(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["vendors~main"],{

/***/ "+/lC":
/*!*****************************************************!*\
  !*** ./node_modules/react-rangeslider/lib/utils.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.capitalize = capitalize;
exports.clamp = clamp;
/**
 * Capitalize first letter of string
 * @private
 * @param  {string} - String
 * @return {string} - String with first letter capitalized
 */
function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.substr(1);
}

/**
 * Clamp position between a range
 * @param  {number} - Value to be clamped
 * @param  {number} - Minimum value in range
 * @param  {number} - Maximum value in range
 * @return {number} - Clamped value
 */
function clamp(value, min, max) {
  return Math.min(Math.max(value, min), max);
}

/***/ }),

/***/ "+/up":
/*!*************************************************!*\
  !*** ./node_modules/base16/lib/atelier-dune.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'atelier dune',
  author: 'bram de haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/dune)',
  base00: '#20201d',
  base01: '#292824',
  base02: '#6e6b5e',
  base03: '#7d7a68',
  base04: '#999580',
  base05: '#a6a28c',
  base06: '#e8e4cf',
  base07: '#fefbec',
  base08: '#d73737',
  base09: '#b65611',
  base0A: '#cfb017',
  base0B: '#60ac39',
  base0C: '#1fad83',
  base0D: '#6684e1',
  base0E: '#b854d4',
  base0F: '#d43552'
};
module.exports = exports['default'];

/***/ }),

/***/ "+0l7":
/*!********************************************!*\
  !*** ./node_modules/xterm/lib/Viewport.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var FALLBACK_SCROLL_BAR_WIDTH = 15;
var Viewport = (function () {
    function Viewport(_terminal, _viewportElement, _scrollArea, _charMeasure) {
        var _this = this;
        this._terminal = _terminal;
        this._viewportElement = _viewportElement;
        this._scrollArea = _scrollArea;
        this._charMeasure = _charMeasure;
        this.scrollBarWidth = 0;
        this._currentRowHeight = 0;
        this._lastRecordedBufferLength = 0;
        this._lastRecordedViewportHeight = 0;
        this._lastRecordedBufferHeight = 0;
        this._wheelPartialScroll = 0;
        this.scrollBarWidth = (this._viewportElement.offsetWidth - this._scrollArea.offsetWidth) || FALLBACK_SCROLL_BAR_WIDTH;
        this._viewportElement.addEventListener('scroll', this._onScroll.bind(this));
        setTimeout(function () { return _this.syncScrollArea(); }, 0);
    }
    Viewport.prototype.onThemeChanged = function (colors) {
        this._viewportElement.style.backgroundColor = colors.background.css;
    };
    Viewport.prototype._refresh = function () {
        if (this._charMeasure.height > 0) {
            this._currentRowHeight = this._terminal.renderer.dimensions.scaledCellHeight / window.devicePixelRatio;
            this._lastRecordedViewportHeight = this._viewportElement.offsetHeight;
            var newBufferHeight = Math.round(this._currentRowHeight * this._lastRecordedBufferLength) + (this._lastRecordedViewportHeight - this._terminal.renderer.dimensions.canvasHeight);
            if (this._lastRecordedBufferHeight !== newBufferHeight) {
                this._lastRecordedBufferHeight = newBufferHeight;
                this._scrollArea.style.height = this._lastRecordedBufferHeight + 'px';
            }
        }
    };
    Viewport.prototype.syncScrollArea = function () {
        if (this._lastRecordedBufferLength !== this._terminal.buffer.lines.length) {
            this._lastRecordedBufferLength = this._terminal.buffer.lines.length;
            this._refresh();
        }
        else if (this._lastRecordedViewportHeight !== this._terminal.renderer.dimensions.canvasHeight) {
            this._refresh();
        }
        else {
            if (this._terminal.renderer.dimensions.scaledCellHeight / window.devicePixelRatio !== this._currentRowHeight) {
                this._refresh();
            }
        }
        var scrollTop = this._terminal.buffer.ydisp * this._currentRowHeight;
        if (this._viewportElement.scrollTop !== scrollTop) {
            this._viewportElement.scrollTop = scrollTop;
        }
    };
    Viewport.prototype._onScroll = function (ev) {
        if (!this._viewportElement.offsetParent) {
            return;
        }
        var newRow = Math.round(this._viewportElement.scrollTop / this._currentRowHeight);
        var diff = newRow - this._terminal.buffer.ydisp;
        this._terminal.scrollLines(diff, true);
    };
    Viewport.prototype.onWheel = function (ev) {
        var amount = this._getPixelsScrolled(ev);
        if (amount === 0) {
            return;
        }
        this._viewportElement.scrollTop += amount;
        ev.preventDefault();
    };
    Viewport.prototype._getPixelsScrolled = function (ev) {
        if (ev.deltaY === 0) {
            return 0;
        }
        var amount = ev.deltaY;
        if (ev.deltaMode === WheelEvent.DOM_DELTA_LINE) {
            amount *= this._currentRowHeight;
        }
        else if (ev.deltaMode === WheelEvent.DOM_DELTA_PAGE) {
            amount *= this._currentRowHeight * this._terminal.rows;
        }
        return amount;
    };
    Viewport.prototype.getLinesScrolled = function (ev) {
        if (ev.deltaY === 0) {
            return 0;
        }
        var amount = ev.deltaY;
        if (ev.deltaMode === WheelEvent.DOM_DELTA_PIXEL) {
            amount /= this._currentRowHeight + 0.0;
            this._wheelPartialScroll += amount;
            amount = Math.floor(Math.abs(this._wheelPartialScroll)) * (this._wheelPartialScroll > 0 ? 1 : -1);
            this._wheelPartialScroll %= 1;
        }
        else if (ev.deltaMode === WheelEvent.DOM_DELTA_PAGE) {
            amount *= this._terminal.rows;
        }
        return amount;
    };
    Viewport.prototype.onTouchStart = function (ev) {
        this._lastTouchY = ev.touches[0].pageY;
    };
    Viewport.prototype.onTouchMove = function (ev) {
        var deltaY = this._lastTouchY - ev.touches[0].pageY;
        this._lastTouchY = ev.touches[0].pageY;
        if (deltaY === 0) {
            return;
        }
        this._viewportElement.scrollTop += deltaY;
        ev.preventDefault();
    };
    return Viewport;
}());
exports.Viewport = Viewport;

//# sourceMappingURL=Viewport.js.map


/***/ }),

/***/ "+1d/":
/*!*****************************************************************************************!*\
  !*** ./node_modules/@jupyterlab/plotly-extension/node_modules/plotly.js/dist/plotly.js ***!
  \*****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global) {var require;var require;/**
* plotly.js v1.45.3
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
* Licensed under the MIT license
*/
(function(f){if(true){module.exports=f()}else { var g; }})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return require(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(_dereq_,module,exports){
'use strict';

var Lib = _dereq_('../src/lib');
var rules = {
    "X,X div": "direction:ltr;font-family:'Open Sans', verdana, arial, sans-serif;margin:0;padding:0;",
    "X input,X button": "font-family:'Open Sans', verdana, arial, sans-serif;",
    "X input:focus,X button:focus": "outline:none;",
    "X a": "text-decoration:none;",
    "X a:hover": "text-decoration:none;",
    "X .crisp": "shape-rendering:crispEdges;",
    "X .user-select-none": "-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;",
    "X svg": "overflow:hidden;",
    "X svg a": "fill:#447adb;",
    "X svg a:hover": "fill:#3c6dc5;",
    "X .main-svg": "position:absolute;top:0;left:0;pointer-events:none;",
    "X .main-svg .draglayer": "pointer-events:all;",
    "X .cursor-default": "cursor:default;",
    "X .cursor-pointer": "cursor:pointer;",
    "X .cursor-crosshair": "cursor:crosshair;",
    "X .cursor-move": "cursor:move;",
    "X .cursor-col-resize": "cursor:col-resize;",
    "X .cursor-row-resize": "cursor:row-resize;",
    "X .cursor-ns-resize": "cursor:ns-resize;",
    "X .cursor-ew-resize": "cursor:ew-resize;",
    "X .cursor-sw-resize": "cursor:sw-resize;",
    "X .cursor-s-resize": "cursor:s-resize;",
    "X .cursor-se-resize": "cursor:se-resize;",
    "X .cursor-w-resize": "cursor:w-resize;",
    "X .cursor-e-resize": "cursor:e-resize;",
    "X .cursor-nw-resize": "cursor:nw-resize;",
    "X .cursor-n-resize": "cursor:n-resize;",
    "X .cursor-ne-resize": "cursor:ne-resize;",
    "X .cursor-grab": "cursor:-webkit-grab;cursor:grab;",
    "X .modebar": "position:absolute;top:2px;right:2px;z-index:1001;",
    "X .ease-bg": "-webkit-transition:background-color 0.3s ease 0s;-moz-transition:background-color 0.3s ease 0s;-ms-transition:background-color 0.3s ease 0s;-o-transition:background-color 0.3s ease 0s;transition:background-color 0.3s ease 0s;",
    "X .modebar--hover>:not(.watermark)": "opacity:0;-webkit-transition:opacity 0.3s ease 0s;-moz-transition:opacity 0.3s ease 0s;-ms-transition:opacity 0.3s ease 0s;-o-transition:opacity 0.3s ease 0s;transition:opacity 0.3s ease 0s;",
    "X:hover .modebar--hover .modebar-group": "opacity:1;",
    "X .modebar-group": "float:left;display:inline-block;box-sizing:border-box;padding-left:8px;position:relative;vertical-align:middle;white-space:nowrap;",
    "X .modebar-btn": "position:relative;font-size:16px;padding:3px 4px;height:22px;cursor:pointer;line-height:normal;box-sizing:border-box;",
    "X .modebar-btn svg": "position:relative;top:2px;",
    "X .modebar.vertical": "display:flex;flex-direction:column;flex-wrap:wrap;align-content:flex-end;max-height:100%;",
    "X .modebar.vertical svg": "top:-1px;",
    "X .modebar.vertical .modebar-group": "display:block;float:none;padding-left:0px;padding-bottom:8px;",
    "X .modebar.vertical .modebar-group .modebar-btn": "display:block;text-align:center;",
    "X [data-title]:before,X [data-title]:after": "position:absolute;-webkit-transform:translate3d(0, 0, 0);-moz-transform:translate3d(0, 0, 0);-ms-transform:translate3d(0, 0, 0);-o-transform:translate3d(0, 0, 0);transform:translate3d(0, 0, 0);display:none;opacity:0;z-index:1001;pointer-events:none;top:110%;right:50%;",
    "X [data-title]:hover:before,X [data-title]:hover:after": "display:block;opacity:1;",
    "X [data-title]:before": "content:'';position:absolute;background:transparent;border:6px solid transparent;z-index:1002;margin-top:-12px;border-bottom-color:#69738a;margin-right:-6px;",
    "X [data-title]:after": "content:attr(data-title);background:#69738a;color:white;padding:8px 10px;font-size:12px;line-height:12px;white-space:nowrap;margin-right:-18px;border-radius:2px;",
    "X .vertical [data-title]:before,X .vertical [data-title]:after": "top:0%;right:200%;",
    "X .vertical [data-title]:before": "border:6px solid transparent;border-left-color:#69738a;margin-top:8px;margin-right:-30px;",
    "X .select-outline": "fill:none;stroke-width:1;shape-rendering:crispEdges;",
    "X .select-outline-1": "stroke:white;",
    "X .select-outline-2": "stroke:black;stroke-dasharray:2px 2px;",
    Y: "font-family:'Open Sans';position:fixed;top:50px;right:20px;z-index:10000;font-size:10pt;max-width:180px;",
    "Y p": "margin:0;",
    "Y .notifier-note": "min-width:180px;max-width:250px;border:1px solid #fff;z-index:3000;margin:0;background-color:#8c97af;background-color:rgba(140,151,175,0.9);color:#fff;padding:10px;overflow-wrap:break-word;word-wrap:break-word;-ms-hyphens:auto;-webkit-hyphens:auto;hyphens:auto;",
    "Y .notifier-close": "color:#fff;opacity:0.8;float:right;padding:0 5px;background:none;border:none;font-size:20px;font-weight:bold;line-height:20px;",
    "Y .notifier-close:hover": "color:#444;text-decoration:none;cursor:pointer;"
};

for(var selector in rules) {
    var fullSelector = selector.replace(/^,/,' ,')
        .replace(/X/g, '.js-plotly-plot .plotly')
        .replace(/Y/g, '.plotly-notifier');
    Lib.addStyleRule(fullSelector, rules[selector]);
}

},{"../src/lib":697}],2:[function(_dereq_,module,exports){
'use strict';

module.exports = {
    'undo': {
        'width': 857.1,
        'height': 1000,
        'path': 'm857 350q0-87-34-166t-91-137-137-92-166-34q-96 0-183 41t-147 114q-4 6-4 13t5 11l76 77q6 5 14 5 9-1 13-7 41-53 100-82t126-29q58 0 110 23t92 61 61 91 22 111-22 111-61 91-92 61-110 23q-55 0-105-20t-90-57l77-77q17-16 8-38-10-23-33-23h-250q-15 0-25 11t-11 25v250q0 24 22 33 22 10 39-8l72-72q60 57 137 88t159 31q87 0 166-34t137-92 91-137 34-166z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'home': {
        'width': 928.6,
        'height': 1000,
        'path': 'm786 296v-267q0-15-11-26t-25-10h-214v214h-143v-214h-214q-15 0-25 10t-11 26v267q0 1 0 2t0 2l321 264 321-264q1-1 1-4z m124 39l-34-41q-5-5-12-6h-2q-7 0-12 3l-386 322-386-322q-7-4-13-4-7 2-12 7l-35 41q-4 5-3 13t6 12l401 334q18 15 42 15t43-15l136-114v109q0 8 5 13t13 5h107q8 0 13-5t5-13v-227l122-102q5-5 6-12t-4-13z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'camera-retro': {
        'width': 1000,
        'height': 1000,
        'path': 'm518 386q0 8-5 13t-13 5q-37 0-63-27t-26-63q0-8 5-13t13-5 12 5 5 13q0 23 16 38t38 16q8 0 13 5t5 13z m125-73q0-59-42-101t-101-42-101 42-42 101 42 101 101 42 101-42 42-101z m-572-320h858v71h-858v-71z m643 320q0 89-62 152t-152 62-151-62-63-152 63-151 151-63 152 63 62 151z m-571 358h214v72h-214v-72z m-72-107h858v143h-462l-36-71h-360v-72z m929 143v-714q0-30-21-51t-50-21h-858q-29 0-50 21t-21 51v714q0 30 21 51t50 21h858q29 0 50-21t21-51z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'zoombox': {
        'width': 1000,
        'height': 1000,
        'path': 'm1000-25l-250 251c40 63 63 138 63 218 0 224-182 406-407 406-224 0-406-182-406-406s183-406 407-406c80 0 155 22 218 62l250-250 125 125z m-812 250l0 438 437 0 0-438-437 0z m62 375l313 0 0-312-313 0 0 312z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'pan': {
        'width': 1000,
        'height': 1000,
        'path': 'm1000 350l-187 188 0-125-250 0 0 250 125 0-188 187-187-187 125 0 0-250-250 0 0 125-188-188 186-187 0 125 252 0 0-250-125 0 187-188 188 188-125 0 0 250 250 0 0-126 187 188z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'zoom_plus': {
        'width': 875,
        'height': 1000,
        'path': 'm1 787l0-875 875 0 0 875-875 0z m687-500l-187 0 0-187-125 0 0 187-188 0 0 125 188 0 0 187 125 0 0-187 187 0 0-125z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'zoom_minus': {
        'width': 875,
        'height': 1000,
        'path': 'm0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'autoscale': {
        'width': 1000,
        'height': 1000,
        'path': 'm250 850l-187 0-63 0 0-62 0-188 63 0 0 188 187 0 0 62z m688 0l-188 0 0-62 188 0 0-188 62 0 0 188 0 62-62 0z m-875-938l0 188-63 0 0-188 0-62 63 0 187 0 0 62-187 0z m875 188l0-188-188 0 0-62 188 0 62 0 0 62 0 188-62 0z m-125 188l-1 0-93-94-156 156 156 156 92-93 2 0 0 250-250 0 0-2 93-92-156-156-156 156 94 92 0 2-250 0 0-250 0 0 93 93 157-156-157-156-93 94 0 0 0-250 250 0 0 0-94 93 156 157 156-157-93-93 0 0 250 0 0 250z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'tooltip_basic': {
        'width': 1500,
        'height': 1000,
        'path': 'm375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'tooltip_compare': {
        'width': 1125,
        'height': 1000,
        'path': 'm187 786l0 2-187-188 188-187 0 0 937 0 0 373-938 0z m0-499l0 1-187-188 188-188 0 0 937 0 0 376-938-1z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'plotlylogo': {
        'width': 1542,
        'height': 1000,
        'path': 'm0-10h182v-140h-182v140z m228 146h183v-286h-183v286z m225 714h182v-1000h-182v1000z m225-285h182v-715h-182v715z m225 142h183v-857h-183v857z m231-428h182v-429h-182v429z m225-291h183v-138h-183v138z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'z-axis': {
        'width': 1000,
        'height': 1000,
        'path': 'm833 5l-17 108v41l-130-65 130-66c0 0 0 38 0 39 0-1 36-14 39-25 4-15-6-22-16-30-15-12-39-16-56-20-90-22-187-23-279-23-261 0-341 34-353 59 3 60 228 110 228 110-140-8-351-35-351-116 0-120 293-142 474-142 155 0 477 22 477 142 0 50-74 79-163 96z m-374 94c-58-5-99-21-99-40 0-24 65-43 144-43 79 0 143 19 143 43 0 19-42 34-98 40v216h87l-132 135-133-135h88v-216z m167 515h-136v1c16 16 31 34 46 52l84 109v54h-230v-71h124v-1c-16-17-28-32-44-51l-89-114v-51h245v72z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    '3d_rotate': {
        'width': 1000,
        'height': 1000,
        'path': 'm922 660c-5 4-9 7-14 11-359 263-580-31-580-31l-102 28 58-400c0 1 1 1 2 2 118 108 351 249 351 249s-62 27-100 42c88 83 222 183 347 122 16-8 30-17 44-27-2 1-4 2-6 4z m36-329c0 0 64 229-88 296-62 27-124 14-175-11 157-78 225-208 249-266 8-19 11-31 11-31 2 5 6 15 11 32-5-13-8-20-8-20z m-775-239c70-31 117-50 198-32-121 80-199 346-199 346l-96-15-58-12c0 0 55-226 155-287z m603 133l-317-139c0 0 4-4 19-14 7-5 24-15 24-15s-177-147-389 4c235-287 536-112 536-112l31-22 100 299-4-1z m-298-153c6-4 14-9 24-15 0 0-17 10-24 15z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'camera': {
        'width': 1000,
        'height': 1000,
        'path': 'm500 450c-83 0-150-67-150-150 0-83 67-150 150-150 83 0 150 67 150 150 0 83-67 150-150 150z m400 150h-120c-16 0-34 13-39 29l-31 93c-6 15-23 28-40 28h-340c-16 0-34-13-39-28l-31-94c-6-15-23-28-40-28h-120c-55 0-100-45-100-100v-450c0-55 45-100 100-100h800c55 0 100 45 100 100v450c0 55-45 100-100 100z m-400-550c-138 0-250 112-250 250 0 138 112 250 250 250 138 0 250-112 250-250 0-138-112-250-250-250z m365 380c-19 0-35 16-35 35 0 19 16 35 35 35 19 0 35-16 35-35 0-19-16-35-35-35z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'movie': {
        'width': 1000,
        'height': 1000,
        'path': 'm938 413l-188-125c0 37-17 71-44 94 64 38 107 107 107 187 0 121-98 219-219 219-121 0-219-98-219-219 0-61 25-117 66-156h-115c30 33 49 76 49 125 0 103-84 187-187 187s-188-84-188-187c0-57 26-107 65-141-38-22-65-62-65-109v-250c0-70 56-126 125-126h500c69 0 125 56 125 126l188-126c34 0 62 28 62 63v375c0 35-28 63-62 63z m-750 0c-69 0-125 56-125 125s56 125 125 125 125-56 125-125-56-125-125-125z m406-1c-87 0-157 70-157 157 0 86 70 156 157 156s156-70 156-156-70-157-156-157z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'question': {
        'width': 857.1,
        'height': 1000,
        'path': 'm500 82v107q0 8-5 13t-13 5h-107q-8 0-13-5t-5-13v-107q0-8 5-13t13-5h107q8 0 13 5t5 13z m143 375q0 49-31 91t-77 65-95 23q-136 0-207-119-9-14 4-24l74-55q4-4 10-4 9 0 14 7 30 38 48 51 19 14 48 14 27 0 48-15t21-33q0-21-11-34t-38-25q-35-16-65-48t-29-70v-20q0-8 5-13t13-5h107q8 0 13 5t5 13q0 10 12 27t30 28q18 10 28 16t25 19 25 27 16 34 7 45z m214-107q0-117-57-215t-156-156-215-58-216 58-155 156-58 215 58 215 155 156 216 58 215-58 156-156 57-215z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'disk': {
        'width': 857.1,
        'height': 1000,
        'path': 'm214-7h429v214h-429v-214z m500 0h72v500q0 8-6 21t-11 20l-157 156q-5 6-19 12t-22 5v-232q0-22-15-38t-38-16h-322q-22 0-37 16t-16 38v232h-72v-714h72v232q0 22 16 38t37 16h465q22 0 38-16t15-38v-232z m-214 518v178q0 8-5 13t-13 5h-107q-7 0-13-5t-5-13v-178q0-8 5-13t13-5h107q7 0 13 5t5 13z m357-18v-518q0-22-15-38t-38-16h-750q-23 0-38 16t-16 38v750q0 22 16 38t38 16h517q23 0 50-12t42-26l156-157q16-15 27-42t11-49z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'lasso': {
        'width': 1031,
        'height': 1000,
        'path': 'm1018 538c-36 207-290 336-568 286-277-48-473-256-436-463 10-57 36-108 76-151-13-66 11-137 68-183 34-28 75-41 114-42l-55-70 0 0c-2-1-3-2-4-3-10-14-8-34 5-45 14-11 34-8 45 4 1 1 2 3 2 5l0 0 113 140c16 11 31 24 45 40 4 3 6 7 8 11 48-3 100 0 151 9 278 48 473 255 436 462z m-624-379c-80 14-149 48-197 96 42 42 109 47 156 9 33-26 47-66 41-105z m-187-74c-19 16-33 37-39 60 50-32 109-55 174-68-42-25-95-24-135 8z m360 75c-34-7-69-9-102-8 8 62-16 128-68 170-73 59-175 54-244-5-9 20-16 40-20 61-28 159 121 317 333 354s407-60 434-217c28-159-121-318-333-355z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'selectbox': {
        'width': 1000,
        'height': 1000,
        'path': 'm0 850l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-285l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'spikeline': {
        'width': 1000,
        'height': 1000,
        'path': 'M512 409c0-57-46-104-103-104-57 0-104 47-104 104 0 57 47 103 104 103 57 0 103-46 103-103z m-327-39l92 0 0 92-92 0z m-185 0l92 0 0 92-92 0z m370-186l92 0 0 93-92 0z m0-184l92 0 0 92-92 0z',
        'transform': 'matrix(1.5 0 0 -1.5 0 850)'
    },
    'newplotlylogo': {
        'name': 'newplotlylogo',
        'svg': '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 132 132\'><defs><style>.cls-1 {fill: #119dff;} .cls-2 {fill: #25fefd;} .cls-3 {fill: #fff;}</style></defs><title>plotly-logomark</title><g id=\'symbol\'><rect class=\'cls-1\' width=\'132\' height=\'132\' rx=\'6\' ry=\'6\'/><circle class=\'cls-2\' cx=\'78\' cy=\'54\' r=\'6\'/><circle class=\'cls-2\' cx=\'102\' cy=\'30\' r=\'6\'/><circle class=\'cls-2\' cx=\'78\' cy=\'30\' r=\'6\'/><circle class=\'cls-2\' cx=\'54\' cy=\'30\' r=\'6\'/><circle class=\'cls-2\' cx=\'30\' cy=\'30\' r=\'6\'/><circle class=\'cls-2\' cx=\'30\' cy=\'54\' r=\'6\'/><path class=\'cls-3\' d=\'M30,72a6,6,0,0,0-6,6v24a6,6,0,0,0,12,0V78A6,6,0,0,0,30,72Z\'/><path class=\'cls-3\' d=\'M78,72a6,6,0,0,0-6,6v24a6,6,0,0,0,12,0V78A6,6,0,0,0,78,72Z\'/><path class=\'cls-3\' d=\'M54,48a6,6,0,0,0-6,6v48a6,6,0,0,0,12,0V54A6,6,0,0,0,54,48Z\'/><path class=\'cls-3\' d=\'M102,48a6,6,0,0,0-6,6v48a6,6,0,0,0,12,0V54A6,6,0,0,0,102,48Z\'/></g></svg>'
    }
};

},{}],3:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/transforms/aggregate');

},{"../src/transforms/aggregate":1160}],4:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/bar');

},{"../src/traces/bar":843}],5:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/barpolar');

},{"../src/traces/barpolar":855}],6:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/box');

},{"../src/traces/box":865}],7:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/components/calendars');

},{"../src/components/calendars":572}],8:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/candlestick');

},{"../src/traces/candlestick":874}],9:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/carpet');

},{"../src/traces/carpet":893}],10:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/choropleth');

},{"../src/traces/choropleth":907}],11:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/cone');

},{"../src/traces/cone":915}],12:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/contour');

},{"../src/traces/contour":930}],13:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/contourcarpet');

},{"../src/traces/contourcarpet":941}],14:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/core');

},{"../src/core":676}],15:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/transforms/filter');

},{"../src/transforms/filter":1161}],16:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/transforms/groupby');

},{"../src/transforms/groupby":1162}],17:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/heatmap');

},{"../src/traces/heatmap":953}],18:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/heatmapgl');

},{"../src/traces/heatmapgl":962}],19:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/histogram');

},{"../src/traces/histogram":974}],20:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/histogram2d');

},{"../src/traces/histogram2d":981}],21:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/histogram2dcontour');

},{"../src/traces/histogram2dcontour":985}],22:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Plotly = _dereq_('./core');

// traces
Plotly.register([
    _dereq_('./bar'),
    _dereq_('./box'),
    _dereq_('./heatmap'),
    _dereq_('./histogram'),
    _dereq_('./histogram2d'),
    _dereq_('./histogram2dcontour'),
    _dereq_('./pie'),
    _dereq_('./contour'),
    _dereq_('./scatterternary'),
    _dereq_('./violin'),

    _dereq_('./scatter3d'),
    _dereq_('./surface'),
    _dereq_('./isosurface'),
    _dereq_('./mesh3d'),
    _dereq_('./cone'),
    _dereq_('./streamtube'),

    _dereq_('./scattergeo'),
    _dereq_('./choropleth'),

    _dereq_('./scattergl'),
    _dereq_('./splom'),

    _dereq_('./pointcloud'),
    _dereq_('./heatmapgl'),
    _dereq_('./parcoords'),
    _dereq_('./parcats'),
    _dereq_('./scattermapbox'),

    _dereq_('./sankey'),

    _dereq_('./table'),

    _dereq_('./carpet'),
    _dereq_('./scattercarpet'),
    _dereq_('./contourcarpet'),

    _dereq_('./ohlc'),
    _dereq_('./candlestick'),

    _dereq_('./scatterpolar'),
    _dereq_('./scatterpolargl'),
    _dereq_('./barpolar')
]);

// transforms
//
// Please note that all *transform* methods are executed before
// all *calcTransform* methods - which could possibly lead to
// unexpected results when applying multiple transforms of different types
// to a given trace.
//
// For more info, see:
// https://github.com/plotly/plotly.js/pull/978#pullrequestreview-2403353
//
Plotly.register([
    _dereq_('./aggregate'),
    _dereq_('./filter'),
    _dereq_('./groupby'),
    _dereq_('./sort')
]);

// components
Plotly.register([
    _dereq_('./calendars')
]);

module.exports = Plotly;

},{"./aggregate":3,"./bar":4,"./barpolar":5,"./box":6,"./calendars":7,"./candlestick":8,"./carpet":9,"./choropleth":10,"./cone":11,"./contour":12,"./contourcarpet":13,"./core":14,"./filter":15,"./groupby":16,"./heatmap":17,"./heatmapgl":18,"./histogram":19,"./histogram2d":20,"./histogram2dcontour":21,"./isosurface":23,"./mesh3d":24,"./ohlc":25,"./parcats":26,"./parcoords":27,"./pie":28,"./pointcloud":29,"./sankey":30,"./scatter3d":31,"./scattercarpet":32,"./scattergeo":33,"./scattergl":34,"./scattermapbox":35,"./scatterpolar":36,"./scatterpolargl":37,"./scatterternary":38,"./sort":39,"./splom":40,"./streamtube":41,"./surface":42,"./table":43,"./violin":44}],23:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/isosurface');

},{"../src/traces/isosurface":990}],24:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/mesh3d');

},{"../src/traces/mesh3d":995}],25:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/ohlc');

},{"../src/traces/ohlc":1000}],26:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/parcats');

},{"../src/traces/parcats":1009}],27:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/parcoords');

},{"../src/traces/parcoords":1018}],28:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/pie');

},{"../src/traces/pie":1029}],29:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/pointcloud');

},{"../src/traces/pointcloud":1038}],30:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/sankey');

},{"../src/traces/sankey":1044}],31:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/scatter3d');

},{"../src/traces/scatter3d":1080}],32:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/scattercarpet');

},{"../src/traces/scattercarpet":1086}],33:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/scattergeo');

},{"../src/traces/scattergeo":1093}],34:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/scattergl');

},{"../src/traces/scattergl":1101}],35:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/scattermapbox');

},{"../src/traces/scattermapbox":1107}],36:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/scatterpolar');

},{"../src/traces/scatterpolar":1114}],37:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/scatterpolargl');

},{"../src/traces/scatterpolargl":1118}],38:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/scatterternary');

},{"../src/traces/scatterternary":1124}],39:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/transforms/sort');

},{"../src/transforms/sort":1164}],40:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/splom');

},{"../src/traces/splom":1129}],41:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/streamtube');

},{"../src/traces/streamtube":1134}],42:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/surface');

},{"../src/traces/surface":1139}],43:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/table');

},{"../src/traces/table":1147}],44:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/violin');

},{"../src/traces/violin":1155}],45:[function(_dereq_,module,exports){
'use strict'

module.exports = createViewController

var createTurntable = _dereq_('turntable-camera-controller')
var createOrbit     = _dereq_('orbit-camera-controller')
var createMatrix    = _dereq_('matrix-camera-controller')

function ViewController(controllers, mode) {
  this._controllerNames = Object.keys(controllers)
  this._controllerList = this._controllerNames.map(function(n) {
    return controllers[n]
  })
  this._mode   = mode
  this._active = controllers[mode]
  if(!this._active) {
    this._mode   = 'turntable'
    this._active = controllers.turntable
  }
  this.modes = this._controllerNames
  this.computedMatrix = this._active.computedMatrix
  this.computedEye    = this._active.computedEye
  this.computedUp     = this._active.computedUp
  this.computedCenter = this._active.computedCenter
  this.computedRadius = this._active.computedRadius
}

var proto = ViewController.prototype

var COMMON_METHODS = [
  ['flush', 1],
  ['idle', 1],
  ['lookAt', 4],
  ['rotate', 4],
  ['pan', 4],
  ['translate', 4],
  ['setMatrix', 2],
  ['setDistanceLimits', 2],
  ['setDistance', 2]
]

COMMON_METHODS.forEach(function(method) {
  var name = method[0]
  var argNames = []
  for(var i=0; i<method[1]; ++i) {
    argNames.push('a'+i)
  }
  var code = 'var cc=this._controllerList;for(var i=0;i<cc.length;++i){cc[i].'+method[0]+'('+argNames.join()+')}'
  proto[name] = Function.apply(null, argNames.concat(code))
})

proto.recalcMatrix = function(t) {
  this._active.recalcMatrix(t)
}

proto.getDistance = function(t) {
  return this._active.getDistance(t)
}
proto.getDistanceLimits = function(out) {
  return this._active.getDistanceLimits(out)
}

proto.lastT = function() {
  return this._active.lastT()
}

proto.setMode = function(mode) {
  if(mode === this._mode) {
    return
  }
  var idx = this._controllerNames.indexOf(mode)
  if(idx < 0) {
    return
  }
  var prev  = this._active
  var next  = this._controllerList[idx]
  var lastT = Math.max(prev.lastT(), next.lastT())

  prev.recalcMatrix(lastT)
  next.setMatrix(lastT, prev.computedMatrix)
  
  this._active = next
  this._mode   = mode

  //Update matrix properties
  this.computedMatrix = this._active.computedMatrix
  this.computedEye    = this._active.computedEye
  this.computedUp     = this._active.computedUp
  this.computedCenter = this._active.computedCenter
  this.computedRadius = this._active.computedRadius
}

proto.getMode = function() {
  return this._mode
}

function createViewController(options) {
  options = options || {}

  var eye       = options.eye    || [0,0,1]
  var center    = options.center || [0,0,0]
  var up        = options.up     || [0,1,0]
  var limits    = options.distanceLimits || [0, Infinity]
  var mode      = options.mode   || 'turntable'

  var turntable = createTurntable()
  var orbit     = createOrbit()
  var matrix    = createMatrix()

  turntable.setDistanceLimits(limits[0], limits[1])
  turntable.lookAt(0, eye, center, up)
  orbit.setDistanceLimits(limits[0], limits[1])
  orbit.lookAt(0, eye, center, up)
  matrix.setDistanceLimits(limits[0], limits[1])
  matrix.lookAt(0, eye, center, up)

  return new ViewController({
    turntable: turntable,
    orbit: orbit,
    matrix: matrix
  }, mode)
}
},{"matrix-camera-controller":422,"orbit-camera-controller":445,"turntable-camera-controller":523}],46:[function(_dereq_,module,exports){
// https://github.com/d3/d3-sankey Version 0.7.2. Copyright 2019 Mike Bostock.
(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, _dereq_('d3-array'), _dereq_('d3-collection'), _dereq_('d3-shape')) :
	typeof define === 'function' && define.amd ? define(['exports', 'd3-array', 'd3-collection', 'd3-shape'], factory) :
	(factory((global.d3 = global.d3 || {}),global.d3,global.d3,global.d3));
}(this, (function (exports,d3Array,d3Collection,d3Shape) { 'use strict';

function targetDepth(d) {
  return d.target.depth;
}

function left(node) {
  return node.depth;
}

function right(node, n) {
  return n - 1 - node.height;
}

function justify(node, n) {
  return node.sourceLinks.length ? node.depth : n - 1;
}

function center(node) {
  return node.targetLinks.length ? node.depth
      : node.sourceLinks.length ? d3Array.min(node.sourceLinks, targetDepth) - 1
      : 0;
}

function constant(x) {
  return function() {
    return x;
  };
}

function ascendingSourceBreadth(a, b) {
  return ascendingBreadth(a.source, b.source) || a.index - b.index;
}

function ascendingTargetBreadth(a, b) {
  return ascendingBreadth(a.target, b.target) || a.index - b.index;
}

function ascendingBreadth(a, b) {
  return a.y0 - b.y0;
}

function value(d) {
  return d.value;
}

function nodeCenter(node) {
  return (node.y0 + node.y1) / 2;
}

function weightedSource(link) {
  return nodeCenter(link.source) * link.value;
}

function weightedTarget(link) {
  return nodeCenter(link.target) * link.value;
}

function defaultId(d) {
  return d.index;
}

function defaultNodes(graph) {
  return graph.nodes;
}

function defaultLinks(graph) {
  return graph.links;
}

function find(nodeById, id) {
  var node = nodeById.get(id);
  if (!node) throw new Error("missing: " + id);
  return node;
}

var sankey = function() {
  var x0 = 0, y0 = 0, x1 = 1, y1 = 1, // extent
      dx = 24, // nodeWidth
      py = 8, // nodePadding
      id = defaultId,
      align = justify,
      nodes = defaultNodes,
      links = defaultLinks,
      iterations = 32,
      maxPaddedSpace = 2 / 3; // Defined as a fraction of the total available space

  function sankey() {
    var graph = {nodes: nodes.apply(null, arguments), links: links.apply(null, arguments)};
    computeNodeLinks(graph);
    computeNodeValues(graph);
    computeNodeDepths(graph);
    computeNodeBreadths(graph, iterations);
    computeLinkBreadths(graph);
    return graph;
  }

  sankey.update = function(graph) {
    computeLinkBreadths(graph);
    return graph;
  };

  sankey.nodeId = function(_) {
    return arguments.length ? (id = typeof _ === "function" ? _ : constant(_), sankey) : id;
  };

  sankey.nodeAlign = function(_) {
    return arguments.length ? (align = typeof _ === "function" ? _ : constant(_), sankey) : align;
  };

  sankey.nodeWidth = function(_) {
    return arguments.length ? (dx = +_, sankey) : dx;
  };

  sankey.nodePadding = function(_) {
    return arguments.length ? (py = +_, sankey) : py;
  };

  sankey.nodes = function(_) {
    return arguments.length ? (nodes = typeof _ === "function" ? _ : constant(_), sankey) : nodes;
  };

  sankey.links = function(_) {
    return arguments.length ? (links = typeof _ === "function" ? _ : constant(_), sankey) : links;
  };

  sankey.size = function(_) {
    return arguments.length ? (x0 = y0 = 0, x1 = +_[0], y1 = +_[1], sankey) : [x1 - x0, y1 - y0];
  };

  sankey.extent = function(_) {
    return arguments.length ? (x0 = +_[0][0], x1 = +_[1][0], y0 = +_[0][1], y1 = +_[1][1], sankey) : [[x0, y0], [x1, y1]];
  };

  sankey.iterations = function(_) {
    return arguments.length ? (iterations = +_, sankey) : iterations;
  };

  // Populate the sourceLinks and targetLinks for each node.
  // Also, if the source and target are not objects, assume they are indices.
  function computeNodeLinks(graph) {
    graph.nodes.forEach(function(node, i) {
      node.index = i;
      node.sourceLinks = [];
      node.targetLinks = [];
    });

    var nodeById = d3Collection.map(graph.nodes, id);
    graph.links.forEach(function(link, i) {
      link.index = i;
      var source = link.source, target = link.target;
      if (typeof source !== "object") source = link.source = find(nodeById, source);
      if (typeof target !== "object") target = link.target = find(nodeById, target);
      source.sourceLinks.push(link);
      target.targetLinks.push(link);
    });
  }

  // Compute the value (size) of each node by summing the associated links.
  function computeNodeValues(graph) {
    graph.nodes.forEach(function(node) {
      node.value = Math.max(
        d3Array.sum(node.sourceLinks, value),
        d3Array.sum(node.targetLinks, value)
      );
    });
  }

  // Iteratively assign the depth (x-position) for each node.
  // Nodes are assigned the maximum depth of incoming neighbors plus one;
  // nodes with no incoming links are assigned depth zero, while
  // nodes with no outgoing links are assigned the maximum depth.
  function computeNodeDepths(graph) {
    var nodes, next, x;

    for (nodes = graph.nodes, next = [], x = 0; nodes.length; ++x, nodes = next, next = []) {
      nodes.forEach(function(node) {
        node.depth = x;
        node.sourceLinks.forEach(function(link) {
          if (next.indexOf(link.target) < 0) {
            next.push(link.target);
          }
        });
      });
    }

    for (nodes = graph.nodes, next = [], x = 0; nodes.length; ++x, nodes = next, next = []) {
      nodes.forEach(function(node) {
        node.height = x;
        node.targetLinks.forEach(function(link) {
          if (next.indexOf(link.source) < 0) {
            next.push(link.source);
          }
        });
      });
    }

    var kx = (x1 - x0 - dx) / (x - 1);
    graph.nodes.forEach(function(node) {
      node.x1 = (node.x0 = x0 + Math.max(0, Math.min(x - 1, Math.floor(align.call(null, node, x)))) * kx) + dx;
    });
  }

  function computeNodeBreadths(graph) {
    var columns = d3Collection.nest()
        .key(function(d) { return d.x0; })
        .sortKeys(d3Array.ascending)
        .entries(graph.nodes)
        .map(function(d) { return d.values; });

    //
    initializeNodeBreadth();
    resolveCollisions();
    for (var alpha = 1, n = iterations; n > 0; --n) {
      relaxRightToLeft(alpha *= 0.99);
      resolveCollisions();
      relaxLeftToRight(alpha);
      resolveCollisions();
    }

    function initializeNodeBreadth() {
      var L = d3Array.max(columns, function(nodes) {
        return nodes.length;
      });
      var maxNodePadding = maxPaddedSpace * (y1 - y0) / (L - 1);
      if(py > maxNodePadding) py = maxNodePadding;
      var ky = d3Array.min(columns, function(nodes) {
        return (y1 - y0 - (nodes.length - 1) * py) / d3Array.sum(nodes, value);
      });

      columns.forEach(function(nodes) {
        nodes.forEach(function(node, i) {
          node.y1 = (node.y0 = i) + node.value * ky;
        });
      });

      graph.links.forEach(function(link) {
        link.width = link.value * ky;
      });
    }

    function relaxLeftToRight(alpha) {
      columns.forEach(function(nodes) {
        nodes.forEach(function(node) {
          if (node.targetLinks.length) {
            var dy = (d3Array.sum(node.targetLinks, weightedSource) / d3Array.sum(node.targetLinks, value) - nodeCenter(node)) * alpha;
            node.y0 += dy, node.y1 += dy;
          }
        });
      });
    }

    function relaxRightToLeft(alpha) {
      columns.slice().reverse().forEach(function(nodes) {
        nodes.forEach(function(node) {
          if (node.sourceLinks.length) {
            var dy = (d3Array.sum(node.sourceLinks, weightedTarget) / d3Array.sum(node.sourceLinks, value) - nodeCenter(node)) * alpha;
            node.y0 += dy, node.y1 += dy;
          }
        });
      });
    }

    function resolveCollisions() {
      columns.forEach(function(nodes) {
        var node,
            dy,
            y = y0,
            n = nodes.length,
            i;

        // Push any overlapping nodes down.
        nodes.sort(ascendingBreadth);
        for (i = 0; i < n; ++i) {
          node = nodes[i];
          dy = y - node.y0;
          if (dy > 0) node.y0 += dy, node.y1 += dy;
          y = node.y1 + py;
        }

        // If the bottommost node goes outside the bounds, push it back up.
        dy = y - py - y1;
        if (dy > 0) {
          y = (node.y0 -= dy), node.y1 -= dy;

          // Push any overlapping nodes back up.
          for (i = n - 2; i >= 0; --i) {
            node = nodes[i];
            dy = node.y1 + py - y;
            if (dy > 0) node.y0 -= dy, node.y1 -= dy;
            y = node.y0;
          }
        }
      });
    }
  }

  function computeLinkBreadths(graph) {
    graph.nodes.forEach(function(node) {
      node.sourceLinks.sort(ascendingTargetBreadth);
      node.targetLinks.sort(ascendingSourceBreadth);
    });
    graph.nodes.forEach(function(node) {
      var y0 = node.y0, y1 = y0;
      node.sourceLinks.forEach(function(link) {
        link.y0 = y0 + link.width / 2, y0 += link.width;
      });
      node.targetLinks.forEach(function(link) {
        link.y1 = y1 + link.width / 2, y1 += link.width;
      });
    });
  }

  return sankey;
};

function horizontalSource(d) {
  return [d.source.x1, d.y0];
}

function horizontalTarget(d) {
  return [d.target.x0, d.y1];
}

var sankeyLinkHorizontal = function() {
  return d3Shape.linkHorizontal()
      .source(horizontalSource)
      .target(horizontalTarget);
};

exports.sankey = sankey;
exports.sankeyCenter = center;
exports.sankeyLeft = left;
exports.sankeyRight = right;
exports.sankeyJustify = justify;
exports.sankeyLinkHorizontal = sankeyLinkHorizontal;

Object.defineProperty(exports, '__esModule', { value: true });

})));

},{"d3-array":140,"d3-collection":141,"d3-shape":149}],47:[function(_dereq_,module,exports){
'use strict'

var weakMap      = typeof WeakMap === 'undefined' ? _dereq_('weak-map') : WeakMap
var createBuffer = _dereq_('gl-buffer')
var createVAO    = _dereq_('gl-vao')

var TriangleCache = new weakMap()

function createABigTriangle(gl) {

  var triangleVAO = TriangleCache.get(gl)
  var handle = triangleVAO && (triangleVAO._triangleBuffer.handle || triangleVAO._triangleBuffer.buffer)
  if(!handle || !gl.isBuffer(handle)) {
    var buf = createBuffer(gl, new Float32Array([-1, -1, -1, 4, 4, -1]))
    triangleVAO = createVAO(gl, [
      { buffer: buf,
        type: gl.FLOAT,
        size: 2
      }
    ])
    triangleVAO._triangleBuffer = buf
    TriangleCache.set(gl, triangleVAO)
  }
  triangleVAO.bind()
  gl.drawArrays(gl.TRIANGLES, 0, 3)
  triangleVAO.unbind()
}

module.exports = createABigTriangle

},{"gl-buffer":234,"gl-vao":316,"weak-map":533}],48:[function(_dereq_,module,exports){

module.exports = absolutize

/**
 * redefine `path` with absolute coordinates
 *
 * @param {Array} path
 * @return {Array}
 */

function absolutize(path){
	var startX = 0
	var startY = 0
	var x = 0
	var y = 0

	return path.map(function(seg){
		seg = seg.slice()
		var type = seg[0]
		var command = type.toUpperCase()

		// is relative
		if (type != command) {
			seg[0] = command
			switch (type) {
				case 'a':
					seg[6] += x
					seg[7] += y
					break
				case 'v':
					seg[1] += y
					break
				case 'h':
					seg[1] += x
					break
				default:
					for (var i = 1; i < seg.length;) {
						seg[i++] += x
						seg[i++] += y
					}
			}
		}

		// update cursor state
		switch (command) {
			case 'Z':
				x = startX
				y = startY
				break
			case 'H':
				x = seg[1]
				break
			case 'V':
				y = seg[1]
				break
			case 'M':
				x = startX = seg[1]
				y = startY = seg[2]
				break
			default:
				x = seg[seg.length - 2]
				y = seg[seg.length - 1]
		}

		return seg
	})
}

},{}],49:[function(_dereq_,module,exports){
var padLeft = _dereq_('pad-left')

module.exports = addLineNumbers
function addLineNumbers (string, start, delim) {
  start = typeof start === 'number' ? start : 1
  delim = delim || ': '

  var lines = string.split(/\r?\n/)
  var totalDigits = String(lines.length + start - 1).length
  return lines.map(function (line, i) {
    var c = i + start
    var digits = String(c).length
    var prefix = padLeft(c, totalDigits - digits)
    return prefix + delim + line
  }).join('\n')
}

},{"pad-left":446}],50:[function(_dereq_,module,exports){
'use strict'

module.exports = affineHull

var orient = _dereq_('robust-orientation')

function linearlyIndependent(points, d) {
  var nhull = new Array(d+1)
  for(var i=0; i<points.length; ++i) {
    nhull[i] = points[i]
  }
  for(var i=0; i<=points.length; ++i) {
    for(var j=points.length; j<=d; ++j) {
      var x = new Array(d)
      for(var k=0; k<d; ++k) {
        x[k] = Math.pow(j+1-i, k)
      }
      nhull[j] = x
    }
    var o = orient.apply(void 0, nhull)
    if(o) {
      return true
    }
  }
  return false
}

function affineHull(points) {
  var n = points.length
  if(n === 0) {
    return []
  }
  if(n === 1) {
    return [0]
  }
  var d = points[0].length
  var frame = [ points[0] ]
  var index = [ 0 ]
  for(var i=1; i<n; ++i) {
    frame.push(points[i])
    if(!linearlyIndependent(frame, d)) {
      frame.pop()
      continue
    }
    index.push(i)
    if(index.length === d+1) {
      return index
    }
  }
  return index
}
},{"robust-orientation":491}],51:[function(_dereq_,module,exports){
'use strict'

module.exports = alphaComplex

var delaunay = _dereq_('delaunay-triangulate')
var circumradius = _dereq_('circumradius')

function alphaComplex(alpha, points) {
  return delaunay(points).filter(function(cell) {
    var simplex = new Array(cell.length)
    for(var i=0; i<cell.length; ++i) {
      simplex[i] = points[cell[i]]
    }
    return circumradius(simplex) * alpha < 1
  })
}
},{"circumradius":102,"delaunay-triangulate":153}],52:[function(_dereq_,module,exports){
module.exports = alphaShape

var ac = _dereq_('alpha-complex')
var bnd = _dereq_('simplicial-complex-boundary')

function alphaShape(alpha, points) {
  return bnd(ac(alpha, points))
}
},{"alpha-complex":51,"simplicial-complex-boundary":498}],53:[function(_dereq_,module,exports){
'use strict'

module.exports = normalize;

function normalize (arr, dim) {
	if (!arr || arr.length == null) throw Error('Argument should be an array')

	if (dim == null) dim = 1
	else dim = Math.floor(dim)

	var bounds = Array(dim * 2)

	for (var offset = 0; offset < dim; offset++) {
		var max = -Infinity, min = Infinity, i = offset, l = arr.length;

		for (; i < l; i+=dim) {
			if (arr[i] > max) max = arr[i];
			if (arr[i] < min) min = arr[i];
		}

		bounds[offset] = min
		bounds[dim + offset] = max
	}

	return bounds;
}

},{}],54:[function(_dereq_,module,exports){
'use strict'

var getBounds = _dereq_('array-bounds')

module.exports = normalize;

function normalize (arr, dim, bounds) {
	if (!arr || arr.length == null) throw Error('Argument should be an array')

	if (dim == null) dim = 1
	if (bounds == null) bounds = getBounds(arr, dim)

	for (var offset = 0; offset < dim; offset++) {
		var max = bounds[dim + offset], min = bounds[offset], i = offset, l = arr.length;

		if (max === Infinity && min === -Infinity) {
			for (i = offset; i < l; i+=dim) {
				arr[i] = arr[i] === max ? 1 : arr[i] === min ? 0 : .5
			}
		}
		else if (max === Infinity) {
			for (i = offset; i < l; i+=dim) {
				arr[i] = arr[i] === max ? 1 : 0
			}
		}
		else if (min === -Infinity) {
			for (i = offset; i < l; i+=dim) {
				arr[i] = arr[i] === min ? 0 : 1
			}
		}
		else {
			var range = max - min
			for (i = offset; i < l; i+=dim) {
				arr[i] = range === 0 ? .5 : (arr[i] - min) / range
			}
		}
	}

	return arr;
}

},{"array-bounds":53}],55:[function(_dereq_,module,exports){

module.exports = function newArray(start, end) {
    var n0 = typeof start === 'number',
        n1 = typeof end === 'number'

    if (n0 && !n1) {
        end = start
        start = 0
    } else if (!n0 && !n1) {
        start = 0
        end = 0
    }

    start = start|0
    end = end|0
    var len = end-start
    if (len<0)
        throw new Error('array length must be positive')
    
    var a = new Array(len)
    for (var i=0, c=start; i<len; i++, c++)
        a[i] = c
    return a
}
},{}],56:[function(_dereq_,module,exports){
(function (global){
'use strict';

// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
// original notice:

/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
 * @license  MIT
 */
function compare(a, b) {
  if (a === b) {
    return 0;
  }

  var x = a.length;
  var y = b.length;

  for (var i = 0, len = Math.min(x, y); i < len; ++i) {
    if (a[i] !== b[i]) {
      x = a[i];
      y = b[i];
      break;
    }
  }

  if (x < y) {
    return -1;
  }
  if (y < x) {
    return 1;
  }
  return 0;
}
function isBuffer(b) {
  if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
    return global.Buffer.isBuffer(b);
  }
  return !!(b != null && b._isBuffer);
}

// based on node assert, original notice:

// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
//
// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
//
// Originally from narwhal.js (http://narwhaljs.org)
// Copyright (c) 2009 Thomas Robinson <280north.com>
//
// 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 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.

var util = _dereq_('util/');
var hasOwn = Object.prototype.hasOwnProperty;
var pSlice = Array.prototype.slice;
var functionsHaveNames = (function () {
  return function foo() {}.name === 'foo';
}());
function pToString (obj) {
  return Object.prototype.toString.call(obj);
}
function isView(arrbuf) {
  if (isBuffer(arrbuf)) {
    return false;
  }
  if (typeof global.ArrayBuffer !== 'function') {
    return false;
  }
  if (typeof ArrayBuffer.isView === 'function') {
    return ArrayBuffer.isView(arrbuf);
  }
  if (!arrbuf) {
    return false;
  }
  if (arrbuf instanceof DataView) {
    return true;
  }
  if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
    return true;
  }
  return false;
}
// 1. The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.

var assert = module.exports = ok;

// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
//                             actual: actual,
//                             expected: expected })

var regex = /\s*function\s+([^\(\s]*)\s*/;
// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
function getName(func) {
  if (!util.isFunction(func)) {
    return;
  }
  if (functionsHaveNames) {
    return func.name;
  }
  var str = func.toString();
  var match = str.match(regex);
  return match && match[1];
}
assert.AssertionError = function AssertionError(options) {
  this.name = 'AssertionError';
  this.actual = options.actual;
  this.expected = options.expected;
  this.operator = options.operator;
  if (options.message) {
    this.message = options.message;
    this.generatedMessage = false;
  } else {
    this.message = getMessage(this);
    this.generatedMessage = true;
  }
  var stackStartFunction = options.stackStartFunction || fail;
  if (Error.captureStackTrace) {
    Error.captureStackTrace(this, stackStartFunction);
  } else {
    // non v8 browsers so we can have a stacktrace
    var err = new Error();
    if (err.stack) {
      var out = err.stack;

      // try to strip useless frames
      var fn_name = getName(stackStartFunction);
      var idx = out.indexOf('\n' + fn_name);
      if (idx >= 0) {
        // once we have located the function frame
        // we need to strip out everything before it (and its line)
        var next_line = out.indexOf('\n', idx + 1);
        out = out.substring(next_line + 1);
      }

      this.stack = out;
    }
  }
};

// assert.AssertionError instanceof Error
util.inherits(assert.AssertionError, Error);

function truncate(s, n) {
  if (typeof s === 'string') {
    return s.length < n ? s : s.slice(0, n);
  } else {
    return s;
  }
}
function inspect(something) {
  if (functionsHaveNames || !util.isFunction(something)) {
    return util.inspect(something);
  }
  var rawname = getName(something);
  var name = rawname ? ': ' + rawname : '';
  return '[Function' +  name + ']';
}
function getMessage(self) {
  return truncate(inspect(self.actual), 128) + ' ' +
         self.operator + ' ' +
         truncate(inspect(self.expected), 128);
}

// At present only the three keys mentioned above are used and
// understood by the spec. Implementations or sub modules can pass
// other keys to the AssertionError's constructor - they will be
// ignored.

// 3. All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided.  All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.

function fail(actual, expected, message, operator, stackStartFunction) {
  throw new assert.AssertionError({
    message: message,
    actual: actual,
    expected: expected,
    operator: operator,
    stackStartFunction: stackStartFunction
  });
}

// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;

// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.

function ok(value, message) {
  if (!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;

// 5. The equality assertion tests shallow, coercive equality with
// ==.
// assert.equal(actual, expected, message_opt);

assert.equal = function equal(actual, expected, message) {
  if (actual != expected) fail(actual, expected, message, '==', assert.equal);
};

// 6. The non-equality assertion tests for whether two objects are not equal
// with != assert.notEqual(actual, expected, message_opt);

assert.notEqual = function notEqual(actual, expected, message) {
  if (actual == expected) {
    fail(actual, expected, message, '!=', assert.notEqual);
  }
};

// 7. The equivalence assertion tests a deep equality relation.
// assert.deepEqual(actual, expected, message_opt);

assert.deepEqual = function deepEqual(actual, expected, message) {
  if (!_deepEqual(actual, expected, false)) {
    fail(actual, expected, message, 'deepEqual', assert.deepEqual);
  }
};

assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
  if (!_deepEqual(actual, expected, true)) {
    fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
  }
};

function _deepEqual(actual, expected, strict, memos) {
  // 7.1. All identical values are equivalent, as determined by ===.
  if (actual === expected) {
    return true;
  } else if (isBuffer(actual) && isBuffer(expected)) {
    return compare(actual, expected) === 0;

  // 7.2. If the expected value is a Date object, the actual value is
  // equivalent if it is also a Date object that refers to the same time.
  } else if (util.isDate(actual) && util.isDate(expected)) {
    return actual.getTime() === expected.getTime();

  // 7.3 If the expected value is a RegExp object, the actual value is
  // equivalent if it is also a RegExp object with the same source and
  // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
  } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
    return actual.source === expected.source &&
           actual.global === expected.global &&
           actual.multiline === expected.multiline &&
           actual.lastIndex === expected.lastIndex &&
           actual.ignoreCase === expected.ignoreCase;

  // 7.4. Other pairs that do not both pass typeof value == 'object',
  // equivalence is determined by ==.
  } else if ((actual === null || typeof actual !== 'object') &&
             (expected === null || typeof expected !== 'object')) {
    return strict ? actual === expected : actual == expected;

  // If both values are instances of typed arrays, wrap their underlying
  // ArrayBuffers in a Buffer each to increase performance
  // This optimization requires the arrays to have the same type as checked by
  // Object.prototype.toString (aka pToString). Never perform binary
  // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
  // bit patterns are not identical.
  } else if (isView(actual) && isView(expected) &&
             pToString(actual) === pToString(expected) &&
             !(actual instanceof Float32Array ||
               actual instanceof Float64Array)) {
    return compare(new Uint8Array(actual.buffer),
                   new Uint8Array(expected.buffer)) === 0;

  // 7.5 For all other Object pairs, including Array objects, equivalence is
  // determined by having the same number of owned properties (as verified
  // with Object.prototype.hasOwnProperty.call), the same set of keys
  // (although not necessarily the same order), equivalent values for every
  // corresponding key, and an identical 'prototype' property. Note: this
  // accounts for both named and indexed properties on Arrays.
  } else if (isBuffer(actual) !== isBuffer(expected)) {
    return false;
  } else {
    memos = memos || {actual: [], expected: []};

    var actualIndex = memos.actual.indexOf(actual);
    if (actualIndex !== -1) {
      if (actualIndex === memos.expected.indexOf(expected)) {
        return true;
      }
    }

    memos.actual.push(actual);
    memos.expected.push(expected);

    return objEquiv(actual, expected, strict, memos);
  }
}

function isArguments(object) {
  return Object.prototype.toString.call(object) == '[object Arguments]';
}

function objEquiv(a, b, strict, actualVisitedObjects) {
  if (a === null || a === undefined || b === null || b === undefined)
    return false;
  // if one is a primitive, the other must be same
  if (util.isPrimitive(a) || util.isPrimitive(b))
    return a === b;
  if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
    return false;
  var aIsArgs = isArguments(a);
  var bIsArgs = isArguments(b);
  if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
    return false;
  if (aIsArgs) {
    a = pSlice.call(a);
    b = pSlice.call(b);
    return _deepEqual(a, b, strict);
  }
  var ka = objectKeys(a);
  var kb = objectKeys(b);
  var key, i;
  // having the same number of owned properties (keys incorporates
  // hasOwnProperty)
  if (ka.length !== kb.length)
    return false;
  //the same set of keys (although not necessarily the same order),
  ka.sort();
  kb.sort();
  //~~~cheap key test
  for (i = ka.length - 1; i >= 0; i--) {
    if (ka[i] !== kb[i])
      return false;
  }
  //equivalent values for every corresponding key, and
  //~~~possibly expensive deep test
  for (i = ka.length - 1; i >= 0; i--) {
    key = ka[i];
    if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
      return false;
  }
  return true;
}

// 8. The non-equivalence assertion tests for any deep inequality.
// assert.notDeepEqual(actual, expected, message_opt);

assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
  if (_deepEqual(actual, expected, false)) {
    fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
  }
};

assert.notDeepStrictEqual = notDeepStrictEqual;
function notDeepStrictEqual(actual, expected, message) {
  if (_deepEqual(actual, expected, true)) {
    fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
  }
}


// 9. The strict equality assertion tests strict equality, as determined by ===.
// assert.strictEqual(actual, expected, message_opt);

assert.strictEqual = function strictEqual(actual, expected, message) {
  if (actual !== expected) {
    fail(actual, expected, message, '===', assert.strictEqual);
  }
};

// 10. The strict non-equality assertion tests for strict inequality, as
// determined by !==.  assert.notStrictEqual(actual, expected, message_opt);

assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (actual === expected) {
    fail(actual, expected, message, '!==', assert.notStrictEqual);
  }
};

function expectedException(actual, expected) {
  if (!actual || !expected) {
    return false;
  }

  if (Object.prototype.toString.call(expected) == '[object RegExp]') {
    return expected.test(actual);
  }

  try {
    if (actual instanceof expected) {
      return true;
    }
  } catch (e) {
    // Ignore.  The instanceof check doesn't work for arrow functions.
  }

  if (Error.isPrototypeOf(expected)) {
    return false;
  }

  return expected.call({}, actual) === true;
}

function _tryBlock(block) {
  var error;
  try {
    block();
  } catch (e) {
    error = e;
  }
  return error;
}

function _throws(shouldThrow, block, expected, message) {
  var actual;

  if (typeof block !== 'function') {
    throw new TypeError('"block" argument must be a function');
  }

  if (typeof expected === 'string') {
    message = expected;
    expected = null;
  }

  actual = _tryBlock(block);

  message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
            (message ? ' ' + message : '.');

  if (shouldThrow && !actual) {
    fail(actual, expected, 'Missing expected exception' + message);
  }

  var userProvidedMessage = typeof message === 'string';
  var isUnwantedException = !shouldThrow && util.isError(actual);
  var isUnexpectedException = !shouldThrow && actual && !expected;

  if ((isUnwantedException &&
      userProvidedMessage &&
      expectedException(actual, expected)) ||
      isUnexpectedException) {
    fail(actual, expected, 'Got unwanted exception' + message);
  }

  if ((shouldThrow && actual && expected &&
      !expectedException(actual, expected)) || (!shouldThrow && actual)) {
    throw actual;
  }
}

// 11. Expected to throw an error:
// assert.throws(block, Error_opt, message_opt);

assert.throws = function(block, /*optional*/error, /*optional*/message) {
  _throws(true, block, error, message);
};

// EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
  _throws(false, block, error, message);
};

assert.ifError = function(err) { if (err) throw err; };

var objectKeys = Object.keys || function (obj) {
  var keys = [];
  for (var key in obj) {
    if (hasOwn.call(obj, key)) keys.push(key);
  }
  return keys;
};

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"util/":59}],57:[function(_dereq_,module,exports){
if (typeof Object.create === 'function') {
  // implementation from standard node.js 'util' module
  module.exports = function inherits(ctor, superCtor) {
    ctor.super_ = superCtor
    ctor.prototype = Object.create(superCtor.prototype, {
      constructor: {
        value: ctor,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
  };
} else {
  // old school shim for old browsers
  module.exports = function inherits(ctor, superCtor) {
    ctor.super_ = superCtor
    var TempCtor = function () {}
    TempCtor.prototype = superCtor.prototype
    ctor.prototype = new TempCtor()
    ctor.prototype.constructor = ctor
  }
}

},{}],58:[function(_dereq_,module,exports){
module.exports = function isBuffer(arg) {
  return arg && typeof arg === 'object'
    && typeof arg.copy === 'function'
    && typeof arg.fill === 'function'
    && typeof arg.readUInt8 === 'function';
}
},{}],59:[function(_dereq_,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.

var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
  if (!isString(f)) {
    var objects = [];
    for (var i = 0; i < arguments.length; i++) {
      objects.push(inspect(arguments[i]));
    }
    return objects.join(' ');
  }

  var i = 1;
  var args = arguments;
  var len = args.length;
  var str = String(f).replace(formatRegExp, function(x) {
    if (x === '%%') return '%';
    if (i >= len) return x;
    switch (x) {
      case '%s': return String(args[i++]);
      case '%d': return Number(args[i++]);
      case '%j':
        try {
          return JSON.stringify(args[i++]);
        } catch (_) {
          return '[Circular]';
        }
      default:
        return x;
    }
  });
  for (var x = args[i]; i < len; x = args[++i]) {
    if (isNull(x) || !isObject(x)) {
      str += ' ' + x;
    } else {
      str += ' ' + inspect(x);
    }
  }
  return str;
};


// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
  // Allow for deprecating things in the process of starting up.
  if (isUndefined(global.process)) {
    return function() {
      return exports.deprecate(fn, msg).apply(this, arguments);
    };
  }

  if (process.noDeprecation === true) {
    return fn;
  }

  var warned = false;
  function deprecated() {
    if (!warned) {
      if (process.throwDeprecation) {
        throw new Error(msg);
      } else if (process.traceDeprecation) {
        console.trace(msg);
      } else {
        console.error(msg);
      }
      warned = true;
    }
    return fn.apply(this, arguments);
  }

  return deprecated;
};


var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
  if (isUndefined(debugEnviron))
    debugEnviron = process.env.NODE_DEBUG || '';
  set = set.toUpperCase();
  if (!debugs[set]) {
    if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
      var pid = process.pid;
      debugs[set] = function() {
        var msg = exports.format.apply(exports, arguments);
        console.error('%s %d: %s', set, pid, msg);
      };
    } else {
      debugs[set] = function() {};
    }
  }
  return debugs[set];
};


/**
 * Echos the value of a value. Trys to print the value out
 * in the best way possible given the different types.
 *
 * @param {Object} obj The object to print out.
 * @param {Object} opts Optional options object that alters the output.
 */
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
  // default options
  var ctx = {
    seen: [],
    stylize: stylizeNoColor
  };
  // legacy...
  if (arguments.length >= 3) ctx.depth = arguments[2];
  if (arguments.length >= 4) ctx.colors = arguments[3];
  if (isBoolean(opts)) {
    // legacy...
    ctx.showHidden = opts;
  } else if (opts) {
    // got an "options" object
    exports._extend(ctx, opts);
  }
  // set default options
  if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  if (isUndefined(ctx.depth)) ctx.depth = 2;
  if (isUndefined(ctx.colors)) ctx.colors = false;
  if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  if (ctx.colors) ctx.stylize = stylizeWithColor;
  return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;


// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
  'bold' : [1, 22],
  'italic' : [3, 23],
  'underline' : [4, 24],
  'inverse' : [7, 27],
  'white' : [37, 39],
  'grey' : [90, 39],
  'black' : [30, 39],
  'blue' : [34, 39],
  'cyan' : [36, 39],
  'green' : [32, 39],
  'magenta' : [35, 39],
  'red' : [31, 39],
  'yellow' : [33, 39]
};

// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
  'special': 'cyan',
  'number': 'yellow',
  'boolean': 'yellow',
  'undefined': 'grey',
  'null': 'bold',
  'string': 'green',
  'date': 'magenta',
  // "name": intentionally not styling
  'regexp': 'red'
};


function stylizeWithColor(str, styleType) {
  var style = inspect.styles[styleType];

  if (style) {
    return '\u001b[' + inspect.colors[style][0] + 'm' + str +
           '\u001b[' + inspect.colors[style][1] + 'm';
  } else {
    return str;
  }
}


function stylizeNoColor(str, styleType) {
  return str;
}


function arrayToHash(array) {
  var hash = {};

  array.forEach(function(val, idx) {
    hash[val] = true;
  });

  return hash;
}


function formatValue(ctx, value, recurseTimes) {
  // Provide a hook for user-specified inspect functions.
  // Check that value is an object with an inspect function on it
  if (ctx.customInspect &&
      value &&
      isFunction(value.inspect) &&
      // Filter out the util module, it's inspect function is special
      value.inspect !== exports.inspect &&
      // Also filter out any prototype objects using the circular check.
      !(value.constructor && value.constructor.prototype === value)) {
    var ret = value.inspect(recurseTimes, ctx);
    if (!isString(ret)) {
      ret = formatValue(ctx, ret, recurseTimes);
    }
    return ret;
  }

  // Primitive types cannot have properties
  var primitive = formatPrimitive(ctx, value);
  if (primitive) {
    return primitive;
  }

  // Look up the keys of the object.
  var keys = Object.keys(value);
  var visibleKeys = arrayToHash(keys);

  if (ctx.showHidden) {
    keys = Object.getOwnPropertyNames(value);
  }

  // IE doesn't make error fields non-enumerable
  // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  if (isError(value)
      && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
    return formatError(value);
  }

  // Some type of object without properties can be shortcutted.
  if (keys.length === 0) {
    if (isFunction(value)) {
      var name = value.name ? ': ' + value.name : '';
      return ctx.stylize('[Function' + name + ']', 'special');
    }
    if (isRegExp(value)) {
      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
    }
    if (isDate(value)) {
      return ctx.stylize(Date.prototype.toString.call(value), 'date');
    }
    if (isError(value)) {
      return formatError(value);
    }
  }

  var base = '', array = false, braces = ['{', '}'];

  // Make Array say that they are Array
  if (isArray(value)) {
    array = true;
    braces = ['[', ']'];
  }

  // Make functions say that they are functions
  if (isFunction(value)) {
    var n = value.name ? ': ' + value.name : '';
    base = ' [Function' + n + ']';
  }

  // Make RegExps say that they are RegExps
  if (isRegExp(value)) {
    base = ' ' + RegExp.prototype.toString.call(value);
  }

  // Make dates with properties first say the date
  if (isDate(value)) {
    base = ' ' + Date.prototype.toUTCString.call(value);
  }

  // Make error with message first say the error
  if (isError(value)) {
    base = ' ' + formatError(value);
  }

  if (keys.length === 0 && (!array || value.length == 0)) {
    return braces[0] + base + braces[1];
  }

  if (recurseTimes < 0) {
    if (isRegExp(value)) {
      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
    } else {
      return ctx.stylize('[Object]', 'special');
    }
  }

  ctx.seen.push(value);

  var output;
  if (array) {
    output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  } else {
    output = keys.map(function(key) {
      return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
    });
  }

  ctx.seen.pop();

  return reduceToSingleString(output, base, braces);
}


function formatPrimitive(ctx, value) {
  if (isUndefined(value))
    return ctx.stylize('undefined', 'undefined');
  if (isString(value)) {
    var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
                                             .replace(/'/g, "\\'")
                                             .replace(/\\"/g, '"') + '\'';
    return ctx.stylize(simple, 'string');
  }
  if (isNumber(value))
    return ctx.stylize('' + value, 'number');
  if (isBoolean(value))
    return ctx.stylize('' + value, 'boolean');
  // For some reason typeof null is "object", so special case here.
  if (isNull(value))
    return ctx.stylize('null', 'null');
}


function formatError(value) {
  return '[' + Error.prototype.toString.call(value) + ']';
}


function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  var output = [];
  for (var i = 0, l = value.length; i < l; ++i) {
    if (hasOwnProperty(value, String(i))) {
      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
          String(i), true));
    } else {
      output.push('');
    }
  }
  keys.forEach(function(key) {
    if (!key.match(/^\d+$/)) {
      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
          key, true));
    }
  });
  return output;
}


function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  var name, str, desc;
  desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  if (desc.get) {
    if (desc.set) {
      str = ctx.stylize('[Getter/Setter]', 'special');
    } else {
      str = ctx.stylize('[Getter]', 'special');
    }
  } else {
    if (desc.set) {
      str = ctx.stylize('[Setter]', 'special');
    }
  }
  if (!hasOwnProperty(visibleKeys, key)) {
    name = '[' + key + ']';
  }
  if (!str) {
    if (ctx.seen.indexOf(desc.value) < 0) {
      if (isNull(recurseTimes)) {
        str = formatValue(ctx, desc.value, null);
      } else {
        str = formatValue(ctx, desc.value, recurseTimes - 1);
      }
      if (str.indexOf('\n') > -1) {
        if (array) {
          str = str.split('\n').map(function(line) {
            return '  ' + line;
          }).join('\n').substr(2);
        } else {
          str = '\n' + str.split('\n').map(function(line) {
            return '   ' + line;
          }).join('\n');
        }
      }
    } else {
      str = ctx.stylize('[Circular]', 'special');
    }
  }
  if (isUndefined(name)) {
    if (array && key.match(/^\d+$/)) {
      return str;
    }
    name = JSON.stringify('' + key);
    if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
      name = name.substr(1, name.length - 2);
      name = ctx.stylize(name, 'name');
    } else {
      name = name.replace(/'/g, "\\'")
                 .replace(/\\"/g, '"')
                 .replace(/(^"|"$)/g, "'");
      name = ctx.stylize(name, 'string');
    }
  }

  return name + ': ' + str;
}


function reduceToSingleString(output, base, braces) {
  var numLinesEst = 0;
  var length = output.reduce(function(prev, cur) {
    numLinesEst++;
    if (cur.indexOf('\n') >= 0) numLinesEst++;
    return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  }, 0);

  if (length > 60) {
    return braces[0] +
           (base === '' ? '' : base + '\n ') +
           ' ' +
           output.join(',\n  ') +
           ' ' +
           braces[1];
  }

  return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}


// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
  return Array.isArray(ar);
}
exports.isArray = isArray;

function isBoolean(arg) {
  return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;

function isNull(arg) {
  return arg === null;
}
exports.isNull = isNull;

function isNullOrUndefined(arg) {
  return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;

function isNumber(arg) {
  return typeof arg === 'number';
}
exports.isNumber = isNumber;

function isString(arg) {
  return typeof arg === 'string';
}
exports.isString = isString;

function isSymbol(arg) {
  return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;

function isUndefined(arg) {
  return arg === void 0;
}
exports.isUndefined = isUndefined;

function isRegExp(re) {
  return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;

function isObject(arg) {
  return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;

function isDate(d) {
  return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;

function isError(e) {
  return isObject(e) &&
      (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;

function isFunction(arg) {
  return typeof arg === 'function';
}
exports.isFunction = isFunction;

function isPrimitive(arg) {
  return arg === null ||
         typeof arg === 'boolean' ||
         typeof arg === 'number' ||
         typeof arg === 'string' ||
         typeof arg === 'symbol' ||  // ES6 symbol
         typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;

exports.isBuffer = _dereq_('./support/isBuffer');

function objectToString(o) {
  return Object.prototype.toString.call(o);
}


function pad(n) {
  return n < 10 ? '0' + n.toString(10) : n.toString(10);
}


var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
              'Oct', 'Nov', 'Dec'];

// 26 Feb 16:19:34
function timestamp() {
  var d = new Date();
  var time = [pad(d.getHours()),
              pad(d.getMinutes()),
              pad(d.getSeconds())].join(':');
  return [d.getDate(), months[d.getMonth()], time].join(' ');
}


// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
  console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};


/**
 * Inherit the prototype methods from one constructor into another.
 *
 * The Function.prototype.inherits from lang.js rewritten as a standalone
 * function (not on Function.prototype). NOTE: If this file is to be loaded
 * during bootstrapping this function needs to be rewritten using some native
 * functions as prototype setup using normal JavaScript does not work as
 * expected during bootstrapping (see mirror.js in r114903).
 *
 * @param {function} ctor Constructor function which needs to inherit the
 *     prototype.
 * @param {function} superCtor Constructor function to inherit prototype from.
 */
exports.inherits = _dereq_('inherits');

exports._extend = function(origin, add) {
  // Don't do anything if add isn't an object
  if (!add || !isObject(add)) return origin;

  var keys = Object.keys(add);
  var i = keys.length;
  while (i--) {
    origin[keys[i]] = add[keys[i]];
  }
  return origin;
};

function hasOwnProperty(obj, prop) {
  return Object.prototype.hasOwnProperty.call(obj, prop);
}

}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":58,"_process":471,"inherits":57}],60:[function(_dereq_,module,exports){
module.exports = function _atob(str) {
  return atob(str)
}

},{}],61:[function(_dereq_,module,exports){
'use strict'

module.exports = barycentric

var solve = _dereq_('robust-linear-solve')

function reduce(x) {
  var r = 0
  for(var i=0; i<x.length; ++i) {
    r += x[i]
  }
  return r
}

function barycentric(simplex, point) {
  var d = point.length
  var A = new Array(d+1)
  for(var i=0; i<d; ++i) {
    var row = new Array(d+1)
    for(var j=0; j<=d; ++j) {
      row[j] = simplex[j][i]
    }
    A[i] = row
  }
  A[d] = new Array(d+1)
  for(var i=0; i<=d; ++i) {
    A[d][i] = 1
  }

  var b = new Array(d+1)
  for(var i=0; i<d; ++i) {
    b[i] = point[i]
  }
  b[d] = 1.0

  var x = solve(A, b)
  var w = reduce(x[d+1])
  
  if(w === 0) {
    w = 1.0
  }
  var y = new Array(d+1)
  for(var i=0; i<=d; ++i) {
    y[i] = reduce(x[i]) / w
  }
  return y
}
},{"robust-linear-solve":490}],62:[function(_dereq_,module,exports){
'use strict'

exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray

var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array

var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
  lookup[i] = code[i]
  revLookup[code.charCodeAt(i)] = i
}

// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63

function getLens (b64) {
  var len = b64.length

  if (len % 4 > 0) {
    throw new Error('Invalid string. Length must be a multiple of 4')
  }

  // Trim off extra bytes after placeholder bytes are found
  // See: https://github.com/beatgammit/base64-js/issues/42
  var validLen = b64.indexOf('=')
  if (validLen === -1) validLen = len

  var placeHoldersLen = validLen === len
    ? 0
    : 4 - (validLen % 4)

  return [validLen, placeHoldersLen]
}

// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function _byteLength (b64, validLen, placeHoldersLen) {
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function toByteArray (b64) {
  var tmp
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]

  var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))

  var curByte = 0

  // if there are placeholders, only get up to the last complete 4 chars
  var len = placeHoldersLen > 0
    ? validLen - 4
    : validLen

  for (var i = 0; i < len; i += 4) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 18) |
      (revLookup[b64.charCodeAt(i + 1)] << 12) |
      (revLookup[b64.charCodeAt(i + 2)] << 6) |
      revLookup[b64.charCodeAt(i + 3)]
    arr[curByte++] = (tmp >> 16) & 0xFF
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 2) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 2) |
      (revLookup[b64.charCodeAt(i + 1)] >> 4)
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 1) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 10) |
      (revLookup[b64.charCodeAt(i + 1)] << 4) |
      (revLookup[b64.charCodeAt(i + 2)] >> 2)
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  return arr
}

function tripletToBase64 (num) {
  return lookup[num >> 18 & 0x3F] +
    lookup[num >> 12 & 0x3F] +
    lookup[num >> 6 & 0x3F] +
    lookup[num & 0x3F]
}

function encodeChunk (uint8, start, end) {
  var tmp
  var output = []
  for (var i = start; i < end; i += 3) {
    tmp =
      ((uint8[i] << 16) & 0xFF0000) +
      ((uint8[i + 1] << 8) & 0xFF00) +
      (uint8[i + 2] & 0xFF)
    output.push(tripletToBase64(tmp))
  }
  return output.join('')
}

function fromByteArray (uint8) {
  var tmp
  var len = uint8.length
  var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  var parts = []
  var maxChunkLength = 16383 // must be multiple of 3

  // go through the array every three bytes, we'll deal with trailing stuff later
  for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
    parts.push(encodeChunk(
      uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
    ))
  }

  // pad the end with zeros, but make sure to not forget the extra bytes
  if (extraBytes === 1) {
    tmp = uint8[len - 1]
    parts.push(
      lookup[tmp >> 2] +
      lookup[(tmp << 4) & 0x3F] +
      '=='
    )
  } else if (extraBytes === 2) {
    tmp = (uint8[len - 2] << 8) + uint8[len - 1]
    parts.push(
      lookup[tmp >> 10] +
      lookup[(tmp >> 4) & 0x3F] +
      lookup[(tmp << 2) & 0x3F] +
      '='
    )
  }

  return parts.join('')
}

},{}],63:[function(_dereq_,module,exports){
'use strict'

var rationalize = _dereq_('./lib/rationalize')

module.exports = add

function add(a, b) {
  return rationalize(
    a[0].mul(b[1]).add(b[0].mul(a[1])),
    a[1].mul(b[1]))
}

},{"./lib/rationalize":73}],64:[function(_dereq_,module,exports){
'use strict'

module.exports = cmp

function cmp(a, b) {
    return a[0].mul(b[1]).cmp(b[0].mul(a[1]))
}

},{}],65:[function(_dereq_,module,exports){
'use strict'

var rationalize = _dereq_('./lib/rationalize')

module.exports = div

function div(a, b) {
  return rationalize(a[0].mul(b[1]), a[1].mul(b[0]))
}

},{"./lib/rationalize":73}],66:[function(_dereq_,module,exports){
'use strict'

var isRat = _dereq_('./is-rat')
var isBN = _dereq_('./lib/is-bn')
var num2bn = _dereq_('./lib/num-to-bn')
var str2bn = _dereq_('./lib/str-to-bn')
var rationalize = _dereq_('./lib/rationalize')
var div = _dereq_('./div')

module.exports = makeRational

function makeRational(numer, denom) {
  if(isRat(numer)) {
    if(denom) {
      return div(numer, makeRational(denom))
    }
    return [numer[0].clone(), numer[1].clone()]
  }
  var shift = 0
  var a, b
  if(isBN(numer)) {
    a = numer.clone()
  } else if(typeof numer === 'string') {
    a = str2bn(numer)
  } else if(numer === 0) {
    return [num2bn(0), num2bn(1)]
  } else if(numer === Math.floor(numer)) {
    a = num2bn(numer)
  } else {
    while(numer !== Math.floor(numer)) {
      numer = numer * Math.pow(2, 256)
      shift -= 256
    }
    a = num2bn(numer)
  }
  if(isRat(denom)) {
    a.mul(denom[1])
    b = denom[0].clone()
  } else if(isBN(denom)) {
    b = denom.clone()
  } else if(typeof denom === 'string') {
    b = str2bn(denom)
  } else if(!denom) {
    b = num2bn(1)
  } else if(denom === Math.floor(denom)) {
    b = num2bn(denom)
  } else {
    while(denom !== Math.floor(denom)) {
      denom = denom * Math.pow(2, 256)
      shift += 256
    }
    b = num2bn(denom)
  }
  if(shift > 0) {
    a = a.ushln(shift)
  } else if(shift < 0) {
    b = b.ushln(-shift)
  }
  return rationalize(a, b)
}

},{"./div":65,"./is-rat":67,"./lib/is-bn":71,"./lib/num-to-bn":72,"./lib/rationalize":73,"./lib/str-to-bn":74}],67:[function(_dereq_,module,exports){
'use strict'

var isBN = _dereq_('./lib/is-bn')

module.exports = isRat

function isRat(x) {
  return Array.isArray(x) && x.length === 2 && isBN(x[0]) && isBN(x[1])
}

},{"./lib/is-bn":71}],68:[function(_dereq_,module,exports){
'use strict'

var BN = _dereq_('bn.js')

module.exports = sign

function sign (x) {
  return x.cmp(new BN(0))
}

},{"bn.js":82}],69:[function(_dereq_,module,exports){
'use strict'

var sign = _dereq_('./bn-sign')

module.exports = bn2num

//TODO: Make this better
function bn2num(b) {
  var l = b.length
  var words = b.words
  var out = 0
  if (l === 1) {
    out = words[0]
  } else if (l === 2) {
    out = words[0] + (words[1] * 0x4000000)
  } else {
    for (var i = 0; i < l; i++) {
      var w = words[i]
      out += w * Math.pow(0x4000000, i)
    }
  }
  return sign(b) * out
}

},{"./bn-sign":68}],70:[function(_dereq_,module,exports){
'use strict'

var db = _dereq_('double-bits')
var ctz = _dereq_('bit-twiddle').countTrailingZeros

module.exports = ctzNumber

//Counts the number of trailing zeros
function ctzNumber(x) {
  var l = ctz(db.lo(x))
  if(l < 32) {
    return l
  }
  var h = ctz(db.hi(x))
  if(h > 20) {
    return 52
  }
  return h + 32
}

},{"bit-twiddle":80,"double-bits":155}],71:[function(_dereq_,module,exports){
'use strict'

var BN = _dereq_('bn.js')

module.exports = isBN

//Test if x is a bignumber
//FIXME: obviously this is the wrong way to do it
function isBN(x) {
  return x && typeof x === 'object' && Boolean(x.words)
}

},{"bn.js":82}],72:[function(_dereq_,module,exports){
'use strict'

var BN = _dereq_('bn.js')
var db = _dereq_('double-bits')

module.exports = num2bn

function num2bn(x) {
  var e = db.exponent(x)
  if(e < 52) {
    return new BN(x)
  } else {
    return (new BN(x * Math.pow(2, 52-e))).ushln(e-52)
  }
}

},{"bn.js":82,"double-bits":155}],73:[function(_dereq_,module,exports){
'use strict'

var num2bn = _dereq_('./num-to-bn')
var sign = _dereq_('./bn-sign')

module.exports = rationalize

function rationalize(numer, denom) {
  var snumer = sign(numer)
  var sdenom = sign(denom)
  if(snumer === 0) {
    return [num2bn(0), num2bn(1)]
  }
  if(sdenom === 0) {
    return [num2bn(0), num2bn(0)]
  }
  if(sdenom < 0) {
    numer = numer.neg()
    denom = denom.neg()
  }
  var d = numer.gcd(denom)
  if(d.cmpn(1)) {
    return [ numer.div(d), denom.div(d) ]
  }
  return [ numer, denom ]
}

},{"./bn-sign":68,"./num-to-bn":72}],74:[function(_dereq_,module,exports){
'use strict'

var BN = _dereq_('bn.js')

module.exports = str2BN

function str2BN(x) {
  return new BN(x)
}

},{"bn.js":82}],75:[function(_dereq_,module,exports){
'use strict'

var rationalize = _dereq_('./lib/rationalize')

module.exports = mul

function mul(a, b) {
  return rationalize(a[0].mul(b[0]), a[1].mul(b[1]))
}

},{"./lib/rationalize":73}],76:[function(_dereq_,module,exports){
'use strict'

var bnsign = _dereq_('./lib/bn-sign')

module.exports = sign

function sign(x) {
  return bnsign(x[0]) * bnsign(x[1])
}

},{"./lib/bn-sign":68}],77:[function(_dereq_,module,exports){
'use strict'

var rationalize = _dereq_('./lib/rationalize')

module.exports = sub

function sub(a, b) {
  return rationalize(a[0].mul(b[1]).sub(a[1].mul(b[0])), a[1].mul(b[1]))
}

},{"./lib/rationalize":73}],78:[function(_dereq_,module,exports){
'use strict'

var bn2num = _dereq_('./lib/bn-to-num')
var ctz = _dereq_('./lib/ctz')

module.exports = roundRat

// Round a rational to the closest float
function roundRat (f) {
  var a = f[0]
  var b = f[1]
  if (a.cmpn(0) === 0) {
    return 0
  }
  var h = a.abs().divmod(b.abs())
  var iv = h.div
  var x = bn2num(iv)
  var ir = h.mod
  var sgn = (a.negative !== b.negative) ? -1 : 1
  if (ir.cmpn(0) === 0) {
    return sgn * x
  }
  if (x) {
    var s = ctz(x) + 4
    var y = bn2num(ir.ushln(s).divRound(b))
    return sgn * (x + y * Math.pow(2, -s))
  } else {
    var ybits = b.bitLength() - ir.bitLength() + 53
    var y = bn2num(ir.ushln(ybits).divRound(b))
    if (ybits < 1023) {
      return sgn * y * Math.pow(2, -ybits)
    }
    y *= Math.pow(2, -1023)
    return sgn * y * Math.pow(2, 1023 - ybits)
  }
}

},{"./lib/bn-to-num":69,"./lib/ctz":70}],79:[function(_dereq_,module,exports){
"use strict"

function compileSearch(funcName, predicate, reversed, extraArgs, useNdarray, earlyOut) {
  var code = [
    "function ", funcName, "(a,l,h,", extraArgs.join(","),  "){",
earlyOut ? "" : "var i=", (reversed ? "l-1" : "h+1"),
";while(l<=h){\
var m=(l+h)>>>1,x=a", useNdarray ? ".get(m)" : "[m]"]
  if(earlyOut) {
    if(predicate.indexOf("c") < 0) {
      code.push(";if(x===y){return m}else if(x<=y){")
    } else {
      code.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){")
    }
  } else {
    code.push(";if(", predicate, "){i=m;")
  }
  if(reversed) {
    code.push("l=m+1}else{h=m-1}")
  } else {
    code.push("h=m-1}else{l=m+1}")
  }
  code.push("}")
  if(earlyOut) {
    code.push("return -1};")
  } else {
    code.push("return i};")
  }
  return code.join("")
}

function compileBoundsSearch(predicate, reversed, suffix, earlyOut) {
  var result = new Function([
  compileSearch("A", "x" + predicate + "y", reversed, ["y"], false, earlyOut),
  compileSearch("B", "x" + predicate + "y", reversed, ["y"], true, earlyOut),
  compileSearch("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], false, earlyOut),
  compileSearch("Q", "c(x,y)" + predicate + "0", reversed, ["y", "c"], true, earlyOut),
"function dispatchBsearch", suffix, "(a,y,c,l,h){\
if(a.shape){\
if(typeof(c)==='function'){\
return Q(a,(l===undefined)?0:l|0,(h===undefined)?a.shape[0]-1:h|0,y,c)\
}else{\
return B(a,(c===undefined)?0:c|0,(l===undefined)?a.shape[0]-1:l|0,y)\
}}else{\
if(typeof(c)==='function'){\
return P(a,(l===undefined)?0:l|0,(h===undefined)?a.length-1:h|0,y,c)\
}else{\
return A(a,(c===undefined)?0:c|0,(l===undefined)?a.length-1:l|0,y)\
}}}\
return dispatchBsearch", suffix].join(""))
  return result()
}

module.exports = {
  ge: compileBoundsSearch(">=", false, "GE"),
  gt: compileBoundsSearch(">", false, "GT"),
  lt: compileBoundsSearch("<", true, "LT"),
  le: compileBoundsSearch("<=", true, "LE"),
  eq: compileBoundsSearch("-", true, "EQ", true)
}

},{}],80:[function(_dereq_,module,exports){
/**
 * Bit twiddling hacks for JavaScript.
 *
 * Author: Mikola Lysenko
 *
 * Ported from Stanford bit twiddling hack library:
 *    http://graphics.stanford.edu/~seander/bithacks.html
 */

"use strict"; "use restrict";

//Number of bits in an integer
var INT_BITS = 32;

//Constants
exports.INT_BITS  = INT_BITS;
exports.INT_MAX   =  0x7fffffff;
exports.INT_MIN   = -1<<(INT_BITS-1);

//Returns -1, 0, +1 depending on sign of x
exports.sign = function(v) {
  return (v > 0) - (v < 0);
}

//Computes absolute value of integer
exports.abs = function(v) {
  var mask = v >> (INT_BITS-1);
  return (v ^ mask) - mask;
}

//Computes minimum of integers x and y
exports.min = function(x, y) {
  return y ^ ((x ^ y) & -(x < y));
}

//Computes maximum of integers x and y
exports.max = function(x, y) {
  return x ^ ((x ^ y) & -(x < y));
}

//Checks if a number is a power of two
exports.isPow2 = function(v) {
  return !(v & (v-1)) && (!!v);
}

//Computes log base 2 of v
exports.log2 = function(v) {
  var r, shift;
  r =     (v > 0xFFFF) << 4; v >>>= r;
  shift = (v > 0xFF  ) << 3; v >>>= shift; r |= shift;
  shift = (v > 0xF   ) << 2; v >>>= shift; r |= shift;
  shift = (v > 0x3   ) << 1; v >>>= shift; r |= shift;
  return r | (v >> 1);
}

//Computes log base 10 of v
exports.log10 = function(v) {
  return  (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 :
          (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 :
          (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0;
}

//Counts number of bits
exports.popCount = function(v) {
  v = v - ((v >>> 1) & 0x55555555);
  v = (v & 0x33333333) + ((v >>> 2) & 0x33333333);
  return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24;
}

//Counts number of trailing zeros
function countTrailingZeros(v) {
  var c = 32;
  v &= -v;
  if (v) c--;
  if (v & 0x0000FFFF) c -= 16;
  if (v & 0x00FF00FF) c -= 8;
  if (v & 0x0F0F0F0F) c -= 4;
  if (v & 0x33333333) c -= 2;
  if (v & 0x55555555) c -= 1;
  return c;
}
exports.countTrailingZeros = countTrailingZeros;

//Rounds to next power of 2
exports.nextPow2 = function(v) {
  v += v === 0;
  --v;
  v |= v >>> 1;
  v |= v >>> 2;
  v |= v >>> 4;
  v |= v >>> 8;
  v |= v >>> 16;
  return v + 1;
}

//Rounds down to previous power of 2
exports.prevPow2 = function(v) {
  v |= v >>> 1;
  v |= v >>> 2;
  v |= v >>> 4;
  v |= v >>> 8;
  v |= v >>> 16;
  return v - (v>>>1);
}

//Computes parity of word
exports.parity = function(v) {
  v ^= v >>> 16;
  v ^= v >>> 8;
  v ^= v >>> 4;
  v &= 0xf;
  return (0x6996 >>> v) & 1;
}

var REVERSE_TABLE = new Array(256);

(function(tab) {
  for(var i=0; i<256; ++i) {
    var v = i, r = i, s = 7;
    for (v >>>= 1; v; v >>>= 1) {
      r <<= 1;
      r |= v & 1;
      --s;
    }
    tab[i] = (r << s) & 0xff;
  }
})(REVERSE_TABLE);

//Reverse bits in a 32 bit word
exports.reverse = function(v) {
  return  (REVERSE_TABLE[ v         & 0xff] << 24) |
          (REVERSE_TABLE[(v >>> 8)  & 0xff] << 16) |
          (REVERSE_TABLE[(v >>> 16) & 0xff] << 8)  |
           REVERSE_TABLE[(v >>> 24) & 0xff];
}

//Interleave bits of 2 coordinates with 16 bits.  Useful for fast quadtree codes
exports.interleave2 = function(x, y) {
  x &= 0xFFFF;
  x = (x | (x << 8)) & 0x00FF00FF;
  x = (x | (x << 4)) & 0x0F0F0F0F;
  x = (x | (x << 2)) & 0x33333333;
  x = (x | (x << 1)) & 0x55555555;

  y &= 0xFFFF;
  y = (y | (y << 8)) & 0x00FF00FF;
  y = (y | (y << 4)) & 0x0F0F0F0F;
  y = (y | (y << 2)) & 0x33333333;
  y = (y | (y << 1)) & 0x55555555;

  return x | (y << 1);
}

//Extracts the nth interleaved component
exports.deinterleave2 = function(v, n) {
  v = (v >>> n) & 0x55555555;
  v = (v | (v >>> 1))  & 0x33333333;
  v = (v | (v >>> 2))  & 0x0F0F0F0F;
  v = (v | (v >>> 4))  & 0x00FF00FF;
  v = (v | (v >>> 16)) & 0x000FFFF;
  return (v << 16) >> 16;
}


//Interleave bits of 3 coordinates, each with 10 bits.  Useful for fast octree codes
exports.interleave3 = function(x, y, z) {
  x &= 0x3FF;
  x  = (x | (x<<16)) & 4278190335;
  x  = (x | (x<<8))  & 251719695;
  x  = (x | (x<<4))  & 3272356035;
  x  = (x | (x<<2))  & 1227133513;

  y &= 0x3FF;
  y  = (y | (y<<16)) & 4278190335;
  y  = (y | (y<<8))  & 251719695;
  y  = (y | (y<<4))  & 3272356035;
  y  = (y | (y<<2))  & 1227133513;
  x |= (y << 1);
  
  z &= 0x3FF;
  z  = (z | (z<<16)) & 4278190335;
  z  = (z | (z<<8))  & 251719695;
  z  = (z | (z<<4))  & 3272356035;
  z  = (z | (z<<2))  & 1227133513;
  
  return x | (z << 2);
}

//Extracts nth interleaved component of a 3-tuple
exports.deinterleave3 = function(v, n) {
  v = (v >>> n)       & 1227133513;
  v = (v | (v>>>2))   & 3272356035;
  v = (v | (v>>>4))   & 251719695;
  v = (v | (v>>>8))   & 4278190335;
  v = (v | (v>>>16))  & 0x3FF;
  return (v<<22)>>22;
}

//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page)
exports.nextCombination = function(v) {
  var t = v | (v - 1);
  return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1));
}


},{}],81:[function(_dereq_,module,exports){
'use strict'

var clamp = _dereq_('clamp')

module.exports = calcSDF

var INF = 1e20;

function calcSDF(src, options) {
    if (!options) options = {}

    var cutoff = options.cutoff == null ? 0.25 : options.cutoff
    var radius = options.radius == null ? 8 : options.radius
    var channel = options.channel || 0
    var w, h, size, data, intData, stride, ctx, canvas, imgData, i, l

    // handle image container
    if (ArrayBuffer.isView(src) || Array.isArray(src)) {
        if (!options.width || !options.height) throw Error('For raw data width and height should be provided by options')
        w = options.width, h = options.height
        data = src

        if (!options.stride) stride = Math.floor(src.length / w / h)
        else stride = options.stride
    }
    else {
        if (window.HTMLCanvasElement && src instanceof window.HTMLCanvasElement) {
            canvas = src
            ctx = canvas.getContext('2d')
            w = canvas.width, h = canvas.height
            imgData = ctx.getImageData(0, 0, w, h)
            data = imgData.data
            stride = 4
        }
        else if (window.CanvasRenderingContext2D && src instanceof window.CanvasRenderingContext2D) {
            canvas = src.canvas
            ctx = src
            w = canvas.width, h = canvas.height
            imgData = ctx.getImageData(0, 0, w, h)
            data = imgData.data
            stride = 4
        }
        else if (window.ImageData && src instanceof window.ImageData) {
            imgData = src
            w = src.width, h = src.height
            data = imgData.data
            stride = 4
        }
    }

    size = Math.max(w, h)

    //convert int data to floats
    if ((window.Uint8ClampedArray && data instanceof window.Uint8ClampedArray) || (window.Uint8Array && data instanceof window.Uint8Array)) {
        intData = data
        data = Array(w*h)

        for (i = 0, l = intData.length; i < l; i++) {
            data[i] = intData[i*stride + channel] / 255
        }
    }
    else {
        if (stride !== 1) throw Error('Raw data can have only 1 value per pixel')
    }

    // temporary arrays for the distance transform
    var gridOuter = Array(w * h)
    var gridInner = Array(w * h)
    var f = Array(size)
    var d = Array(size)
    var z = Array(size + 1)
    var v = Array(size)

    for (i = 0, l = w * h; i < l; i++) {
        var a = data[i]
        gridOuter[i] = a === 1 ? 0 : a === 0 ? INF : Math.pow(Math.max(0, 0.5 - a), 2)
        gridInner[i] = a === 1 ? INF : a === 0 ? 0 : Math.pow(Math.max(0, a - 0.5), 2)
    }

    edt(gridOuter, w, h, f, d, v, z)
    edt(gridInner, w, h, f, d, v, z)

    var dist = window.Float32Array ? new Float32Array(w * h) : new Array(w * h)

    for (i = 0, l = w*h; i < l; i++) {
        dist[i] = clamp(1 - ( (gridOuter[i] - gridInner[i]) / radius + cutoff), 0, 1)
    }

    return dist
}

// 2D Euclidean distance transform by Felzenszwalb & Huttenlocher https://cs.brown.edu/~pff/dt/
function edt(data, width, height, f, d, v, z) {
    for (var x = 0; x < width; x++) {
        for (var y = 0; y < height; y++) {
            f[y] = data[y * width + x]
        }
        edt1d(f, d, v, z, height)
        for (y = 0; y < height; y++) {
            data[y * width + x] = d[y]
        }
    }
    for (y = 0; y < height; y++) {
        for (x = 0; x < width; x++) {
            f[x] = data[y * width + x]
        }
        edt1d(f, d, v, z, width)
        for (x = 0; x < width; x++) {
            data[y * width + x] = Math.sqrt(d[x])
        }
    }
}

// 1D squared distance transform
function edt1d(f, d, v, z, n) {
    v[0] = 0;
    z[0] = -INF
    z[1] = +INF

    for (var q = 1, k = 0; q < n; q++) {
        var s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k])
        while (s <= z[k]) {
            k--
            s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k])
        }
        k++
        v[k] = q
        z[k] = s
        z[k + 1] = +INF
    }

    for (q = 0, k = 0; q < n; q++) {
        while (z[k + 1] < q) k++
        d[q] = (q - v[k]) * (q - v[k]) + f[v[k]]
    }
}

},{"clamp":103}],82:[function(_dereq_,module,exports){
(function (module, exports) {
  'use strict';

  // Utils
  function assert (val, msg) {
    if (!val) throw new Error(msg || 'Assertion failed');
  }

  // Could use `inherits` module, but don't want to move from single file
  // architecture yet.
  function inherits (ctor, superCtor) {
    ctor.super_ = superCtor;
    var TempCtor = function () {};
    TempCtor.prototype = superCtor.prototype;
    ctor.prototype = new TempCtor();
    ctor.prototype.constructor = ctor;
  }

  // BN

  function BN (number, base, endian) {
    if (BN.isBN(number)) {
      return number;
    }

    this.negative = 0;
    this.words = null;
    this.length = 0;

    // Reduction context
    this.red = null;

    if (number !== null) {
      if (base === 'le' || base === 'be') {
        endian = base;
        base = 10;
      }

      this._init(number || 0, base || 10, endian || 'be');
    }
  }
  if (typeof module === 'object') {
    module.exports = BN;
  } else {
    exports.BN = BN;
  }

  BN.BN = BN;
  BN.wordSize = 26;

  var Buffer;
  try {
    Buffer = _dereq_('buffer').Buffer;
  } catch (e) {
  }

  BN.isBN = function isBN (num) {
    if (num instanceof BN) {
      return true;
    }

    return num !== null && typeof num === 'object' &&
      num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
  };

  BN.max = function max (left, right) {
    if (left.cmp(right) > 0) return left;
    return right;
  };

  BN.min = function min (left, right) {
    if (left.cmp(right) < 0) return left;
    return right;
  };

  BN.prototype._init = function init (number, base, endian) {
    if (typeof number === 'number') {
      return this._initNumber(number, base, endian);
    }

    if (typeof number === 'object') {
      return this._initArray(number, base, endian);
    }

    if (base === 'hex') {
      base = 16;
    }
    assert(base === (base | 0) && base >= 2 && base <= 36);

    number = number.toString().replace(/\s+/g, '');
    var start = 0;
    if (number[0] === '-') {
      start++;
    }

    if (base === 16) {
      this._parseHex(number, start);
    } else {
      this._parseBase(number, base, start);
    }

    if (number[0] === '-') {
      this.negative = 1;
    }

    this.strip();

    if (endian !== 'le') return;

    this._initArray(this.toArray(), base, endian);
  };

  BN.prototype._initNumber = function _initNumber (number, base, endian) {
    if (number < 0) {
      this.negative = 1;
      number = -number;
    }
    if (number < 0x4000000) {
      this.words = [ number & 0x3ffffff ];
      this.length = 1;
    } else if (number < 0x10000000000000) {
      this.words = [
        number & 0x3ffffff,
        (number / 0x4000000) & 0x3ffffff
      ];
      this.length = 2;
    } else {
      assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
      this.words = [
        number & 0x3ffffff,
        (number / 0x4000000) & 0x3ffffff,
        1
      ];
      this.length = 3;
    }

    if (endian !== 'le') return;

    // Reverse the bytes
    this._initArray(this.toArray(), base, endian);
  };

  BN.prototype._initArray = function _initArray (number, base, endian) {
    // Perhaps a Uint8Array
    assert(typeof number.length === 'number');
    if (number.length <= 0) {
      this.words = [ 0 ];
      this.length = 1;
      return this;
    }

    this.length = Math.ceil(number.length / 3);
    this.words = new Array(this.length);
    for (var i = 0; i < this.length; i++) {
      this.words[i] = 0;
    }

    var j, w;
    var off = 0;
    if (endian === 'be') {
      for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
        w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
        this.words[j] |= (w << off) & 0x3ffffff;
        this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
        off += 24;
        if (off >= 26) {
          off -= 26;
          j++;
        }
      }
    } else if (endian === 'le') {
      for (i = 0, j = 0; i < number.length; i += 3) {
        w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
        this.words[j] |= (w << off) & 0x3ffffff;
        this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
        off += 24;
        if (off >= 26) {
          off -= 26;
          j++;
        }
      }
    }
    return this.strip();
  };

  function parseHex (str, start, end) {
    var r = 0;
    var len = Math.min(str.length, end);
    for (var i = start; i < len; i++) {
      var c = str.charCodeAt(i) - 48;

      r <<= 4;

      // 'a' - 'f'
      if (c >= 49 && c <= 54) {
        r |= c - 49 + 0xa;

      // 'A' - 'F'
      } else if (c >= 17 && c <= 22) {
        r |= c - 17 + 0xa;

      // '0' - '9'
      } else {
        r |= c & 0xf;
      }
    }
    return r;
  }

  BN.prototype._parseHex = function _parseHex (number, start) {
    // Create possibly bigger array to ensure that it fits the number
    this.length = Math.ceil((number.length - start) / 6);
    this.words = new Array(this.length);
    for (var i = 0; i < this.length; i++) {
      this.words[i] = 0;
    }

    var j, w;
    // Scan 24-bit chunks and add them to the number
    var off = 0;
    for (i = number.length - 6, j = 0; i >= start; i -= 6) {
      w = parseHex(number, i, i + 6);
      this.words[j] |= (w << off) & 0x3ffffff;
      // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
      this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
      off += 24;
      if (off >= 26) {
        off -= 26;
        j++;
      }
    }
    if (i + 6 !== start) {
      w = parseHex(number, start, i + 6);
      this.words[j] |= (w << off) & 0x3ffffff;
      this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
    }
    this.strip();
  };

  function parseBase (str, start, end, mul) {
    var r = 0;
    var len = Math.min(str.length, end);
    for (var i = start; i < len; i++) {
      var c = str.charCodeAt(i) - 48;

      r *= mul;

      // 'a'
      if (c >= 49) {
        r += c - 49 + 0xa;

      // 'A'
      } else if (c >= 17) {
        r += c - 17 + 0xa;

      // '0' - '9'
      } else {
        r += c;
      }
    }
    return r;
  }

  BN.prototype._parseBase = function _parseBase (number, base, start) {
    // Initialize as zero
    this.words = [ 0 ];
    this.length = 1;

    // Find length of limb in base
    for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
      limbLen++;
    }
    limbLen--;
    limbPow = (limbPow / base) | 0;

    var total = number.length - start;
    var mod = total % limbLen;
    var end = Math.min(total, total - mod) + start;

    var word = 0;
    for (var i = start; i < end; i += limbLen) {
      word = parseBase(number, i, i + limbLen, base);

      this.imuln(limbPow);
      if (this.words[0] + word < 0x4000000) {
        this.words[0] += word;
      } else {
        this._iaddn(word);
      }
    }

    if (mod !== 0) {
      var pow = 1;
      word = parseBase(number, i, number.length, base);

      for (i = 0; i < mod; i++) {
        pow *= base;
      }

      this.imuln(pow);
      if (this.words[0] + word < 0x4000000) {
        this.words[0] += word;
      } else {
        this._iaddn(word);
      }
    }
  };

  BN.prototype.copy = function copy (dest) {
    dest.words = new Array(this.length);
    for (var i = 0; i < this.length; i++) {
      dest.words[i] = this.words[i];
    }
    dest.length = this.length;
    dest.negative = this.negative;
    dest.red = this.red;
  };

  BN.prototype.clone = function clone () {
    var r = new BN(null);
    this.copy(r);
    return r;
  };

  BN.prototype._expand = function _expand (size) {
    while (this.length < size) {
      this.words[this.length++] = 0;
    }
    return this;
  };

  // Remove leading `0` from `this`
  BN.prototype.strip = function strip () {
    while (this.length > 1 && this.words[this.length - 1] === 0) {
      this.length--;
    }
    return this._normSign();
  };

  BN.prototype._normSign = function _normSign () {
    // -0 = 0
    if (this.length === 1 && this.words[0] === 0) {
      this.negative = 0;
    }
    return this;
  };

  BN.prototype.inspect = function inspect () {
    return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
  };

  /*

  var zeros = [];
  var groupSizes = [];
  var groupBases = [];

  var s = '';
  var i = -1;
  while (++i < BN.wordSize) {
    zeros[i] = s;
    s += '0';
  }
  groupSizes[0] = 0;
  groupSizes[1] = 0;
  groupBases[0] = 0;
  groupBases[1] = 0;
  var base = 2 - 1;
  while (++base < 36 + 1) {
    var groupSize = 0;
    var groupBase = 1;
    while (groupBase < (1 << BN.wordSize) / base) {
      groupBase *= base;
      groupSize += 1;
    }
    groupSizes[base] = groupSize;
    groupBases[base] = groupBase;
  }

  */

  var zeros = [
    '',
    '0',
    '00',
    '000',
    '0000',
    '00000',
    '000000',
    '0000000',
    '00000000',
    '000000000',
    '0000000000',
    '00000000000',
    '000000000000',
    '0000000000000',
    '00000000000000',
    '000000000000000',
    '0000000000000000',
    '00000000000000000',
    '000000000000000000',
    '0000000000000000000',
    '00000000000000000000',
    '000000000000000000000',
    '0000000000000000000000',
    '00000000000000000000000',
    '000000000000000000000000',
    '0000000000000000000000000'
  ];

  var groupSizes = [
    0, 0,
    25, 16, 12, 11, 10, 9, 8,
    8, 7, 7, 7, 7, 6, 6,
    6, 6, 6, 6, 6, 5, 5,
    5, 5, 5, 5, 5, 5, 5,
    5, 5, 5, 5, 5, 5, 5
  ];

  var groupBases = [
    0, 0,
    33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
    43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
    16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
    6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
    24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
  ];

  BN.prototype.toString = function toString (base, padding) {
    base = base || 10;
    padding = padding | 0 || 1;

    var out;
    if (base === 16 || base === 'hex') {
      out = '';
      var off = 0;
      var carry = 0;
      for (var i = 0; i < this.length; i++) {
        var w = this.words[i];
        var word = (((w << off) | carry) & 0xffffff).toString(16);
        carry = (w >>> (24 - off)) & 0xffffff;
        if (carry !== 0 || i !== this.length - 1) {
          out = zeros[6 - word.length] + word + out;
        } else {
          out = word + out;
        }
        off += 2;
        if (off >= 26) {
          off -= 26;
          i--;
        }
      }
      if (carry !== 0) {
        out = carry.toString(16) + out;
      }
      while (out.length % padding !== 0) {
        out = '0' + out;
      }
      if (this.negative !== 0) {
        out = '-' + out;
      }
      return out;
    }

    if (base === (base | 0) && base >= 2 && base <= 36) {
      // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
      var groupSize = groupSizes[base];
      // var groupBase = Math.pow(base, groupSize);
      var groupBase = groupBases[base];
      out = '';
      var c = this.clone();
      c.negative = 0;
      while (!c.isZero()) {
        var r = c.modn(groupBase).toString(base);
        c = c.idivn(groupBase);

        if (!c.isZero()) {
          out = zeros[groupSize - r.length] + r + out;
        } else {
          out = r + out;
        }
      }
      if (this.isZero()) {
        out = '0' + out;
      }
      while (out.length % padding !== 0) {
        out = '0' + out;
      }
      if (this.negative !== 0) {
        out = '-' + out;
      }
      return out;
    }

    assert(false, 'Base should be between 2 and 36');
  };

  BN.prototype.toNumber = function toNumber () {
    var ret = this.words[0];
    if (this.length === 2) {
      ret += this.words[1] * 0x4000000;
    } else if (this.length === 3 && this.words[2] === 0x01) {
      // NOTE: at this stage it is known that the top bit is set
      ret += 0x10000000000000 + (this.words[1] * 0x4000000);
    } else if (this.length > 2) {
      assert(false, 'Number can only safely store up to 53 bits');
    }
    return (this.negative !== 0) ? -ret : ret;
  };

  BN.prototype.toJSON = function toJSON () {
    return this.toString(16);
  };

  BN.prototype.toBuffer = function toBuffer (endian, length) {
    assert(typeof Buffer !== 'undefined');
    return this.toArrayLike(Buffer, endian, length);
  };

  BN.prototype.toArray = function toArray (endian, length) {
    return this.toArrayLike(Array, endian, length);
  };

  BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
    var byteLength = this.byteLength();
    var reqLength = length || Math.max(1, byteLength);
    assert(byteLength <= reqLength, 'byte array longer than desired length');
    assert(reqLength > 0, 'Requested array length <= 0');

    this.strip();
    var littleEndian = endian === 'le';
    var res = new ArrayType(reqLength);

    var b, i;
    var q = this.clone();
    if (!littleEndian) {
      // Assume big-endian
      for (i = 0; i < reqLength - byteLength; i++) {
        res[i] = 0;
      }

      for (i = 0; !q.isZero(); i++) {
        b = q.andln(0xff);
        q.iushrn(8);

        res[reqLength - i - 1] = b;
      }
    } else {
      for (i = 0; !q.isZero(); i++) {
        b = q.andln(0xff);
        q.iushrn(8);

        res[i] = b;
      }

      for (; i < reqLength; i++) {
        res[i] = 0;
      }
    }

    return res;
  };

  if (Math.clz32) {
    BN.prototype._countBits = function _countBits (w) {
      return 32 - Math.clz32(w);
    };
  } else {
    BN.prototype._countBits = function _countBits (w) {
      var t = w;
      var r = 0;
      if (t >= 0x1000) {
        r += 13;
        t >>>= 13;
      }
      if (t >= 0x40) {
        r += 7;
        t >>>= 7;
      }
      if (t >= 0x8) {
        r += 4;
        t >>>= 4;
      }
      if (t >= 0x02) {
        r += 2;
        t >>>= 2;
      }
      return r + t;
    };
  }

  BN.prototype._zeroBits = function _zeroBits (w) {
    // Short-cut
    if (w === 0) return 26;

    var t = w;
    var r = 0;
    if ((t & 0x1fff) === 0) {
      r += 13;
      t >>>= 13;
    }
    if ((t & 0x7f) === 0) {
      r += 7;
      t >>>= 7;
    }
    if ((t & 0xf) === 0) {
      r += 4;
      t >>>= 4;
    }
    if ((t & 0x3) === 0) {
      r += 2;
      t >>>= 2;
    }
    if ((t & 0x1) === 0) {
      r++;
    }
    return r;
  };

  // Return number of used bits in a BN
  BN.prototype.bitLength = function bitLength () {
    var w = this.words[this.length - 1];
    var hi = this._countBits(w);
    return (this.length - 1) * 26 + hi;
  };

  function toBitArray (num) {
    var w = new Array(num.bitLength());

    for (var bit = 0; bit < w.length; bit++) {
      var off = (bit / 26) | 0;
      var wbit = bit % 26;

      w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
    }

    return w;
  }

  // Number of trailing zero bits
  BN.prototype.zeroBits = function zeroBits () {
    if (this.isZero()) return 0;

    var r = 0;
    for (var i = 0; i < this.length; i++) {
      var b = this._zeroBits(this.words[i]);
      r += b;
      if (b !== 26) break;
    }
    return r;
  };

  BN.prototype.byteLength = function byteLength () {
    return Math.ceil(this.bitLength() / 8);
  };

  BN.prototype.toTwos = function toTwos (width) {
    if (this.negative !== 0) {
      return this.abs().inotn(width).iaddn(1);
    }
    return this.clone();
  };

  BN.prototype.fromTwos = function fromTwos (width) {
    if (this.testn(width - 1)) {
      return this.notn(width).iaddn(1).ineg();
    }
    return this.clone();
  };

  BN.prototype.isNeg = function isNeg () {
    return this.negative !== 0;
  };

  // Return negative clone of `this`
  BN.prototype.neg = function neg () {
    return this.clone().ineg();
  };

  BN.prototype.ineg = function ineg () {
    if (!this.isZero()) {
      this.negative ^= 1;
    }

    return this;
  };

  // Or `num` with `this` in-place
  BN.prototype.iuor = function iuor (num) {
    while (this.length < num.length) {
      this.words[this.length++] = 0;
    }

    for (var i = 0; i < num.length; i++) {
      this.words[i] = this.words[i] | num.words[i];
    }

    return this.strip();
  };

  BN.prototype.ior = function ior (num) {
    assert((this.negative | num.negative) === 0);
    return this.iuor(num);
  };

  // Or `num` with `this`
  BN.prototype.or = function or (num) {
    if (this.length > num.length) return this.clone().ior(num);
    return num.clone().ior(this);
  };

  BN.prototype.uor = function uor (num) {
    if (this.length > num.length) return this.clone().iuor(num);
    return num.clone().iuor(this);
  };

  // And `num` with `this` in-place
  BN.prototype.iuand = function iuand (num) {
    // b = min-length(num, this)
    var b;
    if (this.length > num.length) {
      b = num;
    } else {
      b = this;
    }

    for (var i = 0; i < b.length; i++) {
      this.words[i] = this.words[i] & num.words[i];
    }

    this.length = b.length;

    return this.strip();
  };

  BN.prototype.iand = function iand (num) {
    assert((this.negative | num.negative) === 0);
    return this.iuand(num);
  };

  // And `num` with `this`
  BN.prototype.and = function and (num) {
    if (this.length > num.length) return this.clone().iand(num);
    return num.clone().iand(this);
  };

  BN.prototype.uand = function uand (num) {
    if (this.length > num.length) return this.clone().iuand(num);
    return num.clone().iuand(this);
  };

  // Xor `num` with `this` in-place
  BN.prototype.iuxor = function iuxor (num) {
    // a.length > b.length
    var a;
    var b;
    if (this.length > num.length) {
      a = this;
      b = num;
    } else {
      a = num;
      b = this;
    }

    for (var i = 0; i < b.length; i++) {
      this.words[i] = a.words[i] ^ b.words[i];
    }

    if (this !== a) {
      for (; i < a.length; i++) {
        this.words[i] = a.words[i];
      }
    }

    this.length = a.length;

    return this.strip();
  };

  BN.prototype.ixor = function ixor (num) {
    assert((this.negative | num.negative) === 0);
    return this.iuxor(num);
  };

  // Xor `num` with `this`
  BN.prototype.xor = function xor (num) {
    if (this.length > num.length) return this.clone().ixor(num);
    return num.clone().ixor(this);
  };

  BN.prototype.uxor = function uxor (num) {
    if (this.length > num.length) return this.clone().iuxor(num);
    return num.clone().iuxor(this);
  };

  // Not ``this`` with ``width`` bitwidth
  BN.prototype.inotn = function inotn (width) {
    assert(typeof width === 'number' && width >= 0);

    var bytesNeeded = Math.ceil(width / 26) | 0;
    var bitsLeft = width % 26;

    // Extend the buffer with leading zeroes
    this._expand(bytesNeeded);

    if (bitsLeft > 0) {
      bytesNeeded--;
    }

    // Handle complete words
    for (var i = 0; i < bytesNeeded; i++) {
      this.words[i] = ~this.words[i] & 0x3ffffff;
    }

    // Handle the residue
    if (bitsLeft > 0) {
      this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
    }

    // And remove leading zeroes
    return this.strip();
  };

  BN.prototype.notn = function notn (width) {
    return this.clone().inotn(width);
  };

  // Set `bit` of `this`
  BN.prototype.setn = function setn (bit, val) {
    assert(typeof bit === 'number' && bit >= 0);

    var off = (bit / 26) | 0;
    var wbit = bit % 26;

    this._expand(off + 1);

    if (val) {
      this.words[off] = this.words[off] | (1 << wbit);
    } else {
      this.words[off] = this.words[off] & ~(1 << wbit);
    }

    return this.strip();
  };

  // Add `num` to `this` in-place
  BN.prototype.iadd = function iadd (num) {
    var r;

    // negative + positive
    if (this.negative !== 0 && num.negative === 0) {
      this.negative = 0;
      r = this.isub(num);
      this.negative ^= 1;
      return this._normSign();

    // positive + negative
    } else if (this.negative === 0 && num.negative !== 0) {
      num.negative = 0;
      r = this.isub(num);
      num.negative = 1;
      return r._normSign();
    }

    // a.length > b.length
    var a, b;
    if (this.length > num.length) {
      a = this;
      b = num;
    } else {
      a = num;
      b = this;
    }

    var carry = 0;
    for (var i = 0; i < b.length; i++) {
      r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
      this.words[i] = r & 0x3ffffff;
      carry = r >>> 26;
    }
    for (; carry !== 0 && i < a.length; i++) {
      r = (a.words[i] | 0) + carry;
      this.words[i] = r & 0x3ffffff;
      carry = r >>> 26;
    }

    this.length = a.length;
    if (carry !== 0) {
      this.words[this.length] = carry;
      this.length++;
    // Copy the rest of the words
    } else if (a !== this) {
      for (; i < a.length; i++) {
        this.words[i] = a.words[i];
      }
    }

    return this;
  };

  // Add `num` to `this`
  BN.prototype.add = function add (num) {
    var res;
    if (num.negative !== 0 && this.negative === 0) {
      num.negative = 0;
      res = this.sub(num);
      num.negative ^= 1;
      return res;
    } else if (num.negative === 0 && this.negative !== 0) {
      this.negative = 0;
      res = num.sub(this);
      this.negative = 1;
      return res;
    }

    if (this.length > num.length) return this.clone().iadd(num);

    return num.clone().iadd(this);
  };

  // Subtract `num` from `this` in-place
  BN.prototype.isub = function isub (num) {
    // this - (-num) = this + num
    if (num.negative !== 0) {
      num.negative = 0;
      var r = this.iadd(num);
      num.negative = 1;
      return r._normSign();

    // -this - num = -(this + num)
    } else if (this.negative !== 0) {
      this.negative = 0;
      this.iadd(num);
      this.negative = 1;
      return this._normSign();
    }

    // At this point both numbers are positive
    var cmp = this.cmp(num);

    // Optimization - zeroify
    if (cmp === 0) {
      this.negative = 0;
      this.length = 1;
      this.words[0] = 0;
      return this;
    }

    // a > b
    var a, b;
    if (cmp > 0) {
      a = this;
      b = num;
    } else {
      a = num;
      b = this;
    }

    var carry = 0;
    for (var i = 0; i < b.length; i++) {
      r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
      carry = r >> 26;
      this.words[i] = r & 0x3ffffff;
    }
    for (; carry !== 0 && i < a.length; i++) {
      r = (a.words[i] | 0) + carry;
      carry = r >> 26;
      this.words[i] = r & 0x3ffffff;
    }

    // Copy rest of the words
    if (carry === 0 && i < a.length && a !== this) {
      for (; i < a.length; i++) {
        this.words[i] = a.words[i];
      }
    }

    this.length = Math.max(this.length, i);

    if (a !== this) {
      this.negative = 1;
    }

    return this.strip();
  };

  // Subtract `num` from `this`
  BN.prototype.sub = function sub (num) {
    return this.clone().isub(num);
  };

  function smallMulTo (self, num, out) {
    out.negative = num.negative ^ self.negative;
    var len = (self.length + num.length) | 0;
    out.length = len;
    len = (len - 1) | 0;

    // Peel one iteration (compiler can't do it, because of code complexity)
    var a = self.words[0] | 0;
    var b = num.words[0] | 0;
    var r = a * b;

    var lo = r & 0x3ffffff;
    var carry = (r / 0x4000000) | 0;
    out.words[0] = lo;

    for (var k = 1; k < len; k++) {
      // Sum all words with the same `i + j = k` and accumulate `ncarry`,
      // note that ncarry could be >= 0x3ffffff
      var ncarry = carry >>> 26;
      var rword = carry & 0x3ffffff;
      var maxJ = Math.min(k, num.length - 1);
      for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
        var i = (k - j) | 0;
        a = self.words[i] | 0;
        b = num.words[j] | 0;
        r = a * b + rword;
        ncarry += (r / 0x4000000) | 0;
        rword = r & 0x3ffffff;
      }
      out.words[k] = rword | 0;
      carry = ncarry | 0;
    }
    if (carry !== 0) {
      out.words[k] = carry | 0;
    } else {
      out.length--;
    }

    return out.strip();
  }

  // TODO(indutny): it may be reasonable to omit it for users who don't need
  // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
  // multiplication (like elliptic secp256k1).
  var comb10MulTo = function comb10MulTo (self, num, out) {
    var a = self.words;
    var b = num.words;
    var o = out.words;
    var c = 0;
    var lo;
    var mid;
    var hi;
    var a0 = a[0] | 0;
    var al0 = a0 & 0x1fff;
    var ah0 = a0 >>> 13;
    var a1 = a[1] | 0;
    var al1 = a1 & 0x1fff;
    var ah1 = a1 >>> 13;
    var a2 = a[2] | 0;
    var al2 = a2 & 0x1fff;
    var ah2 = a2 >>> 13;
    var a3 = a[3] | 0;
    var al3 = a3 & 0x1fff;
    var ah3 = a3 >>> 13;
    var a4 = a[4] | 0;
    var al4 = a4 & 0x1fff;
    var ah4 = a4 >>> 13;
    var a5 = a[5] | 0;
    var al5 = a5 & 0x1fff;
    var ah5 = a5 >>> 13;
    var a6 = a[6] | 0;
    var al6 = a6 & 0x1fff;
    var ah6 = a6 >>> 13;
    var a7 = a[7] | 0;
    var al7 = a7 & 0x1fff;
    var ah7 = a7 >>> 13;
    var a8 = a[8] | 0;
    var al8 = a8 & 0x1fff;
    var ah8 = a8 >>> 13;
    var a9 = a[9] | 0;
    var al9 = a9 & 0x1fff;
    var ah9 = a9 >>> 13;
    var b0 = b[0] | 0;
    var bl0 = b0 & 0x1fff;
    var bh0 = b0 >>> 13;
    var b1 = b[1] | 0;
    var bl1 = b1 & 0x1fff;
    var bh1 = b1 >>> 13;
    var b2 = b[2] | 0;
    var bl2 = b2 & 0x1fff;
    var bh2 = b2 >>> 13;
    var b3 = b[3] | 0;
    var bl3 = b3 & 0x1fff;
    var bh3 = b3 >>> 13;
    var b4 = b[4] | 0;
    var bl4 = b4 & 0x1fff;
    var bh4 = b4 >>> 13;
    var b5 = b[5] | 0;
    var bl5 = b5 & 0x1fff;
    var bh5 = b5 >>> 13;
    var b6 = b[6] | 0;
    var bl6 = b6 & 0x1fff;
    var bh6 = b6 >>> 13;
    var b7 = b[7] | 0;
    var bl7 = b7 & 0x1fff;
    var bh7 = b7 >>> 13;
    var b8 = b[8] | 0;
    var bl8 = b8 & 0x1fff;
    var bh8 = b8 >>> 13;
    var b9 = b[9] | 0;
    var bl9 = b9 & 0x1fff;
    var bh9 = b9 >>> 13;

    out.negative = self.negative ^ num.negative;
    out.length = 19;
    /* k = 0 */
    lo = Math.imul(al0, bl0);
    mid = Math.imul(al0, bh0);
    mid = (mid + Math.imul(ah0, bl0)) | 0;
    hi = Math.imul(ah0, bh0);
    var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
    w0 &= 0x3ffffff;
    /* k = 1 */
    lo = Math.imul(al1, bl0);
    mid = Math.imul(al1, bh0);
    mid = (mid + Math.imul(ah1, bl0)) | 0;
    hi = Math.imul(ah1, bh0);
    lo = (lo + Math.imul(al0, bl1)) | 0;
    mid = (mid + Math.imul(al0, bh1)) | 0;
    mid = (mid + Math.imul(ah0, bl1)) | 0;
    hi = (hi + Math.imul(ah0, bh1)) | 0;
    var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
    w1 &= 0x3ffffff;
    /* k = 2 */
    lo = Math.imul(al2, bl0);
    mid = Math.imul(al2, bh0);
    mid = (mid + Math.imul(ah2, bl0)) | 0;
    hi = Math.imul(ah2, bh0);
    lo = (lo + Math.imul(al1, bl1)) | 0;
    mid = (mid + Math.imul(al1, bh1)) | 0;
    mid = (mid + Math.imul(ah1, bl1)) | 0;
    hi = (hi + Math.imul(ah1, bh1)) | 0;
    lo = (lo + Math.imul(al0, bl2)) | 0;
    mid = (mid + Math.imul(al0, bh2)) | 0;
    mid = (mid + Math.imul(ah0, bl2)) | 0;
    hi = (hi + Math.imul(ah0, bh2)) | 0;
    var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
    w2 &= 0x3ffffff;
    /* k = 3 */
    lo = Math.imul(al3, bl0);
    mid = Math.imul(al3, bh0);
    mid = (mid + Math.imul(ah3, bl0)) | 0;
    hi = Math.imul(ah3, bh0);
    lo = (lo + Math.imul(al2, bl1)) | 0;
    mid = (mid + Math.imul(al2, bh1)) | 0;
    mid = (mid + Math.imul(ah2, bl1)) | 0;
    hi = (hi + Math.imul(ah2, bh1)) | 0;
    lo = (lo + Math.imul(al1, bl2)) | 0;
    mid = (mid + Math.imul(al1, bh2)) | 0;
    mid = (mid + Math.imul(ah1, bl2)) | 0;
    hi = (hi + Math.imul(ah1, bh2)) | 0;
    lo = (lo + Math.imul(al0, bl3)) | 0;
    mid = (mid + Math.imul(al0, bh3)) | 0;
    mid = (mid + Math.imul(ah0, bl3)) | 0;
    hi = (hi + Math.imul(ah0, bh3)) | 0;
    var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
    w3 &= 0x3ffffff;
    /* k = 4 */
    lo = Math.imul(al4, bl0);
    mid = Math.imul(al4, bh0);
    mid = (mid + Math.imul(ah4, bl0)) | 0;
    hi = Math.imul(ah4, bh0);
    lo = (lo + Math.imul(al3, bl1)) | 0;
    mid = (mid + Math.imul(al3, bh1)) | 0;
    mid = (mid + Math.imul(ah3, bl1)) | 0;
    hi = (hi + Math.imul(ah3, bh1)) | 0;
    lo = (lo + Math.imul(al2, bl2)) | 0;
    mid = (mid + Math.imul(al2, bh2)) | 0;
    mid = (mid + Math.imul(ah2, bl2)) | 0;
    hi = (hi + Math.imul(ah2, bh2)) | 0;
    lo = (lo + Math.imul(al1, bl3)) | 0;
    mid = (mid + Math.imul(al1, bh3)) | 0;
    mid = (mid + Math.imul(ah1, bl3)) | 0;
    hi = (hi + Math.imul(ah1, bh3)) | 0;
    lo = (lo + Math.imul(al0, bl4)) | 0;
    mid = (mid + Math.imul(al0, bh4)) | 0;
    mid = (mid + Math.imul(ah0, bl4)) | 0;
    hi = (hi + Math.imul(ah0, bh4)) | 0;
    var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
    w4 &= 0x3ffffff;
    /* k = 5 */
    lo = Math.imul(al5, bl0);
    mid = Math.imul(al5, bh0);
    mid = (mid + Math.imul(ah5, bl0)) | 0;
    hi = Math.imul(ah5, bh0);
    lo = (lo + Math.imul(al4, bl1)) | 0;
    mid = (mid + Math.imul(al4, bh1)) | 0;
    mid = (mid + Math.imul(ah4, bl1)) | 0;
    hi = (hi + Math.imul(ah4, bh1)) | 0;
    lo = (lo + Math.imul(al3, bl2)) | 0;
    mid = (mid + Math.imul(al3, bh2)) | 0;
    mid = (mid + Math.imul(ah3, bl2)) | 0;
    hi = (hi + Math.imul(ah3, bh2)) | 0;
    lo = (lo + Math.imul(al2, bl3)) | 0;
    mid = (mid + Math.imul(al2, bh3)) | 0;
    mid = (mid + Math.imul(ah2, bl3)) | 0;
    hi = (hi + Math.imul(ah2, bh3)) | 0;
    lo = (lo + Math.imul(al1, bl4)) | 0;
    mid = (mid + Math.imul(al1, bh4)) | 0;
    mid = (mid + Math.imul(ah1, bl4)) | 0;
    hi = (hi + Math.imul(ah1, bh4)) | 0;
    lo = (lo + Math.imul(al0, bl5)) | 0;
    mid = (mid + Math.imul(al0, bh5)) | 0;
    mid = (mid + Math.imul(ah0, bl5)) | 0;
    hi = (hi + Math.imul(ah0, bh5)) | 0;
    var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
    w5 &= 0x3ffffff;
    /* k = 6 */
    lo = Math.imul(al6, bl0);
    mid = Math.imul(al6, bh0);
    mid = (mid + Math.imul(ah6, bl0)) | 0;
    hi = Math.imul(ah6, bh0);
    lo = (lo + Math.imul(al5, bl1)) | 0;
    mid = (mid + Math.imul(al5, bh1)) | 0;
    mid = (mid + Math.imul(ah5, bl1)) | 0;
    hi = (hi + Math.imul(ah5, bh1)) | 0;
    lo = (lo + Math.imul(al4, bl2)) | 0;
    mid = (mid + Math.imul(al4, bh2)) | 0;
    mid = (mid + Math.imul(ah4, bl2)) | 0;
    hi = (hi + Math.imul(ah4, bh2)) | 0;
    lo = (lo + Math.imul(al3, bl3)) | 0;
    mid = (mid + Math.imul(al3, bh3)) | 0;
    mid = (mid + Math.imul(ah3, bl3)) | 0;
    hi = (hi + Math.imul(ah3, bh3)) | 0;
    lo = (lo + Math.imul(al2, bl4)) | 0;
    mid = (mid + Math.imul(al2, bh4)) | 0;
    mid = (mid + Math.imul(ah2, bl4)) | 0;
    hi = (hi + Math.imul(ah2, bh4)) | 0;
    lo = (lo + Math.imul(al1, bl5)) | 0;
    mid = (mid + Math.imul(al1, bh5)) | 0;
    mid = (mid + Math.imul(ah1, bl5)) | 0;
    hi = (hi + Math.imul(ah1, bh5)) | 0;
    lo = (lo + Math.imul(al0, bl6)) | 0;
    mid = (mid + Math.imul(al0, bh6)) | 0;
    mid = (mid + Math.imul(ah0, bl6)) | 0;
    hi = (hi + Math.imul(ah0, bh6)) | 0;
    var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
    w6 &= 0x3ffffff;
    /* k = 7 */
    lo = Math.imul(al7, bl0);
    mid = Math.imul(al7, bh0);
    mid = (mid + Math.imul(ah7, bl0)) | 0;
    hi = Math.imul(ah7, bh0);
    lo = (lo + Math.imul(al6, bl1)) | 0;
    mid = (mid + Math.imul(al6, bh1)) | 0;
    mid = (mid + Math.imul(ah6, bl1)) | 0;
    hi = (hi + Math.imul(ah6, bh1)) | 0;
    lo = (lo + Math.imul(al5, bl2)) | 0;
    mid = (mid + Math.imul(al5, bh2)) | 0;
    mid = (mid + Math.imul(ah5, bl2)) | 0;
    hi = (hi + Math.imul(ah5, bh2)) | 0;
    lo = (lo + Math.imul(al4, bl3)) | 0;
    mid = (mid + Math.imul(al4, bh3)) | 0;
    mid = (mid + Math.imul(ah4, bl3)) | 0;
    hi = (hi + Math.imul(ah4, bh3)) | 0;
    lo = (lo + Math.imul(al3, bl4)) | 0;
    mid = (mid + Math.imul(al3, bh4)) | 0;
    mid = (mid + Math.imul(ah3, bl4)) | 0;
    hi = (hi + Math.imul(ah3, bh4)) | 0;
    lo = (lo + Math.imul(al2, bl5)) | 0;
    mid = (mid + Math.imul(al2, bh5)) | 0;
    mid = (mid + Math.imul(ah2, bl5)) | 0;
    hi = (hi + Math.imul(ah2, bh5)) | 0;
    lo = (lo + Math.imul(al1, bl6)) | 0;
    mid = (mid + Math.imul(al1, bh6)) | 0;
    mid = (mid + Math.imul(ah1, bl6)) | 0;
    hi = (hi + Math.imul(ah1, bh6)) | 0;
    lo = (lo + Math.imul(al0, bl7)) | 0;
    mid = (mid + Math.imul(al0, bh7)) | 0;
    mid = (mid + Math.imul(ah0, bl7)) | 0;
    hi = (hi + Math.imul(ah0, bh7)) | 0;
    var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
    w7 &= 0x3ffffff;
    /* k = 8 */
    lo = Math.imul(al8, bl0);
    mid = Math.imul(al8, bh0);
    mid = (mid + Math.imul(ah8, bl0)) | 0;
    hi = Math.imul(ah8, bh0);
    lo = (lo + Math.imul(al7, bl1)) | 0;
    mid = (mid + Math.imul(al7, bh1)) | 0;
    mid = (mid + Math.imul(ah7, bl1)) | 0;
    hi = (hi + Math.imul(ah7, bh1)) | 0;
    lo = (lo + Math.imul(al6, bl2)) | 0;
    mid = (mid + Math.imul(al6, bh2)) | 0;
    mid = (mid + Math.imul(ah6, bl2)) | 0;
    hi = (hi + Math.imul(ah6, bh2)) | 0;
    lo = (lo + Math.imul(al5, bl3)) | 0;
    mid = (mid + Math.imul(al5, bh3)) | 0;
    mid = (mid + Math.imul(ah5, bl3)) | 0;
    hi = (hi + Math.imul(ah5, bh3)) | 0;
    lo = (lo + Math.imul(al4, bl4)) | 0;
    mid = (mid + Math.imul(al4, bh4)) | 0;
    mid = (mid + Math.imul(ah4, bl4)) | 0;
    hi = (hi + Math.imul(ah4, bh4)) | 0;
    lo = (lo + Math.imul(al3, bl5)) | 0;
    mid = (mid + Math.imul(al3, bh5)) | 0;
    mid = (mid + Math.imul(ah3, bl5)) | 0;
    hi = (hi + Math.imul(ah3, bh5)) | 0;
    lo = (lo + Math.imul(al2, bl6)) | 0;
    mid = (mid + Math.imul(al2, bh6)) | 0;
    mid = (mid + Math.imul(ah2, bl6)) | 0;
    hi = (hi + Math.imul(ah2, bh6)) | 0;
    lo = (lo + Math.imul(al1, bl7)) | 0;
    mid = (mid + Math.imul(al1, bh7)) | 0;
    mid = (mid + Math.imul(ah1, bl7)) | 0;
    hi = (hi + Math.imul(ah1, bh7)) | 0;
    lo = (lo + Math.imul(al0, bl8)) | 0;
    mid = (mid + Math.imul(al0, bh8)) | 0;
    mid = (mid + Math.imul(ah0, bl8)) | 0;
    hi = (hi + Math.imul(ah0, bh8)) | 0;
    var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
    w8 &= 0x3ffffff;
    /* k = 9 */
    lo = Math.imul(al9, bl0);
    mid = Math.imul(al9, bh0);
    mid = (mid + Math.imul(ah9, bl0)) | 0;
    hi = Math.imul(ah9, bh0);
    lo = (lo + Math.imul(al8, bl1)) | 0;
    mid = (mid + Math.imul(al8, bh1)) | 0;
    mid = (mid + Math.imul(ah8, bl1)) | 0;
    hi = (hi + Math.imul(ah8, bh1)) | 0;
    lo = (lo + Math.imul(al7, bl2)) | 0;
    mid = (mid + Math.imul(al7, bh2)) | 0;
    mid = (mid + Math.imul(ah7, bl2)) | 0;
    hi = (hi + Math.imul(ah7, bh2)) | 0;
    lo = (lo + Math.imul(al6, bl3)) | 0;
    mid = (mid + Math.imul(al6, bh3)) | 0;
    mid = (mid + Math.imul(ah6, bl3)) | 0;
    hi = (hi + Math.imul(ah6, bh3)) | 0;
    lo = (lo + Math.imul(al5, bl4)) | 0;
    mid = (mid + Math.imul(al5, bh4)) | 0;
    mid = (mid + Math.imul(ah5, bl4)) | 0;
    hi = (hi + Math.imul(ah5, bh4)) | 0;
    lo = (lo + Math.imul(al4, bl5)) | 0;
    mid = (mid + Math.imul(al4, bh5)) | 0;
    mid = (mid + Math.imul(ah4, bl5)) | 0;
    hi = (hi + Math.imul(ah4, bh5)) | 0;
    lo = (lo + Math.imul(al3, bl6)) | 0;
    mid = (mid + Math.imul(al3, bh6)) | 0;
    mid = (mid + Math.imul(ah3, bl6)) | 0;
    hi = (hi + Math.imul(ah3, bh6)) | 0;
    lo = (lo + Math.imul(al2, bl7)) | 0;
    mid = (mid + Math.imul(al2, bh7)) | 0;
    mid = (mid + Math.imul(ah2, bl7)) | 0;
    hi = (hi + Math.imul(ah2, bh7)) | 0;
    lo = (lo + Math.imul(al1, bl8)) | 0;
    mid = (mid + Math.imul(al1, bh8)) | 0;
    mid = (mid + Math.imul(ah1, bl8)) | 0;
    hi = (hi + Math.imul(ah1, bh8)) | 0;
    lo = (lo + Math.imul(al0, bl9)) | 0;
    mid = (mid + Math.imul(al0, bh9)) | 0;
    mid = (mid + Math.imul(ah0, bl9)) | 0;
    hi = (hi + Math.imul(ah0, bh9)) | 0;
    var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
    w9 &= 0x3ffffff;
    /* k = 10 */
    lo = Math.imul(al9, bl1);
    mid = Math.imul(al9, bh1);
    mid = (mid + Math.imul(ah9, bl1)) | 0;
    hi = Math.imul(ah9, bh1);
    lo = (lo + Math.imul(al8, bl2)) | 0;
    mid = (mid + Math.imul(al8, bh2)) | 0;
    mid = (mid + Math.imul(ah8, bl2)) | 0;
    hi = (hi + Math.imul(ah8, bh2)) | 0;
    lo = (lo + Math.imul(al7, bl3)) | 0;
    mid = (mid + Math.imul(al7, bh3)) | 0;
    mid = (mid + Math.imul(ah7, bl3)) | 0;
    hi = (hi + Math.imul(ah7, bh3)) | 0;
    lo = (lo + Math.imul(al6, bl4)) | 0;
    mid = (mid + Math.imul(al6, bh4)) | 0;
    mid = (mid + Math.imul(ah6, bl4)) | 0;
    hi = (hi + Math.imul(ah6, bh4)) | 0;
    lo = (lo + Math.imul(al5, bl5)) | 0;
    mid = (mid + Math.imul(al5, bh5)) | 0;
    mid = (mid + Math.imul(ah5, bl5)) | 0;
    hi = (hi + Math.imul(ah5, bh5)) | 0;
    lo = (lo + Math.imul(al4, bl6)) | 0;
    mid = (mid + Math.imul(al4, bh6)) | 0;
    mid = (mid + Math.imul(ah4, bl6)) | 0;
    hi = (hi + Math.imul(ah4, bh6)) | 0;
    lo = (lo + Math.imul(al3, bl7)) | 0;
    mid = (mid + Math.imul(al3, bh7)) | 0;
    mid = (mid + Math.imul(ah3, bl7)) | 0;
    hi = (hi + Math.imul(ah3, bh7)) | 0;
    lo = (lo + Math.imul(al2, bl8)) | 0;
    mid = (mid + Math.imul(al2, bh8)) | 0;
    mid = (mid + Math.imul(ah2, bl8)) | 0;
    hi = (hi + Math.imul(ah2, bh8)) | 0;
    lo = (lo + Math.imul(al1, bl9)) | 0;
    mid = (mid + Math.imul(al1, bh9)) | 0;
    mid = (mid + Math.imul(ah1, bl9)) | 0;
    hi = (hi + Math.imul(ah1, bh9)) | 0;
    var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
    w10 &= 0x3ffffff;
    /* k = 11 */
    lo = Math.imul(al9, bl2);
    mid = Math.imul(al9, bh2);
    mid = (mid + Math.imul(ah9, bl2)) | 0;
    hi = Math.imul(ah9, bh2);
    lo = (lo + Math.imul(al8, bl3)) | 0;
    mid = (mid + Math.imul(al8, bh3)) | 0;
    mid = (mid + Math.imul(ah8, bl3)) | 0;
    hi = (hi + Math.imul(ah8, bh3)) | 0;
    lo = (lo + Math.imul(al7, bl4)) | 0;
    mid = (mid + Math.imul(al7, bh4)) | 0;
    mid = (mid + Math.imul(ah7, bl4)) | 0;
    hi = (hi + Math.imul(ah7, bh4)) | 0;
    lo = (lo + Math.imul(al6, bl5)) | 0;
    mid = (mid + Math.imul(al6, bh5)) | 0;
    mid = (mid + Math.imul(ah6, bl5)) | 0;
    hi = (hi + Math.imul(ah6, bh5)) | 0;
    lo = (lo + Math.imul(al5, bl6)) | 0;
    mid = (mid + Math.imul(al5, bh6)) | 0;
    mid = (mid + Math.imul(ah5, bl6)) | 0;
    hi = (hi + Math.imul(ah5, bh6)) | 0;
    lo = (lo + Math.imul(al4, bl7)) | 0;
    mid = (mid + Math.imul(al4, bh7)) | 0;
    mid = (mid + Math.imul(ah4, bl7)) | 0;
    hi = (hi + Math.imul(ah4, bh7)) | 0;
    lo = (lo + Math.imul(al3, bl8)) | 0;
    mid = (mid + Math.imul(al3, bh8)) | 0;
    mid = (mid + Math.imul(ah3, bl8)) | 0;
    hi = (hi + Math.imul(ah3, bh8)) | 0;
    lo = (lo + Math.imul(al2, bl9)) | 0;
    mid = (mid + Math.imul(al2, bh9)) | 0;
    mid = (mid + Math.imul(ah2, bl9)) | 0;
    hi = (hi + Math.imul(ah2, bh9)) | 0;
    var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
    w11 &= 0x3ffffff;
    /* k = 12 */
    lo = Math.imul(al9, bl3);
    mid = Math.imul(al9, bh3);
    mid = (mid + Math.imul(ah9, bl3)) | 0;
    hi = Math.imul(ah9, bh3);
    lo = (lo + Math.imul(al8, bl4)) | 0;
    mid = (mid + Math.imul(al8, bh4)) | 0;
    mid = (mid + Math.imul(ah8, bl4)) | 0;
    hi = (hi + Math.imul(ah8, bh4)) | 0;
    lo = (lo + Math.imul(al7, bl5)) | 0;
    mid = (mid + Math.imul(al7, bh5)) | 0;
    mid = (mid + Math.imul(ah7, bl5)) | 0;
    hi = (hi + Math.imul(ah7, bh5)) | 0;
    lo = (lo + Math.imul(al6, bl6)) | 0;
    mid = (mid + Math.imul(al6, bh6)) | 0;
    mid = (mid + Math.imul(ah6, bl6)) | 0;
    hi = (hi + Math.imul(ah6, bh6)) | 0;
    lo = (lo + Math.imul(al5, bl7)) | 0;
    mid = (mid + Math.imul(al5, bh7)) | 0;
    mid = (mid + Math.imul(ah5, bl7)) | 0;
    hi = (hi + Math.imul(ah5, bh7)) | 0;
    lo = (lo + Math.imul(al4, bl8)) | 0;
    mid = (mid + Math.imul(al4, bh8)) | 0;
    mid = (mid + Math.imul(ah4, bl8)) | 0;
    hi = (hi + Math.imul(ah4, bh8)) | 0;
    lo = (lo + Math.imul(al3, bl9)) | 0;
    mid = (mid + Math.imul(al3, bh9)) | 0;
    mid = (mid + Math.imul(ah3, bl9)) | 0;
    hi = (hi + Math.imul(ah3, bh9)) | 0;
    var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
    w12 &= 0x3ffffff;
    /* k = 13 */
    lo = Math.imul(al9, bl4);
    mid = Math.imul(al9, bh4);
    mid = (mid + Math.imul(ah9, bl4)) | 0;
    hi = Math.imul(ah9, bh4);
    lo = (lo + Math.imul(al8, bl5)) | 0;
    mid = (mid + Math.imul(al8, bh5)) | 0;
    mid = (mid + Math.imul(ah8, bl5)) | 0;
    hi = (hi + Math.imul(ah8, bh5)) | 0;
    lo = (lo + Math.imul(al7, bl6)) | 0;
    mid = (mid + Math.imul(al7, bh6)) | 0;
    mid = (mid + Math.imul(ah7, bl6)) | 0;
    hi = (hi + Math.imul(ah7, bh6)) | 0;
    lo = (lo + Math.imul(al6, bl7)) | 0;
    mid = (mid + Math.imul(al6, bh7)) | 0;
    mid = (mid + Math.imul(ah6, bl7)) | 0;
    hi = (hi + Math.imul(ah6, bh7)) | 0;
    lo = (lo + Math.imul(al5, bl8)) | 0;
    mid = (mid + Math.imul(al5, bh8)) | 0;
    mid = (mid + Math.imul(ah5, bl8)) | 0;
    hi = (hi + Math.imul(ah5, bh8)) | 0;
    lo = (lo + Math.imul(al4, bl9)) | 0;
    mid = (mid + Math.imul(al4, bh9)) | 0;
    mid = (mid + Math.imul(ah4, bl9)) | 0;
    hi = (hi + Math.imul(ah4, bh9)) | 0;
    var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
    w13 &= 0x3ffffff;
    /* k = 14 */
    lo = Math.imul(al9, bl5);
    mid = Math.imul(al9, bh5);
    mid = (mid + Math.imul(ah9, bl5)) | 0;
    hi = Math.imul(ah9, bh5);
    lo = (lo + Math.imul(al8, bl6)) | 0;
    mid = (mid + Math.imul(al8, bh6)) | 0;
    mid = (mid + Math.imul(ah8, bl6)) | 0;
    hi = (hi + Math.imul(ah8, bh6)) | 0;
    lo = (lo + Math.imul(al7, bl7)) | 0;
    mid = (mid + Math.imul(al7, bh7)) | 0;
    mid = (mid + Math.imul(ah7, bl7)) | 0;
    hi = (hi + Math.imul(ah7, bh7)) | 0;
    lo = (lo + Math.imul(al6, bl8)) | 0;
    mid = (mid + Math.imul(al6, bh8)) | 0;
    mid = (mid + Math.imul(ah6, bl8)) | 0;
    hi = (hi + Math.imul(ah6, bh8)) | 0;
    lo = (lo + Math.imul(al5, bl9)) | 0;
    mid = (mid + Math.imul(al5, bh9)) | 0;
    mid = (mid + Math.imul(ah5, bl9)) | 0;
    hi = (hi + Math.imul(ah5, bh9)) | 0;
    var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
    w14 &= 0x3ffffff;
    /* k = 15 */
    lo = Math.imul(al9, bl6);
    mid = Math.imul(al9, bh6);
    mid = (mid + Math.imul(ah9, bl6)) | 0;
    hi = Math.imul(ah9, bh6);
    lo = (lo + Math.imul(al8, bl7)) | 0;
    mid = (mid + Math.imul(al8, bh7)) | 0;
    mid = (mid + Math.imul(ah8, bl7)) | 0;
    hi = (hi + Math.imul(ah8, bh7)) | 0;
    lo = (lo + Math.imul(al7, bl8)) | 0;
    mid = (mid + Math.imul(al7, bh8)) | 0;
    mid = (mid + Math.imul(ah7, bl8)) | 0;
    hi = (hi + Math.imul(ah7, bh8)) | 0;
    lo = (lo + Math.imul(al6, bl9)) | 0;
    mid = (mid + Math.imul(al6, bh9)) | 0;
    mid = (mid + Math.imul(ah6, bl9)) | 0;
    hi = (hi + Math.imul(ah6, bh9)) | 0;
    var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
    w15 &= 0x3ffffff;
    /* k = 16 */
    lo = Math.imul(al9, bl7);
    mid = Math.imul(al9, bh7);
    mid = (mid + Math.imul(ah9, bl7)) | 0;
    hi = Math.imul(ah9, bh7);
    lo = (lo + Math.imul(al8, bl8)) | 0;
    mid = (mid + Math.imul(al8, bh8)) | 0;
    mid = (mid + Math.imul(ah8, bl8)) | 0;
    hi = (hi + Math.imul(ah8, bh8)) | 0;
    lo = (lo + Math.imul(al7, bl9)) | 0;
    mid = (mid + Math.imul(al7, bh9)) | 0;
    mid = (mid + Math.imul(ah7, bl9)) | 0;
    hi = (hi + Math.imul(ah7, bh9)) | 0;
    var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
    w16 &= 0x3ffffff;
    /* k = 17 */
    lo = Math.imul(al9, bl8);
    mid = Math.imul(al9, bh8);
    mid = (mid + Math.imul(ah9, bl8)) | 0;
    hi = Math.imul(ah9, bh8);
    lo = (lo + Math.imul(al8, bl9)) | 0;
    mid = (mid + Math.imul(al8, bh9)) | 0;
    mid = (mid + Math.imul(ah8, bl9)) | 0;
    hi = (hi + Math.imul(ah8, bh9)) | 0;
    var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
    w17 &= 0x3ffffff;
    /* k = 18 */
    lo = Math.imul(al9, bl9);
    mid = Math.imul(al9, bh9);
    mid = (mid + Math.imul(ah9, bl9)) | 0;
    hi = Math.imul(ah9, bh9);
    var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
    w18 &= 0x3ffffff;
    o[0] = w0;
    o[1] = w1;
    o[2] = w2;
    o[3] = w3;
    o[4] = w4;
    o[5] = w5;
    o[6] = w6;
    o[7] = w7;
    o[8] = w8;
    o[9] = w9;
    o[10] = w10;
    o[11] = w11;
    o[12] = w12;
    o[13] = w13;
    o[14] = w14;
    o[15] = w15;
    o[16] = w16;
    o[17] = w17;
    o[18] = w18;
    if (c !== 0) {
      o[19] = c;
      out.length++;
    }
    return out;
  };

  // Polyfill comb
  if (!Math.imul) {
    comb10MulTo = smallMulTo;
  }

  function bigMulTo (self, num, out) {
    out.negative = num.negative ^ self.negative;
    out.length = self.length + num.length;

    var carry = 0;
    var hncarry = 0;
    for (var k = 0; k < out.length - 1; k++) {
      // Sum all words with the same `i + j = k` and accumulate `ncarry`,
      // note that ncarry could be >= 0x3ffffff
      var ncarry = hncarry;
      hncarry = 0;
      var rword = carry & 0x3ffffff;
      var maxJ = Math.min(k, num.length - 1);
      for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
        var i = k - j;
        var a = self.words[i] | 0;
        var b = num.words[j] | 0;
        var r = a * b;

        var lo = r & 0x3ffffff;
        ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
        lo = (lo + rword) | 0;
        rword = lo & 0x3ffffff;
        ncarry = (ncarry + (lo >>> 26)) | 0;

        hncarry += ncarry >>> 26;
        ncarry &= 0x3ffffff;
      }
      out.words[k] = rword;
      carry = ncarry;
      ncarry = hncarry;
    }
    if (carry !== 0) {
      out.words[k] = carry;
    } else {
      out.length--;
    }

    return out.strip();
  }

  function jumboMulTo (self, num, out) {
    var fftm = new FFTM();
    return fftm.mulp(self, num, out);
  }

  BN.prototype.mulTo = function mulTo (num, out) {
    var res;
    var len = this.length + num.length;
    if (this.length === 10 && num.length === 10) {
      res = comb10MulTo(this, num, out);
    } else if (len < 63) {
      res = smallMulTo(this, num, out);
    } else if (len < 1024) {
      res = bigMulTo(this, num, out);
    } else {
      res = jumboMulTo(this, num, out);
    }

    return res;
  };

  // Cooley-Tukey algorithm for FFT
  // slightly revisited to rely on looping instead of recursion

  function FFTM (x, y) {
    this.x = x;
    this.y = y;
  }

  FFTM.prototype.makeRBT = function makeRBT (N) {
    var t = new Array(N);
    var l = BN.prototype._countBits(N) - 1;
    for (var i = 0; i < N; i++) {
      t[i] = this.revBin(i, l, N);
    }

    return t;
  };

  // Returns binary-reversed representation of `x`
  FFTM.prototype.revBin = function revBin (x, l, N) {
    if (x === 0 || x === N - 1) return x;

    var rb = 0;
    for (var i = 0; i < l; i++) {
      rb |= (x & 1) << (l - i - 1);
      x >>= 1;
    }

    return rb;
  };

  // Performs "tweedling" phase, therefore 'emulating'
  // behaviour of the recursive algorithm
  FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
    for (var i = 0; i < N; i++) {
      rtws[i] = rws[rbt[i]];
      itws[i] = iws[rbt[i]];
    }
  };

  FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
    this.permute(rbt, rws, iws, rtws, itws, N);

    for (var s = 1; s < N; s <<= 1) {
      var l = s << 1;

      var rtwdf = Math.cos(2 * Math.PI / l);
      var itwdf = Math.sin(2 * Math.PI / l);

      for (var p = 0; p < N; p += l) {
        var rtwdf_ = rtwdf;
        var itwdf_ = itwdf;

        for (var j = 0; j < s; j++) {
          var re = rtws[p + j];
          var ie = itws[p + j];

          var ro = rtws[p + j + s];
          var io = itws[p + j + s];

          var rx = rtwdf_ * ro - itwdf_ * io;

          io = rtwdf_ * io + itwdf_ * ro;
          ro = rx;

          rtws[p + j] = re + ro;
          itws[p + j] = ie + io;

          rtws[p + j + s] = re - ro;
          itws[p + j + s] = ie - io;

          /* jshint maxdepth : false */
          if (j !== l) {
            rx = rtwdf * rtwdf_ - itwdf * itwdf_;

            itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
            rtwdf_ = rx;
          }
        }
      }
    }
  };

  FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
    var N = Math.max(m, n) | 1;
    var odd = N & 1;
    var i = 0;
    for (N = N / 2 | 0; N; N = N >>> 1) {
      i++;
    }

    return 1 << i + 1 + odd;
  };

  FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
    if (N <= 1) return;

    for (var i = 0; i < N / 2; i++) {
      var t = rws[i];

      rws[i] = rws[N - i - 1];
      rws[N - i - 1] = t;

      t = iws[i];

      iws[i] = -iws[N - i - 1];
      iws[N - i - 1] = -t;
    }
  };

  FFTM.prototype.normalize13b = function normalize13b (ws, N) {
    var carry = 0;
    for (var i = 0; i < N / 2; i++) {
      var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
        Math.round(ws[2 * i] / N) +
        carry;

      ws[i] = w & 0x3ffffff;

      if (w < 0x4000000) {
        carry = 0;
      } else {
        carry = w / 0x4000000 | 0;
      }
    }

    return ws;
  };

  FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
    var carry = 0;
    for (var i = 0; i < len; i++) {
      carry = carry + (ws[i] | 0);

      rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
      rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
    }

    // Pad with zeroes
    for (i = 2 * len; i < N; ++i) {
      rws[i] = 0;
    }

    assert(carry === 0);
    assert((carry & ~0x1fff) === 0);
  };

  FFTM.prototype.stub = function stub (N) {
    var ph = new Array(N);
    for (var i = 0; i < N; i++) {
      ph[i] = 0;
    }

    return ph;
  };

  FFTM.prototype.mulp = function mulp (x, y, out) {
    var N = 2 * this.guessLen13b(x.length, y.length);

    var rbt = this.makeRBT(N);

    var _ = this.stub(N);

    var rws = new Array(N);
    var rwst = new Array(N);
    var iwst = new Array(N);

    var nrws = new Array(N);
    var nrwst = new Array(N);
    var niwst = new Array(N);

    var rmws = out.words;
    rmws.length = N;

    this.convert13b(x.words, x.length, rws, N);
    this.convert13b(y.words, y.length, nrws, N);

    this.transform(rws, _, rwst, iwst, N, rbt);
    this.transform(nrws, _, nrwst, niwst, N, rbt);

    for (var i = 0; i < N; i++) {
      var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
      iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
      rwst[i] = rx;
    }

    this.conjugate(rwst, iwst, N);
    this.transform(rwst, iwst, rmws, _, N, rbt);
    this.conjugate(rmws, _, N);
    this.normalize13b(rmws, N);

    out.negative = x.negative ^ y.negative;
    out.length = x.length + y.length;
    return out.strip();
  };

  // Multiply `this` by `num`
  BN.prototype.mul = function mul (num) {
    var out = new BN(null);
    out.words = new Array(this.length + num.length);
    return this.mulTo(num, out);
  };

  // Multiply employing FFT
  BN.prototype.mulf = function mulf (num) {
    var out = new BN(null);
    out.words = new Array(this.length + num.length);
    return jumboMulTo(this, num, out);
  };

  // In-place Multiplication
  BN.prototype.imul = function imul (num) {
    return this.clone().mulTo(num, this);
  };

  BN.prototype.imuln = function imuln (num) {
    assert(typeof num === 'number');
    assert(num < 0x4000000);

    // Carry
    var carry = 0;
    for (var i = 0; i < this.length; i++) {
      var w = (this.words[i] | 0) * num;
      var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
      carry >>= 26;
      carry += (w / 0x4000000) | 0;
      // NOTE: lo is 27bit maximum
      carry += lo >>> 26;
      this.words[i] = lo & 0x3ffffff;
    }

    if (carry !== 0) {
      this.words[i] = carry;
      this.length++;
    }

    return this;
  };

  BN.prototype.muln = function muln (num) {
    return this.clone().imuln(num);
  };

  // `this` * `this`
  BN.prototype.sqr = function sqr () {
    return this.mul(this);
  };

  // `this` * `this` in-place
  BN.prototype.isqr = function isqr () {
    return this.imul(this.clone());
  };

  // Math.pow(`this`, `num`)
  BN.prototype.pow = function pow (num) {
    var w = toBitArray(num);
    if (w.length === 0) return new BN(1);

    // Skip leading zeroes
    var res = this;
    for (var i = 0; i < w.length; i++, res = res.sqr()) {
      if (w[i] !== 0) break;
    }

    if (++i < w.length) {
      for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
        if (w[i] === 0) continue;

        res = res.mul(q);
      }
    }

    return res;
  };

  // Shift-left in-place
  BN.prototype.iushln = function iushln (bits) {
    assert(typeof bits === 'number' && bits >= 0);
    var r = bits % 26;
    var s = (bits - r) / 26;
    var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
    var i;

    if (r !== 0) {
      var carry = 0;

      for (i = 0; i < this.length; i++) {
        var newCarry = this.words[i] & carryMask;
        var c = ((this.words[i] | 0) - newCarry) << r;
        this.words[i] = c | carry;
        carry = newCarry >>> (26 - r);
      }

      if (carry) {
        this.words[i] = carry;
        this.length++;
      }
    }

    if (s !== 0) {
      for (i = this.length - 1; i >= 0; i--) {
        this.words[i + s] = this.words[i];
      }

      for (i = 0; i < s; i++) {
        this.words[i] = 0;
      }

      this.length += s;
    }

    return this.strip();
  };

  BN.prototype.ishln = function ishln (bits) {
    // TODO(indutny): implement me
    assert(this.negative === 0);
    return this.iushln(bits);
  };

  // Shift-right in-place
  // NOTE: `hint` is a lowest bit before trailing zeroes
  // NOTE: if `extended` is present - it will be filled with destroyed bits
  BN.prototype.iushrn = function iushrn (bits, hint, extended) {
    assert(typeof bits === 'number' && bits >= 0);
    var h;
    if (hint) {
      h = (hint - (hint % 26)) / 26;
    } else {
      h = 0;
    }

    var r = bits % 26;
    var s = Math.min((bits - r) / 26, this.length);
    var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
    var maskedWords = extended;

    h -= s;
    h = Math.max(0, h);

    // Extended mode, copy masked part
    if (maskedWords) {
      for (var i = 0; i < s; i++) {
        maskedWords.words[i] = this.words[i];
      }
      maskedWords.length = s;
    }

    if (s === 0) {
      // No-op, we should not move anything at all
    } else if (this.length > s) {
      this.length -= s;
      for (i = 0; i < this.length; i++) {
        this.words[i] = this.words[i + s];
      }
    } else {
      this.words[0] = 0;
      this.length = 1;
    }

    var carry = 0;
    for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
      var word = this.words[i] | 0;
      this.words[i] = (carry << (26 - r)) | (word >>> r);
      carry = word & mask;
    }

    // Push carried bits as a mask
    if (maskedWords && carry !== 0) {
      maskedWords.words[maskedWords.length++] = carry;
    }

    if (this.length === 0) {
      this.words[0] = 0;
      this.length = 1;
    }

    return this.strip();
  };

  BN.prototype.ishrn = function ishrn (bits, hint, extended) {
    // TODO(indutny): implement me
    assert(this.negative === 0);
    return this.iushrn(bits, hint, extended);
  };

  // Shift-left
  BN.prototype.shln = function shln (bits) {
    return this.clone().ishln(bits);
  };

  BN.prototype.ushln = function ushln (bits) {
    return this.clone().iushln(bits);
  };

  // Shift-right
  BN.prototype.shrn = function shrn (bits) {
    return this.clone().ishrn(bits);
  };

  BN.prototype.ushrn = function ushrn (bits) {
    return this.clone().iushrn(bits);
  };

  // Test if n bit is set
  BN.prototype.testn = function testn (bit) {
    assert(typeof bit === 'number' && bit >= 0);
    var r = bit % 26;
    var s = (bit - r) / 26;
    var q = 1 << r;

    // Fast case: bit is much higher than all existing words
    if (this.length <= s) return false;

    // Check bit and return
    var w = this.words[s];

    return !!(w & q);
  };

  // Return only lowers bits of number (in-place)
  BN.prototype.imaskn = function imaskn (bits) {
    assert(typeof bits === 'number' && bits >= 0);
    var r = bits % 26;
    var s = (bits - r) / 26;

    assert(this.negative === 0, 'imaskn works only with positive numbers');

    if (this.length <= s) {
      return this;
    }

    if (r !== 0) {
      s++;
    }
    this.length = Math.min(s, this.length);

    if (r !== 0) {
      var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
      this.words[this.length - 1] &= mask;
    }

    return this.strip();
  };

  // Return only lowers bits of number
  BN.prototype.maskn = function maskn (bits) {
    return this.clone().imaskn(bits);
  };

  // Add plain number `num` to `this`
  BN.prototype.iaddn = function iaddn (num) {
    assert(typeof num === 'number');
    assert(num < 0x4000000);
    if (num < 0) return this.isubn(-num);

    // Possible sign change
    if (this.negative !== 0) {
      if (this.length === 1 && (this.words[0] | 0) < num) {
        this.words[0] = num - (this.words[0] | 0);
        this.negative = 0;
        return this;
      }

      this.negative = 0;
      this.isubn(num);
      this.negative = 1;
      return this;
    }

    // Add without checks
    return this._iaddn(num);
  };

  BN.prototype._iaddn = function _iaddn (num) {
    this.words[0] += num;

    // Carry
    for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
      this.words[i] -= 0x4000000;
      if (i === this.length - 1) {
        this.words[i + 1] = 1;
      } else {
        this.words[i + 1]++;
      }
    }
    this.length = Math.max(this.length, i + 1);

    return this;
  };

  // Subtract plain number `num` from `this`
  BN.prototype.isubn = function isubn (num) {
    assert(typeof num === 'number');
    assert(num < 0x4000000);
    if (num < 0) return this.iaddn(-num);

    if (this.negative !== 0) {
      this.negative = 0;
      this.iaddn(num);
      this.negative = 1;
      return this;
    }

    this.words[0] -= num;

    if (this.length === 1 && this.words[0] < 0) {
      this.words[0] = -this.words[0];
      this.negative = 1;
    } else {
      // Carry
      for (var i = 0; i < this.length && this.words[i] < 0; i++) {
        this.words[i] += 0x4000000;
        this.words[i + 1] -= 1;
      }
    }

    return this.strip();
  };

  BN.prototype.addn = function addn (num) {
    return this.clone().iaddn(num);
  };

  BN.prototype.subn = function subn (num) {
    return this.clone().isubn(num);
  };

  BN.prototype.iabs = function iabs () {
    this.negative = 0;

    return this;
  };

  BN.prototype.abs = function abs () {
    return this.clone().iabs();
  };

  BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
    var len = num.length + shift;
    var i;

    this._expand(len);

    var w;
    var carry = 0;
    for (i = 0; i < num.length; i++) {
      w = (this.words[i + shift] | 0) + carry;
      var right = (num.words[i] | 0) * mul;
      w -= right & 0x3ffffff;
      carry = (w >> 26) - ((right / 0x4000000) | 0);
      this.words[i + shift] = w & 0x3ffffff;
    }
    for (; i < this.length - shift; i++) {
      w = (this.words[i + shift] | 0) + carry;
      carry = w >> 26;
      this.words[i + shift] = w & 0x3ffffff;
    }

    if (carry === 0) return this.strip();

    // Subtraction overflow
    assert(carry === -1);
    carry = 0;
    for (i = 0; i < this.length; i++) {
      w = -(this.words[i] | 0) + carry;
      carry = w >> 26;
      this.words[i] = w & 0x3ffffff;
    }
    this.negative = 1;

    return this.strip();
  };

  BN.prototype._wordDiv = function _wordDiv (num, mode) {
    var shift = this.length - num.length;

    var a = this.clone();
    var b = num;

    // Normalize
    var bhi = b.words[b.length - 1] | 0;
    var bhiBits = this._countBits(bhi);
    shift = 26 - bhiBits;
    if (shift !== 0) {
      b = b.ushln(shift);
      a.iushln(shift);
      bhi = b.words[b.length - 1] | 0;
    }

    // Initialize quotient
    var m = a.length - b.length;
    var q;

    if (mode !== 'mod') {
      q = new BN(null);
      q.length = m + 1;
      q.words = new Array(q.length);
      for (var i = 0; i < q.length; i++) {
        q.words[i] = 0;
      }
    }

    var diff = a.clone()._ishlnsubmul(b, 1, m);
    if (diff.negative === 0) {
      a = diff;
      if (q) {
        q.words[m] = 1;
      }
    }

    for (var j = m - 1; j >= 0; j--) {
      var qj = (a.words[b.length + j] | 0) * 0x4000000 +
        (a.words[b.length + j - 1] | 0);

      // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
      // (0x7ffffff)
      qj = Math.min((qj / bhi) | 0, 0x3ffffff);

      a._ishlnsubmul(b, qj, j);
      while (a.negative !== 0) {
        qj--;
        a.negative = 0;
        a._ishlnsubmul(b, 1, j);
        if (!a.isZero()) {
          a.negative ^= 1;
        }
      }
      if (q) {
        q.words[j] = qj;
      }
    }
    if (q) {
      q.strip();
    }
    a.strip();

    // Denormalize
    if (mode !== 'div' && shift !== 0) {
      a.iushrn(shift);
    }

    return {
      div: q || null,
      mod: a
    };
  };

  // NOTE: 1) `mode` can be set to `mod` to request mod only,
  //       to `div` to request div only, or be absent to
  //       request both div & mod
  //       2) `positive` is true if unsigned mod is requested
  BN.prototype.divmod = function divmod (num, mode, positive) {
    assert(!num.isZero());

    if (this.isZero()) {
      return {
        div: new BN(0),
        mod: new BN(0)
      };
    }

    var div, mod, res;
    if (this.negative !== 0 && num.negative === 0) {
      res = this.neg().divmod(num, mode);

      if (mode !== 'mod') {
        div = res.div.neg();
      }

      if (mode !== 'div') {
        mod = res.mod.neg();
        if (positive && mod.negative !== 0) {
          mod.iadd(num);
        }
      }

      return {
        div: div,
        mod: mod
      };
    }

    if (this.negative === 0 && num.negative !== 0) {
      res = this.divmod(num.neg(), mode);

      if (mode !== 'mod') {
        div = res.div.neg();
      }

      return {
        div: div,
        mod: res.mod
      };
    }

    if ((this.negative & num.negative) !== 0) {
      res = this.neg().divmod(num.neg(), mode);

      if (mode !== 'div') {
        mod = res.mod.neg();
        if (positive && mod.negative !== 0) {
          mod.isub(num);
        }
      }

      return {
        div: res.div,
        mod: mod
      };
    }

    // Both numbers are positive at this point

    // Strip both numbers to approximate shift value
    if (num.length > this.length || this.cmp(num) < 0) {
      return {
        div: new BN(0),
        mod: this
      };
    }

    // Very short reduction
    if (num.length === 1) {
      if (mode === 'div') {
        return {
          div: this.divn(num.words[0]),
          mod: null
        };
      }

      if (mode === 'mod') {
        return {
          div: null,
          mod: new BN(this.modn(num.words[0]))
        };
      }

      return {
        div: this.divn(num.words[0]),
        mod: new BN(this.modn(num.words[0]))
      };
    }

    return this._wordDiv(num, mode);
  };

  // Find `this` / `num`
  BN.prototype.div = function div (num) {
    return this.divmod(num, 'div', false).div;
  };

  // Find `this` % `num`
  BN.prototype.mod = function mod (num) {
    return this.divmod(num, 'mod', false).mod;
  };

  BN.prototype.umod = function umod (num) {
    return this.divmod(num, 'mod', true).mod;
  };

  // Find Round(`this` / `num`)
  BN.prototype.divRound = function divRound (num) {
    var dm = this.divmod(num);

    // Fast case - exact division
    if (dm.mod.isZero()) return dm.div;

    var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;

    var half = num.ushrn(1);
    var r2 = num.andln(1);
    var cmp = mod.cmp(half);

    // Round down
    if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;

    // Round up
    return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
  };

  BN.prototype.modn = function modn (num) {
    assert(num <= 0x3ffffff);
    var p = (1 << 26) % num;

    var acc = 0;
    for (var i = this.length - 1; i >= 0; i--) {
      acc = (p * acc + (this.words[i] | 0)) % num;
    }

    return acc;
  };

  // In-place division by number
  BN.prototype.idivn = function idivn (num) {
    assert(num <= 0x3ffffff);

    var carry = 0;
    for (var i = this.length - 1; i >= 0; i--) {
      var w = (this.words[i] | 0) + carry * 0x4000000;
      this.words[i] = (w / num) | 0;
      carry = w % num;
    }

    return this.strip();
  };

  BN.prototype.divn = function divn (num) {
    return this.clone().idivn(num);
  };

  BN.prototype.egcd = function egcd (p) {
    assert(p.negative === 0);
    assert(!p.isZero());

    var x = this;
    var y = p.clone();

    if (x.negative !== 0) {
      x = x.umod(p);
    } else {
      x = x.clone();
    }

    // A * x + B * y = x
    var A = new BN(1);
    var B = new BN(0);

    // C * x + D * y = y
    var C = new BN(0);
    var D = new BN(1);

    var g = 0;

    while (x.isEven() && y.isEven()) {
      x.iushrn(1);
      y.iushrn(1);
      ++g;
    }

    var yp = y.clone();
    var xp = x.clone();

    while (!x.isZero()) {
      for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
      if (i > 0) {
        x.iushrn(i);
        while (i-- > 0) {
          if (A.isOdd() || B.isOdd()) {
            A.iadd(yp);
            B.isub(xp);
          }

          A.iushrn(1);
          B.iushrn(1);
        }
      }

      for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
      if (j > 0) {
        y.iushrn(j);
        while (j-- > 0) {
          if (C.isOdd() || D.isOdd()) {
            C.iadd(yp);
            D.isub(xp);
          }

          C.iushrn(1);
          D.iushrn(1);
        }
      }

      if (x.cmp(y) >= 0) {
        x.isub(y);
        A.isub(C);
        B.isub(D);
      } else {
        y.isub(x);
        C.isub(A);
        D.isub(B);
      }
    }

    return {
      a: C,
      b: D,
      gcd: y.iushln(g)
    };
  };

  // This is reduced incarnation of the binary EEA
  // above, designated to invert members of the
  // _prime_ fields F(p) at a maximal speed
  BN.prototype._invmp = function _invmp (p) {
    assert(p.negative === 0);
    assert(!p.isZero());

    var a = this;
    var b = p.clone();

    if (a.negative !== 0) {
      a = a.umod(p);
    } else {
      a = a.clone();
    }

    var x1 = new BN(1);
    var x2 = new BN(0);

    var delta = b.clone();

    while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
      for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
      if (i > 0) {
        a.iushrn(i);
        while (i-- > 0) {
          if (x1.isOdd()) {
            x1.iadd(delta);
          }

          x1.iushrn(1);
        }
      }

      for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
      if (j > 0) {
        b.iushrn(j);
        while (j-- > 0) {
          if (x2.isOdd()) {
            x2.iadd(delta);
          }

          x2.iushrn(1);
        }
      }

      if (a.cmp(b) >= 0) {
        a.isub(b);
        x1.isub(x2);
      } else {
        b.isub(a);
        x2.isub(x1);
      }
    }

    var res;
    if (a.cmpn(1) === 0) {
      res = x1;
    } else {
      res = x2;
    }

    if (res.cmpn(0) < 0) {
      res.iadd(p);
    }

    return res;
  };

  BN.prototype.gcd = function gcd (num) {
    if (this.isZero()) return num.abs();
    if (num.isZero()) return this.abs();

    var a = this.clone();
    var b = num.clone();
    a.negative = 0;
    b.negative = 0;

    // Remove common factor of two
    for (var shift = 0; a.isEven() && b.isEven(); shift++) {
      a.iushrn(1);
      b.iushrn(1);
    }

    do {
      while (a.isEven()) {
        a.iushrn(1);
      }
      while (b.isEven()) {
        b.iushrn(1);
      }

      var r = a.cmp(b);
      if (r < 0) {
        // Swap `a` and `b` to make `a` always bigger than `b`
        var t = a;
        a = b;
        b = t;
      } else if (r === 0 || b.cmpn(1) === 0) {
        break;
      }

      a.isub(b);
    } while (true);

    return b.iushln(shift);
  };

  // Invert number in the field F(num)
  BN.prototype.invm = function invm (num) {
    return this.egcd(num).a.umod(num);
  };

  BN.prototype.isEven = function isEven () {
    return (this.words[0] & 1) === 0;
  };

  BN.prototype.isOdd = function isOdd () {
    return (this.words[0] & 1) === 1;
  };

  // And first word and num
  BN.prototype.andln = function andln (num) {
    return this.words[0] & num;
  };

  // Increment at the bit position in-line
  BN.prototype.bincn = function bincn (bit) {
    assert(typeof bit === 'number');
    var r = bit % 26;
    var s = (bit - r) / 26;
    var q = 1 << r;

    // Fast case: bit is much higher than all existing words
    if (this.length <= s) {
      this._expand(s + 1);
      this.words[s] |= q;
      return this;
    }

    // Add bit and propagate, if needed
    var carry = q;
    for (var i = s; carry !== 0 && i < this.length; i++) {
      var w = this.words[i] | 0;
      w += carry;
      carry = w >>> 26;
      w &= 0x3ffffff;
      this.words[i] = w;
    }
    if (carry !== 0) {
      this.words[i] = carry;
      this.length++;
    }
    return this;
  };

  BN.prototype.isZero = function isZero () {
    return this.length === 1 && this.words[0] === 0;
  };

  BN.prototype.cmpn = function cmpn (num) {
    var negative = num < 0;

    if (this.negative !== 0 && !negative) return -1;
    if (this.negative === 0 && negative) return 1;

    this.strip();

    var res;
    if (this.length > 1) {
      res = 1;
    } else {
      if (negative) {
        num = -num;
      }

      assert(num <= 0x3ffffff, 'Number is too big');

      var w = this.words[0] | 0;
      res = w === num ? 0 : w < num ? -1 : 1;
    }
    if (this.negative !== 0) return -res | 0;
    return res;
  };

  // Compare two numbers and return:
  // 1 - if `this` > `num`
  // 0 - if `this` == `num`
  // -1 - if `this` < `num`
  BN.prototype.cmp = function cmp (num) {
    if (this.negative !== 0 && num.negative === 0) return -1;
    if (this.negative === 0 && num.negative !== 0) return 1;

    var res = this.ucmp(num);
    if (this.negative !== 0) return -res | 0;
    return res;
  };

  // Unsigned comparison
  BN.prototype.ucmp = function ucmp (num) {
    // At this point both numbers have the same sign
    if (this.length > num.length) return 1;
    if (this.length < num.length) return -1;

    var res = 0;
    for (var i = this.length - 1; i >= 0; i--) {
      var a = this.words[i] | 0;
      var b = num.words[i] | 0;

      if (a === b) continue;
      if (a < b) {
        res = -1;
      } else if (a > b) {
        res = 1;
      }
      break;
    }
    return res;
  };

  BN.prototype.gtn = function gtn (num) {
    return this.cmpn(num) === 1;
  };

  BN.prototype.gt = function gt (num) {
    return this.cmp(num) === 1;
  };

  BN.prototype.gten = function gten (num) {
    return this.cmpn(num) >= 0;
  };

  BN.prototype.gte = function gte (num) {
    return this.cmp(num) >= 0;
  };

  BN.prototype.ltn = function ltn (num) {
    return this.cmpn(num) === -1;
  };

  BN.prototype.lt = function lt (num) {
    return this.cmp(num) === -1;
  };

  BN.prototype.lten = function lten (num) {
    return this.cmpn(num) <= 0;
  };

  BN.prototype.lte = function lte (num) {
    return this.cmp(num) <= 0;
  };

  BN.prototype.eqn = function eqn (num) {
    return this.cmpn(num) === 0;
  };

  BN.prototype.eq = function eq (num) {
    return this.cmp(num) === 0;
  };

  //
  // A reduce context, could be using montgomery or something better, depending
  // on the `m` itself.
  //
  BN.red = function red (num) {
    return new Red(num);
  };

  BN.prototype.toRed = function toRed (ctx) {
    assert(!this.red, 'Already a number in reduction context');
    assert(this.negative === 0, 'red works only with positives');
    return ctx.convertTo(this)._forceRed(ctx);
  };

  BN.prototype.fromRed = function fromRed () {
    assert(this.red, 'fromRed works only with numbers in reduction context');
    return this.red.convertFrom(this);
  };

  BN.prototype._forceRed = function _forceRed (ctx) {
    this.red = ctx;
    return this;
  };

  BN.prototype.forceRed = function forceRed (ctx) {
    assert(!this.red, 'Already a number in reduction context');
    return this._forceRed(ctx);
  };

  BN.prototype.redAdd = function redAdd (num) {
    assert(this.red, 'redAdd works only with red numbers');
    return this.red.add(this, num);
  };

  BN.prototype.redIAdd = function redIAdd (num) {
    assert(this.red, 'redIAdd works only with red numbers');
    return this.red.iadd(this, num);
  };

  BN.prototype.redSub = function redSub (num) {
    assert(this.red, 'redSub works only with red numbers');
    return this.red.sub(this, num);
  };

  BN.prototype.redISub = function redISub (num) {
    assert(this.red, 'redISub works only with red numbers');
    return this.red.isub(this, num);
  };

  BN.prototype.redShl = function redShl (num) {
    assert(this.red, 'redShl works only with red numbers');
    return this.red.shl(this, num);
  };

  BN.prototype.redMul = function redMul (num) {
    assert(this.red, 'redMul works only with red numbers');
    this.red._verify2(this, num);
    return this.red.mul(this, num);
  };

  BN.prototype.redIMul = function redIMul (num) {
    assert(this.red, 'redMul works only with red numbers');
    this.red._verify2(this, num);
    return this.red.imul(this, num);
  };

  BN.prototype.redSqr = function redSqr () {
    assert(this.red, 'redSqr works only with red numbers');
    this.red._verify1(this);
    return this.red.sqr(this);
  };

  BN.prototype.redISqr = function redISqr () {
    assert(this.red, 'redISqr works only with red numbers');
    this.red._verify1(this);
    return this.red.isqr(this);
  };

  // Square root over p
  BN.prototype.redSqrt = function redSqrt () {
    assert(this.red, 'redSqrt works only with red numbers');
    this.red._verify1(this);
    return this.red.sqrt(this);
  };

  BN.prototype.redInvm = function redInvm () {
    assert(this.red, 'redInvm works only with red numbers');
    this.red._verify1(this);
    return this.red.invm(this);
  };

  // Return negative clone of `this` % `red modulo`
  BN.prototype.redNeg = function redNeg () {
    assert(this.red, 'redNeg works only with red numbers');
    this.red._verify1(this);
    return this.red.neg(this);
  };

  BN.prototype.redPow = function redPow (num) {
    assert(this.red && !num.red, 'redPow(normalNum)');
    this.red._verify1(this);
    return this.red.pow(this, num);
  };

  // Prime numbers with efficient reduction
  var primes = {
    k256: null,
    p224: null,
    p192: null,
    p25519: null
  };

  // Pseudo-Mersenne prime
  function MPrime (name, p) {
    // P = 2 ^ N - K
    this.name = name;
    this.p = new BN(p, 16);
    this.n = this.p.bitLength();
    this.k = new BN(1).iushln(this.n).isub(this.p);

    this.tmp = this._tmp();
  }

  MPrime.prototype._tmp = function _tmp () {
    var tmp = new BN(null);
    tmp.words = new Array(Math.ceil(this.n / 13));
    return tmp;
  };

  MPrime.prototype.ireduce = function ireduce (num) {
    // Assumes that `num` is less than `P^2`
    // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
    var r = num;
    var rlen;

    do {
      this.split(r, this.tmp);
      r = this.imulK(r);
      r = r.iadd(this.tmp);
      rlen = r.bitLength();
    } while (rlen > this.n);

    var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
    if (cmp === 0) {
      r.words[0] = 0;
      r.length = 1;
    } else if (cmp > 0) {
      r.isub(this.p);
    } else {
      r.strip();
    }

    return r;
  };

  MPrime.prototype.split = function split (input, out) {
    input.iushrn(this.n, 0, out);
  };

  MPrime.prototype.imulK = function imulK (num) {
    return num.imul(this.k);
  };

  function K256 () {
    MPrime.call(
      this,
      'k256',
      'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
  }
  inherits(K256, MPrime);

  K256.prototype.split = function split (input, output) {
    // 256 = 9 * 26 + 22
    var mask = 0x3fffff;

    var outLen = Math.min(input.length, 9);
    for (var i = 0; i < outLen; i++) {
      output.words[i] = input.words[i];
    }
    output.length = outLen;

    if (input.length <= 9) {
      input.words[0] = 0;
      input.length = 1;
      return;
    }

    // Shift by 9 limbs
    var prev = input.words[9];
    output.words[output.length++] = prev & mask;

    for (i = 10; i < input.length; i++) {
      var next = input.words[i] | 0;
      input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
      prev = next;
    }
    prev >>>= 22;
    input.words[i - 10] = prev;
    if (prev === 0 && input.length > 10) {
      input.length -= 10;
    } else {
      input.length -= 9;
    }
  };

  K256.prototype.imulK = function imulK (num) {
    // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
    num.words[num.length] = 0;
    num.words[num.length + 1] = 0;
    num.length += 2;

    // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
    var lo = 0;
    for (var i = 0; i < num.length; i++) {
      var w = num.words[i] | 0;
      lo += w * 0x3d1;
      num.words[i] = lo & 0x3ffffff;
      lo = w * 0x40 + ((lo / 0x4000000) | 0);
    }

    // Fast length reduction
    if (num.words[num.length - 1] === 0) {
      num.length--;
      if (num.words[num.length - 1] === 0) {
        num.length--;
      }
    }
    return num;
  };

  function P224 () {
    MPrime.call(
      this,
      'p224',
      'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
  }
  inherits(P224, MPrime);

  function P192 () {
    MPrime.call(
      this,
      'p192',
      'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
  }
  inherits(P192, MPrime);

  function P25519 () {
    // 2 ^ 255 - 19
    MPrime.call(
      this,
      '25519',
      '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
  }
  inherits(P25519, MPrime);

  P25519.prototype.imulK = function imulK (num) {
    // K = 0x13
    var carry = 0;
    for (var i = 0; i < num.length; i++) {
      var hi = (num.words[i] | 0) * 0x13 + carry;
      var lo = hi & 0x3ffffff;
      hi >>>= 26;

      num.words[i] = lo;
      carry = hi;
    }
    if (carry !== 0) {
      num.words[num.length++] = carry;
    }
    return num;
  };

  // Exported mostly for testing purposes, use plain name instead
  BN._prime = function prime (name) {
    // Cached version of prime
    if (primes[name]) return primes[name];

    var prime;
    if (name === 'k256') {
      prime = new K256();
    } else if (name === 'p224') {
      prime = new P224();
    } else if (name === 'p192') {
      prime = new P192();
    } else if (name === 'p25519') {
      prime = new P25519();
    } else {
      throw new Error('Unknown prime ' + name);
    }
    primes[name] = prime;

    return prime;
  };

  //
  // Base reduction engine
  //
  function Red (m) {
    if (typeof m === 'string') {
      var prime = BN._prime(m);
      this.m = prime.p;
      this.prime = prime;
    } else {
      assert(m.gtn(1), 'modulus must be greater than 1');
      this.m = m;
      this.prime = null;
    }
  }

  Red.prototype._verify1 = function _verify1 (a) {
    assert(a.negative === 0, 'red works only with positives');
    assert(a.red, 'red works only with red numbers');
  };

  Red.prototype._verify2 = function _verify2 (a, b) {
    assert((a.negative | b.negative) === 0, 'red works only with positives');
    assert(a.red && a.red === b.red,
      'red works only with red numbers');
  };

  Red.prototype.imod = function imod (a) {
    if (this.prime) return this.prime.ireduce(a)._forceRed(this);
    return a.umod(this.m)._forceRed(this);
  };

  Red.prototype.neg = function neg (a) {
    if (a.isZero()) {
      return a.clone();
    }

    return this.m.sub(a)._forceRed(this);
  };

  Red.prototype.add = function add (a, b) {
    this._verify2(a, b);

    var res = a.add(b);
    if (res.cmp(this.m) >= 0) {
      res.isub(this.m);
    }
    return res._forceRed(this);
  };

  Red.prototype.iadd = function iadd (a, b) {
    this._verify2(a, b);

    var res = a.iadd(b);
    if (res.cmp(this.m) >= 0) {
      res.isub(this.m);
    }
    return res;
  };

  Red.prototype.sub = function sub (a, b) {
    this._verify2(a, b);

    var res = a.sub(b);
    if (res.cmpn(0) < 0) {
      res.iadd(this.m);
    }
    return res._forceRed(this);
  };

  Red.prototype.isub = function isub (a, b) {
    this._verify2(a, b);

    var res = a.isub(b);
    if (res.cmpn(0) < 0) {
      res.iadd(this.m);
    }
    return res;
  };

  Red.prototype.shl = function shl (a, num) {
    this._verify1(a);
    return this.imod(a.ushln(num));
  };

  Red.prototype.imul = function imul (a, b) {
    this._verify2(a, b);
    return this.imod(a.imul(b));
  };

  Red.prototype.mul = function mul (a, b) {
    this._verify2(a, b);
    return this.imod(a.mul(b));
  };

  Red.prototype.isqr = function isqr (a) {
    return this.imul(a, a.clone());
  };

  Red.prototype.sqr = function sqr (a) {
    return this.mul(a, a);
  };

  Red.prototype.sqrt = function sqrt (a) {
    if (a.isZero()) return a.clone();

    var mod3 = this.m.andln(3);
    assert(mod3 % 2 === 1);

    // Fast case
    if (mod3 === 3) {
      var pow = this.m.add(new BN(1)).iushrn(2);
      return this.pow(a, pow);
    }

    // Tonelli-Shanks algorithm (Totally unoptimized and slow)
    //
    // Find Q and S, that Q * 2 ^ S = (P - 1)
    var q = this.m.subn(1);
    var s = 0;
    while (!q.isZero() && q.andln(1) === 0) {
      s++;
      q.iushrn(1);
    }
    assert(!q.isZero());

    var one = new BN(1).toRed(this);
    var nOne = one.redNeg();

    // Find quadratic non-residue
    // NOTE: Max is such because of generalized Riemann hypothesis.
    var lpow = this.m.subn(1).iushrn(1);
    var z = this.m.bitLength();
    z = new BN(2 * z * z).toRed(this);

    while (this.pow(z, lpow).cmp(nOne) !== 0) {
      z.redIAdd(nOne);
    }

    var c = this.pow(z, q);
    var r = this.pow(a, q.addn(1).iushrn(1));
    var t = this.pow(a, q);
    var m = s;
    while (t.cmp(one) !== 0) {
      var tmp = t;
      for (var i = 0; tmp.cmp(one) !== 0; i++) {
        tmp = tmp.redSqr();
      }
      assert(i < m);
      var b = this.pow(c, new BN(1).iushln(m - i - 1));

      r = r.redMul(b);
      c = b.redSqr();
      t = t.redMul(c);
      m = i;
    }

    return r;
  };

  Red.prototype.invm = function invm (a) {
    var inv = a._invmp(this.m);
    if (inv.negative !== 0) {
      inv.negative = 0;
      return this.imod(inv).redNeg();
    } else {
      return this.imod(inv);
    }
  };

  Red.prototype.pow = function pow (a, num) {
    if (num.isZero()) return new BN(1).toRed(this);
    if (num.cmpn(1) === 0) return a.clone();

    var windowSize = 4;
    var wnd = new Array(1 << windowSize);
    wnd[0] = new BN(1).toRed(this);
    wnd[1] = a;
    for (var i = 2; i < wnd.length; i++) {
      wnd[i] = this.mul(wnd[i - 1], a);
    }

    var res = wnd[0];
    var current = 0;
    var currentLen = 0;
    var start = num.bitLength() % 26;
    if (start === 0) {
      start = 26;
    }

    for (i = num.length - 1; i >= 0; i--) {
      var word = num.words[i];
      for (var j = start - 1; j >= 0; j--) {
        var bit = (word >> j) & 1;
        if (res !== wnd[0]) {
          res = this.sqr(res);
        }

        if (bit === 0 && current === 0) {
          currentLen = 0;
          continue;
        }

        current <<= 1;
        current |= bit;
        currentLen++;
        if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;

        res = this.mul(res, wnd[current]);
        currentLen = 0;
        current = 0;
      }
      start = 26;
    }

    return res;
  };

  Red.prototype.convertTo = function convertTo (num) {
    var r = num.umod(this.m);

    return r === num ? r.clone() : r;
  };

  Red.prototype.convertFrom = function convertFrom (num) {
    var res = num.clone();
    res.red = null;
    return res;
  };

  //
  // Montgomery method engine
  //

  BN.mont = function mont (num) {
    return new Mont(num);
  };

  function Mont (m) {
    Red.call(this, m);

    this.shift = this.m.bitLength();
    if (this.shift % 26 !== 0) {
      this.shift += 26 - (this.shift % 26);
    }

    this.r = new BN(1).iushln(this.shift);
    this.r2 = this.imod(this.r.sqr());
    this.rinv = this.r._invmp(this.m);

    this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
    this.minv = this.minv.umod(this.r);
    this.minv = this.r.sub(this.minv);
  }
  inherits(Mont, Red);

  Mont.prototype.convertTo = function convertTo (num) {
    return this.imod(num.ushln(this.shift));
  };

  Mont.prototype.convertFrom = function convertFrom (num) {
    var r = this.imod(num.mul(this.rinv));
    r.red = null;
    return r;
  };

  Mont.prototype.imul = function imul (a, b) {
    if (a.isZero() || b.isZero()) {
      a.words[0] = 0;
      a.length = 1;
      return a;
    }

    var t = a.imul(b);
    var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
    var u = t.isub(c).iushrn(this.shift);
    var res = u;

    if (u.cmp(this.m) >= 0) {
      res = u.isub(this.m);
    } else if (u.cmpn(0) < 0) {
      res = u.iadd(this.m);
    }

    return res._forceRed(this);
  };

  Mont.prototype.mul = function mul (a, b) {
    if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);

    var t = a.mul(b);
    var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
    var u = t.isub(c).iushrn(this.shift);
    var res = u;
    if (u.cmp(this.m) >= 0) {
      res = u.isub(this.m);
    } else if (u.cmpn(0) < 0) {
      res = u.iadd(this.m);
    }

    return res._forceRed(this);
  };

  Mont.prototype.invm = function invm (a) {
    // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
    var res = this.imod(a._invmp(this.m).mul(this.r2));
    return res._forceRed(this);
  };
})(typeof module === 'undefined' || module, this);

},{"buffer":91}],83:[function(_dereq_,module,exports){
'use strict'

module.exports = boundary

function boundary (cells) {
  var i, j, k
  var n = cells.length
  var sz = 0
  for (i = 0; i < n; ++i) {
    sz += cells[i].length
  }
  var result = new Array(sz)
  var ptr = 0
  for (i = 0; i < n; ++i) {
    var c = cells[i]
    var d = c.length
    for (j = 0; j < d; ++j) {
      var b = result[ptr++] = new Array(d - 1)
      var p = 0
      for (k = 0; k < d; ++k) {
        if (k === j) {
          continue
        }
        b[p++] = c[k]
      }
      if (j & 1) {
        var tmp = b[1]
        b[1] = b[0]
        b[0] = tmp
      }
    }
  }
  return result
}

},{}],84:[function(_dereq_,module,exports){
'use strict'

module.exports = boxIntersectWrapper

var pool = _dereq_('typedarray-pool')
var sweep = _dereq_('./lib/sweep')
var boxIntersectIter = _dereq_('./lib/intersect')

function boxEmpty(d, box) {
  for(var j=0; j<d; ++j) {
    if(!(box[j] <= box[j+d])) {
      return true
    }
  }
  return false
}

//Unpack boxes into a flat typed array, remove empty boxes
function convertBoxes(boxes, d, data, ids) {
  var ptr = 0
  var count = 0
  for(var i=0, n=boxes.length; i<n; ++i) {
    var b = boxes[i]
    if(boxEmpty(d, b)) {
      continue
    }
    for(var j=0; j<2*d; ++j) {
      data[ptr++] = b[j]
    }
    ids[count++] = i
  }
  return count
}

//Perform type conversions, check bounds
function boxIntersect(red, blue, visit, full) {
  var n = red.length
  var m = blue.length

  //If either array is empty, then we can skip this whole thing
  if(n <= 0 || m <= 0) {
    return
  }

  //Compute dimension, if it is 0 then we skip
  var d = (red[0].length)>>>1
  if(d <= 0) {
    return
  }

  var retval

  //Convert red boxes
  var redList  = pool.mallocDouble(2*d*n)
  var redIds   = pool.mallocInt32(n)
  n = convertBoxes(red, d, redList, redIds)

  if(n > 0) {
    if(d === 1 && full) {
      //Special case: 1d complete
      sweep.init(n)
      retval = sweep.sweepComplete(
        d, visit, 
        0, n, redList, redIds,
        0, n, redList, redIds)
    } else {

      //Convert blue boxes
      var blueList = pool.mallocDouble(2*d*m)
      var blueIds  = pool.mallocInt32(m)
      m = convertBoxes(blue, d, blueList, blueIds)

      if(m > 0) {
        sweep.init(n+m)

        if(d === 1) {
          //Special case: 1d bipartite
          retval = sweep.sweepBipartite(
            d, visit, 
            0, n, redList,  redIds,
            0, m, blueList, blueIds)
        } else {
          //General case:  d>1
          retval = boxIntersectIter(
            d, visit,    full,
            n, redList,  redIds,
            m, blueList, blueIds)
        }

        pool.free(blueList)
        pool.free(blueIds)
      }
    }

    pool.free(redList)
    pool.free(redIds)
  }

  return retval
}


var RESULT

function appendItem(i,j) {
  RESULT.push([i,j])
}

function intersectFullArray(x) {
  RESULT = []
  boxIntersect(x, x, appendItem, true)
  return RESULT
}

function intersectBipartiteArray(x, y) {
  RESULT = []
  boxIntersect(x, y, appendItem, false)
  return RESULT
}

//User-friendly wrapper, handle full input and no-visitor cases
function boxIntersectWrapper(arg0, arg1, arg2) {
  var result
  switch(arguments.length) {
    case 1:
      return intersectFullArray(arg0)
    case 2:
      if(typeof arg1 === 'function') {
        return boxIntersect(arg0, arg0, arg1, true)
      } else {
        return intersectBipartiteArray(arg0, arg1)
      }
    case 3:
      return boxIntersect(arg0, arg1, arg2, false)
    default:
      throw new Error('box-intersect: Invalid arguments')
  }
}
},{"./lib/intersect":86,"./lib/sweep":90,"typedarray-pool":526}],85:[function(_dereq_,module,exports){
'use strict'

var DIMENSION   = 'd'
var AXIS        = 'ax'
var VISIT       = 'vv'
var FLIP        = 'fp'

var ELEM_SIZE   = 'es'

var RED_START   = 'rs'
var RED_END     = 're'
var RED_BOXES   = 'rb'
var RED_INDEX   = 'ri'
var RED_PTR     = 'rp'

var BLUE_START  = 'bs'
var BLUE_END    = 'be'
var BLUE_BOXES  = 'bb'
var BLUE_INDEX  = 'bi'
var BLUE_PTR    = 'bp'

var RETVAL      = 'rv'

var INNER_LABEL = 'Q'

var ARGS = [
  DIMENSION,
  AXIS,
  VISIT,
  RED_START,
  RED_END,
  RED_BOXES,
  RED_INDEX,
  BLUE_START,
  BLUE_END,
  BLUE_BOXES,
  BLUE_INDEX
]

function generateBruteForce(redMajor, flip, full) {
  var funcName = 'bruteForce' + 
    (redMajor ? 'Red' : 'Blue') + 
    (flip ? 'Flip' : '') +
    (full ? 'Full' : '')

  var code = ['function ', funcName, '(', ARGS.join(), '){',
    'var ', ELEM_SIZE, '=2*', DIMENSION, ';']

  var redLoop = 
    'for(var i=' + RED_START + ',' + RED_PTR + '=' + ELEM_SIZE + '*' + RED_START + ';' +
        'i<' + RED_END +';' +
        '++i,' + RED_PTR + '+=' + ELEM_SIZE + '){' +
        'var x0=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '],' +
            'x1=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '+' + DIMENSION + '],' +
            'xi=' + RED_INDEX + '[i];'

  var blueLoop = 
    'for(var j=' + BLUE_START + ',' + BLUE_PTR + '=' + ELEM_SIZE + '*' + BLUE_START + ';' +
        'j<' + BLUE_END + ';' +
        '++j,' + BLUE_PTR + '+=' + ELEM_SIZE + '){' +
        'var y0=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '],' +
            (full ? 'y1=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '+' + DIMENSION + '],' : '') +
            'yi=' + BLUE_INDEX + '[j];'

  if(redMajor) {
    code.push(redLoop, INNER_LABEL, ':', blueLoop)
  } else {
    code.push(blueLoop, INNER_LABEL, ':', redLoop)
  }

  if(full) {
    code.push('if(y1<x0||x1<y0)continue;')
  } else if(flip) {
    code.push('if(y0<=x0||x1<y0)continue;')
  } else {
    code.push('if(y0<x0||x1<y0)continue;')
  }

  code.push('for(var k='+AXIS+'+1;k<'+DIMENSION+';++k){'+
    'var r0='+RED_BOXES+'[k+'+RED_PTR+'],'+
        'r1='+RED_BOXES+'[k+'+DIMENSION+'+'+RED_PTR+'],'+
        'b0='+BLUE_BOXES+'[k+'+BLUE_PTR+'],'+
        'b1='+BLUE_BOXES+'[k+'+DIMENSION+'+'+BLUE_PTR+'];'+
      'if(r1<b0||b1<r0)continue ' + INNER_LABEL + ';}' +
      'var ' + RETVAL + '=' + VISIT + '(')

  if(flip) {
    code.push('yi,xi')
  } else {
    code.push('xi,yi')
  }

  code.push(');if(' + RETVAL + '!==void 0)return ' + RETVAL + ';}}}')

  return {
    name: funcName, 
    code: code.join('')
  }
}

function bruteForcePlanner(full) {
  var funcName = 'bruteForce' + (full ? 'Full' : 'Partial')
  var prefix = []
  var fargs = ARGS.slice()
  if(!full) {
    fargs.splice(3, 0, FLIP)
  }

  var code = ['function ' + funcName + '(' + fargs.join() + '){']

  function invoke(redMajor, flip) {
    var res = generateBruteForce(redMajor, flip, full)
    prefix.push(res.code)
    code.push('return ' + res.name + '(' + ARGS.join() + ');')
  }

  code.push('if(' + RED_END + '-' + RED_START + '>' +
                    BLUE_END + '-' + BLUE_START + '){')

  if(full) {
    invoke(true, false)
    code.push('}else{')
    invoke(false, false)
  } else {
    code.push('if(' + FLIP + '){')
    invoke(true, true)
    code.push('}else{')
    invoke(true, false)
    code.push('}}else{if(' + FLIP + '){')
    invoke(false, true)
    code.push('}else{')
    invoke(false, false)
    code.push('}')
  }
  code.push('}}return ' + funcName)

  var codeStr = prefix.join('') + code.join('')
  var proc = new Function(codeStr)
  return proc()
}


exports.partial = bruteForcePlanner(false)
exports.full    = bruteForcePlanner(true)
},{}],86:[function(_dereq_,module,exports){
'use strict'

module.exports = boxIntersectIter

var pool = _dereq_('typedarray-pool')
var bits = _dereq_('bit-twiddle')
var bruteForce = _dereq_('./brute')
var bruteForcePartial = bruteForce.partial
var bruteForceFull = bruteForce.full
var sweep = _dereq_('./sweep')
var findMedian = _dereq_('./median')
var genPartition = _dereq_('./partition')

//Twiddle parameters
var BRUTE_FORCE_CUTOFF    = 128       //Cut off for brute force search
var SCAN_CUTOFF           = (1<<22)   //Cut off for two way scan
var SCAN_COMPLETE_CUTOFF  = (1<<22)  

//Partition functions
var partitionInteriorContainsInterval = genPartition(
  '!(lo>=p0)&&!(p1>=hi)', 
  ['p0', 'p1'])

var partitionStartEqual = genPartition(
  'lo===p0',
  ['p0'])

var partitionStartLessThan = genPartition(
  'lo<p0',
  ['p0'])

var partitionEndLessThanEqual = genPartition(
  'hi<=p0',
  ['p0'])

var partitionContainsPoint = genPartition(
  'lo<=p0&&p0<=hi',
  ['p0'])

var partitionContainsPointProper = genPartition(
  'lo<p0&&p0<=hi',
  ['p0'])

//Frame size for iterative loop
var IFRAME_SIZE = 6
var DFRAME_SIZE = 2

//Data for box statck
var INIT_CAPACITY = 1024
var BOX_ISTACK  = pool.mallocInt32(INIT_CAPACITY)
var BOX_DSTACK  = pool.mallocDouble(INIT_CAPACITY)

//Initialize iterative loop queue
function iterInit(d, count) {
  var levels = (8 * bits.log2(count+1) * (d+1))|0
  var maxInts = bits.nextPow2(IFRAME_SIZE*levels)
  if(BOX_ISTACK.length < maxInts) {
    pool.free(BOX_ISTACK)
    BOX_ISTACK = pool.mallocInt32(maxInts)
  }
  var maxDoubles = bits.nextPow2(DFRAME_SIZE*levels)
  if(BOX_DSTACK < maxDoubles) {
    pool.free(BOX_DSTACK)
    BOX_DSTACK = pool.mallocDouble(maxDoubles)
  }
}

//Append item to queue
function iterPush(ptr,
  axis, 
  redStart, redEnd, 
  blueStart, blueEnd, 
  state, 
  lo, hi) {

  var iptr = IFRAME_SIZE * ptr
  BOX_ISTACK[iptr]   = axis
  BOX_ISTACK[iptr+1] = redStart
  BOX_ISTACK[iptr+2] = redEnd
  BOX_ISTACK[iptr+3] = blueStart
  BOX_ISTACK[iptr+4] = blueEnd
  BOX_ISTACK[iptr+5] = state

  var dptr = DFRAME_SIZE * ptr
  BOX_DSTACK[dptr]   = lo
  BOX_DSTACK[dptr+1] = hi
}

//Special case:  Intersect single point with list of intervals
function onePointPartial(
  d, axis, visit, flip,
  redStart, redEnd, red, redIndex,
  blueOffset, blue, blueId) {

  var elemSize = 2 * d
  var bluePtr  = blueOffset * elemSize
  var blueX    = blue[bluePtr + axis]

red_loop:
  for(var i=redStart, redPtr=redStart*elemSize; i<redEnd; ++i, redPtr+=elemSize) {
    var r0 = red[redPtr+axis]
    var r1 = red[redPtr+axis+d]
    if(blueX < r0 || r1 < blueX) {
      continue
    }
    if(flip && blueX === r0) {
      continue
    }
    var redId = redIndex[i]
    for(var j=axis+1; j<d; ++j) {
      var r0 = red[redPtr+j]
      var r1 = red[redPtr+j+d]
      var b0 = blue[bluePtr+j]
      var b1 = blue[bluePtr+j+d]
      if(r1 < b0 || b1 < r0) {
        continue red_loop
      }
    }
    var retval
    if(flip) {
      retval = visit(blueId, redId)
    } else {
      retval = visit(redId, blueId)
    }
    if(retval !== void 0) {
      return retval
    }
  }
}

//Special case:  Intersect one point with list of intervals
function onePointFull(
  d, axis, visit,
  redStart, redEnd, red, redIndex,
  blueOffset, blue, blueId) {

  var elemSize = 2 * d
  var bluePtr  = blueOffset * elemSize
  var blueX    = blue[bluePtr + axis]

red_loop:
  for(var i=redStart, redPtr=redStart*elemSize; i<redEnd; ++i, redPtr+=elemSize) {
    var redId = redIndex[i]
    if(redId === blueId) {
      continue
    }
    var r0 = red[redPtr+axis]
    var r1 = red[redPtr+axis+d]
    if(blueX < r0 || r1 < blueX) {
      continue
    }
    for(var j=axis+1; j<d; ++j) {
      var r0 = red[redPtr+j]
      var r1 = red[redPtr+j+d]
      var b0 = blue[bluePtr+j]
      var b1 = blue[bluePtr+j+d]
      if(r1 < b0 || b1 < r0) {
        continue red_loop
      }
    }
    var retval = visit(redId, blueId)
    if(retval !== void 0) {
      return retval
    }
  }
}

//The main box intersection routine
function boxIntersectIter(
  d, visit, initFull,
  xSize, xBoxes, xIndex,
  ySize, yBoxes, yIndex) {

  //Reserve memory for stack
  iterInit(d, xSize + ySize)

  var top  = 0
  var elemSize = 2 * d
  var retval

  iterPush(top++,
      0,
      0, xSize,
      0, ySize,
      initFull ? 16 : 0, 
      -Infinity, Infinity)
  if(!initFull) {
    iterPush(top++,
      0,
      0, ySize,
      0, xSize,
      1, 
      -Infinity, Infinity)
  }

  while(top > 0) {
    top  -= 1

    var iptr = top * IFRAME_SIZE
    var axis      = BOX_ISTACK[iptr]
    var redStart  = BOX_ISTACK[iptr+1]
    var redEnd    = BOX_ISTACK[iptr+2]
    var blueStart = BOX_ISTACK[iptr+3]
    var blueEnd   = BOX_ISTACK[iptr+4]
    var state     = BOX_ISTACK[iptr+5]

    var dptr = top * DFRAME_SIZE
    var lo        = BOX_DSTACK[dptr]
    var hi        = BOX_DSTACK[dptr+1]

    //Unpack state info
    var flip      = (state & 1)
    var full      = !!(state & 16)

    //Unpack indices
    var red       = xBoxes
    var redIndex  = xIndex
    var blue      = yBoxes
    var blueIndex = yIndex
    if(flip) {
      red         = yBoxes
      redIndex    = yIndex
      blue        = xBoxes
      blueIndex   = xIndex
    }

    if(state & 2) {
      redEnd = partitionStartLessThan(
        d, axis,
        redStart, redEnd, red, redIndex,
        hi)
      if(redStart >= redEnd) {
        continue
      }
    }
    if(state & 4) {
      redStart = partitionEndLessThanEqual(
        d, axis,
        redStart, redEnd, red, redIndex,
        lo)
      if(redStart >= redEnd) {
        continue
      }
    }
    
    var redCount  = redEnd  - redStart
    var blueCount = blueEnd - blueStart

    if(full) {
      if(d * redCount * (redCount + blueCount) < SCAN_COMPLETE_CUTOFF) {
        retval = sweep.scanComplete(
          d, axis, visit, 
          redStart, redEnd, red, redIndex,
          blueStart, blueEnd, blue, blueIndex)
        if(retval !== void 0) {
          return retval
        }
        continue
      }
    } else {
      if(d * Math.min(redCount, blueCount) < BRUTE_FORCE_CUTOFF) {
        //If input small, then use brute force
        retval = bruteForcePartial(
            d, axis, visit, flip,
            redStart,  redEnd,  red,  redIndex,
            blueStart, blueEnd, blue, blueIndex)
        if(retval !== void 0) {
          return retval
        }
        continue
      } else if(d * redCount * blueCount < SCAN_CUTOFF) {
        //If input medium sized, then use sweep and prune
        retval = sweep.scanBipartite(
          d, axis, visit, flip, 
          redStart, redEnd, red, redIndex,
          blueStart, blueEnd, blue, blueIndex)
        if(retval !== void 0) {
          return retval
        }
        continue
      }
    }
    
    //First, find all red intervals whose interior contains (lo,hi)
    var red0 = partitionInteriorContainsInterval(
      d, axis, 
      redStart, redEnd, red, redIndex,
      lo, hi)

    //Lower dimensional case
    if(redStart < red0) {

      if(d * (red0 - redStart) < BRUTE_FORCE_CUTOFF) {
        //Special case for small inputs: use brute force
        retval = bruteForceFull(
          d, axis+1, visit,
          redStart, red0, red, redIndex,
          blueStart, blueEnd, blue, blueIndex)
        if(retval !== void 0) {
          return retval
        }
      } else if(axis === d-2) {
        if(flip) {
          retval = sweep.sweepBipartite(
            d, visit,
            blueStart, blueEnd, blue, blueIndex,
            redStart, red0, red, redIndex)
        } else {
          retval = sweep.sweepBipartite(
            d, visit,
            redStart, red0, red, redIndex,
            blueStart, blueEnd, blue, blueIndex)
        }
        if(retval !== void 0) {
          return retval
        }
      } else {
        iterPush(top++,
          axis+1,
          redStart, red0,
          blueStart, blueEnd,
          flip,
          -Infinity, Infinity)
        iterPush(top++,
          axis+1,
          blueStart, blueEnd,
          redStart, red0,
          flip^1,
          -Infinity, Infinity)
      }
    }

    //Divide and conquer phase
    if(red0 < redEnd) {

      //Cut blue into 3 parts:
      //
      //  Points < mid point
      //  Points = mid point
      //  Points > mid point
      //
      var blue0 = findMedian(
        d, axis, 
        blueStart, blueEnd, blue, blueIndex)
      var mid = blue[elemSize * blue0 + axis]
      var blue1 = partitionStartEqual(
        d, axis,
        blue0, blueEnd, blue, blueIndex,
        mid)

      //Right case
      if(blue1 < blueEnd) {
        iterPush(top++,
          axis,
          red0, redEnd,
          blue1, blueEnd,
          (flip|4) + (full ? 16 : 0),
          mid, hi)
      }

      //Left case
      if(blueStart < blue0) {
        iterPush(top++,
          axis,
          red0, redEnd,
          blueStart, blue0,
          (flip|2) + (full ? 16 : 0),
          lo, mid)
      }

      //Center case (the hard part)
      if(blue0 + 1 === blue1) {
        //Optimization: Range with exactly 1 point, use a brute force scan
        if(full) {
          retval = onePointFull(
            d, axis, visit,
            red0, redEnd, red, redIndex,
            blue0, blue, blueIndex[blue0])
        } else {
          retval = onePointPartial(
            d, axis, visit, flip,
            red0, redEnd, red, redIndex,
            blue0, blue, blueIndex[blue0])
        }
        if(retval !== void 0) {
          return retval
        }
      } else if(blue0 < blue1) {
        var red1
        if(full) {
          //If full intersection, need to handle special case
          red1 = partitionContainsPoint(
            d, axis,
            red0, redEnd, red, redIndex,
            mid)
          if(red0 < red1) {
            var redX = partitionStartEqual(
              d, axis,
              red0, red1, red, redIndex,
              mid)
            if(axis === d-2) {
              //Degenerate sweep intersection:
              //  [red0, redX] with [blue0, blue1]
              if(red0 < redX) {
                retval = sweep.sweepComplete(
                  d, visit,
                  red0, redX, red, redIndex,
                  blue0, blue1, blue, blueIndex)
                if(retval !== void 0) {
                  return retval
                }
              }

              //Normal sweep intersection:
              //  [redX, red1] with [blue0, blue1]
              if(redX < red1) {
                retval = sweep.sweepBipartite(
                  d, visit,
                  redX, red1, red, redIndex,
                  blue0, blue1, blue, blueIndex)
                if(retval !== void 0) {
                  return retval
                }
              }
            } else {
              if(red0 < redX) {
                iterPush(top++,
                  axis+1,
                  red0, redX,
                  blue0, blue1,
                  16,
                  -Infinity, Infinity)
              }
              if(redX < red1) {
                iterPush(top++,
                  axis+1,
                  redX, red1,
                  blue0, blue1,
                  0,
                  -Infinity, Infinity)
                iterPush(top++,
                  axis+1,
                  blue0, blue1,
                  redX, red1,
                  1,
                  -Infinity, Infinity)
              }
            }
          }
        } else {
          if(flip) {
            red1 = partitionContainsPointProper(
              d, axis,
              red0, redEnd, red, redIndex,
              mid)
          } else {
            red1 = partitionContainsPoint(
              d, axis,
              red0, redEnd, red, redIndex,
              mid)
          }
          if(red0 < red1) {
            if(axis === d-2) {
              if(flip) {
                retval = sweep.sweepBipartite(
                  d, visit,
                  blue0, blue1, blue, blueIndex,
                  red0, red1, red, redIndex)
              } else {
                retval = sweep.sweepBipartite(
                  d, visit,
                  red0, red1, red, redIndex,
                  blue0, blue1, blue, blueIndex)
              }
            } else {
              iterPush(top++,
                axis+1,
                red0, red1,
                blue0, blue1,
                flip,
                -Infinity, Infinity)
              iterPush(top++,
                axis+1,
                blue0, blue1,
                red0, red1,
                flip^1,
                -Infinity, Infinity)
            }
          }
        }
      }
    }
  }
}
},{"./brute":85,"./median":87,"./partition":88,"./sweep":90,"bit-twiddle":80,"typedarray-pool":526}],87:[function(_dereq_,module,exports){
'use strict'

module.exports = findMedian

var genPartition = _dereq_('./partition')

var partitionStartLessThan = genPartition('lo<p0', ['p0'])

var PARTITION_THRESHOLD = 8   //Cut off for using insertion sort in findMedian

//Base case for median finding:  Use insertion sort
function insertionSort(d, axis, start, end, boxes, ids) {
  var elemSize = 2 * d
  var boxPtr = elemSize * (start+1) + axis
  for(var i=start+1; i<end; ++i, boxPtr+=elemSize) {
    var x = boxes[boxPtr]
    for(var j=i, ptr=elemSize*(i-1); 
        j>start && boxes[ptr+axis] > x; 
        --j, ptr-=elemSize) {
      //Swap
      var aPtr = ptr
      var bPtr = ptr+elemSize
      for(var k=0; k<elemSize; ++k, ++aPtr, ++bPtr) {
        var y = boxes[aPtr]
        boxes[aPtr] = boxes[bPtr]
        boxes[bPtr] = y
      }
      var tmp = ids[j]
      ids[j] = ids[j-1]
      ids[j-1] = tmp
    }
  }
}

//Find median using quick select algorithm
//  takes O(n) time with high probability
function findMedian(d, axis, start, end, boxes, ids) {
  if(end <= start+1) {
    return start
  }

  var lo       = start
  var hi       = end
  var mid      = ((end + start) >>> 1)
  var elemSize = 2*d
  var pivot    = mid
  var value    = boxes[elemSize*mid+axis]
  
  while(lo < hi) {
    if(hi - lo < PARTITION_THRESHOLD) {
      insertionSort(d, axis, lo, hi, boxes, ids)
      value = boxes[elemSize*mid+axis]
      break
    }
    
    //Select pivot using median-of-3
    var count  = hi - lo
    var pivot0 = (Math.random()*count+lo)|0
    var value0 = boxes[elemSize*pivot0 + axis]
    var pivot1 = (Math.random()*count+lo)|0
    var value1 = boxes[elemSize*pivot1 + axis]
    var pivot2 = (Math.random()*count+lo)|0
    var value2 = boxes[elemSize*pivot2 + axis]
    if(value0 <= value1) {
      if(value2 >= value1) {
        pivot = pivot1
        value = value1
      } else if(value0 >= value2) {
        pivot = pivot0
        value = value0
      } else {
        pivot = pivot2
        value = value2
      }
    } else {
      if(value1 >= value2) {
        pivot = pivot1
        value = value1
      } else if(value2 >= value0) {
        pivot = pivot0
        value = value0
      } else {
        pivot = pivot2
        value = value2
      }
    }

    //Swap pivot to end of array
    var aPtr = elemSize * (hi-1)
    var bPtr = elemSize * pivot
    for(var i=0; i<elemSize; ++i, ++aPtr, ++bPtr) {
      var x = boxes[aPtr]
      boxes[aPtr] = boxes[bPtr]
      boxes[bPtr] = x
    }
    var y = ids[hi-1]
    ids[hi-1] = ids[pivot]
    ids[pivot] = y

    //Partition using pivot
    pivot = partitionStartLessThan(
      d, axis, 
      lo, hi-1, boxes, ids,
      value)

    //Swap pivot back
    var aPtr = elemSize * (hi-1)
    var bPtr = elemSize * pivot
    for(var i=0; i<elemSize; ++i, ++aPtr, ++bPtr) {
      var x = boxes[aPtr]
      boxes[aPtr] = boxes[bPtr]
      boxes[bPtr] = x
    }
    var y = ids[hi-1]
    ids[hi-1] = ids[pivot]
    ids[pivot] = y

    //Swap pivot to last pivot
    if(mid < pivot) {
      hi = pivot-1
      while(lo < hi && 
        boxes[elemSize*(hi-1)+axis] === value) {
        hi -= 1
      }
      hi += 1
    } else if(pivot < mid) {
      lo = pivot + 1
      while(lo < hi &&
        boxes[elemSize*lo+axis] === value) {
        lo += 1
      }
    } else {
      break
    }
  }

  //Make sure pivot is at start
  return partitionStartLessThan(
    d, axis, 
    start, mid, boxes, ids,
    boxes[elemSize*mid+axis])
}
},{"./partition":88}],88:[function(_dereq_,module,exports){
'use strict'

module.exports = genPartition

var code = 'for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m'

function genPartition(predicate, args) {
  var fargs ='abcdef'.split('').concat(args)
  var reads = []
  if(predicate.indexOf('lo') >= 0) {
    reads.push('lo=e[k+n]')
  }
  if(predicate.indexOf('hi') >= 0) {
    reads.push('hi=e[k+o]')
  }
  fargs.push(
    code.replace('_', reads.join())
        .replace('$', predicate))
  return Function.apply(void 0, fargs)
}
},{}],89:[function(_dereq_,module,exports){
'use strict';

//This code is extracted from ndarray-sort
//It is inlined here as a temporary workaround

module.exports = wrapper;

var INSERT_SORT_CUTOFF = 32

function wrapper(data, n0) {
  if (n0 <= 4*INSERT_SORT_CUTOFF) {
    insertionSort(0, n0 - 1, data);
  } else {
    quickSort(0, n0 - 1, data);
  }
}

function insertionSort(left, right, data) {
  var ptr = 2*(left+1)
  for(var i=left+1; i<=right; ++i) {
    var a = data[ptr++]
    var b = data[ptr++]
    var j = i
    var jptr = ptr-2
    while(j-- > left) {
      var x = data[jptr-2]
      var y = data[jptr-1]
      if(x < a) {
        break
      } else if(x === a && y < b) {
        break
      }
      data[jptr]   = x
      data[jptr+1] = y
      jptr -= 2
    }
    data[jptr]   = a
    data[jptr+1] = b
  }
}

function swap(i, j, data) {
  i *= 2
  j *= 2
  var x = data[i]
  var y = data[i+1]
  data[i] = data[j]
  data[i+1] = data[j+1]
  data[j] = x
  data[j+1] = y
}

function move(i, j, data) {
  i *= 2
  j *= 2
  data[i] = data[j]
  data[i+1] = data[j+1]
}

function rotate(i, j, k, data) {
  i *= 2
  j *= 2
  k *= 2
  var x = data[i]
  var y = data[i+1]
  data[i] = data[j]
  data[i+1] = data[j+1]
  data[j] = data[k]
  data[j+1] = data[k+1]
  data[k] = x
  data[k+1] = y
}

function shufflePivot(i, j, px, py, data) {
  i *= 2
  j *= 2
  data[i] = data[j]
  data[j] = px
  data[i+1] = data[j+1]
  data[j+1] = py
}

function compare(i, j, data) {
  i *= 2
  j *= 2
  var x = data[i],
      y = data[j]
  if(x < y) {
    return false
  } else if(x === y) {
    return data[i+1] > data[j+1]
  }
  return true
}

function comparePivot(i, y, b, data) {
  i *= 2
  var x = data[i]
  if(x < y) {
    return true
  } else if(x === y) {
    return data[i+1] < b
  }
  return false
}

function quickSort(left, right, data) {
  var sixth = (right - left + 1) / 6 | 0, 
      index1 = left + sixth, 
      index5 = right - sixth, 
      index3 = left + right >> 1, 
      index2 = index3 - sixth, 
      index4 = index3 + sixth, 
      el1 = index1, 
      el2 = index2, 
      el3 = index3, 
      el4 = index4, 
      el5 = index5, 
      less = left + 1, 
      great = right - 1, 
      tmp = 0
  if(compare(el1, el2, data)) {
    tmp = el1
    el1 = el2
    el2 = tmp
  }
  if(compare(el4, el5, data)) {
    tmp = el4
    el4 = el5
    el5 = tmp
  }
  if(compare(el1, el3, data)) {
    tmp = el1
    el1 = el3
    el3 = tmp
  }
  if(compare(el2, el3, data)) {
    tmp = el2
    el2 = el3
    el3 = tmp
  }
  if(compare(el1, el4, data)) {
    tmp = el1
    el1 = el4
    el4 = tmp
  }
  if(compare(el3, el4, data)) {
    tmp = el3
    el3 = el4
    el4 = tmp
  }
  if(compare(el2, el5, data)) {
    tmp = el2
    el2 = el5
    el5 = tmp
  }
  if(compare(el2, el3, data)) {
    tmp = el2
    el2 = el3
    el3 = tmp
  }
  if(compare(el4, el5, data)) {
    tmp = el4
    el4 = el5
    el5 = tmp
  }

  var pivot1X = data[2*el2]
  var pivot1Y = data[2*el2+1]
  var pivot2X = data[2*el4]
  var pivot2Y = data[2*el4+1]

  var ptr0 = 2 * el1;
  var ptr2 = 2 * el3;
  var ptr4 = 2 * el5;
  var ptr5 = 2 * index1;
  var ptr6 = 2 * index3;
  var ptr7 = 2 * index5;
  for (var i1 = 0; i1 < 2; ++i1) {
    var x = data[ptr0+i1];
    var y = data[ptr2+i1];
    var z = data[ptr4+i1];
    data[ptr5+i1] = x;
    data[ptr6+i1] = y;
    data[ptr7+i1] = z;
  }

  move(index2, left, data)
  move(index4, right, data)
  for (var k = less; k <= great; ++k) {
    if (comparePivot(k, pivot1X, pivot1Y, data)) {
      if (k !== less) {
        swap(k, less, data)
      }
      ++less;
    } else {
      if (!comparePivot(k, pivot2X, pivot2Y, data)) {
        while (true) {
          if (!comparePivot(great, pivot2X, pivot2Y, data)) {
            if (--great < k) {
              break;
            }
            continue;
          } else {
            if (comparePivot(great, pivot1X, pivot1Y, data)) {
              rotate(k, less, great, data)
              ++less;
              --great;
            } else {
              swap(k, great, data)
              --great;
            }
            break;
          }
        }
      }
    }
  }
  shufflePivot(left, less-1, pivot1X, pivot1Y, data)
  shufflePivot(right, great+1, pivot2X, pivot2Y, data)
  if (less - 2 - left <= INSERT_SORT_CUTOFF) {
    insertionSort(left, less - 2, data);
  } else {
    quickSort(left, less - 2, data);
  }
  if (right - (great + 2) <= INSERT_SORT_CUTOFF) {
    insertionSort(great + 2, right, data);
  } else {
    quickSort(great + 2, right, data);
  }
  if (great - less <= INSERT_SORT_CUTOFF) {
    insertionSort(less, great, data);
  } else {
    quickSort(less, great, data);
  }
}
},{}],90:[function(_dereq_,module,exports){
'use strict'

module.exports = {
  init:           sqInit,
  sweepBipartite: sweepBipartite,
  sweepComplete:  sweepComplete,
  scanBipartite:  scanBipartite,
  scanComplete:   scanComplete
}

var pool  = _dereq_('typedarray-pool')
var bits  = _dereq_('bit-twiddle')
var isort = _dereq_('./sort')

//Flag for blue
var BLUE_FLAG = (1<<28)

//1D sweep event queue stuff (use pool to save space)
var INIT_CAPACITY      = 1024
var RED_SWEEP_QUEUE    = pool.mallocInt32(INIT_CAPACITY)
var RED_SWEEP_INDEX    = pool.mallocInt32(INIT_CAPACITY)
var BLUE_SWEEP_QUEUE   = pool.mallocInt32(INIT_CAPACITY)
var BLUE_SWEEP_INDEX   = pool.mallocInt32(INIT_CAPACITY)
var COMMON_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY)
var COMMON_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY)
var SWEEP_EVENTS       = pool.mallocDouble(INIT_CAPACITY * 8)

//Reserves memory for the 1D sweep data structures
function sqInit(count) {
  var rcount = bits.nextPow2(count)
  if(RED_SWEEP_QUEUE.length < rcount) {
    pool.free(RED_SWEEP_QUEUE)
    RED_SWEEP_QUEUE = pool.mallocInt32(rcount)
  }
  if(RED_SWEEP_INDEX.length < rcount) {
    pool.free(RED_SWEEP_INDEX)
    RED_SWEEP_INDEX = pool.mallocInt32(rcount)
  }
  if(BLUE_SWEEP_QUEUE.length < rcount) {
    pool.free(BLUE_SWEEP_QUEUE)
    BLUE_SWEEP_QUEUE = pool.mallocInt32(rcount)
  }
  if(BLUE_SWEEP_INDEX.length < rcount) {
    pool.free(BLUE_SWEEP_INDEX)
    BLUE_SWEEP_INDEX = pool.mallocInt32(rcount)
  }
  if(COMMON_SWEEP_QUEUE.length < rcount) {
    pool.free(COMMON_SWEEP_QUEUE)
    COMMON_SWEEP_QUEUE = pool.mallocInt32(rcount)
  }
  if(COMMON_SWEEP_INDEX.length < rcount) {
    pool.free(COMMON_SWEEP_INDEX)
    COMMON_SWEEP_INDEX = pool.mallocInt32(rcount)
  }
  var eventLength = 8 * rcount
  if(SWEEP_EVENTS.length < eventLength) {
    pool.free(SWEEP_EVENTS)
    SWEEP_EVENTS = pool.mallocDouble(eventLength)
  }
}

//Remove an item from the active queue in O(1)
function sqPop(queue, index, count, item) {
  var idx = index[item]
  var top = queue[count-1]
  queue[idx] = top
  index[top] = idx
}

//Insert an item into the active queue in O(1)
function sqPush(queue, index, count, item) {
  queue[count] = item
  index[item]  = count
}

//Recursion base case: use 1D sweep algorithm
function sweepBipartite(
    d, visit,
    redStart,  redEnd, red, redIndex,
    blueStart, blueEnd, blue, blueIndex) {

  //store events as pairs [coordinate, idx]
  //
  //  red create:  -(idx+1)
  //  red destroy: idx
  //  blue create: -(idx+BLUE_FLAG)
  //  blue destroy: idx+BLUE_FLAG
  //
  var ptr      = 0
  var elemSize = 2*d
  var istart   = d-1
  var iend     = elemSize-1

  for(var i=redStart; i<redEnd; ++i) {
    var idx = redIndex[i]
    var redOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = red[redOffset+istart]
    SWEEP_EVENTS[ptr++] = -(idx+1)
    SWEEP_EVENTS[ptr++] = red[redOffset+iend]
    SWEEP_EVENTS[ptr++] = idx
  }

  for(var i=blueStart; i<blueEnd; ++i) {
    var idx = blueIndex[i]+BLUE_FLAG
    var blueOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = blue[blueOffset+istart]
    SWEEP_EVENTS[ptr++] = -idx
    SWEEP_EVENTS[ptr++] = blue[blueOffset+iend]
    SWEEP_EVENTS[ptr++] = idx
  }

  //process events from left->right
  var n = ptr >>> 1
  isort(SWEEP_EVENTS, n)
  
  var redActive  = 0
  var blueActive = 0
  for(var i=0; i<n; ++i) {
    var e = SWEEP_EVENTS[2*i+1]|0
    if(e >= BLUE_FLAG) {
      //blue destroy event
      e = (e-BLUE_FLAG)|0
      sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, e)
    } else if(e >= 0) {
      //red destroy event
      sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e)
    } else if(e <= -BLUE_FLAG) {
      //blue create event
      e = (-e-BLUE_FLAG)|0
      for(var j=0; j<redActive; ++j) {
        var retval = visit(RED_SWEEP_QUEUE[j], e)
        if(retval !== void 0) {
          return retval
        }
      }
      sqPush(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive++, e)
    } else {
      //red create event
      e = (-e-1)|0
      for(var j=0; j<blueActive; ++j) {
        var retval = visit(e, BLUE_SWEEP_QUEUE[j])
        if(retval !== void 0) {
          return retval
        }
      }
      sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, e)
    }
  }
}

//Complete sweep
function sweepComplete(d, visit, 
  redStart, redEnd, red, redIndex,
  blueStart, blueEnd, blue, blueIndex) {

  var ptr      = 0
  var elemSize = 2*d
  var istart   = d-1
  var iend     = elemSize-1

  for(var i=redStart; i<redEnd; ++i) {
    var idx = (redIndex[i]+1)<<1
    var redOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = red[redOffset+istart]
    SWEEP_EVENTS[ptr++] = -idx
    SWEEP_EVENTS[ptr++] = red[redOffset+iend]
    SWEEP_EVENTS[ptr++] = idx
  }

  for(var i=blueStart; i<blueEnd; ++i) {
    var idx = (blueIndex[i]+1)<<1
    var blueOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = blue[blueOffset+istart]
    SWEEP_EVENTS[ptr++] = (-idx)|1
    SWEEP_EVENTS[ptr++] = blue[blueOffset+iend]
    SWEEP_EVENTS[ptr++] = idx|1
  }

  //process events from left->right
  var n = ptr >>> 1
  isort(SWEEP_EVENTS, n)
  
  var redActive    = 0
  var blueActive   = 0
  var commonActive = 0
  for(var i=0; i<n; ++i) {
    var e     = SWEEP_EVENTS[2*i+1]|0
    var color = e&1
    if(i < n-1 && (e>>1) === (SWEEP_EVENTS[2*i+3]>>1)) {
      color = 2
      i += 1
    }
    
    if(e < 0) {
      //Create event
      var id = -(e>>1) - 1

      //Intersect with common
      for(var j=0; j<commonActive; ++j) {
        var retval = visit(COMMON_SWEEP_QUEUE[j], id)
        if(retval !== void 0) {
          return retval
        }
      }

      if(color !== 0) {
        //Intersect with red
        for(var j=0; j<redActive; ++j) {
          var retval = visit(RED_SWEEP_QUEUE[j], id)
          if(retval !== void 0) {
            return retval
          }
        }
      }

      if(color !== 1) {
        //Intersect with blue
        for(var j=0; j<blueActive; ++j) {
          var retval = visit(BLUE_SWEEP_QUEUE[j], id)
          if(retval !== void 0) {
            return retval
          }
        }
      }

      if(color === 0) {
        //Red
        sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, id)
      } else if(color === 1) {
        //Blue
        sqPush(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive++, id)
      } else if(color === 2) {
        //Both
        sqPush(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive++, id)
      }
    } else {
      //Destroy event
      var id = (e>>1) - 1
      if(color === 0) {
        //Red
        sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, id)
      } else if(color === 1) {
        //Blue
        sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, id)
      } else if(color === 2) {
        //Both
        sqPop(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive--, id)
      }
    }
  }
}

//Sweep and prune/scanline algorithm:
//  Scan along axis, detect intersections
//  Brute force all boxes along axis
function scanBipartite(
  d, axis, visit, flip,
  redStart,  redEnd, red, redIndex,
  blueStart, blueEnd, blue, blueIndex) {
  
  var ptr      = 0
  var elemSize = 2*d
  var istart   = axis
  var iend     = axis+d

  var redShift  = 1
  var blueShift = 1
  if(flip) {
    blueShift = BLUE_FLAG
  } else {
    redShift  = BLUE_FLAG
  }

  for(var i=redStart; i<redEnd; ++i) {
    var idx = i + redShift
    var redOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = red[redOffset+istart]
    SWEEP_EVENTS[ptr++] = -idx
    SWEEP_EVENTS[ptr++] = red[redOffset+iend]
    SWEEP_EVENTS[ptr++] = idx
  }
  for(var i=blueStart; i<blueEnd; ++i) {
    var idx = i + blueShift
    var blueOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = blue[blueOffset+istart]
    SWEEP_EVENTS[ptr++] = -idx
  }

  //process events from left->right
  var n = ptr >>> 1
  isort(SWEEP_EVENTS, n)
  
  var redActive    = 0
  for(var i=0; i<n; ++i) {
    var e = SWEEP_EVENTS[2*i+1]|0
    if(e < 0) {
      var idx   = -e
      var isRed = false
      if(idx >= BLUE_FLAG) {
        isRed = !flip
        idx -= BLUE_FLAG 
      } else {
        isRed = !!flip
        idx -= 1
      }
      if(isRed) {
        sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, idx)
      } else {
        var blueId  = blueIndex[idx]
        var bluePtr = elemSize * idx
        
        var b0 = blue[bluePtr+axis+1]
        var b1 = blue[bluePtr+axis+1+d]

red_loop:
        for(var j=0; j<redActive; ++j) {
          var oidx   = RED_SWEEP_QUEUE[j]
          var redPtr = elemSize * oidx

          if(b1 < red[redPtr+axis+1] || 
             red[redPtr+axis+1+d] < b0) {
            continue
          }

          for(var k=axis+2; k<d; ++k) {
            if(blue[bluePtr + k + d] < red[redPtr + k] || 
               red[redPtr + k + d] < blue[bluePtr + k]) {
              continue red_loop
            }
          }

          var redId  = redIndex[oidx]
          var retval
          if(flip) {
            retval = visit(blueId, redId)
          } else {
            retval = visit(redId, blueId)
          }
          if(retval !== void 0) {
            return retval 
          }
        }
      }
    } else {
      sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e - redShift)
    }
  }
}

function scanComplete(
  d, axis, visit,
  redStart,  redEnd, red, redIndex,
  blueStart, blueEnd, blue, blueIndex) {

  var ptr      = 0
  var elemSize = 2*d
  var istart   = axis
  var iend     = axis+d

  for(var i=redStart; i<redEnd; ++i) {
    var idx = i + BLUE_FLAG
    var redOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = red[redOffset+istart]
    SWEEP_EVENTS[ptr++] = -idx
    SWEEP_EVENTS[ptr++] = red[redOffset+iend]
    SWEEP_EVENTS[ptr++] = idx
  }
  for(var i=blueStart; i<blueEnd; ++i) {
    var idx = i + 1
    var blueOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = blue[blueOffset+istart]
    SWEEP_EVENTS[ptr++] = -idx
  }

  //process events from left->right
  var n = ptr >>> 1
  isort(SWEEP_EVENTS, n)
  
  var redActive    = 0
  for(var i=0; i<n; ++i) {
    var e = SWEEP_EVENTS[2*i+1]|0
    if(e < 0) {
      var idx   = -e
      if(idx >= BLUE_FLAG) {
        RED_SWEEP_QUEUE[redActive++] = idx - BLUE_FLAG
      } else {
        idx -= 1
        var blueId  = blueIndex[idx]
        var bluePtr = elemSize * idx

        var b0 = blue[bluePtr+axis+1]
        var b1 = blue[bluePtr+axis+1+d]

red_loop:
        for(var j=0; j<redActive; ++j) {
          var oidx   = RED_SWEEP_QUEUE[j]
          var redId  = redIndex[oidx]

          if(redId === blueId) {
            break
          }

          var redPtr = elemSize * oidx
          if(b1 < red[redPtr+axis+1] || 
            red[redPtr+axis+1+d] < b0) {
            continue
          }
          for(var k=axis+2; k<d; ++k) {
            if(blue[bluePtr + k + d] < red[redPtr + k] || 
               red[redPtr + k + d]   < blue[bluePtr + k]) {
              continue red_loop
            }
          }

          var retval = visit(redId, blueId)
          if(retval !== void 0) {
            return retval 
          }
        }
      }
    } else {
      var idx = e - BLUE_FLAG
      for(var j=redActive-1; j>=0; --j) {
        if(RED_SWEEP_QUEUE[j] === idx) {
          for(var k=j+1; k<redActive; ++k) {
            RED_SWEEP_QUEUE[k-1] = RED_SWEEP_QUEUE[k]
          }
          break
        }
      }
      --redActive
    }
  }
}
},{"./sort":89,"bit-twiddle":80,"typedarray-pool":526}],91:[function(_dereq_,module,exports){

},{}],92:[function(_dereq_,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.

var objectCreate = Object.create || objectCreatePolyfill
var objectKeys = Object.keys || objectKeysPolyfill
var bind = Function.prototype.bind || functionBindPolyfill

function EventEmitter() {
  if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
    this._events = objectCreate(null);
    this._eventsCount = 0;
  }

  this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;

// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;

EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;

// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
var defaultMaxListeners = 10;

var hasDefineProperty;
try {
  var o = {};
  if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
  hasDefineProperty = o.x === 0;
} catch (err) { hasDefineProperty = false }
if (hasDefineProperty) {
  Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
    enumerable: true,
    get: function() {
      return defaultMaxListeners;
    },
    set: function(arg) {
      // check whether the input is a positive number (whose value is zero or
      // greater and not a NaN).
      if (typeof arg !== 'number' || arg < 0 || arg !== arg)
        throw new TypeError('"defaultMaxListeners" must be a positive number');
      defaultMaxListeners = arg;
    }
  });
} else {
  EventEmitter.defaultMaxListeners = defaultMaxListeners;
}

// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  if (typeof n !== 'number' || n < 0 || isNaN(n))
    throw new TypeError('"n" argument must be a positive number');
  this._maxListeners = n;
  return this;
};

function $getMaxListeners(that) {
  if (that._maxListeners === undefined)
    return EventEmitter.defaultMaxListeners;
  return that._maxListeners;
}

EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  return $getMaxListeners(this);
};

// These standalone emit* functions are used to optimize calling of event
// handlers for fast cases because emit() itself often has a variable number of
// arguments and can be deoptimized because of that. These functions always have
// the same number of arguments and thus do not get deoptimized, so the code
// inside them can execute faster.
function emitNone(handler, isFn, self) {
  if (isFn)
    handler.call(self);
  else {
    var len = handler.length;
    var listeners = arrayClone(handler, len);
    for (var i = 0; i < len; ++i)
      listeners[i].call(self);
  }
}
function emitOne(handler, isFn, self, arg1) {
  if (isFn)
    handler.call(self, arg1);
  else {
    var len = handler.length;
    var listeners = arrayClone(handler, len);
    for (var i = 0; i < len; ++i)
      listeners[i].call(self, arg1);
  }
}
function emitTwo(handler, isFn, self, arg1, arg2) {
  if (isFn)
    handler.call(self, arg1, arg2);
  else {
    var len = handler.length;
    var listeners = arrayClone(handler, len);
    for (var i = 0; i < len; ++i)
      listeners[i].call(self, arg1, arg2);
  }
}
function emitThree(handler, isFn, self, arg1, arg2, arg3) {
  if (isFn)
    handler.call(self, arg1, arg2, arg3);
  else {
    var len = handler.length;
    var listeners = arrayClone(handler, len);
    for (var i = 0; i < len; ++i)
      listeners[i].call(self, arg1, arg2, arg3);
  }
}

function emitMany(handler, isFn, self, args) {
  if (isFn)
    handler.apply(self, args);
  else {
    var len = handler.length;
    var listeners = arrayClone(handler, len);
    for (var i = 0; i < len; ++i)
      listeners[i].apply(self, args);
  }
}

EventEmitter.prototype.emit = function emit(type) {
  var er, handler, len, args, i, events;
  var doError = (type === 'error');

  events = this._events;
  if (events)
    doError = (doError && events.error == null);
  else if (!doError)
    return false;

  // If there is no 'error' event listener then throw.
  if (doError) {
    if (arguments.length > 1)
      er = arguments[1];
    if (er instanceof Error) {
      throw er; // Unhandled 'error' event
    } else {
      // At least give some kind of context to the user
      var err = new Error('Unhandled "error" event. (' + er + ')');
      err.context = er;
      throw err;
    }
    return false;
  }

  handler = events[type];

  if (!handler)
    return false;

  var isFn = typeof handler === 'function';
  len = arguments.length;
  switch (len) {
      // fast cases
    case 1:
      emitNone(handler, isFn, this);
      break;
    case 2:
      emitOne(handler, isFn, this, arguments[1]);
      break;
    case 3:
      emitTwo(handler, isFn, this, arguments[1], arguments[2]);
      break;
    case 4:
      emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
      break;
      // slower
    default:
      args = new Array(len - 1);
      for (i = 1; i < len; i++)
        args[i - 1] = arguments[i];
      emitMany(handler, isFn, this, args);
  }

  return true;
};

function _addListener(target, type, listener, prepend) {
  var m;
  var events;
  var existing;

  if (typeof listener !== 'function')
    throw new TypeError('"listener" argument must be a function');

  events = target._events;
  if (!events) {
    events = target._events = objectCreate(null);
    target._eventsCount = 0;
  } else {
    // To avoid recursion in the case that type === "newListener"! Before
    // adding it to the listeners, first emit "newListener".
    if (events.newListener) {
      target.emit('newListener', type,
          listener.listener ? listener.listener : listener);

      // Re-assign `events` because a newListener handler could have caused the
      // this._events to be assigned to a new object
      events = target._events;
    }
    existing = events[type];
  }

  if (!existing) {
    // Optimize the case of one listener. Don't need the extra array object.
    existing = events[type] = listener;
    ++target._eventsCount;
  } else {
    if (typeof existing === 'function') {
      // Adding the second element, need to change to array.
      existing = events[type] =
          prepend ? [listener, existing] : [existing, listener];
    } else {
      // If we've already got an array, just append.
      if (prepend) {
        existing.unshift(listener);
      } else {
        existing.push(listener);
      }
    }

    // Check for listener leak
    if (!existing.warned) {
      m = $getMaxListeners(target);
      if (m && m > 0 && existing.length > m) {
        existing.warned = true;
        var w = new Error('Possible EventEmitter memory leak detected. ' +
            existing.length + ' "' + String(type) + '" listeners ' +
            'added. Use emitter.setMaxListeners() to ' +
            'increase limit.');
        w.name = 'MaxListenersExceededWarning';
        w.emitter = target;
        w.type = type;
        w.count = existing.length;
        if (typeof console === 'object' && console.warn) {
          console.warn('%s: %s', w.name, w.message);
        }
      }
    }
  }

  return target;
}

EventEmitter.prototype.addListener = function addListener(type, listener) {
  return _addListener(this, type, listener, false);
};

EventEmitter.prototype.on = EventEmitter.prototype.addListener;

EventEmitter.prototype.prependListener =
    function prependListener(type, listener) {
      return _addListener(this, type, listener, true);
    };

function onceWrapper() {
  if (!this.fired) {
    this.target.removeListener(this.type, this.wrapFn);
    this.fired = true;
    switch (arguments.length) {
      case 0:
        return this.listener.call(this.target);
      case 1:
        return this.listener.call(this.target, arguments[0]);
      case 2:
        return this.listener.call(this.target, arguments[0], arguments[1]);
      case 3:
        return this.listener.call(this.target, arguments[0], arguments[1],
            arguments[2]);
      default:
        var args = new Array(arguments.length);
        for (var i = 0; i < args.length; ++i)
          args[i] = arguments[i];
        this.listener.apply(this.target, args);
    }
  }
}

function _onceWrap(target, type, listener) {
  var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  var wrapped = bind.call(onceWrapper, state);
  wrapped.listener = listener;
  state.wrapFn = wrapped;
  return wrapped;
}

EventEmitter.prototype.once = function once(type, listener) {
  if (typeof listener !== 'function')
    throw new TypeError('"listener" argument must be a function');
  this.on(type, _onceWrap(this, type, listener));
  return this;
};

EventEmitter.prototype.prependOnceListener =
    function prependOnceListener(type, listener) {
      if (typeof listener !== 'function')
        throw new TypeError('"listener" argument must be a function');
      this.prependListener(type, _onceWrap(this, type, listener));
      return this;
    };

// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
    function removeListener(type, listener) {
      var list, events, position, i, originalListener;

      if (typeof listener !== 'function')
        throw new TypeError('"listener" argument must be a function');

      events = this._events;
      if (!events)
        return this;

      list = events[type];
      if (!list)
        return this;

      if (list === listener || list.listener === listener) {
        if (--this._eventsCount === 0)
          this._events = objectCreate(null);
        else {
          delete events[type];
          if (events.removeListener)
            this.emit('removeListener', type, list.listener || listener);
        }
      } else if (typeof list !== 'function') {
        position = -1;

        for (i = list.length - 1; i >= 0; i--) {
          if (list[i] === listener || list[i].listener === listener) {
            originalListener = list[i].listener;
            position = i;
            break;
          }
        }

        if (position < 0)
          return this;

        if (position === 0)
          list.shift();
        else
          spliceOne(list, position);

        if (list.length === 1)
          events[type] = list[0];

        if (events.removeListener)
          this.emit('removeListener', type, originalListener || listener);
      }

      return this;
    };

EventEmitter.prototype.removeAllListeners =
    function removeAllListeners(type) {
      var listeners, events, i;

      events = this._events;
      if (!events)
        return this;

      // not listening for removeListener, no need to emit
      if (!events.removeListener) {
        if (arguments.length === 0) {
          this._events = objectCreate(null);
          this._eventsCount = 0;
        } else if (events[type]) {
          if (--this._eventsCount === 0)
            this._events = objectCreate(null);
          else
            delete events[type];
        }
        return this;
      }

      // emit removeListener for all listeners on all events
      if (arguments.length === 0) {
        var keys = objectKeys(events);
        var key;
        for (i = 0; i < keys.length; ++i) {
          key = keys[i];
          if (key === 'removeListener') continue;
          this.removeAllListeners(key);
        }
        this.removeAllListeners('removeListener');
        this._events = objectCreate(null);
        this._eventsCount = 0;
        return this;
      }

      listeners = events[type];

      if (typeof listeners === 'function') {
        this.removeListener(type, listeners);
      } else if (listeners) {
        // LIFO order
        for (i = listeners.length - 1; i >= 0; i--) {
          this.removeListener(type, listeners[i]);
        }
      }

      return this;
    };

function _listeners(target, type, unwrap) {
  var events = target._events;

  if (!events)
    return [];

  var evlistener = events[type];
  if (!evlistener)
    return [];

  if (typeof evlistener === 'function')
    return unwrap ? [evlistener.listener || evlistener] : [evlistener];

  return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}

EventEmitter.prototype.listeners = function listeners(type) {
  return _listeners(this, type, true);
};

EventEmitter.prototype.rawListeners = function rawListeners(type) {
  return _listeners(this, type, false);
};

EventEmitter.listenerCount = function(emitter, type) {
  if (typeof emitter.listenerCount === 'function') {
    return emitter.listenerCount(type);
  } else {
    return listenerCount.call(emitter, type);
  }
};

EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
  var events = this._events;

  if (events) {
    var evlistener = events[type];

    if (typeof evlistener === 'function') {
      return 1;
    } else if (evlistener) {
      return evlistener.length;
    }
  }

  return 0;
}

EventEmitter.prototype.eventNames = function eventNames() {
  return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
};

// About 1.5x faster than the two-arg version of Array#splice().
function spliceOne(list, index) {
  for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
    list[i] = list[k];
  list.pop();
}

function arrayClone(arr, n) {
  var copy = new Array(n);
  for (var i = 0; i < n; ++i)
    copy[i] = arr[i];
  return copy;
}

function unwrapListeners(arr) {
  var ret = new Array(arr.length);
  for (var i = 0; i < ret.length; ++i) {
    ret[i] = arr[i].listener || arr[i];
  }
  return ret;
}

function objectCreatePolyfill(proto) {
  var F = function() {};
  F.prototype = proto;
  return new F;
}
function objectKeysPolyfill(obj) {
  var keys = [];
  for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
    keys.push(k);
  }
  return k;
}
function functionBindPolyfill(context) {
  var fn = this;
  return function () {
    return fn.apply(context, arguments);
  };
}

},{}],93:[function(_dereq_,module,exports){
/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <https://feross.org>
 * @license  MIT
 */
/* eslint-disable no-proto */

'use strict'

var base64 = _dereq_('base64-js')
var ieee754 = _dereq_('ieee754')

exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50

var K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH

/**
 * If `Buffer.TYPED_ARRAY_SUPPORT`:
 *   === true    Use Uint8Array implementation (fastest)
 *   === false   Print warning and recommend using `buffer` v4.x which has an Object
 *               implementation (most compatible, even IE6)
 *
 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
 * Opera 11.6+, iOS 4.2+.
 *
 * We report that the browser does not support typed arrays if the are not subclassable
 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
 * for __proto__ and has a buggy typed array implementation.
 */
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()

if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
    typeof console.error === 'function') {
  console.error(
    'This browser lacks typed array (Uint8Array) support which is required by ' +
    '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  )
}

function typedArraySupport () {
  // Can typed array instances can be augmented?
  try {
    var arr = new Uint8Array(1)
    arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
    return arr.foo() === 42
  } catch (e) {
    return false
  }
}

Object.defineProperty(Buffer.prototype, 'parent', {
  enumerable: true,
  get: function () {
    if (!Buffer.isBuffer(this)) return undefined
    return this.buffer
  }
})

Object.defineProperty(Buffer.prototype, 'offset', {
  enumerable: true,
  get: function () {
    if (!Buffer.isBuffer(this)) return undefined
    return this.byteOffset
  }
})

function createBuffer (length) {
  if (length > K_MAX_LENGTH) {
    throw new RangeError('The value "' + length + '" is invalid for option "size"')
  }
  // Return an augmented `Uint8Array` instance
  var buf = new Uint8Array(length)
  buf.__proto__ = Buffer.prototype
  return buf
}

/**
 * The Buffer constructor returns instances of `Uint8Array` that have their
 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
 * returns a single octet.
 *
 * The `Uint8Array` prototype remains unmodified.
 */

function Buffer (arg, encodingOrOffset, length) {
  // Common case.
  if (typeof arg === 'number') {
    if (typeof encodingOrOffset === 'string') {
      throw new TypeError(
        'The "string" argument must be of type string. Received type number'
      )
    }
    return allocUnsafe(arg)
  }
  return from(arg, encodingOrOffset, length)
}

// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (typeof Symbol !== 'undefined' && Symbol.species != null &&
    Buffer[Symbol.species] === Buffer) {
  Object.defineProperty(Buffer, Symbol.species, {
    value: null,
    configurable: true,
    enumerable: false,
    writable: false
  })
}

Buffer.poolSize = 8192 // not used by this implementation

function from (value, encodingOrOffset, length) {
  if (typeof value === 'string') {
    return fromString(value, encodingOrOffset)
  }

  if (ArrayBuffer.isView(value)) {
    return fromArrayLike(value)
  }

  if (value == null) {
    throw TypeError(
      'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
      'or Array-like Object. Received type ' + (typeof value)
    )
  }

  if (isInstance(value, ArrayBuffer) ||
      (value && isInstance(value.buffer, ArrayBuffer))) {
    return fromArrayBuffer(value, encodingOrOffset, length)
  }

  if (typeof value === 'number') {
    throw new TypeError(
      'The "value" argument must not be of type number. Received type number'
    )
  }

  var valueOf = value.valueOf && value.valueOf()
  if (valueOf != null && valueOf !== value) {
    return Buffer.from(valueOf, encodingOrOffset, length)
  }

  var b = fromObject(value)
  if (b) return b

  if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
      typeof value[Symbol.toPrimitive] === 'function') {
    return Buffer.from(
      value[Symbol.toPrimitive]('string'), encodingOrOffset, length
    )
  }

  throw new TypeError(
    'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
    'or Array-like Object. Received type ' + (typeof value)
  )
}

/**
 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
 * if value is a number.
 * Buffer.from(str[, encoding])
 * Buffer.from(array)
 * Buffer.from(buffer)
 * Buffer.from(arrayBuffer[, byteOffset[, length]])
 **/
Buffer.from = function (value, encodingOrOffset, length) {
  return from(value, encodingOrOffset, length)
}

// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array

function assertSize (size) {
  if (typeof size !== 'number') {
    throw new TypeError('"size" argument must be of type number')
  } else if (size < 0) {
    throw new RangeError('The value "' + size + '" is invalid for option "size"')
  }
}

function alloc (size, fill, encoding) {
  assertSize(size)
  if (size <= 0) {
    return createBuffer(size)
  }
  if (fill !== undefined) {
    // Only pay attention to encoding if it's a string. This
    // prevents accidentally sending in a number that would
    // be interpretted as a start offset.
    return typeof encoding === 'string'
      ? createBuffer(size).fill(fill, encoding)
      : createBuffer(size).fill(fill)
  }
  return createBuffer(size)
}

/**
 * Creates a new filled Buffer instance.
 * alloc(size[, fill[, encoding]])
 **/
Buffer.alloc = function (size, fill, encoding) {
  return alloc(size, fill, encoding)
}

function allocUnsafe (size) {
  assertSize(size)
  return createBuffer(size < 0 ? 0 : checked(size) | 0)
}

/**
 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
 * */
Buffer.allocUnsafe = function (size) {
  return allocUnsafe(size)
}
/**
 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
 */
Buffer.allocUnsafeSlow = function (size) {
  return allocUnsafe(size)
}

function fromString (string, encoding) {
  if (typeof encoding !== 'string' || encoding === '') {
    encoding = 'utf8'
  }

  if (!Buffer.isEncoding(encoding)) {
    throw new TypeError('Unknown encoding: ' + encoding)
  }

  var length = byteLength(string, encoding) | 0
  var buf = createBuffer(length)

  var actual = buf.write(string, encoding)

  if (actual !== length) {
    // Writing a hex string, for example, that contains invalid characters will
    // cause everything after the first invalid character to be ignored. (e.g.
    // 'abxxcd' will be treated as 'ab')
    buf = buf.slice(0, actual)
  }

  return buf
}

function fromArrayLike (array) {
  var length = array.length < 0 ? 0 : checked(array.length) | 0
  var buf = createBuffer(length)
  for (var i = 0; i < length; i += 1) {
    buf[i] = array[i] & 255
  }
  return buf
}

function fromArrayBuffer (array, byteOffset, length) {
  if (byteOffset < 0 || array.byteLength < byteOffset) {
    throw new RangeError('"offset" is outside of buffer bounds')
  }

  if (array.byteLength < byteOffset + (length || 0)) {
    throw new RangeError('"length" is outside of buffer bounds')
  }

  var buf
  if (byteOffset === undefined && length === undefined) {
    buf = new Uint8Array(array)
  } else if (length === undefined) {
    buf = new Uint8Array(array, byteOffset)
  } else {
    buf = new Uint8Array(array, byteOffset, length)
  }

  // Return an augmented `Uint8Array` instance
  buf.__proto__ = Buffer.prototype
  return buf
}

function fromObject (obj) {
  if (Buffer.isBuffer(obj)) {
    var len = checked(obj.length) | 0
    var buf = createBuffer(len)

    if (buf.length === 0) {
      return buf
    }

    obj.copy(buf, 0, 0, len)
    return buf
  }

  if (obj.length !== undefined) {
    if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
      return createBuffer(0)
    }
    return fromArrayLike(obj)
  }

  if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
    return fromArrayLike(obj.data)
  }
}

function checked (length) {
  // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  // length is NaN (which is otherwise coerced to zero.)
  if (length >= K_MAX_LENGTH) {
    throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
                         'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  }
  return length | 0
}

function SlowBuffer (length) {
  if (+length != length) { // eslint-disable-line eqeqeq
    length = 0
  }
  return Buffer.alloc(+length)
}

Buffer.isBuffer = function isBuffer (b) {
  return b != null && b._isBuffer === true &&
    b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
}

Buffer.compare = function compare (a, b) {
  if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
  if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
  if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
    throw new TypeError(
      'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
    )
  }

  if (a === b) return 0

  var x = a.length
  var y = b.length

  for (var i = 0, len = Math.min(x, y); i < len; ++i) {
    if (a[i] !== b[i]) {
      x = a[i]
      y = b[i]
      break
    }
  }

  if (x < y) return -1
  if (y < x) return 1
  return 0
}

Buffer.isEncoding = function isEncoding (encoding) {
  switch (String(encoding).toLowerCase()) {
    case 'hex':
    case 'utf8':
    case 'utf-8':
    case 'ascii':
    case 'latin1':
    case 'binary':
    case 'base64':
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return true
    default:
      return false
  }
}

Buffer.concat = function concat (list, length) {
  if (!Array.isArray(list)) {
    throw new TypeError('"list" argument must be an Array of Buffers')
  }

  if (list.length === 0) {
    return Buffer.alloc(0)
  }

  var i
  if (length === undefined) {
    length = 0
    for (i = 0; i < list.length; ++i) {
      length += list[i].length
    }
  }

  var buffer = Buffer.allocUnsafe(length)
  var pos = 0
  for (i = 0; i < list.length; ++i) {
    var buf = list[i]
    if (isInstance(buf, Uint8Array)) {
      buf = Buffer.from(buf)
    }
    if (!Buffer.isBuffer(buf)) {
      throw new TypeError('"list" argument must be an Array of Buffers')
    }
    buf.copy(buffer, pos)
    pos += buf.length
  }
  return buffer
}

function byteLength (string, encoding) {
  if (Buffer.isBuffer(string)) {
    return string.length
  }
  if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
    return string.byteLength
  }
  if (typeof string !== 'string') {
    throw new TypeError(
      'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
      'Received type ' + typeof string
    )
  }

  var len = string.length
  var mustMatch = (arguments.length > 2 && arguments[2] === true)
  if (!mustMatch && len === 0) return 0

  // Use a for loop to avoid recursion
  var loweredCase = false
  for (;;) {
    switch (encoding) {
      case 'ascii':
      case 'latin1':
      case 'binary':
        return len
      case 'utf8':
      case 'utf-8':
        return utf8ToBytes(string).length
      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return len * 2
      case 'hex':
        return len >>> 1
      case 'base64':
        return base64ToBytes(string).length
      default:
        if (loweredCase) {
          return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
        }
        encoding = ('' + encoding).toLowerCase()
        loweredCase = true
    }
  }
}
Buffer.byteLength = byteLength

function slowToString (encoding, start, end) {
  var loweredCase = false

  // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  // property of a typed array.

  // This behaves neither like String nor Uint8Array in that we set start/end
  // to their upper/lower bounds if the value passed is out of range.
  // undefined is handled specially as per ECMA-262 6th Edition,
  // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  if (start === undefined || start < 0) {
    start = 0
  }
  // Return early if start > this.length. Done here to prevent potential uint32
  // coercion fail below.
  if (start > this.length) {
    return ''
  }

  if (end === undefined || end > this.length) {
    end = this.length
  }

  if (end <= 0) {
    return ''
  }

  // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  end >>>= 0
  start >>>= 0

  if (end <= start) {
    return ''
  }

  if (!encoding) encoding = 'utf8'

  while (true) {
    switch (encoding) {
      case 'hex':
        return hexSlice(this, start, end)

      case 'utf8':
      case 'utf-8':
        return utf8Slice(this, start, end)

      case 'ascii':
        return asciiSlice(this, start, end)

      case 'latin1':
      case 'binary':
        return latin1Slice(this, start, end)

      case 'base64':
        return base64Slice(this, start, end)

      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return utf16leSlice(this, start, end)

      default:
        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
        encoding = (encoding + '').toLowerCase()
        loweredCase = true
    }
  }
}

// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true

function swap (b, n, m) {
  var i = b[n]
  b[n] = b[m]
  b[m] = i
}

Buffer.prototype.swap16 = function swap16 () {
  var len = this.length
  if (len % 2 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 16-bits')
  }
  for (var i = 0; i < len; i += 2) {
    swap(this, i, i + 1)
  }
  return this
}

Buffer.prototype.swap32 = function swap32 () {
  var len = this.length
  if (len % 4 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 32-bits')
  }
  for (var i = 0; i < len; i += 4) {
    swap(this, i, i + 3)
    swap(this, i + 1, i + 2)
  }
  return this
}

Buffer.prototype.swap64 = function swap64 () {
  var len = this.length
  if (len % 8 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 64-bits')
  }
  for (var i = 0; i < len; i += 8) {
    swap(this, i, i + 7)
    swap(this, i + 1, i + 6)
    swap(this, i + 2, i + 5)
    swap(this, i + 3, i + 4)
  }
  return this
}

Buffer.prototype.toString = function toString () {
  var length = this.length
  if (length === 0) return ''
  if (arguments.length === 0) return utf8Slice(this, 0, length)
  return slowToString.apply(this, arguments)
}

Buffer.prototype.toLocaleString = Buffer.prototype.toString

Buffer.prototype.equals = function equals (b) {
  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  if (this === b) return true
  return Buffer.compare(this, b) === 0
}

Buffer.prototype.inspect = function inspect () {
  var str = ''
  var max = exports.INSPECT_MAX_BYTES
  str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
  if (this.length > max) str += ' ... '
  return '<Buffer ' + str + '>'
}

Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  if (isInstance(target, Uint8Array)) {
    target = Buffer.from(target, target.offset, target.byteLength)
  }
  if (!Buffer.isBuffer(target)) {
    throw new TypeError(
      'The "target" argument must be one of type Buffer or Uint8Array. ' +
      'Received type ' + (typeof target)
    )
  }

  if (start === undefined) {
    start = 0
  }
  if (end === undefined) {
    end = target ? target.length : 0
  }
  if (thisStart === undefined) {
    thisStart = 0
  }
  if (thisEnd === undefined) {
    thisEnd = this.length
  }

  if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
    throw new RangeError('out of range index')
  }

  if (thisStart >= thisEnd && start >= end) {
    return 0
  }
  if (thisStart >= thisEnd) {
    return -1
  }
  if (start >= end) {
    return 1
  }

  start >>>= 0
  end >>>= 0
  thisStart >>>= 0
  thisEnd >>>= 0

  if (this === target) return 0

  var x = thisEnd - thisStart
  var y = end - start
  var len = Math.min(x, y)

  var thisCopy = this.slice(thisStart, thisEnd)
  var targetCopy = target.slice(start, end)

  for (var i = 0; i < len; ++i) {
    if (thisCopy[i] !== targetCopy[i]) {
      x = thisCopy[i]
      y = targetCopy[i]
      break
    }
  }

  if (x < y) return -1
  if (y < x) return 1
  return 0
}

// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  // Empty buffer means no match
  if (buffer.length === 0) return -1

  // Normalize byteOffset
  if (typeof byteOffset === 'string') {
    encoding = byteOffset
    byteOffset = 0
  } else if (byteOffset > 0x7fffffff) {
    byteOffset = 0x7fffffff
  } else if (byteOffset < -0x80000000) {
    byteOffset = -0x80000000
  }
  byteOffset = +byteOffset // Coerce to Number.
  if (numberIsNaN(byteOffset)) {
    // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
    byteOffset = dir ? 0 : (buffer.length - 1)
  }

  // Normalize byteOffset: negative offsets start from the end of the buffer
  if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  if (byteOffset >= buffer.length) {
    if (dir) return -1
    else byteOffset = buffer.length - 1
  } else if (byteOffset < 0) {
    if (dir) byteOffset = 0
    else return -1
  }

  // Normalize val
  if (typeof val === 'string') {
    val = Buffer.from(val, encoding)
  }

  // Finally, search either indexOf (if dir is true) or lastIndexOf
  if (Buffer.isBuffer(val)) {
    // Special case: looking for empty string/buffer always fails
    if (val.length === 0) {
      return -1
    }
    return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  } else if (typeof val === 'number') {
    val = val & 0xFF // Search for a byte value [0-255]
    if (typeof Uint8Array.prototype.indexOf === 'function') {
      if (dir) {
        return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
      } else {
        return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
      }
    }
    return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  }

  throw new TypeError('val must be string, number or Buffer')
}

function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  var indexSize = 1
  var arrLength = arr.length
  var valLength = val.length

  if (encoding !== undefined) {
    encoding = String(encoding).toLowerCase()
    if (encoding === 'ucs2' || encoding === 'ucs-2' ||
        encoding === 'utf16le' || encoding === 'utf-16le') {
      if (arr.length < 2 || val.length < 2) {
        return -1
      }
      indexSize = 2
      arrLength /= 2
      valLength /= 2
      byteOffset /= 2
    }
  }

  function read (buf, i) {
    if (indexSize === 1) {
      return buf[i]
    } else {
      return buf.readUInt16BE(i * indexSize)
    }
  }

  var i
  if (dir) {
    var foundIndex = -1
    for (i = byteOffset; i < arrLength; i++) {
      if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
        if (foundIndex === -1) foundIndex = i
        if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
      } else {
        if (foundIndex !== -1) i -= i - foundIndex
        foundIndex = -1
      }
    }
  } else {
    if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
    for (i = byteOffset; i >= 0; i--) {
      var found = true
      for (var j = 0; j < valLength; j++) {
        if (read(arr, i + j) !== read(val, j)) {
          found = false
          break
        }
      }
      if (found) return i
    }
  }

  return -1
}

Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  return this.indexOf(val, byteOffset, encoding) !== -1
}

Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}

Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}

function hexWrite (buf, string, offset, length) {
  offset = Number(offset) || 0
  var remaining = buf.length - offset
  if (!length) {
    length = remaining
  } else {
    length = Number(length)
    if (length > remaining) {
      length = remaining
    }
  }

  var strLen = string.length

  if (length > strLen / 2) {
    length = strLen / 2
  }
  for (var i = 0; i < length; ++i) {
    var parsed = parseInt(string.substr(i * 2, 2), 16)
    if (numberIsNaN(parsed)) return i
    buf[offset + i] = parsed
  }
  return i
}

function utf8Write (buf, string, offset, length) {
  return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}

function asciiWrite (buf, string, offset, length) {
  return blitBuffer(asciiToBytes(string), buf, offset, length)
}

function latin1Write (buf, string, offset, length) {
  return asciiWrite(buf, string, offset, length)
}

function base64Write (buf, string, offset, length) {
  return blitBuffer(base64ToBytes(string), buf, offset, length)
}

function ucs2Write (buf, string, offset, length) {
  return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}

Buffer.prototype.write = function write (string, offset, length, encoding) {
  // Buffer#write(string)
  if (offset === undefined) {
    encoding = 'utf8'
    length = this.length
    offset = 0
  // Buffer#write(string, encoding)
  } else if (length === undefined && typeof offset === 'string') {
    encoding = offset
    length = this.length
    offset = 0
  // Buffer#write(string, offset[, length][, encoding])
  } else if (isFinite(offset)) {
    offset = offset >>> 0
    if (isFinite(length)) {
      length = length >>> 0
      if (encoding === undefined) encoding = 'utf8'
    } else {
      encoding = length
      length = undefined
    }
  } else {
    throw new Error(
      'Buffer.write(string, encoding, offset[, length]) is no longer supported'
    )
  }

  var remaining = this.length - offset
  if (length === undefined || length > remaining) length = remaining

  if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
    throw new RangeError('Attempt to write outside buffer bounds')
  }

  if (!encoding) encoding = 'utf8'

  var loweredCase = false
  for (;;) {
    switch (encoding) {
      case 'hex':
        return hexWrite(this, string, offset, length)

      case 'utf8':
      case 'utf-8':
        return utf8Write(this, string, offset, length)

      case 'ascii':
        return asciiWrite(this, string, offset, length)

      case 'latin1':
      case 'binary':
        return latin1Write(this, string, offset, length)

      case 'base64':
        // Warning: maxLength not taken into account in base64Write
        return base64Write(this, string, offset, length)

      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return ucs2Write(this, string, offset, length)

      default:
        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
        encoding = ('' + encoding).toLowerCase()
        loweredCase = true
    }
  }
}

Buffer.prototype.toJSON = function toJSON () {
  return {
    type: 'Buffer',
    data: Array.prototype.slice.call(this._arr || this, 0)
  }
}

function base64Slice (buf, start, end) {
  if (start === 0 && end === buf.length) {
    return base64.fromByteArray(buf)
  } else {
    return base64.fromByteArray(buf.slice(start, end))
  }
}

function utf8Slice (buf, start, end) {
  end = Math.min(buf.length, end)
  var res = []

  var i = start
  while (i < end) {
    var firstByte = buf[i]
    var codePoint = null
    var bytesPerSequence = (firstByte > 0xEF) ? 4
      : (firstByte > 0xDF) ? 3
        : (firstByte > 0xBF) ? 2
          : 1

    if (i + bytesPerSequence <= end) {
      var secondByte, thirdByte, fourthByte, tempCodePoint

      switch (bytesPerSequence) {
        case 1:
          if (firstByte < 0x80) {
            codePoint = firstByte
          }
          break
        case 2:
          secondByte = buf[i + 1]
          if ((secondByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
            if (tempCodePoint > 0x7F) {
              codePoint = tempCodePoint
            }
          }
          break
        case 3:
          secondByte = buf[i + 1]
          thirdByte = buf[i + 2]
          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
            if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
              codePoint = tempCodePoint
            }
          }
          break
        case 4:
          secondByte = buf[i + 1]
          thirdByte = buf[i + 2]
          fourthByte = buf[i + 3]
          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
            if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
              codePoint = tempCodePoint
            }
          }
      }
    }

    if (codePoint === null) {
      // we did not generate a valid codePoint so insert a
      // replacement char (U+FFFD) and advance only 1 byte
      codePoint = 0xFFFD
      bytesPerSequence = 1
    } else if (codePoint > 0xFFFF) {
      // encode to utf16 (surrogate pair dance)
      codePoint -= 0x10000
      res.push(codePoint >>> 10 & 0x3FF | 0xD800)
      codePoint = 0xDC00 | codePoint & 0x3FF
    }

    res.push(codePoint)
    i += bytesPerSequence
  }

  return decodeCodePointsArray(res)
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000

function decodeCodePointsArray (codePoints) {
  var len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }

  // Decode in chunks to avoid "call stack size exceeded".
  var res = ''
  var i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}

function asciiSlice (buf, start, end) {
  var ret = ''
  end = Math.min(buf.length, end)

  for (var i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i] & 0x7F)
  }
  return ret
}

function latin1Slice (buf, start, end) {
  var ret = ''
  end = Math.min(buf.length, end)

  for (var i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i])
  }
  return ret
}

function hexSlice (buf, start, end) {
  var len = buf.length

  if (!start || start < 0) start = 0
  if (!end || end < 0 || end > len) end = len

  var out = ''
  for (var i = start; i < end; ++i) {
    out += toHex(buf[i])
  }
  return out
}

function utf16leSlice (buf, start, end) {
  var bytes = buf.slice(start, end)
  var res = ''
  for (var i = 0; i < bytes.length; i += 2) {
    res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  }
  return res
}

Buffer.prototype.slice = function slice (start, end) {
  var len = this.length
  start = ~~start
  end = end === undefined ? len : ~~end

  if (start < 0) {
    start += len
    if (start < 0) start = 0
  } else if (start > len) {
    start = len
  }

  if (end < 0) {
    end += len
    if (end < 0) end = 0
  } else if (end > len) {
    end = len
  }

  if (end < start) end = start

  var newBuf = this.subarray(start, end)
  // Return an augmented `Uint8Array` instance
  newBuf.__proto__ = Buffer.prototype
  return newBuf
}

/*
 * Need to make sure that buffer isn't trying to write out of bounds.
 */
function checkOffset (offset, ext, length) {
  if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}

Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  var val = this[offset]
  var mul = 1
  var i = 0
  while (++i < byteLength && (mul *= 0x100)) {
    val += this[offset + i] * mul
  }

  return val
}

Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) {
    checkOffset(offset, byteLength, this.length)
  }

  var val = this[offset + --byteLength]
  var mul = 1
  while (byteLength > 0 && (mul *= 0x100)) {
    val += this[offset + --byteLength] * mul
  }

  return val
}

Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 1, this.length)
  return this[offset]
}

Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  return this[offset] | (this[offset + 1] << 8)
}

Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  return (this[offset] << 8) | this[offset + 1]
}

Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return ((this[offset]) |
      (this[offset + 1] << 8) |
      (this[offset + 2] << 16)) +
      (this[offset + 3] * 0x1000000)
}

Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset] * 0x1000000) +
    ((this[offset + 1] << 16) |
    (this[offset + 2] << 8) |
    this[offset + 3])
}

Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  var val = this[offset]
  var mul = 1
  var i = 0
  while (++i < byteLength && (mul *= 0x100)) {
    val += this[offset + i] * mul
  }
  mul *= 0x80

  if (val >= mul) val -= Math.pow(2, 8 * byteLength)

  return val
}

Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  var i = byteLength
  var mul = 1
  var val = this[offset + --i]
  while (i > 0 && (mul *= 0x100)) {
    val += this[offset + --i] * mul
  }
  mul *= 0x80

  if (val >= mul) val -= Math.pow(2, 8 * byteLength)

  return val
}

Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 1, this.length)
  if (!(this[offset] & 0x80)) return (this[offset])
  return ((0xff - this[offset] + 1) * -1)
}

Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  var val = this[offset] | (this[offset + 1] << 8)
  return (val & 0x8000) ? val | 0xFFFF0000 : val
}

Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  var val = this[offset + 1] | (this[offset] << 8)
  return (val & 0x8000) ? val | 0xFFFF0000 : val
}

Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset]) |
    (this[offset + 1] << 8) |
    (this[offset + 2] << 16) |
    (this[offset + 3] << 24)
}

Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset] << 24) |
    (this[offset + 1] << 16) |
    (this[offset + 2] << 8) |
    (this[offset + 3])
}

Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)
  return ieee754.read(this, offset, true, 23, 4)
}

Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)
  return ieee754.read(this, offset, false, 23, 4)
}

Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 8, this.length)
  return ieee754.read(this, offset, true, 52, 8)
}

Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 8, this.length)
  return ieee754.read(this, offset, false, 52, 8)
}

function checkInt (buf, value, offset, ext, max, min) {
  if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  if (offset + ext > buf.length) throw new RangeError('Index out of range')
}

Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) {
    var maxBytes = Math.pow(2, 8 * byteLength) - 1
    checkInt(this, value, offset, byteLength, maxBytes, 0)
  }

  var mul = 1
  var i = 0
  this[offset] = value & 0xFF
  while (++i < byteLength && (mul *= 0x100)) {
    this[offset + i] = (value / mul) & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) {
    var maxBytes = Math.pow(2, 8 * byteLength) - 1
    checkInt(this, value, offset, byteLength, maxBytes, 0)
  }

  var i = byteLength - 1
  var mul = 1
  this[offset + i] = value & 0xFF
  while (--i >= 0 && (mul *= 0x100)) {
    this[offset + i] = (value / mul) & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  this[offset] = (value & 0xff)
  return offset + 1
}

Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  this[offset] = (value & 0xff)
  this[offset + 1] = (value >>> 8)
  return offset + 2
}

Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  this[offset] = (value >>> 8)
  this[offset + 1] = (value & 0xff)
  return offset + 2
}

Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  this[offset + 3] = (value >>> 24)
  this[offset + 2] = (value >>> 16)
  this[offset + 1] = (value >>> 8)
  this[offset] = (value & 0xff)
  return offset + 4
}

Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  this[offset] = (value >>> 24)
  this[offset + 1] = (value >>> 16)
  this[offset + 2] = (value >>> 8)
  this[offset + 3] = (value & 0xff)
  return offset + 4
}

Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    var limit = Math.pow(2, (8 * byteLength) - 1)

    checkInt(this, value, offset, byteLength, limit - 1, -limit)
  }

  var i = 0
  var mul = 1
  var sub = 0
  this[offset] = value & 0xFF
  while (++i < byteLength && (mul *= 0x100)) {
    if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
      sub = 1
    }
    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    var limit = Math.pow(2, (8 * byteLength) - 1)

    checkInt(this, value, offset, byteLength, limit - 1, -limit)
  }

  var i = byteLength - 1
  var mul = 1
  var sub = 0
  this[offset + i] = value & 0xFF
  while (--i >= 0 && (mul *= 0x100)) {
    if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
      sub = 1
    }
    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  if (value < 0) value = 0xff + value + 1
  this[offset] = (value & 0xff)
  return offset + 1
}

Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  this[offset] = (value & 0xff)
  this[offset + 1] = (value >>> 8)
  return offset + 2
}

Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  this[offset] = (value >>> 8)
  this[offset + 1] = (value & 0xff)
  return offset + 2
}

Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  this[offset] = (value & 0xff)
  this[offset + 1] = (value >>> 8)
  this[offset + 2] = (value >>> 16)
  this[offset + 3] = (value >>> 24)
  return offset + 4
}

Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  if (value < 0) value = 0xffffffff + value + 1
  this[offset] = (value >>> 24)
  this[offset + 1] = (value >>> 16)
  this[offset + 2] = (value >>> 8)
  this[offset + 3] = (value & 0xff)
  return offset + 4
}

function checkIEEE754 (buf, value, offset, ext, max, min) {
  if (offset + ext > buf.length) throw new RangeError('Index out of range')
  if (offset < 0) throw new RangeError('Index out of range')
}

function writeFloat (buf, value, offset, littleEndian, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  }
  ieee754.write(buf, value, offset, littleEndian, 23, 4)
  return offset + 4
}

Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  return writeFloat(this, value, offset, true, noAssert)
}

Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  return writeFloat(this, value, offset, false, noAssert)
}

function writeDouble (buf, value, offset, littleEndian, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  }
  ieee754.write(buf, value, offset, littleEndian, 52, 8)
  return offset + 8
}

Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  return writeDouble(this, value, offset, true, noAssert)
}

Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  return writeDouble(this, value, offset, false, noAssert)
}

// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  if (!start) start = 0
  if (!end && end !== 0) end = this.length
  if (targetStart >= target.length) targetStart = target.length
  if (!targetStart) targetStart = 0
  if (end > 0 && end < start) end = start

  // Copy 0 bytes; we're done
  if (end === start) return 0
  if (target.length === 0 || this.length === 0) return 0

  // Fatal error conditions
  if (targetStart < 0) {
    throw new RangeError('targetStart out of bounds')
  }
  if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  if (end < 0) throw new RangeError('sourceEnd out of bounds')

  // Are we oob?
  if (end > this.length) end = this.length
  if (target.length - targetStart < end - start) {
    end = target.length - targetStart + start
  }

  var len = end - start

  if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
    // Use built-in when available, missing from IE11
    this.copyWithin(targetStart, start, end)
  } else if (this === target && start < targetStart && targetStart < end) {
    // descending copy from end
    for (var i = len - 1; i >= 0; --i) {
      target[i + targetStart] = this[i + start]
    }
  } else {
    Uint8Array.prototype.set.call(
      target,
      this.subarray(start, end),
      targetStart
    )
  }

  return len
}

// Usage:
//    buffer.fill(number[, offset[, end]])
//    buffer.fill(buffer[, offset[, end]])
//    buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
  // Handle string cases:
  if (typeof val === 'string') {
    if (typeof start === 'string') {
      encoding = start
      start = 0
      end = this.length
    } else if (typeof end === 'string') {
      encoding = end
      end = this.length
    }
    if (encoding !== undefined && typeof encoding !== 'string') {
      throw new TypeError('encoding must be a string')
    }
    if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
      throw new TypeError('Unknown encoding: ' + encoding)
    }
    if (val.length === 1) {
      var code = val.charCodeAt(0)
      if ((encoding === 'utf8' && code < 128) ||
          encoding === 'latin1') {
        // Fast path: If `val` fits into a single byte, use that numeric value.
        val = code
      }
    }
  } else if (typeof val === 'number') {
    val = val & 255
  }

  // Invalid ranges are not set to a default, so can range check early.
  if (start < 0 || this.length < start || this.length < end) {
    throw new RangeError('Out of range index')
  }

  if (end <= start) {
    return this
  }

  start = start >>> 0
  end = end === undefined ? this.length : end >>> 0

  if (!val) val = 0

  var i
  if (typeof val === 'number') {
    for (i = start; i < end; ++i) {
      this[i] = val
    }
  } else {
    var bytes = Buffer.isBuffer(val)
      ? val
      : Buffer.from(val, encoding)
    var len = bytes.length
    if (len === 0) {
      throw new TypeError('The value "' + val +
        '" is invalid for argument "value"')
    }
    for (i = 0; i < end - start; ++i) {
      this[i + start] = bytes[i % len]
    }
  }

  return this
}

// HELPER FUNCTIONS
// ================

var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g

function base64clean (str) {
  // Node takes equal signs as end of the Base64 encoding
  str = str.split('=')[0]
  // Node strips out invalid characters like \n and \t from the string, base64-js does not
  str = str.trim().replace(INVALID_BASE64_RE, '')
  // Node converts strings with length < 2 to ''
  if (str.length < 2) return ''
  // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  while (str.length % 4 !== 0) {
    str = str + '='
  }
  return str
}

function toHex (n) {
  if (n < 16) return '0' + n.toString(16)
  return n.toString(16)
}

function utf8ToBytes (string, units) {
  units = units || Infinity
  var codePoint
  var length = string.length
  var leadSurrogate = null
  var bytes = []

  for (var i = 0; i < length; ++i) {
    codePoint = string.charCodeAt(i)

    // is surrogate component
    if (codePoint > 0xD7FF && codePoint < 0xE000) {
      // last char was a lead
      if (!leadSurrogate) {
        // no lead yet
        if (codePoint > 0xDBFF) {
          // unexpected trail
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
          continue
        } else if (i + 1 === length) {
          // unpaired lead
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
          continue
        }

        // valid lead
        leadSurrogate = codePoint

        continue
      }

      // 2 leads in a row
      if (codePoint < 0xDC00) {
        if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
        leadSurrogate = codePoint
        continue
      }

      // valid surrogate pair
      codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
    } else if (leadSurrogate) {
      // valid bmp char, but last char was a lead
      if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
    }

    leadSurrogate = null

    // encode utf8
    if (codePoint < 0x80) {
      if ((units -= 1) < 0) break
      bytes.push(codePoint)
    } else if (codePoint < 0x800) {
      if ((units -= 2) < 0) break
      bytes.push(
        codePoint >> 0x6 | 0xC0,
        codePoint & 0x3F | 0x80
      )
    } else if (codePoint < 0x10000) {
      if ((units -= 3) < 0) break
      bytes.push(
        codePoint >> 0xC | 0xE0,
        codePoint >> 0x6 & 0x3F | 0x80,
        codePoint & 0x3F | 0x80
      )
    } else if (codePoint < 0x110000) {
      if ((units -= 4) < 0) break
      bytes.push(
        codePoint >> 0x12 | 0xF0,
        codePoint >> 0xC & 0x3F | 0x80,
        codePoint >> 0x6 & 0x3F | 0x80,
        codePoint & 0x3F | 0x80
      )
    } else {
      throw new Error('Invalid code point')
    }
  }

  return bytes
}

function asciiToBytes (str) {
  var byteArray = []
  for (var i = 0; i < str.length; ++i) {
    // Node's code seems to be doing this and not & 0x7F..
    byteArray.push(str.charCodeAt(i) & 0xFF)
  }
  return byteArray
}

function utf16leToBytes (str, units) {
  var c, hi, lo
  var byteArray = []
  for (var i = 0; i < str.length; ++i) {
    if ((units -= 2) < 0) break

    c = str.charCodeAt(i)
    hi = c >> 8
    lo = c % 256
    byteArray.push(lo)
    byteArray.push(hi)
  }

  return byteArray
}

function base64ToBytes (str) {
  return base64.toByteArray(base64clean(str))
}

function blitBuffer (src, dst, offset, length) {
  for (var i = 0; i < length; ++i) {
    if ((i + offset >= dst.length) || (i >= src.length)) break
    dst[i + offset] = src[i]
  }
  return i
}

// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
// the `instanceof` check but they should be treated as of that type.
// See: https://github.com/feross/buffer/issues/166
function isInstance (obj, type) {
  return obj instanceof type ||
    (obj != null && obj.constructor != null && obj.constructor.name != null &&
      obj.constructor.name === type.name)
}
function numberIsNaN (obj) {
  // For IE11 support
  return obj !== obj // eslint-disable-line no-self-compare
}

},{"base64-js":62,"ieee754":401}],94:[function(_dereq_,module,exports){
'use strict'

var monotoneTriangulate = _dereq_('./lib/monotone')
var makeIndex = _dereq_('./lib/triangulation')
var delaunayFlip = _dereq_('./lib/delaunay')
var filterTriangulation = _dereq_('./lib/filter')

module.exports = cdt2d

function canonicalizeEdge(e) {
  return [Math.min(e[0], e[1]), Math.max(e[0], e[1])]
}

function compareEdge(a, b) {
  return a[0]-b[0] || a[1]-b[1]
}

function canonicalizeEdges(edges) {
  return edges.map(canonicalizeEdge).sort(compareEdge)
}

function getDefault(options, property, dflt) {
  if(property in options) {
    return options[property]
  }
  return dflt
}

function cdt2d(points, edges, options) {

  if(!Array.isArray(edges)) {
    options = edges || {}
    edges = []
  } else {
    options = options || {}
    edges = edges || []
  }

  //Parse out options
  var delaunay = !!getDefault(options, 'delaunay', true)
  var interior = !!getDefault(options, 'interior', true)
  var exterior = !!getDefault(options, 'exterior', true)
  var infinity = !!getDefault(options, 'infinity', false)

  //Handle trivial case
  if((!interior && !exterior) || points.length === 0) {
    return []
  }

  //Construct initial triangulation
  var cells = monotoneTriangulate(points, edges)

  //If delaunay refinement needed, then improve quality by edge flipping
  if(delaunay || interior !== exterior || infinity) {

    //Index all of the cells to support fast neighborhood queries
    var triangulation = makeIndex(points.length, canonicalizeEdges(edges))
    for(var i=0; i<cells.length; ++i) {
      var f = cells[i]
      triangulation.addTriangle(f[0], f[1], f[2])
    }

    //Run edge flipping
    if(delaunay) {
      delaunayFlip(points, triangulation)
    }

    //Filter points
    if(!exterior) {
      return filterTriangulation(triangulation, -1)
    } else if(!interior) {
      return filterTriangulation(triangulation,  1, infinity)
    } else if(infinity) {
      return filterTriangulation(triangulation, 0, infinity)
    } else {
      return triangulation.cells()
    }
    
  } else {
    return cells
  }
}

},{"./lib/delaunay":95,"./lib/filter":96,"./lib/monotone":97,"./lib/triangulation":98}],95:[function(_dereq_,module,exports){
'use strict'

var inCircle = _dereq_('robust-in-sphere')[4]
var bsearch = _dereq_('binary-search-bounds')

module.exports = delaunayRefine

function testFlip(points, triangulation, stack, a, b, x) {
  var y = triangulation.opposite(a, b)

  //Test boundary edge
  if(y < 0) {
    return
  }

  //Swap edge if order flipped
  if(b < a) {
    var tmp = a
    a = b
    b = tmp
    tmp = x
    x = y
    y = tmp
  }

  //Test if edge is constrained
  if(triangulation.isConstraint(a, b)) {
    return
  }

  //Test if edge is delaunay
  if(inCircle(points[a], points[b], points[x], points[y]) < 0) {
    stack.push(a, b)
  }
}

//Assume edges are sorted lexicographically
function delaunayRefine(points, triangulation) {
  var stack = []

  var numPoints = points.length
  var stars = triangulation.stars
  for(var a=0; a<numPoints; ++a) {
    var star = stars[a]
    for(var j=1; j<star.length; j+=2) {
      var b = star[j]

      //If order is not consistent, then skip edge
      if(b < a) {
        continue
      }

      //Check if edge is constrained
      if(triangulation.isConstraint(a, b)) {
        continue
      }

      //Find opposite edge
      var x = star[j-1], y = -1
      for(var k=1; k<star.length; k+=2) {
        if(star[k-1] === b) {
          y = star[k]
          break
        }
      }

      //If this is a boundary edge, don't flip it
      if(y < 0) {
        continue
      }

      //If edge is in circle, flip it
      if(inCircle(points[a], points[b], points[x], points[y]) < 0) {
        stack.push(a, b)
      }
    }
  }

  while(stack.length > 0) {
    var b = stack.pop()
    var a = stack.pop()

    //Find opposite pairs
    var x = -1, y = -1
    var star = stars[a]
    for(var i=1; i<star.length; i+=2) {
      var s = star[i-1]
      var t = star[i]
      if(s === b) {
        y = t
      } else if(t === b) {
        x = s
      }
    }

    //If x/y are both valid then skip edge
    if(x < 0 || y < 0) {
      continue
    }

    //If edge is now delaunay, then don't flip it
    if(inCircle(points[a], points[b], points[x], points[y]) >= 0) {
      continue
    }

    //Flip the edge
    triangulation.flip(a, b)

    //Test flipping neighboring edges
    testFlip(points, triangulation, stack, x, a, y)
    testFlip(points, triangulation, stack, a, y, x)
    testFlip(points, triangulation, stack, y, b, x)
    testFlip(points, triangulation, stack, b, x, y)
  }
}

},{"binary-search-bounds":99,"robust-in-sphere":489}],96:[function(_dereq_,module,exports){
'use strict'

var bsearch = _dereq_('binary-search-bounds')

module.exports = classifyFaces

function FaceIndex(cells, neighbor, constraint, flags, active, next, boundary) {
  this.cells       = cells
  this.neighbor    = neighbor
  this.flags       = flags
  this.constraint  = constraint
  this.active      = active
  this.next        = next
  this.boundary    = boundary
}

var proto = FaceIndex.prototype

function compareCell(a, b) {
  return a[0] - b[0] ||
         a[1] - b[1] ||
         a[2] - b[2]
}

proto.locate = (function() {
  var key = [0,0,0]
  return function(a, b, c) {
    var x = a, y = b, z = c
    if(b < c) {
      if(b < a) {
        x = b
        y = c
        z = a
      }
    } else if(c < a) {
      x = c
      y = a
      z = b
    }
    if(x < 0) {
      return -1
    }
    key[0] = x
    key[1] = y
    key[2] = z
    return bsearch.eq(this.cells, key, compareCell)
  }
})()

function indexCells(triangulation, infinity) {
  //First get cells and canonicalize
  var cells = triangulation.cells()
  var nc = cells.length
  for(var i=0; i<nc; ++i) {
    var c = cells[i]
    var x = c[0], y = c[1], z = c[2]
    if(y < z) {
      if(y < x) {
        c[0] = y
        c[1] = z
        c[2] = x
      }
    } else if(z < x) {
      c[0] = z
      c[1] = x
      c[2] = y
    }
  }
  cells.sort(compareCell)

  //Initialize flag array
  var flags = new Array(nc)
  for(var i=0; i<flags.length; ++i) {
    flags[i] = 0
  }

  //Build neighbor index, initialize queues
  var active = []
  var next   = []
  var neighbor = new Array(3*nc)
  var constraint = new Array(3*nc)
  var boundary = null
  if(infinity) {
    boundary = []
  }
  var index = new FaceIndex(
    cells,
    neighbor,
    constraint,
    flags,
    active,
    next,
    boundary)
  for(var i=0; i<nc; ++i) {
    var c = cells[i]
    for(var j=0; j<3; ++j) {
      var x = c[j], y = c[(j+1)%3]
      var a = neighbor[3*i+j] = index.locate(y, x, triangulation.opposite(y, x))
      var b = constraint[3*i+j] = triangulation.isConstraint(x, y)
      if(a < 0) {
        if(b) {
          next.push(i)
        } else {
          active.push(i)
          flags[i] = 1
        }
        if(infinity) {
          boundary.push([y, x, -1])
        }
      }
    }
  }
  return index
}

function filterCells(cells, flags, target) {
  var ptr = 0
  for(var i=0; i<cells.length; ++i) {
    if(flags[i] === target) {
      cells[ptr++] = cells[i]
    }
  }
  cells.length = ptr
  return cells
}

function classifyFaces(triangulation, target, infinity) {
  var index = indexCells(triangulation, infinity)

  if(target === 0) {
    if(infinity) {
      return index.cells.concat(index.boundary)
    } else {
      return index.cells
    }
  }

  var side = 1
  var active = index.active
  var next = index.next
  var flags = index.flags
  var cells = index.cells
  var constraint = index.constraint
  var neighbor = index.neighbor

  while(active.length > 0 || next.length > 0) {
    while(active.length > 0) {
      var t = active.pop()
      if(flags[t] === -side) {
        continue
      }
      flags[t] = side
      var c = cells[t]
      for(var j=0; j<3; ++j) {
        var f = neighbor[3*t+j]
        if(f >= 0 && flags[f] === 0) {
          if(constraint[3*t+j]) {
            next.push(f)
          } else {
            active.push(f)
            flags[f] = side
          }
        }
      }
    }

    //Swap arrays and loop
    var tmp = next
    next = active
    active = tmp
    next.length = 0
    side = -side
  }

  var result = filterCells(cells, flags, target)
  if(infinity) {
    return result.concat(index.boundary)
  }
  return result
}

},{"binary-search-bounds":99}],97:[function(_dereq_,module,exports){
'use strict'

var bsearch = _dereq_('binary-search-bounds')
var orient = _dereq_('robust-orientation')[3]

var EVENT_POINT = 0
var EVENT_END   = 1
var EVENT_START = 2

module.exports = monotoneTriangulate

//A partial convex hull fragment, made of two unimonotone polygons
function PartialHull(a, b, idx, lowerIds, upperIds) {
  this.a = a
  this.b = b
  this.idx = idx
  this.lowerIds = lowerIds
  this.upperIds = upperIds
}

//An event in the sweep line procedure
function Event(a, b, type, idx) {
  this.a    = a
  this.b    = b
  this.type = type
  this.idx  = idx
}

//This is used to compare events for the sweep line procedure
// Points are:
//  1. sorted lexicographically
//  2. sorted by type  (point < end < start)
//  3. segments sorted by winding order
//  4. sorted by index
function compareEvent(a, b) {
  var d =
    (a.a[0] - b.a[0]) ||
    (a.a[1] - b.a[1]) ||
    (a.type - b.type)
  if(d) { return d }
  if(a.type !== EVENT_POINT) {
    d = orient(a.a, a.b, b.b)
    if(d) { return d }
  }
  return a.idx - b.idx
}

function testPoint(hull, p) {
  return orient(hull.a, hull.b, p)
}

function addPoint(cells, hulls, points, p, idx) {
  var lo = bsearch.lt(hulls, p, testPoint)
  var hi = bsearch.gt(hulls, p, testPoint)
  for(var i=lo; i<hi; ++i) {
    var hull = hulls[i]

    //Insert p into lower hull
    var lowerIds = hull.lowerIds
    var m = lowerIds.length
    while(m > 1 && orient(
        points[lowerIds[m-2]],
        points[lowerIds[m-1]],
        p) > 0) {
      cells.push(
        [lowerIds[m-1],
         lowerIds[m-2],
         idx])
      m -= 1
    }
    lowerIds.length = m
    lowerIds.push(idx)

    //Insert p into upper hull
    var upperIds = hull.upperIds
    var m = upperIds.length
    while(m > 1 && orient(
        points[upperIds[m-2]],
        points[upperIds[m-1]],
        p) < 0) {
      cells.push(
        [upperIds[m-2],
         upperIds[m-1],
         idx])
      m -= 1
    }
    upperIds.length = m
    upperIds.push(idx)
  }
}

function findSplit(hull, edge) {
  var d
  if(hull.a[0] < edge.a[0]) {
    d = orient(hull.a, hull.b, edge.a)
  } else {
    d = orient(edge.b, edge.a, hull.a)
  }
  if(d) { return d }
  if(edge.b[0] < hull.b[0]) {
    d = orient(hull.a, hull.b, edge.b)
  } else {
    d = orient(edge.b, edge.a, hull.b)
  }
  return d || hull.idx - edge.idx
}

function splitHulls(hulls, points, event) {
  var splitIdx = bsearch.le(hulls, event, findSplit)
  var hull = hulls[splitIdx]
  var upperIds = hull.upperIds
  var x = upperIds[upperIds.length-1]
  hull.upperIds = [x]
  hulls.splice(splitIdx+1, 0,
    new PartialHull(event.a, event.b, event.idx, [x], upperIds))
}


function mergeHulls(hulls, points, event) {
  //Swap pointers for merge search
  var tmp = event.a
  event.a = event.b
  event.b = tmp
  var mergeIdx = bsearch.eq(hulls, event, findSplit)
  var upper = hulls[mergeIdx]
  var lower = hulls[mergeIdx-1]
  lower.upperIds = upper.upperIds
  hulls.splice(mergeIdx, 1)
}


function monotoneTriangulate(points, edges) {

  var numPoints = points.length
  var numEdges = edges.length

  var events = []

  //Create point events
  for(var i=0; i<numPoints; ++i) {
    events.push(new Event(
      points[i],
      null,
      EVENT_POINT,
      i))
  }

  //Create edge events
  for(var i=0; i<numEdges; ++i) {
    var e = edges[i]
    var a = points[e[0]]
    var b = points[e[1]]
    if(a[0] < b[0]) {
      events.push(
        new Event(a, b, EVENT_START, i),
        new Event(b, a, EVENT_END, i))
    } else if(a[0] > b[0]) {
      events.push(
        new Event(b, a, EVENT_START, i),
        new Event(a, b, EVENT_END, i))
    }
  }

  //Sort events
  events.sort(compareEvent)

  //Initialize hull
  var minX = events[0].a[0] - (1 + Math.abs(events[0].a[0])) * Math.pow(2, -52)
  var hull = [ new PartialHull([minX, 1], [minX, 0], -1, [], [], [], []) ]

  //Process events in order
  var cells = []
  for(var i=0, numEvents=events.length; i<numEvents; ++i) {
    var event = events[i]
    var type = event.type
    if(type === EVENT_POINT) {
      addPoint(cells, hull, points, event.a, event.idx)
    } else if(type === EVENT_START) {
      splitHulls(hull, points, event)
    } else {
      mergeHulls(hull, points, event)
    }
  }

  //Return triangulation
  return cells
}

},{"binary-search-bounds":99,"robust-orientation":491}],98:[function(_dereq_,module,exports){
'use strict'

var bsearch = _dereq_('binary-search-bounds')

module.exports = createTriangulation

function Triangulation(stars, edges) {
  this.stars = stars
  this.edges = edges
}

var proto = Triangulation.prototype

function removePair(list, j, k) {
  for(var i=1, n=list.length; i<n; i+=2) {
    if(list[i-1] === j && list[i] === k) {
      list[i-1] = list[n-2]
      list[i] = list[n-1]
      list.length = n - 2
      return
    }
  }
}

proto.isConstraint = (function() {
  var e = [0,0]
  function compareLex(a, b) {
    return a[0] - b[0] || a[1] - b[1]
  }
  return function(i, j) {
    e[0] = Math.min(i,j)
    e[1] = Math.max(i,j)
    return bsearch.eq(this.edges, e, compareLex) >= 0
  }
})()

proto.removeTriangle = function(i, j, k) {
  var stars = this.stars
  removePair(stars[i], j, k)
  removePair(stars[j], k, i)
  removePair(stars[k], i, j)
}

proto.addTriangle = function(i, j, k) {
  var stars = this.stars
  stars[i].push(j, k)
  stars[j].push(k, i)
  stars[k].push(i, j)
}

proto.opposite = function(j, i) {
  var list = this.stars[i]
  for(var k=1, n=list.length; k<n; k+=2) {
    if(list[k] === j) {
      return list[k-1]
    }
  }
  return -1
}

proto.flip = function(i, j) {
  var a = this.opposite(i, j)
  var b = this.opposite(j, i)
  this.removeTriangle(i, j, a)
  this.removeTriangle(j, i, b)
  this.addTriangle(i, b, a)
  this.addTriangle(j, a, b)
}

proto.edges = function() {
  var stars = this.stars
  var result = []
  for(var i=0, n=stars.length; i<n; ++i) {
    var list = stars[i]
    for(var j=0, m=list.length; j<m; j+=2) {
      result.push([list[j], list[j+1]])
    }
  }
  return result
}

proto.cells = function() {
  var stars = this.stars
  var result = []
  for(var i=0, n=stars.length; i<n; ++i) {
    var list = stars[i]
    for(var j=0, m=list.length; j<m; j+=2) {
      var s = list[j]
      var t = list[j+1]
      if(i < Math.min(s, t)) {
        result.push([i, s, t])
      }
    }
  }
  return result
}

function createTriangulation(numVerts, edges) {
  var stars = new Array(numVerts)
  for(var i=0; i<numVerts; ++i) {
    stars[i] = []
  }
  return new Triangulation(stars, edges)
}

},{"binary-search-bounds":99}],99:[function(_dereq_,module,exports){
"use strict"

function compileSearch(funcName, predicate, reversed, extraArgs, earlyOut) {
  var code = [
    "function ", funcName, "(a,l,h,", extraArgs.join(","),  "){",
    earlyOut ? "" : "var i=", (reversed ? "l-1" : "h+1"),
    ";while(l<=h){var m=(l+h)>>>1,x=a[m]"]
  if(earlyOut) {
    if(predicate.indexOf("c") < 0) {
      code.push(";if(x===y){return m}else if(x<=y){")
    } else {
      code.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){")
    }
  } else {
    code.push(";if(", predicate, "){i=m;")
  }
  if(reversed) {
    code.push("l=m+1}else{h=m-1}")
  } else {
    code.push("h=m-1}else{l=m+1}")
  }
  code.push("}")
  if(earlyOut) {
    code.push("return -1};")
  } else {
    code.push("return i};")
  }
  return code.join("")
}

function compileBoundsSearch(predicate, reversed, suffix, earlyOut) {
  var result = new Function([
  compileSearch("A", "x" + predicate + "y", reversed, ["y"], earlyOut),
  compileSearch("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut),
"function dispatchBsearch", suffix, "(a,y,c,l,h){\
if(typeof(c)==='function'){\
return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\
}else{\
return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\
}}\
return dispatchBsearch", suffix].join(""))
  return result()
}

module.exports = {
  ge: compileBoundsSearch(">=", false,  "GE"),
  gt: compileBoundsSearch(">",  false,  "GT"),
  lt: compileBoundsSearch("<",  true,   "LT"),
  le: compileBoundsSearch("<=", true,   "LE"),
  eq: compileBoundsSearch("-",  true,   "EQ", true)
}

},{}],100:[function(_dereq_,module,exports){
'use strict'

module.exports = orientation

function orientation(s) {
  var p = 1
  for(var i=1; i<s.length; ++i) {
    for(var j=0; j<i; ++j) {
      if(s[i] < s[j]) {
        p = -p
      } else if(s[j] === s[i]) {
        return 0
      }
    }
  }
  return p
}

},{}],101:[function(_dereq_,module,exports){
"use strict"

var dup = _dereq_("dup")
var solve = _dereq_("robust-linear-solve")

function dot(a, b) {
  var s = 0.0
  var d = a.length
  for(var i=0; i<d; ++i) {
    s += a[i] * b[i]
  }
  return s
}

function barycentricCircumcenter(points) {
  var N = points.length
  if(N === 0) {
    return []
  }
  
  var D = points[0].length
  var A = dup([points.length+1, points.length+1], 1.0)
  var b = dup([points.length+1], 1.0)
  A[N][N] = 0.0
  for(var i=0; i<N; ++i) {
    for(var j=0; j<=i; ++j) {
      A[j][i] = A[i][j] = 2.0 * dot(points[i], points[j])
    }
    b[i] = dot(points[i], points[i])
  }
  var x = solve(A, b)

  var denom = 0.0
  var h = x[N+1]
  for(var i=0; i<h.length; ++i) {
    denom += h[i]
  }

  var y = new Array(N)
  for(var i=0; i<N; ++i) {
    var h = x[i]
    var numer = 0.0
    for(var j=0; j<h.length; ++j) {
      numer += h[j]
    }
    y[i] =  numer / denom
  }

  return y
}

function circumcenter(points) {
  if(points.length === 0) {
    return []
  }
  var D = points[0].length
  var result = dup([D])
  var weights = barycentricCircumcenter(points)
  for(var i=0; i<points.length; ++i) {
    for(var j=0; j<D; ++j) {
      result[j] += points[i][j] * weights[i]
    }
  }
  return result
}

circumcenter.barycenetric = barycentricCircumcenter
module.exports = circumcenter
},{"dup":158,"robust-linear-solve":490}],102:[function(_dereq_,module,exports){
module.exports = circumradius

var circumcenter = _dereq_('circumcenter')

function circumradius(points) {
  var center = circumcenter(points)
  var avgDist = 0.0
  for(var i=0; i<points.length; ++i) {
    var p = points[i]
    for(var j=0; j<center.length; ++j) {
      avgDist += Math.pow(p[j] - center[j], 2)
    }
  }
  return Math.sqrt(avgDist / points.length)
}
},{"circumcenter":101}],103:[function(_dereq_,module,exports){
module.exports = clamp

function clamp(value, min, max) {
  return min < max
    ? (value < min ? min : value > max ? max : value)
    : (value < max ? max : value > min ? min : value)
}

},{}],104:[function(_dereq_,module,exports){
'use strict'

module.exports = cleanPSLG

var UnionFind = _dereq_('union-find')
var boxIntersect = _dereq_('box-intersect')
var segseg = _dereq_('robust-segment-intersect')
var rat = _dereq_('big-rat')
var ratCmp = _dereq_('big-rat/cmp')
var ratToFloat = _dereq_('big-rat/to-float')
var ratVec = _dereq_('rat-vec')
var nextafter = _dereq_('nextafter')

var solveIntersection = _dereq_('./lib/rat-seg-intersect')

// Bounds on a rational number when rounded to a float
function boundRat (r) {
  var f = ratToFloat(r)
  return [
    nextafter(f, -Infinity),
    nextafter(f, Infinity)
  ]
}

// Convert a list of edges in a pslg to bounding boxes
function boundEdges (points, edges) {
  var bounds = new Array(edges.length)
  for (var i = 0; i < edges.length; ++i) {
    var e = edges[i]
    var a = points[e[0]]
    var b = points[e[1]]
    bounds[i] = [
      nextafter(Math.min(a[0], b[0]), -Infinity),
      nextafter(Math.min(a[1], b[1]), -Infinity),
      nextafter(Math.max(a[0], b[0]), Infinity),
      nextafter(Math.max(a[1], b[1]), Infinity)
    ]
  }
  return bounds
}

// Convert a list of points into bounding boxes by duplicating coords
function boundPoints (points) {
  var bounds = new Array(points.length)
  for (var i = 0; i < points.length; ++i) {
    var p = points[i]
    bounds[i] = [
      nextafter(p[0], -Infinity),
      nextafter(p[1], -Infinity),
      nextafter(p[0], Infinity),
      nextafter(p[1], Infinity)
    ]
  }
  return bounds
}

// Find all pairs of crossing edges in a pslg (given edge bounds)
function getCrossings (points, edges, edgeBounds) {
  var result = []
  boxIntersect(edgeBounds, function (i, j) {
    var e = edges[i]
    var f = edges[j]
    if (e[0] === f[0] || e[0] === f[1] ||
      e[1] === f[0] || e[1] === f[1]) {
      return
    }
    var a = points[e[0]]
    var b = points[e[1]]
    var c = points[f[0]]
    var d = points[f[1]]
    if (segseg(a, b, c, d)) {
      result.push([i, j])
    }
  })
  return result
}

// Find all pairs of crossing vertices in a pslg (given edge/vert bounds)
function getTJunctions (points, edges, edgeBounds, vertBounds) {
  var result = []
  boxIntersect(edgeBounds, vertBounds, function (i, v) {
    var e = edges[i]
    if (e[0] === v || e[1] === v) {
      return
    }
    var p = points[v]
    var a = points[e[0]]
    var b = points[e[1]]
    if (segseg(a, b, p, p)) {
      result.push([i, v])
    }
  })
  return result
}

// Cut edges along crossings/tjunctions
function cutEdges (floatPoints, edges, crossings, junctions, useColor) {
  var i, e

  // Convert crossings into tjunctions by constructing rational points
  var ratPoints = floatPoints.map(function(p) {
      return [
          rat(p[0]),
          rat(p[1])
      ]
  })
  for (i = 0; i < crossings.length; ++i) {
    var crossing = crossings[i]
    e = crossing[0]
    var f = crossing[1]
    var ee = edges[e]
    var ef = edges[f]
    var x = solveIntersection(
      ratVec(floatPoints[ee[0]]),
      ratVec(floatPoints[ee[1]]),
      ratVec(floatPoints[ef[0]]),
      ratVec(floatPoints[ef[1]]))
    if (!x) {
      // Segments are parallel, should already be handled by t-junctions
      continue
    }
    var idx = floatPoints.length
    floatPoints.push([ratToFloat(x[0]), ratToFloat(x[1])])
    ratPoints.push(x)
    junctions.push([e, idx], [f, idx])
  }

  // Sort tjunctions
  junctions.sort(function (a, b) {
    if (a[0] !== b[0]) {
      return a[0] - b[0]
    }
    var u = ratPoints[a[1]]
    var v = ratPoints[b[1]]
    return ratCmp(u[0], v[0]) || ratCmp(u[1], v[1])
  })

  // Split edges along junctions
  for (i = junctions.length - 1; i >= 0; --i) {
    var junction = junctions[i]
    e = junction[0]

    var edge = edges[e]
    var s = edge[0]
    var t = edge[1]

    // Check if edge is not lexicographically sorted
    var a = floatPoints[s]
    var b = floatPoints[t]
    if (((a[0] - b[0]) || (a[1] - b[1])) < 0) {
      var tmp = s
      s = t
      t = tmp
    }

    // Split leading edge
    edge[0] = s
    var last = edge[1] = junction[1]

    // If we are grouping edges by color, remember to track data
    var color
    if (useColor) {
      color = edge[2]
    }

    // Split other edges
    while (i > 0 && junctions[i - 1][0] === e) {
      var junction = junctions[--i]
      var next = junction[1]
      if (useColor) {
        edges.push([last, next, color])
      } else {
        edges.push([last, next])
      }
      last = next
    }

    // Add final edge
    if (useColor) {
      edges.push([last, t, color])
    } else {
      edges.push([last, t])
    }
  }

  // Return constructed rational points
  return ratPoints
}

// Merge overlapping points
function dedupPoints (floatPoints, ratPoints, floatBounds) {
  var numPoints = ratPoints.length
  var uf = new UnionFind(numPoints)

  // Compute rational bounds
  var bounds = []
  for (var i = 0; i < ratPoints.length; ++i) {
    var p = ratPoints[i]
    var xb = boundRat(p[0])
    var yb = boundRat(p[1])
    bounds.push([
      nextafter(xb[0], -Infinity),
      nextafter(yb[0], -Infinity),
      nextafter(xb[1], Infinity),
      nextafter(yb[1], Infinity)
    ])
  }

  // Link all points with over lapping boxes
  boxIntersect(bounds, function (i, j) {
    uf.link(i, j)
  })

  // Do 1 pass over points to combine points in label sets
  var noDupes = true
  var labels = new Array(numPoints)
  for (var i = 0; i < numPoints; ++i) {
    var j = uf.find(i)
    if (j !== i) {
      // Clear no-dupes flag, zero out label
      noDupes = false
      // Make each point the top-left point from its cell
      floatPoints[j] = [
        Math.min(floatPoints[i][0], floatPoints[j][0]),
        Math.min(floatPoints[i][1], floatPoints[j][1])
      ]
    }
  }

  // If no duplicates, return null to signal termination
  if (noDupes) {
    return null
  }

  var ptr = 0
  for (var i = 0; i < numPoints; ++i) {
    var j = uf.find(i)
    if (j === i) {
      labels[i] = ptr
      floatPoints[ptr++] = floatPoints[i]
    } else {
      labels[i] = -1
    }
  }

  floatPoints.length = ptr

  // Do a second pass to fix up missing labels
  for (var i = 0; i < numPoints; ++i) {
    if (labels[i] < 0) {
      labels[i] = labels[uf.find(i)]
    }
  }

  // Return resulting union-find data structure
  return labels
}

function compareLex2 (a, b) { return (a[0] - b[0]) || (a[1] - b[1]) }
function compareLex3 (a, b) {
  var d = (a[0] - b[0]) || (a[1] - b[1])
  if (d) {
    return d
  }
  if (a[2] < b[2]) {
    return -1
  } else if (a[2] > b[2]) {
    return 1
  }
  return 0
}

// Remove duplicate edge labels
function dedupEdges (edges, labels, useColor) {
  if (edges.length === 0) {
    return
  }
  if (labels) {
    for (var i = 0; i < edges.length; ++i) {
      var e = edges[i]
      var a = labels[e[0]]
      var b = labels[e[1]]
      e[0] = Math.min(a, b)
      e[1] = Math.max(a, b)
    }
  } else {
    for (var i = 0; i < edges.length; ++i) {
      var e = edges[i]
      var a = e[0]
      var b = e[1]
      e[0] = Math.min(a, b)
      e[1] = Math.max(a, b)
    }
  }
  if (useColor) {
    edges.sort(compareLex3)
  } else {
    edges.sort(compareLex2)
  }
  var ptr = 1
  for (var i = 1; i < edges.length; ++i) {
    var prev = edges[i - 1]
    var next = edges[i]
    if (next[0] === prev[0] && next[1] === prev[1] &&
      (!useColor || next[2] === prev[2])) {
      continue
    }
    edges[ptr++] = next
  }
  edges.length = ptr
}

function preRound (points, edges, useColor) {
  var labels = dedupPoints(points, [], boundPoints(points))
  dedupEdges(edges, labels, useColor)
  return !!labels
}

// Repeat until convergence
function snapRound (points, edges, useColor) {
  // 1. find edge crossings
  var edgeBounds = boundEdges(points, edges)
  var crossings = getCrossings(points, edges, edgeBounds)

  // 2. find t-junctions
  var vertBounds = boundPoints(points)
  var tjunctions = getTJunctions(points, edges, edgeBounds, vertBounds)

  // 3. cut edges, construct rational points
  var ratPoints = cutEdges(points, edges, crossings, tjunctions, useColor)

  // 4. dedupe verts
  var labels = dedupPoints(points, ratPoints, vertBounds)

  // 5. dedupe edges
  dedupEdges(edges, labels, useColor)

  // 6. check termination
  if (!labels) {
    return (crossings.length > 0 || tjunctions.length > 0)
  }

  // More iterations necessary
  return true
}

// Main loop, runs PSLG clean up until completion
function cleanPSLG (points, edges, colors) {
  // If using colors, augment edges with color data
  var prevEdges
  if (colors) {
    prevEdges = edges
    var augEdges = new Array(edges.length)
    for (var i = 0; i < edges.length; ++i) {
      var e = edges[i]
      augEdges[i] = [e[0], e[1], colors[i]]
    }
    edges = augEdges
  }

  // First round: remove duplicate edges and points
  var modified = preRound(points, edges, !!colors)

  // Run snap rounding until convergence
  while (snapRound(points, edges, !!colors)) {
    modified = true
  }

  // Strip color tags
  if (!!colors && modified) {
    prevEdges.length = 0
    colors.length = 0
    for (var i = 0; i < edges.length; ++i) {
      var e = edges[i]
      prevEdges.push([e[0], e[1]])
      colors.push(e[2])
    }
  }

  return modified
}

},{"./lib/rat-seg-intersect":105,"big-rat":66,"big-rat/cmp":64,"big-rat/to-float":78,"box-intersect":84,"nextafter":440,"rat-vec":475,"robust-segment-intersect":494,"union-find":527}],105:[function(_dereq_,module,exports){
'use strict'

module.exports = solveIntersection

var ratMul = _dereq_('big-rat/mul')
var ratDiv = _dereq_('big-rat/div')
var ratSub = _dereq_('big-rat/sub')
var ratSign = _dereq_('big-rat/sign')
var rvSub = _dereq_('rat-vec/sub')
var rvAdd = _dereq_('rat-vec/add')
var rvMuls = _dereq_('rat-vec/muls')

function ratPerp (a, b) {
  return ratSub(ratMul(a[0], b[1]), ratMul(a[1], b[0]))
}

// Solve for intersection
//  x = a + t (b-a)
//  (x - c) ^ (d-c) = 0
//  (t * (b-a) + (a-c) ) ^ (d-c) = 0
//  t * (b-a)^(d-c) = (d-c)^(a-c)
//  t = (d-c)^(a-c) / (b-a)^(d-c)

function solveIntersection (a, b, c, d) {
  var ba = rvSub(b, a)
  var dc = rvSub(d, c)

  var baXdc = ratPerp(ba, dc)

  if (ratSign(baXdc) === 0) {
    return null
  }

  var ac = rvSub(a, c)
  var dcXac = ratPerp(dc, ac)

  var t = ratDiv(dcXac, baXdc)
  var s = rvMuls(ba, t)
  var r = rvAdd(a, s)

  return r
}

},{"big-rat/div":65,"big-rat/mul":75,"big-rat/sign":76,"big-rat/sub":77,"rat-vec/add":474,"rat-vec/muls":476,"rat-vec/sub":477}],106:[function(_dereq_,module,exports){
/** @module  color-id */

'use strict'

var clamp = _dereq_('clamp')

module.exports = toNumber
module.exports.to = toNumber
module.exports.from = fromNumber

function toNumber (rgba, normalized) {
	if(normalized == null) normalized = true

	var r = rgba[0], g = rgba[1], b = rgba[2], a = rgba[3]

	if (a == null) a = normalized ? 1 : 255

	if (normalized) {
		r *= 255
		g *= 255
		b *= 255
		a *= 255
	}

	r = clamp(r, 0, 255) & 0xFF
	g = clamp(g, 0, 255) & 0xFF
	b = clamp(b, 0, 255) & 0xFF
	a = clamp(a, 0, 255) & 0xFF

	//hi-order shift converts to -1, so we can't use <<24
	var n = (r * 0x01000000) + (g << 16) + (b << 8) + (a)

	return n
}

function fromNumber (n, normalized) {
	n = +n

	var r = n >>> 24
	var g = (n & 0x00ff0000) >>> 16
	var b = (n & 0x0000ff00) >>> 8
	var a = n & 0x000000ff

	if (normalized === false) return [r, g, b, a]

	return [r/255, g/255, b/255, a/255]
}

},{"clamp":103}],107:[function(_dereq_,module,exports){
'use strict'

module.exports = {
	"aliceblue": [240, 248, 255],
	"antiquewhite": [250, 235, 215],
	"aqua": [0, 255, 255],
	"aquamarine": [127, 255, 212],
	"azure": [240, 255, 255],
	"beige": [245, 245, 220],
	"bisque": [255, 228, 196],
	"black": [0, 0, 0],
	"blanchedalmond": [255, 235, 205],
	"blue": [0, 0, 255],
	"blueviolet": [138, 43, 226],
	"brown": [165, 42, 42],
	"burlywood": [222, 184, 135],
	"cadetblue": [95, 158, 160],
	"chartreuse": [127, 255, 0],
	"chocolate": [210, 105, 30],
	"coral": [255, 127, 80],
	"cornflowerblue": [100, 149, 237],
	"cornsilk": [255, 248, 220],
	"crimson": [220, 20, 60],
	"cyan": [0, 255, 255],
	"darkblue": [0, 0, 139],
	"darkcyan": [0, 139, 139],
	"darkgoldenrod": [184, 134, 11],
	"darkgray": [169, 169, 169],
	"darkgreen": [0, 100, 0],
	"darkgrey": [169, 169, 169],
	"darkkhaki": [189, 183, 107],
	"darkmagenta": [139, 0, 139],
	"darkolivegreen": [85, 107, 47],
	"darkorange": [255, 140, 0],
	"darkorchid": [153, 50, 204],
	"darkred": [139, 0, 0],
	"darksalmon": [233, 150, 122],
	"darkseagreen": [143, 188, 143],
	"darkslateblue": [72, 61, 139],
	"darkslategray": [47, 79, 79],
	"darkslategrey": [47, 79, 79],
	"darkturquoise": [0, 206, 209],
	"darkviolet": [148, 0, 211],
	"deeppink": [255, 20, 147],
	"deepskyblue": [0, 191, 255],
	"dimgray": [105, 105, 105],
	"dimgrey": [105, 105, 105],
	"dodgerblue": [30, 144, 255],
	"firebrick": [178, 34, 34],
	"floralwhite": [255, 250, 240],
	"forestgreen": [34, 139, 34],
	"fuchsia": [255, 0, 255],
	"gainsboro": [220, 220, 220],
	"ghostwhite": [248, 248, 255],
	"gold": [255, 215, 0],
	"goldenrod": [218, 165, 32],
	"gray": [128, 128, 128],
	"green": [0, 128, 0],
	"greenyellow": [173, 255, 47],
	"grey": [128, 128, 128],
	"honeydew": [240, 255, 240],
	"hotpink": [255, 105, 180],
	"indianred": [205, 92, 92],
	"indigo": [75, 0, 130],
	"ivory": [255, 255, 240],
	"khaki": [240, 230, 140],
	"lavender": [230, 230, 250],
	"lavenderblush": [255, 240, 245],
	"lawngreen": [124, 252, 0],
	"lemonchiffon": [255, 250, 205],
	"lightblue": [173, 216, 230],
	"lightcoral": [240, 128, 128],
	"lightcyan": [224, 255, 255],
	"lightgoldenrodyellow": [250, 250, 210],
	"lightgray": [211, 211, 211],
	"lightgreen": [144, 238, 144],
	"lightgrey": [211, 211, 211],
	"lightpink": [255, 182, 193],
	"lightsalmon": [255, 160, 122],
	"lightseagreen": [32, 178, 170],
	"lightskyblue": [135, 206, 250],
	"lightslategray": [119, 136, 153],
	"lightslategrey": [119, 136, 153],
	"lightsteelblue": [176, 196, 222],
	"lightyellow": [255, 255, 224],
	"lime": [0, 255, 0],
	"limegreen": [50, 205, 50],
	"linen": [250, 240, 230],
	"magenta": [255, 0, 255],
	"maroon": [128, 0, 0],
	"mediumaquamarine": [102, 205, 170],
	"mediumblue": [0, 0, 205],
	"mediumorchid": [186, 85, 211],
	"mediumpurple": [147, 112, 219],
	"mediumseagreen": [60, 179, 113],
	"mediumslateblue": [123, 104, 238],
	"mediumspringgreen": [0, 250, 154],
	"mediumturquoise": [72, 209, 204],
	"mediumvioletred": [199, 21, 133],
	"midnightblue": [25, 25, 112],
	"mintcream": [245, 255, 250],
	"mistyrose": [255, 228, 225],
	"moccasin": [255, 228, 181],
	"navajowhite": [255, 222, 173],
	"navy": [0, 0, 128],
	"oldlace": [253, 245, 230],
	"olive": [128, 128, 0],
	"olivedrab": [107, 142, 35],
	"orange": [255, 165, 0],
	"orangered": [255, 69, 0],
	"orchid": [218, 112, 214],
	"palegoldenrod": [238, 232, 170],
	"palegreen": [152, 251, 152],
	"paleturquoise": [175, 238, 238],
	"palevioletred": [219, 112, 147],
	"papayawhip": [255, 239, 213],
	"peachpuff": [255, 218, 185],
	"peru": [205, 133, 63],
	"pink": [255, 192, 203],
	"plum": [221, 160, 221],
	"powderblue": [176, 224, 230],
	"purple": [128, 0, 128],
	"rebeccapurple": [102, 51, 153],
	"red": [255, 0, 0],
	"rosybrown": [188, 143, 143],
	"royalblue": [65, 105, 225],
	"saddlebrown": [139, 69, 19],
	"salmon": [250, 128, 114],
	"sandybrown": [244, 164, 96],
	"seagreen": [46, 139, 87],
	"seashell": [255, 245, 238],
	"sienna": [160, 82, 45],
	"silver": [192, 192, 192],
	"skyblue": [135, 206, 235],
	"slateblue": [106, 90, 205],
	"slategray": [112, 128, 144],
	"slategrey": [112, 128, 144],
	"snow": [255, 250, 250],
	"springgreen": [0, 255, 127],
	"steelblue": [70, 130, 180],
	"tan": [210, 180, 140],
	"teal": [0, 128, 128],
	"thistle": [216, 191, 216],
	"tomato": [255, 99, 71],
	"turquoise": [64, 224, 208],
	"violet": [238, 130, 238],
	"wheat": [245, 222, 179],
	"white": [255, 255, 255],
	"whitesmoke": [245, 245, 245],
	"yellow": [255, 255, 0],
	"yellowgreen": [154, 205, 50]
};

},{}],108:[function(_dereq_,module,exports){
/** @module  color-normalize */

'use strict'

var rgba = _dereq_('color-rgba')
var clamp = _dereq_('clamp')
var dtype = _dereq_('dtype')

module.exports = function normalize (color, type) {
	if (type === 'float' || !type) type = 'array'
	if (type === 'uint') type = 'uint8'
	if (type === 'uint_clamped') type = 'uint8_clamped'
	var Ctor = dtype(type)
	var output = new Ctor(4)

	var normalize = type !== 'uint8' && type !== 'uint8_clamped'

	// attempt to parse non-array arguments
	if (!color.length || typeof color === 'string') {
		color = rgba(color)
		color[0] /= 255
		color[1] /= 255
		color[2] /= 255
	}

	// 0, 1 are possible contradictory values for Arrays:
	// [1,1,1] input gives [1,1,1] output instead of [1/255,1/255,1/255], which may be collision if input is meant to be uint.
	// converting [1,1,1] to [1/255,1/255,1/255] in case of float input gives larger mistake since [1,1,1] float is frequent edge value, whereas [0,1,1], [1,1,1] etc. uint inputs are relatively rare
	if (isInt(color)) {
		output[0] = color[0]
		output[1] = color[1]
		output[2] = color[2]
		output[3] = color[3] != null ? color[3] : 255

		if (normalize) {
			output[0] /= 255
			output[1] /= 255
			output[2] /= 255
			output[3] /= 255
		}

		return output
	}

	if (!normalize) {
		output[0] = clamp(Math.floor(color[0] * 255), 0, 255)
		output[1] = clamp(Math.floor(color[1] * 255), 0, 255)
		output[2] = clamp(Math.floor(color[2] * 255), 0, 255)
		output[3] = color[3] == null ? 255 : clamp(Math.floor(color[3] * 255), 0, 255)
	} else {
		output[0] = color[0]
		output[1] = color[1]
		output[2] = color[2]
		output[3] = color[3] != null ? color[3] : 1
	}

	return output
}

function isInt(color) {
	if (color instanceof Uint8Array || color instanceof Uint8ClampedArray) return true

	if (Array.isArray(color) &&
		(color[0] > 1 || color[0] === 0) &&
		(color[1] > 1 || color[1] === 0) &&
		(color[2] > 1 || color[2] === 0) &&
		(!color[3] || color[3] > 1)
	) return true

	return false
}

},{"clamp":103,"color-rgba":110,"dtype":157}],109:[function(_dereq_,module,exports){
(function (global){
/**
 * @module color-parse
 */

'use strict'

var names = _dereq_('color-name')
var isObject = _dereq_('is-plain-obj')
var defined = _dereq_('defined')

module.exports = parse

/**
 * Base hues
 * http://dev.w3.org/csswg/css-color/#typedef-named-hue
 */
//FIXME: use external hue detector
var baseHues = {
	red: 0,
	orange: 60,
	yellow: 120,
	green: 180,
	blue: 240,
	purple: 300
}

/**
 * Parse color from the string passed
 *
 * @return {Object} A space indicator `space`, an array `values` and `alpha`
 */
function parse (cstr) {
	var m, parts = [], alpha = 1, space

	if (typeof cstr === 'string') {
		//keyword
		if (names[cstr]) {
			parts = names[cstr].slice()
			space = 'rgb'
		}

		//reserved words
		else if (cstr === 'transparent') {
			alpha = 0
			space = 'rgb'
			parts = [0,0,0]
		}

		//hex
		else if (/^#[A-Fa-f0-9]+$/.test(cstr)) {
			var base = cstr.slice(1)
			var size = base.length
			var isShort = size <= 4
			alpha = 1

			if (isShort) {
				parts = [
					parseInt(base[0] + base[0], 16),
					parseInt(base[1] + base[1], 16),
					parseInt(base[2] + base[2], 16)
				]
				if (size === 4) {
					alpha = parseInt(base[3] + base[3], 16) / 255
				}
			}
			else {
				parts = [
					parseInt(base[0] + base[1], 16),
					parseInt(base[2] + base[3], 16),
					parseInt(base[4] + base[5], 16)
				]
				if (size === 8) {
					alpha = parseInt(base[6] + base[7], 16) / 255
				}
			}

			if (!parts[0]) parts[0] = 0
			if (!parts[1]) parts[1] = 0
			if (!parts[2]) parts[2] = 0

			space = 'rgb'
		}

		//color space
		else if (m = /^((?:rgb|hs[lvb]|hwb|cmyk?|xy[zy]|gray|lab|lchu?v?|[ly]uv|lms)a?)\s*\(([^\)]*)\)/.exec(cstr)) {
			var name = m[1]
			var base = name.replace(/a$/, '')
			space = base
			var size = base === 'cmyk' ? 4 : base === 'gray' ? 1 : 3
			parts = m[2].trim()
				.split(/\s*,\s*/)
				.map(function (x, i) {
					//<percentage>
					if (/%$/.test(x)) {
						//alpha
						if (i === size)	return parseFloat(x) / 100
						//rgb
						if (base === 'rgb') return parseFloat(x) * 255 / 100
						return parseFloat(x)
					}
					//hue
					else if (base[i] === 'h') {
						//<deg>
						if (/deg$/.test(x)) {
							return parseFloat(x)
						}
						//<base-hue>
						else if (baseHues[x] !== undefined) {
							return baseHues[x]
						}
					}
					return parseFloat(x)
				})

			if (name === base) parts.push(1)
			alpha = parts[size] === undefined ? 1 : parts[size]
			parts = parts.slice(0, size)
		}

		//named channels case
		else if (cstr.length > 10 && /[0-9](?:\s|\/)/.test(cstr)) {
			parts = cstr.match(/([0-9]+)/g).map(function (value) {
				return parseFloat(value)
			})

			space = cstr.match(/([a-z])/ig).join('').toLowerCase()
		}
	}

	//numeric case
	else if (!isNaN(cstr)) {
		space = 'rgb'
		parts = [cstr >>> 16, (cstr & 0x00ff00) >>> 8, cstr & 0x0000ff]
	}

	//object case - detects css cases of rgb and hsl
	else if (isObject(cstr)) {
		var r = defined(cstr.r, cstr.red, cstr.R, null)

		if (r !== null) {
			space = 'rgb'
			parts = [
				r,
				defined(cstr.g, cstr.green, cstr.G),
				defined(cstr.b, cstr.blue, cstr.B)
			]
		}
		else {
			space = 'hsl'
			parts = [
				defined(cstr.h, cstr.hue, cstr.H),
				defined(cstr.s, cstr.saturation, cstr.S),
				defined(cstr.l, cstr.lightness, cstr.L, cstr.b, cstr.brightness)
			]
		}

		alpha = defined(cstr.a, cstr.alpha, cstr.opacity, 1)

		if (cstr.opacity != null) alpha /= 100
	}

	//array
	else if (Array.isArray(cstr) || global.ArrayBuffer && ArrayBuffer.isView && ArrayBuffer.isView(cstr)) {
		parts = [cstr[0], cstr[1], cstr[2]]
		space = 'rgb'
		alpha = cstr.length === 4 ? cstr[3] : 1
	}

	return {
		space: space,
		values: parts,
		alpha: alpha
	}
}

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"color-name":107,"defined":152,"is-plain-obj":411}],110:[function(_dereq_,module,exports){
/** @module  color-rgba */

'use strict'

var parse = _dereq_('color-parse')
var hsl = _dereq_('color-space/hsl')
var clamp = _dereq_('clamp')

module.exports = function rgba (color) {
	var values, i, l

	//attempt to parse non-array arguments
	var parsed = parse(color)

	if (!parsed.space) return []

	values = Array(3)
	values[0] = clamp(parsed.values[0], 0, 255)
	values[1] = clamp(parsed.values[1], 0, 255)
	values[2] = clamp(parsed.values[2], 0, 255)

	if (parsed.space[0] === 'h') {
		values = hsl.rgb(values)
	}

	values.push(clamp(parsed.alpha, 0, 1))

	return values
}

},{"clamp":103,"color-parse":109,"color-space/hsl":111}],111:[function(_dereq_,module,exports){
/**
 * @module color-space/hsl
 */
'use strict'

var rgb = _dereq_('./rgb');

module.exports = {
	name: 'hsl',
	min: [0,0,0],
	max: [360,100,100],
	channel: ['hue', 'saturation', 'lightness'],
	alias: ['HSL'],

	rgb: function(hsl) {
		var h = hsl[0] / 360,
				s = hsl[1] / 100,
				l = hsl[2] / 100,
				t1, t2, t3, rgb, val;

		if (s === 0) {
			val = l * 255;
			return [val, val, val];
		}

		if (l < 0.5) {
			t2 = l * (1 + s);
		}
		else {
			t2 = l + s - l * s;
		}
		t1 = 2 * l - t2;

		rgb = [0, 0, 0];
		for (var i = 0; i < 3; i++) {
			t3 = h + 1 / 3 * - (i - 1);
			if (t3 < 0) {
				t3++;
			}
			else if (t3 > 1) {
				t3--;
			}

			if (6 * t3 < 1) {
				val = t1 + (t2 - t1) * 6 * t3;
			}
			else if (2 * t3 < 1) {
				val = t2;
			}
			else if (3 * t3 < 2) {
				val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
			}
			else {
				val = t1;
			}

			rgb[i] = val * 255;
		}

		return rgb;
	}
};


//extend rgb
rgb.hsl = function(rgb) {
	var r = rgb[0]/255,
			g = rgb[1]/255,
			b = rgb[2]/255,
			min = Math.min(r, g, b),
			max = Math.max(r, g, b),
			delta = max - min,
			h, s, l;

	if (max === min) {
		h = 0;
	}
	else if (r === max) {
		h = (g - b) / delta;
	}
	else if (g === max) {
		h = 2 + (b - r) / delta;
	}
	else if (b === max) {
		h = 4 + (r - g)/ delta;
	}

	h = Math.min(h * 60, 360);

	if (h < 0) {
		h += 360;
	}

	l = (min + max) / 2;

	if (max === min) {
		s = 0;
	}
	else if (l <= 0.5) {
		s = delta / (max + min);
	}
	else {
		s = delta / (2 - max - min);
	}

	return [h, s * 100, l * 100];
};

},{"./rgb":112}],112:[function(_dereq_,module,exports){
/**
 * RGB space.
 *
 * @module  color-space/rgb
 */
'use strict'

module.exports = {
	name: 'rgb',
	min: [0,0,0],
	max: [255,255,255],
	channel: ['red', 'green', 'blue'],
	alias: ['RGB']
};

},{}],113:[function(_dereq_,module,exports){
module.exports={
	"jet":[{"index":0,"rgb":[0,0,131]},{"index":0.125,"rgb":[0,60,170]},{"index":0.375,"rgb":[5,255,255]},{"index":0.625,"rgb":[255,255,0]},{"index":0.875,"rgb":[250,0,0]},{"index":1,"rgb":[128,0,0]}],

	"hsv":[{"index":0,"rgb":[255,0,0]},{"index":0.169,"rgb":[253,255,2]},{"index":0.173,"rgb":[247,255,2]},{"index":0.337,"rgb":[0,252,4]},{"index":0.341,"rgb":[0,252,10]},{"index":0.506,"rgb":[1,249,255]},{"index":0.671,"rgb":[2,0,253]},{"index":0.675,"rgb":[8,0,253]},{"index":0.839,"rgb":[255,0,251]},{"index":0.843,"rgb":[255,0,245]},{"index":1,"rgb":[255,0,6]}],

	"hot":[{"index":0,"rgb":[0,0,0]},{"index":0.3,"rgb":[230,0,0]},{"index":0.6,"rgb":[255,210,0]},{"index":1,"rgb":[255,255,255]}],

	"cool":[{"index":0,"rgb":[0,255,255]},{"index":1,"rgb":[255,0,255]}],

	"spring":[{"index":0,"rgb":[255,0,255]},{"index":1,"rgb":[255,255,0]}],

	"summer":[{"index":0,"rgb":[0,128,102]},{"index":1,"rgb":[255,255,102]}],

	"autumn":[{"index":0,"rgb":[255,0,0]},{"index":1,"rgb":[255,255,0]}],

	"winter":[{"index":0,"rgb":[0,0,255]},{"index":1,"rgb":[0,255,128]}],

	"bone":[{"index":0,"rgb":[0,0,0]},{"index":0.376,"rgb":[84,84,116]},{"index":0.753,"rgb":[169,200,200]},{"index":1,"rgb":[255,255,255]}],

	"copper":[{"index":0,"rgb":[0,0,0]},{"index":0.804,"rgb":[255,160,102]},{"index":1,"rgb":[255,199,127]}],

	"greys":[{"index":0,"rgb":[0,0,0]},{"index":1,"rgb":[255,255,255]}],

	"yignbu":[{"index":0,"rgb":[8,29,88]},{"index":0.125,"rgb":[37,52,148]},{"index":0.25,"rgb":[34,94,168]},{"index":0.375,"rgb":[29,145,192]},{"index":0.5,"rgb":[65,182,196]},{"index":0.625,"rgb":[127,205,187]},{"index":0.75,"rgb":[199,233,180]},{"index":0.875,"rgb":[237,248,217]},{"index":1,"rgb":[255,255,217]}],

	"greens":[{"index":0,"rgb":[0,68,27]},{"index":0.125,"rgb":[0,109,44]},{"index":0.25,"rgb":[35,139,69]},{"index":0.375,"rgb":[65,171,93]},{"index":0.5,"rgb":[116,196,118]},{"index":0.625,"rgb":[161,217,155]},{"index":0.75,"rgb":[199,233,192]},{"index":0.875,"rgb":[229,245,224]},{"index":1,"rgb":[247,252,245]}],

	"yiorrd":[{"index":0,"rgb":[128,0,38]},{"index":0.125,"rgb":[189,0,38]},{"index":0.25,"rgb":[227,26,28]},{"index":0.375,"rgb":[252,78,42]},{"index":0.5,"rgb":[253,141,60]},{"index":0.625,"rgb":[254,178,76]},{"index":0.75,"rgb":[254,217,118]},{"index":0.875,"rgb":[255,237,160]},{"index":1,"rgb":[255,255,204]}],

	"bluered":[{"index":0,"rgb":[0,0,255]},{"index":1,"rgb":[255,0,0]}],

	"rdbu":[{"index":0,"rgb":[5,10,172]},{"index":0.35,"rgb":[106,137,247]},{"index":0.5,"rgb":[190,190,190]},{"index":0.6,"rgb":[220,170,132]},{"index":0.7,"rgb":[230,145,90]},{"index":1,"rgb":[178,10,28]}],

	"picnic":[{"index":0,"rgb":[0,0,255]},{"index":0.1,"rgb":[51,153,255]},{"index":0.2,"rgb":[102,204,255]},{"index":0.3,"rgb":[153,204,255]},{"index":0.4,"rgb":[204,204,255]},{"index":0.5,"rgb":[255,255,255]},{"index":0.6,"rgb":[255,204,255]},{"index":0.7,"rgb":[255,153,255]},{"index":0.8,"rgb":[255,102,204]},{"index":0.9,"rgb":[255,102,102]},{"index":1,"rgb":[255,0,0]}],

	"rainbow":[{"index":0,"rgb":[150,0,90]},{"index":0.125,"rgb":[0,0,200]},{"index":0.25,"rgb":[0,25,255]},{"index":0.375,"rgb":[0,152,255]},{"index":0.5,"rgb":[44,255,150]},{"index":0.625,"rgb":[151,255,0]},{"index":0.75,"rgb":[255,234,0]},{"index":0.875,"rgb":[255,111,0]},{"index":1,"rgb":[255,0,0]}],

	"portland":[{"index":0,"rgb":[12,51,131]},{"index":0.25,"rgb":[10,136,186]},{"index":0.5,"rgb":[242,211,56]},{"index":0.75,"rgb":[242,143,56]},{"index":1,"rgb":[217,30,30]}],

	"blackbody":[{"index":0,"rgb":[0,0,0]},{"index":0.2,"rgb":[230,0,0]},{"index":0.4,"rgb":[230,210,0]},{"index":0.7,"rgb":[255,255,255]},{"index":1,"rgb":[160,200,255]}],

	"earth":[{"index":0,"rgb":[0,0,130]},{"index":0.1,"rgb":[0,180,180]},{"index":0.2,"rgb":[40,210,40]},{"index":0.4,"rgb":[230,230,50]},{"index":0.6,"rgb":[120,70,20]},{"index":1,"rgb":[255,255,255]}],

	"electric":[{"index":0,"rgb":[0,0,0]},{"index":0.15,"rgb":[30,0,100]},{"index":0.4,"rgb":[120,0,100]},{"index":0.6,"rgb":[160,90,0]},{"index":0.8,"rgb":[230,200,0]},{"index":1,"rgb":[255,250,220]}],

	"alpha": [{"index":0, "rgb": [255,255,255,0]},{"index":1, "rgb": [255,255,255,1]}],

	"viridis": [{"index":0,"rgb":[68,1,84]},{"index":0.13,"rgb":[71,44,122]},{"index":0.25,"rgb":[59,81,139]},{"index":0.38,"rgb":[44,113,142]},{"index":0.5,"rgb":[33,144,141]},{"index":0.63,"rgb":[39,173,129]},{"index":0.75,"rgb":[92,200,99]},{"index":0.88,"rgb":[170,220,50]},{"index":1,"rgb":[253,231,37]}],

	"inferno": [{"index":0,"rgb":[0,0,4]},{"index":0.13,"rgb":[31,12,72]},{"index":0.25,"rgb":[85,15,109]},{"index":0.38,"rgb":[136,34,106]},{"index":0.5,"rgb":[186,54,85]},{"index":0.63,"rgb":[227,89,51]},{"index":0.75,"rgb":[249,140,10]},{"index":0.88,"rgb":[249,201,50]},{"index":1,"rgb":[252,255,164]}],

	"magma": [{"index":0,"rgb":[0,0,4]},{"index":0.13,"rgb":[28,16,68]},{"index":0.25,"rgb":[79,18,123]},{"index":0.38,"rgb":[129,37,129]},{"index":0.5,"rgb":[181,54,122]},{"index":0.63,"rgb":[229,80,100]},{"index":0.75,"rgb":[251,135,97]},{"index":0.88,"rgb":[254,194,135]},{"index":1,"rgb":[252,253,191]}],

	"plasma": [{"index":0,"rgb":[13,8,135]},{"index":0.13,"rgb":[75,3,161]},{"index":0.25,"rgb":[125,3,168]},{"index":0.38,"rgb":[168,34,150]},{"index":0.5,"rgb":[203,70,121]},{"index":0.63,"rgb":[229,107,93]},{"index":0.75,"rgb":[248,148,65]},{"index":0.88,"rgb":[253,195,40]},{"index":1,"rgb":[240,249,33]}],

	"warm": [{"index":0,"rgb":[125,0,179]},{"index":0.13,"rgb":[172,0,187]},{"index":0.25,"rgb":[219,0,170]},{"index":0.38,"rgb":[255,0,130]},{"index":0.5,"rgb":[255,63,74]},{"index":0.63,"rgb":[255,123,0]},{"index":0.75,"rgb":[234,176,0]},{"index":0.88,"rgb":[190,228,0]},{"index":1,"rgb":[147,255,0]}],

	"cool": [{"index":0,"rgb":[125,0,179]},{"index":0.13,"rgb":[116,0,218]},{"index":0.25,"rgb":[98,74,237]},{"index":0.38,"rgb":[68,146,231]},{"index":0.5,"rgb":[0,204,197]},{"index":0.63,"rgb":[0,247,146]},{"index":0.75,"rgb":[0,255,88]},{"index":0.88,"rgb":[40,255,8]},{"index":1,"rgb":[147,255,0]}],

	"rainbow-soft": [{"index":0,"rgb":[125,0,179]},{"index":0.1,"rgb":[199,0,180]},{"index":0.2,"rgb":[255,0,121]},{"index":0.3,"rgb":[255,108,0]},{"index":0.4,"rgb":[222,194,0]},{"index":0.5,"rgb":[150,255,0]},{"index":0.6,"rgb":[0,255,55]},{"index":0.7,"rgb":[0,246,150]},{"index":0.8,"rgb":[50,167,222]},{"index":0.9,"rgb":[103,51,235]},{"index":1,"rgb":[124,0,186]}],

	"bathymetry": [{"index":0,"rgb":[40,26,44]},{"index":0.13,"rgb":[59,49,90]},{"index":0.25,"rgb":[64,76,139]},{"index":0.38,"rgb":[63,110,151]},{"index":0.5,"rgb":[72,142,158]},{"index":0.63,"rgb":[85,174,163]},{"index":0.75,"rgb":[120,206,163]},{"index":0.88,"rgb":[187,230,172]},{"index":1,"rgb":[253,254,204]}],

	"cdom": [{"index":0,"rgb":[47,15,62]},{"index":0.13,"rgb":[87,23,86]},{"index":0.25,"rgb":[130,28,99]},{"index":0.38,"rgb":[171,41,96]},{"index":0.5,"rgb":[206,67,86]},{"index":0.63,"rgb":[230,106,84]},{"index":0.75,"rgb":[242,149,103]},{"index":0.88,"rgb":[249,193,135]},{"index":1,"rgb":[254,237,176]}],

	"chlorophyll": [{"index":0,"rgb":[18,36,20]},{"index":0.13,"rgb":[25,63,41]},{"index":0.25,"rgb":[24,91,59]},{"index":0.38,"rgb":[13,119,72]},{"index":0.5,"rgb":[18,148,80]},{"index":0.63,"rgb":[80,173,89]},{"index":0.75,"rgb":[132,196,122]},{"index":0.88,"rgb":[175,221,162]},{"index":1,"rgb":[215,249,208]}],

	"density": [{"index":0,"rgb":[54,14,36]},{"index":0.13,"rgb":[89,23,80]},{"index":0.25,"rgb":[110,45,132]},{"index":0.38,"rgb":[120,77,178]},{"index":0.5,"rgb":[120,113,213]},{"index":0.63,"rgb":[115,151,228]},{"index":0.75,"rgb":[134,185,227]},{"index":0.88,"rgb":[177,214,227]},{"index":1,"rgb":[230,241,241]}],

	"freesurface-blue": [{"index":0,"rgb":[30,4,110]},{"index":0.13,"rgb":[47,14,176]},{"index":0.25,"rgb":[41,45,236]},{"index":0.38,"rgb":[25,99,212]},{"index":0.5,"rgb":[68,131,200]},{"index":0.63,"rgb":[114,156,197]},{"index":0.75,"rgb":[157,181,203]},{"index":0.88,"rgb":[200,208,216]},{"index":1,"rgb":[241,237,236]}],

	"freesurface-red": [{"index":0,"rgb":[60,9,18]},{"index":0.13,"rgb":[100,17,27]},{"index":0.25,"rgb":[142,20,29]},{"index":0.38,"rgb":[177,43,27]},{"index":0.5,"rgb":[192,87,63]},{"index":0.63,"rgb":[205,125,105]},{"index":0.75,"rgb":[216,162,148]},{"index":0.88,"rgb":[227,199,193]},{"index":1,"rgb":[241,237,236]}],

	"oxygen": [{"index":0,"rgb":[64,5,5]},{"index":0.13,"rgb":[106,6,15]},{"index":0.25,"rgb":[144,26,7]},{"index":0.38,"rgb":[168,64,3]},{"index":0.5,"rgb":[188,100,4]},{"index":0.63,"rgb":[206,136,11]},{"index":0.75,"rgb":[220,174,25]},{"index":0.88,"rgb":[231,215,44]},{"index":1,"rgb":[248,254,105]}],

	"par": [{"index":0,"rgb":[51,20,24]},{"index":0.13,"rgb":[90,32,35]},{"index":0.25,"rgb":[129,44,34]},{"index":0.38,"rgb":[159,68,25]},{"index":0.5,"rgb":[182,99,19]},{"index":0.63,"rgb":[199,134,22]},{"index":0.75,"rgb":[212,171,35]},{"index":0.88,"rgb":[221,210,54]},{"index":1,"rgb":[225,253,75]}],

	"phase": [{"index":0,"rgb":[145,105,18]},{"index":0.13,"rgb":[184,71,38]},{"index":0.25,"rgb":[186,58,115]},{"index":0.38,"rgb":[160,71,185]},{"index":0.5,"rgb":[110,97,218]},{"index":0.63,"rgb":[50,123,164]},{"index":0.75,"rgb":[31,131,110]},{"index":0.88,"rgb":[77,129,34]},{"index":1,"rgb":[145,105,18]}],

	"salinity": [{"index":0,"rgb":[42,24,108]},{"index":0.13,"rgb":[33,50,162]},{"index":0.25,"rgb":[15,90,145]},{"index":0.38,"rgb":[40,118,137]},{"index":0.5,"rgb":[59,146,135]},{"index":0.63,"rgb":[79,175,126]},{"index":0.75,"rgb":[120,203,104]},{"index":0.88,"rgb":[193,221,100]},{"index":1,"rgb":[253,239,154]}],

	"temperature": [{"index":0,"rgb":[4,35,51]},{"index":0.13,"rgb":[23,51,122]},{"index":0.25,"rgb":[85,59,157]},{"index":0.38,"rgb":[129,79,143]},{"index":0.5,"rgb":[175,95,130]},{"index":0.63,"rgb":[222,112,101]},{"index":0.75,"rgb":[249,146,66]},{"index":0.88,"rgb":[249,196,65]},{"index":1,"rgb":[232,250,91]}],

	"turbidity": [{"index":0,"rgb":[34,31,27]},{"index":0.13,"rgb":[65,50,41]},{"index":0.25,"rgb":[98,69,52]},{"index":0.38,"rgb":[131,89,57]},{"index":0.5,"rgb":[161,112,59]},{"index":0.63,"rgb":[185,140,66]},{"index":0.75,"rgb":[202,174,88]},{"index":0.88,"rgb":[216,209,126]},{"index":1,"rgb":[233,246,171]}],

	"velocity-blue": [{"index":0,"rgb":[17,32,64]},{"index":0.13,"rgb":[35,52,116]},{"index":0.25,"rgb":[29,81,156]},{"index":0.38,"rgb":[31,113,162]},{"index":0.5,"rgb":[50,144,169]},{"index":0.63,"rgb":[87,173,176]},{"index":0.75,"rgb":[149,196,189]},{"index":0.88,"rgb":[203,221,211]},{"index":1,"rgb":[254,251,230]}],

	"velocity-green": [{"index":0,"rgb":[23,35,19]},{"index":0.13,"rgb":[24,64,38]},{"index":0.25,"rgb":[11,95,45]},{"index":0.38,"rgb":[39,123,35]},{"index":0.5,"rgb":[95,146,12]},{"index":0.63,"rgb":[152,165,18]},{"index":0.75,"rgb":[201,186,69]},{"index":0.88,"rgb":[233,216,137]},{"index":1,"rgb":[255,253,205]}],

	"cubehelix": [{"index":0,"rgb":[0,0,0]},{"index":0.07,"rgb":[22,5,59]},{"index":0.13,"rgb":[60,4,105]},{"index":0.2,"rgb":[109,1,135]},{"index":0.27,"rgb":[161,0,147]},{"index":0.33,"rgb":[210,2,142]},{"index":0.4,"rgb":[251,11,123]},{"index":0.47,"rgb":[255,29,97]},{"index":0.53,"rgb":[255,54,69]},{"index":0.6,"rgb":[255,85,46]},{"index":0.67,"rgb":[255,120,34]},{"index":0.73,"rgb":[255,157,37]},{"index":0.8,"rgb":[241,191,57]},{"index":0.87,"rgb":[224,220,93]},{"index":0.93,"rgb":[218,241,142]},{"index":1,"rgb":[227,253,198]}]
};

},{}],114:[function(_dereq_,module,exports){
/*
 * Ben Postlethwaite
 * January 2013
 * License MIT
 */
'use strict';

var colorScale = _dereq_('./colorScale');
var lerp = _dereq_('lerp')

module.exports = createColormap;

function createColormap (spec) {
    /*
     * Default Options
     */
    var indicies, rgba, fromrgba, torgba,
        nsteps, cmap, colormap, format,
        nshades, colors, alpha, index, i,
        r = [],
        g = [],
        b = [],
        a = [];

    if ( !spec ) spec = {};

    nshades = (spec.nshades || 72) - 1;
    format = spec.format || 'hex';

    colormap = spec.colormap;
    if (!colormap) colormap = 'jet';

    if (typeof colormap === 'string') {
        colormap = colormap.toLowerCase();

        if (!colorScale[colormap]) {
            throw Error(colormap + ' not a supported colorscale');
        }

        cmap = colorScale[colormap];

    } else if (Array.isArray(colormap)) {
        cmap = colormap.slice();

    } else {
        throw Error('unsupported colormap option', colormap);
    }

    if (cmap.length > nshades) {
        throw new Error(
            colormap+' map requires nshades to be at least size '+cmap.length
        );
    }

    if (!Array.isArray(spec.alpha)) {

        if (typeof spec.alpha === 'number') {
            alpha = [spec.alpha, spec.alpha];

        } else {
            alpha = [1, 1];
        }

    } else if (spec.alpha.length !== 2) {
        alpha = [1, 1];

    } else {
        alpha = spec.alpha.slice();
    }

    // map index points from 0..1 to 0..n-1
    indicies = cmap.map(function(c) {
        return Math.round(c.index * nshades);
    });

    // Add alpha channel to the map
    alpha[0] = Math.min(Math.max(alpha[0], 0), 1);
    alpha[1] = Math.min(Math.max(alpha[1], 0), 1);

    var steps = cmap.map(function(c, i) {
        var index = cmap[i].index

        var rgba = cmap[i].rgb.slice();

        // if user supplies their own map use it
        if (rgba.length === 4 && rgba[3] >= 0 && rgba[3] <= 1) {
            return rgba
        }
        rgba[3] = alpha[0] + (alpha[1] - alpha[0])*index;

        return rgba
    })


    /*
     * map increasing linear values between indicies to
     * linear steps in colorvalues
     */
    var colors = []
    for (i = 0; i < indicies.length-1; ++i) {
        nsteps = indicies[i+1] - indicies[i];
        fromrgba = steps[i];
        torgba = steps[i+1];

        for (var j = 0; j < nsteps; j++) {
            var amt = j / nsteps
            colors.push([
                Math.round(lerp(fromrgba[0], torgba[0], amt)),
                Math.round(lerp(fromrgba[1], torgba[1], amt)),
                Math.round(lerp(fromrgba[2], torgba[2], amt)),
                lerp(fromrgba[3], torgba[3], amt)
            ])
        }
    }

    //add 1 step as last value
    colors.push(cmap[cmap.length - 1].rgb.concat(alpha[1]))

    if (format === 'hex') colors = colors.map( rgb2hex );
    else if (format === 'rgbaString') colors = colors.map( rgbaStr );
    else if (format === 'float') colors = colors.map( rgb2float );

    return colors;
};

function rgb2float (rgba) {
    return [
        rgba[0] / 255,
        rgba[1] / 255,
        rgba[2] / 255,
        rgba[3]
    ]
}

function rgb2hex (rgba) {
    var dig, hex = '#';
    for (var i = 0; i < 3; ++i) {
        dig = rgba[i];
        dig = dig.toString(16);
        hex += ('00' + dig).substr( dig.length );
    }
    return hex;
}

function rgbaStr (rgba) {
    return 'rgba(' + rgba.join(',') + ')';
}

},{"./colorScale":113,"lerp":414}],115:[function(_dereq_,module,exports){
"use strict"

module.exports = compareAngle

var orient = _dereq_("robust-orientation")
var sgn = _dereq_("signum")
var twoSum = _dereq_("two-sum")
var robustProduct = _dereq_("robust-product")
var robustSum = _dereq_("robust-sum")

function testInterior(a, b, c) {
  var x0 = twoSum(a[0], -b[0])
  var y0 = twoSum(a[1], -b[1])
  var x1 = twoSum(c[0], -b[0])
  var y1 = twoSum(c[1], -b[1])

  var d = robustSum(
    robustProduct(x0, x1),
    robustProduct(y0, y1))

  return d[d.length-1] >= 0
}

function compareAngle(a, b, c, d) {
  var bcd = orient(b, c, d)
  if(bcd === 0) {
    //Handle degenerate cases
    var sabc = sgn(orient(a, b, c))
    var sabd = sgn(orient(a, b, d))
    if(sabc === sabd) {
      if(sabc === 0) {
        var ic = testInterior(a, b, c)
        var id = testInterior(a, b, d)
        if(ic === id) {
          return 0
        } else if(ic) {
          return 1
        } else {
          return -1
        }
      }
      return 0
    } else if(sabd === 0) {
      if(sabc > 0) {
        return -1
      } else if(testInterior(a, b, d)) {
        return -1
      } else {
        return 1
      }
    } else if(sabc === 0) {
      if(sabd > 0) {
        return 1
      } else if(testInterior(a, b, c)) {
        return 1
      } else {
        return -1
      }
    }
    return sgn(sabd - sabc)
  }
  var abc = orient(a, b, c)
  if(abc > 0) {
    if(bcd > 0 && orient(a, b, d) > 0) {
      return 1
    }
    return -1
  } else if(abc < 0) {
    if(bcd > 0 || orient(a, b, d) > 0) {
      return 1
    }
    return -1
  } else {
    var abd = orient(a, b, d)
    if(abd > 0) {
      return 1
    } else {
      if(testInterior(a, b, c)) {
        return 1
      } else {
        return -1
      }
    }
  }
}
},{"robust-orientation":491,"robust-product":492,"robust-sum":496,"signum":497,"two-sum":525}],116:[function(_dereq_,module,exports){
module.exports = compareCells

var min = Math.min

function compareInt(a, b) {
  return a - b
}

function compareCells(a, b) {
  var n = a.length
    , t = a.length - b.length
  if(t) {
    return t
  }
  switch(n) {
    case 0:
      return 0
    case 1:
      return a[0] - b[0]
    case 2:
      return (a[0]+a[1]-b[0]-b[1]) ||
             min(a[0],a[1]) - min(b[0],b[1])
    case 3:
      var l1 = a[0]+a[1]
        , m1 = b[0]+b[1]
      t = l1+a[2] - (m1+b[2])
      if(t) {
        return t
      }
      var l0 = min(a[0], a[1])
        , m0 = min(b[0], b[1])
      return min(l0, a[2]) - min(m0, b[2]) ||
             min(l0+a[2], l1) - min(m0+b[2], m1)
    case 4:
      var aw=a[0], ax=a[1], ay=a[2], az=a[3]
        , bw=b[0], bx=b[1], by=b[2], bz=b[3]
      return (aw+ax+ay+az)-(bw+bx+by+bz) ||
             min(aw,ax,ay,az)-min(bw,bx,by,bz,bw) ||
             min(aw+ax,aw+ay,aw+az,ax+ay,ax+az,ay+az) -
               min(bw+bx,bw+by,bw+bz,bx+by,bx+bz,by+bz) ||
             min(aw+ax+ay,aw+ax+az,aw+ay+az,ax+ay+az) -
               min(bw+bx+by,bw+bx+bz,bw+by+bz,bx+by+bz)
    default:
      var as = a.slice().sort(compareInt)
      var bs = b.slice().sort(compareInt)
      for(var i=0; i<n; ++i) {
        t = as[i] - bs[i]
        if(t) {
          return t
        }
      }
      return 0
  }
}

},{}],117:[function(_dereq_,module,exports){
'use strict'

var compareCells = _dereq_('compare-cell')
var parity = _dereq_('cell-orientation')

module.exports = compareOrientedCells

function compareOrientedCells(a, b) {
  return compareCells(a, b) || parity(a) - parity(b)
}

},{"cell-orientation":100,"compare-cell":116}],118:[function(_dereq_,module,exports){
"use strict"

var convexHull1d = _dereq_('./lib/ch1d')
var convexHull2d = _dereq_('./lib/ch2d')
var convexHullnd = _dereq_('./lib/chnd')

module.exports = convexHull

function convexHull(points) {
  var n = points.length
  if(n === 0) {
    return []
  } else if(n === 1) {
    return [[0]]
  }
  var d = points[0].length
  if(d === 0) {
    return []
  } else if(d === 1) {
    return convexHull1d(points)
  } else if(d === 2) {
    return convexHull2d(points)
  }
  return convexHullnd(points, d)
}
},{"./lib/ch1d":119,"./lib/ch2d":120,"./lib/chnd":121}],119:[function(_dereq_,module,exports){
"use strict"

module.exports = convexHull1d

function convexHull1d(points) {
  var lo = 0
  var hi = 0
  for(var i=1; i<points.length; ++i) {
    if(points[i][0] < points[lo][0]) {
      lo = i
    }
    if(points[i][0] > points[hi][0]) {
      hi = i
    }
  }
  if(lo < hi) {
    return [[lo], [hi]]
  } else if(lo > hi) {
    return [[hi], [lo]]
  } else {
    return [[lo]]
  }
}
},{}],120:[function(_dereq_,module,exports){
'use strict'

module.exports = convexHull2D

var monotoneHull = _dereq_('monotone-convex-hull-2d')

function convexHull2D(points) {
  var hull = monotoneHull(points)
  var h = hull.length
  if(h <= 2) {
    return []
  }
  var edges = new Array(h)
  var a = hull[h-1]
  for(var i=0; i<h; ++i) {
    var b = hull[i]
    edges[i] = [a,b]
    a = b
  }
  return edges
}

},{"monotone-convex-hull-2d":423}],121:[function(_dereq_,module,exports){
'use strict'

module.exports = convexHullnD

var ich = _dereq_('incremental-convex-hull')
var aff = _dereq_('affine-hull')

function permute(points, front) {
  var n = points.length
  var npoints = new Array(n)
  for(var i=0; i<front.length; ++i) {
    npoints[i] = points[front[i]]
  }
  var ptr = front.length
  for(var i=0; i<n; ++i) {
    if(front.indexOf(i) < 0) {
      npoints[ptr++] = points[i]
    }
  }
  return npoints
}

function invPermute(cells, front) {
  var nc = cells.length
  var nf = front.length
  for(var i=0; i<nc; ++i) {
    var c = cells[i]
    for(var j=0; j<c.length; ++j) {
      var x = c[j]
      if(x < nf) {
        c[j] = front[x]
      } else {
        x = x - nf
        for(var k=0; k<nf; ++k) {
          if(x >= front[k]) {
            x += 1
          }
        }
        c[j] = x
      }
    }
  }
  return cells
}

function convexHullnD(points, d) {
  try {
    return ich(points, true)
  } catch(e) {
    //If point set is degenerate, try to find a basis and rerun it
    var ah = aff(points)
    if(ah.length <= d) {
      //No basis, no try
      return []
    }
    var npoints = permute(points, ah)
    var nhull   = ich(npoints, true)
    return invPermute(nhull, ah)
  }
}
},{"affine-hull":50,"incremental-convex-hull":402}],122:[function(_dereq_,module,exports){
module.exports = {
  AFG: 'afghan',
  ALA: '\\b\\wland',
  ALB: 'albania',
  DZA: 'algeria',
  ASM: '^(?=.*americ).*samoa',
  AND: 'andorra',
  AGO: 'angola',
  AIA: 'anguill?a',
  ATA: 'antarctica',
  ATG: 'antigua',
  ARG: 'argentin',
  ARM: 'armenia',
  ABW: '^(?!.*bonaire).*\\baruba',
  AUS: 'australia',
  AUT: '^(?!.*hungary).*austria|\\baustri.*\\bemp',
  AZE: 'azerbaijan',
  BHS: 'bahamas',
  BHR: 'bahrain',
  BGD: 'bangladesh|^(?=.*east).*paki?stan',
  BRB: 'barbados',
  BLR: 'belarus|byelo',
  BEL: '^(?!.*luxem).*belgium',
  BLZ: 'belize|^(?=.*british).*honduras',
  BEN: 'benin|dahome',
  BMU: 'bermuda',
  BTN: 'bhutan',
  BOL: 'bolivia',
  BES: '^(?=.*bonaire).*eustatius|^(?=.*carib).*netherlands|\\bbes.?islands',
  BIH: 'herzegovina|bosnia',
  BWA: 'botswana|bechuana',
  BVT: 'bouvet',
  BRA: 'brazil',
  IOT: 'british.?indian.?ocean',
  BRN: 'brunei',
  BGR: 'bulgaria',
  BFA: 'burkina|\\bfaso|upper.?volta',
  BDI: 'burundi',
  CPV: 'verde',
  KHM: 'cambodia|kampuchea|khmer',
  CMR: 'cameroon',
  CAN: 'canada',
  CYM: 'cayman',
  CAF: '\\bcentral.african.republic',
  TCD: '\\bchad',
  CHL: '\\bchile',
  CHN: '^(?!.*\\bmac)(?!.*\\bhong)(?!.*\\btai)(?!.*\\brep).*china|^(?=.*peo)(?=.*rep).*china',
  CXR: 'christmas',
  CCK: '\\bcocos|keeling',
  COL: 'colombia',
  COM: 'comoro',
  COG: '^(?!.*\\bdem)(?!.*\\bd[\\.]?r)(?!.*kinshasa)(?!.*zaire)(?!.*belg)(?!.*l.opoldville)(?!.*free).*\\bcongo',
  COK: '\\bcook',
  CRI: 'costa.?rica',
  CIV: 'ivoire|ivory',
  HRV: 'croatia',
  CUB: '\\bcuba',
  CUW: '^(?!.*bonaire).*\\bcura(c|ç)ao',
  CYP: 'cyprus',
  CSK: 'czechoslovakia',
  CZE: '^(?=.*rep).*czech|czechia|bohemia',
  COD: '\\bdem.*congo|congo.*\\bdem|congo.*\\bd[\\.]?r|\\bd[\\.]?r.*congo|belgian.?congo|congo.?free.?state|kinshasa|zaire|l.opoldville|drc|droc|rdc',
  DNK: 'denmark',
  DJI: 'djibouti',
  DMA: 'dominica(?!n)',
  DOM: 'dominican.rep',
  ECU: 'ecuador',
  EGY: 'egypt',
  SLV: 'el.?salvador',
  GNQ: 'guine.*eq|eq.*guine|^(?=.*span).*guinea',
  ERI: 'eritrea',
  EST: 'estonia',
  ETH: 'ethiopia|abyssinia',
  FLK: 'falkland|malvinas',
  FRO: 'faroe|faeroe',
  FJI: 'fiji',
  FIN: 'finland',
  FRA: '^(?!.*\\bdep)(?!.*martinique).*france|french.?republic|\\bgaul',
  GUF: '^(?=.*french).*guiana',
  PYF: 'french.?polynesia|tahiti',
  ATF: 'french.?southern',
  GAB: 'gabon',
  GMB: 'gambia',
  GEO: '^(?!.*south).*georgia',
  DDR: 'german.?democratic.?republic|democratic.?republic.*germany|east.germany',
  DEU: '^(?!.*east).*germany|^(?=.*\\bfed.*\\brep).*german',
  GHA: 'ghana|gold.?coast',
  GIB: 'gibraltar',
  GRC: 'greece|hellenic|hellas',
  GRL: 'greenland',
  GRD: 'grenada',
  GLP: 'guadeloupe',
  GUM: '\\bguam',
  GTM: 'guatemala',
  GGY: 'guernsey',
  GIN: '^(?!.*eq)(?!.*span)(?!.*bissau)(?!.*portu)(?!.*new).*guinea',
  GNB: 'bissau|^(?=.*portu).*guinea',
  GUY: 'guyana|british.?guiana',
  HTI: 'haiti',
  HMD: 'heard.*mcdonald',
  VAT: 'holy.?see|vatican|papal.?st',
  HND: '^(?!.*brit).*honduras',
  HKG: 'hong.?kong',
  HUN: '^(?!.*austr).*hungary',
  ISL: 'iceland',
  IND: 'india(?!.*ocea)',
  IDN: 'indonesia',
  IRN: '\\biran|persia',
  IRQ: '\\biraq|mesopotamia',
  IRL: '(^ireland)|(^republic.*ireland)',
  IMN: '^(?=.*isle).*\\bman',
  ISR: 'israel',
  ITA: 'italy',
  JAM: 'jamaica',
  JPN: 'japan',
  JEY: 'jersey',
  JOR: 'jordan',
  KAZ: 'kazak',
  KEN: 'kenya|british.?east.?africa|east.?africa.?prot',
  KIR: 'kiribati',
  PRK: '^(?=.*democrat|people|north|d.*p.*.r).*\\bkorea|dprk|korea.*(d.*p.*r)',
  KWT: 'kuwait',
  KGZ: 'kyrgyz|kirghiz',
  LAO: '\\blaos?\\b',
  LVA: 'latvia',
  LBN: 'lebanon',
  LSO: 'lesotho|basuto',
  LBR: 'liberia',
  LBY: 'libya',
  LIE: 'liechtenstein',
  LTU: 'lithuania',
  LUX: '^(?!.*belg).*luxem',
  MAC: 'maca(o|u)',
  MDG: 'madagascar|malagasy',
  MWI: 'malawi|nyasa',
  MYS: 'malaysia',
  MDV: 'maldive',
  MLI: '\\bmali\\b',
  MLT: '\\bmalta',
  MHL: 'marshall',
  MTQ: 'martinique',
  MRT: 'mauritania',
  MUS: 'mauritius',
  MYT: '\\bmayotte',
  MEX: '\\bmexic',
  FSM: 'fed.*micronesia|micronesia.*fed',
  MCO: 'monaco',
  MNG: 'mongolia',
  MNE: '^(?!.*serbia).*montenegro',
  MSR: 'montserrat',
  MAR: 'morocco|\\bmaroc',
  MOZ: 'mozambique',
  MMR: 'myanmar|burma',
  NAM: 'namibia',
  NRU: 'nauru',
  NPL: 'nepal',
  NLD: '^(?!.*\\bant)(?!.*\\bcarib).*netherlands',
  ANT: '^(?=.*\\bant).*(nether|dutch)',
  NCL: 'new.?caledonia',
  NZL: 'new.?zealand',
  NIC: 'nicaragua',
  NER: '\\bniger(?!ia)',
  NGA: 'nigeria',
  NIU: 'niue',
  NFK: 'norfolk',
  MNP: 'mariana',
  NOR: 'norway',
  OMN: '\\boman|trucial',
  PAK: '^(?!.*east).*paki?stan',
  PLW: 'palau',
  PSE: 'palestin|\\bgaza|west.?bank',
  PAN: 'panama',
  PNG: 'papua|new.?guinea',
  PRY: 'paraguay',
  PER: 'peru',
  PHL: 'philippines',
  PCN: 'pitcairn',
  POL: 'poland',
  PRT: 'portugal',
  PRI: 'puerto.?rico',
  QAT: 'qatar',
  KOR: '^(?!.*d.*p.*r)(?!.*democrat)(?!.*people)(?!.*north).*\\bkorea(?!.*d.*p.*r)',
  MDA: 'moldov|b(a|e)ssarabia',
  REU: 'r(e|é)union',
  ROU: 'r(o|u|ou)mania',
  RUS: '\\brussia|soviet.?union|u\\.?s\\.?s\\.?r|socialist.?republics',
  RWA: 'rwanda',
  BLM: 'barth(e|é)lemy',
  SHN: 'helena',
  KNA: 'kitts|\\bnevis',
  LCA: '\\blucia',
  MAF: '^(?=.*collectivity).*martin|^(?=.*france).*martin(?!ique)|^(?=.*french).*martin(?!ique)',
  SPM: 'miquelon',
  VCT: 'vincent',
  WSM: '^(?!.*amer).*samoa',
  SMR: 'san.?marino',
  STP: '\\bs(a|ã)o.?tom(e|é)',
  SAU: '\\bsa\\w*.?arabia',
  SEN: 'senegal',
  SRB: '^(?!.*monte).*serbia',
  SYC: 'seychell',
  SLE: 'sierra',
  SGP: 'singapore',
  SXM: '^(?!.*martin)(?!.*saba).*maarten',
  SVK: '^(?!.*cze).*slovak',
  SVN: 'slovenia',
  SLB: 'solomon',
  SOM: 'somali',
  ZAF: 'south.africa|s\\\\..?africa',
  SGS: 'south.?georgia|sandwich',
  SSD: '\\bs\\w*.?sudan',
  ESP: 'spain',
  LKA: 'sri.?lanka|ceylon',
  SDN: '^(?!.*\\bs(?!u)).*sudan',
  SUR: 'surinam|dutch.?guiana',
  SJM: 'svalbard',
  SWZ: 'swaziland',
  SWE: 'sweden',
  CHE: 'switz|swiss',
  SYR: 'syria',
  TWN: 'taiwan|taipei|formosa|^(?!.*peo)(?=.*rep).*china',
  TJK: 'tajik',
  THA: 'thailand|\\bsiam',
  MKD: 'macedonia|fyrom',
  TLS: '^(?=.*leste).*timor|^(?=.*east).*timor',
  TGO: 'togo',
  TKL: 'tokelau',
  TON: 'tonga',
  TTO: 'trinidad|tobago',
  TUN: 'tunisia',
  TUR: 'turkey',
  TKM: 'turkmen',
  TCA: 'turks',
  TUV: 'tuvalu',
  UGA: 'uganda',
  UKR: 'ukrain',
  ARE: 'emirates|^u\\.?a\\.?e\\.?$|united.?arab.?em',
  GBR: 'united.?kingdom|britain|^u\\.?k\\.?$',
  TZA: 'tanzania',
  USA: 'united.?states\\b(?!.*islands)|\\bu\\.?s\\.?a\\.?\\b|^\\s*u\\.?s\\.?\\b(?!.*islands)',
  UMI: 'minor.?outlying.?is',
  URY: 'uruguay',
  UZB: 'uzbek',
  VUT: 'vanuatu|new.?hebrides',
  VEN: 'venezuela',
  VNM: '^(?!.*republic).*viet.?nam|^(?=.*socialist).*viet.?nam',
  VGB: '^(?=.*\\bu\\.?\\s?k).*virgin|^(?=.*brit).*virgin|^(?=.*kingdom).*virgin',
  VIR: '^(?=.*\\bu\\.?\\s?s).*virgin|^(?=.*states).*virgin',
  WLF: 'futuna|wallis',
  ESH: 'western.sahara',
  YEM: '^(?!.*arab)(?!.*north)(?!.*sana)(?!.*peo)(?!.*dem)(?!.*south)(?!.*aden)(?!.*\\bp\\.?d\\.?r).*yemen',
  YMD: '^(?=.*peo).*yemen|^(?!.*rep)(?=.*dem).*yemen|^(?=.*south).*yemen|^(?=.*aden).*yemen|^(?=.*\\bp\\.?d\\.?r).*yemen',
  YUG: 'yugoslavia',
  ZMB: 'zambia|northern.?rhodesia',
  EAZ: 'zanzibar',
  ZWE: 'zimbabwe|^(?!.*northern).*rhodesia'
}

},{}],123:[function(_dereq_,module,exports){
module.exports=[
	"xx-small",
	"x-small",
	"small",
	"medium",
	"large",
	"x-large",
	"xx-large",
	"larger",
	"smaller"
]

},{}],124:[function(_dereq_,module,exports){
module.exports=[
	"normal",
	"condensed",
	"semi-condensed",
	"extra-condensed",
	"ultra-condensed",
	"expanded",
	"semi-expanded",
	"extra-expanded",
	"ultra-expanded"
]

},{}],125:[function(_dereq_,module,exports){
module.exports=[
	"normal",
	"italic",
	"oblique"
]

},{}],126:[function(_dereq_,module,exports){
module.exports=[
	"normal",
	"bold",
	"bolder",
	"lighter",
	"100",
	"200",
	"300",
	"400",
	"500",
	"600",
	"700",
	"800",
	"900"
]

},{}],127:[function(_dereq_,module,exports){
'use strict'

module.exports = {
	parse: _dereq_('./parse'),
	stringify: _dereq_('./stringify')
}

},{"./parse":129,"./stringify":130}],128:[function(_dereq_,module,exports){
'use strict'

var sizes = _dereq_('css-font-size-keywords')

module.exports = {
	isSize: function isSize(value) {
		return /^[\d\.]/.test(value)
			|| value.indexOf('/') !== -1
			|| sizes.indexOf(value) !== -1
	}
}

},{"css-font-size-keywords":123}],129:[function(_dereq_,module,exports){
'use strict'

var unquote = _dereq_('unquote')
var globalKeywords = _dereq_('css-global-keywords')
var systemFontKeywords = _dereq_('css-system-font-keywords')
var fontWeightKeywords = _dereq_('css-font-weight-keywords')
var fontStyleKeywords = _dereq_('css-font-style-keywords')
var fontStretchKeywords = _dereq_('css-font-stretch-keywords')
var splitBy = _dereq_('string-split-by')
var isSize = _dereq_('./lib/util').isSize


module.exports = parseFont


var cache = parseFont.cache = {}


function parseFont (value) {
	if (typeof value !== 'string') throw new Error('Font argument must be a string.')

	if (cache[value]) return cache[value]

	if (value === '') {
		throw new Error('Cannot parse an empty string.')
	}

	if (systemFontKeywords.indexOf(value) !== -1) {
		return cache[value] = {system: value}
	}

	var font = {
		style: 'normal',
		variant: 'normal',
		weight: 'normal',
		stretch: 'normal',
		lineHeight: 'normal',
		size: '1rem',
		family: ['serif']
	}

	var tokens = splitBy(value, /\s+/)
	var token

	while (token = tokens.shift()) {
		if (globalKeywords.indexOf(token) !== -1) {
			['style', 'variant', 'weight', 'stretch'].forEach(function(prop) {
				font[prop] = token
			})

			return cache[value] = font
		}

		if (fontStyleKeywords.indexOf(token) !== -1) {
			font.style = token
			continue
		}

		if (token === 'normal' || token === 'small-caps') {
			font.variant = token
			continue
		}

		if (fontStretchKeywords.indexOf(token) !== -1) {
			font.stretch = token
			continue
		}

		if (fontWeightKeywords.indexOf(token) !== -1) {
			font.weight = token
			continue
		}


		if (isSize(token)) {
			var parts = splitBy(token, '/')
			font.size = parts[0]
			if (parts[1] != null) {
				font.lineHeight = parseLineHeight(parts[1])
			}
			else if (tokens[0] === '/') {
				tokens.shift()
				font.lineHeight = parseLineHeight(tokens.shift())
 			}

			if (!tokens.length) {
				throw new Error('Missing required font-family.')
			}
			font.family = splitBy(tokens.join(' '), /\s*,\s*/).map(unquote)

			return cache[value] = font
		}

		throw new Error('Unknown or unsupported font token: ' + token)
	}

	throw new Error('Missing required font-size.')
}


function parseLineHeight(value) {
	var parsed = parseFloat(value)
	if (parsed.toString() === value) {
		return parsed
	}
	return value
}

},{"./lib/util":128,"css-font-stretch-keywords":124,"css-font-style-keywords":125,"css-font-weight-keywords":126,"css-global-keywords":131,"css-system-font-keywords":132,"string-split-by":510,"unquote":529}],130:[function(_dereq_,module,exports){
'use strict'

var pick = _dereq_('pick-by-alias')
var isSize = _dereq_('./lib/util').isSize

var globals = a2o(_dereq_('css-global-keywords'))
var systems = a2o(_dereq_('css-system-font-keywords'))
var weights = a2o(_dereq_('css-font-weight-keywords'))
var styles = a2o(_dereq_('css-font-style-keywords'))
var stretches = a2o(_dereq_('css-font-stretch-keywords'))

var variants = {'normal': 1, 'small-caps': 1}
var fams = {
	'serif': 1,
	'sans-serif': 1,
	'monospace': 1,
	'cursive': 1,
	'fantasy': 1,
	'system-ui': 1
}

var defaults = {
	style: 'normal',
	variant: 'normal',
	weight: 'normal',
	stretch: 'normal',
	size: '1rem',
	lineHeight: 'normal',
	family: 'serif'
}

module.exports = function stringifyFont (o) {
	o = pick(o, {
		style: 'style fontstyle fontStyle font-style slope distinction',
		variant: 'variant font-variant fontVariant fontvariant var capitalization',
		weight: 'weight w font-weight fontWeight fontweight',
		stretch: 'stretch font-stretch fontStretch fontstretch width',
		size: 'size s font-size fontSize fontsize height em emSize',
		lineHeight: 'lh line-height lineHeight lineheight leading',
		family: 'font family fontFamily font-family fontfamily type typeface face',
		system: 'system reserved default global',
	})

	if (o.system) {
		if (o.system) verify(o.system, systems)
		return o.system
	}

	verify(o.style, styles)
	verify(o.variant, variants)
	verify(o.weight, weights)
	verify(o.stretch, stretches)

	// default root value is medium, but by default it's inherited
	if (o.size == null) o.size = defaults.size
	if (typeof o.size === 'number') o.size += 'px'

	if (!isSize) throw Error('Bad size value `' + o.size + '`')

	// many user-agents use serif, we don't detect that for consistency
	if (!o.family) o.family = defaults.family
	if (Array.isArray(o.family)) {
		if (!o.family.length) o.family = [defaults.family]
		o.family = o.family.map(function (f) {
			return fams[f] ? f : '"' + f + '"'
		}).join(', ')
	}

	// [ [ <'font-style'> || <font-variant-css21> || <'font-weight'> || <'font-stretch'> ]? <'font-size'> [ / <'line-height'> ]? <'font-family'> ]
	var result = []

	result.push(o.style)
	if (o.variant !== o.style) result.push(o.variant)

	if (o.weight !== o.variant &&
		o.weight !== o.style) result.push(o.weight)

	if (o.stretch !== o.weight &&
		o.stretch !== o.variant &&
		o.stretch !== o.style) result.push(o.stretch)

	result.push(o.size + (o.lineHeight == null || o.lineHeight === 'normal' || (o.lineHeight + '' === '1')  ? '' : ('/' + o.lineHeight)))
	result.push(o.family)

	return result.filter(Boolean).join(' ')
}

function verify (value, values) {
	if (value && !values[value] && !globals[value]) throw Error('Unknown keyword `' + value +'`')

	return value
}


// ['a', 'b'] -> {a: true, b: true}
function a2o (a) {
	var o = {}
	for (var i = 0; i < a.length; i++) {
		o[a[i]] = 1
	}
	return o
}

},{"./lib/util":128,"css-font-stretch-keywords":124,"css-font-style-keywords":125,"css-font-weight-keywords":126,"css-global-keywords":131,"css-system-font-keywords":132,"pick-by-alias":454}],131:[function(_dereq_,module,exports){
module.exports=[
	"inherit",
	"initial",
	"unset"
]

},{}],132:[function(_dereq_,module,exports){
module.exports=[
	"caption",
	"icon",
	"menu",
	"message-box",
	"small-caption",
	"status-bar"
]

},{}],133:[function(_dereq_,module,exports){
"use strict"

function dcubicHermite(p0, v0, p1, v1, t, f) {
  var dh00 = 6*t*t-6*t,
      dh10 = 3*t*t-4*t + 1,
      dh01 = -6*t*t+6*t,
      dh11 = 3*t*t-2*t
  if(p0.length) {
    if(!f) {
      f = new Array(p0.length)
    }
    for(var i=p0.length-1; i>=0; --i) {
      f[i] = dh00*p0[i] + dh10*v0[i] + dh01*p1[i] + dh11*v1[i]
    }
    return f
  }
  return dh00*p0 + dh10*v0 + dh01*p1[i] + dh11*v1
}

function cubicHermite(p0, v0, p1, v1, t, f) {
  var ti  = (t-1), t2 = t*t, ti2 = ti*ti,
      h00 = (1+2*t)*ti2,
      h10 = t*ti2,
      h01 = t2*(3-2*t),
      h11 = t2*ti
  if(p0.length) {
    if(!f) {
      f = new Array(p0.length)
    }
    for(var i=p0.length-1; i>=0; --i) {
      f[i] = h00*p0[i] + h10*v0[i] + h01*p1[i] + h11*v1[i]
    }
    return f
  }
  return h00*p0 + h10*v0 + h01*p1 + h11*v1
}

module.exports = cubicHermite
module.exports.derivative = dcubicHermite
},{}],134:[function(_dereq_,module,exports){
"use strict"

var createThunk = _dereq_("./lib/thunk.js")

function Procedure() {
  this.argTypes = []
  this.shimArgs = []
  this.arrayArgs = []
  this.arrayBlockIndices = []
  this.scalarArgs = []
  this.offsetArgs = []
  this.offsetArgIndex = []
  this.indexArgs = []
  this.shapeArgs = []
  this.funcName = ""
  this.pre = null
  this.body = null
  this.post = null
  this.debug = false
}

function compileCwise(user_args) {
  //Create procedure
  var proc = new Procedure()
  
  //Parse blocks
  proc.pre    = user_args.pre
  proc.body   = user_args.body
  proc.post   = user_args.post

  //Parse arguments
  var proc_args = user_args.args.slice(0)
  proc.argTypes = proc_args
  for(var i=0; i<proc_args.length; ++i) {
    var arg_type = proc_args[i]
    if(arg_type === "array" || (typeof arg_type === "object" && arg_type.blockIndices)) {
      proc.argTypes[i] = "array"
      proc.arrayArgs.push(i)
      proc.arrayBlockIndices.push(arg_type.blockIndices ? arg_type.blockIndices : 0)
      proc.shimArgs.push("array" + i)
      if(i < proc.pre.args.length && proc.pre.args[i].count>0) {
        throw new Error("cwise: pre() block may not reference array args")
      }
      if(i < proc.post.args.length && proc.post.args[i].count>0) {
        throw new Error("cwise: post() block may not reference array args")
      }
    } else if(arg_type === "scalar") {
      proc.scalarArgs.push(i)
      proc.shimArgs.push("scalar" + i)
    } else if(arg_type === "index") {
      proc.indexArgs.push(i)
      if(i < proc.pre.args.length && proc.pre.args[i].count > 0) {
        throw new Error("cwise: pre() block may not reference array index")
      }
      if(i < proc.body.args.length && proc.body.args[i].lvalue) {
        throw new Error("cwise: body() block may not write to array index")
      }
      if(i < proc.post.args.length && proc.post.args[i].count > 0) {
        throw new Error("cwise: post() block may not reference array index")
      }
    } else if(arg_type === "shape") {
      proc.shapeArgs.push(i)
      if(i < proc.pre.args.length && proc.pre.args[i].lvalue) {
        throw new Error("cwise: pre() block may not write to array shape")
      }
      if(i < proc.body.args.length && proc.body.args[i].lvalue) {
        throw new Error("cwise: body() block may not write to array shape")
      }
      if(i < proc.post.args.length && proc.post.args[i].lvalue) {
        throw new Error("cwise: post() block may not write to array shape")
      }
    } else if(typeof arg_type === "object" && arg_type.offset) {
      proc.argTypes[i] = "offset"
      proc.offsetArgs.push({ array: arg_type.array, offset:arg_type.offset })
      proc.offsetArgIndex.push(i)
    } else {
      throw new Error("cwise: Unknown argument type " + proc_args[i])
    }
  }
  
  //Make sure at least one array argument was specified
  if(proc.arrayArgs.length <= 0) {
    throw new Error("cwise: No array arguments specified")
  }
  
  //Make sure arguments are correct
  if(proc.pre.args.length > proc_args.length) {
    throw new Error("cwise: Too many arguments in pre() block")
  }
  if(proc.body.args.length > proc_args.length) {
    throw new Error("cwise: Too many arguments in body() block")
  }
  if(proc.post.args.length > proc_args.length) {
    throw new Error("cwise: Too many arguments in post() block")
  }

  //Check debug flag
  proc.debug = !!user_args.printCode || !!user_args.debug
  
  //Retrieve name
  proc.funcName = user_args.funcName || "cwise"
  
  //Read in block size
  proc.blockSize = user_args.blockSize || 64

  return createThunk(proc)
}

module.exports = compileCwise

},{"./lib/thunk.js":136}],135:[function(_dereq_,module,exports){
"use strict"

var uniq = _dereq_("uniq")

// This function generates very simple loops analogous to how you typically traverse arrays (the outermost loop corresponds to the slowest changing index, the innermost loop to the fastest changing index)
// TODO: If two arrays have the same strides (and offsets) there is potential for decreasing the number of "pointers" and related variables. The drawback is that the type signature would become more specific and that there would thus be less potential for caching, but it might still be worth it, especially when dealing with large numbers of arguments.
function innerFill(order, proc, body) {
  var dimension = order.length
    , nargs = proc.arrayArgs.length
    , has_index = proc.indexArgs.length>0
    , code = []
    , vars = []
    , idx=0, pidx=0, i, j
  for(i=0; i<dimension; ++i) { // Iteration variables
    vars.push(["i",i,"=0"].join(""))
  }
  //Compute scan deltas
  for(j=0; j<nargs; ++j) {
    for(i=0; i<dimension; ++i) {
      pidx = idx
      idx = order[i]
      if(i === 0) { // The innermost/fastest dimension's delta is simply its stride
        vars.push(["d",j,"s",i,"=t",j,"p",idx].join(""))
      } else { // For other dimensions the delta is basically the stride minus something which essentially "rewinds" the previous (more inner) dimension
        vars.push(["d",j,"s",i,"=(t",j,"p",idx,"-s",pidx,"*t",j,"p",pidx,")"].join(""))
      }
    }
  }
  if (vars.length > 0) {
    code.push("var " + vars.join(","))
  }  
  //Scan loop
  for(i=dimension-1; i>=0; --i) { // Start at largest stride and work your way inwards
    idx = order[i]
    code.push(["for(i",i,"=0;i",i,"<s",idx,";++i",i,"){"].join(""))
  }
  //Push body of inner loop
  code.push(body)
  //Advance scan pointers
  for(i=0; i<dimension; ++i) {
    pidx = idx
    idx = order[i]
    for(j=0; j<nargs; ++j) {
      code.push(["p",j,"+=d",j,"s",i].join(""))
    }
    if(has_index) {
      if(i > 0) {
        code.push(["index[",pidx,"]-=s",pidx].join(""))
      }
      code.push(["++index[",idx,"]"].join(""))
    }
    code.push("}")
  }
  return code.join("\n")
}

// Generate "outer" loops that loop over blocks of data, applying "inner" loops to the blocks by manipulating the local variables in such a way that the inner loop only "sees" the current block.
// TODO: If this is used, then the previous declaration (done by generateCwiseOp) of s* is essentially unnecessary.
//       I believe the s* are not used elsewhere (in particular, I don't think they're used in the pre/post parts and "shape" is defined independently), so it would be possible to make defining the s* dependent on what loop method is being used.
function outerFill(matched, order, proc, body) {
  var dimension = order.length
    , nargs = proc.arrayArgs.length
    , blockSize = proc.blockSize
    , has_index = proc.indexArgs.length > 0
    , code = []
  for(var i=0; i<nargs; ++i) {
    code.push(["var offset",i,"=p",i].join(""))
  }
  //Generate loops for unmatched dimensions
  // The order in which these dimensions are traversed is fairly arbitrary (from small stride to large stride, for the first argument)
  // TODO: It would be nice if the order in which these loops are placed would also be somehow "optimal" (at the very least we should check that it really doesn't hurt us if they're not).
  for(var i=matched; i<dimension; ++i) {
    code.push(["for(var j"+i+"=SS[", order[i], "]|0;j", i, ">0;){"].join("")) // Iterate back to front
    code.push(["if(j",i,"<",blockSize,"){"].join("")) // Either decrease j by blockSize (s = blockSize), or set it to zero (after setting s = j).
    code.push(["s",order[i],"=j",i].join(""))
    code.push(["j",i,"=0"].join(""))
    code.push(["}else{s",order[i],"=",blockSize].join(""))
    code.push(["j",i,"-=",blockSize,"}"].join(""))
    if(has_index) {
      code.push(["index[",order[i],"]=j",i].join(""))
    }
  }
  for(var i=0; i<nargs; ++i) {
    var indexStr = ["offset"+i]
    for(var j=matched; j<dimension; ++j) {
      indexStr.push(["j",j,"*t",i,"p",order[j]].join(""))
    }
    code.push(["p",i,"=(",indexStr.join("+"),")"].join(""))
  }
  code.push(innerFill(order, proc, body))
  for(var i=matched; i<dimension; ++i) {
    code.push("}")
  }
  return code.join("\n")
}

//Count the number of compatible inner orders
// This is the length of the longest common prefix of the arrays in orders.
// Each array in orders lists the dimensions of the correspond ndarray in order of increasing stride.
// This is thus the maximum number of dimensions that can be efficiently traversed by simple nested loops for all arrays.
function countMatches(orders) {
  var matched = 0, dimension = orders[0].length
  while(matched < dimension) {
    for(var j=1; j<orders.length; ++j) {
      if(orders[j][matched] !== orders[0][matched]) {
        return matched
      }
    }
    ++matched
  }
  return matched
}

//Processes a block according to the given data types
// Replaces variable names by different ones, either "local" ones (that are then ferried in and out of the given array) or ones matching the arguments that the function performing the ultimate loop will accept.
function processBlock(block, proc, dtypes) {
  var code = block.body
  var pre = []
  var post = []
  for(var i=0; i<block.args.length; ++i) {
    var carg = block.args[i]
    if(carg.count <= 0) {
      continue
    }
    var re = new RegExp(carg.name, "g")
    var ptrStr = ""
    var arrNum = proc.arrayArgs.indexOf(i)
    switch(proc.argTypes[i]) {
      case "offset":
        var offArgIndex = proc.offsetArgIndex.indexOf(i)
        var offArg = proc.offsetArgs[offArgIndex]
        arrNum = offArg.array
        ptrStr = "+q" + offArgIndex // Adds offset to the "pointer" in the array
      case "array":
        ptrStr = "p" + arrNum + ptrStr
        var localStr = "l" + i
        var arrStr = "a" + arrNum
        if (proc.arrayBlockIndices[arrNum] === 0) { // Argument to body is just a single value from this array
          if(carg.count === 1) { // Argument/array used only once(?)
            if(dtypes[arrNum] === "generic") {
              if(carg.lvalue) {
                pre.push(["var ", localStr, "=", arrStr, ".get(", ptrStr, ")"].join("")) // Is this necessary if the argument is ONLY used as an lvalue? (keep in mind that we can have a += something, so we would actually need to check carg.rvalue)
                code = code.replace(re, localStr)
                post.push([arrStr, ".set(", ptrStr, ",", localStr,")"].join(""))
              } else {
                code = code.replace(re, [arrStr, ".get(", ptrStr, ")"].join(""))
              }
            } else {
              code = code.replace(re, [arrStr, "[", ptrStr, "]"].join(""))
            }
          } else if(dtypes[arrNum] === "generic") {
            pre.push(["var ", localStr, "=", arrStr, ".get(", ptrStr, ")"].join("")) // TODO: Could we optimize by checking for carg.rvalue?
            code = code.replace(re, localStr)
            if(carg.lvalue) {
              post.push([arrStr, ".set(", ptrStr, ",", localStr,")"].join(""))
            }
          } else {
            pre.push(["var ", localStr, "=", arrStr, "[", ptrStr, "]"].join("")) // TODO: Could we optimize by checking for carg.rvalue?
            code = code.replace(re, localStr)
            if(carg.lvalue) {
              post.push([arrStr, "[", ptrStr, "]=", localStr].join(""))
            }
          }
        } else { // Argument to body is a "block"
          var reStrArr = [carg.name], ptrStrArr = [ptrStr]
          for(var j=0; j<Math.abs(proc.arrayBlockIndices[arrNum]); j++) {
            reStrArr.push("\\s*\\[([^\\]]+)\\]")
            ptrStrArr.push("$" + (j+1) + "*t" + arrNum + "b" + j) // Matched index times stride
          }
          re = new RegExp(reStrArr.join(""), "g")
          ptrStr = ptrStrArr.join("+")
          if(dtypes[arrNum] === "generic") {
            /*if(carg.lvalue) {
              pre.push(["var ", localStr, "=", arrStr, ".get(", ptrStr, ")"].join("")) // Is this necessary if the argument is ONLY used as an lvalue? (keep in mind that we can have a += something, so we would actually need to check carg.rvalue)
              code = code.replace(re, localStr)
              post.push([arrStr, ".set(", ptrStr, ",", localStr,")"].join(""))
            } else {
              code = code.replace(re, [arrStr, ".get(", ptrStr, ")"].join(""))
            }*/
            throw new Error("cwise: Generic arrays not supported in combination with blocks!")
          } else {
            // This does not produce any local variables, even if variables are used multiple times. It would be possible to do so, but it would complicate things quite a bit.
            code = code.replace(re, [arrStr, "[", ptrStr, "]"].join(""))
          }
        }
      break
      case "scalar":
        code = code.replace(re, "Y" + proc.scalarArgs.indexOf(i))
      break
      case "index":
        code = code.replace(re, "index")
      break
      case "shape":
        code = code.replace(re, "shape")
      break
    }
  }
  return [pre.join("\n"), code, post.join("\n")].join("\n").trim()
}

function typeSummary(dtypes) {
  var summary = new Array(dtypes.length)
  var allEqual = true
  for(var i=0; i<dtypes.length; ++i) {
    var t = dtypes[i]
    var digits = t.match(/\d+/)
    if(!digits) {
      digits = ""
    } else {
      digits = digits[0]
    }
    if(t.charAt(0) === 0) {
      summary[i] = "u" + t.charAt(1) + digits
    } else {
      summary[i] = t.charAt(0) + digits
    }
    if(i > 0) {
      allEqual = allEqual && summary[i] === summary[i-1]
    }
  }
  if(allEqual) {
    return summary[0]
  }
  return summary.join("")
}

//Generates a cwise operator
function generateCWiseOp(proc, typesig) {

  //Compute dimension
  // Arrays get put first in typesig, and there are two entries per array (dtype and order), so this gets the number of dimensions in the first array arg.
  var dimension = (typesig[1].length - Math.abs(proc.arrayBlockIndices[0]))|0
  var orders = new Array(proc.arrayArgs.length)
  var dtypes = new Array(proc.arrayArgs.length)
  for(var i=0; i<proc.arrayArgs.length; ++i) {
    dtypes[i] = typesig[2*i]
    orders[i] = typesig[2*i+1]
  }
  
  //Determine where block and loop indices start and end
  var blockBegin = [], blockEnd = [] // These indices are exposed as blocks
  var loopBegin = [], loopEnd = [] // These indices are iterated over
  var loopOrders = [] // orders restricted to the loop indices
  for(var i=0; i<proc.arrayArgs.length; ++i) {
    if (proc.arrayBlockIndices[i]<0) {
      loopBegin.push(0)
      loopEnd.push(dimension)
      blockBegin.push(dimension)
      blockEnd.push(dimension+proc.arrayBlockIndices[i])
    } else {
      loopBegin.push(proc.arrayBlockIndices[i]) // Non-negative
      loopEnd.push(proc.arrayBlockIndices[i]+dimension)
      blockBegin.push(0)
      blockEnd.push(proc.arrayBlockIndices[i])
    }
    var newOrder = []
    for(var j=0; j<orders[i].length; j++) {
      if (loopBegin[i]<=orders[i][j] && orders[i][j]<loopEnd[i]) {
        newOrder.push(orders[i][j]-loopBegin[i]) // If this is a loop index, put it in newOrder, subtracting loopBegin, to make sure that all loopOrders are using a common set of indices.
      }
    }
    loopOrders.push(newOrder)
  }

  //First create arguments for procedure
  var arglist = ["SS"] // SS is the overall shape over which we iterate
  var code = ["'use strict'"]
  var vars = []
  
  for(var j=0; j<dimension; ++j) {
    vars.push(["s", j, "=SS[", j, "]"].join("")) // The limits for each dimension.
  }
  for(var i=0; i<proc.arrayArgs.length; ++i) {
    arglist.push("a"+i) // Actual data array
    arglist.push("t"+i) // Strides
    arglist.push("p"+i) // Offset in the array at which the data starts (also used for iterating over the data)
    
    for(var j=0; j<dimension; ++j) { // Unpack the strides into vars for looping
      vars.push(["t",i,"p",j,"=t",i,"[",loopBegin[i]+j,"]"].join(""))
    }
    
    for(var j=0; j<Math.abs(proc.arrayBlockIndices[i]); ++j) { // Unpack the strides into vars for block iteration
      vars.push(["t",i,"b",j,"=t",i,"[",blockBegin[i]+j,"]"].join(""))
    }
  }
  for(var i=0; i<proc.scalarArgs.length; ++i) {
    arglist.push("Y" + i)
  }
  if(proc.shapeArgs.length > 0) {
    vars.push("shape=SS.slice(0)") // Makes the shape over which we iterate available to the user defined functions (so you can use width/height for example)
  }
  if(proc.indexArgs.length > 0) {
    // Prepare an array to keep track of the (logical) indices, initialized to dimension zeroes.
    var zeros = new Array(dimension)
    for(var i=0; i<dimension; ++i) {
      zeros[i] = "0"
    }
    vars.push(["index=[", zeros.join(","), "]"].join(""))
  }
  for(var i=0; i<proc.offsetArgs.length; ++i) { // Offset arguments used for stencil operations
    var off_arg = proc.offsetArgs[i]
    var init_string = []
    for(var j=0; j<off_arg.offset.length; ++j) {
      if(off_arg.offset[j] === 0) {
        continue
      } else if(off_arg.offset[j] === 1) {
        init_string.push(["t", off_arg.array, "p", j].join(""))      
      } else {
        init_string.push([off_arg.offset[j], "*t", off_arg.array, "p", j].join(""))
      }
    }
    if(init_string.length === 0) {
      vars.push("q" + i + "=0")
    } else {
      vars.push(["q", i, "=", init_string.join("+")].join(""))
    }
  }

  //Prepare this variables
  var thisVars = uniq([].concat(proc.pre.thisVars)
                      .concat(proc.body.thisVars)
                      .concat(proc.post.thisVars))
  vars = vars.concat(thisVars)
  if (vars.length > 0) {
    code.push("var " + vars.join(","))
  }
  for(var i=0; i<proc.arrayArgs.length; ++i) {
    code.push("p"+i+"|=0")
  }
  
  //Inline prelude
  if(proc.pre.body.length > 3) {
    code.push(processBlock(proc.pre, proc, dtypes))
  }

  //Process body
  var body = processBlock(proc.body, proc, dtypes)
  var matched = countMatches(loopOrders)
  if(matched < dimension) {
    code.push(outerFill(matched, loopOrders[0], proc, body)) // TODO: Rather than passing loopOrders[0], it might be interesting to look at passing an order that represents the majority of the arguments for example.
  } else {
    code.push(innerFill(loopOrders[0], proc, body))
  }

  //Inline epilog
  if(proc.post.body.length > 3) {
    code.push(processBlock(proc.post, proc, dtypes))
  }
  
  if(proc.debug) {
    console.log("-----Generated cwise routine for ", typesig, ":\n" + code.join("\n") + "\n----------")
  }
  
  var loopName = [(proc.funcName||"unnamed"), "_cwise_loop_", orders[0].join("s"),"m",matched,typeSummary(dtypes)].join("")
  var f = new Function(["function ",loopName,"(", arglist.join(","),"){", code.join("\n"),"} return ", loopName].join(""))
  return f()
}
module.exports = generateCWiseOp

},{"uniq":528}],136:[function(_dereq_,module,exports){
"use strict"

// The function below is called when constructing a cwise function object, and does the following:
// A function object is constructed which accepts as argument a compilation function and returns another function.
// It is this other function that is eventually returned by createThunk, and this function is the one that actually
// checks whether a certain pattern of arguments has already been used before and compiles new loops as needed.
// The compilation passed to the first function object is used for compiling new functions.
// Once this function object is created, it is called with compile as argument, where the first argument of compile
// is bound to "proc" (essentially containing a preprocessed version of the user arguments to cwise).
// So createThunk roughly works like this:
// function createThunk(proc) {
//   var thunk = function(compileBound) {
//     var CACHED = {}
//     return function(arrays and scalars) {
//       if (dtype and order of arrays in CACHED) {
//         var func = CACHED[dtype and order of arrays]
//       } else {
//         var func = CACHED[dtype and order of arrays] = compileBound(dtype and order of arrays)
//       }
//       return func(arrays and scalars)
//     }
//   }
//   return thunk(compile.bind1(proc))
// }

var compile = _dereq_("./compile.js")

function createThunk(proc) {
  var code = ["'use strict'", "var CACHED={}"]
  var vars = []
  var thunkName = proc.funcName + "_cwise_thunk"
  
  //Build thunk
  code.push(["return function ", thunkName, "(", proc.shimArgs.join(","), "){"].join(""))
  var typesig = []
  var string_typesig = []
  var proc_args = [["array",proc.arrayArgs[0],".shape.slice(", // Slice shape so that we only retain the shape over which we iterate (which gets passed to the cwise operator as SS).
                    Math.max(0,proc.arrayBlockIndices[0]),proc.arrayBlockIndices[0]<0?(","+proc.arrayBlockIndices[0]+")"):")"].join("")]
  var shapeLengthConditions = [], shapeConditions = []
  // Process array arguments
  for(var i=0; i<proc.arrayArgs.length; ++i) {
    var j = proc.arrayArgs[i]
    vars.push(["t", j, "=array", j, ".dtype,",
               "r", j, "=array", j, ".order"].join(""))
    typesig.push("t" + j)
    typesig.push("r" + j)
    string_typesig.push("t"+j)
    string_typesig.push("r"+j+".join()")
    proc_args.push("array" + j + ".data")
    proc_args.push("array" + j + ".stride")
    proc_args.push("array" + j + ".offset|0")
    if (i>0) { // Gather conditions to check for shape equality (ignoring block indices)
      shapeLengthConditions.push("array" + proc.arrayArgs[0] + ".shape.length===array" + j + ".shape.length+" + (Math.abs(proc.arrayBlockIndices[0])-Math.abs(proc.arrayBlockIndices[i])))
      shapeConditions.push("array" + proc.arrayArgs[0] + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[0]) + "]===array" + j + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[i]) + "]")
    }
  }
  // Check for shape equality
  if (proc.arrayArgs.length > 1) {
    code.push("if (!(" + shapeLengthConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same dimensionality!')")
    code.push("for(var shapeIndex=array" + proc.arrayArgs[0] + ".shape.length-" + Math.abs(proc.arrayBlockIndices[0]) + "; shapeIndex-->0;) {")
    code.push("if (!(" + shapeConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same shape!')")
    code.push("}")
  }
  // Process scalar arguments
  for(var i=0; i<proc.scalarArgs.length; ++i) {
    proc_args.push("scalar" + proc.scalarArgs[i])
  }
  // Check for cached function (and if not present, generate it)
  vars.push(["type=[", string_typesig.join(","), "].join()"].join(""))
  vars.push("proc=CACHED[type]")
  code.push("var " + vars.join(","))
  
  code.push(["if(!proc){",
             "CACHED[type]=proc=compile([", typesig.join(","), "])}",
             "return proc(", proc_args.join(","), ")}"].join(""))

  if(proc.debug) {
    console.log("-----Generated thunk:\n" + code.join("\n") + "\n----------")
  }
  
  //Compile thunk
  var thunk = new Function("compile", code.join("\n"))
  return thunk(compile.bind(undefined, proc))
}

module.exports = createThunk

},{"./compile.js":135}],137:[function(_dereq_,module,exports){
module.exports = _dereq_("cwise-compiler")
},{"cwise-compiler":134}],138:[function(_dereq_,module,exports){
'use strict';

var copy             = _dereq_('es5-ext/object/copy')
  , normalizeOptions = _dereq_('es5-ext/object/normalize-options')
  , ensureCallable   = _dereq_('es5-ext/object/valid-callable')
  , map              = _dereq_('es5-ext/object/map')
  , callable         = _dereq_('es5-ext/object/valid-callable')
  , validValue       = _dereq_('es5-ext/object/valid-value')

  , bind = Function.prototype.bind, defineProperty = Object.defineProperty
  , hasOwnProperty = Object.prototype.hasOwnProperty
  , define;

define = function (name, desc, options) {
	var value = validValue(desc) && callable(desc.value), dgs;
	dgs = copy(desc);
	delete dgs.writable;
	delete dgs.value;
	dgs.get = function () {
		if (!options.overwriteDefinition && hasOwnProperty.call(this, name)) return value;
		desc.value = bind.call(value, options.resolveContext ? options.resolveContext(this) : this);
		defineProperty(this, name, desc);
		return this[name];
	};
	return dgs;
};

module.exports = function (props/*, options*/) {
	var options = normalizeOptions(arguments[1]);
	if (options.resolveContext != null) ensureCallable(options.resolveContext);
	return map(props, function (desc, name) { return define(name, desc, options); });
};

},{"es5-ext/object/copy":178,"es5-ext/object/map":187,"es5-ext/object/normalize-options":188,"es5-ext/object/valid-callable":192,"es5-ext/object/valid-value":194}],139:[function(_dereq_,module,exports){
'use strict';

var assign        = _dereq_('es5-ext/object/assign')
  , normalizeOpts = _dereq_('es5-ext/object/normalize-options')
  , isCallable    = _dereq_('es5-ext/object/is-callable')
  , contains      = _dereq_('es5-ext/string/#/contains')

  , d;

d = module.exports = function (dscr, value/*, options*/) {
	var c, e, w, options, desc;
	if ((arguments.length < 2) || (typeof dscr !== 'string')) {
		options = value;
		value = dscr;
		dscr = null;
	} else {
		options = arguments[2];
	}
	if (dscr == null) {
		c = w = true;
		e = false;
	} else {
		c = contains.call(dscr, 'c');
		e = contains.call(dscr, 'e');
		w = contains.call(dscr, 'w');
	}

	desc = { value: value, configurable: c, enumerable: e, writable: w };
	return !options ? desc : assign(normalizeOpts(options), desc);
};

d.gs = function (dscr, get, set/*, options*/) {
	var c, e, options, desc;
	if (typeof dscr !== 'string') {
		options = set;
		set = get;
		get = dscr;
		dscr = null;
	} else {
		options = arguments[3];
	}
	if (get == null) {
		get = undefined;
	} else if (!isCallable(get)) {
		options = get;
		get = set = undefined;
	} else if (set == null) {
		set = undefined;
	} else if (!isCallable(set)) {
		options = set;
		set = undefined;
	}
	if (dscr == null) {
		c = true;
		e = false;
	} else {
		c = contains.call(dscr, 'c');
		e = contains.call(dscr, 'e');
	}

	desc = { get: get, set: set, configurable: c, enumerable: e };
	return !options ? desc : assign(normalizeOpts(options), desc);
};

},{"es5-ext/object/assign":175,"es5-ext/object/is-callable":181,"es5-ext/object/normalize-options":188,"es5-ext/string/#/contains":195}],140:[function(_dereq_,module,exports){
// https://d3js.org/d3-array/ v1.2.4 Copyright 2018 Mike Bostock
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.d3 = global.d3 || {})));
}(this, (function (exports) { 'use strict';

function ascending(a, b) {
  return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}

function bisector(compare) {
  if (compare.length === 1) compare = ascendingComparator(compare);
  return {
    left: function(a, x, lo, hi) {
      if (lo == null) lo = 0;
      if (hi == null) hi = a.length;
      while (lo < hi) {
        var mid = lo + hi >>> 1;
        if (compare(a[mid], x) < 0) lo = mid + 1;
        else hi = mid;
      }
      return lo;
    },
    right: function(a, x, lo, hi) {
      if (lo == null) lo = 0;
      if (hi == null) hi = a.length;
      while (lo < hi) {
        var mid = lo + hi >>> 1;
        if (compare(a[mid], x) > 0) hi = mid;
        else lo = mid + 1;
      }
      return lo;
    }
  };
}

function ascendingComparator(f) {
  return function(d, x) {
    return ascending(f(d), x);
  };
}

var ascendingBisect = bisector(ascending);
var bisectRight = ascendingBisect.right;
var bisectLeft = ascendingBisect.left;

function pairs(array, f) {
  if (f == null) f = pair;
  var i = 0, n = array.length - 1, p = array[0], pairs = new Array(n < 0 ? 0 : n);
  while (i < n) pairs[i] = f(p, p = array[++i]);
  return pairs;
}

function pair(a, b) {
  return [a, b];
}

function cross(values0, values1, reduce) {
  var n0 = values0.length,
      n1 = values1.length,
      values = new Array(n0 * n1),
      i0,
      i1,
      i,
      value0;

  if (reduce == null) reduce = pair;

  for (i0 = i = 0; i0 < n0; ++i0) {
    for (value0 = values0[i0], i1 = 0; i1 < n1; ++i1, ++i) {
      values[i] = reduce(value0, values1[i1]);
    }
  }

  return values;
}

function descending(a, b) {
  return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
}

function number(x) {
  return x === null ? NaN : +x;
}

function variance(values, valueof) {
  var n = values.length,
      m = 0,
      i = -1,
      mean = 0,
      value,
      delta,
      sum = 0;

  if (valueof == null) {
    while (++i < n) {
      if (!isNaN(value = number(values[i]))) {
        delta = value - mean;
        mean += delta / ++m;
        sum += delta * (value - mean);
      }
    }
  }

  else {
    while (++i < n) {
      if (!isNaN(value = number(valueof(values[i], i, values)))) {
        delta = value - mean;
        mean += delta / ++m;
        sum += delta * (value - mean);
      }
    }
  }

  if (m > 1) return sum / (m - 1);
}

function deviation(array, f) {
  var v = variance(array, f);
  return v ? Math.sqrt(v) : v;
}

function extent(values, valueof) {
  var n = values.length,
      i = -1,
      value,
      min,
      max;

  if (valueof == null) {
    while (++i < n) { // Find the first comparable value.
      if ((value = values[i]) != null && value >= value) {
        min = max = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = values[i]) != null) {
            if (min > value) min = value;
            if (max < value) max = value;
          }
        }
      }
    }
  }

  else {
    while (++i < n) { // Find the first comparable value.
      if ((value = valueof(values[i], i, values)) != null && value >= value) {
        min = max = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = valueof(values[i], i, values)) != null) {
            if (min > value) min = value;
            if (max < value) max = value;
          }
        }
      }
    }
  }

  return [min, max];
}

var array = Array.prototype;

var slice = array.slice;
var map = array.map;

function constant(x) {
  return function() {
    return x;
  };
}

function identity(x) {
  return x;
}

function range(start, stop, step) {
  start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;

  var i = -1,
      n = Math.max(0, Math.ceil((stop - start) / step)) | 0,
      range = new Array(n);

  while (++i < n) {
    range[i] = start + i * step;
  }

  return range;
}

var e10 = Math.sqrt(50),
    e5 = Math.sqrt(10),
    e2 = Math.sqrt(2);

function ticks(start, stop, count) {
  var reverse,
      i = -1,
      n,
      ticks,
      step;

  stop = +stop, start = +start, count = +count;
  if (start === stop && count > 0) return [start];
  if (reverse = stop < start) n = start, start = stop, stop = n;
  if ((step = tickIncrement(start, stop, count)) === 0 || !isFinite(step)) return [];

  if (step > 0) {
    start = Math.ceil(start / step);
    stop = Math.floor(stop / step);
    ticks = new Array(n = Math.ceil(stop - start + 1));
    while (++i < n) ticks[i] = (start + i) * step;
  } else {
    start = Math.floor(start * step);
    stop = Math.ceil(stop * step);
    ticks = new Array(n = Math.ceil(start - stop + 1));
    while (++i < n) ticks[i] = (start - i) / step;
  }

  if (reverse) ticks.reverse();

  return ticks;
}

function tickIncrement(start, stop, count) {
  var step = (stop - start) / Math.max(0, count),
      power = Math.floor(Math.log(step) / Math.LN10),
      error = step / Math.pow(10, power);
  return power >= 0
      ? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power)
      : -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1);
}

function tickStep(start, stop, count) {
  var step0 = Math.abs(stop - start) / Math.max(0, count),
      step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)),
      error = step0 / step1;
  if (error >= e10) step1 *= 10;
  else if (error >= e5) step1 *= 5;
  else if (error >= e2) step1 *= 2;
  return stop < start ? -step1 : step1;
}

function sturges(values) {
  return Math.ceil(Math.log(values.length) / Math.LN2) + 1;
}

function histogram() {
  var value = identity,
      domain = extent,
      threshold = sturges;

  function histogram(data) {
    var i,
        n = data.length,
        x,
        values = new Array(n);

    for (i = 0; i < n; ++i) {
      values[i] = value(data[i], i, data);
    }

    var xz = domain(values),
        x0 = xz[0],
        x1 = xz[1],
        tz = threshold(values, x0, x1);

    // Convert number of thresholds into uniform thresholds.
    if (!Array.isArray(tz)) {
      tz = tickStep(x0, x1, tz);
      tz = range(Math.ceil(x0 / tz) * tz, x1, tz); // exclusive
    }

    // Remove any thresholds outside the domain.
    var m = tz.length;
    while (tz[0] <= x0) tz.shift(), --m;
    while (tz[m - 1] > x1) tz.pop(), --m;

    var bins = new Array(m + 1),
        bin;

    // Initialize bins.
    for (i = 0; i <= m; ++i) {
      bin = bins[i] = [];
      bin.x0 = i > 0 ? tz[i - 1] : x0;
      bin.x1 = i < m ? tz[i] : x1;
    }

    // Assign data to bins by value, ignoring any outside the domain.
    for (i = 0; i < n; ++i) {
      x = values[i];
      if (x0 <= x && x <= x1) {
        bins[bisectRight(tz, x, 0, m)].push(data[i]);
      }
    }

    return bins;
  }

  histogram.value = function(_) {
    return arguments.length ? (value = typeof _ === "function" ? _ : constant(_), histogram) : value;
  };

  histogram.domain = function(_) {
    return arguments.length ? (domain = typeof _ === "function" ? _ : constant([_[0], _[1]]), histogram) : domain;
  };

  histogram.thresholds = function(_) {
    return arguments.length ? (threshold = typeof _ === "function" ? _ : Array.isArray(_) ? constant(slice.call(_)) : constant(_), histogram) : threshold;
  };

  return histogram;
}

function quantile(values, p, valueof) {
  if (valueof == null) valueof = number;
  if (!(n = values.length)) return;
  if ((p = +p) <= 0 || n < 2) return +valueof(values[0], 0, values);
  if (p >= 1) return +valueof(values[n - 1], n - 1, values);
  var n,
      i = (n - 1) * p,
      i0 = Math.floor(i),
      value0 = +valueof(values[i0], i0, values),
      value1 = +valueof(values[i0 + 1], i0 + 1, values);
  return value0 + (value1 - value0) * (i - i0);
}

function freedmanDiaconis(values, min, max) {
  values = map.call(values, number).sort(ascending);
  return Math.ceil((max - min) / (2 * (quantile(values, 0.75) - quantile(values, 0.25)) * Math.pow(values.length, -1 / 3)));
}

function scott(values, min, max) {
  return Math.ceil((max - min) / (3.5 * deviation(values) * Math.pow(values.length, -1 / 3)));
}

function max(values, valueof) {
  var n = values.length,
      i = -1,
      value,
      max;

  if (valueof == null) {
    while (++i < n) { // Find the first comparable value.
      if ((value = values[i]) != null && value >= value) {
        max = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = values[i]) != null && value > max) {
            max = value;
          }
        }
      }
    }
  }

  else {
    while (++i < n) { // Find the first comparable value.
      if ((value = valueof(values[i], i, values)) != null && value >= value) {
        max = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = valueof(values[i], i, values)) != null && value > max) {
            max = value;
          }
        }
      }
    }
  }

  return max;
}

function mean(values, valueof) {
  var n = values.length,
      m = n,
      i = -1,
      value,
      sum = 0;

  if (valueof == null) {
    while (++i < n) {
      if (!isNaN(value = number(values[i]))) sum += value;
      else --m;
    }
  }

  else {
    while (++i < n) {
      if (!isNaN(value = number(valueof(values[i], i, values)))) sum += value;
      else --m;
    }
  }

  if (m) return sum / m;
}

function median(values, valueof) {
  var n = values.length,
      i = -1,
      value,
      numbers = [];

  if (valueof == null) {
    while (++i < n) {
      if (!isNaN(value = number(values[i]))) {
        numbers.push(value);
      }
    }
  }

  else {
    while (++i < n) {
      if (!isNaN(value = number(valueof(values[i], i, values)))) {
        numbers.push(value);
      }
    }
  }

  return quantile(numbers.sort(ascending), 0.5);
}

function merge(arrays) {
  var n = arrays.length,
      m,
      i = -1,
      j = 0,
      merged,
      array;

  while (++i < n) j += arrays[i].length;
  merged = new Array(j);

  while (--n >= 0) {
    array = arrays[n];
    m = array.length;
    while (--m >= 0) {
      merged[--j] = array[m];
    }
  }

  return merged;
}

function min(values, valueof) {
  var n = values.length,
      i = -1,
      value,
      min;

  if (valueof == null) {
    while (++i < n) { // Find the first comparable value.
      if ((value = values[i]) != null && value >= value) {
        min = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = values[i]) != null && min > value) {
            min = value;
          }
        }
      }
    }
  }

  else {
    while (++i < n) { // Find the first comparable value.
      if ((value = valueof(values[i], i, values)) != null && value >= value) {
        min = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = valueof(values[i], i, values)) != null && min > value) {
            min = value;
          }
        }
      }
    }
  }

  return min;
}

function permute(array, indexes) {
  var i = indexes.length, permutes = new Array(i);
  while (i--) permutes[i] = array[indexes[i]];
  return permutes;
}

function scan(values, compare) {
  if (!(n = values.length)) return;
  var n,
      i = 0,
      j = 0,
      xi,
      xj = values[j];

  if (compare == null) compare = ascending;

  while (++i < n) {
    if (compare(xi = values[i], xj) < 0 || compare(xj, xj) !== 0) {
      xj = xi, j = i;
    }
  }

  if (compare(xj, xj) === 0) return j;
}

function shuffle(array, i0, i1) {
  var m = (i1 == null ? array.length : i1) - (i0 = i0 == null ? 0 : +i0),
      t,
      i;

  while (m) {
    i = Math.random() * m-- | 0;
    t = array[m + i0];
    array[m + i0] = array[i + i0];
    array[i + i0] = t;
  }

  return array;
}

function sum(values, valueof) {
  var n = values.length,
      i = -1,
      value,
      sum = 0;

  if (valueof == null) {
    while (++i < n) {
      if (value = +values[i]) sum += value; // Note: zero and null are equivalent.
    }
  }

  else {
    while (++i < n) {
      if (value = +valueof(values[i], i, values)) sum += value;
    }
  }

  return sum;
}

function transpose(matrix) {
  if (!(n = matrix.length)) return [];
  for (var i = -1, m = min(matrix, length), transpose = new Array(m); ++i < m;) {
    for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n;) {
      row[j] = matrix[j][i];
    }
  }
  return transpose;
}

function length(d) {
  return d.length;
}

function zip() {
  return transpose(arguments);
}

exports.bisect = bisectRight;
exports.bisectRight = bisectRight;
exports.bisectLeft = bisectLeft;
exports.ascending = ascending;
exports.bisector = bisector;
exports.cross = cross;
exports.descending = descending;
exports.deviation = deviation;
exports.extent = extent;
exports.histogram = histogram;
exports.thresholdFreedmanDiaconis = freedmanDiaconis;
exports.thresholdScott = scott;
exports.thresholdSturges = sturges;
exports.max = max;
exports.mean = mean;
exports.median = median;
exports.merge = merge;
exports.min = min;
exports.pairs = pairs;
exports.permute = permute;
exports.quantile = quantile;
exports.range = range;
exports.scan = scan;
exports.shuffle = shuffle;
exports.sum = sum;
exports.ticks = ticks;
exports.tickIncrement = tickIncrement;
exports.tickStep = tickStep;
exports.transpose = transpose;
exports.variance = variance;
exports.zip = zip;

Object.defineProperty(exports, '__esModule', { value: true });

})));

},{}],141:[function(_dereq_,module,exports){
// https://d3js.org/d3-collection/ Version 1.0.4. Copyright 2017 Mike Bostock.
(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
	typeof define === 'function' && define.amd ? define(['exports'], factory) :
	(factory((global.d3 = global.d3 || {})));
}(this, (function (exports) { 'use strict';

var prefix = "$";

function Map() {}

Map.prototype = map.prototype = {
  constructor: Map,
  has: function(key) {
    return (prefix + key) in this;
  },
  get: function(key) {
    return this[prefix + key];
  },
  set: function(key, value) {
    this[prefix + key] = value;
    return this;
  },
  remove: function(key) {
    var property = prefix + key;
    return property in this && delete this[property];
  },
  clear: function() {
    for (var property in this) if (property[0] === prefix) delete this[property];
  },
  keys: function() {
    var keys = [];
    for (var property in this) if (property[0] === prefix) keys.push(property.slice(1));
    return keys;
  },
  values: function() {
    var values = [];
    for (var property in this) if (property[0] === prefix) values.push(this[property]);
    return values;
  },
  entries: function() {
    var entries = [];
    for (var property in this) if (property[0] === prefix) entries.push({key: property.slice(1), value: this[property]});
    return entries;
  },
  size: function() {
    var size = 0;
    for (var property in this) if (property[0] === prefix) ++size;
    return size;
  },
  empty: function() {
    for (var property in this) if (property[0] === prefix) return false;
    return true;
  },
  each: function(f) {
    for (var property in this) if (property[0] === prefix) f(this[property], property.slice(1), this);
  }
};

function map(object, f) {
  var map = new Map;

  // Copy constructor.
  if (object instanceof Map) object.each(function(value, key) { map.set(key, value); });

  // Index array by numeric index or specified key function.
  else if (Array.isArray(object)) {
    var i = -1,
        n = object.length,
        o;

    if (f == null) while (++i < n) map.set(i, object[i]);
    else while (++i < n) map.set(f(o = object[i], i, object), o);
  }

  // Convert object to map.
  else if (object) for (var key in object) map.set(key, object[key]);

  return map;
}

var nest = function() {
  var keys = [],
      sortKeys = [],
      sortValues,
      rollup,
      nest;

  function apply(array, depth, createResult, setResult) {
    if (depth >= keys.length) {
      if (sortValues != null) array.sort(sortValues);
      return rollup != null ? rollup(array) : array;
    }

    var i = -1,
        n = array.length,
        key = keys[depth++],
        keyValue,
        value,
        valuesByKey = map(),
        values,
        result = createResult();

    while (++i < n) {
      if (values = valuesByKey.get(keyValue = key(value = array[i]) + "")) {
        values.push(value);
      } else {
        valuesByKey.set(keyValue, [value]);
      }
    }

    valuesByKey.each(function(values, key) {
      setResult(result, key, apply(values, depth, createResult, setResult));
    });

    return result;
  }

  function entries(map$$1, depth) {
    if (++depth > keys.length) return map$$1;
    var array, sortKey = sortKeys[depth - 1];
    if (rollup != null && depth >= keys.length) array = map$$1.entries();
    else array = [], map$$1.each(function(v, k) { array.push({key: k, values: entries(v, depth)}); });
    return sortKey != null ? array.sort(function(a, b) { return sortKey(a.key, b.key); }) : array;
  }

  return nest = {
    object: function(array) { return apply(array, 0, createObject, setObject); },
    map: function(array) { return apply(array, 0, createMap, setMap); },
    entries: function(array) { return entries(apply(array, 0, createMap, setMap), 0); },
    key: function(d) { keys.push(d); return nest; },
    sortKeys: function(order) { sortKeys[keys.length - 1] = order; return nest; },
    sortValues: function(order) { sortValues = order; return nest; },
    rollup: function(f) { rollup = f; return nest; }
  };
};

function createObject() {
  return {};
}

function setObject(object, key, value) {
  object[key] = value;
}

function createMap() {
  return map();
}

function setMap(map$$1, key, value) {
  map$$1.set(key, value);
}

function Set() {}

var proto = map.prototype;

Set.prototype = set.prototype = {
  constructor: Set,
  has: proto.has,
  add: function(value) {
    value += "";
    this[prefix + value] = value;
    return this;
  },
  remove: proto.remove,
  clear: proto.clear,
  values: proto.keys,
  size: proto.size,
  empty: proto.empty,
  each: proto.each
};

function set(object, f) {
  var set = new Set;

  // Copy constructor.
  if (object instanceof Set) object.each(function(value) { set.add(value); });

  // Otherwise, assume it’s an array.
  else if (object) {
    var i = -1, n = object.length;
    if (f == null) while (++i < n) set.add(object[i]);
    else while (++i < n) set.add(f(object[i], i, object));
  }

  return set;
}

var keys = function(map) {
  var keys = [];
  for (var key in map) keys.push(key);
  return keys;
};

var values = function(map) {
  var values = [];
  for (var key in map) values.push(map[key]);
  return values;
};

var entries = function(map) {
  var entries = [];
  for (var key in map) entries.push({key: key, value: map[key]});
  return entries;
};

exports.nest = nest;
exports.set = set;
exports.map = map;
exports.keys = keys;
exports.values = values;
exports.entries = entries;

Object.defineProperty(exports, '__esModule', { value: true });

})));

},{}],142:[function(_dereq_,module,exports){
// https://d3js.org/d3-color/ v1.2.3 Copyright 2018 Mike Bostock
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.d3 = global.d3 || {})));
}(this, (function (exports) { 'use strict';

function define(constructor, factory, prototype) {
  constructor.prototype = factory.prototype = prototype;
  prototype.constructor = constructor;
}

function extend(parent, definition) {
  var prototype = Object.create(parent.prototype);
  for (var key in definition) prototype[key] = definition[key];
  return prototype;
}

function Color() {}

var darker = 0.7;
var brighter = 1 / darker;

var reI = "\\s*([+-]?\\d+)\\s*",
    reN = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",
    reP = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",
    reHex3 = /^#([0-9a-f]{3})$/,
    reHex6 = /^#([0-9a-f]{6})$/,
    reRgbInteger = new RegExp("^rgb\\(" + [reI, reI, reI] + "\\)$"),
    reRgbPercent = new RegExp("^rgb\\(" + [reP, reP, reP] + "\\)$"),
    reRgbaInteger = new RegExp("^rgba\\(" + [reI, reI, reI, reN] + "\\)$"),
    reRgbaPercent = new RegExp("^rgba\\(" + [reP, reP, reP, reN] + "\\)$"),
    reHslPercent = new RegExp("^hsl\\(" + [reN, reP, reP] + "\\)$"),
    reHslaPercent = new RegExp("^hsla\\(" + [reN, reP, reP, reN] + "\\)$");

var named = {
  aliceblue: 0xf0f8ff,
  antiquewhite: 0xfaebd7,
  aqua: 0x00ffff,
  aquamarine: 0x7fffd4,
  azure: 0xf0ffff,
  beige: 0xf5f5dc,
  bisque: 0xffe4c4,
  black: 0x000000,
  blanchedalmond: 0xffebcd,
  blue: 0x0000ff,
  blueviolet: 0x8a2be2,
  brown: 0xa52a2a,
  burlywood: 0xdeb887,
  cadetblue: 0x5f9ea0,
  chartreuse: 0x7fff00,
  chocolate: 0xd2691e,
  coral: 0xff7f50,
  cornflowerblue: 0x6495ed,
  cornsilk: 0xfff8dc,
  crimson: 0xdc143c,
  cyan: 0x00ffff,
  darkblue: 0x00008b,
  darkcyan: 0x008b8b,
  darkgoldenrod: 0xb8860b,
  darkgray: 0xa9a9a9,
  darkgreen: 0x006400,
  darkgrey: 0xa9a9a9,
  darkkhaki: 0xbdb76b,
  darkmagenta: 0x8b008b,
  darkolivegreen: 0x556b2f,
  darkorange: 0xff8c00,
  darkorchid: 0x9932cc,
  darkred: 0x8b0000,
  darksalmon: 0xe9967a,
  darkseagreen: 0x8fbc8f,
  darkslateblue: 0x483d8b,
  darkslategray: 0x2f4f4f,
  darkslategrey: 0x2f4f4f,
  darkturquoise: 0x00ced1,
  darkviolet: 0x9400d3,
  deeppink: 0xff1493,
  deepskyblue: 0x00bfff,
  dimgray: 0x696969,
  dimgrey: 0x696969,
  dodgerblue: 0x1e90ff,
  firebrick: 0xb22222,
  floralwhite: 0xfffaf0,
  forestgreen: 0x228b22,
  fuchsia: 0xff00ff,
  gainsboro: 0xdcdcdc,
  ghostwhite: 0xf8f8ff,
  gold: 0xffd700,
  goldenrod: 0xdaa520,
  gray: 0x808080,
  green: 0x008000,
  greenyellow: 0xadff2f,
  grey: 0x808080,
  honeydew: 0xf0fff0,
  hotpink: 0xff69b4,
  indianred: 0xcd5c5c,
  indigo: 0x4b0082,
  ivory: 0xfffff0,
  khaki: 0xf0e68c,
  lavender: 0xe6e6fa,
  lavenderblush: 0xfff0f5,
  lawngreen: 0x7cfc00,
  lemonchiffon: 0xfffacd,
  lightblue: 0xadd8e6,
  lightcoral: 0xf08080,
  lightcyan: 0xe0ffff,
  lightgoldenrodyellow: 0xfafad2,
  lightgray: 0xd3d3d3,
  lightgreen: 0x90ee90,
  lightgrey: 0xd3d3d3,
  lightpink: 0xffb6c1,
  lightsalmon: 0xffa07a,
  lightseagreen: 0x20b2aa,
  lightskyblue: 0x87cefa,
  lightslategray: 0x778899,
  lightslategrey: 0x778899,
  lightsteelblue: 0xb0c4de,
  lightyellow: 0xffffe0,
  lime: 0x00ff00,
  limegreen: 0x32cd32,
  linen: 0xfaf0e6,
  magenta: 0xff00ff,
  maroon: 0x800000,
  mediumaquamarine: 0x66cdaa,
  mediumblue: 0x0000cd,
  mediumorchid: 0xba55d3,
  mediumpurple: 0x9370db,
  mediumseagreen: 0x3cb371,
  mediumslateblue: 0x7b68ee,
  mediumspringgreen: 0x00fa9a,
  mediumturquoise: 0x48d1cc,
  mediumvioletred: 0xc71585,
  midnightblue: 0x191970,
  mintcream: 0xf5fffa,
  mistyrose: 0xffe4e1,
  moccasin: 0xffe4b5,
  navajowhite: 0xffdead,
  navy: 0x000080,
  oldlace: 0xfdf5e6,
  olive: 0x808000,
  olivedrab: 0x6b8e23,
  orange: 0xffa500,
  orangered: 0xff4500,
  orchid: 0xda70d6,
  palegoldenrod: 0xeee8aa,
  palegreen: 0x98fb98,
  paleturquoise: 0xafeeee,
  palevioletred: 0xdb7093,
  papayawhip: 0xffefd5,
  peachpuff: 0xffdab9,
  peru: 0xcd853f,
  pink: 0xffc0cb,
  plum: 0xdda0dd,
  powderblue: 0xb0e0e6,
  purple: 0x800080,
  rebeccapurple: 0x663399,
  red: 0xff0000,
  rosybrown: 0xbc8f8f,
  royalblue: 0x4169e1,
  saddlebrown: 0x8b4513,
  salmon: 0xfa8072,
  sandybrown: 0xf4a460,
  seagreen: 0x2e8b57,
  seashell: 0xfff5ee,
  sienna: 0xa0522d,
  silver: 0xc0c0c0,
  skyblue: 0x87ceeb,
  slateblue: 0x6a5acd,
  slategray: 0x708090,
  slategrey: 0x708090,
  snow: 0xfffafa,
  springgreen: 0x00ff7f,
  steelblue: 0x4682b4,
  tan: 0xd2b48c,
  teal: 0x008080,
  thistle: 0xd8bfd8,
  tomato: 0xff6347,
  turquoise: 0x40e0d0,
  violet: 0xee82ee,
  wheat: 0xf5deb3,
  white: 0xffffff,
  whitesmoke: 0xf5f5f5,
  yellow: 0xffff00,
  yellowgreen: 0x9acd32
};

define(Color, color, {
  displayable: function() {
    return this.rgb().displayable();
  },
  hex: function() {
    return this.rgb().hex();
  },
  toString: function() {
    return this.rgb() + "";
  }
});

function color(format) {
  var m;
  format = (format + "").trim().toLowerCase();
  return (m = reHex3.exec(format)) ? (m = parseInt(m[1], 16), new Rgb((m >> 8 & 0xf) | (m >> 4 & 0x0f0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1)) // #f00
      : (m = reHex6.exec(format)) ? rgbn(parseInt(m[1], 16)) // #ff0000
      : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)
      : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)
      : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)
      : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)
      : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)
      : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)
      : named.hasOwnProperty(format) ? rgbn(named[format])
      : format === "transparent" ? new Rgb(NaN, NaN, NaN, 0)
      : null;
}

function rgbn(n) {
  return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);
}

function rgba(r, g, b, a) {
  if (a <= 0) r = g = b = NaN;
  return new Rgb(r, g, b, a);
}

function rgbConvert(o) {
  if (!(o instanceof Color)) o = color(o);
  if (!o) return new Rgb;
  o = o.rgb();
  return new Rgb(o.r, o.g, o.b, o.opacity);
}

function rgb(r, g, b, opacity) {
  return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);
}

function Rgb(r, g, b, opacity) {
  this.r = +r;
  this.g = +g;
  this.b = +b;
  this.opacity = +opacity;
}

define(Rgb, rgb, extend(Color, {
  brighter: function(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  darker: function(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  rgb: function() {
    return this;
  },
  displayable: function() {
    return (0 <= this.r && this.r <= 255)
        && (0 <= this.g && this.g <= 255)
        && (0 <= this.b && this.b <= 255)
        && (0 <= this.opacity && this.opacity <= 1);
  },
  hex: function() {
    return "#" + hex(this.r) + hex(this.g) + hex(this.b);
  },
  toString: function() {
    var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
    return (a === 1 ? "rgb(" : "rgba(")
        + Math.max(0, Math.min(255, Math.round(this.r) || 0)) + ", "
        + Math.max(0, Math.min(255, Math.round(this.g) || 0)) + ", "
        + Math.max(0, Math.min(255, Math.round(this.b) || 0))
        + (a === 1 ? ")" : ", " + a + ")");
  }
}));

function hex(value) {
  value = Math.max(0, Math.min(255, Math.round(value) || 0));
  return (value < 16 ? "0" : "") + value.toString(16);
}

function hsla(h, s, l, a) {
  if (a <= 0) h = s = l = NaN;
  else if (l <= 0 || l >= 1) h = s = NaN;
  else if (s <= 0) h = NaN;
  return new Hsl(h, s, l, a);
}

function hslConvert(o) {
  if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);
  if (!(o instanceof Color)) o = color(o);
  if (!o) return new Hsl;
  if (o instanceof Hsl) return o;
  o = o.rgb();
  var r = o.r / 255,
      g = o.g / 255,
      b = o.b / 255,
      min = Math.min(r, g, b),
      max = Math.max(r, g, b),
      h = NaN,
      s = max - min,
      l = (max + min) / 2;
  if (s) {
    if (r === max) h = (g - b) / s + (g < b) * 6;
    else if (g === max) h = (b - r) / s + 2;
    else h = (r - g) / s + 4;
    s /= l < 0.5 ? max + min : 2 - max - min;
    h *= 60;
  } else {
    s = l > 0 && l < 1 ? 0 : h;
  }
  return new Hsl(h, s, l, o.opacity);
}

function hsl(h, s, l, opacity) {
  return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);
}

function Hsl(h, s, l, opacity) {
  this.h = +h;
  this.s = +s;
  this.l = +l;
  this.opacity = +opacity;
}

define(Hsl, hsl, extend(Color, {
  brighter: function(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  darker: function(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  rgb: function() {
    var h = this.h % 360 + (this.h < 0) * 360,
        s = isNaN(h) || isNaN(this.s) ? 0 : this.s,
        l = this.l,
        m2 = l + (l < 0.5 ? l : 1 - l) * s,
        m1 = 2 * l - m2;
    return new Rgb(
      hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),
      hsl2rgb(h, m1, m2),
      hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),
      this.opacity
    );
  },
  displayable: function() {
    return (0 <= this.s && this.s <= 1 || isNaN(this.s))
        && (0 <= this.l && this.l <= 1)
        && (0 <= this.opacity && this.opacity <= 1);
  }
}));

/* From FvD 13.37, CSS Color Module Level 3 */
function hsl2rgb(h, m1, m2) {
  return (h < 60 ? m1 + (m2 - m1) * h / 60
      : h < 180 ? m2
      : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60
      : m1) * 255;
}

var deg2rad = Math.PI / 180;
var rad2deg = 180 / Math.PI;

// https://beta.observablehq.com/@mbostock/lab-and-rgb
var K = 18,
    Xn = 0.96422,
    Yn = 1,
    Zn = 0.82521,
    t0 = 4 / 29,
    t1 = 6 / 29,
    t2 = 3 * t1 * t1,
    t3 = t1 * t1 * t1;

function labConvert(o) {
  if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity);
  if (o instanceof Hcl) {
    if (isNaN(o.h)) return new Lab(o.l, 0, 0, o.opacity);
    var h = o.h * deg2rad;
    return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity);
  }
  if (!(o instanceof Rgb)) o = rgbConvert(o);
  var r = rgb2lrgb(o.r),
      g = rgb2lrgb(o.g),
      b = rgb2lrgb(o.b),
      y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn), x, z;
  if (r === g && g === b) x = z = y; else {
    x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn);
    z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn);
  }
  return new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity);
}

function gray(l, opacity) {
  return new Lab(l, 0, 0, opacity == null ? 1 : opacity);
}

function lab(l, a, b, opacity) {
  return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity);
}

function Lab(l, a, b, opacity) {
  this.l = +l;
  this.a = +a;
  this.b = +b;
  this.opacity = +opacity;
}

define(Lab, lab, extend(Color, {
  brighter: function(k) {
    return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity);
  },
  darker: function(k) {
    return new Lab(this.l - K * (k == null ? 1 : k), this.a, this.b, this.opacity);
  },
  rgb: function() {
    var y = (this.l + 16) / 116,
        x = isNaN(this.a) ? y : y + this.a / 500,
        z = isNaN(this.b) ? y : y - this.b / 200;
    x = Xn * lab2xyz(x);
    y = Yn * lab2xyz(y);
    z = Zn * lab2xyz(z);
    return new Rgb(
      lrgb2rgb( 3.1338561 * x - 1.6168667 * y - 0.4906146 * z),
      lrgb2rgb(-0.9787684 * x + 1.9161415 * y + 0.0334540 * z),
      lrgb2rgb( 0.0719453 * x - 0.2289914 * y + 1.4052427 * z),
      this.opacity
    );
  }
}));

function xyz2lab(t) {
  return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;
}

function lab2xyz(t) {
  return t > t1 ? t * t * t : t2 * (t - t0);
}

function lrgb2rgb(x) {
  return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);
}

function rgb2lrgb(x) {
  return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
}

function hclConvert(o) {
  if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity);
  if (!(o instanceof Lab)) o = labConvert(o);
  if (o.a === 0 && o.b === 0) return new Hcl(NaN, 0, o.l, o.opacity);
  var h = Math.atan2(o.b, o.a) * rad2deg;
  return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity);
}

function lch(l, c, h, opacity) {
  return arguments.length === 1 ? hclConvert(l) : new Hcl(h, c, l, opacity == null ? 1 : opacity);
}

function hcl(h, c, l, opacity) {
  return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity);
}

function Hcl(h, c, l, opacity) {
  this.h = +h;
  this.c = +c;
  this.l = +l;
  this.opacity = +opacity;
}

define(Hcl, hcl, extend(Color, {
  brighter: function(k) {
    return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity);
  },
  darker: function(k) {
    return new Hcl(this.h, this.c, this.l - K * (k == null ? 1 : k), this.opacity);
  },
  rgb: function() {
    return labConvert(this).rgb();
  }
}));

var A = -0.14861,
    B = +1.78277,
    C = -0.29227,
    D = -0.90649,
    E = +1.97294,
    ED = E * D,
    EB = E * B,
    BC_DA = B * C - D * A;

function cubehelixConvert(o) {
  if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity);
  if (!(o instanceof Rgb)) o = rgbConvert(o);
  var r = o.r / 255,
      g = o.g / 255,
      b = o.b / 255,
      l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB),
      bl = b - l,
      k = (E * (g - l) - C * bl) / D,
      s = Math.sqrt(k * k + bl * bl) / (E * l * (1 - l)), // NaN if l=0 or l=1
      h = s ? Math.atan2(k, bl) * rad2deg - 120 : NaN;
  return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity);
}

function cubehelix(h, s, l, opacity) {
  return arguments.length === 1 ? cubehelixConvert(h) : new Cubehelix(h, s, l, opacity == null ? 1 : opacity);
}

function Cubehelix(h, s, l, opacity) {
  this.h = +h;
  this.s = +s;
  this.l = +l;
  this.opacity = +opacity;
}

define(Cubehelix, cubehelix, extend(Color, {
  brighter: function(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
  },
  darker: function(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
  },
  rgb: function() {
    var h = isNaN(this.h) ? 0 : (this.h + 120) * deg2rad,
        l = +this.l,
        a = isNaN(this.s) ? 0 : this.s * l * (1 - l),
        cosh = Math.cos(h),
        sinh = Math.sin(h);
    return new Rgb(
      255 * (l + a * (A * cosh + B * sinh)),
      255 * (l + a * (C * cosh + D * sinh)),
      255 * (l + a * (E * cosh)),
      this.opacity
    );
  }
}));

exports.color = color;
exports.rgb = rgb;
exports.hsl = hsl;
exports.lab = lab;
exports.hcl = hcl;
exports.lch = lch;
exports.gray = gray;
exports.cubehelix = cubehelix;

Object.defineProperty(exports, '__esModule', { value: true });

})));

},{}],143:[function(_dereq_,module,exports){
// https://d3js.org/d3-dispatch/ Version 1.0.3. Copyright 2017 Mike Bostock.
(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
	typeof define === 'function' && define.amd ? define(['exports'], factory) :
	(factory((global.d3 = global.d3 || {})));
}(this, (function (exports) { 'use strict';

var noop = {value: function() {}};

function dispatch() {
  for (var i = 0, n = arguments.length, _ = {}, t; i < n; ++i) {
    if (!(t = arguments[i] + "") || (t in _)) throw new Error("illegal type: " + t);
    _[t] = [];
  }
  return new Dispatch(_);
}

function Dispatch(_) {
  this._ = _;
}

function parseTypenames(typenames, types) {
  return typenames.trim().split(/^|\s+/).map(function(t) {
    var name = "", i = t.indexOf(".");
    if (i >= 0) name = t.slice(i + 1), t = t.slice(0, i);
    if (t && !types.hasOwnProperty(t)) throw new Error("unknown type: " + t);
    return {type: t, name: name};
  });
}

Dispatch.prototype = dispatch.prototype = {
  constructor: Dispatch,
  on: function(typename, callback) {
    var _ = this._,
        T = parseTypenames(typename + "", _),
        t,
        i = -1,
        n = T.length;

    // If no callback was specified, return the callback of the given type and name.
    if (arguments.length < 2) {
      while (++i < n) if ((t = (typename = T[i]).type) && (t = get(_[t], typename.name))) return t;
      return;
    }

    // If a type was specified, set the callback for the given type and name.
    // Otherwise, if a null callback was specified, remove callbacks of the given name.
    if (callback != null && typeof callback !== "function") throw new Error("invalid callback: " + callback);
    while (++i < n) {
      if (t = (typename = T[i]).type) _[t] = set(_[t], typename.name, callback);
      else if (callback == null) for (t in _) _[t] = set(_[t], typename.name, null);
    }

    return this;
  },
  copy: function() {
    var copy = {}, _ = this._;
    for (var t in _) copy[t] = _[t].slice();
    return new Dispatch(copy);
  },
  call: function(type, that) {
    if ((n = arguments.length - 2) > 0) for (var args = new Array(n), i = 0, n, t; i < n; ++i) args[i] = arguments[i + 2];
    if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type);
    for (t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args);
  },
  apply: function(type, that, args) {
    if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type);
    for (var t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args);
  }
};

function get(type, name) {
  for (var i = 0, n = type.length, c; i < n; ++i) {
    if ((c = type[i]).name === name) {
      return c.value;
    }
  }
}

function set(type, name, callback) {
  for (var i = 0, n = type.length; i < n; ++i) {
    if (type[i].name === name) {
      type[i] = noop, type = type.slice(0, i).concat(type.slice(i + 1));
      break;
    }
  }
  if (callback != null) type.push({name: name, value: callback});
  return type;
}

exports.dispatch = dispatch;

Object.defineProperty(exports, '__esModule', { value: true });

})));

},{}],144:[function(_dereq_,module,exports){
// https://d3js.org/d3-force/ Version 1.1.0. Copyright 2017 Mike Bostock.
(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, _dereq_('d3-quadtree'), _dereq_('d3-collection'), _dereq_('d3-dispatch'), _dereq_('d3-timer')) :
	typeof define === 'function' && define.amd ? define(['exports', 'd3-quadtree', 'd3-collection', 'd3-dispatch', 'd3-timer'], factory) :
	(factory((global.d3 = global.d3 || {}),global.d3,global.d3,global.d3,global.d3));
}(this, (function (exports,d3Quadtree,d3Collection,d3Dispatch,d3Timer) { 'use strict';

var center = function(x, y) {
  var nodes;

  if (x == null) x = 0;
  if (y == null) y = 0;

  function force() {
    var i,
        n = nodes.length,
        node,
        sx = 0,
        sy = 0;

    for (i = 0; i < n; ++i) {
      node = nodes[i], sx += node.x, sy += node.y;
    }

    for (sx = sx / n - x, sy = sy / n - y, i = 0; i < n; ++i) {
      node = nodes[i], node.x -= sx, node.y -= sy;
    }
  }

  force.initialize = function(_) {
    nodes = _;
  };

  force.x = function(_) {
    return arguments.length ? (x = +_, force) : x;
  };

  force.y = function(_) {
    return arguments.length ? (y = +_, force) : y;
  };

  return force;
};

var constant = function(x) {
  return function() {
    return x;
  };
};

var jiggle = function() {
  return (Math.random() - 0.5) * 1e-6;
};

function x(d) {
  return d.x + d.vx;
}

function y(d) {
  return d.y + d.vy;
}

var collide = function(radius) {
  var nodes,
      radii,
      strength = 1,
      iterations = 1;

  if (typeof radius !== "function") radius = constant(radius == null ? 1 : +radius);

  function force() {
    var i, n = nodes.length,
        tree,
        node,
        xi,
        yi,
        ri,
        ri2;

    for (var k = 0; k < iterations; ++k) {
      tree = d3Quadtree.quadtree(nodes, x, y).visitAfter(prepare);
      for (i = 0; i < n; ++i) {
        node = nodes[i];
        ri = radii[node.index], ri2 = ri * ri;
        xi = node.x + node.vx;
        yi = node.y + node.vy;
        tree.visit(apply);
      }
    }

    function apply(quad, x0, y0, x1, y1) {
      var data = quad.data, rj = quad.r, r = ri + rj;
      if (data) {
        if (data.index > node.index) {
          var x = xi - data.x - data.vx,
              y = yi - data.y - data.vy,
              l = x * x + y * y;
          if (l < r * r) {
            if (x === 0) x = jiggle(), l += x * x;
            if (y === 0) y = jiggle(), l += y * y;
            l = (r - (l = Math.sqrt(l))) / l * strength;
            node.vx += (x *= l) * (r = (rj *= rj) / (ri2 + rj));
            node.vy += (y *= l) * r;
            data.vx -= x * (r = 1 - r);
            data.vy -= y * r;
          }
        }
        return;
      }
      return x0 > xi + r || x1 < xi - r || y0 > yi + r || y1 < yi - r;
    }
  }

  function prepare(quad) {
    if (quad.data) return quad.r = radii[quad.data.index];
    for (var i = quad.r = 0; i < 4; ++i) {
      if (quad[i] && quad[i].r > quad.r) {
        quad.r = quad[i].r;
      }
    }
  }

  function initialize() {
    if (!nodes) return;
    var i, n = nodes.length, node;
    radii = new Array(n);
    for (i = 0; i < n; ++i) node = nodes[i], radii[node.index] = +radius(node, i, nodes);
  }

  force.initialize = function(_) {
    nodes = _;
    initialize();
  };

  force.iterations = function(_) {
    return arguments.length ? (iterations = +_, force) : iterations;
  };

  force.strength = function(_) {
    return arguments.length ? (strength = +_, force) : strength;
  };

  force.radius = function(_) {
    return arguments.length ? (radius = typeof _ === "function" ? _ : constant(+_), initialize(), force) : radius;
  };

  return force;
};

function index(d) {
  return d.index;
}

function find(nodeById, nodeId) {
  var node = nodeById.get(nodeId);
  if (!node) throw new Error("missing: " + nodeId);
  return node;
}

var link = function(links) {
  var id = index,
      strength = defaultStrength,
      strengths,
      distance = constant(30),
      distances,
      nodes,
      count,
      bias,
      iterations = 1;

  if (links == null) links = [];

  function defaultStrength(link) {
    return 1 / Math.min(count[link.source.index], count[link.target.index]);
  }

  function force(alpha) {
    for (var k = 0, n = links.length; k < iterations; ++k) {
      for (var i = 0, link, source, target, x, y, l, b; i < n; ++i) {
        link = links[i], source = link.source, target = link.target;
        x = target.x + target.vx - source.x - source.vx || jiggle();
        y = target.y + target.vy - source.y - source.vy || jiggle();
        l = Math.sqrt(x * x + y * y);
        l = (l - distances[i]) / l * alpha * strengths[i];
        x *= l, y *= l;
        target.vx -= x * (b = bias[i]);
        target.vy -= y * b;
        source.vx += x * (b = 1 - b);
        source.vy += y * b;
      }
    }
  }

  function initialize() {
    if (!nodes) return;

    var i,
        n = nodes.length,
        m = links.length,
        nodeById = d3Collection.map(nodes, id),
        link;

    for (i = 0, count = new Array(n); i < m; ++i) {
      link = links[i], link.index = i;
      if (typeof link.source !== "object") link.source = find(nodeById, link.source);
      if (typeof link.target !== "object") link.target = find(nodeById, link.target);
      count[link.source.index] = (count[link.source.index] || 0) + 1;
      count[link.target.index] = (count[link.target.index] || 0) + 1;
    }

    for (i = 0, bias = new Array(m); i < m; ++i) {
      link = links[i], bias[i] = count[link.source.index] / (count[link.source.index] + count[link.target.index]);
    }

    strengths = new Array(m), initializeStrength();
    distances = new Array(m), initializeDistance();
  }

  function initializeStrength() {
    if (!nodes) return;

    for (var i = 0, n = links.length; i < n; ++i) {
      strengths[i] = +strength(links[i], i, links);
    }
  }

  function initializeDistance() {
    if (!nodes) return;

    for (var i = 0, n = links.length; i < n; ++i) {
      distances[i] = +distance(links[i], i, links);
    }
  }

  force.initialize = function(_) {
    nodes = _;
    initialize();
  };

  force.links = function(_) {
    return arguments.length ? (links = _, initialize(), force) : links;
  };

  force.id = function(_) {
    return arguments.length ? (id = _, force) : id;
  };

  force.iterations = function(_) {
    return arguments.length ? (iterations = +_, force) : iterations;
  };

  force.strength = function(_) {
    return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initializeStrength(), force) : strength;
  };

  force.distance = function(_) {
    return arguments.length ? (distance = typeof _ === "function" ? _ : constant(+_), initializeDistance(), force) : distance;
  };

  return force;
};

function x$1(d) {
  return d.x;
}

function y$1(d) {
  return d.y;
}

var initialRadius = 10;
var initialAngle = Math.PI * (3 - Math.sqrt(5));

var simulation = function(nodes) {
  var simulation,
      alpha = 1,
      alphaMin = 0.001,
      alphaDecay = 1 - Math.pow(alphaMin, 1 / 300),
      alphaTarget = 0,
      velocityDecay = 0.6,
      forces = d3Collection.map(),
      stepper = d3Timer.timer(step),
      event = d3Dispatch.dispatch("tick", "end");

  if (nodes == null) nodes = [];

  function step() {
    tick();
    event.call("tick", simulation);
    if (alpha < alphaMin) {
      stepper.stop();
      event.call("end", simulation);
    }
  }

  function tick() {
    var i, n = nodes.length, node;

    alpha += (alphaTarget - alpha) * alphaDecay;

    forces.each(function(force) {
      force(alpha);
    });

    for (i = 0; i < n; ++i) {
      node = nodes[i];
      if (node.fx == null) node.x += node.vx *= velocityDecay;
      else node.x = node.fx, node.vx = 0;
      if (node.fy == null) node.y += node.vy *= velocityDecay;
      else node.y = node.fy, node.vy = 0;
    }
  }

  function initializeNodes() {
    for (var i = 0, n = nodes.length, node; i < n; ++i) {
      node = nodes[i], node.index = i;
      if (isNaN(node.x) || isNaN(node.y)) {
        var radius = initialRadius * Math.sqrt(i), angle = i * initialAngle;
        node.x = radius * Math.cos(angle);
        node.y = radius * Math.sin(angle);
      }
      if (isNaN(node.vx) || isNaN(node.vy)) {
        node.vx = node.vy = 0;
      }
    }
  }

  function initializeForce(force) {
    if (force.initialize) force.initialize(nodes);
    return force;
  }

  initializeNodes();

  return simulation = {
    tick: tick,

    restart: function() {
      return stepper.restart(step), simulation;
    },

    stop: function() {
      return stepper.stop(), simulation;
    },

    nodes: function(_) {
      return arguments.length ? (nodes = _, initializeNodes(), forces.each(initializeForce), simulation) : nodes;
    },

    alpha: function(_) {
      return arguments.length ? (alpha = +_, simulation) : alpha;
    },

    alphaMin: function(_) {
      return arguments.length ? (alphaMin = +_, simulation) : alphaMin;
    },

    alphaDecay: function(_) {
      return arguments.length ? (alphaDecay = +_, simulation) : +alphaDecay;
    },

    alphaTarget: function(_) {
      return arguments.length ? (alphaTarget = +_, simulation) : alphaTarget;
    },

    velocityDecay: function(_) {
      return arguments.length ? (velocityDecay = 1 - _, simulation) : 1 - velocityDecay;
    },

    force: function(name, _) {
      return arguments.length > 1 ? ((_ == null ? forces.remove(name) : forces.set(name, initializeForce(_))), simulation) : forces.get(name);
    },

    find: function(x, y, radius) {
      var i = 0,
          n = nodes.length,
          dx,
          dy,
          d2,
          node,
          closest;

      if (radius == null) radius = Infinity;
      else radius *= radius;

      for (i = 0; i < n; ++i) {
        node = nodes[i];
        dx = x - node.x;
        dy = y - node.y;
        d2 = dx * dx + dy * dy;
        if (d2 < radius) closest = node, radius = d2;
      }

      return closest;
    },

    on: function(name, _) {
      return arguments.length > 1 ? (event.on(name, _), simulation) : event.on(name);
    }
  };
};

var manyBody = function() {
  var nodes,
      node,
      alpha,
      strength = constant(-30),
      strengths,
      distanceMin2 = 1,
      distanceMax2 = Infinity,
      theta2 = 0.81;

  function force(_) {
    var i, n = nodes.length, tree = d3Quadtree.quadtree(nodes, x$1, y$1).visitAfter(accumulate);
    for (alpha = _, i = 0; i < n; ++i) node = nodes[i], tree.visit(apply);
  }

  function initialize() {
    if (!nodes) return;
    var i, n = nodes.length, node;
    strengths = new Array(n);
    for (i = 0; i < n; ++i) node = nodes[i], strengths[node.index] = +strength(node, i, nodes);
  }

  function accumulate(quad) {
    var strength = 0, q, c, weight = 0, x, y, i;

    // For internal nodes, accumulate forces from child quadrants.
    if (quad.length) {
      for (x = y = i = 0; i < 4; ++i) {
        if ((q = quad[i]) && (c = Math.abs(q.value))) {
          strength += q.value, weight += c, x += c * q.x, y += c * q.y;
        }
      }
      quad.x = x / weight;
      quad.y = y / weight;
    }

    // For leaf nodes, accumulate forces from coincident quadrants.
    else {
      q = quad;
      q.x = q.data.x;
      q.y = q.data.y;
      do strength += strengths[q.data.index];
      while (q = q.next);
    }

    quad.value = strength;
  }

  function apply(quad, x1, _, x2) {
    if (!quad.value) return true;

    var x = quad.x - node.x,
        y = quad.y - node.y,
        w = x2 - x1,
        l = x * x + y * y;

    // Apply the Barnes-Hut approximation if possible.
    // Limit forces for very close nodes; randomize direction if coincident.
    if (w * w / theta2 < l) {
      if (l < distanceMax2) {
        if (x === 0) x = jiggle(), l += x * x;
        if (y === 0) y = jiggle(), l += y * y;
        if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l);
        node.vx += x * quad.value * alpha / l;
        node.vy += y * quad.value * alpha / l;
      }
      return true;
    }

    // Otherwise, process points directly.
    else if (quad.length || l >= distanceMax2) return;

    // Limit forces for very close nodes; randomize direction if coincident.
    if (quad.data !== node || quad.next) {
      if (x === 0) x = jiggle(), l += x * x;
      if (y === 0) y = jiggle(), l += y * y;
      if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l);
    }

    do if (quad.data !== node) {
      w = strengths[quad.data.index] * alpha / l;
      node.vx += x * w;
      node.vy += y * w;
    } while (quad = quad.next);
  }

  force.initialize = function(_) {
    nodes = _;
    initialize();
  };

  force.strength = function(_) {
    return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength;
  };

  force.distanceMin = function(_) {
    return arguments.length ? (distanceMin2 = _ * _, force) : Math.sqrt(distanceMin2);
  };

  force.distanceMax = function(_) {
    return arguments.length ? (distanceMax2 = _ * _, force) : Math.sqrt(distanceMax2);
  };

  force.theta = function(_) {
    return arguments.length ? (theta2 = _ * _, force) : Math.sqrt(theta2);
  };

  return force;
};

var radial = function(radius, x, y) {
  var nodes,
      strength = constant(0.1),
      strengths,
      radiuses;

  if (typeof radius !== "function") radius = constant(+radius);
  if (x == null) x = 0;
  if (y == null) y = 0;

  function force(alpha) {
    for (var i = 0, n = nodes.length; i < n; ++i) {
      var node = nodes[i],
          dx = node.x - x || 1e-6,
          dy = node.y - y || 1e-6,
          r = Math.sqrt(dx * dx + dy * dy),
          k = (radiuses[i] - r) * strengths[i] * alpha / r;
      node.vx += dx * k;
      node.vy += dy * k;
    }
  }

  function initialize() {
    if (!nodes) return;
    var i, n = nodes.length;
    strengths = new Array(n);
    radiuses = new Array(n);
    for (i = 0; i < n; ++i) {
      radiuses[i] = +radius(nodes[i], i, nodes);
      strengths[i] = isNaN(radiuses[i]) ? 0 : +strength(nodes[i], i, nodes);
    }
  }

  force.initialize = function(_) {
    nodes = _, initialize();
  };

  force.strength = function(_) {
    return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength;
  };

  force.radius = function(_) {
    return arguments.length ? (radius = typeof _ === "function" ? _ : constant(+_), initialize(), force) : radius;
  };

  force.x = function(_) {
    return arguments.length ? (x = +_, force) : x;
  };

  force.y = function(_) {
    return arguments.length ? (y = +_, force) : y;
  };

  return force;
};

var x$2 = function(x) {
  var strength = constant(0.1),
      nodes,
      strengths,
      xz;

  if (typeof x !== "function") x = constant(x == null ? 0 : +x);

  function force(alpha) {
    for (var i = 0, n = nodes.length, node; i < n; ++i) {
      node = nodes[i], node.vx += (xz[i] - node.x) * strengths[i] * alpha;
    }
  }

  function initialize() {
    if (!nodes) return;
    var i, n = nodes.length;
    strengths = new Array(n);
    xz = new Array(n);
    for (i = 0; i < n; ++i) {
      strengths[i] = isNaN(xz[i] = +x(nodes[i], i, nodes)) ? 0 : +strength(nodes[i], i, nodes);
    }
  }

  force.initialize = function(_) {
    nodes = _;
    initialize();
  };

  force.strength = function(_) {
    return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength;
  };

  force.x = function(_) {
    return arguments.length ? (x = typeof _ === "function" ? _ : constant(+_), initialize(), force) : x;
  };

  return force;
};

var y$2 = function(y) {
  var strength = constant(0.1),
      nodes,
      strengths,
      yz;

  if (typeof y !== "function") y = constant(y == null ? 0 : +y);

  function force(alpha) {
    for (var i = 0, n = nodes.length, node; i < n; ++i) {
      node = nodes[i], node.vy += (yz[i] - node.y) * strengths[i] * alpha;
    }
  }

  function initialize() {
    if (!nodes) return;
    var i, n = nodes.length;
    strengths = new Array(n);
    yz = new Array(n);
    for (i = 0; i < n; ++i) {
      strengths[i] = isNaN(yz[i] = +y(nodes[i], i, nodes)) ? 0 : +strength(nodes[i], i, nodes);
    }
  }

  force.initialize = function(_) {
    nodes = _;
    initialize();
  };

  force.strength = function(_) {
    return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength;
  };

  force.y = function(_) {
    return arguments.length ? (y = typeof _ === "function" ? _ : constant(+_), initialize(), force) : y;
  };

  return force;
};

exports.forceCenter = center;
exports.forceCollide = collide;
exports.forceLink = link;
exports.forceManyBody = manyBody;
exports.forceRadial = radial;
exports.forceSimulation = simulation;
exports.forceX = x$2;
exports.forceY = y$2;

Object.defineProperty(exports, '__esModule', { value: true });

})));

},{"d3-collection":141,"d3-dispatch":143,"d3-quadtree":147,"d3-timer":150}],145:[function(_dereq_,module,exports){
// https://d3js.org/d3-interpolate/ v1.3.2 Copyright 2018 Mike Bostock
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, _dereq_('d3-color')) :
typeof define === 'function' && define.amd ? define(['exports', 'd3-color'], factory) :
(factory((global.d3 = global.d3 || {}),global.d3));
}(this, (function (exports,d3Color) { 'use strict';

function basis(t1, v0, v1, v2, v3) {
  var t2 = t1 * t1, t3 = t2 * t1;
  return ((1 - 3 * t1 + 3 * t2 - t3) * v0
      + (4 - 6 * t2 + 3 * t3) * v1
      + (1 + 3 * t1 + 3 * t2 - 3 * t3) * v2
      + t3 * v3) / 6;
}

function basis$1(values) {
  var n = values.length - 1;
  return function(t) {
    var i = t <= 0 ? (t = 0) : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n),
        v1 = values[i],
        v2 = values[i + 1],
        v0 = i > 0 ? values[i - 1] : 2 * v1 - v2,
        v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1;
    return basis((t - i / n) * n, v0, v1, v2, v3);
  };
}

function basisClosed(values) {
  var n = values.length;
  return function(t) {
    var i = Math.floor(((t %= 1) < 0 ? ++t : t) * n),
        v0 = values[(i + n - 1) % n],
        v1 = values[i % n],
        v2 = values[(i + 1) % n],
        v3 = values[(i + 2) % n];
    return basis((t - i / n) * n, v0, v1, v2, v3);
  };
}

function constant(x) {
  return function() {
    return x;
  };
}

function linear(a, d) {
  return function(t) {
    return a + t * d;
  };
}

function exponential(a, b, y) {
  return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) {
    return Math.pow(a + t * b, y);
  };
}

function hue(a, b) {
  var d = b - a;
  return d ? linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : constant(isNaN(a) ? b : a);
}

function gamma(y) {
  return (y = +y) === 1 ? nogamma : function(a, b) {
    return b - a ? exponential(a, b, y) : constant(isNaN(a) ? b : a);
  };
}

function nogamma(a, b) {
  var d = b - a;
  return d ? linear(a, d) : constant(isNaN(a) ? b : a);
}

var rgb = (function rgbGamma(y) {
  var color = gamma(y);

  function rgb(start, end) {
    var r = color((start = d3Color.rgb(start)).r, (end = d3Color.rgb(end)).r),
        g = color(start.g, end.g),
        b = color(start.b, end.b),
        opacity = nogamma(start.opacity, end.opacity);
    return function(t) {
      start.r = r(t);
      start.g = g(t);
      start.b = b(t);
      start.opacity = opacity(t);
      return start + "";
    };
  }

  rgb.gamma = rgbGamma;

  return rgb;
})(1);

function rgbSpline(spline) {
  return function(colors) {
    var n = colors.length,
        r = new Array(n),
        g = new Array(n),
        b = new Array(n),
        i, color;
    for (i = 0; i < n; ++i) {
      color = d3Color.rgb(colors[i]);
      r[i] = color.r || 0;
      g[i] = color.g || 0;
      b[i] = color.b || 0;
    }
    r = spline(r);
    g = spline(g);
    b = spline(b);
    color.opacity = 1;
    return function(t) {
      color.r = r(t);
      color.g = g(t);
      color.b = b(t);
      return color + "";
    };
  };
}

var rgbBasis = rgbSpline(basis$1);
var rgbBasisClosed = rgbSpline(basisClosed);

function array(a, b) {
  var nb = b ? b.length : 0,
      na = a ? Math.min(nb, a.length) : 0,
      x = new Array(na),
      c = new Array(nb),
      i;

  for (i = 0; i < na; ++i) x[i] = value(a[i], b[i]);
  for (; i < nb; ++i) c[i] = b[i];

  return function(t) {
    for (i = 0; i < na; ++i) c[i] = x[i](t);
    return c;
  };
}

function date(a, b) {
  var d = new Date;
  return a = +a, b -= a, function(t) {
    return d.setTime(a + b * t), d;
  };
}

function number(a, b) {
  return a = +a, b -= a, function(t) {
    return a + b * t;
  };
}

function object(a, b) {
  var i = {},
      c = {},
      k;

  if (a === null || typeof a !== "object") a = {};
  if (b === null || typeof b !== "object") b = {};

  for (k in b) {
    if (k in a) {
      i[k] = value(a[k], b[k]);
    } else {
      c[k] = b[k];
    }
  }

  return function(t) {
    for (k in i) c[k] = i[k](t);
    return c;
  };
}

var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,
    reB = new RegExp(reA.source, "g");

function zero(b) {
  return function() {
    return b;
  };
}

function one(b) {
  return function(t) {
    return b(t) + "";
  };
}

function string(a, b) {
  var bi = reA.lastIndex = reB.lastIndex = 0, // scan index for next number in b
      am, // current match in a
      bm, // current match in b
      bs, // string preceding current number in b, if any
      i = -1, // index in s
      s = [], // string constants and placeholders
      q = []; // number interpolators

  // Coerce inputs to strings.
  a = a + "", b = b + "";

  // Interpolate pairs of numbers in a & b.
  while ((am = reA.exec(a))
      && (bm = reB.exec(b))) {
    if ((bs = bm.index) > bi) { // a string precedes the next number in b
      bs = b.slice(bi, bs);
      if (s[i]) s[i] += bs; // coalesce with previous string
      else s[++i] = bs;
    }
    if ((am = am[0]) === (bm = bm[0])) { // numbers in a & b match
      if (s[i]) s[i] += bm; // coalesce with previous string
      else s[++i] = bm;
    } else { // interpolate non-matching numbers
      s[++i] = null;
      q.push({i: i, x: number(am, bm)});
    }
    bi = reB.lastIndex;
  }

  // Add remains of b.
  if (bi < b.length) {
    bs = b.slice(bi);
    if (s[i]) s[i] += bs; // coalesce with previous string
    else s[++i] = bs;
  }

  // Special optimization for only a single match.
  // Otherwise, interpolate each of the numbers and rejoin the string.
  return s.length < 2 ? (q[0]
      ? one(q[0].x)
      : zero(b))
      : (b = q.length, function(t) {
          for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);
          return s.join("");
        });
}

function value(a, b) {
  var t = typeof b, c;
  return b == null || t === "boolean" ? constant(b)
      : (t === "number" ? number
      : t === "string" ? ((c = d3Color.color(b)) ? (b = c, rgb) : string)
      : b instanceof d3Color.color ? rgb
      : b instanceof Date ? date
      : Array.isArray(b) ? array
      : typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? object
      : number)(a, b);
}

function discrete(range) {
  var n = range.length;
  return function(t) {
    return range[Math.max(0, Math.min(n - 1, Math.floor(t * n)))];
  };
}

function hue$1(a, b) {
  var i = hue(+a, +b);
  return function(t) {
    var x = i(t);
    return x - 360 * Math.floor(x / 360);
  };
}

function round(a, b) {
  return a = +a, b -= a, function(t) {
    return Math.round(a + b * t);
  };
}

var degrees = 180 / Math.PI;

var identity = {
  translateX: 0,
  translateY: 0,
  rotate: 0,
  skewX: 0,
  scaleX: 1,
  scaleY: 1
};

function decompose(a, b, c, d, e, f) {
  var scaleX, scaleY, skewX;
  if (scaleX = Math.sqrt(a * a + b * b)) a /= scaleX, b /= scaleX;
  if (skewX = a * c + b * d) c -= a * skewX, d -= b * skewX;
  if (scaleY = Math.sqrt(c * c + d * d)) c /= scaleY, d /= scaleY, skewX /= scaleY;
  if (a * d < b * c) a = -a, b = -b, skewX = -skewX, scaleX = -scaleX;
  return {
    translateX: e,
    translateY: f,
    rotate: Math.atan2(b, a) * degrees,
    skewX: Math.atan(skewX) * degrees,
    scaleX: scaleX,
    scaleY: scaleY
  };
}

var cssNode,
    cssRoot,
    cssView,
    svgNode;

function parseCss(value) {
  if (value === "none") return identity;
  if (!cssNode) cssNode = document.createElement("DIV"), cssRoot = document.documentElement, cssView = document.defaultView;
  cssNode.style.transform = value;
  value = cssView.getComputedStyle(cssRoot.appendChild(cssNode), null).getPropertyValue("transform");
  cssRoot.removeChild(cssNode);
  value = value.slice(7, -1).split(",");
  return decompose(+value[0], +value[1], +value[2], +value[3], +value[4], +value[5]);
}

function parseSvg(value) {
  if (value == null) return identity;
  if (!svgNode) svgNode = document.createElementNS("http://www.w3.org/2000/svg", "g");
  svgNode.setAttribute("transform", value);
  if (!(value = svgNode.transform.baseVal.consolidate())) return identity;
  value = value.matrix;
  return decompose(value.a, value.b, value.c, value.d, value.e, value.f);
}

function interpolateTransform(parse, pxComma, pxParen, degParen) {

  function pop(s) {
    return s.length ? s.pop() + " " : "";
  }

  function translate(xa, ya, xb, yb, s, q) {
    if (xa !== xb || ya !== yb) {
      var i = s.push("translate(", null, pxComma, null, pxParen);
      q.push({i: i - 4, x: number(xa, xb)}, {i: i - 2, x: number(ya, yb)});
    } else if (xb || yb) {
      s.push("translate(" + xb + pxComma + yb + pxParen);
    }
  }

  function rotate(a, b, s, q) {
    if (a !== b) {
      if (a - b > 180) b += 360; else if (b - a > 180) a += 360; // shortest path
      q.push({i: s.push(pop(s) + "rotate(", null, degParen) - 2, x: number(a, b)});
    } else if (b) {
      s.push(pop(s) + "rotate(" + b + degParen);
    }
  }

  function skewX(a, b, s, q) {
    if (a !== b) {
      q.push({i: s.push(pop(s) + "skewX(", null, degParen) - 2, x: number(a, b)});
    } else if (b) {
      s.push(pop(s) + "skewX(" + b + degParen);
    }
  }

  function scale(xa, ya, xb, yb, s, q) {
    if (xa !== xb || ya !== yb) {
      var i = s.push(pop(s) + "scale(", null, ",", null, ")");
      q.push({i: i - 4, x: number(xa, xb)}, {i: i - 2, x: number(ya, yb)});
    } else if (xb !== 1 || yb !== 1) {
      s.push(pop(s) + "scale(" + xb + "," + yb + ")");
    }
  }

  return function(a, b) {
    var s = [], // string constants and placeholders
        q = []; // number interpolators
    a = parse(a), b = parse(b);
    translate(a.translateX, a.translateY, b.translateX, b.translateY, s, q);
    rotate(a.rotate, b.rotate, s, q);
    skewX(a.skewX, b.skewX, s, q);
    scale(a.scaleX, a.scaleY, b.scaleX, b.scaleY, s, q);
    a = b = null; // gc
    return function(t) {
      var i = -1, n = q.length, o;
      while (++i < n) s[(o = q[i]).i] = o.x(t);
      return s.join("");
    };
  };
}

var interpolateTransformCss = interpolateTransform(parseCss, "px, ", "px)", "deg)");
var interpolateTransformSvg = interpolateTransform(parseSvg, ", ", ")", ")");

var rho = Math.SQRT2,
    rho2 = 2,
    rho4 = 4,
    epsilon2 = 1e-12;

function cosh(x) {
  return ((x = Math.exp(x)) + 1 / x) / 2;
}

function sinh(x) {
  return ((x = Math.exp(x)) - 1 / x) / 2;
}

function tanh(x) {
  return ((x = Math.exp(2 * x)) - 1) / (x + 1);
}

// p0 = [ux0, uy0, w0]
// p1 = [ux1, uy1, w1]
function zoom(p0, p1) {
  var ux0 = p0[0], uy0 = p0[1], w0 = p0[2],
      ux1 = p1[0], uy1 = p1[1], w1 = p1[2],
      dx = ux1 - ux0,
      dy = uy1 - uy0,
      d2 = dx * dx + dy * dy,
      i,
      S;

  // Special case for u0 ≅ u1.
  if (d2 < epsilon2) {
    S = Math.log(w1 / w0) / rho;
    i = function(t) {
      return [
        ux0 + t * dx,
        uy0 + t * dy,
        w0 * Math.exp(rho * t * S)
      ];
    };
  }

  // General case.
  else {
    var d1 = Math.sqrt(d2),
        b0 = (w1 * w1 - w0 * w0 + rho4 * d2) / (2 * w0 * rho2 * d1),
        b1 = (w1 * w1 - w0 * w0 - rho4 * d2) / (2 * w1 * rho2 * d1),
        r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0),
        r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);
    S = (r1 - r0) / rho;
    i = function(t) {
      var s = t * S,
          coshr0 = cosh(r0),
          u = w0 / (rho2 * d1) * (coshr0 * tanh(rho * s + r0) - sinh(r0));
      return [
        ux0 + u * dx,
        uy0 + u * dy,
        w0 * coshr0 / cosh(rho * s + r0)
      ];
    };
  }

  i.duration = S * 1000;

  return i;
}

function hsl(hue$$1) {
  return function(start, end) {
    var h = hue$$1((start = d3Color.hsl(start)).h, (end = d3Color.hsl(end)).h),
        s = nogamma(start.s, end.s),
        l = nogamma(start.l, end.l),
        opacity = nogamma(start.opacity, end.opacity);
    return function(t) {
      start.h = h(t);
      start.s = s(t);
      start.l = l(t);
      start.opacity = opacity(t);
      return start + "";
    };
  }
}

var hsl$1 = hsl(hue);
var hslLong = hsl(nogamma);

function lab(start, end) {
  var l = nogamma((start = d3Color.lab(start)).l, (end = d3Color.lab(end)).l),
      a = nogamma(start.a, end.a),
      b = nogamma(start.b, end.b),
      opacity = nogamma(start.opacity, end.opacity);
  return function(t) {
    start.l = l(t);
    start.a = a(t);
    start.b = b(t);
    start.opacity = opacity(t);
    return start + "";
  };
}

function hcl(hue$$1) {
  return function(start, end) {
    var h = hue$$1((start = d3Color.hcl(start)).h, (end = d3Color.hcl(end)).h),
        c = nogamma(start.c, end.c),
        l = nogamma(start.l, end.l),
        opacity = nogamma(start.opacity, end.opacity);
    return function(t) {
      start.h = h(t);
      start.c = c(t);
      start.l = l(t);
      start.opacity = opacity(t);
      return start + "";
    };
  }
}

var hcl$1 = hcl(hue);
var hclLong = hcl(nogamma);

function cubehelix(hue$$1) {
  return (function cubehelixGamma(y) {
    y = +y;

    function cubehelix(start, end) {
      var h = hue$$1((start = d3Color.cubehelix(start)).h, (end = d3Color.cubehelix(end)).h),
          s = nogamma(start.s, end.s),
          l = nogamma(start.l, end.l),
          opacity = nogamma(start.opacity, end.opacity);
      return function(t) {
        start.h = h(t);
        start.s = s(t);
        start.l = l(Math.pow(t, y));
        start.opacity = opacity(t);
        return start + "";
      };
    }

    cubehelix.gamma = cubehelixGamma;

    return cubehelix;
  })(1);
}

var cubehelix$1 = cubehelix(hue);
var cubehelixLong = cubehelix(nogamma);

function piecewise(interpolate, values) {
  var i = 0, n = values.length - 1, v = values[0], I = new Array(n < 0 ? 0 : n);
  while (i < n) I[i] = interpolate(v, v = values[++i]);
  return function(t) {
    var i = Math.max(0, Math.min(n - 1, Math.floor(t *= n)));
    return I[i](t - i);
  };
}

function quantize(interpolator, n) {
  var samples = new Array(n);
  for (var i = 0; i < n; ++i) samples[i] = interpolator(i / (n - 1));
  return samples;
}

exports.interpolate = value;
exports.interpolateArray = array;
exports.interpolateBasis = basis$1;
exports.interpolateBasisClosed = basisClosed;
exports.interpolateDate = date;
exports.interpolateDiscrete = discrete;
exports.interpolateHue = hue$1;
exports.interpolateNumber = number;
exports.interpolateObject = object;
exports.interpolateRound = round;
exports.interpolateString = string;
exports.interpolateTransformCss = interpolateTransformCss;
exports.interpolateTransformSvg = interpolateTransformSvg;
exports.interpolateZoom = zoom;
exports.interpolateRgb = rgb;
exports.interpolateRgbBasis = rgbBasis;
exports.interpolateRgbBasisClosed = rgbBasisClosed;
exports.interpolateHsl = hsl$1;
exports.interpolateHslLong = hslLong;
exports.interpolateLab = lab;
exports.interpolateHcl = hcl$1;
exports.interpolateHclLong = hclLong;
exports.interpolateCubehelix = cubehelix$1;
exports.interpolateCubehelixLong = cubehelixLong;
exports.piecewise = piecewise;
exports.quantize = quantize;

Object.defineProperty(exports, '__esModule', { value: true });

})));

},{"d3-color":142}],146:[function(_dereq_,module,exports){
// https://d3js.org/d3-path/ v1.0.7 Copyright 2018 Mike Bostock
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.d3 = global.d3 || {})));
}(this, (function (exports) { 'use strict';

var pi = Math.PI,
    tau = 2 * pi,
    epsilon = 1e-6,
    tauEpsilon = tau - epsilon;

function Path() {
  this._x0 = this._y0 = // start of current subpath
  this._x1 = this._y1 = null; // end of current subpath
  this._ = "";
}

function path() {
  return new Path;
}

Path.prototype = path.prototype = {
  constructor: Path,
  moveTo: function(x, y) {
    this._ += "M" + (this._x0 = this._x1 = +x) + "," + (this._y0 = this._y1 = +y);
  },
  closePath: function() {
    if (this._x1 !== null) {
      this._x1 = this._x0, this._y1 = this._y0;
      this._ += "Z";
    }
  },
  lineTo: function(x, y) {
    this._ += "L" + (this._x1 = +x) + "," + (this._y1 = +y);
  },
  quadraticCurveTo: function(x1, y1, x, y) {
    this._ += "Q" + (+x1) + "," + (+y1) + "," + (this._x1 = +x) + "," + (this._y1 = +y);
  },
  bezierCurveTo: function(x1, y1, x2, y2, x, y) {
    this._ += "C" + (+x1) + "," + (+y1) + "," + (+x2) + "," + (+y2) + "," + (this._x1 = +x) + "," + (this._y1 = +y);
  },
  arcTo: function(x1, y1, x2, y2, r) {
    x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r = +r;
    var x0 = this._x1,
        y0 = this._y1,
        x21 = x2 - x1,
        y21 = y2 - y1,
        x01 = x0 - x1,
        y01 = y0 - y1,
        l01_2 = x01 * x01 + y01 * y01;

    // Is the radius negative? Error.
    if (r < 0) throw new Error("negative radius: " + r);

    // Is this path empty? Move to (x1,y1).
    if (this._x1 === null) {
      this._ += "M" + (this._x1 = x1) + "," + (this._y1 = y1);
    }

    // Or, is (x1,y1) coincident with (x0,y0)? Do nothing.
    else if (!(l01_2 > epsilon));

    // Or, are (x0,y0), (x1,y1) and (x2,y2) collinear?
    // Equivalently, is (x1,y1) coincident with (x2,y2)?
    // Or, is the radius zero? Line to (x1,y1).
    else if (!(Math.abs(y01 * x21 - y21 * x01) > epsilon) || !r) {
      this._ += "L" + (this._x1 = x1) + "," + (this._y1 = y1);
    }

    // Otherwise, draw an arc!
    else {
      var x20 = x2 - x0,
          y20 = y2 - y0,
          l21_2 = x21 * x21 + y21 * y21,
          l20_2 = x20 * x20 + y20 * y20,
          l21 = Math.sqrt(l21_2),
          l01 = Math.sqrt(l01_2),
          l = r * Math.tan((pi - Math.acos((l21_2 + l01_2 - l20_2) / (2 * l21 * l01))) / 2),
          t01 = l / l01,
          t21 = l / l21;

      // If the start tangent is not coincident with (x0,y0), line to.
      if (Math.abs(t01 - 1) > epsilon) {
        this._ += "L" + (x1 + t01 * x01) + "," + (y1 + t01 * y01);
      }

      this._ += "A" + r + "," + r + ",0,0," + (+(y01 * x20 > x01 * y20)) + "," + (this._x1 = x1 + t21 * x21) + "," + (this._y1 = y1 + t21 * y21);
    }
  },
  arc: function(x, y, r, a0, a1, ccw) {
    x = +x, y = +y, r = +r;
    var dx = r * Math.cos(a0),
        dy = r * Math.sin(a0),
        x0 = x + dx,
        y0 = y + dy,
        cw = 1 ^ ccw,
        da = ccw ? a0 - a1 : a1 - a0;

    // Is the radius negative? Error.
    if (r < 0) throw new Error("negative radius: " + r);

    // Is this path empty? Move to (x0,y0).
    if (this._x1 === null) {
      this._ += "M" + x0 + "," + y0;
    }

    // Or, is (x0,y0) not coincident with the previous point? Line to (x0,y0).
    else if (Math.abs(this._x1 - x0) > epsilon || Math.abs(this._y1 - y0) > epsilon) {
      this._ += "L" + x0 + "," + y0;
    }

    // Is this arc empty? We’re done.
    if (!r) return;

    // Does the angle go the wrong way? Flip the direction.
    if (da < 0) da = da % tau + tau;

    // Is this a complete circle? Draw two arcs to complete the circle.
    if (da > tauEpsilon) {
      this._ += "A" + r + "," + r + ",0,1," + cw + "," + (x - dx) + "," + (y - dy) + "A" + r + "," + r + ",0,1," + cw + "," + (this._x1 = x0) + "," + (this._y1 = y0);
    }

    // Is this arc non-empty? Draw an arc!
    else if (da > epsilon) {
      this._ += "A" + r + "," + r + ",0," + (+(da >= pi)) + "," + cw + "," + (this._x1 = x + r * Math.cos(a1)) + "," + (this._y1 = y + r * Math.sin(a1));
    }
  },
  rect: function(x, y, w, h) {
    this._ += "M" + (this._x0 = this._x1 = +x) + "," + (this._y0 = this._y1 = +y) + "h" + (+w) + "v" + (+h) + "h" + (-w) + "Z";
  },
  toString: function() {
    return this._;
  }
};

exports.path = path;

Object.defineProperty(exports, '__esModule', { value: true });

})));

},{}],147:[function(_dereq_,module,exports){
// https://d3js.org/d3-quadtree/ Version 1.0.3. Copyright 2017 Mike Bostock.
(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
	typeof define === 'function' && define.amd ? define(['exports'], factory) :
	(factory((global.d3 = global.d3 || {})));
}(this, (function (exports) { 'use strict';

var tree_add = function(d) {
  var x = +this._x.call(null, d),
      y = +this._y.call(null, d);
  return add(this.cover(x, y), x, y, d);
};

function add(tree, x, y, d) {
  if (isNaN(x) || isNaN(y)) return tree; // ignore invalid points

  var parent,
      node = tree._root,
      leaf = {data: d},
      x0 = tree._x0,
      y0 = tree._y0,
      x1 = tree._x1,
      y1 = tree._y1,
      xm,
      ym,
      xp,
      yp,
      right,
      bottom,
      i,
      j;

  // If the tree is empty, initialize the root as a leaf.
  if (!node) return tree._root = leaf, tree;

  // Find the existing leaf for the new point, or add it.
  while (node.length) {
    if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
    if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;
    if (parent = node, !(node = node[i = bottom << 1 | right])) return parent[i] = leaf, tree;
  }

  // Is the new point is exactly coincident with the existing point?
  xp = +tree._x.call(null, node.data);
  yp = +tree._y.call(null, node.data);
  if (x === xp && y === yp) return leaf.next = node, parent ? parent[i] = leaf : tree._root = leaf, tree;

  // Otherwise, split the leaf node until the old and new point are separated.
  do {
    parent = parent ? parent[i] = new Array(4) : tree._root = new Array(4);
    if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
    if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;
  } while ((i = bottom << 1 | right) === (j = (yp >= ym) << 1 | (xp >= xm)));
  return parent[j] = node, parent[i] = leaf, tree;
}

function addAll(data) {
  var d, i, n = data.length,
      x,
      y,
      xz = new Array(n),
      yz = new Array(n),
      x0 = Infinity,
      y0 = Infinity,
      x1 = -Infinity,
      y1 = -Infinity;

  // Compute the points and their extent.
  for (i = 0; i < n; ++i) {
    if (isNaN(x = +this._x.call(null, d = data[i])) || isNaN(y = +this._y.call(null, d))) continue;
    xz[i] = x;
    yz[i] = y;
    if (x < x0) x0 = x;
    if (x > x1) x1 = x;
    if (y < y0) y0 = y;
    if (y > y1) y1 = y;
  }

  // If there were no (valid) points, inherit the existing extent.
  if (x1 < x0) x0 = this._x0, x1 = this._x1;
  if (y1 < y0) y0 = this._y0, y1 = this._y1;

  // Expand the tree to cover the new points.
  this.cover(x0, y0).cover(x1, y1);

  // Add the new points.
  for (i = 0; i < n; ++i) {
    add(this, xz[i], yz[i], data[i]);
  }

  return this;
}

var tree_cover = function(x, y) {
  if (isNaN(x = +x) || isNaN(y = +y)) return this; // ignore invalid points

  var x0 = this._x0,
      y0 = this._y0,
      x1 = this._x1,
      y1 = this._y1;

  // If the quadtree has no extent, initialize them.
  // Integer extent are necessary so that if we later double the extent,
  // the existing quadrant boundaries don’t change due to floating point error!
  if (isNaN(x0)) {
    x1 = (x0 = Math.floor(x)) + 1;
    y1 = (y0 = Math.floor(y)) + 1;
  }

  // Otherwise, double repeatedly to cover.
  else if (x0 > x || x > x1 || y0 > y || y > y1) {
    var z = x1 - x0,
        node = this._root,
        parent,
        i;

    switch (i = (y < (y0 + y1) / 2) << 1 | (x < (x0 + x1) / 2)) {
      case 0: {
        do parent = new Array(4), parent[i] = node, node = parent;
        while (z *= 2, x1 = x0 + z, y1 = y0 + z, x > x1 || y > y1);
        break;
      }
      case 1: {
        do parent = new Array(4), parent[i] = node, node = parent;
        while (z *= 2, x0 = x1 - z, y1 = y0 + z, x0 > x || y > y1);
        break;
      }
      case 2: {
        do parent = new Array(4), parent[i] = node, node = parent;
        while (z *= 2, x1 = x0 + z, y0 = y1 - z, x > x1 || y0 > y);
        break;
      }
      case 3: {
        do parent = new Array(4), parent[i] = node, node = parent;
        while (z *= 2, x0 = x1 - z, y0 = y1 - z, x0 > x || y0 > y);
        break;
      }
    }

    if (this._root && this._root.length) this._root = node;
  }

  // If the quadtree covers the point already, just return.
  else return this;

  this._x0 = x0;
  this._y0 = y0;
  this._x1 = x1;
  this._y1 = y1;
  return this;
};

var tree_data = function() {
  var data = [];
  this.visit(function(node) {
    if (!node.length) do data.push(node.data); while (node = node.next)
  });
  return data;
};

var tree_extent = function(_) {
  return arguments.length
      ? this.cover(+_[0][0], +_[0][1]).cover(+_[1][0], +_[1][1])
      : isNaN(this._x0) ? undefined : [[this._x0, this._y0], [this._x1, this._y1]];
};

var Quad = function(node, x0, y0, x1, y1) {
  this.node = node;
  this.x0 = x0;
  this.y0 = y0;
  this.x1 = x1;
  this.y1 = y1;
};

var tree_find = function(x, y, radius) {
  var data,
      x0 = this._x0,
      y0 = this._y0,
      x1,
      y1,
      x2,
      y2,
      x3 = this._x1,
      y3 = this._y1,
      quads = [],
      node = this._root,
      q,
      i;

  if (node) quads.push(new Quad(node, x0, y0, x3, y3));
  if (radius == null) radius = Infinity;
  else {
    x0 = x - radius, y0 = y - radius;
    x3 = x + radius, y3 = y + radius;
    radius *= radius;
  }

  while (q = quads.pop()) {

    // Stop searching if this quadrant can’t contain a closer node.
    if (!(node = q.node)
        || (x1 = q.x0) > x3
        || (y1 = q.y0) > y3
        || (x2 = q.x1) < x0
        || (y2 = q.y1) < y0) continue;

    // Bisect the current quadrant.
    if (node.length) {
      var xm = (x1 + x2) / 2,
          ym = (y1 + y2) / 2;

      quads.push(
        new Quad(node[3], xm, ym, x2, y2),
        new Quad(node[2], x1, ym, xm, y2),
        new Quad(node[1], xm, y1, x2, ym),
        new Quad(node[0], x1, y1, xm, ym)
      );

      // Visit the closest quadrant first.
      if (i = (y >= ym) << 1 | (x >= xm)) {
        q = quads[quads.length - 1];
        quads[quads.length - 1] = quads[quads.length - 1 - i];
        quads[quads.length - 1 - i] = q;
      }
    }

    // Visit this point. (Visiting coincident points isn’t necessary!)
    else {
      var dx = x - +this._x.call(null, node.data),
          dy = y - +this._y.call(null, node.data),
          d2 = dx * dx + dy * dy;
      if (d2 < radius) {
        var d = Math.sqrt(radius = d2);
        x0 = x - d, y0 = y - d;
        x3 = x + d, y3 = y + d;
        data = node.data;
      }
    }
  }

  return data;
};

var tree_remove = function(d) {
  if (isNaN(x = +this._x.call(null, d)) || isNaN(y = +this._y.call(null, d))) return this; // ignore invalid points

  var parent,
      node = this._root,
      retainer,
      previous,
      next,
      x0 = this._x0,
      y0 = this._y0,
      x1 = this._x1,
      y1 = this._y1,
      x,
      y,
      xm,
      ym,
      right,
      bottom,
      i,
      j;

  // If the tree is empty, initialize the root as a leaf.
  if (!node) return this;

  // Find the leaf node for the point.
  // While descending, also retain the deepest parent with a non-removed sibling.
  if (node.length) while (true) {
    if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
    if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;
    if (!(parent = node, node = node[i = bottom << 1 | right])) return this;
    if (!node.length) break;
    if (parent[(i + 1) & 3] || parent[(i + 2) & 3] || parent[(i + 3) & 3]) retainer = parent, j = i;
  }

  // Find the point to remove.
  while (node.data !== d) if (!(previous = node, node = node.next)) return this;
  if (next = node.next) delete node.next;

  // If there are multiple coincident points, remove just the point.
  if (previous) return (next ? previous.next = next : delete previous.next), this;

  // If this is the root point, remove it.
  if (!parent) return this._root = next, this;

  // Remove this leaf.
  next ? parent[i] = next : delete parent[i];

  // If the parent now contains exactly one leaf, collapse superfluous parents.
  if ((node = parent[0] || parent[1] || parent[2] || parent[3])
      && node === (parent[3] || parent[2] || parent[1] || parent[0])
      && !node.length) {
    if (retainer) retainer[j] = node;
    else this._root = node;
  }

  return this;
};

function removeAll(data) {
  for (var i = 0, n = data.length; i < n; ++i) this.remove(data[i]);
  return this;
}

var tree_root = function() {
  return this._root;
};

var tree_size = function() {
  var size = 0;
  this.visit(function(node) {
    if (!node.length) do ++size; while (node = node.next)
  });
  return size;
};

var tree_visit = function(callback) {
  var quads = [], q, node = this._root, child, x0, y0, x1, y1;
  if (node) quads.push(new Quad(node, this._x0, this._y0, this._x1, this._y1));
  while (q = quads.pop()) {
    if (!callback(node = q.node, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1) && node.length) {
      var xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
      if (child = node[3]) quads.push(new Quad(child, xm, ym, x1, y1));
      if (child = node[2]) quads.push(new Quad(child, x0, ym, xm, y1));
      if (child = node[1]) quads.push(new Quad(child, xm, y0, x1, ym));
      if (child = node[0]) quads.push(new Quad(child, x0, y0, xm, ym));
    }
  }
  return this;
};

var tree_visitAfter = function(callback) {
  var quads = [], next = [], q;
  if (this._root) quads.push(new Quad(this._root, this._x0, this._y0, this._x1, this._y1));
  while (q = quads.pop()) {
    var node = q.node;
    if (node.length) {
      var child, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1, xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
      if (child = node[0]) quads.push(new Quad(child, x0, y0, xm, ym));
      if (child = node[1]) quads.push(new Quad(child, xm, y0, x1, ym));
      if (child = node[2]) quads.push(new Quad(child, x0, ym, xm, y1));
      if (child = node[3]) quads.push(new Quad(child, xm, ym, x1, y1));
    }
    next.push(q);
  }
  while (q = next.pop()) {
    callback(q.node, q.x0, q.y0, q.x1, q.y1);
  }
  return this;
};

function defaultX(d) {
  return d[0];
}

var tree_x = function(_) {
  return arguments.length ? (this._x = _, this) : this._x;
};

function defaultY(d) {
  return d[1];
}

var tree_y = function(_) {
  return arguments.length ? (this._y = _, this) : this._y;
};

function quadtree(nodes, x, y) {
  var tree = new Quadtree(x == null ? defaultX : x, y == null ? defaultY : y, NaN, NaN, NaN, NaN);
  return nodes == null ? tree : tree.addAll(nodes);
}

function Quadtree(x, y, x0, y0, x1, y1) {
  this._x = x;
  this._y = y;
  this._x0 = x0;
  this._y0 = y0;
  this._x1 = x1;
  this._y1 = y1;
  this._root = undefined;
}

function leaf_copy(leaf) {
  var copy = {data: leaf.data}, next = copy;
  while (leaf = leaf.next) next = next.next = {data: leaf.data};
  return copy;
}

var treeProto = quadtree.prototype = Quadtree.prototype;

treeProto.copy = function() {
  var copy = new Quadtree(this._x, this._y, this._x0, this._y0, this._x1, this._y1),
      node = this._root,
      nodes,
      child;

  if (!node) return copy;

  if (!node.length) return copy._root = leaf_copy(node), copy;

  nodes = [{source: node, target: copy._root = new Array(4)}];
  while (node = nodes.pop()) {
    for (var i = 0; i < 4; ++i) {
      if (child = node.source[i]) {
        if (child.length) nodes.push({source: child, target: node.target[i] = new Array(4)});
        else node.target[i] = leaf_copy(child);
      }
    }
  }

  return copy;
};

treeProto.add = tree_add;
treeProto.addAll = addAll;
treeProto.cover = tree_cover;
treeProto.data = tree_data;
treeProto.extent = tree_extent;
treeProto.find = tree_find;
treeProto.remove = tree_remove;
treeProto.removeAll = removeAll;
treeProto.root = tree_root;
treeProto.size = tree_size;
treeProto.visit = tree_visit;
treeProto.visitAfter = tree_visitAfter;
treeProto.x = tree_x;
treeProto.y = tree_y;

exports.quadtree = quadtree;

Object.defineProperty(exports, '__esModule', { value: true });

})));

},{}],148:[function(_dereq_,module,exports){
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, _dereq_('d3-array'), _dereq_('d3-collection'), _dereq_('d3-shape'), _dereq_('elementary-circuits-directed-graph')) :
  typeof define === 'function' && define.amd ? define(['exports', 'd3-array', 'd3-collection', 'd3-shape', 'elementary-circuits-directed-graph'], factory) :
  (factory((global.d3 = global.d3 || {}),global.d3,global.d3,global.d3,null));
}(this, (function (exports,d3Array,d3Collection,d3Shape,findCircuits) { 'use strict';

  findCircuits = findCircuits && findCircuits.hasOwnProperty('default') ? findCircuits['default'] : findCircuits;

  // For a given link, return the target node's depth
  function targetDepth(d) {
    return d.target.depth;
  }

  // The depth of a node when the nodeAlign (align) is set to 'left'
  function left(node) {
    return node.depth;
  }

  // The depth of a node when the nodeAlign (align) is set to 'right'
  function right(node, n) {
    return n - 1 - node.height;
  }

  // The depth of a node when the nodeAlign (align) is set to 'justify'
  function justify(node, n) {
    return node.sourceLinks.length ? node.depth : n - 1;
  }

  // The depth of a node when the nodeAlign (align) is set to 'center'
  function center(node) {
    return node.targetLinks.length ? node.depth : node.sourceLinks.length ? d3Array.min(node.sourceLinks, targetDepth) - 1 : 0;
  }

  // returns a function, using the parameter given to the sankey setting
  function constant(x) {
    return function () {
      return x;
    };
  }

  var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
    return typeof obj;
  } : function (obj) {
    return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  };

  /// https://github.com/tomshanley/d3-sankeyCircular-circular

  // sort links' breadth (ie top to bottom in a column), based on their source nodes' breadths
  function ascendingSourceBreadth(a, b) {
    return ascendingBreadth(a.source, b.source) || a.index - b.index;
  }

  // sort links' breadth (ie top to bottom in a column), based on their target nodes' breadths
  function ascendingTargetBreadth(a, b) {
    return ascendingBreadth(a.target, b.target) || a.index - b.index;
  }

  // sort nodes' breadth (ie top to bottom in a column)
  // if both nodes have circular links, or both don't have circular links, then sort by the top (y0) of the node
  // else push nodes that have top circular links to the top, and nodes that have bottom circular links to the bottom
  function ascendingBreadth(a, b) {
    if (a.partOfCycle === b.partOfCycle) {
      return a.y0 - b.y0;
    } else {
      if (a.circularLinkType === 'top' || b.circularLinkType === 'bottom') {
        return -1;
      } else {
        return 1;
      }
    }
  }

  // return the value of a node or link
  function value(d) {
    return d.value;
  }

  // return the vertical center of a node
  function nodeCenter(node) {
    return (node.y0 + node.y1) / 2;
  }

  // return the vertical center of a link's source node
  function linkSourceCenter(link) {
    return nodeCenter(link.source);
  }

  // return the vertical center of a link's target node
  function linkTargetCenter(link) {
    return nodeCenter(link.target);
  }

  // Return the default value for ID for node, d.index
  function defaultId(d) {
    return d.index;
  }

  // Return the default object the graph's nodes, graph.nodes
  function defaultNodes(graph) {
    return graph.nodes;
  }

  // Return the default object the graph's nodes, graph.links
  function defaultLinks(graph) {
    return graph.links;
  }

  // Return the node from the collection that matches the provided ID, or throw an error if no match
  function find(nodeById, id) {
    var node = nodeById.get(id);
    if (!node) throw new Error('missing: ' + id);
    return node;
  }

  function getNodeID(node, id) {
    return id(node);
  }

  // The main sankeyCircular functions

  // Some constants for circular link calculations
  var verticalMargin = 25;
  var baseRadius = 10;
  var scale = 0.3; //Possibly let user control this, although anything over 0.5 starts to get too cramped

  function sankeyCircular () {
    // Set the default values
    var x0 = 0,
        y0 = 0,
        x1 = 1,
        y1 = 1,
        // extent
    dx = 24,
        // nodeWidth
    py,
        // nodePadding, for vertical postioning
    id = defaultId,
        align = justify,
        nodes = defaultNodes,
        links = defaultLinks,
        iterations = 32,
        circularLinkGap = 2,
        paddingRatio,
        sortNodes = null;

    function sankeyCircular() {
      var graph = {
        nodes: nodes.apply(null, arguments),
        links: links.apply(null, arguments)

        // Process the graph's nodes and links, setting their positions

        // 1.  Associate the nodes with their respective links, and vice versa
      };computeNodeLinks(graph);

      // 2.  Determine which links result in a circular path in the graph
      identifyCircles(graph, id, sortNodes);

      // 4. Calculate the nodes' values, based on the values of the incoming and outgoing links
      computeNodeValues(graph);

      // 5.  Calculate the nodes' depth based on the incoming and outgoing links
      //     Sets the nodes':
      //     - depth:  the depth in the graph
      //     - column: the depth (0, 1, 2, etc), as is relates to visual position from left to right
      //     - x0, x1: the x coordinates, as is relates to visual position from left to right
      computeNodeDepths(graph);

      // 3.  Determine how the circular links will be drawn,
      //     either travelling back above the main chart ("top")
      //     or below the main chart ("bottom")
      selectCircularLinkTypes(graph, id);

      // 6.  Calculate the nodes' and links' vertical position within their respective column
      //     Also readjusts sankeyCircular size if circular links are needed, and node x's
      computeNodeBreadths(graph, iterations, id);
      computeLinkBreadths(graph);

      // 7.  Sort links per node, based on the links' source/target nodes' breadths
      // 8.  Adjust nodes that overlap links that span 2+ columns
      var linkSortingIterations = 4; //Possibly let user control this number, like the iterations over node placement
      for (var iteration = 0; iteration < linkSortingIterations; iteration++) {

        sortSourceLinks(graph, y1, id);
        sortTargetLinks(graph, y1, id);
        resolveNodeLinkOverlaps(graph, y0, y1, id);
        sortSourceLinks(graph, y1, id);
        sortTargetLinks(graph, y1, id);
      }

      // 8.1  Adjust node and link positions back to fill height of chart area if compressed
      fillHeight(graph, y0, y1);

      // 9. Calculate visually appealling path for the circular paths, and create the "d" string
      addCircularPathData(graph, circularLinkGap, y1, id);

      return graph;
    } // end of sankeyCircular function


    // Set the sankeyCircular parameters
    // nodeID, nodeAlign, nodeWidth, nodePadding, nodes, links, size, extent, iterations, nodePaddingRatio, circularLinkGap
    sankeyCircular.nodeId = function (_) {
      return arguments.length ? (id = typeof _ === 'function' ? _ : constant(_), sankeyCircular) : id;
    };

    sankeyCircular.nodeAlign = function (_) {
      return arguments.length ? (align = typeof _ === 'function' ? _ : constant(_), sankeyCircular) : align;
    };

    sankeyCircular.nodeWidth = function (_) {
      return arguments.length ? (dx = +_, sankeyCircular) : dx;
    };

    sankeyCircular.nodePadding = function (_) {
      return arguments.length ? (py = +_, sankeyCircular) : py;
    };

    sankeyCircular.nodes = function (_) {
      return arguments.length ? (nodes = typeof _ === 'function' ? _ : constant(_), sankeyCircular) : nodes;
    };

    sankeyCircular.links = function (_) {
      return arguments.length ? (links = typeof _ === 'function' ? _ : constant(_), sankeyCircular) : links;
    };

    sankeyCircular.size = function (_) {
      return arguments.length ? (x0 = y0 = 0, x1 = +_[0], y1 = +_[1], sankeyCircular) : [x1 - x0, y1 - y0];
    };

    sankeyCircular.extent = function (_) {
      return arguments.length ? (x0 = +_[0][0], x1 = +_[1][0], y0 = +_[0][1], y1 = +_[1][1], sankeyCircular) : [[x0, y0], [x1, y1]];
    };

    sankeyCircular.iterations = function (_) {
      return arguments.length ? (iterations = +_, sankeyCircular) : iterations;
    };

    sankeyCircular.circularLinkGap = function (_) {
      return arguments.length ? (circularLinkGap = +_, sankeyCircular) : circularLinkGap;
    };

    sankeyCircular.nodePaddingRatio = function (_) {
      return arguments.length ? (paddingRatio = +_, sankeyCircular) : paddingRatio;
    };

    sankeyCircular.sortNodes = function (_) {
      return arguments.length ? (sortNodes = _, sankeyCircular) : sortNodes;
    };

    sankeyCircular.update = function (graph) {
      // 5.  Calculate the nodes' depth based on the incoming and outgoing links
      //     Sets the nodes':
      //     - depth:  the depth in the graph
      //     - column: the depth (0, 1, 2, etc), as is relates to visual position from left to right
      //     - x0, x1: the x coordinates, as is relates to visual position from left to right
      // computeNodeDepths(graph)

      // 3.  Determine how the circular links will be drawn,
      //     either travelling back above the main chart ("top")
      //     or below the main chart ("bottom")
      selectCircularLinkTypes(graph, id);

      // 6.  Calculate the nodes' and links' vertical position within their respective column
      //     Also readjusts sankeyCircular size if circular links are needed, and node x's
      // computeNodeBreadths(graph, iterations, id)
      computeLinkBreadths(graph);

      // Force position of circular link type based on position
      graph.links.forEach(function (link) {
        if (link.circular) {
          link.circularLinkType = link.y0 + link.y1 < y1 ? 'top' : 'bottom';

          link.source.circularLinkType = link.circularLinkType;
          link.target.circularLinkType = link.circularLinkType;
        }
      });

      sortSourceLinks(graph, y1, id, false); // Sort links but do not move nodes
      sortTargetLinks(graph, y1, id);

      // 7.  Sort links per node, based on the links' source/target nodes' breadths
      // 8.  Adjust nodes that overlap links that span 2+ columns
      // var linkSortingIterations = 4; //Possibly let user control this number, like the iterations over node placement
      // for (var iteration = 0; iteration < linkSortingIterations; iteration++) {
      //
      //   sortSourceLinks(graph, y1, id)
      //   sortTargetLinks(graph, y1, id)
      //   resolveNodeLinkOverlaps(graph, y0, y1, id)
      //   sortSourceLinks(graph, y1, id)
      //   sortTargetLinks(graph, y1, id)
      //
      // }

      // 8.1  Adjust node and link positions back to fill height of chart area if compressed
      // fillHeight(graph, y0, y1)

      // 9. Calculate visually appealling path for the circular paths, and create the "d" string
      addCircularPathData(graph, circularLinkGap, y1, id);
      return graph;
    };

    // Populate the sourceLinks and targetLinks for each node.
    // Also, if the source and target are not objects, assume they are indices.
    function computeNodeLinks(graph) {
      graph.nodes.forEach(function (node, i) {
        node.index = i;
        node.sourceLinks = [];
        node.targetLinks = [];
      });
      var nodeById = d3Collection.map(graph.nodes, id);
      graph.links.forEach(function (link, i) {
        link.index = i;
        var source = link.source;
        var target = link.target;
        if ((typeof source === "undefined" ? "undefined" : _typeof(source)) !== 'object') {
          source = link.source = find(nodeById, source);
        }
        if ((typeof target === "undefined" ? "undefined" : _typeof(target)) !== 'object') {
          target = link.target = find(nodeById, target);
        }
        source.sourceLinks.push(link);
        target.targetLinks.push(link);
      });
      return graph;
    }

    // Compute the value (size) and cycleness of each node by summing the associated links.
    function computeNodeValues(graph) {
      graph.nodes.forEach(function (node) {
        node.partOfCycle = false;
        node.value = Math.max(d3Array.sum(node.sourceLinks, value), d3Array.sum(node.targetLinks, value));
        node.sourceLinks.forEach(function (link) {
          if (link.circular) {
            node.partOfCycle = true;
            node.circularLinkType = link.circularLinkType;
          }
        });
        node.targetLinks.forEach(function (link) {
          if (link.circular) {
            node.partOfCycle = true;
            node.circularLinkType = link.circularLinkType;
          }
        });
      });
    }

    function getCircleMargins(graph) {
      var totalTopLinksWidth = 0,
          totalBottomLinksWidth = 0,
          totalRightLinksWidth = 0,
          totalLeftLinksWidth = 0;

      var maxColumn = d3Array.max(graph.nodes, function (node) {
        return node.column;
      });

      graph.links.forEach(function (link) {
        if (link.circular) {
          if (link.circularLinkType == 'top') {
            totalTopLinksWidth = totalTopLinksWidth + link.width;
          } else {
            totalBottomLinksWidth = totalBottomLinksWidth + link.width;
          }

          if (link.target.column == 0) {
            totalLeftLinksWidth = totalLeftLinksWidth + link.width;
          }

          if (link.source.column == maxColumn) {
            totalRightLinksWidth = totalRightLinksWidth + link.width;
          }
        }
      });

      //account for radius of curves and padding between links
      totalTopLinksWidth = totalTopLinksWidth > 0 ? totalTopLinksWidth + verticalMargin + baseRadius : totalTopLinksWidth;
      totalBottomLinksWidth = totalBottomLinksWidth > 0 ? totalBottomLinksWidth + verticalMargin + baseRadius : totalBottomLinksWidth;
      totalRightLinksWidth = totalRightLinksWidth > 0 ? totalRightLinksWidth + verticalMargin + baseRadius : totalRightLinksWidth;
      totalLeftLinksWidth = totalLeftLinksWidth > 0 ? totalLeftLinksWidth + verticalMargin + baseRadius : totalLeftLinksWidth;

      return { "top": totalTopLinksWidth, "bottom": totalBottomLinksWidth, "left": totalLeftLinksWidth, "right": totalRightLinksWidth };
    }

    // Update the x0, y0, x1 and y1 for the sankeyCircular, to allow space for any circular links
    function scaleSankeySize(graph, margin) {

      var maxColumn = d3Array.max(graph.nodes, function (node) {
        return node.column;
      });

      var currentWidth = x1 - x0;
      var currentHeight = y1 - y0;

      var newWidth = currentWidth + margin.right + margin.left;
      var newHeight = currentHeight + margin.top + margin.bottom;

      var scaleX = currentWidth / newWidth;
      var scaleY = currentHeight / newHeight;

      x0 = x0 * scaleX + margin.left;
      x1 = margin.right == 0 ? x1 : x1 * scaleX;
      y0 = y0 * scaleY + margin.top;
      y1 = y1 * scaleY;

      graph.nodes.forEach(function (node) {
        node.x0 = x0 + node.column * ((x1 - x0 - dx) / maxColumn);
        node.x1 = node.x0 + dx;
      });

      return scaleY;
    }

    // Iteratively assign the depth for each node.
    // Nodes are assigned the maximum depth of incoming neighbors plus one;
    // nodes with no incoming links are assigned depth zero, while
    // nodes with no outgoing links are assigned the maximum depth.
    function computeNodeDepths(graph) {
      var nodes, next, x;

      for (nodes = graph.nodes, next = [], x = 0; nodes.length; ++x, nodes = next, next = []) {
        nodes.forEach(function (node) {
          node.depth = x;
          node.sourceLinks.forEach(function (link) {
            if (next.indexOf(link.target) < 0 && !link.circular) {
              next.push(link.target);
            }
          });
        });
      }

      for (nodes = graph.nodes, next = [], x = 0; nodes.length; ++x, nodes = next, next = []) {
        nodes.forEach(function (node) {
          node.height = x;
          node.targetLinks.forEach(function (link) {
            if (next.indexOf(link.source) < 0 && !link.circular) {
              next.push(link.source);
            }
          });
        });
      }

      // assign column numbers, and get max value
      graph.nodes.forEach(function (node) {
        node.column = Math.floor(align.call(null, node, x));
      });
    }

    // Assign nodes' breadths, and then shift nodes that overlap (resolveCollisions)
    function computeNodeBreadths(graph, iterations, id) {
      var columns = d3Collection.nest().key(function (d) {
        return d.column;
      }).sortKeys(d3Array.ascending).entries(graph.nodes).map(function (d) {
        return d.values;
      });

      initializeNodeBreadth(id);
      resolveCollisions();

      for (var alpha = 1, n = iterations; n > 0; --n) {
        relaxLeftAndRight(alpha *= 0.99, id);
        resolveCollisions();
      }

      function initializeNodeBreadth(id) {

        //override py if nodePadding has been set
        if (paddingRatio) {
          var padding = Infinity;
          columns.forEach(function (nodes) {
            var thisPadding = y1 * paddingRatio / (nodes.length + 1);
            padding = thisPadding < padding ? thisPadding : padding;
          });
          py = padding;
        }

        var ky = d3Array.min(columns, function (nodes) {
          return (y1 - y0 - (nodes.length - 1) * py) / d3Array.sum(nodes, value);
        });

        //calculate the widths of the links
        ky = ky * scale;

        graph.links.forEach(function (link) {
          link.width = link.value * ky;
        });

        //determine how much to scale down the chart, based on circular links
        var margin = getCircleMargins(graph);
        var ratio = scaleSankeySize(graph, margin);

        //re-calculate widths
        ky = ky * ratio;

        graph.links.forEach(function (link) {
          link.width = link.value * ky;
        });

        columns.forEach(function (nodes) {
          var nodesLength = nodes.length;
          nodes.forEach(function (node, i) {
            if (node.depth == columns.length - 1 && nodesLength == 1) {
              node.y0 = y1 / 2 - node.value * ky;
              node.y1 = node.y0 + node.value * ky;
            } else if (node.depth == 0 && nodesLength == 1) {
              node.y0 = y1 / 2 - node.value * ky;
              node.y1 = node.y0 + node.value * ky;
            } else if (node.partOfCycle) {
              if (numberOfNonSelfLinkingCycles(node, id) == 0) {
                node.y0 = y1 / 2 + i;
                node.y1 = node.y0 + node.value * ky;
              } else if (node.circularLinkType == 'top') {
                node.y0 = y0 + i;
                node.y1 = node.y0 + node.value * ky;
              } else {
                node.y0 = y1 - node.value * ky - i;
                node.y1 = node.y0 + node.value * ky;
              }
            } else {
              if (margin.top == 0 || margin.bottom == 0) {
                node.y0 = (y1 - y0) / nodesLength * i;
                node.y1 = node.y0 + node.value * ky;
              } else {
                node.y0 = (y1 - y0) / 2 - nodesLength / 2 + i;
                node.y1 = node.y0 + node.value * ky;
              }
            }
          });
        });
      }

      // For each node in each column, check the node's vertical position in relation to its targets and sources vertical position
      // and shift up/down to be closer to the vertical middle of those targets and sources
      function relaxLeftAndRight(alpha, id) {
        var columnsLength = columns.length;

        columns.forEach(function (nodes) {
          var n = nodes.length;
          var depth = nodes[0].depth;

          nodes.forEach(function (node) {
            // check the node is not an orphan
            var nodeHeight;
            if (node.sourceLinks.length || node.targetLinks.length) {
              if (node.partOfCycle && numberOfNonSelfLinkingCycles(node, id) > 0) ; else if (depth == 0 && n == 1) {
                nodeHeight = node.y1 - node.y0;

                node.y0 = y1 / 2 - nodeHeight / 2;
                node.y1 = y1 / 2 + nodeHeight / 2;
              } else if (depth == columnsLength - 1 && n == 1) {
                nodeHeight = node.y1 - node.y0;

                node.y0 = y1 / 2 - nodeHeight / 2;
                node.y1 = y1 / 2 + nodeHeight / 2;
              } else {
                var avg = 0;

                var avgTargetY = d3Array.mean(node.sourceLinks, linkTargetCenter);
                var avgSourceY = d3Array.mean(node.targetLinks, linkSourceCenter);

                if (avgTargetY && avgSourceY) {
                  avg = (avgTargetY + avgSourceY) / 2;
                } else {
                  avg = avgTargetY || avgSourceY;
                }

                var dy = (avg - nodeCenter(node)) * alpha;
                // positive if it node needs to move down
                node.y0 += dy;
                node.y1 += dy;
              }
            }
          });
        });
      }

      // For each column, check if nodes are overlapping, and if so, shift up/down
      function resolveCollisions() {
        columns.forEach(function (nodes) {
          var node,
              dy,
              y = y0,
              n = nodes.length,
              i;

          // Push any overlapping nodes down.
          nodes.sort(ascendingBreadth);

          for (i = 0; i < n; ++i) {
            node = nodes[i];
            dy = y - node.y0;

            if (dy > 0) {
              node.y0 += dy;
              node.y1 += dy;
            }
            y = node.y1 + py;
          }

          // If the bottommost node goes outside the bounds, push it back up.
          dy = y - py - y1;
          if (dy > 0) {
            y = node.y0 -= dy, node.y1 -= dy;

            // Push any overlapping nodes back up.
            for (i = n - 2; i >= 0; --i) {
              node = nodes[i];
              dy = node.y1 + py - y;
              if (dy > 0) node.y0 -= dy, node.y1 -= dy;
              y = node.y0;
            }
          }
        });
      }
    }

    // Assign the links y0 and y1 based on source/target nodes position,
    // plus the link's relative position to other links to the same node
    function computeLinkBreadths(graph) {
      graph.nodes.forEach(function (node) {
        node.sourceLinks.sort(ascendingTargetBreadth);
        node.targetLinks.sort(ascendingSourceBreadth);
      });
      graph.nodes.forEach(function (node) {
        var y0 = node.y0;
        var y1 = y0;

        // start from the bottom of the node for cycle links
        var y0cycle = node.y1;
        var y1cycle = y0cycle;

        node.sourceLinks.forEach(function (link) {
          if (link.circular) {
            link.y0 = y0cycle - link.width / 2;
            y0cycle = y0cycle - link.width;
          } else {
            link.y0 = y0 + link.width / 2;
            y0 += link.width;
          }
        });
        node.targetLinks.forEach(function (link) {
          if (link.circular) {
            link.y1 = y1cycle - link.width / 2;
            y1cycle = y1cycle - link.width;
          } else {
            link.y1 = y1 + link.width / 2;
            y1 += link.width;
          }
        });
      });
    }

    return sankeyCircular;
  }

  /// /////////////////////////////////////////////////////////////////////////////////
  // Cycle functions
  // portion of code to detect circular links based on Colin Fergus' bl.ock https://gist.github.com/cfergus/3956043

  // Identify circles in the link objects
  function identifyCircles(graph, id, sortNodes) {

    var circularLinkID = 0;

    if (sortNodes === null) {

      // Building adjacency graph
      var adjList = [];
      for (var i = 0; i < graph.links.length; i++) {
        var link = graph.links[i];
        var source = link.source.index;
        var target = link.target.index;
        if (!adjList[source]) adjList[source] = [];
        if (!adjList[target]) adjList[target] = [];

        // Add links if not already in set
        if (adjList[source].indexOf(target) === -1) adjList[source].push(target);
      }

      // Find all elementary circuits
      var cycles = findCircuits(adjList);

      // Sort by circuits length
      cycles.sort(function (a, b) {
        return a.length - b.length;
      });

      // Make one link circular for each elementary circuit
      var circularLinks = {};
      for (i = 0; i < cycles.length; i++) {
        var cycle = cycles[i];
        var closed = false;
        for (var j = 0; j < cycle.length - 1; j++) {
          if (!circularLinks[cycle[j]]) circularLinks[cycle[j]] = {};

          // Check if there is already a circular link in the circuit
          if (circularLinks[cycle[j]] && circularLinks[cycle[j]][cycle[j + 1]]) {
            closed = true;
            break;
          }
        }

        if (!closed) {
          // If not closed, make the last link the circular one
          var last = cycle.slice(-2);
          circularLinks[last[0]][last[1]] = true;
        }
      }

      graph.links.forEach(function (link) {
        var target = link.target.index;
        var source = link.source.index;
        // If self-linking or a back-edge
        if (target === source || circularLinks[source] && circularLinks[source][target]) {
          link.circular = true;
          link.circularLinkID = circularLinkID;
          circularLinkID = circularLinkID + 1;
        } else {
          link.circular = false;
        }
      });
    } else {
      graph.links.forEach(function (link) {
        if (link.source[sortNodes] < link.target[sortNodes]) {
          link.circular = false;
        } else {
          link.circular = true;
          link.circularLinkID = circularLinkID;
          circularLinkID = circularLinkID + 1;
        }
      });
    }
  }

  // Assign a circular link type (top or bottom), based on:
  // - if the source/target node already has circular links, then use the same type
  // - if not, choose the type with fewer links
  function selectCircularLinkTypes(graph, id) {
    var numberOfTops = 0;
    var numberOfBottoms = 0;
    graph.links.forEach(function (link) {
      if (link.circular) {
        // if either souce or target has type already use that
        if (link.source.circularLinkType || link.target.circularLinkType) {
          // default to source type if available
          link.circularLinkType = link.source.circularLinkType ? link.source.circularLinkType : link.target.circularLinkType;
        } else {
          link.circularLinkType = numberOfTops < numberOfBottoms ? 'top' : 'bottom';
        }

        if (link.circularLinkType == 'top') {
          numberOfTops = numberOfTops + 1;
        } else {
          numberOfBottoms = numberOfBottoms + 1;
        }

        graph.nodes.forEach(function (node) {
          if (getNodeID(node, id) == getNodeID(link.source, id) || getNodeID(node, id) == getNodeID(link.target, id)) {
            node.circularLinkType = link.circularLinkType;
          }
        });
      }
    });

    //correct self-linking links to be same direction as node
    graph.links.forEach(function (link) {
      if (link.circular) {
        //if both source and target node are same type, then link should have same type
        if (link.source.circularLinkType == link.target.circularLinkType) {
          link.circularLinkType = link.source.circularLinkType;
        }
        //if link is selflinking, then link should have same type as node
        if (selfLinking(link, id)) {
          link.circularLinkType = link.source.circularLinkType;
        }
      }
    });
  }

  // Return the angle between a straight line between the source and target of the link, and the vertical plane of the node
  function linkAngle(link) {
    var adjacent = Math.abs(link.y1 - link.y0);
    var opposite = Math.abs(link.target.x0 - link.source.x1);

    return Math.atan(opposite / adjacent);
  }

  // Check if two circular links potentially overlap
  function circularLinksCross(link1, link2) {
    if (link1.source.column < link2.target.column) {
      return false;
    } else if (link1.target.column > link2.source.column) {
      return false;
    } else {
      return true;
    }
  }

  // Return the number of circular links for node, not including self linking links
  function numberOfNonSelfLinkingCycles(node, id) {
    var sourceCount = 0;
    node.sourceLinks.forEach(function (l) {
      sourceCount = l.circular && !selfLinking(l, id) ? sourceCount + 1 : sourceCount;
    });

    var targetCount = 0;
    node.targetLinks.forEach(function (l) {
      targetCount = l.circular && !selfLinking(l, id) ? targetCount + 1 : targetCount;
    });

    return sourceCount + targetCount;
  }

  // Check if a circular link is the only circular link for both its source and target node
  function onlyCircularLink(link) {
    var nodeSourceLinks = link.source.sourceLinks;
    var sourceCount = 0;
    nodeSourceLinks.forEach(function (l) {
      sourceCount = l.circular ? sourceCount + 1 : sourceCount;
    });

    var nodeTargetLinks = link.target.targetLinks;
    var targetCount = 0;
    nodeTargetLinks.forEach(function (l) {
      targetCount = l.circular ? targetCount + 1 : targetCount;
    });

    if (sourceCount > 1 || targetCount > 1) {
      return false;
    } else {
      return true;
    }
  }

  // creates vertical buffer values per set of top/bottom links
  function calcVerticalBuffer(links, circularLinkGap, id) {
    links.sort(sortLinkColumnAscending);
    links.forEach(function (link, i) {
      var buffer = 0;

      if (selfLinking(link, id) && onlyCircularLink(link)) {
        link.circularPathData.verticalBuffer = buffer + link.width / 2;
      } else {
        var j = 0;
        for (j; j < i; j++) {
          if (circularLinksCross(links[i], links[j])) {
            var bufferOverThisLink = links[j].circularPathData.verticalBuffer + links[j].width / 2 + circularLinkGap;
            buffer = bufferOverThisLink > buffer ? bufferOverThisLink : buffer;
          }
        }

        link.circularPathData.verticalBuffer = buffer + link.width / 2;
      }
    });

    return links;
  }

  // calculate the optimum path for a link to reduce overlaps
  function addCircularPathData(graph, circularLinkGap, y1, id) {
    //var baseRadius = 10
    var buffer = 5;
    //var verticalMargin = 25

    var minY = d3Array.min(graph.links, function (link) {
      return link.source.y0;
    });

    // create object for circular Path Data
    graph.links.forEach(function (link) {
      if (link.circular) {
        link.circularPathData = {};
      }
    });

    // calc vertical offsets per top/bottom links
    var topLinks = graph.links.filter(function (l) {
      return l.circularLinkType == 'top';
    });
    /* topLinks = */calcVerticalBuffer(topLinks, circularLinkGap, id);

    var bottomLinks = graph.links.filter(function (l) {
      return l.circularLinkType == 'bottom';
    });
    /* bottomLinks = */calcVerticalBuffer(bottomLinks, circularLinkGap, id);

    // add the base data for each link
    graph.links.forEach(function (link) {
      if (link.circular) {
        link.circularPathData.arcRadius = link.width + baseRadius;
        link.circularPathData.leftNodeBuffer = buffer;
        link.circularPathData.rightNodeBuffer = buffer;
        link.circularPathData.sourceWidth = link.source.x1 - link.source.x0;
        link.circularPathData.sourceX = link.source.x0 + link.circularPathData.sourceWidth;
        link.circularPathData.targetX = link.target.x0;
        link.circularPathData.sourceY = link.y0;
        link.circularPathData.targetY = link.y1;

        // for self linking paths, and that the only circular link in/out of that node
        if (selfLinking(link, id) && onlyCircularLink(link)) {
          link.circularPathData.leftSmallArcRadius = baseRadius + link.width / 2;
          link.circularPathData.leftLargeArcRadius = baseRadius + link.width / 2;
          link.circularPathData.rightSmallArcRadius = baseRadius + link.width / 2;
          link.circularPathData.rightLargeArcRadius = baseRadius + link.width / 2;

          if (link.circularLinkType == 'bottom') {
            link.circularPathData.verticalFullExtent = link.source.y1 + verticalMargin + link.circularPathData.verticalBuffer;
            link.circularPathData.verticalLeftInnerExtent = link.circularPathData.verticalFullExtent - link.circularPathData.leftLargeArcRadius;
            link.circularPathData.verticalRightInnerExtent = link.circularPathData.verticalFullExtent - link.circularPathData.rightLargeArcRadius;
          } else {
            // top links
            link.circularPathData.verticalFullExtent = link.source.y0 - verticalMargin - link.circularPathData.verticalBuffer;
            link.circularPathData.verticalLeftInnerExtent = link.circularPathData.verticalFullExtent + link.circularPathData.leftLargeArcRadius;
            link.circularPathData.verticalRightInnerExtent = link.circularPathData.verticalFullExtent + link.circularPathData.rightLargeArcRadius;
          }
        } else {
          // else calculate normally
          // add left extent coordinates, based on links with same source column and circularLink type
          var thisColumn = link.source.column;
          var thisCircularLinkType = link.circularLinkType;
          var sameColumnLinks = graph.links.filter(function (l) {
            return l.source.column == thisColumn && l.circularLinkType == thisCircularLinkType;
          });

          if (link.circularLinkType == 'bottom') {
            sameColumnLinks.sort(sortLinkSourceYDescending);
          } else {
            sameColumnLinks.sort(sortLinkSourceYAscending);
          }

          var radiusOffset = 0;
          sameColumnLinks.forEach(function (l, i) {
            if (l.circularLinkID == link.circularLinkID) {
              link.circularPathData.leftSmallArcRadius = baseRadius + link.width / 2 + radiusOffset;
              link.circularPathData.leftLargeArcRadius = baseRadius + link.width / 2 + i * circularLinkGap + radiusOffset;
            }
            radiusOffset = radiusOffset + l.width;
          });

          // add right extent coordinates, based on links with same target column and circularLink type
          thisColumn = link.target.column;
          sameColumnLinks = graph.links.filter(function (l) {
            return l.target.column == thisColumn && l.circularLinkType == thisCircularLinkType;
          });
          if (link.circularLinkType == 'bottom') {
            sameColumnLinks.sort(sortLinkTargetYDescending);
          } else {
            sameColumnLinks.sort(sortLinkTargetYAscending);
          }

          radiusOffset = 0;
          sameColumnLinks.forEach(function (l, i) {
            if (l.circularLinkID == link.circularLinkID) {
              link.circularPathData.rightSmallArcRadius = baseRadius + link.width / 2 + radiusOffset;
              link.circularPathData.rightLargeArcRadius = baseRadius + link.width / 2 + i * circularLinkGap + radiusOffset;
            }
            radiusOffset = radiusOffset + l.width;
          });

          // bottom links
          if (link.circularLinkType == 'bottom') {
            link.circularPathData.verticalFullExtent = Math.max(y1, link.source.y1, link.target.y1) + verticalMargin + link.circularPathData.verticalBuffer;
            link.circularPathData.verticalLeftInnerExtent = link.circularPathData.verticalFullExtent - link.circularPathData.leftLargeArcRadius;
            link.circularPathData.verticalRightInnerExtent = link.circularPathData.verticalFullExtent - link.circularPathData.rightLargeArcRadius;
          } else {
            // top links
            link.circularPathData.verticalFullExtent = minY - verticalMargin - link.circularPathData.verticalBuffer;
            link.circularPathData.verticalLeftInnerExtent = link.circularPathData.verticalFullExtent + link.circularPathData.leftLargeArcRadius;
            link.circularPathData.verticalRightInnerExtent = link.circularPathData.verticalFullExtent + link.circularPathData.rightLargeArcRadius;
          }
        }

        // all links
        link.circularPathData.leftInnerExtent = link.circularPathData.sourceX + link.circularPathData.leftNodeBuffer;
        link.circularPathData.rightInnerExtent = link.circularPathData.targetX - link.circularPathData.rightNodeBuffer;
        link.circularPathData.leftFullExtent = link.circularPathData.sourceX + link.circularPathData.leftLargeArcRadius + link.circularPathData.leftNodeBuffer;
        link.circularPathData.rightFullExtent = link.circularPathData.targetX - link.circularPathData.rightLargeArcRadius - link.circularPathData.rightNodeBuffer;
      }

      if (link.circular) {
        link.path = createCircularPathString(link);
      } else {
        var normalPath = d3Shape.linkHorizontal().source(function (d) {
          var x = d.source.x0 + (d.source.x1 - d.source.x0);
          var y = d.y0;
          return [x, y];
        }).target(function (d) {
          var x = d.target.x0;
          var y = d.y1;
          return [x, y];
        });
        link.path = normalPath(link);
      }
    });
  }

  // create a d path using the addCircularPathData
  function createCircularPathString(link) {
    var pathString = '';
    // 'pathData' is assigned a value but never used
    // var pathData = {}

    if (link.circularLinkType == 'top') {
      pathString =
      // start at the right of the source node
      'M' + link.circularPathData.sourceX + ' ' + link.circularPathData.sourceY + ' ' +
      // line right to buffer point
      'L' + link.circularPathData.leftInnerExtent + ' ' + link.circularPathData.sourceY + ' ' +
      // Arc around: Centre of arc X and  //Centre of arc Y
      'A' + link.circularPathData.leftLargeArcRadius + ' ' + link.circularPathData.leftSmallArcRadius + ' 0 0 0 ' +
      // End of arc X //End of arc Y
      link.circularPathData.leftFullExtent + ' ' + (link.circularPathData.sourceY - link.circularPathData.leftSmallArcRadius) + ' ' + // End of arc X
      // line up to buffer point
      'L' + link.circularPathData.leftFullExtent + ' ' + link.circularPathData.verticalLeftInnerExtent + ' ' +
      // Arc around: Centre of arc X and  //Centre of arc Y
      'A' + link.circularPathData.leftLargeArcRadius + ' ' + link.circularPathData.leftLargeArcRadius + ' 0 0 0 ' +
      // End of arc X //End of arc Y
      link.circularPathData.leftInnerExtent + ' ' + link.circularPathData.verticalFullExtent + ' ' + // End of arc X
      // line left to buffer point
      'L' + link.circularPathData.rightInnerExtent + ' ' + link.circularPathData.verticalFullExtent + ' ' +
      // Arc around: Centre of arc X and  //Centre of arc Y
      'A' + link.circularPathData.rightLargeArcRadius + ' ' + link.circularPathData.rightLargeArcRadius + ' 0 0 0 ' +
      // End of arc X //End of arc Y
      link.circularPathData.rightFullExtent + ' ' + link.circularPathData.verticalRightInnerExtent + ' ' + // End of arc X
      // line down
      'L' + link.circularPathData.rightFullExtent + ' ' + (link.circularPathData.targetY - link.circularPathData.rightSmallArcRadius) + ' ' +
      // Arc around: Centre of arc X and  //Centre of arc Y
      'A' + link.circularPathData.rightLargeArcRadius + ' ' + link.circularPathData.rightSmallArcRadius + ' 0 0 0 ' +
      // End of arc X //End of arc Y
      link.circularPathData.rightInnerExtent + ' ' + link.circularPathData.targetY + ' ' + // End of arc X
      // line to end
      'L' + link.circularPathData.targetX + ' ' + link.circularPathData.targetY;
    } else {
      // bottom path
      pathString =
      // start at the right of the source node
      'M' + link.circularPathData.sourceX + ' ' + link.circularPathData.sourceY + ' ' +
      // line right to buffer point
      'L' + link.circularPathData.leftInnerExtent + ' ' + link.circularPathData.sourceY + ' ' +
      // Arc around: Centre of arc X and  //Centre of arc Y
      'A' + link.circularPathData.leftLargeArcRadius + ' ' + link.circularPathData.leftSmallArcRadius + ' 0 0 1 ' +
      // End of arc X //End of arc Y
      link.circularPathData.leftFullExtent + ' ' + (link.circularPathData.sourceY + link.circularPathData.leftSmallArcRadius) + ' ' + // End of arc X
      // line down to buffer point
      'L' + link.circularPathData.leftFullExtent + ' ' + link.circularPathData.verticalLeftInnerExtent + ' ' +
      // Arc around: Centre of arc X and  //Centre of arc Y
      'A' + link.circularPathData.leftLargeArcRadius + ' ' + link.circularPathData.leftLargeArcRadius + ' 0 0 1 ' +
      // End of arc X //End of arc Y
      link.circularPathData.leftInnerExtent + ' ' + link.circularPathData.verticalFullExtent + ' ' + // End of arc X
      // line left to buffer point
      'L' + link.circularPathData.rightInnerExtent + ' ' + link.circularPathData.verticalFullExtent + ' ' +
      // Arc around: Centre of arc X and  //Centre of arc Y
      'A' + link.circularPathData.rightLargeArcRadius + ' ' + link.circularPathData.rightLargeArcRadius + ' 0 0 1 ' +
      // End of arc X //End of arc Y
      link.circularPathData.rightFullExtent + ' ' + link.circularPathData.verticalRightInnerExtent + ' ' + // End of arc X
      // line up
      'L' + link.circularPathData.rightFullExtent + ' ' + (link.circularPathData.targetY + link.circularPathData.rightSmallArcRadius) + ' ' +
      // Arc around: Centre of arc X and  //Centre of arc Y
      'A' + link.circularPathData.rightLargeArcRadius + ' ' + link.circularPathData.rightSmallArcRadius + ' 0 0 1 ' +
      // End of arc X //End of arc Y
      link.circularPathData.rightInnerExtent + ' ' + link.circularPathData.targetY + ' ' + // End of arc X
      // line to end
      'L' + link.circularPathData.targetX + ' ' + link.circularPathData.targetY;
    }

    return pathString;
  }

  // sort links based on the distance between the source and tartget node columns
  // if the same, then use Y position of the source node
  function sortLinkColumnAscending(link1, link2) {
    if (linkColumnDistance(link1) == linkColumnDistance(link2)) {
      return link1.circularLinkType == 'bottom' ? sortLinkSourceYDescending(link1, link2) : sortLinkSourceYAscending(link1, link2);
    } else {
      return linkColumnDistance(link2) - linkColumnDistance(link1);
    }
  }

  // sort ascending links by their source vertical position, y0
  function sortLinkSourceYAscending(link1, link2) {
    return link1.y0 - link2.y0;
  }

  // sort descending links by their source vertical position, y0
  function sortLinkSourceYDescending(link1, link2) {
    return link2.y0 - link1.y0;
  }

  // sort ascending links by their target vertical position, y1
  function sortLinkTargetYAscending(link1, link2) {
    return link1.y1 - link2.y1;
  }

  // sort descending links by their target vertical position, y1
  function sortLinkTargetYDescending(link1, link2) {
    return link2.y1 - link1.y1;
  }

  // return the distance between the link's target and source node, in terms of the nodes' column
  function linkColumnDistance(link) {
    return link.target.column - link.source.column;
  }

  // return the distance between the link's target and source node, in terms of the nodes' X coordinate
  function linkXLength(link) {
    return link.target.x0 - link.source.x1;
  }

  // Return the Y coordinate on the longerLink path * which is perpendicular shorterLink's source.
  // * approx, based on a straight line from target to source, when in fact the path is a bezier
  function linkPerpendicularYToLinkSource(longerLink, shorterLink) {
    // get the angle for the longer link
    var angle = linkAngle(longerLink);

    // get the adjacent length to the other link's x position
    var heightFromY1ToPependicular = linkXLength(shorterLink) / Math.tan(angle);

    // add or subtract from longer link1's original y1, depending on the slope
    var yPerpendicular = incline(longerLink) == 'up' ? longerLink.y1 + heightFromY1ToPependicular : longerLink.y1 - heightFromY1ToPependicular;

    return yPerpendicular;
  }

  // Return the Y coordinate on the longerLink path * which is perpendicular shorterLink's source.
  // * approx, based on a straight line from target to source, when in fact the path is a bezier
  function linkPerpendicularYToLinkTarget(longerLink, shorterLink) {
    // get the angle for the longer link
    var angle = linkAngle(longerLink);

    // get the adjacent length to the other link's x position
    var heightFromY1ToPependicular = linkXLength(shorterLink) / Math.tan(angle);

    // add or subtract from longer link's original y1, depending on the slope
    var yPerpendicular = incline(longerLink) == 'up' ? longerLink.y1 - heightFromY1ToPependicular : longerLink.y1 + heightFromY1ToPependicular;

    return yPerpendicular;
  }

  // Move any nodes that overlap links which span 2+ columns
  function resolveNodeLinkOverlaps(graph, y0, y1, id) {

    graph.links.forEach(function (link) {
      if (link.circular) {
        return;
      }

      if (link.target.column - link.source.column > 1) {
        var columnToTest = link.source.column + 1;
        var maxColumnToTest = link.target.column - 1;

        var i = 1;
        var numberOfColumnsToTest = maxColumnToTest - columnToTest + 1;

        for (i = 1; columnToTest <= maxColumnToTest; columnToTest++, i++) {
          graph.nodes.forEach(function (node) {
            if (node.column == columnToTest) {
              var t = i / (numberOfColumnsToTest + 1);

              // Find all the points of a cubic bezier curve in javascript
              // https://stackoverflow.com/questions/15397596/find-all-the-points-of-a-cubic-bezier-curve-in-javascript

              var B0_t = Math.pow(1 - t, 3);
              var B1_t = 3 * t * Math.pow(1 - t, 2);
              var B2_t = 3 * Math.pow(t, 2) * (1 - t);
              var B3_t = Math.pow(t, 3);

              var py_t = B0_t * link.y0 + B1_t * link.y0 + B2_t * link.y1 + B3_t * link.y1;

              var linkY0AtColumn = py_t - link.width / 2;
              var linkY1AtColumn = py_t + link.width / 2;
              var dy;

              // If top of link overlaps node, push node up
              if (linkY0AtColumn > node.y0 && linkY0AtColumn < node.y1) {

                dy = node.y1 - linkY0AtColumn + 10;
                dy = node.circularLinkType == 'bottom' ? dy : -dy;

                node = adjustNodeHeight(node, dy, y0, y1);

                // check if other nodes need to move up too
                graph.nodes.forEach(function (otherNode) {
                  // don't need to check itself or nodes at different columns
                  if (getNodeID(otherNode, id) == getNodeID(node, id) || otherNode.column != node.column) {
                    return;
                  }
                  if (nodesOverlap(node, otherNode)) {
                    adjustNodeHeight(otherNode, dy, y0, y1);
                  }
                });
              } else if (linkY1AtColumn > node.y0 && linkY1AtColumn < node.y1) {
                // If bottom of link overlaps node, push node down
                dy = linkY1AtColumn - node.y0 + 10;

                node = adjustNodeHeight(node, dy, y0, y1);

                // check if other nodes need to move down too
                graph.nodes.forEach(function (otherNode) {
                  // don't need to check itself or nodes at different columns
                  if (getNodeID(otherNode, id) == getNodeID(node, id) || otherNode.column != node.column) {
                    return;
                  }
                  if (otherNode.y0 < node.y1 && otherNode.y1 > node.y1) {
                    adjustNodeHeight(otherNode, dy, y0, y1);
                  }
                });
              } else if (linkY0AtColumn < node.y0 && linkY1AtColumn > node.y1) {
                // if link completely overlaps node
                dy = linkY1AtColumn - node.y0 + 10;

                node = adjustNodeHeight(node, dy, y0, y1);

                graph.nodes.forEach(function (otherNode) {
                  // don't need to check itself or nodes at different columns
                  if (getNodeID(otherNode, id) == getNodeID(node, id) || otherNode.column != node.column) {
                    return;
                  }
                  if (otherNode.y0 < node.y1 && otherNode.y1 > node.y1) {
                    adjustNodeHeight(otherNode, dy, y0, y1);
                  }
                });
              }
            }
          });
        }
      }
    });
  }

  // check if two nodes overlap
  function nodesOverlap(nodeA, nodeB) {
    // test if nodeA top partially overlaps nodeB
    if (nodeA.y0 > nodeB.y0 && nodeA.y0 < nodeB.y1) {
      return true;
    } else if (nodeA.y1 > nodeB.y0 && nodeA.y1 < nodeB.y1) {
      // test if nodeA bottom partially overlaps nodeB
      return true;
    } else if (nodeA.y0 < nodeB.y0 && nodeA.y1 > nodeB.y1) {
      // test if nodeA covers nodeB
      return true;
    } else {
      return false;
    }
  }

  // update a node, and its associated links, vertical positions (y0, y1)
  function adjustNodeHeight(node, dy, sankeyY0, sankeyY1) {
    if (node.y0 + dy >= sankeyY0 && node.y1 + dy <= sankeyY1) {
      node.y0 = node.y0 + dy;
      node.y1 = node.y1 + dy;

      node.targetLinks.forEach(function (l) {
        l.y1 = l.y1 + dy;
      });

      node.sourceLinks.forEach(function (l) {
        l.y0 = l.y0 + dy;
      });
    }
    return node;
  }

  // sort and set the links' y0 for each node
  function sortSourceLinks(graph, y1, id, moveNodes) {
    graph.nodes.forEach(function (node) {
      // move any nodes up which are off the bottom
      if (moveNodes && node.y + (node.y1 - node.y0) > y1) {
        node.y = node.y - (node.y + (node.y1 - node.y0) - y1);
      }

      var nodesSourceLinks = graph.links.filter(function (l) {
        return getNodeID(l.source, id) == getNodeID(node, id);
      });

      var nodeSourceLinksLength = nodesSourceLinks.length;

      // if more than 1 link then sort
      if (nodeSourceLinksLength > 1) {
        nodesSourceLinks.sort(function (link1, link2) {
          // if both are not circular...
          if (!link1.circular && !link2.circular) {
            // if the target nodes are the same column, then sort by the link's target y
            if (link1.target.column == link2.target.column) {
              return link1.y1 - link2.y1;
            } else if (!sameInclines(link1, link2)) {
              // if the links slope in different directions, then sort by the link's target y
              return link1.y1 - link2.y1;

              // if the links slope in same directions, then sort by any overlap
            } else {
              if (link1.target.column > link2.target.column) {
                var link2Adj = linkPerpendicularYToLinkTarget(link2, link1);
                return link1.y1 - link2Adj;
              }
              if (link2.target.column > link1.target.column) {
                var link1Adj = linkPerpendicularYToLinkTarget(link1, link2);
                return link1Adj - link2.y1;
              }
            }
          }

          // if only one is circular, the move top links up, or bottom links down
          if (link1.circular && !link2.circular) {
            return link1.circularLinkType == 'top' ? -1 : 1;
          } else if (link2.circular && !link1.circular) {
            return link2.circularLinkType == 'top' ? 1 : -1;
          }

          // if both links are circular...
          if (link1.circular && link2.circular) {
            // ...and they both loop the same way (both top)
            if (link1.circularLinkType === link2.circularLinkType && link1.circularLinkType == 'top') {
              // ...and they both connect to a target with same column, then sort by the target's y
              if (link1.target.column === link2.target.column) {
                return link1.target.y1 - link2.target.y1;
              } else {
                // ...and they connect to different column targets, then sort by how far back they
                return link2.target.column - link1.target.column;
              }
            } else if (link1.circularLinkType === link2.circularLinkType && link1.circularLinkType == 'bottom') {
              // ...and they both loop the same way (both bottom)
              // ...and they both connect to a target with same column, then sort by the target's y
              if (link1.target.column === link2.target.column) {
                return link2.target.y1 - link1.target.y1;
              } else {
                // ...and they connect to different column targets, then sort by how far back they
                return link1.target.column - link2.target.column;
              }
            } else {
              // ...and they loop around different ways, the move top up and bottom down
              return link1.circularLinkType == 'top' ? -1 : 1;
            }
          }
        });
      }

      // update y0 for links
      var ySourceOffset = node.y0;

      nodesSourceLinks.forEach(function (link) {
        link.y0 = ySourceOffset + link.width / 2;
        ySourceOffset = ySourceOffset + link.width;
      });

      // correct any circular bottom links so they are at the bottom of the node
      nodesSourceLinks.forEach(function (link, i) {
        if (link.circularLinkType == 'bottom') {
          var j = i + 1;
          var offsetFromBottom = 0;
          // sum the widths of any links that are below this link
          for (j; j < nodeSourceLinksLength; j++) {
            offsetFromBottom = offsetFromBottom + nodesSourceLinks[j].width;
          }
          link.y0 = node.y1 - offsetFromBottom - link.width / 2;
        }
      });
    });
  }

  // sort and set the links' y1 for each node
  function sortTargetLinks(graph, y1, id) {
    graph.nodes.forEach(function (node) {
      var nodesTargetLinks = graph.links.filter(function (l) {
        return getNodeID(l.target, id) == getNodeID(node, id);
      });

      var nodesTargetLinksLength = nodesTargetLinks.length;

      if (nodesTargetLinksLength > 1) {
        nodesTargetLinks.sort(function (link1, link2) {
          // if both are not circular, the base on the source y position
          if (!link1.circular && !link2.circular) {
            if (link1.source.column == link2.source.column) {
              return link1.y0 - link2.y0;
            } else if (!sameInclines(link1, link2)) {
              return link1.y0 - link2.y0;
            } else {
              // get the angle of the link to the further source node (ie the smaller column)
              if (link2.source.column < link1.source.column) {
                var link2Adj = linkPerpendicularYToLinkSource(link2, link1);

                return link1.y0 - link2Adj;
              }
              if (link1.source.column < link2.source.column) {
                var link1Adj = linkPerpendicularYToLinkSource(link1, link2);

                return link1Adj - link2.y0;
              }
            }
          }

          // if only one is circular, the move top links up, or bottom links down
          if (link1.circular && !link2.circular) {
            return link1.circularLinkType == 'top' ? -1 : 1;
          } else if (link2.circular && !link1.circular) {
            return link2.circularLinkType == 'top' ? 1 : -1;
          }

          // if both links are circular...
          if (link1.circular && link2.circular) {
            // ...and they both loop the same way (both top)
            if (link1.circularLinkType === link2.circularLinkType && link1.circularLinkType == 'top') {
              // ...and they both connect to a target with same column, then sort by the target's y
              if (link1.source.column === link2.source.column) {
                return link1.source.y1 - link2.source.y1;
              } else {
                // ...and they connect to different column targets, then sort by how far back they
                return link1.source.column - link2.source.column;
              }
            } else if (link1.circularLinkType === link2.circularLinkType && link1.circularLinkType == 'bottom') {
              // ...and they both loop the same way (both bottom)
              // ...and they both connect to a target with same column, then sort by the target's y
              if (link1.source.column === link2.source.column) {
                return link1.source.y1 - link2.source.y1;
              } else {
                // ...and they connect to different column targets, then sort by how far back they
                return link2.source.column - link1.source.column;
              }
            } else {
              // ...and they loop around different ways, the move top up and bottom down
              return link1.circularLinkType == 'top' ? -1 : 1;
            }
          }
        });
      }

      // update y1 for links
      var yTargetOffset = node.y0;

      nodesTargetLinks.forEach(function (link) {
        link.y1 = yTargetOffset + link.width / 2;
        yTargetOffset = yTargetOffset + link.width;
      });

      // correct any circular bottom links so they are at the bottom of the node
      nodesTargetLinks.forEach(function (link, i) {
        if (link.circularLinkType == 'bottom') {
          var j = i + 1;
          var offsetFromBottom = 0;
          // sum the widths of any links that are below this link
          for (j; j < nodesTargetLinksLength; j++) {
            offsetFromBottom = offsetFromBottom + nodesTargetLinks[j].width;
          }
          link.y1 = node.y1 - offsetFromBottom - link.width / 2;
        }
      });
    });
  }

  // test if links both slope up, or both slope down
  function sameInclines(link1, link2) {
    return incline(link1) == incline(link2);
  }

  // returns the slope of a link, from source to target
  // up => slopes up from source to target
  // down => slopes down from source to target
  function incline(link) {
    return link.y0 - link.y1 > 0 ? 'up' : 'down';
  }

  // check if link is self linking, ie links a node to the same node
  function selfLinking(link, id) {
    return getNodeID(link.source, id) == getNodeID(link.target, id);
  }

  function fillHeight(graph, y0, y1) {

    var nodes = graph.nodes;
    var links = graph.links;

    var top = false;
    var bottom = false;

    links.forEach(function (link) {
      if (link.circularLinkType == "top") {
        top = true;
      } else if (link.circularLinkType == "bottom") {
        bottom = true;
      }
    });

    if (top == false || bottom == false) {
      var minY0 = d3Array.min(nodes, function (node) {
        return node.y0;
      });
      var maxY1 = d3Array.max(nodes, function (node) {
        return node.y1;
      });
      var currentHeight = maxY1 - minY0;
      var chartHeight = y1 - y0;
      var ratio = chartHeight / currentHeight;

      nodes.forEach(function (node) {
        var nodeHeight = (node.y1 - node.y0) * ratio;
        node.y0 = (node.y0 - minY0) * ratio;
        node.y1 = node.y0 + nodeHeight;
      });

      links.forEach(function (link) {
        link.y0 = (link.y0 - minY0) * ratio;
        link.y1 = (link.y1 - minY0) * ratio;
        link.width = link.width * ratio;
      });
    }
  }

  exports.sankeyCircular = sankeyCircular;
  exports.sankeyCenter = center;
  exports.sankeyLeft = left;
  exports.sankeyRight = right;
  exports.sankeyJustify = justify;

  Object.defineProperty(exports, '__esModule', { value: true });

})));

},{"d3-array":140,"d3-collection":141,"d3-shape":149,"elementary-circuits-directed-graph":161}],149:[function(_dereq_,module,exports){
// https://d3js.org/d3-shape/ v1.3.4 Copyright 2019 Mike Bostock
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, _dereq_('d3-path')) :
typeof define === 'function' && define.amd ? define(['exports', 'd3-path'], factory) :
(factory((global.d3 = global.d3 || {}),global.d3));
}(this, (function (exports,d3Path) { 'use strict';

function constant(x) {
  return function constant() {
    return x;
  };
}

var abs = Math.abs;
var atan2 = Math.atan2;
var cos = Math.cos;
var max = Math.max;
var min = Math.min;
var sin = Math.sin;
var sqrt = Math.sqrt;

var epsilon = 1e-12;
var pi = Math.PI;
var halfPi = pi / 2;
var tau = 2 * pi;

function acos(x) {
  return x > 1 ? 0 : x < -1 ? pi : Math.acos(x);
}

function asin(x) {
  return x >= 1 ? halfPi : x <= -1 ? -halfPi : Math.asin(x);
}

function arcInnerRadius(d) {
  return d.innerRadius;
}

function arcOuterRadius(d) {
  return d.outerRadius;
}

function arcStartAngle(d) {
  return d.startAngle;
}

function arcEndAngle(d) {
  return d.endAngle;
}

function arcPadAngle(d) {
  return d && d.padAngle; // Note: optional!
}

function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
  var x10 = x1 - x0, y10 = y1 - y0,
      x32 = x3 - x2, y32 = y3 - y2,
      t = y32 * x10 - x32 * y10;
  if (t * t < epsilon) return;
  t = (x32 * (y0 - y2) - y32 * (x0 - x2)) / t;
  return [x0 + t * x10, y0 + t * y10];
}

// Compute perpendicular offset line of length rc.
// http://mathworld.wolfram.com/Circle-LineIntersection.html
function cornerTangents(x0, y0, x1, y1, r1, rc, cw) {
  var x01 = x0 - x1,
      y01 = y0 - y1,
      lo = (cw ? rc : -rc) / sqrt(x01 * x01 + y01 * y01),
      ox = lo * y01,
      oy = -lo * x01,
      x11 = x0 + ox,
      y11 = y0 + oy,
      x10 = x1 + ox,
      y10 = y1 + oy,
      x00 = (x11 + x10) / 2,
      y00 = (y11 + y10) / 2,
      dx = x10 - x11,
      dy = y10 - y11,
      d2 = dx * dx + dy * dy,
      r = r1 - rc,
      D = x11 * y10 - x10 * y11,
      d = (dy < 0 ? -1 : 1) * sqrt(max(0, r * r * d2 - D * D)),
      cx0 = (D * dy - dx * d) / d2,
      cy0 = (-D * dx - dy * d) / d2,
      cx1 = (D * dy + dx * d) / d2,
      cy1 = (-D * dx + dy * d) / d2,
      dx0 = cx0 - x00,
      dy0 = cy0 - y00,
      dx1 = cx1 - x00,
      dy1 = cy1 - y00;

  // Pick the closer of the two intersection points.
  // TODO Is there a faster way to determine which intersection to use?
  if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1;

  return {
    cx: cx0,
    cy: cy0,
    x01: -ox,
    y01: -oy,
    x11: cx0 * (r1 / r - 1),
    y11: cy0 * (r1 / r - 1)
  };
}

function arc() {
  var innerRadius = arcInnerRadius,
      outerRadius = arcOuterRadius,
      cornerRadius = constant(0),
      padRadius = null,
      startAngle = arcStartAngle,
      endAngle = arcEndAngle,
      padAngle = arcPadAngle,
      context = null;

  function arc() {
    var buffer,
        r,
        r0 = +innerRadius.apply(this, arguments),
        r1 = +outerRadius.apply(this, arguments),
        a0 = startAngle.apply(this, arguments) - halfPi,
        a1 = endAngle.apply(this, arguments) - halfPi,
        da = abs(a1 - a0),
        cw = a1 > a0;

    if (!context) context = buffer = d3Path.path();

    // Ensure that the outer radius is always larger than the inner radius.
    if (r1 < r0) r = r1, r1 = r0, r0 = r;

    // Is it a point?
    if (!(r1 > epsilon)) context.moveTo(0, 0);

    // Or is it a circle or annulus?
    else if (da > tau - epsilon) {
      context.moveTo(r1 * cos(a0), r1 * sin(a0));
      context.arc(0, 0, r1, a0, a1, !cw);
      if (r0 > epsilon) {
        context.moveTo(r0 * cos(a1), r0 * sin(a1));
        context.arc(0, 0, r0, a1, a0, cw);
      }
    }

    // Or is it a circular or annular sector?
    else {
      var a01 = a0,
          a11 = a1,
          a00 = a0,
          a10 = a1,
          da0 = da,
          da1 = da,
          ap = padAngle.apply(this, arguments) / 2,
          rp = (ap > epsilon) && (padRadius ? +padRadius.apply(this, arguments) : sqrt(r0 * r0 + r1 * r1)),
          rc = min(abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments)),
          rc0 = rc,
          rc1 = rc,
          t0,
          t1;

      // Apply padding? Note that since r1 ≥ r0, da1 ≥ da0.
      if (rp > epsilon) {
        var p0 = asin(rp / r0 * sin(ap)),
            p1 = asin(rp / r1 * sin(ap));
        if ((da0 -= p0 * 2) > epsilon) p0 *= (cw ? 1 : -1), a00 += p0, a10 -= p0;
        else da0 = 0, a00 = a10 = (a0 + a1) / 2;
        if ((da1 -= p1 * 2) > epsilon) p1 *= (cw ? 1 : -1), a01 += p1, a11 -= p1;
        else da1 = 0, a01 = a11 = (a0 + a1) / 2;
      }

      var x01 = r1 * cos(a01),
          y01 = r1 * sin(a01),
          x10 = r0 * cos(a10),
          y10 = r0 * sin(a10);

      // Apply rounded corners?
      if (rc > epsilon) {
        var x11 = r1 * cos(a11),
            y11 = r1 * sin(a11),
            x00 = r0 * cos(a00),
            y00 = r0 * sin(a00),
            oc;

        // Restrict the corner radius according to the sector angle.
        if (da < pi && (oc = intersect(x01, y01, x00, y00, x11, y11, x10, y10))) {
          var ax = x01 - oc[0],
              ay = y01 - oc[1],
              bx = x11 - oc[0],
              by = y11 - oc[1],
              kc = 1 / sin(acos((ax * bx + ay * by) / (sqrt(ax * ax + ay * ay) * sqrt(bx * bx + by * by))) / 2),
              lc = sqrt(oc[0] * oc[0] + oc[1] * oc[1]);
          rc0 = min(rc, (r0 - lc) / (kc - 1));
          rc1 = min(rc, (r1 - lc) / (kc + 1));
        }
      }

      // Is the sector collapsed to a line?
      if (!(da1 > epsilon)) context.moveTo(x01, y01);

      // Does the sector’s outer ring have rounded corners?
      else if (rc1 > epsilon) {
        t0 = cornerTangents(x00, y00, x01, y01, r1, rc1, cw);
        t1 = cornerTangents(x11, y11, x10, y10, r1, rc1, cw);

        context.moveTo(t0.cx + t0.x01, t0.cy + t0.y01);

        // Have the corners merged?
        if (rc1 < rc) context.arc(t0.cx, t0.cy, rc1, atan2(t0.y01, t0.x01), atan2(t1.y01, t1.x01), !cw);

        // Otherwise, draw the two corners and the ring.
        else {
          context.arc(t0.cx, t0.cy, rc1, atan2(t0.y01, t0.x01), atan2(t0.y11, t0.x11), !cw);
          context.arc(0, 0, r1, atan2(t0.cy + t0.y11, t0.cx + t0.x11), atan2(t1.cy + t1.y11, t1.cx + t1.x11), !cw);
          context.arc(t1.cx, t1.cy, rc1, atan2(t1.y11, t1.x11), atan2(t1.y01, t1.x01), !cw);
        }
      }

      // Or is the outer ring just a circular arc?
      else context.moveTo(x01, y01), context.arc(0, 0, r1, a01, a11, !cw);

      // Is there no inner ring, and it’s a circular sector?
      // Or perhaps it’s an annular sector collapsed due to padding?
      if (!(r0 > epsilon) || !(da0 > epsilon)) context.lineTo(x10, y10);

      // Does the sector’s inner ring (or point) have rounded corners?
      else if (rc0 > epsilon) {
        t0 = cornerTangents(x10, y10, x11, y11, r0, -rc0, cw);
        t1 = cornerTangents(x01, y01, x00, y00, r0, -rc0, cw);

        context.lineTo(t0.cx + t0.x01, t0.cy + t0.y01);

        // Have the corners merged?
        if (rc0 < rc) context.arc(t0.cx, t0.cy, rc0, atan2(t0.y01, t0.x01), atan2(t1.y01, t1.x01), !cw);

        // Otherwise, draw the two corners and the ring.
        else {
          context.arc(t0.cx, t0.cy, rc0, atan2(t0.y01, t0.x01), atan2(t0.y11, t0.x11), !cw);
          context.arc(0, 0, r0, atan2(t0.cy + t0.y11, t0.cx + t0.x11), atan2(t1.cy + t1.y11, t1.cx + t1.x11), cw);
          context.arc(t1.cx, t1.cy, rc0, atan2(t1.y11, t1.x11), atan2(t1.y01, t1.x01), !cw);
        }
      }

      // Or is the inner ring just a circular arc?
      else context.arc(0, 0, r0, a10, a00, cw);
    }

    context.closePath();

    if (buffer) return context = null, buffer + "" || null;
  }

  arc.centroid = function() {
    var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2,
        a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - pi / 2;
    return [cos(a) * r, sin(a) * r];
  };

  arc.innerRadius = function(_) {
    return arguments.length ? (innerRadius = typeof _ === "function" ? _ : constant(+_), arc) : innerRadius;
  };

  arc.outerRadius = function(_) {
    return arguments.length ? (outerRadius = typeof _ === "function" ? _ : constant(+_), arc) : outerRadius;
  };

  arc.cornerRadius = function(_) {
    return arguments.length ? (cornerRadius = typeof _ === "function" ? _ : constant(+_), arc) : cornerRadius;
  };

  arc.padRadius = function(_) {
    return arguments.length ? (padRadius = _ == null ? null : typeof _ === "function" ? _ : constant(+_), arc) : padRadius;
  };

  arc.startAngle = function(_) {
    return arguments.length ? (startAngle = typeof _ === "function" ? _ : constant(+_), arc) : startAngle;
  };

  arc.endAngle = function(_) {
    return arguments.length ? (endAngle = typeof _ === "function" ? _ : constant(+_), arc) : endAngle;
  };

  arc.padAngle = function(_) {
    return arguments.length ? (padAngle = typeof _ === "function" ? _ : constant(+_), arc) : padAngle;
  };

  arc.context = function(_) {
    return arguments.length ? ((context = _ == null ? null : _), arc) : context;
  };

  return arc;
}

function Linear(context) {
  this._context = context;
}

Linear.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._point = 0;
  },
  lineEnd: function() {
    if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x, y) {
    x = +x, y = +y;
    switch (this._point) {
      case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
      case 1: this._point = 2; // proceed
      default: this._context.lineTo(x, y); break;
    }
  }
};

function curveLinear(context) {
  return new Linear(context);
}

function x(p) {
  return p[0];
}

function y(p) {
  return p[1];
}

function line() {
  var x$$1 = x,
      y$$1 = y,
      defined = constant(true),
      context = null,
      curve = curveLinear,
      output = null;

  function line(data) {
    var i,
        n = data.length,
        d,
        defined0 = false,
        buffer;

    if (context == null) output = curve(buffer = d3Path.path());

    for (i = 0; i <= n; ++i) {
      if (!(i < n && defined(d = data[i], i, data)) === defined0) {
        if (defined0 = !defined0) output.lineStart();
        else output.lineEnd();
      }
      if (defined0) output.point(+x$$1(d, i, data), +y$$1(d, i, data));
    }

    if (buffer) return output = null, buffer + "" || null;
  }

  line.x = function(_) {
    return arguments.length ? (x$$1 = typeof _ === "function" ? _ : constant(+_), line) : x$$1;
  };

  line.y = function(_) {
    return arguments.length ? (y$$1 = typeof _ === "function" ? _ : constant(+_), line) : y$$1;
  };

  line.defined = function(_) {
    return arguments.length ? (defined = typeof _ === "function" ? _ : constant(!!_), line) : defined;
  };

  line.curve = function(_) {
    return arguments.length ? (curve = _, context != null && (output = curve(context)), line) : curve;
  };

  line.context = function(_) {
    return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), line) : context;
  };

  return line;
}

function area() {
  var x0 = x,
      x1 = null,
      y0 = constant(0),
      y1 = y,
      defined = constant(true),
      context = null,
      curve = curveLinear,
      output = null;

  function area(data) {
    var i,
        j,
        k,
        n = data.length,
        d,
        defined0 = false,
        buffer,
        x0z = new Array(n),
        y0z = new Array(n);

    if (context == null) output = curve(buffer = d3Path.path());

    for (i = 0; i <= n; ++i) {
      if (!(i < n && defined(d = data[i], i, data)) === defined0) {
        if (defined0 = !defined0) {
          j = i;
          output.areaStart();
          output.lineStart();
        } else {
          output.lineEnd();
          output.lineStart();
          for (k = i - 1; k >= j; --k) {
            output.point(x0z[k], y0z[k]);
          }
          output.lineEnd();
          output.areaEnd();
        }
      }
      if (defined0) {
        x0z[i] = +x0(d, i, data), y0z[i] = +y0(d, i, data);
        output.point(x1 ? +x1(d, i, data) : x0z[i], y1 ? +y1(d, i, data) : y0z[i]);
      }
    }

    if (buffer) return output = null, buffer + "" || null;
  }

  function arealine() {
    return line().defined(defined).curve(curve).context(context);
  }

  area.x = function(_) {
    return arguments.length ? (x0 = typeof _ === "function" ? _ : constant(+_), x1 = null, area) : x0;
  };

  area.x0 = function(_) {
    return arguments.length ? (x0 = typeof _ === "function" ? _ : constant(+_), area) : x0;
  };

  area.x1 = function(_) {
    return arguments.length ? (x1 = _ == null ? null : typeof _ === "function" ? _ : constant(+_), area) : x1;
  };

  area.y = function(_) {
    return arguments.length ? (y0 = typeof _ === "function" ? _ : constant(+_), y1 = null, area) : y0;
  };

  area.y0 = function(_) {
    return arguments.length ? (y0 = typeof _ === "function" ? _ : constant(+_), area) : y0;
  };

  area.y1 = function(_) {
    return arguments.length ? (y1 = _ == null ? null : typeof _ === "function" ? _ : constant(+_), area) : y1;
  };

  area.lineX0 =
  area.lineY0 = function() {
    return arealine().x(x0).y(y0);
  };

  area.lineY1 = function() {
    return arealine().x(x0).y(y1);
  };

  area.lineX1 = function() {
    return arealine().x(x1).y(y0);
  };

  area.defined = function(_) {
    return arguments.length ? (defined = typeof _ === "function" ? _ : constant(!!_), area) : defined;
  };

  area.curve = function(_) {
    return arguments.length ? (curve = _, context != null && (output = curve(context)), area) : curve;
  };

  area.context = function(_) {
    return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), area) : context;
  };

  return area;
}

function descending(a, b) {
  return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
}

function identity(d) {
  return d;
}

function pie() {
  var value = identity,
      sortValues = descending,
      sort = null,
      startAngle = constant(0),
      endAngle = constant(tau),
      padAngle = constant(0);

  function pie(data) {
    var i,
        n = data.length,
        j,
        k,
        sum = 0,
        index = new Array(n),
        arcs = new Array(n),
        a0 = +startAngle.apply(this, arguments),
        da = Math.min(tau, Math.max(-tau, endAngle.apply(this, arguments) - a0)),
        a1,
        p = Math.min(Math.abs(da) / n, padAngle.apply(this, arguments)),
        pa = p * (da < 0 ? -1 : 1),
        v;

    for (i = 0; i < n; ++i) {
      if ((v = arcs[index[i] = i] = +value(data[i], i, data)) > 0) {
        sum += v;
      }
    }

    // Optionally sort the arcs by previously-computed values or by data.
    if (sortValues != null) index.sort(function(i, j) { return sortValues(arcs[i], arcs[j]); });
    else if (sort != null) index.sort(function(i, j) { return sort(data[i], data[j]); });

    // Compute the arcs! They are stored in the original data's order.
    for (i = 0, k = sum ? (da - n * pa) / sum : 0; i < n; ++i, a0 = a1) {
      j = index[i], v = arcs[j], a1 = a0 + (v > 0 ? v * k : 0) + pa, arcs[j] = {
        data: data[j],
        index: i,
        value: v,
        startAngle: a0,
        endAngle: a1,
        padAngle: p
      };
    }

    return arcs;
  }

  pie.value = function(_) {
    return arguments.length ? (value = typeof _ === "function" ? _ : constant(+_), pie) : value;
  };

  pie.sortValues = function(_) {
    return arguments.length ? (sortValues = _, sort = null, pie) : sortValues;
  };

  pie.sort = function(_) {
    return arguments.length ? (sort = _, sortValues = null, pie) : sort;
  };

  pie.startAngle = function(_) {
    return arguments.length ? (startAngle = typeof _ === "function" ? _ : constant(+_), pie) : startAngle;
  };

  pie.endAngle = function(_) {
    return arguments.length ? (endAngle = typeof _ === "function" ? _ : constant(+_), pie) : endAngle;
  };

  pie.padAngle = function(_) {
    return arguments.length ? (padAngle = typeof _ === "function" ? _ : constant(+_), pie) : padAngle;
  };

  return pie;
}

var curveRadialLinear = curveRadial(curveLinear);

function Radial(curve) {
  this._curve = curve;
}

Radial.prototype = {
  areaStart: function() {
    this._curve.areaStart();
  },
  areaEnd: function() {
    this._curve.areaEnd();
  },
  lineStart: function() {
    this._curve.lineStart();
  },
  lineEnd: function() {
    this._curve.lineEnd();
  },
  point: function(a, r) {
    this._curve.point(r * Math.sin(a), r * -Math.cos(a));
  }
};

function curveRadial(curve) {

  function radial(context) {
    return new Radial(curve(context));
  }

  radial._curve = curve;

  return radial;
}

function lineRadial(l) {
  var c = l.curve;

  l.angle = l.x, delete l.x;
  l.radius = l.y, delete l.y;

  l.curve = function(_) {
    return arguments.length ? c(curveRadial(_)) : c()._curve;
  };

  return l;
}

function lineRadial$1() {
  return lineRadial(line().curve(curveRadialLinear));
}

function areaRadial() {
  var a = area().curve(curveRadialLinear),
      c = a.curve,
      x0 = a.lineX0,
      x1 = a.lineX1,
      y0 = a.lineY0,
      y1 = a.lineY1;

  a.angle = a.x, delete a.x;
  a.startAngle = a.x0, delete a.x0;
  a.endAngle = a.x1, delete a.x1;
  a.radius = a.y, delete a.y;
  a.innerRadius = a.y0, delete a.y0;
  a.outerRadius = a.y1, delete a.y1;
  a.lineStartAngle = function() { return lineRadial(x0()); }, delete a.lineX0;
  a.lineEndAngle = function() { return lineRadial(x1()); }, delete a.lineX1;
  a.lineInnerRadius = function() { return lineRadial(y0()); }, delete a.lineY0;
  a.lineOuterRadius = function() { return lineRadial(y1()); }, delete a.lineY1;

  a.curve = function(_) {
    return arguments.length ? c(curveRadial(_)) : c()._curve;
  };

  return a;
}

function pointRadial(x, y) {
  return [(y = +y) * Math.cos(x -= Math.PI / 2), y * Math.sin(x)];
}

var slice = Array.prototype.slice;

function linkSource(d) {
  return d.source;
}

function linkTarget(d) {
  return d.target;
}

function link(curve) {
  var source = linkSource,
      target = linkTarget,
      x$$1 = x,
      y$$1 = y,
      context = null;

  function link() {
    var buffer, argv = slice.call(arguments), s = source.apply(this, argv), t = target.apply(this, argv);
    if (!context) context = buffer = d3Path.path();
    curve(context, +x$$1.apply(this, (argv[0] = s, argv)), +y$$1.apply(this, argv), +x$$1.apply(this, (argv[0] = t, argv)), +y$$1.apply(this, argv));
    if (buffer) return context = null, buffer + "" || null;
  }

  link.source = function(_) {
    return arguments.length ? (source = _, link) : source;
  };

  link.target = function(_) {
    return arguments.length ? (target = _, link) : target;
  };

  link.x = function(_) {
    return arguments.length ? (x$$1 = typeof _ === "function" ? _ : constant(+_), link) : x$$1;
  };

  link.y = function(_) {
    return arguments.length ? (y$$1 = typeof _ === "function" ? _ : constant(+_), link) : y$$1;
  };

  link.context = function(_) {
    return arguments.length ? ((context = _ == null ? null : _), link) : context;
  };

  return link;
}

function curveHorizontal(context, x0, y0, x1, y1) {
  context.moveTo(x0, y0);
  context.bezierCurveTo(x0 = (x0 + x1) / 2, y0, x0, y1, x1, y1);
}

function curveVertical(context, x0, y0, x1, y1) {
  context.moveTo(x0, y0);
  context.bezierCurveTo(x0, y0 = (y0 + y1) / 2, x1, y0, x1, y1);
}

function curveRadial$1(context, x0, y0, x1, y1) {
  var p0 = pointRadial(x0, y0),
      p1 = pointRadial(x0, y0 = (y0 + y1) / 2),
      p2 = pointRadial(x1, y0),
      p3 = pointRadial(x1, y1);
  context.moveTo(p0[0], p0[1]);
  context.bezierCurveTo(p1[0], p1[1], p2[0], p2[1], p3[0], p3[1]);
}

function linkHorizontal() {
  return link(curveHorizontal);
}

function linkVertical() {
  return link(curveVertical);
}

function linkRadial() {
  var l = link(curveRadial$1);
  l.angle = l.x, delete l.x;
  l.radius = l.y, delete l.y;
  return l;
}

var circle = {
  draw: function(context, size) {
    var r = Math.sqrt(size / pi);
    context.moveTo(r, 0);
    context.arc(0, 0, r, 0, tau);
  }
};

var cross = {
  draw: function(context, size) {
    var r = Math.sqrt(size / 5) / 2;
    context.moveTo(-3 * r, -r);
    context.lineTo(-r, -r);
    context.lineTo(-r, -3 * r);
    context.lineTo(r, -3 * r);
    context.lineTo(r, -r);
    context.lineTo(3 * r, -r);
    context.lineTo(3 * r, r);
    context.lineTo(r, r);
    context.lineTo(r, 3 * r);
    context.lineTo(-r, 3 * r);
    context.lineTo(-r, r);
    context.lineTo(-3 * r, r);
    context.closePath();
  }
};

var tan30 = Math.sqrt(1 / 3),
    tan30_2 = tan30 * 2;

var diamond = {
  draw: function(context, size) {
    var y = Math.sqrt(size / tan30_2),
        x = y * tan30;
    context.moveTo(0, -y);
    context.lineTo(x, 0);
    context.lineTo(0, y);
    context.lineTo(-x, 0);
    context.closePath();
  }
};

var ka = 0.89081309152928522810,
    kr = Math.sin(pi / 10) / Math.sin(7 * pi / 10),
    kx = Math.sin(tau / 10) * kr,
    ky = -Math.cos(tau / 10) * kr;

var star = {
  draw: function(context, size) {
    var r = Math.sqrt(size * ka),
        x = kx * r,
        y = ky * r;
    context.moveTo(0, -r);
    context.lineTo(x, y);
    for (var i = 1; i < 5; ++i) {
      var a = tau * i / 5,
          c = Math.cos(a),
          s = Math.sin(a);
      context.lineTo(s * r, -c * r);
      context.lineTo(c * x - s * y, s * x + c * y);
    }
    context.closePath();
  }
};

var square = {
  draw: function(context, size) {
    var w = Math.sqrt(size),
        x = -w / 2;
    context.rect(x, x, w, w);
  }
};

var sqrt3 = Math.sqrt(3);

var triangle = {
  draw: function(context, size) {
    var y = -Math.sqrt(size / (sqrt3 * 3));
    context.moveTo(0, y * 2);
    context.lineTo(-sqrt3 * y, -y);
    context.lineTo(sqrt3 * y, -y);
    context.closePath();
  }
};

var c = -0.5,
    s = Math.sqrt(3) / 2,
    k = 1 / Math.sqrt(12),
    a = (k / 2 + 1) * 3;

var wye = {
  draw: function(context, size) {
    var r = Math.sqrt(size / a),
        x0 = r / 2,
        y0 = r * k,
        x1 = x0,
        y1 = r * k + r,
        x2 = -x1,
        y2 = y1;
    context.moveTo(x0, y0);
    context.lineTo(x1, y1);
    context.lineTo(x2, y2);
    context.lineTo(c * x0 - s * y0, s * x0 + c * y0);
    context.lineTo(c * x1 - s * y1, s * x1 + c * y1);
    context.lineTo(c * x2 - s * y2, s * x2 + c * y2);
    context.lineTo(c * x0 + s * y0, c * y0 - s * x0);
    context.lineTo(c * x1 + s * y1, c * y1 - s * x1);
    context.lineTo(c * x2 + s * y2, c * y2 - s * x2);
    context.closePath();
  }
};

var symbols = [
  circle,
  cross,
  diamond,
  square,
  star,
  triangle,
  wye
];

function symbol() {
  var type = constant(circle),
      size = constant(64),
      context = null;

  function symbol() {
    var buffer;
    if (!context) context = buffer = d3Path.path();
    type.apply(this, arguments).draw(context, +size.apply(this, arguments));
    if (buffer) return context = null, buffer + "" || null;
  }

  symbol.type = function(_) {
    return arguments.length ? (type = typeof _ === "function" ? _ : constant(_), symbol) : type;
  };

  symbol.size = function(_) {
    return arguments.length ? (size = typeof _ === "function" ? _ : constant(+_), symbol) : size;
  };

  symbol.context = function(_) {
    return arguments.length ? (context = _ == null ? null : _, symbol) : context;
  };

  return symbol;
}

function noop() {}

function point(that, x, y) {
  that._context.bezierCurveTo(
    (2 * that._x0 + that._x1) / 3,
    (2 * that._y0 + that._y1) / 3,
    (that._x0 + 2 * that._x1) / 3,
    (that._y0 + 2 * that._y1) / 3,
    (that._x0 + 4 * that._x1 + x) / 6,
    (that._y0 + 4 * that._y1 + y) / 6
  );
}

function Basis(context) {
  this._context = context;
}

Basis.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 =
    this._y0 = this._y1 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 3: point(this, this._x1, this._y1); // proceed
      case 2: this._context.lineTo(this._x1, this._y1); break;
    }
    if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x, y) {
    x = +x, y = +y;
    switch (this._point) {
      case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
      case 1: this._point = 2; break;
      case 2: this._point = 3; this._context.lineTo((5 * this._x0 + this._x1) / 6, (5 * this._y0 + this._y1) / 6); // proceed
      default: point(this, x, y); break;
    }
    this._x0 = this._x1, this._x1 = x;
    this._y0 = this._y1, this._y1 = y;
  }
};

function basis(context) {
  return new Basis(context);
}

function BasisClosed(context) {
  this._context = context;
}

BasisClosed.prototype = {
  areaStart: noop,
  areaEnd: noop,
  lineStart: function() {
    this._x0 = this._x1 = this._x2 = this._x3 = this._x4 =
    this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 1: {
        this._context.moveTo(this._x2, this._y2);
        this._context.closePath();
        break;
      }
      case 2: {
        this._context.moveTo((this._x2 + 2 * this._x3) / 3, (this._y2 + 2 * this._y3) / 3);
        this._context.lineTo((this._x3 + 2 * this._x2) / 3, (this._y3 + 2 * this._y2) / 3);
        this._context.closePath();
        break;
      }
      case 3: {
        this.point(this._x2, this._y2);
        this.point(this._x3, this._y3);
        this.point(this._x4, this._y4);
        break;
      }
    }
  },
  point: function(x, y) {
    x = +x, y = +y;
    switch (this._point) {
      case 0: this._point = 1; this._x2 = x, this._y2 = y; break;
      case 1: this._point = 2; this._x3 = x, this._y3 = y; break;
      case 2: this._point = 3; this._x4 = x, this._y4 = y; this._context.moveTo((this._x0 + 4 * this._x1 + x) / 6, (this._y0 + 4 * this._y1 + y) / 6); break;
      default: point(this, x, y); break;
    }
    this._x0 = this._x1, this._x1 = x;
    this._y0 = this._y1, this._y1 = y;
  }
};

function basisClosed(context) {
  return new BasisClosed(context);
}

function BasisOpen(context) {
  this._context = context;
}

BasisOpen.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 =
    this._y0 = this._y1 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    if (this._line || (this._line !== 0 && this._point === 3)) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x, y) {
    x = +x, y = +y;
    switch (this._point) {
      case 0: this._point = 1; break;
      case 1: this._point = 2; break;
      case 2: this._point = 3; var x0 = (this._x0 + 4 * this._x1 + x) / 6, y0 = (this._y0 + 4 * this._y1 + y) / 6; this._line ? this._context.lineTo(x0, y0) : this._context.moveTo(x0, y0); break;
      case 3: this._point = 4; // proceed
      default: point(this, x, y); break;
    }
    this._x0 = this._x1, this._x1 = x;
    this._y0 = this._y1, this._y1 = y;
  }
};

function basisOpen(context) {
  return new BasisOpen(context);
}

function Bundle(context, beta) {
  this._basis = new Basis(context);
  this._beta = beta;
}

Bundle.prototype = {
  lineStart: function() {
    this._x = [];
    this._y = [];
    this._basis.lineStart();
  },
  lineEnd: function() {
    var x = this._x,
        y = this._y,
        j = x.length - 1;

    if (j > 0) {
      var x0 = x[0],
          y0 = y[0],
          dx = x[j] - x0,
          dy = y[j] - y0,
          i = -1,
          t;

      while (++i <= j) {
        t = i / j;
        this._basis.point(
          this._beta * x[i] + (1 - this._beta) * (x0 + t * dx),
          this._beta * y[i] + (1 - this._beta) * (y0 + t * dy)
        );
      }
    }

    this._x = this._y = null;
    this._basis.lineEnd();
  },
  point: function(x, y) {
    this._x.push(+x);
    this._y.push(+y);
  }
};

var bundle = (function custom(beta) {

  function bundle(context) {
    return beta === 1 ? new Basis(context) : new Bundle(context, beta);
  }

  bundle.beta = function(beta) {
    return custom(+beta);
  };

  return bundle;
})(0.85);

function point$1(that, x, y) {
  that._context.bezierCurveTo(
    that._x1 + that._k * (that._x2 - that._x0),
    that._y1 + that._k * (that._y2 - that._y0),
    that._x2 + that._k * (that._x1 - x),
    that._y2 + that._k * (that._y1 - y),
    that._x2,
    that._y2
  );
}

function Cardinal(context, tension) {
  this._context = context;
  this._k = (1 - tension) / 6;
}

Cardinal.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 = this._x2 =
    this._y0 = this._y1 = this._y2 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 2: this._context.lineTo(this._x2, this._y2); break;
      case 3: point$1(this, this._x1, this._y1); break;
    }
    if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x, y) {
    x = +x, y = +y;
    switch (this._point) {
      case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
      case 1: this._point = 2; this._x1 = x, this._y1 = y; break;
      case 2: this._point = 3; // proceed
      default: point$1(this, x, y); break;
    }
    this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
    this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
  }
};

var cardinal = (function custom(tension) {

  function cardinal(context) {
    return new Cardinal(context, tension);
  }

  cardinal.tension = function(tension) {
    return custom(+tension);
  };

  return cardinal;
})(0);

function CardinalClosed(context, tension) {
  this._context = context;
  this._k = (1 - tension) / 6;
}

CardinalClosed.prototype = {
  areaStart: noop,
  areaEnd: noop,
  lineStart: function() {
    this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._x5 =
    this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = this._y5 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 1: {
        this._context.moveTo(this._x3, this._y3);
        this._context.closePath();
        break;
      }
      case 2: {
        this._context.lineTo(this._x3, this._y3);
        this._context.closePath();
        break;
      }
      case 3: {
        this.point(this._x3, this._y3);
        this.point(this._x4, this._y4);
        this.point(this._x5, this._y5);
        break;
      }
    }
  },
  point: function(x, y) {
    x = +x, y = +y;
    switch (this._point) {
      case 0: this._point = 1; this._x3 = x, this._y3 = y; break;
      case 1: this._point = 2; this._context.moveTo(this._x4 = x, this._y4 = y); break;
      case 2: this._point = 3; this._x5 = x, this._y5 = y; break;
      default: point$1(this, x, y); break;
    }
    this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
    this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
  }
};

var cardinalClosed = (function custom(tension) {

  function cardinal$$1(context) {
    return new CardinalClosed(context, tension);
  }

  cardinal$$1.tension = function(tension) {
    return custom(+tension);
  };

  return cardinal$$1;
})(0);

function CardinalOpen(context, tension) {
  this._context = context;
  this._k = (1 - tension) / 6;
}

CardinalOpen.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 = this._x2 =
    this._y0 = this._y1 = this._y2 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    if (this._line || (this._line !== 0 && this._point === 3)) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x, y) {
    x = +x, y = +y;
    switch (this._point) {
      case 0: this._point = 1; break;
      case 1: this._point = 2; break;
      case 2: this._point = 3; this._line ? this._context.lineTo(this._x2, this._y2) : this._context.moveTo(this._x2, this._y2); break;
      case 3: this._point = 4; // proceed
      default: point$1(this, x, y); break;
    }
    this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
    this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
  }
};

var cardinalOpen = (function custom(tension) {

  function cardinal$$1(context) {
    return new CardinalOpen(context, tension);
  }

  cardinal$$1.tension = function(tension) {
    return custom(+tension);
  };

  return cardinal$$1;
})(0);

function point$2(that, x, y) {
  var x1 = that._x1,
      y1 = that._y1,
      x2 = that._x2,
      y2 = that._y2;

  if (that._l01_a > epsilon) {
    var a = 2 * that._l01_2a + 3 * that._l01_a * that._l12_a + that._l12_2a,
        n = 3 * that._l01_a * (that._l01_a + that._l12_a);
    x1 = (x1 * a - that._x0 * that._l12_2a + that._x2 * that._l01_2a) / n;
    y1 = (y1 * a - that._y0 * that._l12_2a + that._y2 * that._l01_2a) / n;
  }

  if (that._l23_a > epsilon) {
    var b = 2 * that._l23_2a + 3 * that._l23_a * that._l12_a + that._l12_2a,
        m = 3 * that._l23_a * (that._l23_a + that._l12_a);
    x2 = (x2 * b + that._x1 * that._l23_2a - x * that._l12_2a) / m;
    y2 = (y2 * b + that._y1 * that._l23_2a - y * that._l12_2a) / m;
  }

  that._context.bezierCurveTo(x1, y1, x2, y2, that._x2, that._y2);
}

function CatmullRom(context, alpha) {
  this._context = context;
  this._alpha = alpha;
}

CatmullRom.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 = this._x2 =
    this._y0 = this._y1 = this._y2 = NaN;
    this._l01_a = this._l12_a = this._l23_a =
    this._l01_2a = this._l12_2a = this._l23_2a =
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 2: this._context.lineTo(this._x2, this._y2); break;
      case 3: this.point(this._x2, this._y2); break;
    }
    if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x, y) {
    x = +x, y = +y;

    if (this._point) {
      var x23 = this._x2 - x,
          y23 = this._y2 - y;
      this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));
    }

    switch (this._point) {
      case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
      case 1: this._point = 2; break;
      case 2: this._point = 3; // proceed
      default: point$2(this, x, y); break;
    }

    this._l01_a = this._l12_a, this._l12_a = this._l23_a;
    this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;
    this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
    this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
  }
};

var catmullRom = (function custom(alpha) {

  function catmullRom(context) {
    return alpha ? new CatmullRom(context, alpha) : new Cardinal(context, 0);
  }

  catmullRom.alpha = function(alpha) {
    return custom(+alpha);
  };

  return catmullRom;
})(0.5);

function CatmullRomClosed(context, alpha) {
  this._context = context;
  this._alpha = alpha;
}

CatmullRomClosed.prototype = {
  areaStart: noop,
  areaEnd: noop,
  lineStart: function() {
    this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._x5 =
    this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = this._y5 = NaN;
    this._l01_a = this._l12_a = this._l23_a =
    this._l01_2a = this._l12_2a = this._l23_2a =
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 1: {
        this._context.moveTo(this._x3, this._y3);
        this._context.closePath();
        break;
      }
      case 2: {
        this._context.lineTo(this._x3, this._y3);
        this._context.closePath();
        break;
      }
      case 3: {
        this.point(this._x3, this._y3);
        this.point(this._x4, this._y4);
        this.point(this._x5, this._y5);
        break;
      }
    }
  },
  point: function(x, y) {
    x = +x, y = +y;

    if (this._point) {
      var x23 = this._x2 - x,
          y23 = this._y2 - y;
      this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));
    }

    switch (this._point) {
      case 0: this._point = 1; this._x3 = x, this._y3 = y; break;
      case 1: this._point = 2; this._context.moveTo(this._x4 = x, this._y4 = y); break;
      case 2: this._point = 3; this._x5 = x, this._y5 = y; break;
      default: point$2(this, x, y); break;
    }

    this._l01_a = this._l12_a, this._l12_a = this._l23_a;
    this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;
    this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
    this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
  }
};

var catmullRomClosed = (function custom(alpha) {

  function catmullRom$$1(context) {
    return alpha ? new CatmullRomClosed(context, alpha) : new CardinalClosed(context, 0);
  }

  catmullRom$$1.alpha = function(alpha) {
    return custom(+alpha);
  };

  return catmullRom$$1;
})(0.5);

function CatmullRomOpen(context, alpha) {
  this._context = context;
  this._alpha = alpha;
}

CatmullRomOpen.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 = this._x2 =
    this._y0 = this._y1 = this._y2 = NaN;
    this._l01_a = this._l12_a = this._l23_a =
    this._l01_2a = this._l12_2a = this._l23_2a =
    this._point = 0;
  },
  lineEnd: function() {
    if (this._line || (this._line !== 0 && this._point === 3)) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x, y) {
    x = +x, y = +y;

    if (this._point) {
      var x23 = this._x2 - x,
          y23 = this._y2 - y;
      this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));
    }

    switch (this._point) {
      case 0: this._point = 1; break;
      case 1: this._point = 2; break;
      case 2: this._point = 3; this._line ? this._context.lineTo(this._x2, this._y2) : this._context.moveTo(this._x2, this._y2); break;
      case 3: this._point = 4; // proceed
      default: point$2(this, x, y); break;
    }

    this._l01_a = this._l12_a, this._l12_a = this._l23_a;
    this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;
    this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
    this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
  }
};

var catmullRomOpen = (function custom(alpha) {

  function catmullRom$$1(context) {
    return alpha ? new CatmullRomOpen(context, alpha) : new CardinalOpen(context, 0);
  }

  catmullRom$$1.alpha = function(alpha) {
    return custom(+alpha);
  };

  return catmullRom$$1;
})(0.5);

function LinearClosed(context) {
  this._context = context;
}

LinearClosed.prototype = {
  areaStart: noop,
  areaEnd: noop,
  lineStart: function() {
    this._point = 0;
  },
  lineEnd: function() {
    if (this._point) this._context.closePath();
  },
  point: function(x, y) {
    x = +x, y = +y;
    if (this._point) this._context.lineTo(x, y);
    else this._point = 1, this._context.moveTo(x, y);
  }
};

function linearClosed(context) {
  return new LinearClosed(context);
}

function sign(x) {
  return x < 0 ? -1 : 1;
}

// Calculate the slopes of the tangents (Hermite-type interpolation) based on
// the following paper: Steffen, M. 1990. A Simple Method for Monotonic
// Interpolation in One Dimension. Astronomy and Astrophysics, Vol. 239, NO.
// NOV(II), P. 443, 1990.
function slope3(that, x2, y2) {
  var h0 = that._x1 - that._x0,
      h1 = x2 - that._x1,
      s0 = (that._y1 - that._y0) / (h0 || h1 < 0 && -0),
      s1 = (y2 - that._y1) / (h1 || h0 < 0 && -0),
      p = (s0 * h1 + s1 * h0) / (h0 + h1);
  return (sign(s0) + sign(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p)) || 0;
}

// Calculate a one-sided slope.
function slope2(that, t) {
  var h = that._x1 - that._x0;
  return h ? (3 * (that._y1 - that._y0) / h - t) / 2 : t;
}

// According to https://en.wikipedia.org/wiki/Cubic_Hermite_spline#Representations
// "you can express cubic Hermite interpolation in terms of cubic Bézier curves
// with respect to the four values p0, p0 + m0 / 3, p1 - m1 / 3, p1".
function point$3(that, t0, t1) {
  var x0 = that._x0,
      y0 = that._y0,
      x1 = that._x1,
      y1 = that._y1,
      dx = (x1 - x0) / 3;
  that._context.bezierCurveTo(x0 + dx, y0 + dx * t0, x1 - dx, y1 - dx * t1, x1, y1);
}

function MonotoneX(context) {
  this._context = context;
}

MonotoneX.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 =
    this._y0 = this._y1 =
    this._t0 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 2: this._context.lineTo(this._x1, this._y1); break;
      case 3: point$3(this, this._t0, slope2(this, this._t0)); break;
    }
    if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x, y) {
    var t1 = NaN;

    x = +x, y = +y;
    if (x === this._x1 && y === this._y1) return; // Ignore coincident points.
    switch (this._point) {
      case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
      case 1: this._point = 2; break;
      case 2: this._point = 3; point$3(this, slope2(this, t1 = slope3(this, x, y)), t1); break;
      default: point$3(this, this._t0, t1 = slope3(this, x, y)); break;
    }

    this._x0 = this._x1, this._x1 = x;
    this._y0 = this._y1, this._y1 = y;
    this._t0 = t1;
  }
};

function MonotoneY(context) {
  this._context = new ReflectContext(context);
}

(MonotoneY.prototype = Object.create(MonotoneX.prototype)).point = function(x, y) {
  MonotoneX.prototype.point.call(this, y, x);
};

function ReflectContext(context) {
  this._context = context;
}

ReflectContext.prototype = {
  moveTo: function(x, y) { this._context.moveTo(y, x); },
  closePath: function() { this._context.closePath(); },
  lineTo: function(x, y) { this._context.lineTo(y, x); },
  bezierCurveTo: function(x1, y1, x2, y2, x, y) { this._context.bezierCurveTo(y1, x1, y2, x2, y, x); }
};

function monotoneX(context) {
  return new MonotoneX(context);
}

function monotoneY(context) {
  return new MonotoneY(context);
}

function Natural(context) {
  this._context = context;
}

Natural.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x = [];
    this._y = [];
  },
  lineEnd: function() {
    var x = this._x,
        y = this._y,
        n = x.length;

    if (n) {
      this._line ? this._context.lineTo(x[0], y[0]) : this._context.moveTo(x[0], y[0]);
      if (n === 2) {
        this._context.lineTo(x[1], y[1]);
      } else {
        var px = controlPoints(x),
            py = controlPoints(y);
        for (var i0 = 0, i1 = 1; i1 < n; ++i0, ++i1) {
          this._context.bezierCurveTo(px[0][i0], py[0][i0], px[1][i0], py[1][i0], x[i1], y[i1]);
        }
      }
    }

    if (this._line || (this._line !== 0 && n === 1)) this._context.closePath();
    this._line = 1 - this._line;
    this._x = this._y = null;
  },
  point: function(x, y) {
    this._x.push(+x);
    this._y.push(+y);
  }
};

// See https://www.particleincell.com/2012/bezier-splines/ for derivation.
function controlPoints(x) {
  var i,
      n = x.length - 1,
      m,
      a = new Array(n),
      b = new Array(n),
      r = new Array(n);
  a[0] = 0, b[0] = 2, r[0] = x[0] + 2 * x[1];
  for (i = 1; i < n - 1; ++i) a[i] = 1, b[i] = 4, r[i] = 4 * x[i] + 2 * x[i + 1];
  a[n - 1] = 2, b[n - 1] = 7, r[n - 1] = 8 * x[n - 1] + x[n];
  for (i = 1; i < n; ++i) m = a[i] / b[i - 1], b[i] -= m, r[i] -= m * r[i - 1];
  a[n - 1] = r[n - 1] / b[n - 1];
  for (i = n - 2; i >= 0; --i) a[i] = (r[i] - a[i + 1]) / b[i];
  b[n - 1] = (x[n] + a[n - 1]) / 2;
  for (i = 0; i < n - 1; ++i) b[i] = 2 * x[i + 1] - a[i + 1];
  return [a, b];
}

function natural(context) {
  return new Natural(context);
}

function Step(context, t) {
  this._context = context;
  this._t = t;
}

Step.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x = this._y = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    if (0 < this._t && this._t < 1 && this._point === 2) this._context.lineTo(this._x, this._y);
    if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
    if (this._line >= 0) this._t = 1 - this._t, this._line = 1 - this._line;
  },
  point: function(x, y) {
    x = +x, y = +y;
    switch (this._point) {
      case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
      case 1: this._point = 2; // proceed
      default: {
        if (this._t <= 0) {
          this._context.lineTo(this._x, y);
          this._context.lineTo(x, y);
        } else {
          var x1 = this._x * (1 - this._t) + x * this._t;
          this._context.lineTo(x1, this._y);
          this._context.lineTo(x1, y);
        }
        break;
      }
    }
    this._x = x, this._y = y;
  }
};

function step(context) {
  return new Step(context, 0.5);
}

function stepBefore(context) {
  return new Step(context, 0);
}

function stepAfter(context) {
  return new Step(context, 1);
}

function none(series, order) {
  if (!((n = series.length) > 1)) return;
  for (var i = 1, j, s0, s1 = series[order[0]], n, m = s1.length; i < n; ++i) {
    s0 = s1, s1 = series[order[i]];
    for (j = 0; j < m; ++j) {
      s1[j][1] += s1[j][0] = isNaN(s0[j][1]) ? s0[j][0] : s0[j][1];
    }
  }
}

function none$1(series) {
  var n = series.length, o = new Array(n);
  while (--n >= 0) o[n] = n;
  return o;
}

function stackValue(d, key) {
  return d[key];
}

function stack() {
  var keys = constant([]),
      order = none$1,
      offset = none,
      value = stackValue;

  function stack(data) {
    var kz = keys.apply(this, arguments),
        i,
        m = data.length,
        n = kz.length,
        sz = new Array(n),
        oz;

    for (i = 0; i < n; ++i) {
      for (var ki = kz[i], si = sz[i] = new Array(m), j = 0, sij; j < m; ++j) {
        si[j] = sij = [0, +value(data[j], ki, j, data)];
        sij.data = data[j];
      }
      si.key = ki;
    }

    for (i = 0, oz = order(sz); i < n; ++i) {
      sz[oz[i]].index = i;
    }

    offset(sz, oz);
    return sz;
  }

  stack.keys = function(_) {
    return arguments.length ? (keys = typeof _ === "function" ? _ : constant(slice.call(_)), stack) : keys;
  };

  stack.value = function(_) {
    return arguments.length ? (value = typeof _ === "function" ? _ : constant(+_), stack) : value;
  };

  stack.order = function(_) {
    return arguments.length ? (order = _ == null ? none$1 : typeof _ === "function" ? _ : constant(slice.call(_)), stack) : order;
  };

  stack.offset = function(_) {
    return arguments.length ? (offset = _ == null ? none : _, stack) : offset;
  };

  return stack;
}

function expand(series, order) {
  if (!((n = series.length) > 0)) return;
  for (var i, n, j = 0, m = series[0].length, y; j < m; ++j) {
    for (y = i = 0; i < n; ++i) y += series[i][j][1] || 0;
    if (y) for (i = 0; i < n; ++i) series[i][j][1] /= y;
  }
  none(series, order);
}

function diverging(series, order) {
  if (!((n = series.length) > 1)) return;
  for (var i, j = 0, d, dy, yp, yn, n, m = series[order[0]].length; j < m; ++j) {
    for (yp = yn = 0, i = 0; i < n; ++i) {
      if ((dy = (d = series[order[i]][j])[1] - d[0]) >= 0) {
        d[0] = yp, d[1] = yp += dy;
      } else if (dy < 0) {
        d[1] = yn, d[0] = yn += dy;
      } else {
        d[0] = yp;
      }
    }
  }
}

function silhouette(series, order) {
  if (!((n = series.length) > 0)) return;
  for (var j = 0, s0 = series[order[0]], n, m = s0.length; j < m; ++j) {
    for (var i = 0, y = 0; i < n; ++i) y += series[i][j][1] || 0;
    s0[j][1] += s0[j][0] = -y / 2;
  }
  none(series, order);
}

function wiggle(series, order) {
  if (!((n = series.length) > 0) || !((m = (s0 = series[order[0]]).length) > 0)) return;
  for (var y = 0, j = 1, s0, m, n; j < m; ++j) {
    for (var i = 0, s1 = 0, s2 = 0; i < n; ++i) {
      var si = series[order[i]],
          sij0 = si[j][1] || 0,
          sij1 = si[j - 1][1] || 0,
          s3 = (sij0 - sij1) / 2;
      for (var k = 0; k < i; ++k) {
        var sk = series[order[k]],
            skj0 = sk[j][1] || 0,
            skj1 = sk[j - 1][1] || 0;
        s3 += skj0 - skj1;
      }
      s1 += sij0, s2 += s3 * sij0;
    }
    s0[j - 1][1] += s0[j - 1][0] = y;
    if (s1) y -= s2 / s1;
  }
  s0[j - 1][1] += s0[j - 1][0] = y;
  none(series, order);
}

function appearance(series) {
  var peaks = series.map(peak);
  return none$1(series).sort(function(a, b) { return peaks[a] - peaks[b]; });
}

function peak(series) {
  var i = -1, j = 0, n = series.length, vi, vj = -Infinity;
  while (++i < n) if ((vi = +series[i][1]) > vj) vj = vi, j = i;
  return j;
}

function ascending(series) {
  var sums = series.map(sum);
  return none$1(series).sort(function(a, b) { return sums[a] - sums[b]; });
}

function sum(series) {
  var s = 0, i = -1, n = series.length, v;
  while (++i < n) if (v = +series[i][1]) s += v;
  return s;
}

function descending$1(series) {
  return ascending(series).reverse();
}

function insideOut(series) {
  var n = series.length,
      i,
      j,
      sums = series.map(sum),
      order = appearance(series),
      top = 0,
      bottom = 0,
      tops = [],
      bottoms = [];

  for (i = 0; i < n; ++i) {
    j = order[i];
    if (top < bottom) {
      top += sums[j];
      tops.push(j);
    } else {
      bottom += sums[j];
      bottoms.push(j);
    }
  }

  return bottoms.reverse().concat(tops);
}

function reverse(series) {
  return none$1(series).reverse();
}

exports.arc = arc;
exports.area = area;
exports.line = line;
exports.pie = pie;
exports.areaRadial = areaRadial;
exports.radialArea = areaRadial;
exports.lineRadial = lineRadial$1;
exports.radialLine = lineRadial$1;
exports.pointRadial = pointRadial;
exports.linkHorizontal = linkHorizontal;
exports.linkVertical = linkVertical;
exports.linkRadial = linkRadial;
exports.symbol = symbol;
exports.symbols = symbols;
exports.symbolCircle = circle;
exports.symbolCross = cross;
exports.symbolDiamond = diamond;
exports.symbolSquare = square;
exports.symbolStar = star;
exports.symbolTriangle = triangle;
exports.symbolWye = wye;
exports.curveBasisClosed = basisClosed;
exports.curveBasisOpen = basisOpen;
exports.curveBasis = basis;
exports.curveBundle = bundle;
exports.curveCardinalClosed = cardinalClosed;
exports.curveCardinalOpen = cardinalOpen;
exports.curveCardinal = cardinal;
exports.curveCatmullRomClosed = catmullRomClosed;
exports.curveCatmullRomOpen = catmullRomOpen;
exports.curveCatmullRom = catmullRom;
exports.curveLinearClosed = linearClosed;
exports.curveLinear = curveLinear;
exports.curveMonotoneX = monotoneX;
exports.curveMonotoneY = monotoneY;
exports.curveNatural = natural;
exports.curveStep = step;
exports.curveStepAfter = stepAfter;
exports.curveStepBefore = stepBefore;
exports.stack = stack;
exports.stackOffsetExpand = expand;
exports.stackOffsetDiverging = diverging;
exports.stackOffsetNone = none;
exports.stackOffsetSilhouette = silhouette;
exports.stackOffsetWiggle = wiggle;
exports.stackOrderAppearance = appearance;
exports.stackOrderAscending = ascending;
exports.stackOrderDescending = descending$1;
exports.stackOrderInsideOut = insideOut;
exports.stackOrderNone = none$1;
exports.stackOrderReverse = reverse;

Object.defineProperty(exports, '__esModule', { value: true });

})));

},{"d3-path":146}],150:[function(_dereq_,module,exports){
// https://d3js.org/d3-timer/ Version 1.0.7. Copyright 2017 Mike Bostock.
(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
	typeof define === 'function' && define.amd ? define(['exports'], factory) :
	(factory((global.d3 = global.d3 || {})));
}(this, (function (exports) { 'use strict';

var frame = 0;
var timeout = 0;
var interval = 0;
var pokeDelay = 1000;
var taskHead;
var taskTail;
var clockLast = 0;
var clockNow = 0;
var clockSkew = 0;
var clock = typeof performance === "object" && performance.now ? performance : Date;
var setFrame = typeof window === "object" && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : function(f) { setTimeout(f, 17); };

function now() {
  return clockNow || (setFrame(clearNow), clockNow = clock.now() + clockSkew);
}

function clearNow() {
  clockNow = 0;
}

function Timer() {
  this._call =
  this._time =
  this._next = null;
}

Timer.prototype = timer.prototype = {
  constructor: Timer,
  restart: function(callback, delay, time) {
    if (typeof callback !== "function") throw new TypeError("callback is not a function");
    time = (time == null ? now() : +time) + (delay == null ? 0 : +delay);
    if (!this._next && taskTail !== this) {
      if (taskTail) taskTail._next = this;
      else taskHead = this;
      taskTail = this;
    }
    this._call = callback;
    this._time = time;
    sleep();
  },
  stop: function() {
    if (this._call) {
      this._call = null;
      this._time = Infinity;
      sleep();
    }
  }
};

function timer(callback, delay, time) {
  var t = new Timer;
  t.restart(callback, delay, time);
  return t;
}

function timerFlush() {
  now(); // Get the current time, if not already set.
  ++frame; // Pretend we’ve set an alarm, if we haven’t already.
  var t = taskHead, e;
  while (t) {
    if ((e = clockNow - t._time) >= 0) t._call.call(null, e);
    t = t._next;
  }
  --frame;
}

function wake() {
  clockNow = (clockLast = clock.now()) + clockSkew;
  frame = timeout = 0;
  try {
    timerFlush();
  } finally {
    frame = 0;
    nap();
    clockNow = 0;
  }
}

function poke() {
  var now = clock.now(), delay = now - clockLast;
  if (delay > pokeDelay) clockSkew -= delay, clockLast = now;
}

function nap() {
  var t0, t1 = taskHead, t2, time = Infinity;
  while (t1) {
    if (t1._call) {
      if (time > t1._time) time = t1._time;
      t0 = t1, t1 = t1._next;
    } else {
      t2 = t1._next, t1._next = null;
      t1 = t0 ? t0._next = t2 : taskHead = t2;
    }
  }
  taskTail = t0;
  sleep(time);
}

function sleep(time) {
  if (frame) return; // Soonest alarm already set, or will be.
  if (timeout) timeout = clearTimeout(timeout);
  var delay = time - clockNow; // Strictly less than if we recomputed clockNow.
  if (delay > 24) {
    if (time < Infinity) timeout = setTimeout(wake, time - clock.now() - clockSkew);
    if (interval) interval = clearInterval(interval);
  } else {
    if (!interval) clockLast = clock.now(), interval = setInterval(poke, pokeDelay);
    frame = 1, setFrame(wake);
  }
}

var timeout$1 = function(callback, delay, time) {
  var t = new Timer;
  delay = delay == null ? 0 : +delay;
  t.restart(function(elapsed) {
    t.stop();
    callback(elapsed + delay);
  }, delay, time);
  return t;
};

var interval$1 = function(callback, delay, time) {
  var t = new Timer, total = delay;
  if (delay == null) return t.restart(callback, delay, time), t;
  delay = +delay, time = time == null ? now() : +time;
  t.restart(function tick(elapsed) {
    elapsed += total;
    t.restart(tick, total += delay, time);
    callback(elapsed);
  }, delay, time);
  return t;
};

exports.now = now;
exports.timer = timer;
exports.timerFlush = timerFlush;
exports.timeout = timeout$1;
exports.interval = interval$1;

Object.defineProperty(exports, '__esModule', { value: true });

})));

},{}],151:[function(_dereq_,module,exports){
!function() {
  var d3 = {
    version: "3.5.17"
  };
  var d3_arraySlice = [].slice, d3_array = function(list) {
    return d3_arraySlice.call(list);
  };
  var d3_document = this.document;
  function d3_documentElement(node) {
    return node && (node.ownerDocument || node.document || node).documentElement;
  }
  function d3_window(node) {
    return node && (node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView);
  }
  if (d3_document) {
    try {
      d3_array(d3_document.documentElement.childNodes)[0].nodeType;
    } catch (e) {
      d3_array = function(list) {
        var i = list.length, array = new Array(i);
        while (i--) array[i] = list[i];
        return array;
      };
    }
  }
  if (!Date.now) Date.now = function() {
    return +new Date();
  };
  if (d3_document) {
    try {
      d3_document.createElement("DIV").style.setProperty("opacity", 0, "");
    } catch (error) {
      var d3_element_prototype = this.Element.prototype, d3_element_setAttribute = d3_element_prototype.setAttribute, d3_element_setAttributeNS = d3_element_prototype.setAttributeNS, d3_style_prototype = this.CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty;
      d3_element_prototype.setAttribute = function(name, value) {
        d3_element_setAttribute.call(this, name, value + "");
      };
      d3_element_prototype.setAttributeNS = function(space, local, value) {
        d3_element_setAttributeNS.call(this, space, local, value + "");
      };
      d3_style_prototype.setProperty = function(name, value, priority) {
        d3_style_setProperty.call(this, name, value + "", priority);
      };
    }
  }
  d3.ascending = d3_ascending;
  function d3_ascending(a, b) {
    return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
  }
  d3.descending = function(a, b) {
    return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
  };
  d3.min = function(array, f) {
    var i = -1, n = array.length, a, b;
    if (arguments.length === 1) {
      while (++i < n) if ((b = array[i]) != null && b >= b) {
        a = b;
        break;
      }
      while (++i < n) if ((b = array[i]) != null && a > b) a = b;
    } else {
      while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
        a = b;
        break;
      }
      while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b;
    }
    return a;
  };
  d3.max = function(array, f) {
    var i = -1, n = array.length, a, b;
    if (arguments.length === 1) {
      while (++i < n) if ((b = array[i]) != null && b >= b) {
        a = b;
        break;
      }
      while (++i < n) if ((b = array[i]) != null && b > a) a = b;
    } else {
      while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
        a = b;
        break;
      }
      while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b;
    }
    return a;
  };
  d3.extent = function(array, f) {
    var i = -1, n = array.length, a, b, c;
    if (arguments.length === 1) {
      while (++i < n) if ((b = array[i]) != null && b >= b) {
        a = c = b;
        break;
      }
      while (++i < n) if ((b = array[i]) != null) {
        if (a > b) a = b;
        if (c < b) c = b;
      }
    } else {
      while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
        a = c = b;
        break;
      }
      while (++i < n) if ((b = f.call(array, array[i], i)) != null) {
        if (a > b) a = b;
        if (c < b) c = b;
      }
    }
    return [ a, c ];
  };
  function d3_number(x) {
    return x === null ? NaN : +x;
  }
  function d3_numeric(x) {
    return !isNaN(x);
  }
  d3.sum = function(array, f) {
    var s = 0, n = array.length, a, i = -1;
    if (arguments.length === 1) {
      while (++i < n) if (d3_numeric(a = +array[i])) s += a;
    } else {
      while (++i < n) if (d3_numeric(a = +f.call(array, array[i], i))) s += a;
    }
    return s;
  };
  d3.mean = function(array, f) {
    var s = 0, n = array.length, a, i = -1, j = n;
    if (arguments.length === 1) {
      while (++i < n) if (d3_numeric(a = d3_number(array[i]))) s += a; else --j;
    } else {
      while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) s += a; else --j;
    }
    if (j) return s / j;
  };
  d3.quantile = function(values, p) {
    var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h;
    return e ? v + e * (values[h] - v) : v;
  };
  d3.median = function(array, f) {
    var numbers = [], n = array.length, a, i = -1;
    if (arguments.length === 1) {
      while (++i < n) if (d3_numeric(a = d3_number(array[i]))) numbers.push(a);
    } else {
      while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) numbers.push(a);
    }
    if (numbers.length) return d3.quantile(numbers.sort(d3_ascending), .5);
  };
  d3.variance = function(array, f) {
    var n = array.length, m = 0, a, d, s = 0, i = -1, j = 0;
    if (arguments.length === 1) {
      while (++i < n) {
        if (d3_numeric(a = d3_number(array[i]))) {
          d = a - m;
          m += d / ++j;
          s += d * (a - m);
        }
      }
    } else {
      while (++i < n) {
        if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) {
          d = a - m;
          m += d / ++j;
          s += d * (a - m);
        }
      }
    }
    if (j > 1) return s / (j - 1);
  };
  d3.deviation = function() {
    var v = d3.variance.apply(this, arguments);
    return v ? Math.sqrt(v) : v;
  };
  function d3_bisector(compare) {
    return {
      left: function(a, x, lo, hi) {
        if (arguments.length < 3) lo = 0;
        if (arguments.length < 4) hi = a.length;
        while (lo < hi) {
          var mid = lo + hi >>> 1;
          if (compare(a[mid], x) < 0) lo = mid + 1; else hi = mid;
        }
        return lo;
      },
      right: function(a, x, lo, hi) {
        if (arguments.length < 3) lo = 0;
        if (arguments.length < 4) hi = a.length;
        while (lo < hi) {
          var mid = lo + hi >>> 1;
          if (compare(a[mid], x) > 0) hi = mid; else lo = mid + 1;
        }
        return lo;
      }
    };
  }
  var d3_bisect = d3_bisector(d3_ascending);
  d3.bisectLeft = d3_bisect.left;
  d3.bisect = d3.bisectRight = d3_bisect.right;
  d3.bisector = function(f) {
    return d3_bisector(f.length === 1 ? function(d, x) {
      return d3_ascending(f(d), x);
    } : f);
  };
  d3.shuffle = function(array, i0, i1) {
    if ((m = arguments.length) < 3) {
      i1 = array.length;
      if (m < 2) i0 = 0;
    }
    var m = i1 - i0, t, i;
    while (m) {
      i = Math.random() * m-- | 0;
      t = array[m + i0], array[m + i0] = array[i + i0], array[i + i0] = t;
    }
    return array;
  };
  d3.permute = function(array, indexes) {
    var i = indexes.length, permutes = new Array(i);
    while (i--) permutes[i] = array[indexes[i]];
    return permutes;
  };
  d3.pairs = function(array) {
    var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n);
    while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ];
    return pairs;
  };
  d3.transpose = function(matrix) {
    if (!(n = matrix.length)) return [];
    for (var i = -1, m = d3.min(matrix, d3_transposeLength), transpose = new Array(m); ++i < m; ) {
      for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n; ) {
        row[j] = matrix[j][i];
      }
    }
    return transpose;
  };
  function d3_transposeLength(d) {
    return d.length;
  }
  d3.zip = function() {
    return d3.transpose(arguments);
  };
  d3.keys = function(map) {
    var keys = [];
    for (var key in map) keys.push(key);
    return keys;
  };
  d3.values = function(map) {
    var values = [];
    for (var key in map) values.push(map[key]);
    return values;
  };
  d3.entries = function(map) {
    var entries = [];
    for (var key in map) entries.push({
      key: key,
      value: map[key]
    });
    return entries;
  };
  d3.merge = function(arrays) {
    var n = arrays.length, m, i = -1, j = 0, merged, array;
    while (++i < n) j += arrays[i].length;
    merged = new Array(j);
    while (--n >= 0) {
      array = arrays[n];
      m = array.length;
      while (--m >= 0) {
        merged[--j] = array[m];
      }
    }
    return merged;
  };
  var abs = Math.abs;
  d3.range = function(start, stop, step) {
    if (arguments.length < 3) {
      step = 1;
      if (arguments.length < 2) {
        stop = start;
        start = 0;
      }
    }
    if ((stop - start) / step === Infinity) throw new Error("infinite range");
    var range = [], k = d3_range_integerScale(abs(step)), i = -1, j;
    start *= k, stop *= k, step *= k;
    if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k);
    return range;
  };
  function d3_range_integerScale(x) {
    var k = 1;
    while (x * k % 1) k *= 10;
    return k;
  }
  function d3_class(ctor, properties) {
    for (var key in properties) {
      Object.defineProperty(ctor.prototype, key, {
        value: properties[key],
        enumerable: false
      });
    }
  }
  d3.map = function(object, f) {
    var map = new d3_Map();
    if (object instanceof d3_Map) {
      object.forEach(function(key, value) {
        map.set(key, value);
      });
    } else if (Array.isArray(object)) {
      var i = -1, n = object.length, o;
      if (arguments.length === 1) while (++i < n) map.set(i, object[i]); else while (++i < n) map.set(f.call(object, o = object[i], i), o);
    } else {
      for (var key in object) map.set(key, object[key]);
    }
    return map;
  };
  function d3_Map() {
    this._ = Object.create(null);
  }
  var d3_map_proto = "__proto__", d3_map_zero = "\x00";
  d3_class(d3_Map, {
    has: d3_map_has,
    get: function(key) {
      return this._[d3_map_escape(key)];
    },
    set: function(key, value) {
      return this._[d3_map_escape(key)] = value;
    },
    remove: d3_map_remove,
    keys: d3_map_keys,
    values: function() {
      var values = [];
      for (var key in this._) values.push(this._[key]);
      return values;
    },
    entries: function() {
      var entries = [];
      for (var key in this._) entries.push({
        key: d3_map_unescape(key),
        value: this._[key]
      });
      return entries;
    },
    size: d3_map_size,
    empty: d3_map_empty,
    forEach: function(f) {
      for (var key in this._) f.call(this, d3_map_unescape(key), this._[key]);
    }
  });
  function d3_map_escape(key) {
    return (key += "") === d3_map_proto || key[0] === d3_map_zero ? d3_map_zero + key : key;
  }
  function d3_map_unescape(key) {
    return (key += "")[0] === d3_map_zero ? key.slice(1) : key;
  }
  function d3_map_has(key) {
    return d3_map_escape(key) in this._;
  }
  function d3_map_remove(key) {
    return (key = d3_map_escape(key)) in this._ && delete this._[key];
  }
  function d3_map_keys() {
    var keys = [];
    for (var key in this._) keys.push(d3_map_unescape(key));
    return keys;
  }
  function d3_map_size() {
    var size = 0;
    for (var key in this._) ++size;
    return size;
  }
  function d3_map_empty() {
    for (var key in this._) return false;
    return true;
  }
  d3.nest = function() {
    var nest = {}, keys = [], sortKeys = [], sortValues, rollup;
    function map(mapType, array, depth) {
      if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array;
      var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values;
      while (++i < n) {
        if (values = valuesByKey.get(keyValue = key(object = array[i]))) {
          values.push(object);
        } else {
          valuesByKey.set(keyValue, [ object ]);
        }
      }
      if (mapType) {
        object = mapType();
        setter = function(keyValue, values) {
          object.set(keyValue, map(mapType, values, depth));
        };
      } else {
        object = {};
        setter = function(keyValue, values) {
          object[keyValue] = map(mapType, values, depth);
        };
      }
      valuesByKey.forEach(setter);
      return object;
    }
    function entries(map, depth) {
      if (depth >= keys.length) return map;
      var array = [], sortKey = sortKeys[depth++];
      map.forEach(function(key, keyMap) {
        array.push({
          key: key,
          values: entries(keyMap, depth)
        });
      });
      return sortKey ? array.sort(function(a, b) {
        return sortKey(a.key, b.key);
      }) : array;
    }
    nest.map = function(array, mapType) {
      return map(mapType, array, 0);
    };
    nest.entries = function(array) {
      return entries(map(d3.map, array, 0), 0);
    };
    nest.key = function(d) {
      keys.push(d);
      return nest;
    };
    nest.sortKeys = function(order) {
      sortKeys[keys.length - 1] = order;
      return nest;
    };
    nest.sortValues = function(order) {
      sortValues = order;
      return nest;
    };
    nest.rollup = function(f) {
      rollup = f;
      return nest;
    };
    return nest;
  };
  d3.set = function(array) {
    var set = new d3_Set();
    if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]);
    return set;
  };
  function d3_Set() {
    this._ = Object.create(null);
  }
  d3_class(d3_Set, {
    has: d3_map_has,
    add: function(key) {
      this._[d3_map_escape(key += "")] = true;
      return key;
    },
    remove: d3_map_remove,
    values: d3_map_keys,
    size: d3_map_size,
    empty: d3_map_empty,
    forEach: function(f) {
      for (var key in this._) f.call(this, d3_map_unescape(key));
    }
  });
  d3.behavior = {};
  function d3_identity(d) {
    return d;
  }
  d3.rebind = function(target, source) {
    var i = 1, n = arguments.length, method;
    while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]);
    return target;
  };
  function d3_rebind(target, source, method) {
    return function() {
      var value = method.apply(source, arguments);
      return value === source ? target : value;
    };
  }
  function d3_vendorSymbol(object, name) {
    if (name in object) return name;
    name = name.charAt(0).toUpperCase() + name.slice(1);
    for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) {
      var prefixName = d3_vendorPrefixes[i] + name;
      if (prefixName in object) return prefixName;
    }
  }
  var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ];
  function d3_noop() {}
  d3.dispatch = function() {
    var dispatch = new d3_dispatch(), i = -1, n = arguments.length;
    while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch);
    return dispatch;
  };
  function d3_dispatch() {}
  d3_dispatch.prototype.on = function(type, listener) {
    var i = type.indexOf("."), name = "";
    if (i >= 0) {
      name = type.slice(i + 1);
      type = type.slice(0, i);
    }
    if (type) return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener);
    if (arguments.length === 2) {
      if (listener == null) for (type in this) {
        if (this.hasOwnProperty(type)) this[type].on(name, null);
      }
      return this;
    }
  };
  function d3_dispatch_event(dispatch) {
    var listeners = [], listenerByName = new d3_Map();
    function event() {
      var z = listeners, i = -1, n = z.length, l;
      while (++i < n) if (l = z[i].on) l.apply(this, arguments);
      return dispatch;
    }
    event.on = function(name, listener) {
      var l = listenerByName.get(name), i;
      if (arguments.length < 2) return l && l.on;
      if (l) {
        l.on = null;
        listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1));
        listenerByName.remove(name);
      }
      if (listener) listeners.push(listenerByName.set(name, {
        on: listener
      }));
      return dispatch;
    };
    return event;
  }
  d3.event = null;
  function d3_eventPreventDefault() {
    d3.event.preventDefault();
  }
  function d3_eventSource() {
    var e = d3.event, s;
    while (s = e.sourceEvent) e = s;
    return e;
  }
  function d3_eventDispatch(target) {
    var dispatch = new d3_dispatch(), i = 0, n = arguments.length;
    while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch);
    dispatch.of = function(thiz, argumentz) {
      return function(e1) {
        try {
          var e0 = e1.sourceEvent = d3.event;
          e1.target = target;
          d3.event = e1;
          dispatch[e1.type].apply(thiz, argumentz);
        } finally {
          d3.event = e0;
        }
      };
    };
    return dispatch;
  }
  d3.requote = function(s) {
    return s.replace(d3_requote_re, "\\$&");
  };
  var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;
  var d3_subclass = {}.__proto__ ? function(object, prototype) {
    object.__proto__ = prototype;
  } : function(object, prototype) {
    for (var property in prototype) object[property] = prototype[property];
  };
  function d3_selection(groups) {
    d3_subclass(groups, d3_selectionPrototype);
    return groups;
  }
  var d3_select = function(s, n) {
    return n.querySelector(s);
  }, d3_selectAll = function(s, n) {
    return n.querySelectorAll(s);
  }, d3_selectMatches = function(n, s) {
    var d3_selectMatcher = n.matches || n[d3_vendorSymbol(n, "matchesSelector")];
    d3_selectMatches = function(n, s) {
      return d3_selectMatcher.call(n, s);
    };
    return d3_selectMatches(n, s);
  };
  if (typeof Sizzle === "function") {
    d3_select = function(s, n) {
      return Sizzle(s, n)[0] || null;
    };
    d3_selectAll = Sizzle;
    d3_selectMatches = Sizzle.matchesSelector;
  }
  d3.selection = function() {
    return d3.select(d3_document.documentElement);
  };
  var d3_selectionPrototype = d3.selection.prototype = [];
  d3_selectionPrototype.select = function(selector) {
    var subgroups = [], subgroup, subnode, group, node;
    selector = d3_selection_selector(selector);
    for (var j = -1, m = this.length; ++j < m; ) {
      subgroups.push(subgroup = []);
      subgroup.parentNode = (group = this[j]).parentNode;
      for (var i = -1, n = group.length; ++i < n; ) {
        if (node = group[i]) {
          subgroup.push(subnode = selector.call(node, node.__data__, i, j));
          if (subnode && "__data__" in node) subnode.__data__ = node.__data__;
        } else {
          subgroup.push(null);
        }
      }
    }
    return d3_selection(subgroups);
  };
  function d3_selection_selector(selector) {
    return typeof selector === "function" ? selector : function() {
      return d3_select(selector, this);
    };
  }
  d3_selectionPrototype.selectAll = function(selector) {
    var subgroups = [], subgroup, node;
    selector = d3_selection_selectorAll(selector);
    for (var j = -1, m = this.length; ++j < m; ) {
      for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
        if (node = group[i]) {
          subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j)));
          subgroup.parentNode = node;
        }
      }
    }
    return d3_selection(subgroups);
  };
  function d3_selection_selectorAll(selector) {
    return typeof selector === "function" ? selector : function() {
      return d3_selectAll(selector, this);
    };
  }
  var d3_nsXhtml = "http://www.w3.org/1999/xhtml";
  var d3_nsPrefix = {
    svg: "http://www.w3.org/2000/svg",
    xhtml: d3_nsXhtml,
    xlink: "http://www.w3.org/1999/xlink",
    xml: "http://www.w3.org/XML/1998/namespace",
    xmlns: "http://www.w3.org/2000/xmlns/"
  };
  d3.ns = {
    prefix: d3_nsPrefix,
    qualify: function(name) {
      var i = name.indexOf(":"), prefix = name;
      if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1);
      return d3_nsPrefix.hasOwnProperty(prefix) ? {
        space: d3_nsPrefix[prefix],
        local: name
      } : name;
    }
  };
  d3_selectionPrototype.attr = function(name, value) {
    if (arguments.length < 2) {
      if (typeof name === "string") {
        var node = this.node();
        name = d3.ns.qualify(name);
        return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name);
      }
      for (value in name) this.each(d3_selection_attr(value, name[value]));
      return this;
    }
    return this.each(d3_selection_attr(name, value));
  };
  function d3_selection_attr(name, value) {
    name = d3.ns.qualify(name);
    function attrNull() {
      this.removeAttribute(name);
    }
    function attrNullNS() {
      this.removeAttributeNS(name.space, name.local);
    }
    function attrConstant() {
      this.setAttribute(name, value);
    }
    function attrConstantNS() {
      this.setAttributeNS(name.space, name.local, value);
    }
    function attrFunction() {
      var x = value.apply(this, arguments);
      if (x == null) this.removeAttribute(name); else this.setAttribute(name, x);
    }
    function attrFunctionNS() {
      var x = value.apply(this, arguments);
      if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x);
    }
    return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant;
  }
  function d3_collapse(s) {
    return s.trim().replace(/\s+/g, " ");
  }
  d3_selectionPrototype.classed = function(name, value) {
    if (arguments.length < 2) {
      if (typeof name === "string") {
        var node = this.node(), n = (name = d3_selection_classes(name)).length, i = -1;
        if (value = node.classList) {
          while (++i < n) if (!value.contains(name[i])) return false;
        } else {
          value = node.getAttribute("class");
          while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false;
        }
        return true;
      }
      for (value in name) this.each(d3_selection_classed(value, name[value]));
      return this;
    }
    return this.each(d3_selection_classed(name, value));
  };
  function d3_selection_classedRe(name) {
    return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g");
  }
  function d3_selection_classes(name) {
    return (name + "").trim().split(/^|\s+/);
  }
  function d3_selection_classed(name, value) {
    name = d3_selection_classes(name).map(d3_selection_classedName);
    var n = name.length;
    function classedConstant() {
      var i = -1;
      while (++i < n) name[i](this, value);
    }
    function classedFunction() {
      var i = -1, x = value.apply(this, arguments);
      while (++i < n) name[i](this, x);
    }
    return typeof value === "function" ? classedFunction : classedConstant;
  }
  function d3_selection_classedName(name) {
    var re = d3_selection_classedRe(name);
    return function(node, value) {
      if (c = node.classList) return value ? c.add(name) : c.remove(name);
      var c = node.getAttribute("class") || "";
      if (value) {
        re.lastIndex = 0;
        if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name));
      } else {
        node.setAttribute("class", d3_collapse(c.replace(re, " ")));
      }
    };
  }
  d3_selectionPrototype.style = function(name, value, priority) {
    var n = arguments.length;
    if (n < 3) {
      if (typeof name !== "string") {
        if (n < 2) value = "";
        for (priority in name) this.each(d3_selection_style(priority, name[priority], value));
        return this;
      }
      if (n < 2) {
        var node = this.node();
        return d3_window(node).getComputedStyle(node, null).getPropertyValue(name);
      }
      priority = "";
    }
    return this.each(d3_selection_style(name, value, priority));
  };
  function d3_selection_style(name, value, priority) {
    function styleNull() {
      this.style.removeProperty(name);
    }
    function styleConstant() {
      this.style.setProperty(name, value, priority);
    }
    function styleFunction() {
      var x = value.apply(this, arguments);
      if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority);
    }
    return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant;
  }
  d3_selectionPrototype.property = function(name, value) {
    if (arguments.length < 2) {
      if (typeof name === "string") return this.node()[name];
      for (value in name) this.each(d3_selection_property(value, name[value]));
      return this;
    }
    return this.each(d3_selection_property(name, value));
  };
  function d3_selection_property(name, value) {
    function propertyNull() {
      delete this[name];
    }
    function propertyConstant() {
      this[name] = value;
    }
    function propertyFunction() {
      var x = value.apply(this, arguments);
      if (x == null) delete this[name]; else this[name] = x;
    }
    return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant;
  }
  d3_selectionPrototype.text = function(value) {
    return arguments.length ? this.each(typeof value === "function" ? function() {
      var v = value.apply(this, arguments);
      this.textContent = v == null ? "" : v;
    } : value == null ? function() {
      this.textContent = "";
    } : function() {
      this.textContent = value;
    }) : this.node().textContent;
  };
  d3_selectionPrototype.html = function(value) {
    return arguments.length ? this.each(typeof value === "function" ? function() {
      var v = value.apply(this, arguments);
      this.innerHTML = v == null ? "" : v;
    } : value == null ? function() {
      this.innerHTML = "";
    } : function() {
      this.innerHTML = value;
    }) : this.node().innerHTML;
  };
  d3_selectionPrototype.append = function(name) {
    name = d3_selection_creator(name);
    return this.select(function() {
      return this.appendChild(name.apply(this, arguments));
    });
  };
  function d3_selection_creator(name) {
    function create() {
      var document = this.ownerDocument, namespace = this.namespaceURI;
      return namespace === d3_nsXhtml && document.documentElement.namespaceURI === d3_nsXhtml ? document.createElement(name) : document.createElementNS(namespace, name);
    }
    function createNS() {
      return this.ownerDocument.createElementNS(name.space, name.local);
    }
    return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? createNS : create;
  }
  d3_selectionPrototype.insert = function(name, before) {
    name = d3_selection_creator(name);
    before = d3_selection_selector(before);
    return this.select(function() {
      return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null);
    });
  };
  d3_selectionPrototype.remove = function() {
    return this.each(d3_selectionRemove);
  };
  function d3_selectionRemove() {
    var parent = this.parentNode;
    if (parent) parent.removeChild(this);
  }
  d3_selectionPrototype.data = function(value, key) {
    var i = -1, n = this.length, group, node;
    if (!arguments.length) {
      value = new Array(n = (group = this[0]).length);
      while (++i < n) {
        if (node = group[i]) {
          value[i] = node.__data__;
        }
      }
      return value;
    }
    function bind(group, groupData) {
      var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData;
      if (key) {
        var nodeByKeyValue = new d3_Map(), keyValues = new Array(n), keyValue;
        for (i = -1; ++i < n; ) {
          if (node = group[i]) {
            if (nodeByKeyValue.has(keyValue = key.call(node, node.__data__, i))) {
              exitNodes[i] = node;
            } else {
              nodeByKeyValue.set(keyValue, node);
            }
            keyValues[i] = keyValue;
          }
        }
        for (i = -1; ++i < m; ) {
          if (!(node = nodeByKeyValue.get(keyValue = key.call(groupData, nodeData = groupData[i], i)))) {
            enterNodes[i] = d3_selection_dataNode(nodeData);
          } else if (node !== true) {
            updateNodes[i] = node;
            node.__data__ = nodeData;
          }
          nodeByKeyValue.set(keyValue, true);
        }
        for (i = -1; ++i < n; ) {
          if (i in keyValues && nodeByKeyValue.get(keyValues[i]) !== true) {
            exitNodes[i] = group[i];
          }
        }
      } else {
        for (i = -1; ++i < n0; ) {
          node = group[i];
          nodeData = groupData[i];
          if (node) {
            node.__data__ = nodeData;
            updateNodes[i] = node;
          } else {
            enterNodes[i] = d3_selection_dataNode(nodeData);
          }
        }
        for (;i < m; ++i) {
          enterNodes[i] = d3_selection_dataNode(groupData[i]);
        }
        for (;i < n; ++i) {
          exitNodes[i] = group[i];
        }
      }
      enterNodes.update = updateNodes;
      enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode;
      enter.push(enterNodes);
      update.push(updateNodes);
      exit.push(exitNodes);
    }
    var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]);
    if (typeof value === "function") {
      while (++i < n) {
        bind(group = this[i], value.call(group, group.parentNode.__data__, i));
      }
    } else {
      while (++i < n) {
        bind(group = this[i], value);
      }
    }
    update.enter = function() {
      return enter;
    };
    update.exit = function() {
      return exit;
    };
    return update;
  };
  function d3_selection_dataNode(data) {
    return {
      __data__: data
    };
  }
  d3_selectionPrototype.datum = function(value) {
    return arguments.length ? this.property("__data__", value) : this.property("__data__");
  };
  d3_selectionPrototype.filter = function(filter) {
    var subgroups = [], subgroup, group, node;
    if (typeof filter !== "function") filter = d3_selection_filter(filter);
    for (var j = 0, m = this.length; j < m; j++) {
      subgroups.push(subgroup = []);
      subgroup.parentNode = (group = this[j]).parentNode;
      for (var i = 0, n = group.length; i < n; i++) {
        if ((node = group[i]) && filter.call(node, node.__data__, i, j)) {
          subgroup.push(node);
        }
      }
    }
    return d3_selection(subgroups);
  };
  function d3_selection_filter(selector) {
    return function() {
      return d3_selectMatches(this, selector);
    };
  }
  d3_selectionPrototype.order = function() {
    for (var j = -1, m = this.length; ++j < m; ) {
      for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) {
        if (node = group[i]) {
          if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next);
          next = node;
        }
      }
    }
    return this;
  };
  d3_selectionPrototype.sort = function(comparator) {
    comparator = d3_selection_sortComparator.apply(this, arguments);
    for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator);
    return this.order();
  };
  function d3_selection_sortComparator(comparator) {
    if (!arguments.length) comparator = d3_ascending;
    return function(a, b) {
      return a && b ? comparator(a.__data__, b.__data__) : !a - !b;
    };
  }
  d3_selectionPrototype.each = function(callback) {
    return d3_selection_each(this, function(node, i, j) {
      callback.call(node, node.__data__, i, j);
    });
  };
  function d3_selection_each(groups, callback) {
    for (var j = 0, m = groups.length; j < m; j++) {
      for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) {
        if (node = group[i]) callback(node, i, j);
      }
    }
    return groups;
  }
  d3_selectionPrototype.call = function(callback) {
    var args = d3_array(arguments);
    callback.apply(args[0] = this, args);
    return this;
  };
  d3_selectionPrototype.empty = function() {
    return !this.node();
  };
  d3_selectionPrototype.node = function() {
    for (var j = 0, m = this.length; j < m; j++) {
      for (var group = this[j], i = 0, n = group.length; i < n; i++) {
        var node = group[i];
        if (node) return node;
      }
    }
    return null;
  };
  d3_selectionPrototype.size = function() {
    var n = 0;
    d3_selection_each(this, function() {
      ++n;
    });
    return n;
  };
  function d3_selection_enter(selection) {
    d3_subclass(selection, d3_selection_enterPrototype);
    return selection;
  }
  var d3_selection_enterPrototype = [];
  d3.selection.enter = d3_selection_enter;
  d3.selection.enter.prototype = d3_selection_enterPrototype;
  d3_selection_enterPrototype.append = d3_selectionPrototype.append;
  d3_selection_enterPrototype.empty = d3_selectionPrototype.empty;
  d3_selection_enterPrototype.node = d3_selectionPrototype.node;
  d3_selection_enterPrototype.call = d3_selectionPrototype.call;
  d3_selection_enterPrototype.size = d3_selectionPrototype.size;
  d3_selection_enterPrototype.select = function(selector) {
    var subgroups = [], subgroup, subnode, upgroup, group, node;
    for (var j = -1, m = this.length; ++j < m; ) {
      upgroup = (group = this[j]).update;
      subgroups.push(subgroup = []);
      subgroup.parentNode = group.parentNode;
      for (var i = -1, n = group.length; ++i < n; ) {
        if (node = group[i]) {
          subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j));
          subnode.__data__ = node.__data__;
        } else {
          subgroup.push(null);
        }
      }
    }
    return d3_selection(subgroups);
  };
  d3_selection_enterPrototype.insert = function(name, before) {
    if (arguments.length < 2) before = d3_selection_enterInsertBefore(this);
    return d3_selectionPrototype.insert.call(this, name, before);
  };
  function d3_selection_enterInsertBefore(enter) {
    var i0, j0;
    return function(d, i, j) {
      var group = enter[j].update, n = group.length, node;
      if (j != j0) j0 = j, i0 = 0;
      if (i >= i0) i0 = i + 1;
      while (!(node = group[i0]) && ++i0 < n) ;
      return node;
    };
  }
  d3.select = function(node) {
    var group;
    if (typeof node === "string") {
      group = [ d3_select(node, d3_document) ];
      group.parentNode = d3_document.documentElement;
    } else {
      group = [ node ];
      group.parentNode = d3_documentElement(node);
    }
    return d3_selection([ group ]);
  };
  d3.selectAll = function(nodes) {
    var group;
    if (typeof nodes === "string") {
      group = d3_array(d3_selectAll(nodes, d3_document));
      group.parentNode = d3_document.documentElement;
    } else {
      group = d3_array(nodes);
      group.parentNode = null;
    }
    return d3_selection([ group ]);
  };
  d3_selectionPrototype.on = function(type, listener, capture) {
    var n = arguments.length;
    if (n < 3) {
      if (typeof type !== "string") {
        if (n < 2) listener = false;
        for (capture in type) this.each(d3_selection_on(capture, type[capture], listener));
        return this;
      }
      if (n < 2) return (n = this.node()["__on" + type]) && n._;
      capture = false;
    }
    return this.each(d3_selection_on(type, listener, capture));
  };
  function d3_selection_on(type, listener, capture) {
    var name = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener;
    if (i > 0) type = type.slice(0, i);
    var filter = d3_selection_onFilters.get(type);
    if (filter) type = filter, wrap = d3_selection_onFilter;
    function onRemove() {
      var l = this[name];
      if (l) {
        this.removeEventListener(type, l, l.$);
        delete this[name];
      }
    }
    function onAdd() {
      var l = wrap(listener, d3_array(arguments));
      onRemove.call(this);
      this.addEventListener(type, this[name] = l, l.$ = capture);
      l._ = listener;
    }
    function removeAll() {
      var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match;
      for (var name in this) {
        if (match = name.match(re)) {
          var l = this[name];
          this.removeEventListener(match[1], l, l.$);
          delete this[name];
        }
      }
    }
    return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll;
  }
  var d3_selection_onFilters = d3.map({
    mouseenter: "mouseover",
    mouseleave: "mouseout"
  });
  if (d3_document) {
    d3_selection_onFilters.forEach(function(k) {
      if ("on" + k in d3_document) d3_selection_onFilters.remove(k);
    });
  }
  function d3_selection_onListener(listener, argumentz) {
    return function(e) {
      var o = d3.event;
      d3.event = e;
      argumentz[0] = this.__data__;
      try {
        listener.apply(this, argumentz);
      } finally {
        d3.event = o;
      }
    };
  }
  function d3_selection_onFilter(listener, argumentz) {
    var l = d3_selection_onListener(listener, argumentz);
    return function(e) {
      var target = this, related = e.relatedTarget;
      if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) {
        l.call(target, e);
      }
    };
  }
  var d3_event_dragSelect, d3_event_dragId = 0;
  function d3_event_dragSuppress(node) {
    var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window(node)).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault);
    if (d3_event_dragSelect == null) {
      d3_event_dragSelect = "onselectstart" in node ? false : d3_vendorSymbol(node.style, "userSelect");
    }
    if (d3_event_dragSelect) {
      var style = d3_documentElement(node).style, select = style[d3_event_dragSelect];
      style[d3_event_dragSelect] = "none";
    }
    return function(suppressClick) {
      w.on(name, null);
      if (d3_event_dragSelect) style[d3_event_dragSelect] = select;
      if (suppressClick) {
        var off = function() {
          w.on(click, null);
        };
        w.on(click, function() {
          d3_eventPreventDefault();
          off();
        }, true);
        setTimeout(off, 0);
      }
    };
  }
  d3.mouse = function(container) {
    return d3_mousePoint(container, d3_eventSource());
  };
  var d3_mouse_bug44083 = this.navigator && /WebKit/.test(this.navigator.userAgent) ? -1 : 0;
  function d3_mousePoint(container, e) {
    if (e.changedTouches) e = e.changedTouches[0];
    var svg = container.ownerSVGElement || container;
    if (svg.createSVGPoint) {
      var point = svg.createSVGPoint();
      if (d3_mouse_bug44083 < 0) {
        var window = d3_window(container);
        if (window.scrollX || window.scrollY) {
          svg = d3.select("body").append("svg").style({
            position: "absolute",
            top: 0,
            left: 0,
            margin: 0,
            padding: 0,
            border: "none"
          }, "important");
          var ctm = svg[0][0].getScreenCTM();
          d3_mouse_bug44083 = !(ctm.f || ctm.e);
          svg.remove();
        }
      }
      if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; else point.x = e.clientX, 
      point.y = e.clientY;
      point = point.matrixTransform(container.getScreenCTM().inverse());
      return [ point.x, point.y ];
    }
    var rect = container.getBoundingClientRect();
    return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ];
  }
  d3.touch = function(container, touches, identifier) {
    if (arguments.length < 3) identifier = touches, touches = d3_eventSource().changedTouches;
    if (touches) for (var i = 0, n = touches.length, touch; i < n; ++i) {
      if ((touch = touches[i]).identifier === identifier) {
        return d3_mousePoint(container, touch);
      }
    }
  };
  d3.behavior.drag = function() {
    var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, d3_window, "mousemove", "mouseup"), touchstart = dragstart(d3_behavior_dragTouchId, d3.touch, d3_identity, "touchmove", "touchend");
    function drag() {
      this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart);
    }
    function dragstart(id, position, subject, move, end) {
      return function() {
        var that = this, target = d3.event.target.correspondingElement || d3.event.target, parent = that.parentNode, dispatch = event.of(that, arguments), dragged = 0, dragId = id(), dragName = ".drag" + (dragId == null ? "" : "-" + dragId), dragOffset, dragSubject = d3.select(subject(target)).on(move + dragName, moved).on(end + dragName, ended), dragRestore = d3_event_dragSuppress(target), position0 = position(parent, dragId);
        if (origin) {
          dragOffset = origin.apply(that, arguments);
          dragOffset = [ dragOffset.x - position0[0], dragOffset.y - position0[1] ];
        } else {
          dragOffset = [ 0, 0 ];
        }
        dispatch({
          type: "dragstart"
        });
        function moved() {
          var position1 = position(parent, dragId), dx, dy;
          if (!position1) return;
          dx = position1[0] - position0[0];
          dy = position1[1] - position0[1];
          dragged |= dx | dy;
          position0 = position1;
          dispatch({
            type: "drag",
            x: position1[0] + dragOffset[0],
            y: position1[1] + dragOffset[1],
            dx: dx,
            dy: dy
          });
        }
        function ended() {
          if (!position(parent, dragId)) return;
          dragSubject.on(move + dragName, null).on(end + dragName, null);
          dragRestore(dragged);
          dispatch({
            type: "dragend"
          });
        }
      };
    }
    drag.origin = function(x) {
      if (!arguments.length) return origin;
      origin = x;
      return drag;
    };
    return d3.rebind(drag, event, "on");
  };
  function d3_behavior_dragTouchId() {
    return d3.event.changedTouches[0].identifier;
  }
  d3.touches = function(container, touches) {
    if (arguments.length < 2) touches = d3_eventSource().touches;
    return touches ? d3_array(touches).map(function(touch) {
      var point = d3_mousePoint(container, touch);
      point.identifier = touch.identifier;
      return point;
    }) : [];
  };
  var ε = 1e-6, ε2 = ε * ε, π = Math.PI, τ = 2 * π, τε = τ - ε, halfπ = π / 2, d3_radians = π / 180, d3_degrees = 180 / π;
  function d3_sgn(x) {
    return x > 0 ? 1 : x < 0 ? -1 : 0;
  }
  function d3_cross2d(a, b, c) {
    return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
  }
  function d3_acos(x) {
    return x > 1 ? 0 : x < -1 ? π : Math.acos(x);
  }
  function d3_asin(x) {
    return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x);
  }
  function d3_sinh(x) {
    return ((x = Math.exp(x)) - 1 / x) / 2;
  }
  function d3_cosh(x) {
    return ((x = Math.exp(x)) + 1 / x) / 2;
  }
  function d3_tanh(x) {
    return ((x = Math.exp(2 * x)) - 1) / (x + 1);
  }
  function d3_haversin(x) {
    return (x = Math.sin(x / 2)) * x;
  }
  var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4;
  d3.interpolateZoom = function(p0, p1) {
    var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S;
    if (d2 < ε2) {
      S = Math.log(w1 / w0) / ρ;
      i = function(t) {
        return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * t * S) ];
      };
    } else {
      var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);
      S = (r1 - r0) / ρ;
      i = function(t) {
        var s = t * S, coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0));
        return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0) ];
      };
    }
    i.duration = S * 1e3;
    return i;
  };
  d3.behavior.zoom = function() {
    var view = {
      x: 0,
      y: 0,
      k: 1
    }, translate0, center0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, duration = 250, zooming = 0, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1;
    if (!d3_behavior_zoomWheel) {
      d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() {
        return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1);
      }, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() {
        return d3.event.wheelDelta;
      }, "mousewheel") : (d3_behavior_zoomDelta = function() {
        return -d3.event.detail;
      }, "MozMousePixelScroll");
    }
    function zoom(g) {
      g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted);
    }
    zoom.event = function(g) {
      g.each(function() {
        var dispatch = event.of(this, arguments), view1 = view;
        if (d3_transitionInheritId) {
          d3.select(this).transition().each("start.zoom", function() {
            view = this.__chart__ || {
              x: 0,
              y: 0,
              k: 1
            };
            zoomstarted(dispatch);
          }).tween("zoom:zoom", function() {
            var dx = size[0], dy = size[1], cx = center0 ? center0[0] : dx / 2, cy = center0 ? center0[1] : dy / 2, i = d3.interpolateZoom([ (cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k ], [ (cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k ]);
            return function(t) {
              var l = i(t), k = dx / l[2];
              this.__chart__ = view = {
                x: cx - l[0] * k,
                y: cy - l[1] * k,
                k: k
              };
              zoomed(dispatch);
            };
          }).each("interrupt.zoom", function() {
            zoomended(dispatch);
          }).each("end.zoom", function() {
            zoomended(dispatch);
          });
        } else {
          this.__chart__ = view;
          zoomstarted(dispatch);
          zoomed(dispatch);
          zoomended(dispatch);
        }
      });
    };
    zoom.translate = function(_) {
      if (!arguments.length) return [ view.x, view.y ];
      view = {
        x: +_[0],
        y: +_[1],
        k: view.k
      };
      rescale();
      return zoom;
    };
    zoom.scale = function(_) {
      if (!arguments.length) return view.k;
      view = {
        x: view.x,
        y: view.y,
        k: null
      };
      scaleTo(+_);
      rescale();
      return zoom;
    };
    zoom.scaleExtent = function(_) {
      if (!arguments.length) return scaleExtent;
      scaleExtent = _ == null ? d3_behavior_zoomInfinity : [ +_[0], +_[1] ];
      return zoom;
    };
    zoom.center = function(_) {
      if (!arguments.length) return center;
      center = _ && [ +_[0], +_[1] ];
      return zoom;
    };
    zoom.size = function(_) {
      if (!arguments.length) return size;
      size = _ && [ +_[0], +_[1] ];
      return zoom;
    };
    zoom.duration = function(_) {
      if (!arguments.length) return duration;
      duration = +_;
      return zoom;
    };
    zoom.x = function(z) {
      if (!arguments.length) return x1;
      x1 = z;
      x0 = z.copy();
      view = {
        x: 0,
        y: 0,
        k: 1
      };
      return zoom;
    };
    zoom.y = function(z) {
      if (!arguments.length) return y1;
      y1 = z;
      y0 = z.copy();
      view = {
        x: 0,
        y: 0,
        k: 1
      };
      return zoom;
    };
    function location(p) {
      return [ (p[0] - view.x) / view.k, (p[1] - view.y) / view.k ];
    }
    function point(l) {
      return [ l[0] * view.k + view.x, l[1] * view.k + view.y ];
    }
    function scaleTo(s) {
      view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s));
    }
    function translateTo(p, l) {
      l = point(l);
      view.x += p[0] - l[0];
      view.y += p[1] - l[1];
    }
    function zoomTo(that, p, l, k) {
      that.__chart__ = {
        x: view.x,
        y: view.y,
        k: view.k
      };
      scaleTo(Math.pow(2, k));
      translateTo(center0 = p, l);
      that = d3.select(that);
      if (duration > 0) that = that.transition().duration(duration);
      that.call(zoom.event);
    }
    function rescale() {
      if (x1) x1.domain(x0.range().map(function(x) {
        return (x - view.x) / view.k;
      }).map(x0.invert));
      if (y1) y1.domain(y0.range().map(function(y) {
        return (y - view.y) / view.k;
      }).map(y0.invert));
    }
    function zoomstarted(dispatch) {
      if (!zooming++) dispatch({
        type: "zoomstart"
      });
    }
    function zoomed(dispatch) {
      rescale();
      dispatch({
        type: "zoom",
        scale: view.k,
        translate: [ view.x, view.y ]
      });
    }
    function zoomended(dispatch) {
      if (!--zooming) dispatch({
        type: "zoomend"
      }), center0 = null;
    }
    function mousedowned() {
      var that = this, dispatch = event.of(that, arguments), dragged = 0, subject = d3.select(d3_window(that)).on(mousemove, moved).on(mouseup, ended), location0 = location(d3.mouse(that)), dragRestore = d3_event_dragSuppress(that);
      d3_selection_interrupt.call(that);
      zoomstarted(dispatch);
      function moved() {
        dragged = 1;
        translateTo(d3.mouse(that), location0);
        zoomed(dispatch);
      }
      function ended() {
        subject.on(mousemove, null).on(mouseup, null);
        dragRestore(dragged);
        zoomended(dispatch);
      }
    }
    function touchstarted() {
      var that = this, dispatch = event.of(that, arguments), locations0 = {}, distance0 = 0, scale0, zoomName = ".zoom-" + d3.event.changedTouches[0].identifier, touchmove = "touchmove" + zoomName, touchend = "touchend" + zoomName, targets = [], subject = d3.select(that), dragRestore = d3_event_dragSuppress(that);
      started();
      zoomstarted(dispatch);
      subject.on(mousedown, null).on(touchstart, started);
      function relocate() {
        var touches = d3.touches(that);
        scale0 = view.k;
        touches.forEach(function(t) {
          if (t.identifier in locations0) locations0[t.identifier] = location(t);
        });
        return touches;
      }
      function started() {
        var target = d3.event.target;
        d3.select(target).on(touchmove, moved).on(touchend, ended);
        targets.push(target);
        var changed = d3.event.changedTouches;
        for (var i = 0, n = changed.length; i < n; ++i) {
          locations0[changed[i].identifier] = null;
        }
        var touches = relocate(), now = Date.now();
        if (touches.length === 1) {
          if (now - touchtime < 500) {
            var p = touches[0];
            zoomTo(that, p, locations0[p.identifier], Math.floor(Math.log(view.k) / Math.LN2) + 1);
            d3_eventPreventDefault();
          }
          touchtime = now;
        } else if (touches.length > 1) {
          var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1];
          distance0 = dx * dx + dy * dy;
        }
      }
      function moved() {
        var touches = d3.touches(that), p0, l0, p1, l1;
        d3_selection_interrupt.call(that);
        for (var i = 0, n = touches.length; i < n; ++i, l1 = null) {
          p1 = touches[i];
          if (l1 = locations0[p1.identifier]) {
            if (l0) break;
            p0 = p1, l0 = l1;
          }
        }
        if (l1) {
          var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0);
          p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ];
          l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ];
          scaleTo(scale1 * scale0);
        }
        touchtime = null;
        translateTo(p0, l0);
        zoomed(dispatch);
      }
      function ended() {
        if (d3.event.touches.length) {
          var changed = d3.event.changedTouches;
          for (var i = 0, n = changed.length; i < n; ++i) {
            delete locations0[changed[i].identifier];
          }
          for (var identifier in locations0) {
            return void relocate();
          }
        }
        d3.selectAll(targets).on(zoomName, null);
        subject.on(mousedown, mousedowned).on(touchstart, touchstarted);
        dragRestore();
        zoomended(dispatch);
      }
    }
    function mousewheeled() {
      var dispatch = event.of(this, arguments);
      if (mousewheelTimer) clearTimeout(mousewheelTimer); else d3_selection_interrupt.call(this), 
      translate0 = location(center0 = center || d3.mouse(this)), zoomstarted(dispatch);
      mousewheelTimer = setTimeout(function() {
        mousewheelTimer = null;
        zoomended(dispatch);
      }, 50);
      d3_eventPreventDefault();
      scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k);
      translateTo(center0, translate0);
      zoomed(dispatch);
    }
    function dblclicked() {
      var p = d3.mouse(this), k = Math.log(view.k) / Math.LN2;
      zoomTo(this, p, location(p), d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1);
    }
    return d3.rebind(zoom, event, "on");
  };
  var d3_behavior_zoomInfinity = [ 0, Infinity ], d3_behavior_zoomDelta, d3_behavior_zoomWheel;
  d3.color = d3_color;
  function d3_color() {}
  d3_color.prototype.toString = function() {
    return this.rgb() + "";
  };
  d3.hsl = d3_hsl;
  function d3_hsl(h, s, l) {
    return this instanceof d3_hsl ? void (this.h = +h, this.s = +s, this.l = +l) : arguments.length < 2 ? h instanceof d3_hsl ? new d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : new d3_hsl(h, s, l);
  }
  var d3_hslPrototype = d3_hsl.prototype = new d3_color();
  d3_hslPrototype.brighter = function(k) {
    k = Math.pow(.7, arguments.length ? k : 1);
    return new d3_hsl(this.h, this.s, this.l / k);
  };
  d3_hslPrototype.darker = function(k) {
    k = Math.pow(.7, arguments.length ? k : 1);
    return new d3_hsl(this.h, this.s, k * this.l);
  };
  d3_hslPrototype.rgb = function() {
    return d3_hsl_rgb(this.h, this.s, this.l);
  };
  function d3_hsl_rgb(h, s, l) {
    var m1, m2;
    h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h;
    s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s;
    l = l < 0 ? 0 : l > 1 ? 1 : l;
    m2 = l <= .5 ? l * (1 + s) : l + s - l * s;
    m1 = 2 * l - m2;
    function v(h) {
      if (h > 360) h -= 360; else if (h < 0) h += 360;
      if (h < 60) return m1 + (m2 - m1) * h / 60;
      if (h < 180) return m2;
      if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60;
      return m1;
    }
    function vv(h) {
      return Math.round(v(h) * 255);
    }
    return new d3_rgb(vv(h + 120), vv(h), vv(h - 120));
  }
  d3.hcl = d3_hcl;
  function d3_hcl(h, c, l) {
    return this instanceof d3_hcl ? void (this.h = +h, this.c = +c, this.l = +l) : arguments.length < 2 ? h instanceof d3_hcl ? new d3_hcl(h.h, h.c, h.l) : h instanceof d3_lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : new d3_hcl(h, c, l);
  }
  var d3_hclPrototype = d3_hcl.prototype = new d3_color();
  d3_hclPrototype.brighter = function(k) {
    return new d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)));
  };
  d3_hclPrototype.darker = function(k) {
    return new d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)));
  };
  d3_hclPrototype.rgb = function() {
    return d3_hcl_lab(this.h, this.c, this.l).rgb();
  };
  function d3_hcl_lab(h, c, l) {
    if (isNaN(h)) h = 0;
    if (isNaN(c)) c = 0;
    return new d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c);
  }
  d3.lab = d3_lab;
  function d3_lab(l, a, b) {
    return this instanceof d3_lab ? void (this.l = +l, this.a = +a, this.b = +b) : arguments.length < 2 ? l instanceof d3_lab ? new d3_lab(l.l, l.a, l.b) : l instanceof d3_hcl ? d3_hcl_lab(l.h, l.c, l.l) : d3_rgb_lab((l = d3_rgb(l)).r, l.g, l.b) : new d3_lab(l, a, b);
  }
  var d3_lab_K = 18;
  var d3_lab_X = .95047, d3_lab_Y = 1, d3_lab_Z = 1.08883;
  var d3_labPrototype = d3_lab.prototype = new d3_color();
  d3_labPrototype.brighter = function(k) {
    return new d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b);
  };
  d3_labPrototype.darker = function(k) {
    return new d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b);
  };
  d3_labPrototype.rgb = function() {
    return d3_lab_rgb(this.l, this.a, this.b);
  };
  function d3_lab_rgb(l, a, b) {
    var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200;
    x = d3_lab_xyz(x) * d3_lab_X;
    y = d3_lab_xyz(y) * d3_lab_Y;
    z = d3_lab_xyz(z) * d3_lab_Z;
    return new d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z), d3_xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z), d3_xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z));
  }
  function d3_lab_hcl(l, a, b) {
    return l > 0 ? new d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : new d3_hcl(NaN, NaN, l);
  }
  function d3_lab_xyz(x) {
    return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037;
  }
  function d3_xyz_lab(x) {
    return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29;
  }
  function d3_xyz_rgb(r) {
    return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055));
  }
  d3.rgb = d3_rgb;
  function d3_rgb(r, g, b) {
    return this instanceof d3_rgb ? void (this.r = ~~r, this.g = ~~g, this.b = ~~b) : arguments.length < 2 ? r instanceof d3_rgb ? new d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : new d3_rgb(r, g, b);
  }
  function d3_rgbNumber(value) {
    return new d3_rgb(value >> 16, value >> 8 & 255, value & 255);
  }
  function d3_rgbString(value) {
    return d3_rgbNumber(value) + "";
  }
  var d3_rgbPrototype = d3_rgb.prototype = new d3_color();
  d3_rgbPrototype.brighter = function(k) {
    k = Math.pow(.7, arguments.length ? k : 1);
    var r = this.r, g = this.g, b = this.b, i = 30;
    if (!r && !g && !b) return new d3_rgb(i, i, i);
    if (r && r < i) r = i;
    if (g && g < i) g = i;
    if (b && b < i) b = i;
    return new d3_rgb(Math.min(255, r / k), Math.min(255, g / k), Math.min(255, b / k));
  };
  d3_rgbPrototype.darker = function(k) {
    k = Math.pow(.7, arguments.length ? k : 1);
    return new d3_rgb(k * this.r, k * this.g, k * this.b);
  };
  d3_rgbPrototype.hsl = function() {
    return d3_rgb_hsl(this.r, this.g, this.b);
  };
  d3_rgbPrototype.toString = function() {
    return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b);
  };
  function d3_rgb_hex(v) {
    return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16);
  }
  function d3_rgb_parse(format, rgb, hsl) {
    var r = 0, g = 0, b = 0, m1, m2, color;
    m1 = /([a-z]+)\((.*)\)/.exec(format = format.toLowerCase());
    if (m1) {
      m2 = m1[2].split(",");
      switch (m1[1]) {
       case "hsl":
        {
          return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100);
        }

       case "rgb":
        {
          return rgb(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2]));
        }
      }
    }
    if (color = d3_rgb_names.get(format)) {
      return rgb(color.r, color.g, color.b);
    }
    if (format != null && format.charAt(0) === "#" && !isNaN(color = parseInt(format.slice(1), 16))) {
      if (format.length === 4) {
        r = (color & 3840) >> 4;
        r = r >> 4 | r;
        g = color & 240;
        g = g >> 4 | g;
        b = color & 15;
        b = b << 4 | b;
      } else if (format.length === 7) {
        r = (color & 16711680) >> 16;
        g = (color & 65280) >> 8;
        b = color & 255;
      }
    }
    return rgb(r, g, b);
  }
  function d3_rgb_hsl(r, g, b) {
    var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2;
    if (d) {
      s = l < .5 ? d / (max + min) : d / (2 - max - min);
      if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4;
      h *= 60;
    } else {
      h = NaN;
      s = l > 0 && l < 1 ? 0 : h;
    }
    return new d3_hsl(h, s, l);
  }
  function d3_rgb_lab(r, g, b) {
    r = d3_rgb_xyz(r);
    g = d3_rgb_xyz(g);
    b = d3_rgb_xyz(b);
    var x = d3_xyz_lab((.4124564 * r + .3575761 * g + .1804375 * b) / d3_lab_X), y = d3_xyz_lab((.2126729 * r + .7151522 * g + .072175 * b) / d3_lab_Y), z = d3_xyz_lab((.0193339 * r + .119192 * g + .9503041 * b) / d3_lab_Z);
    return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z));
  }
  function d3_rgb_xyz(r) {
    return (r /= 255) <= .04045 ? r / 12.92 : Math.pow((r + .055) / 1.055, 2.4);
  }
  function d3_rgb_parseNumber(c) {
    var f = parseFloat(c);
    return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f;
  }
  var d3_rgb_names = d3.map({
    aliceblue: 15792383,
    antiquewhite: 16444375,
    aqua: 65535,
    aquamarine: 8388564,
    azure: 15794175,
    beige: 16119260,
    bisque: 16770244,
    black: 0,
    blanchedalmond: 16772045,
    blue: 255,
    blueviolet: 9055202,
    brown: 10824234,
    burlywood: 14596231,
    cadetblue: 6266528,
    chartreuse: 8388352,
    chocolate: 13789470,
    coral: 16744272,
    cornflowerblue: 6591981,
    cornsilk: 16775388,
    crimson: 14423100,
    cyan: 65535,
    darkblue: 139,
    darkcyan: 35723,
    darkgoldenrod: 12092939,
    darkgray: 11119017,
    darkgreen: 25600,
    darkgrey: 11119017,
    darkkhaki: 12433259,
    darkmagenta: 9109643,
    darkolivegreen: 5597999,
    darkorange: 16747520,
    darkorchid: 10040012,
    darkred: 9109504,
    darksalmon: 15308410,
    darkseagreen: 9419919,
    darkslateblue: 4734347,
    darkslategray: 3100495,
    darkslategrey: 3100495,
    darkturquoise: 52945,
    darkviolet: 9699539,
    deeppink: 16716947,
    deepskyblue: 49151,
    dimgray: 6908265,
    dimgrey: 6908265,
    dodgerblue: 2003199,
    firebrick: 11674146,
    floralwhite: 16775920,
    forestgreen: 2263842,
    fuchsia: 16711935,
    gainsboro: 14474460,
    ghostwhite: 16316671,
    gold: 16766720,
    goldenrod: 14329120,
    gray: 8421504,
    green: 32768,
    greenyellow: 11403055,
    grey: 8421504,
    honeydew: 15794160,
    hotpink: 16738740,
    indianred: 13458524,
    indigo: 4915330,
    ivory: 16777200,
    khaki: 15787660,
    lavender: 15132410,
    lavenderblush: 16773365,
    lawngreen: 8190976,
    lemonchiffon: 16775885,
    lightblue: 11393254,
    lightcoral: 15761536,
    lightcyan: 14745599,
    lightgoldenrodyellow: 16448210,
    lightgray: 13882323,
    lightgreen: 9498256,
    lightgrey: 13882323,
    lightpink: 16758465,
    lightsalmon: 16752762,
    lightseagreen: 2142890,
    lightskyblue: 8900346,
    lightslategray: 7833753,
    lightslategrey: 7833753,
    lightsteelblue: 11584734,
    lightyellow: 16777184,
    lime: 65280,
    limegreen: 3329330,
    linen: 16445670,
    magenta: 16711935,
    maroon: 8388608,
    mediumaquamarine: 6737322,
    mediumblue: 205,
    mediumorchid: 12211667,
    mediumpurple: 9662683,
    mediumseagreen: 3978097,
    mediumslateblue: 8087790,
    mediumspringgreen: 64154,
    mediumturquoise: 4772300,
    mediumvioletred: 13047173,
    midnightblue: 1644912,
    mintcream: 16121850,
    mistyrose: 16770273,
    moccasin: 16770229,
    navajowhite: 16768685,
    navy: 128,
    oldlace: 16643558,
    olive: 8421376,
    olivedrab: 7048739,
    orange: 16753920,
    orangered: 16729344,
    orchid: 14315734,
    palegoldenrod: 15657130,
    palegreen: 10025880,
    paleturquoise: 11529966,
    palevioletred: 14381203,
    papayawhip: 16773077,
    peachpuff: 16767673,
    peru: 13468991,
    pink: 16761035,
    plum: 14524637,
    powderblue: 11591910,
    purple: 8388736,
    rebeccapurple: 6697881,
    red: 16711680,
    rosybrown: 12357519,
    royalblue: 4286945,
    saddlebrown: 9127187,
    salmon: 16416882,
    sandybrown: 16032864,
    seagreen: 3050327,
    seashell: 16774638,
    sienna: 10506797,
    silver: 12632256,
    skyblue: 8900331,
    slateblue: 6970061,
    slategray: 7372944,
    slategrey: 7372944,
    snow: 16775930,
    springgreen: 65407,
    steelblue: 4620980,
    tan: 13808780,
    teal: 32896,
    thistle: 14204888,
    tomato: 16737095,
    turquoise: 4251856,
    violet: 15631086,
    wheat: 16113331,
    white: 16777215,
    whitesmoke: 16119285,
    yellow: 16776960,
    yellowgreen: 10145074
  });
  d3_rgb_names.forEach(function(key, value) {
    d3_rgb_names.set(key, d3_rgbNumber(value));
  });
  function d3_functor(v) {
    return typeof v === "function" ? v : function() {
      return v;
    };
  }
  d3.functor = d3_functor;
  d3.xhr = d3_xhrType(d3_identity);
  function d3_xhrType(response) {
    return function(url, mimeType, callback) {
      if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType, 
      mimeType = null;
      return d3_xhr(url, mimeType, response, callback);
    };
  }
  function d3_xhr(url, mimeType, response, callback) {
    var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null;
    if (this.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest();
    "onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() {
      request.readyState > 3 && respond();
    };
    function respond() {
      var status = request.status, result;
      if (!status && d3_xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) {
        try {
          result = response.call(xhr, request);
        } catch (e) {
          dispatch.error.call(xhr, e);
          return;
        }
        dispatch.load.call(xhr, result);
      } else {
        dispatch.error.call(xhr, request);
      }
    }
    request.onprogress = function(event) {
      var o = d3.event;
      d3.event = event;
      try {
        dispatch.progress.call(xhr, request);
      } finally {
        d3.event = o;
      }
    };
    xhr.header = function(name, value) {
      name = (name + "").toLowerCase();
      if (arguments.length < 2) return headers[name];
      if (value == null) delete headers[name]; else headers[name] = value + "";
      return xhr;
    };
    xhr.mimeType = function(value) {
      if (!arguments.length) return mimeType;
      mimeType = value == null ? null : value + "";
      return xhr;
    };
    xhr.responseType = function(value) {
      if (!arguments.length) return responseType;
      responseType = value;
      return xhr;
    };
    xhr.response = function(value) {
      response = value;
      return xhr;
    };
    [ "get", "post" ].forEach(function(method) {
      xhr[method] = function() {
        return xhr.send.apply(xhr, [ method ].concat(d3_array(arguments)));
      };
    });
    xhr.send = function(method, data, callback) {
      if (arguments.length === 2 && typeof data === "function") callback = data, data = null;
      request.open(method, url, true);
      if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*";
      if (request.setRequestHeader) for (var name in headers) request.setRequestHeader(name, headers[name]);
      if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType);
      if (responseType != null) request.responseType = responseType;
      if (callback != null) xhr.on("error", callback).on("load", function(request) {
        callback(null, request);
      });
      dispatch.beforesend.call(xhr, request);
      request.send(data == null ? null : data);
      return xhr;
    };
    xhr.abort = function() {
      request.abort();
      return xhr;
    };
    d3.rebind(xhr, dispatch, "on");
    return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback));
  }
  function d3_xhr_fixCallback(callback) {
    return callback.length === 1 ? function(error, request) {
      callback(error == null ? request : null);
    } : callback;
  }
  function d3_xhrHasResponse(request) {
    var type = request.responseType;
    return type && type !== "text" ? request.response : request.responseText;
  }
  d3.dsv = function(delimiter, mimeType) {
    var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0);
    function dsv(url, row, callback) {
      if (arguments.length < 3) callback = row, row = null;
      var xhr = d3_xhr(url, mimeType, row == null ? response : typedResponse(row), callback);
      xhr.row = function(_) {
        return arguments.length ? xhr.response((row = _) == null ? response : typedResponse(_)) : row;
      };
      return xhr;
    }
    function response(request) {
      return dsv.parse(request.responseText);
    }
    function typedResponse(f) {
      return function(request) {
        return dsv.parse(request.responseText, f);
      };
    }
    dsv.parse = function(text, f) {
      var o;
      return dsv.parseRows(text, function(row, i) {
        if (o) return o(row, i - 1);
        var a = new Function("d", "return {" + row.map(function(name, i) {
          return JSON.stringify(name) + ": d[" + i + "]";
        }).join(",") + "}");
        o = f ? function(row, i) {
          return f(a(row), i);
        } : a;
      });
    };
    dsv.parseRows = function(text, f) {
      var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol;
      function token() {
        if (I >= N) return EOF;
        if (eol) return eol = false, EOL;
        var j = I;
        if (text.charCodeAt(j) === 34) {
          var i = j;
          while (i++ < N) {
            if (text.charCodeAt(i) === 34) {
              if (text.charCodeAt(i + 1) !== 34) break;
              ++i;
            }
          }
          I = i + 2;
          var c = text.charCodeAt(i + 1);
          if (c === 13) {
            eol = true;
            if (text.charCodeAt(i + 2) === 10) ++I;
          } else if (c === 10) {
            eol = true;
          }
          return text.slice(j + 1, i).replace(/""/g, '"');
        }
        while (I < N) {
          var c = text.charCodeAt(I++), k = 1;
          if (c === 10) eol = true; else if (c === 13) {
            eol = true;
            if (text.charCodeAt(I) === 10) ++I, ++k;
          } else if (c !== delimiterCode) continue;
          return text.slice(j, I - k);
        }
        return text.slice(j);
      }
      while ((t = token()) !== EOF) {
        var a = [];
        while (t !== EOL && t !== EOF) {
          a.push(t);
          t = token();
        }
        if (f && (a = f(a, n++)) == null) continue;
        rows.push(a);
      }
      return rows;
    };
    dsv.format = function(rows) {
      if (Array.isArray(rows[0])) return dsv.formatRows(rows);
      var fieldSet = new d3_Set(), fields = [];
      rows.forEach(function(row) {
        for (var field in row) {
          if (!fieldSet.has(field)) {
            fields.push(fieldSet.add(field));
          }
        }
      });
      return [ fields.map(formatValue).join(delimiter) ].concat(rows.map(function(row) {
        return fields.map(function(field) {
          return formatValue(row[field]);
        }).join(delimiter);
      })).join("\n");
    };
    dsv.formatRows = function(rows) {
      return rows.map(formatRow).join("\n");
    };
    function formatRow(row) {
      return row.map(formatValue).join(delimiter);
    }
    function formatValue(text) {
      return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text;
    }
    return dsv;
  };
  d3.csv = d3.dsv(",", "text/csv");
  d3.tsv = d3.dsv("	", "text/tab-separated-values");
  var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_frame = this[d3_vendorSymbol(this, "requestAnimationFrame")] || function(callback) {
    setTimeout(callback, 17);
  };
  d3.timer = function() {
    d3_timer.apply(this, arguments);
  };
  function d3_timer(callback, delay, then) {
    var n = arguments.length;
    if (n < 2) delay = 0;
    if (n < 3) then = Date.now();
    var time = then + delay, timer = {
      c: callback,
      t: time,
      n: null
    };
    if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer;
    d3_timer_queueTail = timer;
    if (!d3_timer_interval) {
      d3_timer_timeout = clearTimeout(d3_timer_timeout);
      d3_timer_interval = 1;
      d3_timer_frame(d3_timer_step);
    }
    return timer;
  }
  function d3_timer_step() {
    var now = d3_timer_mark(), delay = d3_timer_sweep() - now;
    if (delay > 24) {
      if (isFinite(delay)) {
        clearTimeout(d3_timer_timeout);
        d3_timer_timeout = setTimeout(d3_timer_step, delay);
      }
      d3_timer_interval = 0;
    } else {
      d3_timer_interval = 1;
      d3_timer_frame(d3_timer_step);
    }
  }
  d3.timer.flush = function() {
    d3_timer_mark();
    d3_timer_sweep();
  };
  function d3_timer_mark() {
    var now = Date.now(), timer = d3_timer_queueHead;
    while (timer) {
      if (now >= timer.t && timer.c(now - timer.t)) timer.c = null;
      timer = timer.n;
    }
    return now;
  }
  function d3_timer_sweep() {
    var t0, t1 = d3_timer_queueHead, time = Infinity;
    while (t1) {
      if (t1.c) {
        if (t1.t < time) time = t1.t;
        t1 = (t0 = t1).n;
      } else {
        t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n;
      }
    }
    d3_timer_queueTail = t0;
    return time;
  }
  function d3_format_precision(x, p) {
    return p - (x ? Math.ceil(Math.log(x) / Math.LN10) : 1);
  }
  d3.round = function(x, n) {
    return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x);
  };
  var d3_formatPrefixes = [ "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" ].map(d3_formatPrefix);
  d3.formatPrefix = function(value, precision) {
    var i = 0;
    if (value = +value) {
      if (value < 0) value *= -1;
      if (precision) value = d3.round(value, d3_format_precision(value, precision));
      i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10);
      i = Math.max(-24, Math.min(24, Math.floor((i - 1) / 3) * 3));
    }
    return d3_formatPrefixes[8 + i / 3];
  };
  function d3_formatPrefix(d, i) {
    var k = Math.pow(10, abs(8 - i) * 3);
    return {
      scale: i > 8 ? function(d) {
        return d / k;
      } : function(d) {
        return d * k;
      },
      symbol: d
    };
  }
  function d3_locale_numberFormat(locale) {
    var locale_decimal = locale.decimal, locale_thousands = locale.thousands, locale_grouping = locale.grouping, locale_currency = locale.currency, formatGroup = locale_grouping && locale_thousands ? function(value, width) {
      var i = value.length, t = [], j = 0, g = locale_grouping[0], length = 0;
      while (i > 0 && g > 0) {
        if (length + g + 1 > width) g = Math.max(1, width - length);
        t.push(value.substring(i -= g, i + g));
        if ((length += g + 1) > width) break;
        g = locale_grouping[j = (j + 1) % locale_grouping.length];
      }
      return t.reverse().join(locale_thousands);
    } : d3_identity;
    return function(specifier) {
      var match = d3_format_re.exec(specifier), fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "-", symbol = match[4] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, prefix = "", suffix = "", integer = false, exponent = true;
      if (precision) precision = +precision.substring(1);
      if (zfill || fill === "0" && align === "=") {
        zfill = fill = "0";
        align = "=";
      }
      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();

       case "c":
        exponent = false;

       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 (type == "r" && !precision) type = "g";
      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));
      }
      type = d3_format_types.get(type) || d3_format_typeDefault;
      var zcomma = zfill && comma;
      return function(value) {
        var fullSuffix = suffix;
        if (integer && value % 1) return "";
        var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, "-") : sign === "-" ? "" : sign;
        if (scale < 0) {
          var unit = d3.formatPrefix(value, precision);
          value = unit.scale(value);
          fullSuffix = unit.symbol + suffix;
        } else {
          value *= scale;
        }
        value = type(value, precision);
        var i = value.lastIndexOf("."), before, after;
        if (i < 0) {
          var j = exponent ? value.lastIndexOf("e") : -1;
          if (j < 0) before = value, after = ""; else before = value.substring(0, j), after = value.substring(j);
        } else {
          before = value.substring(0, i);
          after = locale_decimal + value.substring(i + 1);
        }
        if (!zfill && comma) before = formatGroup(before, Infinity);
        var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length), padding = length < width ? new Array(length = width - length + 1).join(fill) : "";
        if (zcomma) before = formatGroup(padding + before, padding.length ? width - after.length : Infinity);
        negative += prefix;
        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;
      };
    };
  }
  var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i;
  var d3_format_types = d3.map({
    b: function(x) {
      return x.toString(2);
    },
    c: function(x) {
      return String.fromCharCode(x);
    },
    o: function(x) {
      return x.toString(8);
    },
    x: function(x) {
      return x.toString(16);
    },
    X: function(x) {
      return x.toString(16).toUpperCase();
    },
    g: function(x, p) {
      return x.toPrecision(p);
    },
    e: function(x, p) {
      return x.toExponential(p);
    },
    f: function(x, p) {
      return x.toFixed(p);
    },
    r: function(x, p) {
      return (x = d3.round(x, d3_format_precision(x, p))).toFixed(Math.max(0, Math.min(20, d3_format_precision(x * (1 + 1e-15), p))));
    }
  });
  function d3_format_typeDefault(x) {
    return x + "";
  }
  var d3_time = d3.time = {}, d3_date = Date;
  function d3_date_utc() {
    this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]);
  }
  d3_date_utc.prototype = {
    getDate: function() {
      return this._.getUTCDate();
    },
    getDay: function() {
      return this._.getUTCDay();
    },
    getFullYear: function() {
      return this._.getUTCFullYear();
    },
    getHours: function() {
      return this._.getUTCHours();
    },
    getMilliseconds: function() {
      return this._.getUTCMilliseconds();
    },
    getMinutes: function() {
      return this._.getUTCMinutes();
    },
    getMonth: function() {
      return this._.getUTCMonth();
    },
    getSeconds: function() {
      return this._.getUTCSeconds();
    },
    getTime: function() {
      return this._.getTime();
    },
    getTimezoneOffset: function() {
      return 0;
    },
    valueOf: function() {
      return this._.valueOf();
    },
    setDate: function() {
      d3_time_prototype.setUTCDate.apply(this._, arguments);
    },
    setDay: function() {
      d3_time_prototype.setUTCDay.apply(this._, arguments);
    },
    setFullYear: function() {
      d3_time_prototype.setUTCFullYear.apply(this._, arguments);
    },
    setHours: function() {
      d3_time_prototype.setUTCHours.apply(this._, arguments);
    },
    setMilliseconds: function() {
      d3_time_prototype.setUTCMilliseconds.apply(this._, arguments);
    },
    setMinutes: function() {
      d3_time_prototype.setUTCMinutes.apply(this._, arguments);
    },
    setMonth: function() {
      d3_time_prototype.setUTCMonth.apply(this._, arguments);
    },
    setSeconds: function() {
      d3_time_prototype.setUTCSeconds.apply(this._, arguments);
    },
    setTime: function() {
      d3_time_prototype.setTime.apply(this._, arguments);
    }
  };
  var d3_time_prototype = Date.prototype;
  function d3_time_interval(local, step, number) {
    function round(date) {
      var d0 = local(date), d1 = offset(d0, 1);
      return date - d0 < d1 - date ? d0 : d1;
    }
    function ceil(date) {
      step(date = local(new d3_date(date - 1)), 1);
      return date;
    }
    function offset(date, k) {
      step(date = new d3_date(+date), k);
      return date;
    }
    function range(t0, t1, dt) {
      var time = ceil(t0), times = [];
      if (dt > 1) {
        while (time < t1) {
          if (!(number(time) % dt)) times.push(new Date(+time));
          step(time, 1);
        }
      } else {
        while (time < t1) times.push(new Date(+time)), step(time, 1);
      }
      return times;
    }
    function range_utc(t0, t1, dt) {
      try {
        d3_date = d3_date_utc;
        var utc = new d3_date_utc();
        utc._ = t0;
        return range(utc, t1, dt);
      } finally {
        d3_date = Date;
      }
    }
    local.floor = local;
    local.round = round;
    local.ceil = ceil;
    local.offset = offset;
    local.range = range;
    var utc = local.utc = d3_time_interval_utc(local);
    utc.floor = utc;
    utc.round = d3_time_interval_utc(round);
    utc.ceil = d3_time_interval_utc(ceil);
    utc.offset = d3_time_interval_utc(offset);
    utc.range = range_utc;
    return local;
  }
  function d3_time_interval_utc(method) {
    return function(date, k) {
      try {
        d3_date = d3_date_utc;
        var utc = new d3_date_utc();
        utc._ = date;
        return method(utc, k)._;
      } finally {
        d3_date = Date;
      }
    };
  }
  d3_time.year = d3_time_interval(function(date) {
    date = d3_time.day(date);
    date.setMonth(0, 1);
    return date;
  }, function(date, offset) {
    date.setFullYear(date.getFullYear() + offset);
  }, function(date) {
    return date.getFullYear();
  });
  d3_time.years = d3_time.year.range;
  d3_time.years.utc = d3_time.year.utc.range;
  d3_time.day = d3_time_interval(function(date) {
    var day = new d3_date(2e3, 0);
    day.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());
    return day;
  }, function(date, offset) {
    date.setDate(date.getDate() + offset);
  }, function(date) {
    return date.getDate() - 1;
  });
  d3_time.days = d3_time.day.range;
  d3_time.days.utc = d3_time.day.utc.range;
  d3_time.dayOfYear = function(date) {
    var year = d3_time.year(date);
    return Math.floor((date - year - (date.getTimezoneOffset() - year.getTimezoneOffset()) * 6e4) / 864e5);
  };
  [ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ].forEach(function(day, i) {
    i = 7 - i;
    var interval = d3_time[day] = d3_time_interval(function(date) {
      (date = d3_time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7);
      return date;
    }, function(date, offset) {
      date.setDate(date.getDate() + Math.floor(offset) * 7);
    }, function(date) {
      var day = d3_time.year(date).getDay();
      return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i);
    });
    d3_time[day + "s"] = interval.range;
    d3_time[day + "s"].utc = interval.utc.range;
    d3_time[day + "OfYear"] = function(date) {
      var day = d3_time.year(date).getDay();
      return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7);
    };
  });
  d3_time.week = d3_time.sunday;
  d3_time.weeks = d3_time.sunday.range;
  d3_time.weeks.utc = d3_time.sunday.utc.range;
  d3_time.weekOfYear = d3_time.sundayOfYear;
  function d3_locale_timeFormat(locale) {
    var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_days = locale.days, locale_shortDays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths;
    function d3_time_format(template) {
      var n = template.length;
      function format(date) {
        var string = [], i = -1, j = 0, c, p, f;
        while (++i < n) {
          if (template.charCodeAt(i) === 37) {
            string.push(template.slice(j, i));
            if ((p = d3_time_formatPads[c = template.charAt(++i)]) != null) c = template.charAt(++i);
            if (f = d3_time_formats[c]) c = f(date, p == null ? c === "e" ? " " : "0" : p);
            string.push(c);
            j = i + 1;
          }
        }
        string.push(template.slice(j, i));
        return string.join("");
      }
      format.parse = function(string) {
        var d = {
          y: 1900,
          m: 0,
          d: 1,
          H: 0,
          M: 0,
          S: 0,
          L: 0,
          Z: null
        }, i = d3_time_parse(d, template, string, 0);
        if (i != string.length) return null;
        if ("p" in d) d.H = d.H % 12 + d.p * 12;
        var localZ = d.Z != null && d3_date !== d3_date_utc, date = new (localZ ? d3_date_utc : d3_date)();
        if ("j" in d) date.setFullYear(d.y, 0, d.j); else if ("W" in d || "U" in d) {
          if (!("w" in d)) d.w = "W" in d ? 1 : 0;
          date.setFullYear(d.y, 0, 1);
          date.setFullYear(d.y, 0, "W" in d ? (d.w + 6) % 7 + d.W * 7 - (date.getDay() + 5) % 7 : d.w + d.U * 7 - (date.getDay() + 6) % 7);
        } else date.setFullYear(d.y, d.m, d.d);
        date.setHours(d.H + (d.Z / 100 | 0), d.M + d.Z % 100, d.S, d.L);
        return localZ ? date._ : date;
      };
      format.toString = function() {
        return template;
      };
      return format;
    }
    function d3_time_parse(date, template, string, j) {
      var c, p, t, i = 0, n = template.length, m = string.length;
      while (i < n) {
        if (j >= m) return -1;
        c = template.charCodeAt(i++);
        if (c === 37) {
          t = template.charAt(i++);
          p = d3_time_parsers[t in d3_time_formatPads ? template.charAt(i++) : t];
          if (!p || (j = p(date, string, j)) < 0) return -1;
        } else if (c != string.charCodeAt(j++)) {
          return -1;
        }
      }
      return j;
    }
    d3_time_format.utc = function(template) {
      var local = d3_time_format(template);
      function format(date) {
        try {
          d3_date = d3_date_utc;
          var utc = new d3_date();
          utc._ = date;
          return local(utc);
        } finally {
          d3_date = Date;
        }
      }
      format.parse = function(string) {
        try {
          d3_date = d3_date_utc;
          var date = local.parse(string);
          return date && date._;
        } finally {
          d3_date = Date;
        }
      };
      format.toString = local.toString;
      return format;
    };
    d3_time_format.multi = d3_time_format.utc.multi = d3_time_formatMulti;
    var d3_time_periodLookup = d3.map(), d3_time_dayRe = d3_time_formatRe(locale_days), d3_time_dayLookup = d3_time_formatLookup(locale_days), d3_time_dayAbbrevRe = d3_time_formatRe(locale_shortDays), d3_time_dayAbbrevLookup = d3_time_formatLookup(locale_shortDays), d3_time_monthRe = d3_time_formatRe(locale_months), d3_time_monthLookup = d3_time_formatLookup(locale_months), d3_time_monthAbbrevRe = d3_time_formatRe(locale_shortMonths), d3_time_monthAbbrevLookup = d3_time_formatLookup(locale_shortMonths);
    locale_periods.forEach(function(p, i) {
      d3_time_periodLookup.set(p.toLowerCase(), i);
    });
    var d3_time_formats = {
      a: function(d) {
        return locale_shortDays[d.getDay()];
      },
      A: function(d) {
        return locale_days[d.getDay()];
      },
      b: function(d) {
        return locale_shortMonths[d.getMonth()];
      },
      B: function(d) {
        return locale_months[d.getMonth()];
      },
      c: d3_time_format(locale_dateTime),
      d: function(d, p) {
        return d3_time_formatPad(d.getDate(), p, 2);
      },
      e: function(d, p) {
        return d3_time_formatPad(d.getDate(), p, 2);
      },
      H: function(d, p) {
        return d3_time_formatPad(d.getHours(), p, 2);
      },
      I: function(d, p) {
        return d3_time_formatPad(d.getHours() % 12 || 12, p, 2);
      },
      j: function(d, p) {
        return d3_time_formatPad(1 + d3_time.dayOfYear(d), p, 3);
      },
      L: function(d, p) {
        return d3_time_formatPad(d.getMilliseconds(), p, 3);
      },
      m: function(d, p) {
        return d3_time_formatPad(d.getMonth() + 1, p, 2);
      },
      M: function(d, p) {
        return d3_time_formatPad(d.getMinutes(), p, 2);
      },
      p: function(d) {
        return locale_periods[+(d.getHours() >= 12)];
      },
      S: function(d, p) {
        return d3_time_formatPad(d.getSeconds(), p, 2);
      },
      U: function(d, p) {
        return d3_time_formatPad(d3_time.sundayOfYear(d), p, 2);
      },
      w: function(d) {
        return d.getDay();
      },
      W: function(d, p) {
        return d3_time_formatPad(d3_time.mondayOfYear(d), p, 2);
      },
      x: d3_time_format(locale_date),
      X: d3_time_format(locale_time),
      y: function(d, p) {
        return d3_time_formatPad(d.getFullYear() % 100, p, 2);
      },
      Y: function(d, p) {
        return d3_time_formatPad(d.getFullYear() % 1e4, p, 4);
      },
      Z: d3_time_zone,
      "%": function() {
        return "%";
      }
    };
    var d3_time_parsers = {
      a: d3_time_parseWeekdayAbbrev,
      A: d3_time_parseWeekday,
      b: d3_time_parseMonthAbbrev,
      B: d3_time_parseMonth,
      c: d3_time_parseLocaleFull,
      d: d3_time_parseDay,
      e: d3_time_parseDay,
      H: d3_time_parseHour24,
      I: d3_time_parseHour24,
      j: d3_time_parseDayOfYear,
      L: d3_time_parseMilliseconds,
      m: d3_time_parseMonthNumber,
      M: d3_time_parseMinutes,
      p: d3_time_parseAmPm,
      S: d3_time_parseSeconds,
      U: d3_time_parseWeekNumberSunday,
      w: d3_time_parseWeekdayNumber,
      W: d3_time_parseWeekNumberMonday,
      x: d3_time_parseLocaleDate,
      X: d3_time_parseLocaleTime,
      y: d3_time_parseYear,
      Y: d3_time_parseFullYear,
      Z: d3_time_parseZone,
      "%": d3_time_parseLiteralPercent
    };
    function d3_time_parseWeekdayAbbrev(date, string, i) {
      d3_time_dayAbbrevRe.lastIndex = 0;
      var n = d3_time_dayAbbrevRe.exec(string.slice(i));
      return n ? (date.w = d3_time_dayAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
    }
    function d3_time_parseWeekday(date, string, i) {
      d3_time_dayRe.lastIndex = 0;
      var n = d3_time_dayRe.exec(string.slice(i));
      return n ? (date.w = d3_time_dayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
    }
    function d3_time_parseMonthAbbrev(date, string, i) {
      d3_time_monthAbbrevRe.lastIndex = 0;
      var n = d3_time_monthAbbrevRe.exec(string.slice(i));
      return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
    }
    function d3_time_parseMonth(date, string, i) {
      d3_time_monthRe.lastIndex = 0;
      var n = d3_time_monthRe.exec(string.slice(i));
      return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
    }
    function d3_time_parseLocaleFull(date, string, i) {
      return d3_time_parse(date, d3_time_formats.c.toString(), string, i);
    }
    function d3_time_parseLocaleDate(date, string, i) {
      return d3_time_parse(date, d3_time_formats.x.toString(), string, i);
    }
    function d3_time_parseLocaleTime(date, string, i) {
      return d3_time_parse(date, d3_time_formats.X.toString(), string, i);
    }
    function d3_time_parseAmPm(date, string, i) {
      var n = d3_time_periodLookup.get(string.slice(i, i += 2).toLowerCase());
      return n == null ? -1 : (date.p = n, i);
    }
    return d3_time_format;
  }
  var d3_time_formatPads = {
    "-": "",
    _: " ",
    "0": "0"
  }, d3_time_numberRe = /^\s*\d+/, d3_time_percentRe = /^%/;
  function d3_time_formatPad(value, fill, width) {
    var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length;
    return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string);
  }
  function d3_time_formatRe(names) {
    return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i");
  }
  function d3_time_formatLookup(names) {
    var map = new d3_Map(), i = -1, n = names.length;
    while (++i < n) map.set(names[i].toLowerCase(), i);
    return map;
  }
  function d3_time_parseWeekdayNumber(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 1));
    return n ? (date.w = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseWeekNumberSunday(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i));
    return n ? (date.U = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseWeekNumberMonday(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i));
    return n ? (date.W = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseFullYear(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 4));
    return n ? (date.y = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseYear(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.y = d3_time_expandYear(+n[0]), i + n[0].length) : -1;
  }
  function d3_time_parseZone(date, string, i) {
    return /^[+-]\d{4}$/.test(string = string.slice(i, i + 5)) ? (date.Z = -string, 
    i + 5) : -1;
  }
  function d3_time_expandYear(d) {
    return d + (d > 68 ? 1900 : 2e3);
  }
  function d3_time_parseMonthNumber(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.m = n[0] - 1, i + n[0].length) : -1;
  }
  function d3_time_parseDay(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.d = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseDayOfYear(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 3));
    return n ? (date.j = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseHour24(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.H = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseMinutes(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.M = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseSeconds(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.S = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseMilliseconds(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 3));
    return n ? (date.L = +n[0], i + n[0].length) : -1;
  }
  function d3_time_zone(d) {
    var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = abs(z) / 60 | 0, zm = abs(z) % 60;
    return zs + d3_time_formatPad(zh, "0", 2) + d3_time_formatPad(zm, "0", 2);
  }
  function d3_time_parseLiteralPercent(date, string, i) {
    d3_time_percentRe.lastIndex = 0;
    var n = d3_time_percentRe.exec(string.slice(i, i + 1));
    return n ? i + n[0].length : -1;
  }
  function d3_time_formatMulti(formats) {
    var n = formats.length, i = -1;
    while (++i < n) formats[i][0] = this(formats[i][0]);
    return function(date) {
      var i = 0, f = formats[i];
      while (!f[1](date)) f = formats[++i];
      return f[0](date);
    };
  }
  d3.locale = function(locale) {
    return {
      numberFormat: d3_locale_numberFormat(locale),
      timeFormat: d3_locale_timeFormat(locale)
    };
  };
  var d3_locale_enUS = d3.locale({
    decimal: ".",
    thousands: ",",
    grouping: [ 3 ],
    currency: [ "$", "" ],
    dateTime: "%a %b %e %X %Y",
    date: "%m/%d/%Y",
    time: "%H:%M:%S",
    periods: [ "AM", "PM" ],
    days: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ],
    shortDays: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ],
    months: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ],
    shortMonths: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]
  });
  d3.format = d3_locale_enUS.numberFormat;
  d3.geo = {};
  function d3_adder() {}
  d3_adder.prototype = {
    s: 0,
    t: 0,
    add: function(y) {
      d3_adderSum(y, this.t, d3_adderTemp);
      d3_adderSum(d3_adderTemp.s, this.s, this);
      if (this.s) this.t += d3_adderTemp.t; else this.s = d3_adderTemp.t;
    },
    reset: function() {
      this.s = this.t = 0;
    },
    valueOf: function() {
      return this.s;
    }
  };
  var d3_adderTemp = new d3_adder();
  function d3_adderSum(a, b, o) {
    var x = o.s = a + b, bv = x - a, av = x - bv;
    o.t = a - av + (b - bv);
  }
  d3.geo.stream = function(object, listener) {
    if (object && d3_geo_streamObjectType.hasOwnProperty(object.type)) {
      d3_geo_streamObjectType[object.type](object, listener);
    } else {
      d3_geo_streamGeometry(object, listener);
    }
  };
  function d3_geo_streamGeometry(geometry, listener) {
    if (geometry && d3_geo_streamGeometryType.hasOwnProperty(geometry.type)) {
      d3_geo_streamGeometryType[geometry.type](geometry, listener);
    }
  }
  var d3_geo_streamObjectType = {
    Feature: function(feature, listener) {
      d3_geo_streamGeometry(feature.geometry, listener);
    },
    FeatureCollection: function(object, listener) {
      var features = object.features, i = -1, n = features.length;
      while (++i < n) d3_geo_streamGeometry(features[i].geometry, listener);
    }
  };
  var d3_geo_streamGeometryType = {
    Sphere: function(object, listener) {
      listener.sphere();
    },
    Point: function(object, listener) {
      object = object.coordinates;
      listener.point(object[0], object[1], object[2]);
    },
    MultiPoint: function(object, listener) {
      var coordinates = object.coordinates, i = -1, n = coordinates.length;
      while (++i < n) object = coordinates[i], listener.point(object[0], object[1], object[2]);
    },
    LineString: function(object, listener) {
      d3_geo_streamLine(object.coordinates, listener, 0);
    },
    MultiLineString: function(object, listener) {
      var coordinates = object.coordinates, i = -1, n = coordinates.length;
      while (++i < n) d3_geo_streamLine(coordinates[i], listener, 0);
    },
    Polygon: function(object, listener) {
      d3_geo_streamPolygon(object.coordinates, listener);
    },
    MultiPolygon: function(object, listener) {
      var coordinates = object.coordinates, i = -1, n = coordinates.length;
      while (++i < n) d3_geo_streamPolygon(coordinates[i], listener);
    },
    GeometryCollection: function(object, listener) {
      var geometries = object.geometries, i = -1, n = geometries.length;
      while (++i < n) d3_geo_streamGeometry(geometries[i], listener);
    }
  };
  function d3_geo_streamLine(coordinates, listener, closed) {
    var i = -1, n = coordinates.length - closed, coordinate;
    listener.lineStart();
    while (++i < n) coordinate = coordinates[i], listener.point(coordinate[0], coordinate[1], coordinate[2]);
    listener.lineEnd();
  }
  function d3_geo_streamPolygon(coordinates, listener) {
    var i = -1, n = coordinates.length;
    listener.polygonStart();
    while (++i < n) d3_geo_streamLine(coordinates[i], listener, 1);
    listener.polygonEnd();
  }
  d3.geo.area = function(object) {
    d3_geo_areaSum = 0;
    d3.geo.stream(object, d3_geo_area);
    return d3_geo_areaSum;
  };
  var d3_geo_areaSum, d3_geo_areaRingSum = new d3_adder();
  var d3_geo_area = {
    sphere: function() {
      d3_geo_areaSum += 4 * π;
    },
    point: d3_noop,
    lineStart: d3_noop,
    lineEnd: d3_noop,
    polygonStart: function() {
      d3_geo_areaRingSum.reset();
      d3_geo_area.lineStart = d3_geo_areaRingStart;
    },
    polygonEnd: function() {
      var area = 2 * d3_geo_areaRingSum;
      d3_geo_areaSum += area < 0 ? 4 * π + area : area;
      d3_geo_area.lineStart = d3_geo_area.lineEnd = d3_geo_area.point = d3_noop;
    }
  };
  function d3_geo_areaRingStart() {
    var λ00, φ00, λ0, cosφ0, sinφ0;
    d3_geo_area.point = function(λ, φ) {
      d3_geo_area.point = nextPoint;
      λ0 = (λ00 = λ) * d3_radians, cosφ0 = Math.cos(φ = (φ00 = φ) * d3_radians / 2 + π / 4), 
      sinφ0 = Math.sin(φ);
    };
    function nextPoint(λ, φ) {
      λ *= d3_radians;
      φ = φ * d3_radians / 2 + π / 4;
      var dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, cosφ = Math.cos(φ), sinφ = Math.sin(φ), k = sinφ0 * sinφ, u = cosφ0 * cosφ + k * Math.cos(adλ), v = k * sdλ * Math.sin(adλ);
      d3_geo_areaRingSum.add(Math.atan2(v, u));
      λ0 = λ, cosφ0 = cosφ, sinφ0 = sinφ;
    }
    d3_geo_area.lineEnd = function() {
      nextPoint(λ00, φ00);
    };
  }
  function d3_geo_cartesian(spherical) {
    var λ = spherical[0], φ = spherical[1], cosφ = Math.cos(φ);
    return [ cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ) ];
  }
  function d3_geo_cartesianDot(a, b) {
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  }
  function d3_geo_cartesianCross(a, b) {
    return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ];
  }
  function d3_geo_cartesianAdd(a, b) {
    a[0] += b[0];
    a[1] += b[1];
    a[2] += b[2];
  }
  function d3_geo_cartesianScale(vector, k) {
    return [ vector[0] * k, vector[1] * k, vector[2] * k ];
  }
  function d3_geo_cartesianNormalize(d) {
    var l = Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
    d[0] /= l;
    d[1] /= l;
    d[2] /= l;
  }
  function d3_geo_spherical(cartesian) {
    return [ Math.atan2(cartesian[1], cartesian[0]), d3_asin(cartesian[2]) ];
  }
  function d3_geo_sphericalEqual(a, b) {
    return abs(a[0] - b[0]) < ε && abs(a[1] - b[1]) < ε;
  }
  d3.geo.bounds = function() {
    var λ0, φ0, λ1, φ1, λ_, λ__, φ__, p0, dλSum, ranges, range;
    var bound = {
      point: point,
      lineStart: lineStart,
      lineEnd: lineEnd,
      polygonStart: function() {
        bound.point = ringPoint;
        bound.lineStart = ringStart;
        bound.lineEnd = ringEnd;
        dλSum = 0;
        d3_geo_area.polygonStart();
      },
      polygonEnd: function() {
        d3_geo_area.polygonEnd();
        bound.point = point;
        bound.lineStart = lineStart;
        bound.lineEnd = lineEnd;
        if (d3_geo_areaRingSum < 0) λ0 = -(λ1 = 180), φ0 = -(φ1 = 90); else if (dλSum > ε) φ1 = 90; else if (dλSum < -ε) φ0 = -90;
        range[0] = λ0, range[1] = λ1;
      }
    };
    function point(λ, φ) {
      ranges.push(range = [ λ0 = λ, λ1 = λ ]);
      if (φ < φ0) φ0 = φ;
      if (φ > φ1) φ1 = φ;
    }
    function linePoint(λ, φ) {
      var p = d3_geo_cartesian([ λ * d3_radians, φ * d3_radians ]);
      if (p0) {
        var normal = d3_geo_cartesianCross(p0, p), equatorial = [ normal[1], -normal[0], 0 ], inflection = d3_geo_cartesianCross(equatorial, normal);
        d3_geo_cartesianNormalize(inflection);
        inflection = d3_geo_spherical(inflection);
        var dλ = λ - λ_, s = dλ > 0 ? 1 : -1, λi = inflection[0] * d3_degrees * s, antimeridian = abs(dλ) > 180;
        if (antimeridian ^ (s * λ_ < λi && λi < s * λ)) {
          var φi = inflection[1] * d3_degrees;
          if (φi > φ1) φ1 = φi;
        } else if (λi = (λi + 360) % 360 - 180, antimeridian ^ (s * λ_ < λi && λi < s * λ)) {
          var φi = -inflection[1] * d3_degrees;
          if (φi < φ0) φ0 = φi;
        } else {
          if (φ < φ0) φ0 = φ;
          if (φ > φ1) φ1 = φ;
        }
        if (antimeridian) {
          if (λ < λ_) {
            if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ;
          } else {
            if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ;
          }
        } else {
          if (λ1 >= λ0) {
            if (λ < λ0) λ0 = λ;
            if (λ > λ1) λ1 = λ;
          } else {
            if (λ > λ_) {
              if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ;
            } else {
              if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ;
            }
          }
        }
      } else {
        point(λ, φ);
      }
      p0 = p, λ_ = λ;
    }
    function lineStart() {
      bound.point = linePoint;
    }
    function lineEnd() {
      range[0] = λ0, range[1] = λ1;
      bound.point = point;
      p0 = null;
    }
    function ringPoint(λ, φ) {
      if (p0) {
        var dλ = λ - λ_;
        dλSum += abs(dλ) > 180 ? dλ + (dλ > 0 ? 360 : -360) : dλ;
      } else λ__ = λ, φ__ = φ;
      d3_geo_area.point(λ, φ);
      linePoint(λ, φ);
    }
    function ringStart() {
      d3_geo_area.lineStart();
    }
    function ringEnd() {
      ringPoint(λ__, φ__);
      d3_geo_area.lineEnd();
      if (abs(dλSum) > ε) λ0 = -(λ1 = 180);
      range[0] = λ0, range[1] = λ1;
      p0 = null;
    }
    function angle(λ0, λ1) {
      return (λ1 -= λ0) < 0 ? λ1 + 360 : λ1;
    }
    function compareRanges(a, b) {
      return a[0] - b[0];
    }
    function withinRange(x, range) {
      return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x;
    }
    return function(feature) {
      φ1 = λ1 = -(λ0 = φ0 = Infinity);
      ranges = [];
      d3.geo.stream(feature, bound);
      var n = ranges.length;
      if (n) {
        ranges.sort(compareRanges);
        for (var i = 1, a = ranges[0], b, merged = [ a ]; i < n; ++i) {
          b = ranges[i];
          if (withinRange(b[0], a) || withinRange(b[1], a)) {
            if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1];
            if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0];
          } else {
            merged.push(a = b);
          }
        }
        var best = -Infinity, dλ;
        for (var n = merged.length - 1, i = 0, a = merged[n], b; i <= n; a = b, ++i) {
          b = merged[i];
          if ((dλ = angle(a[1], b[0])) > best) best = dλ, λ0 = b[0], λ1 = a[1];
        }
      }
      ranges = range = null;
      return λ0 === Infinity || φ0 === Infinity ? [ [ NaN, NaN ], [ NaN, NaN ] ] : [ [ λ0, φ0 ], [ λ1, φ1 ] ];
    };
  }();
  d3.geo.centroid = function(object) {
    d3_geo_centroidW0 = d3_geo_centroidW1 = d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0;
    d3.geo.stream(object, d3_geo_centroid);
    var x = d3_geo_centroidX2, y = d3_geo_centroidY2, z = d3_geo_centroidZ2, m = x * x + y * y + z * z;
    if (m < ε2) {
      x = d3_geo_centroidX1, y = d3_geo_centroidY1, z = d3_geo_centroidZ1;
      if (d3_geo_centroidW1 < ε) x = d3_geo_centroidX0, y = d3_geo_centroidY0, z = d3_geo_centroidZ0;
      m = x * x + y * y + z * z;
      if (m < ε2) return [ NaN, NaN ];
    }
    return [ Math.atan2(y, x) * d3_degrees, d3_asin(z / Math.sqrt(m)) * d3_degrees ];
  };
  var d3_geo_centroidW0, d3_geo_centroidW1, d3_geo_centroidX0, d3_geo_centroidY0, d3_geo_centroidZ0, d3_geo_centroidX1, d3_geo_centroidY1, d3_geo_centroidZ1, d3_geo_centroidX2, d3_geo_centroidY2, d3_geo_centroidZ2;
  var d3_geo_centroid = {
    sphere: d3_noop,
    point: d3_geo_centroidPoint,
    lineStart: d3_geo_centroidLineStart,
    lineEnd: d3_geo_centroidLineEnd,
    polygonStart: function() {
      d3_geo_centroid.lineStart = d3_geo_centroidRingStart;
    },
    polygonEnd: function() {
      d3_geo_centroid.lineStart = d3_geo_centroidLineStart;
    }
  };
  function d3_geo_centroidPoint(λ, φ) {
    λ *= d3_radians;
    var cosφ = Math.cos(φ *= d3_radians);
    d3_geo_centroidPointXYZ(cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ));
  }
  function d3_geo_centroidPointXYZ(x, y, z) {
    ++d3_geo_centroidW0;
    d3_geo_centroidX0 += (x - d3_geo_centroidX0) / d3_geo_centroidW0;
    d3_geo_centroidY0 += (y - d3_geo_centroidY0) / d3_geo_centroidW0;
    d3_geo_centroidZ0 += (z - d3_geo_centroidZ0) / d3_geo_centroidW0;
  }
  function d3_geo_centroidLineStart() {
    var x0, y0, z0;
    d3_geo_centroid.point = function(λ, φ) {
      λ *= d3_radians;
      var cosφ = Math.cos(φ *= d3_radians);
      x0 = cosφ * Math.cos(λ);
      y0 = cosφ * Math.sin(λ);
      z0 = Math.sin(φ);
      d3_geo_centroid.point = nextPoint;
      d3_geo_centroidPointXYZ(x0, y0, z0);
    };
    function nextPoint(λ, φ) {
      λ *= d3_radians;
      var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), w = Math.atan2(Math.sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z);
      d3_geo_centroidW1 += w;
      d3_geo_centroidX1 += w * (x0 + (x0 = x));
      d3_geo_centroidY1 += w * (y0 + (y0 = y));
      d3_geo_centroidZ1 += w * (z0 + (z0 = z));
      d3_geo_centroidPointXYZ(x0, y0, z0);
    }
  }
  function d3_geo_centroidLineEnd() {
    d3_geo_centroid.point = d3_geo_centroidPoint;
  }
  function d3_geo_centroidRingStart() {
    var λ00, φ00, x0, y0, z0;
    d3_geo_centroid.point = function(λ, φ) {
      λ00 = λ, φ00 = φ;
      d3_geo_centroid.point = nextPoint;
      λ *= d3_radians;
      var cosφ = Math.cos(φ *= d3_radians);
      x0 = cosφ * Math.cos(λ);
      y0 = cosφ * Math.sin(λ);
      z0 = Math.sin(φ);
      d3_geo_centroidPointXYZ(x0, y0, z0);
    };
    d3_geo_centroid.lineEnd = function() {
      nextPoint(λ00, φ00);
      d3_geo_centroid.lineEnd = d3_geo_centroidLineEnd;
      d3_geo_centroid.point = d3_geo_centroidPoint;
    };
    function nextPoint(λ, φ) {
      λ *= d3_radians;
      var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = Math.sqrt(cx * cx + cy * cy + cz * cz), u = x0 * x + y0 * y + z0 * z, v = m && -d3_acos(u) / m, w = Math.atan2(m, u);
      d3_geo_centroidX2 += v * cx;
      d3_geo_centroidY2 += v * cy;
      d3_geo_centroidZ2 += v * cz;
      d3_geo_centroidW1 += w;
      d3_geo_centroidX1 += w * (x0 + (x0 = x));
      d3_geo_centroidY1 += w * (y0 + (y0 = y));
      d3_geo_centroidZ1 += w * (z0 + (z0 = z));
      d3_geo_centroidPointXYZ(x0, y0, z0);
    }
  }
  function d3_geo_compose(a, b) {
    function compose(x, y) {
      return x = a(x, y), b(x[0], x[1]);
    }
    if (a.invert && b.invert) compose.invert = function(x, y) {
      return x = b.invert(x, y), x && a.invert(x[0], x[1]);
    };
    return compose;
  }
  function d3_true() {
    return true;
  }
  function d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener) {
    var subject = [], clip = [];
    segments.forEach(function(segment) {
      if ((n = segment.length - 1) <= 0) return;
      var n, p0 = segment[0], p1 = segment[n];
      if (d3_geo_sphericalEqual(p0, p1)) {
        listener.lineStart();
        for (var i = 0; i < n; ++i) listener.point((p0 = segment[i])[0], p0[1]);
        listener.lineEnd();
        return;
      }
      var a = new d3_geo_clipPolygonIntersection(p0, segment, null, true), b = new d3_geo_clipPolygonIntersection(p0, null, a, false);
      a.o = b;
      subject.push(a);
      clip.push(b);
      a = new d3_geo_clipPolygonIntersection(p1, segment, null, false);
      b = new d3_geo_clipPolygonIntersection(p1, null, a, true);
      a.o = b;
      subject.push(a);
      clip.push(b);
    });
    clip.sort(compare);
    d3_geo_clipPolygonLinkCircular(subject);
    d3_geo_clipPolygonLinkCircular(clip);
    if (!subject.length) return;
    for (var i = 0, entry = clipStartInside, n = clip.length; i < n; ++i) {
      clip[i].e = entry = !entry;
    }
    var start = subject[0], points, point;
    while (1) {
      var current = start, isSubject = true;
      while (current.v) if ((current = current.n) === start) return;
      points = current.z;
      listener.lineStart();
      do {
        current.v = current.o.v = true;
        if (current.e) {
          if (isSubject) {
            for (var i = 0, n = points.length; i < n; ++i) listener.point((point = points[i])[0], point[1]);
          } else {
            interpolate(current.x, current.n.x, 1, listener);
          }
          current = current.n;
        } else {
          if (isSubject) {
            points = current.p.z;
            for (var i = points.length - 1; i >= 0; --i) listener.point((point = points[i])[0], point[1]);
          } else {
            interpolate(current.x, current.p.x, -1, listener);
          }
          current = current.p;
        }
        current = current.o;
        points = current.z;
        isSubject = !isSubject;
      } while (!current.v);
      listener.lineEnd();
    }
  }
  function d3_geo_clipPolygonLinkCircular(array) {
    if (!(n = array.length)) return;
    var n, i = 0, a = array[0], b;
    while (++i < n) {
      a.n = b = array[i];
      b.p = a;
      a = b;
    }
    a.n = b = array[0];
    b.p = a;
  }
  function d3_geo_clipPolygonIntersection(point, points, other, entry) {
    this.x = point;
    this.z = points;
    this.o = other;
    this.e = entry;
    this.v = false;
    this.n = this.p = null;
  }
  function d3_geo_clip(pointVisible, clipLine, interpolate, clipStart) {
    return function(rotate, listener) {
      var line = clipLine(listener), rotatedClipStart = rotate.invert(clipStart[0], clipStart[1]);
      var clip = {
        point: point,
        lineStart: lineStart,
        lineEnd: lineEnd,
        polygonStart: function() {
          clip.point = pointRing;
          clip.lineStart = ringStart;
          clip.lineEnd = ringEnd;
          segments = [];
          polygon = [];
        },
        polygonEnd: function() {
          clip.point = point;
          clip.lineStart = lineStart;
          clip.lineEnd = lineEnd;
          segments = d3.merge(segments);
          var clipStartInside = d3_geo_pointInPolygon(rotatedClipStart, polygon);
          if (segments.length) {
            if (!polygonStarted) listener.polygonStart(), polygonStarted = true;
            d3_geo_clipPolygon(segments, d3_geo_clipSort, clipStartInside, interpolate, listener);
          } else if (clipStartInside) {
            if (!polygonStarted) listener.polygonStart(), polygonStarted = true;
            listener.lineStart();
            interpolate(null, null, 1, listener);
            listener.lineEnd();
          }
          if (polygonStarted) listener.polygonEnd(), polygonStarted = false;
          segments = polygon = null;
        },
        sphere: function() {
          listener.polygonStart();
          listener.lineStart();
          interpolate(null, null, 1, listener);
          listener.lineEnd();
          listener.polygonEnd();
        }
      };
      function point(λ, φ) {
        var point = rotate(λ, φ);
        if (pointVisible(λ = point[0], φ = point[1])) listener.point(λ, φ);
      }
      function pointLine(λ, φ) {
        var point = rotate(λ, φ);
        line.point(point[0], point[1]);
      }
      function lineStart() {
        clip.point = pointLine;
        line.lineStart();
      }
      function lineEnd() {
        clip.point = point;
        line.lineEnd();
      }
      var segments;
      var buffer = d3_geo_clipBufferListener(), ringListener = clipLine(buffer), polygonStarted = false, polygon, ring;
      function pointRing(λ, φ) {
        ring.push([ λ, φ ]);
        var point = rotate(λ, φ);
        ringListener.point(point[0], point[1]);
      }
      function ringStart() {
        ringListener.lineStart();
        ring = [];
      }
      function ringEnd() {
        pointRing(ring[0][0], ring[0][1]);
        ringListener.lineEnd();
        var clean = ringListener.clean(), ringSegments = buffer.buffer(), segment, n = ringSegments.length;
        ring.pop();
        polygon.push(ring);
        ring = null;
        if (!n) return;
        if (clean & 1) {
          segment = ringSegments[0];
          var n = segment.length - 1, i = -1, point;
          if (n > 0) {
            if (!polygonStarted) listener.polygonStart(), polygonStarted = true;
            listener.lineStart();
            while (++i < n) listener.point((point = segment[i])[0], point[1]);
            listener.lineEnd();
          }
          return;
        }
        if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift()));
        segments.push(ringSegments.filter(d3_geo_clipSegmentLength1));
      }
      return clip;
    };
  }
  function d3_geo_clipSegmentLength1(segment) {
    return segment.length > 1;
  }
  function d3_geo_clipBufferListener() {
    var lines = [], line;
    return {
      lineStart: function() {
        lines.push(line = []);
      },
      point: function(λ, φ) {
        line.push([ λ, φ ]);
      },
      lineEnd: d3_noop,
      buffer: function() {
        var buffer = lines;
        lines = [];
        line = null;
        return buffer;
      },
      rejoin: function() {
        if (lines.length > 1) lines.push(lines.pop().concat(lines.shift()));
      }
    };
  }
  function d3_geo_clipSort(a, b) {
    return ((a = a.x)[0] < 0 ? a[1] - halfπ - ε : halfπ - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfπ - ε : halfπ - b[1]);
  }
  var d3_geo_clipAntimeridian = d3_geo_clip(d3_true, d3_geo_clipAntimeridianLine, d3_geo_clipAntimeridianInterpolate, [ -π, -π / 2 ]);
  function d3_geo_clipAntimeridianLine(listener) {
    var λ0 = NaN, φ0 = NaN, sλ0 = NaN, clean;
    return {
      lineStart: function() {
        listener.lineStart();
        clean = 1;
      },
      point: function(λ1, φ1) {
        var sλ1 = λ1 > 0 ? π : -π, dλ = abs(λ1 - λ0);
        if (abs(dλ - π) < ε) {
          listener.point(λ0, φ0 = (φ0 + φ1) / 2 > 0 ? halfπ : -halfπ);
          listener.point(sλ0, φ0);
          listener.lineEnd();
          listener.lineStart();
          listener.point(sλ1, φ0);
          listener.point(λ1, φ0);
          clean = 0;
        } else if (sλ0 !== sλ1 && dλ >= π) {
          if (abs(λ0 - sλ0) < ε) λ0 -= sλ0 * ε;
          if (abs(λ1 - sλ1) < ε) λ1 -= sλ1 * ε;
          φ0 = d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1);
          listener.point(sλ0, φ0);
          listener.lineEnd();
          listener.lineStart();
          listener.point(sλ1, φ0);
          clean = 0;
        }
        listener.point(λ0 = λ1, φ0 = φ1);
        sλ0 = sλ1;
      },
      lineEnd: function() {
        listener.lineEnd();
        λ0 = φ0 = NaN;
      },
      clean: function() {
        return 2 - clean;
      }
    };
  }
  function d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1) {
    var cosφ0, cosφ1, sinλ0_λ1 = Math.sin(λ0 - λ1);
    return abs(sinλ0_λ1) > ε ? Math.atan((Math.sin(φ0) * (cosφ1 = Math.cos(φ1)) * Math.sin(λ1) - Math.sin(φ1) * (cosφ0 = Math.cos(φ0)) * Math.sin(λ0)) / (cosφ0 * cosφ1 * sinλ0_λ1)) : (φ0 + φ1) / 2;
  }
  function d3_geo_clipAntimeridianInterpolate(from, to, direction, listener) {
    var φ;
    if (from == null) {
      φ = direction * halfπ;
      listener.point(-π, φ);
      listener.point(0, φ);
      listener.point(π, φ);
      listener.point(π, 0);
      listener.point(π, -φ);
      listener.point(0, -φ);
      listener.point(-π, -φ);
      listener.point(-π, 0);
      listener.point(-π, φ);
    } else if (abs(from[0] - to[0]) > ε) {
      var s = from[0] < to[0] ? π : -π;
      φ = direction * s / 2;
      listener.point(-s, φ);
      listener.point(0, φ);
      listener.point(s, φ);
    } else {
      listener.point(to[0], to[1]);
    }
  }
  function d3_geo_pointInPolygon(point, polygon) {
    var meridian = point[0], parallel = point[1], meridianNormal = [ Math.sin(meridian), -Math.cos(meridian), 0 ], polarAngle = 0, winding = 0;
    d3_geo_areaRingSum.reset();
    for (var i = 0, n = polygon.length; i < n; ++i) {
      var ring = polygon[i], m = ring.length;
      if (!m) continue;
      var point0 = ring[0], λ0 = point0[0], φ0 = point0[1] / 2 + π / 4, sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), j = 1;
      while (true) {
        if (j === m) j = 0;
        point = ring[j];
        var λ = point[0], φ = point[1] / 2 + π / 4, sinφ = Math.sin(φ), cosφ = Math.cos(φ), dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, antimeridian = adλ > π, k = sinφ0 * sinφ;
        d3_geo_areaRingSum.add(Math.atan2(k * sdλ * Math.sin(adλ), cosφ0 * cosφ + k * Math.cos(adλ)));
        polarAngle += antimeridian ? dλ + sdλ * τ : dλ;
        if (antimeridian ^ λ0 >= meridian ^ λ >= meridian) {
          var arc = d3_geo_cartesianCross(d3_geo_cartesian(point0), d3_geo_cartesian(point));
          d3_geo_cartesianNormalize(arc);
          var intersection = d3_geo_cartesianCross(meridianNormal, arc);
          d3_geo_cartesianNormalize(intersection);
          var φarc = (antimeridian ^ dλ >= 0 ? -1 : 1) * d3_asin(intersection[2]);
          if (parallel > φarc || parallel === φarc && (arc[0] || arc[1])) {
            winding += antimeridian ^ dλ >= 0 ? 1 : -1;
          }
        }
        if (!j++) break;
        λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ, point0 = point;
      }
    }
    return (polarAngle < -ε || polarAngle < ε && d3_geo_areaRingSum < -ε) ^ winding & 1;
  }
  function d3_geo_clipCircle(radius) {
    var cr = Math.cos(radius), smallRadius = cr > 0, notHemisphere = abs(cr) > ε, interpolate = d3_geo_circleInterpolate(radius, 6 * d3_radians);
    return d3_geo_clip(visible, clipLine, interpolate, smallRadius ? [ 0, -radius ] : [ -π, radius - π ]);
    function visible(λ, φ) {
      return Math.cos(λ) * Math.cos(φ) > cr;
    }
    function clipLine(listener) {
      var point0, c0, v0, v00, clean;
      return {
        lineStart: function() {
          v00 = v0 = false;
          clean = 1;
        },
        point: function(λ, φ) {
          var point1 = [ λ, φ ], point2, v = visible(λ, φ), c = smallRadius ? v ? 0 : code(λ, φ) : v ? code(λ + (λ < 0 ? π : -π), φ) : 0;
          if (!point0 && (v00 = v0 = v)) listener.lineStart();
          if (v !== v0) {
            point2 = intersect(point0, point1);
            if (d3_geo_sphericalEqual(point0, point2) || d3_geo_sphericalEqual(point1, point2)) {
              point1[0] += ε;
              point1[1] += ε;
              v = visible(point1[0], point1[1]);
            }
          }
          if (v !== v0) {
            clean = 0;
            if (v) {
              listener.lineStart();
              point2 = intersect(point1, point0);
              listener.point(point2[0], point2[1]);
            } else {
              point2 = intersect(point0, point1);
              listener.point(point2[0], point2[1]);
              listener.lineEnd();
            }
            point0 = point2;
          } else if (notHemisphere && point0 && smallRadius ^ v) {
            var t;
            if (!(c & c0) && (t = intersect(point1, point0, true))) {
              clean = 0;
              if (smallRadius) {
                listener.lineStart();
                listener.point(t[0][0], t[0][1]);
                listener.point(t[1][0], t[1][1]);
                listener.lineEnd();
              } else {
                listener.point(t[1][0], t[1][1]);
                listener.lineEnd();
                listener.lineStart();
                listener.point(t[0][0], t[0][1]);
              }
            }
          }
          if (v && (!point0 || !d3_geo_sphericalEqual(point0, point1))) {
            listener.point(point1[0], point1[1]);
          }
          point0 = point1, v0 = v, c0 = c;
        },
        lineEnd: function() {
          if (v0) listener.lineEnd();
          point0 = null;
        },
        clean: function() {
          return clean | (v00 && v0) << 1;
        }
      };
    }
    function intersect(a, b, two) {
      var pa = d3_geo_cartesian(a), pb = d3_geo_cartesian(b);
      var n1 = [ 1, 0, 0 ], n2 = d3_geo_cartesianCross(pa, pb), n2n2 = d3_geo_cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2;
      if (!determinant) return !two && a;
      var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = d3_geo_cartesianCross(n1, n2), A = d3_geo_cartesianScale(n1, c1), B = d3_geo_cartesianScale(n2, c2);
      d3_geo_cartesianAdd(A, B);
      var u = n1xn2, w = d3_geo_cartesianDot(A, u), uu = d3_geo_cartesianDot(u, u), t2 = w * w - uu * (d3_geo_cartesianDot(A, A) - 1);
      if (t2 < 0) return;
      var t = Math.sqrt(t2), q = d3_geo_cartesianScale(u, (-w - t) / uu);
      d3_geo_cartesianAdd(q, A);
      q = d3_geo_spherical(q);
      if (!two) return q;
      var λ0 = a[0], λ1 = b[0], φ0 = a[1], φ1 = b[1], z;
      if (λ1 < λ0) z = λ0, λ0 = λ1, λ1 = z;
      var δλ = λ1 - λ0, polar = abs(δλ - π) < ε, meridian = polar || δλ < ε;
      if (!polar && φ1 < φ0) z = φ0, φ0 = φ1, φ1 = z;
      if (meridian ? polar ? φ0 + φ1 > 0 ^ q[1] < (abs(q[0] - λ0) < ε ? φ0 : φ1) : φ0 <= q[1] && q[1] <= φ1 : δλ > π ^ (λ0 <= q[0] && q[0] <= λ1)) {
        var q1 = d3_geo_cartesianScale(u, (-w + t) / uu);
        d3_geo_cartesianAdd(q1, A);
        return [ q, d3_geo_spherical(q1) ];
      }
    }
    function code(λ, φ) {
      var r = smallRadius ? radius : π - radius, code = 0;
      if (λ < -r) code |= 1; else if (λ > r) code |= 2;
      if (φ < -r) code |= 4; else if (φ > r) code |= 8;
      return code;
    }
  }
  function d3_geom_clipLine(x0, y0, x1, y1) {
    return function(line) {
      var a = line.a, b = line.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay, r;
      r = x0 - ax;
      if (!dx && r > 0) return;
      r /= dx;
      if (dx < 0) {
        if (r < t0) return;
        if (r < t1) t1 = r;
      } else if (dx > 0) {
        if (r > t1) return;
        if (r > t0) t0 = r;
      }
      r = x1 - ax;
      if (!dx && r < 0) return;
      r /= dx;
      if (dx < 0) {
        if (r > t1) return;
        if (r > t0) t0 = r;
      } else if (dx > 0) {
        if (r < t0) return;
        if (r < t1) t1 = r;
      }
      r = y0 - ay;
      if (!dy && r > 0) return;
      r /= dy;
      if (dy < 0) {
        if (r < t0) return;
        if (r < t1) t1 = r;
      } else if (dy > 0) {
        if (r > t1) return;
        if (r > t0) t0 = r;
      }
      r = y1 - ay;
      if (!dy && r < 0) return;
      r /= dy;
      if (dy < 0) {
        if (r > t1) return;
        if (r > t0) t0 = r;
      } else if (dy > 0) {
        if (r < t0) return;
        if (r < t1) t1 = r;
      }
      if (t0 > 0) line.a = {
        x: ax + t0 * dx,
        y: ay + t0 * dy
      };
      if (t1 < 1) line.b = {
        x: ax + t1 * dx,
        y: ay + t1 * dy
      };
      return line;
    };
  }
  var d3_geo_clipExtentMAX = 1e9;
  d3.geo.clipExtent = function() {
    var x0, y0, x1, y1, stream, clip, clipExtent = {
      stream: function(output) {
        if (stream) stream.valid = false;
        stream = clip(output);
        stream.valid = true;
        return stream;
      },
      extent: function(_) {
        if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ];
        clip = d3_geo_clipExtent(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]);
        if (stream) stream.valid = false, stream = null;
        return clipExtent;
      }
    };
    return clipExtent.extent([ [ 0, 0 ], [ 960, 500 ] ]);
  };
  function d3_geo_clipExtent(x0, y0, x1, y1) {
    return function(listener) {
      var listener_ = listener, bufferListener = d3_geo_clipBufferListener(), clipLine = d3_geom_clipLine(x0, y0, x1, y1), segments, polygon, ring;
      var clip = {
        point: point,
        lineStart: lineStart,
        lineEnd: lineEnd,
        polygonStart: function() {
          listener = bufferListener;
          segments = [];
          polygon = [];
          clean = true;
        },
        polygonEnd: function() {
          listener = listener_;
          segments = d3.merge(segments);
          var clipStartInside = insidePolygon([ x0, y1 ]), inside = clean && clipStartInside, visible = segments.length;
          if (inside || visible) {
            listener.polygonStart();
            if (inside) {
              listener.lineStart();
              interpolate(null, null, 1, listener);
              listener.lineEnd();
            }
            if (visible) {
              d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener);
            }
            listener.polygonEnd();
          }
          segments = polygon = ring = null;
        }
      };
      function insidePolygon(p) {
        var wn = 0, n = polygon.length, y = p[1];
        for (var i = 0; i < n; ++i) {
          for (var j = 1, v = polygon[i], m = v.length, a = v[0], b; j < m; ++j) {
            b = v[j];
            if (a[1] <= y) {
              if (b[1] > y && d3_cross2d(a, b, p) > 0) ++wn;
            } else {
              if (b[1] <= y && d3_cross2d(a, b, p) < 0) --wn;
            }
            a = b;
          }
        }
        return wn !== 0;
      }
      function interpolate(from, to, direction, listener) {
        var a = 0, a1 = 0;
        if (from == null || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoints(from, to) < 0 ^ direction > 0) {
          do {
            listener.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0);
          } while ((a = (a + direction + 4) % 4) !== a1);
        } else {
          listener.point(to[0], to[1]);
        }
      }
      function pointVisible(x, y) {
        return x0 <= x && x <= x1 && y0 <= y && y <= y1;
      }
      function point(x, y) {
        if (pointVisible(x, y)) listener.point(x, y);
      }
      var x__, y__, v__, x_, y_, v_, first, clean;
      function lineStart() {
        clip.point = linePoint;
        if (polygon) polygon.push(ring = []);
        first = true;
        v_ = false;
        x_ = y_ = NaN;
      }
      function lineEnd() {
        if (segments) {
          linePoint(x__, y__);
          if (v__ && v_) bufferListener.rejoin();
          segments.push(bufferListener.buffer());
        }
        clip.point = point;
        if (v_) listener.lineEnd();
      }
      function linePoint(x, y) {
        x = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, x));
        y = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, y));
        var v = pointVisible(x, y);
        if (polygon) ring.push([ x, y ]);
        if (first) {
          x__ = x, y__ = y, v__ = v;
          first = false;
          if (v) {
            listener.lineStart();
            listener.point(x, y);
          }
        } else {
          if (v && v_) listener.point(x, y); else {
            var l = {
              a: {
                x: x_,
                y: y_
              },
              b: {
                x: x,
                y: y
              }
            };
            if (clipLine(l)) {
              if (!v_) {
                listener.lineStart();
                listener.point(l.a.x, l.a.y);
              }
              listener.point(l.b.x, l.b.y);
              if (!v) listener.lineEnd();
              clean = false;
            } else if (v) {
              listener.lineStart();
              listener.point(x, y);
              clean = false;
            }
          }
        }
        x_ = x, y_ = y, v_ = v;
      }
      return clip;
    };
    function corner(p, direction) {
      return abs(p[0] - x0) < ε ? direction > 0 ? 0 : 3 : abs(p[0] - x1) < ε ? direction > 0 ? 2 : 1 : abs(p[1] - y0) < ε ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2;
    }
    function compare(a, b) {
      return comparePoints(a.x, b.x);
    }
    function comparePoints(a, b) {
      var ca = corner(a, 1), cb = corner(b, 1);
      return ca !== cb ? ca - cb : ca === 0 ? b[1] - a[1] : ca === 1 ? a[0] - b[0] : ca === 2 ? a[1] - b[1] : b[0] - a[0];
    }
  }
  function d3_geo_conic(projectAt) {
    var φ0 = 0, φ1 = π / 3, m = d3_geo_projectionMutator(projectAt), p = m(φ0, φ1);
    p.parallels = function(_) {
      if (!arguments.length) return [ φ0 / π * 180, φ1 / π * 180 ];
      return m(φ0 = _[0] * π / 180, φ1 = _[1] * π / 180);
    };
    return p;
  }
  function d3_geo_conicEqualArea(φ0, φ1) {
    var sinφ0 = Math.sin(φ0), n = (sinφ0 + Math.sin(φ1)) / 2, C = 1 + sinφ0 * (2 * n - sinφ0), ρ0 = Math.sqrt(C) / n;
    function forward(λ, φ) {
      var ρ = Math.sqrt(C - 2 * n * Math.sin(φ)) / n;
      return [ ρ * Math.sin(λ *= n), ρ0 - ρ * Math.cos(λ) ];
    }
    forward.invert = function(x, y) {
      var ρ0_y = ρ0 - y;
      return [ Math.atan2(x, ρ0_y) / n, d3_asin((C - (x * x + ρ0_y * ρ0_y) * n * n) / (2 * n)) ];
    };
    return forward;
  }
  (d3.geo.conicEqualArea = function() {
    return d3_geo_conic(d3_geo_conicEqualArea);
  }).raw = d3_geo_conicEqualArea;
  d3.geo.albers = function() {
    return d3.geo.conicEqualArea().rotate([ 96, 0 ]).center([ -.6, 38.7 ]).parallels([ 29.5, 45.5 ]).scale(1070);
  };
  d3.geo.albersUsa = function() {
    var lower48 = d3.geo.albers();
    var alaska = d3.geo.conicEqualArea().rotate([ 154, 0 ]).center([ -2, 58.5 ]).parallels([ 55, 65 ]);
    var hawaii = d3.geo.conicEqualArea().rotate([ 157, 0 ]).center([ -3, 19.9 ]).parallels([ 8, 18 ]);
    var point, pointStream = {
      point: function(x, y) {
        point = [ x, y ];
      }
    }, lower48Point, alaskaPoint, hawaiiPoint;
    function albersUsa(coordinates) {
      var x = coordinates[0], y = coordinates[1];
      point = null;
      (lower48Point(x, y), point) || (alaskaPoint(x, y), point) || hawaiiPoint(x, y);
      return point;
    }
    albersUsa.invert = function(coordinates) {
      var k = lower48.scale(), t = lower48.translate(), x = (coordinates[0] - t[0]) / k, y = (coordinates[1] - t[1]) / k;
      return (y >= .12 && y < .234 && x >= -.425 && x < -.214 ? alaska : y >= .166 && y < .234 && x >= -.214 && x < -.115 ? hawaii : lower48).invert(coordinates);
    };
    albersUsa.stream = function(stream) {
      var lower48Stream = lower48.stream(stream), alaskaStream = alaska.stream(stream), hawaiiStream = hawaii.stream(stream);
      return {
        point: function(x, y) {
          lower48Stream.point(x, y);
          alaskaStream.point(x, y);
          hawaiiStream.point(x, y);
        },
        sphere: function() {
          lower48Stream.sphere();
          alaskaStream.sphere();
          hawaiiStream.sphere();
        },
        lineStart: function() {
          lower48Stream.lineStart();
          alaskaStream.lineStart();
          hawaiiStream.lineStart();
        },
        lineEnd: function() {
          lower48Stream.lineEnd();
          alaskaStream.lineEnd();
          hawaiiStream.lineEnd();
        },
        polygonStart: function() {
          lower48Stream.polygonStart();
          alaskaStream.polygonStart();
          hawaiiStream.polygonStart();
        },
        polygonEnd: function() {
          lower48Stream.polygonEnd();
          alaskaStream.polygonEnd();
          hawaiiStream.polygonEnd();
        }
      };
    };
    albersUsa.precision = function(_) {
      if (!arguments.length) return lower48.precision();
      lower48.precision(_);
      alaska.precision(_);
      hawaii.precision(_);
      return albersUsa;
    };
    albersUsa.scale = function(_) {
      if (!arguments.length) return lower48.scale();
      lower48.scale(_);
      alaska.scale(_ * .35);
      hawaii.scale(_);
      return albersUsa.translate(lower48.translate());
    };
    albersUsa.translate = function(_) {
      if (!arguments.length) return lower48.translate();
      var k = lower48.scale(), x = +_[0], y = +_[1];
      lower48Point = lower48.translate(_).clipExtent([ [ x - .455 * k, y - .238 * k ], [ x + .455 * k, y + .238 * k ] ]).stream(pointStream).point;
      alaskaPoint = alaska.translate([ x - .307 * k, y + .201 * k ]).clipExtent([ [ x - .425 * k + ε, y + .12 * k + ε ], [ x - .214 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point;
      hawaiiPoint = hawaii.translate([ x - .205 * k, y + .212 * k ]).clipExtent([ [ x - .214 * k + ε, y + .166 * k + ε ], [ x - .115 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point;
      return albersUsa;
    };
    return albersUsa.scale(1070);
  };
  var d3_geo_pathAreaSum, d3_geo_pathAreaPolygon, d3_geo_pathArea = {
    point: d3_noop,
    lineStart: d3_noop,
    lineEnd: d3_noop,
    polygonStart: function() {
      d3_geo_pathAreaPolygon = 0;
      d3_geo_pathArea.lineStart = d3_geo_pathAreaRingStart;
    },
    polygonEnd: function() {
      d3_geo_pathArea.lineStart = d3_geo_pathArea.lineEnd = d3_geo_pathArea.point = d3_noop;
      d3_geo_pathAreaSum += abs(d3_geo_pathAreaPolygon / 2);
    }
  };
  function d3_geo_pathAreaRingStart() {
    var x00, y00, x0, y0;
    d3_geo_pathArea.point = function(x, y) {
      d3_geo_pathArea.point = nextPoint;
      x00 = x0 = x, y00 = y0 = y;
    };
    function nextPoint(x, y) {
      d3_geo_pathAreaPolygon += y0 * x - x0 * y;
      x0 = x, y0 = y;
    }
    d3_geo_pathArea.lineEnd = function() {
      nextPoint(x00, y00);
    };
  }
  var d3_geo_pathBoundsX0, d3_geo_pathBoundsY0, d3_geo_pathBoundsX1, d3_geo_pathBoundsY1;
  var d3_geo_pathBounds = {
    point: d3_geo_pathBoundsPoint,
    lineStart: d3_noop,
    lineEnd: d3_noop,
    polygonStart: d3_noop,
    polygonEnd: d3_noop
  };
  function d3_geo_pathBoundsPoint(x, y) {
    if (x < d3_geo_pathBoundsX0) d3_geo_pathBoundsX0 = x;
    if (x > d3_geo_pathBoundsX1) d3_geo_pathBoundsX1 = x;
    if (y < d3_geo_pathBoundsY0) d3_geo_pathBoundsY0 = y;
    if (y > d3_geo_pathBoundsY1) d3_geo_pathBoundsY1 = y;
  }
  function d3_geo_pathBuffer() {
    var pointCircle = d3_geo_pathBufferCircle(4.5), buffer = [];
    var stream = {
      point: point,
      lineStart: function() {
        stream.point = pointLineStart;
      },
      lineEnd: lineEnd,
      polygonStart: function() {
        stream.lineEnd = lineEndPolygon;
      },
      polygonEnd: function() {
        stream.lineEnd = lineEnd;
        stream.point = point;
      },
      pointRadius: function(_) {
        pointCircle = d3_geo_pathBufferCircle(_);
        return stream;
      },
      result: function() {
        if (buffer.length) {
          var result = buffer.join("");
          buffer = [];
          return result;
        }
      }
    };
    function point(x, y) {
      buffer.push("M", x, ",", y, pointCircle);
    }
    function pointLineStart(x, y) {
      buffer.push("M", x, ",", y);
      stream.point = pointLine;
    }
    function pointLine(x, y) {
      buffer.push("L", x, ",", y);
    }
    function lineEnd() {
      stream.point = point;
    }
    function lineEndPolygon() {
      buffer.push("Z");
    }
    return stream;
  }
  function d3_geo_pathBufferCircle(radius) {
    return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius + "z";
  }
  var d3_geo_pathCentroid = {
    point: d3_geo_pathCentroidPoint,
    lineStart: d3_geo_pathCentroidLineStart,
    lineEnd: d3_geo_pathCentroidLineEnd,
    polygonStart: function() {
      d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidRingStart;
    },
    polygonEnd: function() {
      d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint;
      d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidLineStart;
      d3_geo_pathCentroid.lineEnd = d3_geo_pathCentroidLineEnd;
    }
  };
  function d3_geo_pathCentroidPoint(x, y) {
    d3_geo_centroidX0 += x;
    d3_geo_centroidY0 += y;
    ++d3_geo_centroidZ0;
  }
  function d3_geo_pathCentroidLineStart() {
    var x0, y0;
    d3_geo_pathCentroid.point = function(x, y) {
      d3_geo_pathCentroid.point = nextPoint;
      d3_geo_pathCentroidPoint(x0 = x, y0 = y);
    };
    function nextPoint(x, y) {
      var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy);
      d3_geo_centroidX1 += z * (x0 + x) / 2;
      d3_geo_centroidY1 += z * (y0 + y) / 2;
      d3_geo_centroidZ1 += z;
      d3_geo_pathCentroidPoint(x0 = x, y0 = y);
    }
  }
  function d3_geo_pathCentroidLineEnd() {
    d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint;
  }
  function d3_geo_pathCentroidRingStart() {
    var x00, y00, x0, y0;
    d3_geo_pathCentroid.point = function(x, y) {
      d3_geo_pathCentroid.point = nextPoint;
      d3_geo_pathCentroidPoint(x00 = x0 = x, y00 = y0 = y);
    };
    function nextPoint(x, y) {
      var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy);
      d3_geo_centroidX1 += z * (x0 + x) / 2;
      d3_geo_centroidY1 += z * (y0 + y) / 2;
      d3_geo_centroidZ1 += z;
      z = y0 * x - x0 * y;
      d3_geo_centroidX2 += z * (x0 + x);
      d3_geo_centroidY2 += z * (y0 + y);
      d3_geo_centroidZ2 += z * 3;
      d3_geo_pathCentroidPoint(x0 = x, y0 = y);
    }
    d3_geo_pathCentroid.lineEnd = function() {
      nextPoint(x00, y00);
    };
  }
  function d3_geo_pathContext(context) {
    var pointRadius = 4.5;
    var stream = {
      point: point,
      lineStart: function() {
        stream.point = pointLineStart;
      },
      lineEnd: lineEnd,
      polygonStart: function() {
        stream.lineEnd = lineEndPolygon;
      },
      polygonEnd: function() {
        stream.lineEnd = lineEnd;
        stream.point = point;
      },
      pointRadius: function(_) {
        pointRadius = _;
        return stream;
      },
      result: d3_noop
    };
    function point(x, y) {
      context.moveTo(x + pointRadius, y);
      context.arc(x, y, pointRadius, 0, τ);
    }
    function pointLineStart(x, y) {
      context.moveTo(x, y);
      stream.point = pointLine;
    }
    function pointLine(x, y) {
      context.lineTo(x, y);
    }
    function lineEnd() {
      stream.point = point;
    }
    function lineEndPolygon() {
      context.closePath();
    }
    return stream;
  }
  function d3_geo_resample(project) {
    var δ2 = .5, cosMinDistance = Math.cos(30 * d3_radians), maxDepth = 16;
    function resample(stream) {
      return (maxDepth ? resampleRecursive : resampleNone)(stream);
    }
    function resampleNone(stream) {
      return d3_geo_transformPoint(stream, function(x, y) {
        x = project(x, y);
        stream.point(x[0], x[1]);
      });
    }
    function resampleRecursive(stream) {
      var λ00, φ00, x00, y00, a00, b00, c00, λ0, x0, y0, a0, b0, c0;
      var resample = {
        point: point,
        lineStart: lineStart,
        lineEnd: lineEnd,
        polygonStart: function() {
          stream.polygonStart();
          resample.lineStart = ringStart;
        },
        polygonEnd: function() {
          stream.polygonEnd();
          resample.lineStart = lineStart;
        }
      };
      function point(x, y) {
        x = project(x, y);
        stream.point(x[0], x[1]);
      }
      function lineStart() {
        x0 = NaN;
        resample.point = linePoint;
        stream.lineStart();
      }
      function linePoint(λ, φ) {
        var c = d3_geo_cartesian([ λ, φ ]), p = project(λ, φ);
        resampleLineTo(x0, y0, λ0, a0, b0, c0, x0 = p[0], y0 = p[1], λ0 = λ, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream);
        stream.point(x0, y0);
      }
      function lineEnd() {
        resample.point = point;
        stream.lineEnd();
      }
      function ringStart() {
        lineStart();
        resample.point = ringPoint;
        resample.lineEnd = ringEnd;
      }
      function ringPoint(λ, φ) {
        linePoint(λ00 = λ, φ00 = φ), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0;
        resample.point = linePoint;
      }
      function ringEnd() {
        resampleLineTo(x0, y0, λ0, a0, b0, c0, x00, y00, λ00, a00, b00, c00, maxDepth, stream);
        resample.lineEnd = lineEnd;
        lineEnd();
      }
      return resample;
    }
    function resampleLineTo(x0, y0, λ0, a0, b0, c0, x1, y1, λ1, a1, b1, c1, depth, stream) {
      var dx = x1 - x0, dy = y1 - y0, d2 = dx * dx + dy * dy;
      if (d2 > 4 * δ2 && depth--) {
        var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = Math.sqrt(a * a + b * b + c * c), φ2 = Math.asin(c /= m), λ2 = abs(abs(c) - 1) < ε || abs(λ0 - λ1) < ε ? (λ0 + λ1) / 2 : Math.atan2(b, a), p = project(λ2, φ2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2;
        if (dz * dz / d2 > δ2 || abs((dx * dx2 + dy * dy2) / d2 - .5) > .3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) {
          resampleLineTo(x0, y0, λ0, a0, b0, c0, x2, y2, λ2, a /= m, b /= m, c, depth, stream);
          stream.point(x2, y2);
          resampleLineTo(x2, y2, λ2, a, b, c, x1, y1, λ1, a1, b1, c1, depth, stream);
        }
      }
    }
    resample.precision = function(_) {
      if (!arguments.length) return Math.sqrt(δ2);
      maxDepth = (δ2 = _ * _) > 0 && 16;
      return resample;
    };
    return resample;
  }
  d3.geo.path = function() {
    var pointRadius = 4.5, projection, context, projectStream, contextStream, cacheStream;
    function path(object) {
      if (object) {
        if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments));
        if (!cacheStream || !cacheStream.valid) cacheStream = projectStream(contextStream);
        d3.geo.stream(object, cacheStream);
      }
      return contextStream.result();
    }
    path.area = function(object) {
      d3_geo_pathAreaSum = 0;
      d3.geo.stream(object, projectStream(d3_geo_pathArea));
      return d3_geo_pathAreaSum;
    };
    path.centroid = function(object) {
      d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0;
      d3.geo.stream(object, projectStream(d3_geo_pathCentroid));
      return d3_geo_centroidZ2 ? [ d3_geo_centroidX2 / d3_geo_centroidZ2, d3_geo_centroidY2 / d3_geo_centroidZ2 ] : d3_geo_centroidZ1 ? [ d3_geo_centroidX1 / d3_geo_centroidZ1, d3_geo_centroidY1 / d3_geo_centroidZ1 ] : d3_geo_centroidZ0 ? [ d3_geo_centroidX0 / d3_geo_centroidZ0, d3_geo_centroidY0 / d3_geo_centroidZ0 ] : [ NaN, NaN ];
    };
    path.bounds = function(object) {
      d3_geo_pathBoundsX1 = d3_geo_pathBoundsY1 = -(d3_geo_pathBoundsX0 = d3_geo_pathBoundsY0 = Infinity);
      d3.geo.stream(object, projectStream(d3_geo_pathBounds));
      return [ [ d3_geo_pathBoundsX0, d3_geo_pathBoundsY0 ], [ d3_geo_pathBoundsX1, d3_geo_pathBoundsY1 ] ];
    };
    path.projection = function(_) {
      if (!arguments.length) return projection;
      projectStream = (projection = _) ? _.stream || d3_geo_pathProjectStream(_) : d3_identity;
      return reset();
    };
    path.context = function(_) {
      if (!arguments.length) return context;
      contextStream = (context = _) == null ? new d3_geo_pathBuffer() : new d3_geo_pathContext(_);
      if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius);
      return reset();
    };
    path.pointRadius = function(_) {
      if (!arguments.length) return pointRadius;
      pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_);
      return path;
    };
    function reset() {
      cacheStream = null;
      return path;
    }
    return path.projection(d3.geo.albersUsa()).context(null);
  };
  function d3_geo_pathProjectStream(project) {
    var resample = d3_geo_resample(function(x, y) {
      return project([ x * d3_degrees, y * d3_degrees ]);
    });
    return function(stream) {
      return d3_geo_projectionRadians(resample(stream));
    };
  }
  d3.geo.transform = function(methods) {
    return {
      stream: function(stream) {
        var transform = new d3_geo_transform(stream);
        for (var k in methods) transform[k] = methods[k];
        return transform;
      }
    };
  };
  function d3_geo_transform(stream) {
    this.stream = stream;
  }
  d3_geo_transform.prototype = {
    point: function(x, y) {
      this.stream.point(x, y);
    },
    sphere: function() {
      this.stream.sphere();
    },
    lineStart: function() {
      this.stream.lineStart();
    },
    lineEnd: function() {
      this.stream.lineEnd();
    },
    polygonStart: function() {
      this.stream.polygonStart();
    },
    polygonEnd: function() {
      this.stream.polygonEnd();
    }
  };
  function d3_geo_transformPoint(stream, point) {
    return {
      point: point,
      sphere: function() {
        stream.sphere();
      },
      lineStart: function() {
        stream.lineStart();
      },
      lineEnd: function() {
        stream.lineEnd();
      },
      polygonStart: function() {
        stream.polygonStart();
      },
      polygonEnd: function() {
        stream.polygonEnd();
      }
    };
  }
  d3.geo.projection = d3_geo_projection;
  d3.geo.projectionMutator = d3_geo_projectionMutator;
  function d3_geo_projection(project) {
    return d3_geo_projectionMutator(function() {
      return project;
    })();
  }
  function d3_geo_projectionMutator(projectAt) {
    var project, rotate, projectRotate, projectResample = d3_geo_resample(function(x, y) {
      x = project(x, y);
      return [ x[0] * k + δx, δy - x[1] * k ];
    }), k = 150, x = 480, y = 250, λ = 0, φ = 0, δλ = 0, δφ = 0, δγ = 0, δx, δy, preclip = d3_geo_clipAntimeridian, postclip = d3_identity, clipAngle = null, clipExtent = null, stream;
    function projection(point) {
      point = projectRotate(point[0] * d3_radians, point[1] * d3_radians);
      return [ point[0] * k + δx, δy - point[1] * k ];
    }
    function invert(point) {
      point = projectRotate.invert((point[0] - δx) / k, (δy - point[1]) / k);
      return point && [ point[0] * d3_degrees, point[1] * d3_degrees ];
    }
    projection.stream = function(output) {
      if (stream) stream.valid = false;
      stream = d3_geo_projectionRadians(preclip(rotate, projectResample(postclip(output))));
      stream.valid = true;
      return stream;
    };
    projection.clipAngle = function(_) {
      if (!arguments.length) return clipAngle;
      preclip = _ == null ? (clipAngle = _, d3_geo_clipAntimeridian) : d3_geo_clipCircle((clipAngle = +_) * d3_radians);
      return invalidate();
    };
    projection.clipExtent = function(_) {
      if (!arguments.length) return clipExtent;
      clipExtent = _;
      postclip = _ ? d3_geo_clipExtent(_[0][0], _[0][1], _[1][0], _[1][1]) : d3_identity;
      return invalidate();
    };
    projection.scale = function(_) {
      if (!arguments.length) return k;
      k = +_;
      return reset();
    };
    projection.translate = function(_) {
      if (!arguments.length) return [ x, y ];
      x = +_[0];
      y = +_[1];
      return reset();
    };
    projection.center = function(_) {
      if (!arguments.length) return [ λ * d3_degrees, φ * d3_degrees ];
      λ = _[0] % 360 * d3_radians;
      φ = _[1] % 360 * d3_radians;
      return reset();
    };
    projection.rotate = function(_) {
      if (!arguments.length) return [ δλ * d3_degrees, δφ * d3_degrees, δγ * d3_degrees ];
      δλ = _[0] % 360 * d3_radians;
      δφ = _[1] % 360 * d3_radians;
      δγ = _.length > 2 ? _[2] % 360 * d3_radians : 0;
      return reset();
    };
    d3.rebind(projection, projectResample, "precision");
    function reset() {
      projectRotate = d3_geo_compose(rotate = d3_geo_rotation(δλ, δφ, δγ), project);
      var center = project(λ, φ);
      δx = x - center[0] * k;
      δy = y + center[1] * k;
      return invalidate();
    }
    function invalidate() {
      if (stream) stream.valid = false, stream = null;
      return projection;
    }
    return function() {
      project = projectAt.apply(this, arguments);
      projection.invert = project.invert && invert;
      return reset();
    };
  }
  function d3_geo_projectionRadians(stream) {
    return d3_geo_transformPoint(stream, function(x, y) {
      stream.point(x * d3_radians, y * d3_radians);
    });
  }
  function d3_geo_equirectangular(λ, φ) {
    return [ λ, φ ];
  }
  (d3.geo.equirectangular = function() {
    return d3_geo_projection(d3_geo_equirectangular);
  }).raw = d3_geo_equirectangular.invert = d3_geo_equirectangular;
  d3.geo.rotation = function(rotate) {
    rotate = d3_geo_rotation(rotate[0] % 360 * d3_radians, rotate[1] * d3_radians, rotate.length > 2 ? rotate[2] * d3_radians : 0);
    function forward(coordinates) {
      coordinates = rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians);
      return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates;
    }
    forward.invert = function(coordinates) {
      coordinates = rotate.invert(coordinates[0] * d3_radians, coordinates[1] * d3_radians);
      return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates;
    };
    return forward;
  };
  function d3_geo_identityRotation(λ, φ) {
    return [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ];
  }
  d3_geo_identityRotation.invert = d3_geo_equirectangular;
  function d3_geo_rotation(δλ, δφ, δγ) {
    return δλ ? δφ || δγ ? d3_geo_compose(d3_geo_rotationλ(δλ), d3_geo_rotationφγ(δφ, δγ)) : d3_geo_rotationλ(δλ) : δφ || δγ ? d3_geo_rotationφγ(δφ, δγ) : d3_geo_identityRotation;
  }
  function d3_geo_forwardRotationλ(δλ) {
    return function(λ, φ) {
      return λ += δλ, [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ];
    };
  }
  function d3_geo_rotationλ(δλ) {
    var rotation = d3_geo_forwardRotationλ(δλ);
    rotation.invert = d3_geo_forwardRotationλ(-δλ);
    return rotation;
  }
  function d3_geo_rotationφγ(δφ, δγ) {
    var cosδφ = Math.cos(δφ), sinδφ = Math.sin(δφ), cosδγ = Math.cos(δγ), sinδγ = Math.sin(δγ);
    function rotation(λ, φ) {
      var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδφ + x * sinδφ;
      return [ Math.atan2(y * cosδγ - k * sinδγ, x * cosδφ - z * sinδφ), d3_asin(k * cosδγ + y * sinδγ) ];
    }
    rotation.invert = function(λ, φ) {
      var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδγ - y * sinδγ;
      return [ Math.atan2(y * cosδγ + z * sinδγ, x * cosδφ + k * sinδφ), d3_asin(k * cosδφ - x * sinδφ) ];
    };
    return rotation;
  }
  d3.geo.circle = function() {
    var origin = [ 0, 0 ], angle, precision = 6, interpolate;
    function circle() {
      var center = typeof origin === "function" ? origin.apply(this, arguments) : origin, rotate = d3_geo_rotation(-center[0] * d3_radians, -center[1] * d3_radians, 0).invert, ring = [];
      interpolate(null, null, 1, {
        point: function(x, y) {
          ring.push(x = rotate(x, y));
          x[0] *= d3_degrees, x[1] *= d3_degrees;
        }
      });
      return {
        type: "Polygon",
        coordinates: [ ring ]
      };
    }
    circle.origin = function(x) {
      if (!arguments.length) return origin;
      origin = x;
      return circle;
    };
    circle.angle = function(x) {
      if (!arguments.length) return angle;
      interpolate = d3_geo_circleInterpolate((angle = +x) * d3_radians, precision * d3_radians);
      return circle;
    };
    circle.precision = function(_) {
      if (!arguments.length) return precision;
      interpolate = d3_geo_circleInterpolate(angle * d3_radians, (precision = +_) * d3_radians);
      return circle;
    };
    return circle.angle(90);
  };
  function d3_geo_circleInterpolate(radius, precision) {
    var cr = Math.cos(radius), sr = Math.sin(radius);
    return function(from, to, direction, listener) {
      var step = direction * precision;
      if (from != null) {
        from = d3_geo_circleAngle(cr, from);
        to = d3_geo_circleAngle(cr, to);
        if (direction > 0 ? from < to : from > to) from += direction * τ;
      } else {
        from = radius + direction * τ;
        to = radius - .5 * step;
      }
      for (var point, t = from; direction > 0 ? t > to : t < to; t -= step) {
        listener.point((point = d3_geo_spherical([ cr, -sr * Math.cos(t), -sr * Math.sin(t) ]))[0], point[1]);
      }
    };
  }
  function d3_geo_circleAngle(cr, point) {
    var a = d3_geo_cartesian(point);
    a[0] -= cr;
    d3_geo_cartesianNormalize(a);
    var angle = d3_acos(-a[1]);
    return ((-a[2] < 0 ? -angle : angle) + 2 * Math.PI - ε) % (2 * Math.PI);
  }
  d3.geo.distance = function(a, b) {
    var Δλ = (b[0] - a[0]) * d3_radians, φ0 = a[1] * d3_radians, φ1 = b[1] * d3_radians, sinΔλ = Math.sin(Δλ), cosΔλ = Math.cos(Δλ), sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), sinφ1 = Math.sin(φ1), cosφ1 = Math.cos(φ1), t;
    return Math.atan2(Math.sqrt((t = cosφ1 * sinΔλ) * t + (t = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * t), sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ);
  };
  d3.geo.graticule = function() {
    var x1, x0, X1, X0, y1, y0, Y1, Y0, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5;
    function graticule() {
      return {
        type: "MultiLineString",
        coordinates: lines()
      };
    }
    function lines() {
      return d3.range(Math.ceil(X0 / DX) * DX, X1, DX).map(X).concat(d3.range(Math.ceil(Y0 / DY) * DY, Y1, DY).map(Y)).concat(d3.range(Math.ceil(x0 / dx) * dx, x1, dx).filter(function(x) {
        return abs(x % DX) > ε;
      }).map(x)).concat(d3.range(Math.ceil(y0 / dy) * dy, y1, dy).filter(function(y) {
        return abs(y % DY) > ε;
      }).map(y));
    }
    graticule.lines = function() {
      return lines().map(function(coordinates) {
        return {
          type: "LineString",
          coordinates: coordinates
        };
      });
    };
    graticule.outline = function() {
      return {
        type: "Polygon",
        coordinates: [ X(X0).concat(Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1)) ]
      };
    };
    graticule.extent = function(_) {
      if (!arguments.length) return graticule.minorExtent();
      return graticule.majorExtent(_).minorExtent(_);
    };
    graticule.majorExtent = function(_) {
      if (!arguments.length) return [ [ X0, Y0 ], [ X1, Y1 ] ];
      X0 = +_[0][0], X1 = +_[1][0];
      Y0 = +_[0][1], Y1 = +_[1][1];
      if (X0 > X1) _ = X0, X0 = X1, X1 = _;
      if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _;
      return graticule.precision(precision);
    };
    graticule.minorExtent = function(_) {
      if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ];
      x0 = +_[0][0], x1 = +_[1][0];
      y0 = +_[0][1], y1 = +_[1][1];
      if (x0 > x1) _ = x0, x0 = x1, x1 = _;
      if (y0 > y1) _ = y0, y0 = y1, y1 = _;
      return graticule.precision(precision);
    };
    graticule.step = function(_) {
      if (!arguments.length) return graticule.minorStep();
      return graticule.majorStep(_).minorStep(_);
    };
    graticule.majorStep = function(_) {
      if (!arguments.length) return [ DX, DY ];
      DX = +_[0], DY = +_[1];
      return graticule;
    };
    graticule.minorStep = function(_) {
      if (!arguments.length) return [ dx, dy ];
      dx = +_[0], dy = +_[1];
      return graticule;
    };
    graticule.precision = function(_) {
      if (!arguments.length) return precision;
      precision = +_;
      x = d3_geo_graticuleX(y0, y1, 90);
      y = d3_geo_graticuleY(x0, x1, precision);
      X = d3_geo_graticuleX(Y0, Y1, 90);
      Y = d3_geo_graticuleY(X0, X1, precision);
      return graticule;
    };
    return graticule.majorExtent([ [ -180, -90 + ε ], [ 180, 90 - ε ] ]).minorExtent([ [ -180, -80 - ε ], [ 180, 80 + ε ] ]);
  };
  function d3_geo_graticuleX(y0, y1, dy) {
    var y = d3.range(y0, y1 - ε, dy).concat(y1);
    return function(x) {
      return y.map(function(y) {
        return [ x, y ];
      });
    };
  }
  function d3_geo_graticuleY(x0, x1, dx) {
    var x = d3.range(x0, x1 - ε, dx).concat(x1);
    return function(y) {
      return x.map(function(x) {
        return [ x, y ];
      });
    };
  }
  function d3_source(d) {
    return d.source;
  }
  function d3_target(d) {
    return d.target;
  }
  d3.geo.greatArc = function() {
    var source = d3_source, source_, target = d3_target, target_;
    function greatArc() {
      return {
        type: "LineString",
        coordinates: [ source_ || source.apply(this, arguments), target_ || target.apply(this, arguments) ]
      };
    }
    greatArc.distance = function() {
      return d3.geo.distance(source_ || source.apply(this, arguments), target_ || target.apply(this, arguments));
    };
    greatArc.source = function(_) {
      if (!arguments.length) return source;
      source = _, source_ = typeof _ === "function" ? null : _;
      return greatArc;
    };
    greatArc.target = function(_) {
      if (!arguments.length) return target;
      target = _, target_ = typeof _ === "function" ? null : _;
      return greatArc;
    };
    greatArc.precision = function() {
      return arguments.length ? greatArc : 0;
    };
    return greatArc;
  };
  d3.geo.interpolate = function(source, target) {
    return d3_geo_interpolate(source[0] * d3_radians, source[1] * d3_radians, target[0] * d3_radians, target[1] * d3_radians);
  };
  function d3_geo_interpolate(x0, y0, x1, y1) {
    var cy0 = Math.cos(y0), sy0 = Math.sin(y0), cy1 = Math.cos(y1), sy1 = Math.sin(y1), kx0 = cy0 * Math.cos(x0), ky0 = cy0 * Math.sin(x0), kx1 = cy1 * Math.cos(x1), ky1 = cy1 * Math.sin(x1), d = 2 * Math.asin(Math.sqrt(d3_haversin(y1 - y0) + cy0 * cy1 * d3_haversin(x1 - x0))), k = 1 / Math.sin(d);
    var interpolate = d ? function(t) {
      var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1;
      return [ Math.atan2(y, x) * d3_degrees, Math.atan2(z, Math.sqrt(x * x + y * y)) * d3_degrees ];
    } : function() {
      return [ x0 * d3_degrees, y0 * d3_degrees ];
    };
    interpolate.distance = d;
    return interpolate;
  }
  d3.geo.length = function(object) {
    d3_geo_lengthSum = 0;
    d3.geo.stream(object, d3_geo_length);
    return d3_geo_lengthSum;
  };
  var d3_geo_lengthSum;
  var d3_geo_length = {
    sphere: d3_noop,
    point: d3_noop,
    lineStart: d3_geo_lengthLineStart,
    lineEnd: d3_noop,
    polygonStart: d3_noop,
    polygonEnd: d3_noop
  };
  function d3_geo_lengthLineStart() {
    var λ0, sinφ0, cosφ0;
    d3_geo_length.point = function(λ, φ) {
      λ0 = λ * d3_radians, sinφ0 = Math.sin(φ *= d3_radians), cosφ0 = Math.cos(φ);
      d3_geo_length.point = nextPoint;
    };
    d3_geo_length.lineEnd = function() {
      d3_geo_length.point = d3_geo_length.lineEnd = d3_noop;
    };
    function nextPoint(λ, φ) {
      var sinφ = Math.sin(φ *= d3_radians), cosφ = Math.cos(φ), t = abs((λ *= d3_radians) - λ0), cosΔλ = Math.cos(t);
      d3_geo_lengthSum += Math.atan2(Math.sqrt((t = cosφ * Math.sin(t)) * t + (t = cosφ0 * sinφ - sinφ0 * cosφ * cosΔλ) * t), sinφ0 * sinφ + cosφ0 * cosφ * cosΔλ);
      λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ;
    }
  }
  function d3_geo_azimuthal(scale, angle) {
    function azimuthal(λ, φ) {
      var cosλ = Math.cos(λ), cosφ = Math.cos(φ), k = scale(cosλ * cosφ);
      return [ k * cosφ * Math.sin(λ), k * Math.sin(φ) ];
    }
    azimuthal.invert = function(x, y) {
      var ρ = Math.sqrt(x * x + y * y), c = angle(ρ), sinc = Math.sin(c), cosc = Math.cos(c);
      return [ Math.atan2(x * sinc, ρ * cosc), Math.asin(ρ && y * sinc / ρ) ];
    };
    return azimuthal;
  }
  var d3_geo_azimuthalEqualArea = d3_geo_azimuthal(function(cosλcosφ) {
    return Math.sqrt(2 / (1 + cosλcosφ));
  }, function(ρ) {
    return 2 * Math.asin(ρ / 2);
  });
  (d3.geo.azimuthalEqualArea = function() {
    return d3_geo_projection(d3_geo_azimuthalEqualArea);
  }).raw = d3_geo_azimuthalEqualArea;
  var d3_geo_azimuthalEquidistant = d3_geo_azimuthal(function(cosλcosφ) {
    var c = Math.acos(cosλcosφ);
    return c && c / Math.sin(c);
  }, d3_identity);
  (d3.geo.azimuthalEquidistant = function() {
    return d3_geo_projection(d3_geo_azimuthalEquidistant);
  }).raw = d3_geo_azimuthalEquidistant;
  function d3_geo_conicConformal(φ0, φ1) {
    var cosφ0 = Math.cos(φ0), t = function(φ) {
      return Math.tan(π / 4 + φ / 2);
    }, n = φ0 === φ1 ? Math.sin(φ0) : Math.log(cosφ0 / Math.cos(φ1)) / Math.log(t(φ1) / t(φ0)), F = cosφ0 * Math.pow(t(φ0), n) / n;
    if (!n) return d3_geo_mercator;
    function forward(λ, φ) {
      if (F > 0) {
        if (φ < -halfπ + ε) φ = -halfπ + ε;
      } else {
        if (φ > halfπ - ε) φ = halfπ - ε;
      }
      var ρ = F / Math.pow(t(φ), n);
      return [ ρ * Math.sin(n * λ), F - ρ * Math.cos(n * λ) ];
    }
    forward.invert = function(x, y) {
      var ρ0_y = F - y, ρ = d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y);
      return [ Math.atan2(x, ρ0_y) / n, 2 * Math.atan(Math.pow(F / ρ, 1 / n)) - halfπ ];
    };
    return forward;
  }
  (d3.geo.conicConformal = function() {
    return d3_geo_conic(d3_geo_conicConformal);
  }).raw = d3_geo_conicConformal;
  function d3_geo_conicEquidistant(φ0, φ1) {
    var cosφ0 = Math.cos(φ0), n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0), G = cosφ0 / n + φ0;
    if (abs(n) < ε) return d3_geo_equirectangular;
    function forward(λ, φ) {
      var ρ = G - φ;
      return [ ρ * Math.sin(n * λ), G - ρ * Math.cos(n * λ) ];
    }
    forward.invert = function(x, y) {
      var ρ0_y = G - y;
      return [ Math.atan2(x, ρ0_y) / n, G - d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y) ];
    };
    return forward;
  }
  (d3.geo.conicEquidistant = function() {
    return d3_geo_conic(d3_geo_conicEquidistant);
  }).raw = d3_geo_conicEquidistant;
  var d3_geo_gnomonic = d3_geo_azimuthal(function(cosλcosφ) {
    return 1 / cosλcosφ;
  }, Math.atan);
  (d3.geo.gnomonic = function() {
    return d3_geo_projection(d3_geo_gnomonic);
  }).raw = d3_geo_gnomonic;
  function d3_geo_mercator(λ, φ) {
    return [ λ, Math.log(Math.tan(π / 4 + φ / 2)) ];
  }
  d3_geo_mercator.invert = function(x, y) {
    return [ x, 2 * Math.atan(Math.exp(y)) - halfπ ];
  };
  function d3_geo_mercatorProjection(project) {
    var m = d3_geo_projection(project), scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, clipAuto;
    m.scale = function() {
      var v = scale.apply(m, arguments);
      return v === m ? clipAuto ? m.clipExtent(null) : m : v;
    };
    m.translate = function() {
      var v = translate.apply(m, arguments);
      return v === m ? clipAuto ? m.clipExtent(null) : m : v;
    };
    m.clipExtent = function(_) {
      var v = clipExtent.apply(m, arguments);
      if (v === m) {
        if (clipAuto = _ == null) {
          var k = π * scale(), t = translate();
          clipExtent([ [ t[0] - k, t[1] - k ], [ t[0] + k, t[1] + k ] ]);
        }
      } else if (clipAuto) {
        v = null;
      }
      return v;
    };
    return m.clipExtent(null);
  }
  (d3.geo.mercator = function() {
    return d3_geo_mercatorProjection(d3_geo_mercator);
  }).raw = d3_geo_mercator;
  var d3_geo_orthographic = d3_geo_azimuthal(function() {
    return 1;
  }, Math.asin);
  (d3.geo.orthographic = function() {
    return d3_geo_projection(d3_geo_orthographic);
  }).raw = d3_geo_orthographic;
  var d3_geo_stereographic = d3_geo_azimuthal(function(cosλcosφ) {
    return 1 / (1 + cosλcosφ);
  }, function(ρ) {
    return 2 * Math.atan(ρ);
  });
  (d3.geo.stereographic = function() {
    return d3_geo_projection(d3_geo_stereographic);
  }).raw = d3_geo_stereographic;
  function d3_geo_transverseMercator(λ, φ) {
    return [ Math.log(Math.tan(π / 4 + φ / 2)), -λ ];
  }
  d3_geo_transverseMercator.invert = function(x, y) {
    return [ -y, 2 * Math.atan(Math.exp(x)) - halfπ ];
  };
  (d3.geo.transverseMercator = function() {
    var projection = d3_geo_mercatorProjection(d3_geo_transverseMercator), center = projection.center, rotate = projection.rotate;
    projection.center = function(_) {
      return _ ? center([ -_[1], _[0] ]) : (_ = center(), [ _[1], -_[0] ]);
    };
    projection.rotate = function(_) {
      return _ ? rotate([ _[0], _[1], _.length > 2 ? _[2] + 90 : 90 ]) : (_ = rotate(), 
      [ _[0], _[1], _[2] - 90 ]);
    };
    return rotate([ 0, 0, 90 ]);
  }).raw = d3_geo_transverseMercator;
  d3.geom = {};
  function d3_geom_pointX(d) {
    return d[0];
  }
  function d3_geom_pointY(d) {
    return d[1];
  }
  d3.geom.hull = function(vertices) {
    var x = d3_geom_pointX, y = d3_geom_pointY;
    if (arguments.length) return hull(vertices);
    function hull(data) {
      if (data.length < 3) return [];
      var fx = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = [];
      for (i = 0; i < n; i++) {
        points.push([ +fx.call(this, data[i], i), +fy.call(this, data[i], i), i ]);
      }
      points.sort(d3_geom_hullOrder);
      for (i = 0; i < n; i++) flippedPoints.push([ points[i][0], -points[i][1] ]);
      var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints);
      var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon = [];
      for (i = upper.length - 1; i >= 0; --i) polygon.push(data[points[upper[i]][2]]);
      for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon.push(data[points[lower[i]][2]]);
      return polygon;
    }
    hull.x = function(_) {
      return arguments.length ? (x = _, hull) : x;
    };
    hull.y = function(_) {
      return arguments.length ? (y = _, hull) : y;
    };
    return hull;
  };
  function d3_geom_hullUpper(points) {
    var n = points.length, hull = [ 0, 1 ], hs = 2;
    for (var i = 2; i < n; i++) {
      while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs;
      hull[hs++] = i;
    }
    return hull.slice(0, hs);
  }
  function d3_geom_hullOrder(a, b) {
    return a[0] - b[0] || a[1] - b[1];
  }
  d3.geom.polygon = function(coordinates) {
    d3_subclass(coordinates, d3_geom_polygonPrototype);
    return coordinates;
  };
  var d3_geom_polygonPrototype = d3.geom.polygon.prototype = [];
  d3_geom_polygonPrototype.area = function() {
    var i = -1, n = this.length, a, b = this[n - 1], area = 0;
    while (++i < n) {
      a = b;
      b = this[i];
      area += a[1] * b[0] - a[0] * b[1];
    }
    return area * .5;
  };
  d3_geom_polygonPrototype.centroid = function(k) {
    var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c;
    if (!arguments.length) k = -1 / (6 * this.area());
    while (++i < n) {
      a = b;
      b = this[i];
      c = a[0] * b[1] - b[0] * a[1];
      x += (a[0] + b[0]) * c;
      y += (a[1] + b[1]) * c;
    }
    return [ x * k, y * k ];
  };
  d3_geom_polygonPrototype.clip = function(subject) {
    var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d;
    while (++i < n) {
      input = subject.slice();
      subject.length = 0;
      b = this[i];
      c = input[(m = input.length - closed) - 1];
      j = -1;
      while (++j < m) {
        d = input[j];
        if (d3_geom_polygonInside(d, a, b)) {
          if (!d3_geom_polygonInside(c, a, b)) {
            subject.push(d3_geom_polygonIntersect(c, d, a, b));
          }
          subject.push(d);
        } else if (d3_geom_polygonInside(c, a, b)) {
          subject.push(d3_geom_polygonIntersect(c, d, a, b));
        }
        c = d;
      }
      if (closed) subject.push(subject[0]);
      a = b;
    }
    return subject;
  };
  function d3_geom_polygonInside(p, a, b) {
    return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]);
  }
  function d3_geom_polygonIntersect(c, d, a, b) {
    var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21);
    return [ x1 + ua * x21, y1 + ua * y21 ];
  }
  function d3_geom_polygonClosed(coordinates) {
    var a = coordinates[0], b = coordinates[coordinates.length - 1];
    return !(a[0] - b[0] || a[1] - b[1]);
  }
  var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = [];
  function d3_geom_voronoiBeach() {
    d3_geom_voronoiRedBlackNode(this);
    this.edge = this.site = this.circle = null;
  }
  function d3_geom_voronoiCreateBeach(site) {
    var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach();
    beach.site = site;
    return beach;
  }
  function d3_geom_voronoiDetachBeach(beach) {
    d3_geom_voronoiDetachCircle(beach);
    d3_geom_voronoiBeaches.remove(beach);
    d3_geom_voronoiBeachPool.push(beach);
    d3_geom_voronoiRedBlackNode(beach);
  }
  function d3_geom_voronoiRemoveBeach(beach) {
    var circle = beach.circle, x = circle.x, y = circle.cy, vertex = {
      x: x,
      y: y
    }, previous = beach.P, next = beach.N, disappearing = [ beach ];
    d3_geom_voronoiDetachBeach(beach);
    var lArc = previous;
    while (lArc.circle && abs(x - lArc.circle.x) < ε && abs(y - lArc.circle.cy) < ε) {
      previous = lArc.P;
      disappearing.unshift(lArc);
      d3_geom_voronoiDetachBeach(lArc);
      lArc = previous;
    }
    disappearing.unshift(lArc);
    d3_geom_voronoiDetachCircle(lArc);
    var rArc = next;
    while (rArc.circle && abs(x - rArc.circle.x) < ε && abs(y - rArc.circle.cy) < ε) {
      next = rArc.N;
      disappearing.push(rArc);
      d3_geom_voronoiDetachBeach(rArc);
      rArc = next;
    }
    disappearing.push(rArc);
    d3_geom_voronoiDetachCircle(rArc);
    var nArcs = disappearing.length, iArc;
    for (iArc = 1; iArc < nArcs; ++iArc) {
      rArc = disappearing[iArc];
      lArc = disappearing[iArc - 1];
      d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex);
    }
    lArc = disappearing[0];
    rArc = disappearing[nArcs - 1];
    rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex);
    d3_geom_voronoiAttachCircle(lArc);
    d3_geom_voronoiAttachCircle(rArc);
  }
  function d3_geom_voronoiAddBeach(site) {
    var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._;
    while (node) {
      dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x;
      if (dxl > ε) node = node.L; else {
        dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix);
        if (dxr > ε) {
          if (!node.R) {
            lArc = node;
            break;
          }
          node = node.R;
        } else {
          if (dxl > -ε) {
            lArc = node.P;
            rArc = node;
          } else if (dxr > -ε) {
            lArc = node;
            rArc = node.N;
          } else {
            lArc = rArc = node;
          }
          break;
        }
      }
    }
    var newArc = d3_geom_voronoiCreateBeach(site);
    d3_geom_voronoiBeaches.insert(lArc, newArc);
    if (!lArc && !rArc) return;
    if (lArc === rArc) {
      d3_geom_voronoiDetachCircle(lArc);
      rArc = d3_geom_voronoiCreateBeach(lArc.site);
      d3_geom_voronoiBeaches.insert(newArc, rArc);
      newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site);
      d3_geom_voronoiAttachCircle(lArc);
      d3_geom_voronoiAttachCircle(rArc);
      return;
    }
    if (!rArc) {
      newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site);
      return;
    }
    d3_geom_voronoiDetachCircle(lArc);
    d3_geom_voronoiDetachCircle(rArc);
    var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = {
      x: (cy * hb - by * hc) / d + ax,
      y: (bx * hc - cx * hb) / d + ay
    };
    d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex);
    newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex);
    rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex);
    d3_geom_voronoiAttachCircle(lArc);
    d3_geom_voronoiAttachCircle(rArc);
  }
  function d3_geom_voronoiLeftBreakPoint(arc, directrix) {
    var site = arc.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix;
    if (!pby2) return rfocx;
    var lArc = arc.P;
    if (!lArc) return -Infinity;
    site = lArc.site;
    var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix;
    if (!plby2) return lfocx;
    var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2;
    if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx;
    return (rfocx + lfocx) / 2;
  }
  function d3_geom_voronoiRightBreakPoint(arc, directrix) {
    var rArc = arc.N;
    if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix);
    var site = arc.site;
    return site.y === directrix ? site.x : Infinity;
  }
  function d3_geom_voronoiCell(site) {
    this.site = site;
    this.edges = [];
  }
  d3_geom_voronoiCell.prototype.prepare = function() {
    var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge;
    while (iHalfEdge--) {
      edge = halfEdges[iHalfEdge].edge;
      if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1);
    }
    halfEdges.sort(d3_geom_voronoiHalfEdgeOrder);
    return halfEdges.length;
  };
  function d3_geom_voronoiCloseCells(extent) {
    var x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end;
    while (iCell--) {
      cell = cells[iCell];
      if (!cell || !cell.prepare()) continue;
      halfEdges = cell.edges;
      nHalfEdges = halfEdges.length;
      iHalfEdge = 0;
      while (iHalfEdge < nHalfEdges) {
        end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y;
        start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y;
        if (abs(x3 - x2) > ε || abs(y3 - y2) > ε) {
          halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < ε && y1 - y3 > ε ? {
            x: x0,
            y: abs(x2 - x0) < ε ? y2 : y1
          } : abs(y3 - y1) < ε && x1 - x3 > ε ? {
            x: abs(y2 - y1) < ε ? x2 : x1,
            y: y1
          } : abs(x3 - x1) < ε && y3 - y0 > ε ? {
            x: x1,
            y: abs(x2 - x1) < ε ? y2 : y0
          } : abs(y3 - y0) < ε && x3 - x0 > ε ? {
            x: abs(y2 - y0) < ε ? x2 : x0,
            y: y0
          } : null), cell.site, null));
          ++nHalfEdges;
        }
      }
    }
  }
  function d3_geom_voronoiHalfEdgeOrder(a, b) {
    return b.angle - a.angle;
  }
  function d3_geom_voronoiCircle() {
    d3_geom_voronoiRedBlackNode(this);
    this.x = this.y = this.arc = this.site = this.cy = null;
  }
  function d3_geom_voronoiAttachCircle(arc) {
    var lArc = arc.P, rArc = arc.N;
    if (!lArc || !rArc) return;
    var lSite = lArc.site, cSite = arc.site, rSite = rArc.site;
    if (lSite === rSite) return;
    var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by;
    var d = 2 * (ax * cy - ay * cx);
    if (d >= -ε2) return;
    var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by;
    var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle();
    circle.arc = arc;
    circle.site = cSite;
    circle.x = x + bx;
    circle.y = cy + Math.sqrt(x * x + y * y);
    circle.cy = cy;
    arc.circle = circle;
    var before = null, node = d3_geom_voronoiCircles._;
    while (node) {
      if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) {
        if (node.L) node = node.L; else {
          before = node.P;
          break;
        }
      } else {
        if (node.R) node = node.R; else {
          before = node;
          break;
        }
      }
    }
    d3_geom_voronoiCircles.insert(before, circle);
    if (!before) d3_geom_voronoiFirstCircle = circle;
  }
  function d3_geom_voronoiDetachCircle(arc) {
    var circle = arc.circle;
    if (circle) {
      if (!circle.P) d3_geom_voronoiFirstCircle = circle.N;
      d3_geom_voronoiCircles.remove(circle);
      d3_geom_voronoiCirclePool.push(circle);
      d3_geom_voronoiRedBlackNode(circle);
      arc.circle = null;
    }
  }
  function d3_geom_voronoiClipEdges(extent) {
    var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e;
    while (i--) {
      e = edges[i];
      if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < ε && abs(e.a.y - e.b.y) < ε) {
        e.a = e.b = null;
        edges.splice(i, 1);
      }
    }
  }
  function d3_geom_voronoiConnectEdge(edge, extent) {
    var vb = edge.b;
    if (vb) return true;
    var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb;
    if (ry === ly) {
      if (fx < x0 || fx >= x1) return;
      if (lx > rx) {
        if (!va) va = {
          x: fx,
          y: y0
        }; else if (va.y >= y1) return;
        vb = {
          x: fx,
          y: y1
        };
      } else {
        if (!va) va = {
          x: fx,
          y: y1
        }; else if (va.y < y0) return;
        vb = {
          x: fx,
          y: y0
        };
      }
    } else {
      fm = (lx - rx) / (ry - ly);
      fb = fy - fm * fx;
      if (fm < -1 || fm > 1) {
        if (lx > rx) {
          if (!va) va = {
            x: (y0 - fb) / fm,
            y: y0
          }; else if (va.y >= y1) return;
          vb = {
            x: (y1 - fb) / fm,
            y: y1
          };
        } else {
          if (!va) va = {
            x: (y1 - fb) / fm,
            y: y1
          }; else if (va.y < y0) return;
          vb = {
            x: (y0 - fb) / fm,
            y: y0
          };
        }
      } else {
        if (ly < ry) {
          if (!va) va = {
            x: x0,
            y: fm * x0 + fb
          }; else if (va.x >= x1) return;
          vb = {
            x: x1,
            y: fm * x1 + fb
          };
        } else {
          if (!va) va = {
            x: x1,
            y: fm * x1 + fb
          }; else if (va.x < x0) return;
          vb = {
            x: x0,
            y: fm * x0 + fb
          };
        }
      }
    }
    edge.a = va;
    edge.b = vb;
    return true;
  }
  function d3_geom_voronoiEdge(lSite, rSite) {
    this.l = lSite;
    this.r = rSite;
    this.a = this.b = null;
  }
  function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) {
    var edge = new d3_geom_voronoiEdge(lSite, rSite);
    d3_geom_voronoiEdges.push(edge);
    if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va);
    if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb);
    d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite));
    d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite));
    return edge;
  }
  function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) {
    var edge = new d3_geom_voronoiEdge(lSite, null);
    edge.a = va;
    edge.b = vb;
    d3_geom_voronoiEdges.push(edge);
    return edge;
  }
  function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) {
    if (!edge.a && !edge.b) {
      edge.a = vertex;
      edge.l = lSite;
      edge.r = rSite;
    } else if (edge.l === rSite) {
      edge.b = vertex;
    } else {
      edge.a = vertex;
    }
  }
  function d3_geom_voronoiHalfEdge(edge, lSite, rSite) {
    var va = edge.a, vb = edge.b;
    this.edge = edge;
    this.site = lSite;
    this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y);
  }
  d3_geom_voronoiHalfEdge.prototype = {
    start: function() {
      return this.edge.l === this.site ? this.edge.a : this.edge.b;
    },
    end: function() {
      return this.edge.l === this.site ? this.edge.b : this.edge.a;
    }
  };
  function d3_geom_voronoiRedBlackTree() {
    this._ = null;
  }
  function d3_geom_voronoiRedBlackNode(node) {
    node.U = node.C = node.L = node.R = node.P = node.N = null;
  }
  d3_geom_voronoiRedBlackTree.prototype = {
    insert: function(after, node) {
      var parent, grandpa, uncle;
      if (after) {
        node.P = after;
        node.N = after.N;
        if (after.N) after.N.P = node;
        after.N = node;
        if (after.R) {
          after = after.R;
          while (after.L) after = after.L;
          after.L = node;
        } else {
          after.R = node;
        }
        parent = after;
      } else if (this._) {
        after = d3_geom_voronoiRedBlackFirst(this._);
        node.P = null;
        node.N = after;
        after.P = after.L = node;
        parent = after;
      } else {
        node.P = node.N = null;
        this._ = node;
        parent = null;
      }
      node.L = node.R = null;
      node.U = parent;
      node.C = true;
      after = node;
      while (parent && parent.C) {
        grandpa = parent.U;
        if (parent === grandpa.L) {
          uncle = grandpa.R;
          if (uncle && uncle.C) {
            parent.C = uncle.C = false;
            grandpa.C = true;
            after = grandpa;
          } else {
            if (after === parent.R) {
              d3_geom_voronoiRedBlackRotateLeft(this, parent);
              after = parent;
              parent = after.U;
            }
            parent.C = false;
            grandpa.C = true;
            d3_geom_voronoiRedBlackRotateRight(this, grandpa);
          }
        } else {
          uncle = grandpa.L;
          if (uncle && uncle.C) {
            parent.C = uncle.C = false;
            grandpa.C = true;
            after = grandpa;
          } else {
            if (after === parent.L) {
              d3_geom_voronoiRedBlackRotateRight(this, parent);
              after = parent;
              parent = after.U;
            }
            parent.C = false;
            grandpa.C = true;
            d3_geom_voronoiRedBlackRotateLeft(this, grandpa);
          }
        }
        parent = after.U;
      }
      this._.C = false;
    },
    remove: function(node) {
      if (node.N) node.N.P = node.P;
      if (node.P) node.P.N = node.N;
      node.N = node.P = null;
      var parent = node.U, sibling, left = node.L, right = node.R, next, red;
      if (!left) next = right; else if (!right) next = left; else next = d3_geom_voronoiRedBlackFirst(right);
      if (parent) {
        if (parent.L === node) parent.L = next; else parent.R = next;
      } else {
        this._ = next;
      }
      if (left && right) {
        red = next.C;
        next.C = node.C;
        next.L = left;
        left.U = next;
        if (next !== right) {
          parent = next.U;
          next.U = node.U;
          node = next.R;
          parent.L = node;
          next.R = right;
          right.U = next;
        } else {
          next.U = parent;
          parent = next;
          node = next.R;
        }
      } else {
        red = node.C;
        node = next;
      }
      if (node) node.U = parent;
      if (red) return;
      if (node && node.C) {
        node.C = false;
        return;
      }
      do {
        if (node === this._) break;
        if (node === parent.L) {
          sibling = parent.R;
          if (sibling.C) {
            sibling.C = false;
            parent.C = true;
            d3_geom_voronoiRedBlackRotateLeft(this, parent);
            sibling = parent.R;
          }
          if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) {
            if (!sibling.R || !sibling.R.C) {
              sibling.L.C = false;
              sibling.C = true;
              d3_geom_voronoiRedBlackRotateRight(this, sibling);
              sibling = parent.R;
            }
            sibling.C = parent.C;
            parent.C = sibling.R.C = false;
            d3_geom_voronoiRedBlackRotateLeft(this, parent);
            node = this._;
            break;
          }
        } else {
          sibling = parent.L;
          if (sibling.C) {
            sibling.C = false;
            parent.C = true;
            d3_geom_voronoiRedBlackRotateRight(this, parent);
            sibling = parent.L;
          }
          if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) {
            if (!sibling.L || !sibling.L.C) {
              sibling.R.C = false;
              sibling.C = true;
              d3_geom_voronoiRedBlackRotateLeft(this, sibling);
              sibling = parent.L;
            }
            sibling.C = parent.C;
            parent.C = sibling.L.C = false;
            d3_geom_voronoiRedBlackRotateRight(this, parent);
            node = this._;
            break;
          }
        }
        sibling.C = true;
        node = parent;
        parent = parent.U;
      } while (!node.C);
      if (node) node.C = false;
    }
  };
  function d3_geom_voronoiRedBlackRotateLeft(tree, node) {
    var p = node, q = node.R, parent = p.U;
    if (parent) {
      if (parent.L === p) parent.L = q; else parent.R = q;
    } else {
      tree._ = q;
    }
    q.U = parent;
    p.U = q;
    p.R = q.L;
    if (p.R) p.R.U = p;
    q.L = p;
  }
  function d3_geom_voronoiRedBlackRotateRight(tree, node) {
    var p = node, q = node.L, parent = p.U;
    if (parent) {
      if (parent.L === p) parent.L = q; else parent.R = q;
    } else {
      tree._ = q;
    }
    q.U = parent;
    p.U = q;
    p.L = q.R;
    if (p.L) p.L.U = p;
    q.R = p;
  }
  function d3_geom_voronoiRedBlackFirst(node) {
    while (node.L) node = node.L;
    return node;
  }
  function d3_geom_voronoi(sites, bbox) {
    var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle;
    d3_geom_voronoiEdges = [];
    d3_geom_voronoiCells = new Array(sites.length);
    d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree();
    d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree();
    while (true) {
      circle = d3_geom_voronoiFirstCircle;
      if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) {
        if (site.x !== x0 || site.y !== y0) {
          d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site);
          d3_geom_voronoiAddBeach(site);
          x0 = site.x, y0 = site.y;
        }
        site = sites.pop();
      } else if (circle) {
        d3_geom_voronoiRemoveBeach(circle.arc);
      } else {
        break;
      }
    }
    if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox);
    var diagram = {
      cells: d3_geom_voronoiCells,
      edges: d3_geom_voronoiEdges
    };
    d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null;
    return diagram;
  }
  function d3_geom_voronoiVertexOrder(a, b) {
    return b.y - a.y || b.x - a.x;
  }
  d3.geom.voronoi = function(points) {
    var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent;
    if (points) return voronoi(points);
    function voronoi(data) {
      var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1];
      d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) {
        var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) {
          var s = e.start();
          return [ s.x, s.y ];
        }) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [ [ x0, y1 ], [ x1, y1 ], [ x1, y0 ], [ x0, y0 ] ] : [];
        polygon.point = data[i];
      });
      return polygons;
    }
    function sites(data) {
      return data.map(function(d, i) {
        return {
          x: Math.round(fx(d, i) / ε) * ε,
          y: Math.round(fy(d, i) / ε) * ε,
          i: i
        };
      });
    }
    voronoi.links = function(data) {
      return d3_geom_voronoi(sites(data)).edges.filter(function(edge) {
        return edge.l && edge.r;
      }).map(function(edge) {
        return {
          source: data[edge.l.i],
          target: data[edge.r.i]
        };
      });
    };
    voronoi.triangles = function(data) {
      var triangles = [];
      d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) {
        var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l;
        while (++j < m) {
          e0 = e1;
          s0 = s1;
          e1 = edges[j].edge;
          s1 = e1.l === site ? e1.r : e1.l;
          if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) {
            triangles.push([ data[i], data[s0.i], data[s1.i] ]);
          }
        }
      });
      return triangles;
    };
    voronoi.x = function(_) {
      return arguments.length ? (fx = d3_functor(x = _), voronoi) : x;
    };
    voronoi.y = function(_) {
      return arguments.length ? (fy = d3_functor(y = _), voronoi) : y;
    };
    voronoi.clipExtent = function(_) {
      if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent;
      clipExtent = _ == null ? d3_geom_voronoiClipExtent : _;
      return voronoi;
    };
    voronoi.size = function(_) {
      if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1];
      return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]);
    };
    return voronoi;
  };
  var d3_geom_voronoiClipExtent = [ [ -1e6, -1e6 ], [ 1e6, 1e6 ] ];
  function d3_geom_voronoiTriangleArea(a, b, c) {
    return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y);
  }
  d3.geom.delaunay = function(vertices) {
    return d3.geom.voronoi().triangles(vertices);
  };
  d3.geom.quadtree = function(points, x1, y1, x2, y2) {
    var x = d3_geom_pointX, y = d3_geom_pointY, compat;
    if (compat = arguments.length) {
      x = d3_geom_quadtreeCompatX;
      y = d3_geom_quadtreeCompatY;
      if (compat === 3) {
        y2 = y1;
        x2 = x1;
        y1 = x1 = 0;
      }
      return quadtree(points);
    }
    function quadtree(data) {
      var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_;
      if (x1 != null) {
        x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2;
      } else {
        x2_ = y2_ = -(x1_ = y1_ = Infinity);
        xs = [], ys = [];
        n = data.length;
        if (compat) for (i = 0; i < n; ++i) {
          d = data[i];
          if (d.x < x1_) x1_ = d.x;
          if (d.y < y1_) y1_ = d.y;
          if (d.x > x2_) x2_ = d.x;
          if (d.y > y2_) y2_ = d.y;
          xs.push(d.x);
          ys.push(d.y);
        } else for (i = 0; i < n; ++i) {
          var x_ = +fx(d = data[i], i), y_ = +fy(d, i);
          if (x_ < x1_) x1_ = x_;
          if (y_ < y1_) y1_ = y_;
          if (x_ > x2_) x2_ = x_;
          if (y_ > y2_) y2_ = y_;
          xs.push(x_);
          ys.push(y_);
        }
      }
      var dx = x2_ - x1_, dy = y2_ - y1_;
      if (dx > dy) y2_ = y1_ + dx; else x2_ = x1_ + dy;
      function insert(n, d, x, y, x1, y1, x2, y2) {
        if (isNaN(x) || isNaN(y)) return;
        if (n.leaf) {
          var nx = n.x, ny = n.y;
          if (nx != null) {
            if (abs(nx - x) + abs(ny - y) < .01) {
              insertChild(n, d, x, y, x1, y1, x2, y2);
            } else {
              var nPoint = n.point;
              n.x = n.y = n.point = null;
              insertChild(n, nPoint, nx, ny, x1, y1, x2, y2);
              insertChild(n, d, x, y, x1, y1, x2, y2);
            }
          } else {
            n.x = x, n.y = y, n.point = d;
          }
        } else {
          insertChild(n, d, x, y, x1, y1, x2, y2);
        }
      }
      function insertChild(n, d, x, y, x1, y1, x2, y2) {
        var xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym, i = below << 1 | right;
        n.leaf = false;
        n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode());
        if (right) x1 = xm; else x2 = xm;
        if (below) y1 = ym; else y2 = ym;
        insert(n, d, x, y, x1, y1, x2, y2);
      }
      var root = d3_geom_quadtreeNode();
      root.add = function(d) {
        insert(root, d, +fx(d, ++i), +fy(d, i), x1_, y1_, x2_, y2_);
      };
      root.visit = function(f) {
        d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_);
      };
      root.find = function(point) {
        return d3_geom_quadtreeFind(root, point[0], point[1], x1_, y1_, x2_, y2_);
      };
      i = -1;
      if (x1 == null) {
        while (++i < n) {
          insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_);
        }
        --i;
      } else data.forEach(root.add);
      xs = ys = data = d = null;
      return root;
    }
    quadtree.x = function(_) {
      return arguments.length ? (x = _, quadtree) : x;
    };
    quadtree.y = function(_) {
      return arguments.length ? (y = _, quadtree) : y;
    };
    quadtree.extent = function(_) {
      if (!arguments.length) return x1 == null ? null : [ [ x1, y1 ], [ x2, y2 ] ];
      if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0], 
      y2 = +_[1][1];
      return quadtree;
    };
    quadtree.size = function(_) {
      if (!arguments.length) return x1 == null ? null : [ x2 - x1, y2 - y1 ];
      if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = y1 = 0, x2 = +_[0], y2 = +_[1];
      return quadtree;
    };
    return quadtree;
  };
  function d3_geom_quadtreeCompatX(d) {
    return d.x;
  }
  function d3_geom_quadtreeCompatY(d) {
    return d.y;
  }
  function d3_geom_quadtreeNode() {
    return {
      leaf: true,
      nodes: [],
      point: null,
      x: null,
      y: null
    };
  }
  function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) {
    if (!f(node, x1, y1, x2, y2)) {
      var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes;
      if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy);
      if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy);
      if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2);
      if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2);
    }
  }
  function d3_geom_quadtreeFind(root, x, y, x0, y0, x3, y3) {
    var minDistance2 = Infinity, closestPoint;
    (function find(node, x1, y1, x2, y2) {
      if (x1 > x3 || y1 > y3 || x2 < x0 || y2 < y0) return;
      if (point = node.point) {
        var point, dx = x - node.x, dy = y - node.y, distance2 = dx * dx + dy * dy;
        if (distance2 < minDistance2) {
          var distance = Math.sqrt(minDistance2 = distance2);
          x0 = x - distance, y0 = y - distance;
          x3 = x + distance, y3 = y + distance;
          closestPoint = point;
        }
      }
      var children = node.nodes, xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym;
      for (var i = below << 1 | right, j = i + 4; i < j; ++i) {
        if (node = children[i & 3]) switch (i & 3) {
         case 0:
          find(node, x1, y1, xm, ym);
          break;

         case 1:
          find(node, xm, y1, x2, ym);
          break;

         case 2:
          find(node, x1, ym, xm, y2);
          break;

         case 3:
          find(node, xm, ym, x2, y2);
          break;
        }
      }
    })(root, x0, y0, x3, y3);
    return closestPoint;
  }
  d3.interpolateRgb = d3_interpolateRgb;
  function d3_interpolateRgb(a, b) {
    a = d3.rgb(a);
    b = d3.rgb(b);
    var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab;
    return function(t) {
      return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t));
    };
  }
  d3.interpolateObject = d3_interpolateObject;
  function d3_interpolateObject(a, b) {
    var i = {}, c = {}, k;
    for (k in a) {
      if (k in b) {
        i[k] = d3_interpolate(a[k], b[k]);
      } else {
        c[k] = a[k];
      }
    }
    for (k in b) {
      if (!(k in a)) {
        c[k] = b[k];
      }
    }
    return function(t) {
      for (k in i) c[k] = i[k](t);
      return c;
    };
  }
  d3.interpolateNumber = d3_interpolateNumber;
  function d3_interpolateNumber(a, b) {
    a = +a, b = +b;
    return function(t) {
      return a * (1 - t) + b * t;
    };
  }
  d3.interpolateString = d3_interpolateString;
  function d3_interpolateString(a, b) {
    var bi = d3_interpolate_numberA.lastIndex = d3_interpolate_numberB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = [];
    a = a + "", b = b + "";
    while ((am = d3_interpolate_numberA.exec(a)) && (bm = d3_interpolate_numberB.exec(b))) {
      if ((bs = bm.index) > bi) {
        bs = b.slice(bi, bs);
        if (s[i]) s[i] += bs; else s[++i] = bs;
      }
      if ((am = am[0]) === (bm = bm[0])) {
        if (s[i]) s[i] += bm; else s[++i] = bm;
      } else {
        s[++i] = null;
        q.push({
          i: i,
          x: d3_interpolateNumber(am, bm)
        });
      }
      bi = d3_interpolate_numberB.lastIndex;
    }
    if (bi < b.length) {
      bs = b.slice(bi);
      if (s[i]) s[i] += bs; else s[++i] = bs;
    }
    return s.length < 2 ? q[0] ? (b = q[0].x, function(t) {
      return b(t) + "";
    }) : function() {
      return b;
    } : (b = q.length, function(t) {
      for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);
      return s.join("");
    });
  }
  var d3_interpolate_numberA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, d3_interpolate_numberB = new RegExp(d3_interpolate_numberA.source, "g");
  d3.interpolate = d3_interpolate;
  function d3_interpolate(a, b) {
    var i = d3.interpolators.length, f;
    while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ;
    return f;
  }
  d3.interpolators = [ function(a, b) {
    var t = typeof b;
    return (t === "string" ? d3_rgb_names.has(b.toLowerCase()) || /^(#|rgb\(|hsl\()/i.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_color ? d3_interpolateRgb : Array.isArray(b) ? d3_interpolateArray : t === "object" && isNaN(b) ? d3_interpolateObject : d3_interpolateNumber)(a, b);
  } ];
  d3.interpolateArray = d3_interpolateArray;
  function d3_interpolateArray(a, b) {
    var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i;
    for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i]));
    for (;i < na; ++i) c[i] = a[i];
    for (;i < nb; ++i) c[i] = b[i];
    return function(t) {
      for (i = 0; i < n0; ++i) c[i] = x[i](t);
      return c;
    };
  }
  var d3_ease_default = function() {
    return d3_identity;
  };
  var d3_ease = d3.map({
    linear: d3_ease_default,
    poly: d3_ease_poly,
    quad: function() {
      return d3_ease_quad;
    },
    cubic: function() {
      return d3_ease_cubic;
    },
    sin: function() {
      return d3_ease_sin;
    },
    exp: function() {
      return d3_ease_exp;
    },
    circle: function() {
      return d3_ease_circle;
    },
    elastic: d3_ease_elastic,
    back: d3_ease_back,
    bounce: function() {
      return d3_ease_bounce;
    }
  });
  var d3_ease_mode = d3.map({
    "in": d3_identity,
    out: d3_ease_reverse,
    "in-out": d3_ease_reflect,
    "out-in": function(f) {
      return d3_ease_reflect(d3_ease_reverse(f));
    }
  });
  d3.ease = function(name) {
    var i = name.indexOf("-"), t = i >= 0 ? name.slice(0, i) : name, m = i >= 0 ? name.slice(i + 1) : "in";
    t = d3_ease.get(t) || d3_ease_default;
    m = d3_ease_mode.get(m) || d3_identity;
    return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1))));
  };
  function d3_ease_clamp(f) {
    return function(t) {
      return t <= 0 ? 0 : t >= 1 ? 1 : f(t);
    };
  }
  function d3_ease_reverse(f) {
    return function(t) {
      return 1 - f(1 - t);
    };
  }
  function d3_ease_reflect(f) {
    return function(t) {
      return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t));
    };
  }
  function d3_ease_quad(t) {
    return t * t;
  }
  function d3_ease_cubic(t) {
    return t * t * t;
  }
  function d3_ease_cubicInOut(t) {
    if (t <= 0) return 0;
    if (t >= 1) return 1;
    var t2 = t * t, t3 = t2 * t;
    return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75);
  }
  function d3_ease_poly(e) {
    return function(t) {
      return Math.pow(t, e);
    };
  }
  function d3_ease_sin(t) {
    return 1 - Math.cos(t * halfπ);
  }
  function d3_ease_exp(t) {
    return Math.pow(2, 10 * (t - 1));
  }
  function d3_ease_circle(t) {
    return 1 - Math.sqrt(1 - t * t);
  }
  function d3_ease_elastic(a, p) {
    var s;
    if (arguments.length < 2) p = .45;
    if (arguments.length) s = p / τ * Math.asin(1 / a); else a = 1, s = p / 4;
    return function(t) {
      return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * τ / p);
    };
  }
  function d3_ease_back(s) {
    if (!s) s = 1.70158;
    return function(t) {
      return t * t * ((s + 1) * t - s);
    };
  }
  function d3_ease_bounce(t) {
    return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375;
  }
  d3.interpolateHcl = d3_interpolateHcl;
  function d3_interpolateHcl(a, b) {
    a = d3.hcl(a);
    b = d3.hcl(b);
    var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al;
    if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac;
    if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360;
    return function(t) {
      return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + "";
    };
  }
  d3.interpolateHsl = d3_interpolateHsl;
  function d3_interpolateHsl(a, b) {
    a = d3.hsl(a);
    b = d3.hsl(b);
    var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al;
    if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as;
    if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360;
    return function(t) {
      return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + "";
    };
  }
  d3.interpolateLab = d3_interpolateLab;
  function d3_interpolateLab(a, b) {
    a = d3.lab(a);
    b = d3.lab(b);
    var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab;
    return function(t) {
      return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + "";
    };
  }
  d3.interpolateRound = d3_interpolateRound;
  function d3_interpolateRound(a, b) {
    b -= a;
    return function(t) {
      return Math.round(a + b * t);
    };
  }
  d3.transform = function(string) {
    var g = d3_document.createElementNS(d3.ns.prefix.svg, "g");
    return (d3.transform = function(string) {
      if (string != null) {
        g.setAttribute("transform", string);
        var t = g.transform.baseVal.consolidate();
      }
      return new d3_transform(t ? t.matrix : d3_transformIdentity);
    })(string);
  };
  function d3_transform(m) {
    var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0;
    if (r0[0] * r1[1] < r1[0] * r0[1]) {
      r0[0] *= -1;
      r0[1] *= -1;
      kx *= -1;
      kz *= -1;
    }
    this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees;
    this.translate = [ m.e, m.f ];
    this.scale = [ kx, ky ];
    this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0;
  }
  d3_transform.prototype.toString = function() {
    return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")";
  };
  function d3_transformDot(a, b) {
    return a[0] * b[0] + a[1] * b[1];
  }
  function d3_transformNormalize(a) {
    var k = Math.sqrt(d3_transformDot(a, a));
    if (k) {
      a[0] /= k;
      a[1] /= k;
    }
    return k;
  }
  function d3_transformCombine(a, b, k) {
    a[0] += k * b[0];
    a[1] += k * b[1];
    return a;
  }
  var d3_transformIdentity = {
    a: 1,
    b: 0,
    c: 0,
    d: 1,
    e: 0,
    f: 0
  };
  d3.interpolateTransform = d3_interpolateTransform;
  function d3_interpolateTransformPop(s) {
    return s.length ? s.pop() + "," : "";
  }
  function d3_interpolateTranslate(ta, tb, s, q) {
    if (ta[0] !== tb[0] || ta[1] !== tb[1]) {
      var i = s.push("translate(", null, ",", null, ")");
      q.push({
        i: i - 4,
        x: d3_interpolateNumber(ta[0], tb[0])
      }, {
        i: i - 2,
        x: d3_interpolateNumber(ta[1], tb[1])
      });
    } else if (tb[0] || tb[1]) {
      s.push("translate(" + tb + ")");
    }
  }
  function d3_interpolateRotate(ra, rb, s, q) {
    if (ra !== rb) {
      if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360;
      q.push({
        i: s.push(d3_interpolateTransformPop(s) + "rotate(", null, ")") - 2,
        x: d3_interpolateNumber(ra, rb)
      });
    } else if (rb) {
      s.push(d3_interpolateTransformPop(s) + "rotate(" + rb + ")");
    }
  }
  function d3_interpolateSkew(wa, wb, s, q) {
    if (wa !== wb) {
      q.push({
        i: s.push(d3_interpolateTransformPop(s) + "skewX(", null, ")") - 2,
        x: d3_interpolateNumber(wa, wb)
      });
    } else if (wb) {
      s.push(d3_interpolateTransformPop(s) + "skewX(" + wb + ")");
    }
  }
  function d3_interpolateScale(ka, kb, s, q) {
    if (ka[0] !== kb[0] || ka[1] !== kb[1]) {
      var i = s.push(d3_interpolateTransformPop(s) + "scale(", null, ",", null, ")");
      q.push({
        i: i - 4,
        x: d3_interpolateNumber(ka[0], kb[0])
      }, {
        i: i - 2,
        x: d3_interpolateNumber(ka[1], kb[1])
      });
    } else if (kb[0] !== 1 || kb[1] !== 1) {
      s.push(d3_interpolateTransformPop(s) + "scale(" + kb + ")");
    }
  }
  function d3_interpolateTransform(a, b) {
    var s = [], q = [];
    a = d3.transform(a), b = d3.transform(b);
    d3_interpolateTranslate(a.translate, b.translate, s, q);
    d3_interpolateRotate(a.rotate, b.rotate, s, q);
    d3_interpolateSkew(a.skew, b.skew, s, q);
    d3_interpolateScale(a.scale, b.scale, s, q);
    a = b = null;
    return function(t) {
      var i = -1, n = q.length, o;
      while (++i < n) s[(o = q[i]).i] = o.x(t);
      return s.join("");
    };
  }
  function d3_uninterpolateNumber(a, b) {
    b = (b -= a = +a) || 1 / b;
    return function(x) {
      return (x - a) / b;
    };
  }
  function d3_uninterpolateClamp(a, b) {
    b = (b -= a = +a) || 1 / b;
    return function(x) {
      return Math.max(0, Math.min(1, (x - a) / b));
    };
  }
  d3.layout = {};
  d3.layout.bundle = function() {
    return function(links) {
      var paths = [], i = -1, n = links.length;
      while (++i < n) paths.push(d3_layout_bundlePath(links[i]));
      return paths;
    };
  };
  function d3_layout_bundlePath(link) {
    var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ];
    while (start !== lca) {
      start = start.parent;
      points.push(start);
    }
    var k = points.length;
    while (end !== lca) {
      points.splice(k, 0, end);
      end = end.parent;
    }
    return points;
  }
  function d3_layout_bundleAncestors(node) {
    var ancestors = [], parent = node.parent;
    while (parent != null) {
      ancestors.push(node);
      node = parent;
      parent = parent.parent;
    }
    ancestors.push(node);
    return ancestors;
  }
  function d3_layout_bundleLeastCommonAncestor(a, b) {
    if (a === b) return a;
    var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null;
    while (aNode === bNode) {
      sharedNode = aNode;
      aNode = aNodes.pop();
      bNode = bNodes.pop();
    }
    return sharedNode;
  }
  d3.layout.chord = function() {
    var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords;
    function relayout() {
      var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j;
      chords = [];
      groups = [];
      k = 0, i = -1;
      while (++i < n) {
        x = 0, j = -1;
        while (++j < n) {
          x += matrix[i][j];
        }
        groupSums.push(x);
        subgroupIndex.push(d3.range(n));
        k += x;
      }
      if (sortGroups) {
        groupIndex.sort(function(a, b) {
          return sortGroups(groupSums[a], groupSums[b]);
        });
      }
      if (sortSubgroups) {
        subgroupIndex.forEach(function(d, i) {
          d.sort(function(a, b) {
            return sortSubgroups(matrix[i][a], matrix[i][b]);
          });
        });
      }
      k = (τ - padding * n) / k;
      x = 0, i = -1;
      while (++i < n) {
        x0 = x, j = -1;
        while (++j < n) {
          var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k;
          subgroups[di + "-" + dj] = {
            index: di,
            subindex: dj,
            startAngle: a0,
            endAngle: a1,
            value: v
          };
        }
        groups[di] = {
          index: di,
          startAngle: x0,
          endAngle: x,
          value: groupSums[di]
        };
        x += padding;
      }
      i = -1;
      while (++i < n) {
        j = i - 1;
        while (++j < n) {
          var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i];
          if (source.value || target.value) {
            chords.push(source.value < target.value ? {
              source: target,
              target: source
            } : {
              source: source,
              target: target
            });
          }
        }
      }
      if (sortChords) resort();
    }
    function resort() {
      chords.sort(function(a, b) {
        return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2);
      });
    }
    chord.matrix = function(x) {
      if (!arguments.length) return matrix;
      n = (matrix = x) && matrix.length;
      chords = groups = null;
      return chord;
    };
    chord.padding = function(x) {
      if (!arguments.length) return padding;
      padding = x;
      chords = groups = null;
      return chord;
    };
    chord.sortGroups = function(x) {
      if (!arguments.length) return sortGroups;
      sortGroups = x;
      chords = groups = null;
      return chord;
    };
    chord.sortSubgroups = function(x) {
      if (!arguments.length) return sortSubgroups;
      sortSubgroups = x;
      chords = null;
      return chord;
    };
    chord.sortChords = function(x) {
      if (!arguments.length) return sortChords;
      sortChords = x;
      if (chords) resort();
      return chord;
    };
    chord.chords = function() {
      if (!chords) relayout();
      return chords;
    };
    chord.groups = function() {
      if (!groups) relayout();
      return groups;
    };
    return chord;
  };
  d3.layout.force = function() {
    var force = {}, event = d3.dispatch("start", "tick", "end"), timer, size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, chargeDistance2 = d3_layout_forceChargeDistance2, gravity = .1, theta2 = .64, nodes = [], links = [], distances, strengths, charges;
    function repulse(node) {
      return function(quad, x1, _, x2) {
        if (quad.point !== node) {
          var dx = quad.cx - node.x, dy = quad.cy - node.y, dw = x2 - x1, dn = dx * dx + dy * dy;
          if (dw * dw / theta2 < dn) {
            if (dn < chargeDistance2) {
              var k = quad.charge / dn;
              node.px -= dx * k;
              node.py -= dy * k;
            }
            return true;
          }
          if (quad.point && dn && dn < chargeDistance2) {
            var k = quad.pointCharge / dn;
            node.px -= dx * k;
            node.py -= dy * k;
          }
        }
        return !quad.charge;
      };
    }
    force.tick = function() {
      if ((alpha *= .99) < .005) {
        timer = null;
        event.end({
          type: "end",
          alpha: alpha = 0
        });
        return true;
      }
      var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y;
      for (i = 0; i < m; ++i) {
        o = links[i];
        s = o.source;
        t = o.target;
        x = t.x - s.x;
        y = t.y - s.y;
        if (l = x * x + y * y) {
          l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l;
          x *= l;
          y *= l;
          t.x -= x * (k = s.weight + t.weight ? s.weight / (s.weight + t.weight) : .5);
          t.y -= y * k;
          s.x += x * (k = 1 - k);
          s.y += y * k;
        }
      }
      if (k = alpha * gravity) {
        x = size[0] / 2;
        y = size[1] / 2;
        i = -1;
        if (k) while (++i < n) {
          o = nodes[i];
          o.x += (x - o.x) * k;
          o.y += (y - o.y) * k;
        }
      }
      if (charge) {
        d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges);
        i = -1;
        while (++i < n) {
          if (!(o = nodes[i]).fixed) {
            q.visit(repulse(o));
          }
        }
      }
      i = -1;
      while (++i < n) {
        o = nodes[i];
        if (o.fixed) {
          o.x = o.px;
          o.y = o.py;
        } else {
          o.x -= (o.px - (o.px = o.x)) * friction;
          o.y -= (o.py - (o.py = o.y)) * friction;
        }
      }
      event.tick({
        type: "tick",
        alpha: alpha
      });
    };
    force.nodes = function(x) {
      if (!arguments.length) return nodes;
      nodes = x;
      return force;
    };
    force.links = function(x) {
      if (!arguments.length) return links;
      links = x;
      return force;
    };
    force.size = function(x) {
      if (!arguments.length) return size;
      size = x;
      return force;
    };
    force.linkDistance = function(x) {
      if (!arguments.length) return linkDistance;
      linkDistance = typeof x === "function" ? x : +x;
      return force;
    };
    force.distance = force.linkDistance;
    force.linkStrength = function(x) {
      if (!arguments.length) return linkStrength;
      linkStrength = typeof x === "function" ? x : +x;
      return force;
    };
    force.friction = function(x) {
      if (!arguments.length) return friction;
      friction = +x;
      return force;
    };
    force.charge = function(x) {
      if (!arguments.length) return charge;
      charge = typeof x === "function" ? x : +x;
      return force;
    };
    force.chargeDistance = function(x) {
      if (!arguments.length) return Math.sqrt(chargeDistance2);
      chargeDistance2 = x * x;
      return force;
    };
    force.gravity = function(x) {
      if (!arguments.length) return gravity;
      gravity = +x;
      return force;
    };
    force.theta = function(x) {
      if (!arguments.length) return Math.sqrt(theta2);
      theta2 = x * x;
      return force;
    };
    force.alpha = function(x) {
      if (!arguments.length) return alpha;
      x = +x;
      if (alpha) {
        if (x > 0) {
          alpha = x;
        } else {
          timer.c = null, timer.t = NaN, timer = null;
          event.end({
            type: "end",
            alpha: alpha = 0
          });
        }
      } else if (x > 0) {
        event.start({
          type: "start",
          alpha: alpha = x
        });
        timer = d3_timer(force.tick);
      }
      return force;
    };
    force.start = function() {
      var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o;
      for (i = 0; i < n; ++i) {
        (o = nodes[i]).index = i;
        o.weight = 0;
      }
      for (i = 0; i < m; ++i) {
        o = links[i];
        if (typeof o.source == "number") o.source = nodes[o.source];
        if (typeof o.target == "number") o.target = nodes[o.target];
        ++o.source.weight;
        ++o.target.weight;
      }
      for (i = 0; i < n; ++i) {
        o = nodes[i];
        if (isNaN(o.x)) o.x = position("x", w);
        if (isNaN(o.y)) o.y = position("y", h);
        if (isNaN(o.px)) o.px = o.x;
        if (isNaN(o.py)) o.py = o.y;
      }
      distances = [];
      if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance;
      strengths = [];
      if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength;
      charges = [];
      if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge;
      function position(dimension, size) {
        if (!neighbors) {
          neighbors = new Array(n);
          for (j = 0; j < n; ++j) {
            neighbors[j] = [];
          }
          for (j = 0; j < m; ++j) {
            var o = links[j];
            neighbors[o.source.index].push(o.target);
            neighbors[o.target.index].push(o.source);
          }
        }
        var candidates = neighbors[i], j = -1, l = candidates.length, x;
        while (++j < l) if (!isNaN(x = candidates[j][dimension])) return x;
        return Math.random() * size;
      }
      return force.resume();
    };
    force.resume = function() {
      return force.alpha(.1);
    };
    force.stop = function() {
      return force.alpha(0);
    };
    force.drag = function() {
      if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend);
      if (!arguments.length) return drag;
      this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag);
    };
    function dragmove(d) {
      d.px = d3.event.x, d.py = d3.event.y;
      force.resume();
    }
    return d3.rebind(force, event, "on");
  };
  function d3_layout_forceDragstart(d) {
    d.fixed |= 2;
  }
  function d3_layout_forceDragend(d) {
    d.fixed &= ~6;
  }
  function d3_layout_forceMouseover(d) {
    d.fixed |= 4;
    d.px = d.x, d.py = d.y;
  }
  function d3_layout_forceMouseout(d) {
    d.fixed &= ~4;
  }
  function d3_layout_forceAccumulate(quad, alpha, charges) {
    var cx = 0, cy = 0;
    quad.charge = 0;
    if (!quad.leaf) {
      var nodes = quad.nodes, n = nodes.length, i = -1, c;
      while (++i < n) {
        c = nodes[i];
        if (c == null) continue;
        d3_layout_forceAccumulate(c, alpha, charges);
        quad.charge += c.charge;
        cx += c.charge * c.cx;
        cy += c.charge * c.cy;
      }
    }
    if (quad.point) {
      if (!quad.leaf) {
        quad.point.x += Math.random() - .5;
        quad.point.y += Math.random() - .5;
      }
      var k = alpha * charges[quad.point.index];
      quad.charge += quad.pointCharge = k;
      cx += k * quad.point.x;
      cy += k * quad.point.y;
    }
    quad.cx = cx / quad.charge;
    quad.cy = cy / quad.charge;
  }
  var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1, d3_layout_forceChargeDistance2 = Infinity;
  d3.layout.hierarchy = function() {
    var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue;
    function hierarchy(root) {
      var stack = [ root ], nodes = [], node;
      root.depth = 0;
      while ((node = stack.pop()) != null) {
        nodes.push(node);
        if ((childs = children.call(hierarchy, node, node.depth)) && (n = childs.length)) {
          var n, childs, child;
          while (--n >= 0) {
            stack.push(child = childs[n]);
            child.parent = node;
            child.depth = node.depth + 1;
          }
          if (value) node.value = 0;
          node.children = childs;
        } else {
          if (value) node.value = +value.call(hierarchy, node, node.depth) || 0;
          delete node.children;
        }
      }
      d3_layout_hierarchyVisitAfter(root, function(node) {
        var childs, parent;
        if (sort && (childs = node.children)) childs.sort(sort);
        if (value && (parent = node.parent)) parent.value += node.value;
      });
      return nodes;
    }
    hierarchy.sort = function(x) {
      if (!arguments.length) return sort;
      sort = x;
      return hierarchy;
    };
    hierarchy.children = function(x) {
      if (!arguments.length) return children;
      children = x;
      return hierarchy;
    };
    hierarchy.value = function(x) {
      if (!arguments.length) return value;
      value = x;
      return hierarchy;
    };
    hierarchy.revalue = function(root) {
      if (value) {
        d3_layout_hierarchyVisitBefore(root, function(node) {
          if (node.children) node.value = 0;
        });
        d3_layout_hierarchyVisitAfter(root, function(node) {
          var parent;
          if (!node.children) node.value = +value.call(hierarchy, node, node.depth) || 0;
          if (parent = node.parent) parent.value += node.value;
        });
      }
      return root;
    };
    return hierarchy;
  };
  function d3_layout_hierarchyRebind(object, hierarchy) {
    d3.rebind(object, hierarchy, "sort", "children", "value");
    object.nodes = object;
    object.links = d3_layout_hierarchyLinks;
    return object;
  }
  function d3_layout_hierarchyVisitBefore(node, callback) {
    var nodes = [ node ];
    while ((node = nodes.pop()) != null) {
      callback(node);
      if ((children = node.children) && (n = children.length)) {
        var n, children;
        while (--n >= 0) nodes.push(children[n]);
      }
    }
  }
  function d3_layout_hierarchyVisitAfter(node, callback) {
    var nodes = [ node ], nodes2 = [];
    while ((node = nodes.pop()) != null) {
      nodes2.push(node);
      if ((children = node.children) && (n = children.length)) {
        var i = -1, n, children;
        while (++i < n) nodes.push(children[i]);
      }
    }
    while ((node = nodes2.pop()) != null) {
      callback(node);
    }
  }
  function d3_layout_hierarchyChildren(d) {
    return d.children;
  }
  function d3_layout_hierarchyValue(d) {
    return d.value;
  }
  function d3_layout_hierarchySort(a, b) {
    return b.value - a.value;
  }
  function d3_layout_hierarchyLinks(nodes) {
    return d3.merge(nodes.map(function(parent) {
      return (parent.children || []).map(function(child) {
        return {
          source: parent,
          target: child
        };
      });
    }));
  }
  d3.layout.partition = function() {
    var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ];
    function position(node, x, dx, dy) {
      var children = node.children;
      node.x = x;
      node.y = node.depth * dy;
      node.dx = dx;
      node.dy = dy;
      if (children && (n = children.length)) {
        var i = -1, n, c, d;
        dx = node.value ? dx / node.value : 0;
        while (++i < n) {
          position(c = children[i], x, d = c.value * dx, dy);
          x += d;
        }
      }
    }
    function depth(node) {
      var children = node.children, d = 0;
      if (children && (n = children.length)) {
        var i = -1, n;
        while (++i < n) d = Math.max(d, depth(children[i]));
      }
      return 1 + d;
    }
    function partition(d, i) {
      var nodes = hierarchy.call(this, d, i);
      position(nodes[0], 0, size[0], size[1] / depth(nodes[0]));
      return nodes;
    }
    partition.size = function(x) {
      if (!arguments.length) return size;
      size = x;
      return partition;
    };
    return d3_layout_hierarchyRebind(partition, hierarchy);
  };
  d3.layout.pie = function() {
    var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ, padAngle = 0;
    function pie(data) {
      var n = data.length, values = data.map(function(d, i) {
        return +value.call(pie, d, i);
      }), a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle), da = (typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a, p = Math.min(Math.abs(da) / n, +(typeof padAngle === "function" ? padAngle.apply(this, arguments) : padAngle)), pa = p * (da < 0 ? -1 : 1), sum = d3.sum(values), k = sum ? (da - n * pa) / sum : 0, index = d3.range(n), arcs = [], v;
      if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) {
        return values[j] - values[i];
      } : function(i, j) {
        return sort(data[i], data[j]);
      });
      index.forEach(function(i) {
        arcs[i] = {
          data: data[i],
          value: v = values[i],
          startAngle: a,
          endAngle: a += v * k + pa,
          padAngle: p
        };
      });
      return arcs;
    }
    pie.value = function(_) {
      if (!arguments.length) return value;
      value = _;
      return pie;
    };
    pie.sort = function(_) {
      if (!arguments.length) return sort;
      sort = _;
      return pie;
    };
    pie.startAngle = function(_) {
      if (!arguments.length) return startAngle;
      startAngle = _;
      return pie;
    };
    pie.endAngle = function(_) {
      if (!arguments.length) return endAngle;
      endAngle = _;
      return pie;
    };
    pie.padAngle = function(_) {
      if (!arguments.length) return padAngle;
      padAngle = _;
      return pie;
    };
    return pie;
  };
  var d3_layout_pieSortByValue = {};
  d3.layout.stack = function() {
    var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY;
    function stack(data, index) {
      if (!(n = data.length)) return data;
      var series = data.map(function(d, i) {
        return values.call(stack, d, i);
      });
      var points = series.map(function(d) {
        return d.map(function(v, i) {
          return [ x.call(stack, v, i), y.call(stack, v, i) ];
        });
      });
      var orders = order.call(stack, points, index);
      series = d3.permute(series, orders);
      points = d3.permute(points, orders);
      var offsets = offset.call(stack, points, index);
      var m = series[0].length, n, i, j, o;
      for (j = 0; j < m; ++j) {
        out.call(stack, series[0][j], o = offsets[j], points[0][j][1]);
        for (i = 1; i < n; ++i) {
          out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]);
        }
      }
      return data;
    }
    stack.values = function(x) {
      if (!arguments.length) return values;
      values = x;
      return stack;
    };
    stack.order = function(x) {
      if (!arguments.length) return order;
      order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault;
      return stack;
    };
    stack.offset = function(x) {
      if (!arguments.length) return offset;
      offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero;
      return stack;
    };
    stack.x = function(z) {
      if (!arguments.length) return x;
      x = z;
      return stack;
    };
    stack.y = function(z) {
      if (!arguments.length) return y;
      y = z;
      return stack;
    };
    stack.out = function(z) {
      if (!arguments.length) return out;
      out = z;
      return stack;
    };
    return stack;
  };
  function d3_layout_stackX(d) {
    return d.x;
  }
  function d3_layout_stackY(d) {
    return d.y;
  }
  function d3_layout_stackOut(d, y0, y) {
    d.y0 = y0;
    d.y = y;
  }
  var d3_layout_stackOrders = d3.map({
    "inside-out": function(data) {
      var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) {
        return max[a] - max[b];
      }), top = 0, bottom = 0, tops = [], bottoms = [];
      for (i = 0; i < n; ++i) {
        j = index[i];
        if (top < bottom) {
          top += sums[j];
          tops.push(j);
        } else {
          bottom += sums[j];
          bottoms.push(j);
        }
      }
      return bottoms.reverse().concat(tops);
    },
    reverse: function(data) {
      return d3.range(data.length).reverse();
    },
    "default": d3_layout_stackOrderDefault
  });
  var d3_layout_stackOffsets = d3.map({
    silhouette: function(data) {
      var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = [];
      for (j = 0; j < m; ++j) {
        for (i = 0, o = 0; i < n; i++) o += data[i][j][1];
        if (o > max) max = o;
        sums.push(o);
      }
      for (j = 0; j < m; ++j) {
        y0[j] = (max - sums[j]) / 2;
      }
      return y0;
    },
    wiggle: function(data) {
      var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = [];
      y0[0] = o = o0 = 0;
      for (j = 1; j < m; ++j) {
        for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1];
        for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) {
          for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) {
            s3 += (data[k][j][1] - data[k][j - 1][1]) / dx;
          }
          s2 += s3 * data[i][j][1];
        }
        y0[j] = o -= s1 ? s2 / s1 * dx : 0;
        if (o < o0) o0 = o;
      }
      for (j = 0; j < m; ++j) y0[j] -= o0;
      return y0;
    },
    expand: function(data) {
      var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = [];
      for (j = 0; j < m; ++j) {
        for (i = 0, o = 0; i < n; i++) o += data[i][j][1];
        if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k;
      }
      for (j = 0; j < m; ++j) y0[j] = 0;
      return y0;
    },
    zero: d3_layout_stackOffsetZero
  });
  function d3_layout_stackOrderDefault(data) {
    return d3.range(data.length);
  }
  function d3_layout_stackOffsetZero(data) {
    var j = -1, m = data[0].length, y0 = [];
    while (++j < m) y0[j] = 0;
    return y0;
  }
  function d3_layout_stackMaxIndex(array) {
    var i = 1, j = 0, v = array[0][1], k, n = array.length;
    for (;i < n; ++i) {
      if ((k = array[i][1]) > v) {
        j = i;
        v = k;
      }
    }
    return j;
  }
  function d3_layout_stackReduceSum(d) {
    return d.reduce(d3_layout_stackSum, 0);
  }
  function d3_layout_stackSum(p, d) {
    return p + d[1];
  }
  d3.layout.histogram = function() {
    var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges;
    function histogram(data, i) {
      var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x;
      while (++i < m) {
        bin = bins[i] = [];
        bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]);
        bin.y = 0;
      }
      if (m > 0) {
        i = -1;
        while (++i < n) {
          x = values[i];
          if (x >= range[0] && x <= range[1]) {
            bin = bins[d3.bisect(thresholds, x, 1, m) - 1];
            bin.y += k;
            bin.push(data[i]);
          }
        }
      }
      return bins;
    }
    histogram.value = function(x) {
      if (!arguments.length) return valuer;
      valuer = x;
      return histogram;
    };
    histogram.range = function(x) {
      if (!arguments.length) return ranger;
      ranger = d3_functor(x);
      return histogram;
    };
    histogram.bins = function(x) {
      if (!arguments.length) return binner;
      binner = typeof x === "number" ? function(range) {
        return d3_layout_histogramBinFixed(range, x);
      } : d3_functor(x);
      return histogram;
    };
    histogram.frequency = function(x) {
      if (!arguments.length) return frequency;
      frequency = !!x;
      return histogram;
    };
    return histogram;
  };
  function d3_layout_histogramBinSturges(range, values) {
    return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1));
  }
  function d3_layout_histogramBinFixed(range, n) {
    var x = -1, b = +range[0], m = (range[1] - b) / n, f = [];
    while (++x <= n) f[x] = m * x + b;
    return f;
  }
  function d3_layout_histogramRange(values) {
    return [ d3.min(values), d3.max(values) ];
  }
  d3.layout.pack = function() {
    var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ], radius;
    function pack(d, i) {
      var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() {
        return radius;
      };
      root.x = root.y = 0;
      d3_layout_hierarchyVisitAfter(root, function(d) {
        d.r = +r(d.value);
      });
      d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings);
      if (padding) {
        var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2;
        d3_layout_hierarchyVisitAfter(root, function(d) {
          d.r += dr;
        });
        d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings);
        d3_layout_hierarchyVisitAfter(root, function(d) {
          d.r -= dr;
        });
      }
      d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h));
      return nodes;
    }
    pack.size = function(_) {
      if (!arguments.length) return size;
      size = _;
      return pack;
    };
    pack.radius = function(_) {
      if (!arguments.length) return radius;
      radius = _ == null || typeof _ === "function" ? _ : +_;
      return pack;
    };
    pack.padding = function(_) {
      if (!arguments.length) return padding;
      padding = +_;
      return pack;
    };
    return d3_layout_hierarchyRebind(pack, hierarchy);
  };
  function d3_layout_packSort(a, b) {
    return a.value - b.value;
  }
  function d3_layout_packInsert(a, b) {
    var c = a._pack_next;
    a._pack_next = b;
    b._pack_prev = a;
    b._pack_next = c;
    c._pack_prev = b;
  }
  function d3_layout_packSplice(a, b) {
    a._pack_next = b;
    b._pack_prev = a;
  }
  function d3_layout_packIntersects(a, b) {
    var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r;
    return .999 * dr * dr > dx * dx + dy * dy;
  }
  function d3_layout_packSiblings(node) {
    if (!(nodes = node.children) || !(n = nodes.length)) return;
    var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n;
    function bound(node) {
      xMin = Math.min(node.x - node.r, xMin);
      xMax = Math.max(node.x + node.r, xMax);
      yMin = Math.min(node.y - node.r, yMin);
      yMax = Math.max(node.y + node.r, yMax);
    }
    nodes.forEach(d3_layout_packLink);
    a = nodes[0];
    a.x = -a.r;
    a.y = 0;
    bound(a);
    if (n > 1) {
      b = nodes[1];
      b.x = b.r;
      b.y = 0;
      bound(b);
      if (n > 2) {
        c = nodes[2];
        d3_layout_packPlace(a, b, c);
        bound(c);
        d3_layout_packInsert(a, c);
        a._pack_prev = c;
        d3_layout_packInsert(c, b);
        b = a._pack_next;
        for (i = 3; i < n; i++) {
          d3_layout_packPlace(a, b, c = nodes[i]);
          var isect = 0, s1 = 1, s2 = 1;
          for (j = b._pack_next; j !== b; j = j._pack_next, s1++) {
            if (d3_layout_packIntersects(j, c)) {
              isect = 1;
              break;
            }
          }
          if (isect == 1) {
            for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) {
              if (d3_layout_packIntersects(k, c)) {
                break;
              }
            }
          }
          if (isect) {
            if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b);
            i--;
          } else {
            d3_layout_packInsert(a, c);
            b = c;
            bound(c);
          }
        }
      }
    }
    var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0;
    for (i = 0; i < n; i++) {
      c = nodes[i];
      c.x -= cx;
      c.y -= cy;
      cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y));
    }
    node.r = cr;
    nodes.forEach(d3_layout_packUnlink);
  }
  function d3_layout_packLink(node) {
    node._pack_next = node._pack_prev = node;
  }
  function d3_layout_packUnlink(node) {
    delete node._pack_next;
    delete node._pack_prev;
  }
  function d3_layout_packTransform(node, x, y, k) {
    var children = node.children;
    node.x = x += k * node.x;
    node.y = y += k * node.y;
    node.r *= k;
    if (children) {
      var i = -1, n = children.length;
      while (++i < n) d3_layout_packTransform(children[i], x, y, k);
    }
  }
  function d3_layout_packPlace(a, b, c) {
    var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y;
    if (db && (dx || dy)) {
      var da = b.r + c.r, dc = dx * dx + dy * dy;
      da *= da;
      db *= db;
      var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc);
      c.x = a.x + x * dx + y * dy;
      c.y = a.y + x * dy - y * dx;
    } else {
      c.x = a.x + db;
      c.y = a.y;
    }
  }
  d3.layout.tree = function() {
    var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = null;
    function tree(d, i) {
      var nodes = hierarchy.call(this, d, i), root0 = nodes[0], root1 = wrapTree(root0);
      d3_layout_hierarchyVisitAfter(root1, firstWalk), root1.parent.m = -root1.z;
      d3_layout_hierarchyVisitBefore(root1, secondWalk);
      if (nodeSize) d3_layout_hierarchyVisitBefore(root0, sizeNode); else {
        var left = root0, right = root0, bottom = root0;
        d3_layout_hierarchyVisitBefore(root0, function(node) {
          if (node.x < left.x) left = node;
          if (node.x > right.x) right = node;
          if (node.depth > bottom.depth) bottom = node;
        });
        var tx = separation(left, right) / 2 - left.x, kx = size[0] / (right.x + separation(right, left) / 2 + tx), ky = size[1] / (bottom.depth || 1);
        d3_layout_hierarchyVisitBefore(root0, function(node) {
          node.x = (node.x + tx) * kx;
          node.y = node.depth * ky;
        });
      }
      return nodes;
    }
    function wrapTree(root0) {
      var root1 = {
        A: null,
        children: [ root0 ]
      }, queue = [ root1 ], node1;
      while ((node1 = queue.pop()) != null) {
        for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) {
          queue.push((children[i] = child = {
            _: children[i],
            parent: node1,
            children: (child = children[i].children) && child.slice() || [],
            A: null,
            a: null,
            z: 0,
            m: 0,
            c: 0,
            s: 0,
            t: null,
            i: i
          }).a = child);
        }
      }
      return root1.children[0];
    }
    function firstWalk(v) {
      var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null;
      if (children.length) {
        d3_layout_treeShift(v);
        var midpoint = (children[0].z + children[children.length - 1].z) / 2;
        if (w) {
          v.z = w.z + separation(v._, w._);
          v.m = v.z - midpoint;
        } else {
          v.z = midpoint;
        }
      } else if (w) {
        v.z = w.z + separation(v._, w._);
      }
      v.parent.A = apportion(v, w, v.parent.A || siblings[0]);
    }
    function secondWalk(v) {
      v._.x = v.z + v.parent.m;
      v.m += v.parent.m;
    }
    function apportion(v, w, ancestor) {
      if (w) {
        var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift;
        while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) {
          vom = d3_layout_treeLeft(vom);
          vop = d3_layout_treeRight(vop);
          vop.a = v;
          shift = vim.z + sim - vip.z - sip + separation(vim._, vip._);
          if (shift > 0) {
            d3_layout_treeMove(d3_layout_treeAncestor(vim, v, ancestor), v, shift);
            sip += shift;
            sop += shift;
          }
          sim += vim.m;
          sip += vip.m;
          som += vom.m;
          sop += vop.m;
        }
        if (vim && !d3_layout_treeRight(vop)) {
          vop.t = vim;
          vop.m += sim - sop;
        }
        if (vip && !d3_layout_treeLeft(vom)) {
          vom.t = vip;
          vom.m += sip - som;
          ancestor = v;
        }
      }
      return ancestor;
    }
    function sizeNode(node) {
      node.x *= size[0];
      node.y = node.depth * size[1];
    }
    tree.separation = function(x) {
      if (!arguments.length) return separation;
      separation = x;
      return tree;
    };
    tree.size = function(x) {
      if (!arguments.length) return nodeSize ? null : size;
      nodeSize = (size = x) == null ? sizeNode : null;
      return tree;
    };
    tree.nodeSize = function(x) {
      if (!arguments.length) return nodeSize ? size : null;
      nodeSize = (size = x) == null ? null : sizeNode;
      return tree;
    };
    return d3_layout_hierarchyRebind(tree, hierarchy);
  };
  function d3_layout_treeSeparation(a, b) {
    return a.parent == b.parent ? 1 : 2;
  }
  function d3_layout_treeLeft(v) {
    var children = v.children;
    return children.length ? children[0] : v.t;
  }
  function d3_layout_treeRight(v) {
    var children = v.children, n;
    return (n = children.length) ? children[n - 1] : v.t;
  }
  function d3_layout_treeMove(wm, wp, shift) {
    var change = shift / (wp.i - wm.i);
    wp.c -= change;
    wp.s += shift;
    wm.c += change;
    wp.z += shift;
    wp.m += shift;
  }
  function d3_layout_treeShift(v) {
    var shift = 0, change = 0, children = v.children, i = children.length, w;
    while (--i >= 0) {
      w = children[i];
      w.z += shift;
      w.m += shift;
      shift += w.s + (change += w.c);
    }
  }
  function d3_layout_treeAncestor(vim, v, ancestor) {
    return vim.a.parent === v.parent ? vim.a : ancestor;
  }
  d3.layout.cluster = function() {
    var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false;
    function cluster(d, i) {
      var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0;
      d3_layout_hierarchyVisitAfter(root, function(node) {
        var children = node.children;
        if (children && children.length) {
          node.x = d3_layout_clusterX(children);
          node.y = d3_layout_clusterY(children);
        } else {
          node.x = previousNode ? x += separation(node, previousNode) : 0;
          node.y = 0;
          previousNode = node;
        }
      });
      var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2;
      d3_layout_hierarchyVisitAfter(root, nodeSize ? function(node) {
        node.x = (node.x - root.x) * size[0];
        node.y = (root.y - node.y) * size[1];
      } : function(node) {
        node.x = (node.x - x0) / (x1 - x0) * size[0];
        node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1];
      });
      return nodes;
    }
    cluster.separation = function(x) {
      if (!arguments.length) return separation;
      separation = x;
      return cluster;
    };
    cluster.size = function(x) {
      if (!arguments.length) return nodeSize ? null : size;
      nodeSize = (size = x) == null;
      return cluster;
    };
    cluster.nodeSize = function(x) {
      if (!arguments.length) return nodeSize ? size : null;
      nodeSize = (size = x) != null;
      return cluster;
    };
    return d3_layout_hierarchyRebind(cluster, hierarchy);
  };
  function d3_layout_clusterY(children) {
    return 1 + d3.max(children, function(child) {
      return child.y;
    });
  }
  function d3_layout_clusterX(children) {
    return children.reduce(function(x, child) {
      return x + child.x;
    }, 0) / children.length;
  }
  function d3_layout_clusterLeft(node) {
    var children = node.children;
    return children && children.length ? d3_layout_clusterLeft(children[0]) : node;
  }
  function d3_layout_clusterRight(node) {
    var children = node.children, n;
    return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node;
  }
  d3.layout.treemap = function() {
    var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [ 1, 1 ], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = .5 * (1 + Math.sqrt(5));
    function scale(children, k) {
      var i = -1, n = children.length, child, area;
      while (++i < n) {
        area = (child = children[i]).value * (k < 0 ? 0 : k);
        child.area = isNaN(area) || area <= 0 ? 0 : area;
      }
    }
    function squarify(node) {
      var children = node.children;
      if (children && children.length) {
        var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = mode === "slice" ? rect.dx : mode === "dice" ? rect.dy : mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx : Math.min(rect.dx, rect.dy), n;
        scale(remaining, rect.dx * rect.dy / node.value);
        row.area = 0;
        while ((n = remaining.length) > 0) {
          row.push(child = remaining[n - 1]);
          row.area += child.area;
          if (mode !== "squarify" || (score = worst(row, u)) <= best) {
            remaining.pop();
            best = score;
          } else {
            row.area -= row.pop().area;
            position(row, u, rect, false);
            u = Math.min(rect.dx, rect.dy);
            row.length = row.area = 0;
            best = Infinity;
          }
        }
        if (row.length) {
          position(row, u, rect, true);
          row.length = row.area = 0;
        }
        children.forEach(squarify);
      }
    }
    function stickify(node) {
      var children = node.children;
      if (children && children.length) {
        var rect = pad(node), remaining = children.slice(), child, row = [];
        scale(remaining, rect.dx * rect.dy / node.value);
        row.area = 0;
        while (child = remaining.pop()) {
          row.push(child);
          row.area += child.area;
          if (child.z != null) {
            position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length);
            row.length = row.area = 0;
          }
        }
        children.forEach(stickify);
      }
    }
    function worst(row, u) {
      var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length;
      while (++i < n) {
        if (!(r = row[i].area)) continue;
        if (r < rmin) rmin = r;
        if (r > rmax) rmax = r;
      }
      s *= s;
      u *= u;
      return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity;
    }
    function position(row, u, rect, flush) {
      var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o;
      if (u == rect.dx) {
        if (flush || v > rect.dy) v = rect.dy;
        while (++i < n) {
          o = row[i];
          o.x = x;
          o.y = y;
          o.dy = v;
          x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0);
        }
        o.z = true;
        o.dx += rect.x + rect.dx - x;
        rect.y += v;
        rect.dy -= v;
      } else {
        if (flush || v > rect.dx) v = rect.dx;
        while (++i < n) {
          o = row[i];
          o.x = x;
          o.y = y;
          o.dx = v;
          y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0);
        }
        o.z = false;
        o.dy += rect.y + rect.dy - y;
        rect.x += v;
        rect.dx -= v;
      }
    }
    function treemap(d) {
      var nodes = stickies || hierarchy(d), root = nodes[0];
      root.x = root.y = 0;
      if (root.value) root.dx = size[0], root.dy = size[1]; else root.dx = root.dy = 0;
      if (stickies) hierarchy.revalue(root);
      scale([ root ], root.dx * root.dy / root.value);
      (stickies ? stickify : squarify)(root);
      if (sticky) stickies = nodes;
      return nodes;
    }
    treemap.size = function(x) {
      if (!arguments.length) return size;
      size = x;
      return treemap;
    };
    treemap.padding = function(x) {
      if (!arguments.length) return padding;
      function padFunction(node) {
        var p = x.call(treemap, node, node.depth);
        return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p);
      }
      function padConstant(node) {
        return d3_layout_treemapPad(node, x);
      }
      var type;
      pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ], 
      padConstant) : padConstant;
      return treemap;
    };
    treemap.round = function(x) {
      if (!arguments.length) return round != Number;
      round = x ? Math.round : Number;
      return treemap;
    };
    treemap.sticky = function(x) {
      if (!arguments.length) return sticky;
      sticky = x;
      stickies = null;
      return treemap;
    };
    treemap.ratio = function(x) {
      if (!arguments.length) return ratio;
      ratio = x;
      return treemap;
    };
    treemap.mode = function(x) {
      if (!arguments.length) return mode;
      mode = x + "";
      return treemap;
    };
    return d3_layout_hierarchyRebind(treemap, hierarchy);
  };
  function d3_layout_treemapPadNull(node) {
    return {
      x: node.x,
      y: node.y,
      dx: node.dx,
      dy: node.dy
    };
  }
  function d3_layout_treemapPad(node, padding) {
    var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2];
    if (dx < 0) {
      x += dx / 2;
      dx = 0;
    }
    if (dy < 0) {
      y += dy / 2;
      dy = 0;
    }
    return {
      x: x,
      y: y,
      dx: dx,
      dy: dy
    };
  }
  d3.random = {
    normal: function(µ, σ) {
      var n = arguments.length;
      if (n < 2) σ = 1;
      if (n < 1) µ = 0;
      return function() {
        var x, y, r;
        do {
          x = Math.random() * 2 - 1;
          y = Math.random() * 2 - 1;
          r = x * x + y * y;
        } while (!r || r > 1);
        return µ + σ * x * Math.sqrt(-2 * Math.log(r) / r);
      };
    },
    logNormal: function() {
      var random = d3.random.normal.apply(d3, arguments);
      return function() {
        return Math.exp(random());
      };
    },
    bates: function(m) {
      var random = d3.random.irwinHall(m);
      return function() {
        return random() / m;
      };
    },
    irwinHall: function(m) {
      return function() {
        for (var s = 0, j = 0; j < m; j++) s += Math.random();
        return s;
      };
    }
  };
  d3.scale = {};
  function d3_scaleExtent(domain) {
    var start = domain[0], stop = domain[domain.length - 1];
    return start < stop ? [ start, stop ] : [ stop, start ];
  }
  function d3_scaleRange(scale) {
    return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range());
  }
  function d3_scale_bilinear(domain, range, uninterpolate, interpolate) {
    var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]);
    return function(x) {
      return i(u(x));
    };
  }
  function d3_scale_nice(domain, nice) {
    var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx;
    if (x1 < x0) {
      dx = i0, i0 = i1, i1 = dx;
      dx = x0, x0 = x1, x1 = dx;
    }
    domain[i0] = nice.floor(x0);
    domain[i1] = nice.ceil(x1);
    return domain;
  }
  function d3_scale_niceStep(step) {
    return step ? {
      floor: function(x) {
        return Math.floor(x / step) * step;
      },
      ceil: function(x) {
        return Math.ceil(x / step) * step;
      }
    } : d3_scale_niceIdentity;
  }
  var d3_scale_niceIdentity = {
    floor: d3_identity,
    ceil: d3_identity
  };
  function d3_scale_polylinear(domain, range, uninterpolate, interpolate) {
    var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1;
    if (domain[k] < domain[0]) {
      domain = domain.slice().reverse();
      range = range.slice().reverse();
    }
    while (++j <= k) {
      u.push(uninterpolate(domain[j - 1], domain[j]));
      i.push(interpolate(range[j - 1], range[j]));
    }
    return function(x) {
      var j = d3.bisect(domain, x, 1, k) - 1;
      return i[j](u[j](x));
    };
  }
  d3.scale.linear = function() {
    return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3_interpolate, false);
  };
  function d3_scale_linear(domain, range, interpolate, clamp) {
    var output, input;
    function rescale() {
      var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber;
      output = linear(domain, range, uninterpolate, interpolate);
      input = linear(range, domain, uninterpolate, d3_interpolate);
      return scale;
    }
    function scale(x) {
      return output(x);
    }
    scale.invert = function(y) {
      return input(y);
    };
    scale.domain = function(x) {
      if (!arguments.length) return domain;
      domain = x.map(Number);
      return rescale();
    };
    scale.range = function(x) {
      if (!arguments.length) return range;
      range = x;
      return rescale();
    };
    scale.rangeRound = function(x) {
      return scale.range(x).interpolate(d3_interpolateRound);
    };
    scale.clamp = function(x) {
      if (!arguments.length) return clamp;
      clamp = x;
      return rescale();
    };
    scale.interpolate = function(x) {
      if (!arguments.length) return interpolate;
      interpolate = x;
      return rescale();
    };
    scale.ticks = function(m) {
      return d3_scale_linearTicks(domain, m);
    };
    scale.tickFormat = function(m, format) {
      return d3_scale_linearTickFormat(domain, m, format);
    };
    scale.nice = function(m) {
      d3_scale_linearNice(domain, m);
      return rescale();
    };
    scale.copy = function() {
      return d3_scale_linear(domain, range, interpolate, clamp);
    };
    return rescale();
  }
  function d3_scale_linearRebind(scale, linear) {
    return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp");
  }
  function d3_scale_linearNice(domain, m) {
    d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2]));
    d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2]));
    return domain;
  }
  function d3_scale_linearTickRange(domain, m) {
    if (m == null) m = 10;
    var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step;
    if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2;
    extent[0] = Math.ceil(extent[0] / step) * step;
    extent[1] = Math.floor(extent[1] / step) * step + step * .5;
    extent[2] = step;
    return extent;
  }
  function d3_scale_linearTicks(domain, m) {
    return d3.range.apply(d3, d3_scale_linearTickRange(domain, m));
  }
  function d3_scale_linearTickFormat(domain, m, format) {
    var range = d3_scale_linearTickRange(domain, m);
    if (format) {
      var match = d3_format_re.exec(format);
      match.shift();
      if (match[8] === "s") {
        var prefix = d3.formatPrefix(Math.max(abs(range[0]), abs(range[1])));
        if (!match[7]) match[7] = "." + d3_scale_linearPrecision(prefix.scale(range[2]));
        match[8] = "f";
        format = d3.format(match.join(""));
        return function(d) {
          return format(prefix.scale(d)) + prefix.symbol;
        };
      }
      if (!match[7]) match[7] = "." + d3_scale_linearFormatPrecision(match[8], range);
      format = match.join("");
    } else {
      format = ",." + d3_scale_linearPrecision(range[2]) + "f";
    }
    return d3.format(format);
  }
  var d3_scale_linearFormatSignificant = {
    s: 1,
    g: 1,
    p: 1,
    r: 1,
    e: 1
  };
  function d3_scale_linearPrecision(value) {
    return -Math.floor(Math.log(value) / Math.LN10 + .01);
  }
  function d3_scale_linearFormatPrecision(type, range) {
    var p = d3_scale_linearPrecision(range[2]);
    return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(abs(range[0]), abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2;
  }
  d3.scale.log = function() {
    return d3_scale_log(d3.scale.linear().domain([ 0, 1 ]), 10, true, [ 1, 10 ]);
  };
  function d3_scale_log(linear, base, positive, domain) {
    function log(x) {
      return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base);
    }
    function pow(x) {
      return positive ? Math.pow(base, x) : -Math.pow(base, -x);
    }
    function scale(x) {
      return linear(log(x));
    }
    scale.invert = function(x) {
      return pow(linear.invert(x));
    };
    scale.domain = function(x) {
      if (!arguments.length) return domain;
      positive = x[0] >= 0;
      linear.domain((domain = x.map(Number)).map(log));
      return scale;
    };
    scale.base = function(_) {
      if (!arguments.length) return base;
      base = +_;
      linear.domain(domain.map(log));
      return scale;
    };
    scale.nice = function() {
      var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative);
      linear.domain(niced);
      domain = niced.map(pow);
      return scale;
    };
    scale.ticks = function() {
      var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base;
      if (isFinite(j - i)) {
        if (positive) {
          for (;i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k);
          ticks.push(pow(i));
        } else {
          ticks.push(pow(i));
          for (;i++ < j; ) for (var k = n - 1; k > 0; k--) ticks.push(pow(i) * k);
        }
        for (i = 0; ticks[i] < u; i++) {}
        for (j = ticks.length; ticks[j - 1] > v; j--) {}
        ticks = ticks.slice(i, j);
      }
      return ticks;
    };
    scale.tickFormat = function(n, format) {
      if (!arguments.length) return d3_scale_logFormat;
      if (arguments.length < 2) format = d3_scale_logFormat; else if (typeof format !== "function") format = d3.format(format);
      var k = Math.max(1, base * n / scale.ticks().length);
      return function(d) {
        var i = d / pow(Math.round(log(d)));
        if (i * base < base - .5) i *= base;
        return i <= k ? format(d) : "";
      };
    };
    scale.copy = function() {
      return d3_scale_log(linear.copy(), base, positive, domain);
    };
    return d3_scale_linearRebind(scale, linear);
  }
  var d3_scale_logFormat = d3.format(".0e"), d3_scale_logNiceNegative = {
    floor: function(x) {
      return -Math.ceil(-x);
    },
    ceil: function(x) {
      return -Math.floor(-x);
    }
  };
  d3.scale.pow = function() {
    return d3_scale_pow(d3.scale.linear(), 1, [ 0, 1 ]);
  };
  function d3_scale_pow(linear, exponent, domain) {
    var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent);
    function scale(x) {
      return linear(powp(x));
    }
    scale.invert = function(x) {
      return powb(linear.invert(x));
    };
    scale.domain = function(x) {
      if (!arguments.length) return domain;
      linear.domain((domain = x.map(Number)).map(powp));
      return scale;
    };
    scale.ticks = function(m) {
      return d3_scale_linearTicks(domain, m);
    };
    scale.tickFormat = function(m, format) {
      return d3_scale_linearTickFormat(domain, m, format);
    };
    scale.nice = function(m) {
      return scale.domain(d3_scale_linearNice(domain, m));
    };
    scale.exponent = function(x) {
      if (!arguments.length) return exponent;
      powp = d3_scale_powPow(exponent = x);
      powb = d3_scale_powPow(1 / exponent);
      linear.domain(domain.map(powp));
      return scale;
    };
    scale.copy = function() {
      return d3_scale_pow(linear.copy(), exponent, domain);
    };
    return d3_scale_linearRebind(scale, linear);
  }
  function d3_scale_powPow(e) {
    return function(x) {
      return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e);
    };
  }
  d3.scale.sqrt = function() {
    return d3.scale.pow().exponent(.5);
  };
  d3.scale.ordinal = function() {
    return d3_scale_ordinal([], {
      t: "range",
      a: [ [] ]
    });
  };
  function d3_scale_ordinal(domain, ranger) {
    var index, range, rangeBand;
    function scale(x) {
      return range[((index.get(x) || (ranger.t === "range" ? index.set(x, domain.push(x)) : NaN)) - 1) % range.length];
    }
    function steps(start, step) {
      return d3.range(domain.length).map(function(i) {
        return start + step * i;
      });
    }
    scale.domain = function(x) {
      if (!arguments.length) return domain;
      domain = [];
      index = new d3_Map();
      var i = -1, n = x.length, xi;
      while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi));
      return scale[ranger.t].apply(scale, ranger.a);
    };
    scale.range = function(x) {
      if (!arguments.length) return range;
      range = x;
      rangeBand = 0;
      ranger = {
        t: "range",
        a: arguments
      };
      return scale;
    };
    scale.rangePoints = function(x, padding) {
      if (arguments.length < 2) padding = 0;
      var start = x[0], stop = x[1], step = domain.length < 2 ? (start = (start + stop) / 2, 
      0) : (stop - start) / (domain.length - 1 + padding);
      range = steps(start + step * padding / 2, step);
      rangeBand = 0;
      ranger = {
        t: "rangePoints",
        a: arguments
      };
      return scale;
    };
    scale.rangeRoundPoints = function(x, padding) {
      if (arguments.length < 2) padding = 0;
      var start = x[0], stop = x[1], step = domain.length < 2 ? (start = stop = Math.round((start + stop) / 2), 
      0) : (stop - start) / (domain.length - 1 + padding) | 0;
      range = steps(start + Math.round(step * padding / 2 + (stop - start - (domain.length - 1 + padding) * step) / 2), step);
      rangeBand = 0;
      ranger = {
        t: "rangeRoundPoints",
        a: arguments
      };
      return scale;
    };
    scale.rangeBands = function(x, padding, outerPadding) {
      if (arguments.length < 2) padding = 0;
      if (arguments.length < 3) outerPadding = padding;
      var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding);
      range = steps(start + step * outerPadding, step);
      if (reverse) range.reverse();
      rangeBand = step * (1 - padding);
      ranger = {
        t: "rangeBands",
        a: arguments
      };
      return scale;
    };
    scale.rangeRoundBands = function(x, padding, outerPadding) {
      if (arguments.length < 2) padding = 0;
      if (arguments.length < 3) outerPadding = padding;
      var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding));
      range = steps(start + Math.round((stop - start - (domain.length - padding) * step) / 2), step);
      if (reverse) range.reverse();
      rangeBand = Math.round(step * (1 - padding));
      ranger = {
        t: "rangeRoundBands",
        a: arguments
      };
      return scale;
    };
    scale.rangeBand = function() {
      return rangeBand;
    };
    scale.rangeExtent = function() {
      return d3_scaleExtent(ranger.a[0]);
    };
    scale.copy = function() {
      return d3_scale_ordinal(domain, ranger);
    };
    return scale.domain(domain);
  }
  d3.scale.category10 = function() {
    return d3.scale.ordinal().range(d3_category10);
  };
  d3.scale.category20 = function() {
    return d3.scale.ordinal().range(d3_category20);
  };
  d3.scale.category20b = function() {
    return d3.scale.ordinal().range(d3_category20b);
  };
  d3.scale.category20c = function() {
    return d3.scale.ordinal().range(d3_category20c);
  };
  var d3_category10 = [ 2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175 ].map(d3_rgbString);
  var d3_category20 = [ 2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725 ].map(d3_rgbString);
  var d3_category20b = [ 3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654 ].map(d3_rgbString);
  var d3_category20c = [ 3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081 ].map(d3_rgbString);
  d3.scale.quantile = function() {
    return d3_scale_quantile([], []);
  };
  function d3_scale_quantile(domain, range) {
    var thresholds;
    function rescale() {
      var k = 0, q = range.length;
      thresholds = [];
      while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q);
      return scale;
    }
    function scale(x) {
      if (!isNaN(x = +x)) return range[d3.bisect(thresholds, x)];
    }
    scale.domain = function(x) {
      if (!arguments.length) return domain;
      domain = x.map(d3_number).filter(d3_numeric).sort(d3_ascending);
      return rescale();
    };
    scale.range = function(x) {
      if (!arguments.length) return range;
      range = x;
      return rescale();
    };
    scale.quantiles = function() {
      return thresholds;
    };
    scale.invertExtent = function(y) {
      y = range.indexOf(y);
      return y < 0 ? [ NaN, NaN ] : [ y > 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1] ];
    };
    scale.copy = function() {
      return d3_scale_quantile(domain, range);
    };
    return rescale();
  }
  d3.scale.quantize = function() {
    return d3_scale_quantize(0, 1, [ 0, 1 ]);
  };
  function d3_scale_quantize(x0, x1, range) {
    var kx, i;
    function scale(x) {
      return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))];
    }
    function rescale() {
      kx = range.length / (x1 - x0);
      i = range.length - 1;
      return scale;
    }
    scale.domain = function(x) {
      if (!arguments.length) return [ x0, x1 ];
      x0 = +x[0];
      x1 = +x[x.length - 1];
      return rescale();
    };
    scale.range = function(x) {
      if (!arguments.length) return range;
      range = x;
      return rescale();
    };
    scale.invertExtent = function(y) {
      y = range.indexOf(y);
      y = y < 0 ? NaN : y / kx + x0;
      return [ y, y + 1 / kx ];
    };
    scale.copy = function() {
      return d3_scale_quantize(x0, x1, range);
    };
    return rescale();
  }
  d3.scale.threshold = function() {
    return d3_scale_threshold([ .5 ], [ 0, 1 ]);
  };
  function d3_scale_threshold(domain, range) {
    function scale(x) {
      if (x <= x) return range[d3.bisect(domain, x)];
    }
    scale.domain = function(_) {
      if (!arguments.length) return domain;
      domain = _;
      return scale;
    };
    scale.range = function(_) {
      if (!arguments.length) return range;
      range = _;
      return scale;
    };
    scale.invertExtent = function(y) {
      y = range.indexOf(y);
      return [ domain[y - 1], domain[y] ];
    };
    scale.copy = function() {
      return d3_scale_threshold(domain, range);
    };
    return scale;
  }
  d3.scale.identity = function() {
    return d3_scale_identity([ 0, 1 ]);
  };
  function d3_scale_identity(domain) {
    function identity(x) {
      return +x;
    }
    identity.invert = identity;
    identity.domain = identity.range = function(x) {
      if (!arguments.length) return domain;
      domain = x.map(identity);
      return identity;
    };
    identity.ticks = function(m) {
      return d3_scale_linearTicks(domain, m);
    };
    identity.tickFormat = function(m, format) {
      return d3_scale_linearTickFormat(domain, m, format);
    };
    identity.copy = function() {
      return d3_scale_identity(domain);
    };
    return identity;
  }
  d3.svg = {};
  function d3_zero() {
    return 0;
  }
  d3.svg.arc = function() {
    var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, cornerRadius = d3_zero, padRadius = d3_svg_arcAuto, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle, padAngle = d3_svg_arcPadAngle;
    function arc() {
      var r0 = Math.max(0, +innerRadius.apply(this, arguments)), r1 = Math.max(0, +outerRadius.apply(this, arguments)), a0 = startAngle.apply(this, arguments) - halfπ, a1 = endAngle.apply(this, arguments) - halfπ, da = Math.abs(a1 - a0), cw = a0 > a1 ? 0 : 1;
      if (r1 < r0) rc = r1, r1 = r0, r0 = rc;
      if (da >= τε) return circleSegment(r1, cw) + (r0 ? circleSegment(r0, 1 - cw) : "") + "Z";
      var rc, cr, rp, ap, p0 = 0, p1 = 0, x0, y0, x1, y1, x2, y2, x3, y3, path = [];
      if (ap = (+padAngle.apply(this, arguments) || 0) / 2) {
        rp = padRadius === d3_svg_arcAuto ? Math.sqrt(r0 * r0 + r1 * r1) : +padRadius.apply(this, arguments);
        if (!cw) p1 *= -1;
        if (r1) p1 = d3_asin(rp / r1 * Math.sin(ap));
        if (r0) p0 = d3_asin(rp / r0 * Math.sin(ap));
      }
      if (r1) {
        x0 = r1 * Math.cos(a0 + p1);
        y0 = r1 * Math.sin(a0 + p1);
        x1 = r1 * Math.cos(a1 - p1);
        y1 = r1 * Math.sin(a1 - p1);
        var l1 = Math.abs(a1 - a0 - 2 * p1) <= π ? 0 : 1;
        if (p1 && d3_svg_arcSweep(x0, y0, x1, y1) === cw ^ l1) {
          var h1 = (a0 + a1) / 2;
          x0 = r1 * Math.cos(h1);
          y0 = r1 * Math.sin(h1);
          x1 = y1 = null;
        }
      } else {
        x0 = y0 = 0;
      }
      if (r0) {
        x2 = r0 * Math.cos(a1 - p0);
        y2 = r0 * Math.sin(a1 - p0);
        x3 = r0 * Math.cos(a0 + p0);
        y3 = r0 * Math.sin(a0 + p0);
        var l0 = Math.abs(a0 - a1 + 2 * p0) <= π ? 0 : 1;
        if (p0 && d3_svg_arcSweep(x2, y2, x3, y3) === 1 - cw ^ l0) {
          var h0 = (a0 + a1) / 2;
          x2 = r0 * Math.cos(h0);
          y2 = r0 * Math.sin(h0);
          x3 = y3 = null;
        }
      } else {
        x2 = y2 = 0;
      }
      if (da > ε && (rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > .001) {
        cr = r0 < r1 ^ cw ? 0 : 1;
        var rc1 = rc, rc0 = rc;
        if (da < π) {
          var oc = x3 == null ? [ x2, y2 ] : x1 == null ? [ x0, y0 ] : d3_geom_polygonIntersect([ x0, y0 ], [ x3, y3 ], [ x1, y1 ], [ x2, y2 ]), ax = x0 - oc[0], ay = y0 - oc[1], bx = x1 - oc[0], by = y1 - oc[1], kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2), lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]);
          rc0 = Math.min(rc, (r0 - lc) / (kc - 1));
          rc1 = Math.min(rc, (r1 - lc) / (kc + 1));
        }
        if (x1 != null) {
          var t30 = d3_svg_arcCornerTangents(x3 == null ? [ x2, y2 ] : [ x3, y3 ], [ x0, y0 ], r1, rc1, cw), t12 = d3_svg_arcCornerTangents([ x1, y1 ], [ x2, y2 ], r1, rc1, cw);
          if (rc === rc1) {
            path.push("M", t30[0], "A", rc1, ",", rc1, " 0 0,", cr, " ", t30[1], "A", r1, ",", r1, " 0 ", 1 - cw ^ d3_svg_arcSweep(t30[1][0], t30[1][1], t12[1][0], t12[1][1]), ",", cw, " ", t12[1], "A", rc1, ",", rc1, " 0 0,", cr, " ", t12[0]);
          } else {
            path.push("M", t30[0], "A", rc1, ",", rc1, " 0 1,", cr, " ", t12[0]);
          }
        } else {
          path.push("M", x0, ",", y0);
        }
        if (x3 != null) {
          var t03 = d3_svg_arcCornerTangents([ x0, y0 ], [ x3, y3 ], r0, -rc0, cw), t21 = d3_svg_arcCornerTangents([ x2, y2 ], x1 == null ? [ x0, y0 ] : [ x1, y1 ], r0, -rc0, cw);
          if (rc === rc0) {
            path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t21[1], "A", r0, ",", r0, " 0 ", cw ^ d3_svg_arcSweep(t21[1][0], t21[1][1], t03[1][0], t03[1][1]), ",", 1 - cw, " ", t03[1], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]);
          } else {
            path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]);
          }
        } else {
          path.push("L", x2, ",", y2);
        }
      } else {
        path.push("M", x0, ",", y0);
        if (x1 != null) path.push("A", r1, ",", r1, " 0 ", l1, ",", cw, " ", x1, ",", y1);
        path.push("L", x2, ",", y2);
        if (x3 != null) path.push("A", r0, ",", r0, " 0 ", l0, ",", 1 - cw, " ", x3, ",", y3);
      }
      path.push("Z");
      return path.join("");
    }
    function circleSegment(r1, cw) {
      return "M0," + r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + -r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + r1;
    }
    arc.innerRadius = function(v) {
      if (!arguments.length) return innerRadius;
      innerRadius = d3_functor(v);
      return arc;
    };
    arc.outerRadius = function(v) {
      if (!arguments.length) return outerRadius;
      outerRadius = d3_functor(v);
      return arc;
    };
    arc.cornerRadius = function(v) {
      if (!arguments.length) return cornerRadius;
      cornerRadius = d3_functor(v);
      return arc;
    };
    arc.padRadius = function(v) {
      if (!arguments.length) return padRadius;
      padRadius = v == d3_svg_arcAuto ? d3_svg_arcAuto : d3_functor(v);
      return arc;
    };
    arc.startAngle = function(v) {
      if (!arguments.length) return startAngle;
      startAngle = d3_functor(v);
      return arc;
    };
    arc.endAngle = function(v) {
      if (!arguments.length) return endAngle;
      endAngle = d3_functor(v);
      return arc;
    };
    arc.padAngle = function(v) {
      if (!arguments.length) return padAngle;
      padAngle = d3_functor(v);
      return arc;
    };
    arc.centroid = function() {
      var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - halfπ;
      return [ Math.cos(a) * r, Math.sin(a) * r ];
    };
    return arc;
  };
  var d3_svg_arcAuto = "auto";
  function d3_svg_arcInnerRadius(d) {
    return d.innerRadius;
  }
  function d3_svg_arcOuterRadius(d) {
    return d.outerRadius;
  }
  function d3_svg_arcStartAngle(d) {
    return d.startAngle;
  }
  function d3_svg_arcEndAngle(d) {
    return d.endAngle;
  }
  function d3_svg_arcPadAngle(d) {
    return d && d.padAngle;
  }
  function d3_svg_arcSweep(x0, y0, x1, y1) {
    return (x0 - x1) * y0 - (y0 - y1) * x0 > 0 ? 0 : 1;
  }
  function d3_svg_arcCornerTangents(p0, p1, r1, rc, cw) {
    var x01 = p0[0] - p1[0], y01 = p0[1] - p1[1], lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x1 = p0[0] + ox, y1 = p0[1] + oy, x2 = p1[0] + ox, y2 = p1[1] + oy, x3 = (x1 + x2) / 2, y3 = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, d2 = dx * dx + dy * dy, r = r1 - rc, D = x1 * y2 - x2 * y1, d = (dy < 0 ? -1 : 1) * Math.sqrt(Math.max(0, r * r * d2 - D * D)), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x3, dy0 = cy0 - y3, dx1 = cx1 - x3, dy1 = cy1 - y3;
    if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1;
    return [ [ cx0 - ox, cy0 - oy ], [ cx0 * r1 / r, cy0 * r1 / r ] ];
  }
  function d3_svg_line(projection) {
    var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7;
    function line(data) {
      var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y);
      function segment() {
        segments.push("M", interpolate(projection(points), tension));
      }
      while (++i < n) {
        if (defined.call(this, d = data[i], i)) {
          points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]);
        } else if (points.length) {
          segment();
          points = [];
        }
      }
      if (points.length) segment();
      return segments.length ? segments.join("") : null;
    }
    line.x = function(_) {
      if (!arguments.length) return x;
      x = _;
      return line;
    };
    line.y = function(_) {
      if (!arguments.length) return y;
      y = _;
      return line;
    };
    line.defined = function(_) {
      if (!arguments.length) return defined;
      defined = _;
      return line;
    };
    line.interpolate = function(_) {
      if (!arguments.length) return interpolateKey;
      if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key;
      return line;
    };
    line.tension = function(_) {
      if (!arguments.length) return tension;
      tension = _;
      return line;
    };
    return line;
  }
  d3.svg.line = function() {
    return d3_svg_line(d3_identity);
  };
  var d3_svg_lineInterpolators = d3.map({
    linear: d3_svg_lineLinear,
    "linear-closed": d3_svg_lineLinearClosed,
    step: d3_svg_lineStep,
    "step-before": d3_svg_lineStepBefore,
    "step-after": d3_svg_lineStepAfter,
    basis: d3_svg_lineBasis,
    "basis-open": d3_svg_lineBasisOpen,
    "basis-closed": d3_svg_lineBasisClosed,
    bundle: d3_svg_lineBundle,
    cardinal: d3_svg_lineCardinal,
    "cardinal-open": d3_svg_lineCardinalOpen,
    "cardinal-closed": d3_svg_lineCardinalClosed,
    monotone: d3_svg_lineMonotone
  });
  d3_svg_lineInterpolators.forEach(function(key, value) {
    value.key = key;
    value.closed = /-closed$/.test(key);
  });
  function d3_svg_lineLinear(points) {
    return points.length > 1 ? points.join("L") : points + "Z";
  }
  function d3_svg_lineLinearClosed(points) {
    return points.join("L") + "Z";
  }
  function d3_svg_lineStep(points) {
    var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
    while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]);
    if (n > 1) path.push("H", p[0]);
    return path.join("");
  }
  function d3_svg_lineStepBefore(points) {
    var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
    while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]);
    return path.join("");
  }
  function d3_svg_lineStepAfter(points) {
    var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
    while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]);
    return path.join("");
  }
  function d3_svg_lineCardinalOpen(points, tension) {
    return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, -1), d3_svg_lineCardinalTangents(points, tension));
  }
  function d3_svg_lineCardinalClosed(points, tension) {
    return points.length < 3 ? d3_svg_lineLinearClosed(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), 
    points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension));
  }
  function d3_svg_lineCardinal(points, tension) {
    return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension));
  }
  function d3_svg_lineHermite(points, tangents) {
    if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) {
      return d3_svg_lineLinear(points);
    }
    var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1;
    if (quad) {
      path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1];
      p0 = points[1];
      pi = 2;
    }
    if (tangents.length > 1) {
      t = tangents[1];
      p = points[pi];
      pi++;
      path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
      for (var i = 2; i < tangents.length; i++, pi++) {
        p = points[pi];
        t = tangents[i];
        path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
      }
    }
    if (quad) {
      var lp = points[pi];
      path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1];
    }
    return path;
  }
  function d3_svg_lineCardinalTangents(points, tension) {
    var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length;
    while (++i < n) {
      p0 = p1;
      p1 = p2;
      p2 = points[i];
      tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]);
    }
    return tangents;
  }
  function d3_svg_lineBasis(points) {
    if (points.length < 3) return d3_svg_lineLinear(points);
    var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ];
    points.push(points[n - 1]);
    while (++i <= n) {
      pi = points[i];
      px.shift();
      px.push(pi[0]);
      py.shift();
      py.push(pi[1]);
      d3_svg_lineBasisBezier(path, px, py);
    }
    points.pop();
    path.push("L", pi);
    return path.join("");
  }
  function d3_svg_lineBasisOpen(points) {
    if (points.length < 4) return d3_svg_lineLinear(points);
    var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ];
    while (++i < 3) {
      pi = points[i];
      px.push(pi[0]);
      py.push(pi[1]);
    }
    path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py));
    --i;
    while (++i < n) {
      pi = points[i];
      px.shift();
      px.push(pi[0]);
      py.shift();
      py.push(pi[1]);
      d3_svg_lineBasisBezier(path, px, py);
    }
    return path.join("");
  }
  function d3_svg_lineBasisClosed(points) {
    var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = [];
    while (++i < 4) {
      pi = points[i % n];
      px.push(pi[0]);
      py.push(pi[1]);
    }
    path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ];
    --i;
    while (++i < m) {
      pi = points[i % n];
      px.shift();
      px.push(pi[0]);
      py.shift();
      py.push(pi[1]);
      d3_svg_lineBasisBezier(path, px, py);
    }
    return path.join("");
  }
  function d3_svg_lineBundle(points, tension) {
    var n = points.length - 1;
    if (n) {
      var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t;
      while (++i <= n) {
        p = points[i];
        t = i / n;
        p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx);
        p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy);
      }
    }
    return d3_svg_lineBasis(points);
  }
  function d3_svg_lineDot4(a, b) {
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
  }
  var d3_svg_lineBasisBezier1 = [ 0, 2 / 3, 1 / 3, 0 ], d3_svg_lineBasisBezier2 = [ 0, 1 / 3, 2 / 3, 0 ], d3_svg_lineBasisBezier3 = [ 0, 1 / 6, 2 / 3, 1 / 6 ];
  function d3_svg_lineBasisBezier(path, x, y) {
    path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y));
  }
  function d3_svg_lineSlope(p0, p1) {
    return (p1[1] - p0[1]) / (p1[0] - p0[0]);
  }
  function d3_svg_lineFiniteDifferences(points) {
    var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1);
    while (++i < j) {
      m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2;
    }
    m[i] = d;
    return m;
  }
  function d3_svg_lineMonotoneTangents(points) {
    var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1;
    while (++i < j) {
      d = d3_svg_lineSlope(points[i], points[i + 1]);
      if (abs(d) < ε) {
        m[i] = m[i + 1] = 0;
      } else {
        a = m[i] / d;
        b = m[i + 1] / d;
        s = a * a + b * b;
        if (s > 9) {
          s = d * 3 / Math.sqrt(s);
          m[i] = s * a;
          m[i + 1] = s * b;
        }
      }
    }
    i = -1;
    while (++i <= j) {
      s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i]));
      tangents.push([ s || 0, m[i] * s || 0 ]);
    }
    return tangents;
  }
  function d3_svg_lineMonotone(points) {
    return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points));
  }
  d3.svg.line.radial = function() {
    var line = d3_svg_line(d3_svg_lineRadial);
    line.radius = line.x, delete line.x;
    line.angle = line.y, delete line.y;
    return line;
  };
  function d3_svg_lineRadial(points) {
    var point, i = -1, n = points.length, r, a;
    while (++i < n) {
      point = points[i];
      r = point[0];
      a = point[1] - halfπ;
      point[0] = r * Math.cos(a);
      point[1] = r * Math.sin(a);
    }
    return points;
  }
  function d3_svg_area(projection) {
    var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7;
    function area(data) {
      var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() {
        return x;
      } : d3_functor(x1), fy1 = y0 === y1 ? function() {
        return y;
      } : d3_functor(y1), x, y;
      function segment() {
        segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z");
      }
      while (++i < n) {
        if (defined.call(this, d = data[i], i)) {
          points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]);
          points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]);
        } else if (points0.length) {
          segment();
          points0 = [];
          points1 = [];
        }
      }
      if (points0.length) segment();
      return segments.length ? segments.join("") : null;
    }
    area.x = function(_) {
      if (!arguments.length) return x1;
      x0 = x1 = _;
      return area;
    };
    area.x0 = function(_) {
      if (!arguments.length) return x0;
      x0 = _;
      return area;
    };
    area.x1 = function(_) {
      if (!arguments.length) return x1;
      x1 = _;
      return area;
    };
    area.y = function(_) {
      if (!arguments.length) return y1;
      y0 = y1 = _;
      return area;
    };
    area.y0 = function(_) {
      if (!arguments.length) return y0;
      y0 = _;
      return area;
    };
    area.y1 = function(_) {
      if (!arguments.length) return y1;
      y1 = _;
      return area;
    };
    area.defined = function(_) {
      if (!arguments.length) return defined;
      defined = _;
      return area;
    };
    area.interpolate = function(_) {
      if (!arguments.length) return interpolateKey;
      if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key;
      interpolateReverse = interpolate.reverse || interpolate;
      L = interpolate.closed ? "M" : "L";
      return area;
    };
    area.tension = function(_) {
      if (!arguments.length) return tension;
      tension = _;
      return area;
    };
    return area;
  }
  d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter;
  d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore;
  d3.svg.area = function() {
    return d3_svg_area(d3_identity);
  };
  d3.svg.area.radial = function() {
    var area = d3_svg_area(d3_svg_lineRadial);
    area.radius = area.x, delete area.x;
    area.innerRadius = area.x0, delete area.x0;
    area.outerRadius = area.x1, delete area.x1;
    area.angle = area.y, delete area.y;
    area.startAngle = area.y0, delete area.y0;
    area.endAngle = area.y1, delete area.y1;
    return area;
  };
  d3.svg.chord = function() {
    var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle;
    function chord(d, i) {
      var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i);
      return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z";
    }
    function subgroup(self, f, d, i) {
      var subgroup = f.call(self, d, i), r = radius.call(self, subgroup, i), a0 = startAngle.call(self, subgroup, i) - halfπ, a1 = endAngle.call(self, subgroup, i) - halfπ;
      return {
        r: r,
        a0: a0,
        a1: a1,
        p0: [ r * Math.cos(a0), r * Math.sin(a0) ],
        p1: [ r * Math.cos(a1), r * Math.sin(a1) ]
      };
    }
    function equals(a, b) {
      return a.a0 == b.a0 && a.a1 == b.a1;
    }
    function arc(r, p, a) {
      return "A" + r + "," + r + " 0 " + +(a > π) + ",1 " + p;
    }
    function curve(r0, p0, r1, p1) {
      return "Q 0,0 " + p1;
    }
    chord.radius = function(v) {
      if (!arguments.length) return radius;
      radius = d3_functor(v);
      return chord;
    };
    chord.source = function(v) {
      if (!arguments.length) return source;
      source = d3_functor(v);
      return chord;
    };
    chord.target = function(v) {
      if (!arguments.length) return target;
      target = d3_functor(v);
      return chord;
    };
    chord.startAngle = function(v) {
      if (!arguments.length) return startAngle;
      startAngle = d3_functor(v);
      return chord;
    };
    chord.endAngle = function(v) {
      if (!arguments.length) return endAngle;
      endAngle = d3_functor(v);
      return chord;
    };
    return chord;
  };
  function d3_svg_chordRadius(d) {
    return d.radius;
  }
  d3.svg.diagonal = function() {
    var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection;
    function diagonal(d, i) {
      var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, {
        x: p0.x,
        y: m
      }, {
        x: p3.x,
        y: m
      }, p3 ];
      p = p.map(projection);
      return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3];
    }
    diagonal.source = function(x) {
      if (!arguments.length) return source;
      source = d3_functor(x);
      return diagonal;
    };
    diagonal.target = function(x) {
      if (!arguments.length) return target;
      target = d3_functor(x);
      return diagonal;
    };
    diagonal.projection = function(x) {
      if (!arguments.length) return projection;
      projection = x;
      return diagonal;
    };
    return diagonal;
  };
  function d3_svg_diagonalProjection(d) {
    return [ d.x, d.y ];
  }
  d3.svg.diagonal.radial = function() {
    var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection;
    diagonal.projection = function(x) {
      return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection;
    };
    return diagonal;
  };
  function d3_svg_diagonalRadialProjection(projection) {
    return function() {
      var d = projection.apply(this, arguments), r = d[0], a = d[1] - halfπ;
      return [ r * Math.cos(a), r * Math.sin(a) ];
    };
  }
  d3.svg.symbol = function() {
    var type = d3_svg_symbolType, size = d3_svg_symbolSize;
    function symbol(d, i) {
      return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i));
    }
    symbol.type = function(x) {
      if (!arguments.length) return type;
      type = d3_functor(x);
      return symbol;
    };
    symbol.size = function(x) {
      if (!arguments.length) return size;
      size = d3_functor(x);
      return symbol;
    };
    return symbol;
  };
  function d3_svg_symbolSize() {
    return 64;
  }
  function d3_svg_symbolType() {
    return "circle";
  }
  function d3_svg_symbolCircle(size) {
    var r = Math.sqrt(size / π);
    return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z";
  }
  var d3_svg_symbols = d3.map({
    circle: d3_svg_symbolCircle,
    cross: function(size) {
      var r = Math.sqrt(size / 5) / 2;
      return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z";
    },
    diamond: function(size) {
      var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30;
      return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z";
    },
    square: function(size) {
      var r = Math.sqrt(size) / 2;
      return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z";
    },
    "triangle-down": function(size) {
      var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2;
      return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z";
    },
    "triangle-up": function(size) {
      var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2;
      return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z";
    }
  });
  d3.svg.symbolTypes = d3_svg_symbols.keys();
  var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians);
  d3_selectionPrototype.transition = function(name) {
    var id = d3_transitionInheritId || ++d3_transitionId, ns = d3_transitionNamespace(name), subgroups = [], subgroup, node, transition = d3_transitionInherit || {
      time: Date.now(),
      ease: d3_ease_cubicInOut,
      delay: 0,
      duration: 250
    };
    for (var j = -1, m = this.length; ++j < m; ) {
      subgroups.push(subgroup = []);
      for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
        if (node = group[i]) d3_transitionNode(node, i, ns, id, transition);
        subgroup.push(node);
      }
    }
    return d3_transition(subgroups, ns, id);
  };
  d3_selectionPrototype.interrupt = function(name) {
    return this.each(name == null ? d3_selection_interrupt : d3_selection_interruptNS(d3_transitionNamespace(name)));
  };
  var d3_selection_interrupt = d3_selection_interruptNS(d3_transitionNamespace());
  function d3_selection_interruptNS(ns) {
    return function() {
      var lock, activeId, active;
      if ((lock = this[ns]) && (active = lock[activeId = lock.active])) {
        active.timer.c = null;
        active.timer.t = NaN;
        if (--lock.count) delete lock[activeId]; else delete this[ns];
        lock.active += .5;
        active.event && active.event.interrupt.call(this, this.__data__, active.index);
      }
    };
  }
  function d3_transition(groups, ns, id) {
    d3_subclass(groups, d3_transitionPrototype);
    groups.namespace = ns;
    groups.id = id;
    return groups;
  }
  var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit;
  d3_transitionPrototype.call = d3_selectionPrototype.call;
  d3_transitionPrototype.empty = d3_selectionPrototype.empty;
  d3_transitionPrototype.node = d3_selectionPrototype.node;
  d3_transitionPrototype.size = d3_selectionPrototype.size;
  d3.transition = function(selection, name) {
    return selection && selection.transition ? d3_transitionInheritId ? selection.transition(name) : selection : d3.selection().transition(selection);
  };
  d3.transition.prototype = d3_transitionPrototype;
  d3_transitionPrototype.select = function(selector) {
    var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnode, node;
    selector = d3_selection_selector(selector);
    for (var j = -1, m = this.length; ++j < m; ) {
      subgroups.push(subgroup = []);
      for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
        if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) {
          if ("__data__" in node) subnode.__data__ = node.__data__;
          d3_transitionNode(subnode, i, ns, id, node[ns][id]);
          subgroup.push(subnode);
        } else {
          subgroup.push(null);
        }
      }
    }
    return d3_transition(subgroups, ns, id);
  };
  d3_transitionPrototype.selectAll = function(selector) {
    var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnodes, node, subnode, transition;
    selector = d3_selection_selectorAll(selector);
    for (var j = -1, m = this.length; ++j < m; ) {
      for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
        if (node = group[i]) {
          transition = node[ns][id];
          subnodes = selector.call(node, node.__data__, i, j);
          subgroups.push(subgroup = []);
          for (var k = -1, o = subnodes.length; ++k < o; ) {
            if (subnode = subnodes[k]) d3_transitionNode(subnode, k, ns, id, transition);
            subgroup.push(subnode);
          }
        }
      }
    }
    return d3_transition(subgroups, ns, id);
  };
  d3_transitionPrototype.filter = function(filter) {
    var subgroups = [], subgroup, group, node;
    if (typeof filter !== "function") filter = d3_selection_filter(filter);
    for (var j = 0, m = this.length; j < m; j++) {
      subgroups.push(subgroup = []);
      for (var group = this[j], i = 0, n = group.length; i < n; i++) {
        if ((node = group[i]) && filter.call(node, node.__data__, i, j)) {
          subgroup.push(node);
        }
      }
    }
    return d3_transition(subgroups, this.namespace, this.id);
  };
  d3_transitionPrototype.tween = function(name, tween) {
    var id = this.id, ns = this.namespace;
    if (arguments.length < 2) return this.node()[ns][id].tween.get(name);
    return d3_selection_each(this, tween == null ? function(node) {
      node[ns][id].tween.remove(name);
    } : function(node) {
      node[ns][id].tween.set(name, tween);
    });
  };
  function d3_transition_tween(groups, name, value, tween) {
    var id = groups.id, ns = groups.namespace;
    return d3_selection_each(groups, typeof value === "function" ? function(node, i, j) {
      node[ns][id].tween.set(name, tween(value.call(node, node.__data__, i, j)));
    } : (value = tween(value), function(node) {
      node[ns][id].tween.set(name, value);
    }));
  }
  d3_transitionPrototype.attr = function(nameNS, value) {
    if (arguments.length < 2) {
      for (value in nameNS) this.attr(value, nameNS[value]);
      return this;
    }
    var interpolate = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name = d3.ns.qualify(nameNS);
    function attrNull() {
      this.removeAttribute(name);
    }
    function attrNullNS() {
      this.removeAttributeNS(name.space, name.local);
    }
    function attrTween(b) {
      return b == null ? attrNull : (b += "", function() {
        var a = this.getAttribute(name), i;
        return a !== b && (i = interpolate(a, b), function(t) {
          this.setAttribute(name, i(t));
        });
      });
    }
    function attrTweenNS(b) {
      return b == null ? attrNullNS : (b += "", function() {
        var a = this.getAttributeNS(name.space, name.local), i;
        return a !== b && (i = interpolate(a, b), function(t) {
          this.setAttributeNS(name.space, name.local, i(t));
        });
      });
    }
    return d3_transition_tween(this, "attr." + nameNS, value, name.local ? attrTweenNS : attrTween);
  };
  d3_transitionPrototype.attrTween = function(nameNS, tween) {
    var name = d3.ns.qualify(nameNS);
    function attrTween(d, i) {
      var f = tween.call(this, d, i, this.getAttribute(name));
      return f && function(t) {
        this.setAttribute(name, f(t));
      };
    }
    function attrTweenNS(d, i) {
      var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local));
      return f && function(t) {
        this.setAttributeNS(name.space, name.local, f(t));
      };
    }
    return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween);
  };
  d3_transitionPrototype.style = function(name, value, priority) {
    var n = arguments.length;
    if (n < 3) {
      if (typeof name !== "string") {
        if (n < 2) value = "";
        for (priority in name) this.style(priority, name[priority], value);
        return this;
      }
      priority = "";
    }
    function styleNull() {
      this.style.removeProperty(name);
    }
    function styleString(b) {
      return b == null ? styleNull : (b += "", function() {
        var a = d3_window(this).getComputedStyle(this, null).getPropertyValue(name), i;
        return a !== b && (i = d3_interpolate(a, b), function(t) {
          this.style.setProperty(name, i(t), priority);
        });
      });
    }
    return d3_transition_tween(this, "style." + name, value, styleString);
  };
  d3_transitionPrototype.styleTween = function(name, tween, priority) {
    if (arguments.length < 3) priority = "";
    function styleTween(d, i) {
      var f = tween.call(this, d, i, d3_window(this).getComputedStyle(this, null).getPropertyValue(name));
      return f && function(t) {
        this.style.setProperty(name, f(t), priority);
      };
    }
    return this.tween("style." + name, styleTween);
  };
  d3_transitionPrototype.text = function(value) {
    return d3_transition_tween(this, "text", value, d3_transition_text);
  };
  function d3_transition_text(b) {
    if (b == null) b = "";
    return function() {
      this.textContent = b;
    };
  }
  d3_transitionPrototype.remove = function() {
    var ns = this.namespace;
    return this.each("end.transition", function() {
      var p;
      if (this[ns].count < 2 && (p = this.parentNode)) p.removeChild(this);
    });
  };
  d3_transitionPrototype.ease = function(value) {
    var id = this.id, ns = this.namespace;
    if (arguments.length < 1) return this.node()[ns][id].ease;
    if (typeof value !== "function") value = d3.ease.apply(d3, arguments);
    return d3_selection_each(this, function(node) {
      node[ns][id].ease = value;
    });
  };
  d3_transitionPrototype.delay = function(value) {
    var id = this.id, ns = this.namespace;
    if (arguments.length < 1) return this.node()[ns][id].delay;
    return d3_selection_each(this, typeof value === "function" ? function(node, i, j) {
      node[ns][id].delay = +value.call(node, node.__data__, i, j);
    } : (value = +value, function(node) {
      node[ns][id].delay = value;
    }));
  };
  d3_transitionPrototype.duration = function(value) {
    var id = this.id, ns = this.namespace;
    if (arguments.length < 1) return this.node()[ns][id].duration;
    return d3_selection_each(this, typeof value === "function" ? function(node, i, j) {
      node[ns][id].duration = Math.max(1, value.call(node, node.__data__, i, j));
    } : (value = Math.max(1, value), function(node) {
      node[ns][id].duration = value;
    }));
  };
  d3_transitionPrototype.each = function(type, listener) {
    var id = this.id, ns = this.namespace;
    if (arguments.length < 2) {
      var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId;
      try {
        d3_transitionInheritId = id;
        d3_selection_each(this, function(node, i, j) {
          d3_transitionInherit = node[ns][id];
          type.call(node, node.__data__, i, j);
        });
      } finally {
        d3_transitionInherit = inherit;
        d3_transitionInheritId = inheritId;
      }
    } else {
      d3_selection_each(this, function(node) {
        var transition = node[ns][id];
        (transition.event || (transition.event = d3.dispatch("start", "end", "interrupt"))).on(type, listener);
      });
    }
    return this;
  };
  d3_transitionPrototype.transition = function() {
    var id0 = this.id, id1 = ++d3_transitionId, ns = this.namespace, subgroups = [], subgroup, group, node, transition;
    for (var j = 0, m = this.length; j < m; j++) {
      subgroups.push(subgroup = []);
      for (var group = this[j], i = 0, n = group.length; i < n; i++) {
        if (node = group[i]) {
          transition = node[ns][id0];
          d3_transitionNode(node, i, ns, id1, {
            time: transition.time,
            ease: transition.ease,
            delay: transition.delay + transition.duration,
            duration: transition.duration
          });
        }
        subgroup.push(node);
      }
    }
    return d3_transition(subgroups, ns, id1);
  };
  function d3_transitionNamespace(name) {
    return name == null ? "__transition__" : "__transition_" + name + "__";
  }
  function d3_transitionNode(node, i, ns, id, inherit) {
    var lock = node[ns] || (node[ns] = {
      active: 0,
      count: 0
    }), transition = lock[id], time, timer, duration, ease, tweens;
    function schedule(elapsed) {
      var delay = transition.delay;
      timer.t = delay + time;
      if (delay <= elapsed) return start(elapsed - delay);
      timer.c = start;
    }
    function start(elapsed) {
      var activeId = lock.active, active = lock[activeId];
      if (active) {
        active.timer.c = null;
        active.timer.t = NaN;
        --lock.count;
        delete lock[activeId];
        active.event && active.event.interrupt.call(node, node.__data__, active.index);
      }
      for (var cancelId in lock) {
        if (+cancelId < id) {
          var cancel = lock[cancelId];
          cancel.timer.c = null;
          cancel.timer.t = NaN;
          --lock.count;
          delete lock[cancelId];
        }
      }
      timer.c = tick;
      d3_timer(function() {
        if (timer.c && tick(elapsed || 1)) {
          timer.c = null;
          timer.t = NaN;
        }
        return 1;
      }, 0, time);
      lock.active = id;
      transition.event && transition.event.start.call(node, node.__data__, i);
      tweens = [];
      transition.tween.forEach(function(key, value) {
        if (value = value.call(node, node.__data__, i)) {
          tweens.push(value);
        }
      });
      ease = transition.ease;
      duration = transition.duration;
    }
    function tick(elapsed) {
      var t = elapsed / duration, e = ease(t), n = tweens.length;
      while (n > 0) {
        tweens[--n].call(node, e);
      }
      if (t >= 1) {
        transition.event && transition.event.end.call(node, node.__data__, i);
        if (--lock.count) delete lock[id]; else delete node[ns];
        return 1;
      }
    }
    if (!transition) {
      time = inherit.time;
      timer = d3_timer(schedule, 0, time);
      transition = lock[id] = {
        tween: new d3_Map(),
        time: time,
        timer: timer,
        delay: inherit.delay,
        duration: inherit.duration,
        ease: inherit.ease,
        index: i
      };
      inherit = null;
      ++lock.count;
    }
  }
  d3.svg.axis = function() {
    var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_;
    function axis(g) {
      g.each(function() {
        var g = d3.select(this);
        var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy();
        var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d3.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d3.transition(tick.order()).style("opacity", 1), tickSpacing = Math.max(innerTickSize, 0) + tickPadding, tickTransform;
        var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"), 
        d3.transition(path));
        tickEnter.append("line");
        tickEnter.append("text");
        var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"), sign = orient === "top" || orient === "left" ? -1 : 1, x1, x2, y1, y2;
        if (orient === "bottom" || orient === "top") {
          tickTransform = d3_svg_axisX, x1 = "x", y1 = "y", x2 = "x2", y2 = "y2";
          text.attr("dy", sign < 0 ? "0em" : ".71em").style("text-anchor", "middle");
          pathUpdate.attr("d", "M" + range[0] + "," + sign * outerTickSize + "V0H" + range[1] + "V" + sign * outerTickSize);
        } else {
          tickTransform = d3_svg_axisY, x1 = "y", y1 = "x", x2 = "y2", y2 = "x2";
          text.attr("dy", ".32em").style("text-anchor", sign < 0 ? "end" : "start");
          pathUpdate.attr("d", "M" + sign * outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + sign * outerTickSize);
        }
        lineEnter.attr(y2, sign * innerTickSize);
        textEnter.attr(y1, sign * tickSpacing);
        lineUpdate.attr(x2, 0).attr(y2, sign * innerTickSize);
        textUpdate.attr(x1, 0).attr(y1, sign * tickSpacing);
        if (scale1.rangeBand) {
          var x = scale1, dx = x.rangeBand() / 2;
          scale0 = scale1 = function(d) {
            return x(d) + dx;
          };
        } else if (scale0.rangeBand) {
          scale0 = scale1;
        } else {
          tickExit.call(tickTransform, scale1, scale0);
        }
        tickEnter.call(tickTransform, scale0, scale1);
        tickUpdate.call(tickTransform, scale1, scale1);
      });
    }
    axis.scale = function(x) {
      if (!arguments.length) return scale;
      scale = x;
      return axis;
    };
    axis.orient = function(x) {
      if (!arguments.length) return orient;
      orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient;
      return axis;
    };
    axis.ticks = function() {
      if (!arguments.length) return tickArguments_;
      tickArguments_ = d3_array(arguments);
      return axis;
    };
    axis.tickValues = function(x) {
      if (!arguments.length) return tickValues;
      tickValues = x;
      return axis;
    };
    axis.tickFormat = function(x) {
      if (!arguments.length) return tickFormat_;
      tickFormat_ = x;
      return axis;
    };
    axis.tickSize = function(x) {
      var n = arguments.length;
      if (!n) return innerTickSize;
      innerTickSize = +x;
      outerTickSize = +arguments[n - 1];
      return axis;
    };
    axis.innerTickSize = function(x) {
      if (!arguments.length) return innerTickSize;
      innerTickSize = +x;
      return axis;
    };
    axis.outerTickSize = function(x) {
      if (!arguments.length) return outerTickSize;
      outerTickSize = +x;
      return axis;
    };
    axis.tickPadding = function(x) {
      if (!arguments.length) return tickPadding;
      tickPadding = +x;
      return axis;
    };
    axis.tickSubdivide = function() {
      return arguments.length && axis;
    };
    return axis;
  };
  var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = {
    top: 1,
    right: 1,
    bottom: 1,
    left: 1
  };
  function d3_svg_axisX(selection, x0, x1) {
    selection.attr("transform", function(d) {
      var v0 = x0(d);
      return "translate(" + (isFinite(v0) ? v0 : x1(d)) + ",0)";
    });
  }
  function d3_svg_axisY(selection, y0, y1) {
    selection.attr("transform", function(d) {
      var v0 = y0(d);
      return "translate(0," + (isFinite(v0) ? v0 : y1(d)) + ")";
    });
  }
  d3.svg.brush = function() {
    var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [ 0, 0 ], yExtent = [ 0, 0 ], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0];
    function brush(g) {
      g.each(function() {
        var g = d3.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart);
        var background = g.selectAll(".background").data([ 0 ]);
        background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair");
        g.selectAll(".extent").data([ 0 ]).enter().append("rect").attr("class", "extent").style("cursor", "move");
        var resize = g.selectAll(".resize").data(resizes, d3_identity);
        resize.exit().remove();
        resize.enter().append("g").attr("class", function(d) {
          return "resize " + d;
        }).style("cursor", function(d) {
          return d3_svg_brushCursor[d];
        }).append("rect").attr("x", function(d) {
          return /[ew]$/.test(d) ? -3 : null;
        }).attr("y", function(d) {
          return /^[ns]/.test(d) ? -3 : null;
        }).attr("width", 6).attr("height", 6).style("visibility", "hidden");
        resize.style("display", brush.empty() ? "none" : null);
        var gUpdate = d3.transition(g), backgroundUpdate = d3.transition(background), range;
        if (x) {
          range = d3_scaleRange(x);
          backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]);
          redrawX(gUpdate);
        }
        if (y) {
          range = d3_scaleRange(y);
          backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]);
          redrawY(gUpdate);
        }
        redraw(gUpdate);
      });
    }
    brush.event = function(g) {
      g.each(function() {
        var event_ = event.of(this, arguments), extent1 = {
          x: xExtent,
          y: yExtent,
          i: xExtentDomain,
          j: yExtentDomain
        }, extent0 = this.__chart__ || extent1;
        this.__chart__ = extent1;
        if (d3_transitionInheritId) {
          d3.select(this).transition().each("start.brush", function() {
            xExtentDomain = extent0.i;
            yExtentDomain = extent0.j;
            xExtent = extent0.x;
            yExtent = extent0.y;
            event_({
              type: "brushstart"
            });
          }).tween("brush:brush", function() {
            var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y);
            xExtentDomain = yExtentDomain = null;
            return function(t) {
              xExtent = extent1.x = xi(t);
              yExtent = extent1.y = yi(t);
              event_({
                type: "brush",
                mode: "resize"
              });
            };
          }).each("end.brush", function() {
            xExtentDomain = extent1.i;
            yExtentDomain = extent1.j;
            event_({
              type: "brush",
              mode: "resize"
            });
            event_({
              type: "brushend"
            });
          });
        } else {
          event_({
            type: "brushstart"
          });
          event_({
            type: "brush",
            mode: "resize"
          });
          event_({
            type: "brushend"
          });
        }
      });
    };
    function redraw(g) {
      g.selectAll(".resize").attr("transform", function(d) {
        return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")";
      });
    }
    function redrawX(g) {
      g.select(".extent").attr("x", xExtent[0]);
      g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]);
    }
    function redrawY(g) {
      g.select(".extent").attr("y", yExtent[0]);
      g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]);
    }
    function brushstart() {
      var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(target), center, origin = d3.mouse(target), offset;
      var w = d3.select(d3_window(target)).on("keydown.brush", keydown).on("keyup.brush", keyup);
      if (d3.event.changedTouches) {
        w.on("touchmove.brush", brushmove).on("touchend.brush", brushend);
      } else {
        w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend);
      }
      g.interrupt().selectAll("*").interrupt();
      if (dragging) {
        origin[0] = xExtent[0] - origin[0];
        origin[1] = yExtent[0] - origin[1];
      } else if (resizing) {
        var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing);
        offset = [ xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1] ];
        origin[0] = xExtent[ex];
        origin[1] = yExtent[ey];
      } else if (d3.event.altKey) center = origin.slice();
      g.style("pointer-events", "none").selectAll(".resize").style("display", null);
      d3.select("body").style("cursor", eventTarget.style("cursor"));
      event_({
        type: "brushstart"
      });
      brushmove();
      function keydown() {
        if (d3.event.keyCode == 32) {
          if (!dragging) {
            center = null;
            origin[0] -= xExtent[1];
            origin[1] -= yExtent[1];
            dragging = 2;
          }
          d3_eventPreventDefault();
        }
      }
      function keyup() {
        if (d3.event.keyCode == 32 && dragging == 2) {
          origin[0] += xExtent[1];
          origin[1] += yExtent[1];
          dragging = 0;
          d3_eventPreventDefault();
        }
      }
      function brushmove() {
        var point = d3.mouse(target), moved = false;
        if (offset) {
          point[0] += offset[0];
          point[1] += offset[1];
        }
        if (!dragging) {
          if (d3.event.altKey) {
            if (!center) center = [ (xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2 ];
            origin[0] = xExtent[+(point[0] < center[0])];
            origin[1] = yExtent[+(point[1] < center[1])];
          } else center = null;
        }
        if (resizingX && move1(point, x, 0)) {
          redrawX(g);
          moved = true;
        }
        if (resizingY && move1(point, y, 1)) {
          redrawY(g);
          moved = true;
        }
        if (moved) {
          redraw(g);
          event_({
            type: "brush",
            mode: dragging ? "move" : "resize"
          });
        }
      }
      function move1(point, scale, i) {
        var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], extent = i ? yExtent : xExtent, size = extent[1] - extent[0], min, max;
        if (dragging) {
          r0 -= position;
          r1 -= size + position;
        }
        min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i];
        if (dragging) {
          max = (min += position) + size;
        } else {
          if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min));
          if (position < min) {
            max = min;
            min = position;
          } else {
            max = position;
          }
        }
        if (extent[0] != min || extent[1] != max) {
          if (i) yExtentDomain = null; else xExtentDomain = null;
          extent[0] = min;
          extent[1] = max;
          return true;
        }
      }
      function brushend() {
        brushmove();
        g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null);
        d3.select("body").style("cursor", null);
        w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null);
        dragRestore();
        event_({
          type: "brushend"
        });
      }
    }
    brush.x = function(z) {
      if (!arguments.length) return x;
      x = z;
      resizes = d3_svg_brushResizes[!x << 1 | !y];
      return brush;
    };
    brush.y = function(z) {
      if (!arguments.length) return y;
      y = z;
      resizes = d3_svg_brushResizes[!x << 1 | !y];
      return brush;
    };
    brush.clamp = function(z) {
      if (!arguments.length) return x && y ? [ xClamp, yClamp ] : x ? xClamp : y ? yClamp : null;
      if (x && y) xClamp = !!z[0], yClamp = !!z[1]; else if (x) xClamp = !!z; else if (y) yClamp = !!z;
      return brush;
    };
    brush.extent = function(z) {
      var x0, x1, y0, y1, t;
      if (!arguments.length) {
        if (x) {
          if (xExtentDomain) {
            x0 = xExtentDomain[0], x1 = xExtentDomain[1];
          } else {
            x0 = xExtent[0], x1 = xExtent[1];
            if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1);
            if (x1 < x0) t = x0, x0 = x1, x1 = t;
          }
        }
        if (y) {
          if (yExtentDomain) {
            y0 = yExtentDomain[0], y1 = yExtentDomain[1];
          } else {
            y0 = yExtent[0], y1 = yExtent[1];
            if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1);
            if (y1 < y0) t = y0, y0 = y1, y1 = t;
          }
        }
        return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ];
      }
      if (x) {
        x0 = z[0], x1 = z[1];
        if (y) x0 = x0[0], x1 = x1[0];
        xExtentDomain = [ x0, x1 ];
        if (x.invert) x0 = x(x0), x1 = x(x1);
        if (x1 < x0) t = x0, x0 = x1, x1 = t;
        if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [ x0, x1 ];
      }
      if (y) {
        y0 = z[0], y1 = z[1];
        if (x) y0 = y0[1], y1 = y1[1];
        yExtentDomain = [ y0, y1 ];
        if (y.invert) y0 = y(y0), y1 = y(y1);
        if (y1 < y0) t = y0, y0 = y1, y1 = t;
        if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [ y0, y1 ];
      }
      return brush;
    };
    brush.clear = function() {
      if (!brush.empty()) {
        xExtent = [ 0, 0 ], yExtent = [ 0, 0 ];
        xExtentDomain = yExtentDomain = null;
      }
      return brush;
    };
    brush.empty = function() {
      return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1];
    };
    return d3.rebind(brush, event, "on");
  };
  var d3_svg_brushCursor = {
    n: "ns-resize",
    e: "ew-resize",
    s: "ns-resize",
    w: "ew-resize",
    nw: "nwse-resize",
    ne: "nesw-resize",
    se: "nwse-resize",
    sw: "nesw-resize"
  };
  var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ];
  var d3_time_format = d3_time.format = d3_locale_enUS.timeFormat;
  var d3_time_formatUtc = d3_time_format.utc;
  var d3_time_formatIso = d3_time_formatUtc("%Y-%m-%dT%H:%M:%S.%LZ");
  d3_time_format.iso = Date.prototype.toISOString && +new Date("2000-01-01T00:00:00.000Z") ? d3_time_formatIsoNative : d3_time_formatIso;
  function d3_time_formatIsoNative(date) {
    return date.toISOString();
  }
  d3_time_formatIsoNative.parse = function(string) {
    var date = new Date(string);
    return isNaN(date) ? null : date;
  };
  d3_time_formatIsoNative.toString = d3_time_formatIso.toString;
  d3_time.second = d3_time_interval(function(date) {
    return new d3_date(Math.floor(date / 1e3) * 1e3);
  }, function(date, offset) {
    date.setTime(date.getTime() + Math.floor(offset) * 1e3);
  }, function(date) {
    return date.getSeconds();
  });
  d3_time.seconds = d3_time.second.range;
  d3_time.seconds.utc = d3_time.second.utc.range;
  d3_time.minute = d3_time_interval(function(date) {
    return new d3_date(Math.floor(date / 6e4) * 6e4);
  }, function(date, offset) {
    date.setTime(date.getTime() + Math.floor(offset) * 6e4);
  }, function(date) {
    return date.getMinutes();
  });
  d3_time.minutes = d3_time.minute.range;
  d3_time.minutes.utc = d3_time.minute.utc.range;
  d3_time.hour = d3_time_interval(function(date) {
    var timezone = date.getTimezoneOffset() / 60;
    return new d3_date((Math.floor(date / 36e5 - timezone) + timezone) * 36e5);
  }, function(date, offset) {
    date.setTime(date.getTime() + Math.floor(offset) * 36e5);
  }, function(date) {
    return date.getHours();
  });
  d3_time.hours = d3_time.hour.range;
  d3_time.hours.utc = d3_time.hour.utc.range;
  d3_time.month = d3_time_interval(function(date) {
    date = d3_time.day(date);
    date.setDate(1);
    return date;
  }, function(date, offset) {
    date.setMonth(date.getMonth() + offset);
  }, function(date) {
    return date.getMonth();
  });
  d3_time.months = d3_time.month.range;
  d3_time.months.utc = d3_time.month.utc.range;
  function d3_time_scale(linear, methods, format) {
    function scale(x) {
      return linear(x);
    }
    scale.invert = function(x) {
      return d3_time_scaleDate(linear.invert(x));
    };
    scale.domain = function(x) {
      if (!arguments.length) return linear.domain().map(d3_time_scaleDate);
      linear.domain(x);
      return scale;
    };
    function tickMethod(extent, count) {
      var span = extent[1] - extent[0], target = span / count, i = d3.bisect(d3_time_scaleSteps, target);
      return i == d3_time_scaleSteps.length ? [ methods.year, d3_scale_linearTickRange(extent.map(function(d) {
        return d / 31536e6;
      }), count)[2] ] : !i ? [ d3_time_scaleMilliseconds, d3_scale_linearTickRange(extent, count)[2] ] : methods[target / d3_time_scaleSteps[i - 1] < d3_time_scaleSteps[i] / target ? i - 1 : i];
    }
    scale.nice = function(interval, skip) {
      var domain = scale.domain(), extent = d3_scaleExtent(domain), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" && tickMethod(extent, interval);
      if (method) interval = method[0], skip = method[1];
      function skipped(date) {
        return !isNaN(date) && !interval.range(date, d3_time_scaleDate(+date + 1), skip).length;
      }
      return scale.domain(d3_scale_nice(domain, skip > 1 ? {
        floor: function(date) {
          while (skipped(date = interval.floor(date))) date = d3_time_scaleDate(date - 1);
          return date;
        },
        ceil: function(date) {
          while (skipped(date = interval.ceil(date))) date = d3_time_scaleDate(+date + 1);
          return date;
        }
      } : interval));
    };
    scale.ticks = function(interval, skip) {
      var extent = d3_scaleExtent(scale.domain()), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" ? tickMethod(extent, interval) : !interval.range && [ {
        range: interval
      }, skip ];
      if (method) interval = method[0], skip = method[1];
      return interval.range(extent[0], d3_time_scaleDate(+extent[1] + 1), skip < 1 ? 1 : skip);
    };
    scale.tickFormat = function() {
      return format;
    };
    scale.copy = function() {
      return d3_time_scale(linear.copy(), methods, format);
    };
    return d3_scale_linearRebind(scale, linear);
  }
  function d3_time_scaleDate(t) {
    return new Date(t);
  }
  var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ];
  var d3_time_scaleLocalMethods = [ [ d3_time.second, 1 ], [ d3_time.second, 5 ], [ d3_time.second, 15 ], [ d3_time.second, 30 ], [ d3_time.minute, 1 ], [ d3_time.minute, 5 ], [ d3_time.minute, 15 ], [ d3_time.minute, 30 ], [ d3_time.hour, 1 ], [ d3_time.hour, 3 ], [ d3_time.hour, 6 ], [ d3_time.hour, 12 ], [ d3_time.day, 1 ], [ d3_time.day, 2 ], [ d3_time.week, 1 ], [ d3_time.month, 1 ], [ d3_time.month, 3 ], [ d3_time.year, 1 ] ];
  var d3_time_scaleLocalFormat = d3_time_format.multi([ [ ".%L", function(d) {
    return d.getMilliseconds();
  } ], [ ":%S", function(d) {
    return d.getSeconds();
  } ], [ "%I:%M", function(d) {
    return d.getMinutes();
  } ], [ "%I %p", function(d) {
    return d.getHours();
  } ], [ "%a %d", function(d) {
    return d.getDay() && d.getDate() != 1;
  } ], [ "%b %d", function(d) {
    return d.getDate() != 1;
  } ], [ "%B", function(d) {
    return d.getMonth();
  } ], [ "%Y", d3_true ] ]);
  var d3_time_scaleMilliseconds = {
    range: function(start, stop, step) {
      return d3.range(Math.ceil(start / step) * step, +stop, step).map(d3_time_scaleDate);
    },
    floor: d3_identity,
    ceil: d3_identity
  };
  d3_time_scaleLocalMethods.year = d3_time.year;
  d3_time.scale = function() {
    return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat);
  };
  var d3_time_scaleUtcMethods = d3_time_scaleLocalMethods.map(function(m) {
    return [ m[0].utc, m[1] ];
  });
  var d3_time_scaleUtcFormat = d3_time_formatUtc.multi([ [ ".%L", function(d) {
    return d.getUTCMilliseconds();
  } ], [ ":%S", function(d) {
    return d.getUTCSeconds();
  } ], [ "%I:%M", function(d) {
    return d.getUTCMinutes();
  } ], [ "%I %p", function(d) {
    return d.getUTCHours();
  } ], [ "%a %d", function(d) {
    return d.getUTCDay() && d.getUTCDate() != 1;
  } ], [ "%b %d", function(d) {
    return d.getUTCDate() != 1;
  } ], [ "%B", function(d) {
    return d.getUTCMonth();
  } ], [ "%Y", d3_true ] ]);
  d3_time_scaleUtcMethods.year = d3_time.year.utc;
  d3_time.scale.utc = function() {
    return d3_time_scale(d3.scale.linear(), d3_time_scaleUtcMethods, d3_time_scaleUtcFormat);
  };
  d3.text = d3_xhrType(function(request) {
    return request.responseText;
  });
  d3.json = function(url, callback) {
    return d3_xhr(url, "application/json", d3_json, callback);
  };
  function d3_json(request) {
    return JSON.parse(request.responseText);
  }
  d3.html = function(url, callback) {
    return d3_xhr(url, "text/html", d3_html, callback);
  };
  function d3_html(request) {
    var range = d3_document.createRange();
    range.selectNode(d3_document.body);
    return range.createContextualFragment(request.responseText);
  }
  d3.xml = d3_xhrType(function(request) {
    return request.responseXML;
  });
  if (typeof define === "function" && define.amd) this.d3 = d3, define(d3); else if (typeof module === "object" && module.exports) module.exports = d3; else this.d3 = d3;
}();
},{}],152:[function(_dereq_,module,exports){
module.exports = function () {
    for (var i = 0; i < arguments.length; i++) {
        if (arguments[i] !== undefined) return arguments[i];
    }
};

},{}],153:[function(_dereq_,module,exports){
"use strict"

var ch = _dereq_("incremental-convex-hull")
var uniq = _dereq_("uniq")

module.exports = triangulate

function LiftedPoint(p, i) {
  this.point = p
  this.index = i
}

function compareLifted(a, b) {
  var ap = a.point
  var bp = b.point
  var d = ap.length
  for(var i=0; i<d; ++i) {
    var s = bp[i] - ap[i]
    if(s) {
      return s
    }
  }
  return 0
}

function triangulate1D(n, points, includePointAtInfinity) {
  if(n === 1) {
    if(includePointAtInfinity) {
      return [ [-1, 0] ]
    } else {
      return []
    }
  }
  var lifted = points.map(function(p, i) {
    return [ p[0], i ]
  })
  lifted.sort(function(a,b) {
    return a[0] - b[0]
  })
  var cells = new Array(n - 1)
  for(var i=1; i<n; ++i) {
    var a = lifted[i-1]
    var b = lifted[i]
    cells[i-1] = [ a[1], b[1] ]
  }
  if(includePointAtInfinity) {
    cells.push(
      [ -1, cells[0][1], ],
      [ cells[n-1][1], -1 ])
  }
  return cells
}

function triangulate(points, includePointAtInfinity) {
  var n = points.length
  if(n === 0) {
    return []
  }
  
  var d = points[0].length
  if(d < 1) {
    return []
  }

  //Special case:  For 1D we can just sort the points
  if(d === 1) {
    return triangulate1D(n, points, includePointAtInfinity)
  }
  
  //Lift points, sort
  var lifted = new Array(n)
  var upper = 1.0
  for(var i=0; i<n; ++i) {
    var p = points[i]
    var x = new Array(d+1)
    var l = 0.0
    for(var j=0; j<d; ++j) {
      var v = p[j]
      x[j] = v
      l += v * v
    }
    x[d] = l
    lifted[i] = new LiftedPoint(x, i)
    upper = Math.max(l, upper)
  }
  uniq(lifted, compareLifted)
  
  //Double points
  n = lifted.length

  //Create new list of points
  var dpoints = new Array(n + d + 1)
  var dindex = new Array(n + d + 1)

  //Add steiner points at top
  var u = (d+1) * (d+1) * upper
  var y = new Array(d+1)
  for(var i=0; i<=d; ++i) {
    y[i] = 0.0
  }
  y[d] = u

  dpoints[0] = y.slice()
  dindex[0] = -1

  for(var i=0; i<=d; ++i) {
    var x = y.slice()
    x[i] = 1
    dpoints[i+1] = x
    dindex[i+1] = -1
  }

  //Copy rest of the points over
  for(var i=0; i<n; ++i) {
    var h = lifted[i]
    dpoints[i + d + 1] = h.point
    dindex[i + d + 1] =  h.index
  }

  //Construct convex hull
  var hull = ch(dpoints, false)
  if(includePointAtInfinity) {
    hull = hull.filter(function(cell) {
      var count = 0
      for(var j=0; j<=d; ++j) {
        var v = dindex[cell[j]]
        if(v < 0) {
          if(++count >= 2) {
            return false
          }
        }
        cell[j] = v
      }
      return true
    })
  } else {
    hull = hull.filter(function(cell) {
      for(var i=0; i<=d; ++i) {
        var v = dindex[cell[i]]
        if(v < 0) {
          return false
        }
        cell[i] = v
      }
      return true
    })
  }

  if(d & 1) {
    for(var i=0; i<hull.length; ++i) {
      var h = hull[i]
      var x = h[0]
      h[0] = h[1]
      h[1] = x
    }
  }

  return hull
}
},{"incremental-convex-hull":402,"uniq":528}],154:[function(_dereq_,module,exports){
'use strict'


module.exports = kerning


var canvas = kerning.canvas = document.createElement('canvas')
var ctx = canvas.getContext('2d')
var asciiPairs = createPairs([32, 126])

kerning.createPairs = createPairs
kerning.ascii = asciiPairs


function kerning (family, o) {
	if (Array.isArray(family)) family = family.join(', ')

	var table = {}, pairs, fs = 16, threshold = .05

	if (o) {
		if (o.length === 2 && typeof o[0] === 'number') {
			pairs = createPairs(o)
		}
		else if (Array.isArray(o)) {
			pairs = o
		}
		else {
			if (o.o) pairs = createPairs(o.o)
			else if (o.pairs) pairs = o.pairs

			if (o.fontSize) fs = o.fontSize
			if (o.threshold != null) threshold = o.threshold
		}
	}

	if (!pairs) pairs = asciiPairs

	ctx.font = fs + 'px ' + family

	for (var i = 0; i < pairs.length; i++) {
		var pair = pairs[i]
		var width = ctx.measureText(pair[0]).width + ctx.measureText(pair[1]).width
		var kerningWidth = ctx.measureText(pair).width
		if (Math.abs(width - kerningWidth) > fs * threshold) {
			var emWidth = (kerningWidth - width) / fs
			table[pair] = emWidth * 1000
		}
	}

	return table
}


function createPairs (range) {
	var pairs = []

    for (var i = range[0]; i <= range[1]; i++) {
		var leftChar = String.fromCharCode(i)
		for (var j = range[0]; j < range[1]; j++) {
			var rightChar = String.fromCharCode(j)
			var pair = leftChar + rightChar

			pairs.push(pair)
		}
	}

	return pairs
}

},{}],155:[function(_dereq_,module,exports){
(function (Buffer){
var hasTypedArrays = false
if(typeof Float64Array !== "undefined") {
  var DOUBLE_VIEW = new Float64Array(1)
    , UINT_VIEW   = new Uint32Array(DOUBLE_VIEW.buffer)
  DOUBLE_VIEW[0] = 1.0
  hasTypedArrays = true
  if(UINT_VIEW[1] === 0x3ff00000) {
    //Use little endian
    module.exports = function doubleBitsLE(n) {
      DOUBLE_VIEW[0] = n
      return [ UINT_VIEW[0], UINT_VIEW[1] ]
    }
    function toDoubleLE(lo, hi) {
      UINT_VIEW[0] = lo
      UINT_VIEW[1] = hi
      return DOUBLE_VIEW[0]
    }
    module.exports.pack = toDoubleLE
    function lowUintLE(n) {
      DOUBLE_VIEW[0] = n
      return UINT_VIEW[0]
    }
    module.exports.lo = lowUintLE
    function highUintLE(n) {
      DOUBLE_VIEW[0] = n
      return UINT_VIEW[1]
    }
    module.exports.hi = highUintLE
  } else if(UINT_VIEW[0] === 0x3ff00000) {
    //Use big endian
    module.exports = function doubleBitsBE(n) {
      DOUBLE_VIEW[0] = n
      return [ UINT_VIEW[1], UINT_VIEW[0] ]
    }
    function toDoubleBE(lo, hi) {
      UINT_VIEW[1] = lo
      UINT_VIEW[0] = hi
      return DOUBLE_VIEW[0]
    }
    module.exports.pack = toDoubleBE
    function lowUintBE(n) {
      DOUBLE_VIEW[0] = n
      return UINT_VIEW[1]
    }
    module.exports.lo = lowUintBE
    function highUintBE(n) {
      DOUBLE_VIEW[0] = n
      return UINT_VIEW[0]
    }
    module.exports.hi = highUintBE
  } else {
    hasTypedArrays = false
  }
}
if(!hasTypedArrays) {
  var buffer = new Buffer(8)
  module.exports = function doubleBits(n) {
    buffer.writeDoubleLE(n, 0, true)
    return [ buffer.readUInt32LE(0, true), buffer.readUInt32LE(4, true) ]
  }
  function toDouble(lo, hi) {
    buffer.writeUInt32LE(lo, 0, true)
    buffer.writeUInt32LE(hi, 4, true)
    return buffer.readDoubleLE(0, true)
  }
  module.exports.pack = toDouble  
  function lowUint(n) {
    buffer.writeDoubleLE(n, 0, true)
    return buffer.readUInt32LE(0, true)
  }
  module.exports.lo = lowUint
  function highUint(n) {
    buffer.writeDoubleLE(n, 0, true)
    return buffer.readUInt32LE(4, true)
  }
  module.exports.hi = highUint
}

module.exports.sign = function(n) {
  return module.exports.hi(n) >>> 31
}

module.exports.exponent = function(n) {
  var b = module.exports.hi(n)
  return ((b<<1) >>> 21) - 1023
}

module.exports.fraction = function(n) {
  var lo = module.exports.lo(n)
  var hi = module.exports.hi(n)
  var b = hi & ((1<<20) - 1)
  if(hi & 0x7ff00000) {
    b += (1<<20)
  }
  return [lo, b]
}

module.exports.denormalized = function(n) {
  var hi = module.exports.hi(n)
  return !(hi & 0x7ff00000)
}
}).call(this,_dereq_("buffer").Buffer)
},{"buffer":93}],156:[function(_dereq_,module,exports){
var abs = _dereq_('abs-svg-path')
var normalize = _dereq_('normalize-svg-path')

var methods = {
  'M': 'moveTo',
  'C': 'bezierCurveTo'
}

module.exports = function(context, segments) {
  context.beginPath()

  // Make path easy to reproduce.
  normalize(abs(segments)).forEach(
    function(segment) {
      var command = segment[0]
      var args = segment.slice(1)

      // Convert the path command to a context method.
      context[methods[command]].apply(context, args)
    }
  )

  context.closePath()
}

},{"abs-svg-path":48,"normalize-svg-path":441}],157:[function(_dereq_,module,exports){
module.exports = function(dtype) {
  switch (dtype) {
    case 'int8':
      return Int8Array
    case 'int16':
      return Int16Array
    case 'int32':
      return Int32Array
    case 'uint8':
      return Uint8Array
    case 'uint16':
      return Uint16Array
    case 'uint32':
      return Uint32Array
    case 'float32':
      return Float32Array
    case 'float64':
      return Float64Array
    case 'array':
      return Array
    case 'uint8_clamped':
      return Uint8ClampedArray
  }
}

},{}],158:[function(_dereq_,module,exports){
"use strict"

function dupe_array(count, value, i) {
  var c = count[i]|0
  if(c <= 0) {
    return []
  }
  var result = new Array(c), j
  if(i === count.length-1) {
    for(j=0; j<c; ++j) {
      result[j] = value
    }
  } else {
    for(j=0; j<c; ++j) {
      result[j] = dupe_array(count, value, i+1)
    }
  }
  return result
}

function dupe_number(count, value) {
  var result, i
  result = new Array(count)
  for(i=0; i<count; ++i) {
    result[i] = value
  }
  return result
}

function dupe(count, value) {
  if(typeof value === "undefined") {
    value = 0
  }
  switch(typeof count) {
    case "number":
      if(count > 0) {
        return dupe_number(count|0, value)
      }
    break
    case "object":
      if(typeof (count.length) === "number") {
        return dupe_array(count, value, 0)
      }
    break
  }
  return []
}

module.exports = dupe
},{}],159:[function(_dereq_,module,exports){
'use strict';

module.exports = earcut;
module.exports.default = earcut;

function earcut(data, holeIndices, dim) {

    dim = dim || 2;

    var hasHoles = holeIndices && holeIndices.length,
        outerLen = hasHoles ? holeIndices[0] * dim : data.length,
        outerNode = linkedList(data, 0, outerLen, dim, true),
        triangles = [];

    if (!outerNode) return triangles;

    var minX, minY, maxX, maxY, x, y, invSize;

    if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);

    // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
    if (data.length > 80 * dim) {
        minX = maxX = data[0];
        minY = maxY = data[1];

        for (var i = dim; i < outerLen; i += dim) {
            x = data[i];
            y = data[i + 1];
            if (x < minX) minX = x;
            if (y < minY) minY = y;
            if (x > maxX) maxX = x;
            if (y > maxY) maxY = y;
        }

        // minX, minY and invSize are later used to transform coords into integers for z-order calculation
        invSize = Math.max(maxX - minX, maxY - minY);
        invSize = invSize !== 0 ? 1 / invSize : 0;
    }

    earcutLinked(outerNode, triangles, dim, minX, minY, invSize);

    return triangles;
}

// create a circular doubly linked list from polygon points in the specified winding order
function linkedList(data, start, end, dim, clockwise) {
    var i, last;

    if (clockwise === (signedArea(data, start, end, dim) > 0)) {
        for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
    } else {
        for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
    }

    if (last && equals(last, last.next)) {
        removeNode(last);
        last = last.next;
    }

    return last;
}

// eliminate colinear or duplicate points
function filterPoints(start, end) {
    if (!start) return start;
    if (!end) end = start;

    var p = start,
        again;
    do {
        again = false;

        if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
            removeNode(p);
            p = end = p.prev;
            if (p === p.next) break;
            again = true;

        } else {
            p = p.next;
        }
    } while (again || p !== end);

    return end;
}

// main ear slicing loop which triangulates a polygon (given as a linked list)
function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
    if (!ear) return;

    // interlink polygon nodes in z-order
    if (!pass && invSize) indexCurve(ear, minX, minY, invSize);

    var stop = ear,
        prev, next;

    // iterate through ears, slicing them one by one
    while (ear.prev !== ear.next) {
        prev = ear.prev;
        next = ear.next;

        if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
            // cut off the triangle
            triangles.push(prev.i / dim);
            triangles.push(ear.i / dim);
            triangles.push(next.i / dim);

            removeNode(ear);

            // skipping the next vertice leads to less sliver triangles
            ear = next.next;
            stop = next.next;

            continue;
        }

        ear = next;

        // if we looped through the whole remaining polygon and can't find any more ears
        if (ear === stop) {
            // try filtering points and slicing again
            if (!pass) {
                earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);

            // if this didn't work, try curing all small self-intersections locally
            } else if (pass === 1) {
                ear = cureLocalIntersections(ear, triangles, dim);
                earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);

            // as a last resort, try splitting the remaining polygon into two
            } else if (pass === 2) {
                splitEarcut(ear, triangles, dim, minX, minY, invSize);
            }

            break;
        }
    }
}

// check whether a polygon node forms a valid ear with adjacent nodes
function isEar(ear) {
    var a = ear.prev,
        b = ear,
        c = ear.next;

    if (area(a, b, c) >= 0) return false; // reflex, can't be an ear

    // now make sure we don't have other points inside the potential ear
    var p = ear.next.next;

    while (p !== ear.prev) {
        if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
            area(p.prev, p, p.next) >= 0) return false;
        p = p.next;
    }

    return true;
}

function isEarHashed(ear, minX, minY, invSize) {
    var a = ear.prev,
        b = ear,
        c = ear.next;

    if (area(a, b, c) >= 0) return false; // reflex, can't be an ear

    // triangle bbox; min & max are calculated like this for speed
    var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
        minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
        maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
        maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);

    // z-order range for the current triangle bbox;
    var minZ = zOrder(minTX, minTY, minX, minY, invSize),
        maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);

    var p = ear.prevZ,
        n = ear.nextZ;

    // look for points inside the triangle in both directions
    while (p && p.z >= minZ && n && n.z <= maxZ) {
        if (p !== ear.prev && p !== ear.next &&
            pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
            area(p.prev, p, p.next) >= 0) return false;
        p = p.prevZ;

        if (n !== ear.prev && n !== ear.next &&
            pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) &&
            area(n.prev, n, n.next) >= 0) return false;
        n = n.nextZ;
    }

    // look for remaining points in decreasing z-order
    while (p && p.z >= minZ) {
        if (p !== ear.prev && p !== ear.next &&
            pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
            area(p.prev, p, p.next) >= 0) return false;
        p = p.prevZ;
    }

    // look for remaining points in increasing z-order
    while (n && n.z <= maxZ) {
        if (n !== ear.prev && n !== ear.next &&
            pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) &&
            area(n.prev, n, n.next) >= 0) return false;
        n = n.nextZ;
    }

    return true;
}

// go through all polygon nodes and cure small local self-intersections
function cureLocalIntersections(start, triangles, dim) {
    var p = start;
    do {
        var a = p.prev,
            b = p.next.next;

        if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {

            triangles.push(a.i / dim);
            triangles.push(p.i / dim);
            triangles.push(b.i / dim);

            // remove two nodes involved
            removeNode(p);
            removeNode(p.next);

            p = start = b;
        }
        p = p.next;
    } while (p !== start);

    return p;
}

// try splitting polygon into two and triangulate them independently
function splitEarcut(start, triangles, dim, minX, minY, invSize) {
    // look for a valid diagonal that divides the polygon into two
    var a = start;
    do {
        var b = a.next.next;
        while (b !== a.prev) {
            if (a.i !== b.i && isValidDiagonal(a, b)) {
                // split the polygon in two by the diagonal
                var c = splitPolygon(a, b);

                // filter colinear points around the cuts
                a = filterPoints(a, a.next);
                c = filterPoints(c, c.next);

                // run earcut on each half
                earcutLinked(a, triangles, dim, minX, minY, invSize);
                earcutLinked(c, triangles, dim, minX, minY, invSize);
                return;
            }
            b = b.next;
        }
        a = a.next;
    } while (a !== start);
}

// link every hole into the outer loop, producing a single-ring polygon without holes
function eliminateHoles(data, holeIndices, outerNode, dim) {
    var queue = [],
        i, len, start, end, list;

    for (i = 0, len = holeIndices.length; i < len; i++) {
        start = holeIndices[i] * dim;
        end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
        list = linkedList(data, start, end, dim, false);
        if (list === list.next) list.steiner = true;
        queue.push(getLeftmost(list));
    }

    queue.sort(compareX);

    // process holes from left to right
    for (i = 0; i < queue.length; i++) {
        eliminateHole(queue[i], outerNode);
        outerNode = filterPoints(outerNode, outerNode.next);
    }

    return outerNode;
}

function compareX(a, b) {
    return a.x - b.x;
}

// find a bridge between vertices that connects hole with an outer ring and and link it
function eliminateHole(hole, outerNode) {
    outerNode = findHoleBridge(hole, outerNode);
    if (outerNode) {
        var b = splitPolygon(outerNode, hole);
        filterPoints(b, b.next);
    }
}

// David Eberly's algorithm for finding a bridge between hole and outer polygon
function findHoleBridge(hole, outerNode) {
    var p = outerNode,
        hx = hole.x,
        hy = hole.y,
        qx = -Infinity,
        m;

    // find a segment intersected by a ray from the hole's leftmost point to the left;
    // segment's endpoint with lesser x will be potential connection point
    do {
        if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
            var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
            if (x <= hx && x > qx) {
                qx = x;
                if (x === hx) {
                    if (hy === p.y) return p;
                    if (hy === p.next.y) return p.next;
                }
                m = p.x < p.next.x ? p : p.next;
            }
        }
        p = p.next;
    } while (p !== outerNode);

    if (!m) return null;

    if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint

    // look for points inside the triangle of hole point, segment intersection and endpoint;
    // if there are no points found, we have a valid connection;
    // otherwise choose the point of the minimum angle with the ray as connection point

    var stop = m,
        mx = m.x,
        my = m.y,
        tanMin = Infinity,
        tan;

    p = m.next;

    while (p !== stop) {
        if (hx >= p.x && p.x >= mx && hx !== p.x &&
                pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {

            tan = Math.abs(hy - p.y) / (hx - p.x); // tangential

            if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
                m = p;
                tanMin = tan;
            }
        }

        p = p.next;
    }

    return m;
}

// interlink polygon nodes in z-order
function indexCurve(start, minX, minY, invSize) {
    var p = start;
    do {
        if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
        p.prevZ = p.prev;
        p.nextZ = p.next;
        p = p.next;
    } while (p !== start);

    p.prevZ.nextZ = null;
    p.prevZ = null;

    sortLinked(p);
}

// Simon Tatham's linked list merge sort algorithm
// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
function sortLinked(list) {
    var i, p, q, e, tail, numMerges, pSize, qSize,
        inSize = 1;

    do {
        p = list;
        list = null;
        tail = null;
        numMerges = 0;

        while (p) {
            numMerges++;
            q = p;
            pSize = 0;
            for (i = 0; i < inSize; i++) {
                pSize++;
                q = q.nextZ;
                if (!q) break;
            }
            qSize = inSize;

            while (pSize > 0 || (qSize > 0 && q)) {

                if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
                    e = p;
                    p = p.nextZ;
                    pSize--;
                } else {
                    e = q;
                    q = q.nextZ;
                    qSize--;
                }

                if (tail) tail.nextZ = e;
                else list = e;

                e.prevZ = tail;
                tail = e;
            }

            p = q;
        }

        tail.nextZ = null;
        inSize *= 2;

    } while (numMerges > 1);

    return list;
}

// z-order of a point given coords and inverse of the longer side of data bbox
function zOrder(x, y, minX, minY, invSize) {
    // coords are transformed into non-negative 15-bit integer range
    x = 32767 * (x - minX) * invSize;
    y = 32767 * (y - minY) * invSize;

    x = (x | (x << 8)) & 0x00FF00FF;
    x = (x | (x << 4)) & 0x0F0F0F0F;
    x = (x | (x << 2)) & 0x33333333;
    x = (x | (x << 1)) & 0x55555555;

    y = (y | (y << 8)) & 0x00FF00FF;
    y = (y | (y << 4)) & 0x0F0F0F0F;
    y = (y | (y << 2)) & 0x33333333;
    y = (y | (y << 1)) & 0x55555555;

    return x | (y << 1);
}

// find the leftmost node of a polygon ring
function getLeftmost(start) {
    var p = start,
        leftmost = start;
    do {
        if (p.x < leftmost.x) leftmost = p;
        p = p.next;
    } while (p !== start);

    return leftmost;
}

// check if a point lies within a convex triangle
function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
    return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
           (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
           (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
}

// check if a diagonal between two polygon nodes is valid (lies in polygon interior)
function isValidDiagonal(a, b) {
    return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) &&
           locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
}

// signed area of a triangle
function area(p, q, r) {
    return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
}

// check if two points are equal
function equals(p1, p2) {
    return p1.x === p2.x && p1.y === p2.y;
}

// check if two segments intersect
function intersects(p1, q1, p2, q2) {
    if ((equals(p1, q1) && equals(p2, q2)) ||
        (equals(p1, q2) && equals(p2, q1))) return true;
    return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
           area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
}

// check if a polygon diagonal intersects any polygon segments
function intersectsPolygon(a, b) {
    var p = a;
    do {
        if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
                intersects(p, p.next, a, b)) return true;
        p = p.next;
    } while (p !== a);

    return false;
}

// check if a polygon diagonal is locally inside the polygon
function locallyInside(a, b) {
    return area(a.prev, a, a.next) < 0 ?
        area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
        area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
}

// check if the middle point of a polygon diagonal is inside the polygon
function middleInside(a, b) {
    var p = a,
        inside = false,
        px = (a.x + b.x) / 2,
        py = (a.y + b.y) / 2;
    do {
        if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
                (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
            inside = !inside;
        p = p.next;
    } while (p !== a);

    return inside;
}

// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
// if one belongs to the outer ring and another to a hole, it merges it into a single ring
function splitPolygon(a, b) {
    var a2 = new Node(a.i, a.x, a.y),
        b2 = new Node(b.i, b.x, b.y),
        an = a.next,
        bp = b.prev;

    a.next = b;
    b.prev = a;

    a2.next = an;
    an.prev = a2;

    b2.next = a2;
    a2.prev = b2;

    bp.next = b2;
    b2.prev = bp;

    return b2;
}

// create a node and optionally link it with previous one (in a circular doubly linked list)
function insertNode(i, x, y, last) {
    var p = new Node(i, x, y);

    if (!last) {
        p.prev = p;
        p.next = p;

    } else {
        p.next = last.next;
        p.prev = last;
        last.next.prev = p;
        last.next = p;
    }
    return p;
}

function removeNode(p) {
    p.next.prev = p.prev;
    p.prev.next = p.next;

    if (p.prevZ) p.prevZ.nextZ = p.nextZ;
    if (p.nextZ) p.nextZ.prevZ = p.prevZ;
}

function Node(i, x, y) {
    // vertice index in coordinates array
    this.i = i;

    // vertex coordinates
    this.x = x;
    this.y = y;

    // previous and next vertice nodes in a polygon ring
    this.prev = null;
    this.next = null;

    // z-order curve value
    this.z = null;

    // previous and next nodes in z-order
    this.prevZ = null;
    this.nextZ = null;

    // indicates whether this is a steiner point
    this.steiner = false;
}

// return a percentage difference between the polygon area and its triangulation area;
// used to verify correctness of triangulation
earcut.deviation = function (data, holeIndices, dim, triangles) {
    var hasHoles = holeIndices && holeIndices.length;
    var outerLen = hasHoles ? holeIndices[0] * dim : data.length;

    var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
    if (hasHoles) {
        for (var i = 0, len = holeIndices.length; i < len; i++) {
            var start = holeIndices[i] * dim;
            var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
            polygonArea -= Math.abs(signedArea(data, start, end, dim));
        }
    }

    var trianglesArea = 0;
    for (i = 0; i < triangles.length; i += 3) {
        var a = triangles[i] * dim;
        var b = triangles[i + 1] * dim;
        var c = triangles[i + 2] * dim;
        trianglesArea += Math.abs(
            (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
            (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
    }

    return polygonArea === 0 && trianglesArea === 0 ? 0 :
        Math.abs((trianglesArea - polygonArea) / polygonArea);
};

function signedArea(data, start, end, dim) {
    var sum = 0;
    for (var i = start, j = end - dim; i < end; i += dim) {
        sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
        j = i;
    }
    return sum;
}

// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
earcut.flatten = function (data) {
    var dim = data[0][0].length,
        result = {vertices: [], holes: [], dimensions: dim},
        holeIndex = 0;

    for (var i = 0; i < data.length; i++) {
        for (var j = 0; j < data[i].length; j++) {
            for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
        }
        if (i > 0) {
            holeIndex += data[i - 1].length;
            result.holes.push(holeIndex);
        }
    }
    return result;
};

},{}],160:[function(_dereq_,module,exports){
"use strict"

module.exports = edgeToAdjacency

var uniq = _dereq_("uniq")

function edgeToAdjacency(edges, numVertices) {
  var numEdges = edges.length
  if(typeof numVertices !== "number") {
    numVertices = 0
    for(var i=0; i<numEdges; ++i) {
      var e = edges[i]
      numVertices = Math.max(numVertices, e[0], e[1])
    }
    numVertices = (numVertices|0) + 1
  }
  numVertices = numVertices|0
  var adj = new Array(numVertices)
  for(var i=0; i<numVertices; ++i) {
    adj[i] = []
  }
  for(var i=0; i<numEdges; ++i) {
    var e = edges[i]
    adj[e[0]].push(e[1])
    adj[e[1]].push(e[0])
  }
  for(var j=0; j<numVertices; ++j) {
    uniq(adj[j], function(a, b) {
      return a - b
    })
  }
  return adj
}
},{"uniq":528}],161:[function(_dereq_,module,exports){
var tarjan = _dereq_('strongly-connected-components');

module.exports = function findCircuits(edges) {
    var circuits = []; // Output

    var stack = [];
    var blocked = [];
    var B = {};
    var Ak = [];
    var s;

    function unblock(u) {
        blocked[u] = false;
        if(B.hasOwnProperty(u)) {
            Object.keys(B[u]).forEach(function(w) {
                delete B[u][w];
                if(blocked[w]) {unblock(w);}
            });
        }
    }

    function circuit(v) {
        var found = false;

        stack.push(v);
        blocked[v] = true;

        // L1
        var i;
        var w;
        for(i = 0; i < Ak[v].length; i++) {
            w = Ak[v][i];
            if(w === s) {
                output(s, stack);
                found = true;
            } else if(!blocked[w]) {
                found = circuit(w);
            }
        }

        // L2
        if(found) {
            unblock(v);
        } else {
            for(i = 0; i < Ak[v].length; i++) {
                w = Ak[v][i];
                var entry = B[w];

                if(!entry) {
                    entry = {};
                    B[w] = entry;
                }

                entry[w] = true;
            }
        }
        stack.pop();
        return found;
    }

    function output(start, stack) {
        var cycle = [].concat(stack).concat(start);
        circuits.push(cycle);
    }

    function subgraph(minId) {
      // Remove edges with indice smaller than minId
        for(var i = 0; i < edges.length; i++) {
            if(i < minId) edges[i] = [];
            edges[i] = edges[i].filter(function(i) {
                return i >= minId;
            });
        }
    }

    function adjacencyStructureSCC(from) {
      // Make subgraph starting from vertex minId
        subgraph(from);
        var g = edges;

      // Find strongly connected components using Tarjan algorithm
        var sccs = tarjan(g);

      // Filter out trivial connected components (ie. made of one node)
        var ccs = sccs.components.filter(function(scc) {
            return scc.length > 1;
        });

      // Find least vertex
        var leastVertex = Infinity;
        var leastVertexComponent;
        for(var i = 0; i < ccs.length; i++) {
            for(var j = 0; j < ccs[i].length; j++) {
                if(ccs[i][j] < leastVertex) {
                    leastVertex = ccs[i][j];
                    leastVertexComponent = i;
                }
            }
        }

        var cc = ccs[leastVertexComponent];

        if(!cc) return false;

      // Return the adjacency list of first component
        var adjList = edges.map(function(l, index) {
            if(cc.indexOf(index) === -1) return [];
            return l.filter(function(i) {
                return cc.indexOf(i) !== -1;
            });
        });

        return {
            leastVertex: leastVertex,
            adjList: adjList
        };
    }

    s = 0;
    var n = edges.length;
    while(s < n) {
        // find strong component with least vertex in
        // subgraph starting from vertex `s`
        var p = adjacencyStructureSCC(s);

        // Its least vertex
        s = p.leastVertex;
        // Its adjacency list
        Ak = p.adjList;

        if(Ak) {
            for(var i = 0; i < Ak.length; i++) {
                for(var j = 0; j < Ak[i].length; j++) {
                    var vertexId = Ak[i][j];
                    blocked[+vertexId] = false;
                    B[vertexId] = {};
                }
            }
            circuit(s);
            s = s + 1;
        } else {
            s = n;
        }

    }

    return circuits;
};

},{"strongly-connected-components":511}],162:[function(_dereq_,module,exports){
// Inspired by Google Closure:
// http://closure-library.googlecode.com/svn/docs/
// closure_goog_array_array.js.html#goog.array.clear

"use strict";

var value = _dereq_("../../object/valid-value");

module.exports = function () {
	value(this).length = 0;
	return this;
};

},{"../../object/valid-value":194}],163:[function(_dereq_,module,exports){
"use strict";

module.exports = _dereq_("./is-implemented")()
	? Array.from
	: _dereq_("./shim");

},{"./is-implemented":164,"./shim":165}],164:[function(_dereq_,module,exports){
"use strict";

module.exports = function () {
	var from = Array.from, arr, result;
	if (typeof from !== "function") return false;
	arr = ["raz", "dwa"];
	result = from(arr);
	return Boolean(result && (result !== arr) && (result[1] === "dwa"));
};

},{}],165:[function(_dereq_,module,exports){
"use strict";

var iteratorSymbol = _dereq_("es6-symbol").iterator
  , isArguments    = _dereq_("../../function/is-arguments")
  , isFunction     = _dereq_("../../function/is-function")
  , toPosInt       = _dereq_("../../number/to-pos-integer")
  , callable       = _dereq_("../../object/valid-callable")
  , validValue     = _dereq_("../../object/valid-value")
  , isValue        = _dereq_("../../object/is-value")
  , isString       = _dereq_("../../string/is-string")
  , isArray        = Array.isArray
  , call           = Function.prototype.call
  , desc           = { configurable: true, enumerable: true, writable: true, value: null }
  , defineProperty = Object.defineProperty;

// eslint-disable-next-line complexity
module.exports = function (arrayLike /*, mapFn, thisArg*/) {
	var mapFn = arguments[1]
	  , thisArg = arguments[2]
	  , Context
	  , i
	  , j
	  , arr
	  , length
	  , code
	  , iterator
	  , result
	  , getIterator
	  , value;

	arrayLike = Object(validValue(arrayLike));

	if (isValue(mapFn)) callable(mapFn);
	if (!this || this === Array || !isFunction(this)) {
		// Result: Plain array
		if (!mapFn) {
			if (isArguments(arrayLike)) {
				// Source: Arguments
				length = arrayLike.length;
				if (length !== 1) return Array.apply(null, arrayLike);
				arr = new Array(1);
				arr[0] = arrayLike[0];
				return arr;
			}
			if (isArray(arrayLike)) {
				// Source: Array
				arr = new Array(length = arrayLike.length);
				for (i = 0; i < length; ++i) arr[i] = arrayLike[i];
				return arr;
			}
		}
		arr = [];
	} else {
		// Result: Non plain array
		Context = this;
	}

	if (!isArray(arrayLike)) {
		if ((getIterator = arrayLike[iteratorSymbol]) !== undefined) {
			// Source: Iterator
			iterator = callable(getIterator).call(arrayLike);
			if (Context) arr = new Context();
			result = iterator.next();
			i = 0;
			while (!result.done) {
				value = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value;
				if (Context) {
					desc.value = value;
					defineProperty(arr, i, desc);
				} else {
					arr[i] = value;
				}
				result = iterator.next();
				++i;
			}
			length = i;
		} else if (isString(arrayLike)) {
			// Source: String
			length = arrayLike.length;
			if (Context) arr = new Context();
			for (i = 0, j = 0; i < length; ++i) {
				value = arrayLike[i];
				if (i + 1 < length) {
					code = value.charCodeAt(0);
					// eslint-disable-next-line max-depth
					if (code >= 0xd800 && code <= 0xdbff) value += arrayLike[++i];
				}
				value = mapFn ? call.call(mapFn, thisArg, value, j) : value;
				if (Context) {
					desc.value = value;
					defineProperty(arr, j, desc);
				} else {
					arr[j] = value;
				}
				++j;
			}
			length = j;
		}
	}
	if (length === undefined) {
		// Source: array or array-like
		length = toPosInt(arrayLike.length);
		if (Context) arr = new Context(length);
		for (i = 0; i < length; ++i) {
			value = mapFn ? call.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[i];
			if (Context) {
				desc.value = value;
				defineProperty(arr, i, desc);
			} else {
				arr[i] = value;
			}
		}
	}
	if (Context) {
		desc.value = null;
		arr.length = length;
	}
	return arr;
};

},{"../../function/is-arguments":166,"../../function/is-function":167,"../../number/to-pos-integer":173,"../../object/is-value":183,"../../object/valid-callable":192,"../../object/valid-value":194,"../../string/is-string":198,"es6-symbol":208}],166:[function(_dereq_,module,exports){
"use strict";

var objToString = Object.prototype.toString
  , id = objToString.call(
	(function () {
		return arguments;
	})()
);

module.exports = function (value) {
	return objToString.call(value) === id;
};

},{}],167:[function(_dereq_,module,exports){
"use strict";

var objToString = Object.prototype.toString, id = objToString.call(_dereq_("./noop"));

module.exports = function (value) {
	return typeof value === "function" && objToString.call(value) === id;
};

},{"./noop":168}],168:[function(_dereq_,module,exports){
"use strict";

// eslint-disable-next-line no-empty-function
module.exports = function () {};

},{}],169:[function(_dereq_,module,exports){
"use strict";

module.exports = _dereq_("./is-implemented")()
	? Math.sign
	: _dereq_("./shim");

},{"./is-implemented":170,"./shim":171}],170:[function(_dereq_,module,exports){
"use strict";

module.exports = function () {
	var sign = Math.sign;
	if (typeof sign !== "function") return false;
	return (sign(10) === 1) && (sign(-20) === -1);
};

},{}],171:[function(_dereq_,module,exports){
"use strict";

module.exports = function (value) {
	value = Number(value);
	if (isNaN(value) || (value === 0)) return value;
	return value > 0 ? 1 : -1;
};

},{}],172:[function(_dereq_,module,exports){
"use strict";

var sign = _dereq_("../math/sign")

  , abs = Math.abs, floor = Math.floor;

module.exports = function (value) {
	if (isNaN(value)) return 0;
	value = Number(value);
	if ((value === 0) || !isFinite(value)) return value;
	return sign(value) * floor(abs(value));
};

},{"../math/sign":169}],173:[function(_dereq_,module,exports){
"use strict";

var toInteger = _dereq_("./to-integer")

  , max = Math.max;

module.exports = function (value) {
 return max(0, toInteger(value));
};

},{"./to-integer":172}],174:[function(_dereq_,module,exports){
// Internal method, used by iteration functions.
// Calls a function for each key-value pair found in object
// Optionally takes compareFn to iterate object in specific order

"use strict";

var callable                = _dereq_("./valid-callable")
  , value                   = _dereq_("./valid-value")
  , bind                    = Function.prototype.bind
  , call                    = Function.prototype.call
  , keys                    = Object.keys
  , objPropertyIsEnumerable = Object.prototype.propertyIsEnumerable;

module.exports = function (method, defVal) {
	return function (obj, cb /*, thisArg, compareFn*/) {
		var list, thisArg = arguments[2], compareFn = arguments[3];
		obj = Object(value(obj));
		callable(cb);

		list = keys(obj);
		if (compareFn) {
			list.sort(typeof compareFn === "function" ? bind.call(compareFn, obj) : undefined);
		}
		if (typeof method !== "function") method = list[method];
		return call.call(method, list, function (key, index) {
			if (!objPropertyIsEnumerable.call(obj, key)) return defVal;
			return call.call(cb, thisArg, obj[key], key, obj, index);
		});
	};
};

},{"./valid-callable":192,"./valid-value":194}],175:[function(_dereq_,module,exports){
"use strict";

module.exports = _dereq_("./is-implemented")()
	? Object.assign
	: _dereq_("./shim");

},{"./is-implemented":176,"./shim":177}],176:[function(_dereq_,module,exports){
"use strict";

module.exports = function () {
	var assign = Object.assign, obj;
	if (typeof assign !== "function") return false;
	obj = { foo: "raz" };
	assign(obj, { bar: "dwa" }, { trzy: "trzy" });
	return (obj.foo + obj.bar + obj.trzy) === "razdwatrzy";
};

},{}],177:[function(_dereq_,module,exports){
"use strict";

var keys  = _dereq_("../keys")
  , value = _dereq_("../valid-value")
  , max   = Math.max;

module.exports = function (dest, src /*, …srcn*/) {
	var error, i, length = max(arguments.length, 2), assign;
	dest = Object(value(dest));
	assign = function (key) {
		try {
			dest[key] = src[key];
		} catch (e) {
			if (!error) error = e;
		}
	};
	for (i = 1; i < length; ++i) {
		src = arguments[i];
		keys(src).forEach(assign);
	}
	if (error !== undefined) throw error;
	return dest;
};

},{"../keys":184,"../valid-value":194}],178:[function(_dereq_,module,exports){
"use strict";

var aFrom  = _dereq_("../array/from")
  , assign = _dereq_("./assign")
  , value  = _dereq_("./valid-value");

module.exports = function (obj/*, propertyNames, options*/) {
	var copy = Object(value(obj)), propertyNames = arguments[1], options = Object(arguments[2]);
	if (copy !== obj && !propertyNames) return copy;
	var result = {};
	if (propertyNames) {
		aFrom(propertyNames, function (propertyName) {
			if (options.ensure || propertyName in obj) result[propertyName] = obj[propertyName];
		});
	} else {
		assign(result, obj);
	}
	return result;
};

},{"../array/from":163,"./assign":175,"./valid-value":194}],179:[function(_dereq_,module,exports){
// Workaround for http://code.google.com/p/v8/issues/detail?id=2804

"use strict";

var create = Object.create, shim;

if (!_dereq_("./set-prototype-of/is-implemented")()) {
	shim = _dereq_("./set-prototype-of/shim");
}

module.exports = (function () {
	var nullObject, polyProps, desc;
	if (!shim) return create;
	if (shim.level !== 1) return create;

	nullObject = {};
	polyProps = {};
	desc = {
		configurable: false,
		enumerable: false,
		writable: true,
		value: undefined
	};
	Object.getOwnPropertyNames(Object.prototype).forEach(function (name) {
		if (name === "__proto__") {
			polyProps[name] = {
				configurable: true,
				enumerable: false,
				writable: true,
				value: undefined
			};
			return;
		}
		polyProps[name] = desc;
	});
	Object.defineProperties(nullObject, polyProps);

	Object.defineProperty(shim, "nullPolyfill", {
		configurable: false,
		enumerable: false,
		writable: false,
		value: nullObject
	});

	return function (prototype, props) {
		return create(prototype === null ? nullObject : prototype, props);
	};
}());

},{"./set-prototype-of/is-implemented":190,"./set-prototype-of/shim":191}],180:[function(_dereq_,module,exports){
"use strict";

module.exports = _dereq_("./_iterate")("forEach");

},{"./_iterate":174}],181:[function(_dereq_,module,exports){
// Deprecated

"use strict";

module.exports = function (obj) {
 return typeof obj === "function";
};

},{}],182:[function(_dereq_,module,exports){
"use strict";

var isValue = _dereq_("./is-value");

var map = { function: true, object: true };

module.exports = function (value) {
	return (isValue(value) && map[typeof value]) || false;
};

},{"./is-value":183}],183:[function(_dereq_,module,exports){
"use strict";

var _undefined = _dereq_("../function/noop")(); // Support ES3 engines

module.exports = function (val) {
 return (val !== _undefined) && (val !== null);
};

},{"../function/noop":168}],184:[function(_dereq_,module,exports){
"use strict";

module.exports = _dereq_("./is-implemented")() ? Object.keys : _dereq_("./shim");

},{"./is-implemented":185,"./shim":186}],185:[function(_dereq_,module,exports){
"use strict";

module.exports = function () {
	try {
		Object.keys("primitive");
		return true;
	} catch (e) {
		return false;
	}
};

},{}],186:[function(_dereq_,module,exports){
"use strict";

var isValue = _dereq_("../is-value");

var keys = Object.keys;

module.exports = function (object) { return keys(isValue(object) ? Object(object) : object); };

},{"../is-value":183}],187:[function(_dereq_,module,exports){
"use strict";

var callable = _dereq_("./valid-callable")
  , forEach  = _dereq_("./for-each")
  , call     = Function.prototype.call;

module.exports = function (obj, cb /*, thisArg*/) {
	var result = {}, thisArg = arguments[2];
	callable(cb);
	forEach(obj, function (value, key, targetObj, index) {
		result[key] = call.call(cb, thisArg, value, key, targetObj, index);
	});
	return result;
};

},{"./for-each":180,"./valid-callable":192}],188:[function(_dereq_,module,exports){
"use strict";

var isValue = _dereq_("./is-value");

var forEach = Array.prototype.forEach, create = Object.create;

var process = function (src, obj) {
	var key;
	for (key in src) obj[key] = src[key];
};

// eslint-disable-next-line no-unused-vars
module.exports = function (opts1 /*, …options*/) {
	var result = create(null);
	forEach.call(arguments, function (options) {
		if (!isValue(options)) return;
		process(Object(options), result);
	});
	return result;
};

},{"./is-value":183}],189:[function(_dereq_,module,exports){
"use strict";

module.exports = _dereq_("./is-implemented")()
	? Object.setPrototypeOf
	: _dereq_("./shim");

},{"./is-implemented":190,"./shim":191}],190:[function(_dereq_,module,exports){
"use strict";

var create = Object.create, getPrototypeOf = Object.getPrototypeOf, plainObject = {};

module.exports = function (/* CustomCreate*/) {
	var setPrototypeOf = Object.setPrototypeOf, customCreate = arguments[0] || create;
	if (typeof setPrototypeOf !== "function") return false;
	return getPrototypeOf(setPrototypeOf(customCreate(null), plainObject)) === plainObject;
};

},{}],191:[function(_dereq_,module,exports){
/* eslint no-proto: "off" */

// Big thanks to @WebReflection for sorting this out
// https://gist.github.com/WebReflection/5593554

"use strict";

var isObject        = _dereq_("../is-object")
  , value           = _dereq_("../valid-value")
  , objIsPrototypeOf = Object.prototype.isPrototypeOf
  , defineProperty  = Object.defineProperty
  , nullDesc        = {
	configurable: true,
	enumerable: false,
	writable: true,
	value: undefined
}
  , validate;

validate = function (obj, prototype) {
	value(obj);
	if (prototype === null || isObject(prototype)) return obj;
	throw new TypeError("Prototype must be null or an object");
};

module.exports = (function (status) {
	var fn, set;
	if (!status) return null;
	if (status.level === 2) {
		if (status.set) {
			set = status.set;
			fn = function (obj, prototype) {
				set.call(validate(obj, prototype), prototype);
				return obj;
			};
		} else {
			fn = function (obj, prototype) {
				validate(obj, prototype).__proto__ = prototype;
				return obj;
			};
		}
	} else {
		fn = function self(obj, prototype) {
			var isNullBase;
			validate(obj, prototype);
			isNullBase = objIsPrototypeOf.call(self.nullPolyfill, obj);
			if (isNullBase) delete self.nullPolyfill.__proto__;
			if (prototype === null) prototype = self.nullPolyfill;
			obj.__proto__ = prototype;
			if (isNullBase) defineProperty(self.nullPolyfill, "__proto__", nullDesc);
			return obj;
		};
	}
	return Object.defineProperty(fn, "level", {
		configurable: false,
		enumerable: false,
		writable: false,
		value: status.level
	});
}(
	(function () {
		var tmpObj1 = Object.create(null)
		  , tmpObj2 = {}
		  , set
		  , desc = Object.getOwnPropertyDescriptor(Object.prototype, "__proto__");

		if (desc) {
			try {
				set = desc.set; // Opera crashes at this point
				set.call(tmpObj1, tmpObj2);
			} catch (ignore) {}
			if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { set: set, level: 2 };
		}

		tmpObj1.__proto__ = tmpObj2;
		if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 2 };

		tmpObj1 = {};
		tmpObj1.__proto__ = tmpObj2;
		if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 1 };

		return false;
	})()
));

_dereq_("../create");

},{"../create":179,"../is-object":182,"../valid-value":194}],192:[function(_dereq_,module,exports){
"use strict";

module.exports = function (fn) {
	if (typeof fn !== "function") throw new TypeError(fn + " is not a function");
	return fn;
};

},{}],193:[function(_dereq_,module,exports){
"use strict";

var isObject = _dereq_("./is-object");

module.exports = function (value) {
	if (!isObject(value)) throw new TypeError(value + " is not an Object");
	return value;
};

},{"./is-object":182}],194:[function(_dereq_,module,exports){
"use strict";

var isValue = _dereq_("./is-value");

module.exports = function (value) {
	if (!isValue(value)) throw new TypeError("Cannot use null or undefined");
	return value;
};

},{"./is-value":183}],195:[function(_dereq_,module,exports){
"use strict";

module.exports = _dereq_("./is-implemented")()
	? String.prototype.contains
	: _dereq_("./shim");

},{"./is-implemented":196,"./shim":197}],196:[function(_dereq_,module,exports){
"use strict";

var str = "razdwatrzy";

module.exports = function () {
	if (typeof str.contains !== "function") return false;
	return (str.contains("dwa") === true) && (str.contains("foo") === false);
};

},{}],197:[function(_dereq_,module,exports){
"use strict";

var indexOf = String.prototype.indexOf;

module.exports = function (searchString/*, position*/) {
	return indexOf.call(this, searchString, arguments[1]) > -1;
};

},{}],198:[function(_dereq_,module,exports){
"use strict";

var objToString = Object.prototype.toString, id = objToString.call("");

module.exports = function (value) {
	return (
		typeof value === "string" ||
		(value &&
			typeof value === "object" &&
			(value instanceof String || objToString.call(value) === id)) ||
		false
	);
};

},{}],199:[function(_dereq_,module,exports){
"use strict";

var generated = Object.create(null), random = Math.random;

module.exports = function () {
	var str;
	do {
		str = random()
			.toString(36)
			.slice(2);
	} while (generated[str]);
	return str;
};

},{}],200:[function(_dereq_,module,exports){
"use strict";

var setPrototypeOf = _dereq_("es5-ext/object/set-prototype-of")
  , contains       = _dereq_("es5-ext/string/#/contains")
  , d              = _dereq_("d")
  , Symbol         = _dereq_("es6-symbol")
  , Iterator       = _dereq_("./");

var defineProperty = Object.defineProperty, ArrayIterator;

ArrayIterator = module.exports = function (arr, kind) {
	if (!(this instanceof ArrayIterator)) throw new TypeError("Constructor requires 'new'");
	Iterator.call(this, arr);
	if (!kind) kind = "value";
	else if (contains.call(kind, "key+value")) kind = "key+value";
	else if (contains.call(kind, "key")) kind = "key";
	else kind = "value";
	defineProperty(this, "__kind__", d("", kind));
};
if (setPrototypeOf) setPrototypeOf(ArrayIterator, Iterator);

// Internal %ArrayIteratorPrototype% doesn't expose its constructor
delete ArrayIterator.prototype.constructor;

ArrayIterator.prototype = Object.create(Iterator.prototype, {
	_resolve: d(function (i) {
		if (this.__kind__ === "value") return this.__list__[i];
		if (this.__kind__ === "key+value") return [i, this.__list__[i]];
		return i;
	})
});
defineProperty(ArrayIterator.prototype, Symbol.toStringTag, d("c", "Array Iterator"));

},{"./":203,"d":139,"es5-ext/object/set-prototype-of":189,"es5-ext/string/#/contains":195,"es6-symbol":208}],201:[function(_dereq_,module,exports){
"use strict";

var isArguments = _dereq_("es5-ext/function/is-arguments")
  , callable    = _dereq_("es5-ext/object/valid-callable")
  , isString    = _dereq_("es5-ext/string/is-string")
  , get         = _dereq_("./get");

var isArray = Array.isArray, call = Function.prototype.call, some = Array.prototype.some;

module.exports = function (iterable, cb /*, thisArg*/) {
	var mode, thisArg = arguments[2], result, doBreak, broken, i, length, char, code;
	if (isArray(iterable) || isArguments(iterable)) mode = "array";
	else if (isString(iterable)) mode = "string";
	else iterable = get(iterable);

	callable(cb);
	doBreak = function () {
		broken = true;
	};
	if (mode === "array") {
		some.call(iterable, function (value) {
			call.call(cb, thisArg, value, doBreak);
			return broken;
		});
		return;
	}
	if (mode === "string") {
		length = iterable.length;
		for (i = 0; i < length; ++i) {
			char = iterable[i];
			if (i + 1 < length) {
				code = char.charCodeAt(0);
				if (code >= 0xd800 && code <= 0xdbff) char += iterable[++i];
			}
			call.call(cb, thisArg, char, doBreak);
			if (broken) break;
		}
		return;
	}
	result = iterable.next();

	while (!result.done) {
		call.call(cb, thisArg, result.value, doBreak);
		if (broken) return;
		result = iterable.next();
	}
};

},{"./get":202,"es5-ext/function/is-arguments":166,"es5-ext/object/valid-callable":192,"es5-ext/string/is-string":198}],202:[function(_dereq_,module,exports){
"use strict";

var isArguments    = _dereq_("es5-ext/function/is-arguments")
  , isString       = _dereq_("es5-ext/string/is-string")
  , ArrayIterator  = _dereq_("./array")
  , StringIterator = _dereq_("./string")
  , iterable       = _dereq_("./valid-iterable")
  , iteratorSymbol = _dereq_("es6-symbol").iterator;

module.exports = function (obj) {
	if (typeof iterable(obj)[iteratorSymbol] === "function") return obj[iteratorSymbol]();
	if (isArguments(obj)) return new ArrayIterator(obj);
	if (isString(obj)) return new StringIterator(obj);
	return new ArrayIterator(obj);
};

},{"./array":200,"./string":205,"./valid-iterable":206,"es5-ext/function/is-arguments":166,"es5-ext/string/is-string":198,"es6-symbol":208}],203:[function(_dereq_,module,exports){
"use strict";

var clear    = _dereq_("es5-ext/array/#/clear")
  , assign   = _dereq_("es5-ext/object/assign")
  , callable = _dereq_("es5-ext/object/valid-callable")
  , value    = _dereq_("es5-ext/object/valid-value")
  , d        = _dereq_("d")
  , autoBind = _dereq_("d/auto-bind")
  , Symbol   = _dereq_("es6-symbol");

var defineProperty = Object.defineProperty, defineProperties = Object.defineProperties, Iterator;

module.exports = Iterator = function (list, context) {
	if (!(this instanceof Iterator)) throw new TypeError("Constructor requires 'new'");
	defineProperties(this, {
		__list__: d("w", value(list)),
		__context__: d("w", context),
		__nextIndex__: d("w", 0)
	});
	if (!context) return;
	callable(context.on);
	context.on("_add", this._onAdd);
	context.on("_delete", this._onDelete);
	context.on("_clear", this._onClear);
};

// Internal %IteratorPrototype% doesn't expose its constructor
delete Iterator.prototype.constructor;

defineProperties(
	Iterator.prototype,
	assign(
		{
			_next: d(function () {
				var i;
				if (!this.__list__) return undefined;
				if (this.__redo__) {
					i = this.__redo__.shift();
					if (i !== undefined) return i;
				}
				if (this.__nextIndex__ < this.__list__.length) return this.__nextIndex__++;
				this._unBind();
				return undefined;
			}),
			next: d(function () {
				return this._createResult(this._next());
			}),
			_createResult: d(function (i) {
				if (i === undefined) return { done: true, value: undefined };
				return { done: false, value: this._resolve(i) };
			}),
			_resolve: d(function (i) {
				return this.__list__[i];
			}),
			_unBind: d(function () {
				this.__list__ = null;
				delete this.__redo__;
				if (!this.__context__) return;
				this.__context__.off("_add", this._onAdd);
				this.__context__.off("_delete", this._onDelete);
				this.__context__.off("_clear", this._onClear);
				this.__context__ = null;
			}),
			toString: d(function () {
				return "[object " + (this[Symbol.toStringTag] || "Object") + "]";
			})
		},
		autoBind({
			_onAdd: d(function (index) {
				if (index >= this.__nextIndex__) return;
				++this.__nextIndex__;
				if (!this.__redo__) {
					defineProperty(this, "__redo__", d("c", [index]));
					return;
				}
				this.__redo__.forEach(function (redo, i) {
					if (redo >= index) this.__redo__[i] = ++redo;
				}, this);
				this.__redo__.push(index);
			}),
			_onDelete: d(function (index) {
				var i;
				if (index >= this.__nextIndex__) return;
				--this.__nextIndex__;
				if (!this.__redo__) return;
				i = this.__redo__.indexOf(index);
				if (i !== -1) this.__redo__.splice(i, 1);
				this.__redo__.forEach(function (redo, j) {
					if (redo > index) this.__redo__[j] = --redo;
				}, this);
			}),
			_onClear: d(function () {
				if (this.__redo__) clear.call(this.__redo__);
				this.__nextIndex__ = 0;
			})
		})
	)
);

defineProperty(
	Iterator.prototype,
	Symbol.iterator,
	d(function () {
		return this;
	})
);

},{"d":139,"d/auto-bind":138,"es5-ext/array/#/clear":162,"es5-ext/object/assign":175,"es5-ext/object/valid-callable":192,"es5-ext/object/valid-value":194,"es6-symbol":208}],204:[function(_dereq_,module,exports){
"use strict";

var isArguments = _dereq_("es5-ext/function/is-arguments")
  , isValue     = _dereq_("es5-ext/object/is-value")
  , isString    = _dereq_("es5-ext/string/is-string");

var iteratorSymbol = _dereq_("es6-symbol").iterator
  , isArray        = Array.isArray;

module.exports = function (value) {
	if (!isValue(value)) return false;
	if (isArray(value)) return true;
	if (isString(value)) return true;
	if (isArguments(value)) return true;
	return typeof value[iteratorSymbol] === "function";
};

},{"es5-ext/function/is-arguments":166,"es5-ext/object/is-value":183,"es5-ext/string/is-string":198,"es6-symbol":208}],205:[function(_dereq_,module,exports){
// Thanks @mathiasbynens
// http://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols

"use strict";

var setPrototypeOf = _dereq_("es5-ext/object/set-prototype-of")
  , d              = _dereq_("d")
  , Symbol         = _dereq_("es6-symbol")
  , Iterator       = _dereq_("./");

var defineProperty = Object.defineProperty, StringIterator;

StringIterator = module.exports = function (str) {
	if (!(this instanceof StringIterator)) throw new TypeError("Constructor requires 'new'");
	str = String(str);
	Iterator.call(this, str);
	defineProperty(this, "__length__", d("", str.length));
};
if (setPrototypeOf) setPrototypeOf(StringIterator, Iterator);

// Internal %ArrayIteratorPrototype% doesn't expose its constructor
delete StringIterator.prototype.constructor;

StringIterator.prototype = Object.create(Iterator.prototype, {
	_next: d(function () {
		if (!this.__list__) return undefined;
		if (this.__nextIndex__ < this.__length__) return this.__nextIndex__++;
		this._unBind();
		return undefined;
	}),
	_resolve: d(function (i) {
		var char = this.__list__[i], code;
		if (this.__nextIndex__ === this.__length__) return char;
		code = char.charCodeAt(0);
		if (code >= 0xd800 && code <= 0xdbff) return char + this.__list__[this.__nextIndex__++];
		return char;
	})
});
defineProperty(StringIterator.prototype, Symbol.toStringTag, d("c", "String Iterator"));

},{"./":203,"d":139,"es5-ext/object/set-prototype-of":189,"es6-symbol":208}],206:[function(_dereq_,module,exports){
"use strict";

var isIterable = _dereq_("./is-iterable");

module.exports = function (value) {
	if (!isIterable(value)) throw new TypeError(value + " is not iterable");
	return value;
};

},{"./is-iterable":204}],207:[function(_dereq_,module,exports){
(function (process,global){
/*!
 * @overview es6-promise - a tiny implementation of Promises/A+.
 * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
 * @license   Licensed under MIT license
 *            See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
 * @version   3.3.1
 */

(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
    typeof define === 'function' && define.amd ? define(factory) :
    (global.ES6Promise = factory());
}(this, (function () { 'use strict';

function objectOrFunction(x) {
  return typeof x === 'function' || typeof x === 'object' && x !== null;
}

function isFunction(x) {
  return typeof x === 'function';
}

var _isArray = undefined;
if (!Array.isArray) {
  _isArray = function (x) {
    return Object.prototype.toString.call(x) === '[object Array]';
  };
} else {
  _isArray = Array.isArray;
}

var isArray = _isArray;

var len = 0;
var vertxNext = undefined;
var customSchedulerFn = undefined;

var asap = function asap(callback, arg) {
  queue[len] = callback;
  queue[len + 1] = arg;
  len += 2;
  if (len === 2) {
    // If len is 2, that means that we need to schedule an async flush.
    // If additional callbacks are queued before the queue is flushed, they
    // will be processed by this flush that we are scheduling.
    if (customSchedulerFn) {
      customSchedulerFn(flush);
    } else {
      scheduleFlush();
    }
  }
};

function setScheduler(scheduleFn) {
  customSchedulerFn = scheduleFn;
}

function setAsap(asapFn) {
  asap = asapFn;
}

var browserWindow = typeof window !== 'undefined' ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';

// test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';

// node
function useNextTick() {
  // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  // see https://github.com/cujojs/when/issues/410 for details
  return function () {
    return process.nextTick(flush);
  };
}

// vertx
function useVertxTimer() {
  return function () {
    vertxNext(flush);
  };
}

function useMutationObserver() {
  var iterations = 0;
  var observer = new BrowserMutationObserver(flush);
  var node = document.createTextNode('');
  observer.observe(node, { characterData: true });

  return function () {
    node.data = iterations = ++iterations % 2;
  };
}

// web worker
function useMessageChannel() {
  var channel = new MessageChannel();
  channel.port1.onmessage = flush;
  return function () {
    return channel.port2.postMessage(0);
  };
}

function useSetTimeout() {
  // Store setTimeout reference so es6-promise will be unaffected by
  // other code modifying setTimeout (like sinon.useFakeTimers())
  var globalSetTimeout = setTimeout;
  return function () {
    return globalSetTimeout(flush, 1);
  };
}

var queue = new Array(1000);
function flush() {
  for (var i = 0; i < len; i += 2) {
    var callback = queue[i];
    var arg = queue[i + 1];

    callback(arg);

    queue[i] = undefined;
    queue[i + 1] = undefined;
  }

  len = 0;
}

function attemptVertx() {
  try {
    var r = _dereq_;
    var vertx = r('vertx');
    vertxNext = vertx.runOnLoop || vertx.runOnContext;
    return useVertxTimer();
  } catch (e) {
    return useSetTimeout();
  }
}

var scheduleFlush = undefined;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
  scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
  scheduleFlush = useMutationObserver();
} else if (isWorker) {
  scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && typeof _dereq_ === 'function') {
  scheduleFlush = attemptVertx();
} else {
  scheduleFlush = useSetTimeout();
}

function then(onFulfillment, onRejection) {
  var _arguments = arguments;

  var parent = this;

  var child = new this.constructor(noop);

  if (child[PROMISE_ID] === undefined) {
    makePromise(child);
  }

  var _state = parent._state;

  if (_state) {
    (function () {
      var callback = _arguments[_state - 1];
      asap(function () {
        return invokeCallback(_state, child, callback, parent._result);
      });
    })();
  } else {
    subscribe(parent, child, onFulfillment, onRejection);
  }

  return child;
}

/**
  `Promise.resolve` returns a promise that will become resolved with the
  passed `value`. It is shorthand for the following:

  ```javascript
  let promise = new Promise(function(resolve, reject){
    resolve(1);
  });

  promise.then(function(value){
    // value === 1
  });
  ```

  Instead of writing the above, your code now simply becomes the following:

  ```javascript
  let promise = Promise.resolve(1);

  promise.then(function(value){
    // value === 1
  });
  ```

  @method resolve
  @static
  @param {Any} value value that the returned promise will be resolved with
  Useful for tooling.
  @return {Promise} a promise that will become fulfilled with the given
  `value`
*/
function resolve(object) {
  /*jshint validthis:true */
  var Constructor = this;

  if (object && typeof object === 'object' && object.constructor === Constructor) {
    return object;
  }

  var promise = new Constructor(noop);
  _resolve(promise, object);
  return promise;
}

var PROMISE_ID = Math.random().toString(36).substring(16);

function noop() {}

var PENDING = void 0;
var FULFILLED = 1;
var REJECTED = 2;

var GET_THEN_ERROR = new ErrorObject();

function selfFulfillment() {
  return new TypeError("You cannot resolve a promise with itself");
}

function cannotReturnOwn() {
  return new TypeError('A promises callback cannot return that same promise.');
}

function getThen(promise) {
  try {
    return promise.then;
  } catch (error) {
    GET_THEN_ERROR.error = error;
    return GET_THEN_ERROR;
  }
}

function tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  try {
    then.call(value, fulfillmentHandler, rejectionHandler);
  } catch (e) {
    return e;
  }
}

function handleForeignThenable(promise, thenable, then) {
  asap(function (promise) {
    var sealed = false;
    var error = tryThen(then, thenable, function (value) {
      if (sealed) {
        return;
      }
      sealed = true;
      if (thenable !== value) {
        _resolve(promise, value);
      } else {
        fulfill(promise, value);
      }
    }, function (reason) {
      if (sealed) {
        return;
      }
      sealed = true;

      _reject(promise, reason);
    }, 'Settle: ' + (promise._label || ' unknown promise'));

    if (!sealed && error) {
      sealed = true;
      _reject(promise, error);
    }
  }, promise);
}

function handleOwnThenable(promise, thenable) {
  if (thenable._state === FULFILLED) {
    fulfill(promise, thenable._result);
  } else if (thenable._state === REJECTED) {
    _reject(promise, thenable._result);
  } else {
    subscribe(thenable, undefined, function (value) {
      return _resolve(promise, value);
    }, function (reason) {
      return _reject(promise, reason);
    });
  }
}

function handleMaybeThenable(promise, maybeThenable, then$$) {
  if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) {
    handleOwnThenable(promise, maybeThenable);
  } else {
    if (then$$ === GET_THEN_ERROR) {
      _reject(promise, GET_THEN_ERROR.error);
    } else if (then$$ === undefined) {
      fulfill(promise, maybeThenable);
    } else if (isFunction(then$$)) {
      handleForeignThenable(promise, maybeThenable, then$$);
    } else {
      fulfill(promise, maybeThenable);
    }
  }
}

function _resolve(promise, value) {
  if (promise === value) {
    _reject(promise, selfFulfillment());
  } else if (objectOrFunction(value)) {
    handleMaybeThenable(promise, value, getThen(value));
  } else {
    fulfill(promise, value);
  }
}

function publishRejection(promise) {
  if (promise._onerror) {
    promise._onerror(promise._result);
  }

  publish(promise);
}

function fulfill(promise, value) {
  if (promise._state !== PENDING) {
    return;
  }

  promise._result = value;
  promise._state = FULFILLED;

  if (promise._subscribers.length !== 0) {
    asap(publish, promise);
  }
}

function _reject(promise, reason) {
  if (promise._state !== PENDING) {
    return;
  }
  promise._state = REJECTED;
  promise._result = reason;

  asap(publishRejection, promise);
}

function subscribe(parent, child, onFulfillment, onRejection) {
  var _subscribers = parent._subscribers;
  var length = _subscribers.length;

  parent._onerror = null;

  _subscribers[length] = child;
  _subscribers[length + FULFILLED] = onFulfillment;
  _subscribers[length + REJECTED] = onRejection;

  if (length === 0 && parent._state) {
    asap(publish, parent);
  }
}

function publish(promise) {
  var subscribers = promise._subscribers;
  var settled = promise._state;

  if (subscribers.length === 0) {
    return;
  }

  var child = undefined,
      callback = undefined,
      detail = promise._result;

  for (var i = 0; i < subscribers.length; i += 3) {
    child = subscribers[i];
    callback = subscribers[i + settled];

    if (child) {
      invokeCallback(settled, child, callback, detail);
    } else {
      callback(detail);
    }
  }

  promise._subscribers.length = 0;
}

function ErrorObject() {
  this.error = null;
}

var TRY_CATCH_ERROR = new ErrorObject();

function tryCatch(callback, detail) {
  try {
    return callback(detail);
  } catch (e) {
    TRY_CATCH_ERROR.error = e;
    return TRY_CATCH_ERROR;
  }
}

function invokeCallback(settled, promise, callback, detail) {
  var hasCallback = isFunction(callback),
      value = undefined,
      error = undefined,
      succeeded = undefined,
      failed = undefined;

  if (hasCallback) {
    value = tryCatch(callback, detail);

    if (value === TRY_CATCH_ERROR) {
      failed = true;
      error = value.error;
      value = null;
    } else {
      succeeded = true;
    }

    if (promise === value) {
      _reject(promise, cannotReturnOwn());
      return;
    }
  } else {
    value = detail;
    succeeded = true;
  }

  if (promise._state !== PENDING) {
    // noop
  } else if (hasCallback && succeeded) {
      _resolve(promise, value);
    } else if (failed) {
      _reject(promise, error);
    } else if (settled === FULFILLED) {
      fulfill(promise, value);
    } else if (settled === REJECTED) {
      _reject(promise, value);
    }
}

function initializePromise(promise, resolver) {
  try {
    resolver(function resolvePromise(value) {
      _resolve(promise, value);
    }, function rejectPromise(reason) {
      _reject(promise, reason);
    });
  } catch (e) {
    _reject(promise, e);
  }
}

var id = 0;
function nextId() {
  return id++;
}

function makePromise(promise) {
  promise[PROMISE_ID] = id++;
  promise._state = undefined;
  promise._result = undefined;
  promise._subscribers = [];
}

function Enumerator(Constructor, input) {
  this._instanceConstructor = Constructor;
  this.promise = new Constructor(noop);

  if (!this.promise[PROMISE_ID]) {
    makePromise(this.promise);
  }

  if (isArray(input)) {
    this._input = input;
    this.length = input.length;
    this._remaining = input.length;

    this._result = new Array(this.length);

    if (this.length === 0) {
      fulfill(this.promise, this._result);
    } else {
      this.length = this.length || 0;
      this._enumerate();
      if (this._remaining === 0) {
        fulfill(this.promise, this._result);
      }
    }
  } else {
    _reject(this.promise, validationError());
  }
}

function validationError() {
  return new Error('Array Methods must be provided an Array');
};

Enumerator.prototype._enumerate = function () {
  var length = this.length;
  var _input = this._input;

  for (var i = 0; this._state === PENDING && i < length; i++) {
    this._eachEntry(_input[i], i);
  }
};

Enumerator.prototype._eachEntry = function (entry, i) {
  var c = this._instanceConstructor;
  var resolve$$ = c.resolve;

  if (resolve$$ === resolve) {
    var _then = getThen(entry);

    if (_then === then && entry._state !== PENDING) {
      this._settledAt(entry._state, i, entry._result);
    } else if (typeof _then !== 'function') {
      this._remaining--;
      this._result[i] = entry;
    } else if (c === Promise) {
      var promise = new c(noop);
      handleMaybeThenable(promise, entry, _then);
      this._willSettleAt(promise, i);
    } else {
      this._willSettleAt(new c(function (resolve$$) {
        return resolve$$(entry);
      }), i);
    }
  } else {
    this._willSettleAt(resolve$$(entry), i);
  }
};

Enumerator.prototype._settledAt = function (state, i, value) {
  var promise = this.promise;

  if (promise._state === PENDING) {
    this._remaining--;

    if (state === REJECTED) {
      _reject(promise, value);
    } else {
      this._result[i] = value;
    }
  }

  if (this._remaining === 0) {
    fulfill(promise, this._result);
  }
};

Enumerator.prototype._willSettleAt = function (promise, i) {
  var enumerator = this;

  subscribe(promise, undefined, function (value) {
    return enumerator._settledAt(FULFILLED, i, value);
  }, function (reason) {
    return enumerator._settledAt(REJECTED, i, reason);
  });
};

/**
  `Promise.all` accepts an array of promises, and returns a new promise which
  is fulfilled with an array of fulfillment values for the passed promises, or
  rejected with the reason of the first passed promise to be rejected. It casts all
  elements of the passed iterable to promises as it runs this algorithm.

  Example:

  ```javascript
  let promise1 = resolve(1);
  let promise2 = resolve(2);
  let promise3 = resolve(3);
  let promises = [ promise1, promise2, promise3 ];

  Promise.all(promises).then(function(array){
    // The array here would be [ 1, 2, 3 ];
  });
  ```

  If any of the `promises` given to `all` are rejected, the first promise
  that is rejected will be given as an argument to the returned promises's
  rejection handler. For example:

  Example:

  ```javascript
  let promise1 = resolve(1);
  let promise2 = reject(new Error("2"));
  let promise3 = reject(new Error("3"));
  let promises = [ promise1, promise2, promise3 ];

  Promise.all(promises).then(function(array){
    // Code here never runs because there are rejected promises!
  }, function(error) {
    // error.message === "2"
  });
  ```

  @method all
  @static
  @param {Array} entries array of promises
  @param {String} label optional string for labeling the promise.
  Useful for tooling.
  @return {Promise} promise that is fulfilled when all `promises` have been
  fulfilled, or rejected if any of them become rejected.
  @static
*/
function all(entries) {
  return new Enumerator(this, entries).promise;
}

/**
  `Promise.race` returns a new promise which is settled in the same way as the
  first passed promise to settle.

  Example:

  ```javascript
  let promise1 = new Promise(function(resolve, reject){
    setTimeout(function(){
      resolve('promise 1');
    }, 200);
  });

  let promise2 = new Promise(function(resolve, reject){
    setTimeout(function(){
      resolve('promise 2');
    }, 100);
  });

  Promise.race([promise1, promise2]).then(function(result){
    // result === 'promise 2' because it was resolved before promise1
    // was resolved.
  });
  ```

  `Promise.race` is deterministic in that only the state of the first
  settled promise matters. For example, even if other promises given to the
  `promises` array argument are resolved, but the first settled promise has
  become rejected before the other promises became fulfilled, the returned
  promise will become rejected:

  ```javascript
  let promise1 = new Promise(function(resolve, reject){
    setTimeout(function(){
      resolve('promise 1');
    }, 200);
  });

  let promise2 = new Promise(function(resolve, reject){
    setTimeout(function(){
      reject(new Error('promise 2'));
    }, 100);
  });

  Promise.race([promise1, promise2]).then(function(result){
    // Code here never runs
  }, function(reason){
    // reason.message === 'promise 2' because promise 2 became rejected before
    // promise 1 became fulfilled
  });
  ```

  An example real-world use case is implementing timeouts:

  ```javascript
  Promise.race([ajax('foo.json'), timeout(5000)])
  ```

  @method race
  @static
  @param {Array} promises array of promises to observe
  Useful for tooling.
  @return {Promise} a promise which settles in the same way as the first passed
  promise to settle.
*/
function race(entries) {
  /*jshint validthis:true */
  var Constructor = this;

  if (!isArray(entries)) {
    return new Constructor(function (_, reject) {
      return reject(new TypeError('You must pass an array to race.'));
    });
  } else {
    return new Constructor(function (resolve, reject) {
      var length = entries.length;
      for (var i = 0; i < length; i++) {
        Constructor.resolve(entries[i]).then(resolve, reject);
      }
    });
  }
}

/**
  `Promise.reject` returns a promise rejected with the passed `reason`.
  It is shorthand for the following:

  ```javascript
  let promise = new Promise(function(resolve, reject){
    reject(new Error('WHOOPS'));
  });

  promise.then(function(value){
    // Code here doesn't run because the promise is rejected!
  }, function(reason){
    // reason.message === 'WHOOPS'
  });
  ```

  Instead of writing the above, your code now simply becomes the following:

  ```javascript
  let promise = Promise.reject(new Error('WHOOPS'));

  promise.then(function(value){
    // Code here doesn't run because the promise is rejected!
  }, function(reason){
    // reason.message === 'WHOOPS'
  });
  ```

  @method reject
  @static
  @param {Any} reason value that the returned promise will be rejected with.
  Useful for tooling.
  @return {Promise} a promise rejected with the given `reason`.
*/
function reject(reason) {
  /*jshint validthis:true */
  var Constructor = this;
  var promise = new Constructor(noop);
  _reject(promise, reason);
  return promise;
}

function needsResolver() {
  throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}

function needsNew() {
  throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}

/**
  Promise objects represent the eventual result of an asynchronous operation. The
  primary way of interacting with a promise is through its `then` method, which
  registers callbacks to receive either a promise's eventual value or the reason
  why the promise cannot be fulfilled.

  Terminology
  -----------

  - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  - `thenable` is an object or function that defines a `then` method.
  - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  - `exception` is a value that is thrown using the throw statement.
  - `reason` is a value that indicates why a promise was rejected.
  - `settled` the final resting state of a promise, fulfilled or rejected.

  A promise can be in one of three states: pending, fulfilled, or rejected.

  Promises that are fulfilled have a fulfillment value and are in the fulfilled
  state.  Promises that are rejected have a rejection reason and are in the
  rejected state.  A fulfillment value is never a thenable.

  Promises can also be said to *resolve* a value.  If this value is also a
  promise, then the original promise's settled state will match the value's
  settled state.  So a promise that *resolves* a promise that rejects will
  itself reject, and a promise that *resolves* a promise that fulfills will
  itself fulfill.


  Basic Usage:
  ------------

  ```js
  let promise = new Promise(function(resolve, reject) {
    // on success
    resolve(value);

    // on failure
    reject(reason);
  });

  promise.then(function(value) {
    // on fulfillment
  }, function(reason) {
    // on rejection
  });
  ```

  Advanced Usage:
  ---------------

  Promises shine when abstracting away asynchronous interactions such as
  `XMLHttpRequest`s.

  ```js
  function getJSON(url) {
    return new Promise(function(resolve, reject){
      let xhr = new XMLHttpRequest();

      xhr.open('GET', url);
      xhr.onreadystatechange = handler;
      xhr.responseType = 'json';
      xhr.setRequestHeader('Accept', 'application/json');
      xhr.send();

      function handler() {
        if (this.readyState === this.DONE) {
          if (this.status === 200) {
            resolve(this.response);
          } else {
            reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
          }
        }
      };
    });
  }

  getJSON('/posts.json').then(function(json) {
    // on fulfillment
  }, function(reason) {
    // on rejection
  });
  ```

  Unlike callbacks, promises are great composable primitives.

  ```js
  Promise.all([
    getJSON('/posts'),
    getJSON('/comments')
  ]).then(function(values){
    values[0] // => postsJSON
    values[1] // => commentsJSON

    return values;
  });
  ```

  @class Promise
  @param {function} resolver
  Useful for tooling.
  @constructor
*/
function Promise(resolver) {
  this[PROMISE_ID] = nextId();
  this._result = this._state = undefined;
  this._subscribers = [];

  if (noop !== resolver) {
    typeof resolver !== 'function' && needsResolver();
    this instanceof Promise ? initializePromise(this, resolver) : needsNew();
  }
}

Promise.all = all;
Promise.race = race;
Promise.resolve = resolve;
Promise.reject = reject;
Promise._setScheduler = setScheduler;
Promise._setAsap = setAsap;
Promise._asap = asap;

Promise.prototype = {
  constructor: Promise,

  /**
    The primary way of interacting with a promise is through its `then` method,
    which registers callbacks to receive either a promise's eventual value or the
    reason why the promise cannot be fulfilled.
  
    ```js
    findUser().then(function(user){
      // user is available
    }, function(reason){
      // user is unavailable, and you are given the reason why
    });
    ```
  
    Chaining
    --------
  
    The return value of `then` is itself a promise.  This second, 'downstream'
    promise is resolved with the return value of the first promise's fulfillment
    or rejection handler, or rejected if the handler throws an exception.
  
    ```js
    findUser().then(function (user) {
      return user.name;
    }, function (reason) {
      return 'default name';
    }).then(function (userName) {
      // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
      // will be `'default name'`
    });
  
    findUser().then(function (user) {
      throw new Error('Found user, but still unhappy');
    }, function (reason) {
      throw new Error('`findUser` rejected and we're unhappy');
    }).then(function (value) {
      // never reached
    }, function (reason) {
      // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
      // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
    });
    ```
    If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  
    ```js
    findUser().then(function (user) {
      throw new PedagogicalException('Upstream error');
    }).then(function (value) {
      // never reached
    }).then(function (value) {
      // never reached
    }, function (reason) {
      // The `PedgagocialException` is propagated all the way down to here
    });
    ```
  
    Assimilation
    ------------
  
    Sometimes the value you want to propagate to a downstream promise can only be
    retrieved asynchronously. This can be achieved by returning a promise in the
    fulfillment or rejection handler. The downstream promise will then be pending
    until the returned promise is settled. This is called *assimilation*.
  
    ```js
    findUser().then(function (user) {
      return findCommentsByAuthor(user);
    }).then(function (comments) {
      // The user's comments are now available
    });
    ```
  
    If the assimliated promise rejects, then the downstream promise will also reject.
  
    ```js
    findUser().then(function (user) {
      return findCommentsByAuthor(user);
    }).then(function (comments) {
      // If `findCommentsByAuthor` fulfills, we'll have the value here
    }, function (reason) {
      // If `findCommentsByAuthor` rejects, we'll have the reason here
    });
    ```
  
    Simple Example
    --------------
  
    Synchronous Example
  
    ```javascript
    let result;
  
    try {
      result = findResult();
      // success
    } catch(reason) {
      // failure
    }
    ```
  
    Errback Example
  
    ```js
    findResult(function(result, err){
      if (err) {
        // failure
      } else {
        // success
      }
    });
    ```
  
    Promise Example;
  
    ```javascript
    findResult().then(function(result){
      // success
    }, function(reason){
      // failure
    });
    ```
  
    Advanced Example
    --------------
  
    Synchronous Example
  
    ```javascript
    let author, books;
  
    try {
      author = findAuthor();
      books  = findBooksByAuthor(author);
      // success
    } catch(reason) {
      // failure
    }
    ```
  
    Errback Example
  
    ```js
  
    function foundBooks(books) {
  
    }
  
    function failure(reason) {
  
    }
  
    findAuthor(function(author, err){
      if (err) {
        failure(err);
        // failure
      } else {
        try {
          findBoooksByAuthor(author, function(books, err) {
            if (err) {
              failure(err);
            } else {
              try {
                foundBooks(books);
              } catch(reason) {
                failure(reason);
              }
            }
          });
        } catch(error) {
          failure(err);
        }
        // success
      }
    });
    ```
  
    Promise Example;
  
    ```javascript
    findAuthor().
      then(findBooksByAuthor).
      then(function(books){
        // found books
    }).catch(function(reason){
      // something went wrong
    });
    ```
  
    @method then
    @param {Function} onFulfilled
    @param {Function} onRejected
    Useful for tooling.
    @return {Promise}
  */
  then: then,

  /**
    `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
    as the catch block of a try/catch statement.
  
    ```js
    function findAuthor(){
      throw new Error('couldn't find that author');
    }
  
    // synchronous
    try {
      findAuthor();
    } catch(reason) {
      // something went wrong
    }
  
    // async with promises
    findAuthor().catch(function(reason){
      // something went wrong
    });
    ```
  
    @method catch
    @param {Function} onRejection
    Useful for tooling.
    @return {Promise}
  */
  'catch': function _catch(onRejection) {
    return this.then(null, onRejection);
  }
};

function polyfill() {
    var local = undefined;

    if (typeof global !== 'undefined') {
        local = global;
    } else if (typeof self !== 'undefined') {
        local = self;
    } else {
        try {
            local = Function('return this')();
        } catch (e) {
            throw new Error('polyfill failed because global object is unavailable in this environment');
        }
    }

    var P = local.Promise;

    if (P) {
        var promiseToString = null;
        try {
            promiseToString = Object.prototype.toString.call(P.resolve());
        } catch (e) {
            // silently ignored
        }

        if (promiseToString === '[object Promise]' && !P.cast) {
            return;
        }
    }

    local.Promise = Promise;
}

polyfill();
// Strange compat..
Promise.polyfill = polyfill;
Promise.Promise = Promise;

return Promise;

})));

}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":471}],208:[function(_dereq_,module,exports){
'use strict';

module.exports = _dereq_('./is-implemented')() ? Symbol : _dereq_('./polyfill');

},{"./is-implemented":209,"./polyfill":211}],209:[function(_dereq_,module,exports){
'use strict';

var validTypes = { object: true, symbol: true };

module.exports = function () {
	var symbol;
	if (typeof Symbol !== 'function') return false;
	symbol = Symbol('test symbol');
	try { String(symbol); } catch (e) { return false; }

	// Return 'true' also for polyfills
	if (!validTypes[typeof Symbol.iterator]) return false;
	if (!validTypes[typeof Symbol.toPrimitive]) return false;
	if (!validTypes[typeof Symbol.toStringTag]) return false;

	return true;
};

},{}],210:[function(_dereq_,module,exports){
'use strict';

module.exports = function (x) {
	if (!x) return false;
	if (typeof x === 'symbol') return true;
	if (!x.constructor) return false;
	if (x.constructor.name !== 'Symbol') return false;
	return (x[x.constructor.toStringTag] === 'Symbol');
};

},{}],211:[function(_dereq_,module,exports){
// ES2015 Symbol polyfill for environments that do not (or partially) support it

'use strict';

var d              = _dereq_('d')
  , validateSymbol = _dereq_('./validate-symbol')

  , create = Object.create, defineProperties = Object.defineProperties
  , defineProperty = Object.defineProperty, objPrototype = Object.prototype
  , NativeSymbol, SymbolPolyfill, HiddenSymbol, globalSymbols = create(null)
  , isNativeSafe;

if (typeof Symbol === 'function') {
	NativeSymbol = Symbol;
	try {
		String(NativeSymbol());
		isNativeSafe = true;
	} catch (ignore) {}
}

var generateName = (function () {
	var created = create(null);
	return function (desc) {
		var postfix = 0, name, ie11BugWorkaround;
		while (created[desc + (postfix || '')]) ++postfix;
		desc += (postfix || '');
		created[desc] = true;
		name = '@@' + desc;
		defineProperty(objPrototype, name, d.gs(null, function (value) {
			// For IE11 issue see:
			// https://connect.microsoft.com/IE/feedbackdetail/view/1928508/
			//    ie11-broken-getters-on-dom-objects
			// https://github.com/medikoo/es6-symbol/issues/12
			if (ie11BugWorkaround) return;
			ie11BugWorkaround = true;
			defineProperty(this, name, d(value));
			ie11BugWorkaround = false;
		}));
		return name;
	};
}());

// Internal constructor (not one exposed) for creating Symbol instances.
// This one is used to ensure that `someSymbol instanceof Symbol` always return false
HiddenSymbol = function Symbol(description) {
	if (this instanceof HiddenSymbol) throw new TypeError('Symbol is not a constructor');
	return SymbolPolyfill(description);
};

// Exposed `Symbol` constructor
// (returns instances of HiddenSymbol)
module.exports = SymbolPolyfill = function Symbol(description) {
	var symbol;
	if (this instanceof Symbol) throw new TypeError('Symbol is not a constructor');
	if (isNativeSafe) return NativeSymbol(description);
	symbol = create(HiddenSymbol.prototype);
	description = (description === undefined ? '' : String(description));
	return defineProperties(symbol, {
		__description__: d('', description),
		__name__: d('', generateName(description))
	});
};
defineProperties(SymbolPolyfill, {
	for: d(function (key) {
		if (globalSymbols[key]) return globalSymbols[key];
		return (globalSymbols[key] = SymbolPolyfill(String(key)));
	}),
	keyFor: d(function (s) {
		var key;
		validateSymbol(s);
		for (key in globalSymbols) if (globalSymbols[key] === s) return key;
	}),

	// To ensure proper interoperability with other native functions (e.g. Array.from)
	// fallback to eventual native implementation of given symbol
	hasInstance: d('', (NativeSymbol && NativeSymbol.hasInstance) || SymbolPolyfill('hasInstance')),
	isConcatSpreadable: d('', (NativeSymbol && NativeSymbol.isConcatSpreadable) ||
		SymbolPolyfill('isConcatSpreadable')),
	iterator: d('', (NativeSymbol && NativeSymbol.iterator) || SymbolPolyfill('iterator')),
	match: d('', (NativeSymbol && NativeSymbol.match) || SymbolPolyfill('match')),
	replace: d('', (NativeSymbol && NativeSymbol.replace) || SymbolPolyfill('replace')),
	search: d('', (NativeSymbol && NativeSymbol.search) || SymbolPolyfill('search')),
	species: d('', (NativeSymbol && NativeSymbol.species) || SymbolPolyfill('species')),
	split: d('', (NativeSymbol && NativeSymbol.split) || SymbolPolyfill('split')),
	toPrimitive: d('', (NativeSymbol && NativeSymbol.toPrimitive) || SymbolPolyfill('toPrimitive')),
	toStringTag: d('', (NativeSymbol && NativeSymbol.toStringTag) || SymbolPolyfill('toStringTag')),
	unscopables: d('', (NativeSymbol && NativeSymbol.unscopables) || SymbolPolyfill('unscopables'))
});

// Internal tweaks for real symbol producer
defineProperties(HiddenSymbol.prototype, {
	constructor: d(SymbolPolyfill),
	toString: d('', function () { return this.__name__; })
});

// Proper implementation of methods exposed on Symbol.prototype
// They won't be accessible on produced symbol instances as they derive from HiddenSymbol.prototype
defineProperties(SymbolPolyfill.prototype, {
	toString: d(function () { return 'Symbol (' + validateSymbol(this).__description__ + ')'; }),
	valueOf: d(function () { return validateSymbol(this); })
});
defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toPrimitive, d('', function () {
	var symbol = validateSymbol(this);
	if (typeof symbol === 'symbol') return symbol;
	return symbol.toString();
}));
defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, d('c', 'Symbol'));

// Proper implementaton of toPrimitive and toStringTag for returned symbol instances
defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toStringTag,
	d('c', SymbolPolyfill.prototype[SymbolPolyfill.toStringTag]));

// Note: It's important to define `toPrimitive` as last one, as some implementations
// implement `toPrimitive` natively without implementing `toStringTag` (or other specified symbols)
// And that may invoke error in definition flow:
// See: https://github.com/medikoo/es6-symbol/issues/13#issuecomment-164146149
defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toPrimitive,
	d('c', SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive]));

},{"./validate-symbol":212,"d":139}],212:[function(_dereq_,module,exports){
'use strict';

var isSymbol = _dereq_('./is-symbol');

module.exports = function (value) {
	if (!isSymbol(value)) throw new TypeError(value + " is not a symbol");
	return value;
};

},{"./is-symbol":210}],213:[function(_dereq_,module,exports){
'use strict';

module.exports = _dereq_('./is-implemented')() ? WeakMap : _dereq_('./polyfill');

},{"./is-implemented":214,"./polyfill":216}],214:[function(_dereq_,module,exports){
'use strict';

module.exports = function () {
	var weakMap, x;
	if (typeof WeakMap !== 'function') return false;
	try {
		// WebKit doesn't support arguments and crashes
		weakMap = new WeakMap([[x = {}, 'one'], [{}, 'two'], [{}, 'three']]);
	} catch (e) {
		return false;
	}
	if (String(weakMap) !== '[object WeakMap]') return false;
	if (typeof weakMap.set !== 'function') return false;
	if (weakMap.set({}, 1) !== weakMap) return false;
	if (typeof weakMap.delete !== 'function') return false;
	if (typeof weakMap.has !== 'function') return false;
	if (weakMap.get(x) !== 'one') return false;

	return true;
};

},{}],215:[function(_dereq_,module,exports){
// Exports true if environment provides native `WeakMap` implementation, whatever that is.

'use strict';

module.exports = (function () {
	if (typeof WeakMap !== 'function') return false;
	return (Object.prototype.toString.call(new WeakMap()) === '[object WeakMap]');
}());

},{}],216:[function(_dereq_,module,exports){
'use strict';

var setPrototypeOf    = _dereq_('es5-ext/object/set-prototype-of')
  , object            = _dereq_('es5-ext/object/valid-object')
  , value             = _dereq_('es5-ext/object/valid-value')
  , randomUniq        = _dereq_('es5-ext/string/random-uniq')
  , d                 = _dereq_('d')
  , getIterator       = _dereq_('es6-iterator/get')
  , forOf             = _dereq_('es6-iterator/for-of')
  , toStringTagSymbol = _dereq_('es6-symbol').toStringTag
  , isNative          = _dereq_('./is-native-implemented')

  , isArray = Array.isArray, defineProperty = Object.defineProperty
  , hasOwnProperty = Object.prototype.hasOwnProperty, getPrototypeOf = Object.getPrototypeOf
  , WeakMapPoly;

module.exports = WeakMapPoly = function (/*iterable*/) {
	var iterable = arguments[0], self;
	if (!(this instanceof WeakMapPoly)) throw new TypeError('Constructor requires \'new\'');
	if (isNative && setPrototypeOf && (WeakMap !== WeakMapPoly)) {
		self = setPrototypeOf(new WeakMap(), getPrototypeOf(this));
	} else {
		self = this;
	}
	if (iterable != null) {
		if (!isArray(iterable)) iterable = getIterator(iterable);
	}
	defineProperty(self, '__weakMapData__', d('c', '$weakMap$' + randomUniq()));
	if (!iterable) return self;
	forOf(iterable, function (val) {
		value(val);
		self.set(val[0], val[1]);
	});
	return self;
};

if (isNative) {
	if (setPrototypeOf) setPrototypeOf(WeakMapPoly, WeakMap);
	WeakMapPoly.prototype = Object.create(WeakMap.prototype, {
		constructor: d(WeakMapPoly)
	});
}

Object.defineProperties(WeakMapPoly.prototype, {
	delete: d(function (key) {
		if (hasOwnProperty.call(object(key), this.__weakMapData__)) {
			delete key[this.__weakMapData__];
			return true;
		}
		return false;
	}),
	get: d(function (key) {
		if (hasOwnProperty.call(object(key), this.__weakMapData__)) {
			return key[this.__weakMapData__];
		}
	}),
	has: d(function (key) {
		return hasOwnProperty.call(object(key), this.__weakMapData__);
	}),
	set: d(function (key, value) {
		defineProperty(object(key), this.__weakMapData__, d('c', value));
		return this;
	}),
	toString: d(function () { return '[object WeakMap]'; })
});
defineProperty(WeakMapPoly.prototype, toStringTagSymbol, d('c', 'WeakMap'));

},{"./is-native-implemented":215,"d":139,"es5-ext/object/set-prototype-of":189,"es5-ext/object/valid-object":193,"es5-ext/object/valid-value":194,"es5-ext/string/random-uniq":199,"es6-iterator/for-of":201,"es6-iterator/get":202,"es6-symbol":208}],217:[function(_dereq_,module,exports){
"use strict"

module.exports = extractPlanes

function extractPlanes(M, zNear, zFar) {
  var z  = zNear || 0.0
  var zf = zFar || 1.0
  return [
    [ M[12] + M[0], M[13] + M[1], M[14] + M[2], M[15] + M[3] ],
    [ M[12] - M[0], M[13] - M[1], M[14] - M[2], M[15] - M[3] ],
    [ M[12] + M[4], M[13] + M[5], M[14] + M[6], M[15] + M[7] ],
    [ M[12] - M[4], M[13] - M[5], M[14] - M[6], M[15] - M[7] ],
    [ z*M[12] + M[8], z*M[13] + M[9], z*M[14] + M[10], z*M[15] + M[11] ],
    [ zf*M[12] - M[8], zf*M[13] - M[9], zf*M[14] - M[10], zf*M[15] - M[11] ]
  ]
}
},{}],218:[function(_dereq_,module,exports){
/**
 * inspired by is-number <https://github.com/jonschlinkert/is-number>
 * but significantly simplified and sped up by ignoring number and string constructors
 * ie these return false:
 *   new Number(1)
 *   new String('1')
 */

'use strict';

var allBlankCharCodes = _dereq_('is-string-blank');

module.exports = function(n) {
    var type = typeof n;
    if(type === 'string') {
        var original = n;
        n = +n;
        // whitespace strings cast to zero - filter them out
        if(n===0 && allBlankCharCodes(original)) return false;
    }
    else if(type !== 'number') return false;

    return n - n < 1;
};

},{"is-string-blank":412}],219:[function(_dereq_,module,exports){
'use strict'

module.exports = createFilteredVector

var cubicHermite = _dereq_('cubic-hermite')
var bsearch = _dereq_('binary-search-bounds')

function clamp(lo, hi, x) {
  return Math.min(hi, Math.max(lo, x))
}

function FilteredVector(state0, velocity0, t0) {
  this.dimension  = state0.length
  this.bounds     = [ new Array(this.dimension), new Array(this.dimension) ]
  for(var i=0; i<this.dimension; ++i) {
    this.bounds[0][i] = -Infinity
    this.bounds[1][i] = Infinity
  }
  this._state     = state0.slice().reverse()
  this._velocity  = velocity0.slice().reverse()
  this._time      = [ t0 ]
  this._scratch   = [ state0.slice(), state0.slice(), state0.slice(), state0.slice(), state0.slice() ]
}

var proto = FilteredVector.prototype

proto.flush = function(t) {
  var idx = bsearch.gt(this._time, t) - 1
  if(idx <= 0) {
    return
  }
  this._time.splice(0, idx)
  this._state.splice(0, idx * this.dimension)
  this._velocity.splice(0, idx * this.dimension)
}

proto.curve = function(t) {
  var time      = this._time
  var n         = time.length
  var idx       = bsearch.le(time, t)
  var result    = this._scratch[0]
  var state     = this._state
  var velocity  = this._velocity
  var d         = this.dimension
  var bounds    = this.bounds
  if(idx < 0) {
    var ptr = d-1
    for(var i=0; i<d; ++i, --ptr) {
      result[i] = state[ptr]
    }
  } else if(idx >= n-1) {
    var ptr = state.length-1
    var tf = t - time[n-1]
    for(var i=0; i<d; ++i, --ptr) {
      result[i] = state[ptr] + tf * velocity[ptr]
    }
  } else {
    var ptr = d * (idx+1) - 1
    var t0  = time[idx]
    var t1  = time[idx+1]
    var dt  = (t1 - t0) || 1.0
    var x0  = this._scratch[1]
    var x1  = this._scratch[2]
    var v0  = this._scratch[3]
    var v1  = this._scratch[4]
    var steady = true
    for(var i=0; i<d; ++i, --ptr) {
      x0[i] = state[ptr]
      v0[i] = velocity[ptr] * dt
      x1[i] = state[ptr+d]
      v1[i] = velocity[ptr+d] * dt
      steady = steady && (x0[i] === x1[i] && v0[i] === v1[i] && v0[i] === 0.0)
    }
    if(steady) {
      for(var i=0; i<d; ++i) {
        result[i] = x0[i]
      }
    } else {
      cubicHermite(x0, v0, x1, v1, (t-t0)/dt, result)
    }
  }
  var lo = bounds[0]
  var hi = bounds[1]
  for(var i=0; i<d; ++i) {
    result[i] = clamp(lo[i], hi[i], result[i])
  }
  return result
}

proto.dcurve = function(t) {
  var time     = this._time
  var n        = time.length
  var idx      = bsearch.le(time, t)
  var result   = this._scratch[0]
  var state    = this._state
  var velocity = this._velocity
  var d        = this.dimension
  if(idx >= n-1) {
    var ptr = state.length-1
    var tf = t - time[n-1]
    for(var i=0; i<d; ++i, --ptr) {
      result[i] = velocity[ptr]
    }
  } else {
    var ptr = d * (idx+1) - 1
    var t0 = time[idx]
    var t1 = time[idx+1]
    var dt = (t1 - t0) || 1.0
    var x0 = this._scratch[1]
    var x1 = this._scratch[2]
    var v0 = this._scratch[3]
    var v1 = this._scratch[4]
    var steady = true
    for(var i=0; i<d; ++i, --ptr) {
      x0[i] = state[ptr]
      v0[i] = velocity[ptr] * dt
      x1[i] = state[ptr+d]
      v1[i] = velocity[ptr+d] * dt
      steady = steady && (x0[i] === x1[i] && v0[i] === v1[i] && v0[i] === 0.0)
    }
    if(steady) {
      for(var i=0; i<d; ++i) {
        result[i] = 0.0
      }
    } else {
      cubicHermite.derivative(x0, v0, x1, v1, (t-t0)/dt, result)
      for(var i=0; i<d; ++i) {
        result[i] /= dt
      }
    }
  }
  return result
}

proto.lastT = function() {
  var time = this._time
  return time[time.length-1]
}

proto.stable = function() {
  var velocity = this._velocity
  var ptr = velocity.length
  for(var i=this.dimension-1; i>=0; --i) {
    if(velocity[--ptr]) {
      return false
    }
  }
  return true
}

proto.jump = function(t) {
  var t0 = this.lastT()
  var d  = this.dimension
  if(t < t0 || arguments.length !== d+1) {
    return
  }
  var state     = this._state
  var velocity  = this._velocity
  var ptr       = state.length-this.dimension
  var bounds    = this.bounds
  var lo        = bounds[0]
  var hi        = bounds[1]
  this._time.push(t0, t)
  for(var j=0; j<2; ++j) {
    for(var i=0; i<d; ++i) {
      state.push(state[ptr++])
      velocity.push(0)
    }
  }
  this._time.push(t)
  for(var i=d; i>0; --i) {
    state.push(clamp(lo[i-1], hi[i-1], arguments[i]))
    velocity.push(0)
  }
}

proto.push = function(t) {
  var t0 = this.lastT()
  var d  = this.dimension
  if(t < t0 || arguments.length !== d+1) {
    return
  }
  var state     = this._state
  var velocity  = this._velocity
  var ptr       = state.length-this.dimension
  var dt        = t - t0
  var bounds    = this.bounds
  var lo        = bounds[0]
  var hi        = bounds[1]
  var sf        = (dt > 1e-6) ? 1/dt : 0
  this._time.push(t)
  for(var i=d; i>0; --i) {
    var xc = clamp(lo[i-1], hi[i-1], arguments[i])
    state.push(xc)
    velocity.push((xc - state[ptr++]) * sf)
  }
}

proto.set = function(t) {
  var d = this.dimension
  if(t < this.lastT() || arguments.length !== d+1) {
    return
  }
  var state     = this._state
  var velocity  = this._velocity
  var bounds    = this.bounds
  var lo        = bounds[0]
  var hi        = bounds[1]
  this._time.push(t)
  for(var i=d; i>0; --i) {
    state.push(clamp(lo[i-1], hi[i-1], arguments[i]))
    velocity.push(0)
  }
}

proto.move = function(t) {
  var t0 = this.lastT()
  var d  = this.dimension
  if(t <= t0 || arguments.length !== d+1) {
    return
  }
  var state    = this._state
  var velocity = this._velocity
  var statePtr = state.length - this.dimension
  var bounds   = this.bounds
  var lo       = bounds[0]
  var hi       = bounds[1]
  var dt       = t - t0
  var sf       = (dt > 1e-6) ? 1/dt : 0.0
  this._time.push(t)
  for(var i=d; i>0; --i) {
    var dx = arguments[i]
    state.push(clamp(lo[i-1], hi[i-1], state[statePtr++] + dx))
    velocity.push(dx * sf)
  }
}

proto.idle = function(t) {
  var t0 = this.lastT()
  if(t < t0) {
    return
  }
  var d        = this.dimension
  var state    = this._state
  var velocity = this._velocity
  var statePtr = state.length-d
  var bounds   = this.bounds
  var lo       = bounds[0]
  var hi       = bounds[1]
  var dt       = t - t0
  this._time.push(t)
  for(var i=d-1; i>=0; --i) {
    state.push(clamp(lo[i], hi[i], state[statePtr] + dt * velocity[statePtr]))
    velocity.push(0)
    statePtr += 1
  }
}

function getZero(d) {
  var result = new Array(d)
  for(var i=0; i<d; ++i) {
    result[i] = 0.0
  }
  return result
}

function createFilteredVector(initState, initVelocity, initTime) {
  switch(arguments.length) {
    case 0:
      return new FilteredVector([0], [0], 0)
    case 1:
      if(typeof initState === 'number') {
        var zero = getZero(initState)
        return new FilteredVector(zero, zero, 0)
      } else {
        return new FilteredVector(initState, getZero(initState.length), 0)
      }
    case 2:
      if(typeof initVelocity === 'number') {
        var zero = getZero(initState.length)
        return new FilteredVector(initState, zero, +initVelocity)
      } else {
        initTime = 0
      }
    case 3:
      if(initState.length !== initVelocity.length) {
        throw new Error('state and velocity lengths must match')
      }
      return new FilteredVector(initState, initVelocity, initTime)
  }
}

},{"binary-search-bounds":79,"cubic-hermite":133}],220:[function(_dereq_,module,exports){
/*eslint new-cap:0*/
var dtype = _dereq_('dtype')

module.exports = flattenVertexData

function flattenVertexData (data, output, offset) {
  if (!data) throw new TypeError('must specify data as first parameter')
  offset = +(offset || 0) | 0

  if (Array.isArray(data) && (data[0] && typeof data[0][0] === 'number')) {
    var dim = data[0].length
    var length = data.length * dim
    var i, j, k, l

    // no output specified, create a new typed array
    if (!output || typeof output === 'string') {
      output = new (dtype(output || 'float32'))(length + offset)
    }

    var dstLength = output.length - offset
    if (length !== dstLength) {
      throw new Error('source length ' + length + ' (' + dim + 'x' + data.length + ')' +
        ' does not match destination length ' + dstLength)
    }

    for (i = 0, k = offset; i < data.length; i++) {
      for (j = 0; j < dim; j++) {
        output[k++] = data[i][j] === null ? NaN : data[i][j]
      }
    }
  } else {
    if (!output || typeof output === 'string') {
      // no output, create a new one
      var Ctor = dtype(output || 'float32')

      // handle arrays separately due to possible nulls
      if (Array.isArray(data) || output === 'array') {
        output = new Ctor(data.length + offset)
        for (i = 0, k = offset, l = output.length; k < l; k++, i++) {
          output[k] = data[i] === null ? NaN : data[i]
        }
      } else {
        if (offset === 0) {
          output = new Ctor(data)
        } else {
          output = new Ctor(data.length + offset)

          output.set(data, offset)
        }
      }
    } else {
      // store output in existing array
      output.set(data, offset)
    }
  }

  return output
}

},{"dtype":157}],221:[function(_dereq_,module,exports){
'use strict'

var stringifyFont = _dereq_('css-font/stringify')
var defaultChars = [32, 126]

module.exports = atlas

function atlas(options) {
  options = options || {}

  var shape  = options.shape ? options.shape : options.canvas ? [options.canvas.width, options.canvas.height] : [512, 512]
  var canvas = options.canvas || document.createElement('canvas')
  var font   = options.font
  var step   = typeof options.step === 'number' ? [options.step, options.step] : options.step || [32, 32]
  var chars  = options.chars || defaultChars

  if (font && typeof font !== 'string') font = stringifyFont(font)

  if (!Array.isArray(chars)) {
    chars = String(chars).split('')
  } else
  if (chars.length === 2
    && typeof chars[0] === 'number'
    && typeof chars[1] === 'number'
  ) {
    var newchars = []

    for (var i = chars[0], j = 0; i <= chars[1]; i++) {
      newchars[j++] = String.fromCharCode(i)
    }

    chars = newchars
  }

  shape = shape.slice()
  canvas.width  = shape[0]
  canvas.height = shape[1]

  var ctx = canvas.getContext('2d')

  ctx.fillStyle = '#000'
  ctx.fillRect(0, 0, canvas.width, canvas.height)

  ctx.font = font
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'
  ctx.fillStyle = '#fff'

  var x = step[0] / 2
  var y = step[1] / 2
  for (var i = 0; i < chars.length; i++) {
    ctx.fillText(chars[i], x, y)
    if ((x += step[0]) > shape[0] - step[0]/2) (x = step[0]/2), (y += step[1])
  }

  return canvas
}

},{"css-font/stringify":130}],222:[function(_dereq_,module,exports){
'use strict'

module.exports = measure

measure.canvas = document.createElement('canvas')
measure.cache = {}

function measure (font, o) {
	if (!o) o = {}

	if (typeof font === 'string' || Array.isArray(font)) {
		o.family = font
	}

	var family = Array.isArray(o.family) ? o.family.join(', ') : o.family
	if (!family) throw Error('`family` must be defined')

	var fs = o.size || o.fontSize || o.em || 48
	var weight = o.weight || o.fontWeight || ''
	var style = o.style || o.fontStyle || ''
	var font = [style, weight, fs].join(' ') + 'px ' + family
	var origin = o.origin || 'top'

	if (measure.cache[family]) {
		// return more precise values if cache has them
		if (fs <= measure.cache[family].em) {
			return applyOrigin(measure.cache[family], origin)
		}
	}

	var canvas = o.canvas || measure.canvas
	var ctx = canvas.getContext('2d')
	var chars = {
		upper: o.upper !== undefined ? o.upper : 'H',
		lower: o.lower !== undefined ? o.lower : 'x',
		descent: o.descent !== undefined ? o.descent : 'p',
		ascent: o.ascent !== undefined ? o.ascent : 'h',
		tittle: o.tittle !== undefined ? o.tittle : 'i',
		overshoot: o.overshoot !== undefined ? o.overshoot : 'O'
	}
	var l = Math.ceil(fs * 1.5)
	canvas.height = l
	canvas.width = l * .5
	ctx.font = font

	var char = 'H'
	var result = {
		top: 0
	}

	// measure line-height
	ctx.clearRect(0, 0, l, l)
	ctx.textBaseline = 'top'
	ctx.fillStyle = 'black'
	ctx.fillText(char, 0, 0)
	var topPx = firstTop(ctx.getImageData(0, 0, l, l))
	ctx.clearRect(0, 0, l, l)
	ctx.textBaseline = 'bottom'
	ctx.fillText(char, 0, l)
	var bottomPx = firstTop(ctx.getImageData(0, 0, l, l))
	result.lineHeight =
	result.bottom = l - bottomPx + topPx

	// measure baseline
	ctx.clearRect(0, 0, l, l)
	ctx.textBaseline = 'alphabetic'
	ctx.fillText(char, 0, l)
	var baselinePx = firstTop(ctx.getImageData(0, 0, l, l))
	var baseline = l - baselinePx - 1 + topPx
	result.baseline =
	result.alphabetic = baseline

	// measure median
	ctx.clearRect(0, 0, l, l)
	ctx.textBaseline = 'middle'
	ctx.fillText(char, 0, l * .5)
	var medianPx = firstTop(ctx.getImageData(0, 0, l, l))
	result.median =
	result.middle = l - medianPx - 1 + topPx - l * .5

	// measure hanging
	ctx.clearRect(0, 0, l, l)
	ctx.textBaseline = 'hanging'
	ctx.fillText(char, 0, l * .5)
	var hangingPx = firstTop(ctx.getImageData(0, 0, l, l))
	result.hanging = l - hangingPx - 1 + topPx - l * .5

	// measure ideographic
	ctx.clearRect(0, 0, l, l)
	ctx.textBaseline = 'ideographic'
	ctx.fillText(char, 0, l)
	var ideographicPx = firstTop(ctx.getImageData(0, 0, l, l))
	result.ideographic = l - ideographicPx - 1 + topPx

	// measure cap
	if (chars.upper) {
		ctx.clearRect(0, 0, l, l)
		ctx.textBaseline = 'top'
		ctx.fillText(chars.upper, 0, 0)
		result.upper = firstTop(ctx.getImageData(0, 0, l, l))
		result.capHeight = (result.baseline - result.upper)
	}

	// measure x
	if (chars.lower) {
		ctx.clearRect(0, 0, l, l)
		ctx.textBaseline = 'top'
		ctx.fillText(chars.lower, 0, 0)
		result.lower = firstTop(ctx.getImageData(0, 0, l, l))
		result.xHeight = (result.baseline - result.lower)
	}

	// measure tittle
	if (chars.tittle) {
		ctx.clearRect(0, 0, l, l)
		ctx.textBaseline = 'top'
		ctx.fillText(chars.tittle, 0, 0)
		result.tittle = firstTop(ctx.getImageData(0, 0, l, l))
	}

	// measure ascent
	if (chars.ascent) {
		ctx.clearRect(0, 0, l, l)
		ctx.textBaseline = 'top'
		ctx.fillText(chars.ascent, 0, 0)
		result.ascent = firstTop(ctx.getImageData(0, 0, l, l))
	}

	// measure descent
	if (chars.descent) {
		ctx.clearRect(0, 0, l, l)
		ctx.textBaseline = 'top'
		ctx.fillText(chars.descent, 0, 0)
		result.descent = firstBottom(ctx.getImageData(0, 0, l, l))
	}

	// measure overshoot
	if (chars.overshoot) {
		ctx.clearRect(0, 0, l, l)
		ctx.textBaseline = 'top'
		ctx.fillText(chars.overshoot, 0, 0)
		var overshootPx = firstBottom(ctx.getImageData(0, 0, l, l))
		result.overshoot = overshootPx - baseline
	}

	// normalize result
	for (var name in result) {
		result[name] /= fs
	}

	result.em = fs
	measure.cache[family] = result

	return applyOrigin(result, origin)
}

function applyOrigin(obj, origin) {
	var res = {}
	if (typeof origin === 'string') origin = obj[origin]
	for (var name in obj) {
		if (name === 'em') continue
		res[name] = obj[name] - origin
	}
	return res
}

function firstTop(iData) {
	var l = iData.height
	var data = iData.data
	for (var i = 3; i < data.length; i+=4) {
		if (data[i] !== 0) {
			return Math.floor((i - 3) *.25 / l)
		}
	}
}

function firstBottom(iData) {
	var l = iData.height
	var data = iData.data
	for (var i = data.length - 1; i > 0; i -= 4) {
		if (data[i] !== 0) {
			return Math.floor((i - 3) *.25 / l)
		}
	}
}

},{}],223:[function(_dereq_,module,exports){
"use strict"

module.exports = createRBTree

var RED   = 0
var BLACK = 1

function RBNode(color, key, value, left, right, count) {
  this._color = color
  this.key = key
  this.value = value
  this.left = left
  this.right = right
  this._count = count
}

function cloneNode(node) {
  return new RBNode(node._color, node.key, node.value, node.left, node.right, node._count)
}

function repaint(color, node) {
  return new RBNode(color, node.key, node.value, node.left, node.right, node._count)
}

function recount(node) {
  node._count = 1 + (node.left ? node.left._count : 0) + (node.right ? node.right._count : 0)
}

function RedBlackTree(compare, root) {
  this._compare = compare
  this.root = root
}

var proto = RedBlackTree.prototype

Object.defineProperty(proto, "keys", {
  get: function() {
    var result = []
    this.forEach(function(k,v) {
      result.push(k)
    })
    return result
  }
})

Object.defineProperty(proto, "values", {
  get: function() {
    var result = []
    this.forEach(function(k,v) {
      result.push(v)
    })
    return result
  }
})

//Returns the number of nodes in the tree
Object.defineProperty(proto, "length", {
  get: function() {
    if(this.root) {
      return this.root._count
    }
    return 0
  }
})

//Insert a new item into the tree
proto.insert = function(key, value) {
  var cmp = this._compare
  //Find point to insert new node at
  var n = this.root
  var n_stack = []
  var d_stack = []
  while(n) {
    var d = cmp(key, n.key)
    n_stack.push(n)
    d_stack.push(d)
    if(d <= 0) {
      n = n.left
    } else {
      n = n.right
    }
  }
  //Rebuild path to leaf node
  n_stack.push(new RBNode(RED, key, value, null, null, 1))
  for(var s=n_stack.length-2; s>=0; --s) {
    var n = n_stack[s]
    if(d_stack[s] <= 0) {
      n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s+1], n.right, n._count+1)
    } else {
      n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s+1], n._count+1)
    }
  }
  //Rebalance tree using rotations
  //console.log("start insert", key, d_stack)
  for(var s=n_stack.length-1; s>1; --s) {
    var p = n_stack[s-1]
    var n = n_stack[s]
    if(p._color === BLACK || n._color === BLACK) {
      break
    }
    var pp = n_stack[s-2]
    if(pp.left === p) {
      if(p.left === n) {
        var y = pp.right
        if(y && y._color === RED) {
          //console.log("LLr")
          p._color = BLACK
          pp.right = repaint(BLACK, y)
          pp._color = RED
          s -= 1
        } else {
          //console.log("LLb")
          pp._color = RED
          pp.left = p.right
          p._color = BLACK
          p.right = pp
          n_stack[s-2] = p
          n_stack[s-1] = n
          recount(pp)
          recount(p)
          if(s >= 3) {
            var ppp = n_stack[s-3]
            if(ppp.left === pp) {
              ppp.left = p
            } else {
              ppp.right = p
            }
          }
          break
        }
      } else {
        var y = pp.right
        if(y && y._color === RED) {
          //console.log("LRr")
          p._color = BLACK
          pp.right = repaint(BLACK, y)
          pp._color = RED
          s -= 1
        } else {
          //console.log("LRb")
          p.right = n.left
          pp._color = RED
          pp.left = n.right
          n._color = BLACK
          n.left = p
          n.right = pp
          n_stack[s-2] = n
          n_stack[s-1] = p
          recount(pp)
          recount(p)
          recount(n)
          if(s >= 3) {
            var ppp = n_stack[s-3]
            if(ppp.left === pp) {
              ppp.left = n
            } else {
              ppp.right = n
            }
          }
          break
        }
      }
    } else {
      if(p.right === n) {
        var y = pp.left
        if(y && y._color === RED) {
          //console.log("RRr", y.key)
          p._color = BLACK
          pp.left = repaint(BLACK, y)
          pp._color = RED
          s -= 1
        } else {
          //console.log("RRb")
          pp._color = RED
          pp.right = p.left
          p._color = BLACK
          p.left = pp
          n_stack[s-2] = p
          n_stack[s-1] = n
          recount(pp)
          recount(p)
          if(s >= 3) {
            var ppp = n_stack[s-3]
            if(ppp.right === pp) {
              ppp.right = p
            } else {
              ppp.left = p
            }
          }
          break
        }
      } else {
        var y = pp.left
        if(y && y._color === RED) {
          //console.log("RLr")
          p._color = BLACK
          pp.left = repaint(BLACK, y)
          pp._color = RED
          s -= 1
        } else {
          //console.log("RLb")
          p.left = n.right
          pp._color = RED
          pp.right = n.left
          n._color = BLACK
          n.right = p
          n.left = pp
          n_stack[s-2] = n
          n_stack[s-1] = p
          recount(pp)
          recount(p)
          recount(n)
          if(s >= 3) {
            var ppp = n_stack[s-3]
            if(ppp.right === pp) {
              ppp.right = n
            } else {
              ppp.left = n
            }
          }
          break
        }
      }
    }
  }
  //Return new tree
  n_stack[0]._color = BLACK
  return new RedBlackTree(cmp, n_stack[0])
}


//Visit all nodes inorder
function doVisitFull(visit, node) {
  if(node.left) {
    var v = doVisitFull(visit, node.left)
    if(v) { return v }
  }
  var v = visit(node.key, node.value)
  if(v) { return v }
  if(node.right) {
    return doVisitFull(visit, node.right)
  }
}

//Visit half nodes in order
function doVisitHalf(lo, compare, visit, node) {
  var l = compare(lo, node.key)
  if(l <= 0) {
    if(node.left) {
      var v = doVisitHalf(lo, compare, visit, node.left)
      if(v) { return v }
    }
    var v = visit(node.key, node.value)
    if(v) { return v }
  }
  if(node.right) {
    return doVisitHalf(lo, compare, visit, node.right)
  }
}

//Visit all nodes within a range
function doVisit(lo, hi, compare, visit, node) {
  var l = compare(lo, node.key)
  var h = compare(hi, node.key)
  var v
  if(l <= 0) {
    if(node.left) {
      v = doVisit(lo, hi, compare, visit, node.left)
      if(v) { return v }
    }
    if(h > 0) {
      v = visit(node.key, node.value)
      if(v) { return v }
    }
  }
  if(h > 0 && node.right) {
    return doVisit(lo, hi, compare, visit, node.right)
  }
}


proto.forEach = function rbTreeForEach(visit, lo, hi) {
  if(!this.root) {
    return
  }
  switch(arguments.length) {
    case 1:
      return doVisitFull(visit, this.root)
    break

    case 2:
      return doVisitHalf(lo, this._compare, visit, this.root)
    break

    case 3:
      if(this._compare(lo, hi) >= 0) {
        return
      }
      return doVisit(lo, hi, this._compare, visit, this.root)
    break
  }
}

//First item in list
Object.defineProperty(proto, "begin", {
  get: function() {
    var stack = []
    var n = this.root
    while(n) {
      stack.push(n)
      n = n.left
    }
    return new RedBlackTreeIterator(this, stack)
  }
})

//Last item in list
Object.defineProperty(proto, "end", {
  get: function() {
    var stack = []
    var n = this.root
    while(n) {
      stack.push(n)
      n = n.right
    }
    return new RedBlackTreeIterator(this, stack)
  }
})

//Find the ith item in the tree
proto.at = function(idx) {
  if(idx < 0) {
    return new RedBlackTreeIterator(this, [])
  }
  var n = this.root
  var stack = []
  while(true) {
    stack.push(n)
    if(n.left) {
      if(idx < n.left._count) {
        n = n.left
        continue
      }
      idx -= n.left._count
    }
    if(!idx) {
      return new RedBlackTreeIterator(this, stack)
    }
    idx -= 1
    if(n.right) {
      if(idx >= n.right._count) {
        break
      }
      n = n.right
    } else {
      break
    }
  }
  return new RedBlackTreeIterator(this, [])
}

proto.ge = function(key) {
  var cmp = this._compare
  var n = this.root
  var stack = []
  var last_ptr = 0
  while(n) {
    var d = cmp(key, n.key)
    stack.push(n)
    if(d <= 0) {
      last_ptr = stack.length
    }
    if(d <= 0) {
      n = n.left
    } else {
      n = n.right
    }
  }
  stack.length = last_ptr
  return new RedBlackTreeIterator(this, stack)
}

proto.gt = function(key) {
  var cmp = this._compare
  var n = this.root
  var stack = []
  var last_ptr = 0
  while(n) {
    var d = cmp(key, n.key)
    stack.push(n)
    if(d < 0) {
      last_ptr = stack.length
    }
    if(d < 0) {
      n = n.left
    } else {
      n = n.right
    }
  }
  stack.length = last_ptr
  return new RedBlackTreeIterator(this, stack)
}

proto.lt = function(key) {
  var cmp = this._compare
  var n = this.root
  var stack = []
  var last_ptr = 0
  while(n) {
    var d = cmp(key, n.key)
    stack.push(n)
    if(d > 0) {
      last_ptr = stack.length
    }
    if(d <= 0) {
      n = n.left
    } else {
      n = n.right
    }
  }
  stack.length = last_ptr
  return new RedBlackTreeIterator(this, stack)
}

proto.le = function(key) {
  var cmp = this._compare
  var n = this.root
  var stack = []
  var last_ptr = 0
  while(n) {
    var d = cmp(key, n.key)
    stack.push(n)
    if(d >= 0) {
      last_ptr = stack.length
    }
    if(d < 0) {
      n = n.left
    } else {
      n = n.right
    }
  }
  stack.length = last_ptr
  return new RedBlackTreeIterator(this, stack)
}

//Finds the item with key if it exists
proto.find = function(key) {
  var cmp = this._compare
  var n = this.root
  var stack = []
  while(n) {
    var d = cmp(key, n.key)
    stack.push(n)
    if(d === 0) {
      return new RedBlackTreeIterator(this, stack)
    }
    if(d <= 0) {
      n = n.left
    } else {
      n = n.right
    }
  }
  return new RedBlackTreeIterator(this, [])
}

//Removes item with key from tree
proto.remove = function(key) {
  var iter = this.find(key)
  if(iter) {
    return iter.remove()
  }
  return this
}

//Returns the item at `key`
proto.get = function(key) {
  var cmp = this._compare
  var n = this.root
  while(n) {
    var d = cmp(key, n.key)
    if(d === 0) {
      return n.value
    }
    if(d <= 0) {
      n = n.left
    } else {
      n = n.right
    }
  }
  return
}

//Iterator for red black tree
function RedBlackTreeIterator(tree, stack) {
  this.tree = tree
  this._stack = stack
}

var iproto = RedBlackTreeIterator.prototype

//Test if iterator is valid
Object.defineProperty(iproto, "valid", {
  get: function() {
    return this._stack.length > 0
  }
})

//Node of the iterator
Object.defineProperty(iproto, "node", {
  get: function() {
    if(this._stack.length > 0) {
      return this._stack[this._stack.length-1]
    }
    return null
  },
  enumerable: true
})

//Makes a copy of an iterator
iproto.clone = function() {
  return new RedBlackTreeIterator(this.tree, this._stack.slice())
}

//Swaps two nodes
function swapNode(n, v) {
  n.key = v.key
  n.value = v.value
  n.left = v.left
  n.right = v.right
  n._color = v._color
  n._count = v._count
}

//Fix up a double black node in a tree
function fixDoubleBlack(stack) {
  var n, p, s, z
  for(var i=stack.length-1; i>=0; --i) {
    n = stack[i]
    if(i === 0) {
      n._color = BLACK
      return
    }
    //console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key)
    p = stack[i-1]
    if(p.left === n) {
      //console.log("left child")
      s = p.right
      if(s.right && s.right._color === RED) {
        //console.log("case 1: right sibling child red")
        s = p.right = cloneNode(s)
        z = s.right = cloneNode(s.right)
        p.right = s.left
        s.left = p
        s.right = z
        s._color = p._color
        n._color = BLACK
        p._color = BLACK
        z._color = BLACK
        recount(p)
        recount(s)
        if(i > 1) {
          var pp = stack[i-2]
          if(pp.left === p) {
            pp.left = s
          } else {
            pp.right = s
          }
        }
        stack[i-1] = s
        return
      } else if(s.left && s.left._color === RED) {
        //console.log("case 1: left sibling child red")
        s = p.right = cloneNode(s)
        z = s.left = cloneNode(s.left)
        p.right = z.left
        s.left = z.right
        z.left = p
        z.right = s
        z._color = p._color
        p._color = BLACK
        s._color = BLACK
        n._color = BLACK
        recount(p)
        recount(s)
        recount(z)
        if(i > 1) {
          var pp = stack[i-2]
          if(pp.left === p) {
            pp.left = z
          } else {
            pp.right = z
          }
        }
        stack[i-1] = z
        return
      }
      if(s._color === BLACK) {
        if(p._color === RED) {
          //console.log("case 2: black sibling, red parent", p.right.value)
          p._color = BLACK
          p.right = repaint(RED, s)
          return
        } else {
          //console.log("case 2: black sibling, black parent", p.right.value)
          p.right = repaint(RED, s)
          continue  
        }
      } else {
        //console.log("case 3: red sibling")
        s = cloneNode(s)
        p.right = s.left
        s.left = p
        s._color = p._color
        p._color = RED
        recount(p)
        recount(s)
        if(i > 1) {
          var pp = stack[i-2]
          if(pp.left === p) {
            pp.left = s
          } else {
            pp.right = s
          }
        }
        stack[i-1] = s
        stack[i] = p
        if(i+1 < stack.length) {
          stack[i+1] = n
        } else {
          stack.push(n)
        }
        i = i+2
      }
    } else {
      //console.log("right child")
      s = p.left
      if(s.left && s.left._color === RED) {
        //console.log("case 1: left sibling child red", p.value, p._color)
        s = p.left = cloneNode(s)
        z = s.left = cloneNode(s.left)
        p.left = s.right
        s.right = p
        s.left = z
        s._color = p._color
        n._color = BLACK
        p._color = BLACK
        z._color = BLACK
        recount(p)
        recount(s)
        if(i > 1) {
          var pp = stack[i-2]
          if(pp.right === p) {
            pp.right = s
          } else {
            pp.left = s
          }
        }
        stack[i-1] = s
        return
      } else if(s.right && s.right._color === RED) {
        //console.log("case 1: right sibling child red")
        s = p.left = cloneNode(s)
        z = s.right = cloneNode(s.right)
        p.left = z.right
        s.right = z.left
        z.right = p
        z.left = s
        z._color = p._color
        p._color = BLACK
        s._color = BLACK
        n._color = BLACK
        recount(p)
        recount(s)
        recount(z)
        if(i > 1) {
          var pp = stack[i-2]
          if(pp.right === p) {
            pp.right = z
          } else {
            pp.left = z
          }
        }
        stack[i-1] = z
        return
      }
      if(s._color === BLACK) {
        if(p._color === RED) {
          //console.log("case 2: black sibling, red parent")
          p._color = BLACK
          p.left = repaint(RED, s)
          return
        } else {
          //console.log("case 2: black sibling, black parent")
          p.left = repaint(RED, s)
          continue  
        }
      } else {
        //console.log("case 3: red sibling")
        s = cloneNode(s)
        p.left = s.right
        s.right = p
        s._color = p._color
        p._color = RED
        recount(p)
        recount(s)
        if(i > 1) {
          var pp = stack[i-2]
          if(pp.right === p) {
            pp.right = s
          } else {
            pp.left = s
          }
        }
        stack[i-1] = s
        stack[i] = p
        if(i+1 < stack.length) {
          stack[i+1] = n
        } else {
          stack.push(n)
        }
        i = i+2
      }
    }
  }
}

//Removes item at iterator from tree
iproto.remove = function() {
  var stack = this._stack
  if(stack.length === 0) {
    return this.tree
  }
  //First copy path to node
  var cstack = new Array(stack.length)
  var n = stack[stack.length-1]
  cstack[cstack.length-1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count)
  for(var i=stack.length-2; i>=0; --i) {
    var n = stack[i]
    if(n.left === stack[i+1]) {
      cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count)
    } else {
      cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
    }
  }

  //Get node
  n = cstack[cstack.length-1]
  //console.log("start remove: ", n.value)

  //If not leaf, then swap with previous node
  if(n.left && n.right) {
    //console.log("moving to leaf")

    //First walk to previous leaf
    var split = cstack.length
    n = n.left
    while(n.right) {
      cstack.push(n)
      n = n.right
    }
    //Copy path to leaf
    var v = cstack[split-1]
    cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count))
    cstack[split-1].key = n.key
    cstack[split-1].value = n.value

    //Fix up stack
    for(var i=cstack.length-2; i>=split; --i) {
      n = cstack[i]
      cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
    }
    cstack[split-1].left = cstack[split]
  }
  //console.log("stack=", cstack.map(function(v) { return v.value }))

  //Remove leaf node
  n = cstack[cstack.length-1]
  if(n._color === RED) {
    //Easy case: removing red leaf
    //console.log("RED leaf")
    var p = cstack[cstack.length-2]
    if(p.left === n) {
      p.left = null
    } else if(p.right === n) {
      p.right = null
    }
    cstack.pop()
    for(var i=0; i<cstack.length; ++i) {
      cstack[i]._count--
    }
    return new RedBlackTree(this.tree._compare, cstack[0])
  } else {
    if(n.left || n.right) {
      //Second easy case:  Single child black parent
      //console.log("BLACK single child")
      if(n.left) {
        swapNode(n, n.left)
      } else if(n.right) {
        swapNode(n, n.right)
      }
      //Child must be red, so repaint it black to balance color
      n._color = BLACK
      for(var i=0; i<cstack.length-1; ++i) {
        cstack[i]._count--
      }
      return new RedBlackTree(this.tree._compare, cstack[0])
    } else if(cstack.length === 1) {
      //Third easy case: root
      //console.log("ROOT")
      return new RedBlackTree(this.tree._compare, null)
    } else {
      //Hard case: Repaint n, and then do some nasty stuff
      //console.log("BLACK leaf no children")
      for(var i=0; i<cstack.length; ++i) {
        cstack[i]._count--
      }
      var parent = cstack[cstack.length-2]
      fixDoubleBlack(cstack)
      //Fix up links
      if(parent.left === n) {
        parent.left = null
      } else {
        parent.right = null
      }
    }
  }
  return new RedBlackTree(this.tree._compare, cstack[0])
}

//Returns key
Object.defineProperty(iproto, "key", {
  get: function() {
    if(this._stack.length > 0) {
      return this._stack[this._stack.length-1].key
    }
    return
  },
  enumerable: true
})

//Returns value
Object.defineProperty(iproto, "value", {
  get: function() {
    if(this._stack.length > 0) {
      return this._stack[this._stack.length-1].value
    }
    return
  },
  enumerable: true
})


//Returns the position of this iterator in the sorted list
Object.defineProperty(iproto, "index", {
  get: function() {
    var idx = 0
    var stack = this._stack
    if(stack.length === 0) {
      var r = this.tree.root
      if(r) {
        return r._count
      }
      return 0
    } else if(stack[stack.length-1].left) {
      idx = stack[stack.length-1].left._count
    }
    for(var s=stack.length-2; s>=0; --s) {
      if(stack[s+1] === stack[s].right) {
        ++idx
        if(stack[s].left) {
          idx += stack[s].left._count
        }
      }
    }
    return idx
  },
  enumerable: true
})

//Advances iterator to next element in list
iproto.next = function() {
  var stack = this._stack
  if(stack.length === 0) {
    return
  }
  var n = stack[stack.length-1]
  if(n.right) {
    n = n.right
    while(n) {
      stack.push(n)
      n = n.left
    }
  } else {
    stack.pop()
    while(stack.length > 0 && stack[stack.length-1].right === n) {
      n = stack[stack.length-1]
      stack.pop()
    }
  }
}

//Checks if iterator is at end of tree
Object.defineProperty(iproto, "hasNext", {
  get: function() {
    var stack = this._stack
    if(stack.length === 0) {
      return false
    }
    if(stack[stack.length-1].right) {
      return true
    }
    for(var s=stack.length-1; s>0; --s) {
      if(stack[s-1].left === stack[s]) {
        return true
      }
    }
    return false
  }
})

//Update value
iproto.update = function(value) {
  var stack = this._stack
  if(stack.length === 0) {
    throw new Error("Can't update empty node!")
  }
  var cstack = new Array(stack.length)
  var n = stack[stack.length-1]
  cstack[cstack.length-1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count)
  for(var i=stack.length-2; i>=0; --i) {
    n = stack[i]
    if(n.left === stack[i+1]) {
      cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count)
    } else {
      cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
    }
  }
  return new RedBlackTree(this.tree._compare, cstack[0])
}

//Moves iterator backward one element
iproto.prev = function() {
  var stack = this._stack
  if(stack.length === 0) {
    return
  }
  var n = stack[stack.length-1]
  if(n.left) {
    n = n.left
    while(n) {
      stack.push(n)
      n = n.right
    }
  } else {
    stack.pop()
    while(stack.length > 0 && stack[stack.length-1].left === n) {
      n = stack[stack.length-1]
      stack.pop()
    }
  }
}

//Checks if iterator is at start of tree
Object.defineProperty(iproto, "hasPrev", {
  get: function() {
    var stack = this._stack
    if(stack.length === 0) {
      return false
    }
    if(stack[stack.length-1].left) {
      return true
    }
    for(var s=stack.length-1; s>0; --s) {
      if(stack[s-1].right === stack[s]) {
        return true
      }
    }
    return false
  }
})

//Default comparison function
function defaultCompare(a, b) {
  if(a < b) {
    return -1
  }
  if(a > b) {
    return 1
  }
  return 0
}

//Build a tree
function createRBTree(compare) {
  return new RedBlackTree(compare || defaultCompare, null)
}
},{}],224:[function(_dereq_,module,exports){
// transliterated from the python snippet here:
// http://en.wikipedia.org/wiki/Lanczos_approximation

var g = 7;
var p = [
    0.99999999999980993,
    676.5203681218851,
    -1259.1392167224028,
    771.32342877765313,
    -176.61502916214059,
    12.507343278686905,
    -0.13857109526572012,
    9.9843695780195716e-6,
    1.5056327351493116e-7
];

var g_ln = 607/128;
var p_ln = [
    0.99999999999999709182,
    57.156235665862923517,
    -59.597960355475491248,
    14.136097974741747174,
    -0.49191381609762019978,
    0.33994649984811888699e-4,
    0.46523628927048575665e-4,
    -0.98374475304879564677e-4,
    0.15808870322491248884e-3,
    -0.21026444172410488319e-3,
    0.21743961811521264320e-3,
    -0.16431810653676389022e-3,
    0.84418223983852743293e-4,
    -0.26190838401581408670e-4,
    0.36899182659531622704e-5
];

// Spouge approximation (suitable for large arguments)
function lngamma(z) {

    if(z < 0) return Number('0/0');
    var x = p_ln[0];
    for(var i = p_ln.length - 1; i > 0; --i) x += p_ln[i] / (z + i);
    var t = z + g_ln + 0.5;
    return .5*Math.log(2*Math.PI)+(z+.5)*Math.log(t)-t+Math.log(x)-Math.log(z);
}

module.exports = function gamma (z) {
    if (z < 0.5) {
        return Math.PI / (Math.sin(Math.PI * z) * gamma(1 - z));
    }
    else if(z > 100) return Math.exp(lngamma(z));
    else {
        z -= 1;
        var x = p[0];
        for (var i = 1; i < g + 2; i++) {
            x += p[i] / (z + i);
        }
        var t = z + g + 0.5;

        return Math.sqrt(2 * Math.PI)
            * Math.pow(t, z + 0.5)
            * Math.exp(-t)
            * x
        ;
    }
};

module.exports.log = lngamma;

},{}],225:[function(_dereq_,module,exports){
module.exports = getCanvasContext
function getCanvasContext (type, opts) {
  if (typeof type !== 'string') {
    throw new TypeError('must specify type string')
  }

  opts = opts || {}

  if (typeof document === 'undefined' && !opts.canvas) {
    return null // check for Node
  }

  var canvas = opts.canvas || document.createElement('canvas')
  if (typeof opts.width === 'number') {
    canvas.width = opts.width
  }
  if (typeof opts.height === 'number') {
    canvas.height = opts.height
  }

  var attribs = opts
  var gl
  try {
    var names = [ type ]
    // prefix GL contexts
    if (type.indexOf('webgl') === 0) {
      names.push('experimental-' + type)
    }

    for (var i = 0; i < names.length; i++) {
      gl = canvas.getContext(names[i], attribs)
      if (gl) return gl
    }
  } catch (e) {
    gl = null
  }
  return (gl || null) // ensure null on fail
}

},{}],226:[function(_dereq_,module,exports){
'use strict'

module.exports = createAxes

var createText        = _dereq_('./lib/text.js')
var createLines       = _dereq_('./lib/lines.js')
var createBackground  = _dereq_('./lib/background.js')
var getCubeProperties = _dereq_('./lib/cube.js')
var Ticks             = _dereq_('./lib/ticks.js')

var identity = new Float32Array([
  1, 0, 0, 0,
  0, 1, 0, 0,
  0, 0, 1, 0,
  0, 0, 0, 1])

function copyVec3(a, b) {
  a[0] = b[0]
  a[1] = b[1]
  a[2] = b[2]
  return a
}

function Axes(gl) {
  this.gl             = gl

  this.pixelRatio     = 1

  this.bounds         = [ [-10, -10, -10],
                          [ 10,  10,  10] ]
  this.ticks          = [ [], [], [] ]
  this.autoTicks      = true
  this.tickSpacing    = [ 1, 1, 1 ]

  this.tickEnable     = [ true, true, true ]
  this.tickFont       = [ 'sans-serif', 'sans-serif', 'sans-serif' ]
  this.tickSize       = [ 12, 12, 12 ]
  this.tickAngle      = [ 0, 0, 0 ]
  this.tickAlign      = [ 'auto', 'auto', 'auto' ]
  this.tickColor      = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ]
  this.tickPad        = [ 10, 10, 10 ]

  this.lastCubeProps  = {
    cubeEdges: [0,0,0],
    axis:      [0,0,0]
  }

  this.labels         = [ 'x', 'y', 'z' ]
  this.labelEnable    = [ true, true, true ]
  this.labelFont      = 'sans-serif'
  this.labelSize      = [ 20, 20, 20 ]
  this.labelAngle     = [ 0, 0, 0 ]
  this.labelAlign     = [ 'auto', 'auto', 'auto' ]
  this.labelColor     = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ]
  this.labelPad       = [ 10, 10, 10 ]

  this.lineEnable     = [ true, true, true ]
  this.lineMirror     = [ false, false, false ]
  this.lineWidth      = [ 1, 1, 1 ]
  this.lineColor      = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ]

  this.lineTickEnable = [ true, true, true ]
  this.lineTickMirror = [ false, false, false ]
  this.lineTickLength = [ 0, 0, 0 ]
  this.lineTickWidth  = [ 1, 1, 1 ]
  this.lineTickColor  = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ]

  this.gridEnable     = [ true, true, true ]
  this.gridWidth      = [ 1, 1, 1 ]
  this.gridColor      = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ]

  this.zeroEnable     = [ true, true, true ]
  this.zeroLineColor  = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ]
  this.zeroLineWidth  = [ 2, 2, 2 ]

  this.backgroundEnable = [ false, false, false ]
  this.backgroundColor  = [ [0.8, 0.8, 0.8, 0.5],
                            [0.8, 0.8, 0.8, 0.5],
                            [0.8, 0.8, 0.8, 0.5] ]

  this._firstInit = true
  this._text  = null
  this._lines = null
  this._background = createBackground(gl)
}

var proto = Axes.prototype

proto.update = function(options) {
  options = options || {}

  //Option parsing helper functions
  function parseOption(nest, cons, name) {
    if(name in options) {
      var opt = options[name]
      var prev = this[name]
      var next
      if(nest ? (Array.isArray(opt) && Array.isArray(opt[0])) :
                 Array.isArray(opt) ) {
        this[name] = next = [ cons(opt[0]), cons(opt[1]), cons(opt[2]) ]
      } else {
        this[name] = next = [ cons(opt), cons(opt), cons(opt) ]
      }
      for(var i=0; i<3; ++i) {
        if(next[i] !== prev[i]) {
          return true
        }
      }
    }
    return false
  }

  var NUMBER  = parseOption.bind(this, false, Number)
  var BOOLEAN = parseOption.bind(this, false, Boolean)
  var STRING  = parseOption.bind(this, false, String)
  var COLOR   = parseOption.bind(this, true, function(v) {
    if(Array.isArray(v)) {
      if(v.length === 3) {
        return [ +v[0], +v[1], +v[2], 1.0 ]
      } else if(v.length === 4) {
        return [ +v[0], +v[1], +v[2], +v[3] ]
      }
    }
    return [ 0, 0, 0, 1 ]
  })

  //Tick marks and bounds
  var nextTicks
  var ticksUpdate   = false
  var boundsChanged = false
  if('bounds' in options) {
    var bounds = options.bounds
i_loop:
    for(var i=0; i<2; ++i) {
      for(var j=0; j<3; ++j) {
        if(bounds[i][j] !== this.bounds[i][j]) {
          boundsChanged = true
        }
        this.bounds[i][j] = bounds[i][j]
      }
    }
  }
  if('ticks' in options) {
    nextTicks      = options.ticks
    ticksUpdate    = true
    this.autoTicks = false
    for(var i=0; i<3; ++i) {
      this.tickSpacing[i] = 0.0
    }
  } else if(NUMBER('tickSpacing')) {
    this.autoTicks  = true
    boundsChanged   = true
  }

  if(this._firstInit) {
    if(!('ticks' in options || 'tickSpacing' in options)) {
      this.autoTicks = true
    }

    //Force tick recomputation on first update
    boundsChanged   = true
    ticksUpdate     = true
    this._firstInit = false
  }

  if(boundsChanged && this.autoTicks) {
    nextTicks = Ticks.create(this.bounds, this.tickSpacing)
    ticksUpdate = true
  }

  //Compare next ticks to previous ticks, only update if needed
  if(ticksUpdate) {
    for(var i=0; i<3; ++i) {
      nextTicks[i].sort(function(a,b) {
        return a.x-b.x
      })
    }
    if(Ticks.equal(nextTicks, this.ticks)) {
      ticksUpdate = false
    } else {
      this.ticks = nextTicks
    }
  }

  //Parse tick properties
  BOOLEAN('tickEnable')
  if(STRING('tickFont')) {
    ticksUpdate = true  //If font changes, must rebuild vbo
  }
  NUMBER('tickSize')
  NUMBER('tickAngle')
  NUMBER('tickPad')
  COLOR('tickColor')

  //Axis labels
  var labelUpdate = STRING('labels')
  if(STRING('labelFont')) {
    labelUpdate = true
  }
  BOOLEAN('labelEnable')
  NUMBER('labelSize')
  NUMBER('labelPad')
  COLOR('labelColor')

  //Axis lines
  BOOLEAN('lineEnable')
  BOOLEAN('lineMirror')
  NUMBER('lineWidth')
  COLOR('lineColor')

  //Axis line ticks
  BOOLEAN('lineTickEnable')
  BOOLEAN('lineTickMirror')
  NUMBER('lineTickLength')
  NUMBER('lineTickWidth')
  COLOR('lineTickColor')

  //Grid lines
  BOOLEAN('gridEnable')
  NUMBER('gridWidth')
  COLOR('gridColor')

  //Zero line
  BOOLEAN('zeroEnable')
  COLOR('zeroLineColor')
  NUMBER('zeroLineWidth')

  //Background
  BOOLEAN('backgroundEnable')
  COLOR('backgroundColor')

  //Update text if necessary
  if(!this._text) {
    this._text = createText(
      this.gl,
      this.bounds,
      this.labels,
      this.labelFont,
      this.ticks,
      this.tickFont)
  } else if(this._text && (labelUpdate || ticksUpdate)) {
    this._text.update(
      this.bounds,
      this.labels,
      this.labelFont,
      this.ticks,
      this.tickFont)
  }

  //Update lines if necessary
  if(this._lines && ticksUpdate) {
    this._lines.dispose()
    this._lines = null
  }
  if(!this._lines) {
    this._lines = createLines(this.gl, this.bounds, this.ticks)
  }
}

function OffsetInfo() {
  this.primalOffset = [0,0,0]
  this.primalMinor  = [0,0,0]
  this.mirrorOffset = [0,0,0]
  this.mirrorMinor  = [0,0,0]
}

var LINE_OFFSET = [ new OffsetInfo(), new OffsetInfo(), new OffsetInfo() ]

function computeLineOffset(result, i, bounds, cubeEdges, cubeAxis) {
  var primalOffset = result.primalOffset
  var primalMinor  = result.primalMinor
  var dualOffset   = result.mirrorOffset
  var dualMinor    = result.mirrorMinor
  var e = cubeEdges[i]

  //Calculate offsets
  for(var j=0; j<3; ++j) {
    if(i === j) {
      continue
    }
    var a = primalOffset,
        b = dualOffset,
        c = primalMinor,
        d = dualMinor
    if(e & (1<<j)) {
      a = dualOffset
      b = primalOffset
      c = dualMinor
      d = primalMinor
    }
    a[j] = bounds[0][j]
    b[j] = bounds[1][j]
    if(cubeAxis[j] > 0) {
      c[j] = -1
      d[j] = 0
    } else {
      c[j] = 0
      d[j] = +1
    }
  }
}

var CUBE_ENABLE = [0,0,0]
var DEFAULT_PARAMS = {
  model:      identity,
  view:       identity,
  projection: identity,
  _ortho:      false
}

proto.isOpaque = function() {
  return true
}

proto.isTransparent = function() {
  return false
}

proto.drawTransparent = function(params) {}

var ALIGN_OPTION_AUTO = 0 // i.e. as defined in the shader the text would rotate to stay upwards range: [-90,90]

var PRIMAL_MINOR  = [0,0,0]
var MIRROR_MINOR  = [0,0,0]
var PRIMAL_OFFSET = [0,0,0]

proto.draw = function(params) {
  params = params || DEFAULT_PARAMS

  var gl = this.gl

  //Geometry for camera and axes
  var model       = params.model || identity
  var view        = params.view || identity
  var projection  = params.projection || identity
  var bounds      = this.bounds
  var isOrtho     = params._ortho || false

  //Unpack axis info
  var cubeParams  = getCubeProperties(model, view, projection, bounds, isOrtho)
  var cubeEdges   = cubeParams.cubeEdges
  var cubeAxis    = cubeParams.axis

  var cx = view[12]
  var cy = view[13]
  var cz = view[14]
  var cw = view[15]

  var orthoFix = (isOrtho) ? 2 : 1 // double up padding for orthographic ticks & labels
  var pixelScaleF = orthoFix * this.pixelRatio * (projection[3]*cx + projection[7]*cy + projection[11]*cz + projection[15]*cw) / gl.drawingBufferHeight

  for(var i=0; i<3; ++i) {
    this.lastCubeProps.cubeEdges[i] = cubeEdges[i]
    this.lastCubeProps.axis[i] = cubeAxis[i]
  }

  //Compute axis info
  var lineOffset  = LINE_OFFSET
  for(var i=0; i<3; ++i) {
    computeLineOffset(
      LINE_OFFSET[i],
      i,
      this.bounds,
      cubeEdges,
      cubeAxis)
  }

  //Set up state parameters
  var gl = this.gl

  //Draw background first
  var cubeEnable = CUBE_ENABLE
  for(var i=0; i<3; ++i) {
    if(this.backgroundEnable[i]) {
      cubeEnable[i] = cubeAxis[i]
    } else {
      cubeEnable[i] = 0
    }
  }

  this._background.draw(
    model,
    view,
    projection,
    bounds,
    cubeEnable,
    this.backgroundColor)

  //Draw lines
  this._lines.bind(
    model,
    view,
    projection,
    this)

  //First draw grid lines and zero lines
  for(var i=0; i<3; ++i) {
    var x = [0,0,0]
    if(cubeAxis[i] > 0) {
      x[i] = bounds[1][i]
    } else {
      x[i] = bounds[0][i]
    }

    //Draw grid lines
    for(var j=0; j<2; ++j) {
      var u = (i + 1 + j) % 3
      var v = (i + 1 + (j^1)) % 3
      if(this.gridEnable[u]) {
        this._lines.drawGrid(u, v, this.bounds, x, this.gridColor[u], this.gridWidth[u]*this.pixelRatio)
      }
    }

    //Draw zero lines (need to do this AFTER all grid lines are drawn)
    for(var j=0; j<2; ++j) {
      var u = (i + 1 + j) % 3
      var v = (i + 1 + (j^1)) % 3
      if(this.zeroEnable[v]) {
        //Check if zero line in bounds
        if(Math.min(bounds[0][v], bounds[1][v]) <= 0 && Math.max(bounds[0][v], bounds[1][v]) >= 0) {
          this._lines.drawZero(u, v, this.bounds, x, this.zeroLineColor[v], this.zeroLineWidth[v]*this.pixelRatio)
        }
      }
    }
  }

  //Then draw axis lines and tick marks
  for(var i=0; i<3; ++i) {

    //Draw axis lines
    if(this.lineEnable[i]) {
      this._lines.drawAxisLine(i, this.bounds, lineOffset[i].primalOffset, this.lineColor[i], this.lineWidth[i]*this.pixelRatio)
    }
    if(this.lineMirror[i]) {
      this._lines.drawAxisLine(i, this.bounds, lineOffset[i].mirrorOffset, this.lineColor[i], this.lineWidth[i]*this.pixelRatio)
    }

    //Compute minor axes
    var primalMinor = copyVec3(PRIMAL_MINOR, lineOffset[i].primalMinor)
    var mirrorMinor = copyVec3(MIRROR_MINOR, lineOffset[i].mirrorMinor)
    var tickLength  = this.lineTickLength
    for(var j=0; j<3; ++j) {
      var scaleFactor = pixelScaleF / model[5*j]
      primalMinor[j] *= tickLength[j] * scaleFactor
      mirrorMinor[j] *= tickLength[j] * scaleFactor
    }



    //Draw axis line ticks
    if(this.lineTickEnable[i]) {
      this._lines.drawAxisTicks(i, lineOffset[i].primalOffset, primalMinor, this.lineTickColor[i], this.lineTickWidth[i]*this.pixelRatio)
    }
    if(this.lineTickMirror[i]) {
      this._lines.drawAxisTicks(i, lineOffset[i].mirrorOffset, mirrorMinor, this.lineTickColor[i], this.lineTickWidth[i]*this.pixelRatio)
    }
  }
  this._lines.unbind()

  //Draw text sprites
  this._text.bind(
    model,
    view,
    projection,
    this.pixelRatio)

  var alignOpt // options in shader are from this list {-1, 0, 1, 2, 3, ..., n}
  // -1: backward compatible
  //  0: raw data
  //  1: auto align, free angles
  //  2: auto align, horizontal or vertical
  //3-n: auto align, round to n directions e.g. 12 -> round to angles with 30-degree steps

  var hv_ratio = 0.5 // can have an effect on the ratio between horizontals and verticals when using option 2

  var enableAlign
  var alignDir

  function alignTo(i) {
    alignDir = [0,0,0]
    alignDir[i] = 1
  }

  function solveTickAlignments(i, minor, major) {

    var i1 = (i + 1) % 3
    var i2 = (i + 2) % 3

    var A = minor[i1]
    var B = minor[i2]
    var C = major[i1]
    var D = major[i2]

         if ((A > 0) && (D > 0)) { alignTo(i1); return; }
    else if ((A > 0) && (D < 0)) { alignTo(i1); return; }
    else if ((A < 0) && (D > 0)) { alignTo(i1); return; }
    else if ((A < 0) && (D < 0)) { alignTo(i1); return; }
    else if ((B > 0) && (C > 0)) { alignTo(i2); return; }
    else if ((B > 0) && (C < 0)) { alignTo(i2); return; }
    else if ((B < 0) && (C > 0)) { alignTo(i2); return; }
    else if ((B < 0) && (C < 0)) { alignTo(i2); return; }
  }

  for(var i=0; i<3; ++i) {

    var minor      = lineOffset[i].primalMinor
    var major      = lineOffset[i].mirrorMinor

    var offset     = copyVec3(PRIMAL_OFFSET, lineOffset[i].primalOffset)

    for(var j=0; j<3; ++j) {
      if(this.lineTickEnable[i]) {
        offset[j] += pixelScaleF * minor[j] * Math.max(this.lineTickLength[j], 0)  / model[5*j]
      }
    }

    var axis = [0,0,0]
    axis[i] = 1

    //Draw tick text
    if(this.tickEnable[i]) {

      if(this.tickAngle[i] === -3600) {
        this.tickAngle[i] = 0
        this.tickAlign[i] = 'auto'
      } else {
        this.tickAlign[i] = -1
      }

      enableAlign = 1;

      alignOpt = [this.tickAlign[i], hv_ratio, enableAlign]
      if(alignOpt[0] === 'auto') alignOpt[0] = ALIGN_OPTION_AUTO
      else alignOpt[0] = parseInt('' + alignOpt[0])

      alignDir = [0,0,0]
      solveTickAlignments(i, minor, major)

      //Add tick padding
      for(var j=0; j<3; ++j) {
        offset[j] += pixelScaleF * minor[j] * this.tickPad[j] / model[5*j]
      }

      //Draw axis
      this._text.drawTicks(
        i,
        this.tickSize[i],
        this.tickAngle[i],
        offset,
        this.tickColor[i],
        axis,
        alignDir,
        alignOpt)
    }

    //Draw labels
    if(this.labelEnable[i]) {

      enableAlign = 0
      alignDir = [0,0,0]
      if(this.labels[i].length > 4) { // for large label axis enable alignDir to axis
        alignTo(i)
        enableAlign = 1
      }

      alignOpt = [this.labelAlign[i], hv_ratio, enableAlign]
      if(alignOpt[0] === 'auto') alignOpt[0] = ALIGN_OPTION_AUTO
      else alignOpt[0] = parseInt('' + alignOpt[0])

      //Add label padding
      for(var j=0; j<3; ++j) {
        offset[j] += pixelScaleF * minor[j] * this.labelPad[j] / model[5*j]
      }
      offset[i] += 0.5 * (bounds[0][i] + bounds[1][i])

      //Draw axis
      this._text.drawLabel(
        i,
        this.labelSize[i],
        this.labelAngle[i],
        offset,
        this.labelColor[i],
        [0,0,0],
        alignDir,
        alignOpt)
    }
  }

  this._text.unbind()
}

proto.dispose = function() {
  this._text.dispose()
  this._lines.dispose()
  this._background.dispose()
  this._lines = null
  this._text = null
  this._background = null
  this.gl = null
}

function createAxes(gl, options) {
  var axes = new Axes(gl)
  axes.update(options)
  return axes
}

},{"./lib/background.js":227,"./lib/cube.js":228,"./lib/lines.js":229,"./lib/text.js":231,"./lib/ticks.js":232}],227:[function(_dereq_,module,exports){
'use strict'

module.exports = createBackgroundCube

var createBuffer = _dereq_('gl-buffer')
var createVAO    = _dereq_('gl-vao')
var createShader = _dereq_('./shaders').bg

function BackgroundCube(gl, buffer, vao, shader) {
  this.gl = gl
  this.buffer = buffer
  this.vao = vao
  this.shader = shader
}

var proto = BackgroundCube.prototype

proto.draw = function(model, view, projection, bounds, enable, colors) {
  var needsBG = false
  for(var i=0; i<3; ++i) {
    needsBG = needsBG || enable[i]
  }
  if(!needsBG) {
    return
  }

  var gl = this.gl

  gl.enable(gl.POLYGON_OFFSET_FILL)
  gl.polygonOffset(1, 2)

  this.shader.bind()
  this.shader.uniforms = {
    model: model,
    view: view,
    projection: projection,
    bounds: bounds,
    enable: enable,
    colors: colors
  }
  this.vao.bind()
  this.vao.draw(this.gl.TRIANGLES, 36)
  this.vao.unbind()

  gl.disable(gl.POLYGON_OFFSET_FILL)
}

proto.dispose = function() {
  this.vao.dispose()
  this.buffer.dispose()
  this.shader.dispose()
}

function createBackgroundCube(gl) {
  //Create cube vertices
  var vertices = []
  var indices  = []
  var ptr = 0
  for(var d=0; d<3; ++d) {
    var u = (d+1) % 3
    var v = (d+2) % 3
    var x = [0,0,0]
    var c = [0,0,0]
    for(var s=-1; s<=1; s+=2) {
      indices.push(ptr,   ptr+2, ptr+1,
                   ptr+1, ptr+2, ptr+3)
      x[d] = s
      c[d] = s
      for(var i=-1; i<=1; i+=2) {
        x[u] = i
        for(var j=-1; j<=1; j+=2) {
          x[v] = j
          vertices.push(x[0], x[1], x[2],
                        c[0], c[1], c[2])
          ptr += 1
        }
      }
      //Swap u and v
      var tt = u
      u = v
      v = tt
    }
  }

  //Allocate buffer and vertex array
  var buffer = createBuffer(gl, new Float32Array(vertices))
  var elements = createBuffer(gl, new Uint16Array(indices), gl.ELEMENT_ARRAY_BUFFER)
  var vao = createVAO(gl, [
      {
        buffer: buffer,
        type: gl.FLOAT,
        size: 3,
        offset: 0,
        stride: 24
      },
      {
        buffer: buffer,
        type: gl.FLOAT,
        size: 3,
        offset: 12,
        stride: 24
      }
    ], elements)

  //Create shader object
  var shader = createShader(gl)
  shader.attributes.position.location = 0
  shader.attributes.normal.location = 1

  return new BackgroundCube(gl, buffer, vao, shader)
}

},{"./shaders":230,"gl-buffer":234,"gl-vao":316}],228:[function(_dereq_,module,exports){
"use strict"

module.exports = getCubeEdges

var bits      = _dereq_('bit-twiddle')
var multiply  = _dereq_('gl-mat4/multiply')
var splitPoly = _dereq_('split-polygon')
var orient    = _dereq_('robust-orientation')

var mvp        = new Array(16)
var pCubeVerts = new Array(8)
var cubeVerts  = new Array(8)
var x          = new Array(3)
var zero3      = [0,0,0]

;(function() {
  for(var i=0; i<8; ++i) {
    pCubeVerts[i] =[1,1,1,1]
    cubeVerts[i] = [1,1,1]
  }
})()


function transformHg(result, x, mat) {
  for(var i=0; i<4; ++i) {
    result[i] = mat[12+i]
    for(var j=0; j<3; ++j) {
      result[i] += x[j]*mat[4*j+i]
    }
  }
}

var FRUSTUM_PLANES = [
  [ 0, 0, 1, 0, 0],
  [ 0, 0,-1, 1, 0],
  [ 0,-1, 0, 1, 0],
  [ 0, 1, 0, 1, 0],
  [-1, 0, 0, 1, 0],
  [ 1, 0, 0, 1, 0]
]

function polygonArea(p) {
  for(var i=0; i<FRUSTUM_PLANES.length; ++i) {
    p = splitPoly.positive(p, FRUSTUM_PLANES[i])
    if(p.length < 3) {
      return 0
    }
  }

  var base = p[0]
  var ax = base[0] / base[3]
  var ay = base[1] / base[3]
  var area = 0.0
  for(var i=1; i+1<p.length; ++i) {
    var b = p[i]
    var c = p[i+1]

    var bx = b[0]/b[3]
    var by = b[1]/b[3]
    var cx = c[0]/c[3]
    var cy = c[1]/c[3]

    var ux = bx - ax
    var uy = by - ay

    var vx = cx - ax
    var vy = cy - ay

    area += Math.abs(ux * vy - uy * vx)
  }

  return area
}

var CUBE_EDGES = [1,1,1]
var CUBE_AXIS  = [0,0,0]
var CUBE_RESULT = {
  cubeEdges: CUBE_EDGES,
  axis: CUBE_AXIS
}

function getCubeEdges(model, view, projection, bounds, ortho) {

  //Concatenate matrices
  multiply(mvp, view, model)
  multiply(mvp, projection, mvp)

  //First project cube vertices
  var ptr = 0
  for(var i=0; i<2; ++i) {
    x[2] = bounds[i][2]
    for(var j=0; j<2; ++j) {
      x[1] = bounds[j][1]
      for(var k=0; k<2; ++k) {
        x[0] = bounds[k][0]
        transformHg(pCubeVerts[ptr], x, mvp)
        ptr += 1
      }
    }
  }

  //Classify camera against cube faces
  var closest = -1

  for(var i=0; i<8; ++i) {
    var w = pCubeVerts[i][3]
    for(var l=0; l<3; ++l) {
      cubeVerts[i][l] = pCubeVerts[i][l] / w
    }

    if(ortho) cubeVerts[i][2] *= -1;

    if(w < 0) {
      if(closest < 0) {
        closest = i
      } else if(cubeVerts[i][2] < cubeVerts[closest][2]) {
        closest = i
      }
    }
  }

  if(closest < 0) {
    closest = 0
    for(var d=0; d<3; ++d) {
      var u = (d+2) % 3
      var v = (d+1) % 3
      var o0 = -1
      var o1 = -1
      for(var s=0; s<2; ++s) {
        var f0 = (s<<d)
        var f1 = f0 + (s << u) + ((1-s) << v)
        var f2 = f0 + ((1-s) << u) + (s << v)
        if(orient(cubeVerts[f0], cubeVerts[f1], cubeVerts[f2], zero3) < 0) {
          continue
        }
        if(s) {
          o0 = 1
        } else {
          o1 = 1
        }
      }
      if(o0 < 0 || o1 < 0) {
        if(o1 > o0) {
          closest |= 1<<d
        }
        continue
      }
      for(var s=0; s<2; ++s) {
        var f0 = (s<<d)
        var f1 = f0 + (s << u) + ((1-s) << v)
        var f2 = f0 + ((1-s) << u) + (s << v)
        var o = polygonArea([
            pCubeVerts[f0],
            pCubeVerts[f1],
            pCubeVerts[f2],
            pCubeVerts[f0+(1<<u)+(1<<v)]])
        if(s) {
          o0 = o
        } else {
          o1 = o
        }
      }
      if(o1 > o0) {
        closest |= 1<<d
        continue
      }
    }
  }

  var farthest = 7^closest

  //Find lowest vertex which is not closest closest
  var bottom = -1
  for(var i=0; i<8; ++i) {
    if(i === closest || i === farthest) {
      continue
    }
    if(bottom < 0) {
      bottom = i
    } else if(cubeVerts[bottom][1] > cubeVerts[i][1]) {
      bottom = i
    }
  }

  //Find left/right neighbors of bottom vertex
  var left = -1
  for(var i=0; i<3; ++i) {
    var idx = bottom ^ (1<<i)
    if(idx === closest || idx === farthest) {
      continue
    }
    if(left < 0) {
      left = idx
    }
    var v = cubeVerts[idx]
    if(v[0] < cubeVerts[left][0]) {
      left = idx
    }
  }
  var right = -1
  for(var i=0; i<3; ++i) {
    var idx = bottom ^ (1<<i)
    if(idx === closest || idx === farthest || idx === left) {
      continue
    }
    if(right < 0) {
      right = idx
    }
    var v = cubeVerts[idx]
    if(v[0] > cubeVerts[right][0]) {
      right = idx
    }
  }

  //Determine edge axis coordinates
  var cubeEdges = CUBE_EDGES
  cubeEdges[0] = cubeEdges[1] = cubeEdges[2] = 0
  cubeEdges[bits.log2(left^bottom)] = bottom&left
  cubeEdges[bits.log2(bottom^right)] = bottom&right
  var top = right ^ 7
  if(top === closest || top === farthest) {
    top = left ^ 7
    cubeEdges[bits.log2(right^top)] = top&right
  } else {
    cubeEdges[bits.log2(left^top)] = top&left
  }

  //Determine visible faces
  var axis = CUBE_AXIS
  var cutCorner = closest
  for(var d=0; d<3; ++d) {
    if(cutCorner & (1<<d)) {
      axis[d] = -1
    } else {
      axis[d] = 1
    }
  }

  //Return result
  return CUBE_RESULT
}
},{"bit-twiddle":80,"gl-mat4/multiply":260,"robust-orientation":491,"split-polygon":508}],229:[function(_dereq_,module,exports){
'use strict'

module.exports    = createLines

var createBuffer  = _dereq_('gl-buffer')
var createVAO     = _dereq_('gl-vao')
var createShader  = _dereq_('./shaders').line

var MAJOR_AXIS = [0,0,0]
var MINOR_AXIS = [0,0,0]
var SCREEN_AXIS = [0,0,0]
var OFFSET_VEC = [0,0,0]
var SHAPE = [1,1]

function zeroVec(a) {
  a[0] = a[1] = a[2] = 0
  return a
}

function copyVec(a,b) {
  a[0] = b[0]
  a[1] = b[1]
  a[2] = b[2]
  return a
}

function Lines(gl, vertBuffer, vao, shader, tickCount, tickOffset, gridCount, gridOffset) {
  this.gl         = gl
  this.vertBuffer = vertBuffer
  this.vao        = vao
  this.shader     = shader
  this.tickCount  = tickCount
  this.tickOffset = tickOffset
  this.gridCount  = gridCount
  this.gridOffset = gridOffset
}

var proto = Lines.prototype

proto.bind = function(model, view, projection) {
  this.shader.bind()
  this.shader.uniforms.model = model
  this.shader.uniforms.view = view
  this.shader.uniforms.projection = projection

  SHAPE[0] = this.gl.drawingBufferWidth
  SHAPE[1] = this.gl.drawingBufferHeight

  this.shader.uniforms.screenShape = SHAPE
  this.vao.bind()
}

proto.unbind = function() {
  this.vao.unbind()
}

proto.drawAxisLine = function(j, bounds, offset, color, lineWidth) {
  var minorAxis = zeroVec(MINOR_AXIS)
  this.shader.uniforms.majorAxis = MINOR_AXIS

  minorAxis[j] = bounds[1][j] - bounds[0][j]
  this.shader.uniforms.minorAxis = minorAxis

  var noffset = copyVec(OFFSET_VEC, offset)
  noffset[j] += bounds[0][j]
  this.shader.uniforms.offset = noffset

  this.shader.uniforms.lineWidth = lineWidth

  this.shader.uniforms.color = color

  var screenAxis = zeroVec(SCREEN_AXIS)
  screenAxis[(j+2)%3] = 1
  this.shader.uniforms.screenAxis = screenAxis
  this.vao.draw(this.gl.TRIANGLES, 6)

  var screenAxis = zeroVec(SCREEN_AXIS)
  screenAxis[(j+1)%3] = 1
  this.shader.uniforms.screenAxis = screenAxis
  this.vao.draw(this.gl.TRIANGLES, 6)
}

proto.drawAxisTicks = function(j, offset, minorAxis, color, lineWidth) {
  if(!this.tickCount[j]) {
    return
  }

  var majorAxis = zeroVec(MAJOR_AXIS)
  majorAxis[j]  = 1
  this.shader.uniforms.majorAxis = majorAxis
  this.shader.uniforms.offset    = offset
  this.shader.uniforms.minorAxis = minorAxis
  this.shader.uniforms.color     = color
  this.shader.uniforms.lineWidth = lineWidth

  var screenAxis = zeroVec(SCREEN_AXIS)
  screenAxis[j] = 1
  this.shader.uniforms.screenAxis = screenAxis
  this.vao.draw(this.gl.TRIANGLES, this.tickCount[j], this.tickOffset[j])
}


proto.drawGrid = function(i, j, bounds, offset, color, lineWidth) {
  if(!this.gridCount[i]) {
    return
  }

  var minorAxis = zeroVec(MINOR_AXIS)
  minorAxis[j]  = bounds[1][j] - bounds[0][j]
  this.shader.uniforms.minorAxis = minorAxis

  var noffset = copyVec(OFFSET_VEC, offset)
  noffset[j] += bounds[0][j]
  this.shader.uniforms.offset = noffset

  var majorAxis = zeroVec(MAJOR_AXIS)
  majorAxis[i]  = 1
  this.shader.uniforms.majorAxis = majorAxis

  var screenAxis = zeroVec(SCREEN_AXIS)
  screenAxis[i] = 1
  this.shader.uniforms.screenAxis = screenAxis
  this.shader.uniforms.lineWidth = lineWidth

  this.shader.uniforms.color = color
  this.vao.draw(this.gl.TRIANGLES, this.gridCount[i], this.gridOffset[i])
}

proto.drawZero = function(j, i, bounds, offset, color, lineWidth) {
  var minorAxis = zeroVec(MINOR_AXIS)
  this.shader.uniforms.majorAxis = minorAxis

  minorAxis[j] = bounds[1][j] - bounds[0][j]
  this.shader.uniforms.minorAxis = minorAxis

  var noffset = copyVec(OFFSET_VEC, offset)
  noffset[j] += bounds[0][j]
  this.shader.uniforms.offset = noffset

  var screenAxis = zeroVec(SCREEN_AXIS)
  screenAxis[i] = 1
  this.shader.uniforms.screenAxis = screenAxis
  this.shader.uniforms.lineWidth = lineWidth

  this.shader.uniforms.color = color
  this.vao.draw(this.gl.TRIANGLES, 6)
}

proto.dispose = function() {
  this.vao.dispose()
  this.vertBuffer.dispose()
  this.shader.dispose()
}

function createLines(gl, bounds, ticks) {
  var vertices    = []
  var tickOffset  = [0,0,0]
  var tickCount   = [0,0,0]

  //Create grid lines for each axis/direction
  var gridOffset = [0,0,0]
  var gridCount  = [0,0,0]

  //Add zero line
  vertices.push(
    0,0,1,   0,1,1,   0,0,-1,
    0,0,-1,  0,1,1,   0,1,-1)

  for(var i=0; i<3; ++i) {
    //Axis tick marks
    var start = ((vertices.length / 3)|0)
    for(var j=0; j<ticks[i].length; ++j) {
      var x = +ticks[i][j].x
      vertices.push(
        x,0,1,   x,1,1,   x,0,-1,
        x,0,-1,  x,1,1,   x,1,-1)
    }
    var end = ((vertices.length / 3)|0)
    tickOffset[i] = start
    tickCount[i]  = end - start

    //Grid lines
    var start = ((vertices.length / 3)|0)
    for(var k=0; k<ticks[i].length; ++k) {
      var x = +ticks[i][k].x
      vertices.push(
        x,0,1,   x,1,1,   x,0,-1,
        x,0,-1,  x,1,1,   x,1,-1)
    }
    var end = ((vertices.length / 3)|0)
    gridOffset[i] = start
    gridCount[i]  = end - start
  }

  //Create cube VAO
  var vertBuf = createBuffer(gl, new Float32Array(vertices))
  var vao = createVAO(gl, [
    { "buffer": vertBuf,
      "type": gl.FLOAT,
      "size": 3,
      "stride": 0,
      "offset": 0
    }
  ])
  var shader = createShader(gl)
  shader.attributes.position.location = 0
  return new Lines(gl, vertBuf, vao, shader, tickCount, tickOffset, gridCount, gridOffset)
}

},{"./shaders":230,"gl-buffer":234,"gl-vao":316}],230:[function(_dereq_,module,exports){
'use strict'

var glslify = _dereq_('glslify')
var createShader = _dereq_('gl-shader')

var lineVert = glslify(["#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, majorAxis, minorAxis, screenAxis;\nuniform float lineWidth;\nuniform vec2 screenShape;\n\nvec3 project(vec3 p) {\n  vec4 pp = projection * view * model * vec4(p, 1.0);\n  return pp.xyz / max(pp.w, 0.0001);\n}\n\nvoid main() {\n  vec3 major = position.x * majorAxis;\n  vec3 minor = position.y * minorAxis;\n\n  vec3 vPosition = major + minor + offset;\n  vec3 pPosition = project(vPosition);\n  vec3 offset = project(vPosition + screenAxis * position.z);\n\n  vec2 screen = normalize((offset - pPosition).xy * screenShape) / screenShape;\n\n  gl_Position = vec4(pPosition + vec3(0.5 * screen * lineWidth, 0), 1.0);\n}\n"])
var lineFrag = glslify(["precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n  gl_FragColor = color;\n}"])
exports.line = function(gl) {
  return createShader(gl, lineVert, lineFrag, null, [
    {name: 'position', type: 'vec3'}
  ])
}

var textVert = glslify(["#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, axis, alignDir, alignOpt;\nuniform float scale, angle, pixelScale;\nuniform vec2 resolution;\n\nvec3 project(vec3 p) {\n  vec4 pp = projection * view * model * vec4(p, 1.0);\n  return pp.xyz / max(pp.w, 0.0001);\n}\n\nfloat computeViewAngle(vec3 a, vec3 b) {\n  vec3 A = project(a);\n  vec3 B = project(b);\n\n  return atan(\n    (B.y - A.y) * resolution.y,\n    (B.x - A.x) * resolution.x\n  );\n}\n\nconst float PI = 3.141592;\nconst float TWO_PI = 2.0 * PI;\nconst float HALF_PI = 0.5 * PI;\nconst float ONE_AND_HALF_PI = 1.5 * PI;\n\nint option = int(floor(alignOpt.x + 0.001));\nfloat hv_ratio =       alignOpt.y;\nbool enableAlign =    (alignOpt.z != 0.0);\n\nfloat mod_angle(float a) {\n  return mod(a, PI);\n}\n\nfloat positive_angle(float a) {\n  return mod_angle((a < 0.0) ?\n    a + TWO_PI :\n    a\n  );\n}\n\nfloat look_upwards(float a) {\n  float b = positive_angle(a);\n  return ((b > HALF_PI) && (b <= ONE_AND_HALF_PI)) ?\n    b - PI :\n    b;\n}\n\nfloat look_horizontal_or_vertical(float a, float ratio) {\n  // ratio controls the ratio between being horizontal to (vertical + horizontal)\n  // if ratio is set to 0.5 then it is 50%, 50%.\n  // when using a higher ratio e.g. 0.75 the result would\n  // likely be more horizontal than vertical.\n\n  float b = positive_angle(a);\n\n  return\n    (b < (      ratio) * HALF_PI) ? 0.0 :\n    (b < (2.0 - ratio) * HALF_PI) ? -HALF_PI :\n    (b < (2.0 + ratio) * HALF_PI) ? 0.0 :\n    (b < (4.0 - ratio) * HALF_PI) ? HALF_PI :\n                                    0.0;\n}\n\nfloat roundTo(float a, float b) {\n  return float(b * floor((a + 0.5 * b) / b));\n}\n\nfloat look_round_n_directions(float a, int n) {\n  float b = positive_angle(a);\n  float div = TWO_PI / float(n);\n  float c = roundTo(b, div);\n  return look_upwards(c);\n}\n\nfloat applyAlignOption(float rawAngle, float delta) {\n  return\n    (option >  2) ? look_round_n_directions(rawAngle + delta, option) :       // option 3-n: round to n directions\n    (option == 2) ? look_horizontal_or_vertical(rawAngle + delta, hv_ratio) : // horizontal or vertical\n    (option == 1) ? rawAngle + delta :       // use free angle, and flip to align with one direction of the axis\n    (option == 0) ? look_upwards(rawAngle) : // use free angle, and stay upwards\n    (option ==-1) ? 0.0 :                    // useful for backward compatibility, all texts remains horizontal\n                    rawAngle;                // otherwise return back raw input angle\n}\n\nbool isAxisTitle = (axis.x == 0.0) &&\n                   (axis.y == 0.0) &&\n                   (axis.z == 0.0);\n\nvoid main() {\n  //Compute world offset\n  float axisDistance = position.z;\n  vec3 dataPosition = axisDistance * axis + offset;\n\n  float beta = angle; // i.e. user defined attributes for each tick\n\n  float axisAngle;\n  float clipAngle;\n  float flip;\n\n  if (enableAlign) {\n    axisAngle = (isAxisTitle) ? HALF_PI :\n                      computeViewAngle(dataPosition, dataPosition + axis);\n    clipAngle = computeViewAngle(dataPosition, dataPosition + alignDir);\n\n    axisAngle += (sin(axisAngle) < 0.0) ? PI : 0.0;\n    clipAngle += (sin(clipAngle) < 0.0) ? PI : 0.0;\n\n    flip = (dot(vec2(cos(axisAngle), sin(axisAngle)),\n                vec2(sin(clipAngle),-cos(clipAngle))) > 0.0) ? 1.0 : 0.0;\n\n    beta += applyAlignOption(clipAngle, flip * PI);\n  }\n\n  //Compute plane offset\n  vec2 planeCoord = position.xy * pixelScale;\n\n  mat2 planeXform = scale * mat2(\n     cos(beta), sin(beta),\n    -sin(beta), cos(beta)\n  );\n\n  vec2 viewOffset = 2.0 * planeXform * planeCoord / resolution;\n\n  //Compute clip position\n  vec3 clipPosition = project(dataPosition);\n\n  //Apply text offset in clip coordinates\n  clipPosition += vec3(viewOffset, 0.0);\n\n  //Done\n  gl_Position = vec4(clipPosition, 1.0);\n}"])
var textFrag = glslify(["precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n  gl_FragColor = color;\n}"])
exports.text = function(gl) {
  return createShader(gl, textVert, textFrag, null, [
    {name: 'position', type: 'vec3'}
  ])
}

var bgVert = glslify(["#define GLSLIFY 1\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection;\nuniform vec3 enable;\nuniform vec3 bounds[2];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n\n  vec3 signAxis = sign(bounds[1] - bounds[0]);\n\n  vec3 realNormal = signAxis * normal;\n\n  if(dot(realNormal, enable) > 0.0) {\n    vec3 minRange = min(bounds[0], bounds[1]);\n    vec3 maxRange = max(bounds[0], bounds[1]);\n    vec3 nPosition = mix(minRange, maxRange, 0.5 * (position + 1.0));\n    gl_Position = projection * view * model * vec4(nPosition, 1.0);\n  } else {\n    gl_Position = vec4(0,0,0,0);\n  }\n\n  colorChannel = abs(realNormal);\n}"])
var bgFrag = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 colors[3];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n  gl_FragColor = colorChannel.x * colors[0] +\n                 colorChannel.y * colors[1] +\n                 colorChannel.z * colors[2];\n}"])
exports.bg = function(gl) {
  return createShader(gl, bgVert, bgFrag, null, [
    {name: 'position', type: 'vec3'},
    {name: 'normal', type: 'vec3'}
  ])
}

},{"gl-shader":294,"glslify":398}],231:[function(_dereq_,module,exports){
(function (process){
"use strict"

module.exports = createTextSprites

var createBuffer  = _dereq_('gl-buffer')
var createVAO     = _dereq_('gl-vao')
var vectorizeText = _dereq_('vectorize-text')
var createShader  = _dereq_('./shaders').text

var globals = window || process.global || {}
var __TEXT_CACHE  = globals.__TEXT_CACHE || {}
globals.__TEXT_CACHE = {}

//Vertex buffer format for text is:
//
/// [x,y,z] = Spatial coordinate
//

var VERTEX_SIZE = 3

function TextSprites(
  gl,
  shader,
  buffer,
  vao) {
  this.gl           = gl
  this.shader       = shader
  this.buffer       = buffer
  this.vao          = vao
  this.tickOffset   =
  this.tickCount    =
  this.labelOffset  =
  this.labelCount   = null
}

var proto = TextSprites.prototype

//Bind textures for rendering
var SHAPE = [0,0]
proto.bind = function(model, view, projection, pixelScale) {
  this.vao.bind()
  this.shader.bind()
  var uniforms = this.shader.uniforms
  uniforms.model = model
  uniforms.view = view
  uniforms.projection = projection
  uniforms.pixelScale = pixelScale
  SHAPE[0] = this.gl.drawingBufferWidth
  SHAPE[1] = this.gl.drawingBufferHeight
  this.shader.uniforms.resolution = SHAPE
}

proto.unbind = function() {
  this.vao.unbind()
}

proto.update = function(bounds, labels, labelFont, ticks, tickFont) {
  var data = []

  function addItem(t, text, font, size, lineSpacing, styletags) {
    var fontcache = __TEXT_CACHE[font]
    if(!fontcache) {
      fontcache = __TEXT_CACHE[font] = {}
    }
    var mesh = fontcache[text]
    if(!mesh) {
      mesh = fontcache[text] = tryVectorizeText(text, {
        triangles: true,
        font: font,
        textAlign: 'center',
        textBaseline: 'middle',
        lineSpacing: lineSpacing,
        styletags: styletags
      })
    }
    var scale = (size || 12) / 12
    var positions = mesh.positions
    var cells = mesh.cells
    for(var i=0, nc=cells.length; i<nc; ++i) {
      var c = cells[i]
      for(var j=2; j>=0; --j) {
        var p = positions[c[j]]
        data.push(scale*p[0], -scale*p[1], t)
      }
    }
  }

  //Generate sprites for all 3 axes, store data in texture atlases
  var tickOffset  = [0,0,0]
  var tickCount   = [0,0,0]
  var labelOffset = [0,0,0]
  var labelCount  = [0,0,0]
  var lineSpacing = 1.25
  var styletags = {
    breaklines:true,
    bolds: true,
    italics: true,
    subscripts:true,
    superscripts:true
  }
  for(var d=0; d<3; ++d) {

    //Generate label
    labelOffset[d] = (data.length/VERTEX_SIZE)|0
    addItem(
      0.5*(bounds[0][d]+bounds[1][d]),
      labels[d],
      labelFont[d],
      12, // labelFontSize
      lineSpacing,
      styletags
    )
    labelCount[d] = ((data.length/VERTEX_SIZE)|0) - labelOffset[d]

    //Generate sprites for tick marks
    tickOffset[d] = (data.length/VERTEX_SIZE)|0
    for(var i=0; i<ticks[d].length; ++i) {
      if(!ticks[d][i].text) {
        continue
      }
      addItem(
        ticks[d][i].x,
        ticks[d][i].text,
        ticks[d][i].font || tickFont,
        ticks[d][i].fontSize || 12,
        lineSpacing,
        styletags
      )
    }
    tickCount[d] = ((data.length/VERTEX_SIZE)|0) - tickOffset[d]
  }

  this.buffer.update(data)
  this.tickOffset = tickOffset
  this.tickCount = tickCount
  this.labelOffset = labelOffset
  this.labelCount = labelCount
}

//Draws the tick marks for an axis
proto.drawTicks = function(d, scale, angle, offset, color, axis, alignDir, alignOpt) {
  if(!this.tickCount[d]) {
    return
  }

  this.shader.uniforms.axis = axis
  this.shader.uniforms.color = color
  this.shader.uniforms.angle = angle
  this.shader.uniforms.scale = scale
  this.shader.uniforms.offset = offset
  this.shader.uniforms.alignDir = alignDir
  this.shader.uniforms.alignOpt = alignOpt
  this.vao.draw(this.gl.TRIANGLES, this.tickCount[d], this.tickOffset[d])
}

//Draws the text label for an axis
proto.drawLabel = function(d, scale, angle, offset, color, axis, alignDir, alignOpt) {
  if(!this.labelCount[d]) {
    return
  }

  this.shader.uniforms.axis = axis
  this.shader.uniforms.color = color
  this.shader.uniforms.angle = angle
  this.shader.uniforms.scale = scale
  this.shader.uniforms.offset = offset
  this.shader.uniforms.alignDir = alignDir
  this.shader.uniforms.alignOpt = alignOpt
  this.vao.draw(this.gl.TRIANGLES, this.labelCount[d], this.labelOffset[d])
}

//Releases all resources attached to this object
proto.dispose = function() {
  this.shader.dispose()
  this.vao.dispose()
  this.buffer.dispose()
}

function tryVectorizeText(text, options) {
  try {
    return vectorizeText(text, options)
  } catch(e) {
    console.warn('error vectorizing text:"' + text + '" error:', e)
    return {
      cells: [],
      positions: []
    }
  }
}

function createTextSprites(
    gl,
    bounds,
    labels,
    labelFont,
    ticks,
    tickFont) {

  var buffer = createBuffer(gl)
  var vao = createVAO(gl, [
    { "buffer": buffer,
      "size": 3
    }
  ])

  var shader = createShader(gl)
  shader.attributes.position.location = 0

  var result = new TextSprites(
    gl,
    shader,
    buffer,
    vao)

  result.update(bounds, labels, labelFont, ticks, tickFont)

  return result
}

}).call(this,_dereq_('_process'))
},{"./shaders":230,"_process":471,"gl-buffer":234,"gl-vao":316,"vectorize-text":531}],232:[function(_dereq_,module,exports){
'use strict'

exports.create   = defaultTicks
exports.equal    = ticksEqual

function prettyPrint(spacing, i) {
  var stepStr = spacing + ""
  var u = stepStr.indexOf(".")
  var sigFigs = 0
  if(u >= 0) {
    sigFigs = stepStr.length - u - 1
  }
  var shift = Math.pow(10, sigFigs)
  var x = Math.round(spacing * i * shift)
  var xstr = x + ""
  if(xstr.indexOf("e") >= 0) {
    return xstr
  }
  var xi = x / shift, xf = x % shift
  if(x < 0) {
    xi = -Math.ceil(xi)|0
    xf = (-xf)|0
  } else {
    xi = Math.floor(xi)|0
    xf = xf|0
  }
  var xis = "" + xi 
  if(x < 0) {
    xis = "-" + xis
  }
  if(sigFigs) {
    var xs = "" + xf
    while(xs.length < sigFigs) {
      xs = "0" + xs
    }
    return xis + "." + xs
  } else {
    return xis
  }
}

function defaultTicks(bounds, tickSpacing) {
  var array = []
  for(var d=0; d<3; ++d) {
    var ticks = []
    var m = 0.5*(bounds[0][d]+bounds[1][d])
    for(var t=0; t*tickSpacing[d]<=bounds[1][d]; ++t) {
      ticks.push({x: t*tickSpacing[d], text: prettyPrint(tickSpacing[d], t)})
    }
    for(var t=-1; t*tickSpacing[d]>=bounds[0][d]; --t) {
      ticks.push({x: t*tickSpacing[d], text: prettyPrint(tickSpacing[d], t)})
    }
    array.push(ticks)
  }
  return array
}

function ticksEqual(ticksA, ticksB) {
  for(var i=0; i<3; ++i) {
    if(ticksA[i].length !== ticksB[i].length) {
      return false
    }
    for(var j=0; j<ticksA[i].length; ++j) {
      var a = ticksA[i][j]
      var b = ticksB[i][j]
      if(
        a.x !== b.x ||
        a.text !== b.text ||
        a.font !== b.font ||
        a.fontColor !== b.fontColor ||
        a.fontSize !== b.fontSize ||
        a.dx !== b.dx ||
        a.dy !== b.dy
      ) {
        return false
      }
    }
  }
  return true
}
},{}],233:[function(_dereq_,module,exports){
"use strict"

module.exports = axesProperties

var getPlanes   = _dereq_("extract-frustum-planes")
var splitPoly   = _dereq_("split-polygon")
var cubeParams  = _dereq_("./lib/cube.js")
var m4mul       = _dereq_("gl-mat4/multiply")
var m4transpose = _dereq_("gl-mat4/transpose")
var v4transformMat4 = _dereq_("gl-vec4/transformMat4")

var identity    = new Float32Array([
    1, 0, 0, 0,
    0, 1, 0, 0,
    0, 0, 1, 0,
    0, 0, 0, 1
  ])

var mvp         = new Float32Array(16)

function AxesRange3D(lo, hi, pixelsPerDataUnit) {
  this.lo = lo
  this.hi = hi
  this.pixelsPerDataUnit = pixelsPerDataUnit
}

var SCRATCH_P = [0,0,0,1]
var SCRATCH_Q = [0,0,0,1]

function gradient(result, M, v, width, height) {
  for(var i=0; i<3; ++i) {
    var p = SCRATCH_P
    var q = SCRATCH_Q
    for(var j=0; j<3; ++j) {
      q[j] = p[j] = v[j]
    }
    q[3] = p[3] = 1

    q[i] += 1
    v4transformMat4(q, q, M)
    if(q[3] < 0) {
      result[i] = Infinity
    }

    p[i] -= 1
    v4transformMat4(p, p, M)
    if(p[3] < 0) {
      result[i] = Infinity
    }

    var dx = (p[0]/p[3] - q[0]/q[3]) * width
    var dy = (p[1]/p[3] - q[1]/q[3]) * height

    result[i] = 0.25 * Math.sqrt(dx*dx + dy*dy)
  }
  return result
}

var RANGES = [
  new AxesRange3D(Infinity, -Infinity, Infinity),
  new AxesRange3D(Infinity, -Infinity, Infinity),
  new AxesRange3D(Infinity, -Infinity, Infinity)
]

var SCRATCH_X = [0,0,0]

function axesProperties(axes, camera, width, height, params) {
  var model       = camera.model || identity
  var view        = camera.view || identity
  var projection  = camera.projection || identity
  var isOrtho     = camera._ortho || false
  var bounds      = axes.bounds
  var params      = params || cubeParams(model, view, projection, bounds, isOrtho)
  var axis        = params.axis

  m4mul(mvp, view, model)
  m4mul(mvp, projection, mvp)

  //Calculate the following properties for each axis:
  //
  // * lo - start of visible range for each axis in tick coordinates
  // * hi - end of visible range for each axis in tick coordinates
  // * ticksPerPixel - pixel density of tick marks for the axis
  //
  var ranges = RANGES
  for(var i=0; i<3; ++i) {
    ranges[i].lo = Infinity
    ranges[i].hi = -Infinity
    ranges[i].pixelsPerDataUnit = Infinity
  }

  //Compute frustum planes, intersect with box
  var frustum = getPlanes(m4transpose(mvp, mvp))
  m4transpose(mvp, mvp)

  //Loop over vertices of viewable box
  for(var d=0; d<3; ++d) {
    var u = (d+1)%3
    var v = (d+2)%3
    var x = SCRATCH_X
i_loop:
    for(var i=0; i<2; ++i) {
      var poly = []

      if((axis[d] < 0) === !!i) {
        continue
      }

      x[d] = bounds[i][d]
      for(var j=0; j<2; ++j) {
        x[u] = bounds[j^i][u]
        for(var k=0; k<2; ++k) {
          x[v] = bounds[k^j^i][v]
          poly.push(x.slice())
        }
      }

      var Q = (isOrtho) ? 5 : 4
      for(var j=Q; j===Q; ++j) { // Note: using only near plane here (& for orthographic projection we use the far).
        if(poly.length === 0) {
          continue i_loop
        }
        poly = splitPoly.positive(poly, frustum[j])
      }

      //Loop over vertices of polygon to find extremal points
      for(var j=0; j<poly.length; ++j) {
        var v = poly[j]
        var grad = gradient(SCRATCH_X, mvp, v, width, height)
        for(var k=0; k<3; ++k) {
          ranges[k].lo = Math.min(ranges[k].lo, v[k])
          ranges[k].hi = Math.max(ranges[k].hi, v[k])
          if(k !== d) {
            ranges[k].pixelsPerDataUnit = Math.min(ranges[k].pixelsPerDataUnit, Math.abs(grad[k]))
          }
        }
      }
    }
  }

  return ranges
}

},{"./lib/cube.js":228,"extract-frustum-planes":217,"gl-mat4/multiply":260,"gl-mat4/transpose":269,"gl-vec4/transformMat4":387,"split-polygon":508}],234:[function(_dereq_,module,exports){
"use strict"

var pool = _dereq_("typedarray-pool")
var ops = _dereq_("ndarray-ops")
var ndarray = _dereq_("ndarray")

var SUPPORTED_TYPES = [
  "uint8",
  "uint8_clamped",
  "uint16",
  "uint32",
  "int8",
  "int16",
  "int32",
  "float32" ]

function GLBuffer(gl, type, handle, length, usage) {
  this.gl = gl
  this.type = type
  this.handle = handle
  this.length = length
  this.usage = usage
}

var proto = GLBuffer.prototype

proto.bind = function() {
  this.gl.bindBuffer(this.type, this.handle)
}

proto.unbind = function() {
  this.gl.bindBuffer(this.type, null)
}

proto.dispose = function() {
  this.gl.deleteBuffer(this.handle)
}

function updateTypeArray(gl, type, len, usage, data, offset) {
  var dataLen = data.length * data.BYTES_PER_ELEMENT
  if(offset < 0) {
    gl.bufferData(type, data, usage)
    return dataLen
  }
  if(dataLen + offset > len) {
    throw new Error("gl-buffer: If resizing buffer, must not specify offset")
  }
  gl.bufferSubData(type, offset, data)
  return len
}

function makeScratchTypeArray(array, dtype) {
  var res = pool.malloc(array.length, dtype)
  var n = array.length
  for(var i=0; i<n; ++i) {
    res[i] = array[i]
  }
  return res
}

function isPacked(shape, stride) {
  var n = 1
  for(var i=stride.length-1; i>=0; --i) {
    if(stride[i] !== n) {
      return false
    }
    n *= shape[i]
  }
  return true
}

proto.update = function(array, offset) {
  if(typeof offset !== "number") {
    offset = -1
  }
  this.bind()
  if(typeof array === "object" && typeof array.shape !== "undefined") { //ndarray
    var dtype = array.dtype
    if(SUPPORTED_TYPES.indexOf(dtype) < 0) {
      dtype = "float32"
    }
    if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) {
      var ext = gl.getExtension('OES_element_index_uint')
      if(ext && dtype !== "uint16") {
        dtype = "uint32"
      } else {
        dtype = "uint16"
      }
    }
    if(dtype === array.dtype && isPacked(array.shape, array.stride)) {
      if(array.offset === 0 && array.data.length === array.shape[0]) {
        this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data, offset)
      } else {
        this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data.subarray(array.offset, array.shape[0]), offset)
      }
    } else {
      var tmp = pool.malloc(array.size, dtype)
      var ndt = ndarray(tmp, array.shape)
      ops.assign(ndt, array)
      if(offset < 0) {
        this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp, offset)
      } else {
        this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp.subarray(0, array.size), offset)
      }
      pool.free(tmp)
    }
  } else if(Array.isArray(array)) { //Vanilla array
    var t
    if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) {
      t = makeScratchTypeArray(array, "uint16")
    } else {
      t = makeScratchTypeArray(array, "float32")
    }
    if(offset < 0) {
      this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t, offset)
    } else {
      this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t.subarray(0, array.length), offset)
    }
    pool.free(t)
  } else if(typeof array === "object" && typeof array.length === "number") { //Typed array
    this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array, offset)
  } else if(typeof array === "number" || array === undefined) { //Number/default
    if(offset >= 0) {
      throw new Error("gl-buffer: Cannot specify offset when resizing buffer")
    }
    array = array | 0
    if(array <= 0) {
      array = 1
    }
    this.gl.bufferData(this.type, array|0, this.usage)
    this.length = array
  } else { //Error, case should not happen
    throw new Error("gl-buffer: Invalid data type")
  }
}

function createBuffer(gl, data, type, usage) {
  type = type || gl.ARRAY_BUFFER
  usage = usage || gl.DYNAMIC_DRAW
  if(type !== gl.ARRAY_BUFFER && type !== gl.ELEMENT_ARRAY_BUFFER) {
    throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER")
  }
  if(usage !== gl.DYNAMIC_DRAW && usage !== gl.STATIC_DRAW && usage !== gl.STREAM_DRAW) {
    throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW")
  }
  var handle = gl.createBuffer()
  var result = new GLBuffer(gl, type, handle, 0, usage)
  result.update(data)
  return result
}

module.exports = createBuffer

},{"ndarray":439,"ndarray-ops":433,"typedarray-pool":526}],235:[function(_dereq_,module,exports){
"use strict";

var V = _dereq_('gl-vec3');

var vec3 = function(x, y, z) {
	var v = V.create();
	if (x !== undefined) {
		V.set(v, x, y, z);
	}
	return v;
}

var createPositionsForMeshgrid = function(meshgrid) {
	var xs = meshgrid[0], ys = meshgrid[1], zs = meshgrid[2];
	var positions = [];
	for (var z=0; z<zs.length; z++) {
		for (var y=0; y<ys.length; y++) {
			for (var x=0; x<xs.length; x++) {
				positions.push([zs[z], ys[y], xs[x]]);
			}
		}
	}
	return positions;
};

var findLastSmallerIndex = function(points, v) {
	for (var i=0; i<points.length; i++) {
		if (points[i] >= v) {
			return i-1;
		}
	}
	return i;
};

var tmp = V.create();
var tmp2 = V.create();

var clamp = function(v, min, max) {
	return v < min ? min : (v > max ? max : v);
};

var sampleMeshgrid = function(point, array, meshgrid, clampOverflow) {
	var x = point[0];
	var y = point[1];
	var z = point[2];

	var w = meshgrid[0].length;
	var h = meshgrid[1].length;
	var d = meshgrid[2].length;

	// Find the index of the nearest smaller value in the meshgrid for each coordinate of (x,y,z).
	// The nearest smaller value index for x is the index x0 such that
	// meshgrid[0][x0] < x and for all x1 > x0, meshgrid[0][x1] >= x.
	var x0 = findLastSmallerIndex(meshgrid[0], x);
	var y0 = findLastSmallerIndex(meshgrid[1], y);
	var z0 = findLastSmallerIndex(meshgrid[2], z);

	// Get the nearest larger meshgrid value indices.
	// From the above "nearest smaller value", we know that
	//   meshgrid[0][x0] < x
	//   meshgrid[0][x0+1] >= x
	var x1 = x0 + 1;
	var y1 = y0 + 1;
	var z1 = z0 + 1;

	if (clampOverflow) {
		x0 = clamp(x0, 0, w-1);
		x1 = clamp(x1, 0, w-1);
		y0 = clamp(y0, 0, h-1);
		y1 = clamp(y1, 0, h-1);
		z0 = clamp(z0, 0, d-1);
		z1 = clamp(z1, 0, d-1);
	}

	// Reject points outside the meshgrid, return a zero vector.
	if (x0 < 0 || y0 < 0 || z0 < 0 || x1 >= w || y1 >= h || z1 >= d) {
		return V.create();
	}

	// Normalize point coordinates to 0..1 scaling factor between x0 and x1.
	var xf = (x - meshgrid[0][x0]) / (meshgrid[0][x1] - meshgrid[0][x0]);
	var yf = (y - meshgrid[1][y0]) / (meshgrid[1][y1] - meshgrid[1][y0]);
	var zf = (z - meshgrid[2][z0]) / (meshgrid[2][z1] - meshgrid[2][z0]);

	if (xf < 0 || xf > 1 || isNaN(xf)) xf = 0;
	if (yf < 0 || yf > 1 || isNaN(yf)) yf = 0;
	if (zf < 0 || zf > 1 || isNaN(zf)) zf = 0;

	var z0off = z0*w*h;
	var z1off = z1*w*h;

	var y0off = y0*w;
	var y1off = y1*w;

	var x0off = x0;
	var x1off = x1;

	// Sample data array around the (x,y,z) point.
	//  vZYX = array[zZoff + yYoff + xXoff]
	var v000 = array[y0off + z0off + x0off];
	var v001 = array[y0off + z0off + x1off];
	var v010 = array[y1off + z0off + x0off];
	var v011 = array[y1off + z0off + x1off];
	var v100 = array[y0off + z1off + x0off];
	var v101 = array[y0off + z1off + x1off];
	var v110 = array[y1off + z1off + x0off];
	var v111 = array[y1off + z1off + x1off];

	var result = V.create();

	// Average samples according to distance to point.
	V.lerp(result, v000, v001, xf);
	V.lerp(tmp, v010, v011, xf);
	V.lerp(result, result, tmp, yf);
	V.lerp(tmp, v100, v101, xf);
	V.lerp(tmp2, v110, v111, xf);
	V.lerp(tmp, tmp, tmp2, yf);
	V.lerp(result, result, tmp, zf);

	return result;
};

var getOrthogonalVector = function(dst, v) {
	// Return up-vector for only-z vector.
	if (v[0] === 0 && v[1] === 0) {
		V.set(dst, 0, 1, 0);
	} else {
		// Return ax + by + cz = 0, a point that lies on the plane that has v as a normal and that isn't (0,0,0).
		// From the above if-statement we have ||a|| > 0  U  ||b|| > 0.
		// Assign z = 0, x = -b, y = a:
		// a*-b + b*a + c*0 = -ba + ba + 0 = 0
		V.set(dst, -v[1], v[0], 0);
	}
	return dst;
};

module.exports = function(vectorfield, bounds) {
	var positions;
	if (vectorfield.positions) {
		positions = vectorfield.positions;
	} else {
		positions = createPositionsForMeshgrid(vectorfield.meshgrid);
	}
	var meshgrid = vectorfield.meshgrid;
	var vectors = vectorfield.vectors;
	var geo = {
		positions: [],
		vertexIntensity: [],
		vertexIntensityBounds: vectorfield.vertexIntensityBounds,
		vertexNormals: [],
		vectors: [],
		cells: [],
		coneOffset: vectorfield.coneOffset,
		colormap: vectorfield.colormap
	};

	if (vectorfield.positions.length === 0) {
		if (bounds) {
			bounds[0] = [0,0,0];
			bounds[1] = [0,0,0];
		}
		return geo;
	}

	// Compute bounding box for the dataset.
	// Compute maximum velocity for the dataset to use for scaling the cones.
	var maxNorm = 0;
	var minX = 1/0, maxX = -1/0;
	var minY = 1/0, maxY = -1/0;
	var minZ = 1/0, maxZ = -1/0;
	var p2 = null;
	var u2 = null;
	var positionVectors = [];
	var vectorScale = 1/0;
	for (var i = 0; i < positions.length; i++) {
		var p = positions[i];
		minX = Math.min(p[0], minX);
		maxX = Math.max(p[0], maxX);
		minY = Math.min(p[1], minY);
		maxY = Math.max(p[1], maxY);
		minZ = Math.min(p[2], minZ);
		maxZ = Math.max(p[2], maxZ);
		var u;
		if (meshgrid) {
			u = sampleMeshgrid(p, vectors, meshgrid, true);
		} else {
			u = vectors[i];
		}
		if (V.length(u) > maxNorm) {
			maxNorm = V.length(u);
		}
		if (i) {
			// Find vector scale [w/ units of time] using "successive" positions
			// (not "adjacent" with would be O(n^2)),
			//
			// The vector scale corresponds to the minimum "time" to travel across two
			// two adjacent positions at the average velocity of those two adjacent positions
			vectorScale = Math.min(vectorScale,
				2 * V.distance(p2, p) / (V.length(u2) + V.length(u))
			);
		}
		p2 = p;
		u2 = u;
		positionVectors.push(u);
	}
	var minV = [minX, minY, minZ];
	var maxV = [maxX, maxY, maxZ];
	if (bounds) {
		bounds[0] = minV;
		bounds[1] = maxV;
	}
	if (maxNorm === 0) {
		maxNorm = 1;
	}

	// Inverted max norm would map vector with norm maxNorm to 1 coord space units in length
	var invertedMaxNorm = 1 / maxNorm;

	if (!isFinite(vectorScale) || isNaN(vectorScale)) {
		vectorScale = 1.0;
	}
	geo.vectorScale = vectorScale;

	var nml = vec3(0,1,0);

	var coneScale = vectorfield.coneSize || 0.5;

	if (vectorfield.absoluteConeSize) {
		coneScale = vectorfield.absoluteConeSize * invertedMaxNorm;
	}

	geo.coneScale = coneScale;

	// Build the cone model.
	for (var i = 0, j = 0; i < positions.length; i++) {
		var p = positions[i];
		var x = p[0], y = p[1], z = p[2];
		var d = positionVectors[i];
		var intensity = V.length(d) * invertedMaxNorm;
		for (var k = 0, l = 8; k < l; k++) {
			geo.positions.push([x, y, z, j++]);
			geo.positions.push([x, y, z, j++]);
			geo.positions.push([x, y, z, j++]);
			geo.positions.push([x, y, z, j++]);
			geo.positions.push([x, y, z, j++]);
			geo.positions.push([x, y, z, j++]);

			geo.vectors.push(d);
			geo.vectors.push(d);
			geo.vectors.push(d);
			geo.vectors.push(d);
			geo.vectors.push(d);
			geo.vectors.push(d);

			geo.vertexIntensity.push(intensity, intensity, intensity);
			geo.vertexIntensity.push(intensity, intensity, intensity);

			geo.vertexNormals.push(nml, nml, nml);
			geo.vertexNormals.push(nml, nml, nml);

			var m = geo.positions.length;
			geo.cells.push([m-6, m-5, m-4], [m-3, m-2, m-1]);
		}
	}

	return geo;
};

module.exports.createConeMesh = _dereq_('./lib/conemesh');

},{"./lib/conemesh":236,"gl-vec3":335}],236:[function(_dereq_,module,exports){
'use strict'

var DEFAULT_VERTEX_NORMALS_EPSILON = 1e-6; // may be too large if triangles are very small
var DEFAULT_FACE_NORMALS_EPSILON = 1e-6;

var createShader  = _dereq_('gl-shader')
var createBuffer  = _dereq_('gl-buffer')
var createVAO     = _dereq_('gl-vao')
var createTexture = _dereq_('gl-texture2d')
var normals       = _dereq_('normals')
var multiply      = _dereq_('gl-mat4/multiply')
var invert        = _dereq_('gl-mat4/invert')
var ndarray       = _dereq_('ndarray')
var colormap      = _dereq_('colormap')
var getContour    = _dereq_('simplicial-complex-contour')
var pool          = _dereq_('typedarray-pool')
var shaders       = _dereq_('./shaders')

var meshShader    = shaders.meshShader
var pickShader    = shaders.pickShader

var IDENTITY = [
  1,0,0,0,
  0,1,0,0,
  0,0,1,0,
  0,0,0,1]

function SimplicialMesh(gl
  , texture
  , triShader
  , pickShader
  , trianglePositions
  , triangleVectors
  , triangleIds
  , triangleColors
  , triangleUVs
  , triangleNormals
  , triangleVAO
  , edgePositions
  , edgeIds
  , edgeColors
  , edgeUVs
  , edgeVAO
  , pointPositions
  , pointIds
  , pointColors
  , pointUVs
  , pointSizes
  , pointVAO
  , contourPositions
  , contourVAO) {

  this.gl                = gl
  this.pixelRatio         = 1
  this.cells             = []
  this.positions         = []
  this.intensity         = []
  this.texture           = texture
  this.dirty             = true

  this.triShader         = triShader
  this.pickShader        = pickShader

  this.trianglePositions = trianglePositions
  this.triangleVectors   = triangleVectors
  this.triangleColors    = triangleColors
  this.triangleNormals   = triangleNormals
  this.triangleUVs       = triangleUVs
  this.triangleIds       = triangleIds
  this.triangleVAO       = triangleVAO
  this.triangleCount     = 0

  this.lineWidth         = 1
  this.edgePositions     = edgePositions
  this.edgeColors        = edgeColors
  this.edgeUVs           = edgeUVs
  this.edgeIds           = edgeIds
  this.edgeVAO           = edgeVAO
  this.edgeCount         = 0

  this.pointPositions    = pointPositions
  this.pointColors       = pointColors
  this.pointUVs          = pointUVs
  this.pointSizes        = pointSizes
  this.pointIds          = pointIds
  this.pointVAO          = pointVAO
  this.pointCount        = 0

  this.contourLineWidth  = 1
  this.contourPositions  = contourPositions
  this.contourVAO        = contourVAO
  this.contourCount      = 0
  this.contourColor      = [0,0,0]
  this.contourEnable     = true

  this.pickId            = 1
  this.bounds            = [
    [ Infinity, Infinity, Infinity],
    [-Infinity,-Infinity,-Infinity] ]
  this.clipBounds        = [
    [-Infinity,-Infinity,-Infinity],
    [ Infinity, Infinity, Infinity] ]

  this.lightPosition = [1e5, 1e5, 0]
  this.ambientLight  = 0.8
  this.diffuseLight  = 0.8
  this.specularLight = 2.0
  this.roughness     = 0.5
  this.fresnel       = 1.5

  this.opacity       = 1.0

  this.coneScale     = 2.0
  this.vectorScale   = 1.0
  this.coneOffset    = 1.0 / 4.0;

  this._model       = IDENTITY
  this._view        = IDENTITY
  this._projection  = IDENTITY
  this._resolution  = [1,1]
}

var proto = SimplicialMesh.prototype

proto.isOpaque = function() {
  return this.opacity >= 1
}

proto.isTransparent = function() {
  return this.opacity < 1
}

proto.pickSlots = 1

proto.setPickBase = function(id) {
  this.pickId = id
}

function genColormap(param) {
  var colors = colormap({
      colormap: param
    , nshades:  256
    , format:  'rgba'
  })

  var result = new Uint8Array(256*4)
  for(var i=0; i<256; ++i) {
    var c = colors[i]
    for(var j=0; j<3; ++j) {
      result[4*i+j] = c[j]
    }
    result[4*i+3] = c[3]*255
  }

  return ndarray(result, [256,256,4], [4,0,1])
}

function unpackIntensity(cells, numVerts, cellIntensity) {
  var result = new Array(numVerts)
  for(var i=0; i<numVerts; ++i) {
    result[i] = 0
  }
  var numCells = cells.length
  for(var i=0; i<numCells; ++i) {
    var c = cells[i]
    for(var j=0; j<c.length; ++j) {
      result[c[j]] = cellIntensity[i]
    }
  }
  return result
}

function takeZComponent(array) {
  var n = array.length
  var result = new Array(n)
  for(var i=0; i<n; ++i) {
    result[i] = array[i][2]
  }
  return result
}

proto.highlight = function(selection) {
  if(!selection || !this.contourEnable) {
    this.contourCount = 0
    return
  }
  var level = getContour(this.cells, this.intensity, selection.intensity)
  var cells         = level.cells
  var vertexIds     = level.vertexIds
  var vertexWeights = level.vertexWeights
  var numCells = cells.length
  var result = pool.mallocFloat32(2 * 3 * numCells)
  var ptr = 0
  for(var i=0; i<numCells; ++i) {
    var c = cells[i]
    for(var j=0; j<2; ++j) {
      var v = c[0]
      if(c.length === 2) {
        v = c[j]
      }
      var a = vertexIds[v][0]
      var b = vertexIds[v][1]
      var w = vertexWeights[v]
      var wi = 1.0 - w
      var pa = this.positions[a]
      var pb = this.positions[b]
      for(var k=0; k<3; ++k) {
        result[ptr++] = w * pa[k] + wi * pb[k]
      }
    }
  }
  this.contourCount = (ptr / 3)|0
  this.contourPositions.update(result.subarray(0, ptr))
  pool.free(result)
}

proto.update = function(params) {
  params = params || {}
  var gl = this.gl

  this.dirty = true

  if('contourEnable' in params) {
    this.contourEnable = params.contourEnable
  }
  if('contourColor' in params) {
    this.contourColor = params.contourColor
  }
  if('lineWidth' in params) {
    this.lineWidth = params.lineWidth
  }
  if('lightPosition' in params) {
    this.lightPosition = params.lightPosition
  }
  if('opacity' in params) {
    this.opacity = params.opacity
  }
  if('ambient' in params) {
    this.ambientLight  = params.ambient
  }
  if('diffuse' in params) {
    this.diffuseLight = params.diffuse
  }
  if('specular' in params) {
    this.specularLight = params.specular
  }
  if('roughness' in params) {
    this.roughness = params.roughness
  }
  if('fresnel' in params) {
    this.fresnel = params.fresnel
  }

  if (params.vectorScale !== undefined) {
    this.vectorScale = params.vectorScale;
  }
  if (params.coneScale !== undefined) {
    this.coneScale = params.coneScale;
  }
  if (params.coneOffset !== undefined) {
    this.coneOffset = params.coneOffset;
  }

  if(params.texture) {
    this.texture.dispose()
    this.texture = createTexture(gl, params.texture)
  } else if (params.colormap) {
    this.texture.shape = [256,256]
    this.texture.minFilter = gl.LINEAR_MIPMAP_LINEAR
    this.texture.magFilter = gl.LINEAR
    this.texture.setPixels(genColormap(params.colormap))
    this.texture.generateMipmap()
  }

  var cells = params.cells
  var positions = params.positions
  var vectors = params.vectors

  if(!positions || !cells || !vectors) {
    return
  }

  var tPos = []
  var tVec = []
  var tCol = []
  var tNor = []
  var tUVs = []
  var tIds = []

  var ePos = []
  var eCol = []
  var eUVs = []
  var eIds = []

  var pPos = []
  var pCol = []
  var pUVs = []
  var pSiz = []
  var pIds = []

  //Save geometry data for picking calculations
  this.cells     = cells
  this.positions = positions

  //Compute normals
  var vertexNormals = params.vertexNormals
  var cellNormals   = params.cellNormals
  var vertexNormalsEpsilon = params.vertexNormalsEpsilon === void(0) ? DEFAULT_VERTEX_NORMALS_EPSILON : params.vertexNormalsEpsilon
  var faceNormalsEpsilon = params.faceNormalsEpsilon === void(0) ? DEFAULT_FACE_NORMALS_EPSILON : params.faceNormalsEpsilon
  if(params.useFacetNormals && !cellNormals) {
    cellNormals = normals.faceNormals(cells, positions, faceNormalsEpsilon)
  }
  if(!cellNormals && !vertexNormals) {
    vertexNormals = normals.vertexNormals(cells, positions, vertexNormalsEpsilon)
  }

  //Compute colors
  var vertexColors    = params.vertexColors
  var cellColors      = params.cellColors
  var meshColor       = params.meshColor || [1,1,1,1]

  //UVs
  var vertexUVs       = params.vertexUVs
  var vertexIntensity = params.vertexIntensity
  var cellUVs         = params.cellUVs
  var cellIntensity   = params.cellIntensity

  var intensityLo     = Infinity
  var intensityHi     = -Infinity
  if(!vertexUVs && !cellUVs) {
    if(vertexIntensity) {
      if(params.vertexIntensityBounds) {
        intensityLo = +params.vertexIntensityBounds[0]
        intensityHi = +params.vertexIntensityBounds[1]
      } else {
        for(var i=0; i<vertexIntensity.length; ++i) {
          var f = vertexIntensity[i]
          intensityLo = Math.min(intensityLo, f)
          intensityHi = Math.max(intensityHi, f)
        }
      }
    } else if(cellIntensity) {
      for(var i=0; i<cellIntensity.length; ++i) {
        var f = cellIntensity[i]
        intensityLo = Math.min(intensityLo, f)
        intensityHi = Math.max(intensityHi, f)
      }
    } else {
      for(var i=0; i<positions.length; ++i) {
        var f = positions[i][2]
        intensityLo = Math.min(intensityLo, f)
        intensityHi = Math.max(intensityHi, f)
      }
    }
  }

  if(vertexIntensity) {
    this.intensity = vertexIntensity
  } else if(cellIntensity) {
    this.intensity = unpackIntensity(cells, positions.length, cellIntensity)
  } else {
    this.intensity = takeZComponent(positions)
  }

  //Point size
  var pointSizes      = params.pointSizes
  var meshPointSize   = params.pointSize || 1.0

  //Update bounds
  this.bounds       = [[Infinity,Infinity,Infinity], [-Infinity,-Infinity,-Infinity]]
  for(var i=0; i<positions.length; ++i) {
    var p = positions[i]
    for(var j=0; j<3; ++j) {
      if(isNaN(p[j]) || !isFinite(p[j])) {
        continue
      }
      this.bounds[0][j] = Math.min(this.bounds[0][j], p[j])
      this.bounds[1][j] = Math.max(this.bounds[1][j], p[j])
    }
  }

  //Pack cells into buffers
  var triangleCount = 0
  var edgeCount = 0
  var pointCount = 0

fill_loop:
  for(var i=0; i<cells.length; ++i) {
    var cell = cells[i]
    switch(cell.length) {
      case 1:

        var v = cell[0]
        var p = positions[v]

        //Check NaNs
        for(var j=0; j<3; ++j) {
          if(isNaN(p[j]) || !isFinite(p[j])) {
            continue fill_loop
          }
        }

        pPos.push(p[0], p[1], p[2], p[3])

        var c
        if(vertexColors) {
          c = vertexColors[v]
        } else if(cellColors) {
          c = cellColors[i]
        } else {
          c = meshColor
        }
        if(c.length === 3) {
          pCol.push(c[0], c[1], c[2], 1)
        } else {
          pCol.push(c[0], c[1], c[2], c[3])
        }

        var uv
        if(vertexUVs) {
          uv = vertexUVs[v]
        } else if(vertexIntensity) {
          uv = [
            (vertexIntensity[v] - intensityLo) /
            (intensityHi - intensityLo), 0]
        } else if(cellUVs) {
          uv = cellUVs[i]
        } else if(cellIntensity) {
          uv = [
            (cellIntensity[i] - intensityLo) /
            (intensityHi - intensityLo), 0]
        } else {
          uv = [
            (p[2] - intensityLo) /
            (intensityHi - intensityLo), 0]
        }
        pUVs.push(uv[0], uv[1])

        if(pointSizes) {
          pSiz.push(pointSizes[v])
        } else {
          pSiz.push(meshPointSize)
        }

        pIds.push(i)

        pointCount += 1
      break

      case 2:

        //Check NaNs
        for(var j=0; j<2; ++j) {
          var v = cell[j]
          var p = positions[v]
          for(var k=0; k<3; ++k) {
            if(isNaN(p[k]) || !isFinite(p[k])) {
              continue fill_loop
            }
          }
        }

        for(var j=0; j<2; ++j) {
          var v = cell[j]
          var p = positions[v]

          ePos.push(p[0], p[1], p[2])

          var c
          if(vertexColors) {
            c = vertexColors[v]
          } else if(cellColors) {
            c = cellColors[i]
          } else {
            c = meshColor
          }
          if(c.length === 3) {
            eCol.push(c[0], c[1], c[2], 1)
          } else {
            eCol.push(c[0], c[1], c[2], c[3])
          }

          var uv
          if(vertexUVs) {
            uv = vertexUVs[v]
          } else if(vertexIntensity) {
            uv = [
              (vertexIntensity[v] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else if(cellUVs) {
            uv = cellUVs[i]
          } else if(cellIntensity) {
            uv = [
              (cellIntensity[i] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else {
            uv = [
              (p[2] - intensityLo) /
              (intensityHi - intensityLo), 0]
          }
          eUVs.push(uv[0], uv[1])

          eIds.push(i)
        }
        edgeCount += 1
      break

      case 3:
        //Check NaNs
        for(var j=0; j<3; ++j) {
          var v = cell[j]
          var p = positions[v]
          for(var k=0; k<3; ++k) {
            if(isNaN(p[k]) || !isFinite(p[k])) {
              continue fill_loop
            }
          }
        }

        for(var j=0; j<3; ++j) {
          var v = cell[2 - j]

          var p = positions[v]
          tPos.push(p[0], p[1], p[2], p[3])

          var w = vectors[v]
          tVec.push(w[0], w[1], w[2]);

          var c
          if(vertexColors) {
            c = vertexColors[v]
          } else if(cellColors) {
            c = cellColors[i]
          } else {
            c = meshColor
          }
          if(c.length === 3) {
            tCol.push(c[0], c[1], c[2], 1)
          } else {
            tCol.push(c[0], c[1], c[2], c[3])
          }

          var uv
          if(vertexUVs) {
            uv = vertexUVs[v]
          } else if(vertexIntensity) {
            uv = [
              (vertexIntensity[v] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else if(cellUVs) {
            uv = cellUVs[i]
          } else if(cellIntensity) {
            uv = [
              (cellIntensity[i] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else {
            uv = [
              (p[2] - intensityLo) /
              (intensityHi - intensityLo), 0]
          }
          tUVs.push(uv[0], uv[1])

          var q
          if(vertexNormals) {
            q = vertexNormals[v]
          } else {
            q = cellNormals[i]
          }
          tNor.push(q[0], q[1], q[2])

          tIds.push(i)
        }
        triangleCount += 1
      break

      default:
      break
    }
  }

  this.pointCount     = pointCount
  this.edgeCount      = edgeCount
  this.triangleCount  = triangleCount

  this.pointPositions.update(pPos)
  this.pointColors.update(pCol)
  this.pointUVs.update(pUVs)
  this.pointSizes.update(pSiz)
  this.pointIds.update(new Uint32Array(pIds))

  this.edgePositions.update(ePos)
  this.edgeColors.update(eCol)
  this.edgeUVs.update(eUVs)
  this.edgeIds.update(new Uint32Array(eIds))

  this.trianglePositions.update(tPos)
  this.triangleVectors.update(tVec)
  this.triangleColors.update(tCol)
  this.triangleUVs.update(tUVs)
  this.triangleNormals.update(tNor)
  this.triangleIds.update(new Uint32Array(tIds))
}

proto.drawTransparent = proto.draw = function(params) {
  params = params || {}
  var gl          = this.gl
  var model       = params.model      || IDENTITY
  var view        = params.view       || IDENTITY
  var projection  = params.projection || IDENTITY

  var clipBounds = [[-1e6,-1e6,-1e6],[1e6,1e6,1e6]]
  for(var i=0; i<3; ++i) {
    clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i])
    clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i])
  }

  var uniforms = {
    model:      model,
    view:       view,
    projection: projection,
    inverseModel: IDENTITY.slice(),

    clipBounds: clipBounds,

    kambient:   this.ambientLight,
    kdiffuse:   this.diffuseLight,
    kspecular:  this.specularLight,
    roughness:  this.roughness,
    fresnel:    this.fresnel,

    eyePosition:   [0,0,0],
    lightPosition: [0,0,0],

    opacity:  this.opacity,

    vectorScale: this.vectorScale,
    coneScale: this.coneScale,
    coneOffset: this.coneOffset,

    contourColor: this.contourColor,

    texture:    0
  }

  uniforms.inverseModel = invert(uniforms.inverseModel, uniforms.model)

  gl.disable(gl.CULL_FACE)

  this.texture.bind(0)

  var invCameraMatrix = new Array(16)
  multiply(invCameraMatrix, uniforms.view, uniforms.model)
  multiply(invCameraMatrix, uniforms.projection, invCameraMatrix)
  invert(invCameraMatrix, invCameraMatrix)

  for(var i=0; i<3; ++i) {
    uniforms.eyePosition[i] = invCameraMatrix[12+i] / invCameraMatrix[15]
  }

  var w = invCameraMatrix[15]
  for(var i=0; i<3; ++i) {
    w += this.lightPosition[i] * invCameraMatrix[4*i+3]
  }
  for(var i=0; i<3; ++i) {
    var s = invCameraMatrix[12+i]
    for(var j=0; j<3; ++j) {
      s += invCameraMatrix[4*j+i] * this.lightPosition[j]
    }
    uniforms.lightPosition[i] = s / w
  }

  if(this.triangleCount > 0) {
    var shader = this.triShader
    shader.bind()
    shader.uniforms = uniforms

    this.triangleVAO.bind()
    gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3)
    this.triangleVAO.unbind()
  }
}
proto.drawPick = function(params) {
  params = params || {}

  var gl         = this.gl

  var model      = params.model      || IDENTITY
  var view       = params.view       || IDENTITY
  var projection = params.projection || IDENTITY

  var clipBounds = [[-1e6,-1e6,-1e6],[1e6,1e6,1e6]]
  for(var i=0; i<3; ++i) {
    clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i])
    clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i])
  }

  //Save camera parameters
  this._model      = [].slice.call(model)
  this._view       = [].slice.call(view)
  this._projection = [].slice.call(projection)
  this._resolution = [gl.drawingBufferWidth, gl.drawingBufferHeight]

  var uniforms = {
    model:      model,
    view:       view,
    projection: projection,
    clipBounds: clipBounds,

    vectorScale: this.vectorScale,
    coneScale: this.coneScale,
    coneOffset: this.coneOffset,

    pickId:     this.pickId / 255.0,
  }

  var shader = this.pickShader
  shader.bind()
  shader.uniforms = uniforms

  if(this.triangleCount > 0) {
    this.triangleVAO.bind()
    gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3)
    this.triangleVAO.unbind()
  }

  if(this.edgeCount > 0) {
    this.edgeVAO.bind()
    gl.lineWidth(this.lineWidth * this.pixelRatio)
    gl.drawArrays(gl.LINES, 0, this.edgeCount*2)
    this.edgeVAO.unbind()
  }

}


proto.pick = function(pickData) {
  if(!pickData) {
    return null
  }
  if(pickData.id !== this.pickId) {
    return null
  }

  var cellId    = pickData.value[0] + 256*pickData.value[1] + 65536*pickData.value[2]
  var cell      = this.cells[cellId]
  var pos =     this.positions[cell[1]].slice(0, 3)

  return {
    // corresponding to input indices
    index: Math.floor(cell[1] / 48),
    position: pos,
    dataCoordinate: pos
  }
}


proto.dispose = function() {
  this.texture.dispose()

  this.triShader.dispose()
  this.pickShader.dispose()

  this.triangleVAO.dispose()
  this.trianglePositions.dispose()
  this.triangleVectors.dispose()
  this.triangleColors.dispose()
  this.triangleUVs.dispose()
  this.triangleNormals.dispose()
  this.triangleIds.dispose()

  this.edgeVAO.dispose()
  this.edgePositions.dispose()
  this.edgeColors.dispose()
  this.edgeUVs.dispose()
  this.edgeIds.dispose()

  this.pointVAO.dispose()
  this.pointPositions.dispose()
  this.pointColors.dispose()
  this.pointUVs.dispose()
  this.pointSizes.dispose()
  this.pointIds.dispose()

  this.contourVAO.dispose()
  this.contourPositions.dispose()
}

function createMeshShader(gl) {
  // need to pass meshShader attributes manually,
  // to make this work on etpinard's Ubuntu Thinkpad
  var shader = createShader(gl, meshShader.vertex, meshShader.fragment, null, meshShader.attributes)
  shader.attributes.position.location = 0
  shader.attributes.color.location    = 2
  shader.attributes.uv.location       = 3
  shader.attributes.vector.location   = 5
  return shader
}


function createPickShader(gl) {
  var shader = createShader(gl, pickShader.vertex, pickShader.fragment, null, pickShader.attributes)
  shader.attributes.position.location = 0
  shader.attributes.id.location       = 1
  shader.attributes.vector.location   = 5
  return shader
}



function createSimplicialMesh(gl, params) {
  if (arguments.length === 1) {
    params = gl;
    gl = params.gl;
  }


  var triShader       = params.triShader || createMeshShader(gl)
  var pickShader      = createPickShader(gl)
  var meshTexture       = createTexture(gl,
    ndarray(new Uint8Array([255,255,255,255]), [1,1,4]))
  meshTexture.generateMipmap()
  meshTexture.minFilter = gl.LINEAR_MIPMAP_LINEAR
  meshTexture.magFilter = gl.LINEAR

  var trianglePositions = createBuffer(gl)
  var triangleVectors   = createBuffer(gl)
  var triangleColors    = createBuffer(gl)
  var triangleUVs       = createBuffer(gl)
  var triangleNormals   = createBuffer(gl)
  var triangleIds       = createBuffer(gl)
  var triangleVAO       = createVAO(gl, [
    { buffer: trianglePositions,
      type: gl.FLOAT,
      size: 4
    },
    { buffer: triangleIds,
      type: gl.UNSIGNED_BYTE,
      size: 4,
      normalized: true
    },
    { buffer: triangleColors,
      type: gl.FLOAT,
      size: 4
    },
    { buffer: triangleUVs,
      type: gl.FLOAT,
      size: 2
    },
    { buffer: triangleNormals,
      type: gl.FLOAT,
      size: 3
    },
    { buffer: triangleVectors,
      type: gl.FLOAT,
      size: 3
    }
  ])

  var edgePositions = createBuffer(gl)
  var edgeColors    = createBuffer(gl)
  var edgeUVs       = createBuffer(gl)
  var edgeIds       = createBuffer(gl)
  var edgeVAO       = createVAO(gl, [
    { buffer: edgePositions,
      type: gl.FLOAT,
      size: 3
    },
    { buffer: edgeIds,
      type: gl.UNSIGNED_BYTE,
      size: 4,
      normalized: true
    },
    { buffer: edgeColors,
      type: gl.FLOAT,
      size: 4
    },
    { buffer: edgeUVs,
      type: gl.FLOAT,
      size: 2
    }
  ])

  var pointPositions  = createBuffer(gl)
  var pointColors     = createBuffer(gl)
  var pointUVs        = createBuffer(gl)
  var pointSizes      = createBuffer(gl)
  var pointIds        = createBuffer(gl)
  var pointVAO        = createVAO(gl, [
    { buffer: pointPositions,
      type: gl.FLOAT,
      size: 3
    },
    { buffer: pointIds,
      type: gl.UNSIGNED_BYTE,
      size: 4,
      normalized: true
    },
    { buffer: pointColors,
      type: gl.FLOAT,
      size: 4
    },
    { buffer: pointUVs,
      type: gl.FLOAT,
      size: 2
    },
    { buffer: pointSizes,
      type: gl.FLOAT,
      size: 1
    }
  ])

  var contourPositions = createBuffer(gl)
  var contourVAO       = createVAO(gl, [
    { buffer: contourPositions,
      type:   gl.FLOAT,
      size:   3
    }])

  var mesh = new SimplicialMesh(gl
    , meshTexture
    , triShader
    , pickShader
    , trianglePositions
    , triangleVectors
    , triangleIds
    , triangleColors
    , triangleUVs
    , triangleNormals
    , triangleVAO
    , edgePositions
    , edgeIds
    , edgeColors
    , edgeUVs
    , edgeVAO
    , pointPositions
    , pointIds
    , pointColors
    , pointUVs
    , pointSizes
    , pointVAO
    , contourPositions
    , contourVAO)

  mesh.update(params)

  return mesh
}

module.exports = createSimplicialMesh

},{"./shaders":237,"colormap":114,"gl-buffer":234,"gl-mat4/invert":258,"gl-mat4/multiply":260,"gl-shader":294,"gl-texture2d":311,"gl-vao":316,"ndarray":439,"normals":442,"simplicial-complex-contour":499,"typedarray-pool":526}],237:[function(_dereq_,module,exports){
var glslify       = _dereq_('glslify')

var triVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nvec3 getOrthogonalVector(vec3 v) {\n  // Return up-vector for only-z vector.\n  // Return ax + by + cz = 0, a point that lies on the plane that has v as a normal and that isn't (0,0,0).\n  // From the above if-statement we have ||a|| > 0  U  ||b|| > 0.\n  // Assign z = 0, x = -b, y = a:\n  // a*-b + b*a + c*0 = -ba + ba + 0 = 0\n  if (v.x*v.x > v.z*v.z || v.y*v.y > v.z*v.z) {\n    return normalize(vec3(-v.y, v.x, 0.0));\n  } else {\n    return normalize(vec3(0.0, v.z, -v.y));\n  }\n}\n\n// Calculate the cone vertex and normal at the given index.\n//\n// The returned vertex is for a cone with its top at origin and height of 1.0,\n// pointing in the direction of the vector attribute.\n//\n// Each cone is made up of a top vertex, a center base vertex and base perimeter vertices.\n// These vertices are used to make up the triangles of the cone by the following:\n//   segment + 0 top vertex\n//   segment + 1 perimeter vertex a+1\n//   segment + 2 perimeter vertex a\n//   segment + 3 center base vertex\n//   segment + 4 perimeter vertex a\n//   segment + 5 perimeter vertex a+1\n// Where segment is the number of the radial segment * 6 and a is the angle at that radial segment.\n// To go from index to segment, floor(index / 6)\n// To go from segment to angle, 2*pi * (segment/segmentCount)\n// To go from index to segment index, index - (segment*6)\n//\nvec3 getConePosition(vec3 d, float rawIndex, float coneOffset, out vec3 normal) {\n\n  const float segmentCount = 8.0;\n\n  float index = rawIndex - floor(rawIndex /\n    (segmentCount * 6.0)) *\n    (segmentCount * 6.0);\n\n  float segment = floor(0.001 + index/6.0);\n  float segmentIndex = index - (segment*6.0);\n\n  normal = -normalize(d);\n\n  if (segmentIndex > 2.99 && segmentIndex < 3.01) {\n    return mix(vec3(0.0), -d, coneOffset);\n  }\n\n  float nextAngle = (\n    (segmentIndex > 0.99 &&  segmentIndex < 1.01) ||\n    (segmentIndex > 4.99 &&  segmentIndex < 5.01)\n  ) ? 1.0 : 0.0;\n  float angle = 2.0 * 3.14159 * ((segment + nextAngle) / segmentCount);\n\n  vec3 v1 = mix(d, vec3(0.0), coneOffset);\n  vec3 v2 = v1 - d;\n\n  vec3 u = getOrthogonalVector(d);\n  vec3 v = normalize(cross(u, d));\n\n  vec3 x = u * cos(angle) * length(d)*0.25;\n  vec3 y = v * sin(angle) * length(d)*0.25;\n  vec3 v3 = v2 + x + y;\n  if (segmentIndex < 3.0) {\n    vec3 tx = u * sin(angle);\n    vec3 ty = v * -cos(angle);\n    vec3 tangent = tx + ty;\n    normal = normalize(cross(v3 - v1, tangent));\n  }\n\n  if (segmentIndex == 0.0) {\n    return mix(d, vec3(0.0), coneOffset);\n  }\n  return v3;\n}\n\nattribute vec3 vector;\nattribute vec4 color, position;\nattribute vec2 uv;\nuniform float vectorScale;\nuniform float coneScale;\n\nuniform float coneOffset;\n\nuniform mat4 model\n           , view\n           , projection\n           , inverseModel;\nuniform vec3 eyePosition\n           , lightPosition;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data\n           , f_position;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  // Scale the vector magnitude to stay constant with\n  // model & view changes.\n  vec3 normal;\n  vec3 XYZ = getConePosition(mat3(model) * ((vectorScale * coneScale) * vector), position.w, coneOffset, normal);\n  vec4 conePosition = model * vec4(position.xyz, 1.0) + vec4(XYZ, 0.0);\n\n  //Lighting geometry parameters\n  vec4 cameraCoordinate = view * conePosition;\n  cameraCoordinate.xyz /= cameraCoordinate.w;\n  f_lightDirection = lightPosition - cameraCoordinate.xyz;\n  f_eyeDirection   = eyePosition - cameraCoordinate.xyz;\n  f_normal = normalize((vec4(normal,0.0) * inverseModel).xyz);\n\n  // vec4 m_position  = model * vec4(conePosition, 1.0);\n  vec4 t_position  = view * conePosition;\n  gl_Position      = projection * t_position;\n\n  f_color          = color;\n  f_data           = conePosition.xyz;\n  f_position       = position.xyz;\n  f_uv             = uv;\n}\n"])
var triFragSrc = glslify(["#extension GL_OES_standard_derivatives : enable\n\nprecision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution(float x, float roughness) {\n  float NdotH = max(x, 0.0001);\n  float cos2Alpha = NdotH * NdotH;\n  float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n  float roughness2 = roughness * roughness;\n  float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n  return exp(tan2Alpha / roughness2) / denom;\n}\n\nfloat cookTorranceSpecular(\n  vec3 lightDirection,\n  vec3 viewDirection,\n  vec3 surfaceNormal,\n  float roughness,\n  float fresnel) {\n\n  float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n  float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n  //Half angle vector\n  vec3 H = normalize(lightDirection + viewDirection);\n\n  //Geometric term\n  float NdotH = max(dot(surfaceNormal, H), 0.0);\n  float VdotH = max(dot(viewDirection, H), 0.000001);\n  float LdotH = max(dot(lightDirection, H), 0.000001);\n  float G1 = (2.0 * NdotH * VdotN) / VdotH;\n  float G2 = (2.0 * NdotH * LdotN) / LdotH;\n  float G = min(1.0, min(G1, G2));\n  \n  //Distribution term\n  float D = beckmannDistribution(NdotH, roughness);\n\n  //Fresnel term\n  float F = pow(1.0 - VdotN, fresnel);\n\n  //Multiply terms and done\n  return  G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n            , fresnel\n            , kambient\n            , kdiffuse\n            , kspecular\n            , opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data\n           , f_position;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n  vec3 N = normalize(f_normal);\n  vec3 L = normalize(f_lightDirection);\n  vec3 V = normalize(f_eyeDirection);\n\n  if(gl_FrontFacing) {\n    N = -N;\n  }\n\n  float specular = min(1.0, max(0.0, cookTorranceSpecular(L, V, N, roughness, fresnel)));\n  float diffuse  = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n  vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n  vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular,  1.0);\n\n  gl_FragColor = litColor * opacity;\n}\n"])
var pickVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nvec3 getOrthogonalVector(vec3 v) {\n  // Return up-vector for only-z vector.\n  // Return ax + by + cz = 0, a point that lies on the plane that has v as a normal and that isn't (0,0,0).\n  // From the above if-statement we have ||a|| > 0  U  ||b|| > 0.\n  // Assign z = 0, x = -b, y = a:\n  // a*-b + b*a + c*0 = -ba + ba + 0 = 0\n  if (v.x*v.x > v.z*v.z || v.y*v.y > v.z*v.z) {\n    return normalize(vec3(-v.y, v.x, 0.0));\n  } else {\n    return normalize(vec3(0.0, v.z, -v.y));\n  }\n}\n\n// Calculate the cone vertex and normal at the given index.\n//\n// The returned vertex is for a cone with its top at origin and height of 1.0,\n// pointing in the direction of the vector attribute.\n//\n// Each cone is made up of a top vertex, a center base vertex and base perimeter vertices.\n// These vertices are used to make up the triangles of the cone by the following:\n//   segment + 0 top vertex\n//   segment + 1 perimeter vertex a+1\n//   segment + 2 perimeter vertex a\n//   segment + 3 center base vertex\n//   segment + 4 perimeter vertex a\n//   segment + 5 perimeter vertex a+1\n// Where segment is the number of the radial segment * 6 and a is the angle at that radial segment.\n// To go from index to segment, floor(index / 6)\n// To go from segment to angle, 2*pi * (segment/segmentCount)\n// To go from index to segment index, index - (segment*6)\n//\nvec3 getConePosition(vec3 d, float rawIndex, float coneOffset, out vec3 normal) {\n\n  const float segmentCount = 8.0;\n\n  float index = rawIndex - floor(rawIndex /\n    (segmentCount * 6.0)) *\n    (segmentCount * 6.0);\n\n  float segment = floor(0.001 + index/6.0);\n  float segmentIndex = index - (segment*6.0);\n\n  normal = -normalize(d);\n\n  if (segmentIndex > 2.99 && segmentIndex < 3.01) {\n    return mix(vec3(0.0), -d, coneOffset);\n  }\n\n  float nextAngle = (\n    (segmentIndex > 0.99 &&  segmentIndex < 1.01) ||\n    (segmentIndex > 4.99 &&  segmentIndex < 5.01)\n  ) ? 1.0 : 0.0;\n  float angle = 2.0 * 3.14159 * ((segment + nextAngle) / segmentCount);\n\n  vec3 v1 = mix(d, vec3(0.0), coneOffset);\n  vec3 v2 = v1 - d;\n\n  vec3 u = getOrthogonalVector(d);\n  vec3 v = normalize(cross(u, d));\n\n  vec3 x = u * cos(angle) * length(d)*0.25;\n  vec3 y = v * sin(angle) * length(d)*0.25;\n  vec3 v3 = v2 + x + y;\n  if (segmentIndex < 3.0) {\n    vec3 tx = u * sin(angle);\n    vec3 ty = v * -cos(angle);\n    vec3 tangent = tx + ty;\n    normal = normalize(cross(v3 - v1, tangent));\n  }\n\n  if (segmentIndex == 0.0) {\n    return mix(d, vec3(0.0), coneOffset);\n  }\n  return v3;\n}\n\nattribute vec3 vector;\nattribute vec4 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\n\nuniform float vectorScale;\nuniform float coneScale;\nuniform float coneOffset;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  vec3 normal;\n  vec3 XYZ = getConePosition(mat3(model) * ((vectorScale * coneScale) * vector), position.w, coneOffset, normal);\n  vec4 conePosition = model * vec4(position.xyz, 1.0) + vec4(XYZ, 0.0);\n  gl_Position = projection * view * conePosition;\n  f_id        = id;\n  f_position  = position.xyz;\n}\n"])
var pickFragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3  clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n\n  gl_FragColor = vec4(pickId, f_id.xyz);\n}"])

exports.meshShader = {
  vertex:   triVertSrc,
  fragment: triFragSrc,
  attributes: [
    {name: 'position', type: 'vec4'},
    {name: 'normal', type: 'vec3'},
    {name: 'color', type: 'vec4'},
    {name: 'uv', type: 'vec2'},
    {name: 'vector', type: 'vec3'}
  ]
}
exports.pickShader = {
  vertex:   pickVertSrc,
  fragment: pickFragSrc,
  attributes: [
    {name: 'position', type: 'vec4'},
    {name: 'id', type: 'vec4'},
    {name: 'vector', type: 'vec3'}
  ]
}

},{"glslify":398}],238:[function(_dereq_,module,exports){
module.exports = {
  0: 'NONE',
  1: 'ONE',
  2: 'LINE_LOOP',
  3: 'LINE_STRIP',
  4: 'TRIANGLES',
  5: 'TRIANGLE_STRIP',
  6: 'TRIANGLE_FAN',
  256: 'DEPTH_BUFFER_BIT',
  512: 'NEVER',
  513: 'LESS',
  514: 'EQUAL',
  515: 'LEQUAL',
  516: 'GREATER',
  517: 'NOTEQUAL',
  518: 'GEQUAL',
  519: 'ALWAYS',
  768: 'SRC_COLOR',
  769: 'ONE_MINUS_SRC_COLOR',
  770: 'SRC_ALPHA',
  771: 'ONE_MINUS_SRC_ALPHA',
  772: 'DST_ALPHA',
  773: 'ONE_MINUS_DST_ALPHA',
  774: 'DST_COLOR',
  775: 'ONE_MINUS_DST_COLOR',
  776: 'SRC_ALPHA_SATURATE',
  1024: 'STENCIL_BUFFER_BIT',
  1028: 'FRONT',
  1029: 'BACK',
  1032: 'FRONT_AND_BACK',
  1280: 'INVALID_ENUM',
  1281: 'INVALID_VALUE',
  1282: 'INVALID_OPERATION',
  1285: 'OUT_OF_MEMORY',
  1286: 'INVALID_FRAMEBUFFER_OPERATION',
  2304: 'CW',
  2305: 'CCW',
  2849: 'LINE_WIDTH',
  2884: 'CULL_FACE',
  2885: 'CULL_FACE_MODE',
  2886: 'FRONT_FACE',
  2928: 'DEPTH_RANGE',
  2929: 'DEPTH_TEST',
  2930: 'DEPTH_WRITEMASK',
  2931: 'DEPTH_CLEAR_VALUE',
  2932: 'DEPTH_FUNC',
  2960: 'STENCIL_TEST',
  2961: 'STENCIL_CLEAR_VALUE',
  2962: 'STENCIL_FUNC',
  2963: 'STENCIL_VALUE_MASK',
  2964: 'STENCIL_FAIL',
  2965: 'STENCIL_PASS_DEPTH_FAIL',
  2966: 'STENCIL_PASS_DEPTH_PASS',
  2967: 'STENCIL_REF',
  2968: 'STENCIL_WRITEMASK',
  2978: 'VIEWPORT',
  3024: 'DITHER',
  3042: 'BLEND',
  3088: 'SCISSOR_BOX',
  3089: 'SCISSOR_TEST',
  3106: 'COLOR_CLEAR_VALUE',
  3107: 'COLOR_WRITEMASK',
  3317: 'UNPACK_ALIGNMENT',
  3333: 'PACK_ALIGNMENT',
  3379: 'MAX_TEXTURE_SIZE',
  3386: 'MAX_VIEWPORT_DIMS',
  3408: 'SUBPIXEL_BITS',
  3410: 'RED_BITS',
  3411: 'GREEN_BITS',
  3412: 'BLUE_BITS',
  3413: 'ALPHA_BITS',
  3414: 'DEPTH_BITS',
  3415: 'STENCIL_BITS',
  3553: 'TEXTURE_2D',
  4352: 'DONT_CARE',
  4353: 'FASTEST',
  4354: 'NICEST',
  5120: 'BYTE',
  5121: 'UNSIGNED_BYTE',
  5122: 'SHORT',
  5123: 'UNSIGNED_SHORT',
  5124: 'INT',
  5125: 'UNSIGNED_INT',
  5126: 'FLOAT',
  5386: 'INVERT',
  5890: 'TEXTURE',
  6401: 'STENCIL_INDEX',
  6402: 'DEPTH_COMPONENT',
  6406: 'ALPHA',
  6407: 'RGB',
  6408: 'RGBA',
  6409: 'LUMINANCE',
  6410: 'LUMINANCE_ALPHA',
  7680: 'KEEP',
  7681: 'REPLACE',
  7682: 'INCR',
  7683: 'DECR',
  7936: 'VENDOR',
  7937: 'RENDERER',
  7938: 'VERSION',
  9728: 'NEAREST',
  9729: 'LINEAR',
  9984: 'NEAREST_MIPMAP_NEAREST',
  9985: 'LINEAR_MIPMAP_NEAREST',
  9986: 'NEAREST_MIPMAP_LINEAR',
  9987: 'LINEAR_MIPMAP_LINEAR',
  10240: 'TEXTURE_MAG_FILTER',
  10241: 'TEXTURE_MIN_FILTER',
  10242: 'TEXTURE_WRAP_S',
  10243: 'TEXTURE_WRAP_T',
  10497: 'REPEAT',
  10752: 'POLYGON_OFFSET_UNITS',
  16384: 'COLOR_BUFFER_BIT',
  32769: 'CONSTANT_COLOR',
  32770: 'ONE_MINUS_CONSTANT_COLOR',
  32771: 'CONSTANT_ALPHA',
  32772: 'ONE_MINUS_CONSTANT_ALPHA',
  32773: 'BLEND_COLOR',
  32774: 'FUNC_ADD',
  32777: 'BLEND_EQUATION_RGB',
  32778: 'FUNC_SUBTRACT',
  32779: 'FUNC_REVERSE_SUBTRACT',
  32819: 'UNSIGNED_SHORT_4_4_4_4',
  32820: 'UNSIGNED_SHORT_5_5_5_1',
  32823: 'POLYGON_OFFSET_FILL',
  32824: 'POLYGON_OFFSET_FACTOR',
  32854: 'RGBA4',
  32855: 'RGB5_A1',
  32873: 'TEXTURE_BINDING_2D',
  32926: 'SAMPLE_ALPHA_TO_COVERAGE',
  32928: 'SAMPLE_COVERAGE',
  32936: 'SAMPLE_BUFFERS',
  32937: 'SAMPLES',
  32938: 'SAMPLE_COVERAGE_VALUE',
  32939: 'SAMPLE_COVERAGE_INVERT',
  32968: 'BLEND_DST_RGB',
  32969: 'BLEND_SRC_RGB',
  32970: 'BLEND_DST_ALPHA',
  32971: 'BLEND_SRC_ALPHA',
  33071: 'CLAMP_TO_EDGE',
  33170: 'GENERATE_MIPMAP_HINT',
  33189: 'DEPTH_COMPONENT16',
  33306: 'DEPTH_STENCIL_ATTACHMENT',
  33635: 'UNSIGNED_SHORT_5_6_5',
  33648: 'MIRRORED_REPEAT',
  33901: 'ALIASED_POINT_SIZE_RANGE',
  33902: 'ALIASED_LINE_WIDTH_RANGE',
  33984: 'TEXTURE0',
  33985: 'TEXTURE1',
  33986: 'TEXTURE2',
  33987: 'TEXTURE3',
  33988: 'TEXTURE4',
  33989: 'TEXTURE5',
  33990: 'TEXTURE6',
  33991: 'TEXTURE7',
  33992: 'TEXTURE8',
  33993: 'TEXTURE9',
  33994: 'TEXTURE10',
  33995: 'TEXTURE11',
  33996: 'TEXTURE12',
  33997: 'TEXTURE13',
  33998: 'TEXTURE14',
  33999: 'TEXTURE15',
  34000: 'TEXTURE16',
  34001: 'TEXTURE17',
  34002: 'TEXTURE18',
  34003: 'TEXTURE19',
  34004: 'TEXTURE20',
  34005: 'TEXTURE21',
  34006: 'TEXTURE22',
  34007: 'TEXTURE23',
  34008: 'TEXTURE24',
  34009: 'TEXTURE25',
  34010: 'TEXTURE26',
  34011: 'TEXTURE27',
  34012: 'TEXTURE28',
  34013: 'TEXTURE29',
  34014: 'TEXTURE30',
  34015: 'TEXTURE31',
  34016: 'ACTIVE_TEXTURE',
  34024: 'MAX_RENDERBUFFER_SIZE',
  34041: 'DEPTH_STENCIL',
  34055: 'INCR_WRAP',
  34056: 'DECR_WRAP',
  34067: 'TEXTURE_CUBE_MAP',
  34068: 'TEXTURE_BINDING_CUBE_MAP',
  34069: 'TEXTURE_CUBE_MAP_POSITIVE_X',
  34070: 'TEXTURE_CUBE_MAP_NEGATIVE_X',
  34071: 'TEXTURE_CUBE_MAP_POSITIVE_Y',
  34072: 'TEXTURE_CUBE_MAP_NEGATIVE_Y',
  34073: 'TEXTURE_CUBE_MAP_POSITIVE_Z',
  34074: 'TEXTURE_CUBE_MAP_NEGATIVE_Z',
  34076: 'MAX_CUBE_MAP_TEXTURE_SIZE',
  34338: 'VERTEX_ATTRIB_ARRAY_ENABLED',
  34339: 'VERTEX_ATTRIB_ARRAY_SIZE',
  34340: 'VERTEX_ATTRIB_ARRAY_STRIDE',
  34341: 'VERTEX_ATTRIB_ARRAY_TYPE',
  34342: 'CURRENT_VERTEX_ATTRIB',
  34373: 'VERTEX_ATTRIB_ARRAY_POINTER',
  34466: 'NUM_COMPRESSED_TEXTURE_FORMATS',
  34467: 'COMPRESSED_TEXTURE_FORMATS',
  34660: 'BUFFER_SIZE',
  34661: 'BUFFER_USAGE',
  34816: 'STENCIL_BACK_FUNC',
  34817: 'STENCIL_BACK_FAIL',
  34818: 'STENCIL_BACK_PASS_DEPTH_FAIL',
  34819: 'STENCIL_BACK_PASS_DEPTH_PASS',
  34877: 'BLEND_EQUATION_ALPHA',
  34921: 'MAX_VERTEX_ATTRIBS',
  34922: 'VERTEX_ATTRIB_ARRAY_NORMALIZED',
  34930: 'MAX_TEXTURE_IMAGE_UNITS',
  34962: 'ARRAY_BUFFER',
  34963: 'ELEMENT_ARRAY_BUFFER',
  34964: 'ARRAY_BUFFER_BINDING',
  34965: 'ELEMENT_ARRAY_BUFFER_BINDING',
  34975: 'VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
  35040: 'STREAM_DRAW',
  35044: 'STATIC_DRAW',
  35048: 'DYNAMIC_DRAW',
  35632: 'FRAGMENT_SHADER',
  35633: 'VERTEX_SHADER',
  35660: 'MAX_VERTEX_TEXTURE_IMAGE_UNITS',
  35661: 'MAX_COMBINED_TEXTURE_IMAGE_UNITS',
  35663: 'SHADER_TYPE',
  35664: 'FLOAT_VEC2',
  35665: 'FLOAT_VEC3',
  35666: 'FLOAT_VEC4',
  35667: 'INT_VEC2',
  35668: 'INT_VEC3',
  35669: 'INT_VEC4',
  35670: 'BOOL',
  35671: 'BOOL_VEC2',
  35672: 'BOOL_VEC3',
  35673: 'BOOL_VEC4',
  35674: 'FLOAT_MAT2',
  35675: 'FLOAT_MAT3',
  35676: 'FLOAT_MAT4',
  35678: 'SAMPLER_2D',
  35680: 'SAMPLER_CUBE',
  35712: 'DELETE_STATUS',
  35713: 'COMPILE_STATUS',
  35714: 'LINK_STATUS',
  35715: 'VALIDATE_STATUS',
  35716: 'INFO_LOG_LENGTH',
  35717: 'ATTACHED_SHADERS',
  35718: 'ACTIVE_UNIFORMS',
  35719: 'ACTIVE_UNIFORM_MAX_LENGTH',
  35720: 'SHADER_SOURCE_LENGTH',
  35721: 'ACTIVE_ATTRIBUTES',
  35722: 'ACTIVE_ATTRIBUTE_MAX_LENGTH',
  35724: 'SHADING_LANGUAGE_VERSION',
  35725: 'CURRENT_PROGRAM',
  36003: 'STENCIL_BACK_REF',
  36004: 'STENCIL_BACK_VALUE_MASK',
  36005: 'STENCIL_BACK_WRITEMASK',
  36006: 'FRAMEBUFFER_BINDING',
  36007: 'RENDERBUFFER_BINDING',
  36048: 'FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
  36049: 'FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
  36050: 'FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
  36051: 'FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
  36053: 'FRAMEBUFFER_COMPLETE',
  36054: 'FRAMEBUFFER_INCOMPLETE_ATTACHMENT',
  36055: 'FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT',
  36057: 'FRAMEBUFFER_INCOMPLETE_DIMENSIONS',
  36061: 'FRAMEBUFFER_UNSUPPORTED',
  36064: 'COLOR_ATTACHMENT0',
  36096: 'DEPTH_ATTACHMENT',
  36128: 'STENCIL_ATTACHMENT',
  36160: 'FRAMEBUFFER',
  36161: 'RENDERBUFFER',
  36162: 'RENDERBUFFER_WIDTH',
  36163: 'RENDERBUFFER_HEIGHT',
  36164: 'RENDERBUFFER_INTERNAL_FORMAT',
  36168: 'STENCIL_INDEX8',
  36176: 'RENDERBUFFER_RED_SIZE',
  36177: 'RENDERBUFFER_GREEN_SIZE',
  36178: 'RENDERBUFFER_BLUE_SIZE',
  36179: 'RENDERBUFFER_ALPHA_SIZE',
  36180: 'RENDERBUFFER_DEPTH_SIZE',
  36181: 'RENDERBUFFER_STENCIL_SIZE',
  36194: 'RGB565',
  36336: 'LOW_FLOAT',
  36337: 'MEDIUM_FLOAT',
  36338: 'HIGH_FLOAT',
  36339: 'LOW_INT',
  36340: 'MEDIUM_INT',
  36341: 'HIGH_INT',
  36346: 'SHADER_COMPILER',
  36347: 'MAX_VERTEX_UNIFORM_VECTORS',
  36348: 'MAX_VARYING_VECTORS',
  36349: 'MAX_FRAGMENT_UNIFORM_VECTORS',
  37440: 'UNPACK_FLIP_Y_WEBGL',
  37441: 'UNPACK_PREMULTIPLY_ALPHA_WEBGL',
  37442: 'CONTEXT_LOST_WEBGL',
  37443: 'UNPACK_COLORSPACE_CONVERSION_WEBGL',
  37444: 'BROWSER_DEFAULT_WEBGL'
}

},{}],239:[function(_dereq_,module,exports){
var gl10 = _dereq_('./1.0/numbers')

module.exports = function lookupConstant (number) {
  return gl10[number]
}

},{"./1.0/numbers":238}],240:[function(_dereq_,module,exports){
'use strict'

module.exports = createErrorBars

var createBuffer  = _dereq_('gl-buffer')
var createVAO     = _dereq_('gl-vao')
var createShader  = _dereq_('./shaders/index')

var IDENTITY = [1,0,0,0,
                0,1,0,0,
                0,0,1,0,
                0,0,0,1]

function ErrorBars(gl, buffer, vao, shader) {
  this.gl           = gl
  this.shader       = shader
  this.buffer       = buffer
  this.vao          = vao
  this.pixelRatio   = 1
  this.bounds       = [[ Infinity, Infinity, Infinity], [-Infinity,-Infinity,-Infinity]]
  this.clipBounds   = [[-Infinity,-Infinity,-Infinity], [ Infinity, Infinity, Infinity]]
  this.lineWidth    = [1,1,1]
  this.capSize      = [10,10,10]
  this.lineCount    = [0,0,0]
  this.lineOffset   = [0,0,0]
  this.opacity      = 1
  this.hasAlpha     = false
}

var proto = ErrorBars.prototype

proto.isOpaque = function() {
  return !this.hasAlpha
}

proto.isTransparent = function() {
  return this.hasAlpha
}

proto.drawTransparent = proto.draw = function(cameraParams) {
  var gl = this.gl
  var uniforms        = this.shader.uniforms

  this.shader.bind()
  var view       = uniforms.view       = cameraParams.view       || IDENTITY
  var projection = uniforms.projection = cameraParams.projection || IDENTITY
  uniforms.model      = cameraParams.model      || IDENTITY
  uniforms.clipBounds = this.clipBounds
  uniforms.opacity    = this.opacity


  var cx = view[12]
  var cy = view[13]
  var cz = view[14]
  var cw = view[15]

  var isOrtho = cameraParams._ortho || false
  var orthoFix = (isOrtho) ? 2 : 1 // double up padding for orthographic ticks & labels
  var pixelScaleF = orthoFix * this.pixelRatio * (projection[3]*cx + projection[7]*cy + projection[11]*cz + projection[15]*cw) / gl.drawingBufferHeight

  this.vao.bind()
  for(var i=0; i<3; ++i) {
    gl.lineWidth(this.lineWidth[i] * this.pixelRatio)
    uniforms.capSize = this.capSize[i] * pixelScaleF
    if (this.lineCount[i]) {
      gl.drawArrays(gl.LINES, this.lineOffset[i], this.lineCount[i])
    }
  }
  this.vao.unbind()
}

function updateBounds(bounds, point) {
  for(var i=0; i<3; ++i) {
    bounds[0][i] = Math.min(bounds[0][i], point[i])
    bounds[1][i] = Math.max(bounds[1][i], point[i])
  }
}

var FACE_TABLE = (function(){
  var table = new Array(3)
  for(var d=0; d<3; ++d) {
    var row = []
    for(var j=1; j<=2; ++j) {
      for(var s=-1; s<=1; s+=2) {
        var u = (j+d) % 3
        var y = [0,0,0]
        y[u] = s
        row.push(y)
      }
    }
    table[d] = row
  }
  return table
})()


function emitFace(verts, x, c, d) {
  var offsets = FACE_TABLE[d]
  for(var i=0; i<offsets.length; ++i) {
    var o = offsets[i]
    verts.push(x[0], x[1], x[2],
               c[0], c[1], c[2], c[3],
               o[0], o[1], o[2])
  }
  return offsets.length
}

proto.update = function(options) {
  options = options || {}

  if('lineWidth' in options) {
    this.lineWidth = options.lineWidth
    if(!Array.isArray(this.lineWidth)) {
      this.lineWidth = [this.lineWidth, this.lineWidth, this.lineWidth]
    }
  }
  if('capSize' in options) {
    this.capSize = options.capSize
    if(!Array.isArray(this.capSize)) {
      this.capSize = [this.capSize, this.capSize, this.capSize]
    }
  }

  this.hasAlpha = false // default to no transparent draw
  if('opacity' in options) {
    this.opacity = +options.opacity
    if(this.opacity < 1) {
      this.hasAlpha = true;
    }
  }

  var color    = options.color || [[0,0,0],[0,0,0],[0,0,0]]
  var position = options.position
  var error    = options.error
  if(!Array.isArray(color[0])) {
    color = [color,color,color]
  }

  if(position && error) {

    var verts       = []
    var n           = position.length
    var vertexCount = 0
    this.bounds     = [[ Infinity, Infinity, Infinity],
                       [-Infinity,-Infinity,-Infinity]]
    this.lineCount  = [0,0,0]

    //Build geometry for lines
    for(var j=0; j<3; ++j) {
      this.lineOffset[j] = vertexCount

i_loop:
      for(var i=0; i<n; ++i) {
        var p = position[i]

        for(var k=0; k<3; ++k) {
          if(isNaN(p[k]) || !isFinite(p[k])) {
            continue i_loop
          }
        }

        var e = error[i]
        var c = color[j]
        if(Array.isArray(c[0])) {
          c = color[i]
        }
        if(c.length === 3) {
          c = [c[0], c[1], c[2], 1]
        } else if(c.length === 4) {
          c = [c[0], c[1], c[2], c[3]]
          if(!this.hasAlpha && c[3] < 1) this.hasAlpha = true
        }

        if(isNaN(e[0][j]) || isNaN(e[1][j])) {
          continue
        }
        if(e[0][j] < 0) {
          var x = p.slice()
          x[j] += e[0][j]
          verts.push(p[0], p[1], p[2],
                     c[0], c[1], c[2], c[3],
                        0,    0,    0,
                     x[0], x[1], x[2],
                     c[0], c[1], c[2], c[3],
                        0,    0,    0)
          updateBounds(this.bounds, x)
          vertexCount += 2 + emitFace(verts, x, c, j)
        }
        if(e[1][j] > 0) {
          var x = p.slice()
          x[j] += e[1][j]
          verts.push(p[0], p[1], p[2],
                     c[0], c[1], c[2], c[3],
                        0,    0,    0,
                     x[0], x[1], x[2],
                     c[0], c[1], c[2], c[3],
                        0,    0,    0)
          updateBounds(this.bounds, x)
          vertexCount += 2 + emitFace(verts, x, c, j)
        }
      }
      this.lineCount[j] = vertexCount - this.lineOffset[j]
    }
    this.buffer.update(verts)
  }
}

proto.dispose = function() {
  this.shader.dispose()
  this.buffer.dispose()
  this.vao.dispose()
}

function createErrorBars(options) {
  var gl = options.gl
  var buffer = createBuffer(gl)
  var vao = createVAO(gl, [
      {
        buffer: buffer,
        type:   gl.FLOAT,
        size:   3,
        offset: 0,
        stride: 40
      },
      {
        buffer: buffer,
        type:   gl.FLOAT,
        size:   4,
        offset: 12,
        stride: 40
      },
      {
        buffer: buffer,
        type:   gl.FLOAT,
        size:   3,
        offset: 28,
        stride: 40
      }
    ])

  var shader = createShader(gl)
  shader.attributes.position.location = 0
  shader.attributes.color.location    = 1
  shader.attributes.offset.location   = 2

  var result = new ErrorBars(gl, buffer, vao, shader)
  result.update(options)
  return result
}

},{"./shaders/index":241,"gl-buffer":234,"gl-vao":316}],241:[function(_dereq_,module,exports){
'use strict'

var glslify = _dereq_('glslify')
var createShader = _dereq_('gl-shader')

var vertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, offset;\nattribute vec4 color;\nuniform mat4 model, view, projection;\nuniform float capSize;\nvarying vec4 fragColor;\nvarying vec3 fragPosition;\n\nvoid main() {\n  vec4 worldPosition  = model * vec4(position, 1.0);\n  worldPosition       = (worldPosition / worldPosition.w) + vec4(capSize * offset, 0.0);\n  gl_Position         = projection * view * worldPosition;\n  fragColor           = color;\n  fragPosition        = position;\n}"])
var fragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform float opacity;\nvarying vec3 fragPosition;\nvarying vec4 fragColor;\n\nvoid main() {\n  if (\n    outOfRange(clipBounds[0], clipBounds[1], fragPosition) ||\n    fragColor.a * opacity == 0.\n  ) discard;\n\n  gl_FragColor = opacity * fragColor;\n}"])

module.exports = function(gl) {
  return createShader(gl, vertSrc, fragSrc, null, [
    {name: 'position', type: 'vec3'},
    {name: 'color', type: 'vec4'},
    {name: 'offset', type: 'vec3'}
  ])
}

},{"gl-shader":294,"glslify":398}],242:[function(_dereq_,module,exports){
'use strict'

var createTexture = _dereq_('gl-texture2d')

module.exports = createFBO

var colorAttachmentArrays = null
var FRAMEBUFFER_UNSUPPORTED
var FRAMEBUFFER_INCOMPLETE_ATTACHMENT
var FRAMEBUFFER_INCOMPLETE_DIMENSIONS
var FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT

function saveFBOState(gl) {
  var fbo = gl.getParameter(gl.FRAMEBUFFER_BINDING)
  var rbo = gl.getParameter(gl.RENDERBUFFER_BINDING)
  var tex = gl.getParameter(gl.TEXTURE_BINDING_2D)
  return [fbo, rbo, tex]
}

function restoreFBOState(gl, data) {
  gl.bindFramebuffer(gl.FRAMEBUFFER, data[0])
  gl.bindRenderbuffer(gl.RENDERBUFFER, data[1])
  gl.bindTexture(gl.TEXTURE_2D, data[2])
}

function lazyInitColorAttachments(gl, ext) {
  var maxColorAttachments = gl.getParameter(ext.MAX_COLOR_ATTACHMENTS_WEBGL)
  colorAttachmentArrays = new Array(maxColorAttachments + 1)
  for(var i=0; i<=maxColorAttachments; ++i) {
    var x = new Array(maxColorAttachments)
    for(var j=0; j<i; ++j) {
      x[j] = gl.COLOR_ATTACHMENT0 + j
    }
    for(var j=i; j<maxColorAttachments; ++j) {
      x[j] = gl.NONE
    }
    colorAttachmentArrays[i] = x
  }
}

//Throw an appropriate error
function throwFBOError(status) {
  switch(status){
    case FRAMEBUFFER_UNSUPPORTED:
      throw new Error('gl-fbo: Framebuffer unsupported')
    case FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
      throw new Error('gl-fbo: Framebuffer incomplete attachment')
    case FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
      throw new Error('gl-fbo: Framebuffer incomplete dimensions')
    case FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
      throw new Error('gl-fbo: Framebuffer incomplete missing attachment')
    default:
      throw new Error('gl-fbo: Framebuffer failed for unspecified reason')
  }
}

//Initialize a texture object
function initTexture(gl, width, height, type, format, attachment) {
  if(!type) {
    return null
  }
  var result = createTexture(gl, width, height, format, type)
  result.magFilter = gl.NEAREST
  result.minFilter = gl.NEAREST
  result.mipSamples = 1
  result.bind()
  gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, result.handle, 0)
  return result
}

//Initialize a render buffer object
function initRenderBuffer(gl, width, height, component, attachment) {
  var result = gl.createRenderbuffer()
  gl.bindRenderbuffer(gl.RENDERBUFFER, result)
  gl.renderbufferStorage(gl.RENDERBUFFER, component, width, height)
  gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, result)
  return result
}

//Rebuild the frame buffer
function rebuildFBO(fbo) {

  //Save FBO state
  var state = saveFBOState(fbo.gl)

  var gl = fbo.gl
  var handle = fbo.handle = gl.createFramebuffer()
  var width = fbo._shape[0]
  var height = fbo._shape[1]
  var numColors = fbo.color.length
  var ext = fbo._ext
  var useStencil = fbo._useStencil
  var useDepth = fbo._useDepth
  var colorType = fbo._colorType

  //Bind the fbo
  gl.bindFramebuffer(gl.FRAMEBUFFER, handle)

  //Allocate color buffers
  for(var i=0; i<numColors; ++i) {
    fbo.color[i] = initTexture(gl, width, height, colorType, gl.RGBA, gl.COLOR_ATTACHMENT0 + i)
  }
  if(numColors === 0) {
    fbo._color_rb = initRenderBuffer(gl, width, height, gl.RGBA4, gl.COLOR_ATTACHMENT0)
    if(ext) {
      ext.drawBuffersWEBGL(colorAttachmentArrays[0])
    }
  } else if(numColors > 1) {
    ext.drawBuffersWEBGL(colorAttachmentArrays[numColors])
  }

  //Allocate depth/stencil buffers
  var WEBGL_depth_texture = gl.getExtension('WEBGL_depth_texture')
  if(WEBGL_depth_texture) {
    if(useStencil) {
      fbo.depth = initTexture(gl, width, height,
                          WEBGL_depth_texture.UNSIGNED_INT_24_8_WEBGL,
                          gl.DEPTH_STENCIL,
                          gl.DEPTH_STENCIL_ATTACHMENT)
    } else if(useDepth) {
      fbo.depth = initTexture(gl, width, height,
                          gl.UNSIGNED_SHORT,
                          gl.DEPTH_COMPONENT,
                          gl.DEPTH_ATTACHMENT)
    }
  } else {
    if(useDepth && useStencil) {
      fbo._depth_rb = initRenderBuffer(gl, width, height, gl.DEPTH_STENCIL, gl.DEPTH_STENCIL_ATTACHMENT)
    } else if(useDepth) {
      fbo._depth_rb = initRenderBuffer(gl, width, height, gl.DEPTH_COMPONENT16, gl.DEPTH_ATTACHMENT)
    } else if(useStencil) {
      fbo._depth_rb = initRenderBuffer(gl, width, height, gl.STENCIL_INDEX, gl.STENCIL_ATTACHMENT)
    }
  }

  //Check frame buffer state
  var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER)
  if(status !== gl.FRAMEBUFFER_COMPLETE) {

    //Release all partially allocated resources
    fbo._destroyed = true

    //Release all resources
    gl.bindFramebuffer(gl.FRAMEBUFFER, null)
    gl.deleteFramebuffer(fbo.handle)
    fbo.handle = null
    if(fbo.depth) {
      fbo.depth.dispose()
      fbo.depth = null
    }
    if(fbo._depth_rb) {
      gl.deleteRenderbuffer(fbo._depth_rb)
      fbo._depth_rb = null
    }
    for(var i=0; i<fbo.color.length; ++i) {
      fbo.color[i].dispose()
      fbo.color[i] = null
    }
    if(fbo._color_rb) {
      gl.deleteRenderbuffer(fbo._color_rb)
      fbo._color_rb = null
    }

    restoreFBOState(gl, state)

    //Throw the frame buffer error
    throwFBOError(status)
  }

  //Everything ok, let's get on with life
  restoreFBOState(gl, state)
}

function Framebuffer(gl, width, height, colorType, numColors, useDepth, useStencil, ext) {

  //Handle and set properties
  this.gl = gl
  this._shape = [width|0, height|0]
  this._destroyed = false
  this._ext = ext

  //Allocate buffers
  this.color = new Array(numColors)
  for(var i=0; i<numColors; ++i) {
    this.color[i] = null
  }
  this._color_rb = null
  this.depth = null
  this._depth_rb = null

  //Save depth and stencil flags
  this._colorType = colorType
  this._useDepth = useDepth
  this._useStencil = useStencil

  //Shape vector for resizing
  var parent = this
  var shapeVector = [width|0, height|0]
  Object.defineProperties(shapeVector, {
    0: {
      get: function() {
        return parent._shape[0]
      },
      set: function(w) {
        return parent.width = w
      }
    },
    1: {
      get: function() {
        return parent._shape[1]
      },
      set: function(h) {
        return parent.height = h
      }
    }
  })
  this._shapeVector = shapeVector

  //Initialize all attachments
  rebuildFBO(this)
}

var proto = Framebuffer.prototype

function reshapeFBO(fbo, w, h) {
  //If fbo is invalid, just skip this
  if(fbo._destroyed) {
    throw new Error('gl-fbo: Can\'t resize destroyed FBO')
  }

  //Don't resize if no change in shape
  if( (fbo._shape[0] === w) &&
      (fbo._shape[1] === h) ) {
    return
  }

  var gl = fbo.gl

  //Check parameter ranges
  var maxFBOSize = gl.getParameter(gl.MAX_RENDERBUFFER_SIZE)
  if( w < 0 || w > maxFBOSize ||
      h < 0 || h > maxFBOSize) {
    throw new Error('gl-fbo: Can\'t resize FBO, invalid dimensions')
  }

  //Update shape
  fbo._shape[0] = w
  fbo._shape[1] = h

  //Save framebuffer state
  var state = saveFBOState(gl)

  //Resize framebuffer attachments
  for(var i=0; i<fbo.color.length; ++i) {
    fbo.color[i].shape = fbo._shape
  }
  if(fbo._color_rb) {
    gl.bindRenderbuffer(gl.RENDERBUFFER, fbo._color_rb)
    gl.renderbufferStorage(gl.RENDERBUFFER, gl.RGBA4, fbo._shape[0], fbo._shape[1])
  }
  if(fbo.depth) {
    fbo.depth.shape = fbo._shape
  }
  if(fbo._depth_rb) {
    gl.bindRenderbuffer(gl.RENDERBUFFER, fbo._depth_rb)
    if(fbo._useDepth && fbo._useStencil) {
      gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, fbo._shape[0], fbo._shape[1])
    } else if(fbo._useDepth) {
      gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, fbo._shape[0], fbo._shape[1])
    } else if(fbo._useStencil) {
      gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX, fbo._shape[0], fbo._shape[1])
    }
  }

  //Check FBO status after resize, if something broke then die in a fire
  gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.handle)
  var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER)
  if(status !== gl.FRAMEBUFFER_COMPLETE) {
    fbo.dispose()
    restoreFBOState(gl, state)
    throwFBOError(status)
  }

  //Restore framebuffer state
  restoreFBOState(gl, state)
}

Object.defineProperties(proto, {
  'shape': {
    get: function() {
      if(this._destroyed) {
        return [0,0]
      }
      return this._shapeVector
    },
    set: function(x) {
      if(!Array.isArray(x)) {
        x = [x|0, x|0]
      }
      if(x.length !== 2) {
        throw new Error('gl-fbo: Shape vector must be length 2')
      }

      var w = x[0]|0
      var h = x[1]|0
      reshapeFBO(this, w, h)

      return [w, h]
    },
    enumerable: false
  },
  'width': {
    get: function() {
      if(this._destroyed) {
        return 0
      }
      return this._shape[0]
    },
    set: function(w) {
      w = w|0
      reshapeFBO(this, w, this._shape[1])
      return w
    },
    enumerable: false
  },
  'height': {
    get: function() {
      if(this._destroyed) {
        return 0
      }
      return this._shape[1]
    },
    set: function(h) {
      h = h|0
      reshapeFBO(this, this._shape[0], h)
      return h
    },
    enumerable: false
  }
})

proto.bind = function() {
  if(this._destroyed) {
    return
  }
  var gl = this.gl
  gl.bindFramebuffer(gl.FRAMEBUFFER, this.handle)
  gl.viewport(0, 0, this._shape[0], this._shape[1])
}

proto.dispose = function() {
  if(this._destroyed) {
    return
  }
  this._destroyed = true
  var gl = this.gl
  gl.deleteFramebuffer(this.handle)
  this.handle = null
  if(this.depth) {
    this.depth.dispose()
    this.depth = null
  }
  if(this._depth_rb) {
    gl.deleteRenderbuffer(this._depth_rb)
    this._depth_rb = null
  }
  for(var i=0; i<this.color.length; ++i) {
    this.color[i].dispose()
    this.color[i] = null
  }
  if(this._color_rb) {
    gl.deleteRenderbuffer(this._color_rb)
    this._color_rb = null
  }
}

function createFBO(gl, width, height, options) {

  //Update frame buffer error code values
  if(!FRAMEBUFFER_UNSUPPORTED) {
    FRAMEBUFFER_UNSUPPORTED = gl.FRAMEBUFFER_UNSUPPORTED
    FRAMEBUFFER_INCOMPLETE_ATTACHMENT = gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT
    FRAMEBUFFER_INCOMPLETE_DIMENSIONS = gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS
    FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT
  }

  //Lazily initialize color attachment arrays
  var WEBGL_draw_buffers = gl.getExtension('WEBGL_draw_buffers')
  if(!colorAttachmentArrays && WEBGL_draw_buffers) {
    lazyInitColorAttachments(gl, WEBGL_draw_buffers)
  }

  //Special case: Can accept an array as argument
  if(Array.isArray(width)) {
    options = height
    height = width[1]|0
    width = width[0]|0
  }

  if(typeof width !== 'number') {
    throw new Error('gl-fbo: Missing shape parameter')
  }

  //Validate width/height properties
  var maxFBOSize = gl.getParameter(gl.MAX_RENDERBUFFER_SIZE)
  if(width < 0 || width > maxFBOSize || height < 0 || height > maxFBOSize) {
    throw new Error('gl-fbo: Parameters are too large for FBO')
  }

  //Handle each option type
  options = options || {}

  //Figure out number of color buffers to use
  var numColors = 1
  if('color' in options) {
    numColors = Math.max(options.color|0, 0)
    if(numColors < 0) {
      throw new Error('gl-fbo: Must specify a nonnegative number of colors')
    }
    if(numColors > 1) {
      //Check if multiple render targets supported
      if(!WEBGL_draw_buffers) {
        throw new Error('gl-fbo: Multiple draw buffer extension not supported')
      } else if(numColors > gl.getParameter(WEBGL_draw_buffers.MAX_COLOR_ATTACHMENTS_WEBGL)) {
        throw new Error('gl-fbo: Context does not support ' + numColors + ' draw buffers')
      }
    }
  }

  //Determine whether to use floating point textures
  var colorType = gl.UNSIGNED_BYTE
  var OES_texture_float = gl.getExtension('OES_texture_float')
  if(options.float && numColors > 0) {
    if(!OES_texture_float) {
      throw new Error('gl-fbo: Context does not support floating point textures')
    }
    colorType = gl.FLOAT
  } else if(options.preferFloat && numColors > 0) {
    if(OES_texture_float) {
      colorType = gl.FLOAT
    }
  }

  //Check if we should use depth buffer
  var useDepth = true
  if('depth' in options) {
    useDepth = !!options.depth
  }

  //Check if we should use a stencil buffer
  var useStencil = false
  if('stencil' in options) {
    useStencil = !!options.stencil
  }

  return new Framebuffer(
    gl,
    width,
    height,
    colorType,
    numColors,
    useDepth,
    useStencil,
    WEBGL_draw_buffers)
}

},{"gl-texture2d":311}],243:[function(_dereq_,module,exports){

var sprintf = _dereq_('sprintf-js').sprintf;
var glConstants = _dereq_('gl-constants/lookup');
var shaderName = _dereq_('glsl-shader-name');
var addLineNumbers = _dereq_('add-line-numbers');

module.exports = formatCompilerError;

function formatCompilerError(errLog, src, type) {
    "use strict";

    var name = shaderName(src) || 'of unknown name (see npm glsl-shader-name)';

    var typeName = 'unknown type';
    if (type !== undefined) {
        typeName = type === glConstants.FRAGMENT_SHADER ? 'fragment' : 'vertex'
    }

    var longForm = sprintf('Error compiling %s shader %s:\n', typeName, name);
    var shortForm = sprintf("%s%s", longForm, errLog);

    var errorStrings = errLog.split('\n');
    var errors = {};

    for (var i = 0; i < errorStrings.length; i++) {
        var errorString = errorStrings[i];
        if (errorString === '' || errorString === "\0") continue;
        var lineNo = parseInt(errorString.split(':')[2]);
        if (isNaN(lineNo)) {
            throw new Error(sprintf('Could not parse error: %s', errorString));
        }
        errors[lineNo] = errorString;
    }

    var lines = addLineNumbers(src).split('\n');

    for (var i = 0; i < lines.length; i++) {
        if (!errors[i+3] && !errors[i+2] && !errors[i+1]) continue;
        var line = lines[i];
        longForm += line + '\n';
        if (errors[i+1]) {
            var e = errors[i+1];
            e = e.substr(e.split(':', 3).join(':').length + 1).trim();
            longForm += sprintf('^^^ %s\n\n', e);
        }
    }

    return {
        long: longForm.trim(),
        short: shortForm.trim()
    };
}


},{"add-line-numbers":49,"gl-constants/lookup":239,"glsl-shader-name":390,"sprintf-js":509}],244:[function(_dereq_,module,exports){
'use strict'

module.exports = createHeatmap2D

var bsearch = _dereq_('binary-search-bounds')
var iota = _dereq_('iota-array')
var pool = _dereq_('typedarray-pool')
var createShader = _dereq_('gl-shader')
var createBuffer = _dereq_('gl-buffer')

var shaders = _dereq_('./lib/shaders')

function GLHeatmap2D (
  plot,
  shader,
  pickShader,
  positionBuffer,
  weightBuffer,
  colorBuffer,
  idBuffer) {
  this.plot = plot
  this.shader = shader
  this.pickShader = pickShader
  this.positionBuffer = positionBuffer
  this.weightBuffer = weightBuffer
  this.colorBuffer = colorBuffer
  this.idBuffer = idBuffer
  this.xData = []
  this.yData = []
  this.shape = [0, 0]
  this.bounds = [Infinity, Infinity, -Infinity, -Infinity]
  this.pickOffset = 0
}

var proto = GLHeatmap2D.prototype

var WEIGHTS = [
  0, 0,
  1, 0,
  0, 1,
  1, 0,
  1, 1,
  0, 1
]

proto.draw = (function () {
  var MATRIX = [
    1, 0, 0,
    0, 1, 0,
    0, 0, 1
  ]

  return function () {
    var plot = this.plot
    var shader = this.shader
    var bounds = this.bounds
    var numVertices = this.numVertices

    if (numVertices <= 0) {
      return
    }

    var gl = plot.gl
    var dataBox = plot.dataBox

    var boundX = bounds[2] - bounds[0]
    var boundY = bounds[3] - bounds[1]
    var dataX = dataBox[2] - dataBox[0]
    var dataY = dataBox[3] - dataBox[1]

    MATRIX[0] = 2.0 * boundX / dataX
    MATRIX[4] = 2.0 * boundY / dataY
    MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0
    MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0

    shader.bind()

    var uniforms = shader.uniforms
    uniforms.viewTransform = MATRIX

    uniforms.shape = this.shape

    var attributes = shader.attributes
    this.positionBuffer.bind()
    attributes.position.pointer()

    this.weightBuffer.bind()
    attributes.weight.pointer(gl.UNSIGNED_BYTE, false)

    this.colorBuffer.bind()
    attributes.color.pointer(gl.UNSIGNED_BYTE, true)

    gl.drawArrays(gl.TRIANGLES, 0, numVertices)
  }
})()

proto.drawPick = (function () {
  var MATRIX = [
    1, 0, 0,
    0, 1, 0,
    0, 0, 1
  ]

  var PICK_VECTOR = [0, 0, 0, 0]

  return function (pickOffset) {
    var plot = this.plot
    var shader = this.pickShader
    var bounds = this.bounds
    var numVertices = this.numVertices

    if (numVertices <= 0) {
      return
    }

    var gl = plot.gl
    var dataBox = plot.dataBox

    var boundX = bounds[2] - bounds[0]
    var boundY = bounds[3] - bounds[1]
    var dataX = dataBox[2] - dataBox[0]
    var dataY = dataBox[3] - dataBox[1]

    MATRIX[0] = 2.0 * boundX / dataX
    MATRIX[4] = 2.0 * boundY / dataY
    MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0
    MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0

    for (var i = 0; i < 4; ++i) {
      PICK_VECTOR[i] = (pickOffset >> (i * 8)) & 0xff
    }

    this.pickOffset = pickOffset

    shader.bind()

    var uniforms = shader.uniforms
    uniforms.viewTransform = MATRIX
    uniforms.pickOffset = PICK_VECTOR
    uniforms.shape = this.shape

    var attributes = shader.attributes
    this.positionBuffer.bind()
    attributes.position.pointer()

    this.weightBuffer.bind()
    attributes.weight.pointer(gl.UNSIGNED_BYTE, false)

    this.idBuffer.bind()
    attributes.pickId.pointer(gl.UNSIGNED_BYTE, false)

    gl.drawArrays(gl.TRIANGLES, 0, numVertices)

    return pickOffset + this.shape[0] * this.shape[1]
  }
})()

proto.pick = function (x, y, value) {
  var pickOffset = this.pickOffset
  var pointCount = this.shape[0] * this.shape[1]
  if (value < pickOffset || value >= pickOffset + pointCount) {
    return null
  }
  var pointId = value - pickOffset
  var xData = this.xData
  var yData = this.yData
  return {
    object: this,
    pointId: pointId,
    dataCoord: [
      xData[pointId % this.shape[0]],
      yData[(pointId / this.shape[0]) | 0]]
  }
}

proto.update = function (options) {
  options = options || {}

  var shape = options.shape || [0, 0]

  var x = options.x || iota(shape[0])
  var y = options.y || iota(shape[1])
  var z = options.z || new Float32Array(shape[0] * shape[1])

  this.xData = x
  this.yData = y

  var colorLevels = options.colorLevels || [0]
  var colorValues = options.colorValues || [0, 0, 0, 1]
  var colorCount = colorLevels.length

  var bounds = this.bounds
  var lox = bounds[0] = x[0]
  var loy = bounds[1] = y[0]
  var hix = bounds[2] = x[x.length - 1]
  var hiy = bounds[3] = y[y.length - 1]

  var xs = 1.0 / (hix - lox)
  var ys = 1.0 / (hiy - loy)

  var numX = shape[0]
  var numY = shape[1]

  this.shape = [numX, numY]

  var numVerts = (numX - 1) * (numY - 1) * (WEIGHTS.length >>> 1)

  this.numVertices = numVerts

  var colors = pool.mallocUint8(numVerts * 4)
  var positions = pool.mallocFloat32(numVerts * 2)
  var weights   = pool.mallocUint8 (numVerts * 2)
  var ids = pool.mallocUint32(numVerts)

  var ptr = 0

  for (var j = 0; j < numY - 1; ++j) {
    var yc0 = ys * (y[j] - loy)
    var yc1 = ys * (y[j + 1] - loy)
    for (var i = 0; i < numX - 1; ++i) {
      var xc0 = xs * (x[i] - lox)
      var xc1 = xs * (x[i + 1] - lox)

      for (var dd = 0; dd < WEIGHTS.length; dd += 2) {
        var dx = WEIGHTS[dd]
        var dy = WEIGHTS[dd + 1]
        var offset = (j + dy) * numX + (i + dx)
        var zc = z[offset]
        var colorIdx = bsearch.le(colorLevels, zc)
        var r, g, b, a
        if (colorIdx < 0) {
          r = colorValues[0]
          g = colorValues[1]
          b = colorValues[2]
          a = colorValues[3]
        } else if (colorIdx === colorCount - 1) {
          r = colorValues[4 * colorCount - 4]
          g = colorValues[4 * colorCount - 3]
          b = colorValues[4 * colorCount - 2]
          a = colorValues[4 * colorCount - 1]
        } else {
          var t = (zc - colorLevels[colorIdx]) /
            (colorLevels[colorIdx + 1] - colorLevels[colorIdx])
          var ti = 1.0 - t
          var i0 = 4 * colorIdx
          var i1 = 4 * (colorIdx + 1)
          r = ti * colorValues[i0] + t * colorValues[i1]
          g = ti * colorValues[i0 + 1] + t * colorValues[i1 + 1]
          b = ti * colorValues[i0 + 2] + t * colorValues[i1 + 2]
          a = ti * colorValues[i0 + 3] + t * colorValues[i1 + 3]
        }

        colors[4 * ptr] = 255 * r
        colors[4 * ptr + 1] = 255 * g
        colors[4 * ptr + 2] = 255 * b
        colors[4 * ptr + 3] = 255 * a

        positions[2*ptr] = xc0*.5 + xc1*.5;
        positions[2*ptr+1] = yc0*.5 + yc1*.5;

        weights[2*ptr] = dx;
        weights[2*ptr+1] = dy;

        ids[ptr] = j * numX + i

        ptr += 1
      }
    }
  }

  this.positionBuffer.update(positions)
  this.weightBuffer.update(weights)
  this.colorBuffer.update(colors)
  this.idBuffer.update(ids)

  pool.free(positions)
  pool.free(colors)
  pool.free(weights)
  pool.free(ids)
}

proto.dispose = function () {
  this.shader.dispose()
  this.pickShader.dispose()
  this.positionBuffer.dispose()
  this.weightBuffer.dispose()
  this.colorBuffer.dispose()
  this.idBuffer.dispose()
  this.plot.removeObject(this)
}

function createHeatmap2D (plot, options) {
  var gl = plot.gl

  var shader = createShader(gl, shaders.vertex, shaders.fragment)
  var pickShader = createShader(gl, shaders.pickVertex, shaders.pickFragment)

  var positionBuffer = createBuffer(gl)
  var weightBuffer   = createBuffer(gl)
  var colorBuffer = createBuffer(gl)
  var idBuffer = createBuffer(gl)

  var heatmap = new GLHeatmap2D(
    plot,
    shader,
    pickShader,
    positionBuffer,
    weightBuffer,
    colorBuffer,
    idBuffer)

  heatmap.update(options)
  plot.addObject(heatmap)

  return heatmap
}

},{"./lib/shaders":245,"binary-search-bounds":246,"gl-buffer":234,"gl-shader":294,"iota-array":405,"typedarray-pool":526}],245:[function(_dereq_,module,exports){
'use strict'

var glslify = _dereq_('glslify')

module.exports = {
  fragment:     glslify(["precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n  gl_FragColor = vec4(fragColor.rgb * fragColor.a, fragColor.a);\n}\n"]),
  vertex:       glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 color;\nattribute vec2 weight;\n\nuniform vec2 shape;\nuniform mat3 viewTransform;\n\nvarying vec4 fragColor;\n\nvoid main() {\n  vec3 vPosition = viewTransform * vec3( position + (weight-.5)/(shape-1.) , 1.0);\n  fragColor = color;\n  gl_Position = vec4(vPosition.xy, 0, vPosition.z);\n}\n"]),
  pickFragment: glslify(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragId;\nvarying vec2 vWeight;\n\nuniform vec2 shape;\nuniform vec4 pickOffset;\n\nvoid main() {\n  vec2 d = step(.5, vWeight);\n  vec4 id = fragId + pickOffset;\n  id.x += d.x + d.y*shape.x;\n\n  id.y += floor(id.x / 256.0);\n  id.x -= floor(id.x / 256.0) * 256.0;\n\n  id.z += floor(id.y / 256.0);\n  id.y -= floor(id.y / 256.0) * 256.0;\n\n  id.w += floor(id.z / 256.0);\n  id.z -= floor(id.z / 256.0) * 256.0;\n\n  gl_FragColor = id/255.;\n}\n"]),
  pickVertex:   glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 pickId;\nattribute vec2 weight;\n\nuniform vec2 shape;\nuniform mat3 viewTransform;\n\nvarying vec4 fragId;\nvarying vec2 vWeight;\n\nvoid main() {\n  vWeight = weight;\n\n  fragId = pickId;\n\n  vec3 vPosition = viewTransform * vec3( position + (weight-.5)/(shape-1.) , 1.0);\n  gl_Position = vec4(vPosition.xy, 0, vPosition.z);\n}\n"])
}

},{"glslify":398}],246:[function(_dereq_,module,exports){
arguments[4][99][0].apply(exports,arguments)
},{"dup":99}],247:[function(_dereq_,module,exports){
var glslify       = _dereq_('glslify')
var createShader  = _dereq_('gl-shader')

var vertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, nextPosition;\nattribute float arcLength, lineWidth;\nattribute vec4 color;\n\nuniform vec2 screenShape;\nuniform float pixelRatio;\nuniform mat4 model, view, projection;\n\nvarying vec4 fragColor;\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\n\nvec4 project(vec3 p) {\n  return projection * view * model * vec4(p, 1.0);\n}\n\nvoid main() {\n  vec4 startPoint = project(position);\n  vec4 endPoint   = project(nextPosition);\n\n  vec2 A = startPoint.xy / startPoint.w;\n  vec2 B =   endPoint.xy /   endPoint.w;\n\n  float clipAngle = atan(\n    (B.y - A.y) * screenShape.y,\n    (B.x - A.x) * screenShape.x\n  );\n\n  vec2 offset = 0.5 * pixelRatio * lineWidth * vec2(\n    sin(clipAngle),\n    -cos(clipAngle)\n  ) / screenShape;\n\n  gl_Position = vec4(startPoint.xy + startPoint.w * offset, startPoint.zw);\n\n  worldPosition = position;\n  pixelArcLength = arcLength;\n  fragColor = color;\n}\n"])
var forwardFrag = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3      clipBounds[2];\nuniform sampler2D dashTexture;\nuniform float     dashScale;\nuniform float     opacity;\n\nvarying vec3    worldPosition;\nvarying float   pixelArcLength;\nvarying vec4    fragColor;\n\nvoid main() {\n  if (\n    outOfRange(clipBounds[0], clipBounds[1], worldPosition) ||\n    fragColor.a * opacity == 0.\n  ) discard;\n\n  float dashWeight = texture2D(dashTexture, vec2(dashScale * pixelArcLength, 0)).r;\n  if(dashWeight < 0.5) {\n    discard;\n  }\n  gl_FragColor = fragColor * opacity;\n}\n"])
var pickFrag = glslify(["precision mediump float;\n#define GLSLIFY 1\n\n#define FLOAT_MAX  1.70141184e38\n#define FLOAT_MIN  1.17549435e-38\n\nlowp vec4 encode_float_1540259130(highp float v) {\n  highp float av = abs(v);\n\n  //Handle special cases\n  if(av < FLOAT_MIN) {\n    return vec4(0.0, 0.0, 0.0, 0.0);\n  } else if(v > FLOAT_MAX) {\n    return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n  } else if(v < -FLOAT_MAX) {\n    return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n  }\n\n  highp vec4 c = vec4(0,0,0,0);\n\n  //Compute exponent and mantissa\n  highp float e = floor(log2(av));\n  highp float m = av * pow(2.0, -e) - 1.0;\n  \n  //Unpack mantissa\n  c[1] = floor(128.0 * m);\n  m -= c[1] / 128.0;\n  c[2] = floor(32768.0 * m);\n  m -= c[2] / 32768.0;\n  c[3] = floor(8388608.0 * m);\n  \n  //Unpack exponent\n  highp float ebias = e + 127.0;\n  c[0] = floor(ebias / 2.0);\n  ebias -= c[0] * 2.0;\n  c[1] += floor(ebias) * 128.0; \n\n  //Unpack sign bit\n  c[0] += 128.0 * step(0.0, -v);\n\n  //Scale back to range\n  return c / 255.0;\n}\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], worldPosition)) discard;\n\n  gl_FragColor = vec4(pickId/255.0, encode_float_1540259130(pixelArcLength).xyz);\n}"])

var ATTRIBUTES = [
  {name: 'position', type: 'vec3'},
  {name: 'nextPosition', type: 'vec3'},
  {name: 'arcLength', type: 'float'},
  {name: 'lineWidth', type: 'float'},
  {name: 'color', type: 'vec4'}
]

exports.createShader = function(gl) {
  return createShader(gl, vertSrc, forwardFrag, null, ATTRIBUTES)
}

exports.createPickShader = function(gl) {
  return createShader(gl, vertSrc, pickFrag, null, ATTRIBUTES)
}

},{"gl-shader":294,"glslify":398}],248:[function(_dereq_,module,exports){
'use strict'

module.exports = createLinePlot

var createBuffer = _dereq_('gl-buffer')
var createVAO = _dereq_('gl-vao')
var createTexture = _dereq_('gl-texture2d')
var unpackFloat = _dereq_('glsl-read-float')
var bsearch = _dereq_('binary-search-bounds')
var ndarray = _dereq_('ndarray')
var shaders = _dereq_('./lib/shaders')

var createShader = shaders.createShader
var createPickShader = shaders.createPickShader

var identity = [1, 0, 0, 0,
  0, 1, 0, 0,
  0, 0, 1, 0,
  0, 0, 0, 1]

function distance (a, b) {
  var s = 0.0
  for (var i = 0; i < 3; ++i) {
    var d = a[i] - b[i]
    s += d * d
  }
  return Math.sqrt(s)
}

function filterClipBounds (bounds) {
  var result = [[-1e6, -1e6, -1e6], [1e6, 1e6, 1e6]]
  for (var i = 0; i < 3; ++i) {
    result[0][i] = Math.max(bounds[0][i], result[0][i])
    result[1][i] = Math.min(bounds[1][i], result[1][i])
  }
  return result
}

function PickResult (tau, position, index, dataCoordinate) {
  this.arcLength = tau
  this.position = position
  this.index = index
  this.dataCoordinate = dataCoordinate
}

function LinePlot (gl, shader, pickShader, buffer, vao, texture) {
  this.gl = gl
  this.shader = shader
  this.pickShader = pickShader
  this.buffer = buffer
  this.vao = vao
  this.clipBounds = [
    [ -Infinity, -Infinity, -Infinity ],
    [ Infinity, Infinity, Infinity ]]
  this.points = []
  this.arcLength = []
  this.vertexCount = 0
  this.bounds = [[0, 0, 0], [0, 0, 0]]
  this.pickId = 0
  this.lineWidth = 1
  this.texture = texture
  this.dashScale = 1
  this.opacity = 1
  this.hasAlpha = false
  this.dirty = true
  this.pixelRatio = 1
}

var proto = LinePlot.prototype

proto.isTransparent = function () {
  return this.hasAlpha
}

proto.isOpaque = function () {
  return !this.hasAlpha
}

proto.pickSlots = 1

proto.setPickBase = function (id) {
  this.pickId = id
}

proto.drawTransparent = proto.draw = function (camera) {
  if (!this.vertexCount) return
  var gl = this.gl
  var shader = this.shader
  var vao = this.vao
  shader.bind()
  shader.uniforms = {
    model: camera.model || identity,
    view: camera.view || identity,
    projection: camera.projection || identity,
    clipBounds: filterClipBounds(this.clipBounds),
    dashTexture: this.texture.bind(),
    dashScale: this.dashScale / this.arcLength[this.arcLength.length - 1],
    opacity: this.opacity,
    screenShape: [gl.drawingBufferWidth, gl.drawingBufferHeight],
    pixelRatio: this.pixelRatio
  }
  vao.bind()
  vao.draw(gl.TRIANGLE_STRIP, this.vertexCount)
  vao.unbind()
}

proto.drawPick = function (camera) {
  if (!this.vertexCount) return
  var gl = this.gl
  var shader = this.pickShader
  var vao = this.vao
  shader.bind()
  shader.uniforms = {
    model: camera.model || identity,
    view: camera.view || identity,
    projection: camera.projection || identity,
    pickId: this.pickId,
    clipBounds: filterClipBounds(this.clipBounds),
    screenShape: [gl.drawingBufferWidth, gl.drawingBufferHeight],
    pixelRatio: this.pixelRatio
  }
  vao.bind()
  vao.draw(gl.TRIANGLE_STRIP, this.vertexCount)
  vao.unbind()
}

proto.update = function (options) {
  var i, j

  this.dirty = true

  var connectGaps = !!options.connectGaps

  if ('dashScale' in options) {
    this.dashScale = options.dashScale
  }

  this.hasAlpha = false // default to no transparent draw
  if ('opacity' in options) {
    this.opacity = +options.opacity
    if(this.opacity < 1) {
      this.hasAlpha = true;
    }
  }

  // Recalculate buffer data
  var buffer = []
  var arcLengthArray = []
  var pointArray = []
  var arcLength = 0.0
  var vertexCount = 0
  var bounds = [
    [ Infinity, Infinity, Infinity ],
    [ -Infinity, -Infinity, -Infinity ]]

  var positions = options.position || options.positions
  if (positions) {

    // Default color
    var colors = options.color || options.colors || [0, 0, 0, 1]

    var lineWidth = options.lineWidth || 1

    var hadGap = false

    fill_loop:
    for (i = 1; i < positions.length; ++i) {
      var a = positions[i - 1]
      var b = positions[i]

      arcLengthArray.push(arcLength)
      pointArray.push(a.slice())

      for (j = 0; j < 3; ++j) {
        if (isNaN(a[j]) || isNaN(b[j]) ||
          !isFinite(a[j]) || !isFinite(b[j])) {

          if (!connectGaps && buffer.length > 0) {
            for (var k = 0; k < 24; ++k) {
              buffer.push(buffer[buffer.length - 12])
            }
            vertexCount += 2
            hadGap = true
          }

          continue fill_loop
        }
        bounds[0][j] = Math.min(bounds[0][j], a[j], b[j])
        bounds[1][j] = Math.max(bounds[1][j], a[j], b[j])
      }

      var acolor, bcolor
      if (Array.isArray(colors[0])) {
        acolor = (colors.length > i - 1) ? colors[i - 1] :             // using index value
                 (colors.length > 0)     ? colors[colors.length - 1] : // using last item
                                           [0, 0, 0, 1];               // using black

        bcolor = (colors.length > i) ? colors[i] :                 // using index value
                 (colors.length > 0) ? colors[colors.length - 1] : // using last item
                                       [0, 0, 0, 1];               // using black
      } else {
        acolor = bcolor = colors
      }

      if (acolor.length === 3) {
        acolor = [acolor[0], acolor[1], acolor[2], 1]
      }
      if (bcolor.length === 3) {
        bcolor = [bcolor[0], bcolor[1], bcolor[2], 1]
      }

      if(!this.hasAlpha && acolor[3] < 1) this.hasAlpha = true

      var w0
      if (Array.isArray(lineWidth)) {
        w0 = (lineWidth.length > i - 1) ? lineWidth[i - 1] :                // using index value
             (lineWidth.length > 0)     ? lineWidth[lineWidth.length - 1] : // using last item
                                          [0, 0, 0, 1];                     // using black
      } else {
        w0 = lineWidth
      }

      var t0 = arcLength
      arcLength += distance(a, b)

      if (hadGap) {
        for (j = 0; j < 2; ++j) {
          buffer.push(
            a[0], a[1], a[2], b[0], b[1], b[2], t0, w0, acolor[0], acolor[1], acolor[2], acolor[3])
        }
        vertexCount += 2
        hadGap = false
      }

      buffer.push(
        a[0], a[1], a[2], b[0], b[1], b[2], t0, w0, acolor[0], acolor[1], acolor[2], acolor[3],
        a[0], a[1], a[2], b[0], b[1], b[2], t0, -w0, acolor[0], acolor[1], acolor[2], acolor[3],
        b[0], b[1], b[2], a[0], a[1], a[2], arcLength, -w0, bcolor[0], bcolor[1], bcolor[2], bcolor[3],
        b[0], b[1], b[2], a[0], a[1], a[2], arcLength, w0, bcolor[0], bcolor[1], bcolor[2], bcolor[3])

      vertexCount += 4
    }
  }
  this.buffer.update(buffer)

  arcLengthArray.push(arcLength)
  pointArray.push(positions[positions.length - 1].slice())

  this.bounds = bounds

  this.vertexCount = vertexCount

  this.points = pointArray
  this.arcLength = arcLengthArray

  if ('dashes' in options) {
    var dashArray = options.dashes

    // Calculate prefix sum
    var prefixSum = dashArray.slice()
    prefixSum.unshift(0)
    for (i = 1; i < prefixSum.length; ++i) {
      prefixSum[i] = prefixSum[i - 1] + prefixSum[i]
    }

    var dashTexture = ndarray(new Array(256 * 4), [256, 1, 4])
    for (i = 0; i < 256; ++i) {
      for (j = 0; j < 4; ++j) {
        dashTexture.set(i, 0, j, 0)
      }
      if (bsearch.le(prefixSum, prefixSum[prefixSum.length - 1] * i / 255.0) & 1) {
        dashTexture.set(i, 0, 0, 0)
      } else {
        dashTexture.set(i, 0, 0, 255)
      }
    }

    this.texture.setPixels(dashTexture)
  }
}

proto.dispose = function () {
  this.shader.dispose()
  this.vao.dispose()
  this.buffer.dispose()
}

proto.pick = function (selection) {
  if (!selection) {
    return null
  }
  if (selection.id !== this.pickId) {
    return null
  }
  var tau = unpackFloat(
    selection.value[0],
    selection.value[1],
    selection.value[2],
    0)
  var index = bsearch.le(this.arcLength, tau)
  if (index < 0) {
    return null
  }
  if (index === this.arcLength.length - 1) {
    return new PickResult(
      this.arcLength[this.arcLength.length - 1],
      this.points[this.points.length - 1].slice(),
      index)
  }
  var a = this.points[index]
  var b = this.points[Math.min(index + 1, this.points.length - 1)]
  var t = (tau - this.arcLength[index]) / (this.arcLength[index + 1] - this.arcLength[index])
  var ti = 1.0 - t
  var x = [0, 0, 0]
  for (var i = 0; i < 3; ++i) {
    x[i] = ti * a[i] + t * b[i]
  }
  var dataIndex = Math.min((t < 0.5) ? index : (index + 1), this.points.length - 1)
  return new PickResult(
    tau,
    x,
    dataIndex,
    this.points[dataIndex])
}

function createLinePlot (options) {
  var gl = options.gl || (options.scene && options.scene.gl)

  var shader = createShader(gl)
  shader.attributes.position.location = 0
  shader.attributes.nextPosition.location = 1
  shader.attributes.arcLength.location = 2
  shader.attributes.lineWidth.location = 3
  shader.attributes.color.location = 4

  var pickShader = createPickShader(gl)
  pickShader.attributes.position.location = 0
  pickShader.attributes.nextPosition.location = 1
  pickShader.attributes.arcLength.location = 2
  pickShader.attributes.lineWidth.location = 3
  pickShader.attributes.color.location = 4

  var buffer = createBuffer(gl)
  var vao = createVAO(gl, [
    {
      'buffer': buffer,
      'size': 3,
      'offset': 0,
      'stride': 48
    },
    {
      'buffer': buffer,
      'size': 3,
      'offset': 12,
      'stride': 48
    },
    {
      'buffer': buffer,
      'size': 1,
      'offset': 24,
      'stride': 48
    },
    {
      'buffer': buffer,
      'size': 1,
      'offset': 28,
      'stride': 48
    },
    {
      'buffer': buffer,
      'size': 4,
      'offset': 32,
      'stride': 48
    }
  ])

  // Create texture for dash pattern
  var defaultTexture = ndarray(new Array(256 * 4), [256, 1, 4])
  for (var i = 0; i < 256 * 4; ++i) {
    defaultTexture.data[i] = 255
  }
  var texture = createTexture(gl, defaultTexture)
  texture.wrap = gl.REPEAT

  var linePlot = new LinePlot(gl, shader, pickShader, buffer, vao, texture)
  linePlot.update(options)
  return linePlot
}

},{"./lib/shaders":247,"binary-search-bounds":249,"gl-buffer":234,"gl-texture2d":311,"gl-vao":316,"glsl-read-float":389,"ndarray":439}],249:[function(_dereq_,module,exports){
arguments[4][99][0].apply(exports,arguments)
},{"dup":99}],250:[function(_dereq_,module,exports){
module.exports = invert

/**
 * Inverts a mat2
 *
 * @alias mat2.invert
 * @param {mat2} out the receiving matrix
 * @param {mat2} a the source matrix
 * @returns {mat2} out
 */
function invert(out, a) {
  var a0 = a[0]
  var a1 = a[1]
  var a2 = a[2]
  var a3 = a[3]
  var det = a0 * a3 - a2 * a1

  if (!det) return null
  det = 1.0 / det

  out[0] =  a3 * det
  out[1] = -a1 * det
  out[2] = -a2 * det
  out[3] =  a0 * det

  return out
}

},{}],251:[function(_dereq_,module,exports){
module.exports = invert

/**
 * Inverts a mat3
 *
 * @alias mat3.invert
 * @param {mat3} out the receiving matrix
 * @param {mat3} a the source matrix
 * @returns {mat3} out
 */
function invert(out, a) {
  var a00 = a[0], a01 = a[1], a02 = a[2]
  var a10 = a[3], a11 = a[4], a12 = a[5]
  var a20 = a[6], a21 = a[7], a22 = a[8]

  var b01 = a22 * a11 - a12 * a21
  var b11 = -a22 * a10 + a12 * a20
  var b21 = a21 * a10 - a11 * a20

  // Calculate the determinant
  var det = a00 * b01 + a01 * b11 + a02 * b21

  if (!det) return null
  det = 1.0 / det

  out[0] = b01 * det
  out[1] = (-a22 * a01 + a02 * a21) * det
  out[2] = (a12 * a01 - a02 * a11) * det
  out[3] = b11 * det
  out[4] = (a22 * a00 - a02 * a20) * det
  out[5] = (-a12 * a00 + a02 * a10) * det
  out[6] = b21 * det
  out[7] = (-a21 * a00 + a01 * a20) * det
  out[8] = (a11 * a00 - a01 * a10) * det

  return out
}

},{}],252:[function(_dereq_,module,exports){
module.exports = clone;

/**
 * Creates a new mat4 initialized with values from an existing matrix
 *
 * @param {mat4} a matrix to clone
 * @returns {mat4} a new 4x4 matrix
 */
function clone(a) {
    var out = new Float32Array(16);
    out[0] = a[0];
    out[1] = a[1];
    out[2] = a[2];
    out[3] = a[3];
    out[4] = a[4];
    out[5] = a[5];
    out[6] = a[6];
    out[7] = a[7];
    out[8] = a[8];
    out[9] = a[9];
    out[10] = a[10];
    out[11] = a[11];
    out[12] = a[12];
    out[13] = a[13];
    out[14] = a[14];
    out[15] = a[15];
    return out;
};
},{}],253:[function(_dereq_,module,exports){
module.exports = create;

/**
 * Creates a new identity mat4
 *
 * @returns {mat4} a new 4x4 matrix
 */
function create() {
    var out = new Float32Array(16);
    out[0] = 1;
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = 0;
    out[5] = 1;
    out[6] = 0;
    out[7] = 0;
    out[8] = 0;
    out[9] = 0;
    out[10] = 1;
    out[11] = 0;
    out[12] = 0;
    out[13] = 0;
    out[14] = 0;
    out[15] = 1;
    return out;
};
},{}],254:[function(_dereq_,module,exports){
module.exports = determinant;

/**
 * Calculates the determinant of a mat4
 *
 * @param {mat4} a the source matrix
 * @returns {Number} determinant of a
 */
function determinant(a) {
    var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
        a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
        a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
        a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15],

        b00 = a00 * a11 - a01 * a10,
        b01 = a00 * a12 - a02 * a10,
        b02 = a00 * a13 - a03 * a10,
        b03 = a01 * a12 - a02 * a11,
        b04 = a01 * a13 - a03 * a11,
        b05 = a02 * a13 - a03 * a12,
        b06 = a20 * a31 - a21 * a30,
        b07 = a20 * a32 - a22 * a30,
        b08 = a20 * a33 - a23 * a30,
        b09 = a21 * a32 - a22 * a31,
        b10 = a21 * a33 - a23 * a31,
        b11 = a22 * a33 - a23 * a32;

    // Calculate the determinant
    return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
};
},{}],255:[function(_dereq_,module,exports){
module.exports = fromQuat;

/**
 * Creates a matrix from a quaternion rotation.
 *
 * @param {mat4} out mat4 receiving operation result
 * @param {quat4} q Rotation quaternion
 * @returns {mat4} out
 */
function fromQuat(out, q) {
    var x = q[0], y = q[1], z = q[2], w = q[3],
        x2 = x + x,
        y2 = y + y,
        z2 = z + z,

        xx = x * x2,
        yx = y * x2,
        yy = y * y2,
        zx = z * x2,
        zy = z * y2,
        zz = z * z2,
        wx = w * x2,
        wy = w * y2,
        wz = w * z2;

    out[0] = 1 - yy - zz;
    out[1] = yx + wz;
    out[2] = zx - wy;
    out[3] = 0;

    out[4] = yx - wz;
    out[5] = 1 - xx - zz;
    out[6] = zy + wx;
    out[7] = 0;

    out[8] = zx + wy;
    out[9] = zy - wx;
    out[10] = 1 - xx - yy;
    out[11] = 0;

    out[12] = 0;
    out[13] = 0;
    out[14] = 0;
    out[15] = 1;

    return out;
};
},{}],256:[function(_dereq_,module,exports){
module.exports = fromRotationTranslation;

/**
 * Creates a matrix from a quaternion rotation and vector translation
 * This is equivalent to (but much faster than):
 *
 *     mat4.identity(dest);
 *     mat4.translate(dest, vec);
 *     var quatMat = mat4.create();
 *     quat4.toMat4(quat, quatMat);
 *     mat4.multiply(dest, quatMat);
 *
 * @param {mat4} out mat4 receiving operation result
 * @param {quat4} q Rotation quaternion
 * @param {vec3} v Translation vector
 * @returns {mat4} out
 */
function fromRotationTranslation(out, q, v) {
    // Quaternion math
    var x = q[0], y = q[1], z = q[2], w = q[3],
        x2 = x + x,
        y2 = y + y,
        z2 = z + z,

        xx = x * x2,
        xy = x * y2,
        xz = x * z2,
        yy = y * y2,
        yz = y * z2,
        zz = z * z2,
        wx = w * x2,
        wy = w * y2,
        wz = w * z2;

    out[0] = 1 - (yy + zz);
    out[1] = xy + wz;
    out[2] = xz - wy;
    out[3] = 0;
    out[4] = xy - wz;
    out[5] = 1 - (xx + zz);
    out[6] = yz + wx;
    out[7] = 0;
    out[8] = xz + wy;
    out[9] = yz - wx;
    out[10] = 1 - (xx + yy);
    out[11] = 0;
    out[12] = v[0];
    out[13] = v[1];
    out[14] = v[2];
    out[15] = 1;
    
    return out;
};
},{}],257:[function(_dereq_,module,exports){
module.exports = identity;

/**
 * Set a mat4 to the identity matrix
 *
 * @param {mat4} out the receiving matrix
 * @returns {mat4} out
 */
function identity(out) {
    out[0] = 1;
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = 0;
    out[5] = 1;
    out[6] = 0;
    out[7] = 0;
    out[8] = 0;
    out[9] = 0;
    out[10] = 1;
    out[11] = 0;
    out[12] = 0;
    out[13] = 0;
    out[14] = 0;
    out[15] = 1;
    return out;
};
},{}],258:[function(_dereq_,module,exports){
module.exports = invert;

/**
 * Inverts a mat4
 *
 * @param {mat4} out the receiving matrix
 * @param {mat4} a the source matrix
 * @returns {mat4} out
 */
function invert(out, a) {
    var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
        a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
        a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
        a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15],

        b00 = a00 * a11 - a01 * a10,
        b01 = a00 * a12 - a02 * a10,
        b02 = a00 * a13 - a03 * a10,
        b03 = a01 * a12 - a02 * a11,
        b04 = a01 * a13 - a03 * a11,
        b05 = a02 * a13 - a03 * a12,
        b06 = a20 * a31 - a21 * a30,
        b07 = a20 * a32 - a22 * a30,
        b08 = a20 * a33 - a23 * a30,
        b09 = a21 * a32 - a22 * a31,
        b10 = a21 * a33 - a23 * a31,
        b11 = a22 * a33 - a23 * a32,

        // Calculate the determinant
        det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;

    if (!det) { 
        return null; 
    }
    det = 1.0 / det;

    out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
    out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
    out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
    out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
    out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
    out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
    out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
    out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
    out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
    out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
    out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
    out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
    out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
    out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
    out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
    out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;

    return out;
};
},{}],259:[function(_dereq_,module,exports){
var identity = _dereq_('./identity');

module.exports = lookAt;

/**
 * Generates a look-at matrix with the given eye position, focal point, and up axis
 *
 * @param {mat4} out mat4 frustum matrix will be written into
 * @param {vec3} eye Position of the viewer
 * @param {vec3} center Point the viewer is looking at
 * @param {vec3} up vec3 pointing up
 * @returns {mat4} out
 */
function lookAt(out, eye, center, up) {
    var x0, x1, x2, y0, y1, y2, z0, z1, z2, len,
        eyex = eye[0],
        eyey = eye[1],
        eyez = eye[2],
        upx = up[0],
        upy = up[1],
        upz = up[2],
        centerx = center[0],
        centery = center[1],
        centerz = center[2];

    if (Math.abs(eyex - centerx) < 0.000001 &&
        Math.abs(eyey - centery) < 0.000001 &&
        Math.abs(eyez - centerz) < 0.000001) {
        return identity(out);
    }

    z0 = eyex - centerx;
    z1 = eyey - centery;
    z2 = eyez - centerz;

    len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);
    z0 *= len;
    z1 *= len;
    z2 *= len;

    x0 = upy * z2 - upz * z1;
    x1 = upz * z0 - upx * z2;
    x2 = upx * z1 - upy * z0;
    len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);
    if (!len) {
        x0 = 0;
        x1 = 0;
        x2 = 0;
    } else {
        len = 1 / len;
        x0 *= len;
        x1 *= len;
        x2 *= len;
    }

    y0 = z1 * x2 - z2 * x1;
    y1 = z2 * x0 - z0 * x2;
    y2 = z0 * x1 - z1 * x0;

    len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2);
    if (!len) {
        y0 = 0;
        y1 = 0;
        y2 = 0;
    } else {
        len = 1 / len;
        y0 *= len;
        y1 *= len;
        y2 *= len;
    }

    out[0] = x0;
    out[1] = y0;
    out[2] = z0;
    out[3] = 0;
    out[4] = x1;
    out[5] = y1;
    out[6] = z1;
    out[7] = 0;
    out[8] = x2;
    out[9] = y2;
    out[10] = z2;
    out[11] = 0;
    out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
    out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
    out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
    out[15] = 1;

    return out;
};
},{"./identity":257}],260:[function(_dereq_,module,exports){
module.exports = multiply;

/**
 * Multiplies two mat4's
 *
 * @param {mat4} out the receiving matrix
 * @param {mat4} a the first operand
 * @param {mat4} b the second operand
 * @returns {mat4} out
 */
function multiply(out, a, b) {
    var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
        a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
        a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
        a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];

    // Cache only the current line of the second matrix
    var b0  = b[0], b1 = b[1], b2 = b[2], b3 = b[3];  
    out[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
    out[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
    out[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
    out[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33;

    b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7];
    out[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
    out[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
    out[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
    out[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33;

    b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11];
    out[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
    out[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
    out[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
    out[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33;

    b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15];
    out[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
    out[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
    out[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
    out[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
    return out;
};
},{}],261:[function(_dereq_,module,exports){
module.exports = ortho;

/**
 * Generates a orthogonal projection matrix with the given bounds
 *
 * @param {mat4} out mat4 frustum matrix will be written into
 * @param {number} left Left bound of the frustum
 * @param {number} right Right bound of the frustum
 * @param {number} bottom Bottom bound of the frustum
 * @param {number} top Top bound of the frustum
 * @param {number} near Near bound of the frustum
 * @param {number} far Far bound of the frustum
 * @returns {mat4} out
 */
function ortho(out, left, right, bottom, top, near, far) {
    var lr = 1 / (left - right),
        bt = 1 / (bottom - top),
        nf = 1 / (near - far);
    out[0] = -2 * lr;
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = 0;
    out[5] = -2 * bt;
    out[6] = 0;
    out[7] = 0;
    out[8] = 0;
    out[9] = 0;
    out[10] = 2 * nf;
    out[11] = 0;
    out[12] = (left + right) * lr;
    out[13] = (top + bottom) * bt;
    out[14] = (far + near) * nf;
    out[15] = 1;
    return out;
};
},{}],262:[function(_dereq_,module,exports){
module.exports = perspective;

/**
 * Generates a perspective projection matrix with the given bounds
 *
 * @param {mat4} out mat4 frustum matrix will be written into
 * @param {number} fovy Vertical field of view in radians
 * @param {number} aspect Aspect ratio. typically viewport width/height
 * @param {number} near Near bound of the frustum
 * @param {number} far Far bound of the frustum
 * @returns {mat4} out
 */
function perspective(out, fovy, aspect, near, far) {
    var f = 1.0 / Math.tan(fovy / 2),
        nf = 1 / (near - far);
    out[0] = f / aspect;
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = 0;
    out[5] = f;
    out[6] = 0;
    out[7] = 0;
    out[8] = 0;
    out[9] = 0;
    out[10] = (far + near) * nf;
    out[11] = -1;
    out[12] = 0;
    out[13] = 0;
    out[14] = (2 * far * near) * nf;
    out[15] = 0;
    return out;
};
},{}],263:[function(_dereq_,module,exports){
module.exports = rotate;

/**
 * Rotates a mat4 by the given angle
 *
 * @param {mat4} out the receiving matrix
 * @param {mat4} a the matrix to rotate
 * @param {Number} rad the angle to rotate the matrix by
 * @param {vec3} axis the axis to rotate around
 * @returns {mat4} out
 */
function rotate(out, a, rad, axis) {
    var x = axis[0], y = axis[1], z = axis[2],
        len = Math.sqrt(x * x + y * y + z * z),
        s, c, t,
        a00, a01, a02, a03,
        a10, a11, a12, a13,
        a20, a21, a22, a23,
        b00, b01, b02,
        b10, b11, b12,
        b20, b21, b22;

    if (Math.abs(len) < 0.000001) { return null; }
    
    len = 1 / len;
    x *= len;
    y *= len;
    z *= len;

    s = Math.sin(rad);
    c = Math.cos(rad);
    t = 1 - c;

    a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3];
    a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7];
    a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11];

    // Construct the elements of the rotation matrix
    b00 = x * x * t + c; b01 = y * x * t + z * s; b02 = z * x * t - y * s;
    b10 = x * y * t - z * s; b11 = y * y * t + c; b12 = z * y * t + x * s;
    b20 = x * z * t + y * s; b21 = y * z * t - x * s; b22 = z * z * t + c;

    // Perform rotation-specific matrix multiplication
    out[0] = a00 * b00 + a10 * b01 + a20 * b02;
    out[1] = a01 * b00 + a11 * b01 + a21 * b02;
    out[2] = a02 * b00 + a12 * b01 + a22 * b02;
    out[3] = a03 * b00 + a13 * b01 + a23 * b02;
    out[4] = a00 * b10 + a10 * b11 + a20 * b12;
    out[5] = a01 * b10 + a11 * b11 + a21 * b12;
    out[6] = a02 * b10 + a12 * b11 + a22 * b12;
    out[7] = a03 * b10 + a13 * b11 + a23 * b12;
    out[8] = a00 * b20 + a10 * b21 + a20 * b22;
    out[9] = a01 * b20 + a11 * b21 + a21 * b22;
    out[10] = a02 * b20 + a12 * b21 + a22 * b22;
    out[11] = a03 * b20 + a13 * b21 + a23 * b22;

    if (a !== out) { // If the source and destination differ, copy the unchanged last row
        out[12] = a[12];
        out[13] = a[13];
        out[14] = a[14];
        out[15] = a[15];
    }
    return out;
};
},{}],264:[function(_dereq_,module,exports){
module.exports = rotateX;

/**
 * Rotates a matrix by the given angle around the X axis
 *
 * @param {mat4} out the receiving matrix
 * @param {mat4} a the matrix to rotate
 * @param {Number} rad the angle to rotate the matrix by
 * @returns {mat4} out
 */
function rotateX(out, a, rad) {
    var s = Math.sin(rad),
        c = Math.cos(rad),
        a10 = a[4],
        a11 = a[5],
        a12 = a[6],
        a13 = a[7],
        a20 = a[8],
        a21 = a[9],
        a22 = a[10],
        a23 = a[11];

    if (a !== out) { // If the source and destination differ, copy the unchanged rows
        out[0]  = a[0];
        out[1]  = a[1];
        out[2]  = a[2];
        out[3]  = a[3];
        out[12] = a[12];
        out[13] = a[13];
        out[14] = a[14];
        out[15] = a[15];
    }

    // Perform axis-specific matrix multiplication
    out[4] = a10 * c + a20 * s;
    out[5] = a11 * c + a21 * s;
    out[6] = a12 * c + a22 * s;
    out[7] = a13 * c + a23 * s;
    out[8] = a20 * c - a10 * s;
    out[9] = a21 * c - a11 * s;
    out[10] = a22 * c - a12 * s;
    out[11] = a23 * c - a13 * s;
    return out;
};
},{}],265:[function(_dereq_,module,exports){
module.exports = rotateY;

/**
 * Rotates a matrix by the given angle around the Y axis
 *
 * @param {mat4} out the receiving matrix
 * @param {mat4} a the matrix to rotate
 * @param {Number} rad the angle to rotate the matrix by
 * @returns {mat4} out
 */
function rotateY(out, a, rad) {
    var s = Math.sin(rad),
        c = Math.cos(rad),
        a00 = a[0],
        a01 = a[1],
        a02 = a[2],
        a03 = a[3],
        a20 = a[8],
        a21 = a[9],
        a22 = a[10],
        a23 = a[11];

    if (a !== out) { // If the source and destination differ, copy the unchanged rows
        out[4]  = a[4];
        out[5]  = a[5];
        out[6]  = a[6];
        out[7]  = a[7];
        out[12] = a[12];
        out[13] = a[13];
        out[14] = a[14];
        out[15] = a[15];
    }

    // Perform axis-specific matrix multiplication
    out[0] = a00 * c - a20 * s;
    out[1] = a01 * c - a21 * s;
    out[2] = a02 * c - a22 * s;
    out[3] = a03 * c - a23 * s;
    out[8] = a00 * s + a20 * c;
    out[9] = a01 * s + a21 * c;
    out[10] = a02 * s + a22 * c;
    out[11] = a03 * s + a23 * c;
    return out;
};
},{}],266:[function(_dereq_,module,exports){
module.exports = rotateZ;

/**
 * Rotates a matrix by the given angle around the Z axis
 *
 * @param {mat4} out the receiving matrix
 * @param {mat4} a the matrix to rotate
 * @param {Number} rad the angle to rotate the matrix by
 * @returns {mat4} out
 */
function rotateZ(out, a, rad) {
    var s = Math.sin(rad),
        c = Math.cos(rad),
        a00 = a[0],
        a01 = a[1],
        a02 = a[2],
        a03 = a[3],
        a10 = a[4],
        a11 = a[5],
        a12 = a[6],
        a13 = a[7];

    if (a !== out) { // If the source and destination differ, copy the unchanged last row
        out[8]  = a[8];
        out[9]  = a[9];
        out[10] = a[10];
        out[11] = a[11];
        out[12] = a[12];
        out[13] = a[13];
        out[14] = a[14];
        out[15] = a[15];
    }

    // Perform axis-specific matrix multiplication
    out[0] = a00 * c + a10 * s;
    out[1] = a01 * c + a11 * s;
    out[2] = a02 * c + a12 * s;
    out[3] = a03 * c + a13 * s;
    out[4] = a10 * c - a00 * s;
    out[5] = a11 * c - a01 * s;
    out[6] = a12 * c - a02 * s;
    out[7] = a13 * c - a03 * s;
    return out;
};
},{}],267:[function(_dereq_,module,exports){
module.exports = scale;

/**
 * Scales the mat4 by the dimensions in the given vec3
 *
 * @param {mat4} out the receiving matrix
 * @param {mat4} a the matrix to scale
 * @param {vec3} v the vec3 to scale the matrix by
 * @returns {mat4} out
 **/
function scale(out, a, v) {
    var x = v[0], y = v[1], z = v[2];

    out[0] = a[0] * x;
    out[1] = a[1] * x;
    out[2] = a[2] * x;
    out[3] = a[3] * x;
    out[4] = a[4] * y;
    out[5] = a[5] * y;
    out[6] = a[6] * y;
    out[7] = a[7] * y;
    out[8] = a[8] * z;
    out[9] = a[9] * z;
    out[10] = a[10] * z;
    out[11] = a[11] * z;
    out[12] = a[12];
    out[13] = a[13];
    out[14] = a[14];
    out[15] = a[15];
    return out;
};
},{}],268:[function(_dereq_,module,exports){
module.exports = translate;

/**
 * Translate a mat4 by the given vector
 *
 * @param {mat4} out the receiving matrix
 * @param {mat4} a the matrix to translate
 * @param {vec3} v vector to translate by
 * @returns {mat4} out
 */
function translate(out, a, v) {
    var x = v[0], y = v[1], z = v[2],
        a00, a01, a02, a03,
        a10, a11, a12, a13,
        a20, a21, a22, a23;

    if (a === out) {
        out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
        out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
        out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
        out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
    } else {
        a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3];
        a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7];
        a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11];

        out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a03;
        out[4] = a10; out[5] = a11; out[6] = a12; out[7] = a13;
        out[8] = a20; out[9] = a21; out[10] = a22; out[11] = a23;

        out[12] = a00 * x + a10 * y + a20 * z + a[12];
        out[13] = a01 * x + a11 * y + a21 * z + a[13];
        out[14] = a02 * x + a12 * y + a22 * z + a[14];
        out[15] = a03 * x + a13 * y + a23 * z + a[15];
    }

    return out;
};
},{}],269:[function(_dereq_,module,exports){
module.exports = transpose;

/**
 * Transpose the values of a mat4
 *
 * @param {mat4} out the receiving matrix
 * @param {mat4} a the source matrix
 * @returns {mat4} out
 */
function transpose(out, a) {
    // If we are transposing ourselves we can skip a few steps but have to cache some values
    if (out === a) {
        var a01 = a[1], a02 = a[2], a03 = a[3],
            a12 = a[6], a13 = a[7],
            a23 = a[11];

        out[1] = a[4];
        out[2] = a[8];
        out[3] = a[12];
        out[4] = a01;
        out[6] = a[9];
        out[7] = a[13];
        out[8] = a02;
        out[9] = a12;
        out[11] = a[14];
        out[12] = a03;
        out[13] = a13;
        out[14] = a23;
    } else {
        out[0] = a[0];
        out[1] = a[4];
        out[2] = a[8];
        out[3] = a[12];
        out[4] = a[1];
        out[5] = a[5];
        out[6] = a[9];
        out[7] = a[13];
        out[8] = a[2];
        out[9] = a[6];
        out[10] = a[10];
        out[11] = a[14];
        out[12] = a[3];
        out[13] = a[7];
        out[14] = a[11];
        out[15] = a[15];
    }
    
    return out;
};
},{}],270:[function(_dereq_,module,exports){
'use strict'

module.exports = invert

var invert2 = _dereq_('gl-mat2/invert')
var invert3 = _dereq_('gl-mat3/invert')
var invert4 = _dereq_('gl-mat4/invert')

function invert(out, M) {
  switch(M.length) {
    case 0:
    break
    case 1:
      out[0] = 1.0 / M[0]
    break
    case 4:
      invert2(out, M)
    break
    case 9:
      invert3(out, M)
    break
    case 16:
      invert4(out, M)
    break
    default:
      throw new Error('currently supports matrices up to 4x4')
    break
  }
  return out
}
},{"gl-mat2/invert":250,"gl-mat3/invert":251,"gl-mat4/invert":258}],271:[function(_dereq_,module,exports){
'use strict'

var barycentric            = _dereq_('barycentric')
var closestPointToTriangle = _dereq_('polytope-closest-point/lib/closest_point_2d.js')

module.exports = closestPointToPickLocation

function xformMatrix(m, v) {
  var out = [0,0,0,0]
  for(var i=0; i<4; ++i) {
    for(var j=0; j<4; ++j) {
      out[j] += m[4*i + j] * v[i]
    }
  }
  return out
}

function projectVertex(v, model, view, projection, resolution) {
  var p = xformMatrix(projection,
            xformMatrix(view,
              xformMatrix(model, [v[0], v[1], v[2], 1])))
  for(var i=0; i<3; ++i) {
    p[i] /= p[3]
  }
  return [ 0.5 * resolution[0] * (1.0+p[0]), 0.5 * resolution[1] * (1.0-p[1]) ]
}

function barycentricCoord(simplex, point) {
  if(simplex.length === 2) {
    var d0 = 0.0
    var d1 = 0.0
    for(var i=0; i<2; ++i) {
      d0 += Math.pow(point[i] - simplex[0][i], 2)
      d1 += Math.pow(point[i] - simplex[1][i], 2)
    }
    d0 = Math.sqrt(d0)
    d1 = Math.sqrt(d1)
    if(d0+d1 < 1e-6) {
      return [1,0]
    }
    return [d1/(d0+d1),d0/(d1+d0)]
  } else if(simplex.length === 3) {
    var closestPoint = [0,0]
    closestPointToTriangle(simplex[0], simplex[1], simplex[2], point, closestPoint)
    return barycentric(simplex, closestPoint)
  }
  return []
}

function interpolate(simplex, weights) {
  var result = [0,0,0]
  for(var i=0; i<simplex.length; ++i) {
    var p = simplex[i]
    var w = weights[i]
    for(var j=0; j<3; ++j) {
      result[j] += w * p[j]
    }
  }
  return result
}

function closestPointToPickLocation(simplex, pixelCoord, model, view, projection, resolution) {
  if(simplex.length === 1) {
    return [0, simplex[0].slice()]
  }
  var simplex2D = new Array(simplex.length)
  for(var i=0; i<simplex.length; ++i) {
    simplex2D[i] = projectVertex(simplex[i], model, view, projection, resolution);
  }

  var closestIndex = 0
  var closestDist  = Infinity
  for(var i=0; i<simplex2D.length; ++i) {
    var d2 = 0.0
    for(var j=0; j<2; ++j) {
      d2 += Math.pow(simplex2D[i][j] - pixelCoord[j], 2)
    }
    if(d2 < closestDist) {
      closestDist  = d2
      closestIndex = i
    }
  }

  var weights = barycentricCoord(simplex2D, pixelCoord)
  var s = 0.0
  for(var i=0; i<3; ++i) {
    if(weights[i] < -0.001 ||
       weights[i] > 1.0001) {
      return null
    }
    s += weights[i]
  }
  if(Math.abs(s - 1.0) > 0.001) {
    return null
  }
  return [closestIndex, interpolate(simplex, weights), weights]
}
},{"barycentric":61,"polytope-closest-point/lib/closest_point_2d.js":470}],272:[function(_dereq_,module,exports){
var glslify       = _dereq_('glslify')

var triVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, normal;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model\n           , view\n           , projection\n           , inverseModel;\nuniform vec3 eyePosition\n           , lightPosition;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvec4 project(vec3 p) {\n  return projection * view * model * vec4(p, 1.0);\n}\n\nvoid main() {\n  gl_Position      = project(position);\n\n  //Lighting geometry parameters\n  vec4 cameraCoordinate = view * vec4(position , 1.0);\n  cameraCoordinate.xyz /= cameraCoordinate.w;\n  f_lightDirection = lightPosition - cameraCoordinate.xyz;\n  f_eyeDirection   = eyePosition - cameraCoordinate.xyz;\n  f_normal  = normalize((vec4(normal,0) * inverseModel).xyz);\n\n  f_color          = color;\n  f_data           = position;\n  f_uv             = uv;\n}\n"])
var triFragSrc = glslify(["#extension GL_OES_standard_derivatives : enable\n\nprecision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution(float x, float roughness) {\n  float NdotH = max(x, 0.0001);\n  float cos2Alpha = NdotH * NdotH;\n  float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n  float roughness2 = roughness * roughness;\n  float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n  return exp(tan2Alpha / roughness2) / denom;\n}\n\nfloat cookTorranceSpecular(\n  vec3 lightDirection,\n  vec3 viewDirection,\n  vec3 surfaceNormal,\n  float roughness,\n  float fresnel) {\n\n  float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n  float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n  //Half angle vector\n  vec3 H = normalize(lightDirection + viewDirection);\n\n  //Geometric term\n  float NdotH = max(dot(surfaceNormal, H), 0.0);\n  float VdotH = max(dot(viewDirection, H), 0.000001);\n  float LdotH = max(dot(lightDirection, H), 0.000001);\n  float G1 = (2.0 * NdotH * VdotN) / VdotH;\n  float G2 = (2.0 * NdotH * LdotN) / LdotH;\n  float G = min(1.0, min(G1, G2));\n  \n  //Distribution term\n  float D = beckmannDistribution(NdotH, roughness);\n\n  //Fresnel term\n  float F = pow(1.0 - VdotN, fresnel);\n\n  //Multiply terms and done\n  return  G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\n//#pragma glslify: beckmann = require(glsl-specular-beckmann) // used in gl-surface3d\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n            , fresnel\n            , kambient\n            , kdiffuse\n            , kspecular\n            , opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_data)) discard;\n\n  vec3 N = normalize(f_normal);\n  vec3 L = normalize(f_lightDirection);\n  vec3 V = normalize(f_eyeDirection);\n\n  if(gl_FrontFacing) {\n    N = -N;\n  }\n\n  float specular = min(1.0, max(0.0, cookTorranceSpecular(L, V, N, roughness, fresnel)));\n  //float specular = max(0.0, beckmann(L, V, N, roughness)); // used in gl-surface3d\n\n  float diffuse  = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n  vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n  vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular,  1.0);\n\n  gl_FragColor = litColor * opacity;\n}\n"])
var edgeVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model, view, projection;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n  gl_Position = projection * view * model * vec4(position, 1.0);\n  f_color = color;\n  f_data  = position;\n  f_uv    = uv;\n}"])
var edgeFragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_data)) discard;\n\n  gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}"])
var pointVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\nattribute float pointSize;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    gl_Position = projection * view * model * vec4(position, 1.0);\n  }\n  gl_PointSize = pointSize;\n  f_color = color;\n  f_uv = uv;\n}"])
var pointFragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  vec2 pointR = gl_PointCoord.xy - vec2(0.5,0.5);\n  if(dot(pointR, pointR) > 0.25) {\n    discard;\n  }\n  gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}"])
var pickVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  gl_Position = projection * view * model * vec4(position, 1.0);\n  f_id        = id;\n  f_position  = position;\n}"])
var pickFragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3  clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n\n  gl_FragColor = vec4(pickId, f_id.xyz);\n}"])
var pickPointVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3  position;\nattribute float pointSize;\nattribute vec4  id;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    gl_Position  = projection * view * model * vec4(position, 1.0);\n    gl_PointSize = pointSize;\n  }\n  f_id         = id;\n  f_position   = position;\n}"])
var contourVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\n\nvoid main() {\n  gl_Position = projection * view * model * vec4(position, 1.0);\n}"])
var contourFragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n  gl_FragColor = vec4(contourColor,1);\n}\n"])

exports.meshShader = {
  vertex:   triVertSrc,
  fragment: triFragSrc,
  attributes: [
    {name: 'position', type: 'vec3'},
    {name: 'normal', type: 'vec3'},
    {name: 'color', type: 'vec4'},
    {name: 'uv', type: 'vec2'}
  ]
}
exports.wireShader = {
  vertex:   edgeVertSrc,
  fragment: edgeFragSrc,
  attributes: [
    {name: 'position', type: 'vec3'},
    {name: 'color', type: 'vec4'},
    {name: 'uv', type: 'vec2'}
  ]
}
exports.pointShader = {
  vertex:   pointVertSrc,
  fragment: pointFragSrc,
  attributes: [
    {name: 'position', type: 'vec3'},
    {name: 'color', type: 'vec4'},
    {name: 'uv', type: 'vec2'},
    {name: 'pointSize', type: 'float'}
  ]
}
exports.pickShader = {
  vertex:   pickVertSrc,
  fragment: pickFragSrc,
  attributes: [
    {name: 'position', type: 'vec3'},
    {name: 'id', type: 'vec4'}
  ]
}
exports.pointPickShader = {
  vertex:   pickPointVertSrc,
  fragment: pickFragSrc,
  attributes: [
    {name: 'position', type: 'vec3'},
    {name: 'pointSize', type: 'float'},
    {name: 'id', type: 'vec4'}
  ]
}
exports.contourShader = {
  vertex:   contourVertSrc,
  fragment: contourFragSrc,
  attributes: [
    {name: 'position', type: 'vec3'}
  ]
}

},{"glslify":398}],273:[function(_dereq_,module,exports){
'use strict'

var DEFAULT_VERTEX_NORMALS_EPSILON = 1e-6; // may be too large if triangles are very small
var DEFAULT_FACE_NORMALS_EPSILON = 1e-6;

var createShader  = _dereq_('gl-shader')
var createBuffer  = _dereq_('gl-buffer')
var createVAO     = _dereq_('gl-vao')
var createTexture = _dereq_('gl-texture2d')
var normals       = _dereq_('normals')
var multiply      = _dereq_('gl-mat4/multiply')
var invert        = _dereq_('gl-mat4/invert')
var ndarray       = _dereq_('ndarray')
var colormap      = _dereq_('colormap')
var getContour    = _dereq_('simplicial-complex-contour')
var pool          = _dereq_('typedarray-pool')
var shaders       = _dereq_('./lib/shaders')
var closestPoint  = _dereq_('./lib/closest-point')

var meshShader    = shaders.meshShader
var wireShader    = shaders.wireShader
var pointShader   = shaders.pointShader
var pickShader    = shaders.pickShader
var pointPickShader = shaders.pointPickShader
var contourShader = shaders.contourShader

var IDENTITY = [
  1,0,0,0,
  0,1,0,0,
  0,0,1,0,
  0,0,0,1]


function SimplicialMesh(gl
  , texture
  , triShader
  , lineShader
  , pointShader
  , pickShader
  , pointPickShader
  , contourShader
  , trianglePositions
  , triangleIds
  , triangleColors
  , triangleUVs
  , triangleNormals
  , triangleVAO
  , edgePositions
  , edgeIds
  , edgeColors
  , edgeUVs
  , edgeVAO
  , pointPositions
  , pointIds
  , pointColors
  , pointUVs
  , pointSizes
  , pointVAO
  , contourPositions
  , contourVAO) {

  this.gl                = gl
  this.pixelRatio         = 1
  this.cells             = []
  this.positions         = []
  this.intensity         = []
  this.texture           = texture
  this.dirty             = true

  this.triShader         = triShader
  this.lineShader        = lineShader
  this.pointShader       = pointShader
  this.pickShader        = pickShader
  this.pointPickShader   = pointPickShader
  this.contourShader     = contourShader

  this.trianglePositions = trianglePositions
  this.triangleColors    = triangleColors
  this.triangleNormals   = triangleNormals
  this.triangleUVs       = triangleUVs
  this.triangleIds       = triangleIds
  this.triangleVAO       = triangleVAO
  this.triangleCount     = 0

  this.lineWidth         = 1
  this.edgePositions     = edgePositions
  this.edgeColors        = edgeColors
  this.edgeUVs           = edgeUVs
  this.edgeIds           = edgeIds
  this.edgeVAO           = edgeVAO
  this.edgeCount         = 0

  this.pointPositions    = pointPositions
  this.pointColors       = pointColors
  this.pointUVs          = pointUVs
  this.pointSizes        = pointSizes
  this.pointIds          = pointIds
  this.pointVAO          = pointVAO
  this.pointCount        = 0

  this.contourLineWidth  = 1
  this.contourPositions  = contourPositions
  this.contourVAO        = contourVAO
  this.contourCount      = 0
  this.contourColor      = [0,0,0]
  this.contourEnable     = true

  this.pickId            = 1
  this.bounds            = [
    [ Infinity, Infinity, Infinity],
    [-Infinity,-Infinity,-Infinity] ]
  this.clipBounds        = [
    [-Infinity,-Infinity,-Infinity],
    [ Infinity, Infinity, Infinity] ]

  this.lightPosition = [1e5, 1e5, 0]
  this.ambientLight  = 0.8
  this.diffuseLight  = 0.8
  this.specularLight = 2.0
  this.roughness     = 0.5
  this.fresnel       = 1.5

  this.opacity       = 1.0

  this._model       = IDENTITY
  this._view        = IDENTITY
  this._projection  = IDENTITY
  this._resolution  = [1,1]
}

var proto = SimplicialMesh.prototype

proto.isOpaque = function() {
  return this.opacity >= 1
}

proto.isTransparent = function() {
  return this.opacity < 1
}

proto.pickSlots = 1

proto.setPickBase = function(id) {
  this.pickId = id
}

function genColormap(param) {
  var colors = colormap({
      colormap: param
    , nshades:  256
    , format:  'rgba'
  })

  var result = new Uint8Array(256*4)
  for(var i=0; i<256; ++i) {
    var c = colors[i]
    for(var j=0; j<3; ++j) {
      result[4*i+j] = c[j]
    }
    result[4*i+3] = c[3]*255
  }

  return ndarray(result, [256,256,4], [4,0,1])
}

function unpackIntensity(cells, numVerts, cellIntensity) {
  var result = new Array(numVerts)
  for(var i=0; i<numVerts; ++i) {
    result[i] = 0
  }
  var numCells = cells.length
  for(var i=0; i<numCells; ++i) {
    var c = cells[i]
    for(var j=0; j<c.length; ++j) {
      result[c[j]] = cellIntensity[i]
    }
  }
  return result
}

function takeZComponent(array) {
  var n = array.length
  var result = new Array(n)
  for(var i=0; i<n; ++i) {
    result[i] = array[i][2]
  }
  return result
}

proto.highlight = function(selection) {
  if(!selection || !this.contourEnable) {
    this.contourCount = 0
    return
  }
  var level = getContour(this.cells, this.intensity, selection.intensity)
  var cells         = level.cells
  var vertexIds     = level.vertexIds
  var vertexWeights = level.vertexWeights
  var numCells = cells.length
  var result = pool.mallocFloat32(2 * 3 * numCells)
  var ptr = 0
  for(var i=0; i<numCells; ++i) {
    var c = cells[i]
    for(var j=0; j<2; ++j) {
      var v = c[0]
      if(c.length === 2) {
        v = c[j]
      }
      var a = vertexIds[v][0]
      var b = vertexIds[v][1]
      var w = vertexWeights[v]
      var wi = 1.0 - w
      var pa = this.positions[a]
      var pb = this.positions[b]
      for(var k=0; k<3; ++k) {
        result[ptr++] = w * pa[k] + wi * pb[k]
      }
    }
  }
  this.contourCount = (ptr / 3)|0
  this.contourPositions.update(result.subarray(0, ptr))
  pool.free(result)
}

proto.update = function(params) {
  params = params || {}
  var gl = this.gl

  this.dirty = true

  if('contourEnable' in params) {
    this.contourEnable = params.contourEnable
  }
  if('contourColor' in params) {
    this.contourColor = params.contourColor
  }
  if('lineWidth' in params) {
    this.lineWidth = params.lineWidth
  }
  if('lightPosition' in params) {
    this.lightPosition = params.lightPosition
  }
  if('opacity' in params) {
    this.opacity = params.opacity
  }
  if('ambient' in params) {
    this.ambientLight  = params.ambient
  }
  if('diffuse' in params) {
    this.diffuseLight = params.diffuse
  }
  if('specular' in params) {
    this.specularLight = params.specular
  }
  if('roughness' in params) {
    this.roughness = params.roughness
  }
  if('fresnel' in params) {
    this.fresnel = params.fresnel
  }

  if(params.texture) {
    this.texture.dispose()
    this.texture = createTexture(gl, params.texture)
  } else if (params.colormap) {
    this.texture.shape = [256,256]
    this.texture.minFilter = gl.LINEAR_MIPMAP_LINEAR
    this.texture.magFilter = gl.LINEAR
    this.texture.setPixels(genColormap(params.colormap))
    this.texture.generateMipmap()
  }

  var cells = params.cells
  var positions = params.positions

  if(!positions || !cells) {
    return
  }

  var tPos = []
  var tCol = []
  var tNor = []
  var tUVs = []
  var tIds = []

  var ePos = []
  var eCol = []
  var eUVs = []
  var eIds = []

  var pPos = []
  var pCol = []
  var pUVs = []
  var pSiz = []
  var pIds = []

  //Save geometry data for picking calculations
  this.cells     = cells
  this.positions = positions

  //Compute normals
  var vertexNormals = params.vertexNormals
  var cellNormals   = params.cellNormals
  var vertexNormalsEpsilon = params.vertexNormalsEpsilon === void(0) ? DEFAULT_VERTEX_NORMALS_EPSILON : params.vertexNormalsEpsilon
  var faceNormalsEpsilon = params.faceNormalsEpsilon === void(0) ? DEFAULT_FACE_NORMALS_EPSILON : params.faceNormalsEpsilon
  if(params.useFacetNormals && !cellNormals) {
    cellNormals = normals.faceNormals(cells, positions, faceNormalsEpsilon)
  }
  if(!cellNormals && !vertexNormals) {
    vertexNormals = normals.vertexNormals(cells, positions, vertexNormalsEpsilon)
  }

  //Compute colors
  var vertexColors    = params.vertexColors
  var cellColors      = params.cellColors
  var meshColor       = params.meshColor || [1,1,1,1]

  //UVs
  var vertexUVs       = params.vertexUVs
  var vertexIntensity = params.vertexIntensity
  var cellUVs         = params.cellUVs
  var cellIntensity   = params.cellIntensity

  var intensityLo     = Infinity
  var intensityHi     = -Infinity
  if(!vertexUVs && !cellUVs) {
    if(vertexIntensity) {
      if(params.vertexIntensityBounds) {
        intensityLo = +params.vertexIntensityBounds[0]
        intensityHi = +params.vertexIntensityBounds[1]
      } else {
        for(var i=0; i<vertexIntensity.length; ++i) {
          var f = vertexIntensity[i]
          intensityLo = Math.min(intensityLo, f)
          intensityHi = Math.max(intensityHi, f)
        }
      }
    } else if(cellIntensity) {
      for(var i=0; i<cellIntensity.length; ++i) {
        var f = cellIntensity[i]
        intensityLo = Math.min(intensityLo, f)
        intensityHi = Math.max(intensityHi, f)
      }
    } else {
      for(var i=0; i<positions.length; ++i) {
        var f = positions[i][2]
        intensityLo = Math.min(intensityLo, f)
        intensityHi = Math.max(intensityHi, f)
      }
    }
  }

  if(vertexIntensity) {
    this.intensity = vertexIntensity
  } else if(cellIntensity) {
    this.intensity = unpackIntensity(cells, positions.length, cellIntensity)
  } else {
    this.intensity = takeZComponent(positions)
  }

  //Point size
  var pointSizes      = params.pointSizes
  var meshPointSize   = params.pointSize || 1.0

  //Update bounds
  this.bounds       = [[Infinity,Infinity,Infinity], [-Infinity,-Infinity,-Infinity]]
  for(var i=0; i<positions.length; ++i) {
    var p = positions[i]
    for(var j=0; j<3; ++j) {
      if(isNaN(p[j]) || !isFinite(p[j])) {
        continue
      }
      this.bounds[0][j] = Math.min(this.bounds[0][j], p[j])
      this.bounds[1][j] = Math.max(this.bounds[1][j], p[j])
    }
  }

  //Pack cells into buffers
  var triangleCount = 0
  var edgeCount = 0
  var pointCount = 0

fill_loop:
  for(var i=0; i<cells.length; ++i) {
    var cell = cells[i]
    switch(cell.length) {
      case 1:

        var v = cell[0]
        var p = positions[v]

        //Check NaNs
        for(var j=0; j<3; ++j) {
          if(isNaN(p[j]) || !isFinite(p[j])) {
            continue fill_loop
          }
        }

        pPos.push(p[0], p[1], p[2])

        var c
        if(vertexColors) {
          c = vertexColors[v]
        } else if(cellColors) {
          c = cellColors[i]
        } else {
          c = meshColor
        }
        if(c.length === 3) {
          pCol.push(c[0], c[1], c[2], 1)
        } else {
          pCol.push(c[0], c[1], c[2], c[3])
        }

        var uv
        if(vertexUVs) {
          uv = vertexUVs[v]
        } else if(vertexIntensity) {
          uv = [
            (vertexIntensity[v] - intensityLo) /
            (intensityHi - intensityLo), 0]
        } else if(cellUVs) {
          uv = cellUVs[i]
        } else if(cellIntensity) {
          uv = [
            (cellIntensity[i] - intensityLo) /
            (intensityHi - intensityLo), 0]
        } else {
          uv = [
            (p[2] - intensityLo) /
            (intensityHi - intensityLo), 0]
        }
        pUVs.push(uv[0], uv[1])

        if(pointSizes) {
          pSiz.push(pointSizes[v])
        } else {
          pSiz.push(meshPointSize)
        }

        pIds.push(i)

        pointCount += 1
      break

      case 2:

        //Check NaNs
        for(var j=0; j<2; ++j) {
          var v = cell[j]
          var p = positions[v]
          for(var k=0; k<3; ++k) {
            if(isNaN(p[k]) || !isFinite(p[k])) {
              continue fill_loop
            }
          }
        }

        for(var j=0; j<2; ++j) {
          var v = cell[j]
          var p = positions[v]

          ePos.push(p[0], p[1], p[2])

          var c
          if(vertexColors) {
            c = vertexColors[v]
          } else if(cellColors) {
            c = cellColors[i]
          } else {
            c = meshColor
          }
          if(c.length === 3) {
            eCol.push(c[0], c[1], c[2], 1)
          } else {
            eCol.push(c[0], c[1], c[2], c[3])
          }

          var uv
          if(vertexUVs) {
            uv = vertexUVs[v]
          } else if(vertexIntensity) {
            uv = [
              (vertexIntensity[v] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else if(cellUVs) {
            uv = cellUVs[i]
          } else if(cellIntensity) {
            uv = [
              (cellIntensity[i] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else {
            uv = [
              (p[2] - intensityLo) /
              (intensityHi - intensityLo), 0]
          }
          eUVs.push(uv[0], uv[1])

          eIds.push(i)
        }
        edgeCount += 1
      break

      case 3:
        //Check NaNs
        for(var j=0; j<3; ++j) {
          var v = cell[j]
          var p = positions[v]
          for(var k=0; k<3; ++k) {
            if(isNaN(p[k]) || !isFinite(p[k])) {
              continue fill_loop
            }
          }
        }

        for(var j=0; j<3; ++j) {
          var v = cell[2 - j]

          var p = positions[v]
          tPos.push(p[0], p[1], p[2])

          var c
          if(vertexColors) {
            c = vertexColors[v]
          } else if(cellColors) {
            c = cellColors[i]
          } else {
            c = meshColor
          }
          if(c.length === 3) {
            tCol.push(c[0], c[1], c[2], 1)
          } else {
            tCol.push(c[0], c[1], c[2], c[3])
          }

          var uv
          if(vertexUVs) {
            uv = vertexUVs[v]
          } else if(vertexIntensity) {
            uv = [
              (vertexIntensity[v] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else if(cellUVs) {
            uv = cellUVs[i]
          } else if(cellIntensity) {
            uv = [
              (cellIntensity[i] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else {
            uv = [
              (p[2] - intensityLo) /
              (intensityHi - intensityLo), 0]
          }
          tUVs.push(uv[0], uv[1])

          var q
          if(vertexNormals) {
            q = vertexNormals[v]
          } else {
            q = cellNormals[i]
          }
          tNor.push(q[0], q[1], q[2])

          tIds.push(i)
        }
        triangleCount += 1
      break

      default:
      break
    }
  }

  this.pointCount     = pointCount
  this.edgeCount      = edgeCount
  this.triangleCount  = triangleCount

  this.pointPositions.update(pPos)
  this.pointColors.update(pCol)
  this.pointUVs.update(pUVs)
  this.pointSizes.update(pSiz)
  this.pointIds.update(new Uint32Array(pIds))

  this.edgePositions.update(ePos)
  this.edgeColors.update(eCol)
  this.edgeUVs.update(eUVs)
  this.edgeIds.update(new Uint32Array(eIds))

  this.trianglePositions.update(tPos)
  this.triangleColors.update(tCol)
  this.triangleUVs.update(tUVs)
  this.triangleNormals.update(tNor)
  this.triangleIds.update(new Uint32Array(tIds))
}

proto.drawTransparent = proto.draw = function(params) {
  params = params || {}
  var gl          = this.gl
  var model       = params.model      || IDENTITY
  var view        = params.view       || IDENTITY
  var projection  = params.projection || IDENTITY

  var clipBounds = [[-1e6,-1e6,-1e6],[1e6,1e6,1e6]]
  for(var i=0; i<3; ++i) {
    clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i])
    clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i])
  }

  var uniforms = {
    model:      model,
    view:       view,
    projection: projection,
    inverseModel: IDENTITY.slice(),

    clipBounds: clipBounds,

    kambient:   this.ambientLight,
    kdiffuse:   this.diffuseLight,
    kspecular:  this.specularLight,
    roughness:  this.roughness,
    fresnel:    this.fresnel,

    eyePosition:   [0,0,0],
    lightPosition: [0,0,0],

    opacity:  this.opacity,

    contourColor: this.contourColor,

    texture:    0
  }

  uniforms.inverseModel = invert(uniforms.inverseModel, uniforms.model)

  gl.disable(gl.CULL_FACE)

  this.texture.bind(0)

  var invCameraMatrix = new Array(16)
  multiply(invCameraMatrix, uniforms.view, uniforms.model)
  multiply(invCameraMatrix, uniforms.projection, invCameraMatrix)
  invert(invCameraMatrix, invCameraMatrix)

  for(var i=0; i<3; ++i) {
    uniforms.eyePosition[i] = invCameraMatrix[12+i] / invCameraMatrix[15]
  }

  var w = invCameraMatrix[15]
  for(var i=0; i<3; ++i) {
    w += this.lightPosition[i] * invCameraMatrix[4*i+3]
  }
  for(var i=0; i<3; ++i) {
    var s = invCameraMatrix[12+i]
    for(var j=0; j<3; ++j) {
      s += invCameraMatrix[4*j+i] * this.lightPosition[j]
    }
    uniforms.lightPosition[i] = s / w
  }

  if(this.triangleCount > 0) {
    var shader = this.triShader
    shader.bind()
    shader.uniforms = uniforms

    this.triangleVAO.bind()
    gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3)
    this.triangleVAO.unbind()
  }

  if(this.edgeCount > 0 && this.lineWidth > 0) {
    var shader = this.lineShader
    shader.bind()
    shader.uniforms = uniforms

    this.edgeVAO.bind()
    gl.lineWidth(this.lineWidth * this.pixelRatio)
    gl.drawArrays(gl.LINES, 0, this.edgeCount*2)
    this.edgeVAO.unbind()
  }

  if(this.pointCount > 0) {
    var shader = this.pointShader
    shader.bind()
    shader.uniforms = uniforms

    this.pointVAO.bind()
    gl.drawArrays(gl.POINTS, 0, this.pointCount)
    this.pointVAO.unbind()
  }

  if(this.contourEnable && this.contourCount > 0 && this.contourLineWidth > 0) {
    var shader = this.contourShader
    shader.bind()
    shader.uniforms = uniforms

    this.contourVAO.bind()
    gl.drawArrays(gl.LINES, 0, this.contourCount)
    this.contourVAO.unbind()
  }
}

proto.drawPick = function(params) {
  params = params || {}

  var gl         = this.gl

  var model      = params.model      || IDENTITY
  var view       = params.view       || IDENTITY
  var projection = params.projection || IDENTITY

  var clipBounds = [[-1e6,-1e6,-1e6],[1e6,1e6,1e6]]
  for(var i=0; i<3; ++i) {
    clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i])
    clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i])
  }

  //Save camera parameters
  this._model      = [].slice.call(model)
  this._view       = [].slice.call(view)
  this._projection = [].slice.call(projection)
  this._resolution = [gl.drawingBufferWidth, gl.drawingBufferHeight]

  var uniforms = {
    model:      model,
    view:       view,
    projection: projection,
    clipBounds: clipBounds,
    pickId:     this.pickId / 255.0,
  }

  var shader = this.pickShader
  shader.bind()
  shader.uniforms = uniforms

  if(this.triangleCount > 0) {
    this.triangleVAO.bind()
    gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3)
    this.triangleVAO.unbind()
  }

  if(this.edgeCount > 0) {
    this.edgeVAO.bind()
    gl.lineWidth(this.lineWidth * this.pixelRatio)
    gl.drawArrays(gl.LINES, 0, this.edgeCount*2)
    this.edgeVAO.unbind()
  }

  if(this.pointCount > 0) {
    var shader = this.pointPickShader
    shader.bind()
    shader.uniforms = uniforms

    this.pointVAO.bind()
    gl.drawArrays(gl.POINTS, 0, this.pointCount)
    this.pointVAO.unbind()
  }
}


proto.pick = function(pickData) {
  if(!pickData) {
    return null
  }
  if(pickData.id !== this.pickId) {
    return null
  }

  var cellId    = pickData.value[0] + 256*pickData.value[1] + 65536*pickData.value[2]
  var cell      = this.cells[cellId]
  var positions = this.positions

  var simplex   = new Array(cell.length)
  for(var i=0; i<cell.length; ++i) {
    simplex[i] = positions[cell[i]]
  }

  var data = closestPoint(
    simplex,
    [pickData.coord[0], this._resolution[1]-pickData.coord[1]],
    this._model,
    this._view,
    this._projection,
    this._resolution)

  if(!data) {
    return null
  }

  var weights = data[2]
  var interpIntensity = 0.0
  for(var i=0; i<cell.length; ++i) {
    interpIntensity += weights[i] * this.intensity[cell[i]]
  }

  return {
    position: data[1],
    index:    cell[data[0]],
    cell:     cell,
    cellId:   cellId,
    intensity:  interpIntensity,
    dataCoordinate: this.positions[cell[data[0]]]
  }
}


proto.dispose = function() {
  this.texture.dispose()

  this.triShader.dispose()
  this.lineShader.dispose()
  this.pointShader.dispose()
  this.pickShader.dispose()
  this.pointPickShader.dispose()

  this.triangleVAO.dispose()
  this.trianglePositions.dispose()
  this.triangleColors.dispose()
  this.triangleUVs.dispose()
  this.triangleNormals.dispose()
  this.triangleIds.dispose()

  this.edgeVAO.dispose()
  this.edgePositions.dispose()
  this.edgeColors.dispose()
  this.edgeUVs.dispose()
  this.edgeIds.dispose()

  this.pointVAO.dispose()
  this.pointPositions.dispose()
  this.pointColors.dispose()
  this.pointUVs.dispose()
  this.pointSizes.dispose()
  this.pointIds.dispose()

  this.contourVAO.dispose()
  this.contourPositions.dispose()
  this.contourShader.dispose()
}

function createMeshShader(gl) {
  var shader = createShader(gl, meshShader.vertex, meshShader.fragment)
  shader.attributes.position.location = 0
  shader.attributes.color.location    = 2
  shader.attributes.uv.location       = 3
  shader.attributes.normal.location   = 4
  return shader
}

function createWireShader(gl) {
  var shader = createShader(gl, wireShader.vertex, wireShader.fragment)
  shader.attributes.position.location = 0
  shader.attributes.color.location    = 2
  shader.attributes.uv.location       = 3
  return shader
}

function createPointShader(gl) {
  var shader = createShader(gl, pointShader.vertex, pointShader.fragment)
  shader.attributes.position.location  = 0
  shader.attributes.color.location     = 2
  shader.attributes.uv.location        = 3
  shader.attributes.pointSize.location = 4
  return shader
}

function createPickShader(gl) {
  var shader = createShader(gl, pickShader.vertex, pickShader.fragment)
  shader.attributes.position.location = 0
  shader.attributes.id.location       = 1
  return shader
}

function createPointPickShader(gl) {
  var shader = createShader(gl, pointPickShader.vertex, pointPickShader.fragment)
  shader.attributes.position.location  = 0
  shader.attributes.id.location        = 1
  shader.attributes.pointSize.location = 4
  return shader
}

function createContourShader(gl) {
  var shader = createShader(gl, contourShader.vertex, contourShader.fragment)
  shader.attributes.position.location = 0
  return shader
}

function createSimplicialMesh(gl, params) {
  if (arguments.length === 1) {
    params = gl;
    gl = params.gl;
  }

  //enable derivatives for face normals
  var ext = gl.getExtension('OES_standard_derivatives') || gl.getExtension('MOZ_OES_standard_derivatives') || gl.getExtension('WEBKIT_OES_standard_derivatives')
  if (!ext)
    throw new Error('derivatives not supported')

  var triShader       = createMeshShader(gl)
  var lineShader      = createWireShader(gl)
  var pointShader     = createPointShader(gl)
  var pickShader      = createPickShader(gl)
  var pointPickShader = createPointPickShader(gl)
  var contourShader   = createContourShader(gl)

  var meshTexture       = createTexture(gl,
    ndarray(new Uint8Array([255,255,255,255]), [1,1,4]))
  meshTexture.generateMipmap()
  meshTexture.minFilter = gl.LINEAR_MIPMAP_LINEAR
  meshTexture.magFilter = gl.LINEAR

  var trianglePositions = createBuffer(gl)
  var triangleColors    = createBuffer(gl)
  var triangleUVs       = createBuffer(gl)
  var triangleNormals   = createBuffer(gl)
  var triangleIds       = createBuffer(gl)
  var triangleVAO       = createVAO(gl, [
    { buffer: trianglePositions,
      type: gl.FLOAT,
      size: 3
    },
    { buffer: triangleIds,
      type: gl.UNSIGNED_BYTE,
      size: 4,
      normalized: true
    },
    { buffer: triangleColors,
      type: gl.FLOAT,
      size: 4
    },
    { buffer: triangleUVs,
      type: gl.FLOAT,
      size: 2
    },
    { buffer: triangleNormals,
      type: gl.FLOAT,
      size: 3
    }
  ])

  var edgePositions = createBuffer(gl)
  var edgeColors    = createBuffer(gl)
  var edgeUVs       = createBuffer(gl)
  var edgeIds       = createBuffer(gl)
  var edgeVAO       = createVAO(gl, [
    { buffer: edgePositions,
      type: gl.FLOAT,
      size: 3
    },
    { buffer: edgeIds,
      type: gl.UNSIGNED_BYTE,
      size: 4,
      normalized: true
    },
    { buffer: edgeColors,
      type: gl.FLOAT,
      size: 4
    },
    { buffer: edgeUVs,
      type: gl.FLOAT,
      size: 2
    }
  ])

  var pointPositions  = createBuffer(gl)
  var pointColors     = createBuffer(gl)
  var pointUVs        = createBuffer(gl)
  var pointSizes      = createBuffer(gl)
  var pointIds        = createBuffer(gl)
  var pointVAO        = createVAO(gl, [
    { buffer: pointPositions,
      type: gl.FLOAT,
      size: 3
    },
    { buffer: pointIds,
      type: gl.UNSIGNED_BYTE,
      size: 4,
      normalized: true
    },
    { buffer: pointColors,
      type: gl.FLOAT,
      size: 4
    },
    { buffer: pointUVs,
      type: gl.FLOAT,
      size: 2
    },
    { buffer: pointSizes,
      type: gl.FLOAT,
      size: 1
    }
  ])

  var contourPositions = createBuffer(gl)
  var contourVAO       = createVAO(gl, [
    { buffer: contourPositions,
      type:   gl.FLOAT,
      size:   3
    }])

  var mesh = new SimplicialMesh(gl
    , meshTexture
    , triShader
    , lineShader
    , pointShader
    , pickShader
    , pointPickShader
    , contourShader
    , trianglePositions
    , triangleIds
    , triangleColors
    , triangleUVs
    , triangleNormals
    , triangleVAO
    , edgePositions
    , edgeIds
    , edgeColors
    , edgeUVs
    , edgeVAO
    , pointPositions
    , pointIds
    , pointColors
    , pointUVs
    , pointSizes
    , pointVAO
    , contourPositions
    , contourVAO)

  mesh.update(params)

  return mesh
}

module.exports = createSimplicialMesh

},{"./lib/closest-point":271,"./lib/shaders":272,"colormap":114,"gl-buffer":234,"gl-mat4/invert":258,"gl-mat4/multiply":260,"gl-shader":294,"gl-texture2d":311,"gl-vao":316,"ndarray":439,"normals":442,"simplicial-complex-contour":499,"typedarray-pool":526}],274:[function(_dereq_,module,exports){
'use strict'

module.exports = createBoxes

var createBuffer = _dereq_('gl-buffer')
var createShader = _dereq_('gl-shader')

var shaders = _dereq_('./shaders')

function Boxes(plot, vbo, shader) {
  this.plot   = plot
  this.vbo    = vbo
  this.shader = shader
}

var proto = Boxes.prototype

proto.bind = function() {
  var shader = this.shader
  this.vbo.bind()
  this.shader.bind()
  shader.attributes.coord.pointer()
  shader.uniforms.screenBox = this.plot.screenBox
}

proto.drawBox = (function() {
  var lo = [0,0]
  var hi = [0,0]
  return function(loX, loY, hiX, hiY, color) {
    var plot       = this.plot
    var shader     = this.shader
    var gl         = plot.gl

    lo[0] = loX
    lo[1] = loY
    hi[0] = hiX
    hi[1] = hiY

    shader.uniforms.lo     = lo
    shader.uniforms.hi     = hi
    shader.uniforms.color  = color

    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
  }
}())

proto.dispose = function() {
  this.vbo.dispose()
  this.shader.dispose()
}

function createBoxes(plot) {
  var gl  = plot.gl
  var vbo = createBuffer(gl, [
    0,0,
    0,1,
    1,0,
    1,1])
  var shader  = createShader(gl, shaders.boxVert, shaders.lineFrag)
  return new Boxes(plot, vbo, shader)
}

},{"./shaders":277,"gl-buffer":234,"gl-shader":294}],275:[function(_dereq_,module,exports){
'use strict'

module.exports = createGrid

var createBuffer  = _dereq_('gl-buffer')
var createShader  = _dereq_('gl-shader')
var bsearch       = _dereq_('binary-search-bounds')
var shaders       = _dereq_('./shaders')

function Grid(plot, vbo, shader, tickShader) {
  this.plot   = plot
  this.vbo    = vbo
  this.shader = shader
  this.tickShader = tickShader
  this.ticks  = [[], []]
}

function compareTickNum(a, b) {
  return a - b
}

var proto = Grid.prototype

proto.draw = (function() {

  var DATA_SHIFT = [0,0]
  var DATA_SCALE = [0,0]
  var DATA_AXIS  = [0,0]

  return function() {
    var plot       = this.plot
    var vbo        = this.vbo
    var shader     = this.shader
    var ticks      = this.ticks
    var gl         = plot.gl
    var bounds     = plot._tickBounds
    var dataBox    = plot.dataBox
    var viewPixels = plot.viewBox
    var lineWidth  = plot.gridLineWidth
    var gridColor  = plot.gridLineColor
    var gridEnable = plot.gridLineEnable
    var pixelRatio = plot.pixelRatio

    for(var i=0; i<2; ++i) {
      var lo = bounds[i]
      var hi = bounds[i+2]
      var boundScale = hi - lo
      var dataCenter  = 0.5 * (dataBox[i+2] + dataBox[i])
      var dataWidth   = dataBox[i+2] - dataBox[i]
      DATA_SCALE[i] = 2.0 * boundScale / dataWidth
      DATA_SHIFT[i] = 2.0 * (lo - dataCenter) / dataWidth
    }

    shader.bind()
    vbo.bind()
    shader.attributes.dataCoord.pointer()
    shader.uniforms.dataShift = DATA_SHIFT
    shader.uniforms.dataScale = DATA_SCALE

    var offset = 0
    for(var i=0; i<2; ++i) {
      DATA_AXIS[0] = DATA_AXIS[1] = 0
      DATA_AXIS[i] = 1
      shader.uniforms.dataAxis  = DATA_AXIS
      shader.uniforms.lineWidth = lineWidth[i] / (viewPixels[i+2] - viewPixels[i]) * pixelRatio
      shader.uniforms.color     = gridColor[i]

      var size = ticks[i].length * 6
      if(gridEnable[i] && size) {
        gl.drawArrays(gl.TRIANGLES, offset, size)
      }
      offset += size
    }
  }
})()

proto.drawTickMarks = (function() {
  var DATA_SHIFT = [0,0]
  var DATA_SCALE = [0,0]
  var X_AXIS     = [1,0]
  var Y_AXIS     = [0,1]
  var SCR_OFFSET = [0,0]
  var TICK_SCALE = [0,0]

  return function() {
    var plot       = this.plot
    var vbo        = this.vbo
    var shader     = this.tickShader
    var ticks      = this.ticks
    var gl         = plot.gl
    var bounds     = plot._tickBounds
    var dataBox    = plot.dataBox
    var viewBox    = plot.viewBox
    var pixelRatio = plot.pixelRatio
    var screenBox  = plot.screenBox

    var screenWidth  = screenBox[2] - screenBox[0]
    var screenHeight = screenBox[3] - screenBox[1]
    var viewWidth    = viewBox[2]   - viewBox[0]
    var viewHeight   = viewBox[3]   - viewBox[1]

    for(var i=0; i<2; ++i) {
      var lo = bounds[i]
      var hi = bounds[i+2]
      var boundScale = hi - lo
      var dataCenter  = 0.5 * (dataBox[i+2] + dataBox[i])
      var dataWidth   = (dataBox[i+2] - dataBox[i])
      DATA_SCALE[i] = 2.0 * boundScale / dataWidth
      DATA_SHIFT[i] = 2.0 * (lo - dataCenter) / dataWidth
    }

    DATA_SCALE[0] *= viewWidth / screenWidth
    DATA_SHIFT[0] *= viewWidth / screenWidth

    DATA_SCALE[1] *= viewHeight / screenHeight
    DATA_SHIFT[1] *= viewHeight / screenHeight

    shader.bind()
    vbo.bind()

    shader.attributes.dataCoord.pointer()

    var uniforms = shader.uniforms
    uniforms.dataShift = DATA_SHIFT
    uniforms.dataScale = DATA_SCALE

    var tickMarkLength = plot.tickMarkLength
    var tickMarkWidth  = plot.tickMarkWidth
    var tickMarkColor  = plot.tickMarkColor

    var xTicksOffset = 0
    var yTicksOffset = ticks[0].length * 6

    var xStart = Math.min(bsearch.ge(ticks[0], (dataBox[0] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length)
    var xEnd   = Math.min(bsearch.gt(ticks[0], (dataBox[2] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length)
    var xOffset = xTicksOffset + 6 * xStart
    var xCount  = 6 * Math.max(0, xEnd - xStart)

    var yStart = Math.min(bsearch.ge(ticks[1], (dataBox[1] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length)
    var yEnd   = Math.min(bsearch.gt(ticks[1], (dataBox[3] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length)
    var yOffset = yTicksOffset + 6 * yStart
    var yCount  = 6 * Math.max(0, yEnd - yStart)

    SCR_OFFSET[0]         = 2.0 * (viewBox[0] - tickMarkLength[1]) / screenWidth - 1.0
    SCR_OFFSET[1]         = (viewBox[3] + viewBox[1]) / screenHeight - 1.0
    TICK_SCALE[0]         = tickMarkLength[1] * pixelRatio / screenWidth
    TICK_SCALE[1]         = tickMarkWidth[1]  * pixelRatio / screenHeight

    if(yCount) {
      uniforms.color        = tickMarkColor[1]
      uniforms.tickScale    = TICK_SCALE
      uniforms.dataAxis     = Y_AXIS
      uniforms.screenOffset = SCR_OFFSET
      gl.drawArrays(gl.TRIANGLES, yOffset, yCount)
    }

    SCR_OFFSET[0]         = (viewBox[2] + viewBox[0]) / screenWidth - 1.0
    SCR_OFFSET[1]         = 2.0 * (viewBox[1] - tickMarkLength[0]) / screenHeight - 1.0
    TICK_SCALE[0]         = tickMarkWidth[0]  * pixelRatio / screenWidth
    TICK_SCALE[1]         = tickMarkLength[0] * pixelRatio / screenHeight

    if(xCount) {
      uniforms.color        = tickMarkColor[0]
      uniforms.tickScale    = TICK_SCALE
      uniforms.dataAxis     = X_AXIS
      uniforms.screenOffset = SCR_OFFSET
      gl.drawArrays(gl.TRIANGLES, xOffset, xCount)
    }

    SCR_OFFSET[0]         = 2.0 * (viewBox[2] + tickMarkLength[3]) / screenWidth - 1.0
    SCR_OFFSET[1]         = (viewBox[3] + viewBox[1]) / screenHeight - 1.0
    TICK_SCALE[0]         = tickMarkLength[3] * pixelRatio / screenWidth
    TICK_SCALE[1]         = tickMarkWidth[3]  * pixelRatio / screenHeight

    if(yCount) {
      uniforms.color        = tickMarkColor[3]
      uniforms.tickScale    = TICK_SCALE
      uniforms.dataAxis     = Y_AXIS
      uniforms.screenOffset = SCR_OFFSET
      gl.drawArrays(gl.TRIANGLES, yOffset, yCount)
    }

    SCR_OFFSET[0]         = (viewBox[2] + viewBox[0]) / screenWidth - 1.0
    SCR_OFFSET[1]         = 2.0 * (viewBox[3] + tickMarkLength[2]) / screenHeight - 1.0
    TICK_SCALE[0]         = tickMarkWidth[2]  * pixelRatio / screenWidth
    TICK_SCALE[1]         = tickMarkLength[2] * pixelRatio / screenHeight

    if(xCount) {
      uniforms.color        = tickMarkColor[2]
      uniforms.tickScale    = TICK_SCALE
      uniforms.dataAxis     = X_AXIS
      uniforms.screenOffset = SCR_OFFSET
      gl.drawArrays(gl.TRIANGLES, xOffset, xCount)
    }
  }
})()

proto.update = (function() {
  var OFFSET_X = [1,  1, -1, -1,  1, -1]
  var OFFSET_Y = [1, -1,  1,  1, -1, -1]

  return function(options) {
    var ticks  = options.ticks
    var bounds = options.bounds
    var data   = new Float32Array(6 * 3 * (ticks[0].length + ticks[1].length))

    var zeroLineEnable = this.plot.zeroLineEnable

    var ptr    = 0
    var gridTicks = [[], []]
    for(var dim=0; dim<2; ++dim) {
      var localTicks = gridTicks[dim]
      var axisTicks = ticks[dim]
      var lo = bounds[dim]
      var hi = bounds[dim+2]
      for(var i=0; i<axisTicks.length; ++i) {
        var x = (axisTicks[i].x - lo) / (hi - lo)
        localTicks.push(x)
        for(var j=0; j<6; ++j) {
          data[ptr++] = x
          data[ptr++] = OFFSET_X[j]
          data[ptr++] = OFFSET_Y[j]
        }
      }
    }

    this.ticks = gridTicks
    this.vbo.update(data)
  }
})()

proto.dispose = function() {
  this.vbo.dispose()
  this.shader.dispose()
  this.tickShader.dispose()
}

function createGrid(plot) {
  var gl     = plot.gl
  var vbo    = createBuffer(gl)
  var shader = createShader(gl, shaders.gridVert, shaders.gridFrag)
  var tickShader = createShader(gl, shaders.tickVert, shaders.gridFrag)
  var grid   = new Grid(plot, vbo, shader, tickShader)
  return grid
}

},{"./shaders":277,"binary-search-bounds":279,"gl-buffer":234,"gl-shader":294}],276:[function(_dereq_,module,exports){
'use strict'

module.exports = createLines

var createBuffer = _dereq_('gl-buffer')
var createShader = _dereq_('gl-shader')

var shaders = _dereq_('./shaders')

function Lines(plot, vbo, shader) {
  this.plot   = plot
  this.vbo    = vbo
  this.shader = shader
}

var proto = Lines.prototype

proto.bind = function() {
  var shader = this.shader
  this.vbo.bind()
  this.shader.bind()
  shader.attributes.coord.pointer()
  shader.uniforms.screenBox = this.plot.screenBox
}

proto.drawLine = (function() {
  var start = [0,0]
  var end   = [0,0]
  return function(startX, startY, endX, endY, width, color) {
    var plot       = this.plot
    var shader     = this.shader
    var gl         = plot.gl

    start[0] = startX
    start[1] = startY
    end[0]   = endX
    end[1]   = endY

    shader.uniforms.start  = start
    shader.uniforms.end    = end
    shader.uniforms.width  = width * plot.pixelRatio
    shader.uniforms.color  = color

    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
  }
}())

proto.dispose = function() {
  this.vbo.dispose()
  this.shader.dispose()
}

function createLines(plot) {
  var gl  = plot.gl
  var vbo = createBuffer(gl, [
    -1,-1,
    -1,1,
    1,-1,
    1,1])
  var shader  = createShader(gl, shaders.lineVert, shaders.lineFrag)
  var lines   = new Lines(plot, vbo, shader)
  return lines
}

},{"./shaders":277,"gl-buffer":234,"gl-shader":294}],277:[function(_dereq_,module,exports){
'use strict'

var glslify = _dereq_('glslify')

var FRAGMENT = glslify(["precision lowp float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n  gl_FragColor = vec4(color.xyz * color.w, color.w);\n}\n"])

module.exports = {
  lineVert: glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 start, end;\nuniform float width;\n\nvec2 perp(vec2 v) {\n  return vec2(v.y, -v.x);\n}\n\nvec2 screen(vec2 v) {\n  return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n  vec2 delta = normalize(perp(start - end));\n  vec2 offset = mix(start, end, 0.5 * (coord.y+1.0));\n  gl_Position = vec4(screen(offset + 0.5 * width * delta * coord.x), 0, 1);\n}\n"]),
  lineFrag: FRAGMENT,
  textVert: glslify(["#define GLSLIFY 1\nattribute vec3 textCoordinate;\n\nuniform vec2 dataScale, dataShift, dataAxis, screenOffset, textScale;\nuniform float angle;\n\nvoid main() {\n  float dataOffset  = textCoordinate.z;\n  vec2 glyphOffset  = textCoordinate.xy;\n  mat2 glyphMatrix = mat2(cos(angle), sin(angle), -sin(angle), cos(angle));\n  vec2 screenCoordinate = dataAxis * (dataScale * dataOffset + dataShift) +\n    glyphMatrix * glyphOffset * textScale + screenOffset;\n  gl_Position = vec4(screenCoordinate, 0, 1);\n}\n"]),
  textFrag: FRAGMENT,
  gridVert: glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale;\nuniform float lineWidth;\n\nvoid main() {\n  vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n  pos += 10.0 * dataCoord.y * vec2(dataAxis.y, -dataAxis.x) + dataCoord.z * lineWidth;\n  gl_Position = vec4(pos, 0, 1);\n}\n"]),
  gridFrag: FRAGMENT,
  boxVert:  glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 lo, hi;\n\nvec2 screen(vec2 v) {\n  return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n  gl_Position = vec4(screen(mix(lo, hi, coord)), 0, 1);\n}\n"]),
  tickVert: glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale, screenOffset, tickScale;\n\nvoid main() {\n  vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n  gl_Position = vec4(pos + tickScale*dataCoord.yz + screenOffset, 0, 1);\n}\n"])
}

},{"glslify":398}],278:[function(_dereq_,module,exports){
'use strict'

module.exports = createTextElements

var createBuffer = _dereq_('gl-buffer')
var createShader = _dereq_('gl-shader')
var getText      = _dereq_('text-cache')
var bsearch      = _dereq_('binary-search-bounds')
var shaders      = _dereq_('./shaders')

function TextElements(plot, vbo, shader) {
  this.plot         = plot
  this.vbo          = vbo
  this.shader       = shader
  this.tickOffset   = [[],[]]
  this.tickX        = [[],[]]
  this.labelOffset  = [0,0]
  this.labelCount   = [0,0]
}

var proto = TextElements.prototype

proto.drawTicks = (function() {
  var DATA_AXIS = [0,0]
  var SCREEN_OFFSET = [0,0]
  var ZERO_2 = [0,0]

  return function(axis) {
    var plot        = this.plot
    var shader      = this.shader
    var tickX       = this.tickX[axis]
    var tickOffset  = this.tickOffset[axis]
    var gl          = plot.gl
    var viewBox     = plot.viewBox
    var dataBox     = plot.dataBox
    var screenBox   = plot.screenBox
    var pixelRatio  = plot.pixelRatio
    var tickEnable  = plot.tickEnable
    var tickPad     = plot.tickPad
    var textColor   = plot.tickColor
    var textAngle   = plot.tickAngle
    // todo check if this should be used (now unused)
    // var tickLength  = plot.tickMarkLength

    var labelEnable = plot.labelEnable
    var labelPad    = plot.labelPad
    var labelColor  = plot.labelColor
    var labelAngle  = plot.labelAngle
    var labelOffset = this.labelOffset[axis]
    var labelCount  = this.labelCount[axis]

    var start = bsearch.lt(tickX, dataBox[axis])
    var end   = bsearch.le(tickX, dataBox[axis+2])

    DATA_AXIS[0]    = DATA_AXIS[1] = 0
    DATA_AXIS[axis] = 1

    SCREEN_OFFSET[axis] = (viewBox[2+axis] + viewBox[axis]) / (screenBox[2+axis] - screenBox[axis]) - 1.0

    var screenScale = 2.0 / screenBox[2+(axis^1)] - screenBox[axis^1]

    SCREEN_OFFSET[axis^1] = screenScale * viewBox[axis^1] - 1.0
    if(tickEnable[axis]) {
      SCREEN_OFFSET[axis^1] -= screenScale * pixelRatio * tickPad[axis]
      if(start < end && tickOffset[end] > tickOffset[start]) {
        shader.uniforms.dataAxis     = DATA_AXIS
        shader.uniforms.screenOffset = SCREEN_OFFSET
        shader.uniforms.color        = textColor[axis]
        shader.uniforms.angle        = textAngle[axis]
        gl.drawArrays(
          gl.TRIANGLES,
          tickOffset[start],
          tickOffset[end] - tickOffset[start])
      }
    }
    if(labelEnable[axis] && labelCount) {
      SCREEN_OFFSET[axis^1] -= screenScale * pixelRatio * labelPad[axis]
      shader.uniforms.dataAxis     = ZERO_2
      shader.uniforms.screenOffset = SCREEN_OFFSET
      shader.uniforms.color        = labelColor[axis]
      shader.uniforms.angle        = labelAngle[axis]
      gl.drawArrays(
        gl.TRIANGLES,
        labelOffset,
        labelCount)
    }

    SCREEN_OFFSET[axis^1] = screenScale * viewBox[2+(axis^1)] - 1.0
    if(tickEnable[axis+2]) {
      SCREEN_OFFSET[axis^1] += screenScale * pixelRatio * tickPad[axis+2]
      if(start < end && tickOffset[end] > tickOffset[start]) {
        shader.uniforms.dataAxis     = DATA_AXIS
        shader.uniforms.screenOffset = SCREEN_OFFSET
        shader.uniforms.color        = textColor[axis+2]
        shader.uniforms.angle        = textAngle[axis+2]
        gl.drawArrays(
          gl.TRIANGLES,
          tickOffset[start],
          tickOffset[end] - tickOffset[start])
      }
    }
    if(labelEnable[axis+2] && labelCount) {
      SCREEN_OFFSET[axis^1] += screenScale * pixelRatio * labelPad[axis+2]
      shader.uniforms.dataAxis     = ZERO_2
      shader.uniforms.screenOffset = SCREEN_OFFSET
      shader.uniforms.color        = labelColor[axis+2]
      shader.uniforms.angle        = labelAngle[axis+2]
      gl.drawArrays(
        gl.TRIANGLES,
        labelOffset,
        labelCount)
    }

  }
})()

proto.drawTitle = (function() {
  var DATA_AXIS = [0,0]
  var SCREEN_OFFSET = [0,0]

  return function() {
    var plot        = this.plot
    var shader      = this.shader
    var gl          = plot.gl
    var screenBox   = plot.screenBox
    var titleCenter = plot.titleCenter
    var titleAngle  = plot.titleAngle
    var titleColor  = plot.titleColor
    var pixelRatio  = plot.pixelRatio

    if(!this.titleCount) {
      return
    }

    for(var i=0; i<2; ++i) {
      SCREEN_OFFSET[i] = 2.0 * (titleCenter[i]*pixelRatio - screenBox[i]) /
        (screenBox[2+i] - screenBox[i]) - 1
    }

    shader.bind()
    shader.uniforms.dataAxis      = DATA_AXIS
    shader.uniforms.screenOffset  = SCREEN_OFFSET
    shader.uniforms.angle         = titleAngle
    shader.uniforms.color         = titleColor

    gl.drawArrays(gl.TRIANGLES, this.titleOffset, this.titleCount)
  }
})()

proto.bind = (function() {
  var DATA_SHIFT = [0,0]
  var DATA_SCALE = [0,0]
  var TEXT_SCALE = [0,0]

  return function() {
    var plot      = this.plot
    var shader    = this.shader
    var bounds    = plot._tickBounds
    var dataBox   = plot.dataBox
    var screenBox = plot.screenBox
    var viewBox   = plot.viewBox

    shader.bind()

    //Set up coordinate scaling uniforms
    for(var i=0; i<2; ++i) {

      var lo = bounds[i]
      var hi = bounds[i+2]
      var boundScale = hi - lo
      var dataCenter  = 0.5 * (dataBox[i+2] + dataBox[i])
      var dataWidth   = (dataBox[i+2] - dataBox[i])

      var viewLo = viewBox[i]
      var viewHi = viewBox[i+2]
      var viewScale = viewHi - viewLo
      var screenLo = screenBox[i]
      var screenHi = screenBox[i+2]
      var screenScale = screenHi - screenLo

      DATA_SCALE[i] = 2.0 * boundScale / dataWidth * viewScale / screenScale
      DATA_SHIFT[i] = 2.0 * (lo - dataCenter) / dataWidth * viewScale / screenScale
    }

    TEXT_SCALE[1] = 2.0 * plot.pixelRatio / (screenBox[3] - screenBox[1])
    TEXT_SCALE[0] = TEXT_SCALE[1] * (screenBox[3] - screenBox[1]) / (screenBox[2] - screenBox[0])

    shader.uniforms.dataScale = DATA_SCALE
    shader.uniforms.dataShift = DATA_SHIFT
    shader.uniforms.textScale = TEXT_SCALE

    //Set attributes
    this.vbo.bind()
    shader.attributes.textCoordinate.pointer()
  }
})()

proto.update = function(options) {
  var vertices  = []
  var axesTicks = options.ticks
  var bounds    = options.bounds
  var i, j, k, data, scale, dimension

  for(dimension=0; dimension<2; ++dimension) {
    var offsets = [Math.floor(vertices.length/3)], tickX = [-Infinity]

    //Copy vertices over to buffer
    var ticks = axesTicks[dimension]
    for(i=0; i<ticks.length; ++i) {
      var tick  = ticks[i]
      var x     = tick.x
      var text  = tick.text
      var font  = tick.font || 'sans-serif'
      scale = (tick.fontSize || 12)

      var coordScale = 1.0 / (bounds[dimension+2] - bounds[dimension])
      var coordShift = bounds[dimension]

      var rows = text.split('\n')
      for(var r = 0; r < rows.length; r++) {
        data = getText(font, rows[r]).data
        for (j = 0; j < data.length; j += 2) {
          vertices.push(
              data[j] * scale,
              -data[j + 1] * scale - r * scale * 1.2,
              (x - coordShift) * coordScale)
        }
      }

      offsets.push(Math.floor(vertices.length/3))
      tickX.push(x)
    }

    this.tickOffset[dimension] = offsets
    this.tickX[dimension] = tickX
  }

  //Add labels
  for(dimension=0; dimension<2; ++dimension) {
    this.labelOffset[dimension] = Math.floor(vertices.length/3)

    data  = getText(options.labelFont[dimension], options.labels[dimension], { textAlign: 'center' }).data
    scale = options.labelSize[dimension]
    for(i=0; i<data.length; i+=2) {
      vertices.push(data[i]*scale, -data[i+1]*scale, 0)
    }

    this.labelCount[dimension] =
      Math.floor(vertices.length/3) - this.labelOffset[dimension]
  }

  //Add title
  this.titleOffset = Math.floor(vertices.length/3)
  data = getText(options.titleFont, options.title).data
  scale = options.titleSize
  for(i=0; i<data.length; i+=2) {
    vertices.push(data[i]*scale, -data[i+1]*scale, 0)
  }
  this.titleCount = Math.floor(vertices.length/3) - this.titleOffset

  //Upload new vertices
  this.vbo.update(vertices)
}

proto.dispose = function() {
  this.vbo.dispose()
  this.shader.dispose()
}

function createTextElements(plot) {
  var gl = plot.gl
  var vbo = createBuffer(gl)
  var shader = createShader(gl, shaders.textVert, shaders.textFrag)
  var text = new TextElements(plot, vbo, shader)
  return text
}

},{"./shaders":277,"binary-search-bounds":279,"gl-buffer":234,"gl-shader":294,"text-cache":517}],279:[function(_dereq_,module,exports){
arguments[4][99][0].apply(exports,arguments)
},{"dup":99}],280:[function(_dereq_,module,exports){
'use strict'

module.exports = createGLPlot2D

var createPick = _dereq_('gl-select-static')

var createGrid = _dereq_('./lib/grid')
var createText = _dereq_('./lib/text')
var createLine = _dereq_('./lib/line')
var createBox  = _dereq_('./lib/box')

function GLPlot2D(gl, pickBuffer) {
  this.gl               = gl
  this.pickBuffer       = pickBuffer

  this.screenBox        = [0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight]
  this.viewBox          = [0, 0, 0, 0]
  this.dataBox          = [-10, -10, 10, 10]

  this.gridLineEnable   = [true,true]
  this.gridLineWidth    = [1,1]
  this.gridLineColor    = [[0,0,0,1],
                           [0,0,0,1]]

  this.pixelRatio       = 1

  this.tickMarkLength   = [0,0,0,0]
  this.tickMarkWidth    = [0,0,0,0]
  this.tickMarkColor    = [[0,0,0,1],
                           [0,0,0,1],
                           [0,0,0,1],
                           [0,0,0,1]]

  this.tickPad          = [15,15,15,15]
  this.tickAngle        = [0,0,0,0]
  this.tickEnable       = [true,true,true,true]
  this.tickColor        = [[0,0,0,1],
                           [0,0,0,1],
                           [0,0,0,1],
                           [0,0,0,1]]

  this.labelPad         = [15,15,15,15]
  this.labelAngle       = [0,Math.PI/2,0,3.0*Math.PI/2]
  this.labelEnable      = [true,true,true,true]
  this.labelColor       = [[0,0,0,1],
                           [0,0,0,1],
                           [0,0,0,1],
                           [0,0,0,1]]

  this.titleCenter      = [0,0]
  this.titleEnable      = true
  this.titleAngle       = 0
  this.titleColor       = [0,0,0,1]

  this.borderColor      = [0,0,0,0]
  this.backgroundColor  = [0,0,0,0]

  this.zeroLineEnable   = [true, true]
  this.zeroLineWidth    = [4, 4]
  this.zeroLineColor    = [[0, 0, 0, 1],[0, 0, 0, 1]]

  this.borderLineEnable = [true,true,true,true]
  this.borderLineWidth  = [2,2,2,2]
  this.borderLineColor  = [[0,0,0,1],
                           [0,0,0,1],
                           [0,0,0,1],
                           [0,0,0,1]]

  //Drawing parameters
  this.grid             = null
  this.text             = null
  this.line             = null
  this.box              = null
  this.objects          = []
  this.overlays         = []

  this._tickBounds      = [Infinity, Infinity, -Infinity, -Infinity]

  this.static = false

  this.dirty        = false
  this.pickDirty    = false
  this.pickDelay    = 120
  this.pickRadius   = 10
  this._pickTimeout = null
  this._drawPick    = this.drawPick.bind(this)

  this._depthCounter = 0
}

var proto = GLPlot2D.prototype

proto.setDirty = function() {
  this.dirty = this.pickDirty = true
}

proto.setOverlayDirty = function() {
  this.dirty = true
}

proto.nextDepthValue = function() {
  return (this._depthCounter++) / 65536.0
}

function lerp(a, b, t) {
  var s = 0.5 * (t + 1.0)
  return Math.floor((1.0-s)*a + s*b)|0
}

proto.draw = (function() {
var TICK_MARK_BOX = [0,0,0,0]
return function() {
  var gl         = this.gl
  var screenBox  = this.screenBox
  var viewPixels = this.viewBox
  var dataBox    = this.dataBox
  var pixelRatio = this.pixelRatio
  var grid       = this.grid
  var line       = this.line
  var text       = this.text
  var objects    = this.objects

  this._depthCounter = 0

  if(this.pickDirty) {
    if(this._pickTimeout) {
      clearTimeout(this._pickTimeout)
    }
    this.pickDirty = false
    this._pickTimeout = setTimeout(this._drawPick, this.pickDelay)
  }

  if(!this.dirty) {
    return
  }
  this.dirty = false

  gl.bindFramebuffer(gl.FRAMEBUFFER, null)

  //Turn on scissor
  gl.enable(gl.SCISSOR_TEST)

  //Turn off depth buffer
  gl.disable(gl.DEPTH_TEST)
  gl.depthFunc(gl.LESS)
  gl.depthMask(false)

  //Configure premultiplied alpha blending
  gl.enable(gl.BLEND)
  gl.blendEquation(gl.FUNC_ADD, gl.FUNC_ADD);
  gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);

  //Draw border
  if (this.borderColor) {
    gl.scissor(
      screenBox[0],
      screenBox[1],
      screenBox[2]-screenBox[0],
      screenBox[3]-screenBox[1])
    var borderColor = this.borderColor
    gl.clearColor(
      borderColor[0]*borderColor[3],
      borderColor[1]*borderColor[3],
      borderColor[2]*borderColor[3],
      borderColor[3])
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
  }

  //Draw center pane
  gl.scissor(
    viewPixels[0],
    viewPixels[1],
    viewPixels[2]-viewPixels[0],
    viewPixels[3]-viewPixels[1])
  gl.viewport(
    viewPixels[0],
    viewPixels[1],
    viewPixels[2]-viewPixels[0],
    viewPixels[3]-viewPixels[1])
  var backgroundColor = this.backgroundColor
  gl.clearColor(
    backgroundColor[0]*backgroundColor[3],
    backgroundColor[1]*backgroundColor[3],
    backgroundColor[2]*backgroundColor[3],
    backgroundColor[3])
  gl.clear(gl.COLOR_BUFFER_BIT)

  //Draw grid
  grid.draw()

  //Draw zero lines separately
  var zeroLineEnable = this.zeroLineEnable
  var zeroLineColor  = this.zeroLineColor
  var zeroLineWidth  = this.zeroLineWidth
  if(zeroLineEnable[0] || zeroLineEnable[1]) {
    line.bind()
    for(var i=0; i<2; ++i) {
      if(!zeroLineEnable[i] ||
        !(dataBox[i] <= 0 && dataBox[i+2] >= 0)) {
        continue
      }

      var zeroIntercept = screenBox[i] -
        dataBox[i] * (screenBox[i+2] - screenBox[i]) / (dataBox[i+2] - dataBox[i])

      if(i === 0) {
        line.drawLine(
          zeroIntercept, screenBox[1], zeroIntercept, screenBox[3],
          zeroLineWidth[i],
          zeroLineColor[i])
      } else {
        line.drawLine(
          screenBox[0], zeroIntercept, screenBox[2], zeroIntercept,
          zeroLineWidth[i],
          zeroLineColor[i])
      }
    }
  }

  //Draw traces
  for(var i=0; i<objects.length; ++i) {
    objects[i].draw()
  }

  //Return viewport to default
  gl.viewport(
    screenBox[0],
    screenBox[1],
    screenBox[2]-screenBox[0],
    screenBox[3]-screenBox[1])
  gl.scissor(
    screenBox[0],
    screenBox[1],
    screenBox[2]-screenBox[0],
    screenBox[3]-screenBox[1])

  //Draw tick marks
  this.grid.drawTickMarks()

  //Draw line elements
  line.bind()

  //Draw border lines
  var borderLineEnable = this.borderLineEnable
  var borderLineWidth  = this.borderLineWidth
  var borderLineColor  = this.borderLineColor
  if(borderLineEnable[1]) {
    line.drawLine(
      viewPixels[0], viewPixels[1] - 0.5*borderLineWidth[1]*pixelRatio,
      viewPixels[0], viewPixels[3] + 0.5*borderLineWidth[3]*pixelRatio,
      borderLineWidth[1], borderLineColor[1])
  }
  if(borderLineEnable[0]) {
    line.drawLine(
      viewPixels[0] - 0.5*borderLineWidth[0]*pixelRatio, viewPixels[1],
      viewPixels[2] + 0.5*borderLineWidth[2]*pixelRatio, viewPixels[1],
      borderLineWidth[0], borderLineColor[0])
  }
  if(borderLineEnable[3]) {
    line.drawLine(
      viewPixels[2], viewPixels[1] - 0.5*borderLineWidth[1]*pixelRatio,
      viewPixels[2], viewPixels[3] + 0.5*borderLineWidth[3]*pixelRatio,
      borderLineWidth[3], borderLineColor[3])
  }
  if(borderLineEnable[2]) {
    line.drawLine(
      viewPixels[0] - 0.5*borderLineWidth[0]*pixelRatio, viewPixels[3],
      viewPixels[2] + 0.5*borderLineWidth[2]*pixelRatio, viewPixels[3],
      borderLineWidth[2], borderLineColor[2])
  }

  //Draw text elements
  text.bind()
  for(var i=0; i<2; ++i) {
    text.drawTicks(i)
  }
  if(this.titleEnable) {
    text.drawTitle()
  }

  //Draw other overlay elements (select boxes, etc.)
  var overlays = this.overlays
  for(var i=0; i<overlays.length; ++i) {
    overlays[i].draw()
  }

  //Turn off scissor test
  gl.disable(gl.SCISSOR_TEST)
  gl.disable(gl.BLEND)
  gl.depthMask(true)
}
})()

proto.drawPick = (function() {

return function() {
  if (this.static) return;

  var pickBuffer = this.pickBuffer
  var gl = this.gl

  this._pickTimeout = null
  pickBuffer.begin()

  var pickOffset = 1
  var objects = this.objects
  for(var i=0; i<objects.length; ++i) {
    pickOffset = objects[i].drawPick(pickOffset)
  }

  pickBuffer.end()
}
})()

proto.pick = (function() {
return function(x, y) {
  if (this.static) return;

  var pixelRatio     = this.pixelRatio
  var pickPixelRatio = this.pickPixelRatio
  var viewBox        = this.viewBox

  var scrX = Math.round((x - viewBox[0] / pixelRatio) * pickPixelRatio)|0
  var scrY = Math.round((y - viewBox[1] / pixelRatio) * pickPixelRatio)|0

  var pickResult = this.pickBuffer.query(scrX, scrY, this.pickRadius)
  if(!pickResult) {
    return null
  }

  var pickValue = pickResult.id +
    (pickResult.value[0]<<8)  +
    (pickResult.value[1]<<16) +
    (pickResult.value[2]<<24)

  var objects = this.objects
  for(var i=0; i<objects.length; ++i) {
    var result = objects[i].pick(scrX, scrY, pickValue)
    if(result) {
      return result
    }
  }

  return null
}
})()

function deepClone(array) {
  var result = array.slice()
  for(var i=0; i<result.length; ++i) {
    result[i] = result[i].slice()
  }
  return result
}

function compareTicks(a, b) {
  return a.x - b.x
}

proto.setScreenBox = function(nbox) {
  var screenBox = this.screenBox
  var pixelRatio = this.pixelRatio

  screenBox[0] = Math.round(nbox[0] * pixelRatio) | 0
  screenBox[1] = Math.round(nbox[1] * pixelRatio) | 0
  screenBox[2] = Math.round(nbox[2] * pixelRatio) | 0
  screenBox[3] = Math.round(nbox[3] * pixelRatio) | 0

  this.setDirty()
}

proto.setDataBox = function(nbox) {
  var dataBox = this.dataBox

  var different =
    dataBox[0] !== nbox[0] ||
    dataBox[1] !== nbox[1] ||
    dataBox[2] !== nbox[2] ||
    dataBox[3] !== nbox[3]

  if(different) {
    dataBox[0] = nbox[0]
    dataBox[1] = nbox[1]
    dataBox[2] = nbox[2]
    dataBox[3] = nbox[3]

    this.setDirty()
  }
}

proto.setViewBox = function(nbox) {
  var pixelRatio = this.pixelRatio
  var viewBox = this.viewBox

  viewBox[0] = Math.round(nbox[0] * pixelRatio)|0
  viewBox[1] = Math.round(nbox[1] * pixelRatio)|0
  viewBox[2] = Math.round(nbox[2] * pixelRatio)|0
  viewBox[3] = Math.round(nbox[3] * pixelRatio)|0

  var pickPixelRatio = this.pickPixelRatio
  this.pickBuffer.shape = [
    Math.round((nbox[2] - nbox[0]) * pickPixelRatio)|0,
    Math.round((nbox[3] - nbox[1]) * pickPixelRatio)|0 ]

  this.setDirty()
}

proto.update = function(options) {
  options = options || {}

  var gl = this.gl

  this.pixelRatio      = options.pixelRatio || 1

  var pixelRatio       = this.pixelRatio
  this.pickPixelRatio  = Math.max(pixelRatio, 1)

  this.setScreenBox(options.screenBox ||
    [0, 0, gl.drawingBufferWidth/pixelRatio, gl.drawingBufferHeight/pixelRatio])

  var screenBox = this.screenBox
  this.setViewBox(options.viewBox ||
    [0.125*(this.screenBox[2]-this.screenBox[0])/pixelRatio,
     0.125*(this.screenBox[3]-this.screenBox[1])/pixelRatio,
     0.875*(this.screenBox[2]-this.screenBox[0])/pixelRatio,
     0.875*(this.screenBox[3]-this.screenBox[1])/pixelRatio])

  var viewBox = this.viewBox
  var aspectRatio = (viewBox[2] - viewBox[0]) / (viewBox[3] - viewBox[1])
  this.setDataBox(options.dataBox || [-10, -10/aspectRatio, 10, 10/aspectRatio])

  this.borderColor     = options.borderColor !== false ? (options.borderColor || [0,0,0,0]).slice() : false
  this.backgroundColor = (options.backgroundColor || [0,0,0,0]).slice()

  this.gridLineEnable  = (options.gridLineEnable || [true,true]).slice()
  this.gridLineWidth   = (options.gridLineWidth || [1,1]).slice()
  this.gridLineColor   = deepClone(options.gridLineColor ||
    [[0.5,0.5,0.5,1],[0.5,0.5,0.5,1]])

  this.zeroLineEnable   = (options.zeroLineEnable || [true, true]).slice()
  this.zeroLineWidth    = (options.zeroLineWidth || [4, 4]).slice()
  this.zeroLineColor    = deepClone(options.zeroLineColor ||
    [[0, 0, 0, 1],[0, 0, 0, 1]])

  this.tickMarkLength   = (options.tickMarkLength || [0,0,0,0]).slice()
  this.tickMarkWidth    = (options.tickMarkWidth || [0,0,0,0]).slice()
  this.tickMarkColor    = deepClone(options.tickMarkColor ||
    [[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]])

  this.titleCenter      = (options.titleCenter || [
    0.5*(viewBox[0]+viewBox[2])/pixelRatio,(viewBox[3]+120)/pixelRatio]).slice()
  this.titleEnable      = !('titleEnable' in options) || !!options.titleEnable
  this.titleAngle       = options.titleAngle || 0
  this.titleColor       = (options.titleColor || [0,0,0,1]).slice()

  this.labelPad         = (options.labelPad || [15,15,15,15]).slice()
  this.labelAngle       = (options.labelAngle ||
    [0,Math.PI/2,0,3.0*Math.PI/2]).slice()
  this.labelEnable      = (options.labelEnable || [true,true,true,true]).slice()
  this.labelColor       = deepClone(options.labelColor ||
    [[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]])

  this.tickPad         = (options.tickPad || [15,15,15,15]).slice()
  this.tickAngle       = (options.tickAngle || [0,0,0,0]).slice()
  this.tickEnable      = (options.tickEnable || [true,true,true,true]).slice()
  this.tickColor       = deepClone(options.tickColor ||
    [[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]])

  this.borderLineEnable = (options.borderLineEnable ||
                            [true,true,true,true]).slice()
  this.borderLineWidth  = (options.borderLineWidth || [2,2,2,2]).slice()
  this.borderLineColor  = deepClone(options.borderLineColor ||
                          [[0,0,0,1],
                           [0,0,0,1],
                           [0,0,0,1],
                           [0,0,0,1]])

  var ticks = options.ticks || [ [], [] ]

  //Compute bounds on ticks
  var bounds = this._tickBounds
  bounds[0] = bounds[1] =  Infinity
  bounds[2] = bounds[3] = -Infinity
  for(var i=0; i<2; ++i) {
    var axisTicks = ticks[i].slice(0)
    if(axisTicks.length === 0) {
      continue
    }
    axisTicks.sort(compareTicks)
    bounds[i]   = Math.min(bounds[i], axisTicks[0].x)
    bounds[i+2] = Math.max(bounds[i+2], axisTicks[axisTicks.length-1].x)
  }

  //Update grid
  this.grid.update({
    bounds: bounds,
    ticks:  ticks
  })

  //Update text
  this.text.update({
    bounds:     bounds,
    ticks:      ticks,
    labels:     options.labels    || ['x', 'y'],
    labelSize:  options.labelSize || [12,12],
    labelFont:  options.labelFont || ['sans-serif', 'sans-serif'],
    title:      options.title     || '',
    titleSize:  options.titleSize || 18,
    titleFont:  options.titleFont || 'sans-serif'
  })

  this.static = !!options.static;

  this.setDirty()
}

proto.dispose = function() {
  this.box.dispose()
  this.grid.dispose()
  this.text.dispose()
  this.line.dispose()
  for(var i=this.objects.length-1; i>=0; --i) {
    this.objects[i].dispose()
  }
  this.objects.length = 0
  for(var i=this.overlays.length-1; i>=0; --i) {
    this.overlays[i].dispose()
  }
  this.overlays.length = 0

  this.gl = null
}

proto.addObject = function(object) {
  if(this.objects.indexOf(object) < 0) {
    this.objects.push(object)
    this.setDirty()
  }
}

proto.removeObject = function(object) {
  var objects = this.objects
  for(var i=0; i<objects.length; ++i) {
    if(objects[i] === object) {
      objects.splice(i,1)
      this.setDirty()
      break
    }
  }
}

proto.addOverlay = function(object) {
  if(this.overlays.indexOf(object) < 0) {
    this.overlays.push(object)
    this.setOverlayDirty()
  }
}

proto.removeOverlay = function(object) {
  var objects = this.overlays
  for(var i=0; i<objects.length; ++i) {
    if(objects[i] === object) {
      objects.splice(i,1)
      this.setOverlayDirty()
      break
    }
  }
}

function createGLPlot2D(options) {
  var gl = options.gl
  var pickBuffer = createPick(gl, [
    gl.drawingBufferWidth, gl.drawingBufferHeight])
  var plot = new GLPlot2D(gl, pickBuffer)
  plot.grid = createGrid(plot)
  plot.text = createText(plot)
  plot.line = createLine(plot)
  plot.box  = createBox(plot)
  plot.update(options)
  return plot
}

},{"./lib/box":274,"./lib/grid":275,"./lib/line":276,"./lib/text":278,"gl-select-static":293}],281:[function(_dereq_,module,exports){
'use strict'

module.exports = createCamera

var now         = _dereq_('right-now')
var createView  = _dereq_('3d-view')
var mouseChange = _dereq_('mouse-change')
var mouseWheel  = _dereq_('mouse-wheel')
var mouseOffset = _dereq_('mouse-event-offset')
var hasPassive  = _dereq_('has-passive-events')

function createCamera(element, options) {
  element = element || document.body
  options = options || {}

  var limits  = [ 0.01, Infinity ]
  if('distanceLimits' in options) {
    limits[0] = options.distanceLimits[0]
    limits[1] = options.distanceLimits[1]
  }
  if('zoomMin' in options) {
    limits[0] = options.zoomMin
  }
  if('zoomMax' in options) {
    limits[1] = options.zoomMax
  }

  var view = createView({
    center: options.center || [0,0,0],
    up:     options.up     || [0,1,0],
    eye:    options.eye    || [0,0,10],
    mode:   options.mode   || 'orbit',
    distanceLimits: limits
  })

  var pmatrix = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
  var distance = 0.0
  var width   = element.clientWidth
  var height  = element.clientHeight

  var camera = {
    keyBindingMode: 'rotate',
    enableWheel: true,
    view:               view,
    element:            element,
    delay:              options.delay          || 16,
    rotateSpeed:        options.rotateSpeed    || 1,
    zoomSpeed:          options.zoomSpeed      || 1,
    translateSpeed:     options.translateSpeed || 1,
    flipX:              !!options.flipX,
    flipY:              !!options.flipY,
    modes:              view.modes,
    _ortho: options._ortho || (options.projection && options.projection.type === 'orthographic') || false,
    tick: function() {
      var t = now()
      var delay = this.delay
      var ctime = t - 2 * delay
      view.idle(t-delay)
      view.recalcMatrix(ctime)
      view.flush(t-(100+delay*2))
      var allEqual = true
      var matrix = view.computedMatrix
      for(var i=0; i<16; ++i) {
        allEqual = allEqual && (pmatrix[i] === matrix[i])
        pmatrix[i] = matrix[i]
      }
      var sizeChanged =
          element.clientWidth === width &&
          element.clientHeight === height
      width  = element.clientWidth
      height = element.clientHeight
      if(allEqual) {
        return !sizeChanged
      }
      distance = Math.exp(view.computedRadius[0])
      return true
    },
    lookAt: function(eye, center, up) {
      view.lookAt(view.lastT(), eye, center, up)
    },
    rotate: function(pitch, yaw, roll) {
      view.rotate(view.lastT(), pitch, yaw, roll)
    },
    pan: function(dx, dy, dz) {
      view.pan(view.lastT(), dx, dy, dz)
    },
    translate: function(dx, dy, dz) {
      view.translate(view.lastT(), dx, dy, dz)
    }
  }

  Object.defineProperties(camera, {
    matrix: {
      get: function() {
        return view.computedMatrix
      },
      set: function(mat) {
        view.setMatrix(view.lastT(), mat)
        return view.computedMatrix
      },
      enumerable: true
    },
    mode: {
      get: function() {
        return view.getMode()
      },
      set: function(mode) {
        var curUp = view.computedUp.slice()
        var curEye = view.computedEye.slice()
        var curCenter = view.computedCenter.slice()
        view.setMode(mode)
        if(mode === 'turntable') {
          // Hacky time warping stuff to generate smooth animation
          var t0 = now()
          view._active.lookAt(t0, curEye, curCenter, curUp)
          view._active.lookAt(t0 + 500, curEye, curCenter, [0, 0, 1])
          view._active.flush(t0)
        }
        return view.getMode()
      },
      enumerable: true
    },
    center: {
      get: function() {
        return view.computedCenter
      },
      set: function(ncenter) {
        view.lookAt(view.lastT(), null, ncenter)
        return view.computedCenter
      },
      enumerable: true
    },
    eye: {
      get: function() {
        return view.computedEye
      },
      set: function(neye) {
        view.lookAt(view.lastT(), neye)
        return view.computedEye
      },
      enumerable: true
    },
    up: {
      get: function() {
        return view.computedUp
      },
      set: function(nup) {
        view.lookAt(view.lastT(), null, null, nup)
        return view.computedUp
      },
      enumerable: true
    },
    distance: {
      get: function() {
        return distance
      },
      set: function(d) {
        view.setDistance(view.lastT(), d)
        return d
      },
      enumerable: true
    },
    distanceLimits: {
      get: function() {
        return view.getDistanceLimits(limits)
      },
      set: function(v) {
        view.setDistanceLimits(v)
        return v
      },
      enumerable: true
    }
  })

  element.addEventListener('contextmenu', function(ev) {
    ev.preventDefault()
    return false
  })

  var lastX = 0, lastY = 0, lastMods = {shift: false, control: false, alt: false, meta: false}
  camera.mouseListener = mouseChange(element, handleInteraction)

  //enable simple touch interactions
  element.addEventListener('touchstart', function (ev) {
    var xy = mouseOffset(ev.changedTouches[0], element)
    handleInteraction(0, xy[0], xy[1], lastMods)
    handleInteraction(1, xy[0], xy[1], lastMods)

    ev.preventDefault()
  }, hasPassive ? {passive: false} : false)

  element.addEventListener('touchmove', function (ev) {
    var xy = mouseOffset(ev.changedTouches[0], element)
    handleInteraction(1, xy[0], xy[1], lastMods)

    ev.preventDefault()
  }, hasPassive ? {passive: false} : false)

  element.addEventListener('touchend', function (ev) {

    handleInteraction(0, lastX, lastY, lastMods)

    ev.preventDefault()
  }, hasPassive ? {passive: false} : false)

  function handleInteraction (buttons, x, y, mods) {
    var keyBindingMode = camera.keyBindingMode

    if(keyBindingMode === false) return

    var rotate = keyBindingMode === 'rotate'
    var pan = keyBindingMode === 'pan'
    var zoom = keyBindingMode === 'zoom'

    var ctrl = !!mods.control
    var alt = !!mods.alt
    var shift = !!mods.shift
    var left = !!(buttons & 1)
    var right = !!(buttons & 2)
    var middle = !!(buttons & 4)

    var scale = 1.0 / element.clientHeight
    var dx    = scale * (x - lastX)
    var dy    = scale * (y - lastY)

    var flipX = camera.flipX ? 1 : -1
    var flipY = camera.flipY ? 1 : -1

    var drot  = Math.PI * camera.rotateSpeed

    var t = now()

    if((rotate && left && !ctrl && !alt && !shift) || (left && !ctrl && !alt && shift)) {
      // Rotate
      view.rotate(t, flipX * drot * dx, -flipY * drot * dy, 0)
    }

    if((pan && left && !ctrl && !alt && !shift) || right || (left && ctrl && !alt && !shift)) {
      // Pan
      view.pan(t, -camera.translateSpeed * dx * distance, camera.translateSpeed * dy * distance, 0)
    }

    if((zoom && left && !ctrl && !alt && !shift) || middle || (left && !ctrl && alt && !shift)) {
      // Zoom
      var kzoom = -camera.zoomSpeed * dy / window.innerHeight * (t - view.lastT()) * 100
      view.pan(t, 0, 0, distance * (Math.exp(kzoom) - 1))
    }

    lastX = x
    lastY = y
    lastMods = mods

    return true
  }

  camera.wheelListener = mouseWheel(element, function(dx, dy) {
    // TODO remove now that we can disable scroll via scrollZoom?
    if(camera.keyBindingMode === false) return
    if(!camera.enableWheel) return

    var flipX = camera.flipX ? 1 : -1
    var flipY = camera.flipY ? 1 : -1
    var t = now()
    if(Math.abs(dx) > Math.abs(dy)) {
      view.rotate(t, 0, 0, -dx * flipX * Math.PI * camera.rotateSpeed / window.innerWidth)
    } else {
      var kzoom = -camera.zoomSpeed * flipY * dy / window.innerHeight * (t - view.lastT()) / 20.0
      view.pan(t, 0, 0, distance * (Math.exp(kzoom) - 1))
    }
  }, true)

  return camera
}

},{"3d-view":45,"has-passive-events":400,"mouse-change":424,"mouse-event-offset":425,"mouse-wheel":427,"right-now":485}],282:[function(_dereq_,module,exports){
var glslify      = _dereq_('glslify')
var createShader = _dereq_('gl-shader')

var vertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\nattribute vec2 position;\nvarying vec2 uv;\nvoid main() {\n  uv = position;\n  gl_Position = vec4(position, 0, 1);\n}"])
var fragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nuniform sampler2D accumBuffer;\nvarying vec2 uv;\n\nvoid main() {\n  vec4 accum = texture2D(accumBuffer, 0.5 * (uv + 1.0));\n  gl_FragColor = min(vec4(1,1,1,1), accum);\n}"])

module.exports = function(gl) {
  return createShader(gl, vertSrc, fragSrc, null, [ { name: 'position', type: 'vec2'}])
}

},{"gl-shader":294,"glslify":398}],283:[function(_dereq_,module,exports){
'use strict'

var createCamera = _dereq_('./camera.js')
var createAxes   = _dereq_('gl-axes3d')
var axesRanges   = _dereq_('gl-axes3d/properties')
var createSpikes = _dereq_('gl-spikes3d')
var createSelect = _dereq_('gl-select-static')
var createFBO    = _dereq_('gl-fbo')
var drawTriangle = _dereq_('a-big-triangle')
var mouseChange  = _dereq_('mouse-change')
var perspective  = _dereq_('gl-mat4/perspective')
var ortho        = _dereq_('gl-mat4/ortho')
var createShader = _dereq_('./lib/shader')
var isMobile = _dereq_('is-mobile')({ tablet: true })

module.exports = {
  createScene: createScene,
  createCamera: createCamera
}

function MouseSelect() {
  this.mouse          = [-1,-1]
  this.screen         = null
  this.distance       = Infinity
  this.index          = null
  this.dataCoordinate = null
  this.dataPosition   = null
  this.object         = null
  this.data           = null
}

function getContext(canvas, options) {
  var gl = null
  try {
    gl = canvas.getContext('webgl', options)
    if(!gl) {
      gl = canvas.getContext('experimental-webgl', options)
    }
  } catch(e) {
    return null
  }
  return gl
}

function roundUpPow10(x) {
  var y = Math.round(Math.log(Math.abs(x)) / Math.log(10))
  if(y < 0) {
    var base = Math.round(Math.pow(10, -y))
    return Math.ceil(x*base) / base
  } else if(y > 0) {
    var base = Math.round(Math.pow(10, y))
    return Math.ceil(x/base) * base
  }
  return Math.ceil(x)
}

function defaultBool(x) {
  if(typeof x === 'boolean') {
    return x
  }
  return true
}

function createScene(options) {
  options = options || {}

  var stopped = false

  var canvas = options.canvas
  if(!canvas) {
    canvas = document.createElement('canvas')
    if(options.container) {
      var container = options.container
      container.appendChild(canvas)
    } else {
      document.body.appendChild(canvas)
    }
  }

  var gl = options.gl
  if(!gl) {
    gl = getContext(canvas,
      options.glOptions || {
        premultipliedAlpha: true,
        antialias: true,
        preserveDrawingBuffer: isMobile
      })
  }
  if(!gl) {
    throw new Error('webgl not supported')
  }

  //Initial bounds
  var bounds = options.bounds || [[-10,-10,-10], [10,10,10]]

  //Create selection
  var selection = new MouseSelect()

  //Accumulation buffer
  var accumBuffer = createFBO(gl,
    [gl.drawingBufferWidth, gl.drawingBufferHeight], {
      preferFloat: !isMobile
    })

  var accumShader = createShader(gl)

  //Create a camera
  var cameraOptions = {
    eye:     options.camera.eye     || [2,0,0],
    center:  options.camera.center  || [0,0,0],
    up:      options.camera.up      || [0,1,0],
    zoomMin: options.camera.zoomMax || 0.1,
    zoomMax: options.camera.zoomMin || 100,
    mode:    options.camera.mode    || 'turntable',
    _ortho:   (options.camera.projection && options.camera.projection.type === 'orthographic') || false
  }

  //Create axes
  var axesOptions = options.axes || {}
  var axes = createAxes(gl, axesOptions)
  axes.enable = !axesOptions.disable

  //Create spikes
  var spikeOptions = options.spikes || {}
  var spikes = createSpikes(gl, spikeOptions)

  //Object list is empty initially
  var objects         = []
  var pickBufferIds   = []
  var pickBufferCount = []
  var pickBuffers     = []

  //Dirty flag, skip redraw if scene static
  var dirty       = true
  var pickDirty   = true

  var projection     = new Array(16)
  var model          = new Array(16)

  var cameraParams = {
    view:         null,
    projection:   projection,
    model:        model,
    _ortho:        false
  }

  var pickDirty = true

  var viewShape = [ gl.drawingBufferWidth, gl.drawingBufferHeight ]

  var camera = createCamera(canvas, cameraOptions)

  //Create scene object
  var scene = {
    gl:           gl,
    contextLost:  false,
    pixelRatio:   options.pixelRatio || 1,
    canvas:       canvas,
    selection:    selection,
    camera:       camera,
    axes:         axes,
    axesPixels:   null,
    spikes:       spikes,
    bounds:       bounds,
    objects:      objects,
    shape:        viewShape,
    aspect:       options.aspectRatio || [1,1,1],
    pickRadius:   options.pickRadius || 10,
    zNear:        options.zNear || 0.01,
    zFar:         options.zFar  || 1000,
    fovy:         options.fovy  || Math.PI/4,
    clearColor:   options.clearColor || [0,0,0,0],
    autoResize:   defaultBool(options.autoResize),
    autoBounds:   defaultBool(options.autoBounds),
    autoScale:    !!options.autoScale,
    autoCenter:   defaultBool(options.autoCenter),
    clipToBounds: defaultBool(options.clipToBounds),
    snapToData:   !!options.snapToData,
    onselect:     options.onselect || null,
    onrender:     options.onrender || null,
    onclick:      options.onclick  || null,
    cameraParams: cameraParams,
    oncontextloss: null,
    mouseListener: null
  }

  var pickShape = [ (gl.drawingBufferWidth/scene.pixelRatio)|0, (gl.drawingBufferHeight/scene.pixelRatio)|0 ]

  function resizeListener() {
    if(stopped) {
      return
    }
    if(!scene.autoResize) {
      return
    }
    var parent = canvas.parentNode
    var width  = 1
    var height = 1
    if(parent && parent !== document.body) {
      width  = parent.clientWidth
      height = parent.clientHeight
    } else {
      width  = window.innerWidth
      height = window.innerHeight
    }
    var nextWidth  = Math.ceil(width  * scene.pixelRatio)|0
    var nextHeight = Math.ceil(height * scene.pixelRatio)|0
    if(nextWidth !== canvas.width || nextHeight !== canvas.height) {
      canvas.width   = nextWidth
      canvas.height  = nextHeight
      var style = canvas.style
      style.position = style.position || 'absolute'
      style.left     = '0px'
      style.top      = '0px'
      style.width    = width  + 'px'
      style.height   = height + 'px'
      dirty = true
    }
  }
  if(scene.autoResize) {
    resizeListener()
  }
  window.addEventListener('resize', resizeListener)

  function reallocPickIds() {
    var numObjs = objects.length
    var numPick = pickBuffers.length
    for(var i=0; i<numPick; ++i) {
      pickBufferCount[i] = 0
    }
    obj_loop:
    for(var i=0; i<numObjs; ++i) {
      var obj = objects[i]
      var pickCount = obj.pickSlots
      if(!pickCount) {
        pickBufferIds[i] = -1
        continue
      }
      for(var j=0; j<numPick; ++j) {
        if(pickBufferCount[j] + pickCount < 255) {
          pickBufferIds[i] = j
          obj.setPickBase(pickBufferCount[j]+1)
          pickBufferCount[j] += pickCount
          continue obj_loop
        }
      }
      //Create new pick buffer
      var nbuffer = createSelect(gl, viewShape)
      pickBufferIds[i] = numPick
      pickBuffers.push(nbuffer)
      pickBufferCount.push(pickCount)
      obj.setPickBase(1)
      numPick += 1
    }
    while(numPick > 0 && pickBufferCount[numPick-1] === 0) {
      pickBufferCount.pop()
      pickBuffers.pop().dispose()
    }
  }

  scene.update = function(options) {

    if(stopped) {
      return
    }
    options = options || {}
    dirty = true
    pickDirty = true
  }

  scene.add = function(obj) {
    if(stopped) {
      return
    }
    obj.axes = axes
    objects.push(obj)
    pickBufferIds.push(-1)
    dirty = true
    pickDirty = true
    reallocPickIds()
  }

  scene.remove = function(obj) {
    if(stopped) {
      return
    }
    var idx = objects.indexOf(obj)
    if(idx < 0) {
      return
    }
    objects.splice(idx, 1)
    pickBufferIds.pop()
    dirty = true
    pickDirty = true
    reallocPickIds()
  }

  scene.dispose = function() {
    if(stopped) {
      return
    }

    stopped = true

    window.removeEventListener('resize', resizeListener)
    canvas.removeEventListener('webglcontextlost', checkContextLoss)
    scene.mouseListener.enabled = false

    if(scene.contextLost) {
      return
    }

    //Destroy objects
    axes.dispose()
    spikes.dispose()
    for(var i=0; i<objects.length; ++i) {
      objects[i].dispose()
    }

    //Clean up buffers
    accumBuffer.dispose()
    for(var i=0; i<pickBuffers.length; ++i) {
      pickBuffers[i].dispose()
    }

    //Clean up shaders
    accumShader.dispose()

    //Release all references
    gl = null
    axes = null
    spikes = null
    objects = []
  }

  //Update mouse position
  var mouseRotating = false

  var prevButtons = 0

  scene.mouseListener = mouseChange(canvas, function(buttons, x, y) {
    if(stopped) {
      return
    }

    var numPick = pickBuffers.length
    var numObjs = objects.length
    var prevObj = selection.object

    selection.distance = Infinity
    selection.mouse[0] = x
    selection.mouse[1] = y
    selection.object = null
    selection.screen = null
    selection.dataCoordinate = selection.dataPosition = null

    var change = false

    if(buttons && prevButtons) {
      mouseRotating = true
    } else {
      if(mouseRotating) {
        pickDirty = true
      }
      mouseRotating = false

      for(var i=0; i<numPick; ++i) {
        var result = pickBuffers[i].query(x, pickShape[1] - y - 1, scene.pickRadius)
        if(result) {
          if(result.distance > selection.distance) {
            continue
          }
          for(var j=0; j<numObjs; ++j) {
            var obj = objects[j]
            if(pickBufferIds[j] !== i) {
              continue
            }
            var objPick = obj.pick(result)
            if(objPick) {
              selection.buttons        = buttons
              selection.screen         = result.coord
              selection.distance       = result.distance
              selection.object         = obj
              selection.index          = objPick.distance
              selection.dataPosition   = objPick.position
              selection.dataCoordinate = objPick.dataCoordinate
              selection.data           = objPick
              change = true
            }
          }
        }
      }
    }

    if(prevObj && prevObj !== selection.object) {
      if(prevObj.highlight) {
        prevObj.highlight(null)
      }
      dirty = true
    }
    if(selection.object) {
      if(selection.object.highlight) {
        selection.object.highlight(selection.data)
      }
      dirty = true
    }

    change = change || (selection.object !== prevObj)
    if(change && scene.onselect) {
      scene.onselect(selection)
    }

    if((buttons & 1) && !(prevButtons & 1) && scene.onclick) {
      scene.onclick(selection)
    }
    prevButtons = buttons
  })

  function checkContextLoss() {
    if(scene.contextLost) {
      return true
    }
    if(gl.isContextLost()) {
      scene.contextLost = true
      scene.mouseListener.enabled = false
      scene.selection.object = null
      if(scene.oncontextloss) {
        scene.oncontextloss()
      }
    }
  }

  canvas.addEventListener('webglcontextlost', checkContextLoss)

  //Render the scene for mouse picking
  function renderPick() {
    if(checkContextLoss()) {
      return
    }

    gl.colorMask(true, true, true, true)
    gl.depthMask(true)
    gl.disable(gl.BLEND)
    gl.enable(gl.DEPTH_TEST)

    var numObjs = objects.length
    var numPick = pickBuffers.length
    for(var j=0; j<numPick; ++j) {
      var buf = pickBuffers[j]
      buf.shape = pickShape
      buf.begin()
      for(var i=0; i<numObjs; ++i) {
        if(pickBufferIds[i] !== j) {
          continue
        }
        var obj = objects[i]
        if(obj.drawPick) {
          obj.pixelRatio = 1
          obj.drawPick(cameraParams)
        }
      }
      buf.end()
    }
  }

  var nBounds = [
    [ Infinity, Infinity, Infinity],
    [-Infinity,-Infinity,-Infinity]]

  var prevBounds = [nBounds[0].slice(), nBounds[1].slice()]

  function redraw() {
    if(checkContextLoss()) {
      return
    }

    resizeListener()

    //Tick camera
    var cameraMoved = scene.camera.tick()
    cameraParams.view = scene.camera.matrix
    dirty     = dirty || cameraMoved
    pickDirty = pickDirty || cameraMoved

      //Set pixel ratio
    axes.pixelRatio   = scene.pixelRatio
    spikes.pixelRatio = scene.pixelRatio

    //Check if any objects changed, recalculate bounds
    var numObjs = objects.length
    var lo = nBounds[0]
    var hi = nBounds[1]
    lo[0] = lo[1] = lo[2] =  Infinity
    hi[0] = hi[1] = hi[2] = -Infinity
    for(var i=0; i<numObjs; ++i) {
      var obj = objects[i]

      //Set the axes properties for each object
      obj.pixelRatio = scene.pixelRatio
      obj.axes = scene.axes

      dirty = dirty || !!obj.dirty
      pickDirty = pickDirty || !!obj.dirty
      var obb = obj.bounds
      if(obb) {
        var olo = obb[0]
        var ohi = obb[1]
        for(var j=0; j<3; ++j) {
          lo[j] = Math.min(lo[j], olo[j])
          hi[j] = Math.max(hi[j], ohi[j])
        }
      }
    }

    //Recalculate bounds
    var bounds = scene.bounds
    if(scene.autoBounds) {
      for(var j=0; j<3; ++j) {
        if(hi[j] < lo[j]) {
          lo[j] = -1
          hi[j] = 1
        } else {
          if(lo[j] === hi[j]) {
            lo[j] -= 1
            hi[j] += 1
          }
          var padding = 0.05 * (hi[j] - lo[j])
          lo[j] = lo[j] - padding
          hi[j] = hi[j] + padding
        }
        bounds[0][j] = lo[j]
        bounds[1][j] = hi[j]
      }
    }

    var boundsChanged = false
    for(var j=0; j<3; ++j) {
        boundsChanged = boundsChanged ||
            (prevBounds[0][j] !== bounds[0][j])  ||
            (prevBounds[1][j] !== bounds[1][j])
        prevBounds[0][j] = bounds[0][j]
        prevBounds[1][j] = bounds[1][j]
    }

    //Recalculate bounds
    pickDirty = pickDirty || boundsChanged
    dirty = dirty || boundsChanged

    if(!dirty) {
      return
    }

    if(boundsChanged) {
      var tickSpacing = [0,0,0]
      for(var i=0; i<3; ++i) {
        tickSpacing[i] = roundUpPow10((bounds[1][i]-bounds[0][i]) / 10.0)
      }
      if(axes.autoTicks) {
        axes.update({
          bounds: bounds,
          tickSpacing: tickSpacing
        })
      } else {
        axes.update({
          bounds: bounds
        })
      }
    }

    //Get scene
    var width  = gl.drawingBufferWidth
    var height = gl.drawingBufferHeight
    viewShape[0] = width
    viewShape[1] = height
    pickShape[0] = Math.max(width/scene.pixelRatio, 1)|0
    pickShape[1] = Math.max(height/scene.pixelRatio, 1)|0

    //Compute camera parameters

    if(cameraOptions._ortho === true) {
      ortho(projection,
        -width/height,
        width/height,
        -1,
        1,
        scene.zNear,
        scene.zFar
      )
      cameraParams._ortho = true
    } else {
      perspective(projection,
        scene.fovy,
        width/height,
        scene.zNear,
        scene.zFar
      )
      cameraParams._ortho = false
    }

    //Compute model matrix
    for(var i=0; i<16; ++i) {
      model[i] = 0
    }
    model[15] = 1

    var maxS = 0
    for(var i=0; i<3; ++i) {
      maxS = Math.max(maxS, bounds[1][i] - bounds[0][i])
    }

    for(var i=0; i<3; ++i) {
      if(scene.autoScale) {
        model[5*i] = scene.aspect[i] / (bounds[1][i] - bounds[0][i])
      } else {
        model[5*i] = 1  / maxS
      }
      if(scene.autoCenter) {
        model[12+i] = -model[5*i] * 0.5 * (bounds[0][i] + bounds[1][i])
      }
    }

    //Apply axes/clip bounds
    for(var i=0; i<numObjs; ++i) {
      var obj = objects[i]

      //Set axes bounds
      obj.axesBounds = bounds

      //Set clip bounds
      if(scene.clipToBounds) {
        obj.clipBounds = bounds
      }
    }
    //Set spike parameters
    if(selection.object) {
      if(scene.snapToData) {
        spikes.position = selection.dataCoordinate
      } else {
        spikes.position = selection.dataPosition
      }
      spikes.bounds = bounds
    }

    //If state changed, then redraw pick buffers
    if(pickDirty) {
      pickDirty = false
      renderPick()
    }

    //Recalculate pixel data
    scene.axesPixels = axesRanges(scene.axes, cameraParams, width, height)

    //Call render callback
    if(scene.onrender) {
      scene.onrender()
    }

    //Read value
    gl.bindFramebuffer(gl.FRAMEBUFFER, null)
    gl.viewport(0, 0, width, height)

    //General strategy: 3 steps
    //  1. render non-transparent objects
    //  2. accumulate transparent objects into separate fbo
    //  3. composite final scene

    //Clear FBO
    var clearColor = scene.clearColor
    gl.clearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3])
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
    gl.depthMask(true)
    gl.colorMask(true, true, true, true)
    gl.enable(gl.DEPTH_TEST)
    gl.depthFunc(gl.LEQUAL)
    gl.disable(gl.BLEND)
    gl.disable(gl.CULL_FACE)  //most visualization surfaces are 2 sided

    //Render opaque pass
    var hasTransparent = false
    if(axes.enable) {
      hasTransparent = hasTransparent || axes.isTransparent()
      axes.draw(cameraParams)
    }
    spikes.axes = axes
    if(selection.object) {
      spikes.draw(cameraParams)
    }

    gl.disable(gl.CULL_FACE)  //most visualization surfaces are 2 sided

    for(var i=0; i<numObjs; ++i) {
      var obj = objects[i]
      obj.axes = axes
      obj.pixelRatio = scene.pixelRatio
      if(obj.isOpaque && obj.isOpaque()) {
        obj.draw(cameraParams)
      }
      if(obj.isTransparent && obj.isTransparent()) {
        hasTransparent = true
      }
    }

    if(hasTransparent) {
      //Render transparent pass
      accumBuffer.shape = viewShape
      accumBuffer.bind()
      gl.clear(gl.DEPTH_BUFFER_BIT)
      gl.colorMask(false, false, false, false)
      gl.depthMask(true)
      gl.depthFunc(gl.LESS)

      //Render forward facing objects
      if(axes.enable && axes.isTransparent()) {
        axes.drawTransparent(cameraParams)
      }
      for(var i=0; i<numObjs; ++i) {
        var obj = objects[i]
        if(obj.isOpaque && obj.isOpaque()) {
          obj.draw(cameraParams)
        }
      }

      //Render transparent pass
      gl.enable(gl.BLEND)
      gl.blendEquation(gl.FUNC_ADD)
      gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
      gl.colorMask(true, true, true, true)
      gl.depthMask(false)
      gl.clearColor(0,0,0,0)
      gl.clear(gl.COLOR_BUFFER_BIT)

      if(axes.isTransparent()) {
        axes.drawTransparent(cameraParams)
      }

      for(var i=0; i<numObjs; ++i) {
        var obj = objects[i]
        if(obj.isTransparent && obj.isTransparent()) {
          obj.drawTransparent(cameraParams)
        }
      }

      //Unbind framebuffer
      gl.bindFramebuffer(gl.FRAMEBUFFER, null)

      //Draw composite pass
      gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
      gl.disable(gl.DEPTH_TEST)
      accumShader.bind()
      accumBuffer.color[0].bind(0)
      accumShader.uniforms.accumBuffer = 0
      drawTriangle(gl)

      //Turn off blending
      gl.disable(gl.BLEND)
    }

    //Clear dirty flags
    dirty = false
    for(var i=0; i<numObjs; ++i) {
      objects[i].dirty = false
    }
  }


  //Draw the whole scene
  function render() {
    if(stopped || scene.contextLost) {
      return
    }
    // this order is important: ios safari sometimes has sync raf
    redraw()
    requestAnimationFrame(render)
  }
  render()

  //Force redraw of whole scene
  scene.redraw = function() {
    if(stopped) {
      return
    }
    dirty = true
    redraw()
  }

  return scene
}

},{"./camera.js":281,"./lib/shader":282,"a-big-triangle":47,"gl-axes3d":226,"gl-axes3d/properties":233,"gl-fbo":242,"gl-mat4/ortho":261,"gl-mat4/perspective":262,"gl-select-static":293,"gl-spikes3d":303,"is-mobile":409,"mouse-change":424}],284:[function(_dereq_,module,exports){
var glslify = _dereq_('glslify')

exports.pointVertex       = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform float pointCloud;\n\nhighp float rand(vec2 co) {\n  highp float a = 12.9898;\n  highp float b = 78.233;\n  highp float c = 43758.5453;\n  highp float d = dot(co.xy, vec2(a, b));\n  highp float e = mod(d, 3.14);\n  return fract(sin(e) * c);\n}\n\nvoid main() {\n  vec3 hgPosition = matrix * vec3(position, 1);\n  gl_Position  = vec4(hgPosition.xy, 0, hgPosition.z);\n    // if we don't jitter the point size a bit, overall point cloud\n    // saturation 'jumps' on zooming, which is disturbing and confusing\n  gl_PointSize = pointSize * ((19.5 + rand(position)) / 20.0);\n  if(pointCloud != 0.0) { // pointCloud is truthy\n    // get the same square surface as circle would be\n    gl_PointSize *= 0.886;\n  }\n}"])
exports.pointFragment     = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color, borderColor;\nuniform float centerFraction;\nuniform float pointCloud;\n\nvoid main() {\n  float radius;\n  vec4 baseColor;\n  if(pointCloud != 0.0) { // pointCloud is truthy\n    if(centerFraction == 1.0) {\n      gl_FragColor = color;\n    } else {\n      gl_FragColor = mix(borderColor, color, centerFraction);\n    }\n  } else {\n    radius = length(2.0 * gl_PointCoord.xy - 1.0);\n    if(radius > 1.0) {\n      discard;\n    }\n    baseColor = mix(borderColor, color, step(radius, centerFraction));\n    gl_FragColor = vec4(baseColor.rgb * baseColor.a, baseColor.a);\n  }\n}\n"])
exports.pickVertex        = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 pickId;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform vec4 pickOffset;\n\nvarying vec4 fragId;\n\nvoid main() {\n  vec3 hgPosition = matrix * vec3(position, 1);\n  gl_Position  = vec4(hgPosition.xy, 0, hgPosition.z);\n  gl_PointSize = pointSize;\n\n  vec4 id = pickId + pickOffset;\n  id.y += floor(id.x / 256.0);\n  id.x -= floor(id.x / 256.0) * 256.0;\n\n  id.z += floor(id.y / 256.0);\n  id.y -= floor(id.y / 256.0) * 256.0;\n\n  id.w += floor(id.z / 256.0);\n  id.z -= floor(id.z / 256.0) * 256.0;\n\n  fragId = id;\n}\n"])
exports.pickFragment      = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragId;\n\nvoid main() {\n  float radius = length(2.0 * gl_PointCoord.xy - 1.0);\n  if(radius > 1.0) {\n    discard;\n  }\n  gl_FragColor = fragId / 255.0;\n}\n"])

},{"glslify":398}],285:[function(_dereq_,module,exports){
'use strict'

var createShader = _dereq_('gl-shader')
var createBuffer = _dereq_('gl-buffer')

var pool = _dereq_('typedarray-pool')

var SHADERS = _dereq_('./lib/shader')

module.exports = createPointcloud2D

function Pointcloud2D(plot, offsetBuffer, pickBuffer, shader, pickShader) {
  this.plot           = plot
  this.offsetBuffer   = offsetBuffer
  this.pickBuffer     = pickBuffer
  this.shader         = shader
  this.pickShader     = pickShader
  this.sizeMin        = 0.5
  this.sizeMinCap     = 2
  this.sizeMax        = 20
  this.areaRatio      = 1.0
  this.pointCount     = 0
  this.color          = [1, 0, 0, 1]
  this.borderColor    = [0, 0, 0, 1]
  this.blend          = false
  this.pickOffset     = 0
  this.points         = null
}

var proto = Pointcloud2D.prototype

proto.dispose = function() {
  this.shader.dispose()
  this.pickShader.dispose()
  this.offsetBuffer.dispose()
  this.pickBuffer.dispose()
  this.plot.removeObject(this)
}

proto.update = function(options) {

  var i

  options = options || {}

  function dflt(opt, value) {
    if(opt in options) {
      return options[opt]
    }
    return value
  }

  this.sizeMin      = dflt('sizeMin', 0.5)
  // this.sizeMinCap      = dflt('sizeMinCap', 2)
  this.sizeMax      = dflt('sizeMax', 20)
  this.color        = dflt('color', [1, 0, 0, 1]).slice()
  this.areaRatio    = dflt('areaRatio', 1)
  this.borderColor  = dflt('borderColor', [0, 0, 0, 1]).slice()
  this.blend        = dflt('blend', false)

  //Update point data

  // Attempt straight-through processing (STP) to avoid allocation and copy
  // TODO eventually abstract out STP logic, maybe into `pool` or a layer above
  var pointCount = options.positions.length >>> 1
  var dataStraightThrough = options.positions instanceof Float32Array
  var idStraightThrough = options.idToIndex instanceof Int32Array && options.idToIndex.length >= pointCount // permit larger to help reuse

  var data          = options.positions
  var packed        = dataStraightThrough ? data : pool.mallocFloat32(data.length)
  var packedId      = idStraightThrough ? options.idToIndex : pool.mallocInt32(pointCount)

  if(!dataStraightThrough) {
    packed.set(data)
  }

  if(!idStraightThrough) {
    packed.set(data)
    for(i = 0; i < pointCount; i++) {
      packedId[i] = i
    }
  }

  this.points       = data

  this.offsetBuffer.update(packed)
  this.pickBuffer.update(packedId)

  if(!dataStraightThrough) {
    pool.free(packed)
  }

  if(!idStraightThrough) {
    pool.free(packedId)
  }

  this.pointCount = pointCount
  this.pickOffset = 0
}

function count(points, dataBox) {
  var visiblePointCountEstimate = 0
  var length = points.length >>> 1
  var i
  for(i = 0; i < length; i++) {
    var x = points[i * 2]
    var y = points[i * 2 + 1]
    if(x >= dataBox[0] && x <= dataBox[2] && y >= dataBox[1] && y <= dataBox[3])
      visiblePointCountEstimate++
  }
  return visiblePointCountEstimate
}

proto.unifiedDraw = (function() {
  var MATRIX = [1, 0, 0,
                0, 1, 0,
                0, 0, 1]
  var PICK_VEC4 = [0, 0, 0, 0]
return function(pickOffset) {
  var pick = pickOffset !== void(0)

  var shader        = pick ? this.pickShader : this.shader
  var gl            = this.plot.gl
  var dataBox       = this.plot.dataBox

  if(this.pointCount === 0) {
    return pickOffset
  }

  var dataX   = dataBox[2] - dataBox[0]
  var dataY   = dataBox[3] - dataBox[1]

  var visiblePointCountEstimate = count(this.points, dataBox)
  var basicPointSize =  this.plot.pickPixelRatio * Math.max(Math.min(this.sizeMinCap, this.sizeMin), Math.min(this.sizeMax, this.sizeMax / Math.pow(visiblePointCountEstimate, 0.33333)))

  MATRIX[0] = 2.0 / dataX
  MATRIX[4] = 2.0 / dataY
  MATRIX[6] = -2.0 * dataBox[0] / dataX - 1.0
  MATRIX[7] = -2.0 * dataBox[1] / dataY - 1.0

  this.offsetBuffer.bind()

  shader.bind()
  shader.attributes.position.pointer()
  shader.uniforms.matrix      = MATRIX
  shader.uniforms.color       = this.color
  shader.uniforms.borderColor = this.borderColor
  shader.uniforms.pointCloud = basicPointSize < 5
  shader.uniforms.pointSize = basicPointSize
  shader.uniforms.centerFraction = Math.min(1, Math.max(0, Math.sqrt(1 - this.areaRatio)))

  if(pick) {

    PICK_VEC4[0] = ( pickOffset        & 0xff)
    PICK_VEC4[1] = ((pickOffset >> 8)  & 0xff)
    PICK_VEC4[2] = ((pickOffset >> 16) & 0xff)
    PICK_VEC4[3] = ((pickOffset >> 24) & 0xff)

    this.pickBuffer.bind()
    shader.attributes.pickId.pointer(gl.UNSIGNED_BYTE)
    shader.uniforms.pickOffset = PICK_VEC4
    this.pickOffset = pickOffset
  }

  // Worth switching these off, but we can't make assumptions about other
  // renderers, so let's restore it after each draw
  var blend = gl.getParameter(gl.BLEND)
  var dither = gl.getParameter(gl.DITHER)

  if(blend && !this.blend)
    gl.disable(gl.BLEND)
  if(dither)
    gl.disable(gl.DITHER)

  gl.drawArrays(gl.POINTS, 0, this.pointCount)

  if(blend && !this.blend)
    gl.enable(gl.BLEND)
  if(dither)
    gl.enable(gl.DITHER)

  return pickOffset + this.pointCount
}
})()

proto.draw = proto.unifiedDraw
proto.drawPick = proto.unifiedDraw

proto.pick = function(x, y, value) {
  var pickOffset = this.pickOffset
  var pointCount = this.pointCount
  if(value < pickOffset || value >= pickOffset + pointCount) {
    return null
  }
  var pointId = value - pickOffset
  var points = this.points
  return {
    object: this,
    pointId: pointId,
    dataCoord: [points[2 * pointId], points[2 * pointId + 1] ]
  }
}

function createPointcloud2D(plot, options) {
  var gl = plot.gl
  var buffer = createBuffer(gl)
  var pickBuffer = createBuffer(gl)
  var shader = createShader(gl, SHADERS.pointVertex, SHADERS.pointFragment)
  var pickShader = createShader(gl, SHADERS.pickVertex, SHADERS.pickFragment)

  var result = new Pointcloud2D(plot, buffer, pickBuffer, shader, pickShader)
  result.update(options)

  //Register with plot
  plot.addObject(result)

  return result
}

},{"./lib/shader":284,"gl-buffer":234,"gl-shader":294,"typedarray-pool":526}],286:[function(_dereq_,module,exports){
module.exports = slerp

/**
 * Performs a spherical linear interpolation between two quat
 *
 * @param {quat} out the receiving quaternion
 * @param {quat} a the first operand
 * @param {quat} b the second operand
 * @param {Number} t interpolation amount between the two inputs
 * @returns {quat} out
 */
function slerp (out, a, b, t) {
  // benchmarks:
  //    http://jsperf.com/quaternion-slerp-implementations

  var ax = a[0], ay = a[1], az = a[2], aw = a[3],
    bx = b[0], by = b[1], bz = b[2], bw = b[3]

  var omega, cosom, sinom, scale0, scale1

  // calc cosine
  cosom = ax * bx + ay * by + az * bz + aw * bw
  // adjust signs (if necessary)
  if (cosom < 0.0) {
    cosom = -cosom
    bx = -bx
    by = -by
    bz = -bz
    bw = -bw
  }
  // calculate coefficients
  if ((1.0 - cosom) > 0.000001) {
    // standard case (slerp)
    omega = Math.acos(cosom)
    sinom = Math.sin(omega)
    scale0 = Math.sin((1.0 - t) * omega) / sinom
    scale1 = Math.sin(t * omega) / sinom
  } else {
    // "from" and "to" quaternions are very close
    //  ... so we can do a linear interpolation
    scale0 = 1.0 - t
    scale1 = t
  }
  // calculate final values
  out[0] = scale0 * ax + scale1 * bx
  out[1] = scale0 * ay + scale1 * by
  out[2] = scale0 * az + scale1 * bz
  out[3] = scale0 * aw + scale1 * bw

  return out
}

},{}],287:[function(_dereq_,module,exports){
'use strict';

module.exports = function(a){
  return (!a && a !== 0) ? '' : a.toString();
}

},{}],288:[function(_dereq_,module,exports){
"use strict"

var vectorizeText = _dereq_("vectorize-text")

module.exports = getGlyph

var GLYPH_CACHE = {}

function getGlyph(symbol, font, pixelRatio) {
  var fontCache = GLYPH_CACHE[font]
  if(!fontCache) {
    fontCache = GLYPH_CACHE[font] = {}
  }
  if(symbol in fontCache) {
    return fontCache[symbol]
  }

  var config = {
    textAlign: "center",
    textBaseline: "middle",
    lineHeight: 1.0,
    font: font,
    lineSpacing: 1.25,
    styletags: {
      breaklines:true,
      bolds: true,
      italics: true,
      subscripts:true,
      superscripts:true
    }
  }

  //Get line and triangle meshes for glyph
  config.triangles = true
  var triSymbol = vectorizeText(symbol, config)
  config.triangles = false
  var lineSymbol = vectorizeText(symbol, config)

  var i, j

  if(pixelRatio && pixelRatio !== 1) {
    for(i = 0; i < triSymbol.positions.length; ++i){
      for(j = 0; j < triSymbol.positions[i].length; ++j){
        triSymbol.positions[i][j] /= pixelRatio;
      }
    }

    for(i = 0; i < lineSymbol.positions.length; ++i){
      for(j = 0; j < lineSymbol.positions[i].length; ++j){
        lineSymbol.positions[i][j] /= pixelRatio;
      }
    }
  }

  //Calculate bounding box
  var bounds = [[Infinity,Infinity], [-Infinity,-Infinity]]
  var n = lineSymbol.positions.length
  for(i = 0; i < n; ++i) {
    var p = lineSymbol.positions[i]
    for(j=0; j<2; ++j) {
      bounds[0][j] = Math.min(bounds[0][j], p[j])
      bounds[1][j] = Math.max(bounds[1][j], p[j])
    }
  }

  //Save cached symbol
  return fontCache[symbol] = [triSymbol, lineSymbol, bounds]
}
},{"vectorize-text":531}],289:[function(_dereq_,module,exports){
var createShaderWrapper = _dereq_('gl-shader')
var glslify = _dereq_('glslify')

var perspectiveVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform vec4 highlightId;\nuniform float highlightScale;\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    float scale = 1.0;\n    if(distance(highlightId, id) < 0.0001) {\n      scale = highlightScale;\n    }\n\n    vec4 worldPosition = model * vec4(position, 1);\n    vec4 viewPosition = view * worldPosition;\n    viewPosition = viewPosition / viewPosition.w;\n    vec4 clipPosition = projection * (viewPosition + scale * vec4(glyph.x, -glyph.y, 0, 0));\n\n    gl_Position = clipPosition;\n    interpColor = color;\n    pickId = id;\n    dataCoordinate = position;\n  }\n}"])
var orthographicVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float highlightScale, pixelRatio;\nuniform vec4 highlightId;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    float scale = pixelRatio;\n    if(distance(highlightId.bgr, id.bgr) < 0.001) {\n      scale *= highlightScale;\n    }\n\n    vec4 worldPosition = model * vec4(position, 1.0);\n    vec4 viewPosition = view * worldPosition;\n    vec4 clipPosition = projection * viewPosition;\n    clipPosition /= clipPosition.w;\n\n    gl_Position = clipPosition + vec4(screenSize * scale * vec2(glyph.x, -glyph.y), 0.0, 0.0);\n    interpColor = color;\n    pickId = id;\n    dataCoordinate = position;\n  }\n}"])
var projectionVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform float highlightScale;\nuniform vec4 highlightId;\nuniform vec3 axes[2];\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float scale, pixelRatio;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    float lscale = pixelRatio * scale;\n    if(distance(highlightId, id) < 0.0001) {\n      lscale *= highlightScale;\n    }\n\n    vec4 clipCenter   = projection * view * model * vec4(position, 1);\n    vec3 dataPosition = position + 0.5*lscale*(axes[0] * glyph.x + axes[1] * glyph.y) * clipCenter.w * screenSize.y;\n    vec4 clipPosition = projection * view * model * vec4(dataPosition, 1);\n\n    gl_Position = clipPosition;\n    interpColor = color;\n    pickId = id;\n    dataCoordinate = dataPosition;\n  }\n}\n"])
var drawFragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 fragClipBounds[2];\nuniform float opacity;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if (\n    outOfRange(fragClipBounds[0], fragClipBounds[1], dataCoordinate) ||\n    interpColor.a * opacity == 0.\n  ) discard;\n  gl_FragColor = interpColor * opacity;\n}\n"])
var pickFragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 fragClipBounds[2];\nuniform float pickGroup;\n\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if (outOfRange(fragClipBounds[0], fragClipBounds[1], dataCoordinate)) discard;\n\n  gl_FragColor = vec4(pickGroup, pickId.bgr);\n}"])

var ATTRIBUTES = [
  {name: 'position', type: 'vec3'},
  {name: 'color', type: 'vec4'},
  {name: 'glyph', type: 'vec2'},
  {name: 'id', type: 'vec4'}
]

var perspective = {
    vertex: perspectiveVertSrc,
    fragment: drawFragSrc,
    attributes: ATTRIBUTES
  },
  ortho = {
    vertex: orthographicVertSrc,
    fragment: drawFragSrc,
    attributes: ATTRIBUTES
  },
  project = {
    vertex: projectionVertSrc,
    fragment: drawFragSrc,
    attributes: ATTRIBUTES
  },
  pickPerspective = {
    vertex: perspectiveVertSrc,
    fragment: pickFragSrc,
    attributes: ATTRIBUTES
  },
  pickOrtho = {
    vertex: orthographicVertSrc,
    fragment: pickFragSrc,
    attributes: ATTRIBUTES
  },
  pickProject = {
    vertex: projectionVertSrc,
    fragment: pickFragSrc,
    attributes: ATTRIBUTES
  }

function createShader(gl, src) {
  var shader = createShaderWrapper(gl, src)
  var attr = shader.attributes
  attr.position.location = 0
  attr.color.location = 1
  attr.glyph.location = 2
  attr.id.location = 3
  return shader
}

exports.createPerspective = function(gl) {
  return createShader(gl, perspective)
}
exports.createOrtho = function(gl) {
  return createShader(gl, ortho)
}
exports.createProject = function(gl) {
  return createShader(gl, project)
}
exports.createPickPerspective = function(gl) {
  return createShader(gl, pickPerspective)
}
exports.createPickOrtho = function(gl) {
  return createShader(gl, pickOrtho)
}
exports.createPickProject = function(gl) {
  return createShader(gl, pickProject)
}

},{"gl-shader":294,"glslify":398}],290:[function(_dereq_,module,exports){
'use strict'

var isAllBlank      = _dereq_('is-string-blank')
var createBuffer    = _dereq_('gl-buffer')
var createVAO       = _dereq_('gl-vao')
var pool            = _dereq_('typedarray-pool')
var mat4mult        = _dereq_('gl-mat4/multiply')
var shaders         = _dereq_('./lib/shaders')
var getGlyph        = _dereq_('./lib/glyphs')
var getSimpleString = _dereq_('./lib/get-simple-string')

var IDENTITY = [1,0,0,0,
                0,1,0,0,
                0,0,1,0,
                0,0,0,1]

module.exports = createPointCloud

function transformMat4(x, m) {
  var x0 = x[0]
  var x1 = x[1]
  var x2 = x[2]
  var x3 = x[3]
  x[0] = m[0] * x0 + m[4] * x1 + m[8]  * x2 + m[12] * x3
  x[1] = m[1] * x0 + m[5] * x1 + m[9]  * x2 + m[13] * x3
  x[2] = m[2] * x0 + m[6] * x1 + m[10] * x2 + m[14] * x3
  x[3] = m[3] * x0 + m[7] * x1 + m[11] * x2 + m[15] * x3
  return x
}

function project(p, v, m, x) {
  transformMat4(x, x, m)
  transformMat4(x, x, v)
  return transformMat4(x, x, p)
}

function ScatterPlotPickResult(index, position) {
  this.index = index
  this.dataCoordinate = this.position = position
}

function fixOpacity(a) {
  if(a === true) return 1
  if(a > 1) return 1
  return a
}

function PointCloud(
  gl,
  shader,
  orthoShader,
  projectShader,
  pointBuffer,
  colorBuffer,
  glyphBuffer,
  idBuffer,
  vao,
  pickPerspectiveShader,
  pickOrthoShader,
  pickProjectShader) {

  this.gl              = gl

  this.pixelRatio      = 1

  this.shader          = shader
  this.orthoShader     = orthoShader
  this.projectShader   = projectShader

  this.pointBuffer     = pointBuffer
  this.colorBuffer     = colorBuffer
  this.glyphBuffer     = glyphBuffer
  this.idBuffer        = idBuffer
  this.vao             = vao
  this.vertexCount     = 0
  this.lineVertexCount = 0

  this.opacity         = 1
  this.hasAlpha        = false

  this.lineWidth       = 0
  this.projectScale    = [2.0/3.0, 2.0/3.0, 2.0/3.0]
  this.projectOpacity  = [1, 1, 1]
  this.projectHasAlpha  = false

  this.pickId                = 0
  this.pickPerspectiveShader = pickPerspectiveShader
  this.pickOrthoShader       = pickOrthoShader
  this.pickProjectShader     = pickProjectShader
  this.points                = []

  this._selectResult = new ScatterPlotPickResult(0, [0,0,0])

  this.useOrtho = true
  this.bounds   = [[ Infinity,Infinity,Infinity],
                   [-Infinity,-Infinity,-Infinity]]

  //Axes projections
  this.axesProject = [ true, true, true ]
  this.axesBounds = [[-Infinity,-Infinity,-Infinity],
                     [ Infinity, Infinity, Infinity]]

  this.highlightId    = [1,1,1,1]
  this.highlightScale = 2

  this.clipBounds = [[-Infinity,-Infinity,-Infinity],
                     [ Infinity, Infinity, Infinity]]

  this.dirty = true
}

var proto = PointCloud.prototype

proto.pickSlots = 1

proto.setPickBase = function(pickBase) {
  this.pickId = pickBase
}

proto.isTransparent = function() {
  if(this.hasAlpha)  {
    return true
  }
  for(var i=0; i<3; ++i) {
    if(this.axesProject[i] && this.projectHasAlpha) {
      return true
    }
  }
  return false
}

proto.isOpaque = function() {
  if(!this.hasAlpha)  {
    return true
  }
  for(var i=0; i<3; ++i) {
    if(this.axesProject[i] && !this.projectHasAlpha) {
      return true
    }
  }
  return false
}

var VIEW_SHAPE = [0,0]
var U_VEC = [0,0,0]
var V_VEC = [0,0,0]
var MU_VEC = [0,0,0,1]
var MV_VEC = [0,0,0,1]
var SCRATCH_MATRIX = IDENTITY.slice()
var SCRATCH_VEC = [0,0,0]
var CLIP_BOUNDS = [[0,0,0], [0,0,0]]

function zeroVec(a) {
  a[0] = a[1] = a[2] = 0
  return a
}

function augment(hg, af) {
  hg[0] = af[0]
  hg[1] = af[1]
  hg[2] = af[2]
  hg[3] = 1
  return hg
}

function setComponent(out, v, i, x) {
  out[0] = v[0]
  out[1] = v[1]
  out[2] = v[2]
  out[i] = x
  return out
}

function getClipBounds(bounds) {
  var result = CLIP_BOUNDS
  for(var i=0; i<2; ++i) {
    for(var j=0; j<3; ++j) {
      result[i][j] = Math.max(Math.min(bounds[i][j], 1e8), -1e8)
    }
  }
  return result
}

function drawProject(shader, points, camera, pixelRatio) {
  var axesProject = points.axesProject

  var gl         = points.gl
  var uniforms   = shader.uniforms
  var model      = camera.model      || IDENTITY
  var view       = camera.view       || IDENTITY
  var projection = camera.projection || IDENTITY
  var bounds     = points.axesBounds
  var clipBounds = getClipBounds(points.clipBounds)

  var cubeAxis
  if(points.axes && points.axes.lastCubeProps) {
    cubeAxis = points.axes.lastCubeProps.axis
  } else {
    cubeAxis = [1,1,1]
  }

  VIEW_SHAPE[0] = 2.0/gl.drawingBufferWidth
  VIEW_SHAPE[1] = 2.0/gl.drawingBufferHeight

  shader.bind()
  uniforms.view           = view
  uniforms.projection     = projection
  uniforms.screenSize     = VIEW_SHAPE
  uniforms.highlightId    = points.highlightId
  uniforms.highlightScale = points.highlightScale
  uniforms.clipBounds     = clipBounds
  uniforms.pickGroup      = points.pickId / 255.0
  uniforms.pixelRatio     = pixelRatio

  for(var i=0; i<3; ++i) {
    if(!axesProject[i]) {
      continue
    }

    uniforms.scale          = points.projectScale[i]
    uniforms.opacity        = points.projectOpacity[i]

    //Project model matrix
    var pmodel = SCRATCH_MATRIX
    for(var j=0; j<16; ++j) {
      pmodel[j] = 0
    }
    for(var j=0; j<4; ++j) {
      pmodel[5*j] = 1
    }
    pmodel[5*i] = 0
    if(cubeAxis[i] < 0) {
      pmodel[12+i] = bounds[0][i]
    } else {
      pmodel[12+i] = bounds[1][i]
    }
    mat4mult(pmodel, model, pmodel)
    uniforms.model = pmodel

    //Compute initial axes
    var u = (i+1)%3
    var v = (i+2)%3
    var du = zeroVec(U_VEC)
    var dv = zeroVec(V_VEC)
    du[u] = 1
    dv[v] = 1

    //Align orientation relative to viewer
    var mdu = project(projection, view, model, augment(MU_VEC, du))
    var mdv = project(projection, view, model, augment(MV_VEC, dv))
    if(Math.abs(mdu[1]) > Math.abs(mdv[1])) {
      var tmp = mdu
      mdu = mdv
      mdv = tmp
      tmp = du
      du = dv
      dv = tmp
      var t = u
      u = v
      v = t
    }
    if(mdu[0] < 0) {
      du[u] = -1
    }
    if(mdv[1] > 0) {
      dv[v] = -1
    }
    var su = 0.0
    var sv = 0.0
    for(var j=0; j<4; ++j) {
      su += Math.pow(model[4*u+j], 2)
      sv += Math.pow(model[4*v+j], 2)
    }
    du[u] /= Math.sqrt(su)
    dv[v] /= Math.sqrt(sv)
    uniforms.axes[0] = du
    uniforms.axes[1] = dv

    //Update fragment clip bounds
    uniforms.fragClipBounds[0] = setComponent(SCRATCH_VEC, clipBounds[0], i, -1e8)
    uniforms.fragClipBounds[1] = setComponent(SCRATCH_VEC, clipBounds[1], i, 1e8)

    points.vao.bind()

    //Draw interior
    points.vao.draw(gl.TRIANGLES, points.vertexCount)

    //Draw edges
    if(points.lineWidth > 0) {
      gl.lineWidth(points.lineWidth * pixelRatio)
      points.vao.draw(gl.LINES, points.lineVertexCount, points.vertexCount)
    }

    points.vao.unbind()
  }
}


var NEG_INFINITY3 = [-1e8, -1e8, -1e8]
var POS_INFINITY3 = [1e8, 1e8, 1e8]
var CLIP_GROUP    = [NEG_INFINITY3, POS_INFINITY3]

function drawFull(shader, pshader, points, camera, pixelRatio, transparent, forceDraw) {
  var gl = points.gl

  if(transparent === points.projectHasAlpha || forceDraw) {
    drawProject(pshader, points, camera, pixelRatio)
  }

  if(transparent === points.hasAlpha || forceDraw) {

    shader.bind()
    var uniforms = shader.uniforms

    uniforms.model      = camera.model      || IDENTITY
    uniforms.view       = camera.view       || IDENTITY
    uniforms.projection = camera.projection || IDENTITY

    VIEW_SHAPE[0]       = 2.0/gl.drawingBufferWidth
    VIEW_SHAPE[1]       = 2.0/gl.drawingBufferHeight
    uniforms.screenSize = VIEW_SHAPE

    uniforms.highlightId    = points.highlightId
    uniforms.highlightScale = points.highlightScale

    uniforms.fragClipBounds = CLIP_GROUP
    uniforms.clipBounds     = points.axes.bounds

    uniforms.opacity    = points.opacity
    uniforms.pickGroup  = points.pickId / 255.0

    uniforms.pixelRatio = pixelRatio

    points.vao.bind()

    //Draw interior
    points.vao.draw(gl.TRIANGLES, points.vertexCount)

    //Draw edges
    if(points.lineWidth > 0) {
      gl.lineWidth(points.lineWidth * pixelRatio)
      points.vao.draw(gl.LINES, points.lineVertexCount, points.vertexCount)
    }

    points.vao.unbind()
  }


}

proto.draw = function(camera) {
  var shader = this.useOrtho ? this.orthoShader : this.shader
  drawFull(shader, this.projectShader, this, camera, this.pixelRatio, false, false)
}

proto.drawTransparent = function(camera) {
  var shader = this.useOrtho ? this.orthoShader : this.shader
  drawFull(shader, this.projectShader, this, camera, this.pixelRatio, true, false)
}

proto.drawPick = function(camera) {
  var shader = this.useOrtho ? this.pickOrthoShader : this.pickPerspectiveShader
  drawFull(shader, this.pickProjectShader, this, camera, 1, true, true)
}

proto.pick = function(selected) {
  if(!selected) {
    return null
  }
  if(selected.id !== this.pickId) {
    return null
  }
  var x = selected.value[2] + (selected.value[1]<<8) + (selected.value[0]<<16)
  if(x >= this.pointCount || x < 0) {
    return null
  }

  //Unpack result
  var coord = this.points[x]
  var result = this._selectResult
  result.index = x
  for(var i=0; i<3; ++i) {
    result.position[i] = result.dataCoordinate[i] = coord[i]
  }
  return result
}

proto.highlight = function(selection) {
  if(!selection) {
    this.highlightId = [1,1,1,1]
  } else {
    var pointId = selection.index
    var a0 =  pointId     &0xff
    var a1 = (pointId>>8) &0xff
    var a2 = (pointId>>16)&0xff
    this.highlightId = [a0/255.0, a1/255.0, a2/255.0, 0]
  }
}

function get_glyphData(glyphs, index, font, pixelRatio) {
  var str

  // use the data if presented in an array
  if(Array.isArray(glyphs)) {
    if(index < glyphs.length) {
      str = glyphs[index]
    } else {
      str = undefined
    }
  } else {
    str = glyphs
  }

  str = getSimpleString(str) // this would handle undefined cases

  var visible = true
  if(isAllBlank(str)) {
    str = '▼' // Note: this special character may have minimum number of surfaces
    visible = false
  }

  var glyph = getGlyph(str, font, pixelRatio)

  return { mesh:glyph[0],
          lines:glyph[1],
         bounds:glyph[2],
        visible:visible };
}



proto.update = function(options) {

  options = options || {}

  if('perspective' in options) {
    this.useOrtho = !options.perspective
  }
  if('orthographic' in options) {
    this.useOrtho = !!options.orthographic
  }
  if('lineWidth' in options) {
    this.lineWidth = options.lineWidth
  }
  if('project' in options) {
    if(Array.isArray(options.project)) {
      this.axesProject = options.project
    } else {
      var v = !!options.project
      this.axesProject = [v,v,v]
    }
  }
  if('projectScale' in options) {
    if(Array.isArray(options.projectScale)) {
      this.projectScale = options.projectScale.slice()
    } else {
      var s = +options.projectScale
      this.projectScale = [s,s,s]
    }
  }

  this.projectHasAlpha = false // default to no transparent draw
  if('projectOpacity' in options) {
    if(Array.isArray(options.projectOpacity)) {
      this.projectOpacity = options.projectOpacity.slice()
    } else {
      var s = +options.projectOpacity
      this.projectOpacity = [s,s,s]
    }
    for(var i=0; i<3; ++i) {
      this.projectOpacity[i] = fixOpacity(this.projectOpacity[i]);
      if(this.projectOpacity[i] < 1) {
        this.projectHasAlpha = true;
      }
    }
  }

  this.hasAlpha = false // default to no transparent draw
  if('opacity' in options) {
    this.opacity = fixOpacity(options.opacity)
    if(this.opacity < 1) {
      this.hasAlpha = true;
    }
  }

  //Set dirty flag
  this.dirty = true

  //Create new buffers
  var points = options.position

  //Text font
  var font      = options.font      || 'normal'
  var alignment = options.alignment || [0,0]

  var alignmentX;
  var alignmentY;
  if (alignment.length === 2) {
    alignmentX = alignment[0]
    alignmentY = alignment[1]
  } else {
    alignmentX = []
    alignmentY = []
    for (var i = 0; i < alignment.length; ++i) {
      alignmentX[i] = alignment[i][0]
      alignmentY[i] = alignment[i][1]
    }
  }

  //Bounds
  var lowerBound = [ Infinity, Infinity, Infinity]
  var upperBound = [-Infinity,-Infinity,-Infinity]

  //Unpack options
  var glyphs     = options.glyph
  var colors     = options.color
  var sizes      = options.size
  var angles     = options.angle
  var lineColors = options.lineColor

  //Picking geometry
  var pickCounter = -1

  //First do pass to compute buffer sizes
  var triVertexCount  = 0
  var lineVertexCount = 0

  var numPoints = 0;

  if(points.length) {

    //Count number of points and buffer size
    numPoints = points.length

  count_loop:
    for(var i=0; i<numPoints; ++i) {
      var x = points[i]
      for(var j=0; j<3; ++j) {
        if(isNaN(x[j]) || !isFinite(x[j])) {
          continue count_loop
        }
      }

      var glyphData = get_glyphData(glyphs, i, font, this.pixelRatio)

      var glyphMesh   = glyphData.mesh
      var glyphLines  = glyphData.lines
      var glyphBounds = glyphData.bounds

      triVertexCount  += glyphMesh.cells.length * 3
      lineVertexCount += glyphLines.edges.length * 2
    }
  }

  var vertexCount   = triVertexCount + lineVertexCount

  //Preallocate data
  var positionArray = pool.mallocFloat(3*vertexCount)
  var colorArray    = pool.mallocFloat(4*vertexCount)
  var glyphArray    = pool.mallocFloat(2*vertexCount)
  var idArray       = pool.mallocUint32(vertexCount)

  if(vertexCount > 0) {
    var triOffset  = 0
    var lineOffset = triVertexCount
    var color      = [0,0,0,1]
    var lineColor  = [0,0,0,1]

    var isColorArray      = Array.isArray(colors)     && Array.isArray(colors[0])
    var isLineColorArray  = Array.isArray(lineColors) && Array.isArray(lineColors[0])

  fill_loop:
    for(var i=0; i<numPoints; ++i) {
      //Increment pickCounter
      pickCounter += 1

      var x = points[i]
      for(var j=0; j<3; ++j) {
        if(isNaN(x[j]) || !isFinite(x[j])) {
          continue fill_loop
        }

        upperBound[j] = Math.max(upperBound[j], x[j])
        lowerBound[j] = Math.min(lowerBound[j], x[j])
      }

      var glyphData = get_glyphData(glyphs, i, font, this.pixelRatio)

      var glyphMesh   = glyphData.mesh
      var glyphLines  = glyphData.lines
      var glyphBounds = glyphData.bounds
      var glyphVisible = glyphData.visible

      //Get color
      if(!glyphVisible) color = [1,1,1,0]
      else if(Array.isArray(colors)) {
        var c
        if(isColorArray) {
          if(i < colors.length) {
            c = colors[i]
          } else {
            c = [0,0,0,0]
          }
        } else {
          c = colors
        }

        if(c.length === 3) {
          for(var j=0; j<3; ++j) {
            color[j] = c[j]
          }
          color[3] = 1
        } else if(c.length === 4) {
          for(var j=0; j<4; ++j) {
            color[j] = c[j]
          }
          if(!this.hasAlpha && c[3] < 1) this.hasAlpha = true
        }
      } else {
        color[0] = color[1] = color[2] = 0
        color[3] = 1
      }


      //Get lineColor
      if(!glyphVisible) lineColor = [1,1,1,0]
      else if(Array.isArray(lineColors)) {
        var c
        if(isLineColorArray) {
          if(i < lineColors.length) {
            c = lineColors[i]
          } else {
            c = [0,0,0,0]
          }
        } else {
          c = lineColors
        }

        if(c.length === 3) {
          for(var j=0; j<3; ++j) {
            lineColor[j] = c[j]
          }
          lineColor[j] = 1
        } else if(c.length === 4) {
          for(var j=0; j<4; ++j) {
            lineColor[j] = c[j]
          }
          if(!this.hasAlpha && c[3] < 1) this.hasAlpha = true
        }
      } else {
        lineColor[0] = lineColor[1] = lineColor[2] = 0
        lineColor[3] = 1
      }


      var size = 0.5
      if(!glyphVisible) size = 0.0
      else if(Array.isArray(sizes)) {
        if(i < sizes.length) {
          size = +sizes[i]
        } else {
          size = 12
        }
      } else if(sizes) {
        size = +sizes
      } else if(this.useOrtho) {
        size = 12
      }


      var angle = 0
      if(Array.isArray(angles)) {
        if(i < angles.length) {
          angle = +angles[i]
        } else {
          angle = 0
        }
      } else if(angles) {
        angle = +angles
      }

      //Loop through markers and append to buffers
      var cos = Math.cos(angle)
      var sin = Math.sin(angle)

      var x = points[i]
      for(var j=0; j<3; ++j) {
        upperBound[j] = Math.max(upperBound[j], x[j])
        lowerBound[j] = Math.min(lowerBound[j], x[j])
      }

      //Calculate text offset
      var textOffsetX = alignmentX
      var textOffsetY = alignmentY

      var textOffsetX = 0
      if(Array.isArray(alignmentX)) {
        if(i < alignmentX.length) {
          textOffsetX = alignmentX[i]
        } else {
          textOffsetX = 0
        }
      } else if(alignmentX) {
        textOffsetX = alignmentX
      }

      var textOffsetY = 0
      if(Array.isArray(alignmentY)) {
        if(i < alignmentY.length) {
          textOffsetY = alignmentY[i]
        } else {
          textOffsetY = 0
        }
      } else if(alignmentY) {
        textOffsetY = alignmentY
      }

      textOffsetX *= (textOffsetX > 0) ? (1 - glyphBounds[0][0]) :
                     (textOffsetX < 0) ? (1 + glyphBounds[1][0]) : 1;

      textOffsetY *= (textOffsetY > 0) ? (1 - glyphBounds[0][1]) :
                     (textOffsetY < 0) ? (1 + glyphBounds[1][1]) : 1;

      var textOffset = [textOffsetX, textOffsetY]

      //Write out inner marker
      var cells = glyphMesh.cells || []
      var verts = glyphMesh.positions || []

      for(var j=0; j<cells.length; ++j) {
        var cell = cells[j]
        for(var k=0; k<3; ++k) {
          for(var l=0; l<3; ++l) {
            positionArray[3*triOffset+l] = x[l]
          }
          for(var l=0; l<4; ++l) {
            colorArray[4*triOffset+l] = color[l]
          }
          idArray[triOffset] = pickCounter
          var p = verts[cell[k]]
          glyphArray[2*triOffset]   = size * (cos*p[0] - sin*p[1] + textOffset[0])
          glyphArray[2*triOffset+1] = size * (sin*p[0] + cos*p[1] + textOffset[1])
          triOffset += 1
        }
      }

      var cells = glyphLines.edges
      var verts = glyphLines.positions

      for(var j=0; j<cells.length; ++j) {
        var cell = cells[j]
        for(var k=0; k<2; ++k) {
          for(var l=0; l<3; ++l) {
            positionArray[3*lineOffset+l] = x[l]
          }
          for(var l=0; l<4; ++l) {
            colorArray[4*lineOffset+l] = lineColor[l]
          }
          idArray[lineOffset] = pickCounter
          var p = verts[cell[k]]
          glyphArray[2*lineOffset]   = size * (cos*p[0] - sin*p[1] + textOffset[0])
          glyphArray[2*lineOffset+1] = size * (sin*p[0] + cos*p[1] + textOffset[1])
          lineOffset += 1
        }
      }

    }



  }

  //Update bounds
  this.bounds = [lowerBound, upperBound]

  //Save points
  this.points = points

  //Save number of points
  this.pointCount = points.length

  //Update vertex counts
  this.vertexCount      = triVertexCount
  this.lineVertexCount  = lineVertexCount

  this.pointBuffer.update(positionArray)
  this.colorBuffer.update(colorArray)
  this.glyphBuffer.update(glyphArray)
  //this.idBuffer.update(new Uint32Array(idArray))
  this.idBuffer.update(idArray)

  pool.free(positionArray)
  pool.free(colorArray)
  pool.free(glyphArray)
  pool.free(idArray)
}

proto.dispose = function() {
  //Shaders
  this.shader.dispose()
  this.orthoShader.dispose()
  this.pickPerspectiveShader.dispose()
  this.pickOrthoShader.dispose()

  //Vertex array
  this.vao.dispose()

  //Buffers
  this.pointBuffer.dispose()
  this.colorBuffer.dispose()
  this.glyphBuffer.dispose()
  this.idBuffer.dispose()
}

function createPointCloud(options) {
  var gl = options.gl

  var shader                = shaders.createPerspective(gl)
  var orthoShader           = shaders.createOrtho(gl)
  var projectShader         = shaders.createProject(gl)
  var pickPerspectiveShader = shaders.createPickPerspective(gl)
  var pickOrthoShader       = shaders.createPickOrtho(gl)
  var pickProjectShader     = shaders.createPickProject(gl)

  var pointBuffer = createBuffer(gl)
  var colorBuffer = createBuffer(gl)
  var glyphBuffer = createBuffer(gl)
  var idBuffer    = createBuffer(gl)
  var vao = createVAO(gl, [
    {
      buffer: pointBuffer,
      size: 3,
      type: gl.FLOAT
    },
    {
      buffer: colorBuffer,
      size: 4,
      type: gl.FLOAT
    },
    {
      buffer: glyphBuffer,
      size: 2,
      type: gl.FLOAT
    },
    {
      buffer: idBuffer,
      size: 4,
      type: gl.UNSIGNED_BYTE,
      normalized: true
    }
  ])

  var pointCloud = new PointCloud(
    gl,
    shader,
    orthoShader,
    projectShader,
    pointBuffer,
    colorBuffer,
    glyphBuffer,
    idBuffer,
    vao,
    pickPerspectiveShader,
    pickOrthoShader,
    pickProjectShader)

  pointCloud.update(options)

  return pointCloud
}

},{"./lib/get-simple-string":287,"./lib/glyphs":288,"./lib/shaders":289,"gl-buffer":234,"gl-mat4/multiply":260,"gl-vao":316,"is-string-blank":412,"typedarray-pool":526}],291:[function(_dereq_,module,exports){
'use strict'

var glslify = _dereq_('glslify')

exports.boxVertex = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 vertex;\n\nuniform vec2 cornerA, cornerB;\n\nvoid main() {\n  gl_Position = vec4(mix(cornerA, cornerB, vertex), 0, 1);\n}\n"])
exports.boxFragment = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n  gl_FragColor = color;\n}\n"])

},{"glslify":398}],292:[function(_dereq_,module,exports){
'use strict'

var createShader = _dereq_('gl-shader')
var createBuffer = _dereq_('gl-buffer')

var SHADERS = _dereq_('./lib/shaders')

module.exports = createSelectBox

function SelectBox(plot, boxBuffer, boxShader) {
  this.plot = plot
  this.boxBuffer = boxBuffer
  this.boxShader = boxShader

  this.enabled = true

  this.selectBox = [Infinity,Infinity,-Infinity,-Infinity]

  this.borderColor = [0,0,0,1]
  this.innerFill   = false
  this.innerColor  = [0,0,0,0.25]
  this.outerFill   = true
  this.outerColor  = [0,0,0,0.5]
  this.borderWidth = 10
}

var proto = SelectBox.prototype

proto.draw = function() {
  if(!this.enabled) {
    return
  }

  var plot         = this.plot
  var selectBox    = this.selectBox
  var lineWidth    = this.borderWidth

  var innerFill    = this.innerFill
  var innerColor   = this.innerColor
  var outerFill    = this.outerFill
  var outerColor   = this.outerColor
  var borderColor  = this.borderColor

  var boxes        = plot.box
  var screenBox    = plot.screenBox
  var dataBox      = plot.dataBox
  var viewBox      = plot.viewBox
  var pixelRatio   = plot.pixelRatio

  //Map select box into pixel coordinates
  var loX = (selectBox[0]-dataBox[0])*(viewBox[2]-viewBox[0])/(dataBox[2]-dataBox[0])+viewBox[0]
  var loY = (selectBox[1]-dataBox[1])*(viewBox[3]-viewBox[1])/(dataBox[3]-dataBox[1])+viewBox[1]
  var hiX = (selectBox[2]-dataBox[0])*(viewBox[2]-viewBox[0])/(dataBox[2]-dataBox[0])+viewBox[0]
  var hiY = (selectBox[3]-dataBox[1])*(viewBox[3]-viewBox[1])/(dataBox[3]-dataBox[1])+viewBox[1]

  loX = Math.max(loX, viewBox[0])
  loY = Math.max(loY, viewBox[1])
  hiX = Math.min(hiX, viewBox[2])
  hiY = Math.min(hiY, viewBox[3])

  if(hiX < loX || hiY < loY) {
    return
  }

  boxes.bind()

  //Draw box
  var screenWidth  = screenBox[2] - screenBox[0]
  var screenHeight = screenBox[3] - screenBox[1]

  if(this.outerFill) {
    boxes.drawBox(0, 0, screenWidth, loY, outerColor)
    boxes.drawBox(0, loY, loX, hiY, outerColor)
    boxes.drawBox(0, hiY, screenWidth, screenHeight, outerColor)
    boxes.drawBox(hiX, loY, screenWidth, hiY, outerColor)
  }

  if(this.innerFill) {
    boxes.drawBox(loX, loY, hiX, hiY, innerColor)
  }

  //Draw border
  if(lineWidth > 0) {

    //Draw border
    var w = lineWidth * pixelRatio
    boxes.drawBox(loX-w, loY-w, hiX+w, loY+w, borderColor)
    boxes.drawBox(loX-w, hiY-w, hiX+w, hiY+w, borderColor)
    boxes.drawBox(loX-w, loY-w, loX+w, hiY+w, borderColor)
    boxes.drawBox(hiX-w, loY-w, hiX+w, hiY+w, borderColor)
  }
}

proto.update = function(options) {
  options = options || {}

  this.innerFill    = !!options.innerFill
  this.outerFill    = !!options.outerFill
  this.innerColor   = (options.innerColor   || [0,0,0,0.5]).slice()
  this.outerColor   = (options.outerColor   || [0,0,0,0.5]).slice()
  this.borderColor  = (options.borderColor || [0,0,0,1]).slice()
  this.borderWidth  = options.borderWidth || 0
  this.selectBox    = (options.selectBox || this.selectBox).slice()
}

proto.dispose = function() {
  this.boxBuffer.dispose()
  this.boxShader.dispose()
  this.plot.removeOverlay(this)
}

function createSelectBox(plot, options) {
  var gl = plot.gl
  var buffer = createBuffer(gl, [
    0, 0,
    0, 1,
    1, 0,
    1, 1 ])
  var shader = createShader(gl, SHADERS.boxVertex, SHADERS.boxFragment)
  var selectBox = new SelectBox(plot, buffer, shader)
  selectBox.update(options)
  plot.addOverlay(selectBox)
  return selectBox
}

},{"./lib/shaders":291,"gl-buffer":234,"gl-shader":294}],293:[function(_dereq_,module,exports){
'use strict'

module.exports = createSelectBuffer

var createFBO = _dereq_('gl-fbo')
var pool      = _dereq_('typedarray-pool')
var ndarray   = _dereq_('ndarray')

var nextPow2  = _dereq_('bit-twiddle').nextPow2

var selectRange = _dereq_('cwise/lib/wrapper')({"args":["array",{"offset":[0,0,1],"array":0},{"offset":[0,0,2],"array":0},{"offset":[0,0,3],"array":0},"scalar","scalar","index"],"pre":{"body":"{this_closestD2=1e8,this_closestX=-1,this_closestY=-1}","args":[],"thisVars":["this_closestD2","this_closestX","this_closestY"],"localVars":[]},"body":{"body":"{if(_inline_16_arg0_<255||_inline_16_arg1_<255||_inline_16_arg2_<255||_inline_16_arg3_<255){var _inline_16_l=_inline_16_arg4_-_inline_16_arg6_[0],_inline_16_a=_inline_16_arg5_-_inline_16_arg6_[1],_inline_16_f=_inline_16_l*_inline_16_l+_inline_16_a*_inline_16_a;_inline_16_f<this_closestD2&&(this_closestD2=_inline_16_f,this_closestX=_inline_16_arg6_[0],this_closestY=_inline_16_arg6_[1])}}","args":[{"name":"_inline_16_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_16_arg1_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_16_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_16_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_16_arg4_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_16_arg5_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_16_arg6_","lvalue":false,"rvalue":true,"count":4}],"thisVars":["this_closestD2","this_closestX","this_closestY"],"localVars":["_inline_16_a","_inline_16_f","_inline_16_l"]},"post":{"body":"{return[this_closestX,this_closestY,this_closestD2]}","args":[],"thisVars":["this_closestD2","this_closestX","this_closestY"],"localVars":[]},"debug":false,"funcName":"cwise","blockSize":64})

function SelectResult(x, y, id, value, distance) {
  this.coord = [x, y]
  this.id = id
  this.value = value
  this.distance = distance
}

function SelectBuffer(gl, fbo, buffer) {
  this.gl     = gl
  this.fbo    = fbo
  this.buffer = buffer
  this._readTimeout = null
  var self = this

  this._readCallback = function() {
    if(!self.gl) {
      return
    }
    fbo.bind()
    gl.readPixels(0,0,fbo.shape[0],fbo.shape[1],gl.RGBA,gl.UNSIGNED_BYTE,self.buffer)
    self._readTimeout = null
  }
}

var proto = SelectBuffer.prototype

Object.defineProperty(proto, 'shape', {
  get: function() {
    if(!this.gl) {
      return [0,0]
    }
    return this.fbo.shape.slice()
  },
  set: function(v) {
    if(!this.gl) {
      return
    }
    this.fbo.shape = v
    var c = this.fbo.shape[0]
    var r = this.fbo.shape[1]
    if(r*c*4 > this.buffer.length) {
      pool.free(this.buffer)
      var buffer = this.buffer = pool.mallocUint8(nextPow2(r*c*4))
      for(var i=0; i<r*c*4; ++i) {
        buffer[i] = 0xff
      }
    }
    return v
  }
})

proto.begin = function() {
  var gl = this.gl
  var shape = this.shape
  if(!gl) {
    return
  }

  this.fbo.bind()
  gl.clearColor(1,1,1,1)
  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
}

proto.end = function() {
  var gl = this.gl
  if(!gl) {
    return
  }
  gl.bindFramebuffer(gl.FRAMEBUFFER, null)
  if(!this._readTimeout) {
    clearTimeout(this._readTimeout)
  }
  this._readTimeout = setTimeout(this._readCallback, 1)
}

proto.query = function(x, y, radius) {
  if(!this.gl) {
    return null
  }

  var shape = this.fbo.shape.slice()

  x = x|0
  y = y|0
  if(typeof radius !== 'number') {
    radius = 1.0
  }

  var x0 = Math.min(Math.max(x - radius, 0), shape[0])|0
  var x1 = Math.min(Math.max(x + radius, 0), shape[0])|0
  var y0 = Math.min(Math.max(y - radius, 0), shape[1])|0
  var y1 = Math.min(Math.max(y + radius, 0), shape[1])|0

  if(x1 <= x0 || y1 <= y0) {
    return null
  }

  var dims   = [x1-x0,y1-y0]
  var region = ndarray(
    this.buffer,
    [dims[0], dims[1], 4],
    [4, shape[0]*4, 1],
    4*(x0 + shape[0]*y0));

  var closest = selectRange(region.hi(dims[0],dims[1],1), radius, radius)
  var dx = closest[0]
  var dy = closest[1]
  if(dx < 0 || Math.pow(this.radius, 2) < closest[2]) {
    return null
  }

  var c0 = region.get(dx, dy, 0)
  var c1 = region.get(dx, dy, 1)
  var c2 = region.get(dx, dy, 2)
  var c3 = region.get(dx, dy, 3)

  return new SelectResult(
     (dx + x0)|0,
     (dy + y0)|0,
     c0,
     [c1, c2, c3],
     Math.sqrt(closest[2]))
}

proto.dispose = function() {
  if(!this.gl) {
    return
  }
  this.fbo.dispose()
  pool.free(this.buffer)
  this.gl = null
  if(this._readTimeout) {
    clearTimeout(this._readTimeout)
  }
}

function createSelectBuffer(gl, shape) {
  var fbo = createFBO(gl, shape)
  var buffer = pool.mallocUint8(shape[0]*shape[1]*4)
  return new SelectBuffer(gl, fbo, buffer)
}

},{"bit-twiddle":80,"cwise/lib/wrapper":137,"gl-fbo":242,"ndarray":439,"typedarray-pool":526}],294:[function(_dereq_,module,exports){
'use strict'

var createUniformWrapper   = _dereq_('./lib/create-uniforms')
var createAttributeWrapper = _dereq_('./lib/create-attributes')
var makeReflect            = _dereq_('./lib/reflect')
var shaderCache            = _dereq_('./lib/shader-cache')
var runtime                = _dereq_('./lib/runtime-reflect')
var GLError                = _dereq_("./lib/GLError")

//Shader object
function Shader(gl) {
  this.gl         = gl
  this.gl.lastAttribCount = 0  // fixme where else should we store info, safe but not nice on the gl object

  //Default initialize these to null
  this._vref      =
  this._fref      =
  this._relink    =
  this.vertShader =
  this.fragShader =
  this.program    =
  this.attributes =
  this.uniforms   =
  this.types      = null
}

var proto = Shader.prototype

proto.bind = function() {
  if(!this.program) {
    this._relink()
  }

  // ensuring that we have the right number of enabled vertex attributes
  var i
  var newAttribCount = this.gl.getProgramParameter(this.program, this.gl.ACTIVE_ATTRIBUTES) // more robust approach
  //var newAttribCount = Object.keys(this.attributes).length // avoids the probably immaterial introspection slowdown
  var oldAttribCount = this.gl.lastAttribCount
  if(newAttribCount > oldAttribCount) {
    for(i = oldAttribCount; i < newAttribCount; i++) {
      this.gl.enableVertexAttribArray(i)
    }
  } else if(oldAttribCount > newAttribCount) {
    for(i = newAttribCount; i < oldAttribCount; i++) {
      this.gl.disableVertexAttribArray(i)
    }
  }

  this.gl.lastAttribCount = newAttribCount

  this.gl.useProgram(this.program)
}

proto.dispose = function() {

  // disabling vertex attributes so new shader starts with zero
  // and it's also useful if all shaders are disposed but the
  // gl context is reused for subsequent replotting
  var oldAttribCount = this.gl.lastAttribCount
  for (var i = 0; i < oldAttribCount; i++) {
    this.gl.disableVertexAttribArray(i)
  }
  this.gl.lastAttribCount = 0

  if(this._fref) {
    this._fref.dispose()
  }
  if(this._vref) {
    this._vref.dispose()
  }
  this.attributes =
  this.types      =
  this.vertShader =
  this.fragShader =
  this.program    =
  this._relink    =
  this._fref      =
  this._vref      = null
}

function compareAttributes(a, b) {
  if(a.name < b.name) {
    return -1
  }
  return 1
}

//Update export hook for glslify-live
proto.update = function(
    vertSource
  , fragSource
  , uniforms
  , attributes) {

  //If only one object passed, assume glslify style output
  if(!fragSource || arguments.length === 1) {
    var obj = vertSource
    vertSource = obj.vertex
    fragSource = obj.fragment
    uniforms   = obj.uniforms
    attributes = obj.attributes
  }

  var wrapper = this
  var gl      = wrapper.gl

  //Compile vertex and fragment shaders
  var pvref = wrapper._vref
  wrapper._vref = shaderCache.shader(gl, gl.VERTEX_SHADER, vertSource)
  if(pvref) {
    pvref.dispose()
  }
  wrapper.vertShader = wrapper._vref.shader
  var pfref = this._fref
  wrapper._fref = shaderCache.shader(gl, gl.FRAGMENT_SHADER, fragSource)
  if(pfref) {
    pfref.dispose()
  }
  wrapper.fragShader = wrapper._fref.shader

  //If uniforms/attributes is not specified, use RT reflection
  if(!uniforms || !attributes) {

    //Create initial test program
    var testProgram = gl.createProgram()
    gl.attachShader(testProgram, wrapper.fragShader)
    gl.attachShader(testProgram, wrapper.vertShader)
    gl.linkProgram(testProgram)
    if(!gl.getProgramParameter(testProgram, gl.LINK_STATUS)) {
      var errLog = gl.getProgramInfoLog(testProgram)
      throw new GLError(errLog, 'Error linking program:' + errLog)
    }

    //Load data from runtime
    uniforms   = uniforms   || runtime.uniforms(gl, testProgram)
    attributes = attributes || runtime.attributes(gl, testProgram)

    //Release test program
    gl.deleteProgram(testProgram)
  }

  //Sort attributes lexicographically
  // overrides undefined WebGL behavior for attribute locations
  attributes = attributes.slice()
  attributes.sort(compareAttributes)

  //Convert attribute types, read out locations
  var attributeUnpacked  = []
  var attributeNames     = []
  var attributeLocations = []
  var i
  for(i=0; i<attributes.length; ++i) {
    var attr = attributes[i]
    if(attr.type.indexOf('mat') >= 0) {
      var size = attr.type.charAt(attr.type.length-1)|0
      var locVector = new Array(size)
      for(var j=0; j<size; ++j) {
        locVector[j] = attributeLocations.length
        attributeNames.push(attr.name + '[' + j + ']')
        if(typeof attr.location === 'number') {
          attributeLocations.push(attr.location + j)
        } else if(Array.isArray(attr.location) &&
                  attr.location.length === size &&
                  typeof attr.location[j] === 'number') {
          attributeLocations.push(attr.location[j]|0)
        } else {
          attributeLocations.push(-1)
        }
      }
      attributeUnpacked.push({
        name: attr.name,
        type: attr.type,
        locations: locVector
      })
    } else {
      attributeUnpacked.push({
        name: attr.name,
        type: attr.type,
        locations: [ attributeLocations.length ]
      })
      attributeNames.push(attr.name)
      if(typeof attr.location === 'number') {
        attributeLocations.push(attr.location|0)
      } else {
        attributeLocations.push(-1)
      }
    }
  }

  //For all unspecified attributes, assign them lexicographically min attribute
  var curLocation = 0
  for(i=0; i<attributeLocations.length; ++i) {
    if(attributeLocations[i] < 0) {
      while(attributeLocations.indexOf(curLocation) >= 0) {
        curLocation += 1
      }
      attributeLocations[i] = curLocation
    }
  }

  //Rebuild program and recompute all uniform locations
  var uniformLocations = new Array(uniforms.length)
  function relink() {
    wrapper.program = shaderCache.program(
        gl
      , wrapper._vref
      , wrapper._fref
      , attributeNames
      , attributeLocations)

    for(var i=0; i<uniforms.length; ++i) {
      uniformLocations[i] = gl.getUniformLocation(
          wrapper.program
        , uniforms[i].name)
    }
  }

  //Perform initial linking, reuse program used for reflection
  relink()

  //Save relinking procedure, defer until runtime
  wrapper._relink = relink

  //Generate type info
  wrapper.types = {
    uniforms:   makeReflect(uniforms),
    attributes: makeReflect(attributes)
  }

  //Generate attribute wrappers
  wrapper.attributes = createAttributeWrapper(
      gl
    , wrapper
    , attributeUnpacked
    , attributeLocations)

  //Generate uniform wrappers
  Object.defineProperty(wrapper, 'uniforms', createUniformWrapper(
      gl
    , wrapper
    , uniforms
    , uniformLocations))
}

//Compiles and links a shader program with the given attribute and vertex list
function createShader(
    gl
  , vertSource
  , fragSource
  , uniforms
  , attributes) {

  var shader = new Shader(gl)

  shader.update(
      vertSource
    , fragSource
    , uniforms
    , attributes)

  return shader
}

module.exports = createShader

},{"./lib/GLError":295,"./lib/create-attributes":296,"./lib/create-uniforms":297,"./lib/reflect":298,"./lib/runtime-reflect":299,"./lib/shader-cache":300}],295:[function(_dereq_,module,exports){
function GLError (rawError, shortMessage, longMessage) {
    this.shortMessage = shortMessage || ''
    this.longMessage = longMessage || ''
    this.rawError = rawError || ''
    this.message =
      'gl-shader: ' + (shortMessage || rawError || '') +
      (longMessage ? '\n'+longMessage : '')
    this.stack = (new Error()).stack
}
GLError.prototype = new Error
GLError.prototype.name = 'GLError'
GLError.prototype.constructor = GLError
module.exports = GLError

},{}],296:[function(_dereq_,module,exports){
'use strict'

module.exports = createAttributeWrapper

var GLError = _dereq_("./GLError")

function ShaderAttribute(
    gl
  , wrapper
  , index
  , locations
  , dimension
  , constFunc) {
  this._gl        = gl
  this._wrapper   = wrapper
  this._index     = index
  this._locations = locations
  this._dimension = dimension
  this._constFunc = constFunc
}

var proto = ShaderAttribute.prototype

proto.pointer = function setAttribPointer(
    type
  , normalized
  , stride
  , offset) {

  var self      = this
  var gl        = self._gl
  var location  = self._locations[self._index]

  gl.vertexAttribPointer(
      location
    , self._dimension
    , type || gl.FLOAT
    , !!normalized
    , stride || 0
    , offset || 0)
  gl.enableVertexAttribArray(location)
}

proto.set = function(x0, x1, x2, x3) {
  return this._constFunc(this._locations[this._index], x0, x1, x2, x3)
}

Object.defineProperty(proto, 'location', {
  get: function() {
    return this._locations[this._index]
  }
  , set: function(v) {
    if(v !== this._locations[this._index]) {
      this._locations[this._index] = v|0
      this._wrapper.program = null
    }
    return v|0
  }
})

//Adds a vector attribute to obj
function addVectorAttribute(
    gl
  , wrapper
  , index
  , locations
  , dimension
  , obj
  , name) {

  //Construct constant function
  var constFuncArgs = [ 'gl', 'v' ]
  var varNames = []
  for(var i=0; i<dimension; ++i) {
    constFuncArgs.push('x'+i)
    varNames.push('x'+i)
  }
  constFuncArgs.push(
    'if(x0.length===void 0){return gl.vertexAttrib' +
    dimension + 'f(v,' +
    varNames.join() +
    ')}else{return gl.vertexAttrib' +
    dimension +
    'fv(v,x0)}')
  var constFunc = Function.apply(null, constFuncArgs)

  //Create attribute wrapper
  var attr = new ShaderAttribute(
      gl
    , wrapper
    , index
    , locations
    , dimension
    , constFunc)

  //Create accessor
  Object.defineProperty(obj, name, {
    set: function(x) {
      gl.disableVertexAttribArray(locations[index])
      constFunc(gl, locations[index], x)
      return x
    }
    , get: function() {
      return attr
    }
    , enumerable: true
  })
}

function addMatrixAttribute(
    gl
  , wrapper
  , index
  , locations
  , dimension
  , obj
  , name) {

  var parts = new Array(dimension)
  var attrs = new Array(dimension)
  for(var i=0; i<dimension; ++i) {
    addVectorAttribute(
        gl
      , wrapper
      , index[i]
      , locations
      , dimension
      , parts
      , i)
    attrs[i] = parts[i]
  }

  Object.defineProperty(parts, 'location', {
    set: function(v) {
      if(Array.isArray(v)) {
        for(var i=0; i<dimension; ++i) {
          attrs[i].location = v[i]
        }
      } else {
        for(var i=0; i<dimension; ++i) {
          attrs[i].location = v + i
        }
      }
      return v
    }
    , get: function() {
      var result = new Array(dimension)
      for(var i=0; i<dimension; ++i) {
        result[i] = locations[index[i]]
      }
      return result
    }
    , enumerable: true
  })

  parts.pointer = function(type, normalized, stride, offset) {
    type       = type || gl.FLOAT
    normalized = !!normalized
    stride     = stride || (dimension * dimension)
    offset     = offset || 0
    for(var i=0; i<dimension; ++i) {
      var location = locations[index[i]]
      gl.vertexAttribPointer(
            location
          , dimension
          , type
          , normalized
          , stride
          , offset + i * dimension)
      gl.enableVertexAttribArray(location)
    }
  }

  var scratch = new Array(dimension)
  var vertexAttrib = gl['vertexAttrib' + dimension + 'fv']

  Object.defineProperty(obj, name, {
    set: function(x) {
      for(var i=0; i<dimension; ++i) {
        var loc = locations[index[i]]
        gl.disableVertexAttribArray(loc)
        if(Array.isArray(x[0])) {
          vertexAttrib.call(gl, loc, x[i])
        } else {
          for(var j=0; j<dimension; ++j) {
            scratch[j] = x[dimension*i + j]
          }
          vertexAttrib.call(gl, loc, scratch)
        }
      }
      return x
    }
    , get: function() {
      return parts
    }
    , enumerable: true
  })
}

//Create shims for attributes
function createAttributeWrapper(
    gl
  , wrapper
  , attributes
  , locations) {

  var obj = {}
  for(var i=0, n=attributes.length; i<n; ++i) {

    var a = attributes[i]
    var name = a.name
    var type = a.type
    var locs = a.locations

    switch(type) {
      case 'bool':
      case 'int':
      case 'float':
        addVectorAttribute(
            gl
          , wrapper
          , locs[0]
          , locations
          , 1
          , obj
          , name)
      break

      default:
        if(type.indexOf('vec') >= 0) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new GLError('', 'Invalid data type for attribute ' + name + ': ' + type)
          }
          addVectorAttribute(
              gl
            , wrapper
            , locs[0]
            , locations
            , d
            , obj
            , name)
        } else if(type.indexOf('mat') >= 0) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new GLError('', 'Invalid data type for attribute ' + name + ': ' + type)
          }
          addMatrixAttribute(
              gl
            , wrapper
            , locs
            , locations
            , d
            , obj
            , name)
        } else {
          throw new GLError('', 'Unknown data type for attribute ' + name + ': ' + type)
        }
      break
    }
  }
  return obj
}

},{"./GLError":295}],297:[function(_dereq_,module,exports){
'use strict'

var coallesceUniforms = _dereq_('./reflect')
var GLError = _dereq_("./GLError")

module.exports = createUniformWrapper

//Binds a function and returns a value
function identity(x) {
  var c = new Function('y', 'return function(){return y}')
  return c(x)
}

function makeVector(length, fill) {
  var result = new Array(length)
  for(var i=0; i<length; ++i) {
    result[i] = fill
  }
  return result
}

//Create shims for uniforms
function createUniformWrapper(gl, wrapper, uniforms, locations) {

  function makeGetter(index) {
    var proc = new Function(
        'gl'
      , 'wrapper'
      , 'locations'
      , 'return function(){return gl.getUniform(wrapper.program,locations[' + index + '])}')
    return proc(gl, wrapper, locations)
  }

  function makePropSetter(path, index, type) {
    switch(type) {
      case 'bool':
      case 'int':
      case 'sampler2D':
      case 'samplerCube':
        return 'gl.uniform1i(locations[' + index + '],obj' + path + ')'
      case 'float':
        return 'gl.uniform1f(locations[' + index + '],obj' + path + ')'
      default:
        var vidx = type.indexOf('vec')
        if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new GLError('', 'Invalid data type')
          }
          switch(type.charAt(0)) {
            case 'b':
            case 'i':
              return 'gl.uniform' + d + 'iv(locations[' + index + '],obj' + path + ')'
            case 'v':
              return 'gl.uniform' + d + 'fv(locations[' + index + '],obj' + path + ')'
            default:
              throw new GLError('', 'Unrecognized data type for vector ' + name + ': ' + type)
          }
        } else if(type.indexOf('mat') === 0 && type.length === 4) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new GLError('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type)
          }
          return 'gl.uniformMatrix' + d + 'fv(locations[' + index + '],false,obj' + path + ')'
        } else {
          throw new GLError('', 'Unknown uniform data type for ' + name + ': ' + type)
        }
      break
    }
  }

  function enumerateIndices(prefix, type) {
    if(typeof type !== 'object') {
      return [ [prefix, type] ]
    }
    var indices = []
    for(var id in type) {
      var prop = type[id]
      var tprefix = prefix
      if(parseInt(id) + '' === id) {
        tprefix += '[' + id + ']'
      } else {
        tprefix += '.' + id
      }
      if(typeof prop === 'object') {
        indices.push.apply(indices, enumerateIndices(tprefix, prop))
      } else {
        indices.push([tprefix, prop])
      }
    }
    return indices
  }

  function makeSetter(type) {
    var code = [ 'return function updateProperty(obj){' ]
    var indices = enumerateIndices('', type)
    for(var i=0; i<indices.length; ++i) {
      var item = indices[i]
      var path = item[0]
      var idx  = item[1]
      if(locations[idx]) {
        code.push(makePropSetter(path, idx, uniforms[idx].type))
      }
    }
    code.push('return obj}')
    var proc = new Function('gl', 'locations', code.join('\n'))
    return proc(gl, locations)
  }

  function defaultValue(type) {
    switch(type) {
      case 'bool':
        return false
      case 'int':
      case 'sampler2D':
      case 'samplerCube':
        return 0
      case 'float':
        return 0.0
      default:
        var vidx = type.indexOf('vec')
        if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new GLError('', 'Invalid data type')
          }
          if(type.charAt(0) === 'b') {
            return makeVector(d, false)
          }
          return makeVector(d, 0)
        } else if(type.indexOf('mat') === 0 && type.length === 4) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new GLError('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type)
          }
          return makeVector(d*d, 0)
        } else {
          throw new GLError('', 'Unknown uniform data type for ' + name + ': ' + type)
        }
      break
    }
  }

  function storeProperty(obj, prop, type) {
    if(typeof type === 'object') {
      var child = processObject(type)
      Object.defineProperty(obj, prop, {
        get: identity(child),
        set: makeSetter(type),
        enumerable: true,
        configurable: false
      })
    } else {
      if(locations[type]) {
        Object.defineProperty(obj, prop, {
          get: makeGetter(type),
          set: makeSetter(type),
          enumerable: true,
          configurable: false
        })
      } else {
        obj[prop] = defaultValue(uniforms[type].type)
      }
    }
  }

  function processObject(obj) {
    var result
    if(Array.isArray(obj)) {
      result = new Array(obj.length)
      for(var i=0; i<obj.length; ++i) {
        storeProperty(result, i, obj[i])
      }
    } else {
      result = {}
      for(var id in obj) {
        storeProperty(result, id, obj[id])
      }
    }
    return result
  }

  //Return data
  var coallesced = coallesceUniforms(uniforms, true)
  return {
    get: identity(processObject(coallesced)),
    set: makeSetter(coallesced),
    enumerable: true,
    configurable: true
  }
}

},{"./GLError":295,"./reflect":298}],298:[function(_dereq_,module,exports){
'use strict'

module.exports = makeReflectTypes

//Construct type info for reflection.
//
// This iterates over the flattened list of uniform type values and smashes them into a JSON object.
//
// The leaves of the resulting object are either indices or type strings representing primitive glslify types
function makeReflectTypes(uniforms, useIndex) {
  var obj = {}
  for(var i=0; i<uniforms.length; ++i) {
    var n = uniforms[i].name
    var parts = n.split(".")
    var o = obj
    for(var j=0; j<parts.length; ++j) {
      var x = parts[j].split("[")
      if(x.length > 1) {
        if(!(x[0] in o)) {
          o[x[0]] = []
        }
        o = o[x[0]]
        for(var k=1; k<x.length; ++k) {
          var y = parseInt(x[k])
          if(k<x.length-1 || j<parts.length-1) {
            if(!(y in o)) {
              if(k < x.length-1) {
                o[y] = []
              } else {
                o[y] = {}
              }
            }
            o = o[y]
          } else {
            if(useIndex) {
              o[y] = i
            } else {
              o[y] = uniforms[i].type
            }
          }
        }
      } else if(j < parts.length-1) {
        if(!(x[0] in o)) {
          o[x[0]] = {}
        }
        o = o[x[0]]
      } else {
        if(useIndex) {
          o[x[0]] = i
        } else {
          o[x[0]] = uniforms[i].type
        }
      }
    }
  }
  return obj
}
},{}],299:[function(_dereq_,module,exports){
'use strict'

exports.uniforms    = runtimeUniforms
exports.attributes  = runtimeAttributes

var GL_TO_GLSL_TYPES = {
  'FLOAT':       'float',
  'FLOAT_VEC2':  'vec2',
  'FLOAT_VEC3':  'vec3',
  'FLOAT_VEC4':  'vec4',
  'INT':         'int',
  'INT_VEC2':    'ivec2',
  'INT_VEC3':    'ivec3',
  'INT_VEC4':    'ivec4',
  'BOOL':        'bool',
  'BOOL_VEC2':   'bvec2',
  'BOOL_VEC3':   'bvec3',
  'BOOL_VEC4':   'bvec4',
  'FLOAT_MAT2':  'mat2',
  'FLOAT_MAT3':  'mat3',
  'FLOAT_MAT4':  'mat4',
  'SAMPLER_2D':  'sampler2D',
  'SAMPLER_CUBE':'samplerCube'
}

var GL_TABLE = null

function getType(gl, type) {
  if(!GL_TABLE) {
    var typeNames = Object.keys(GL_TO_GLSL_TYPES)
    GL_TABLE = {}
    for(var i=0; i<typeNames.length; ++i) {
      var tn = typeNames[i]
      GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]
    }
  }
  return GL_TABLE[type]
}

function runtimeUniforms(gl, program) {
  var numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS)
  var result = []
  for(var i=0; i<numUniforms; ++i) {
    var info = gl.getActiveUniform(program, i)
    if(info) {
      var type = getType(gl, info.type)
      if(info.size > 1) {
        for(var j=0; j<info.size; ++j) {
          result.push({
            name: info.name.replace('[0]', '[' + j + ']'),
            type: type
          })
        }
      } else {
        result.push({
          name: info.name,
          type: type
        })
      }
    }
  }
  return result
}

function runtimeAttributes(gl, program) {
  var numAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES)
  var result = []
  for(var i=0; i<numAttributes; ++i) {
    var info = gl.getActiveAttrib(program, i)
    if(info) {
      result.push({
        name: info.name,
        type: getType(gl, info.type)
      })
    }
  }
  return result
}

},{}],300:[function(_dereq_,module,exports){
'use strict'

exports.shader   = getShaderReference
exports.program  = createProgram

var GLError = _dereq_("./GLError")
var formatCompilerError = _dereq_('gl-format-compiler-error');

var weakMap = typeof WeakMap === 'undefined' ? _dereq_('weakmap-shim') : WeakMap
var CACHE = new weakMap()

var SHADER_COUNTER = 0

function ShaderReference(id, src, type, shader, programs, count, cache) {
  this.id       = id
  this.src      = src
  this.type     = type
  this.shader   = shader
  this.count    = count
  this.programs = []
  this.cache    = cache
}

ShaderReference.prototype.dispose = function() {
  if(--this.count === 0) {
    var cache    = this.cache
    var gl       = cache.gl

    //Remove program references
    var programs = this.programs
    for(var i=0, n=programs.length; i<n; ++i) {
      var p = cache.programs[programs[i]]
      if(p) {
        delete cache.programs[i]
        gl.deleteProgram(p)
      }
    }

    //Remove shader reference
    gl.deleteShader(this.shader)
    delete cache.shaders[(this.type === gl.FRAGMENT_SHADER)|0][this.src]
  }
}

function ContextCache(gl) {
  this.gl       = gl
  this.shaders  = [{}, {}]
  this.programs = {}
}

var proto = ContextCache.prototype

function compileShader(gl, type, src) {
  var shader = gl.createShader(type)
  gl.shaderSource(shader, src)
  gl.compileShader(shader)
  if(!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
    var errLog = gl.getShaderInfoLog(shader)
    try {
        var fmt = formatCompilerError(errLog, src, type);
    } catch (e){
        console.warn('Failed to format compiler error: ' + e);
        throw new GLError(errLog, 'Error compiling shader:\n' + errLog)
    }
    throw new GLError(errLog, fmt.short, fmt.long)
  }
  return shader
}

proto.getShaderReference = function(type, src) {
  var gl      = this.gl
  var shaders = this.shaders[(type === gl.FRAGMENT_SHADER)|0]
  var shader  = shaders[src]
  if(!shader || !gl.isShader(shader.shader)) {
    var shaderObj = compileShader(gl, type, src)
    shader = shaders[src] = new ShaderReference(
      SHADER_COUNTER++,
      src,
      type,
      shaderObj,
      [],
      1,
      this)
  } else {
    shader.count += 1
  }
  return shader
}

function linkProgram(gl, vshader, fshader, attribs, locations) {
  var program = gl.createProgram()
  gl.attachShader(program, vshader)
  gl.attachShader(program, fshader)
  for(var i=0; i<attribs.length; ++i) {
    gl.bindAttribLocation(program, locations[i], attribs[i])
  }
  gl.linkProgram(program)
  if(!gl.getProgramParameter(program, gl.LINK_STATUS)) {
    var errLog = gl.getProgramInfoLog(program)
    throw new GLError(errLog, 'Error linking program: ' + errLog)
  }
  return program
}

proto.getProgram = function(vref, fref, attribs, locations) {
  var token = [vref.id, fref.id, attribs.join(':'), locations.join(':')].join('@')
  var prog  = this.programs[token]
  if(!prog || !this.gl.isProgram(prog)) {
    this.programs[token] = prog = linkProgram(
      this.gl,
      vref.shader,
      fref.shader,
      attribs,
      locations)
    vref.programs.push(token)
    fref.programs.push(token)
  }
  return prog
}

function getCache(gl) {
  var ctxCache = CACHE.get(gl)
  if(!ctxCache) {
    ctxCache = new ContextCache(gl)
    CACHE.set(gl, ctxCache)
  }
  return ctxCache
}

function getShaderReference(gl, type, src) {
  return getCache(gl).getShaderReference(type, src)
}

function createProgram(gl, vref, fref, attribs, locations) {
  return getCache(gl).getProgram(vref, fref, attribs, locations)
}

},{"./GLError":295,"gl-format-compiler-error":243,"weakmap-shim":536}],301:[function(_dereq_,module,exports){
'use strict'

module.exports = createSpikes2D

function GLSpikes2D(plot) {
  this.plot = plot
  this.enable = [true, true, false, false]
  this.width  = [1, 1, 1, 1]
  this.color  = [[0,0,0,1],
                 [0,0,0,1],
                 [0,0,0,1],
                 [0,0,0,1]]
  this.center = [Infinity, Infinity]
}

var proto = GLSpikes2D.prototype

proto.update = function(options) {
  options = options || {}
  this.enable = (options.enable || [true,true,false,false]).slice()
  this.width  = (options.width || [1,1,1,1]).slice()
  this.color  = (options.color || [
                  [0,0,0,1],
                  [0,0,0,1],
                  [0,0,0,1],
                  [0,0,0,1]]).map(function(x) { return x.slice() })
  this.center = (options.center || [Infinity,Infinity]).slice()
  this.plot.setOverlayDirty()
}

proto.draw = function() {
  var spikeEnable = this.enable
  var spikeWidth  = this.width
  var spikeColor  = this.color
  var spikeCenter = this.center
  var plot        = this.plot
  var line        = plot.line

  var dataBox     = plot.dataBox
  var viewPixels  = plot.viewBox

  line.bind()

  if(dataBox[0] <= spikeCenter[0] && spikeCenter[0] <= dataBox[2] &&
     dataBox[1] <= spikeCenter[1] && spikeCenter[1] <= dataBox[3]) {

    var centerX = viewPixels[0] + (spikeCenter[0] - dataBox[0]) / (dataBox[2] - dataBox[0]) * (viewPixels[2] - viewPixels[0])
    var centerY = viewPixels[1] + (spikeCenter[1] - dataBox[1]) / (dataBox[3] - dataBox[1]) * (viewPixels[3] - viewPixels[1])

    if(spikeEnable[0]) {
     line.drawLine(
       centerX, centerY,
       viewPixels[0], centerY,
       spikeWidth[0], spikeColor[0])
    }
    if(spikeEnable[1]) {
     line.drawLine(
       centerX, centerY,
       centerX, viewPixels[1],
       spikeWidth[1], spikeColor[1])
    }
    if(spikeEnable[2]) {
      line.drawLine(
        centerX, centerY,
        viewPixels[2], centerY,
        spikeWidth[2], spikeColor[2])
    }
    if(spikeEnable[3]) {
      line.drawLine(
        centerX, centerY,
        centerX, viewPixels[3],
        spikeWidth[3], spikeColor[3])
    }
  }
}

proto.dispose = function() {
  this.plot.removeOverlay(this)
}

function createSpikes2D(plot, options) {
  var spikes = new GLSpikes2D(plot)
  spikes.update(options)
  plot.addOverlay(spikes)
  return spikes
}

},{}],302:[function(_dereq_,module,exports){
'use strict'

var glslify      = _dereq_('glslify')
var createShader = _dereq_('gl-shader')

var vertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, color;\nattribute float weight;\n\nuniform mat4 model, view, projection;\nuniform vec3 coordinates[3];\nuniform vec4 colors[3];\nuniform vec2 screenShape;\nuniform float lineWidth;\n\nvarying vec4 fragColor;\n\nvoid main() {\n  vec3 vertexPosition = mix(coordinates[0],\n    mix(coordinates[2], coordinates[1], 0.5 * (position + 1.0)), abs(position));\n\n  vec4 clipPos = projection * view * model * vec4(vertexPosition, 1.0);\n  vec2 clipOffset = (projection * view * model * vec4(color, 0.0)).xy;\n  vec2 delta = weight * clipOffset * screenShape;\n  vec2 lineOffset = normalize(vec2(delta.y, -delta.x)) / screenShape;\n\n  gl_Position   = vec4(clipPos.xy + clipPos.w * 0.5 * lineWidth * lineOffset, clipPos.z, clipPos.w);\n  fragColor     = color.x * colors[0] + color.y * colors[1] + color.z * colors[2];\n}\n"])
var fragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n  gl_FragColor = fragColor;\n}"])

module.exports = function(gl) {
  return createShader(gl, vertSrc, fragSrc, null, [
    {name: 'position', type: 'vec3'},
    {name: 'color', type: 'vec3'},
    {name: 'weight', type: 'float'}
  ])
}

},{"gl-shader":294,"glslify":398}],303:[function(_dereq_,module,exports){
'use strict'

var createBuffer = _dereq_('gl-buffer')
var createVAO = _dereq_('gl-vao')
var createShader = _dereq_('./shaders/index')

module.exports = createSpikes

var identity = [1,0,0,0,
                0,1,0,0,
                0,0,1,0,
                0,0,0,1]

function AxisSpikes(gl, buffer, vao, shader) {
  this.gl         = gl
  this.buffer     = buffer
  this.vao        = vao
  this.shader     = shader
  this.pixelRatio = 1
  this.bounds     = [[-1000,-1000,-1000], [1000,1000,1000]]
  this.position   = [0,0,0]
  this.lineWidth  = [2,2,2]
  this.colors     = [[0,0,0,1], [0,0,0,1], [0,0,0,1]]
  this.enabled    = [true,true,true]
  this.drawSides  = [true,true,true]
  this.axes       = null
}

var proto = AxisSpikes.prototype

var OUTER_FACE = [0,0,0]
var INNER_FACE = [0,0,0]

var SHAPE = [0,0]

proto.isTransparent = function() {
  return false
}

proto.drawTransparent = function(camera) {}

proto.draw = function(camera) {
  var gl = this.gl
  var vao = this.vao
  var shader = this.shader

  vao.bind()
  shader.bind()

  var model      = camera.model || identity
  var view       = camera.view || identity
  var projection = camera.projection || identity

  var axis
  if(this.axes) {
    axis = this.axes.lastCubeProps.axis
  }

  var outerFace = OUTER_FACE
  var innerFace = INNER_FACE
  for(var i=0; i<3; ++i) {
    if(axis && axis[i] < 0) {
      outerFace[i] = this.bounds[0][i]
      innerFace[i] = this.bounds[1][i]
    } else {
      outerFace[i] = this.bounds[1][i]
      innerFace[i] = this.bounds[0][i]
    }
  }

  SHAPE[0] = gl.drawingBufferWidth
  SHAPE[1] = gl.drawingBufferHeight

  shader.uniforms.model       = model
  shader.uniforms.view        = view
  shader.uniforms.projection  = projection
  shader.uniforms.coordinates = [this.position, outerFace, innerFace]
  shader.uniforms.colors      = this.colors
  shader.uniforms.screenShape = SHAPE

  for(var i=0; i<3; ++i) {
    shader.uniforms.lineWidth = this.lineWidth[i] * this.pixelRatio
    if(this.enabled[i]) {
      vao.draw(gl.TRIANGLES, 6, 6*i)
      if(this.drawSides[i]) {
        vao.draw(gl.TRIANGLES, 12, 18+12*i)
      }
    }
  }

  vao.unbind()
}

proto.update = function(options) {
  if(!options) {
    return
  }
  if("bounds" in options) {
    this.bounds = options.bounds
  }
  if("position" in options) {
    this.position = options.position
  }
  if("lineWidth" in options) {
    this.lineWidth = options.lineWidth
  }
  if("colors" in options) {
    this.colors = options.colors
  }
  if("enabled" in options) {
    this.enabled = options.enabled
  }
  if("drawSides" in options) {
    this.drawSides = options.drawSides
  }
}

proto.dispose = function() {
  this.vao.dispose()
  this.buffer.dispose()
  this.shader.dispose()
}



function createSpikes(gl, options) {
  //Create buffers
  var data = [ ]

  function line(x,y,z,i,l,h) {
    var row = [x,y,z,  0,0,0,  1]
    row[i+3] = 1
    row[i] = l
    data.push.apply(data, row)
    row[6] = -1
    data.push.apply(data, row)
    row[i] = h
    data.push.apply(data, row)
    data.push.apply(data, row)
    row[6] = 1
    data.push.apply(data, row)
    row[i] = l
    data.push.apply(data, row)
  }

  line(0,0,0, 0, 0, 1)
  line(0,0,0, 1, 0, 1)
  line(0,0,0, 2, 0, 1)

  line(1,0,0,  1,  -1,1)
  line(1,0,0,  2,  -1,1)

  line(0,1,0,  0,  -1,1)
  line(0,1,0,  2,  -1,1)

  line(0,0,1,  0,  -1,1)
  line(0,0,1,  1,  -1,1)

  var buffer = createBuffer(gl, data)
  var vao = createVAO(gl, [{
    type: gl.FLOAT,
    buffer: buffer,
    size: 3,
    offset: 0,
    stride: 28
  }, {
    type: gl.FLOAT,
    buffer: buffer,
    size: 3,
    offset: 12,
    stride: 28
  }, {
    type: gl.FLOAT,
    buffer: buffer,
    size: 1,
    offset: 24,
    stride: 28
  }])

  //Create shader
  var shader = createShader(gl)
  shader.attributes.position.location = 0
  shader.attributes.color.location = 1
  shader.attributes.weight.location = 2

  //Create spike object
  var spikes = new AxisSpikes(gl, buffer, vao, shader)

  //Set parameters
  spikes.update(options)

  //Return resulting object
  return spikes
}

},{"./shaders/index":302,"gl-buffer":234,"gl-vao":316}],304:[function(_dereq_,module,exports){
var glslify       = _dereq_('glslify')

var triVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nvec3 getOrthogonalVector(vec3 v) {\n  // Return up-vector for only-z vector.\n  // Return ax + by + cz = 0, a point that lies on the plane that has v as a normal and that isn't (0,0,0).\n  // From the above if-statement we have ||a|| > 0  U  ||b|| > 0.\n  // Assign z = 0, x = -b, y = a:\n  // a*-b + b*a + c*0 = -ba + ba + 0 = 0\n  if (v.x*v.x > v.z*v.z || v.y*v.y > v.z*v.z) {\n    return normalize(vec3(-v.y, v.x, 0.0));\n  } else {\n    return normalize(vec3(0.0, v.z, -v.y));\n  }\n}\n\n// Calculate the tube vertex and normal at the given index.\n//\n// The returned vertex is for a tube ring with its center at origin, radius of length(d), pointing in the direction of d.\n//\n// Each tube segment is made up of a ring of vertices.\n// These vertices are used to make up the triangles of the tube by connecting them together in the vertex array.\n// The indexes of tube segments run from 0 to 8.\n//\nvec3 getTubePosition(vec3 d, float index, out vec3 normal) {\n  float segmentCount = 8.0;\n\n  float angle = 2.0 * 3.14159 * (index / segmentCount);\n\n  vec3 u = getOrthogonalVector(d);\n  vec3 v = normalize(cross(u, d));\n\n  vec3 x = u * cos(angle) * length(d);\n  vec3 y = v * sin(angle) * length(d);\n  vec3 v3 = x + y;\n\n  normal = normalize(v3);\n\n  return v3;\n}\n\nattribute vec4 vector;\nattribute vec4 color, position;\nattribute vec2 uv;\nuniform float vectorScale;\nuniform float tubeScale;\n\nuniform mat4 model\n           , view\n           , projection\n           , inverseModel;\nuniform vec3 eyePosition\n           , lightPosition;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data\n           , f_position;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  // Scale the vector magnitude to stay constant with\n  // model & view changes.\n  vec3 normal;\n  vec3 XYZ = getTubePosition(mat3(model) * (tubeScale * vector.w * normalize(vector.xyz)), position.w, normal);\n  vec4 tubePosition = model * vec4(position.xyz, 1.0) + vec4(XYZ, 0.0);\n\n  //Lighting geometry parameters\n  vec4 cameraCoordinate = view * tubePosition;\n  cameraCoordinate.xyz /= cameraCoordinate.w;\n  f_lightDirection = lightPosition - cameraCoordinate.xyz;\n  f_eyeDirection   = eyePosition - cameraCoordinate.xyz;\n  f_normal = normalize((vec4(normal,0.0) * inverseModel).xyz);\n\n  // vec4 m_position  = model * vec4(tubePosition, 1.0);\n  vec4 t_position  = view * tubePosition;\n  gl_Position      = projection * t_position;\n\n  f_color          = color;\n  f_data           = tubePosition.xyz;\n  f_position       = position.xyz;\n  f_uv             = uv;\n}\n"])
var triFragSrc = glslify(["#extension GL_OES_standard_derivatives : enable\n\nprecision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution(float x, float roughness) {\n  float NdotH = max(x, 0.0001);\n  float cos2Alpha = NdotH * NdotH;\n  float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n  float roughness2 = roughness * roughness;\n  float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n  return exp(tan2Alpha / roughness2) / denom;\n}\n\nfloat cookTorranceSpecular(\n  vec3 lightDirection,\n  vec3 viewDirection,\n  vec3 surfaceNormal,\n  float roughness,\n  float fresnel) {\n\n  float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n  float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n  //Half angle vector\n  vec3 H = normalize(lightDirection + viewDirection);\n\n  //Geometric term\n  float NdotH = max(dot(surfaceNormal, H), 0.0);\n  float VdotH = max(dot(viewDirection, H), 0.000001);\n  float LdotH = max(dot(lightDirection, H), 0.000001);\n  float G1 = (2.0 * NdotH * VdotN) / VdotH;\n  float G2 = (2.0 * NdotH * LdotN) / LdotH;\n  float G = min(1.0, min(G1, G2));\n  \n  //Distribution term\n  float D = beckmannDistribution(NdotH, roughness);\n\n  //Fresnel term\n  float F = pow(1.0 - VdotN, fresnel);\n\n  //Multiply terms and done\n  return  G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n            , fresnel\n            , kambient\n            , kdiffuse\n            , kspecular\n            , opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data\n           , f_position;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n  vec3 N = normalize(f_normal);\n  vec3 L = normalize(f_lightDirection);\n  vec3 V = normalize(f_eyeDirection);\n\n  if(gl_FrontFacing) {\n    N = -N;\n  }\n\n  float specular = min(1.0, max(0.0, cookTorranceSpecular(L, V, N, roughness, fresnel)));\n  float diffuse  = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n  vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n  vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular,  1.0);\n\n  gl_FragColor = litColor * opacity;\n}\n"])
var pickVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nvec3 getOrthogonalVector(vec3 v) {\n  // Return up-vector for only-z vector.\n  // Return ax + by + cz = 0, a point that lies on the plane that has v as a normal and that isn't (0,0,0).\n  // From the above if-statement we have ||a|| > 0  U  ||b|| > 0.\n  // Assign z = 0, x = -b, y = a:\n  // a*-b + b*a + c*0 = -ba + ba + 0 = 0\n  if (v.x*v.x > v.z*v.z || v.y*v.y > v.z*v.z) {\n    return normalize(vec3(-v.y, v.x, 0.0));\n  } else {\n    return normalize(vec3(0.0, v.z, -v.y));\n  }\n}\n\n// Calculate the tube vertex and normal at the given index.\n//\n// The returned vertex is for a tube ring with its center at origin, radius of length(d), pointing in the direction of d.\n//\n// Each tube segment is made up of a ring of vertices.\n// These vertices are used to make up the triangles of the tube by connecting them together in the vertex array.\n// The indexes of tube segments run from 0 to 8.\n//\nvec3 getTubePosition(vec3 d, float index, out vec3 normal) {\n  float segmentCount = 8.0;\n\n  float angle = 2.0 * 3.14159 * (index / segmentCount);\n\n  vec3 u = getOrthogonalVector(d);\n  vec3 v = normalize(cross(u, d));\n\n  vec3 x = u * cos(angle) * length(d);\n  vec3 y = v * sin(angle) * length(d);\n  vec3 v3 = x + y;\n\n  normal = normalize(v3);\n\n  return v3;\n}\n\nattribute vec4 vector;\nattribute vec4 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform float tubeScale;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  vec3 normal;\n  vec3 XYZ = getTubePosition(mat3(model) * (tubeScale * vector.w * normalize(vector.xyz)), position.w, normal);\n  vec4 tubePosition = model * vec4(position.xyz, 1.0) + vec4(XYZ, 0.0);\n\n  gl_Position = projection * view * tubePosition;\n  f_id        = id;\n  f_position  = position.xyz;\n}\n"])
var pickFragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3  clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n\n  gl_FragColor = vec4(pickId, f_id.xyz);\n}"])

exports.meshShader = {
  vertex:   triVertSrc,
  fragment: triFragSrc,
  attributes: [
    {name: 'position', type: 'vec4'},
    {name: 'normal', type: 'vec3'},
    {name: 'color', type: 'vec4'},
    {name: 'uv', type: 'vec2'},
    {name: 'vector', type: 'vec4'}
  ]
}
exports.pickShader = {
  vertex:   pickVertSrc,
  fragment: pickFragSrc,
  attributes: [
    {name: 'position', type: 'vec4'},
    {name: 'id', type: 'vec4'},
    {name: 'vector', type: 'vec4'}
  ]
}

},{"glslify":398}],305:[function(_dereq_,module,exports){
'use strict'

var DEFAULT_VERTEX_NORMALS_EPSILON = 1e-6; // may be too large if triangles are very small
var DEFAULT_FACE_NORMALS_EPSILON = 1e-6;

var createShader  = _dereq_('gl-shader')
var createBuffer  = _dereq_('gl-buffer')
var createVAO     = _dereq_('gl-vao')
var createTexture = _dereq_('gl-texture2d')
var normals       = _dereq_('normals')
var multiply      = _dereq_('gl-mat4/multiply')
var invert        = _dereq_('gl-mat4/invert')
var ndarray       = _dereq_('ndarray')
var colormap      = _dereq_('colormap')
var getContour    = _dereq_('simplicial-complex-contour')
var pool          = _dereq_('typedarray-pool')
var shaders       = _dereq_('./shaders')

var meshShader    = shaders.meshShader
var pickShader    = shaders.pickShader

var IDENTITY = [
  1,0,0,0,
  0,1,0,0,
  0,0,1,0,
  0,0,0,1]

function SimplicialMesh(gl
  , texture
  , triShader
  , pickShader
  , trianglePositions
  , triangleVectors
  , triangleIds
  , triangleColors
  , triangleUVs
  , triangleNormals
  , triangleVAO
  , edgePositions
  , edgeIds
  , edgeColors
  , edgeUVs
  , edgeVAO
  , pointPositions
  , pointIds
  , pointColors
  , pointUVs
  , pointSizes
  , pointVAO
  , contourPositions
  , contourVAO) {

  this.gl                = gl
  this.cells             = []
  this.positions         = []
  this.intensity         = []
  this.texture           = texture
  this.dirty             = true

  this.triShader         = triShader
  this.pickShader        = pickShader

  this.trianglePositions = trianglePositions
  this.triangleVectors   = triangleVectors
  this.triangleColors    = triangleColors
  this.triangleNormals   = triangleNormals
  this.triangleUVs       = triangleUVs
  this.triangleIds       = triangleIds
  this.triangleVAO       = triangleVAO
  this.triangleCount     = 0

  this.lineWidth         = 1
  this.edgePositions     = edgePositions
  this.edgeColors        = edgeColors
  this.edgeUVs           = edgeUVs
  this.edgeIds           = edgeIds
  this.edgeVAO           = edgeVAO
  this.edgeCount         = 0

  this.pointPositions    = pointPositions
  this.pointColors       = pointColors
  this.pointUVs          = pointUVs
  this.pointSizes        = pointSizes
  this.pointIds          = pointIds
  this.pointVAO          = pointVAO
  this.pointCount        = 0

  this.contourLineWidth  = 1
  this.contourPositions  = contourPositions
  this.contourVAO        = contourVAO
  this.contourCount      = 0
  this.contourColor      = [0,0,0]
  this.contourEnable     = false

  this.pickId            = 1
  this.bounds            = [
    [ Infinity, Infinity, Infinity],
    [-Infinity,-Infinity,-Infinity] ]
  this.clipBounds        = [
    [-Infinity,-Infinity,-Infinity],
    [ Infinity, Infinity, Infinity] ]

  this.lightPosition = [1e5, 1e5, 0]
  this.ambientLight  = 0.8
  this.diffuseLight  = 0.8
  this.specularLight = 2.0
  this.roughness     = 0.5
  this.fresnel       = 1.5

  this.opacity       = 1.0

  this.tubeScale     = 1.0

  this._model       = IDENTITY
  this._view        = IDENTITY
  this._projection  = IDENTITY
  this._resolution  = [1,1]
  this.pixelRatio   = 1
}

var proto = SimplicialMesh.prototype

proto.isOpaque = function() {
  return this.opacity >= 1
}

proto.isTransparent = function() {
  return this.opacity < 1
}

proto.pickSlots = 1

proto.setPickBase = function(id) {
  this.pickId = id
}

function genColormap(param) {
  var colors = colormap({
      colormap: param
    , nshades:  256
    , format:  'rgba'
  })

  var result = new Uint8Array(256*4)
  for(var i=0; i<256; ++i) {
    var c = colors[i]
    for(var j=0; j<3; ++j) {
      result[4*i+j] = c[j]
    }
    result[4*i+3] = c[3]*255
  }

  return ndarray(result, [256,256,4], [4,0,1])
}

function unpackIntensity(cells, numVerts, cellIntensity) {
  var result = new Array(numVerts)
  for(var i=0; i<numVerts; ++i) {
    result[i] = 0
  }
  var numCells = cells.length
  for(var i=0; i<numCells; ++i) {
    var c = cells[i]
    for(var j=0; j<c.length; ++j) {
      result[c[j]] = cellIntensity[i]
    }
  }
  return result
}

function takeZComponent(array) {
  var n = array.length
  var result = new Array(n)
  for(var i=0; i<n; ++i) {
    result[i] = array[i][2]
  }
  return result
}

proto.highlight = function(selection) {
  if(!selection || !this.contourEnable) {
    this.contourCount = 0
    return
  }
  var level = getContour(this.cells, this.intensity, selection.intensity)
  var cells         = level.cells
  var vertexIds     = level.vertexIds
  var vertexWeights = level.vertexWeights
  var numCells = cells.length
  var result = pool.mallocFloat32(2 * 3 * numCells)
  var ptr = 0
  for(var i=0; i<numCells; ++i) {
    var c = cells[i]
    for(var j=0; j<2; ++j) {
      var v = c[0]
      if(c.length === 2) {
        v = c[j]
      }
      var a = vertexIds[v][0]
      var b = vertexIds[v][1]
      var w = vertexWeights[v]
      var wi = 1.0 - w
      var pa = this.positions[a]
      var pb = this.positions[b]
      for(var k=0; k<3; ++k) {
        result[ptr++] = w * pa[k] + wi * pb[k]
      }
    }
  }
  this.contourCount = (ptr / 3)|0
  this.contourPositions.update(result.subarray(0, ptr))
  pool.free(result)
}

proto.update = function(params) {
  params = params || {}
  var gl = this.gl

  this.dirty = true

  if('contourEnable' in params) {
    this.contourEnable = params.contourEnable
  }
  if('contourColor' in params) {
    this.contourColor = params.contourColor
  }
  if('lineWidth' in params) {
    this.lineWidth = params.lineWidth
  }
  if('lightPosition' in params) {
    this.lightPosition = params.lightPosition
  }
  if('opacity' in params) {
    this.opacity = params.opacity
  }
  if('ambient' in params) {
    this.ambientLight  = params.ambient
  }
  if('diffuse' in params) {
    this.diffuseLight = params.diffuse
  }
  if('specular' in params) {
    this.specularLight = params.specular
  }
  if('roughness' in params) {
    this.roughness = params.roughness
  }
  if('fresnel' in params) {
    this.fresnel = params.fresnel
  }

  if(params.texture) {
    this.texture.dispose()
    this.texture = createTexture(gl, params.texture)
  } else if (params.colormap) {
    this.texture.shape = [256,256]
    this.texture.minFilter = gl.LINEAR_MIPMAP_LINEAR
    this.texture.magFilter = gl.LINEAR
    this.texture.setPixels(genColormap(params.colormap))
    this.texture.generateMipmap()
  }

  var cells = params.cells
  var positions = params.positions
  var vectors = params.vectors

  if(!positions || !cells || !vectors) {
    return
  }

  if (params.tubeScale !== undefined) {
    this.tubeScale = params.tubeScale;
  }

  var tPos = []
  var tVec = []
  var tCol = []
  var tNor = []
  var tUVs = []
  var tIds = []

  var ePos = []
  var eCol = []
  var eUVs = []
  var eIds = []

  var pPos = []
  var pCol = []
  var pUVs = []
  var pSiz = []
  var pIds = []

  //Save geometry data for picking calculations
  this.cells     = cells
  this.positions = positions
  this.vectors   = vectors

  //Compute normals
  var vertexNormals = params.vertexNormals
  var cellNormals   = params.cellNormals
  var vertexNormalsEpsilon = params.vertexNormalsEpsilon === void(0) ? DEFAULT_VERTEX_NORMALS_EPSILON : params.vertexNormalsEpsilon
  var faceNormalsEpsilon = params.faceNormalsEpsilon === void(0) ? DEFAULT_FACE_NORMALS_EPSILON : params.faceNormalsEpsilon
  if(params.useFacetNormals && !cellNormals) {
    cellNormals = normals.faceNormals(cells, positions, faceNormalsEpsilon)
  }
  if(!cellNormals && !vertexNormals) {
    vertexNormals = normals.vertexNormals(cells, positions, vertexNormalsEpsilon)
  }

  //Compute colors
  var vertexColors    = params.vertexColors
  var cellColors      = params.cellColors
  var meshColor       = params.meshColor || [1,1,1,1]

  //UVs
  var vertexUVs       = params.vertexUVs
  var vertexIntensity = params.vertexIntensity
  var cellUVs         = params.cellUVs
  var cellIntensity   = params.cellIntensity

  var intensityLo     = Infinity
  var intensityHi     = -Infinity
  if(!vertexUVs && !cellUVs) {
    if(vertexIntensity) {
      if(params.vertexIntensityBounds) {
        intensityLo = +params.vertexIntensityBounds[0]
        intensityHi = +params.vertexIntensityBounds[1]
      } else {
        for(var i=0; i<vertexIntensity.length; ++i) {
          var f = vertexIntensity[i]
          intensityLo = Math.min(intensityLo, f)
          intensityHi = Math.max(intensityHi, f)
        }
      }
    } else if(cellIntensity) {
      for(var i=0; i<cellIntensity.length; ++i) {
        var f = cellIntensity[i]
        intensityLo = Math.min(intensityLo, f)
        intensityHi = Math.max(intensityHi, f)
      }
    } else {
      for(var i=0; i<positions.length; ++i) {
        var f = positions[i][2]
        intensityLo = Math.min(intensityLo, f)
        intensityHi = Math.max(intensityHi, f)
      }
    }
  }

  if(vertexIntensity) {
    this.intensity = vertexIntensity
  } else if(cellIntensity) {
    this.intensity = unpackIntensity(cells, positions.length, cellIntensity)
  } else {
    this.intensity = takeZComponent(positions)
  }

  //Point size
  var pointSizes      = params.pointSizes
  var meshPointSize   = params.pointSize || 1.0

  //Update bounds
  this.bounds       = [[Infinity,Infinity,Infinity], [-Infinity,-Infinity,-Infinity]]
  for(var i=0; i<positions.length; ++i) {
    var p = positions[i]
    for(var j=0; j<3; ++j) {
      if(isNaN(p[j]) || !isFinite(p[j])) {
        continue
      }
      this.bounds[0][j] = Math.min(this.bounds[0][j], p[j])
      this.bounds[1][j] = Math.max(this.bounds[1][j], p[j])
    }
  }

  //Pack cells into buffers
  var triangleCount = 0
  var edgeCount = 0
  var pointCount = 0

fill_loop:
  for(var i=0; i<cells.length; ++i) {
    var cell = cells[i]
    switch(cell.length) {
      case 1:

        var v = cell[0]
        var p = positions[v]

        //Check NaNs
        for(var j=0; j<3; ++j) {
          if(isNaN(p[j]) || !isFinite(p[j])) {
            continue fill_loop
          }
        }

        pPos.push(p[0], p[1], p[2], p[3])

        var c
        if(vertexColors) {
          c = vertexColors[v]
        } else if(cellColors) {
          c = cellColors[i]
        } else {
          c = meshColor
        }
        if(c.length === 3) {
          pCol.push(c[0], c[1], c[2], 1)
        } else {
          pCol.push(c[0], c[1], c[2], c[3])
        }

        var uv
        if(vertexUVs) {
          uv = vertexUVs[v]
        } else if(vertexIntensity) {
          uv = [
            (vertexIntensity[v] - intensityLo) /
            (intensityHi - intensityLo), 0]
        } else if(cellUVs) {
          uv = cellUVs[i]
        } else if(cellIntensity) {
          uv = [
            (cellIntensity[i] - intensityLo) /
            (intensityHi - intensityLo), 0]
        } else {
          uv = [
            (p[2] - intensityLo) /
            (intensityHi - intensityLo), 0]
        }
        pUVs.push(uv[0], uv[1])

        if(pointSizes) {
          pSiz.push(pointSizes[v])
        } else {
          pSiz.push(meshPointSize)
        }

        pIds.push(i)

        pointCount += 1
      break

      case 2:

        //Check NaNs
        for(var j=0; j<2; ++j) {
          var v = cell[j]
          var p = positions[v]
          for(var k=0; k<3; ++k) {
            if(isNaN(p[k]) || !isFinite(p[k])) {
              continue fill_loop
            }
          }
        }

        for(var j=0; j<2; ++j) {
          var v = cell[j]
          var p = positions[v]

          ePos.push(p[0], p[1], p[2])

          var c
          if(vertexColors) {
            c = vertexColors[v]
          } else if(cellColors) {
            c = cellColors[i]
          } else {
            c = meshColor
          }
          if(c.length === 3) {
            eCol.push(c[0], c[1], c[2], 1)
          } else {
            eCol.push(c[0], c[1], c[2], c[3])
          }

          var uv
          if(vertexUVs) {
            uv = vertexUVs[v]
          } else if(vertexIntensity) {
            uv = [
              (vertexIntensity[v] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else if(cellUVs) {
            uv = cellUVs[i]
          } else if(cellIntensity) {
            uv = [
              (cellIntensity[i] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else {
            uv = [
              (p[2] - intensityLo) /
              (intensityHi - intensityLo), 0]
          }
          eUVs.push(uv[0], uv[1])

          eIds.push(i)
        }
        edgeCount += 1
      break

      case 3:
        //Check NaNs
        for(var j=0; j<3; ++j) {
          var v = cell[j]
          var p = positions[v]
          for(var k=0; k<3; ++k) {
            if(isNaN(p[k]) || !isFinite(p[k])) {
              continue fill_loop
            }
          }
        }

        for(var j=0; j<3; ++j) {
          var v = cell[2 - j]

          var p = positions[v]
          tPos.push(p[0], p[1], p[2], p[3])

          var w = vectors[v]
          tVec.push(w[0], w[1], w[2], w[3]);

          var c
          if(vertexColors) {
            c = vertexColors[v]
          } else if(cellColors) {
            c = cellColors[i]
          } else {
            c = meshColor
          }
          if(c.length === 3) {
            tCol.push(c[0], c[1], c[2], 1)
          } else {
            tCol.push(c[0], c[1], c[2], c[3])
          }

          var uv
          if(vertexUVs) {
            uv = vertexUVs[v]
          } else if(vertexIntensity) {
            uv = [
              (vertexIntensity[v] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else if(cellUVs) {
            uv = cellUVs[i]
          } else if(cellIntensity) {
            uv = [
              (cellIntensity[i] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else {
            uv = [
              (p[2] - intensityLo) /
              (intensityHi - intensityLo), 0]
          }
          tUVs.push(uv[0], uv[1])

          var q
          if(vertexNormals) {
            q = vertexNormals[v]
          } else {
            q = cellNormals[i]
          }
          tNor.push(q[0], q[1], q[2])

          tIds.push(i)
        }
        triangleCount += 1
      break

      default:
      break
    }
  }

  this.pointCount     = pointCount
  this.edgeCount      = edgeCount
  this.triangleCount  = triangleCount

  this.pointPositions.update(pPos)
  this.pointColors.update(pCol)
  this.pointUVs.update(pUVs)
  this.pointSizes.update(pSiz)
  this.pointIds.update(new Uint32Array(pIds))

  this.edgePositions.update(ePos)
  this.edgeColors.update(eCol)
  this.edgeUVs.update(eUVs)
  this.edgeIds.update(new Uint32Array(eIds))

  this.trianglePositions.update(tPos)
  this.triangleVectors.update(tVec)
  this.triangleColors.update(tCol)
  this.triangleUVs.update(tUVs)
  this.triangleNormals.update(tNor)
  this.triangleIds.update(new Uint32Array(tIds))
}

proto.drawTransparent = proto.draw = function(params) {
  params = params || {}
  var gl          = this.gl
  var model       = params.model      || IDENTITY
  var view        = params.view       || IDENTITY
  var projection  = params.projection || IDENTITY

  var clipBounds = [[-1e6,-1e6,-1e6],[1e6,1e6,1e6]]
  for(var i=0; i<3; ++i) {
    clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i])
    clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i])
  }

  var uniforms = {
    model:      model,
    view:       view,
    projection: projection,
    inverseModel: IDENTITY.slice(),

    clipBounds: clipBounds,

    kambient:   this.ambientLight,
    kdiffuse:   this.diffuseLight,
    kspecular:  this.specularLight,
    roughness:  this.roughness,
    fresnel:    this.fresnel,

    eyePosition:   [0,0,0],
    lightPosition: [0,0,0],

    opacity:  this.opacity,

    tubeScale: this.tubeScale,

    contourColor: this.contourColor,

    texture:    0
  }

  uniforms.inverseModel = invert(uniforms.inverseModel, uniforms.model)

  gl.disable(gl.CULL_FACE)

  this.texture.bind(0)

  var invCameraMatrix = new Array(16)
  multiply(invCameraMatrix, uniforms.view, uniforms.model)
  multiply(invCameraMatrix, uniforms.projection, invCameraMatrix)
  invert(invCameraMatrix, invCameraMatrix)

  for(var i=0; i<3; ++i) {
    uniforms.eyePosition[i] = invCameraMatrix[12+i] / invCameraMatrix[15]
  }

  var w = invCameraMatrix[15]
  for(var i=0; i<3; ++i) {
    w += this.lightPosition[i] * invCameraMatrix[4*i+3]
  }
  for(var i=0; i<3; ++i) {
    var s = invCameraMatrix[12+i]
    for(var j=0; j<3; ++j) {
      s += invCameraMatrix[4*j+i] * this.lightPosition[j]
    }
    uniforms.lightPosition[i] = s / w
  }

  if(this.triangleCount > 0) {
    var shader = this.triShader
    shader.bind()
    shader.uniforms = uniforms

    this.triangleVAO.bind()
    gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3)
    this.triangleVAO.unbind()
  }
}

proto.drawPick = function(params) {
  params = params || {}

  var gl         = this.gl

  var model      = params.model      || IDENTITY
  var view       = params.view       || IDENTITY
  var projection = params.projection || IDENTITY

  var clipBounds = [[-1e6,-1e6,-1e6],[1e6,1e6,1e6]]
  for(var i=0; i<3; ++i) {
    clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i])
    clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i])
  }

  //Save camera parameters
  this._model      = [].slice.call(model)
  this._view       = [].slice.call(view)
  this._projection = [].slice.call(projection)
  this._resolution = [gl.drawingBufferWidth, gl.drawingBufferHeight]

  var uniforms = {
    model:      model,
    view:       view,
    projection: projection,
    clipBounds: clipBounds,

    tubeScale: this.tubeScale,

    pickId:     this.pickId / 255.0,
  }

  var shader = this.pickShader
  shader.bind()
  shader.uniforms = uniforms

  if(this.triangleCount > 0) {
    this.triangleVAO.bind()
    gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3)
    this.triangleVAO.unbind()
  }

  if(this.edgeCount > 0) {
    this.edgeVAO.bind()
    gl.lineWidth(this.lineWidth * this.pixelRatio)
    gl.drawArrays(gl.LINES, 0, this.edgeCount*2)
    this.edgeVAO.unbind()
  }

}


proto.pick = function(pickData) {
  if(!pickData) {
    return null
  }
  if(pickData.id !== this.pickId) {
    return null
  }

  var cellId = pickData.value[0] + 256*pickData.value[1] + 65536*pickData.value[2]
  var cell = this.cells[cellId]

  var pos = this.positions[cell[1]].slice(0, 3)
  var intensity = this.intensity[cell[1]]
  var velocity = this.vectors[cell[1]].slice(0, 3)
  var divergence = this.vectors[cell[1]][3]

  return {
    index: cellId,
    position: pos,
    intensity: intensity,
    velocity: velocity,
    divergence: divergence,
    dataCoordinate: pos
  }
}


proto.dispose = function() {
  this.texture.dispose()

  this.triShader.dispose()
  this.pickShader.dispose()

  this.triangleVAO.dispose()
  this.trianglePositions.dispose()
  this.triangleVectors.dispose()
  this.triangleColors.dispose()
  this.triangleUVs.dispose()
  this.triangleNormals.dispose()
  this.triangleIds.dispose()

  this.edgeVAO.dispose()
  this.edgePositions.dispose()
  this.edgeColors.dispose()
  this.edgeUVs.dispose()
  this.edgeIds.dispose()

  this.pointVAO.dispose()
  this.pointPositions.dispose()
  this.pointColors.dispose()
  this.pointUVs.dispose()
  this.pointSizes.dispose()
  this.pointIds.dispose()

  this.contourVAO.dispose()
  this.contourPositions.dispose()
}

function createMeshShader(gl) {
  var shader = createShader(gl, meshShader.vertex, meshShader.fragment, null, meshShader.attributes)
  shader.attributes.position.location = 0
  shader.attributes.color.location    = 2
  shader.attributes.uv.location       = 3
  shader.attributes.vector.location   = 5
  return shader
}


function createPickShader(gl) {
  var shader = createShader(gl, pickShader.vertex, pickShader.fragment, null, pickShader.attributes)
  shader.attributes.position.location = 0
  shader.attributes.id.location       = 1
  shader.attributes.vector.location   = 5
  return shader
}


function createSimplicialMesh(gl, params) {
  if (arguments.length === 1) {
    params = gl;
    gl = params.gl;
  }

  var triShader       = params.triShader || createMeshShader(gl)
  var pickShader      = createPickShader(gl)

  var meshTexture       = createTexture(gl,
    ndarray(new Uint8Array([255,255,255,255]), [1,1,4]))
  meshTexture.generateMipmap()
  meshTexture.minFilter = gl.LINEAR_MIPMAP_LINEAR
  meshTexture.magFilter = gl.LINEAR

  var trianglePositions = createBuffer(gl)
  var triangleVectors   = createBuffer(gl)
  var triangleColors    = createBuffer(gl)
  var triangleUVs       = createBuffer(gl)
  var triangleNormals   = createBuffer(gl)
  var triangleIds       = createBuffer(gl)
  var triangleVAO       = createVAO(gl, [
    { buffer: trianglePositions,
      type: gl.FLOAT,
      size: 4
    },
    { buffer: triangleIds,
      type: gl.UNSIGNED_BYTE,
      size: 4,
      normalized: true
    },
    { buffer: triangleColors,
      type: gl.FLOAT,
      size: 4
    },
    { buffer: triangleUVs,
      type: gl.FLOAT,
      size: 2
    },
    { buffer: triangleNormals,
      type: gl.FLOAT,
      size: 3
    },
    { buffer: triangleVectors,
      type: gl.FLOAT,
      size: 4
    }
  ])

  var edgePositions = createBuffer(gl)
  var edgeColors    = createBuffer(gl)
  var edgeUVs       = createBuffer(gl)
  var edgeIds       = createBuffer(gl)
  var edgeVAO       = createVAO(gl, [
    { buffer: edgePositions,
      type: gl.FLOAT,
      size: 3
    },
    { buffer: edgeIds,
      type: gl.UNSIGNED_BYTE,
      size: 4,
      normalized: true
    },
    { buffer: edgeColors,
      type: gl.FLOAT,
      size: 4
    },
    { buffer: edgeUVs,
      type: gl.FLOAT,
      size: 2
    }
  ])

  var pointPositions  = createBuffer(gl)
  var pointColors     = createBuffer(gl)
  var pointUVs        = createBuffer(gl)
  var pointSizes      = createBuffer(gl)
  var pointIds        = createBuffer(gl)
  var pointVAO        = createVAO(gl, [
    { buffer: pointPositions,
      type: gl.FLOAT,
      size: 3
    },
    { buffer: pointIds,
      type: gl.UNSIGNED_BYTE,
      size: 4,
      normalized: true
    },
    { buffer: pointColors,
      type: gl.FLOAT,
      size: 4
    },
    { buffer: pointUVs,
      type: gl.FLOAT,
      size: 2
    },
    { buffer: pointSizes,
      type: gl.FLOAT,
      size: 1
    }
  ])

  var contourPositions = createBuffer(gl)
  var contourVAO       = createVAO(gl, [
    { buffer: contourPositions,
      type:   gl.FLOAT,
      size:   3
    }])

  var mesh = new SimplicialMesh(gl
    , meshTexture
    , triShader
    , pickShader
    , trianglePositions
    , triangleVectors
    , triangleIds
    , triangleColors
    , triangleUVs
    , triangleNormals
    , triangleVAO
    , edgePositions
    , edgeIds
    , edgeColors
    , edgeUVs
    , edgeVAO
    , pointPositions
    , pointIds
    , pointColors
    , pointUVs
    , pointSizes
    , pointVAO
    , contourPositions
    , contourVAO)

  mesh.update(params)

  return mesh
}

module.exports = createSimplicialMesh

},{"./shaders":304,"colormap":114,"gl-buffer":234,"gl-mat4/invert":258,"gl-mat4/multiply":260,"gl-shader":294,"gl-texture2d":311,"gl-vao":316,"ndarray":439,"normals":442,"simplicial-complex-contour":499,"typedarray-pool":526}],306:[function(_dereq_,module,exports){
"use strict";

var vec3 = _dereq_('gl-vec3');
var vec4 = _dereq_('gl-vec4');

var streamToTube = function(stream, maxDivergence, minDistance, maxNorm) {
	var points = stream.points;
	var velocities = stream.velocities;
	var divergences = stream.divergences;

	var p, fwd, r, u, v, up;
	up = vec3.set(vec3.create(), 0, 1, 0);
	u = vec3.create();
	v = vec3.create();
	var p2 = vec3.create();

	var verts = [];
	var faces = [];
	var vectors = [];
	var previousVerts = [];
	var currentVerts = [];
	var intensities = [];
	var previousIntensity = 0;
	var currentIntensity = 0;
	var currentVector = vec4.create();
	var previousVector = vec4.create();

	var facets = 8;

	for (var i = 0; i < points.length; i++) {
		p = points[i];
		fwd = velocities[i];
		r = divergences[i];
		if (maxDivergence === 0) {
			r = minDistance * 0.05;
		}
		currentIntensity = vec3.length(fwd) / maxNorm;
		currentVector = vec4.create();
		vec3.copy(currentVector, fwd);
		currentVector[3] = r;
		
		for (var a = 0; a < facets; a++) {
			currentVerts[a] = [p[0], p[1], p[2], a];
		}
		if (previousVerts.length > 0) {
			for (var a = 0; a < facets; a++) {
				var a1 = (a+1) % facets;
				verts.push(
					previousVerts[a],
					currentVerts[a],
					currentVerts[a1],

					currentVerts[a1],
					previousVerts[a1],
					previousVerts[a]
				);
				vectors.push(
					previousVector,
					currentVector,
					currentVector,

					currentVector,
					previousVector,
					previousVector
				);
				intensities.push(
					previousIntensity,
					currentIntensity,
					currentIntensity,

					currentIntensity,
					previousIntensity,
					previousIntensity
				);
				faces.push(
					[verts.length-6, verts.length-5, verts.length-4],
					[verts.length-3, verts.length-2, verts.length-1]
				);
			}
		}
		var tmp = previousVerts;
		previousVerts = currentVerts;
		currentVerts = tmp;
		tmp = previousVector;
		previousVector = currentVector;
		currentVector = tmp;
		tmp = previousIntensity;
		previousIntensity = currentIntensity;
		currentIntensity = tmp;
	}
	return {
		positions: verts,
		cells: faces,
		vectors: vectors,
		vertexIntensity: intensities
	};

};

var createTubes = function(streams, colormap, maxDivergence, minDistance) {

	var maxNorm = 0;
	for (var i=0; i<streams.length; i++) {
		var velocities = streams[i].velocities;
		for (var j=0; j<velocities.length; j++) {
			var norm = vec3.length(velocities[j]);
			if (norm > maxNorm) {
				maxNorm = norm;
			}
		}
	}

	var tubes = streams.map(function(s) {
		return streamToTube(s, maxDivergence, minDistance, maxNorm);
	});

	var positions = [];
	var cells = [];
	var vectors = [];
	var vertexIntensity = [];
	for (var i=0; i < tubes.length; i++) {
		var tube = tubes[i];
		var offset = positions.length;
		positions = positions.concat(tube.positions);
		vectors = vectors.concat(tube.vectors);
		vertexIntensity = vertexIntensity.concat(tube.vertexIntensity);
		for (var j=0; j<tube.cells.length; j++) {
			var cell = tube.cells[j];
			var newCell = [];
			cells.push(newCell);
			for (var k=0; k<cell.length; k++) {
				newCell.push(cell[k] + offset);
			}
		}
	}
	return {
		positions: positions,
		cells: cells,
		vectors: vectors,
		vertexIntensity: vertexIntensity,
		colormap: colormap
	};
};

var defaultGetDivergence = function(p, v0) {
	var dp = vec3.create();
	var e = 1/10000;

	vec3.add(dp, p, [e, 0, 0]);
	var vx = this.getVelocity(dp);
	vec3.subtract(vx, vx, v0);
	vec3.scale(vx, vx, 1/e);

	vec3.add(dp, p, [0, e, 0]);
	var vy = this.getVelocity(dp);
	vec3.subtract(vy, vy, v0);
	vec3.scale(vy, vy, 1/e);

	vec3.add(dp, p, [0, 0, e]);
	var vz = this.getVelocity(dp);
	vec3.subtract(vz, vz, v0);
	vec3.scale(vz, vz, 1/e);

	vec3.add(dp, vx, vy);
	vec3.add(dp, dp, vz);
	return dp;
};

var defaultGetVelocity = function(p) {
    var u = sampleMeshgrid(p, this.vectors, this.meshgrid, this.clampBorders);
    return u;
};


var findLastSmallerIndex = function(points, v) {
  for (var i=0; i<points.length; i++) {
  	var p = points[i];
  	if (p === v) return i;
    if (p > v) return i-1;
  }
  return i;
};

var tmp = vec3.create();
var tmp2 = vec3.create();

var clamp = function(v, min, max) {
	return v < min ? min : (v > max ? max : v);
};

var sampleMeshgrid = function(point, array, meshgrid, clampOverflow) {
	var x = point[0];
	var y = point[1];
	var z = point[2];

	var w = meshgrid[0].length;
	var h = meshgrid[1].length;
	var d = meshgrid[2].length;

	// Find the index of the nearest smaller value in the meshgrid for each coordinate of (x,y,z).
	// The nearest smaller value index for x is the index x0 such that
	// meshgrid[0][x0] < x and for all x1 > x0, meshgrid[0][x1] >= x.
	var x0 = findLastSmallerIndex(meshgrid[0], x);
	var y0 = findLastSmallerIndex(meshgrid[1], y);
	var z0 = findLastSmallerIndex(meshgrid[2], z);

	// Get the nearest larger meshgrid value indices.
	// From the above "nearest smaller value", we know that
	//   meshgrid[0][x0] < x
	//   meshgrid[0][x0+1] >= x
	var x1 = x0 + 1;
	var y1 = y0 + 1;
	var z1 = z0 + 1;

	if (meshgrid[0][x0] === x) x1 = x0;
	if (meshgrid[1][y0] === y) y1 = y0;
	if (meshgrid[2][z0] === z) z1 = z0;

	if (clampOverflow) {
		x0 = clamp(x0, 0, w-1);
		x1 = clamp(x1, 0, w-1);
		y0 = clamp(y0, 0, h-1);
		y1 = clamp(y1, 0, h-1);
		z0 = clamp(z0, 0, d-1);
		z1 = clamp(z1, 0, d-1);
	}

	// Reject points outside the meshgrid, return a zero vector.
	if (x0 < 0 || y0 < 0 || z0 < 0 || x1 >= w || y1 >= h || z1 >= d) {
		return vec3.create();
	}

	// Normalize point coordinates to 0..1 scaling factor between x0 and x1.
	var xf = (x - meshgrid[0][x0]) / (meshgrid[0][x1] - meshgrid[0][x0]);
	var yf = (y - meshgrid[1][y0]) / (meshgrid[1][y1] - meshgrid[1][y0]);
	var zf = (z - meshgrid[2][z0]) / (meshgrid[2][z1] - meshgrid[2][z0]);

	if (xf < 0 || xf > 1 || isNaN(xf)) xf = 0;
	if (yf < 0 || yf > 1 || isNaN(yf)) yf = 0;
	if (zf < 0 || zf > 1 || isNaN(zf)) zf = 0;

	var z0off = z0*w*h;
	var z1off = z1*w*h;

	var y0off = y0*w;
	var y1off = y1*w;

	var x0off = x0;
	var x1off = x1;

	// Sample data array around the (x,y,z) point.
	//  vZYX = array[zZoff + yYoff + xXoff]
	var v000 = array[y0off + z0off + x0off];
	var v001 = array[y0off + z0off + x1off];
	var v010 = array[y1off + z0off + x0off];
	var v011 = array[y1off + z0off + x1off];
	var v100 = array[y0off + z1off + x0off];
	var v101 = array[y0off + z1off + x1off];
	var v110 = array[y1off + z1off + x0off];
	var v111 = array[y1off + z1off + x1off];

	var result = vec3.create();

	// Average samples according to distance to point.
	vec3.lerp(result, v000, v001, xf);
	vec3.lerp(tmp, v010, v011, xf);
	vec3.lerp(result, result, tmp, yf);
	vec3.lerp(tmp, v100, v101, xf);
	vec3.lerp(tmp2, v110, v111, xf);
	vec3.lerp(tmp, tmp, tmp2, yf);
	vec3.lerp(result, result, tmp, zf);

	return result;
};


var vabs = function(dst, v) {
	var x = v[0];
	var y = v[1];
	var z = v[2];
	dst[0] = x >= 0 ? x : -x;
	dst[1] = y >= 0 ? y : -y;
	dst[2] = z >= 0 ? z : -z;
	return dst;
};

var findMinSeparation = function(xs) {
	var minSeparation = 1/0;
	xs.sort(function(a, b) { return a - b; });
	for (var i=1; i<xs.length; i++) {
		var d = Math.abs(xs[i] - xs[i-1]);
		if (d < minSeparation) {
			minSeparation = d;
		}
	}
	return minSeparation;
};

// Finds the minimum per-component distance in positions.
// 
var calculateMinPositionDistance = function(positions) {
	var xs = [], ys = [], zs = [];
	var xi = {}, yi = {}, zi = {};
	for (var i=0; i<positions.length; i++) {
		var p = positions[i];
		var x = p[0], y = p[1], z = p[2];

		// Split the positions array into arrays of unique component values.
		//
		// Why go through the trouble of using a uniqueness hash table vs
		// sort and uniq: 
		//
		// Suppose you've got a million positions in a 100x100x100 grid.
		//
		// Using a uniqueness hash table, you're doing 1M array reads, 
		// 3M hash table lookups from 100-element hashes, 300 hash table inserts, then
		// sorting three 100-element arrays and iterating over them.
		// Roughly, 1M + 3M * ln(100) + 300 * ln(100/2) + 3 * 100 * ln(100) + 3 * 100 = 
		//          1M + 13.8M + 0.0012M +  0.0014M + 0.0003M 
		//          =~ 15M
		//
		// Sort and uniq solution would do 1M array reads, 3M array inserts,
		// sort three 1M-element arrays and iterate over them.
		// Roughly, 1M + 3M + 3 * 1M * ln(1M) + 3 * 1M = 
		//          1M + 3M + 41.4M + 3M 
		//          =~ 48.4M
		//
		// Guessing that a hard-coded sort & uniq would be faster due to not having
		// to run a hashing function on everything. More memory usage though 
		// (bunch of small hash tables vs. duplicating the input array.)
		//
		// In JS-land, who knows. Maybe xi[x] casts x to string and destroys perf, 
		// maybe numeric keys get special-cased, maybe the object lookups run at near O(1)-speeds.
		// Maybe the sorting comparison function is expensive to call, maybe it gets inlined or special-cased.
		//
		// ... You're probably not going to call this with more than 10k positions anyhow, so this is very academic.
		//
		if (!xi[x]) {
			xs.push(x);
			xi[x] = true;
		}
		if (!yi[y]) {
			ys.push(y);
			yi[y] = true;
		}
		if (!zi[z]) {
			zs.push(z);
			zi[z] = true;
		}
	}
	var xSep = findMinSeparation(xs);
	var ySep = findMinSeparation(ys);
	var zSep = findMinSeparation(zs);
	var minSeparation = Math.min(xSep, ySep, zSep);
	if (!isFinite(minSeparation)) {
		return 1;
	}
	return minSeparation;
};

module.exports = function(vectorField, bounds) {
	var positions = vectorField.startingPositions;
	var maxLength = vectorField.maxLength || 1000;
	var tubeSize = vectorField.tubeSize || 1;
	var absoluteTubeSize = vectorField.absoluteTubeSize;

	if (!vectorField.getDivergence) {
		vectorField.getDivergence = defaultGetDivergence;
	}

	if (!vectorField.getVelocity) {
		vectorField.getVelocity = defaultGetVelocity;
	}

	if (vectorField.clampBorders === undefined) {
		vectorField.clampBorders = true;
	}

	var streams = [];

	var minX = bounds[0][0], minY = bounds[0][1], minZ = bounds[0][2];
	var maxX = bounds[1][0], maxY = bounds[1][1], maxZ = bounds[1][2];

	var inBounds = function(bounds, p) {
		var x = p[0];
		var y = p[1];
		var z = p[2];
		return (
			x >= minX && x <= maxX &&
			y >= minY && y <= maxY &&
			z >= minZ && z <= maxZ
		);
	};

	var boundsSize = vec3.distance(bounds[0], bounds[1]);
	var maxStepSize = 10 * boundsSize / maxLength;
	var maxStepSizeSq = maxStepSize * maxStepSize;

	var minDistance = 1;
	var maxDivergence = 0; // For component-wise divergence vec3.create();
	var tmp = vec3.create();

	if (positions.length >= 2) {
		minDistance = calculateMinPositionDistance(positions);
	}

	for (var i = 0; i < positions.length; i++) {
		var p = vec3.create();
		vec3.copy(p, positions[i]);

		var stream = [p];
		var velocities = [];
		var v = vectorField.getVelocity(p);
		var op = p;
		velocities.push(v);

		var divergences = [];

		var dv = vectorField.getDivergence(p, v);
		var dvLength = vec3.length(dv);
		if (dvLength > maxDivergence && !isNaN(dvLength) && isFinite(dvLength)) {
			maxDivergence = dvLength;
		}
		// In case we need to do component-wise divergence visualization
		// vec3.max(maxDivergence, maxDivergence, vabs(tmp, dv));
		divergences.push(dvLength);

		streams.push({points: stream, velocities: velocities, divergences: divergences});

		var j = 0;

		while (j < maxLength * 100 && stream.length < maxLength && inBounds(bounds, p)) {
			j++;
			var np = vec3.clone(v);
			var sqLen = vec3.squaredLength(np);
			if (sqLen === 0) {
				break;
			} else if (sqLen > maxStepSizeSq) {
				vec3.scale(np, np, maxStepSize / Math.sqrt(sqLen));
			}
			vec3.add(np, np, p);

			v = vectorField.getVelocity(np);

			if (vec3.squaredDistance(op, np) - maxStepSizeSq > -0.0001 * maxStepSizeSq) {
				stream.push(np);
				op = np;
				velocities.push(v);
				var dv = vectorField.getDivergence(np, v);
				var dvLength = vec3.length(dv);
				if (dvLength > maxDivergence && !isNaN(dvLength) && isFinite(dvLength)) {
					maxDivergence = dvLength;
				}
				// In case we need to do component-wise divergence visualization
				//vec3.max(maxDivergence, maxDivergence, vabs(tmp, dv));
				divergences.push(dvLength);
			}

			p = np;
		}
	}

	// Replace NaNs and Infinities with non-NaN, finite maxDivergence
	for (var i=0; i<divergences.length; i++) {
		var dvLength = divergences[i];
		if (isNaN(dvLength) || !isFinite(dvLength)) {
			divergences[i] = maxDivergence;
		}
	}

	var tubes = createTubes(streams, vectorField.colormap, maxDivergence, minDistance);

	if (absoluteTubeSize) {
		tubes.tubeScale = absoluteTubeSize;
	} else {
		// Avoid division by zero.
		if (maxDivergence === 0) {
			maxDivergence = 1;
		}
		tubes.tubeScale = tubeSize * 0.5 * minDistance / maxDivergence;
	}

	return tubes;
};

module.exports.createTubeMesh = _dereq_('./lib/tubemesh');

},{"./lib/tubemesh":305,"gl-vec3":335,"gl-vec4":371}],307:[function(_dereq_,module,exports){
var createShader = _dereq_('gl-shader')
var glslify = _dereq_('glslify')

var vertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute vec3 f;\nattribute vec3 normal;\n\nuniform vec3 objectOffset;\nuniform mat4 model, view, projection, inverseModel;\nuniform vec3 lightPosition, eyePosition;\nuniform sampler2D colormap;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\nvarying vec4 vColor;\n\nvoid main() {\n  vec3 localCoordinate = vec3(uv.zw, f.x);\n  worldCoordinate = objectOffset + localCoordinate;\n  vec4 worldPosition = model * vec4(worldCoordinate, 1.0);\n  vec4 clipPosition = projection * view * worldPosition;\n  gl_Position = clipPosition;\n  kill = f.y;\n  value = f.z;\n  planeCoordinate = uv.xy;\n\n  vColor = texture2D(colormap, vec2(value, value));\n\n  //Lighting geometry parameters\n  vec4 cameraCoordinate = view * worldPosition;\n  cameraCoordinate.xyz /= cameraCoordinate.w;\n  lightDirection = lightPosition - cameraCoordinate.xyz;\n  eyeDirection   = eyePosition - cameraCoordinate.xyz;\n  surfaceNormal  = normalize((vec4(normal,0) * inverseModel).xyz);\n}\n"])
var fragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution(float x, float roughness) {\n  float NdotH = max(x, 0.0001);\n  float cos2Alpha = NdotH * NdotH;\n  float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n  float roughness2 = roughness * roughness;\n  float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n  return exp(tan2Alpha / roughness2) / denom;\n}\n\nfloat beckmannSpecular(\n  vec3 lightDirection,\n  vec3 viewDirection,\n  vec3 surfaceNormal,\n  float roughness) {\n  return beckmannDistribution(dot(surfaceNormal, normalize(lightDirection + viewDirection)), roughness);\n}\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 lowerBound, upperBound;\nuniform float contourTint;\nuniform vec4 contourColor;\nuniform sampler2D colormap;\nuniform vec3 clipBounds[2];\nuniform float roughness, fresnel, kambient, kdiffuse, kspecular, opacity;\nuniform float vertexColor;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\nvarying vec4 vColor;\n\nvoid main() {\n  if ((kill > 0.0) ||\n      (outOfRange(clipBounds[0], clipBounds[1], worldCoordinate))) discard;\n\n  vec3 N = normalize(surfaceNormal);\n  vec3 V = normalize(eyeDirection);\n  vec3 L = normalize(lightDirection);\n\n  if(gl_FrontFacing) {\n    N = -N;\n  }\n\n  float specular = max(beckmannSpecular(L, V, N, roughness), 0.);\n  float diffuse  = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n  //decide how to interpolate color — in vertex or in fragment\n  vec4 surfaceColor =\n    step(vertexColor, .5) * texture2D(colormap, vec2(value, value)) +\n    step(.5, vertexColor) * vColor;\n\n  vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular,  1.0);\n\n  gl_FragColor = mix(litColor, contourColor, contourTint) * opacity;\n}\n"])
var contourVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute float f;\n\nuniform vec3 objectOffset;\nuniform mat3 permutation;\nuniform mat4 model, view, projection;\nuniform float height, zOffset;\nuniform sampler2D colormap;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\nvarying vec4 vColor;\n\nvoid main() {\n  vec3 dataCoordinate = permutation * vec3(uv.xy, height);\n  worldCoordinate = objectOffset + dataCoordinate;\n  vec4 worldPosition = model * vec4(worldCoordinate, 1.0);\n\n  vec4 clipPosition = projection * view * worldPosition;\n  clipPosition.z += zOffset;\n\n  gl_Position = clipPosition;\n  value = f + objectOffset.z;\n  kill = -1.0;\n  planeCoordinate = uv.zw;\n\n  vColor = texture2D(colormap, vec2(value, value));\n\n  //Don't do lighting for contours\n  surfaceNormal   = vec3(1,0,0);\n  eyeDirection    = vec3(0,1,0);\n  lightDirection  = vec3(0,0,1);\n}\n"])
var pickSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec2 shape;\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 surfaceNormal;\n\nvec2 splitFloat(float v) {\n  float vh = 255.0 * v;\n  float upper = floor(vh);\n  float lower = fract(vh);\n  return vec2(upper / 255.0, floor(lower * 16.0) / 16.0);\n}\n\nvoid main() {\n  if ((kill > 0.0) ||\n      (outOfRange(clipBounds[0], clipBounds[1], worldCoordinate))) discard;\n\n  vec2 ux = splitFloat(planeCoordinate.x / shape.x);\n  vec2 uy = splitFloat(planeCoordinate.y / shape.y);\n  gl_FragColor = vec4(pickId, ux.x, uy.x, ux.y + (uy.y/16.0));\n}\n"])

exports.createShader = function (gl) {
  var shader = createShader(gl, vertSrc, fragSrc, null, [
    {name: 'uv', type: 'vec4'},
    {name: 'f', type: 'vec3'},
    {name: 'normal', type: 'vec3'}
  ])
  shader.attributes.uv.location = 0
  shader.attributes.f.location = 1
  shader.attributes.normal.location = 2
  return shader
}
exports.createPickShader = function (gl) {
  var shader = createShader(gl, vertSrc, pickSrc, null, [
    {name: 'uv', type: 'vec4'},
    {name: 'f', type: 'vec3'},
    {name: 'normal', type: 'vec3'}
  ])
  shader.attributes.uv.location = 0
  shader.attributes.f.location = 1
  shader.attributes.normal.location = 2
  return shader
}
exports.createContourShader = function (gl) {
  var shader = createShader(gl, contourVertSrc, fragSrc, null, [
    {name: 'uv', type: 'vec4'},
    {name: 'f', type: 'float'}
  ])
  shader.attributes.uv.location = 0
  shader.attributes.f.location = 1
  return shader
}
exports.createPickContourShader = function (gl) {
  var shader = createShader(gl, contourVertSrc, pickSrc, null, [
    {name: 'uv', type: 'vec4'},
    {name: 'f', type: 'float'}
  ])
  shader.attributes.uv.location = 0
  shader.attributes.f.location = 1
  return shader
}

},{"gl-shader":294,"glslify":398}],308:[function(_dereq_,module,exports){
arguments[4][99][0].apply(exports,arguments)
},{"dup":99}],309:[function(_dereq_,module,exports){
'use strict'

module.exports = createSurfacePlot

var bits = _dereq_('bit-twiddle')
var createBuffer = _dereq_('gl-buffer')
var createVAO = _dereq_('gl-vao')
var createTexture = _dereq_('gl-texture2d')
var pool = _dereq_('typedarray-pool')
var colormap = _dereq_('colormap')
var ops = _dereq_('ndarray-ops')
var pack = _dereq_('ndarray-pack')
var ndarray = _dereq_('ndarray')
var surfaceNets = _dereq_('surface-nets')
var multiply = _dereq_('gl-mat4/multiply')
var invert = _dereq_('gl-mat4/invert')
var bsearch = _dereq_('binary-search-bounds')
var gradient = _dereq_('ndarray-gradient')
var shaders = _dereq_('./lib/shaders')

var createShader = shaders.createShader
var createContourShader = shaders.createContourShader
var createPickShader = shaders.createPickShader
var createPickContourShader = shaders.createPickContourShader

var SURFACE_VERTEX_SIZE = 4 * (4 + 3 + 3)

var IDENTITY = [
  1, 0, 0, 0,
  0, 1, 0, 0,
  0, 0, 1, 0,
  0, 0, 0, 1 ]

var QUAD = [
  [0, 0],
  [0, 1],
  [1, 0],
  [1, 1],
  [1, 0],
  [0, 1]
]

var PERMUTATIONS = [
  [0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0]
]

;(function () {
  for (var i = 0; i < 3; ++i) {
    var p = PERMUTATIONS[i]
    var u = (i + 1) % 3
    var v = (i + 2) % 3
    p[u + 0] = 1
    p[v + 3] = 1
    p[i + 6] = 1
  }
})()

function SurfacePickResult (position, index, uv, level, dataCoordinate) {
  this.position = position
  this.index = index
  this.uv = uv
  this.level = level
  this.dataCoordinate = dataCoordinate
}

var N_COLORS = 256

function genColormap (name) {
  var x = pack([colormap({
    colormap: name,
    nshades: N_COLORS,
    format: 'rgba'
  }).map(function (c) {
    return [c[0], c[1], c[2], 255 * c[3]]
  })])
  ops.divseq(x, 255.0)
  return x
}

function SurfacePlot (
  gl,
  shape,
  bounds,
  shader,
  pickShader,
  coordinates,
  vao,
  colorMap,
  contourShader,
  contourPickShader,
  contourBuffer,
  contourVAO,
  dynamicBuffer,
  dynamicVAO,
  objectOffset) {
  this.gl = gl
  this.shape = shape
  this.bounds = bounds
  this.objectOffset = objectOffset
  this.intensityBounds = []

  this._shader = shader
  this._pickShader = pickShader
  this._coordinateBuffer = coordinates
  this._vao = vao
  this._colorMap = colorMap

  this._contourShader = contourShader
  this._contourPickShader = contourPickShader
  this._contourBuffer = contourBuffer
  this._contourVAO = contourVAO
  this._contourOffsets = [[], [], []]
  this._contourCounts = [[], [], []]
  this._vertexCount = 0

  this._pickResult = new SurfacePickResult([0, 0, 0], [0, 0], [0, 0], [0, 0, 0], [0, 0, 0])

  this._dynamicBuffer = dynamicBuffer
  this._dynamicVAO = dynamicVAO
  this._dynamicOffsets = [0, 0, 0]
  this._dynamicCounts = [0, 0, 0]

  this.contourWidth = [ 1, 1, 1 ]
  this.contourLevels = [[1], [1], [1]]
  this.contourTint = [0, 0, 0]
  this.contourColor = [[0.5, 0.5, 0.5, 1], [0.5, 0.5, 0.5, 1], [0.5, 0.5, 0.5, 1]]

  this.showContour = true
  this.showSurface = true

  this.enableHighlight = [true, true, true]
  this.highlightColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]]
  this.highlightTint = [ 1, 1, 1 ]
  this.highlightLevel = [-1, -1, -1]

  // Dynamic contour options
  this.enableDynamic = [ true, true, true ]
  this.dynamicLevel = [ NaN, NaN, NaN ]
  this.dynamicColor = [ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1] ]
  this.dynamicTint = [ 1, 1, 1 ]
  this.dynamicWidth = [ 1, 1, 1 ]

  this.axesBounds = [[Infinity, Infinity, Infinity], [-Infinity, -Infinity, -Infinity]]
  this.surfaceProject = [ false, false, false ]
  this.contourProject = [[ false, false, false ],
    [ false, false, false ],
    [ false, false, false ]]

  this.colorBounds = [ false, false ]

  // Store xyz fields, need this for picking
  this._field = [
    ndarray(pool.mallocFloat(1024), [0, 0]),
    ndarray(pool.mallocFloat(1024), [0, 0]),
    ndarray(pool.mallocFloat(1024), [0, 0]) ]

  this.pickId = 1
  this.clipBounds = [[-Infinity, -Infinity, -Infinity], [Infinity, Infinity, Infinity]]

  this.snapToData = false

  this.pixelRatio = 1

  this.opacity = 1.0

  this.lightPosition = [10, 10000, 0]
  this.ambientLight = 0.8
  this.diffuseLight = 0.8
  this.specularLight = 2.0
  this.roughness = 0.5
  this.fresnel = 1.5
  this.vertexColor = 0

  this.dirty = true
}

var proto = SurfacePlot.prototype

proto.isTransparent = function () {
  return this.opacity < 1
}

proto.isOpaque = function () {
  if (this.opacity >= 1) {
    return true
  }
  for (var i = 0; i < 3; ++i) {
    if (this._contourCounts[i].length > 0 || this._dynamicCounts[i] > 0) {
      return true
    }
  }
  return false
}

proto.pickSlots = 1

proto.setPickBase = function (id) {
  this.pickId = id
}

var ZERO_VEC = [0, 0, 0]

var PROJECT_DATA = {
  showSurface: false,
  showContour: false,
  projections: [IDENTITY.slice(), IDENTITY.slice(), IDENTITY.slice()],
  clipBounds: [
    [[0, 0, 0], [0, 0, 0]],
    [[0, 0, 0], [0, 0, 0]],
    [[0, 0, 0], [0, 0, 0]]]
}

function computeProjectionData (camera, obj) {
  var i, j, k

  // Compute cube properties
  var cubeAxis = (obj.axes && obj.axes.lastCubeProps.axis) || ZERO_VEC

  var showSurface = obj.showSurface
  var showContour = obj.showContour

  for (i = 0; i < 3; ++i) {
    showSurface = showSurface || obj.surfaceProject[i]
    for (j = 0; j < 3; ++j) {
      showContour = showContour || obj.contourProject[i][j]
    }
  }

  for (i = 0; i < 3; ++i) {
    // Construct projection onto axis
    var axisSquish = PROJECT_DATA.projections[i]
    for (j = 0; j < 16; ++j) {
      axisSquish[j] = 0
    }
    for (j = 0; j < 4; ++j) {
      axisSquish[5 * j] = 1
    }
    axisSquish[5 * i] = 0
    axisSquish[12 + i] = obj.axesBounds[+(cubeAxis[i] > 0)][i]
    multiply(axisSquish, camera.model, axisSquish)

    var nclipBounds = PROJECT_DATA.clipBounds[i]
    for (k = 0; k < 2; ++k) {
      for (j = 0; j < 3; ++j) {
        nclipBounds[k][j] = camera.clipBounds[k][j]
      }
    }
    nclipBounds[0][i] = -1e8
    nclipBounds[1][i] = 1e8
  }

  PROJECT_DATA.showSurface = showSurface
  PROJECT_DATA.showContour = showContour

  return PROJECT_DATA
}

var UNIFORMS = {
  model: IDENTITY,
  view: IDENTITY,
  projection: IDENTITY,
  inverseModel: IDENTITY.slice(),
  lowerBound: [0, 0, 0],
  upperBound: [0, 0, 0],
  colorMap: 0,
  clipBounds: [[0, 0, 0], [0, 0, 0]],
  height: 0.0,
  contourTint: 0,
  contourColor: [0, 0, 0, 1],
  permutation: [1, 0, 0, 0, 1, 0, 0, 0, 1],
  zOffset: -1e-4,
  objectOffset: [0, 0, 0],
  kambient: 1,
  kdiffuse: 1,
  kspecular: 1,
  lightPosition: [1000, 1000, 1000],
  eyePosition: [0, 0, 0],
  roughness: 1,
  fresnel: 1,
  opacity: 1,
  vertexColor: 0
}

var MATRIX_INVERSE = IDENTITY.slice()
var DEFAULT_PERM = [1, 0, 0, 0, 1, 0, 0, 0, 1]

function drawCore (params, transparent) {
  params = params || {}
  var gl = this.gl

  gl.disable(gl.CULL_FACE)

  this._colorMap.bind(0)

  var uniforms = UNIFORMS
  uniforms.model = params.model || IDENTITY
  uniforms.view = params.view || IDENTITY
  uniforms.projection = params.projection || IDENTITY
  uniforms.lowerBound = [this.bounds[0][0], this.bounds[0][1], this.colorBounds[0] || this.bounds[0][2]]
  uniforms.upperBound = [this.bounds[1][0], this.bounds[1][1], this.colorBounds[1] || this.bounds[1][2]]
  uniforms.objectOffset = this.objectOffset
  uniforms.contourColor = this.contourColor[0]

  uniforms.inverseModel = invert(uniforms.inverseModel, uniforms.model)

  for (var i = 0; i < 2; ++i) {
    var clipClamped = uniforms.clipBounds[i]
    for (var j = 0; j < 3; ++j) {
      clipClamped[j] = Math.min(Math.max(this.clipBounds[i][j], -1e8), 1e8)
    }
  }

  uniforms.kambient = this.ambientLight
  uniforms.kdiffuse = this.diffuseLight
  uniforms.kspecular = this.specularLight

  uniforms.roughness = this.roughness
  uniforms.fresnel = this.fresnel
  uniforms.opacity = this.opacity

  uniforms.height = 0.0
  uniforms.permutation = DEFAULT_PERM

  uniforms.vertexColor = this.vertexColor

  // Compute camera matrix inverse
  var invCameraMatrix = MATRIX_INVERSE
  multiply(invCameraMatrix, uniforms.view, uniforms.model)
  multiply(invCameraMatrix, uniforms.projection, invCameraMatrix)
  invert(invCameraMatrix, invCameraMatrix)

  for (i = 0; i < 3; ++i) {
    uniforms.eyePosition[i] = invCameraMatrix[12 + i] / invCameraMatrix[15]
  }

  var w = invCameraMatrix[15]
  for (i = 0; i < 3; ++i) {
    w += this.lightPosition[i] * invCameraMatrix[4 * i + 3]
  }
  for (i = 0; i < 3; ++i) {
    var s = invCameraMatrix[12 + i]
    for (j = 0; j < 3; ++j) {
      s += invCameraMatrix[4 * j + i] * this.lightPosition[j]
    }
    uniforms.lightPosition[i] = s / w
  }

  var projectData = computeProjectionData(uniforms, this)

  if (projectData.showSurface && (transparent === (this.opacity < 1))) {
    // Set up uniforms
    this._shader.bind()
    this._shader.uniforms = uniforms

    // Draw it
    this._vao.bind()

    if (this.showSurface && this._vertexCount) {
      this._vao.draw(gl.TRIANGLES, this._vertexCount)
    }

    // Draw projections of surface
    for (i = 0; i < 3; ++i) {
      if (!this.surfaceProject[i] || !this.vertexCount) {
        continue
      }
      this._shader.uniforms.model = projectData.projections[i]
      this._shader.uniforms.clipBounds = projectData.clipBounds[i]
      this._vao.draw(gl.TRIANGLES, this._vertexCount)
    }

    this._vao.unbind()
  }

  if (projectData.showContour && !transparent) {
    var shader = this._contourShader

    // Don't apply lighting to contours
    uniforms.kambient = 1.0
    uniforms.kdiffuse = 0.0
    uniforms.kspecular = 0.0
    uniforms.opacity = 1.0

    shader.bind()
    shader.uniforms = uniforms

    // Draw contour lines
    var vao = this._contourVAO
    vao.bind()

    // Draw contour levels
    for (i = 0; i < 3; ++i) {
      shader.uniforms.permutation = PERMUTATIONS[i]
      gl.lineWidth(this.contourWidth[i] * this.pixelRatio)

      for (j = 0; j < this.contourLevels[i].length; ++j) {
        if (j === this.highlightLevel[i]) {
          shader.uniforms.contourColor = this.highlightColor[i]
          shader.uniforms.contourTint = this.highlightTint[i]
        } else if (j === 0 || (j - 1) === this.highlightLevel[i]) {
          shader.uniforms.contourColor = this.contourColor[i]
          shader.uniforms.contourTint = this.contourTint[i]
        }
        if (!this._contourCounts[i][j]) {
          continue
        }

        shader.uniforms.height = this.contourLevels[i][j]

        vao.draw(gl.LINES, this._contourCounts[i][j], this._contourOffsets[i][j])
      }
    }

    // Draw projections of surface
    for (i = 0; i < 3; ++i) {
      shader.uniforms.model = projectData.projections[i]
      shader.uniforms.clipBounds = projectData.clipBounds[i]
      for (j = 0; j < 3; ++j) {
        if (!this.contourProject[i][j]) {
          continue
        }
        shader.uniforms.permutation = PERMUTATIONS[j]
        gl.lineWidth(this.contourWidth[j] * this.pixelRatio)
        for (var k = 0; k < this.contourLevels[j].length; ++k) {
          if (k === this.highlightLevel[j]) {
            shader.uniforms.contourColor = this.highlightColor[j]
            shader.uniforms.contourTint = this.highlightTint[j]
          } else if (k === 0 || (k - 1) === this.highlightLevel[j]) {
            shader.uniforms.contourColor = this.contourColor[j]
            shader.uniforms.contourTint = this.contourTint[j]
          }
          shader.uniforms.height = this.contourLevels[j][k]
          vao.draw(gl.LINES, this._contourCounts[j][k], this._contourOffsets[j][k])
        }
      }
    }

    vao.unbind()

    // Draw dynamic contours
    vao = this._dynamicVAO
    vao.bind()

    // Draw contour levels
    for (i = 0; i < 3; ++i) {
      if (this._dynamicCounts[i] === 0) {
        continue
      }

      shader.uniforms.model = uniforms.model
      shader.uniforms.clipBounds = uniforms.clipBounds
      shader.uniforms.permutation = PERMUTATIONS[i]
      gl.lineWidth(this.dynamicWidth[i] * this.pixelRatio)

      shader.uniforms.contourColor = this.dynamicColor[i]
      shader.uniforms.contourTint = this.dynamicTint[i]
      shader.uniforms.height = this.dynamicLevel[i]
      vao.draw(gl.LINES, this._dynamicCounts[i], this._dynamicOffsets[i])

      for (j = 0; j < 3; ++j) {
        if (!this.contourProject[j][i]) {
          continue
        }

        shader.uniforms.model = projectData.projections[j]
        shader.uniforms.clipBounds = projectData.clipBounds[j]
        vao.draw(gl.LINES, this._dynamicCounts[i], this._dynamicOffsets[i])
      }
    }

    vao.unbind()
  }
}

proto.draw = function (params) {
  return drawCore.call(this, params, false)
}

proto.drawTransparent = function (params) {
  return drawCore.call(this, params, true)
}

var PICK_UNIFORMS = {
  model: IDENTITY,
  view: IDENTITY,
  projection: IDENTITY,
  inverseModel: IDENTITY,
  clipBounds: [[0, 0, 0], [0, 0, 0]],
  height: 0.0,
  shape: [0, 0],
  pickId: 0,
  lowerBound: [0, 0, 0],
  upperBound: [0, 0, 0],
  zOffset: 0.0,
  objectOffset: [0, 0, 0],
  permutation: [1, 0, 0, 0, 1, 0, 0, 0, 1],
  lightPosition: [0, 0, 0],
  eyePosition: [0, 0, 0]
}

proto.drawPick = function (params) {
  params = params || {}
  var gl = this.gl
  gl.disable(gl.CULL_FACE)

  var uniforms = PICK_UNIFORMS
  uniforms.model = params.model || IDENTITY
  uniforms.view = params.view || IDENTITY
  uniforms.projection = params.projection || IDENTITY
  uniforms.shape = this._field[2].shape
  uniforms.pickId = this.pickId / 255.0
  uniforms.lowerBound = this.bounds[0]
  uniforms.upperBound = this.bounds[1]
  uniforms.objectOffset = this.objectOffset
  uniforms.permutation = DEFAULT_PERM

  for (var i = 0; i < 2; ++i) {
    var clipClamped = uniforms.clipBounds[i]
    for (var j = 0; j < 3; ++j) {
      clipClamped[j] = Math.min(Math.max(this.clipBounds[i][j], -1e8), 1e8)
    }
  }

  var projectData = computeProjectionData(uniforms, this)

  if (projectData.showSurface) {
    // Set up uniforms
    this._pickShader.bind()
    this._pickShader.uniforms = uniforms

    // Draw it
    this._vao.bind()
    this._vao.draw(gl.TRIANGLES, this._vertexCount)

    // Draw projections of surface
    for (i = 0; i < 3; ++i) {
      if (!this.surfaceProject[i]) {
        continue
      }
      this._pickShader.uniforms.model = projectData.projections[i]
      this._pickShader.uniforms.clipBounds = projectData.clipBounds[i]
      this._vao.draw(gl.TRIANGLES, this._vertexCount)
    }

    this._vao.unbind()
  }

  if (projectData.showContour) {
    var shader = this._contourPickShader

    shader.bind()
    shader.uniforms = uniforms

    var vao = this._contourVAO
    vao.bind()

    for (j = 0; j < 3; ++j) {
      gl.lineWidth(this.contourWidth[j] * this.pixelRatio)
      shader.uniforms.permutation = PERMUTATIONS[j]
      for (i = 0; i < this.contourLevels[j].length; ++i) {
        if (this._contourCounts[j][i]) {
          shader.uniforms.height = this.contourLevels[j][i]
          vao.draw(gl.LINES, this._contourCounts[j][i], this._contourOffsets[j][i])
        }
      }
    }

    // Draw projections of surface
    for (i = 0; i < 3; ++i) {
      shader.uniforms.model = projectData.projections[i]
      shader.uniforms.clipBounds = projectData.clipBounds[i]

      for (j = 0; j < 3; ++j) {
        if (!this.contourProject[i][j]) {
          continue
        }

        shader.uniforms.permutation = PERMUTATIONS[j]
        gl.lineWidth(this.contourWidth[j] * this.pixelRatio)
        for (var k = 0; k < this.contourLevels[j].length; ++k) {
          if (this._contourCounts[j][k]) {
            shader.uniforms.height = this.contourLevels[j][k]
            vao.draw(gl.LINES, this._contourCounts[j][k], this._contourOffsets[j][k])
          }
        }
      }
    }

    vao.unbind()
  }
}

proto.pick = function (selection) {
  if (!selection) {
    return null
  }

  if (selection.id !== this.pickId) {
    return null
  }

  var shape = this._field[2].shape

  var result = this._pickResult

  // Compute uv coordinate
  var x = shape[0] * (selection.value[0] + (selection.value[2] >> 4) / 16.0) / 255.0
  var ix = Math.floor(x)
  var fx = x - ix

  var y = shape[1] * (selection.value[1] + (selection.value[2] & 15) / 16.0) / 255.0
  var iy = Math.floor(y)
  var fy = y - iy

  ix += 1
  iy += 1

  // Compute xyz coordinate
  var pos = result.position
  pos[0] = pos[1] = pos[2] = 0
  for (var dx = 0; dx < 2; ++dx) {
    var s = dx ? fx : 1.0 - fx
    for (var dy = 0; dy < 2; ++dy) {
      var t = dy ? fy : 1.0 - fy

      var r = ix + dx
      var c = iy + dy
      var w = s * t

      for (var i = 0; i < 3; ++i) {
        pos[i] += this._field[i].get(r, c) * w
      }
    }
  }

  // Find closest level
  var levelIndex = this._pickResult.level
  for (var j = 0; j < 3; ++j) {
    levelIndex[j] = bsearch.le(this.contourLevels[j], pos[j])
    if (levelIndex[j] < 0) {
      if (this.contourLevels[j].length > 0) {
        levelIndex[j] = 0
      }
    } else if (levelIndex[j] < this.contourLevels[j].length - 1) {
      var a = this.contourLevels[j][levelIndex[j]]
      var b = this.contourLevels[j][levelIndex[j] + 1]
      if (Math.abs(a - pos[j]) > Math.abs(b - pos[j])) {
        levelIndex[j] += 1
      }
    }
  }

  result.index[0] = fx < 0.5 ? ix : (ix + 1)
  result.index[1] = fy < 0.5 ? iy : (iy + 1)

  result.uv[0] = x / shape[0]
  result.uv[1] = y / shape[1]

  for (i = 0; i < 3; ++i) {
    result.dataCoordinate[i] = this._field[i].get(result.index[0], result.index[1])
  }

  return result
}

proto.padField = function(dstField, srcField) {
  var srcShape = srcField.shape.slice()
  var dstShape = dstField.shape.slice()

  // Center
  ops.assign(dstField.lo(1, 1).hi(srcShape[0], srcShape[1]), srcField)

  // Edges
  ops.assign(dstField.lo(1).hi(srcShape[0], 1),
    srcField.hi(srcShape[0], 1))
  ops.assign(dstField.lo(1, dstShape[1] - 1).hi(srcShape[0], 1),
    srcField.lo(0, srcShape[1] - 1).hi(srcShape[0], 1))
  ops.assign(dstField.lo(0, 1).hi(1, srcShape[1]),
    srcField.hi(1))
  ops.assign(dstField.lo(dstShape[0] - 1, 1).hi(1, srcShape[1]),
    srcField.lo(srcShape[0] - 1))
  // Corners
  dstField.set(0, 0, srcField.get(0, 0))
  dstField.set(0, dstShape[1] - 1, srcField.get(0, srcShape[1] - 1))
  dstField.set(dstShape[0] - 1, 0, srcField.get(srcShape[0] - 1, 0))
  dstField.set(dstShape[0] - 1, dstShape[1] - 1, srcField.get(srcShape[0] - 1, srcShape[1] - 1))
}

function handleArray (param, ctor) {
  if (Array.isArray(param)) {
    return [ ctor(param[0]), ctor(param[1]), ctor(param[2]) ]
  }
  return [ ctor(param), ctor(param), ctor(param) ]
}

function toColor (x) {
  if (Array.isArray(x)) {
    if (x.length === 3) {
      return [x[0], x[1], x[2], 1]
    }
    return [x[0], x[1], x[2], x[3]]
  }
  return [0, 0, 0, 1]
}

function handleColor (param) {
  if (Array.isArray(param)) {
    if (Array.isArray(param)) {
      return [
        toColor(param[0]),
        toColor(param[1]),
        toColor(param[2]) ]
    } else {
      var c = toColor(param)
      return [
        c.slice(),
        c.slice(),
        c.slice() ]
    }
  }
}

proto.update = function (params) {
  params = params || {}

  this.objectOffset = params.objectOffset || this.objectOffset

  this.dirty = true

  if ('contourWidth' in params) {
    this.contourWidth = handleArray(params.contourWidth, Number)
  }
  if ('showContour' in params) {
    this.showContour = handleArray(params.showContour, Boolean)
  }
  if ('showSurface' in params) {
    this.showSurface = !!params.showSurface
  }
  if ('contourTint' in params) {
    this.contourTint = handleArray(params.contourTint, Boolean)
  }
  if ('contourColor' in params) {
    this.contourColor = handleColor(params.contourColor)
  }
  if ('contourProject' in params) {
    this.contourProject = handleArray(params.contourProject, function (x) {
      return handleArray(x, Boolean)
    })
  }
  if ('surfaceProject' in params) {
    this.surfaceProject = params.surfaceProject
  }
  if ('dynamicColor' in params) {
    this.dynamicColor = handleColor(params.dynamicColor)
  }
  if ('dynamicTint' in params) {
    this.dynamicTint = handleArray(params.dynamicTint, Number)
  }
  if ('dynamicWidth' in params) {
    this.dynamicWidth = handleArray(params.dynamicWidth, Number)
  }
  if ('opacity' in params) {
    this.opacity = params.opacity
  }
  if ('colorBounds' in params) {
    this.colorBounds = params.colorBounds
  }
  if ('vertexColor' in params) {
    this.vertexColor = params.vertexColor ? 1 : 0;
  }

  var field = params.field || (params.coords && params.coords[2]) || null
  var levelsChanged = false

  if (!field) {
    if (this._field[2].shape[0] || this._field[2].shape[2]) {
      field = this._field[2].lo(1, 1).hi(this._field[2].shape[0] - 2, this._field[2].shape[1] - 2)
    } else {
      field = this._field[2].hi(0, 0)
    }
  }

  // Update field
  if ('field' in params || 'coords' in params) {
    var fsize = (field.shape[0] + 2) * (field.shape[1] + 2)

    // Resize if necessary
    if (fsize > this._field[2].data.length) {
      pool.freeFloat(this._field[2].data)
      this._field[2].data = pool.mallocFloat(bits.nextPow2(fsize))
    }

    // Pad field
    this._field[2] = ndarray(this._field[2].data, [field.shape[0] + 2, field.shape[1] + 2])
    this.padField(this._field[2], field)

    // Save shape of field
    this.shape = field.shape.slice()
    var shape = this.shape

    // Resize coordinate fields if necessary
    for (var i = 0; i < 2; ++i) {
      if (this._field[2].size > this._field[i].data.length) {
        pool.freeFloat(this._field[i].data)
        this._field[i].data = pool.mallocFloat(this._field[2].size)
      }
      this._field[i] = ndarray(this._field[i].data, [shape[0] + 2, shape[1] + 2])
    }

    // Generate x/y coordinates
    if (params.coords) {
      var coords = params.coords
      if (!Array.isArray(coords) || coords.length !== 3) {
        throw new Error('gl-surface: invalid coordinates for x/y')
      }
      for (i = 0; i < 2; ++i) {
        var coord = coords[i]
        for (j = 0; j < 2; ++j) {
          if (coord.shape[j] !== shape[j]) {
            throw new Error('gl-surface: coords have incorrect shape')
          }
        }
        this.padField(this._field[i], coord)
      }
    } else if (params.ticks) {
      var ticks = params.ticks
      if (!Array.isArray(ticks) || ticks.length !== 2) {
        throw new Error('gl-surface: invalid ticks')
      }
      for (i = 0; i < 2; ++i) {
        var tick = ticks[i]
        if (Array.isArray(tick) || tick.length) {
          tick = ndarray(tick)
        }
        if (tick.shape[0] !== shape[i]) {
          throw new Error('gl-surface: invalid tick length')
        }
        // Make a copy view of the tick array
        var tick2 = ndarray(tick.data, shape)
        tick2.stride[i] = tick.stride[0]
        tick2.stride[i ^ 1] = 0

        // Fill in field array
        this.padField(this._field[i], tick2)
      }
    } else {
      for (i = 0; i < 2; ++i) {
        var offset = [0, 0]
        offset[i] = 1
        this._field[i] = ndarray(this._field[i].data, [shape[0] + 2, shape[1] + 2], offset, 0)
      }
      this._field[0].set(0, 0, 0)
      for (var j = 0; j < shape[0]; ++j) {
        this._field[0].set(j + 1, 0, j)
      }
      this._field[0].set(shape[0] + 1, 0, shape[0] - 1)
      this._field[1].set(0, 0, 0)
      for (j = 0; j < shape[1]; ++j) {
        this._field[1].set(0, j + 1, j)
      }
      this._field[1].set(0, shape[1] + 1, shape[1] - 1)
    }

    // Save shape
    var fields = this._field

    // Compute surface normals
    var dfields = ndarray(pool.mallocFloat(fields[2].size * 3 * 2), [3, shape[0] + 2, shape[1] + 2, 2])
    for (i = 0; i < 3; ++i) {
      gradient(dfields.pick(i), fields[i], 'mirror')
    }
    var normals = ndarray(pool.mallocFloat(fields[2].size * 3), [shape[0] + 2, shape[1] + 2, 3])
    for (i = 0; i < shape[0] + 2; ++i) {
      for (j = 0; j < shape[1] + 2; ++j) {
        var dxdu = dfields.get(0, i, j, 0)
        var dxdv = dfields.get(0, i, j, 1)
        var dydu = dfields.get(1, i, j, 0)
        var dydv = dfields.get(1, i, j, 1)
        var dzdu = dfields.get(2, i, j, 0)
        var dzdv = dfields.get(2, i, j, 1)

        var nx = dydu * dzdv - dydv * dzdu
        var ny = dzdu * dxdv - dzdv * dxdu
        var nz = dxdu * dydv - dxdv * dydu

        var nl = Math.sqrt(nx * nx + ny * ny + nz * nz)
        if (nl < 1e-8) {
          nl = Math.max(Math.abs(nx), Math.abs(ny), Math.abs(nz))
          if (nl < 1e-8) {
            nz = 1.0
            ny = nx = 0.0
            nl = 1.0
          } else {
            nl = 1.0 / nl
          }
        } else {
          nl = 1.0 / Math.sqrt(nl)
        }

        normals.set(i, j, 0, nx * nl)
        normals.set(i, j, 1, ny * nl)
        normals.set(i, j, 2, nz * nl)
      }
    }
    pool.free(dfields.data)

    // Initialize surface
    var lo = [ Infinity, Infinity, Infinity ]
    var hi = [ -Infinity, -Infinity, -Infinity ]
    var lo_intensity = Infinity
    var hi_intensity = -Infinity
    var count = (shape[0] - 1) * (shape[1] - 1) * 6
    var tverts = pool.mallocFloat(bits.nextPow2(10 * count))
    var tptr = 0
    var vertexCount = 0
    for (i = 0; i < shape[0] - 1; ++i) {
      j_loop:
      for (j = 0; j < shape[1] - 1; ++j) {
        // Test for NaNs
        for (var dx = 0; dx < 2; ++dx) {
          for (var dy = 0; dy < 2; ++dy) {
            for (var k = 0; k < 3; ++k) {
              var f = this._field[k].get(1 + i + dx, 1 + j + dy)
              if (isNaN(f) || !isFinite(f)) {
                continue j_loop
              }
            }
          }
        }
        for (k = 0; k < 6; ++k) {
          var r = i + QUAD[k][0]
          var c = j + QUAD[k][1]

          var tx = this._field[0].get(r + 1, c + 1)
          var ty = this._field[1].get(r + 1, c + 1)
          f =      this._field[2].get(r + 1, c + 1)

          nx = normals.get(r + 1, c + 1, 0)
          ny = normals.get(r + 1, c + 1, 1)
          nz = normals.get(r + 1, c + 1, 2)

          if (params.intensity) {
            vf = params.intensity.get(r, c)
          }

          var vf = (params.intensity) ?
            params.intensity.get(r, c) :
            f + this.objectOffset[2];

          tverts[tptr++] = r
          tverts[tptr++] = c
          tverts[tptr++] = tx
          tverts[tptr++] = ty
          tverts[tptr++] = f
          tverts[tptr++] = 0
          tverts[tptr++] = vf
          tverts[tptr++] = nx
          tverts[tptr++] = ny
          tverts[tptr++] = nz

          lo[0] = Math.min(lo[0], tx + this.objectOffset[0])
          lo[1] = Math.min(lo[1], ty + this.objectOffset[1])
          lo[2] = Math.min(lo[2], f  + this.objectOffset[2])
          lo_intensity = Math.min(lo_intensity, vf)

          hi[0] = Math.max(hi[0], tx + this.objectOffset[0])
          hi[1] = Math.max(hi[1], ty + this.objectOffset[1])
          hi[2] = Math.max(hi[2], f  + this.objectOffset[2])
          hi_intensity = Math.max(hi_intensity, vf)

          vertexCount += 1
        }
      }
    }

    if (params.intensityBounds) {
      lo_intensity = +params.intensityBounds[0]
      hi_intensity = +params.intensityBounds[1]
    }

    // Scale all vertex intensities
    for (i = 6; i < tptr; i += 10) {
      tverts[i] = (tverts[i] - lo_intensity) / (hi_intensity - lo_intensity)
    }

    this._vertexCount = vertexCount
    this._coordinateBuffer.update(tverts.subarray(0, tptr))
    pool.freeFloat(tverts)
    pool.free(normals.data)

    // Update bounds
    this.bounds = [lo, hi]

    // Save intensity
    this.intensity = params.intensity || this._field[2]

    if(this.intensityBounds[0] !== lo_intensity || this.intensityBounds[1] !== hi_intensity) {
        levelsChanged = true
    }

    // Save intensity bound
    this.intensityBounds = [lo_intensity, hi_intensity]
  }

  // Update level crossings
  if ('levels' in params) {
    var levels = params.levels
    if (!Array.isArray(levels[0])) {
      levels = [ [], [], levels ]
    } else {
      levels = levels.slice()
    }
    for (i = 0; i < 3; ++i) {
      levels[i] = levels[i].slice()
      levels.sort(function (a, b) {
        return a - b
      })
    }
    for (i = 0; i < 3; ++i) {
      for (j = 0; j < levels[i].length; ++j) {
        levels[i][j] -= this.objectOffset[i]
      }
    }
    change_test:
    for (i = 0; i < 3; ++i) {
      if (levels[i].length !== this.contourLevels[i].length) {
        levelsChanged = true
        break
      }
      for (j = 0; j < levels[i].length; ++j) {
        if (levels[i][j] !== this.contourLevels[i][j]) {
          levelsChanged = true
          break change_test
        }
      }
    }
    this.contourLevels = levels
  }

  if (levelsChanged) {
    fields = this._field
    shape = this.shape

    // Update contour lines
    var contourVerts = []

    for (var dim = 0; dim < 3; ++dim) {
      levels = this.contourLevels[dim]
      var levelOffsets = []
      var levelCounts = []

      var parts = [0, 0, 0]

      for (i = 0; i < levels.length; ++i) {
        var graph = surfaceNets(this._field[dim], levels[i])

        levelOffsets.push((contourVerts.length / 5) | 0)
        vertexCount = 0

        edge_loop:
        for (j = 0; j < graph.cells.length; ++j) {
          var e = graph.cells[j]
          for (k = 0; k < 2; ++k) {
            var p = graph.positions[e[k]]

            var x = p[0]
            var ix = Math.floor(x) | 0
            var fx = x - ix

            var y = p[1]
            var iy = Math.floor(y) | 0
            var fy = y - iy

            var hole = false
            axis_loop:
            for (var axis = 0; axis < 3; ++axis) {
              parts[axis] = 0.0
              var iu = (dim + axis + 1) % 3
              for (dx = 0; dx < 2; ++dx) {
                var s = dx ? fx : 1.0 - fx
                r = Math.min(Math.max(ix + dx, 0), shape[0]) | 0
                for (dy = 0; dy < 2; ++dy) {
                  var t = dy ? fy : 1.0 - fy
                  c = Math.min(Math.max(iy + dy, 0), shape[1]) | 0

                  if (axis < 2) {
                    f = this._field[iu].get(r, c)
                  } else {
                    f = (this.intensity.get(r, c) - this.intensityBounds[0]) / (this.intensityBounds[1] - this.intensityBounds[0])
                  }
                  if (!isFinite(f) || isNaN(f)) {
                    hole = true
                    break axis_loop
                  }

                  var w = s * t
                  parts[axis] += w * f
                }
              }
            }

            if (!hole) {
              contourVerts.push(
                parts[0],
                parts[1],
                p[0],
                p[1],
                parts[2]
              )
              vertexCount += 1
            } else {
              if (k > 0) {
                // If we already added first edge, pop off verts
                for (var l = 0; l < 5; ++l) {
                  contourVerts.pop()
                }
                vertexCount -= 1
              }
              continue edge_loop
            }
          }
        }
        levelCounts.push(vertexCount)
      }

      // Store results
      this._contourOffsets[dim] = levelOffsets
      this._contourCounts[dim] = levelCounts

    }

    var floatBuffer = pool.mallocFloat(contourVerts.length)
    for (i = 0; i < contourVerts.length; ++i) {
      floatBuffer[i] = contourVerts[i]
    }
    this._contourBuffer.update(floatBuffer)
    pool.freeFloat(floatBuffer)
  }

  if (params.colormap) {
    this._colorMap.setPixels(genColormap(params.colormap))
  }
}

proto.dispose = function () {
  this._shader.dispose()
  this._vao.dispose()
  this._coordinateBuffer.dispose()
  this._colorMap.dispose()
  this._contourBuffer.dispose()
  this._contourVAO.dispose()
  this._contourShader.dispose()
  this._contourPickShader.dispose()
  this._dynamicBuffer.dispose()
  this._dynamicVAO.dispose()
  for (var i = 0; i < 3; ++i) {
    pool.freeFloat(this._field[i].data)
  }
}

proto.highlight = function (selection) {
  var i

  if (!selection) {
    this._dynamicCounts = [0, 0, 0]
    this.dyanamicLevel = [NaN, NaN, NaN]
    this.highlightLevel = [-1, -1, -1]
    return
  }

  for (i = 0; i < 3; ++i) {
    if (this.enableHighlight[i]) {
      this.highlightLevel[i] = selection.level[i]
    } else {
      this.highlightLevel[i] = -1
    }
  }

  var levels
  if (this.snapToData) {
    levels = selection.dataCoordinate
  } else {
    levels = selection.position
  }
  for (i = 0; i < 3; ++i) {
    levels[i] -= this.objectOffset[i]
  }
  if ((!this.enableDynamic[0] || levels[0] === this.dynamicLevel[0]) &&
    (!this.enableDynamic[1] || levels[1] === this.dynamicLevel[1]) &&
    (!this.enableDynamic[2] || levels[2] === this.dynamicLevel[2])) {
    return
  }

  var vertexCount = 0
  var shape = this.shape
  var scratchBuffer = pool.mallocFloat(12 * shape[0] * shape[1])

  for (var d = 0; d < 3; ++d) {
    if (!this.enableDynamic[d]) {
      this.dynamicLevel[d] = NaN
      this._dynamicCounts[d] = 0
      continue
    }

    this.dynamicLevel[d] = levels[d]

    var u = (d + 1) % 3
    var v = (d + 2) % 3

    var f = this._field[d]
    var g = this._field[u]
    var h = this._field[v]

    var graph = surfaceNets(f, levels[d])
    var edges = graph.cells
    var positions = graph.positions

    this._dynamicOffsets[d] = vertexCount

    for (i = 0; i < edges.length; ++i) {
      var e = edges[i]
      for (var j = 0; j < 2; ++j) {
        var p = positions[e[j]]

        var x = +p[0]
        var ix = x | 0
        var jx = Math.min(ix + 1, shape[0]) | 0
        var fx = x - ix
        var hx = 1.0 - fx

        var y = +p[1]
        var iy = y | 0
        var jy = Math.min(iy + 1, shape[1]) | 0
        var fy = y - iy
        var hy = 1.0 - fy

        var w00 = hx * hy
        var w01 = hx * fy
        var w10 = fx * hy
        var w11 = fx * fy

        var cu = w00 * g.get(ix, iy) +
          w01 * g.get(ix, jy) +
          w10 * g.get(jx, iy) +
          w11 * g.get(jx, jy)

        var cv = w00 * h.get(ix, iy) +
          w01 * h.get(ix, jy) +
          w10 * h.get(jx, iy) +
          w11 * h.get(jx, jy)

        if (isNaN(cu) || isNaN(cv)) {
          if (j) {
            vertexCount -= 1
          }
          break
        }

        scratchBuffer[2 * vertexCount + 0] = cu
        scratchBuffer[2 * vertexCount + 1] = cv

        vertexCount += 1
      }
    }

    this._dynamicCounts[d] = vertexCount - this._dynamicOffsets[d]
  }

  this._dynamicBuffer.update(scratchBuffer.subarray(0, 2 * vertexCount))
  pool.freeFloat(scratchBuffer)
}

function createSurfacePlot (params) {
  var gl = params.gl

  var shader = createShader(gl)
  var pickShader = createPickShader(gl)
  var contourShader = createContourShader(gl)
  var contourPickShader = createPickContourShader(gl)

  var coordinateBuffer = createBuffer(gl)
  var vao = createVAO(gl, [
    { buffer: coordinateBuffer,
      size: 4,
      stride: SURFACE_VERTEX_SIZE,
      offset: 0
    },
    { buffer: coordinateBuffer,
      size: 3,
      stride: SURFACE_VERTEX_SIZE,
      offset: 16
    },
    {
      buffer: coordinateBuffer,
      size: 3,
      stride: SURFACE_VERTEX_SIZE,
      offset: 28
    }
  ])

  var contourBuffer = createBuffer(gl)
  var contourVAO = createVAO(gl, [
    {
      buffer: contourBuffer,
      size: 4,
      stride: 20,
      offset: 0
    },
    {
      buffer: contourBuffer,
      size: 1,
      stride: 20,
      offset: 16
    }
  ])

  var dynamicBuffer = createBuffer(gl)
  var dynamicVAO = createVAO(gl, [
    {
      buffer: dynamicBuffer,
      size: 2,
      type: gl.FLOAT
    }])

  var cmap = createTexture(gl, 1, N_COLORS, gl.RGBA, gl.UNSIGNED_BYTE)
  cmap.minFilter = gl.LINEAR
  cmap.magFilter = gl.LINEAR

  var surface = new SurfacePlot(
    gl,
    [0, 0], // shape
    [[0, 0, 0], [0, 0, 0]], // bounds
    shader,
    pickShader,
    coordinateBuffer,
    vao,
    cmap,
    contourShader,
    contourPickShader,
    contourBuffer,
    contourVAO,
    dynamicBuffer,
    dynamicVAO,
    [0, 0, 0] // objectOffset
  )

  var nparams = {
    levels: [[], [], []]
  }
  for (var id in params) {
    nparams[id] = params[id]
  }
  nparams.colormap = nparams.colormap || 'jet'

  surface.update(nparams)

  return surface
}

},{"./lib/shaders":307,"binary-search-bounds":308,"bit-twiddle":80,"colormap":114,"gl-buffer":234,"gl-mat4/invert":258,"gl-mat4/multiply":260,"gl-texture2d":311,"gl-vao":316,"ndarray":439,"ndarray-gradient":430,"ndarray-ops":433,"ndarray-pack":434,"surface-nets":512,"typedarray-pool":526}],310:[function(_dereq_,module,exports){
'use strict'

var Font = _dereq_('css-font')
var pick = _dereq_('pick-by-alias')
var createRegl = _dereq_('regl')
var createGl = _dereq_('gl-util/context')
var WeakMap = _dereq_('es6-weak-map')
var rgba = _dereq_('color-normalize')
var fontAtlas = _dereq_('font-atlas')
var pool = _dereq_('typedarray-pool')
var parseRect = _dereq_('parse-rect')
var isObj = _dereq_('is-plain-obj')
var parseUnit = _dereq_('parse-unit')
var px = _dereq_('to-px')
var kerning = _dereq_('detect-kerning')
var extend = _dereq_('object-assign')
var metrics = _dereq_('font-measure')
var flatten = _dereq_('flatten-vertex-data')
var ref = _dereq_('bit-twiddle');
var nextPow2 = ref.nextPow2;

var shaderCache = new WeakMap


// Safari does not support font-stretch
var isStretchSupported = false
if (document.body) {
    var el = document.body.appendChild(document.createElement('div'))
    el.style.font = 'italic small-caps bold condensed 16px/2 cursive'
    if (getComputedStyle(el).fontStretch) {
        isStretchSupported = true
    }
    document.body.removeChild(el)
}

var GlText = function GlText (o) {
	if (isRegl(o)) {
		o = {regl: o}
		this.gl = o.regl._gl
	}
	else {
		this.gl = createGl(o)
	}

	this.shader = shaderCache.get(this.gl)

	if (!this.shader) {
		this.regl = o.regl || createRegl({ gl: this.gl })
	}
	else {
		this.regl = this.shader.regl
	}

	this.charBuffer = this.regl.buffer({ type: 'uint8', usage: 'stream' })
	this.sizeBuffer = this.regl.buffer({ type: 'float', usage: 'stream' })

	if (!this.shader) {
		this.shader = this.createShader()
		shaderCache.set(this.gl, this.shader)
	}

	this.batch = []

	// multiple options initial state
	this.fontSize = []
	this.font = []
	this.fontAtlas = []

	this.draw = this.shader.draw.bind(this)
	this.render = function () {
		// FIXME: add Safari regl report here:
		// charBuffer and width just do not trigger
		this.regl._refresh()
		this.draw(this.batch)
	}
	this.canvas = this.gl.canvas

	this.update(isObj(o) ? o : {})
};

GlText.prototype.createShader = function createShader () {
	var regl = this.regl

	// FIXME: store 2 shader versions: with normal viewport and without
	// draw texture method
	var draw = regl({
		blend: {
			enable: true,
			color: [0,0,0,1],

			func: {
				srcRGB: 'src alpha',
				dstRGB: 'one minus src alpha',
				srcAlpha: 'one minus dst alpha',
				dstAlpha: 'one'
			}
		},
		stencil: {enable: false},
		depth: {enable: false},

		count: regl.prop('count'),
		offset: regl.prop('offset'),
		attributes: {
			charOffset: {
				offset: 4,
				stride: 8,
				buffer: regl.this('sizeBuffer')
			},
			width: {
				offset: 0,
				stride: 8,
				buffer: regl.this('sizeBuffer')
			},
			char: regl.this('charBuffer'),
			position: regl.this('position')
		},
		uniforms: {
			atlasSize: function (c, p) { return [p.atlas.width, p.atlas.height]; },
			atlasDim: function (c, p) { return [p.atlas.cols, p.atlas.rows]; },
			atlas: function (c, p) { return p.atlas.texture; },
			charStep: function (c, p) { return p.atlas.step; },
			em: function (c, p) { return p.atlas.em; },
			color: regl.prop('color'),
			opacity: regl.prop('opacity'),
			viewport: regl.this('viewportArray'),
			scale: regl.this('scale'),
			align: regl.prop('align'),
			baseline: regl.prop('baseline'),
			translate: regl.this('translate'),
			positionOffset: regl.prop('positionOffset')
		},
		primitive: 'points',
		viewport: regl.this('viewport'),

		vert: ("\n\t\t\tprecision highp float;\n\t\t\tattribute float width, charOffset, char;\n\t\t\tattribute vec2 position;\n\t\t\tuniform float fontSize, charStep, em, align, baseline;\n\t\t\tuniform vec4 viewport;\n\t\t\tuniform vec4 color;\n\t\t\tuniform vec2 atlasSize, atlasDim, scale, translate, positionOffset;\n\t\t\tvarying vec2 charCoord, charId;\n\t\t\tvarying float charWidth;\n\t\t\tvarying vec4 fontColor;\n\t\t\tvoid main () {\n\t\t\t\t" + (!GlText.normalViewport ? 'vec2 positionOffset = vec2(positionOffset.x,- positionOffset.y);' : '') + "\n\n\t\t\t\tvec2 offset = floor(em * (vec2(align + charOffset, baseline)\n\t\t\t\t\t+ positionOffset))\n\t\t\t\t\t/ (viewport.zw * scale.xy);\n\n\t\t\t\tvec2 position = (position + translate) * scale;\n\t\t\t\tposition += offset * scale;\n\n\t\t\t\t" + (GlText.normalViewport ? 'position.y = 1. - position.y;' : '') + "\n\n\t\t\t\tcharCoord = position * viewport.zw + viewport.xy;\n\n\t\t\t\tgl_Position = vec4(position * 2. - 1., 0, 1);\n\n\t\t\t\tgl_PointSize = charStep;\n\n\t\t\t\tcharId.x = mod(char, atlasDim.x);\n\t\t\t\tcharId.y = floor(char / atlasDim.x);\n\n\t\t\t\tcharWidth = width * em;\n\n\t\t\t\tfontColor = color / 255.;\n\t\t\t}"),

		frag: "\n\t\t\tprecision highp float;\n\t\t\tuniform sampler2D atlas;\n\t\t\tuniform float fontSize, charStep, opacity;\n\t\t\tuniform vec2 atlasSize;\n\t\t\tuniform vec4 viewport;\n\t\t\tvarying vec4 fontColor;\n\t\t\tvarying vec2 charCoord, charId;\n\t\t\tvarying float charWidth;\n\n\t\t\tfloat lightness(vec4 color) {\n\t\t\t\treturn color.r * 0.299 + color.g * 0.587 + color.b * 0.114;\n\t\t\t}\n\n\t\t\tvoid main () {\n\t\t\t\tvec2 uv = gl_FragCoord.xy - charCoord + charStep * .5;\n\t\t\t\tfloat halfCharStep = floor(charStep * .5 + .5);\n\n\t\t\t\t// invert y and shift by 1px (FF expecially needs that)\n\t\t\t\tuv.y = charStep - uv.y;\n\n\t\t\t\t// ignore points outside of character bounding box\n\t\t\t\tfloat halfCharWidth = ceil(charWidth * .5);\n\t\t\t\tif (floor(uv.x) > halfCharStep + halfCharWidth ||\n\t\t\t\t\tfloor(uv.x) < halfCharStep - halfCharWidth) return;\n\n\t\t\t\tuv += charId * charStep;\n\t\t\t\tuv = uv / atlasSize;\n\n\t\t\t\tvec4 color = fontColor;\n\t\t\t\tvec4 mask = texture2D(atlas, uv);\n\n\t\t\t\tfloat maskY = lightness(mask);\n\t\t\t\t// float colorY = lightness(color);\n\t\t\t\tcolor.a *= maskY;\n\t\t\t\tcolor.a *= opacity;\n\n\t\t\t\t// color.a += .1;\n\n\t\t\t\t// antialiasing, see yiq color space y-channel formula\n\t\t\t\t// color.rgb += (1. - color.rgb) * (1. - mask.rgb);\n\n\t\t\t\tgl_FragColor = color;\n\t\t\t}"
	})

	// per font-size atlas
	var atlas = {}

	return { regl: regl, draw: draw, atlas: atlas }
};

GlText.prototype.update = function update (o) {
		var this$1 = this;

	if (typeof o === 'string') { o = { text: o } }
	else if (!o) { return }

	// FIXME: make this a static transform or more general approact
	o = pick(o, {
		position: 'position positions coord coords coordinates',
		font: 'font fontFace fontface typeface cssFont css-font family fontFamily',
		fontSize: 'fontSize fontsize size font-size',
		text: 'text texts chars characters value values symbols',
		align: 'align alignment textAlign textbaseline',
		baseline: 'baseline textBaseline textbaseline',
		direction: 'dir direction textDirection',
		color: 'color colour fill fill-color fillColor textColor textcolor',
		kerning: 'kerning kern',
		range: 'range dataBox',
		viewport: 'vp viewport viewBox viewbox viewPort',
		opacity: 'opacity alpha transparency visible visibility opaque',
		offset: 'offset positionOffset padding shift indent indentation'
	}, true)


	if (o.opacity != null) {
		if (Array.isArray(o.opacity)) {
			this.opacity = o.opacity.map(function (o) { return parseFloat(o); })
		}
		else {
			this.opacity = parseFloat(o.opacity)
		}
	}

	if (o.viewport != null) {
		this.viewport = parseRect(o.viewport)

		if (GlText.normalViewport) {
			this.viewport.y = this.canvas.height - this.viewport.y - this.viewport.height
		}

		this.viewportArray = [this.viewport.x, this.viewport.y, this.viewport.width, this.viewport.height]

	}
	if (this.viewport == null) {
		this.viewport = {
			x: 0, y: 0,
			width: this.gl.drawingBufferWidth,
			height: this.gl.drawingBufferHeight
		}
		this.viewportArray = [this.viewport.x, this.viewport.y, this.viewport.width, this.viewport.height]
	}

	if (o.kerning != null) { this.kerning = o.kerning }

	if (o.offset != null) {
		if (typeof o.offset === 'number') { o.offset = [o.offset, 0] }

		this.positionOffset = flatten(o.offset)
	}

	if (o.direction) { this.direction = o.direction }

	if (o.range) {
		this.range = o.range
		this.scale = [1 / (o.range[2] - o.range[0]), 1 / (o.range[3] - o.range[1])]
		this.translate = [-o.range[0], -o.range[1]]
	}
	if (o.scale) { this.scale = o.scale }
	if (o.translate) { this.translate = o.translate }

	// default scale corresponds to viewport
	if (!this.scale) { this.scale = [1 / this.viewport.width, 1 / this.viewport.height] }

	if (!this.translate) { this.translate = [0, 0] }

	if (!this.font.length && !o.font) { o.font = GlText.baseFontSize + 'px sans-serif' }

	// normalize font caching string
	var newFont = false, newFontSize = false

	// obtain new font data
	if (o.font) {
		(Array.isArray(o.font) ? o.font : [o.font]).forEach(function (font, i) {
			// normalize font
			if (typeof font === 'string') {
				try {
					font = Font.parse(font)
				} catch (e) {
					font = Font.parse(GlText.baseFontSize + 'px ' + font)
				}
			}
			else { font = Font.parse(Font.stringify(font)) }

			var baseString = Font.stringify({
				size: GlText.baseFontSize,
				family: font.family,
				stretch: isStretchSupported ? font.stretch : undefined,
				variant: font.variant,
				weight: font.weight,
				style: font.style
			})

			var unit = parseUnit(font.size)
			var fs = Math.round(unit[0] * px(unit[1]))
			if (fs !== this$1.fontSize[i]) {
				newFontSize = true
				this$1.fontSize[i] = fs
			}

			// calc new font metrics/atlas
			if (!this$1.font[i] || baseString != this$1.font[i].baseString) {
				newFont = true

				// obtain font cache or create one
				this$1.font[i] = GlText.fonts[baseString]
				if (!this$1.font[i]) {
					var family = font.family.join(', ')
					var style = [font.style]
					if (font.style != font.variant) { style.push(font.variant) }
					if (font.variant != font.weight) { style.push(font.weight) }
					if (isStretchSupported && font.weight != font.stretch) { style.push(font.stretch) }

					this$1.font[i] = {
						baseString: baseString,

						// typeface
						family: family,
						weight: font.weight,
						stretch: font.stretch,
						style: font.style,
						variant: font.variant,

						// widths of characters
						width: {},

						// kernin pairs offsets
						kerning: {},

						metrics: metrics(family, {
							origin: 'top',
							fontSize: GlText.baseFontSize,
							fontStyle: style.join(' ')
						})
					}

					GlText.fonts[baseString] = this$1.font[i]
				}
			}
		})
	}

	// FIXME: make independend font-size
	// if (o.fontSize) {
	// let unit = parseUnit(o.fontSize)
	// let fs = Math.round(unit[0] * px(unit[1]))

	// if (fs != this.fontSize) {
	// 	newFontSize = true
	// 	this.fontSize = fs
	// }
	// }

	if (newFont || newFontSize) {
		this.font.forEach(function (font, i) {
			var fontString = Font.stringify({
				size: this$1.fontSize[i],
				family: font.family,
				stretch: isStretchSupported ? font.stretch : undefined,
				variant: font.variant,
				weight: font.weight,
				style: font.style
			})

			// calc new font size atlas
			this$1.fontAtlas[i] = this$1.shader.atlas[fontString]

			if (!this$1.fontAtlas[i]) {
				var metrics = font.metrics

				this$1.shader.atlas[fontString] =
				this$1.fontAtlas[i] = {
					fontString: fontString,
					// even step is better for rendered characters
					step: Math.ceil(this$1.fontSize[i] * metrics.bottom * .5) * 2,
					em: this$1.fontSize[i],
					cols: 0,
					rows: 0,
					height: 0,
					width: 0,
					chars: [],
					ids: {},
					texture: this$1.regl.texture()
				}
			}

			// bump atlas characters
			if (o.text == null) { o.text = this$1.text }
		})
	}

	// if multiple positions - duplicate text arguments
	// FIXME: this possibly can be done better to avoid array spawn
	if (typeof o.text === 'string' && o.position && o.position.length > 2) {
		var textArray = Array(o.position.length * .5)
		for (var i = 0; i < textArray.length; i++) {
			textArray[i] = o.text
		}
		o.text = textArray
	}

	// calculate offsets for the new font/text
	var newAtlasChars
	if (o.text != null || newFont) {
		// FIXME: ignore spaces
		// text offsets within the text buffer
		this.textOffsets = [0]

		if (Array.isArray(o.text)) {
			this.count = o.text[0].length
			this.counts = [this.count]
			for (var i$1 = 1; i$1 < o.text.length; i$1++) {
				this$1.textOffsets[i$1] = this$1.textOffsets[i$1 - 1] + o.text[i$1 - 1].length
				this$1.count += o.text[i$1].length
				this$1.counts.push(o.text[i$1].length)
			}
			this.text = o.text.join('')
		}
		else {
			this.text = o.text
			this.count = this.text.length
			this.counts = [this.count]
		}

		newAtlasChars = []

		// detect & measure new characters
		this.font.forEach(function (font, idx) {
			GlText.atlasContext.font = font.baseString

			var atlas = this$1.fontAtlas[idx]

			for (var i = 0; i < this$1.text.length; i++) {
				var char = this$1.text.charAt(i)

				if (atlas.ids[char] == null) {
					atlas.ids[char] = atlas.chars.length
					atlas.chars.push(char)
					newAtlasChars.push(char)
				}

				if (font.width[char] == null) {
					font.width[char] = GlText.atlasContext.measureText(char).width / GlText.baseFontSize

					// measure kerning pairs for the new character
					if (this$1.kerning) {
						var pairs = []
						for (var baseChar in font.width) {
							pairs.push(baseChar + char, char + baseChar)
						}
						extend(font.kerning, kerning(font.family, {
							pairs: pairs
						}))
					}
				}
			}
		})
	}

	// create single position buffer (faster than batch or multiple separate instances)
	if (o.position) {
		if (o.position.length > 2) {
			var flat = !o.position[0].length
			var positionData = pool.mallocFloat(this.count * 2)
			for (var i$2 = 0, ptr = 0; i$2 < this.counts.length; i$2++) {
				var count = this$1.counts[i$2]
				if (flat) {
					for (var j = 0; j < count; j++) {
						positionData[ptr++] = o.position[i$2 * 2]
						positionData[ptr++] = o.position[i$2 * 2 + 1]
					}
				}
				else {
					for (var j$1 = 0; j$1 < count; j$1++) {
						positionData[ptr++] = o.position[i$2][0]
						positionData[ptr++] = o.position[i$2][1]
					}
				}
			}
			if (this.position.call) {
				this.position({
					type: 'float',
					data: positionData
				})
			} else {
				this.position = this.regl.buffer({
					type: 'float',
					data: positionData
				})
			}
			pool.freeFloat(positionData)
		}
		else {
			if (this.position.destroy) { this.position.destroy() }
			this.position = {
				constant: o.position
			}
		}
	}

	// populate text/offset buffers if font/text has changed
	// as [charWidth, offset, charWidth, offset...]
	// that is in em units since font-size can change often
	if (o.text || newFont) {
		var charIds = pool.mallocUint8(this.count)
		var sizeData = pool.mallocFloat(this.count * 2)
		this.textWidth = []

		for (var i$3 = 0, ptr$1 = 0; i$3 < this.counts.length; i$3++) {
			var count$1 = this$1.counts[i$3]
			var font = this$1.font[i$3] || this$1.font[0]
			var atlas = this$1.fontAtlas[i$3] || this$1.fontAtlas[0]

			for (var j$2 = 0; j$2 < count$1; j$2++) {
				var char = this$1.text.charAt(ptr$1)
				var prevChar = this$1.text.charAt(ptr$1 - 1)

				charIds[ptr$1] = atlas.ids[char]
				sizeData[ptr$1 * 2] = font.width[char]

				if (j$2) {
					var prevWidth = sizeData[ptr$1 * 2 - 2]
					var currWidth = sizeData[ptr$1 * 2]
					var prevOffset = sizeData[ptr$1 * 2 - 1]
					var offset = prevOffset + prevWidth * .5 + currWidth * .5;

					if (this$1.kerning) {
						var kerning$1 = font.kerning[prevChar + char]
						if (kerning$1) {
							offset += kerning$1 * 1e-3
						}
					}

					sizeData[ptr$1 * 2 + 1] = offset
				}
				else {
					sizeData[ptr$1 * 2 + 1] = sizeData[ptr$1 * 2] * .5
				}

				ptr$1++
			}
			this$1.textWidth.push(
				!sizeData.length ? 0 :
				// last offset + half last width
				sizeData[ptr$1 * 2 - 2] * .5 + sizeData[ptr$1 * 2 - 1]
			)
		}


		// bump recalc align offset
		if (!o.align) { o.align = this.align }
		this.charBuffer({data: charIds, type: 'uint8', usage: 'stream'})
		this.sizeBuffer({data: sizeData, type: 'float', usage: 'stream'})
		pool.freeUint8(charIds)
		pool.freeFloat(sizeData)

		// udpate font atlas and texture
		if (newAtlasChars.length) {
			this.font.forEach(function (font, i) {
				var atlas = this$1.fontAtlas[i]

				// FIXME: insert metrics-based ratio here
				var step = atlas.step

				var maxCols = Math.floor(GlText.maxAtlasSize / step)
				var cols = Math.min(maxCols, atlas.chars.length)
				var rows = Math.ceil(atlas.chars.length / cols)

				var atlasWidth = nextPow2( cols * step )
				// let atlasHeight = Math.min(rows * step + step * .5, GlText.maxAtlasSize);
				var atlasHeight = nextPow2( rows * step );

				atlas.width = atlasWidth
				atlas.height = atlasHeight;
				atlas.rows = rows
				atlas.cols = cols

				if (!atlas.em) { return }

				atlas.texture({
					data: fontAtlas({
						canvas: GlText.atlasCanvas,
						font: atlas.fontString,
						chars: atlas.chars,
						shape: [atlasWidth, atlasHeight],
						step: [step, step]
					})
				})

			})
		}
	}

	if (o.align) {
		this.align = o.align
		this.alignOffset = this.textWidth.map(function (textWidth, i) {
			var align = !Array.isArray(this$1.align) ? this$1.align : this$1.align.length > 1 ? this$1.align[i] : this$1.align[0]

			if (typeof align === 'number') { return align }
			switch (align) {
				case 'right':
				case 'end':
					return -textWidth
				case 'center':
				case 'centre':
				case 'middle':
					return -textWidth * .5
			}

			return 0
		})
	}

	if (this.baseline == null && o.baseline == null) {
		o.baseline = 0
	}
	if (o.baseline != null) {
		this.baseline = o.baseline
		if (!Array.isArray(this.baseline)) { this.baseline = [this.baseline] }
		this.baselineOffset = this.baseline.map(function (baseline, i) {
			var m = (this$1.font[i] || this$1.font[0]).metrics
			var base = 0

			base += m.bottom * .5

			if (typeof baseline === 'number') {
				base += (baseline - m.baseline)
			}
			else {
				base += -m[baseline]
			}

			if (!GlText.normalViewport) { base *= -1 }
			return base
		})
	}

	// flatten colors to a single uint8 array
	if (o.color != null) {
		if (!o.color) { o.color = 'transparent' }

		// single color
		if (typeof o.color === 'string' || !isNaN(o.color)) {
			this.color = rgba(o.color, 'uint8')
		}
		// array
		else {
			var colorData

			// flat array
			if (typeof o.color[0] === 'number' && o.color.length > this.counts.length) {
				var l = o.color.length
				colorData = pool.mallocUint8(l)
				var sub = (o.color.subarray || o.color.slice).bind(o.color)
				for (var i$4 = 0; i$4 < l; i$4 += 4) {
					colorData.set(rgba(sub(i$4, i$4 + 4), 'uint8'), i$4)
				}
			}
			// nested array
			else {
				var l$1 = o.color.length
				colorData = pool.mallocUint8(l$1 * 4)
				for (var i$5 = 0; i$5 < l$1; i$5++) {
					colorData.set(rgba(o.color[i$5] || 0, 'uint8'), i$5 * 4)
				}
			}

			this.color = colorData
		}
	}

	// update render batch
	if (o.position || o.text || o.color || o.baseline || o.align || o.font || o.offset || o.opacity) {
		var isBatch = (this.color.length > 4)
			|| (this.baselineOffset.length > 1)
			|| (this.align && this.align.length > 1)
			|| (this.fontAtlas.length > 1)
			|| (this.positionOffset.length > 2)
		if (isBatch) {
			var length = Math.max(
				this.position.length * .5 || 0,
				this.color.length * .25 || 0,
				this.baselineOffset.length || 0,
				this.alignOffset.length || 0,
				this.font.length || 0,
				this.opacity.length || 0,
				this.positionOffset.length * .5 || 0
			)
			this.batch = Array(length)
			for (var i$6 = 0; i$6 < this.batch.length; i$6++) {
				this$1.batch[i$6] = {
					count: this$1.counts.length > 1 ? this$1.counts[i$6] : this$1.counts[0],
					offset: this$1.textOffsets.length > 1 ? this$1.textOffsets[i$6] : this$1.textOffsets[0],
					color: !this$1.color ? [0,0,0,255] : this$1.color.length <= 4 ? this$1.color : this$1.color.subarray(i$6 * 4, i$6 * 4 + 4),
					opacity: Array.isArray(this$1.opacity) ? this$1.opacity[i$6] : this$1.opacity,
					baseline: this$1.baselineOffset[i$6] != null ? this$1.baselineOffset[i$6] : this$1.baselineOffset[0],
					align: !this$1.align ? 0 : this$1.alignOffset[i$6] != null ? this$1.alignOffset[i$6] : this$1.alignOffset[0],
					atlas: this$1.fontAtlas[i$6] || this$1.fontAtlas[0],
					positionOffset: this$1.positionOffset.length > 2 ? this$1.positionOffset.subarray(i$6 * 2, i$6 * 2 + 2) : this$1.positionOffset
				}
			}
		}
		// single-color, single-baseline, single-align batch is faster to render
		else {
			if (this.count) {
				this.batch = [{
					count: this.count,
					offset: 0,
					color: this.color || [0,0,0,255],
					opacity: Array.isArray(this.opacity) ? this.opacity[0] : this.opacity,
					baseline: this.baselineOffset[0],
					align: this.alignOffset ? this.alignOffset[0] : 0,
					atlas: this.fontAtlas[0],
					positionOffset: this.positionOffset
				}]
			}
			else {
				this.batch = []
			}
		}
	}
};

GlText.prototype.destroy = function destroy () {
	// TODO: count instances of atlases and destroy all on null
};


// defaults
GlText.prototype.kerning = true
GlText.prototype.position = { constant: new Float32Array(2) }
GlText.prototype.translate = null
GlText.prototype.scale = null
GlText.prototype.font = null
GlText.prototype.text = ''
GlText.prototype.positionOffset = [0, 0]
GlText.prototype.opacity = 1
GlText.prototype.color = new Uint8Array([0, 0, 0, 255])
GlText.prototype.alignOffset = [0, 0]


// whether viewport should be top↓bottom 2d one (true) or webgl one (false)
GlText.normalViewport = false

// size of an atlas
GlText.maxAtlasSize = 1024

// font atlas canvas is singleton
GlText.atlasCanvas = document.createElement('canvas')
GlText.atlasContext = GlText.atlasCanvas.getContext('2d', {alpha: false})

// font-size used for metrics, atlas step calculation
GlText.baseFontSize = 64

// fonts storage
GlText.fonts = {}

// max number of different font atlases/textures cached
// FIXME: enable atlas size limitation via LRU
// GlText.atlasCacheSize = 64

function isRegl (o) {
	return typeof o === 'function' &&
	o._gl &&
	o.prop &&
	o.texture &&
	o.buffer
}


module.exports = GlText


},{"bit-twiddle":80,"color-normalize":108,"css-font":127,"detect-kerning":154,"es6-weak-map":213,"flatten-vertex-data":220,"font-atlas":221,"font-measure":222,"gl-util/context":312,"is-plain-obj":411,"object-assign":443,"parse-rect":448,"parse-unit":450,"pick-by-alias":454,"regl":483,"to-px":520,"typedarray-pool":526}],311:[function(_dereq_,module,exports){
'use strict'

var ndarray = _dereq_('ndarray')
var ops     = _dereq_('ndarray-ops')
var pool    = _dereq_('typedarray-pool')

module.exports = createTexture2D

var linearTypes = null
var filterTypes = null
var wrapTypes   = null

function lazyInitLinearTypes(gl) {
  linearTypes = [
    gl.LINEAR,
    gl.NEAREST_MIPMAP_LINEAR,
    gl.LINEAR_MIPMAP_NEAREST,
    gl.LINEAR_MIPMAP_NEAREST
  ]
  filterTypes = [
    gl.NEAREST,
    gl.LINEAR,
    gl.NEAREST_MIPMAP_NEAREST,
    gl.NEAREST_MIPMAP_LINEAR,
    gl.LINEAR_MIPMAP_NEAREST,
    gl.LINEAR_MIPMAP_LINEAR
  ]
  wrapTypes = [
    gl.REPEAT,
    gl.CLAMP_TO_EDGE,
    gl.MIRRORED_REPEAT
  ]
}

function acceptTextureDOM (obj) {
  return (
    ('undefined' != typeof HTMLCanvasElement && obj instanceof HTMLCanvasElement) ||
    ('undefined' != typeof HTMLImageElement && obj instanceof HTMLImageElement) ||
    ('undefined' != typeof HTMLVideoElement && obj instanceof HTMLVideoElement) ||
    ('undefined' != typeof ImageData && obj instanceof ImageData))
}

var convertFloatToUint8 = function(out, inp) {
  ops.muls(out, inp, 255.0)
}

function reshapeTexture(tex, w, h) {
  var gl = tex.gl
  var maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE)
  if(w < 0 || w > maxSize || h < 0 || h > maxSize) {
    throw new Error('gl-texture2d: Invalid texture size')
  }
  tex._shape = [w, h]
  tex.bind()
  gl.texImage2D(gl.TEXTURE_2D, 0, tex.format, w, h, 0, tex.format, tex.type, null)
  tex._mipLevels = [0]
  return tex
}

function Texture2D(gl, handle, width, height, format, type) {
  this.gl = gl
  this.handle = handle
  this.format = format
  this.type = type
  this._shape = [width, height]
  this._mipLevels = [0]
  this._magFilter = gl.NEAREST
  this._minFilter = gl.NEAREST
  this._wrapS = gl.CLAMP_TO_EDGE
  this._wrapT = gl.CLAMP_TO_EDGE
  this._anisoSamples = 1

  var parent = this
  var wrapVector = [this._wrapS, this._wrapT]
  Object.defineProperties(wrapVector, [
    {
      get: function() {
        return parent._wrapS
      },
      set: function(v) {
        return parent.wrapS = v
      }
    },
    {
      get: function() {
        return parent._wrapT
      },
      set: function(v) {
        return parent.wrapT = v
      }
    }
  ])
  this._wrapVector = wrapVector

  var shapeVector = [this._shape[0], this._shape[1]]
  Object.defineProperties(shapeVector, [
    {
      get: function() {
        return parent._shape[0]
      },
      set: function(v) {
        return parent.width = v
      }
    },
    {
      get: function() {
        return parent._shape[1]
      },
      set: function(v) {
        return parent.height = v
      }
    }
  ])
  this._shapeVector = shapeVector
}

var proto = Texture2D.prototype

Object.defineProperties(proto, {
  minFilter: {
    get: function() {
      return this._minFilter
    },
    set: function(v) {
      this.bind()
      var gl = this.gl
      if(this.type === gl.FLOAT && linearTypes.indexOf(v) >= 0) {
        if(!gl.getExtension('OES_texture_float_linear')) {
          v = gl.NEAREST
        }
      }
      if(filterTypes.indexOf(v) < 0) {
        throw new Error('gl-texture2d: Unknown filter mode ' + v)
      }
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, v)
      return this._minFilter = v
    }
  },
  magFilter: {
    get: function() {
      return this._magFilter
    },
    set: function(v) {
      this.bind()
      var gl = this.gl
      if(this.type === gl.FLOAT && linearTypes.indexOf(v) >= 0) {
        if(!gl.getExtension('OES_texture_float_linear')) {
          v = gl.NEAREST
        }
      }
      if(filterTypes.indexOf(v) < 0) {
        throw new Error('gl-texture2d: Unknown filter mode ' + v)
      }
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, v)
      return this._magFilter = v
    }
  },
  mipSamples: {
    get: function() {
      return this._anisoSamples
    },
    set: function(i) {
      var psamples = this._anisoSamples
      this._anisoSamples = Math.max(i, 1)|0
      if(psamples !== this._anisoSamples) {
        var ext = this.gl.getExtension('EXT_texture_filter_anisotropic')
        if(ext) {
          this.gl.texParameterf(this.gl.TEXTURE_2D, ext.TEXTURE_MAX_ANISOTROPY_EXT, this._anisoSamples)
        }
      }
      return this._anisoSamples
    }
  },
  wrapS: {
    get: function() {
      return this._wrapS
    },
    set: function(v) {
      this.bind()
      if(wrapTypes.indexOf(v) < 0) {
        throw new Error('gl-texture2d: Unknown wrap mode ' + v)
      }
      this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, v)
      return this._wrapS = v
    }
  },
  wrapT: {
    get: function() {
      return this._wrapT
    },
    set: function(v) {
      this.bind()
      if(wrapTypes.indexOf(v) < 0) {
        throw new Error('gl-texture2d: Unknown wrap mode ' + v)
      }
      this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, v)
      return this._wrapT = v
    }
  },
  wrap: {
    get: function() {
      return this._wrapVector
    },
    set: function(v) {
      if(!Array.isArray(v)) {
        v = [v,v]
      }
      if(v.length !== 2) {
        throw new Error('gl-texture2d: Must specify wrap mode for rows and columns')
      }
      for(var i=0; i<2; ++i) {
        if(wrapTypes.indexOf(v[i]) < 0) {
          throw new Error('gl-texture2d: Unknown wrap mode ' + v)
        }
      }
      this._wrapS = v[0]
      this._wrapT = v[1]

      var gl = this.gl
      this.bind()
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this._wrapS)
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this._wrapT)

      return v
    }
  },
  shape: {
    get: function() {
      return this._shapeVector
    },
    set: function(x) {
      if(!Array.isArray(x)) {
        x = [x|0,x|0]
      } else {
        if(x.length !== 2) {
          throw new Error('gl-texture2d: Invalid texture shape')
        }
      }
      reshapeTexture(this, x[0]|0, x[1]|0)
      return [x[0]|0, x[1]|0]
    }
  },
  width: {
    get: function() {
      return this._shape[0]
    },
    set: function(w) {
      w = w|0
      reshapeTexture(this, w, this._shape[1])
      return w
    }
  },
  height: {
    get: function() {
      return this._shape[1]
    },
    set: function(h) {
      h = h|0
      reshapeTexture(this, this._shape[0], h)
      return h
    }
  }
})

proto.bind = function(unit) {
  var gl = this.gl
  if(unit !== undefined) {
    gl.activeTexture(gl.TEXTURE0 + (unit|0))
  }
  gl.bindTexture(gl.TEXTURE_2D, this.handle)
  if(unit !== undefined) {
    return (unit|0)
  }
  return gl.getParameter(gl.ACTIVE_TEXTURE) - gl.TEXTURE0
}

proto.dispose = function() {
  this.gl.deleteTexture(this.handle)
}

proto.generateMipmap = function() {
  this.bind()
  this.gl.generateMipmap(this.gl.TEXTURE_2D)

  //Update mip levels
  var l = Math.min(this._shape[0], this._shape[1])
  for(var i=0; l>0; ++i, l>>>=1) {
    if(this._mipLevels.indexOf(i) < 0) {
      this._mipLevels.push(i)
    }
  }
}

proto.setPixels = function(data, x_off, y_off, mip_level) {
  var gl = this.gl
  this.bind()
  if(Array.isArray(x_off)) {
    mip_level = y_off
    y_off = x_off[1]|0
    x_off = x_off[0]|0
  } else {
    x_off = x_off || 0
    y_off = y_off || 0
  }
  mip_level = mip_level || 0
  var directData = acceptTextureDOM(data) ? data : data.raw
  if(directData) {
    var needsMip = this._mipLevels.indexOf(mip_level) < 0
    if(needsMip) {
      gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, directData)
      this._mipLevels.push(mip_level)
    } else {
      gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, this.format, this.type, directData)
    }
  } else if(data.shape && data.stride && data.data) {
    if(data.shape.length < 2 ||
       x_off + data.shape[1] > this._shape[1]>>>mip_level ||
       y_off + data.shape[0] > this._shape[0]>>>mip_level ||
       x_off < 0 ||
       y_off < 0) {
      throw new Error('gl-texture2d: Texture dimensions are out of bounds')
    }
    texSubImageArray(gl, x_off, y_off, mip_level, this.format, this.type, this._mipLevels, data)
  } else {
    throw new Error('gl-texture2d: Unsupported data type')
  }
}


function isPacked(shape, stride) {
  if(shape.length === 3) {
    return  (stride[2] === 1) &&
            (stride[1] === shape[0]*shape[2]) &&
            (stride[0] === shape[2])
  }
  return  (stride[0] === 1) &&
          (stride[1] === shape[0])
}

function texSubImageArray(gl, x_off, y_off, mip_level, cformat, ctype, mipLevels, array) {
  var dtype = array.dtype
  var shape = array.shape.slice()
  if(shape.length < 2 || shape.length > 3) {
    throw new Error('gl-texture2d: Invalid ndarray, must be 2d or 3d')
  }
  var type = 0, format = 0
  var packed = isPacked(shape, array.stride.slice())
  if(dtype === 'float32') {
    type = gl.FLOAT
  } else if(dtype === 'float64') {
    type = gl.FLOAT
    packed = false
    dtype = 'float32'
  } else if(dtype === 'uint8') {
    type = gl.UNSIGNED_BYTE
  } else {
    type = gl.UNSIGNED_BYTE
    packed = false
    dtype = 'uint8'
  }
  var channels = 1
  if(shape.length === 2) {
    format = gl.LUMINANCE
    shape = [shape[0], shape[1], 1]
    array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset)
  } else if(shape.length === 3) {
    if(shape[2] === 1) {
      format = gl.ALPHA
    } else if(shape[2] === 2) {
      format = gl.LUMINANCE_ALPHA
    } else if(shape[2] === 3) {
      format = gl.RGB
    } else if(shape[2] === 4) {
      format = gl.RGBA
    } else {
      throw new Error('gl-texture2d: Invalid shape for pixel coords')
    }
    channels = shape[2]
  } else {
    throw new Error('gl-texture2d: Invalid shape for texture')
  }
  //For 1-channel textures allow conversion between formats
  if((format  === gl.LUMINANCE || format  === gl.ALPHA) &&
     (cformat === gl.LUMINANCE || cformat === gl.ALPHA)) {
    format = cformat
  }
  if(format !== cformat) {
    throw new Error('gl-texture2d: Incompatible texture format for setPixels')
  }
  var size = array.size
  var needsMip = mipLevels.indexOf(mip_level) < 0
  if(needsMip) {
    mipLevels.push(mip_level)
  }
  if(type === ctype && packed) {
    //Array data types are compatible, can directly copy into texture
    if(array.offset === 0 && array.data.length === size) {
      if(needsMip) {
        gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, array.data)
      } else {
        gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, array.data)
      }
    } else {
      if(needsMip) {
        gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, array.data.subarray(array.offset, array.offset+size))
      } else {
        gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, array.data.subarray(array.offset, array.offset+size))
      }
    }
  } else {
    //Need to do type conversion to pack data into buffer
    var pack_buffer
    if(ctype === gl.FLOAT) {
      pack_buffer = pool.mallocFloat32(size)
    } else {
      pack_buffer = pool.mallocUint8(size)
    }
    var pack_view = ndarray(pack_buffer, shape, [shape[2], shape[2]*shape[0], 1])
    if(type === gl.FLOAT && ctype === gl.UNSIGNED_BYTE) {
      convertFloatToUint8(pack_view, array)
    } else {
      ops.assign(pack_view, array)
    }
    if(needsMip) {
      gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, pack_buffer.subarray(0, size))
    } else {
      gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, pack_buffer.subarray(0, size))
    }
    if(ctype === gl.FLOAT) {
      pool.freeFloat32(pack_buffer)
    } else {
      pool.freeUint8(pack_buffer)
    }
  }
}

function initTexture(gl) {
  var tex = gl.createTexture()
  gl.bindTexture(gl.TEXTURE_2D, tex)
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
  return tex
}

function createTextureShape(gl, width, height, format, type) {
  var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE)
  if(width < 0 || width > maxTextureSize || height < 0 || height  > maxTextureSize) {
    throw new Error('gl-texture2d: Invalid texture shape')
  }
  if(type === gl.FLOAT && !gl.getExtension('OES_texture_float')) {
    throw new Error('gl-texture2d: Floating point textures not supported on this platform')
  }
  var tex = initTexture(gl)
  gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, 0, format, type, null)
  return new Texture2D(gl, tex, width, height, format, type)
}

function createTextureDOM(gl, directData, width, height, format, type) {
  var tex = initTexture(gl)
  gl.texImage2D(gl.TEXTURE_2D, 0, format, format, type, directData)
  return new Texture2D(gl, tex, width, height, format, type)
}

//Creates a texture from an ndarray
function createTextureArray(gl, array) {
  var dtype = array.dtype
  var shape = array.shape.slice()
  var maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE)
  if(shape[0] < 0 || shape[0] > maxSize || shape[1] < 0 || shape[1] > maxSize) {
    throw new Error('gl-texture2d: Invalid texture size')
  }
  var packed = isPacked(shape, array.stride.slice())
  var type = 0
  if(dtype === 'float32') {
    type = gl.FLOAT
  } else if(dtype === 'float64') {
    type = gl.FLOAT
    packed = false
    dtype = 'float32'
  } else if(dtype === 'uint8') {
    type = gl.UNSIGNED_BYTE
  } else {
    type = gl.UNSIGNED_BYTE
    packed = false
    dtype = 'uint8'
  }
  var format = 0
  if(shape.length === 2) {
    format = gl.LUMINANCE
    shape = [shape[0], shape[1], 1]
    array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset)
  } else if(shape.length === 3) {
    if(shape[2] === 1) {
      format = gl.ALPHA
    } else if(shape[2] === 2) {
      format = gl.LUMINANCE_ALPHA
    } else if(shape[2] === 3) {
      format = gl.RGB
    } else if(shape[2] === 4) {
      format = gl.RGBA
    } else {
      throw new Error('gl-texture2d: Invalid shape for pixel coords')
    }
  } else {
    throw new Error('gl-texture2d: Invalid shape for texture')
  }
  if(type === gl.FLOAT && !gl.getExtension('OES_texture_float')) {
    type = gl.UNSIGNED_BYTE
    packed = false
  }
  var buffer, buf_store
  var size = array.size
  if(!packed) {
    var stride = [shape[2], shape[2]*shape[0], 1]
    buf_store = pool.malloc(size, dtype)
    var buf_array = ndarray(buf_store, shape, stride, 0)
    if((dtype === 'float32' || dtype === 'float64') && type === gl.UNSIGNED_BYTE) {
      convertFloatToUint8(buf_array, array)
    } else {
      ops.assign(buf_array, array)
    }
    buffer = buf_store.subarray(0, size)
  } else if (array.offset === 0 && array.data.length === size) {
    buffer = array.data
  } else {
    buffer = array.data.subarray(array.offset, array.offset + size)
  }
  var tex = initTexture(gl)
  gl.texImage2D(gl.TEXTURE_2D, 0, format, shape[0], shape[1], 0, format, type, buffer)
  if(!packed) {
    pool.free(buf_store)
  }
  return new Texture2D(gl, tex, shape[0], shape[1], format, type)
}

function createTexture2D(gl) {
  if(arguments.length <= 1) {
    throw new Error('gl-texture2d: Missing arguments for texture2d constructor')
  }
  if(!linearTypes) {
    lazyInitLinearTypes(gl)
  }
  if(typeof arguments[1] === 'number') {
    return createTextureShape(gl, arguments[1], arguments[2], arguments[3]||gl.RGBA, arguments[4]||gl.UNSIGNED_BYTE)
  }
  if(Array.isArray(arguments[1])) {
    return createTextureShape(gl, arguments[1][0]|0, arguments[1][1]|0, arguments[2]||gl.RGBA, arguments[3]||gl.UNSIGNED_BYTE)
  }
  if(typeof arguments[1] === 'object') {
    var obj = arguments[1]
    var directData = acceptTextureDOM(obj) ? obj : obj.raw
    if (directData) {
      return createTextureDOM(gl, directData, obj.width|0, obj.height|0, arguments[2]||gl.RGBA, arguments[3]||gl.UNSIGNED_BYTE)
    } else if(obj.shape && obj.data && obj.stride) {
      return createTextureArray(gl, obj)
    }
  }
  throw new Error('gl-texture2d: Invalid arguments for texture2d constructor')
}

},{"ndarray":439,"ndarray-ops":433,"typedarray-pool":526}],312:[function(_dereq_,module,exports){
/** @module  gl-util/context */
'use strict'

var pick = _dereq_('pick-by-alias')

module.exports = function setContext (o) {
	if (!o) o = {}
	else if (typeof o === 'string') o = {container: o}

	// HTMLCanvasElement
	if (isCanvas(o)) {
		o = {container: o}
	}
	// HTMLElement
	else if (isElement(o)) {
		o = {container: o}
	}
	// WebGLContext
	else if (isContext(o)) {
		o = {gl: o}
	}
	// options object
	else {
		o = pick(o, {
			container: 'container target element el canvas holder parent parentNode wrapper use ref root node',
			gl: 'gl context webgl glContext',
			attrs: 'attributes attrs contextAttributes',
			pixelRatio: 'pixelRatio pxRatio px ratio pxratio pixelratio'
		}, true)
	}

	if (!o.pixelRatio) o.pixelRatio = window.pixelRatio || 1

	// make sure there is container and canvas
	if (o.gl) {
		return o.gl
	}
	if (o.canvas) {
		o.container = o.canvas.parentNode
	}
	if (o.container) {
		if (typeof o.container === 'string') {
			var c = document.querySelector(o.container)
			if (!c) throw Error('Element ' + o.container + ' is not found')
			o.container = c
		}
		if (isCanvas(o.container)) {
			o.canvas = o.container
			o.container = o.canvas.parentNode
		}
		else if (!o.canvas) {
			o.canvas = document.createElement('canvas')
			o.container.appendChild(o.canvas)
			resize(o)
		}
	}
	// blank new canvas
	else if (!o.canvas) {
		o.container = document.body || document.documentElement
		o.canvas = document.createElement('canvas')
		o.canvas.style.position = 'absolute'
		o.canvas.style.top = 0
		o.canvas.style.left = 0
		o.container.appendChild(o.canvas)
		resize(o)
	}

	// make sure there is context
	if (!o.gl) {
		try {
			o.gl = o.canvas.getContext('webgl', o.attrs)
		} catch (e) {
			try {
				o.gl = o.canvas.getContext('experimental-webgl', o.attrs)
			}
			catch (e) {
				o.gl = o.canvas.getContext('webgl-experimental', o.attrs)
			}
		}
	}

	return o.gl
}


function resize (o) {
	if (o.container) {
		if (o.container == document.body) {
			if (!document.body.style.width) o.canvas.width = o.width || (o.pixelRatio * window.innerWidth)
			if (!document.body.style.height) o.canvas.height = o.height || (o.pixelRatio * window.innerHeight)
		}
		else {
			var bounds = o.container.getBoundingClientRect()
			o.canvas.width = o.width || (bounds.right - bounds.left)
			o.canvas.height = o.height || (bounds.bottom - bounds.top)
		}
	}
}

function isCanvas (e) {
	return typeof e.getContext === 'function'
		&& 'width' in e
		&& 'height' in e
}

function isElement (e) {
	return typeof e.nodeName === 'string' &&
		typeof e.appendChild === 'function' &&
		typeof e.getBoundingClientRect === 'function'
}

function isContext (e) {
	return typeof e.drawArrays === 'function' ||
		typeof e.drawElements === 'function'
}

},{"pick-by-alias":454}],313:[function(_dereq_,module,exports){
"use strict"

function doBind(gl, elements, attributes) {
  if(elements) {
    elements.bind()
  } else {
    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null)
  }
  var nattribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS)|0
  if(attributes) {
    if(attributes.length > nattribs) {
      throw new Error("gl-vao: Too many vertex attributes")
    }
    for(var i=0; i<attributes.length; ++i) {
      var attrib = attributes[i]
      if(attrib.buffer) {
        var buffer = attrib.buffer
        var size = attrib.size || 4
        var type = attrib.type || gl.FLOAT
        var normalized = !!attrib.normalized
        var stride = attrib.stride || 0
        var offset = attrib.offset || 0
        buffer.bind()
        gl.enableVertexAttribArray(i)
        gl.vertexAttribPointer(i, size, type, normalized, stride, offset)
      } else {
        if(typeof attrib === "number") {
          gl.vertexAttrib1f(i, attrib)
        } else if(attrib.length === 1) {
          gl.vertexAttrib1f(i, attrib[0])
        } else if(attrib.length === 2) {
          gl.vertexAttrib2f(i, attrib[0], attrib[1])
        } else if(attrib.length === 3) {
          gl.vertexAttrib3f(i, attrib[0], attrib[1], attrib[2])
        } else if(attrib.length === 4) {
          gl.vertexAttrib4f(i, attrib[0], attrib[1], attrib[2], attrib[3])
        } else {
          throw new Error("gl-vao: Invalid vertex attribute")
        }
        gl.disableVertexAttribArray(i)
      }
    }
    for(; i<nattribs; ++i) {
      gl.disableVertexAttribArray(i)
    }
  } else {
    gl.bindBuffer(gl.ARRAY_BUFFER, null)
    for(var i=0; i<nattribs; ++i) {
      gl.disableVertexAttribArray(i)
    }
  }
}

module.exports = doBind
},{}],314:[function(_dereq_,module,exports){
"use strict"

var bindAttribs = _dereq_("./do-bind.js")

function VAOEmulated(gl) {
  this.gl = gl
  this._elements = null
  this._attributes = null
  this._elementsType = gl.UNSIGNED_SHORT
}

VAOEmulated.prototype.bind = function() {
  bindAttribs(this.gl, this._elements, this._attributes)
}

VAOEmulated.prototype.update = function(attributes, elements, elementsType) {
  this._elements = elements
  this._attributes = attributes
  this._elementsType = elementsType || this.gl.UNSIGNED_SHORT
}

VAOEmulated.prototype.dispose = function() { }
VAOEmulated.prototype.unbind = function() { }

VAOEmulated.prototype.draw = function(mode, count, offset) {
  offset = offset || 0
  var gl = this.gl
  if(this._elements) {
    gl.drawElements(mode, count, this._elementsType, offset)
  } else {
    gl.drawArrays(mode, offset, count)
  }
}

function createVAOEmulated(gl) {
  return new VAOEmulated(gl)
}

module.exports = createVAOEmulated
},{"./do-bind.js":313}],315:[function(_dereq_,module,exports){
"use strict"

var bindAttribs = _dereq_("./do-bind.js")

function VertexAttribute(location, dimension, a, b, c, d) {
  this.location = location
  this.dimension = dimension
  this.a = a
  this.b = b
  this.c = c
  this.d = d
}

VertexAttribute.prototype.bind = function(gl) {
  switch(this.dimension) {
    case 1:
      gl.vertexAttrib1f(this.location, this.a)
    break
    case 2:
      gl.vertexAttrib2f(this.location, this.a, this.b)
    break
    case 3:
      gl.vertexAttrib3f(this.location, this.a, this.b, this.c)
    break
    case 4:
      gl.vertexAttrib4f(this.location, this.a, this.b, this.c, this.d)
    break
  }
}

function VAONative(gl, ext, handle) {
  this.gl = gl
  this._ext = ext
  this.handle = handle
  this._attribs = []
  this._useElements = false
  this._elementsType = gl.UNSIGNED_SHORT
}

VAONative.prototype.bind = function() {
  this._ext.bindVertexArrayOES(this.handle)
  for(var i=0; i<this._attribs.length; ++i) {
    this._attribs[i].bind(this.gl)
  }
}

VAONative.prototype.unbind = function() {
  this._ext.bindVertexArrayOES(null)
}

VAONative.prototype.dispose = function() {
  this._ext.deleteVertexArrayOES(this.handle)
}

VAONative.prototype.update = function(attributes, elements, elementsType) {
  this.bind()
  bindAttribs(this.gl, elements, attributes)
  this.unbind()
  this._attribs.length = 0
  if(attributes)
  for(var i=0; i<attributes.length; ++i) {
    var a = attributes[i]
    if(typeof a === "number") {
      this._attribs.push(new VertexAttribute(i, 1, a))
    } else if(Array.isArray(a)) {
      this._attribs.push(new VertexAttribute(i, a.length, a[0], a[1], a[2], a[3]))
    }
  }
  this._useElements = !!elements
  this._elementsType = elementsType || this.gl.UNSIGNED_SHORT
}

VAONative.prototype.draw = function(mode, count, offset) {
  offset = offset || 0
  var gl = this.gl
  if(this._useElements) {
    gl.drawElements(mode, count, this._elementsType, offset)
  } else {
    gl.drawArrays(mode, offset, count)
  }
}

function createVAONative(gl, ext) {
  return new VAONative(gl, ext, ext.createVertexArrayOES())
}

module.exports = createVAONative
},{"./do-bind.js":313}],316:[function(_dereq_,module,exports){
"use strict"

var createVAONative = _dereq_("./lib/vao-native.js")
var createVAOEmulated = _dereq_("./lib/vao-emulated.js")

function ExtensionShim (gl) {
  this.bindVertexArrayOES = gl.bindVertexArray.bind(gl)
  this.createVertexArrayOES = gl.createVertexArray.bind(gl)
  this.deleteVertexArrayOES = gl.deleteVertexArray.bind(gl)
}

function createVAO(gl, attributes, elements, elementsType) {
  var ext = gl.createVertexArray
    ? new ExtensionShim(gl)
    : gl.getExtension('OES_vertex_array_object')
  var vao

  if(ext) {
    vao = createVAONative(gl, ext)
  } else {
    vao = createVAOEmulated(gl)
  }
  vao.update(attributes, elements, elementsType)
  return vao
}

module.exports = createVAO

},{"./lib/vao-emulated.js":314,"./lib/vao-native.js":315}],317:[function(_dereq_,module,exports){
module.exports = add;

/**
 * Adds two vec3's
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @returns {vec3} out
 */
function add(out, a, b) {
    out[0] = a[0] + b[0]
    out[1] = a[1] + b[1]
    out[2] = a[2] + b[2]
    return out
}
},{}],318:[function(_dereq_,module,exports){
module.exports = angle

var fromValues = _dereq_('./fromValues')
var normalize = _dereq_('./normalize')
var dot = _dereq_('./dot')

/**
 * Get the angle between two 3D vectors
 * @param {vec3} a The first operand
 * @param {vec3} b The second operand
 * @returns {Number} The angle in radians
 */
function angle(a, b) {
    var tempA = fromValues(a[0], a[1], a[2])
    var tempB = fromValues(b[0], b[1], b[2])
 
    normalize(tempA, tempA)
    normalize(tempB, tempB)
 
    var cosine = dot(tempA, tempB)

    if(cosine > 1.0){
        return 0
    } else {
        return Math.acos(cosine)
    }     
}

},{"./dot":328,"./fromValues":334,"./normalize":345}],319:[function(_dereq_,module,exports){
module.exports = ceil

/**
 * Math.ceil the components of a vec3
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a vector to ceil
 * @returns {vec3} out
 */
function ceil(out, a) {
  out[0] = Math.ceil(a[0])
  out[1] = Math.ceil(a[1])
  out[2] = Math.ceil(a[2])
  return out
}

},{}],320:[function(_dereq_,module,exports){
module.exports = clone;

/**
 * Creates a new vec3 initialized with values from an existing vector
 *
 * @param {vec3} a vector to clone
 * @returns {vec3} a new 3D vector
 */
function clone(a) {
    var out = new Float32Array(3)
    out[0] = a[0]
    out[1] = a[1]
    out[2] = a[2]
    return out
}
},{}],321:[function(_dereq_,module,exports){
module.exports = copy;

/**
 * Copy the values from one vec3 to another
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the source vector
 * @returns {vec3} out
 */
function copy(out, a) {
    out[0] = a[0]
    out[1] = a[1]
    out[2] = a[2]
    return out
}
},{}],322:[function(_dereq_,module,exports){
module.exports = create;

/**
 * Creates a new, empty vec3
 *
 * @returns {vec3} a new 3D vector
 */
function create() {
    var out = new Float32Array(3)
    out[0] = 0
    out[1] = 0
    out[2] = 0
    return out
}
},{}],323:[function(_dereq_,module,exports){
module.exports = cross;

/**
 * Computes the cross product of two vec3's
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @returns {vec3} out
 */
function cross(out, a, b) {
    var ax = a[0], ay = a[1], az = a[2],
        bx = b[0], by = b[1], bz = b[2]

    out[0] = ay * bz - az * by
    out[1] = az * bx - ax * bz
    out[2] = ax * by - ay * bx
    return out
}
},{}],324:[function(_dereq_,module,exports){
module.exports = _dereq_('./distance')

},{"./distance":325}],325:[function(_dereq_,module,exports){
module.exports = distance;

/**
 * Calculates the euclidian distance between two vec3's
 *
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @returns {Number} distance between a and b
 */
function distance(a, b) {
    var x = b[0] - a[0],
        y = b[1] - a[1],
        z = b[2] - a[2]
    return Math.sqrt(x*x + y*y + z*z)
}
},{}],326:[function(_dereq_,module,exports){
module.exports = _dereq_('./divide')

},{"./divide":327}],327:[function(_dereq_,module,exports){
module.exports = divide;

/**
 * Divides two vec3's
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @returns {vec3} out
 */
function divide(out, a, b) {
    out[0] = a[0] / b[0]
    out[1] = a[1] / b[1]
    out[2] = a[2] / b[2]
    return out
}
},{}],328:[function(_dereq_,module,exports){
module.exports = dot;

/**
 * Calculates the dot product of two vec3's
 *
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @returns {Number} dot product of a and b
 */
function dot(a, b) {
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
},{}],329:[function(_dereq_,module,exports){
module.exports = 0.000001

},{}],330:[function(_dereq_,module,exports){
module.exports = equals

var EPSILON = _dereq_('./epsilon')

/**
 * Returns whether or not the vectors have approximately the same elements in the same position.
 *
 * @param {vec3} a The first vector.
 * @param {vec3} b The second vector.
 * @returns {Boolean} True if the vectors are equal, false otherwise.
 */
function equals(a, b) {
  var a0 = a[0]
  var a1 = a[1]
  var a2 = a[2]
  var b0 = b[0]
  var b1 = b[1]
  var b2 = b[2]
  return (Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) &&
          Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) &&
          Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)))
}

},{"./epsilon":329}],331:[function(_dereq_,module,exports){
module.exports = exactEquals

/**
 * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===)
 *
 * @param {vec3} a The first vector.
 * @param {vec3} b The second vector.
 * @returns {Boolean} True if the vectors are equal, false otherwise.
 */
function exactEquals(a, b) {
  return a[0] === b[0] && a[1] === b[1] && a[2] === b[2]
}

},{}],332:[function(_dereq_,module,exports){
module.exports = floor

/**
 * Math.floor the components of a vec3
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a vector to floor
 * @returns {vec3} out
 */
function floor(out, a) {
  out[0] = Math.floor(a[0])
  out[1] = Math.floor(a[1])
  out[2] = Math.floor(a[2])
  return out
}

},{}],333:[function(_dereq_,module,exports){
module.exports = forEach;

var vec = _dereq_('./create')()

/**
 * Perform some operation over an array of vec3s.
 *
 * @param {Array} a the array of vectors to iterate over
 * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
 * @param {Number} offset Number of elements to skip at the beginning of the array
 * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
 * @param {Function} fn Function to call for each vector in the array
 * @param {Object} [arg] additional argument to pass to fn
 * @returns {Array} a
 * @function
 */
function forEach(a, stride, offset, count, fn, arg) {
        var i, l
        if(!stride) {
            stride = 3
        }

        if(!offset) {
            offset = 0
        }
        
        if(count) {
            l = Math.min((count * stride) + offset, a.length)
        } else {
            l = a.length
        }

        for(i = offset; i < l; i += stride) {
            vec[0] = a[i] 
            vec[1] = a[i+1] 
            vec[2] = a[i+2]
            fn(vec, vec, arg)
            a[i] = vec[0] 
            a[i+1] = vec[1] 
            a[i+2] = vec[2]
        }
        
        return a
}
},{"./create":322}],334:[function(_dereq_,module,exports){
module.exports = fromValues;

/**
 * Creates a new vec3 initialized with the given values
 *
 * @param {Number} x X component
 * @param {Number} y Y component
 * @param {Number} z Z component
 * @returns {vec3} a new 3D vector
 */
function fromValues(x, y, z) {
    var out = new Float32Array(3)
    out[0] = x
    out[1] = y
    out[2] = z
    return out
}
},{}],335:[function(_dereq_,module,exports){
module.exports = {
  EPSILON: _dereq_('./epsilon')
  , create: _dereq_('./create')
  , clone: _dereq_('./clone')
  , angle: _dereq_('./angle')
  , fromValues: _dereq_('./fromValues')
  , copy: _dereq_('./copy')
  , set: _dereq_('./set')
  , equals: _dereq_('./equals')
  , exactEquals: _dereq_('./exactEquals')
  , add: _dereq_('./add')
  , subtract: _dereq_('./subtract')
  , sub: _dereq_('./sub')
  , multiply: _dereq_('./multiply')
  , mul: _dereq_('./mul')
  , divide: _dereq_('./divide')
  , div: _dereq_('./div')
  , min: _dereq_('./min')
  , max: _dereq_('./max')
  , floor: _dereq_('./floor')
  , ceil: _dereq_('./ceil')
  , round: _dereq_('./round')
  , scale: _dereq_('./scale')
  , scaleAndAdd: _dereq_('./scaleAndAdd')
  , distance: _dereq_('./distance')
  , dist: _dereq_('./dist')
  , squaredDistance: _dereq_('./squaredDistance')
  , sqrDist: _dereq_('./sqrDist')
  , length: _dereq_('./length')
  , len: _dereq_('./len')
  , squaredLength: _dereq_('./squaredLength')
  , sqrLen: _dereq_('./sqrLen')
  , negate: _dereq_('./negate')
  , inverse: _dereq_('./inverse')
  , normalize: _dereq_('./normalize')
  , dot: _dereq_('./dot')
  , cross: _dereq_('./cross')
  , lerp: _dereq_('./lerp')
  , random: _dereq_('./random')
  , transformMat4: _dereq_('./transformMat4')
  , transformMat3: _dereq_('./transformMat3')
  , transformQuat: _dereq_('./transformQuat')
  , rotateX: _dereq_('./rotateX')
  , rotateY: _dereq_('./rotateY')
  , rotateZ: _dereq_('./rotateZ')
  , forEach: _dereq_('./forEach')
}

},{"./add":317,"./angle":318,"./ceil":319,"./clone":320,"./copy":321,"./create":322,"./cross":323,"./dist":324,"./distance":325,"./div":326,"./divide":327,"./dot":328,"./epsilon":329,"./equals":330,"./exactEquals":331,"./floor":332,"./forEach":333,"./fromValues":334,"./inverse":336,"./len":337,"./length":338,"./lerp":339,"./max":340,"./min":341,"./mul":342,"./multiply":343,"./negate":344,"./normalize":345,"./random":346,"./rotateX":347,"./rotateY":348,"./rotateZ":349,"./round":350,"./scale":351,"./scaleAndAdd":352,"./set":353,"./sqrDist":354,"./sqrLen":355,"./squaredDistance":356,"./squaredLength":357,"./sub":358,"./subtract":359,"./transformMat3":360,"./transformMat4":361,"./transformQuat":362}],336:[function(_dereq_,module,exports){
module.exports = inverse;

/**
 * Returns the inverse of the components of a vec3
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a vector to invert
 * @returns {vec3} out
 */
function inverse(out, a) {
  out[0] = 1.0 / a[0]
  out[1] = 1.0 / a[1]
  out[2] = 1.0 / a[2]
  return out
}
},{}],337:[function(_dereq_,module,exports){
module.exports = _dereq_('./length')

},{"./length":338}],338:[function(_dereq_,module,exports){
module.exports = length;

/**
 * Calculates the length of a vec3
 *
 * @param {vec3} a vector to calculate length of
 * @returns {Number} length of a
 */
function length(a) {
    var x = a[0],
        y = a[1],
        z = a[2]
    return Math.sqrt(x*x + y*y + z*z)
}
},{}],339:[function(_dereq_,module,exports){
module.exports = lerp;

/**
 * Performs a linear interpolation between two vec3's
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @param {Number} t interpolation amount between the two inputs
 * @returns {vec3} out
 */
function lerp(out, a, b, t) {
    var ax = a[0],
        ay = a[1],
        az = a[2]
    out[0] = ax + t * (b[0] - ax)
    out[1] = ay + t * (b[1] - ay)
    out[2] = az + t * (b[2] - az)
    return out
}
},{}],340:[function(_dereq_,module,exports){
module.exports = max;

/**
 * Returns the maximum of two vec3's
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @returns {vec3} out
 */
function max(out, a, b) {
    out[0] = Math.max(a[0], b[0])
    out[1] = Math.max(a[1], b[1])
    out[2] = Math.max(a[2], b[2])
    return out
}
},{}],341:[function(_dereq_,module,exports){
module.exports = min;

/**
 * Returns the minimum of two vec3's
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @returns {vec3} out
 */
function min(out, a, b) {
    out[0] = Math.min(a[0], b[0])
    out[1] = Math.min(a[1], b[1])
    out[2] = Math.min(a[2], b[2])
    return out
}
},{}],342:[function(_dereq_,module,exports){
module.exports = _dereq_('./multiply')

},{"./multiply":343}],343:[function(_dereq_,module,exports){
module.exports = multiply;

/**
 * Multiplies two vec3's
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @returns {vec3} out
 */
function multiply(out, a, b) {
    out[0] = a[0] * b[0]
    out[1] = a[1] * b[1]
    out[2] = a[2] * b[2]
    return out
}
},{}],344:[function(_dereq_,module,exports){
module.exports = negate;

/**
 * Negates the components of a vec3
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a vector to negate
 * @returns {vec3} out
 */
function negate(out, a) {
    out[0] = -a[0]
    out[1] = -a[1]
    out[2] = -a[2]
    return out
}
},{}],345:[function(_dereq_,module,exports){
module.exports = normalize;

/**
 * Normalize a vec3
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a vector to normalize
 * @returns {vec3} out
 */
function normalize(out, a) {
    var x = a[0],
        y = a[1],
        z = a[2]
    var len = x*x + y*y + z*z
    if (len > 0) {
        //TODO: evaluate use of glm_invsqrt here?
        len = 1 / Math.sqrt(len)
        out[0] = a[0] * len
        out[1] = a[1] * len
        out[2] = a[2] * len
    }
    return out
}
},{}],346:[function(_dereq_,module,exports){
module.exports = random;

/**
 * Generates a random vector with the given scale
 *
 * @param {vec3} out the receiving vector
 * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned
 * @returns {vec3} out
 */
function random(out, scale) {
    scale = scale || 1.0

    var r = Math.random() * 2.0 * Math.PI
    var z = (Math.random() * 2.0) - 1.0
    var zScale = Math.sqrt(1.0-z*z) * scale

    out[0] = Math.cos(r) * zScale
    out[1] = Math.sin(r) * zScale
    out[2] = z * scale
    return out
}
},{}],347:[function(_dereq_,module,exports){
module.exports = rotateX;

/**
 * Rotate a 3D vector around the x-axis
 * @param {vec3} out The receiving vec3
 * @param {vec3} a The vec3 point to rotate
 * @param {vec3} b The origin of the rotation
 * @param {Number} c The angle of rotation
 * @returns {vec3} out
 */
function rotateX(out, a, b, c){
    var by = b[1]
    var bz = b[2]

    // Translate point to the origin
    var py = a[1] - by
    var pz = a[2] - bz

    var sc = Math.sin(c)
    var cc = Math.cos(c)

    // perform rotation and translate to correct position
    out[0] = a[0]
    out[1] = by + py * cc - pz * sc
    out[2] = bz + py * sc + pz * cc

    return out
}

},{}],348:[function(_dereq_,module,exports){
module.exports = rotateY;

/**
 * Rotate a 3D vector around the y-axis
 * @param {vec3} out The receiving vec3
 * @param {vec3} a The vec3 point to rotate
 * @param {vec3} b The origin of the rotation
 * @param {Number} c The angle of rotation
 * @returns {vec3} out
 */
function rotateY(out, a, b, c){
    var bx = b[0]
    var bz = b[2]

    // translate point to the origin
    var px = a[0] - bx
    var pz = a[2] - bz
    
    var sc = Math.sin(c)
    var cc = Math.cos(c)
  
    // perform rotation and translate to correct position
    out[0] = bx + pz * sc + px * cc
    out[1] = a[1]
    out[2] = bz + pz * cc - px * sc
  
    return out
}

},{}],349:[function(_dereq_,module,exports){
module.exports = rotateZ;

/**
 * Rotate a 3D vector around the z-axis
 * @param {vec3} out The receiving vec3
 * @param {vec3} a The vec3 point to rotate
 * @param {vec3} b The origin of the rotation
 * @param {Number} c The angle of rotation
 * @returns {vec3} out
 */
function rotateZ(out, a, b, c){
    var bx = b[0]
    var by = b[1]

    //Translate point to the origin
    var px = a[0] - bx
    var py = a[1] - by
  
    var sc = Math.sin(c)
    var cc = Math.cos(c)

    // perform rotation and translate to correct position
    out[0] = bx + px * cc - py * sc
    out[1] = by + px * sc + py * cc
    out[2] = a[2]
  
    return out
}

},{}],350:[function(_dereq_,module,exports){
module.exports = round

/**
 * Math.round the components of a vec3
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a vector to round
 * @returns {vec3} out
 */
function round(out, a) {
  out[0] = Math.round(a[0])
  out[1] = Math.round(a[1])
  out[2] = Math.round(a[2])
  return out
}

},{}],351:[function(_dereq_,module,exports){
module.exports = scale;

/**
 * Scales a vec3 by a scalar number
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the vector to scale
 * @param {Number} b amount to scale the vector by
 * @returns {vec3} out
 */
function scale(out, a, b) {
    out[0] = a[0] * b
    out[1] = a[1] * b
    out[2] = a[2] * b
    return out
}
},{}],352:[function(_dereq_,module,exports){
module.exports = scaleAndAdd;

/**
 * Adds two vec3's after scaling the second operand by a scalar value
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @param {Number} scale the amount to scale b by before adding
 * @returns {vec3} out
 */
function scaleAndAdd(out, a, b, scale) {
    out[0] = a[0] + (b[0] * scale)
    out[1] = a[1] + (b[1] * scale)
    out[2] = a[2] + (b[2] * scale)
    return out
}
},{}],353:[function(_dereq_,module,exports){
module.exports = set;

/**
 * Set the components of a vec3 to the given values
 *
 * @param {vec3} out the receiving vector
 * @param {Number} x X component
 * @param {Number} y Y component
 * @param {Number} z Z component
 * @returns {vec3} out
 */
function set(out, x, y, z) {
    out[0] = x
    out[1] = y
    out[2] = z
    return out
}
},{}],354:[function(_dereq_,module,exports){
module.exports = _dereq_('./squaredDistance')

},{"./squaredDistance":356}],355:[function(_dereq_,module,exports){
module.exports = _dereq_('./squaredLength')

},{"./squaredLength":357}],356:[function(_dereq_,module,exports){
module.exports = squaredDistance;

/**
 * Calculates the squared euclidian distance between two vec3's
 *
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @returns {Number} squared distance between a and b
 */
function squaredDistance(a, b) {
    var x = b[0] - a[0],
        y = b[1] - a[1],
        z = b[2] - a[2]
    return x*x + y*y + z*z
}
},{}],357:[function(_dereq_,module,exports){
module.exports = squaredLength;

/**
 * Calculates the squared length of a vec3
 *
 * @param {vec3} a vector to calculate squared length of
 * @returns {Number} squared length of a
 */
function squaredLength(a) {
    var x = a[0],
        y = a[1],
        z = a[2]
    return x*x + y*y + z*z
}
},{}],358:[function(_dereq_,module,exports){
module.exports = _dereq_('./subtract')

},{"./subtract":359}],359:[function(_dereq_,module,exports){
module.exports = subtract;

/**
 * Subtracts vector b from vector a
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @returns {vec3} out
 */
function subtract(out, a, b) {
    out[0] = a[0] - b[0]
    out[1] = a[1] - b[1]
    out[2] = a[2] - b[2]
    return out
}
},{}],360:[function(_dereq_,module,exports){
module.exports = transformMat3;

/**
 * Transforms the vec3 with a mat3.
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the vector to transform
 * @param {mat4} m the 3x3 matrix to transform with
 * @returns {vec3} out
 */
function transformMat3(out, a, m) {
    var x = a[0], y = a[1], z = a[2]
    out[0] = x * m[0] + y * m[3] + z * m[6]
    out[1] = x * m[1] + y * m[4] + z * m[7]
    out[2] = x * m[2] + y * m[5] + z * m[8]
    return out
}
},{}],361:[function(_dereq_,module,exports){
module.exports = transformMat4;

/**
 * Transforms the vec3 with a mat4.
 * 4th vector component is implicitly '1'
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the vector to transform
 * @param {mat4} m matrix to transform with
 * @returns {vec3} out
 */
function transformMat4(out, a, m) {
    var x = a[0], y = a[1], z = a[2],
        w = m[3] * x + m[7] * y + m[11] * z + m[15]
    w = w || 1.0
    out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w
    out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w
    out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w
    return out
}
},{}],362:[function(_dereq_,module,exports){
module.exports = transformQuat;

/**
 * Transforms the vec3 with a quat
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the vector to transform
 * @param {quat} q quaternion to transform with
 * @returns {vec3} out
 */
function transformQuat(out, a, q) {
    // benchmarks: http://jsperf.com/quaternion-transform-vec3-implementations

    var x = a[0], y = a[1], z = a[2],
        qx = q[0], qy = q[1], qz = q[2], qw = q[3],

        // calculate quat * vec
        ix = qw * x + qy * z - qz * y,
        iy = qw * y + qz * x - qx * z,
        iz = qw * z + qx * y - qy * x,
        iw = -qx * x - qy * y - qz * z

    // calculate result * inverse quat
    out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy
    out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz
    out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx
    return out
}
},{}],363:[function(_dereq_,module,exports){
module.exports = add

/**
 * Adds two vec4's
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the first operand
 * @param {vec4} b the second operand
 * @returns {vec4} out
 */
function add (out, a, b) {
  out[0] = a[0] + b[0]
  out[1] = a[1] + b[1]
  out[2] = a[2] + b[2]
  out[3] = a[3] + b[3]
  return out
}

},{}],364:[function(_dereq_,module,exports){
module.exports = clone

/**
 * Creates a new vec4 initialized with values from an existing vector
 *
 * @param {vec4} a vector to clone
 * @returns {vec4} a new 4D vector
 */
function clone (a) {
  var out = new Float32Array(4)
  out[0] = a[0]
  out[1] = a[1]
  out[2] = a[2]
  out[3] = a[3]
  return out
}

},{}],365:[function(_dereq_,module,exports){
module.exports = copy

/**
 * Copy the values from one vec4 to another
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the source vector
 * @returns {vec4} out
 */
function copy (out, a) {
  out[0] = a[0]
  out[1] = a[1]
  out[2] = a[2]
  out[3] = a[3]
  return out
}

},{}],366:[function(_dereq_,module,exports){
module.exports = create

/**
 * Creates a new, empty vec4
 *
 * @returns {vec4} a new 4D vector
 */
function create () {
  var out = new Float32Array(4)
  out[0] = 0
  out[1] = 0
  out[2] = 0
  out[3] = 0
  return out
}

},{}],367:[function(_dereq_,module,exports){
module.exports = distance

/**
 * Calculates the euclidian distance between two vec4's
 *
 * @param {vec4} a the first operand
 * @param {vec4} b the second operand
 * @returns {Number} distance between a and b
 */
function distance (a, b) {
  var x = b[0] - a[0],
    y = b[1] - a[1],
    z = b[2] - a[2],
    w = b[3] - a[3]
  return Math.sqrt(x * x + y * y + z * z + w * w)
}

},{}],368:[function(_dereq_,module,exports){
module.exports = divide

/**
 * Divides two vec4's
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the first operand
 * @param {vec4} b the second operand
 * @returns {vec4} out
 */
function divide (out, a, b) {
  out[0] = a[0] / b[0]
  out[1] = a[1] / b[1]
  out[2] = a[2] / b[2]
  out[3] = a[3] / b[3]
  return out
}

},{}],369:[function(_dereq_,module,exports){
module.exports = dot

/**
 * Calculates the dot product of two vec4's
 *
 * @param {vec4} a the first operand
 * @param {vec4} b the second operand
 * @returns {Number} dot product of a and b
 */
function dot (a, b) {
  return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]
}

},{}],370:[function(_dereq_,module,exports){
module.exports = fromValues

/**
 * Creates a new vec4 initialized with the given values
 *
 * @param {Number} x X component
 * @param {Number} y Y component
 * @param {Number} z Z component
 * @param {Number} w W component
 * @returns {vec4} a new 4D vector
 */
function fromValues (x, y, z, w) {
  var out = new Float32Array(4)
  out[0] = x
  out[1] = y
  out[2] = z
  out[3] = w
  return out
}

},{}],371:[function(_dereq_,module,exports){
module.exports = {
  create: _dereq_('./create'),
  clone: _dereq_('./clone'),
  fromValues: _dereq_('./fromValues'),
  copy: _dereq_('./copy'),
  set: _dereq_('./set'),
  add: _dereq_('./add'),
  subtract: _dereq_('./subtract'),
  multiply: _dereq_('./multiply'),
  divide: _dereq_('./divide'),
  min: _dereq_('./min'),
  max: _dereq_('./max'),
  scale: _dereq_('./scale'),
  scaleAndAdd: _dereq_('./scaleAndAdd'),
  distance: _dereq_('./distance'),
  squaredDistance: _dereq_('./squaredDistance'),
  length: _dereq_('./length'),
  squaredLength: _dereq_('./squaredLength'),
  negate: _dereq_('./negate'),
  inverse: _dereq_('./inverse'),
  normalize: _dereq_('./normalize'),
  dot: _dereq_('./dot'),
  lerp: _dereq_('./lerp'),
  random: _dereq_('./random'),
  transformMat4: _dereq_('./transformMat4'),
  transformQuat: _dereq_('./transformQuat')
}

},{"./add":363,"./clone":364,"./copy":365,"./create":366,"./distance":367,"./divide":368,"./dot":369,"./fromValues":370,"./inverse":372,"./length":373,"./lerp":374,"./max":375,"./min":376,"./multiply":377,"./negate":378,"./normalize":379,"./random":380,"./scale":381,"./scaleAndAdd":382,"./set":383,"./squaredDistance":384,"./squaredLength":385,"./subtract":386,"./transformMat4":387,"./transformQuat":388}],372:[function(_dereq_,module,exports){
module.exports = inverse

/**
 * Returns the inverse of the components of a vec4
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a vector to invert
 * @returns {vec4} out
 */
function inverse (out, a) {
  out[0] = 1.0 / a[0]
  out[1] = 1.0 / a[1]
  out[2] = 1.0 / a[2]
  out[3] = 1.0 / a[3]
  return out
}

},{}],373:[function(_dereq_,module,exports){
module.exports = length

/**
 * Calculates the length of a vec4
 *
 * @param {vec4} a vector to calculate length of
 * @returns {Number} length of a
 */
function length (a) {
  var x = a[0],
    y = a[1],
    z = a[2],
    w = a[3]
  return Math.sqrt(x * x + y * y + z * z + w * w)
}

},{}],374:[function(_dereq_,module,exports){
module.exports = lerp

/**
 * Performs a linear interpolation between two vec4's
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the first operand
 * @param {vec4} b the second operand
 * @param {Number} t interpolation amount between the two inputs
 * @returns {vec4} out
 */
function lerp (out, a, b, t) {
  var ax = a[0],
    ay = a[1],
    az = a[2],
    aw = a[3]
  out[0] = ax + t * (b[0] - ax)
  out[1] = ay + t * (b[1] - ay)
  out[2] = az + t * (b[2] - az)
  out[3] = aw + t * (b[3] - aw)
  return out
}

},{}],375:[function(_dereq_,module,exports){
module.exports = max

/**
 * Returns the maximum of two vec4's
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the first operand
 * @param {vec4} b the second operand
 * @returns {vec4} out
 */
function max (out, a, b) {
  out[0] = Math.max(a[0], b[0])
  out[1] = Math.max(a[1], b[1])
  out[2] = Math.max(a[2], b[2])
  out[3] = Math.max(a[3], b[3])
  return out
}

},{}],376:[function(_dereq_,module,exports){
module.exports = min

/**
 * Returns the minimum of two vec4's
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the first operand
 * @param {vec4} b the second operand
 * @returns {vec4} out
 */
function min (out, a, b) {
  out[0] = Math.min(a[0], b[0])
  out[1] = Math.min(a[1], b[1])
  out[2] = Math.min(a[2], b[2])
  out[3] = Math.min(a[3], b[3])
  return out
}

},{}],377:[function(_dereq_,module,exports){
module.exports = multiply

/**
 * Multiplies two vec4's
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the first operand
 * @param {vec4} b the second operand
 * @returns {vec4} out
 */
function multiply (out, a, b) {
  out[0] = a[0] * b[0]
  out[1] = a[1] * b[1]
  out[2] = a[2] * b[2]
  out[3] = a[3] * b[3]
  return out
}

},{}],378:[function(_dereq_,module,exports){
module.exports = negate

/**
 * Negates the components of a vec4
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a vector to negate
 * @returns {vec4} out
 */
function negate (out, a) {
  out[0] = -a[0]
  out[1] = -a[1]
  out[2] = -a[2]
  out[3] = -a[3]
  return out
}

},{}],379:[function(_dereq_,module,exports){
module.exports = normalize

/**
 * Normalize a vec4
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a vector to normalize
 * @returns {vec4} out
 */
function normalize (out, a) {
  var x = a[0],
    y = a[1],
    z = a[2],
    w = a[3]
  var len = x * x + y * y + z * z + w * w
  if (len > 0) {
    len = 1 / Math.sqrt(len)
    out[0] = x * len
    out[1] = y * len
    out[2] = z * len
    out[3] = w * len
  }
  return out
}

},{}],380:[function(_dereq_,module,exports){
var vecNormalize = _dereq_('./normalize')
var vecScale = _dereq_('./scale')

module.exports = random

/**
 * Generates a random vector with the given scale
 *
 * @param {vec4} out the receiving vector
 * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned
 * @returns {vec4} out
 */
function random (out, scale) {
  scale = scale || 1.0

  // TODO: This is a pretty awful way of doing this. Find something better.
  out[0] = Math.random()
  out[1] = Math.random()
  out[2] = Math.random()
  out[3] = Math.random()
  vecNormalize(out, out)
  vecScale(out, out, scale)
  return out
}

},{"./normalize":379,"./scale":381}],381:[function(_dereq_,module,exports){
module.exports = scale

/**
 * Scales a vec4 by a scalar number
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the vector to scale
 * @param {Number} b amount to scale the vector by
 * @returns {vec4} out
 */
function scale (out, a, b) {
  out[0] = a[0] * b
  out[1] = a[1] * b
  out[2] = a[2] * b
  out[3] = a[3] * b
  return out
}

},{}],382:[function(_dereq_,module,exports){
module.exports = scaleAndAdd

/**
 * Adds two vec4's after scaling the second operand by a scalar value
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the first operand
 * @param {vec4} b the second operand
 * @param {Number} scale the amount to scale b by before adding
 * @returns {vec4} out
 */
function scaleAndAdd (out, a, b, scale) {
  out[0] = a[0] + (b[0] * scale)
  out[1] = a[1] + (b[1] * scale)
  out[2] = a[2] + (b[2] * scale)
  out[3] = a[3] + (b[3] * scale)
  return out
}

},{}],383:[function(_dereq_,module,exports){
module.exports = set

/**
 * Set the components of a vec4 to the given values
 *
 * @param {vec4} out the receiving vector
 * @param {Number} x X component
 * @param {Number} y Y component
 * @param {Number} z Z component
 * @param {Number} w W component
 * @returns {vec4} out
 */
function set (out, x, y, z, w) {
  out[0] = x
  out[1] = y
  out[2] = z
  out[3] = w
  return out
}

},{}],384:[function(_dereq_,module,exports){
module.exports = squaredDistance

/**
 * Calculates the squared euclidian distance between two vec4's
 *
 * @param {vec4} a the first operand
 * @param {vec4} b the second operand
 * @returns {Number} squared distance between a and b
 */
function squaredDistance (a, b) {
  var x = b[0] - a[0],
    y = b[1] - a[1],
    z = b[2] - a[2],
    w = b[3] - a[3]
  return x * x + y * y + z * z + w * w
}

},{}],385:[function(_dereq_,module,exports){
module.exports = squaredLength

/**
 * Calculates the squared length of a vec4
 *
 * @param {vec4} a vector to calculate squared length of
 * @returns {Number} squared length of a
 */
function squaredLength (a) {
  var x = a[0],
    y = a[1],
    z = a[2],
    w = a[3]
  return x * x + y * y + z * z + w * w
}

},{}],386:[function(_dereq_,module,exports){
module.exports = subtract

/**
 * Subtracts vector b from vector a
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the first operand
 * @param {vec4} b the second operand
 * @returns {vec4} out
 */
function subtract (out, a, b) {
  out[0] = a[0] - b[0]
  out[1] = a[1] - b[1]
  out[2] = a[2] - b[2]
  out[3] = a[3] - b[3]
  return out
}

},{}],387:[function(_dereq_,module,exports){
module.exports = transformMat4

/**
 * Transforms the vec4 with a mat4.
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the vector to transform
 * @param {mat4} m matrix to transform with
 * @returns {vec4} out
 */
function transformMat4 (out, a, m) {
  var x = a[0], y = a[1], z = a[2], w = a[3]
  out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w
  out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w
  out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w
  out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w
  return out
}

},{}],388:[function(_dereq_,module,exports){
module.exports = transformQuat

/**
 * Transforms the vec4 with a quat
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the vector to transform
 * @param {quat} q quaternion to transform with
 * @returns {vec4} out
 */
function transformQuat (out, a, q) {
  var x = a[0], y = a[1], z = a[2],
    qx = q[0], qy = q[1], qz = q[2], qw = q[3],

    // calculate quat * vec
    ix = qw * x + qy * z - qz * y,
    iy = qw * y + qz * x - qx * z,
    iz = qw * z + qx * y - qy * x,
    iw = -qx * x - qy * y - qz * z

  // calculate result * inverse quat
  out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy
  out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz
  out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx
  out[3] = a[3]
  return out
}

},{}],389:[function(_dereq_,module,exports){
module.exports = decodeFloat

var UINT8_VIEW = new Uint8Array(4)
var FLOAT_VIEW = new Float32Array(UINT8_VIEW.buffer)

function decodeFloat(x, y, z, w) {
  UINT8_VIEW[0] = w
  UINT8_VIEW[1] = z
  UINT8_VIEW[2] = y
  UINT8_VIEW[3] = x
  return FLOAT_VIEW[0]
}

},{}],390:[function(_dereq_,module,exports){
var tokenize = _dereq_('glsl-tokenizer')
var atob     = _dereq_('atob-lite')

module.exports = getName

function getName(src) {
  var tokens = Array.isArray(src)
    ? src
    : tokenize(src)

  for (var i = 0; i < tokens.length; i++) {
    var token = tokens[i]
    if (token.type !== 'preprocessor') continue
    var match = token.data.match(/\#define\s+SHADER_NAME(_B64)?\s+(.+)$/)
    if (!match) continue
    if (!match[2]) continue

    var b64  = match[1]
    var name = match[2]

    return (b64 ? atob(name) : name).trim()
  }
}

},{"atob-lite":60,"glsl-tokenizer":397}],391:[function(_dereq_,module,exports){
module.exports = tokenize

var literals100 = _dereq_('./lib/literals')
  , operators = _dereq_('./lib/operators')
  , builtins100 = _dereq_('./lib/builtins')
  , literals300es = _dereq_('./lib/literals-300es')
  , builtins300es = _dereq_('./lib/builtins-300es')

var NORMAL = 999          // <-- never emitted
  , TOKEN = 9999          // <-- never emitted
  , BLOCK_COMMENT = 0
  , LINE_COMMENT = 1
  , PREPROCESSOR = 2
  , OPERATOR = 3
  , INTEGER = 4
  , FLOAT = 5
  , IDENT = 6
  , BUILTIN = 7
  , KEYWORD = 8
  , WHITESPACE = 9
  , EOF = 10
  , HEX = 11

var map = [
    'block-comment'
  , 'line-comment'
  , 'preprocessor'
  , 'operator'
  , 'integer'
  , 'float'
  , 'ident'
  , 'builtin'
  , 'keyword'
  , 'whitespace'
  , 'eof'
  , 'integer'
]

function tokenize(opt) {
  var i = 0
    , total = 0
    , mode = NORMAL
    , c
    , last
    , content = []
    , tokens = []
    , token_idx = 0
    , token_offs = 0
    , line = 1
    , col = 0
    , start = 0
    , isnum = false
    , isoperator = false
    , input = ''
    , len

  opt = opt || {}
  var allBuiltins = builtins100
  var allLiterals = literals100
  if (opt.version === '300 es') {
    allBuiltins = builtins300es
    allLiterals = literals300es
  }

  return function(data) {
    tokens = []
    if (data !== null) return write(data.replace ? data.replace(/\r\n/g, '\n') : data)
    return end()
  }

  function token(data) {
    if (data.length) {
      tokens.push({
        type: map[mode]
      , data: data
      , position: start
      , line: line
      , column: col
      })
    }
  }

  function write(chunk) {
    i = 0
    input += chunk
    len = input.length

    var last

    while(c = input[i], i < len) {
      last = i

      switch(mode) {
        case BLOCK_COMMENT: i = block_comment(); break
        case LINE_COMMENT: i = line_comment(); break
        case PREPROCESSOR: i = preprocessor(); break
        case OPERATOR: i = operator(); break
        case INTEGER: i = integer(); break
        case HEX: i = hex(); break
        case FLOAT: i = decimal(); break
        case TOKEN: i = readtoken(); break
        case WHITESPACE: i = whitespace(); break
        case NORMAL: i = normal(); break
      }

      if(last !== i) {
        switch(input[last]) {
          case '\n': col = 0; ++line; break
          default: ++col; break
        }
      }
    }

    total += i
    input = input.slice(i)
    return tokens
  }

  function end(chunk) {
    if(content.length) {
      token(content.join(''))
    }

    mode = EOF
    token('(eof)')
    return tokens
  }

  function normal() {
    content = content.length ? [] : content

    if(last === '/' && c === '*') {
      start = total + i - 1
      mode = BLOCK_COMMENT
      last = c
      return i + 1
    }

    if(last === '/' && c === '/') {
      start = total + i - 1
      mode = LINE_COMMENT
      last = c
      return i + 1
    }

    if(c === '#') {
      mode = PREPROCESSOR
      start = total + i
      return i
    }

    if(/\s/.test(c)) {
      mode = WHITESPACE
      start = total + i
      return i
    }

    isnum = /\d/.test(c)
    isoperator = /[^\w_]/.test(c)

    start = total + i
    mode = isnum ? INTEGER : isoperator ? OPERATOR : TOKEN
    return i
  }

  function whitespace() {
    if(/[^\s]/g.test(c)) {
      token(content.join(''))
      mode = NORMAL
      return i
    }
    content.push(c)
    last = c
    return i + 1
  }

  function preprocessor() {
    if((c === '\r' || c === '\n') && last !== '\\') {
      token(content.join(''))
      mode = NORMAL
      return i
    }
    content.push(c)
    last = c
    return i + 1
  }

  function line_comment() {
    return preprocessor()
  }

  function block_comment() {
    if(c === '/' && last === '*') {
      content.push(c)
      token(content.join(''))
      mode = NORMAL
      return i + 1
    }

    content.push(c)
    last = c
    return i + 1
  }

  function operator() {
    if(last === '.' && /\d/.test(c)) {
      mode = FLOAT
      return i
    }

    if(last === '/' && c === '*') {
      mode = BLOCK_COMMENT
      return i
    }

    if(last === '/' && c === '/') {
      mode = LINE_COMMENT
      return i
    }

    if(c === '.' && content.length) {
      while(determine_operator(content));

      mode = FLOAT
      return i
    }

    if(c === ';' || c === ')' || c === '(') {
      if(content.length) while(determine_operator(content));
      token(c)
      mode = NORMAL
      return i + 1
    }

    var is_composite_operator = content.length === 2 && c !== '='
    if(/[\w_\d\s]/.test(c) || is_composite_operator) {
      while(determine_operator(content));
      mode = NORMAL
      return i
    }

    content.push(c)
    last = c
    return i + 1
  }

  function determine_operator(buf) {
    var j = 0
      , idx
      , res

    do {
      idx = operators.indexOf(buf.slice(0, buf.length + j).join(''))
      res = operators[idx]

      if(idx === -1) {
        if(j-- + buf.length > 0) continue
        res = buf.slice(0, 1).join('')
      }

      token(res)

      start += res.length
      content = content.slice(res.length)
      return content.length
    } while(1)
  }

  function hex() {
    if(/[^a-fA-F0-9]/.test(c)) {
      token(content.join(''))
      mode = NORMAL
      return i
    }

    content.push(c)
    last = c
    return i + 1
  }

  function integer() {
    if(c === '.') {
      content.push(c)
      mode = FLOAT
      last = c
      return i + 1
    }

    if(/[eE]/.test(c)) {
      content.push(c)
      mode = FLOAT
      last = c
      return i + 1
    }

    if(c === 'x' && content.length === 1 && content[0] === '0') {
      mode = HEX
      content.push(c)
      last = c
      return i + 1
    }

    if(/[^\d]/.test(c)) {
      token(content.join(''))
      mode = NORMAL
      return i
    }

    content.push(c)
    last = c
    return i + 1
  }

  function decimal() {
    if(c === 'f') {
      content.push(c)
      last = c
      i += 1
    }

    if(/[eE]/.test(c)) {
      content.push(c)
      last = c
      return i + 1
    }

    if (c === '-' && /[eE]/.test(last)) {
      content.push(c)
      last = c
      return i + 1
    }

    if(/[^\d]/.test(c)) {
      token(content.join(''))
      mode = NORMAL
      return i
    }

    content.push(c)
    last = c
    return i + 1
  }

  function readtoken() {
    if(/[^\d\w_]/.test(c)) {
      var contentstr = content.join('')
      if(allLiterals.indexOf(contentstr) > -1) {
        mode = KEYWORD
      } else if(allBuiltins.indexOf(contentstr) > -1) {
        mode = BUILTIN
      } else {
        mode = IDENT
      }
      token(content.join(''))
      mode = NORMAL
      return i
    }
    content.push(c)
    last = c
    return i + 1
  }
}

},{"./lib/builtins":393,"./lib/builtins-300es":392,"./lib/literals":395,"./lib/literals-300es":394,"./lib/operators":396}],392:[function(_dereq_,module,exports){
// 300es builtins/reserved words that were previously valid in v100
var v100 = _dereq_('./builtins')

// The texture2D|Cube functions have been removed
// And the gl_ features are updated
v100 = v100.slice().filter(function (b) {
  return !/^(gl\_|texture)/.test(b)
})

module.exports = v100.concat([
  // the updated gl_ constants
    'gl_VertexID'
  , 'gl_InstanceID'
  , 'gl_Position'
  , 'gl_PointSize'
  , 'gl_FragCoord'
  , 'gl_FrontFacing'
  , 'gl_FragDepth'
  , 'gl_PointCoord'
  , 'gl_MaxVertexAttribs'
  , 'gl_MaxVertexUniformVectors'
  , 'gl_MaxVertexOutputVectors'
  , 'gl_MaxFragmentInputVectors'
  , 'gl_MaxVertexTextureImageUnits'
  , 'gl_MaxCombinedTextureImageUnits'
  , 'gl_MaxTextureImageUnits'
  , 'gl_MaxFragmentUniformVectors'
  , 'gl_MaxDrawBuffers'
  , 'gl_MinProgramTexelOffset'
  , 'gl_MaxProgramTexelOffset'
  , 'gl_DepthRangeParameters'
  , 'gl_DepthRange'

  // other builtins
  , 'trunc'
  , 'round'
  , 'roundEven'
  , 'isnan'
  , 'isinf'
  , 'floatBitsToInt'
  , 'floatBitsToUint'
  , 'intBitsToFloat'
  , 'uintBitsToFloat'
  , 'packSnorm2x16'
  , 'unpackSnorm2x16'
  , 'packUnorm2x16'
  , 'unpackUnorm2x16'
  , 'packHalf2x16'
  , 'unpackHalf2x16'
  , 'outerProduct'
  , 'transpose'
  , 'determinant'
  , 'inverse'
  , 'texture'
  , 'textureSize'
  , 'textureProj'
  , 'textureLod'
  , 'textureOffset'
  , 'texelFetch'
  , 'texelFetchOffset'
  , 'textureProjOffset'
  , 'textureLodOffset'
  , 'textureProjLod'
  , 'textureProjLodOffset'
  , 'textureGrad'
  , 'textureGradOffset'
  , 'textureProjGrad'
  , 'textureProjGradOffset'
])

},{"./builtins":393}],393:[function(_dereq_,module,exports){
module.exports = [
  // Keep this list sorted
  'abs'
  , 'acos'
  , 'all'
  , 'any'
  , 'asin'
  , 'atan'
  , 'ceil'
  , 'clamp'
  , 'cos'
  , 'cross'
  , 'dFdx'
  , 'dFdy'
  , 'degrees'
  , 'distance'
  , 'dot'
  , 'equal'
  , 'exp'
  , 'exp2'
  , 'faceforward'
  , 'floor'
  , 'fract'
  , 'gl_BackColor'
  , 'gl_BackLightModelProduct'
  , 'gl_BackLightProduct'
  , 'gl_BackMaterial'
  , 'gl_BackSecondaryColor'
  , 'gl_ClipPlane'
  , 'gl_ClipVertex'
  , 'gl_Color'
  , 'gl_DepthRange'
  , 'gl_DepthRangeParameters'
  , 'gl_EyePlaneQ'
  , 'gl_EyePlaneR'
  , 'gl_EyePlaneS'
  , 'gl_EyePlaneT'
  , 'gl_Fog'
  , 'gl_FogCoord'
  , 'gl_FogFragCoord'
  , 'gl_FogParameters'
  , 'gl_FragColor'
  , 'gl_FragCoord'
  , 'gl_FragData'
  , 'gl_FragDepth'
  , 'gl_FragDepthEXT'
  , 'gl_FrontColor'
  , 'gl_FrontFacing'
  , 'gl_FrontLightModelProduct'
  , 'gl_FrontLightProduct'
  , 'gl_FrontMaterial'
  , 'gl_FrontSecondaryColor'
  , 'gl_LightModel'
  , 'gl_LightModelParameters'
  , 'gl_LightModelProducts'
  , 'gl_LightProducts'
  , 'gl_LightSource'
  , 'gl_LightSourceParameters'
  , 'gl_MaterialParameters'
  , 'gl_MaxClipPlanes'
  , 'gl_MaxCombinedTextureImageUnits'
  , 'gl_MaxDrawBuffers'
  , 'gl_MaxFragmentUniformComponents'
  , 'gl_MaxLights'
  , 'gl_MaxTextureCoords'
  , 'gl_MaxTextureImageUnits'
  , 'gl_MaxTextureUnits'
  , 'gl_MaxVaryingFloats'
  , 'gl_MaxVertexAttribs'
  , 'gl_MaxVertexTextureImageUnits'
  , 'gl_MaxVertexUniformComponents'
  , 'gl_ModelViewMatrix'
  , 'gl_ModelViewMatrixInverse'
  , 'gl_ModelViewMatrixInverseTranspose'
  , 'gl_ModelViewMatrixTranspose'
  , 'gl_ModelViewProjectionMatrix'
  , 'gl_ModelViewProjectionMatrixInverse'
  , 'gl_ModelViewProjectionMatrixInverseTranspose'
  , 'gl_ModelViewProjectionMatrixTranspose'
  , 'gl_MultiTexCoord0'
  , 'gl_MultiTexCoord1'
  , 'gl_MultiTexCoord2'
  , 'gl_MultiTexCoord3'
  , 'gl_MultiTexCoord4'
  , 'gl_MultiTexCoord5'
  , 'gl_MultiTexCoord6'
  , 'gl_MultiTexCoord7'
  , 'gl_Normal'
  , 'gl_NormalMatrix'
  , 'gl_NormalScale'
  , 'gl_ObjectPlaneQ'
  , 'gl_ObjectPlaneR'
  , 'gl_ObjectPlaneS'
  , 'gl_ObjectPlaneT'
  , 'gl_Point'
  , 'gl_PointCoord'
  , 'gl_PointParameters'
  , 'gl_PointSize'
  , 'gl_Position'
  , 'gl_ProjectionMatrix'
  , 'gl_ProjectionMatrixInverse'
  , 'gl_ProjectionMatrixInverseTranspose'
  , 'gl_ProjectionMatrixTranspose'
  , 'gl_SecondaryColor'
  , 'gl_TexCoord'
  , 'gl_TextureEnvColor'
  , 'gl_TextureMatrix'
  , 'gl_TextureMatrixInverse'
  , 'gl_TextureMatrixInverseTranspose'
  , 'gl_TextureMatrixTranspose'
  , 'gl_Vertex'
  , 'greaterThan'
  , 'greaterThanEqual'
  , 'inversesqrt'
  , 'length'
  , 'lessThan'
  , 'lessThanEqual'
  , 'log'
  , 'log2'
  , 'matrixCompMult'
  , 'max'
  , 'min'
  , 'mix'
  , 'mod'
  , 'normalize'
  , 'not'
  , 'notEqual'
  , 'pow'
  , 'radians'
  , 'reflect'
  , 'refract'
  , 'sign'
  , 'sin'
  , 'smoothstep'
  , 'sqrt'
  , 'step'
  , 'tan'
  , 'texture2D'
  , 'texture2DLod'
  , 'texture2DProj'
  , 'texture2DProjLod'
  , 'textureCube'
  , 'textureCubeLod'
  , 'texture2DLodEXT'
  , 'texture2DProjLodEXT'
  , 'textureCubeLodEXT'
  , 'texture2DGradEXT'
  , 'texture2DProjGradEXT'
  , 'textureCubeGradEXT'
]

},{}],394:[function(_dereq_,module,exports){
var v100 = _dereq_('./literals')

module.exports = v100.slice().concat([
   'layout'
  , 'centroid'
  , 'smooth'
  , 'case'
  , 'mat2x2'
  , 'mat2x3'
  , 'mat2x4'
  , 'mat3x2'
  , 'mat3x3'
  , 'mat3x4'
  , 'mat4x2'
  , 'mat4x3'
  , 'mat4x4'
  , 'uint'
  , 'uvec2'
  , 'uvec3'
  , 'uvec4'
  , 'samplerCubeShadow'
  , 'sampler2DArray'
  , 'sampler2DArrayShadow'
  , 'isampler2D'
  , 'isampler3D'
  , 'isamplerCube'
  , 'isampler2DArray'
  , 'usampler2D'
  , 'usampler3D'
  , 'usamplerCube'
  , 'usampler2DArray'
  , 'coherent'
  , 'restrict'
  , 'readonly'
  , 'writeonly'
  , 'resource'
  , 'atomic_uint'
  , 'noperspective'
  , 'patch'
  , 'sample'
  , 'subroutine'
  , 'common'
  , 'partition'
  , 'active'
  , 'filter'
  , 'image1D'
  , 'image2D'
  , 'image3D'
  , 'imageCube'
  , 'iimage1D'
  , 'iimage2D'
  , 'iimage3D'
  , 'iimageCube'
  , 'uimage1D'
  , 'uimage2D'
  , 'uimage3D'
  , 'uimageCube'
  , 'image1DArray'
  , 'image2DArray'
  , 'iimage1DArray'
  , 'iimage2DArray'
  , 'uimage1DArray'
  , 'uimage2DArray'
  , 'image1DShadow'
  , 'image2DShadow'
  , 'image1DArrayShadow'
  , 'image2DArrayShadow'
  , 'imageBuffer'
  , 'iimageBuffer'
  , 'uimageBuffer'
  , 'sampler1DArray'
  , 'sampler1DArrayShadow'
  , 'isampler1D'
  , 'isampler1DArray'
  , 'usampler1D'
  , 'usampler1DArray'
  , 'isampler2DRect'
  , 'usampler2DRect'
  , 'samplerBuffer'
  , 'isamplerBuffer'
  , 'usamplerBuffer'
  , 'sampler2DMS'
  , 'isampler2DMS'
  , 'usampler2DMS'
  , 'sampler2DMSArray'
  , 'isampler2DMSArray'
  , 'usampler2DMSArray'
])

},{"./literals":395}],395:[function(_dereq_,module,exports){
module.exports = [
  // current
    'precision'
  , 'highp'
  , 'mediump'
  , 'lowp'
  , 'attribute'
  , 'const'
  , 'uniform'
  , 'varying'
  , 'break'
  , 'continue'
  , 'do'
  , 'for'
  , 'while'
  , 'if'
  , 'else'
  , 'in'
  , 'out'
  , 'inout'
  , 'float'
  , 'int'
  , 'void'
  , 'bool'
  , 'true'
  , 'false'
  , 'discard'
  , 'return'
  , 'mat2'
  , 'mat3'
  , 'mat4'
  , 'vec2'
  , 'vec3'
  , 'vec4'
  , 'ivec2'
  , 'ivec3'
  , 'ivec4'
  , 'bvec2'
  , 'bvec3'
  , 'bvec4'
  , 'sampler1D'
  , 'sampler2D'
  , 'sampler3D'
  , 'samplerCube'
  , 'sampler1DShadow'
  , 'sampler2DShadow'
  , 'struct'

  // future
  , 'asm'
  , 'class'
  , 'union'
  , 'enum'
  , 'typedef'
  , 'template'
  , 'this'
  , 'packed'
  , 'goto'
  , 'switch'
  , 'default'
  , 'inline'
  , 'noinline'
  , 'volatile'
  , 'public'
  , 'static'
  , 'extern'
  , 'external'
  , 'interface'
  , 'long'
  , 'short'
  , 'double'
  , 'half'
  , 'fixed'
  , 'unsigned'
  , 'input'
  , 'output'
  , 'hvec2'
  , 'hvec3'
  , 'hvec4'
  , 'dvec2'
  , 'dvec3'
  , 'dvec4'
  , 'fvec2'
  , 'fvec3'
  , 'fvec4'
  , 'sampler2DRect'
  , 'sampler3DRect'
  , 'sampler2DRectShadow'
  , 'sizeof'
  , 'cast'
  , 'namespace'
  , 'using'
]

},{}],396:[function(_dereq_,module,exports){
module.exports = [
    '<<='
  , '>>='
  , '++'
  , '--'
  , '<<'
  , '>>'
  , '<='
  , '>='
  , '=='
  , '!='
  , '&&'
  , '||'
  , '+='
  , '-='
  , '*='
  , '/='
  , '%='
  , '&='
  , '^^'
  , '^='
  , '|='
  , '('
  , ')'
  , '['
  , ']'
  , '.'
  , '!'
  , '~'
  , '*'
  , '/'
  , '%'
  , '+'
  , '-'
  , '<'
  , '>'
  , '&'
  , '^'
  , '|'
  , '?'
  , ':'
  , '='
  , ','
  , ';'
  , '{'
  , '}'
]

},{}],397:[function(_dereq_,module,exports){
var tokenize = _dereq_('./index')

module.exports = tokenizeString

function tokenizeString(str, opt) {
  var generator = tokenize(opt)
  var tokens = []

  tokens = tokens.concat(generator(str))
  tokens = tokens.concat(generator(null))

  return tokens
}

},{"./index":391}],398:[function(_dereq_,module,exports){
module.exports = function(strings) {
  if (typeof strings === 'string') strings = [strings]
  var exprs = [].slice.call(arguments,1)
  var parts = []
  for (var i = 0; i < strings.length-1; i++) {
    parts.push(strings[i], exprs[i] || '')
  }
  parts.push(strings[i])
  return parts.join('')
}

},{}],399:[function(_dereq_,module,exports){
(function (global){
'use strict'

var isBrowser = _dereq_('is-browser')
var hasHover

if (typeof global.matchMedia === 'function') {
	hasHover = !global.matchMedia('(hover: none)').matches
}
else {
	hasHover = isBrowser
}

module.exports = hasHover

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"is-browser":406}],400:[function(_dereq_,module,exports){
'use strict'

var isBrowser = _dereq_('is-browser')

function detect() {
	var supported = false

	try {
		var opts = Object.defineProperty({}, 'passive', {
			get: function() {
				supported = true
			}
		})

		window.addEventListener('test', null, opts)
		window.removeEventListener('test', null, opts)
	} catch(e) {
		supported = false
	}

	return supported
}

module.exports = isBrowser && detect()

},{"is-browser":406}],401:[function(_dereq_,module,exports){
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  var e, m
  var eLen = (nBytes * 8) - mLen - 1
  var eMax = (1 << eLen) - 1
  var eBias = eMax >> 1
  var nBits = -7
  var i = isLE ? (nBytes - 1) : 0
  var d = isLE ? -1 : 1
  var s = buffer[offset + i]

  i += d

  e = s & ((1 << (-nBits)) - 1)
  s >>= (-nBits)
  nBits += eLen
  for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  m = e & ((1 << (-nBits)) - 1)
  e >>= (-nBits)
  nBits += mLen
  for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  if (e === 0) {
    e = 1 - eBias
  } else if (e === eMax) {
    return m ? NaN : ((s ? -1 : 1) * Infinity)
  } else {
    m = m + Math.pow(2, mLen)
    e = e - eBias
  }
  return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}

exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  var e, m, c
  var eLen = (nBytes * 8) - mLen - 1
  var eMax = (1 << eLen) - 1
  var eBias = eMax >> 1
  var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  var i = isLE ? 0 : (nBytes - 1)
  var d = isLE ? 1 : -1
  var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0

  value = Math.abs(value)

  if (isNaN(value) || value === Infinity) {
    m = isNaN(value) ? 1 : 0
    e = eMax
  } else {
    e = Math.floor(Math.log(value) / Math.LN2)
    if (value * (c = Math.pow(2, -e)) < 1) {
      e--
      c *= 2
    }
    if (e + eBias >= 1) {
      value += rt / c
    } else {
      value += rt * Math.pow(2, 1 - eBias)
    }
    if (value * c >= 2) {
      e++
      c /= 2
    }

    if (e + eBias >= eMax) {
      m = 0
      e = eMax
    } else if (e + eBias >= 1) {
      m = ((value * c) - 1) * Math.pow(2, mLen)
      e = e + eBias
    } else {
      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
      e = 0
    }
  }

  for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}

  e = (e << mLen) | m
  eLen += mLen
  for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}

  buffer[offset + i - d] |= s * 128
}

},{}],402:[function(_dereq_,module,exports){
"use strict"

//High level idea:
// 1. Use Clarkson's incremental construction to find convex hull
// 2. Point location in triangulation by jump and walk

module.exports = incrementalConvexHull

var orient = _dereq_("robust-orientation")
var compareCell = _dereq_("simplicial-complex").compareCells

function compareInt(a, b) {
  return a - b
}

function Simplex(vertices, adjacent, boundary) {
  this.vertices = vertices
  this.adjacent = adjacent
  this.boundary = boundary
  this.lastVisited = -1
}

Simplex.prototype.flip = function() {
  var t = this.vertices[0]
  this.vertices[0] = this.vertices[1]
  this.vertices[1] = t
  var u = this.adjacent[0]
  this.adjacent[0] = this.adjacent[1]
  this.adjacent[1] = u
}

function GlueFacet(vertices, cell, index) {
  this.vertices = vertices
  this.cell = cell
  this.index = index
}

function compareGlue(a, b) {
  return compareCell(a.vertices, b.vertices)
}

function bakeOrient(d) {
  var code = ["function orient(){var tuple=this.tuple;return test("]
  for(var i=0; i<=d; ++i) {
    if(i > 0) {
      code.push(",")
    }
    code.push("tuple[", i, "]")
  }
  code.push(")}return orient")
  var proc = new Function("test", code.join(""))
  var test = orient[d+1]
  if(!test) {
    test = orient
  }
  return proc(test)
}

var BAKED = []

function Triangulation(dimension, vertices, simplices) {
  this.dimension = dimension
  this.vertices = vertices
  this.simplices = simplices
  this.interior = simplices.filter(function(c) {
    return !c.boundary
  })

  this.tuple = new Array(dimension+1)
  for(var i=0; i<=dimension; ++i) {
    this.tuple[i] = this.vertices[i]
  }

  var o = BAKED[dimension]
  if(!o) {
    o = BAKED[dimension] = bakeOrient(dimension)
  }
  this.orient = o
}

var proto = Triangulation.prototype

//Degenerate situation where we are on boundary, but coplanar to face
proto.handleBoundaryDegeneracy = function(cell, point) {
  var d = this.dimension
  var n = this.vertices.length - 1
  var tuple = this.tuple
  var verts = this.vertices

  //Dumb solution: Just do dfs from boundary cell until we find any peak, or terminate
  var toVisit = [ cell ]
  cell.lastVisited = -n
  while(toVisit.length > 0) {
    cell = toVisit.pop()
    var cellVerts = cell.vertices
    var cellAdj = cell.adjacent
    for(var i=0; i<=d; ++i) {
      var neighbor = cellAdj[i]
      if(!neighbor.boundary || neighbor.lastVisited <= -n) {
        continue
      }
      var nv = neighbor.vertices
      for(var j=0; j<=d; ++j) {
        var vv = nv[j]
        if(vv < 0) {
          tuple[j] = point
        } else {
          tuple[j] = verts[vv]
        }
      }
      var o = this.orient()
      if(o > 0) {
        return neighbor
      }
      neighbor.lastVisited = -n
      if(o === 0) {
        toVisit.push(neighbor)
      }
    }
  }
  return null
}

proto.walk = function(point, random) {
  //Alias local properties
  var n = this.vertices.length - 1
  var d = this.dimension
  var verts = this.vertices
  var tuple = this.tuple

  //Compute initial jump cell
  var initIndex = random ? (this.interior.length * Math.random())|0 : (this.interior.length-1)
  var cell = this.interior[ initIndex ]

  //Start walking
outerLoop:
  while(!cell.boundary) {
    var cellVerts = cell.vertices
    var cellAdj = cell.adjacent

    for(var i=0; i<=d; ++i) {
      tuple[i] = verts[cellVerts[i]]
    }
    cell.lastVisited = n

    //Find farthest adjacent cell
    for(var i=0; i<=d; ++i) {
      var neighbor = cellAdj[i]
      if(neighbor.lastVisited >= n) {
        continue
      }
      var prev = tuple[i]
      tuple[i] = point
      var o = this.orient()
      tuple[i] = prev
      if(o < 0) {
        cell = neighbor
        continue outerLoop
      } else {
        if(!neighbor.boundary) {
          neighbor.lastVisited = n
        } else {
          neighbor.lastVisited = -n
        }
      }
    }
    return
  }

  return cell
}

proto.addPeaks = function(point, cell) {
  var n = this.vertices.length - 1
  var d = this.dimension
  var verts = this.vertices
  var tuple = this.tuple
  var interior = this.interior
  var simplices = this.simplices

  //Walking finished at boundary, time to add peaks
  var tovisit = [ cell ]

  //Stretch initial boundary cell into a peak
  cell.lastVisited = n
  cell.vertices[cell.vertices.indexOf(-1)] = n
  cell.boundary = false
  interior.push(cell)

  //Record a list of all new boundaries created by added peaks so we can glue them together when we are all done
  var glueFacets = []

  //Do a traversal of the boundary walking outward from starting peak
  while(tovisit.length > 0) {
    //Pop off peak and walk over adjacent cells
    var cell = tovisit.pop()
    var cellVerts = cell.vertices
    var cellAdj = cell.adjacent
    var indexOfN = cellVerts.indexOf(n)
    if(indexOfN < 0) {
      continue
    }

    for(var i=0; i<=d; ++i) {
      if(i === indexOfN) {
        continue
      }

      //For each boundary neighbor of the cell
      var neighbor = cellAdj[i]
      if(!neighbor.boundary || neighbor.lastVisited >= n) {
        continue
      }

      var nv = neighbor.vertices

      //Test if neighbor is a peak
      if(neighbor.lastVisited !== -n) {      
        //Compute orientation of p relative to each boundary peak
        var indexOfNeg1 = 0
        for(var j=0; j<=d; ++j) {
          if(nv[j] < 0) {
            indexOfNeg1 = j
            tuple[j] = point
          } else {
            tuple[j] = verts[nv[j]]
          }
        }
        var o = this.orient()

        //Test if neighbor cell is also a peak
        if(o > 0) {
          nv[indexOfNeg1] = n
          neighbor.boundary = false
          interior.push(neighbor)
          tovisit.push(neighbor)
          neighbor.lastVisited = n
          continue
        } else {
          neighbor.lastVisited = -n
        }
      }

      var na = neighbor.adjacent

      //Otherwise, replace neighbor with new face
      var vverts = cellVerts.slice()
      var vadj = cellAdj.slice()
      var ncell = new Simplex(vverts, vadj, true)
      simplices.push(ncell)

      //Connect to neighbor
      var opposite = na.indexOf(cell)
      if(opposite < 0) {
        continue
      }
      na[opposite] = ncell
      vadj[indexOfN] = neighbor

      //Connect to cell
      vverts[i] = -1
      vadj[i] = cell
      cellAdj[i] = ncell

      //Flip facet
      ncell.flip()

      //Add to glue list
      for(var j=0; j<=d; ++j) {
        var uu = vverts[j]
        if(uu < 0 || uu === n) {
          continue
        }
        var nface = new Array(d-1)
        var nptr = 0
        for(var k=0; k<=d; ++k) {
          var vv = vverts[k]
          if(vv < 0 || k === j) {
            continue
          }
          nface[nptr++] = vv
        }
        glueFacets.push(new GlueFacet(nface, ncell, j))
      }
    }
  }

  //Glue boundary facets together
  glueFacets.sort(compareGlue)

  for(var i=0; i+1<glueFacets.length; i+=2) {
    var a = glueFacets[i]
    var b = glueFacets[i+1]
    var ai = a.index
    var bi = b.index
    if(ai < 0 || bi < 0) {
      continue
    }
    a.cell.adjacent[a.index] = b.cell
    b.cell.adjacent[b.index] = a.cell
  }
}

proto.insert = function(point, random) {
  //Add point
  var verts = this.vertices
  verts.push(point)

  var cell = this.walk(point, random)
  if(!cell) {
    return
  }

  //Alias local properties
  var d = this.dimension
  var tuple = this.tuple

  //Degenerate case: If point is coplanar to cell, then walk until we find a non-degenerate boundary
  for(var i=0; i<=d; ++i) {
    var vv = cell.vertices[i]
    if(vv < 0) {
      tuple[i] = point
    } else {
      tuple[i] = verts[vv]
    }
  }
  var o = this.orient(tuple)
  if(o < 0) {
    return
  } else if(o === 0) {
    cell = this.handleBoundaryDegeneracy(cell, point)
    if(!cell) {
      return
    }
  }

  //Add peaks
  this.addPeaks(point, cell)
}

//Extract all boundary cells
proto.boundary = function() {
  var d = this.dimension
  var boundary = []
  var cells = this.simplices
  var nc = cells.length
  for(var i=0; i<nc; ++i) {
    var c = cells[i]
    if(c.boundary) {
      var bcell = new Array(d)
      var cv = c.vertices
      var ptr = 0
      var parity = 0
      for(var j=0; j<=d; ++j) {
        if(cv[j] >= 0) {
          bcell[ptr++] = cv[j]
        } else {
          parity = j&1
        }
      }
      if(parity === (d&1)) {
        var t = bcell[0]
        bcell[0] = bcell[1]
        bcell[1] = t
      }
      boundary.push(bcell)
    }
  }
  return boundary
}

function incrementalConvexHull(points, randomSearch) {
  var n = points.length
  if(n === 0) {
    throw new Error("Must have at least d+1 points")
  }
  var d = points[0].length
  if(n <= d) {
    throw new Error("Must input at least d+1 points")
  }

  //FIXME: This could be degenerate, but need to select d+1 non-coplanar points to bootstrap process
  var initialSimplex = points.slice(0, d+1)

  //Make sure initial simplex is positively oriented
  var o = orient.apply(void 0, initialSimplex)
  if(o === 0) {
    throw new Error("Input not in general position")
  }
  var initialCoords = new Array(d+1)
  for(var i=0; i<=d; ++i) {
    initialCoords[i] = i
  }
  if(o < 0) {
    initialCoords[0] = 1
    initialCoords[1] = 0
  }

  //Create initial topological index, glue pointers together (kind of messy)
  var initialCell = new Simplex(initialCoords, new Array(d+1), false)
  var boundary = initialCell.adjacent
  var list = new Array(d+2)
  for(var i=0; i<=d; ++i) {
    var verts = initialCoords.slice()
    for(var j=0; j<=d; ++j) {
      if(j === i) {
        verts[j] = -1
      }
    }
    var t = verts[0]
    verts[0] = verts[1]
    verts[1] = t
    var cell = new Simplex(verts, new Array(d+1), true)
    boundary[i] = cell
    list[i] = cell
  }
  list[d+1] = initialCell
  for(var i=0; i<=d; ++i) {
    var verts = boundary[i].vertices
    var adj = boundary[i].adjacent
    for(var j=0; j<=d; ++j) {
      var v = verts[j]
      if(v < 0) {
        adj[j] = initialCell
        continue
      }
      for(var k=0; k<=d; ++k) {
        if(boundary[k].vertices.indexOf(v) < 0) {
          adj[j] = boundary[k]
        }
      }
    }
  }

  //Initialize triangles
  var triangles = new Triangulation(d, initialSimplex, list)

  //Insert remaining points
  var useRandom = !!randomSearch
  for(var i=d+1; i<n; ++i) {
    triangles.insert(points[i], useRandom)
  }
  
  //Extract boundary cells
  return triangles.boundary()
}
},{"robust-orientation":491,"simplicial-complex":501}],403:[function(_dereq_,module,exports){
"use strict"

var bounds = _dereq_("binary-search-bounds")

var NOT_FOUND = 0
var SUCCESS = 1
var EMPTY = 2

module.exports = createWrapper

function IntervalTreeNode(mid, left, right, leftPoints, rightPoints) {
  this.mid = mid
  this.left = left
  this.right = right
  this.leftPoints = leftPoints
  this.rightPoints = rightPoints
  this.count = (left ? left.count : 0) + (right ? right.count : 0) + leftPoints.length
}

var proto = IntervalTreeNode.prototype

function copy(a, b) {
  a.mid = b.mid
  a.left = b.left
  a.right = b.right
  a.leftPoints = b.leftPoints
  a.rightPoints = b.rightPoints
  a.count = b.count
}

function rebuild(node, intervals) {
  var ntree = createIntervalTree(intervals)
  node.mid = ntree.mid
  node.left = ntree.left
  node.right = ntree.right
  node.leftPoints = ntree.leftPoints
  node.rightPoints = ntree.rightPoints
  node.count = ntree.count
}

function rebuildWithInterval(node, interval) {
  var intervals = node.intervals([])
  intervals.push(interval)
  rebuild(node, intervals)    
}

function rebuildWithoutInterval(node, interval) {
  var intervals = node.intervals([])
  var idx = intervals.indexOf(interval)
  if(idx < 0) {
    return NOT_FOUND
  }
  intervals.splice(idx, 1)
  rebuild(node, intervals)
  return SUCCESS
}

proto.intervals = function(result) {
  result.push.apply(result, this.leftPoints)
  if(this.left) {
    this.left.intervals(result)
  }
  if(this.right) {
    this.right.intervals(result)
  }
  return result
}

proto.insert = function(interval) {
  var weight = this.count - this.leftPoints.length
  this.count += 1
  if(interval[1] < this.mid) {
    if(this.left) {
      if(4*(this.left.count+1) > 3*(weight+1)) {
        rebuildWithInterval(this, interval)
      } else {
        this.left.insert(interval)
      }
    } else {
      this.left = createIntervalTree([interval])
    }
  } else if(interval[0] > this.mid) {
    if(this.right) {
      if(4*(this.right.count+1) > 3*(weight+1)) {
        rebuildWithInterval(this, interval)
      } else {
        this.right.insert(interval)
      }
    } else {
      this.right = createIntervalTree([interval])
    }
  } else {
    var l = bounds.ge(this.leftPoints, interval, compareBegin)
    var r = bounds.ge(this.rightPoints, interval, compareEnd)
    this.leftPoints.splice(l, 0, interval)
    this.rightPoints.splice(r, 0, interval)
  }
}

proto.remove = function(interval) {
  var weight = this.count - this.leftPoints
  if(interval[1] < this.mid) {
    if(!this.left) {
      return NOT_FOUND
    }
    var rw = this.right ? this.right.count : 0
    if(4 * rw > 3 * (weight-1)) {
      return rebuildWithoutInterval(this, interval)
    }
    var r = this.left.remove(interval)
    if(r === EMPTY) {
      this.left = null
      this.count -= 1
      return SUCCESS
    } else if(r === SUCCESS) {
      this.count -= 1
    }
    return r
  } else if(interval[0] > this.mid) {
    if(!this.right) {
      return NOT_FOUND
    }
    var lw = this.left ? this.left.count : 0
    if(4 * lw > 3 * (weight-1)) {
      return rebuildWithoutInterval(this, interval)
    }
    var r = this.right.remove(interval)
    if(r === EMPTY) {
      this.right = null
      this.count -= 1
      return SUCCESS
    } else if(r === SUCCESS) {
      this.count -= 1
    }
    return r
  } else {
    if(this.count === 1) {
      if(this.leftPoints[0] === interval) {
        return EMPTY
      } else {
        return NOT_FOUND
      }
    }
    if(this.leftPoints.length === 1 && this.leftPoints[0] === interval) {
      if(this.left && this.right) {
        var p = this
        var n = this.left
        while(n.right) {
          p = n
          n = n.right
        }
        if(p === this) {
          n.right = this.right
        } else {
          var l = this.left
          var r = this.right
          p.count -= n.count
          p.right = n.left
          n.left = l
          n.right = r
        }
        copy(this, n)
        this.count = (this.left?this.left.count:0) + (this.right?this.right.count:0) + this.leftPoints.length
      } else if(this.left) {
        copy(this, this.left)
      } else {
        copy(this, this.right)
      }
      return SUCCESS
    }
    for(var l = bounds.ge(this.leftPoints, interval, compareBegin); l<this.leftPoints.length; ++l) {
      if(this.leftPoints[l][0] !== interval[0]) {
        break
      }
      if(this.leftPoints[l] === interval) {
        this.count -= 1
        this.leftPoints.splice(l, 1)
        for(var r = bounds.ge(this.rightPoints, interval, compareEnd); r<this.rightPoints.length; ++r) {
          if(this.rightPoints[r][1] !== interval[1]) {
            break
          } else if(this.rightPoints[r] === interval) {
            this.rightPoints.splice(r, 1)
            return SUCCESS
          }
        }
      }
    }
    return NOT_FOUND
  }
}

function reportLeftRange(arr, hi, cb) {
  for(var i=0; i<arr.length && arr[i][0] <= hi; ++i) {
    var r = cb(arr[i])
    if(r) { return r }
  }
}

function reportRightRange(arr, lo, cb) {
  for(var i=arr.length-1; i>=0 && arr[i][1] >= lo; --i) {
    var r = cb(arr[i])
    if(r) { return r }
  }
}

function reportRange(arr, cb) {
  for(var i=0; i<arr.length; ++i) {
    var r = cb(arr[i])
    if(r) { return r }
  }
}

proto.queryPoint = function(x, cb) {
  if(x < this.mid) {
    if(this.left) {
      var r = this.left.queryPoint(x, cb)
      if(r) { return r }
    }
    return reportLeftRange(this.leftPoints, x, cb)
  } else if(x > this.mid) {
    if(this.right) {
      var r = this.right.queryPoint(x, cb)
      if(r) { return r }
    }
    return reportRightRange(this.rightPoints, x, cb)
  } else {
    return reportRange(this.leftPoints, cb)
  }
}

proto.queryInterval = function(lo, hi, cb) {
  if(lo < this.mid && this.left) {
    var r = this.left.queryInterval(lo, hi, cb)
    if(r) { return r }
  }
  if(hi > this.mid && this.right) {
    var r = this.right.queryInterval(lo, hi, cb)
    if(r) { return r }
  }
  if(hi < this.mid) {
    return reportLeftRange(this.leftPoints, hi, cb)
  } else if(lo > this.mid) {
    return reportRightRange(this.rightPoints, lo, cb)
  } else {
    return reportRange(this.leftPoints, cb)
  }
}

function compareNumbers(a, b) {
  return a - b
}

function compareBegin(a, b) {
  var d = a[0] - b[0]
  if(d) { return d }
  return a[1] - b[1]
}

function compareEnd(a, b) {
  var d = a[1] - b[1]
  if(d) { return d }
  return a[0] - b[0]
}

function createIntervalTree(intervals) {
  if(intervals.length === 0) {
    return null
  }
  var pts = []
  for(var i=0; i<intervals.length; ++i) {
    pts.push(intervals[i][0], intervals[i][1])
  }
  pts.sort(compareNumbers)

  var mid = pts[pts.length>>1]

  var leftIntervals = []
  var rightIntervals = []
  var centerIntervals = []
  for(var i=0; i<intervals.length; ++i) {
    var s = intervals[i]
    if(s[1] < mid) {
      leftIntervals.push(s)
    } else if(mid < s[0]) {
      rightIntervals.push(s)
    } else {
      centerIntervals.push(s)
    }
  }

  //Split center intervals
  var leftPoints = centerIntervals
  var rightPoints = centerIntervals.slice()
  leftPoints.sort(compareBegin)
  rightPoints.sort(compareEnd)

  return new IntervalTreeNode(mid, 
    createIntervalTree(leftIntervals),
    createIntervalTree(rightIntervals),
    leftPoints,
    rightPoints)
}

//User friendly wrapper that makes it possible to support empty trees
function IntervalTree(root) {
  this.root = root
}

var tproto = IntervalTree.prototype

tproto.insert = function(interval) {
  if(this.root) {
    this.root.insert(interval)
  } else {
    this.root = new IntervalTreeNode(interval[0], null, null, [interval], [interval])
  }
}

tproto.remove = function(interval) {
  if(this.root) {
    var r = this.root.remove(interval)
    if(r === EMPTY) {
      this.root = null
    }
    return r !== NOT_FOUND
  }
  return false
}

tproto.queryPoint = function(p, cb) {
  if(this.root) {
    return this.root.queryPoint(p, cb)
  }
}

tproto.queryInterval = function(lo, hi, cb) {
  if(lo <= hi && this.root) {
    return this.root.queryInterval(lo, hi, cb)
  }
}

Object.defineProperty(tproto, "count", {
  get: function() {
    if(this.root) {
      return this.root.count
    }
    return 0
  }
})

Object.defineProperty(tproto, "intervals", {
  get: function() {
    if(this.root) {
      return this.root.intervals([])
    }
    return []
  }
})

function createWrapper(intervals) {
  if(!intervals || intervals.length === 0) {
    return new IntervalTree(null)
  }
  return new IntervalTree(createIntervalTree(intervals))
}

},{"binary-search-bounds":79}],404:[function(_dereq_,module,exports){
"use strict"

function invertPermutation(pi, result) {
  result = result || new Array(pi.length)
  for(var i=0; i<pi.length; ++i) {
    result[pi[i]] = i
  }
  return result
}

module.exports = invertPermutation
},{}],405:[function(_dereq_,module,exports){
"use strict"

function iota(n) {
  var result = new Array(n)
  for(var i=0; i<n; ++i) {
    result[i] = i
  }
  return result
}

module.exports = iota
},{}],406:[function(_dereq_,module,exports){
module.exports = true;
},{}],407:[function(_dereq_,module,exports){
/*!
 * Determine if an object is a Buffer
 *
 * @author   Feross Aboukhadijeh <https://feross.org>
 * @license  MIT
 */

// The _isBuffer check is for Safari 5-7 support, because it's missing
// Object.prototype.constructor. Remove this eventually
module.exports = function (obj) {
  return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
}

function isBuffer (obj) {
  return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
}

// For Node v0.10 support. Remove this eventually.
function isSlowBuffer (obj) {
  return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
}

},{}],408:[function(_dereq_,module,exports){
'use strict';
module.exports = typeof navigator !== 'undefined' &&
	(/MSIE/.test(navigator.userAgent) || /Trident\//.test(navigator.appVersion));

},{}],409:[function(_dereq_,module,exports){
'use strict'

module.exports = isMobile;
module.exports.isMobile = isMobile;

var mobileRE = /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i;

var tabletRE = /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino|android|ipad|playbook|silk/i;

function isMobile (opts) {
  if (!opts) opts = {}
  var ua = opts.ua
  if (!ua && typeof navigator !== 'undefined') ua = navigator.userAgent;
  if (ua && ua.headers && typeof ua.headers['user-agent'] === 'string') {
    ua = ua.headers['user-agent'];
  }
  if (typeof ua !== 'string') return false;

  return opts.tablet
    ? tabletRE.test(ua)
    : mobileRE.test(ua);
}

},{}],410:[function(_dereq_,module,exports){
'use strict';
module.exports = function (x) {
	var type = typeof x;
	return x !== null && (type === 'object' || type === 'function');
};

},{}],411:[function(_dereq_,module,exports){
'use strict';
var toString = Object.prototype.toString;

module.exports = function (x) {
	var prototype;
	return toString.call(x) === '[object Object]' && (prototype = Object.getPrototypeOf(x), prototype === null || prototype === Object.getPrototypeOf({}));
};

},{}],412:[function(_dereq_,module,exports){
'use strict';

/**
 * Is this string all whitespace?
 * This solution kind of makes my brain hurt, but it's significantly faster
 * than !str.trim() or any other solution I could find.
 *
 * whitespace codes from: http://en.wikipedia.org/wiki/Whitespace_character
 * and verified with:
 *
 *  for(var i = 0; i < 65536; i++) {
 *      var s = String.fromCharCode(i);
 *      if(+s===0 && !s.trim()) console.log(i, s);
 *  }
 *
 * which counts a couple of these as *not* whitespace, but finds nothing else
 * that *is* whitespace. Note that charCodeAt stops at 16 bits, but it appears
 * that there are no whitespace characters above this, and code points above
 * this do not map onto white space characters.
 */

module.exports = function(str){
    var l = str.length,
        a;
    for(var i = 0; i < l; i++) {
        a = str.charCodeAt(i);
        if((a < 9 || a > 13) && (a !== 32) && (a !== 133) && (a !== 160) &&
            (a !== 5760) && (a !== 6158) && (a < 8192 || a > 8205) &&
            (a !== 8232) && (a !== 8233) && (a !== 8239) && (a !== 8287) &&
            (a !== 8288) && (a !== 12288) && (a !== 65279)) {
                return false;
        }
    }
    return true;
}

},{}],413:[function(_dereq_,module,exports){
'use strict'

module.exports = function isPath(str) {
	if (typeof str !== 'string') return false

	str = str.trim()

	// https://www.w3.org/TR/SVG/paths.html#PathDataBNF
	if (/^[mzlhvcsqta]\s*[-+.0-9][^mlhvzcsqta]+/i.test(str) && /[\dz]$/i.test(str) && str.length > 4) return true

	return false
}

},{}],414:[function(_dereq_,module,exports){
function lerp(v0, v1, t) {
    return v0*(1-t)+v1*t
}
module.exports = lerp
},{}],415:[function(_dereq_,module,exports){
(function (global){
(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
	typeof define === 'function' && define.amd ? define(factory) :
	(global.mapboxgl = factory());
}(this, (function () { 'use strict';

/* eslint-disable */

var shared, worker, mapboxgl;
// define gets called three times: one for each chunk. we rely on the order
// they're imported to know which is which
function define(_, chunk) {
if (!shared) {
    shared = chunk;
} else if (!worker) {
    worker = chunk;
} else {
    var workerBundleString = 'var sharedChunk = {}; (' + shared + ')(sharedChunk); (' + worker + ')(sharedChunk);'

    var sharedChunk = {};
    shared(sharedChunk);
    mapboxgl = chunk(sharedChunk);
    mapboxgl.workerUrl = window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' }));
}
}


define(["exports"],function(t){"use strict";var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function r(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function n(t,e){return t(e={exports:{}},e.exports),e.exports}var i=o;function o(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=n,this.p2x=r,this.p2y=n;}o.prototype.sampleCurveX=function(t){return((this.ax*t+this.bx)*t+this.cx)*t},o.prototype.sampleCurveY=function(t){return((this.ay*t+this.by)*t+this.cy)*t},o.prototype.sampleCurveDerivativeX=function(t){return(3*this.ax*t+2*this.bx)*t+this.cx},o.prototype.solveCurveX=function(t,e){var r,n,i,o,a;for(void 0===e&&(e=1e-6),i=t,a=0;a<8;a++){if(o=this.sampleCurveX(i)-t,Math.abs(o)<e)return i;var s=this.sampleCurveDerivativeX(i);if(Math.abs(s)<1e-6)break;i-=o/s;}if((i=t)<(r=0))return r;if(i>(n=1))return n;for(;r<n;){if(o=this.sampleCurveX(i),Math.abs(o-t)<e)return i;t>o?r=i:n=i,i=.5*(n-r)+r;}return i},o.prototype.solve=function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))};var a=function(t,e,r){this.column=t,this.row=e,this.zoom=r;};a.prototype.clone=function(){return new a(this.column,this.row,this.zoom)},a.prototype.zoomTo=function(t){return this.clone()._zoomTo(t)},a.prototype.sub=function(t){return this.clone()._sub(t)},a.prototype._zoomTo=function(t){var e=Math.pow(2,t-this.zoom);return this.column*=e,this.row*=e,this.zoom=t,this},a.prototype._sub=function(t){return t=t.zoomTo(this.zoom),this.column-=t.column,this.row-=t.row,this};var s=u;function u(t,e){this.x=t,this.y=e;}function l(t,e,r,n){var o=new i(t,e,r,n);return function(t){return o.solve(t)}}u.prototype={clone:function(){return new u(this.x,this.y)},add:function(t){return this.clone()._add(t)},sub:function(t){return this.clone()._sub(t)},multByPoint:function(t){return this.clone()._multByPoint(t)},divByPoint:function(t){return this.clone()._divByPoint(t)},mult:function(t){return this.clone()._mult(t)},div:function(t){return this.clone()._div(t)},rotate:function(t){return this.clone()._rotate(t)},rotateAround:function(t,e){return this.clone()._rotateAround(t,e)},matMult:function(t){return this.clone()._matMult(t)},unit:function(){return this.clone()._unit()},perp:function(){return this.clone()._perp()},round:function(){return this.clone()._round()},mag:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals:function(t){return this.x===t.x&&this.y===t.y},dist:function(t){return Math.sqrt(this.distSqr(t))},distSqr:function(t){var e=t.x-this.x,r=t.y-this.y;return e*e+r*r},angle:function(){return Math.atan2(this.y,this.x)},angleTo:function(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith:function(t){return this.angleWithSep(t.x,t.y)},angleWithSep:function(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult:function(t){var e=t[0]*this.x+t[1]*this.y,r=t[2]*this.x+t[3]*this.y;return this.x=e,this.y=r,this},_add:function(t){return this.x+=t.x,this.y+=t.y,this},_sub:function(t){return this.x-=t.x,this.y-=t.y,this},_mult:function(t){return this.x*=t,this.y*=t,this},_div:function(t){return this.x/=t,this.y/=t,this},_multByPoint:function(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint:function(t){return this.x/=t.x,this.y/=t.y,this},_unit:function(){return this._div(this.mag()),this},_perp:function(){var t=this.y;return this.y=this.x,this.x=-t,this},_rotate:function(t){var e=Math.cos(t),r=Math.sin(t),n=e*this.x-r*this.y,i=r*this.x+e*this.y;return this.x=n,this.y=i,this},_rotateAround:function(t,e){var r=Math.cos(t),n=Math.sin(t),i=e.x+r*(this.x-e.x)-n*(this.y-e.y),o=e.y+n*(this.x-e.x)+r*(this.y-e.y);return this.x=i,this.y=o,this},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}},u.convert=function(t){return t instanceof u?t:Array.isArray(t)?new u(t[0],t[1]):t};var p=l(.25,.1,.25,1);function c(t,e,r){return Math.min(r,Math.max(e,t))}function h(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];for(var n=0,i=e;n<i.length;n+=1){var o=i[n];for(var a in o)t[a]=o[a];}return t}var f=1;function y(t,e){t.forEach(function(t){e[t]&&(e[t]=e[t].bind(e));});}function d(t,e){return-1!==t.indexOf(e,t.length-e.length)}function v(t,e,r){var n={};for(var i in t)n[i]=e.call(r||this,t[i],i,t);return n}function m(t,e,r){var n={};for(var i in t)e.call(r||this,t[i],i,t)&&(n[i]=t[i]);return n}function g(t){return Array.isArray(t)?t.map(g):"object"==typeof t&&t?v(t,g):t}var x={};function b(t){x[t]||("undefined"!=typeof console&&console.warn(t),x[t]=!0);}function w(t,e,r){return(r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)}function _(t){for(var e=0,r=0,n=t.length,i=n-1,o=void 0,a=void 0;r<n;i=r++)o=t[r],e+=((a=t[i]).x-o.x)*(o.y+a.y);return e}var A={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Image:"Image"};"function"==typeof Object.freeze&&Object.freeze(A);var k=function(t){function e(e,r,n){t.call(this,e),this.status=r,this.url=n,this.name=this.constructor.name,this.message=e;}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.toString=function(){return this.name+": "+this.message+" ("+this.status+"): "+this.url},e}(Error);function z(t){var e=new self.XMLHttpRequest;for(var r in e.open("GET",t.url,!0),t.headers)e.setRequestHeader(r,t.headers[r]);return e.withCredentials="include"===t.credentials,e}var S=function(t,e){var r=z(t);return r.responseType="arraybuffer",r.onerror=function(){e(new Error(r.statusText));},r.onload=function(){var n=r.response;if(0===n.byteLength&&200===r.status)return e(new Error("http status 200 returned without content."));r.status>=200&&r.status<300&&r.response?e(null,{data:n,cacheControl:r.getResponseHeader("Cache-Control"),expires:r.getResponseHeader("Expires")}):e(new k(r.statusText,r.status,t.url));},r.send(),r};function M(t,e,r){r[t]=r[t]||[],r[t].push(e);}function V(t,e,r){if(r&&r[t]){var n=r[t].indexOf(e);-1!==n&&r[t].splice(n,1);}}var B=function(t,e){void 0===e&&(e={}),h(this,e),this.type=t;},C=function(t){function e(e,r){void 0===r&&(r={}),t.call(this,"error",h({error:e},r));}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(B),I=function(){};I.prototype.on=function(t,e){return this._listeners=this._listeners||{},M(t,e,this._listeners),this},I.prototype.off=function(t,e){return V(t,e,this._listeners),V(t,e,this._oneTimeListeners),this},I.prototype.once=function(t,e){return this._oneTimeListeners=this._oneTimeListeners||{},M(t,e,this._oneTimeListeners),this},I.prototype.fire=function(t){"string"==typeof t&&(t=new B(t,arguments[1]||{}));var e=t.type;if(this.listens(e)){t.target=this;for(var r=0,n=this._listeners&&this._listeners[e]?this._listeners[e].slice():[];r<n.length;r+=1){n[r].call(this,t);}for(var i=0,o=this._oneTimeListeners&&this._oneTimeListeners[e]?this._oneTimeListeners[e].slice():[];i<o.length;i+=1){var a=o[i];V(e,a,this._oneTimeListeners),a.call(this,t);}var s=this._eventedParent;s&&(h(t,"function"==typeof this._eventedParentData?this._eventedParentData():this._eventedParentData),s.fire(t));}else d(e,"error")?console.error(t&&t.error||t||"Empty error event"):d(e,"warning")&&console.warn(t&&t.warning||t||"Empty warning event");return this},I.prototype.listens=function(t){return this._listeners&&this._listeners[t]&&this._listeners[t].length>0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)},I.prototype.setEventedParent=function(t,e){return this._eventedParent=t,this._eventedParentData=e,this};var E={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},light:{type:"light"},sources:{required:!0,type:"sources"},sprite:{type:"string"},glyphs:{type:"string"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:!0,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.0511,180,85.0511]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},"*":{type:"*"}},source_raster:{type:{required:!0,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.0511,180,85.0511]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},"*":{type:"*"}},source_raster_dem:{type:{required:!0,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.0511,180,85.0511]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{}},default:"mapbox"},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:{geojson:{}}},data:{type:"*"},maxzoom:{type:"number",default:18},buffer:{type:"number",default:128,maximum:512,minimum:0},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},lineMetrics:{type:"boolean",default:!1}},source_video:{type:{required:!0,type:"enum",values:{video:{}}},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:{image:{}}},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},background:{}},required:!0},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},layout_fill:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},layout_circle:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},layout_line:{"line-cap":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{butt:{},round:{},square:{}},default:"butt"},"line-join":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:{bevel:{},round:{},miter:{}},default:"miter"},"line-miter-limit":{type:"number",default:2,function:"interpolated","zoom-function":!0,requires:[{"line-join":"miter"}]},"line-round-limit":{type:"number",default:1.05,function:"interpolated","zoom-function":!0,requires:[{"line-join":"round"}]},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},layout_symbol:{"symbol-placement":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{point:{},line:{}},default:"point"},"symbol-spacing":{type:"number",default:250,minimum:1,function:"interpolated","zoom-function":!0,units:"pixels",requires:[{"symbol-placement":"line"}]},"symbol-avoid-edges":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1},"icon-allow-overlap":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1,requires:["icon-image"]},"icon-ignore-placement":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1,requires:["icon-image"]},"icon-optional":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1,requires:["icon-image","text-field"]},"icon-rotation-alignment":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"]},"icon-size":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,units:"factor of the original icon size",requires:["icon-image"]},"icon-text-fit":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"]},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",function:"interpolated","zoom-function":!0,requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}]},"icon-image":{type:"string",function:"piecewise-constant","zoom-function":!0,"property-function":!0,tokens:!0},"icon-rotate":{type:"number",default:0,period:360,function:"interpolated","zoom-function":!0,"property-function":!0,units:"degrees",requires:["icon-image"]},"icon-padding":{type:"number",default:2,minimum:0,function:"interpolated","zoom-function":!0,units:"pixels",requires:["icon-image"]},"icon-keep-upright":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":"line"}]},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,"property-function":!0,requires:["icon-image"]},"icon-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"]},"icon-pitch-alignment":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"]},"text-pitch-alignment":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"]},"text-rotation-alignment":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"]},"text-field":{type:"string",function:"piecewise-constant","zoom-function":!0,"property-function":!0,default:"",tokens:!0},"text-font":{type:"array",value:"string",function:"piecewise-constant","zoom-function":!0,"property-function":!0,default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"]},"text-size":{type:"number",default:16,minimum:0,units:"pixels",function:"interpolated","zoom-function":!0,"property-function":!0,requires:["text-field"]},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",function:"interpolated","zoom-function":!0,"property-function":!0,requires:["text-field"]},"text-line-height":{type:"number",default:1.2,units:"ems",function:"interpolated","zoom-function":!0,requires:["text-field"]},"text-letter-spacing":{type:"number",default:0,units:"ems",function:"interpolated","zoom-function":!0,"property-function":!0,requires:["text-field"]},"text-justify":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:{left:{},center:{},right:{}},default:"center",requires:["text-field"]},"text-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field"]},"text-max-angle":{type:"number",default:45,units:"degrees",function:"interpolated","zoom-function":!0,requires:["text-field",{"symbol-placement":"line"}]},"text-rotate":{type:"number",default:0,period:360,units:"degrees",function:"interpolated","zoom-function":!0,"property-function":!0,requires:["text-field"]},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",function:"interpolated","zoom-function":!0,requires:["text-field"]},"text-keep-upright":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":"line"}]},"text-transform":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"]},"text-offset":{type:"array",value:"number",units:"ems",function:"interpolated","zoom-function":!0,"property-function":!0,length:2,default:[0,0],requires:["text-field"]},"text-allow-overlap":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1,requires:["text-field"]},"text-ignore-placement":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1,requires:["text-field"]},"text-optional":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1,requires:["text-field","icon-image"]},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},filter:{type:"array",value:"*"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function_stop:{type:"array",minimum:0,maximum:22,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},expression_name:{type:"enum",values:{let:{group:"Variable binding"},var:{group:"Variable binding"},literal:{group:"Types"},array:{group:"Types"},at:{group:"Lookup"},case:{group:"Decision"},match:{group:"Decision"},coalesce:{group:"Decision"},step:{group:"Ramps, scales, curves"},interpolate:{group:"Ramps, scales, curves"},ln2:{group:"Math"},pi:{group:"Math"},e:{group:"Math"},typeof:{group:"Types"},string:{group:"Types"},number:{group:"Types"},boolean:{group:"Types"},object:{group:"Types"},collator:{group:"Types"},"to-string":{group:"Types"},"to-number":{group:"Types"},"to-boolean":{group:"Types"},"to-rgba":{group:"Color"},"to-color":{group:"Types"},rgb:{group:"Color"},rgba:{group:"Color"},get:{group:"Lookup"},has:{group:"Lookup"},length:{group:"Lookup"},properties:{group:"Feature data"},"geometry-type":{group:"Feature data"},id:{group:"Feature data"},zoom:{group:"Zoom"},"heatmap-density":{group:"Heatmap"},"line-progress":{group:"Heatmap"},"+":{group:"Math"},"*":{group:"Math"},"-":{group:"Math"},"/":{group:"Math"},"%":{group:"Math"},"^":{group:"Math"},sqrt:{group:"Math"},log10:{group:"Math"},ln:{group:"Math"},log2:{group:"Math"},sin:{group:"Math"},cos:{group:"Math"},tan:{group:"Math"},asin:{group:"Math"},acos:{group:"Math"},atan:{group:"Math"},min:{group:"Math"},max:{group:"Math"},round:{group:"Math"},abs:{group:"Math"},ceil:{group:"Math"},floor:{group:"Math"},"==":{group:"Decision"},"!=":{group:"Decision"},">":{group:"Decision"},"<":{group:"Decision"},">=":{group:"Decision"},"<=":{group:"Decision"},all:{group:"Decision"},any:{group:"Decision"},"!":{group:"Decision"},"is-supported-script":{group:"String"},upcase:{group:"String"},downcase:{group:"String"},concat:{group:"String"},"resolved-locale":{group:"String"}}},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},transition:!1,"zoom-function":!0,"property-function":!1,function:"piecewise-constant"},position:{type:"array",default:[1.15,210,30],length:3,value:"number",transition:!0,function:"interpolated","zoom-function":!0,"property-function":!1},color:{type:"color",default:"#ffffff",function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0},intensity:{type:"number",default:.5,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!0},"fill-opacity":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:1,minimum:0,maximum:1,transition:!0},"fill-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"fill-pattern"}]},"fill-outline-color":{type:"color",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}]},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"fill-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["fill-translate"]},"fill-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0}},paint_line:{"line-opacity":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:1,minimum:0,maximum:1,transition:!0},"line-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"line-pattern"}]},"line-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"line-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["line-translate"]},"line-width":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-gap-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-offset":{type:"number",default:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-dasharray":{type:"array",value:"number",function:"piecewise-constant","zoom-function":!0,minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}]},"line-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0},"line-gradient":{type:"color",function:"interpolated","zoom-function":!1,"property-function":!1,transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}]}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"circle-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-blur":{type:"number",default:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"circle-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["circle-translate"]},"circle-pitch-scale":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map"},"circle-pitch-alignment":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"viewport"},"circle-stroke-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"circle-stroke-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"heatmap-weight":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!1},"heatmap-intensity":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],function:"interpolated","zoom-function":!1,"property-function":!1,transition:!1},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-halo-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-halo-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"]},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-halo-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-halo-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"]}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-hue-rotate":{type:"number",default:0,period:360,function:"interpolated","zoom-function":!0,transition:!0,units:"degrees"},"raster-brightness-min":{type:"number",function:"interpolated","zoom-function":!0,default:0,minimum:0,maximum:1,transition:!0},"raster-brightness-max":{type:"number",function:"interpolated","zoom-function":!0,default:1,minimum:0,maximum:1,transition:!0},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-fade-duration":{type:"number",default:300,minimum:0,function:"interpolated","zoom-function":!0,transition:!1,units:"milliseconds"}},paint_hillshade:{"hillshade-illumination-direction":{type:"number",default:335,minimum:0,maximum:359,function:"interpolated","zoom-function":!0,transition:!1},"hillshade-illumination-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"viewport"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"hillshade-shadow-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,transition:!0},"hillshade-highlight-color":{type:"color",default:"#FFFFFF",function:"interpolated","zoom-function":!0,transition:!0},"hillshade-accent-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,transition:!0}},paint_background:{"background-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,transition:!0,requires:[{"!":"background-pattern"}]},"background-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,transition:!0}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!1,default:1,minimum:0,maximum:1,transition:!0},"fill-extrusion-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"fill-extrusion-pattern"}]},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"fill-extrusion-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"]},"fill-extrusion-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0},"fill-extrusion-height":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:0,minimum:0,units:"meters",transition:!0},"fill-extrusion-base":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"]}}},F=function(t,e,r,n){this.message=(t?t+": ":"")+r,n&&(this.identifier=n),null!=e&&e.__line__&&(this.line=e.__line__);};function P(t){var e=t.key,r=t.value;return r?[new F(e,r,"constants have been deprecated as of v8")]:[]}function T(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];for(var n=0,i=e;n<i.length;n+=1){var o=i[n];for(var a in o)t[a]=o[a];}return t}function O(t){return t instanceof Number||t instanceof String||t instanceof Boolean?t.valueOf():t}function L(t){return Array.isArray(t)?t.map(L):O(t)}var j=function(t){function e(e,r){t.call(this,r),this.message=r,this.key=e;}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(Error),q=function(t,e){void 0===e&&(e=[]),this.parent=t,this.bindings={};for(var r=0,n=e;r<n.length;r+=1){var i=n[r],o=i[0],a=i[1];this.bindings[o]=a;}};q.prototype.concat=function(t){return new q(this,t)},q.prototype.get=function(t){if(this.bindings[t])return this.bindings[t];if(this.parent)return this.parent.get(t);throw new Error(t+" not found in scope.")},q.prototype.has=function(t){return!!this.bindings[t]||!!this.parent&&this.parent.has(t)};var R={kind:"null"},U={kind:"number"},D={kind:"string"},N={kind:"boolean"},Z={kind:"color"},K={kind:"object"},J={kind:"value"},$={kind:"collator"};function H(t,e){return{kind:"array",itemType:t,N:e}}function X(t){if("array"===t.kind){var e=X(t.itemType);return"number"==typeof t.N?"array<"+e+", "+t.N+">":"value"===t.itemType.kind?"array":"array<"+e+">"}return t.kind}var G=[R,U,D,N,Z,K,H(J)];function Y(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&!Y(t.itemType,e.itemType)&&("number"!=typeof t.N||t.N===e.N))return null}else{if(t.kind===e.kind)return null;if("value"===t.kind)for(var r=0,n=G;r<n.length;r+=1){if(!Y(n[r],e))return null}}return"Expected "+X(t)+" but found "+X(e)+" instead."}var W=n(function(t,e){var r={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],rebeccapurple:[102,51,153,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function n(t){return(t=Math.round(t))<0?0:t>255?255:t}function i(t){return t<0?0:t>1?1:t}function o(t){return"%"===t[t.length-1]?n(parseFloat(t)/100*255):n(parseInt(t))}function a(t){return"%"===t[t.length-1]?i(parseFloat(t)/100):i(parseFloat(t))}function s(t,e,r){return r<0?r+=1:r>1&&(r-=1),6*r<1?t+(e-t)*r*6:2*r<1?e:3*r<2?t+(e-t)*(2/3-r)*6:t}try{e.parseCSSColor=function(t){var e,i=t.replace(/ /g,"").toLowerCase();if(i in r)return r[i].slice();if("#"===i[0])return 4===i.length?(e=parseInt(i.substr(1),16))>=0&&e<=4095?[(3840&e)>>4|(3840&e)>>8,240&e|(240&e)>>4,15&e|(15&e)<<4,1]:null:7===i.length&&(e=parseInt(i.substr(1),16))>=0&&e<=16777215?[(16711680&e)>>16,(65280&e)>>8,255&e,1]:null;var u=i.indexOf("("),l=i.indexOf(")");if(-1!==u&&l+1===i.length){var p=i.substr(0,u),c=i.substr(u+1,l-(u+1)).split(","),h=1;switch(p){case"rgba":if(4!==c.length)return null;h=a(c.pop());case"rgb":return 3!==c.length?null:[o(c[0]),o(c[1]),o(c[2]),h];case"hsla":if(4!==c.length)return null;h=a(c.pop());case"hsl":if(3!==c.length)return null;var f=(parseFloat(c[0])%360+360)%360/360,y=a(c[1]),d=a(c[2]),v=d<=.5?d*(y+1):d+y-d*y,m=2*d-v;return[n(255*s(m,v,f+1/3)),n(255*s(m,v,f)),n(255*s(m,v,f-1/3)),h];default:return null}}return null};}catch(t){}}).parseCSSColor,Q=function(t,e,r,n){void 0===n&&(n=1),this.r=t,this.g=e,this.b=r,this.a=n;};Q.parse=function(t){if(t){if(t instanceof Q)return t;if("string"==typeof t){var e=W(t);if(e)return new Q(e[0]/255*e[3],e[1]/255*e[3],e[2]/255*e[3],e[3])}}},Q.prototype.toString=function(){var t=this.toArray(),e=t[0],r=t[1],n=t[2],i=t[3];return"rgba("+Math.round(e)+","+Math.round(r)+","+Math.round(n)+","+i+")"},Q.prototype.toArray=function(){var t=this.r,e=this.g,r=this.b,n=this.a;return 0===n?[0,0,0,0]:[255*t/n,255*e/n,255*r/n,n]},Q.black=new Q(0,0,0,1),Q.white=new Q(1,1,1,1),Q.transparent=new Q(0,0,0,0);var tt=function(t,e,r){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=r,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"});};tt.prototype.compare=function(t,e){return this.collator.compare(t,e)},tt.prototype.resolvedLocale=function(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale};var et=function(t,e,r){this.type=$,this.locale=r,this.caseSensitive=t,this.diacriticSensitive=e;};function rt(t,e,r,n){return"number"==typeof t&&t>=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:"Invalid rgba value ["+[t,e,r,n].join(", ")+"]: 'a' must be between 0 and 1.":"Invalid rgba value ["+("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")+"]: 'r', 'g', and 'b' must be between 0 and 255."}function nt(t){if(null===t)return R;if("string"==typeof t)return D;if("boolean"==typeof t)return N;if("number"==typeof t)return U;if(t instanceof Q)return Z;if(t instanceof tt)return $;if(Array.isArray(t)){for(var e,r=t.length,n=0,i=t;n<i.length;n+=1){var o=nt(i[n]);if(e){if(e===o)continue;e=J;break}e=o;}return H(e||J,r)}return K}et.parse=function(t,e){if(2!==t.length)return e.error("Expected one argument.");var r=t[1];if("object"!=typeof r||Array.isArray(r))return e.error("Collator options argument must be an object.");var n=e.parse(void 0!==r["case-sensitive"]&&r["case-sensitive"],1,N);if(!n)return null;var i=e.parse(void 0!==r["diacritic-sensitive"]&&r["diacritic-sensitive"],1,N);if(!i)return null;var o=null;return r.locale&&!(o=e.parse(r.locale,1,D))?null:new et(n,i,o)},et.prototype.evaluate=function(t){return new tt(this.caseSensitive.evaluate(t),this.diacriticSensitive.evaluate(t),this.locale?this.locale.evaluate(t):null)},et.prototype.eachChild=function(t){t(this.caseSensitive),t(this.diacriticSensitive),this.locale&&t(this.locale);},et.prototype.possibleOutputs=function(){return[void 0]},et.prototype.serialize=function(){var t={};return t["case-sensitive"]=this.caseSensitive.serialize(),t["diacritic-sensitive"]=this.diacriticSensitive.serialize(),this.locale&&(t.locale=this.locale.serialize()),["collator",t]};var it=function(t,e){this.type=t,this.value=e;};it.parse=function(t,e){if(2!==t.length)return e.error("'literal' expression requires exactly one argument, but found "+(t.length-1)+" instead.");if(!function t(e){if(null===e)return!0;if("string"==typeof e)return!0;if("boolean"==typeof e)return!0;if("number"==typeof e)return!0;if(e instanceof Q)return!0;if(e instanceof tt)return!0;if(Array.isArray(e)){for(var r=0,n=e;r<n.length;r+=1)if(!t(n[r]))return!1;return!0}if("object"==typeof e){for(var i in e)if(!t(e[i]))return!1;return!0}return!1}(t[1]))return e.error("invalid value");var r=t[1],n=nt(r),i=e.expectedType;return"array"!==n.kind||0!==n.N||!i||"array"!==i.kind||"number"==typeof i.N&&0!==i.N||(n=i),new it(n,r)},it.prototype.evaluate=function(){return this.value},it.prototype.eachChild=function(){},it.prototype.possibleOutputs=function(){return[this.value]},it.prototype.serialize=function(){return"array"===this.type.kind||"object"===this.type.kind?["literal",this.value]:this.value instanceof Q?["rgba"].concat(this.value.toArray()):this.value};var ot=function(t){this.name="ExpressionEvaluationError",this.message=t;};ot.prototype.toJSON=function(){return this.message};var at={string:D,number:U,boolean:N,object:K},st=function(t,e){this.type=t,this.args=e;};st.parse=function(t,e){if(t.length<2)return e.error("Expected at least one argument.");for(var r=t[0],n=at[r],i=[],o=1;o<t.length;o++){var a=e.parse(t[o],o,J);if(!a)return null;i.push(a);}return new st(n,i)},st.prototype.evaluate=function(t){for(var e=0;e<this.args.length;e++){var r=this.args[e].evaluate(t);if(!Y(this.type,nt(r)))return r;if(e===this.args.length-1)throw new ot("Expected value to be of type "+X(this.type)+", but found "+X(nt(r))+" instead.")}return null},st.prototype.eachChild=function(t){this.args.forEach(t);},st.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.args.map(function(t){return t.possibleOutputs()}));var t;},st.prototype.serialize=function(){return[this.type.kind].concat(this.args.map(function(t){return t.serialize()}))};var ut={string:D,number:U,boolean:N},lt=function(t,e){this.type=t,this.input=e;};lt.parse=function(t,e){if(t.length<2||t.length>4)return e.error("Expected 1, 2, or 3 arguments, but found "+(t.length-1)+" instead.");var r,n;if(t.length>2){var i=t[1];if("string"!=typeof i||!(i in ut))return e.error('The item type argument of "array" must be one of string, number, boolean',1);r=ut[i];}else r=J;if(t.length>3){if("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2]))return e.error('The length argument to "array" must be a positive integer literal',2);n=t[2];}var o=H(r,n),a=e.parse(t[t.length-1],t.length-1,J);return a?new lt(o,a):null},lt.prototype.evaluate=function(t){var e=this.input.evaluate(t);if(Y(this.type,nt(e)))throw new ot("Expected value to be of type "+X(this.type)+", but found "+X(nt(e))+" instead.");return e},lt.prototype.eachChild=function(t){t(this.input);},lt.prototype.possibleOutputs=function(){return this.input.possibleOutputs()},lt.prototype.serialize=function(){var t=["array"],e=this.type.itemType;if("string"===e.kind||"number"===e.kind||"boolean"===e.kind){t.push(e.kind);var r=this.type.N;"number"==typeof r&&t.push(r);}return t.push(this.input.serialize()),t};var pt={"to-number":U,"to-color":Z},ct=function(t,e){this.type=t,this.args=e;};ct.parse=function(t,e){if(t.length<2)return e.error("Expected at least one argument.");for(var r=t[0],n=pt[r],i=[],o=1;o<t.length;o++){var a=e.parse(t[o],o,J);if(!a)return null;i.push(a);}return new ct(n,i)},ct.prototype.evaluate=function(t){if("color"===this.type.kind){for(var e,r,n=0,i=this.args;n<i.length;n+=1){if(r=null,"string"==typeof(e=i[n].evaluate(t))){var o=t.parseColor(e);if(o)return o}else if(Array.isArray(e)&&!(r=e.length<3||e.length>4?"Invalid rbga value "+JSON.stringify(e)+": expected an array containing either three or four numeric values.":rt(e[0],e[1],e[2],e[3])))return new Q(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new ot(r||"Could not parse color from value '"+("string"==typeof e?e:JSON.stringify(e))+"'")}for(var a=null,s=0,u=this.args;s<u.length;s+=1){if(null!==(a=u[s].evaluate(t))){var l=Number(a);if(!isNaN(l))return l}}throw new ot("Could not convert "+JSON.stringify(a)+" to number.")},ct.prototype.eachChild=function(t){this.args.forEach(t);},ct.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.args.map(function(t){return t.possibleOutputs()}));var t;},ct.prototype.serialize=function(){var t=["to-"+this.type.kind];return this.eachChild(function(e){t.push(e.serialize());}),t};var ht=["Unknown","Point","LineString","Polygon"],ft=function(){this._parseColorCache={};};ft.prototype.id=function(){return this.feature&&"id"in this.feature?this.feature.id:null},ft.prototype.geometryType=function(){return this.feature?"number"==typeof this.feature.type?ht[this.feature.type]:this.feature.type:null},ft.prototype.properties=function(){return this.feature&&this.feature.properties||{}},ft.prototype.parseColor=function(t){var e=this._parseColorCache[t];return e||(e=this._parseColorCache[t]=Q.parse(t)),e};var yt=function(t,e,r,n){this.name=t,this.type=e,this._evaluate=r,this.args=n;};function dt(t){if(t instanceof yt){if("get"===t.name&&1===t.args.length)return!1;if("has"===t.name&&1===t.args.length)return!1;if("properties"===t.name||"geometry-type"===t.name||"id"===t.name)return!1;if(/^filter-/.test(t.name))return!1}var e=!0;return t.eachChild(function(t){e&&!dt(t)&&(e=!1);}),e}function vt(t,e){if(t instanceof yt&&e.indexOf(t.name)>=0)return!1;var r=!0;return t.eachChild(function(t){r&&!vt(t,e)&&(r=!1);}),r}yt.prototype.evaluate=function(t){return this._evaluate(t,this.args)},yt.prototype.eachChild=function(t){this.args.forEach(t);},yt.prototype.possibleOutputs=function(){return[void 0]},yt.prototype.serialize=function(){return[this.name].concat(this.args.map(function(t){return t.serialize()}))},yt.parse=function(t,e){var r=t[0],n=yt.definitions[r];if(!n)return e.error('Unknown expression "'+r+'". If you wanted a literal array, use ["literal", [...]].',0);for(var i=Array.isArray(n)?n[0]:n.type,o=Array.isArray(n)?[[n[1],n[2]]]:n.overloads,a=o.filter(function(e){var r=e[0];return!Array.isArray(r)||r.length===t.length-1}),s=[],u=1;u<t.length;u++){var l=t[u],p=void 0;if(1===a.length){var c=a[0][0];p=Array.isArray(c)?c[u-1]:c.type;}var h=e.parse(l,1+s.length,p);if(!h)return null;s.push(h);}for(var f=null,y=0,d=a;y<d.length;y+=1){var v=d[y],m=v[0],g=v[1];if(f=new gt(e.registry,e.path,null,e.scope),Array.isArray(m)&&m.length!==s.length)f.error("Expected "+m.length+" arguments, but found "+s.length+" instead.");else{for(var x=0;x<s.length;x++){var b=Array.isArray(m)?m[x]:m.type,w=s[x];f.concat(x+1).checkSubtype(b,w.type);}if(0===f.errors.length)return new yt(r,i,g,s)}}if(1===a.length)e.errors.push.apply(e.errors,f.errors);else{var _=(a.length?a:o).map(function(t){var e,r=t[0];return e=r,Array.isArray(e)?"("+e.map(X).join(", ")+")":"("+X(e.type)+"...)"}).join(" | "),A=s.map(function(t){return X(t.type)}).join(", ");e.error("Expected arguments of type "+_+", but found ("+A+") instead.");}return null},yt.register=function(t,e){for(var r in yt.definitions=e,e)t[r]=yt;};var mt=function(t,e){this.type=e.type,this.name=t,this.boundExpression=e;};mt.parse=function(t,e){if(2!==t.length||"string"!=typeof t[1])return e.error("'var' expression requires exactly one string literal argument.");var r=t[1];return e.scope.has(r)?new mt(r,e.scope.get(r)):e.error('Unknown variable "'+r+'". Make sure "'+r+'" has been bound in an enclosing "let" expression before using it.',1)},mt.prototype.evaluate=function(t){return this.boundExpression.evaluate(t)},mt.prototype.eachChild=function(){},mt.prototype.possibleOutputs=function(){return[void 0]},mt.prototype.serialize=function(){return["var",this.name]};var gt=function(t,e,r,n,i){void 0===e&&(e=[]),void 0===n&&(n=new q),void 0===i&&(i=[]),this.registry=t,this.path=e,this.key=e.map(function(t){return"["+t+"]"}).join(""),this.scope=n,this.errors=i,this.expectedType=r;};function xt(t,e){for(var r,n,i=0,o=t.length-1,a=0;i<=o;){if(r=t[a=Math.floor((i+o)/2)],n=t[a+1],e===r||e>r&&e<n)return a;if(r<e)i=a+1;else{if(!(r>e))throw new ot("Input is not a number.");o=a-1;}}return Math.max(a-1,0)}gt.prototype.parse=function(t,e,r,n,i){return void 0===i&&(i={}),e?this.concat(e,r,n)._parse(t,i):this._parse(t,i)},gt.prototype._parse=function(t,e){if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');var r=t[0];if("string"!=typeof r)return this.error("Expression name must be a string, but found "+typeof r+' instead. If you wanted a literal array, use ["literal", [...]].',0),null;var n=this.registry[r];if(n){var i=n.parse(t,this);if(!i)return null;if(this.expectedType){var o=this.expectedType,a=i.type;if("string"!==o.kind&&"number"!==o.kind&&"boolean"!==o.kind&&"object"!==o.kind||"value"!==a.kind)if("array"===o.kind&&"value"===a.kind)e.omitTypeAnnotations||(i=new lt(o,i));else if("color"!==o.kind||"value"!==a.kind&&"string"!==a.kind){if(this.checkSubtype(this.expectedType,i.type))return null}else e.omitTypeAnnotations||(i=new ct(o,[i]));else e.omitTypeAnnotations||(i=new st(o,[i]));}if(!(i instanceof it)&&function t(e){if(e instanceof mt)return t(e.boundExpression);if(e instanceof yt&&"error"===e.name)return!1;if(e instanceof et)return!1;var r=e instanceof ct||e instanceof st||e instanceof lt;var n=!0;e.eachChild(function(e){n=r?n&&t(e):n&&e instanceof it;});if(!n)return!1;return dt(e)&&vt(e,["zoom","heatmap-density","line-progress","is-supported-script"])}(i)){var s=new ft;try{i=new it(i.type,i.evaluate(s));}catch(t){return this.error(t.message),null}}return i}return this.error('Unknown expression "'+r+'". If you wanted a literal array, use ["literal", [...]].',0)}return void 0===t?this.error("'undefined' value invalid. Use null instead."):"object"==typeof t?this.error('Bare objects invalid. Use ["literal", {...}] instead.'):this.error("Expected an array, but found "+typeof t+" instead.")},gt.prototype.concat=function(t,e,r){var n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new gt(this.registry,n,e||null,i,this.errors)},gt.prototype.error=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];var n=""+this.key+e.map(function(t){return"["+t+"]"}).join("");this.errors.push(new j(n,t));},gt.prototype.checkSubtype=function(t,e){var r=Y(t,e);return r&&this.error(r),r};var bt=function(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(var n=0,i=r;n<i.length;n+=1){var o=i[n],a=o[0],s=o[1];this.labels.push(a),this.outputs.push(s);}};function wt(t,e,r){return t*(1-r)+e*r}bt.parse=function(t,e){var r=t[1],n=t.slice(2);if(t.length-1<4)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(!(r=e.parse(r,1,U)))return null;var i=[],o=null;e.expectedType&&"value"!==e.expectedType.kind&&(o=e.expectedType),n.unshift(-1/0);for(var a=0;a<n.length;a+=2){var s=n[a],u=n[a+1],l=a+1,p=a+2;if("number"!=typeof s)return e.error('Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values.',l);if(i.length&&i[i.length-1][0]>=s)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',l);var c=e.parse(u,p,o);if(!c)return null;o=o||c.type,i.push([s,c]);}return new bt(o,r,i)},bt.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var i=e.length;return n>=e[i-1]?r[i-1].evaluate(t):r[xt(e,n)].evaluate(t)},bt.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;e<r.length;e+=1){t(r[e]);}},bt.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.outputs.map(function(t){return t.possibleOutputs()}));var t;},bt.prototype.serialize=function(){for(var t=["step",this.input.serialize()],e=0;e<this.labels.length;e++)e>0&&t.push(this.labels[e]),t.push(this.outputs[e].serialize());return t};var _t=Object.freeze({number:wt,color:function(t,e,r){return new Q(wt(t.r,e.r,r),wt(t.g,e.g,r),wt(t.b,e.b,r),wt(t.a,e.a,r))},array:function(t,e,r){return t.map(function(t,n){return wt(t,e[n],r)})}}),At=function(t,e,r,n){this.type=t,this.interpolation=e,this.input=r,this.labels=[],this.outputs=[];for(var i=0,o=n;i<o.length;i+=1){var a=o[i],s=a[0],u=a[1];this.labels.push(s),this.outputs.push(u);}};function kt(t,e,r,n){var i=n-r,o=t-r;return 0===i?0:1===e?o/i:(Math.pow(e,o)-1)/(Math.pow(e,i)-1)}At.interpolationFactor=function(t,e,r,n){var o=0;if("exponential"===t.name)o=kt(e,t.base,r,n);else if("linear"===t.name)o=kt(e,1,r,n);else if("cubic-bezier"===t.name){var a=t.controlPoints;o=new i(a[0],a[1],a[2],a[3]).solve(kt(e,1,r,n));}return o},At.parse=function(t,e){var r=t[1],n=t[2],i=t.slice(3);if(!Array.isArray(r)||0===r.length)return e.error("Expected an interpolation type expression.",1);if("linear"===r[0])r={name:"linear"};else if("exponential"===r[0]){var o=r[1];if("number"!=typeof o)return e.error("Exponential interpolation requires a numeric base.",1,1);r={name:"exponential",base:o};}else{if("cubic-bezier"!==r[0])return e.error("Unknown interpolation type "+String(r[0]),1,0);var a=r.slice(1);if(4!==a.length||a.some(function(t){return"number"!=typeof t||t<0||t>1}))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);r={name:"cubic-bezier",controlPoints:a};}if(t.length-1<4)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(!(n=e.parse(n,2,U)))return null;var s=[],u=null;e.expectedType&&"value"!==e.expectedType.kind&&(u=e.expectedType);for(var l=0;l<i.length;l+=2){var p=i[l],c=i[l+1],h=l+3,f=l+4;if("number"!=typeof p)return e.error('Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.',h);if(s.length&&s[s.length-1][0]>=p)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',h);var y=e.parse(c,f,u);if(!y)return null;u=u||y.type,s.push([p,y]);}return"number"===u.kind||"color"===u.kind||"array"===u.kind&&"number"===u.itemType.kind&&"number"==typeof u.N?new At(u,r,n,s):e.error("Type "+X(u)+" is not interpolatable.")},At.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);var o=xt(e,n),a=e[o],s=e[o+1],u=At.interpolationFactor(this.interpolation,n,a,s),l=r[o].evaluate(t),p=r[o+1].evaluate(t);return _t[this.type.kind.toLowerCase()](l,p,u)},At.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;e<r.length;e+=1){t(r[e]);}},At.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.outputs.map(function(t){return t.possibleOutputs()}));var t;},At.prototype.serialize=function(){for(var t=["interpolate","linear"===this.interpolation.name?["linear"]:"exponential"===this.interpolation.name?1===this.interpolation.base?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier"].concat(this.interpolation.controlPoints),this.input.serialize()],e=0;e<this.labels.length;e++)t.push(this.labels[e],this.outputs[e].serialize());return t};var zt=function(t,e){this.type=t,this.args=e;};zt.parse=function(t,e){if(t.length<2)return e.error("Expectected at least one argument.");var r=null,n=e.expectedType;n&&"value"!==n.kind&&(r=n);for(var i=[],o=0,a=t.slice(1);o<a.length;o+=1){var s=a[o],u=e.parse(s,1+i.length,r,void 0,{omitTypeAnnotations:!0});if(!u)return null;r=r||u.type,i.push(u);}var l=n&&i.some(function(t){return Y(n,t.type)});return new zt(l?J:r,i)},zt.prototype.evaluate=function(t){for(var e=null,r=0,n=this.args;r<n.length;r+=1){if(null!==(e=n[r].evaluate(t)))break}return e},zt.prototype.eachChild=function(t){this.args.forEach(t);},zt.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.args.map(function(t){return t.possibleOutputs()}));var t;},zt.prototype.serialize=function(){var t=["coalesce"];return this.eachChild(function(e){t.push(e.serialize());}),t};var St=function(t,e){this.type=e.type,this.bindings=[].concat(t),this.result=e;};St.prototype.evaluate=function(t){return this.result.evaluate(t)},St.prototype.eachChild=function(t){for(var e=0,r=this.bindings;e<r.length;e+=1){t(r[e][1]);}t(this.result);},St.parse=function(t,e){if(t.length<4)return e.error("Expected at least 3 arguments, but found "+(t.length-1)+" instead.");for(var r=[],n=1;n<t.length-1;n+=2){var i=t[n];if("string"!=typeof i)return e.error("Expected string, but found "+typeof i+" instead.",n);if(/[^a-zA-Z0-9_]/.test(i))return e.error("Variable names must contain only alphanumeric characters or '_'.",n);var o=e.parse(t[n+1],n+1);if(!o)return null;r.push([i,o]);}var a=e.parse(t[t.length-1],t.length-1,void 0,r);return a?new St(r,a):null},St.prototype.possibleOutputs=function(){return this.result.possibleOutputs()},St.prototype.serialize=function(){for(var t=["let"],e=0,r=this.bindings;e<r.length;e+=1){var n=r[e],i=n[0],o=n[1];t.push(i,o.serialize());}return t.push(this.result.serialize()),t};var Mt=function(t,e,r){this.type=t,this.index=e,this.input=r;};Mt.parse=function(t,e){if(3!==t.length)return e.error("Expected 2 arguments, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1,U),n=e.parse(t[2],2,H(e.expectedType||J));if(!r||!n)return null;var i=n.type;return new Mt(i.itemType,r,n)},Mt.prototype.evaluate=function(t){var e=this.index.evaluate(t),r=this.input.evaluate(t);if(e<0)throw new ot("Array index out of bounds: "+e+" < 0.");if(e>=r.length)throw new ot("Array index out of bounds: "+e+" > "+(r.length-1)+".");if(e!==Math.floor(e))throw new ot("Array index must be an integer, but found "+e+" instead.");return r[e]},Mt.prototype.eachChild=function(t){t(this.index),t(this.input);},Mt.prototype.possibleOutputs=function(){return[void 0]},Mt.prototype.serialize=function(){return["at",this.index.serialize(),this.input.serialize()]};var Vt=function(t,e,r,n,i,o){this.inputType=t,this.type=e,this.input=r,this.cases=n,this.outputs=i,this.otherwise=o;};Vt.parse=function(t,e){if(t.length<5)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if(t.length%2!=1)return e.error("Expected an even number of arguments.");var r,n;e.expectedType&&"value"!==e.expectedType.kind&&(n=e.expectedType);for(var i={},o=[],a=2;a<t.length-1;a+=2){var s=t[a],u=t[a+1];Array.isArray(s)||(s=[s]);var l=e.concat(a);if(0===s.length)return l.error("Expected at least one branch label.");for(var p=0,c=s;p<c.length;p+=1){var h=c[p];if("number"!=typeof h&&"string"!=typeof h)return l.error("Branch labels must be numbers or strings.");if("number"==typeof h&&Math.abs(h)>Number.MAX_SAFE_INTEGER)return l.error("Branch labels must be integers no larger than "+Number.MAX_SAFE_INTEGER+".");if("number"==typeof h&&Math.floor(h)!==h)return l.error("Numeric branch labels must be integer values.");if(r){if(l.checkSubtype(r,nt(h)))return null}else r=nt(h);if(void 0!==i[String(h)])return l.error("Branch labels must be unique.");i[String(h)]=o.length;}var f=e.parse(u,a,n);if(!f)return null;n=n||f.type,o.push(f);}var y=e.parse(t[1],1,r);if(!y)return null;var d=e.parse(t[t.length-1],t.length-1,n);return d?new Vt(r,n,y,i,o,d):null},Vt.prototype.evaluate=function(t){var e=this.input.evaluate(t);return(this.outputs[this.cases[e]]||this.otherwise).evaluate(t)},Vt.prototype.eachChild=function(t){t(this.input),this.outputs.forEach(t),t(this.otherwise);},Vt.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.outputs.map(function(t){return t.possibleOutputs()})).concat(this.otherwise.possibleOutputs());var t;},Vt.prototype.serialize=function(){for(var t=this,e=["match",this.input.serialize()],r=[],n={},i=0,o=Object.keys(this.cases).sort();i<o.length;i+=1){var a=o[i],s=n[t.cases[a]];void 0===s?(n[t.cases[a]]=r.length,r.push([t.cases[a],[a]])):r[s][1].push(a);}for(var u=function(e){return"number"===t.input.type.kind?Number(e):e},l=0,p=r;l<p.length;l+=1){var c=p[l],h=c[0],f=c[1];1===f.length?e.push(u(f[0])):e.push(f.map(u)),e.push(t.outputs[h].serialize());}return e.push(this.otherwise.serialize()),e};var Bt=function(t,e,r){this.type=t,this.branches=e,this.otherwise=r;};function Ct(t){return"string"===t.kind||"number"===t.kind||"boolean"===t.kind||"null"===t.kind}function It(t,e){return function(){function r(t,e,r){this.type=N,this.lhs=t,this.rhs=e,this.collator=r;}return r.parse=function(t,e){if(3!==t.length&&4!==t.length)return e.error("Expected two or three arguments.");var n=e.parse(t[1],1,J);if(!n)return null;var i=e.parse(t[2],2,J);if(!i)return null;if(!Ct(n.type)&&!Ct(i.type))return e.error("Expected at least one argument to be a string, number, boolean, or null, but found ("+X(n.type)+", "+X(i.type)+") instead.");if(n.type.kind!==i.type.kind&&"value"!==n.type.kind&&"value"!==i.type.kind)return e.error("Cannot compare "+X(n.type)+" and "+X(i.type)+".");var o=null;if(4===t.length){if("string"!==n.type.kind&&"string"!==i.type.kind)return e.error("Cannot use collator to compare non-string types.");if(!(o=e.parse(t[3],3,$)))return null}return new r(n,i,o)},r.prototype.evaluate=function(t){var r=this.collator?0===this.collator.evaluate(t).compare(this.lhs.evaluate(t),this.rhs.evaluate(t)):this.lhs.evaluate(t)===this.rhs.evaluate(t);return e?!r:r},r.prototype.eachChild=function(t){t(this.lhs),t(this.rhs),this.collator&&t(this.collator);},r.prototype.possibleOutputs=function(){return[!0,!1]},r.prototype.serialize=function(){var e=[t];return this.eachChild(function(t){e.push(t.serialize());}),e},r}()}Bt.parse=function(t,e){if(t.length<4)return e.error("Expected at least 3 arguments, but found only "+(t.length-1)+".");if(t.length%2!=0)return e.error("Expected an odd number of arguments.");var r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);for(var n=[],i=1;i<t.length-1;i+=2){var o=e.parse(t[i],i,N);if(!o)return null;var a=e.parse(t[i+1],i+1,r);if(!a)return null;n.push([o,a]),r=r||a.type;}var s=e.parse(t[t.length-1],t.length-1,r);return s?new Bt(r,n,s):null},Bt.prototype.evaluate=function(t){for(var e=0,r=this.branches;e<r.length;e+=1){var n=r[e],i=n[0],o=n[1];if(i.evaluate(t))return o.evaluate(t)}return this.otherwise.evaluate(t)},Bt.prototype.eachChild=function(t){for(var e=0,r=this.branches;e<r.length;e+=1){var n=r[e],i=n[0],o=n[1];t(i),t(o);}t(this.otherwise);},Bt.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.branches.map(function(t){t[0];return t[1].possibleOutputs()})).concat(this.otherwise.possibleOutputs());var t;},Bt.prototype.serialize=function(){var t=["case"];return this.eachChild(function(e){t.push(e.serialize());}),t};var Et=It("==",!1),Ft=It("!=",!0),Pt=function(t){this.type=U,this.input=t;};Pt.parse=function(t,e){if(2!==t.length)return e.error("Expected 1 argument, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1);return r?"array"!==r.type.kind&&"string"!==r.type.kind&&"value"!==r.type.kind?e.error("Expected argument of type string or array, but found "+X(r.type)+" instead."):new Pt(r):null},Pt.prototype.evaluate=function(t){var e=this.input.evaluate(t);if("string"==typeof e)return e.length;if(Array.isArray(e))return e.length;throw new ot("Expected value to be of type string or array, but found "+X(nt(e))+" instead.")},Pt.prototype.eachChild=function(t){t(this.input);},Pt.prototype.possibleOutputs=function(){return[void 0]},Pt.prototype.serialize=function(){var t=["length"];return this.eachChild(function(e){t.push(e.serialize());}),t};var Tt={"==":Et,"!=":Ft,array:lt,at:Mt,boolean:st,case:Bt,coalesce:zt,collator:et,interpolate:At,length:Pt,let:St,literal:it,match:Vt,number:st,object:st,step:bt,string:st,"to-color":ct,"to-number":ct,var:mt};function Ot(t,e){var r=e[0],n=e[1],i=e[2],o=e[3];r=r.evaluate(t),n=n.evaluate(t),i=i.evaluate(t);var a=o?o.evaluate(t):1,s=rt(r,n,i,a);if(s)throw new ot(s);return new Q(r/255*a,n/255*a,i/255*a,a)}function Lt(t,e){return t in e}function jt(t,e){var r=e[t];return void 0===r?null:r}function qt(t,e){var r=e[0],n=e[1];return r.evaluate(t)<n.evaluate(t)}function Rt(t,e){var r=e[0],n=e[1];return r.evaluate(t)>n.evaluate(t)}function Ut(t,e){var r=e[0],n=e[1];return r.evaluate(t)<=n.evaluate(t)}function Dt(t,e){var r=e[0],n=e[1];return r.evaluate(t)>=n.evaluate(t)}function Nt(t){return{type:t}}function Zt(t){return{result:"success",value:t}}function Kt(t){return{result:"error",value:t}}yt.register(Tt,{error:[{kind:"error"},[D],function(t,e){var r=e[0];throw new ot(r.evaluate(t))}],typeof:[D,[J],function(t,e){return X(nt(e[0].evaluate(t)))}],"to-string":[D,[J],function(t,e){var r=e[0],n=typeof(r=r.evaluate(t));return null===r?"":"string"===n||"number"===n||"boolean"===n?String(r):r instanceof Q?r.toString():JSON.stringify(r)}],"to-boolean":[N,[J],function(t,e){var r=e[0];return Boolean(r.evaluate(t))}],"to-rgba":[H(U,4),[Z],function(t,e){return e[0].evaluate(t).toArray()}],rgb:[Z,[U,U,U],Ot],rgba:[Z,[U,U,U,U],Ot],has:{type:N,overloads:[[[D],function(t,e){return Lt(e[0].evaluate(t),t.properties())}],[[D,K],function(t,e){var r=e[0],n=e[1];return Lt(r.evaluate(t),n.evaluate(t))}]]},get:{type:J,overloads:[[[D],function(t,e){return jt(e[0].evaluate(t),t.properties())}],[[D,K],function(t,e){var r=e[0],n=e[1];return jt(r.evaluate(t),n.evaluate(t))}]]},properties:[K,[],function(t){return t.properties()}],"geometry-type":[D,[],function(t){return t.geometryType()}],id:[J,[],function(t){return t.id()}],zoom:[U,[],function(t){return t.globals.zoom}],"heatmap-density":[U,[],function(t){return t.globals.heatmapDensity||0}],"line-progress":[U,[],function(t){return t.globals.lineProgress||0}],"+":[U,Nt(U),function(t,e){for(var r=0,n=0,i=e;n<i.length;n+=1){r+=i[n].evaluate(t);}return r}],"*":[U,Nt(U),function(t,e){for(var r=1,n=0,i=e;n<i.length;n+=1){r*=i[n].evaluate(t);}return r}],"-":{type:U,overloads:[[[U,U],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)-n.evaluate(t)}],[[U],function(t,e){return-e[0].evaluate(t)}]]},"/":[U,[U,U],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)/n.evaluate(t)}],"%":[U,[U,U],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)%n.evaluate(t)}],ln2:[U,[],function(){return Math.LN2}],pi:[U,[],function(){return Math.PI}],e:[U,[],function(){return Math.E}],"^":[U,[U,U],function(t,e){var r=e[0],n=e[1];return Math.pow(r.evaluate(t),n.evaluate(t))}],sqrt:[U,[U],function(t,e){var r=e[0];return Math.sqrt(r.evaluate(t))}],log10:[U,[U],function(t,e){var r=e[0];return Math.log10(r.evaluate(t))}],ln:[U,[U],function(t,e){var r=e[0];return Math.log(r.evaluate(t))}],log2:[U,[U],function(t,e){var r=e[0];return Math.log2(r.evaluate(t))}],sin:[U,[U],function(t,e){var r=e[0];return Math.sin(r.evaluate(t))}],cos:[U,[U],function(t,e){var r=e[0];return Math.cos(r.evaluate(t))}],tan:[U,[U],function(t,e){var r=e[0];return Math.tan(r.evaluate(t))}],asin:[U,[U],function(t,e){var r=e[0];return Math.asin(r.evaluate(t))}],acos:[U,[U],function(t,e){var r=e[0];return Math.acos(r.evaluate(t))}],atan:[U,[U],function(t,e){var r=e[0];return Math.atan(r.evaluate(t))}],min:[U,Nt(U),function(t,e){return Math.min.apply(Math,e.map(function(e){return e.evaluate(t)}))}],max:[U,Nt(U),function(t,e){return Math.max.apply(Math,e.map(function(e){return e.evaluate(t)}))}],abs:[U,[U],function(t,e){var r=e[0];return Math.abs(r.evaluate(t))}],round:[U,[U],function(t,e){var r=e[0].evaluate(t);return r<0?-Math.round(-r):Math.round(r)}],floor:[U,[U],function(t,e){var r=e[0];return Math.floor(r.evaluate(t))}],ceil:[U,[U],function(t,e){var r=e[0];return Math.ceil(r.evaluate(t))}],"filter-==":[N,[D,J],function(t,e){var r=e[0],n=e[1];return t.properties()[r.value]===n.value}],"filter-id-==":[N,[J],function(t,e){var r=e[0];return t.id()===r.value}],"filter-type-==":[N,[D],function(t,e){var r=e[0];return t.geometryType()===r.value}],"filter-<":[N,[D,J],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],o=n.value;return typeof i==typeof o&&i<o}],"filter-id-<":[N,[J],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n<i}],"filter->":[N,[D,J],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],o=n.value;return typeof i==typeof o&&i>o}],"filter-id->":[N,[J],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>i}],"filter-<=":[N,[D,J],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],o=n.value;return typeof i==typeof o&&i<=o}],"filter-id-<=":[N,[J],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n<=i}],"filter->=":[N,[D,J],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],o=n.value;return typeof i==typeof o&&i>=o}],"filter-id->=":[N,[J],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>=i}],"filter-has":[N,[J],function(t,e){return e[0].value in t.properties()}],"filter-has-id":[N,[],function(t){return null!==t.id()}],"filter-type-in":[N,[H(D)],function(t,e){return e[0].value.indexOf(t.geometryType())>=0}],"filter-id-in":[N,[H(J)],function(t,e){return e[0].value.indexOf(t.id())>=0}],"filter-in-small":[N,[D,H(J)],function(t,e){var r=e[0];return e[1].value.indexOf(t.properties()[r.value])>=0}],"filter-in-large":[N,[D,H(J)],function(t,e){var r=e[0],n=e[1];return function(t,e,r,n){for(;r<=n;){var i=r+n>>1;if(e[i]===t)return!0;e[i]>t?n=i-1:r=i+1;}return!1}(t.properties()[r.value],n.value,0,n.value.length-1)}],">":{type:N,overloads:[[[U,U],Rt],[[D,D],Rt],[[D,D,$],function(t,e){var r=e[0],n=e[1];return e[2].evaluate(t).compare(r.evaluate(t),n.evaluate(t))>0}]]},"<":{type:N,overloads:[[[U,U],qt],[[D,D],qt],[[D,D,$],function(t,e){var r=e[0],n=e[1];return e[2].evaluate(t).compare(r.evaluate(t),n.evaluate(t))<0}]]},">=":{type:N,overloads:[[[U,U],Dt],[[D,D],Dt],[[D,D,$],function(t,e){var r=e[0],n=e[1];return e[2].evaluate(t).compare(r.evaluate(t),n.evaluate(t))>=0}]]},"<=":{type:N,overloads:[[[U,U],Ut],[[D,D],Ut],[[D,D,$],function(t,e){var r=e[0],n=e[1];return e[2].evaluate(t).compare(r.evaluate(t),n.evaluate(t))<=0}]]},all:{type:N,overloads:[[[N,N],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)&&n.evaluate(t)}],[Nt(N),function(t,e){for(var r=0,n=e;r<n.length;r+=1){if(!n[r].evaluate(t))return!1}return!0}]]},any:{type:N,overloads:[[[N,N],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)||n.evaluate(t)}],[Nt(N),function(t,e){for(var r=0,n=e;r<n.length;r+=1){if(n[r].evaluate(t))return!0}return!1}]]},"!":[N,[N],function(t,e){return!e[0].evaluate(t)}],"is-supported-script":[N,[D],function(t,e){var r=e[0],n=t.globals&&t.globals.isSupportedScript;return!n||n(r.evaluate(t))}],upcase:[D,[D],function(t,e){return e[0].evaluate(t).toUpperCase()}],downcase:[D,[D],function(t,e){return e[0].evaluate(t).toLowerCase()}],concat:[D,Nt(D),function(t,e){return e.map(function(e){return e.evaluate(t)}).join("")}],"resolved-locale":[D,[$],function(t,e){return e[0].evaluate(t).resolvedLocale()}]});var Jt=.95047,$t=1,Ht=1.08883,Xt=4/29,Gt=6/29,Yt=3*Gt*Gt,Wt=Gt*Gt*Gt,Qt=Math.PI/180,te=180/Math.PI;function ee(t){return t>Wt?Math.pow(t,1/3):t/Yt+Xt}function re(t){return t>Gt?t*t*t:Yt*(t-Xt)}function ne(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function ie(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function oe(t){var e=ie(t.r),r=ie(t.g),n=ie(t.b),i=ee((.4124564*e+.3575761*r+.1804375*n)/Jt),o=ee((.2126729*e+.7151522*r+.072175*n)/$t);return{l:116*o-16,a:500*(i-o),b:200*(o-ee((.0193339*e+.119192*r+.9503041*n)/Ht)),alpha:t.a}}function ae(t){var e=(t.l+16)/116,r=isNaN(t.a)?e:e+t.a/500,n=isNaN(t.b)?e:e-t.b/200;return e=$t*re(e),r=Jt*re(r),n=Ht*re(n),new Q(ne(3.2404542*r-1.5371385*e-.4985314*n),ne(-.969266*r+1.8760108*e+.041556*n),ne(.0556434*r-.2040259*e+1.0572252*n),t.alpha)}var se={forward:oe,reverse:ae,interpolate:function(t,e,r){return{l:wt(t.l,e.l,r),a:wt(t.a,e.a,r),b:wt(t.b,e.b,r),alpha:wt(t.alpha,e.alpha,r)}}},ue={forward:function(t){var e=oe(t),r=e.l,n=e.a,i=e.b,o=Math.atan2(i,n)*te;return{h:o<0?o+360:o,c:Math.sqrt(n*n+i*i),l:r,alpha:t.a}},reverse:function(t){var e=t.h*Qt,r=t.c;return ae({l:t.l,a:Math.cos(e)*r,b:Math.sin(e)*r,alpha:t.alpha})},interpolate:function(t,e,r){return{h:function(t,e,r){var n=e-t;return t+r*(n>180||n<-180?n-360*Math.round(n/360):n)}(t.h,e.h,r),c:wt(t.c,e.c,r),l:wt(t.l,e.l,r),alpha:wt(t.alpha,e.alpha,r)}}},le=Object.freeze({lab:se,hcl:ue});function pe(t){return t instanceof Number?"number":t instanceof String?"string":t instanceof Boolean?"boolean":Array.isArray(t)?"array":null===t?"null":typeof t}function ce(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function he(t){return t}function fe(t,e,r){return void 0!==t?t:void 0!==e?e:void 0!==r?r:void 0}function ye(t,e,r,n,i){return fe(typeof r===i?n[r]:void 0,t.default,e.default)}function de(t,e,r){if("number"!==pe(r))return fe(t.default,e.default);var n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];var i=ge(t.stops,r);return t.stops[i][1]}function ve(t,e,r){var n=void 0!==t.base?t.base:1;if("number"!==pe(r))return fe(t.default,e.default);var i=t.stops.length;if(1===i)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[i-1][0])return t.stops[i-1][1];var o=ge(t.stops,r),a=function(t,e,r,n){var i=n-r,o=t-r;return 0===i?0:1===e?o/i:(Math.pow(e,o)-1)/(Math.pow(e,i)-1)}(r,n,t.stops[o][0],t.stops[o+1][0]),s=t.stops[o][1],u=t.stops[o+1][1],l=_t[e.type]||he;if(t.colorSpace&&"rgb"!==t.colorSpace){var p=le[t.colorSpace];l=function(t,e){return p.reverse(p.interpolate(p.forward(t),p.forward(e),a))};}return"function"==typeof s.evaluate?{evaluate:function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];var r=s.evaluate.apply(void 0,t),n=u.evaluate.apply(void 0,t);if(void 0!==r&&void 0!==n)return l(r,n,a)}}:l(s,u,a)}function me(t,e,r){return"color"===e.type?r=Q.parse(r):pe(r)===e.type||"enum"===e.type&&e.values[r]||(r=void 0),fe(r,t.default,e.default)}function ge(t,e){for(var r,n,i=0,o=t.length-1,a=0;i<=o;){if(r=t[a=Math.floor((i+o)/2)][0],n=t[a+1][0],e===r||e>r&&e<n)return a;r<e?i=a+1:r>e&&(o=a-1);}return Math.max(a-1,0)}var xe=function(t,e){var r;this.expression=t,this._warningHistory={},this._defaultValue="color"===(r=e).type&&ce(r.default)?new Q(0,0,0,0):"color"===r.type?Q.parse(r.default)||null:void 0===r.default?null:r.default,"enum"===e.type&&(this._enumValues=e.values);};function be(t){return Array.isArray(t)&&t.length>0&&"string"==typeof t[0]&&t[0]in Tt}function we(t,e){var r=new gt(Tt,[],function(t){var e={color:Z,string:D,number:U,enum:D,boolean:N};if("array"===t.type)return H(e[t.value]||J,t.length);return e[t.type]||null}(e)),n=r.parse(t);return n?Zt(new xe(n,e)):Kt(r.errors)}xe.prototype.evaluateWithoutErrorHandling=function(t,e){return this._evaluator||(this._evaluator=new ft),this._evaluator.globals=t,this._evaluator.feature=e,this.expression.evaluate(this._evaluator)},xe.prototype.evaluate=function(t,e){this._evaluator||(this._evaluator=new ft),this._evaluator.globals=t,this._evaluator.feature=e;try{var r=this.expression.evaluate(this._evaluator);if(null==r)return this._defaultValue;if(this._enumValues&&!(r in this._enumValues))throw new ot("Expected value to be one of "+Object.keys(this._enumValues).map(function(t){return JSON.stringify(t)}).join(", ")+", but found "+JSON.stringify(r)+" instead.");return r}catch(t){return this._warningHistory[t.message]||(this._warningHistory[t.message]=!0,"undefined"!=typeof console&&console.warn(t.message)),this._defaultValue}};var _e=function(t,e){this.kind=t,this._styleExpression=e;};_e.prototype.evaluateWithoutErrorHandling=function(t,e){return this._styleExpression.evaluateWithoutErrorHandling(t,e)},_e.prototype.evaluate=function(t,e){return this._styleExpression.evaluate(t,e)};var Ae=function(t,e,r){this.kind=t,this.zoomStops=r.labels,this._styleExpression=e,r instanceof At&&(this._interpolationType=r.interpolation);};function ke(t,e){if("error"===(t=we(t,e)).result)return t;var r=t.value.expression,n=dt(r);if(!n&&!e["property-function"])return Kt([new j("","property expressions not supported")]);var i=vt(r,["zoom"]);if(!i&&!1===e["zoom-function"])return Kt([new j("","zoom expressions not supported")]);var o=function t(e){var r=null;if(e instanceof St)r=t(e.result);else if(e instanceof zt)for(var n=0,i=e.args;n<i.length;n+=1){var o=i[n];if(r=t(o))break}else(e instanceof bt||e instanceof At)&&e.input instanceof yt&&"zoom"===e.input.name&&(r=e);if(r instanceof j)return r;e.eachChild(function(e){var n=t(e);n instanceof j?r=n:!r&&n?r=new j("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):r&&n&&r!==n&&(r=new j("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'));});return r}(r);return o||i?o instanceof j?Kt([o]):o instanceof At&&"piecewise-constant"===e.function?Kt([new j("",'"interpolate" expressions cannot be used with this property')]):Zt(o?new Ae(n?"camera":"composite",t.value,o):new _e(n?"constant":"source",t.value)):Kt([new j("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}Ae.prototype.evaluateWithoutErrorHandling=function(t,e){return this._styleExpression.evaluateWithoutErrorHandling(t,e)},Ae.prototype.evaluate=function(t,e){return this._styleExpression.evaluate(t,e)},Ae.prototype.interpolationFactor=function(t,e,r){return this._interpolationType?At.interpolationFactor(this._interpolationType,t,e,r):0};var ze=function(t,e){this._parameters=t,this._specification=e,T(this,function t(e,r){var n,i,o,a="color"===r.type,s=e.stops&&"object"==typeof e.stops[0][0],u=s||void 0!==e.property,l=s||!u,p=e.type||("interpolated"===r.function?"exponential":"interval");if(a&&((e=T({},e)).stops&&(e.stops=e.stops.map(function(t){return[t[0],Q.parse(t[1])]})),e.default?e.default=Q.parse(e.default):e.default=Q.parse(r.default)),e.colorSpace&&"rgb"!==e.colorSpace&&!le[e.colorSpace])throw new Error("Unknown color space: "+e.colorSpace);if("exponential"===p)n=ve;else if("interval"===p)n=de;else if("categorical"===p){n=ye,i=Object.create(null);for(var c=0,h=e.stops;c<h.length;c+=1){var f=h[c];i[f[0]]=f[1];}o=typeof e.stops[0][0];}else{if("identity"!==p)throw new Error('Unknown function type "'+p+'"');n=me;}if(s){for(var y={},d=[],v=0;v<e.stops.length;v++){var m=e.stops[v],g=m[0].zoom;void 0===y[g]&&(y[g]={zoom:g,type:e.type,property:e.property,default:e.default,stops:[]},d.push(g)),y[g].stops.push([m[0].value,m[1]]);}for(var x=[],b=0,w=d;b<w.length;b+=1){var _=w[b];x.push([y[_].zoom,t(y[_],r)]);}return{kind:"composite",interpolationFactor:At.interpolationFactor.bind(void 0,{name:"linear"}),zoomStops:x.map(function(t){return t[0]}),evaluate:function(t,n){var i=t.zoom;return ve({stops:x,base:e.base},r,i).evaluate(i,n)}}}return l?{kind:"camera",interpolationFactor:"exponential"===p?At.interpolationFactor.bind(void 0,{name:"exponential",base:void 0!==e.base?e.base:1}):function(){return 0},zoomStops:e.stops.map(function(t){return t[0]}),evaluate:function(t){var a=t.zoom;return n(e,r,a,i,o)}}:{kind:"source",evaluate:function(t,a){var s=a&&a.properties?a.properties[e.property]:void 0;return void 0===s?fe(e.default,r.default):n(e,r,s,i,o)}}}(this._parameters,this._specification));};function Se(t,e){if(ce(t))return new ze(t,e);if(be(t)){var r=ke(t,e);if("error"===r.result)throw new Error(r.value.map(function(t){return t.key+": "+t.message}).join(", "));return r.value}var n=t;return"string"==typeof t&&"color"===e.type&&(n=Q.parse(t)),{kind:"constant",evaluate:function(){return n}}}function Me(t){var e=t.key,r=t.value,n=t.valueSpec||{},i=t.objectElementValidators||{},o=t.style,a=t.styleSpec,s=[],u=pe(r);if("object"!==u)return[new F(e,r,"object expected, "+u+" found")];for(var l in r){var p=l.split(".")[0],c=n[p]||n["*"],h=void 0;if(i[p])h=i[p];else if(n[p])h=Ye;else if(i["*"])h=i["*"];else{if(!n["*"]){s.push(new F(e,r[l],'unknown property "'+l+'"'));continue}h=Ye;}s=s.concat(h({key:(e?e+".":e)+l,value:r[l],valueSpec:c,style:o,styleSpec:a,object:r,objectKey:l},r));}for(var f in n)i[f]||n[f].required&&void 0===n[f].default&&void 0===r[f]&&s.push(new F(e,r,'missing required property "'+f+'"'));return s}function Ve(t){var e=t.value,r=t.valueSpec,n=t.style,i=t.styleSpec,o=t.key,a=t.arrayElementValidator||Ye;if("array"!==pe(e))return[new F(o,e,"array expected, "+pe(e)+" found")];if(r.length&&e.length!==r.length)return[new F(o,e,"array length "+r.length+" expected, length "+e.length+" found")];if(r["min-length"]&&e.length<r["min-length"])return[new F(o,e,"array length at least "+r["min-length"]+" expected, length "+e.length+" found")];var s={type:r.value};i.$version<7&&(s.function=r.function),"object"===pe(r.value)&&(s=r.value);for(var u=[],l=0;l<e.length;l++)u=u.concat(a({array:e,arrayIndex:l,value:e[l],valueSpec:s,style:n,styleSpec:i,key:o+"["+l+"]"}));return u}function Be(t){var e=t.key,r=t.value,n=t.valueSpec,i=pe(r);return"number"!==i?[new F(e,r,"number expected, "+i+" found")]:"minimum"in n&&r<n.minimum?[new F(e,r,r+" is less than the minimum value "+n.minimum)]:"maximum"in n&&r>n.maximum?[new F(e,r,r+" is greater than the maximum value "+n.maximum)]:[]}function Ce(t){var e,r,n,i=t.valueSpec,o=O(t.value.type),a={},s="categorical"!==o&&void 0===t.value.property,u=!s,l="array"===pe(t.value.stops)&&"array"===pe(t.value.stops[0])&&"object"===pe(t.value.stops[0][0]),p=Me({key:t.key,value:t.value,valueSpec:t.styleSpec.function,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{stops:function(t){if("identity"===o)return[new F(t.key,t.value,'identity function may not have a "stops" property')];var e=[],r=t.value;e=e.concat(Ve({key:t.key,value:r,valueSpec:t.valueSpec,style:t.style,styleSpec:t.styleSpec,arrayElementValidator:c})),"array"===pe(r)&&0===r.length&&e.push(new F(t.key,r,"array must have at least one stop"));return e},default:function(t){return Ye({key:t.key,value:t.value,valueSpec:i,style:t.style,styleSpec:t.styleSpec})}}});return"identity"===o&&s&&p.push(new F(t.key,t.value,'missing required property "property"')),"identity"===o||t.value.stops||p.push(new F(t.key,t.value,'missing required property "stops"')),"exponential"===o&&"piecewise-constant"===t.valueSpec.function&&p.push(new F(t.key,t.value,"exponential functions not supported")),t.styleSpec.$version>=8&&(u&&!t.valueSpec["property-function"]?p.push(new F(t.key,t.value,"property functions not supported")):s&&!t.valueSpec["zoom-function"]&&"heatmap-color"!==t.objectKey&&"line-gradient"!==t.objectKey&&p.push(new F(t.key,t.value,"zoom functions not supported"))),"categorical"!==o&&!l||void 0!==t.value.property||p.push(new F(t.key,t.value,'"property" property is required')),p;function c(t){var e=[],o=t.value,s=t.key;if("array"!==pe(o))return[new F(s,o,"array expected, "+pe(o)+" found")];if(2!==o.length)return[new F(s,o,"array length 2 expected, length "+o.length+" found")];if(l){if("object"!==pe(o[0]))return[new F(s,o,"object expected, "+pe(o[0])+" found")];if(void 0===o[0].zoom)return[new F(s,o,"object stop key must have zoom")];if(void 0===o[0].value)return[new F(s,o,"object stop key must have value")];if(n&&n>O(o[0].zoom))return[new F(s,o[0].zoom,"stop zoom values must appear in ascending order")];O(o[0].zoom)!==n&&(n=O(o[0].zoom),r=void 0,a={}),e=e.concat(Me({key:s+"[0]",value:o[0],valueSpec:{zoom:{}},style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:Be,value:h}}));}else e=e.concat(h({key:s+"[0]",value:o[0],valueSpec:{},style:t.style,styleSpec:t.styleSpec},o));return e.concat(Ye({key:s+"[1]",value:o[1],valueSpec:i,style:t.style,styleSpec:t.styleSpec}))}function h(t,n){var s=pe(t.value),u=O(t.value),l=null!==t.value?t.value:n;if(e){if(s!==e)return[new F(t.key,l,s+" stop domain type must match previous stop domain type "+e)]}else e=s;if("number"!==s&&"string"!==s&&"boolean"!==s)return[new F(t.key,l,"stop domain value must be a number, string, or boolean")];if("number"!==s&&"categorical"!==o){var p="number expected, "+s+" found";return i["property-function"]&&void 0===o&&(p+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new F(t.key,l,p)]}return"categorical"!==o||"number"!==s||isFinite(u)&&Math.floor(u)===u?"categorical"!==o&&"number"===s&&void 0!==r&&u<r?[new F(t.key,l,"stop domain values must appear in ascending order")]:(r=u,"categorical"===o&&u in a?[new F(t.key,l,"stop domain values must be unique")]:(a[u]=!0,[])):[new F(t.key,l,"integer expected, found "+u)]}}function Ie(t){var e=("property"===t.expressionContext?ke:we)(L(t.value),t.valueSpec);return"error"===e.result?e.value.map(function(e){return new F(""+t.key+e.key,t.value,e.message)}):"property"===t.expressionContext&&"text-font"===t.propertyKey&&-1!==e.value._styleExpression.expression.possibleOutputs().indexOf(void 0)?[new F(t.key,t.value,'Invalid data expression for "text-font". Output values must be contained as literals within the expression.')]:[]}function Ee(t){var e=t.key,r=t.value,n=t.valueSpec,i=[];return Array.isArray(n.values)?-1===n.values.indexOf(O(r))&&i.push(new F(e,r,"expected one of ["+n.values.join(", ")+"], "+JSON.stringify(r)+" found")):-1===Object.keys(n.values).indexOf(O(r))&&i.push(new F(e,r,"expected one of ["+Object.keys(n.values).join(", ")+"], "+JSON.stringify(r)+" found")),i}function Fe(t){if(!Array.isArray(t)||0===t.length)return!1;switch(t[0]){case"has":return t.length>=2&&"$id"!==t[1]&&"$type"!==t[1];case"in":case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return 3===t.length&&(Array.isArray(t[1])||Array.isArray(t[2]));case"any":case"all":for(var e=0,r=t.slice(1);e<r.length;e+=1){var n=r[e];if(!Fe(n)&&"boolean"!=typeof n)return!1}return!0;default:return!0}}ze.deserialize=function(t){return new ze(t._parameters,t._specification)},ze.serialize=function(t){return{_parameters:t._parameters,_specification:t._specification}};var Pe={type:"boolean",default:!1,function:!0,"property-function":!0,"zoom-function":!0};function Te(t){if(!t)return function(){return!0};Fe(t)||(t=Le(t));var e=we(t,Pe);if("error"===e.result)throw new Error(e.value.map(function(t){return t.key+": "+t.message}).join(", "));return function(t,r){return e.value.evaluate(t,r)}}function Oe(t,e){return t<e?-1:t>e?1:0}function Le(t){if(!t)return!0;var e,r=t[0];return t.length<=1?"any"!==r:"=="===r?je(t[1],t[2],"=="):"!="===r?Ue(je(t[1],t[2],"==")):"<"===r||">"===r||"<="===r||">="===r?je(t[1],t[2],r):"any"===r?(e=t.slice(1),["any"].concat(e.map(Le))):"all"===r?["all"].concat(t.slice(1).map(Le)):"none"===r?["all"].concat(t.slice(1).map(Le).map(Ue)):"in"===r?qe(t[1],t.slice(2)):"!in"===r?Ue(qe(t[1],t.slice(2))):"has"===r?Re(t[1]):"!has"!==r||Ue(Re(t[1]))}function je(t,e,r){switch(t){case"$type":return["filter-type-"+r,e];case"$id":return["filter-id-"+r,e];default:return["filter-"+r,t,e]}}function qe(t,e){if(0===e.length)return!1;switch(t){case"$type":return["filter-type-in",["literal",e]];case"$id":return["filter-id-in",["literal",e]];default:return e.length>200&&!e.some(function(t){return typeof t!=typeof e[0]})?["filter-in-large",t,["literal",e.sort(Oe)]]:["filter-in-small",t,["literal",e]]}}function Re(t){switch(t){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",t]}}function Ue(t){return["!",t]}function De(t){return Fe(L(t.value))?Ie(T({},t,{expressionContext:"filter",valueSpec:{value:"boolean"}})):function t(e){var r=e.value;var n=e.key;if("array"!==pe(r))return[new F(n,r,"array expected, "+pe(r)+" found")];var i=e.styleSpec;var o;var a=[];if(r.length<1)return[new F(n,r,"filter array must have at least 1 element")];a=a.concat(Ee({key:n+"[0]",value:r[0],valueSpec:i.filter_operator,style:e.style,styleSpec:e.styleSpec}));switch(O(r[0])){case"<":case"<=":case">":case">=":r.length>=2&&"$type"===O(r[1])&&a.push(new F(n,r,'"$type" cannot be use with operator "'+r[0]+'"'));case"==":case"!=":3!==r.length&&a.push(new F(n,r,'filter array for operator "'+r[0]+'" must have 3 elements'));case"in":case"!in":r.length>=2&&"string"!==(o=pe(r[1]))&&a.push(new F(n+"[1]",r[1],"string expected, "+o+" found"));for(var s=2;s<r.length;s++)o=pe(r[s]),"$type"===O(r[1])?a=a.concat(Ee({key:n+"["+s+"]",value:r[s],valueSpec:i.geometry_type,style:e.style,styleSpec:e.styleSpec})):"string"!==o&&"number"!==o&&"boolean"!==o&&a.push(new F(n+"["+s+"]",r[s],"string, number, or boolean expected, "+o+" found"));break;case"any":case"all":case"none":for(var u=1;u<r.length;u++)a=a.concat(t({key:n+"["+u+"]",value:r[u],style:e.style,styleSpec:e.styleSpec}));break;case"has":case"!has":o=pe(r[1]),2!==r.length?a.push(new F(n,r,'filter array for "'+r[0]+'" operator must have 2 elements')):"string"!==o&&a.push(new F(n+"[1]",r[1],"string expected, "+o+" found"));}return a}(t)}function Ne(t,e){var r=t.key,n=t.style,i=t.styleSpec,o=t.value,a=t.objectKey,s=i[e+"_"+t.layerType];if(!s)return[];var u=a.match(/^(.*)-transition$/);if("paint"===e&&u&&s[u[1]]&&s[u[1]].transition)return Ye({key:r,value:o,valueSpec:i.transition,style:n,styleSpec:i});var l,p=t.valueSpec||s[a];if(!p)return[new F(r,o,'unknown property "'+a+'"')];if("string"===pe(o)&&p["property-function"]&&!p.tokens&&(l=/^{([^}]+)}$/.exec(o)))return[new F(r,o,'"'+a+'" does not support interpolation syntax\nUse an identity property function instead: `{ "type": "identity", "property": '+JSON.stringify(l[1])+" }`.")];var c=[];return"symbol"===t.layerType&&("text-field"===a&&n&&!n.glyphs&&c.push(new F(r,o,'use of "text-field" requires a style "glyphs" property')),"text-font"===a&&ce(L(o))&&"identity"===O(o.type)&&c.push(new F(r,o,'"text-font" does not support identity functions'))),c.concat(Ye({key:t.key,value:o,valueSpec:p,style:n,styleSpec:i,expressionContext:"property",propertyKey:a}))}function Ze(t){return Ne(t,"paint")}function Ke(t){return Ne(t,"layout")}function Je(t){var e=[],r=t.value,n=t.key,i=t.style,o=t.styleSpec;r.type||r.ref||e.push(new F(n,r,'either "type" or "ref" is required'));var a,s=O(r.type),u=O(r.ref);if(r.id)for(var l=O(r.id),p=0;p<t.arrayIndex;p++){var c=i.layers[p];O(c.id)===l&&e.push(new F(n,r.id,'duplicate layer id "'+r.id+'", previously used at line '+c.id.__line__));}if("ref"in r)["type","source","source-layer","filter","layout"].forEach(function(t){t in r&&e.push(new F(n,r[t],'"'+t+'" is prohibited for ref layers'));}),i.layers.forEach(function(t){O(t.id)===u&&(a=t);}),a?a.ref?e.push(new F(n,r.ref,"ref cannot reference another ref layer")):s=O(a.type):e.push(new F(n,r.ref,'ref layer "'+u+'" not found'));else if("background"!==s)if(r.source){var h=i.sources&&i.sources[r.source],f=h&&O(h.type);h?"vector"===f&&"raster"===s?e.push(new F(n,r.source,'layer "'+r.id+'" requires a raster source')):"raster"===f&&"raster"!==s?e.push(new F(n,r.source,'layer "'+r.id+'" requires a vector source')):"vector"!==f||r["source-layer"]?"raster-dem"===f&&"hillshade"!==s?e.push(new F(n,r.source,"raster-dem source can only be used with layer type 'hillshade'.")):"line"!==s||!r.paint||!r.paint["line-gradient"]||"geojson"===f&&h.lineMetrics||e.push(new F(n,r,'layer "'+r.id+'" specifies a line-gradient, which requires a GeoJSON source with `lineMetrics` enabled.')):e.push(new F(n,r,'layer "'+r.id+'" must specify a "source-layer"')):e.push(new F(n,r.source,'source "'+r.source+'" not found'));}else e.push(new F(n,r,'missing required property "source"'));return e=e.concat(Me({key:n,value:r,valueSpec:o.layer,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{"*":function(){return[]},type:function(){return Ye({key:n+".type",value:r.type,valueSpec:o.layer.type,style:t.style,styleSpec:t.styleSpec,object:r,objectKey:"type"})},filter:De,layout:function(t){return Me({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{"*":function(t){return Ke(T({layerType:s},t))}}})},paint:function(t){return Me({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{"*":function(t){return Ze(T({layerType:s},t))}}})}}}))}function $e(t){var e=t.value,r=t.key,n=t.styleSpec,i=t.style;if(!e.type)return[new F(r,e,'"type" is required')];var o=O(e.type),a=[];switch(o){case"vector":case"raster":case"raster-dem":if(a=a.concat(Me({key:r,value:e,valueSpec:n["source_"+o.replace("-","_")],style:t.style,styleSpec:n})),"url"in e)for(var s in e)["type","url","tileSize"].indexOf(s)<0&&a.push(new F(r+"."+s,e[s],'a source with a "url" property may not include a "'+s+'" property'));return a;case"geojson":return Me({key:r,value:e,valueSpec:n.source_geojson,style:i,styleSpec:n});case"video":return Me({key:r,value:e,valueSpec:n.source_video,style:i,styleSpec:n});case"image":return Me({key:r,value:e,valueSpec:n.source_image,style:i,styleSpec:n});case"canvas":return a.push(new F(r,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")),a;default:return Ee({key:r+".type",value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]},style:i,styleSpec:n})}}function He(t){var e=t.value,r=t.styleSpec,n=r.light,i=t.style,o=[],a=pe(e);if(void 0===e)return o;if("object"!==a)return o=o.concat([new F("light",e,"object expected, "+a+" found")]);for(var s in e){var u=s.match(/^(.*)-transition$/);o=u&&n[u[1]]&&n[u[1]].transition?o.concat(Ye({key:s,value:e[s],valueSpec:r.transition,style:i,styleSpec:r})):n[s]?o.concat(Ye({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r})):o.concat([new F(s,e[s],'unknown property "'+s+'"')]);}return o}function Xe(t){var e=t.value,r=t.key,n=pe(e);return"string"!==n?[new F(r,e,"string expected, "+n+" found")]:[]}var Ge={"*":function(){return[]},array:Ve,boolean:function(t){var e=t.value,r=t.key,n=pe(e);return"boolean"!==n?[new F(r,e,"boolean expected, "+n+" found")]:[]},number:Be,color:function(t){var e=t.key,r=t.value,n=pe(r);return"string"!==n?[new F(e,r,"color expected, "+n+" found")]:null===W(r)?[new F(e,r,'color expected, "'+r+'" found')]:[]},constants:P,enum:Ee,filter:De,function:Ce,layer:Je,object:Me,source:$e,light:He,string:Xe};function Ye(t){var e=t.value,r=t.valueSpec,n=t.styleSpec;return r.function&&ce(O(e))?Ce(t):r.function&&be(L(e))?Ie(t):r.type&&Ge[r.type]?Ge[r.type](t):Me(T({},t,{valueSpec:r.type?n[r.type]:r}))}function We(t){var e=t.value,r=t.key,n=Xe(t);return n.length?n:(-1===e.indexOf("{fontstack}")&&n.push(new F(r,e,'"glyphs" url must include a "{fontstack}" token')),-1===e.indexOf("{range}")&&n.push(new F(r,e,'"glyphs" url must include a "{range}" token')),n)}function Qe(t,e){e=e||E;var r=[];return r=r.concat(Ye({key:"",value:t,valueSpec:e.$root,styleSpec:e,style:t,objectElementValidators:{glyphs:We,"*":function(){return[]}}})),t.constants&&(r=r.concat(P({key:"constants",value:t.constants,style:t,styleSpec:e}))),tr(r)}function tr(t){return[].concat(t).sort(function(t,e){return t.line-e.line})}function er(t){return function(){return tr(t.apply(this,arguments))}}Qe.source=er($e),Qe.light=er(He),Qe.layer=er(Je),Qe.filter=er(De),Qe.paintProperty=er(Ze),Qe.layoutProperty=er(Ke);var rr=Qe,nr=Qe.light,ir=Qe.paintProperty,or=Qe.layoutProperty;function ar(t,e){var r=!1;if(e&&e.length)for(var n=0,i=e;n<i.length;n+=1){var o=i[n];t.fire(new C(new Error(o.message))),r=!0;}return r}var sr=lr,ur=3;function lr(t,e,r){var n=this.cells=[];if(t instanceof ArrayBuffer){this.arrayBuffer=t;var i=new Int32Array(this.arrayBuffer);t=i[0],e=i[1],r=i[2],this.d=e+2*r;for(var o=0;o<this.d*this.d;o++){var a=i[ur+o],s=i[ur+o+1];n.push(a===s?null:i.subarray(a,s));}var u=i[ur+n.length],l=i[ur+n.length+1];this.keys=i.subarray(u,l),this.bboxes=i.subarray(l),this.insert=this._insertReadonly;}else{this.d=e+2*r;for(var p=0;p<this.d*this.d;p++)n.push([]);this.keys=[],this.bboxes=[];}this.n=e,this.extent=t,this.padding=r,this.scale=e/t,this.uid=0;var c=r/e*t;this.min=-c,this.max=t+c;}lr.prototype.insert=function(t,e,r,n,i){this._forEachCell(e,r,n,i,this._insertCell,this.uid++),this.keys.push(t),this.bboxes.push(e),this.bboxes.push(r),this.bboxes.push(n),this.bboxes.push(i);},lr.prototype._insertReadonly=function(){throw"Cannot insert into a GridIndex created from an ArrayBuffer."},lr.prototype._insertCell=function(t,e,r,n,i,o){this.cells[i].push(o);},lr.prototype.query=function(t,e,r,n){var i=this.min,o=this.max;if(t<=i&&e<=i&&o<=r&&o<=n)return Array.prototype.slice.call(this.keys);var a=[];return this._forEachCell(t,e,r,n,this._queryCell,a,{}),a},lr.prototype._queryCell=function(t,e,r,n,i,o,a){var s=this.cells[i];if(null!==s)for(var u=this.keys,l=this.bboxes,p=0;p<s.length;p++){var c=s[p];if(void 0===a[c]){var h=4*c;t<=l[h+2]&&e<=l[h+3]&&r>=l[h+0]&&n>=l[h+1]?(a[c]=!0,o.push(u[c])):a[c]=!1;}}},lr.prototype._forEachCell=function(t,e,r,n,i,o,a){for(var s=this._convertToCellCoord(t),u=this._convertToCellCoord(e),l=this._convertToCellCoord(r),p=this._convertToCellCoord(n),c=s;c<=l;c++)for(var h=u;h<=p;h++){var f=this.d*h+c;if(i.call(this,t,e,r,n,f,o,a))return}},lr.prototype._convertToCellCoord=function(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))},lr.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var t=this.cells,e=ur+this.cells.length+1+1,r=0,n=0;n<this.cells.length;n++)r+=this.cells[n].length;var i=new Int32Array(e+r+this.keys.length+this.bboxes.length);i[0]=this.extent,i[1]=this.n,i[2]=this.padding;for(var o=e,a=0;a<t.length;a++){var s=t[a];i[ur+a]=o,i.set(s,o),o+=s.length;}return i[ur+t.length]=o,i.set(this.keys,o),o+=this.keys.length,i[ur+t.length+1]=o,i.set(this.bboxes,o),o+=this.bboxes.length,i.buffer};var pr=self.ImageData,cr={};function hr(t,e,r){void 0===r&&(r={}),Object.defineProperty(e,"_classRegistryKey",{value:t,writeable:!1}),cr[t]={klass:e,omit:r.omit||[],shallow:r.shallow||[]};}for(var fr in hr("Object",Object),sr.serialize=function(t,e){var r=t.toArrayBuffer();return e&&e.push(r),r},sr.deserialize=function(t){return new sr(t)},hr("Grid",sr),hr("Color",Q),hr("Error",Error),hr("StylePropertyFunction",ze),hr("StyleExpression",xe,{omit:["_evaluator"]}),hr("ZoomDependentExpression",Ae),hr("ZoomConstantExpression",_e),hr("CompoundExpression",yt,{omit:["_evaluate"]}),Tt)Tt[fr]._classRegistryKey||hr("Expression_"+fr,Tt[fr]);function yr(t,e){if(null==t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||t instanceof Boolean||t instanceof Number||t instanceof String||t instanceof Date||t instanceof RegExp)return t;if(t instanceof ArrayBuffer)return e&&e.push(t),t;if(ArrayBuffer.isView(t)){var r=t;return e&&e.push(r.buffer),r}if(t instanceof pr)return e&&e.push(t.data.buffer),t;if(Array.isArray(t)){for(var n=[],i=0,o=t;i<o.length;i+=1){var a=o[i];n.push(yr(a,e));}return n}if("object"==typeof t){var s=t.constructor,u=s._classRegistryKey;if(!u)throw new Error("can't serialize object of unregistered class");var l={};if(s.serialize)l._serialized=s.serialize(t,e);else{for(var p in t)if(t.hasOwnProperty(p)&&!(cr[u].omit.indexOf(p)>=0)){var c=t[p];l[p]=cr[u].shallow.indexOf(p)>=0?c:yr(c,e);}t instanceof Error&&(l.message=t.message);}return{name:u,properties:l}}throw new Error("can't serialize object of type "+typeof t)}function dr(t){if(null==t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||t instanceof Boolean||t instanceof Number||t instanceof String||t instanceof Date||t instanceof RegExp||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||t instanceof pr)return t;if(Array.isArray(t))return t.map(function(t){return dr(t)});if("object"==typeof t){var e=t,r=e.name,n=e.properties;if(!r)throw new Error("can't deserialize object of anonymous class");var i=cr[r].klass;if(!i)throw new Error("can't deserialize unregistered class "+r);if(i.deserialize)return i.deserialize(n._serialized);for(var o=Object.create(i.prototype),a=0,s=Object.keys(n);a<s.length;a+=1){var u=s[a];o[u]=cr[r].shallow.indexOf(u)>=0?n[u]:dr(n[u]);}return o}throw new Error("can't deserialize object of type "+typeof t)}var vr=function(){this.first=!0;};vr.prototype.update=function(t,e){var r=Math.floor(t);return this.first?(this.first=!1,this.lastIntegerZoom=r,this.lastIntegerZoomTime=0,this.lastZoom=t,this.lastFloorZoom=r,!0):(this.lastFloorZoom>r?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoom<r&&(this.lastIntegerZoom=r,this.lastIntegerZoomTime=e),t!==this.lastZoom&&(this.lastZoom=t,this.lastFloorZoom=r,!0))};var mr={"Latin-1 Supplement":function(t){return t>=128&&t<=255},Arabic:function(t){return t>=1536&&t<=1791},"Arabic Supplement":function(t){return t>=1872&&t<=1919},"Arabic Extended-A":function(t){return t>=2208&&t<=2303},"Hangul Jamo":function(t){return t>=4352&&t<=4607},"Unified Canadian Aboriginal Syllabics":function(t){return t>=5120&&t<=5759},Khmer:function(t){return t>=6016&&t<=6143},"Unified Canadian Aboriginal Syllabics Extended":function(t){return t>=6320&&t<=6399},"General Punctuation":function(t){return t>=8192&&t<=8303},"Letterlike Symbols":function(t){return t>=8448&&t<=8527},"Number Forms":function(t){return t>=8528&&t<=8591},"Miscellaneous Technical":function(t){return t>=8960&&t<=9215},"Control Pictures":function(t){return t>=9216&&t<=9279},"Optical Character Recognition":function(t){return t>=9280&&t<=9311},"Enclosed Alphanumerics":function(t){return t>=9312&&t<=9471},"Geometric Shapes":function(t){return t>=9632&&t<=9727},"Miscellaneous Symbols":function(t){return t>=9728&&t<=9983},"Miscellaneous Symbols and Arrows":function(t){return t>=11008&&t<=11263},"CJK Radicals Supplement":function(t){return t>=11904&&t<=12031},"Kangxi Radicals":function(t){return t>=12032&&t<=12255},"Ideographic Description Characters":function(t){return t>=12272&&t<=12287},"CJK Symbols and Punctuation":function(t){return t>=12288&&t<=12351},Hiragana:function(t){return t>=12352&&t<=12447},Katakana:function(t){return t>=12448&&t<=12543},Bopomofo:function(t){return t>=12544&&t<=12591},"Hangul Compatibility Jamo":function(t){return t>=12592&&t<=12687},Kanbun:function(t){return t>=12688&&t<=12703},"Bopomofo Extended":function(t){return t>=12704&&t<=12735},"CJK Strokes":function(t){return t>=12736&&t<=12783},"Katakana Phonetic Extensions":function(t){return t>=12784&&t<=12799},"Enclosed CJK Letters and Months":function(t){return t>=12800&&t<=13055},"CJK Compatibility":function(t){return t>=13056&&t<=13311},"CJK Unified Ideographs Extension A":function(t){return t>=13312&&t<=19903},"Yijing Hexagram Symbols":function(t){return t>=19904&&t<=19967},"CJK Unified Ideographs":function(t){return t>=19968&&t<=40959},"Yi Syllables":function(t){return t>=40960&&t<=42127},"Yi Radicals":function(t){return t>=42128&&t<=42191},"Hangul Jamo Extended-A":function(t){return t>=43360&&t<=43391},"Hangul Syllables":function(t){return t>=44032&&t<=55215},"Hangul Jamo Extended-B":function(t){return t>=55216&&t<=55295},"Private Use Area":function(t){return t>=57344&&t<=63743},"CJK Compatibility Ideographs":function(t){return t>=63744&&t<=64255},"Arabic Presentation Forms-A":function(t){return t>=64336&&t<=65023},"Vertical Forms":function(t){return t>=65040&&t<=65055},"CJK Compatibility Forms":function(t){return t>=65072&&t<=65103},"Small Form Variants":function(t){return t>=65104&&t<=65135},"Arabic Presentation Forms-B":function(t){return t>=65136&&t<=65279},"Halfwidth and Fullwidth Forms":function(t){return t>=65280&&t<=65519}};function gr(t){for(var e=0,r=t;e<r.length;e+=1){if(br(r[e].charCodeAt(0)))return!0}return!1}function xr(t){return!mr.Arabic(t)&&(!mr["Arabic Supplement"](t)&&(!mr["Arabic Extended-A"](t)&&(!mr["Arabic Presentation Forms-A"](t)&&!mr["Arabic Presentation Forms-B"](t))))}function br(t){return 746===t||747===t||!(t<4352)&&(!!mr["Bopomofo Extended"](t)||(!!mr.Bopomofo(t)||(!(!mr["CJK Compatibility Forms"](t)||t>=65097&&t<=65103)||(!!mr["CJK Compatibility Ideographs"](t)||(!!mr["CJK Compatibility"](t)||(!!mr["CJK Radicals Supplement"](t)||(!!mr["CJK Strokes"](t)||(!(!mr["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||(!!mr["CJK Unified Ideographs Extension A"](t)||(!!mr["CJK Unified Ideographs"](t)||(!!mr["Enclosed CJK Letters and Months"](t)||(!!mr["Hangul Compatibility Jamo"](t)||(!!mr["Hangul Jamo Extended-A"](t)||(!!mr["Hangul Jamo Extended-B"](t)||(!!mr["Hangul Jamo"](t)||(!!mr["Hangul Syllables"](t)||(!!mr.Hiragana(t)||(!!mr["Ideographic Description Characters"](t)||(!!mr.Kanbun(t)||(!!mr["Kangxi Radicals"](t)||(!!mr["Katakana Phonetic Extensions"](t)||(!(!mr.Katakana(t)||12540===t)||(!(!mr["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||(!(!mr["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||(!!mr["Unified Canadian Aboriginal Syllabics"](t)||(!!mr["Unified Canadian Aboriginal Syllabics Extended"](t)||(!!mr["Vertical Forms"](t)||(!!mr["Yijing Hexagram Symbols"](t)||(!!mr["Yi Syllables"](t)||!!mr["Yi Radicals"](t))))))))))))))))))))))))))))))}function wr(t){return!(br(t)||function(t){return!!(mr["Latin-1 Supplement"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||mr["General Punctuation"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||mr["Letterlike Symbols"](t)||mr["Number Forms"](t)||mr["Miscellaneous Technical"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||mr["Control Pictures"](t)&&9251!==t||mr["Optical Character Recognition"](t)||mr["Enclosed Alphanumerics"](t)||mr["Geometric Shapes"](t)||mr["Miscellaneous Symbols"](t)&&!(t>=9754&&t<=9759)||mr["Miscellaneous Symbols and Arrows"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||mr["CJK Symbols and Punctuation"](t)||mr.Katakana(t)||mr["Private Use Area"](t)||mr["CJK Compatibility Forms"](t)||mr["Small Form Variants"](t)||mr["Halfwidth and Fullwidth Forms"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)}(t))}function _r(t,e){return!(!e&&(t>=1424&&t<=2303||mr["Arabic Presentation Forms-A"](t)||mr["Arabic Presentation Forms-B"](t)))&&!(t>=2304&&t<=3583||t>=3840&&t<=4255||mr.Khmer(t))}var Ar,kr=!1,zr=null,Sr=!1,Mr=new I,Vr={applyArabicShaping:null,processBidirectionalText:null,isLoaded:function(){return Sr||null!=Vr.applyArabicShaping}},Br=function(t,e){this.zoom=t,e?(this.now=e.now,this.fadeDuration=e.fadeDuration,this.zoomHistory=e.zoomHistory,this.transition=e.transition):(this.now=0,this.fadeDuration=0,this.zoomHistory=new vr,this.transition={});};Br.prototype.isSupportedScript=function(t){return function(t,e){for(var r=0,n=t;r<n.length;r+=1)if(!_r(n[r].charCodeAt(0),e))return!1;return!0}(t,Vr.isLoaded())},Br.prototype.crossFadingFactor=function(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)};var Cr=function(t,e){this.property=t,this.value=e,this.expression=Se(void 0===e?t.specification.default:e,t.specification);};Cr.prototype.isDataDriven=function(){return"source"===this.expression.kind||"composite"===this.expression.kind},Cr.prototype.possiblyEvaluate=function(t){return this.property.possiblyEvaluate(this,t)};var Ir=function(t){this.property=t,this.value=new Cr(t,void 0);};Ir.prototype.transitioned=function(t,e){return new Fr(this.property,this.value,e,h({},t.transition,this.transition),t.now)},Ir.prototype.untransitioned=function(){return new Fr(this.property,this.value,null,{},0)};var Er=function(t){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues);};Er.prototype.getValue=function(t){return g(this._values[t].value.value)},Er.prototype.setValue=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new Ir(this._values[t].property)),this._values[t].value=new Cr(this._values[t].property,null===e?void 0:g(e));},Er.prototype.getTransition=function(t){return g(this._values[t].transition)},Er.prototype.setTransition=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new Ir(this._values[t].property)),this._values[t].transition=g(e)||void 0;},Er.prototype.serialize=function(){for(var t={},e=0,r=Object.keys(this._values);e<r.length;e+=1){var n=r[e],i=this.getValue(n);void 0!==i&&(t[n]=i);var o=this.getTransition(n);void 0!==o&&(t[n+"-transition"]=o);}return t},Er.prototype.transitioned=function(t,e){for(var r=new Pr(this._properties),n=0,i=Object.keys(this._values);n<i.length;n+=1){var o=i[n];r._values[o]=this._values[o].transitioned(t,e._values[o]);}return r},Er.prototype.untransitioned=function(){for(var t=new Pr(this._properties),e=0,r=Object.keys(this._values);e<r.length;e+=1){var n=r[e];t._values[n]=this._values[n].untransitioned();}return t};var Fr=function(t,e,r,n,i){this.property=t,this.value=e,this.begin=i+n.delay||0,this.end=this.begin+n.duration||0,t.specification.transition&&(n.delay||n.duration)&&(this.prior=r);};Fr.prototype.possiblyEvaluate=function(t){var e=t.now||0,r=this.value.possiblyEvaluate(t),n=this.prior;if(n){if(e>this.end)return this.prior=null,r;if(this.value.isDataDriven())return this.prior=null,r;if(e<this.begin)return n.possiblyEvaluate(t);var i=(e-this.begin)/(this.end-this.begin);return this.property.interpolate(n.possiblyEvaluate(t),r,function(t){if(t<=0)return 0;if(t>=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}(i))}return r};var Pr=function(t){this._properties=t,this._values=Object.create(t.defaultTransitioningPropertyValues);};Pr.prototype.possiblyEvaluate=function(t){for(var e=new Lr(this._properties),r=0,n=Object.keys(this._values);r<n.length;r+=1){var i=n[r];e._values[i]=this._values[i].possiblyEvaluate(t);}return e},Pr.prototype.hasTransition=function(){for(var t=0,e=Object.keys(this._values);t<e.length;t+=1){var r=e[t];if(this._values[r].prior)return!0}return!1};var Tr=function(t){this._properties=t,this._values=Object.create(t.defaultPropertyValues);};Tr.prototype.getValue=function(t){return g(this._values[t].value)},Tr.prototype.setValue=function(t,e){this._values[t]=new Cr(this._values[t].property,null===e?void 0:g(e));},Tr.prototype.serialize=function(){for(var t={},e=0,r=Object.keys(this._values);e<r.length;e+=1){var n=r[e],i=this.getValue(n);void 0!==i&&(t[n]=i);}return t},Tr.prototype.possiblyEvaluate=function(t){for(var e=new Lr(this._properties),r=0,n=Object.keys(this._values);r<n.length;r+=1){var i=n[r];e._values[i]=this._values[i].possiblyEvaluate(t);}return e};var Or=function(t,e,r){this.property=t,this.value=e,this.globals=r;};Or.prototype.isConstant=function(){return"constant"===this.value.kind},Or.prototype.constantOr=function(t){return"constant"===this.value.kind?this.value.value:t},Or.prototype.evaluate=function(t){return this.property.evaluate(this.value,this.globals,t)};var Lr=function(t){this._properties=t,this._values=Object.create(t.defaultPossiblyEvaluatedValues);};Lr.prototype.get=function(t){return this._values[t]};var jr=function(t){this.specification=t;};jr.prototype.possiblyEvaluate=function(t,e){return t.expression.evaluate(e)},jr.prototype.interpolate=function(t,e,r){var n=_t[this.specification.type];return n?n(t,e,r):t};var qr=function(t){this.specification=t;};qr.prototype.possiblyEvaluate=function(t,e){return"constant"===t.expression.kind||"camera"===t.expression.kind?new Or(this,{kind:"constant",value:t.expression.evaluate(e)},e):new Or(this,t.expression,e)},qr.prototype.interpolate=function(t,e,r){if("constant"!==t.value.kind||"constant"!==e.value.kind)return t;if(void 0===t.value.value||void 0===e.value.value)return new Or(this,{kind:"constant",value:void 0},t.globals);var n=_t[this.specification.type];return n?new Or(this,{kind:"constant",value:n(t.value.value,e.value.value,r)},t.globals):t},qr.prototype.evaluate=function(t,e,r){return"constant"===t.kind?t.value:t.evaluate(e,r)};var Rr=function(t){this.specification=t;};Rr.prototype.possiblyEvaluate=function(t,e){if(void 0!==t.value){if("constant"===t.expression.kind){var r=t.expression.evaluate(e);return this._calculate(r,r,r,e)}return this._calculate(t.expression.evaluate(new Br(Math.floor(e.zoom-1),e)),t.expression.evaluate(new Br(Math.floor(e.zoom),e)),t.expression.evaluate(new Br(Math.floor(e.zoom+1),e)),e)}},Rr.prototype._calculate=function(t,e,r,n){var i=n.zoom,o=i-Math.floor(i),a=n.crossFadingFactor();return i>n.zoomHistory.lastIntegerZoom?{from:t,to:e,fromScale:2,toScale:1,t:o+(1-o)*a}:{from:r,to:e,fromScale:.5,toScale:1,t:1-(1-a)*o}},Rr.prototype.interpolate=function(t){return t};var Ur=function(t){this.specification=t;};Ur.prototype.possiblyEvaluate=function(t,e){return!!t.expression.evaluate(e)},Ur.prototype.interpolate=function(){return!1};var Dr=function(t){for(var e in this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},t){var r=t[e],n=this.defaultPropertyValues[e]=new Cr(r,void 0),i=this.defaultTransitionablePropertyValues[e]=new Ir(r);this.defaultTransitioningPropertyValues[e]=i.untransitioned(),this.defaultPossiblyEvaluatedValues[e]=n.possiblyEvaluate({});}};hr("DataDrivenProperty",qr),hr("DataConstantProperty",jr),hr("CrossFadedProperty",Rr),hr("ColorRampProperty",Ur);var Nr=function(t){function e(e,r){for(var n in t.call(this),this.id=e.id,this.metadata=e.metadata,this.type=e.type,this.minzoom=e.minzoom,this.maxzoom=e.maxzoom,this.visibility="visible","background"!==e.type&&(this.source=e.source,this.sourceLayer=e["source-layer"],this.filter=e.filter),this._featureFilter=function(){return!0},r.layout&&(this._unevaluatedLayout=new Tr(r.layout)),this._transitionablePaint=new Er(r.paint),e.paint)this.setPaintProperty(n,e.paint[n],{validate:!1});for(var i in e.layout)this.setLayoutProperty(i,e.layout[i],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned();}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getLayoutProperty=function(t){return"visibility"===t?this.visibility:this._unevaluatedLayout.getValue(t)},e.prototype.setLayoutProperty=function(t,e,r){if(null!=e){var n="layers."+this.id+".layout."+t;if(this._validate(or,n,t,e,r))return}"visibility"!==t?this._unevaluatedLayout.setValue(t,e):this.visibility="none"===e?e:"visible";},e.prototype.getPaintProperty=function(t){return d(t,"-transition")?this._transitionablePaint.getTransition(t.slice(0,-"-transition".length)):this._transitionablePaint.getValue(t)},e.prototype.setPaintProperty=function(t,e,r){if(null!=e){var n="layers."+this.id+".paint."+t;if(this._validate(ir,n,t,e,r))return}d(t,"-transition")?this._transitionablePaint.setTransition(t.slice(0,-"-transition".length),e||void 0):this._transitionablePaint.setValue(t,e);},e.prototype.isHidden=function(t){return!!(this.minzoom&&t<this.minzoom)||(!!(this.maxzoom&&t>=this.maxzoom)||"none"===this.visibility)},e.prototype.updateTransitions=function(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint);},e.prototype.hasTransition=function(){return this._transitioningPaint.hasTransition()},e.prototype.recalculate=function(t){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t)),this.paint=this._transitioningPaint.possiblyEvaluate(t);},e.prototype.serialize=function(){var t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return"none"===this.visibility&&(t.layout=t.layout||{},t.layout.visibility="none"),m(t,function(t,e){return!(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)})},e.prototype._validate=function(t,e,r,n,i){return(!i||!1!==i.validate)&&ar(this,t.call(rr,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:E,style:{glyphs:!0,sprite:!0}}))},e.prototype.hasOffscreenPass=function(){return!1},e.prototype.resize=function(){},e}(I),Zr={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array},Kr=function(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8;},Jr=function(){this.isTransferred=!1,this.capacity=-1,this.resize(0);};function $r(t,e){void 0===e&&(e=1);var r=0,n=0;return{members:t.map(function(t){var i,o=(i=t.type,Zr[i].BYTES_PER_ELEMENT),a=r=Hr(r,Math.max(e,o)),s=t.components||1;return n=Math.max(n,o),r+=o*s,{name:t.name,type:t.type,components:s,offset:a}}),size:Hr(r,Math.max(n,e)),alignment:e}}function Hr(t,e){return Math.ceil(t/e)*e}Jr.serialize=function(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}},Jr.deserialize=function(t){var e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e},Jr.prototype._trim=function(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews());},Jr.prototype.clear=function(){this.length=0;},Jr.prototype.resize=function(t){this.reserve(t),this.length=t;},Jr.prototype.reserve=function(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);var e=this.uint8;this._refreshViews(),e&&this.uint8.set(e);}},Jr.prototype._refreshViews=function(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")};var Xr=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e){var r=this.length;this.resize(r+1);var n=2*r;return this.int16[n+0]=t,this.int16[n+1]=e,r},e}(Jr);Xr.prototype.bytesPerElement=4,hr("StructArrayLayout2i4",Xr);var Gr=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n){var i=this.length;this.resize(i+1);var o=4*i;return this.int16[o+0]=t,this.int16[o+1]=e,this.int16[o+2]=r,this.int16[o+3]=n,i},e}(Jr);Gr.prototype.bytesPerElement=8,hr("StructArrayLayout4i8",Gr);var Yr=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,o){var a=this.length;this.resize(a+1);var s=6*a;return this.int16[s+0]=t,this.int16[s+1]=e,this.int16[s+2]=r,this.int16[s+3]=n,this.int16[s+4]=i,this.int16[s+5]=o,a},e}(Jr);Yr.prototype.bytesPerElement=12,hr("StructArrayLayout2i4i12",Yr);var Wr=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,o,a,s){var u=this.length;this.resize(u+1);var l=6*u,p=12*u;return this.int16[l+0]=t,this.int16[l+1]=e,this.int16[l+2]=r,this.int16[l+3]=n,this.uint8[p+8]=i,this.uint8[p+9]=o,this.uint8[p+10]=a,this.uint8[p+11]=s,u},e}(Jr);Wr.prototype.bytesPerElement=12,hr("StructArrayLayout4i4ub12",Wr);var Qr=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,o,a,s){var u=this.length;this.resize(u+1);var l=8*u;return this.int16[l+0]=t,this.int16[l+1]=e,this.int16[l+2]=r,this.int16[l+3]=n,this.uint16[l+4]=i,this.uint16[l+5]=o,this.uint16[l+6]=a,this.uint16[l+7]=s,u},e}(Jr);Qr.prototype.bytesPerElement=16,hr("StructArrayLayout4i4ui16",Qr);var tn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;this.resize(n+1);var i=3*n;return this.float32[i+0]=t,this.float32[i+1]=e,this.float32[i+2]=r,n},e}(Jr);tn.prototype.bytesPerElement=12,hr("StructArrayLayout3f12",tn);var en=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t){var e=this.length;this.resize(e+1);var r=1*e;return this.uint32[r+0]=t,e},e}(Jr);en.prototype.bytesPerElement=4,hr("StructArrayLayout1ul4",en);var rn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,o,a,s,u,l,p){var c=this.length;this.resize(c+1);var h=12*c,f=6*c;return this.int16[h+0]=t,this.int16[h+1]=e,this.int16[h+2]=r,this.int16[h+3]=n,this.int16[h+4]=i,this.int16[h+5]=o,this.uint32[f+3]=a,this.uint16[h+8]=s,this.uint16[h+9]=u,this.int16[h+10]=l,this.int16[h+11]=p,c},e}(Jr);rn.prototype.bytesPerElement=24,hr("StructArrayLayout6i1ul2ui2i24",rn);var nn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,o){var a=this.length;this.resize(a+1);var s=6*a;return this.int16[s+0]=t,this.int16[s+1]=e,this.int16[s+2]=r,this.int16[s+3]=n,this.int16[s+4]=i,this.int16[s+5]=o,a},e}(Jr);nn.prototype.bytesPerElement=12,hr("StructArrayLayout2i2i2i12",nn);var on=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e){var r=this.length;this.resize(r+1);var n=4*r;return this.uint8[n+0]=t,this.uint8[n+1]=e,r},e}(Jr);on.prototype.bytesPerElement=4,hr("StructArrayLayout2ub4",on);var an=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,o,a,s,u,l,p,c,h,f){var y=this.length;this.resize(y+1);var d=20*y,v=10*y,m=40*y;return this.int16[d+0]=t,this.int16[d+1]=e,this.uint16[d+2]=r,this.uint16[d+3]=n,this.uint32[v+2]=i,this.uint32[v+3]=o,this.uint32[v+4]=a,this.uint16[d+10]=s,this.uint16[d+11]=u,this.uint16[d+12]=l,this.float32[v+7]=p,this.float32[v+8]=c,this.uint8[m+36]=h,this.uint8[m+37]=f,y},e}(Jr);an.prototype.bytesPerElement=40,hr("StructArrayLayout2i2ui3ul3ui2f2ub40",an);var sn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t){var e=this.length;this.resize(e+1);var r=1*e;return this.float32[r+0]=t,e},e}(Jr);sn.prototype.bytesPerElement=4,hr("StructArrayLayout1f4",sn);var un=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;this.resize(n+1);var i=3*n;return this.int16[i+0]=t,this.int16[i+1]=e,this.int16[i+2]=r,n},e}(Jr);un.prototype.bytesPerElement=6,hr("StructArrayLayout3i6",un);var ln=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;this.resize(n+1);var i=2*n,o=4*n;return this.uint32[i+0]=t,this.uint16[o+2]=e,this.uint16[o+3]=r,n},e}(Jr);ln.prototype.bytesPerElement=8,hr("StructArrayLayout1ul2ui8",ln);var pn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;this.resize(n+1);var i=3*n;return this.uint16[i+0]=t,this.uint16[i+1]=e,this.uint16[i+2]=r,n},e}(Jr);pn.prototype.bytesPerElement=6,hr("StructArrayLayout3ui6",pn);var cn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e){var r=this.length;this.resize(r+1);var n=2*r;return this.uint16[n+0]=t,this.uint16[n+1]=e,r},e}(Jr);cn.prototype.bytesPerElement=4,hr("StructArrayLayout2ui4",cn);var hn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e){var r=this.length;this.resize(r+1);var n=2*r;return this.float32[n+0]=t,this.float32[n+1]=e,r},e}(Jr);hn.prototype.bytesPerElement=8,hr("StructArrayLayout2f8",hn);var fn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n){var i=this.length;this.resize(i+1);var o=4*i;return this.float32[o+0]=t,this.float32[o+1]=e,this.float32[o+2]=r,this.float32[o+3]=n,i},e}(Jr);fn.prototype.bytesPerElement=16,hr("StructArrayLayout4f16",fn);var yn=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={anchorPointX:{configurable:!0},anchorPointY:{configurable:!0},x1:{configurable:!0},y1:{configurable:!0},x2:{configurable:!0},y2:{configurable:!0},featureIndex:{configurable:!0},sourceLayerIndex:{configurable:!0},bucketIndex:{configurable:!0},radius:{configurable:!0},signedDistanceFromAnchor:{configurable:!0},anchorPoint:{configurable:!0}};return r.anchorPointX.get=function(){return this._structArray.int16[this._pos2+0]},r.anchorPointX.set=function(t){this._structArray.int16[this._pos2+0]=t;},r.anchorPointY.get=function(){return this._structArray.int16[this._pos2+1]},r.anchorPointY.set=function(t){this._structArray.int16[this._pos2+1]=t;},r.x1.get=function(){return this._structArray.int16[this._pos2+2]},r.x1.set=function(t){this._structArray.int16[this._pos2+2]=t;},r.y1.get=function(){return this._structArray.int16[this._pos2+3]},r.y1.set=function(t){this._structArray.int16[this._pos2+3]=t;},r.x2.get=function(){return this._structArray.int16[this._pos2+4]},r.x2.set=function(t){this._structArray.int16[this._pos2+4]=t;},r.y2.get=function(){return this._structArray.int16[this._pos2+5]},r.y2.set=function(t){this._structArray.int16[this._pos2+5]=t;},r.featureIndex.get=function(){return this._structArray.uint32[this._pos4+3]},r.featureIndex.set=function(t){this._structArray.uint32[this._pos4+3]=t;},r.sourceLayerIndex.get=function(){return this._structArray.uint16[this._pos2+8]},r.sourceLayerIndex.set=function(t){this._structArray.uint16[this._pos2+8]=t;},r.bucketIndex.get=function(){return this._structArray.uint16[this._pos2+9]},r.bucketIndex.set=function(t){this._structArray.uint16[this._pos2+9]=t;},r.radius.get=function(){return this._structArray.int16[this._pos2+10]},r.radius.set=function(t){this._structArray.int16[this._pos2+10]=t;},r.signedDistanceFromAnchor.get=function(){return this._structArray.int16[this._pos2+11]},r.signedDistanceFromAnchor.set=function(t){this._structArray.int16[this._pos2+11]=t;},r.anchorPoint.get=function(){return new s(this.anchorPointX,this.anchorPointY)},Object.defineProperties(e.prototype,r),e}(Kr);yn.prototype.size=24;var dn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.get=function(t){return new yn(this,t)},e}(rn);hr("CollisionBoxArray",dn);var vn=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={anchorX:{configurable:!0},anchorY:{configurable:!0},glyphStartIndex:{configurable:!0},numGlyphs:{configurable:!0},vertexStartIndex:{configurable:!0},lineStartIndex:{configurable:!0},lineLength:{configurable:!0},segment:{configurable:!0},lowerSize:{configurable:!0},upperSize:{configurable:!0},lineOffsetX:{configurable:!0},lineOffsetY:{configurable:!0},writingMode:{configurable:!0},hidden:{configurable:!0}};return r.anchorX.get=function(){return this._structArray.int16[this._pos2+0]},r.anchorX.set=function(t){this._structArray.int16[this._pos2+0]=t;},r.anchorY.get=function(){return this._structArray.int16[this._pos2+1]},r.anchorY.set=function(t){this._structArray.int16[this._pos2+1]=t;},r.glyphStartIndex.get=function(){return this._structArray.uint16[this._pos2+2]},r.glyphStartIndex.set=function(t){this._structArray.uint16[this._pos2+2]=t;},r.numGlyphs.get=function(){return this._structArray.uint16[this._pos2+3]},r.numGlyphs.set=function(t){this._structArray.uint16[this._pos2+3]=t;},r.vertexStartIndex.get=function(){return this._structArray.uint32[this._pos4+2]},r.vertexStartIndex.set=function(t){this._structArray.uint32[this._pos4+2]=t;},r.lineStartIndex.get=function(){return this._structArray.uint32[this._pos4+3]},r.lineStartIndex.set=function(t){this._structArray.uint32[this._pos4+3]=t;},r.lineLength.get=function(){return this._structArray.uint32[this._pos4+4]},r.lineLength.set=function(t){this._structArray.uint32[this._pos4+4]=t;},r.segment.get=function(){return this._structArray.uint16[this._pos2+10]},r.segment.set=function(t){this._structArray.uint16[this._pos2+10]=t;},r.lowerSize.get=function(){return this._structArray.uint16[this._pos2+11]},r.lowerSize.set=function(t){this._structArray.uint16[this._pos2+11]=t;},r.upperSize.get=function(){return this._structArray.uint16[this._pos2+12]},r.upperSize.set=function(t){this._structArray.uint16[this._pos2+12]=t;},r.lineOffsetX.get=function(){return this._structArray.float32[this._pos4+7]},r.lineOffsetX.set=function(t){this._structArray.float32[this._pos4+7]=t;},r.lineOffsetY.get=function(){return this._structArray.float32[this._pos4+8]},r.lineOffsetY.set=function(t){this._structArray.float32[this._pos4+8]=t;},r.writingMode.get=function(){return this._structArray.uint8[this._pos1+36]},r.writingMode.set=function(t){this._structArray.uint8[this._pos1+36]=t;},r.hidden.get=function(){return this._structArray.uint8[this._pos1+37]},r.hidden.set=function(t){this._structArray.uint8[this._pos1+37]=t;},Object.defineProperties(e.prototype,r),e}(Kr);vn.prototype.size=40;var mn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.get=function(t){return new vn(this,t)},e}(an);hr("PlacedSymbolArray",mn);var gn=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={offsetX:{configurable:!0}};return r.offsetX.get=function(){return this._structArray.float32[this._pos4+0]},r.offsetX.set=function(t){this._structArray.float32[this._pos4+0]=t;},Object.defineProperties(e.prototype,r),e}(Kr);gn.prototype.size=4;var xn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getoffsetX=function(t){return this.float32[1*t+0]},e.prototype.get=function(t){return new gn(this,t)},e}(sn);hr("GlyphOffsetArray",xn);var bn=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={x:{configurable:!0},y:{configurable:!0},tileUnitDistanceFromAnchor:{configurable:!0}};return r.x.get=function(){return this._structArray.int16[this._pos2+0]},r.x.set=function(t){this._structArray.int16[this._pos2+0]=t;},r.y.get=function(){return this._structArray.int16[this._pos2+1]},r.y.set=function(t){this._structArray.int16[this._pos2+1]=t;},r.tileUnitDistanceFromAnchor.get=function(){return this._structArray.int16[this._pos2+2]},r.tileUnitDistanceFromAnchor.set=function(t){this._structArray.int16[this._pos2+2]=t;},Object.defineProperties(e.prototype,r),e}(Kr);bn.prototype.size=6;var wn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getx=function(t){return this.int16[3*t+0]},e.prototype.gety=function(t){return this.int16[3*t+1]},e.prototype.gettileUnitDistanceFromAnchor=function(t){return this.int16[3*t+2]},e.prototype.get=function(t){return new bn(this,t)},e}(un);hr("SymbolLineVertexArray",wn);var _n=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={featureIndex:{configurable:!0},sourceLayerIndex:{configurable:!0},bucketIndex:{configurable:!0}};return r.featureIndex.get=function(){return this._structArray.uint32[this._pos4+0]},r.featureIndex.set=function(t){this._structArray.uint32[this._pos4+0]=t;},r.sourceLayerIndex.get=function(){return this._structArray.uint16[this._pos2+2]},r.sourceLayerIndex.set=function(t){this._structArray.uint16[this._pos2+2]=t;},r.bucketIndex.get=function(){return this._structArray.uint16[this._pos2+3]},r.bucketIndex.set=function(t){this._structArray.uint16[this._pos2+3]=t;},Object.defineProperties(e.prototype,r),e}(Kr);_n.prototype.size=8;var An=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.get=function(t){return new _n(this,t)},e}(ln);hr("FeatureIndexArray",An);var kn=$r([{name:"a_pos",components:2,type:"Int16"}],4).members,zn=function(t){void 0===t&&(t=[]),this.segments=t;};zn.prototype.prepareSegment=function(t,e,r){var n=this.segments[this.segments.length-1];return t>zn.MAX_VERTEX_ARRAY_LENGTH&&b("Max vertices per segment is "+zn.MAX_VERTEX_ARRAY_LENGTH+": bucket requested "+t),(!n||n.vertexLength+t>zn.MAX_VERTEX_ARRAY_LENGTH)&&(n={vertexOffset:e.length,primitiveOffset:r.length,vertexLength:0,primitiveLength:0},this.segments.push(n)),n},zn.prototype.get=function(){return this.segments},zn.prototype.destroy=function(){for(var t=0,e=this.segments;t<e.length;t+=1){var r=e[t];for(var n in r.vaos)r.vaos[n].destroy();}},zn.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,hr("SegmentVector",zn);var Sn=function(t,e){return 256*(t=c(Math.floor(t),0,255))+(e=c(Math.floor(e),0,255))};function Mn(t){return[Sn(255*t.r,255*t.g),Sn(255*t.b,255*t.a)]}var Vn=function(t,e,r){this.value=t,this.name=e,this.type=r,this.statistics={max:-1/0};};Vn.prototype.defines=function(){return["#define HAS_UNIFORM_u_"+this.name]},Vn.prototype.populatePaintArray=function(){},Vn.prototype.upload=function(){},Vn.prototype.destroy=function(){},Vn.prototype.setUniforms=function(t,e,r,n){var i=n.constantOr(this.value),o=t.gl;"color"===this.type?o.uniform4f(e.uniforms["u_"+this.name],i.r,i.g,i.b,i.a):o.uniform1f(e.uniforms["u_"+this.name],i);};var Bn=function(t,e,r){this.expression=t,this.name=e,this.type=r,this.statistics={max:-1/0};var n="color"===r?hn:sn;this.paintVertexAttributes=[{name:"a_"+e,type:"Float32",components:"color"===r?2:1,offset:0}],this.paintVertexArray=new n;};Bn.prototype.defines=function(){return[]},Bn.prototype.populatePaintArray=function(t,e){var r=this.paintVertexArray,n=r.length;r.reserve(t);var i=this.expression.evaluate(new Br(0),e);if("color"===this.type)for(var o=Mn(i),a=n;a<t;a++)r.emplaceBack(o[0],o[1]);else{for(var s=n;s<t;s++)r.emplaceBack(i);this.statistics.max=Math.max(this.statistics.max,i);}},Bn.prototype.upload=function(t){this.paintVertexArray&&(this.paintVertexBuffer=t.createVertexBuffer(this.paintVertexArray,this.paintVertexAttributes));},Bn.prototype.destroy=function(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy();},Bn.prototype.setUniforms=function(t,e){t.gl.uniform1f(e.uniforms["a_"+this.name+"_t"],0);};var Cn=function(t,e,r,n,i){this.expression=t,this.name=e,this.type=r,this.useIntegerZoom=n,this.zoom=i,this.statistics={max:-1/0};var o="color"===r?fn:hn;this.paintVertexAttributes=[{name:"a_"+e,type:"Float32",components:"color"===r?4:2,offset:0}],this.paintVertexArray=new o;};Cn.prototype.defines=function(){return[]},Cn.prototype.populatePaintArray=function(t,e){var r=this.paintVertexArray,n=r.length;r.reserve(t);var i=this.expression.evaluate(new Br(this.zoom),e),o=this.expression.evaluate(new Br(this.zoom+1),e);if("color"===this.type)for(var a=Mn(i),s=Mn(o),u=n;u<t;u++)r.emplaceBack(a[0],a[1],s[0],s[1]);else{for(var l=n;l<t;l++)r.emplaceBack(i,o);this.statistics.max=Math.max(this.statistics.max,i,o);}},Cn.prototype.upload=function(t){this.paintVertexArray&&(this.paintVertexBuffer=t.createVertexBuffer(this.paintVertexArray,this.paintVertexAttributes));},Cn.prototype.destroy=function(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy();},Cn.prototype.interpolationFactor=function(t){return this.useIntegerZoom?this.expression.interpolationFactor(Math.floor(t),this.zoom,this.zoom+1):this.expression.interpolationFactor(t,this.zoom,this.zoom+1)},Cn.prototype.setUniforms=function(t,e,r){t.gl.uniform1f(e.uniforms["a_"+this.name+"_t"],this.interpolationFactor(r.zoom));};var In=function(){this.binders={},this.cacheKey="",this._buffers=[];};In.createDynamic=function(t,e,r){var n=new In,i=[];for(var o in t.paint._values)if(r(o)){var a=t.paint.get(o);if(a instanceof Or&&a.property.specification["property-function"]){var s=Fn(o,t.type),u=a.property.specification.type,l=a.property.useIntegerZoom;"constant"===a.value.kind?(n.binders[o]=new Vn(a.value,s,u),i.push("/u_"+s)):"source"===a.value.kind?(n.binders[o]=new Bn(a.value,s,u),i.push("/a_"+s)):(n.binders[o]=new Cn(a.value,s,u,l,e),i.push("/z_"+s));}}return n.cacheKey=i.sort().join(""),n},In.prototype.populatePaintArrays=function(t,e){for(var r in this.binders)this.binders[r].populatePaintArray(t,e);},In.prototype.defines=function(){var t=[];for(var e in this.binders)t.push.apply(t,this.binders[e].defines());return t},In.prototype.setUniforms=function(t,e,r,n){for(var i in this.binders){this.binders[i].setUniforms(t,e,n,r.get(i));}},In.prototype.getPaintVertexBuffers=function(){return this._buffers},In.prototype.upload=function(t){for(var e in this.binders)this.binders[e].upload(t);var r=[];for(var n in this.binders){var i=this.binders[n];(i instanceof Bn||i instanceof Cn)&&i.paintVertexBuffer&&r.push(i.paintVertexBuffer);}this._buffers=r;},In.prototype.destroy=function(){for(var t in this.binders)this.binders[t].destroy();};var En=function(t,e,r,n){void 0===n&&(n=function(){return!0}),this.programConfigurations={};for(var i=0,o=e;i<o.length;i+=1){var a=o[i];this.programConfigurations[a.id]=In.createDynamic(a,r,n),this.programConfigurations[a.id].layoutAttributes=t;}};function Fn(t,e){return{"text-opacity":"opacity","icon-opacity":"opacity","text-color":"fill_color","icon-color":"fill_color","text-halo-color":"halo_color","icon-halo-color":"halo_color","text-halo-blur":"halo_blur","icon-halo-blur":"halo_blur","text-halo-width":"halo_width","icon-halo-width":"halo_width","line-gap-width":"gapwidth"}[t]||t.replace(e+"-","").replace(/-/g,"_")}En.prototype.populatePaintArrays=function(t,e){for(var r in this.programConfigurations)this.programConfigurations[r].populatePaintArrays(t,e);},En.prototype.get=function(t){return this.programConfigurations[t]},En.prototype.upload=function(t){for(var e in this.programConfigurations)this.programConfigurations[e].upload(t);},En.prototype.destroy=function(){for(var t in this.programConfigurations)this.programConfigurations[t].destroy();},hr("ConstantBinder",Vn),hr("SourceExpressionBinder",Bn),hr("CompositeExpressionBinder",Cn),hr("ProgramConfiguration",In,{omit:["_buffers"]}),hr("ProgramConfigurationSet",En);var Pn=8192;var Tn,On=(Tn=16,{min:-1*Math.pow(2,Tn-1),max:Math.pow(2,Tn-1)-1});function Ln(t){for(var e=Pn/t.extent,r=t.loadGeometry(),n=0;n<r.length;n++)for(var i=r[n],o=0;o<i.length;o++){var a=i[o];a.x=Math.round(a.x*e),a.y=Math.round(a.y*e),(a.x<On.min||a.x>On.max||a.y<On.min||a.y>On.max)&&b("Geometry exceeds allowed extent, reduce your vector tile buffer size");}return r}function jn(t,e,r,n,i){t.emplaceBack(2*e+(n+1)/2,2*r+(i+1)/2);}var qn=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new Xr,this.indexArray=new pn,this.segments=new zn,this.programConfigurations=new En(kn,t.layers,t.zoom);};function Rn(t,e,r){for(var n=0;n<t.length;n++){var i=t[n];if(Xn(i,e))return!0;if(Jn(e,i,r))return!0}return!1}function Un(t,e){if(1===t.length&&1===t[0].length)return Hn(e,t[0][0]);for(var r=0;r<e.length;r++)for(var n=e[r],i=0;i<n.length;i++)if(Hn(t,n[i]))return!0;for(var o=0;o<t.length;o++){for(var a=t[o],s=0;s<a.length;s++)if(Hn(e,a[s]))return!0;for(var u=0;u<e.length;u++)if(Zn(a,e[u]))return!0}return!1}function Dn(t,e,r){for(var n=0;n<e.length;n++)for(var i=e[n],o=0;o<t.length;o++){var a=t[o];if(a.length>=3)for(var s=0;s<i.length;s++)if(Xn(a,i[s]))return!0;if(Nn(a,i,r))return!0}return!1}function Nn(t,e,r){if(t.length>1){if(Zn(t,e))return!0;for(var n=0;n<e.length;n++)if(Jn(e[n],t,r))return!0}for(var i=0;i<t.length;i++)if(Jn(t[i],e,r))return!0;return!1}function Zn(t,e){if(0===t.length||0===e.length)return!1;for(var r=0;r<t.length-1;r++)for(var n=t[r],i=t[r+1],o=0;o<e.length-1;o++){if(Kn(n,i,e[o],e[o+1]))return!0}return!1}function Kn(t,e,r,n){return w(t,r,n)!==w(e,r,n)&&w(t,e,r)!==w(t,e,n)}function Jn(t,e,r){var n=r*r;if(1===e.length)return t.distSqr(e[0])<n;for(var i=1;i<e.length;i++){if($n(t,e[i-1],e[i])<n)return!0}return!1}function $n(t,e,r){var n=e.distSqr(r);if(0===n)return t.distSqr(e);var i=((t.x-e.x)*(r.x-e.x)+(t.y-e.y)*(r.y-e.y))/n;return i<0?t.distSqr(e):i>1?t.distSqr(r):t.distSqr(r.sub(e)._mult(i)._add(e))}function Hn(t,e){for(var r,n,i,o=!1,a=0;a<t.length;a++)for(var s=0,u=(r=t[a]).length-1;s<r.length;u=s++)n=r[s],i=r[u],n.y>e.y!=i.y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(o=!o);return o}function Xn(t,e){for(var r=!1,n=0,i=t.length-1;n<t.length;i=n++){var o=t[n],a=t[i];o.y>e.y!=a.y>e.y&&e.x<(a.x-o.x)*(e.y-o.y)/(a.y-o.y)+o.x&&(r=!r);}return r}function Gn(t,e,r){var n=e.paint.get(t).value;return"constant"===n.kind?n.value:r.programConfigurations.get(e.id).binders[t].statistics.max}function Yn(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])}function Wn(t,e,r,n,i){if(!e[0]&&!e[1])return t;var o=s.convert(e);"viewport"===r&&o._rotate(-n);for(var a=[],u=0;u<t.length;u++){for(var l=t[u],p=[],c=0;c<l.length;c++)p.push(l[c].sub(o._mult(i)));a.push(p);}return a}qn.prototype.populate=function(t,e){for(var r=0,n=t;r<n.length;r+=1){var i=n[r],o=i.feature,a=i.index,s=i.sourceLayerIndex;if(this.layers[0]._featureFilter(new Br(this.zoom),o)){var u=Ln(o);this.addFeature(o,u),e.featureIndex.insert(o,u,a,s,this.index);}}},qn.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},qn.prototype.upload=function(t){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,kn),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.programConfigurations.upload(t);},qn.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());},qn.prototype.addFeature=function(t,e){for(var r=0,n=e;r<n.length;r+=1)for(var i=0,o=n[r];i<o.length;i+=1){var a=o[i],s=a.x,u=a.y;if(!(s<0||s>=Pn||u<0||u>=Pn)){var l=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray),p=l.vertexLength;jn(this.layoutVertexArray,s,u,-1,-1),jn(this.layoutVertexArray,s,u,1,-1),jn(this.layoutVertexArray,s,u,1,1),jn(this.layoutVertexArray,s,u,-1,1),this.indexArray.emplaceBack(p,p+1,p+2),this.indexArray.emplaceBack(p,p+3,p+2),l.vertexLength+=4,l.primitiveLength+=2;}}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t);},hr("CircleBucket",qn,{omit:["layers"]});var Qn={paint:new Dr({"circle-radius":new qr(E.paint_circle["circle-radius"]),"circle-color":new qr(E.paint_circle["circle-color"]),"circle-blur":new qr(E.paint_circle["circle-blur"]),"circle-opacity":new qr(E.paint_circle["circle-opacity"]),"circle-translate":new jr(E.paint_circle["circle-translate"]),"circle-translate-anchor":new jr(E.paint_circle["circle-translate-anchor"]),"circle-pitch-scale":new jr(E.paint_circle["circle-pitch-scale"]),"circle-pitch-alignment":new jr(E.paint_circle["circle-pitch-alignment"]),"circle-stroke-width":new qr(E.paint_circle["circle-stroke-width"]),"circle-stroke-color":new qr(E.paint_circle["circle-stroke-color"]),"circle-stroke-opacity":new qr(E.paint_circle["circle-stroke-opacity"])})},ti=n(function(t,e){var r;t.exports=((r=new Float32Array(3))[0]=0,r[1]=0,r[2]=0,function(){var t=new Float32Array(4);t[0]=0,t[1]=0,t[2]=0,t[3]=0;}(),{vec3:{transformMat3:function(t,e,r){var n=e[0],i=e[1],o=e[2];return t[0]=n*r[0]+i*r[3]+o*r[6],t[1]=n*r[1]+i*r[4]+o*r[7],t[2]=n*r[2]+i*r[5]+o*r[8],t}},vec4:{transformMat4:function(t,e,r){var n=e[0],i=e[1],o=e[2],a=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*o+r[12]*a,t[1]=r[1]*n+r[5]*i+r[9]*o+r[13]*a,t[2]=r[2]*n+r[6]*i+r[10]*o+r[14]*a,t[3]=r[3]*n+r[7]*i+r[11]*o+r[15]*a,t}},mat2:{create:function(){var t=new Float32Array(4);return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t},rotate:function(t,e,r){var n=e[0],i=e[1],o=e[2],a=e[3],s=Math.sin(r),u=Math.cos(r);return t[0]=n*u+o*s,t[1]=i*u+a*s,t[2]=n*-s+o*u,t[3]=i*-s+a*u,t},scale:function(t,e,r){var n=e[0],i=e[1],o=e[2],a=e[3],s=r[0],u=r[1];return t[0]=n*s,t[1]=i*s,t[2]=o*u,t[3]=a*u,t}},mat3:{create:function(){var t=new Float32Array(9);return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t},fromRotation:function(t,e){var r=Math.sin(e),n=Math.cos(e);return t[0]=n,t[1]=r,t[2]=0,t[3]=-r,t[4]=n,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t}},mat4:{create:function(){var t=new Float32Array(16);return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},identity:function(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},translate:function(t,e,r){var n,i,o,a,s,u,l,p,c,h,f,y,d=r[0],v=r[1],m=r[2];return e===t?(t[12]=e[0]*d+e[4]*v+e[8]*m+e[12],t[13]=e[1]*d+e[5]*v+e[9]*m+e[13],t[14]=e[2]*d+e[6]*v+e[10]*m+e[14],t[15]=e[3]*d+e[7]*v+e[11]*m+e[15]):(n=e[0],i=e[1],o=e[2],a=e[3],s=e[4],u=e[5],l=e[6],p=e[7],c=e[8],h=e[9],f=e[10],y=e[11],t[0]=n,t[1]=i,t[2]=o,t[3]=a,t[4]=s,t[5]=u,t[6]=l,t[7]=p,t[8]=c,t[9]=h,t[10]=f,t[11]=y,t[12]=n*d+s*v+c*m+e[12],t[13]=i*d+u*v+h*m+e[13],t[14]=o*d+l*v+f*m+e[14],t[15]=a*d+p*v+y*m+e[15]),t},scale:function(t,e,r){var n=r[0],i=r[1],o=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*o,t[9]=e[9]*o,t[10]=e[10]*o,t[11]=e[11]*o,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},multiply:function(t,e,r){var n=e[0],i=e[1],o=e[2],a=e[3],s=e[4],u=e[5],l=e[6],p=e[7],c=e[8],h=e[9],f=e[10],y=e[11],d=e[12],v=e[13],m=e[14],g=e[15],x=r[0],b=r[1],w=r[2],_=r[3];return t[0]=x*n+b*s+w*c+_*d,t[1]=x*i+b*u+w*h+_*v,t[2]=x*o+b*l+w*f+_*m,t[3]=x*a+b*p+w*y+_*g,x=r[4],b=r[5],w=r[6],_=r[7],t[4]=x*n+b*s+w*c+_*d,t[5]=x*i+b*u+w*h+_*v,t[6]=x*o+b*l+w*f+_*m,t[7]=x*a+b*p+w*y+_*g,x=r[8],b=r[9],w=r[10],_=r[11],t[8]=x*n+b*s+w*c+_*d,t[9]=x*i+b*u+w*h+_*v,t[10]=x*o+b*l+w*f+_*m,t[11]=x*a+b*p+w*y+_*g,x=r[12],b=r[13],w=r[14],_=r[15],t[12]=x*n+b*s+w*c+_*d,t[13]=x*i+b*u+w*h+_*v,t[14]=x*o+b*l+w*f+_*m,t[15]=x*a+b*p+w*y+_*g,t},perspective:function(t,e,r,n,i){var o=1/Math.tan(e/2),a=1/(n-i);return t[0]=o/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=o,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=(i+n)*a,t[11]=-1,t[12]=0,t[13]=0,t[14]=2*i*n*a,t[15]=0,t},rotateX:function(t,e,r){var n=Math.sin(r),i=Math.cos(r),o=e[4],a=e[5],s=e[6],u=e[7],l=e[8],p=e[9],c=e[10],h=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=o*i+l*n,t[5]=a*i+p*n,t[6]=s*i+c*n,t[7]=u*i+h*n,t[8]=l*i-o*n,t[9]=p*i-a*n,t[10]=c*i-s*n,t[11]=h*i-u*n,t},rotateZ:function(t,e,r){var n=Math.sin(r),i=Math.cos(r),o=e[0],a=e[1],s=e[2],u=e[3],l=e[4],p=e[5],c=e[6],h=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=o*i+l*n,t[1]=a*i+p*n,t[2]=s*i+c*n,t[3]=u*i+h*n,t[4]=l*i-o*n,t[5]=p*i-a*n,t[6]=c*i-s*n,t[7]=h*i-u*n,t},invert:function(t,e){var r=e[0],n=e[1],i=e[2],o=e[3],a=e[4],s=e[5],u=e[6],l=e[7],p=e[8],c=e[9],h=e[10],f=e[11],y=e[12],d=e[13],v=e[14],m=e[15],g=r*s-n*a,x=r*u-i*a,b=r*l-o*a,w=n*u-i*s,_=n*l-o*s,A=i*l-o*u,k=p*d-c*y,z=p*v-h*y,S=p*m-f*y,M=c*v-h*d,V=c*m-f*d,B=h*m-f*v,C=g*B-x*V+b*M+w*S-_*z+A*k;return C?(C=1/C,t[0]=(s*B-u*V+l*M)*C,t[1]=(i*V-n*B-o*M)*C,t[2]=(d*A-v*_+m*w)*C,t[3]=(h*_-c*A-f*w)*C,t[4]=(u*S-a*B-l*z)*C,t[5]=(r*B-i*S+o*z)*C,t[6]=(v*b-y*A-m*x)*C,t[7]=(p*A-h*b+f*x)*C,t[8]=(a*V-s*S+l*k)*C,t[9]=(n*S-r*V-o*k)*C,t[10]=(y*_-d*b+m*g)*C,t[11]=(c*b-p*_-f*g)*C,t[12]=(s*z-a*M-u*k)*C,t[13]=(r*M-n*z+i*k)*C,t[14]=(d*x-y*w-v*g)*C,t[15]=(p*w-c*x+h*g)*C,t):null},ortho:function(t,e,r,n,i,o,a){var s=1/(e-r),u=1/(n-i),l=1/(o-a);return t[0]=-2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*u,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*l,t[11]=0,t[12]=(e+r)*s,t[13]=(i+n)*u,t[14]=(a+o)*l,t[15]=1,t}}});}),ei=(ti.vec3,ti.vec4),ri=(ti.mat2,ti.mat3,ti.mat4),ni=function(t){function e(e){t.call(this,e,Qn);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new qn(t)},e.prototype.queryRadius=function(t){var e=t;return Gn("circle-radius",this,e)+Gn("circle-stroke-width",this,e)+Yn(this.paint.get("circle-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,o,a){for(var s=Wn(t,this.paint.get("circle-translate"),this.paint.get("circle-translate-anchor"),i.angle,o),u=this.paint.get("circle-radius").evaluate(e)+this.paint.get("circle-stroke-width").evaluate(e),l="map"===this.paint.get("circle-pitch-alignment"),p=l?s:function(t,e,r){return t.map(function(t){return t.map(function(t){return ii(t,e,r)})})}(s,a,i),c=l?u*o:u,h=0,f=r;h<f.length;h+=1)for(var y=0,d=f[h];y<d.length;y+=1){var v=d[y],m=l?v:ii(v,a,i),g=c,x=ei.transformMat4([],[v.x,v.y,0,1],a);if("viewport"===this.paint.get("circle-pitch-scale")&&"map"===this.paint.get("circle-pitch-alignment")?g*=x[3]/i.cameraToCenterDistance:"map"===this.paint.get("circle-pitch-scale")&&"viewport"===this.paint.get("circle-pitch-alignment")&&(g*=i.cameraToCenterDistance/x[3]),Rn(p,m,g))return!0}return!1},e}(Nr);function ii(t,e,r){var n=ei.transformMat4([],[t.x,t.y,0,1],e);return new s((n[0]/n[3]+1)*r.width*.5,(n[1]/n[3]+1)*r.height*.5)}var oi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(qn);function ai(t,e,r,n){var i=e.width,o=e.height;if(n){if(n.length!==i*o*r)throw new RangeError("mismatched image size")}else n=new Uint8Array(i*o*r);return t.width=i,t.height=o,t.data=n,t}function si(t,e,r){var n=e.width,i=e.height;if(n!==t.width||i!==t.height){var o=ai({},{width:n,height:i},r);ui(t,o,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,n),height:Math.min(t.height,i)},r),t.width=n,t.height=i,t.data=o.data;}}function ui(t,e,r,n,i,o){if(0===i.width||0===i.height)return e;if(i.width>t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");for(var a=t.data,s=e.data,u=0;u<i.height;u++)for(var l=((r.y+u)*t.width+r.x)*o,p=((n.y+u)*e.width+n.x)*o,c=0;c<i.width*o;c++)s[p+c]=a[l+c];return e}hr("HeatmapBucket",oi,{omit:["layers"]});var li=function(t,e){ai(this,t,1,e);};li.prototype.resize=function(t){si(this,t,1);},li.prototype.clone=function(){return new li({width:this.width,height:this.height},new Uint8Array(this.data))},li.copy=function(t,e,r,n,i){ui(t,e,r,n,i,1);};var pi=function(t,e){ai(this,t,4,e);};pi.prototype.resize=function(t){si(this,t,4);},pi.prototype.clone=function(){return new pi({width:this.width,height:this.height},new Uint8Array(this.data))},pi.copy=function(t,e,r,n,i){ui(t,e,r,n,i,4);},hr("AlphaImage",li),hr("RGBAImage",pi);var ci={paint:new Dr({"heatmap-radius":new qr(E.paint_heatmap["heatmap-radius"]),"heatmap-weight":new qr(E.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new jr(E.paint_heatmap["heatmap-intensity"]),"heatmap-color":new Ur(E.paint_heatmap["heatmap-color"]),"heatmap-opacity":new jr(E.paint_heatmap["heatmap-opacity"])})};function hi(t,e){for(var r=new Uint8Array(1024),n={},i=0,o=0;i<256;i++,o+=4){n[e]=i/255;var a=t.evaluate(n);r[o+0]=Math.floor(255*a.r/a.a),r[o+1]=Math.floor(255*a.g/a.a),r[o+2]=Math.floor(255*a.b/a.a),r[o+3]=Math.floor(255*a.a);}return new pi({width:256,height:1},r)}var fi=function(t){function e(e){t.call(this,e,ci),this._updateColorRamp();}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new oi(t)},e.prototype.setPaintProperty=function(e,r,n){t.prototype.setPaintProperty.call(this,e,r,n),"heatmap-color"===e&&this._updateColorRamp();},e.prototype._updateColorRamp=function(){var t=this._transitionablePaint._values["heatmap-color"].value.expression;this.colorRamp=hi(t,"heatmapDensity"),this.colorRampTexture=null;},e.prototype.resize=function(){this.heatmapFbo&&(this.heatmapFbo.destroy(),this.heatmapFbo=null);},e.prototype.queryRadius=function(){return 0},e.prototype.queryIntersectsFeature=function(){return!1},e.prototype.hasOffscreenPass=function(){return 0!==this.paint.get("heatmap-opacity")&&"none"!==this.visibility},e}(Nr),yi={paint:new Dr({"hillshade-illumination-direction":new jr(E.paint_hillshade["hillshade-illumination-direction"]),"hillshade-illumination-anchor":new jr(E.paint_hillshade["hillshade-illumination-anchor"]),"hillshade-exaggeration":new jr(E.paint_hillshade["hillshade-exaggeration"]),"hillshade-shadow-color":new jr(E.paint_hillshade["hillshade-shadow-color"]),"hillshade-highlight-color":new jr(E.paint_hillshade["hillshade-highlight-color"]),"hillshade-accent-color":new jr(E.paint_hillshade["hillshade-accent-color"])})},di=function(t){function e(e){t.call(this,e,yi);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.hasOffscreenPass=function(){return 0!==this.paint.get("hillshade-exaggeration")&&"none"!==this.visibility},e}(Nr),vi=$r([{name:"a_pos",components:2,type:"Int16"}],4).members,mi=xi,gi=xi;function xi(t,e,r){r=r||2;var n,i,o,a,s,u,l,p=e&&e.length,c=p?e[0]*r:t.length,h=bi(t,0,c,r,!0),f=[];if(!h)return f;if(p&&(h=function(t,e,r,n){var i,o,a,s,u,l=[];for(i=0,o=e.length;i<o;i++)a=e[i]*n,s=i<o-1?e[i+1]*n:t.length,(u=bi(t,a,s,n,!1))===u.next&&(u.steiner=!0),l.push(Ci(u));for(l.sort(Mi),i=0;i<l.length;i++)Vi(l[i],r),r=wi(r,r.next);return r}(t,e,h,r)),t.length>80*r){n=o=t[0],i=a=t[1];for(var y=r;y<c;y+=r)(s=t[y])<n&&(n=s),(u=t[y+1])<i&&(i=u),s>o&&(o=s),u>a&&(a=u);l=0!==(l=Math.max(o-n,a-i))?1/l:0;}return _i(h,f,r,n,i,l),f}function bi(t,e,r,n,i){var o,a;if(i===Ui(t,e,r,n)>0)for(o=e;o<r;o+=n)a=ji(o,t[o],t[o+1],a);else for(o=r-n;o>=e;o-=n)a=ji(o,t[o],t[o+1],a);return a&&Pi(a,a.next)&&(qi(a),a=a.next),a}function wi(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!Pi(n,n.next)&&0!==Fi(n.prev,n,n.next))n=n.next;else{if(qi(n),(n=e=n.prev)===n.next)break;r=!0;}}while(r||n!==e);return e}function _i(t,e,r,n,i,o,a){if(t){!a&&o&&function(t,e,r,n){var i=t;do{null===i.z&&(i.z=Bi(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,r,n,i,o,a,s,u,l=1;do{for(r=t,t=null,o=null,a=0;r;){for(a++,n=r,s=0,e=0;e<l&&(s++,n=n.nextZ);e++);for(u=l;s>0||u>0&&n;)0!==s&&(0===u||!n||r.z<=n.z)?(i=r,r=r.nextZ,s--):(i=n,n=n.nextZ,u--),o?o.nextZ=i:t=i,i.prevZ=o,o=i;r=n;}o.nextZ=null,l*=2;}while(a>1)}(i);}(t,n,i,o);for(var s,u,l=t;t.prev!==t.next;)if(s=t.prev,u=t.next,o?ki(t,n,i,o):Ai(t))e.push(s.i/r),e.push(t.i/r),e.push(u.i/r),qi(t),t=u.next,l=u.next;else if((t=u)===l){a?1===a?_i(t=zi(t,e,r),e,r,n,i,o,2):2===a&&Si(t,e,r,n,i,o):_i(wi(t),e,r,n,i,o,1);break}}}function Ai(t){var e=t.prev,r=t,n=t.next;if(Fi(e,r,n)>=0)return!1;for(var i=t.next.next;i!==t.prev;){if(Ii(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&Fi(i.prev,i,i.next)>=0)return!1;i=i.next;}return!0}function ki(t,e,r,n){var i=t.prev,o=t,a=t.next;if(Fi(i,o,a)>=0)return!1;for(var s=i.x<o.x?i.x<a.x?i.x:a.x:o.x<a.x?o.x:a.x,u=i.y<o.y?i.y<a.y?i.y:a.y:o.y<a.y?o.y:a.y,l=i.x>o.x?i.x>a.x?i.x:a.x:o.x>a.x?o.x:a.x,p=i.y>o.y?i.y>a.y?i.y:a.y:o.y>a.y?o.y:a.y,c=Bi(s,u,e,r,n),h=Bi(l,p,e,r,n),f=t.prevZ,y=t.nextZ;f&&f.z>=c&&y&&y.z<=h;){if(f!==t.prev&&f!==t.next&&Ii(i.x,i.y,o.x,o.y,a.x,a.y,f.x,f.y)&&Fi(f.prev,f,f.next)>=0)return!1;if(f=f.prevZ,y!==t.prev&&y!==t.next&&Ii(i.x,i.y,o.x,o.y,a.x,a.y,y.x,y.y)&&Fi(y.prev,y,y.next)>=0)return!1;y=y.nextZ;}for(;f&&f.z>=c;){if(f!==t.prev&&f!==t.next&&Ii(i.x,i.y,o.x,o.y,a.x,a.y,f.x,f.y)&&Fi(f.prev,f,f.next)>=0)return!1;f=f.prevZ;}for(;y&&y.z<=h;){if(y!==t.prev&&y!==t.next&&Ii(i.x,i.y,o.x,o.y,a.x,a.y,y.x,y.y)&&Fi(y.prev,y,y.next)>=0)return!1;y=y.nextZ;}return!0}function zi(t,e,r){var n=t;do{var i=n.prev,o=n.next.next;!Pi(i,o)&&Ti(i,n,n.next,o)&&Oi(i,o)&&Oi(o,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(o.i/r),qi(n),qi(n.next),n=t=o),n=n.next;}while(n!==t);return n}function Si(t,e,r,n,i,o){var a=t;do{for(var s=a.next.next;s!==a.prev;){if(a.i!==s.i&&Ei(a,s)){var u=Li(a,s);return a=wi(a,a.next),u=wi(u,u.next),_i(a,e,r,n,i,o),void _i(u,e,r,n,i,o)}s=s.next;}a=a.next;}while(a!==t)}function Mi(t,e){return t.x-e.x}function Vi(t,e){if(e=function(t,e){var r,n=e,i=t.x,o=t.y,a=-1/0;do{if(o<=n.y&&o>=n.next.y&&n.next.y!==n.y){var s=n.x+(o-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(s<=i&&s>a){if(a=s,s===i){if(o===n.y)return n;if(o===n.next.y)return n.next}r=n.x<n.next.x?n:n.next;}}n=n.next;}while(n!==e);if(!r)return null;if(i===a)return r.prev;var u,l=r,p=r.x,c=r.y,h=1/0;n=r.next;for(;n!==l;)i>=n.x&&n.x>=p&&i!==n.x&&Ii(o<c?i:a,o,p,c,o<c?a:i,o,n.x,n.y)&&((u=Math.abs(o-n.y)/(i-n.x))<h||u===h&&n.x>r.x)&&Oi(n,t)&&(r=n,h=u),n=n.next;return r}(t,e)){var r=Li(e,t);wi(r,r.next);}}function Bi(t,e,r,n,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*i)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*i)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function Ci(t){var e=t,r=t;do{e.x<r.x&&(r=e),e=e.next;}while(e!==t);return r}function Ii(t,e,r,n,i,o,a,s){return(i-a)*(e-s)-(t-a)*(o-s)>=0&&(t-a)*(n-s)-(r-a)*(e-s)>=0&&(r-a)*(o-s)-(i-a)*(n-s)>=0}function Ei(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&Ti(r,r.next,t,e))return!0;r=r.next;}while(r!==t);return!1}(t,e)&&Oi(t,e)&&Oi(e,t)&&function(t,e){var r=t,n=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;do{r.y>o!=r.next.y>o&&r.next.y!==r.y&&i<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;}while(r!==t);return n}(t,e)}function Fi(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function Pi(t,e){return t.x===e.x&&t.y===e.y}function Ti(t,e,r,n){return!!(Pi(t,e)&&Pi(r,n)||Pi(t,n)&&Pi(r,e))||Fi(t,e,r)>0!=Fi(t,e,n)>0&&Fi(r,n,t)>0!=Fi(r,n,e)>0}function Oi(t,e){return Fi(t.prev,t,t.next)<0?Fi(t,e,t.next)>=0&&Fi(t,t.prev,e)>=0:Fi(t,e,t.prev)<0||Fi(t,t.next,e)<0}function Li(t,e){var r=new Ri(t.i,t.x,t.y),n=new Ri(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,o.next=n,n.prev=o,n}function ji(t,e,r,n){var i=new Ri(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function qi(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ);}function Ri(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1;}function Ui(t,e,r,n){for(var i=0,o=e,a=r-n;o<r;o+=n)i+=(t[a]-t[o])*(t[o+1]+t[a+1]),a=o;return i}xi.deviation=function(t,e,r,n){var i=e&&e.length,o=i?e[0]*r:t.length,a=Math.abs(Ui(t,0,o,r));if(i)for(var s=0,u=e.length;s<u;s++){var l=e[s]*r,p=s<u-1?e[s+1]*r:t.length;a-=Math.abs(Ui(t,l,p,r));}var c=0;for(s=0;s<n.length;s+=3){var h=n[s]*r,f=n[s+1]*r,y=n[s+2]*r;c+=Math.abs((t[h]-t[y])*(t[f+1]-t[h+1])-(t[h]-t[f])*(t[y+1]-t[h+1]));}return 0===a&&0===c?0:Math.abs((c-a)/a)},xi.flatten=function(t){for(var e=t[0][0].length,r={vertices:[],holes:[],dimensions:e},n=0,i=0;i<t.length;i++){for(var o=0;o<t[i].length;o++)for(var a=0;a<e;a++)r.vertices.push(t[i][o][a]);i>0&&(n+=t[i-1].length,r.holes.push(n));}return r},mi.default=gi;var Di=Zi,Ni=Zi;function Zi(t,e,r,n,i){!function t(e,r,n,i,o){for(;i>n;){if(i-n>600){var a=i-n+1,s=r-n+1,u=Math.log(a),l=.5*Math.exp(2*u/3),p=.5*Math.sqrt(u*l*(a-l)/a)*(s-a/2<0?-1:1),c=Math.max(n,Math.floor(r-s*l/a+p)),h=Math.min(i,Math.floor(r+(a-s)*l/a+p));t(e,r,c,h,o);}var f=e[r],y=n,d=i;for(Ki(e,n,r),o(e[i],f)>0&&Ki(e,n,i);y<d;){for(Ki(e,y,d),y++,d--;o(e[y],f)<0;)y++;for(;o(e[d],f)>0;)d--;}0===o(e[n],f)?Ki(e,n,d):Ki(e,++d,i),d<=r&&(n=d+1),r<=d&&(i=d-1);}}(t,e,r||0,n||t.length-1,i||Ji);}function Ki(t,e,r){var n=t[e];t[e]=t[r],t[r]=n;}function Ji(t,e){return t<e?-1:t>e?1:0}function $i(t,e){var r=t.length;if(r<=1)return[t];for(var n,i,o=[],a=0;a<r;a++){var s=_(t[a]);0!==s&&(t[a].area=Math.abs(s),void 0===i&&(i=s<0),i===s<0?(n&&o.push(n),n=[t[a]]):n.push(t[a]));}if(n&&o.push(n),e>1)for(var u=0;u<o.length;u++)o[u].length<=e||(Di(o[u],e,1,o[u].length-1,Hi),o[u]=o[u].slice(0,e));return o}function Hi(t,e){return e.area-t.area}Di.default=Ni;var Xi=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new Xr,this.indexArray=new pn,this.indexArray2=new cn,this.programConfigurations=new En(vi,t.layers,t.zoom),this.segments=new zn,this.segments2=new zn;};Xi.prototype.populate=function(t,e){for(var r=0,n=t;r<n.length;r+=1){var i=n[r],o=i.feature,a=i.index,s=i.sourceLayerIndex;if(this.layers[0]._featureFilter(new Br(this.zoom),o)){var u=Ln(o);this.addFeature(o,u),e.featureIndex.insert(o,u,a,s,this.index);}}},Xi.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},Xi.prototype.upload=function(t){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,vi),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.indexBuffer2=t.createIndexBuffer(this.indexArray2),this.programConfigurations.upload(t);},Xi.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy());},Xi.prototype.addFeature=function(t,e){for(var r=0,n=$i(e,500);r<n.length;r+=1){for(var i=n[r],o=0,a=0,s=i;a<s.length;a+=1){o+=s[a].length;}for(var u=this.segments.prepareSegment(o,this.layoutVertexArray,this.indexArray),l=u.vertexLength,p=[],c=[],h=0,f=i;h<f.length;h+=1){var y=f[h];if(0!==y.length){y!==i[0]&&c.push(p.length/2);var d=this.segments2.prepareSegment(y.length,this.layoutVertexArray,this.indexArray2),v=d.vertexLength;this.layoutVertexArray.emplaceBack(y[0].x,y[0].y),this.indexArray2.emplaceBack(v+y.length-1,v),p.push(y[0].x),p.push(y[0].y);for(var m=1;m<y.length;m++)this.layoutVertexArray.emplaceBack(y[m].x,y[m].y),this.indexArray2.emplaceBack(v+m-1,v+m),p.push(y[m].x),p.push(y[m].y);d.vertexLength+=y.length,d.primitiveLength+=y.length;}}for(var g=mi(p,c),x=0;x<g.length;x+=3)this.indexArray.emplaceBack(l+g[x],l+g[x+1],l+g[x+2]);u.vertexLength+=o,u.primitiveLength+=g.length/3;}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t);},hr("FillBucket",Xi,{omit:["layers"]});var Gi={paint:new Dr({"fill-antialias":new jr(E.paint_fill["fill-antialias"]),"fill-opacity":new qr(E.paint_fill["fill-opacity"]),"fill-color":new qr(E.paint_fill["fill-color"]),"fill-outline-color":new qr(E.paint_fill["fill-outline-color"]),"fill-translate":new jr(E.paint_fill["fill-translate"]),"fill-translate-anchor":new jr(E.paint_fill["fill-translate-anchor"]),"fill-pattern":new Rr(E.paint_fill["fill-pattern"])})},Yi=function(t){function e(e){t.call(this,e,Gi);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.recalculate=function(t){this.paint=this._transitioningPaint.possiblyEvaluate(t);var e=this.paint._values["fill-outline-color"];"constant"===e.value.kind&&void 0===e.value.value&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"]);},e.prototype.createBucket=function(t){return new Xi(t)},e.prototype.queryRadius=function(){return Yn(this.paint.get("fill-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,o){return Un(Wn(t,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),i.angle,o),r)},e}(Nr),Wi=$r([{name:"a_pos",components:2,type:"Int16"},{name:"a_normal_ed",components:4,type:"Int16"}],4).members,Qi=Math.pow(2,13);function to(t,e,r,n,i,o,a,s){t.emplaceBack(e,r,2*Math.floor(n*Qi)+a,i*Qi*2,o*Qi*2,Math.round(s));}var eo=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new Yr,this.indexArray=new pn,this.programConfigurations=new En(Wi,t.layers,t.zoom),this.segments=new zn;};function ro(t,e){return t.x===e.x&&(t.x<0||t.x>Pn)||t.y===e.y&&(t.y<0||t.y>Pn)}function no(t){return t.every(function(t){return t.x<0})||t.every(function(t){return t.x>Pn})||t.every(function(t){return t.y<0})||t.every(function(t){return t.y>Pn})}eo.prototype.populate=function(t,e){for(var r=0,n=t;r<n.length;r+=1){var i=n[r],o=i.feature,a=i.index,s=i.sourceLayerIndex;if(this.layers[0]._featureFilter(new Br(this.zoom),o)){var u=Ln(o);this.addFeature(o,u),e.featureIndex.insert(o,u,a,s,this.index);}}},eo.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},eo.prototype.upload=function(t){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Wi),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.programConfigurations.upload(t);},eo.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());},eo.prototype.addFeature=function(t,e){for(var r=0,n=$i(e,500);r<n.length;r+=1){for(var i=n[r],o=0,a=0,s=i;a<s.length;a+=1){o+=s[a].length;}for(var u=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray),l=0,p=i;l<p.length;l+=1){var c=p[l];if(0!==c.length&&!no(c))for(var h=0,f=0;f<c.length;f++){var y=c[f];if(f>=1){var d=c[f-1];if(!ro(y,d)){u.vertexLength+4>zn.MAX_VERTEX_ARRAY_LENGTH&&(u=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));var v=y.sub(d)._perp()._unit(),m=d.dist(y);h+m>32768&&(h=0),to(this.layoutVertexArray,y.x,y.y,v.x,v.y,0,0,h),to(this.layoutVertexArray,y.x,y.y,v.x,v.y,0,1,h),h+=m,to(this.layoutVertexArray,d.x,d.y,v.x,v.y,0,0,h),to(this.layoutVertexArray,d.x,d.y,v.x,v.y,0,1,h);var g=u.vertexLength;this.indexArray.emplaceBack(g,g+1,g+2),this.indexArray.emplaceBack(g+1,g+2,g+3),u.vertexLength+=4,u.primitiveLength+=2;}}}}u.vertexLength+o>zn.MAX_VERTEX_ARRAY_LENGTH&&(u=this.segments.prepareSegment(o,this.layoutVertexArray,this.indexArray));for(var x=[],b=[],w=u.vertexLength,_=0,A=i;_<A.length;_+=1){var k=A[_];if(0!==k.length){k!==i[0]&&b.push(x.length/2);for(var z=0;z<k.length;z++){var S=k[z];to(this.layoutVertexArray,S.x,S.y,0,0,1,1,0),x.push(S.x),x.push(S.y);}}}for(var M=mi(x,b),V=0;V<M.length;V+=3)this.indexArray.emplaceBack(w+M[V],w+M[V+1],w+M[V+2]);u.primitiveLength+=M.length/3,u.vertexLength+=o;}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t);},hr("FillExtrusionBucket",eo,{omit:["layers"]});var io={paint:new Dr({"fill-extrusion-opacity":new jr(E["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new qr(E["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new jr(E["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new jr(E["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new Rr(E["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new qr(E["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new qr(E["paint_fill-extrusion"]["fill-extrusion-base"])})},oo=function(t){function e(e){t.call(this,e,io);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new eo(t)},e.prototype.queryRadius=function(){return Yn(this.paint.get("fill-extrusion-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,o){return Un(Wn(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),i.angle,o),r)},e.prototype.hasOffscreenPass=function(){return 0!==this.paint.get("fill-extrusion-opacity")&&"none"!==this.visibility},e.prototype.resize=function(){this.viewportFrame&&(this.viewportFrame.destroy(),this.viewportFrame=null);},e}(Nr),ao=$r([{name:"a_pos_normal",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint8"}],4).members,so=uo;function uo(t,e,r,n,i){this.properties={},this.extent=r,this.type=0,this._pbf=t,this._geometry=-1,this._keys=n,this._values=i,t.readFields(lo,this,e);}function lo(t,e,r){1==t?e.id=r.readVarint():2==t?function(t,e){var r=t.readVarint()+t.pos;for(;t.pos<r;){var n=e._keys[t.readVarint()],i=e._values[t.readVarint()];e.properties[n]=i;}}(r,e):3==t?e.type=r.readVarint():4==t&&(e._geometry=r.pos);}function po(t){for(var e,r,n=0,i=0,o=t.length,a=o-1;i<o;a=i++)e=t[i],n+=((r=t[a]).x-e.x)*(e.y+r.y);return n}uo.types=["Unknown","Point","LineString","Polygon"],uo.prototype.loadGeometry=function(){var t=this._pbf;t.pos=this._geometry;for(var e,r=t.readVarint()+t.pos,n=1,i=0,o=0,a=0,u=[];t.pos<r;){if(i<=0){var l=t.readVarint();n=7&l,i=l>>3;}if(i--,1===n||2===n)o+=t.readSVarint(),a+=t.readSVarint(),1===n&&(e&&u.push(e),e=[]),e.push(new s(o,a));else{if(7!==n)throw new Error("unknown command "+n);e&&e.push(e[0].clone());}}return e&&u.push(e),u},uo.prototype.bbox=function(){var t=this._pbf;t.pos=this._geometry;for(var e=t.readVarint()+t.pos,r=1,n=0,i=0,o=0,a=1/0,s=-1/0,u=1/0,l=-1/0;t.pos<e;){if(n<=0){var p=t.readVarint();r=7&p,n=p>>3;}if(n--,1===r||2===r)(i+=t.readSVarint())<a&&(a=i),i>s&&(s=i),(o+=t.readSVarint())<u&&(u=o),o>l&&(l=o);else if(7!==r)throw new Error("unknown command "+r)}return[a,u,s,l]},uo.prototype.toGeoJSON=function(t,e,r){var n,i,o=this.extent*Math.pow(2,r),a=this.extent*t,s=this.extent*e,u=this.loadGeometry(),l=uo.types[this.type];function p(t){for(var e=0;e<t.length;e++){var r=t[e],n=180-360*(r.y+s)/o;t[e]=[360*(r.x+a)/o-180,360/Math.PI*Math.atan(Math.exp(n*Math.PI/180))-90];}}switch(this.type){case 1:var c=[];for(n=0;n<u.length;n++)c[n]=u[n][0];p(u=c);break;case 2:for(n=0;n<u.length;n++)p(u[n]);break;case 3:for(u=function(t){var e=t.length;if(e<=1)return[t];for(var r,n,i=[],o=0;o<e;o++){var a=po(t[o]);0!==a&&(void 0===n&&(n=a<0),n===a<0?(r&&i.push(r),r=[t[o]]):r.push(t[o]));}r&&i.push(r);return i}(u),n=0;n<u.length;n++)for(i=0;i<u[n].length;i++)p(u[n][i]);}1===u.length?u=u[0]:l="Multi"+l;var h={type:"Feature",geometry:{type:l,coordinates:u},properties:this.properties};return"id"in this&&(h.id=this.id),h};var co=ho;function ho(t,e){this.version=1,this.name=null,this.extent=4096,this.length=0,this._pbf=t,this._keys=[],this._values=[],this._features=[],t.readFields(fo,this,e),this.length=this._features.length;}function fo(t,e,r){15===t?e.version=r.readVarint():1===t?e.name=r.readString():5===t?e.extent=r.readVarint():2===t?e._features.push(r.pos):3===t?e._keys.push(r.readString()):4===t&&e._values.push(function(t){var e=null,r=t.readVarint()+t.pos;for(;t.pos<r;){var n=t.readVarint()>>3;e=1===n?t.readString():2===n?t.readFloat():3===n?t.readDouble():4===n?t.readVarint64():5===n?t.readVarint():6===n?t.readSVarint():7===n?t.readBoolean():null;}return e}(r));}function yo(t,e,r){if(3===t){var n=new co(r,r.readVarint()+r.pos);n.length&&(e[n.name]=n);}}ho.prototype.feature=function(t){if(t<0||t>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];var e=this._pbf.readVarint()+this._pbf.pos;return new so(this._pbf,e,this.extent,this._keys,this._values)};var vo={VectorTile:function(t,e){this.layers=t.readFields(yo,{},e);},VectorTileFeature:so,VectorTileLayer:co},mo=vo.VectorTileFeature.types,go=63,xo=Math.cos(Math.PI/180*37.5),bo=.5,wo=Math.pow(2,14)/bo;function _o(t,e,r,n,i,o,a){t.emplaceBack(e.x,e.y,n?1:0,i?1:-1,Math.round(go*r.x)+128,Math.round(go*r.y)+128,1+(0===o?0:o<0?-1:1)|(a*bo&63)<<2,a*bo>>6);}var Ao=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new Wr,this.indexArray=new pn,this.programConfigurations=new En(ao,t.layers,t.zoom),this.segments=new zn;};function ko(t,e){return(t/e.tileTotal*(e.end-e.start)+e.start)*(wo-1)}Ao.prototype.populate=function(t,e){for(var r=0,n=t;r<n.length;r+=1){var i=n[r],o=i.feature,a=i.index,s=i.sourceLayerIndex;if(this.layers[0]._featureFilter(new Br(this.zoom),o)){var u=Ln(o);this.addFeature(o,u),e.featureIndex.insert(o,u,a,s,this.index);}}},Ao.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},Ao.prototype.upload=function(t){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,ao),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.programConfigurations.upload(t);},Ao.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());},Ao.prototype.addFeature=function(t,e){for(var r=this.layers[0].layout,n=r.get("line-join").evaluate(t),i=r.get("line-cap"),o=r.get("line-miter-limit"),a=r.get("line-round-limit"),s=0,u=e;s<u.length;s+=1){var l=u[s];this.addLine(l,t,n,i,o,a);}},Ao.prototype.addLine=function(t,e,r,n,i,o){var a=null;e.properties&&e.properties.hasOwnProperty("mapbox_clip_start")&&e.properties.hasOwnProperty("mapbox_clip_end")&&(a={start:e.properties.mapbox_clip_start,end:e.properties.mapbox_clip_end,tileTotal:void 0});for(var s="Polygon"===mo[e.type],u=t.length;u>=2&&t[u-1].equals(t[u-2]);)u--;for(var l=0;l<u-1&&t[l].equals(t[l+1]);)l++;if(!(u<(s?3:2))){a&&(a.tileTotal=function(t,e,r){for(var n,i,o=0,a=e;a<r-1;a++)n=t[a],i=t[a+1],o+=n.dist(i);return o}(t,l,u)),"bevel"===r&&(i=1.05);var p=Pn/(512*this.overscaling)*15,c=t[l],h=this.segments.prepareSegment(10*u,this.layoutVertexArray,this.indexArray);this.distance=0;var f,y,d,v=n,m=s?"butt":n,g=!0,x=void 0,b=void 0,w=void 0,_=void 0;this.e1=this.e2=this.e3=-1,s&&(f=t[u-2],_=c.sub(f)._unit()._perp());for(var A=l;A<u;A++)if(!(b=s&&A===u-1?t[l+1]:t[A+1])||!t[A].equals(b)){_&&(w=_),f&&(x=f),f=t[A],_=b?b.sub(f)._unit()._perp():w;var k=(w=w||_).add(_);0===k.x&&0===k.y||k._unit();var z=k.x*_.x+k.y*_.y,S=0!==z?1/z:1/0,M=z<xo&&x&&b;if(M&&A>l){var V=f.dist(x);if(V>2*p){var B=f.sub(f.sub(x)._mult(p/V)._round());this.distance+=B.dist(x),this.addCurrentVertex(B,this.distance,w.mult(1),0,0,!1,h,a),x=B;}}var C=x&&b,I=C?r:b?v:m;if(C&&"round"===I&&(S<o?I="miter":S<=2&&(I="fakeround")),"miter"===I&&S>i&&(I="bevel"),"bevel"===I&&(S>2&&(I="flipbevel"),S<i&&(I="miter")),x&&(this.distance+=f.dist(x)),"miter"===I)k._mult(S),this.addCurrentVertex(f,this.distance,k,0,0,!1,h,a);else if("flipbevel"===I){if(S>100)k=_.clone().mult(-1);else{var E=w.x*_.y-w.y*_.x>0?-1:1,F=S*w.add(_).mag()/w.sub(_).mag();k._perp()._mult(F*E);}this.addCurrentVertex(f,this.distance,k,0,0,!1,h,a),this.addCurrentVertex(f,this.distance,k.mult(-1),0,0,!1,h,a);}else if("bevel"===I||"fakeround"===I){var P=w.x*_.y-w.y*_.x>0,T=-Math.sqrt(S*S-1);if(P?(d=0,y=T):(y=0,d=T),g||this.addCurrentVertex(f,this.distance,w,y,d,!1,h,a),"fakeround"===I){for(var O=Math.floor(8*(.5-(z-.5))),L=void 0,j=0;j<O;j++)L=_.mult((j+1)/(O+1))._add(w)._unit(),this.addPieSliceVertex(f,this.distance,L,P,h,a);this.addPieSliceVertex(f,this.distance,k,P,h,a);for(var q=O-1;q>=0;q--)L=w.mult((q+1)/(O+1))._add(_)._unit(),this.addPieSliceVertex(f,this.distance,L,P,h,a);}b&&this.addCurrentVertex(f,this.distance,_,-y,-d,!1,h,a);}else"butt"===I?(g||this.addCurrentVertex(f,this.distance,w,0,0,!1,h,a),b&&this.addCurrentVertex(f,this.distance,_,0,0,!1,h,a)):"square"===I?(g||(this.addCurrentVertex(f,this.distance,w,1,1,!1,h,a),this.e1=this.e2=-1),b&&this.addCurrentVertex(f,this.distance,_,-1,-1,!1,h,a)):"round"===I&&(g||(this.addCurrentVertex(f,this.distance,w,0,0,!1,h,a),this.addCurrentVertex(f,this.distance,w,1,1,!0,h,a),this.e1=this.e2=-1),b&&(this.addCurrentVertex(f,this.distance,_,-1,-1,!0,h,a),this.addCurrentVertex(f,this.distance,_,0,0,!1,h,a)));if(M&&A<u-1){var R=f.dist(b);if(R>2*p){var U=f.add(b.sub(f)._mult(p/R)._round());this.distance+=U.dist(f),this.addCurrentVertex(U,this.distance,_.mult(1),0,0,!1,h,a),f=U;}}g=!1;}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,e);}},Ao.prototype.addCurrentVertex=function(t,e,r,n,i,o,a,s){var u,l=this.layoutVertexArray,p=this.indexArray;s&&(e=ko(e,s)),u=r.clone(),n&&u._sub(r.perp()._mult(n)),_o(l,t,u,o,!1,n,e),this.e3=a.vertexLength++,this.e1>=0&&this.e2>=0&&(p.emplaceBack(this.e1,this.e2,this.e3),a.primitiveLength++),this.e1=this.e2,this.e2=this.e3,u=r.mult(-1),i&&u._sub(r.perp()._mult(i)),_o(l,t,u,o,!0,-i,e),this.e3=a.vertexLength++,this.e1>=0&&this.e2>=0&&(p.emplaceBack(this.e1,this.e2,this.e3),a.primitiveLength++),this.e1=this.e2,this.e2=this.e3,e>wo/2&&!s&&(this.distance=0,this.addCurrentVertex(t,this.distance,r,n,i,o,a));},Ao.prototype.addPieSliceVertex=function(t,e,r,n,i,o){r=r.mult(n?-1:1);var a=this.layoutVertexArray,s=this.indexArray;o&&(e=ko(e,o)),_o(a,t,r,!1,n,0,e),this.e3=i.vertexLength++,this.e1>=0&&this.e2>=0&&(s.emplaceBack(this.e1,this.e2,this.e3),i.primitiveLength++),n?this.e2=this.e3:this.e1=this.e3;},hr("LineBucket",Ao,{omit:["layers"]});var zo=new Dr({"line-cap":new jr(E.layout_line["line-cap"]),"line-join":new qr(E.layout_line["line-join"]),"line-miter-limit":new jr(E.layout_line["line-miter-limit"]),"line-round-limit":new jr(E.layout_line["line-round-limit"])}),So={paint:new Dr({"line-opacity":new qr(E.paint_line["line-opacity"]),"line-color":new qr(E.paint_line["line-color"]),"line-translate":new jr(E.paint_line["line-translate"]),"line-translate-anchor":new jr(E.paint_line["line-translate-anchor"]),"line-width":new qr(E.paint_line["line-width"]),"line-gap-width":new qr(E.paint_line["line-gap-width"]),"line-offset":new qr(E.paint_line["line-offset"]),"line-blur":new qr(E.paint_line["line-blur"]),"line-dasharray":new Rr(E.paint_line["line-dasharray"]),"line-pattern":new Rr(E.paint_line["line-pattern"]),"line-gradient":new Ur(E.paint_line["line-gradient"])}),layout:zo},Mo=new(function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.possiblyEvaluate=function(e,r){return r=new Br(Math.floor(r.zoom),{now:r.now,fadeDuration:r.fadeDuration,zoomHistory:r.zoomHistory,transition:r.transition}),t.prototype.possiblyEvaluate.call(this,e,r)},e.prototype.evaluate=function(e,r,n){return r=h({},r,{zoom:Math.floor(r.zoom)}),t.prototype.evaluate.call(this,e,r,n)},e}(qr))(So.paint.properties["line-width"].specification);Mo.useIntegerZoom=!0;var Vo=function(t){function e(e){t.call(this,e,So);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.setPaintProperty=function(e,r,n){t.prototype.setPaintProperty.call(this,e,r,n),"line-gradient"===e&&this._updateGradient();},e.prototype._updateGradient=function(){var t=this._transitionablePaint._values["line-gradient"].value.expression;this.gradient=hi(t,"lineProgress"),this.gradientTexture=null;},e.prototype.recalculate=function(e){t.prototype.recalculate.call(this,e),this.paint._values["line-floorwidth"]=Mo.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,e);},e.prototype.createBucket=function(t){return new Ao(t)},e.prototype.queryRadius=function(t){var e=t,r=Bo(Gn("line-width",this,e),Gn("line-gap-width",this,e)),n=Gn("line-offset",this,e);return r/2+Math.abs(n)+Yn(this.paint.get("line-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,o){var a=Wn(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),i.angle,o),u=o/2*Bo(this.paint.get("line-width").evaluate(e),this.paint.get("line-gap-width").evaluate(e)),l=this.paint.get("line-offset").evaluate(e);return l&&(r=function(t,e){for(var r=[],n=new s(0,0),i=0;i<t.length;i++){for(var o=t[i],a=[],u=0;u<o.length;u++){var l=o[u-1],p=o[u],c=o[u+1],h=0===u?n:p.sub(l)._unit()._perp(),f=u===o.length-1?n:c.sub(p)._unit()._perp(),y=h._add(f)._unit(),d=y.x*f.x+y.y*f.y;y._mult(1/d),a.push(y._mult(e)._add(p));}r.push(a);}return r}(r,l*o)),Dn(a,r,u)},e}(Nr);function Bo(t,e){return e>0?e+2*t:t}var Co=$r([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"}]),Io=$r([{name:"a_projected_pos",components:3,type:"Float32"}],4),Eo=($r([{name:"a_fade_opacity",components:1,type:"Uint32"}],4),$r([{name:"a_placed",components:2,type:"Uint8"}],4)),Fo=($r([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"},{type:"Int16",name:"radius"},{type:"Int16",name:"signedDistanceFromAnchor"}]),$r([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4)),Po=$r([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4);$r([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"hidden"}]),$r([{type:"Float32",name:"offsetX"}]),$r([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]);function To(t,e,r){var n=e.layout.get("text-transform").evaluate(r);return"uppercase"===n?t=t.toLocaleUpperCase():"lowercase"===n&&(t=t.toLocaleLowerCase()),Vr.applyArabicShaping&&(t=Vr.applyArabicShaping(t)),t}var Oo={"!":"︕","#":"＃",$:"＄","%":"％","&":"＆","(":"︵",")":"︶","*":"＊","+":"＋",",":"︐","-":"︲",".":"・","/":"／",":":"︓",";":"︔","<":"︿","=":"＝",">":"﹀","?":"︖","@":"＠","[":"﹇","\\":"＼","]":"﹈","^":"＾",_:"︳","`":"｀","{":"︷","|":"―","}":"︸","~":"～","¢":"￠","£":"￡","¥":"￥","¦":"￤","¬":"￢","¯":"￣","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"￦","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","！":"︕","（":"︵","）":"︶","，":"︐","－":"︲","．":"・","：":"︓","；":"︔","＜":"︿","＞":"﹀","？":"︖","［":"﹇","］":"﹈","＿":"︳","｛":"︷","｜":"―","｝":"︸","｟":"︵","｠":"︶","｡":"︒","｢":"﹁","｣":"﹂"};var Lo=function(t){function e(e,r,n,i){t.call(this,e,r),this.angle=n,void 0!==i&&(this.segment=i);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.clone=function(){return new e(this.x,this.y,this.angle,this.segment)},e}(s);function jo(t,e){var r=e.expression;if("constant"===r.kind)return{functionType:"constant",layoutSize:r.evaluate(new Br(t+1))};if("source"===r.kind)return{functionType:"source"};for(var n=r.zoomStops,i=0;i<n.length&&n[i]<=t;)i++;for(var o=i=Math.max(0,i-1);o<n.length&&n[o]<t+1;)o++;o=Math.min(n.length-1,o);var a={min:n[i],max:n[o]};return"composite"===r.kind?{functionType:"composite",zoomRange:a,propertyValue:e.value}:{functionType:"camera",layoutSize:r.evaluate(new Br(t+1)),zoomRange:a,sizeRange:{min:r.evaluate(new Br(a.min)),max:r.evaluate(new Br(a.max))},propertyValue:e.value}}hr("Anchor",Lo);var qo=vo.VectorTileFeature.types,Ro=[{name:"a_fade_opacity",components:1,type:"Uint8",offset:0}];function Uo(t,e,r,n,i,o,a,s){t.emplaceBack(e,r,Math.round(32*n),Math.round(32*i),o,a,s?s[0]:0,s?s[1]:0);}function Do(t,e,r){t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r);}var No=function(t){this.layoutVertexArray=new Qr,this.indexArray=new pn,this.programConfigurations=t,this.segments=new zn,this.dynamicLayoutVertexArray=new tn,this.opacityVertexArray=new en,this.placedSymbolArray=new mn;};No.prototype.upload=function(t,e){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Co.members),this.indexBuffer=t.createIndexBuffer(this.indexArray,e),this.programConfigurations.upload(t),this.dynamicLayoutVertexBuffer=t.createVertexBuffer(this.dynamicLayoutVertexArray,Io.members,!0),this.opacityVertexBuffer=t.createVertexBuffer(this.opacityVertexArray,Ro,!0),this.opacityVertexBuffer.itemSize=1;},No.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.dynamicLayoutVertexBuffer.destroy(),this.opacityVertexBuffer.destroy());},hr("SymbolBuffers",No);var Zo=function(t,e,r){this.layoutVertexArray=new t,this.layoutAttributes=e,this.indexArray=new r,this.segments=new zn,this.collisionVertexArray=new on;};Zo.prototype.upload=function(t){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=t.createVertexBuffer(this.collisionVertexArray,Eo.members,!0);},Zo.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy());},hr("CollisionBuffers",Zo);var Ko=function(t){this.collisionBoxArray=t.collisionBoxArray,this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.pixelRatio=t.pixelRatio,this.sourceLayerIndex=t.sourceLayerIndex;var e=this.layers[0]._unevaluatedLayout._values;this.textSizeData=jo(this.zoom,e["text-size"]),this.iconSizeData=jo(this.zoom,e["icon-size"]);var r=this.layers[0].layout;this.sortFeaturesByY=r.get("text-allow-overlap")||r.get("icon-allow-overlap")||r.get("text-ignore-placement")||r.get("icon-ignore-placement");};Ko.prototype.createArrays=function(){this.text=new No(new En(Co.members,this.layers,this.zoom,function(t){return/^text/.test(t)})),this.icon=new No(new En(Co.members,this.layers,this.zoom,function(t){return/^icon/.test(t)})),this.collisionBox=new Zo(nn,Fo.members,cn),this.collisionCircle=new Zo(nn,Po.members,pn),this.glyphOffsetArray=new xn,this.lineVertexArray=new wn;},Ko.prototype.populate=function(t,e){var r=this.layers[0],n=r.layout,i=n.get("text-font"),o=n.get("text-field"),a=n.get("icon-image"),s=("constant"!==o.value.kind||o.value.value.length>0)&&("constant"!==i.value.kind||i.value.value.length>0),u="constant"!==a.value.kind||a.value.value&&a.value.value.length>0;if(this.features=[],s||u){for(var l=e.iconDependencies,p=e.glyphDependencies,c=new Br(this.zoom),h=0,f=t;h<f.length;h+=1){var y=f[h],d=y.feature,v=y.index,m=y.sourceLayerIndex;if(r._featureFilter(c,d)){var g=void 0;s&&(g=To(g=r.getValueAndResolveTokens("text-field",d),r,d));var x=void 0;if(u&&(x=r.getValueAndResolveTokens("icon-image",d)),g||x){var b={text:g,icon:x,index:v,sourceLayerIndex:m,geometry:Ln(d),properties:d.properties,type:qo[d.type]};if(void 0!==d.id&&(b.id=d.id),this.features.push(b),x&&(l[x]=!0),g)for(var w=i.evaluate(d).join(","),_=p[w]=p[w]||{},A="map"===n.get("text-rotation-alignment")&&"line"===n.get("symbol-placement"),k=gr(g),z=0;z<g.length;z++)if(_[g.charCodeAt(z)]=!0,A&&k){var S=Oo[g.charAt(z)];S&&(_[S.charCodeAt(0)]=!0);}}}}"line"===n.get("symbol-placement")&&(this.features=function(t){var e={},r={},n=[],i=0;function o(e){n.push(t[e]),i++;}function a(t,e,i){var o=r[t];return delete r[t],r[e]=o,n[o].geometry[0].pop(),n[o].geometry[0]=n[o].geometry[0].concat(i[0]),o}function s(t,r,i){var o=e[r];return delete e[r],e[t]=o,n[o].geometry[0].shift(),n[o].geometry[0]=i[0].concat(n[o].geometry[0]),o}function u(t,e,r){var n=r?e[0][e[0].length-1]:e[0][0];return t+":"+n.x+":"+n.y}for(var l=0;l<t.length;l++){var p=t[l],c=p.geometry,h=p.text;if(h){var f=u(h,c),y=u(h,c,!0);if(f in r&&y in e&&r[f]!==e[y]){var d=s(f,y,c),v=a(f,y,n[d].geometry);delete e[f],delete r[y],r[u(h,n[v].geometry,!0)]=v,n[d].geometry=null;}else f in r?a(f,y,c):y in e?s(f,y,c):(o(l),e[f]=i-1,r[y]=i-1);}else o(l);}return n.filter(function(t){return t.geometry})}(this.features));}},Ko.prototype.isEmpty=function(){return 0===this.symbolInstances.length},Ko.prototype.upload=function(t){this.text.upload(t,this.sortFeaturesByY),this.icon.upload(t,this.sortFeaturesByY),this.collisionBox.upload(t),this.collisionCircle.upload(t);},Ko.prototype.destroy=function(){this.text.destroy(),this.icon.destroy(),this.collisionBox.destroy(),this.collisionCircle.destroy();},Ko.prototype.addToLineVertexArray=function(t,e){var r=this.lineVertexArray.length;if(void 0!==t.segment){for(var n=t.dist(e[t.segment+1]),i=t.dist(e[t.segment]),o={},a=t.segment+1;a<e.length;a++)o[a]={x:e[a].x,y:e[a].y,tileUnitDistanceFromAnchor:n},a<e.length-1&&(n+=e[a+1].dist(e[a]));for(var s=t.segment||0;s>=0;s--)o[s]={x:e[s].x,y:e[s].y,tileUnitDistanceFromAnchor:i},s>0&&(i+=e[s-1].dist(e[s]));for(var u=0;u<e.length;u++){var l=o[u];this.lineVertexArray.emplaceBack(l.x,l.y,l.tileUnitDistanceFromAnchor);}}return{lineStartIndex:r,lineLength:this.lineVertexArray.length-r}},Ko.prototype.addSymbols=function(t,e,r,n,i,o,a,s,u,l){for(var p=t.indexArray,c=t.layoutVertexArray,h=t.dynamicLayoutVertexArray,f=t.segments.prepareSegment(4*e.length,t.layoutVertexArray,t.indexArray),y=this.glyphOffsetArray.length,d=f.vertexLength,v=0,m=e;v<m.length;v+=1){var g=m[v],x=g.tl,b=g.tr,w=g.bl,_=g.br,A=g.tex,k=f.vertexLength,z=g.glyphOffset[1];Uo(c,s.x,s.y,x.x,z+x.y,A.x,A.y,r),Uo(c,s.x,s.y,b.x,z+b.y,A.x+A.w,A.y,r),Uo(c,s.x,s.y,w.x,z+w.y,A.x,A.y+A.h,r),Uo(c,s.x,s.y,_.x,z+_.y,A.x+A.w,A.y+A.h,r),Do(h,s,0),p.emplaceBack(k,k+1,k+2),p.emplaceBack(k+1,k+2,k+3),f.vertexLength+=4,f.primitiveLength+=2,this.glyphOffsetArray.emplaceBack(g.glyphOffset[0]);}t.placedSymbolArray.emplaceBack(s.x,s.y,y,this.glyphOffsetArray.length-y,d,u,l,s.segment,r?r[0]:0,r?r[1]:0,n[0],n[1],a,!1),t.programConfigurations.populatePaintArrays(t.layoutVertexArray.length,o);},Ko.prototype._addCollisionDebugVertex=function(t,e,r,n,i){return e.emplaceBack(0,0),t.emplaceBack(r.x,r.y,n.x,n.y,Math.round(i.x),Math.round(i.y))},Ko.prototype.addCollisionDebugVertices=function(t,e,r,n,i,o,a,u){var l=i.segments.prepareSegment(4,i.layoutVertexArray,i.indexArray),p=l.vertexLength,c=i.layoutVertexArray,h=i.collisionVertexArray;if(this._addCollisionDebugVertex(c,h,o,a.anchor,new s(t,e)),this._addCollisionDebugVertex(c,h,o,a.anchor,new s(r,e)),this._addCollisionDebugVertex(c,h,o,a.anchor,new s(r,n)),this._addCollisionDebugVertex(c,h,o,a.anchor,new s(t,n)),l.vertexLength+=4,u){var f=i.indexArray;f.emplaceBack(p,p+1,p+2),f.emplaceBack(p,p+2,p+3),l.primitiveLength+=2;}else{var y=i.indexArray;y.emplaceBack(p,p+1),y.emplaceBack(p+1,p+2),y.emplaceBack(p+2,p+3),y.emplaceBack(p+3,p),l.primitiveLength+=4;}},Ko.prototype.generateCollisionDebugBuffers=function(){for(var t=0,e=this.symbolInstances;t<e.length;t+=1){var r=e[t];r.textCollisionFeature={boxStartIndex:r.textBoxStartIndex,boxEndIndex:r.textBoxEndIndex},r.iconCollisionFeature={boxStartIndex:r.iconBoxStartIndex,boxEndIndex:r.iconBoxEndIndex};for(var n=0;n<2;n++){var i=r[0===n?"textCollisionFeature":"iconCollisionFeature"];if(i)for(var o=i.boxStartIndex;o<i.boxEndIndex;o++){var a=this.collisionBoxArray.get(o),s=a.x1,u=a.y1,l=a.x2,p=a.y2,c=a.radius>0;this.addCollisionDebugVertices(s,u,l,p,c?this.collisionCircle:this.collisionBox,a.anchorPoint,r,c);}}}},Ko.prototype.deserializeCollisionBoxes=function(t,e,r,n,i){for(var o={},a=e;a<r;a++){var s=t.get(a);if(0===s.radius){o.textBox={x1:s.x1,y1:s.y1,x2:s.x2,y2:s.y2,anchorPointX:s.anchorPointX,anchorPointY:s.anchorPointY},o.textFeatureIndex=s.featureIndex;break}o.textCircles||(o.textCircles=[],o.textFeatureIndex=s.featureIndex);o.textCircles.push(s.anchorPointX,s.anchorPointY,s.radius,s.signedDistanceFromAnchor,1);}for(var u=n;u<i;u++){var l=t.get(u);if(0===l.radius){o.iconBox={x1:l.x1,y1:l.y1,x2:l.x2,y2:l.y2,anchorPointX:l.anchorPointX,anchorPointY:l.anchorPointY},o.iconFeatureIndex=l.featureIndex;break}}return o},Ko.prototype.hasTextData=function(){return this.text.segments.get().length>0},Ko.prototype.hasIconData=function(){return this.icon.segments.get().length>0},Ko.prototype.hasCollisionBoxData=function(){return this.collisionBox.segments.get().length>0},Ko.prototype.hasCollisionCircleData=function(){return this.collisionCircle.segments.get().length>0},Ko.prototype.sortFeatures=function(t){var e=this;if(this.sortFeaturesByY&&this.sortedAngle!==t&&(this.sortedAngle=t,!(this.text.segments.get().length>1||this.icon.segments.get().length>1))){for(var r=[],n=0;n<this.symbolInstances.length;n++)r.push(n);var i=Math.sin(t),o=Math.cos(t);r.sort(function(t,r){var n=e.symbolInstances[t],a=e.symbolInstances[r];return(i*n.anchor.x+o*n.anchor.y|0)-(i*a.anchor.x+o*a.anchor.y|0)||a.featureIndex-n.featureIndex}),this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(var a=0,s=r;a<s.length;a+=1){var u=s[a],l=e.symbolInstances[u];e.featureSortOrder.push(l.featureIndex);for(var p=0,c=l.placedTextSymbolIndices;p<c.length;p+=1)for(var h=c[p],f=e.text.placedSymbolArray.get(h),y=f.vertexStartIndex+4*f.numGlyphs,d=f.vertexStartIndex;d<y;d+=4)e.text.indexArray.emplaceBack(d,d+1,d+2),e.text.indexArray.emplaceBack(d+1,d+2,d+3);var v=e.icon.placedSymbolArray.get(u);if(v.numGlyphs){var m=v.vertexStartIndex;e.icon.indexArray.emplaceBack(m,m+1,m+2),e.icon.indexArray.emplaceBack(m+1,m+2,m+3);}}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray);}},hr("SymbolBucket",Ko,{omit:["layers","collisionBoxArray","features","compareText"],shallow:["symbolInstances"]}),Ko.MAX_GLYPHS=65535,Ko.addDynamicAttributes=Do;var Jo=new Dr({"symbol-placement":new jr(E.layout_symbol["symbol-placement"]),"symbol-spacing":new jr(E.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new jr(E.layout_symbol["symbol-avoid-edges"]),"icon-allow-overlap":new jr(E.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new jr(E.layout_symbol["icon-ignore-placement"]),"icon-optional":new jr(E.layout_symbol["icon-optional"]),"icon-rotation-alignment":new jr(E.layout_symbol["icon-rotation-alignment"]),"icon-size":new qr(E.layout_symbol["icon-size"]),"icon-text-fit":new jr(E.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new jr(E.layout_symbol["icon-text-fit-padding"]),"icon-image":new qr(E.layout_symbol["icon-image"]),"icon-rotate":new qr(E.layout_symbol["icon-rotate"]),"icon-padding":new jr(E.layout_symbol["icon-padding"]),"icon-keep-upright":new jr(E.layout_symbol["icon-keep-upright"]),"icon-offset":new qr(E.layout_symbol["icon-offset"]),"icon-anchor":new qr(E.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new jr(E.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new jr(E.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new jr(E.layout_symbol["text-rotation-alignment"]),"text-field":new qr(E.layout_symbol["text-field"]),"text-font":new qr(E.layout_symbol["text-font"]),"text-size":new qr(E.layout_symbol["text-size"]),"text-max-width":new qr(E.layout_symbol["text-max-width"]),"text-line-height":new jr(E.layout_symbol["text-line-height"]),"text-letter-spacing":new qr(E.layout_symbol["text-letter-spacing"]),"text-justify":new qr(E.layout_symbol["text-justify"]),"text-anchor":new qr(E.layout_symbol["text-anchor"]),"text-max-angle":new jr(E.layout_symbol["text-max-angle"]),"text-rotate":new qr(E.layout_symbol["text-rotate"]),"text-padding":new jr(E.layout_symbol["text-padding"]),"text-keep-upright":new jr(E.layout_symbol["text-keep-upright"]),"text-transform":new qr(E.layout_symbol["text-transform"]),"text-offset":new qr(E.layout_symbol["text-offset"]),"text-allow-overlap":new jr(E.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new jr(E.layout_symbol["text-ignore-placement"]),"text-optional":new jr(E.layout_symbol["text-optional"])}),$o={paint:new Dr({"icon-opacity":new qr(E.paint_symbol["icon-opacity"]),"icon-color":new qr(E.paint_symbol["icon-color"]),"icon-halo-color":new qr(E.paint_symbol["icon-halo-color"]),"icon-halo-width":new qr(E.paint_symbol["icon-halo-width"]),"icon-halo-blur":new qr(E.paint_symbol["icon-halo-blur"]),"icon-translate":new jr(E.paint_symbol["icon-translate"]),"icon-translate-anchor":new jr(E.paint_symbol["icon-translate-anchor"]),"text-opacity":new qr(E.paint_symbol["text-opacity"]),"text-color":new qr(E.paint_symbol["text-color"]),"text-halo-color":new qr(E.paint_symbol["text-halo-color"]),"text-halo-width":new qr(E.paint_symbol["text-halo-width"]),"text-halo-blur":new qr(E.paint_symbol["text-halo-blur"]),"text-translate":new jr(E.paint_symbol["text-translate"]),"text-translate-anchor":new jr(E.paint_symbol["text-translate-anchor"])}),layout:Jo},Ho=function(t){function e(e){t.call(this,e,$o);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.recalculate=function(e){t.prototype.recalculate.call(this,e),"auto"===this.layout.get("icon-rotation-alignment")&&("line"===this.layout.get("symbol-placement")?this.layout._values["icon-rotation-alignment"]="map":this.layout._values["icon-rotation-alignment"]="viewport"),"auto"===this.layout.get("text-rotation-alignment")&&("line"===this.layout.get("symbol-placement")?this.layout._values["text-rotation-alignment"]="map":this.layout._values["text-rotation-alignment"]="viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]=this.layout.get("text-rotation-alignment")),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment"));},e.prototype.getValueAndResolveTokens=function(t,e){var r,n=this.layout.get(t).evaluate(e),i=this._unevaluatedLayout._values[t];return i.isDataDriven()||be(i.value)?n:(r=e.properties,n.replace(/{([^{}]+)}/g,function(t,e){return e in r?String(r[e]):""}))},e.prototype.createBucket=function(t){return new Ko(t)},e.prototype.queryRadius=function(){return 0},e.prototype.queryIntersectsFeature=function(){return!1},e}(Nr),Xo={paint:new Dr({"background-color":new jr(E.paint_background["background-color"]),"background-pattern":new Rr(E.paint_background["background-pattern"]),"background-opacity":new jr(E.paint_background["background-opacity"])})},Go=function(t){function e(e){t.call(this,e,Xo);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(Nr),Yo={paint:new Dr({"raster-opacity":new jr(E.paint_raster["raster-opacity"]),"raster-hue-rotate":new jr(E.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new jr(E.paint_raster["raster-brightness-min"]),"raster-brightness-max":new jr(E.paint_raster["raster-brightness-max"]),"raster-saturation":new jr(E.paint_raster["raster-saturation"]),"raster-contrast":new jr(E.paint_raster["raster-contrast"]),"raster-fade-duration":new jr(E.paint_raster["raster-fade-duration"])})},Wo={circle:ni,heatmap:fi,hillshade:di,fill:Yi,"fill-extrusion":oo,line:Vo,symbol:Ho,background:Go,raster:function(t){function e(e){t.call(this,e,Yo);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(Nr)};var Qo=n(function(t,e){t.exports=function(){function t(t,e,r){r=r||{},this.w=t||64,this.h=e||64,this.autoResize=!!r.autoResize,this.shelves=[],this.freebins=[],this.stats={},this.bins={},this.maxId=0;}function e(t,e,r){this.x=0,this.y=t,this.w=this.free=e,this.h=r;}return t.prototype.pack=function(t,e){t=[].concat(t),e=e||{};for(var r,n,i,o,a=[],s=0;s<t.length;s++)if(r=t[s].w||t[s].width,n=t[s].h||t[s].height,i=t[s].id,r&&n){if(!(o=this.packOne(r,n,i)))continue;e.inPlace&&(t[s].x=o.x,t[s].y=o.y,t[s].id=o.id),a.push(o);}return this.shrink(),a},t.prototype.packOne=function(t,r,n){var i,o,a,s,u,l,p,c,h={freebin:-1,shelf:-1,waste:1/0},f=0;if("string"==typeof n||"number"==typeof n){if(i=this.getBin(n))return this.ref(i),i;"number"==typeof n&&(this.maxId=Math.max(n,this.maxId));}else n=++this.maxId;for(s=0;s<this.freebins.length;s++){if(r===(i=this.freebins[s]).maxh&&t===i.maxw)return this.allocFreebin(s,t,r,n);r>i.maxh||t>i.maxw||r<=i.maxh&&t<=i.maxw&&(a=i.maxw*i.maxh-t*r)<h.waste&&(h.waste=a,h.freebin=s);}for(s=0;s<this.shelves.length;s++)if(f+=(o=this.shelves[s]).h,!(t>o.free)){if(r===o.h)return this.allocShelf(s,t,r,n);r>o.h||r<o.h&&(a=(o.h-r)*t)<h.waste&&(h.freebin=-1,h.waste=a,h.shelf=s);}return-1!==h.freebin?this.allocFreebin(h.freebin,t,r,n):-1!==h.shelf?this.allocShelf(h.shelf,t,r,n):r<=this.h-f&&t<=this.w?(o=new e(f,this.w,r),this.allocShelf(this.shelves.push(o)-1,t,r,n)):this.autoResize?(u=l=this.h,((p=c=this.w)<=u||t>p)&&(c=2*Math.max(t,p)),(u<p||r>u)&&(l=2*Math.max(r,u)),this.resize(c,l),this.packOne(t,r,n)):null},t.prototype.allocFreebin=function(t,e,r,n){var i=this.freebins.splice(t,1)[0];return i.id=n,i.w=e,i.h=r,i.refcount=0,this.bins[n]=i,this.ref(i),i},t.prototype.allocShelf=function(t,e,r,n){var i=this.shelves[t].alloc(e,r,n);return this.bins[n]=i,this.ref(i),i},t.prototype.shrink=function(){if(this.shelves.length>0){for(var t=0,e=0,r=0;r<this.shelves.length;r++){var n=this.shelves[r];e+=n.h,t=Math.max(n.w-n.free,t);}this.resize(t,e);}},t.prototype.getBin=function(t){return this.bins[t]},t.prototype.ref=function(t){if(1==++t.refcount){var e=t.h;this.stats[e]=1+(0|this.stats[e]);}return t.refcount},t.prototype.unref=function(t){return 0===t.refcount?0:(0==--t.refcount&&(this.stats[t.h]--,delete this.bins[t.id],this.freebins.push(t)),t.refcount)},t.prototype.clear=function(){this.shelves=[],this.freebins=[],this.stats={},this.bins={},this.maxId=0;},t.prototype.resize=function(t,e){this.w=t,this.h=e;for(var r=0;r<this.shelves.length;r++)this.shelves[r].resize(t);return!0},e.prototype.alloc=function(t,e,r){if(t>this.free||e>this.h)return null;var n=this.x;return this.x+=t,this.free-=t,new function(t,e,r,n,i,o,a){this.id=t,this.x=e,this.y=r,this.w=n,this.h=i,this.maxw=o||n,this.maxh=a||i,this.refcount=0;}(r,n,this.y,t,e,t,this.h)},e.prototype.resize=function(t){return this.free+=t-this.w,this.w=t,!0},t}();}),ta=function(t,e){var r=e.pixelRatio;this.paddedRect=t,this.pixelRatio=r;},ea={tl:{configurable:!0},br:{configurable:!0},displaySize:{configurable:!0}};ea.tl.get=function(){return[this.paddedRect.x+1,this.paddedRect.y+1]},ea.br.get=function(){return[this.paddedRect.x+this.paddedRect.w-1,this.paddedRect.y+this.paddedRect.h-1]},ea.displaySize.get=function(){return[(this.paddedRect.w-2)/this.pixelRatio,(this.paddedRect.h-2)/this.pixelRatio]},Object.defineProperties(ta.prototype,ea);var ra=function(t){var e=new pi({width:0,height:0}),r={},n=new Qo(0,0,{autoResize:!0});for(var i in t){var o=t[i],a=n.packOne(o.data.width+2,o.data.height+2);e.resize({width:n.w,height:n.h}),pi.copy(o.data,e,{x:0,y:0},{x:a.x+1,y:a.y+1},o.data),r[i]=new ta(a,o);}n.shrink(),e.resize({width:n.w,height:n.h}),this.image=e,this.positions=r;};hr("ImagePosition",ta),hr("ImageAtlas",ra);var na=function(t,e,r,n,i){var o,a,s=8*i-n-1,u=(1<<s)-1,l=u>>1,p=-7,c=r?i-1:0,h=r?-1:1,f=t[e+c];for(c+=h,o=f&(1<<-p)-1,f>>=-p,p+=s;p>0;o=256*o+t[e+c],c+=h,p-=8);for(a=o&(1<<-p)-1,o>>=-p,p+=n;p>0;a=256*a+t[e+c],c+=h,p-=8);if(0===o)o=1-l;else{if(o===u)return a?NaN:1/0*(f?-1:1);a+=Math.pow(2,n),o-=l;}return(f?-1:1)*a*Math.pow(2,o-n)},ia=function(t,e,r,n,i,o){var a,s,u,l=8*o-i-1,p=(1<<l)-1,c=p>>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:o-1,y=n?1:-1,d=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,a=p):(a=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-a))<1&&(a--,u*=2),(e+=a+c>=1?h/u:h*Math.pow(2,1-c))*u>=2&&(a++,u/=2),a+c>=p?(s=0,a=p):a+c>=1?(s=(e*u-1)*Math.pow(2,i),a+=c):(s=e*Math.pow(2,c-1)*Math.pow(2,i),a=0));i>=8;t[r+f]=255&s,f+=y,s/=256,i-=8);for(a=a<<i|s,l+=i;l>0;t[r+f]=255&a,f+=y,a/=256,l-=8);t[r+f-y]|=128*d;},oa=aa;function aa(t){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(t)?t:new Uint8Array(t||0),this.pos=0,this.type=0,this.length=this.buf.length;}aa.Varint=0,aa.Fixed64=1,aa.Bytes=2,aa.Fixed32=5;function sa(t){return t.type===aa.Bytes?t.readVarint()+t.pos:t.pos+1}function ua(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function la(t,e,r){var n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.ceil(Math.log(e)/(7*Math.LN2));r.realloc(n);for(var i=r.pos-1;i>=t;i--)r.buf[i+n]=r.buf[i];}function pa(t,e){for(var r=0;r<t.length;r++)e.writeVarint(t[r]);}function ca(t,e){for(var r=0;r<t.length;r++)e.writeSVarint(t[r]);}function ha(t,e){for(var r=0;r<t.length;r++)e.writeFloat(t[r]);}function fa(t,e){for(var r=0;r<t.length;r++)e.writeDouble(t[r]);}function ya(t,e){for(var r=0;r<t.length;r++)e.writeBoolean(t[r]);}function da(t,e){for(var r=0;r<t.length;r++)e.writeFixed32(t[r]);}function va(t,e){for(var r=0;r<t.length;r++)e.writeSFixed32(t[r]);}function ma(t,e){for(var r=0;r<t.length;r++)e.writeFixed64(t[r]);}function ga(t,e){for(var r=0;r<t.length;r++)e.writeSFixed64(t[r]);}function xa(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16)+16777216*t[e+3]}function ba(t,e,r){t[r]=e,t[r+1]=e>>>8,t[r+2]=e>>>16,t[r+3]=e>>>24;}function wa(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16)+(t[e+3]<<24)}aa.prototype={destroy:function(){this.buf=null;},readFields:function(t,e,r){for(r=r||this.length;this.pos<r;){var n=this.readVarint(),i=n>>3,o=this.pos;this.type=7&n,t(i,e,this),this.pos===o&&this.skip(n);}return e},readMessage:function(t,e){return this.readFields(t,e,this.readVarint()+this.pos)},readFixed32:function(){var t=xa(this.buf,this.pos);return this.pos+=4,t},readSFixed32:function(){var t=wa(this.buf,this.pos);return this.pos+=4,t},readFixed64:function(){var t=xa(this.buf,this.pos)+4294967296*xa(this.buf,this.pos+4);return this.pos+=8,t},readSFixed64:function(){var t=xa(this.buf,this.pos)+4294967296*wa(this.buf,this.pos+4);return this.pos+=8,t},readFloat:function(){var t=na(this.buf,this.pos,!0,23,4);return this.pos+=4,t},readDouble:function(){var t=na(this.buf,this.pos,!0,52,8);return this.pos+=8,t},readVarint:function(t){var e,r,n=this.buf;return e=127&(r=n[this.pos++]),r<128?e:(e|=(127&(r=n[this.pos++]))<<7,r<128?e:(e|=(127&(r=n[this.pos++]))<<14,r<128?e:(e|=(127&(r=n[this.pos++]))<<21,r<128?e:function(t,e,r){var n,i,o=r.buf;if(i=o[r.pos++],n=(112&i)>>4,i<128)return ua(t,n,e);if(i=o[r.pos++],n|=(127&i)<<3,i<128)return ua(t,n,e);if(i=o[r.pos++],n|=(127&i)<<10,i<128)return ua(t,n,e);if(i=o[r.pos++],n|=(127&i)<<17,i<128)return ua(t,n,e);if(i=o[r.pos++],n|=(127&i)<<24,i<128)return ua(t,n,e);if(i=o[r.pos++],n|=(1&i)<<31,i<128)return ua(t,n,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(r=n[this.pos]))<<28,t,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var t=this.readVarint();return t%2==1?(t+1)/-2:t/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var t=this.readVarint()+this.pos,e=function(t,e,r){var n="",i=e;for(;i<r;){var o,a,s,u=t[i],l=null,p=u>239?4:u>223?3:u>191?2:1;if(i+p>r)break;1===p?u<128&&(l=u):2===p?128==(192&(o=t[i+1]))&&(l=(31&u)<<6|63&o)<=127&&(l=null):3===p?(o=t[i+1],a=t[i+2],128==(192&o)&&128==(192&a)&&((l=(15&u)<<12|(63&o)<<6|63&a)<=2047||l>=55296&&l<=57343)&&(l=null)):4===p&&(o=t[i+1],a=t[i+2],s=t[i+3],128==(192&o)&&128==(192&a)&&128==(192&s)&&((l=(15&u)<<18|(63&o)<<12|(63&a)<<6|63&s)<=65535||l>=1114112)&&(l=null)),null===l?(l=65533,p=1):l>65535&&(l-=65536,n+=String.fromCharCode(l>>>10&1023|55296),l=56320|1023&l),n+=String.fromCharCode(l),i+=p;}return n}(this.buf,this.pos,t);return this.pos=t,e},readBytes:function(){var t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e},readPackedVarint:function(t,e){var r=sa(this);for(t=t||[];this.pos<r;)t.push(this.readVarint(e));return t},readPackedSVarint:function(t){var e=sa(this);for(t=t||[];this.pos<e;)t.push(this.readSVarint());return t},readPackedBoolean:function(t){var e=sa(this);for(t=t||[];this.pos<e;)t.push(this.readBoolean());return t},readPackedFloat:function(t){var e=sa(this);for(t=t||[];this.pos<e;)t.push(this.readFloat());return t},readPackedDouble:function(t){var e=sa(this);for(t=t||[];this.pos<e;)t.push(this.readDouble());return t},readPackedFixed32:function(t){var e=sa(this);for(t=t||[];this.pos<e;)t.push(this.readFixed32());return t},readPackedSFixed32:function(t){var e=sa(this);for(t=t||[];this.pos<e;)t.push(this.readSFixed32());return t},readPackedFixed64:function(t){var e=sa(this);for(t=t||[];this.pos<e;)t.push(this.readFixed64());return t},readPackedSFixed64:function(t){var e=sa(this);for(t=t||[];this.pos<e;)t.push(this.readSFixed64());return t},skip:function(t){var e=7&t;if(e===aa.Varint)for(;this.buf[this.pos++]>127;);else if(e===aa.Bytes)this.pos=this.readVarint()+this.pos;else if(e===aa.Fixed32)this.pos+=4;else{if(e!==aa.Fixed64)throw new Error("Unimplemented type: "+e);this.pos+=8;}},writeTag:function(t,e){this.writeVarint(t<<3|e);},realloc:function(t){for(var e=this.length||16;e<this.pos+t;)e*=2;if(e!==this.length){var r=new Uint8Array(e);r.set(this.buf),this.buf=r,this.length=e;}},finish:function(){return this.length=this.pos,this.pos=0,this.buf.subarray(0,this.length)},writeFixed32:function(t){this.realloc(4),ba(this.buf,t,this.pos),this.pos+=4;},writeSFixed32:function(t){this.realloc(4),ba(this.buf,t,this.pos),this.pos+=4;},writeFixed64:function(t){this.realloc(8),ba(this.buf,-1&t,this.pos),ba(this.buf,Math.floor(t*(1/4294967296)),this.pos+4),this.pos+=8;},writeSFixed64:function(t){this.realloc(8),ba(this.buf,-1&t,this.pos),ba(this.buf,Math.floor(t*(1/4294967296)),this.pos+4),this.pos+=8;},writeVarint:function(t){(t=+t||0)>268435455||t<0?function(t,e){var r,n;t>=0?(r=t%4294967296|0,n=t/4294967296|0):(n=~(-t/4294967296),4294967295^(r=~(-t%4294967296))?r=r+1|0:(r=0,n=n+1|0));if(t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos]=127&t;}(r,0,e),function(t,e){var r=(7&t)<<4;if(e.buf[e.pos++]|=r|((t>>>=3)?128:0),!t)return;if(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),!t)return;if(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),!t)return;if(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),!t)return;if(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),!t)return;e.buf[e.pos++]=127&t;}(n,e);}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))));},writeSVarint:function(t){this.writeVarint(t<0?2*-t-1:2*t);},writeBoolean:function(t){this.writeVarint(Boolean(t));},writeString:function(t){t=String(t),this.realloc(4*t.length),this.pos++;var e=this.pos;this.pos=function(t,e,r){for(var n,i,o=0;o<e.length;o++){if((n=e.charCodeAt(o))>55295&&n<57344){if(!i){n>56319||o+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null;}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128);}return r}(this.buf,t,this.pos);var r=this.pos-e;r>=128&&la(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r;},writeFloat:function(t){this.realloc(4),ia(this.buf,t,this.pos,!0,23,4),this.pos+=4;},writeDouble:function(t){this.realloc(8),ia(this.buf,t,this.pos,!0,52,8),this.pos+=8;},writeBytes:function(t){var e=t.length;this.writeVarint(e),this.realloc(e);for(var r=0;r<e;r++)this.buf[this.pos++]=t[r];},writeRawMessage:function(t,e){this.pos++;var r=this.pos;t(e,this);var n=this.pos-r;n>=128&&la(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n;},writeMessage:function(t,e,r){this.writeTag(t,aa.Bytes),this.writeRawMessage(e,r);},writePackedVarint:function(t,e){this.writeMessage(t,pa,e);},writePackedSVarint:function(t,e){this.writeMessage(t,ca,e);},writePackedBoolean:function(t,e){this.writeMessage(t,ya,e);},writePackedFloat:function(t,e){this.writeMessage(t,ha,e);},writePackedDouble:function(t,e){this.writeMessage(t,fa,e);},writePackedFixed32:function(t,e){this.writeMessage(t,da,e);},writePackedSFixed32:function(t,e){this.writeMessage(t,va,e);},writePackedFixed64:function(t,e){this.writeMessage(t,ma,e);},writePackedSFixed64:function(t,e){this.writeMessage(t,ga,e);},writeBytesField:function(t,e){this.writeTag(t,aa.Bytes),this.writeBytes(e);},writeFixed32Field:function(t,e){this.writeTag(t,aa.Fixed32),this.writeFixed32(e);},writeSFixed32Field:function(t,e){this.writeTag(t,aa.Fixed32),this.writeSFixed32(e);},writeFixed64Field:function(t,e){this.writeTag(t,aa.Fixed64),this.writeFixed64(e);},writeSFixed64Field:function(t,e){this.writeTag(t,aa.Fixed64),this.writeSFixed64(e);},writeVarintField:function(t,e){this.writeTag(t,aa.Varint),this.writeVarint(e);},writeSVarintField:function(t,e){this.writeTag(t,aa.Varint),this.writeSVarint(e);},writeStringField:function(t,e){this.writeTag(t,aa.Bytes),this.writeString(e);},writeFloatField:function(t,e){this.writeTag(t,aa.Fixed32),this.writeFloat(e);},writeDoubleField:function(t,e){this.writeTag(t,aa.Fixed64),this.writeDouble(e);},writeBooleanField:function(t,e){this.writeVarintField(t,Boolean(e));}};var _a=3;function Aa(t,e,r){1===t&&r.readMessage(ka,e);}function ka(t,e,r){if(3===t){var n=r.readMessage(za,{}),i=n.id,o=n.bitmap,a=n.width,s=n.height,u=n.left,l=n.top,p=n.advance;e.push({id:i,bitmap:new li({width:a+2*_a,height:s+2*_a},o),metrics:{width:a,height:s,left:u,top:l,advance:p}});}}function za(t,e,r){1===t?e.id=r.readVarint():2===t?e.bitmap=r.readBytes():3===t?e.width=r.readVarint():4===t?e.height=r.readVarint():5===t?e.left=r.readSVarint():6===t?e.top=r.readSVarint():7===t&&(e.advance=r.readVarint());}var Sa=_a,Ma=function(t,e,r){this.target=t,this.parent=e,this.mapId=r,this.callbacks={},this.callbackID=0,y(["receive"],this),this.target.addEventListener("message",this.receive,!1);};Ma.prototype.send=function(t,e,r,n){var i=r?this.mapId+":"+this.callbackID++:null;r&&(this.callbacks[i]=r);var o=[];this.target.postMessage({targetMapId:n,sourceMapId:this.mapId,type:t,id:String(i),data:yr(e,o)},o);},Ma.prototype.receive=function(t){var e,r=this,n=t.data,i=n.id;if(!n.targetMapId||this.mapId===n.targetMapId){var o=function(t,e){var n=[];r.target.postMessage({sourceMapId:r.mapId,type:"<response>",id:String(i),error:t?yr(t):null,data:yr(e,n)},n);};if("<response>"===n.type)e=this.callbacks[n.id],delete this.callbacks[n.id],e&&n.error?e(dr(n.error)):e&&e(null,dr(n.data));else if(void 0!==n.id&&this.parent[n.type])this.parent[n.type](n.sourceMapId,dr(n.data),o);else if(void 0!==n.id&&this.parent.getWorkerSource){var a=n.type.split(".");this.parent.getWorkerSource(n.sourceMapId,a[0],a[1])[a[2]](dr(n.data),o);}else this.parent[n.type](dr(n.data));}},Ma.prototype.remove=function(){this.target.removeEventListener("message",this.receive,!1);};var Va=r(n(function(t,e){!function(t){function e(t,e,n){e=Math.pow(2,n)-e-1;var i=r(256*t,256*e,n),o=r(256*(t+1),256*(e+1),n);return i[0]+","+i[1]+","+o[0]+","+o[1]}function r(t,e,r){var n=2*Math.PI*6378137/256/Math.pow(2,r),i=t*n-2*Math.PI*6378137/2,o=e*n-2*Math.PI*6378137/2;return[i,o]}t.getURL=function(t,r,n,i,o,a){return a=a||{},t+"?"+["bbox="+e(n,i,o),"format="+(a.format||"image/png"),"service="+(a.service||"WMS"),"version="+(a.version||"1.1.1"),"request="+(a.request||"GetMap"),"srs="+(a.srs||"EPSG:3857"),"width="+(a.width||256),"height="+(a.height||256),"layers="+r].join("&")},t.getTileBBox=e,t.getMercCoords=r,Object.defineProperty(t,"__esModule",{value:!0});}(e);})),Ba=function(t,e,r){this.z=t,this.x=e,this.y=r,this.key=Ea(0,t,e,r);};Ba.prototype.equals=function(t){return this.z===t.z&&this.x===t.x&&this.y===t.y},Ba.prototype.url=function(t,e){var r=Va.getTileBBox(this.x,this.y,this.z),n=function(t,e,r){for(var n,i="",o=t;o>0;o--)i+=(e&(n=1<<o-1)?1:0)+(r&n?2:0);return i}(this.z,this.x,this.y);return t[(this.x+this.y)%t.length].replace("{prefix}",(this.x%16).toString(16)+(this.y%16).toString(16)).replace("{z}",String(this.z)).replace("{x}",String(this.x)).replace("{y}",String("tms"===e?Math.pow(2,this.z)-this.y-1:this.y)).replace("{quadkey}",n).replace("{bbox-epsg-3857}",r)};var Ca=function(t,e){this.wrap=t,this.canonical=e,this.key=Ea(t,e.z,e.x,e.y);},Ia=function(t,e,r,n,i){this.overscaledZ=t,this.wrap=e,this.canonical=new Ba(r,+n,+i),this.key=Ea(e,t,n,i);};function Ea(t,e,r,n){(t*=2)<0&&(t=-1*t-1);var i=1<<e;return 32*(i*i*t+i*n+r)+e}Ia.prototype.equals=function(t){return this.overscaledZ===t.overscaledZ&&this.wrap===t.wrap&&this.canonical.equals(t.canonical)},Ia.prototype.scaledTo=function(t){var e=this.canonical.z-t;return t>this.canonical.z?new Ia(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new Ia(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)},Ia.prototype.isChildOf=function(t){var e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ<this.overscaledZ&&t.canonical.x===this.canonical.x>>e&&t.canonical.y===this.canonical.y>>e},Ia.prototype.children=function(t){if(this.overscaledZ>=t)return[new Ia(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];var e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return[new Ia(e,this.wrap,e,r,n),new Ia(e,this.wrap,e,r+1,n),new Ia(e,this.wrap,e,r,n+1),new Ia(e,this.wrap,e,r+1,n+1)]},Ia.prototype.isLessThan=function(t){return this.wrap<t.wrap||!(this.wrap>t.wrap)&&(this.overscaledZ<t.overscaledZ||!(this.overscaledZ>t.overscaledZ)&&(this.canonical.x<t.canonical.x||!(this.canonical.x>t.canonical.x)&&this.canonical.y<t.canonical.y))},Ia.prototype.wrapped=function(){return new Ia(this.overscaledZ,0,this.canonical.z,this.canonical.x,this.canonical.y)},Ia.prototype.unwrapTo=function(t){return new Ia(this.overscaledZ,t,this.canonical.z,this.canonical.x,this.canonical.y)},Ia.prototype.overscaleFactor=function(){return Math.pow(2,this.overscaledZ-this.canonical.z)},Ia.prototype.toUnwrapped=function(){return new Ca(this.wrap,this.canonical)},Ia.prototype.toString=function(){return this.overscaledZ+"/"+this.canonical.x+"/"+this.canonical.y},Ia.prototype.toCoordinate=function(){return new a(this.canonical.x+Math.pow(2,this.wrap),this.canonical.y,this.canonical.z)},hr("CanonicalTileID",Ba),hr("OverscaledTileID",Ia,{omit:["posMatrix"]});var Fa=function(t,e,r){if(t<=0)throw new RangeError("Level must have positive dimension");this.dim=t,this.border=e,this.stride=this.dim+2*this.border,this.data=r||new Int32Array((this.dim+2*this.border)*(this.dim+2*this.border));};Fa.prototype.set=function(t,e,r){this.data[this._idx(t,e)]=r+65536;},Fa.prototype.get=function(t,e){return this.data[this._idx(t,e)]-65536},Fa.prototype._idx=function(t,e){if(t<-this.border||t>=this.dim+this.border||e<-this.border||e>=this.dim+this.border)throw new RangeError("out of range source coordinates for DEM data");return(e+this.border)*this.stride+(t+this.border)},hr("Level",Fa);var Pa=function(t,e,r){this.uid=t,this.scale=e||1,this.level=r||new Fa(256,512),this.loaded=!!r;};Pa.prototype.loadFromImage=function(t,e){if(t.height!==t.width)throw new RangeError("DEM tiles must be square");if(e&&"mapbox"!==e&&"terrarium"!==e)return b('"'+e+'" is not a valid encoding type. Valid types include "mapbox" and "terrarium".');var r=this.level=new Fa(t.width,t.width/2),n=t.data;this._unpackData(r,n,e||"mapbox");for(var i=0;i<r.dim;i++)r.set(-1,i,r.get(0,i)),r.set(r.dim,i,r.get(r.dim-1,i)),r.set(i,-1,r.get(i,0)),r.set(i,r.dim,r.get(i,r.dim-1));r.set(-1,-1,r.get(0,0)),r.set(r.dim,-1,r.get(r.dim-1,0)),r.set(-1,r.dim,r.get(0,r.dim-1)),r.set(r.dim,r.dim,r.get(r.dim-1,r.dim-1)),this.loaded=!0;},Pa.prototype._unpackMapbox=function(t,e,r){return(256*t*256+256*e+r)/10-1e4},Pa.prototype._unpackTerrarium=function(t,e,r){return 256*t+e+r/256-32768},Pa.prototype._unpackData=function(t,e,r){for(var n={mapbox:this._unpackMapbox,terrarium:this._unpackTerrarium}[r],i=0;i<t.dim;i++)for(var o=0;o<t.dim;o++){var a=4*(i*t.dim+o);t.set(o,i,this.scale*n(e[a],e[a+1],e[a+2]));}},Pa.prototype.getPixels=function(){return new pi({width:this.level.dim+2*this.level.border,height:this.level.dim+2*this.level.border},new Uint8Array(this.level.data.buffer))},Pa.prototype.backfillBorder=function(t,e,r){var n=this.level,i=t.level;if(n.dim!==i.dim)throw new Error("level mismatch (dem dimension)");var o=e*n.dim,a=e*n.dim+n.dim,s=r*n.dim,u=r*n.dim+n.dim;switch(e){case-1:o=a-1;break;case 1:a=o+1;}switch(r){case-1:s=u-1;break;case 1:u=s+1;}for(var l=c(o,-n.border,n.dim+n.border),p=c(a,-n.border,n.dim+n.border),h=c(s,-n.border,n.dim+n.border),f=c(u,-n.border,n.dim+n.border),y=-e*n.dim,d=-r*n.dim,v=h;v<f;v++)for(var m=l;m<p;m++)n.set(m,v,i.get(m+y,v+d));},hr("DEMData",Pa);var Ta=function(t){this._stringToNumber={},this._numberToString=[];for(var e=0;e<t.length;e++){var r=t[e];this._stringToNumber[r]=e,this._numberToString[e]=r;}};Ta.prototype.encode=function(t){return this._stringToNumber[t]},Ta.prototype.decode=function(t){return this._numberToString[t]};var Oa=function(t,e,r,n){this.type="Feature",this._vectorTileFeature=t,t._z=e,t._x=r,t._y=n,this.properties=t.properties,null!=t.id&&(this.id=t.id);},La={geometry:{configurable:!0}};La.geometry.get=function(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry},La.geometry.set=function(t){this._geometry=t;},Oa.prototype.toJSON=function(){var t={geometry:this.geometry};for(var e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&(t[e]=this[e]);return t},Object.defineProperties(Oa.prototype,La);var ja=function(t,e,r){this.tileID=t,this.x=t.canonical.x,this.y=t.canonical.y,this.z=t.canonical.z,this.grid=e||new sr(Pn,16,0),this.featureIndexArray=r||new An;};function qa(t,e){return e-t}ja.prototype.insert=function(t,e,r,n,i){var o=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(r,n,i);for(var a=0;a<e.length;a++){for(var s=e[a],u=[1/0,1/0,-1/0,-1/0],l=0;l<s.length;l++){var p=s[l];u[0]=Math.min(u[0],p.x),u[1]=Math.min(u[1],p.y),u[2]=Math.max(u[2],p.x),u[3]=Math.max(u[3],p.y);}u[0]<Pn&&u[1]<Pn&&u[2]>=0&&u[3]>=0&&this.grid.insert(o,u[0],u[1],u[2],u[3]);}},ja.prototype.loadVTLayers=function(){return this.vtLayers||(this.vtLayers=new vo.VectorTile(new oa(this.rawTileData)).layers,this.sourceLayerCoder=new Ta(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])),this.vtLayers},ja.prototype.query=function(t,e){var r=this;this.loadVTLayers();for(var n=t.params||{},i=Pn/t.tileSize/t.scale,o=Te(n.filter),a=t.queryGeometry,s=t.queryPadding*i,u=1/0,l=1/0,p=-1/0,c=-1/0,h=0;h<a.length;h++)for(var f=a[h],y=0;y<f.length;y++){var d=f[y];u=Math.min(u,d.x),l=Math.min(l,d.y),p=Math.max(p,d.x),c=Math.max(c,d.y);}var v=this.grid.query(u-s,l-s,p+s,c+s);v.sort(qa);for(var m,g={},x=function(s){var u=v[s];if(u!==m){m=u;var l=r.featureIndexArray.get(u),p=null;r.loadMatchingFeature(g,l.bucketIndex,l.sourceLayerIndex,l.featureIndex,o,n.layers,e,function(e,n){return p||(p=Ln(e)),n.queryIntersectsFeature(a,e,p,r.z,t.transform,i,t.posMatrix)});}},b=0;b<v.length;b++)x(b);return g},ja.prototype.loadMatchingFeature=function(t,e,r,n,i,o,a,s){var u=this.bucketLayerIDs[e];if(!o||function(t,e){for(var r=0;r<t.length;r++)if(e.indexOf(t[r])>=0)return!0;return!1}(o,u)){var l=this.sourceLayerCoder.decode(r),p=this.vtLayers[l].feature(n);if(i(new Br(this.tileID.overscaledZ),p))for(var c=0;c<u.length;c++){var h=u[c];if(!(o&&o.indexOf(h)<0)){var f=a[h];if(f&&(!s||s(p,f))){var y=new Oa(p,this.z,this.x,this.y);y.layer=f.serialize();var d=t[h];void 0===d&&(d=t[h]=[]),d.push({featureIndex:n,feature:y});}}}}},ja.prototype.lookupSymbolFeatures=function(t,e,r,n,i,o){var a={};this.loadVTLayers();for(var s=Te(n),u=0,l=t;u<l.length;u+=1){var p=l[u];this.loadMatchingFeature(a,e,r,p,s,i,o);}return a},ja.prototype.hasLayer=function(t){for(var e=0,r=this.bucketLayerIDs;e<r.length;e+=1)for(var n=0,i=r[e];n<i.length;n+=1){if(t===i[n])return!0}return!1},hr("FeatureIndex",ja,{omit:["rawTileData","sourceLayerCoder"]});var Ra={horizontal:1,vertical:2,horizontalOnly:3};var Ua={9:!0,10:!0,11:!0,12:!0,13:!0,32:!0},Da={};function Na(t,e,r,n){var i=Math.pow(t-e,2);return n?t<e?i/2:2*i:i+Math.abs(r)*r}function Za(t,e){var r=0;return 10===t&&(r-=1e4),40!==t&&65288!==t||(r+=50),41!==e&&65289!==e||(r+=50),r}function Ka(t,e,r,n,i,o){for(var a=null,s=Na(e,r,i,o),u=0,l=n;u<l.length;u+=1){var p=l[u],c=Na(e-p.x,r,i,o)+p.badness;c<=s&&(a=p,s=c);}return{index:t,x:e,priorBreak:a,badness:s}}function Ja(t,e,r,n){if(!r)return[];if(!t)return[];for(var i,o=[],a=function(t,e,r,n){for(var i=0,o=0;o<t.length;o++){var a=n[t.charCodeAt(o)];a&&(i+=a.metrics.advance+e);}return i/Math.max(1,Math.ceil(i/r))}(t,e,r,n),s=0,u=0;u<t.length;u++){var l=t.charCodeAt(u),p=n[l];p&&!Ua[l]&&(s+=p.metrics.advance+e),u<t.length-1&&(Da[l]||!((i=l)<11904)&&(mr["Bopomofo Extended"](i)||mr.Bopomofo(i)||mr["CJK Compatibility Forms"](i)||mr["CJK Compatibility Ideographs"](i)||mr["CJK Compatibility"](i)||mr["CJK Radicals Supplement"](i)||mr["CJK Strokes"](i)||mr["CJK Symbols and Punctuation"](i)||mr["CJK Unified Ideographs Extension A"](i)||mr["CJK Unified Ideographs"](i)||mr["Enclosed CJK Letters and Months"](i)||mr["Halfwidth and Fullwidth Forms"](i)||mr.Hiragana(i)||mr["Ideographic Description Characters"](i)||mr["Kangxi Radicals"](i)||mr["Katakana Phonetic Extensions"](i)||mr.Katakana(i)||mr["Vertical Forms"](i)||mr["Yi Radicals"](i)||mr["Yi Syllables"](i)))&&o.push(Ka(u+1,s,a,o,Za(l,t.charCodeAt(u+1)),!1));}return function t(e){return e?t(e.priorBreak).concat(e.index):[]}(Ka(t.length,s,a,o,0,!0))}function $a(t){var e=.5,r=.5;switch(t){case"right":case"top-right":case"bottom-right":e=1;break;case"left":case"top-left":case"bottom-left":e=0;}switch(t){case"bottom":case"bottom-right":case"bottom-left":r=1;break;case"top":case"top-right":case"top-left":r=0;}return{horizontalAlign:e,verticalAlign:r}}function Ha(t,e,r,n,i){if(i){var o=e[t[n].glyph];if(o)for(var a=o.metrics.advance,s=(t[n].x+a)*i,u=r;u<=n;u++)t[u].x-=s;}}Da[10]=!0,Da[32]=!0,Da[38]=!0,Da[40]=!0,Da[41]=!0,Da[43]=!0,Da[45]=!0,Da[47]=!0,Da[173]=!0,Da[183]=!0,Da[8203]=!0,Da[8208]=!0,Da[8211]=!0,Da[8231]=!0,t.commonjsGlobal=e,t.unwrapExports=r,t.createCommonjsModule=n,t.default=self,t.default$1=s,t.getJSON=function(t,e){var r=z(t);return r.setRequestHeader("Accept","application/json"),r.onerror=function(){e(new Error(r.statusText));},r.onload=function(){if(r.status>=200&&r.status<300&&r.response){var n;try{n=JSON.parse(r.response);}catch(t){return e(t)}e(null,n);}else 401===r.status&&t.url.match(/mapbox.com/)?e(new k(r.statusText+": you may have provided an invalid Mapbox access token. See https://www.mapbox.com/api-documentation/#access-tokens",r.status,t.url)):e(new k(r.statusText,r.status,t.url));},r.send(),r},t.getImage=function(t,e){return S(t,function(t,r){if(t)e(t);else if(r){var n=new self.Image,i=self.URL||self.webkitURL;n.onload=function(){e(null,n),i.revokeObjectURL(n.src);};var o=new self.Blob([new Uint8Array(r.data)],{type:"image/png"});n.cacheControl=r.cacheControl,n.expires=r.expires,n.src=r.data.byteLength?i.createObjectURL(o):"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";}})},t.ResourceType=A,t.RGBAImage=pi,t.default$2=Qo,t.ImagePosition=ta,t.getArrayBuffer=S,t.default$3=function(t){return new oa(t).readFields(Aa,[])},t.default$4=mr,t.asyncAll=function(t,e,r){if(!t.length)return r(null,[]);var n=t.length,i=new Array(t.length),o=null;t.forEach(function(t,a){e(t,function(t,e){t&&(o=t),i[a]=e,0==--n&&r(o,i);});});},t.AlphaImage=li,t.default$5=E,t.endsWith=d,t.extend=h,t.sphericalToCartesian=function(t){var e=t[0],r=t[1],n=t[2];return r+=90,r*=Math.PI/180,n*=Math.PI/180,{x:e*Math.cos(r)*Math.sin(n),y:e*Math.sin(r)*Math.sin(n),z:e*Math.cos(n)}},t.Evented=I,t.validateStyle=rr,t.validateLight=nr,t.emitValidationErrors=ar,t.default$6=Q,t.number=wt,t.Properties=Dr,t.Transitionable=Er,t.Transitioning=Pr,t.PossiblyEvaluated=Lr,t.DataConstantProperty=jr,t.warnOnce=b,t.uniqueId=function(){return f++},t.default$7=Ma,t.pick=function(t,e){for(var r={},n=0;n<e.length;n++){var i=e[n];i in t&&(r[i]=t[i]);}return r},t.wrap=function(t,e,r){var n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i},t.clamp=c,t.Event=B,t.ErrorEvent=C,t.OverscaledTileID=Ia,t.default$8=Pn,t.createLayout=$r,t.getCoordinatesCenter=function(t){for(var e=1/0,r=1/0,n=-1/0,i=-1/0,o=0;o<t.length;o++)e=Math.min(e,t[o].column),r=Math.min(r,t[o].row),n=Math.max(n,t[o].column),i=Math.max(i,t[o].row);var s=n-e,u=i-r,l=Math.max(s,u),p=Math.max(0,Math.floor(-Math.log(l)/Math.LN2));return new a((e+n)/2,(r+i)/2,0).zoomTo(p)},t.CanonicalTileID=Ba,t.RasterBoundsArray=Gr,t.getVideo=function(t,e){var r,n,i=self.document.createElement("video");i.onloadstart=function(){e(null,i);};for(var o=0;o<t.length;o++){var a=self.document.createElement("source");r=t[o],n=void 0,(n=self.document.createElement("a")).href=r,(n.protocol!==self.document.location.protocol||n.host!==self.document.location.host)&&(i.crossOrigin="Anonymous"),a.src=t[o],i.appendChild(a);}return i},t.default$9=F,t.bindAll=y,t.default$10=function t(e,r){if(Array.isArray(e)){if(!Array.isArray(r)||e.length!==r.length)return!1;for(var n=0;n<e.length;n++)if(!t(e[n],r[n]))return!1;return!0}if("object"==typeof e&&null!==e&&null!==r){if("object"!=typeof r)return!1;if(Object.keys(e).length!==Object.keys(r).length)return!1;for(var i in e)if(!t(e[i],r[i]))return!1;return!0}return e===r},t.parseCacheControl=function(t){var e={};if(t.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,function(t,r,n,i){var o=n||i;return e[r]=!o||o.toLowerCase(),""}),e["max-age"]){var r=parseInt(e["max-age"],10);isNaN(r)?delete e["max-age"]:e["max-age"]=r;}return e},t.default$11=ja,t.default$12=Oa,t.default$13=Te,t.default$14=Ko,t.CollisionBoxArray=dn,t.default$15=zn,t.TriangleIndexArray=pn,t.default$16=Br,t.default$17=a,t.keysDifference=function(t,e){var r=[];for(var n in t)n in e||r.push(n);return r},t.default$18=["type","source","source-layer","minzoom","maxzoom","filter","layout"],t.mat4=ri,t.vec4=ei,t.getSizeData=jo,t.evaluateSizeForFeature=function(t,e,r){var n=e;return"source"===t.functionType?r.lowerSize/10:"composite"===t.functionType?wt(r.lowerSize/10,r.upperSize/10,n.uSizeT):n.uSize},t.evaluateSizeForZoom=function(t,e,r){if("constant"===t.functionType)return{uSizeT:0,uSize:t.layoutSize};if("source"===t.functionType)return{uSizeT:0,uSize:0};if("camera"===t.functionType){var n=t.propertyValue,i=t.zoomRange,o=t.sizeRange,a=c(Se(n,r.specification).interpolationFactor(e,i.min,i.max),0,1);return{uSizeT:0,uSize:o.min+a*(o.max-o.min)}}var s=t.propertyValue,u=t.zoomRange;return{uSizeT:c(Se(s,r.specification).interpolationFactor(e,u.min,u.max),0,1),uSize:0}},t.addDynamicAttributes=Do,t.default$19=$o,t.WritingMode=Ra,t.multiPolygonIntersectsBufferedPoint=Rn,t.multiPolygonIntersectsMultiPolygon=Un,t.multiPolygonIntersectsBufferedMultiLine=Dn,t.polygonIntersectsPolygon=function(t,e){for(var r=0;r<t.length;r++)if(Xn(e,t[r]))return!0;for(var n=0;n<e.length;n++)if(Xn(t,e[n]))return!0;return!!Zn(t,e)},t.distToSegmentSquared=$n,t.default$20=ti,t.default$21=Nr,t.default$22=function(t){return new Wo[t.type](t)},t.clone=g,t.filterObject=m,t.mapObject=v,t.registerForPluginAvailability=function(t){return zr?t({pluginURL:zr,completionCallback:Ar}):Mr.once("pluginAvailable",t),t},t.evented=Mr,t.default$23=vr,t.default$24=In,t.PosArray=Xr,t.UnwrappedTileID=Ca,t.ease=p,t.bezier=l,t.setRTLTextPlugin=function(t,e){if(kr)throw new Error("setRTLTextPlugin cannot be called multiple times.");kr=!0,zr=t,Ar=function(t){t?(kr=!1,zr=null,e&&e(t)):Sr=!0;},Mr.fire(new B("pluginAvailable",{pluginURL:zr,completionCallback:Ar}));},t.values=function(t){var e=[];for(var r in t)e.push(t[r]);return e},t.default$25=Lo,t.register=hr,t.GLYPH_PBF_BORDER=Sa,t.shapeText=function(t,e,r,n,i,o,a,s,u,l){var p=t.trim();l===Ra.vertical&&(p=function(t){for(var e="",r=0;r<t.length;r++){var n=t.charCodeAt(r+1)||null,i=t.charCodeAt(r-1)||null;n&&wr(n)&&!Oo[t[r+1]]||i&&wr(i)&&!Oo[t[r-1]]||!Oo[t[r]]?e+=t[r]:e+=Oo[t[r]];}return e}(p));var c=[],h={positionedGlyphs:c,text:p,top:s[1],bottom:s[1],left:s[0],right:s[0],writingMode:l},f=Vr.processBidirectionalText;return function(t,e,r,n,i,o,a,s,u){for(var l=0,p=-17,c=0,h=t.positionedGlyphs,f="right"===o?1:"left"===o?0:.5,y=0,d=r;y<d.length;y+=1){var v=d[y];if((v=v.trim()).length){for(var m=h.length,g=0;g<v.length;g++){var x=v.charCodeAt(g),b=e[x];b&&(br(x)&&a!==Ra.horizontal?(h.push({glyph:x,x:l,y:0,vertical:!0}),l+=u+s):(h.push({glyph:x,x:l,y:p,vertical:!1}),l+=b.metrics.advance+s));}if(h.length!==m){var w=l-s;c=Math.max(w,c),Ha(h,e,m,h.length-1,f);}l=0,p+=n;}else p+=n;}var _=$a(i),A=_.horizontalAlign,k=_.verticalAlign;!function(t,e,r,n,i,o,a){for(var s=(e-r)*i,u=(-n*a+.5)*o,l=0;l<t.length;l++)t[l].x+=s,t[l].y+=u;}(h,f,A,k,c,n,r.length);var z=r.length*n;t.top+=-k*z,t.bottom=t.top+z,t.left+=-A*c,t.right=t.left+c;}(h,e,f?f(p,Ja(p,a,r,e)):function(t,e){for(var r=[],n=0,i=0,o=e;i<o.length;i+=1){var a=o[i];r.push(t.substring(n,a)),n=a;}return n<t.length&&r.push(t.substring(n,t.length)),r}(p,Ja(p,a,r,e)),n,i,o,l,a,u),!!c.length&&h},t.shapeIcon=function(t,e,r){var n=$a(r),i=n.horizontalAlign,o=n.verticalAlign,a=e[0],s=e[1],u=a-t.displaySize[0]*i,l=u+t.displaySize[0],p=s-t.displaySize[1]*o;return{image:t,top:p,bottom:p+t.displaySize[1],left:u,right:l}},t.allowsVerticalWritingMode=gr,t.allowsLetterSpacing=function(t){for(var e=0,r=t;e<r.length;e+=1)if(!xr(r[e].charCodeAt(0)))return!1;return!0},t.default$26=$i,t.default$27=Ta,t.default$28=ra,t.default$29=vo,t.default$30=oa,t.default$31=Pa,t.__moduleExports=vo,t.default$32=s,t.__moduleExports$1=oa,t.plugin=Vr;});

define(["./chunk1.js"],function(e){"use strict";function t(e){var i=typeof e;if("number"===i||"boolean"===i||"string"===i||null==e)return JSON.stringify(e);if(Array.isArray(e)){for(var r="[",n=0,o=e;n<o.length;n+=1){r+=t(o[n])+",";}return r+"]"}for(var a=Object.keys(e).sort(),s="{",l=0;l<a.length;l++)s+=JSON.stringify(a[l])+":"+t(e[a[l]])+",";return s+"}"}function i(i){for(var r="",n=0,o=e.default$18;n<o.length;n+=1){r+="/"+t(i[o[n]]);}return r}var r=function(e){e&&this.replace(e);};function n(e,t,i,r,n){if(void 0===t.segment)return!0;for(var o=t,a=t.segment+1,s=0;s>-i/2;){if(--a<0)return!1;s-=e[a].dist(o),o=e[a];}s+=e[a].dist(e[a+1]),a++;for(var l=[],u=0;s<i/2;){var h=e[a-1],c=e[a],f=e[a+1];if(!f)return!1;var p=h.angleTo(c)-c.angleTo(f);for(p=Math.abs((p+3*Math.PI)%(2*Math.PI)-Math.PI),l.push({distance:s,angleDelta:p}),u+=p;s-l[0].distance>r;)u-=l.shift().angleDelta;if(u>n)return!1;a++,s+=c.dist(f);}return!0}function o(t,i,r,o,a,s,l,u,h){var c=o?.6*s*l:0,f=Math.max(o?o.right-o.left:0,a?a.right-a.left:0),p=0===t[0].x||t[0].x===h||0===t[0].y||t[0].y===h;return i-f*l<i/4&&(i=f*l+i/4),function t(i,r,o,a,s,l,u,h,c){var f=l/2;var p=0;for(var d=0;d<i.length-1;d++)p+=i[d].dist(i[d+1]);var g=0,v=r-o;var y=[];for(var m=0;m<i.length-1;m++){for(var x=i[m],w=i[m+1],S=x.dist(w),M=w.angleTo(x);v+o<g+S;){var b=((v+=o)-g)/S,_=e.number(x.x,w.x,b),I=e.number(x.y,w.y,b);if(_>=0&&_<c&&I>=0&&I<c&&v-f>=0&&v+f<=p){var z=new e.default$25(_,I,M,m);z._round(),a&&!n(i,z,l,a,s)||y.push(z);}}g+=S;}h||y.length||u||(y=t(i,g/2,o,a,s,l,u,!0,c));return y}(t,p?i/2*u%i:(f/2+2*s)*l*u%i,i,c,r,f*l,p,!1,h)}r.prototype.replace=function(e){this._layerConfigs={},this._layers={},this.update(e,[]);},r.prototype.update=function(t,r){for(var n=this,o=0,a=t;o<a.length;o+=1){var s=a[o];n._layerConfigs[s.id]=s;var l=n._layers[s.id]=e.default$22(s);l._featureFilter=e.default$13(l.filter);}for(var u=0,h=r;u<h.length;u+=1){var c=h[u];delete n._layerConfigs[c],delete n._layers[c];}this.familiesBySource={};for(var f=0,p=function(e){for(var t={},r=0;r<e.length;r++){var n=i(e[r]),o=t[n];o||(o=t[n]=[]),o.push(e[r]);}var a=[];for(var s in t)a.push(t[s]);return a}(e.values(this._layerConfigs));f<p.length;f+=1){var d=p[f].map(function(e){return n._layers[e.id]}),g=d[0];if("none"!==g.visibility){var v=g.source||"",y=n.familiesBySource[v];y||(y=n.familiesBySource[v]={});var m=g.sourceLayer||"_geojsonTileLayer",x=y[m];x||(x=y[m]=[]),x.push(d);}}};var a=function(){this.opacity=0,this.targetOpacity=0,this.time=0;};a.prototype.clone=function(){var e=new a;return e.opacity=this.opacity,e.targetOpacity=this.targetOpacity,e.time=this.time,e},e.register("OpacityState",a);var s=function(e,t,i,r,n,o,a,s,l,u,h){var c=a.top*s-l,f=a.bottom*s+l,p=a.left*s-l,d=a.right*s+l;if(this.boxStartIndex=e.length,u){var g=f-c,v=d-p;g>0&&(g=Math.max(10*s,g),this._addLineCollisionCircles(e,t,i,i.segment,v,g,r,n,o,h));}else e.emplaceBack(i.x,i.y,p,c,d,f,r,n,o,0,0);this.boxEndIndex=e.length;};s.prototype._addLineCollisionCircles=function(e,t,i,r,n,o,a,s,l,u){var h=o/2,c=Math.floor(n/h),f=1+.4*Math.log(u)/Math.LN2,p=Math.floor(c*f/2),d=-o/2,g=i,v=r+1,y=d,m=-n/2,x=m-n/4;do{if(--v<0){if(y>m)return;v=0;break}y-=t[v].dist(g),g=t[v];}while(y>x);for(var w=t[v].dist(t[v+1]),S=-p;S<c+p;S++){var M=S*h,b=m+M;if(M<0&&(b+=M),M>n&&(b+=M-n),!(b<y)){for(;y+w<b;){if(y+=w,++v+1>=t.length)return;w=t[v].dist(t[v+1]);}var _=b-y,I=t[v],z=t[v+1].sub(I)._unit()._mult(_)._add(I)._round(),T=Math.abs(b-d)<h?0:.8*(b-d);e.emplaceBack(z.x,z.y,-o/2,-o/2,o/2,o/2,a,s,l,o/2,T);}}};var l=h,u=h;function h(e,t){if(!(this instanceof h))return new h(e,t);if(this.data=e||[],this.length=this.data.length,this.compare=t||c,this.length>0)for(var i=(this.length>>1)-1;i>=0;i--)this._down(i);}function c(e,t){return e<t?-1:e>t?1:0}function f(t,i,r){void 0===i&&(i=1),void 0===r&&(r=!1);for(var n=1/0,o=1/0,a=-1/0,s=-1/0,u=t[0],h=0;h<u.length;h++){var c=u[h];(!h||c.x<n)&&(n=c.x),(!h||c.y<o)&&(o=c.y),(!h||c.x>a)&&(a=c.x),(!h||c.y>s)&&(s=c.y);}var f=a-n,g=s-o,v=Math.min(f,g),y=v/2,m=new l(null,p);if(0===v)return new e.default$1(n,o);for(var x=n;x<a;x+=v)for(var w=o;w<s;w+=v)m.push(new d(x+y,w+y,y,t));for(var S=function(e){for(var t=0,i=0,r=0,n=e[0],o=0,a=n.length,s=a-1;o<a;s=o++){var l=n[o],u=n[s],h=l.x*u.y-u.x*l.y;i+=(l.x+u.x)*h,r+=(l.y+u.y)*h,t+=3*h;}return new d(i/t,r/t,0,e)}(t),M=m.length;m.length;){var b=m.pop();(b.d>S.d||!S.d)&&(S=b,r&&console.log("found best %d after %d probes",Math.round(1e4*b.d)/1e4,M)),b.max-S.d<=i||(y=b.h/2,m.push(new d(b.p.x-y,b.p.y-y,y,t)),m.push(new d(b.p.x+y,b.p.y-y,y,t)),m.push(new d(b.p.x-y,b.p.y+y,y,t)),m.push(new d(b.p.x+y,b.p.y+y,y,t)),M+=4);}return r&&(console.log("num probes: "+M),console.log("best distance: "+S.d)),S.p}function p(e,t){return t.max-e.max}function d(t,i,r,n){this.p=new e.default$1(t,i),this.h=r,this.d=function(t,i){for(var r=!1,n=1/0,o=0;o<i.length;o++)for(var a=i[o],s=0,l=a.length,u=l-1;s<l;u=s++){var h=a[s],c=a[u];h.y>t.y!=c.y>t.y&&t.x<(c.x-h.x)*(t.y-h.y)/(c.y-h.y)+h.x&&(r=!r),n=Math.min(n,e.distToSegmentSquared(t,h,c));}return(r?1:-1)*Math.sqrt(n)}(this.p,n),this.max=this.d+this.h*Math.SQRT2;}function g(t,i,r,n,o,a){t.createArrays(),t.symbolInstances=[];var s=512*t.overscaling;t.tilePixelRatio=e.default$8/s,t.compareText={},t.iconsNeedLinear=!1;var l=t.layers[0].layout,u=t.layers[0]._unevaluatedLayout._values,h={};if("composite"===t.textSizeData.functionType){var c=t.textSizeData.zoomRange,f=c.min,p=c.max;h.compositeTextSizes=[u["text-size"].possiblyEvaluate(new e.default$16(f)),u["text-size"].possiblyEvaluate(new e.default$16(p))];}if("composite"===t.iconSizeData.functionType){var d=t.iconSizeData.zoomRange,g=d.min,y=d.max;h.compositeIconSizes=[u["icon-size"].possiblyEvaluate(new e.default$16(g)),u["icon-size"].possiblyEvaluate(new e.default$16(y))];}h.layoutTextSize=u["text-size"].possiblyEvaluate(new e.default$16(t.zoom+1)),h.layoutIconSize=u["icon-size"].possiblyEvaluate(new e.default$16(t.zoom+1)),h.textMaxSize=u["text-size"].possiblyEvaluate(new e.default$16(18));for(var m=24*l.get("text-line-height"),x="map"===l.get("text-rotation-alignment")&&"line"===l.get("symbol-placement"),w=l.get("text-keep-upright"),S=0,M=t.features;S<M.length;S+=1){var b=M[S],_=l.get("text-font").evaluate(b).join(","),I=i[_]||{},z=r[_]||{},T={},P=b.text;if(P){var k=l.get("text-offset").evaluate(b).map(function(e){return 24*e}),L=24*l.get("text-letter-spacing").evaluate(b),$=e.allowsLetterSpacing(P)?L:0,D=l.get("text-anchor").evaluate(b),O=l.get("text-justify").evaluate(b),C="line"!==l.get("symbol-placement")?24*l.get("text-max-width").evaluate(b):0;T.horizontal=e.shapeText(P,I,C,m,D,O,$,k,24,e.WritingMode.horizontal),e.allowsVerticalWritingMode(P)&&x&&w&&(T.vertical=e.shapeText(P,I,C,m,D,O,$,k,24,e.WritingMode.vertical));}var A=void 0;if(b.icon){var E=n[b.icon];E&&(A=e.shapeIcon(o[b.icon],l.get("icon-offset").evaluate(b),l.get("icon-anchor").evaluate(b)),void 0===t.sdfIcons?t.sdfIcons=E.sdf:t.sdfIcons!==E.sdf&&e.warnOnce("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"),E.pixelRatio!==t.pixelRatio?t.iconsNeedLinear=!0:0!==l.get("icon-rotate").constantOr(1)&&(t.iconsNeedLinear=!0));}(T.horizontal||A)&&v(t,b,T,A,z,h);}a&&t.generateCollisionDebugBuffers();}function v(t,i,r,n,l,u){var h=u.layoutTextSize.evaluate(i),c=u.layoutIconSize.evaluate(i),p=u.textMaxSize.evaluate(i);void 0===p&&(p=h);var d=t.layers[0].layout,g=d.get("text-offset").evaluate(i),v=d.get("icon-offset").evaluate(i),x=h/24,w=t.tilePixelRatio*x,S=t.tilePixelRatio*p/24,M=t.tilePixelRatio*c,b=t.tilePixelRatio*d.get("symbol-spacing"),_=d.get("text-padding")*t.tilePixelRatio,I=d.get("icon-padding")*t.tilePixelRatio,z=d.get("text-max-angle")/180*Math.PI,T="map"===d.get("text-rotation-alignment")&&"line"===d.get("symbol-placement"),P="map"===d.get("icon-rotation-alignment")&&"line"===d.get("symbol-placement"),k=b/2,L=function(o,h){h.x<0||h.x>=e.default$8||h.y<0||h.y>=e.default$8||t.symbolInstances.push(function(t,i,r,n,o,l,u,h,c,f,p,d,g,v,m,x,w,S,M,b,_){var I,z,T=t.addToLineVertexArray(i,r),P=0,k=0,L=0,$=n.horizontal?n.horizontal.text:"",D=[];n.horizontal&&(I=new s(u,r,i,h,c,f,n.horizontal,p,d,g,t.overscaling),k+=y(t,i,n.horizontal,l,g,M,v,T,n.vertical?e.WritingMode.horizontal:e.WritingMode.horizontalOnly,D,b,_),n.vertical&&(L+=y(t,i,n.vertical,l,g,M,v,T,e.WritingMode.vertical,D,b,_)));var O=I?I.boxStartIndex:t.collisionBoxArray.length,C=I?I.boxEndIndex:t.collisionBoxArray.length;if(o){var A=function(t,i,r,n,o,a){var s,l,u,h,c=i.image,f=r.layout,p=i.top-1/c.pixelRatio,d=i.left-1/c.pixelRatio,g=i.bottom+1/c.pixelRatio,v=i.right+1/c.pixelRatio;if("none"!==f.get("icon-text-fit")&&o){var y=v-d,m=g-p,x=f.get("text-size").evaluate(a)/24,w=o.left*x,S=o.right*x,M=o.top*x,b=S-w,_=o.bottom*x-M,I=f.get("icon-text-fit-padding")[0],z=f.get("icon-text-fit-padding")[1],T=f.get("icon-text-fit-padding")[2],P=f.get("icon-text-fit-padding")[3],k="width"===f.get("icon-text-fit")?.5*(_-m):0,L="height"===f.get("icon-text-fit")?.5*(b-y):0,$="width"===f.get("icon-text-fit")||"both"===f.get("icon-text-fit")?b:y,D="height"===f.get("icon-text-fit")||"both"===f.get("icon-text-fit")?_:m;s=new e.default$1(w+L-P,M+k-I),l=new e.default$1(w+L+z+$,M+k-I),u=new e.default$1(w+L+z+$,M+k+T+D),h=new e.default$1(w+L-P,M+k+T+D);}else s=new e.default$1(d,p),l=new e.default$1(v,p),u=new e.default$1(v,g),h=new e.default$1(d,g);var O=r.layout.get("icon-rotate").evaluate(a)*Math.PI/180;if(O){var C=Math.sin(O),A=Math.cos(O),E=[A,-C,C,A];s._matMult(E),l._matMult(E),h._matMult(E),u._matMult(E);}return[{tl:s,tr:l,bl:h,br:u,tex:c.paddedRect,writingMode:void 0,glyphOffset:[0,0]}]}(0,o,l,0,n.horizontal,M);z=new s(u,r,i,h,c,f,o,m,x,!1,t.overscaling),P=4*A.length;var E=t.iconSizeData,N=null;"source"===E.functionType?N=[10*l.layout.get("icon-size").evaluate(M)]:"composite"===E.functionType&&(N=[10*_.compositeIconSizes[0].evaluate(M),10*_.compositeIconSizes[1].evaluate(M)]),t.addSymbols(t.icon,A,N,S,w,M,!1,i,T.lineStartIndex,T.lineLength);}var R=z?z.boxStartIndex:t.collisionBoxArray.length,B=z?z.boxEndIndex:t.collisionBoxArray.length;t.glyphOffsetArray.length>=e.default$14.MAX_GLYPHS&&e.warnOnce("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907");var F=new a,G=new a;return{key:$,textBoxStartIndex:O,textBoxEndIndex:C,iconBoxStartIndex:R,iconBoxEndIndex:B,textOffset:v,iconOffset:S,anchor:i,line:r,featureIndex:h,feature:M,numGlyphVertices:k,numVerticalGlyphVertices:L,numIconVertices:P,textOpacityState:F,iconOpacityState:G,isDuplicate:!1,placedTextSymbolIndices:D,crossTileID:0}}(t,h,o,r,n,t.layers[0],t.collisionBoxArray,i.index,i.sourceLayerIndex,t.index,w,_,T,g,M,I,P,v,i,l,u));};if("line"===d.get("symbol-placement"))for(var $=0,D=function(t,i,r,n,o){for(var a=[],s=0;s<t.length;s++)for(var l=t[s],u=void 0,h=0;h<l.length-1;h++){var c=l[h],f=l[h+1];c.x<i&&f.x<i||(c.x<i?c=new e.default$1(i,c.y+(f.y-c.y)*((i-c.x)/(f.x-c.x)))._round():f.x<i&&(f=new e.default$1(i,c.y+(f.y-c.y)*((i-c.x)/(f.x-c.x)))._round()),c.y<r&&f.y<r||(c.y<r?c=new e.default$1(c.x+(f.x-c.x)*((r-c.y)/(f.y-c.y)),r)._round():f.y<r&&(f=new e.default$1(c.x+(f.x-c.x)*((r-c.y)/(f.y-c.y)),r)._round()),c.x>=n&&f.x>=n||(c.x>=n?c=new e.default$1(n,c.y+(f.y-c.y)*((n-c.x)/(f.x-c.x)))._round():f.x>=n&&(f=new e.default$1(n,c.y+(f.y-c.y)*((n-c.x)/(f.x-c.x)))._round()),c.y>=o&&f.y>=o||(c.y>=o?c=new e.default$1(c.x+(f.x-c.x)*((o-c.y)/(f.y-c.y)),o)._round():f.y>=o&&(f=new e.default$1(c.x+(f.x-c.x)*((o-c.y)/(f.y-c.y)),o)._round()),u&&c.equals(u[u.length-1])||(u=[c],a.push(u)),u.push(f)))));}return a}(i.geometry,0,0,e.default$8,e.default$8);$<D.length;$+=1)for(var O=D[$],C=0,A=o(O,b,z,r.vertical||r.horizontal,n,24,S,t.overscaling,e.default$8);C<A.length;C+=1){var E=A[C],N=r.horizontal;N&&m(t,N.text,k,E)||L(O,E);}else if("Polygon"===i.type)for(var R=0,B=e.default$26(i.geometry,0);R<B.length;R+=1){var F=B[R],G=f(F,16);L(F[0],new e.default$25(G.x,G.y,0));}else if("LineString"===i.type)for(var V=0,J=i.geometry;V<J.length;V+=1){var W=J[V];L(W,new e.default$25(W[0].x,W[0].y,0));}else if("Point"===i.type)for(var Y=0,Z=i.geometry;Y<Z.length;Y+=1)for(var j=0,X=Z[Y];j<X.length;j+=1){var q=X[j];L([q],new e.default$25(q.x,q.y,0));}}function y(t,i,r,n,o,a,s,l,u,h,c,f){var p=function(t,i,r,n,o,a){for(var s=r.layout.get("text-rotate").evaluate(o)*Math.PI/180,l=r.layout.get("text-offset").evaluate(o).map(function(e){return 24*e}),u=i.positionedGlyphs,h=[],c=0;c<u.length;c++){var f=u[c],p=a[f.glyph];if(p){var d=p.rect;if(d){var g=e.GLYPH_PBF_BORDER+1,v=p.metrics.advance/2,y=n?[f.x+v,f.y]:[0,0],m=n?[0,0]:[f.x+v+l[0],f.y+l[1]],x=p.metrics.left-g-v+m[0],w=-p.metrics.top-g+m[1],S=x+d.w,M=w+d.h,b=new e.default$1(x,w),_=new e.default$1(S,w),I=new e.default$1(x,M),z=new e.default$1(S,M);if(n&&f.vertical){var T=new e.default$1(-v,v),P=-Math.PI/2,k=new e.default$1(5,0);b._rotateAround(P,T)._add(k),_._rotateAround(P,T)._add(k),I._rotateAround(P,T)._add(k),z._rotateAround(P,T)._add(k);}if(s){var L=Math.sin(s),$=Math.cos(s),D=[$,-L,L,$];b._matMult(D),_._matMult(D),I._matMult(D),z._matMult(D);}h.push({tl:b,tr:_,bl:I,br:z,tex:d,writingMode:i.writingMode,glyphOffset:y});}}}return h}(0,r,n,o,a,c),d=t.textSizeData,g=null;return"source"===d.functionType?g=[10*n.layout.get("text-size").evaluate(a)]:"composite"===d.functionType&&(g=[10*f.compositeTextSizes[0].evaluate(a),10*f.compositeTextSizes[1].evaluate(a)]),t.addSymbols(t.text,p,g,s,o,a,u,i,l.lineStartIndex,l.lineLength),h.push(t.text.placedSymbolArray.length-1),4*p.length}function m(e,t,i,r){var n=e.compareText;if(t in n){for(var o=n[t],a=o.length-1;a>=0;a--)if(r.dist(o[a])<i)return!0}else n[t]=[];return n[t].push(r),!1}h.prototype={push:function(e){this.data.push(e),this.length++,this._up(this.length-1);},pop:function(){if(0!==this.length){var e=this.data[0];return this.length--,this.length>0&&(this.data[0]=this.data[this.length],this._down(0)),this.data.pop(),e}},peek:function(){return this.data[0]},_up:function(e){for(var t=this.data,i=this.compare,r=t[e];e>0;){var n=e-1>>1,o=t[n];if(i(r,o)>=0)break;t[e]=o,e=n;}t[e]=r;},_down:function(e){for(var t=this.data,i=this.compare,r=this.length>>1,n=t[e];e<r;){var o=1+(e<<1),a=o+1,s=t[o];if(a<this.length&&i(t[a],s)<0&&(o=a,s=t[a]),i(s,n)>=0)break;t[e]=s,e=o;}t[e]=n;}},l.default=u;var x=function(t){var i=new e.AlphaImage({width:0,height:0}),r={},n=new e.default$2(0,0,{autoResize:!0});for(var o in t){var a=t[o],s=r[o]={};for(var l in a){var u=a[+l];if(u&&0!==u.bitmap.width&&0!==u.bitmap.height){var h=n.packOne(u.bitmap.width+2,u.bitmap.height+2);i.resize({width:n.w,height:n.h}),e.AlphaImage.copy(u.bitmap,i,{x:0,y:0},{x:h.x+1,y:h.y+1},u.bitmap),s[l]={rect:h,metrics:u.metrics};}}}n.shrink(),i.resize({width:n.w,height:n.h}),this.image=i,this.positions=r;};e.register("GlyphAtlas",x);var w=function(t){this.tileID=new e.OverscaledTileID(t.tileID.overscaledZ,t.tileID.wrap,t.tileID.canonical.z,t.tileID.canonical.x,t.tileID.canonical.y),this.uid=t.uid,this.zoom=t.zoom,this.pixelRatio=t.pixelRatio,this.tileSize=t.tileSize,this.source=t.source,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=t.showCollisionBoxes,this.collectResourceTiming=!!t.collectResourceTiming;};function S(t,i){for(var r=new e.default$16(i),n=0,o=t;n<o.length;n+=1){o[n].recalculate(r);}}w.prototype.parse=function(t,i,r,n){var o=this;this.status="parsing",this.data=t,this.collisionBoxArray=new e.CollisionBoxArray;var a=new e.default$27(Object.keys(t.layers).sort()),s=new e.default$11(this.tileID);s.bucketLayerIDs=[];var l,u,h,c={},f={featureIndex:s,iconDependencies:{},glyphDependencies:{}},p=i.familiesBySource[this.source];for(var d in p){var v=t.layers[d];if(v){1===v.version&&e.warnOnce('Vector tile source "'+o.source+'" layer "'+d+'" does not use vector tile spec v2 and therefore may have some rendering errors.');for(var y=a.encode(d),m=[],w=0;w<v.length;w++){var M=v.feature(w);m.push({feature:M,index:w,sourceLayerIndex:y});}for(var b=0,_=p[d];b<_.length;b+=1){var I=_[b],z=I[0];if(!(z.minzoom&&o.zoom<Math.floor(z.minzoom)))if(!(z.maxzoom&&o.zoom>=z.maxzoom))if("none"!==z.visibility)S(I,o.zoom),(c[z.id]=z.createBucket({index:s.bucketLayerIDs.length,layers:I,zoom:o.zoom,pixelRatio:o.pixelRatio,overscaling:o.overscaling,collisionBoxArray:o.collisionBoxArray,sourceLayerIndex:y})).populate(m,f),s.bucketLayerIDs.push(I.map(function(e){return e.id}));}}}var T=e.mapObject(f.glyphDependencies,function(e){return Object.keys(e).map(Number)});Object.keys(T).length?r.send("getGlyphs",{uid:this.uid,stacks:T},function(e,t){l||(l=e,u=t,k.call(o));}):u={};var P=Object.keys(f.iconDependencies);function k(){if(l)return n(l);if(u&&h){var t=new x(u),i=new e.default$28(h);for(var r in c){var o=c[r];o instanceof e.default$14&&(S(o.layers,this.zoom),g(o,u,t.positions,h,i.positions,this.showCollisionBoxes));}this.status="done",n(null,{buckets:e.values(c).filter(function(e){return!e.isEmpty()}),featureIndex:s,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:t.image,iconAtlasImage:i.image});}}P.length?r.send("getImages",{icons:P},function(e,t){l||(l=e,h=t,k.call(o));}):h={},k.call(this);};var M=function(e){return!(!performance||!performance.getEntriesByName)&&performance.getEntriesByName(e)};function b(t,i){var r=e.getArrayBuffer(t.request,function(t,r){t?i(t):r&&i(null,{vectorTile:new e.default$29.VectorTile(new e.default$30(r.data)),rawData:r.data,cacheControl:r.cacheControl,expires:r.expires});});return function(){r.abort(),i();}}var _=function(e,t,i){this.actor=e,this.layerIndex=t,this.loadVectorData=i||b,this.loading={},this.loaded={};};_.prototype.loadTile=function(t,i){var r=this,n=t.uid;this.loading||(this.loading={});var o=this.loading[n]=new w(t);o.abort=this.loadVectorData(t,function(a,s){if(delete r.loading[n],a||!s)return i(a);var l=s.rawData,u={};s.expires&&(u.expires=s.expires),s.cacheControl&&(u.cacheControl=s.cacheControl);var h={};if(t.request&&t.request.collectResourceTiming){var c=M(t.request.url);c&&(h.resourceTiming=JSON.parse(JSON.stringify(c)));}o.vectorTile=s.vectorTile,o.parse(s.vectorTile,r.layerIndex,r.actor,function(t,r){if(t||!r)return i(t);i(null,e.extend({rawTileData:l.slice(0)},r,u,h));}),r.loaded=r.loaded||{},r.loaded[n]=o;});},_.prototype.reloadTile=function(e,t){var i=this.loaded,r=e.uid,n=this;if(i&&i[r]){var o=i[r];o.showCollisionBoxes=e.showCollisionBoxes;var a=function(e,i){var r=o.reloadCallback;r&&(delete o.reloadCallback,o.parse(o.vectorTile,n.layerIndex,n.actor,r)),t(e,i);};"parsing"===o.status?o.reloadCallback=a:"done"===o.status&&o.parse(o.vectorTile,this.layerIndex,this.actor,a);}},_.prototype.abortTile=function(e,t){var i=this.loading,r=e.uid;i&&i[r]&&i[r].abort&&(i[r].abort(),delete i[r]),t();},_.prototype.removeTile=function(e,t){var i=this.loaded,r=e.uid;i&&i[r]&&delete i[r],t();};var I=function(){this.loading={},this.loaded={};};I.prototype.loadTile=function(t,i){var r=t.uid,n=t.encoding,o=new e.default$31(r);this.loading[r]=o,o.loadFromImage(t.rawImageData,n),delete this.loading[r],this.loaded=this.loaded||{},this.loaded[r]=o,i(null,o);},I.prototype.removeTile=function(e){var t=this.loaded,i=e.uid;t&&t[i]&&delete t[i];};var z={RADIUS:6378137,FLATTENING:1/298.257223563,POLAR_RADIUS:6356752.3142};function T(e){var t=0;if(e&&e.length>0){t+=Math.abs(P(e[0]));for(var i=1;i<e.length;i++)t-=Math.abs(P(e[i]));}return t}function P(e){var t,i,r,n,o,a,s=0,l=e.length;if(l>2){for(a=0;a<l;a++)a===l-2?(r=l-2,n=l-1,o=0):a===l-1?(r=l-1,n=0,o=1):(r=a,n=a+1,o=a+2),t=e[r],i=e[n],s+=(k(e[o][0])-k(t[0]))*Math.sin(k(i[1]));s=s*z.RADIUS*z.RADIUS/2;}return s}function k(e){return e*Math.PI/180}var L={geometry:function e(t){var i,r=0;switch(t.type){case"Polygon":return T(t.coordinates);case"MultiPolygon":for(i=0;i<t.coordinates.length;i++)r+=T(t.coordinates[i]);return r;case"Point":case"MultiPoint":case"LineString":case"MultiLineString":return 0;case"GeometryCollection":for(i=0;i<t.geometries.length;i++)r+=e(t.geometries[i]);return r}},ring:P},$=function e(t,i){switch(t&&t.type||null){case"FeatureCollection":return t.features=t.features.map(D(e,i)),t;case"Feature":return t.geometry=e(t.geometry,i),t;case"Polygon":case"MultiPolygon":return function(e,t){"Polygon"===e.type?e.coordinates=O(e.coordinates,t):"MultiPolygon"===e.type&&(e.coordinates=e.coordinates.map(D(O,t)));return e}(t,i);default:return t}};function D(e,t){return function(i){return e(i,t)}}function O(e,t){t=!!t,e[0]=C(e[0],t);for(var i=1;i<e.length;i++)e[i]=C(e[i],!t);return e}function C(e,t){return function(e){return L.ring(e)>=0}(e)===t?e:e.reverse()}var A=e.default$29.VectorTileFeature.prototype.toGeoJSON,E=function(t){this._feature=t,this.extent=e.default$8,this.type=t.type,this.properties=t.tags,"id"in t&&!isNaN(t.id)&&(this.id=parseInt(t.id,10));};E.prototype.loadGeometry=function(){if(1===this._feature.type){for(var t=[],i=0,r=this._feature.geometry;i<r.length;i+=1){var n=r[i];t.push([new e.default$1(n[0],n[1])]);}return t}for(var o=[],a=0,s=this._feature.geometry;a<s.length;a+=1){for(var l=[],u=0,h=s[a];u<h.length;u+=1){var c=h[u];l.push(new e.default$1(c[0],c[1]));}o.push(l);}return o},E.prototype.toGeoJSON=function(e,t,i){return A.call(this,e,t,i)};var N=function(t){this.layers={_geojsonTileLayer:this},this.name="_geojsonTileLayer",this.extent=e.default$8,this.length=t.length,this._features=t;};N.prototype.feature=function(e){return new E(this._features[e])};var R=e.__moduleExports.VectorTileFeature,B=F;function F(e,t){this.options=t||{},this.features=e,this.length=e.length;}function G(e,t){this.id="number"==typeof e.id?e.id:void 0,this.type=e.type,this.rawGeometry=1===e.type?[e.geometry]:e.geometry,this.properties=e.tags,this.extent=t||4096;}F.prototype.feature=function(e){return new G(this.features[e],this.options.extent)},G.prototype.loadGeometry=function(){var t=this.rawGeometry;this.geometry=[];for(var i=0;i<t.length;i++){for(var r=t[i],n=[],o=0;o<r.length;o++)n.push(new e.default$32(r[o][0],r[o][1]));this.geometry.push(n);}return this.geometry},G.prototype.bbox=function(){this.geometry||this.loadGeometry();for(var e=this.geometry,t=1/0,i=-1/0,r=1/0,n=-1/0,o=0;o<e.length;o++)for(var a=e[o],s=0;s<a.length;s++){var l=a[s];t=Math.min(t,l.x),i=Math.max(i,l.x),r=Math.min(r,l.y),n=Math.max(n,l.y);}return[t,r,i,n]},G.prototype.toGeoJSON=R.prototype.toGeoJSON;var V=Z,J=Z,W=function(e,t){t=t||{};var i={};for(var r in e)i[r]=new B(e[r].features,t),i[r].name=r,i[r].version=t.version,i[r].extent=t.extent;return Z({layers:i})},Y=B;function Z(t){var i=new e.__moduleExports$1;return function(e,t){for(var i in e.layers)t.writeMessage(3,j,e.layers[i]);}(t,i),i.finish()}function j(e,t){var i;t.writeVarintField(15,e.version||1),t.writeStringField(1,e.name||""),t.writeVarintField(5,e.extent||4096);var r={keys:[],values:[],keycache:{},valuecache:{}};for(i=0;i<e.length;i++)r.feature=e.feature(i),t.writeMessage(2,X,r);var n=r.keys;for(i=0;i<n.length;i++)t.writeStringField(3,n[i]);var o=r.values;for(i=0;i<o.length;i++)t.writeMessage(4,K,o[i]);}function X(e,t){var i=e.feature;void 0!==i.id&&t.writeVarintField(1,i.id),t.writeMessage(2,q,e),t.writeVarintField(3,i.type),t.writeMessage(4,Q,i);}function q(e,t){var i=e.feature,r=e.keys,n=e.values,o=e.keycache,a=e.valuecache;for(var s in i.properties){var l=o[s];void 0===l&&(r.push(s),l=r.length-1,o[s]=l),t.writeVarint(l);var u=i.properties[s],h=typeof u;"string"!==h&&"boolean"!==h&&"number"!==h&&(u=JSON.stringify(u));var c=h+":"+u,f=a[c];void 0===f&&(n.push(u),f=n.length-1,a[c]=f),t.writeVarint(f);}}function U(e,t){return(t<<3)+(7&e)}function H(e){return e<<1^e>>31}function Q(e,t){for(var i=e.loadGeometry(),r=e.type,n=0,o=0,a=i.length,s=0;s<a;s++){var l=i[s],u=1;1===r&&(u=l.length),t.writeVarint(U(1,u));for(var h=3===r?l.length-1:l.length,c=0;c<h;c++){1===c&&1!==r&&t.writeVarint(U(2,h-1));var f=l[c].x-n,p=l[c].y-o;t.writeVarint(H(f)),t.writeVarint(H(p)),n+=f,o+=p;}3===r&&t.writeVarint(U(7,0));}}function K(e,t){var i=typeof e;"string"===i?t.writeStringField(1,e):"boolean"===i?t.writeBooleanField(7,e):"number"===i&&(e%1!=0?t.writeDoubleField(3,e):e<0?t.writeSVarintField(6,e):t.writeVarintField(5,e));}V.fromVectorTileJs=J,V.fromGeojsonVt=W,V.GeoJSONWrapper=Y;var ee=function e(t,i,r,n,o,a){if(o-n<=r)return;var s=Math.floor((n+o)/2);!function e(t,i,r,n,o,a){for(;o>n;){if(o-n>600){var s=o-n+1,l=r-n+1,u=Math.log(s),h=.5*Math.exp(2*u/3),c=.5*Math.sqrt(u*h*(s-h)/s)*(l-s/2<0?-1:1),f=Math.max(n,Math.floor(r-l*h/s+c)),p=Math.min(o,Math.floor(r+(s-l)*h/s+c));e(t,i,r,f,p,a);}var d=i[2*r+a],g=n,v=o;for(te(t,i,n,r),i[2*o+a]>d&&te(t,i,n,o);g<v;){for(te(t,i,g,v),g++,v--;i[2*g+a]<d;)g++;for(;i[2*v+a]>d;)v--;}i[2*n+a]===d?te(t,i,n,v):te(t,i,++v,o),v<=r&&(n=v+1),r<=v&&(o=v-1);}}(t,i,s,n,o,a%2);e(t,i,r,n,s-1,a+1);e(t,i,r,s+1,o,a+1);};function te(e,t,i,r){ie(e,i,r),ie(t,2*i,2*r),ie(t,2*i+1,2*r+1);}function ie(e,t,i){var r=e[t];e[t]=e[i],e[i]=r;}var re=function(e,t,i,r,n,o,a){var s,l,u=[0,e.length-1,0],h=[];for(;u.length;){var c=u.pop(),f=u.pop(),p=u.pop();if(f-p<=a)for(var d=p;d<=f;d++)s=t[2*d],l=t[2*d+1],s>=i&&s<=n&&l>=r&&l<=o&&h.push(e[d]);else{var g=Math.floor((p+f)/2);s=t[2*g],l=t[2*g+1],s>=i&&s<=n&&l>=r&&l<=o&&h.push(e[g]);var v=(c+1)%2;(0===c?i<=s:r<=l)&&(u.push(p),u.push(g-1),u.push(v)),(0===c?n>=s:o>=l)&&(u.push(g+1),u.push(f),u.push(v));}}return h};var ne=function(e,t,i,r,n,o){var a=[0,e.length-1,0],s=[],l=n*n;for(;a.length;){var u=a.pop(),h=a.pop(),c=a.pop();if(h-c<=o)for(var f=c;f<=h;f++)oe(t[2*f],t[2*f+1],i,r)<=l&&s.push(e[f]);else{var p=Math.floor((c+h)/2),d=t[2*p],g=t[2*p+1];oe(d,g,i,r)<=l&&s.push(e[p]);var v=(u+1)%2;(0===u?i-n<=d:r-n<=g)&&(a.push(c),a.push(p-1),a.push(v)),(0===u?i+n>=d:r+n>=g)&&(a.push(p+1),a.push(h),a.push(v));}}return s};function oe(e,t,i,r){var n=e-i,o=t-r;return n*n+o*o}var ae=function(e,t,i,r,n){return new se(e,t,i,r,n)};function se(e,t,i,r,n){t=t||le,i=i||ue,n=n||Array,this.nodeSize=r||64,this.points=e,this.ids=new n(e.length),this.coords=new n(2*e.length);for(var o=0;o<e.length;o++)this.ids[o]=o,this.coords[2*o]=t(e[o]),this.coords[2*o+1]=i(e[o]);ee(this.ids,this.coords,this.nodeSize,0,this.ids.length-1,0);}function le(e){return e[0]}function ue(e){return e[1]}se.prototype={range:function(e,t,i,r){return re(this.ids,this.coords,e,t,i,r,this.nodeSize)},within:function(e,t,i){return ne(this.ids,this.coords,e,t,i,this.nodeSize)}};var he=function(e){return new ce(e)};function ce(e){this.options=me(Object.create(this.options),e),this.trees=new Array(this.options.maxZoom+1);}function fe(e,t,i,r,n){return{x:e,y:t,zoom:1/0,id:r,properties:n,parentId:-1,numPoints:i}}function pe(e,t){var i=e.geometry.coordinates;return{x:ve(i[0]),y:ye(i[1]),zoom:1/0,id:t,parentId:-1}}function de(e){return{type:"Feature",properties:ge(e),geometry:{type:"Point",coordinates:[(r=e.x,360*(r-.5)),(t=e.y,i=(180-360*t)*Math.PI/180,360*Math.atan(Math.exp(i))/Math.PI-90)]}};var t,i,r;}function ge(e){var t=e.numPoints,i=t>=1e4?Math.round(t/1e3)+"k":t>=1e3?Math.round(t/100)/10+"k":t;return me(me({},e.properties),{cluster:!0,cluster_id:e.id,point_count:t,point_count_abbreviated:i})}function ve(e){return e/360+.5}function ye(e){var t=Math.sin(e*Math.PI/180),i=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return i<0?0:i>1?1:i}function me(e,t){for(var i in t)e[i]=t[i];return e}function xe(e){return e.x}function we(e){return e.y}function Se(e,t,i,r,n,o){var a=n-i,s=o-r;if(0!==a||0!==s){var l=((e-i)*a+(t-r)*s)/(a*a+s*s);l>1?(i=n,r=o):l>0&&(i+=a*l,r+=s*l);}return(a=e-i)*a+(s=t-r)*s}function Me(e,t,i,r){var n={id:e||null,type:t,geometry:i,tags:r,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};return function(e){var t=e.geometry,i=e.type;if("Point"===i||"MultiPoint"===i||"LineString"===i)be(e,t);else if("Polygon"===i||"MultiLineString"===i)for(var r=0;r<t.length;r++)be(e,t[r]);else if("MultiPolygon"===i)for(r=0;r<t.length;r++)for(var n=0;n<t[r].length;n++)be(e,t[r][n]);}(n),n}function be(e,t){for(var i=0;i<t.length;i+=3)e.minX=Math.min(e.minX,t[i]),e.minY=Math.min(e.minY,t[i+1]),e.maxX=Math.max(e.maxX,t[i]),e.maxY=Math.max(e.maxY,t[i+1]);}function _e(e,t,i){if(t.geometry){var r=t.geometry.coordinates,n=t.geometry.type,o=Math.pow(i.tolerance/((1<<i.maxZoom)*i.extent),2),a=[];if("Point"===n)Ie(r,a);else if("MultiPoint"===n)for(var s=0;s<r.length;s++)Ie(r[s],a);else if("LineString"===n)ze(r,a,o,!1);else if("MultiLineString"===n)if(i.lineMetrics)for(s=0;s<r.length;s++)return a=[],ze(r[s],a,o,!1),void e.push(Me(t.id,"LineString",a,t.properties));else Te(r,a,o,!1);else if("Polygon"===n)Te(r,a,o,!0);else{if("MultiPolygon"!==n){if("GeometryCollection"===n){for(s=0;s<t.geometry.geometries.length;s++)_e(e,{id:t.id,geometry:t.geometry.geometries[s],properties:t.properties},i);return}throw new Error("Input data is not a valid GeoJSON object.")}for(s=0;s<r.length;s++){var l=[];Te(r[s],l,o,!0),a.push(l);}}e.push(Me(t.id,n,a,t.properties));}}function Ie(e,t){t.push(Pe(e[0])),t.push(ke(e[1])),t.push(0);}function ze(e,t,i,r){for(var n,o,a=0,s=0;s<e.length;s++){var l=Pe(e[s][0]),u=ke(e[s][1]);t.push(l),t.push(u),t.push(0),s>0&&(a+=r?(n*u-l*o)/2:Math.sqrt(Math.pow(l-n,2)+Math.pow(u-o,2))),n=l,o=u;}var h=t.length-3;t[2]=1,function e(t,i,r,n){for(var o,a=n,s=t[i],l=t[i+1],u=t[r],h=t[r+1],c=i+3;c<r;c+=3){var f=Se(t[c],t[c+1],s,l,u,h);f>a&&(o=c,a=f);}a>n&&(o-i>3&&e(t,i,o,n),t[o+2]=a,r-o>3&&e(t,o,r,n));}(t,0,h,i),t[h+2]=1,t.size=Math.abs(a),t.start=0,t.end=t.size;}function Te(e,t,i,r){for(var n=0;n<e.length;n++){var o=[];ze(e[n],o,i,r),t.push(o);}}function Pe(e){return e/360+.5}function ke(e){var t=Math.sin(e*Math.PI/180),i=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return i<0?0:i>1?1:i}function Le(e,t,i,r,n,o,a,s){if(r/=t,o>=(i/=t)&&a<=r)return e;if(o>r||a<i)return null;for(var l=[],u=0;u<e.length;u++){var h=e[u],c=h.geometry,f=h.type,p=0===n?h.minX:h.minY,d=0===n?h.maxX:h.maxY;if(p>=i&&d<=r)l.push(h);else if(!(p>r||d<i)){var g=[];if("Point"===f||"MultiPoint"===f)$e(c,g,i,r,n);else if("LineString"===f)De(c,g,i,r,n,!1,s.lineMetrics);else if("MultiLineString"===f)Ce(c,g,i,r,n,!1);else if("Polygon"===f)Ce(c,g,i,r,n,!0);else if("MultiPolygon"===f)for(var v=0;v<c.length;v++){var y=[];Ce(c[v],y,i,r,n,!0),y.length&&g.push(y);}if(g.length){if(s.lineMetrics&&"LineString"===f){for(v=0;v<g.length;v++)l.push(Me(h.id,f,g[v],h.tags));continue}"LineString"!==f&&"MultiLineString"!==f||(1===g.length?(f="LineString",g=g[0]):f="MultiLineString"),"Point"!==f&&"MultiPoint"!==f||(f=3===g.length?"Point":"MultiPoint"),l.push(Me(h.id,f,g,h.tags));}}}return l.length?l:null}function $e(e,t,i,r,n){for(var o=0;o<e.length;o+=3){var a=e[o+n];a>=i&&a<=r&&(t.push(e[o]),t.push(e[o+1]),t.push(e[o+2]));}}function De(e,t,i,r,n,o,a){for(var s,l,u=Oe(e),h=0===n?Ee:Ne,c=e.start,f=0;f<e.length-3;f+=3){var p=e[f],d=e[f+1],g=e[f+2],v=e[f+3],y=e[f+4],m=0===n?p:d,x=0===n?v:y,w=!1;a&&(s=Math.sqrt(Math.pow(p-v,2)+Math.pow(d-y,2))),m<i?x>=i&&(l=h(u,p,d,v,y,i),a&&(u.start=c+s*l)):m>r?x<=r&&(l=h(u,p,d,v,y,r),a&&(u.start=c+s*l)):Ae(u,p,d,g),x<i&&m>=i&&(l=h(u,p,d,v,y,i),w=!0),x>r&&m<=r&&(l=h(u,p,d,v,y,r),w=!0),!o&&w&&(a&&(u.end=c+s*l),t.push(u),u=Oe(e)),a&&(c+=s);}var S=e.length-3;p=e[S],d=e[S+1],g=e[S+2],(m=0===n?p:d)>=i&&m<=r&&Ae(u,p,d,g),S=u.length-3,o&&S>=3&&(u[S]!==u[0]||u[S+1]!==u[1])&&Ae(u,u[0],u[1],u[2]),u.length&&t.push(u);}function Oe(e){var t=[];return t.size=e.size,t.start=e.start,t.end=e.end,t}function Ce(e,t,i,r,n,o){for(var a=0;a<e.length;a++)De(e[a],t,i,r,n,o,!1);}function Ae(e,t,i,r){e.push(t),e.push(i),e.push(r);}function Ee(e,t,i,r,n,o){var a=(o-t)/(r-t);return e.push(o),e.push(i+(n-i)*a),e.push(1),a}function Ne(e,t,i,r,n,o){var a=(o-i)/(n-i);return e.push(t+(r-t)*a),e.push(o),e.push(1),a}function Re(e,t){for(var i=[],r=0;r<e.length;r++){var n,o=e[r],a=o.type;if("Point"===a||"MultiPoint"===a||"LineString"===a)n=Be(o.geometry,t);else if("MultiLineString"===a||"Polygon"===a){n=[];for(var s=0;s<o.geometry.length;s++)n.push(Be(o.geometry[s],t));}else if("MultiPolygon"===a)for(n=[],s=0;s<o.geometry.length;s++){for(var l=[],u=0;u<o.geometry[s].length;u++)l.push(Be(o.geometry[s][u],t));n.push(l);}i.push(Me(o.id,a,n,o.tags));}return i}function Be(e,t){var i=[];i.size=e.size,void 0!==e.start&&(i.start=e.start,i.end=e.end);for(var r=0;r<e.length;r+=3)i.push(e[r]+t,e[r+1],e[r+2]);return i}function Fe(e,t){if(e.transformed)return e;var i,r,n,o=1<<e.z,a=e.x,s=e.y;for(i=0;i<e.features.length;i++){var l=e.features[i],u=l.geometry,h=l.type;if(l.geometry=[],1===h)for(r=0;r<u.length;r+=2)l.geometry.push(Ge(u[r],u[r+1],t,o,a,s));else for(r=0;r<u.length;r++){var c=[];for(n=0;n<u[r].length;n+=2)c.push(Ge(u[r][n],u[r][n+1],t,o,a,s));l.geometry.push(c);}}return e.transformed=!0,e}function Ge(e,t,i,r,n,o){return[Math.round(i*(e*r-n)),Math.round(i*(t*r-o))]}function Ve(e,t,i,r,n){for(var o=t===n.maxZoom?0:n.tolerance/((1<<t)*n.extent),a={features:[],numPoints:0,numSimplified:0,numFeatures:0,source:null,x:i,y:r,z:t,transformed:!1,minX:2,minY:1,maxX:-1,maxY:0},s=0;s<e.length;s++){a.numFeatures++,Je(a,e[s],o,n);var l=e[s].minX,u=e[s].minY,h=e[s].maxX,c=e[s].maxY;l<a.minX&&(a.minX=l),u<a.minY&&(a.minY=u),h>a.maxX&&(a.maxX=h),c>a.maxY&&(a.maxY=c);}return a}function Je(e,t,i,r){var n=t.geometry,o=t.type,a=[];if("Point"===o||"MultiPoint"===o)for(var s=0;s<n.length;s+=3)a.push(n[s]),a.push(n[s+1]),e.numPoints++,e.numSimplified++;else if("LineString"===o)We(a,n,e,i,!1,!1);else if("MultiLineString"===o||"Polygon"===o)for(s=0;s<n.length;s++)We(a,n[s],e,i,"Polygon"===o,0===s);else if("MultiPolygon"===o)for(var l=0;l<n.length;l++){var u=n[l];for(s=0;s<u.length;s++)We(a,u[s],e,i,!0,0===s);}if(a.length){var h=t.tags||null;if("LineString"===o&&r.lineMetrics){for(var c in h={},t.tags)h[c]=t.tags[c];h.mapbox_clip_start=n.start/n.size,h.mapbox_clip_end=n.end/n.size;}var f={geometry:a,type:"Polygon"===o||"MultiPolygon"===o?3:"LineString"===o||"MultiLineString"===o?2:1,tags:h};null!==t.id&&(f.id=t.id),e.features.push(f);}}function We(e,t,i,r,n,o){var a=r*r;if(r>0&&t.size<(n?a:r))i.numPoints+=t.length/3;else{for(var s=[],l=0;l<t.length;l+=3)(0===r||t[l+2]>a)&&(i.numSimplified++,s.push(t[l]),s.push(t[l+1])),i.numPoints++;n&&function(e,t){for(var i=0,r=0,n=e.length,o=n-2;r<n;o=r,r+=2)i+=(e[r]-e[o])*(e[r+1]+e[o+1]);if(i>0===t)for(r=0,n=e.length;r<n/2;r+=2){var a=e[r],s=e[r+1];e[r]=e[n-2-r],e[r+1]=e[n-1-r],e[n-2-r]=a,e[n-1-r]=s;}}(s,o),e.push(s);}}function Ye(e,t){var i=(t=this.options=function(e,t){for(var i in t)e[i]=t[i];return e}(Object.create(this.options),t)).debug;if(i&&console.time("preprocess data"),t.maxZoom<0||t.maxZoom>24)throw new Error("maxZoom should be in the 0-24 range");var r=function(e,t){var i=[];if("FeatureCollection"===e.type)for(var r=0;r<e.features.length;r++)_e(i,e.features[r],t);else"Feature"===e.type?_e(i,e,t):_e(i,{geometry:e},t);return i}(e,t);this.tiles={},this.tileCoords=[],i&&(console.timeEnd("preprocess data"),console.log("index: maxZoom: %d, maxPoints: %d",t.indexMaxZoom,t.indexMaxPoints),console.time("generate tiles"),this.stats={},this.total=0),(r=function(e,t){var i=t.buffer/t.extent,r=e,n=Le(e,1,-1-i,i,0,-1,2,t),o=Le(e,1,1-i,2+i,0,-1,2,t);return(n||o)&&(r=Le(e,1,-i,1+i,0,-1,2,t)||[],n&&(r=Re(n,1).concat(r)),o&&(r=r.concat(Re(o,-1)))),r}(r,t)).length&&this.splitTile(r,0,0,0),i&&(r.length&&console.log("features: %d, points: %d",this.tiles[0].numFeatures,this.tiles[0].numPoints),console.timeEnd("generate tiles"),console.log("tiles generated:",this.total,JSON.stringify(this.stats)));}function Ze(e,t,i){return 32*((1<<e)*i+t)+e}function je(e,t){var i=e.tileID.canonical;if(!this._geoJSONIndex)return t(null,null);var r=this._geoJSONIndex.getTile(i.z,i.x,i.y);if(!r)return t(null,null);var n=new N(r.features),o=V(n);0===o.byteOffset&&o.byteLength===o.buffer.byteLength||(o=new Uint8Array(o)),t(null,{vectorTile:n,rawData:o.buffer});}ce.prototype={options:{minZoom:0,maxZoom:16,radius:40,extent:512,nodeSize:64,log:!1,reduce:null,initial:function(){return{}},map:function(e){return e}},load:function(e){var t=this.options.log;t&&console.time("total time");var i="prepare "+e.length+" points";t&&console.time(i),this.points=e;var r=e.map(pe);t&&console.timeEnd(i);for(var n=this.options.maxZoom;n>=this.options.minZoom;n--){var o=+Date.now();this.trees[n+1]=ae(r,xe,we,this.options.nodeSize,Float32Array),r=this._cluster(r,n),t&&console.log("z%d: %d clusters in %dms",n,r.length,+Date.now()-o);}return this.trees[this.options.minZoom]=ae(r,xe,we,this.options.nodeSize,Float32Array),t&&console.timeEnd("total time"),this},getClusters:function(e,t){for(var i=this.trees[this._limitZoom(t)],r=i.range(ve(e[0]),ye(e[3]),ve(e[2]),ye(e[1])),n=[],o=0;o<r.length;o++){var a=i.points[r[o]];n.push(a.numPoints?de(a):this.points[a.id]);}return n},getChildren:function(e,t){for(var i=this.trees[t+1].points[e],r=this.options.radius/(this.options.extent*Math.pow(2,t)),n=this.trees[t+1].within(i.x,i.y,r),o=[],a=0;a<n.length;a++){var s=this.trees[t+1].points[n[a]];s.parentId===e&&o.push(s.numPoints?de(s):this.points[s.id]);}return o},getLeaves:function(e,t,i,r){i=i||10,r=r||0;var n=[];return this._appendLeaves(n,e,t,i,r,0),n},getTile:function(e,t,i){var r=this.trees[this._limitZoom(e)],n=Math.pow(2,e),o=this.options.extent,a=this.options.radius/o,s=(i-a)/n,l=(i+1+a)/n,u={features:[]};return this._addTileFeatures(r.range((t-a)/n,s,(t+1+a)/n,l),r.points,t,i,n,u),0===t&&this._addTileFeatures(r.range(1-a/n,s,1,l),r.points,n,i,n,u),t===n-1&&this._addTileFeatures(r.range(0,s,a/n,l),r.points,-1,i,n,u),u.features.length?u:null},getClusterExpansionZoom:function(e,t){for(;t<this.options.maxZoom;){var i=this.getChildren(e,t);if(t++,1!==i.length)break;e=i[0].properties.cluster_id;}return t},_appendLeaves:function(e,t,i,r,n,o){for(var a=this.getChildren(t,i),s=0;s<a.length;s++){var l=a[s].properties;if(l.cluster?o+l.point_count<=n?o+=l.point_count:o=this._appendLeaves(e,l.cluster_id,i+1,r,n,o):o<n?o++:e.push(a[s]),e.length===r)break}return o},_addTileFeatures:function(e,t,i,r,n,o){for(var a=0;a<e.length;a++){var s=t[e[a]];o.features.push({type:1,geometry:[[Math.round(this.options.extent*(s.x*n-i)),Math.round(this.options.extent*(s.y*n-r))]],tags:s.numPoints?ge(s):this.points[s.id].properties});}},_limitZoom:function(e){return Math.max(this.options.minZoom,Math.min(e,this.options.maxZoom+1))},_cluster:function(e,t){for(var i=[],r=this.options.radius/(this.options.extent*Math.pow(2,t)),n=0;n<e.length;n++){var o=e[n];if(!(o.zoom<=t)){o.zoom=t;var a=this.trees[t+1],s=a.within(o.x,o.y,r),l=o.numPoints||1,u=o.x*l,h=o.y*l,c=null;this.options.reduce&&(c=this.options.initial(),this._accumulate(c,o));for(var f=0;f<s.length;f++){var p=a.points[s[f]];if(t<p.zoom){var d=p.numPoints||1;p.zoom=t,u+=p.x*d,h+=p.y*d,l+=d,p.parentId=n,this.options.reduce&&this._accumulate(c,p);}}1===l?i.push(o):(o.parentId=n,i.push(fe(u/l,h/l,l,n,c)));}}return i},_accumulate:function(e,t){var i=t.numPoints?t.properties:this.options.map(this.points[t.id].properties);this.options.reduce(e,i);}},Ye.prototype.options={maxZoom:14,indexMaxZoom:5,indexMaxPoints:1e5,tolerance:3,extent:4096,buffer:64,lineMetrics:!1,debug:0},Ye.prototype.splitTile=function(e,t,i,r,n,o,a){for(var s=[e,t,i,r],l=this.options,u=l.debug;s.length;){r=s.pop(),i=s.pop(),t=s.pop(),e=s.pop();var h=1<<t,c=Ze(t,i,r),f=this.tiles[c];if(!f&&(u>1&&console.time("creation"),f=this.tiles[c]=Ve(e,t,i,r,l),this.tileCoords.push({z:t,x:i,y:r}),u)){u>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",t,i,r,f.numFeatures,f.numPoints,f.numSimplified),console.timeEnd("creation"));var p="z"+t;this.stats[p]=(this.stats[p]||0)+1,this.total++;}if(f.source=e,n){if(t===l.maxZoom||t===n)continue;var d=1<<n-t;if(i!==Math.floor(o/d)||r!==Math.floor(a/d))continue}else if(t===l.indexMaxZoom||f.numPoints<=l.indexMaxPoints)continue;if(f.source=null,0!==e.length){u>1&&console.time("clipping");var g,v,y,m,x,w,S=.5*l.buffer/l.extent,M=.5-S,b=.5+S,_=1+S;g=v=y=m=null,x=Le(e,h,i-S,i+b,0,f.minX,f.maxX,l),w=Le(e,h,i+M,i+_,0,f.minX,f.maxX,l),e=null,x&&(g=Le(x,h,r-S,r+b,1,f.minY,f.maxY,l),v=Le(x,h,r+M,r+_,1,f.minY,f.maxY,l),x=null),w&&(y=Le(w,h,r-S,r+b,1,f.minY,f.maxY,l),m=Le(w,h,r+M,r+_,1,f.minY,f.maxY,l),w=null),u>1&&console.timeEnd("clipping"),s.push(g||[],t+1,2*i,2*r),s.push(v||[],t+1,2*i,2*r+1),s.push(y||[],t+1,2*i+1,2*r),s.push(m||[],t+1,2*i+1,2*r+1);}}},Ye.prototype.getTile=function(e,t,i){var r=this.options,n=r.extent,o=r.debug;if(e<0||e>24)return null;var a=1<<e,s=Ze(e,t=(t%a+a)%a,i);if(this.tiles[s])return Fe(this.tiles[s],n);o>1&&console.log("drilling down to z%d-%d-%d",e,t,i);for(var l,u=e,h=t,c=i;!l&&u>0;)u--,h=Math.floor(h/2),c=Math.floor(c/2),l=this.tiles[Ze(u,h,c)];return l&&l.source?(o>1&&console.log("found parent tile z%d-%d-%d",u,h,c),o>1&&console.time("drilling down"),this.splitTile(l.source,u,h,c,e,t,i),o>1&&console.timeEnd("drilling down"),this.tiles[s]?Fe(this.tiles[s],n):null):null};var Xe=function(t){function i(e,i,r){t.call(this,e,i,je),r&&(this.loadGeoJSON=r);}return t&&(i.__proto__=t),i.prototype=Object.create(t&&t.prototype),i.prototype.constructor=i,i.prototype.loadData=function(e,t){this._pendingCallback&&this._pendingCallback(null,{abandoned:!0}),this._pendingCallback=t,this._pendingLoadDataParams=e,this._state&&"Idle"!==this._state?this._state="NeedsLoadData":(this._state="Coalescing",this._loadData());},i.prototype._loadData=function(){var e=this;if(this._pendingCallback&&this._pendingLoadDataParams){var t=this._pendingCallback,i=this._pendingLoadDataParams;delete this._pendingCallback,delete this._pendingLoadDataParams,this.loadGeoJSON(i,function(r,n){if(r||!n)return t(r);if("object"!=typeof n)return t(new Error("Input data is not a valid GeoJSON object."));$(n,!0);try{e._geoJSONIndex=i.cluster?he(i.superclusterOptions).load(n.features):function(e,t){return new Ye(e,t)}(n,i.geojsonVtOptions);}catch(r){return t(r)}e.loaded={};var o={};if(i.request&&i.request.collectResourceTiming){var a=M(i.request.url);a&&(o.resourceTiming={},o.resourceTiming[i.source]=JSON.parse(JSON.stringify(a)));}t(null,o);});}},i.prototype.coalesce=function(){"Coalescing"===this._state?this._state="Idle":"NeedsLoadData"===this._state&&(this._state="Coalescing",this._loadData());},i.prototype.reloadTile=function(e,i){var r=this.loaded,n=e.uid;return r&&r[n]?t.prototype.reloadTile.call(this,e,i):this.loadTile(e,i)},i.prototype.loadGeoJSON=function(t,i){if(t.request)e.getJSON(t.request,i);else{if("string"!=typeof t.data)return i(new Error("Input data is not a valid GeoJSON object."));try{return i(null,JSON.parse(t.data))}catch(e){return i(new Error("Input data is not a valid GeoJSON object."))}}},i.prototype.removeSource=function(e,t){this._pendingCallback&&this._pendingCallback(null,{abandoned:!0}),t();},i}(_),qe=function(t){var i=this;this.self=t,this.actor=new e.default$7(t,this),this.layerIndexes={},this.workerSourceTypes={vector:_,geojson:Xe},this.workerSources={},this.demWorkerSources={},this.self.registerWorkerSource=function(e,t){if(i.workerSourceTypes[e])throw new Error('Worker source with name "'+e+'" already registered.');i.workerSourceTypes[e]=t;},this.self.registerRTLTextPlugin=function(t){if(e.plugin.isLoaded())throw new Error("RTL text plugin already registered.");e.plugin.applyArabicShaping=t.applyArabicShaping,e.plugin.processBidirectionalText=t.processBidirectionalText;};};return qe.prototype.setLayers=function(e,t,i){this.getLayerIndex(e).replace(t),i();},qe.prototype.updateLayers=function(e,t,i){this.getLayerIndex(e).update(t.layers,t.removedIds),i();},qe.prototype.loadTile=function(e,t,i){this.getWorkerSource(e,t.type,t.source).loadTile(t,i);},qe.prototype.loadDEMTile=function(e,t,i){this.getDEMWorkerSource(e,t.source).loadTile(t,i);},qe.prototype.reloadTile=function(e,t,i){this.getWorkerSource(e,t.type,t.source).reloadTile(t,i);},qe.prototype.abortTile=function(e,t,i){this.getWorkerSource(e,t.type,t.source).abortTile(t,i);},qe.prototype.removeTile=function(e,t,i){this.getWorkerSource(e,t.type,t.source).removeTile(t,i);},qe.prototype.removeDEMTile=function(e,t){this.getDEMWorkerSource(e,t.source).removeTile(t);},qe.prototype.removeSource=function(e,t,i){if(this.workerSources[e]&&this.workerSources[e][t.type]&&this.workerSources[e][t.type][t.source]){var r=this.workerSources[e][t.type][t.source];delete this.workerSources[e][t.type][t.source],void 0!==r.removeSource?r.removeSource(t,i):i();}},qe.prototype.loadWorkerSource=function(e,t,i){try{this.self.importScripts(t.url),i();}catch(e){i(e.toString());}},qe.prototype.loadRTLTextPlugin=function(t,i,r){try{e.plugin.isLoaded()||(this.self.importScripts(i),r(e.plugin.isLoaded()?null:new Error("RTL Text Plugin failed to import scripts from "+i)));}catch(e){r(e.toString());}},qe.prototype.getLayerIndex=function(e){var t=this.layerIndexes[e];return t||(t=this.layerIndexes[e]=new r),t},qe.prototype.getWorkerSource=function(e,t,i){var r=this;if(this.workerSources[e]||(this.workerSources[e]={}),this.workerSources[e][t]||(this.workerSources[e][t]={}),!this.workerSources[e][t][i]){var n={send:function(t,i,n){r.actor.send(t,i,n,e);}};this.workerSources[e][t][i]=new this.workerSourceTypes[t](n,this.getLayerIndex(e));}return this.workerSources[e][t][i]},qe.prototype.getDEMWorkerSource=function(e,t){return this.demWorkerSources[e]||(this.demWorkerSources[e]={}),this.demWorkerSources[e][t]||(this.demWorkerSources[e][t]=new I),this.demWorkerSources[e][t]},"undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof self&&self instanceof WorkerGlobalScope&&new qe(self),qe});

define(["./chunk1.js"],function(t){"use strict";var e=t.createCommonjsModule(function(t){function e(t){return!!("undefined"!=typeof window&&"undefined"!=typeof document&&Array.prototype&&Array.prototype.every&&Array.prototype.filter&&Array.prototype.forEach&&Array.prototype.indexOf&&Array.prototype.lastIndexOf&&Array.prototype.map&&Array.prototype.some&&Array.prototype.reduce&&Array.prototype.reduceRight&&Array.isArray&&Function.prototype&&Function.prototype.bind&&Object.keys&&Object.create&&Object.getPrototypeOf&&Object.getOwnPropertyNames&&Object.isSealed&&Object.isFrozen&&Object.isExtensible&&Object.getOwnPropertyDescriptor&&Object.defineProperty&&Object.defineProperties&&Object.seal&&Object.freeze&&Object.preventExtensions&&"JSON"in window&&"parse"in JSON&&"stringify"in JSON&&function(){if(!("Worker"in window&&"Blob"in window&&"URL"in window))return!1;var t,e,i=new Blob([""],{type:"text/javascript"}),n=URL.createObjectURL(i);try{e=new Worker(n),t=!0;}catch(e){t=!1;}e&&e.terminate();return URL.revokeObjectURL(n),t}()&&"Uint8ClampedArray"in window&&function(t){void 0===i[t]&&(i[t]=function(t){var i=document.createElement("canvas"),n=Object.create(e.webGLContextAttributes);return n.failIfMajorPerformanceCaveat=t,i.probablySupportsContext?i.probablySupportsContext("webgl",n)||i.probablySupportsContext("experimental-webgl",n):i.supportsContext?i.supportsContext("webgl",n)||i.supportsContext("experimental-webgl",n):i.getContext("webgl",n)||i.getContext("experimental-webgl",n)}(t));return i[t]}(t&&t.failIfMajorPerformanceCaveat))}t.exports?t.exports=e:window&&(window.mapboxgl=window.mapboxgl||{},window.mapboxgl.supported=e);var i={};e.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0};}),i=t.default.performance&&t.default.performance.now?t.default.performance.now.bind(t.default.performance):Date.now.bind(Date),n=t.default.requestAnimationFrame||t.default.mozRequestAnimationFrame||t.default.webkitRequestAnimationFrame||t.default.msRequestAnimationFrame,o=t.default.cancelAnimationFrame||t.default.mozCancelAnimationFrame||t.default.webkitCancelAnimationFrame||t.default.msCancelAnimationFrame,r={now:i,frame:function(t){return n(t)},cancelFrame:function(t){return o(t)},getImageData:function(e){var i=t.default.document.createElement("canvas"),n=i.getContext("2d");if(!n)throw new Error("failed to create canvas 2d context");return i.width=e.width,i.height=e.height,n.drawImage(e,0,0,e.width,e.height),n.getImageData(0,0,e.width,e.height)},hardwareConcurrency:t.default.navigator.hardwareConcurrency||4,get devicePixelRatio(){return t.default.devicePixelRatio},supportsWebp:!1};if(t.default.document){var a=t.default.document.createElement("img");a.onload=function(){r.supportsWebp=!0;},a.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=";}var s={create:function(e,i,n){var o=t.default.document.createElement(e);return i&&(o.className=i),n&&n.appendChild(o),o},createNS:function(e,i){return t.default.document.createElementNS(e,i)}},l=t.default.document?t.default.document.documentElement.style:null;function c(t){if(!l)return null;for(var e=0;e<t.length;e++)if(t[e]in l)return t[e];return t[0]}var u,h=c(["userSelect","MozUserSelect","WebkitUserSelect","msUserSelect"]);s.disableDrag=function(){l&&h&&(u=l[h],l[h]="none");},s.enableDrag=function(){l&&h&&(l[h]=u);};var p=c(["transform","WebkitTransform"]);s.setTransform=function(t,e){t.style[p]=e;};var d=!1;try{var f=Object.defineProperty({},"passive",{get:function(){d=!0;}});t.default.addEventListener("test",f,f),t.default.removeEventListener("test",f,f);}catch(t){d=!1;}s.addEventListener=function(t,e,i,n){void 0===n&&(n={}),"passive"in n&&d?t.addEventListener(e,i,n):t.addEventListener(e,i,n.capture);},s.removeEventListener=function(t,e,i,n){void 0===n&&(n={}),"passive"in n&&d?t.removeEventListener(e,i,n):t.removeEventListener(e,i,n.capture);};var m=function(e){e.preventDefault(),e.stopPropagation(),t.default.removeEventListener("click",m,!0);};s.suppressClick=function(){t.default.addEventListener("click",m,!0),t.default.setTimeout(function(){t.default.removeEventListener("click",m,!0);},0);},s.mousePos=function(e,i){var n=e.getBoundingClientRect();return i=i.touches?i.touches[0]:i,new t.default$1(i.clientX-n.left-e.clientLeft,i.clientY-n.top-e.clientTop)},s.touchPos=function(e,i){for(var n=e.getBoundingClientRect(),o=[],r="touchend"===i.type?i.changedTouches:i.touches,a=0;a<r.length;a++)o.push(new t.default$1(r[a].clientX-n.left-e.clientLeft,r[a].clientY-n.top-e.clientTop));return o},s.mouseButton=function(e){return void 0!==t.default.InstallTrigger&&2===e.button&&e.ctrlKey&&t.default.navigator.platform.toUpperCase().indexOf("MAC")>=0?0:e.button},s.remove=function(t){t.parentNode&&t.parentNode.removeChild(t);};var _={API_URL:"https://api.mapbox.com",REQUIRE_ACCESS_TOKEN:!0,ACCESS_TOKEN:null},g="See https://www.mapbox.com/api-documentation/#access-tokens";function v(t,e){var i=C(_.API_URL);if(t.protocol=i.protocol,t.authority=i.authority,"/"!==i.path&&(t.path=""+i.path+t.path),!_.REQUIRE_ACCESS_TOKEN)return S(t);if(!(e=e||_.ACCESS_TOKEN))throw new Error("An API access token is required to use Mapbox GL. "+g);if("s"===e[0])throw new Error("Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). "+g);return t.params.push("access_token="+e),S(t)}function y(t){return 0===t.indexOf("mapbox:")}var x=function(t,e){if(!y(t))return t;var i=C(t);return i.path="/fonts/v1"+i.path,v(i,e)},b=function(t,e){if(!y(t))return t;var i=C(t);return i.path="/v4/"+i.authority+".json",i.params.push("secure"),v(i,e)},w=function(t,e,i,n){var o=C(t);return y(t)?(o.path="/styles/v1"+o.path+"/sprite"+e+i,v(o,n)):(o.path+=""+e+i,S(o))},E=/(\.(png|jpg)\d*)(?=$)/,T=function(t,e,i){if(!e||!y(e))return t;var n=C(t),o=r.devicePixelRatio>=2||512===i?"@2x":"",a=r.supportsWebp?".webp":"$1";return n.path=n.path.replace(E,""+o+a),function(t){for(var e=0;e<t.length;e++)0===t[e].indexOf("access_token=tk.")&&(t[e]="access_token="+(_.ACCESS_TOKEN||""));}(n.params),S(n)};var I=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function C(t){var e=t.match(I);if(!e)throw new Error("Unable to parse URL object");return{protocol:e[1],authority:e[2],path:e[3]||"/",params:e[4]?e[4].split("&"):[]}}function S(t){var e=t.params.length?"?"+t.params.join("&"):"";return t.protocol+"://"+t.authority+t.path+e}var z=t.default.HTMLImageElement,A=t.default.HTMLCanvasElement,R=t.default.HTMLVideoElement,D=t.default.ImageData,M=function(t,e,i,n){this.context=t,this.format=i,this.texture=t.gl.createTexture(),this.update(e,n);};M.prototype.update=function(t,e){var i=t.width,n=t.height,o=!this.size||this.size[0]!==i||this.size[1]!==n,r=this.context,a=r.gl;this.useMipmap=Boolean(e&&e.useMipmap),a.bindTexture(a.TEXTURE_2D,this.texture),o?(this.size=[i,n],r.pixelStoreUnpack.set(1),this.format!==a.RGBA||e&&!1===e.premultiply||r.pixelStoreUnpackPremultiplyAlpha.set(!0),t instanceof z||t instanceof A||t instanceof R||t instanceof D?a.texImage2D(a.TEXTURE_2D,0,this.format,this.format,a.UNSIGNED_BYTE,t):a.texImage2D(a.TEXTURE_2D,0,this.format,i,n,0,this.format,a.UNSIGNED_BYTE,t.data)):t instanceof z||t instanceof A||t instanceof R||t instanceof D?a.texSubImage2D(a.TEXTURE_2D,0,0,0,a.RGBA,a.UNSIGNED_BYTE,t):a.texSubImage2D(a.TEXTURE_2D,0,0,0,i,n,a.RGBA,a.UNSIGNED_BYTE,t.data),this.useMipmap&&this.isSizePowerOfTwo()&&a.generateMipmap(a.TEXTURE_2D);},M.prototype.bind=function(t,e,i){var n=this.context.gl;n.bindTexture(n.TEXTURE_2D,this.texture),i!==n.LINEAR_MIPMAP_NEAREST||this.isSizePowerOfTwo()||(i=n.LINEAR),t!==this.filter&&(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,t),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,i||t),this.filter=t),e!==this.wrap&&(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,e),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,e),this.wrap=e);},M.prototype.isSizePowerOfTwo=function(){return this.size[0]===this.size[1]&&Math.log(this.size[0])/Math.LN2%1==0},M.prototype.destroy=function(){this.context.gl.deleteTexture(this.texture),this.texture=null;};var L=function(){this.images={},this.loaded=!1,this.requestors=[],this.shelfPack=new t.default$2(64,64,{autoResize:!0}),this.patterns={},this.atlasImage=new t.RGBAImage({width:64,height:64}),this.dirty=!0;};L.prototype.isLoaded=function(){return this.loaded},L.prototype.setLoaded=function(t){if(this.loaded!==t&&(this.loaded=t,t)){for(var e=0,i=this.requestors;e<i.length;e+=1){var n=i[e],o=n.ids,r=n.callback;this._notify(o,r);}this.requestors=[];}},L.prototype.getImage=function(t){return this.images[t]},L.prototype.addImage=function(t,e){this.images[t]=e;},L.prototype.removeImage=function(t){delete this.images[t];var e=this.patterns[t];e&&(this.shelfPack.unref(e.bin),delete this.patterns[t]);},L.prototype.getImages=function(t,e){var i=!0;if(!this.isLoaded())for(var n=0,o=t;n<o.length;n+=1){var r=o[n];this.images[r]||(i=!1);}this.isLoaded()||i?this._notify(t,e):this.requestors.push({ids:t,callback:e});},L.prototype._notify=function(t,e){for(var i={},n=0,o=t;n<o.length;n+=1){var r=o[n],a=this.images[r];a&&(i[r]={data:a.data.clone(),pixelRatio:a.pixelRatio,sdf:a.sdf});}e(null,i);},L.prototype.getPixelSize=function(){return{width:this.shelfPack.w,height:this.shelfPack.h}},L.prototype.getPattern=function(e){var i=this.patterns[e];if(i)return i.position;var n=this.getImage(e);if(!n)return null;var o=n.data.width+2,r=n.data.height+2,a=this.shelfPack.packOne(o,r);if(!a)return null;this.atlasImage.resize(this.getPixelSize());var s=n.data,l=this.atlasImage,c=a.x+1,u=a.y+1,h=s.width,p=s.height;t.RGBAImage.copy(s,l,{x:0,y:0},{x:c,y:u},{width:h,height:p}),t.RGBAImage.copy(s,l,{x:0,y:p-1},{x:c,y:u-1},{width:h,height:1}),t.RGBAImage.copy(s,l,{x:0,y:0},{x:c,y:u+p},{width:h,height:1}),t.RGBAImage.copy(s,l,{x:h-1,y:0},{x:c-1,y:u},{width:1,height:p}),t.RGBAImage.copy(s,l,{x:0,y:0},{x:c+h,y:u},{width:1,height:p}),this.dirty=!0;var d=new t.ImagePosition(a,n);return this.patterns[e]={bin:a,position:d},d},L.prototype.bind=function(t){var e=t.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=!1):this.atlasTexture=new M(t,this.atlasImage,e.RGBA),this.atlasTexture.bind(e.LINEAR,e.CLAMP_TO_EDGE);};var P=B,k=1e20;function B(t,e,i,n,o,r){this.fontSize=t||24,this.buffer=void 0===e?3:e,this.cutoff=n||.25,this.fontFamily=o||"sans-serif",this.fontWeight=r||"normal",this.radius=i||8;var a=this.size=this.fontSize+2*this.buffer;this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=a,this.ctx=this.canvas.getContext("2d"),this.ctx.font=this.fontWeight+" "+this.fontSize+"px "+this.fontFamily,this.ctx.textBaseline="middle",this.ctx.fillStyle="black",this.gridOuter=new Float64Array(a*a),this.gridInner=new Float64Array(a*a),this.f=new Float64Array(a),this.d=new Float64Array(a),this.z=new Float64Array(a+1),this.v=new Int16Array(a),this.middle=Math.round(a/2*(navigator.userAgent.indexOf("Gecko/")>=0?1.2:1));}function O(t,e,i,n,o,r,a){for(var s=0;s<e;s++){for(var l=0;l<i;l++)n[l]=t[l*e+s];for(F(n,o,r,a,i),l=0;l<i;l++)t[l*e+s]=o[l];}for(l=0;l<i;l++){for(s=0;s<e;s++)n[s]=t[l*e+s];for(F(n,o,r,a,e),s=0;s<e;s++)t[l*e+s]=Math.sqrt(o[s]);}}function F(t,e,i,n,o){i[0]=0,n[0]=-k,n[1]=+k;for(var r=1,a=0;r<o;r++){for(var s=(t[r]+r*r-(t[i[a]]+i[a]*i[a]))/(2*r-2*i[a]);s<=n[a];)a--,s=(t[r]+r*r-(t[i[a]]+i[a]*i[a]))/(2*r-2*i[a]);i[++a]=r,n[a]=s,n[a+1]=+k;}for(r=0,a=0;r<o;r++){for(;n[a+1]<r;)a++;e[r]=(r-i[a])*(r-i[a])+t[i[a]];}}B.prototype.draw=function(t){this.ctx.clearRect(0,0,this.size,this.size),this.ctx.fillText(t,this.buffer,this.middle);for(var e=this.ctx.getImageData(0,0,this.size,this.size),i=new Uint8ClampedArray(this.size*this.size),n=0;n<this.size*this.size;n++){var o=e.data[4*n+3]/255;this.gridOuter[n]=1===o?0:0===o?k:Math.pow(Math.max(0,.5-o),2),this.gridInner[n]=1===o?k:0===o?0:Math.pow(Math.max(0,o-.5),2);}for(O(this.gridOuter,this.size,this.size,this.f,this.d,this.v,this.z),O(this.gridInner,this.size,this.size,this.f,this.d,this.v,this.z),n=0;n<this.size*this.size;n++){var r=this.gridOuter[n]-this.gridInner[n];i[n]=Math.max(0,Math.min(255,Math.round(255-255*(r/this.radius+this.cutoff))));}return i};var N=function(t,e){this.requestTransform=t,this.localIdeographFontFamily=e,this.entries={};};N.prototype.setURL=function(t){this.url=t;},N.prototype.getGlyphs=function(e,i){var n=this,o=[];for(var r in e)for(var a=0,s=e[r];a<s.length;a+=1){var l=s[a];o.push({stack:r,id:l});}t.asyncAll(o,function(t,e){var i=t.stack,o=t.id,r=n.entries[i];r||(r=n.entries[i]={glyphs:{},requests:{}});var a=r.glyphs[o];if(void 0===a)if(a=n._tinySDF(r,i,o))e(null,{stack:i,id:o,glyph:a});else{var s=Math.floor(o/256);if(256*s>65535)e(new Error("glyphs > 65535 not supported"));else{var l=r.requests[s];l||(l=r.requests[s]=[],N.loadGlyphRange(i,s,n.url,n.requestTransform,function(t,e){if(e)for(var i in e)r.glyphs[+i]=e[+i];for(var n=0,o=l;n<o.length;n+=1){(0,o[n])(t,e);}delete r.requests[s];})),l.push(function(t,n){t?e(t):n&&e(null,{stack:i,id:o,glyph:n[o]||null});});}}else e(null,{stack:i,id:o,glyph:a});},function(t,e){if(t)i(t);else if(e){for(var n={},o=0,r=e;o<r.length;o+=1){var a=r[o],s=a.stack,l=a.id,c=a.glyph;(n[s]||(n[s]={}))[l]=c&&{id:c.id,bitmap:c.bitmap.clone(),metrics:c.metrics};}i(null,n);}});},N.prototype._tinySDF=function(e,i,n){var o=this.localIdeographFontFamily;if(o&&(t.default$4["CJK Unified Ideographs"](n)||t.default$4["Hangul Syllables"](n))){var r=e.tinySDF;if(!r){var a="400";/bold/i.test(i)?a="900":/medium/i.test(i)?a="500":/light/i.test(i)&&(a="200"),r=e.tinySDF=new N.TinySDF(24,3,8,.25,o,a);}return{id:n,bitmap:new t.AlphaImage({width:30,height:30},r.draw(String.fromCharCode(n))),metrics:{width:24,height:24,left:0,top:-8,advance:24}}}},N.loadGlyphRange=function(e,i,n,o,r){var a=256*i,s=a+255,l=o(x(n).replace("{fontstack}",e).replace("{range}",a+"-"+s),t.ResourceType.Glyphs);t.getArrayBuffer(l,function(e,i){if(e)r(e);else if(i){for(var n={},o=0,a=t.default$3(i.data);o<a.length;o+=1){var s=a[o];n[s.id]=s;}r(null,n);}});},N.TinySDF=P;var U=function(){this.specification=t.default$5.light.position;};U.prototype.possiblyEvaluate=function(e,i){return t.sphericalToCartesian(e.expression.evaluate(i))},U.prototype.interpolate=function(e,i,n){return{x:t.number(e.x,i.x,n),y:t.number(e.y,i.y,n),z:t.number(e.z,i.z,n)}};var Z=new t.Properties({anchor:new t.DataConstantProperty(t.default$5.light.anchor),position:new U,color:new t.DataConstantProperty(t.default$5.light.color),intensity:new t.DataConstantProperty(t.default$5.light.intensity)}),V=function(e){function i(i){e.call(this),this._transitionable=new t.Transitionable(Z),this.setLight(i),this._transitioning=this._transitionable.untransitioned();}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.getLight=function(){return this._transitionable.serialize()},i.prototype.setLight=function(e){if(!this._validate(t.validateLight,e))for(var i in e){var n=e[i];t.endsWith(i,"-transition")?this._transitionable.setTransition(i.slice(0,-"-transition".length),n):this._transitionable.setValue(i,n);}},i.prototype.updateTransitions=function(t){this._transitioning=this._transitionable.transitioned(t,this._transitioning);},i.prototype.hasTransition=function(){return this._transitioning.hasTransition()},i.prototype.recalculate=function(t){this.properties=this._transitioning.possiblyEvaluate(t);},i.prototype._validate=function(e,i){return t.emitValidationErrors(this,e.call(t.validateStyle,t.extend({value:i,style:{glyphs:!0,sprite:!0},styleSpec:t.default$5})))},i}(t.Evented),j=function(t,e){this.width=t,this.height=e,this.nextRow=0,this.bytes=4,this.data=new Uint8Array(this.width*this.height*this.bytes),this.positions={};};j.prototype.getDash=function(t,e){var i=t.join(",")+String(e);return this.positions[i]||(this.positions[i]=this.addDash(t,e)),this.positions[i]},j.prototype.addDash=function(e,i){var n=i?7:0,o=2*n+1;if(this.nextRow+o>this.height)return t.warnOnce("LineAtlas out of space"),null;for(var r=0,a=0;a<e.length;a++)r+=e[a];for(var s=this.width/r,l=s/2,c=e.length%2==1,u=-n;u<=n;u++)for(var h=this.nextRow+n+u,p=this.width*h,d=c?-e[e.length-1]:0,f=e[0],m=1,_=0;_<this.width;_++){for(;f<_/s;)d=f,f+=e[m],c&&m===e.length-1&&(f+=e[0]),m++;var g=Math.abs(_-d*s),v=Math.abs(_-f*s),y=Math.min(g,v),x=m%2==1,b=void 0;if(i){var w=n?u/n*(l+1):0;if(x){var E=l-Math.abs(w);b=Math.sqrt(y*y+E*E);}else b=l-Math.sqrt(y*y+w*w);}else b=(x?1:-1)*y;this.data[3+4*(p+_)]=Math.max(0,Math.min(255,b+128));}var T={y:(this.nextRow+n+.5)/this.height,height:2*n/this.height,width:r};return this.nextRow+=o,this.dirty=!0,T},j.prototype.bind=function(t){var e=t.gl;this.texture?(e.bindTexture(e.TEXTURE_2D,this.texture),this.dirty&&(this.dirty=!1,e.texSubImage2D(e.TEXTURE_2D,0,0,0,this.width,this.height,e.RGBA,e.UNSIGNED_BYTE,this.data))):(this.texture=e.createTexture(),e.bindTexture(e.TEXTURE_2D,this.texture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,this.width,this.height,0,e.RGBA,e.UNSIGNED_BYTE,this.data));};var $=function e(i,n){this.workerPool=i,this.actors=[],this.currentActor=0,this.id=t.uniqueId();for(var o=this.workerPool.acquire(this.id),r=0;r<o.length;r++){var a=o[r],s=new e.Actor(a,n,this.id);s.name="Worker "+r,this.actors.push(s);}};function G(e,i,n){var o=function(e,i){if(e)return n(e);if(i){var o=t.pick(i,["tiles","minzoom","maxzoom","attribution","mapbox_logo","bounds"]);i.vector_layers&&(o.vectorLayers=i.vector_layers,o.vectorLayerIds=o.vectorLayers.map(function(t){return t.id})),n(null,o);}};e.url?t.getJSON(i(b(e.url),t.ResourceType.Source),o):r.frame(function(){return o(null,e)});}$.prototype.broadcast=function(e,i,n){n=n||function(){},t.asyncAll(this.actors,function(t,n){t.send(e,i,n);},n);},$.prototype.send=function(t,e,i,n){return("number"!=typeof n||isNaN(n))&&(n=this.currentActor=(this.currentActor+1)%this.actors.length),this.actors[n].send(t,e,i),n},$.prototype.remove=function(){this.actors.forEach(function(t){t.remove();}),this.actors=[],this.workerPool.release(this.id);},$.Actor=t.default$7;var W=function(t,e){if(isNaN(t)||isNaN(e))throw new Error("Invalid LngLat object: ("+t+", "+e+")");if(this.lng=+t,this.lat=+e,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")};W.prototype.wrap=function(){return new W(t.wrap(this.lng,-180,180),this.lat)},W.prototype.toArray=function(){return[this.lng,this.lat]},W.prototype.toString=function(){return"LngLat("+this.lng+", "+this.lat+")"},W.prototype.toBounds=function(t){var e=360*t/40075017,i=e/Math.cos(Math.PI/180*this.lat);return new q(new W(this.lng-i,this.lat-e),new W(this.lng+i,this.lat+e))},W.convert=function(t){if(t instanceof W)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new W(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new W(Number(t.lng),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: <lng>, lat: <lat>}, or an array of [<lng>, <lat>]")};var q=function(t,e){t&&(e?this.setSouthWest(t).setNorthEast(e):4===t.length?this.setSouthWest([t[0],t[1]]).setNorthEast([t[2],t[3]]):this.setSouthWest(t[0]).setNorthEast(t[1]));};q.prototype.setNorthEast=function(t){return this._ne=t instanceof W?new W(t.lng,t.lat):W.convert(t),this},q.prototype.setSouthWest=function(t){return this._sw=t instanceof W?new W(t.lng,t.lat):W.convert(t),this},q.prototype.extend=function(t){var e,i,n=this._sw,o=this._ne;if(t instanceof W)e=t,i=t;else{if(!(t instanceof q))return Array.isArray(t)?t.every(Array.isArray)?this.extend(q.convert(t)):this.extend(W.convert(t)):this;if(e=t._sw,i=t._ne,!e||!i)return this}return n||o?(n.lng=Math.min(e.lng,n.lng),n.lat=Math.min(e.lat,n.lat),o.lng=Math.max(i.lng,o.lng),o.lat=Math.max(i.lat,o.lat)):(this._sw=new W(e.lng,e.lat),this._ne=new W(i.lng,i.lat)),this},q.prototype.getCenter=function(){return new W((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)},q.prototype.getSouthWest=function(){return this._sw},q.prototype.getNorthEast=function(){return this._ne},q.prototype.getNorthWest=function(){return new W(this.getWest(),this.getNorth())},q.prototype.getSouthEast=function(){return new W(this.getEast(),this.getSouth())},q.prototype.getWest=function(){return this._sw.lng},q.prototype.getSouth=function(){return this._sw.lat},q.prototype.getEast=function(){return this._ne.lng},q.prototype.getNorth=function(){return this._ne.lat},q.prototype.toArray=function(){return[this._sw.toArray(),this._ne.toArray()]},q.prototype.toString=function(){return"LngLatBounds("+this._sw.toString()+", "+this._ne.toString()+")"},q.prototype.isEmpty=function(){return!(this._sw&&this._ne)},q.convert=function(t){return!t||t instanceof q?t:new q(t)};var X=function(t,e,i){this.bounds=q.convert(this.validateBounds(t)),this.minzoom=e||0,this.maxzoom=i||24;};X.prototype.validateBounds=function(t){return Array.isArray(t)&&4===t.length?[Math.max(-180,t[0]),Math.max(-90,t[1]),Math.min(180,t[2]),Math.min(90,t[3])]:[-180,-90,180,90]},X.prototype.contains=function(t){var e=Math.floor(this.lngX(this.bounds.getWest(),t.z)),i=Math.floor(this.latY(this.bounds.getNorth(),t.z)),n=Math.ceil(this.lngX(this.bounds.getEast(),t.z)),o=Math.ceil(this.latY(this.bounds.getSouth(),t.z));return t.x>=e&&t.x<n&&t.y>=i&&t.y<o},X.prototype.lngX=function(t,e){return(t+180)*(Math.pow(2,e)/360)},X.prototype.latY=function(e,i){var n=t.clamp(Math.sin(Math.PI/180*e),-.9999,.9999),o=Math.pow(2,i)/(2*Math.PI);return Math.pow(2,i-1)+.5*Math.log((1+n)/(1-n))*-o};var H=function(e){function i(i,n,o,r){if(e.call(this),this.id=i,this.dispatcher=o,this.type="vector",this.minzoom=0,this.maxzoom=22,this.scheme="xyz",this.tileSize=512,this.reparseOverscaled=!0,this.isTileClipped=!0,t.extend(this,t.pick(n,["url","scheme","tileSize"])),this._options=t.extend({type:"vector"},n),this._collectResourceTiming=n.collectResourceTiming,512!==this.tileSize)throw new Error("vector tile sources must have a tileSize of 512");this.setEventedParent(r);}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.load=function(){var e=this;this.fire(new t.Event("dataloading",{dataType:"source"})),G(this._options,this.map._transformRequest,function(i,n){i?e.fire(new t.ErrorEvent(i)):n&&(t.extend(e,n),n.bounds&&(e.tileBounds=new X(n.bounds,e.minzoom,e.maxzoom)),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"content"})));});},i.prototype.hasTile=function(t){return!this.tileBounds||this.tileBounds.contains(t.canonical)},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.serialize=function(){return t.extend({},this._options)},i.prototype.loadTile=function(e,i){var n=T(e.tileID.canonical.url(this.tiles,this.scheme),this.url),o={request:this.map._transformRequest(n,t.ResourceType.Tile),uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,tileSize:this.tileSize*e.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:r.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes};function a(t,n){return e.aborted?i(null):t?i(t):(n&&n.resourceTiming&&(e.resourceTiming=n.resourceTiming),this.map._refreshExpiredTiles&&e.setExpiryData(n),e.loadVectorData(n,this.map.painter),i(null),void(e.reloadCallback&&(this.loadTile(e,e.reloadCallback),e.reloadCallback=null)))}o.request.collectResourceTiming=this._collectResourceTiming,void 0===e.workerID||"expired"===e.state?e.workerID=this.dispatcher.send("loadTile",o,a.bind(this)):"loading"===e.state?e.reloadCallback=i:this.dispatcher.send("reloadTile",o,a.bind(this),e.workerID);},i.prototype.abortTile=function(t){this.dispatcher.send("abortTile",{uid:t.uid,type:this.type,source:this.id},void 0,t.workerID);},i.prototype.unloadTile=function(t){t.unloadVectorData(),this.dispatcher.send("removeTile",{uid:t.uid,type:this.type,source:this.id},void 0,t.workerID);},i.prototype.hasTransition=function(){return!1},i}(t.Evented),K=function(e){function i(i,n,o,r){e.call(this),this.id=i,this.dispatcher=o,this.setEventedParent(r),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=t.extend({},n),t.extend(this,t.pick(n,["url","scheme","tileSize"]));}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.load=function(){var e=this;this.fire(new t.Event("dataloading",{dataType:"source"})),G(this._options,this.map._transformRequest,function(i,n){i?e.fire(new t.ErrorEvent(i)):n&&(t.extend(e,n),n.bounds&&(e.tileBounds=new X(n.bounds,e.minzoom,e.maxzoom)),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"content"})));});},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.serialize=function(){return t.extend({},this._options)},i.prototype.hasTile=function(t){return!this.tileBounds||this.tileBounds.contains(t.canonical)},i.prototype.loadTile=function(e,i){var n=this,o=T(e.tileID.canonical.url(this.tiles,this.scheme),this.url,this.tileSize);e.request=t.getImage(this.map._transformRequest(o,t.ResourceType.Tile),function(t,o){if(delete e.request,e.aborted)e.state="unloaded",i(null);else if(t)e.state="errored",i(t);else if(o){n.map._refreshExpiredTiles&&e.setExpiryData(o),delete o.cacheControl,delete o.expires;var r=n.map.painter.context,a=r.gl;e.texture=n.map.painter.getTileTexture(o.width),e.texture?e.texture.update(o,{useMipmap:!0}):(e.texture=new M(r,o,a.RGBA,{useMipmap:!0}),e.texture.bind(a.LINEAR,a.CLAMP_TO_EDGE,a.LINEAR_MIPMAP_NEAREST),r.extTextureFilterAnisotropic&&a.texParameterf(a.TEXTURE_2D,r.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,r.extTextureFilterAnisotropicMax)),e.state="loaded",i(null);}});},i.prototype.abortTile=function(t,e){t.request&&(t.request.abort(),delete t.request),e();},i.prototype.unloadTile=function(t,e){t.texture&&this.map.painter.saveTileTexture(t.texture),e();},i.prototype.hasTransition=function(){return!1},i}(t.Evented),Y=function(e){function i(i,n,o,r){e.call(this,i,n,o,r),this.type="raster-dem",this.maxzoom=22,this._options=t.extend({},n),this.encoding=n.encoding||"mapbox";}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.serialize=function(){return{type:"raster-dem",url:this.url,tileSize:this.tileSize,tiles:this.tiles,bounds:this.bounds,encoding:this.encoding}},i.prototype.loadTile=function(e,i){var n=T(e.tileID.canonical.url(this.tiles,this.scheme),this.url,this.tileSize);e.request=t.getImage(this.map._transformRequest(n,t.ResourceType.Tile),function(t,n){if(delete e.request,e.aborted)e.state="unloaded",i(null);else if(t)e.state="errored",i(t);else if(n){this.map._refreshExpiredTiles&&e.setExpiryData(n),delete n.cacheControl,delete n.expires;var o=r.getImageData(n),a={uid:e.uid,coord:e.tileID,source:this.id,rawImageData:o,encoding:this.encoding};e.workerID&&"expired"!==e.state||(e.workerID=this.dispatcher.send("loadDEMTile",a,function(t,n){t&&(e.state="errored",i(t));n&&(e.dem=n,e.needsHillshadePrepare=!0,e.state="loaded",i(null));}.bind(this)));}}.bind(this)),e.neighboringTiles=this._getNeighboringTiles(e.tileID);},i.prototype._getNeighboringTiles=function(e){var i=e.canonical,n=Math.pow(2,i.z),o=(i.x-1+n)%n,r=0===i.x?e.wrap-1:e.wrap,a=(i.x+1+n)%n,s=i.x+1===n?e.wrap+1:e.wrap,l={};return l[new t.OverscaledTileID(e.overscaledZ,r,i.z,o,i.y).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,s,i.z,a,i.y).key]={backfilled:!1},i.y>0&&(l[new t.OverscaledTileID(e.overscaledZ,r,i.z,o,i.y-1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,e.wrap,i.z,i.x,i.y-1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,s,i.z,a,i.y-1).key]={backfilled:!1}),i.y+1<n&&(l[new t.OverscaledTileID(e.overscaledZ,r,i.z,o,i.y+1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,e.wrap,i.z,i.x,i.y+1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,s,i.z,a,i.y+1).key]={backfilled:!1}),l},i.prototype.unloadTile=function(t){t.demTexture&&this.map.painter.saveTileTexture(t.demTexture),t.fbo&&(t.fbo.destroy(),delete t.fbo),t.dem&&delete t.dem,delete t.neighboringTiles,t.state="unloaded",this.dispatcher.send("removeDEMTile",{uid:t.uid,source:this.id},void 0,t.workerID);},i}(K),J=function(e){function i(i,n,o,r){e.call(this),this.id=i,this.type="geojson",this.minzoom=0,this.maxzoom=18,this.tileSize=512,this.isTileClipped=!0,this.reparseOverscaled=!0,this._removed=!1,this.dispatcher=o,this.setEventedParent(r),this._data=n.data,this._options=t.extend({},n),this._collectResourceTiming=n.collectResourceTiming,this._resourceTiming=[],void 0!==n.maxzoom&&(this.maxzoom=n.maxzoom),n.type&&(this.type=n.type);var a=t.default$8/this.tileSize;this.workerOptions=t.extend({source:this.id,cluster:n.cluster||!1,geojsonVtOptions:{buffer:(void 0!==n.buffer?n.buffer:128)*a,tolerance:(void 0!==n.tolerance?n.tolerance:.375)*a,extent:t.default$8,maxZoom:this.maxzoom,lineMetrics:n.lineMetrics||!1},superclusterOptions:{maxZoom:void 0!==n.clusterMaxZoom?Math.min(n.clusterMaxZoom,this.maxzoom-1):this.maxzoom-1,extent:t.default$8,radius:(n.clusterRadius||50)*a,log:!1}},n.workerOptions);}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.load=function(){var e=this;this.fire(new t.Event("dataloading",{dataType:"source"})),this._updateWorkerData(function(i){if(i)e.fire(new t.ErrorEvent(i));else{var n={dataType:"source",sourceDataType:"metadata"};e._collectResourceTiming&&e._resourceTiming&&e._resourceTiming.length>0&&(n.resourceTiming=e._resourceTiming,e._resourceTiming=[]),e.fire(new t.Event("data",n));}});},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.setData=function(e){var i=this;return this._data=e,this.fire(new t.Event("dataloading",{dataType:"source"})),this._updateWorkerData(function(e){if(e)return i.fire(new t.ErrorEvent(e));var n={dataType:"source",sourceDataType:"content"};i._collectResourceTiming&&i._resourceTiming&&i._resourceTiming.length>0&&(n.resourceTiming=i._resourceTiming,i._resourceTiming=[]),i.fire(new t.Event("data",n));}),this},i.prototype._updateWorkerData=function(e){var i,n,o=this,r=t.extend({},this.workerOptions),a=this._data;"string"==typeof a?(r.request=this.map._transformRequest((i=a,(n=t.default.document.createElement("a")).href=i,n.href),t.ResourceType.Source),r.request.collectResourceTiming=this._collectResourceTiming):r.data=JSON.stringify(a),this.workerID=this.dispatcher.send(this.type+"."+r.source+".loadData",r,function(t,i){o._removed||i&&i.abandoned||(o._loaded=!0,i&&i.resourceTiming&&i.resourceTiming[o.id]&&(o._resourceTiming=i.resourceTiming[o.id].slice(0)),o.dispatcher.send(o.type+"."+r.source+".coalesce",null,null,o.workerID),e(t));},this.workerID);},i.prototype.loadTile=function(t,e){var i=this,n=void 0===t.workerID?"loadTile":"reloadTile",o={type:this.type,uid:t.uid,tileID:t.tileID,zoom:t.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:r.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes};t.workerID=this.dispatcher.send(n,o,function(o,r){return t.unloadVectorData(),t.aborted?e(null):o?e(o):(t.loadVectorData(r,i.map.painter,"reloadTile"===n),e(null))},this.workerID);},i.prototype.abortTile=function(t){t.aborted=!0;},i.prototype.unloadTile=function(t){t.unloadVectorData(),this.dispatcher.send("removeTile",{uid:t.uid,type:this.type,source:this.id},null,t.workerID);},i.prototype.onRemove=function(){this._removed=!0,this.dispatcher.send("removeSource",{type:this.type,source:this.id},null,this.workerID);},i.prototype.serialize=function(){return t.extend({},this._options,{type:this.type,data:this._data})},i.prototype.hasTransition=function(){return!1},i}(t.Evented);var Q=t.createLayout([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]),tt=function(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null;};tt.prototype.bind=function(t,e,i,n,o,r,a,s){this.context=t;for(var l=this.boundPaintVertexBuffers.length!==n.length,c=0;!l&&c<n.length;c++)this.boundPaintVertexBuffers[c]!==n[c]&&(l=!0);var u=!this.vao||this.boundProgram!==e||this.boundLayoutVertexBuffer!==i||l||this.boundIndexBuffer!==o||this.boundVertexOffset!==r||this.boundDynamicVertexBuffer!==a||this.boundDynamicVertexBuffer2!==s;!t.extVertexArrayObject||u?this.freshBind(e,i,n,o,r,a,s):(t.bindVertexArrayOES.set(this.vao),a&&a.bind(),o&&o.dynamicDraw&&o.bind(),s&&s.bind());},tt.prototype.freshBind=function(t,e,i,n,o,r,a){var s,l=t.numAttributes,c=this.context,u=c.gl;if(c.extVertexArrayObject)this.vao&&this.destroy(),this.vao=c.extVertexArrayObject.createVertexArrayOES(),c.bindVertexArrayOES.set(this.vao),s=0,this.boundProgram=t,this.boundLayoutVertexBuffer=e,this.boundPaintVertexBuffers=i,this.boundIndexBuffer=n,this.boundVertexOffset=o,this.boundDynamicVertexBuffer=r,this.boundDynamicVertexBuffer2=a;else{s=c.currentNumAttributes||0;for(var h=l;h<s;h++)u.disableVertexAttribArray(h);}e.enableAttributes(u,t);for(var p=0,d=i;p<d.length;p+=1){d[p].enableAttributes(u,t);}r&&r.enableAttributes(u,t),a&&a.enableAttributes(u,t),e.bind(),e.setVertexAttribPointers(u,t,o);for(var f=0,m=i;f<m.length;f+=1){var _=m[f];_.bind(),_.setVertexAttribPointers(u,t,o);}r&&(r.bind(),r.setVertexAttribPointers(u,t,o)),n&&n.bind(),a&&(a.bind(),a.setVertexAttribPointers(u,t,o)),c.currentNumAttributes=l;},tt.prototype.destroy=function(){this.vao&&(this.context.extVertexArrayObject.deleteVertexArrayOES(this.vao),this.vao=null);};var et=function(e){function i(t,i,n,o){e.call(this),this.id=t,this.dispatcher=n,this.coordinates=i.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this.setEventedParent(o),this.options=i;}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.load=function(){var e=this;this.fire(new t.Event("dataloading",{dataType:"source"})),this.url=this.options.url,t.getImage(this.map._transformRequest(this.url,t.ResourceType.Image),function(i,n){i?e.fire(new t.ErrorEvent(i)):n&&(e.image=r.getImageData(n),e._finishLoading());});},i.prototype._finishLoading=function(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})));},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.setCoordinates=function(e){this.coordinates=e;var i=this.map,n=e.map(function(t){return i.transform.locationCoordinate(W.convert(t)).zoomTo(0)}),o=this.centerCoord=t.getCoordinatesCenter(n);o.column=Math.floor(o.column),o.row=Math.floor(o.row),this.tileID=new t.CanonicalTileID(o.zoom,o.column,o.row),this.minzoom=this.maxzoom=o.zoom;var r=n.map(function(e){var i=e.zoomTo(o.zoom);return new t.default$1(Math.round((i.column-o.column)*t.default$8),Math.round((i.row-o.row)*t.default$8))});return this._boundsArray=new t.RasterBoundsArray,this._boundsArray.emplaceBack(r[0].x,r[0].y,0,0),this._boundsArray.emplaceBack(r[1].x,r[1].y,t.default$8,0),this._boundsArray.emplaceBack(r[3].x,r[3].y,0,t.default$8),this._boundsArray.emplaceBack(r[2].x,r[2].y,t.default$8,t.default$8),this.boundsBuffer&&(this.boundsBuffer.destroy(),delete this.boundsBuffer),this.fire(new t.Event("data",{dataType:"source",sourceDataType:"content"})),this},i.prototype.prepare=function(){if(0!==Object.keys(this.tiles).length&&this.image){var t=this.map.painter.context,e=t.gl;for(var i in this.boundsBuffer||(this.boundsBuffer=t.createVertexBuffer(this._boundsArray,Q.members)),this.boundsVAO||(this.boundsVAO=new tt),this.texture||(this.texture=new M(t,this.image,e.RGBA),this.texture.bind(e.LINEAR,e.CLAMP_TO_EDGE)),this.tiles){var n=this.tiles[i];"loaded"!==n.state&&(n.state="loaded",n.texture=this.texture);}}},i.prototype.loadTile=function(t,e){this.tileID&&this.tileID.equals(t.tileID.canonical)?(this.tiles[String(t.tileID.wrap)]=t,t.buckets={},e(null)):(t.state="errored",e(null));},i.prototype.serialize=function(){return{type:"image",url:this.options.url,coordinates:this.coordinates}},i.prototype.hasTransition=function(){return!1},i}(t.Evented),it=function(e){function i(t,i,n,o){e.call(this,t,i,n,o),this.roundZoom=!0,this.type="video",this.options=i;}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.load=function(){var e=this,i=this.options;this.urls=[];for(var n=0,o=i.urls;n<o.length;n+=1){var r=o[n];e.urls.push(e.map._transformRequest(r,t.ResourceType.Source).url);}t.getVideo(this.urls,function(i,n){i?e.fire(new t.ErrorEvent(i)):n&&(e.video=n,e.video.loop=!0,e.video.addEventListener("playing",function(){e.map._rerender();}),e.map&&e.video.play(),e._finishLoading());});},i.prototype.getVideo=function(){return this.video},i.prototype.onAdd=function(t){this.map||(this.map=t,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)));},i.prototype.prepare=function(){if(!(0===Object.keys(this.tiles).length||this.video.readyState<2)){var t=this.map.painter.context,e=t.gl;for(var i in this.boundsBuffer||(this.boundsBuffer=t.createVertexBuffer(this._boundsArray,Q.members)),this.boundsVAO||(this.boundsVAO=new tt),this.texture?this.video.paused||(this.texture.bind(e.LINEAR,e.CLAMP_TO_EDGE),e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,this.video)):(this.texture=new M(t,this.video,e.RGBA),this.texture.bind(e.LINEAR,e.CLAMP_TO_EDGE)),this.tiles){var n=this.tiles[i];"loaded"!==n.state&&(n.state="loaded",n.texture=this.texture);}}},i.prototype.serialize=function(){return{type:"video",urls:this.urls,coordinates:this.coordinates}},i.prototype.hasTransition=function(){return this.video&&!this.video.paused},i}(et),nt=function(e){function i(i,n,o,r){e.call(this,i,n,o,r),n.coordinates?Array.isArray(n.coordinates)&&4===n.coordinates.length&&!n.coordinates.some(function(t){return!Array.isArray(t)||2!==t.length||t.some(function(t){return"number"!=typeof t})})||this.fire(new t.ErrorEvent(new t.default$9("sources."+i,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new t.ErrorEvent(new t.default$9("sources."+i,null,'missing required property "coordinates"'))),n.animate&&"boolean"!=typeof n.animate&&this.fire(new t.ErrorEvent(new t.default$9("sources."+i,null,'optional "animate" property must be a boolean value'))),n.canvas?"string"==typeof n.canvas||n.canvas instanceof t.default.HTMLCanvasElement||this.fire(new t.ErrorEvent(new t.default$9("sources."+i,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new t.ErrorEvent(new t.default$9("sources."+i,null,'missing required property "canvas"'))),this.options=n,this.animate=void 0===n.animate||n.animate;}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.load=function(){this.canvas||(this.canvas=this.options.canvas instanceof t.default.HTMLCanvasElement?this.options.canvas:t.default.document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new t.ErrorEvent(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map._rerender();},this.pause=function(){this._playing=!1;},this._finishLoading());},i.prototype.getCanvas=function(){return this.canvas},i.prototype.onAdd=function(t){this.map=t,this.load(),this.canvas&&this.animate&&this.play();},i.prototype.onRemove=function(){this.pause();},i.prototype.prepare=function(){var t=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,t=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,t=!0),!this._hasInvalidDimensions()&&0!==Object.keys(this.tiles).length){var e=this.map.painter.context,i=e.gl;for(var n in this.boundsBuffer||(this.boundsBuffer=e.createVertexBuffer(this._boundsArray,Q.members)),this.boundsVAO||(this.boundsVAO=new tt),this.texture?t?this.texture.update(this.canvas):this._playing&&(this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE),i.texSubImage2D(i.TEXTURE_2D,0,0,0,i.RGBA,i.UNSIGNED_BYTE,this.canvas)):(this.texture=new M(e,this.canvas,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE)),this.tiles){var o=this.tiles[n];"loaded"!==o.state&&(o.state="loaded",o.texture=this.texture);}}},i.prototype.serialize=function(){return{type:"canvas",coordinates:this.coordinates}},i.prototype.hasTransition=function(){return this._playing},i.prototype._hasInvalidDimensions=function(){for(var t=0,e=[this.canvas.width,this.canvas.height];t<e.length;t+=1){var i=e[t];if(isNaN(i)||i<=0)return!0}return!1},i}(et),ot={vector:H,raster:K,"raster-dem":Y,geojson:J,video:it,image:et,canvas:nt},rt=function(e,i,n,o){var r=new ot[i.type](e,i,n,o);if(r.id!==e)throw new Error("Expected Source id to be "+e+" instead of "+r.id);return t.bindAll(["load","abort","unload","serialize","prepare"],r),r};function at(t,e,i,n,o){var r=o.maxPitchScaleFactor(),a=t.tilesIn(i,r);a.sort(st);for(var s=[],l=0,c=a;l<c.length;l+=1){var u=c[l];s.push({wrappedTileID:u.tileID.wrapped().key,queryResults:u.tile.queryRenderedFeatures(e,u.queryGeometry,u.scale,n,o,r,t.transform.calculatePosMatrix(u.tileID.toUnwrapped()))});}return function(t){for(var e={},i={},n=0,o=t;n<o.length;n+=1){var r=o[n],a=r.queryResults,s=r.wrappedTileID,l=i[s]=i[s]||{};for(var c in a)for(var u=a[c],h=l[c]=l[c]||{},p=e[c]=e[c]||[],d=0,f=u;d<f.length;d+=1){var m=f[d];h[m.featureIndex]||(h[m.featureIndex]=!0,p.push(m.feature));}}return e}(s)}function st(t,e){var i=t.tileID,n=e.tileID;return i.overscaledZ-n.overscaledZ||i.canonical.y-n.canonical.y||i.wrap-n.wrap||i.canonical.x-n.canonical.x}var lt=function(e,i){this.tileID=e,this.uid=t.uniqueId(),this.uses=0,this.tileSize=i,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.expiredRequestCount=0,this.state="loading";};lt.prototype.registerFadeDuration=function(t){var e=t+this.timeAdded;e<r.now()||this.fadeEndTime&&e<this.fadeEndTime||(this.fadeEndTime=e);},lt.prototype.wasRequested=function(){return"errored"===this.state||"loaded"===this.state||"reloading"===this.state},lt.prototype.loadVectorData=function(e,i,n){if(this.hasData()&&this.unloadVectorData(),this.state="loaded",e){if(e.featureIndex&&(this.latestFeatureIndex=e.featureIndex,e.rawTileData?(this.latestRawTileData=e.rawTileData,this.latestFeatureIndex.rawTileData=e.rawTileData):this.latestRawTileData&&(this.latestFeatureIndex.rawTileData=this.latestRawTileData)),this.collisionBoxArray=e.collisionBoxArray,this.buckets=function(t,e){var i={};if(!e)return i;for(var n=0,o=t;n<o.length;n+=1){var r=o[n],a=r.layerIds.map(function(t){return e.getLayer(t)}).filter(Boolean);if(0!==a.length){r.layers=a;for(var s=0,l=a;s<l.length;s+=1)i[l[s].id]=r;}}return i}(e.buckets,i.style),n)for(var o in this.buckets){var r=this.buckets[o];r instanceof t.default$14&&(r.justReloaded=!0);}for(var a in this.queryPadding=0,this.buckets){var s=this.buckets[a];this.queryPadding=Math.max(this.queryPadding,i.style.getLayer(s.layerIds[0]).queryRadius(s));}e.iconAtlasImage&&(this.iconAtlasImage=e.iconAtlasImage),e.glyphAtlasImage&&(this.glyphAtlasImage=e.glyphAtlasImage);}else this.collisionBoxArray=new t.CollisionBoxArray;},lt.prototype.unloadVectorData=function(){for(var t in this.buckets)this.buckets[t].destroy();this.buckets={},this.iconAtlasTexture&&this.iconAtlasTexture.destroy(),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.latestFeatureIndex=null,this.state="unloaded";},lt.prototype.unloadDEMData=function(){this.dem=null,this.neighboringTiles=null,this.state="unloaded";},lt.prototype.getBucket=function(t){return this.buckets[t.id]},lt.prototype.upload=function(t){for(var e in this.buckets){var i=this.buckets[e];i.uploaded||(i.upload(t),i.uploaded=!0);}var n=t.gl;this.iconAtlasImage&&(this.iconAtlasTexture=new M(t,this.iconAtlasImage,n.RGBA),this.iconAtlasImage=null),this.glyphAtlasImage&&(this.glyphAtlasTexture=new M(t,this.glyphAtlasImage,n.ALPHA),this.glyphAtlasImage=null);},lt.prototype.queryRenderedFeatures=function(t,e,i,n,o,r,a){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({queryGeometry:e,scale:i,tileSize:this.tileSize,posMatrix:a,transform:o,params:n,queryPadding:this.queryPadding*r},t):{}},lt.prototype.querySourceFeatures=function(e,i){if(this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData){var n=this.latestFeatureIndex.loadVTLayers(),o=i?i.sourceLayer:"",r=n._geojsonTileLayer||n[o];if(r)for(var a=t.default$13(i&&i.filter),s={z:this.tileID.overscaledZ,x:this.tileID.canonical.x,y:this.tileID.canonical.y},l=0;l<r.length;l++){var c=r.feature(l);if(a(new t.default$16(this.tileID.overscaledZ),c)){var u=new t.default$12(c,s.z,s.x,s.y);u.tile=s,e.push(u);}}}},lt.prototype.clearMask=function(){this.segments&&(this.segments.destroy(),delete this.segments),this.maskedBoundsBuffer&&(this.maskedBoundsBuffer.destroy(),delete this.maskedBoundsBuffer),this.maskedIndexBuffer&&(this.maskedIndexBuffer.destroy(),delete this.maskedIndexBuffer);},lt.prototype.setMask=function(e,i){if(!t.default$10(this.mask,e)&&(this.mask=e,this.clearMask(),!t.default$10(e,{0:!0}))){var n=new t.RasterBoundsArray,o=new t.TriangleIndexArray;this.segments=new t.default$15,this.segments.prepareSegment(0,n,o);for(var r=Object.keys(e),a=0;a<r.length;a++){var s=e[r[a]],l=t.default$8>>s.z,c=new t.default$1(s.x*l,s.y*l),u=new t.default$1(c.x+l,c.y+l),h=this.segments.prepareSegment(4,n,o);n.emplaceBack(c.x,c.y,c.x,c.y),n.emplaceBack(u.x,c.y,u.x,c.y),n.emplaceBack(c.x,u.y,c.x,u.y),n.emplaceBack(u.x,u.y,u.x,u.y);var p=h.vertexLength;o.emplaceBack(p,p+1,p+2),o.emplaceBack(p+1,p+2,p+3),h.vertexLength+=4,h.primitiveLength+=2;}this.maskedBoundsBuffer=i.createVertexBuffer(n,Q.members),this.maskedIndexBuffer=i.createIndexBuffer(o);}},lt.prototype.hasData=function(){return"loaded"===this.state||"reloading"===this.state||"expired"===this.state},lt.prototype.setExpiryData=function(e){var i=this.expirationTime;if(e.cacheControl){var n=t.parseCacheControl(e.cacheControl);n["max-age"]&&(this.expirationTime=Date.now()+1e3*n["max-age"]);}else e.expires&&(this.expirationTime=new Date(e.expires).getTime());if(this.expirationTime){var o=Date.now(),r=!1;if(this.expirationTime>o)r=!1;else if(i)if(this.expirationTime<i)r=!0;else{var a=this.expirationTime-i;a?this.expirationTime=o+Math.max(a,3e4):r=!0;}else r=!0;r?(this.expiredRequestCount++,this.state="expired"):this.expiredRequestCount=0;}},lt.prototype.getExpiryTimeout=function(){if(this.expirationTime)return this.expiredRequestCount?1e3*(1<<Math.min(this.expiredRequestCount-1,31)):Math.min(this.expirationTime-(new Date).getTime(),Math.pow(2,31)-1)};var ct=function(t,e){this.max=t,this.onRemove=e,this.reset();};ct.prototype.reset=function(){for(var t in this.data)for(var e=0,i=this.data[t];e<i.length;e+=1){var n=i[e];n.timeout&&clearTimeout(n.timeout),this.onRemove(n.value);}return this.data={},this.order=[],this},ct.prototype.add=function(t,e,i){var n=this,o=t.wrapped().key;void 0===this.data[o]&&(this.data[o]=[]);var r={value:e,timeout:void 0};if(void 0!==i&&(r.timeout=setTimeout(function(){n.remove(t,r);},i)),this.data[o].push(r),this.order.push(o),this.order.length>this.max){var a=this._getAndRemoveByKey(this.order[0]);a&&this.onRemove(a);}return this},ct.prototype.has=function(t){return t.wrapped().key in this.data},ct.prototype.getAndRemove=function(t){return this.has(t)?this._getAndRemoveByKey(t.wrapped().key):null},ct.prototype._getAndRemoveByKey=function(t){var e=this.data[t].shift();return e.timeout&&clearTimeout(e.timeout),0===this.data[t].length&&delete this.data[t],this.order.splice(this.order.indexOf(t),1),e.value},ct.prototype.get=function(t){return this.has(t)?this.data[t.wrapped().key][0].value:null},ct.prototype.remove=function(t,e){if(!this.has(t))return this;var i=t.wrapped().key,n=void 0===e?0:this.data[i].indexOf(e),o=this.data[i][n];return this.data[i].splice(n,1),o.timeout&&clearTimeout(o.timeout),0===this.data[i].length&&delete this.data[i],this.onRemove(o.value),this.order.splice(this.order.indexOf(i),1),this},ct.prototype.setMaxSize=function(t){for(this.max=t;this.order.length>this.max;){var e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this};var ut=function(t,e,i){this.context=t;var n=t.gl;this.buffer=n.createBuffer(),this.dynamicDraw=Boolean(i),this.unbindVAO(),t.bindElementBuffer.set(this.buffer),n.bufferData(n.ELEMENT_ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?n.DYNAMIC_DRAW:n.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer;};ut.prototype.unbindVAO=function(){this.context.extVertexArrayObject&&this.context.bindVertexArrayOES.set(null);},ut.prototype.bind=function(){this.context.bindElementBuffer.set(this.buffer);},ut.prototype.updateData=function(t){var e=this.context.gl;this.unbindVAO(),this.bind(),e.bufferSubData(e.ELEMENT_ARRAY_BUFFER,0,t.arrayBuffer);},ut.prototype.destroy=function(){var t=this.context.gl;this.buffer&&(t.deleteBuffer(this.buffer),delete this.buffer);};var ht={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"},pt=function(t,e,i,n){this.length=e.length,this.attributes=i,this.itemSize=e.bytesPerElement,this.dynamicDraw=n,this.context=t;var o=t.gl;this.buffer=o.createBuffer(),t.bindVertexBuffer.set(this.buffer),o.bufferData(o.ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?o.DYNAMIC_DRAW:o.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer;};pt.prototype.bind=function(){this.context.bindVertexBuffer.set(this.buffer);},pt.prototype.updateData=function(t){var e=this.context.gl;this.bind(),e.bufferSubData(e.ARRAY_BUFFER,0,t.arrayBuffer);},pt.prototype.enableAttributes=function(t,e){for(var i=0;i<this.attributes.length;i++){var n=this.attributes[i],o=e.attributes[n.name];void 0!==o&&t.enableVertexAttribArray(o);}},pt.prototype.setVertexAttribPointers=function(t,e,i){for(var n=0;n<this.attributes.length;n++){var o=this.attributes[n],r=e.attributes[o.name];void 0!==r&&t.vertexAttribPointer(r,o.components,t[ht[o.type]],!1,this.itemSize,o.offset+this.itemSize*(i||0));}},pt.prototype.destroy=function(){var t=this.context.gl;this.buffer&&(t.deleteBuffer(this.buffer),delete this.buffer);};var dt=function(e){this.context=e,this.current=t.default$6.transparent;};dt.prototype.get=function(){return this.current},dt.prototype.set=function(t){var e=this.current;t.r===e.r&&t.g===e.g&&t.b===e.b&&t.a===e.a||(this.context.gl.clearColor(t.r,t.g,t.b,t.a),this.current=t);};var ft=function(t){this.context=t,this.current=1;};ft.prototype.get=function(){return this.current},ft.prototype.set=function(t){this.current!==t&&(this.context.gl.clearDepth(t),this.current=t);};var mt=function(t){this.context=t,this.current=0;};mt.prototype.get=function(){return this.current},mt.prototype.set=function(t){this.current!==t&&(this.context.gl.clearStencil(t),this.current=t);};var _t=function(t){this.context=t,this.current=[!0,!0,!0,!0];};_t.prototype.get=function(){return this.current},_t.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(this.context.gl.colorMask(t[0],t[1],t[2],t[3]),this.current=t);};var gt=function(t){this.context=t,this.current=!0;};gt.prototype.get=function(){return this.current},gt.prototype.set=function(t){this.current!==t&&(this.context.gl.depthMask(t),this.current=t);};var vt=function(t){this.context=t,this.current=255;};vt.prototype.get=function(){return this.current},vt.prototype.set=function(t){this.current!==t&&(this.context.gl.stencilMask(t),this.current=t);};var yt=function(t){this.context=t,this.current={func:t.gl.ALWAYS,ref:0,mask:255};};yt.prototype.get=function(){return this.current},yt.prototype.set=function(t){var e=this.current;t.func===e.func&&t.ref===e.ref&&t.mask===e.mask||(this.context.gl.stencilFunc(t.func,t.ref,t.mask),this.current=t);};var xt=function(t){this.context=t;var e=this.context.gl;this.current=[e.KEEP,e.KEEP,e.KEEP];};xt.prototype.get=function(){return this.current},xt.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]||(this.context.gl.stencilOp(t[0],t[1],t[2]),this.current=t);};var bt=function(t){this.context=t,this.current=!1;};bt.prototype.get=function(){return this.current},bt.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;t?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this.current=t;}};var wt=function(t){this.context=t,this.current=[0,1];};wt.prototype.get=function(){return this.current},wt.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]||(this.context.gl.depthRange(t[0],t[1]),this.current=t);};var Et=function(t){this.context=t,this.current=!1;};Et.prototype.get=function(){return this.current},Et.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;t?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this.current=t;}};var Tt=function(t){this.context=t,this.current=t.gl.LESS;};Tt.prototype.get=function(){return this.current},Tt.prototype.set=function(t){this.current!==t&&(this.context.gl.depthFunc(t),this.current=t);};var It=function(t){this.context=t,this.current=!1;};It.prototype.get=function(){return this.current},It.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;t?e.enable(e.BLEND):e.disable(e.BLEND),this.current=t;}};var Ct=function(t){this.context=t;var e=this.context.gl;this.current=[e.ONE,e.ZERO];};Ct.prototype.get=function(){return this.current},Ct.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]||(this.context.gl.blendFunc(t[0],t[1]),this.current=t);};var St=function(e){this.context=e,this.current=t.default$6.transparent;};St.prototype.get=function(){return this.current},St.prototype.set=function(t){var e=this.current;t.r===e.r&&t.g===e.g&&t.b===e.b&&t.a===e.a||(this.context.gl.blendColor(t.r,t.g,t.b,t.a),this.current=t);};var zt=function(t){this.context=t,this.current=null;};zt.prototype.get=function(){return this.current},zt.prototype.set=function(t){this.current!==t&&(this.context.gl.useProgram(t),this.current=t);};var At=function(t){this.context=t,this.current=1;};At.prototype.get=function(){return this.current},At.prototype.set=function(e){var i=this.context.lineWidthRange,n=t.clamp(e,i[0],i[1]);this.current!==n&&(this.context.gl.lineWidth(n),this.current=e);};var Rt=function(t){this.context=t,this.current=t.gl.TEXTURE0;};Rt.prototype.get=function(){return this.current},Rt.prototype.set=function(t){this.current!==t&&(this.context.gl.activeTexture(t),this.current=t);};var Dt=function(t){this.context=t;var e=this.context.gl;this.current=[0,0,e.drawingBufferWidth,e.drawingBufferHeight];};Dt.prototype.get=function(){return this.current},Dt.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(this.context.gl.viewport(t[0],t[1],t[2],t[3]),this.current=t);};var Mt=function(t){this.context=t,this.current=null;};Mt.prototype.get=function(){return this.current},Mt.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindFramebuffer(e.FRAMEBUFFER,t),this.current=t;}};var Lt=function(t){this.context=t,this.current=null;};Lt.prototype.get=function(){return this.current},Lt.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindRenderbuffer(e.RENDERBUFFER,t),this.current=t;}};var Pt=function(t){this.context=t,this.current=null;};Pt.prototype.get=function(){return this.current},Pt.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindTexture(e.TEXTURE_2D,t),this.current=t;}};var kt=function(t){this.context=t,this.current=null;};kt.prototype.get=function(){return this.current},kt.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindBuffer(e.ARRAY_BUFFER,t),this.current=t;}};var Bt=function(t){this.context=t,this.current=null;};Bt.prototype.get=function(){return this.current},Bt.prototype.set=function(t){var e=this.context.gl;e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t),this.current=t;};var Ot=function(t){this.context=t,this.current=null;};Ot.prototype.get=function(){return this.current},Ot.prototype.set=function(t){this.current!==t&&this.context.extVertexArrayObject&&(this.context.extVertexArrayObject.bindVertexArrayOES(t),this.current=t);};var Ft=function(t){this.context=t,this.current=4;};Ft.prototype.get=function(){return this.current},Ft.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.pixelStorei(e.UNPACK_ALIGNMENT,t),this.current=t;}};var Nt=function(t){this.context=t,this.current=!1;};Nt.prototype.get=function(){return this.current},Nt.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t),this.current=t;}};var Ut=function(t,e){this.context=t,this.current=null,this.parent=e;};Ut.prototype.get=function(){return this.current};var Zt=function(t){function e(e,i){t.call(this,e,i),this.dirty=!1;}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.set=function(t){if(this.dirty||this.current!==t){var e=this.context.gl;this.context.bindFramebuffer.set(this.parent),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.current=t,this.dirty=!1;}},e.prototype.setDirty=function(){this.dirty=!0;},e}(Ut),Vt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;this.context.bindFramebuffer.set(this.parent),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,t),this.current=t;}},e}(Ut),jt=function(t,e,i){this.context=t,this.width=e,this.height=i;var n=t.gl,o=this.framebuffer=n.createFramebuffer();this.colorAttachment=new Zt(t,o),this.depthAttachment=new Vt(t,o);};jt.prototype.destroy=function(){var t=this.context.gl,e=this.colorAttachment.get();e&&t.deleteTexture(e);var i=this.depthAttachment.get();i&&t.deleteRenderbuffer(i),t.deleteFramebuffer(this.framebuffer);};var $t=function(t,e,i){this.func=t,this.mask=e,this.range=i;};$t.ReadOnly=!1,$t.ReadWrite=!0,$t.disabled=new $t(519,$t.ReadOnly,[0,1]);var Gt=function(t,e,i,n,o,r){this.test=t,this.ref=e,this.mask=i,this.fail=n,this.depthFail=o,this.pass=r;};Gt.disabled=new Gt({func:519,mask:0},0,0,7680,7680,7680);var Wt=function(t,e,i){this.blendFunction=t,this.blendColor=e,this.mask=i;};Wt.Replace=[1,0],Wt.disabled=new Wt(Wt.Replace,t.default$6.transparent,[!1,!1,!1,!1]),Wt.unblended=new Wt(Wt.Replace,t.default$6.transparent,[!0,!0,!0,!0]),Wt.alphaBlended=new Wt([1,771],t.default$6.transparent,[!0,!0,!0,!0]);var qt=function(t){this.gl=t,this.extVertexArrayObject=this.gl.getExtension("OES_vertex_array_object"),this.lineWidthRange=t.getParameter(t.ALIASED_LINE_WIDTH_RANGE),this.clearColor=new dt(this),this.clearDepth=new ft(this),this.clearStencil=new mt(this),this.colorMask=new _t(this),this.depthMask=new gt(this),this.stencilMask=new vt(this),this.stencilFunc=new yt(this),this.stencilOp=new xt(this),this.stencilTest=new bt(this),this.depthRange=new wt(this),this.depthTest=new Et(this),this.depthFunc=new Tt(this),this.blend=new It(this),this.blendFunc=new Ct(this),this.blendColor=new St(this),this.program=new zt(this),this.lineWidth=new At(this),this.activeTexture=new Rt(this),this.viewport=new Dt(this),this.bindFramebuffer=new Mt(this),this.bindRenderbuffer=new Lt(this),this.bindTexture=new Pt(this),this.bindVertexBuffer=new kt(this),this.bindElementBuffer=new Bt(this),this.bindVertexArrayOES=this.extVertexArrayObject&&new Ot(this),this.pixelStoreUnpack=new Ft(this),this.pixelStoreUnpackPremultiplyAlpha=new Nt(this),this.extTextureFilterAnisotropic=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=t.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT)),this.extTextureHalfFloat=t.getExtension("OES_texture_half_float"),this.extTextureHalfFloat&&t.getExtension("OES_texture_half_float_linear");};qt.prototype.createIndexBuffer=function(t,e){return new ut(this,t,e)},qt.prototype.createVertexBuffer=function(t,e,i){return new pt(this,t,e,i)},qt.prototype.createRenderbuffer=function(t,e,i){var n=this.gl,o=n.createRenderbuffer();return this.bindRenderbuffer.set(o),n.renderbufferStorage(n.RENDERBUFFER,t,e,i),this.bindRenderbuffer.set(null),o},qt.prototype.createFramebuffer=function(t,e){return new jt(this,t,e)},qt.prototype.clear=function(t){var e=t.color,i=t.depth,n=this.gl,o=0;e&&(o|=n.COLOR_BUFFER_BIT,this.clearColor.set(e),this.colorMask.set([!0,!0,!0,!0])),void 0!==i&&(o|=n.DEPTH_BUFFER_BIT,this.clearDepth.set(i),this.depthMask.set(!0)),n.clear(o);},qt.prototype.setDepthMode=function(t){t.func!==this.gl.ALWAYS||t.mask?(this.depthTest.set(!0),this.depthFunc.set(t.func),this.depthMask.set(t.mask),this.depthRange.set(t.range)):this.depthTest.set(!1);},qt.prototype.setStencilMode=function(t){t.test.func!==this.gl.ALWAYS||t.mask?(this.stencilTest.set(!0),this.stencilMask.set(t.mask),this.stencilOp.set([t.fail,t.depthFail,t.pass]),this.stencilFunc.set({func:t.test.func,ref:t.ref,mask:t.test.mask})):this.stencilTest.set(!1);},qt.prototype.setColorMode=function(e){t.default$10(e.blendFunction,Wt.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(e.blendFunction),this.blendColor.set(e.blendColor)),this.colorMask.set(e.mask);};var Xt=function(e){function i(t,i,n){var o=this;e.call(this),this.id=t,this.dispatcher=n,this.on("data",function(t){"source"===t.dataType&&"metadata"===t.sourceDataType&&(o._sourceLoaded=!0),o._sourceLoaded&&!o._paused&&"source"===t.dataType&&"content"===t.sourceDataType&&(o.reload(),o.transform&&o.update(o.transform));}),this.on("error",function(){o._sourceErrored=!0;}),this._source=rt(t,i,n,this),this._tiles={},this._cache=new ct(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._maxTileCacheSize=null,this._isIdRenderable=this._isIdRenderable.bind(this),this._coveredTiles={};}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.onAdd=function(t){this.map=t,this._maxTileCacheSize=t?t._maxTileCacheSize:null,this._source&&this._source.onAdd&&this._source.onAdd(t);},i.prototype.onRemove=function(t){this._source&&this._source.onRemove&&this._source.onRemove(t);},i.prototype.loaded=function(){if(this._sourceErrored)return!0;if(!this._sourceLoaded)return!1;for(var t in this._tiles){var e=this._tiles[t];if("loaded"!==e.state&&"errored"!==e.state)return!1}return!0},i.prototype.getSource=function(){return this._source},i.prototype.pause=function(){this._paused=!0;},i.prototype.resume=function(){if(this._paused){var t=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,t&&this.reload(),this.transform&&this.update(this.transform);}},i.prototype._loadTile=function(t,e){return this._source.loadTile(t,e)},i.prototype._unloadTile=function(t){if(this._source.unloadTile)return this._source.unloadTile(t,function(){})},i.prototype._abortTile=function(t){if(this._source.abortTile)return this._source.abortTile(t,function(){})},i.prototype.serialize=function(){return this._source.serialize()},i.prototype.prepare=function(t){for(var e in this._source.prepare&&this._source.prepare(),this._tiles)this._tiles[e].upload(t);},i.prototype.getIds=function(){var e=this;return Object.keys(this._tiles).map(Number).sort(function(i,n){var o=e._tiles[i].tileID,r=e._tiles[n].tileID,a=new t.default$1(o.canonical.x,o.canonical.y).rotate(e.transform.angle),s=new t.default$1(r.canonical.x,r.canonical.y).rotate(e.transform.angle);return o.overscaledZ-r.overscaledZ||s.y-a.y||s.x-a.x})},i.prototype.getRenderableIds=function(){return this.getIds().filter(this._isIdRenderable)},i.prototype.hasRenderableParent=function(t){var e=this.findLoadedParent(t,0,{});return!!e&&this._isIdRenderable(e.tileID.key)},i.prototype._isIdRenderable=function(t){return this._tiles[t]&&this._tiles[t].hasData()&&!this._coveredTiles[t]},i.prototype.reload=function(){if(this._paused)this._shouldReloadOnResume=!0;else for(var t in this._cache.reset(),this._tiles)this._reloadTile(t,"reloading");},i.prototype._reloadTile=function(t,e){var i=this._tiles[t];i&&("loading"!==i.state&&(i.state=e),this._loadTile(i,this._tileLoaded.bind(this,i,t,e)));},i.prototype._tileLoaded=function(e,i,n,o){if(o)return e.state="errored",void(404!==o.status?this._source.fire(new t.ErrorEvent(o,{tile:e})):this.update(this.transform));e.timeAdded=r.now(),"expired"===n&&(e.refreshedUponExpiration=!0),this._setTileReloadTimer(i,e),"raster-dem"===this.getSource().type&&e.dem&&this._backfillDEM(e),this._source.fire(new t.Event("data",{dataType:"source",tile:e,coord:e.tileID})),this.map&&(this.map.painter.tileExtentVAO.vao=null);},i.prototype._backfillDEM=function(t){for(var e=this.getRenderableIds(),i=0;i<e.length;i++){var n=e[i];if(t.neighboringTiles&&t.neighboringTiles[n]){var o=this.getTileByID(n);r(t,o),r(o,t);}}function r(t,e){t.needsHillshadePrepare=!0;var i=e.tileID.canonical.x-t.tileID.canonical.x,n=e.tileID.canonical.y-t.tileID.canonical.y,o=Math.pow(2,t.tileID.canonical.z),r=e.tileID.key;0===i&&0===n||Math.abs(n)>1||(Math.abs(i)>1&&(1===Math.abs(i+o)?i+=o:1===Math.abs(i-o)&&(i-=o)),e.dem&&t.dem&&(t.dem.backfillBorder(e.dem,i,n),t.neighboringTiles&&t.neighboringTiles[r]&&(t.neighboringTiles[r].backfilled=!0)));}},i.prototype.getTile=function(t){return this.getTileByID(t.key)},i.prototype.getTileByID=function(t){return this._tiles[t]},i.prototype.getZoom=function(t){return t.zoom+t.scaleZoom(t.tileSize/this._source.tileSize)},i.prototype._findLoadedChildren=function(t,e,i){var n=!1;for(var o in this._tiles){var r=this._tiles[o];if(!(i[o]||!r.hasData()||r.tileID.overscaledZ<=t.overscaledZ||r.tileID.overscaledZ>e)){var a=Math.pow(2,r.tileID.canonical.z-t.canonical.z);if(Math.floor(r.tileID.canonical.x/a)===t.canonical.x&&Math.floor(r.tileID.canonical.y/a)===t.canonical.y)for(i[o]=r.tileID,n=!0;r&&r.tileID.overscaledZ-1>t.overscaledZ;){var s=r.tileID.scaledTo(r.tileID.overscaledZ-1);if(!s)break;(r=this._tiles[s.key])&&r.hasData()&&(delete i[o],i[s.key]=s);}}}return n},i.prototype.findLoadedParent=function(t,e,i){for(var n=t.overscaledZ-1;n>=e;n--){var o=t.scaledTo(n);if(!o)return;var r=String(o.key),a=this._tiles[r];if(a&&a.hasData())return i[r]=o,a;if(this._cache.has(o))return i[r]=o,this._cache.get(o)}},i.prototype.updateCacheSize=function(t){var e=(Math.ceil(t.width/this._source.tileSize)+1)*(Math.ceil(t.height/this._source.tileSize)+1),i=Math.floor(5*e),n="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,i):i;this._cache.setMaxSize(n);},i.prototype.handleWrapJump=function(t){var e=(t-(void 0===this._prevLng?t:this._prevLng))/360,i=Math.round(e);if(this._prevLng=t,i){var n={};for(var o in this._tiles){var r=this._tiles[o];r.tileID=r.tileID.unwrapTo(r.tileID.wrap+i),n[r.tileID.key]=r;}for(var a in this._tiles=n,this._timers)clearTimeout(this._timers[a]),delete this._timers[a];for(var s in this._tiles){var l=this._tiles[s];this._setTileReloadTimer(s,l);}}},i.prototype.update=function(e){var n=this;if(this.transform=e,this._sourceLoaded&&!this._paused){var o;this.updateCacheSize(e),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used?this._source.tileID?o=e.getVisibleUnwrappedCoordinates(this._source.tileID).map(function(e){return new t.OverscaledTileID(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y)}):(o=e.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}),this._source.hasTile&&(o=o.filter(function(t){return n._source.hasTile(t)}))):o=[];var a,s=(this._source.roundZoom?Math.round:Math.floor)(this.getZoom(e)),l=Math.max(s-i.maxOverzooming,this._source.minzoom),c=Math.max(s+i.maxUnderzooming,this._source.minzoom),u=this._updateRetainedTiles(o,s),h={};if(Kt(this._source.type))for(var p=Object.keys(u),d=0;d<p.length;d++){var f=p[d],m=u[f],_=n._tiles[f];if(_&&(void 0===_.fadeEndTime||_.fadeEndTime>=r.now())){n._findLoadedChildren(m,c,u)&&(u[f]=m);var g=n.findLoadedParent(m,l,h);g&&n._addTile(g.tileID);}}for(a in h)u[a]||(n._coveredTiles[a]=!0);for(a in h)u[a]=h[a];for(var v=t.keysDifference(this._tiles,u),y=0;y<v.length;y++)n._removeTile(v[y]);}},i.prototype._updateRetainedTiles=function(t,e){for(var n={},o={},r=Math.max(e-i.maxOverzooming,this._source.minzoom),a=Math.max(e+i.maxUnderzooming,this._source.minzoom),s=0;s<t.length;s++){var l=t[s],c=this._addTile(l),u=!1;if(c.hasData())n[l.key]=l;else{u=c.wasRequested(),n[l.key]=l;var h=!0;if(e+1>this._source.maxzoom){var p=l.children(this._source.maxzoom)[0],d=this.getTile(p);d&&d.hasData()?n[p.key]=p:h=!1;}else{this._findLoadedChildren(l,a,n);for(var f=l.children(this._source.maxzoom),m=0;m<f.length;m++)if(!n[f[m].key]){h=!1;break}}if(!h)for(var _=l.overscaledZ-1;_>=r;--_){var g=l.scaledTo(_);if(o[g.key])break;if(o[g.key]=!0,!(c=this.getTile(g))&&u&&(c=this._addTile(g)),c&&(n[g.key]=g,u=c.wasRequested(),c.hasData()))break}}}return n},i.prototype._addTile=function(e){var i=this._tiles[e.key];if(i)return i;(i=this._cache.getAndRemove(e))&&(this._setTileReloadTimer(e.key,i),i.tileID=e);var n=Boolean(i);return n||(i=new lt(e,this._source.tileSize*e.overscaleFactor()),this._loadTile(i,this._tileLoaded.bind(this,i,e.key,i.state))),i?(i.uses++,this._tiles[e.key]=i,n||this._source.fire(new t.Event("dataloading",{tile:i,coord:i.tileID,dataType:"source"})),i):null},i.prototype._setTileReloadTimer=function(t,e){var i=this;t in this._timers&&(clearTimeout(this._timers[t]),delete this._timers[t]);var n=e.getExpiryTimeout();n&&(this._timers[t]=setTimeout(function(){i._reloadTile(t,"expired"),delete i._timers[t];},n));},i.prototype._removeTile=function(t){var e=this._tiles[t];e&&(e.uses--,delete this._tiles[t],this._timers[t]&&(clearTimeout(this._timers[t]),delete this._timers[t]),e.uses>0||(e.hasData()?this._cache.add(e.tileID,e,e.getExpiryTimeout()):(e.aborted=!0,this._abortTile(e),this._unloadTile(e))));},i.prototype.clearTiles=function(){for(var t in this._shouldReloadOnResume=!1,this._paused=!1,this._tiles)this._removeTile(t);this._cache.reset();},i.prototype.tilesIn=function(e,i){for(var n=[],o=this.getIds(),r=1/0,a=1/0,s=-1/0,l=-1/0,c=e[0].zoom,u=0;u<e.length;u++){var h=e[u];r=Math.min(r,h.column),a=Math.min(a,h.row),s=Math.max(s,h.column),l=Math.max(l,h.row);}for(var p=0;p<o.length;p++){var d=this._tiles[o[p]],f=d.tileID,m=Math.pow(2,this.transform.zoom-d.tileID.overscaledZ),_=i*d.queryPadding*t.default$8/d.tileSize/m,g=[Ht(f,new t.default$17(r,a,c)),Ht(f,new t.default$17(s,l,c))];if(g[0].x-_<t.default$8&&g[0].y-_<t.default$8&&g[1].x+_>=0&&g[1].y+_>=0){for(var v=[],y=0;y<e.length;y++)v.push(Ht(f,e[y]));n.push({tile:d,tileID:f,queryGeometry:[v],scale:m});}}return n},i.prototype.getVisibleCoordinates=function(){for(var t=this,e=this.getRenderableIds().map(function(e){return t._tiles[e].tileID}),i=0,n=e;i<n.length;i+=1){var o=n[i];o.posMatrix=t.transform.calculatePosMatrix(o.toUnwrapped());}return e},i.prototype.hasTransition=function(){if(this._source.hasTransition())return!0;if(Kt(this._source.type))for(var t in this._tiles){var e=this._tiles[t];if(void 0!==e.fadeEndTime&&e.fadeEndTime>=r.now())return!0}return!1},i}(t.Evented);function Ht(e,i){var n=i.zoomTo(e.canonical.z);return new t.default$1((n.column-(e.canonical.x+e.wrap*Math.pow(2,e.canonical.z)))*t.default$8,(n.row-e.canonical.y)*t.default$8)}function Kt(t){return"raster"===t||"image"===t||"video"===t}function Yt(){return new t.default.Worker(Rn.workerUrl)}Xt.maxOverzooming=10,Xt.maxUnderzooming=3;var Jt,Qt=function(){this.active={};};function te(e,i){var n={};for(var o in e)"ref"!==o&&(n[o]=e[o]);return t.default$18.forEach(function(t){t in i&&(n[t]=i[t]);}),n}function ee(t){t=t.slice();for(var e=Object.create(null),i=0;i<t.length;i++)e[t[i].id]=t[i];for(var n=0;n<t.length;n++)"ref"in t[n]&&(t[n]=te(t[n],e[t[n].ref]));return t}Qt.prototype.acquire=function(t){if(!this.workers){var e=Rn.workerCount;for(this.workers=[];this.workers.length<e;)this.workers.push(new Yt);}return this.active[t]=!0,this.workers.slice()},Qt.prototype.release=function(t){delete this.active[t],0===Object.keys(this.active).length&&(this.workers.forEach(function(t){t.terminate();}),this.workers=null);};var ie={setStyle:"setStyle",addLayer:"addLayer",removeLayer:"removeLayer",setPaintProperty:"setPaintProperty",setLayoutProperty:"setLayoutProperty",setFilter:"setFilter",addSource:"addSource",removeSource:"removeSource",setGeoJSONSourceData:"setGeoJSONSourceData",setLayerZoomRange:"setLayerZoomRange",setLayerProperty:"setLayerProperty",setCenter:"setCenter",setZoom:"setZoom",setBearing:"setBearing",setPitch:"setPitch",setSprite:"setSprite",setGlyphs:"setGlyphs",setTransition:"setTransition",setLight:"setLight"};function ne(t,e,i){i.push({command:ie.addSource,args:[t,e[t]]});}function oe(t,e,i){e.push({command:ie.removeSource,args:[t]}),i[t]=!0;}function re(t,e,i,n){oe(t,i,n),ne(t,e,i);}function ae(e,i,n){var o;for(o in e[n])if(e[n].hasOwnProperty(o)&&"data"!==o&&!t.default$10(e[n][o],i[n][o]))return!1;for(o in i[n])if(i[n].hasOwnProperty(o)&&"data"!==o&&!t.default$10(e[n][o],i[n][o]))return!1;return!0}function se(e,i,n,o,r,a){var s;for(s in i=i||{},e=e||{})e.hasOwnProperty(s)&&(t.default$10(e[s],i[s])||n.push({command:a,args:[o,s,i[s],r]}));for(s in i)i.hasOwnProperty(s)&&!e.hasOwnProperty(s)&&(t.default$10(e[s],i[s])||n.push({command:a,args:[o,s,i[s],r]}));}function le(t){return t.id}function ce(t,e){return t[e.id]=e,t}function ue(e,i){if(!e)return[{command:ie.setStyle,args:[i]}];var n=[];try{if(!t.default$10(e.version,i.version))return[{command:ie.setStyle,args:[i]}];t.default$10(e.center,i.center)||n.push({command:ie.setCenter,args:[i.center]}),t.default$10(e.zoom,i.zoom)||n.push({command:ie.setZoom,args:[i.zoom]}),t.default$10(e.bearing,i.bearing)||n.push({command:ie.setBearing,args:[i.bearing]}),t.default$10(e.pitch,i.pitch)||n.push({command:ie.setPitch,args:[i.pitch]}),t.default$10(e.sprite,i.sprite)||n.push({command:ie.setSprite,args:[i.sprite]}),t.default$10(e.glyphs,i.glyphs)||n.push({command:ie.setGlyphs,args:[i.glyphs]}),t.default$10(e.transition,i.transition)||n.push({command:ie.setTransition,args:[i.transition]}),t.default$10(e.light,i.light)||n.push({command:ie.setLight,args:[i.light]});var o={},r=[];!function(e,i,n,o){var r;for(r in i=i||{},e=e||{})e.hasOwnProperty(r)&&(i.hasOwnProperty(r)||oe(r,n,o));for(r in i)i.hasOwnProperty(r)&&(e.hasOwnProperty(r)?t.default$10(e[r],i[r])||("geojson"===e[r].type&&"geojson"===i[r].type&&ae(e,i,r)?n.push({command:ie.setGeoJSONSourceData,args:[r,i[r].data]}):re(r,i,n,o)):ne(r,i,n));}(e.sources,i.sources,r,o);var a=[];e.layers&&e.layers.forEach(function(t){o[t.source]?n.push({command:ie.removeLayer,args:[t.id]}):a.push(t);}),n=n.concat(r),function(e,i,n){i=i||[];var o,r,a,s,l,c,u,h=(e=e||[]).map(le),p=i.map(le),d=e.reduce(ce,{}),f=i.reduce(ce,{}),m=h.slice(),_=Object.create(null);for(o=0,r=0;o<h.length;o++)a=h[o],f.hasOwnProperty(a)?r++:(n.push({command:ie.removeLayer,args:[a]}),m.splice(m.indexOf(a,r),1));for(o=0,r=0;o<p.length;o++)a=p[p.length-1-o],m[m.length-1-o]!==a&&(d.hasOwnProperty(a)?(n.push({command:ie.removeLayer,args:[a]}),m.splice(m.lastIndexOf(a,m.length-r),1)):r++,c=m[m.length-o],n.push({command:ie.addLayer,args:[f[a],c]}),m.splice(m.length-o,0,a),_[a]=!0);for(o=0;o<p.length;o++)if(s=d[a=p[o]],l=f[a],!_[a]&&!t.default$10(s,l))if(t.default$10(s.source,l.source)&&t.default$10(s["source-layer"],l["source-layer"])&&t.default$10(s.type,l.type)){for(u in se(s.layout,l.layout,n,a,null,ie.setLayoutProperty),se(s.paint,l.paint,n,a,null,ie.setPaintProperty),t.default$10(s.filter,l.filter)||n.push({command:ie.setFilter,args:[a,l.filter]}),t.default$10(s.minzoom,l.minzoom)&&t.default$10(s.maxzoom,l.maxzoom)||n.push({command:ie.setLayerZoomRange,args:[a,l.minzoom,l.maxzoom]}),s)s.hasOwnProperty(u)&&"layout"!==u&&"paint"!==u&&"filter"!==u&&"metadata"!==u&&"minzoom"!==u&&"maxzoom"!==u&&(0===u.indexOf("paint.")?se(s[u],l[u],n,a,u.slice(6),ie.setPaintProperty):t.default$10(s[u],l[u])||n.push({command:ie.setLayerProperty,args:[a,u,l[u]]}));for(u in l)l.hasOwnProperty(u)&&!s.hasOwnProperty(u)&&"layout"!==u&&"paint"!==u&&"filter"!==u&&"metadata"!==u&&"minzoom"!==u&&"maxzoom"!==u&&(0===u.indexOf("paint.")?se(s[u],l[u],n,a,u.slice(6),ie.setPaintProperty):t.default$10(s[u],l[u])||n.push({command:ie.setLayerProperty,args:[a,u,l[u]]}));}else n.push({command:ie.removeLayer,args:[a]}),c=m[m.lastIndexOf(a)+1],n.push({command:ie.addLayer,args:[l,c]});}(a,i.layers,n);}catch(t){console.warn("Unable to compute style diff:",t),n=[{command:ie.setStyle,args:[i]}];}return n}var he=function(t,e,i){var n=this.boxCells=[],o=this.circleCells=[];this.xCellCount=Math.ceil(t/i),this.yCellCount=Math.ceil(e/i);for(var r=0;r<this.xCellCount*this.yCellCount;r++)n.push([]),o.push([]);this.circleKeys=[],this.boxKeys=[],this.bboxes=[],this.circles=[],this.width=t,this.height=e,this.xScale=this.xCellCount/t,this.yScale=this.yCellCount/e,this.boxUid=0,this.circleUid=0;};he.prototype.keysLength=function(){return this.boxKeys.length+this.circleKeys.length},he.prototype.insert=function(t,e,i,n,o){this._forEachCell(e,i,n,o,this._insertBoxCell,this.boxUid++),this.boxKeys.push(t),this.bboxes.push(e),this.bboxes.push(i),this.bboxes.push(n),this.bboxes.push(o);},he.prototype.insertCircle=function(t,e,i,n){this._forEachCell(e-n,i-n,e+n,i+n,this._insertCircleCell,this.circleUid++),this.circleKeys.push(t),this.circles.push(e),this.circles.push(i),this.circles.push(n);},he.prototype._insertBoxCell=function(t,e,i,n,o,r){this.boxCells[o].push(r);},he.prototype._insertCircleCell=function(t,e,i,n,o,r){this.circleCells[o].push(r);},he.prototype._query=function(t,e,i,n,o){if(i<0||t>this.width||n<0||e>this.height)return!o&&[];var r=[];if(t<=0&&e<=0&&this.width<=i&&this.height<=n){if(o)return!0;for(var a=0;a<this.boxKeys.length;a++)r.push({key:this.boxKeys[a],x1:this.bboxes[4*a],y1:this.bboxes[4*a+1],x2:this.bboxes[4*a+2],y2:this.bboxes[4*a+3]});for(var s=0;s<this.circleKeys.length;s++){var l=this.circles[3*s],c=this.circles[3*s+1],u=this.circles[3*s+2];r.push({key:this.circleKeys[s],x1:l-u,y1:c-u,x2:l+u,y2:c+u});}}else{var h={hitTest:o,seenUids:{box:{},circle:{}}};this._forEachCell(t,e,i,n,this._queryCell,r,h);}return o?r.length>0:r},he.prototype._queryCircle=function(t,e,i,n){var o=t-i,r=t+i,a=e-i,s=e+i;if(r<0||o>this.width||s<0||a>this.height)return!n&&[];var l=[],c={hitTest:n,circle:{x:t,y:e,radius:i},seenUids:{box:{},circle:{}}};return this._forEachCell(o,a,r,s,this._queryCellCircle,l,c),n?l.length>0:l},he.prototype.query=function(t,e,i,n){return this._query(t,e,i,n,!1)},he.prototype.hitTest=function(t,e,i,n){return this._query(t,e,i,n,!0)},he.prototype.hitTestCircle=function(t,e,i){return this._queryCircle(t,e,i,!0)},he.prototype._queryCell=function(t,e,i,n,o,r,a){var s=a.seenUids,l=this.boxCells[o];if(null!==l)for(var c=this.bboxes,u=0,h=l;u<h.length;u+=1){var p=h[u];if(!s.box[p]){s.box[p]=!0;var d=4*p;if(t<=c[d+2]&&e<=c[d+3]&&i>=c[d+0]&&n>=c[d+1]){if(a.hitTest)return r.push(!0),!0;r.push({key:this.boxKeys[p],x1:c[d],y1:c[d+1],x2:c[d+2],y2:c[d+3]});}}}var f=this.circleCells[o];if(null!==f)for(var m=this.circles,_=0,g=f;_<g.length;_+=1){var v=g[_];if(!s.circle[v]){s.circle[v]=!0;var y=3*v;if(this._circleAndRectCollide(m[y],m[y+1],m[y+2],t,e,i,n)){if(a.hitTest)return r.push(!0),!0;var x=m[y],b=m[y+1],w=m[y+2];r.push({key:this.circleKeys[v],x1:x-w,y1:b-w,x2:x+w,y2:b+w});}}}},he.prototype._queryCellCircle=function(t,e,i,n,o,r,a){var s=a.circle,l=a.seenUids,c=this.boxCells[o];if(null!==c)for(var u=this.bboxes,h=0,p=c;h<p.length;h+=1){var d=p[h];if(!l.box[d]){l.box[d]=!0;var f=4*d;if(this._circleAndRectCollide(s.x,s.y,s.radius,u[f+0],u[f+1],u[f+2],u[f+3]))return r.push(!0),!0}}var m=this.circleCells[o];if(null!==m)for(var _=this.circles,g=0,v=m;g<v.length;g+=1){var y=v[g];if(!l.circle[y]){l.circle[y]=!0;var x=3*y;if(this._circlesCollide(_[x],_[x+1],_[x+2],s.x,s.y,s.radius))return r.push(!0),!0}}},he.prototype._forEachCell=function(t,e,i,n,o,r,a){for(var s=this._convertToXCellCoord(t),l=this._convertToYCellCoord(e),c=this._convertToXCellCoord(i),u=this._convertToYCellCoord(n),h=s;h<=c;h++)for(var p=l;p<=u;p++){var d=this.xCellCount*p+h;if(o.call(this,t,e,i,n,d,r,a))return}},he.prototype._convertToXCellCoord=function(t){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(t*this.xScale)))},he.prototype._convertToYCellCoord=function(t){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(t*this.yScale)))},he.prototype._circlesCollide=function(t,e,i,n,o,r){var a=n-t,s=o-e,l=i+r;return l*l>a*a+s*s},he.prototype._circleAndRectCollide=function(t,e,i,n,o,r,a){var s=(r-n)/2,l=Math.abs(t-(n+s));if(l>s+i)return!1;var c=(a-o)/2,u=Math.abs(e-(o+c));if(u>c+i)return!1;if(l<=s||u<=c)return!0;var h=l-s,p=u-c;return h*h+p*p<=i*i};var pe=t.default$19.layout;function de(e,i,n,o,r){var a=t.mat4.identity(new Float32Array(16));return i?(t.mat4.identity(a),t.mat4.scale(a,a,[1/r,1/r,1]),n||t.mat4.rotateZ(a,a,o.angle)):(t.mat4.scale(a,a,[o.width/2,-o.height/2,1]),t.mat4.translate(a,a,[1,-1,0]),t.mat4.multiply(a,a,e)),a}function fe(e,i,n,o,r){var a=t.mat4.identity(new Float32Array(16));return i?(t.mat4.multiply(a,a,e),t.mat4.scale(a,a,[r,r,1]),n||t.mat4.rotateZ(a,a,-o.angle)):(t.mat4.scale(a,a,[1,-1,1]),t.mat4.translate(a,a,[-1,-1,0]),t.mat4.scale(a,a,[2/o.width,2/o.height,1])),a}function me(e,i){var n=[e.x,e.y,0,1];Ie(n,n,i);var o=n[3];return{point:new t.default$1(n[0]/o,n[1]/o),signedDistanceFromCamera:o}}function _e(t,e){var i=t[0]/t[3],n=t[1]/t[3];return i>=-e[0]&&i<=e[0]&&n>=-e[1]&&n<=e[1]}function ge(e,i,n,o,r,a,s,l){var c=o?e.textSizeData:e.iconSizeData,u=t.evaluateSizeForZoom(c,n.transform.zoom,pe.properties[o?"text-size":"icon-size"]),h=[256/n.width*2+1,256/n.height*2+1],p=o?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;p.clear();for(var d=e.lineVertexArray,f=o?e.text.placedSymbolArray:e.icon.placedSymbolArray,m=n.transform.width/n.transform.height,_=!1,g=0;g<f.length;g++){var v=f.get(g);if(v.hidden||v.writingMode===t.WritingMode.vertical&&!_)Te(v.numGlyphs,p);else{_=!1;var y=[v.anchorX,v.anchorY,0,1];if(t.vec4.transformMat4(y,y,i),_e(y,h)){var x=.5+y[3]/n.transform.cameraToCenterDistance*.5,b=t.evaluateSizeForFeature(c,u,v),w=s?b*x:b/x,E=new t.default$1(v.anchorX,v.anchorY),T=me(E,r).point,I={},C=xe(v,w,!1,l,i,r,a,e.glyphOffsetArray,d,p,T,E,I,m);_=C.useVertical,(C.notEnoughRoom||_||C.needsFlipping&&xe(v,w,!0,l,i,r,a,e.glyphOffsetArray,d,p,T,E,I,m).notEnoughRoom)&&Te(v.numGlyphs,p);}else Te(v.numGlyphs,p);}}o?e.text.dynamicLayoutVertexBuffer.updateData(p):e.icon.dynamicLayoutVertexBuffer.updateData(p);}function ve(t,e,i,n,o,r,a,s,l,c,u,h){var p=s.glyphStartIndex+s.numGlyphs,d=s.lineStartIndex,f=s.lineStartIndex+s.lineLength,m=e.getoffsetX(s.glyphStartIndex),_=e.getoffsetX(p-1),g=we(t*m,i,n,o,r,a,s.segment,d,f,l,c,u,h);if(!g)return null;var v=we(t*_,i,n,o,r,a,s.segment,d,f,l,c,u,h);return v?{first:g,last:v}:null}function ye(e,i,n,o){if(e===t.WritingMode.horizontal&&Math.abs(n.y-i.y)>Math.abs(n.x-i.x)*o)return{useVertical:!0};return(e===t.WritingMode.vertical?i.y<n.y:i.x>n.x)?{needsFlipping:!0}:null}function xe(e,i,n,o,r,a,s,l,c,u,h,p,d,f){var m,_=i/24,g=e.lineOffsetX*i,v=e.lineOffsetY*i;if(e.numGlyphs>1){var y=e.glyphStartIndex+e.numGlyphs,x=e.lineStartIndex,b=e.lineStartIndex+e.lineLength,w=ve(_,l,g,v,n,h,p,e,c,a,d,!1);if(!w)return{notEnoughRoom:!0};var E=me(w.first.point,s).point,T=me(w.last.point,s).point;if(o&&!n){var I=ye(e.writingMode,E,T,f);if(I)return I}m=[w.first];for(var C=e.glyphStartIndex+1;C<y-1;C++)m.push(we(_*l.getoffsetX(C),g,v,n,h,p,e.segment,x,b,c,a,d,!1));m.push(w.last);}else{if(o&&!n){var S=me(p,r).point,z=e.lineStartIndex+e.segment+1,A=new t.default$1(c.getx(z),c.gety(z)),R=me(A,r),D=R.signedDistanceFromCamera>0?R.point:be(p,A,S,1,r),M=ye(e.writingMode,S,D,f);if(M)return M}var L=we(_*l.getoffsetX(e.glyphStartIndex),g,v,n,h,p,e.segment,e.lineStartIndex,e.lineStartIndex+e.lineLength,c,a,d,!1);if(!L)return{notEnoughRoom:!0};m=[L];}for(var P=0,k=m;P<k.length;P+=1){var B=k[P];t.addDynamicAttributes(u,B.point,B.angle);}return{}}function be(t,e,i,n,o){var r=me(t.add(t.sub(e)._unit()),o).point,a=i.sub(r);return i.add(a._mult(n/a.mag()))}function we(e,i,n,o,r,a,s,l,c,u,h,p,d){var f=o?e-i:e+i,m=f>0?1:-1,_=0;o&&(m*=-1,_=Math.PI),m<0&&(_+=Math.PI);for(var g=m>0?l+s:l+s+1,v=g,y=r,x=r,b=0,w=0,E=Math.abs(f);b+w<=E;){if((g+=m)<l||g>=c)return null;if(x=y,void 0===(y=p[g])){var T=new t.default$1(u.getx(g),u.gety(g)),I=me(T,h);if(I.signedDistanceFromCamera>0)y=p[g]=I.point;else{var C=g-m;y=be(0===b?a:new t.default$1(u.getx(C),u.gety(C)),T,x,E-b+1,h);}}b+=w,w=x.dist(y);}var S=(E-b)/w,z=y.sub(x),A=z.mult(S)._add(x);return A._add(z._unit()._perp()._mult(n*m)),{point:A,angle:_+Math.atan2(y.y-x.y,y.x-x.x),tileDistance:d?{prevTileDistance:g-m===v?0:u.gettileUnitDistanceFromAnchor(g-m),lastSegmentViewportDistance:E-b}:null}}var Ee=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function Te(t,e){for(var i=0;i<t;i++){var n=e.length;e.resize(n+4),e.float32.set(Ee,3*n);}}function Ie(t,e,i){var n=e[0],o=e[1];return t[0]=i[0]*n+i[4]*o+i[12],t[1]=i[1]*n+i[5]*o+i[13],t[3]=i[3]*n+i[7]*o+i[15],t}t.default$20.mat4;var Ce=function(t,e,i){void 0===e&&(e=new he(t.width+200,t.height+200,25)),void 0===i&&(i=new he(t.width+200,t.height+200,25)),this.transform=t,this.grid=e,this.ignoredGrid=i,this.pitchfactor=Math.cos(t._pitch)*t.cameraToCenterDistance,this.screenRightBoundary=t.width+100,this.screenBottomBoundary=t.height+100;};function Se(t,e,i){t[e+4]=i?1:0;}function ze(e,i,n){return i*(t.default$8/(e.tileSize*Math.pow(2,n-e.tileID.overscaledZ)))}Ce.prototype.placeCollisionBox=function(t,e,i,n){var o=this.projectAndGetPerspectiveRatio(n,t.anchorPointX,t.anchorPointY),r=i*o.perspectiveRatio,a=t.x1*r+o.point.x,s=t.y1*r+o.point.y,l=t.x2*r+o.point.x,c=t.y2*r+o.point.y;return!e&&this.grid.hitTest(a,s,l,c)?{box:[],offscreen:!1}:{box:[a,s,l,c],offscreen:this.isOffscreen(a,s,l,c)}},Ce.prototype.approximateTileDistance=function(t,e,i,n,o){var r=o?1:n/this.pitchfactor,a=t.lastSegmentViewportDistance*i;return t.prevTileDistance+a+(r-1)*a*Math.abs(Math.sin(e))},Ce.prototype.placeCollisionCircles=function(e,i,n,o,r,a,s,l,c,u,h,p,d){var f=[],m=this.projectAnchor(u,a.anchorX,a.anchorY),_=c/24,g=a.lineOffsetX*c,v=a.lineOffsetY*c,y=new t.default$1(a.anchorX,a.anchorY),x=ve(_,l,g,v,!1,me(y,h).point,y,a,s,h,{},!0),b=!1,w=!0,E=m.perspectiveRatio*o,T=1/(o*n),I=0,C=0;x&&(I=this.approximateTileDistance(x.first.tileDistance,x.first.angle,T,m.cameraDistance,d),C=this.approximateTileDistance(x.last.tileDistance,x.last.angle,T,m.cameraDistance,d));for(var S=0;S<e.length;S+=5){var z=e[S],A=e[S+1],R=e[S+2],D=e[S+3];if(!x||D<-I||D>C)Se(e,S,!1);else{var M=this.projectPoint(u,z,A),L=R*E;if(f.length>0){var P=M.x-f[f.length-4],k=M.y-f[f.length-3];if(L*L*2>P*P+k*k)if(S+8<e.length){var B=e[S+8];if(B>-I&&B<C){Se(e,S,!1);continue}}}var O=S/5;if(f.push(M.x,M.y,L,O),Se(e,S,!0),w=w&&this.isOffscreen(M.x-L,M.y-L,M.x+L,M.y+L),!i&&this.grid.hitTestCircle(M.x,M.y,L)){if(!p)return{circles:[],offscreen:!1};b=!0;}}}return{circles:b?[]:f,offscreen:w}},Ce.prototype.queryRenderedSymbols=function(e){if(0===e.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return{};for(var i=[],n=1/0,o=1/0,r=-1/0,a=-1/0,s=0,l=e;s<l.length;s+=1){var c=l[s],u=new t.default$1(c.x+100,c.y+100);n=Math.min(n,u.x),o=Math.min(o,u.y),r=Math.max(r,u.x),a=Math.max(a,u.y),i.push(u);}for(var h={},p={},d=0,f=this.grid.query(n,o,r,a).concat(this.ignoredGrid.query(n,o,r,a));d<f.length;d+=1){var m=f[d],_=m.key;if(void 0===h[_.bucketInstanceId]&&(h[_.bucketInstanceId]={}),!h[_.bucketInstanceId][_.featureIndex]){var g=[new t.default$1(m.x1,m.y1),new t.default$1(m.x2,m.y1),new t.default$1(m.x2,m.y2),new t.default$1(m.x1,m.y2)];t.polygonIntersectsPolygon(i,g)&&(h[_.bucketInstanceId][_.featureIndex]=!0,void 0===p[_.bucketInstanceId]&&(p[_.bucketInstanceId]=[]),p[_.bucketInstanceId].push(_.featureIndex));}}return p},Ce.prototype.insertCollisionBox=function(t,e,i,n){var o={bucketInstanceId:i,featureIndex:n};(e?this.ignoredGrid:this.grid).insert(o,t[0],t[1],t[2],t[3]);},Ce.prototype.insertCollisionCircles=function(t,e,i,n){for(var o=e?this.ignoredGrid:this.grid,r={bucketInstanceId:i,featureIndex:n},a=0;a<t.length;a+=4)o.insertCircle(r,t[a],t[a+1],t[a+2]);},Ce.prototype.projectAnchor=function(t,e,i){var n=[e,i,0,1];return Ie(n,n,t),{perspectiveRatio:.5+this.transform.cameraToCenterDistance/n[3]*.5,cameraDistance:n[3]}},Ce.prototype.projectPoint=function(e,i,n){var o=[i,n,0,1];return Ie(o,o,e),new t.default$1((o[0]/o[3]+1)/2*this.transform.width+100,(-o[1]/o[3]+1)/2*this.transform.height+100)},Ce.prototype.projectAndGetPerspectiveRatio=function(e,i,n){var o=[i,n,0,1];return Ie(o,o,e),{point:new t.default$1((o[0]/o[3]+1)/2*this.transform.width+100,(-o[1]/o[3]+1)/2*this.transform.height+100),perspectiveRatio:.5+this.transform.cameraToCenterDistance/o[3]*.5}},Ce.prototype.isOffscreen=function(t,e,i,n){return i<100||t>=this.screenRightBoundary||n<100||e>this.screenBottomBoundary};var Ae=t.default$19.layout,Re=function(t,e,i,n){this.opacity=t?Math.max(0,Math.min(1,t.opacity+(t.placed?e:-e))):n&&i?1:0,this.placed=i;};Re.prototype.isHidden=function(){return 0===this.opacity&&!this.placed};var De=function(t,e,i,n,o){this.text=new Re(t?t.text:null,e,i,o),this.icon=new Re(t?t.icon:null,e,n,o);};De.prototype.isHidden=function(){return this.text.isHidden()&&this.icon.isHidden()};var Me=function(t,e,i){this.text=t,this.icon=e,this.skipFade=i;},Le=function(t,e){this.transform=t.clone(),this.collisionIndex=new Ce(this.transform),this.placements={},this.opacities={},this.stale=!1,this.fadeDuration=e,this.retainedQueryData={};};function Pe(t,e,i){t.emplaceBack(e?1:0,i?1:0),t.emplaceBack(e?1:0,i?1:0),t.emplaceBack(e?1:0,i?1:0),t.emplaceBack(e?1:0,i?1:0);}Le.prototype.placeLayerTile=function(e,i,n,o){var r=i.getBucket(e),a=i.latestFeatureIndex;if(r&&a&&e.id===r.layerIds[0]){var s=i.collisionBoxArray,l=r.layers[0].layout,c=Math.pow(2,this.transform.zoom-i.tileID.overscaledZ),u=i.tileSize/t.default$8,h=this.transform.calculatePosMatrix(i.tileID.toUnwrapped()),p=de(h,"map"===l.get("text-pitch-alignment"),"map"===l.get("text-rotation-alignment"),this.transform,ze(i,1,this.transform.zoom)),d=de(h,"map"===l.get("icon-pitch-alignment"),"map"===l.get("icon-rotation-alignment"),this.transform,ze(i,1,this.transform.zoom));this.retainedQueryData[r.bucketInstanceId]=new function(t,e,i,n,o){this.bucketInstanceId=t,this.featureIndex=e,this.sourceLayerIndex=i,this.bucketIndex=n,this.tileID=o;}(r.bucketInstanceId,a,r.sourceLayerIndex,r.index,i.tileID),this.placeLayerBucket(r,h,p,d,c,u,n,o,s);}},Le.prototype.placeLayerBucket=function(e,i,n,o,r,a,s,l,c){for(var u=e.layers[0].layout,h=t.evaluateSizeForZoom(e.textSizeData,this.transform.zoom,Ae.properties["text-size"]),p=!e.hasTextData()||u.get("text-optional"),d=!e.hasIconData()||u.get("icon-optional"),f=0,m=e.symbolInstances;f<m.length;f+=1){var _=m[f];if(!l[_.crossTileID]){var g=void 0!==_.feature.text,v=void 0!==_.feature.icon,y=!0,x=null,b=null,w=null,E=0,T=0;_.collisionArrays||(_.collisionArrays=e.deserializeCollisionBoxes(c,_.textBoxStartIndex,_.textBoxEndIndex,_.iconBoxStartIndex,_.iconBoxEndIndex)),_.collisionArrays.textFeatureIndex&&(E=_.collisionArrays.textFeatureIndex),_.collisionArrays.textBox&&(g=(x=this.collisionIndex.placeCollisionBox(_.collisionArrays.textBox,u.get("text-allow-overlap"),a,i)).box.length>0,y=y&&x.offscreen);var I=_.collisionArrays.textCircles;if(I){var C=e.text.placedSymbolArray.get(_.placedTextSymbolIndices[0]),S=t.evaluateSizeForFeature(e.textSizeData,h,C);b=this.collisionIndex.placeCollisionCircles(I,u.get("text-allow-overlap"),r,a,_.key,C,e.lineVertexArray,e.glyphOffsetArray,S,i,n,s,"map"===u.get("text-pitch-alignment")),g=u.get("text-allow-overlap")||b.circles.length>0,y=y&&b.offscreen;}_.collisionArrays.iconFeatureIndex&&(T=_.collisionArrays.iconFeatureIndex),_.collisionArrays.iconBox&&(v=(w=this.collisionIndex.placeCollisionBox(_.collisionArrays.iconBox,u.get("icon-allow-overlap"),a,i)).box.length>0,y=y&&w.offscreen),p||d?d?p||(v=v&&g):g=v&&g:v=g=v&&g,g&&x&&this.collisionIndex.insertCollisionBox(x.box,u.get("text-ignore-placement"),e.bucketInstanceId,E),v&&w&&this.collisionIndex.insertCollisionBox(w.box,u.get("icon-ignore-placement"),e.bucketInstanceId,T),g&&b&&this.collisionIndex.insertCollisionCircles(b.circles,u.get("text-ignore-placement"),e.bucketInstanceId,E),this.placements[_.crossTileID]=new Me(g,v,y||e.justReloaded),l[_.crossTileID]=!0;}}e.justReloaded=!1;},Le.prototype.commit=function(t,e){this.commitTime=e;var i=!1,n=t&&0!==this.fadeDuration?(this.commitTime-t.commitTime)/this.fadeDuration:1,o=t?t.opacities:{};for(var r in this.placements){var a=this.placements[r],s=o[r];s?(this.opacities[r]=new De(s,n,a.text,a.icon),i=i||a.text!==s.text.placed||a.icon!==s.icon.placed):(this.opacities[r]=new De(null,n,a.text,a.icon,a.skipFade),i=i||a.text||a.icon);}for(var l in o){var c=o[l];if(!this.opacities[l]){var u=new De(c,n,!1,!1);u.isHidden()||(this.opacities[l]=u,i=i||c.text.placed||c.icon.placed);}}i?this.lastPlacementChangeTime=e:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=t?t.lastPlacementChangeTime:e);},Le.prototype.updateLayerOpacities=function(t,e){for(var i={},n=0,o=e;n<o.length;n+=1){var r=o[n],a=r.getBucket(t);a&&r.latestFeatureIndex&&t.id===a.layerIds[0]&&this.updateBucketOpacities(a,i,r.collisionBoxArray);}},Le.prototype.updateBucketOpacities=function(t,e,i){t.hasTextData()&&t.text.opacityVertexArray.clear(),t.hasIconData()&&t.icon.opacityVertexArray.clear(),t.hasCollisionBoxData()&&t.collisionBox.collisionVertexArray.clear(),t.hasCollisionCircleData()&&t.collisionCircle.collisionVertexArray.clear();for(var n=t.layers[0].layout,o=new De(null,0,!1,!1,!0),r=new De(null,0,n.get("text-allow-overlap"),n.get("icon-allow-overlap"),!0),a=0;a<t.symbolInstances.length;a++){var s=t.symbolInstances[a],l=e[s.crossTileID],c=this.opacities[s.crossTileID];l?c=o:c||(c=r,this.opacities[s.crossTileID]=c),e[s.crossTileID]=!0;var u=s.numGlyphVertices>0||s.numVerticalGlyphVertices>0,h=s.numIconVertices>0;if(u){for(var p=Ve(c.text),d=(s.numGlyphVertices+s.numVerticalGlyphVertices)/4,f=0;f<d;f++)t.text.opacityVertexArray.emplaceBack(p);for(var m=0,_=s.placedTextSymbolIndices;m<_.length;m+=1){var g=_[m];t.text.placedSymbolArray.get(g).hidden=c.text.isHidden();}}if(h){for(var v=Ve(c.icon),y=0;y<s.numIconVertices/4;y++)t.icon.opacityVertexArray.emplaceBack(v);t.icon.placedSymbolArray.get(a).hidden=c.icon.isHidden();}s.collisionArrays||(s.collisionArrays=t.deserializeCollisionBoxes(i,s.textBoxStartIndex,s.textBoxEndIndex,s.iconBoxStartIndex,s.iconBoxEndIndex));var x=s.collisionArrays;if(x){x.textBox&&t.hasCollisionBoxData()&&Pe(t.collisionBox.collisionVertexArray,c.text.placed,!1),x.iconBox&&t.hasCollisionBoxData()&&Pe(t.collisionBox.collisionVertexArray,c.icon.placed,!1);var b=x.textCircles;if(b&&t.hasCollisionCircleData())for(var w=0;w<b.length;w+=5){var E=l||0===b[w+4];Pe(t.collisionCircle.collisionVertexArray,c.text.placed,E);}}}t.sortFeatures(this.transform.angle),this.retainedQueryData[t.bucketInstanceId]&&(this.retainedQueryData[t.bucketInstanceId].featureSortOrder=t.featureSortOrder),t.hasTextData()&&t.text.opacityVertexBuffer&&t.text.opacityVertexBuffer.updateData(t.text.opacityVertexArray),t.hasIconData()&&t.icon.opacityVertexBuffer&&t.icon.opacityVertexBuffer.updateData(t.icon.opacityVertexArray),t.hasCollisionBoxData()&&t.collisionBox.collisionVertexBuffer&&t.collisionBox.collisionVertexBuffer.updateData(t.collisionBox.collisionVertexArray),t.hasCollisionCircleData()&&t.collisionCircle.collisionVertexBuffer&&t.collisionCircle.collisionVertexBuffer.updateData(t.collisionCircle.collisionVertexArray);},Le.prototype.symbolFadeChange=function(t){return 0===this.fadeDuration?1:(t-this.commitTime)/this.fadeDuration},Le.prototype.hasTransitions=function(t){return this.stale||t-this.lastPlacementChangeTime<this.fadeDuration},Le.prototype.stillRecent=function(t){return"undefined"!==this.commitTime&&this.commitTime+this.fadeDuration>t},Le.prototype.setStale=function(){this.stale=!0;};var ke=Math.pow(2,25),Be=Math.pow(2,24),Oe=Math.pow(2,17),Fe=Math.pow(2,16),Ne=Math.pow(2,9),Ue=Math.pow(2,8),Ze=Math.pow(2,1);function Ve(t){if(0===t.opacity&&!t.placed)return 0;if(1===t.opacity&&t.placed)return 4294967295;var e=t.placed?1:0,i=Math.floor(127*t.opacity);return i*ke+e*Be+i*Oe+e*Fe+i*Ne+e*Ue+i*Ze+e}var je=function(){this._currentTileIndex=0,this._seenCrossTileIDs={};};je.prototype.continuePlacement=function(t,e,i,n,o){for(;this._currentTileIndex<t.length;){var r=t[this._currentTileIndex];if(e.placeLayerTile(n,r,i,this._seenCrossTileIDs),this._currentTileIndex++,o())return!0}};var $e=function(t,e,i,n,o){this.placement=new Le(t,o),this._currentPlacementIndex=e.length-1,this._forceFullPlacement=i,this._showCollisionBoxes=n,this._done=!1;};$e.prototype.isDone=function(){return this._done},$e.prototype.continuePlacement=function(t,e,i){for(var n=this,o=r.now(),a=function(){var t=r.now()-o;return!n._forceFullPlacement&&t>2};this._currentPlacementIndex>=0;){var s=e[t[n._currentPlacementIndex]],l=n.placement.collisionIndex.transform.zoom;if("symbol"===s.type&&(!s.minzoom||s.minzoom<=l)&&(!s.maxzoom||s.maxzoom>l)){if(n._inProgressLayer||(n._inProgressLayer=new je),n._inProgressLayer.continuePlacement(i[s.source],n.placement,n._showCollisionBoxes,s,a))return;delete n._inProgressLayer;}n._currentPlacementIndex--;}this._done=!0;},$e.prototype.commit=function(t,e){return this.placement.commit(t,e),this.placement};var Ge=512/t.default$8/2,We=function(t,e,i){this.tileID=t,this.indexedSymbolInstances={},this.bucketInstanceId=i;for(var n=0,o=e;n<o.length;n+=1){var r=o[n],a=r.key;this.indexedSymbolInstances[a]||(this.indexedSymbolInstances[a]=[]),this.indexedSymbolInstances[a].push({crossTileID:r.crossTileID,coord:this.getScaledCoordinates(r,t)});}};We.prototype.getScaledCoordinates=function(e,i){var n=i.canonical.z-this.tileID.canonical.z,o=Ge/Math.pow(2,n),r=e.anchor;return{x:Math.floor((i.canonical.x*t.default$8+r.x)*o),y:Math.floor((i.canonical.y*t.default$8+r.y)*o)}},We.prototype.findMatches=function(t,e,i){for(var n=this.tileID.canonical.z<e.canonical.z?1:Math.pow(2,this.tileID.canonical.z-e.canonical.z),o=0,r=t;o<r.length;o+=1){var a=r[o];if(!a.crossTileID){var s=this.indexedSymbolInstances[a.key];if(s)for(var l=this.getScaledCoordinates(a,e),c=0,u=s;c<u.length;c+=1){var h=u[c];if(Math.abs(h.coord.x-l.x)<=n&&Math.abs(h.coord.y-l.y)<=n&&!i[h.crossTileID]){i[h.crossTileID]=!0,a.crossTileID=h.crossTileID;break}}}}};var qe=function(){this.maxCrossTileID=0;};qe.prototype.generate=function(){return++this.maxCrossTileID};var Xe=function(){this.indexes={},this.usedCrossTileIDs={},this.lng=0;};Xe.prototype.handleWrapJump=function(t){var e=Math.round((t-this.lng)/360);if(0!==e)for(var i in this.indexes){var n=this.indexes[i],o={};for(var r in n){var a=n[r];a.tileID=a.tileID.unwrapTo(a.tileID.wrap+e),o[a.tileID.key]=a;}this.indexes[i]=o;}this.lng=t;},Xe.prototype.addBucket=function(t,e,i){if(this.indexes[t.overscaledZ]&&this.indexes[t.overscaledZ][t.key]){if(this.indexes[t.overscaledZ][t.key].bucketInstanceId===e.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(t.overscaledZ,this.indexes[t.overscaledZ][t.key]);}for(var n=0,o=e.symbolInstances;n<o.length;n+=1){o[n].crossTileID=0;}this.usedCrossTileIDs[t.overscaledZ]||(this.usedCrossTileIDs[t.overscaledZ]={});var r=this.usedCrossTileIDs[t.overscaledZ];for(var a in this.indexes){var s=this.indexes[a];if(Number(a)>t.overscaledZ)for(var l in s){var c=s[l];c.tileID.isChildOf(t)&&c.findMatches(e.symbolInstances,t,r);}else{var u=s[t.scaledTo(Number(a)).key];u&&u.findMatches(e.symbolInstances,t,r);}}for(var h=0,p=e.symbolInstances;h<p.length;h+=1){var d=p[h];d.crossTileID||(d.crossTileID=i.generate(),r[d.crossTileID]=!0);}return void 0===this.indexes[t.overscaledZ]&&(this.indexes[t.overscaledZ]={}),this.indexes[t.overscaledZ][t.key]=new We(t,e.symbolInstances,e.bucketInstanceId),!0},Xe.prototype.removeBucketCrossTileIDs=function(t,e){for(var i in e.indexedSymbolInstances)for(var n=0,o=e.indexedSymbolInstances[i];n<o.length;n+=1){var r=o[n];delete this.usedCrossTileIDs[t][r.crossTileID];}},Xe.prototype.removeStaleBuckets=function(t){var e=!1;for(var i in this.indexes){var n=this.indexes[i];for(var o in n)t[n[o].bucketInstanceId]||(this.removeBucketCrossTileIDs(i,n[o]),delete n[o],e=!0);}return e};var He=function(){this.layerIndexes={},this.crossTileIDs=new qe,this.maxBucketInstanceId=0,this.bucketsInCurrentPlacement={};};He.prototype.addLayer=function(t,e,i){var n=this.layerIndexes[t.id];void 0===n&&(n=this.layerIndexes[t.id]=new Xe);var o=!1,r={};n.handleWrapJump(i);for(var a=0,s=e;a<s.length;a+=1){var l=s[a],c=l.getBucket(t);c&&t.id===c.layerIds[0]&&(c.bucketInstanceId||(c.bucketInstanceId=++this.maxBucketInstanceId),n.addBucket(l.tileID,c,this.crossTileIDs)&&(o=!0),r[c.bucketInstanceId]=!0);}return n.removeStaleBuckets(r)&&(o=!0),o},He.prototype.pruneUnusedLayers=function(t){var e={};for(var i in t.forEach(function(t){e[t]=!0;}),this.layerIndexes)e[i]||delete this.layerIndexes[i];};var Ke=function(e,i){return t.emitValidationErrors(e,i&&i.filter(function(t){return"source.canvas"!==t.identifier}))},Ye=t.pick(ie,["addLayer","removeLayer","setPaintProperty","setLayoutProperty","setFilter","addSource","removeSource","setLayerZoomRange","setLight","setTransition","setGeoJSONSourceData"]),Je=t.pick(ie,["setCenter","setZoom","setBearing","setPitch"]),Qe=function(e){function i(n,o){var r=this;void 0===o&&(o={}),e.call(this),this.map=n,this.dispatcher=new $((Jt||(Jt=new Qt),Jt),this),this.imageManager=new L,this.glyphManager=new N(n._transformRequest,o.localIdeographFontFamily),this.lineAtlas=new j(256,512),this.crossTileSymbolIndex=new He,this._layers={},this._order=[],this.sourceCaches={},this.zoomHistory=new t.default$23,this._loaded=!1,this._resetUpdates();var a=this;this._rtlTextPluginCallback=i.registerForPluginAvailability(function(t){for(var e in a.dispatcher.broadcast("loadRTLTextPlugin",t.pluginURL,t.completionCallback),a.sourceCaches)a.sourceCaches[e].reload();}),this.on("data",function(t){if("source"===t.dataType&&"metadata"===t.sourceDataType){var e=r.sourceCaches[t.sourceId];if(e){var i=e.getSource();if(i&&i.vectorLayerIds)for(var n in r._layers){var o=r._layers[n];o.source===i.id&&r._validateLayer(o);}}}});}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.loadURL=function(e,i){var n=this;void 0===i&&(i={}),this.fire(new t.Event("dataloading",{dataType:"style"}));var o="boolean"==typeof i.validate?i.validate:!y(e);e=function(t,e){if(!y(t))return t;var i=C(t);return i.path="/styles/v1"+i.path,v(i,e)}(e,i.accessToken);var r=this.map._transformRequest(e,t.ResourceType.Style);t.getJSON(r,function(e,i){e?n.fire(new t.ErrorEvent(e)):i&&n._load(i,o);});},i.prototype.loadJSON=function(e,i){var n=this;void 0===i&&(i={}),this.fire(new t.Event("dataloading",{dataType:"style"})),r.frame(function(){n._load(e,!1!==i.validate);});},i.prototype._load=function(e,i){var n=this;if(!i||!Ke(this,t.validateStyle(e))){for(var o in this._loaded=!0,this.stylesheet=e,e.sources)n.addSource(o,e.sources[o],{validate:!1});e.sprite?function(e,i,n){var o,a,s,l=r.devicePixelRatio>1?"@2x":"";function c(){if(s)n(s);else if(o&&a){var e=r.getImageData(a),i={};for(var l in o){var c=o[l],u=c.width,h=c.height,p=c.x,d=c.y,f=c.sdf,m=c.pixelRatio,_=new t.RGBAImage({width:u,height:h});t.RGBAImage.copy(e,_,{x:p,y:d},{x:0,y:0},{width:u,height:h}),i[l]={data:_,pixelRatio:m,sdf:f};}n(null,i);}}t.getJSON(i(w(e,l,".json"),t.ResourceType.SpriteJSON),function(t,e){s||(s=t,o=e,c());}),t.getImage(i(w(e,l,".png"),t.ResourceType.SpriteImage),function(t,e){s||(s=t,a=e,c());});}(e.sprite,this.map._transformRequest,function(e,i){if(e)n.fire(new t.ErrorEvent(e));else if(i)for(var o in i)n.imageManager.addImage(o,i[o]);n.imageManager.setLoaded(!0),n.fire(new t.Event("data",{dataType:"style"}));}):this.imageManager.setLoaded(!0),this.glyphManager.setURL(e.glyphs);var a=ee(this.stylesheet.layers);this._order=a.map(function(t){return t.id}),this._layers={};for(var s=0,l=a;s<l.length;s+=1){var c=l[s];(c=t.default$22(c)).setEventedParent(n,{layer:{id:c.id}}),n._layers[c.id]=c;}this.dispatcher.broadcast("setLayers",this._serializeLayers(this._order)),this.light=new V(this.stylesheet.light),this.fire(new t.Event("data",{dataType:"style"})),this.fire(new t.Event("style.load"));}},i.prototype._validateLayer=function(e){var i=this.sourceCaches[e.source];if(i){var n=e.sourceLayer;if(n){var o=i.getSource();("geojson"===o.type||o.vectorLayerIds&&-1===o.vectorLayerIds.indexOf(n))&&this.fire(new t.ErrorEvent(new Error('Source layer "'+n+'" does not exist on source "'+o.id+'" as specified by style layer "'+e.id+'"')));}}},i.prototype.loaded=function(){if(!this._loaded)return!1;if(Object.keys(this._updatedSources).length)return!1;for(var t in this.sourceCaches)if(!this.sourceCaches[t].loaded())return!1;return!!this.imageManager.isLoaded()},i.prototype._serializeLayers=function(t){var e=this;return t.map(function(t){return e._layers[t].serialize()})},i.prototype.hasTransitions=function(){if(this.light&&this.light.hasTransition())return!0;for(var t in this.sourceCaches)if(this.sourceCaches[t].hasTransition())return!0;for(var e in this._layers)if(this._layers[e].hasTransition())return!0;return!1},i.prototype._checkLoaded=function(){if(!this._loaded)throw new Error("Style is not done loading")},i.prototype.update=function(e){if(this._loaded){if(this._changed){var i=Object.keys(this._updatedLayers),n=Object.keys(this._removedLayers);for(var o in(i.length||n.length)&&this._updateWorkerLayers(i,n),this._updatedSources){var r=this._updatedSources[o];"reload"===r?this._reloadSource(o):"clear"===r&&this._clearSource(o);}for(var a in this._updatedPaintProps)this._layers[a].updateTransitions(e);this.light.updateTransitions(e),this._resetUpdates(),this.fire(new t.Event("data",{dataType:"style"}));}for(var s in this.sourceCaches)this.sourceCaches[s].used=!1;for(var l=0,c=this._order;l<c.length;l+=1){var u=c[l],h=this._layers[u];h.recalculate(e),!h.isHidden(e.zoom)&&h.source&&(this.sourceCaches[h.source].used=!0);}this.light.recalculate(e),this.z=e.zoom;}},i.prototype._updateWorkerLayers=function(t,e){this.dispatcher.broadcast("updateLayers",{layers:this._serializeLayers(t),removedIds:e});},i.prototype._resetUpdates=function(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={};},i.prototype.setState=function(e){var i=this;if(this._checkLoaded(),Ke(this,t.validateStyle(e)))return!1;(e=t.clone(e)).layers=ee(e.layers);var n=ue(this.serialize(),e).filter(function(t){return!(t.command in Je)});if(0===n.length)return!1;var o=n.filter(function(t){return!(t.command in Ye)});if(o.length>0)throw new Error("Unimplemented: "+o.map(function(t){return t.command}).join(", ")+".");return n.forEach(function(t){"setTransition"!==t.command&&i[t.command].apply(i,t.args);}),this.stylesheet=e,!0},i.prototype.addImage=function(e,i){if(this.getImage(e))return this.fire(new t.ErrorEvent(new Error("An image with this name already exists.")));this.imageManager.addImage(e,i),this.fire(new t.Event("data",{dataType:"style"}));},i.prototype.getImage=function(t){return this.imageManager.getImage(t)},i.prototype.removeImage=function(e){if(!this.getImage(e))return this.fire(new t.ErrorEvent(new Error("No image with this name exists.")));this.imageManager.removeImage(e),this.fire(new t.Event("data",{dataType:"style"}));},i.prototype.addSource=function(e,i,n){var o=this;if(this._checkLoaded(),void 0!==this.sourceCaches[e])throw new Error("There is already a source with this ID");if(!i.type)throw new Error("The type property must be defined, but the only the following properties were given: "+Object.keys(i).join(", ")+".");if(!(["vector","raster","geojson","video","image"].indexOf(i.type)>=0)||!this._validate(t.validateStyle.source,"sources."+e,i,null,n)){this.map&&this.map._collectResourceTiming&&(i.collectResourceTiming=!0);var r=this.sourceCaches[e]=new Xt(e,i,this.dispatcher);r.style=this,r.setEventedParent(this,function(){return{isSourceLoaded:o.loaded(),source:r.serialize(),sourceId:e}}),r.onAdd(this.map),this._changed=!0;}},i.prototype.removeSource=function(e){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error("There is no source with this ID");for(var i in this._layers)if(this._layers[i].source===e)return this.fire(new t.ErrorEvent(new Error('Source "'+e+'" cannot be removed while layer "'+i+'" is using it.')));var n=this.sourceCaches[e];delete this.sourceCaches[e],delete this._updatedSources[e],n.fire(new t.Event("data",{sourceDataType:"metadata",dataType:"source",sourceId:e})),n.setEventedParent(null),n.clearTiles(),n.onRemove&&n.onRemove(this.map),this._changed=!0;},i.prototype.setGeoJSONSourceData=function(t,e){this._checkLoaded(),this.sourceCaches[t].getSource().setData(e),this._changed=!0;},i.prototype.getSource=function(t){return this.sourceCaches[t]&&this.sourceCaches[t].getSource()},i.prototype.addLayer=function(e,i,n){this._checkLoaded();var o=e.id;if(this.getLayer(o))this.fire(new t.ErrorEvent(new Error('Layer with id "'+o+'" already exists on this map')));else if("object"==typeof e.source&&(this.addSource(o,e.source),e=t.clone(e),e=t.extend(e,{source:o})),!this._validate(t.validateStyle.layer,"layers."+o,e,{arrayIndex:-1},n)){var r=t.default$22(e);this._validateLayer(r),r.setEventedParent(this,{layer:{id:o}});var a=i?this._order.indexOf(i):this._order.length;if(i&&-1===a)this.fire(new t.ErrorEvent(new Error('Layer with id "'+i+'" does not exist on this map.')));else{if(this._order.splice(a,0,o),this._layerOrderChanged=!0,this._layers[o]=r,this._removedLayers[o]&&r.source){var s=this._removedLayers[o];delete this._removedLayers[o],s.type!==r.type?this._updatedSources[r.source]="clear":(this._updatedSources[r.source]="reload",this.sourceCaches[r.source].pause());}this._updateLayer(r);}}},i.prototype.moveLayer=function(e,i){if(this._checkLoaded(),this._changed=!0,this._layers[e]){if(e!==i){var n=this._order.indexOf(e);this._order.splice(n,1);var o=i?this._order.indexOf(i):this._order.length;i&&-1===o?this.fire(new t.ErrorEvent(new Error('Layer with id "'+i+'" does not exist on this map.'))):(this._order.splice(o,0,e),this._layerOrderChanged=!0);}}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be moved.")));},i.prototype.removeLayer=function(e){this._checkLoaded();var i=this._layers[e];if(i){i.setEventedParent(null);var n=this._order.indexOf(e);this._order.splice(n,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[e]=i,delete this._layers[e],delete this._updatedLayers[e],delete this._updatedPaintProps[e];}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be removed.")));},i.prototype.getLayer=function(t){return this._layers[t]},i.prototype.setLayerZoomRange=function(e,i,n){this._checkLoaded();var o=this.getLayer(e);o?o.minzoom===i&&o.maxzoom===n||(null!=i&&(o.minzoom=i),null!=n&&(o.maxzoom=n),this._updateLayer(o)):this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot have zoom extent.")));},i.prototype.setFilter=function(e,i){this._checkLoaded();var n=this.getLayer(e);if(n){if(!t.default$10(n.filter,i))return null==i?(n.filter=void 0,void this._updateLayer(n)):void(this._validate(t.validateStyle.filter,"layers."+n.id+".filter",i)||(n.filter=t.clone(i),this._updateLayer(n)))}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be filtered.")));},i.prototype.getFilter=function(e){return t.clone(this.getLayer(e).filter)},i.prototype.setLayoutProperty=function(e,i,n){this._checkLoaded();var o=this.getLayer(e);o?t.default$10(o.getLayoutProperty(i),n)||(o.setLayoutProperty(i,n),this._updateLayer(o)):this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be styled.")));},i.prototype.getLayoutProperty=function(t,e){return this.getLayer(t).getLayoutProperty(e)},i.prototype.setPaintProperty=function(e,i,n){this._checkLoaded();var o=this.getLayer(e);if(o){if(!t.default$10(o.getPaintProperty(i),n)){var r=o._transitionablePaint._values[i].value.isDataDriven();o.setPaintProperty(i,n),(o._transitionablePaint._values[i].value.isDataDriven()||r)&&this._updateLayer(o),this._changed=!0,this._updatedPaintProps[e]=!0;}}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be styled.")));},i.prototype.getPaintProperty=function(t,e){return this.getLayer(t).getPaintProperty(e)},i.prototype.getTransition=function(){return t.extend({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)},i.prototype.serialize=function(){var e=this;return t.filterObject({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,light:this.stylesheet.light,center:this.stylesheet.center,zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,sources:t.mapObject(this.sourceCaches,function(t){return t.serialize()}),layers:this._order.map(function(t){return e._layers[t].serialize()})},function(t){return void 0!==t})},i.prototype._updateLayer=function(t){this._updatedLayers[t.id]=!0,t.source&&!this._updatedSources[t.source]&&(this._updatedSources[t.source]="reload",this.sourceCaches[t.source].pause()),this._changed=!0;},i.prototype._flattenRenderedFeatures=function(t){for(var e=[],i=this._order.length-1;i>=0;i--)for(var n=this._order[i],o=0,r=t;o<r.length;o+=1){var a=r[o][n];if(a)for(var s=0,l=a;s<l.length;s+=1){var c=l[s];e.push(c);}}return e},i.prototype.queryRenderedFeatures=function(e,i,n){i&&i.filter&&this._validate(t.validateStyle.filter,"queryRenderedFeatures.filter",i.filter);var o={};if(i&&i.layers){if(!Array.isArray(i.layers))return this.fire(new t.ErrorEvent(new Error("parameters.layers must be an Array."))),[];for(var r=0,a=i.layers;r<a.length;r+=1){var s=a[r],l=this._layers[s];if(!l)return this.fire(new t.ErrorEvent(new Error("The layer '"+s+"' does not exist in the map's style and cannot be queried for features."))),[];o[l.source]=!0;}}var c=[];for(var u in this.sourceCaches)i.layers&&!o[u]||c.push(at(this.sourceCaches[u],this._layers,e.worldCoordinate,i,n));return this.placement&&c.push(function(t,e,i,n,o){for(var r={},a=n.queryRenderedSymbols(e),s=[],l=0,c=Object.keys(a).map(Number);l<c.length;l+=1){var u=c[l];s.push(o[u]);}s.sort(st);for(var h=function(){var e=d[p],n=e.featureIndex.lookupSymbolFeatures(a[e.bucketInstanceId],e.bucketIndex,e.sourceLayerIndex,i.filter,i.layers,t);for(var o in n){var s=r[o]=r[o]||[],l=n[o];l.sort(function(t,i){var n=e.featureSortOrder;if(n){var o=n.indexOf(t.featureIndex);return n.indexOf(i.featureIndex)-o}return i.featureIndex-t.featureIndex});for(var c=0,u=l;c<u.length;c+=1){var h=u[c];s.push(h.feature);}}},p=0,d=s;p<d.length;p+=1)h();return r}(this._layers,e.viewport,i,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenRenderedFeatures(c)},i.prototype.querySourceFeatures=function(e,i){i&&i.filter&&this._validate(t.validateStyle.filter,"querySourceFeatures.filter",i.filter);var n=this.sourceCaches[e];return n?function(t,e){for(var i=t.getRenderableIds().map(function(e){return t.getTileByID(e)}),n=[],o={},r=0;r<i.length;r++){var a=i[r],s=a.tileID.canonical.key;o[s]||(o[s]=!0,a.querySourceFeatures(n,e));}return n}(n,i):[]},i.prototype.addSourceType=function(t,e,n){return i.getSourceType(t)?n(new Error('A source type called "'+t+'" already exists.')):(i.setSourceType(t,e),e.workerSourceURL?void this.dispatcher.broadcast("loadWorkerSource",{name:t,url:e.workerSourceURL},n):n(null,null))},i.prototype.getLight=function(){return this.light.getLight()},i.prototype.setLight=function(e){this._checkLoaded();var i=this.light.getLight(),n=!1;for(var o in e)if(!t.default$10(e[o],i[o])){n=!0;break}if(n){var a={now:r.now(),transition:t.extend({duration:300,delay:0},this.stylesheet.transition)};this.light.setLight(e),this.light.updateTransitions(a);}},i.prototype._validate=function(e,i,n,o,r){return(!r||!1!==r.validate)&&Ke(this,e.call(t.validateStyle,t.extend({key:i,style:this.serialize(),value:n,styleSpec:t.default$5},o)))},i.prototype._remove=function(){for(var e in t.evented.off("pluginAvailable",this._rtlTextPluginCallback),this.sourceCaches)this.sourceCaches[e].clearTiles();this.dispatcher.remove();},i.prototype._clearSource=function(t){this.sourceCaches[t].clearTiles();},i.prototype._reloadSource=function(t){this.sourceCaches[t].resume(),this.sourceCaches[t].reload();},i.prototype._updateSources=function(t){for(var e in this.sourceCaches)this.sourceCaches[e].update(t);},i.prototype._generateCollisionBoxes=function(){for(var t in this.sourceCaches)this._reloadSource(t);},i.prototype._updatePlacement=function(t,e,i){for(var n=!1,o=!1,a={},s=0,l=this._order;s<l.length;s+=1){var c=l[s],u=this._layers[c];if("symbol"===u.type){if(!a[u.source]){var h=this.sourceCaches[u.source];a[u.source]=h.getRenderableIds().map(function(t){return h.getTileByID(t)}).sort(function(t,e){return e.tileID.overscaledZ-t.tileID.overscaledZ||(t.tileID.isLessThan(e.tileID)?-1:1)});}var p=this.crossTileSymbolIndex.addLayer(u,a[u.source],t.center.lng);n=n||p;}}this.crossTileSymbolIndex.pruneUnusedLayers(this._order);var d=this._layerOrderChanged;if((d||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(r.now()))&&(this.pauseablePlacement=new $e(t,this._order,d,e,i),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,a),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(this.placement,r.now()),o=!0),n&&this.pauseablePlacement.placement.setStale()),o||n)for(var f=0,m=this._order;f<m.length;f+=1){var _=m[f],g=this._layers[_];"symbol"===g.type&&this.placement.updateLayerOpacities(g,a[g.source]);}return!this.pauseablePlacement.isDone()||this.placement.hasTransitions(r.now())},i.prototype.getImages=function(t,e,i){this.imageManager.getImages(e.icons,i);},i.prototype.getGlyphs=function(t,e,i){this.glyphManager.getGlyphs(e.stacks,i);},i}(t.Evented);Qe.getSourceType=function(t){return ot[t]},Qe.setSourceType=function(t,e){ot[t]=e;},Qe.registerForPluginAvailability=t.registerForPluginAvailability;var ti=t.createLayout([{name:"a_pos",type:"Int16",components:2}]),ei={prelude:{fragmentSource:"#ifdef GL_ES\nprecision mediump float;\n#else\n\n#if !defined(lowp)\n#define lowp\n#endif\n\n#if !defined(mediump)\n#define mediump\n#endif\n\n#if !defined(highp)\n#define highp\n#endif\n\n#endif\n",vertexSource:"#ifdef GL_ES\nprecision highp float;\n#else\n\n#if !defined(lowp)\n#define lowp\n#endif\n\n#if !defined(mediump)\n#define mediump\n#endif\n\n#if !defined(highp)\n#define highp\n#endif\n\n#endif\n\n// Unpack a pair of values that have been packed into a single float.\n// The packed values are assumed to be 8-bit unsigned integers, and are\n// packed like so:\n// packedValue = floor(input[0]) * 256 + input[1],\nvec2 unpack_float(const float packedValue) {\n    int packedIntValue = int(packedValue);\n    int v0 = packedIntValue / 256;\n    return vec2(v0, packedIntValue - v0 * 256);\n}\n\nvec2 unpack_opacity(const float packedOpacity) {\n    int intOpacity = int(packedOpacity) / 2;\n    return vec2(float(intOpacity) / 127.0, mod(packedOpacity, 2.0));\n}\n\n// To minimize the number of attributes needed, we encode a 4-component\n// color into a pair of floats (i.e. a vec2) as follows:\n// [ floor(color.r * 255) * 256 + color.g * 255,\n//   floor(color.b * 255) * 256 + color.g * 255 ]\nvec4 decode_color(const vec2 encodedColor) {\n    return vec4(\n        unpack_float(encodedColor[0]) / 255.0,\n        unpack_float(encodedColor[1]) / 255.0\n    );\n}\n\n// Unpack a pair of paint values and interpolate between them.\nfloat unpack_mix_vec2(const vec2 packedValue, const float t) {\n    return mix(packedValue[0], packedValue[1], t);\n}\n\n// Unpack a pair of paint values and interpolate between them.\nvec4 unpack_mix_vec4(const vec4 packedColors, const float t) {\n    vec4 minColor = decode_color(vec2(packedColors[0], packedColors[1]));\n    vec4 maxColor = decode_color(vec2(packedColors[2], packedColors[3]));\n    return mix(minColor, maxColor, t);\n}\n\n// The offset depends on how many pixels are between the world origin and the edge of the tile:\n// vec2 offset = mod(pixel_coord, size)\n//\n// At high zoom levels there are a ton of pixels between the world origin and the edge of the tile.\n// The glsl spec only guarantees 16 bits of precision for highp floats. We need more than that.\n//\n// The pixel_coord is passed in as two 16 bit values:\n// pixel_coord_upper = floor(pixel_coord / 2^16)\n// pixel_coord_lower = mod(pixel_coord, 2^16)\n//\n// The offset is calculated in a series of steps that should preserve this precision:\nvec2 get_pattern_pos(const vec2 pixel_coord_upper, const vec2 pixel_coord_lower,\n    const vec2 pattern_size, const float tile_units_to_pixels, const vec2 pos) {\n\n    vec2 offset = mod(mod(mod(pixel_coord_upper, pattern_size) * 256.0, pattern_size) * 256.0 + pixel_coord_lower, pattern_size);\n    return (tile_units_to_pixels * pos + offset) / pattern_size;\n}\n"},background:{fragmentSource:"uniform vec4 u_color;\nuniform float u_opacity;\n\nvoid main() {\n    gl_FragColor = u_color * u_opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n"},backgroundPattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\nuniform float u_opacity;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\nvoid main() {\n    vec2 imagecoord = mod(v_pos_a, 1.0);\n    vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n    vec4 color1 = texture2D(u_image, pos);\n\n    vec2 imagecoord_b = mod(v_pos_b, 1.0);\n    vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n    vec4 color2 = texture2D(u_image, pos2);\n\n    gl_FragColor = mix(color1, color2, u_mix) * u_opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n\n    v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, a_pos);\n    v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, a_pos);\n}\n"},circle:{fragmentSource:"#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\n\nvarying vec3 v_data;\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize mediump float radius\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize highp vec4 stroke_color\n    #pragma mapbox: initialize mediump float stroke_width\n    #pragma mapbox: initialize lowp float stroke_opacity\n\n    vec2 extrude = v_data.xy;\n    float extrude_length = length(extrude);\n\n    lowp float antialiasblur = v_data.z;\n    float antialiased_blur = -max(blur, antialiasblur);\n\n    float opacity_t = smoothstep(0.0, antialiased_blur, extrude_length - 1.0);\n\n    float color_t = stroke_width < 0.01 ? 0.0 : smoothstep(\n        antialiased_blur,\n        0.0,\n        extrude_length - radius / (radius + stroke_width)\n    );\n\n    gl_FragColor = opacity_t * mix(color * opacity, stroke_color * stroke_opacity, color_t);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform bool u_scale_with_map;\nuniform bool u_pitch_with_map;\nuniform vec2 u_extrude_scale;\nuniform highp float u_camera_to_center_distance;\n\nattribute vec2 a_pos;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\n\nvarying vec3 v_data;\n\nvoid main(void) {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize mediump float radius\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize highp vec4 stroke_color\n    #pragma mapbox: initialize mediump float stroke_width\n    #pragma mapbox: initialize lowp float stroke_opacity\n\n    // unencode the extrusion vector that we snuck into the a_pos vector\n    vec2 extrude = vec2(mod(a_pos, 2.0) * 2.0 - 1.0);\n\n    // multiply a_pos by 0.5, since we had it * 2 in order to sneak\n    // in extrusion data\n    vec2 circle_center = floor(a_pos * 0.5);\n    if (u_pitch_with_map) {\n        vec2 corner_position = circle_center;\n        if (u_scale_with_map) {\n            corner_position += extrude * (radius + stroke_width) * u_extrude_scale;\n        } else {\n            // Pitching the circle with the map effectively scales it with the map\n            // To counteract the effect for pitch-scale: viewport, we rescale the\n            // whole circle based on the pitch scaling effect at its central point\n            vec4 projected_center = u_matrix * vec4(circle_center, 0, 1);\n            corner_position += extrude * (radius + stroke_width) * u_extrude_scale * (projected_center.w / u_camera_to_center_distance);\n        }\n\n        gl_Position = u_matrix * vec4(corner_position, 0, 1);\n    } else {\n        gl_Position = u_matrix * vec4(circle_center, 0, 1);\n\n        if (u_scale_with_map) {\n            gl_Position.xy += extrude * (radius + stroke_width) * u_extrude_scale * u_camera_to_center_distance;\n        } else {\n            gl_Position.xy += extrude * (radius + stroke_width) * u_extrude_scale * gl_Position.w;\n        }\n    }\n\n    // This is a minimum blur distance that serves as a faux-antialiasing for\n    // the circle. since blur is a ratio of the circle's size and the intent is\n    // to keep the blur at roughly 1px, the two are inversely related.\n    lowp float antialiasblur = 1.0 / DEVICE_PIXEL_RATIO / (radius + stroke_width);\n\n    v_data = vec3(extrude.x, extrude.y, antialiasblur);\n}\n"},clippingMask:{fragmentSource:"void main() {\n    gl_FragColor = vec4(1.0);\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n"},heatmap:{fragmentSource:"#pragma mapbox: define highp float weight\n\nuniform highp float u_intensity;\nvarying vec2 v_extrude;\n\n// Gaussian kernel coefficient: 1 / sqrt(2 * PI)\n#define GAUSS_COEF 0.3989422804014327\n\nvoid main() {\n    #pragma mapbox: initialize highp float weight\n\n    // Kernel density estimation with a Gaussian kernel of size 5x5\n    float d = -0.5 * 3.0 * 3.0 * dot(v_extrude, v_extrude);\n    float val = weight * u_intensity * GAUSS_COEF * exp(d);\n\n    gl_FragColor = vec4(val, 1.0, 1.0, 1.0);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\n\nuniform mat4 u_matrix;\nuniform float u_extrude_scale;\nuniform float u_opacity;\nuniform float u_intensity;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_extrude;\n\n// Effective \"0\" in the kernel density texture to adjust the kernel size to;\n// this empirically chosen number minimizes artifacts on overlapping kernels\n// for typical heatmap cases (assuming clustered source)\nconst highp float ZERO = 1.0 / 255.0 / 16.0;\n\n// Gaussian kernel coefficient: 1 / sqrt(2 * PI)\n#define GAUSS_COEF 0.3989422804014327\n\nvoid main(void) {\n    #pragma mapbox: initialize highp float weight\n    #pragma mapbox: initialize mediump float radius\n\n    // unencode the extrusion vector that we snuck into the a_pos vector\n    vec2 unscaled_extrude = vec2(mod(a_pos, 2.0) * 2.0 - 1.0);\n\n    // This 'extrude' comes in ranging from [-1, -1], to [1, 1].  We'll use\n    // it to produce the vertices of a square mesh framing the point feature\n    // we're adding to the kernel density texture.  We'll also pass it as\n    // a varying, so that the fragment shader can determine the distance of\n    // each fragment from the point feature.\n    // Before we do so, we need to scale it up sufficiently so that the\n    // kernel falls effectively to zero at the edge of the mesh.\n    // That is, we want to know S such that\n    // weight * u_intensity * GAUSS_COEF * exp(-0.5 * 3.0^2 * S^2) == ZERO\n    // Which solves to:\n    // S = sqrt(-2.0 * log(ZERO / (weight * u_intensity * GAUSS_COEF))) / 3.0\n    float S = sqrt(-2.0 * log(ZERO / weight / u_intensity / GAUSS_COEF)) / 3.0;\n\n    // Pass the varying in units of radius\n    v_extrude = S * unscaled_extrude;\n\n    // Scale by radius and the zoom-based scale factor to produce actual\n    // mesh position\n    vec2 extrude = v_extrude * radius * u_extrude_scale;\n\n    // multiply a_pos by 0.5, since we had it * 2 in order to sneak\n    // in extrusion data\n    vec4 pos = vec4(floor(a_pos * 0.5) + extrude, 0, 1);\n\n    gl_Position = u_matrix * pos;\n}\n"},heatmapTexture:{fragmentSource:"uniform sampler2D u_image;\nuniform sampler2D u_color_ramp;\nuniform float u_opacity;\nvarying vec2 v_pos;\n\nvoid main() {\n    float t = texture2D(u_image, v_pos).r;\n    vec4 color = texture2D(u_color_ramp, vec2(t, 0.5));\n    gl_FragColor = color * u_opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(0.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_world;\nattribute vec2 a_pos;\nvarying vec2 v_pos;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos * u_world, 0, 1);\n\n    v_pos.x = a_pos.x;\n    v_pos.y = 1.0 - a_pos.y;\n}\n"},collisionBox:{fragmentSource:"\nvarying float v_placed;\nvarying float v_notUsed;\n\nvoid main() {\n\n    float alpha = 0.5;\n\n    // Red = collision, hide label\n    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0) * alpha;\n\n    // Blue = no collision, label is showing\n    if (v_placed > 0.5) {\n        gl_FragColor = vec4(0.0, 0.0, 1.0, 0.5) * alpha;\n    }\n\n    if (v_notUsed > 0.5) {\n        // This box not used, fade it out\n        gl_FragColor *= .1;\n    }\n}",vertexSource:"attribute vec2 a_pos;\nattribute vec2 a_anchor_pos;\nattribute vec2 a_extrude;\nattribute vec2 a_placed;\n\nuniform mat4 u_matrix;\nuniform vec2 u_extrude_scale;\nuniform float u_camera_to_center_distance;\n\nvarying float v_placed;\nvarying float v_notUsed;\n\nvoid main() {\n    vec4 projectedPoint = u_matrix * vec4(a_anchor_pos, 0, 1);\n    highp float camera_to_anchor_distance = projectedPoint.w;\n    highp float collision_perspective_ratio = clamp(\n        0.5 + 0.5 * (u_camera_to_center_distance / camera_to_anchor_distance),\n        0.0, // Prevents oversized near-field boxes in pitched/overzoomed tiles\n        4.0);\n\n    gl_Position = u_matrix * vec4(a_pos, 0.0, 1.0);\n    gl_Position.xy += a_extrude * u_extrude_scale * gl_Position.w * collision_perspective_ratio;\n\n    v_placed = a_placed.x;\n    v_notUsed = a_placed.y;\n}\n"},collisionCircle:{fragmentSource:"uniform float u_overscale_factor;\n\nvarying float v_placed;\nvarying float v_notUsed;\nvarying float v_radius;\nvarying vec2 v_extrude;\nvarying vec2 v_extrude_scale;\n\nvoid main() {\n    float alpha = 0.5;\n\n    // Red = collision, hide label\n    vec4 color = vec4(1.0, 0.0, 0.0, 1.0) * alpha;\n\n    // Blue = no collision, label is showing\n    if (v_placed > 0.5) {\n        color = vec4(0.0, 0.0, 1.0, 0.5) * alpha;\n    }\n\n    if (v_notUsed > 0.5) {\n        // This box not used, fade it out\n        color *= .2;\n    }\n\n    float extrude_scale_length = length(v_extrude_scale);\n    float extrude_length = length(v_extrude) * extrude_scale_length;\n    float stroke_width = 15.0 * extrude_scale_length / u_overscale_factor;\n    float radius = v_radius * extrude_scale_length;\n\n    float distance_to_edge = abs(extrude_length - radius);\n    float opacity_t = smoothstep(-stroke_width, 0.0, -distance_to_edge);\n\n    gl_FragColor = opacity_t * color;\n}\n",vertexSource:"attribute vec2 a_pos;\nattribute vec2 a_anchor_pos;\nattribute vec2 a_extrude;\nattribute vec2 a_placed;\n\nuniform mat4 u_matrix;\nuniform vec2 u_extrude_scale;\nuniform float u_camera_to_center_distance;\n\nvarying float v_placed;\nvarying float v_notUsed;\nvarying float v_radius;\n\nvarying vec2 v_extrude;\nvarying vec2 v_extrude_scale;\n\nvoid main() {\n    vec4 projectedPoint = u_matrix * vec4(a_anchor_pos, 0, 1);\n    highp float camera_to_anchor_distance = projectedPoint.w;\n    highp float collision_perspective_ratio = clamp(\n        0.5 + 0.5 * (u_camera_to_center_distance / camera_to_anchor_distance),\n        0.0, // Prevents oversized near-field circles in pitched/overzoomed tiles\n        4.0);\n\n    gl_Position = u_matrix * vec4(a_pos, 0.0, 1.0);\n\n    highp float padding_factor = 1.2; // Pad the vertices slightly to make room for anti-alias blur\n    gl_Position.xy += a_extrude * u_extrude_scale * padding_factor * gl_Position.w * collision_perspective_ratio;\n\n    v_placed = a_placed.x;\n    v_notUsed = a_placed.y;\n    v_radius = abs(a_extrude.y); // We don't pitch the circles, so both units of the extrusion vector are equal in magnitude to the radius\n\n    v_extrude = a_extrude * padding_factor;\n    v_extrude_scale = u_extrude_scale * u_camera_to_center_distance * collision_perspective_ratio;\n}\n"},debug:{fragmentSource:"uniform highp vec4 u_color;\n\nvoid main() {\n    gl_FragColor = u_color;\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n"},fill:{fragmentSource:"#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float opacity\n\n    gl_FragColor = color * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float opacity\n\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n"},fillOutline:{fragmentSource:"#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_pos;\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 outline_color\n    #pragma mapbox: initialize lowp float opacity\n\n    float dist = length(v_pos - gl_FragCoord.xy);\n    float alpha = 1.0 - smoothstep(0.0, 1.0, dist);\n    gl_FragColor = outline_color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\nuniform vec2 u_world;\n\nvarying vec2 v_pos;\n\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 outline_color\n    #pragma mapbox: initialize lowp float opacity\n\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n    v_pos = (gl_Position.xy / gl_Position.w + 1.0) / 2.0 * u_world;\n}\n"},fillOutlinePattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec2 v_pos;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    vec2 imagecoord = mod(v_pos_a, 1.0);\n    vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n    vec4 color1 = texture2D(u_image, pos);\n\n    vec2 imagecoord_b = mod(v_pos_b, 1.0);\n    vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n    vec4 color2 = texture2D(u_image, pos2);\n\n    // find distance to outline for alpha interpolation\n\n    float dist = length(v_pos - gl_FragCoord.xy);\n    float alpha = 1.0 - smoothstep(0.0, 1.0, dist);\n\n\n    gl_FragColor = mix(color1, color2, u_mix) * alpha * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_world;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec2 v_pos;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n\n    v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, a_pos);\n    v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, a_pos);\n\n    v_pos = (gl_Position.xy / gl_Position.w + 1.0) / 2.0 * u_world;\n}\n"},fillPattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    vec2 imagecoord = mod(v_pos_a, 1.0);\n    vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n    vec4 color1 = texture2D(u_image, pos);\n\n    vec2 imagecoord_b = mod(v_pos_b, 1.0);\n    vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n    vec4 color2 = texture2D(u_image, pos2);\n\n    gl_FragColor = mix(color1, color2, u_mix) * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n\n    v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, a_pos);\n    v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, a_pos);\n}\n"},fillExtrusion:{fragmentSource:"varying vec4 v_color;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define highp vec4 color\n\nvoid main() {\n    #pragma mapbox: initialize lowp float base\n    #pragma mapbox: initialize lowp float height\n    #pragma mapbox: initialize highp vec4 color\n\n    gl_FragColor = v_color;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec3 u_lightcolor;\nuniform lowp vec3 u_lightpos;\nuniform lowp float u_lightintensity;\n\nattribute vec2 a_pos;\nattribute vec4 a_normal_ed;\n\nvarying vec4 v_color;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\n#pragma mapbox: define highp vec4 color\n\nvoid main() {\n    #pragma mapbox: initialize lowp float base\n    #pragma mapbox: initialize lowp float height\n    #pragma mapbox: initialize highp vec4 color\n\n    vec3 normal = a_normal_ed.xyz;\n\n    base = max(0.0, base);\n    height = max(0.0, height);\n\n    float t = mod(normal.x, 2.0);\n\n    gl_Position = u_matrix * vec4(a_pos, t > 0.0 ? height : base, 1);\n\n    // Relative luminance (how dark/bright is the surface color?)\n    float colorvalue = color.r * 0.2126 + color.g * 0.7152 + color.b * 0.0722;\n\n    v_color = vec4(0.0, 0.0, 0.0, 1.0);\n\n    // Add slight ambient lighting so no extrusions are totally black\n    vec4 ambientlight = vec4(0.03, 0.03, 0.03, 1.0);\n    color += ambientlight;\n\n    // Calculate cos(theta), where theta is the angle between surface normal and diffuse light ray\n    float directional = clamp(dot(normal / 16384.0, u_lightpos), 0.0, 1.0);\n\n    // Adjust directional so that\n    // the range of values for highlight/shading is narrower\n    // with lower light intensity\n    // and with lighter/brighter surface colors\n    directional = mix((1.0 - u_lightintensity), max((1.0 - colorvalue + u_lightintensity), 1.0), directional);\n\n    // Add gradient along z axis of side surfaces\n    if (normal.y != 0.0) {\n        directional *= clamp((t + base) * pow(height / 150.0, 0.5), mix(0.7, 0.98, 1.0 - u_lightintensity), 1.0);\n    }\n\n    // Assign final color based on surface + ambient light color, diffuse light directional, and light color\n    // with lower bounds adjusted to hue of light\n    // so that shading is tinted with the complementary (opposite) color to the light color\n    v_color.r += clamp(color.r * directional * u_lightcolor.r, mix(0.0, 0.3, 1.0 - u_lightcolor.r), 1.0);\n    v_color.g += clamp(color.g * directional * u_lightcolor.g, mix(0.0, 0.3, 1.0 - u_lightcolor.g), 1.0);\n    v_color.b += clamp(color.b * directional * u_lightcolor.b, mix(0.0, 0.3, 1.0 - u_lightcolor.b), 1.0);\n}\n"},fillExtrusionPattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec4 v_lighting;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\nvoid main() {\n    #pragma mapbox: initialize lowp float base\n    #pragma mapbox: initialize lowp float height\n\n    vec2 imagecoord = mod(v_pos_a, 1.0);\n    vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n    vec4 color1 = texture2D(u_image, pos);\n\n    vec2 imagecoord_b = mod(v_pos_b, 1.0);\n    vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n    vec4 color2 = texture2D(u_image, pos2);\n\n    vec4 mixedColor = mix(color1, color2, u_mix);\n\n    gl_FragColor = mixedColor * v_lighting;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\nuniform float u_height_factor;\n\nuniform vec3 u_lightcolor;\nuniform lowp vec3 u_lightpos;\nuniform lowp float u_lightintensity;\n\nattribute vec2 a_pos;\nattribute vec4 a_normal_ed;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec4 v_lighting;\nvarying float v_directional;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\nvoid main() {\n    #pragma mapbox: initialize lowp float base\n    #pragma mapbox: initialize lowp float height\n\n    vec3 normal = a_normal_ed.xyz;\n    float edgedistance = a_normal_ed.w;\n\n    base = max(0.0, base);\n    height = max(0.0, height);\n\n    float t = mod(normal.x, 2.0);\n    float z = t > 0.0 ? height : base;\n\n    gl_Position = u_matrix * vec4(a_pos, z, 1);\n\n    vec2 pos = normal.x == 1.0 && normal.y == 0.0 && normal.z == 16384.0\n        ? a_pos // extrusion top\n        : vec2(edgedistance, z * u_height_factor); // extrusion side\n\n    v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, pos);\n    v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, pos);\n\n    v_lighting = vec4(0.0, 0.0, 0.0, 1.0);\n    float directional = clamp(dot(normal / 16383.0, u_lightpos), 0.0, 1.0);\n    directional = mix((1.0 - u_lightintensity), max((0.5 + u_lightintensity), 1.0), directional);\n\n    if (normal.y != 0.0) {\n        directional *= clamp((t + base) * pow(height / 150.0, 0.5), mix(0.7, 0.98, 1.0 - u_lightintensity), 1.0);\n    }\n\n    v_lighting.rgb += clamp(directional * u_lightcolor, mix(vec3(0.0), vec3(0.3), 1.0 - u_lightcolor), vec3(1.0));\n}\n"},extrusionTexture:{fragmentSource:"uniform sampler2D u_image;\nuniform float u_opacity;\nvarying vec2 v_pos;\n\nvoid main() {\n    gl_FragColor = texture2D(u_image, v_pos) * u_opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(0.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_world;\nattribute vec2 a_pos;\nvarying vec2 v_pos;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos * u_world, 0, 1);\n\n    v_pos.x = a_pos.x;\n    v_pos.y = 1.0 - a_pos.y;\n}\n"},hillshadePrepare:{fragmentSource:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D u_image;\nvarying vec2 v_pos;\nuniform vec2 u_dimension;\nuniform float u_zoom;\nuniform float u_maxzoom;\n\nfloat getElevation(vec2 coord, float bias) {\n    // Convert encoded elevation value to meters\n    vec4 data = texture2D(u_image, coord) * 255.0;\n    return (data.r + data.g * 256.0 + data.b * 256.0 * 256.0) / 4.0;\n}\n\nvoid main() {\n    vec2 epsilon = 1.0 / u_dimension;\n\n    // queried pixels:\n    // +-----------+\n    // |   |   |   |\n    // | a | b | c |\n    // |   |   |   |\n    // +-----------+\n    // |   |   |   |\n    // | d | e | f |\n    // |   |   |   |\n    // +-----------+\n    // |   |   |   |\n    // | g | h | i |\n    // |   |   |   |\n    // +-----------+\n\n    float a = getElevation(v_pos + vec2(-epsilon.x, -epsilon.y), 0.0);\n    float b = getElevation(v_pos + vec2(0, -epsilon.y), 0.0);\n    float c = getElevation(v_pos + vec2(epsilon.x, -epsilon.y), 0.0);\n    float d = getElevation(v_pos + vec2(-epsilon.x, 0), 0.0);\n    float e = getElevation(v_pos, 0.0);\n    float f = getElevation(v_pos + vec2(epsilon.x, 0), 0.0);\n    float g = getElevation(v_pos + vec2(-epsilon.x, epsilon.y), 0.0);\n    float h = getElevation(v_pos + vec2(0, epsilon.y), 0.0);\n    float i = getElevation(v_pos + vec2(epsilon.x, epsilon.y), 0.0);\n\n    // here we divide the x and y slopes by 8 * pixel size\n    // where pixel size (aka meters/pixel) is:\n    // circumference of the world / (pixels per tile * number of tiles)\n    // which is equivalent to: 8 * 40075016.6855785 / (512 * pow(2, u_zoom))\n    // which can be reduced to: pow(2, 19.25619978527 - u_zoom)\n    // we want to vertically exaggerate the hillshading though, because otherwise\n    // it is barely noticeable at low zooms. to do this, we multiply this by some\n    // scale factor pow(2, (u_zoom - u_maxzoom) * a) where a is an arbitrary value\n    // Here we use a=0.3 which works out to the expression below. see \n    // nickidlugash's awesome breakdown for more info\n    // https://github.com/mapbox/mapbox-gl-js/pull/5286#discussion_r148419556\n    float exaggeration = u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;\n\n    vec2 deriv = vec2(\n        (c + f + f + i) - (a + d + d + g),\n        (g + h + h + i) - (a + b + b + c)\n    ) /  pow(2.0, (u_zoom - u_maxzoom) * exaggeration + 19.2562 - u_zoom);\n\n    gl_FragColor = clamp(vec4(\n        deriv.x / 2.0 + 0.5,\n        deriv.y / 2.0 + 0.5,\n        1.0,\n        1.0), 0.0, 1.0);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n    v_pos = (a_texture_pos / 8192.0) / 2.0 + 0.25;\n}\n"},hillshade:{fragmentSource:"uniform sampler2D u_image;\nvarying vec2 v_pos;\n\nuniform vec2 u_latrange;\nuniform vec2 u_light;\nuniform vec4 u_shadow;\nuniform vec4 u_highlight;\nuniform vec4 u_accent;\n\n#define PI 3.141592653589793\n\nvoid main() {\n    vec4 pixel = texture2D(u_image, v_pos);\n\n    vec2 deriv = ((pixel.rg * 2.0) - 1.0);\n\n    // We divide the slope by a scale factor based on the cosin of the pixel's approximate latitude\n    // to account for mercator projection distortion. see #4807 for details\n    float scaleFactor = cos(radians((u_latrange[0] - u_latrange[1]) * (1.0 - v_pos.y) + u_latrange[1]));\n    // We also multiply the slope by an arbitrary z-factor of 1.25\n    float slope = atan(1.25 * length(deriv) / scaleFactor);\n    float aspect = deriv.x != 0.0 ? atan(deriv.y, -deriv.x) : PI / 2.0 * (deriv.y > 0.0 ? 1.0 : -1.0);\n\n    float intensity = u_light.x;\n    // We add PI to make this property match the global light object, which adds PI/2 to the light's azimuthal\n    // position property to account for 0deg corresponding to north/the top of the viewport in the style spec\n    // and the original shader was written to accept (-illuminationDirection - 90) as the azimuthal.\n    float azimuth = u_light.y + PI;\n\n    // We scale the slope exponentially based on intensity, using a calculation similar to\n    // the exponential interpolation function in the style spec:\n    // https://github.com/mapbox/mapbox-gl-js/blob/master/src/style-spec/expression/definitions/interpolate.js#L217-L228\n    // so that higher intensity values create more opaque hillshading.\n    float base = 1.875 - intensity * 1.75;\n    float maxValue = 0.5 * PI;\n    float scaledSlope = intensity != 0.5 ? ((pow(base, slope) - 1.0) / (pow(base, maxValue) - 1.0)) * maxValue : slope;\n\n    // The accent color is calculated with the cosine of the slope while the shade color is calculated with the sine\n    // so that the accent color's rate of change eases in while the shade color's eases out.\n    float accent = cos(scaledSlope);\n    // We multiply both the accent and shade color by a clamped intensity value\n    // so that intensities >= 0.5 do not additionally affect the color values\n    // while intensity values < 0.5 make the overall color more transparent.\n    vec4 accent_color = (1.0 - accent) * u_accent * clamp(intensity * 2.0, 0.0, 1.0);\n    float shade = abs(mod((aspect + azimuth) / PI + 0.5, 2.0) - 1.0);\n    vec4 shade_color = mix(u_shadow, u_highlight, shade) * sin(scaledSlope) * clamp(intensity * 2.0, 0.0, 1.0);\n    gl_FragColor = accent_color * (1.0 - shade_color.a) + shade_color;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n    v_pos = a_texture_pos / 8192.0;\n}\n"},line:{fragmentSource:"#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_width2;\nvarying vec2 v_normal;\nvarying float v_gamma_scale;\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n\n    // Calculate the distance of the pixel from the line in pixels.\n    float dist = length(v_normal) * v_width2.s;\n\n    // Calculate the antialiasing fade factor. This is either when fading in\n    // the line in case of an offset line (v_width2.t) or when fading out\n    // (v_width2.s)\n    float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n    float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n    gl_FragColor = color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\n// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_gamma_scale;\nvarying highp float v_linesofar;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize mediump float gapwidth\n    #pragma mapbox: initialize lowp float offset\n    #pragma mapbox: initialize mediump float width\n\n    vec2 a_extrude = a_data.xy - 128.0;\n    float a_direction = mod(a_data.z, 4.0) - 1.0;\n\n    v_linesofar = (floor(a_data.z / 4.0) + a_data.w * 64.0) * 2.0;\n\n    vec2 pos = a_pos_normal.xy;\n\n    // x is 1 if it's a round cap, 0 otherwise\n    // y is 1 if the normal points up, and -1 if it points down\n    mediump vec2 normal = a_pos_normal.zw;\n    v_normal = normal;\n\n    // these transformations used to be applied in the JS and native code bases.\n    // moved them into the shader for clarity and simplicity.\n    gapwidth = gapwidth / 2.0;\n    float halfwidth = width / 2.0;\n    offset = -1.0 * offset;\n\n    float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n    float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n    // Scale the extrusion vector down to a normal and then up by the line width\n    // of this vertex.\n    mediump vec2 dist = outset * a_extrude * scale;\n\n    // Calculate the offset when drawing a line that is to the side of the actual line.\n    // We do this by creating a vector that points towards the extrude, but rotate\n    // it when we're drawing round end points (a_direction = -1 or 1) since their\n    // extrude vector points in another direction.\n    mediump float u = 0.5 * a_direction;\n    mediump float t = 1.0 - abs(u);\n    mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n    vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n    gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n    // calculate how much the perspective view squishes or stretches the extrude\n    float extrude_length_without_perspective = length(dist);\n    float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n    v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n    v_width2 = vec2(outset, inset);\n}\n"},lineGradient:{fragmentSource:"\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n\nuniform sampler2D u_image;\n\nvarying vec2 v_width2;\nvarying vec2 v_normal;\nvarying float v_gamma_scale;\nvarying highp float v_lineprogress;\n\nvoid main() {\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n\n    // Calculate the distance of the pixel from the line in pixels.\n    float dist = length(v_normal) * v_width2.s;\n\n    // Calculate the antialiasing fade factor. This is either when fading in\n    // the line in case of an offset line (v_width2.t) or when fading out\n    // (v_width2.s)\n    float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n    float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n    // For gradient lines, v_lineprogress is the ratio along the entire line,\n    // scaled to [0, 2^15), and the gradient ramp is stored in a texture.\n    vec4 color = texture2D(u_image, vec2(v_lineprogress, 0.5));\n\n    gl_FragColor = color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"\n// the attribute conveying progress along a line is scaled to [0, 2^15)\n#define MAX_LINE_DISTANCE 32767.0\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\n// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_gamma_scale;\nvarying highp float v_lineprogress;\n\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n\nvoid main() {\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize mediump float gapwidth\n    #pragma mapbox: initialize lowp float offset\n    #pragma mapbox: initialize mediump float width\n\n    vec2 a_extrude = a_data.xy - 128.0;\n    float a_direction = mod(a_data.z, 4.0) - 1.0;\n\n    v_lineprogress = (floor(a_data.z / 4.0) + a_data.w * 64.0) * 2.0 / MAX_LINE_DISTANCE;\n\n    vec2 pos = a_pos_normal.xy;\n\n    // x is 1 if it's a round cap, 0 otherwise\n    // y is 1 if the normal points up, and -1 if it points down\n    mediump vec2 normal = a_pos_normal.zw;\n    v_normal = normal;\n\n    // these transformations used to be applied in the JS and native code bases.\n    // moved them into the shader for clarity and simplicity.\n    gapwidth = gapwidth / 2.0;\n    float halfwidth = width / 2.0;\n    offset = -1.0 * offset;\n\n    float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n    float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n    // Scale the extrusion vector down to a normal and then up by the line width\n    // of this vertex.\n    mediump vec2 dist = outset * a_extrude * scale;\n\n    // Calculate the offset when drawing a line that is to the side of the actual line.\n    // We do this by creating a vector that points towards the extrude, but rotate\n    // it when we're drawing round end points (a_direction = -1 or 1) since their\n    // extrude vector points in another direction.\n    mediump float u = 0.5 * a_direction;\n    mediump float t = 1.0 - abs(u);\n    mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n    vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n    gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n    // calculate how much the perspective view squishes or stretches the extrude\n    float extrude_length_without_perspective = length(dist);\n    float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n    v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n    v_width2 = vec2(outset, inset);\n}\n"},linePattern:{fragmentSource:"uniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_fade;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_linesofar;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n\n    // Calculate the distance of the pixel from the line in pixels.\n    float dist = length(v_normal) * v_width2.s;\n\n    // Calculate the antialiasing fade factor. This is either when fading in\n    // the line in case of an offset line (v_width2.t) or when fading out\n    // (v_width2.s)\n    float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n    float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n    float x_a = mod(v_linesofar / u_pattern_size_a.x, 1.0);\n    float x_b = mod(v_linesofar / u_pattern_size_b.x, 1.0);\n\n    // v_normal.y is 0 at the midpoint of the line, -1 at the lower edge, 1 at the upper edge\n    // we clamp the line width outset to be between 0 and half the pattern height plus padding (2.0)\n    // to ensure we don't sample outside the designated symbol on the sprite sheet.\n    // 0.5 is added to shift the component to be bounded between 0 and 1 for interpolation of\n    // the texture coordinate\n    float y_a = 0.5 + (v_normal.y * clamp(v_width2.s, 0.0, (u_pattern_size_a.y + 2.0) / 2.0) / u_pattern_size_a.y);\n    float y_b = 0.5 + (v_normal.y * clamp(v_width2.s, 0.0, (u_pattern_size_b.y + 2.0) / 2.0) / u_pattern_size_b.y);\n    vec2 pos_a = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, vec2(x_a, y_a));\n    vec2 pos_b = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, vec2(x_b, y_b));\n\n    vec4 color = mix(texture2D(u_image, pos_a), texture2D(u_image, pos_b), u_fade);\n\n    gl_FragColor = color * alpha * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\n// We scale the distance before adding it to the buffers so that we can store\n// long distances for long segments. Use this value to unscale the distance.\n#define LINE_DISTANCE_SCALE 2.0\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_linesofar;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n\nvoid main() {\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize lowp float offset\n    #pragma mapbox: initialize mediump float gapwidth\n    #pragma mapbox: initialize mediump float width\n\n    vec2 a_extrude = a_data.xy - 128.0;\n    float a_direction = mod(a_data.z, 4.0) - 1.0;\n    float a_linesofar = (floor(a_data.z / 4.0) + a_data.w * 64.0) * LINE_DISTANCE_SCALE;\n\n    vec2 pos = a_pos_normal.xy;\n\n    // x is 1 if it's a round cap, 0 otherwise\n    // y is 1 if the normal points up, and -1 if it points down\n    mediump vec2 normal = a_pos_normal.zw;\n    v_normal = normal;\n\n    // these transformations used to be applied in the JS and native code bases.\n    // moved them into the shader for clarity and simplicity.\n    gapwidth = gapwidth / 2.0;\n    float halfwidth = width / 2.0;\n    offset = -1.0 * offset;\n\n    float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n    float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n    // Scale the extrusion vector down to a normal and then up by the line width\n    // of this vertex.\n    mediump vec2 dist = outset * a_extrude * scale;\n\n    // Calculate the offset when drawing a line that is to the side of the actual line.\n    // We do this by creating a vector that points towards the extrude, but rotate\n    // it when we're drawing round end points (a_direction = -1 or 1) since their\n    // extrude vector points in another direction.\n    mediump float u = 0.5 * a_direction;\n    mediump float t = 1.0 - abs(u);\n    mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n    vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n    gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n    // calculate how much the perspective view squishes or stretches the extrude\n    float extrude_length_without_perspective = length(dist);\n    float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n    v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n    v_linesofar = a_linesofar;\n    v_width2 = vec2(outset, inset);\n}\n"},lineSDF:{fragmentSource:"\nuniform sampler2D u_image;\nuniform float u_sdfgamma;\nuniform float u_mix;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying vec2 v_tex_a;\nvarying vec2 v_tex_b;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize mediump float width\n    #pragma mapbox: initialize lowp float floorwidth\n\n    // Calculate the distance of the pixel from the line in pixels.\n    float dist = length(v_normal) * v_width2.s;\n\n    // Calculate the antialiasing fade factor. This is either when fading in\n    // the line in case of an offset line (v_width2.t) or when fading out\n    // (v_width2.s)\n    float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n    float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n    float sdfdist_a = texture2D(u_image, v_tex_a).a;\n    float sdfdist_b = texture2D(u_image, v_tex_b).a;\n    float sdfdist = mix(sdfdist_a, sdfdist_b, u_mix);\n    alpha *= smoothstep(0.5 - u_sdfgamma / floorwidth, 0.5 + u_sdfgamma / floorwidth, sdfdist);\n\n    gl_FragColor = color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\n// We scale the distance before adding it to the buffers so that we can store\n// long distances for long segments. Use this value to unscale the distance.\n#define LINE_DISTANCE_SCALE 2.0\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_patternscale_a;\nuniform float u_tex_y_a;\nuniform vec2 u_patternscale_b;\nuniform float u_tex_y_b;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying vec2 v_tex_a;\nvarying vec2 v_tex_b;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize mediump float gapwidth\n    #pragma mapbox: initialize lowp float offset\n    #pragma mapbox: initialize mediump float width\n    #pragma mapbox: initialize lowp float floorwidth\n\n    vec2 a_extrude = a_data.xy - 128.0;\n    float a_direction = mod(a_data.z, 4.0) - 1.0;\n    float a_linesofar = (floor(a_data.z / 4.0) + a_data.w * 64.0) * LINE_DISTANCE_SCALE;\n\n    vec2 pos = a_pos_normal.xy;\n\n    // x is 1 if it's a round cap, 0 otherwise\n    // y is 1 if the normal points up, and -1 if it points down\n    mediump vec2 normal = a_pos_normal.zw;\n    v_normal = normal;\n\n    // these transformations used to be applied in the JS and native code bases.\n    // moved them into the shader for clarity and simplicity.\n    gapwidth = gapwidth / 2.0;\n    float halfwidth = width / 2.0;\n    offset = -1.0 * offset;\n\n    float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n    float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n    // Scale the extrusion vector down to a normal and then up by the line width\n    // of this vertex.\n    mediump vec2 dist =outset * a_extrude * scale;\n\n    // Calculate the offset when drawing a line that is to the side of the actual line.\n    // We do this by creating a vector that points towards the extrude, but rotate\n    // it when we're drawing round end points (a_direction = -1 or 1) since their\n    // extrude vector points in another direction.\n    mediump float u = 0.5 * a_direction;\n    mediump float t = 1.0 - abs(u);\n    mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n    vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n    gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n    // calculate how much the perspective view squishes or stretches the extrude\n    float extrude_length_without_perspective = length(dist);\n    float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n    v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n    v_tex_a = vec2(a_linesofar * u_patternscale_a.x / floorwidth, normal.y * u_patternscale_a.y + u_tex_y_a);\n    v_tex_b = vec2(a_linesofar * u_patternscale_b.x / floorwidth, normal.y * u_patternscale_b.y + u_tex_y_b);\n\n    v_width2 = vec2(outset, inset);\n}\n"},raster:{fragmentSource:"uniform float u_fade_t;\nuniform float u_opacity;\nuniform sampler2D u_image0;\nuniform sampler2D u_image1;\nvarying vec2 v_pos0;\nvarying vec2 v_pos1;\n\nuniform float u_brightness_low;\nuniform float u_brightness_high;\n\nuniform float u_saturation_factor;\nuniform float u_contrast_factor;\nuniform vec3 u_spin_weights;\n\nvoid main() {\n\n    // read and cross-fade colors from the main and parent tiles\n    vec4 color0 = texture2D(u_image0, v_pos0);\n    vec4 color1 = texture2D(u_image1, v_pos1);\n    if (color0.a > 0.0) {\n        color0.rgb = color0.rgb / color0.a;\n    }\n    if (color1.a > 0.0) {\n        color1.rgb = color1.rgb / color1.a;\n    }\n    vec4 color = mix(color0, color1, u_fade_t);\n    color.a *= u_opacity;\n    vec3 rgb = color.rgb;\n\n    // spin\n    rgb = vec3(\n        dot(rgb, u_spin_weights.xyz),\n        dot(rgb, u_spin_weights.zxy),\n        dot(rgb, u_spin_weights.yzx));\n\n    // saturation\n    float average = (color.r + color.g + color.b) / 3.0;\n    rgb += (average - rgb) * u_saturation_factor;\n\n    // contrast\n    rgb = (rgb - 0.5) * u_contrast_factor + 0.5;\n\n    // brightness\n    vec3 u_high_vec = vec3(u_brightness_low, u_brightness_low, u_brightness_low);\n    vec3 u_low_vec = vec3(u_brightness_high, u_brightness_high, u_brightness_high);\n\n    gl_FragColor = vec4(mix(u_high_vec, u_low_vec, rgb) * color.a, color.a);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_tl_parent;\nuniform float u_scale_parent;\nuniform float u_buffer_scale;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos0;\nvarying vec2 v_pos1;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n    // We are using Int16 for texture position coordinates to give us enough precision for\n    // fractional coordinates. We use 8192 to scale the texture coordinates in the buffer\n    // as an arbitrarily high number to preserve adequate precision when rendering.\n    // This is also the same value as the EXTENT we are using for our tile buffer pos coordinates,\n    // so math for modifying either is consistent.\n    v_pos0 = (((a_texture_pos / 8192.0) - 0.5) / u_buffer_scale ) + 0.5;\n    v_pos1 = (v_pos0 * u_scale_parent) + u_tl_parent;\n}\n"},symbolIcon:{fragmentSource:"uniform sampler2D u_texture;\n\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_tex;\nvarying float v_fade_opacity;\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    lowp float alpha = opacity * v_fade_opacity;\n    gl_FragColor = texture2D(u_texture, v_tex) * alpha;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"const float PI = 3.141592653589793;\n\nattribute vec4 a_pos_offset;\nattribute vec4 a_data;\nattribute vec3 a_projected_pos;\nattribute float a_fade_opacity;\n\nuniform bool u_is_size_zoom_constant;\nuniform bool u_is_size_feature_constant;\nuniform highp float u_size_t; // used to interpolate between zoom stops when size is a composite function\nuniform highp float u_size; // used when size is both zoom and feature constant\nuniform highp float u_camera_to_center_distance;\nuniform highp float u_pitch;\nuniform bool u_rotate_symbol;\nuniform highp float u_aspect_ratio;\nuniform float u_fade_change;\n\n#pragma mapbox: define lowp float opacity\n\nuniform mat4 u_matrix;\nuniform mat4 u_label_plane_matrix;\nuniform mat4 u_gl_coord_matrix;\n\nuniform bool u_is_text;\nuniform bool u_pitch_with_map;\n\nuniform vec2 u_texsize;\n\nvarying vec2 v_tex;\nvarying float v_fade_opacity;\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    vec2 a_pos = a_pos_offset.xy;\n    vec2 a_offset = a_pos_offset.zw;\n\n    vec2 a_tex = a_data.xy;\n    vec2 a_size = a_data.zw;\n\n    highp float segment_angle = -a_projected_pos[2];\n\n    float size;\n    if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {\n        size = mix(a_size[0], a_size[1], u_size_t) / 10.0;\n    } else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {\n        size = a_size[0] / 10.0;\n    } else if (!u_is_size_zoom_constant && u_is_size_feature_constant) {\n        size = u_size;\n    } else {\n        size = u_size;\n    }\n\n    vec4 projectedPoint = u_matrix * vec4(a_pos, 0, 1);\n    highp float camera_to_anchor_distance = projectedPoint.w;\n    // See comments in symbol_sdf.vertex\n    highp float distance_ratio = u_pitch_with_map ?\n        camera_to_anchor_distance / u_camera_to_center_distance :\n        u_camera_to_center_distance / camera_to_anchor_distance;\n    highp float perspective_ratio = clamp(\n            0.5 + 0.5 * distance_ratio,\n            0.0, // Prevents oversized near-field symbols in pitched/overzoomed tiles\n            4.0);\n\n    size *= perspective_ratio;\n\n    float fontScale = u_is_text ? size / 24.0 : size;\n\n    highp float symbol_rotation = 0.0;\n    if (u_rotate_symbol) {\n        // See comments in symbol_sdf.vertex\n        vec4 offsetProjectedPoint = u_matrix * vec4(a_pos + vec2(1, 0), 0, 1);\n\n        vec2 a = projectedPoint.xy / projectedPoint.w;\n        vec2 b = offsetProjectedPoint.xy / offsetProjectedPoint.w;\n\n        symbol_rotation = atan((b.y - a.y) / u_aspect_ratio, b.x - a.x);\n    }\n\n    highp float angle_sin = sin(segment_angle + symbol_rotation);\n    highp float angle_cos = cos(segment_angle + symbol_rotation);\n    mat2 rotation_matrix = mat2(angle_cos, -1.0 * angle_sin, angle_sin, angle_cos);\n\n    vec4 projected_pos = u_label_plane_matrix * vec4(a_projected_pos.xy, 0.0, 1.0);\n    gl_Position = u_gl_coord_matrix * vec4(projected_pos.xy / projected_pos.w + rotation_matrix * (a_offset / 32.0 * fontScale), 0.0, 1.0);\n\n    v_tex = a_tex / u_texsize;\n    vec2 fade_opacity = unpack_opacity(a_fade_opacity);\n    float fade_change = fade_opacity[1] > 0.5 ? u_fade_change : -u_fade_change;\n    v_fade_opacity = max(0.0, min(1.0, fade_opacity[0] + fade_change));\n}\n"},symbolSDF:{fragmentSource:"#define SDF_PX 8.0\n#define EDGE_GAMMA 0.105/DEVICE_PIXEL_RATIO\n\nuniform bool u_is_halo;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\n\nuniform sampler2D u_texture;\nuniform highp float u_gamma_scale;\nuniform bool u_is_text;\n\nvarying vec2 v_data0;\nvarying vec3 v_data1;\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 fill_color\n    #pragma mapbox: initialize highp vec4 halo_color\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize lowp float halo_width\n    #pragma mapbox: initialize lowp float halo_blur\n\n    vec2 tex = v_data0.xy;\n    float gamma_scale = v_data1.x;\n    float size = v_data1.y;\n    float fade_opacity = v_data1[2];\n\n    float fontScale = u_is_text ? size / 24.0 : size;\n\n    lowp vec4 color = fill_color;\n    highp float gamma = EDGE_GAMMA / (fontScale * u_gamma_scale);\n    lowp float buff = (256.0 - 64.0) / 256.0;\n    if (u_is_halo) {\n        color = halo_color;\n        gamma = (halo_blur * 1.19 / SDF_PX + EDGE_GAMMA) / (fontScale * u_gamma_scale);\n        buff = (6.0 - halo_width / fontScale) / SDF_PX;\n    }\n\n    lowp float dist = texture2D(u_texture, tex).a;\n    highp float gamma_scaled = gamma * gamma_scale;\n    highp float alpha = smoothstep(buff - gamma_scaled, buff + gamma_scaled, dist);\n\n    gl_FragColor = color * (alpha * opacity * fade_opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"const float PI = 3.141592653589793;\n\nattribute vec4 a_pos_offset;\nattribute vec4 a_data;\nattribute vec3 a_projected_pos;\nattribute float a_fade_opacity;\n\n// contents of a_size vary based on the type of property value\n// used for {text,icon}-size.\n// For constants, a_size is disabled.\n// For source functions, we bind only one value per vertex: the value of {text,icon}-size evaluated for the current feature.\n// For composite functions:\n// [ text-size(lowerZoomStop, feature),\n//   text-size(upperZoomStop, feature) ]\nuniform bool u_is_size_zoom_constant;\nuniform bool u_is_size_feature_constant;\nuniform highp float u_size_t; // used to interpolate between zoom stops when size is a composite function\nuniform highp float u_size; // used when size is both zoom and feature constant\n\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\n\nuniform mat4 u_matrix;\nuniform mat4 u_label_plane_matrix;\nuniform mat4 u_gl_coord_matrix;\n\nuniform bool u_is_text;\nuniform bool u_pitch_with_map;\nuniform highp float u_pitch;\nuniform bool u_rotate_symbol;\nuniform highp float u_aspect_ratio;\nuniform highp float u_camera_to_center_distance;\nuniform float u_fade_change;\n\nuniform vec2 u_texsize;\n\nvarying vec2 v_data0;\nvarying vec3 v_data1;\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 fill_color\n    #pragma mapbox: initialize highp vec4 halo_color\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize lowp float halo_width\n    #pragma mapbox: initialize lowp float halo_blur\n\n    vec2 a_pos = a_pos_offset.xy;\n    vec2 a_offset = a_pos_offset.zw;\n\n    vec2 a_tex = a_data.xy;\n    vec2 a_size = a_data.zw;\n\n    highp float segment_angle = -a_projected_pos[2];\n    float size;\n\n    if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {\n        size = mix(a_size[0], a_size[1], u_size_t) / 10.0;\n    } else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {\n        size = a_size[0] / 10.0;\n    } else if (!u_is_size_zoom_constant && u_is_size_feature_constant) {\n        size = u_size;\n    } else {\n        size = u_size;\n    }\n\n    vec4 projectedPoint = u_matrix * vec4(a_pos, 0, 1);\n    highp float camera_to_anchor_distance = projectedPoint.w;\n    // If the label is pitched with the map, layout is done in pitched space,\n    // which makes labels in the distance smaller relative to viewport space.\n    // We counteract part of that effect by multiplying by the perspective ratio.\n    // If the label isn't pitched with the map, we do layout in viewport space,\n    // which makes labels in the distance larger relative to the features around\n    // them. We counteract part of that effect by dividing by the perspective ratio.\n    highp float distance_ratio = u_pitch_with_map ?\n        camera_to_anchor_distance / u_camera_to_center_distance :\n        u_camera_to_center_distance / camera_to_anchor_distance;\n    highp float perspective_ratio = clamp(\n        0.5 + 0.5 * distance_ratio,\n        0.0, // Prevents oversized near-field symbols in pitched/overzoomed tiles\n        4.0);\n\n    size *= perspective_ratio;\n\n    float fontScale = u_is_text ? size / 24.0 : size;\n\n    highp float symbol_rotation = 0.0;\n    if (u_rotate_symbol) {\n        // Point labels with 'rotation-alignment: map' are horizontal with respect to tile units\n        // To figure out that angle in projected space, we draw a short horizontal line in tile\n        // space, project it, and measure its angle in projected space.\n        vec4 offsetProjectedPoint = u_matrix * vec4(a_pos + vec2(1, 0), 0, 1);\n\n        vec2 a = projectedPoint.xy / projectedPoint.w;\n        vec2 b = offsetProjectedPoint.xy / offsetProjectedPoint.w;\n\n        symbol_rotation = atan((b.y - a.y) / u_aspect_ratio, b.x - a.x);\n    }\n\n    highp float angle_sin = sin(segment_angle + symbol_rotation);\n    highp float angle_cos = cos(segment_angle + symbol_rotation);\n    mat2 rotation_matrix = mat2(angle_cos, -1.0 * angle_sin, angle_sin, angle_cos);\n\n    vec4 projected_pos = u_label_plane_matrix * vec4(a_projected_pos.xy, 0.0, 1.0);\n    gl_Position = u_gl_coord_matrix * vec4(projected_pos.xy / projected_pos.w + rotation_matrix * (a_offset / 32.0 * fontScale), 0.0, 1.0);\n    float gamma_scale = gl_Position.w;\n\n    vec2 tex = a_tex / u_texsize;\n    vec2 fade_opacity = unpack_opacity(a_fade_opacity);\n    float fade_change = fade_opacity[1] > 0.5 ? u_fade_change : -u_fade_change;\n    float interpolated_fade_opacity = max(0.0, min(1.0, fade_opacity[0] + fade_change));\n\n    v_data0 = vec2(tex.x, tex.y);\n    v_data1 = vec3(gamma_scale, size, interpolated_fade_opacity);\n}\n"}},ii=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,ni=function(t){var e=ei[t],i={};e.fragmentSource=e.fragmentSource.replace(ii,function(t,e,n,o,r){return i[r]=!0,"define"===e?"\n#ifndef HAS_UNIFORM_u_"+r+"\nvarying "+n+" "+o+" "+r+";\n#else\nuniform "+n+" "+o+" u_"+r+";\n#endif\n":"\n#ifdef HAS_UNIFORM_u_"+r+"\n    "+n+" "+o+" "+r+" = u_"+r+";\n#endif\n"}),e.vertexSource=e.vertexSource.replace(ii,function(t,e,n,o,r){var a="float"===o?"vec2":"vec4";return i[r]?"define"===e?"\n#ifndef HAS_UNIFORM_u_"+r+"\nuniform lowp float a_"+r+"_t;\nattribute "+n+" "+a+" a_"+r+";\nvarying "+n+" "+o+" "+r+";\n#else\nuniform "+n+" "+o+" u_"+r+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+r+"\n    "+r+" = unpack_mix_"+a+"(a_"+r+", a_"+r+"_t);\n#else\n    "+n+" "+o+" "+r+" = u_"+r+";\n#endif\n":"define"===e?"\n#ifndef HAS_UNIFORM_u_"+r+"\nuniform lowp float a_"+r+"_t;\nattribute "+n+" "+a+" a_"+r+";\n#else\nuniform "+n+" "+o+" u_"+r+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+r+"\n    "+n+" "+o+" "+r+" = unpack_mix_"+a+"(a_"+r+", a_"+r+"_t);\n#else\n    "+n+" "+o+" "+r+" = u_"+r+";\n#endif\n"});};for(var oi in ei)ni(oi);var ri=ei,ai=function(t,e,i,n){var o=t.gl;this.program=o.createProgram();var a=i.defines().concat("#define DEVICE_PIXEL_RATIO "+r.devicePixelRatio.toFixed(1));n&&a.push("#define OVERDRAW_INSPECTOR;");var s=a.concat(ri.prelude.fragmentSource,e.fragmentSource).join("\n"),l=a.concat(ri.prelude.vertexSource,e.vertexSource).join("\n"),c=o.createShader(o.FRAGMENT_SHADER);o.shaderSource(c,s),o.compileShader(c),o.attachShader(this.program,c);var u=o.createShader(o.VERTEX_SHADER);o.shaderSource(u,l),o.compileShader(u),o.attachShader(this.program,u);for(var h=i.layoutAttributes||[],p=0;p<h.length;p++)o.bindAttribLocation(this.program,p,h[p].name);o.linkProgram(this.program),this.numAttributes=o.getProgramParameter(this.program,o.ACTIVE_ATTRIBUTES),this.attributes={},this.uniforms={};for(var d=0;d<this.numAttributes;d++){var f=o.getActiveAttrib(this.program,d);f&&(this.attributes[f.name]=o.getAttribLocation(this.program,f.name));}for(var m=o.getProgramParameter(this.program,o.ACTIVE_UNIFORMS),_=0;_<m;_++){var g=o.getActiveUniform(this.program,_);g&&(this.uniforms[g.name]=o.getUniformLocation(this.program,g.name));}};function si(e,i,n,o,r){for(var a=0;a<n.length;a++){var s=n[a];if(o.isLessThan(s.tileID))break;if(i.key===s.tileID.key)return;if(s.tileID.isChildOf(i)){for(var l=i.children(1/0),c=0;c<l.length;c++){si(e,l[c],n.slice(a),o,r);}return}}var u=i.overscaledZ-e.overscaledZ,h=new t.CanonicalTileID(u,i.canonical.x-(e.canonical.x<<u),i.canonical.y-(e.canonical.y<<u));r[h.key]=r[h.key]||h;}function li(t,e,i,n,o){var r=t.context,a=r.gl,s=o?t.useProgram("collisionCircle"):t.useProgram("collisionBox");r.setDepthMode($t.disabled),r.setStencilMode(Gt.disabled),r.setColorMode(t.colorModeForRenderPass());for(var l=0;l<n.length;l++){var c=n[l],u=e.getTile(c),h=u.getBucket(i);if(h){var p=o?h.collisionCircle:h.collisionBox;if(p){a.uniformMatrix4fv(s.uniforms.u_matrix,!1,c.posMatrix),o||r.lineWidth.set(1),a.uniform1f(s.uniforms.u_camera_to_center_distance,t.transform.cameraToCenterDistance);var d=ze(u,1,t.transform.zoom),f=Math.pow(2,t.transform.zoom-u.tileID.overscaledZ);a.uniform1f(s.uniforms.u_pixels_to_tile_units,d),a.uniform2f(s.uniforms.u_extrude_scale,t.transform.pixelsToGLUnits[0]/(d*f),t.transform.pixelsToGLUnits[1]/(d*f)),a.uniform1f(s.uniforms.u_overscale_factor,u.tileID.overscaleFactor()),s.draw(r,o?a.TRIANGLES:a.LINES,i.id,p.layoutVertexBuffer,p.indexBuffer,p.segments,null,p.collisionVertexBuffer,null);}}}}ai.prototype.draw=function(t,e,i,n,o,r,a,s,l){for(var c,u=t.gl,h=(c={},c[u.LINES]=2,c[u.TRIANGLES]=3,c)[e],p=0,d=r.get();p<d.length;p+=1){var f=d[p],m=f.vaos||(f.vaos={});(m[i]||(m[i]=new tt)).bind(t,this,n,a?a.getPaintVertexBuffers():[],o,f.vertexOffset,s,l),u.drawElements(e,f.primitiveLength*h,u.UNSIGNED_SHORT,f.primitiveOffset*h*2);}};var ci=t.mat4.identity(new Float32Array(16)),ui=t.default$19.layout;function hi(t,e,i,n,o,r,a,s,l,c){var u,h=t.context,p=h.gl,d=t.transform,f="map"===s,m="map"===l,_=f&&"line"===i.layout.get("symbol-placement"),g=f&&!m&&!_,v=m;h.setDepthMode(v?t.depthModeForSublayer(0,$t.ReadOnly):$t.disabled);for(var y=0,x=n;y<x.length;y+=1){var b=x[y],w=e.getTile(b),E=w.getBucket(i);if(E){var T=o?E.text:E.icon;if(T&&T.segments.get().length){var I=T.programConfigurations.get(i.id),C=o||E.sdfIcons,S=o?E.textSizeData:E.iconSizeData;if(u||(u=t.useProgram(C?"symbolSDF":"symbolIcon",I),I.setUniforms(t.context,u,i.paint,{zoom:t.transform.zoom}),pi(u,t,i,o,g,m,S)),h.activeTexture.set(p.TEXTURE0),p.uniform1i(u.uniforms.u_texture,0),o)w.glyphAtlasTexture.bind(p.LINEAR,p.CLAMP_TO_EDGE),p.uniform2fv(u.uniforms.u_texsize,w.glyphAtlasTexture.size);else{var z=1!==i.layout.get("icon-size").constantOr(0)||E.iconsNeedLinear,A=m||0!==d.pitch;w.iconAtlasTexture.bind(C||t.options.rotating||t.options.zooming||z||A?p.LINEAR:p.NEAREST,p.CLAMP_TO_EDGE),p.uniform2fv(u.uniforms.u_texsize,w.iconAtlasTexture.size);}p.uniformMatrix4fv(u.uniforms.u_matrix,!1,t.translatePosMatrix(b.posMatrix,w,r,a));var R=ze(w,1,t.transform.zoom),D=de(b.posMatrix,m,f,t.transform,R),M=fe(b.posMatrix,m,f,t.transform,R);p.uniformMatrix4fv(u.uniforms.u_gl_coord_matrix,!1,t.translatePosMatrix(M,w,r,a,!0)),_?(p.uniformMatrix4fv(u.uniforms.u_label_plane_matrix,!1,ci),ge(E,b.posMatrix,t,o,D,M,m,c)):p.uniformMatrix4fv(u.uniforms.u_label_plane_matrix,!1,D),p.uniform1f(u.uniforms.u_fade_change,t.options.fadeDuration?t.symbolFadeChange:1),di(u,I,t,i,w,T,o,C,m);}}}}function pi(e,i,n,o,r,a,s){var l=i.context.gl,c=i.transform;l.uniform1i(e.uniforms.u_pitch_with_map,a?1:0),l.uniform1f(e.uniforms.u_is_text,o?1:0),l.uniform1f(e.uniforms.u_pitch,c.pitch/360*2*Math.PI);var u="constant"===s.functionType||"source"===s.functionType,h="constant"===s.functionType||"camera"===s.functionType;l.uniform1i(e.uniforms.u_is_size_zoom_constant,u?1:0),l.uniform1i(e.uniforms.u_is_size_feature_constant,h?1:0),l.uniform1f(e.uniforms.u_camera_to_center_distance,c.cameraToCenterDistance);var p=t.evaluateSizeForZoom(s,c.zoom,ui.properties[o?"text-size":"icon-size"]);void 0!==p.uSizeT&&l.uniform1f(e.uniforms.u_size_t,p.uSizeT),void 0!==p.uSize&&l.uniform1f(e.uniforms.u_size,p.uSize),l.uniform1f(e.uniforms.u_aspect_ratio,c.width/c.height),l.uniform1i(e.uniforms.u_rotate_symbol,r?1:0);}function di(t,e,i,n,o,r,a,s,l){var c=i.context,u=c.gl,h=i.transform;if(s){var p=0!==n.paint.get(a?"text-halo-width":"icon-halo-width").constantOr(1),d=l?Math.cos(h._pitch)*h.cameraToCenterDistance:1;u.uniform1f(t.uniforms.u_gamma_scale,d),p&&(u.uniform1f(t.uniforms.u_is_halo,1),fi(r,n,c,t)),u.uniform1f(t.uniforms.u_is_halo,0);}fi(r,n,c,t);}function fi(t,e,i,n){n.draw(i,i.gl.TRIANGLES,e.id,t.layoutVertexBuffer,t.indexBuffer,t.segments,t.programConfigurations.get(e.id),t.dynamicLayoutVertexBuffer,t.opacityVertexBuffer);}function mi(t,e,i,n,o,a,s,l,c){var u,h,p,d,f=e.context,m=f.gl,_=o.paint.get("line-dasharray"),g=o.paint.get("line-pattern");if(l||c){var v=1/ze(i,1,e.transform.tileZoom);if(_){u=e.lineAtlas.getDash(_.from,"round"===o.layout.get("line-cap")),h=e.lineAtlas.getDash(_.to,"round"===o.layout.get("line-cap"));var y=u.width*_.fromScale,x=h.width*_.toScale;m.uniform2f(t.uniforms.u_patternscale_a,v/y,-u.height/2),m.uniform2f(t.uniforms.u_patternscale_b,v/x,-h.height/2),m.uniform1f(t.uniforms.u_sdfgamma,e.lineAtlas.width/(256*Math.min(y,x)*r.devicePixelRatio)/2);}else if(g){if(p=e.imageManager.getPattern(g.from),d=e.imageManager.getPattern(g.to),!p||!d)return;m.uniform2f(t.uniforms.u_pattern_size_a,p.displaySize[0]*g.fromScale/v,p.displaySize[1]),m.uniform2f(t.uniforms.u_pattern_size_b,d.displaySize[0]*g.toScale/v,d.displaySize[1]);var b=e.imageManager.getPixelSize(),w=b.width,E=b.height;m.uniform2fv(t.uniforms.u_texsize,[w,E]);}m.uniform2f(t.uniforms.u_gl_units_to_pixels,1/e.transform.pixelsToGLUnits[0],1/e.transform.pixelsToGLUnits[1]);}l&&(_?(m.uniform1i(t.uniforms.u_image,0),f.activeTexture.set(m.TEXTURE0),e.lineAtlas.bind(f),m.uniform1f(t.uniforms.u_tex_y_a,u.y),m.uniform1f(t.uniforms.u_tex_y_b,h.y),m.uniform1f(t.uniforms.u_mix,_.t)):g&&(m.uniform1i(t.uniforms.u_image,0),f.activeTexture.set(m.TEXTURE0),e.imageManager.bind(f),m.uniform2fv(t.uniforms.u_pattern_tl_a,p.tl),m.uniform2fv(t.uniforms.u_pattern_br_a,p.br),m.uniform2fv(t.uniforms.u_pattern_tl_b,d.tl),m.uniform2fv(t.uniforms.u_pattern_br_b,d.br),m.uniform1f(t.uniforms.u_fade,g.t))),f.setStencilMode(e.stencilModeForClipping(a));var T=e.translatePosMatrix(a.posMatrix,i,o.paint.get("line-translate"),o.paint.get("line-translate-anchor"));if(m.uniformMatrix4fv(t.uniforms.u_matrix,!1,T),m.uniform1f(t.uniforms.u_ratio,1/ze(i,1,e.transform.zoom)),o.paint.get("line-gradient")){f.activeTexture.set(m.TEXTURE0);var I=o.gradientTexture;if(!o.gradient)return;I||(I=o.gradientTexture=new M(f,o.gradient,m.RGBA)),I.bind(m.LINEAR,m.CLAMP_TO_EDGE),m.uniform1i(t.uniforms.u_image,0);}t.draw(f,m.TRIANGLES,o.id,n.layoutVertexBuffer,n.indexBuffer,n.segments,s);}var _i=function(t,e){if(!t)return!1;var i=e.imageManager.getPattern(t.from),n=e.imageManager.getPattern(t.to);return!i||!n},gi=function(t,e,i){var n=e.context,o=n.gl,r=e.imageManager.getPattern(t.from),a=e.imageManager.getPattern(t.to);o.uniform1i(i.uniforms.u_image,0),o.uniform2fv(i.uniforms.u_pattern_tl_a,r.tl),o.uniform2fv(i.uniforms.u_pattern_br_a,r.br),o.uniform2fv(i.uniforms.u_pattern_tl_b,a.tl),o.uniform2fv(i.uniforms.u_pattern_br_b,a.br);var s=e.imageManager.getPixelSize(),l=s.width,c=s.height;o.uniform2fv(i.uniforms.u_texsize,[l,c]),o.uniform1f(i.uniforms.u_mix,t.t),o.uniform2fv(i.uniforms.u_pattern_size_a,r.displaySize),o.uniform2fv(i.uniforms.u_pattern_size_b,a.displaySize),o.uniform1f(i.uniforms.u_scale_a,t.fromScale),o.uniform1f(i.uniforms.u_scale_b,t.toScale),n.activeTexture.set(o.TEXTURE0),e.imageManager.bind(e.context);},vi=function(t,e,i){var n=e.context.gl;n.uniform1f(i.uniforms.u_tile_units_to_pixels,1/ze(t,1,e.transform.tileZoom));var o=Math.pow(2,t.tileID.overscaledZ),r=t.tileSize*Math.pow(2,e.transform.tileZoom)/o,a=r*(t.tileID.canonical.x+t.tileID.wrap*o),s=r*t.tileID.canonical.y;n.uniform2f(i.uniforms.u_pixel_coord_upper,a>>16,s>>16),n.uniform2f(i.uniforms.u_pixel_coord_lower,65535&a,65535&s);};function yi(t,e,i,n,o){if(!_i(i.paint.get("fill-pattern"),t))for(var r=!0,a=0,s=n;a<s.length;a+=1){var l=s[a],c=e.getTile(l),u=c.getBucket(i);u&&(t.context.setStencilMode(t.stencilModeForClipping(l)),o(t,e,i,c,l,u,r),r=!1);}}function xi(t,e,i,n,o,r,a){var s=t.context.gl,l=r.programConfigurations.get(i.id);wi("fill",i.paint.get("fill-pattern"),t,l,i,n,o,a).draw(t.context,s.TRIANGLES,i.id,r.layoutVertexBuffer,r.indexBuffer,r.segments,l);}function bi(t,e,i,n,o,r,a){var s=t.context.gl,l=r.programConfigurations.get(i.id),c=wi("fillOutline",i.getPaintProperty("fill-outline-color")?null:i.paint.get("fill-pattern"),t,l,i,n,o,a);s.uniform2f(c.uniforms.u_world,s.drawingBufferWidth,s.drawingBufferHeight),c.draw(t.context,s.LINES,i.id,r.layoutVertexBuffer,r.indexBuffer2,r.segments2,l);}function wi(t,e,i,n,o,r,a,s){var l,c=i.context.program.get();return e?(l=i.useProgram(t+"Pattern",n),(s||l.program!==c)&&(n.setUniforms(i.context,l,o.paint,{zoom:i.transform.zoom}),gi(e,i,l)),vi(r,i,l)):(l=i.useProgram(t,n),(s||l.program!==c)&&n.setUniforms(i.context,l,o.paint,{zoom:i.transform.zoom})),i.context.gl.uniformMatrix4fv(l.uniforms.u_matrix,!1,i.translatePosMatrix(a.posMatrix,r,o.paint.get("fill-translate"),o.paint.get("fill-translate-anchor"))),l}var Ei=t.default$20.mat3,Ti=t.default$20.mat4,Ii=t.default$20.vec3;function Ci(t,e,i,n,o,r,a){var s=t.context,l=s.gl,c=i.paint.get("fill-extrusion-pattern"),u=t.context.program.get(),h=r.programConfigurations.get(i.id),p=t.useProgram(c?"fillExtrusionPattern":"fillExtrusion",h);if((a||p.program!==u)&&h.setUniforms(s,p,i.paint,{zoom:t.transform.zoom}),c){if(_i(c,t))return;gi(c,t,p),vi(n,t,p),l.uniform1f(p.uniforms.u_height_factor,-Math.pow(2,o.overscaledZ)/n.tileSize/8);}t.context.gl.uniformMatrix4fv(p.uniforms.u_matrix,!1,t.translatePosMatrix(o.posMatrix,n,i.paint.get("fill-extrusion-translate"),i.paint.get("fill-extrusion-translate-anchor"))),function(t,e){var i=e.context.gl,n=e.style.light,o=n.properties.get("position"),r=[o.x,o.y,o.z],a=Ei.create();"viewport"===n.properties.get("anchor")&&Ei.fromRotation(a,-e.transform.angle);Ii.transformMat3(r,r,a);var s=n.properties.get("color");i.uniform3fv(t.uniforms.u_lightpos,r),i.uniform1f(t.uniforms.u_lightintensity,n.properties.get("intensity")),i.uniform3f(t.uniforms.u_lightcolor,s.r,s.g,s.b);}(p,t),p.draw(s,l.TRIANGLES,i.id,r.layoutVertexBuffer,r.indexBuffer,r.segments,h);}function Si(e,i,n){var o=e.context,r=o.gl,a=i.fbo;if(a){var s=e.useProgram("hillshade"),l=e.transform.calculatePosMatrix(i.tileID.toUnwrapped(),!0);!function(t,e,i){var n=i.paint.get("hillshade-illumination-direction")*(Math.PI/180);"viewport"===i.paint.get("hillshade-illumination-anchor")&&(n-=e.transform.angle),e.context.gl.uniform2f(t.uniforms.u_light,i.paint.get("hillshade-exaggeration"),n);}(s,e,n);var c=function(e,i){var n=i.toCoordinate(),o=new t.default$17(n.column,n.row+1,n.zoom);return[e.transform.coordinateLocation(n).lat,e.transform.coordinateLocation(o).lat]}(e,i.tileID);o.activeTexture.set(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,a.colorAttachment.get()),r.uniformMatrix4fv(s.uniforms.u_matrix,!1,l),r.uniform2fv(s.uniforms.u_latrange,c),r.uniform1i(s.uniforms.u_image,0);var u=n.paint.get("hillshade-shadow-color");r.uniform4f(s.uniforms.u_shadow,u.r,u.g,u.b,u.a);var h=n.paint.get("hillshade-highlight-color");r.uniform4f(s.uniforms.u_highlight,h.r,h.g,h.b,h.a);var p=n.paint.get("hillshade-accent-color");if(r.uniform4f(s.uniforms.u_accent,p.r,p.g,p.b,p.a),i.maskedBoundsBuffer&&i.maskedIndexBuffer&&i.segments)s.draw(o,r.TRIANGLES,n.id,i.maskedBoundsBuffer,i.maskedIndexBuffer,i.segments);else{var d=e.rasterBoundsBuffer;e.rasterBoundsVAO.bind(o,s,d,[]),r.drawArrays(r.TRIANGLE_STRIP,0,d.length);}}}function zi(e,i,n){var o=e.context,r=o.gl;if(i.dem&&i.dem.level){var a=i.dem.level.dim,s=i.dem.getPixels();if(o.activeTexture.set(r.TEXTURE1),o.pixelStoreUnpackPremultiplyAlpha.set(!1),i.demTexture=i.demTexture||e.getTileTexture(i.tileSize),i.demTexture){var l=i.demTexture;l.update(s,{premultiply:!1}),l.bind(r.NEAREST,r.CLAMP_TO_EDGE);}else i.demTexture=new M(o,s,r.RGBA,{premultiply:!1}),i.demTexture.bind(r.NEAREST,r.CLAMP_TO_EDGE);o.activeTexture.set(r.TEXTURE0);var c=i.fbo;if(!c){var u=new M(o,{width:a,height:a,data:null},r.RGBA);u.bind(r.LINEAR,r.CLAMP_TO_EDGE),(c=i.fbo=o.createFramebuffer(a,a)).colorAttachment.set(u.texture);}o.bindFramebuffer.set(c.framebuffer),o.viewport.set([0,0,a,a]);var h=t.mat4.create();t.mat4.ortho(h,0,t.default$8,-t.default$8,0,0,1),t.mat4.translate(h,h,[0,-t.default$8,0]);var p=e.useProgram("hillshadePrepare");r.uniformMatrix4fv(p.uniforms.u_matrix,!1,h),r.uniform1f(p.uniforms.u_zoom,i.tileID.overscaledZ),r.uniform2fv(p.uniforms.u_dimension,[2*a,2*a]),r.uniform1i(p.uniforms.u_image,1),r.uniform1f(p.uniforms.u_maxzoom,n);var d=e.rasterBoundsBuffer;e.rasterBoundsVAO.bind(o,p,d,[]),r.drawArrays(r.TRIANGLE_STRIP,0,d.length),i.needsHillshadePrepare=!1;}}function Ai(e,i,n,o,a){var s=o.paint.get("raster-fade-duration");if(s>0){var l=r.now(),c=(l-e.timeAdded)/s,u=i?(l-i.timeAdded)/s:-1,h=n.getSource(),p=a.coveringZoomLevel({tileSize:h.tileSize,roundZoom:h.roundZoom}),d=!i||Math.abs(i.tileID.overscaledZ-p)>Math.abs(e.tileID.overscaledZ-p),f=d&&e.refreshedUponExpiration?1:t.clamp(d?c:1-u,0,1);return e.refreshedUponExpiration&&c>=1&&(e.refreshedUponExpiration=!1),i?{opacity:1,mix:1-f}:{opacity:f,mix:0}}return{opacity:1,mix:0}}function Ri(e,i,n){var o=e.context,a=o.gl;o.lineWidth.set(1*r.devicePixelRatio);var s=n.posMatrix,l=e.useProgram("debug");o.setDepthMode($t.disabled),o.setStencilMode(Gt.disabled),o.setColorMode(e.colorModeForRenderPass()),a.uniformMatrix4fv(l.uniforms.u_matrix,!1,s),a.uniform4f(l.uniforms.u_color,1,0,0,1),e.debugVAO.bind(o,l,e.debugBuffer,[]),a.drawArrays(a.LINE_STRIP,0,e.debugBuffer.length);for(var c=function(t,e,i,n){n=n||1;var o,r,a,s,l,c,u,h,p=[];for(o=0,r=t.length;o<r;o++)if(l=Di[t[o]]){for(h=null,a=0,s=l[1].length;a<s;a+=2)-1===l[1][a]&&-1===l[1][a+1]?h=null:(c=e+l[1][a]*n,u=i-l[1][a+1]*n,h&&p.push(h.x,h.y,c,u),h={x:c,y:u});e+=l[0]*n;}return p}(n.toString(),50,200,5),u=new t.PosArray,h=0;h<c.length;h+=2)u.emplaceBack(c[h],c[h+1]);var p=o.createVertexBuffer(u,ti.members);(new tt).bind(o,l,p,[]),a.uniform4f(l.uniforms.u_color,1,1,1,1);for(var d=i.getTile(n).tileSize,f=t.default$8/(Math.pow(2,e.transform.zoom-n.overscaledZ)*d),m=[[-1,-1],[-1,1],[1,-1],[1,1]],_=0;_<m.length;_++){var g=m[_];a.uniformMatrix4fv(l.uniforms.u_matrix,!1,t.mat4.translate([],s,[f*g[0],f*g[1],0])),a.drawArrays(a.LINES,0,p.length);}a.uniform4f(l.uniforms.u_color,0,0,0,1),a.uniformMatrix4fv(l.uniforms.u_matrix,!1,s),a.drawArrays(a.LINES,0,p.length);}var Di={" ":[16,[]],"!":[10,[5,21,5,7,-1,-1,5,2,4,1,5,0,6,1,5,2]],'"':[16,[4,21,4,14,-1,-1,12,21,12,14]],"#":[21,[11,25,4,-7,-1,-1,17,25,10,-7,-1,-1,4,12,18,12,-1,-1,3,6,17,6]],$:[20,[8,25,8,-4,-1,-1,12,25,12,-4,-1,-1,17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3]],"%":[24,[21,21,3,0,-1,-1,8,21,10,19,10,17,9,15,7,14,5,14,3,16,3,18,4,20,6,21,8,21,10,20,13,19,16,19,19,20,21,21,-1,-1,17,7,15,6,14,4,14,2,16,0,18,0,20,1,21,3,21,5,19,7,17,7]],"&":[26,[23,12,23,13,22,14,21,14,20,13,19,11,17,6,15,3,13,1,11,0,7,0,5,1,4,2,3,4,3,6,4,8,5,9,12,13,13,14,14,16,14,18,13,20,11,21,9,20,8,18,8,16,9,13,11,10,16,3,18,1,20,0,22,0,23,1,23,2]],"'":[10,[5,19,4,20,5,21,6,20,6,18,5,16,4,15]],"(":[14,[11,25,9,23,7,20,5,16,4,11,4,7,5,2,7,-2,9,-5,11,-7]],")":[14,[3,25,5,23,7,20,9,16,10,11,10,7,9,2,7,-2,5,-5,3,-7]],"*":[16,[8,21,8,9,-1,-1,3,18,13,12,-1,-1,13,18,3,12]],"+":[26,[13,18,13,0,-1,-1,4,9,22,9]],",":[10,[6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4]],"-":[26,[4,9,22,9]],".":[10,[5,2,4,1,5,0,6,1,5,2]],"/":[22,[20,25,2,-7]],0:[20,[9,21,6,20,4,17,3,12,3,9,4,4,6,1,9,0,11,0,14,1,16,4,17,9,17,12,16,17,14,20,11,21,9,21]],1:[20,[6,17,8,18,11,21,11,0]],2:[20,[4,16,4,17,5,19,6,20,8,21,12,21,14,20,15,19,16,17,16,15,15,13,13,10,3,0,17,0]],3:[20,[5,21,16,21,10,13,13,13,15,12,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4]],4:[20,[13,21,3,7,18,7,-1,-1,13,21,13,0]],5:[20,[15,21,5,21,4,12,5,13,8,14,11,14,14,13,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4]],6:[20,[16,18,15,20,12,21,10,21,7,20,5,17,4,12,4,7,5,3,7,1,10,0,11,0,14,1,16,3,17,6,17,7,16,10,14,12,11,13,10,13,7,12,5,10,4,7]],7:[20,[17,21,7,0,-1,-1,3,21,17,21]],8:[20,[8,21,5,20,4,18,4,16,5,14,7,13,11,12,14,11,16,9,17,7,17,4,16,2,15,1,12,0,8,0,5,1,4,2,3,4,3,7,4,9,6,11,9,12,13,13,15,14,16,16,16,18,15,20,12,21,8,21]],9:[20,[16,14,15,11,13,9,10,8,9,8,6,9,4,11,3,14,3,15,4,18,6,20,9,21,10,21,13,20,15,18,16,14,16,9,15,4,13,1,10,0,8,0,5,1,4,3]],":":[10,[5,14,4,13,5,12,6,13,5,14,-1,-1,5,2,4,1,5,0,6,1,5,2]],";":[10,[5,14,4,13,5,12,6,13,5,14,-1,-1,6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4]],"<":[24,[20,18,4,9,20,0]],"=":[26,[4,12,22,12,-1,-1,4,6,22,6]],">":[24,[4,18,20,9,4,0]],"?":[18,[3,16,3,17,4,19,5,20,7,21,11,21,13,20,14,19,15,17,15,15,14,13,13,12,9,10,9,7,-1,-1,9,2,8,1,9,0,10,1,9,2]],"@":[27,[18,13,17,15,15,16,12,16,10,15,9,14,8,11,8,8,9,6,11,5,14,5,16,6,17,8,-1,-1,12,16,10,14,9,11,9,8,10,6,11,5,-1,-1,18,16,17,8,17,6,19,5,21,5,23,7,24,10,24,12,23,15,22,17,20,19,18,20,15,21,12,21,9,20,7,19,5,17,4,15,3,12,3,9,4,6,5,4,7,2,9,1,12,0,15,0,18,1,20,2,21,3,-1,-1,19,16,18,8,18,6,19,5]],A:[18,[9,21,1,0,-1,-1,9,21,17,0,-1,-1,4,7,14,7]],B:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,-1,-1,4,11,13,11,16,10,17,9,18,7,18,4,17,2,16,1,13,0,4,0]],C:[21,[18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5]],D:[21,[4,21,4,0,-1,-1,4,21,11,21,14,20,16,18,17,16,18,13,18,8,17,5,16,3,14,1,11,0,4,0]],E:[19,[4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11,-1,-1,4,0,17,0]],F:[18,[4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11]],G:[21,[18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,18,8,-1,-1,13,8,18,8]],H:[22,[4,21,4,0,-1,-1,18,21,18,0,-1,-1,4,11,18,11]],I:[8,[4,21,4,0]],J:[16,[12,21,12,5,11,2,10,1,8,0,6,0,4,1,3,2,2,5,2,7]],K:[21,[4,21,4,0,-1,-1,18,21,4,7,-1,-1,9,12,18,0]],L:[17,[4,21,4,0,-1,-1,4,0,16,0]],M:[24,[4,21,4,0,-1,-1,4,21,12,0,-1,-1,20,21,12,0,-1,-1,20,21,20,0]],N:[22,[4,21,4,0,-1,-1,4,21,18,0,-1,-1,18,21,18,0]],O:[22,[9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21]],P:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,14,17,12,16,11,13,10,4,10]],Q:[22,[9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,-1,-1,12,4,18,-2]],R:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,4,11,-1,-1,11,11,18,0]],S:[20,[17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3]],T:[16,[8,21,8,0,-1,-1,1,21,15,21]],U:[22,[4,21,4,6,5,3,7,1,10,0,12,0,15,1,17,3,18,6,18,21]],V:[18,[1,21,9,0,-1,-1,17,21,9,0]],W:[24,[2,21,7,0,-1,-1,12,21,7,0,-1,-1,12,21,17,0,-1,-1,22,21,17,0]],X:[20,[3,21,17,0,-1,-1,17,21,3,0]],Y:[18,[1,21,9,11,9,0,-1,-1,17,21,9,11]],Z:[20,[17,21,3,0,-1,-1,3,21,17,21,-1,-1,3,0,17,0]],"[":[14,[4,25,4,-7,-1,-1,5,25,5,-7,-1,-1,4,25,11,25,-1,-1,4,-7,11,-7]],"\\":[14,[0,21,14,-3]],"]":[14,[9,25,9,-7,-1,-1,10,25,10,-7,-1,-1,3,25,10,25,-1,-1,3,-7,10,-7]],"^":[16,[6,15,8,18,10,15,-1,-1,3,12,8,17,13,12,-1,-1,8,17,8,0]],_:[16,[0,-2,16,-2]],"`":[10,[6,21,5,20,4,18,4,16,5,15,6,16,5,17]],a:[19,[15,14,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],b:[19,[4,21,4,0,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3]],c:[18,[15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],d:[19,[15,21,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],e:[18,[3,8,15,8,15,10,14,12,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],f:[12,[10,21,8,21,6,20,5,17,5,0,-1,-1,2,14,9,14]],g:[19,[15,14,15,-2,14,-5,13,-6,11,-7,8,-7,6,-6,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],h:[19,[4,21,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0]],i:[8,[3,21,4,20,5,21,4,22,3,21,-1,-1,4,14,4,0]],j:[10,[5,21,6,20,7,21,6,22,5,21,-1,-1,6,14,6,-3,5,-6,3,-7,1,-7]],k:[17,[4,21,4,0,-1,-1,14,14,4,4,-1,-1,8,8,15,0]],l:[8,[4,21,4,0]],m:[30,[4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,15,10,18,13,20,14,23,14,25,13,26,10,26,0]],n:[19,[4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0]],o:[19,[8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,16,6,16,8,15,11,13,13,11,14,8,14]],p:[19,[4,14,4,-7,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3]],q:[19,[15,14,15,-7,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],r:[13,[4,14,4,0,-1,-1,4,8,5,11,7,13,9,14,12,14]],s:[17,[14,11,13,13,10,14,7,14,4,13,3,11,4,9,6,8,11,7,13,6,14,4,14,3,13,1,10,0,7,0,4,1,3,3]],t:[12,[5,21,5,4,6,1,8,0,10,0,-1,-1,2,14,9,14]],u:[19,[4,14,4,4,5,1,7,0,10,0,12,1,15,4,-1,-1,15,14,15,0]],v:[16,[2,14,8,0,-1,-1,14,14,8,0]],w:[22,[3,14,7,0,-1,-1,11,14,7,0,-1,-1,11,14,15,0,-1,-1,19,14,15,0]],x:[17,[3,14,14,0,-1,-1,14,14,3,0]],y:[16,[2,14,8,0,-1,-1,14,14,8,0,6,-4,4,-6,2,-7,1,-7]],z:[17,[14,14,3,0,-1,-1,3,14,14,14,-1,-1,3,0,14,0]],"{":[14,[9,25,7,24,6,23,5,21,5,19,6,17,7,16,8,14,8,12,6,10,-1,-1,7,24,6,22,6,20,7,18,8,17,9,15,9,13,8,11,4,9,8,7,9,5,9,3,8,1,7,0,6,-2,6,-4,7,-6,-1,-1,6,8,8,6,8,4,7,2,6,1,5,-1,5,-3,6,-5,7,-6,9,-7]],"|":[8,[4,25,4,-7]],"}":[14,[5,25,7,24,8,23,9,21,9,19,8,17,7,16,6,14,6,12,8,10,-1,-1,7,24,8,22,8,20,7,18,6,17,5,15,5,13,6,11,10,9,6,7,5,5,5,3,6,1,7,0,8,-2,8,-4,7,-6,-1,-1,8,8,6,6,6,4,7,2,8,1,9,-1,9,-3,8,-5,7,-6,5,-7]],"~":[24,[3,6,3,8,4,11,6,12,8,12,10,11,14,8,16,7,18,7,20,8,21,10,-1,-1,3,8,4,10,6,11,8,11,10,10,14,7,16,6,18,6,20,7,21,10,21,12]]};var Mi={symbol:function(t,e,i,n){if("translucent"===t.renderPass){var o=t.context;o.setStencilMode(Gt.disabled),o.setColorMode(t.colorModeForRenderPass()),0!==i.paint.get("icon-opacity").constantOr(1)&&hi(t,e,i,n,!1,i.paint.get("icon-translate"),i.paint.get("icon-translate-anchor"),i.layout.get("icon-rotation-alignment"),i.layout.get("icon-pitch-alignment"),i.layout.get("icon-keep-upright")),0!==i.paint.get("text-opacity").constantOr(1)&&hi(t,e,i,n,!0,i.paint.get("text-translate"),i.paint.get("text-translate-anchor"),i.layout.get("text-rotation-alignment"),i.layout.get("text-pitch-alignment"),i.layout.get("text-keep-upright")),e.map.showCollisionBoxes&&function(t,e,i,n){li(t,e,i,n,!1),li(t,e,i,n,!0);}(t,e,i,n);}},circle:function(t,e,i,n){if("translucent"===t.renderPass){var o=i.paint.get("circle-opacity"),r=i.paint.get("circle-stroke-width"),a=i.paint.get("circle-stroke-opacity");if(0!==o.constantOr(1)||0!==r.constantOr(1)&&0!==a.constantOr(1)){var s=t.context,l=s.gl;s.setDepthMode(t.depthModeForSublayer(0,$t.ReadOnly)),s.setStencilMode(Gt.disabled),s.setColorMode(t.colorModeForRenderPass());for(var c=!0,u=0;u<n.length;u++){var h=n[u],p=e.getTile(h),d=p.getBucket(i);if(d){var f=t.context.program.get(),m=d.programConfigurations.get(i.id),_=t.useProgram("circle",m);if((c||_.program!==f)&&(m.setUniforms(s,_,i.paint,{zoom:t.transform.zoom}),c=!1),l.uniform1f(_.uniforms.u_camera_to_center_distance,t.transform.cameraToCenterDistance),l.uniform1i(_.uniforms.u_scale_with_map,"map"===i.paint.get("circle-pitch-scale")?1:0),"map"===i.paint.get("circle-pitch-alignment")){l.uniform1i(_.uniforms.u_pitch_with_map,1);var g=ze(p,1,t.transform.zoom);l.uniform2f(_.uniforms.u_extrude_scale,g,g);}else l.uniform1i(_.uniforms.u_pitch_with_map,0),l.uniform2fv(_.uniforms.u_extrude_scale,t.transform.pixelsToGLUnits);l.uniformMatrix4fv(_.uniforms.u_matrix,!1,t.translatePosMatrix(h.posMatrix,p,i.paint.get("circle-translate"),i.paint.get("circle-translate-anchor"))),_.draw(s,l.TRIANGLES,i.id,d.layoutVertexBuffer,d.indexBuffer,d.segments,m);}}}}},heatmap:function(e,i,n,o){if(0!==n.paint.get("heatmap-opacity"))if("offscreen"===e.renderPass){var r=e.context,a=r.gl;r.setDepthMode(e.depthModeForSublayer(0,$t.ReadOnly)),r.setStencilMode(Gt.disabled),function(t,e,i){var n=t.gl;t.activeTexture.set(n.TEXTURE1),t.viewport.set([0,0,e.width/4,e.height/4]);var o=i.heatmapFbo;if(o)n.bindTexture(n.TEXTURE_2D,o.colorAttachment.get()),t.bindFramebuffer.set(o.framebuffer);else{var r=n.createTexture();n.bindTexture(n.TEXTURE_2D,r),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),o=i.heatmapFbo=t.createFramebuffer(e.width/4,e.height/4),function t(e,i,n,o){var r=e.gl;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,i.width/4,i.height/4,0,r.RGBA,e.extTextureHalfFloat?e.extTextureHalfFloat.HALF_FLOAT_OES:r.UNSIGNED_BYTE,null),o.colorAttachment.set(n),e.extTextureHalfFloat&&r.checkFramebufferStatus(r.FRAMEBUFFER)!==r.FRAMEBUFFER_COMPLETE&&(e.extTextureHalfFloat=null,o.colorAttachment.setDirty(),t(e,i,n,o));}(t,e,r,o);}}(r,e,n),r.clear({color:t.default$6.transparent}),r.setColorMode(new Wt([a.ONE,a.ONE],t.default$6.transparent,[!0,!0,!0,!0]));for(var s=!0,l=0;l<o.length;l++){var c=o[l];if(!i.hasRenderableParent(c)){var u=i.getTile(c),h=u.getBucket(n);if(h){var p=e.context.program.get(),d=h.programConfigurations.get(n.id),f=e.useProgram("heatmap",d),m=e.transform.zoom;(s||f.program!==p)&&(d.setUniforms(e.context,f,n.paint,{zoom:m}),s=!1),a.uniform1f(f.uniforms.u_extrude_scale,ze(u,1,m)),a.uniform1f(f.uniforms.u_intensity,n.paint.get("heatmap-intensity")),a.uniformMatrix4fv(f.uniforms.u_matrix,!1,c.posMatrix),f.draw(r,a.TRIANGLES,n.id,h.layoutVertexBuffer,h.indexBuffer,h.segments,d);}}}r.viewport.set([0,0,e.width,e.height]);}else"translucent"===e.renderPass&&(e.context.setColorMode(e.colorModeForRenderPass()),function(e,i){var n=e.context,o=n.gl,r=i.heatmapFbo;if(r){n.activeTexture.set(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,r.colorAttachment.get()),n.activeTexture.set(o.TEXTURE1);var a=i.colorRampTexture;a||(a=i.colorRampTexture=new M(n,i.colorRamp,o.RGBA)),a.bind(o.LINEAR,o.CLAMP_TO_EDGE),n.setDepthMode($t.disabled);var s=e.useProgram("heatmapTexture"),l=i.paint.get("heatmap-opacity");o.uniform1f(s.uniforms.u_opacity,l),o.uniform1i(s.uniforms.u_image,0),o.uniform1i(s.uniforms.u_color_ramp,1);var c=t.mat4.create();t.mat4.ortho(c,0,e.width,e.height,0,0,1),o.uniformMatrix4fv(s.uniforms.u_matrix,!1,c),o.uniform2f(s.uniforms.u_world,o.drawingBufferWidth,o.drawingBufferHeight),e.viewportVAO.bind(e.context,s,e.viewportBuffer,[]),o.drawArrays(o.TRIANGLE_STRIP,0,4);}}(e,n));},line:function(t,e,i,n){if("translucent"===t.renderPass&&0!==i.paint.get("line-opacity").constantOr(1)){var o=t.context;o.setDepthMode(t.depthModeForSublayer(0,$t.ReadOnly)),o.setColorMode(t.colorModeForRenderPass());for(var r,a=i.paint.get("line-dasharray")?"lineSDF":i.paint.get("line-pattern")?"linePattern":i.paint.get("line-gradient")?"lineGradient":"line",s=!0,l=0,c=n;l<c.length;l+=1){var u=c[l],h=e.getTile(u),p=h.getBucket(i);if(p){var d=p.programConfigurations.get(i.id),f=t.context.program.get(),m=t.useProgram(a,d),_=s||m.program!==f,g=r!==h.tileID.overscaledZ;_&&d.setUniforms(t.context,m,i.paint,{zoom:t.transform.zoom}),mi(m,t,h,p,i,u,d,_,g),r=h.tileID.overscaledZ,s=!1;}}}},fill:function(e,i,n,o){var r=n.paint.get("fill-color"),a=n.paint.get("fill-opacity");if(0!==a.constantOr(1)){var s=e.context;s.setColorMode(e.colorModeForRenderPass());var l=n.paint.get("fill-pattern")||1!==r.constantOr(t.default$6.transparent).a||1!==a.constantOr(0)?"translucent":"opaque";e.renderPass===l&&(s.setDepthMode(e.depthModeForSublayer(1,"opaque"===e.renderPass?$t.ReadWrite:$t.ReadOnly)),yi(e,i,n,o,xi)),"translucent"===e.renderPass&&n.paint.get("fill-antialias")&&(s.lineWidth.set(2),s.setDepthMode(e.depthModeForSublayer(n.getPaintProperty("fill-outline-color")?2:0,$t.ReadOnly)),yi(e,i,n,o,bi));}},"fill-extrusion":function(e,i,n,o){if(0!==n.paint.get("fill-extrusion-opacity"))if("offscreen"===e.renderPass){!function(e,i){var n=e.context,o=n.gl,r=i.viewportFrame;if(e.depthRboNeedsClear&&e.setupOffscreenDepthRenderbuffer(),!r){var a=new M(n,{width:e.width,height:e.height,data:null},o.RGBA);a.bind(o.LINEAR,o.CLAMP_TO_EDGE),(r=i.viewportFrame=n.createFramebuffer(e.width,e.height)).colorAttachment.set(a.texture);}n.bindFramebuffer.set(r.framebuffer),r.depthAttachment.set(e.depthRbo),e.depthRboNeedsClear&&(n.clear({depth:1}),e.depthRboNeedsClear=!1),n.clear({color:t.default$6.transparent}),n.setStencilMode(Gt.disabled),n.setDepthMode(new $t(o.LEQUAL,$t.ReadWrite,[0,1])),n.setColorMode(e.colorModeForRenderPass());}(e,n);for(var r=!0,a=0,s=o;a<s.length;a+=1){var l=s[a],c=i.getTile(l),u=c.getBucket(n);u&&(Ci(e,0,n,c,l,u,r),r=!1);}}else"translucent"===e.renderPass&&function(t,e){var i=e.viewportFrame;if(i){var n=t.context,o=n.gl,r=t.useProgram("extrusionTexture");n.setStencilMode(Gt.disabled),n.setDepthMode($t.disabled),n.setColorMode(t.colorModeForRenderPass()),n.activeTexture.set(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,i.colorAttachment.get()),o.uniform1f(r.uniforms.u_opacity,e.paint.get("fill-extrusion-opacity")),o.uniform1i(r.uniforms.u_image,0);var a=Ti.create();Ti.ortho(a,0,t.width,t.height,0,0,1),o.uniformMatrix4fv(r.uniforms.u_matrix,!1,a),o.uniform2f(r.uniforms.u_world,o.drawingBufferWidth,o.drawingBufferHeight),t.viewportVAO.bind(n,r,t.viewportBuffer,[]),o.drawArrays(o.TRIANGLE_STRIP,0,4);}}(e,n);},hillshade:function(t,e,i,n){if("offscreen"===t.renderPass||"translucent"===t.renderPass){var o=t.context,r=e.getSource().maxzoom;o.setDepthMode(t.depthModeForSublayer(0,$t.ReadOnly)),o.setStencilMode(Gt.disabled),o.setColorMode(t.colorModeForRenderPass());for(var a=0,s=n;a<s.length;a+=1){var l=s[a],c=e.getTile(l);c.needsHillshadePrepare&&"offscreen"===t.renderPass?zi(t,c,r):"translucent"===t.renderPass&&Si(t,c,i);}o.viewport.set([0,0,t.width,t.height]);}},raster:function(t,e,i,n){if("translucent"===t.renderPass&&0!==i.paint.get("raster-opacity")){var o,r,a=t.context,s=a.gl,l=e.getSource(),c=t.useProgram("raster");a.setStencilMode(Gt.disabled),a.setColorMode(t.colorModeForRenderPass()),s.uniform1f(c.uniforms.u_brightness_low,i.paint.get("raster-brightness-min")),s.uniform1f(c.uniforms.u_brightness_high,i.paint.get("raster-brightness-max")),s.uniform1f(c.uniforms.u_saturation_factor,(o=i.paint.get("raster-saturation"))>0?1-1/(1.001-o):-o),s.uniform1f(c.uniforms.u_contrast_factor,(r=i.paint.get("raster-contrast"))>0?1/(1-r):1+r),s.uniform3fv(c.uniforms.u_spin_weights,function(t){t*=Math.PI/180;var e=Math.sin(t),i=Math.cos(t);return[(2*i+1)/3,(-Math.sqrt(3)*e-i+1)/3,(Math.sqrt(3)*e-i+1)/3]}(i.paint.get("raster-hue-rotate"))),s.uniform1f(c.uniforms.u_buffer_scale,1),s.uniform1i(c.uniforms.u_image0,0),s.uniform1i(c.uniforms.u_image1,1);for(var u=n.length&&n[0].overscaledZ,h=0,p=n;h<p.length;h+=1){var d=p[h];a.setDepthMode(t.depthModeForSublayer(d.overscaledZ-u,1===i.paint.get("raster-opacity")?$t.ReadWrite:$t.ReadOnly,s.LESS));var f=e.getTile(d),m=t.transform.calculatePosMatrix(d.toUnwrapped(),!0);f.registerFadeDuration(i.paint.get("raster-fade-duration")),s.uniformMatrix4fv(c.uniforms.u_matrix,!1,m);var _=e.findLoadedParent(d,0,{}),g=Ai(f,_,e,i,t.transform),v=void 0,y=void 0;if(a.activeTexture.set(s.TEXTURE0),f.texture.bind(s.LINEAR,s.CLAMP_TO_EDGE,s.LINEAR_MIPMAP_NEAREST),a.activeTexture.set(s.TEXTURE1),_?(_.texture.bind(s.LINEAR,s.CLAMP_TO_EDGE,s.LINEAR_MIPMAP_NEAREST),v=Math.pow(2,_.tileID.overscaledZ-f.tileID.overscaledZ),y=[f.tileID.canonical.x*v%1,f.tileID.canonical.y*v%1]):f.texture.bind(s.LINEAR,s.CLAMP_TO_EDGE,s.LINEAR_MIPMAP_NEAREST),s.uniform2fv(c.uniforms.u_tl_parent,y||[0,0]),s.uniform1f(c.uniforms.u_scale_parent,v||1),s.uniform1f(c.uniforms.u_fade_t,g.mix),s.uniform1f(c.uniforms.u_opacity,g.opacity*i.paint.get("raster-opacity")),l instanceof et){var x=l.boundsBuffer;l.boundsVAO.bind(a,c,x,[]),s.drawArrays(s.TRIANGLE_STRIP,0,x.length);}else if(f.maskedBoundsBuffer&&f.maskedIndexBuffer&&f.segments)c.draw(a,s.TRIANGLES,i.id,f.maskedBoundsBuffer,f.maskedIndexBuffer,f.segments);else{var b=t.rasterBoundsBuffer;t.rasterBoundsVAO.bind(a,c,b,[]),s.drawArrays(s.TRIANGLE_STRIP,0,b.length);}}}},background:function(t,e,i){var n=i.paint.get("background-color"),o=i.paint.get("background-opacity");if(0!==o){var r=t.context,a=r.gl,s=t.transform,l=s.tileSize,c=i.paint.get("background-pattern"),u=c||1!==n.a||1!==o?"translucent":"opaque";if(t.renderPass===u){var h;if(r.setStencilMode(Gt.disabled),r.setDepthMode(t.depthModeForSublayer(0,"opaque"===u?$t.ReadWrite:$t.ReadOnly)),r.setColorMode(t.colorModeForRenderPass()),c){if(_i(c,t))return;h=t.useProgram("backgroundPattern"),gi(c,t,h),t.tileExtentPatternVAO.bind(r,h,t.tileExtentBuffer,[]);}else h=t.useProgram("background"),a.uniform4fv(h.uniforms.u_color,[n.r,n.g,n.b,n.a]),t.tileExtentVAO.bind(r,h,t.tileExtentBuffer,[]);a.uniform1f(h.uniforms.u_opacity,o);for(var p=0,d=s.coveringTiles({tileSize:l});p<d.length;p+=1){var f=d[p];c&&vi({tileID:f,tileSize:l},t,h),a.uniformMatrix4fv(h.uniforms.u_matrix,!1,t.transform.calculatePosMatrix(f.toUnwrapped())),a.drawArrays(a.TRIANGLE_STRIP,0,t.tileExtentBuffer.length);}}}},debug:function(t,e,i){for(var n=0;n<i.length;n++)Ri(t,e,i[n]);}},Li=function(e,i){this.context=new qt(e),this.transform=i,this._tileTextures={},this.setup(),this.numSublayers=Xt.maxUnderzooming+Xt.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.depthRboNeedsClear=!0,this.emptyProgramConfiguration=new t.default$24,this.crossTileSymbolIndex=new He;};function Pi(t,e){if(t.row>e.row){var i=t;t=e,e=i;}return{x0:t.column,y0:t.row,x1:e.column,y1:e.row,dx:e.column-t.column,dy:e.row-t.row}}function ki(t,e,i,n,o){var r=Math.max(i,Math.floor(e.y0)),a=Math.min(n,Math.ceil(e.y1));if(t.x0===e.x0&&t.y0===e.y0?t.x0+e.dy/t.dy*t.dx<e.x1:t.x1-e.dy/t.dy*t.dx<e.x0){var s=t;t=e,e=s;}for(var l=t.dx/t.dy,c=e.dx/e.dy,u=t.dx>0,h=e.dx<0,p=r;p<a;p++){var d=l*Math.max(0,Math.min(t.dy,p+u-t.y0))+t.x0,f=c*Math.max(0,Math.min(e.dy,p+h-e.y0))+e.x0;o(Math.floor(f),Math.ceil(d),p);}}function Bi(t,e,i,n,o,r){var a,s=Pi(t,e),l=Pi(e,i),c=Pi(i,t);s.dy>l.dy&&(a=s,s=l,l=a),s.dy>c.dy&&(a=s,s=c,c=a),l.dy>c.dy&&(a=l,l=c,c=a),s.dy&&ki(c,s,n,o,r),l.dy&&ki(c,l,n,o,r);}Li.prototype.resize=function(t,e){var i=this.context.gl;if(this.width=t*r.devicePixelRatio,this.height=e*r.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(var n=0,o=this.style._order;n<o.length;n+=1){var a=o[n];this.style._layers[a].resize();}this.depthRbo&&(i.deleteRenderbuffer(this.depthRbo),this.depthRbo=null);},Li.prototype.setup=function(){var e=this.context,i=new t.PosArray;i.emplaceBack(0,0),i.emplaceBack(t.default$8,0),i.emplaceBack(0,t.default$8),i.emplaceBack(t.default$8,t.default$8),this.tileExtentBuffer=e.createVertexBuffer(i,ti.members),this.tileExtentVAO=new tt,this.tileExtentPatternVAO=new tt;var n=new t.PosArray;n.emplaceBack(0,0),n.emplaceBack(t.default$8,0),n.emplaceBack(t.default$8,t.default$8),n.emplaceBack(0,t.default$8),n.emplaceBack(0,0),this.debugBuffer=e.createVertexBuffer(n,ti.members),this.debugVAO=new tt;var o=new t.RasterBoundsArray;o.emplaceBack(0,0,0,0),o.emplaceBack(t.default$8,0,t.default$8,0),o.emplaceBack(0,t.default$8,0,t.default$8),o.emplaceBack(t.default$8,t.default$8,t.default$8,t.default$8),this.rasterBoundsBuffer=e.createVertexBuffer(o,Q.members),this.rasterBoundsVAO=new tt;var r=new t.PosArray;r.emplaceBack(0,0),r.emplaceBack(1,0),r.emplaceBack(0,1),r.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(r,ti.members),this.viewportVAO=new tt;},Li.prototype.clearStencil=function(){var e=this.context,i=e.gl;e.setColorMode(Wt.disabled),e.setDepthMode($t.disabled),e.setStencilMode(new Gt({func:i.ALWAYS,mask:0},0,255,i.ZERO,i.ZERO,i.ZERO));var n=t.mat4.create();t.mat4.ortho(n,0,this.width,this.height,0,0,1),t.mat4.scale(n,n,[i.drawingBufferWidth,i.drawingBufferHeight,0]);var o=this.useProgram("clippingMask");i.uniformMatrix4fv(o.uniforms.u_matrix,!1,n),this.viewportVAO.bind(e,o,this.viewportBuffer,[]),i.drawArrays(i.TRIANGLE_STRIP,0,4);},Li.prototype._renderTileClippingMasks=function(t){var e=this.context,i=e.gl;e.setColorMode(Wt.disabled),e.setDepthMode($t.disabled);var n=1;this._tileClippingMaskIDs={};for(var o=0,r=t;o<r.length;o+=1){var a=r[o],s=this._tileClippingMaskIDs[a.key]=n++;e.setStencilMode(new Gt({func:i.ALWAYS,mask:0},s,255,i.KEEP,i.KEEP,i.REPLACE));var l=this.useProgram("clippingMask");i.uniformMatrix4fv(l.uniforms.u_matrix,!1,a.posMatrix),this.tileExtentVAO.bind(this.context,l,this.tileExtentBuffer,[]),i.drawArrays(i.TRIANGLE_STRIP,0,this.tileExtentBuffer.length);}},Li.prototype.stencilModeForClipping=function(t){var e=this.context.gl;return new Gt({func:e.EQUAL,mask:255},this._tileClippingMaskIDs[t.key],0,e.KEEP,e.KEEP,e.REPLACE)},Li.prototype.colorModeForRenderPass=function(){var e=this.context.gl;if(this._showOverdrawInspector){return new Wt([e.CONSTANT_COLOR,e.ONE],new t.default$6(1/8,1/8,1/8,0),[!0,!0,!0,!0])}return"opaque"===this.renderPass?Wt.unblended:Wt.alphaBlended},Li.prototype.depthModeForSublayer=function(t,e,i){var n=1-((1+this.currentLayer)*this.numSublayers+t)*this.depthEpsilon,o=n-1+this.depthRange;return new $t(i||this.context.gl.LEQUAL,e,[o,n])},Li.prototype.render=function(e,i){var n=this;for(var o in this.style=e,this.options=i,this.lineAtlas=e.lineAtlas,this.imageManager=e.imageManager,this.glyphManager=e.glyphManager,this.symbolFadeChange=e.placement.symbolFadeChange(r.now()),e.sourceCaches){var a=n.style.sourceCaches[o];a.used&&a.prepare(n.context);}var s=this.style._order,l=t.filterObject(this.style.sourceCaches,function(t){return"raster"===t.getSource().type||"raster-dem"===t.getSource().type}),c=function(e){var i=l[e];!function(e,i){for(var n=e.sort(function(t,e){return t.tileID.isLessThan(e.tileID)?-1:e.tileID.isLessThan(t.tileID)?1:0}),o=0;o<n.length;o++){var r={},a=n[o],s=n.slice(o+1);si(a.tileID.wrapped(),a.tileID,s,new t.OverscaledTileID(0,a.tileID.wrap+1,0,0,0),r),a.setMask(r,i);}}(i.getVisibleCoordinates().map(function(t){return i.getTile(t)}),n.context);};for(var u in l)c(u);this.renderPass="offscreen";var h,p=[];this.depthRboNeedsClear=!0;for(var d=0;d<s.length;d++){var f=n.style._layers[s[d]];f.hasOffscreenPass()&&!f.isHidden(n.transform.zoom)&&(f.source!==(h&&h.id)&&(p=[],(h=n.style.sourceCaches[f.source])&&(p=h.getVisibleCoordinates()).reverse()),p.length&&n.renderLayer(n,h,f,p));}this.context.bindFramebuffer.set(null),this.context.clear({color:i.showOverdrawInspector?t.default$6.black:t.default$6.transparent,depth:1}),this._showOverdrawInspector=i.showOverdrawInspector,this.depthRange=(e._order.length+2)*this.numSublayers*this.depthEpsilon,this.renderPass="opaque";var m,_=[];for(this.currentLayer=s.length-1,this.currentLayer;this.currentLayer>=0;this.currentLayer--){var g=n.style._layers[s[n.currentLayer]];g.source!==(m&&m.id)&&(_=[],(m=n.style.sourceCaches[g.source])&&(n.clearStencil(),_=m.getVisibleCoordinates(),m.getSource().isTileClipped&&n._renderTileClippingMasks(_))),n.renderLayer(n,m,g,_);}this.renderPass="translucent";var v,y=[];for(this.currentLayer=0,this.currentLayer;this.currentLayer<s.length;this.currentLayer++){var x=n.style._layers[s[n.currentLayer]];x.source!==(v&&v.id)&&(y=[],(v=n.style.sourceCaches[x.source])&&(n.clearStencil(),y=v.getVisibleCoordinates(),v.getSource().isTileClipped&&n._renderTileClippingMasks(y)),y.reverse()),n.renderLayer(n,v,x,y);}if(this.options.showTileBoundaries){var b=this.style.sourceCaches[Object.keys(this.style.sourceCaches)[0]];b&&Mi.debug(this,b,b.getVisibleCoordinates());}},Li.prototype.setupOffscreenDepthRenderbuffer=function(){var t=this.context;this.depthRbo||(this.depthRbo=t.createRenderbuffer(t.gl.DEPTH_COMPONENT16,this.width,this.height));},Li.prototype.renderLayer=function(t,e,i,n){i.isHidden(this.transform.zoom)||("background"===i.type||n.length)&&(this.id=i.id,Mi[i.type](t,e,i,n));},Li.prototype.translatePosMatrix=function(e,i,n,o,r){if(!n[0]&&!n[1])return e;var a=r?"map"===o?this.transform.angle:0:"viewport"===o?-this.transform.angle:0;if(a){var s=Math.sin(a),l=Math.cos(a);n=[n[0]*l-n[1]*s,n[0]*s+n[1]*l];}var c=[r?n[0]:ze(i,n[0],this.transform.zoom),r?n[1]:ze(i,n[1],this.transform.zoom),0],u=new Float32Array(16);return t.mat4.translate(u,e,c),u},Li.prototype.saveTileTexture=function(t){var e=this._tileTextures[t.size[0]];e?e.push(t):this._tileTextures[t.size[0]]=[t];},Li.prototype.getTileTexture=function(t){var e=this._tileTextures[t];return e&&e.length>0?e.pop():null},Li.prototype._createProgramCached=function(t,e){this.cache=this.cache||{};var i=""+t+(e.cacheKey||"")+(this._showOverdrawInspector?"/overdraw":"");return this.cache[i]||(this.cache[i]=new ai(this.context,ri[t],e,this._showOverdrawInspector)),this.cache[i]},Li.prototype.useProgram=function(t,e){var i=this._createProgramCached(t,e||this.emptyProgramConfiguration);return this.context.program.set(i.program),i};var Oi=t.default$20.vec4,Fi=t.default$20.mat4,Ni=t.default$20.mat2,Ui=function(t,e,i){this.tileSize=512,this._renderWorldCopies=void 0===i||i,this._minZoom=t||0,this._maxZoom=e||22,this.latRange=[-85.05113,85.05113],this.width=0,this.height=0,this._center=new W(0,0),this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._unmodified=!0,this._posMatrixCache={},this._alignedPosMatrixCache={};},Zi={minZoom:{configurable:!0},maxZoom:{configurable:!0},renderWorldCopies:{configurable:!0},worldSize:{configurable:!0},centerPoint:{configurable:!0},size:{configurable:!0},bearing:{configurable:!0},pitch:{configurable:!0},fov:{configurable:!0},zoom:{configurable:!0},center:{configurable:!0},unmodified:{configurable:!0},x:{configurable:!0},y:{configurable:!0},point:{configurable:!0}};Ui.prototype.clone=function(){var t=new Ui(this._minZoom,this._maxZoom,this._renderWorldCopies);return t.tileSize=this.tileSize,t.latRange=this.latRange,t.width=this.width,t.height=this.height,t._center=this._center,t.zoom=this.zoom,t.angle=this.angle,t._fov=this._fov,t._pitch=this._pitch,t._unmodified=this._unmodified,t._calcMatrices(),t},Zi.minZoom.get=function(){return this._minZoom},Zi.minZoom.set=function(t){this._minZoom!==t&&(this._minZoom=t,this.zoom=Math.max(this.zoom,t));},Zi.maxZoom.get=function(){return this._maxZoom},Zi.maxZoom.set=function(t){this._maxZoom!==t&&(this._maxZoom=t,this.zoom=Math.min(this.zoom,t));},Zi.renderWorldCopies.get=function(){return this._renderWorldCopies},Zi.renderWorldCopies.set=function(t){void 0===t?t=!0:null===t&&(t=!1),this._renderWorldCopies=t;},Zi.worldSize.get=function(){return this.tileSize*this.scale},Zi.centerPoint.get=function(){return this.size._div(2)},Zi.size.get=function(){return new t.default$1(this.width,this.height)},Zi.bearing.get=function(){return-this.angle/Math.PI*180},Zi.bearing.set=function(e){var i=-t.wrap(e,-180,180)*Math.PI/180;this.angle!==i&&(this._unmodified=!1,this.angle=i,this._calcMatrices(),this.rotationMatrix=Ni.create(),Ni.rotate(this.rotationMatrix,this.rotationMatrix,this.angle));},Zi.pitch.get=function(){return this._pitch/Math.PI*180},Zi.pitch.set=function(e){var i=t.clamp(e,0,60)/180*Math.PI;this._pitch!==i&&(this._unmodified=!1,this._pitch=i,this._calcMatrices());},Zi.fov.get=function(){return this._fov/Math.PI*180},Zi.fov.set=function(t){t=Math.max(.01,Math.min(60,t)),this._fov!==t&&(this._unmodified=!1,this._fov=t/180*Math.PI,this._calcMatrices());},Zi.zoom.get=function(){return this._zoom},Zi.zoom.set=function(t){var e=Math.min(Math.max(t,this.minZoom),this.maxZoom);this._zoom!==e&&(this._unmodified=!1,this._zoom=e,this.scale=this.zoomScale(e),this.tileZoom=Math.floor(e),this.zoomFraction=e-this.tileZoom,this._constrain(),this._calcMatrices());},Zi.center.get=function(){return this._center},Zi.center.set=function(t){t.lat===this._center.lat&&t.lng===this._center.lng||(this._unmodified=!1,this._center=t,this._constrain(),this._calcMatrices());},Ui.prototype.coveringZoomLevel=function(t){return(t.roundZoom?Math.round:Math.floor)(this.zoom+this.scaleZoom(this.tileSize/t.tileSize))},Ui.prototype.getVisibleUnwrappedCoordinates=function(e){var i=this.pointCoordinate(new t.default$1(0,0),0),n=this.pointCoordinate(new t.default$1(this.width,0),0),o=Math.floor(i.column),r=Math.floor(n.column),a=[new t.UnwrappedTileID(0,e)];if(this._renderWorldCopies)for(var s=o;s<=r;s++)0!==s&&a.push(new t.UnwrappedTileID(s,e));return a},Ui.prototype.coveringTiles=function(e){var i=this.coveringZoomLevel(e),n=i;if(void 0!==e.minzoom&&i<e.minzoom)return[];void 0!==e.maxzoom&&i>e.maxzoom&&(i=e.maxzoom);var o=this.pointCoordinate(this.centerPoint,i),r=new t.default$1(o.column-.5,o.row-.5);return function(e,i,n,o){void 0===o&&(o=!0);var r=1<<e,a={};function s(i,s,l){var c,u,h,p;if(l>=0&&l<=r)for(c=i;c<s;c++)u=Math.floor(c/r),h=(c%r+r)%r,0!==u&&!0!==o||(p=new t.OverscaledTileID(n,u,e,h,l),a[p.key]=p);}return Bi(i[0],i[1],i[2],0,r,s),Bi(i[2],i[3],i[0],0,r,s),Object.keys(a).map(function(t){return a[t]})}(i,[this.pointCoordinate(new t.default$1(0,0),i),this.pointCoordinate(new t.default$1(this.width,0),i),this.pointCoordinate(new t.default$1(this.width,this.height),i),this.pointCoordinate(new t.default$1(0,this.height),i)],e.reparseOverscaled?n:i,this._renderWorldCopies).sort(function(t,e){return r.dist(t.canonical)-r.dist(e.canonical)})},Ui.prototype.resize=function(t,e){this.width=t,this.height=e,this.pixelsToGLUnits=[2/t,-2/e],this._constrain(),this._calcMatrices();},Zi.unmodified.get=function(){return this._unmodified},Ui.prototype.zoomScale=function(t){return Math.pow(2,t)},Ui.prototype.scaleZoom=function(t){return Math.log(t)/Math.LN2},Ui.prototype.project=function(e){return new t.default$1(this.lngX(e.lng),this.latY(e.lat))},Ui.prototype.unproject=function(t){return new W(this.xLng(t.x),this.yLat(t.y))},Zi.x.get=function(){return this.lngX(this.center.lng)},Zi.y.get=function(){return this.latY(this.center.lat)},Zi.point.get=function(){return new t.default$1(this.x,this.y)},Ui.prototype.lngX=function(t){return(180+t)*this.worldSize/360},Ui.prototype.latY=function(t){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))*this.worldSize/360},Ui.prototype.xLng=function(t){return 360*t/this.worldSize-180},Ui.prototype.yLat=function(t){var e=180-360*t/this.worldSize;return 360/Math.PI*Math.atan(Math.exp(e*Math.PI/180))-90},Ui.prototype.setLocationAtPoint=function(t,e){var i=this.pointCoordinate(e)._sub(this.pointCoordinate(this.centerPoint));this.center=this.coordinateLocation(this.locationCoordinate(t)._sub(i)),this._renderWorldCopies&&(this.center=this.center.wrap());},Ui.prototype.locationPoint=function(t){return this.coordinatePoint(this.locationCoordinate(t))},Ui.prototype.pointLocation=function(t){return this.coordinateLocation(this.pointCoordinate(t))},Ui.prototype.locationCoordinate=function(e){return new t.default$17(this.lngX(e.lng)/this.tileSize,this.latY(e.lat)/this.tileSize,this.zoom).zoomTo(this.tileZoom)},Ui.prototype.coordinateLocation=function(t){var e=t.zoomTo(this.zoom);return new W(this.xLng(e.column*this.tileSize),this.yLat(e.row*this.tileSize))},Ui.prototype.pointCoordinate=function(e,i){void 0===i&&(i=this.tileZoom);var n=[e.x,e.y,0,1],o=[e.x,e.y,1,1];Oi.transformMat4(n,n,this.pixelMatrixInverse),Oi.transformMat4(o,o,this.pixelMatrixInverse);var r=n[3],a=o[3],s=n[0]/r,l=o[0]/a,c=n[1]/r,u=o[1]/a,h=n[2]/r,p=o[2]/a,d=h===p?0:(0-h)/(p-h);return new t.default$17(t.number(s,l,d)/this.tileSize,t.number(c,u,d)/this.tileSize,this.zoom)._zoomTo(i)},Ui.prototype.coordinatePoint=function(e){var i=e.zoomTo(this.zoom),n=[i.column*this.tileSize,i.row*this.tileSize,0,1];return Oi.transformMat4(n,n,this.pixelMatrix),new t.default$1(n[0]/n[3],n[1]/n[3])},Ui.prototype.calculatePosMatrix=function(e,i){void 0===i&&(i=!1);var n=e.key,o=i?this._alignedPosMatrixCache:this._posMatrixCache;if(o[n])return o[n];var r=e.canonical,a=this.worldSize/this.zoomScale(r.z),s=r.x+Math.pow(2,r.z)*e.wrap,l=Fi.identity(new Float64Array(16));return Fi.translate(l,l,[s*a,r.y*a,0]),Fi.scale(l,l,[a/t.default$8,a/t.default$8,1]),Fi.multiply(l,i?this.alignedProjMatrix:this.projMatrix,l),o[n]=new Float32Array(l),o[n]},Ui.prototype._constrain=function(){if(this.center&&this.width&&this.height&&!this._constraining){this._constraining=!0;var e,i,n,o,r=-90,a=90,s=-180,l=180,c=this.size,u=this._unmodified;if(this.latRange){var h=this.latRange;r=this.latY(h[1]),e=(a=this.latY(h[0]))-r<c.y?c.y/(a-r):0;}if(this.lngRange){var p=this.lngRange;s=this.lngX(p[0]),i=(l=this.lngX(p[1]))-s<c.x?c.x/(l-s):0;}var d=Math.max(i||0,e||0);if(d)return this.center=this.unproject(new t.default$1(i?(l+s)/2:this.x,e?(a+r)/2:this.y)),this.zoom+=this.scaleZoom(d),this._unmodified=u,void(this._constraining=!1);if(this.latRange){var f=this.y,m=c.y/2;f-m<r&&(o=r+m),f+m>a&&(o=a-m);}if(this.lngRange){var _=this.x,g=c.x/2;_-g<s&&(n=s+g),_+g>l&&(n=l-g);}void 0===n&&void 0===o||(this.center=this.unproject(new t.default$1(void 0!==n?n:this.x,void 0!==o?o:this.y))),this._unmodified=u,this._constraining=!1;}},Ui.prototype._calcMatrices=function(){if(this.height){this.cameraToCenterDistance=.5/Math.tan(this._fov/2)*this.height;var t=this._fov/2,e=Math.PI/2+this._pitch,i=Math.sin(t)*this.cameraToCenterDistance/Math.sin(Math.PI-e-t),n=this.x,o=this.y,r=1.01*(Math.cos(Math.PI/2-this._pitch)*i+this.cameraToCenterDistance),a=new Float64Array(16);Fi.perspective(a,this._fov,this.width/this.height,1,r),Fi.scale(a,a,[1,-1,1]),Fi.translate(a,a,[0,0,-this.cameraToCenterDistance]),Fi.rotateX(a,a,this._pitch),Fi.rotateZ(a,a,this.angle),Fi.translate(a,a,[-n,-o,0]);var s=this.worldSize/(2*Math.PI*6378137*Math.abs(Math.cos(this.center.lat*(Math.PI/180))));Fi.scale(a,a,[1,1,s,1]),this.projMatrix=a;var l=this.width%2/2,c=this.height%2/2,u=Math.cos(this.angle),h=Math.sin(this.angle),p=n-Math.round(n)+u*l+h*c,d=o-Math.round(o)+u*c+h*l,f=new Float64Array(a);if(Fi.translate(f,f,[p>.5?p-1:p,d>.5?d-1:d,0]),this.alignedProjMatrix=f,a=Fi.create(),Fi.scale(a,a,[this.width/2,-this.height/2,1]),Fi.translate(a,a,[1,-1,0]),this.pixelMatrix=Fi.multiply(new Float64Array(16),a,this.projMatrix),!(a=Fi.invert(new Float64Array(16),this.pixelMatrix)))throw new Error("failed to invert matrix");this.pixelMatrixInverse=a,this._posMatrixCache={},this._alignedPosMatrixCache={};}},Ui.prototype.maxPitchScaleFactor=function(){if(!this.pixelMatrixInverse)return 1;var e=this.pointCoordinate(new t.default$1(0,0)).zoomTo(this.zoom),i=[e.column*this.tileSize,e.row*this.tileSize,0,1];return Oi.transformMat4(i,i,this.pixelMatrix)[3]/this.cameraToCenterDistance},Object.defineProperties(Ui.prototype,Zi);var Vi=function(){var e,i,n,o,r;t.bindAll(["_onHashChange","_updateHash"],this),this._updateHash=(e=this._updateHashUnthrottled.bind(this),i=300,n=!1,o=0,r=function(){o=0,n&&(e(),o=setTimeout(r,i),n=!1);},function(){return n=!0,o||r(),o});};Vi.prototype.addTo=function(e){return this._map=e,t.default.addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this},Vi.prototype.remove=function(){return t.default.removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),delete this._map,this},Vi.prototype.getHashString=function(t){var e=this._map.getCenter(),i=Math.round(100*this._map.getZoom())/100,n=Math.ceil((i*Math.LN2+Math.log(512/360/.5))/Math.LN10),o=Math.pow(10,n),r=Math.round(e.lng*o)/o,a=Math.round(e.lat*o)/o,s=this._map.getBearing(),l=this._map.getPitch(),c="";return c+=t?"#/"+r+"/"+a+"/"+i:"#"+i+"/"+a+"/"+r,(s||l)&&(c+="/"+Math.round(10*s)/10),l&&(c+="/"+Math.round(l)),c},Vi.prototype._onHashChange=function(){var e=t.default.location.hash.replace("#","").split("/");return e.length>=3&&(this._map.jumpTo({center:[+e[2],+e[1]],zoom:+e[0],bearing:+(e[3]||0),pitch:+(e[4]||0)}),!0)},Vi.prototype._updateHashUnthrottled=function(){var e=this.getHashString();t.default.history.replaceState(t.default.history.state,"",e);};var ji=function(e){function i(i,n,o,r){void 0===r&&(r={});var a=s.mousePos(n.getCanvasContainer(),o),l=n.unproject(a);e.call(this,i,t.extend({point:a,lngLat:l,originalEvent:o},r)),this._defaultPrevented=!1,this.target=n;}e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i;var n={defaultPrevented:{configurable:!0}};return i.prototype.preventDefault=function(){this._defaultPrevented=!0;},n.defaultPrevented.get=function(){return this._defaultPrevented},Object.defineProperties(i.prototype,n),i}(t.Event),$i=function(e){function i(i,n,o){var r=s.touchPos(n.getCanvasContainer(),o),a=r.map(function(t){return n.unproject(t)}),l=r.reduce(function(t,e,i,n){return t.add(e.div(n.length))},new t.default$1(0,0)),c=n.unproject(l);e.call(this,i,{points:r,point:l,lngLats:a,lngLat:c,originalEvent:o}),this._defaultPrevented=!1;}e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i;var n={defaultPrevented:{configurable:!0}};return i.prototype.preventDefault=function(){this._defaultPrevented=!0;},n.defaultPrevented.get=function(){return this._defaultPrevented},Object.defineProperties(i.prototype,n),i}(t.Event),Gi=function(t){function e(e,i,n){t.call(this,e,{originalEvent:n}),this._defaultPrevented=!1;}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var i={defaultPrevented:{configurable:!0}};return e.prototype.preventDefault=function(){this._defaultPrevented=!0;},i.defaultPrevented.get=function(){return this._defaultPrevented},Object.defineProperties(e.prototype,i),e}(t.Event),Wi=function(e){this._map=e,this._el=e.getCanvasContainer(),this._delta=0,t.bindAll(["_onWheel","_onTimeout","_onScrollFrame","_onScrollFinished"],this);};Wi.prototype.isEnabled=function(){return!!this._enabled},Wi.prototype.isActive=function(){return!!this._active},Wi.prototype.enable=function(t){this.isEnabled()||(this._enabled=!0,this._aroundCenter=t&&"center"===t.around);},Wi.prototype.disable=function(){this.isEnabled()&&(this._enabled=!1);},Wi.prototype.onWheel=function(e){if(this.isEnabled()){var i=e.deltaMode===t.default.WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY,n=r.now(),o=n-(this._lastWheelEventTime||0);this._lastWheelEventTime=n,0!==i&&i%4.000244140625==0?this._type="wheel":0!==i&&Math.abs(i)<4?this._type="trackpad":o>400?(this._type=null,this._lastValue=i,this._timeout=setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(o*i)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,i+=this._lastValue)),e.shiftKey&&i&&(i/=4),this._type&&(this._lastWheelEvent=e,this._delta-=i,this.isActive()||this._start(e)),e.preventDefault();}},Wi.prototype._onTimeout=function(t){this._type="wheel",this._delta-=this._lastValue,this.isActive()||this._start(t);},Wi.prototype._start=function(e){if(this._delta){this._frameId&&(this._map._cancelRenderFrame(this._frameId),this._frameId=null),this._active=!0,this._map.fire(new t.Event("movestart",{originalEvent:e})),this._map.fire(new t.Event("zoomstart",{originalEvent:e})),this._finishTimeout&&clearTimeout(this._finishTimeout);var i=s.mousePos(this._el,e);this._around=W.convert(this._aroundCenter?this._map.getCenter():this._map.unproject(i)),this._aroundPoint=this._map.transform.locationPoint(this._around),this._frameId||(this._frameId=this._map._requestRenderFrame(this._onScrollFrame));}},Wi.prototype._onScrollFrame=function(){var e=this;if(this._frameId=null,this.isActive()){var i=this._map.transform;if(0!==this._delta){var n="wheel"===this._type&&Math.abs(this._delta)>4.000244140625?1/450:.01,o=2/(1+Math.exp(-Math.abs(this._delta*n)));this._delta<0&&0!==o&&(o=1/o);var a="number"==typeof this._targetZoom?i.zoomScale(this._targetZoom):i.scale;this._targetZoom=Math.min(i.maxZoom,Math.max(i.minZoom,i.scaleZoom(a*o))),"wheel"===this._type&&(this._startZoom=i.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0;}var s=!1;if("wheel"===this._type){var l=Math.min((r.now()-this._lastWheelEventTime)/200,1),c=this._easing(l);i.zoom=t.number(this._startZoom,this._targetZoom,c),l<1?this._frameId||(this._frameId=this._map._requestRenderFrame(this._onScrollFrame)):s=!0;}else i.zoom=this._targetZoom,s=!0;i.setLocationAtPoint(this._around,this._aroundPoint),this._map.fire(new t.Event("move",{originalEvent:this._lastWheelEvent})),this._map.fire(new t.Event("zoom",{originalEvent:this._lastWheelEvent})),s&&(this._active=!1,this._finishTimeout=setTimeout(function(){e._map.fire(new t.Event("zoomend",{originalEvent:e._lastWheelEvent})),e._map.fire(new t.Event("moveend",{originalEvent:e._lastWheelEvent})),delete e._targetZoom;},200));}},Wi.prototype._smoothOutEasing=function(e){var i=t.ease;if(this._prevEase){var n=this._prevEase,o=(r.now()-n.start)/n.duration,a=n.easing(o+.01)-n.easing(o),s=.27/Math.sqrt(a*a+1e-4)*.01,l=Math.sqrt(.0729-s*s);i=t.bezier(s,l,.25,1);}return this._prevEase={start:r.now(),duration:e,easing:i},i};var qi=function(e){this._map=e,this._el=e.getCanvasContainer(),this._container=e.getContainer(),t.bindAll(["_onMouseMove","_onMouseUp","_onKeyDown"],this);};qi.prototype.isEnabled=function(){return!!this._enabled},qi.prototype.isActive=function(){return!!this._active},qi.prototype.enable=function(){this.isEnabled()||(this._enabled=!0);},qi.prototype.disable=function(){this.isEnabled()&&(this._enabled=!1);},qi.prototype.onMouseDown=function(e){this.isEnabled()&&e.shiftKey&&0===e.button&&(t.default.document.addEventListener("mousemove",this._onMouseMove,!1),t.default.document.addEventListener("keydown",this._onKeyDown,!1),t.default.document.addEventListener("mouseup",this._onMouseUp,!1),s.disableDrag(),this._startPos=s.mousePos(this._el,e),this._active=!0);},qi.prototype._onMouseMove=function(t){var e=this._startPos,i=s.mousePos(this._el,t);this._box||(this._box=s.create("div","mapboxgl-boxzoom",this._container),this._container.classList.add("mapboxgl-crosshair"),this._fireEvent("boxzoomstart",t));var n=Math.min(e.x,i.x),o=Math.max(e.x,i.x),r=Math.min(e.y,i.y),a=Math.max(e.y,i.y);s.setTransform(this._box,"translate("+n+"px,"+r+"px)"),this._box.style.width=o-n+"px",this._box.style.height=a-r+"px";},qi.prototype._onMouseUp=function(e){if(0===e.button){var i=this._startPos,n=s.mousePos(this._el,e),o=(new q).extend(this._map.unproject(i)).extend(this._map.unproject(n));this._finish(),s.suppressClick(),i.x===n.x&&i.y===n.y?this._fireEvent("boxzoomcancel",e):this._map.fitBounds(o,{linear:!0}).fire(new t.Event("boxzoomend",{originalEvent:e,boxZoomBounds:o}));}},qi.prototype._onKeyDown=function(t){27===t.keyCode&&(this._finish(),this._fireEvent("boxzoomcancel",t));},qi.prototype._finish=function(){this._active=!1,t.default.document.removeEventListener("mousemove",this._onMouseMove,!1),t.default.document.removeEventListener("keydown",this._onKeyDown,!1),t.default.document.removeEventListener("mouseup",this._onMouseUp,!1),this._container.classList.remove("mapboxgl-crosshair"),this._box&&(s.remove(this._box),this._box=null),s.enableDrag();},qi.prototype._fireEvent=function(e,i){return this._map.fire(new t.Event(e,{originalEvent:i}))};var Xi=t.bezier(0,0,.25,1),Hi=function(e,i){this._map=e,this._el=i.element||e.getCanvasContainer(),this._state="disabled",this._button=i.button||"right",this._bearingSnap=i.bearingSnap||0,this._pitchWithRotate=!1!==i.pitchWithRotate,t.bindAll(["_onMouseMove","_onMouseUp","_onBlur","_onDragFrame"],this);};Hi.prototype.isEnabled=function(){return"disabled"!==this._state},Hi.prototype.isActive=function(){return"active"===this._state},Hi.prototype.enable=function(){this.isEnabled()||(this._state="enabled");},Hi.prototype.disable=function(){if(this.isEnabled())switch(this._state){case"active":this._state="disabled",this._unbind(),this._deactivate(),this._fireEvent("rotateend"),this._pitchWithRotate&&this._fireEvent("pitchend"),this._fireEvent("moveend");break;case"pending":this._state="disabled",this._unbind();break;default:this._state="disabled";}},Hi.prototype.onMouseDown=function(e){if("enabled"===this._state){if("right"===this._button){if(this._eventButton=s.mouseButton(e),this._eventButton!==(e.ctrlKey?0:2))return}else{if(e.ctrlKey||0!==s.mouseButton(e))return;this._eventButton=0;}s.disableDrag(),t.default.document.addEventListener("mousemove",this._onMouseMove,{capture:!0}),t.default.document.addEventListener("mouseup",this._onMouseUp),t.default.addEventListener("blur",this._onBlur),this._state="pending",this._inertia=[[r.now(),this._map.getBearing()]],this._previousPos=s.mousePos(this._el,e),this._center=this._map.transform.centerPoint,e.preventDefault();}},Hi.prototype._onMouseMove=function(t){this._lastMoveEvent=t,this._pos=s.mousePos(this._el,t),"pending"===this._state&&(this._state="active",this._fireEvent("rotatestart",t),this._fireEvent("movestart",t),this._pitchWithRotate&&this._fireEvent("pitchstart",t)),this._frameId||(this._frameId=this._map._requestRenderFrame(this._onDragFrame));},Hi.prototype._onDragFrame=function(){this._frameId=null;var t=this._lastMoveEvent;if(t){var e=this._map.transform,i=this._previousPos,n=this._pos,o=.8*(i.x-n.x),a=-.5*(i.y-n.y),s=e.bearing-o,l=e.pitch-a,c=this._inertia,u=c[c.length-1];this._drainInertiaBuffer(),c.push([r.now(),this._map._normalizeBearing(s,u[1])]),e.bearing=s,this._pitchWithRotate&&(this._fireEvent("pitch",t),e.pitch=l),this._fireEvent("rotate",t),this._fireEvent("move",t),delete this._lastMoveEvent,this._previousPos=this._pos;}},Hi.prototype._onMouseUp=function(t){if(s.mouseButton(t)===this._eventButton)switch(this._state){case"active":this._state="enabled",s.suppressClick(),this._unbind(),this._deactivate(),this._inertialRotate(t);break;case"pending":this._state="enabled",this._unbind();}},Hi.prototype._onBlur=function(t){switch(this._state){case"active":this._state="enabled",this._unbind(),this._deactivate(),this._fireEvent("rotateend",t),this._pitchWithRotate&&this._fireEvent("pitchend",t),this._fireEvent("moveend",t);break;case"pending":this._state="enabled",this._unbind();}},Hi.prototype._unbind=function(){t.default.document.removeEventListener("mousemove",this._onMouseMove,{capture:!0}),t.default.document.removeEventListener("mouseup",this._onMouseUp),t.default.removeEventListener("blur",this._onBlur),s.enableDrag();},Hi.prototype._deactivate=function(){this._frameId&&(this._map._cancelRenderFrame(this._frameId),this._frameId=null),delete this._lastMoveEvent,delete this._previousPos;},Hi.prototype._inertialRotate=function(t){var e=this;this._fireEvent("rotateend",t),this._drainInertiaBuffer();var i=this._map,n=i.getBearing(),o=this._inertia,r=function(){Math.abs(n)<e._bearingSnap?i.resetNorth({noMoveStart:!0},{originalEvent:t}):e._fireEvent("moveend",t),e._pitchWithRotate&&e._fireEvent("pitchend",t);};if(o.length<2)r();else{var a=o[0],s=o[o.length-1],l=o[o.length-2],c=i._normalizeBearing(n,l[1]),u=s[1]-a[1],h=u<0?-1:1,p=(s[0]-a[0])/1e3;if(0!==u&&0!==p){var d=Math.abs(u*(.25/p));d>180&&(d=180);var f=d/180;c+=h*d*(f/2),Math.abs(i._normalizeBearing(c,0))<this._bearingSnap&&(c=i._normalizeBearing(0,c)),i.rotateTo(c,{duration:1e3*f,easing:Xi,noMoveStart:!0},{originalEvent:t});}else r();}},Hi.prototype._fireEvent=function(e,i){return this._map.fire(new t.Event(e,i?{originalEvent:i}:{}))},Hi.prototype._drainInertiaBuffer=function(){for(var t=this._inertia,e=r.now();t.length>0&&e-t[0][0]>160;)t.shift();};var Ki=t.bezier(0,0,.3,1),Yi=function(e){this._map=e,this._el=e.getCanvasContainer(),this._state="disabled",t.bindAll(["_onMove","_onMouseUp","_onTouchEnd","_onBlur","_onDragFrame"],this);};Yi.prototype.isEnabled=function(){return"disabled"!==this._state},Yi.prototype.isActive=function(){return"active"===this._state},Yi.prototype.enable=function(){this.isEnabled()||(this._el.classList.add("mapboxgl-touch-drag-pan"),this._state="enabled");},Yi.prototype.disable=function(){if(this.isEnabled())switch(this._el.classList.remove("mapboxgl-touch-drag-pan"),this._state){case"active":this._state="disabled",this._unbind(),this._deactivate(),this._fireEvent("dragend"),this._fireEvent("moveend");break;case"pending":this._state="disabled",this._unbind();break;default:this._state="disabled";}},Yi.prototype.onMouseDown=function(e){"enabled"===this._state&&(e.ctrlKey||0!==s.mouseButton(e)||(s.addEventListener(t.default.document,"mousemove",this._onMove,{capture:!0}),s.addEventListener(t.default.document,"mouseup",this._onMouseUp),this._start(e)));},Yi.prototype.onTouchStart=function(e){"enabled"===this._state&&(e.touches.length>1||(s.addEventListener(t.default.document,"touchmove",this._onMove,{capture:!0,passive:!1}),s.addEventListener(t.default.document,"touchend",this._onTouchEnd),this._start(e)));},Yi.prototype._start=function(e){t.default.addEventListener("blur",this._onBlur),this._state="pending",this._previousPos=s.mousePos(this._el,e),this._inertia=[[r.now(),this._previousPos]];},Yi.prototype._onMove=function(t){this._lastMoveEvent=t,t.preventDefault(),this._pos=s.mousePos(this._el,t),this._drainInertiaBuffer(),this._inertia.push([r.now(),this._pos]),"pending"===this._state&&(this._state="active",this._fireEvent("dragstart",t),this._fireEvent("movestart",t)),this._frameId||(this._frameId=this._map._requestRenderFrame(this._onDragFrame));},Yi.prototype._onDragFrame=function(){this._frameId=null;var t=this._lastMoveEvent;if(t){var e=this._map.transform;e.setLocationAtPoint(e.pointLocation(this._previousPos),this._pos),this._fireEvent("drag",t),this._fireEvent("move",t),this._previousPos=this._pos,delete this._lastMoveEvent;}},Yi.prototype._onMouseUp=function(t){if(0===s.mouseButton(t))switch(this._state){case"active":this._state="enabled",s.suppressClick(),this._unbind(),this._deactivate(),this._inertialPan(t);break;case"pending":this._state="enabled",this._unbind();}},Yi.prototype._onTouchEnd=function(t){switch(this._state){case"active":this._state="enabled",this._unbind(),this._deactivate(),this._inertialPan(t);break;case"pending":this._state="enabled",this._unbind();}},Yi.prototype._onBlur=function(t){switch(this._state){case"active":this._state="enabled",this._unbind(),this._deactivate(),this._fireEvent("dragend",t),this._fireEvent("moveend",t);break;case"pending":this._state="enabled",this._unbind();}},Yi.prototype._unbind=function(){s.removeEventListener(t.default.document,"touchmove",this._onMove,{capture:!0,passive:!1}),s.removeEventListener(t.default.document,"touchend",this._onTouchEnd),s.removeEventListener(t.default.document,"mousemove",this._onMove,{capture:!0}),s.removeEventListener(t.default.document,"mouseup",this._onMouseUp),s.removeEventListener(t.default,"blur",this._onBlur);},Yi.prototype._deactivate=function(){this._frameId&&(this._map._cancelRenderFrame(this._frameId),this._frameId=null),delete this._lastMoveEvent,delete this._previousPos,delete this._pos;},Yi.prototype._inertialPan=function(t){this._fireEvent("dragend",t),this._drainInertiaBuffer();var e=this._inertia;if(e.length<2)this._fireEvent("moveend",t);else{var i=e[e.length-1],n=e[0],o=i[1].sub(n[1]),r=(i[0]-n[0])/1e3;if(0===r||i[1].equals(n[1]))this._fireEvent("moveend",t);else{var a=o.mult(.3/r),s=a.mag();s>1400&&(s=1400,a._unit()._mult(s));var l=s/750,c=a.mult(-l/2);this._map.panBy(c,{duration:1e3*l,easing:Ki,noMoveStart:!0},{originalEvent:t});}}},Yi.prototype._fireEvent=function(e,i){return this._map.fire(new t.Event(e,i?{originalEvent:i}:{}))},Yi.prototype._drainInertiaBuffer=function(){for(var t=this._inertia,e=r.now();t.length>0&&e-t[0][0]>160;)t.shift();};var Ji=function(e){this._map=e,this._el=e.getCanvasContainer(),t.bindAll(["_onKeyDown"],this);};function Qi(t){return t*(2-t)}Ji.prototype.isEnabled=function(){return!!this._enabled},Ji.prototype.enable=function(){this.isEnabled()||(this._el.addEventListener("keydown",this._onKeyDown,!1),this._enabled=!0);},Ji.prototype.disable=function(){this.isEnabled()&&(this._el.removeEventListener("keydown",this._onKeyDown),this._enabled=!1);},Ji.prototype._onKeyDown=function(t){if(!(t.altKey||t.ctrlKey||t.metaKey)){var e=0,i=0,n=0,o=0,r=0;switch(t.keyCode){case 61:case 107:case 171:case 187:e=1;break;case 189:case 109:case 173:e=-1;break;case 37:t.shiftKey?i=-1:(t.preventDefault(),o=-1);break;case 39:t.shiftKey?i=1:(t.preventDefault(),o=1);break;case 38:t.shiftKey?n=1:(t.preventDefault(),r=-1);break;case 40:t.shiftKey?n=-1:(r=1,t.preventDefault());break;default:return}var a=this._map,s=a.getZoom(),l={duration:300,delayEndEvents:500,easing:Qi,zoom:e?Math.round(s)+e*(t.shiftKey?2:1):s,bearing:a.getBearing()+15*i,pitch:a.getPitch()+10*n,offset:[100*-o,100*-r],center:a.getCenter()};a.easeTo(l,{originalEvent:t});}};var tn=function(e){this._map=e,t.bindAll(["_onDblClick","_onZoomEnd"],this);};tn.prototype.isEnabled=function(){return!!this._enabled},tn.prototype.isActive=function(){return!!this._active},tn.prototype.enable=function(){this.isEnabled()||(this._enabled=!0);},tn.prototype.disable=function(){this.isEnabled()&&(this._enabled=!1);},tn.prototype.onTouchStart=function(t){var e=this;this.isEnabled()&&(t.points.length>1||(this._tapped?(clearTimeout(this._tapped),this._tapped=null,this._zoom(t)):this._tapped=setTimeout(function(){e._tapped=null;},300)));},tn.prototype.onDblClick=function(t){this.isEnabled()&&(t.originalEvent.preventDefault(),this._zoom(t));},tn.prototype._zoom=function(t){this._active=!0,this._map.on("zoomend",this._onZoomEnd),this._map.zoomTo(this._map.getZoom()+(t.originalEvent.shiftKey?-1:1),{around:t.lngLat},t);},tn.prototype._onZoomEnd=function(){this._active=!1,this._map.off("zoomend",this._onZoomEnd);};var en=t.bezier(0,0,.15,1),nn=function(e){this._map=e,this._el=e.getCanvasContainer(),t.bindAll(["_onMove","_onEnd","_onTouchFrame"],this);};nn.prototype.isEnabled=function(){return!!this._enabled},nn.prototype.enable=function(t){this.isEnabled()||(this._el.classList.add("mapboxgl-touch-zoom-rotate"),this._enabled=!0,this._aroundCenter=!!t&&"center"===t.around);},nn.prototype.disable=function(){this.isEnabled()&&(this._el.classList.remove("mapboxgl-touch-zoom-rotate"),this._enabled=!1);},nn.prototype.disableRotation=function(){this._rotationDisabled=!0;},nn.prototype.enableRotation=function(){this._rotationDisabled=!1;},nn.prototype.onStart=function(e){if(this.isEnabled()&&2===e.touches.length){var i=s.mousePos(this._el,e.touches[0]),n=s.mousePos(this._el,e.touches[1]);this._startVec=i.sub(n),this._gestureIntent=void 0,this._inertia=[],s.addEventListener(t.default.document,"touchmove",this._onMove,{passive:!1}),s.addEventListener(t.default.document,"touchend",this._onEnd);}},nn.prototype._getTouchEventData=function(t){var e=s.mousePos(this._el,t.touches[0]),i=s.mousePos(this._el,t.touches[1]),n=e.sub(i);return{vec:n,center:e.add(i).div(2),scale:n.mag()/this._startVec.mag(),bearing:this._rotationDisabled?0:180*n.angleWith(this._startVec)/Math.PI}},nn.prototype._onMove=function(e){if(2===e.touches.length){var i=this._getTouchEventData(e),n=i.vec,o=i.scale,r=i.bearing;if(!this._gestureIntent){var a=Math.abs(1-o)>.15;Math.abs(r)>10?this._gestureIntent="rotate":a&&(this._gestureIntent="zoom"),this._gestureIntent&&(this._map.fire(new t.Event(this._gestureIntent+"start",{originalEvent:e})),this._map.fire(new t.Event("movestart",{originalEvent:e})),this._startVec=n);}this._lastTouchEvent=e,this._frameId||(this._frameId=this._map._requestRenderFrame(this._onTouchFrame)),e.preventDefault();}},nn.prototype._onTouchFrame=function(){this._frameId=null;var e=this._gestureIntent;if(e){var i=this._map.transform;this._startScale||(this._startScale=i.scale,this._startBearing=i.bearing);var n=this._getTouchEventData(this._lastTouchEvent),o=n.center,a=n.bearing,s=n.scale,l=i.pointLocation(o),c=i.locationPoint(l);"rotate"===e&&(i.bearing=this._startBearing+a),i.zoom=i.scaleZoom(this._startScale*s),i.setLocationAtPoint(l,c),this._map.fire(new t.Event(e,{originalEvent:this._lastTouchEvent})),this._map.fire(new t.Event("move",{originalEvent:this._lastTouchEvent})),this._drainInertiaBuffer(),this._inertia.push([r.now(),s,o]);}},nn.prototype._onEnd=function(e){s.removeEventListener(t.default.document,"touchmove",this._onMove,{passive:!1}),s.removeEventListener(t.default.document,"touchend",this._onEnd);var i=this._gestureIntent,n=this._startScale;if(this._frameId&&(this._map._cancelRenderFrame(this._frameId),this._frameId=null),delete this._gestureIntent,delete this._startScale,delete this._startBearing,delete this._lastTouchEvent,i){this._map.fire(new t.Event(i+"end",{originalEvent:e})),this._drainInertiaBuffer();var o=this._inertia,r=this._map;if(o.length<2)r.snapToNorth({},{originalEvent:e});else{var a=o[o.length-1],l=o[0],c=r.transform.scaleZoom(n*a[1]),u=r.transform.scaleZoom(n*l[1]),h=c-u,p=(a[0]-l[0])/1e3,d=a[2];if(0!==p&&c!==u){var f=.15*h/p;Math.abs(f)>2.5&&(f=f>0?2.5:-2.5);var m=1e3*Math.abs(f/(12*.15)),_=c+f*m/2e3;_<0&&(_=0),r.easeTo({zoom:_,duration:m,easing:en,around:this._aroundCenter?r.getCenter():r.unproject(d),noMoveStart:!0},{originalEvent:e});}else r.snapToNorth({},{originalEvent:e});}}},nn.prototype._drainInertiaBuffer=function(){for(var t=this._inertia,e=r.now();t.length>2&&e-t[0][0]>160;)t.shift();};var on={scrollZoom:Wi,boxZoom:qi,dragRotate:Hi,dragPan:Yi,keyboard:Ji,doubleClickZoom:tn,touchZoomRotate:nn};var rn=function(e){function i(i,n){e.call(this),this._moving=!1,this._zooming=!1,this.transform=i,this._bearingSnap=n.bearingSnap,t.bindAll(["_renderFrameCallback"],this);}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.getCenter=function(){return this.transform.center},i.prototype.setCenter=function(t,e){return this.jumpTo({center:t},e)},i.prototype.panBy=function(e,i,n){return e=t.default$1.convert(e).mult(-1),this.panTo(this.transform.center,t.extend({offset:e},i),n)},i.prototype.panTo=function(e,i,n){return this.easeTo(t.extend({center:e},i),n)},i.prototype.getZoom=function(){return this.transform.zoom},i.prototype.setZoom=function(t,e){return this.jumpTo({zoom:t},e),this},i.prototype.zoomTo=function(e,i,n){return this.easeTo(t.extend({zoom:e},i),n)},i.prototype.zoomIn=function(t,e){return this.zoomTo(this.getZoom()+1,t,e),this},i.prototype.zoomOut=function(t,e){return this.zoomTo(this.getZoom()-1,t,e),this},i.prototype.getBearing=function(){return this.transform.bearing},i.prototype.setBearing=function(t,e){return this.jumpTo({bearing:t},e),this},i.prototype.rotateTo=function(e,i,n){return this.easeTo(t.extend({bearing:e},i),n)},i.prototype.resetNorth=function(e,i){return this.rotateTo(0,t.extend({duration:1e3},e),i),this},i.prototype.snapToNorth=function(t,e){return Math.abs(this.getBearing())<this._bearingSnap?this.resetNorth(t,e):this},i.prototype.getPitch=function(){return this.transform.pitch},i.prototype.setPitch=function(t,e){return this.jumpTo({pitch:t},e),this},i.prototype.fitBounds=function(e,i,n){if("number"==typeof(i=t.extend({padding:{top:0,bottom:0,right:0,left:0},offset:[0,0],maxZoom:this.transform.maxZoom},i)).padding){var o=i.padding;i.padding={top:o,bottom:o,right:o,left:o};}if(!t.default$10(Object.keys(i.padding).sort(function(t,e){return t<e?-1:t>e?1:0}),["bottom","left","right","top"]))return t.warnOnce("options.padding must be a positive number, or an Object with keys 'bottom', 'left', 'right', 'top'"),this;e=q.convert(e);var r=[(i.padding.left-i.padding.right)/2,(i.padding.top-i.padding.bottom)/2],a=Math.min(i.padding.right,i.padding.left),s=Math.min(i.padding.top,i.padding.bottom);i.offset=[i.offset[0]+r[0],i.offset[1]+r[1]];var l=t.default$1.convert(i.offset),c=this.transform,u=c.project(e.getNorthWest()),h=c.project(e.getSouthEast()),p=h.sub(u),d=(c.width-2*a-2*Math.abs(l.x))/p.x,f=(c.height-2*s-2*Math.abs(l.y))/p.y;return f<0||d<0?(t.warnOnce("Map cannot fit within canvas with the given bounds, padding, and/or offset."),this):(i.center=c.unproject(u.add(h).div(2)),i.zoom=Math.min(c.scaleZoom(c.scale*Math.min(d,f)),i.maxZoom),i.bearing=0,i.linear?this.easeTo(i,n):this.flyTo(i,n))},i.prototype.jumpTo=function(e,i){this.stop();var n=this.transform,o=!1,r=!1,a=!1;return"zoom"in e&&n.zoom!==+e.zoom&&(o=!0,n.zoom=+e.zoom),void 0!==e.center&&(n.center=W.convert(e.center)),"bearing"in e&&n.bearing!==+e.bearing&&(r=!0,n.bearing=+e.bearing),"pitch"in e&&n.pitch!==+e.pitch&&(a=!0,n.pitch=+e.pitch),this.fire(new t.Event("movestart",i)).fire(new t.Event("move",i)),o&&this.fire(new t.Event("zoomstart",i)).fire(new t.Event("zoom",i)).fire(new t.Event("zoomend",i)),r&&this.fire(new t.Event("rotatestart",i)).fire(new t.Event("rotate",i)).fire(new t.Event("rotateend",i)),a&&this.fire(new t.Event("pitchstart",i)).fire(new t.Event("pitch",i)).fire(new t.Event("pitchend",i)),this.fire(new t.Event("moveend",i))},i.prototype.easeTo=function(e,i){var n=this;this.stop(),!1===(e=t.extend({offset:[0,0],duration:500,easing:t.ease},e)).animate&&(e.duration=0);var o=this.transform,r=this.getZoom(),a=this.getBearing(),s=this.getPitch(),l="zoom"in e?+e.zoom:r,c="bearing"in e?this._normalizeBearing(e.bearing,a):a,u="pitch"in e?+e.pitch:s,h=o.centerPoint.add(t.default$1.convert(e.offset)),p=o.pointLocation(h),d=W.convert(e.center||p);this._normalizeCenter(d);var f,m,_=o.project(p),g=o.project(d).sub(_),v=o.zoomScale(l-r);return e.around&&(f=W.convert(e.around),m=o.locationPoint(f)),this._zooming=l!==r,this._rotating=a!==c,this._pitching=u!==s,this._prepareEase(i,e.noMoveStart),clearTimeout(this._easeEndTimeoutID),this._ease(function(e){if(n._zooming&&(o.zoom=t.number(r,l,e)),n._rotating&&(o.bearing=t.number(a,c,e)),n._pitching&&(o.pitch=t.number(s,u,e)),f)o.setLocationAtPoint(f,m);else{var p=o.zoomScale(o.zoom-r),d=l>r?Math.min(2,v):Math.max(.5,v),y=Math.pow(d,1-e),x=o.unproject(_.add(g.mult(e*y)).mult(p));o.setLocationAtPoint(o.renderWorldCopies?x.wrap():x,h);}n._fireMoveEvents(i);},function(){e.delayEndEvents?n._easeEndTimeoutID=setTimeout(function(){return n._afterEase(i)},e.delayEndEvents):n._afterEase(i);},e),this},i.prototype._prepareEase=function(e,i){this._moving=!0,i||this.fire(new t.Event("movestart",e)),this._zooming&&this.fire(new t.Event("zoomstart",e)),this._rotating&&this.fire(new t.Event("rotatestart",e)),this._pitching&&this.fire(new t.Event("pitchstart",e));},i.prototype._fireMoveEvents=function(e){this.fire(new t.Event("move",e)),this._zooming&&this.fire(new t.Event("zoom",e)),this._rotating&&this.fire(new t.Event("rotate",e)),this._pitching&&this.fire(new t.Event("pitch",e));},i.prototype._afterEase=function(e){var i=this._zooming,n=this._rotating,o=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,i&&this.fire(new t.Event("zoomend",e)),n&&this.fire(new t.Event("rotateend",e)),o&&this.fire(new t.Event("pitchend",e)),this.fire(new t.Event("moveend",e));},i.prototype.flyTo=function(e,i){var n=this;this.stop(),e=t.extend({offset:[0,0],speed:1.2,curve:1.42,easing:t.ease},e);var o=this.transform,r=this.getZoom(),a=this.getBearing(),s=this.getPitch(),l="zoom"in e?t.clamp(+e.zoom,o.minZoom,o.maxZoom):r,c="bearing"in e?this._normalizeBearing(e.bearing,a):a,u="pitch"in e?+e.pitch:s,h=o.zoomScale(l-r),p=o.centerPoint.add(t.default$1.convert(e.offset)),d=o.pointLocation(p),f=W.convert(e.center||d);this._normalizeCenter(f);var m=o.project(d),_=o.project(f).sub(m),g=e.curve,v=Math.max(o.width,o.height),y=v/h,x=_.mag();if("minZoom"in e){var b=t.clamp(Math.min(e.minZoom,r,l),o.minZoom,o.maxZoom),w=v/o.zoomScale(b-r);g=Math.sqrt(w/x*2);}var E=g*g;function T(t){var e=(y*y-v*v+(t?-1:1)*E*E*x*x)/(2*(t?y:v)*E*x);return Math.log(Math.sqrt(e*e+1)-e)}function I(t){return(Math.exp(t)-Math.exp(-t))/2}function C(t){return(Math.exp(t)+Math.exp(-t))/2}var S=T(0),z=function(t){return C(S)/C(S+g*t)},A=function(t){return v*((C(S)*(I(e=S+g*t)/C(e))-I(S))/E)/x;var e;},R=(T(1)-S)/g;if(Math.abs(x)<1e-6||!isFinite(R)){if(Math.abs(v-y)<1e-6)return this.easeTo(e,i);var D=y<v?-1:1;R=Math.abs(Math.log(y/v))/g,A=function(){return 0},z=function(t){return Math.exp(D*g*t)};}if("duration"in e)e.duration=+e.duration;else{var M="screenSpeed"in e?+e.screenSpeed/g:+e.speed;e.duration=1e3*R/M;}return e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0),this._zooming=!0,this._rotating=a!==c,this._pitching=u!==s,this._prepareEase(i,!1),this._ease(function(e){var l=e*R,h=1/z(l);o.zoom=r+o.scaleZoom(h),n._rotating&&(o.bearing=t.number(a,c,e)),n._pitching&&(o.pitch=t.number(s,u,e));var d=o.unproject(m.add(_.mult(A(l))).mult(h));o.setLocationAtPoint(o.renderWorldCopies?d.wrap():d,p),n._fireMoveEvents(i);},function(){return n._afterEase(i)},e),this},i.prototype.isEasing=function(){return!!this._easeFrameId},i.prototype.stop=function(){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){var t=this._onEaseEnd;delete this._onEaseEnd,t.call(this);}return this},i.prototype._ease=function(t,e,i){!1===i.animate||0===i.duration?(t(1),e()):(this._easeStart=r.now(),this._easeOptions=i,this._onEaseFrame=t,this._onEaseEnd=e,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback));},i.prototype._renderFrameCallback=function(){var t=Math.min((r.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(t)),t<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop();},i.prototype._normalizeBearing=function(e,i){e=t.wrap(e,-180,180);var n=Math.abs(e-i);return Math.abs(e-360-i)<n&&(e-=360),Math.abs(e+360-i)<n&&(e+=360),e},i.prototype._normalizeCenter=function(t){var e=this.transform;if(e.renderWorldCopies&&!e.lngRange){var i=t.lng-e.center.lng;t.lng+=i>180?-360:i<-180?360:0;}},i}(t.Evented),an=function(e){void 0===e&&(e={}),this.options=e,t.bindAll(["_updateEditLink","_updateData","_updateCompact"],this);};an.prototype.getDefaultPosition=function(){return"bottom-right"},an.prototype.onAdd=function(t){var e=this.options&&this.options.compact;return this._map=t,this._container=s.create("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),e&&this._container.classList.add("mapboxgl-compact"),this._updateAttributions(),this._updateEditLink(),this._map.on("sourcedata",this._updateData),this._map.on("moveend",this._updateEditLink),void 0===e&&(this._map.on("resize",this._updateCompact),this._updateCompact()),this._container},an.prototype.onRemove=function(){s.remove(this._container),this._map.off("sourcedata",this._updateData),this._map.off("moveend",this._updateEditLink),this._map.off("resize",this._updateCompact),this._map=void 0;},an.prototype._updateEditLink=function(){var t=this._editLink;t||(t=this._editLink=this._container.querySelector(".mapbox-improve-map"));var e=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:_.ACCESS_TOKEN}];if(t){var i=e.reduce(function(t,i,n){return i.value&&(t+=i.key+"="+i.value+(n<e.length-1?"&":"")),t},"?");t.href="https://www.mapbox.com/feedback/"+i+(this._map._hash?this._map._hash.getHashString(!0):"");}},an.prototype._updateData=function(t){t&&"metadata"===t.sourceDataType&&(this._updateAttributions(),this._updateEditLink());},an.prototype._updateAttributions=function(){if(this._map.style){var t=[];if(this._map.style.stylesheet){var e=this._map.style.stylesheet;this.styleOwner=e.owner,this.styleId=e.id;}var i=this._map.style.sourceCaches;for(var n in i){var o=i[n].getSource();o.attribution&&t.indexOf(o.attribution)<0&&t.push(o.attribution);}t.sort(function(t,e){return t.length-e.length}),(t=t.filter(function(e,i){for(var n=i+1;n<t.length;n++)if(t[n].indexOf(e)>=0)return!1;return!0})).length?(this._container.innerHTML=t.join(" | "),this._container.classList.remove("mapboxgl-attrib-empty")):this._container.classList.add("mapboxgl-attrib-empty"),this._editLink=null;}},an.prototype._updateCompact=function(){this._map.getCanvasContainer().offsetWidth<=640?this._container.classList.add("mapboxgl-compact"):this._container.classList.remove("mapboxgl-compact");};var sn=function(){t.bindAll(["_updateLogo"],this);};sn.prototype.onAdd=function(t){this._map=t,this._container=s.create("div","mapboxgl-ctrl");var e=s.create("a","mapboxgl-ctrl-logo");return e.target="_blank",e.href="https://www.mapbox.com/",e.setAttribute("aria-label","Mapbox logo"),this._container.appendChild(e),this._container.style.display="none",this._map.on("sourcedata",this._updateLogo),this._updateLogo(),this._container},sn.prototype.onRemove=function(){s.remove(this._container),this._map.off("sourcedata",this._updateLogo);},sn.prototype.getDefaultPosition=function(){return"bottom-left"},sn.prototype._updateLogo=function(t){t&&"metadata"!==t.sourceDataType||(this._container.style.display=this._logoRequired()?"block":"none");},sn.prototype._logoRequired=function(){if(this._map.style){var t=this._map.style.sourceCaches;for(var e in t){if(t[e].getSource().mapbox_logo)return!0}return!1}};var ln=function(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1;};ln.prototype.add=function(t){var e=++this._id;return this._queue.push({callback:t,id:e,cancelled:!1}),e},ln.prototype.remove=function(t){for(var e=this._currentlyRunning,i=0,n=e?this._queue.concat(e):this._queue;i<n.length;i+=1){var o=n[i];if(o.id===t)return void(o.cancelled=!0)}},ln.prototype.run=function(){var t=this._currentlyRunning=this._queue;this._queue=[];for(var e=0,i=t;e<i.length;e+=1){var n=i[e];if(!n.cancelled&&(n.callback(),this._cleared))break}this._cleared=!1,this._currentlyRunning=!1;},ln.prototype.clear=function(){this._currentlyRunning&&(this._cleared=!0),this._queue=[];};var cn=t.default.HTMLImageElement,un=t.default.HTMLElement,hn={center:[0,0],zoom:0,bearing:0,pitch:0,minZoom:0,maxZoom:22,interactive:!0,scrollZoom:!0,boxZoom:!0,dragRotate:!0,dragPan:!0,keyboard:!0,doubleClickZoom:!0,touchZoomRotate:!0,bearingSnap:7,hash:!1,attributionControl:!0,failIfMajorPerformanceCaveat:!1,preserveDrawingBuffer:!1,trackResize:!0,renderWorldCopies:!0,refreshExpiredTiles:!0,maxTileCacheSize:null,transformRequest:null,fadeDuration:300},pn=function(i){function n(e){if(null!=(e=t.extend({},hn,e)).minZoom&&null!=e.maxZoom&&e.minZoom>e.maxZoom)throw new Error("maxZoom must be greater than minZoom");var n=new Ui(e.minZoom,e.maxZoom,e.renderWorldCopies);i.call(this,n,e),this._interactive=e.interactive,this._maxTileCacheSize=e.maxTileCacheSize,this._failIfMajorPerformanceCaveat=e.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=e.preserveDrawingBuffer,this._trackResize=e.trackResize,this._bearingSnap=e.bearingSnap,this._refreshExpiredTiles=e.refreshExpiredTiles,this._fadeDuration=e.fadeDuration,this._crossFadingFactor=1,this._collectResourceTiming=e.collectResourceTiming,this._renderTaskQueue=new ln;var o=e.transformRequest;if(this._transformRequest=o?function(t,e){return o(t,e)||{url:t}}:function(t){return{url:t}},"string"==typeof e.container){var r=t.default.document.getElementById(e.container);if(!r)throw new Error("Container '"+e.container+"' not found.");this._container=r;}else{if(!(e.container instanceof un))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=e.container;}e.maxBounds&&this.setMaxBounds(e.maxBounds),t.bindAll(["_onWindowOnline","_onWindowResize","_contextLost","_contextRestored","_update","_render","_onData","_onDataLoading"],this),this._setupContainer(),this._setupPainter(),this.on("move",this._update.bind(this,!1)),this.on("zoom",this._update.bind(this,!0)),void 0!==t.default&&(t.default.addEventListener("online",this._onWindowOnline,!1),t.default.addEventListener("resize",this._onWindowResize,!1)),function(t,e){var i=t.getCanvasContainer(),n=null,o=!1;for(var r in on)t[r]=new on[r](t,e),e.interactive&&e[r]&&t[r].enable(e[r]);s.addEventListener(i,"mouseout",function(e){t.fire(new ji("mouseout",t,e));}),s.addEventListener(i,"mousedown",function(i){o=!0;var n=new ji("mousedown",t,i);t.fire(n),n.defaultPrevented||(e.interactive&&!t.doubleClickZoom.isActive()&&t.stop(),t.boxZoom.onMouseDown(i),t.boxZoom.isActive()||t.dragPan.isActive()||t.dragRotate.onMouseDown(i),t.boxZoom.isActive()||t.dragRotate.isActive()||t.dragPan.onMouseDown(i));}),s.addEventListener(i,"mouseup",function(e){var i=t.dragRotate.isActive();n&&!i&&t.fire(new ji("contextmenu",t,n)),n=null,o=!1,t.fire(new ji("mouseup",t,e));}),s.addEventListener(i,"mousemove",function(e){if(!t.dragPan.isActive()&&!t.dragRotate.isActive()){for(var n=e.toElement||e.target;n&&n!==i;)n=n.parentNode;n===i&&t.fire(new ji("mousemove",t,e));}}),s.addEventListener(i,"mouseover",function(e){for(var n=e.toElement||e.target;n&&n!==i;)n=n.parentNode;n===i&&t.fire(new ji("mouseover",t,e));}),s.addEventListener(i,"touchstart",function(i){var n=new $i("touchstart",t,i);t.fire(n),n.defaultPrevented||(e.interactive&&t.stop(),t.boxZoom.isActive()||t.dragRotate.isActive()||t.dragPan.onTouchStart(i),t.touchZoomRotate.onStart(i),t.doubleClickZoom.onTouchStart(n));},{passive:!1}),s.addEventListener(i,"touchmove",function(e){t.fire(new $i("touchmove",t,e));},{passive:!1}),s.addEventListener(i,"touchend",function(e){t.fire(new $i("touchend",t,e));}),s.addEventListener(i,"touchcancel",function(e){t.fire(new $i("touchcancel",t,e));}),s.addEventListener(i,"click",function(e){t.fire(new ji("click",t,e));}),s.addEventListener(i,"dblclick",function(e){var i=new ji("dblclick",t,e);t.fire(i),i.defaultPrevented||t.doubleClickZoom.onDblClick(i);}),s.addEventListener(i,"contextmenu",function(e){var i=t.dragRotate.isActive();o||i?o&&(n=e):t.fire(new ji("contextmenu",t,e)),e.preventDefault();}),s.addEventListener(i,"wheel",function(e){var i=new Gi("wheel",t,e);t.fire(i),i.defaultPrevented||t.scrollZoom.onWheel(e);},{passive:!1});}(this,e),this._hash=e.hash&&(new Vi).addTo(this),this._hash&&this._hash._onHashChange()||this.jumpTo({center:e.center,zoom:e.zoom,bearing:e.bearing,pitch:e.pitch}),this.resize(),e.style&&this.setStyle(e.style,{localIdeographFontFamily:e.localIdeographFontFamily}),e.attributionControl&&this.addControl(new an),this.addControl(new sn,e.logoPosition),this.on("style.load",function(){this.transform.unmodified&&this.jumpTo(this.style.stylesheet);}),this.on("data",this._onData),this.on("dataloading",this._onDataLoading);}i&&(n.__proto__=i),n.prototype=Object.create(i&&i.prototype),n.prototype.constructor=n;var o={showTileBoundaries:{configurable:!0},showCollisionBoxes:{configurable:!0},showOverdrawInspector:{configurable:!0},repaint:{configurable:!0},vertices:{configurable:!0}};return n.prototype.addControl=function(t,e){void 0===e&&t.getDefaultPosition&&(e=t.getDefaultPosition()),void 0===e&&(e="top-right");var i=t.onAdd(this),n=this._controlPositions[e];return-1!==e.indexOf("bottom")?n.insertBefore(i,n.firstChild):n.appendChild(i),this},n.prototype.removeControl=function(t){return t.onRemove(this),this},n.prototype.resize=function(e){var i=this._containerDimensions(),n=i[0],o=i[1];return this._resizeCanvas(n,o),this.transform.resize(n,o),this.painter.resize(n,o),this.fire(new t.Event("movestart",e)).fire(new t.Event("move",e)).fire(new t.Event("resize",e)).fire(new t.Event("moveend",e))},n.prototype.getBounds=function(){var e=new q(this.transform.pointLocation(new t.default$1(0,this.transform.height)),this.transform.pointLocation(new t.default$1(this.transform.width,0)));return(this.transform.angle||this.transform.pitch)&&(e.extend(this.transform.pointLocation(new t.default$1(this.transform.size.x,0))),e.extend(this.transform.pointLocation(new t.default$1(0,this.transform.size.y)))),e},n.prototype.getMaxBounds=function(){return this.transform.latRange&&2===this.transform.latRange.length&&this.transform.lngRange&&2===this.transform.lngRange.length?new q([this.transform.lngRange[0],this.transform.latRange[0]],[this.transform.lngRange[1],this.transform.latRange[1]]):null},n.prototype.setMaxBounds=function(t){if(t){var e=q.convert(t);this.transform.lngRange=[e.getWest(),e.getEast()],this.transform.latRange=[e.getSouth(),e.getNorth()],this.transform._constrain(),this._update();}else null==t&&(this.transform.lngRange=null,this.transform.latRange=null,this._update());return this},n.prototype.setMinZoom=function(t){if((t=null==t?0:t)>=0&&t<=this.transform.maxZoom)return this.transform.minZoom=t,this._update(),this.getZoom()<t&&this.setZoom(t),this;throw new Error("minZoom must be between 0 and the current maxZoom, inclusive")},n.prototype.getMinZoom=function(){return this.transform.minZoom},n.prototype.setMaxZoom=function(t){if((t=null==t?22:t)>=this.transform.minZoom)return this.transform.maxZoom=t,this._update(),this.getZoom()>t&&this.setZoom(t),this;throw new Error("maxZoom must be greater than the current minZoom")},n.prototype.getRenderWorldCopies=function(){return this.transform.renderWorldCopies},n.prototype.setRenderWorldCopies=function(t){return this.transform.renderWorldCopies=t,this._update(),this},n.prototype.getMaxZoom=function(){return this.transform.maxZoom},n.prototype.project=function(t){return this.transform.locationPoint(W.convert(t))},n.prototype.unproject=function(e){return this.transform.pointLocation(t.default$1.convert(e))},n.prototype.isMoving=function(){return this._moving||this.dragPan.isActive()||this.dragRotate.isActive()||this.scrollZoom.isActive()},n.prototype.isZooming=function(){return this._zooming||this.scrollZoom.isActive()},n.prototype.isRotating=function(){return this._rotating||this.dragRotate.isActive()},n.prototype.on=function(t,e,n){var o,r=this;if(void 0===n)return i.prototype.on.call(this,t,e);var a=function(){if("mouseenter"===t||"mouseover"===t){var i=!1;return{layer:e,listener:n,delegates:{mousemove:function(o){var a=r.getLayer(e)?r.queryRenderedFeatures(o.point,{layers:[e]}):[];a.length?i||(i=!0,n.call(r,new ji(t,r,o.originalEvent,{features:a}))):i=!1;},mouseout:function(){i=!1;}}}}if("mouseleave"===t||"mouseout"===t){var a=!1;return{layer:e,listener:n,delegates:{mousemove:function(i){(r.getLayer(e)?r.queryRenderedFeatures(i.point,{layers:[e]}):[]).length?a=!0:a&&(a=!1,n.call(r,new ji(t,r,i.originalEvent)));},mouseout:function(e){a&&(a=!1,n.call(r,new ji(t,r,e.originalEvent)));}}}}return{layer:e,listener:n,delegates:(o={},o[t]=function(t){var i=r.getLayer(e)?r.queryRenderedFeatures(t.point,{layers:[e]}):[];i.length&&(t.features=i,n.call(r,t),delete t.features);},o)}}();for(var s in this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[t]=this._delegatedListeners[t]||[],this._delegatedListeners[t].push(a),a.delegates)r.on(s,a.delegates[s]);return this},n.prototype.off=function(t,e,n){if(void 0===n)return i.prototype.off.call(this,t,e);if(this._delegatedListeners&&this._delegatedListeners[t])for(var o=this._delegatedListeners[t],r=0;r<o.length;r++){var a=o[r];if(a.layer===e&&a.listener===n){for(var s in a.delegates)this.off(s,a.delegates[s]);return o.splice(r,1),this}}return this},n.prototype.queryRenderedFeatures=function(e,i){var n;return 2===arguments.length?(e=arguments[0],i=arguments[1]):1===arguments.length&&((n=arguments[0])instanceof t.default$1||Array.isArray(n))?(e=arguments[0],i={}):1===arguments.length?(e=void 0,i=arguments[0]):(e=void 0,i={}),this.style?this.style.queryRenderedFeatures(this._makeQueryGeometry(e),i,this.transform):[]},n.prototype._makeQueryGeometry=function(e){var i,n=this;if(void 0===e&&(e=[t.default$1.convert([0,0]),t.default$1.convert([this.transform.width,this.transform.height])]),e instanceof t.default$1||"number"==typeof e[0]){i=[t.default$1.convert(e)];}else{var o=[t.default$1.convert(e[0]),t.default$1.convert(e[1])];i=[o[0],new t.default$1(o[1].x,o[0].y),o[1],new t.default$1(o[0].x,o[1].y),o[0]];}return{viewport:i,worldCoordinate:i.map(function(t){return n.transform.pointCoordinate(t)})}},n.prototype.querySourceFeatures=function(t,e){return this.style.querySourceFeatures(t,e)},n.prototype.setStyle=function(e,i){if((!i||!1!==i.diff&&!i.localIdeographFontFamily)&&this.style&&e&&"object"==typeof e)try{return this.style.setState(e)&&this._update(!0),this}catch(e){t.warnOnce("Unable to perform style diff: "+(e.message||e.error||e)+".  Rebuilding the style from scratch.");}return this.style&&(this.style.setEventedParent(null),this.style._remove()),e?(this.style=new Qe(this,i||{}),this.style.setEventedParent(this,{style:this.style}),"string"==typeof e?this.style.loadURL(e):this.style.loadJSON(e),this):(delete this.style,this)},n.prototype.getStyle=function(){if(this.style)return this.style.serialize()},n.prototype.isStyleLoaded=function(){return this.style?this.style.loaded():t.warnOnce("There is no style added to the map.")},n.prototype.addSource=function(t,e){return this.style.addSource(t,e),this._update(!0),this},n.prototype.isSourceLoaded=function(e){var i=this.style&&this.style.sourceCaches[e];if(void 0!==i)return i.loaded();this.fire(new t.ErrorEvent(new Error("There is no source with ID '"+e+"'")));},n.prototype.areTilesLoaded=function(){var t=this.style&&this.style.sourceCaches;for(var e in t){var i=t[e]._tiles;for(var n in i){var o=i[n];if("loaded"!==o.state&&"errored"!==o.state)return!1}}return!0},n.prototype.addSourceType=function(t,e,i){return this.style.addSourceType(t,e,i)},n.prototype.removeSource=function(t){return this.style.removeSource(t),this._update(!0),this},n.prototype.getSource=function(t){return this.style.getSource(t)},n.prototype.addImage=function(e,i,n){void 0===n&&(n={});var o=n.pixelRatio;void 0===o&&(o=1);var a=n.sdf;if(void 0===a&&(a=!1),i instanceof cn){var s=r.getImageData(i),l=s.width,c=s.height,u=s.data;this.style.addImage(e,{data:new t.RGBAImage({width:l,height:c},u),pixelRatio:o,sdf:a});}else{if(void 0===i.width||void 0===i.height)return this.fire(new t.ErrorEvent(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));var h=i.width,p=i.height,d=i.data;this.style.addImage(e,{data:new t.RGBAImage({width:h,height:p},d.slice(0)),pixelRatio:o,sdf:a});}},n.prototype.hasImage=function(e){return e?!!this.style.getImage(e):(this.fire(new t.ErrorEvent(new Error("Missing required image id"))),!1)},n.prototype.removeImage=function(t){this.style.removeImage(t);},n.prototype.loadImage=function(e,i){t.getImage(this._transformRequest(e,t.ResourceType.Image),i);},n.prototype.addLayer=function(t,e){return this.style.addLayer(t,e),this._update(!0),this},n.prototype.moveLayer=function(t,e){return this.style.moveLayer(t,e),this._update(!0),this},n.prototype.removeLayer=function(t){return this.style.removeLayer(t),this._update(!0),this},n.prototype.getLayer=function(t){return this.style.getLayer(t)},n.prototype.setFilter=function(t,e){return this.style.setFilter(t,e),this._update(!0),this},n.prototype.setLayerZoomRange=function(t,e,i){return this.style.setLayerZoomRange(t,e,i),this._update(!0),this},n.prototype.getFilter=function(t){return this.style.getFilter(t)},n.prototype.setPaintProperty=function(t,e,i){return this.style.setPaintProperty(t,e,i),this._update(!0),this},n.prototype.getPaintProperty=function(t,e){return this.style.getPaintProperty(t,e)},n.prototype.setLayoutProperty=function(t,e,i){return this.style.setLayoutProperty(t,e,i),this._update(!0),this},n.prototype.getLayoutProperty=function(t,e){return this.style.getLayoutProperty(t,e)},n.prototype.setLight=function(t){return this.style.setLight(t),this._update(!0),this},n.prototype.getLight=function(){return this.style.getLight()},n.prototype.getContainer=function(){return this._container},n.prototype.getCanvasContainer=function(){return this._canvasContainer},n.prototype.getCanvas=function(){return this._canvas},n.prototype._containerDimensions=function(){var t=0,e=0;return this._container&&(t=this._container.offsetWidth||400,e=this._container.offsetHeight||300),[t,e]},n.prototype._setupContainer=function(){var t=this._container;t.classList.add("mapboxgl-map"),(this._missingCSSContainer=s.create("div","mapboxgl-missing-css",t)).innerHTML="Missing Mapbox GL JS CSS";var e=this._canvasContainer=s.create("div","mapboxgl-canvas-container",t);this._interactive&&e.classList.add("mapboxgl-interactive"),this._canvas=s.create("canvas","mapboxgl-canvas",e),this._canvas.style.position="absolute",this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("tabindex","0"),this._canvas.setAttribute("aria-label","Map");var i=this._containerDimensions();this._resizeCanvas(i[0],i[1]);var n=this._controlContainer=s.create("div","mapboxgl-control-container",t),o=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach(function(t){o[t]=s.create("div","mapboxgl-ctrl-"+t,n);});},n.prototype._resizeCanvas=function(e,i){var n=t.default.devicePixelRatio||1;this._canvas.width=n*e,this._canvas.height=n*i,this._canvas.style.width=e+"px",this._canvas.style.height=i+"px";},n.prototype._setupPainter=function(){var i=t.extend({failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer},e.webGLContextAttributes),n=this._canvas.getContext("webgl",i)||this._canvas.getContext("experimental-webgl",i);n?this.painter=new Li(n,this.transform):this.fire(new t.ErrorEvent(new Error("Failed to initialize WebGL")));},n.prototype._contextLost=function(e){e.preventDefault(),this._frameId&&(r.cancelFrame(this._frameId),this._frameId=null),this.fire(new t.Event("webglcontextlost",{originalEvent:e}));},n.prototype._contextRestored=function(e){this._setupPainter(),this.resize(),this._update(),this.fire(new t.Event("webglcontextrestored",{originalEvent:e}));},n.prototype.loaded=function(){return!this._styleDirty&&!this._sourcesDirty&&!(!this.style||!this.style.loaded())},n.prototype._update=function(t){this.style&&(this._styleDirty=this._styleDirty||t,this._sourcesDirty=!0,this._rerender());},n.prototype._requestRenderFrame=function(t){return this._update(),this._renderTaskQueue.add(t)},n.prototype._cancelRenderFrame=function(t){this._renderTaskQueue.remove(t);},n.prototype._render=function(){this._renderTaskQueue.run();var e=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;var i=this.transform.zoom,n=r.now();this.style.zoomHistory.update(i,n);var o=new t.default$16(i,{now:n,fadeDuration:this._fadeDuration,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),a=o.crossFadingFactor();1===a&&a===this._crossFadingFactor||(e=!0,this._crossFadingFactor=a),this.style.update(o);}return this.style&&this._sourcesDirty&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this._placementDirty=this.style&&this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,this._fadeDuration),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),fadeDuration:this._fadeDuration}),this.fire(new t.Event("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,this.fire(new t.Event("load"))),this.style&&(this.style.hasTransitions()||e)&&(this._styleDirty=!0),(this._sourcesDirty||this._repaint||this._styleDirty||this._placementDirty)&&this._rerender(),this},n.prototype.remove=function(){this._hash&&this._hash.remove(),r.cancelFrame(this._frameId),this._renderTaskQueue.clear(),this._frameId=null,this.setStyle(null),void 0!==t.default&&(t.default.removeEventListener("resize",this._onWindowResize,!1),t.default.removeEventListener("online",this._onWindowOnline,!1));var e=this.painter.context.gl.getExtension("WEBGL_lose_context");e&&e.loseContext(),dn(this._canvasContainer),dn(this._controlContainer),dn(this._missingCSSContainer),this._container.classList.remove("mapboxgl-map"),this.fire(new t.Event("remove"));},n.prototype._rerender=function(){var t=this;this.style&&!this._frameId&&(this._frameId=r.frame(function(){t._frameId=null,t._render();}));},n.prototype._onWindowOnline=function(){this._update();},n.prototype._onWindowResize=function(){this._trackResize&&this.stop().resize()._update();},o.showTileBoundaries.get=function(){return!!this._showTileBoundaries},o.showTileBoundaries.set=function(t){this._showTileBoundaries!==t&&(this._showTileBoundaries=t,this._update());},o.showCollisionBoxes.get=function(){return!!this._showCollisionBoxes},o.showCollisionBoxes.set=function(t){this._showCollisionBoxes!==t&&(this._showCollisionBoxes=t,t?this.style._generateCollisionBoxes():this._update());},o.showOverdrawInspector.get=function(){return!!this._showOverdrawInspector},o.showOverdrawInspector.set=function(t){this._showOverdrawInspector!==t&&(this._showOverdrawInspector=t,this._update());},o.repaint.get=function(){return!!this._repaint},o.repaint.set=function(t){this._repaint=t,this._update();},o.vertices.get=function(){return!!this._vertices},o.vertices.set=function(t){this._vertices=t,this._update();},n.prototype._onData=function(e){this._update("style"===e.dataType),this.fire(new t.Event(e.dataType+"data",e));},n.prototype._onDataLoading=function(e){this.fire(new t.Event(e.dataType+"dataloading",e));},Object.defineProperties(n.prototype,o),n}(rn);function dn(t){t.parentNode&&t.parentNode.removeChild(t);}var fn={showCompass:!0,showZoom:!0},mn=function(e){var i=this;this.options=t.extend({},fn,e),this._container=s.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",function(t){return t.preventDefault()}),this.options.showZoom&&(this._zoomInButton=this._createButton("mapboxgl-ctrl-icon mapboxgl-ctrl-zoom-in","Zoom In",function(){return i._map.zoomIn()}),this._zoomOutButton=this._createButton("mapboxgl-ctrl-icon mapboxgl-ctrl-zoom-out","Zoom Out",function(){return i._map.zoomOut()})),this.options.showCompass&&(t.bindAll(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-icon mapboxgl-ctrl-compass","Reset North",function(){return i._map.resetNorth()}),this._compassArrow=s.create("span","mapboxgl-ctrl-compass-arrow",this._compass));};function _n(t,e,i){if(t=new W(t.lng,t.lat),e){var n=new W(t.lng-360,t.lat),o=new W(t.lng+360,t.lat),r=i.locationPoint(t).distSqr(e);i.locationPoint(n).distSqr(e)<r?t=n:i.locationPoint(o).distSqr(e)<r&&(t=o);}for(;Math.abs(t.lng-i.center.lng)>180;){var a=i.locationPoint(t);if(a.x>=0&&a.y>=0&&a.x<=i.width&&a.y<=i.height)break;t.lng>i.center.lng?t.lng-=360:t.lng+=360;}return t}mn.prototype._rotateCompassArrow=function(){var t="rotate("+this._map.transform.angle*(180/Math.PI)+"deg)";this._compassArrow.style.transform=t;},mn.prototype.onAdd=function(t){return this._map=t,this.options.showCompass&&(this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new Hi(t,{button:"left",element:this._compass}),this._handler.enable()),this._container},mn.prototype.onRemove=function(){s.remove(this._container),this.options.showCompass&&(this._map.off("rotate",this._rotateCompassArrow),this._handler.disable(),delete this._handler),delete this._map;},mn.prototype._createButton=function(t,e,i){var n=s.create("button",t,this._container);return n.type="button",n.setAttribute("aria-label",e),n.addEventListener("click",i),n};var gn={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function vn(t,e,i){var n=t.classList;for(var o in gn)n.remove("mapboxgl-"+i+"-anchor-"+o);n.add("mapboxgl-"+i+"-anchor-"+e);}var yn=function(e){if((arguments[0]instanceof t.default.HTMLElement||2===arguments.length)&&(e=t.extend({element:e},arguments[1])),t.bindAll(["_update","_onMapClick"],this),this._anchor=e&&e.anchor||"center",this._color=e&&e.color||"#3FB1CE",e&&e.element)this._element=e.element,this._offset=t.default$1.convert(e&&e.offset||[0,0]);else{this._defaultMarker=!0,this._element=s.create("div");var i=s.createNS("http://www.w3.org/2000/svg","svg");i.setAttributeNS(null,"height","41px"),i.setAttributeNS(null,"width","27px"),i.setAttributeNS(null,"viewBox","0 0 27 41");var n=s.createNS("http://www.w3.org/2000/svg","g");n.setAttributeNS(null,"stroke","none"),n.setAttributeNS(null,"stroke-width","1"),n.setAttributeNS(null,"fill","none"),n.setAttributeNS(null,"fill-rule","evenodd");var o=s.createNS("http://www.w3.org/2000/svg","g");o.setAttributeNS(null,"fill-rule","nonzero");var r=s.createNS("http://www.w3.org/2000/svg","g");r.setAttributeNS(null,"transform","translate(3.0, 29.0)"),r.setAttributeNS(null,"fill","#000000");for(var a=0,l=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];a<l.length;a+=1){var c=l[a],u=s.createNS("http://www.w3.org/2000/svg","ellipse");u.setAttributeNS(null,"opacity","0.04"),u.setAttributeNS(null,"cx","10.5"),u.setAttributeNS(null,"cy","5.80029008"),u.setAttributeNS(null,"rx",c.rx),u.setAttributeNS(null,"ry",c.ry),r.appendChild(u);}var h=s.createNS("http://www.w3.org/2000/svg","g");h.setAttributeNS(null,"fill",this._color);var p=s.createNS("http://www.w3.org/2000/svg","path");p.setAttributeNS(null,"d","M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z"),h.appendChild(p);var d=s.createNS("http://www.w3.org/2000/svg","g");d.setAttributeNS(null,"opacity","0.25"),d.setAttributeNS(null,"fill","#000000");var f=s.createNS("http://www.w3.org/2000/svg","path");f.setAttributeNS(null,"d","M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z"),d.appendChild(f);var m=s.createNS("http://www.w3.org/2000/svg","g");m.setAttributeNS(null,"transform","translate(6.0, 7.0)"),m.setAttributeNS(null,"fill","#FFFFFF");var _=s.createNS("http://www.w3.org/2000/svg","g");_.setAttributeNS(null,"transform","translate(8.0, 8.0)");var g=s.createNS("http://www.w3.org/2000/svg","circle");g.setAttributeNS(null,"fill","#000000"),g.setAttributeNS(null,"opacity","0.25"),g.setAttributeNS(null,"cx","5.5"),g.setAttributeNS(null,"cy","5.5"),g.setAttributeNS(null,"r","5.4999962");var v=s.createNS("http://www.w3.org/2000/svg","circle");v.setAttributeNS(null,"fill","#FFFFFF"),v.setAttributeNS(null,"cx","5.5"),v.setAttributeNS(null,"cy","5.5"),v.setAttributeNS(null,"r","5.4999962"),_.appendChild(g),_.appendChild(v),o.appendChild(r),o.appendChild(h),o.appendChild(d),o.appendChild(m),o.appendChild(_),i.appendChild(o),this._element.appendChild(i),this._offset=t.default$1.convert(e&&e.offset||[0,-14]);}this._element.classList.add("mapboxgl-marker"),this._popup=null;};yn.prototype.addTo=function(t){return this.remove(),this._map=t,t.getCanvasContainer().appendChild(this._element),t.on("move",this._update),t.on("moveend",this._update),this._update(),this._map.on("click",this._onMapClick),this},yn.prototype.remove=function(){return this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),delete this._map),s.remove(this._element),this._popup&&this._popup.remove(),this},yn.prototype.getLngLat=function(){return this._lngLat},yn.prototype.setLngLat=function(t){return this._lngLat=W.convert(t),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this},yn.prototype.getElement=function(){return this._element},yn.prototype.setPopup=function(t){if(this._popup&&(this._popup.remove(),this._popup=null),t){if(!("offset"in t.options)){var e=Math.sqrt(Math.pow(13.5,2)/2);t.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[e,-1*(24.6+e)],"bottom-right":[-e,-1*(24.6+e)],left:[13.5,-24.6],right:[-13.5,-24.6]}:this._offset;}this._popup=t,this._lngLat&&this._popup.setLngLat(this._lngLat);}return this},yn.prototype._onMapClick=function(t){var e=t.originalEvent.target,i=this._element;this._popup&&(e===i||i.contains(e))&&this.togglePopup();},yn.prototype.getPopup=function(){return this._popup},yn.prototype.togglePopup=function(){var t=this._popup;return t?(t.isOpen()?t.remove():t.addTo(this._map),this):this},yn.prototype._update=function(t){this._map&&(this._map.transform.renderWorldCopies&&(this._lngLat=_n(this._lngLat,this._pos,this._map.transform)),this._pos=this._map.project(this._lngLat)._add(this._offset),t&&"moveend"!==t.type||(this._pos=this._pos.round()),s.setTransform(this._element,gn[this._anchor]+" translate("+this._pos.x+"px, "+this._pos.y+"px)"),vn(this._element,this._anchor,"marker"));},yn.prototype.getOffset=function(){return this._offset},yn.prototype.setOffset=function(e){return this._offset=t.default$1.convert(e),this._update(),this};var xn,bn={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showUserLocation:!0};var wn=function(e){function i(i){e.call(this),this.options=t.extend({},bn,i),t.bindAll(["_onSuccess","_onError","_finish","_setupUI","_updateCamera","_updateMarker"],this);}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.onAdd=function(e){var i;return this._map=e,this._container=s.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),i=this._setupUI,void 0!==xn?i(xn):void 0!==t.default.navigator.permissions?t.default.navigator.permissions.query({name:"geolocation"}).then(function(t){xn="denied"!==t.state,i(xn);}):(xn=!!t.default.navigator.geolocation,i(xn)),this._container},i.prototype.onRemove=function(){void 0!==this._geolocationWatchID&&(t.default.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker.remove(),s.remove(this._container),this._map=void 0;},i.prototype._onSuccess=function(e){if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove("mapboxgl-user-location-dot-stale"),this.fire(new t.Event("geolocate",e)),this._finish();},i.prototype._updateCamera=function(t){var e=new W(t.coords.longitude,t.coords.latitude),i=t.coords.accuracy;this._map.fitBounds(e.toBounds(i),this.options.fitBoundsOptions,{geolocateSource:!0});},i.prototype._updateMarker=function(t){t?this._userLocationDotMarker.setLngLat([t.coords.longitude,t.coords.latitude]).addTo(this._map):this._userLocationDotMarker.remove();},i.prototype._onError=function(e){if(this.options.trackUserLocation)if(1===e.code)this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),void 0!==this._geolocationWatchID&&this._clearWatch();else switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("mapboxgl-user-location-dot-stale"),this.fire(new t.Event("error",e)),this._finish();},i.prototype._finish=function(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0;},i.prototype._setupUI=function(e){var i=this;!1!==e&&(this._container.addEventListener("contextmenu",function(t){return t.preventDefault()}),this._geolocateButton=s.create("button","mapboxgl-ctrl-icon mapboxgl-ctrl-geolocate",this._container),this._geolocateButton.type="button",this._geolocateButton.setAttribute("aria-label","Geolocate"),this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=s.create("div","mapboxgl-user-location-dot"),this._userLocationDotMarker=new yn(this._dotElement),this.options.trackUserLocation&&(this._watchState="OFF")),this._geolocateButton.addEventListener("click",this.trigger.bind(this)),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",function(e){e.geolocateSource||"ACTIVE_LOCK"!==i._watchState||(i._watchState="BACKGROUND",i._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),i._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),i.fire(new t.Event("trackuserlocationend")));}));},i.prototype.trigger=function(){if(!this._setup)return t.warnOnce("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new t.Event("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this.fire(new t.Event("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new t.Event("trackuserlocationstart"));}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"BACKGROUND":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");break;case"BACKGROUND_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error");}"OFF"===this._watchState&&void 0!==this._geolocationWatchID?this._clearWatch():void 0===this._geolocationWatchID&&(this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),this._geolocationWatchID=t.default.navigator.geolocation.watchPosition(this._onSuccess,this._onError,this.options.positionOptions));}else t.default.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return!0},i.prototype._clearWatch=function(){t.default.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null);},i}(t.Evented),En={maxWidth:100,unit:"metric"},Tn=function(e){this.options=t.extend({},En,e),t.bindAll(["_onMove","setUnit"],this);};function In(t,e,i){var n,o,r,a,s,l,c=i&&i.maxWidth||100,u=t._container.clientHeight/2,h=(n=t.unproject([0,u]),o=t.unproject([c,u]),r=Math.PI/180,a=n.lat*r,s=o.lat*r,l=Math.sin(a)*Math.sin(s)+Math.cos(a)*Math.cos(s)*Math.cos((o.lng-n.lng)*r),6371e3*Math.acos(Math.min(l,1)));if(i&&"imperial"===i.unit){var p=3.2808*h;if(p>5280)Cn(e,c,p/5280,"mi");else Cn(e,c,p,"ft");}else if(i&&"nautical"===i.unit){Cn(e,c,h/1852,"nm");}else Cn(e,c,h,"m");}function Cn(t,e,i,n){var o,r,a,s=(o=i,(r=Math.pow(10,(""+Math.floor(o)).length-1))*(a=(a=o/r)>=10?10:a>=5?5:a>=3?3:a>=2?2:1)),l=s/i;"m"===n&&s>=1e3&&(s/=1e3,n="km"),t.style.width=e*l+"px",t.innerHTML=s+n;}Tn.prototype.getDefaultPosition=function(){return"bottom-left"},Tn.prototype._onMove=function(){In(this._map,this._container,this.options);},Tn.prototype.onAdd=function(t){return this._map=t,this._container=s.create("div","mapboxgl-ctrl mapboxgl-ctrl-scale",t.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container},Tn.prototype.onRemove=function(){s.remove(this._container),this._map.off("move",this._onMove),this._map=void 0;},Tn.prototype.setUnit=function(t){this.options.unit=t,In(this._map,this._container,this.options);};var Sn=function(){this._fullscreen=!1,t.bindAll(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in t.default.document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in t.default.document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in t.default.document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in t.default.document&&(this._fullscreenchange="MSFullscreenChange"),this._className="mapboxgl-ctrl";};Sn.prototype.onAdd=function(e){return this._map=e,this._mapContainer=this._map.getContainer(),this._container=s.create("div",this._className+" mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._container.style.display="none",t.warnOnce("This device does not support fullscreen mode.")),this._container},Sn.prototype.onRemove=function(){s.remove(this._container),this._map=null,t.default.document.removeEventListener(this._fullscreenchange,this._changeIcon);},Sn.prototype._checkFullscreenSupport=function(){return!!(t.default.document.fullscreenEnabled||t.default.document.mozFullScreenEnabled||t.default.document.msFullscreenEnabled||t.default.document.webkitFullscreenEnabled)},Sn.prototype._setupUI=function(){var e=this._fullscreenButton=s.create("button",this._className+"-icon "+this._className+"-fullscreen",this._container);e.setAttribute("aria-label","Toggle fullscreen"),e.type="button",this._fullscreenButton.addEventListener("click",this._onClickFullscreen),t.default.document.addEventListener(this._fullscreenchange,this._changeIcon);},Sn.prototype._isFullscreen=function(){return this._fullscreen},Sn.prototype._changeIcon=function(){(t.default.document.fullscreenElement||t.default.document.mozFullScreenElement||t.default.document.webkitFullscreenElement||t.default.document.msFullscreenElement)===this._mapContainer!==this._fullscreen&&(this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle(this._className+"-shrink"),this._fullscreenButton.classList.toggle(this._className+"-fullscreen"));},Sn.prototype._onClickFullscreen=function(){this._isFullscreen()?t.default.document.exitFullscreen?t.default.document.exitFullscreen():t.default.document.mozCancelFullScreen?t.default.document.mozCancelFullScreen():t.default.document.msExitFullscreen?t.default.document.msExitFullscreen():t.default.document.webkitCancelFullScreen&&t.default.document.webkitCancelFullScreen():this._mapContainer.requestFullscreen?this._mapContainer.requestFullscreen():this._mapContainer.mozRequestFullScreen?this._mapContainer.mozRequestFullScreen():this._mapContainer.msRequestFullscreen?this._mapContainer.msRequestFullscreen():this._mapContainer.webkitRequestFullscreen&&this._mapContainer.webkitRequestFullscreen();};var zn={closeButton:!0,closeOnClick:!0},An=function(e){function i(i){e.call(this),this.options=t.extend(Object.create(zn),i),t.bindAll(["_update","_onClickClose"],this);}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.addTo=function(e){return this._map=e,this._map.on("move",this._update),this.options.closeOnClick&&this._map.on("click",this._onClickClose),this._update(),this.fire(new t.Event("open")),this},i.prototype.isOpen=function(){return!!this._map},i.prototype.remove=function(){return this._content&&s.remove(this._content),this._container&&(s.remove(this._container),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("click",this._onClickClose),delete this._map),this.fire(new t.Event("close")),this},i.prototype.getLngLat=function(){return this._lngLat},i.prototype.setLngLat=function(t){return this._lngLat=W.convert(t),this._pos=null,this._update(),this},i.prototype.setText=function(e){return this.setDOMContent(t.default.document.createTextNode(e))},i.prototype.setHTML=function(e){var i,n=t.default.document.createDocumentFragment(),o=t.default.document.createElement("body");for(o.innerHTML=e;i=o.firstChild;)n.appendChild(i);return this.setDOMContent(n)},i.prototype.setDOMContent=function(t){return this._createContent(),this._content.appendChild(t),this._update(),this},i.prototype._createContent=function(){this._content&&s.remove(this._content),this._content=s.create("div","mapboxgl-popup-content",this._container),this.options.closeButton&&(this._closeButton=s.create("button","mapboxgl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.setAttribute("aria-label","Close popup"),this._closeButton.innerHTML="&#215;",this._closeButton.addEventListener("click",this._onClickClose));},i.prototype._update=function(){if(this._map&&this._lngLat&&this._content){this._container||(this._container=s.create("div","mapboxgl-popup",this._map.getContainer()),this._tip=s.create("div","mapboxgl-popup-tip",this._container),this._container.appendChild(this._content)),this._map.transform.renderWorldCopies&&(this._lngLat=_n(this._lngLat,this._pos,this._map.transform));var e=this._pos=this._map.project(this._lngLat),i=this.options.anchor,n=function e(i){if(i){if("number"==typeof i){var n=Math.round(Math.sqrt(.5*Math.pow(i,2)));return{center:new t.default$1(0,0),top:new t.default$1(0,i),"top-left":new t.default$1(n,n),"top-right":new t.default$1(-n,n),bottom:new t.default$1(0,-i),"bottom-left":new t.default$1(n,-n),"bottom-right":new t.default$1(-n,-n),left:new t.default$1(i,0),right:new t.default$1(-i,0)}}if(i instanceof t.default$1||Array.isArray(i)){var o=t.default$1.convert(i);return{center:o,top:o,"top-left":o,"top-right":o,bottom:o,"bottom-left":o,"bottom-right":o,left:o,right:o}}return{center:t.default$1.convert(i.center||[0,0]),top:t.default$1.convert(i.top||[0,0]),"top-left":t.default$1.convert(i["top-left"]||[0,0]),"top-right":t.default$1.convert(i["top-right"]||[0,0]),bottom:t.default$1.convert(i.bottom||[0,0]),"bottom-left":t.default$1.convert(i["bottom-left"]||[0,0]),"bottom-right":t.default$1.convert(i["bottom-right"]||[0,0]),left:t.default$1.convert(i.left||[0,0]),right:t.default$1.convert(i.right||[0,0])}}return e(new t.default$1(0,0))}(this.options.offset);if(!i){var o,r=this._container.offsetWidth,a=this._container.offsetHeight;o=e.y+n.bottom.y<a?["top"]:e.y>this._map.transform.height-a?["bottom"]:[],e.x<r/2?o.push("left"):e.x>this._map.transform.width-r/2&&o.push("right"),i=0===o.length?"bottom":o.join("-");}var l=e.add(n[i]).round();s.setTransform(this._container,gn[i]+" translate("+l.x+"px,"+l.y+"px)"),vn(this._container,i,"popup");}},i.prototype._onClickClose=function(){this.remove();},i}(t.Evented);var Rn={version:"0.45.0",supported:e,workerCount:Math.max(Math.floor(r.hardwareConcurrency/2),1),setRTLTextPlugin:t.setRTLTextPlugin,Map:pn,NavigationControl:mn,GeolocateControl:wn,AttributionControl:an,ScaleControl:Tn,FullscreenControl:Sn,Popup:An,Marker:yn,Style:Qe,LngLat:W,LngLatBounds:q,Point:t.default$1,Evented:t.Evented,config:_,get accessToken(){return _.ACCESS_TOKEN},set accessToken(t){_.ACCESS_TOKEN=t;},workerUrl:""};return Rn});

//

return mapboxgl;

})));


}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],416:[function(_dereq_,module,exports){
'use strict'

module.exports = createTable

var chull = _dereq_('convex-hull')

function constructVertex(d, a, b) {
  var x = new Array(d)
  for(var i=0; i<d; ++i) {
    x[i] = 0.0
    if(i === a) {
      x[i] += 0.5
    }
    if(i === b) {
      x[i] += 0.5
    }
  }
  return x
}

function constructCell(dimension, mask) {
  if(mask === 0 || mask === (1<<(dimension+1))-1) {
    return []
  }
  var points = []
  var index  = []
  for(var i=0; i<=dimension; ++i) {
    if(mask & (1<<i)) {
      points.push(constructVertex(dimension, i-1, i-1))
      index.push(null)
      for(var j=0; j<=dimension; ++j) {
        if(~mask & (1<<j)) {
          points.push(constructVertex(dimension, i-1, j-1))
          index.push([i,j])
        }
      }
    }
  }
  
  //Preprocess points so first d+1 points are linearly independent
  var hull = chull(points)
  var faces = []
i_loop:
  for(var i=0; i<hull.length; ++i) {
    var face = hull[i]
    var nface = []
    for(var j=0; j<face.length; ++j) {
      if(!index[face[j]]) {
        continue i_loop
      }
      nface.push(index[face[j]].slice())
    }
    faces.push(nface)
  }
  return faces
}

function createTable(dimension) {
  var numCells = 1<<(dimension+1)
  var result = new Array(numCells)
  for(var i=0; i<numCells; ++i) {
    result[i] = constructCell(dimension, i)
  }
  return result
}
},{"convex-hull":118}],417:[function(_dereq_,module,exports){
/*jshint unused:true*/
/*
Input:  matrix      ; a 4x4 matrix
Output: translation ; a 3 component vector
        scale       ; a 3 component vector
        skew        ; skew factors XY,XZ,YZ represented as a 3 component vector
        perspective ; a 4 component vector
        quaternion  ; a 4 component vector
Returns false if the matrix cannot be decomposed, true if it can


References:
https://github.com/kamicane/matrix3d/blob/master/lib/Matrix3d.js
https://github.com/ChromiumWebApps/chromium/blob/master/ui/gfx/transform_util.cc
http://www.w3.org/TR/css3-transforms/#decomposing-a-3d-matrix
*/

var normalize = _dereq_('./normalize')

var create = _dereq_('gl-mat4/create')
var clone = _dereq_('gl-mat4/clone')
var determinant = _dereq_('gl-mat4/determinant')
var invert = _dereq_('gl-mat4/invert')
var transpose = _dereq_('gl-mat4/transpose')
var vec3 = {
    length: _dereq_('gl-vec3/length'),
    normalize: _dereq_('gl-vec3/normalize'),
    dot: _dereq_('gl-vec3/dot'),
    cross: _dereq_('gl-vec3/cross')
}

var tmp = create()
var perspectiveMatrix = create()
var tmpVec4 = [0, 0, 0, 0]
var row = [ [0,0,0], [0,0,0], [0,0,0] ]
var pdum3 = [0,0,0]

module.exports = function decomposeMat4(matrix, translation, scale, skew, perspective, quaternion) {
    if (!translation) translation = [0,0,0]
    if (!scale) scale = [0,0,0]
    if (!skew) skew = [0,0,0]
    if (!perspective) perspective = [0,0,0,1]
    if (!quaternion) quaternion = [0,0,0,1]

    //normalize, if not possible then bail out early
    if (!normalize(tmp, matrix))
        return false

    // perspectiveMatrix is used to solve for perspective, but it also provides
    // an easy way to test for singularity of the upper 3x3 component.
    clone(perspectiveMatrix, tmp)

    perspectiveMatrix[3] = 0
    perspectiveMatrix[7] = 0
    perspectiveMatrix[11] = 0
    perspectiveMatrix[15] = 1

    // If the perspectiveMatrix is not invertible, we are also unable to
    // decompose, so we'll bail early. Constant taken from SkMatrix44::invert.
    if (Math.abs(determinant(perspectiveMatrix) < 1e-8))
        return false

    var a03 = tmp[3], a13 = tmp[7], a23 = tmp[11],
            a30 = tmp[12], a31 = tmp[13], a32 = tmp[14], a33 = tmp[15]

    // First, isolate perspective.
    if (a03 !== 0 || a13 !== 0 || a23 !== 0) {
        tmpVec4[0] = a03
        tmpVec4[1] = a13
        tmpVec4[2] = a23
        tmpVec4[3] = a33

        // Solve the equation by inverting perspectiveMatrix and multiplying
        // rightHandSide by the inverse.
        // resuing the perspectiveMatrix here since it's no longer needed
        var ret = invert(perspectiveMatrix, perspectiveMatrix)
        if (!ret) return false
        transpose(perspectiveMatrix, perspectiveMatrix)

        //multiply by transposed inverse perspective matrix, into perspective vec4
        vec4multMat4(perspective, tmpVec4, perspectiveMatrix)
    } else { 
        //no perspective
        perspective[0] = perspective[1] = perspective[2] = 0
        perspective[3] = 1
    }

    // Next take care of translation
    translation[0] = a30
    translation[1] = a31
    translation[2] = a32

    // Now get scale and shear. 'row' is a 3 element array of 3 component vectors
    mat3from4(row, tmp)

    // Compute X scale factor and normalize first row.
    scale[0] = vec3.length(row[0])
    vec3.normalize(row[0], row[0])

    // Compute XY shear factor and make 2nd row orthogonal to 1st.
    skew[0] = vec3.dot(row[0], row[1])
    combine(row[1], row[1], row[0], 1.0, -skew[0])

    // Now, compute Y scale and normalize 2nd row.
    scale[1] = vec3.length(row[1])
    vec3.normalize(row[1], row[1])
    skew[0] /= scale[1]

    // Compute XZ and YZ shears, orthogonalize 3rd row
    skew[1] = vec3.dot(row[0], row[2])
    combine(row[2], row[2], row[0], 1.0, -skew[1])
    skew[2] = vec3.dot(row[1], row[2])
    combine(row[2], row[2], row[1], 1.0, -skew[2])

    // Next, get Z scale and normalize 3rd row.
    scale[2] = vec3.length(row[2])
    vec3.normalize(row[2], row[2])
    skew[1] /= scale[2]
    skew[2] /= scale[2]


    // At this point, the matrix (in rows) is orthonormal.
    // Check for a coordinate system flip.  If the determinant
    // is -1, then negate the matrix and the scaling factors.
    vec3.cross(pdum3, row[1], row[2])
    if (vec3.dot(row[0], pdum3) < 0) {
        for (var i = 0; i < 3; i++) {
            scale[i] *= -1;
            row[i][0] *= -1
            row[i][1] *= -1
            row[i][2] *= -1
        }
    }

    // Now, get the rotations out
    quaternion[0] = 0.5 * Math.sqrt(Math.max(1 + row[0][0] - row[1][1] - row[2][2], 0))
    quaternion[1] = 0.5 * Math.sqrt(Math.max(1 - row[0][0] + row[1][1] - row[2][2], 0))
    quaternion[2] = 0.5 * Math.sqrt(Math.max(1 - row[0][0] - row[1][1] + row[2][2], 0))
    quaternion[3] = 0.5 * Math.sqrt(Math.max(1 + row[0][0] + row[1][1] + row[2][2], 0))

    if (row[2][1] > row[1][2])
        quaternion[0] = -quaternion[0]
    if (row[0][2] > row[2][0])
        quaternion[1] = -quaternion[1]
    if (row[1][0] > row[0][1])
        quaternion[2] = -quaternion[2]
    return true
}

//will be replaced by gl-vec4 eventually
function vec4multMat4(out, a, m) {
    var x = a[0], y = a[1], z = a[2], w = a[3];
    out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
    out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
    out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
    out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
    return out;
}

//gets upper-left of a 4x4 matrix into a 3x3 of vectors
function mat3from4(out, mat4x4) {
    out[0][0] = mat4x4[0]
    out[0][1] = mat4x4[1]
    out[0][2] = mat4x4[2]
    
    out[1][0] = mat4x4[4]
    out[1][1] = mat4x4[5]
    out[1][2] = mat4x4[6]

    out[2][0] = mat4x4[8]
    out[2][1] = mat4x4[9]
    out[2][2] = mat4x4[10]
}

function combine(out, a, b, scale1, scale2) {
    out[0] = a[0] * scale1 + b[0] * scale2
    out[1] = a[1] * scale1 + b[1] * scale2
    out[2] = a[2] * scale1 + b[2] * scale2
}
},{"./normalize":418,"gl-mat4/clone":252,"gl-mat4/create":253,"gl-mat4/determinant":254,"gl-mat4/invert":258,"gl-mat4/transpose":269,"gl-vec3/cross":323,"gl-vec3/dot":328,"gl-vec3/length":338,"gl-vec3/normalize":345}],418:[function(_dereq_,module,exports){
module.exports = function normalize(out, mat) {
    var m44 = mat[15]
    // Cannot normalize.
    if (m44 === 0) 
        return false
    var scale = 1 / m44
    for (var i=0; i<16; i++)
        out[i] = mat[i] * scale
    return true
}
},{}],419:[function(_dereq_,module,exports){
var lerp = _dereq_('gl-vec3/lerp')

var recompose = _dereq_('mat4-recompose')
var decompose = _dereq_('mat4-decompose')
var determinant = _dereq_('gl-mat4/determinant')
var slerp = _dereq_('quat-slerp')

var state0 = state()
var state1 = state()
var tmp = state()

module.exports = interpolate
function interpolate(out, start, end, alpha) {
    if (determinant(start) === 0 || determinant(end) === 0)
        return false

    //decompose the start and end matrices into individual components
    var r0 = decompose(start, state0.translate, state0.scale, state0.skew, state0.perspective, state0.quaternion)
    var r1 = decompose(end, state1.translate, state1.scale, state1.skew, state1.perspective, state1.quaternion)
    if (!r0 || !r1)
        return false    


    //now lerp/slerp the start and end components into a temporary     lerp(tmptranslate, state0.translate, state1.translate, alpha)
    lerp(tmp.translate, state0.translate, state1.translate, alpha)
    lerp(tmp.skew, state0.skew, state1.skew, alpha)
    lerp(tmp.scale, state0.scale, state1.scale, alpha)
    lerp(tmp.perspective, state0.perspective, state1.perspective, alpha)
    slerp(tmp.quaternion, state0.quaternion, state1.quaternion, alpha)

    //and recompose into our 'out' matrix
    recompose(out, tmp.translate, tmp.scale, tmp.skew, tmp.perspective, tmp.quaternion)
    return true
}

function state() {
    return {
        translate: vec3(),
        scale: vec3(1),
        skew: vec3(),
        perspective: vec4(),
        quaternion: vec4()
    }
}

function vec3(n) {
    return [n||0,n||0,n||0]
}

function vec4() {
    return [0,0,0,1]
}
},{"gl-mat4/determinant":254,"gl-vec3/lerp":339,"mat4-decompose":417,"mat4-recompose":420,"quat-slerp":472}],420:[function(_dereq_,module,exports){
/*
Input:  translation ; a 3 component vector
        scale       ; a 3 component vector
        skew        ; skew factors XY,XZ,YZ represented as a 3 component vector
        perspective ; a 4 component vector
        quaternion  ; a 4 component vector
Output: matrix      ; a 4x4 matrix

From: http://www.w3.org/TR/css3-transforms/#recomposing-to-a-3d-matrix
*/

var mat4 = {
    identity: _dereq_('gl-mat4/identity'),
    translate: _dereq_('gl-mat4/translate'),
    multiply: _dereq_('gl-mat4/multiply'),
    create: _dereq_('gl-mat4/create'),
    scale: _dereq_('gl-mat4/scale'),
    fromRotationTranslation: _dereq_('gl-mat4/fromRotationTranslation')
}

var rotationMatrix = mat4.create()
var temp = mat4.create()

module.exports = function recomposeMat4(matrix, translation, scale, skew, perspective, quaternion) {
    mat4.identity(matrix)

    //apply translation & rotation
    mat4.fromRotationTranslation(matrix, quaternion, translation)

    //apply perspective
    matrix[3] = perspective[0]
    matrix[7] = perspective[1]
    matrix[11] = perspective[2]
    matrix[15] = perspective[3]
        
    // apply skew
    // temp is a identity 4x4 matrix initially
    mat4.identity(temp)

    if (skew[2] !== 0) {
        temp[9] = skew[2]
        mat4.multiply(matrix, matrix, temp)
    }

    if (skew[1] !== 0) {
        temp[9] = 0
        temp[8] = skew[1]
        mat4.multiply(matrix, matrix, temp)
    }

    if (skew[0] !== 0) {
        temp[8] = 0
        temp[4] = skew[0]
        mat4.multiply(matrix, matrix, temp)
    }

    //apply scale
    mat4.scale(matrix, matrix, scale)
    return matrix
}
},{"gl-mat4/create":253,"gl-mat4/fromRotationTranslation":256,"gl-mat4/identity":257,"gl-mat4/multiply":260,"gl-mat4/scale":267,"gl-mat4/translate":268}],421:[function(_dereq_,module,exports){
'use strict';
module.exports = Math.log2 || function (x) {
	return Math.log(x) * Math.LOG2E;
};

},{}],422:[function(_dereq_,module,exports){
'use strict'

var bsearch   = _dereq_('binary-search-bounds')
var m4interp  = _dereq_('mat4-interpolate')
var invert44  = _dereq_('gl-mat4/invert')
var rotateX   = _dereq_('gl-mat4/rotateX')
var rotateY   = _dereq_('gl-mat4/rotateY')
var rotateZ   = _dereq_('gl-mat4/rotateZ')
var lookAt    = _dereq_('gl-mat4/lookAt')
var translate = _dereq_('gl-mat4/translate')
var scale     = _dereq_('gl-mat4/scale')
var normalize = _dereq_('gl-vec3/normalize')

var DEFAULT_CENTER = [0,0,0]

module.exports = createMatrixCameraController

function MatrixCameraController(initialMatrix) {
  this._components    = initialMatrix.slice()
  this._time          = [0]
  this.prevMatrix     = initialMatrix.slice()
  this.nextMatrix     = initialMatrix.slice()
  this.computedMatrix = initialMatrix.slice()
  this.computedInverse = initialMatrix.slice()
  this.computedEye    = [0,0,0]
  this.computedUp     = [0,0,0]
  this.computedCenter = [0,0,0]
  this.computedRadius = [0]
  this._limits        = [-Infinity, Infinity]
}

var proto = MatrixCameraController.prototype

proto.recalcMatrix = function(t) {
  var time = this._time
  var tidx = bsearch.le(time, t)
  var mat = this.computedMatrix
  if(tidx < 0) {
    return
  }
  var comps = this._components
  if(tidx === time.length-1) {
    var ptr = 16*tidx
    for(var i=0; i<16; ++i) {
      mat[i] = comps[ptr++]
    }
  } else {
    var dt = (time[tidx+1] - time[tidx])
    var ptr = 16*tidx
    var prev = this.prevMatrix
    var allEqual = true
    for(var i=0; i<16; ++i) {
      prev[i] = comps[ptr++]
    }
    var next = this.nextMatrix
    for(var i=0; i<16; ++i) {
      next[i] = comps[ptr++]
      allEqual = allEqual && (prev[i] === next[i])
    }
    if(dt < 1e-6 || allEqual) {
      for(var i=0; i<16; ++i) {
        mat[i] = prev[i]
      }
    } else {
      m4interp(mat, prev, next, (t - time[tidx])/dt)
    }
  }

  var up = this.computedUp
  up[0] = mat[1]
  up[1] = mat[5]
  up[2] = mat[9]
  normalize(up, up)

  var imat = this.computedInverse
  invert44(imat, mat)
  var eye = this.computedEye
  var w = imat[15]
  eye[0] = imat[12]/w
  eye[1] = imat[13]/w
  eye[2] = imat[14]/w

  var center = this.computedCenter
  var radius = Math.exp(this.computedRadius[0])
  for(var i=0; i<3; ++i) {
    center[i] = eye[i] - mat[2+4*i] * radius
  }
}

proto.idle = function(t) {
  if(t < this.lastT()) {
    return
  }
  var mc = this._components
  var ptr = mc.length-16
  for(var i=0; i<16; ++i) {
    mc.push(mc[ptr++])
  }
  this._time.push(t)
}

proto.flush = function(t) {
  var idx = bsearch.gt(this._time, t) - 2
  if(idx < 0) {
    return
  }
  this._time.splice(0, idx)
  this._components.splice(0, 16*idx)
}

proto.lastT = function() {
  return this._time[this._time.length-1]
}

proto.lookAt = function(t, eye, center, up) {
  this.recalcMatrix(t)
  eye    = eye || this.computedEye
  center = center || DEFAULT_CENTER
  up     = up || this.computedUp
  this.setMatrix(t, lookAt(this.computedMatrix, eye, center, up))
  var d2 = 0.0
  for(var i=0; i<3; ++i) {
    d2 += Math.pow(center[i] - eye[i], 2)
  }
  d2 = Math.log(Math.sqrt(d2))
  this.computedRadius[0] = d2
}

proto.rotate = function(t, yaw, pitch, roll) {
  this.recalcMatrix(t)
  var mat = this.computedInverse
  if(yaw)   rotateY(mat, mat, yaw)
  if(pitch) rotateX(mat, mat, pitch)
  if(roll)  rotateZ(mat, mat, roll)
  this.setMatrix(t, invert44(this.computedMatrix, mat))
}

var tvec = [0,0,0]

proto.pan = function(t, dx, dy, dz) {
  tvec[0] = -(dx || 0.0)
  tvec[1] = -(dy || 0.0)
  tvec[2] = -(dz || 0.0)
  this.recalcMatrix(t)
  var mat = this.computedInverse
  translate(mat, mat, tvec)
  this.setMatrix(t, invert44(mat, mat))
}

proto.translate = function(t, dx, dy, dz) {
  tvec[0] = dx || 0.0
  tvec[1] = dy || 0.0
  tvec[2] = dz || 0.0
  this.recalcMatrix(t)
  var mat = this.computedMatrix
  translate(mat, mat, tvec)
  this.setMatrix(t, mat)
}

proto.setMatrix = function(t, mat) {
  if(t < this.lastT()) {
    return
  }
  this._time.push(t)
  for(var i=0; i<16; ++i) {
    this._components.push(mat[i])
  }
}

proto.setDistance = function(t, d) {
  this.computedRadius[0] = d
}

proto.setDistanceLimits = function(a,b) {
  var lim = this._limits
  lim[0] = a
  lim[1] = b
}

proto.getDistanceLimits = function(out) {
  var lim = this._limits
  if(out) {
    out[0] = lim[0]
    out[1] = lim[1]
    return out
  }
  return lim
}

function createMatrixCameraController(options) {
  options = options || {}
  var matrix = options.matrix || 
              [1,0,0,0,
               0,1,0,0,
               0,0,1,0,
               0,0,0,1]
  return new MatrixCameraController(matrix)
}

},{"binary-search-bounds":79,"gl-mat4/invert":258,"gl-mat4/lookAt":259,"gl-mat4/rotateX":264,"gl-mat4/rotateY":265,"gl-mat4/rotateZ":266,"gl-mat4/scale":267,"gl-mat4/translate":268,"gl-vec3/normalize":345,"mat4-interpolate":419}],423:[function(_dereq_,module,exports){
'use strict'

module.exports = monotoneConvexHull2D

var orient = _dereq_('robust-orientation')[3]

function monotoneConvexHull2D(points) {
  var n = points.length

  if(n < 3) {
    var result = new Array(n)
    for(var i=0; i<n; ++i) {
      result[i] = i
    }

    if(n === 2 &&
       points[0][0] === points[1][0] &&
       points[0][1] === points[1][1]) {
      return [0]
    }

    return result
  }

  //Sort point indices along x-axis
  var sorted = new Array(n)
  for(var i=0; i<n; ++i) {
    sorted[i] = i
  }
  sorted.sort(function(a,b) {
    var d = points[a][0]-points[b][0]
    if(d) {
      return d
    }
    return points[a][1] - points[b][1]
  })

  //Construct upper and lower hulls
  var lower = [sorted[0], sorted[1]]
  var upper = [sorted[0], sorted[1]]

  for(var i=2; i<n; ++i) {
    var idx = sorted[i]
    var p   = points[idx]

    //Insert into lower list
    var m = lower.length
    while(m > 1 && orient(
        points[lower[m-2]], 
        points[lower[m-1]], 
        p) <= 0) {
      m -= 1
      lower.pop()
    }
    lower.push(idx)

    //Insert into upper list
    m = upper.length
    while(m > 1 && orient(
        points[upper[m-2]], 
        points[upper[m-1]], 
        p) >= 0) {
      m -= 1
      upper.pop()
    }
    upper.push(idx)
  }

  //Merge lists together
  var result = new Array(upper.length + lower.length - 2)
  var ptr    = 0
  for(var i=0, nl=lower.length; i<nl; ++i) {
    result[ptr++] = lower[i]
  }
  for(var j=upper.length-2; j>0; --j) {
    result[ptr++] = upper[j]
  }

  //Return result
  return result
}
},{"robust-orientation":491}],424:[function(_dereq_,module,exports){
'use strict'

module.exports = mouseListen

var mouse = _dereq_('mouse-event')

function mouseListen (element, callback) {
  if (!callback) {
    callback = element
    element = window
  }

  var buttonState = 0
  var x = 0
  var y = 0
  var mods = {
    shift: false,
    alt: false,
    control: false,
    meta: false
  }
  var attached = false

  function updateMods (ev) {
    var changed = false
    if ('altKey' in ev) {
      changed = changed || ev.altKey !== mods.alt
      mods.alt = !!ev.altKey
    }
    if ('shiftKey' in ev) {
      changed = changed || ev.shiftKey !== mods.shift
      mods.shift = !!ev.shiftKey
    }
    if ('ctrlKey' in ev) {
      changed = changed || ev.ctrlKey !== mods.control
      mods.control = !!ev.ctrlKey
    }
    if ('metaKey' in ev) {
      changed = changed || ev.metaKey !== mods.meta
      mods.meta = !!ev.metaKey
    }
    return changed
  }

  function handleEvent (nextButtons, ev) {
    var nextX = mouse.x(ev)
    var nextY = mouse.y(ev)
    if ('buttons' in ev) {
      nextButtons = ev.buttons | 0
    }
    if (nextButtons !== buttonState ||
      nextX !== x ||
      nextY !== y ||
      updateMods(ev)) {
      buttonState = nextButtons | 0
      x = nextX || 0
      y = nextY || 0
      callback && callback(buttonState, x, y, mods)
    }
  }

  function clearState (ev) {
    handleEvent(0, ev)
  }

  function handleBlur () {
    if (buttonState ||
      x ||
      y ||
      mods.shift ||
      mods.alt ||
      mods.meta ||
      mods.control) {
      x = y = 0
      buttonState = 0
      mods.shift = mods.alt = mods.control = mods.meta = false
      callback && callback(0, 0, 0, mods)
    }
  }

  function handleMods (ev) {
    if (updateMods(ev)) {
      callback && callback(buttonState, x, y, mods)
    }
  }

  function handleMouseMove (ev) {
    if (mouse.buttons(ev) === 0) {
      handleEvent(0, ev)
    } else {
      handleEvent(buttonState, ev)
    }
  }

  function handleMouseDown (ev) {
    handleEvent(buttonState | mouse.buttons(ev), ev)
  }

  function handleMouseUp (ev) {
    handleEvent(buttonState & ~mouse.buttons(ev), ev)
  }

  function attachListeners () {
    if (attached) {
      return
    }
    attached = true

    element.addEventListener('mousemove', handleMouseMove)

    element.addEventListener('mousedown', handleMouseDown)

    element.addEventListener('mouseup', handleMouseUp)

    element.addEventListener('mouseleave', clearState)
    element.addEventListener('mouseenter', clearState)
    element.addEventListener('mouseout', clearState)
    element.addEventListener('mouseover', clearState)

    element.addEventListener('blur', handleBlur)

    element.addEventListener('keyup', handleMods)
    element.addEventListener('keydown', handleMods)
    element.addEventListener('keypress', handleMods)

    if (element !== window) {
      window.addEventListener('blur', handleBlur)

      window.addEventListener('keyup', handleMods)
      window.addEventListener('keydown', handleMods)
      window.addEventListener('keypress', handleMods)
    }
  }

  function detachListeners () {
    if (!attached) {
      return
    }
    attached = false

    element.removeEventListener('mousemove', handleMouseMove)

    element.removeEventListener('mousedown', handleMouseDown)

    element.removeEventListener('mouseup', handleMouseUp)

    element.removeEventListener('mouseleave', clearState)
    element.removeEventListener('mouseenter', clearState)
    element.removeEventListener('mouseout', clearState)
    element.removeEventListener('mouseover', clearState)

    element.removeEventListener('blur', handleBlur)

    element.removeEventListener('keyup', handleMods)
    element.removeEventListener('keydown', handleMods)
    element.removeEventListener('keypress', handleMods)

    if (element !== window) {
      window.removeEventListener('blur', handleBlur)

      window.removeEventListener('keyup', handleMods)
      window.removeEventListener('keydown', handleMods)
      window.removeEventListener('keypress', handleMods)
    }
  }

  // Attach listeners
  attachListeners()

  var result = {
    element: element
  }

  Object.defineProperties(result, {
    enabled: {
      get: function () { return attached },
      set: function (f) {
        if (f) {
          attachListeners()
        } else {
          detachListeners()
        }
      },
      enumerable: true
    },
    buttons: {
      get: function () { return buttonState },
      enumerable: true
    },
    x: {
      get: function () { return x },
      enumerable: true
    },
    y: {
      get: function () { return y },
      enumerable: true
    },
    mods: {
      get: function () { return mods },
      enumerable: true
    }
  })

  return result
}

},{"mouse-event":426}],425:[function(_dereq_,module,exports){
var rootPosition = { left: 0, top: 0 }

module.exports = mouseEventOffset
function mouseEventOffset (ev, target, out) {
  target = target || ev.currentTarget || ev.srcElement
  if (!Array.isArray(out)) {
    out = [ 0, 0 ]
  }
  var cx = ev.clientX || 0
  var cy = ev.clientY || 0
  var rect = getBoundingClientOffset(target)
  out[0] = cx - rect.left
  out[1] = cy - rect.top
  return out
}

function getBoundingClientOffset (element) {
  if (element === window ||
      element === document ||
      element === document.body) {
    return rootPosition
  } else {
    return element.getBoundingClientRect()
  }
}

},{}],426:[function(_dereq_,module,exports){
'use strict'

function mouseButtons(ev) {
  if(typeof ev === 'object') {
    if('buttons' in ev) {
      return ev.buttons
    } else if('which' in ev) {
      var b = ev.which
      if(b === 2) {
        return 4
      } else if(b === 3) {
        return 2
      } else if(b > 0) {
        return 1<<(b-1)
      }
    } else if('button' in ev) {
      var b = ev.button
      if(b === 1) {
        return 4
      } else if(b === 2) {
        return 2
      } else if(b >= 0) {
        return 1<<b
      }
    }
  }
  return 0
}
exports.buttons = mouseButtons

function mouseElement(ev) {
  return ev.target || ev.srcElement || window
}
exports.element = mouseElement

function mouseRelativeX(ev) {
  if(typeof ev === 'object') {
    if('offsetX' in ev) {
      return ev.offsetX
    }
    var target = mouseElement(ev)
    var bounds = target.getBoundingClientRect()
    return ev.clientX - bounds.left
  }
  return 0
}
exports.x = mouseRelativeX

function mouseRelativeY(ev) {
  if(typeof ev === 'object') {
    if('offsetY' in ev) {
      return ev.offsetY
    }
    var target = mouseElement(ev)
    var bounds = target.getBoundingClientRect()
    return ev.clientY - bounds.top
  }
  return 0
}
exports.y = mouseRelativeY

},{}],427:[function(_dereq_,module,exports){
'use strict'

var toPX = _dereq_('to-px')

module.exports = mouseWheelListen

function mouseWheelListen(element, callback, noScroll) {
  if(typeof element === 'function') {
    noScroll = !!callback
    callback = element
    element = window
  }
  var lineHeight = toPX('ex', element)
  var listener = function(ev) {
    if(noScroll) {
      ev.preventDefault()
    }
    var dx = ev.deltaX || 0
    var dy = ev.deltaY || 0
    var dz = ev.deltaZ || 0
    var mode = ev.deltaMode
    var scale = 1
    switch(mode) {
      case 1:
        scale = lineHeight
      break
      case 2:
        scale = window.innerHeight
      break
    }
    dx *= scale
    dy *= scale
    dz *= scale
    if(dx || dy || dz) {
      return callback(dx, dy, dz, ev)
    }
  }
  element.addEventListener('wheel', listener)
  return listener
}

},{"to-px":520}],428:[function(_dereq_,module,exports){
"use strict"

var pool = _dereq_("typedarray-pool")

module.exports = createSurfaceExtractor

//Helper macros
function array(i) {
  return "a" + i
}
function data(i) {
  return "d" + i
}
function cube(i,bitmask) {
  return "c" + i + "_" + bitmask
}
function shape(i) {
  return "s" + i
}
function stride(i,j) {
  return "t" + i + "_" + j
}
function offset(i) {
  return "o" + i
}
function scalar(i) {
  return "x" + i
}
function pointer(i) {
  return "p" + i
}
function delta(i,bitmask) {
  return "d" + i + "_" + bitmask
}
function index(i) {
  return "i" + i
}
function step(i,j) {
  return "u" + i + "_" + j
}
function pcube(bitmask) {
  return "b" + bitmask
}
function qcube(bitmask) {
  return "y" + bitmask
}
function pdelta(bitmask) {
  return "e" + bitmask
}
function vert(i) {
  return "v" + i
}
var VERTEX_IDS = "V"
var PHASES = "P"
var VERTEX_COUNT = "N"
var POOL_SIZE = "Q"
var POINTER = "X"
var TEMPORARY = "T"

function permBitmask(dimension, mask, order) {
  var r = 0
  for(var i=0; i<dimension; ++i) {
    if(mask & (1<<i)) {
      r |= (1<<order[i])
    }
  }
  return r
}

//Generates the surface procedure
function compileSurfaceProcedure(vertexFunc, faceFunc, phaseFunc, scalarArgs, order, typesig) {
  var arrayArgs = typesig.length
  var dimension = order.length

  if(dimension < 2) {
    throw new Error("ndarray-extract-contour: Dimension must be at least 2")
  }

  var funcName = "extractContour" + order.join("_")
  var code = []
  var vars = []
  var args = []

  //Assemble arguments
  for(var i=0; i<arrayArgs; ++i) {
    args.push(array(i))  
  }
  for(var i=0; i<scalarArgs; ++i) {
    args.push(scalar(i))
  }

  //Shape
  for(var i=0; i<dimension; ++i) {
    vars.push(shape(i) + "=" + array(0) + ".shape[" + i + "]|0")
  }
  //Data, stride, offset pointers
  for(var i=0; i<arrayArgs; ++i) {
    vars.push(data(i) + "=" + array(i) + ".data",
              offset(i) + "=" + array(i) + ".offset|0")
    for(var j=0; j<dimension; ++j) {
      vars.push(stride(i,j) + "=" + array(i) + ".stride[" + j + "]|0")
    }
  }
  //Pointer, delta and cube variables
  for(var i=0; i<arrayArgs; ++i) {
    vars.push(pointer(i) + "=" + offset(i))
    vars.push(cube(i,0))
    for(var j=1; j<(1<<dimension); ++j) {
      var ptrStr = []
      for(var k=0; k<dimension; ++k) {
        if(j & (1<<k)) {
          ptrStr.push("-" + stride(i,k))
        }
      }
      vars.push(delta(i,j) + "=(" + ptrStr.join("") + ")|0")
      vars.push(cube(i,j) + "=0")
    }
  }
  //Create step variables
  for(var i=0; i<arrayArgs; ++i) {
    for(var j=0; j<dimension; ++j) {
      var stepVal = [ stride(i,order[j]) ]
      if(j > 0) {
        stepVal.push(stride(i, order[j-1]) + "*" + shape(order[j-1]) )
      }
      vars.push(step(i,order[j]) + "=(" + stepVal.join("-") + ")|0")
    }
  }
  //Create index variables
  for(var i=0; i<dimension; ++i) {
    vars.push(index(i) + "=0")
  }
  //Vertex count
  vars.push(VERTEX_COUNT + "=0")
  //Compute pool size, initialize pool step
  var sizeVariable = ["2"]
  for(var i=dimension-2; i>=0; --i) {
    sizeVariable.push(shape(order[i]))
  }
  //Previous phases and vertex_ids
  vars.push(POOL_SIZE + "=(" + sizeVariable.join("*") + ")|0",
            PHASES + "=mallocUint32(" + POOL_SIZE + ")",
            VERTEX_IDS + "=mallocUint32(" + POOL_SIZE + ")",
            POINTER + "=0")
  //Create cube variables for phases
  vars.push(pcube(0) + "=0")
  for(var j=1; j<(1<<dimension); ++j) {
    var cubeDelta = []
    var cubeStep = [ ]
    for(var k=0; k<dimension; ++k) {
      if(j & (1<<k)) {
        if(cubeStep.length === 0) {
          cubeDelta.push("1")
        } else {
          cubeDelta.unshift(cubeStep.join("*"))
        }
      }
      cubeStep.push(shape(order[k]))
    }
    var signFlag = ""
    if(cubeDelta[0].indexOf(shape(order[dimension-2])) < 0) {
      signFlag = "-"
    }
    var jperm = permBitmask(dimension, j, order)
    vars.push(pdelta(jperm) + "=(-" + cubeDelta.join("-") + ")|0",
              qcube(jperm) + "=(" + signFlag + cubeDelta.join("-") + ")|0",
              pcube(jperm) + "=0")
  }
  vars.push(vert(0) + "=0", TEMPORARY + "=0")

  function forLoopBegin(i, start) {
    code.push("for(", index(order[i]), "=", start, ";",
      index(order[i]), "<", shape(order[i]), ";",
      "++", index(order[i]), "){")
  }

  function forLoopEnd(i) {
    for(var j=0; j<arrayArgs; ++j) {
      code.push(pointer(j), "+=", step(j,order[i]), ";")
    }
    code.push("}")
  }

  function fillEmptySlice(k) {
    for(var i=k-1; i>=0; --i) {
      forLoopBegin(i, 0) 
    }
    var phaseFuncArgs = []
    for(var i=0; i<arrayArgs; ++i) {
      if(typesig[i]) {
        phaseFuncArgs.push(data(i) + ".get(" + pointer(i) + ")")
      } else {
        phaseFuncArgs.push(data(i) + "[" + pointer(i) + "]")
      }
    }
    for(var i=0; i<scalarArgs; ++i) {
      phaseFuncArgs.push(scalar(i))
    }
    code.push(PHASES, "[", POINTER, "++]=phase(", phaseFuncArgs.join(), ");")
    for(var i=0; i<k; ++i) {
      forLoopEnd(i)
    }
    for(var j=0; j<arrayArgs; ++j) {
      code.push(pointer(j), "+=", step(j,order[k]), ";")
    }
  }

  function processGridCell(mask) {
    //Read in local data
    for(var i=0; i<arrayArgs; ++i) {
      if(typesig[i]) {
        code.push(cube(i,0), "=", data(i), ".get(", pointer(i), ");")
      } else {
        code.push(cube(i,0), "=", data(i), "[", pointer(i), "];")
      }
    }

    //Read in phase
    var phaseFuncArgs = []
    for(var i=0; i<arrayArgs; ++i) {
      phaseFuncArgs.push(cube(i,0))
    }
    for(var i=0; i<scalarArgs; ++i) {
      phaseFuncArgs.push(scalar(i))
    }
    
    code.push(pcube(0), "=", PHASES, "[", POINTER, "]=phase(", phaseFuncArgs.join(), ");")
    
    //Read in other cube data
    for(var j=1; j<(1<<dimension); ++j) {
      code.push(pcube(j), "=", PHASES, "[", POINTER, "+", pdelta(j), "];")
    }

    //Check for boundary crossing
    var vertexPredicate = []
    for(var j=1; j<(1<<dimension); ++j) {
      vertexPredicate.push("(" + pcube(0) + "!==" + pcube(j) + ")")
    }
    code.push("if(", vertexPredicate.join("||"), "){")

    //Read in boundary data
    var vertexArgs = []
    for(var i=0; i<dimension; ++i) {
      vertexArgs.push(index(i))
    }
    for(var i=0; i<arrayArgs; ++i) {
      vertexArgs.push(cube(i,0))
      for(var j=1; j<(1<<dimension); ++j) {
        if(typesig[i]) {
          code.push(cube(i,j), "=", data(i), ".get(", pointer(i), "+", delta(i,j), ");")
        } else {
          code.push(cube(i,j), "=", data(i), "[", pointer(i), "+", delta(i,j), "];")
        }
        vertexArgs.push(cube(i,j))
      }
    }
    for(var i=0; i<(1<<dimension); ++i) {
      vertexArgs.push(pcube(i))
    }
    for(var i=0; i<scalarArgs; ++i) {
      vertexArgs.push(scalar(i))
    }

    //Generate vertex
    code.push("vertex(", vertexArgs.join(), ");",
      vert(0), "=", VERTEX_IDS, "[", POINTER, "]=", VERTEX_COUNT, "++;")

    //Check for face crossings
    var base = (1<<dimension)-1
    var corner = pcube(base)
    for(var j=0; j<dimension; ++j) {
      if((mask & ~(1<<j))===0) {
        //Check face
        var subset = base^(1<<j)
        var edge = pcube(subset)
        var faceArgs = [ ]
        for(var k=subset; k>0; k=(k-1)&subset) {
          faceArgs.push(VERTEX_IDS + "[" + POINTER + "+" + pdelta(k) + "]")
        }
        faceArgs.push(vert(0))
        for(var k=0; k<arrayArgs; ++k) {
          if(j&1) {
            faceArgs.push(cube(k,base), cube(k,subset))
          } else {
            faceArgs.push(cube(k,subset), cube(k,base))
          }
        }
        if(j&1) {
          faceArgs.push(corner, edge)
        } else {
          faceArgs.push(edge, corner)
        }
        for(var k=0; k<scalarArgs; ++k) {
          faceArgs.push(scalar(k))
        }
        code.push("if(", corner, "!==", edge, "){",
          "face(", faceArgs.join(), ")}")
      }
    }
    
    //Increment pointer, close off if statement
    code.push("}",
      POINTER, "+=1;")
  }

  function flip() {
    for(var j=1; j<(1<<dimension); ++j) {
      code.push(TEMPORARY, "=", pdelta(j), ";",
                pdelta(j), "=", qcube(j), ";",
                qcube(j), "=", TEMPORARY, ";")
    }
  }

  function createLoop(i, mask) {
    if(i < 0) {
      processGridCell(mask)
      return
    }
    fillEmptySlice(i)
    code.push("if(", shape(order[i]), ">0){",
      index(order[i]), "=1;")
    createLoop(i-1, mask|(1<<order[i]))

    for(var j=0; j<arrayArgs; ++j) {
      code.push(pointer(j), "+=", step(j,order[i]), ";")
    }
    if(i === dimension-1) {
      code.push(POINTER, "=0;")
      flip()
    }
    forLoopBegin(i, 2)
    createLoop(i-1, mask)
    if(i === dimension-1) {
      code.push("if(", index(order[dimension-1]), "&1){",
        POINTER, "=0;}")
      flip()
    }
    forLoopEnd(i)
    code.push("}")
  }

  createLoop(dimension-1, 0)

  //Release scratch memory
  code.push("freeUint32(", VERTEX_IDS, ");freeUint32(", PHASES, ");")

  //Compile and link procedure
  var procedureCode = [
    "'use strict';",
    "function ", funcName, "(", args.join(), "){",
      "var ", vars.join(), ";",
      code.join(""),
    "}",
    "return ", funcName ].join("")

  var proc = new Function(
    "vertex", 
    "face", 
    "phase", 
    "mallocUint32", 
    "freeUint32",
    procedureCode)
  return proc(
    vertexFunc, 
    faceFunc, 
    phaseFunc, 
    pool.mallocUint32, 
    pool.freeUint32)
}

function createSurfaceExtractor(args) {
  function error(msg) {
    throw new Error("ndarray-extract-contour: " + msg)
  }
  if(typeof args !== "object") {
    error("Must specify arguments")
  }
  var order = args.order
  if(!Array.isArray(order)) {
    error("Must specify order")
  }
  var arrays = args.arrayArguments||1
  if(arrays < 1) {
    error("Must have at least one array argument")
  }
  var scalars = args.scalarArguments||0
  if(scalars < 0) {
    error("Scalar arg count must be > 0")
  }
  if(typeof args.vertex !== "function") {
    error("Must specify vertex creation function")
  }
  if(typeof args.cell !== "function") {
    error("Must specify cell creation function")
  }
  if(typeof args.phase !== "function") {
    error("Must specify phase function")
  }
  var getters = args.getters || []
  var typesig = new Array(arrays)
  for(var i=0; i<arrays; ++i) {
    if(getters.indexOf(i) >= 0) {
      typesig[i] = true
    } else {
      typesig[i] = false
    }
  }
  return compileSurfaceProcedure(
    args.vertex,
    args.cell,
    args.phase,
    scalars,
    order,
    typesig)
}
},{"typedarray-pool":526}],429:[function(_dereq_,module,exports){
"use strict"



var fill = _dereq_('cwise/lib/wrapper')({"args":["index","array","scalar"],"pre":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"body":{"body":"{_inline_1_arg1_=_inline_1_arg2_.apply(void 0,_inline_1_arg0_)}","args":[{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_1_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_1_arg2_","lvalue":false,"rvalue":true,"count":1}],"thisVars":[],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"cwise","blockSize":64})

module.exports = function(array, f) {
  fill(array, f)
  return array
}

},{"cwise/lib/wrapper":137}],430:[function(_dereq_,module,exports){
'use strict'

module.exports      = gradient

var dup             = _dereq_('dup')
var cwiseCompiler   = _dereq_('cwise-compiler')

var TEMPLATE_CACHE  = {}
var GRADIENT_CACHE  = {}

var EmptyProc = {
  body: "",
  args: [],
  thisVars: [],
  localVars: []
}

var centralDiff = cwiseCompiler({
  args: [ 'array', 'array', 'array' ],
  pre: EmptyProc,
  post: EmptyProc,
  body: {
    args: [ {
      name: 'out', 
      lvalue: true,
      rvalue: false,
      count: 1
    }, {
      name: 'left', 
      lvalue: false,
      rvalue: true,
      count: 1
    }, {
      name: 'right', 
      lvalue: false,
      rvalue: true,
      count: 1
    }],
    body: "out=0.5*(left-right)",
    thisVars: [],
    localVars: []
  },
  funcName: 'cdiff'
})

var zeroOut = cwiseCompiler({
  args: [ 'array' ],
  pre: EmptyProc,
  post: EmptyProc,
  body: {
    args: [ {
      name: 'out', 
      lvalue: true,
      rvalue: false,
      count: 1
    }],
    body: "out=0",
    thisVars: [],
    localVars: []
  },
  funcName: 'zero'
})

function generateTemplate(d) {
  if(d in TEMPLATE_CACHE) {
    return TEMPLATE_CACHE[d]
  }
  var code = []
  for(var i=0; i<d; ++i) {
    code.push('out', i, 's=0.5*(inp', i, 'l-inp', i, 'r);')
  }
  var args = [ 'array' ]
  var names = ['junk']
  for(var i=0; i<d; ++i) {
    args.push('array')
    names.push('out' + i + 's')
    var o = dup(d)
    o[i] = -1
    args.push({
      array: 0,
      offset: o.slice()
    })
    o[i] = 1
    args.push({
      array: 0,
      offset: o.slice()
    })
    names.push('inp' + i + 'l', 'inp' + i + 'r')
  }
  return TEMPLATE_CACHE[d] = cwiseCompiler({
    args: args,
    pre:  EmptyProc,
    post: EmptyProc,
    body: {
      body: code.join(''),
      args: names.map(function(n) {
        return {
          name: n,
          lvalue: n.indexOf('out') === 0,
          rvalue: n.indexOf('inp') === 0,
          count: (n!=='junk')|0
        }
      }),
      thisVars: [],
      localVars: []
    },
    funcName: 'fdTemplate' + d
  })
}

function generateGradient(boundaryConditions) {
  var token = boundaryConditions.join()
  var proc = GRADIENT_CACHE[token]
  if(proc) {
    return proc
  }

  var d = boundaryConditions.length
  var code = ['function gradient(dst,src){var s=src.shape.slice();' ]
  
  function handleBoundary(facet) {
    var cod = d - facet.length

    var loStr = []
    var hiStr = []
    var pickStr = []
    for(var i=0; i<d; ++i) {
      if(facet.indexOf(i+1) >= 0) {
        pickStr.push('0')
      } else if(facet.indexOf(-(i+1)) >= 0) {
        pickStr.push('s['+i+']-1')
      } else {
        pickStr.push('-1')
        loStr.push('1')
        hiStr.push('s['+i+']-2')
      }
    }
    var boundStr = '.lo(' + loStr.join() + ').hi(' + hiStr.join() + ')'
    if(loStr.length === 0) {
      boundStr = ''
    }
        
    if(cod > 0) {
      code.push('if(1') 
      for(var i=0; i<d; ++i) {
        if(facet.indexOf(i+1) >= 0 || facet.indexOf(-(i+1)) >= 0) {
          continue
        }
        code.push('&&s[', i, ']>2')
      }
      code.push('){grad', cod, '(src.pick(', pickStr.join(), ')', boundStr)
      for(var i=0; i<d; ++i) {
        if(facet.indexOf(i+1) >= 0 || facet.indexOf(-(i+1)) >= 0) {
          continue
        }
        code.push(',dst.pick(', pickStr.join(), ',', i, ')', boundStr)
      }
      code.push(');')
    }

    for(var i=0; i<facet.length; ++i) {
      var bnd = Math.abs(facet[i])-1
      var outStr = 'dst.pick(' + pickStr.join() + ',' + bnd + ')' + boundStr
      switch(boundaryConditions[bnd]) {

        case 'clamp':
          var cPickStr = pickStr.slice()
          var dPickStr = pickStr.slice()
          if(facet[i] < 0) {
            cPickStr[bnd] = 's[' + bnd + ']-2'
          } else {
            dPickStr[bnd] = '1'
          }
          if(cod === 0) {
            code.push('if(s[', bnd, ']>1){dst.set(',
              pickStr.join(), ',', bnd, ',0.5*(src.get(',
                cPickStr.join(), ')-src.get(',
                dPickStr.join(), ')))}else{dst.set(',
              pickStr.join(), ',', bnd, ',0)};')
          } else {
            code.push('if(s[', bnd, ']>1){diff(', outStr, 
                ',src.pick(', cPickStr.join(), ')', boundStr, 
                ',src.pick(', dPickStr.join(), ')', boundStr, 
                ');}else{zero(', outStr, ');};')
          }
        break

        case 'mirror':
          if(cod === 0) {
            code.push('dst.set(', pickStr.join(), ',', bnd, ',0);')
          } else {
            code.push('zero(', outStr, ');')
          }
        break

        case 'wrap':
          var aPickStr = pickStr.slice()
          var bPickStr = pickStr.slice()
          if(facet[i] < 0) {
            aPickStr[bnd] = 's[' + bnd + ']-2'
            bPickStr[bnd] = '0'
            
          } else {
            aPickStr[bnd] = 's[' + bnd + ']-1'
            bPickStr[bnd] = '1'
          }
          if(cod === 0) {
            code.push('if(s[', bnd, ']>2){dst.set(',
              pickStr.join(), ',', bnd, ',0.5*(src.get(',
                aPickStr.join(), ')-src.get(',
                bPickStr.join(), ')))}else{dst.set(',
              pickStr.join(), ',', bnd, ',0)};')
          } else {
            code.push('if(s[', bnd, ']>2){diff(', outStr, 
                ',src.pick(', aPickStr.join(), ')', boundStr, 
                ',src.pick(', bPickStr.join(), ')', boundStr, 
                ');}else{zero(', outStr, ');};')
          }
        break

        default:
          throw new Error('ndarray-gradient: Invalid boundary condition')
      }
    }

    if(cod > 0) {
      code.push('};')
    }
  }

  //Enumerate ridges, facets, etc. of hypercube
  for(var i=0; i<(1<<d); ++i) {
    var faces = []
    for(var j=0; j<d; ++j) {
      if(i & (1<<j)) {
        faces.push(j+1)
      }
    }
    for(var k=0; k<(1<<faces.length); ++k) {
      var sfaces = faces.slice()
      for(var j=0; j<faces.length; ++j) {
        if(k & (1<<j)) {
          sfaces[j] = -sfaces[j]
        }
      }
      handleBoundary(sfaces)
    }
  }

  code.push('return dst;};return gradient')

  //Compile and link routine, save cached procedure
  var linkNames = [ 'diff', 'zero' ]
  var linkArgs  = [ centralDiff, zeroOut ]
  for(var i=1; i<=d; ++i) {
    linkNames.push('grad' + i)
    linkArgs.push(generateTemplate(i))
  }
  linkNames.push(code.join(''))

  var link = Function.apply(void 0, linkNames)
  var proc = link.apply(void 0, linkArgs)
  TEMPLATE_CACHE[token] = proc
  return proc
}

function gradient(out, inp, bc) {
  if(Array.isArray(bc)) {
    if(bc.length !== inp.dimension) {
      throw new Error('ndarray-gradient: invalid boundary conditions')
    }
  } else if(typeof bc === 'string') {
    bc = dup(inp.dimension, bc)
  } else {
    bc = dup(inp.dimension, 'clamp')
  }
  if(out.dimension !== inp.dimension + 1) {
    throw new Error('ndarray-gradient: output dimension must be +1 input dimension')
  }
  if(out.shape[inp.dimension] !== inp.dimension) {
    throw new Error('ndarray-gradient: output shape must match input shape')
  }
  for(var i=0; i<inp.dimension; ++i) {
    if(out.shape[i] !== inp.shape[i]) {
      throw new Error('ndarray-gradient: shape mismatch')
    }
  }
  if(inp.size === 0) {
    return out
  }
  if(inp.dimension <= 0) {
    out.set(0)
    return out
  }
  var cached = generateGradient(bc)
  return cached(out, inp)
}
},{"cwise-compiler":134,"dup":158}],431:[function(_dereq_,module,exports){
'use strict'

var warp = _dereq_('ndarray-warp')
var invert = _dereq_('gl-matrix-invert')

module.exports = applyHomography

function applyHomography(dest, src, Xi) {
  var n = src.dimension
  var X = invert([], Xi)
  warp(dest, src, function(out_c, inp_c) {
    for(var i=0; i<n; ++i) {
      out_c[i] = X[(n+1)*n + i]
      for(var j=0; j<n; ++j) {
        out_c[i] += X[(n+1)*j+i] * inp_c[j]
      }
    }
    var w = X[(n+1)*(n+1)-1]
    for(var j=0; j<n; ++j) {
      w += X[(n+1)*j+n] * inp_c[j]
    }
    var wr = 1.0 / w
    for(var i=0; i<n; ++i) {
      out_c[i] *= wr
    }
    return out_c
  })
  return dest
}
},{"gl-matrix-invert":270,"ndarray-warp":438}],432:[function(_dereq_,module,exports){
"use strict"

function interp1d(arr, x) {
  var ix = Math.floor(x)
    , fx = x - ix
    , s0 = 0 <= ix   && ix   < arr.shape[0]
    , s1 = 0 <= ix+1 && ix+1 < arr.shape[0]
    , w0 = s0 ? +arr.get(ix)   : 0.0
    , w1 = s1 ? +arr.get(ix+1) : 0.0
  return (1.0-fx)*w0 + fx*w1
}

function interp2d(arr, x, y) {
  var ix = Math.floor(x)
    , fx = x - ix
    , s0 = 0 <= ix   && ix   < arr.shape[0]
    , s1 = 0 <= ix+1 && ix+1 < arr.shape[0]
    , iy = Math.floor(y)
    , fy = y - iy
    , t0 = 0 <= iy   && iy   < arr.shape[1]
    , t1 = 0 <= iy+1 && iy+1 < arr.shape[1]
    , w00 = s0&&t0 ? arr.get(ix  ,iy  ) : 0.0
    , w01 = s0&&t1 ? arr.get(ix  ,iy+1) : 0.0
    , w10 = s1&&t0 ? arr.get(ix+1,iy  ) : 0.0
    , w11 = s1&&t1 ? arr.get(ix+1,iy+1) : 0.0
  return (1.0-fy) * ((1.0-fx)*w00 + fx*w10) + fy * ((1.0-fx)*w01 + fx*w11)
}

function interp3d(arr, x, y, z) {
  var ix = Math.floor(x)
    , fx = x - ix
    , s0 = 0 <= ix   && ix   < arr.shape[0]
    , s1 = 0 <= ix+1 && ix+1 < arr.shape[0]
    , iy = Math.floor(y)
    , fy = y - iy
    , t0 = 0 <= iy   && iy   < arr.shape[1]
    , t1 = 0 <= iy+1 && iy+1 < arr.shape[1]
    , iz = Math.floor(z)
    , fz = z - iz
    , u0 = 0 <= iz   && iz   < arr.shape[2]
    , u1 = 0 <= iz+1 && iz+1 < arr.shape[2]
    , w000 = s0&&t0&&u0 ? arr.get(ix,iy,iz)       : 0.0
    , w010 = s0&&t1&&u0 ? arr.get(ix,iy+1,iz)     : 0.0
    , w100 = s1&&t0&&u0 ? arr.get(ix+1,iy,iz)     : 0.0
    , w110 = s1&&t1&&u0 ? arr.get(ix+1,iy+1,iz)   : 0.0
    , w001 = s0&&t0&&u1 ? arr.get(ix,iy,iz+1)     : 0.0
    , w011 = s0&&t1&&u1 ? arr.get(ix,iy+1,iz+1)   : 0.0
    , w101 = s1&&t0&&u1 ? arr.get(ix+1,iy,iz+1)   : 0.0
    , w111 = s1&&t1&&u1 ? arr.get(ix+1,iy+1,iz+1) : 0.0
  return (1.0-fz) * ((1.0-fy) * ((1.0-fx)*w000 + fx*w100) + fy * ((1.0-fx)*w010 + fx*w110)) + fz * ((1.0-fy) * ((1.0-fx)*w001 + fx*w101) + fy * ((1.0-fx)*w011 + fx*w111))
}

function interpNd(arr) {
  var d = arr.shape.length|0
    , ix = new Array(d)
    , fx = new Array(d)
    , s0 = new Array(d)
    , s1 = new Array(d)
    , i, t
  for(i=0; i<d; ++i) {
    t = +arguments[i+1]
    ix[i] = Math.floor(t)
    fx[i] = t - ix[i]
    s0[i] = (0 <= ix[i]   && ix[i]   < arr.shape[i])
    s1[i] = (0 <= ix[i]+1 && ix[i]+1 < arr.shape[i])
  }
  var r = 0.0, j, w, idx
i_loop:
  for(i=0; i<(1<<d); ++i) {
    w = 1.0
    idx = arr.offset
    for(j=0; j<d; ++j) {
      if(i & (1<<j)) {
        if(!s1[j]) {
          continue i_loop
        }
        w *= fx[j]
        idx += arr.stride[j] * (ix[j] + 1)
      } else {
        if(!s0[j]) {
          continue i_loop
        }
        w *= 1.0 - fx[j]
        idx += arr.stride[j] * ix[j]
      }
    }
    r += w * arr.data[idx]
  }
  return r
}

function interpolate(arr, x, y, z) {
  switch(arr.shape.length) {
    case 0:
      return 0.0
    case 1:
      return interp1d(arr, x)
    case 2:
      return interp2d(arr, x, y)
    case 3:
      return interp3d(arr, x, y, z)
    default:
      return interpNd.apply(undefined, arguments)
  }
}
module.exports = interpolate
module.exports.d1 = interp1d
module.exports.d2 = interp2d
module.exports.d3 = interp3d

},{}],433:[function(_dereq_,module,exports){
"use strict"

var compile = _dereq_("cwise-compiler")

var EmptyProc = {
  body: "",
  args: [],
  thisVars: [],
  localVars: []
}

function fixup(x) {
  if(!x) {
    return EmptyProc
  }
  for(var i=0; i<x.args.length; ++i) {
    var a = x.args[i]
    if(i === 0) {
      x.args[i] = {name: a, lvalue:true, rvalue: !!x.rvalue, count:x.count||1 }
    } else {
      x.args[i] = {name: a, lvalue:false, rvalue:true, count: 1}
    }
  }
  if(!x.thisVars) {
    x.thisVars = []
  }
  if(!x.localVars) {
    x.localVars = []
  }
  return x
}

function pcompile(user_args) {
  return compile({
    args:     user_args.args,
    pre:      fixup(user_args.pre),
    body:     fixup(user_args.body),
    post:     fixup(user_args.proc),
    funcName: user_args.funcName
  })
}

function makeOp(user_args) {
  var args = []
  for(var i=0; i<user_args.args.length; ++i) {
    args.push("a"+i)
  }
  var wrapper = new Function("P", [
    "return function ", user_args.funcName, "_ndarrayops(", args.join(","), ") {P(", args.join(","), ");return a0}"
  ].join(""))
  return wrapper(pcompile(user_args))
}

var assign_ops = {
  add:  "+",
  sub:  "-",
  mul:  "*",
  div:  "/",
  mod:  "%",
  band: "&",
  bor:  "|",
  bxor: "^",
  lshift: "<<",
  rshift: ">>",
  rrshift: ">>>"
}
;(function(){
  for(var id in assign_ops) {
    var op = assign_ops[id]
    exports[id] = makeOp({
      args: ["array","array","array"],
      body: {args:["a","b","c"],
             body: "a=b"+op+"c"},
      funcName: id
    })
    exports[id+"eq"] = makeOp({
      args: ["array","array"],
      body: {args:["a","b"],
             body:"a"+op+"=b"},
      rvalue: true,
      funcName: id+"eq"
    })
    exports[id+"s"] = makeOp({
      args: ["array", "array", "scalar"],
      body: {args:["a","b","s"],
             body:"a=b"+op+"s"},
      funcName: id+"s"
    })
    exports[id+"seq"] = makeOp({
      args: ["array","scalar"],
      body: {args:["a","s"],
             body:"a"+op+"=s"},
      rvalue: true,
      funcName: id+"seq"
    })
  }
})();

var unary_ops = {
  not: "!",
  bnot: "~",
  neg: "-",
  recip: "1.0/"
}
;(function(){
  for(var id in unary_ops) {
    var op = unary_ops[id]
    exports[id] = makeOp({
      args: ["array", "array"],
      body: {args:["a","b"],
             body:"a="+op+"b"},
      funcName: id
    })
    exports[id+"eq"] = makeOp({
      args: ["array"],
      body: {args:["a"],
             body:"a="+op+"a"},
      rvalue: true,
      count: 2,
      funcName: id+"eq"
    })
  }
})();

var binary_ops = {
  and: "&&",
  or: "||",
  eq: "===",
  neq: "!==",
  lt: "<",
  gt: ">",
  leq: "<=",
  geq: ">="
}
;(function() {
  for(var id in binary_ops) {
    var op = binary_ops[id]
    exports[id] = makeOp({
      args: ["array","array","array"],
      body: {args:["a", "b", "c"],
             body:"a=b"+op+"c"},
      funcName: id
    })
    exports[id+"s"] = makeOp({
      args: ["array","array","scalar"],
      body: {args:["a", "b", "s"],
             body:"a=b"+op+"s"},
      funcName: id+"s"
    })
    exports[id+"eq"] = makeOp({
      args: ["array", "array"],
      body: {args:["a", "b"],
             body:"a=a"+op+"b"},
      rvalue:true,
      count:2,
      funcName: id+"eq"
    })
    exports[id+"seq"] = makeOp({
      args: ["array", "scalar"],
      body: {args:["a","s"],
             body:"a=a"+op+"s"},
      rvalue:true,
      count:2,
      funcName: id+"seq"
    })
  }
})();

var math_unary = [
  "abs",
  "acos",
  "asin",
  "atan",
  "ceil",
  "cos",
  "exp",
  "floor",
  "log",
  "round",
  "sin",
  "sqrt",
  "tan"
]
;(function() {
  for(var i=0; i<math_unary.length; ++i) {
    var f = math_unary[i]
    exports[f] = makeOp({
                    args: ["array", "array"],
                    pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
                    body: {args:["a","b"], body:"a=this_f(b)", thisVars:["this_f"]},
                    funcName: f
                  })
    exports[f+"eq"] = makeOp({
                      args: ["array"],
                      pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
                      body: {args: ["a"], body:"a=this_f(a)", thisVars:["this_f"]},
                      rvalue: true,
                      count: 2,
                      funcName: f+"eq"
                    })
  }
})();

var math_comm = [
  "max",
  "min",
  "atan2",
  "pow"
]
;(function(){
  for(var i=0; i<math_comm.length; ++i) {
    var f= math_comm[i]
    exports[f] = makeOp({
                  args:["array", "array", "array"],
                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
                  body: {args:["a","b","c"], body:"a=this_f(b,c)", thisVars:["this_f"]},
                  funcName: f
                })
    exports[f+"s"] = makeOp({
                  args:["array", "array", "scalar"],
                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
                  body: {args:["a","b","c"], body:"a=this_f(b,c)", thisVars:["this_f"]},
                  funcName: f+"s"
                  })
    exports[f+"eq"] = makeOp({ args:["array", "array"],
                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
                  body: {args:["a","b"], body:"a=this_f(a,b)", thisVars:["this_f"]},
                  rvalue: true,
                  count: 2,
                  funcName: f+"eq"
                  })
    exports[f+"seq"] = makeOp({ args:["array", "scalar"],
                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
                  body: {args:["a","b"], body:"a=this_f(a,b)", thisVars:["this_f"]},
                  rvalue:true,
                  count:2,
                  funcName: f+"seq"
                  })
  }
})();

var math_noncomm = [
  "atan2",
  "pow"
]
;(function(){
  for(var i=0; i<math_noncomm.length; ++i) {
    var f= math_noncomm[i]
    exports[f+"op"] = makeOp({
                  args:["array", "array", "array"],
                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
                  body: {args:["a","b","c"], body:"a=this_f(c,b)", thisVars:["this_f"]},
                  funcName: f+"op"
                })
    exports[f+"ops"] = makeOp({
                  args:["array", "array", "scalar"],
                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
                  body: {args:["a","b","c"], body:"a=this_f(c,b)", thisVars:["this_f"]},
                  funcName: f+"ops"
                  })
    exports[f+"opeq"] = makeOp({ args:["array", "array"],
                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
                  body: {args:["a","b"], body:"a=this_f(b,a)", thisVars:["this_f"]},
                  rvalue: true,
                  count: 2,
                  funcName: f+"opeq"
                  })
    exports[f+"opseq"] = makeOp({ args:["array", "scalar"],
                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
                  body: {args:["a","b"], body:"a=this_f(b,a)", thisVars:["this_f"]},
                  rvalue:true,
                  count:2,
                  funcName: f+"opseq"
                  })
  }
})();

exports.any = compile({
  args:["array"],
  pre: EmptyProc,
  body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "if(a){return true}", localVars: [], thisVars: []},
  post: {args:[], localVars:[], thisVars:[], body:"return false"},
  funcName: "any"
})

exports.all = compile({
  args:["array"],
  pre: EmptyProc,
  body: {args:[{name:"x", lvalue:false, rvalue:true, count:1}], body: "if(!x){return false}", localVars: [], thisVars: []},
  post: {args:[], localVars:[], thisVars:[], body:"return true"},
  funcName: "all"
})

exports.sum = compile({
  args:["array"],
  pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
  body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "this_s+=a", localVars: [], thisVars: ["this_s"]},
  post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
  funcName: "sum"
})

exports.prod = compile({
  args:["array"],
  pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=1"},
  body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "this_s*=a", localVars: [], thisVars: ["this_s"]},
  post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
  funcName: "prod"
})

exports.norm2squared = compile({
  args:["array"],
  pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
  body: {args:[{name:"a", lvalue:false, rvalue:true, count:2}], body: "this_s+=a*a", localVars: [], thisVars: ["this_s"]},
  post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
  funcName: "norm2squared"
})
  
exports.norm2 = compile({
  args:["array"],
  pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
  body: {args:[{name:"a", lvalue:false, rvalue:true, count:2}], body: "this_s+=a*a", localVars: [], thisVars: ["this_s"]},
  post: {args:[], localVars:[], thisVars:["this_s"], body:"return Math.sqrt(this_s)"},
  funcName: "norm2"
})
  

exports.norminf = compile({
  args:["array"],
  pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
  body: {args:[{name:"a", lvalue:false, rvalue:true, count:4}], body:"if(-a>this_s){this_s=-a}else if(a>this_s){this_s=a}", localVars: [], thisVars: ["this_s"]},
  post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
  funcName: "norminf"
})

exports.norm1 = compile({
  args:["array"],
  pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
  body: {args:[{name:"a", lvalue:false, rvalue:true, count:3}], body: "this_s+=a<0?-a:a", localVars: [], thisVars: ["this_s"]},
  post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
  funcName: "norm1"
})

exports.sup = compile({
  args: [ "array" ],
  pre:
   { body: "this_h=-Infinity",
     args: [],
     thisVars: [ "this_h" ],
     localVars: [] },
  body:
   { body: "if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_",
     args: [{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":2} ],
     thisVars: [ "this_h" ],
     localVars: [] },
  post:
   { body: "return this_h",
     args: [],
     thisVars: [ "this_h" ],
     localVars: [] }
 })

exports.inf = compile({
  args: [ "array" ],
  pre:
   { body: "this_h=Infinity",
     args: [],
     thisVars: [ "this_h" ],
     localVars: [] },
  body:
   { body: "if(_inline_1_arg0_<this_h)this_h=_inline_1_arg0_",
     args: [{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":2} ],
     thisVars: [ "this_h" ],
     localVars: [] },
  post:
   { body: "return this_h",
     args: [],
     thisVars: [ "this_h" ],
     localVars: [] }
 })

exports.argmin = compile({
  args:["index","array","shape"],
  pre:{
    body:"{this_v=Infinity;this_i=_inline_0_arg2_.slice(0)}",
    args:[
      {name:"_inline_0_arg0_",lvalue:false,rvalue:false,count:0},
      {name:"_inline_0_arg1_",lvalue:false,rvalue:false,count:0},
      {name:"_inline_0_arg2_",lvalue:false,rvalue:true,count:1}
      ],
    thisVars:["this_i","this_v"],
    localVars:[]},
  body:{
    body:"{if(_inline_1_arg1_<this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",
    args:[
      {name:"_inline_1_arg0_",lvalue:false,rvalue:true,count:2},
      {name:"_inline_1_arg1_",lvalue:false,rvalue:true,count:2}],
    thisVars:["this_i","this_v"],
    localVars:["_inline_1_k"]},
  post:{
    body:"{return this_i}",
    args:[],
    thisVars:["this_i"],
    localVars:[]}
})

exports.argmax = compile({
  args:["index","array","shape"],
  pre:{
    body:"{this_v=-Infinity;this_i=_inline_0_arg2_.slice(0)}",
    args:[
      {name:"_inline_0_arg0_",lvalue:false,rvalue:false,count:0},
      {name:"_inline_0_arg1_",lvalue:false,rvalue:false,count:0},
      {name:"_inline_0_arg2_",lvalue:false,rvalue:true,count:1}
      ],
    thisVars:["this_i","this_v"],
    localVars:[]},
  body:{
    body:"{if(_inline_1_arg1_>this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",
    args:[
      {name:"_inline_1_arg0_",lvalue:false,rvalue:true,count:2},
      {name:"_inline_1_arg1_",lvalue:false,rvalue:true,count:2}],
    thisVars:["this_i","this_v"],
    localVars:["_inline_1_k"]},
  post:{
    body:"{return this_i}",
    args:[],
    thisVars:["this_i"],
    localVars:[]}
})  

exports.random = makeOp({
  args: ["array"],
  pre: {args:[], body:"this_f=Math.random", thisVars:["this_f"]},
  body: {args: ["a"], body:"a=this_f()", thisVars:["this_f"]},
  funcName: "random"
})

exports.assign = makeOp({
  args:["array", "array"],
  body: {args:["a", "b"], body:"a=b"},
  funcName: "assign" })

exports.assigns = makeOp({
  args:["array", "scalar"],
  body: {args:["a", "b"], body:"a=b"},
  funcName: "assigns" })


exports.equals = compile({
  args:["array", "array"],
  pre: EmptyProc,
  body: {args:[{name:"x", lvalue:false, rvalue:true, count:1},
               {name:"y", lvalue:false, rvalue:true, count:1}], 
        body: "if(x!==y){return false}", 
        localVars: [], 
        thisVars: []},
  post: {args:[], localVars:[], thisVars:[], body:"return true"},
  funcName: "equals"
})



},{"cwise-compiler":134}],434:[function(_dereq_,module,exports){
"use strict"

var ndarray = _dereq_("ndarray")
var do_convert = _dereq_("./doConvert.js")

module.exports = function convert(arr, result) {
  var shape = [], c = arr, sz = 1
  while(Array.isArray(c)) {
    shape.push(c.length)
    sz *= c.length
    c = c[0]
  }
  if(shape.length === 0) {
    return ndarray()
  }
  if(!result) {
    result = ndarray(new Float64Array(sz), shape)
  }
  do_convert(result, arr)
  return result
}

},{"./doConvert.js":435,"ndarray":439}],435:[function(_dereq_,module,exports){
module.exports=_dereq_('cwise-compiler')({"args":["array","scalar","index"],"pre":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"body":{"body":"{\nvar _inline_1_v=_inline_1_arg1_,_inline_1_i\nfor(_inline_1_i=0;_inline_1_i<_inline_1_arg2_.length-1;++_inline_1_i) {\n_inline_1_v=_inline_1_v[_inline_1_arg2_[_inline_1_i]]\n}\n_inline_1_arg0_=_inline_1_v[_inline_1_arg2_[_inline_1_arg2_.length-1]]\n}","args":[{"name":"_inline_1_arg0_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_1_arg1_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_1_arg2_","lvalue":false,"rvalue":true,"count":4}],"thisVars":[],"localVars":["_inline_1_i","_inline_1_v"]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"funcName":"convert","blockSize":64})

},{"cwise-compiler":134}],436:[function(_dereq_,module,exports){
"use strict"

var pool = _dereq_("typedarray-pool")

var INSERTION_SORT_THRESHOLD = 32

function getMallocFree(dtype) {
  switch(dtype) {
    case "uint8":
      return [pool.mallocUint8, pool.freeUint8]
    case "uint16":
      return [pool.mallocUint16, pool.freeUint16]
    case "uint32":
      return [pool.mallocUint32, pool.freeUint32]
    case "int8":
      return [pool.mallocInt8, pool.freeInt8]
    case "int16":
      return [pool.mallocInt16, pool.freeInt16]
    case "int32":
      return [pool.mallocInt32, pool.freeInt32]
    case "float32":
      return [pool.mallocFloat, pool.freeFloat]
    case "float64":
      return [pool.mallocDouble, pool.freeDouble]
    default:
      return null
  }
}

function shapeArgs(dimension) {
  var args = []
  for(var i=0; i<dimension; ++i) {
    args.push("s"+i)
  }
  for(var i=0; i<dimension; ++i) {
    args.push("n"+i)
  }
  for(var i=1; i<dimension; ++i) {
    args.push("d"+i)
  }
  for(var i=1; i<dimension; ++i) {
    args.push("e"+i)
  }
  for(var i=1; i<dimension; ++i) {
    args.push("f"+i)
  }
  return args
}

function createInsertionSort(order, dtype) {

  var code = ["'use strict'"]
  var funcName = ["ndarrayInsertionSort", order.join("d"), dtype].join("")
  var funcArgs = ["left", "right", "data", "offset" ].concat(shapeArgs(order.length))
  var allocator = getMallocFree(dtype)
  
  var vars = [ "i,j,cptr,ptr=left*s0+offset" ]
  
  if(order.length > 1) {
    var scratch_shape = []
    for(var i=1; i<order.length; ++i) {
      vars.push("i"+i)
      scratch_shape.push("n"+i)
    }
    if(allocator) {
      vars.push("scratch=malloc(" + scratch_shape.join("*") + ")")
    } else {
      vars.push("scratch=new Array("+scratch_shape.join("*") + ")")
    }
    vars.push("dptr","sptr","a","b")
  } else {
    vars.push("scratch")
  }
  
  function dataRead(ptr) {
    if(dtype === "generic") {
      return ["data.get(", ptr, ")"].join("")
    }
    return ["data[",ptr,"]"].join("")
  }
  
  function dataWrite(ptr, v) {
    if(dtype === "generic") {
      return ["data.set(", ptr, ",", v, ")"].join("")
    }
    return ["data[",ptr,"]=",v].join("")
  }
  
  //Create function header
  code.push(
    ["function ", funcName, "(", funcArgs.join(","), "){var ", vars.join(",")].join(""),
      "for(i=left+1;i<=right;++i){",
        "j=i;ptr+=s0",
        "cptr=ptr")
  
  
  if(order.length > 1) {
  
    //Copy data into scratch
    code.push("dptr=0;sptr=ptr")
    for(var i=order.length-1; i>=0; --i) {
      var j = order[i]
      if(j === 0) {
        continue
      }
      code.push(["for(i",j,"=0;i",j,"<n",j,";++i",j,"){"].join(""))
    }
    code.push("scratch[dptr++]=",dataRead("sptr"))
    for(var i=0; i<order.length; ++i) {
      var j = order[i]
      if(j === 0) {
        continue
      }
      code.push("sptr+=d"+j,"}")
    }

    
    //Compare items in outer loop
    code.push("__g:while(j-->left){",
              "dptr=0",
              "sptr=cptr-s0")
    for(var i=1; i<order.length; ++i) {
      if(i === 1) {
        code.push("__l:")
      }
      code.push(["for(i",i,"=0;i",i,"<n",i,";++i",i,"){"].join(""))
    }
    code.push(["a=", dataRead("sptr"),"\nb=scratch[dptr]\nif(a<b){break __g}\nif(a>b){break __l}"].join(""))
    for(var i=order.length-1; i>=1; --i) {
      code.push(
        "sptr+=e"+i,
        "dptr+=f"+i,
        "}")
    }
    
    //Copy data back
    code.push("dptr=cptr;sptr=cptr-s0")
    for(var i=order.length-1; i>=0; --i) {
      var j = order[i]
      if(j === 0) {
        continue
      }
      code.push(["for(i",j,"=0;i",j,"<n",j,";++i",j,"){"].join(""))
    }
    code.push(dataWrite("dptr", dataRead("sptr")))
    for(var i=0; i<order.length; ++i) {
      var j = order[i]
      if(j === 0) {
        continue
      }
      code.push(["dptr+=d",j,";sptr+=d",j].join(""),"}")
    }
    
    //Close while loop
    code.push("cptr-=s0\n}")

    //Copy scratch into cptr
    code.push("dptr=cptr;sptr=0")
    for(var i=order.length-1; i>=0; --i) {
      var j = order[i]
      if(j === 0) {
        continue
      }
      code.push(["for(i",j,"=0;i",j,"<n",j,";++i",j,"){"].join(""))
    }
    code.push(dataWrite("dptr", "scratch[sptr++]"))
    for(var i=0; i<order.length; ++i) {
      var j = order[i]
      if(j === 0) {
        continue
      }
      code.push("dptr+=d"+j,"}")
    }
  } else {
    code.push("scratch=" + dataRead("ptr"),
              "while((j-->left)&&("+dataRead("cptr-s0")+">scratch)){",
                dataWrite("cptr", dataRead("cptr-s0")),
                "cptr-=s0",
              "}",
              dataWrite("cptr", "scratch"))
  }
  
  //Close outer loop body
  code.push("}")
  if(order.length > 1 && allocator) {
    code.push("free(scratch)")
  }
  code.push("} return " + funcName)
  
  //Compile and link function
  if(allocator) {
    var result = new Function("malloc", "free", code.join("\n"))
    return result(allocator[0], allocator[1])
  } else {
    var result = new Function(code.join("\n"))
    return result()
  }
}

function createQuickSort(order, dtype, insertionSort) {
  var code = [ "'use strict'" ]
  var funcName = ["ndarrayQuickSort", order.join("d"), dtype].join("")
  var funcArgs = ["left", "right", "data", "offset" ].concat(shapeArgs(order.length))
  var allocator = getMallocFree(dtype)
  var labelCounter=0
  
  code.push(["function ", funcName, "(", funcArgs.join(","), "){"].join(""))
  
  var vars = [
    "sixth=((right-left+1)/6)|0",
    "index1=left+sixth",
    "index5=right-sixth",
    "index3=(left+right)>>1",
    "index2=index3-sixth",
    "index4=index3+sixth",
    "el1=index1",
    "el2=index2",
    "el3=index3",
    "el4=index4",
    "el5=index5",
    "less=left+1",
    "great=right-1",
    "pivots_are_equal=true",
    "tmp",
    "tmp0",
    "x",
    "y",
    "z",
    "k",
    "ptr0",
    "ptr1",
    "ptr2",
    "comp_pivot1=0",
    "comp_pivot2=0",
    "comp=0"
  ]
  
  if(order.length > 1) {
    var ele_size = []
    for(var i=1; i<order.length; ++i) {
      ele_size.push("n"+i)
      vars.push("i"+i)
    }
    for(var i=0; i<8; ++i) {
      vars.push("b_ptr"+i)
    }
    vars.push(
      "ptr3",
      "ptr4",
      "ptr5",
      "ptr6",
      "ptr7",
      "pivot_ptr",
      "ptr_shift",
      "elementSize="+ele_size.join("*"))
    if(allocator) {
      vars.push("pivot1=malloc(elementSize)",
                "pivot2=malloc(elementSize)")
    } else {
      vars.push("pivot1=new Array(elementSize),pivot2=new Array(elementSize)")
    }
  } else {
    vars.push("pivot1", "pivot2")
  }
  
  //Initialize local variables
  code.push("var " + vars.join(","))
  
  function toPointer(v) {
    return ["(offset+",v,"*s0)"].join("")
  }
  
  function dataRead(ptr) {
    if(dtype === "generic") {
      return ["data.get(", ptr, ")"].join("")
    }
    return ["data[",ptr,"]"].join("")
  }
  
  function dataWrite(ptr, v) {
    if(dtype === "generic") {
      return ["data.set(", ptr, ",", v, ")"].join("")
    }
    return ["data[",ptr,"]=",v].join("")
  }
  
  function cacheLoop(ptrs, usePivot, body) {
    if(ptrs.length === 1) {
      code.push("ptr0="+toPointer(ptrs[0]))
    } else {
      for(var i=0; i<ptrs.length; ++i) {
        code.push(["b_ptr",i,"=s0*",ptrs[i]].join(""))
      }
    }
    if(usePivot) {
      code.push("pivot_ptr=0")
    }
    code.push("ptr_shift=offset")
    for(var i=order.length-1; i>=0; --i) {
      var j = order[i]
      if(j === 0) {
        continue
      }
      code.push(["for(i",j,"=0;i",j,"<n",j,";++i",j,"){"].join(""))
    }
    if(ptrs.length > 1) {
      for(var i=0; i<ptrs.length; ++i) {
        code.push(["ptr",i,"=b_ptr",i,"+ptr_shift"].join(""))
      }
    }
    code.push(body)
    if(usePivot) {
      code.push("++pivot_ptr")
    }
    for(var i=0; i<order.length; ++i) {
      var j = order[i]
      if(j === 0) {
        continue
      }
      if(ptrs.length>1) {
        code.push("ptr_shift+=d"+j)
      } else {
        code.push("ptr0+=d"+j)
      }
      code.push("}")
    }
  }
  
  function lexicoLoop(label, ptrs, usePivot, body) {
    if(ptrs.length === 1) {
      code.push("ptr0="+toPointer(ptrs[0]))
    } else {
      for(var i=0; i<ptrs.length; ++i) {
        code.push(["b_ptr",i,"=s0*",ptrs[i]].join(""))
      }
      code.push("ptr_shift=offset")
    }
    if(usePivot) {
      code.push("pivot_ptr=0")
    }
    if(label) {
      code.push(label+":")
    }
    for(var i=1; i<order.length; ++i) {
      code.push(["for(i",i,"=0;i",i,"<n",i,";++i",i,"){"].join(""))
    }
    if(ptrs.length > 1) {
      for(var i=0; i<ptrs.length; ++i) {
        code.push(["ptr",i,"=b_ptr",i,"+ptr_shift"].join(""))
      }
    }
    code.push(body)
    for(var i=order.length-1; i>=1; --i) {
      if(usePivot) {
        code.push("pivot_ptr+=f"+i)
      }
      if(ptrs.length > 1) {
        code.push("ptr_shift+=e"+i)
      } else {
        code.push("ptr0+=e"+i)
      }
      code.push("}")
    }
  }
  
  function cleanUp() {
    if(order.length > 1 && allocator) {
      code.push("free(pivot1)", "free(pivot2)")
    }
  }
  
  function compareSwap(a_id, b_id) {
    var a = "el"+a_id
    var b = "el"+b_id
    if(order.length > 1) {
      var lbl = "__l" + (++labelCounter)
      lexicoLoop(lbl, [a, b], false, [
        "comp=",dataRead("ptr0"),"-",dataRead("ptr1"),"\n",
        "if(comp>0){tmp0=", a, ";",a,"=",b,";", b,"=tmp0;break ", lbl,"}\n",
        "if(comp<0){break ", lbl, "}"
      ].join(""))
    } else {
      code.push(["if(", dataRead(toPointer(a)), ">", dataRead(toPointer(b)), "){tmp0=", a, ";",a,"=",b,";", b,"=tmp0}"].join(""))
    }
  }
  
  compareSwap(1, 2)
  compareSwap(4, 5)
  compareSwap(1, 3)
  compareSwap(2, 3)
  compareSwap(1, 4)
  compareSwap(3, 4)
  compareSwap(2, 5)
  compareSwap(2, 3)
  compareSwap(4, 5)
  
  if(order.length > 1) {
    cacheLoop(["el1", "el2", "el3", "el4", "el5", "index1", "index3", "index5"], true, [
      "pivot1[pivot_ptr]=",dataRead("ptr1"),"\n",
      "pivot2[pivot_ptr]=",dataRead("ptr3"),"\n",
      "pivots_are_equal=pivots_are_equal&&(pivot1[pivot_ptr]===pivot2[pivot_ptr])\n",
      "x=",dataRead("ptr0"),"\n",
      "y=",dataRead("ptr2"),"\n",
      "z=",dataRead("ptr4"),"\n",
      dataWrite("ptr5", "x"),"\n",
      dataWrite("ptr6", "y"),"\n",
      dataWrite("ptr7", "z")
    ].join(""))
  } else {
    code.push([
      "pivot1=", dataRead(toPointer("el2")), "\n",
      "pivot2=", dataRead(toPointer("el4")), "\n",
      "pivots_are_equal=pivot1===pivot2\n",
      "x=", dataRead(toPointer("el1")), "\n",
      "y=", dataRead(toPointer("el3")), "\n",
      "z=", dataRead(toPointer("el5")), "\n",
      dataWrite(toPointer("index1"), "x"), "\n",
      dataWrite(toPointer("index3"), "y"), "\n",
      dataWrite(toPointer("index5"), "z")
    ].join(""))
  }
  

  function moveElement(dst, src) {
    if(order.length > 1) {
      cacheLoop([dst, src], false,
        dataWrite("ptr0", dataRead("ptr1"))
      )
    } else {
      code.push(dataWrite(toPointer(dst), dataRead(toPointer(src))))
    }
  }
  
  moveElement("index2", "left")
  moveElement("index4", "right")
  
  function comparePivot(result, ptr, n) {
    if(order.length > 1) {
      var lbl = "__l" + (++labelCounter)
      lexicoLoop(lbl, [ptr], true, [
        result,"=",dataRead("ptr0"),"-pivot",n,"[pivot_ptr]\n",
        "if(",result,"!==0){break ", lbl, "}"
      ].join(""))
    } else {
      code.push([result,"=", dataRead(toPointer(ptr)), "-pivot", n].join(""))
    }
  }
  
  function swapElements(a, b) {
    if(order.length > 1) {
      cacheLoop([a,b],false,[
        "tmp=",dataRead("ptr0"),"\n",
        dataWrite("ptr0", dataRead("ptr1")),"\n",
        dataWrite("ptr1", "tmp")
      ].join(""))
    } else {
      code.push([
        "ptr0=",toPointer(a),"\n",
        "ptr1=",toPointer(b),"\n",
        "tmp=",dataRead("ptr0"),"\n",
        dataWrite("ptr0", dataRead("ptr1")),"\n",
        dataWrite("ptr1", "tmp")
      ].join(""))
    }
  }
  
  function tripleSwap(k, less, great) {
    if(order.length > 1) {
      cacheLoop([k,less,great], false, [
        "tmp=",dataRead("ptr0"),"\n",
        dataWrite("ptr0", dataRead("ptr1")),"\n",
        dataWrite("ptr1", dataRead("ptr2")),"\n",
        dataWrite("ptr2", "tmp")
      ].join(""))
      code.push("++"+less, "--"+great)
    } else {
      code.push([
        "ptr0=",toPointer(k),"\n",
        "ptr1=",toPointer(less),"\n",
        "ptr2=",toPointer(great),"\n",
        "++",less,"\n",
        "--",great,"\n",
        "tmp=", dataRead("ptr0"), "\n",
        dataWrite("ptr0", dataRead("ptr1")), "\n",
        dataWrite("ptr1", dataRead("ptr2")), "\n",
        dataWrite("ptr2", "tmp")
      ].join(""))
    }
  }
  
  function swapAndDecrement(k, great) {
    swapElements(k, great)
    code.push("--"+great)
  }
    
  code.push("if(pivots_are_equal){")
    //Pivots are equal case
    code.push("for(k=less;k<=great;++k){")
      comparePivot("comp", "k", 1)
      code.push("if(comp===0){continue}")
      code.push("if(comp<0){")
        code.push("if(k!==less){")
          swapElements("k", "less")
        code.push("}")
        code.push("++less")
      code.push("}else{")
        code.push("while(true){")
          comparePivot("comp", "great", 1)
          code.push("if(comp>0){")
            code.push("great--")
          code.push("}else if(comp<0){")
            tripleSwap("k", "less", "great")
            code.push("break")
          code.push("}else{")
            swapAndDecrement("k", "great")
            code.push("break")
          code.push("}")
        code.push("}")
      code.push("}")
    code.push("}")
  code.push("}else{")
    //Pivots not equal case
    code.push("for(k=less;k<=great;++k){")
      comparePivot("comp_pivot1", "k", 1)
      code.push("if(comp_pivot1<0){")
        code.push("if(k!==less){")
          swapElements("k", "less")
        code.push("}")
        code.push("++less")
      code.push("}else{")
        comparePivot("comp_pivot2", "k", 2)
        code.push("if(comp_pivot2>0){")
          code.push("while(true){")
            comparePivot("comp", "great", 2)
            code.push("if(comp>0){")
              code.push("if(--great<k){break}")
              code.push("continue")
            code.push("}else{")
              comparePivot("comp", "great", 1)
              code.push("if(comp<0){")
                tripleSwap("k", "less", "great")
              code.push("}else{")
                swapAndDecrement("k", "great")
              code.push("}")
              code.push("break")
            code.push("}")
          code.push("}")
        code.push("}")
      code.push("}")
    code.push("}")
  code.push("}")
  
  //Move pivots to correct place
  function storePivot(mem_dest, pivot_dest, pivot) {
    if(order.length>1) {
      cacheLoop([mem_dest, pivot_dest], true, [
        dataWrite("ptr0", dataRead("ptr1")), "\n",
        dataWrite("ptr1", ["pivot",pivot,"[pivot_ptr]"].join(""))
      ].join(""))
    } else {
      code.push(
          dataWrite(toPointer(mem_dest), dataRead(toPointer(pivot_dest))),
          dataWrite(toPointer(pivot_dest), "pivot"+pivot))
    }
  }
  
  storePivot("left", "(less-1)", 1)
  storePivot("right", "(great+1)", 2)

  //Recursive sort call
  function doSort(left, right) {
    code.push([
      "if((",right,"-",left,")<=",INSERTION_SORT_THRESHOLD,"){\n",
        "insertionSort(", left, ",", right, ",data,offset,", shapeArgs(order.length).join(","), ")\n",
      "}else{\n",
        funcName, "(", left, ",", right, ",data,offset,", shapeArgs(order.length).join(","), ")\n",
      "}"
    ].join(""))
  }
  doSort("left", "(less-2)")
  doSort("(great+2)", "right")
  
  //If pivots are equal, then early out
  code.push("if(pivots_are_equal){")
    cleanUp()
    code.push("return")
  code.push("}")
  
  function walkPointer(ptr, pivot, body) {
    if(order.length > 1) {
      code.push(["__l",++labelCounter,":while(true){"].join(""))
      cacheLoop([ptr], true, [
        "if(", dataRead("ptr0"), "!==pivot", pivot, "[pivot_ptr]){break __l", labelCounter, "}"
      ].join(""))
      code.push(body, "}")
    } else {
      code.push(["while(", dataRead(toPointer(ptr)), "===pivot", pivot, "){", body, "}"].join(""))
    }
  }
  
  //Check bounds
  code.push("if(less<index1&&great>index5){")
  
    walkPointer("less", 1, "++less")
    walkPointer("great", 2, "--great")
  
    code.push("for(k=less;k<=great;++k){")
      comparePivot("comp_pivot1", "k", 1)
      code.push("if(comp_pivot1===0){")
        code.push("if(k!==less){")
          swapElements("k", "less")
        code.push("}")
        code.push("++less")
      code.push("}else{")
        comparePivot("comp_pivot2", "k", 2)
        code.push("if(comp_pivot2===0){")
          code.push("while(true){")
            comparePivot("comp", "great", 2)
            code.push("if(comp===0){")
              code.push("if(--great<k){break}")
              code.push("continue")
            code.push("}else{")
              comparePivot("comp", "great", 1)
              code.push("if(comp<0){")
                tripleSwap("k", "less", "great")
              code.push("}else{")
                swapAndDecrement("k", "great")
              code.push("}")
              code.push("break")
            code.push("}")
          code.push("}")
        code.push("}")
      code.push("}")
    code.push("}")
  code.push("}")
  
  //Clean up and do a final sorting pass
  cleanUp()
  doSort("less", "great")
 
  //Close off main loop
  code.push("}return " + funcName)
  
  //Compile and link
  if(order.length > 1 && allocator) {
    var compiled = new Function("insertionSort", "malloc", "free", code.join("\n"))
    return compiled(insertionSort, allocator[0], allocator[1])
  }
  var compiled = new Function("insertionSort", code.join("\n"))
  return compiled(insertionSort)
}

function compileSort(order, dtype) {
  var code = ["'use strict'"]
  var funcName = ["ndarraySortWrapper", order.join("d"), dtype].join("")
  var funcArgs = [ "array" ]
  
  code.push(["function ", funcName, "(", funcArgs.join(","), "){"].join(""))
  
  //Unpack local variables from array
  var vars = ["data=array.data,offset=array.offset|0,shape=array.shape,stride=array.stride"]
  for(var i=0; i<order.length; ++i) {
    vars.push(["s",i,"=stride[",i,"]|0,n",i,"=shape[",i,"]|0"].join(""))
  }
  
  var scratch_stride = new Array(order.length)
  var nprod = []
  for(var i=0; i<order.length; ++i) {
    var k = order[i]
    if(k === 0) {
      continue
    }
    if(nprod.length === 0) {
      scratch_stride[k] = "1"
    } else {
      scratch_stride[k] = nprod.join("*")
    }
    nprod.push("n"+k)
  }
  
  var p = -1, q = -1
  for(var i=0; i<order.length; ++i) {
    var j = order[i]
    if(j !== 0) {
      if(p > 0) {
        vars.push(["d",j,"=s",j,"-d",p,"*n",p].join(""))
      } else {
        vars.push(["d",j,"=s",j].join(""))
      }
      p = j
    }
    var k = order.length-1-i
    if(k !== 0) {
      if(q > 0) {
        vars.push(["e",k,"=s",k,"-e",q,"*n",q,
                  ",f",k,"=",scratch_stride[k],"-f",q,"*n",q].join(""))
      } else {
        vars.push(["e",k,"=s",k,",f",k,"=",scratch_stride[k]].join(""))
      }
      q = k
    }
  }
  
  //Declare local variables
  code.push("var " + vars.join(","))
  
  //Create arguments for subroutine
  var sortArgs = ["0", "n0-1", "data", "offset"].concat(shapeArgs(order.length))
  
  //Call main sorting routine
  code.push([
    "if(n0<=",INSERTION_SORT_THRESHOLD,"){",
      "insertionSort(", sortArgs.join(","), ")}else{",
      "quickSort(", sortArgs.join(","),
    ")}"
  ].join(""))
  
  //Return
  code.push("}return " + funcName)
  
  //Link everything together
  var result = new Function("insertionSort", "quickSort", code.join("\n"))
  var insertionSort = createInsertionSort(order, dtype)
  var quickSort = createQuickSort(order, dtype, insertionSort)
  return result(insertionSort, quickSort)
}

module.exports = compileSort
},{"typedarray-pool":526}],437:[function(_dereq_,module,exports){
"use strict"

var compile = _dereq_("./lib/compile_sort.js")
var CACHE = {}

function sort(array) {
  var order = array.order
  var dtype = array.dtype
  var typeSig = [order, dtype ]
  var typeName = typeSig.join(":")
  var compiled = CACHE[typeName]
  if(!compiled) {
    CACHE[typeName] = compiled = compile(order, dtype)
  }
  compiled(array)
  return array
}

module.exports = sort
},{"./lib/compile_sort.js":436}],438:[function(_dereq_,module,exports){
'use strict'

var interp  = _dereq_('ndarray-linear-interpolate')


var do_warp = _dereq_('cwise/lib/wrapper')({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=new Array(_inline_3_arg4_)}","args":[{"name":"_inline_3_arg0_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_3_arg1_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_3_arg2_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_3_arg3_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_3_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_4_arg2_(this_warped,_inline_4_arg0_),_inline_4_arg1_=_inline_4_arg3_.apply(void 0,this_warped)}","args":[{"name":"_inline_4_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_4_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_4_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_4_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_4_arg4_","lvalue":false,"rvalue":false,"count":0}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warpND","blockSize":64})

var do_warp_1 = _dereq_('cwise/lib/wrapper')({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=[0]}","args":[],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_7_arg2_(this_warped,_inline_7_arg0_),_inline_7_arg1_=_inline_7_arg3_(_inline_7_arg4_,this_warped[0])}","args":[{"name":"_inline_7_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_7_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_7_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_7_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_7_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warp1D","blockSize":64})

var do_warp_2 = _dereq_('cwise/lib/wrapper')({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=[0,0]}","args":[],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_10_arg2_(this_warped,_inline_10_arg0_),_inline_10_arg1_=_inline_10_arg3_(_inline_10_arg4_,this_warped[0],this_warped[1])}","args":[{"name":"_inline_10_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_10_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_10_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_10_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_10_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warp2D","blockSize":64})

var do_warp_3 = _dereq_('cwise/lib/wrapper')({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=[0,0,0]}","args":[],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_13_arg2_(this_warped,_inline_13_arg0_),_inline_13_arg1_=_inline_13_arg3_(_inline_13_arg4_,this_warped[0],this_warped[1],this_warped[2])}","args":[{"name":"_inline_13_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_13_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_13_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_13_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_13_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warp3D","blockSize":64})

module.exports = function warp(dest, src, func) {
  switch(src.shape.length) {
    case 1:
      do_warp_1(dest, func, interp.d1, src)
      break
    case 2:
      do_warp_2(dest, func, interp.d2, src)
      break
    case 3:
      do_warp_3(dest, func, interp.d3, src)
      break
    default:
      do_warp(dest, func, interp.bind(undefined, src), src.shape.length)
      break
  }
  return dest
}

},{"cwise/lib/wrapper":137,"ndarray-linear-interpolate":432}],439:[function(_dereq_,module,exports){
var iota = _dereq_("iota-array")
var isBuffer = _dereq_("is-buffer")

var hasTypedArrays  = ((typeof Float64Array) !== "undefined")

function compare1st(a, b) {
  return a[0] - b[0]
}

function order() {
  var stride = this.stride
  var terms = new Array(stride.length)
  var i
  for(i=0; i<terms.length; ++i) {
    terms[i] = [Math.abs(stride[i]), i]
  }
  terms.sort(compare1st)
  var result = new Array(terms.length)
  for(i=0; i<result.length; ++i) {
    result[i] = terms[i][1]
  }
  return result
}

function compileConstructor(dtype, dimension) {
  var className = ["View", dimension, "d", dtype].join("")
  if(dimension < 0) {
    className = "View_Nil" + dtype
  }
  var useGetters = (dtype === "generic")

  if(dimension === -1) {
    //Special case for trivial arrays
    var code =
      "function "+className+"(a){this.data=a;};\
var proto="+className+".prototype;\
proto.dtype='"+dtype+"';\
proto.index=function(){return -1};\
proto.size=0;\
proto.dimension=-1;\
proto.shape=proto.stride=proto.order=[];\
proto.lo=proto.hi=proto.transpose=proto.step=\
function(){return new "+className+"(this.data);};\
proto.get=proto.set=function(){};\
proto.pick=function(){return null};\
return function construct_"+className+"(a){return new "+className+"(a);}"
    var procedure = new Function(code)
    return procedure()
  } else if(dimension === 0) {
    //Special case for 0d arrays
    var code =
      "function "+className+"(a,d) {\
this.data = a;\
this.offset = d\
};\
var proto="+className+".prototype;\
proto.dtype='"+dtype+"';\
proto.index=function(){return this.offset};\
proto.dimension=0;\
proto.size=1;\
proto.shape=\
proto.stride=\
proto.order=[];\
proto.lo=\
proto.hi=\
proto.transpose=\
proto.step=function "+className+"_copy() {\
return new "+className+"(this.data,this.offset)\
};\
proto.pick=function "+className+"_pick(){\
return TrivialArray(this.data);\
};\
proto.valueOf=proto.get=function "+className+"_get(){\
return "+(useGetters ? "this.data.get(this.offset)" : "this.data[this.offset]")+
"};\
proto.set=function "+className+"_set(v){\
return "+(useGetters ? "this.data.set(this.offset,v)" : "this.data[this.offset]=v")+"\
};\
return function construct_"+className+"(a,b,c,d){return new "+className+"(a,d)}"
    var procedure = new Function("TrivialArray", code)
    return procedure(CACHED_CONSTRUCTORS[dtype][0])
  }

  var code = ["'use strict'"]

  //Create constructor for view
  var indices = iota(dimension)
  var args = indices.map(function(i) { return "i"+i })
  var index_str = "this.offset+" + indices.map(function(i) {
        return "this.stride[" + i + "]*i" + i
      }).join("+")
  var shapeArg = indices.map(function(i) {
      return "b"+i
    }).join(",")
  var strideArg = indices.map(function(i) {
      return "c"+i
    }).join(",")
  code.push(
    "function "+className+"(a," + shapeArg + "," + strideArg + ",d){this.data=a",
      "this.shape=[" + shapeArg + "]",
      "this.stride=[" + strideArg + "]",
      "this.offset=d|0}",
    "var proto="+className+".prototype",
    "proto.dtype='"+dtype+"'",
    "proto.dimension="+dimension)

  //view.size:
  code.push("Object.defineProperty(proto,'size',{get:function "+className+"_size(){\
return "+indices.map(function(i) { return "this.shape["+i+"]" }).join("*"),
"}})")

  //view.order:
  if(dimension === 1) {
    code.push("proto.order=[0]")
  } else {
    code.push("Object.defineProperty(proto,'order',{get:")
    if(dimension < 4) {
      code.push("function "+className+"_order(){")
      if(dimension === 2) {
        code.push("return (Math.abs(this.stride[0])>Math.abs(this.stride[1]))?[1,0]:[0,1]}})")
      } else if(dimension === 3) {
        code.push(
"var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);\
if(s0>s1){\
if(s1>s2){\
return [2,1,0];\
}else if(s0>s2){\
return [1,2,0];\
}else{\
return [1,0,2];\
}\
}else if(s0>s2){\
return [2,0,1];\
}else if(s2>s1){\
return [0,1,2];\
}else{\
return [0,2,1];\
}}})")
      }
    } else {
      code.push("ORDER})")
    }
  }

  //view.set(i0, ..., v):
  code.push(
"proto.set=function "+className+"_set("+args.join(",")+",v){")
  if(useGetters) {
    code.push("return this.data.set("+index_str+",v)}")
  } else {
    code.push("return this.data["+index_str+"]=v}")
  }

  //view.get(i0, ...):
  code.push("proto.get=function "+className+"_get("+args.join(",")+"){")
  if(useGetters) {
    code.push("return this.data.get("+index_str+")}")
  } else {
    code.push("return this.data["+index_str+"]}")
  }

  //view.index:
  code.push(
    "proto.index=function "+className+"_index(", args.join(), "){return "+index_str+"}")

  //view.hi():
  code.push("proto.hi=function "+className+"_hi("+args.join(",")+"){return new "+className+"(this.data,"+
    indices.map(function(i) {
      return ["(typeof i",i,"!=='number'||i",i,"<0)?this.shape[", i, "]:i", i,"|0"].join("")
    }).join(",")+","+
    indices.map(function(i) {
      return "this.stride["+i + "]"
    }).join(",")+",this.offset)}")

  //view.lo():
  var a_vars = indices.map(function(i) { return "a"+i+"=this.shape["+i+"]" })
  var c_vars = indices.map(function(i) { return "c"+i+"=this.stride["+i+"]" })
  code.push("proto.lo=function "+className+"_lo("+args.join(",")+"){var b=this.offset,d=0,"+a_vars.join(",")+","+c_vars.join(","))
  for(var i=0; i<dimension; ++i) {
    code.push(
"if(typeof i"+i+"==='number'&&i"+i+">=0){\
d=i"+i+"|0;\
b+=c"+i+"*d;\
a"+i+"-=d}")
  }
  code.push("return new "+className+"(this.data,"+
    indices.map(function(i) {
      return "a"+i
    }).join(",")+","+
    indices.map(function(i) {
      return "c"+i
    }).join(",")+",b)}")

  //view.step():
  code.push("proto.step=function "+className+"_step("+args.join(",")+"){var "+
    indices.map(function(i) {
      return "a"+i+"=this.shape["+i+"]"
    }).join(",")+","+
    indices.map(function(i) {
      return "b"+i+"=this.stride["+i+"]"
    }).join(",")+",c=this.offset,d=0,ceil=Math.ceil")
  for(var i=0; i<dimension; ++i) {
    code.push(
"if(typeof i"+i+"==='number'){\
d=i"+i+"|0;\
if(d<0){\
c+=b"+i+"*(a"+i+"-1);\
a"+i+"=ceil(-a"+i+"/d)\
}else{\
a"+i+"=ceil(a"+i+"/d)\
}\
b"+i+"*=d\
}")
  }
  code.push("return new "+className+"(this.data,"+
    indices.map(function(i) {
      return "a" + i
    }).join(",")+","+
    indices.map(function(i) {
      return "b" + i
    }).join(",")+",c)}")

  //view.transpose():
  var tShape = new Array(dimension)
  var tStride = new Array(dimension)
  for(var i=0; i<dimension; ++i) {
    tShape[i] = "a[i"+i+"]"
    tStride[i] = "b[i"+i+"]"
  }
  code.push("proto.transpose=function "+className+"_transpose("+args+"){"+
    args.map(function(n,idx) { return n + "=(" + n + "===undefined?" + idx + ":" + n + "|0)"}).join(";"),
    "var a=this.shape,b=this.stride;return new "+className+"(this.data,"+tShape.join(",")+","+tStride.join(",")+",this.offset)}")

  //view.pick():
  code.push("proto.pick=function "+className+"_pick("+args+"){var a=[],b=[],c=this.offset")
  for(var i=0; i<dimension; ++i) {
    code.push("if(typeof i"+i+"==='number'&&i"+i+">=0){c=(c+this.stride["+i+"]*i"+i+")|0}else{a.push(this.shape["+i+"]);b.push(this.stride["+i+"])}")
  }
  code.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}")

  //Add return statement
  code.push("return function construct_"+className+"(data,shape,stride,offset){return new "+className+"(data,"+
    indices.map(function(i) {
      return "shape["+i+"]"
    }).join(",")+","+
    indices.map(function(i) {
      return "stride["+i+"]"
    }).join(",")+",offset)}")

  //Compile procedure
  var procedure = new Function("CTOR_LIST", "ORDER", code.join("\n"))
  return procedure(CACHED_CONSTRUCTORS[dtype], order)
}

function arrayDType(data) {
  if(isBuffer(data)) {
    return "buffer"
  }
  if(hasTypedArrays) {
    switch(Object.prototype.toString.call(data)) {
      case "[object Float64Array]":
        return "float64"
      case "[object Float32Array]":
        return "float32"
      case "[object Int8Array]":
        return "int8"
      case "[object Int16Array]":
        return "int16"
      case "[object Int32Array]":
        return "int32"
      case "[object Uint8Array]":
        return "uint8"
      case "[object Uint16Array]":
        return "uint16"
      case "[object Uint32Array]":
        return "uint32"
      case "[object Uint8ClampedArray]":
        return "uint8_clamped"
    }
  }
  if(Array.isArray(data)) {
    return "array"
  }
  return "generic"
}

var CACHED_CONSTRUCTORS = {
  "float32":[],
  "float64":[],
  "int8":[],
  "int16":[],
  "int32":[],
  "uint8":[],
  "uint16":[],
  "uint32":[],
  "array":[],
  "uint8_clamped":[],
  "buffer":[],
  "generic":[]
}

;(function() {
  for(var id in CACHED_CONSTRUCTORS) {
    CACHED_CONSTRUCTORS[id].push(compileConstructor(id, -1))
  }
});

function wrappedNDArrayCtor(data, shape, stride, offset) {
  if(data === undefined) {
    var ctor = CACHED_CONSTRUCTORS.array[0]
    return ctor([])
  } else if(typeof data === "number") {
    data = [data]
  }
  if(shape === undefined) {
    shape = [ data.length ]
  }
  var d = shape.length
  if(stride === undefined) {
    stride = new Array(d)
    for(var i=d-1, sz=1; i>=0; --i) {
      stride[i] = sz
      sz *= shape[i]
    }
  }
  if(offset === undefined) {
    offset = 0
    for(var i=0; i<d; ++i) {
      if(stride[i] < 0) {
        offset -= (shape[i]-1)*stride[i]
      }
    }
  }
  var dtype = arrayDType(data)
  var ctor_list = CACHED_CONSTRUCTORS[dtype]
  while(ctor_list.length <= d+1) {
    ctor_list.push(compileConstructor(dtype, ctor_list.length-1))
  }
  var ctor = ctor_list[d+1]
  return ctor(data, shape, stride, offset)
}

module.exports = wrappedNDArrayCtor

},{"iota-array":405,"is-buffer":407}],440:[function(_dereq_,module,exports){
"use strict"

var doubleBits = _dereq_("double-bits")

var SMALLEST_DENORM = Math.pow(2, -1074)
var UINT_MAX = (-1)>>>0

module.exports = nextafter

function nextafter(x, y) {
  if(isNaN(x) || isNaN(y)) {
    return NaN
  }
  if(x === y) {
    return x
  }
  if(x === 0) {
    if(y < 0) {
      return -SMALLEST_DENORM
    } else {
      return SMALLEST_DENORM
    }
  }
  var hi = doubleBits.hi(x)
  var lo = doubleBits.lo(x)
  if((y > x) === (x > 0)) {
    if(lo === UINT_MAX) {
      hi += 1
      lo = 0
    } else {
      lo += 1
    }
  } else {
    if(lo === 0) {
      lo = UINT_MAX
      hi -= 1
    } else {
      lo -= 1
    }
  }
  return doubleBits.pack(lo, hi)
}
},{"double-bits":155}],441:[function(_dereq_,module,exports){

var π = Math.PI
var _120 = radians(120)

module.exports = normalize

/**
 * describe `path` in terms of cubic bézier 
 * curves and move commands
 *
 * @param {Array} path
 * @return {Array}
 */

function normalize(path){
	// init state
	var prev
	var result = []
	var bezierX = 0
	var bezierY = 0
	var startX = 0
	var startY = 0
	var quadX = null
	var quadY = null
	var x = 0
	var y = 0

	for (var i = 0, len = path.length; i < len; i++) {
		var seg = path[i]
		var command = seg[0]
		switch (command) {
			case 'M':
				startX = seg[1]
				startY = seg[2]
				break
			case 'A':
				seg = arc(x, y,seg[1],seg[2],radians(seg[3]),seg[4],seg[5],seg[6],seg[7])
				// split multi part
				seg.unshift('C')
				if (seg.length > 7) {
					result.push(seg.splice(0, 7))
					seg.unshift('C')
				}
				break
			case 'S':
				// default control point
				var cx = x
				var cy = y
				if (prev == 'C' || prev == 'S') {
					cx += cx - bezierX // reflect the previous command's control
					cy += cy - bezierY // point relative to the current point
				}
				seg = ['C', cx, cy, seg[1], seg[2], seg[3], seg[4]]
				break
			case 'T':
				if (prev == 'Q' || prev == 'T') {
					quadX = x * 2 - quadX // as with 'S' reflect previous control point
					quadY = y * 2 - quadY
				} else {
					quadX = x
					quadY = y
				}
				seg = quadratic(x, y, quadX, quadY, seg[1], seg[2])
				break
			case 'Q':
				quadX = seg[1]
				quadY = seg[2]
				seg = quadratic(x, y, seg[1], seg[2], seg[3], seg[4])
				break
			case 'L':
				seg = line(x, y, seg[1], seg[2])
				break
			case 'H':
				seg = line(x, y, seg[1], y)
				break
			case 'V':
				seg = line(x, y, x, seg[1])
				break
			case 'Z':
				seg = line(x, y, startX, startY)
				break
		}

		// update state
		prev = command
		x = seg[seg.length - 2]
		y = seg[seg.length - 1]
		if (seg.length > 4) {
			bezierX = seg[seg.length - 4]
			bezierY = seg[seg.length - 3]
		} else {
			bezierX = x
			bezierY = y
		}
		result.push(seg)
	}

	return result
}

function line(x1, y1, x2, y2){
	return ['C', x1, y1, x2, y2, x2, y2]
}

function quadratic(x1, y1, cx, cy, x2, y2){
	return [
		'C',
		x1/3 + (2/3) * cx,
		y1/3 + (2/3) * cy,
		x2/3 + (2/3) * cx,
		y2/3 + (2/3) * cy,
		x2,
		y2
	]
}

// This function is ripped from 
// github.com/DmitryBaranovskiy/raphael/blob/4d97d4/raphael.js#L2216-L2304 
// which references w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
// TODO: make it human readable

function arc(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) {
	if (!recursive) {
		var xy = rotate(x1, y1, -angle)
		x1 = xy.x
		y1 = xy.y
		xy = rotate(x2, y2, -angle)
		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 = Math.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)
			* Math.sqrt(Math.abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x)))
		if (k == Infinity) k = 1 // neutralize
		var cx = k * rx * y / ry + (x1 + x2) / 2
		var cy = k * -ry * x / rx + (y1 + y2) / 2
		var f1 = Math.asin(((y1 - cy) / ry).toFixed(9))
		var f2 = Math.asin(((y2 - cy) / ry).toFixed(9))

		f1 = x1 < cx ? π - f1 : f1
		f2 = x2 < cx ? π - f2 : f2
		if (f1 < 0) f1 = π * 2 + f1
		if (f2 < 0) f2 = π * 2 + f2
		if (sweep_flag && f1 > f2) f1 = f1 - π * 2
		if (!sweep_flag && f2 > f1) f2 = f2 - π * 2
	} else {
		f1 = recursive[0]
		f2 = recursive[1]
		cx = recursive[2]
		cy = recursive[3]
	}
	// greater than 120 degrees requires multiple segments
	if (Math.abs(f2 - f1) > _120) {
		var f2old = f2
		var x2old = x2
		var y2old = y2
		f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1)
		x2 = cx + rx * Math.cos(f2)
		y2 = cy + ry * Math.sin(f2)
		var res = arc(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy])
	}
	var t = Math.tan((f2 - f1) / 4)
	var hx = 4 / 3 * rx * t
	var hy = 4 / 3 * ry * t
	var curve = [
		2 * x1 - (x1 + hx * Math.sin(f1)),
		2 * y1 - (y1 - hy * Math.cos(f1)),
		x2 + hx * Math.sin(f2),
		y2 - hy * Math.cos(f2),
		x2,
		y2
	]
	if (recursive) return curve
	if (res) curve = curve.concat(res)
	for (var i = 0; i < curve.length;) {
		var rot = rotate(curve[i], curve[i+1], angle)
		curve[i++] = rot.x
		curve[i++] = rot.y
	}
	return curve
}

function rotate(x, y, rad){
	return {
		x: x * Math.cos(rad) - y * Math.sin(rad),
		y: x * Math.sin(rad) + y * Math.cos(rad)
	}
}

function radians(degress){
	return degress * (π / 180)
}

},{}],442:[function(_dereq_,module,exports){
var DEFAULT_NORMALS_EPSILON = 1e-6;
var DEFAULT_FACE_EPSILON = 1e-6;

//Estimate the vertex normals of a mesh
exports.vertexNormals = function(faces, positions, specifiedEpsilon) {

  var N         = positions.length;
  var normals   = new Array(N);
  var epsilon   = specifiedEpsilon === void(0) ? DEFAULT_NORMALS_EPSILON : specifiedEpsilon;

  //Initialize normal array
  for(var i=0; i<N; ++i) {
    normals[i] = [0.0, 0.0, 0.0];
  }

  //Walk over all the faces and add per-vertex contribution to normal weights
  for(var i=0; i<faces.length; ++i) {
    var f = faces[i];
    var p = 0;
    var c = f[f.length-1];
    var n = f[0];
    for(var j=0; j<f.length; ++j) {

      //Shift indices back
      p = c;
      c = n;
      n = f[(j+1) % f.length];

      var v0 = positions[p];
      var v1 = positions[c];
      var v2 = positions[n];

      //Compute infineteismal arcs
      var d01 = new Array(3);
      var m01 = 0.0;
      var d21 = new Array(3);
      var m21 = 0.0;
      for(var k=0; k<3; ++k) {
        d01[k] = v0[k]  - v1[k];
        m01   += d01[k] * d01[k];
        d21[k] = v2[k]  - v1[k];
        m21   += d21[k] * d21[k];
      }

      //Accumulate values in normal
      if(m01 * m21 > epsilon) {
        var norm = normals[c];
        var w = 1.0 / Math.sqrt(m01 * m21);
        for(var k=0; k<3; ++k) {
          var u = (k+1)%3;
          var v = (k+2)%3;
          norm[k] += w * (d21[u] * d01[v] - d21[v] * d01[u]);
        }
      }
    }
  }

  //Scale all normals to unit length
  for(var i=0; i<N; ++i) {
    var norm = normals[i];
    var m = 0.0;
    for(var k=0; k<3; ++k) {
      m += norm[k] * norm[k];
    }
    if(m > epsilon) {
      var w = 1.0 / Math.sqrt(m);
      for(var k=0; k<3; ++k) {
        norm[k] *= w;
      }
    } else {
      for(var k=0; k<3; ++k) {
        norm[k] = 0.0;
      }
    }
  }

  //Return the resulting set of patches
  return normals;
}

//Compute face normals of a mesh
exports.faceNormals = function(faces, positions, specifiedEpsilon) {

  var N         = faces.length;
  var normals   = new Array(N);
  var epsilon   = specifiedEpsilon === void(0) ? DEFAULT_FACE_EPSILON : specifiedEpsilon;

  for(var i=0; i<N; ++i) {
    var f = faces[i];
    var pos = new Array(3);
    for(var j=0; j<3; ++j) {
      pos[j] = positions[f[j]];
    }

    var d01 = new Array(3);
    var d21 = new Array(3);
    for(var j=0; j<3; ++j) {
      d01[j] = pos[1][j] - pos[0][j];
      d21[j] = pos[2][j] - pos[0][j];
    }

    var n = new Array(3);
    var l = 0.0;
    for(var j=0; j<3; ++j) {
      var u = (j+1)%3;
      var v = (j+2)%3;
      n[j] = d01[u] * d21[v] - d01[v] * d21[u];
      l += n[j] * n[j];
    }
    if(l > epsilon) {
      l = 1.0 / Math.sqrt(l);
    } else {
      l = 0.0;
    }
    for(var j=0; j<3; ++j) {
      n[j] *= l;
    }
    normals[i] = n;
  }
  return normals;
}



},{}],443:[function(_dereq_,module,exports){
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/

'use strict';
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;

function toObject(val) {
	if (val === null || val === undefined) {
		throw new TypeError('Object.assign cannot be called with null or undefined');
	}

	return Object(val);
}

function shouldUseNative() {
	try {
		if (!Object.assign) {
			return false;
		}

		// Detect buggy property enumeration order in older V8 versions.

		// https://bugs.chromium.org/p/v8/issues/detail?id=4118
		var test1 = new String('abc');  // eslint-disable-line no-new-wrappers
		test1[5] = 'de';
		if (Object.getOwnPropertyNames(test1)[0] === '5') {
			return false;
		}

		// https://bugs.chromium.org/p/v8/issues/detail?id=3056
		var test2 = {};
		for (var i = 0; i < 10; i++) {
			test2['_' + String.fromCharCode(i)] = i;
		}
		var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
			return test2[n];
		});
		if (order2.join('') !== '0123456789') {
			return false;
		}

		// https://bugs.chromium.org/p/v8/issues/detail?id=3056
		var test3 = {};
		'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
			test3[letter] = letter;
		});
		if (Object.keys(Object.assign({}, test3)).join('') !==
				'abcdefghijklmnopqrst') {
			return false;
		}

		return true;
	} catch (err) {
		// We don't expect any of the above to throw, but better to be safe.
		return false;
	}
}

module.exports = shouldUseNative() ? Object.assign : function (target, source) {
	var from;
	var to = toObject(target);
	var symbols;

	for (var s = 1; s < arguments.length; s++) {
		from = Object(arguments[s]);

		for (var key in from) {
			if (hasOwnProperty.call(from, key)) {
				to[key] = from[key];
			}
		}

		if (getOwnPropertySymbols) {
			symbols = getOwnPropertySymbols(from);
			for (var i = 0; i < symbols.length; i++) {
				if (propIsEnumerable.call(from, symbols[i])) {
					to[symbols[i]] = from[symbols[i]];
				}
			}
		}
	}

	return to;
};

},{}],444:[function(_dereq_,module,exports){
'use strict'

module.exports = quatFromFrame

function quatFromFrame(
  out,
  rx, ry, rz,
  ux, uy, uz,
  fx, fy, fz) {
  var tr = rx + uy + fz
  if(l > 0) {
    var l = Math.sqrt(tr + 1.0)
    out[0] = 0.5 * (uz - fy) / l
    out[1] = 0.5 * (fx - rz) / l
    out[2] = 0.5 * (ry - uy) / l
    out[3] = 0.5 * l
  } else {
    var tf = Math.max(rx, uy, fz)
    var l = Math.sqrt(2 * tf - tr + 1.0)
    if(rx >= tf) {
      //x y z  order
      out[0] = 0.5 * l
      out[1] = 0.5 * (ux + ry) / l
      out[2] = 0.5 * (fx + rz) / l
      out[3] = 0.5 * (uz - fy) / l
    } else if(uy >= tf) {
      //y z x  order
      out[0] = 0.5 * (ry + ux) / l
      out[1] = 0.5 * l
      out[2] = 0.5 * (fy + uz) / l
      out[3] = 0.5 * (fx - rz) / l
    } else {
      //z x y  order
      out[0] = 0.5 * (rz + fx) / l
      out[1] = 0.5 * (uz + fy) / l
      out[2] = 0.5 * l
      out[3] = 0.5 * (ry - ux) / l
    }
  }
  return out
}
},{}],445:[function(_dereq_,module,exports){
'use strict'

module.exports = createOrbitController

var filterVector  = _dereq_('filtered-vector')
var lookAt        = _dereq_('gl-mat4/lookAt')
var mat4FromQuat  = _dereq_('gl-mat4/fromQuat')
var invert44      = _dereq_('gl-mat4/invert')
var quatFromFrame = _dereq_('./lib/quatFromFrame')

function len3(x,y,z) {
  return Math.sqrt(Math.pow(x,2) + Math.pow(y,2) + Math.pow(z,2))
}

function len4(w,x,y,z) {
  return Math.sqrt(Math.pow(w,2) + Math.pow(x,2) + Math.pow(y,2) + Math.pow(z,2))
}

function normalize4(out, a) {
  var ax = a[0]
  var ay = a[1]
  var az = a[2]
  var aw = a[3]
  var al = len4(ax, ay, az, aw)
  if(al > 1e-6) {
    out[0] = ax/al
    out[1] = ay/al
    out[2] = az/al
    out[3] = aw/al
  } else {
    out[0] = out[1] = out[2] = 0.0
    out[3] = 1.0
  }
}

function OrbitCameraController(initQuat, initCenter, initRadius) {
  this.radius    = filterVector([initRadius])
  this.center    = filterVector(initCenter)
  this.rotation  = filterVector(initQuat)

  this.computedRadius   = this.radius.curve(0)
  this.computedCenter   = this.center.curve(0)
  this.computedRotation = this.rotation.curve(0)
  this.computedUp       = [0.1,0,0]
  this.computedEye      = [0.1,0,0]
  this.computedMatrix   = [0.1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

  this.recalcMatrix(0)
}

var proto = OrbitCameraController.prototype

proto.lastT = function() {
  return Math.max(
    this.radius.lastT(),
    this.center.lastT(),
    this.rotation.lastT())
}

proto.recalcMatrix = function(t) {
  this.radius.curve(t)
  this.center.curve(t)
  this.rotation.curve(t)

  var quat = this.computedRotation
  normalize4(quat, quat)

  var mat = this.computedMatrix
  mat4FromQuat(mat, quat)

  var center = this.computedCenter
  var eye    = this.computedEye
  var up     = this.computedUp
  var radius = Math.exp(this.computedRadius[0])

  eye[0] = center[0] + radius * mat[2]
  eye[1] = center[1] + radius * mat[6]
  eye[2] = center[2] + radius * mat[10]
  up[0] = mat[1]
  up[1] = mat[5]
  up[2] = mat[9]

  for(var i=0; i<3; ++i) {
    var rr = 0.0
    for(var j=0; j<3; ++j) {
      rr += mat[i+4*j] * eye[j]
    }
    mat[12+i] = -rr
  }
}

proto.getMatrix = function(t, result) {
  this.recalcMatrix(t)
  var m = this.computedMatrix
  if(result) {
    for(var i=0; i<16; ++i) {
      result[i] = m[i]
    }
    return result
  }
  return m
}

proto.idle = function(t) {
  this.center.idle(t)
  this.radius.idle(t)
  this.rotation.idle(t)
}

proto.flush = function(t) {
  this.center.flush(t)
  this.radius.flush(t)
  this.rotation.flush(t)
}

proto.pan = function(t, dx, dy, dz) {
  dx = dx || 0.0
  dy = dy || 0.0
  dz = dz || 0.0

  this.recalcMatrix(t)
  var mat = this.computedMatrix

  var ux = mat[1]
  var uy = mat[5]
  var uz = mat[9]
  var ul = len3(ux, uy, uz)
  ux /= ul
  uy /= ul
  uz /= ul

  var rx = mat[0]
  var ry = mat[4]
  var rz = mat[8]
  var ru = rx * ux + ry * uy + rz * uz
  rx -= ux * ru
  ry -= uy * ru
  rz -= uz * ru
  var rl = len3(rx, ry, rz)
  rx /= rl
  ry /= rl
  rz /= rl

  var fx = mat[2]
  var fy = mat[6]
  var fz = mat[10]
  var fu = fx * ux + fy * uy + fz * uz
  var fr = fx * rx + fy * ry + fz * rz
  fx -= fu * ux + fr * rx
  fy -= fu * uy + fr * ry
  fz -= fu * uz + fr * rz
  var fl = len3(fx, fy, fz)
  fx /= fl
  fy /= fl
  fz /= fl

  var vx = rx * dx + ux * dy
  var vy = ry * dx + uy * dy
  var vz = rz * dx + uz * dy

  this.center.move(t, vx, vy, vz)

  //Update z-component of radius
  var radius = Math.exp(this.computedRadius[0])
  radius = Math.max(1e-4, radius + dz)
  this.radius.set(t, Math.log(radius))
}

proto.rotate = function(t, dx, dy, dz) {
  this.recalcMatrix(t)

  dx = dx||0.0
  dy = dy||0.0

  var mat = this.computedMatrix

  var rx = mat[0]
  var ry = mat[4]
  var rz = mat[8]

  var ux = mat[1]
  var uy = mat[5]
  var uz = mat[9]

  var fx = mat[2]
  var fy = mat[6]
  var fz = mat[10]

  var qx = dx * rx + dy * ux
  var qy = dx * ry + dy * uy
  var qz = dx * rz + dy * uz

  var bx = -(fy * qz - fz * qy)
  var by = -(fz * qx - fx * qz)
  var bz = -(fx * qy - fy * qx)  
  var bw = Math.sqrt(Math.max(0.0, 1.0 - Math.pow(bx,2) - Math.pow(by,2) - Math.pow(bz,2)))
  var bl = len4(bx, by, bz, bw)
  if(bl > 1e-6) {
    bx /= bl
    by /= bl
    bz /= bl
    bw /= bl
  } else {
    bx = by = bz = 0.0
    bw = 1.0
  }

  var rotation = this.computedRotation
  var ax = rotation[0]
  var ay = rotation[1]
  var az = rotation[2]
  var aw = rotation[3]

  var cx = ax*bw + aw*bx + ay*bz - az*by
  var cy = ay*bw + aw*by + az*bx - ax*bz
  var cz = az*bw + aw*bz + ax*by - ay*bx
  var cw = aw*bw - ax*bx - ay*by - az*bz
  
  //Apply roll
  if(dz) {
    bx = fx
    by = fy
    bz = fz
    var s = Math.sin(dz) / len3(bx, by, bz)
    bx *= s
    by *= s
    bz *= s
    bw = Math.cos(dx)
    cx = cx*bw + cw*bx + cy*bz - cz*by
    cy = cy*bw + cw*by + cz*bx - cx*bz
    cz = cz*bw + cw*bz + cx*by - cy*bx
    cw = cw*bw - cx*bx - cy*by - cz*bz
  }

  var cl = len4(cx, cy, cz, cw)
  if(cl > 1e-6) {
    cx /= cl
    cy /= cl
    cz /= cl
    cw /= cl
  } else {
    cx = cy = cz = 0.0
    cw = 1.0
  }

  this.rotation.set(t, cx, cy, cz, cw)
}

proto.lookAt = function(t, eye, center, up) {
  this.recalcMatrix(t)

  center = center || this.computedCenter
  eye    = eye    || this.computedEye
  up     = up     || this.computedUp

  var mat = this.computedMatrix
  lookAt(mat, eye, center, up)

  var rotation = this.computedRotation
  quatFromFrame(rotation,
    mat[0], mat[1], mat[2],
    mat[4], mat[5], mat[6],
    mat[8], mat[9], mat[10])
  normalize4(rotation, rotation)
  this.rotation.set(t, rotation[0], rotation[1], rotation[2], rotation[3])

  var fl = 0.0
  for(var i=0; i<3; ++i) {
    fl += Math.pow(center[i] - eye[i], 2)
  }
  this.radius.set(t, 0.5 * Math.log(Math.max(fl, 1e-6)))

  this.center.set(t, center[0], center[1], center[2])
}

proto.translate = function(t, dx, dy, dz) {
  this.center.move(t,
    dx||0.0,
    dy||0.0,
    dz||0.0)
}

proto.setMatrix = function(t, matrix) {

  var rotation = this.computedRotation
  quatFromFrame(rotation,
    matrix[0], matrix[1], matrix[2],
    matrix[4], matrix[5], matrix[6],
    matrix[8], matrix[9], matrix[10])
  normalize4(rotation, rotation)
  this.rotation.set(t, rotation[0], rotation[1], rotation[2], rotation[3])

  var mat = this.computedMatrix
  invert44(mat, matrix)
  var w = mat[15]
  if(Math.abs(w) > 1e-6) {
    var cx = mat[12]/w
    var cy = mat[13]/w
    var cz = mat[14]/w

    this.recalcMatrix(t)  
    var r = Math.exp(this.computedRadius[0])
    this.center.set(t, cx-mat[2]*r, cy-mat[6]*r, cz-mat[10]*r)
    this.radius.idle(t)
  } else {
    this.center.idle(t)
    this.radius.idle(t)
  }
}

proto.setDistance = function(t, d) {
  if(d > 0) {
    this.radius.set(t, Math.log(d))
  }
}

proto.setDistanceLimits = function(lo, hi) {
  if(lo > 0) {
    lo = Math.log(lo)
  } else {
    lo = -Infinity    
  }
  if(hi > 0) {
    hi = Math.log(hi)
  } else {
    hi = Infinity
  }
  hi = Math.max(hi, lo)
  this.radius.bounds[0][0] = lo
  this.radius.bounds[1][0] = hi
}

proto.getDistanceLimits = function(out) {
  var bounds = this.radius.bounds
  if(out) {
    out[0] = Math.exp(bounds[0][0])
    out[1] = Math.exp(bounds[1][0])
    return out
  }
  return [ Math.exp(bounds[0][0]), Math.exp(bounds[1][0]) ]
}

proto.toJSON = function() {
  this.recalcMatrix(this.lastT())
  return {
    center:   this.computedCenter.slice(),
    rotation: this.computedRotation.slice(),
    distance: Math.log(this.computedRadius[0]),
    zoomMin:  this.radius.bounds[0][0],
    zoomMax:  this.radius.bounds[1][0]
  }
}

proto.fromJSON = function(options) {
  var t = this.lastT()
  var c = options.center
  if(c) {
    this.center.set(t, c[0], c[1], c[2])
  }
  var r = options.rotation
  if(r) {
    this.rotation.set(t, r[0], r[1], r[2], r[3])
  }
  var d = options.distance
  if(d && d > 0) {
    this.radius.set(t, Math.log(d))
  }
  this.setDistanceLimits(options.zoomMin, options.zoomMax)
}

function createOrbitController(options) {
  options = options || {}
  var center   = options.center   || [0,0,0]
  var rotation = options.rotation || [0,0,0,1]
  var radius   = options.radius   || 1.0

  center = [].slice.call(center, 0, 3)
  rotation = [].slice.call(rotation, 0, 4)
  normalize4(rotation, rotation)

  var result = new OrbitCameraController(
    rotation,
    center,
    Math.log(radius))

  result.setDistanceLimits(options.zoomMin, options.zoomMax)

  if('eye' in options || 'up' in options) {
    result.lookAt(0, options.eye, options.center, options.up)
  }

  return result
}
},{"./lib/quatFromFrame":444,"filtered-vector":219,"gl-mat4/fromQuat":255,"gl-mat4/invert":258,"gl-mat4/lookAt":259}],446:[function(_dereq_,module,exports){
/*!
 * pad-left <https://github.com/jonschlinkert/pad-left>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT license.
 */

'use strict';

var repeat = _dereq_('repeat-string');

module.exports = function padLeft(str, num, ch) {
  ch = typeof ch !== 'undefined' ? (ch + '') : ' ';
  return repeat(ch, num) + str;
};
},{"repeat-string":484}],447:[function(_dereq_,module,exports){
'use strict'

/**
 * @module parenthesis
 */

function parse (str, opts) {
	// pretend non-string parsed per-se
	if (typeof str !== 'string') return [str]

	var res = [str]

	if (typeof opts === 'string' || Array.isArray(opts)) {
		opts = {brackets: opts}
	}
	else if (!opts) opts = {}

	var brackets = opts.brackets ? (Array.isArray(opts.brackets) ? opts.brackets : [opts.brackets]) : ['{}', '[]', '()']

	var escape = opts.escape || '___'

	var flat = !!opts.flat

	brackets.forEach(function (bracket) {
		// create parenthesis regex
		var pRE = new RegExp(['\\', bracket[0], '[^\\', bracket[0], '\\', bracket[1], ']*\\', bracket[1]].join(''))

		var ids = []

		function replaceToken(token, idx, str){
			// save token to res
			var refId = res.push(token.slice(bracket[0].length, -bracket[1].length)) - 1

			ids.push(refId)

			return escape + refId
		}

		res.forEach(function (str, i) {
			var prevStr

			// replace paren tokens till there’s none
			var a = 0
			while (str != prevStr) {
				prevStr = str
				str = str.replace(pRE, replaceToken)
				if (a++ > 10e3) throw Error('References have circular dependency. Please, check them.')
			}

			res[i] = str
		})

		// wrap found refs to brackets
		ids = ids.reverse()
		res = res.map(function (str) {
			ids.forEach(function (id) {
				str = str.replace(new RegExp('(\\' + escape + id + '(?![0-9]))', 'g'), bracket[0] + '$1' + bracket[1])
			})
			return str
		})
	})

	var re = new RegExp('\\' + escape + '([0-9]+)')

	// transform references to tree
	function nest (str, refs, escape) {
		var res = [], match

		var a = 0
		while (match = re.exec(str)) {
			if (a++ > 10e3) throw Error('Circular references in parenthesis')

			res.push(str.slice(0, match.index))

			res.push(nest(refs[match[1]], refs))

			str = str.slice(match.index + match[0].length)
		}

		res.push(str)

		return res
	}

	return flat ? res : nest(res[0], res)
}

function stringify (arg, opts) {
	if (opts && opts.flat) {
		var escape = opts && opts.escape || '___'

		var str = arg[0], prevStr

		// pretend bad string stringified with no parentheses
		if (!str) return ''


		var re = new RegExp('\\' + escape + '([0-9]+)')

		var a = 0
		while (str != prevStr) {
			if (a++ > 10e3) throw Error('Circular references in ' + arg)
			prevStr = str
			str = str.replace(re, replaceRef)
		}

		return str
	}

	return arg.reduce(function f (prev, curr) {
		if (Array.isArray(curr)) {
			curr = curr.reduce(f, '')
		}
		return prev + curr
	}, '')

	function replaceRef(match, idx){
		if (arg[idx] == null) throw Error('Reference ' + idx + 'is undefined')
		return arg[idx]
	}
}

function parenthesis (arg, opts) {
	if (Array.isArray(arg)) {
		return stringify(arg, opts)
	}
	else {
		return parse(arg, opts)
	}
}

parenthesis.parse = parse
parenthesis.stringify = stringify

module.exports = parenthesis

},{}],448:[function(_dereq_,module,exports){
'use strict'

var pick = _dereq_('pick-by-alias')

module.exports = parseRect

function parseRect (arg) {
  var rect

  // direct arguments sequence
  if (arguments.length > 1) {
    arg = arguments
  }

  // svg viewbox
  if (typeof arg === 'string') {
    arg = arg.split(/\s/).map(parseFloat)
  }
  else if (typeof arg === 'number') {
    arg = [arg]
  }

  // 0, 0, 100, 100 - array-like
  if (arg.length && typeof arg[0] === 'number') {
    // [w, w]
    if (arg.length === 1) {
      rect = {
        width: arg[0],
        height: arg[0],
        x: 0, y: 0
      }
    }
    // [w, h]
    else if (arg.length === 2) {
      rect = {
        width: arg[0],
        height: arg[1],
        x: 0, y: 0
      }
    }
    // [l, t, r, b]
    else {
      rect = {
        x: arg[0],
        y: arg[1],
        width: (arg[2] - arg[0]) || 0,
        height: (arg[3] - arg[1]) || 0
      }
    }
  }
  // {x, y, w, h} or {l, t, b, r}
  else if (arg) {
    arg = pick(arg, {
      left: 'x l left Left',
      top: 'y t top Top',
      width: 'w width W Width',
      height: 'h height W Width',
      bottom: 'b bottom Bottom',
      right: 'r right Right'
    })

    rect = {
      x: arg.left || 0,
      y: arg.top || 0
    }

    if (arg.width == null) {
      if (arg.right) rect.width = arg.right - rect.x
      else rect.width = 0
    }
    else {
      rect.width = arg.width
    }

    if (arg.height == null) {
      if (arg.bottom) rect.height = arg.bottom - rect.y
      else rect.height = 0
    }
    else {
      rect.height = arg.height
    }
  }

  return rect
}

},{"pick-by-alias":454}],449:[function(_dereq_,module,exports){

module.exports = parse

/**
 * expected argument lengths
 * @type {Object}
 */

var length = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0}

/**
 * segment pattern
 * @type {RegExp}
 */

var segment = /([astvzqmhlc])([^astvzqmhlc]*)/ig

/**
 * parse an svg path data string. Generates an Array
 * of commands where each command is an Array of the
 * form `[command, arg1, arg2, ...]`
 *
 * @param {String} path
 * @return {Array}
 */

function parse(path) {
	var data = []
	path.replace(segment, function(_, command, args){
		var type = command.toLowerCase()
		args = parseValues(args)

		// overloaded moveTo
		if (type == 'm' && args.length > 2) {
			data.push([command].concat(args.splice(0, 2)))
			type = 'l'
			command = command == 'm' ? 'l' : 'L'
		}

		while (true) {
			if (args.length == length[type]) {
				args.unshift(command)
				return data.push(args)
			}
			if (args.length < length[type]) throw new Error('malformed path data')
			data.push([command].concat(args.splice(0, length[type])))
		}
	})
	return data
}

var number = /-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig

function parseValues(args) {
	var numbers = args.match(number)
	return numbers ? numbers.map(Number) : []
}

},{}],450:[function(_dereq_,module,exports){
module.exports = function parseUnit(str, out) {
    if (!out)
        out = [ 0, '' ]

    str = String(str)
    var num = parseFloat(str, 10)
    out[0] = num
    out[1] = str.match(/[\d.\-\+]*\s*(.*)/)[1] || ''
    return out
}
},{}],451:[function(_dereq_,module,exports){
(function (process){
// Generated by CoffeeScript 1.12.2
(function() {
  var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime;

  if ((typeof performance !== "undefined" && performance !== null) && performance.now) {
    module.exports = function() {
      return performance.now();
    };
  } else if ((typeof process !== "undefined" && process !== null) && process.hrtime) {
    module.exports = function() {
      return (getNanoSeconds() - nodeLoadTime) / 1e6;
    };
    hrtime = process.hrtime;
    getNanoSeconds = function() {
      var hr;
      hr = hrtime();
      return hr[0] * 1e9 + hr[1];
    };
    moduleLoadTime = getNanoSeconds();
    upTime = process.uptime() * 1e9;
    nodeLoadTime = moduleLoadTime - upTime;
  } else if (Date.now) {
    module.exports = function() {
      return Date.now() - loadTime;
    };
    loadTime = Date.now();
  } else {
    module.exports = function() {
      return new Date().getTime() - loadTime;
    };
    loadTime = new Date().getTime();
  }

}).call(this);



}).call(this,_dereq_('_process'))
},{"_process":471}],452:[function(_dereq_,module,exports){
"use strict"

module.exports = permutationSign

var BRUTE_FORCE_CUTOFF = 32

var pool = _dereq_("typedarray-pool")

function permutationSign(p) {
  var n = p.length
  if(n < BRUTE_FORCE_CUTOFF) {
    //Use quadratic algorithm for small n
    var sgn = 1
    for(var i=0; i<n; ++i) {
      for(var j=0; j<i; ++j) {
        if(p[i] < p[j]) {
          sgn = -sgn
        } else if(p[i] === p[j]) {
          return 0
        }
      }
    }
    return sgn
  } else {
    //Otherwise use linear time algorithm
    var visited = pool.mallocUint8(n)
    for(var i=0; i<n; ++i) {
      visited[i] = 0
    }
    var sgn = 1
    for(var i=0; i<n; ++i) {
      if(!visited[i]) {
        var count = 1
        visited[i] = 1
        for(var j=p[i]; j!==i; j=p[j]) {
          if(visited[j]) {
            pool.freeUint8(visited)
            return 0
          }
          count += 1
          visited[j] = 1
        }
        if(!(count & 1)) {
          sgn = -sgn
        }
      }
    }
    pool.freeUint8(visited)
    return sgn
  }
}
},{"typedarray-pool":526}],453:[function(_dereq_,module,exports){
"use strict"

var pool = _dereq_("typedarray-pool")
var inverse = _dereq_("invert-permutation")

function rank(permutation) {
  var n = permutation.length
  switch(n) {
    case 0:
    case 1:
      return 0
    case 2:
      return permutation[1]
    default:
      break
  }
  var p = pool.mallocUint32(n)
  var pinv = pool.mallocUint32(n)
  var r = 0, s, t, i
  inverse(permutation, pinv)
  for(i=0; i<n; ++i) {
    p[i] = permutation[i]
  }
  for(i=n-1; i>0; --i) {
    t = pinv[i]
    s = p[i]
    p[i] = p[t]
    p[t] = s
    pinv[i] = pinv[s]
    pinv[s] = t
    r = (r + s) * i
  }
  pool.freeUint32(pinv)
  pool.freeUint32(p)
  return r
}

function unrank(n, r, p) {
  switch(n) {
    case 0:
      if(p) { return p }
      return []
    case 1:
      if(p) {
        p[0] = 0
        return p
      } else {
        return [0]
      }
    case 2:
      if(p) {
        if(r) {
          p[0] = 0
          p[1] = 1
        } else {
          p[0] = 1
          p[1] = 0
        }
        return p
      } else {
        return r ? [0,1] : [1,0]
      }
    default:
      break
  }
  p = p || new Array(n)
  var s, t, i, nf=1
  p[0] = 0
  for(i=1; i<n; ++i) {
    p[i] = i
    nf = (nf*i)|0
  }
  for(i=n-1; i>0; --i) {
    s = (r / nf)|0
    r = (r - s * nf)|0
    nf = (nf / i)|0
    t = p[i]|0
    p[i] = p[s]|0
    p[s] = t|0
  }
  return p
}

exports.rank = rank
exports.unrank = unrank

},{"invert-permutation":404,"typedarray-pool":526}],454:[function(_dereq_,module,exports){
'use strict'


module.exports = function pick (src, props, keepRest) {
	var result = {}, prop, i

	if (typeof props === 'string') props = toList(props)
	if (Array.isArray(props)) {
		var res = {}
		for (i = 0; i < props.length; i++) {
			res[props[i]] = true
		}
		props = res
	}

	// convert strings to lists
	for (prop in props) {
		props[prop] = toList(props[prop])
	}

	// keep-rest strategy requires unmatched props to be preserved
	var occupied = {}

	for (prop in props) {
		var aliases = props[prop]

		if (Array.isArray(aliases)) {
			for (i = 0; i < aliases.length; i++) {
				var alias = aliases[i]

				if (keepRest) {
					occupied[alias] = true
				}

				if (alias in src) {
					result[prop] = src[alias]

					if (keepRest) {
						for (var j = i; j < aliases.length; j++) {
							occupied[aliases[j]] = true
						}
					}

					break
				}
			}
		}
		else if (prop in src) {
			if (props[prop]) {
				result[prop] = src[prop]
			}

			if (keepRest) {
				occupied[prop] = true
			}
		}
	}

	if (keepRest) {
		for (prop in src) {
			if (occupied[prop]) continue
			result[prop] = src[prop]
		}
	}

	return result
}

var CACHE = {}

function toList(arg) {
	if (CACHE[arg]) return CACHE[arg]
	if (typeof arg === 'string') {
		arg = CACHE[arg] = arg.split(/\s*,\s*|\s+/)
	}
	return arg
}

},{}],455:[function(_dereq_,module,exports){
"use strict"

module.exports = planarDual

var compareAngle = _dereq_("compare-angle")

function planarDual(cells, positions) {

  var numVertices = positions.length|0
  var numEdges = cells.length
  var adj = [new Array(numVertices), new Array(numVertices)]
  for(var i=0; i<numVertices; ++i) {
    adj[0][i] = []
    adj[1][i] = []
  }
  for(var i=0; i<numEdges; ++i) {
    var c = cells[i]
    adj[0][c[0]].push(c)
    adj[1][c[1]].push(c)
  }

  var cycles = []

  //Add isolated vertices as trivial case
  for(var i=0; i<numVertices; ++i) {
    if(adj[0][i].length + adj[1][i].length === 0) {
      cycles.push( [i] )
    }
  }

  //Remove a half edge
  function cut(c, i) {
    var a = adj[i][c[i]]
    a.splice(a.indexOf(c), 1)
  }

  //Find next vertex and cut edge
  function next(a, b, noCut) {
    var nextCell, nextVertex, nextDir
    for(var i=0; i<2; ++i) {
      if(adj[i][b].length > 0) {
        nextCell = adj[i][b][0]
        nextDir = i
        break
      }
    }
    nextVertex = nextCell[nextDir^1]

    for(var dir=0; dir<2; ++dir) {
      var nbhd = adj[dir][b]
      for(var k=0; k<nbhd.length; ++k) {
        var e = nbhd[k]
        var p = e[dir^1]
        var cmp = compareAngle(
            positions[a], 
            positions[b], 
            positions[nextVertex],
            positions[p])
        if(cmp > 0) {
          nextCell = e
          nextVertex = p
          nextDir = dir
        }
      }
    }
    if(noCut) {
      return nextVertex
    }
    if(nextCell) {
      cut(nextCell, nextDir)
    }
    return nextVertex
  }

  function extractCycle(v, dir) {
    var e0 = adj[dir][v][0]
    var cycle = [v]
    cut(e0, dir)
    var u = e0[dir^1]
    var d0 = dir
    while(true) {
      while(u !== v) {
        cycle.push(u)
        u = next(cycle[cycle.length-2], u, false)
      }
      if(adj[0][v].length + adj[1][v].length === 0) {
        break
      }
      var a = cycle[cycle.length-1]
      var b = v
      var c = cycle[1]
      var d = next(a, b, true)
      if(compareAngle(positions[a], positions[b], positions[c], positions[d]) < 0) {
        break
      }
      cycle.push(v)
      u = next(a, b)
    }
    return cycle
  }

  function shouldGlue(pcycle, ncycle) {
    return (ncycle[1] === ncycle[ncycle.length-1])
  }

  for(var i=0; i<numVertices; ++i) {
    for(var j=0; j<2; ++j) {
      var pcycle = []
      while(adj[j][i].length > 0) {
        var ni = adj[0][i].length
        var ncycle = extractCycle(i,j)
        if(shouldGlue(pcycle, ncycle)) {
          //Glue together trivial cycles
          pcycle.push.apply(pcycle, ncycle)
        } else {
          if(pcycle.length > 0) {
            cycles.push(pcycle)
          }
          pcycle = ncycle
        }
      }
      if(pcycle.length > 0) {
        cycles.push(pcycle)
      }
    }
  }

  //Combine paths and loops together
  return cycles
}
},{"compare-angle":115}],456:[function(_dereq_,module,exports){
'use strict'

module.exports = trimLeaves

var e2a = _dereq_('edges-to-adjacency-list')

function trimLeaves(edges, positions) {
  var adj = e2a(edges, positions.length)
  var live = new Array(positions.length)
  var nbhd = new Array(positions.length)

  var dead = []
  for(var i=0; i<positions.length; ++i) {
    var count = adj[i].length
    nbhd[i] = count
    live[i] = true
    if(count <= 1) {
      dead.push(i)
    }
  }

  while(dead.length > 0) {
    var v = dead.pop()
    live[v] = false
    var n = adj[v]
    for(var i=0; i<n.length; ++i) {
      var u = n[i]
      if(--nbhd[u] === 0) {
        dead.push(u)
      }
    }
  }

  var newIndex = new Array(positions.length)
  var npositions = []
  for(var i=0; i<positions.length; ++i) {
    if(live[i]) {
      var v = npositions.length
      newIndex[i] = v
      npositions.push(positions[i])
    } else {
      newIndex[i] = -1
    }
  }

  var nedges = []
  for(var i=0; i<edges.length; ++i) {
    var e = edges[i]
    if(live[e[0]] && live[e[1]]) {
      nedges.push([ newIndex[e[0]], newIndex[e[1]] ])
    }
  }
  
  return [ nedges, npositions ]
}
},{"edges-to-adjacency-list":160}],457:[function(_dereq_,module,exports){
'use strict'

module.exports = planarGraphToPolyline

var e2a = _dereq_('edges-to-adjacency-list')
var planarDual = _dereq_('planar-dual')
var preprocessPolygon = _dereq_('point-in-big-polygon')
var twoProduct = _dereq_('two-product')
var robustSum = _dereq_('robust-sum')
var uniq = _dereq_('uniq')
var trimLeaves = _dereq_('./lib/trim-leaves')

function makeArray(length, fill) {
  var result = new Array(length)
  for(var i=0; i<length; ++i) {
    result[i] = fill
  }
  return result
}

function makeArrayOfArrays(length) {
  var result = new Array(length)
  for(var i=0; i<length; ++i) {
    result[i] = []
  }
  return result
}


function planarGraphToPolyline(edges, positions) {

  //Trim leaves
  var result = trimLeaves(edges, positions)
  edges = result[0]
  positions = result[1]

  var numVertices = positions.length
  var numEdges = edges.length

  //Calculate adjacency list, check manifold
  var adj = e2a(edges, positions.length)
  for(var i=0; i<numVertices; ++i) {
    if(adj[i].length % 2 === 1) {
      throw new Error('planar-graph-to-polyline: graph must be manifold')
    }
  }

  //Get faces
  var faces = planarDual(edges, positions)

  //Check orientation of a polygon using exact arithmetic
  function ccw(c) {
    var n = c.length
    var area = [0]
    for(var j=0; j<n; ++j) {
      var a = positions[c[j]]
      var b = positions[c[(j+1)%n]]
      var t00 = twoProduct(-a[0], a[1])
      var t01 = twoProduct(-a[0], b[1])
      var t10 = twoProduct( b[0], a[1])
      var t11 = twoProduct( b[0], b[1])
      area = robustSum(area, robustSum(robustSum(t00, t01), robustSum(t10, t11)))
    }
    return area[area.length-1] > 0
  }

  //Extract all clockwise faces
  faces = faces.filter(ccw)

  //Detect which loops are contained in one another to handle parent-of relation
  var numFaces = faces.length
  var parent = new Array(numFaces)
  var containment = new Array(numFaces)
  for(var i=0; i<numFaces; ++i) {
    parent[i] = i
    var row = new Array(numFaces)
    var loopVertices = faces[i].map(function(v) {
      return positions[v]
    })
    var pmc = preprocessPolygon([loopVertices])
    var count = 0
    outer:
    for(var j=0; j<numFaces; ++j) {
      row[j] = 0
      if(i === j) {
        continue
      }
      var c = faces[j]
      var n = c.length
      for(var k=0; k<n; ++k) {
        var d = pmc(positions[c[k]])
        if(d !== 0) {
          if(d < 0) {
            row[j] = 1
            count += 1
          }
          continue outer
        }
      }
      row[j] = 1
      count += 1
    }
    containment[i] = [count, i, row]
  }
  containment.sort(function(a,b) {
    return b[0] - a[0]
  })
  for(var i=0; i<numFaces; ++i) {
    var row = containment[i]
    var idx = row[1]
    var children = row[2]
    for(var j=0; j<numFaces; ++j) {
      if(children[j]) {
        parent[j] = idx
      }
    }
  }

  //Initialize face adjacency list
  var fadj = makeArrayOfArrays(numFaces)
  for(var i=0; i<numFaces; ++i) {
    fadj[i].push(parent[i])
    fadj[parent[i]].push(i)
  }

  //Build adjacency matrix for edges
  var edgeAdjacency = {}
  var internalVertices = makeArray(numVertices, false)
  for(var i=0; i<numFaces; ++i) {
    var c = faces[i]
    var n = c.length
    for(var j=0; j<n; ++j) {
      var a = c[j]
      var b = c[(j+1)%n]
      var key = Math.min(a,b) + ":" + Math.max(a,b)
      if(key in edgeAdjacency) {
        var neighbor = edgeAdjacency[key]
        fadj[neighbor].push(i)
        fadj[i].push(neighbor)
        internalVertices[a] = internalVertices[b] = true
      } else {
        edgeAdjacency[key] = i
      }
    }
  }

  function sharedBoundary(c) {
    var n = c.length
    for(var i=0; i<n; ++i) {
      if(!internalVertices[c[i]]) {
        return false
      }
    }
    return true
  }

  var toVisit = []
  var parity = makeArray(numFaces, -1)
  for(var i=0; i<numFaces; ++i) {
    if(parent[i] === i && !sharedBoundary(faces[i])) {
      toVisit.push(i)
      parity[i] = 0
    } else {
      parity[i] = -1
    }
  }

  //Using face adjacency, classify faces as in/out
  var result = []
  while(toVisit.length > 0) {
    var top = toVisit.pop()
    var nbhd = fadj[top]
    uniq(nbhd, function(a,b) {
      return a-b
    })
    var nnbhr = nbhd.length
    var p = parity[top]
    var polyline
    if(p === 0) {
      var c = faces[top]
      polyline = [c]
    }
    for(var i=0; i<nnbhr; ++i) {
      var f = nbhd[i]
      if(parity[f] >= 0) {
        continue
      }
      parity[f] = p^1
      toVisit.push(f)
      if(p === 0) {
        var c = faces[f]
        if(!sharedBoundary(c)) {
          c.reverse()
          polyline.push(c)
        }
      }
    }
    if(p === 0) {
      result.push(polyline)
    }
  }

  return result
}
},{"./lib/trim-leaves":456,"edges-to-adjacency-list":160,"planar-dual":455,"point-in-big-polygon":461,"robust-sum":496,"two-product":524,"uniq":528}],458:[function(_dereq_,module,exports){
'use strict'

module.exports = _dereq_('./quad')
},{"./quad":460}],459:[function(_dereq_,module,exports){
arguments[4][99][0].apply(exports,arguments)
},{"dup":99}],460:[function(_dereq_,module,exports){
/**
 * @module  point-cluster/quad
 *
 * Bucket based quad tree clustering
 */

'use strict'

var search = _dereq_('binary-search-bounds')
var clamp = _dereq_('clamp')
var rect = _dereq_('parse-rect')
var getBounds = _dereq_('array-bounds')
var pick = _dereq_('pick-by-alias')
var defined = _dereq_('defined')
var flatten = _dereq_('flatten-vertex-data')
var isObj = _dereq_('is-obj')
var dtype = _dereq_('dtype')
var log2 = _dereq_('math-log2')


module.exports = function cluster (srcPoints, options) {
	if (!options) { options = {} }

	srcPoints = flatten(srcPoints, 'float64')

	options = pick(options, {
		bounds: 'range bounds dataBox databox',
		maxDepth: 'depth maxDepth maxdepth level maxLevel maxlevel levels',
		dtype: 'type dtype format out dst output destination'
		// sort: 'sortBy sortby sort',
		// pick: 'pick levelPoint',
		// nodeSize: 'node nodeSize minNodeSize minSize size'
	})

	// let nodeSize = defined(options.nodeSize, 1)
	var maxDepth = defined(options.maxDepth, 255)
	var bounds = defined(options.bounds, getBounds(srcPoints, 2))
	if (bounds[0] === bounds[2]) { bounds[2]++ }
	if (bounds[1] === bounds[3]) { bounds[3]++ }

	var points = normalize(srcPoints, bounds)

	// init variables
	var n = srcPoints.length >>> 1
	var ids
	if (!options.dtype) { options.dtype = 'array' }

	if (typeof options.dtype === 'string') {
		ids = new (dtype(options.dtype))(n)
	}
	else if (options.dtype) {
		ids = options.dtype
		if (Array.isArray(ids)) { ids.length = n }
	}
	for (var i = 0; i < n; ++i) {
		ids[i] = i
	}

	// point indexes for levels [0: [a,b,c,d], 1: [a,b,c,d,e,f,...], ...]
	var levels = []

	// starting indexes of subranges in sub levels, levels.length * 4
	var sublevels = []

	// unique group ids, sorted in z-curve fashion within levels
	var groups = []

	// level offsets in `ids`
	var offsets = []


	// sort points
	sort(0, 0, 1, ids, 0, 1)


	// return reordered ids with provided methods
	// save level offsets in output buffer
	var offset = 0
	for (var level = 0; level < levels.length; level++) {
		var levelItems = levels[level]
		if (ids.set) { ids.set(levelItems, offset) }
		else {
			for (var i$1 = 0, l = levelItems.length; i$1 < l; i$1++) {
				ids[i$1 + offset] = levelItems[i$1]
			}
		}
		var nextOffset = offset + levels[level].length
		offsets[level] = [offset, nextOffset]
		offset = nextOffset
	}

	ids.range = range

	return ids



	// FIXME: it is possible to create one typed array heap and reuse that to avoid memory blow
	function sort (x, y, diam, ids, level, group) {
		if (!ids.length) { return null }

		// save first point as level representative
		var levelItems = levels[level] || (levels[level] = [])
		var levelGroups = groups[level] || (groups[level] = [])
		var sublevel = sublevels[level] || (sublevels[level] = [])
		var offset = levelItems.length

		level++

		// max depth reached - put all items into a first group
		if (level > maxDepth) {
			for (var i = 0; i < ids.length; i++) {
				levelItems.push(ids[i])
				levelGroups.push(group)
				sublevel.push(null, null, null, null)
			}

			return offset
		}

		levelItems.push(ids[0])
		levelGroups.push(group)

		if (ids.length <= 1) {
			sublevel.push(null, null, null, null)
			return offset
		}


		var d2 = diam * .5
		var cx = x + d2, cy = y + d2

		// distribute points by 4 buckets
		var lolo = [], lohi = [], hilo = [], hihi = []

		for (var i$1 = 1, l = ids.length; i$1 < l; i$1++) {
			var idx = ids[i$1],
				x$1 = points[idx * 2],
				y$1 = points[idx * 2 + 1]
			x$1 < cx ? (y$1 < cy ? lolo.push(idx) : lohi.push(idx)) : (y$1 < cy ? hilo.push(idx) : hihi.push(idx))
		}

		group <<= 2
		sublevel.push(
			sort(x, y, d2, lolo, level, group),
			sort(x, cy, d2, lohi, level, group + 1),
			sort(cx, y, d2, hilo, level, group + 2),
			sort(cx, cy, d2, hihi, level, group + 3)
		)

		return offset
	}

	// get all points within the passed range
	function range () {
		var args = [], len = arguments.length;
		while ( len-- ) args[ len ] = arguments[ len ];

		var options

		if (isObj(args[args.length - 1])) {
			var arg = args.pop()

			// detect if that was a rect object
			if (!args.length && (arg.x != null || arg.l != null || arg.left != null)) {
				args = [arg]
				options = {}
			}

			options = pick(arg, {
				level: 'level maxLevel',
				d: 'd diam diameter r radius px pxSize pixel pixelSize maxD size minSize',
				lod: 'lod details ranges offsets'
			})
		}
		else {
			options = {}
		}

		if (!args.length) { args = bounds }

		var box = rect.apply( void 0, args )

		var ref = [
			Math.min(box.x, box.x + box.width),
			Math.min(box.y, box.y + box.height),
			Math.max(box.x, box.x + box.width),
			Math.max(box.y, box.y + box.height)
		];
		var minX = ref[0];
		var minY = ref[1];
		var maxX = ref[2];
		var maxY = ref[3];

		var ref$1 = normalize([minX, minY, maxX, maxY], bounds );
		var nminX = ref$1[0];
		var nminY = ref$1[1];
		var nmaxX = ref$1[2];
		var nmaxY = ref$1[3];

		var maxLevel = defined(options.level, levels.length)

		// limit maxLevel by px size
		if (options.d != null) {
			var d
			if (typeof options.d === 'number') { d = [options.d, options.d] }
			else if (options.d.length) { d = options.d }

			maxLevel = Math.min(
				Math.max(
					Math.ceil(-log2(Math.abs(d[0]) / (bounds[2] - bounds[0]))),
					Math.ceil(-log2(Math.abs(d[1]) / (bounds[3] - bounds[1])))
				),
				maxLevel
			)
		}
		maxLevel = Math.min(maxLevel, levels.length)

		// return levels of details
		if (options.lod) {
			return lod(nminX, nminY, nmaxX, nmaxY, maxLevel)
		}



		// do selection ids
		var selection = []

		// FIXME: probably we can do LOD here beforehead
		select( 0, 0, 1, 0, 0, 1)

		function select ( lox, loy, d, level, from, to ) {
			if (from === null || to === null) { return }

			var hix = lox + d
			var hiy = loy + d

			// if box does not intersect level - ignore
			if ( nminX > hix || nminY > hiy || nmaxX < lox || nmaxY < loy ) { return }
			if ( level >= maxLevel ) { return }
			if ( from === to ) { return }

			// if points fall into box range - take it
			var levelItems = levels[level]

			if (to === undefined) { to = levelItems.length }

			for (var i = from; i < to; i++) {
				var id = levelItems[i]

				var px = srcPoints[ id * 2 ]
				var py = srcPoints[ id * 2 + 1 ]

				if ( px >= minX && px <= maxX && py >= minY && py <= maxY ) {selection.push(id)
				}
			}

			// for every subsection do select
			var offsets = sublevels[ level ]
			var off0 = offsets[ from * 4 + 0 ]
			var off1 = offsets[ from * 4 + 1 ]
			var off2 = offsets[ from * 4 + 2 ]
			var off3 = offsets[ from * 4 + 3 ]
			var end = nextOffset(offsets, from + 1)

			var d2 = d * .5
			var nextLevel = level + 1
			select( lox, loy, d2, nextLevel, off0, off1 || off2 || off3 || end)
			select( lox, loy + d2, d2, nextLevel, off1, off2 || off3 || end)
			select( lox + d2, loy, d2, nextLevel, off2, off3 || end)
			select( lox + d2, loy + d2, d2, nextLevel, off3, end)
		}

		function nextOffset(offsets, from) {
			var offset = null, i = 0
			while(offset === null) {
				offset = offsets[ from * 4 + i ]
				i++
				if (i > offsets.length) { return null }
			}
			return offset
		}

		return selection
	}

	// get range offsets within levels to render lods appropriate for zoom level
	// TODO: it is possible to store minSize of a point to optimize neede level calc
	function lod (lox, loy, hix, hiy, maxLevel) {
		var ranges = []

		for (var level = 0; level < maxLevel; level++) {
			var levelGroups = groups[level]
			var from = offsets[level][0]

			var levelGroupStart = group(lox, loy, level)
			var levelGroupEnd = group(hix, hiy, level)

			// FIXME: utilize sublevels to speed up search range here
			var startOffset = search.ge(levelGroups, levelGroupStart)
			var endOffset = search.gt(levelGroups, levelGroupEnd, startOffset, levelGroups.length - 1)

			ranges[level] = [startOffset + from, endOffset + from]
		}

		return ranges
	}

	// get group id closest to the x,y coordinate, corresponding to a level
	function group (x, y, level) {
		var group = 1

		var cx = .5, cy = .5
		var diam = .5

		for (var i = 0; i < level; i++) {
			group <<= 2

			group += x < cx ? (y < cy ? 0 : 1) : (y < cy ? 2 : 3)

			diam *= .5

			cx += x < cx ? -diam : diam
			cy += y < cy ? -diam : diam
		}

		return group
	}
}


// normalize points by bounds
function normalize (pts, bounds) {
	var lox = bounds[0];
	var loy = bounds[1];
	var hix = bounds[2];
	var hiy = bounds[3];
	var scaleX = 1.0 / (hix - lox)
	var scaleY = 1.0 / (hiy - loy)
	var result = new Array(pts.length)

	for (var i = 0, n = pts.length / 2; i < n; i++) {
		result[2*i] = clamp((pts[2*i] - lox) * scaleX, 0, 1)
		result[2*i+1] = clamp((pts[2*i+1] - loy) * scaleY, 0, 1)
	}

	return result
}
},{"array-bounds":53,"binary-search-bounds":459,"clamp":103,"defined":152,"dtype":157,"flatten-vertex-data":220,"is-obj":410,"math-log2":421,"parse-rect":448,"pick-by-alias":454}],461:[function(_dereq_,module,exports){
module.exports = preprocessPolygon

var orient = _dereq_('robust-orientation')[3]
var makeSlabs = _dereq_('slab-decomposition')
var makeIntervalTree = _dereq_('interval-tree-1d')
var bsearch = _dereq_('binary-search-bounds')

function visitInterval() {
  return true
}

function intervalSearch(table) {
  return function(x, y) {
    var tree = table[x]
    if(tree) {
      return !!tree.queryPoint(y, visitInterval)
    }
    return false
  }
}

function buildVerticalIndex(segments) {
  var table = {}
  for(var i=0; i<segments.length; ++i) {
    var s = segments[i]
    var x = s[0][0]
    var y0 = s[0][1]
    var y1 = s[1][1]
    var p = [ Math.min(y0, y1), Math.max(y0, y1) ]
    if(x in table) {
      table[x].push(p)
    } else {
      table[x] = [ p ]
    }
  }
  var intervalTable = {}
  var keys = Object.keys(table)
  for(var i=0; i<keys.length; ++i) {
    var segs = table[keys[i]]
    intervalTable[keys[i]] = makeIntervalTree(segs)
  }
  return intervalSearch(intervalTable)
}

function buildSlabSearch(slabs, coordinates) {
  return function(p) {
    var bucket = bsearch.le(coordinates, p[0])
    if(bucket < 0) {
      return 1
    }
    var root = slabs[bucket]
    if(!root) {
      if(bucket > 0 && coordinates[bucket] === p[0]) {
        root = slabs[bucket-1]
      } else {
        return 1
      }
    }
    var lastOrientation = 1
    while(root) {
      var s = root.key
      var o = orient(p, s[0], s[1])
      if(s[0][0] < s[1][0]) {
        if(o < 0) {
          root = root.left
        } else if(o > 0) {
          lastOrientation = -1
          root = root.right
        } else {
          return 0
        }
      } else {
        if(o > 0) {
          root = root.left
        } else if(o < 0) {
          lastOrientation = 1
          root = root.right
        } else {
          return 0
        }
      }
    }
    return lastOrientation
  }
}

function classifyEmpty(p) {
  return 1
}

function createClassifyVertical(testVertical) {
  return function classify(p) {
    if(testVertical(p[0], p[1])) {
      return 0
    }
    return 1
  }
}

function createClassifyPointDegen(testVertical, testNormal) {
  return function classify(p) {
    if(testVertical(p[0], p[1])) {
      return 0
    }
    return testNormal(p)
  }
}

function preprocessPolygon(loops) {
  //Compute number of loops
  var numLoops = loops.length

  //Unpack segments
  var segments = []
  var vsegments = []
  var ptr = 0
  for(var i=0; i<numLoops; ++i) {
    var loop = loops[i]
    var numVertices = loop.length
    for(var s=numVertices-1,t=0; t<numVertices; s=(t++)) {
      var a = loop[s]
      var b = loop[t]
      if(a[0] === b[0]) {
        vsegments.push([a,b])
      } else {
        segments.push([a,b])
      }
    }
  }

  //Degenerate case: All loops are empty
  if(segments.length === 0) {
    if(vsegments.length === 0) {
      return classifyEmpty
    } else {
      return createClassifyVertical(buildVerticalIndex(vsegments))
    }
  }

  //Build slab decomposition
  var slabs = makeSlabs(segments)
  var testSlab = buildSlabSearch(slabs.slabs, slabs.coordinates)

  if(vsegments.length === 0) {
    return testSlab
  } else {
    return createClassifyPointDegen(
      buildVerticalIndex(vsegments),
      testSlab)
  }
}
},{"binary-search-bounds":79,"interval-tree-1d":403,"robust-orientation":491,"slab-decomposition":507}],462:[function(_dereq_,module,exports){
/*
 * @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc
 * @license MIT
 * @preserve Project Home: https://github.com/voidqk/polybooljs
 */

var BuildLog = _dereq_('./lib/build-log');
var Epsilon = _dereq_('./lib/epsilon');
var Intersecter = _dereq_('./lib/intersecter');
var SegmentChainer = _dereq_('./lib/segment-chainer');
var SegmentSelector = _dereq_('./lib/segment-selector');
var GeoJSON = _dereq_('./lib/geojson');

var buildLog = false;
var epsilon = Epsilon();

var PolyBool;
PolyBool = {
	// getter/setter for buildLog
	buildLog: function(bl){
		if (bl === true)
			buildLog = BuildLog();
		else if (bl === false)
			buildLog = false;
		return buildLog === false ? false : buildLog.list;
	},
	// getter/setter for epsilon
	epsilon: function(v){
		return epsilon.epsilon(v);
	},

	// core API
	segments: function(poly){
		var i = Intersecter(true, epsilon, buildLog);
		poly.regions.forEach(i.addRegion);
		return {
			segments: i.calculate(poly.inverted),
			inverted: poly.inverted
		};
	},
	combine: function(segments1, segments2){
		var i3 = Intersecter(false, epsilon, buildLog);
		return {
			combined: i3.calculate(
				segments1.segments, segments1.inverted,
				segments2.segments, segments2.inverted
			),
			inverted1: segments1.inverted,
			inverted2: segments2.inverted
		};
	},
	selectUnion: function(combined){
		return {
			segments: SegmentSelector.union(combined.combined, buildLog),
			inverted: combined.inverted1 || combined.inverted2
		}
	},
	selectIntersect: function(combined){
		return {
			segments: SegmentSelector.intersect(combined.combined, buildLog),
			inverted: combined.inverted1 && combined.inverted2
		}
	},
	selectDifference: function(combined){
		return {
			segments: SegmentSelector.difference(combined.combined, buildLog),
			inverted: combined.inverted1 && !combined.inverted2
		}
	},
	selectDifferenceRev: function(combined){
		return {
			segments: SegmentSelector.differenceRev(combined.combined, buildLog),
			inverted: !combined.inverted1 && combined.inverted2
		}
	},
	selectXor: function(combined){
		return {
			segments: SegmentSelector.xor(combined.combined, buildLog),
			inverted: combined.inverted1 !== combined.inverted2
		}
	},
	polygon: function(segments){
		return {
			regions: SegmentChainer(segments.segments, epsilon, buildLog),
			inverted: segments.inverted
		};
	},

	// GeoJSON converters
	polygonFromGeoJSON: function(geojson){
		return GeoJSON.toPolygon(PolyBool, geojson);
	},
	polygonToGeoJSON: function(poly){
		return GeoJSON.fromPolygon(PolyBool, epsilon, poly);
	},

	// helper functions for common operations
	union: function(poly1, poly2){
		return operate(poly1, poly2, PolyBool.selectUnion);
	},
	intersect: function(poly1, poly2){
		return operate(poly1, poly2, PolyBool.selectIntersect);
	},
	difference: function(poly1, poly2){
		return operate(poly1, poly2, PolyBool.selectDifference);
	},
	differenceRev: function(poly1, poly2){
		return operate(poly1, poly2, PolyBool.selectDifferenceRev);
	},
	xor: function(poly1, poly2){
		return operate(poly1, poly2, PolyBool.selectXor);
	}
};

function operate(poly1, poly2, selector){
	var seg1 = PolyBool.segments(poly1);
	var seg2 = PolyBool.segments(poly2);
	var comb = PolyBool.combine(seg1, seg2);
	var seg3 = selector(comb);
	return PolyBool.polygon(seg3);
}

if (typeof window === 'object')
	window.PolyBool = PolyBool;

module.exports = PolyBool;

},{"./lib/build-log":463,"./lib/epsilon":464,"./lib/geojson":465,"./lib/intersecter":466,"./lib/segment-chainer":468,"./lib/segment-selector":469}],463:[function(_dereq_,module,exports){
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs

//
// used strictly for logging the processing of the algorithm... only useful if you intend on
// looking under the covers (for pretty UI's or debugging)
//

function BuildLog(){
	var my;
	var nextSegmentId = 0;
	var curVert = false;

	function push(type, data){
		my.list.push({
			type: type,
			data: data ? JSON.parse(JSON.stringify(data)) : void 0
		});
		return my;
	}

	my = {
		list: [],
		segmentId: function(){
			return nextSegmentId++;
		},
		checkIntersection: function(seg1, seg2){
			return push('check', { seg1: seg1, seg2: seg2 });
		},
		segmentChop: function(seg, end){
			push('div_seg', { seg: seg, pt: end });
			return push('chop', { seg: seg, pt: end });
		},
		statusRemove: function(seg){
			return push('pop_seg', { seg: seg });
		},
		segmentUpdate: function(seg){
			return push('seg_update', { seg: seg });
		},
		segmentNew: function(seg, primary){
			return push('new_seg', { seg: seg, primary: primary });
		},
		segmentRemove: function(seg){
			return push('rem_seg', { seg: seg });
		},
		tempStatus: function(seg, above, below){
			return push('temp_status', { seg: seg, above: above, below: below });
		},
		rewind: function(seg){
			return push('rewind', { seg: seg });
		},
		status: function(seg, above, below){
			return push('status', { seg: seg, above: above, below: below });
		},
		vert: function(x){
			if (x === curVert)
				return my;
			curVert = x;
			return push('vert', { x: x });
		},
		log: function(data){
			if (typeof data !== 'string')
				data = JSON.stringify(data, false, '  ');
			return push('log', { txt: data });
		},
		reset: function(){
			return push('reset');
		},
		selected: function(segs){
			return push('selected', { segs: segs });
		},
		chainStart: function(seg){
			return push('chain_start', { seg: seg });
		},
		chainRemoveHead: function(index, pt){
			return push('chain_rem_head', { index: index, pt: pt });
		},
		chainRemoveTail: function(index, pt){
			return push('chain_rem_tail', { index: index, pt: pt });
		},
		chainNew: function(pt1, pt2){
			return push('chain_new', { pt1: pt1, pt2: pt2 });
		},
		chainMatch: function(index){
			return push('chain_match', { index: index });
		},
		chainClose: function(index){
			return push('chain_close', { index: index });
		},
		chainAddHead: function(index, pt){
			return push('chain_add_head', { index: index, pt: pt });
		},
		chainAddTail: function(index, pt){
			return push('chain_add_tail', { index: index, pt: pt, });
		},
		chainConnect: function(index1, index2){
			return push('chain_con', { index1: index1, index2: index2 });
		},
		chainReverse: function(index){
			return push('chain_rev', { index: index });
		},
		chainJoin: function(index1, index2){
			return push('chain_join', { index1: index1, index2: index2 });
		},
		done: function(){
			return push('done');
		}
	};
	return my;
}

module.exports = BuildLog;

},{}],464:[function(_dereq_,module,exports){
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs

//
// provides the raw computation functions that takes epsilon into account
//
// zero is defined to be between (-epsilon, epsilon) exclusive
//

function Epsilon(eps){
	if (typeof eps !== 'number')
		eps = 0.0000000001; // sane default? sure why not
	var my = {
		epsilon: function(v){
			if (typeof v === 'number')
				eps = v;
			return eps;
		},
		pointAboveOrOnLine: function(pt, left, right){
			var Ax = left[0];
			var Ay = left[1];
			var Bx = right[0];
			var By = right[1];
			var Cx = pt[0];
			var Cy = pt[1];
			return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps;
		},
		pointBetween: function(p, left, right){
			// p must be collinear with left->right
			// returns false if p == left, p == right, or left == right
			var d_py_ly = p[1] - left[1];
			var d_rx_lx = right[0] - left[0];
			var d_px_lx = p[0] - left[0];
			var d_ry_ly = right[1] - left[1];

			var dot = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly;
			// if `dot` is 0, then `p` == `left` or `left` == `right` (reject)
			// if `dot` is less than 0, then `p` is to the left of `left` (reject)
			if (dot < eps)
				return false;

			var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly;
			// if `dot` > `sqlen`, then `p` is to the right of `right` (reject)
			// therefore, if `dot - sqlen` is greater than 0, then `p` is to the right of `right` (reject)
			if (dot - sqlen > -eps)
				return false;

			return true;
		},
		pointsSameX: function(p1, p2){
			return Math.abs(p1[0] - p2[0]) < eps;
		},
		pointsSameY: function(p1, p2){
			return Math.abs(p1[1] - p2[1]) < eps;
		},
		pointsSame: function(p1, p2){
			return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2);
		},
		pointsCompare: function(p1, p2){
			// returns -1 if p1 is smaller, 1 if p2 is smaller, 0 if equal
			if (my.pointsSameX(p1, p2))
				return my.pointsSameY(p1, p2) ? 0 : (p1[1] < p2[1] ? -1 : 1);
			return p1[0] < p2[0] ? -1 : 1;
		},
		pointsCollinear: function(pt1, pt2, pt3){
			// does pt1->pt2->pt3 make a straight line?
			// essentially this is just checking to see if the slope(pt1->pt2) === slope(pt2->pt3)
			// if slopes are equal, then they must be collinear, because they share pt2
			var dx1 = pt1[0] - pt2[0];
			var dy1 = pt1[1] - pt2[1];
			var dx2 = pt2[0] - pt3[0];
			var dy2 = pt2[1] - pt3[1];
			return Math.abs(dx1 * dy2 - dx2 * dy1) < eps;
		},
		linesIntersect: function(a0, a1, b0, b1){
			// returns false if the lines are coincident (e.g., parallel or on top of each other)
			//
			// returns an object if the lines intersect:
			//   {
			//     pt: [x, y],    where the intersection point is at
			//     alongA: where intersection point is along A,
			//     alongB: where intersection point is along B
			//   }
			//
			//  alongA and alongB will each be one of: -2, -1, 0, 1, 2
			//
			//  with the following meaning:
			//
			//    -2   intersection point is before segment's first point
			//    -1   intersection point is directly on segment's first point
			//     0   intersection point is between segment's first and second points (exclusive)
			//     1   intersection point is directly on segment's second point
			//     2   intersection point is after segment's second point
			var adx = a1[0] - a0[0];
			var ady = a1[1] - a0[1];
			var bdx = b1[0] - b0[0];
			var bdy = b1[1] - b0[1];

			var axb = adx * bdy - ady * bdx;
			if (Math.abs(axb) < eps)
				return false; // lines are coincident

			var dx = a0[0] - b0[0];
			var dy = a0[1] - b0[1];

			var A = (bdx * dy - bdy * dx) / axb;
			var B = (adx * dy - ady * dx) / axb;

			var ret = {
				alongA: 0,
				alongB: 0,
				pt: [
					a0[0] + A * adx,
					a0[1] + A * ady
				]
			};

			// categorize where intersection point is along A and B

			if (A <= -eps)
				ret.alongA = -2;
			else if (A < eps)
				ret.alongA = -1;
			else if (A - 1 <= -eps)
				ret.alongA = 0;
			else if (A - 1 < eps)
				ret.alongA = 1;
			else
				ret.alongA = 2;

			if (B <= -eps)
				ret.alongB = -2;
			else if (B < eps)
				ret.alongB = -1;
			else if (B - 1 <= -eps)
				ret.alongB = 0;
			else if (B - 1 < eps)
				ret.alongB = 1;
			else
				ret.alongB = 2;

			return ret;
		},
		pointInsideRegion: function(pt, region){
			var x = pt[0];
			var y = pt[1];
			var last_x = region[region.length - 1][0];
			var last_y = region[region.length - 1][1];
			var inside = false;
			for (var i = 0; i < region.length; i++){
				var curr_x = region[i][0];
				var curr_y = region[i][1];

				// if y is between curr_y and last_y, and
				// x is to the right of the boundary created by the line
				if ((curr_y - y > eps) != (last_y - y > eps) &&
					(last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps)
					inside = !inside

				last_x = curr_x;
				last_y = curr_y;
			}
			return inside;
		}
	};
	return my;
}

module.exports = Epsilon;

},{}],465:[function(_dereq_,module,exports){
// (c) Copyright 2017, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs

//
// convert between PolyBool polygon format and GeoJSON formats (Polygon and MultiPolygon)
//

var GeoJSON = {
	// convert a GeoJSON object to a PolyBool polygon
	toPolygon: function(PolyBool, geojson){

		// converts list of LineString's to segments
		function GeoPoly(coords){
			// check for empty coords
			if (coords.length <= 0)
				return PolyBool.segments({ inverted: false, regions: [] });

			// convert LineString to segments
			function LineString(ls){
				// remove tail which should be the same as head
				var reg = ls.slice(0, ls.length - 1);
				return PolyBool.segments({ inverted: false, regions: [reg] });
			}

			// the first LineString is considered the outside
			var out = LineString(coords[0]);

			// the rest of the LineStrings are considered interior holes, so subtract them from the
			// current result
			for (var i = 1; i < coords.length; i++)
				out = PolyBool.selectDifference(PolyBool.combine(out, LineString(coords[i])));

			return out;
		}

		if (geojson.type === 'Polygon'){
			// single polygon, so just convert it and we're done
			return PolyBool.polygon(GeoPoly(geojson.coordinates));
		}
		else if (geojson.type === 'MultiPolygon'){
			// multiple polygons, so union all the polygons together
			var out = PolyBool.segments({ inverted: false, regions: [] });
			for (var i = 0; i < geojson.coordinates.length; i++)
				out = PolyBool.selectUnion(PolyBool.combine(out, GeoPoly(geojson.coordinates[i])));
			return PolyBool.polygon(out);
		}
		throw new Error('PolyBool: Cannot convert GeoJSON object to PolyBool polygon');
	},

	// convert a PolyBool polygon to a GeoJSON object
	fromPolygon: function(PolyBool, eps, poly){
		// make sure out polygon is clean
		poly = PolyBool.polygon(PolyBool.segments(poly));

		// test if r1 is inside r2
		function regionInsideRegion(r1, r2){
			// we're guaranteed no lines intersect (because the polygon is clean), but a vertex
			// could be on the edge -- so we just average pt[0] and pt[1] to produce a point on the
			// edge of the first line, which cannot be on an edge
			return eps.pointInsideRegion([
				(r1[0][0] + r1[1][0]) * 0.5,
				(r1[0][1] + r1[1][1]) * 0.5
			], r2);
		}

		// calculate inside heirarchy
		//
		//  _____________________   _______    roots -> A       -> F
		// |          A          | |   F   |            |          |
		// |  _______   _______  | |  ___  |            +-- B      +-- G
		// | |   B   | |   C   | | | |   | |            |   |
		// | |  ___  | |  ___  | | | |   | |            |   +-- D
		// | | | D | | | | E | | | | | G | |            |
		// | | |___| | | |___| | | | |   | |            +-- C
		// | |_______| |_______| | | |___| |                |
		// |_____________________| |_______|                +-- E

		function newNode(region){
			return {
				region: region,
				children: []
			};
		}

		var roots = newNode(null);

		function addChild(root, region){
			// first check if we're inside any children
			for (var i = 0; i < root.children.length; i++){
				var child = root.children[i];
				if (regionInsideRegion(region, child.region)){
					// we are, so insert inside them instead
					addChild(child, region);
					return;
				}
			}

			// not inside any children, so check to see if any children are inside us
			var node = newNode(region);
			for (var i = 0; i < root.children.length; i++){
				var child = root.children[i];
				if (regionInsideRegion(child.region, region)){
					// oops... move the child beneath us, and remove them from root
					node.children.push(child);
					root.children.splice(i, 1);
					i--;
				}
			}

			// now we can add ourselves
			root.children.push(node);
		}

		// add all regions to the root
		for (var i = 0; i < poly.regions.length; i++){
			var region = poly.regions[i];
			if (region.length < 3) // regions must have at least 3 points (sanity check)
				continue;
			addChild(roots, region);
		}

		// with our heirarchy, we can distinguish between exterior borders, and interior holes
		// the root nodes are exterior, children are interior, children's children are exterior,
		// children's children's children are interior, etc

		// while we're at it, exteriors are counter-clockwise, and interiors are clockwise

		function forceWinding(region, clockwise){
			// first, see if we're clockwise or counter-clockwise
			// https://en.wikipedia.org/wiki/Shoelace_formula
			var winding = 0;
			var last_x = region[region.length - 1][0];
			var last_y = region[region.length - 1][1];
			var copy = [];
			for (var i = 0; i < region.length; i++){
				var curr_x = region[i][0];
				var curr_y = region[i][1];
				copy.push([curr_x, curr_y]); // create a copy while we're at it
				winding += curr_y * last_x - curr_x * last_y;
				last_x = curr_x;
				last_y = curr_y;
			}
			// this assumes Cartesian coordinates (Y is positive going up)
			var isclockwise = winding < 0;
			if (isclockwise !== clockwise)
				copy.reverse();
			// while we're here, the last point must be the first point...
			copy.push([copy[0][0], copy[0][1]]);
			return copy;
		}

		var geopolys = [];

		function addExterior(node){
			var poly = [forceWinding(node.region, false)];
			geopolys.push(poly);
			// children of exteriors are interior
			for (var i = 0; i < node.children.length; i++)
				poly.push(getInterior(node.children[i]));
		}

		function getInterior(node){
			// children of interiors are exterior
			for (var i = 0; i < node.children.length; i++)
				addExterior(node.children[i]);
			// return the clockwise interior
			return forceWinding(node.region, true);
		}

		// root nodes are exterior
		for (var i = 0; i < roots.children.length; i++)
			addExterior(roots.children[i]);

		// lastly, construct the approrpriate GeoJSON object

		if (geopolys.length <= 0) // empty GeoJSON Polygon
			return { type: 'Polygon', coordinates: [] };
		if (geopolys.length == 1) // use a GeoJSON Polygon
			return { type: 'Polygon', coordinates: geopolys[0] };
		return { // otherwise, use a GeoJSON MultiPolygon
			type: 'MultiPolygon',
			coordinates: geopolys
		};
	}
};

module.exports = GeoJSON;

},{}],466:[function(_dereq_,module,exports){
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs

//
// this is the core work-horse
//

var LinkedList = _dereq_('./linked-list');

function Intersecter(selfIntersection, eps, buildLog){
	// selfIntersection is true/false depending on the phase of the overall algorithm

	//
	// segment creation
	//

	function segmentNew(start, end){
		return {
			id: buildLog ? buildLog.segmentId() : -1,
			start: start,
			end: end,
			myFill: {
				above: null, // is there fill above us?
				below: null  // is there fill below us?
			},
			otherFill: null
		};
	}

	function segmentCopy(start, end, seg){
		return {
			id: buildLog ? buildLog.segmentId() : -1,
			start: start,
			end: end,
			myFill: {
				above: seg.myFill.above,
				below: seg.myFill.below
			},
			otherFill: null
		};
	}

	//
	// event logic
	//

	var event_root = LinkedList.create();

	function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2){
		// compare the selected points first
		var comp = eps.pointsCompare(p1_1, p2_1);
		if (comp !== 0)
			return comp;
		// the selected points are the same

		if (eps.pointsSame(p1_2, p2_2)) // if the non-selected points are the same too...
			return 0; // then the segments are equal

		if (p1_isStart !== p2_isStart) // if one is a start and the other isn't...
			return p1_isStart ? 1 : -1; // favor the one that isn't the start

		// otherwise, we'll have to calculate which one is below the other manually
		return eps.pointAboveOrOnLine(p1_2,
			p2_isStart ? p2_1 : p2_2, // order matters
			p2_isStart ? p2_2 : p2_1
		) ? 1 : -1;
	}

	function eventAdd(ev, other_pt){
		event_root.insertBefore(ev, function(here){
			// should ev be inserted before here?
			var comp = eventCompare(
				ev  .isStart, ev  .pt,      other_pt,
				here.isStart, here.pt, here.other.pt
			);
			return comp < 0;
		});
	}

	function eventAddSegmentStart(seg, primary){
		var ev_start = LinkedList.node({
			isStart: true,
			pt: seg.start,
			seg: seg,
			primary: primary,
			other: null,
			status: null
		});
		eventAdd(ev_start, seg.end);
		return ev_start;
	}

	function eventAddSegmentEnd(ev_start, seg, primary){
		var ev_end = LinkedList.node({
			isStart: false,
			pt: seg.end,
			seg: seg,
			primary: primary,
			other: ev_start,
			status: null
		});
		ev_start.other = ev_end;
		eventAdd(ev_end, ev_start.pt);
	}

	function eventAddSegment(seg, primary){
		var ev_start = eventAddSegmentStart(seg, primary);
		eventAddSegmentEnd(ev_start, seg, primary);
		return ev_start;
	}

	function eventUpdateEnd(ev, end){
		// slides an end backwards
		//   (start)------------(end)    to:
		//   (start)---(end)

		if (buildLog)
			buildLog.segmentChop(ev.seg, end);

		ev.other.remove();
		ev.seg.end = end;
		ev.other.pt = end;
		eventAdd(ev.other, ev.pt);
	}

	function eventDivide(ev, pt){
		var ns = segmentCopy(pt, ev.seg.end, ev.seg);
		eventUpdateEnd(ev, pt);
		return eventAddSegment(ns, ev.primary);
	}

	function calculate(primaryPolyInverted, secondaryPolyInverted){
		// if selfIntersection is true then there is no secondary polygon, so that isn't used

		//
		// status logic
		//

		var status_root = LinkedList.create();

		function statusCompare(ev1, ev2){
			var a1 = ev1.seg.start;
			var a2 = ev1.seg.end;
			var b1 = ev2.seg.start;
			var b2 = ev2.seg.end;

			if (eps.pointsCollinear(a1, b1, b2)){
				if (eps.pointsCollinear(a2, b1, b2))
					return 1;//eventCompare(true, a1, a2, true, b1, b2);
				return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1;
			}
			return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1;
		}

		function statusFindSurrounding(ev){
			return status_root.findTransition(function(here){
				var comp = statusCompare(ev, here.ev);
				return comp > 0;
			});
		}

		function checkIntersection(ev1, ev2){
			// returns the segment equal to ev1, or false if nothing equal

			var seg1 = ev1.seg;
			var seg2 = ev2.seg;
			var a1 = seg1.start;
			var a2 = seg1.end;
			var b1 = seg2.start;
			var b2 = seg2.end;

			if (buildLog)
				buildLog.checkIntersection(seg1, seg2);

			var i = eps.linesIntersect(a1, a2, b1, b2);

			if (i === false){
				// segments are parallel or coincident

				// if points aren't collinear, then the segments are parallel, so no intersections
				if (!eps.pointsCollinear(a1, a2, b1))
					return false;
				// otherwise, segments are on top of each other somehow (aka coincident)

				if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1))
					return false; // segments touch at endpoints... no intersection

				var a1_equ_b1 = eps.pointsSame(a1, b1);
				var a2_equ_b2 = eps.pointsSame(a2, b2);

				if (a1_equ_b1 && a2_equ_b2)
					return ev2; // segments are exactly equal

				var a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2);
				var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2);

				// handy for debugging:
				// buildLog.log({
				//	a1_equ_b1: a1_equ_b1,
				//	a2_equ_b2: a2_equ_b2,
				//	a1_between: a1_between,
				//	a2_between: a2_between
				// });

				if (a1_equ_b1){
					if (a2_between){
						//  (a1)---(a2)
						//  (b1)----------(b2)
						eventDivide(ev2, a2);
					}
					else{
						//  (a1)----------(a2)
						//  (b1)---(b2)
						eventDivide(ev1, b2);
					}
					return ev2;
				}
				else if (a1_between){
					if (!a2_equ_b2){
						// make a2 equal to b2
						if (a2_between){
							//         (a1)---(a2)
							//  (b1)-----------------(b2)
							eventDivide(ev2, a2);
						}
						else{
							//         (a1)----------(a2)
							//  (b1)----------(b2)
							eventDivide(ev1, b2);
						}
					}

					//         (a1)---(a2)
					//  (b1)----------(b2)
					eventDivide(ev2, a1);
				}
			}
			else{
				// otherwise, lines intersect at i.pt, which may or may not be between the endpoints

				// is A divided between its endpoints? (exclusive)
				if (i.alongA === 0){
					if (i.alongB === -1) // yes, at exactly b1
						eventDivide(ev1, b1);
					else if (i.alongB === 0) // yes, somewhere between B's endpoints
						eventDivide(ev1, i.pt);
					else if (i.alongB === 1) // yes, at exactly b2
						eventDivide(ev1, b2);
				}

				// is B divided between its endpoints? (exclusive)
				if (i.alongB === 0){
					if (i.alongA === -1) // yes, at exactly a1
						eventDivide(ev2, a1);
					else if (i.alongA === 0) // yes, somewhere between A's endpoints (exclusive)
						eventDivide(ev2, i.pt);
					else if (i.alongA === 1) // yes, at exactly a2
						eventDivide(ev2, a2);
				}
			}
			return false;
		}

		//
		// main event loop
		//
		var segments = [];
		while (!event_root.isEmpty()){
			var ev = event_root.getHead();

			if (buildLog)
				buildLog.vert(ev.pt[0]);

			if (ev.isStart){

				if (buildLog)
					buildLog.segmentNew(ev.seg, ev.primary);

				var surrounding = statusFindSurrounding(ev);
				var above = surrounding.before ? surrounding.before.ev : null;
				var below = surrounding.after ? surrounding.after.ev : null;

				if (buildLog){
					buildLog.tempStatus(
						ev.seg,
						above ? above.seg : false,
						below ? below.seg : false
					);
				}

				function checkBothIntersections(){
					if (above){
						var eve = checkIntersection(ev, above);
						if (eve)
							return eve;
					}
					if (below)
						return checkIntersection(ev, below);
					return false;
				}

				var eve = checkBothIntersections();
				if (eve){
					// ev and eve are equal
					// we'll keep eve and throw away ev

					// merge ev.seg's fill information into eve.seg

					if (selfIntersection){
						var toggle; // are we a toggling edge?
						if (ev.seg.myFill.below === null)
							toggle = true;
						else
							toggle = ev.seg.myFill.above !== ev.seg.myFill.below;

						// merge two segments that belong to the same polygon
						// think of this as sandwiching two segments together, where `eve.seg` is
						// the bottom -- this will cause the above fill flag to toggle
						if (toggle)
							eve.seg.myFill.above = !eve.seg.myFill.above;
					}
					else{
						// merge two segments that belong to different polygons
						// each segment has distinct knowledge, so no special logic is needed
						// note that this can only happen once per segment in this phase, because we
						// are guaranteed that all self-intersections are gone
						eve.seg.otherFill = ev.seg.myFill;
					}

					if (buildLog)
						buildLog.segmentUpdate(eve.seg);

					ev.other.remove();
					ev.remove();
				}

				if (event_root.getHead() !== ev){
					// something was inserted before us in the event queue, so loop back around and
					// process it before continuing
					if (buildLog)
						buildLog.rewind(ev.seg);
					continue;
				}

				//
				// calculate fill flags
				//
				if (selfIntersection){
					var toggle; // are we a toggling edge?
					if (ev.seg.myFill.below === null) // if we are a new segment...
						toggle = true; // then we toggle
					else // we are a segment that has previous knowledge from a division
						toggle = ev.seg.myFill.above !== ev.seg.myFill.below; // calculate toggle

					// next, calculate whether we are filled below us
					if (!below){ // if nothing is below us...
						// we are filled below us if the polygon is inverted
						ev.seg.myFill.below = primaryPolyInverted;
					}
					else{
						// otherwise, we know the answer -- it's the same if whatever is below
						// us is filled above it
						ev.seg.myFill.below = below.seg.myFill.above;
					}

					// since now we know if we're filled below us, we can calculate whether
					// we're filled above us by applying toggle to whatever is below us
					if (toggle)
						ev.seg.myFill.above = !ev.seg.myFill.below;
					else
						ev.seg.myFill.above = ev.seg.myFill.below;
				}
				else{
					// now we fill in any missing transition information, since we are all-knowing
					// at this point

					if (ev.seg.otherFill === null){
						// if we don't have other information, then we need to figure out if we're
						// inside the other polygon
						var inside;
						if (!below){
							// if nothing is below us, then we're inside if the other polygon is
							// inverted
							inside =
								ev.primary ? secondaryPolyInverted : primaryPolyInverted;
						}
						else{ // otherwise, something is below us
							// so copy the below segment's other polygon's above
							if (ev.primary === below.primary)
								inside = below.seg.otherFill.above;
							else
								inside = below.seg.myFill.above;
						}
						ev.seg.otherFill = {
							above: inside,
							below: inside
						};
					}
				}

				if (buildLog){
					buildLog.status(
						ev.seg,
						above ? above.seg : false,
						below ? below.seg : false
					);
				}

				// insert the status and remember it for later removal
				ev.other.status = surrounding.insert(LinkedList.node({ ev: ev }));
			}
			else{
				var st = ev.status;

				if (st === null){
					throw new Error('PolyBool: Zero-length segment detected; your epsilon is ' +
						'probably too small or too large');
				}

				// removing the status will create two new adjacent edges, so we'll need to check
				// for those
				if (status_root.exists(st.prev) && status_root.exists(st.next))
					checkIntersection(st.prev.ev, st.next.ev);

				if (buildLog)
					buildLog.statusRemove(st.ev.seg);

				// remove the status
				st.remove();

				// if we've reached this point, we've calculated everything there is to know, so
				// save the segment for reporting
				if (!ev.primary){
					// make sure `seg.myFill` actually points to the primary polygon though
					var s = ev.seg.myFill;
					ev.seg.myFill = ev.seg.otherFill;
					ev.seg.otherFill = s;
				}
				segments.push(ev.seg);
			}

			// remove the event and continue
			event_root.getHead().remove();
		}

		if (buildLog)
			buildLog.done();

		return segments;
	}

	// return the appropriate API depending on what we're doing
	if (!selfIntersection){
		// performing combination of polygons, so only deal with already-processed segments
		return {
			calculate: function(segments1, inverted1, segments2, inverted2){
				// segmentsX come from the self-intersection API, or this API
				// invertedX is whether we treat that list of segments as an inverted polygon or not
				// returns segments that can be used for further operations
				segments1.forEach(function(seg){
					eventAddSegment(segmentCopy(seg.start, seg.end, seg), true);
				});
				segments2.forEach(function(seg){
					eventAddSegment(segmentCopy(seg.start, seg.end, seg), false);
				});
				return calculate(inverted1, inverted2);
			}
		};
	}

	// otherwise, performing self-intersection, so deal with regions
	return {
		addRegion: function(region){
			// regions are a list of points:
			//  [ [0, 0], [100, 0], [50, 100] ]
			// you can add multiple regions before running calculate
			var pt1;
			var pt2 = region[region.length - 1];
			for (var i = 0; i < region.length; i++){
				pt1 = pt2;
				pt2 = region[i];

				var forward = eps.pointsCompare(pt1, pt2);
				if (forward === 0) // points are equal, so we have a zero-length segment
					continue; // just skip it

				eventAddSegment(
					segmentNew(
						forward < 0 ? pt1 : pt2,
						forward < 0 ? pt2 : pt1
					),
					true
				);
			}
		},
		calculate: function(inverted){
			// is the polygon inverted?
			// returns segments
			return calculate(inverted, false);
		}
	};
}

module.exports = Intersecter;

},{"./linked-list":467}],467:[function(_dereq_,module,exports){
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs

//
// simple linked list implementation that allows you to traverse down nodes and save positions
//

var LinkedList = {
	create: function(){
		var my = {
			root: { root: true, next: null },
			exists: function(node){
				if (node === null || node === my.root)
					return false;
				return true;
			},
			isEmpty: function(){
				return my.root.next === null;
			},
			getHead: function(){
				return my.root.next;
			},
			insertBefore: function(node, check){
				var last = my.root;
				var here = my.root.next;
				while (here !== null){
					if (check(here)){
						node.prev = here.prev;
						node.next = here;
						here.prev.next = node;
						here.prev = node;
						return;
					}
					last = here;
					here = here.next;
				}
				last.next = node;
				node.prev = last;
				node.next = null;
			},
			findTransition: function(check){
				var prev = my.root;
				var here = my.root.next;
				while (here !== null){
					if (check(here))
						break;
					prev = here;
					here = here.next;
				}
				return {
					before: prev === my.root ? null : prev,
					after: here,
					insert: function(node){
						node.prev = prev;
						node.next = here;
						prev.next = node;
						if (here !== null)
							here.prev = node;
						return node;
					}
				};
			}
		};
		return my;
	},
	node: function(data){
		data.prev = null;
		data.next = null;
		data.remove = function(){
			data.prev.next = data.next;
			if (data.next)
				data.next.prev = data.prev;
			data.prev = null;
			data.next = null;
		};
		return data;
	}
};

module.exports = LinkedList;

},{}],468:[function(_dereq_,module,exports){
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs

//
// converts a list of segments into a list of regions, while also removing unnecessary verticies
//

function SegmentChainer(segments, eps, buildLog){
	var chains = [];
	var regions = [];

	segments.forEach(function(seg){
		var pt1 = seg.start;
		var pt2 = seg.end;
		if (eps.pointsSame(pt1, pt2)){
			console.warn('PolyBool: Warning: Zero-length segment detected; your epsilon is ' +
				'probably too small or too large');
			return;
		}

		if (buildLog)
			buildLog.chainStart(seg);

		// search for two chains that this segment matches
		var first_match = {
			index: 0,
			matches_head: false,
			matches_pt1: false
		};
		var second_match = {
			index: 0,
			matches_head: false,
			matches_pt1: false
		};
		var next_match = first_match;
		function setMatch(index, matches_head, matches_pt1){
			// return true if we've matched twice
			next_match.index = index;
			next_match.matches_head = matches_head;
			next_match.matches_pt1 = matches_pt1;
			if (next_match === first_match){
				next_match = second_match;
				return false;
			}
			next_match = null;
			return true; // we've matched twice, we're done here
		}
		for (var i = 0; i < chains.length; i++){
			var chain = chains[i];
			var head  = chain[0];
			var head2 = chain[1];
			var tail  = chain[chain.length - 1];
			var tail2 = chain[chain.length - 2];
			if (eps.pointsSame(head, pt1)){
				if (setMatch(i, true, true))
					break;
			}
			else if (eps.pointsSame(head, pt2)){
				if (setMatch(i, true, false))
					break;
			}
			else if (eps.pointsSame(tail, pt1)){
				if (setMatch(i, false, true))
					break;
			}
			else if (eps.pointsSame(tail, pt2)){
				if (setMatch(i, false, false))
					break;
			}
		}

		if (next_match === first_match){
			// we didn't match anything, so create a new chain
			chains.push([ pt1, pt2 ]);
			if (buildLog)
				buildLog.chainNew(pt1, pt2);
			return;
		}

		if (next_match === second_match){
			// we matched a single chain

			if (buildLog)
				buildLog.chainMatch(first_match.index);

			// add the other point to the apporpriate end, and check to see if we've closed the
			// chain into a loop

			var index = first_match.index;
			var pt = first_match.matches_pt1 ? pt2 : pt1; // if we matched pt1, then we add pt2, etc
			var addToHead = first_match.matches_head; // if we matched at head, then add to the head

			var chain = chains[index];
			var grow  = addToHead ? chain[0] : chain[chain.length - 1];
			var grow2 = addToHead ? chain[1] : chain[chain.length - 2];
			var oppo  = addToHead ? chain[chain.length - 1] : chain[0];
			var oppo2 = addToHead ? chain[chain.length - 2] : chain[1];

			if (eps.pointsCollinear(grow2, grow, pt)){
				// grow isn't needed because it's directly between grow2 and pt:
				// grow2 ---grow---> pt
				if (addToHead){
					if (buildLog)
						buildLog.chainRemoveHead(first_match.index, pt);
					chain.shift();
				}
				else{
					if (buildLog)
						buildLog.chainRemoveTail(first_match.index, pt);
					chain.pop();
				}
				grow = grow2; // old grow is gone... new grow is what grow2 was
			}

			if (eps.pointsSame(oppo, pt)){
				// we're closing the loop, so remove chain from chains
				chains.splice(index, 1);

				if (eps.pointsCollinear(oppo2, oppo, grow)){
					// oppo isn't needed because it's directly between oppo2 and grow:
					// oppo2 ---oppo--->grow
					if (addToHead){
						if (buildLog)
							buildLog.chainRemoveTail(first_match.index, grow);
						chain.pop();
					}
					else{
						if (buildLog)
							buildLog.chainRemoveHead(first_match.index, grow);
						chain.shift();
					}
				}

				if (buildLog)
					buildLog.chainClose(first_match.index);

				// we have a closed chain!
				regions.push(chain);
				return;
			}

			// not closing a loop, so just add it to the apporpriate side
			if (addToHead){
				if (buildLog)
					buildLog.chainAddHead(first_match.index, pt);
				chain.unshift(pt);
			}
			else{
				if (buildLog)
					buildLog.chainAddTail(first_match.index, pt);
				chain.push(pt);
			}
			return;
		}

		// otherwise, we matched two chains, so we need to combine those chains together

		function reverseChain(index){
			if (buildLog)
				buildLog.chainReverse(index);
			chains[index].reverse(); // gee, that's easy
		}

		function appendChain(index1, index2){
			// index1 gets index2 appended to it, and index2 is removed
			var chain1 = chains[index1];
			var chain2 = chains[index2];
			var tail  = chain1[chain1.length - 1];
			var tail2 = chain1[chain1.length - 2];
			var head  = chain2[0];
			var head2 = chain2[1];

			if (eps.pointsCollinear(tail2, tail, head)){
				// tail isn't needed because it's directly between tail2 and head
				// tail2 ---tail---> head
				if (buildLog)
					buildLog.chainRemoveTail(index1, tail);
				chain1.pop();
				tail = tail2; // old tail is gone... new tail is what tail2 was
			}

			if (eps.pointsCollinear(tail, head, head2)){
				// head isn't needed because it's directly between tail and head2
				// tail ---head---> head2
				if (buildLog)
					buildLog.chainRemoveHead(index2, head);
				chain2.shift();
			}

			if (buildLog)
				buildLog.chainJoin(index1, index2);
			chains[index1] = chain1.concat(chain2);
			chains.splice(index2, 1);
		}

		var F = first_match.index;
		var S = second_match.index;

		if (buildLog)
			buildLog.chainConnect(F, S);

		var reverseF = chains[F].length < chains[S].length; // reverse the shorter chain, if needed
		if (first_match.matches_head){
			if (second_match.matches_head){
				if (reverseF){
					// <<<< F <<<< --- >>>> S >>>>
					reverseChain(F);
					// >>>> F >>>> --- >>>> S >>>>
					appendChain(F, S);
				}
				else{
					// <<<< F <<<< --- >>>> S >>>>
					reverseChain(S);
					// <<<< F <<<< --- <<<< S <<<<   logically same as:
					// >>>> S >>>> --- >>>> F >>>>
					appendChain(S, F);
				}
			}
			else{
				// <<<< F <<<< --- <<<< S <<<<   logically same as:
				// >>>> S >>>> --- >>>> F >>>>
				appendChain(S, F);
			}
		}
		else{
			if (second_match.matches_head){
				// >>>> F >>>> --- >>>> S >>>>
				appendChain(F, S);
			}
			else{
				if (reverseF){
					// >>>> F >>>> --- <<<< S <<<<
					reverseChain(F);
					// <<<< F <<<< --- <<<< S <<<<   logically same as:
					// >>>> S >>>> --- >>>> F >>>>
					appendChain(S, F);
				}
				else{
					// >>>> F >>>> --- <<<< S <<<<
					reverseChain(S);
					// >>>> F >>>> --- >>>> S >>>>
					appendChain(F, S);
				}
			}
		}
	});

	return regions;
}

module.exports = SegmentChainer;

},{}],469:[function(_dereq_,module,exports){
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs

//
// filter a list of segments based on boolean operations
//

function select(segments, selection, buildLog){
	var result = [];
	segments.forEach(function(seg){
		var index =
			(seg.myFill.above ? 8 : 0) +
			(seg.myFill.below ? 4 : 0) +
			((seg.otherFill && seg.otherFill.above) ? 2 : 0) +
			((seg.otherFill && seg.otherFill.below) ? 1 : 0);
		if (selection[index] !== 0){
			// copy the segment to the results, while also calculating the fill status
			result.push({
				id: buildLog ? buildLog.segmentId() : -1,
				start: seg.start,
				end: seg.end,
				myFill: {
					above: selection[index] === 1, // 1 if filled above
					below: selection[index] === 2  // 2 if filled below
				},
				otherFill: null
			});
		}
	});

	if (buildLog)
		buildLog.selected(result);

	return result;
}

var SegmentSelector = {
	union: function(segments, buildLog){ // primary | secondary
		// above1 below1 above2 below2    Keep?               Value
		//    0      0      0      0   =>   no                  0
		//    0      0      0      1   =>   yes filled below    2
		//    0      0      1      0   =>   yes filled above    1
		//    0      0      1      1   =>   no                  0
		//    0      1      0      0   =>   yes filled below    2
		//    0      1      0      1   =>   yes filled below    2
		//    0      1      1      0   =>   no                  0
		//    0      1      1      1   =>   no                  0
		//    1      0      0      0   =>   yes filled above    1
		//    1      0      0      1   =>   no                  0
		//    1      0      1      0   =>   yes filled above    1
		//    1      0      1      1   =>   no                  0
		//    1      1      0      0   =>   no                  0
		//    1      1      0      1   =>   no                  0
		//    1      1      1      0   =>   no                  0
		//    1      1      1      1   =>   no                  0
		return select(segments, [
			0, 2, 1, 0,
			2, 2, 0, 0,
			1, 0, 1, 0,
			0, 0, 0, 0
		], buildLog);
	},
	intersect: function(segments, buildLog){ // primary & secondary
		// above1 below1 above2 below2    Keep?               Value
		//    0      0      0      0   =>   no                  0
		//    0      0      0      1   =>   no                  0
		//    0      0      1      0   =>   no                  0
		//    0      0      1      1   =>   no                  0
		//    0      1      0      0   =>   no                  0
		//    0      1      0      1   =>   yes filled below    2
		//    0      1      1      0   =>   no                  0
		//    0      1      1      1   =>   yes filled below    2
		//    1      0      0      0   =>   no                  0
		//    1      0      0      1   =>   no                  0
		//    1      0      1      0   =>   yes filled above    1
		//    1      0      1      1   =>   yes filled above    1
		//    1      1      0      0   =>   no                  0
		//    1      1      0      1   =>   yes filled below    2
		//    1      1      1      0   =>   yes filled above    1
		//    1      1      1      1   =>   no                  0
		return select(segments, [
			0, 0, 0, 0,
			0, 2, 0, 2,
			0, 0, 1, 1,
			0, 2, 1, 0
		], buildLog);
	},
	difference: function(segments, buildLog){ // primary - secondary
		// above1 below1 above2 below2    Keep?               Value
		//    0      0      0      0   =>   no                  0
		//    0      0      0      1   =>   no                  0
		//    0      0      1      0   =>   no                  0
		//    0      0      1      1   =>   no                  0
		//    0      1      0      0   =>   yes filled below    2
		//    0      1      0      1   =>   no                  0
		//    0      1      1      0   =>   yes filled below    2
		//    0      1      1      1   =>   no                  0
		//    1      0      0      0   =>   yes filled above    1
		//    1      0      0      1   =>   yes filled above    1
		//    1      0      1      0   =>   no                  0
		//    1      0      1      1   =>   no                  0
		//    1      1      0      0   =>   no                  0
		//    1      1      0      1   =>   yes filled above    1
		//    1      1      1      0   =>   yes filled below    2
		//    1      1      1      1   =>   no                  0
		return select(segments, [
			0, 0, 0, 0,
			2, 0, 2, 0,
			1, 1, 0, 0,
			0, 1, 2, 0
		], buildLog);
	},
	differenceRev: function(segments, buildLog){ // secondary - primary
		// above1 below1 above2 below2    Keep?               Value
		//    0      0      0      0   =>   no                  0
		//    0      0      0      1   =>   yes filled below    2
		//    0      0      1      0   =>   yes filled above    1
		//    0      0      1      1   =>   no                  0
		//    0      1      0      0   =>   no                  0
		//    0      1      0      1   =>   no                  0
		//    0      1      1      0   =>   yes filled above    1
		//    0      1      1      1   =>   yes filled above    1
		//    1      0      0      0   =>   no                  0
		//    1      0      0      1   =>   yes filled below    2
		//    1      0      1      0   =>   no                  0
		//    1      0      1      1   =>   yes filled below    2
		//    1      1      0      0   =>   no                  0
		//    1      1      0      1   =>   no                  0
		//    1      1      1      0   =>   no                  0
		//    1      1      1      1   =>   no                  0
		return select(segments, [
			0, 2, 1, 0,
			0, 0, 1, 1,
			0, 2, 0, 2,
			0, 0, 0, 0
		], buildLog);
	},
	xor: function(segments, buildLog){ // primary ^ secondary
		// above1 below1 above2 below2    Keep?               Value
		//    0      0      0      0   =>   no                  0
		//    0      0      0      1   =>   yes filled below    2
		//    0      0      1      0   =>   yes filled above    1
		//    0      0      1      1   =>   no                  0
		//    0      1      0      0   =>   yes filled below    2
		//    0      1      0      1   =>   no                  0
		//    0      1      1      0   =>   no                  0
		//    0      1      1      1   =>   yes filled above    1
		//    1      0      0      0   =>   yes filled above    1
		//    1      0      0      1   =>   no                  0
		//    1      0      1      0   =>   no                  0
		//    1      0      1      1   =>   yes filled below    2
		//    1      1      0      0   =>   no                  0
		//    1      1      0      1   =>   yes filled above    1
		//    1      1      1      0   =>   yes filled below    2
		//    1      1      1      1   =>   no                  0
		return select(segments, [
			0, 2, 1, 0,
			2, 0, 0, 1,
			1, 0, 0, 2,
			0, 1, 2, 0
		], buildLog);
	}
};

module.exports = SegmentSelector;

},{}],470:[function(_dereq_,module,exports){
//Optimized version for triangle closest point
// Based on Eberly's WildMagick codes
// http://www.geometrictools.com/LibMathematics/Distance/Distance.html
"use strict";

var diff = new Float64Array(4);
var edge0 = new Float64Array(4);
var edge1 = new Float64Array(4);

function closestPoint2d(V0, V1, V2, point, result) {
  //Reallocate buffers if necessary
  if(diff.length < point.length) {
    diff = new Float64Array(point.length);
    edge0 = new Float64Array(point.length);
    edge1 = new Float64Array(point.length);
  }
  //Compute edges
  for(var i=0; i<point.length; ++i) {
    diff[i]  = V0[i] - point[i];
    edge0[i] = V1[i] - V0[i];
    edge1[i] = V2[i] - V0[i];
  }
  //Compute coefficients for quadratic func
  var a00 = 0.0
    , a01 = 0.0
    , a11 = 0.0
    , b0  = 0.0
    , b1  = 0.0
    , c   = 0.0;
  for(var i=0; i<point.length; ++i) {
    var e0 = edge0[i]
      , e1 = edge1[i]
      , d  = diff[i];
    a00 += e0 * e0;
    a01 += e0 * e1;
    a11 += e1 * e1;
    b0  += d * e0;
    b1  += d * e1;
    c   += d * d;
  }
  //Compute determinant/coeffs
  var det = Math.abs(a00*a11 - a01*a01);
  var s   = a01*b1 - a11*b0;
  var t   = a01*b0 - a00*b1;
  var sqrDistance;
  //Hardcoded Voronoi diagram classification
  if (s + t <= det) {
    if (s < 0) {
      if (t < 0) { // region 4
        if (b0 < 0) {
          t = 0;
          if (-b0 >= a00) {
            s = 1.0;
            sqrDistance = a00 + 2.0*b0 + c;
          } else {
            s = -b0/a00;
            sqrDistance = b0*s + c;
          }
        } else {
          s = 0;
          if (b1 >= 0) {
            t = 0;
            sqrDistance = c;
          } else if (-b1 >= a11) {
            t = 1;
            sqrDistance = a11 + 2.0*b1 + c;
          } else {
            t = -b1/a11;
            sqrDistance = b1*t + c;
          }
        }
      } else {  // region 3
        s = 0;
        if (b1 >= 0) {
          t = 0;
          sqrDistance = c;
        } else if (-b1 >= a11) {
          t = 1;
          sqrDistance = a11 + 2.0*b1 + c;
        } else {
          t = -b1/a11;
          sqrDistance = b1*t + c;
        }
      }
    } else if (t < 0) { // region 5
      t = 0;
      if (b0 >= 0) {
        s = 0;
        sqrDistance = c;
      } else if (-b0 >= a00) {
        s = 1;
        sqrDistance = a00 + 2.0*b0 + c;
      } else {
        s = -b0/a00;
        sqrDistance = b0*s + c;
      }
    } else {  // region 0
      // minimum at interior point
      var invDet = 1.0 / det;
      s *= invDet;
      t *= invDet;
      sqrDistance = s*(a00*s + a01*t + 2.0*b0) + t*(a01*s + a11*t + 2.0*b1) + c;
    }
  } else {
    var tmp0, tmp1, numer, denom;
    
    if (s < 0) {  // region 2
      tmp0 = a01 + b0;
      tmp1 = a11 + b1;
      if (tmp1 > tmp0) {
        numer = tmp1 - tmp0;
        denom = a00 - 2.0*a01 + a11;
        if (numer >= denom) {
          s = 1;
          t = 0;
          sqrDistance = a00 + 2.0*b0 + c;
        } else {
          s = numer/denom;
          t = 1 - s;
          sqrDistance = s*(a00*s + a01*t + 2.0*b0) +
          t*(a01*s + a11*t + 2.0*b1) + c;
        }
      } else {
        s = 0;
        if (tmp1 <= 0) {
          t = 1;
          sqrDistance = a11 + 2.0*b1 + c;
        } else if (b1 >= 0) {
          t = 0;
          sqrDistance = c;
        } else {
          t = -b1/a11;
          sqrDistance = b1*t + c;
        }
      }
    } else if (t < 0) {  // region 6
      tmp0 = a01 + b1;
      tmp1 = a00 + b0;
      if (tmp1 > tmp0) {
        numer = tmp1 - tmp0;
        denom = a00 - 2.0*a01 + a11;
        if (numer >= denom) {
          t = 1;
          s = 0;
          sqrDistance = a11 + 2.0*b1 + c;
        } else {
          t = numer/denom;
          s = 1 - t;
          sqrDistance = s*(a00*s + a01*t + 2.0*b0) +
          t*(a01*s + a11*t + 2.0*b1) + c;
        }
      } else {
        t = 0;
        if (tmp1 <= 0) {
          s = 1;
          sqrDistance = a00 + 2.0*b0 + c;
        } else if (b0 >= 0) {
          s = 0;
          sqrDistance = c;
        } else {
          s = -b0/a00;
          sqrDistance = b0*s + c;
        }
      }
    } else {  // region 1
      numer = a11 + b1 - a01 - b0;
      if (numer <= 0) {
        s = 0;
        t = 1;
        sqrDistance = a11 + 2.0*b1 + c;
      } else {
        denom = a00 - 2.0*a01 + a11;
        if (numer >= denom) {
          s = 1;
          t = 0;
          sqrDistance = a00 + 2.0*b0 + c;
        } else {
          s = numer/denom;
          t = 1 - s;
          sqrDistance = s*(a00*s + a01*t + 2.0*b0) +
          t*(a01*s + a11*t + 2.0*b1) + c;
        }
      }
    }
  }
  var u = 1.0 - s - t;
  for(var i=0; i<point.length; ++i) {
    result[i] = u * V0[i] + s * V1[i] + t * V2[i];
  }
  if(sqrDistance < 0) {
    return 0;
  }
  return sqrDistance;
}

module.exports = closestPoint2d;

},{}],471:[function(_dereq_,module,exports){
// shim for using process in browser
var process = module.exports = {};

// cached from whatever global is present so that test runners that stub it
// don't break things.  But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals.  It's inside a
// function because try/catches deoptimize in certain engines.

var cachedSetTimeout;
var cachedClearTimeout;

function defaultSetTimout() {
    throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
    throw new Error('clearTimeout has not been defined');
}
(function () {
    try {
        if (typeof setTimeout === 'function') {
            cachedSetTimeout = setTimeout;
        } else {
            cachedSetTimeout = defaultSetTimout;
        }
    } catch (e) {
        cachedSetTimeout = defaultSetTimout;
    }
    try {
        if (typeof clearTimeout === 'function') {
            cachedClearTimeout = clearTimeout;
        } else {
            cachedClearTimeout = defaultClearTimeout;
        }
    } catch (e) {
        cachedClearTimeout = defaultClearTimeout;
    }
} ())
function runTimeout(fun) {
    if (cachedSetTimeout === setTimeout) {
        //normal enviroments in sane situations
        return setTimeout(fun, 0);
    }
    // if setTimeout wasn't available but was latter defined
    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
        cachedSetTimeout = setTimeout;
        return setTimeout(fun, 0);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedSetTimeout(fun, 0);
    } catch(e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
            return cachedSetTimeout.call(null, fun, 0);
        } catch(e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
            return cachedSetTimeout.call(this, fun, 0);
        }
    }


}
function runClearTimeout(marker) {
    if (cachedClearTimeout === clearTimeout) {
        //normal enviroments in sane situations
        return clearTimeout(marker);
    }
    // if clearTimeout wasn't available but was latter defined
    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
        cachedClearTimeout = clearTimeout;
        return clearTimeout(marker);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedClearTimeout(marker);
    } catch (e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
            return cachedClearTimeout.call(null, marker);
        } catch (e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
            // Some versions of I.E. have different rules for clearTimeout vs setTimeout
            return cachedClearTimeout.call(this, marker);
        }
    }



}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;

function cleanUpNextTick() {
    if (!draining || !currentQueue) {
        return;
    }
    draining = false;
    if (currentQueue.length) {
        queue = currentQueue.concat(queue);
    } else {
        queueIndex = -1;
    }
    if (queue.length) {
        drainQueue();
    }
}

function drainQueue() {
    if (draining) {
        return;
    }
    var timeout = runTimeout(cleanUpNextTick);
    draining = true;

    var len = queue.length;
    while(len) {
        currentQueue = queue;
        queue = [];
        while (++queueIndex < len) {
            if (currentQueue) {
                currentQueue[queueIndex].run();
            }
        }
        queueIndex = -1;
        len = queue.length;
    }
    currentQueue = null;
    draining = false;
    runClearTimeout(timeout);
}

process.nextTick = function (fun) {
    var args = new Array(arguments.length - 1);
    if (arguments.length > 1) {
        for (var i = 1; i < arguments.length; i++) {
            args[i - 1] = arguments[i];
        }
    }
    queue.push(new Item(fun, args));
    if (queue.length === 1 && !draining) {
        runTimeout(drainQueue);
    }
};

// v8 likes predictible objects
function Item(fun, array) {
    this.fun = fun;
    this.array = array;
}
Item.prototype.run = function () {
    this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};

function noop() {}

process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;

process.listeners = function (name) { return [] }

process.binding = function (name) {
    throw new Error('process.binding is not supported');
};

process.cwd = function () { return '/' };
process.chdir = function (dir) {
    throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };

},{}],472:[function(_dereq_,module,exports){
module.exports = _dereq_('gl-quat/slerp')
},{"gl-quat/slerp":286}],473:[function(_dereq_,module,exports){
(function (global){
var now = _dereq_('performance-now')
  , root = typeof window === 'undefined' ? global : window
  , vendors = ['moz', 'webkit']
  , suffix = 'AnimationFrame'
  , raf = root['request' + suffix]
  , caf = root['cancel' + suffix] || root['cancelRequest' + suffix]

for(var i = 0; !raf && i < vendors.length; i++) {
  raf = root[vendors[i] + 'Request' + suffix]
  caf = root[vendors[i] + 'Cancel' + suffix]
      || root[vendors[i] + 'CancelRequest' + suffix]
}

// Some versions of FF have rAF but not cAF
if(!raf || !caf) {
  var last = 0
    , id = 0
    , queue = []
    , frameDuration = 1000 / 60

  raf = function(callback) {
    if(queue.length === 0) {
      var _now = now()
        , next = Math.max(0, frameDuration - (_now - last))
      last = next + _now
      setTimeout(function() {
        var cp = queue.slice(0)
        // Clear queue here to prevent
        // callbacks from appending listeners
        // to the current frame's queue
        queue.length = 0
        for(var i = 0; i < cp.length; i++) {
          if(!cp[i].cancelled) {
            try{
              cp[i].callback(last)
            } catch(e) {
              setTimeout(function() { throw e }, 0)
            }
          }
        }
      }, Math.round(next))
    }
    queue.push({
      handle: ++id,
      callback: callback,
      cancelled: false
    })
    return id
  }

  caf = function(handle) {
    for(var i = 0; i < queue.length; i++) {
      if(queue[i].handle === handle) {
        queue[i].cancelled = true
      }
    }
  }
}

module.exports = function(fn) {
  // Wrap in a new function to prevent
  // `cancel` potentially being assigned
  // to the native rAF function
  return raf.call(root, fn)
}
module.exports.cancel = function() {
  caf.apply(root, arguments)
}
module.exports.polyfill = function(object) {
  if (!object) {
    object = root;
  }
  object.requestAnimationFrame = raf
  object.cancelAnimationFrame = caf
}

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"performance-now":451}],474:[function(_dereq_,module,exports){
'use strict'

var bnadd = _dereq_('big-rat/add')

module.exports = add

function add (a, b) {
  var n = a.length
  var r = new Array(n)
  for (var i=0; i<n; ++i) {
    r[i] = bnadd(a[i], b[i])
  }
  return r
}

},{"big-rat/add":63}],475:[function(_dereq_,module,exports){
'use strict'

module.exports = float2rat

var rat = _dereq_('big-rat')

function float2rat(v) {
  var result = new Array(v.length)
  for(var i=0; i<v.length; ++i) {
    result[i] = rat(v[i])
  }
  return result
}

},{"big-rat":66}],476:[function(_dereq_,module,exports){
'use strict'

var rat = _dereq_('big-rat')
var mul = _dereq_('big-rat/mul')

module.exports = muls

function muls(a, x) {
  var s = rat(x)
  var n = a.length
  var r = new Array(n)
  for(var i=0; i<n; ++i) {
    r[i] = mul(a[i], s)
  }
  return r
}

},{"big-rat":66,"big-rat/mul":75}],477:[function(_dereq_,module,exports){
'use strict'

var bnsub = _dereq_('big-rat/sub')

module.exports = sub

function sub(a, b) {
  var n = a.length
  var r = new Array(n)
    for(var i=0; i<n; ++i) {
    r[i] = bnsub(a[i], b[i])
  }
  return r
}

},{"big-rat/sub":77}],478:[function(_dereq_,module,exports){
'use strict'

var compareCell = _dereq_('compare-cell')
var compareOrientedCell = _dereq_('compare-oriented-cell')
var orientation = _dereq_('cell-orientation')

module.exports = reduceCellComplex

function reduceCellComplex(cells) {
  cells.sort(compareOrientedCell)
  var n = cells.length
  var ptr = 0
  for(var i=0; i<n; ++i) {
    var c = cells[i]
    var o = orientation(c)
    if(o === 0) {
      continue
    }
    if(ptr > 0) {
      var f = cells[ptr-1]
      if(compareCell(c, f) === 0 &&
         orientation(f)    !== o) {
        ptr -= 1
        continue
      }
    }
    cells[ptr++] = c
  }
  cells.length = ptr
  return cells
}

},{"cell-orientation":100,"compare-cell":116,"compare-oriented-cell":117}],479:[function(_dereq_,module,exports){
'use strict'

var getBounds = _dereq_('array-bounds')
var rgba = _dereq_('color-normalize')
var updateDiff = _dereq_('update-diff')
var pick = _dereq_('pick-by-alias')
var extend = _dereq_('object-assign')
var flatten = _dereq_('flatten-vertex-data')
var ref = _dereq_('to-float32');
var float32 = ref.float32;
var fract32 = ref.fract32;

module.exports = Error2D

var WEIGHTS = [
	//direction, lineWidth shift, capSize shift

	// x-error bar
	[1, 0, 0, 1, 0, 0],
	[1, 0, 0, -1, 0, 0],
	[-1, 0, 0, -1, 0, 0],

	[-1, 0, 0, -1, 0, 0],
	[-1, 0, 0, 1, 0, 0],
	[1, 0, 0, 1, 0, 0],

	// x-error right cap
	[1, 0, -1, 0, 0, 1],
	[1, 0, -1, 0, 0, -1],
	[1, 0, 1, 0, 0, -1],

	[1, 0, 1, 0, 0, -1],
	[1, 0, 1, 0, 0, 1],
	[1, 0, -1, 0, 0, 1],

	// x-error left cap
	[-1, 0, -1, 0, 0, 1],
	[-1, 0, -1, 0, 0, -1],
	[-1, 0, 1, 0, 0, -1],

	[-1, 0, 1, 0, 0, -1],
	[-1, 0, 1, 0, 0, 1],
	[-1, 0, -1, 0, 0, 1],

	// y-error bar
	[0, 1, 1, 0, 0, 0],
	[0, 1, -1, 0, 0, 0],
	[0, -1, -1, 0, 0, 0],

	[0, -1, -1, 0, 0, 0],
	[0, 1, 1, 0, 0, 0],
	[0, -1, 1, 0, 0, 0],

	// y-error top cap
	[0, 1, 0, -1, 1, 0],
	[0, 1, 0, -1, -1, 0],
	[0, 1, 0, 1, -1, 0],

	[0, 1, 0, 1, 1, 0],
	[0, 1, 0, -1, 1, 0],
	[0, 1, 0, 1, -1, 0],

	// y-error bottom cap
	[0, -1, 0, -1, 1, 0],
	[0, -1, 0, -1, -1, 0],
	[0, -1, 0, 1, -1, 0],

	[0, -1, 0, 1, 1, 0],
	[0, -1, 0, -1, 1, 0],
	[0, -1, 0, 1, -1, 0]
]


function Error2D (regl, options) {
	if (typeof regl === 'function') {
		if (!options) { options = {} }
		options.regl = regl
	}
	else {
		options = regl
	}
	if (options.length) { options.positions = options }
	regl = options.regl

	if (!regl.hasExtension('ANGLE_instanced_arrays')) {
		throw Error('regl-error2d: `ANGLE_instanced_arrays` extension should be enabled');
	}

	// persistent variables
	var gl = regl._gl, drawErrors, positionBuffer, positionFractBuffer, colorBuffer, errorBuffer, meshBuffer,
			defaults = {
				color: 'black',
				capSize: 5,
				lineWidth: 1,
				opacity: 1,
				viewport: null,
				range: null,
				offset: 0,
				count: 0,
				bounds: null,
				positions: [],
				errors: []
			}, groups = []

	//color per-point
	colorBuffer = regl.buffer({
		usage: 'dynamic',
		type: 'uint8',
		data: new Uint8Array(0)
	})
	//xy-position per-point
	positionBuffer = regl.buffer({
		usage: 'dynamic',
		type: 'float',
		data: new Uint8Array(0)
	})
	//xy-position float32-fraction
	positionFractBuffer = regl.buffer({
		usage: 'dynamic',
		type: 'float',
		data: new Uint8Array(0)
	})
	//4 errors per-point
	errorBuffer = regl.buffer({
		usage: 'dynamic',
		type: 'float',
		data: new Uint8Array(0)
	})
	//error bar mesh
	meshBuffer = regl.buffer({
		usage: 'static',
		type: 'float',
		data: WEIGHTS
	})

	update(options)

	//drawing method
	drawErrors = regl({
		vert: "\n\t\tprecision highp float;\n\n\t\tattribute vec2 position, positionFract;\n\t\tattribute vec4 error;\n\t\tattribute vec4 color;\n\n\t\tattribute vec2 direction, lineOffset, capOffset;\n\n\t\tuniform vec4 viewport;\n\t\tuniform float lineWidth, capSize;\n\t\tuniform vec2 scale, scaleFract, translate, translateFract;\n\n\t\tvarying vec4 fragColor;\n\n\t\tvoid main() {\n\t\t\tfragColor = color / 255.;\n\n\t\t\tvec2 pixelOffset = lineWidth * lineOffset + (capSize + lineWidth) * capOffset;\n\n\t\t\tvec2 dxy = -step(.5, direction.xy) * error.xz + step(direction.xy, vec2(-.5)) * error.yw;\n\n\t\t\tvec2 position = position + dxy;\n\n\t\t\tvec2 pos = (position + translate) * scale\n\t\t\t\t+ (positionFract + translateFract) * scale\n\t\t\t\t+ (position + translate) * scaleFract\n\t\t\t\t+ (positionFract + translateFract) * scaleFract;\n\n\t\t\tpos += pixelOffset / viewport.zw;\n\n\t\t\tgl_Position = vec4(pos * 2. - 1., 0, 1);\n\t\t}\n\t\t",

		frag: "\n\t\tprecision mediump float;\n\n\t\tvarying vec4 fragColor;\n\n\t\tuniform float opacity;\n\n\t\tvoid main() {\n\t\t\tgl_FragColor = fragColor;\n\t\t\tgl_FragColor.a *= opacity;\n\t\t}\n\t\t",

		uniforms: {
			range: regl.prop('range'),
			lineWidth: regl.prop('lineWidth'),
			capSize: regl.prop('capSize'),
			opacity: regl.prop('opacity'),
			scale: regl.prop('scale'),
			translate: regl.prop('translate'),
			scaleFract: regl.prop('scaleFract'),
			translateFract: regl.prop('translateFract'),
			viewport: function (ctx, prop) { return [prop.viewport.x, prop.viewport.y, ctx.viewportWidth, ctx.viewportHeight]; }
		},

		attributes: {
			//dynamic attributes
			color: {
				buffer: colorBuffer,
				offset: function (ctx, prop) { return prop.offset * 4; },
				divisor: 1,
			},
			position: {
				buffer: positionBuffer,
				offset: function (ctx, prop) { return prop.offset * 8; },
				divisor: 1
			},
			positionFract: {
				buffer: positionFractBuffer,
				offset: function (ctx, prop) { return prop.offset * 8; },
				divisor: 1
			},
			error: {
				buffer: errorBuffer,
				offset: function (ctx, prop) { return prop.offset * 16; },
				divisor: 1
			},

			//static attributes
			direction: {
				buffer: meshBuffer,
				stride: 24,
				offset: 0
			},
			lineOffset: {
				buffer: meshBuffer,
				stride: 24,
				offset: 8
			},
			capOffset: {
				buffer: meshBuffer,
				stride: 24,
				offset: 16
			}
		},

		primitive: 'triangles',

		blend: {
			enable: true,
			color: [0,0,0,0],
			equation: {
				rgb: 'add',
				alpha: 'add'
			},
			func: {
				srcRGB: 'src alpha',
				dstRGB: 'one minus src alpha',
				srcAlpha: 'one minus dst alpha',
				dstAlpha: 'one'
			}
		},

		depth: {
			enable: false
		},

		scissor: {
			enable: true,
			box: regl.prop('viewport')
		},
		viewport: regl.prop('viewport'),
		stencil: false,

		instances: regl.prop('count'),
		count: WEIGHTS.length
	})

	//expose API
	extend(error2d, {
		update: update,
		draw: draw,
		destroy: destroy,
		regl: regl,
		gl: gl,
		canvas: gl.canvas,
		groups: groups
	})

	return error2d

	function error2d (opts) {
		//update
		if (opts) {
			update(opts)
		}

		//destroy
		else if (opts === null) {
			destroy()
		}

		draw()
	}


	//main draw method
	function draw (options) {
		if (typeof options === 'number') { return drawGroup(options) }

		//make options a batch
		if (options && !Array.isArray(options)) { options = [options] }


		regl._refresh()

		//render multiple polylines via regl batch
		groups.forEach(function (s, i) {
			if (!s) { return }

			if (options) {
				if (!options[i]) { s.draw = false }
				else { s.draw = true }
			}

			//ignore draw flag for one pass
			if (!s.draw) {
				s.draw = true;
				return
			}

			drawGroup(i)
		})
	}

	//draw single error group by id
	function drawGroup (s) {
		if (typeof s === 'number') { s = groups[s] }
		if (s == null) { return }

		if (!(s && s.count && s.color && s.opacity && s.positions && s.positions.length > 1)) { return }

		s.scaleRatio = [
			s.scale[0] * s.viewport.width,
			s.scale[1] * s.viewport.height
		]

		drawErrors(s)

		if (s.after) { s.after(s) }
	}

	function update (options) {
		if (!options) { return }

		//direct points argument
		if (options.length != null) {
			if (typeof options[0] === 'number') { options = [{positions: options}] }
		}

		//make options a batch
		else if (!Array.isArray(options)) { options = [options] }

		//global count of points
		var pointCount = 0, errorCount = 0

		error2d.groups = groups = options.map(function (options, i) {
			var group = groups[i]

			if (!options) { return group }
			else if (typeof options === 'function') { options = {after: options} }
			else if (typeof options[0] === 'number') { options = {positions: options} }

			//copy options to avoid mutation & handle aliases
			options = pick(options, {
				color: 'color colors fill',
				capSize: 'capSize cap capsize cap-size',
				lineWidth: 'lineWidth line-width width line thickness',
				opacity: 'opacity alpha',
				range: 'range dataBox',
				viewport: 'viewport viewBox',
				errors: 'errors error',
				positions: 'positions position data points'
			})

			if (!group) {
				groups[i] = group = {
					id: i,
					scale: null,
					translate: null,
					scaleFract: null,
					translateFract: null,
					draw: true
				}
				options = extend({}, defaults, options)
			}

			updateDiff(group, options, [{
				lineWidth: function (v) { return +v * .5; },
				capSize: function (v) { return +v * .5; },
				opacity: parseFloat,
				errors: function (errors) {
					errors = flatten(errors)

					errorCount += errors.length
					return errors
				},
				positions: function (positions, state) {
					positions = flatten(positions, 'float64')
					state.count = Math.floor(positions.length / 2)
					state.bounds = getBounds(positions, 2)
					state.offset = pointCount

					pointCount += state.count

					return positions
				}
			}, {
				color: function (colors, state) {
					var count = state.count

					if (!colors) { colors = 'transparent' }

					// 'black' or [0,0,0,0] case
					if (!Array.isArray(colors) || typeof colors[0] === 'number') {
						var color = colors
						colors = Array(count)
						for (var i = 0; i < count; i++) {
							colors[i] = color
						}
					}

					if (colors.length < count) { throw Error('Not enough colors') }

					var colorData = new Uint8Array(count * 4)

					//convert colors to float arrays
					for (var i$1 = 0; i$1 < count; i$1++) {
						var c = rgba(colors[i$1], 'uint8')
						colorData.set(c, i$1 * 4)
					}

					return colorData
				},

				range: function (range, state, options) {
					var bounds = state.bounds
					if (!range) { range = bounds }

					state.scale = [1 / (range[2] - range[0]), 1 / (range[3] - range[1])]
					state.translate = [-range[0], -range[1]]

					state.scaleFract = fract32(state.scale)
					state.translateFract = fract32(state.translate)

					return range
				},

				viewport: function (vp) {
					var viewport

					if (Array.isArray(vp)) {
						viewport = {
							x: vp[0],
							y: vp[1],
							width: vp[2] - vp[0],
							height: vp[3] - vp[1]
						}
					}
					else if (vp) {
						viewport = {
							x: vp.x || vp.left || 0,
							y: vp.y || vp.top || 0
						}

						if (vp.right) { viewport.width = vp.right - viewport.x }
						else { viewport.width = vp.w || vp.width || 0 }

						if (vp.bottom) { viewport.height = vp.bottom - viewport.y }
						else { viewport.height = vp.h || vp.height || 0 }
					}
					else {
						viewport = {
							x: 0, y: 0,
							width: gl.drawingBufferWidth,
							height: gl.drawingBufferHeight
						}
					}

					return viewport
				}
			}])

			return group
		})

		if (pointCount || errorCount) {
			var len = groups.reduce(function (acc, group, i) {
				return acc + (group ? group.count : 0)
			}, 0)

			var positionData = new Float64Array(len * 2)
			var colorData = new Uint8Array(len * 4)
			var errorData = new Float32Array(len * 4)

			groups.forEach(function (group, i) {
				if (!group) { return }
				var positions = group.positions;
				var count = group.count;
				var offset = group.offset;
				var color = group.color;
				var errors = group.errors;
				if (!count) { return }

				colorData.set(color, offset * 4)
				errorData.set(errors, offset * 4)
				positionData.set(positions, offset * 2)
			})

			positionBuffer(float32(positionData))
			positionFractBuffer(fract32(positionData))
			colorBuffer(colorData)
			errorBuffer(errorData)
		}

	}

	function destroy () {
		positionBuffer.destroy()
		positionFractBuffer.destroy()
		colorBuffer.destroy()
		errorBuffer.destroy()
		meshBuffer.destroy()
	}
}

},{"array-bounds":53,"color-normalize":108,"flatten-vertex-data":220,"object-assign":443,"pick-by-alias":454,"to-float32":519,"update-diff":530}],480:[function(_dereq_,module,exports){
'use strict'


var rgba = _dereq_('color-normalize')
var getBounds = _dereq_('array-bounds')
var extend = _dereq_('object-assign')
var glslify = _dereq_('glslify')
var pick = _dereq_('pick-by-alias')
var flatten = _dereq_('flatten-vertex-data')
var triangulate = _dereq_('earcut')
var normalize = _dereq_('array-normalize')
var ref = _dereq_('to-float32');
var float32 = ref.float32;
var fract32 = ref.fract32;
var WeakMap = _dereq_('es6-weak-map')
var parseRect = _dereq_('parse-rect')


module.exports = Line2D


/** @constructor */
function Line2D (regl, options) {
	if (!(this instanceof Line2D)) { return new Line2D(regl, options) }

	if (typeof regl === 'function') {
		if (!options) { options = {} }
		options.regl = regl
	}
	else {
		options = regl
	}
	if (options.length) { options.positions = options }
	regl = options.regl

	if (!regl.hasExtension('ANGLE_instanced_arrays')) {
		throw Error('regl-error2d: `ANGLE_instanced_arrays` extension should be enabled');
	}

	// persistent variables
	this.gl = regl._gl
	this.regl = regl

	// list of options for lines
	this.passes = []

	// cached shaders instance
	this.shaders = Line2D.shaders.has(regl) ? Line2D.shaders.get(regl) : Line2D.shaders.set(regl, Line2D.createShaders(regl)).get(regl)


	// init defaults
	this.update(options)
}


Line2D.dashMult = 2
Line2D.maxPatternLength = 256
Line2D.precisionThreshold = 3e6
Line2D.maxPoints = 1e4
Line2D.maxLines = 2048


// cache of created draw calls per-regl instance
Line2D.shaders = new WeakMap()


// create static shaders once
Line2D.createShaders = function (regl) {
	var offsetBuffer = regl.buffer({
		usage: 'static',
		type: 'float',
		data: [0,1, 0,0, 1,1, 1,0]
	})

	var shaderOptions = {
		primitive: 'triangle strip',
		instances: regl.prop('count'),
		count: 4,
		offset: 0,

		uniforms: {
			miterMode: function (ctx, prop) { return prop.join === 'round' ? 2 : 1; },
			miterLimit: regl.prop('miterLimit'),
			scale: regl.prop('scale'),
			scaleFract: regl.prop('scaleFract'),
			translateFract: regl.prop('translateFract'),
			translate: regl.prop('translate'),
			thickness: regl.prop('thickness'),
			dashPattern: regl.prop('dashTexture'),
			opacity: regl.prop('opacity'),
			pixelRatio: regl.context('pixelRatio'),
			id: regl.prop('id'),
			dashSize: regl.prop('dashLength'),
			viewport: function (c, p) { return [p.viewport.x, p.viewport.y, c.viewportWidth, c.viewportHeight]; },
			depth: regl.prop('depth')
		},

		blend: {
			enable: true,
			color: [0,0,0,0],
			equation: {
				rgb: 'add',
				alpha: 'add'
			},
			func: {
				srcRGB: 'src alpha',
				dstRGB: 'one minus src alpha',
				srcAlpha: 'one minus dst alpha',
				dstAlpha: 'one'
			}
		},
		depth: {
			enable: function (c, p) {
				return !p.overlay
			}
		},
		stencil: {enable: false},
		scissor: {
			enable: true,
			box: regl.prop('viewport')
		},
		viewport: regl.prop('viewport')
	}


	// simplified rectangular line shader
	var drawRectLine = regl(extend({
		vert: glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, aCoordFract, bCoordFract;\nattribute vec4 color;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float thickness, pixelRatio, id, depth;\nuniform vec4 viewport;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nvec2 project(vec2 position, vec2 positionFract, vec2 scale, vec2 scaleFract, vec2 translate, vec2 translateFract) {\n\t// the order is important\n\treturn position * scale + translate\n       + positionFract * scale + translateFract\n       + position * scaleFract\n       + positionFract * scaleFract;\n}\n\nvoid main() {\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineOffset = lineTop * 2. - 1.;\n\n\tvec2 diff = (bCoord + bCoordFract - aCoord - aCoordFract);\n\ttangent = normalize(diff * scale * viewport.zw);\n\tvec2 normal = vec2(-tangent.y, tangent.x);\n\n\tvec2 position = project(aCoord, aCoordFract, scale, scaleFract, translate, translateFract) * lineStart\n\t\t+ project(bCoord, bCoordFract, scale, scaleFract, translate, translateFract) * lineEnd\n\n\t\t+ thickness * normal * .5 * lineOffset / viewport.zw;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n}\n"]),
		frag: glslify(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\n\nuniform float dashSize, pixelRatio, thickness, opacity, id;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nvoid main() {\n\tfloat alpha = 1.;\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashSize) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t, .5)).r;\n\n\tgl_FragColor = fragColor;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]),

		attributes: {
			// if point is at the end of segment
			lineEnd: {
				buffer: offsetBuffer,
				divisor: 0,
				stride: 8,
				offset: 0
			},
			// if point is at the top of segment
			lineTop: {
				buffer: offsetBuffer,
				divisor: 0,
				stride: 8,
				offset: 4
			},
			// beginning of line coordinate
			aCoord: {
				buffer: regl.prop('positionBuffer'),
				stride: 8,
				offset: 8,
				divisor: 1
			},
			// end of line coordinate
			bCoord: {
				buffer: regl.prop('positionBuffer'),
				stride: 8,
				offset: 16,
				divisor: 1
			},
			aCoordFract: {
				buffer: regl.prop('positionFractBuffer'),
				stride: 8,
				offset: 8,
				divisor: 1
			},
			bCoordFract: {
				buffer: regl.prop('positionFractBuffer'),
				stride: 8,
				offset: 16,
				divisor: 1
			},
			color: {
				buffer: regl.prop('colorBuffer'),
				stride: 4,
				offset: 0,
				divisor: 1
			}
		}
	}, shaderOptions))

	// create regl draw
	var drawMiterLine

	try {
		drawMiterLine = regl(extend({
			// culling removes polygon creasing
			cull: {
				enable: true,
				face: 'back'
			},

			vert: glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, nextCoord, prevCoord;\nattribute vec4 aColor, bColor;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, translate;\nuniform float thickness, pixelRatio, id, depth;\nuniform vec4 viewport;\nuniform float miterLimit, miterMode;\n\nvarying vec4 fragColor;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 tangent;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nconst float REVERSE_THRESHOLD = -.875;\nconst float MIN_DIFF = 1e-6;\n\n// TODO: possible optimizations: avoid overcalculating all for vertices and calc just one instead\n// TODO: precalculate dot products, normalize things beforehead etc.\n// TODO: refactor to rectangular algorithm\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nbool isNaN( float val ){\n  return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true;\n}\n\nvoid main() {\n\tvec2 aCoord = aCoord, bCoord = bCoord, prevCoord = prevCoord, nextCoord = nextCoord;\n\n  vec2 adjustedScale;\n  adjustedScale.x = (abs(scale.x) < MIN_DIFF) ? MIN_DIFF : scale.x;\n  adjustedScale.y = (abs(scale.y) < MIN_DIFF) ? MIN_DIFF : scale.y;\n\n  vec2 scaleRatio = adjustedScale * viewport.zw;\n\tvec2 normalWidth = thickness / scaleRatio;\n\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineBot = 1. - lineTop;\n\n\tfragColor = (lineStart * aColor + lineEnd * bColor) / 255.;\n\n\tif (isNaN(aCoord.x) || isNaN(aCoord.y) || isNaN(bCoord.x) || isNaN(bCoord.y)) return;\n\n\tif (aCoord == prevCoord) prevCoord = aCoord + normalize(bCoord - aCoord);\n\tif (bCoord == nextCoord) nextCoord = bCoord - normalize(bCoord - aCoord);\n\n\tvec2 prevDiff = aCoord - prevCoord;\n\tvec2 currDiff = bCoord - aCoord;\n\tvec2 nextDiff = nextCoord - bCoord;\n\n\tvec2 prevTangent = normalize(prevDiff * scaleRatio);\n\tvec2 currTangent = normalize(currDiff * scaleRatio);\n\tvec2 nextTangent = normalize(nextDiff * scaleRatio);\n\n\tvec2 prevNormal = vec2(-prevTangent.y, prevTangent.x);\n\tvec2 currNormal = vec2(-currTangent.y, currTangent.x);\n\tvec2 nextNormal = vec2(-nextTangent.y, nextTangent.x);\n\n\tvec2 startJoinDirection = normalize(prevTangent - currTangent);\n\tvec2 endJoinDirection = normalize(currTangent - nextTangent);\n\n\t// collapsed/unidirectional segment cases\n\t// FIXME: there should be more elegant solution\n\tvec2 prevTanDiff = abs(prevTangent - currTangent);\n\tvec2 nextTanDiff = abs(nextTangent - currTangent);\n\tif (max(prevTanDiff.x, prevTanDiff.y) < MIN_DIFF) {\n\t\tstartJoinDirection = currNormal;\n\t}\n\tif (max(nextTanDiff.x, nextTanDiff.y) < MIN_DIFF) {\n\t\tendJoinDirection = currNormal;\n\t}\n\tif (aCoord == bCoord) {\n\t\tendJoinDirection = startJoinDirection;\n\t\tcurrNormal = prevNormal;\n\t\tcurrTangent = prevTangent;\n\t}\n\n\ttangent = currTangent;\n\n\t//calculate join shifts relative to normals\n\tfloat startJoinShift = dot(currNormal, startJoinDirection);\n\tfloat endJoinShift = dot(currNormal, endJoinDirection);\n\n\tfloat startMiterRatio = abs(1. / startJoinShift);\n\tfloat endMiterRatio = abs(1. / endJoinShift);\n\n\tvec2 startJoin = startJoinDirection * startMiterRatio;\n\tvec2 endJoin = endJoinDirection * endMiterRatio;\n\n\tvec2 startTopJoin, startBotJoin, endTopJoin, endBotJoin;\n\tstartTopJoin = sign(startJoinShift) * startJoin * .5;\n\tstartBotJoin = -startTopJoin;\n\n\tendTopJoin = sign(endJoinShift) * endJoin * .5;\n\tendBotJoin = -endTopJoin;\n\n\tvec2 aTopCoord = aCoord + normalWidth * startTopJoin;\n\tvec2 bTopCoord = bCoord + normalWidth * endTopJoin;\n\tvec2 aBotCoord = aCoord + normalWidth * startBotJoin;\n\tvec2 bBotCoord = bCoord + normalWidth * endBotJoin;\n\n\t//miter anti-clipping\n\tfloat baClipping = distToLine(bCoord, aCoord, aBotCoord) / dot(normalize(normalWidth * endBotJoin), normalize(normalWidth.yx * vec2(-startBotJoin.y, startBotJoin.x)));\n\tfloat abClipping = distToLine(aCoord, bCoord, bTopCoord) / dot(normalize(normalWidth * startBotJoin), normalize(normalWidth.yx * vec2(-endBotJoin.y, endBotJoin.x)));\n\n\t//prevent close to reverse direction switch\n\tbool prevReverse = dot(currTangent, prevTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, prevNormal)) * min(length(prevDiff), length(currDiff)) <  length(normalWidth * currNormal);\n\tbool nextReverse = dot(currTangent, nextTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, nextNormal)) * min(length(nextDiff), length(currDiff)) <  length(normalWidth * currNormal);\n\n\tif (prevReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * startJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / startMiterRatio, 1.);\n\t\taBotCoord = aCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\taTopCoord = aCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!nextReverse && baClipping > 0. && baClipping < length(normalWidth * endBotJoin)) {\n\t\t//handle miter clipping\n\t\tbTopCoord -= normalWidth * endTopJoin;\n\t\tbTopCoord += normalize(endTopJoin * normalWidth) * baClipping;\n\t}\n\n\tif (nextReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * endJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / endMiterRatio, 1.);\n\t\tbBotCoord = bCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\tbTopCoord = bCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!prevReverse && abClipping > 0. && abClipping < length(normalWidth * startBotJoin)) {\n\t\t//handle miter clipping\n\t\taBotCoord -= normalWidth * startBotJoin;\n\t\taBotCoord += normalize(startBotJoin * normalWidth) * abClipping;\n\t}\n\n\tvec2 aTopPosition = (aTopCoord) * adjustedScale + translate;\n\tvec2 aBotPosition = (aBotCoord) * adjustedScale + translate;\n\n\tvec2 bTopPosition = (bTopCoord) * adjustedScale + translate;\n\tvec2 bBotPosition = (bBotCoord) * adjustedScale + translate;\n\n\t//position is normalized 0..1 coord on the screen\n\tvec2 position = (aTopPosition * lineTop + aBotPosition * lineBot) * lineStart + (bTopPosition * lineTop + bBotPosition * lineBot) * lineEnd;\n\n\tstartCoord = aCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\tendCoord = bCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\n\tgl_Position = vec4(position  * 2.0 - 1.0, depth, 1);\n\n\tenableStartMiter = step(dot(currTangent, prevTangent), .5);\n\tenableEndMiter = step(dot(currTangent, nextTangent), .5);\n\n\t//bevel miter cutoffs\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * miterLimit * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * miterLimit * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x)  / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n\n\t//round miter cutoffs\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * abs(dot(startJoinDirection, currNormal)) * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * abs(dot(endJoinDirection, currNormal)) * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x)  / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n}\n"]),
			frag: glslify(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\nuniform float dashSize, pixelRatio, thickness, opacity, id, miterMode;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nvoid main() {\n\tfloat alpha = 1., distToStart, distToEnd;\n\tfloat cutoff = thickness * .5;\n\n\t//bevel miter\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToStart + 1., 0.), 1.);\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToEnd + 1., 0.), 1.);\n\t\t}\n\t}\n\n\t// round miter\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - startCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - endCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\t}\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashSize) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t, .5)).r;\n\n\tgl_FragColor = fragColor;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]),

			attributes: {
				// is line end
				lineEnd: {
					buffer: offsetBuffer,
					divisor: 0,
					stride: 8,
					offset: 0
				},
				// is line top
				lineTop: {
					buffer: offsetBuffer,
					divisor: 0,
					stride: 8,
					offset: 4
				},
				// left color
				aColor: {
					buffer: regl.prop('colorBuffer'),
					stride: 4,
					offset: 0,
					divisor: 1
				},
				// right color
				bColor: {
					buffer: regl.prop('colorBuffer'),
					stride: 4,
					offset: 4,
					divisor: 1
				},
				prevCoord: {
					buffer: regl.prop('positionBuffer'),
					stride: 8,
					offset: 0,
					divisor: 1
				},
				aCoord: {
					buffer: regl.prop('positionBuffer'),
					stride: 8,
					offset: 8,
					divisor: 1
				},
				bCoord: {
					buffer: regl.prop('positionBuffer'),
					stride: 8,
					offset: 16,
					divisor: 1
				},
				nextCoord: {
					buffer: regl.prop('positionBuffer'),
					stride: 8,
					offset: 24,
					divisor: 1
				}
			}
		}, shaderOptions))
	} catch (e) {
		// IE/bad Webkit fallback
		drawMiterLine = drawRectLine
	}

	// fill shader
	var drawFill = regl({
		primitive: 'triangle',
		elements: function (ctx, prop) { return prop.triangles; },
		offset: 0,

		vert: glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\n\nuniform vec4 color;\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio, id;\nuniform vec4 viewport;\nuniform float opacity;\n\nvarying vec4 fragColor;\n\nconst float MAX_LINES = 256.;\n\nvoid main() {\n\tfloat depth = (MAX_LINES - 4. - id) / (MAX_LINES);\n\n\tvec2 position = position * scale + translate\n       + positionFract * scale + translateFract\n       + position * scaleFract\n       + positionFract * scaleFract;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n\tfragColor.a *= opacity;\n}\n"]),
		frag: glslify(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n\tgl_FragColor = fragColor;\n}\n"]),

		uniforms: {
			scale: regl.prop('scale'),
			color: regl.prop('fill'),
			scaleFract: regl.prop('scaleFract'),
			translateFract: regl.prop('translateFract'),
			translate: regl.prop('translate'),
			opacity: regl.prop('opacity'),
			pixelRatio: regl.context('pixelRatio'),
			id: regl.prop('id'),
			viewport: function (ctx, prop) { return [prop.viewport.x, prop.viewport.y, ctx.viewportWidth, ctx.viewportHeight]; }
		},

		attributes: {
			position: {
				buffer: regl.prop('positionBuffer'),
				stride: 8,
				offset: 8
			},
			positionFract: {
				buffer: regl.prop('positionFractBuffer'),
				stride: 8,
				offset: 8
			}
		},

		blend: shaderOptions.blend,

		depth: { enable: false },
		scissor: shaderOptions.scissor,
		stencil: shaderOptions.stencil,
		viewport: shaderOptions.viewport
	})

	return {
		fill: drawFill, rect: drawRectLine, miter: drawMiterLine
	}
}


// used to for new lines instances
Line2D.defaults = {
	dashes: null,
	join: 'miter',
	miterLimit: 1,
	thickness: 10,
	cap: 'square',
	color: 'black',
	opacity: 1,
	overlay: false,
	viewport: null,
	range: null,
	close: false,
	fill: null
}


Line2D.prototype.render = function () {
	var ref;

	var args = [], len = arguments.length;
	while ( len-- ) args[ len ] = arguments[ len ];
	if (args.length) {
		(ref = this).update.apply(ref, args)
	}

	this.draw()
}


Line2D.prototype.draw = function () {
	var this$1 = this;
	var args = [], len = arguments.length;
	while ( len-- ) args[ len ] = arguments[ len ];

	// render multiple polylines via regl batch
	(args.length ? args : this.passes).forEach(function (s, i) {
		var ref;

		// render array pass as a list of passes
		if (s && Array.isArray(s)) { return (ref = this$1).draw.apply(ref, s) }

		if (typeof s === 'number') { s = this$1.passes[s] }

		if (!(s && s.count > 1 && s.opacity)) { return }

		this$1.regl._refresh()

		if (s.fill && s.triangles && s.triangles.length > 2) {
			this$1.shaders.fill(s)
		}

		if (!s.thickness) { return }

		// high scale is only available for rect mode with precision
		if (s.scale[0] * s.viewport.width > Line2D.precisionThreshold || s.scale[1] * s.viewport.height > Line2D.precisionThreshold) {
			this$1.shaders.rect(s)
		}

		// thin this.passes or too many points are rendered as simplified rect shader
		else if (s.join === 'rect' || (!s.join && (s.thickness <= 2 || s.count >= Line2D.maxPoints))) {
			this$1.shaders.rect(s)
		}
		else {
			this$1.shaders.miter(s)
		}
	})

	return this
}

Line2D.prototype.update = function (options) {
	var this$1 = this;

	if (!options) { return }

	if (options.length != null) {
		if (typeof options[0] === 'number') { options = [{positions: options}] }
	}

	// make options a batch
	else if (!Array.isArray(options)) { options = [options] }

	var ref = this;
	var regl = ref.regl;
	var gl = ref.gl;

	// process per-line settings
	options.forEach(function (o, i) {
		var state = this$1.passes[i]

		if (o === undefined) { return }

		// null-argument removes pass
		if (o === null) {
			this$1.passes[i] = null
			return
		}

		if (typeof o[0] === 'number') { o = {positions: o} }

		// handle aliases
		o = pick(o, {
			positions: 'positions points data coords',
			thickness: 'thickness lineWidth lineWidths line-width linewidth width stroke-width strokewidth strokeWidth',
			join: 'lineJoin linejoin join type mode',
			miterLimit: 'miterlimit miterLimit',
			dashes: 'dash dashes dasharray dash-array dashArray',
			color: 'color colour stroke colors colours stroke-color strokeColor',
			fill: 'fill fill-color fillColor',
			opacity: 'alpha opacity',
			overlay: 'overlay crease overlap intersect',
			close: 'closed close closed-path closePath',
			range: 'range dataBox',
			viewport: 'viewport viewBox',
			hole: 'holes hole hollow'
		})

		// init state
		if (!state) {
			this$1.passes[i] = state = {
				id: i,
				scale: null,
				scaleFract: null,
				translate: null,
				translateFract: null,
				count: 0,
				hole: [],
				depth: 0,

				dashLength: 1,
				dashTexture: regl.texture({
					channels: 1,
					data: new Uint8Array([255]),
					width: 1,
					height: 1,
					mag: 'linear',
					min: 'linear'
				}),

				colorBuffer: regl.buffer({
					usage: 'dynamic',
					type: 'uint8',
					data: new Uint8Array()
				}),
				positionBuffer: regl.buffer({
					usage: 'dynamic',
					type: 'float',
					data: new Uint8Array()
				}),
				positionFractBuffer: regl.buffer({
					usage: 'dynamic',
					type: 'float',
					data: new Uint8Array()
				})
			}

			o = extend({}, Line2D.defaults, o)
		}
		if (o.thickness != null) { state.thickness = parseFloat(o.thickness) }
		if (o.opacity != null) { state.opacity = parseFloat(o.opacity) }
		if (o.miterLimit != null) { state.miterLimit = parseFloat(o.miterLimit) }
		if (o.overlay != null) {
			state.overlay = !!o.overlay
			if (i < Line2D.maxLines) {
				state.depth = 2 * (Line2D.maxLines - 1 - i % Line2D.maxLines) / Line2D.maxLines - 1.;
			}
		}
		if (o.join != null) { state.join = o.join }
		if (o.hole != null) { state.hole = o.hole }
		if (o.fill != null) { state.fill = !o.fill ? null : rgba(o.fill, 'uint8') }
		if (o.viewport != null) { state.viewport = parseRect(o.viewport) }

		if (!state.viewport) {
			state.viewport = parseRect([
				gl.drawingBufferWidth,
				gl.drawingBufferHeight
			])
		}

		if (o.close != null) { state.close = o.close }

		// reset positions
		if (o.positions === null) { o.positions = [] }
		if (o.positions) {
			var positions, count

			// if positions are an object with x/y
			if (o.positions.x && o.positions.y) {
				var xPos = o.positions.x
				var yPos = o.positions.y
				count = state.count = Math.max(
					xPos.length,
					yPos.length
				)
				positions = new Float64Array(count * 2)
				for (var i$1 = 0; i$1 < count; i$1++) {
					positions[i$1 * 2] = xPos[i$1]
					positions[i$1 * 2 + 1] = yPos[i$1]
				}
			}
			else {
				positions = flatten(o.positions, 'float64')
				count = state.count = Math.floor(positions.length / 2)
			}

			var bounds = state.bounds = getBounds(positions, 2)

			// create fill positions
			// FIXME: fill positions can be set only along with positions
			if (state.fill) {
				var pos = []

				// filter bad vertices and remap triangles to ensure shape
				var ids = {}
				var lastId = 0

				for (var i$2 = 0, ptr = 0, l = state.count; i$2 < l; i$2++) {
					var x = positions[i$2*2]
					var y = positions[i$2*2 + 1]
					if (isNaN(x) || isNaN(y) || x == null || y == null) {
						x = positions[lastId*2]
						y = positions[lastId*2 + 1]
						ids[i$2] = lastId
					}
					else {
						lastId = i$2
					}
					pos[ptr++] = x
					pos[ptr++] = y
				}

				var triangles = triangulate(pos, state.hole || [])

				for (var i$3 = 0, l$1 = triangles.length; i$3 < l$1; i$3++) {
					if (ids[triangles[i$3]] != null) { triangles[i$3] = ids[triangles[i$3]] }
				}

				state.triangles = triangles
			}

			// update position buffers
			var npos = new Float64Array(positions)
			normalize(npos, 2, bounds)

			var positionData = new Float64Array(count * 2 + 6)

			// rotate first segment join
			if (state.close) {
				if (positions[0] === positions[count*2 - 2] &&
					positions[1] === positions[count*2 - 1]) {
					positionData[0] = npos[count*2 - 4]
					positionData[1] = npos[count*2 - 3]
				}
				else {
					positionData[0] = npos[count*2 - 2]
					positionData[1] = npos[count*2 - 1]
				}
			}
			else {
				positionData[0] = npos[0]
				positionData[1] = npos[1]
			}

			positionData.set(npos, 2)

			// add last segment
			if (state.close) {
				// ignore coinciding start/end
				if (positions[0] === positions[count*2 - 2] &&
					positions[1] === positions[count*2 - 1]) {
					positionData[count*2 + 2] = npos[2]
					positionData[count*2 + 3] = npos[3]
					state.count -= 1
				}
				else {
					positionData[count*2 + 2] = npos[0]
					positionData[count*2 + 3] = npos[1]
					positionData[count*2 + 4] = npos[2]
					positionData[count*2 + 5] = npos[3]
				}
			}
			// add stub
			else {
				positionData[count*2 + 2] = npos[count*2 - 2]
				positionData[count*2 + 3] = npos[count*2 - 1]
				positionData[count*2 + 4] = npos[count*2 - 2]
				positionData[count*2 + 5] = npos[count*2 - 1]
			}

			state.positionBuffer(float32(positionData))
			state.positionFractBuffer(fract32(positionData))
		}

		if (o.range) {
			state.range = o.range
		} else if (!state.range) {
			state.range = state.bounds
		}

		if ((o.range || o.positions) && state.count) {
			var bounds$1 = state.bounds

			var boundsW = bounds$1[2] - bounds$1[0],
				boundsH = bounds$1[3] - bounds$1[1]

			var rangeW = state.range[2] - state.range[0],
				rangeH = state.range[3] - state.range[1]

			state.scale = [
				boundsW / rangeW,
				boundsH / rangeH
			]
			state.translate = [
				-state.range[0] / rangeW + bounds$1[0] / rangeW || 0,
				-state.range[1] / rangeH + bounds$1[1] / rangeH || 0
			]

			state.scaleFract = fract32(state.scale)
			state.translateFract = fract32(state.translate)
		}

		if (o.dashes) {
			var dashLength = 0., dashData

			if (!o.dashes || o.dashes.length < 2) {
				dashLength = 1.
				dashData = new Uint8Array([255, 255, 255, 255, 255, 255, 255, 255])
			}

			else {
				dashLength = 0.;
				for(var i$4 = 0; i$4 < o.dashes.length; ++i$4) {
					dashLength += o.dashes[i$4]
				}
				dashData = new Uint8Array(dashLength * Line2D.dashMult)
				var ptr$1 = 0
				var fillColor = 255

				// repeat texture two times to provide smooth 0-step
				for (var k = 0; k < 2; k++) {
					for(var i$5 = 0; i$5 < o.dashes.length; ++i$5) {
						for(var j = 0, l$2 = o.dashes[i$5] * Line2D.dashMult * .5; j < l$2; ++j) {
							dashData[ptr$1++] = fillColor
						}
						fillColor ^= 255
					}
				}
			}

			state.dashLength = dashLength
			state.dashTexture({
				channels: 1,
				data: dashData,
				width: dashData.length,
				height: 1,
				mag: 'linear',
				min: 'linear'
			}, 0, 0)
		}

		if (o.color) {
			var count$1 = state.count
			var colors = o.color

			if (!colors) { colors = 'transparent' }

			var colorData = new Uint8Array(count$1 * 4 + 4)

			// convert colors to typed arrays
			if (!Array.isArray(colors) || typeof colors[0] === 'number') {
				var c = rgba(colors, 'uint8')

				for (var i$6 = 0; i$6 < count$1 + 1; i$6++) {
					colorData.set(c, i$6 * 4)
				}
			} else {
				for (var i$7 = 0; i$7 < count$1; i$7++) {
					var c$1 = rgba(colors[i$7], 'uint8')
					colorData.set(c$1, i$7 * 4)
				}
				colorData.set(rgba(colors[0], 'uint8'), count$1 * 4)
			}

			state.colorBuffer({
				usage: 'dynamic',
				type: 'uint8',
				data: colorData
			})
		}
	})

	// remove unmentioned passes
	if (options.length < this.passes.length) {
		for (var i = options.length; i < this.passes.length; i++) {
			var pass = this$1.passes[i]
			if (!pass) { continue }
			pass.colorBuffer.destroy()
			pass.positionBuffer.destroy()
			pass.dashTexture.destroy()
		}
		this.passes.length = options.length
	}

	// remove null items
	var passes = []
	for (var i$1 = 0; i$1 < this.passes.length; i$1++) {
		if (this$1.passes[i$1] !== null) { passes.push(this$1.passes[i$1]) }
	}
	this.passes = passes

	return this
}

Line2D.prototype.destroy = function () {
	this.passes.forEach(function (pass) {
		pass.colorBuffer.destroy()
		pass.positionBuffer.destroy()
		pass.dashTexture.destroy()
	})

	this.passes.length = 0

	return this
}

},{"array-bounds":53,"array-normalize":54,"color-normalize":108,"earcut":159,"es6-weak-map":213,"flatten-vertex-data":220,"glslify":398,"object-assign":443,"parse-rect":448,"pick-by-alias":454,"to-float32":519}],481:[function(_dereq_,module,exports){
'use strict';

function _slicedToArray(arr, i) {
  return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}

function _toConsumableArray(arr) {
  return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}

function _arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) {
    for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];

    return arr2;
  }
}

function _arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}

function _iterableToArray(iter) {
  if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}

function _iterableToArrayLimit(arr, i) {
  var _arr = [];
  var _n = true;
  var _d = false;
  var _e = undefined;

  try {
    for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
      _arr.push(_s.value);

      if (i && _arr.length === i) break;
    }
  } catch (err) {
    _d = true;
    _e = err;
  } finally {
    try {
      if (!_n && _i["return"] != null) _i["return"]();
    } finally {
      if (_d) throw _e;
    }
  }

  return _arr;
}

function _nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance");
}

function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance");
}

var rgba = _dereq_('color-normalize');

var getBounds = _dereq_('array-bounds');

var colorId = _dereq_('color-id');

var cluster = _dereq_('point-cluster');

var extend = _dereq_('object-assign');

var glslify = _dereq_('glslify');

var pick = _dereq_('pick-by-alias');

var updateDiff = _dereq_('update-diff');

var flatten = _dereq_('flatten-vertex-data');

var ie = _dereq_('is-iexplorer');

var f32 = _dereq_('to-float32');

var parseRect = _dereq_('parse-rect');

var scatter = Scatter;

function Scatter(regl, options) {
  var _this = this;

  if (!(this instanceof Scatter)) return new Scatter(regl, options);

  if (typeof regl === 'function') {
    if (!options) options = {};
    options.regl = regl;
  } else {
    options = regl;
    regl = null;
  }

  if (options && options.length) options.positions = options;
  regl = options.regl; // persistent variables

  var gl = regl._gl,
      paletteTexture,
      palette = [],
      paletteIds = {},
      // state
  groups = [],
      // textures for marker keys
  markerTextures = [null],
      markerCache = [null];
  var maxColors = 255,
      maxSize = 100; // direct color buffer mode
  // IE does not support palette anyways

  this.tooManyColors = ie; // texture with color palette

  paletteTexture = regl.texture({
    data: new Uint8Array(maxColors * 4),
    width: maxColors,
    height: 1,
    type: 'uint8',
    format: 'rgba',
    wrapS: 'clamp',
    wrapT: 'clamp',
    mag: 'nearest',
    min: 'nearest'
  });
  extend(this, {
    regl: regl,
    gl: gl,
    groups: groups,
    markerCache: markerCache,
    markerTextures: markerTextures,
    palette: palette,
    paletteIds: paletteIds,
    paletteTexture: paletteTexture,
    maxColors: maxColors,
    maxSize: maxSize,
    canvas: gl.canvas
  });
  this.update(options); // common shader options

  var shaderOptions = {
    uniforms: {
      pixelRatio: regl.context('pixelRatio'),
      palette: paletteTexture,
      paletteSize: function paletteSize(ctx, prop) {
        return [_this.tooManyColors ? 0 : maxColors, paletteTexture.height];
      },
      scale: regl.prop('scale'),
      scaleFract: regl.prop('scaleFract'),
      translate: regl.prop('translate'),
      translateFract: regl.prop('translateFract'),
      opacity: regl.prop('opacity'),
      marker: regl.prop('markerTexture')
    },
    attributes: {
      // FIXME: optimize these parts
      x: function x(ctx, prop) {
        return prop.xAttr || {
          buffer: prop.positionBuffer,
          stride: 8,
          offset: 0
        };
      },
      y: function y(ctx, prop) {
        return prop.yAttr || {
          buffer: prop.positionBuffer,
          stride: 8,
          offset: 4
        };
      },
      xFract: function xFract(ctx, prop) {
        return prop.xAttr ? {
          constant: [0, 0]
        } : {
          buffer: prop.positionFractBuffer,
          stride: 8,
          offset: 0
        };
      },
      yFract: function yFract(ctx, prop) {
        return prop.yAttr ? {
          constant: [0, 0]
        } : {
          buffer: prop.positionFractBuffer,
          stride: 8,
          offset: 4
        };
      },
      size: function size(ctx, prop) {
        return prop.size.length ? {
          buffer: prop.sizeBuffer,
          stride: 2,
          offset: 0
        } : {
          constant: [Math.round(prop.size * 255 / _this.maxSize)]
        };
      },
      borderSize: function borderSize(ctx, prop) {
        return prop.borderSize.length ? {
          buffer: prop.sizeBuffer,
          stride: 2,
          offset: 1
        } : {
          constant: [Math.round(prop.borderSize * 255 / _this.maxSize)]
        };
      },
      colorId: function colorId(ctx, prop) {
        return prop.color.length ? {
          buffer: prop.colorBuffer,
          stride: _this.tooManyColors ? 8 : 4,
          offset: 0
        } : {
          constant: _this.tooManyColors ? palette.slice(prop.color * 4, prop.color * 4 + 4) : [prop.color]
        };
      },
      borderColorId: function borderColorId(ctx, prop) {
        return prop.borderColor.length ? {
          buffer: prop.colorBuffer,
          stride: _this.tooManyColors ? 8 : 4,
          offset: _this.tooManyColors ? 4 : 2
        } : {
          constant: _this.tooManyColors ? palette.slice(prop.borderColor * 4, prop.borderColor * 4 + 4) : [prop.borderColor]
        };
      },
      isActive: function isActive(ctx, prop) {
        return prop.activation === true ? {
          constant: [1]
        } : prop.activation ? prop.activation : {
          constant: [0]
        };
      }
    },
    blend: {
      enable: true,
      color: [0, 0, 0, 1],
      // photoshop blending
      func: {
        srcRGB: 'src alpha',
        dstRGB: 'one minus src alpha',
        srcAlpha: 'one minus dst alpha',
        dstAlpha: 'one'
      }
    },
    scissor: {
      enable: true,
      box: regl.prop('viewport')
    },
    viewport: regl.prop('viewport'),
    stencil: {
      enable: false
    },
    depth: {
      enable: false
    },
    elements: regl.prop('elements'),
    count: regl.prop('count'),
    offset: regl.prop('offset'),
    primitive: 'points' // draw sdf-marker

  };
  var markerOptions = extend({}, shaderOptions);
  markerOptions.frag = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragWidth, fragBorderColorLevel, fragColorLevel;\n\nuniform sampler2D marker;\nuniform float pixelRatio, opacity;\n\nfloat smoothStep(float x, float y) {\n  return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n  float dist = texture2D(marker, gl_PointCoord).r, delta = fragWidth;\n\n  // max-distance alpha\n  if (dist < 0.003) discard;\n\n  // null-border case\n  if (fragBorderColorLevel == fragColorLevel || fragBorderColor.a == 0.) {\n    float colorAmt = smoothstep(.5 - delta, .5 + delta, dist);\n    gl_FragColor = vec4(fragColor.rgb, colorAmt * fragColor.a * opacity);\n  }\n  else {\n    float borderColorAmt = smoothstep(fragBorderColorLevel - delta, fragBorderColorLevel + delta, dist);\n    float colorAmt = smoothstep(fragColorLevel - delta, fragColorLevel + delta, dist);\n\n    vec4 color = fragBorderColor;\n    color.a *= borderColorAmt;\n    color = mix(color, fragColor, colorAmt);\n    color.a *= opacity;\n\n    gl_FragColor = color;\n  }\n\n}\n"]);
  markerOptions.vert = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute float x, y, xFract, yFract;\nattribute float size, borderSize;\nattribute vec4 colorId, borderColorId;\nattribute float isActive;\n\nuniform vec2 scale, scaleFract, translate, translateFract, paletteSize;\nuniform float pixelRatio;\nuniform sampler2D palette;\n\nconst float maxSize = 100.;\nconst float borderLevel = .5;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragPointSize, fragBorderRadius, fragWidth, fragBorderColorLevel, fragColorLevel;\n\nbool isDirect = (paletteSize.x < 1.);\n\nvec4 getColor(vec4 id) {\n  return isDirect ? id / 255. : texture2D(palette,\n    vec2(\n      (id.x + .5) / paletteSize.x,\n      (id.y + .5) / paletteSize.y\n    )\n  );\n}\n\nvoid main() {\n  if (isActive == 0.) return;\n\n  vec2 position = vec2(x, y);\n  vec2 positionFract = vec2(xFract, yFract);\n\n  vec4 color = getColor(colorId);\n  vec4 borderColor = getColor(borderColorId);\n\n  float size = size * maxSize / 255.;\n  float borderSize = borderSize * maxSize / 255.;\n\n  gl_PointSize = 2. * size * pixelRatio;\n  fragPointSize = size * pixelRatio;\n\n  vec2 pos = (position + translate) * scale\n      + (positionFract + translateFract) * scale\n      + (position + translate) * scaleFract\n      + (positionFract + translateFract) * scaleFract;\n\n  gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n  fragColor = color;\n  fragBorderColor = borderColor;\n  fragWidth = 1. / gl_PointSize;\n\n  fragBorderColorLevel = clamp(borderLevel - borderLevel * borderSize / size, 0., 1.);\n  fragColorLevel = clamp(borderLevel + (1. - borderLevel) * borderSize / size, 0., 1.);\n}"]);
  this.drawMarker = regl(markerOptions); // draw circle

  var circleOptions = extend({}, shaderOptions);
  circleOptions.frag = glslify(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\n\nuniform float opacity;\nvarying float fragBorderRadius, fragWidth;\n\nfloat smoothStep(float edge0, float edge1, float x) {\n\tfloat t;\n\tt = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);\n\treturn t * t * (3.0 - 2.0 * t);\n}\n\nvoid main() {\n\tfloat radius, alpha = 1.0, delta = fragWidth;\n\n\tradius = length(2.0 * gl_PointCoord.xy - 1.0);\n\n\tif (radius > 1.0 + delta) {\n\t\tdiscard;\n\t}\n\n\talpha -= smoothstep(1.0 - delta, 1.0 + delta, radius);\n\n\tfloat borderRadius = fragBorderRadius;\n\tfloat ratio = smoothstep(borderRadius - delta, borderRadius + delta, radius);\n\tvec4 color = mix(fragColor, fragBorderColor, ratio);\n\tcolor.a *= alpha * opacity;\n\tgl_FragColor = color;\n}\n"]);
  circleOptions.vert = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute float x, y, xFract, yFract;\nattribute float size, borderSize;\nattribute vec4 colorId, borderColorId;\nattribute float isActive;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio;\nuniform sampler2D palette;\nuniform vec2 paletteSize;\n\nconst float maxSize = 100.;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth;\n\nbool isDirect = (paletteSize.x < 1.);\n\nvec4 getColor(vec4 id) {\n  return isDirect ? id / 255. : texture2D(palette,\n    vec2(\n      (id.x + .5) / paletteSize.x,\n      (id.y + .5) / paletteSize.y\n    )\n  );\n}\n\nvoid main() {\n  // ignore inactive points\n  if (isActive == 0.) return;\n\n  vec2 position = vec2(x, y);\n  vec2 positionFract = vec2(xFract, yFract);\n\n  vec4 color = getColor(colorId);\n  vec4 borderColor = getColor(borderColorId);\n\n  float size = size * maxSize / 255.;\n  float borderSize = borderSize * maxSize / 255.;\n\n  gl_PointSize = (size + borderSize) * pixelRatio;\n\n  vec2 pos = (position + translate) * scale\n      + (positionFract + translateFract) * scale\n      + (position + translate) * scaleFract\n      + (positionFract + translateFract) * scaleFract;\n\n  gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n  fragBorderRadius = 1. - 2. * borderSize / (size + borderSize);\n  fragColor = color;\n  fragBorderColor = borderColor.a == 0. || borderSize == 0. ? vec4(color.rgb, 0.) : borderColor;\n  fragWidth = 1. / gl_PointSize;\n}\n"]); // polyfill IE

  if (ie) {
    circleOptions.frag = circleOptions.frag.replace('smoothstep', 'smoothStep');
    markerOptions.frag = markerOptions.frag.replace('smoothstep', 'smoothStep');
  }

  this.drawCircle = regl(circleOptions);
} // single pass defaults


Scatter.defaults = {
  color: 'black',
  borderColor: 'transparent',
  borderSize: 0,
  size: 12,
  opacity: 1,
  marker: undefined,
  viewport: null,
  range: null,
  pixelSize: null,
  count: 0,
  offset: 0,
  bounds: null,
  positions: [],
  snap: 1e4 // update & redraw

};

Scatter.prototype.render = function () {
  if (arguments.length) {
    this.update.apply(this, arguments);
  }

  this.draw();
  return this;
}; // draw all groups or only indicated ones


Scatter.prototype.draw = function () {
  var _this2 = this;

  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
    args[_key] = arguments[_key];
  }

  var groups = this.groups; // if directly array passed - treat as passes

  if (args.length === 1 && Array.isArray(args[0]) && (args[0][0] === null || Array.isArray(args[0][0]))) {
    args = args[0];
  } // FIXME: remove once https://github.com/regl-project/regl/issues/474 resolved


  this.regl._refresh();

  if (args.length) {
    for (var i = 0; i < args.length; i++) {
      this.drawItem(i, args[i]);
    }
  } // draw all passes
  else {
      groups.forEach(function (group, i) {
        _this2.drawItem(i);
      });
    }

  return this;
}; // draw specific scatter group


Scatter.prototype.drawItem = function (id, els) {
  var groups = this.groups;
  var group = groups[id]; // debug viewport
  // let { viewport } = group
  // gl.enable(gl.SCISSOR_TEST);
  // gl.scissor(viewport.x, viewport.y, viewport.width, viewport.height);
  // gl.clearColor(0, 0, 0, .5);
  // gl.clear(gl.COLOR_BUFFER_BIT);

  if (typeof els === 'number') {
    id = els;
    group = groups[els];
    els = null;
  }

  if (!(group && group.count && group.opacity)) return; // draw circles

  if (group.activation[0]) {
    // TODO: optimize this performance by making groups and regl.this props
    this.drawCircle(this.getMarkerDrawOptions(0, group, els));
  } // draw all other available markers


  var batch = [];

  for (var i = 1; i < group.activation.length; i++) {
    if (!group.activation[i] || group.activation[i] !== true && !group.activation[i].data.length) continue;
    batch.push.apply(batch, _toConsumableArray(this.getMarkerDrawOptions(i, group, els)));
  }

  if (batch.length) {
    this.drawMarker(batch);
  }
}; // get options for the marker ids


Scatter.prototype.getMarkerDrawOptions = function (markerId, group, elements) {
  var range = group.range,
      tree = group.tree,
      viewport = group.viewport,
      activation = group.activation,
      selectionBuffer = group.selectionBuffer,
      count = group.count;
  var regl = this.regl; // direct points

  if (!tree) {
    // if elements array - draw unclustered points
    if (elements) {
      return [extend({}, group, {
        markerTexture: this.markerTextures[markerId],
        activation: activation[markerId],
        count: elements.length,
        elements: elements,
        offset: 0
      })];
    }

    return [extend({}, group, {
      markerTexture: this.markerTextures[markerId],
      activation: activation[markerId],
      offset: 0
    })];
  } // clustered points


  var batch = [];
  var lod = tree.range(range, {
    lod: true,
    px: [(range[2] - range[0]) / viewport.width, (range[3] - range[1]) / viewport.height]
  }); // enable elements by using selection buffer

  if (elements) {
    var markerActivation = activation[markerId];
    var mask = markerActivation.data;
    var data = new Uint8Array(count);

    for (var i = 0; i < elements.length; i++) {
      var id = elements[i];
      data[id] = mask ? mask[id] : 1;
    }

    selectionBuffer.subdata(data);
  }

  for (var l = lod.length; l--;) {
    var _lod$l = _slicedToArray(lod[l], 2),
        from = _lod$l[0],
        to = _lod$l[1];

    batch.push(extend({}, group, {
      markerTexture: this.markerTextures[markerId],
      activation: elements ? selectionBuffer : activation[markerId],
      offset: from,
      count: to - from
    }));
  }

  return batch;
}; // update groups options


Scatter.prototype.update = function () {
  var _this3 = this;

  for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
    args[_key2] = arguments[_key2];
  }

  if (!args.length) return; // passes are as single array

  if (args.length === 1 && Array.isArray(args[0])) args = args[0];
  var groups = this.groups,
      gl = this.gl,
      regl = this.regl,
      maxSize = this.maxSize,
      maxColors = this.maxColors,
      palette = this.palette;
  this.groups = groups = args.map(function (options, i) {
    var group = groups[i];
    if (options === undefined) return group;
    if (options === null) options = {
      positions: null
    };else if (typeof options === 'function') options = {
      ondraw: options
    };else if (typeof options[0] === 'number') options = {
      positions: options // copy options to avoid mutation & handle aliases

    };
    options = pick(options, {
      positions: 'positions data points',
      snap: 'snap cluster lod tree',
      size: 'sizes size radius',
      borderSize: 'borderSizes borderSize border-size bordersize borderWidth borderWidths border-width borderwidth stroke-width strokeWidth strokewidth outline',
      color: 'colors color fill fill-color fillColor',
      borderColor: 'borderColors borderColor stroke stroke-color strokeColor',
      marker: 'markers marker shape',
      range: 'range dataBox databox',
      viewport: 'viewport viewPort viewBox viewbox',
      opacity: 'opacity alpha transparency',
      bounds: 'bound bounds boundaries limits',
      tooManyColors: 'tooManyColors palette paletteMode optimizePalette enablePalette'
    });
    if (options.positions === null) options.positions = [];
    if (options.tooManyColors != null) _this3.tooManyColors = options.tooManyColors;

    if (!group) {
      groups[i] = group = {
        id: i,
        scale: null,
        translate: null,
        scaleFract: null,
        translateFract: null,
        // buffers for active markers
        activation: [],
        // buffer for filtered markers
        selectionBuffer: regl.buffer({
          data: new Uint8Array(0),
          usage: 'stream',
          type: 'uint8'
        }),
        // buffers with data: it is faster to switch them per-pass
        // than provide one congregate buffer
        sizeBuffer: regl.buffer({
          data: new Uint8Array(0),
          usage: 'dynamic',
          type: 'uint8'
        }),
        colorBuffer: regl.buffer({
          data: new Uint8Array(0),
          usage: 'dynamic',
          type: 'uint8'
        }),
        positionBuffer: regl.buffer({
          data: new Uint8Array(0),
          usage: 'dynamic',
          type: 'float'
        }),
        positionFractBuffer: regl.buffer({
          data: new Uint8Array(0),
          usage: 'dynamic',
          type: 'float'
        })
      };
      options = extend({}, Scatter.defaults, options);
    } // force update triggers


    if (options.positions && !('marker' in options)) {
      options.marker = group.marker;
      delete group.marker;
    } // updating markers cause recalculating snapping


    if (options.marker && !('positions' in options)) {
      options.positions = group.positions;
      delete group.positions;
    } // global count of points


    var hasSize = 0,
        hasColor = 0;
    updateDiff(group, options, [{
      snap: true,
      size: function size(s, group) {
        if (s == null) s = Scatter.defaults.size;
        hasSize += s && s.length ? 1 : 0;
        return s;
      },
      borderSize: function borderSize(s, group) {
        if (s == null) s = Scatter.defaults.borderSize;
        hasSize += s && s.length ? 1 : 0;
        return s;
      },
      opacity: parseFloat,
      // add colors to palette, save references
      color: function color(c, group) {
        if (c == null) c = Scatter.defaults.color;
        c = _this3.updateColor(c);
        hasColor++;
        return c;
      },
      borderColor: function borderColor(c, group) {
        if (c == null) c = Scatter.defaults.borderColor;
        c = _this3.updateColor(c);
        hasColor++;
        return c;
      },
      bounds: function bounds(_bounds, group, options) {
        if (!('range' in options)) options.range = null;
        return _bounds;
      },
      positions: function positions(_positions, group, options) {
        var snap = group.snap;
        var positionBuffer = group.positionBuffer,
            positionFractBuffer = group.positionFractBuffer,
            selectionBuffer = group.selectionBuffer; // separate buffers for x/y coordinates

        if (_positions.x || _positions.y) {
          if (_positions.x.length) {
            group.xAttr = {
              buffer: regl.buffer(_positions.x),
              offset: 0,
              stride: 4,
              count: _positions.x.length
            };
          } else {
            group.xAttr = {
              buffer: _positions.x.buffer,
              offset: _positions.x.offset * 4 || 0,
              stride: (_positions.x.stride || 1) * 4,
              count: _positions.x.count
            };
          }

          if (_positions.y.length) {
            group.yAttr = {
              buffer: regl.buffer(_positions.y),
              offset: 0,
              stride: 4,
              count: _positions.y.length
            };
          } else {
            group.yAttr = {
              buffer: _positions.y.buffer,
              offset: _positions.y.offset * 4 || 0,
              stride: (_positions.y.stride || 1) * 4,
              count: _positions.y.count
            };
          }

          group.count = Math.max(group.xAttr.count, group.yAttr.count);
          return _positions;
        }

        _positions = flatten(_positions, 'float64');
        var count = group.count = Math.floor(_positions.length / 2);
        var bounds = group.bounds = count ? getBounds(_positions, 2) : null; // if range is not provided updated - recalc it

        if (!options.range && !group.range) {
          delete group.range;
          options.range = bounds;
        } // reset marker


        if (!options.marker && !group.marker) {
          delete group.marker;
          options.marker = null;
        } // build cluster tree if required


        if (snap && (snap === true || count > snap)) {
          group.tree = cluster(_positions, {
            bounds: bounds
          });
        } // existing tree instance
        else if (snap && snap.length) {
            group.tree = snap;
          }

        if (group.tree) {
          var opts = {
            primitive: 'points',
            usage: 'static',
            data: group.tree,
            type: 'uint32'
          };
          if (group.elements) group.elements(opts);else group.elements = regl.elements(opts);
        } // update position buffers


        positionBuffer({
          data: f32.float(_positions),
          usage: 'dynamic'
        });
        positionFractBuffer({
          data: f32.fract(_positions),
          usage: 'dynamic'
        }); // expand selectionBuffer

        selectionBuffer({
          data: new Uint8Array(count),
          type: 'uint8',
          usage: 'stream'
        });
        return _positions;
      }
    }, {
      // create marker ids corresponding to known marker textures
      marker: function marker(markers, group, options) {
        var activation = group.activation; // reset marker elements

        activation.forEach(function (buffer) {
          return buffer && buffer.destroy && buffer.destroy();
        });
        activation.length = 0; // single sdf marker

        if (!markers || typeof markers[0] === 'number') {
          var id = _this3.addMarker(markers);

          activation[id] = true;
        } // per-point markers use mask buffers to enable markers in vert shader
        else {
            var markerMasks = [];

            for (var _i = 0, l = Math.min(markers.length, group.count); _i < l; _i++) {
              var _id = _this3.addMarker(markers[_i]);

              if (!markerMasks[_id]) markerMasks[_id] = new Uint8Array(group.count); // enable marker by default

              markerMasks[_id][_i] = 1;
            }

            for (var _id2 = 0; _id2 < markerMasks.length; _id2++) {
              if (!markerMasks[_id2]) continue;
              var opts = {
                data: markerMasks[_id2],
                type: 'uint8',
                usage: 'static'
              };

              if (!activation[_id2]) {
                activation[_id2] = regl.buffer(opts);
              } else {
                activation[_id2](opts);
              }

              activation[_id2].data = markerMasks[_id2];
            }
          }

        return markers;
      },
      range: function range(_range, group, options) {
        var bounds = group.bounds; // FIXME: why do we need this?

        if (!bounds) return;
        if (!_range) _range = bounds;
        group.scale = [1 / (_range[2] - _range[0]), 1 / (_range[3] - _range[1])];
        group.translate = [-_range[0], -_range[1]];
        group.scaleFract = f32.fract(group.scale);
        group.translateFract = f32.fract(group.translate);
        return _range;
      },
      viewport: function viewport(vp) {
        var rect = parseRect(vp || [gl.drawingBufferWidth, gl.drawingBufferHeight]); // normalize viewport to the canvas coordinates
        // rect.y = gl.drawingBufferHeight - rect.height - rect.y

        return rect;
      }
    }]); // update size buffer, if needed

    if (hasSize) {
      var _group = group,
          count = _group.count,
          size = _group.size,
          borderSize = _group.borderSize,
          sizeBuffer = _group.sizeBuffer;
      var sizes = new Uint8Array(count * 2);

      if (size.length || borderSize.length) {
        for (var _i2 = 0; _i2 < count; _i2++) {
          // we downscale size to allow for fractions
          sizes[_i2 * 2] = Math.round((size[_i2] == null ? size : size[_i2]) * 255 / maxSize);
          sizes[_i2 * 2 + 1] = Math.round((borderSize[_i2] == null ? borderSize : borderSize[_i2]) * 255 / maxSize);
        }
      }

      sizeBuffer({
        data: sizes,
        usage: 'dynamic'
      });
    } // update color buffer if needed


    if (hasColor) {
      var _group2 = group,
          _count = _group2.count,
          color = _group2.color,
          borderColor = _group2.borderColor,
          colorBuffer = _group2.colorBuffer;
      var colors; // if too many colors - put colors to buffer directly

      if (_this3.tooManyColors) {
        if (color.length || borderColor.length) {
          colors = new Uint8Array(_count * 8);

          for (var _i3 = 0; _i3 < _count; _i3++) {
            var _colorId = color[_i3];
            colors[_i3 * 8] = palette[_colorId * 4];
            colors[_i3 * 8 + 1] = palette[_colorId * 4 + 1];
            colors[_i3 * 8 + 2] = palette[_colorId * 4 + 2];
            colors[_i3 * 8 + 3] = palette[_colorId * 4 + 3];
            var borderColorId = borderColor[_i3];
            colors[_i3 * 8 + 4] = palette[borderColorId * 4];
            colors[_i3 * 8 + 5] = palette[borderColorId * 4 + 1];
            colors[_i3 * 8 + 6] = palette[borderColorId * 4 + 2];
            colors[_i3 * 8 + 7] = palette[borderColorId * 4 + 3];
          }
        }
      } // if limited amount of colors - keep palette color picking
      // that saves significant memory
      else {
          if (color.length || borderColor.length) {
            // we need slight data increase by 2 due to vec4 borderId in shader
            colors = new Uint8Array(_count * 4 + 2);

            for (var _i4 = 0; _i4 < _count; _i4++) {
              // put color coords in palette texture
              if (color[_i4] != null) {
                colors[_i4 * 4] = color[_i4] % maxColors;
                colors[_i4 * 4 + 1] = Math.floor(color[_i4] / maxColors);
              }

              if (borderColor[_i4] != null) {
                colors[_i4 * 4 + 2] = borderColor[_i4] % maxColors;
                colors[_i4 * 4 + 3] = Math.floor(borderColor[_i4] / maxColors);
              }
            }
          }
        }

      colorBuffer({
        data: colors || new Uint8Array(0),
        type: 'uint8',
        usage: 'dynamic'
      });
    }

    return group;
  });
}; // get (and create) marker texture id


Scatter.prototype.addMarker = function (sdf) {
  var markerTextures = this.markerTextures,
      regl = this.regl,
      markerCache = this.markerCache;
  var pos = sdf == null ? 0 : markerCache.indexOf(sdf);
  if (pos >= 0) return pos; // convert sdf to 0..255 range

  var distArr;

  if (sdf instanceof Uint8Array || sdf instanceof Uint8ClampedArray) {
    distArr = sdf;
  } else {
    distArr = new Uint8Array(sdf.length);

    for (var i = 0, l = sdf.length; i < l; i++) {
      distArr[i] = sdf[i] * 255;
    }
  }

  var radius = Math.floor(Math.sqrt(distArr.length));
  pos = markerTextures.length;
  markerCache.push(sdf);
  markerTextures.push(regl.texture({
    channels: 1,
    data: distArr,
    radius: radius,
    mag: 'linear',
    min: 'linear'
  }));
  return pos;
}; // register color to palette, return it's index or list of indexes


Scatter.prototype.updateColor = function (colors) {
  var paletteIds = this.paletteIds,
      palette = this.palette,
      maxColors = this.maxColors;

  if (!Array.isArray(colors)) {
    colors = [colors];
  }

  var idx = []; // if color groups - flatten them

  if (typeof colors[0] === 'number') {
    var grouped = [];

    if (Array.isArray(colors)) {
      for (var i = 0; i < colors.length; i += 4) {
        grouped.push(colors.slice(i, i + 4));
      }
    } else {
      for (var _i5 = 0; _i5 < colors.length; _i5 += 4) {
        grouped.push(colors.subarray(_i5, _i5 + 4));
      }
    }

    colors = grouped;
  }

  for (var _i6 = 0; _i6 < colors.length; _i6++) {
    var color = colors[_i6];
    color = rgba(color, 'uint8');
    var id = colorId(color, false); // if new color - save it

    if (paletteIds[id] == null) {
      var pos = palette.length;
      paletteIds[id] = Math.floor(pos / 4);
      palette[pos] = color[0];
      palette[pos + 1] = color[1];
      palette[pos + 2] = color[2];
      palette[pos + 3] = color[3];
    }

    idx[_i6] = paletteIds[id];
  } // detect if too many colors in palette


  if (!this.tooManyColors && palette.length > maxColors * 4) this.tooManyColors = true; // limit max color

  this.updatePalette(palette); // keep static index for single-color property

  return idx.length === 1 ? idx[0] : idx;
};

Scatter.prototype.updatePalette = function (palette) {
  if (this.tooManyColors) return;
  var maxColors = this.maxColors,
      paletteTexture = this.paletteTexture;
  var requiredHeight = Math.ceil(palette.length * .25 / maxColors); // pad data

  if (requiredHeight > 1) {
    palette = palette.slice();

    for (var i = palette.length * .25 % maxColors; i < requiredHeight * maxColors; i++) {
      palette.push(0, 0, 0, 0);
    }
  } // ensure height


  if (paletteTexture.height < requiredHeight) {
    paletteTexture.resize(maxColors, requiredHeight);
  } // update full data


  paletteTexture.subimage({
    width: Math.min(palette.length * .25, maxColors),
    height: requiredHeight,
    data: palette
  }, 0, 0);
}; // remove unused stuff


Scatter.prototype.destroy = function () {
  this.groups.forEach(function (group) {
    group.sizeBuffer.destroy();
    group.positionBuffer.destroy();
    group.positionFractBuffer.destroy();
    group.colorBuffer.destroy();
    group.activation.forEach(function (b) {
      return b && b.destroy && b.destroy();
    });
    group.selectionBuffer.destroy();
    if (group.elements) group.elements.destroy();
  });
  this.groups.length = 0;
  this.paletteTexture.destroy();
  this.markerTextures.forEach(function (txt) {
    return txt && txt.destroy && txt.destroy();
  });
  return this;
};

var extend$1 = _dereq_('object-assign');

var reglScatter2d = function reglScatter2d(regl, options) {
  var scatter$$1 = new scatter(regl, options);
  var render = scatter$$1.render.bind(scatter$$1); // expose API

  extend$1(render, {
    render: render,
    update: scatter$$1.update.bind(scatter$$1),
    draw: scatter$$1.draw.bind(scatter$$1),
    destroy: scatter$$1.destroy.bind(scatter$$1),
    regl: scatter$$1.regl,
    gl: scatter$$1.gl,
    canvas: scatter$$1.gl.canvas,
    groups: scatter$$1.groups,
    markers: scatter$$1.markerCache,
    palette: scatter$$1.palette
  });
  return render;
};

module.exports = reglScatter2d;

},{"array-bounds":53,"color-id":106,"color-normalize":108,"flatten-vertex-data":220,"glslify":398,"is-iexplorer":408,"object-assign":443,"parse-rect":448,"pick-by-alias":454,"point-cluster":458,"to-float32":519,"update-diff":530}],482:[function(_dereq_,module,exports){
'use strict'


var createScatter = _dereq_('regl-scatter2d')
var pick = _dereq_('pick-by-alias')
var getBounds = _dereq_('array-bounds')
var raf = _dereq_('raf')
var arrRange = _dereq_('array-range')
var rect = _dereq_('parse-rect')
var flatten = _dereq_('flatten-vertex-data')


module.exports = SPLOM


// @constructor
function SPLOM (regl, options) {
	if (!(this instanceof SPLOM)) { return new SPLOM(regl, options) }

	// render passes
	this.traces = []

	// passes for scatter, combined across traces
	this.passes = {}

	this.regl = regl

	// main scatter drawing instance
	this.scatter = createScatter(regl)

	this.canvas = this.scatter.canvas
}


// update & draw passes once per frame
SPLOM.prototype.render = function () {
	var this$1 = this;
	var ref;

	var args = [], len = arguments.length;
	while ( len-- ) args[ len ] = arguments[ len ];
	if (args.length) {
		(ref = this).update.apply(ref, args)
	}

	if (this.regl.attributes.preserveDrawingBuffer) { return this.draw() }

	// make sure draw is not called more often than once a frame
	if (this.dirty) {
		if (this.planned == null) {
			this.planned = raf(function () {
				this$1.draw()
				this$1.dirty = true
				this$1.planned = null
			})
		}
	}
	else {
		this.draw()
		this.dirty = true
		raf(function () {
			this$1.dirty = false
		})
	}

	return this
}


// update passes
SPLOM.prototype.update = function () {
	var this$1 = this;
	var ref;

	var args = [], len = arguments.length;
	while ( len-- ) args[ len ] = arguments[ len ];
	if (!args.length) { return }

	for (var i = 0; i < args.length; i++) {
		this$1.updateItem(i, args[i])
	}

	// remove nulled passes
	this.traces = this.traces.filter(Boolean)

	// FIXME: update passes independently
	var passes = []
	var offset = 0
	for (var i$1 = 0; i$1 < this.traces.length; i$1++) {
		var trace = this$1.traces[i$1]
		var tracePasses = this$1.traces[i$1].passes
		for (var j = 0; j < tracePasses.length; j++) {
			passes.push(this$1.passes[tracePasses[j]])
		}
		// save offset of passes
		trace.passOffset = offset
		offset += trace.passes.length
	}

	(ref = this.scatter).update.apply(ref, passes)

	return this
}


// update trace by index, not supposed to be called directly
SPLOM.prototype.updateItem = function (i, options) {
	var this$1 = this;

	var ref = this;
	var regl = ref.regl;

	// remove pass if null
	if (options === null) {
		this.traces[i] = null
		return this
	}

	if (!options) { return this }

	var o = pick(options, {
		data: 'data items columns rows values dimensions samples x',
		snap: 'snap cluster',
		size: 'sizes size radius',
		color: 'colors color fill fill-color fillColor',
		opacity: 'opacity alpha transparency opaque',
		borderSize: 'borderSizes borderSize border-size bordersize borderWidth borderWidths border-width borderwidth stroke-width strokeWidth strokewidth outline',
		borderColor: 'borderColors borderColor bordercolor stroke stroke-color strokeColor',
		marker: 'markers marker shape',
		range: 'range ranges databox dataBox',
		viewport: 'viewport viewBox viewbox',
		domain: 'domain domains area areas',
		padding: 'pad padding paddings pads margin margins',
		transpose: 'transpose transposed',
		diagonal: 'diagonal diag showDiagonal',
		upper: 'upper up top upperhalf upperHalf showupperhalf showUpper showUpperHalf',
		lower: 'lower low bottom lowerhalf lowerHalf showlowerhalf showLowerHalf showLower'
	})

	// we provide regl buffer per-trace, since trace data can be changed
	var trace = (this.traces[i] || (this.traces[i] = {
		id: i,
		buffer: regl.buffer({
			usage: 'dynamic',
			type: 'float',
			data: new Uint8Array()
		}),
		color: 'black',
		marker: null,
		size: 12,
		borderColor: 'transparent',
		borderSize: 1,
		viewport:  rect([regl._gl.drawingBufferWidth, regl._gl.drawingBufferHeight]),
		padding: [0, 0, 0, 0],
		opacity: 1,
		diagonal: true,
		upper: true,
		lower: true
	}))


	// save styles
	if (o.color != null) {
		trace.color = o.color
	}
	if (o.size != null) {
		trace.size = o.size
	}
	if (o.marker != null) {
		trace.marker = o.marker
	}
	if (o.borderColor != null) {
		trace.borderColor = o.borderColor
	}
	if (o.borderSize != null) {
		trace.borderSize = o.borderSize
	}
	if (o.opacity != null) {
		trace.opacity = o.opacity
	}
	if (o.viewport) {
		trace.viewport = rect(o.viewport)
	}
	if (o.diagonal != null) { trace.diagonal = o.diagonal }
	if (o.upper != null) { trace.upper = o.upper }
	if (o.lower != null) { trace.lower = o.lower }

	// put flattened data into buffer
	if (o.data) {
		trace.buffer(flatten(o.data))
		trace.columns = o.data.length
		trace.count = o.data[0].length

		// detect bounds per-column
		trace.bounds = []

		for (var i$1 = 0; i$1 < trace.columns; i$1++) {
			trace.bounds[i$1] = getBounds(o.data[i$1], 1)
		}
	}

	// add proper range updating markers
	var multirange
	if (o.range) {
		trace.range = o.range
		multirange = trace.range && typeof trace.range[0] !== 'number'
	}

	if (o.domain) {
		trace.domain = o.domain
	}
	var multipadding = false
	if (o.padding != null) {
		// multiple paddings
		if (Array.isArray(o.padding) && o.padding.length === trace.columns && typeof o.padding[o.padding.length - 1] === 'number') {
			trace.padding = o.padding.map(getPad)
			multipadding = true
		}
		// single padding
		else {
			trace.padding = getPad(o.padding)
		}
	}

	// create passes
	var m = trace.columns
	var n = trace.count

	var w = trace.viewport.width
	var h = trace.viewport.height
	var left = trace.viewport.x
	var top = trace.viewport.y
	var iw = w / m
	var ih = h / m

	trace.passes = []

	for (var i$2 = 0; i$2 < m; i$2++) {
		for (var j = 0; j < m; j++) {
			if (!trace.diagonal && j === i$2) { continue }
			if (!trace.upper && i$2 > j) { continue }
			if (!trace.lower && i$2 < j) { continue }

			var key = passId(trace.id, i$2, j)

			var pass = this$1.passes[key] || (this$1.passes[key] = {})

			if (o.data) {
				if (o.transpose) {
					pass.positions = {
						x: {buffer: trace.buffer, offset: j, count: n, stride: m},
						y: {buffer: trace.buffer, offset: i$2, count: n, stride: m}
					}
				}
				else {
					pass.positions = {
						x: {buffer: trace.buffer, offset: j * n, count: n},
						y: {buffer: trace.buffer, offset: i$2 * n, count: n}
					}
				}

				pass.bounds = getBox(trace.bounds, i$2, j)
			}

			if (o.domain || o.viewport || o.data) {
				var pad = multipadding ? getBox(trace.padding, i$2, j) : trace.padding
				if (trace.domain) {
					var ref$1 = getBox(trace.domain, i$2, j);
					var lox = ref$1[0];
					var loy = ref$1[1];
					var hix = ref$1[2];
					var hiy = ref$1[3];

					pass.viewport = [
						left + lox * w + pad[0],
						top + loy * h + pad[1],
						left + hix * w - pad[2],
						top + hiy * h - pad[3]
					]
				}
				// consider auto-domain equipartial
				else {
					pass.viewport = [
						left + j * iw + iw * pad[0],
						top + i$2 * ih + ih * pad[1],
						left + (j + 1) * iw - iw * pad[2],
						top + (i$2 + 1) * ih - ih * pad[3]
					]
				}
			}

			if (o.color) { pass.color = trace.color }
			if (o.size) { pass.size = trace.size }
			if (o.marker) { pass.marker = trace.marker }
			if (o.borderSize) { pass.borderSize = trace.borderSize }
			if (o.borderColor) { pass.borderColor = trace.borderColor }
			if (o.opacity) { pass.opacity = trace.opacity }

			if (o.range) {
				pass.range = multirange ? getBox(trace.range, i$2, j) : trace.range || pass.bounds
			}

			trace.passes.push(key)
		}
	}

	return this
}


// draw all or passed passes
SPLOM.prototype.draw = function () {
	var this$1 = this;
	var ref$2;

	var args = [], len = arguments.length;
	while ( len-- ) args[ len ] = arguments[ len ];
	if (!args.length) {
		this.scatter.draw()
	}
	else {
		var idx = []
		for (var i = 0; i < args.length; i++) {
			// draw(0, 2, 5) - draw traces
			if (typeof args[i] === 'number' ) {
				var ref = this$1.traces[args[i]];
				var passes = ref.passes;
				var passOffset = ref.passOffset;
				idx.push.apply(idx, arrRange(passOffset, passOffset + passes.length))
			}
			// draw([0, 1, 2 ...], [3, 4, 5]) - draw points
			else if (args[i].length) {
				var els = args[i]
				var ref$1 = this$1.traces[i];
				var passes$1 = ref$1.passes;
				var passOffset$1 = ref$1.passOffset;
				passes$1 = passes$1.map(function (passId, i) {
					idx[passOffset$1 + i] = els
				})
			}
		}
		(ref$2 = this.scatter).draw.apply(ref$2, idx)
	}

	return this
}


// dispose resources
SPLOM.prototype.destroy = function () {
	this.traces.forEach(function (trace) {
		if (trace.buffer && trace.buffer.destroy) { trace.buffer.destroy() }
	})
	this.traces = null
	this.passes = null

	this.scatter.destroy()

	return this
}


// return pass corresponding to trace i- j- square
function passId (trace, i, j) {
	var id = (trace.id != null ? trace.id : trace)
	var n = i
	var m = j
	var key = id << 16 | (n & 0xff) << 8 | m & 0xff

	return key
}


// return bounding box corresponding to a pass
function getBox (items, i, j) {
	var ilox, iloy, ihix, ihiy, jlox, jloy, jhix, jhiy
	var iitem = items[i], jitem = items[j]

	if (iitem.length > 2) {
		ilox = iitem[0]
		ihix = iitem[2]
		iloy = iitem[1]
		ihiy = iitem[3]
	}
	else if (iitem.length) {
		ilox = iloy = iitem[0]
		ihix = ihiy = iitem[1]
	}
	else {
		ilox = iitem.x
		iloy = iitem.y
		ihix = iitem.x + iitem.width
		ihiy = iitem.y + iitem.height
	}

	if (jitem.length > 2) {
		jlox = jitem[0]
		jhix = jitem[2]
		jloy = jitem[1]
		jhiy = jitem[3]
	}
	else if (jitem.length) {
		jlox = jloy = jitem[0]
		jhix = jhiy = jitem[1]
	}
	else {
		jlox = jitem.x
		jloy = jitem.y
		jhix = jitem.x + jitem.width
		jhiy = jitem.y + jitem.height
	}

	return [ jlox, iloy, jhix, ihiy ]
}


function getPad (arg) {
	if (typeof arg === 'number') { return [arg, arg, arg, arg] }
	else if (arg.length === 2) { return [arg[0], arg[1], arg[0], arg[1]] }
	else {
		var box = rect(arg)
		return [box.x, box.y, box.x + box.width, box.y + box.height]
	}
}

},{"array-bounds":53,"array-range":55,"flatten-vertex-data":220,"parse-rect":448,"pick-by-alias":454,"raf":473,"regl-scatter2d":481}],483:[function(_dereq_,module,exports){
(function(aa,ia){"object"===typeof exports&&"undefined"!==typeof module?module.exports=ia():"function"===typeof define&&define.amd?define(ia):aa.createREGL=ia()})(this,function(){function aa(a,b){this.id=Ab++;this.type=a;this.data=b}function ia(a){if(0===a.length)return[];var b=a.charAt(0),c=a.charAt(a.length-1);if(1<a.length&&b===c&&('"'===b||"'"===b))return['"'+a.substr(1,a.length-2).replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'];if(b=/\[(false|true|null|\d+|'[^']*'|"[^"]*")\]/.exec(a))return ia(a.substr(0,
b.index)).concat(ia(b[1])).concat(ia(a.substr(b.index+b[0].length)));b=a.split(".");if(1===b.length)return['"'+a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'];a=[];for(c=0;c<b.length;++c)a=a.concat(ia(b[c]));return a}function Za(a){return"["+ia(a).join("][")+"]"}function Bb(){var a={"":0},b=[""];return{id:function(c){var e=a[c];if(e)return e;e=a[c]=b.length;b.push(c);return e},str:function(a){return b[a]}}}function Cb(a,b,c){function e(){var b=window.innerWidth,e=window.innerHeight;a!==document.body&&
(e=a.getBoundingClientRect(),b=e.right-e.left,e=e.bottom-e.top);g.width=c*b;g.height=c*e;E(g.style,{width:b+"px",height:e+"px"})}var g=document.createElement("canvas");E(g.style,{border:0,margin:0,padding:0,top:0,left:0});a.appendChild(g);a===document.body&&(g.style.position="absolute",E(a.style,{margin:0,padding:0}));window.addEventListener("resize",e,!1);e();return{canvas:g,onDestroy:function(){window.removeEventListener("resize",e);a.removeChild(g)}}}function Db(a,b){function c(c){try{return a.getContext(c,
b)}catch(g){return null}}return c("webgl")||c("experimental-webgl")||c("webgl-experimental")}function $a(a){return"string"===typeof a?a.split():a}function ab(a){return"string"===typeof a?document.querySelector(a):a}function Eb(a){var b=a||{},c,e,g,d;a={};var n=[],f=[],r="undefined"===typeof window?1:window.devicePixelRatio,q=!1,t=function(a){},m=function(){};"string"===typeof b?c=document.querySelector(b):"object"===typeof b&&("string"===typeof b.nodeName&&"function"===typeof b.appendChild&&"function"===
typeof b.getBoundingClientRect?c=b:"function"===typeof b.drawArrays||"function"===typeof b.drawElements?(d=b,g=d.canvas):("gl"in b?d=b.gl:"canvas"in b?g=ab(b.canvas):"container"in b&&(e=ab(b.container)),"attributes"in b&&(a=b.attributes),"extensions"in b&&(n=$a(b.extensions)),"optionalExtensions"in b&&(f=$a(b.optionalExtensions)),"onDone"in b&&(t=b.onDone),"profile"in b&&(q=!!b.profile),"pixelRatio"in b&&(r=+b.pixelRatio)));c&&("canvas"===c.nodeName.toLowerCase()?g=c:e=c);if(!d){if(!g){c=Cb(e||document.body,
t,r);if(!c)return null;g=c.canvas;m=c.onDestroy}d=Db(g,a)}return d?{gl:d,canvas:g,container:e,extensions:n,optionalExtensions:f,pixelRatio:r,profile:q,onDone:t,onDestroy:m}:(m(),t("webgl not supported, try upgrading your browser or graphics drivers http://get.webgl.org"),null)}function Fb(a,b){function c(b){b=b.toLowerCase();var c;try{c=e[b]=a.getExtension(b)}catch(g){}return!!c}for(var e={},g=0;g<b.extensions.length;++g){var d=b.extensions[g];if(!c(d))return b.onDestroy(),b.onDone('"'+d+'" extension is not supported by the current WebGL context, try upgrading your system or a different browser'),
null}b.optionalExtensions.forEach(c);return{extensions:e,restore:function(){Object.keys(e).forEach(function(a){if(e[a]&&!c(a))throw Error("(regl): error restoring extension "+a);})}}}function J(a,b){for(var c=Array(a),e=0;e<a;++e)c[e]=b(e);return c}function bb(a){var b,c;b=(65535<a)<<4;a>>>=b;c=(255<a)<<3;a>>>=c;b|=c;c=(15<a)<<2;a>>>=c;b|=c;c=(3<a)<<1;return b|c|a>>>c>>1}function cb(){function a(a){a:{for(var b=16;268435456>=b;b*=16)if(a<=b){a=b;break a}a=0}b=c[bb(a)>>2];return 0<b.length?b.pop():
new ArrayBuffer(a)}function b(a){c[bb(a.byteLength)>>2].push(a)}var c=J(8,function(){return[]});return{alloc:a,free:b,allocType:function(b,c){var d=null;switch(b){case 5120:d=new Int8Array(a(c),0,c);break;case 5121:d=new Uint8Array(a(c),0,c);break;case 5122:d=new Int16Array(a(2*c),0,c);break;case 5123:d=new Uint16Array(a(2*c),0,c);break;case 5124:d=new Int32Array(a(4*c),0,c);break;case 5125:d=new Uint32Array(a(4*c),0,c);break;case 5126:d=new Float32Array(a(4*c),0,c);break;default:return null}return d.length!==
c?d.subarray(0,c):d},freeType:function(a){b(a.buffer)}}}function ma(a){return!!a&&"object"===typeof a&&Array.isArray(a.shape)&&Array.isArray(a.stride)&&"number"===typeof a.offset&&a.shape.length===a.stride.length&&(Array.isArray(a.data)||M(a.data))}function db(a,b,c,e,g,d){for(var n=0;n<b;++n)for(var f=a[n],r=0;r<c;++r)for(var q=f[r],t=0;t<e;++t)g[d++]=q[t]}function eb(a,b,c,e,g){for(var d=1,n=c+1;n<b.length;++n)d*=b[n];var f=b[c];if(4===b.length-c){var r=b[c+1],q=b[c+2];b=b[c+3];for(n=0;n<f;++n)db(a[n],
r,q,b,e,g),g+=d}else for(n=0;n<f;++n)eb(a[n],b,c+1,e,g),g+=d}function Ha(a){return Ia[Object.prototype.toString.call(a)]|0}function fb(a,b){for(var c=0;c<b.length;++c)a[c]=b[c]}function gb(a,b,c,e,g,d,n){for(var f=0,r=0;r<c;++r)for(var q=0;q<e;++q)a[f++]=b[g*r+d*q+n]}function Gb(a,b,c,e){function g(b){this.id=r++;this.buffer=a.createBuffer();this.type=b;this.usage=35044;this.byteLength=0;this.dimension=1;this.dtype=5121;this.persistentData=null;c.profile&&(this.stats={size:0})}function d(b,c,k){b.byteLength=
c.byteLength;a.bufferData(b.type,c,k)}function n(a,b,c,h,l,e){a.usage=c;if(Array.isArray(b)){if(a.dtype=h||5126,0<b.length)if(Array.isArray(b[0])){l=hb(b);for(var v=h=1;v<l.length;++v)h*=l[v];a.dimension=h;b=Qa(b,l,a.dtype);d(a,b,c);e?a.persistentData=b:x.freeType(b)}else"number"===typeof b[0]?(a.dimension=l,l=x.allocType(a.dtype,b.length),fb(l,b),d(a,l,c),e?a.persistentData=l:x.freeType(l)):M(b[0])&&(a.dimension=b[0].length,a.dtype=h||Ha(b[0])||5126,b=Qa(b,[b.length,b[0].length],a.dtype),d(a,b,c),
e?a.persistentData=b:x.freeType(b))}else if(M(b))a.dtype=h||Ha(b),a.dimension=l,d(a,b,c),e&&(a.persistentData=new Uint8Array(new Uint8Array(b.buffer)));else if(ma(b)){l=b.shape;var g=b.stride,v=b.offset,f=0,q=0,r=0,t=0;1===l.length?(f=l[0],q=1,r=g[0],t=0):2===l.length&&(f=l[0],q=l[1],r=g[0],t=g[1]);a.dtype=h||Ha(b.data)||5126;a.dimension=q;l=x.allocType(a.dtype,f*q);gb(l,b.data,f,q,r,t,v);d(a,l,c);e?a.persistentData=l:x.freeType(l)}}function f(c){b.bufferCount--;for(var d=0;d<e.state.length;++d){var k=
e.state[d];k.buffer===c&&(a.disableVertexAttribArray(d),k.buffer=null)}a.deleteBuffer(c.buffer);c.buffer=null;delete q[c.id]}var r=0,q={};g.prototype.bind=function(){a.bindBuffer(this.type,this.buffer)};g.prototype.destroy=function(){f(this)};var t=[];c.profile&&(b.getTotalBufferSize=function(){var a=0;Object.keys(q).forEach(function(b){a+=q[b].stats.size});return a});return{create:function(m,e,d,h){function l(b){var m=35044,e=null,d=0,k=0,g=1;Array.isArray(b)||M(b)||ma(b)?e=b:"number"===typeof b?
d=b|0:b&&("data"in b&&(e=b.data),"usage"in b&&(m=jb[b.usage]),"type"in b&&(k=Ra[b.type]),"dimension"in b&&(g=b.dimension|0),"length"in b&&(d=b.length|0));u.bind();e?n(u,e,m,k,g,h):(d&&a.bufferData(u.type,d,m),u.dtype=k||5121,u.usage=m,u.dimension=g,u.byteLength=d);c.profile&&(u.stats.size=u.byteLength*ja[u.dtype]);return l}b.bufferCount++;var u=new g(e);q[u.id]=u;d||l(m);l._reglType="buffer";l._buffer=u;l.subdata=function(b,c){var m=(c||0)|0,e;u.bind();if(M(b))a.bufferSubData(u.type,m,b);else if(Array.isArray(b)){if(0<
b.length)if("number"===typeof b[0]){var d=x.allocType(u.dtype,b.length);fb(d,b);a.bufferSubData(u.type,m,d);x.freeType(d)}else if(Array.isArray(b[0])||M(b[0]))e=hb(b),d=Qa(b,e,u.dtype),a.bufferSubData(u.type,m,d),x.freeType(d)}else if(ma(b)){e=b.shape;var h=b.stride,k=d=0,g=0,F=0;1===e.length?(d=e[0],k=1,g=h[0],F=0):2===e.length&&(d=e[0],k=e[1],g=h[0],F=h[1]);e=Array.isArray(b.data)?u.dtype:Ha(b.data);e=x.allocType(e,d*k);gb(e,b.data,d,k,g,F,b.offset);a.bufferSubData(u.type,m,e);x.freeType(e)}return l};
c.profile&&(l.stats=u.stats);l.destroy=function(){f(u)};return l},createStream:function(a,b){var c=t.pop();c||(c=new g(a));c.bind();n(c,b,35040,0,1,!1);return c},destroyStream:function(a){t.push(a)},clear:function(){S(q).forEach(f);t.forEach(f)},getBuffer:function(a){return a&&a._buffer instanceof g?a._buffer:null},restore:function(){S(q).forEach(function(b){b.buffer=a.createBuffer();a.bindBuffer(b.type,b.buffer);a.bufferData(b.type,b.persistentData||b.byteLength,b.usage)})},_initBuffer:n}}function Hb(a,
b,c,e){function g(a){this.id=r++;f[this.id]=this;this.buffer=a;this.primType=4;this.type=this.vertCount=0}function d(e,d,g,h,l,u,v){e.buffer.bind();if(d){var f=v;v||M(d)&&(!ma(d)||M(d.data))||(f=b.oes_element_index_uint?5125:5123);c._initBuffer(e.buffer,d,g,f,3)}else a.bufferData(34963,u,g),e.buffer.dtype=f||5121,e.buffer.usage=g,e.buffer.dimension=3,e.buffer.byteLength=u;f=v;if(!v){switch(e.buffer.dtype){case 5121:case 5120:f=5121;break;case 5123:case 5122:f=5123;break;case 5125:case 5124:f=5125}e.buffer.dtype=
f}e.type=f;d=l;0>d&&(d=e.buffer.byteLength,5123===f?d>>=1:5125===f&&(d>>=2));e.vertCount=d;d=h;0>h&&(d=4,h=e.buffer.dimension,1===h&&(d=0),2===h&&(d=1),3===h&&(d=4));e.primType=d}function n(a){e.elementsCount--;delete f[a.id];a.buffer.destroy();a.buffer=null}var f={},r=0,q={uint8:5121,uint16:5123};b.oes_element_index_uint&&(q.uint32=5125);g.prototype.bind=function(){this.buffer.bind()};var t=[];return{create:function(a,b){function k(a){if(a)if("number"===typeof a)h(a),l.primType=4,l.vertCount=a|0,
l.type=5121;else{var b=null,c=35044,e=-1,g=-1,f=0,m=0;if(Array.isArray(a)||M(a)||ma(a))b=a;else if("data"in a&&(b=a.data),"usage"in a&&(c=jb[a.usage]),"primitive"in a&&(e=Sa[a.primitive]),"count"in a&&(g=a.count|0),"type"in a&&(m=q[a.type]),"length"in a)f=a.length|0;else if(f=g,5123===m||5122===m)f*=2;else if(5125===m||5124===m)f*=4;d(l,b,c,e,g,f,m)}else h(),l.primType=4,l.vertCount=0,l.type=5121;return k}var h=c.create(null,34963,!0),l=new g(h._buffer);e.elementsCount++;k(a);k._reglType="elements";
k._elements=l;k.subdata=function(a,b){h.subdata(a,b);return k};k.destroy=function(){n(l)};return k},createStream:function(a){var b=t.pop();b||(b=new g(c.create(null,34963,!0,!1)._buffer));d(b,a,35040,-1,-1,0,0);return b},destroyStream:function(a){t.push(a)},getElements:function(a){return"function"===typeof a&&a._elements instanceof g?a._elements:null},clear:function(){S(f).forEach(n)}}}function kb(a){for(var b=x.allocType(5123,a.length),c=0;c<a.length;++c)if(isNaN(a[c]))b[c]=65535;else if(Infinity===
a[c])b[c]=31744;else if(-Infinity===a[c])b[c]=64512;else{lb[0]=a[c];var e=Ib[0],g=e>>>31<<15,d=(e<<1>>>24)-127,e=e>>13&1023;b[c]=-24>d?g:-14>d?g+(e+1024>>-14-d):15<d?g+31744:g+(d+15<<10)+e}return b}function pa(a){return Array.isArray(a)||M(a)}function Ea(a){return"[object "+a+"]"}function mb(a){return Array.isArray(a)&&(0===a.length||"number"===typeof a[0])}function nb(a){return Array.isArray(a)&&0!==a.length&&pa(a[0])?!0:!1}function na(a){return Object.prototype.toString.call(a)}function Ta(a){if(!a)return!1;
var b=na(a);return 0<=Jb.indexOf(b)?!0:mb(a)||nb(a)||ma(a)}function ob(a,b){36193===a.type?(a.data=kb(b),x.freeType(b)):a.data=b}function Ja(a,b,c,e,g,d){a="undefined"!==typeof y[a]?y[a]:L[a]*qa[b];d&&(a*=6);if(g){for(e=0;1<=c;)e+=a*c*c,c/=2;return e}return a*c*e}function Kb(a,b,c,e,g,d,n){function f(){this.format=this.internalformat=6408;this.type=5121;this.flipY=this.premultiplyAlpha=this.compressed=!1;this.unpackAlignment=1;this.colorSpace=37444;this.channels=this.height=this.width=0}function r(a,
b){a.internalformat=b.internalformat;a.format=b.format;a.type=b.type;a.compressed=b.compressed;a.premultiplyAlpha=b.premultiplyAlpha;a.flipY=b.flipY;a.unpackAlignment=b.unpackAlignment;a.colorSpace=b.colorSpace;a.width=b.width;a.height=b.height;a.channels=b.channels}function q(a,b){if("object"===typeof b&&b){"premultiplyAlpha"in b&&(a.premultiplyAlpha=b.premultiplyAlpha);"flipY"in b&&(a.flipY=b.flipY);"alignment"in b&&(a.unpackAlignment=b.alignment);"colorSpace"in b&&(a.colorSpace=wa[b.colorSpace]);
"type"in b&&(a.type=G[b.type]);var c=a.width,e=a.height,d=a.channels,h=!1;"shape"in b?(c=b.shape[0],e=b.shape[1],3===b.shape.length&&(d=b.shape[2],h=!0)):("radius"in b&&(c=e=b.radius),"width"in b&&(c=b.width),"height"in b&&(e=b.height),"channels"in b&&(d=b.channels,h=!0));a.width=c|0;a.height=e|0;a.channels=d|0;c=!1;"format"in b&&(c=b.format,e=a.internalformat=U[c],a.format=Lb[e],c in G&&!("type"in b)&&(a.type=G[c]),c in W&&(a.compressed=!0),c=!0);!h&&c?a.channels=L[a.format]:h&&!c&&a.channels!==
La[a.format]&&(a.format=a.internalformat=La[a.channels])}}function t(b){a.pixelStorei(37440,b.flipY);a.pixelStorei(37441,b.premultiplyAlpha);a.pixelStorei(37443,b.colorSpace);a.pixelStorei(3317,b.unpackAlignment)}function m(){f.call(this);this.yOffset=this.xOffset=0;this.data=null;this.needsFree=!1;this.element=null;this.needsCopy=!1}function C(a,b){var c=null;Ta(b)?c=b:b&&(q(a,b),"x"in b&&(a.xOffset=b.x|0),"y"in b&&(a.yOffset=b.y|0),Ta(b.data)&&(c=b.data));if(b.copy){var e=g.viewportWidth,d=g.viewportHeight;
a.width=a.width||e-a.xOffset;a.height=a.height||d-a.yOffset;a.needsCopy=!0}else if(!c)a.width=a.width||1,a.height=a.height||1,a.channels=a.channels||4;else if(M(c))a.channels=a.channels||4,a.data=c,"type"in b||5121!==a.type||(a.type=Ia[Object.prototype.toString.call(c)]|0);else if(mb(c)){a.channels=a.channels||4;e=c;d=e.length;switch(a.type){case 5121:case 5123:case 5125:case 5126:d=x.allocType(a.type,d);d.set(e);a.data=d;break;case 36193:a.data=kb(e)}a.alignment=1;a.needsFree=!0}else if(ma(c)){e=
c.data;Array.isArray(e)||5121!==a.type||(a.type=Ia[Object.prototype.toString.call(e)]|0);var d=c.shape,h=c.stride,f,l,p,w;3===d.length?(p=d[2],w=h[2]):w=p=1;f=d[0];l=d[1];d=h[0];h=h[1];a.alignment=1;a.width=f;a.height=l;a.channels=p;a.format=a.internalformat=La[p];a.needsFree=!0;f=w;c=c.offset;p=a.width;w=a.height;l=a.channels;for(var z=x.allocType(36193===a.type?5126:a.type,p*w*l),I=0,fa=0;fa<w;++fa)for(var ga=0;ga<p;++ga)for(var xa=0;xa<l;++xa)z[I++]=e[d*ga+h*fa+f*xa+c];ob(a,z)}else if(na(c)===
Ua||na(c)===pb)na(c)===Ua?a.element=c:a.element=c.canvas,a.width=a.element.width,a.height=a.element.height,a.channels=4;else if(na(c)===qb)a.element=c,a.width=c.width,a.height=c.height,a.channels=4;else if(na(c)===rb)a.element=c,a.width=c.naturalWidth,a.height=c.naturalHeight,a.channels=4;else if(na(c)===sb)a.element=c,a.width=c.videoWidth,a.height=c.videoHeight,a.channels=4;else if(nb(c)){e=a.width||c[0].length;d=a.height||c.length;h=a.channels;h=pa(c[0][0])?h||c[0][0].length:h||1;f=Ma.shape(c);
p=1;for(w=0;w<f.length;++w)p*=f[w];p=x.allocType(36193===a.type?5126:a.type,p);Ma.flatten(c,f,"",p);ob(a,p);a.alignment=1;a.width=e;a.height=d;a.channels=h;a.format=a.internalformat=La[h];a.needsFree=!0}}function k(b,c,d,h,f){var g=b.element,l=b.data,k=b.internalformat,p=b.format,w=b.type,z=b.width,I=b.height;t(b);g?a.texSubImage2D(c,f,d,h,p,w,g):b.compressed?a.compressedTexSubImage2D(c,f,d,h,k,z,I,l):b.needsCopy?(e(),a.copyTexSubImage2D(c,f,d,h,b.xOffset,b.yOffset,z,I)):a.texSubImage2D(c,f,d,h,z,
I,p,w,l)}function h(){return P.pop()||new m}function l(a){a.needsFree&&x.freeType(a.data);m.call(a);P.push(a)}function u(){f.call(this);this.genMipmaps=!1;this.mipmapHint=4352;this.mipmask=0;this.images=Array(16)}function v(a,b,c){var d=a.images[0]=h();a.mipmask=1;d.width=a.width=b;d.height=a.height=c;d.channels=a.channels=4}function N(a,b){var c=null;if(Ta(b))c=a.images[0]=h(),r(c,a),C(c,b),a.mipmask=1;else if(q(a,b),Array.isArray(b.mipmap))for(var d=b.mipmap,e=0;e<d.length;++e)c=a.images[e]=h(),
r(c,a),c.width>>=e,c.height>>=e,C(c,d[e]),a.mipmask|=1<<e;else c=a.images[0]=h(),r(c,a),C(c,b),a.mipmask=1;r(a,a.images[0])}function B(b,c){for(var d=b.images,h=0;h<d.length&&d[h];++h){var f=d[h],g=c,l=h,k=f.element,p=f.data,w=f.internalformat,z=f.format,I=f.type,fa=f.width,ga=f.height,xa=f.channels;t(f);k?a.texImage2D(g,l,z,z,I,k):f.compressed?a.compressedTexImage2D(g,l,w,fa,ga,0,p):f.needsCopy?(e(),a.copyTexImage2D(g,l,z,f.xOffset,f.yOffset,fa,ga,0)):((f=!p)&&(p=x.zero.allocType(I,fa*ga*xa)),a.texImage2D(g,
l,z,fa,ga,0,z,I,p),f&&p&&x.zero.freeType(p))}}function D(){var a=tb.pop()||new u;f.call(a);for(var b=a.mipmask=0;16>b;++b)a.images[b]=null;return a}function ib(a){for(var b=a.images,c=0;c<b.length;++c)b[c]&&l(b[c]),b[c]=null;tb.push(a)}function y(){this.magFilter=this.minFilter=9728;this.wrapT=this.wrapS=33071;this.anisotropic=1;this.genMipmaps=!1;this.mipmapHint=4352}function O(a,b){"min"in b&&(a.minFilter=Va[b.min],0<=Mb.indexOf(a.minFilter)&&!("faces"in b)&&(a.genMipmaps=!0));"mag"in b&&(a.magFilter=
V[b.mag]);var c=a.wrapS,d=a.wrapT;if("wrap"in b){var e=b.wrap;"string"===typeof e?c=d=K[e]:Array.isArray(e)&&(c=K[e[0]],d=K[e[1]])}else"wrapS"in b&&(c=K[b.wrapS]),"wrapT"in b&&(d=K[b.wrapT]);a.wrapS=c;a.wrapT=d;"anisotropic"in b&&(a.anisotropic=b.anisotropic);if("mipmap"in b){c=!1;switch(typeof b.mipmap){case "string":a.mipmapHint=ua[b.mipmap];c=a.genMipmaps=!0;break;case "boolean":c=a.genMipmaps=b.mipmap;break;case "object":a.genMipmaps=!1,c=!0}!c||"min"in b||(a.minFilter=9984)}}function R(c,d){a.texParameteri(d,
10241,c.minFilter);a.texParameteri(d,10240,c.magFilter);a.texParameteri(d,10242,c.wrapS);a.texParameteri(d,10243,c.wrapT);b.ext_texture_filter_anisotropic&&a.texParameteri(d,34046,c.anisotropic);c.genMipmaps&&(a.hint(33170,c.mipmapHint),a.generateMipmap(d))}function F(b){f.call(this);this.mipmask=0;this.internalformat=6408;this.id=ya++;this.refCount=1;this.target=b;this.texture=a.createTexture();this.unit=-1;this.bindCount=0;this.texInfo=new y;n.profile&&(this.stats={size:0})}function T(b){a.activeTexture(33984);
a.bindTexture(b.target,b.texture)}function Aa(){var b=ha[0];b?a.bindTexture(b.target,b.texture):a.bindTexture(3553,null)}function A(b){var c=b.texture,e=b.unit,h=b.target;0<=e&&(a.activeTexture(33984+e),a.bindTexture(h,null),ha[e]=null);a.deleteTexture(c);b.texture=null;b.params=null;b.pixels=null;b.refCount=0;delete X[b.id];d.textureCount--}var ua={"don't care":4352,"dont care":4352,nice:4354,fast:4353},K={repeat:10497,clamp:33071,mirror:33648},V={nearest:9728,linear:9729},Va=E({mipmap:9987,"nearest mipmap nearest":9984,
"linear mipmap nearest":9985,"nearest mipmap linear":9986,"linear mipmap linear":9987},V),wa={none:0,browser:37444},G={uint8:5121,rgba4:32819,rgb565:33635,"rgb5 a1":32820},U={alpha:6406,luminance:6409,"luminance alpha":6410,rgb:6407,rgba:6408,rgba4:32854,"rgb5 a1":32855,rgb565:36194},W={};b.ext_srgb&&(U.srgb=35904,U.srgba=35906);b.oes_texture_float&&(G.float32=G["float"]=5126);b.oes_texture_half_float&&(G.float16=G["half float"]=36193);b.webgl_depth_texture&&(E(U,{depth:6402,"depth stencil":34041}),
E(G,{uint16:5123,uint32:5125,"depth stencil":34042}));b.webgl_compressed_texture_s3tc&&E(W,{"rgb s3tc dxt1":33776,"rgba s3tc dxt1":33777,"rgba s3tc dxt3":33778,"rgba s3tc dxt5":33779});b.webgl_compressed_texture_atc&&E(W,{"rgb atc":35986,"rgba atc explicit alpha":35987,"rgba atc interpolated alpha":34798});b.webgl_compressed_texture_pvrtc&&E(W,{"rgb pvrtc 4bppv1":35840,"rgb pvrtc 2bppv1":35841,"rgba pvrtc 4bppv1":35842,"rgba pvrtc 2bppv1":35843});b.webgl_compressed_texture_etc1&&(W["rgb etc1"]=36196);
var Nb=Array.prototype.slice.call(a.getParameter(34467));Object.keys(W).forEach(function(a){var b=W[a];0<=Nb.indexOf(b)&&(U[a]=b)});var ca=Object.keys(U);c.textureFormats=ca;var J=[];Object.keys(U).forEach(function(a){J[U[a]]=a});var da=[];Object.keys(G).forEach(function(a){da[G[a]]=a});var oa=[];Object.keys(V).forEach(function(a){oa[V[a]]=a});var za=[];Object.keys(Va).forEach(function(a){za[Va[a]]=a});var ka=[];Object.keys(K).forEach(function(a){ka[K[a]]=a});var Lb=ca.reduce(function(a,b){var c=
U[b];6409===c||6406===c||6409===c||6410===c||6402===c||34041===c?a[c]=c:32855===c||0<=b.indexOf("rgba")?a[c]=6408:a[c]=6407;return a},{}),P=[],tb=[],ya=0,X={},ea=c.maxTextureUnits,ha=Array(ea).map(function(){return null});E(F.prototype,{bind:function(){this.bindCount+=1;var b=this.unit;if(0>b){for(var c=0;c<ea;++c){var e=ha[c];if(e){if(0<e.bindCount)continue;e.unit=-1}ha[c]=this;b=c;break}n.profile&&d.maxTextureUnits<b+1&&(d.maxTextureUnits=b+1);this.unit=b;a.activeTexture(33984+b);a.bindTexture(this.target,
this.texture)}return b},unbind:function(){--this.bindCount},decRef:function(){0>=--this.refCount&&A(this)}});n.profile&&(d.getTotalTextureSize=function(){var a=0;Object.keys(X).forEach(function(b){a+=X[b].stats.size});return a});return{create2D:function(b,c){function e(a,b){var c=f.texInfo;y.call(c);var d=D();"number"===typeof a?"number"===typeof b?v(d,a|0,b|0):v(d,a|0,a|0):a?(O(c,a),N(d,a)):v(d,1,1);c.genMipmaps&&(d.mipmask=(d.width<<1)-1);f.mipmask=d.mipmask;r(f,d);f.internalformat=d.internalformat;
e.width=d.width;e.height=d.height;T(f);B(d,3553);R(c,3553);Aa();ib(d);n.profile&&(f.stats.size=Ja(f.internalformat,f.type,d.width,d.height,c.genMipmaps,!1));e.format=J[f.internalformat];e.type=da[f.type];e.mag=oa[c.magFilter];e.min=za[c.minFilter];e.wrapS=ka[c.wrapS];e.wrapT=ka[c.wrapT];return e}var f=new F(3553);X[f.id]=f;d.textureCount++;e(b,c);e.subimage=function(a,b,c,d){b|=0;c|=0;d|=0;var p=h();r(p,f);p.width=0;p.height=0;C(p,a);p.width=p.width||(f.width>>d)-b;p.height=p.height||(f.height>>d)-
c;T(f);k(p,3553,b,c,d);Aa();l(p);return e};e.resize=function(b,c){var d=b|0,h=c|0||d;if(d===f.width&&h===f.height)return e;e.width=f.width=d;e.height=f.height=h;T(f);for(var p,w=f.channels,z=f.type,I=0;f.mipmask>>I;++I){var fa=d>>I,ga=h>>I;if(!fa||!ga)break;p=x.zero.allocType(z,fa*ga*w);a.texImage2D(3553,I,f.format,fa,ga,0,f.format,f.type,p);p&&x.zero.freeType(p)}Aa();n.profile&&(f.stats.size=Ja(f.internalformat,f.type,d,h,!1,!1));return e};e._reglType="texture2d";e._texture=f;n.profile&&(e.stats=
f.stats);e.destroy=function(){f.decRef()};return e},createCube:function(b,c,e,f,g,ua){function A(a,b,c,d,e,f){var H,Y=m.texInfo;y.call(Y);for(H=0;6>H;++H)p[H]=D();if("number"===typeof a||!a)for(a=a|0||1,H=0;6>H;++H)v(p[H],a,a);else if("object"===typeof a)if(b)N(p[0],a),N(p[1],b),N(p[2],c),N(p[3],d),N(p[4],e),N(p[5],f);else if(O(Y,a),q(m,a),"faces"in a)for(a=a.faces,H=0;6>H;++H)r(p[H],m),N(p[H],a[H]);else for(H=0;6>H;++H)N(p[H],a);r(m,p[0]);m.mipmask=Y.genMipmaps?(p[0].width<<1)-1:p[0].mipmask;m.internalformat=
p[0].internalformat;A.width=p[0].width;A.height=p[0].height;T(m);for(H=0;6>H;++H)B(p[H],34069+H);R(Y,34067);Aa();n.profile&&(m.stats.size=Ja(m.internalformat,m.type,A.width,A.height,Y.genMipmaps,!0));A.format=J[m.internalformat];A.type=da[m.type];A.mag=oa[Y.magFilter];A.min=za[Y.minFilter];A.wrapS=ka[Y.wrapS];A.wrapT=ka[Y.wrapT];for(H=0;6>H;++H)ib(p[H]);return A}var m=new F(34067);X[m.id]=m;d.cubeCount++;var p=Array(6);A(b,c,e,f,g,ua);A.subimage=function(a,b,c,p,d){c|=0;p|=0;d|=0;var e=h();r(e,m);
e.width=0;e.height=0;C(e,b);e.width=e.width||(m.width>>d)-c;e.height=e.height||(m.height>>d)-p;T(m);k(e,34069+a,c,p,d);Aa();l(e);return A};A.resize=function(b){b|=0;if(b!==m.width){A.width=m.width=b;A.height=m.height=b;T(m);for(var c=0;6>c;++c)for(var p=0;m.mipmask>>p;++p)a.texImage2D(34069+c,p,m.format,b>>p,b>>p,0,m.format,m.type,null);Aa();n.profile&&(m.stats.size=Ja(m.internalformat,m.type,A.width,A.height,!1,!0));return A}};A._reglType="textureCube";A._texture=m;n.profile&&(A.stats=m.stats);A.destroy=
function(){m.decRef()};return A},clear:function(){for(var b=0;b<ea;++b)a.activeTexture(33984+b),a.bindTexture(3553,null),ha[b]=null;S(X).forEach(A);d.cubeCount=0;d.textureCount=0},getTexture:function(a){return null},restore:function(){for(var b=0;b<ea;++b){var c=ha[b];c&&(c.bindCount=0,c.unit=-1,ha[b]=null)}S(X).forEach(function(b){b.texture=a.createTexture();a.bindTexture(b.target,b.texture);for(var c=0;32>c;++c)if(0!==(b.mipmask&1<<c))if(3553===b.target)a.texImage2D(3553,c,b.internalformat,b.width>>
c,b.height>>c,0,b.internalformat,b.type,null);else for(var d=0;6>d;++d)a.texImage2D(34069+d,c,b.internalformat,b.width>>c,b.height>>c,0,b.internalformat,b.type,null);R(b.texInfo,b.target)})}}}function Ob(a,b,c,e,g,d){function n(a,b,c){this.target=a;this.texture=b;this.renderbuffer=c;var d=a=0;b?(a=b.width,d=b.height):c&&(a=c.width,d=c.height);this.width=a;this.height=d}function f(a){a&&(a.texture&&a.texture._texture.decRef(),a.renderbuffer&&a.renderbuffer._renderbuffer.decRef())}function r(a,b,c){a&&
(a.texture?a.texture._texture.refCount+=1:a.renderbuffer._renderbuffer.refCount+=1)}function q(b,c){c&&(c.texture?a.framebufferTexture2D(36160,b,c.target,c.texture._texture.texture,0):a.framebufferRenderbuffer(36160,b,36161,c.renderbuffer._renderbuffer.renderbuffer))}function t(a){var b=3553,c=null,d=null,e=a;"object"===typeof a&&(e=a.data,"target"in a&&(b=a.target|0));a=e._reglType;"texture2d"===a?c=e:"textureCube"===a?c=e:"renderbuffer"===a&&(d=e,b=36161);return new n(b,c,d)}function m(a,b,c,d,
f){if(c)return a=e.create2D({width:a,height:b,format:d,type:f}),a._texture.refCount=0,new n(3553,a,null);a=g.create({width:a,height:b,format:d});a._renderbuffer.refCount=0;return new n(36161,null,a)}function C(a){return a&&(a.texture||a.renderbuffer)}function k(a,b,c){a&&(a.texture?a.texture.resize(b,c):a.renderbuffer&&a.renderbuffer.resize(b,c),a.width=b,a.height=c)}function h(){this.id=O++;R[this.id]=this;this.framebuffer=a.createFramebuffer();this.height=this.width=0;this.colorAttachments=[];this.depthStencilAttachment=
this.stencilAttachment=this.depthAttachment=null}function l(a){a.colorAttachments.forEach(f);f(a.depthAttachment);f(a.stencilAttachment);f(a.depthStencilAttachment)}function u(b){a.deleteFramebuffer(b.framebuffer);b.framebuffer=null;d.framebufferCount--;delete R[b.id]}function v(b){var d;a.bindFramebuffer(36160,b.framebuffer);var e=b.colorAttachments;for(d=0;d<e.length;++d)q(36064+d,e[d]);for(d=e.length;d<c.maxColorAttachments;++d)a.framebufferTexture2D(36160,36064+d,3553,null,0);a.framebufferTexture2D(36160,
33306,3553,null,0);a.framebufferTexture2D(36160,36096,3553,null,0);a.framebufferTexture2D(36160,36128,3553,null,0);q(36096,b.depthAttachment);q(36128,b.stencilAttachment);q(33306,b.depthStencilAttachment);a.checkFramebufferStatus(36160);a.isContextLost();a.bindFramebuffer(36160,B.next?B.next.framebuffer:null);B.cur=B.next;a.getError()}function N(a,b){function c(a,b){var d,f=0,h=0,g=!0,k=!0;d=null;var q=!0,u="rgba",n="uint8",N=1,da=null,oa=null,B=null,ka=!1;if("number"===typeof a)f=a|0,h=b|0||f;else if(a){"shape"in
a?(h=a.shape,f=h[0],h=h[1]):("radius"in a&&(f=h=a.radius),"width"in a&&(f=a.width),"height"in a&&(h=a.height));if("color"in a||"colors"in a)d=a.color||a.colors,Array.isArray(d);if(!d){"colorCount"in a&&(N=a.colorCount|0);"colorTexture"in a&&(q=!!a.colorTexture,u="rgba4");if("colorType"in a&&(n=a.colorType,!q))if("half float"===n||"float16"===n)u="rgba16f";else if("float"===n||"float32"===n)u="rgba32f";"colorFormat"in a&&(u=a.colorFormat,0<=x.indexOf(u)?q=!0:0<=D.indexOf(u)&&(q=!1))}if("depthTexture"in
a||"depthStencilTexture"in a)ka=!(!a.depthTexture&&!a.depthStencilTexture);"depth"in a&&("boolean"===typeof a.depth?g=a.depth:(da=a.depth,k=!1));"stencil"in a&&("boolean"===typeof a.stencil?k=a.stencil:(oa=a.stencil,g=!1));"depthStencil"in a&&("boolean"===typeof a.depthStencil?g=k=a.depthStencil:(B=a.depthStencil,k=g=!1))}else f=h=1;var F=null,y=null,E=null,T=null;if(Array.isArray(d))F=d.map(t);else if(d)F=[t(d)];else for(F=Array(N),d=0;d<N;++d)F[d]=m(f,h,q,u,n);f=f||F[0].width;h=h||F[0].height;da?
y=t(da):g&&!k&&(y=m(f,h,ka,"depth","uint32"));oa?E=t(oa):k&&!g&&(E=m(f,h,!1,"stencil","uint8"));B?T=t(B):!da&&!oa&&k&&g&&(T=m(f,h,ka,"depth stencil","depth stencil"));g=null;for(d=0;d<F.length;++d)r(F[d],f,h),F[d]&&F[d].texture&&(k=Wa[F[d].texture._texture.format]*Na[F[d].texture._texture.type],null===g&&(g=k));r(y,f,h);r(E,f,h);r(T,f,h);l(e);e.width=f;e.height=h;e.colorAttachments=F;e.depthAttachment=y;e.stencilAttachment=E;e.depthStencilAttachment=T;c.color=F.map(C);c.depth=C(y);c.stencil=C(E);
c.depthStencil=C(T);c.width=e.width;c.height=e.height;v(e);return c}var e=new h;d.framebufferCount++;c(a,b);return E(c,{resize:function(a,b){var d=Math.max(a|0,1),f=Math.max(b|0||d,1);if(d===e.width&&f===e.height)return c;for(var h=e.colorAttachments,g=0;g<h.length;++g)k(h[g],d,f);k(e.depthAttachment,d,f);k(e.stencilAttachment,d,f);k(e.depthStencilAttachment,d,f);e.width=c.width=d;e.height=c.height=f;v(e);return c},_reglType:"framebuffer",_framebuffer:e,destroy:function(){u(e);l(e)},use:function(a){B.setFBO({framebuffer:c},
a)}})}var B={cur:null,next:null,dirty:!1,setFBO:null},x=["rgba"],D=["rgba4","rgb565","rgb5 a1"];b.ext_srgb&&D.push("srgba");b.ext_color_buffer_half_float&&D.push("rgba16f","rgb16f");b.webgl_color_buffer_float&&D.push("rgba32f");var y=["uint8"];b.oes_texture_half_float&&y.push("half float","float16");b.oes_texture_float&&y.push("float","float32");var O=0,R={};return E(B,{getFramebuffer:function(a){return"function"===typeof a&&"framebuffer"===a._reglType&&(a=a._framebuffer,a instanceof h)?a:null},create:N,
createCube:function(a){function b(a){var d,f={color:null},h=0,g=null;d="rgba";var l="uint8",m=1;if("number"===typeof a)h=a|0;else if(a){"shape"in a?h=a.shape[0]:("radius"in a&&(h=a.radius|0),"width"in a?h=a.width|0:"height"in a&&(h=a.height|0));if("color"in a||"colors"in a)g=a.color||a.colors,Array.isArray(g);g||("colorCount"in a&&(m=a.colorCount|0),"colorType"in a&&(l=a.colorType),"colorFormat"in a&&(d=a.colorFormat));"depth"in a&&(f.depth=a.depth);"stencil"in a&&(f.stencil=a.stencil);"depthStencil"in
a&&(f.depthStencil=a.depthStencil)}else h=1;if(g)if(Array.isArray(g))for(a=[],d=0;d<g.length;++d)a[d]=g[d];else a=[g];else for(a=Array(m),g={radius:h,format:d,type:l},d=0;d<m;++d)a[d]=e.createCube(g);f.color=Array(a.length);for(d=0;d<a.length;++d)m=a[d],h=h||m.width,f.color[d]={target:34069,data:a[d]};for(d=0;6>d;++d){for(m=0;m<a.length;++m)f.color[m].target=34069+d;0<d&&(f.depth=c[0].depth,f.stencil=c[0].stencil,f.depthStencil=c[0].depthStencil);if(c[d])c[d](f);else c[d]=N(f)}return E(b,{width:h,
height:h,color:a})}var c=Array(6);b(a);return E(b,{faces:c,resize:function(a){var d=a|0;if(d===b.width)return b;var e=b.color;for(a=0;a<e.length;++a)e[a].resize(d);for(a=0;6>a;++a)c[a].resize(d);b.width=b.height=d;return b},_reglType:"framebufferCube",destroy:function(){c.forEach(function(a){a.destroy()})}})},clear:function(){S(R).forEach(u)},restore:function(){B.cur=null;B.next=null;B.dirty=!0;S(R).forEach(function(b){b.framebuffer=a.createFramebuffer();v(b)})}})}function ub(){this.w=this.z=this.y=
this.x=this.state=0;this.buffer=null;this.size=0;this.normalized=!1;this.type=5126;this.divisor=this.stride=this.offset=0}function Pb(a,b,c,e){a=c.maxAttributes;b=Array(a);for(c=0;c<a;++c)b[c]=new ub;return{Record:ub,scope:{},state:b}}function Qb(a,b,c,e){function g(a,b,c,d){this.name=a;this.id=b;this.location=c;this.info=d}function d(a,b){for(var c=0;c<a.length;++c)if(a[c].id===b.id){a[c].location=b.location;return}a.push(b)}function n(c,d,e){e=35632===c?q:t;var f=e[d];if(!f){var g=b.str(d),f=a.createShader(c);
a.shaderSource(f,g);a.compileShader(f);e[d]=f}return f}function f(a,b){this.id=k++;this.fragId=a;this.vertId=b;this.program=null;this.uniforms=[];this.attributes=[];e.profile&&(this.stats={uniformsCount:0,attributesCount:0})}function r(c,f){var m,k;m=n(35632,c.fragId);k=n(35633,c.vertId);var q=c.program=a.createProgram();a.attachShader(q,m);a.attachShader(q,k);a.linkProgram(q);var r=a.getProgramParameter(q,35718);e.profile&&(c.stats.uniformsCount=r);var t=c.uniforms;for(m=0;m<r;++m)if(k=a.getActiveUniform(q,
m))if(1<k.size)for(var C=0;C<k.size;++C){var y=k.name.replace("[0]","["+C+"]");d(t,new g(y,b.id(y),a.getUniformLocation(q,y),k))}else d(t,new g(k.name,b.id(k.name),a.getUniformLocation(q,k.name),k));r=a.getProgramParameter(q,35721);e.profile&&(c.stats.attributesCount=r);t=c.attributes;for(m=0;m<r;++m)(k=a.getActiveAttrib(q,m))&&d(t,new g(k.name,b.id(k.name),a.getAttribLocation(q,k.name),k))}var q={},t={},m={},C=[],k=0;e.profile&&(c.getMaxUniformsCount=function(){var a=0;C.forEach(function(b){b.stats.uniformsCount>
a&&(a=b.stats.uniformsCount)});return a},c.getMaxAttributesCount=function(){var a=0;C.forEach(function(b){b.stats.attributesCount>a&&(a=b.stats.attributesCount)});return a});return{clear:function(){var b=a.deleteShader.bind(a);S(q).forEach(b);q={};S(t).forEach(b);t={};C.forEach(function(b){a.deleteProgram(b.program)});C.length=0;m={};c.shaderCount=0},program:function(a,b,d){var e=m[b];e||(e=m[b]={});var g=e[a];g||(g=new f(b,a),c.shaderCount++,r(g,d),e[a]=g,C.push(g));return g},restore:function(){q=
{};t={};for(var a=0;a<C.length;++a)r(C[a])},shader:n,frag:-1,vert:-1}}function Rb(a,b,c,e,g,d,n){function f(d){var f;f=null===b.next?5121:b.next.colorAttachments[0].texture._texture.type;var g=0,r=0,k=e.framebufferWidth,h=e.framebufferHeight,l=null;M(d)?l=d:d&&(g=d.x|0,r=d.y|0,k=(d.width||e.framebufferWidth-g)|0,h=(d.height||e.framebufferHeight-r)|0,l=d.data||null);c();d=k*h*4;l||(5121===f?l=new Uint8Array(d):5126===f&&(l=l||new Float32Array(d)));a.pixelStorei(3333,4);a.readPixels(g,r,k,h,6408,f,
l);return l}function r(a){var c;b.setFBO({framebuffer:a.framebuffer},function(){c=f(a)});return c}return function(a){return a&&"framebuffer"in a?r(a):f(a)}}function Ba(a){return Array.prototype.slice.call(a)}function Ca(a){return Ba(a).join("")}function Sb(){function a(){var a=[],b=[];return E(function(){a.push.apply(a,Ba(arguments))},{def:function(){var d="v"+c++;b.push(d);0<arguments.length&&(a.push(d,"="),a.push.apply(a,Ba(arguments)),a.push(";"));return d},toString:function(){return Ca([0<b.length?
"var "+b+";":"",Ca(a)])}})}function b(){function b(a,e){d(a,e,"=",c.def(a,e),";")}var c=a(),d=a(),e=c.toString,g=d.toString;return E(function(){c.apply(c,Ba(arguments))},{def:c.def,entry:c,exit:d,save:b,set:function(a,d,e){b(a,d);c(a,d,"=",e,";")},toString:function(){return e()+g()}})}var c=0,e=[],g=[],d=a(),n={};return{global:d,link:function(a){for(var b=0;b<g.length;++b)if(g[b]===a)return e[b];b="g"+c++;e.push(b);g.push(a);return b},block:a,proc:function(a,c){function d(){var a="a"+e.length;e.push(a);
return a}var e=[];c=c||0;for(var g=0;g<c;++g)d();var g=b(),C=g.toString;return n[a]=E(g,{arg:d,toString:function(){return Ca(["function(",e.join(),"){",C(),"}"])}})},scope:b,cond:function(){var a=Ca(arguments),c=b(),d=b(),e=c.toString,g=d.toString;return E(c,{then:function(){c.apply(c,Ba(arguments));return this},"else":function(){d.apply(d,Ba(arguments));return this},toString:function(){var b=g();b&&(b="else{"+b+"}");return Ca(["if(",a,"){",e(),"}",b])}})},compile:function(){var a=['"use strict";',
d,"return {"];Object.keys(n).forEach(function(b){a.push('"',b,'":',n[b].toString(),",")});a.push("}");var b=Ca(a).replace(/;/g,";\n").replace(/}/g,"}\n").replace(/{/g,"{\n");return Function.apply(null,e.concat(b)).apply(null,g)}}}function Oa(a){return Array.isArray(a)||M(a)||ma(a)}function vb(a){return a.sort(function(a,c){return"viewport"===a?-1:"viewport"===c?1:a<c?-1:1})}function Z(a,b,c,e){this.thisDep=a;this.contextDep=b;this.propDep=c;this.append=e}function va(a){return a&&!(a.thisDep||a.contextDep||
a.propDep)}function D(a){return new Z(!1,!1,!1,a)}function P(a,b){var c=a.type;return 0===c?(c=a.data.length,new Z(!0,1<=c,2<=c,b)):4===c?(c=a.data,new Z(c.thisDep,c.contextDep,c.propDep,b)):new Z(3===c,2===c,1===c,b)}function Tb(a,b,c,e,g,d,n,f,r,q,t,m,C,k,h){function l(a){return a.replace(".","_")}function u(a,b,c){var d=l(a);Ka.push(a);Fa[d]=ra[d]=!!c;sa[d]=b}function v(a,b,c){var d=l(a);Ka.push(a);Array.isArray(c)?(ra[d]=c.slice(),Fa[d]=c.slice()):ra[d]=Fa[d]=c;ta[d]=b}function N(){var a=Sb(),
c=a.link,d=a.global;a.id=qa++;a.batchId="0";var e=c(na),f=a.shared={props:"a0"};Object.keys(na).forEach(function(a){f[a]=d.def(e,".",a)});var g=a.next={},xa=a.current={};Object.keys(ta).forEach(function(a){Array.isArray(ra[a])&&(g[a]=d.def(f.next,".",a),xa[a]=d.def(f.current,".",a))});var H=a.constants={};Object.keys(aa).forEach(function(a){H[a]=d.def(JSON.stringify(aa[a]))});a.invoke=function(b,d){switch(d.type){case 0:var e=["this",f.context,f.props,a.batchId];return b.def(c(d.data),".call(",e.slice(0,
Math.max(d.data.length+1,4)),")");case 1:return b.def(f.props,d.data);case 2:return b.def(f.context,d.data);case 3:return b.def("this",d.data);case 4:return d.data.append(a,b),d.data.ref}};a.attribCache={};var Y={};a.scopeAttrib=function(a){a=b.id(a);if(a in Y)return Y[a];var d=q.scope[a];d||(d=q.scope[a]=new ya);return Y[a]=c(d)};return a}function B(a){var b=a["static"];a=a.dynamic;var c;if("profile"in b){var d=!!b.profile;c=D(function(a,b){return d});c.enable=d}else if("profile"in a){var e=a.profile;
c=P(e,function(a,b){return a.invoke(b,e)})}return c}function y(a,b){var c=a["static"],d=a.dynamic;if("framebuffer"in c){var e=c.framebuffer;return e?(e=f.getFramebuffer(e),D(function(a,b){var c=a.link(e),d=a.shared;b.set(d.framebuffer,".next",c);d=d.context;b.set(d,".framebufferWidth",c+".width");b.set(d,".framebufferHeight",c+".height");return c})):D(function(a,b){var c=a.shared;b.set(c.framebuffer,".next","null");c=c.context;b.set(c,".framebufferWidth",c+".drawingBufferWidth");b.set(c,".framebufferHeight",
c+".drawingBufferHeight");return"null"})}if("framebuffer"in d){var g=d.framebuffer;return P(g,function(a,b){var c=a.invoke(b,g),d=a.shared,e=d.framebuffer,c=b.def(e,".getFramebuffer(",c,")");b.set(e,".next",c);d=d.context;b.set(d,".framebufferWidth",c+"?"+c+".width:"+d+".drawingBufferWidth");b.set(d,".framebufferHeight",c+"?"+c+".height:"+d+".drawingBufferHeight");return c})}return null}function x(a,b,c){function d(a){if(a in e){var c=e[a];a=!0;var p=c.x|0,ba=c.y|0,g,h;"width"in c?g=c.width|0:a=!1;
"height"in c?h=c.height|0:a=!1;return new Z(!a&&b&&b.thisDep,!a&&b&&b.contextDep,!a&&b&&b.propDep,function(a,b){var d=a.shared.context,e=g;"width"in c||(e=b.def(d,".","framebufferWidth","-",p));var f=h;"height"in c||(f=b.def(d,".","framebufferHeight","-",ba));return[p,ba,e,f]})}if(a in f){var z=f[a];a=P(z,function(a,b){var c=a.invoke(b,z),d=a.shared.context,e=b.def(c,".x|0"),p=b.def(c,".y|0"),Y=b.def('"width" in ',c,"?",c,".width|0:","(",d,".","framebufferWidth","-",e,")"),c=b.def('"height" in ',
c,"?",c,".height|0:","(",d,".","framebufferHeight","-",p,")");return[e,p,Y,c]});b&&(a.thisDep=a.thisDep||b.thisDep,a.contextDep=a.contextDep||b.contextDep,a.propDep=a.propDep||b.propDep);return a}return b?new Z(b.thisDep,b.contextDep,b.propDep,function(a,b){var c=a.shared.context;return[0,0,b.def(c,".","framebufferWidth"),b.def(c,".","framebufferHeight")]}):null}var e=a["static"],f=a.dynamic;if(a=d("viewport")){var g=a;a=new Z(a.thisDep,a.contextDep,a.propDep,function(a,b){var c=g.append(a,b),d=a.shared.context;
b.set(d,".viewportWidth",c[2]);b.set(d,".viewportHeight",c[3]);return c})}return{viewport:a,scissor_box:d("scissor.box")}}function E(a){function c(a){if(a in d){var p=b.id(d[a]);a=D(function(){return p});a.id=p;return a}if(a in e){var f=e[a];return P(f,function(a,b){var c=a.invoke(b,f);return b.def(a.shared.strings,".id(",c,")")})}return null}var d=a["static"],e=a.dynamic,f=c("frag"),g=c("vert"),h=null;va(f)&&va(g)?(h=t.program(g.id,f.id),a=D(function(a,b){return a.link(h)})):a=new Z(f&&f.thisDep||
g&&g.thisDep,f&&f.contextDep||g&&g.contextDep,f&&f.propDep||g&&g.propDep,function(a,b){var c=a.shared.shader,d;d=f?f.append(a,b):b.def(c,".","frag");var e;e=g?g.append(a,b):b.def(c,".","vert");return b.def(c+".program("+e+","+d+")")});return{frag:f,vert:g,progVar:a,program:h}}function O(a,b){function c(a,b){if(a in e){var d=e[a]|0;return D(function(a,c){b&&(a.OFFSET=d);return d})}if(a in f){var p=f[a];return P(p,function(a,c){var d=a.invoke(c,p);b&&(a.OFFSET=d);return d})}return b&&g?D(function(a,
b){a.OFFSET="0";return 0}):null}var e=a["static"],f=a.dynamic,g=function(){if("elements"in e){var a=e.elements;Oa(a)?a=d.getElements(d.create(a,!0)):a&&(a=d.getElements(a));var b=D(function(b,c){if(a){var d=b.link(a);return b.ELEMENTS=d}return b.ELEMENTS=null});b.value=a;return b}if("elements"in f){var c=f.elements;return P(c,function(a,b){var d=a.shared,e=d.isBufferArgs,d=d.elements,p=a.invoke(b,c),f=b.def("null"),e=b.def(e,"(",p,")"),p=a.cond(e).then(f,"=",d,".createStream(",p,");")["else"](f,"=",
d,".getElements(",p,");");b.entry(p);b.exit(a.cond(e).then(d,".destroyStream(",f,");"));return a.ELEMENTS=f})}return null}(),h=c("offset",!0);return{elements:g,primitive:function(){if("primitive"in e){var a=e.primitive;return D(function(b,c){return Sa[a]})}if("primitive"in f){var b=f.primitive;return P(b,function(a,c){var d=a.constants.primTypes,e=a.invoke(c,b);return c.def(d,"[",e,"]")})}return g?va(g)?g.value?D(function(a,b){return b.def(a.ELEMENTS,".primType")}):D(function(){return 4}):new Z(g.thisDep,
g.contextDep,g.propDep,function(a,b){var c=a.ELEMENTS;return b.def(c,"?",c,".primType:",4)}):null}(),count:function(){if("count"in e){var a=e.count|0;return D(function(){return a})}if("count"in f){var b=f.count;return P(b,function(a,c){return a.invoke(c,b)})}return g?va(g)?g?h?new Z(h.thisDep,h.contextDep,h.propDep,function(a,b){return b.def(a.ELEMENTS,".vertCount-",a.OFFSET)}):D(function(a,b){return b.def(a.ELEMENTS,".vertCount")}):D(function(){return-1}):new Z(g.thisDep||h.thisDep,g.contextDep||
h.contextDep,g.propDep||h.propDep,function(a,b){var c=a.ELEMENTS;return a.OFFSET?b.def(c,"?",c,".vertCount-",a.OFFSET,":-1"):b.def(c,"?",c,".vertCount:-1")}):null}(),instances:c("instances",!1),offset:h}}function R(a,b){var c=a["static"],d=a.dynamic,e={};Ka.forEach(function(a){function b(f,g){if(a in c){var w=f(c[a]);e[p]=D(function(){return w})}else if(a in d){var h=d[a];e[p]=P(h,function(a,b){return g(a,b,a.invoke(b,h))})}}var p=l(a);switch(a){case "cull.enable":case "blend.enable":case "dither":case "stencil.enable":case "depth.enable":case "scissor.enable":case "polygonOffset.enable":case "sample.alpha":case "sample.enable":case "depth.mask":return b(function(a){return a},
function(a,b,c){return c});case "depth.func":return b(function(a){return Xa[a]},function(a,b,c){return b.def(a.constants.compareFuncs,"[",c,"]")});case "depth.range":return b(function(a){return a},function(a,b,c){a=b.def("+",c,"[0]");b=b.def("+",c,"[1]");return[a,b]});case "blend.func":return b(function(a){return[Ga["srcRGB"in a?a.srcRGB:a.src],Ga["dstRGB"in a?a.dstRGB:a.dst],Ga["srcAlpha"in a?a.srcAlpha:a.src],Ga["dstAlpha"in a?a.dstAlpha:a.dst]]},function(a,b,c){function d(a,e){return b.def('"',
a,e,'" in ',c,"?",c,".",a,e,":",c,".",a)}a=a.constants.blendFuncs;var e=d("src","RGB"),p=d("dst","RGB"),e=b.def(a,"[",e,"]"),f=b.def(a,"[",d("src","Alpha"),"]"),p=b.def(a,"[",p,"]");a=b.def(a,"[",d("dst","Alpha"),"]");return[e,p,f,a]});case "blend.equation":return b(function(a){if("string"===typeof a)return[X[a],X[a]];if("object"===typeof a)return[X[a.rgb],X[a.alpha]]},function(a,b,c){var d=a.constants.blendEquations,e=b.def(),p=b.def();a=a.cond("typeof ",c,'==="string"');a.then(e,"=",p,"=",d,"[",
c,"];");a["else"](e,"=",d,"[",c,".rgb];",p,"=",d,"[",c,".alpha];");b(a);return[e,p]});case "blend.color":return b(function(a){return J(4,function(b){return+a[b]})},function(a,b,c){return J(4,function(a){return b.def("+",c,"[",a,"]")})});case "stencil.mask":return b(function(a){return a|0},function(a,b,c){return b.def(c,"|0")});case "stencil.func":return b(function(a){return[Xa[a.cmp||"keep"],a.ref||0,"mask"in a?a.mask:-1]},function(a,b,c){a=b.def('"cmp" in ',c,"?",a.constants.compareFuncs,"[",c,".cmp]",
":",7680);var d=b.def(c,".ref|0");b=b.def('"mask" in ',c,"?",c,".mask|0:-1");return[a,d,b]});case "stencil.opFront":case "stencil.opBack":return b(function(b){return["stencil.opBack"===a?1029:1028,Pa[b.fail||"keep"],Pa[b.zfail||"keep"],Pa[b.zpass||"keep"]]},function(b,c,d){function e(a){return c.def('"',a,'" in ',d,"?",p,"[",d,".",a,"]:",7680)}var p=b.constants.stencilOps;return["stencil.opBack"===a?1029:1028,e("fail"),e("zfail"),e("zpass")]});case "polygonOffset.offset":return b(function(a){return[a.factor|
0,a.units|0]},function(a,b,c){a=b.def(c,".factor|0");b=b.def(c,".units|0");return[a,b]});case "cull.face":return b(function(a){var b=0;"front"===a?b=1028:"back"===a&&(b=1029);return b},function(a,b,c){return b.def(c,'==="front"?',1028,":",1029)});case "lineWidth":return b(function(a){return a},function(a,b,c){return c});case "frontFace":return b(function(a){return wb[a]},function(a,b,c){return b.def(c+'==="cw"?2304:2305')});case "colorMask":return b(function(a){return a.map(function(a){return!!a})},
function(a,b,c){return J(4,function(a){return"!!"+c+"["+a+"]"})});case "sample.coverage":return b(function(a){return["value"in a?a.value:1,!!a.invert]},function(a,b,c){a=b.def('"value" in ',c,"?+",c,".value:1");b=b.def("!!",c,".invert");return[a,b]})}});return e}function F(a,b){var c=a["static"],d=a.dynamic,e={};Object.keys(c).forEach(function(a){var b=c[a],d;if("number"===typeof b||"boolean"===typeof b)d=D(function(){return b});else if("function"===typeof b){var p=b._reglType;if("texture2d"===p||
"textureCube"===p)d=D(function(a){return a.link(b)});else if("framebuffer"===p||"framebufferCube"===p)d=D(function(a){return a.link(b.color[0])})}else pa(b)&&(d=D(function(a){return a.global.def("[",J(b.length,function(a){return b[a]}),"]")}));d.value=b;e[a]=d});Object.keys(d).forEach(function(a){var b=d[a];e[a]=P(b,function(a,c){return a.invoke(c,b)})});return e}function T(a,c){var d=a["static"],e=a.dynamic,f={};Object.keys(d).forEach(function(a){var c=d[a],e=b.id(a),p=new ya;if(Oa(c))p.state=1,
p.buffer=g.getBuffer(g.create(c,34962,!1,!0)),p.type=0;else{var w=g.getBuffer(c);if(w)p.state=1,p.buffer=w,p.type=0;else if("constant"in c){var h=c.constant;p.buffer="null";p.state=2;"number"===typeof h?p.x=h:Da.forEach(function(a,b){b<h.length&&(p[a]=h[b])})}else{var w=Oa(c.buffer)?g.getBuffer(g.create(c.buffer,34962,!1,!0)):g.getBuffer(c.buffer),k=c.offset|0,m=c.stride|0,I=c.size|0,l=!!c.normalized,n=0;"type"in c&&(n=Ra[c.type]);c=c.divisor|0;p.buffer=w;p.state=1;p.size=I;p.normalized=l;p.type=
n||w.dtype;p.offset=k;p.stride=m;p.divisor=c}}f[a]=D(function(a,b){var c=a.attribCache;if(e in c)return c[e];var d={isStream:!1};Object.keys(p).forEach(function(a){d[a]=p[a]});p.buffer&&(d.buffer=a.link(p.buffer),d.type=d.type||d.buffer+".dtype");return c[e]=d})});Object.keys(e).forEach(function(a){var b=e[a];f[a]=P(b,function(a,c){function d(a){c(w[a],"=",e,".",a,"|0;")}var e=a.invoke(c,b),p=a.shared,f=p.isBufferArgs,g=p.buffer,w={isStream:c.def(!1)},h=new ya;h.state=1;Object.keys(h).forEach(function(a){w[a]=
c.def(""+h[a])});var z=w.buffer,k=w.type;c("if(",f,"(",e,")){",w.isStream,"=true;",z,"=",g,".createStream(",34962,",",e,");",k,"=",z,".dtype;","}else{",z,"=",g,".getBuffer(",e,");","if(",z,"){",k,"=",z,".dtype;",'}else if("constant" in ',e,"){",w.state,"=",2,";","if(typeof "+e+'.constant === "number"){',w[Da[0]],"=",e,".constant;",Da.slice(1).map(function(a){return w[a]}).join("="),"=0;","}else{",Da.map(function(a,b){return w[a]+"="+e+".constant.length>"+b+"?"+e+".constant["+b+"]:0;"}).join(""),"}}else{",
"if(",f,"(",e,".buffer)){",z,"=",g,".createStream(",34962,",",e,".buffer);","}else{",z,"=",g,".getBuffer(",e,".buffer);","}",k,'="type" in ',e,"?",p.glTypes,"[",e,".type]:",z,".dtype;",w.normalized,"=!!",e,".normalized;");d("size");d("offset");d("stride");d("divisor");c("}}");c.exit("if(",w.isStream,"){",g,".destroyStream(",z,");","}");return w})});return f}function M(a){var b=a["static"],c=a.dynamic,d={};Object.keys(b).forEach(function(a){var c=b[a];d[a]=D(function(a,b){return"number"===typeof c||
"boolean"===typeof c?""+c:a.link(c)})});Object.keys(c).forEach(function(a){var b=c[a];d[a]=P(b,function(a,c){return a.invoke(c,b)})});return d}function A(a,b,c,d,e){var f=y(a,e),g=x(a,f,e),h=O(a,e),k=R(a,e),m=E(a,e),ba=g.viewport;ba&&(k.viewport=ba);ba=l("scissor.box");(g=g[ba])&&(k[ba]=g);g=0<Object.keys(k).length;f={framebuffer:f,draw:h,shader:m,state:k,dirty:g};f.profile=B(a,e);f.uniforms=F(c,e);f.attributes=T(b,e);f.context=M(d,e);return f}function ua(a,b,c){var d=a.shared.context,e=a.scope();
Object.keys(c).forEach(function(f){b.save(d,"."+f);e(d,".",f,"=",c[f].append(a,b),";")});b(e)}function K(a,b,c,d){var e=a.shared,f=e.gl,g=e.framebuffer,h;ha&&(h=b.def(e.extensions,".webgl_draw_buffers"));var k=a.constants,e=k.drawBuffer,k=k.backBuffer;a=c?c.append(a,b):b.def(g,".next");d||b("if(",a,"!==",g,".cur){");b("if(",a,"){",f,".bindFramebuffer(",36160,",",a,".framebuffer);");ha&&b(h,".drawBuffersWEBGL(",e,"[",a,".colorAttachments.length]);");b("}else{",f,".bindFramebuffer(",36160,",null);");
ha&&b(h,".drawBuffersWEBGL(",k,");");b("}",g,".cur=",a,";");d||b("}")}function V(a,b,c){var d=a.shared,e=d.gl,f=a.current,g=a.next,h=d.current,k=d.next,m=a.cond(h,".dirty");Ka.forEach(function(b){b=l(b);if(!(b in c.state)){var d,w;if(b in g){d=g[b];w=f[b];var I=J(ra[b].length,function(a){return m.def(d,"[",a,"]")});m(a.cond(I.map(function(a,b){return a+"!=="+w+"["+b+"]"}).join("||")).then(e,".",ta[b],"(",I,");",I.map(function(a,b){return w+"["+b+"]="+a}).join(";"),";"))}else d=m.def(k,".",b),I=a.cond(d,
"!==",h,".",b),m(I),b in sa?I(a.cond(d).then(e,".enable(",sa[b],");")["else"](e,".disable(",sa[b],");"),h,".",b,"=",d,";"):I(e,".",ta[b],"(",d,");",h,".",b,"=",d,";")}});0===Object.keys(c.state).length&&m(h,".dirty=false;");b(m)}function Q(a,b,c,d){var e=a.shared,f=a.current,g=e.current,h=e.gl;vb(Object.keys(c)).forEach(function(e){var k=c[e];if(!d||d(k)){var m=k.append(a,b);if(sa[e]){var l=sa[e];va(k)?m?b(h,".enable(",l,");"):b(h,".disable(",l,");"):b(a.cond(m).then(h,".enable(",l,");")["else"](h,
".disable(",l,");"));b(g,".",e,"=",m,";")}else if(pa(m)){var n=f[e];b(h,".",ta[e],"(",m,");",m.map(function(a,b){return n+"["+b+"]="+a}).join(";"),";")}else b(h,".",ta[e],"(",m,");",g,".",e,"=",m,";")}})}function wa(a,b){ea&&(a.instancing=b.def(a.shared.extensions,".angle_instanced_arrays"))}function G(a,b,c,d,e){function f(){return"undefined"===typeof performance?"Date.now()":"performance.now()"}function g(a){t=b.def();a(t,"=",f(),";");"string"===typeof e?a(ba,".count+=",e,";"):a(ba,".count++;");
k&&(d?(r=b.def(),a(r,"=",q,".getNumPendingQueries();")):a(q,".beginQuery(",ba,");"))}function h(a){a(ba,".cpuTime+=",f(),"-",t,";");k&&(d?a(q,".pushScopeStats(",r,",",q,".getNumPendingQueries(),",ba,");"):a(q,".endQuery();"))}function m(a){var c=b.def(n,".profile");b(n,".profile=",a,";");b.exit(n,".profile=",c,";")}var l=a.shared,ba=a.stats,n=l.current,q=l.timer;c=c.profile;var t,r;if(c){if(va(c)){c.enable?(g(b),h(b.exit),m("true")):m("false");return}c=c.append(a,b);m(c)}else c=b.def(n,".profile");
l=a.block();g(l);b("if(",c,"){",l,"}");a=a.block();h(a);b.exit("if(",c,"){",a,"}")}function U(a,b,c,d,e){function f(a){switch(a){case 35664:case 35667:case 35671:return 2;case 35665:case 35668:case 35672:return 3;case 35666:case 35669:case 35673:return 4;default:return 1}}function g(c,d,e){function f(){b("if(!",z,".buffer){",k,".enableVertexAttribArray(",l,");}");var c=e.type,g;g=e.size?b.def(e.size,"||",d):d;b("if(",z,".type!==",c,"||",z,".size!==",g,"||",q.map(function(a){return z+"."+a+"!=="+e[a]}).join("||"),
"){",k,".bindBuffer(",34962,",",I,".buffer);",k,".vertexAttribPointer(",[l,g,c,e.normalized,e.stride,e.offset],");",z,".type=",c,";",z,".size=",g,";",q.map(function(a){return z+"."+a+"="+e[a]+";"}).join(""),"}");ea&&(c=e.divisor,b("if(",z,".divisor!==",c,"){",a.instancing,".vertexAttribDivisorANGLE(",[l,c],");",z,".divisor=",c,";}"))}function m(){b("if(",z,".buffer){",k,".disableVertexAttribArray(",l,");","}if(",Da.map(function(a,b){return z+"."+a+"!=="+n[b]}).join("||"),"){",k,".vertexAttrib4f(",
l,",",n,");",Da.map(function(a,b){return z+"."+a+"="+n[b]+";"}).join(""),"}")}var k=h.gl,l=b.def(c,".location"),z=b.def(h.attributes,"[",l,"]");c=e.state;var I=e.buffer,n=[e.x,e.y,e.z,e.w],q=["buffer","normalized","offset","stride"];1===c?f():2===c?m():(b("if(",c,"===",1,"){"),f(),b("}else{"),m(),b("}"))}var h=a.shared;d.forEach(function(d){var h=d.name,k=c.attributes[h],m;if(k){if(!e(k))return;m=k.append(a,b)}else{if(!e(xb))return;var l=a.scopeAttrib(h);m={};Object.keys(new ya).forEach(function(a){m[a]=
b.def(l,".",a)})}g(a.link(d),f(d.info.type),m)})}function W(a,c,d,e,f){for(var g=a.shared,h=g.gl,k,m=0;m<e.length;++m){var l=e[m],n=l.name,q=l.info.type,t=d.uniforms[n],l=a.link(l)+".location",r;if(t){if(!f(t))continue;if(va(t)){n=t.value;if(35678===q||35680===q)q=a.link(n._texture||n.color[0]._texture),c(h,".uniform1i(",l,",",q+".bind());"),c.exit(q,".unbind();");else if(35674===q||35675===q||35676===q)n=a.global.def("new Float32Array(["+Array.prototype.slice.call(n)+"])"),t=2,35675===q?t=3:35676===
q&&(t=4),c(h,".uniformMatrix",t,"fv(",l,",false,",n,");");else{switch(q){case 5126:k="1f";break;case 35664:k="2f";break;case 35665:k="3f";break;case 35666:k="4f";break;case 35670:k="1i";break;case 5124:k="1i";break;case 35671:k="2i";break;case 35667:k="2i";break;case 35672:k="3i";break;case 35668:k="3i";break;case 35673:k="4i";break;case 35669:k="4i"}c(h,".uniform",k,"(",l,",",pa(n)?Array.prototype.slice.call(n):n,");")}continue}else r=t.append(a,c)}else{if(!f(xb))continue;r=c.def(g.uniforms,"[",
b.id(n),"]")}35678===q?c("if(",r,"&&",r,'._reglType==="framebuffer"){',r,"=",r,".color[0];","}"):35680===q&&c("if(",r,"&&",r,'._reglType==="framebufferCube"){',r,"=",r,".color[0];","}");n=1;switch(q){case 35678:case 35680:q=c.def(r,"._texture");c(h,".uniform1i(",l,",",q,".bind());");c.exit(q,".unbind();");continue;case 5124:case 35670:k="1i";break;case 35667:case 35671:k="2i";n=2;break;case 35668:case 35672:k="3i";n=3;break;case 35669:case 35673:k="4i";n=4;break;case 5126:k="1f";break;case 35664:k=
"2f";n=2;break;case 35665:k="3f";n=3;break;case 35666:k="4f";n=4;break;case 35674:k="Matrix2fv";break;case 35675:k="Matrix3fv";break;case 35676:k="Matrix4fv"}c(h,".uniform",k,"(",l,",");if("M"===k.charAt(0)){var l=Math.pow(q-35674+2,2),v=a.global.def("new Float32Array(",l,")");c("false,(Array.isArray(",r,")||",r," instanceof Float32Array)?",r,":(",J(l,function(a){return v+"["+a+"]="+r+"["+a+"]"}),",",v,")")}else 1<n?c(J(n,function(a){return r+"["+a+"]"})):c(r);c(");")}}function S(a,b,c,d){function e(f){var g=
l[f];return g?g.contextDep&&d.contextDynamic||g.propDep?g.append(a,c):g.append(a,b):b.def(m,".",f)}function f(){function a(){c(u,".drawElementsInstancedANGLE(",[q,t,C,r+"<<(("+C+"-5121)>>1)",v],");")}function b(){c(u,".drawArraysInstancedANGLE(",[q,r,t,v],");")}n?da?a():(c("if(",n,"){"),a(),c("}else{"),b(),c("}")):b()}function g(){function a(){c(k+".drawElements("+[q,t,C,r+"<<(("+C+"-5121)>>1)"]+");")}function b(){c(k+".drawArrays("+[q,r,t]+");")}n?da?a():(c("if(",n,"){"),a(),c("}else{"),b(),c("}")):
b()}var h=a.shared,k=h.gl,m=h.draw,l=d.draw,n=function(){var e=l.elements,f=b;if(e){if(e.contextDep&&d.contextDynamic||e.propDep)f=c;e=e.append(a,f)}else e=f.def(m,".","elements");e&&f("if("+e+")"+k+".bindBuffer(34963,"+e+".buffer.buffer);");return e}(),q=e("primitive"),r=e("offset"),t=function(){var e=l.count,f=b;if(e){if(e.contextDep&&d.contextDynamic||e.propDep)f=c;e=e.append(a,f)}else e=f.def(m,".","count");return e}();if("number"===typeof t){if(0===t)return}else c("if(",t,"){"),c.exit("}");var v,
u;ea&&(v=e("instances"),u=a.instancing);var C=n+".type",da=l.elements&&va(l.elements);ea&&("number"!==typeof v||0<=v)?"string"===typeof v?(c("if(",v,">0){"),f(),c("}else if(",v,"<0){"),g(),c("}")):f():g()}function ca(a,b,c,d,e){b=N();e=b.proc("body",e);ea&&(b.instancing=e.def(b.shared.extensions,".angle_instanced_arrays"));a(b,e,c,d);return b.compile().body}function L(a,b,c,d){wa(a,b);U(a,b,c,d.attributes,function(){return!0});W(a,b,c,d.uniforms,function(){return!0});S(a,b,b,c)}function da(a,b){var c=
a.proc("draw",1);wa(a,c);ua(a,c,b.context);K(a,c,b.framebuffer);V(a,c,b);Q(a,c,b.state);G(a,c,b,!1,!0);var d=b.shader.progVar.append(a,c);c(a.shared.gl,".useProgram(",d,".program);");if(b.shader.program)L(a,c,b,b.shader.program);else{var e=a.global.def("{}"),f=c.def(d,".id"),g=c.def(e,"[",f,"]");c(a.cond(g).then(g,".call(this,a0);")["else"](g,"=",e,"[",f,"]=",a.link(function(c){return ca(L,a,b,c,1)}),"(",d,");",g,".call(this,a0);"))}0<Object.keys(b.state).length&&c(a.shared.current,".dirty=true;")}
function oa(a,b,c,d){function e(){return!0}a.batchId="a1";wa(a,b);U(a,b,c,d.attributes,e);W(a,b,c,d.uniforms,e);S(a,b,b,c)}function za(a,b,c,d){function e(a){return a.contextDep&&g||a.propDep}function f(a){return!e(a)}wa(a,b);var g=c.contextDep,h=b.def(),k=b.def();a.shared.props=k;a.batchId=h;var m=a.scope(),l=a.scope();b(m.entry,"for(",h,"=0;",h,"<","a1",";++",h,"){",k,"=","a0","[",h,"];",l,"}",m.exit);c.needsContext&&ua(a,l,c.context);c.needsFramebuffer&&K(a,l,c.framebuffer);Q(a,l,c.state,e);c.profile&&
e(c.profile)&&G(a,l,c,!1,!0);d?(U(a,m,c,d.attributes,f),U(a,l,c,d.attributes,e),W(a,m,c,d.uniforms,f),W(a,l,c,d.uniforms,e),S(a,m,l,c)):(b=a.global.def("{}"),d=c.shader.progVar.append(a,l),k=l.def(d,".id"),m=l.def(b,"[",k,"]"),l(a.shared.gl,".useProgram(",d,".program);","if(!",m,"){",m,"=",b,"[",k,"]=",a.link(function(b){return ca(oa,a,c,b,2)}),"(",d,");}",m,".call(this,a0[",h,"],",h,");"))}function ka(a,b){function c(a){return a.contextDep&&e||a.propDep}var d=a.proc("batch",2);a.batchId="0";wa(a,
d);var e=!1,f=!0;Object.keys(b.context).forEach(function(a){e=e||b.context[a].propDep});e||(ua(a,d,b.context),f=!1);var g=b.framebuffer,h=!1;g?(g.propDep?e=h=!0:g.contextDep&&e&&(h=!0),h||K(a,d,g)):K(a,d,null);b.state.viewport&&b.state.viewport.propDep&&(e=!0);V(a,d,b);Q(a,d,b.state,function(a){return!c(a)});b.profile&&c(b.profile)||G(a,d,b,!1,"a1");b.contextDep=e;b.needsContext=f;b.needsFramebuffer=h;f=b.shader.progVar;if(f.contextDep&&e||f.propDep)za(a,d,b,null);else if(f=f.append(a,d),d(a.shared.gl,
".useProgram(",f,".program);"),b.shader.program)za(a,d,b,b.shader.program);else{var g=a.global.def("{}"),h=d.def(f,".id"),k=d.def(g,"[",h,"]");d(a.cond(k).then(k,".call(this,a0,a1);")["else"](k,"=",g,"[",h,"]=",a.link(function(c){return ca(za,a,b,c,2)}),"(",f,");",k,".call(this,a0,a1);"))}0<Object.keys(b.state).length&&d(a.shared.current,".dirty=true;")}function ia(a,c){function d(b){var g=c.shader[b];g&&e.set(f.shader,"."+b,g.append(a,e))}var e=a.proc("scope",3);a.batchId="a2";var f=a.shared,g=f.current;
ua(a,e,c.context);c.framebuffer&&c.framebuffer.append(a,e);vb(Object.keys(c.state)).forEach(function(b){var d=c.state[b].append(a,e);pa(d)?d.forEach(function(c,d){e.set(a.next[b],"["+d+"]",c)}):e.set(f.next,"."+b,d)});G(a,e,c,!0,!0);["elements","offset","count","instances","primitive"].forEach(function(b){var d=c.draw[b];d&&e.set(f.draw,"."+b,""+d.append(a,e))});Object.keys(c.uniforms).forEach(function(d){e.set(f.uniforms,"["+b.id(d)+"]",c.uniforms[d].append(a,e))});Object.keys(c.attributes).forEach(function(b){var d=
c.attributes[b].append(a,e),f=a.scopeAttrib(b);Object.keys(new ya).forEach(function(a){e.set(f,"."+a,d[a])})});d("vert");d("frag");0<Object.keys(c.state).length&&(e(g,".dirty=true;"),e.exit(g,".dirty=true;"));e("a1(",a.shared.context,",a0,",a.batchId,");")}function ma(a){if("object"===typeof a&&!pa(a)){for(var b=Object.keys(a),c=0;c<b.length;++c)if(la.isDynamic(a[b[c]]))return!0;return!1}}function ja(a,b,c){function d(a,b){g.forEach(function(c){var d=e[c];la.isDynamic(d)&&(d=a.invoke(b,d),b(l,".",
c,"=",d,";"))})}var e=b["static"][c];if(e&&ma(e)){var f=a.global,g=Object.keys(e),h=!1,k=!1,m=!1,l=a.global.def("{}");g.forEach(function(b){var c=e[b];if(la.isDynamic(c))"function"===typeof c&&(c=e[b]=la.unbox(c)),b=P(c,null),h=h||b.thisDep,m=m||b.propDep,k=k||b.contextDep;else{f(l,".",b,"=");switch(typeof c){case "number":f(c);break;case "string":f('"',c,'"');break;case "object":Array.isArray(c)&&f("[",c.join(),"]");break;default:f(a.link(c))}f(";")}});b.dynamic[c]=new la.DynamicVariable(4,{thisDep:h,
contextDep:k,propDep:m,ref:l,append:d});delete b["static"][c]}}var ya=q.Record,X={add:32774,subtract:32778,"reverse subtract":32779};c.ext_blend_minmax&&(X.min=32775,X.max=32776);var ea=c.angle_instanced_arrays,ha=c.webgl_draw_buffers,ra={dirty:!0,profile:h.profile},Fa={},Ka=[],sa={},ta={};u("dither",3024);u("blend.enable",3042);v("blend.color","blendColor",[0,0,0,0]);v("blend.equation","blendEquationSeparate",[32774,32774]);v("blend.func","blendFuncSeparate",[1,0,1,0]);u("depth.enable",2929,!0);
v("depth.func","depthFunc",513);v("depth.range","depthRange",[0,1]);v("depth.mask","depthMask",!0);v("colorMask","colorMask",[!0,!0,!0,!0]);u("cull.enable",2884);v("cull.face","cullFace",1029);v("frontFace","frontFace",2305);v("lineWidth","lineWidth",1);u("polygonOffset.enable",32823);v("polygonOffset.offset","polygonOffset",[0,0]);u("sample.alpha",32926);u("sample.enable",32928);v("sample.coverage","sampleCoverage",[1,!1]);u("stencil.enable",2960);v("stencil.mask","stencilMask",-1);v("stencil.func",
"stencilFunc",[519,0,-1]);v("stencil.opFront","stencilOpSeparate",[1028,7680,7680,7680]);v("stencil.opBack","stencilOpSeparate",[1029,7680,7680,7680]);u("scissor.enable",3089);v("scissor.box","scissor",[0,0,a.drawingBufferWidth,a.drawingBufferHeight]);v("viewport","viewport",[0,0,a.drawingBufferWidth,a.drawingBufferHeight]);var na={gl:a,context:C,strings:b,next:Fa,current:ra,draw:m,elements:d,buffer:g,shader:t,attributes:q.state,uniforms:r,framebuffer:f,extensions:c,timer:k,isBufferArgs:Oa},aa={primTypes:Sa,
compareFuncs:Xa,blendFuncs:Ga,blendEquations:X,stencilOps:Pa,glTypes:Ra,orientationType:wb};ha&&(aa.backBuffer=[1029],aa.drawBuffer=J(e.maxDrawbuffers,function(a){return 0===a?[0]:J(a,function(a){return 36064+a})}));var qa=0;return{next:Fa,current:ra,procs:function(){var a=N(),b=a.proc("poll"),c=a.proc("refresh"),d=a.block();b(d);c(d);var f=a.shared,g=f.gl,h=f.next,k=f.current;d(k,".dirty=false;");K(a,b);K(a,c,null,!0);var m;ea&&(m=a.link(ea));for(var l=0;l<e.maxAttributes;++l){var n=c.def(f.attributes,
"[",l,"]"),q=a.cond(n,".buffer");q.then(g,".enableVertexAttribArray(",l,");",g,".bindBuffer(",34962,",",n,".buffer.buffer);",g,".vertexAttribPointer(",l,",",n,".size,",n,".type,",n,".normalized,",n,".stride,",n,".offset);")["else"](g,".disableVertexAttribArray(",l,");",g,".vertexAttrib4f(",l,",",n,".x,",n,".y,",n,".z,",n,".w);",n,".buffer=null;");c(q);ea&&c(m,".vertexAttribDivisorANGLE(",l,",",n,".divisor);")}Object.keys(sa).forEach(function(e){var f=sa[e],m=d.def(h,".",e),l=a.block();l("if(",m,"){",
g,".enable(",f,")}else{",g,".disable(",f,")}",k,".",e,"=",m,";");c(l);b("if(",m,"!==",k,".",e,"){",l,"}")});Object.keys(ta).forEach(function(e){var f=ta[e],m=ra[e],l,n,q=a.block();q(g,".",f,"(");pa(m)?(f=m.length,l=a.global.def(h,".",e),n=a.global.def(k,".",e),q(J(f,function(a){return l+"["+a+"]"}),");",J(f,function(a){return n+"["+a+"]="+l+"["+a+"];"}).join("")),b("if(",J(f,function(a){return l+"["+a+"]!=="+n+"["+a+"]"}).join("||"),"){",q,"}")):(l=d.def(h,".",e),n=d.def(k,".",e),q(l,");",k,".",e,
"=",l,";"),b("if(",l,"!==",n,"){",q,"}"));c(q)});return a.compile()}(),compile:function(a,b,c,d,e){var f=N();f.stats=f.link(e);Object.keys(b["static"]).forEach(function(a){ja(f,b,a)});Ub.forEach(function(b){ja(f,a,b)});c=A(a,b,c,d,f);da(f,c);ia(f,c);ka(f,c);return f.compile()}}}function yb(a,b){for(var c=0;c<a.length;++c)if(a[c]===b)return c;return-1}var E=function(a,b){for(var c=Object.keys(b),e=0;e<c.length;++e)a[c[e]]=b[c[e]];return a},Ab=0,la={DynamicVariable:aa,define:function(a,b){return new aa(a,
Za(b+""))},isDynamic:function(a){return"function"===typeof a&&!a._reglType||a instanceof aa},unbox:function(a,b){return"function"===typeof a?new aa(0,a):a},accessor:Za},Ya={next:"function"===typeof requestAnimationFrame?function(a){return requestAnimationFrame(a)}:function(a){return setTimeout(a,16)},cancel:"function"===typeof cancelAnimationFrame?function(a){return cancelAnimationFrame(a)}:clearTimeout},zb="undefined"!==typeof performance&&performance.now?function(){return performance.now()}:function(){return+new Date},
x=cb();x.zero=cb();var Vb=function(a,b){var c=1;b.ext_texture_filter_anisotropic&&(c=a.getParameter(34047));var e=1,g=1;b.webgl_draw_buffers&&(e=a.getParameter(34852),g=a.getParameter(36063));var d=!!b.oes_texture_float;if(d){d=a.createTexture();a.bindTexture(3553,d);a.texImage2D(3553,0,6408,1,1,0,6408,5126,null);var n=a.createFramebuffer();a.bindFramebuffer(36160,n);a.framebufferTexture2D(36160,36064,3553,d,0);a.bindTexture(3553,null);if(36053!==a.checkFramebufferStatus(36160))d=!1;else{a.viewport(0,
0,1,1);a.clearColor(1,0,0,1);a.clear(16384);var f=x.allocType(5126,4);a.readPixels(0,0,1,1,6408,5126,f);a.getError()?d=!1:(a.deleteFramebuffer(n),a.deleteTexture(d),d=1===f[0]);x.freeType(f)}}f=!0;"undefined"!==typeof navigator&&(/MSIE/.test(navigator.userAgent)||/Trident\//.test(navigator.appVersion)||/Edge/.test(navigator.userAgent))||(f=a.createTexture(),n=x.allocType(5121,36),a.activeTexture(33984),a.bindTexture(34067,f),a.texImage2D(34069,0,6408,3,3,0,6408,5121,n),x.freeType(n),a.bindTexture(34067,
null),a.deleteTexture(f),f=!a.getError());return{colorBits:[a.getParameter(3410),a.getParameter(3411),a.getParameter(3412),a.getParameter(3413)],depthBits:a.getParameter(3414),stencilBits:a.getParameter(3415),subpixelBits:a.getParameter(3408),extensions:Object.keys(b).filter(function(a){return!!b[a]}),maxAnisotropic:c,maxDrawbuffers:e,maxColorAttachments:g,pointSizeDims:a.getParameter(33901),lineWidthDims:a.getParameter(33902),maxViewportDims:a.getParameter(3386),maxCombinedTextureUnits:a.getParameter(35661),
maxCubeMapSize:a.getParameter(34076),maxRenderbufferSize:a.getParameter(34024),maxTextureUnits:a.getParameter(34930),maxTextureSize:a.getParameter(3379),maxAttributes:a.getParameter(34921),maxVertexUniforms:a.getParameter(36347),maxVertexTextureUnits:a.getParameter(35660),maxVaryingVectors:a.getParameter(36348),maxFragmentUniforms:a.getParameter(36349),glsl:a.getParameter(35724),renderer:a.getParameter(7937),vendor:a.getParameter(7936),version:a.getParameter(7938),readFloat:d,npotTextureCube:f}},
M=function(a){return a instanceof Uint8Array||a instanceof Uint16Array||a instanceof Uint32Array||a instanceof Int8Array||a instanceof Int16Array||a instanceof Int32Array||a instanceof Float32Array||a instanceof Float64Array||a instanceof Uint8ClampedArray},S=function(a){return Object.keys(a).map(function(b){return a[b]})},Ma={shape:function(a){for(var b=[];a.length;a=a[0])b.push(a.length);return b},flatten:function(a,b,c,e){var g=1;if(b.length)for(var d=0;d<b.length;++d)g*=b[d];else g=0;c=e||x.allocType(c,
g);switch(b.length){case 0:break;case 1:e=b[0];for(b=0;b<e;++b)c[b]=a[b];break;case 2:e=b[0];b=b[1];for(d=g=0;d<e;++d)for(var n=a[d],f=0;f<b;++f)c[g++]=n[f];break;case 3:db(a,b[0],b[1],b[2],c,0);break;default:eb(a,b,0,c,0)}return c}},Ia={"[object Int8Array]":5120,"[object Int16Array]":5122,"[object Int32Array]":5124,"[object Uint8Array]":5121,"[object Uint8ClampedArray]":5121,"[object Uint16Array]":5123,"[object Uint32Array]":5125,"[object Float32Array]":5126,"[object Float64Array]":5121,"[object ArrayBuffer]":5121},
Ra={int8:5120,int16:5122,int32:5124,uint8:5121,uint16:5123,uint32:5125,"float":5126,float32:5126},jb={dynamic:35048,stream:35040,"static":35044},Qa=Ma.flatten,hb=Ma.shape,ja=[];ja[5120]=1;ja[5122]=2;ja[5124]=4;ja[5121]=1;ja[5123]=2;ja[5125]=4;ja[5126]=4;var Sa={points:0,point:0,lines:1,line:1,triangles:4,triangle:4,"line loop":2,"line strip":3,"triangle strip":5,"triangle fan":6},lb=new Float32Array(1),Ib=new Uint32Array(lb.buffer),Mb=[9984,9986,9985,9987],La=[0,6409,6410,6407,6408],L={};L[6409]=
L[6406]=L[6402]=1;L[34041]=L[6410]=2;L[6407]=L[35904]=3;L[6408]=L[35906]=4;var Ua=Ea("HTMLCanvasElement"),pb=Ea("CanvasRenderingContext2D"),qb=Ea("ImageBitmap"),rb=Ea("HTMLImageElement"),sb=Ea("HTMLVideoElement"),Jb=Object.keys(Ia).concat([Ua,pb,qb,rb,sb]),qa=[];qa[5121]=1;qa[5126]=4;qa[36193]=2;qa[5123]=2;qa[5125]=4;var y=[];y[32854]=2;y[32855]=2;y[36194]=2;y[34041]=4;y[33776]=.5;y[33777]=.5;y[33778]=1;y[33779]=1;y[35986]=.5;y[35987]=1;y[34798]=1;y[35840]=.5;y[35841]=.25;y[35842]=.5;y[35843]=.25;
y[36196]=.5;var Q=[];Q[32854]=2;Q[32855]=2;Q[36194]=2;Q[33189]=2;Q[36168]=1;Q[34041]=4;Q[35907]=4;Q[34836]=16;Q[34842]=8;Q[34843]=6;var Wb=function(a,b,c,e,g){function d(a){this.id=q++;this.refCount=1;this.renderbuffer=a;this.format=32854;this.height=this.width=0;g.profile&&(this.stats={size:0})}function n(b){var c=b.renderbuffer;a.bindRenderbuffer(36161,null);a.deleteRenderbuffer(c);b.renderbuffer=null;b.refCount=0;delete t[b.id];e.renderbufferCount--}var f={rgba4:32854,rgb565:36194,"rgb5 a1":32855,
depth:33189,stencil:36168,"depth stencil":34041};b.ext_srgb&&(f.srgba=35907);b.ext_color_buffer_half_float&&(f.rgba16f=34842,f.rgb16f=34843);b.webgl_color_buffer_float&&(f.rgba32f=34836);var r=[];Object.keys(f).forEach(function(a){r[f[a]]=a});var q=0,t={};d.prototype.decRef=function(){0>=--this.refCount&&n(this)};g.profile&&(e.getTotalRenderbufferSize=function(){var a=0;Object.keys(t).forEach(function(b){a+=t[b].stats.size});return a});return{create:function(b,c){function k(b,c){var d=0,e=0,m=32854;
"object"===typeof b&&b?("shape"in b?(e=b.shape,d=e[0]|0,e=e[1]|0):("radius"in b&&(d=e=b.radius|0),"width"in b&&(d=b.width|0),"height"in b&&(e=b.height|0)),"format"in b&&(m=f[b.format])):"number"===typeof b?(d=b|0,e="number"===typeof c?c|0:d):b||(d=e=1);if(d!==h.width||e!==h.height||m!==h.format)return k.width=h.width=d,k.height=h.height=e,h.format=m,a.bindRenderbuffer(36161,h.renderbuffer),a.renderbufferStorage(36161,m,d,e),g.profile&&(h.stats.size=Q[h.format]*h.width*h.height),k.format=r[h.format],
k}var h=new d(a.createRenderbuffer());t[h.id]=h;e.renderbufferCount++;k(b,c);k.resize=function(b,c){var d=b|0,e=c|0||d;if(d===h.width&&e===h.height)return k;k.width=h.width=d;k.height=h.height=e;a.bindRenderbuffer(36161,h.renderbuffer);a.renderbufferStorage(36161,h.format,d,e);g.profile&&(h.stats.size=Q[h.format]*h.width*h.height);return k};k._reglType="renderbuffer";k._renderbuffer=h;g.profile&&(k.stats=h.stats);k.destroy=function(){h.decRef()};return k},clear:function(){S(t).forEach(n)},restore:function(){S(t).forEach(function(b){b.renderbuffer=
a.createRenderbuffer();a.bindRenderbuffer(36161,b.renderbuffer);a.renderbufferStorage(36161,b.format,b.width,b.height)});a.bindRenderbuffer(36161,null)}}},Wa=[];Wa[6408]=4;Wa[6407]=3;var Na=[];Na[5121]=1;Na[5126]=4;Na[36193]=2;var Da=["x","y","z","w"],Ub="blend.func blend.equation stencil.func stencil.opFront stencil.opBack sample.coverage viewport scissor.box polygonOffset.offset".split(" "),Ga={0:0,1:1,zero:0,one:1,"src color":768,"one minus src color":769,"src alpha":770,"one minus src alpha":771,
"dst color":774,"one minus dst color":775,"dst alpha":772,"one minus dst alpha":773,"constant color":32769,"one minus constant color":32770,"constant alpha":32771,"one minus constant alpha":32772,"src alpha saturate":776},Xa={never:512,less:513,"<":513,equal:514,"=":514,"==":514,"===":514,lequal:515,"<=":515,greater:516,">":516,notequal:517,"!=":517,"!==":517,gequal:518,">=":518,always:519},Pa={0:0,zero:0,keep:7680,replace:7681,increment:7682,decrement:7683,"increment wrap":34055,"decrement wrap":34056,
invert:5386},wb={cw:2304,ccw:2305},xb=new Z(!1,!1,!1,function(){}),Xb=function(a,b){function c(){this.endQueryIndex=this.startQueryIndex=-1;this.sum=0;this.stats=null}function e(a,b,d){var e=n.pop()||new c;e.startQueryIndex=a;e.endQueryIndex=b;e.sum=0;e.stats=d;f.push(e)}if(!b.ext_disjoint_timer_query)return null;var g=[],d=[],n=[],f=[],r=[],q=[];return{beginQuery:function(a){var c=g.pop()||b.ext_disjoint_timer_query.createQueryEXT();b.ext_disjoint_timer_query.beginQueryEXT(35007,c);d.push(c);e(d.length-
1,d.length,a)},endQuery:function(){b.ext_disjoint_timer_query.endQueryEXT(35007)},pushScopeStats:e,update:function(){var a,c;a=d.length;if(0!==a){q.length=Math.max(q.length,a+1);r.length=Math.max(r.length,a+1);r[0]=0;var e=q[0]=0;for(c=a=0;c<d.length;++c){var k=d[c];b.ext_disjoint_timer_query.getQueryObjectEXT(k,34919)?(e+=b.ext_disjoint_timer_query.getQueryObjectEXT(k,34918),g.push(k)):d[a++]=k;r[c+1]=e;q[c+1]=a}d.length=a;for(c=a=0;c<f.length;++c){var e=f[c],h=e.startQueryIndex,k=e.endQueryIndex;
e.sum+=r[k]-r[h];h=q[h];k=q[k];k===h?(e.stats.gpuTime+=e.sum/1E6,n.push(e)):(e.startQueryIndex=h,e.endQueryIndex=k,f[a++]=e)}f.length=a}},getNumPendingQueries:function(){return d.length},clear:function(){g.push.apply(g,d);for(var a=0;a<g.length;a++)b.ext_disjoint_timer_query.deleteQueryEXT(g[a]);d.length=0;g.length=0},restore:function(){d.length=0;g.length=0}}};return function(a){function b(){if(0===G.length)B&&B.update(),ca=null;else{ca=Ya.next(b);t();for(var a=G.length-1;0<=a;--a){var c=G[a];c&&
c(O,null,0)}k.flush();B&&B.update()}}function c(){!ca&&0<G.length&&(ca=Ya.next(b))}function e(){ca&&(Ya.cancel(b),ca=null)}function g(a){a.preventDefault();e();U.forEach(function(a){a()})}function d(a){k.getError();l.restore();Q.restore();F.restore();A.restore();M.restore();K.restore();B&&B.restore();V.procs.refresh();c();W.forEach(function(a){a()})}function n(a){function b(a){var c={},d={};Object.keys(a).forEach(function(b){var e=a[b];la.isDynamic(e)?d[b]=la.unbox(e,b):c[b]=e});return{dynamic:d,
"static":c}}function c(a){for(;m.length<a;)m.push(null);return m}var d=b(a.context||{}),e=b(a.uniforms||{}),f=b(a.attributes||{}),g=b(function(a){function b(a){if(a in c){var d=c[a];delete c[a];Object.keys(d).forEach(function(b){c[a+"."+b]=d[b]})}}var c=E({},a);delete c.uniforms;delete c.attributes;delete c.context;"stencil"in c&&c.stencil.op&&(c.stencil.opBack=c.stencil.opFront=c.stencil.op,delete c.stencil.op);b("blend");b("depth");b("cull");b("stencil");b("polygonOffset");b("scissor");b("sample");
return c}(a));a={gpuTime:0,cpuTime:0,count:0};var d=V.compile(g,f,e,d,a),h=d.draw,k=d.batch,l=d.scope,m=[];return E(function(a,b){var d;if("function"===typeof a)return l.call(this,null,a,0);if("function"===typeof b)if("number"===typeof a)for(d=0;d<a;++d)l.call(this,null,b,d);else if(Array.isArray(a))for(d=0;d<a.length;++d)l.call(this,a[d],b,d);else return l.call(this,a,b,0);else if("number"===typeof a){if(0<a)return k.call(this,c(a|0),a|0)}else if(Array.isArray(a)){if(a.length)return k.call(this,
a,a.length)}else return h.call(this,a)},{stats:a})}function f(a,b){var c=0;V.procs.poll();var d=b.color;d&&(k.clearColor(+d[0]||0,+d[1]||0,+d[2]||0,+d[3]||0),c|=16384);"depth"in b&&(k.clearDepth(+b.depth),c|=256);"stencil"in b&&(k.clearStencil(b.stencil|0),c|=1024);k.clear(c)}function r(a){G.push(a);c();return{cancel:function(){function b(){var a=yb(G,b);G[a]=G[G.length-1];--G.length;0>=G.length&&e()}var c=yb(G,a);G[c]=b}}}function q(){var a=S.viewport,b=S.scissor_box;a[0]=a[1]=b[0]=b[1]=0;O.viewportWidth=
O.framebufferWidth=O.drawingBufferWidth=a[2]=b[2]=k.drawingBufferWidth;O.viewportHeight=O.framebufferHeight=O.drawingBufferHeight=a[3]=b[3]=k.drawingBufferHeight}function t(){O.tick+=1;O.time=y();q();V.procs.poll()}function m(){q();V.procs.refresh();B&&B.update()}function y(){return(zb()-D)/1E3}a=Eb(a);if(!a)return null;var k=a.gl,h=k.getContextAttributes();k.isContextLost();var l=Fb(k,a);if(!l)return null;var u=Bb(),v={bufferCount:0,elementsCount:0,framebufferCount:0,shaderCount:0,textureCount:0,
cubeCount:0,renderbufferCount:0,maxTextureUnits:0},x=l.extensions,B=Xb(k,x),D=zb(),J=k.drawingBufferWidth,P=k.drawingBufferHeight,O={tick:0,time:0,viewportWidth:J,viewportHeight:P,framebufferWidth:J,framebufferHeight:P,drawingBufferWidth:J,drawingBufferHeight:P,pixelRatio:a.pixelRatio},R=Vb(k,x),J=Pb(k,x,R,u),F=Gb(k,v,a,J),T=Hb(k,x,F,v),Q=Qb(k,u,v,a),A=Kb(k,x,R,function(){V.procs.poll()},O,v,a),M=Wb(k,x,R,v,a),K=Ob(k,x,R,A,M,v),V=Tb(k,u,x,R,F,T,A,K,{},J,Q,{elements:null,primitive:4,count:-1,offset:0,
instances:-1},O,B,a),u=Rb(k,K,V.procs.poll,O,h,x,R),S=V.next,L=k.canvas,G=[],U=[],W=[],Z=[a.onDestroy],ca=null;L&&(L.addEventListener("webglcontextlost",g,!1),L.addEventListener("webglcontextrestored",d,!1));var aa=K.setFBO=n({framebuffer:la.define.call(null,1,"framebuffer")});m();h=E(n,{clear:function(a){if("framebuffer"in a)if(a.framebuffer&&"framebufferCube"===a.framebuffer_reglType)for(var b=0;6>b;++b)aa(E({framebuffer:a.framebuffer.faces[b]},a),f);else aa(a,f);else f(null,a)},prop:la.define.bind(null,
1),context:la.define.bind(null,2),"this":la.define.bind(null,3),draw:n({}),buffer:function(a){return F.create(a,34962,!1,!1)},elements:function(a){return T.create(a,!1)},texture:A.create2D,cube:A.createCube,renderbuffer:M.create,framebuffer:K.create,framebufferCube:K.createCube,attributes:h,frame:r,on:function(a,b){var c;switch(a){case "frame":return r(b);case "lost":c=U;break;case "restore":c=W;break;case "destroy":c=Z}c.push(b);return{cancel:function(){for(var a=0;a<c.length;++a)if(c[a]===b){c[a]=
c[c.length-1];c.pop();break}}}},limits:R,hasExtension:function(a){return 0<=R.extensions.indexOf(a.toLowerCase())},read:u,destroy:function(){G.length=0;e();L&&(L.removeEventListener("webglcontextlost",g),L.removeEventListener("webglcontextrestored",d));Q.clear();K.clear();M.clear();A.clear();T.clear();F.clear();B&&B.clear();Z.forEach(function(a){a()})},_gl:k,_refresh:m,poll:function(){t();B&&B.update()},now:y,stats:v});a.onDone(null,h);return h}});

},{}],484:[function(_dereq_,module,exports){
/*!
 * repeat-string <https://github.com/jonschlinkert/repeat-string>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

/**
 * Results cache
 */

var res = '';
var cache;

/**
 * Expose `repeat`
 */

module.exports = repeat;

/**
 * Repeat the given `string` the specified `number`
 * of times.
 *
 * **Example:**
 *
 * ```js
 * var repeat = require('repeat-string');
 * repeat('A', 5);
 * //=> AAAAA
 * ```
 *
 * @param {String} `string` The string to repeat
 * @param {Number} `number` The number of times to repeat the string
 * @return {String} Repeated string
 * @api public
 */

function repeat(str, num) {
  if (typeof str !== 'string') {
    throw new TypeError('expected a string');
  }

  // cover common, quick use cases
  if (num === 1) return str;
  if (num === 2) return str + str;

  var max = str.length * num;
  if (cache !== str || typeof cache === 'undefined') {
    cache = str;
    res = '';
  } else if (res.length >= max) {
    return res.substr(0, max);
  }

  while (max > res.length && num > 1) {
    if (num & 1) {
      res += str;
    }

    num >>= 1;
    str += str;
  }

  res += str;
  res = res.substr(0, max);
  return res;
}

},{}],485:[function(_dereq_,module,exports){
(function (global){
module.exports =
  global.performance &&
  global.performance.now ? function now() {
    return performance.now()
  } : Date.now || function now() {
    return +new Date
  }

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],486:[function(_dereq_,module,exports){
"use strict"

module.exports = compressExpansion

function compressExpansion(e) {
  var m = e.length
  var Q = e[e.length-1]
  var bottom = m
  for(var i=m-2; i>=0; --i) {
    var a = Q
    var b = e[i]
    Q = a + b
    var bv = Q - a
    var q = b - bv
    if(q) {
      e[--bottom] = Q
      Q = q
    }
  }
  var top = 0
  for(var i=bottom; i<m; ++i) {
    var a = e[i]
    var b = Q
    Q = a + b
    var bv = Q - a
    var q = b - bv
    if(q) {
      e[top++] = q
    }
  }
  e[top++] = Q
  e.length = top
  return e
}
},{}],487:[function(_dereq_,module,exports){
"use strict"

var twoProduct = _dereq_("two-product")
var robustSum = _dereq_("robust-sum")
var robustScale = _dereq_("robust-scale")
var compress = _dereq_("robust-compress")

var NUM_EXPANDED = 6

function cofactor(m, c) {
  var result = new Array(m.length-1)
  for(var i=1; i<m.length; ++i) {
    var r = result[i-1] = new Array(m.length-1)
    for(var j=0,k=0; j<m.length; ++j) {
      if(j === c) {
        continue
      }
      r[k++] = m[i][j]
    }
  }
  return result
}

function matrix(n) {
  var result = new Array(n)
  for(var i=0; i<n; ++i) {
    result[i] = new Array(n)
    for(var j=0; j<n; ++j) {
      result[i][j] = ["m[", i, "][", j, "]"].join("")
    }
  }
  return result
}

function sign(n) {
  if(n & 1) {
    return "-"
  }
  return ""
}

function generateSum(expr) {
  if(expr.length === 1) {
    return expr[0]
  } else if(expr.length === 2) {
    return ["sum(", expr[0], ",", expr[1], ")"].join("")
  } else {
    var m = expr.length>>1
    return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("")
  }
}

function determinant(m) {
  if(m.length === 2) {
    return ["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("")
  } else {
    var expr = []
    for(var i=0; i<m.length; ++i) {
      expr.push(["scale(", determinant(cofactor(m, i)), ",", sign(i), m[0][i], ")"].join(""))
    }
    return generateSum(expr)
  }
}

function compileDeterminant(n) {
  var proc = new Function("sum", "scale", "prod", "compress", [
    "function robustDeterminant",n, "(m){return compress(", 
      determinant(matrix(n)),
    ")};return robustDeterminant", n].join(""))
  return proc(robustSum, robustScale, twoProduct, compress)
}

var CACHE = [
  function robustDeterminant0() { return [0] },
  function robustDeterminant1(m) { return [m[0][0]] }
]

function generateDispatch() {
  while(CACHE.length < NUM_EXPANDED) {
    CACHE.push(compileDeterminant(CACHE.length))
  }
  var procArgs = []
  var code = ["function robustDeterminant(m){switch(m.length){"]
  for(var i=0; i<NUM_EXPANDED; ++i) {
    procArgs.push("det" + i)
    code.push("case ", i, ":return det", i, "(m);")
  }
  code.push("}\
var det=CACHE[m.length];\
if(!det)\
det=CACHE[m.length]=gen(m.length);\
return det(m);\
}\
return robustDeterminant")
  procArgs.push("CACHE", "gen", code.join(""))
  var proc = Function.apply(undefined, procArgs)
  module.exports = proc.apply(undefined, CACHE.concat([CACHE, compileDeterminant]))
  for(var i=0; i<CACHE.length; ++i) {
    module.exports[i] = CACHE[i]
  }
}

generateDispatch()
},{"robust-compress":486,"robust-scale":493,"robust-sum":496,"two-product":524}],488:[function(_dereq_,module,exports){
"use strict"

var twoProduct = _dereq_("two-product")
var robustSum = _dereq_("robust-sum")

module.exports = robustDotProduct

function robustDotProduct(a, b) {
  var r = twoProduct(a[0], b[0])
  for(var i=1; i<a.length; ++i) {
    r = robustSum(r, twoProduct(a[i], b[i]))
  }
  return r
}
},{"robust-sum":496,"two-product":524}],489:[function(_dereq_,module,exports){
"use strict"

var twoProduct = _dereq_("two-product")
var robustSum = _dereq_("robust-sum")
var robustDiff = _dereq_("robust-subtract")
var robustScale = _dereq_("robust-scale")

var NUM_EXPAND = 6

function cofactor(m, c) {
  var result = new Array(m.length-1)
  for(var i=1; i<m.length; ++i) {
    var r = result[i-1] = new Array(m.length-1)
    for(var j=0,k=0; j<m.length; ++j) {
      if(j === c) {
        continue
      }
      r[k++] = m[i][j]
    }
  }
  return result
}

function matrix(n) {
  var result = new Array(n)
  for(var i=0; i<n; ++i) {
    result[i] = new Array(n)
    for(var j=0; j<n; ++j) {
      result[i][j] = ["m", j, "[", (n-i-2), "]"].join("")
    }
  }
  return result
}

function generateSum(expr) {
  if(expr.length === 1) {
    return expr[0]
  } else if(expr.length === 2) {
    return ["sum(", expr[0], ",", expr[1], ")"].join("")
  } else {
    var m = expr.length>>1
    return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("")
  }
}

function makeProduct(a, b) {
  if(a.charAt(0) === "m") {
    if(b.charAt(0) === "w") {
      var toks = a.split("[")
      return ["w", b.substr(1), "m", toks[0].substr(1)].join("")
    } else {
      return ["prod(", a, ",", b, ")"].join("")
    }
  } else {
    return makeProduct(b, a)
  }
}

function sign(s) {
  if(s & 1 !== 0) {
    return "-"
  }
  return ""
}

function determinant(m) {
  if(m.length === 2) {
    return [["diff(", makeProduct(m[0][0], m[1][1]), ",", makeProduct(m[1][0], m[0][1]), ")"].join("")]
  } else {
    var expr = []
    for(var i=0; i<m.length; ++i) {
      expr.push(["scale(", generateSum(determinant(cofactor(m, i))), ",", sign(i), m[0][i], ")"].join(""))
    }
    return expr
  }
}

function makeSquare(d, n) {
  var terms = []
  for(var i=0; i<n-2; ++i) {
    terms.push(["prod(m", d, "[", i, "],m", d, "[", i, "])"].join(""))
  }
  return generateSum(terms)
}

function orientation(n) {
  var pos = []
  var neg = []
  var m = matrix(n)
  for(var i=0; i<n; ++i) {
    m[0][i] = "1"
    m[n-1][i] = "w"+i
  } 
  for(var i=0; i<n; ++i) {
    if((i&1)===0) {
      pos.push.apply(pos,determinant(cofactor(m, i)))
    } else {
      neg.push.apply(neg,determinant(cofactor(m, i)))
    }
  }
  var posExpr = generateSum(pos)
  var negExpr = generateSum(neg)
  var funcName = "exactInSphere" + n
  var funcArgs = []
  for(var i=0; i<n; ++i) {
    funcArgs.push("m" + i)
  }
  var code = ["function ", funcName, "(", funcArgs.join(), "){"]
  for(var i=0; i<n; ++i) {
    code.push("var w",i,"=",makeSquare(i,n),";")
    for(var j=0; j<n; ++j) {
      if(j !== i) {
        code.push("var w",i,"m",j,"=scale(w",i,",m",j,"[0]);")
      }
    }
  }
  code.push("var p=", posExpr, ",n=", negExpr, ",d=diff(p,n);return d[d.length-1];}return ", funcName)
  var proc = new Function("sum", "diff", "prod", "scale", code.join(""))
  return proc(robustSum, robustDiff, twoProduct, robustScale)
}

function inSphere0() { return 0 }
function inSphere1() { return 0 }
function inSphere2() { return 0 }

var CACHED = [
  inSphere0,
  inSphere1,
  inSphere2
]

function slowInSphere(args) {
  var proc = CACHED[args.length]
  if(!proc) {
    proc = CACHED[args.length] = orientation(args.length)
  }
  return proc.apply(undefined, args)
}

function generateInSphereTest() {
  while(CACHED.length <= NUM_EXPAND) {
    CACHED.push(orientation(CACHED.length))
  }
  var args = []
  var procArgs = ["slow"]
  for(var i=0; i<=NUM_EXPAND; ++i) {
    args.push("a" + i)
    procArgs.push("o" + i)
  }
  var code = [
    "function testInSphere(", args.join(), "){switch(arguments.length){case 0:case 1:return 0;"
  ]
  for(var i=2; i<=NUM_EXPAND; ++i) {
    code.push("case ", i, ":return o", i, "(", args.slice(0, i).join(), ");")
  }
  code.push("}var s=new Array(arguments.length);for(var i=0;i<arguments.length;++i){s[i]=arguments[i]};return slow(s);}return testInSphere")
  procArgs.push(code.join(""))

  var proc = Function.apply(undefined, procArgs)

  module.exports = proc.apply(undefined, [slowInSphere].concat(CACHED))
  for(var i=0; i<=NUM_EXPAND; ++i) {
    module.exports[i] = CACHED[i]
  }
}

generateInSphereTest()
},{"robust-scale":493,"robust-subtract":495,"robust-sum":496,"two-product":524}],490:[function(_dereq_,module,exports){
"use strict"

var determinant = _dereq_("robust-determinant")

var NUM_EXPAND = 6

function generateSolver(n) {
  var funcName = "robustLinearSolve" + n + "d"
  var code = ["function ", funcName, "(A,b){return ["]
  for(var i=0; i<n; ++i) {
    code.push("det([")
    for(var j=0; j<n; ++j) {
      if(j > 0) {
        code.push(",")
      }
      code.push("[")
      for(var k=0; k<n; ++k) {
        if(k > 0) {
          code.push(",")
        }
        if(k === i) {
          code.push("+b[", j, "]")
        } else {
          code.push("+A[", j, "][", k, "]")
        }
      }
      code.push("]")
    }
    code.push("]),")
  }
  code.push("det(A)]}return ", funcName)
  var proc = new Function("det", code.join(""))
  if(n < 6) {
    return proc(determinant[n])
  }
  return proc(determinant)
}

function robustLinearSolve0d() {
  return [ 0 ]
}

function robustLinearSolve1d(A, b) {
  return [ [ b[0] ], [ A[0][0] ] ]
}

var CACHE = [
  robustLinearSolve0d,
  robustLinearSolve1d
]

function generateDispatch() {
  while(CACHE.length < NUM_EXPAND) {
    CACHE.push(generateSolver(CACHE.length))
  }
  var procArgs = []
  var code = ["function dispatchLinearSolve(A,b){switch(A.length){"]
  for(var i=0; i<NUM_EXPAND; ++i) {
    procArgs.push("s" + i)
    code.push("case ", i, ":return s", i, "(A,b);")
  }
  code.push("}var s=CACHE[A.length];if(!s)s=CACHE[A.length]=g(A.length);return s(A,b)}return dispatchLinearSolve")
  procArgs.push("CACHE", "g", code.join(""))
  var proc = Function.apply(undefined, procArgs)
  module.exports = proc.apply(undefined, CACHE.concat([CACHE, generateSolver]))
  for(var i=0; i<NUM_EXPAND; ++i) {
    module.exports[i] = CACHE[i]
  }
}

generateDispatch()
},{"robust-determinant":487}],491:[function(_dereq_,module,exports){
"use strict"

var twoProduct = _dereq_("two-product")
var robustSum = _dereq_("robust-sum")
var robustScale = _dereq_("robust-scale")
var robustSubtract = _dereq_("robust-subtract")

var NUM_EXPAND = 5

var EPSILON     = 1.1102230246251565e-16
var ERRBOUND3   = (3.0 + 16.0 * EPSILON) * EPSILON
var ERRBOUND4   = (7.0 + 56.0 * EPSILON) * EPSILON

function cofactor(m, c) {
  var result = new Array(m.length-1)
  for(var i=1; i<m.length; ++i) {
    var r = result[i-1] = new Array(m.length-1)
    for(var j=0,k=0; j<m.length; ++j) {
      if(j === c) {
        continue
      }
      r[k++] = m[i][j]
    }
  }
  return result
}

function matrix(n) {
  var result = new Array(n)
  for(var i=0; i<n; ++i) {
    result[i] = new Array(n)
    for(var j=0; j<n; ++j) {
      result[i][j] = ["m", j, "[", (n-i-1), "]"].join("")
    }
  }
  return result
}

function sign(n) {
  if(n & 1) {
    return "-"
  }
  return ""
}

function generateSum(expr) {
  if(expr.length === 1) {
    return expr[0]
  } else if(expr.length === 2) {
    return ["sum(", expr[0], ",", expr[1], ")"].join("")
  } else {
    var m = expr.length>>1
    return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("")
  }
}

function determinant(m) {
  if(m.length === 2) {
    return [["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("")]
  } else {
    var expr = []
    for(var i=0; i<m.length; ++i) {
      expr.push(["scale(", generateSum(determinant(cofactor(m, i))), ",", sign(i), m[0][i], ")"].join(""))
    }
    return expr
  }
}

function orientation(n) {
  var pos = []
  var neg = []
  var m = matrix(n)
  var args = []
  for(var i=0; i<n; ++i) {
    if((i&1)===0) {
      pos.push.apply(pos, determinant(cofactor(m, i)))
    } else {
      neg.push.apply(neg, determinant(cofactor(m, i)))
    }
    args.push("m" + i)
  }
  var posExpr = generateSum(pos)
  var negExpr = generateSum(neg)
  var funcName = "orientation" + n + "Exact"
  var code = ["function ", funcName, "(", args.join(), "){var p=", posExpr, ",n=", negExpr, ",d=sub(p,n);\
return d[d.length-1];};return ", funcName].join("")
  var proc = new Function("sum", "prod", "scale", "sub", code)
  return proc(robustSum, twoProduct, robustScale, robustSubtract)
}

var orientation3Exact = orientation(3)
var orientation4Exact = orientation(4)

var CACHED = [
  function orientation0() { return 0 },
  function orientation1() { return 0 },
  function orientation2(a, b) { 
    return b[0] - a[0]
  },
  function orientation3(a, b, c) {
    var l = (a[1] - c[1]) * (b[0] - c[0])
    var r = (a[0] - c[0]) * (b[1] - c[1])
    var det = l - r
    var s
    if(l > 0) {
      if(r <= 0) {
        return det
      } else {
        s = l + r
      }
    } else if(l < 0) {
      if(r >= 0) {
        return det
      } else {
        s = -(l + r)
      }
    } else {
      return det
    }
    var tol = ERRBOUND3 * s
    if(det >= tol || det <= -tol) {
      return det
    }
    return orientation3Exact(a, b, c)
  },
  function orientation4(a,b,c,d) {
    var adx = a[0] - d[0]
    var bdx = b[0] - d[0]
    var cdx = c[0] - d[0]
    var ady = a[1] - d[1]
    var bdy = b[1] - d[1]
    var cdy = c[1] - d[1]
    var adz = a[2] - d[2]
    var bdz = b[2] - d[2]
    var cdz = c[2] - d[2]
    var bdxcdy = bdx * cdy
    var cdxbdy = cdx * bdy
    var cdxady = cdx * ady
    var adxcdy = adx * cdy
    var adxbdy = adx * bdy
    var bdxady = bdx * ady
    var det = adz * (bdxcdy - cdxbdy) 
            + bdz * (cdxady - adxcdy)
            + cdz * (adxbdy - bdxady)
    var permanent = (Math.abs(bdxcdy) + Math.abs(cdxbdy)) * Math.abs(adz)
                  + (Math.abs(cdxady) + Math.abs(adxcdy)) * Math.abs(bdz)
                  + (Math.abs(adxbdy) + Math.abs(bdxady)) * Math.abs(cdz)
    var tol = ERRBOUND4 * permanent
    if ((det > tol) || (-det > tol)) {
      return det
    }
    return orientation4Exact(a,b,c,d)
  }
]

function slowOrient(args) {
  var proc = CACHED[args.length]
  if(!proc) {
    proc = CACHED[args.length] = orientation(args.length)
  }
  return proc.apply(undefined, args)
}

function generateOrientationProc() {
  while(CACHED.length <= NUM_EXPAND) {
    CACHED.push(orientation(CACHED.length))
  }
  var args = []
  var procArgs = ["slow"]
  for(var i=0; i<=NUM_EXPAND; ++i) {
    args.push("a" + i)
    procArgs.push("o" + i)
  }
  var code = [
    "function getOrientation(", args.join(), "){switch(arguments.length){case 0:case 1:return 0;"
  ]
  for(var i=2; i<=NUM_EXPAND; ++i) {
    code.push("case ", i, ":return o", i, "(", args.slice(0, i).join(), ");")
  }
  code.push("}var s=new Array(arguments.length);for(var i=0;i<arguments.length;++i){s[i]=arguments[i]};return slow(s);}return getOrientation")
  procArgs.push(code.join(""))

  var proc = Function.apply(undefined, procArgs)
  module.exports = proc.apply(undefined, [slowOrient].concat(CACHED))
  for(var i=0; i<=NUM_EXPAND; ++i) {
    module.exports[i] = CACHED[i]
  }
}

generateOrientationProc()
},{"robust-scale":493,"robust-subtract":495,"robust-sum":496,"two-product":524}],492:[function(_dereq_,module,exports){
"use strict"

var robustSum = _dereq_("robust-sum")
var robustScale = _dereq_("robust-scale")

module.exports = robustProduct

function robustProduct(a, b) {
  if(a.length === 1) {
    return robustScale(b, a[0])
  }
  if(b.length === 1) {
    return robustScale(a, b[0])
  }
  if(a.length === 0 || b.length === 0) {
    return [0]
  }
  var r = [0]
  if(a.length < b.length) {
    for(var i=0; i<a.length; ++i) {
      r = robustSum(r, robustScale(b, a[i]))
    }
  } else {
    for(var i=0; i<b.length; ++i) {
      r = robustSum(r, robustScale(a, b[i]))
    }    
  }
  return r
}
},{"robust-scale":493,"robust-sum":496}],493:[function(_dereq_,module,exports){
"use strict"

var twoProduct = _dereq_("two-product")
var twoSum = _dereq_("two-sum")

module.exports = scaleLinearExpansion

function scaleLinearExpansion(e, scale) {
  var n = e.length
  if(n === 1) {
    var ts = twoProduct(e[0], scale)
    if(ts[0]) {
      return ts
    }
    return [ ts[1] ]
  }
  var g = new Array(2 * n)
  var q = [0.1, 0.1]
  var t = [0.1, 0.1]
  var count = 0
  twoProduct(e[0], scale, q)
  if(q[0]) {
    g[count++] = q[0]
  }
  for(var i=1; i<n; ++i) {
    twoProduct(e[i], scale, t)
    var pq = q[1]
    twoSum(pq, t[0], q)
    if(q[0]) {
      g[count++] = q[0]
    }
    var a = t[1]
    var b = q[1]
    var x = a + b
    var bv = x - a
    var y = b - bv
    q[1] = x
    if(y) {
      g[count++] = y
    }
  }
  if(q[1]) {
    g[count++] = q[1]
  }
  if(count === 0) {
    g[count++] = 0.0
  }
  g.length = count
  return g
}
},{"two-product":524,"two-sum":525}],494:[function(_dereq_,module,exports){
"use strict"

module.exports = segmentsIntersect

var orient = _dereq_("robust-orientation")[3]

function checkCollinear(a0, a1, b0, b1) {

  for(var d=0; d<2; ++d) {
    var x0 = a0[d]
    var y0 = a1[d]
    var l0 = Math.min(x0, y0)
    var h0 = Math.max(x0, y0)    

    var x1 = b0[d]
    var y1 = b1[d]
    var l1 = Math.min(x1, y1)
    var h1 = Math.max(x1, y1)    

    if(h1 < l0 || h0 < l1) {
      return false
    }
  }

  return true
}

function segmentsIntersect(a0, a1, b0, b1) {
  var x0 = orient(a0, b0, b1)
  var y0 = orient(a1, b0, b1)
  if((x0 > 0 && y0 > 0) || (x0 < 0 && y0 < 0)) {
    return false
  }

  var x1 = orient(b0, a0, a1)
  var y1 = orient(b1, a0, a1)
  if((x1 > 0 && y1 > 0) || (x1 < 0 && y1 < 0)) {
    return false
  }

  //Check for degenerate collinear case
  if(x0 === 0 && y0 === 0 && x1 === 0 && y1 === 0) {
    return checkCollinear(a0, a1, b0, b1)
  }

  return true
}
},{"robust-orientation":491}],495:[function(_dereq_,module,exports){
"use strict"

module.exports = robustSubtract

//Easy case: Add two scalars
function scalarScalar(a, b) {
  var x = a + b
  var bv = x - a
  var av = x - bv
  var br = b - bv
  var ar = a - av
  var y = ar + br
  if(y) {
    return [y, x]
  }
  return [x]
}

function robustSubtract(e, f) {
  var ne = e.length|0
  var nf = f.length|0
  if(ne === 1 && nf === 1) {
    return scalarScalar(e[0], -f[0])
  }
  var n = ne + nf
  var g = new Array(n)
  var count = 0
  var eptr = 0
  var fptr = 0
  var abs = Math.abs
  var ei = e[eptr]
  var ea = abs(ei)
  var fi = -f[fptr]
  var fa = abs(fi)
  var a, b
  if(ea < fa) {
    b = ei
    eptr += 1
    if(eptr < ne) {
      ei = e[eptr]
      ea = abs(ei)
    }
  } else {
    b = fi
    fptr += 1
    if(fptr < nf) {
      fi = -f[fptr]
      fa = abs(fi)
    }
  }
  if((eptr < ne && ea < fa) || (fptr >= nf)) {
    a = ei
    eptr += 1
    if(eptr < ne) {
      ei = e[eptr]
      ea = abs(ei)
    }
  } else {
    a = fi
    fptr += 1
    if(fptr < nf) {
      fi = -f[fptr]
      fa = abs(fi)
    }
  }
  var x = a + b
  var bv = x - a
  var y = b - bv
  var q0 = y
  var q1 = x
  var _x, _bv, _av, _br, _ar
  while(eptr < ne && fptr < nf) {
    if(ea < fa) {
      a = ei
      eptr += 1
      if(eptr < ne) {
        ei = e[eptr]
        ea = abs(ei)
      }
    } else {
      a = fi
      fptr += 1
      if(fptr < nf) {
        fi = -f[fptr]
        fa = abs(fi)
      }
    }
    b = q0
    x = a + b
    bv = x - a
    y = b - bv
    if(y) {
      g[count++] = y
    }
    _x = q1 + x
    _bv = _x - q1
    _av = _x - _bv
    _br = x - _bv
    _ar = q1 - _av
    q0 = _ar + _br
    q1 = _x
  }
  while(eptr < ne) {
    a = ei
    b = q0
    x = a + b
    bv = x - a
    y = b - bv
    if(y) {
      g[count++] = y
    }
    _x = q1 + x
    _bv = _x - q1
    _av = _x - _bv
    _br = x - _bv
    _ar = q1 - _av
    q0 = _ar + _br
    q1 = _x
    eptr += 1
    if(eptr < ne) {
      ei = e[eptr]
    }
  }
  while(fptr < nf) {
    a = fi
    b = q0
    x = a + b
    bv = x - a
    y = b - bv
    if(y) {
      g[count++] = y
    } 
    _x = q1 + x
    _bv = _x - q1
    _av = _x - _bv
    _br = x - _bv
    _ar = q1 - _av
    q0 = _ar + _br
    q1 = _x
    fptr += 1
    if(fptr < nf) {
      fi = -f[fptr]
    }
  }
  if(q0) {
    g[count++] = q0
  }
  if(q1) {
    g[count++] = q1
  }
  if(!count) {
    g[count++] = 0.0  
  }
  g.length = count
  return g
}
},{}],496:[function(_dereq_,module,exports){
"use strict"

module.exports = linearExpansionSum

//Easy case: Add two scalars
function scalarScalar(a, b) {
  var x = a + b
  var bv = x - a
  var av = x - bv
  var br = b - bv
  var ar = a - av
  var y = ar + br
  if(y) {
    return [y, x]
  }
  return [x]
}

function linearExpansionSum(e, f) {
  var ne = e.length|0
  var nf = f.length|0
  if(ne === 1 && nf === 1) {
    return scalarScalar(e[0], f[0])
  }
  var n = ne + nf
  var g = new Array(n)
  var count = 0
  var eptr = 0
  var fptr = 0
  var abs = Math.abs
  var ei = e[eptr]
  var ea = abs(ei)
  var fi = f[fptr]
  var fa = abs(fi)
  var a, b
  if(ea < fa) {
    b = ei
    eptr += 1
    if(eptr < ne) {
      ei = e[eptr]
      ea = abs(ei)
    }
  } else {
    b = fi
    fptr += 1
    if(fptr < nf) {
      fi = f[fptr]
      fa = abs(fi)
    }
  }
  if((eptr < ne && ea < fa) || (fptr >= nf)) {
    a = ei
    eptr += 1
    if(eptr < ne) {
      ei = e[eptr]
      ea = abs(ei)
    }
  } else {
    a = fi
    fptr += 1
    if(fptr < nf) {
      fi = f[fptr]
      fa = abs(fi)
    }
  }
  var x = a + b
  var bv = x - a
  var y = b - bv
  var q0 = y
  var q1 = x
  var _x, _bv, _av, _br, _ar
  while(eptr < ne && fptr < nf) {
    if(ea < fa) {
      a = ei
      eptr += 1
      if(eptr < ne) {
        ei = e[eptr]
        ea = abs(ei)
      }
    } else {
      a = fi
      fptr += 1
      if(fptr < nf) {
        fi = f[fptr]
        fa = abs(fi)
      }
    }
    b = q0
    x = a + b
    bv = x - a
    y = b - bv
    if(y) {
      g[count++] = y
    }
    _x = q1 + x
    _bv = _x - q1
    _av = _x - _bv
    _br = x - _bv
    _ar = q1 - _av
    q0 = _ar + _br
    q1 = _x
  }
  while(eptr < ne) {
    a = ei
    b = q0
    x = a + b
    bv = x - a
    y = b - bv
    if(y) {
      g[count++] = y
    }
    _x = q1 + x
    _bv = _x - q1
    _av = _x - _bv
    _br = x - _bv
    _ar = q1 - _av
    q0 = _ar + _br
    q1 = _x
    eptr += 1
    if(eptr < ne) {
      ei = e[eptr]
    }
  }
  while(fptr < nf) {
    a = fi
    b = q0
    x = a + b
    bv = x - a
    y = b - bv
    if(y) {
      g[count++] = y
    } 
    _x = q1 + x
    _bv = _x - q1
    _av = _x - _bv
    _br = x - _bv
    _ar = q1 - _av
    q0 = _ar + _br
    q1 = _x
    fptr += 1
    if(fptr < nf) {
      fi = f[fptr]
    }
  }
  if(q0) {
    g[count++] = q0
  }
  if(q1) {
    g[count++] = q1
  }
  if(!count) {
    g[count++] = 0.0  
  }
  g.length = count
  return g
}
},{}],497:[function(_dereq_,module,exports){
"use strict"

module.exports = function signum(x) {
  if(x < 0) { return -1 }
  if(x > 0) { return 1 }
  return 0.0
}
},{}],498:[function(_dereq_,module,exports){
'use strict'

module.exports = boundary

var bnd = _dereq_('boundary-cells')
var reduce = _dereq_('reduce-simplicial-complex')

function boundary(cells) {
  return reduce(bnd(cells))
}

},{"boundary-cells":83,"reduce-simplicial-complex":478}],499:[function(_dereq_,module,exports){
'use strict'

module.exports = extractContour

var ndarray = _dereq_('ndarray')
var pool    = _dereq_('typedarray-pool')
var ndsort  = _dereq_('ndarray-sort')

var contourAlgorithm = _dereq_('./lib/codegen')

function getDimension(cells) {
  var numCells = cells.length
  var d = 0
  for(var i=0; i<numCells; ++i) {
    d = Math.max(d, cells[i].length)|0
  }
  return d-1
}

function getSigns(values, level) {
  var numVerts    = values.length
  var vertexSigns = pool.mallocUint8(numVerts)
  for(var i=0; i<numVerts; ++i) {
    vertexSigns[i] = (values[i] < level)|0
  }
  return vertexSigns
}

function getEdges(cells, d) {
  var numCells = cells.length
  var maxEdges = ((d * (d+1)/2) * numCells)|0
  var edges    = pool.mallocUint32(maxEdges*2)
  var ePtr     = 0
  for(var i=0; i<numCells; ++i) {
    var c = cells[i]
    var d = c.length
    for(var j=0; j<d; ++j) {
      for(var k=0; k<j; ++k) {
        var a = c[k]
        var b = c[j]
        edges[ePtr++] = Math.min(a,b)|0
        edges[ePtr++] = Math.max(a,b)|0
      }
    }
  }
  var nedges = (ePtr/2)|0
  ndsort(ndarray(edges, [nedges,2])) 
  var ptr = 2
  for(var i=2; i<ePtr; i+=2) {
    if(edges[i-2] === edges[i] &&
       edges[i-1] === edges[i+1]) {
      continue
    }
    edges[ptr++] = edges[i]
    edges[ptr++] = edges[i+1]
  }

  return ndarray(edges, [(ptr/2)|0, 2])
}

function getCrossingWeights(edges, values, signs, level) {
  var edata     = edges.data
  var numEdges  = edges.shape[0]
  var weights   = pool.mallocDouble(numEdges)
  var ptr       = 0
  for(var i=0; i<numEdges; ++i) {
    var a  = edata[2*i]
    var b  = edata[2*i+1]
    if(signs[a] === signs[b]) {
      continue
    }
    var va = values[a]
    var vb = values[b]
    edata[2*ptr]     = a
    edata[2*ptr+1]   = b
    weights[ptr++]   = (vb - level) / (vb - va)
  }
  edges.shape[0] = ptr
  return ndarray(weights, [ptr])
}

function getCascade(edges, numVerts) {
  var result   = pool.mallocInt32(numVerts*2)
  var numEdges = edges.shape[0]
  var edata    = edges.data
  result[0]    = 0
  var lastV    = 0
  for(var i=0; i<numEdges; ++i) {
    var a = edata[2*i]
    if(a !== lastV) {
      result[2*lastV+1] = i
      while(++lastV < a) {
        result[2*lastV] = i
        result[2*lastV+1] = i
      }
      result[2*lastV] = i
    }
  }
  result[2*lastV+1] = numEdges
  while(++lastV < numVerts) {
    result[2*lastV] = result[2*lastV+1] = numEdges
  }
  return result
}

function unpackEdges(edges) {
  var ne = edges.shape[0]|0
  var edata = edges.data
  var result = new Array(ne)
  for(var i=0; i<ne; ++i) {
    result[i] = [edata[2*i], edata[2*i+1]]
  }
  return result
}

function extractContour(cells, values, level, d) {
  level = level||0.0

  //If user didn't specify `d`, use brute force scan
  if(typeof d === 'undefined') {
    d = getDimension(cells)
  }

  //Count number of cells
  var numCells = cells.length
  if(numCells === 0 || d < 1) {
    return {
      cells:         [],
      vertexIds:     [],
      vertexWeights: []
    }
  }

  //Read in vertex signs
  var vertexSigns = getSigns(values, +level)

  //First get 1-skeleton, find all crossings
  var edges   = getEdges(cells, d)
  var weights = getCrossingWeights(edges, values, vertexSigns, +level)

  //Build vertex cascade to speed up binary search
  var vcascade = getCascade(edges, values.length|0)

  //Then construct cells
  var faces = contourAlgorithm(d)(cells, edges.data, vcascade, vertexSigns)

  //Unpack data into pretty format
  var uedges   = unpackEdges(edges)
  var uweights = [].slice.call(weights.data, 0, weights.shape[0])

  //Release data
  pool.free(vertexSigns)
  pool.free(edges.data)
  pool.free(weights.data)
  pool.free(vcascade)
  
  return {
    cells:         faces,
    vertexIds:     uedges,
    vertexWeights: uweights
  }
}
},{"./lib/codegen":500,"ndarray":439,"ndarray-sort":437,"typedarray-pool":526}],500:[function(_dereq_,module,exports){
'use strict'

module.exports = getPolygonizer

var pool = _dereq_('typedarray-pool')
var createMSTable = _dereq_('marching-simplex-table')

var CACHE = {}

function createCellPolygonizer(d) {
  var maxCellSize = 0
  var tables = new Array(d+1)
  tables[0] = [ [] ]
  for(var i=1; i<=d; ++i) {
    var tab = tables[i] = createMSTable(i)
    for(var j=0; j<tab.length; ++j) {
      maxCellSize = Math.max(maxCellSize, tab[i].length)
    }
  }

  var code  = [
  'function B(C,E,i,j){',
    'var a=Math.min(i,j)|0,b=Math.max(i,j)|0,l=C[2*a],h=C[2*a+1];',
    'while(l<h){',
      'var m=(l+h)>>1,v=E[2*m+1];',
      'if(v===b){return m}',
      'if(b<v){h=m}else{l=m+1}',
    '}',
    'return l;',
  '};',
  'function getContour', d, 'd(F,E,C,S){',
    'var n=F.length,R=[];',
    'for(var i=0;i<n;++i){var c=F[i],l=c.length;'
  ]

  function generateCase(facets) {
    if(facets.length <= 0) {
      return
    }
    code.push('R.push(')
    for(var i=0; i<facets.length; ++i) {
      var facet = facets[i]
      if(i > 0) {
        code.push(',')
      }
      code.push('[')
      for(var j=0; j<facet.length; ++j) {
        var f = facet[j]
        if(j > 0) {
          code.push(',')
        }
        code.push('B(C,E,c[', f[0], '],c[', f[1], '])')
      }
      code.push(']')
    }
    code.push(');')
  }

  for(var i=d+1; i>1; --i) {
    if(i < d+1) {
      code.push('else ')
    }
    code.push('if(l===', i, '){')

    //Generate mask
    var maskStr = []
    for(var j=0; j<i; ++j) {
      maskStr.push('(S[c['+j+']]<<'+j+')')
    }

    //Perform table look up
    code.push('var M=', maskStr.join('+'), 
      ';if(M===0||M===', (1<<i)-1, 
        '){continue}switch(M){')

    var tab = tables[i-1]
    for(var j=0; j<tab.length; ++j) {
      code.push('case ', j, ':')
      generateCase(tab[j])
      code.push('break;')
    }
    code.push('}}')
  }
  code.push('}return R;};return getContour', d, 'd')

  var proc = new Function('pool', code.join(''))
  return proc(pool)
}

function getPolygonizer(d) {
  var alg = CACHE[d]
  if(!alg) {
    alg = CACHE[d] = createCellPolygonizer(d) 
  }
  return alg
}
},{"marching-simplex-table":416,"typedarray-pool":526}],501:[function(_dereq_,module,exports){
"use strict"; "use restrict";

var bits      = _dereq_("bit-twiddle")
  , UnionFind = _dereq_("union-find")

//Returns the dimension of a cell complex
function dimension(cells) {
  var d = 0
    , max = Math.max
  for(var i=0, il=cells.length; i<il; ++i) {
    d = max(d, cells[i].length)
  }
  return d-1
}
exports.dimension = dimension

//Counts the number of vertices in faces
function countVertices(cells) {
  var vc = -1
    , max = Math.max
  for(var i=0, il=cells.length; i<il; ++i) {
    var c = cells[i]
    for(var j=0, jl=c.length; j<jl; ++j) {
      vc = max(vc, c[j])
    }
  }
  return vc+1
}
exports.countVertices = countVertices

//Returns a deep copy of cells
function cloneCells(cells) {
  var ncells = new Array(cells.length)
  for(var i=0, il=cells.length; i<il; ++i) {
    ncells[i] = cells[i].slice(0)
  }
  return ncells
}
exports.cloneCells = cloneCells

//Ranks a pair of cells up to permutation
function compareCells(a, b) {
  var n = a.length
    , t = a.length - b.length
    , min = Math.min
  if(t) {
    return t
  }
  switch(n) {
    case 0:
      return 0;
    case 1:
      return a[0] - b[0];
    case 2:
      var d = a[0]+a[1]-b[0]-b[1]
      if(d) {
        return d
      }
      return min(a[0],a[1]) - min(b[0],b[1])
    case 3:
      var l1 = a[0]+a[1]
        , m1 = b[0]+b[1]
      d = l1+a[2] - (m1+b[2])
      if(d) {
        return d
      }
      var l0 = min(a[0], a[1])
        , m0 = min(b[0], b[1])
        , d  = min(l0, a[2]) - min(m0, b[2])
      if(d) {
        return d
      }
      return min(l0+a[2], l1) - min(m0+b[2], m1)
    
    //TODO: Maybe optimize n=4 as well?
    
    default:
      var as = a.slice(0)
      as.sort()
      var bs = b.slice(0)
      bs.sort()
      for(var i=0; i<n; ++i) {
        t = as[i] - bs[i]
        if(t) {
          return t
        }
      }
      return 0
  }
}
exports.compareCells = compareCells

function compareZipped(a, b) {
  return compareCells(a[0], b[0])
}

//Puts a cell complex into normal order for the purposes of findCell queries
function normalize(cells, attr) {
  if(attr) {
    var len = cells.length
    var zipped = new Array(len)
    for(var i=0; i<len; ++i) {
      zipped[i] = [cells[i], attr[i]]
    }
    zipped.sort(compareZipped)
    for(var i=0; i<len; ++i) {
      cells[i] = zipped[i][0]
      attr[i] = zipped[i][1]
    }
    return cells
  } else {
    cells.sort(compareCells)
    return cells
  }
}
exports.normalize = normalize

//Removes all duplicate cells in the complex
function unique(cells) {
  if(cells.length === 0) {
    return []
  }
  var ptr = 1
    , len = cells.length
  for(var i=1; i<len; ++i) {
    var a = cells[i]
    if(compareCells(a, cells[i-1])) {
      if(i === ptr) {
        ptr++
        continue
      }
      cells[ptr++] = a
    }
  }
  cells.length = ptr
  return cells
}
exports.unique = unique;

//Finds a cell in a normalized cell complex
function findCell(cells, c) {
  var lo = 0
    , hi = cells.length-1
    , r  = -1
  while (lo <= hi) {
    var mid = (lo + hi) >> 1
      , s   = compareCells(cells[mid], c)
    if(s <= 0) {
      if(s === 0) {
        r = mid
      }
      lo = mid + 1
    } else if(s > 0) {
      hi = mid - 1
    }
  }
  return r
}
exports.findCell = findCell;

//Builds an index for an n-cell.  This is more general than dual, but less efficient
function incidence(from_cells, to_cells) {
  var index = new Array(from_cells.length)
  for(var i=0, il=index.length; i<il; ++i) {
    index[i] = []
  }
  var b = []
  for(var i=0, n=to_cells.length; i<n; ++i) {
    var c = to_cells[i]
    var cl = c.length
    for(var k=1, kn=(1<<cl); k<kn; ++k) {
      b.length = bits.popCount(k)
      var l = 0
      for(var j=0; j<cl; ++j) {
        if(k & (1<<j)) {
          b[l++] = c[j]
        }
      }
      var idx=findCell(from_cells, b)
      if(idx < 0) {
        continue
      }
      while(true) {
        index[idx++].push(i)
        if(idx >= from_cells.length || compareCells(from_cells[idx], b) !== 0) {
          break
        }
      }
    }
  }
  return index
}
exports.incidence = incidence

//Computes the dual of the mesh.  This is basically an optimized version of buildIndex for the situation where from_cells is just the list of vertices
function dual(cells, vertex_count) {
  if(!vertex_count) {
    return incidence(unique(skeleton(cells, 0)), cells, 0)
  }
  var res = new Array(vertex_count)
  for(var i=0; i<vertex_count; ++i) {
    res[i] = []
  }
  for(var i=0, len=cells.length; i<len; ++i) {
    var c = cells[i]
    for(var j=0, cl=c.length; j<cl; ++j) {
      res[c[j]].push(i)
    }
  }
  return res
}
exports.dual = dual

//Enumerates all cells in the complex
function explode(cells) {
  var result = []
  for(var i=0, il=cells.length; i<il; ++i) {
    var c = cells[i]
      , cl = c.length|0
    for(var j=1, jl=(1<<cl); j<jl; ++j) {
      var b = []
      for(var k=0; k<cl; ++k) {
        if((j >>> k) & 1) {
          b.push(c[k])
        }
      }
      result.push(b)
    }
  }
  return normalize(result)
}
exports.explode = explode

//Enumerates all of the n-cells of a cell complex
function skeleton(cells, n) {
  if(n < 0) {
    return []
  }
  var result = []
    , k0     = (1<<(n+1))-1
  for(var i=0; i<cells.length; ++i) {
    var c = cells[i]
    for(var k=k0; k<(1<<c.length); k=bits.nextCombination(k)) {
      var b = new Array(n+1)
        , l = 0
      for(var j=0; j<c.length; ++j) {
        if(k & (1<<j)) {
          b[l++] = c[j]
        }
      }
      result.push(b)
    }
  }
  return normalize(result)
}
exports.skeleton = skeleton;

//Computes the boundary of all cells, does not remove duplicates
function boundary(cells) {
  var res = []
  for(var i=0,il=cells.length; i<il; ++i) {
    var c = cells[i]
    for(var j=0,cl=c.length; j<cl; ++j) {
      var b = new Array(c.length-1)
      for(var k=0, l=0; k<cl; ++k) {
        if(k !== j) {
          b[l++] = c[k]
        }
      }
      res.push(b)
    }
  }
  return normalize(res)
}
exports.boundary = boundary;

//Computes connected components for a dense cell complex
function connectedComponents_dense(cells, vertex_count) {
  var labels = new UnionFind(vertex_count)
  for(var i=0; i<cells.length; ++i) {
    var c = cells[i]
    for(var j=0; j<c.length; ++j) {
      for(var k=j+1; k<c.length; ++k) {
        labels.link(c[j], c[k])
      }
    }
  }
  var components = []
    , component_labels = labels.ranks
  for(var i=0; i<component_labels.length; ++i) {
    component_labels[i] = -1
  }
  for(var i=0; i<cells.length; ++i) {
    var l = labels.find(cells[i][0])
    if(component_labels[l] < 0) {
      component_labels[l] = components.length
      components.push([cells[i].slice(0)])
    } else {
      components[component_labels[l]].push(cells[i].slice(0))
    }
  }
  return components
}

//Computes connected components for a sparse graph
function connectedComponents_sparse(cells) {
  var vertices  = unique(normalize(skeleton(cells, 0)))
    , labels    = new UnionFind(vertices.length)
  for(var i=0; i<cells.length; ++i) {
    var c = cells[i]
    for(var j=0; j<c.length; ++j) {
      var vj = findCell(vertices, [c[j]])
      for(var k=j+1; k<c.length; ++k) {
        labels.link(vj, findCell(vertices, [c[k]]))
      }
    }
  }
  var components        = []
    , component_labels  = labels.ranks
  for(var i=0; i<component_labels.length; ++i) {
    component_labels[i] = -1
  }
  for(var i=0; i<cells.length; ++i) {
    var l = labels.find(findCell(vertices, [cells[i][0]]));
    if(component_labels[l] < 0) {
      component_labels[l] = components.length
      components.push([cells[i].slice(0)])
    } else {
      components[component_labels[l]].push(cells[i].slice(0))
    }
  }
  return components
}

//Computes connected components for a cell complex
function connectedComponents(cells, vertex_count) {
  if(vertex_count) {
    return connectedComponents_dense(cells, vertex_count)
  }
  return connectedComponents_sparse(cells)
}
exports.connectedComponents = connectedComponents

},{"bit-twiddle":80,"union-find":527}],502:[function(_dereq_,module,exports){
arguments[4][80][0].apply(exports,arguments)
},{"dup":80}],503:[function(_dereq_,module,exports){
arguments[4][501][0].apply(exports,arguments)
},{"bit-twiddle":502,"dup":501,"union-find":504}],504:[function(_dereq_,module,exports){
"use strict"; "use restrict";

module.exports = UnionFind;

function UnionFind(count) {
  this.roots = new Array(count);
  this.ranks = new Array(count);
  
  for(var i=0; i<count; ++i) {
    this.roots[i] = i;
    this.ranks[i] = 0;
  }
}

UnionFind.prototype.length = function() {
  return this.roots.length;
}

UnionFind.prototype.makeSet = function() {
  var n = this.roots.length;
  this.roots.push(n);
  this.ranks.push(0);
  return n;
}

UnionFind.prototype.find = function(x) {
  var roots = this.roots;
  while(roots[x] !== x) {
    var y = roots[x];
    roots[x] = roots[y];
    x = y;
  }
  return x;
}

UnionFind.prototype.link = function(x, y) {
  var xr = this.find(x)
    , yr = this.find(y);
  if(xr === yr) {
    return;
  }
  var ranks = this.ranks
    , roots = this.roots
    , xd    = ranks[xr]
    , yd    = ranks[yr];
  if(xd < yd) {
    roots[xr] = yr;
  } else if(yd < xd) {
    roots[yr] = xr;
  } else {
    roots[yr] = xr;
    ++ranks[xr];
  }
}


},{}],505:[function(_dereq_,module,exports){
"use strict"

module.exports = simplifyPolygon

var orient = _dereq_("robust-orientation")
var sc = _dereq_("simplicial-complex")

function errorWeight(base, a, b) {
  var area = Math.abs(orient(base, a, b))
  var perim = Math.sqrt(Math.pow(a[0] - b[0], 2) + Math.pow(a[1]-b[1], 2))
  return area / perim
}

function simplifyPolygon(cells, positions, minArea) {

  var n = positions.length
  var nc = cells.length
  var inv = new Array(n)
  var outv = new Array(n)
  var weights = new Array(n)
  var dead = new Array(n)
  
  //Initialize tables
  for(var i=0; i<n; ++i) {
    inv[i] = outv[i] = -1
    weights[i] = Infinity
    dead[i] = false
  }

  //Compute neighbors
  for(var i=0; i<nc; ++i) {
    var c = cells[i]
    if(c.length !== 2) {
      throw new Error("Input must be a graph")
    }
    var s = c[1]
    var t = c[0]
    if(outv[t] !== -1) {
      outv[t] = -2
    } else {
      outv[t] = s
    }
    if(inv[s] !== -1) {
      inv[s] = -2
    } else {
      inv[s] = t
    }
  }

  //Updates the weight for vertex i
  function computeWeight(i) {
    if(dead[i]) {
      return Infinity
    }
    //TODO: Check that the line segment doesn't cross once simplified
    var s = inv[i]
    var t = outv[i]
    if((s<0) || (t<0)) {
      return Infinity
    } else {
      return errorWeight(positions[i], positions[s], positions[t])
    }
  }

  //Swaps two nodes on the heap (i,j) are the index of the nodes
  function heapSwap(i,j) {
    var a = heap[i]
    var b = heap[j]
    heap[i] = b
    heap[j] = a
    index[a] = j
    index[b] = i
  }

  //Returns the weight of node i on the heap
  function heapWeight(i) {
    return weights[heap[i]]
  }

  function heapParent(i) {
    if(i & 1) {
      return (i - 1) >> 1
    }
    return (i >> 1) - 1
  }

  //Bubble element i down the heap
  function heapDown(i) {
    var w = heapWeight(i)
    while(true) {
      var tw = w
      var left  = 2*i + 1
      var right = 2*(i + 1)
      var next = i
      if(left < heapCount) {
        var lw = heapWeight(left)
        if(lw < tw) {
          next = left
          tw = lw
        }
      }
      if(right < heapCount) {
        var rw = heapWeight(right)
        if(rw < tw) {
          next = right
        }
      }
      if(next === i) {
        return i
      }
      heapSwap(i, next)
      i = next      
    }
  }

  //Bubbles element i up the heap
  function heapUp(i) {
    var w = heapWeight(i)
    while(i > 0) {
      var parent = heapParent(i)
      if(parent >= 0) {
        var pw = heapWeight(parent)
        if(w < pw) {
          heapSwap(i, parent)
          i = parent
          continue
        }
      }
      return i
    }
  }

  //Pop minimum element
  function heapPop() {
    if(heapCount > 0) {
      var head = heap[0]
      heapSwap(0, heapCount-1)
      heapCount -= 1
      heapDown(0)
      return head
    }
    return -1
  }

  //Update heap item i
  function heapUpdate(i, w) {
    var a = heap[i]
    if(weights[a] === w) {
      return i
    }
    weights[a] = -Infinity
    heapUp(i)
    heapPop()
    weights[a] = w
    heapCount += 1
    return heapUp(heapCount-1)
  }

  //Kills a vertex (assume vertex already removed from heap)
  function kill(i) {
    if(dead[i]) {
      return
    }
    //Kill vertex
    dead[i] = true
    //Fixup topology
    var s = inv[i]
    var t = outv[i]
    if(inv[t] >= 0) {
      inv[t] = s
    }
    if(outv[s] >= 0) {
      outv[s] = t
    }

    //Update weights on s and t
    if(index[s] >= 0) {
      heapUpdate(index[s], computeWeight(s))
    }
    if(index[t] >= 0) {
      heapUpdate(index[t], computeWeight(t))
    }
  }

  //Initialize weights and heap
  var heap = []
  var index = new Array(n)
  for(var i=0; i<n; ++i) {
    var w = weights[i] = computeWeight(i)
    if(w < Infinity) {
      index[i] = heap.length
      heap.push(i)
    } else {
      index[i] = -1
    }
  }
  var heapCount = heap.length
  for(var i=heapCount>>1; i>=0; --i) {
    heapDown(i)
  }
  
  //Kill vertices
  while(true) {
    var hmin = heapPop()
    if((hmin < 0) || (weights[hmin] > minArea)) {
      break
    }
    kill(hmin)
  }

  //Build collapsed vertex table
  var npositions = []
  for(var i=0; i<n; ++i) {
    if(!dead[i]) {
      index[i] = npositions.length
      npositions.push(positions[i].slice())
    }
  }
  var nv = npositions.length

  function tortoiseHare(seq, start) {
    if(seq[start] < 0) {
      return start
    }
    var t = start
    var h = start
    do {
      //Walk two steps with h
      var nh = seq[h]
      if(!dead[h] || nh < 0 || nh === h) {
        break
      }
      h = nh
      nh = seq[h]
      if(!dead[h] || nh < 0 || nh === h) {
        break
      }
      h = nh

      //Walk one step with t
      t = seq[t]
    } while(t !== h)
    //Compress cycles
    for(var v=start; v!==h; v = seq[v]) {
      seq[v] = h
    }
    return h
  }

  var ncells = []
  cells.forEach(function(c) {
    var tin = tortoiseHare(inv, c[0])
    var tout = tortoiseHare(outv, c[1])
    if(tin >= 0 && tout >= 0 && tin !== tout) {
      var cin = index[tin]
      var cout = index[tout]
      if(cin !== cout) {
        ncells.push([ cin, cout ])
      }
    }
  })

  //Normalize result
  sc.unique(sc.normalize(ncells))

  //Return final list of cells
  return {
    positions: npositions,
    edges: ncells
  }
}
},{"robust-orientation":491,"simplicial-complex":503}],506:[function(_dereq_,module,exports){
"use strict"

module.exports = orderSegments

var orient = _dereq_("robust-orientation")

function horizontalOrder(a, b) {
  var bl, br
  if(b[0][0] < b[1][0]) {
    bl = b[0]
    br = b[1]
  } else if(b[0][0] > b[1][0]) {
    bl = b[1]
    br = b[0]
  } else {
    var alo = Math.min(a[0][1], a[1][1])
    var ahi = Math.max(a[0][1], a[1][1])
    var blo = Math.min(b[0][1], b[1][1])
    var bhi = Math.max(b[0][1], b[1][1])
    if(ahi < blo) {
      return ahi - blo
    }
    if(alo > bhi) {
      return alo - bhi
    }
    return ahi - bhi
  }
  var al, ar
  if(a[0][1] < a[1][1]) {
    al = a[0]
    ar = a[1]
  } else {
    al = a[1]
    ar = a[0]
  }
  var d = orient(br, bl, al)
  if(d) {
    return d
  }
  d = orient(br, bl, ar)
  if(d) {
    return d
  }
  return ar - br
}

function orderSegments(b, a) {
  var al, ar
  if(a[0][0] < a[1][0]) {
    al = a[0]
    ar = a[1]
  } else if(a[0][0] > a[1][0]) {
    al = a[1]
    ar = a[0]
  } else {
    return horizontalOrder(a, b)
  }
  var bl, br
  if(b[0][0] < b[1][0]) {
    bl = b[0]
    br = b[1]
  } else if(b[0][0] > b[1][0]) {
    bl = b[1]
    br = b[0]
  } else {
    return -horizontalOrder(b, a)
  }
  var d1 = orient(al, ar, br)
  var d2 = orient(al, ar, bl)
  if(d1 < 0) {
    if(d2 <= 0) {
      return d1
    }
  } else if(d1 > 0) {
    if(d2 >= 0) {
      return d1
    }
  } else if(d2) {
    return d2
  }
  d1 = orient(br, bl, ar)
  d2 = orient(br, bl, al)
  if(d1 < 0) {
    if(d2 <= 0) {
      return d1
    }
  } else if(d1 > 0) {
    if(d2 >= 0) {
      return d1
    }
  } else if(d2) {
    return d2
  }
  return ar[0] - br[0]
}
},{"robust-orientation":491}],507:[function(_dereq_,module,exports){
"use strict"

module.exports = createSlabDecomposition

var bounds = _dereq_("binary-search-bounds")
var createRBTree = _dereq_("functional-red-black-tree")
var orient = _dereq_("robust-orientation")
var orderSegments = _dereq_("./lib/order-segments")

function SlabDecomposition(slabs, coordinates, horizontal) {
  this.slabs = slabs
  this.coordinates = coordinates
  this.horizontal = horizontal
}

var proto = SlabDecomposition.prototype

function compareHorizontal(e, y) {
  return e.y - y
}

function searchBucket(root, p) {
  var lastNode = null
  while(root) {
    var seg = root.key
    var l, r
    if(seg[0][0] < seg[1][0]) {
      l = seg[0]
      r = seg[1]
    } else {
      l = seg[1]
      r = seg[0]
    }
    var o = orient(l, r, p)
    if(o < 0) {
      root = root.left
    } else if(o > 0) {
      if(p[0] !== seg[1][0]) {
        lastNode = root
        root = root.right
      } else {
        var val = searchBucket(root.right, p)
        if(val) {
          return val
        }
        root = root.left
      }
    } else {
      if(p[0] !== seg[1][0]) {
        return root
      } else {
        var val = searchBucket(root.right, p)
        if(val) {
          return val
        }
        root = root.left
      }
    }
  }
  return lastNode
}

proto.castUp = function(p) {
  var bucket = bounds.le(this.coordinates, p[0])
  if(bucket < 0) {
    return -1
  }
  var root = this.slabs[bucket]
  var hitNode = searchBucket(this.slabs[bucket], p)
  var lastHit = -1
  if(hitNode) {
    lastHit = hitNode.value
  }
  //Edge case: need to handle horizontal segments (sucks)
  if(this.coordinates[bucket] === p[0]) {
    var lastSegment = null
    if(hitNode) {
      lastSegment = hitNode.key
    }
    if(bucket > 0) {
      var otherHitNode = searchBucket(this.slabs[bucket-1], p)
      if(otherHitNode) {
        if(lastSegment) {
          if(orderSegments(otherHitNode.key, lastSegment) > 0) {
            lastSegment = otherHitNode.key
            lastHit = otherHitNode.value
          }
        } else {
          lastHit = otherHitNode.value
          lastSegment = otherHitNode.key
        }
      }
    }
    var horiz = this.horizontal[bucket]
    if(horiz.length > 0) {
      var hbucket = bounds.ge(horiz, p[1], compareHorizontal)
      if(hbucket < horiz.length) {
        var e = horiz[hbucket]
        if(p[1] === e.y) {
          if(e.closed) {
            return e.index
          } else {
            while(hbucket < horiz.length-1 && horiz[hbucket+1].y === p[1]) {
              hbucket = hbucket+1
              e = horiz[hbucket]
              if(e.closed) {
                return e.index
              }
            }
            if(e.y === p[1] && !e.start) {
              hbucket = hbucket+1
              if(hbucket >= horiz.length) {
                return lastHit
              }
              e = horiz[hbucket]
            }
          }
        }
        //Check if e is above/below last segment
        if(e.start) {
          if(lastSegment) {
            var o = orient(lastSegment[0], lastSegment[1], [p[0], e.y])
            if(lastSegment[0][0] > lastSegment[1][0]) {
              o = -o
            }
            if(o > 0) {
              lastHit = e.index
            }
          } else {
            lastHit = e.index
          }
        } else if(e.y !== p[1]) {
          lastHit = e.index
        }
      }
    }
  }
  return lastHit
}

function IntervalSegment(y, index, start, closed) {
  this.y = y
  this.index = index
  this.start = start
  this.closed = closed
}

function Event(x, segment, create, index) {
  this.x = x
  this.segment = segment
  this.create = create
  this.index = index
}


function createSlabDecomposition(segments) {
  var numSegments = segments.length
  var numEvents = 2 * numSegments
  var events = new Array(numEvents)
  for(var i=0; i<numSegments; ++i) {
    var s = segments[i]
    var f = s[0][0] < s[1][0]
    events[2*i] = new Event(s[0][0], s, f, i)
    events[2*i+1] = new Event(s[1][0], s, !f, i)
  }
  events.sort(function(a,b) {
    var d = a.x - b.x
    if(d) {
      return d
    }
    d = a.create - b.create
    if(d) {
      return d
    }
    return Math.min(a.segment[0][1], a.segment[1][1]) - Math.min(b.segment[0][1], b.segment[1][1])
  })
  var tree = createRBTree(orderSegments)
  var slabs = []
  var lines = []
  var horizontal = []
  var lastX = -Infinity
  for(var i=0; i<numEvents; ) {
    var x = events[i].x
    var horiz = []
    while(i < numEvents) {
      var e = events[i]
      if(e.x !== x) {
        break
      }
      i += 1
      if(e.segment[0][0] === e.x && e.segment[1][0] === e.x) {
        if(e.create) {
          if(e.segment[0][1] < e.segment[1][1]) {
            horiz.push(new IntervalSegment(
                e.segment[0][1],
                e.index,
                true,
                true))
            horiz.push(new IntervalSegment(
                e.segment[1][1],
                e.index,
                false,
                false))
          } else {
            horiz.push(new IntervalSegment(
                e.segment[1][1],
                e.index,
                true,
                false))
            horiz.push(new IntervalSegment(
                e.segment[0][1],
                e.index,
                false,
                true))
          }
        }
      } else {
        if(e.create) {
          tree = tree.insert(e.segment, e.index)
        } else {
          tree = tree.remove(e.segment)
        }
      }
    }
    slabs.push(tree.root)
    lines.push(x)
    horizontal.push(horiz)
  }
  return new SlabDecomposition(slabs, lines, horizontal)
}
},{"./lib/order-segments":506,"binary-search-bounds":79,"functional-red-black-tree":223,"robust-orientation":491}],508:[function(_dereq_,module,exports){
"use strict"

var robustDot = _dereq_("robust-dot-product")
var robustSum = _dereq_("robust-sum")

module.exports = splitPolygon
module.exports.positive = positive
module.exports.negative = negative

function planeT(p, plane) {
  var r = robustSum(robustDot(p, plane), [plane[plane.length-1]])
  return r[r.length-1]
}


//Can't do this exactly and emit a floating point result
function lerpW(a, wa, b, wb) {
  var d = wb - wa
  var t = -wa / d
  if(t < 0.0) {
    t = 0.0
  } else if(t > 1.0) {
    t = 1.0
  }
  var ti = 1.0 - t
  var n = a.length
  var r = new Array(n)
  for(var i=0; i<n; ++i) {
    r[i] = t * a[i] + ti * b[i]
  }
  return r
}

function splitPolygon(points, plane) {
  var pos = []
  var neg = []
  var a = planeT(points[points.length-1], plane)
  for(var s=points[points.length-1], t=points[0], i=0; i<points.length; ++i, s=t) {
    t = points[i]
    var b = planeT(t, plane)
    if((a < 0 && b > 0) || (a > 0 && b < 0)) {
      var p = lerpW(s, b, t, a)
      pos.push(p)
      neg.push(p.slice())
    }
    if(b < 0) {
      neg.push(t.slice())
    } else if(b > 0) {
      pos.push(t.slice())
    } else {
      pos.push(t.slice())
      neg.push(t.slice())
    }
    a = b
  }
  return { positive: pos, negative: neg }
}

function positive(points, plane) {
  var pos = []
  var a = planeT(points[points.length-1], plane)
  for(var s=points[points.length-1], t=points[0], i=0; i<points.length; ++i, s=t) {
    t = points[i]
    var b = planeT(t, plane)
    if((a < 0 && b > 0) || (a > 0 && b < 0)) {
      pos.push(lerpW(s, b, t, a))
    }
    if(b >= 0) {
      pos.push(t.slice())
    }
    a = b
  }
  return pos
}

function negative(points, plane) {
  var neg = []
  var a = planeT(points[points.length-1], plane)
  for(var s=points[points.length-1], t=points[0], i=0; i<points.length; ++i, s=t) {
    t = points[i]
    var b = planeT(t, plane)
    if((a < 0 && b > 0) || (a > 0 && b < 0)) {
      neg.push(lerpW(s, b, t, a))
    }
    if(b <= 0) {
      neg.push(t.slice())
    }
    a = b
  }
  return neg
}
},{"robust-dot-product":488,"robust-sum":496}],509:[function(_dereq_,module,exports){
/* global window, exports, define */

!function() {
    'use strict'

    var re = {
        not_string: /[^s]/,
        not_bool: /[^t]/,
        not_type: /[^T]/,
        not_primitive: /[^v]/,
        number: /[diefg]/,
        numeric_arg: /[bcdiefguxX]/,
        json: /[j]/,
        not_json: /[^j]/,
        text: /^[^\x25]+/,
        modulo: /^\x25{2}/,
        placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
        key: /^([a-z_][a-z_\d]*)/i,
        key_access: /^\.([a-z_][a-z_\d]*)/i,
        index_access: /^\[(\d+)\]/,
        sign: /^[+-]/
    }

    function sprintf(key) {
        // `arguments` is not an array, but should be fine for this call
        return sprintf_format(sprintf_parse(key), arguments)
    }

    function vsprintf(fmt, argv) {
        return sprintf.apply(null, [fmt].concat(argv || []))
    }

    function sprintf_format(parse_tree, argv) {
        var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign
        for (i = 0; i < tree_length; i++) {
            if (typeof parse_tree[i] === 'string') {
                output += parse_tree[i]
            }
            else if (typeof parse_tree[i] === 'object') {
                ph = parse_tree[i] // convenience purposes only
                if (ph.keys) { // keyword argument
                    arg = argv[cursor]
                    for (k = 0; k < ph.keys.length; k++) {
                        if (arg == undefined) {
                            throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k-1]))
                        }
                        arg = arg[ph.keys[k]]
                    }
                }
                else if (ph.param_no) { // positional argument (explicit)
                    arg = argv[ph.param_no]
                }
                else { // positional argument (implicit)
                    arg = argv[cursor++]
                }

                if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
                    arg = arg()
                }

                if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {
                    throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg))
                }

                if (re.number.test(ph.type)) {
                    is_positive = arg >= 0
                }

                switch (ph.type) {
                    case 'b':
                        arg = parseInt(arg, 10).toString(2)
                        break
                    case 'c':
                        arg = String.fromCharCode(parseInt(arg, 10))
                        break
                    case 'd':
                    case 'i':
                        arg = parseInt(arg, 10)
                        break
                    case 'j':
                        arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0)
                        break
                    case 'e':
                        arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential()
                        break
                    case 'f':
                        arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg)
                        break
                    case 'g':
                        arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg)
                        break
                    case 'o':
                        arg = (parseInt(arg, 10) >>> 0).toString(8)
                        break
                    case 's':
                        arg = String(arg)
                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
                        break
                    case 't':
                        arg = String(!!arg)
                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
                        break
                    case 'T':
                        arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase()
                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
                        break
                    case 'u':
                        arg = parseInt(arg, 10) >>> 0
                        break
                    case 'v':
                        arg = arg.valueOf()
                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
                        break
                    case 'x':
                        arg = (parseInt(arg, 10) >>> 0).toString(16)
                        break
                    case 'X':
                        arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase()
                        break
                }
                if (re.json.test(ph.type)) {
                    output += arg
                }
                else {
                    if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
                        sign = is_positive ? '+' : '-'
                        arg = arg.toString().replace(re.sign, '')
                    }
                    else {
                        sign = ''
                    }
                    pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' '
                    pad_length = ph.width - (sign + arg).length
                    pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : ''
                    output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg)
                }
            }
        }
        return output
    }

    var sprintf_cache = Object.create(null)

    function sprintf_parse(fmt) {
        if (sprintf_cache[fmt]) {
            return sprintf_cache[fmt]
        }

        var _fmt = fmt, match, parse_tree = [], arg_names = 0
        while (_fmt) {
            if ((match = re.text.exec(_fmt)) !== null) {
                parse_tree.push(match[0])
            }
            else if ((match = re.modulo.exec(_fmt)) !== null) {
                parse_tree.push('%')
            }
            else if ((match = re.placeholder.exec(_fmt)) !== null) {
                if (match[2]) {
                    arg_names |= 1
                    var field_list = [], replacement_field = match[2], field_match = []
                    if ((field_match = re.key.exec(replacement_field)) !== null) {
                        field_list.push(field_match[1])
                        while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
                            if ((field_match = re.key_access.exec(replacement_field)) !== null) {
                                field_list.push(field_match[1])
                            }
                            else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
                                field_list.push(field_match[1])
                            }
                            else {
                                throw new SyntaxError('[sprintf] failed to parse named argument key')
                            }
                        }
                    }
                    else {
                        throw new SyntaxError('[sprintf] failed to parse named argument key')
                    }
                    match[2] = field_list
                }
                else {
                    arg_names |= 2
                }
                if (arg_names === 3) {
                    throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported')
                }

                parse_tree.push(
                    {
                        placeholder: match[0],
                        param_no:    match[1],
                        keys:        match[2],
                        sign:        match[3],
                        pad_char:    match[4],
                        align:       match[5],
                        width:       match[6],
                        precision:   match[7],
                        type:        match[8]
                    }
                )
            }
            else {
                throw new SyntaxError('[sprintf] unexpected placeholder')
            }
            _fmt = _fmt.substring(match[0].length)
        }
        return sprintf_cache[fmt] = parse_tree
    }

    /**
     * export to either browser or node.js
     */
    /* eslint-disable quote-props */
    if (typeof exports !== 'undefined') {
        exports['sprintf'] = sprintf
        exports['vsprintf'] = vsprintf
    }
    if (typeof window !== 'undefined') {
        window['sprintf'] = sprintf
        window['vsprintf'] = vsprintf

        if (typeof define === 'function' && define['amd']) {
            define(function() {
                return {
                    'sprintf': sprintf,
                    'vsprintf': vsprintf
                }
            })
        }
    }
    /* eslint-enable quote-props */
}(); // eslint-disable-line

},{}],510:[function(_dereq_,module,exports){
'use strict'

var paren = _dereq_('parenthesis')

module.exports = function splitBy (string, separator, o) {
	if (string == null) throw Error('First argument should be a string')
	if (separator == null) throw Error('Separator should be a string or a RegExp')

	if (!o) o = {}
	else if (typeof o === 'string' || Array.isArray(o)) {
		o = {ignore: o}
	}

	if (o.escape == null) o.escape = true
	if (o.ignore == null) o.ignore = ['[]', '()', '{}', '<>', '""', "''", '``', '“”', '«»']
	else {
		if (typeof o.ignore === 'string') {o.ignore = [o.ignore]}

		o.ignore = o.ignore.map(function (pair) {
			// '"' → '""'
			if (pair.length === 1) pair = pair + pair
			return pair
		})
	}

	var tokens = paren.parse(string, {flat: true, brackets: o.ignore})
	var str = tokens[0]

	var parts = str.split(separator)

	// join parts separated by escape
	if (o.escape) {
		var cleanParts = []
		for (var i = 0; i < parts.length; i++) {
			var prev = parts[i]
			var part = parts[i + 1]

			if (prev[prev.length - 1] === '\\' && prev[prev.length - 2] !== '\\') {
				cleanParts.push(prev + separator + part)
				i++
			}
			else {
				cleanParts.push(prev)
			}
		}
		parts = cleanParts
	}

	// open parens pack & apply unquotes, if any
	for (var i = 0; i < parts.length; i++) {
		tokens[0] = parts[i]
		parts[i] = paren.stringify(tokens, {flat: true})
	}

	return parts
}

},{"parenthesis":447}],511:[function(_dereq_,module,exports){
"use strict"

module.exports = stronglyConnectedComponents

function stronglyConnectedComponents(adjList) {
  var numVertices = adjList.length;
  var index = new Array(numVertices)
  var lowValue = new Array(numVertices)
  var active = new Array(numVertices)
  var child = new Array(numVertices)
  var scc = new Array(numVertices)
  var sccLinks = new Array(numVertices)
  
  //Initialize tables
  for(var i=0; i<numVertices; ++i) {
    index[i] = -1
    lowValue[i] = 0
    active[i] = false
    child[i] = 0
    scc[i] = -1
    sccLinks[i] = []
  }

  // The strongConnect function
  var count = 0
  var components = []
  var sccAdjList = []

  function strongConnect(v) {
    // To avoid running out of stack space, this emulates the recursive behaviour of the normal algorithm, effectively using T as the call stack.
    var S = [v], T = [v]
    index[v] = lowValue[v] = count
    active[v] = true
    count += 1
    while(T.length > 0) {
      v = T[T.length-1]
      var e = adjList[v]
      if (child[v] < e.length) { // If we're not done iterating over the children, first try finishing that.
        for(var i=child[v]; i<e.length; ++i) { // Start where we left off.
          var u = e[i]
          if(index[u] < 0) {
            index[u] = lowValue[u] = count
            active[u] = true
            count += 1
            S.push(u)
            T.push(u)
            break // First recurse, then continue here (with the same child!).
            // There is a slight change to Tarjan's algorithm here.
            // Normally, after having recursed, we set lowValue like we do for an active child (although some variants of the algorithm do it slightly differently).
            // Here, we only do so if the child we recursed on is still active.
            // The reasoning is that if it is no longer active, it must have had a lowValue equal to its own index, which means that it is necessarily higher than our lowValue.
          } else if (active[u]) {
            lowValue[v] = Math.min(lowValue[v], lowValue[u])|0
          }
          if (scc[u] >= 0) {
            // Node v is not yet assigned an scc, but once it is that scc can apparently reach scc[u].
            sccLinks[v].push(scc[u])
          }
        }
        child[v] = i // Remember where we left off.
      } else { // If we're done iterating over the children, check whether we have an scc.
        if(lowValue[v] === index[v]) { // TODO: It /might/ be true that T is always a prefix of S (at this point!!!), and if so, this could be used here.
          var component = []
          var links = [], linkCount = 0
          for(var i=S.length-1; i>=0; --i) {
            var w = S[i]
            active[w] = false
            component.push(w)
            links.push(sccLinks[w])
            linkCount += sccLinks[w].length
            scc[w] = components.length
            if(w === v) {
              S.length = i
              break
            }
          }
          components.push(component)
          var allLinks = new Array(linkCount)
          for(var i=0; i<links.length; i++) {
            for(var j=0; j<links[i].length; j++) {
              allLinks[--linkCount] = links[i][j]
            }
          }
          sccAdjList.push(allLinks)
        }
        T.pop() // Now we're finished exploring this particular node (normally corresponds to the return statement)
      }
    }
  }

  //Run strong connect starting from each vertex
  for(var i=0; i<numVertices; ++i) {
    if(index[i] < 0) {
      strongConnect(i)
    }
  }
  
  // Compact sccAdjList
  var newE
  for(var i=0; i<sccAdjList.length; i++) {
    var e = sccAdjList[i]
    if (e.length === 0) continue
    e.sort(function (a,b) { return a-b; })
    newE = [e[0]]
    for(var j=1; j<e.length; j++) {
      if (e[j] !== e[j-1]) {
        newE.push(e[j])
      }
    }
    sccAdjList[i] = newE
  }  

  return {components: components, adjacencyList: sccAdjList}
}

},{}],512:[function(_dereq_,module,exports){
"use strict"

module.exports = surfaceNets

var generateContourExtractor = _dereq_("ndarray-extract-contour")
var triangulateCube = _dereq_("triangulate-hypercube")
var zeroCrossings = _dereq_("zero-crossings")

function buildSurfaceNets(order, dtype) {
  var dimension = order.length
  var code = ["'use strict';"]
  var funcName = "surfaceNets" + order.join("_") + "d" + dtype

  //Contour extraction function
  code.push(
    "var contour=genContour({",
      "order:[", order.join(), "],",
      "scalarArguments: 3,",
      "phase:function phaseFunc(p,a,b,c) { return (p > c)|0 },")
  if(dtype === "generic") {
    code.push("getters:[0],")
  }

  //Generate vertex function
  var cubeArgs = []
  var extraArgs = []
  for(var i=0; i<dimension; ++i) {
    cubeArgs.push("d" + i)
    extraArgs.push("d" + i)
  }
  for(var i=0; i<(1<<dimension); ++i) {
    cubeArgs.push("v" + i)
    extraArgs.push("v" + i)
  }
  for(var i=0; i<(1<<dimension); ++i) {
    cubeArgs.push("p" + i)
    extraArgs.push("p" + i)
  }
  cubeArgs.push("a", "b", "c")
  extraArgs.push("a", "c")
  code.push("vertex:function vertexFunc(", cubeArgs.join(), "){")
  //Mask args together
  var maskStr = []
  for(var i=0; i<(1<<dimension); ++i) {
    maskStr.push("(p" + i + "<<" + i + ")")
  }
  //Generate variables and giganto switch statement
  code.push("var m=(", maskStr.join("+"), ")|0;if(m===0||m===", (1<<(1<<dimension))-1, "){return}")
  var extraFuncs = []
  var currentFunc = []
  if(1<<(1<<dimension) <= 128) {
    code.push("switch(m){")
    currentFunc = code
  } else {
    code.push("switch(m>>>7){")
  }
  for(var i=0; i<1<<(1<<dimension); ++i) {
    if(1<<(1<<dimension) > 128) {
      if((i%128)===0) {
        if(extraFuncs.length > 0) {
          currentFunc.push("}}")
        }
        var efName = "vExtra" + extraFuncs.length
        code.push("case ", (i>>>7), ":", efName, "(m&0x7f,", extraArgs.join(), ");break;")
        currentFunc = [
          "function ", efName, "(m,", extraArgs.join(), "){switch(m){"
        ]
        extraFuncs.push(currentFunc)
      }  
    }
    currentFunc.push("case ", (i&0x7f), ":")
    var crossings = new Array(dimension)
    var denoms = new Array(dimension)
    var crossingCount = new Array(dimension)
    var bias = new Array(dimension)
    var totalCrossings = 0
    for(var j=0; j<dimension; ++j) {
      crossings[j] = []
      denoms[j] = []
      crossingCount[j] = 0
      bias[j] = 0
    }
    for(var j=0; j<(1<<dimension); ++j) {
      for(var k=0; k<dimension; ++k) {
        var u = j ^ (1<<k)
        if(u > j) {
          continue
        }
        if(!(i&(1<<u)) !== !(i&(1<<j))) {
          var sign = 1
          if(i&(1<<u)) {
            denoms[k].push("v" + u + "-v" + j)
          } else {
            denoms[k].push("v" + j + "-v" + u)
            sign = -sign
          }
          if(sign < 0) {
            crossings[k].push("-v" + j + "-v" + u)
            crossingCount[k] += 2
          } else {
            crossings[k].push("v" + j + "+v" + u)
            crossingCount[k] -= 2            
          }
          totalCrossings += 1
          for(var l=0; l<dimension; ++l) {
            if(l === k) {
              continue
            }
            if(u&(1<<l)) {
              bias[l] += 1
            } else {
              bias[l] -= 1
            }
          }
        }
      }
    }
    var vertexStr = []
    for(var k=0; k<dimension; ++k) {
      if(crossings[k].length === 0) {
        vertexStr.push("d" + k + "-0.5")
      } else {
        var cStr = ""
        if(crossingCount[k] < 0) {
          cStr = crossingCount[k] + "*c"
        } else if(crossingCount[k] > 0) {
          cStr = "+" + crossingCount[k] + "*c"
        }
        var weight = 0.5 * (crossings[k].length / totalCrossings)
        var shift = 0.5 + 0.5 * (bias[k] / totalCrossings)
        vertexStr.push("d" + k + "-" + shift + "-" + weight + "*(" + crossings[k].join("+") + cStr + ")/(" + denoms[k].join("+") + ")")
        
      }
    }
    currentFunc.push("a.push([", vertexStr.join(), "]);",
      "break;")
  }
  code.push("}},")
  if(extraFuncs.length > 0) {
    currentFunc.push("}}")
  }

  //Create face function
  var faceArgs = []
  for(var i=0; i<(1<<(dimension-1)); ++i) {
    faceArgs.push("v" + i)
  }
  faceArgs.push("c0", "c1", "p0", "p1", "a", "b", "c")
  code.push("cell:function cellFunc(", faceArgs.join(), "){")

  var facets = triangulateCube(dimension-1)
  code.push("if(p0){b.push(",
    facets.map(function(f) {
      return "[" + f.map(function(v) {
        return "v" + v
      }) + "]"
    }).join(), ")}else{b.push(",
    facets.map(function(f) {
      var e = f.slice()
      e.reverse()
      return "[" + e.map(function(v) {
        return "v" + v
      }) + "]"
    }).join(),
    ")}}});function ", funcName, "(array,level){var verts=[],cells=[];contour(array,verts,cells,level);return {positions:verts,cells:cells};} return ", funcName, ";")

  for(var i=0; i<extraFuncs.length; ++i) {
    code.push(extraFuncs[i].join(""))
  }

  //Compile and link
  var proc = new Function("genContour", code.join(""))
  return proc(generateContourExtractor)
}

//1D case: Need to handle specially
function mesh1D(array, level) {
  var zc = zeroCrossings(array, level)
  var n = zc.length
  var npos = new Array(n)
  var ncel = new Array(n)
  for(var i=0; i<n; ++i) {
    npos[i] = [ zc[i] ]
    ncel[i] = [ i ]
  }
  return {
    positions: npos,
    cells: ncel
  }
}

var CACHE = {}

function surfaceNets(array,level) {
  if(array.dimension <= 0) {
    return { positions: [], cells: [] }
  } else if(array.dimension === 1) {
    return mesh1D(array, level)
  }
  var typesig = array.order.join() + "-" + array.dtype
  var proc = CACHE[typesig]
  var level = (+level) || 0.0
  if(!proc) {
    proc = CACHE[typesig] = buildSurfaceNets(array.order, array.dtype)
  }
  return proc(array,level)
}
},{"ndarray-extract-contour":428,"triangulate-hypercube":522,"zero-crossings":555}],513:[function(_dereq_,module,exports){
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var TAU = Math.PI * 2;

var mapToEllipse = function mapToEllipse(_ref, rx, ry, cosphi, sinphi, centerx, centery) {
  var x = _ref.x,
      y = _ref.y;

  x *= rx;
  y *= ry;

  var xp = cosphi * x - sinphi * y;
  var yp = sinphi * x + cosphi * y;

  return {
    x: xp + centerx,
    y: yp + centery
  };
};

var approxUnitArc = function approxUnitArc(ang1, ang2) {
  // See http://spencermortensen.com/articles/bezier-circle/ for the derivation
  // of this constant.
  var c = 0.551915024494;

  var x1 = Math.cos(ang1);
  var y1 = Math.sin(ang1);
  var x2 = Math.cos(ang1 + ang2);
  var y2 = Math.sin(ang1 + ang2);

  return [{
    x: x1 - y1 * c,
    y: y1 + x1 * c
  }, {
    x: x2 + y2 * c,
    y: y2 - x2 * c
  }, {
    x: x2,
    y: y2
  }];
};

var vectorAngle = function vectorAngle(ux, uy, vx, vy) {
  var sign = ux * vy - uy * vx < 0 ? -1 : 1;
  var umag = Math.sqrt(ux * ux + uy * uy);
  var vmag = Math.sqrt(ux * ux + uy * uy);
  var dot = ux * vx + uy * vy;

  var div = dot / (umag * vmag);

  if (div > 1) {
    div = 1;
  }

  if (div < -1) {
    div = -1;
  }

  return sign * Math.acos(div);
};

var getArcCenter = function getArcCenter(px, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp) {
  var rxsq = Math.pow(rx, 2);
  var rysq = Math.pow(ry, 2);
  var pxpsq = Math.pow(pxp, 2);
  var pypsq = Math.pow(pyp, 2);

  var radicant = rxsq * rysq - rxsq * pypsq - rysq * pxpsq;

  if (radicant < 0) {
    radicant = 0;
  }

  radicant /= rxsq * pypsq + rysq * pxpsq;
  radicant = Math.sqrt(radicant) * (largeArcFlag === sweepFlag ? -1 : 1);

  var centerxp = radicant * rx / ry * pyp;
  var centeryp = radicant * -ry / rx * pxp;

  var centerx = cosphi * centerxp - sinphi * centeryp + (px + cx) / 2;
  var centery = sinphi * centerxp + cosphi * centeryp + (py + cy) / 2;

  var vx1 = (pxp - centerxp) / rx;
  var vy1 = (pyp - centeryp) / ry;
  var vx2 = (-pxp - centerxp) / rx;
  var vy2 = (-pyp - centeryp) / ry;

  var ang1 = vectorAngle(1, 0, vx1, vy1);
  var ang2 = vectorAngle(vx1, vy1, vx2, vy2);

  if (sweepFlag === 0 && ang2 > 0) {
    ang2 -= TAU;
  }

  if (sweepFlag === 1 && ang2 < 0) {
    ang2 += TAU;
  }

  return [centerx, centery, ang1, ang2];
};

var arcToBezier = function arcToBezier(_ref2) {
  var px = _ref2.px,
      py = _ref2.py,
      cx = _ref2.cx,
      cy = _ref2.cy,
      rx = _ref2.rx,
      ry = _ref2.ry,
      _ref2$xAxisRotation = _ref2.xAxisRotation,
      xAxisRotation = _ref2$xAxisRotation === undefined ? 0 : _ref2$xAxisRotation,
      _ref2$largeArcFlag = _ref2.largeArcFlag,
      largeArcFlag = _ref2$largeArcFlag === undefined ? 0 : _ref2$largeArcFlag,
      _ref2$sweepFlag = _ref2.sweepFlag,
      sweepFlag = _ref2$sweepFlag === undefined ? 0 : _ref2$sweepFlag;

  var curves = [];

  if (rx === 0 || ry === 0) {
    return [];
  }

  var sinphi = Math.sin(xAxisRotation * TAU / 360);
  var cosphi = Math.cos(xAxisRotation * TAU / 360);

  var pxp = cosphi * (px - cx) / 2 + sinphi * (py - cy) / 2;
  var pyp = -sinphi * (px - cx) / 2 + cosphi * (py - cy) / 2;

  if (pxp === 0 && pyp === 0) {
    return [];
  }

  rx = Math.abs(rx);
  ry = Math.abs(ry);

  var lambda = Math.pow(pxp, 2) / Math.pow(rx, 2) + Math.pow(pyp, 2) / Math.pow(ry, 2);

  if (lambda > 1) {
    rx *= Math.sqrt(lambda);
    ry *= Math.sqrt(lambda);
  }

  var _getArcCenter = getArcCenter(px, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp),
      _getArcCenter2 = _slicedToArray(_getArcCenter, 4),
      centerx = _getArcCenter2[0],
      centery = _getArcCenter2[1],
      ang1 = _getArcCenter2[2],
      ang2 = _getArcCenter2[3];

  // If 'ang2' == 90.0000000001, then `ratio` will evaluate to
  // 1.0000000001. This causes `segments` to be greater than one, which is an
  // unecessary split, and adds extra points to the bezier curve. To alleviate
  // this issue, we round to 1.0 when the ratio is close to 1.0.


  var ratio = Math.abs(ang2) / (TAU / 4);
  if (Math.abs(1.0 - ratio) < 0.0000001) {
    ratio = 1.0;
  }

  var segments = Math.max(Math.ceil(ratio), 1);

  ang2 /= segments;

  for (var i = 0; i < segments; i++) {
    curves.push(approxUnitArc(ang1, ang2));
    ang1 += ang2;
  }

  return curves.map(function (curve) {
    var _mapToEllipse = mapToEllipse(curve[0], rx, ry, cosphi, sinphi, centerx, centery),
        x1 = _mapToEllipse.x,
        y1 = _mapToEllipse.y;

    var _mapToEllipse2 = mapToEllipse(curve[1], rx, ry, cosphi, sinphi, centerx, centery),
        x2 = _mapToEllipse2.x,
        y2 = _mapToEllipse2.y;

    var _mapToEllipse3 = mapToEllipse(curve[2], rx, ry, cosphi, sinphi, centerx, centery),
        x = _mapToEllipse3.x,
        y = _mapToEllipse3.y;

    return { x1: x1, y1: y1, x2: x2, y2: y2, x: x, y: y };
  });
};

exports.default = arcToBezier;
module.exports = exports.default;
},{}],514:[function(_dereq_,module,exports){
'use strict'

var parse = _dereq_('parse-svg-path')
var abs = _dereq_('abs-svg-path')
var normalize = _dereq_('normalize-svg-path')
var isSvgPath = _dereq_('is-svg-path')
var assert = _dereq_('assert')

module.exports = pathBounds


function pathBounds(path) {
  // ES6 string tpl call
  if (Array.isArray(path) && path.length === 1 && typeof path[0] === 'string') path = path[0]

  // svg path string
  if (typeof path === 'string') {
    assert(isSvgPath(path), 'String is not an SVG path.')
    path = parse(path)
  }

  assert(Array.isArray(path), 'Argument should be a string or an array of path segments.')

  path = abs(path)
  path = normalize(path)

  if (!path.length) return [0, 0, 0, 0]

  var bounds = [Infinity, Infinity, -Infinity, -Infinity]

  for (var i = 0, l = path.length; i < l; i++) {
    var points = path[i].slice(1)

    for (var j = 0; j < points.length; j += 2) {
      if (points[j + 0] < bounds[0]) bounds[0] = points[j + 0]
      if (points[j + 1] < bounds[1]) bounds[1] = points[j + 1]
      if (points[j + 0] > bounds[2]) bounds[2] = points[j + 0]
      if (points[j + 1] > bounds[3]) bounds[3] = points[j + 1]
    }
  }

  return bounds
}

},{"abs-svg-path":48,"assert":56,"is-svg-path":413,"normalize-svg-path":515,"parse-svg-path":449}],515:[function(_dereq_,module,exports){
'use strict'

module.exports = normalize

var arcToCurve = _dereq_('svg-arc-to-cubic-bezier')

function normalize(path){
  // init state
  var prev
  var result = []
  var bezierX = 0
  var bezierY = 0
  var startX = 0
  var startY = 0
  var quadX = null
  var quadY = null
  var x = 0
  var y = 0

  for (var i = 0, len = path.length; i < len; i++) {
    var seg = path[i]
    var command = seg[0]

    switch (command) {
      case 'M':
        startX = seg[1]
        startY = seg[2]
        break
      case 'A':
        var curves = arcToCurve({
          px: x,
          py: y,
          cx: seg[6],
          cy:  seg[7],
          rx: seg[1],
          ry: seg[2],
          xAxisRotation: seg[3],
          largeArcFlag: seg[4],
          sweepFlag: seg[5]
        })

        // null-curves
        if (!curves.length) continue

        for (var j = 0, c; j < curves.length; j++) {
          c = curves[j]
          seg = ['C', c.x1, c.y1, c.x2, c.y2, c.x, c.y]
          if (j < curves.length - 1) result.push(seg)
        }

        break
      case 'S':
        // default control point
        var cx = x
        var cy = y
        if (prev == 'C' || prev == 'S') {
          cx += cx - bezierX // reflect the previous command's control
          cy += cy - bezierY // point relative to the current point
        }
        seg = ['C', cx, cy, seg[1], seg[2], seg[3], seg[4]]
        break
      case 'T':
        if (prev == 'Q' || prev == 'T') {
          quadX = x * 2 - quadX // as with 'S' reflect previous control point
          quadY = y * 2 - quadY
        } else {
          quadX = x
          quadY = y
        }
        seg = quadratic(x, y, quadX, quadY, seg[1], seg[2])
        break
      case 'Q':
        quadX = seg[1]
        quadY = seg[2]
        seg = quadratic(x, y, seg[1], seg[2], seg[3], seg[4])
        break
      case 'L':
        seg = line(x, y, seg[1], seg[2])
        break
      case 'H':
        seg = line(x, y, seg[1], y)
        break
      case 'V':
        seg = line(x, y, x, seg[1])
        break
      case 'Z':
        seg = line(x, y, startX, startY)
        break
    }

    // update state
    prev = command
    x = seg[seg.length - 2]
    y = seg[seg.length - 1]
    if (seg.length > 4) {
      bezierX = seg[seg.length - 4]
      bezierY = seg[seg.length - 3]
    } else {
      bezierX = x
      bezierY = y
    }
    result.push(seg)
  }

  return result
}

function line(x1, y1, x2, y2){
  return ['C', x1, y1, x2, y2, x2, y2]
}

function quadratic(x1, y1, cx, cy, x2, y2){
  return [
    'C',
    x1/3 + (2/3) * cx,
    y1/3 + (2/3) * cy,
    x2/3 + (2/3) * cx,
    y2/3 + (2/3) * cy,
    x2,
    y2
  ]
}

},{"svg-arc-to-cubic-bezier":513}],516:[function(_dereq_,module,exports){
'use strict'

var pathBounds = _dereq_('svg-path-bounds')
var parsePath = _dereq_('parse-svg-path')
var drawPath = _dereq_('draw-svg-path')
var isSvgPath = _dereq_('is-svg-path')
var bitmapSdf = _dereq_('bitmap-sdf')

var canvas = document.createElement('canvas')
var ctx = canvas.getContext('2d')


module.exports = pathSdf


function pathSdf (path, options) {
	if (!isSvgPath(path)) throw Error('Argument should be valid svg path string')

	if (!options) options = {}

	var w, h
	if (options.shape) {
		w = options.shape[0]
		h = options.shape[1]
	}
	else {
		w = canvas.width = options.w || options.width || 200
		h = canvas.height = options.h || options.height || 200
	}
	var size = Math.min(w, h)

	var stroke = options.stroke || 0

	var viewbox = options.viewbox || options.viewBox || pathBounds(path)
	var scale = [w / (viewbox[2] - viewbox[0]), h / (viewbox[3] - viewbox[1])]
	var maxScale = Math.min(scale[0] || 0, scale[1] || 0) / 2

	//clear ctx
	ctx.fillStyle = 'black'
	ctx.fillRect(0, 0, w, h)

	ctx.fillStyle = 'white'

	if (stroke)	{
		if (typeof stroke != 'number') stroke = 1
		if (stroke > 0) {
			ctx.strokeStyle = 'white'
		}
		else {
			ctx.strokeStyle = 'black'
		}

		ctx.lineWidth = Math.abs(stroke)
	}

	ctx.translate(w * .5, h * .5)
	ctx.scale(maxScale, maxScale)

	//if canvas svg paths api is available
	if (isPath2DSupported()) {
		var path2d = new Path2D(path)
		ctx.fill(path2d)
		stroke && ctx.stroke(path2d)
	}
	//fallback to bezier-curves
	else {
		var segments = parsePath(path)
		drawPath(ctx, segments)
		ctx.fill()
		stroke && ctx.stroke()
	}

	ctx.setTransform(1, 0, 0, 1, 0, 0);

	var data = bitmapSdf(ctx, {
		cutoff: options.cutoff != null ? options.cutoff : .5,
		radius: options.radius != null ? options.radius : size * .5
	})

	return data
}

var path2DSupported

function isPath2DSupported () {
	if (path2DSupported != null) return path2DSupported

	var ctx = document.createElement('canvas').getContext('2d')
	ctx.canvas.width = ctx.canvas.height = 1

	if (!window.Path2D) return path2DSupported = false

	var path = new Path2D('M0,0h1v1h-1v-1Z')

	ctx.fillStyle = 'black'
	ctx.fill(path)

	var idata = ctx.getImageData(0,0,1,1)

	return path2DSupported = idata && idata.data && idata.data[3] === 255
}

},{"bitmap-sdf":81,"draw-svg-path":156,"is-svg-path":413,"parse-svg-path":449,"svg-path-bounds":514}],517:[function(_dereq_,module,exports){
(function (process){
'use strict'

module.exports = textGet

var vectorizeText = _dereq_('vectorize-text')

var globals = window || process.global || {}
var __TEXT_CACHE  = globals.__TEXT_CACHE || {}
globals.__TEXT_CACHE = {}

function unwrap(mesh) {
  var cells     = mesh.cells
  var positions = mesh.positions
  var data      = new Float32Array(cells.length * 6)
  var ptr       = 0
  var shapeX    = 0
  for(var i=0; i<cells.length; ++i) {
    var tri = cells[i]
    for(var j=0; j<3; ++j) {
      var point = positions[tri[j]]
      data[ptr++] = point[0]
      data[ptr++] = point[1] + 1.4
      shapeX      = Math.max(point[0], shapeX)
    }
  }
  return {
    data:  data,
    shape: shapeX
  }
}

function textGet(font, text, opts) {
  var opts = opts || {}
  var fontcache = __TEXT_CACHE[font]
  if(!fontcache) {
    fontcache = __TEXT_CACHE[font] = {
      ' ': {
        data:   new Float32Array(0),
        shape: 0.2
      }
    }
  }
  var mesh = fontcache[text]
  if(!mesh) {
    if(text.length <= 1 || !/\d/.test(text)) {
      mesh = fontcache[text] = unwrap(vectorizeText(text, {
        triangles:     true,
        font:          font,
        textAlign:     opts.textAlign || 'left',
        textBaseline:  'alphabetic',
        styletags: {
            breaklines: true,
                 bolds: true,
               italics: true,
            subscripts: true,
          superscripts: true
        }
      }))
    } else {
      var parts = text.split(/(\d|\s)/)
      var buffer = new Array(parts.length)
      var bufferSize = 0
      var shapeX = 0
      for(var i=0; i<parts.length; ++i) {
        buffer[i] = textGet(font, parts[i])
        bufferSize += buffer[i].data.length
        shapeX += buffer[i].shape
        if(i>0) {
          shapeX += 0.02
        }
      }

      var data = new Float32Array(bufferSize)
      var ptr     = 0
      var xOffset = -0.5 * shapeX
      for(var i=0; i<buffer.length; ++i) {
        var bdata = buffer[i].data
        for(var j=0; j<bdata.length; j+=2) {
          data[ptr++] = bdata[j] + xOffset
          data[ptr++] = bdata[j+1]
        }
        xOffset += buffer[i].shape + 0.02
      }

      mesh = fontcache[text] = {
        data:  data,
        shape: shapeX
      }
    }
  }

   return mesh
}

}).call(this,_dereq_('_process'))
},{"_process":471,"vectorize-text":531}],518:[function(_dereq_,module,exports){
// TinyColor v1.4.1
// https://github.com/bgrins/TinyColor
// Brian Grinstead, MIT License

(function(Math) {

var trimLeft = /^\s+/,
    trimRight = /\s+$/,
    tinyCounter = 0,
    mathRound = Math.round,
    mathMin = Math.min,
    mathMax = Math.max,
    mathRandom = Math.random;

function tinycolor (color, opts) {

    color = (color) ? color : '';
    opts = opts || { };

    // If input is already a tinycolor, return itself
    if (color instanceof tinycolor) {
       return color;
    }
    // If we are called as a function, call using new instead
    if (!(this instanceof tinycolor)) {
        return new tinycolor(color, opts);
    }

    var rgb = inputToRGB(color);
    this._originalInput = color,
    this._r = rgb.r,
    this._g = rgb.g,
    this._b = rgb.b,
    this._a = rgb.a,
    this._roundA = mathRound(100*this._a) / 100,
    this._format = opts.format || rgb.format;
    this._gradientType = opts.gradientType;

    // Don't let the range of [0,255] come back in [0,1].
    // Potentially lose a little bit of precision here, but will fix issues where
    // .5 gets interpreted as half of the total, instead of half of 1
    // If it was supposed to be 128, this was already taken care of by `inputToRgb`
    if (this._r < 1) { this._r = mathRound(this._r); }
    if (this._g < 1) { this._g = mathRound(this._g); }
    if (this._b < 1) { this._b = mathRound(this._b); }

    this._ok = rgb.ok;
    this._tc_id = tinyCounter++;
}

tinycolor.prototype = {
    isDark: function() {
        return this.getBrightness() < 128;
    },
    isLight: function() {
        return !this.isDark();
    },
    isValid: function() {
        return this._ok;
    },
    getOriginalInput: function() {
      return this._originalInput;
    },
    getFormat: function() {
        return this._format;
    },
    getAlpha: function() {
        return this._a;
    },
    getBrightness: function() {
        //http://www.w3.org/TR/AERT#color-contrast
        var rgb = this.toRgb();
        return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
    },
    getLuminance: function() {
        //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
        var rgb = this.toRgb();
        var RsRGB, GsRGB, BsRGB, R, G, B;
        RsRGB = rgb.r/255;
        GsRGB = rgb.g/255;
        BsRGB = rgb.b/255;

        if (RsRGB <= 0.03928) {R = RsRGB / 12.92;} else {R = Math.pow(((RsRGB + 0.055) / 1.055), 2.4);}
        if (GsRGB <= 0.03928) {G = GsRGB / 12.92;} else {G = Math.pow(((GsRGB + 0.055) / 1.055), 2.4);}
        if (BsRGB <= 0.03928) {B = BsRGB / 12.92;} else {B = Math.pow(((BsRGB + 0.055) / 1.055), 2.4);}
        return (0.2126 * R) + (0.7152 * G) + (0.0722 * B);
    },
    setAlpha: function(value) {
        this._a = boundAlpha(value);
        this._roundA = mathRound(100*this._a) / 100;
        return this;
    },
    toHsv: function() {
        var hsv = rgbToHsv(this._r, this._g, this._b);
        return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };
    },
    toHsvString: function() {
        var hsv = rgbToHsv(this._r, this._g, this._b);
        var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);
        return (this._a == 1) ?
          "hsv("  + h + ", " + s + "%, " + v + "%)" :
          "hsva(" + h + ", " + s + "%, " + v + "%, "+ this._roundA + ")";
    },
    toHsl: function() {
        var hsl = rgbToHsl(this._r, this._g, this._b);
        return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };
    },
    toHslString: function() {
        var hsl = rgbToHsl(this._r, this._g, this._b);
        var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);
        return (this._a == 1) ?
          "hsl("  + h + ", " + s + "%, " + l + "%)" :
          "hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")";
    },
    toHex: function(allow3Char) {
        return rgbToHex(this._r, this._g, this._b, allow3Char);
    },
    toHexString: function(allow3Char) {
        return '#' + this.toHex(allow3Char);
    },
    toHex8: function(allow4Char) {
        return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char);
    },
    toHex8String: function(allow4Char) {
        return '#' + this.toHex8(allow4Char);
    },
    toRgb: function() {
        return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a };
    },
    toRgbString: function() {
        return (this._a == 1) ?
          "rgb("  + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" :
          "rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")";
    },
    toPercentageRgb: function() {
        return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a };
    },
    toPercentageRgbString: function() {
        return (this._a == 1) ?
          "rgb("  + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" :
          "rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")";
    },
    toName: function() {
        if (this._a === 0) {
            return "transparent";
        }

        if (this._a < 1) {
            return false;
        }

        return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
    },
    toFilter: function(secondColor) {
        var hex8String = '#' + rgbaToArgbHex(this._r, this._g, this._b, this._a);
        var secondHex8String = hex8String;
        var gradientType = this._gradientType ? "GradientType = 1, " : "";

        if (secondColor) {
            var s = tinycolor(secondColor);
            secondHex8String = '#' + rgbaToArgbHex(s._r, s._g, s._b, s._a);
        }

        return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")";
    },
    toString: function(format) {
        var formatSet = !!format;
        format = format || this._format;

        var formattedString = false;
        var hasAlpha = this._a < 1 && this._a >= 0;
        var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name");

        if (needsAlphaFormat) {
            // Special case for "transparent", all other non-alpha formats
            // will return rgba when there is transparency.
            if (format === "name" && this._a === 0) {
                return this.toName();
            }
            return this.toRgbString();
        }
        if (format === "rgb") {
            formattedString = this.toRgbString();
        }
        if (format === "prgb") {
            formattedString = this.toPercentageRgbString();
        }
        if (format === "hex" || format === "hex6") {
            formattedString = this.toHexString();
        }
        if (format === "hex3") {
            formattedString = this.toHexString(true);
        }
        if (format === "hex4") {
            formattedString = this.toHex8String(true);
        }
        if (format === "hex8") {
            formattedString = this.toHex8String();
        }
        if (format === "name") {
            formattedString = this.toName();
        }
        if (format === "hsl") {
            formattedString = this.toHslString();
        }
        if (format === "hsv") {
            formattedString = this.toHsvString();
        }

        return formattedString || this.toHexString();
    },
    clone: function() {
        return tinycolor(this.toString());
    },

    _applyModification: function(fn, args) {
        var color = fn.apply(null, [this].concat([].slice.call(args)));
        this._r = color._r;
        this._g = color._g;
        this._b = color._b;
        this.setAlpha(color._a);
        return this;
    },
    lighten: function() {
        return this._applyModification(lighten, arguments);
    },
    brighten: function() {
        return this._applyModification(brighten, arguments);
    },
    darken: function() {
        return this._applyModification(darken, arguments);
    },
    desaturate: function() {
        return this._applyModification(desaturate, arguments);
    },
    saturate: function() {
        return this._applyModification(saturate, arguments);
    },
    greyscale: function() {
        return this._applyModification(greyscale, arguments);
    },
    spin: function() {
        return this._applyModification(spin, arguments);
    },

    _applyCombination: function(fn, args) {
        return fn.apply(null, [this].concat([].slice.call(args)));
    },
    analogous: function() {
        return this._applyCombination(analogous, arguments);
    },
    complement: function() {
        return this._applyCombination(complement, arguments);
    },
    monochromatic: function() {
        return this._applyCombination(monochromatic, arguments);
    },
    splitcomplement: function() {
        return this._applyCombination(splitcomplement, arguments);
    },
    triad: function() {
        return this._applyCombination(triad, arguments);
    },
    tetrad: function() {
        return this._applyCombination(tetrad, arguments);
    }
};

// If input is an object, force 1 into "1.0" to handle ratios properly
// String input requires "1.0" as input, so 1 will be treated as 1
tinycolor.fromRatio = function(color, opts) {
    if (typeof color == "object") {
        var newColor = {};
        for (var i in color) {
            if (color.hasOwnProperty(i)) {
                if (i === "a") {
                    newColor[i] = color[i];
                }
                else {
                    newColor[i] = convertToPercentage(color[i]);
                }
            }
        }
        color = newColor;
    }

    return tinycolor(color, opts);
};

// Given a string or object, convert that input to RGB
// Possible string inputs:
//
//     "red"
//     "#f00" or "f00"
//     "#ff0000" or "ff0000"
//     "#ff000000" or "ff000000"
//     "rgb 255 0 0" or "rgb (255, 0, 0)"
//     "rgb 1.0 0 0" or "rgb (1, 0, 0)"
//     "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
//     "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
//     "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
//     "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
//     "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
//
function inputToRGB(color) {

    var rgb = { r: 0, g: 0, b: 0 };
    var a = 1;
    var s = null;
    var v = null;
    var l = null;
    var ok = false;
    var format = false;

    if (typeof color == "string") {
        color = stringInputToObject(color);
    }

    if (typeof color == "object") {
        if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) {
            rgb = rgbToRgb(color.r, color.g, color.b);
            ok = true;
            format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
        }
        else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) {
            s = convertToPercentage(color.s);
            v = convertToPercentage(color.v);
            rgb = hsvToRgb(color.h, s, v);
            ok = true;
            format = "hsv";
        }
        else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) {
            s = convertToPercentage(color.s);
            l = convertToPercentage(color.l);
            rgb = hslToRgb(color.h, s, l);
            ok = true;
            format = "hsl";
        }

        if (color.hasOwnProperty("a")) {
            a = color.a;
        }
    }

    a = boundAlpha(a);

    return {
        ok: ok,
        format: color.format || format,
        r: mathMin(255, mathMax(rgb.r, 0)),
        g: mathMin(255, mathMax(rgb.g, 0)),
        b: mathMin(255, mathMax(rgb.b, 0)),
        a: a
    };
}


// Conversion Functions
// --------------------

// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
// <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript>

// `rgbToRgb`
// Handle bounds / percentage checking to conform to CSS color spec
// <http://www.w3.org/TR/css3-color/>
// *Assumes:* r, g, b in [0, 255] or [0, 1]
// *Returns:* { r, g, b } in [0, 255]
function rgbToRgb(r, g, b){
    return {
        r: bound01(r, 255) * 255,
        g: bound01(g, 255) * 255,
        b: bound01(b, 255) * 255
    };
}

// `rgbToHsl`
// Converts an RGB color value to HSL.
// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]
// *Returns:* { h, s, l } in [0,1]
function rgbToHsl(r, g, b) {

    r = bound01(r, 255);
    g = bound01(g, 255);
    b = bound01(b, 255);

    var max = mathMax(r, g, b), min = mathMin(r, g, b);
    var h, s, l = (max + min) / 2;

    if(max == min) {
        h = s = 0; // achromatic
    }
    else {
        var d = max - min;
        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
        switch(max) {
            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
            case g: h = (b - r) / d + 2; break;
            case b: h = (r - g) / d + 4; break;
        }

        h /= 6;
    }

    return { h: h, s: s, l: l };
}

// `hslToRgb`
// Converts an HSL color value to RGB.
// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]
// *Returns:* { r, g, b } in the set [0, 255]
function hslToRgb(h, s, l) {
    var r, g, b;

    h = bound01(h, 360);
    s = bound01(s, 100);
    l = bound01(l, 100);

    function hue2rgb(p, q, t) {
        if(t < 0) t += 1;
        if(t > 1) t -= 1;
        if(t < 1/6) return p + (q - p) * 6 * t;
        if(t < 1/2) return q;
        if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
        return p;
    }

    if(s === 0) {
        r = g = b = l; // achromatic
    }
    else {
        var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
        var p = 2 * l - q;
        r = hue2rgb(p, q, h + 1/3);
        g = hue2rgb(p, q, h);
        b = hue2rgb(p, q, h - 1/3);
    }

    return { r: r * 255, g: g * 255, b: b * 255 };
}

// `rgbToHsv`
// Converts an RGB color value to HSV
// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]
// *Returns:* { h, s, v } in [0,1]
function rgbToHsv(r, g, b) {

    r = bound01(r, 255);
    g = bound01(g, 255);
    b = bound01(b, 255);

    var max = mathMax(r, g, b), min = mathMin(r, g, b);
    var h, s, v = max;

    var d = max - min;
    s = max === 0 ? 0 : d / max;

    if(max == min) {
        h = 0; // achromatic
    }
    else {
        switch(max) {
            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
            case g: h = (b - r) / d + 2; break;
            case b: h = (r - g) / d + 4; break;
        }
        h /= 6;
    }
    return { h: h, s: s, v: v };
}

// `hsvToRgb`
// Converts an HSV color value to RGB.
// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]
// *Returns:* { r, g, b } in the set [0, 255]
 function hsvToRgb(h, s, v) {

    h = bound01(h, 360) * 6;
    s = bound01(s, 100);
    v = bound01(v, 100);

    var i = Math.floor(h),
        f = h - i,
        p = v * (1 - s),
        q = v * (1 - f * s),
        t = v * (1 - (1 - f) * s),
        mod = i % 6,
        r = [v, q, p, p, t, v][mod],
        g = [t, v, v, q, p, p][mod],
        b = [p, p, t, v, v, q][mod];

    return { r: r * 255, g: g * 255, b: b * 255 };
}

// `rgbToHex`
// Converts an RGB color to hex
// Assumes r, g, and b are contained in the set [0, 255]
// Returns a 3 or 6 character hex
function rgbToHex(r, g, b, allow3Char) {

    var hex = [
        pad2(mathRound(r).toString(16)),
        pad2(mathRound(g).toString(16)),
        pad2(mathRound(b).toString(16))
    ];

    // Return a 3 character hex if possible
    if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
        return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
    }

    return hex.join("");
}

// `rgbaToHex`
// Converts an RGBA color plus alpha transparency to hex
// Assumes r, g, b are contained in the set [0, 255] and
// a in [0, 1]. Returns a 4 or 8 character rgba hex
function rgbaToHex(r, g, b, a, allow4Char) {

    var hex = [
        pad2(mathRound(r).toString(16)),
        pad2(mathRound(g).toString(16)),
        pad2(mathRound(b).toString(16)),
        pad2(convertDecimalToHex(a))
    ];

    // Return a 4 character hex if possible
    if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) {
        return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0);
    }

    return hex.join("");
}

// `rgbaToArgbHex`
// Converts an RGBA color to an ARGB Hex8 string
// Rarely used, but required for "toFilter()"
function rgbaToArgbHex(r, g, b, a) {

    var hex = [
        pad2(convertDecimalToHex(a)),
        pad2(mathRound(r).toString(16)),
        pad2(mathRound(g).toString(16)),
        pad2(mathRound(b).toString(16))
    ];

    return hex.join("");
}

// `equals`
// Can be called with any tinycolor input
tinycolor.equals = function (color1, color2) {
    if (!color1 || !color2) { return false; }
    return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
};

tinycolor.random = function() {
    return tinycolor.fromRatio({
        r: mathRandom(),
        g: mathRandom(),
        b: mathRandom()
    });
};


// Modification Functions
// ----------------------
// Thanks to less.js for some of the basics here
// <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js>

function desaturate(color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var hsl = tinycolor(color).toHsl();
    hsl.s -= amount / 100;
    hsl.s = clamp01(hsl.s);
    return tinycolor(hsl);
}

function saturate(color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var hsl = tinycolor(color).toHsl();
    hsl.s += amount / 100;
    hsl.s = clamp01(hsl.s);
    return tinycolor(hsl);
}

function greyscale(color) {
    return tinycolor(color).desaturate(100);
}

function lighten (color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var hsl = tinycolor(color).toHsl();
    hsl.l += amount / 100;
    hsl.l = clamp01(hsl.l);
    return tinycolor(hsl);
}

function brighten(color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var rgb = tinycolor(color).toRgb();
    rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100))));
    rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100))));
    rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100))));
    return tinycolor(rgb);
}

function darken (color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var hsl = tinycolor(color).toHsl();
    hsl.l -= amount / 100;
    hsl.l = clamp01(hsl.l);
    return tinycolor(hsl);
}

// Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.
// Values outside of this range will be wrapped into this range.
function spin(color, amount) {
    var hsl = tinycolor(color).toHsl();
    var hue = (hsl.h + amount) % 360;
    hsl.h = hue < 0 ? 360 + hue : hue;
    return tinycolor(hsl);
}

// Combination Functions
// ---------------------
// Thanks to jQuery xColor for some of the ideas behind these
// <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js>

function complement(color) {
    var hsl = tinycolor(color).toHsl();
    hsl.h = (hsl.h + 180) % 360;
    return tinycolor(hsl);
}

function triad(color) {
    var hsl = tinycolor(color).toHsl();
    var h = hsl.h;
    return [
        tinycolor(color),
        tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),
        tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l })
    ];
}

function tetrad(color) {
    var hsl = tinycolor(color).toHsl();
    var h = hsl.h;
    return [
        tinycolor(color),
        tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),
        tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),
        tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l })
    ];
}

function splitcomplement(color) {
    var hsl = tinycolor(color).toHsl();
    var h = hsl.h;
    return [
        tinycolor(color),
        tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}),
        tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l})
    ];
}

function analogous(color, results, slices) {
    results = results || 6;
    slices = slices || 30;

    var hsl = tinycolor(color).toHsl();
    var part = 360 / slices;
    var ret = [tinycolor(color)];

    for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) {
        hsl.h = (hsl.h + part) % 360;
        ret.push(tinycolor(hsl));
    }
    return ret;
}

function monochromatic(color, results) {
    results = results || 6;
    var hsv = tinycolor(color).toHsv();
    var h = hsv.h, s = hsv.s, v = hsv.v;
    var ret = [];
    var modification = 1 / results;

    while (results--) {
        ret.push(tinycolor({ h: h, s: s, v: v}));
        v = (v + modification) % 1;
    }

    return ret;
}

// Utility Functions
// ---------------------

tinycolor.mix = function(color1, color2, amount) {
    amount = (amount === 0) ? 0 : (amount || 50);

    var rgb1 = tinycolor(color1).toRgb();
    var rgb2 = tinycolor(color2).toRgb();

    var p = amount / 100;

    var rgba = {
        r: ((rgb2.r - rgb1.r) * p) + rgb1.r,
        g: ((rgb2.g - rgb1.g) * p) + rgb1.g,
        b: ((rgb2.b - rgb1.b) * p) + rgb1.b,
        a: ((rgb2.a - rgb1.a) * p) + rgb1.a
    };

    return tinycolor(rgba);
};


// Readability Functions
// ---------------------
// <http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef (WCAG Version 2)

// `contrast`
// Analyze the 2 colors and returns the color contrast defined by (WCAG Version 2)
tinycolor.readability = function(color1, color2) {
    var c1 = tinycolor(color1);
    var c2 = tinycolor(color2);
    return (Math.max(c1.getLuminance(),c2.getLuminance())+0.05) / (Math.min(c1.getLuminance(),c2.getLuminance())+0.05);
};

// `isReadable`
// Ensure that foreground and background color combinations meet WCAG2 guidelines.
// The third argument is an optional Object.
//      the 'level' property states 'AA' or 'AAA' - if missing or invalid, it defaults to 'AA';
//      the 'size' property states 'large' or 'small' - if missing or invalid, it defaults to 'small'.
// If the entire object is absent, isReadable defaults to {level:"AA",size:"small"}.

// *Example*
//    tinycolor.isReadable("#000", "#111") => false
//    tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false
tinycolor.isReadable = function(color1, color2, wcag2) {
    var readability = tinycolor.readability(color1, color2);
    var wcag2Parms, out;

    out = false;

    wcag2Parms = validateWCAG2Parms(wcag2);
    switch (wcag2Parms.level + wcag2Parms.size) {
        case "AAsmall":
        case "AAAlarge":
            out = readability >= 4.5;
            break;
        case "AAlarge":
            out = readability >= 3;
            break;
        case "AAAsmall":
            out = readability >= 7;
            break;
    }
    return out;

};

// `mostReadable`
// Given a base color and a list of possible foreground or background
// colors for that base, returns the most readable color.
// Optionally returns Black or White if the most readable color is unreadable.
// *Example*
//    tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255"
//    tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString();  // "#ffffff"
//    tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3"
//    tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff"
tinycolor.mostReadable = function(baseColor, colorList, args) {
    var bestColor = null;
    var bestScore = 0;
    var readability;
    var includeFallbackColors, level, size ;
    args = args || {};
    includeFallbackColors = args.includeFallbackColors ;
    level = args.level;
    size = args.size;

    for (var i= 0; i < colorList.length ; i++) {
        readability = tinycolor.readability(baseColor, colorList[i]);
        if (readability > bestScore) {
            bestScore = readability;
            bestColor = tinycolor(colorList[i]);
        }
    }

    if (tinycolor.isReadable(baseColor, bestColor, {"level":level,"size":size}) || !includeFallbackColors) {
        return bestColor;
    }
    else {
        args.includeFallbackColors=false;
        return tinycolor.mostReadable(baseColor,["#fff", "#000"],args);
    }
};


// Big List of Colors
// ------------------
// <http://www.w3.org/TR/css3-color/#svg-color>
var names = tinycolor.names = {
    aliceblue: "f0f8ff",
    antiquewhite: "faebd7",
    aqua: "0ff",
    aquamarine: "7fffd4",
    azure: "f0ffff",
    beige: "f5f5dc",
    bisque: "ffe4c4",
    black: "000",
    blanchedalmond: "ffebcd",
    blue: "00f",
    blueviolet: "8a2be2",
    brown: "a52a2a",
    burlywood: "deb887",
    burntsienna: "ea7e5d",
    cadetblue: "5f9ea0",
    chartreuse: "7fff00",
    chocolate: "d2691e",
    coral: "ff7f50",
    cornflowerblue: "6495ed",
    cornsilk: "fff8dc",
    crimson: "dc143c",
    cyan: "0ff",
    darkblue: "00008b",
    darkcyan: "008b8b",
    darkgoldenrod: "b8860b",
    darkgray: "a9a9a9",
    darkgreen: "006400",
    darkgrey: "a9a9a9",
    darkkhaki: "bdb76b",
    darkmagenta: "8b008b",
    darkolivegreen: "556b2f",
    darkorange: "ff8c00",
    darkorchid: "9932cc",
    darkred: "8b0000",
    darksalmon: "e9967a",
    darkseagreen: "8fbc8f",
    darkslateblue: "483d8b",
    darkslategray: "2f4f4f",
    darkslategrey: "2f4f4f",
    darkturquoise: "00ced1",
    darkviolet: "9400d3",
    deeppink: "ff1493",
    deepskyblue: "00bfff",
    dimgray: "696969",
    dimgrey: "696969",
    dodgerblue: "1e90ff",
    firebrick: "b22222",
    floralwhite: "fffaf0",
    forestgreen: "228b22",
    fuchsia: "f0f",
    gainsboro: "dcdcdc",
    ghostwhite: "f8f8ff",
    gold: "ffd700",
    goldenrod: "daa520",
    gray: "808080",
    green: "008000",
    greenyellow: "adff2f",
    grey: "808080",
    honeydew: "f0fff0",
    hotpink: "ff69b4",
    indianred: "cd5c5c",
    indigo: "4b0082",
    ivory: "fffff0",
    khaki: "f0e68c",
    lavender: "e6e6fa",
    lavenderblush: "fff0f5",
    lawngreen: "7cfc00",
    lemonchiffon: "fffacd",
    lightblue: "add8e6",
    lightcoral: "f08080",
    lightcyan: "e0ffff",
    lightgoldenrodyellow: "fafad2",
    lightgray: "d3d3d3",
    lightgreen: "90ee90",
    lightgrey: "d3d3d3",
    lightpink: "ffb6c1",
    lightsalmon: "ffa07a",
    lightseagreen: "20b2aa",
    lightskyblue: "87cefa",
    lightslategray: "789",
    lightslategrey: "789",
    lightsteelblue: "b0c4de",
    lightyellow: "ffffe0",
    lime: "0f0",
    limegreen: "32cd32",
    linen: "faf0e6",
    magenta: "f0f",
    maroon: "800000",
    mediumaquamarine: "66cdaa",
    mediumblue: "0000cd",
    mediumorchid: "ba55d3",
    mediumpurple: "9370db",
    mediumseagreen: "3cb371",
    mediumslateblue: "7b68ee",
    mediumspringgreen: "00fa9a",
    mediumturquoise: "48d1cc",
    mediumvioletred: "c71585",
    midnightblue: "191970",
    mintcream: "f5fffa",
    mistyrose: "ffe4e1",
    moccasin: "ffe4b5",
    navajowhite: "ffdead",
    navy: "000080",
    oldlace: "fdf5e6",
    olive: "808000",
    olivedrab: "6b8e23",
    orange: "ffa500",
    orangered: "ff4500",
    orchid: "da70d6",
    palegoldenrod: "eee8aa",
    palegreen: "98fb98",
    paleturquoise: "afeeee",
    palevioletred: "db7093",
    papayawhip: "ffefd5",
    peachpuff: "ffdab9",
    peru: "cd853f",
    pink: "ffc0cb",
    plum: "dda0dd",
    powderblue: "b0e0e6",
    purple: "800080",
    rebeccapurple: "663399",
    red: "f00",
    rosybrown: "bc8f8f",
    royalblue: "4169e1",
    saddlebrown: "8b4513",
    salmon: "fa8072",
    sandybrown: "f4a460",
    seagreen: "2e8b57",
    seashell: "fff5ee",
    sienna: "a0522d",
    silver: "c0c0c0",
    skyblue: "87ceeb",
    slateblue: "6a5acd",
    slategray: "708090",
    slategrey: "708090",
    snow: "fffafa",
    springgreen: "00ff7f",
    steelblue: "4682b4",
    tan: "d2b48c",
    teal: "008080",
    thistle: "d8bfd8",
    tomato: "ff6347",
    turquoise: "40e0d0",
    violet: "ee82ee",
    wheat: "f5deb3",
    white: "fff",
    whitesmoke: "f5f5f5",
    yellow: "ff0",
    yellowgreen: "9acd32"
};

// Make it easy to access colors via `hexNames[hex]`
var hexNames = tinycolor.hexNames = flip(names);


// Utilities
// ---------

// `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`
function flip(o) {
    var flipped = { };
    for (var i in o) {
        if (o.hasOwnProperty(i)) {
            flipped[o[i]] = i;
        }
    }
    return flipped;
}

// Return a valid alpha value [0,1] with all invalid values being set to 1
function boundAlpha(a) {
    a = parseFloat(a);

    if (isNaN(a) || a < 0 || a > 1) {
        a = 1;
    }

    return a;
}

// Take input from [0, n] and return it as [0, 1]
function bound01(n, max) {
    if (isOnePointZero(n)) { n = "100%"; }

    var processPercent = isPercentage(n);
    n = mathMin(max, mathMax(0, parseFloat(n)));

    // Automatically convert percentage into number
    if (processPercent) {
        n = parseInt(n * max, 10) / 100;
    }

    // Handle floating point rounding errors
    if ((Math.abs(n - max) < 0.000001)) {
        return 1;
    }

    // Convert into [0, 1] range if it isn't already
    return (n % max) / parseFloat(max);
}

// Force a number between 0 and 1
function clamp01(val) {
    return mathMin(1, mathMax(0, val));
}

// Parse a base-16 hex value into a base-10 integer
function parseIntFromHex(val) {
    return parseInt(val, 16);
}

// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
// <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
function isOnePointZero(n) {
    return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1;
}

// Check to see if string passed in is a percentage
function isPercentage(n) {
    return typeof n === "string" && n.indexOf('%') != -1;
}

// Force a hex value to have 2 characters
function pad2(c) {
    return c.length == 1 ? '0' + c : '' + c;
}

// Replace a decimal with it's percentage value
function convertToPercentage(n) {
    if (n <= 1) {
        n = (n * 100) + "%";
    }

    return n;
}

// Converts a decimal to a hex value
function convertDecimalToHex(d) {
    return Math.round(parseFloat(d) * 255).toString(16);
}
// Converts a hex value to a decimal
function convertHexToDecimal(h) {
    return (parseIntFromHex(h) / 255);
}

var matchers = (function() {

    // <http://www.w3.org/TR/css3-values/#integers>
    var CSS_INTEGER = "[-\\+]?\\d+%?";

    // <http://www.w3.org/TR/css3-values/#number-value>
    var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";

    // Allow positive/negative integer/number.  Don't capture the either/or, just the entire outcome.
    var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";

    // Actual matching.
    // Parentheses and commas are optional, but not required.
    // Whitespace can take the place of commas or opening paren
    var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
    var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";

    return {
        CSS_UNIT: new RegExp(CSS_UNIT),
        rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
        rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
        hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
        hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
        hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
        hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
        hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
        hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
        hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
        hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
    };
})();

// `isValidCSSUnit`
// Take in a single string / number and check to see if it looks like a CSS unit
// (see `matchers` above for definition).
function isValidCSSUnit(color) {
    return !!matchers.CSS_UNIT.exec(color);
}

// `stringInputToObject`
// Permissive string parsing.  Take in a number of formats, and output an object
// based on detected format.  Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`
function stringInputToObject(color) {

    color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase();
    var named = false;
    if (names[color]) {
        color = names[color];
        named = true;
    }
    else if (color == 'transparent') {
        return { r: 0, g: 0, b: 0, a: 0, format: "name" };
    }

    // Try to match string input using regular expressions.
    // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]
    // Just return an object and let the conversion functions handle that.
    // This way the result will be the same whether the tinycolor is initialized with string or object.
    var match;
    if ((match = matchers.rgb.exec(color))) {
        return { r: match[1], g: match[2], b: match[3] };
    }
    if ((match = matchers.rgba.exec(color))) {
        return { r: match[1], g: match[2], b: match[3], a: match[4] };
    }
    if ((match = matchers.hsl.exec(color))) {
        return { h: match[1], s: match[2], l: match[3] };
    }
    if ((match = matchers.hsla.exec(color))) {
        return { h: match[1], s: match[2], l: match[3], a: match[4] };
    }
    if ((match = matchers.hsv.exec(color))) {
        return { h: match[1], s: match[2], v: match[3] };
    }
    if ((match = matchers.hsva.exec(color))) {
        return { h: match[1], s: match[2], v: match[3], a: match[4] };
    }
    if ((match = matchers.hex8.exec(color))) {
        return {
            r: parseIntFromHex(match[1]),
            g: parseIntFromHex(match[2]),
            b: parseIntFromHex(match[3]),
            a: convertHexToDecimal(match[4]),
            format: named ? "name" : "hex8"
        };
    }
    if ((match = matchers.hex6.exec(color))) {
        return {
            r: parseIntFromHex(match[1]),
            g: parseIntFromHex(match[2]),
            b: parseIntFromHex(match[3]),
            format: named ? "name" : "hex"
        };
    }
    if ((match = matchers.hex4.exec(color))) {
        return {
            r: parseIntFromHex(match[1] + '' + match[1]),
            g: parseIntFromHex(match[2] + '' + match[2]),
            b: parseIntFromHex(match[3] + '' + match[3]),
            a: convertHexToDecimal(match[4] + '' + match[4]),
            format: named ? "name" : "hex8"
        };
    }
    if ((match = matchers.hex3.exec(color))) {
        return {
            r: parseIntFromHex(match[1] + '' + match[1]),
            g: parseIntFromHex(match[2] + '' + match[2]),
            b: parseIntFromHex(match[3] + '' + match[3]),
            format: named ? "name" : "hex"
        };
    }

    return false;
}

function validateWCAG2Parms(parms) {
    // return valid WCAG2 parms for isReadable.
    // If input parms are invalid, return {"level":"AA", "size":"small"}
    var level, size;
    parms = parms || {"level":"AA", "size":"small"};
    level = (parms.level || "AA").toUpperCase();
    size = (parms.size || "small").toLowerCase();
    if (level !== "AA" && level !== "AAA") {
        level = "AA";
    }
    if (size !== "small" && size !== "large") {
        size = "small";
    }
    return {"level":level, "size":size};
}

// Node: Export function
if (typeof module !== "undefined" && module.exports) {
    module.exports = tinycolor;
}
// AMD/requirejs: Define the module
else if (typeof define === 'function' && define.amd) {
    define(function () {return tinycolor;});
}
// Browser: Expose to window
else {
    window.tinycolor = tinycolor;
}

})(Math);

},{}],519:[function(_dereq_,module,exports){
/* @module to-float32 */

'use strict'

module.exports = float32
module.exports.float32 =
module.exports.float = float32
module.exports.fract32 =
module.exports.fract = fract32

var narr = new Float32Array(1)

// return fractional part of float32 array
function fract32 (arr) {
	if (arr.length) {
		var fract = float32(arr)
		for (var i = 0, l = fract.length; i < l; i++) {
			fract[i] = arr[i] - fract[i]
		}
		return fract
	}

	// number
	return float32(arr - float32(arr))
}

// make sure data is float32 array
function float32 (arr) {
	if (arr.length) {
		if (arr instanceof Float32Array) return arr
		var float = new Float32Array(arr)
		float.set(arr)
		return float
	}

	// number
	narr[0] = arr
	return narr[0]
}

},{}],520:[function(_dereq_,module,exports){
'use strict'

var parseUnit = _dereq_('parse-unit')

module.exports = toPX

var PIXELS_PER_INCH = 96

function getPropertyInPX(element, prop) {
  var parts = parseUnit(getComputedStyle(element).getPropertyValue(prop))
  return parts[0] * toPX(parts[1], element)
}

//This brutal hack is needed
function getSizeBrutal(unit, element) {
  var testDIV = document.createElement('div')
  testDIV.style['font-size'] = '128' + unit
  element.appendChild(testDIV)
  var size = getPropertyInPX(testDIV, 'font-size') / 128
  element.removeChild(testDIV)
  return size
}

function toPX(str, element) {
  element = element || document.body
  str = (str || 'px').trim().toLowerCase()
  if(element === window || element === document) {
    element = document.body 
  }
  switch(str) {
    case '%':  //Ambiguous, not sure if we should use width or height
      return element.clientHeight / 100.0
    case 'ch':
    case 'ex':
      return getSizeBrutal(str, element)
    case 'em':
      return getPropertyInPX(element, 'font-size')
    case 'rem':
      return getPropertyInPX(document.body, 'font-size')
    case 'vw':
      return window.innerWidth/100
    case 'vh':
      return window.innerHeight/100
    case 'vmin':
      return Math.min(window.innerWidth, window.innerHeight) / 100
    case 'vmax':
      return Math.max(window.innerWidth, window.innerHeight) / 100
    case 'in':
      return PIXELS_PER_INCH
    case 'cm':
      return PIXELS_PER_INCH / 2.54
    case 'mm':
      return PIXELS_PER_INCH / 25.4
    case 'pt':
      return PIXELS_PER_INCH / 72
    case 'pc':
      return PIXELS_PER_INCH / 6
  }
  return 1
}
},{"parse-unit":450}],521:[function(_dereq_,module,exports){
// https://github.com/topojson/topojson-client Version 2.1.0. Copyright 2016 Mike Bostock.
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
  (factory((global.topojson = global.topojson || {})));
}(this, (function (exports) { 'use strict';

var identity = function(x) {
  return x;
};

var transform = function(topology) {
  if ((transform = topology.transform) == null) return identity;
  var transform,
      x0,
      y0,
      kx = transform.scale[0],
      ky = transform.scale[1],
      dx = transform.translate[0],
      dy = transform.translate[1];
  return function(point, i) {
    if (!i) x0 = y0 = 0;
    point[0] = (x0 += point[0]) * kx + dx;
    point[1] = (y0 += point[1]) * ky + dy;
    return point;
  };
};

var bbox = function(topology) {
  var bbox = topology.bbox;

  function bboxPoint(p0) {
    p1[0] = p0[0], p1[1] = p0[1], t(p1);
    if (p1[0] < x0) x0 = p1[0];
    if (p1[0] > x1) x1 = p1[0];
    if (p1[1] < y0) y0 = p1[1];
    if (p1[1] > y1) y1 = p1[1];
  }

  function bboxGeometry(o) {
    switch (o.type) {
      case "GeometryCollection": o.geometries.forEach(bboxGeometry); break;
      case "Point": bboxPoint(o.coordinates); break;
      case "MultiPoint": o.coordinates.forEach(bboxPoint); break;
    }
  }

  if (!bbox) {
    var t = transform(topology), p0, p1 = new Array(2), name,
        x0 = Infinity, y0 = x0, x1 = -x0, y1 = -x0;

    topology.arcs.forEach(function(arc) {
      var i = -1, n = arc.length;
      while (++i < n) {
        p0 = arc[i], p1[0] = p0[0], p1[1] = p0[1], t(p1, i);
        if (p1[0] < x0) x0 = p1[0];
        if (p1[0] > x1) x1 = p1[0];
        if (p1[1] < y0) y0 = p1[1];
        if (p1[1] > y1) y1 = p1[1];
      }
    });

    for (name in topology.objects) {
      bboxGeometry(topology.objects[name]);
    }

    bbox = topology.bbox = [x0, y0, x1, y1];
  }

  return bbox;
};

var reverse = function(array, n) {
  var t, j = array.length, i = j - n;
  while (i < --j) t = array[i], array[i++] = array[j], array[j] = t;
};

var feature = function(topology, o) {
  return o.type === "GeometryCollection"
      ? {type: "FeatureCollection", features: o.geometries.map(function(o) { return feature$1(topology, o); })}
      : feature$1(topology, o);
};

function feature$1(topology, o) {
  var id = o.id,
      bbox = o.bbox,
      properties = o.properties == null ? {} : o.properties,
      geometry = object(topology, o);
  return id == null && bbox == null ? {type: "Feature", properties: properties, geometry: geometry}
      : bbox == null ? {type: "Feature", id: id, properties: properties, geometry: geometry}
      : {type: "Feature", id: id, bbox: bbox, properties: properties, geometry: geometry};
}

function object(topology, o) {
  var transformPoint = transform(topology),
      arcs = topology.arcs;

  function arc(i, points) {
    if (points.length) points.pop();
    for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length; k < n; ++k) {
      points.push(transformPoint(a[k].slice(), k));
    }
    if (i < 0) reverse(points, n);
  }

  function point(p) {
    return transformPoint(p.slice());
  }

  function line(arcs) {
    var points = [];
    for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points);
    if (points.length < 2) points.push(points[0].slice());
    return points;
  }

  function ring(arcs) {
    var points = line(arcs);
    while (points.length < 4) points.push(points[0].slice());
    return points;
  }

  function polygon(arcs) {
    return arcs.map(ring);
  }

  function geometry(o) {
    var type = o.type, coordinates;
    switch (type) {
      case "GeometryCollection": return {type: type, geometries: o.geometries.map(geometry)};
      case "Point": coordinates = point(o.coordinates); break;
      case "MultiPoint": coordinates = o.coordinates.map(point); break;
      case "LineString": coordinates = line(o.arcs); break;
      case "MultiLineString": coordinates = o.arcs.map(line); break;
      case "Polygon": coordinates = polygon(o.arcs); break;
      case "MultiPolygon": coordinates = o.arcs.map(polygon); break;
      default: return null;
    }
    return {type: type, coordinates: coordinates};
  }

  return geometry(o);
}

var stitch = function(topology, arcs) {
  var stitchedArcs = {},
      fragmentByStart = {},
      fragmentByEnd = {},
      fragments = [],
      emptyIndex = -1;

  // Stitch empty arcs first, since they may be subsumed by other arcs.
  arcs.forEach(function(i, j) {
    var arc = topology.arcs[i < 0 ? ~i : i], t;
    if (arc.length < 3 && !arc[1][0] && !arc[1][1]) {
      t = arcs[++emptyIndex], arcs[emptyIndex] = i, arcs[j] = t;
    }
  });

  arcs.forEach(function(i) {
    var e = ends(i),
        start = e[0],
        end = e[1],
        f, g;

    if (f = fragmentByEnd[start]) {
      delete fragmentByEnd[f.end];
      f.push(i);
      f.end = end;
      if (g = fragmentByStart[end]) {
        delete fragmentByStart[g.start];
        var fg = g === f ? f : f.concat(g);
        fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg;
      } else {
        fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
      }
    } else if (f = fragmentByStart[end]) {
      delete fragmentByStart[f.start];
      f.unshift(i);
      f.start = start;
      if (g = fragmentByEnd[start]) {
        delete fragmentByEnd[g.end];
        var gf = g === f ? f : g.concat(f);
        fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf;
      } else {
        fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
      }
    } else {
      f = [i];
      fragmentByStart[f.start = start] = fragmentByEnd[f.end = end] = f;
    }
  });

  function ends(i) {
    var arc = topology.arcs[i < 0 ? ~i : i], p0 = arc[0], p1;
    if (topology.transform) p1 = [0, 0], arc.forEach(function(dp) { p1[0] += dp[0], p1[1] += dp[1]; });
    else p1 = arc[arc.length - 1];
    return i < 0 ? [p1, p0] : [p0, p1];
  }

  function flush(fragmentByEnd, fragmentByStart) {
    for (var k in fragmentByEnd) {
      var f = fragmentByEnd[k];
      delete fragmentByStart[f.start];
      delete f.start;
      delete f.end;
      f.forEach(function(i) { stitchedArcs[i < 0 ? ~i : i] = 1; });
      fragments.push(f);
    }
  }

  flush(fragmentByEnd, fragmentByStart);
  flush(fragmentByStart, fragmentByEnd);
  arcs.forEach(function(i) { if (!stitchedArcs[i < 0 ? ~i : i]) fragments.push([i]); });

  return fragments;
};

var mesh = function(topology) {
  return object(topology, meshArcs.apply(this, arguments));
};

function meshArcs(topology, object$$1, filter) {
  var arcs, i, n;
  if (arguments.length > 1) arcs = extractArcs(topology, object$$1, filter);
  else for (i = 0, arcs = new Array(n = topology.arcs.length); i < n; ++i) arcs[i] = i;
  return {type: "MultiLineString", arcs: stitch(topology, arcs)};
}

function extractArcs(topology, object$$1, filter) {
  var arcs = [],
      geomsByArc = [],
      geom;

  function extract0(i) {
    var j = i < 0 ? ~i : i;
    (geomsByArc[j] || (geomsByArc[j] = [])).push({i: i, g: geom});
  }

  function extract1(arcs) {
    arcs.forEach(extract0);
  }

  function extract2(arcs) {
    arcs.forEach(extract1);
  }

  function extract3(arcs) {
    arcs.forEach(extract2);
  }

  function geometry(o) {
    switch (geom = o, o.type) {
      case "GeometryCollection": o.geometries.forEach(geometry); break;
      case "LineString": extract1(o.arcs); break;
      case "MultiLineString": case "Polygon": extract2(o.arcs); break;
      case "MultiPolygon": extract3(o.arcs); break;
    }
  }

  geometry(object$$1);

  geomsByArc.forEach(filter == null
      ? function(geoms) { arcs.push(geoms[0].i); }
      : function(geoms) { if (filter(geoms[0].g, geoms[geoms.length - 1].g)) arcs.push(geoms[0].i); });

  return arcs;
}

function planarRingArea(ring) {
  var i = -1, n = ring.length, a, b = ring[n - 1], area = 0;
  while (++i < n) a = b, b = ring[i], area += a[0] * b[1] - a[1] * b[0];
  return Math.abs(area); // Note: doubled area!
}

var merge = function(topology) {
  return object(topology, mergeArcs.apply(this, arguments));
};

function mergeArcs(topology, objects) {
  var polygonsByArc = {},
      polygons = [],
      groups = [];

  objects.forEach(geometry);

  function geometry(o) {
    switch (o.type) {
      case "GeometryCollection": o.geometries.forEach(geometry); break;
      case "Polygon": extract(o.arcs); break;
      case "MultiPolygon": o.arcs.forEach(extract); break;
    }
  }

  function extract(polygon) {
    polygon.forEach(function(ring) {
      ring.forEach(function(arc) {
        (polygonsByArc[arc = arc < 0 ? ~arc : arc] || (polygonsByArc[arc] = [])).push(polygon);
      });
    });
    polygons.push(polygon);
  }

  function area(ring) {
    return planarRingArea(object(topology, {type: "Polygon", arcs: [ring]}).coordinates[0]);
  }

  polygons.forEach(function(polygon) {
    if (!polygon._) {
      var group = [],
          neighbors = [polygon];
      polygon._ = 1;
      groups.push(group);
      while (polygon = neighbors.pop()) {
        group.push(polygon);
        polygon.forEach(function(ring) {
          ring.forEach(function(arc) {
            polygonsByArc[arc < 0 ? ~arc : arc].forEach(function(polygon) {
              if (!polygon._) {
                polygon._ = 1;
                neighbors.push(polygon);
              }
            });
          });
        });
      }
    }
  });

  polygons.forEach(function(polygon) {
    delete polygon._;
  });

  return {
    type: "MultiPolygon",
    arcs: groups.map(function(polygons) {
      var arcs = [], n;

      // Extract the exterior (unique) arcs.
      polygons.forEach(function(polygon) {
        polygon.forEach(function(ring) {
          ring.forEach(function(arc) {
            if (polygonsByArc[arc < 0 ? ~arc : arc].length < 2) {
              arcs.push(arc);
            }
          });
        });
      });

      // Stitch the arcs into one or more rings.
      arcs = stitch(topology, arcs);

      // If more than one ring is returned,
      // at most one of these rings can be the exterior;
      // choose the one with the greatest absolute area.
      if ((n = arcs.length) > 1) {
        for (var i = 1, k = area(arcs[0]), ki, t; i < n; ++i) {
          if ((ki = area(arcs[i])) > k) {
            t = arcs[0], arcs[0] = arcs[i], arcs[i] = t, k = ki;
          }
        }
      }

      return arcs;
    })
  };
}

var bisect = function(a, x) {
  var lo = 0, hi = a.length;
  while (lo < hi) {
    var mid = lo + hi >>> 1;
    if (a[mid] < x) lo = mid + 1;
    else hi = mid;
  }
  return lo;
};

var neighbors = function(objects) {
  var indexesByArc = {}, // arc index -> array of object indexes
      neighbors = objects.map(function() { return []; });

  function line(arcs, i) {
    arcs.forEach(function(a) {
      if (a < 0) a = ~a;
      var o = indexesByArc[a];
      if (o) o.push(i);
      else indexesByArc[a] = [i];
    });
  }

  function polygon(arcs, i) {
    arcs.forEach(function(arc) { line(arc, i); });
  }

  function geometry(o, i) {
    if (o.type === "GeometryCollection") o.geometries.forEach(function(o) { geometry(o, i); });
    else if (o.type in geometryType) geometryType[o.type](o.arcs, i);
  }

  var geometryType = {
    LineString: line,
    MultiLineString: polygon,
    Polygon: polygon,
    MultiPolygon: function(arcs, i) { arcs.forEach(function(arc) { polygon(arc, i); }); }
  };

  objects.forEach(geometry);

  for (var i in indexesByArc) {
    for (var indexes = indexesByArc[i], m = indexes.length, j = 0; j < m; ++j) {
      for (var k = j + 1; k < m; ++k) {
        var ij = indexes[j], ik = indexes[k], n;
        if ((n = neighbors[ij])[i = bisect(n, ik)] !== ik) n.splice(i, 0, ik);
        if ((n = neighbors[ik])[i = bisect(n, ij)] !== ij) n.splice(i, 0, ij);
      }
    }
  }

  return neighbors;
};

var quantize = function(topology, n) {
  if (!((n = Math.floor(n)) >= 2)) throw new Error("n must be ≥2");
  if (topology.transform) throw new Error("already quantized");
  var bb = bbox(topology), name,
      dx = bb[0], kx = (bb[2] - dx) / (n - 1) || 1,
      dy = bb[1], ky = (bb[3] - dy) / (n - 1) || 1;

  function quantizePoint(p) {
    p[0] = Math.round((p[0] - dx) / kx);
    p[1] = Math.round((p[1] - dy) / ky);
  }

  function quantizeGeometry(o) {
    switch (o.type) {
      case "GeometryCollection": o.geometries.forEach(quantizeGeometry); break;
      case "Point": quantizePoint(o.coordinates); break;
      case "MultiPoint": o.coordinates.forEach(quantizePoint); break;
    }
  }

  topology.arcs.forEach(function(arc) {
    var i = 1,
        j = 1,
        n = arc.length,
        pi = arc[0],
        x0 = pi[0] = Math.round((pi[0] - dx) / kx),
        y0 = pi[1] = Math.round((pi[1] - dy) / ky),
        pj,
        x1,
        y1;

    for (; i < n; ++i) {
      pi = arc[i];
      x1 = Math.round((pi[0] - dx) / kx);
      y1 = Math.round((pi[1] - dy) / ky);
      if (x1 !== x0 || y1 !== y0) {
        pj = arc[j++];
        pj[0] = x1 - x0, x0 = x1;
        pj[1] = y1 - y0, y0 = y1;
      }
    }

    if (j < 2) {
      pj = arc[j++];
      pj[0] = 0;
      pj[1] = 0;
    }

    arc.length = j;
  });

  for (name in topology.objects) {
    quantizeGeometry(topology.objects[name]);
  }

  topology.transform = {
    scale: [kx, ky],
    translate: [dx, dy]
  };

  return topology;
};

var untransform = function(topology) {
  if ((transform = topology.transform) == null) return identity;
  var transform,
      x0,
      y0,
      kx = transform.scale[0],
      ky = transform.scale[1],
      dx = transform.translate[0],
      dy = transform.translate[1];
  return function(point, i) {
    if (!i) x0 = y0 = 0;
    var x1 = Math.round((point[0] - dx) / kx),
        y1 = Math.round((point[1] - dy) / ky);
    point[0] = x1 - x0, x0 = x1;
    point[1] = y1 - y0, y0 = y1;
    return point;
  };
};

exports.bbox = bbox;
exports.feature = feature;
exports.mesh = mesh;
exports.meshArcs = meshArcs;
exports.merge = merge;
exports.mergeArcs = mergeArcs;
exports.neighbors = neighbors;
exports.quantize = quantize;
exports.transform = transform;
exports.untransform = untransform;

Object.defineProperty(exports, '__esModule', { value: true });

})));

},{}],522:[function(_dereq_,module,exports){
"use strict"

module.exports = triangulateCube

var perm = _dereq_("permutation-rank")
var sgn = _dereq_("permutation-parity")
var gamma = _dereq_("gamma")

function triangulateCube(dimension) {
  if(dimension < 0) {
    return [ ]
  }
  if(dimension === 0) {
    return [ [0] ]
  }
  var dfactorial = Math.round(gamma(dimension+1))|0
  var result = []
  for(var i=0; i<dfactorial; ++i) {
    var p = perm.unrank(dimension, i)
    var cell = [ 0 ]
    var v = 0
    for(var j=0; j<p.length; ++j) {
      v += (1<<p[j])
      cell.push(v)
    }
    if(sgn(p) < 1) {
      cell[0] = v
      cell[dimension] = 0
    }
    result.push(cell)
  }
  return result
}
},{"gamma":224,"permutation-parity":452,"permutation-rank":453}],523:[function(_dereq_,module,exports){
'use strict'

module.exports = createTurntableController

var filterVector = _dereq_('filtered-vector')
var invert44     = _dereq_('gl-mat4/invert')
var rotateM      = _dereq_('gl-mat4/rotate')
var cross        = _dereq_('gl-vec3/cross')
var normalize3   = _dereq_('gl-vec3/normalize')
var dot3         = _dereq_('gl-vec3/dot')

function len3(x, y, z) {
  return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2))
}

function clamp1(x) {
  return Math.min(1.0, Math.max(-1.0, x))
}

function findOrthoPair(v) {
  var vx = Math.abs(v[0])
  var vy = Math.abs(v[1])
  var vz = Math.abs(v[2])

  var u = [0,0,0]
  if(vx > Math.max(vy, vz)) {
    u[2] = 1
  } else if(vy > Math.max(vx, vz)) {
    u[0] = 1
  } else {
    u[1] = 1
  }

  var vv = 0
  var uv = 0
  for(var i=0; i<3; ++i ) {
    vv += v[i] * v[i]
    uv += u[i] * v[i]
  }
  for(var i=0; i<3; ++i) {
    u[i] -= (uv / vv) *  v[i]
  }
  normalize3(u, u)
  return u
}

function TurntableController(zoomMin, zoomMax, center, up, right, radius, theta, phi) {
  this.center = filterVector(center)
  this.up     = filterVector(up)
  this.right  = filterVector(right)
  this.radius = filterVector([radius])
  this.angle  = filterVector([theta, phi])
  this.angle.bounds = [[-Infinity,-Math.PI/2], [Infinity,Math.PI/2]]
  this.setDistanceLimits(zoomMin, zoomMax)

  this.computedCenter = this.center.curve(0)
  this.computedUp     = this.up.curve(0)
  this.computedRight  = this.right.curve(0)
  this.computedRadius = this.radius.curve(0)
  this.computedAngle  = this.angle.curve(0)
  this.computedToward = [0,0,0]
  this.computedEye    = [0,0,0]
  this.computedMatrix = new Array(16)
  for(var i=0; i<16; ++i) {
    this.computedMatrix[i] = 0.5
  }

  this.recalcMatrix(0)
}

var proto = TurntableController.prototype

proto.setDistanceLimits = function(minDist, maxDist) {
  if(minDist > 0) {
    minDist = Math.log(minDist)
  } else {
    minDist = -Infinity
  }
  if(maxDist > 0) {
    maxDist = Math.log(maxDist)
  } else {
    maxDist = Infinity
  }
  maxDist = Math.max(maxDist, minDist)
  this.radius.bounds[0][0] = minDist
  this.radius.bounds[1][0] = maxDist
}

proto.getDistanceLimits = function(out) {
  var bounds = this.radius.bounds[0]
  if(out) {
    out[0] = Math.exp(bounds[0][0])
    out[1] = Math.exp(bounds[1][0])
    return out
  }
  return [ Math.exp(bounds[0][0]), Math.exp(bounds[1][0]) ]
}

proto.recalcMatrix = function(t) {
  //Recompute curves
  this.center.curve(t)
  this.up.curve(t)
  this.right.curve(t)
  this.radius.curve(t)
  this.angle.curve(t)

  //Compute frame for camera matrix
  var up     = this.computedUp
  var right  = this.computedRight
  var uu = 0.0
  var ur = 0.0
  for(var i=0; i<3; ++i) {
    ur += up[i] * right[i]
    uu += up[i] * up[i]
  }
  var ul = Math.sqrt(uu)
  var rr = 0.0
  for(var i=0; i<3; ++i) {
    right[i] -= up[i] * ur / uu
    rr       += right[i] * right[i]
    up[i]    /= ul
  }
  var rl = Math.sqrt(rr)
  for(var i=0; i<3; ++i) {
    right[i] /= rl
  }

  //Compute toward vector
  var toward = this.computedToward
  cross(toward, up, right)
  normalize3(toward, toward)

  //Compute angular parameters
  var radius = Math.exp(this.computedRadius[0])
  var theta  = this.computedAngle[0]
  var phi    = this.computedAngle[1]

  var ctheta = Math.cos(theta)
  var stheta = Math.sin(theta)
  var cphi   = Math.cos(phi)
  var sphi   = Math.sin(phi)

  var center = this.computedCenter

  var wx = ctheta * cphi 
  var wy = stheta * cphi
  var wz = sphi

  var sx = -ctheta * sphi
  var sy = -stheta * sphi
  var sz = cphi

  var eye = this.computedEye
  var mat = this.computedMatrix
  for(var i=0; i<3; ++i) {
    var x      = wx * right[i] + wy * toward[i] + wz * up[i]
    mat[4*i+1] = sx * right[i] + sy * toward[i] + sz * up[i]
    mat[4*i+2] = x
    mat[4*i+3] = 0.0
  }

  var ax = mat[1]
  var ay = mat[5]
  var az = mat[9]
  var bx = mat[2]
  var by = mat[6]
  var bz = mat[10]
  var cx = ay * bz - az * by
  var cy = az * bx - ax * bz
  var cz = ax * by - ay * bx
  var cl = len3(cx, cy, cz)
  cx /= cl
  cy /= cl
  cz /= cl
  mat[0] = cx
  mat[4] = cy
  mat[8] = cz

  for(var i=0; i<3; ++i) {
    eye[i] = center[i] + mat[2+4*i]*radius
  }

  for(var i=0; i<3; ++i) {
    var rr = 0.0
    for(var j=0; j<3; ++j) {
      rr += mat[i+4*j] * eye[j]
    }
    mat[12+i] = -rr
  }
  mat[15] = 1.0
}

proto.getMatrix = function(t, result) {
  this.recalcMatrix(t)
  var mat = this.computedMatrix
  if(result) {
    for(var i=0; i<16; ++i) {
      result[i] = mat[i]
    }
    return result
  }
  return mat
}

var zAxis = [0,0,0]
proto.rotate = function(t, dtheta, dphi, droll) {
  this.angle.move(t, dtheta, dphi)
  if(droll) {
    this.recalcMatrix(t)

    var mat = this.computedMatrix
    zAxis[0] = mat[2]
    zAxis[1] = mat[6]
    zAxis[2] = mat[10]

    var up     = this.computedUp
    var right  = this.computedRight
    var toward = this.computedToward

    for(var i=0; i<3; ++i) {
      mat[4*i]   = up[i]
      mat[4*i+1] = right[i]
      mat[4*i+2] = toward[i]
    }
    rotateM(mat, mat, droll, zAxis)
    for(var i=0; i<3; ++i) {
      up[i] =    mat[4*i]
      right[i] = mat[4*i+1]
    }

    this.up.set(t, up[0], up[1], up[2])
    this.right.set(t, right[0], right[1], right[2])
  }
}

proto.pan = function(t, dx, dy, dz) {
  dx = dx || 0.0
  dy = dy || 0.0
  dz = dz || 0.0

  this.recalcMatrix(t)
  var mat = this.computedMatrix

  var dist = Math.exp(this.computedRadius[0])

  var ux = mat[1]
  var uy = mat[5]
  var uz = mat[9]
  var ul = len3(ux, uy, uz)
  ux /= ul
  uy /= ul
  uz /= ul

  var rx = mat[0]
  var ry = mat[4]
  var rz = mat[8]
  var ru = rx * ux + ry * uy + rz * uz
  rx -= ux * ru
  ry -= uy * ru
  rz -= uz * ru
  var rl = len3(rx, ry, rz)
  rx /= rl
  ry /= rl
  rz /= rl

  var vx = rx * dx + ux * dy
  var vy = ry * dx + uy * dy
  var vz = rz * dx + uz * dy
  this.center.move(t, vx, vy, vz)

  //Update z-component of radius
  var radius = Math.exp(this.computedRadius[0])
  radius = Math.max(1e-4, radius + dz)
  this.radius.set(t, Math.log(radius))
}

proto.translate = function(t, dx, dy, dz) {
  this.center.move(t,
    dx||0.0,
    dy||0.0,
    dz||0.0)
}

//Recenters the coordinate axes
proto.setMatrix = function(t, mat, axes, noSnap) {
  
  //Get the axes for tare
  var ushift = 1
  if(typeof axes === 'number') {
    ushift = (axes)|0
  } 
  if(ushift < 0 || ushift > 3) {
    ushift = 1
  }
  var vshift = (ushift + 2) % 3
  var fshift = (ushift + 1) % 3

  //Recompute state for new t value
  if(!mat) { 
    this.recalcMatrix(t)
    mat = this.computedMatrix
  }

  //Get right and up vectors
  var ux = mat[ushift]
  var uy = mat[ushift+4]
  var uz = mat[ushift+8]
  if(!noSnap) {
    var ul = len3(ux, uy, uz)
    ux /= ul
    uy /= ul
    uz /= ul
  } else {
    var ax = Math.abs(ux)
    var ay = Math.abs(uy)
    var az = Math.abs(uz)
    var am = Math.max(ax,ay,az)
    if(ax === am) {
      ux = (ux < 0) ? -1 : 1
      uy = uz = 0
    } else if(az === am) {
      uz = (uz < 0) ? -1 : 1
      ux = uy = 0
    } else {
      uy = (uy < 0) ? -1 : 1
      ux = uz = 0
    }
  }

  var rx = mat[vshift]
  var ry = mat[vshift+4]
  var rz = mat[vshift+8]
  var ru = rx * ux + ry * uy + rz * uz
  rx -= ux * ru
  ry -= uy * ru
  rz -= uz * ru
  var rl = len3(rx, ry, rz)
  rx /= rl
  ry /= rl
  rz /= rl
  
  var fx = uy * rz - uz * ry
  var fy = uz * rx - ux * rz
  var fz = ux * ry - uy * rx
  var fl = len3(fx, fy, fz)
  fx /= fl
  fy /= fl
  fz /= fl

  this.center.jump(t, ex, ey, ez)
  this.radius.idle(t)
  this.up.jump(t, ux, uy, uz)
  this.right.jump(t, rx, ry, rz)

  var phi, theta
  if(ushift === 2) {
    var cx = mat[1]
    var cy = mat[5]
    var cz = mat[9]
    var cr = cx * rx + cy * ry + cz * rz
    var cf = cx * fx + cy * fy + cz * fz
    if(tu < 0) {
      phi = -Math.PI/2
    } else {
      phi = Math.PI/2
    }
    theta = Math.atan2(cf, cr)
  } else {
    var tx = mat[2]
    var ty = mat[6]
    var tz = mat[10]
    var tu = tx * ux + ty * uy + tz * uz
    var tr = tx * rx + ty * ry + tz * rz
    var tf = tx * fx + ty * fy + tz * fz

    phi = Math.asin(clamp1(tu))
    theta = Math.atan2(tf, tr)
  }

  this.angle.jump(t, theta, phi)

  this.recalcMatrix(t)
  var dx = mat[2]
  var dy = mat[6]
  var dz = mat[10]

  var imat = this.computedMatrix
  invert44(imat, mat)
  var w  = imat[15]
  var ex = imat[12] / w
  var ey = imat[13] / w
  var ez = imat[14] / w

  var gs = Math.exp(this.computedRadius[0])
  this.center.jump(t, ex-dx*gs, ey-dy*gs, ez-dz*gs)
}

proto.lastT = function() {
  return Math.max(
    this.center.lastT(),
    this.up.lastT(),
    this.right.lastT(),
    this.radius.lastT(),
    this.angle.lastT())
}

proto.idle = function(t) {
  this.center.idle(t)
  this.up.idle(t)
  this.right.idle(t)
  this.radius.idle(t)
  this.angle.idle(t)
}

proto.flush = function(t) {
  this.center.flush(t)
  this.up.flush(t)
  this.right.flush(t)
  this.radius.flush(t)
  this.angle.flush(t)
}

proto.setDistance = function(t, d) {
  if(d > 0) {
    this.radius.set(t, Math.log(d))
  }
}

proto.lookAt = function(t, eye, center, up) {
  this.recalcMatrix(t)

  eye    = eye    || this.computedEye
  center = center || this.computedCenter
  up     = up     || this.computedUp

  var ux = up[0]
  var uy = up[1]
  var uz = up[2]
  var ul = len3(ux, uy, uz)
  if(ul < 1e-6) {
    return
  }
  ux /= ul
  uy /= ul
  uz /= ul

  var tx = eye[0] - center[0]
  var ty = eye[1] - center[1]
  var tz = eye[2] - center[2]
  var tl = len3(tx, ty, tz)
  if(tl < 1e-6) {
    return
  }
  tx /= tl
  ty /= tl
  tz /= tl

  var right = this.computedRight
  var rx = right[0]
  var ry = right[1]
  var rz = right[2]
  var ru = ux*rx + uy*ry + uz*rz
  rx -= ru * ux
  ry -= ru * uy
  rz -= ru * uz
  var rl = len3(rx, ry, rz)

  if(rl < 0.01) {
    rx = uy * tz - uz * ty
    ry = uz * tx - ux * tz
    rz = ux * ty - uy * tx
    rl = len3(rx, ry, rz)
    if(rl < 1e-6) {
      return
    }
  }
  rx /= rl
  ry /= rl
  rz /= rl

  this.up.set(t, ux, uy, uz)
  this.right.set(t, rx, ry, rz)
  this.center.set(t, center[0], center[1], center[2])
  this.radius.set(t, Math.log(tl))

  var fx = uy * rz - uz * ry
  var fy = uz * rx - ux * rz
  var fz = ux * ry - uy * rx
  var fl = len3(fx, fy, fz)
  fx /= fl
  fy /= fl
  fz /= fl

  var tu = ux*tx + uy*ty + uz*tz
  var tr = rx*tx + ry*ty + rz*tz
  var tf = fx*tx + fy*ty + fz*tz

  var phi   = Math.asin(clamp1(tu))
  var theta = Math.atan2(tf, tr)

  var angleState = this.angle._state
  var lastTheta  = angleState[angleState.length-1]
  var lastPhi    = angleState[angleState.length-2]
  lastTheta      = lastTheta % (2.0 * Math.PI)
  var dp = Math.abs(lastTheta + 2.0 * Math.PI - theta)
  var d0 = Math.abs(lastTheta - theta)
  var dn = Math.abs(lastTheta - 2.0 * Math.PI - theta)
  if(dp < d0) {
    lastTheta += 2.0 * Math.PI
  }
  if(dn < d0) {
    lastTheta -= 2.0 * Math.PI
  }

  this.angle.jump(this.angle.lastT(), lastTheta, lastPhi)
  this.angle.set(t, theta, phi)
}

function createTurntableController(options) {
  options = options || {}

  var center = options.center || [0,0,0]
  var up     = options.up     || [0,1,0]
  var right  = options.right  || findOrthoPair(up)
  var radius = options.radius || 1.0
  var theta  = options.theta  || 0.0
  var phi    = options.phi    || 0.0

  center = [].slice.call(center, 0, 3)

  up = [].slice.call(up, 0, 3)
  normalize3(up, up)

  right = [].slice.call(right, 0, 3)
  normalize3(right, right)

  if('eye' in options) {
    var eye = options.eye
    var toward = [
      eye[0]-center[0],
      eye[1]-center[1],
      eye[2]-center[2]
    ]
    cross(right, toward, up)
    if(len3(right[0], right[1], right[2]) < 1e-6) {
      right = findOrthoPair(up)
    } else {
      normalize3(right, right)
    }

    radius = len3(toward[0], toward[1], toward[2])

    var ut = dot3(up, toward) / radius
    var rt = dot3(right, toward) / radius
    phi    = Math.acos(ut)
    theta  = Math.acos(rt)
  }

  //Use logarithmic coordinates for radius
  radius = Math.log(radius)

  //Return the controller
  return new TurntableController(
    options.zoomMin,
    options.zoomMax,
    center,
    up,
    right,
    radius,
    theta,
    phi)
}
},{"filtered-vector":219,"gl-mat4/invert":258,"gl-mat4/rotate":263,"gl-vec3/cross":323,"gl-vec3/dot":328,"gl-vec3/normalize":345}],524:[function(_dereq_,module,exports){
"use strict"

module.exports = twoProduct

var SPLITTER = +(Math.pow(2, 27) + 1.0)

function twoProduct(a, b, result) {
  var x = a * b

  var c = SPLITTER * a
  var abig = c - a
  var ahi = c - abig
  var alo = a - ahi

  var d = SPLITTER * b
  var bbig = d - b
  var bhi = d - bbig
  var blo = b - bhi

  var err1 = x - (ahi * bhi)
  var err2 = err1 - (alo * bhi)
  var err3 = err2 - (ahi * blo)

  var y = alo * blo - err3

  if(result) {
    result[0] = y
    result[1] = x
    return result
  }

  return [ y, x ]
}
},{}],525:[function(_dereq_,module,exports){
"use strict"

module.exports = fastTwoSum

function fastTwoSum(a, b, result) {
	var x = a + b
	var bv = x - a
	var av = x - bv
	var br = b - bv
	var ar = a - av
	if(result) {
		result[0] = ar + br
		result[1] = x
		return result
	}
	return [ar+br, x]
}
},{}],526:[function(_dereq_,module,exports){
(function (global,Buffer){
'use strict'

var bits = _dereq_('bit-twiddle')
var dup = _dereq_('dup')

//Legacy pool support
if(!global.__TYPEDARRAY_POOL) {
  global.__TYPEDARRAY_POOL = {
      UINT8   : dup([32, 0])
    , UINT16  : dup([32, 0])
    , UINT32  : dup([32, 0])
    , INT8    : dup([32, 0])
    , INT16   : dup([32, 0])
    , INT32   : dup([32, 0])
    , FLOAT   : dup([32, 0])
    , DOUBLE  : dup([32, 0])
    , DATA    : dup([32, 0])
    , UINT8C  : dup([32, 0])
    , BUFFER  : dup([32, 0])
  }
}

var hasUint8C = (typeof Uint8ClampedArray) !== 'undefined'
var POOL = global.__TYPEDARRAY_POOL

//Upgrade pool
if(!POOL.UINT8C) {
  POOL.UINT8C = dup([32, 0])
}
if(!POOL.BUFFER) {
  POOL.BUFFER = dup([32, 0])
}

//New technique: Only allocate from ArrayBufferView and Buffer
var DATA    = POOL.DATA
  , BUFFER  = POOL.BUFFER

exports.free = function free(array) {
  if(Buffer.isBuffer(array)) {
    BUFFER[bits.log2(array.length)].push(array)
  } else {
    if(Object.prototype.toString.call(array) !== '[object ArrayBuffer]') {
      array = array.buffer
    }
    if(!array) {
      return
    }
    var n = array.length || array.byteLength
    var log_n = bits.log2(n)|0
    DATA[log_n].push(array)
  }
}

function freeArrayBuffer(buffer) {
  if(!buffer) {
    return
  }
  var n = buffer.length || buffer.byteLength
  var log_n = bits.log2(n)
  DATA[log_n].push(buffer)
}

function freeTypedArray(array) {
  freeArrayBuffer(array.buffer)
}

exports.freeUint8 =
exports.freeUint16 =
exports.freeUint32 =
exports.freeInt8 =
exports.freeInt16 =
exports.freeInt32 =
exports.freeFloat32 = 
exports.freeFloat =
exports.freeFloat64 = 
exports.freeDouble = 
exports.freeUint8Clamped = 
exports.freeDataView = freeTypedArray

exports.freeArrayBuffer = freeArrayBuffer

exports.freeBuffer = function freeBuffer(array) {
  BUFFER[bits.log2(array.length)].push(array)
}

exports.malloc = function malloc(n, dtype) {
  if(dtype === undefined || dtype === 'arraybuffer') {
    return mallocArrayBuffer(n)
  } else {
    switch(dtype) {
      case 'uint8':
        return mallocUint8(n)
      case 'uint16':
        return mallocUint16(n)
      case 'uint32':
        return mallocUint32(n)
      case 'int8':
        return mallocInt8(n)
      case 'int16':
        return mallocInt16(n)
      case 'int32':
        return mallocInt32(n)
      case 'float':
      case 'float32':
        return mallocFloat(n)
      case 'double':
      case 'float64':
        return mallocDouble(n)
      case 'uint8_clamped':
        return mallocUint8Clamped(n)
      case 'buffer':
        return mallocBuffer(n)
      case 'data':
      case 'dataview':
        return mallocDataView(n)

      default:
        return null
    }
  }
  return null
}

function mallocArrayBuffer(n) {
  var n = bits.nextPow2(n)
  var log_n = bits.log2(n)
  var d = DATA[log_n]
  if(d.length > 0) {
    return d.pop()
  }
  return new ArrayBuffer(n)
}
exports.mallocArrayBuffer = mallocArrayBuffer

function mallocUint8(n) {
  return new Uint8Array(mallocArrayBuffer(n), 0, n)
}
exports.mallocUint8 = mallocUint8

function mallocUint16(n) {
  return new Uint16Array(mallocArrayBuffer(2*n), 0, n)
}
exports.mallocUint16 = mallocUint16

function mallocUint32(n) {
  return new Uint32Array(mallocArrayBuffer(4*n), 0, n)
}
exports.mallocUint32 = mallocUint32

function mallocInt8(n) {
  return new Int8Array(mallocArrayBuffer(n), 0, n)
}
exports.mallocInt8 = mallocInt8

function mallocInt16(n) {
  return new Int16Array(mallocArrayBuffer(2*n), 0, n)
}
exports.mallocInt16 = mallocInt16

function mallocInt32(n) {
  return new Int32Array(mallocArrayBuffer(4*n), 0, n)
}
exports.mallocInt32 = mallocInt32

function mallocFloat(n) {
  return new Float32Array(mallocArrayBuffer(4*n), 0, n)
}
exports.mallocFloat32 = exports.mallocFloat = mallocFloat

function mallocDouble(n) {
  return new Float64Array(mallocArrayBuffer(8*n), 0, n)
}
exports.mallocFloat64 = exports.mallocDouble = mallocDouble

function mallocUint8Clamped(n) {
  if(hasUint8C) {
    return new Uint8ClampedArray(mallocArrayBuffer(n), 0, n)
  } else {
    return mallocUint8(n)
  }
}
exports.mallocUint8Clamped = mallocUint8Clamped

function mallocDataView(n) {
  return new DataView(mallocArrayBuffer(n), 0, n)
}
exports.mallocDataView = mallocDataView

function mallocBuffer(n) {
  n = bits.nextPow2(n)
  var log_n = bits.log2(n)
  var cache = BUFFER[log_n]
  if(cache.length > 0) {
    return cache.pop()
  }
  return new Buffer(n)
}
exports.mallocBuffer = mallocBuffer

exports.clearCache = function clearCache() {
  for(var i=0; i<32; ++i) {
    POOL.UINT8[i].length = 0
    POOL.UINT16[i].length = 0
    POOL.UINT32[i].length = 0
    POOL.INT8[i].length = 0
    POOL.INT16[i].length = 0
    POOL.INT32[i].length = 0
    POOL.FLOAT[i].length = 0
    POOL.DOUBLE[i].length = 0
    POOL.UINT8C[i].length = 0
    DATA[i].length = 0
    BUFFER[i].length = 0
  }
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_("buffer").Buffer)
},{"bit-twiddle":80,"buffer":93,"dup":158}],527:[function(_dereq_,module,exports){
"use strict"; "use restrict";

module.exports = UnionFind;

function UnionFind(count) {
  this.roots = new Array(count);
  this.ranks = new Array(count);
  
  for(var i=0; i<count; ++i) {
    this.roots[i] = i;
    this.ranks[i] = 0;
  }
}

var proto = UnionFind.prototype

Object.defineProperty(proto, "length", {
  "get": function() {
    return this.roots.length
  }
})

proto.makeSet = function() {
  var n = this.roots.length;
  this.roots.push(n);
  this.ranks.push(0);
  return n;
}

proto.find = function(x) {
  var x0 = x
  var roots = this.roots;
  while(roots[x] !== x) {
    x = roots[x]
  }
  while(roots[x0] !== x) {
    var y = roots[x0]
    roots[x0] = x
    x0 = y
  }
  return x;
}

proto.link = function(x, y) {
  var xr = this.find(x)
    , yr = this.find(y);
  if(xr === yr) {
    return;
  }
  var ranks = this.ranks
    , roots = this.roots
    , xd    = ranks[xr]
    , yd    = ranks[yr];
  if(xd < yd) {
    roots[xr] = yr;
  } else if(yd < xd) {
    roots[yr] = xr;
  } else {
    roots[yr] = xr;
    ++ranks[xr];
  }
}
},{}],528:[function(_dereq_,module,exports){
"use strict"

function unique_pred(list, compare) {
  var ptr = 1
    , len = list.length
    , a=list[0], b=list[0]
  for(var i=1; i<len; ++i) {
    b = a
    a = list[i]
    if(compare(a, b)) {
      if(i === ptr) {
        ptr++
        continue
      }
      list[ptr++] = a
    }
  }
  list.length = ptr
  return list
}

function unique_eq(list) {
  var ptr = 1
    , len = list.length
    , a=list[0], b = list[0]
  for(var i=1; i<len; ++i, b=a) {
    b = a
    a = list[i]
    if(a !== b) {
      if(i === ptr) {
        ptr++
        continue
      }
      list[ptr++] = a
    }
  }
  list.length = ptr
  return list
}

function unique(list, compare, sorted) {
  if(list.length === 0) {
    return list
  }
  if(compare) {
    if(!sorted) {
      list.sort(compare)
    }
    return unique_pred(list, compare)
  }
  if(!sorted) {
    list.sort()
  }
  return unique_eq(list)
}

module.exports = unique

},{}],529:[function(_dereq_,module,exports){
var reg = /[\'\"]/

module.exports = function unquote(str) {
  if (!str) {
    return ''
  }
  if (reg.test(str.charAt(0))) {
    str = str.substr(1)
  }
  if (reg.test(str.charAt(str.length - 1))) {
    str = str.substr(0, str.length - 1)
  }
  return str
}

},{}],530:[function(_dereq_,module,exports){
/**
 * @module update-diff
 */

'use strict'

module.exports = function updateDiff (obj, diff, mappers) {
	if (!Array.isArray(mappers)) mappers = [].slice.call(arguments, 2)

	for (var i = 0, l = mappers.length; i < l; i++) {
		var dict = mappers[i]
		for (var prop in dict) {
			if (diff[prop] !== undefined && !Array.isArray(diff[prop]) && obj[prop] === diff[prop]) continue

			if (prop in diff) {
				var result

				if (dict[prop] === true) result = diff[prop]
				else if (dict[prop] === false) continue
				else if (typeof dict[prop] === 'function') {
					result = dict[prop](diff[prop], obj, diff)
					if (result === undefined) continue
				}

				obj[prop] = result
			}
		}
	}

	return obj
}

},{}],531:[function(_dereq_,module,exports){
"use strict"

module.exports = createText

var vectorizeText = _dereq_("./lib/vtext")
var defaultCanvas = null
var defaultContext = null

if(typeof document !== 'undefined') {
  defaultCanvas = document.createElement('canvas')
  defaultCanvas.width = 8192
  defaultCanvas.height = 1024
  defaultContext = defaultCanvas.getContext("2d")
}

function createText(str, options) {
  if((typeof options !== "object") || (options === null)) {
    options = {}
  }
  return vectorizeText(
    str,
    options.canvas || defaultCanvas,
    options.context || defaultContext,
    options)
}

},{"./lib/vtext":532}],532:[function(_dereq_,module,exports){
module.exports = vectorizeText
module.exports.processPixels = processPixels

var surfaceNets = _dereq_('surface-nets')
var ndarray = _dereq_('ndarray')
var simplify = _dereq_('simplify-planar-graph')
var cleanPSLG = _dereq_('clean-pslg')
var cdt2d = _dereq_('cdt2d')
var toPolygonCrappy = _dereq_('planar-graph-to-polyline')

var TAG_bold = "b"
var CHR_bold = 'b|'

var TAG_italic = "i"
var CHR_italic = 'i|'

var TAG_super = "sup"
var CHR_super0 = '+'
var CHR_super = '+1'

var TAG_sub = "sub"
var CHR_sub0 = '-'
var CHR_sub = '-1'

function parseTag(tag, TAG_CHR, str, map) {

  var opnTag =  "<"  + tag + ">"
  var clsTag =  "</" + tag + ">"

  var nOPN = opnTag.length
  var nCLS = clsTag.length

  var isRecursive = (TAG_CHR[0] === CHR_super0) ||
                    (TAG_CHR[0] === CHR_sub0);

  var a = 0
  var b = -nCLS
  while (a > -1) {
    a = str.indexOf(opnTag, a)
    if(a === -1) break

    b = str.indexOf(clsTag, a + nOPN)
    if(b === -1) break

    if(b <= a) break

    for(var i = a; i < b + nCLS; ++i){
      if((i < a + nOPN) || (i >= b)) {
        map[i] = null
        str = str.substr(0, i) + " " + str.substr(i + 1)
      } else {
        if(map[i] !== null) {
          var pos = map[i].indexOf(TAG_CHR[0])
          if(pos === -1) {
            map[i] += TAG_CHR
          } else { // i.e. to handle multiple sub/super-scripts
            if(isRecursive) {
              // i.e to increase the sub/sup number
              map[i] = map[i].substr(0, pos + 1) + (1 + parseInt(map[i][pos + 1])) + map[i].substr(pos + 2)
            }
          }
        }
      }
    }

    var start = a + nOPN
    var remainingStr = str.substr(start, b - start)

    var c = remainingStr.indexOf(opnTag)
    if(c !== -1) a = c
    else a = b + nCLS
  }

  return map
}

function transformPositions(positions, options, size) {
  var align = options.textAlign || "start"
  var baseline = options.textBaseline || "alphabetic"

  var lo = [1<<30, 1<<30]
  var hi = [0,0]
  var n = positions.length
  for(var i=0; i<n; ++i) {
    var p = positions[i]
    for(var j=0; j<2; ++j) {
      lo[j] = Math.min(lo[j], p[j])|0
      hi[j] = Math.max(hi[j], p[j])|0
    }
  }

  var xShift = 0
  switch(align) {
    case "center":
      xShift = -0.5 * (lo[0] + hi[0])
    break

    case "right":
    case "end":
      xShift = -hi[0]
    break

    case "left":
    case "start":
      xShift = -lo[0]
    break

    default:
      throw new Error("vectorize-text: Unrecognized textAlign: '" + align + "'")
  }

  var yShift = 0
  switch(baseline) {
    case "hanging":
    case "top":
      yShift = -lo[1]
    break

    case "middle":
      yShift = -0.5 * (lo[1] + hi[1])
    break

    case "alphabetic":
    case "ideographic":
      yShift = -3 * size
    break

    case "bottom":
      yShift = -hi[1]
    break

    default:
      throw new Error("vectorize-text: Unrecoginized textBaseline: '" + baseline + "'")
  }

  var scale = 1.0 / size
  if("lineHeight" in options) {
    scale *= +options.lineHeight
  } else if("width" in options) {
    scale = options.width / (hi[0] - lo[0])
  } else if("height" in options) {
    scale = options.height / (hi[1] - lo[1])
  }

  return positions.map(function(p) {
    return [ scale * (p[0] + xShift), scale * (p[1] + yShift) ]
  })
}

function getPixels(canvas, context, rawString, fontSize, lineSpacing, styletags) {

  rawString = rawString.replace(/\n/g, '') // don't accept \n in the input

  if(styletags.breaklines === true) {
    rawString = rawString.replace(/\<br\>/g, '\n') // replace <br> tags with \n in the string
  } else {
    rawString = rawString.replace(/\<br\>/g, ' ') // don't accept <br> tags in the input and replace with space in this case
  }

  var activeStyle = ""
  var map = []
  for(j = 0; j < rawString.length; ++j) {
    map[j] = activeStyle
  }

  if(styletags.bolds === true) map = parseTag(TAG_bold, CHR_bold, rawString, map)
  if(styletags.italics === true) map = parseTag(TAG_italic, CHR_italic, rawString, map)
  if(styletags.superscripts === true) map = parseTag(TAG_super, CHR_super, rawString, map)
  if(styletags.subscripts === true) map = parseTag(TAG_sub, CHR_sub, rawString, map)

  var allStyles = []
  var plainText = ""
  for(j = 0; j < rawString.length; ++j) {
    if(map[j] !== null) {
      plainText += rawString[j]
      allStyles.push(map[j])
    }
  }

  var allTexts = plainText.split('\n')

  var numberOfLines = allTexts.length
  var lineHeight = Math.round(lineSpacing * fontSize)
  var offsetX = fontSize
  var offsetY = fontSize * 2
  var maxWidth = 0
  var minHeight = numberOfLines * lineHeight + offsetY

  if(canvas.height < minHeight) {
    canvas.height = minHeight
  }

  context.fillStyle = "#000"
  context.fillRect(0, 0, canvas.width, canvas.height)

  context.fillStyle = "#fff"
  var i, j, xPos, yPos, zPos
  var nDone = 0

  var buffer = ""
  function writeBuffer() {
    if(buffer !== "") {
      var delta = context.measureText(buffer).width

      context.fillText(buffer, offsetX + xPos, offsetY + yPos)
      xPos += delta
    }
  }

  function getTextFontSize() {
    return "" + Math.round(zPos) + "px ";
  }

  function changeStyle(oldStyle, newStyle) {
    var ctxFont = "" + context.font;

    if(styletags.subscripts === true) {
      var oldIndex_Sub = oldStyle.indexOf(CHR_sub0);
      var newIndex_Sub = newStyle.indexOf(CHR_sub0);

      var oldSub = (oldIndex_Sub > -1) ? parseInt(oldStyle[1 + oldIndex_Sub]) : 0;
      var newSub = (newIndex_Sub > -1) ? parseInt(newStyle[1 + newIndex_Sub]) : 0;

      if(oldSub !== newSub) {
        ctxFont = ctxFont.replace(getTextFontSize(), "?px ")
        zPos *= Math.pow(0.75, (newSub - oldSub))
        ctxFont = ctxFont.replace("?px ", getTextFontSize())
      }
      yPos += 0.25 * lineHeight * (newSub - oldSub);
    }

    if(styletags.superscripts === true) {
      var oldIndex_Super = oldStyle.indexOf(CHR_super0);
      var newIndex_Super = newStyle.indexOf(CHR_super0);

      var oldSuper = (oldIndex_Super > -1) ? parseInt(oldStyle[1 + oldIndex_Super]) : 0;
      var newSuper = (newIndex_Super > -1) ? parseInt(newStyle[1 + newIndex_Super]) : 0;

      if(oldSuper !== newSuper) {
        ctxFont = ctxFont.replace(getTextFontSize(), "?px ")
        zPos *= Math.pow(0.75, (newSuper - oldSuper))
        ctxFont = ctxFont.replace("?px ", getTextFontSize())
      }
      yPos -= 0.25 * lineHeight * (newSuper - oldSuper);
    }

    if(styletags.bolds === true) {
      var wasBold = (oldStyle.indexOf(CHR_bold) > -1)
      var is_Bold = (newStyle.indexOf(CHR_bold) > -1)

      if(!wasBold && is_Bold) {
        if(wasItalic) {
          ctxFont = ctxFont.replace("italic ", "italic bold ")
        } else {
          ctxFont = "bold " + ctxFont
        }
      }
      if(wasBold && !is_Bold) {
        ctxFont = ctxFont.replace("bold ", '')
      }
    }

    if(styletags.italics === true) {
      var wasItalic = (oldStyle.indexOf(CHR_italic) > -1)
      var is_Italic = (newStyle.indexOf(CHR_italic) > -1)

      if(!wasItalic && is_Italic) {
        ctxFont = "italic " + ctxFont
      }
      if(wasItalic && !is_Italic) {
        ctxFont = ctxFont.replace("italic ", '')
      }
    }
    context.font = ctxFont
  }

  for(i = 0; i < numberOfLines; ++i) {
    var txt = allTexts[i] + '\n'
    xPos = 0
    yPos = i * lineHeight
    zPos = fontSize

    buffer = ""
    
    for(j = 0; j < txt.length; ++j) {
      var style = (j + nDone < allStyles.length) ? allStyles[j + nDone] : allStyles[allStyles.length - 1]
      if(activeStyle === style) {
        buffer += txt[j]
      } else {
        writeBuffer()
        buffer = txt[j]

        if(style !== undefined) {
          changeStyle(activeStyle, style)
          activeStyle = style
        }
      }
    }
    writeBuffer()

    nDone += txt.length

    var width = Math.round(xPos + 2 * offsetX) | 0
    if(maxWidth < width) maxWidth = width
  }

  //Cut pixels from image
  var xCut = maxWidth
  var yCut = offsetY + lineHeight * numberOfLines
  var pixels = ndarray(context.getImageData(0, 0, xCut, yCut).data, [yCut, xCut, 4])
  return pixels.pick(-1, -1, 0).transpose(1, 0)
}

function getContour(pixels, doSimplify) {
  var contour = surfaceNets(pixels, 128)
  if(doSimplify) {
    return simplify(contour.cells, contour.positions, 0.25)
  }
  return {
    edges: contour.cells,
    positions: contour.positions
  }
}

function processPixelsImpl(pixels, options, size, simplify) {
  //Extract contour
  var contour = getContour(pixels, simplify)

  //Apply warp to positions
  var positions = transformPositions(contour.positions, options, size)
  var edges     = contour.edges
  var flip = "ccw" === options.orientation

  //Clean up the PSLG, resolve self intersections, etc.
  cleanPSLG(positions, edges)

  //If triangulate flag passed, triangulate the result
  if(options.polygons || options.polygon || options.polyline) {
    var result = toPolygonCrappy(edges, positions)
    var nresult = new Array(result.length)
    for(var i=0; i<result.length; ++i) {
      var loops = result[i]
      var nloops = new Array(loops.length)
      for(var j=0; j<loops.length; ++j) {
        var loop = loops[j]
        var nloop = new Array(loop.length)
        for(var k=0; k<loop.length; ++k) {
          nloop[k] = positions[loop[k]].slice()
        }
        if(flip) {
          nloop.reverse()
        }
        nloops[j] = nloop
      }
      nresult[i] = nloops
    }
    return nresult
  } else if(options.triangles || options.triangulate || options.triangle) {
    return {
      cells: cdt2d(positions, edges, {
        delaunay: false,
        exterior: false,
        interior: true
      }),
      positions: positions
    }
  } else {
    return {
      edges:     edges,
      positions: positions
    }
  }
}

function processPixels(pixels, options, size) {
  try {
    return processPixelsImpl(pixels, options, size, true)
  } catch(e) {}
  try {
    return processPixelsImpl(pixels, options, size, false)
  } catch(e) {}
  if(options.polygons || options.polyline || options.polygon) {
    return []
  }
  if(options.triangles || options.triangulate || options.triangle) {
    return {
      cells: [],
      positions: []
    }
  }
  return {
    edges: [],
    positions: []
  }
}

function vectorizeText(str, canvas, context, options) {
  var size = 64
  var lineSpacing = 1.25
  var styletags = {
    breaklines: false,
    bolds: false,
    italics: false,
    subscripts: false,
    superscripts: false
  }

  if(options) {

    if(options.size &&
       options.size > 0) size =
       options.size

    if(options.lineSpacing &&
       options.lineSpacing > 0) lineSpacing =
       options.lineSpacing

    if(options.styletags &&
       options.styletags.breaklines) styletags.breaklines =
       options.styletags.breaklines ? true : false

    if(options.styletags &&
       options.styletags.bolds) styletags.bolds =
       options.styletags.bolds ? true : false

    if(options.styletags &&
       options.styletags.italics) styletags.italics =
       options.styletags.italics ? true : false

    if(options.styletags &&
       options.styletags.subscripts) styletags.subscripts =
       options.styletags.subscripts ? true : false

    if(options.styletags &&
       options.styletags.superscripts) styletags.superscripts =
       options.styletags.superscripts ? true : false
  }

  context.font = [
    options.fontStyle,
    options.fontVariant,
    options.fontWeight,
    size + "px",
    options.font
  ].filter(function(d) {return d}).join(" ")
  context.textAlign = "start"
  context.textBaseline = "alphabetic"
  context.direction = "ltr"

  var pixels = getPixels(canvas, context, str, size, lineSpacing, styletags)

  return processPixels(pixels, options, size)
}

},{"cdt2d":94,"clean-pslg":104,"ndarray":439,"planar-graph-to-polyline":457,"simplify-planar-graph":505,"surface-nets":512}],533:[function(_dereq_,module,exports){
// Copyright (C) 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Install a leaky WeakMap emulation on platforms that
 * don't provide a built-in one.
 *
 * <p>Assumes that an ES5 platform where, if {@code WeakMap} is
 * already present, then it conforms to the anticipated ES6
 * specification. To run this file on an ES5 or almost ES5
 * implementation where the {@code WeakMap} specification does not
 * quite conform, run <code>repairES5.js</code> first.
 *
 * <p>Even though WeakMapModule is not global, the linter thinks it
 * is, which is why it is in the overrides list below.
 *
 * <p>NOTE: Before using this WeakMap emulation in a non-SES
 * environment, see the note below about hiddenRecord.
 *
 * @author Mark S. Miller
 * @requires crypto, ArrayBuffer, Uint8Array, navigator, console
 * @overrides WeakMap, ses, Proxy
 * @overrides WeakMapModule
 */

/**
 * This {@code WeakMap} emulation is observably equivalent to the
 * ES-Harmony WeakMap, but with leakier garbage collection properties.
 *
 * <p>As with true WeakMaps, in this emulation, a key does not
 * retain maps indexed by that key and (crucially) a map does not
 * retain the keys it indexes. A map by itself also does not retain
 * the values associated with that map.
 *
 * <p>However, the values associated with a key in some map are
 * retained so long as that key is retained and those associations are
 * not overridden. For example, when used to support membranes, all
 * values exported from a given membrane will live for the lifetime
 * they would have had in the absence of an interposed membrane. Even
 * when the membrane is revoked, all objects that would have been
 * reachable in the absence of revocation will still be reachable, as
 * far as the GC can tell, even though they will no longer be relevant
 * to ongoing computation.
 *
 * <p>The API implemented here is approximately the API as implemented
 * in FF6.0a1 and agreed to by MarkM, Andreas Gal, and Dave Herman,
 * rather than the offially approved proposal page. TODO(erights):
 * upgrade the ecmascript WeakMap proposal page to explain this API
 * change and present to EcmaScript committee for their approval.
 *
 * <p>The first difference between the emulation here and that in
 * FF6.0a1 is the presence of non enumerable {@code get___, has___,
 * set___, and delete___} methods on WeakMap instances to represent
 * what would be the hidden internal properties of a primitive
 * implementation. Whereas the FF6.0a1 WeakMap.prototype methods
 * require their {@code this} to be a genuine WeakMap instance (i.e.,
 * an object of {@code [[Class]]} "WeakMap}), since there is nothing
 * unforgeable about the pseudo-internal method names used here,
 * nothing prevents these emulated prototype methods from being
 * applied to non-WeakMaps with pseudo-internal methods of the same
 * names.
 *
 * <p>Another difference is that our emulated {@code
 * WeakMap.prototype} is not itself a WeakMap. A problem with the
 * current FF6.0a1 API is that WeakMap.prototype is itself a WeakMap
 * providing ambient mutability and an ambient communications
 * channel. Thus, if a WeakMap is already present and has this
 * problem, repairES5.js wraps it in a safe wrappper in order to
 * prevent access to this channel. (See
 * PATCH_MUTABLE_FROZEN_WEAKMAP_PROTO in repairES5.js).
 */

/**
 * If this is a full <a href=
 * "http://code.google.com/p/es-lab/wiki/SecureableES5"
 * >secureable ES5</a> platform and the ES-Harmony {@code WeakMap} is
 * absent, install an approximate emulation.
 *
 * <p>If WeakMap is present but cannot store some objects, use our approximate
 * emulation as a wrapper.
 *
 * <p>If this is almost a secureable ES5 platform, then WeakMap.js
 * should be run after repairES5.js.
 *
 * <p>See {@code WeakMap} for documentation of the garbage collection
 * properties of this WeakMap emulation.
 */
(function WeakMapModule() {
  "use strict";

  if (typeof ses !== 'undefined' && ses.ok && !ses.ok()) {
    // already too broken, so give up
    return;
  }

  /**
   * In some cases (current Firefox), we must make a choice betweeen a
   * WeakMap which is capable of using all varieties of host objects as
   * keys and one which is capable of safely using proxies as keys. See
   * comments below about HostWeakMap and DoubleWeakMap for details.
   *
   * This function (which is a global, not exposed to guests) marks a
   * WeakMap as permitted to do what is necessary to index all host
   * objects, at the cost of making it unsafe for proxies.
   *
   * Do not apply this function to anything which is not a genuine
   * fresh WeakMap.
   */
  function weakMapPermitHostObjects(map) {
    // identity of function used as a secret -- good enough and cheap
    if (map.permitHostObjects___) {
      map.permitHostObjects___(weakMapPermitHostObjects);
    }
  }
  if (typeof ses !== 'undefined') {
    ses.weakMapPermitHostObjects = weakMapPermitHostObjects;
  }

  // IE 11 has no Proxy but has a broken WeakMap such that we need to patch
  // it using DoubleWeakMap; this flag tells DoubleWeakMap so.
  var doubleWeakMapCheckSilentFailure = false;

  // Check if there is already a good-enough WeakMap implementation, and if so
  // exit without replacing it.
  if (typeof WeakMap === 'function') {
    var HostWeakMap = WeakMap;
    // There is a WeakMap -- is it good enough?
    if (typeof navigator !== 'undefined' &&
        /Firefox/.test(navigator.userAgent)) {
      // We're now *assuming not*, because as of this writing (2013-05-06)
      // Firefox's WeakMaps have a miscellany of objects they won't accept, and
      // we don't want to make an exhaustive list, and testing for just one
      // will be a problem if that one is fixed alone (as they did for Event).

      // If there is a platform that we *can* reliably test on, here's how to
      // do it:
      //  var problematic = ... ;
      //  var testHostMap = new HostWeakMap();
      //  try {
      //    testHostMap.set(problematic, 1);  // Firefox 20 will throw here
      //    if (testHostMap.get(problematic) === 1) {
      //      return;
      //    }
      //  } catch (e) {}

    } else {
      // IE 11 bug: WeakMaps silently fail to store frozen objects.
      var testMap = new HostWeakMap();
      var testObject = Object.freeze({});
      testMap.set(testObject, 1);
      if (testMap.get(testObject) !== 1) {
        doubleWeakMapCheckSilentFailure = true;
        // Fall through to installing our WeakMap.
      } else {
        module.exports = WeakMap;
        return;
      }
    }
  }

  var hop = Object.prototype.hasOwnProperty;
  var gopn = Object.getOwnPropertyNames;
  var defProp = Object.defineProperty;
  var isExtensible = Object.isExtensible;

  /**
   * Security depends on HIDDEN_NAME being both <i>unguessable</i> and
   * <i>undiscoverable</i> by untrusted code.
   *
   * <p>Given the known weaknesses of Math.random() on existing
   * browsers, it does not generate unguessability we can be confident
   * of.
   *
   * <p>It is the monkey patching logic in this file that is intended
   * to ensure undiscoverability. The basic idea is that there are
   * three fundamental means of discovering properties of an object:
   * The for/in loop, Object.keys(), and Object.getOwnPropertyNames(),
   * as well as some proposed ES6 extensions that appear on our
   * whitelist. The first two only discover enumerable properties, and
   * we only use HIDDEN_NAME to name a non-enumerable property, so the
   * only remaining threat should be getOwnPropertyNames and some
   * proposed ES6 extensions that appear on our whitelist. We monkey
   * patch them to remove HIDDEN_NAME from the list of properties they
   * returns.
   *
   * <p>TODO(erights): On a platform with built-in Proxies, proxies
   * could be used to trap and thereby discover the HIDDEN_NAME, so we
   * need to monkey patch Proxy.create, Proxy.createFunction, etc, in
   * order to wrap the provided handler with the real handler which
   * filters out all traps using HIDDEN_NAME.
   *
   * <p>TODO(erights): Revisit Mike Stay's suggestion that we use an
   * encapsulated function at a not-necessarily-secret name, which
   * uses the Stiegler shared-state rights amplification pattern to
   * reveal the associated value only to the WeakMap in which this key
   * is associated with that value. Since only the key retains the
   * function, the function can also remember the key without causing
   * leakage of the key, so this doesn't violate our general gc
   * goals. In addition, because the name need not be a guarded
   * secret, we could efficiently handle cross-frame frozen keys.
   */
  var HIDDEN_NAME_PREFIX = 'weakmap:';
  var HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'ident:' + Math.random() + '___';

  if (typeof crypto !== 'undefined' &&
      typeof crypto.getRandomValues === 'function' &&
      typeof ArrayBuffer === 'function' &&
      typeof Uint8Array === 'function') {
    var ab = new ArrayBuffer(25);
    var u8s = new Uint8Array(ab);
    crypto.getRandomValues(u8s);
    HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'rand:' +
      Array.prototype.map.call(u8s, function(u8) {
        return (u8 % 36).toString(36);
      }).join('') + '___';
  }

  function isNotHiddenName(name) {
    return !(
        name.substr(0, HIDDEN_NAME_PREFIX.length) == HIDDEN_NAME_PREFIX &&
        name.substr(name.length - 3) === '___');
  }

  /**
   * Monkey patch getOwnPropertyNames to avoid revealing the
   * HIDDEN_NAME.
   *
   * <p>The ES5.1 spec requires each name to appear only once, but as
   * of this writing, this requirement is controversial for ES6, so we
   * made this code robust against this case. If the resulting extra
   * search turns out to be expensive, we can probably relax this once
   * ES6 is adequately supported on all major browsers, iff no browser
   * versions we support at that time have relaxed this constraint
   * without providing built-in ES6 WeakMaps.
   */
  defProp(Object, 'getOwnPropertyNames', {
    value: function fakeGetOwnPropertyNames(obj) {
      return gopn(obj).filter(isNotHiddenName);
    }
  });

  /**
   * getPropertyNames is not in ES5 but it is proposed for ES6 and
   * does appear in our whitelist, so we need to clean it too.
   */
  if ('getPropertyNames' in Object) {
    var originalGetPropertyNames = Object.getPropertyNames;
    defProp(Object, 'getPropertyNames', {
      value: function fakeGetPropertyNames(obj) {
        return originalGetPropertyNames(obj).filter(isNotHiddenName);
      }
    });
  }

  /**
   * <p>To treat objects as identity-keys with reasonable efficiency
   * on ES5 by itself (i.e., without any object-keyed collections), we
   * need to add a hidden property to such key objects when we
   * can. This raises several issues:
   * <ul>
   * <li>Arranging to add this property to objects before we lose the
   *     chance, and
   * <li>Hiding the existence of this new property from most
   *     JavaScript code.
   * <li>Preventing <i>certification theft</i>, where one object is
   *     created falsely claiming to be the key of an association
   *     actually keyed by another object.
   * <li>Preventing <i>value theft</i>, where untrusted code with
   *     access to a key object but not a weak map nevertheless
   *     obtains access to the value associated with that key in that
   *     weak map.
   * </ul>
   * We do so by
   * <ul>
   * <li>Making the name of the hidden property unguessable, so "[]"
   *     indexing, which we cannot intercept, cannot be used to access
   *     a property without knowing the name.
   * <li>Making the hidden property non-enumerable, so we need not
   *     worry about for-in loops or {@code Object.keys},
   * <li>monkey patching those reflective methods that would
   *     prevent extensions, to add this hidden property first,
   * <li>monkey patching those methods that would reveal this
   *     hidden property.
   * </ul>
   * Unfortunately, because of same-origin iframes, we cannot reliably
   * add this hidden property before an object becomes
   * non-extensible. Instead, if we encounter a non-extensible object
   * without a hidden record that we can detect (whether or not it has
   * a hidden record stored under a name secret to us), then we just
   * use the key object itself to represent its identity in a brute
   * force leaky map stored in the weak map, losing all the advantages
   * of weakness for these.
   */
  function getHiddenRecord(key) {
    if (key !== Object(key)) {
      throw new TypeError('Not an object: ' + key);
    }
    var hiddenRecord = key[HIDDEN_NAME];
    if (hiddenRecord && hiddenRecord.key === key) { return hiddenRecord; }
    if (!isExtensible(key)) {
      // Weak map must brute force, as explained in doc-comment above.
      return void 0;
    }

    // The hiddenRecord and the key point directly at each other, via
    // the "key" and HIDDEN_NAME properties respectively. The key
    // field is for quickly verifying that this hidden record is an
    // own property, not a hidden record from up the prototype chain.
    //
    // NOTE: Because this WeakMap emulation is meant only for systems like
    // SES where Object.prototype is frozen without any numeric
    // properties, it is ok to use an object literal for the hiddenRecord.
    // This has two advantages:
    // * It is much faster in a performance critical place
    // * It avoids relying on Object.create(null), which had been
    //   problematic on Chrome 28.0.1480.0. See
    //   https://code.google.com/p/google-caja/issues/detail?id=1687
    hiddenRecord = { key: key };

    // When using this WeakMap emulation on platforms where
    // Object.prototype might not be frozen and Object.create(null) is
    // reliable, use the following two commented out lines instead.
    // hiddenRecord = Object.create(null);
    // hiddenRecord.key = key;

    // Please contact us if you need this to work on platforms where
    // Object.prototype might not be frozen and
    // Object.create(null) might not be reliable.

    try {
      defProp(key, HIDDEN_NAME, {
        value: hiddenRecord,
        writable: false,
        enumerable: false,
        configurable: false
      });
      return hiddenRecord;
    } catch (error) {
      // Under some circumstances, isExtensible seems to misreport whether
      // the HIDDEN_NAME can be defined.
      // The circumstances have not been isolated, but at least affect
      // Node.js v0.10.26 on TravisCI / Linux, but not the same version of
      // Node.js on OS X.
      return void 0;
    }
  }

  /**
   * Monkey patch operations that would make their argument
   * non-extensible.
   *
   * <p>The monkey patched versions throw a TypeError if their
   * argument is not an object, so it should only be done to functions
   * that should throw a TypeError anyway if their argument is not an
   * object.
   */
  (function(){
    var oldFreeze = Object.freeze;
    defProp(Object, 'freeze', {
      value: function identifyingFreeze(obj) {
        getHiddenRecord(obj);
        return oldFreeze(obj);
      }
    });
    var oldSeal = Object.seal;
    defProp(Object, 'seal', {
      value: function identifyingSeal(obj) {
        getHiddenRecord(obj);
        return oldSeal(obj);
      }
    });
    var oldPreventExtensions = Object.preventExtensions;
    defProp(Object, 'preventExtensions', {
      value: function identifyingPreventExtensions(obj) {
        getHiddenRecord(obj);
        return oldPreventExtensions(obj);
      }
    });
  })();

  function constFunc(func) {
    func.prototype = null;
    return Object.freeze(func);
  }

  var calledAsFunctionWarningDone = false;
  function calledAsFunctionWarning() {
    // Future ES6 WeakMap is currently (2013-09-10) expected to reject WeakMap()
    // but we used to permit it and do it ourselves, so warn only.
    if (!calledAsFunctionWarningDone && typeof console !== 'undefined') {
      calledAsFunctionWarningDone = true;
      console.warn('WeakMap should be invoked as new WeakMap(), not ' +
          'WeakMap(). This will be an error in the future.');
    }
  }

  var nextId = 0;

  var OurWeakMap = function() {
    if (!(this instanceof OurWeakMap)) {  // approximate test for new ...()
      calledAsFunctionWarning();
    }

    // We are currently (12/25/2012) never encountering any prematurely
    // non-extensible keys.
    var keys = []; // brute force for prematurely non-extensible keys.
    var values = []; // brute force for corresponding values.
    var id = nextId++;

    function get___(key, opt_default) {
      var index;
      var hiddenRecord = getHiddenRecord(key);
      if (hiddenRecord) {
        return id in hiddenRecord ? hiddenRecord[id] : opt_default;
      } else {
        index = keys.indexOf(key);
        return index >= 0 ? values[index] : opt_default;
      }
    }

    function has___(key) {
      var hiddenRecord = getHiddenRecord(key);
      if (hiddenRecord) {
        return id in hiddenRecord;
      } else {
        return keys.indexOf(key) >= 0;
      }
    }

    function set___(key, value) {
      var index;
      var hiddenRecord = getHiddenRecord(key);
      if (hiddenRecord) {
        hiddenRecord[id] = value;
      } else {
        index = keys.indexOf(key);
        if (index >= 0) {
          values[index] = value;
        } else {
          // Since some browsers preemptively terminate slow turns but
          // then continue computing with presumably corrupted heap
          // state, we here defensively get keys.length first and then
          // use it to update both the values and keys arrays, keeping
          // them in sync.
          index = keys.length;
          values[index] = value;
          // If we crash here, values will be one longer than keys.
          keys[index] = key;
        }
      }
      return this;
    }

    function delete___(key) {
      var hiddenRecord = getHiddenRecord(key);
      var index, lastIndex;
      if (hiddenRecord) {
        return id in hiddenRecord && delete hiddenRecord[id];
      } else {
        index = keys.indexOf(key);
        if (index < 0) {
          return false;
        }
        // Since some browsers preemptively terminate slow turns but
        // then continue computing with potentially corrupted heap
        // state, we here defensively get keys.length first and then use
        // it to update both the keys and the values array, keeping
        // them in sync. We update the two with an order of assignments,
        // such that any prefix of these assignments will preserve the
        // key/value correspondence, either before or after the delete.
        // Note that this needs to work correctly when index === lastIndex.
        lastIndex = keys.length - 1;
        keys[index] = void 0;
        // If we crash here, there's a void 0 in the keys array, but
        // no operation will cause a "keys.indexOf(void 0)", since
        // getHiddenRecord(void 0) will always throw an error first.
        values[index] = values[lastIndex];
        // If we crash here, values[index] cannot be found here,
        // because keys[index] is void 0.
        keys[index] = keys[lastIndex];
        // If index === lastIndex and we crash here, then keys[index]
        // is still void 0, since the aliasing killed the previous key.
        keys.length = lastIndex;
        // If we crash here, keys will be one shorter than values.
        values.length = lastIndex;
        return true;
      }
    }

    return Object.create(OurWeakMap.prototype, {
      get___:    { value: constFunc(get___) },
      has___:    { value: constFunc(has___) },
      set___:    { value: constFunc(set___) },
      delete___: { value: constFunc(delete___) }
    });
  };

  OurWeakMap.prototype = Object.create(Object.prototype, {
    get: {
      /**
       * Return the value most recently associated with key, or
       * opt_default if none.
       */
      value: function get(key, opt_default) {
        return this.get___(key, opt_default);
      },
      writable: true,
      configurable: true
    },

    has: {
      /**
       * Is there a value associated with key in this WeakMap?
       */
      value: function has(key) {
        return this.has___(key);
      },
      writable: true,
      configurable: true
    },

    set: {
      /**
       * Associate value with key in this WeakMap, overwriting any
       * previous association if present.
       */
      value: function set(key, value) {
        return this.set___(key, value);
      },
      writable: true,
      configurable: true
    },

    'delete': {
      /**
       * Remove any association for key in this WeakMap, returning
       * whether there was one.
       *
       * <p>Note that the boolean return here does not work like the
       * {@code delete} operator. The {@code delete} operator returns
       * whether the deletion succeeds at bringing about a state in
       * which the deleted property is absent. The {@code delete}
       * operator therefore returns true if the property was already
       * absent, whereas this {@code delete} method returns false if
       * the association was already absent.
       */
      value: function remove(key) {
        return this.delete___(key);
      },
      writable: true,
      configurable: true
    }
  });

  if (typeof HostWeakMap === 'function') {
    (function() {
      // If we got here, then the platform has a WeakMap but we are concerned
      // that it may refuse to store some key types. Therefore, make a map
      // implementation which makes use of both as possible.

      // In this mode we are always using double maps, so we are not proxy-safe.
      // This combination does not occur in any known browser, but we had best
      // be safe.
      if (doubleWeakMapCheckSilentFailure && typeof Proxy !== 'undefined') {
        Proxy = undefined;
      }

      function DoubleWeakMap() {
        if (!(this instanceof OurWeakMap)) {  // approximate test for new ...()
          calledAsFunctionWarning();
        }

        // Preferable, truly weak map.
        var hmap = new HostWeakMap();

        // Our hidden-property-based pseudo-weak-map. Lazily initialized in the
        // 'set' implementation; thus we can avoid performing extra lookups if
        // we know all entries actually stored are entered in 'hmap'.
        var omap = undefined;

        // Hidden-property maps are not compatible with proxies because proxies
        // can observe the hidden name and either accidentally expose it or fail
        // to allow the hidden property to be set. Therefore, we do not allow
        // arbitrary WeakMaps to switch to using hidden properties, but only
        // those which need the ability, and unprivileged code is not allowed
        // to set the flag.
        //
        // (Except in doubleWeakMapCheckSilentFailure mode in which case we
        // disable proxies.)
        var enableSwitching = false;

        function dget(key, opt_default) {
          if (omap) {
            return hmap.has(key) ? hmap.get(key)
                : omap.get___(key, opt_default);
          } else {
            return hmap.get(key, opt_default);
          }
        }

        function dhas(key) {
          return hmap.has(key) || (omap ? omap.has___(key) : false);
        }

        var dset;
        if (doubleWeakMapCheckSilentFailure) {
          dset = function(key, value) {
            hmap.set(key, value);
            if (!hmap.has(key)) {
              if (!omap) { omap = new OurWeakMap(); }
              omap.set(key, value);
            }
            return this;
          };
        } else {
          dset = function(key, value) {
            if (enableSwitching) {
              try {
                hmap.set(key, value);
              } catch (e) {
                if (!omap) { omap = new OurWeakMap(); }
                omap.set___(key, value);
              }
            } else {
              hmap.set(key, value);
            }
            return this;
          };
        }

        function ddelete(key) {
          var result = !!hmap['delete'](key);
          if (omap) { return omap.delete___(key) || result; }
          return result;
        }

        return Object.create(OurWeakMap.prototype, {
          get___:    { value: constFunc(dget) },
          has___:    { value: constFunc(dhas) },
          set___:    { value: constFunc(dset) },
          delete___: { value: constFunc(ddelete) },
          permitHostObjects___: { value: constFunc(function(token) {
            if (token === weakMapPermitHostObjects) {
              enableSwitching = true;
            } else {
              throw new Error('bogus call to permitHostObjects___');
            }
          })}
        });
      }
      DoubleWeakMap.prototype = OurWeakMap.prototype;
      module.exports = DoubleWeakMap;

      // define .constructor to hide OurWeakMap ctor
      Object.defineProperty(WeakMap.prototype, 'constructor', {
        value: WeakMap,
        enumerable: false,  // as default .constructor is
        configurable: true,
        writable: true
      });
    })();
  } else {
    // There is no host WeakMap, so we must use the emulation.

    // Emulated WeakMaps are incompatible with native proxies (because proxies
    // can observe the hidden name), so we must disable Proxy usage (in
    // ArrayLike and Domado, currently).
    if (typeof Proxy !== 'undefined') {
      Proxy = undefined;
    }

    module.exports = OurWeakMap;
  }
})();

},{}],534:[function(_dereq_,module,exports){
var hiddenStore = _dereq_('./hidden-store.js');

module.exports = createStore;

function createStore() {
    var key = {};

    return function (obj) {
        if ((typeof obj !== 'object' || obj === null) &&
            typeof obj !== 'function'
        ) {
            throw new Error('Weakmap-shim: Key must be object')
        }

        var store = obj.valueOf(key);
        return store && store.identity === key ?
            store : hiddenStore(obj, key);
    };
}

},{"./hidden-store.js":535}],535:[function(_dereq_,module,exports){
module.exports = hiddenStore;

function hiddenStore(obj, key) {
    var store = { identity: key };
    var valueOf = obj.valueOf;

    Object.defineProperty(obj, "valueOf", {
        value: function (value) {
            return value !== key ?
                valueOf.apply(this, arguments) : store;
        },
        writable: true
    });

    return store;
}

},{}],536:[function(_dereq_,module,exports){
// Original - @Gozola.
// https://gist.github.com/Gozala/1269991
// This is a reimplemented version (with a few bug fixes).

var createStore = _dereq_('./create-store.js');

module.exports = weakMap;

function weakMap() {
    var privates = createStore();

    return {
        'get': function (key, fallback) {
            var store = privates(key)
            return store.hasOwnProperty('value') ?
                store.value : fallback
        },
        'set': function (key, value) {
            privates(key).value = value;
            return this;
        },
        'has': function(key) {
            return 'value' in privates(key);
        },
        'delete': function (key) {
            return delete privates(key).value;
        }
    }
}

},{"./create-store.js":534}],537:[function(_dereq_,module,exports){
var getContext = _dereq_('get-canvas-context')

module.exports = function getWebGLContext (opt) {
  return getContext('webgl', opt)
}

},{"get-canvas-context":225}],538:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Traditional Chinese calendar for jQuery v2.0.2.
   Written by Nicolas Riesco (enquiries@nicolasriesco.net) December 2016.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


var gregorianCalendar = main.instance();

/** Implementation of the traditional Chinese calendar.
    Source of calendar tables https://github.com/isee15/Lunar-Solar-Calendar-Converter .
    @class ChineseCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function ChineseCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

ChineseCalendar.prototype = new main.baseCalendar;

assign(ChineseCalendar.prototype, {
    /** The calendar name.
        @memberof ChineseCalendar */
    name: 'Chinese',
     /** Julian date of start of Gregorian epoch: 1 January 0001 CE.
        @memberof GregorianCalendar */
    jdEpoch: 1721425.5,
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof ChineseCalendar */
    hasYearZero: false,
    /** The minimum month number.
        This calendar uses month indices to account for intercalary months. 
        @memberof ChineseCalendar */
    minMonth: 0,
    /** The first month in the year.
        This calendar uses month indices to account for intercalary months. 
        @memberof ChineseCalendar */
    firstMonth: 0,
    /** The minimum day number.
        @memberof ChineseCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof ChineseCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Chinese',
            epochs: ['BEC', 'EC'],
            monthNumbers: function(date, padded) {
                if (typeof date === 'string') {
                    var match = date.match(MONTH_NUMBER_REGEXP);
                    return (match) ? match[0] : '';
                }

                var year = this._validateYear(date);
                var monthIndex = date.month();

                var month = '' + this.toChineseMonth(year, monthIndex);

                if (padded && month.length < 2) {
                    month = "0" + month;
                }

                if (this.isIntercalaryMonth(year, monthIndex)) {
                    month += 'i';
                }

                return month;
            },
            monthNames: function(date) {
                if (typeof date === 'string') {
                    var match = date.match(MONTH_NAME_REGEXP);
                    return (match) ? match[0] : '';
                }

                var year = this._validateYear(date);
                var monthIndex = date.month();

                var month = this.toChineseMonth(year, monthIndex);

                var monthName = ['一月','二月','三月','四月','五月','六月',
                    '七月','八月','九月','十月','十一月','十二月'][month - 1];

                if (this.isIntercalaryMonth(year, monthIndex)) {
                    monthName = '闰' + monthName;
                }

                return monthName;
            },
            monthNamesShort: function(date) {
                if (typeof date === 'string') {
                    var match = date.match(MONTH_SHORT_NAME_REGEXP);
                    return (match) ? match[0] : '';
                }

                var year = this._validateYear(date);
                var monthIndex = date.month();

                var month = this.toChineseMonth(year, monthIndex);

                var monthName = ['一','二','三','四','五','六',
                    '七','八','九','十','十一','十二'][month - 1];

                if (this.isIntercalaryMonth(year, monthIndex)) {
                    monthName = '闰' + monthName;
                }

                return monthName;
            },
            parseMonth: function(year, monthString) {
                year = this._validateYear(year);
                var month = parseInt(monthString);
                var isIntercalary;

                if (!isNaN(month)) {
                    var i = monthString[monthString.length - 1];
                    isIntercalary = (i === 'i' || i === 'I');
                } else {
                    if (monthString[0] === '闰') {
                        isIntercalary = true;
                        monthString = monthString.substring(1);
                    }
                    if (monthString[monthString.length - 1] === '月') {
                        monthString = monthString.substring(0, monthString.length - 1);
                    }
                    month = 1 +
                        ['一','二','三','四','五','六',
                        '七','八','九','十','十一','十二'].indexOf(monthString);
                }

                var monthIndex = this.toMonthIndex(year, month, isIntercalary);
                return monthIndex;
            },
            dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
            dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
            dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
            digits: null,
            dateFormat: 'yyyy/mm/dd',
            firstDay: 1,
            isRTL: false
        }
    },

    /** Check that a candidate date is from the same calendar and is valid.
        @memberof BaseCalendar
        @private
        @param year {CDate|number} The date or the year to validate.
        @param error {string} Error message if invalid.
        @return {number} The year.
        @throws Error if year out of range. */
    _validateYear: function(year, error) {
        if (year.year) {
            year = year.year();
        }

        if (typeof year !== 'number' || year < 1888 || year > 2111) {
            throw error.replace(/\{0\}/, this.local.name);
        }

        return year;
    },

    /** Retrieve the month index (i.e. accounting for intercalary months).
        @memberof ChineseCalendar
        @param year {number} The year.
        @param month {number} The month (1 for first month).
        @param [isIntercalary=false] {boolean} If month is intercalary.
        @return {number} The month index (0 for first month).
        @throws Error if an invalid month/year or a different calendar used. */
    toMonthIndex: function(year, month, isIntercalary) {
        // compute intercalary month in the year (0 if none)
        var intercalaryMonth = this.intercalaryMonth(year);

        // validate month
        var invalidIntercalaryMonth = 
            (isIntercalary && month !== intercalaryMonth);
        if (invalidIntercalaryMonth || month < 1 || month > 12) {
            throw main.local.invalidMonth
                .replace(/\{0\}/, this.local.name);
        }

        // compute month index
        var monthIndex;

        if (!intercalaryMonth) {
            monthIndex = month - 1;
        } else if(!isIntercalary && month <= intercalaryMonth) {
            monthIndex = month - 1;
        } else {
            monthIndex = month;
        }

        return monthIndex;
    },

    /** Retrieve the month (i.e. accounting for intercalary months).
        @memberof ChineseCalendar
        @param year {CDate|number} The date or the year to examine.
        @param monthIndex {number} The month index (0 for first month).
        @return {number} The month (1 for first month).
        @throws Error if an invalid month/year or a different calendar used. */
    toChineseMonth: function(year, monthIndex) {
        if (year.year) {
            year = year.year();
            monthIndex = year.month();
        }

        // compute intercalary month in the year (0 if none)
        var intercalaryMonth = this.intercalaryMonth(year);

        // validate month
        var maxMonthIndex = (intercalaryMonth) ? 12 : 11;
        if (monthIndex < 0 || monthIndex > maxMonthIndex) {
            throw main.local.invalidMonth
                .replace(/\{0\}/, this.local.name);
        }

        // compute Chinese month
        var month;

        if (!intercalaryMonth) {
            month = monthIndex + 1;
        } else if(monthIndex < intercalaryMonth) {
            month = monthIndex + 1;
        } else {
            month = monthIndex;
        }

        return month;
    },

    /** Determine the intercalary month of a year (if any).
        @memberof ChineseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The intercalary month number, or 0 if none.
        @throws Error if an invalid year or a different calendar used. */
    intercalaryMonth: function(year) {
        year = this._validateYear(year);

        var monthDaysTable = LUNAR_MONTH_DAYS[year - LUNAR_MONTH_DAYS[0]];
        var intercalaryMonth = monthDaysTable >> 13;

        return intercalaryMonth;
    },

    /** Determine whether this date is an intercalary month.
        @memberof ChineseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [monthIndex] {number} The month index to examine.
        @return {boolean} <code>true</code> if this is an intercalary month, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    isIntercalaryMonth: function(year, monthIndex) {
        if (year.year) {
            year = year.year();
            monthIndex = year.month();
        }

        var intercalaryMonth = this.intercalaryMonth(year);

        return !!intercalaryMonth && intercalaryMonth === monthIndex;
    },

    /** Determine whether this date is in a leap year.
        @memberof ChineseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        return (this.intercalaryMonth(year) !== 0);
    },

    /** Determine the week of the year for a date - ISO 8601.
        @memberof ChineseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [monthIndex] {number} The month index to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, monthIndex, day) {
        // compute Chinese new year
        var validatedYear =
            this._validateYear(year, main.local.invalidyear);
        var packedDate =
            CHINESE_NEW_YEAR[validatedYear - CHINESE_NEW_YEAR[0]];

        var y = (packedDate >> 9) & 0xFFF;
        var m = (packedDate >> 5) & 0x0F;
        var d = packedDate & 0x1F;
        
        // find first Thrusday of the year
        var firstThursday;
        firstThursday = gregorianCalendar.newDate(y, m, d);
        firstThursday.add(4 - (firstThursday.dayOfWeek() || 7), 'd');

        // compute days from first Thursday
        var offset =
            this.toJD(year, monthIndex, day) - firstThursday.toJD();
        return 1 + Math.floor(offset / 7);
    },

    /** Retrieve the number of months in a year.
        @memberof ChineseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of months.
        @throws Error if an invalid year or a different calendar used. */
    monthsInYear: function(year) {
        return (this.leapYear(year)) ? 13 : 12;
    },

    /** Retrieve the number of days in a month.
        @memberof ChineseCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [monthIndex] {number} The month index.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, monthIndex) {
        if (year.year) {
            monthIndex = year.month();
            year = year.year();
        }

        year = this._validateYear(year);

        var monthDaysTable = LUNAR_MONTH_DAYS[year - LUNAR_MONTH_DAYS[0]];

        var intercalaryMonth = monthDaysTable >> 13;
        var maxMonthIndex = (intercalaryMonth) ? 12 : 11;
        if (monthIndex > maxMonthIndex) {
            throw main.local.invalidMonth
                .replace(/\{0\}/, this.local.name);
        }

        var daysInMonth = (monthDaysTable & (1 << (12 - monthIndex))) ?
            30 : 29;

        return daysInMonth;
    },

    /** Determine whether this date is a week day.
        @memberof ChineseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [monthIndex] {number} The month index to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, monthIndex, day) {
        return (this.dayOfWeek(year, monthIndex, day) || 7) < 6;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof ChineseCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [monthIndex] {number} The month index to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, monthIndex, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        year = this._validateYear(date.year());
        monthIndex = date.month();
        day = date.day();

        var isIntercalary = this.isIntercalaryMonth(year, monthIndex);
        var month = this.toChineseMonth(year, monthIndex);

        var solar = toSolar(year, month, day, isIntercalary);

        return gregorianCalendar.toJD(solar.year, solar.month, solar.day);
    },

    /** Create a new date from a Julian date.
        @memberof ChineseCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        var date = gregorianCalendar.fromJD(jd);
        var lunar = toLunar(date.year(), date.month(), date.day());
        var monthIndex = this.toMonthIndex(
            lunar.year, lunar.month, lunar.isIntercalary);
        return this.newDate(lunar.year, monthIndex, lunar.day);
    },

    /** Create a new date from a string.
        @memberof ChineseCalendar
        @param dateString {string} String representing a Chinese date
        @return {CDate} The new date.
        @throws Error if an invalid date. */
    fromString: function(dateString) {
        var match = dateString.match(DATE_REGEXP);

        var year = this._validateYear(+match[1]);

        var month = +match[2];
        var isIntercalary = !!match[3];
        var monthIndex = this.toMonthIndex(year, month, isIntercalary);

        var day = +match[4];

        return this.newDate(year, monthIndex, day);
    },

    /** Add period(s) to a date.
        Cater for no year zero.
        @memberof ChineseCalendar
        @param date {CDate} The starting date.
        @param offset {number} The number of periods to adjust by.
        @param period {string} One of 'y' for year, 'm' for month, 'w' for week, 'd' for day.
        @return {CDate} The updated date.
        @throws Error if a different calendar used. */
    add: function(date, offset, period) {
        var year = date.year();
        var monthIndex = date.month();
        var isIntercalary = this.isIntercalaryMonth(year, monthIndex);
        var month = this.toChineseMonth(year, monthIndex);

        var cdate = Object.getPrototypeOf(ChineseCalendar.prototype)
            .add.call(this, date, offset, period);

        if (period === 'y') {
            // Resync month
            var resultYear = cdate.year();
            var resultMonthIndex = cdate.month();

            // Using the fact the month index of an intercalary month
            // equals its month number:
            var resultCanBeIntercalaryMonth =
                this.isIntercalaryMonth(resultYear, month);

            var correctedMonthIndex =
                (isIntercalary && resultCanBeIntercalaryMonth) ?
                this.toMonthIndex(resultYear, month, true) :
                this.toMonthIndex(resultYear, month, false);

            if (correctedMonthIndex !== resultMonthIndex) {
                cdate.month(correctedMonthIndex);
            }
        }

        return cdate;
    },
});

// Used by ChineseCalendar.prototype.fromString
var DATE_REGEXP = /^\s*(-?\d\d\d\d|\d\d)[-/](\d?\d)([iI]?)[-/](\d?\d)/m;
var MONTH_NUMBER_REGEXP = /^\d?\d[iI]?/m;
var MONTH_NAME_REGEXP = /^闰?十?[一二三四五六七八九]?月/m;
var MONTH_SHORT_NAME_REGEXP = /^闰?十?[一二三四五六七八九]?/m;

// Chinese calendar implementation
main.calendars.chinese = ChineseCalendar;

// Chinese calendar tables from year 1888 to 2111
//
// Source:
// https://github.com/isee15/Lunar-Solar-Calendar-Converter.git

// Table of intercalary months and days per month from year 1888 to 2111
//
// bit (12 - i):        days in the i^th month
//                      (= 0 if i^th lunar month has 29 days)
//                      (= 1 if i^th lunar month has 30 days)
//                      (first month in lunar year is i = 0)
// bits (13,14,15,16):  intercalary month
//                      (= 0 if lunar year has no intercalary month)
var LUNAR_MONTH_DAYS = [1887, 0x1694, 0x16aa, 0x4ad5,
    0xab6, 0xc4b7, 0x4ae, 0xa56, 0xb52a, 0x1d2a, 0xd54, 0x75aa, 0x156a,
    0x1096d, 0x95c, 0x14ae, 0xaa4d, 0x1a4c, 0x1b2a, 0x8d55, 0xad4,
    0x135a, 0x495d, 0x95c, 0xd49b, 0x149a, 0x1a4a, 0xbaa5, 0x16a8,
    0x1ad4, 0x52da, 0x12b6, 0xe937, 0x92e, 0x1496, 0xb64b, 0xd4a,
    0xda8, 0x95b5, 0x56c, 0x12ae, 0x492f, 0x92e, 0xcc96, 0x1a94,
    0x1d4a, 0xada9, 0xb5a, 0x56c, 0x726e, 0x125c, 0xf92d, 0x192a,
    0x1a94, 0xdb4a, 0x16aa, 0xad4, 0x955b, 0x4ba, 0x125a, 0x592b,
    0x152a, 0xf695, 0xd94, 0x16aa, 0xaab5, 0x9b4, 0x14b6, 0x6a57,
    0xa56, 0x1152a, 0x1d2a, 0xd54, 0xd5aa, 0x156a, 0x96c, 0x94ae,
    0x14ae, 0xa4c, 0x7d26, 0x1b2a, 0xeb55, 0xad4, 0x12da, 0xa95d,
    0x95a, 0x149a, 0x9a4d, 0x1a4a, 0x11aa5, 0x16a8, 0x16d4, 0xd2da,
    0x12b6, 0x936, 0x9497, 0x1496, 0x1564b, 0xd4a, 0xda8, 0xd5b4,
    0x156c, 0x12ae, 0xa92f, 0x92e, 0xc96, 0x6d4a, 0x1d4a, 0x10d65,
    0xb58, 0x156c, 0xb26d, 0x125c, 0x192c, 0x9a95, 0x1a94, 0x1b4a,
    0x4b55, 0xad4, 0xf55b, 0x4ba, 0x125a, 0xb92b, 0x152a, 0x1694,
    0x96aa, 0x15aa, 0x12ab5, 0x974, 0x14b6, 0xca57, 0xa56, 0x1526,
    0x8e95, 0xd54, 0x15aa, 0x49b5, 0x96c, 0xd4ae, 0x149c, 0x1a4c,
    0xbd26, 0x1aa6, 0xb54, 0x6d6a, 0x12da, 0x1695d, 0x95a, 0x149a,
    0xda4b, 0x1a4a, 0x1aa4, 0xbb54, 0x16b4, 0xada, 0x495b, 0x936,
    0xf497, 0x1496, 0x154a, 0xb6a5, 0xda4, 0x15b4, 0x6ab6, 0x126e,
    0x1092f, 0x92e, 0xc96, 0xcd4a, 0x1d4a, 0xd64, 0x956c, 0x155c,
    0x125c, 0x792e, 0x192c, 0xfa95, 0x1a94, 0x1b4a, 0xab55, 0xad4,
    0x14da, 0x8a5d, 0xa5a, 0x1152b, 0x152a, 0x1694, 0xd6aa, 0x15aa,
    0xab4, 0x94ba, 0x14b6, 0xa56, 0x7527, 0xd26, 0xee53, 0xd54, 0x15aa,
    0xa9b5, 0x96c, 0x14ae, 0x8a4e, 0x1a4c, 0x11d26, 0x1aa4, 0x1b54,
    0xcd6a, 0xada, 0x95c, 0x949d, 0x149a, 0x1a2a, 0x5b25, 0x1aa4,
    0xfb52, 0x16b4, 0xaba, 0xa95b, 0x936, 0x1496, 0x9a4b, 0x154a,
    0x136a5, 0xda4, 0x15ac];

// Table of Chinese New Years from year 1888 to 2111
// 
// bits (0 to 4):   solar day
// bits (5 to 8):   solar month
// bits (9 to 20):  solar year
var CHINESE_NEW_YEAR = [1887, 0xec04c, 0xec23f, 0xec435, 0xec649,
    0xec83e, 0xeca51, 0xecc46, 0xece3a, 0xed04d, 0xed242, 0xed436,
    0xed64a, 0xed83f, 0xeda53, 0xedc48, 0xede3d, 0xee050, 0xee244,
    0xee439, 0xee64d, 0xee842, 0xeea36, 0xeec4a, 0xeee3e, 0xef052,
    0xef246, 0xef43a, 0xef64e, 0xef843, 0xefa37, 0xefc4b, 0xefe41,
    0xf0054, 0xf0248, 0xf043c, 0xf0650, 0xf0845, 0xf0a38, 0xf0c4d,
    0xf0e42, 0xf1037, 0xf124a, 0xf143e, 0xf1651, 0xf1846, 0xf1a3a,
    0xf1c4e, 0xf1e44, 0xf2038, 0xf224b, 0xf243f, 0xf2653, 0xf2848,
    0xf2a3b, 0xf2c4f, 0xf2e45, 0xf3039, 0xf324d, 0xf3442, 0xf3636,
    0xf384a, 0xf3a3d, 0xf3c51, 0xf3e46, 0xf403b, 0xf424e, 0xf4443,
    0xf4638, 0xf484c, 0xf4a3f, 0xf4c52, 0xf4e48, 0xf503c, 0xf524f,
    0xf5445, 0xf5639, 0xf584d, 0xf5a42, 0xf5c35, 0xf5e49, 0xf603e,
    0xf6251, 0xf6446, 0xf663b, 0xf684f, 0xf6a43, 0xf6c37, 0xf6e4b,
    0xf703f, 0xf7252, 0xf7447, 0xf763c, 0xf7850, 0xf7a45, 0xf7c39,
    0xf7e4d, 0xf8042, 0xf8254, 0xf8449, 0xf863d, 0xf8851, 0xf8a46,
    0xf8c3b, 0xf8e4f, 0xf9044, 0xf9237, 0xf944a, 0xf963f, 0xf9853,
    0xf9a47, 0xf9c3c, 0xf9e50, 0xfa045, 0xfa238, 0xfa44c, 0xfa641,
    0xfa836, 0xfaa49, 0xfac3d, 0xfae52, 0xfb047, 0xfb23a, 0xfb44e,
    0xfb643, 0xfb837, 0xfba4a, 0xfbc3f, 0xfbe53, 0xfc048, 0xfc23c,
    0xfc450, 0xfc645, 0xfc839, 0xfca4c, 0xfcc41, 0xfce36, 0xfd04a,
    0xfd23d, 0xfd451, 0xfd646, 0xfd83a, 0xfda4d, 0xfdc43, 0xfde37,
    0xfe04b, 0xfe23f, 0xfe453, 0xfe648, 0xfe83c, 0xfea4f, 0xfec44,
    0xfee38, 0xff04c, 0xff241, 0xff436, 0xff64a, 0xff83e, 0xffa51,
    0xffc46, 0xffe3a, 0x10004e, 0x100242, 0x100437, 0x10064b, 0x100841,
    0x100a53, 0x100c48, 0x100e3c, 0x10104f, 0x101244, 0x101438,
    0x10164c, 0x101842, 0x101a35, 0x101c49, 0x101e3d, 0x102051,
    0x102245, 0x10243a, 0x10264e, 0x102843, 0x102a37, 0x102c4b,
    0x102e3f, 0x103053, 0x103247, 0x10343b, 0x10364f, 0x103845,
    0x103a38, 0x103c4c, 0x103e42, 0x104036, 0x104249, 0x10443d,
    0x104651, 0x104846, 0x104a3a, 0x104c4e, 0x104e43, 0x105038,
    0x10524a, 0x10543e, 0x105652, 0x105847, 0x105a3b, 0x105c4f,
    0x105e45, 0x106039, 0x10624c, 0x106441, 0x106635, 0x106849,
    0x106a3d, 0x106c51, 0x106e47, 0x10703c, 0x10724f, 0x107444,
    0x107638, 0x10784c, 0x107a3f, 0x107c53, 0x107e48];

function toLunar(yearOrDate, monthOrResult, day, result) {
    var solarDate;
    var lunarDate;

    if(typeof yearOrDate === 'object') {
        solarDate = yearOrDate;
        lunarDate = monthOrResult || {};

    } else {
        var isValidYear = (typeof yearOrDate === 'number') &&
            (yearOrDate >= 1888) && (yearOrDate <= 2111);
        if(!isValidYear)
            throw new Error("Solar year outside range 1888-2111");

        var isValidMonth = (typeof monthOrResult === 'number') &&
            (monthOrResult >= 1) && (monthOrResult <= 12);
        if(!isValidMonth)
            throw new Error("Solar month outside range 1 - 12");

        var isValidDay = (typeof day === 'number') && (day >= 1) && (day <= 31);
        if(!isValidDay)
            throw new Error("Solar day outside range 1 - 31");

        solarDate = {
            year: yearOrDate,
            month: monthOrResult,
            day: day,
        };
        lunarDate = result || {};
    }

    // Compute Chinese new year and lunar year
    var chineseNewYearPackedDate =
        CHINESE_NEW_YEAR[solarDate.year - CHINESE_NEW_YEAR[0]];

    var packedDate = (solarDate.year << 9) | (solarDate.month << 5)
        | solarDate.day;

    lunarDate.year = (packedDate >= chineseNewYearPackedDate) ?
        solarDate.year :
        solarDate.year - 1;

    chineseNewYearPackedDate =
        CHINESE_NEW_YEAR[lunarDate.year - CHINESE_NEW_YEAR[0]];

    var y = (chineseNewYearPackedDate >> 9) & 0xFFF;
    var m = (chineseNewYearPackedDate >> 5) & 0x0F;
    var d = chineseNewYearPackedDate & 0x1F;

    // Compute days from new year
    var daysFromNewYear;

    var chineseNewYearJSDate = new Date(y, m -1, d);
    var jsDate = new Date(solarDate.year, solarDate.month - 1, solarDate.day);

    daysFromNewYear = Math.round(
        (jsDate - chineseNewYearJSDate) / (24 * 3600 * 1000));

    // Compute lunar month and day
    var monthDaysTable = LUNAR_MONTH_DAYS[lunarDate.year - LUNAR_MONTH_DAYS[0]];

    var i;
    for(i = 0; i < 13; i++) {
        var daysInMonth = (monthDaysTable & (1 << (12 - i))) ? 30 : 29;

        if (daysFromNewYear < daysInMonth) {
            break;
        }

        daysFromNewYear -= daysInMonth;
    }

    var intercalaryMonth = monthDaysTable >> 13;
    if (!intercalaryMonth || i < intercalaryMonth) {
        lunarDate.isIntercalary = false;
        lunarDate.month = 1 + i;
    } else if (i === intercalaryMonth) {
        lunarDate.isIntercalary = true;
        lunarDate.month = i;
    } else {
        lunarDate.isIntercalary = false;
        lunarDate.month = i;
    }

    lunarDate.day = 1 + daysFromNewYear;

    return lunarDate;
}

function toSolar(yearOrDate, monthOrResult, day, isIntercalaryOrResult, result) {
    var solarDate;
    var lunarDate;

    if(typeof yearOrDate === 'object') {
        lunarDate = yearOrDate;
        solarDate = monthOrResult || {};

    } else {
        var isValidYear = (typeof yearOrDate === 'number') &&
            (yearOrDate >= 1888) && (yearOrDate <= 2111);
        if(!isValidYear)
            throw new Error("Lunar year outside range 1888-2111");

        var isValidMonth = (typeof monthOrResult === 'number') &&
            (monthOrResult >= 1) && (monthOrResult <= 12);
        if(!isValidMonth)
            throw new Error("Lunar month outside range 1 - 12");

        var isValidDay = (typeof day === 'number') && (day >= 1) && (day <= 30);
        if(!isValidDay)
            throw new Error("Lunar day outside range 1 - 30");

        var isIntercalary;
        if(typeof isIntercalaryOrResult === 'object') {
            isIntercalary = false;
            solarDate = isIntercalaryOrResult;
        } else {
            isIntercalary = !!isIntercalaryOrResult;
            solarDate = result || {};
        }

        lunarDate = {
            year: yearOrDate,
            month: monthOrResult,
            day: day,
            isIntercalary: isIntercalary,
        };
    }

    // Compute days from new year
    var daysFromNewYear;

    daysFromNewYear = lunarDate.day - 1;

    var monthDaysTable = LUNAR_MONTH_DAYS[lunarDate.year - LUNAR_MONTH_DAYS[0]];
    var intercalaryMonth = monthDaysTable >> 13;

    var monthsFromNewYear;
    if (!intercalaryMonth) {
        monthsFromNewYear = lunarDate.month - 1;
    } else if (lunarDate.month > intercalaryMonth) {
        monthsFromNewYear = lunarDate.month;
    } else if (lunarDate.isIntercalary) {
        monthsFromNewYear = lunarDate.month;
    } else {
        monthsFromNewYear = lunarDate.month - 1;
    }

    for(var i = 0; i < monthsFromNewYear; i++) {
        var daysInMonth = (monthDaysTable & (1 << (12 - i))) ? 30 : 29;
        daysFromNewYear += daysInMonth;
    }

    // Compute Chinese new year
    var packedDate = CHINESE_NEW_YEAR[lunarDate.year - CHINESE_NEW_YEAR[0]];

    var y = (packedDate >> 9) & 0xFFF;
    var m = (packedDate >> 5) & 0x0F;
    var d = packedDate & 0x1F;

    // Compute solar date
    var jsDate = new Date(y, m - 1, d + daysFromNewYear);

    solarDate.year = jsDate.getFullYear();
    solarDate.month = 1 + jsDate.getMonth();
    solarDate.day = jsDate.getDate();

    return solarDate;
}


},{"../main":552,"object-assign":443}],539:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Coptic calendar for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) February 2010.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


/** Implementation of the Coptic calendar.
    See <a href="http://en.wikipedia.org/wiki/Coptic_calendar">http://en.wikipedia.org/wiki/Coptic_calendar</a>.
    See also Calendrical Calculations: The Millennium Edition
    (<a href="http://emr.cs.iit.edu/home/reingold/calendar-book/index.shtml">http://emr.cs.iit.edu/home/reingold/calendar-book/index.shtml</a>).
    @class CopticCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function CopticCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

CopticCalendar.prototype = new main.baseCalendar;

assign(CopticCalendar.prototype, {
    /** The calendar name.
        @memberof CopticCalendar */
    name: 'Coptic',
    /** Julian date of start of Coptic epoch: 29 August 284 CE (Gregorian).
        @memberof CopticCalendar */
    jdEpoch: 1825029.5,
    /** Days per month in a common year.
        @memberof CopticCalendar */
    daysPerMonth: [30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 5],
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof CopticCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof CopticCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof CopticCalendar */
    firstMonth: 1,
    /** The minimum day number.
        @memberof CopticCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof CopticCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Coptic',
            epochs: ['BAM', 'AM'],
            monthNames: ['Thout', 'Paopi', 'Hathor', 'Koiak', 'Tobi', 'Meshir',
            'Paremhat', 'Paremoude', 'Pashons', 'Paoni', 'Epip', 'Mesori', 'Pi Kogi Enavot'],
            monthNamesShort: ['Tho', 'Pao', 'Hath', 'Koi', 'Tob', 'Mesh',
            'Pat', 'Pad', 'Pash', 'Pao', 'Epi', 'Meso', 'PiK'],
            dayNames: ['Tkyriaka', 'Pesnau', 'Pshoment', 'Peftoou', 'Ptiou', 'Psoou', 'Psabbaton'],
            dayNamesShort: ['Tky', 'Pes', 'Psh', 'Pef', 'Pti', 'Pso', 'Psa'],
            dayNamesMin: ['Tk', 'Pes', 'Psh', 'Pef', 'Pt', 'Pso', 'Psa'],
            digits: null,
            dateFormat: 'dd/mm/yyyy',
            firstDay: 0,
            isRTL: false
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof CopticCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        var year = date.year() + (date.year() < 0 ? 1 : 0); // No year zero
        return year % 4 === 3 || year % 4 === -1;
    },

    /** Retrieve the number of months in a year.
        @memberof CopticCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of months.
        @throws Error if an invalid year or a different calendar used. */
    monthsInYear: function(year) {
        this._validate(year, this.minMonth, this.minDay,
            main.local.invalidYear || main.regionalOptions[''].invalidYear);
        return 13;
    },

    /** Determine the week of the year for a date.
        @memberof CopticCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number) the month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        // Find Sunday of this week starting on Sunday
        var checkDate = this.newDate(year, month, day);
        checkDate.add(-checkDate.dayOfWeek(), 'd');
        return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
    },

    /** Retrieve the number of days in a month.
        @memberof CopticCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
        return this.daysPerMonth[date.month() - 1] +
            (date.month() === 13 && this.leapYear(date.year()) ? 1 : 0);
    },

    /** Determine whether this date is a week day.
        @memberof CopticCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param month {number} The month to examine.
        @param day {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        return (this.dayOfWeek(year, month, day) || 7) < 6;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof CopticCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number) the month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        year = date.year();
        if (year < 0) { year++; } // No year zero
        return date.day() + (date.month() - 1) * 30 +
            (year - 1) * 365 + Math.floor(year / 4) + this.jdEpoch - 1;
    },

    /** Create a new date from a Julian date.
        @memberof CopticCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        var c = Math.floor(jd) + 0.5 - this.jdEpoch;
        var year = Math.floor((c - Math.floor((c + 366) / 1461)) / 365) + 1;
        if (year <= 0) { year--; } // No year zero
        c = Math.floor(jd) + 0.5 - this.newDate(year, 1, 1).toJD();
        var month = Math.floor(c / 30) + 1;
        var day = c - (month - 1) * 30 + 1;
        return this.newDate(year, month, day);
    }
});

// Coptic calendar implementation
main.calendars.coptic = CopticCalendar;


},{"../main":552,"object-assign":443}],540:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Discworld calendar for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) January 2016.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


/** Implementation of the Discworld calendar - Unseen University version.
    See also <a href="http://wiki.lspace.org/mediawiki/Discworld_calendar">http://wiki.lspace.org/mediawiki/Discworld_calendar</a>
    and <a href="http://discworld.wikia.com/wiki/Discworld_calendar">http://discworld.wikia.com/wiki/Discworld_calendar</a>.
    @class DiscworldCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function DiscworldCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

DiscworldCalendar.prototype = new main.baseCalendar;

assign(DiscworldCalendar.prototype, {
    /** The calendar name.
        @memberof DiscworldCalendar */
    name: 'Discworld',
    /** Julian date of start of Discworld epoch: 1 January 0001 CE.
        @memberof DiscworldCalendar */
    jdEpoch: 1721425.5,
    /** Days per month in a common year.
        @memberof DiscworldCalendar */
    daysPerMonth: [16, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32],
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof DiscworldCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof DiscworldCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof DiscworldCalendar */
    firstMonth: 1,
    /** The minimum day number.
        @memberof DiscworldCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof DiscworldCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Discworld',
            epochs: ['BUC', 'UC'],
            monthNames: ['Ick', 'Offle', 'February', 'March', 'April', 'May', 'June',
            'Grune', 'August', 'Spune', 'Sektober', 'Ember', 'December'],
            monthNamesShort: ['Ick', 'Off', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Gru', 'Aug', 'Spu', 'Sek', 'Emb', 'Dec'],
            dayNames: ['Sunday', 'Octeday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
            dayNamesShort: ['Sun', 'Oct', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
            dayNamesMin: ['Su', 'Oc', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
            digits: null,
            dateFormat: 'yyyy/mm/dd',
            firstDay: 2,
            isRTL: false
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof DiscworldCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        return false;
    },

    /** Retrieve the number of months in a year.
        @memberof DiscworldCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of months.
        @throws Error if an invalid year or a different calendar used. */
    monthsInYear: function(year) {
        this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        return 13;
    },

    /** Retrieve the number of days in a year.
        @memberof DiscworldCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of days.
        @throws Error if an invalid year or a different calendar used. */
    daysInYear: function(year) {
        this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        return 400;
    },

    /** Determine the week of the year for a date.
        @memberof DiscworldCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        // Find Sunday of this week starting on Sunday
        var checkDate = this.newDate(year, month, day);
        checkDate.add(-checkDate.dayOfWeek(), 'd');
        return Math.floor((checkDate.dayOfYear() - 1) / 8) + 1;
    },

    /** Retrieve the number of days in a month.
        @memberof DiscworldCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
        return this.daysPerMonth[date.month() - 1];
    },

    /** Retrieve the number of days in a week.
        @memberof DiscworldCalendar
        @return {number} The number of days. */
    daysInWeek: function() {
        return 8;
    },

    /** Retrieve the day of the week for a date.
        @memberof DiscworldCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The day of the week: 0 to number of days - 1.
        @throws Error if an invalid date or a different calendar used. */
    dayOfWeek: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        return (date.day() + 1) % 8;
    },

    /** Determine whether this date is a week day.
        @memberof DiscworldCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        var dow = this.dayOfWeek(year, month, day);
        return (dow >= 2 && dow <= 6);
    },

    /** Retrieve additional information about a date.
        @memberof DiscworldCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {object} Additional information - contents depends on calendar.
        @throws Error if an invalid date or a different calendar used. */
    extraInfo: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        return {century: centuries[Math.floor((date.year() - 1) / 100) + 1] || ''};
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof DiscworldCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        year = date.year() + (date.year() < 0 ? 1 : 0);
        month = date.month();
        day = date.day();
        return day + (month > 1 ? 16 : 0) + (month > 2 ? (month - 2) * 32 : 0) +
            (year - 1) * 400 + this.jdEpoch - 1;
    },

    /** Create a new date from a Julian date.
        @memberof DiscworldCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        jd = Math.floor(jd + 0.5) - Math.floor(this.jdEpoch) - 1;
        var year = Math.floor(jd / 400) + 1;
        jd -= (year - 1) * 400;
        jd += (jd > 15 ? 16 : 0);
        var month = Math.floor(jd / 32) + 1;
        var day = jd - (month - 1) * 32 + 1;
        return this.newDate(year <= 0 ? year - 1 : year, month, day);
    }
});

// Names of the centuries
var centuries = {
    20: 'Fruitbat',
    21: 'Anchovy'
};

// Discworld calendar implementation
main.calendars.discworld = DiscworldCalendar;


},{"../main":552,"object-assign":443}],541:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Ethiopian calendar for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) February 2010.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


/** Implementation of the Ethiopian calendar.
    See <a href="http://en.wikipedia.org/wiki/Ethiopian_calendar">http://en.wikipedia.org/wiki/Ethiopian_calendar</a>.
    See also Calendrical Calculations: The Millennium Edition
    (<a href="http://emr.cs.iit.edu/home/reingold/calendar-book/index.shtml">http://emr.cs.iit.edu/home/reingold/calendar-book/index.shtml</a>).
    @class EthiopianCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function EthiopianCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

EthiopianCalendar.prototype = new main.baseCalendar;

assign(EthiopianCalendar.prototype, {
    /** The calendar name.
        @memberof EthiopianCalendar */
    name: 'Ethiopian',
    /** Julian date of start of Ethiopian epoch: 27 August 8 CE (Gregorian).
        @memberof EthiopianCalendar */
    jdEpoch: 1724220.5,
    /** Days per month in a common year.
        @memberof EthiopianCalendar */
    daysPerMonth: [30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 5],
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof EthiopianCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof EthiopianCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof EthiopianCalendar */
    firstMonth: 1,
    /** The minimum day number.
        @memberof EthiopianCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof EthiopianCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Ethiopian',
            epochs: ['BEE', 'EE'],
            monthNames: ['Meskerem', 'Tikemet', 'Hidar', 'Tahesas', 'Tir', 'Yekatit',
            'Megabit', 'Miazia', 'Genbot', 'Sene', 'Hamle', 'Nehase', 'Pagume'],
            monthNamesShort: ['Mes', 'Tik', 'Hid', 'Tah', 'Tir', 'Yek',
            'Meg', 'Mia', 'Gen', 'Sen', 'Ham', 'Neh', 'Pag'],
            dayNames: ['Ehud', 'Segno', 'Maksegno', 'Irob', 'Hamus', 'Arb', 'Kidame'],
            dayNamesShort: ['Ehu', 'Seg', 'Mak', 'Iro', 'Ham', 'Arb', 'Kid'],
            dayNamesMin: ['Eh', 'Se', 'Ma', 'Ir', 'Ha', 'Ar', 'Ki'],
            digits: null,
            dateFormat: 'dd/mm/yyyy',
            firstDay: 0,
            isRTL: false
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof EthiopianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        var year = date.year() + (date.year() < 0 ? 1 : 0); // No year zero
        return year % 4 === 3 || year % 4 === -1;
    },

    /** Retrieve the number of months in a year.
        @memberof EthiopianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of months.
        @throws Error if an invalid year or a different calendar used. */
    monthsInYear: function(year) {
        this._validate(year, this.minMonth, this.minDay,
            main.local.invalidYear || main.regionalOptions[''].invalidYear);
        return 13;
    },

    /** Determine the week of the year for a date.
        @memberof EthiopianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        // Find Sunday of this week starting on Sunday
        var checkDate = this.newDate(year, month, day);
        checkDate.add(-checkDate.dayOfWeek(), 'd');
        return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
    },

    /** Retrieve the number of days in a month.
        @memberof EthiopianCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
        return this.daysPerMonth[date.month() - 1] +
            (date.month() === 13 && this.leapYear(date.year()) ? 1 : 0);
    },

    /** Determine whether this date is a week day.
        @memberof EthiopianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        return (this.dayOfWeek(year, month, day) || 7) < 6;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof EthiopianCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        year = date.year();
        if (year < 0) { year++; } // No year zero
        return date.day() + (date.month() - 1) * 30 +
            (year - 1) * 365 + Math.floor(year / 4) + this.jdEpoch - 1;
    },

    /** Create a new date from a Julian date.
        @memberof EthiopianCalendar
        @param jd {number} the Julian date to convert.
        @return {CDate} the equivalent date. */
    fromJD: function(jd) {
        var c = Math.floor(jd) + 0.5 - this.jdEpoch;
        var year = Math.floor((c - Math.floor((c + 366) / 1461)) / 365) + 1;
        if (year <= 0) { year--; } // No year zero
        c = Math.floor(jd) + 0.5 - this.newDate(year, 1, 1).toJD();
        var month = Math.floor(c / 30) + 1;
        var day = c - (month - 1) * 30 + 1;
        return this.newDate(year, month, day);
    }
});

// Ethiopian calendar implementation
main.calendars.ethiopian = EthiopianCalendar;


},{"../main":552,"object-assign":443}],542:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Hebrew calendar for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) August 2009.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


/** Implementation of the Hebrew civil calendar.
    Based on code from <a href="http://www.fourmilab.ch/documents/calendar/">http://www.fourmilab.ch/documents/calendar/</a>.
    See also <a href="http://en.wikipedia.org/wiki/Hebrew_calendar">http://en.wikipedia.org/wiki/Hebrew_calendar</a>.
    @class HebrewCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function HebrewCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

HebrewCalendar.prototype = new main.baseCalendar;

assign(HebrewCalendar.prototype, {
    /** The calendar name.
        @memberof HebrewCalendar */
    name: 'Hebrew',
    /** Julian date of start of Hebrew epoch: 7 October 3761 BCE.
        @memberof HebrewCalendar */
    jdEpoch: 347995.5,
    /** Days per month in a common year.
        @memberof HebrewCalendar */
    daysPerMonth: [30, 29, 30, 29, 30, 29, 30, 29, 30, 29, 30, 29, 29],
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof HebrewCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof HebrewCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof HebrewCalendar */
    firstMonth: 7,
    /** The minimum day number.
        @memberof HebrewCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof HebrewCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Hebrew',
            epochs: ['BAM', 'AM'],
            monthNames: ['Nisan', 'Iyar', 'Sivan', 'Tammuz', 'Av', 'Elul',
            'Tishrei', 'Cheshvan', 'Kislev', 'Tevet', 'Shevat', 'Adar', 'Adar II'],
            monthNamesShort: ['Nis', 'Iya', 'Siv', 'Tam', 'Av', 'Elu', 'Tis', 'Che', 'Kis', 'Tev', 'She', 'Ada', 'Ad2'],
            dayNames: ['Yom Rishon', 'Yom Sheni', 'Yom Shlishi', 'Yom Revi\'i', 'Yom Chamishi', 'Yom Shishi', 'Yom Shabbat'],
            dayNamesShort: ['Ris', 'She', 'Shl', 'Rev', 'Cha', 'Shi', 'Sha'],
            dayNamesMin: ['Ri','She','Shl','Re','Ch','Shi','Sha'],
            digits: null,
            dateFormat: 'dd/mm/yyyy',
            firstDay: 0,
            isRTL: false
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof HebrewCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        return this._leapYear(date.year());
    },

    /** Determine whether this date is in a leap year.
        @memberof HebrewCalendar
        @private
        @param year {number} The year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    _leapYear: function(year) {
        year = (year < 0 ? year + 1 : year);
        return mod(year * 7 + 1, 19) < 7;
    },

    /** Retrieve the number of months in a year.
        @memberof HebrewCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of months.
        @throws Error if an invalid year or a different calendar used. */
    monthsInYear: function(year) {
        this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        return this._leapYear(year.year ? year.year() : year) ? 13 : 12;
    },

    /** Determine the week of the year for a date.
        @memberof HebrewCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        // Find Sunday of this week starting on Sunday
        var checkDate = this.newDate(year, month, day);
        checkDate.add(-checkDate.dayOfWeek(), 'd');
        return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
    },

    /** Retrieve the number of days in a year.
        @memberof HebrewCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of days.
        @throws Error if an invalid year or a different calendar used. */
    daysInYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        year = date.year();
        return this.toJD((year === -1 ? +1 : year + 1), 7, 1) - this.toJD(year, 7, 1);
    },

    /** Retrieve the number of days in a month.
        @memberof HebrewCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        if (year.year) {
            month = year.month();
            year = year.year();
        }
        this._validate(year, month, this.minDay, main.local.invalidMonth);
        return (month === 12 && this.leapYear(year) ? 30 : // Adar I
                (month === 8 && mod(this.daysInYear(year), 10) === 5 ? 30 : // Cheshvan in shlemah year
                (month === 9 && mod(this.daysInYear(year), 10) === 3 ? 29 : // Kislev in chaserah year
                this.daysPerMonth[month - 1])));
    },

    /** Determine whether this date is a week day.
        @memberof HebrewCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        return this.dayOfWeek(year, month, day) !== 6;
    },

    /** Retrieve additional information about a date - year type.
        @memberof HebrewCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {object} Additional information - contents depends on calendar.
        @throws Error if an invalid date or a different calendar used. */
    extraInfo: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        return {yearType: (this.leapYear(date) ? 'embolismic' : 'common') + ' ' +
            ['deficient', 'regular', 'complete'][this.daysInYear(date) % 10 - 3]};
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof HebrewCalendar
        @param year {CDate)|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        year = date.year();
        month = date.month();
        day = date.day();
        var adjYear = (year <= 0 ? year + 1 : year);
        var jd = this.jdEpoch + this._delay1(adjYear) +
            this._delay2(adjYear) + day + 1;
        if (month < 7) {
            for (var m = 7; m <= this.monthsInYear(year); m++) {
                jd += this.daysInMonth(year, m);
            }
            for (var m = 1; m < month; m++) {
                jd += this.daysInMonth(year, m);
            }
        }
        else {
            for (var m = 7; m < month; m++) {
                jd += this.daysInMonth(year, m);
            }
        }
        return jd;
    },

    /** Test for delay of start of new year and to avoid
        Sunday, Wednesday, or Friday as start of the new year.
        @memberof HebrewCalendar
        @private
        @param year {number} The year to examine.
        @return {number} The days to offset by. */
    _delay1: function(year) {
        var months = Math.floor((235 * year - 234) / 19);
        var parts = 12084 + 13753 * months;
        var day = months * 29 + Math.floor(parts / 25920);
        if (mod(3 * (day + 1), 7) < 3) {
            day++;
        }
        return day;
    },

    /** Check for delay in start of new year due to length of adjacent years.
        @memberof HebrewCalendar
        @private
        @param year {number} The year to examine.
        @return {number} The days to offset by. */
    _delay2: function(year) {
        var last = this._delay1(year - 1);
        var present = this._delay1(year);
        var next = this._delay1(year + 1);
        return ((next - present) === 356 ? 2 : ((present - last) === 382 ? 1 : 0));
    },

    /** Create a new date from a Julian date.
        @memberof HebrewCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        jd = Math.floor(jd) + 0.5;
        var year = Math.floor(((jd - this.jdEpoch) * 98496.0) / 35975351.0) - 1;
        while (jd >= this.toJD((year === -1 ? +1 : year + 1), 7, 1)) {
            year++;
        }
        var month = (jd < this.toJD(year, 1, 1)) ? 7 : 1;
        while (jd > this.toJD(year, month, this.daysInMonth(year, month))) {
            month++;
        }
        var day = jd - this.toJD(year, month, 1) + 1;
        return this.newDate(year, month, day);
    }
});

// Modulus function which works for non-integers.
function mod(a, b) {
    return a - (b * Math.floor(a / b));
}

// Hebrew calendar implementation
main.calendars.hebrew = HebrewCalendar;


},{"../main":552,"object-assign":443}],543:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Islamic calendar for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) August 2009.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


/** Implementation of the Islamic or '16 civil' calendar.
    Based on code from <a href="http://www.iranchamber.com/calendar/converter/iranian_calendar_converter.php">http://www.iranchamber.com/calendar/converter/iranian_calendar_converter.php</a>.
    See also <a href="http://en.wikipedia.org/wiki/Islamic_calendar">http://en.wikipedia.org/wiki/Islamic_calendar</a>.
    @class IslamicCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function IslamicCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

IslamicCalendar.prototype = new main.baseCalendar;

assign(IslamicCalendar.prototype, {
    /** The calendar name.
        @memberof IslamicCalendar */
    name: 'Islamic',
    /** Julian date of start of Islamic epoch: 16 July 622 CE.
        @memberof IslamicCalendar */
    jdEpoch: 1948439.5,
    /** Days per month in a common year.
        @memberof IslamicCalendar */
    daysPerMonth: [30, 29, 30, 29, 30, 29, 30, 29, 30, 29, 30, 29],
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof IslamicCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof IslamicCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof IslamicCalendar */
    firstMonth: 1,
    /** The minimum day number.
        @memberof IslamicCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof IslamicCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Islamic',
            epochs: ['BH', 'AH'],
            monthNames: ['Muharram', 'Safar', 'Rabi\' al-awwal', 'Rabi\' al-thani', 'Jumada al-awwal', 'Jumada al-thani',
            'Rajab', 'Sha\'aban', 'Ramadan', 'Shawwal', 'Dhu al-Qi\'dah', 'Dhu al-Hijjah'],
            monthNamesShort: ['Muh', 'Saf', 'Rab1', 'Rab2', 'Jum1', 'Jum2', 'Raj', 'Sha\'', 'Ram', 'Shaw', 'DhuQ', 'DhuH'],
            dayNames: ['Yawm al-ahad', 'Yawm al-ithnayn', 'Yawm ath-thulaathaa\'',
            'Yawm al-arbi\'aa\'', 'Yawm al-khamīs', 'Yawm al-jum\'a', 'Yawm as-sabt'],
            dayNamesShort: ['Aha', 'Ith', 'Thu', 'Arb', 'Kha', 'Jum', 'Sab'],
            dayNamesMin: ['Ah','It','Th','Ar','Kh','Ju','Sa'],
            digits: null,
            dateFormat: 'yyyy/mm/dd',
            firstDay: 6,
            isRTL: false
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof IslamicCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        return (date.year() * 11 + 14) % 30 < 11;
    },

    /** Determine the week of the year for a date.
        @memberof IslamicCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        // Find Sunday of this week starting on Sunday
        var checkDate = this.newDate(year, month, day);
        checkDate.add(-checkDate.dayOfWeek(), 'd');
        return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
    },

    /** Retrieve the number of days in a year.
        @memberof IslamicCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of days.
        @throws Error if an invalid year or a different calendar used. */
    daysInYear: function(year) {
        return (this.leapYear(year) ? 355 : 354);
    },

    /** Retrieve the number of days in a month.
        @memberof IslamicCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
        return this.daysPerMonth[date.month() - 1] +
            (date.month() === 12 && this.leapYear(date.year()) ? 1 : 0);
    },

    /** Determine whether this date is a week day.
        @memberof IslamicCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        return this.dayOfWeek(year, month, day) !== 5;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof IslamicCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        year = date.year();
        month = date.month();
        day = date.day();
        year = (year <= 0 ? year + 1 : year);
        return day + Math.ceil(29.5 * (month - 1)) + (year - 1) * 354 +
            Math.floor((3 + (11 * year)) / 30) + this.jdEpoch - 1;
    },

    /** Create a new date from a Julian date.
        @memberof IslamicCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        jd = Math.floor(jd) + 0.5;
        var year = Math.floor((30 * (jd - this.jdEpoch) + 10646) / 10631);
        year = (year <= 0 ? year - 1 : year);
        var month = Math.min(12, Math.ceil((jd - 29 - this.toJD(year, 1, 1)) / 29.5) + 1);
        var day = jd - this.toJD(year, month, 1) + 1;
        return this.newDate(year, month, day);
    }
});

// Islamic (16 civil) calendar implementation
main.calendars.islamic = IslamicCalendar;


},{"../main":552,"object-assign":443}],544:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Julian calendar for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) August 2009.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


/** Implementation of the Julian calendar.
    Based on code from <a href="http://www.fourmilab.ch/documents/calendar/">http://www.fourmilab.ch/documents/calendar/</a>.
    See also <a href="http://en.wikipedia.org/wiki/Julian_calendar">http://en.wikipedia.org/wiki/Julian_calendar</a>.
    @class JulianCalendar
    @augments BaseCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function JulianCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

JulianCalendar.prototype = new main.baseCalendar;

assign(JulianCalendar.prototype, {
    /** The calendar name.
        @memberof JulianCalendar */
    name: 'Julian',
    /** Julian date of start of Julian epoch: 1 January 0001 AD = 30 December 0001 BCE.
        @memberof JulianCalendar */
    jdEpoch: 1721423.5,
    /** Days per month in a common year.
        @memberof JulianCalendar */
    daysPerMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof JulianCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof JulianCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof JulianCalendar */
    firstMonth: 1,
    /** The minimum day number.
        @memberof JulianCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof JulianCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Julian',
            epochs: ['BC', 'AD'],
            monthNames: ['January', 'February', 'March', 'April', 'May', 'June',
            'July', 'August', 'September', 'October', 'November', 'December'],
            monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
            dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
            dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
            digits: null,
            dateFormat: 'mm/dd/yyyy',
            firstDay: 0,
            isRTL: false
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof JulianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        var year = (date.year() < 0 ? date.year() + 1 : date.year()); // No year zero
        return (year % 4) === 0;
    },

    /** Determine the week of the year for a date - ISO 8601.
        @memberof JulianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        // Find Thursday of this week starting on Monday
        var checkDate = this.newDate(year, month, day);
        checkDate.add(4 - (checkDate.dayOfWeek() || 7), 'd');
        return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
    },

    /** Retrieve the number of days in a month.
        @memberof JulianCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
        return this.daysPerMonth[date.month() - 1] +
            (date.month() === 2 && this.leapYear(date.year()) ? 1 : 0);
    },

    /** Determine whether this date is a week day.
        @memberof JulianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} True if a week day, false if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        return (this.dayOfWeek(year, month, day) || 7) < 6;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof JulianCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        year = date.year();
        month = date.month();
        day = date.day();
        if (year < 0) { year++; } // No year zero
        // Jean Meeus algorithm, "Astronomical Algorithms", 1991
        if (month <= 2) {
            year--;
            month += 12;
        }
        return Math.floor(365.25 * (year + 4716)) +
            Math.floor(30.6001 * (month + 1)) + day - 1524.5;
    },

    /** Create a new date from a Julian date.
        @memberof JulianCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        // Jean Meeus algorithm, "Astronomical Algorithms", 1991
        var a = Math.floor(jd + 0.5);
        var b = a + 1524;
        var c = Math.floor((b - 122.1) / 365.25);
        var d = Math.floor(365.25 * c);
        var e = Math.floor((b - d) / 30.6001);
        var month = e - Math.floor(e < 14 ? 1 : 13);
        var year = c - Math.floor(month > 2 ? 4716 : 4715);
        var day = b - d - Math.floor(30.6001 * e);
        if (year <= 0) { year--; } // No year zero
        return this.newDate(year, month, day);
    }
});

// Julian calendar implementation
main.calendars.julian = JulianCalendar;


},{"../main":552,"object-assign":443}],545:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Mayan calendar for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) August 2009.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


/** Implementation of the Mayan Long Count calendar.
    See also <a href="http://en.wikipedia.org/wiki/Mayan_calendar">http://en.wikipedia.org/wiki/Mayan_calendar</a>.
    @class MayanCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function MayanCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

MayanCalendar.prototype = new main.baseCalendar;

assign(MayanCalendar.prototype, {
    /** The calendar name.
        @memberof MayanCalendar */
    name: 'Mayan',
    /** Julian date of start of Mayan epoch: 11 August 3114 BCE.
        @memberof MayanCalendar */
    jdEpoch: 584282.5,
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof MayanCalendar */
    hasYearZero: true,
    /** The minimum month number.
        @memberof MayanCalendar */
    minMonth: 0,
    /** The first month in the year.
        @memberof MayanCalendar */
    firstMonth: 0,
    /** The minimum day number.
        @memberof MayanCalendar */
    minDay: 0,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof MayanCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left.
        @property haabMonths {string[]} The names of the Haab months.
        @property tzolkinMonths {string[]} The names of the Tzolkin months. */
    regionalOptions: { // Localisations
        '': {
            name: 'Mayan',
            epochs: ['', ''],
            monthNames: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            '10', '11', '12', '13', '14', '15', '16', '17'],
            monthNamesShort: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            '10', '11', '12', '13', '14', '15', '16', '17'],
            dayNames: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            '10', '11', '12', '13', '14', '15', '16', '17', '18', '19'],
            dayNamesShort: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            '10', '11', '12', '13', '14', '15', '16', '17', '18', '19'],
            dayNamesMin: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            '10', '11', '12', '13', '14', '15', '16', '17', '18', '19'],
            digits: null,
            dateFormat: 'YYYY.m.d',
            firstDay: 0,
            isRTL: false,
            haabMonths: ['Pop', 'Uo', 'Zip', 'Zotz', 'Tzec', 'Xul', 'Yaxkin', 'Mol', 'Chen', 'Yax',
            'Zac', 'Ceh', 'Mac', 'Kankin', 'Muan', 'Pax', 'Kayab', 'Cumku', 'Uayeb'],
            tzolkinMonths: ['Imix', 'Ik', 'Akbal', 'Kan', 'Chicchan', 'Cimi', 'Manik', 'Lamat', 'Muluc', 'Oc',
            'Chuen', 'Eb', 'Ben', 'Ix', 'Men', 'Cib', 'Caban', 'Etznab', 'Cauac', 'Ahau']
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof MayanCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        return false;
    },

    /** Format the year, if not a simple sequential number.
        @memberof MayanCalendar
        @param year {CDate|number} The date to format or the year to format.
        @return {string} The formatted year.
        @throws Error if an invalid year or a different calendar used. */
    formatYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        year = date.year();
        var baktun = Math.floor(year / 400);
        year = year % 400;
        year += (year < 0 ? 400 : 0);
        var katun = Math.floor(year / 20);
        return baktun + '.' + katun + '.' + (year % 20);
    },

    /** Convert from the formatted year back to a single number.
        @memberof MayanCalendar
        @param years {string} The year as n.n.n.
        @return {number} The sequential year.
        @throws Error if an invalid value is supplied. */
    forYear: function(years) {
        years = years.split('.');
        if (years.length < 3) {
            throw 'Invalid Mayan year';
        }
        var year = 0;
        for (var i = 0; i < years.length; i++) {
            var y = parseInt(years[i], 10);
            if (Math.abs(y) > 19 || (i > 0 && y < 0)) {
                throw 'Invalid Mayan year';
            }
            year = year * 20 + y;
        }
        return year;
    },

    /** Retrieve the number of months in a year.
        @memberof MayanCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of months.
        @throws Error if an invalid year or a different calendar used. */
    monthsInYear: function(year) {
        this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        return 18;
    },

    /** Determine the week of the year for a date.
        @memberof MayanCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        this._validate(year, month, day, main.local.invalidDate);
        return 0;
    },

    /** Retrieve the number of days in a year.
        @memberof MayanCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of days.
        @throws Error if an invalid year or a different calendar used. */
    daysInYear: function(year) {
        this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        return 360;
    },

    /** Retrieve the number of days in a month.
        @memberof MayanCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        this._validate(year, month, this.minDay, main.local.invalidMonth);
        return 20;
    },

    /** Retrieve the number of days in a week.
        @memberof MayanCalendar
        @return {number} The number of days. */
    daysInWeek: function() {
        return 5; // Just for formatting
    },

    /** Retrieve the day of the week for a date.
        @memberof MayanCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The day of the week: 0 to number of days - 1.
        @throws Error if an invalid date or a different calendar used. */
    dayOfWeek: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        return date.day();
    },

    /** Determine whether this date is a week day.
        @memberof MayanCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        this._validate(year, month, day, main.local.invalidDate);
        return true;
    },

    /** Retrieve additional information about a date - Haab and Tzolkin equivalents.
        @memberof MayanCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {object} Additional information - contents depends on calendar.
        @throws Error if an invalid date or a different calendar used. */
    extraInfo: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        var jd = date.toJD();
        var haab = this._toHaab(jd);
        var tzolkin = this._toTzolkin(jd);
        return {haabMonthName: this.local.haabMonths[haab[0] - 1],
            haabMonth: haab[0], haabDay: haab[1],
            tzolkinDayName: this.local.tzolkinMonths[tzolkin[0] - 1],
            tzolkinDay: tzolkin[0], tzolkinTrecena: tzolkin[1]};
    },

    /** Retrieve Haab date from a Julian date.
        @memberof MayanCalendar
        @private
        @param jd  {number} The Julian date.
        @return {number[]} Corresponding Haab month and day. */
    _toHaab: function(jd) {
        jd -= this.jdEpoch;
        var day = mod(jd + 8 + ((18 - 1) * 20), 365);
        return [Math.floor(day / 20) + 1, mod(day, 20)];
    },

    /** Retrieve Tzolkin date from a Julian date.
        @memberof MayanCalendar
        @private
        @param jd {number} The Julian date.
        @return {number[]} Corresponding Tzolkin day and trecena. */
    _toTzolkin: function(jd) {
        jd -= this.jdEpoch;
        return [amod(jd + 20, 20), amod(jd + 4, 13)];
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof MayanCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        return date.day() + (date.month() * 20) + (date.year() * 360) + this.jdEpoch;
    },

    /** Create a new date from a Julian date.
        @memberof MayanCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        jd = Math.floor(jd) + 0.5 - this.jdEpoch;
        var year = Math.floor(jd / 360);
        jd = jd % 360;
        jd += (jd < 0 ? 360 : 0);
        var month = Math.floor(jd / 20);
        var day = jd % 20;
        return this.newDate(year, month, day);
    }
});

// Modulus function which works for non-integers.
function mod(a, b) {
    return a - (b * Math.floor(a / b));
}

// Modulus function which returns numerator if modulus is zero.
function amod(a, b) {
    return mod(a - 1, b) + 1;
}

// Mayan calendar implementation
main.calendars.mayan = MayanCalendar;


},{"../main":552,"object-assign":443}],546:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

/* http://keith-wood.name/calendars.html
   Nanakshahi calendar for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) January 2016.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


/** Implementation of the Nanakshahi calendar.
    See also <a href="https://en.wikipedia.org/wiki/Nanakshahi_calendar">https://en.wikipedia.org/wiki/Nanakshahi_calendar</a>.
    @class NanakshahiCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function NanakshahiCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

NanakshahiCalendar.prototype = new main.baseCalendar;

var gregorian = main.instance('gregorian');

assign(NanakshahiCalendar.prototype, {
    /** The calendar name.
        @memberof NanakshahiCalendar */
    name: 'Nanakshahi',
    /** Julian date of start of Nanakshahi epoch: 14 March 1469 CE.
        @memberof NanakshahiCalendar */
    jdEpoch: 2257673.5,
    /** Days per month in a common year.
        @memberof NanakshahiCalendar */
    daysPerMonth: [31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30, 30],
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof NanakshahiCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof NanakshahiCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof NanakshahiCalendar */
    firstMonth: 1,
    /** The minimum day number.
        @memberof NanakshahiCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof NanakshahiCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Nanakshahi',
            epochs: ['BN', 'AN'],
            monthNames: ['Chet', 'Vaisakh', 'Jeth', 'Harh', 'Sawan', 'Bhadon',
            'Assu', 'Katak', 'Maghar', 'Poh', 'Magh', 'Phagun'],
            monthNamesShort: ['Che', 'Vai', 'Jet', 'Har', 'Saw', 'Bha', 'Ass', 'Kat', 'Mgr', 'Poh', 'Mgh', 'Pha'],
            dayNames: ['Somvaar', 'Mangalvar', 'Budhvaar', 'Veervaar', 'Shukarvaar', 'Sanicharvaar', 'Etvaar'],
            dayNamesShort: ['Som', 'Mangal', 'Budh', 'Veer', 'Shukar', 'Sanichar', 'Et'],
            dayNamesMin: ['So', 'Ma', 'Bu', 'Ve', 'Sh', 'Sa', 'Et'],
            digits: null,
            dateFormat: 'dd-mm-yyyy',
            firstDay: 0,
            isRTL: false
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof NanakshahiCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay,
            main.local.invalidYear || main.regionalOptions[''].invalidYear);
        return gregorian.leapYear(date.year() + (date.year() < 1 ? 1 : 0) + 1469);
    },

    /** Determine the week of the year for a date.
        @memberof NanakshahiCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        // Find Monday of this week starting on Monday
        var checkDate = this.newDate(year, month, day);
        checkDate.add(1 - (checkDate.dayOfWeek() || 7), 'd');
        return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
    },

    /** Retrieve the number of days in a month.
        @memberof NanakshahiCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
        return this.daysPerMonth[date.month() - 1] +
            (date.month() === 12 && this.leapYear(date.year()) ? 1 : 0);
    },

    /** Determine whether this date is a week day.
        @memberof NanakshahiCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        return (this.dayOfWeek(year, month, day) || 7) < 6;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof NanakshahiCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidMonth);
        var year = date.year();
        if (year < 0) { year++; } // No year zero
        var doy = date.day();
        for (var m = 1; m < date.month(); m++) {
            doy += this.daysPerMonth[m - 1];
        }
        return doy + gregorian.toJD(year + 1468, 3, 13);
    },

    /** Create a new date from a Julian date.
        @memberof NanakshahiCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        jd = Math.floor(jd + 0.5);
        var year = Math.floor((jd - (this.jdEpoch - 1)) / 366);
        while (jd >= this.toJD(year + 1, 1, 1)) {
            year++;
        }
        var day = jd - Math.floor(this.toJD(year, 1, 1) + 0.5) + 1;
        var month = 1;
        while (day > this.daysInMonth(year, month)) {
            day -= this.daysInMonth(year, month);
            month++;
        }
        return this.newDate(year, month, day);
    }
});

// Nanakshahi calendar implementation
main.calendars.nanakshahi = NanakshahiCalendar;


},{"../main":552,"object-assign":443}],547:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Nepali calendar for jQuery v2.0.2.
   Written by Artur Neumann (ict.projects{at}nepal.inf.org) April 2013.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


/** Implementation of the Nepali civil calendar.
    Based on the ideas from 
    <a href="http://codeissue.com/articles/a04e050dea7468f/algorithm-to-convert-english-date-to-nepali-date-using-c-net">http://codeissue.com/articles/a04e050dea7468f/algorithm-to-convert-english-date-to-nepali-date-using-c-net</a>
    and <a href="http://birenj2ee.blogspot.com/2011/04/nepali-calendar-in-java.html">http://birenj2ee.blogspot.com/2011/04/nepali-calendar-in-java.html</a>
    See also <a href="http://en.wikipedia.org/wiki/Nepali_calendar">http://en.wikipedia.org/wiki/Nepali_calendar</a>
    and <a href="https://en.wikipedia.org/wiki/Bikram_Samwat">https://en.wikipedia.org/wiki/Bikram_Samwat</a>.
    @class NepaliCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function NepaliCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

NepaliCalendar.prototype = new main.baseCalendar;

assign(NepaliCalendar.prototype, {
    /** The calendar name.
        @memberof NepaliCalendar */
    name: 'Nepali',
    /** Julian date of start of Nepali epoch: 14 April 57 BCE.
        @memberof NepaliCalendar */
    jdEpoch: 1700709.5,
    /** Days per month in a common year.
        @memberof NepaliCalendar */
    daysPerMonth: [31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof NepaliCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof NepaliCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof NepaliCalendar */
    firstMonth: 1,
    /** The minimum day number.
        @memberof NepaliCalendar */
    minDay: 1, 
    /** The number of days in the year.
        @memberof NepaliCalendar */
    daysPerYear: 365,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof NepaliCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Nepali',
            epochs: ['BBS', 'ABS'],
            monthNames: ['Baisakh', 'Jestha', 'Ashadh', 'Shrawan', 'Bhadra', 'Ashwin',
            'Kartik', 'Mangsir', 'Paush', 'Mangh', 'Falgun', 'Chaitra'],
            monthNamesShort: ['Bai', 'Je', 'As', 'Shra', 'Bha', 'Ash', 'Kar', 'Mang', 'Pau', 'Ma', 'Fal', 'Chai'],
            dayNames: ['Aaitabaar', 'Sombaar', 'Manglbaar', 'Budhabaar', 'Bihibaar', 'Shukrabaar', 'Shanibaar'],
            dayNamesShort: ['Aaita', 'Som', 'Mangl', 'Budha', 'Bihi', 'Shukra', 'Shani'],
            dayNamesMin: ['Aai', 'So', 'Man', 'Bu', 'Bi', 'Shu', 'Sha'],
            digits: null,
            dateFormat: 'dd/mm/yyyy',
            firstDay: 1,
            isRTL: false
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof NepaliCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        return this.daysInYear(year) !== this.daysPerYear;
    },

    /** Determine the week of the year for a date.
        @memberof NepaliCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        // Find Sunday of this week starting on Sunday
        var checkDate = this.newDate(year, month, day);
        checkDate.add(-checkDate.dayOfWeek(), 'd');
        return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
    },

    /** Retrieve the number of days in a year.
        @memberof NepaliCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of days.
        @throws Error if an invalid year or a different calendar used. */
    daysInYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        year = date.year();
        if (typeof this.NEPALI_CALENDAR_DATA[year] === 'undefined') {
            return this.daysPerYear;
        }
        var daysPerYear = 0;
        for (var month_number = this.minMonth; month_number <= 12; month_number++) {
            daysPerYear += this.NEPALI_CALENDAR_DATA[year][month_number];
        }
        return daysPerYear;
    },

    /** Retrieve the number of days in a month.
        @memberof NepaliCalendar
        @param year {CDate|number| The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        if (year.year) {
            month = year.month();
            year = year.year();
        }
        this._validate(year, month, this.minDay, main.local.invalidMonth);
        return (typeof this.NEPALI_CALENDAR_DATA[year] === 'undefined' ?
            this.daysPerMonth[month - 1] : this.NEPALI_CALENDAR_DATA[year][month]);
    },

    /** Determine whether this date is a week day.
        @memberof NepaliCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        return this.dayOfWeek(year, month, day) !== 6;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof NepaliCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(nepaliYear, nepaliMonth, nepaliDay) {
        var date = this._validate(nepaliYear, nepaliMonth, nepaliDay, main.local.invalidDate);
        nepaliYear = date.year();
        nepaliMonth = date.month();
        nepaliDay = date.day();
        var gregorianCalendar = main.instance();
        var gregorianDayOfYear = 0; // We will add all the days that went by since
        // the 1st. January and then we can get the Gregorian Date
        var nepaliMonthToCheck = nepaliMonth;
        var nepaliYearToCheck = nepaliYear;
        this._createMissingCalendarData(nepaliYear);
        // Get the correct year
        var gregorianYear = nepaliYear - (nepaliMonthToCheck > 9 || (nepaliMonthToCheck === 9 &&
            nepaliDay >= this.NEPALI_CALENDAR_DATA[nepaliYearToCheck][0]) ? 56 : 57);
        // First we add the amount of days in the actual Nepali month as the day of year in the
        // Gregorian one because at least this days are gone since the 1st. Jan. 
        if (nepaliMonth !== 9) {
            gregorianDayOfYear = nepaliDay;
            nepaliMonthToCheck--;
        }
        // Now we loop throw all Nepali month and add the amount of days to gregorianDayOfYear 
        // we do this till we reach Paush (9th month). 1st. January always falls in this month  
        while (nepaliMonthToCheck !== 9) {
            if (nepaliMonthToCheck <= 0) {
                nepaliMonthToCheck = 12;
                nepaliYearToCheck--;
            }                
            gregorianDayOfYear += this.NEPALI_CALENDAR_DATA[nepaliYearToCheck][nepaliMonthToCheck];
            nepaliMonthToCheck--;
        }        
        // If the date that has to be converted is in Paush (month no. 9) we have to do some other calculation
        if (nepaliMonth === 9) {
            // Add the days that are passed since the first day of Paush and substract the
            // amount of days that lie between 1st. Jan and 1st Paush
            gregorianDayOfYear += nepaliDay - this.NEPALI_CALENDAR_DATA[nepaliYearToCheck][0];
            // For the first days of Paush we are now in negative values,
            // because in the end of the gregorian year we substract
            // 365 / 366 days (P.S. remember math in school + - gives -)
            if (gregorianDayOfYear < 0) {
                gregorianDayOfYear += gregorianCalendar.daysInYear(gregorianYear);
            }
        }
        else {
            gregorianDayOfYear += this.NEPALI_CALENDAR_DATA[nepaliYearToCheck][9] -
                this.NEPALI_CALENDAR_DATA[nepaliYearToCheck][0];
        }        
        return gregorianCalendar.newDate(gregorianYear, 1 ,1).add(gregorianDayOfYear, 'd').toJD();
    },
    
    /** Create a new date from a Julian date.
        @memberof NepaliCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        var gregorianCalendar =  main.instance();
        var gregorianDate = gregorianCalendar.fromJD(jd);
        var gregorianYear = gregorianDate.year();
        var gregorianDayOfYear = gregorianDate.dayOfYear();
        var nepaliYear = gregorianYear + 56; //this is not final, it could be also +57 but +56 is always true for 1st Jan.
        this._createMissingCalendarData(nepaliYear);
        var nepaliMonth = 9; // Jan 1 always fall in Nepali month Paush which is the 9th month of Nepali calendar.
        // Get the Nepali day in Paush (month 9) of 1st January 
        var dayOfFirstJanInPaush = this.NEPALI_CALENDAR_DATA[nepaliYear][0];
        // Check how many days are left of Paush .
        // Days calculated from 1st Jan till the end of the actual Nepali month, 
        // we use this value to check if the gregorian Date is in the actual Nepali month.
        var daysSinceJanFirstToEndOfNepaliMonth =
            this.NEPALI_CALENDAR_DATA[nepaliYear][nepaliMonth] - dayOfFirstJanInPaush + 1;
        // If the gregorian day-of-year is smaller o equal than the sum of days between the 1st January and 
        // the end of the actual nepali month we found the correct nepali month.
        // Example: 
        // The 4th February 2011 is the gregorianDayOfYear 35 (31 days of January + 4)
        // 1st January 2011 is in the nepali year 2067, where 1st. January is in the 17th day of Paush (9th month)
        // In 2067 Paush has 30days, This means (30-17+1=14) there are 14days between 1st January and end of Paush 
        // (including 17th January)
        // The gregorianDayOfYear (35) is bigger than 14, so we check the next month
        // The next nepali month (Mangh) has 29 days 
        // 29+14=43, this is bigger than gregorianDayOfYear(35) so, we found the correct nepali month
        while (gregorianDayOfYear > daysSinceJanFirstToEndOfNepaliMonth) {
            nepaliMonth++;
            if (nepaliMonth > 12) {
                nepaliMonth = 1;
                nepaliYear++;
            }    
            daysSinceJanFirstToEndOfNepaliMonth += this.NEPALI_CALENDAR_DATA[nepaliYear][nepaliMonth];
        }
        // The last step is to calculate the nepali day-of-month
        // to continue our example from before:
        // we calculated there are 43 days from 1st. January (17 Paush) till end of Mangh (29 days)
        // when we subtract from this 43 days the day-of-year of the the Gregorian date (35),
        // we know how far the searched day is away from the end of the Nepali month.
        // So we simply subtract this number from the amount of days in this month (30) 
        var nepaliDayOfMonth = this.NEPALI_CALENDAR_DATA[nepaliYear][nepaliMonth] -
            (daysSinceJanFirstToEndOfNepaliMonth - gregorianDayOfYear);        
        return this.newDate(nepaliYear, nepaliMonth, nepaliDayOfMonth);
    },
    
    /** Creates missing data in the NEPALI_CALENDAR_DATA table.
        This data will not be correct but just give an estimated result. Mostly -/+ 1 day
        @private
        @param nepaliYear {number} The missing year number. */
    _createMissingCalendarData: function(nepaliYear) {
        var tmp_calendar_data = this.daysPerMonth.slice(0);
        tmp_calendar_data.unshift(17);
        for (var nepaliYearToCreate = (nepaliYear - 1); nepaliYearToCreate < (nepaliYear + 2); nepaliYearToCreate++) {
            if (typeof this.NEPALI_CALENDAR_DATA[nepaliYearToCreate] === 'undefined') {
                this.NEPALI_CALENDAR_DATA[nepaliYearToCreate] = tmp_calendar_data;
            }
        }
    },
    
    NEPALI_CALENDAR_DATA:  {
        // These data are from http://www.ashesh.com.np
        1970: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        1971: [18, 31, 31, 32, 31, 32, 30, 30, 29, 30, 29, 30, 30],
        1972: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 30],
        1973: [19, 30, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        1974: [19, 31, 31, 32, 30, 31, 31, 30, 29, 30, 29, 30, 30],
        1975: [18, 31, 31, 32, 32, 30, 31, 30, 29, 30, 29, 30, 30],
        1976: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        1977: [18, 31, 32, 31, 32, 31, 31, 29, 30, 29, 30, 29, 31],
        1978: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        1979: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        1980: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        1981: [18, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 30, 30],
        1982: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        1983: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        1984: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        1985: [18, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 30, 30],
        1986: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        1987: [18, 31, 32, 31, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        1988: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        1989: [18, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
        1990: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        1991: [18, 31, 32, 31, 32, 31, 30, 30, 29, 30, 29, 30, 30],    
        // These data are from http://nepalicalendar.rat32.com/index.php
        1992: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        1993: [18, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
        1994: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        1995: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 30],
        1996: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        1997: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        1998: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        1999: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2000: [17, 30, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        2001: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2002: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2003: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2004: [17, 30, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        2005: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2006: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2007: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2008: [17, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 29, 31],
        2009: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2010: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2011: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2012: [17, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 30, 30],
        2013: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2014: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2015: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2016: [17, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 30, 30],
        2017: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2018: [18, 31, 32, 31, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2019: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        2020: [17, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
        2021: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2022: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 30],
        2023: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        2024: [17, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
        2025: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2026: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2027: [17, 30, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        2028: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2029: [18, 31, 31, 32, 31, 32, 30, 30, 29, 30, 29, 30, 30],
        2030: [17, 31, 32, 31, 32, 31, 30, 30, 30, 30, 30, 30, 31],
        2031: [17, 31, 32, 31, 32, 31, 31, 31, 31, 31, 31, 31, 31],
        2032: [17, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32],
        2033: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2034: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2035: [17, 30, 32, 31, 32, 31, 31, 29, 30, 30, 29, 29, 31],
        2036: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2037: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2038: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2039: [17, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 30, 30],
        2040: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2041: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2042: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2043: [17, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 30, 30],
        2044: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2045: [18, 31, 32, 31, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2046: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2047: [17, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
        2048: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2049: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 30],
        2050: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        2051: [17, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
        2052: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2053: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 30],
        2054: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        2055: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 30, 29, 30],
        2056: [17, 31, 31, 32, 31, 32, 30, 30, 29, 30, 29, 30, 30],
        2057: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2058: [17, 30, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        2059: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2060: [17, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2061: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2062: [17, 30, 32, 31, 32, 31, 31, 29, 30, 29, 30, 29, 31],
        2063: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2064: [17, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2065: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2066: [17, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 29, 31],
        2067: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2068: [17, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2069: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2070: [17, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 30, 30],
        2071: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2072: [17, 31, 32, 31, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2073: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2074: [17, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
        2075: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2076: [16, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 30],
        2077: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        2078: [17, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
        2079: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2080: [16, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 30],
        // These data are from http://www.ashesh.com.np/nepali-calendar/
        2081: [17, 31, 31, 32, 32, 31, 30, 30, 30, 29, 30, 30, 30],
        2082: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 30, 30],
        2083: [17, 31, 31, 32, 31, 31, 30, 30, 30, 29, 30, 30, 30],
        2084: [17, 31, 31, 32, 31, 31, 30, 30, 30, 29, 30, 30, 30],
        2085: [17, 31, 32, 31, 32, 31, 31, 30, 30, 29, 30, 30, 30],
        2086: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 30, 30],
        2087: [16, 31, 31, 32, 31, 31, 31, 30, 30, 29, 30, 30, 30],
        2088: [16, 30, 31, 32, 32, 30, 31, 30, 30, 29, 30, 30, 30],
        2089: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 30, 30],
        2090: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 30, 30],
        2091: [16, 31, 31, 32, 31, 31, 31, 30, 30, 29, 30, 30, 30],
        2092: [16, 31, 31, 32, 32, 31, 30, 30, 30, 29, 30, 30, 30],
        2093: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 30, 30],
        2094: [17, 31, 31, 32, 31, 31, 30, 30, 30, 29, 30, 30, 30],
        2095: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 30, 30, 30],
        2096: [17, 30, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2097: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 30, 30],
        2098: [17, 31, 31, 32, 31, 31, 31, 29, 30, 29, 30, 30, 31],
        2099: [17, 31, 31, 32, 31, 31, 31, 30, 29, 29, 30, 30, 30],
        2100: [17, 31, 32, 31, 32, 30, 31, 30, 29, 30, 29, 30, 30]    
    }
});    

// Nepali calendar implementation
main.calendars.nepali = NepaliCalendar;


},{"../main":552,"object-assign":443}],548:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Persian calendar for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) August 2009.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


/** Implementation of the Persian or Jalali calendar.
    Based on code from <a href="http://www.iranchamber.com/calendar/converter/iranian_calendar_converter.php">http://www.iranchamber.com/calendar/converter/iranian_calendar_converter.php</a>.
    See also <a href="http://en.wikipedia.org/wiki/Iranian_calendar">http://en.wikipedia.org/wiki/Iranian_calendar</a>.
    @class PersianCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function PersianCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

PersianCalendar.prototype = new main.baseCalendar;

assign(PersianCalendar.prototype, {
    /** The calendar name.
        @memberof PersianCalendar */
    name: 'Persian',
    /** Julian date of start of Persian epoch: 19 March 622 CE.
        @memberof PersianCalendar */
    jdEpoch: 1948320.5,
    /** Days per month in a common year.
        @memberof PersianCalendar */
    daysPerMonth: [31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29],
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof PersianCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof PersianCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof PersianCalendar */
    firstMonth: 1,
    /** The minimum day number.
        @memberof PersianCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof PersianCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Persian',
            epochs: ['BP', 'AP'],
            monthNames: ['Farvardin', 'Ordibehesht', 'Khordad', 'Tir', 'Mordad', 'Shahrivar',
            'Mehr', 'Aban', 'Azar', 'Day', 'Bahman', 'Esfand'],
            monthNamesShort: ['Far', 'Ord', 'Kho', 'Tir', 'Mor', 'Sha', 'Meh', 'Aba', 'Aza', 'Day', 'Bah', 'Esf'],
            dayNames: ['Yekshambe', 'Doshambe', 'Seshambe', 'Chæharshambe', 'Panjshambe', 'Jom\'e', 'Shambe'],
            dayNamesShort: ['Yek', 'Do', 'Se', 'Chæ', 'Panj', 'Jom', 'Sha'],
            dayNamesMin: ['Ye','Do','Se','Ch','Pa','Jo','Sh'],
            digits: null,
            dateFormat: 'yyyy/mm/dd',
            firstDay: 6,
            isRTL: false
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof PersianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        return (((((date.year() - (date.year() > 0 ? 474 : 473)) % 2820) +
            474 + 38) * 682) % 2816) < 682;
    },

    /** Determine the week of the year for a date.
        @memberof PersianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        // Find Saturday of this week starting on Saturday
        var checkDate = this.newDate(year, month, day);
        checkDate.add(-((checkDate.dayOfWeek() + 1) % 7), 'd');
        return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
    },

    /** Retrieve the number of days in a month.
        @memberof PersianCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
        return this.daysPerMonth[date.month() - 1] +
            (date.month() === 12 && this.leapYear(date.year()) ? 1 : 0);
    },

    /** Determine whether this date is a week day.
        @memberof PersianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        return this.dayOfWeek(year, month, day) !== 5;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof PersianCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        year = date.year();
        month = date.month();
        day = date.day();
        var epBase = year - (year >= 0 ? 474 : 473);
        var epYear = 474 + mod(epBase, 2820);
        return day + (month <= 7 ? (month - 1) * 31 : (month - 1) * 30 + 6) +
            Math.floor((epYear * 682 - 110) / 2816) + (epYear - 1) * 365 +
            Math.floor(epBase / 2820) * 1029983 + this.jdEpoch - 1;
    },

    /** Create a new date from a Julian date.
        @memberof PersianCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        jd = Math.floor(jd) + 0.5;
        var depoch = jd - this.toJD(475, 1, 1);
        var cycle = Math.floor(depoch / 1029983);
        var cyear = mod(depoch, 1029983);
        var ycycle = 2820;
        if (cyear !== 1029982) {
            var aux1 = Math.floor(cyear / 366);
            var aux2 = mod(cyear, 366);
            ycycle = Math.floor(((2134 * aux1) + (2816 * aux2) + 2815) / 1028522) + aux1 + 1;
        }
        var year = ycycle + (2820 * cycle) + 474;
        year = (year <= 0 ? year - 1 : year);
        var yday = jd - this.toJD(year, 1, 1) + 1;
        var month = (yday <= 186 ? Math.ceil(yday / 31) : Math.ceil((yday - 6) / 30));
        var day = jd - this.toJD(year, month, 1) + 1;
        return this.newDate(year, month, day);
    }
});

// Modulus function which works for non-integers.
function mod(a, b) {
    return a - (b * Math.floor(a / b));
}

// Persian (Jalali) calendar implementation
main.calendars.persian = PersianCalendar;
main.calendars.jalali = PersianCalendar;


},{"../main":552,"object-assign":443}],549:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Taiwanese (Minguo) calendar for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) February 2010.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


var gregorianCalendar = main.instance();

/** Implementation of the Taiwanese calendar.
    See http://en.wikipedia.org/wiki/Minguo_calendar.
    @class TaiwanCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function TaiwanCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

TaiwanCalendar.prototype = new main.baseCalendar;

assign(TaiwanCalendar.prototype, {
    /** The calendar name.
        @memberof TaiwanCalendar */
    name: 'Taiwan',
    /** Julian date of start of Taiwan epoch: 1 January 1912 CE (Gregorian).
        @memberof TaiwanCalendar */
    jdEpoch: 2419402.5,
    /** Difference in years between Taiwan and Gregorian calendars.
        @memberof TaiwanCalendar */
    yearsOffset: 1911,
    /** Days per month in a common year.
        @memberof TaiwanCalendar */
    daysPerMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof TaiwanCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof TaiwanCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof TaiwanCalendar */
    firstMonth: 1,
    /** The minimum day number.
        @memberof TaiwanCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof TaiwanCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Taiwan',
            epochs: ['BROC', 'ROC'],
            monthNames: ['January', 'February', 'March', 'April', 'May', 'June',
            'July', 'August', 'September', 'October', 'November', 'December'],
            monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
            dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
            dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
            digits: null,
            dateFormat: 'yyyy/mm/dd',
            firstDay: 1,
            isRTL: false
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof TaiwanCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        var year = this._t2gYear(date.year());
        return gregorianCalendar.leapYear(year);
    },

    /** Determine the week of the year for a date - ISO 8601.
        @memberof TaiwanCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        var year = this._t2gYear(date.year());
        return gregorianCalendar.weekOfYear(year, date.month(), date.day());
    },

    /** Retrieve the number of days in a month.
        @memberof TaiwanCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
        return this.daysPerMonth[date.month() - 1] +
            (date.month() === 2 && this.leapYear(date.year()) ? 1 : 0);
    },

    /** Determine whether this date is a week day.
        @memberof TaiwanCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        return (this.dayOfWeek(year, month, day) || 7) < 6;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof TaiwanCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        var year = this._t2gYear(date.year());
        return gregorianCalendar.toJD(year, date.month(), date.day());
    },

    /** Create a new date from a Julian date.
        @memberof TaiwanCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        var date = gregorianCalendar.fromJD(jd);
        var year = this._g2tYear(date.year());
        return this.newDate(year, date.month(), date.day());
    },

    /** Convert Taiwanese to Gregorian year.
        @memberof TaiwanCalendar
        @private
        @param year {number} The Taiwanese year.
        @return {number} The corresponding Gregorian year. */
    _t2gYear: function(year) {
        return year + this.yearsOffset + (year >= -this.yearsOffset && year <= -1 ? 1 : 0);
    },

    /** Convert Gregorian to Taiwanese year.
        @memberof TaiwanCalendar
        @private
        @param year {number} The Gregorian year.
        @return {number} The corresponding Taiwanese year. */
    _g2tYear: function(year) {
        return year - this.yearsOffset - (year >= 1 && year <= this.yearsOffset ? 1 : 0);
    }
});

// Taiwan calendar implementation
main.calendars.taiwan = TaiwanCalendar;


},{"../main":552,"object-assign":443}],550:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Thai calendar for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) February 2010.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


var gregorianCalendar = main.instance();

/** Implementation of the Thai calendar.
    See http://en.wikipedia.org/wiki/Thai_calendar.
    @class ThaiCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function ThaiCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

ThaiCalendar.prototype = new main.baseCalendar;

assign(ThaiCalendar.prototype, {
    /** The calendar name.
        @memberof ThaiCalendar */
    name: 'Thai',
    /** Julian date of start of Thai epoch: 1 January 543 BCE (Gregorian).
        @memberof ThaiCalendar */
    jdEpoch: 1523098.5,
    /** Difference in years between Thai and Gregorian calendars.
        @memberof ThaiCalendar */
    yearsOffset: 543, 
    /** Days per month in a common year.
        @memberof ThaiCalendar */
    daysPerMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof ThaiCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof ThaiCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof ThaiCalendar */
    firstMonth: 1,
    /** The minimum day number.
        @memberof ThaiCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof ThaiCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Thai',
            epochs: ['BBE', 'BE'],
            monthNames: ['January', 'February', 'March', 'April', 'May', 'June',
            'July', 'August', 'September', 'October', 'November', 'December'],
            monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
            dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
            dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
            digits: null,
            dateFormat: 'dd/mm/yyyy',
            firstDay: 0,
            isRTL: false
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof ThaiCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        var year = this._t2gYear(date.year());
        return gregorianCalendar.leapYear(year);
    },

    /** Determine the week of the year for a date - ISO 8601.
        @memberof ThaiCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        var year = this._t2gYear(date.year());
        return gregorianCalendar.weekOfYear(year, date.month(), date.day());
    },

    /** Retrieve the number of days in a month.
        @memberof ThaiCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
        return this.daysPerMonth[date.month() - 1] +
            (date.month() === 2 && this.leapYear(date.year()) ? 1 : 0);
    },

    /** Determine whether this date is a week day.
        @memberof ThaiCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        return (this.dayOfWeek(year, month, day) || 7) < 6;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof ThaiCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        var year = this._t2gYear(date.year());
        return gregorianCalendar.toJD(year, date.month(), date.day());
    },

    /** Create a new date from a Julian date.
        @memberof ThaiCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        var date = gregorianCalendar.fromJD(jd);
        var year = this._g2tYear(date.year());
        return this.newDate(year, date.month(), date.day());
    },

    /** Convert Thai to Gregorian year.
        @memberof ThaiCalendar
        @private
        @param year {number} The Thai year.
        @return {number} The corresponding Gregorian year. */
    _t2gYear: function(year) {
        return year - this.yearsOffset - (year >= 1 && year <= this.yearsOffset ? 1 : 0);
    },

    /** Convert Gregorian to Thai year.
        @memberof ThaiCalendar
        @private
        @param year {number} The Gregorian year.
        @return {number} The corresponding Thai year. */
    _g2tYear: function(year) {
        return year + this.yearsOffset + (year >= -this.yearsOffset && year <= -1 ? 1 : 0);
    }
});

// Thai calendar implementation
main.calendars.thai = ThaiCalendar;


},{"../main":552,"object-assign":443}],551:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   UmmAlQura calendar for jQuery v2.0.2.
   Written by Amro Osama March 2013.
   Modified by Binnooh.com & www.elm.sa - 2014 - Added dates back to 1276 Hijri year.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


/** Implementation of the UmmAlQura or 'saudi' calendar.
    See also <a href="http://en.wikipedia.org/wiki/Islamic_calendar#Saudi_Arabia.27s_Umm_al-Qura_calendar">http://en.wikipedia.org/wiki/Islamic_calendar#Saudi_Arabia.27s_Umm_al-Qura_calendar</a>.
    <a href="http://www.ummulqura.org.sa/About.aspx">http://www.ummulqura.org.sa/About.aspx</a>
    <a href="http://www.staff.science.uu.nl/~gent0113/islam/ummalqura.htm">http://www.staff.science.uu.nl/~gent0113/islam/ummalqura.htm</a>
    @class UmmAlQuraCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function UmmAlQuraCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

UmmAlQuraCalendar.prototype = new main.baseCalendar;

assign(UmmAlQuraCalendar.prototype, {
    /** The calendar name.
        @memberof UmmAlQuraCalendar */
    name: 'UmmAlQura',
    //jdEpoch: 1948440, // Julian date of start of UmmAlQura epoch: 14 March 1937 CE
    //daysPerMonth: // Days per month in a common year, replaced by a method.
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof UmmAlQuraCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof UmmAlQuraCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof UmmAlQuraCalendar */
    firstMonth: 1,
    /** The minimum day number.
        @memberof UmmAlQuraCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof UmmAlQuraCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Umm al-Qura',
            epochs: ['BH', 'AH'],
            monthNames: ['Al-Muharram', 'Safar', 'Rabi\' al-awwal', 'Rabi\' Al-Thani', 'Jumada Al-Awwal', 'Jumada Al-Thani',
            'Rajab', 'Sha\'aban', 'Ramadan', 'Shawwal', 'Dhu al-Qi\'dah', 'Dhu al-Hijjah'],
            monthNamesShort: ['Muh', 'Saf', 'Rab1', 'Rab2', 'Jum1', 'Jum2', 'Raj', 'Sha\'', 'Ram', 'Shaw', 'DhuQ', 'DhuH'],
            dayNames: ['Yawm al-Ahad', 'Yawm al-Ithnain', 'Yawm al-Thalāthā’', 'Yawm al-Arba‘ā’', 'Yawm al-Khamīs', 'Yawm al-Jum‘a', 'Yawm al-Sabt'],
            dayNamesMin: ['Ah', 'Ith', 'Th', 'Ar', 'Kh', 'Ju', 'Sa'],
            digits: null,
            dateFormat: 'yyyy/mm/dd',
            firstDay: 6,
            isRTL: true
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof UmmAlQuraCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function (year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        return (this.daysInYear(date.year()) === 355);
    },

    /** Determine the week of the year for a date.
        @memberof UmmAlQuraCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function (year, month, day) {
        // Find Sunday of this week starting on Sunday
        var checkDate = this.newDate(year, month, day);
        checkDate.add(-checkDate.dayOfWeek(), 'd');
        return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
    },

    /** Retrieve the number of days in a year.
        @memberof UmmAlQuraCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of days.
        @throws Error if an invalid year or a different calendar used. */
    daysInYear: function (year) {
        var daysCount = 0;
        for (var i = 1; i <= 12; i++) {
            daysCount += this.daysInMonth(year, i);
        }
        return daysCount;
    },

    /** Retrieve the number of days in a month.
        @memberof UmmAlQuraCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function (year, month) {
        var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
        var mcjdn = date.toJD() - 2400000 + 0.5; // Modified Chronological Julian Day Number (MCJDN)
        // the MCJDN's of the start of the lunations in the Umm al-Qura calendar are stored in the 'ummalqura_dat' array
        var index = 0;
        for (var i = 0; i < ummalqura_dat.length; i++) {
            if (ummalqura_dat[i] > mcjdn) {
                return (ummalqura_dat[index] - ummalqura_dat[index - 1]);
            }
            index++;
        }
        return 30; // Unknown outside
    },

    /** Determine whether this date is a week day.
        @memberof UmmAlQuraCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function (year, month, day) {
        return this.dayOfWeek(year, month, day) !== 5;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof UmmAlQuraCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function (year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        var index = (12 * (date.year() - 1)) + date.month() - 15292;
        var mcjdn = date.day() + ummalqura_dat[index - 1] - 1;
        return mcjdn + 2400000 - 0.5; // Modified Chronological Julian Day Number (MCJDN)
    },

    /** Create a new date from a Julian date.
        @memberof UmmAlQuraCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function (jd) {
        var mcjdn = jd - 2400000 + 0.5; // Modified Chronological Julian Day Number (MCJDN)
        // the MCJDN's of the start of the lunations in the Umm al-Qura calendar 
        // are stored in the 'ummalqura_dat' array
        var index = 0;
        for (var i = 0; i < ummalqura_dat.length; i++) {
            if (ummalqura_dat[i] > mcjdn) break;
            index++;
        }
        var lunation = index + 15292; //UmmAlQura Lunation Number
        var ii = Math.floor((lunation - 1) / 12);
        var year = ii + 1;
        var month = lunation - 12 * ii;
        var day = mcjdn - ummalqura_dat[index - 1] + 1;
        return this.newDate(year, month, day);
    },

    /** Determine whether a date is valid for this calendar.
        @memberof UmmAlQuraCalendar
        @param year {number} The year to examine.
        @param month {number} The month to examine.
        @param day {number} The day to examine.
        @return {boolean} <code>true</code> if a valid date, <code>false</code> if not. */
    isValid: function(year, month, day) {
        var valid = main.baseCalendar.prototype.isValid.apply(this, arguments);
        if (valid) {
            year = (year.year != null ? year.year : year);
            valid = (year >= 1276 && year <= 1500);
        }
        return valid;
    },

    /** Check that a candidate date is from the same calendar and is valid.
        @memberof UmmAlQuraCalendar
        @private
        @param year {CDate|number} The date to validate or the year to validate.
        @param month {number} The month to validate.
        @param day {number} The day to validate.
        @param error {string} Error message if invalid.
        @throws Error if different calendars used or invalid date. */
    _validate: function(year, month, day, error) {
        var date = main.baseCalendar.prototype._validate.apply(this, arguments);
        if (date.year < 1276 || date.year > 1500) {
            throw error.replace(/\{0\}/, this.local.name);
        }
        return date;
    }
});

// UmmAlQura calendar implementation
main.calendars.ummalqura = UmmAlQuraCalendar;

var ummalqura_dat = [
    20,    50,    79,    109,   138,   168,   197,   227,   256,   286,   315,   345,   374,   404,   433,   463,   492,   522,   551,   581, 
    611,   641,   670,   700,   729,   759,   788,   818,   847,   877,   906,   936,   965,   995,   1024,  1054,  1083,  1113,  1142,  1172,
    1201,  1231,  1260,  1290,  1320,  1350,  1379,  1409,  1438,  1468,  1497,  1527,  1556,  1586,  1615,  1645,  1674,  1704,  1733,  1763,
    1792,  1822,  1851,  1881,  1910,  1940,  1969,  1999,  2028,  2058,  2087,  2117,  2146,  2176,  2205,  2235,  2264,  2294,  2323,  2353,
    2383,  2413,  2442,  2472,  2501,  2531,  2560,  2590,  2619,  2649,  2678,  2708,  2737,  2767,  2796,  2826,  2855,  2885,  2914,  2944,
    2973,  3003,  3032,  3062,  3091,  3121,  3150,  3180,  3209,  3239,  3268,  3298,  3327,  3357,  3386,  3416,  3446,  3476,  3505,  3535,
    3564,  3594,  3623,  3653,  3682,  3712,  3741,  3771,  3800,  3830,  3859,  3889,  3918,  3948,  3977,  4007,  4036,  4066,  4095,  4125,
    4155,  4185,  4214,  4244,  4273,  4303,  4332,  4362,  4391,  4421,  4450,  4480,  4509,  4539,  4568,  4598,  4627,  4657,  4686,  4716,
    4745,  4775,  4804,  4834,  4863,  4893,  4922,  4952,  4981,  5011,  5040,  5070,  5099,  5129,  5158,  5188,  5218,  5248,  5277,  5307,
    5336,  5366,  5395,  5425,  5454,  5484,  5513,  5543,  5572,  5602,  5631,  5661,  5690,  5720,  5749,  5779,  5808,  5838,  5867,  5897,
    5926,  5956,  5985,  6015,  6044,  6074,  6103,  6133,  6162,  6192,  6221,  6251,  6281,  6311,  6340,  6370,  6399,  6429,  6458,  6488,
    6517,  6547,  6576,  6606,  6635,  6665,  6694,  6724,  6753,  6783,  6812,  6842,  6871,  6901,  6930,  6960,  6989,  7019,  7048,  7078,
    7107,  7137,  7166,  7196,  7225,  7255,  7284,  7314,  7344,  7374,  7403,  7433,  7462,  7492,  7521,  7551,  7580,  7610,  7639,  7669,
    7698,  7728,  7757,  7787,  7816,  7846,  7875,  7905,  7934,  7964,  7993,  8023,  8053,  8083,  8112,  8142,  8171,  8201,  8230,  8260,
    8289,  8319,  8348,  8378,  8407,  8437,  8466,  8496,  8525,  8555,  8584,  8614,  8643,  8673,  8702,  8732,  8761,  8791,  8821,  8850,
    8880,  8909,  8938,  8968,  8997,  9027,  9056,  9086,  9115,  9145,  9175,  9205,  9234,  9264,  9293,  9322,  9352,  9381,  9410,  9440,
    9470,  9499,  9529,  9559,  9589,  9618,  9648,  9677,  9706,  9736,  9765,  9794,  9824,  9853,  9883,  9913,  9943,  9972,  10002, 10032,
    10061, 10090, 10120, 10149, 10178, 10208, 10237, 10267, 10297, 10326, 10356, 10386, 10415, 10445, 10474, 10504, 10533, 10562, 10592, 10621,
    10651, 10680, 10710, 10740, 10770, 10799, 10829, 10858, 10888, 10917, 10947, 10976, 11005, 11035, 11064, 11094, 11124, 11153, 11183, 11213,
    11242, 11272, 11301, 11331, 11360, 11389, 11419, 11448, 11478, 11507, 11537, 11567, 11596, 11626, 11655, 11685, 11715, 11744, 11774, 11803,
    11832, 11862, 11891, 11921, 11950, 11980, 12010, 12039, 12069, 12099, 12128, 12158, 12187, 12216, 12246, 12275, 12304, 12334, 12364, 12393,
    12423, 12453, 12483, 12512, 12542, 12571, 12600, 12630, 12659, 12688, 12718, 12747, 12777, 12807, 12837, 12866, 12896, 12926, 12955, 12984,
    13014, 13043, 13072, 13102, 13131, 13161, 13191, 13220, 13250, 13280, 13310, 13339, 13368, 13398, 13427, 13456, 13486, 13515, 13545, 13574,
    13604, 13634, 13664, 13693, 13723, 13752, 13782, 13811, 13840, 13870, 13899, 13929, 13958, 13988, 14018, 14047, 14077, 14107, 14136, 14166,
    14195, 14224, 14254, 14283, 14313, 14342, 14372, 14401, 14431, 14461, 14490, 14520, 14550, 14579, 14609, 14638, 14667, 14697, 14726, 14756,
    14785, 14815, 14844, 14874, 14904, 14933, 14963, 14993, 15021, 15051, 15081, 15110, 15140, 15169, 15199, 15228, 15258, 15287, 15317, 15347,
    15377, 15406, 15436, 15465, 15494, 15524, 15553, 15582, 15612, 15641, 15671, 15701, 15731, 15760, 15790, 15820, 15849, 15878, 15908, 15937,
    15966, 15996, 16025, 16055, 16085, 16114, 16144, 16174, 16204, 16233, 16262, 16292, 16321, 16350, 16380, 16409, 16439, 16468, 16498, 16528,
    16558, 16587, 16617, 16646, 16676, 16705, 16734, 16764, 16793, 16823, 16852, 16882, 16912, 16941, 16971, 17001, 17030, 17060, 17089, 17118,
    17148, 17177, 17207, 17236, 17266, 17295, 17325, 17355, 17384, 17414, 17444, 17473, 17502, 17532, 17561, 17591, 17620, 17650, 17679, 17709,
    17738, 17768, 17798, 17827, 17857, 17886, 17916, 17945, 17975, 18004, 18034, 18063, 18093, 18122, 18152, 18181, 18211, 18241, 18270, 18300,
    18330, 18359, 18388, 18418, 18447, 18476, 18506, 18535, 18565, 18595, 18625, 18654, 18684, 18714, 18743, 18772, 18802, 18831, 18860, 18890,
    18919, 18949, 18979, 19008, 19038, 19068, 19098, 19127, 19156, 19186, 19215, 19244, 19274, 19303, 19333, 19362, 19392, 19422, 19452, 19481,
    19511, 19540, 19570, 19599, 19628, 19658, 19687, 19717, 19746, 19776, 19806, 19836, 19865, 19895, 19924, 19954, 19983, 20012, 20042, 20071,
    20101, 20130, 20160, 20190, 20219, 20249, 20279, 20308, 20338, 20367, 20396, 20426, 20455, 20485, 20514, 20544, 20573, 20603, 20633, 20662,
    20692, 20721, 20751, 20780, 20810, 20839, 20869, 20898, 20928, 20957, 20987, 21016, 21046, 21076, 21105, 21135, 21164, 21194, 21223, 21253,
    21282, 21312, 21341, 21371, 21400, 21430, 21459, 21489, 21519, 21548, 21578, 21607, 21637, 21666, 21696, 21725, 21754, 21784, 21813, 21843,
    21873, 21902, 21932, 21962, 21991, 22021, 22050, 22080, 22109, 22138, 22168, 22197, 22227, 22256, 22286, 22316, 22346, 22375, 22405, 22434,
    22464, 22493, 22522, 22552, 22581, 22611, 22640, 22670, 22700, 22730, 22759, 22789, 22818, 22848, 22877, 22906, 22936, 22965, 22994, 23024,
    23054, 23083, 23113, 23143, 23173, 23202, 23232, 23261, 23290, 23320, 23349, 23379, 23408, 23438, 23467, 23497, 23527, 23556, 23586, 23616,
    23645, 23674, 23704, 23733, 23763, 23792, 23822, 23851, 23881, 23910, 23940, 23970, 23999, 24029, 24058, 24088, 24117, 24147, 24176, 24206,
    24235, 24265, 24294, 24324, 24353, 24383, 24413, 24442, 24472, 24501, 24531, 24560, 24590, 24619, 24648, 24678, 24707, 24737, 24767, 24796,
    24826, 24856, 24885, 24915, 24944, 24974, 25003, 25032, 25062, 25091, 25121, 25150, 25180, 25210, 25240, 25269, 25299, 25328, 25358, 25387,
    25416, 25446, 25475, 25505, 25534, 25564, 25594, 25624, 25653, 25683, 25712, 25742, 25771, 25800, 25830, 25859, 25888, 25918, 25948, 25977,
    26007, 26037, 26067, 26096, 26126, 26155, 26184, 26214, 26243, 26272, 26302, 26332, 26361, 26391, 26421, 26451, 26480, 26510, 26539, 26568,
    26598, 26627, 26656, 26686, 26715, 26745, 26775, 26805, 26834, 26864, 26893, 26923, 26952, 26982, 27011, 27041, 27070, 27099, 27129, 27159,
    27188, 27218, 27248, 27277, 27307, 27336, 27366, 27395, 27425, 27454, 27484, 27513, 27542, 27572, 27602, 27631, 27661, 27691, 27720, 27750,
    27779, 27809, 27838, 27868, 27897, 27926, 27956, 27985, 28015, 28045, 28074, 28104, 28134, 28163, 28193, 28222, 28252, 28281, 28310, 28340,
    28369, 28399, 28428, 28458, 28488, 28517, 28547, 28577,
    // From 1356
    28607, 28636, 28665, 28695, 28724, 28754, 28783, 28813, 28843, 28872, 28901, 28931, 28960, 28990, 29019, 29049, 29078, 29108, 29137, 29167,
    29196, 29226, 29255, 29285, 29315, 29345, 29375, 29404, 29434, 29463, 29492, 29522, 29551, 29580, 29610, 29640, 29669, 29699, 29729, 29759,
    29788, 29818, 29847, 29876, 29906, 29935, 29964, 29994, 30023, 30053, 30082, 30112, 30141, 30171, 30200, 30230, 30259, 30289, 30318, 30348,
    30378, 30408, 30437, 30467, 30496, 30526, 30555, 30585, 30614, 30644, 30673, 30703, 30732, 30762, 30791, 30821, 30850, 30880, 30909, 30939,
    30968, 30998, 31027, 31057, 31086, 31116, 31145, 31175, 31204, 31234, 31263, 31293, 31322, 31352, 31381, 31411, 31441, 31471, 31500, 31530,
    31559, 31589, 31618, 31648, 31676, 31706, 31736, 31766, 31795, 31825, 31854, 31884, 31913, 31943, 31972, 32002, 32031, 32061, 32090, 32120,
    32150, 32180, 32209, 32239, 32268, 32298, 32327, 32357, 32386, 32416, 32445, 32475, 32504, 32534, 32563, 32593, 32622, 32652, 32681, 32711,
    32740, 32770, 32799, 32829, 32858, 32888, 32917, 32947, 32976, 33006, 33035, 33065, 33094, 33124, 33153, 33183, 33213, 33243, 33272, 33302,
    33331, 33361, 33390, 33420, 33450, 33479, 33509, 33539, 33568, 33598, 33627, 33657, 33686, 33716, 33745, 33775, 33804, 33834, 33863, 33893,
    33922, 33952, 33981, 34011, 34040, 34069, 34099, 34128, 34158, 34187, 34217, 34247, 34277, 34306, 34336, 34365, 34395, 34424, 34454, 34483,
    34512, 34542, 34571, 34601, 34631, 34660, 34690, 34719, 34749, 34778, 34808, 34837, 34867, 34896, 34926, 34955, 34985, 35015, 35044, 35074,
    35103, 35133, 35162, 35192, 35222, 35251, 35280, 35310, 35340, 35370, 35399, 35429, 35458, 35488, 35517, 35547, 35576, 35605, 35635, 35665,
    35694, 35723, 35753, 35782, 35811, 35841, 35871, 35901, 35930, 35960, 35989, 36019, 36048, 36078, 36107, 36136, 36166, 36195, 36225, 36254,
    36284, 36314, 36343, 36373, 36403, 36433, 36462, 36492, 36521, 36551, 36580, 36610, 36639, 36669, 36698, 36728, 36757, 36786, 36816, 36845,
    36875, 36904, 36934, 36963, 36993, 37022, 37052, 37081, 37111, 37141, 37170, 37200, 37229, 37259, 37288, 37318, 37347, 37377, 37406, 37436,
    37465, 37495, 37524, 37554, 37584, 37613, 37643, 37672, 37701, 37731, 37760, 37790, 37819, 37849, 37878, 37908, 37938, 37967, 37997, 38027,
    38056, 38085, 38115, 38144, 38174, 38203, 38233, 38262, 38292, 38322, 38351, 38381, 38410, 38440, 38469, 38499, 38528, 38558, 38587, 38617,
    38646, 38676, 38705, 38735, 38764, 38794, 38823, 38853, 38882, 38912, 38941, 38971, 39001, 39030, 39059, 39089, 39118, 39148, 39178, 39208,
    39237, 39267, 39297, 39326, 39355, 39385, 39414, 39444, 39473, 39503, 39532, 39562, 39592, 39621, 39650, 39680, 39709, 39739, 39768, 39798,
    39827, 39857, 39886, 39916, 39946, 39975, 40005, 40035, 40064, 40094, 40123, 40153, 40182, 40212, 40241, 40271, 40300, 40330, 40359, 40389,
    40418, 40448, 40477, 40507, 40536, 40566, 40595, 40625, 40655, 40685, 40714, 40744, 40773, 40803, 40832, 40862, 40892, 40921, 40951, 40980,
    41009, 41039, 41068, 41098, 41127, 41157, 41186, 41216, 41245, 41275, 41304, 41334, 41364, 41393, 41422, 41452, 41481, 41511, 41540, 41570,
    41599, 41629, 41658, 41688, 41718, 41748, 41777, 41807, 41836, 41865, 41894, 41924, 41953, 41983, 42012, 42042, 42072, 42102, 42131, 42161,
    42190, 42220, 42249, 42279, 42308, 42337, 42367, 42397, 42426, 42456, 42485, 42515, 42545, 42574, 42604, 42633, 42662, 42692, 42721, 42751,
    42780, 42810, 42839, 42869, 42899, 42929, 42958, 42988, 43017, 43046, 43076, 43105, 43135, 43164, 43194, 43223, 43253, 43283, 43312, 43342,
    43371, 43401, 43430, 43460, 43489, 43519, 43548, 43578, 43607, 43637, 43666, 43696, 43726, 43755, 43785, 43814, 43844, 43873, 43903, 43932,
    43962, 43991, 44021, 44050, 44080, 44109, 44139, 44169, 44198, 44228, 44258, 44287, 44317, 44346, 44375, 44405, 44434, 44464, 44493, 44523,
    44553, 44582, 44612, 44641, 44671, 44700, 44730, 44759, 44788, 44818, 44847, 44877, 44906, 44936, 44966, 44996, 45025, 45055, 45084, 45114,
    45143, 45172, 45202, 45231, 45261, 45290, 45320, 45350, 45380, 45409, 45439, 45468, 45498, 45527, 45556, 45586, 45615, 45644, 45674, 45704,
    45733, 45763, 45793, 45823, 45852, 45882, 45911, 45940, 45970, 45999, 46028, 46058, 46088, 46117, 46147, 46177, 46206, 46236, 46265, 46295,
    46324, 46354, 46383, 46413, 46442, 46472, 46501, 46531, 46560, 46590, 46620, 46649, 46679, 46708, 46738, 46767, 46797, 46826, 46856, 46885,
    46915, 46944, 46974, 47003, 47033, 47063, 47092, 47122, 47151, 47181, 47210, 47240, 47269, 47298, 47328, 47357, 47387, 47417, 47446, 47476,
    47506, 47535, 47565, 47594, 47624, 47653, 47682, 47712, 47741, 47771, 47800, 47830, 47860, 47890, 47919, 47949, 47978, 48008, 48037, 48066,
    48096, 48125, 48155, 48184, 48214, 48244, 48273, 48303, 48333, 48362, 48392, 48421, 48450, 48480, 48509, 48538, 48568, 48598, 48627, 48657,
    48687, 48717, 48746, 48776, 48805, 48834, 48864, 48893, 48922, 48952, 48982, 49011, 49041, 49071, 49100, 49130, 49160, 49189, 49218, 49248,
    49277, 49306, 49336, 49365, 49395, 49425, 49455, 49484, 49514, 49543, 49573, 49602, 49632, 49661, 49690, 49720, 49749, 49779, 49809, 49838,
    49868, 49898, 49927, 49957, 49986, 50016, 50045, 50075, 50104, 50133, 50163, 50192, 50222, 50252, 50281, 50311, 50340, 50370, 50400, 50429,
    50459, 50488, 50518, 50547, 50576, 50606, 50635, 50665, 50694, 50724, 50754, 50784, 50813, 50843, 50872, 50902, 50931, 50960, 50990, 51019,
    51049, 51078, 51108, 51138, 51167, 51197, 51227, 51256, 51286, 51315, 51345, 51374, 51403, 51433, 51462, 51492, 51522, 51552, 51582, 51611,
    51641, 51670, 51699, 51729, 51758, 51787, 51816, 51846, 51876, 51906, 51936, 51965, 51995, 52025, 52054, 52083, 52113, 52142, 52171, 52200,
    52230, 52260, 52290, 52319, 52349, 52379, 52408, 52438, 52467, 52497, 52526, 52555, 52585, 52614, 52644, 52673, 52703, 52733, 52762, 52792,
    52822, 52851, 52881, 52910, 52939, 52969, 52998, 53028, 53057, 53087, 53116, 53146, 53176, 53205, 53235, 53264, 53294, 53324, 53353, 53383,
    53412, 53441, 53471, 53500, 53530, 53559, 53589, 53619, 53648, 53678, 53708, 53737, 53767, 53796, 53825, 53855, 53884, 53913, 53943, 53973,
    54003, 54032, 54062, 54092, 54121, 54151, 54180, 54209, 54239, 54268, 54297, 54327, 54357, 54387, 54416, 54446, 54476, 54505, 54535, 54564,
    54593, 54623, 54652, 54681, 54711, 54741, 54770, 54800, 54830, 54859, 54889, 54919, 54948, 54977, 55007, 55036, 55066, 55095, 55125, 55154,
    55184, 55213, 55243, 55273, 55302, 55332, 55361, 55391, 55420, 55450, 55479, 55508, 55538, 55567, 55597, 55627, 55657, 55686, 55716, 55745,
    55775, 55804, 55834, 55863, 55892, 55922, 55951, 55981, 56011, 56040, 56070, 56100, 56129, 56159, 56188, 56218, 56247, 56276, 56306, 56335,
    56365, 56394, 56424, 56454, 56483, 56513, 56543, 56572, 56601, 56631, 56660, 56690, 56719, 56749, 56778, 56808, 56837, 56867, 56897, 56926,
    56956, 56985, 57015, 57044, 57074, 57103, 57133, 57162, 57192, 57221, 57251, 57280, 57310, 57340, 57369, 57399, 57429, 57458, 57487, 57517,
    57546, 57576, 57605, 57634, 57664, 57694, 57723, 57753, 57783, 57813, 57842, 57871, 57901, 57930, 57959, 57989, 58018, 58048, 58077, 58107,
    58137, 58167, 58196, 58226, 58255, 58285, 58314, 58343, 58373, 58402, 58432, 58461, 58491, 58521, 58551, 58580, 58610, 58639, 58669, 58698,
    58727, 58757, 58786, 58816, 58845, 58875, 58905, 58934, 58964, 58994, 59023, 59053, 59082, 59111, 59141, 59170, 59200, 59229, 59259, 59288,
    59318, 59348, 59377, 59407, 59436, 59466, 59495, 59525, 59554, 59584, 59613, 59643, 59672, 59702, 59731, 59761, 59791, 59820, 59850, 59879,
    59909, 59939, 59968, 59997, 60027, 60056, 60086, 60115, 60145, 60174, 60204, 60234, 60264, 60293, 60323, 60352, 60381, 60411, 60440, 60469,
    60499, 60528, 60558, 60588, 60618, 60648, 60677, 60707, 60736, 60765, 60795, 60824, 60853, 60883, 60912, 60942, 60972, 61002, 61031, 61061,
    61090, 61120, 61149, 61179, 61208, 61237, 61267, 61296, 61326, 61356, 61385, 61415, 61445, 61474, 61504, 61533, 61563, 61592, 61621, 61651,
    61680, 61710, 61739, 61769, 61799, 61828, 61858, 61888, 61917, 61947, 61976, 62006, 62035, 62064, 62094, 62123, 62153, 62182, 62212, 62242,
    62271, 62301, 62331, 62360, 62390, 62419, 62448, 62478, 62507, 62537, 62566, 62596, 62625, 62655, 62685, 62715, 62744, 62774, 62803, 62832,
    62862, 62891, 62921, 62950, 62980, 63009, 63039, 63069, 63099, 63128, 63157, 63187, 63216, 63246, 63275, 63305, 63334, 63363, 63393, 63423,
    63453, 63482, 63512, 63541, 63571, 63600, 63630, 63659, 63689, 63718, 63747, 63777, 63807, 63836, 63866, 63895, 63925, 63955, 63984, 64014,
    64043, 64073, 64102, 64131, 64161, 64190, 64220, 64249, 64279, 64309, 64339, 64368, 64398, 64427, 64457, 64486, 64515, 64545, 64574, 64603,
    64633, 64663, 64692, 64722, 64752, 64782, 64811, 64841, 64870, 64899, 64929, 64958, 64987, 65017, 65047, 65076, 65106, 65136, 65166, 65195,
    65225, 65254, 65283, 65313, 65342, 65371, 65401, 65431, 65460, 65490, 65520, 65549, 65579, 65608, 65638, 65667, 65697, 65726, 65755, 65785,
    65815, 65844, 65874, 65903, 65933, 65963, 65992, 66022, 66051, 66081, 66110, 66140, 66169, 66199, 66228, 66258, 66287, 66317, 66346, 66376,
    66405, 66435, 66465, 66494, 66524, 66553, 66583, 66612, 66641, 66671, 66700, 66730, 66760, 66789, 66819, 66849, 66878, 66908, 66937, 66967,
    66996, 67025, 67055, 67084, 67114, 67143, 67173, 67203, 67233, 67262, 67292, 67321, 67351, 67380, 67409, 67439, 67468, 67497, 67527, 67557,
    67587, 67617, 67646, 67676, 67705, 67735, 67764, 67793, 67823, 67852, 67882, 67911, 67941, 67971, 68000, 68030, 68060, 68089, 68119, 68148,
    68177, 68207, 68236, 68266, 68295, 68325, 68354, 68384, 68414, 68443, 68473, 68502, 68532, 68561, 68591, 68620, 68650, 68679, 68708, 68738,
    68768, 68797, 68827, 68857, 68886, 68916, 68946, 68975, 69004, 69034, 69063, 69092, 69122, 69152, 69181, 69211, 69240, 69270, 69300, 69330,
    69359, 69388, 69418, 69447, 69476, 69506, 69535, 69565, 69595, 69624, 69654, 69684, 69713, 69743, 69772, 69802, 69831, 69861, 69890, 69919,
    69949, 69978, 70008, 70038, 70067, 70097, 70126, 70156, 70186, 70215, 70245, 70274, 70303, 70333, 70362, 70392, 70421, 70451, 70481, 70510,
    70540, 70570, 70599, 70629, 70658, 70687, 70717, 70746, 70776, 70805, 70835, 70864, 70894, 70924, 70954, 70983, 71013, 71042, 71071, 71101,
    71130, 71159, 71189, 71218, 71248, 71278, 71308, 71337, 71367, 71397, 71426, 71455, 71485, 71514, 71543, 71573, 71602, 71632, 71662, 71691,
    71721, 71751, 71781, 71810, 71839, 71869, 71898, 71927, 71957, 71986, 72016, 72046, 72075, 72105, 72135, 72164, 72194, 72223, 72253, 72282,
    72311, 72341, 72370, 72400, 72429, 72459, 72489, 72518, 72548, 72577, 72607, 72637, 72666, 72695, 72725, 72754, 72784, 72813, 72843, 72872,
    72902, 72931, 72961, 72991, 73020, 73050, 73080, 73109, 73139, 73168, 73197, 73227, 73256, 73286, 73315, 73345, 73375, 73404, 73434, 73464,
    73493, 73523, 73552, 73581, 73611, 73640, 73669, 73699, 73729, 73758, 73788, 73818, 73848, 73877, 73907, 73936, 73965, 73995, 74024, 74053,
    74083, 74113, 74142, 74172, 74202, 74231, 74261, 74291, 74320, 74349, 74379, 74408, 74437, 74467, 74497, 74526, 74556, 74586, 74615, 74645,
    74675, 74704, 74733, 74763, 74792, 74822, 74851, 74881, 74910, 74940, 74969, 74999, 75029, 75058, 75088, 75117, 75147, 75176, 75206, 75235,
    75264, 75294, 75323, 75353, 75383, 75412, 75442, 75472, 75501, 75531, 75560, 75590, 75619, 75648, 75678, 75707, 75737, 75766, 75796, 75826,
    75856, 75885, 75915, 75944, 75974, 76003, 76032, 76062, 76091, 76121, 76150, 76180, 76210, 76239, 76269, 76299, 76328, 76358, 76387, 76416,
    76446, 76475, 76505, 76534, 76564, 76593, 76623, 76653, 76682, 76712, 76741, 76771, 76801, 76830, 76859, 76889, 76918, 76948, 76977, 77007,
    77036, 77066, 77096, 77125, 77155, 77185, 77214, 77243, 77273, 77302, 77332, 77361, 77390, 77420, 77450, 77479, 77509, 77539, 77569, 77598,
    77627, 77657, 77686, 77715, 77745, 77774, 77804, 77833, 77863, 77893, 77923, 77952, 77982, 78011, 78041, 78070, 78099, 78129, 78158, 78188,
    78217, 78247, 78277, 78307, 78336, 78366, 78395, 78425, 78454, 78483, 78513, 78542, 78572, 78601, 78631, 78661, 78690, 78720, 78750, 78779,
    78808, 78838, 78867, 78897, 78926, 78956, 78985, 79015, 79044, 79074, 79104, 79133, 79163, 79192, 79222, 79251, 79281, 79310, 79340, 79369,
    79399, 79428, 79458, 79487, 79517, 79546, 79576, 79606, 79635, 79665, 79695, 79724, 79753, 79783, 79812, 79841, 79871, 79900, 79930, 79960,
    79990];


},{"../main":552,"object-assign":443}],552:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Calendars for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) August 2009.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var assign = _dereq_('object-assign');


function Calendars() {
    this.regionalOptions = [];
    this.regionalOptions[''] = {
        invalidCalendar: 'Calendar {0} not found',
        invalidDate: 'Invalid {0} date',
        invalidMonth: 'Invalid {0} month',
        invalidYear: 'Invalid {0} year',
        differentCalendars: 'Cannot mix {0} and {1} dates'
    };
    this.local = this.regionalOptions[''];
    this.calendars = {};
    this._localCals = {};
}

/** Create the calendars plugin.
    <p>Provides support for various world calendars in a consistent manner.</p>
     @class Calendars
    @example _exports.instance('julian').newDate(2014, 12, 25) */
assign(Calendars.prototype, {

    /** Obtain a calendar implementation and localisation.
        @memberof Calendars
        @param [name='gregorian'] {string} The name of the calendar, e.g. 'gregorian', 'persian', 'islamic'.
        @param [language=''] {string} The language code to use for localisation (default is English).
        @return {Calendar} The calendar and localisation.
        @throws Error if calendar not found. */
    instance: function(name, language) {
        name = (name || 'gregorian').toLowerCase();
        language = language || '';
        var cal = this._localCals[name + '-' + language];
        if (!cal && this.calendars[name]) {
            cal = new this.calendars[name](language);
            this._localCals[name + '-' + language] = cal;
        }
        if (!cal) {
            throw (this.local.invalidCalendar || this.regionalOptions[''].invalidCalendar).
                replace(/\{0\}/, name);
        }
        return cal;
    },

    /** Create a new date - for today if no other parameters given.
        @memberof Calendars
        @param year {CDate|number} The date to copy or the year for the date.
        @param [month] {number} The month for the date.
        @param [day] {number} The day for the date.
        @param [calendar='gregorian'] {BaseCalendar|string} The underlying calendar or the name of the calendar.
        @param [language=''] {string} The language to use for localisation (default English).
        @return {CDate} The new date.
        @throws Error if an invalid date. */
    newDate: function(year, month, day, calendar, language) {
        calendar = (year != null && year.year ? year.calendar() : (typeof calendar === 'string' ?
            this.instance(calendar, language) : calendar)) || this.instance();
        return calendar.newDate(year, month, day);
    },
    
    /** A simple digit substitution function for localising numbers via the Calendar digits option.
        @member Calendars
        @param digits {string[]} The substitute digits, for 0 through 9.
        @return {function} The substitution function. */
    substituteDigits: function(digits) {
        return function(value) {
            return (value + '').replace(/[0-9]/g, function(digit) {
                return digits[digit];
            });
        }
    },
    
    /** Digit substitution function for localising Chinese style numbers via the Calendar digits option.
        @member Calendars
        @param digits {string[]} The substitute digits, for 0 through 9.
        @param powers {string[]} The characters denoting powers of 10, i.e. 1, 10, 100, 1000.
        @return {function} The substitution function. */
    substituteChineseDigits: function(digits, powers) {
        return function(value) {
            var localNumber = '';
            var power = 0;
            while (value > 0) {
                var units = value % 10;
                localNumber = (units === 0 ? '' : digits[units] + powers[power]) + localNumber;
                power++;
                value = Math.floor(value / 10);
            }
            if (localNumber.indexOf(digits[1] + powers[1]) === 0) {
                localNumber = localNumber.substr(1);
            }
            return localNumber || digits[0];
        }
    }
});

/** Generic date, based on a particular calendar.
    @class CDate
    @param calendar {BaseCalendar} The underlying calendar implementation.
    @param year {number} The year for this date.
    @param month {number} The month for this date.
    @param day {number} The day for this date.
    @return {CDate} The date object.
    @throws Error if an invalid date. */
function CDate(calendar, year, month, day) {
    this._calendar = calendar;
    this._year = year;
    this._month = month;
    this._day = day;
    if (this._calendar._validateLevel === 0 &&
            !this._calendar.isValid(this._year, this._month, this._day)) {
        throw (_exports.local.invalidDate || _exports.regionalOptions[''].invalidDate).
            replace(/\{0\}/, this._calendar.local.name);
    }
}

/** Pad a numeric value with leading zeroes.
    @private
    @param value {number} The number to format.
    @param length {number} The minimum length.
    @return {string} The formatted number. */
function pad(value, length) {
    value = '' + value;
    return '000000'.substring(0, length - value.length) + value;
}

assign(CDate.prototype, {

    /** Create a new date.
        @memberof CDate
        @param [year] {CDate|number} The date to copy or the year for the date (default this date).
        @param [month] {number} The month for the date.
        @param [day] {number} The day for the date.
        @return {CDate} The new date.
        @throws Error if an invalid date. */
    newDate: function(year, month, day) {
        return this._calendar.newDate((year == null ? this : year), month, day);
    },

    /** Set or retrieve the year for this date.
        @memberof CDate
        @param [year] {number} The year for the date.
        @return {number|CDate} The date's year (if no parameter) or the updated date.
        @throws Error if an invalid date. */
    year: function(year) {
        return (arguments.length === 0 ? this._year : this.set(year, 'y'));
    },

    /** Set or retrieve the month for this date.
        @memberof CDate
        @param [month] {number} The month for the date.
        @return {number|CDate} The date's month (if no parameter) or the updated date.
        @throws Error if an invalid date. */
    month: function(month) {
        return (arguments.length === 0 ? this._month : this.set(month, 'm'));
    },

    /** Set or retrieve the day for this date.
        @memberof CDate
        @param [day] {number} The day for the date.
        @return {number|CData} The date's day (if no parameter) or the updated date.
        @throws Error if an invalid date. */
    day: function(day) {
        return (arguments.length === 0 ? this._day : this.set(day, 'd'));
    },

    /** Set new values for this date.
        @memberof CDate
        @param year {number} The year for the date.
        @param month {number} The month for the date.
        @param day {number} The day for the date.
        @return {CDate} The updated date.
        @throws Error if an invalid date. */
    date: function(year, month, day) {
        if (!this._calendar.isValid(year, month, day)) {
            throw (_exports.local.invalidDate || _exports.regionalOptions[''].invalidDate).
                replace(/\{0\}/, this._calendar.local.name);
        }
        this._year = year;
        this._month = month;
        this._day = day;
        return this;
    },

    /** Determine whether this date is in a leap year.
        @memberof CDate
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not. */
    leapYear: function() {
        return this._calendar.leapYear(this);
    },

    /** Retrieve the epoch designator for this date, e.g. BCE or CE.
        @memberof CDate
        @return {string} The current epoch. */
    epoch: function() {
        return this._calendar.epoch(this);
    },

    /** Format the year, if not a simple sequential number.
        @memberof CDate
        @return {string} The formatted year. */
    formatYear: function() {
        return this._calendar.formatYear(this);
    },

    /** Retrieve the month of the year for this date,
        i.e. the month's position within a numbered year.
        @memberof CDate
        @return {number} The month of the year: <code>minMonth</code> to months per year. */
    monthOfYear: function() {
        return this._calendar.monthOfYear(this);
    },

    /** Retrieve the week of the year for this date.
        @memberof CDate
        @return {number} The week of the year: 1 to weeks per year. */
    weekOfYear: function() {
        return this._calendar.weekOfYear(this);
    },

    /** Retrieve the number of days in the year for this date.
        @memberof CDate
        @return {number} The number of days in this year. */
    daysInYear: function() {
        return this._calendar.daysInYear(this);
    },

    /** Retrieve the day of the year for this date.
        @memberof CDate
        @return {number} The day of the year: 1 to days per year. */
    dayOfYear: function() {
        return this._calendar.dayOfYear(this);
    },

    /** Retrieve the number of days in the month for this date.
        @memberof CDate
        @return {number} The number of days. */
    daysInMonth: function() {
        return this._calendar.daysInMonth(this);
    },

    /** Retrieve the day of the week for this date.
        @memberof CDate
        @return {number} The day of the week: 0 to number of days - 1. */
    dayOfWeek: function() {
        return this._calendar.dayOfWeek(this);
    },

    /** Determine whether this date is a week day.
        @memberof CDate
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not. */
    weekDay: function() {
        return this._calendar.weekDay(this);
    },

    /** Retrieve additional information about this date.
        @memberof CDate
        @return {object} Additional information - contents depends on calendar. */
    extraInfo: function() {
        return this._calendar.extraInfo(this);
    },

    /** Add period(s) to a date.
        @memberof CDate
        @param offset {number} The number of periods to adjust by.
        @param period {string} One of 'y' for year, 'm' for month, 'w' for week, 'd' for day.
        @return {CDate} The updated date. */
    add: function(offset, period) {
        return this._calendar.add(this, offset, period);
    },

    /** Set a portion of the date.
        @memberof CDate
        @param value {number} The new value for the period.
        @param period {string} One of 'y' for year, 'm' for month, 'd' for day.
        @return {CDate} The updated date.
        @throws Error if not a valid date. */
    set: function(value, period) {
        return this._calendar.set(this, value, period);
    },

    /** Compare this date to another date.
        @memberof CDate
        @param date {CDate} The other date.
        @return {number} -1 if this date is before the other date,
                0 if they are equal, or +1 if this date is after the other date. */
    compareTo: function(date) {
        if (this._calendar.name !== date._calendar.name) {
            throw (_exports.local.differentCalendars || _exports.regionalOptions[''].differentCalendars).
                replace(/\{0\}/, this._calendar.local.name).replace(/\{1\}/, date._calendar.local.name);
        }
        var c = (this._year !== date._year ? this._year - date._year :
            this._month !== date._month ? this.monthOfYear() - date.monthOfYear() :
            this._day - date._day);
        return (c === 0 ? 0 : (c < 0 ? -1 : +1));
    },

    /** Retrieve the calendar backing this date.
        @memberof CDate
        @return {BaseCalendar} The calendar implementation. */
    calendar: function() {
        return this._calendar;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof CDate
        @return {number} The equivalent Julian date. */
    toJD: function() {
        return this._calendar.toJD(this);
    },

    /** Create a new date from a Julian date.
        @memberof CDate
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        return this._calendar.fromJD(jd);
    },

    /** Convert this date to a standard (Gregorian) JavaScript Date.
        @memberof CDate
        @return {Date} The equivalent JavaScript date. */
    toJSDate: function() {
        return this._calendar.toJSDate(this);
    },

    /** Create a new date from a standard (Gregorian) JavaScript Date.
        @memberof CDate
        @param jsd {Date} The JavaScript date to convert.
        @return {CDate} The equivalent date. */
    fromJSDate: function(jsd) {
        return this._calendar.fromJSDate(jsd);
    },

    /** Convert to a string for display.
        @memberof CDate
        @return {string} This date as a string. */
    toString: function() {
        return (this.year() < 0 ? '-' : '') + pad(Math.abs(this.year()), 4) +
            '-' + pad(this.month(), 2) + '-' + pad(this.day(), 2);
    }
});

/** Basic functionality for all calendars.
    Other calendars should extend this:
    <pre>OtherCalendar.prototype = new BaseCalendar;</pre>
    @class BaseCalendar */
function BaseCalendar() {
    this.shortYearCutoff = '+10';
}

assign(BaseCalendar.prototype, {
    _validateLevel: 0, // "Stack" to turn validation on/off

    /** Create a new date within this calendar - today if no parameters given.
        @memberof BaseCalendar
        @param year {CDate|number} The date to duplicate or the year for the date.
        @param [month] {number} The month for the date.
        @param [day] {number} The day for the date.
        @return {CDate} The new date.
        @throws Error if not a valid date or a different calendar used. */
    newDate: function(year, month, day) {
        if (year == null) {
            return this.today();
        }
        if (year.year) {
            this._validate(year, month, day,
                _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate);
            day = year.day();
            month = year.month();
            year = year.year();
        }
        return new CDate(this, year, month, day);
    },

    /** Create a new date for today.
        @memberof BaseCalendar
        @return {CDate} Today's date. */
    today: function() {
        return this.fromJSDate(new Date());
    },

    /** Retrieve the epoch designator for this date.
        @memberof BaseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {string} The current epoch.
        @throws Error if an invalid year or a different calendar used. */
    epoch: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay,
            _exports.local.invalidYear || _exports.regionalOptions[''].invalidYear);
        return (date.year() < 0 ? this.local.epochs[0] : this.local.epochs[1]);
    },

    /** Format the year, if not a simple sequential number
        @memberof BaseCalendar
        @param year {CDate|number} The date to format or the year to format.
        @return {string} The formatted year.
        @throws Error if an invalid year or a different calendar used. */
    formatYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay,
            _exports.local.invalidYear || _exports.regionalOptions[''].invalidYear);
        return (date.year() < 0 ? '-' : '') + pad(Math.abs(date.year()), 4)
    },

    /** Retrieve the number of months in a year.
        @memberof BaseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of months.
        @throws Error if an invalid year or a different calendar used. */
    monthsInYear: function(year) {
        this._validate(year, this.minMonth, this.minDay,
            _exports.local.invalidYear || _exports.regionalOptions[''].invalidYear);
        return 12;
    },

    /** Calculate the month's ordinal position within the year -
        for those calendars that don't start at month 1!
        @memberof BaseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param month {number} The month to examine.
        @return {number} The ordinal position, starting from <code>minMonth</code>.
        @throws Error if an invalid year/month or a different calendar used. */
    monthOfYear: function(year, month) {
        var date = this._validate(year, month, this.minDay,
            _exports.local.invalidMonth || _exports.regionalOptions[''].invalidMonth);
        return (date.month() + this.monthsInYear(date) - this.firstMonth) %
            this.monthsInYear(date) + this.minMonth;
    },

    /** Calculate actual month from ordinal position, starting from minMonth.
        @memberof BaseCalendar
        @param year {number} The year to examine.
        @param ord {number} The month's ordinal position.
        @return {number} The month's number.
        @throws Error if an invalid year/month. */
    fromMonthOfYear: function(year, ord) {
        var m = (ord + this.firstMonth - 2 * this.minMonth) %
            this.monthsInYear(year) + this.minMonth;
        this._validate(year, m, this.minDay,
            _exports.local.invalidMonth || _exports.regionalOptions[''].invalidMonth);
        return m;
    },

    /** Retrieve the number of days in a year.
        @memberof BaseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of days.
        @throws Error if an invalid year or a different calendar used. */
    daysInYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay,
            _exports.local.invalidYear || _exports.regionalOptions[''].invalidYear);
        return (this.leapYear(date) ? 366 : 365);
    },

    /** Retrieve the day of the year for a date.
        @memberof BaseCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The day of the year.
        @throws Error if an invalid date or a different calendar used. */
    dayOfYear: function(year, month, day) {
        var date = this._validate(year, month, day,
            _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate);
        return date.toJD() - this.newDate(date.year(),
            this.fromMonthOfYear(date.year(), this.minMonth), this.minDay).toJD() + 1;
    },

    /** Retrieve the number of days in a week.
        @memberof BaseCalendar
        @return {number} The number of days. */
    daysInWeek: function() {
        return 7;
    },

    /** Retrieve the day of the week for a date.
        @memberof BaseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The day of the week: 0 to number of days - 1.
        @throws Error if an invalid date or a different calendar used. */
    dayOfWeek: function(year, month, day) {
        var date = this._validate(year, month, day,
            _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate);
        return (Math.floor(this.toJD(date)) + 2) % this.daysInWeek();
    },

    /** Retrieve additional information about a date.
        @memberof BaseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {object} Additional information - contents depends on calendar.
        @throws Error if an invalid date or a different calendar used. */
    extraInfo: function(year, month, day) {
        this._validate(year, month, day,
            _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate);
        return {};
    },

    /** Add period(s) to a date.
        Cater for no year zero.
        @memberof BaseCalendar
        @param date {CDate} The starting date.
        @param offset {number} The number of periods to adjust by.
        @param period {string} One of 'y' for year, 'm' for month, 'w' for week, 'd' for day.
        @return {CDate} The updated date.
        @throws Error if a different calendar used. */
    add: function(date, offset, period) {
        this._validate(date, this.minMonth, this.minDay,
            _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate);
        return this._correctAdd(date, this._add(date, offset, period), offset, period);
    },

    /** Add period(s) to a date.
        @memberof BaseCalendar
        @private
        @param date {CDate} The starting date.
        @param offset {number} The number of periods to adjust by.
        @param period {string} One of 'y' for year, 'm' for month, 'w' for week, 'd' for day.
        @return {CDate} The updated date. */
    _add: function(date, offset, period) {
        this._validateLevel++;
        if (period === 'd' || period === 'w') {
            var jd = date.toJD() + offset * (period === 'w' ? this.daysInWeek() : 1);
            var d = date.calendar().fromJD(jd);
            this._validateLevel--;
            return [d.year(), d.month(), d.day()];
        }
        try {
            var y = date.year() + (period === 'y' ? offset : 0);
            var m = date.monthOfYear() + (period === 'm' ? offset : 0);
            var d = date.day();// + (period === 'd' ? offset : 0) +
                //(period === 'w' ? offset * this.daysInWeek() : 0);
            var resyncYearMonth = function(calendar) {
                while (m < calendar.minMonth) {
                    y--;
                    m += calendar.monthsInYear(y);
                }
                var yearMonths = calendar.monthsInYear(y);
                while (m > yearMonths - 1 + calendar.minMonth) {
                    y++;
                    m -= yearMonths;
                    yearMonths = calendar.monthsInYear(y);
                }
            };
            if (period === 'y') {
                if (date.month() !== this.fromMonthOfYear(y, m)) { // Hebrew
                    m = this.newDate(y, date.month(), this.minDay).monthOfYear();
                }
                m = Math.min(m, this.monthsInYear(y));
                d = Math.min(d, this.daysInMonth(y, this.fromMonthOfYear(y, m)));
            }
            else if (period === 'm') {
                resyncYearMonth(this);
                d = Math.min(d, this.daysInMonth(y, this.fromMonthOfYear(y, m)));
            }
            var ymd = [y, this.fromMonthOfYear(y, m), d];
            this._validateLevel--;
            return ymd;
        }
        catch (e) {
            this._validateLevel--;
            throw e;
        }
    },

    /** Correct a candidate date after adding period(s) to a date.
        Handle no year zero if necessary.
        @memberof BaseCalendar
        @private
        @param date {CDate} The starting date.
        @param ymd {number[]} The added date.
        @param offset {number} The number of periods to adjust by.
        @param period {string} One of 'y' for year, 'm' for month, 'w' for week, 'd' for day.
        @return {CDate} The updated date. */
    _correctAdd: function(date, ymd, offset, period) {
        if (!this.hasYearZero && (period === 'y' || period === 'm')) {
            if (ymd[0] === 0 || // In year zero
                    (date.year() > 0) !== (ymd[0] > 0)) { // Crossed year zero
                var adj = {y: [1, 1, 'y'], m: [1, this.monthsInYear(-1), 'm'],
                    w: [this.daysInWeek(), this.daysInYear(-1), 'd'],
                    d: [1, this.daysInYear(-1), 'd']}[period];
                var dir = (offset < 0 ? -1 : +1);
                ymd = this._add(date, offset * adj[0] + dir * adj[1], adj[2]);
            }
        }
        return date.date(ymd[0], ymd[1], ymd[2]);
    },

    /** Set a portion of the date.
        @memberof BaseCalendar
        @param date {CDate} The starting date.
        @param value {number} The new value for the period.
        @param period {string} One of 'y' for year, 'm' for month, 'd' for day.
        @return {CDate} The updated date.
        @throws Error if an invalid date or a different calendar used. */
    set: function(date, value, period) {
        this._validate(date, this.minMonth, this.minDay,
            _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate);
        var y = (period === 'y' ? value : date.year());
        var m = (period === 'm' ? value : date.month());
        var d = (period === 'd' ? value : date.day());
        if (period === 'y' || period === 'm') {
            d = Math.min(d, this.daysInMonth(y, m));
        }
        return date.date(y, m, d);
    },

    /** Determine whether a date is valid for this calendar.
        @memberof BaseCalendar
        @param year {number} The year to examine.
        @param month {number} The month to examine.
        @param day {number} The day to examine.
        @return {boolean} <code>true</code> if a valid date, <code>false</code> if not. */
    isValid: function(year, month, day) {
        this._validateLevel++;
        var valid = (this.hasYearZero || year !== 0);
        if (valid) {
            var date = this.newDate(year, month, this.minDay);
            valid = (month >= this.minMonth && month - this.minMonth < this.monthsInYear(date)) &&
                (day >= this.minDay && day - this.minDay < this.daysInMonth(date));
        }
        this._validateLevel--;
        return valid;
    },

    /** Convert the date to a standard (Gregorian) JavaScript Date.
        @memberof BaseCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {Date} The equivalent JavaScript date.
        @throws Error if an invalid date or a different calendar used. */
    toJSDate: function(year, month, day) {
        var date = this._validate(year, month, day,
            _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate);
        return _exports.instance().fromJD(this.toJD(date)).toJSDate();
    },

    /** Convert the date from a standard (Gregorian) JavaScript Date.
        @memberof BaseCalendar
        @param jsd {Date} The JavaScript date.
        @return {CDate} The equivalent calendar date. */
    fromJSDate: function(jsd) {
        return this.fromJD(_exports.instance().fromJSDate(jsd).toJD());
    },

    /** Check that a candidate date is from the same calendar and is valid.
        @memberof BaseCalendar
        @private
        @param year {CDate|number} The date to validate or the year to validate.
        @param [month] {number} The month to validate.
        @param [day] {number} The day to validate.
        @param error {string} Rrror message if invalid.
        @throws Error if different calendars used or invalid date. */
    _validate: function(year, month, day, error) {
        if (year.year) {
            if (this._validateLevel === 0 && this.name !== year.calendar().name) {
                throw (_exports.local.differentCalendars || _exports.regionalOptions[''].differentCalendars).
                    replace(/\{0\}/, this.local.name).replace(/\{1\}/, year.calendar().local.name);
            }
            return year;
        }
        try {
            this._validateLevel++;
            if (this._validateLevel === 1 && !this.isValid(year, month, day)) {
                throw error.replace(/\{0\}/, this.local.name);
            }
            var date = this.newDate(year, month, day);
            this._validateLevel--;
            return date;
        }
        catch (e) {
            this._validateLevel--;
            throw e;
        }
    }
});

/** Implementation of the Proleptic Gregorian Calendar.
    See <a href=":http://en.wikipedia.org/wiki/Gregorian_calendar">http://en.wikipedia.org/wiki/Gregorian_calendar</a>
    and <a href="http://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar">http://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar</a>.
    @class GregorianCalendar
    @augments BaseCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function GregorianCalendar(language) {
    this.local = this.regionalOptions[language] || this.regionalOptions[''];
}

GregorianCalendar.prototype = new BaseCalendar;

assign(GregorianCalendar.prototype, {
    /** The calendar name.
        @memberof GregorianCalendar */
    name: 'Gregorian',
     /** Julian date of start of Gregorian epoch: 1 January 0001 CE.
        @memberof GregorianCalendar */
    jdEpoch: 1721425.5,
     /** Days per month in a common year.
        @memberof GregorianCalendar */
    daysPerMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
     /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof GregorianCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof GregorianCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof GregorianCalendar */
    firstMonth: 1,
     /** The minimum day number.
        @memberof GregorianCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof GregorianCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Gregorian',
            epochs: ['BCE', 'CE'],
            monthNames: ['January', 'February', 'March', 'April', 'May', 'June',
            'July', 'August', 'September', 'October', 'November', 'December'],
            monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
            dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
            dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
            digits: null,
            dateFormat: 'mm/dd/yyyy',
            firstDay: 0,
            isRTL: false
        }
    },
    
    /** Determine whether this date is in a leap year.
        @memberof GregorianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay,
            _exports.local.invalidYear || _exports.regionalOptions[''].invalidYear);
        var year = date.year() + (date.year() < 0 ? 1 : 0); // No year zero
        return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
    },

    /** Determine the week of the year for a date - ISO 8601.
        @memberof GregorianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year, starting from 1.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        // Find Thursday of this week starting on Monday
        var checkDate = this.newDate(year, month, day);
        checkDate.add(4 - (checkDate.dayOfWeek() || 7), 'd');
        return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
    },

    /** Retrieve the number of days in a month.
        @memberof GregorianCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        var date = this._validate(year, month, this.minDay,
            _exports.local.invalidMonth || _exports.regionalOptions[''].invalidMonth);
        return this.daysPerMonth[date.month() - 1] +
            (date.month() === 2 && this.leapYear(date.year()) ? 1 : 0);
    },

    /** Determine whether this date is a week day.
        @memberof GregorianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        return (this.dayOfWeek(year, month, day) || 7) < 6;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof GregorianCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day,
            _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate);
        year = date.year();
        month = date.month();
        day = date.day();
        if (year < 0) { year++; } // No year zero
        // Jean Meeus algorithm, "Astronomical Algorithms", 1991
        if (month < 3) {
            month += 12;
            year--;
        }
        var a = Math.floor(year / 100);
        var b = 2 - a + Math.floor(a / 4);
        return Math.floor(365.25 * (year + 4716)) +
            Math.floor(30.6001 * (month + 1)) + day + b - 1524.5;
    },

    /** Create a new date from a Julian date.
        @memberof GregorianCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        // Jean Meeus algorithm, "Astronomical Algorithms", 1991
        var z = Math.floor(jd + 0.5);
        var a = Math.floor((z - 1867216.25) / 36524.25);
        a = z + 1 + a - Math.floor(a / 4);
        var b = a + 1524;
        var c = Math.floor((b - 122.1) / 365.25);
        var d = Math.floor(365.25 * c);
        var e = Math.floor((b - d) / 30.6001);
        var day = b - d - Math.floor(e * 30.6001);
        var month = e - (e > 13.5 ? 13 : 1);
        var year = c - (month > 2.5 ? 4716 : 4715);
        if (year <= 0) { year--; } // No year zero
        return this.newDate(year, month, day);
    },

    /** Convert this date to a standard (Gregorian) JavaScript Date.
        @memberof GregorianCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {Date} The equivalent JavaScript date.
        @throws Error if an invalid date or a different calendar used. */
    toJSDate: function(year, month, day) {
        var date = this._validate(year, month, day,
            _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate);
        var jsd = new Date(date.year(), date.month() - 1, date.day());
        jsd.setHours(0);
        jsd.setMinutes(0);
        jsd.setSeconds(0);
        jsd.setMilliseconds(0);
        // Hours may be non-zero on daylight saving cut-over:
        // > 12 when midnight changeover, but then cannot generate
        // midnight datetime, so jump to 1AM, otherwise reset.
        jsd.setHours(jsd.getHours() > 12 ? jsd.getHours() + 2 : 0);
        return jsd;
    },

    /** Create a new date from a standard (Gregorian) JavaScript Date.
        @memberof GregorianCalendar
        @param jsd {Date} The JavaScript date to convert.
        @return {CDate} The equivalent date. */
    fromJSDate: function(jsd) {
        return this.newDate(jsd.getFullYear(), jsd.getMonth() + 1, jsd.getDate());
    }
});

// Singleton manager
var _exports = module.exports = new Calendars();

// Date template
_exports.cdate = CDate;

// Base calendar template
_exports.baseCalendar = BaseCalendar;

// Gregorian calendar implementation
_exports.calendars.gregorian = GregorianCalendar;


},{"object-assign":443}],553:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Calendars extras for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) August 2009.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var assign = _dereq_('object-assign');
var main = _dereq_('./main');


assign(main.regionalOptions[''], {
    invalidArguments: 'Invalid arguments',
    invalidFormat: 'Cannot format a date from another calendar',
    missingNumberAt: 'Missing number at position {0}',
    unknownNameAt: 'Unknown name at position {0}',
    unexpectedLiteralAt: 'Unexpected literal at position {0}',
    unexpectedText: 'Additional text found at end'
});
main.local = main.regionalOptions[''];

assign(main.cdate.prototype, {

    /** Format this date.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof CDate
        @param [format] {string} The date format to use (see <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a>).
        @param [settings] {object} Options for the <code>formatDate</code> function.
        @return {string} The formatted date. */
    formatDate: function(format, settings) {
        if (typeof format !== 'string') {
            settings = format;
            format = '';
        }
        return this._calendar.formatDate(format || '', this, settings);
    }
});

assign(main.baseCalendar.prototype, {

    UNIX_EPOCH: main.instance().newDate(1970, 1, 1).toJD(),
    SECS_PER_DAY: 24 * 60 * 60,
    TICKS_EPOCH: main.instance().jdEpoch, // 1 January 0001 CE
    TICKS_PER_DAY: 24 * 60 * 60 * 10000000,

    /** Date form for ATOM (RFC 3339/ISO 8601).
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    ATOM: 'yyyy-mm-dd',
    /** Date form for cookies.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    COOKIE: 'D, dd M yyyy',
    /** Date form for full date.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    FULL: 'DD, MM d, yyyy',
    /** Date form for ISO 8601.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    ISO_8601: 'yyyy-mm-dd',
    /** Date form for Julian date.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    JULIAN: 'J',
    /** Date form for RFC 822.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    RFC_822: 'D, d M yy',
    /** Date form for RFC 850.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    RFC_850: 'DD, dd-M-yy',
    /** Date form for RFC 1036.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    RFC_1036: 'D, d M yy',
    /** Date form for RFC 1123.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    RFC_1123: 'D, d M yyyy',
    /** Date form for RFC 2822.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    RFC_2822: 'D, d M yyyy',
    /** Date form for RSS (RFC 822).
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    RSS: 'D, d M yy',
    /** Date form for Windows ticks.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    TICKS: '!',
    /** Date form for Unix timestamp.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    TIMESTAMP: '@',
    /** Date form for W3c (ISO 8601).
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    W3C: 'yyyy-mm-dd',

    /** Format a date object into a string value.
        The format can be combinations of the following:
        <ul>
        <li>d  - day of month (no leading zero)</li>
        <li>dd - day of month (two digit)</li>
        <li>o  - day of year (no leading zeros)</li>
        <li>oo - day of year (three digit)</li>
        <li>D  - day name short</li>
        <li>DD - day name long</li>
        <li>w  - week of year (no leading zero)</li>
        <li>ww - week of year (two digit)</li>
        <li>m  - month of year (no leading zero)</li>
        <li>mm - month of year (two digit)</li>
        <li>M  - month name short</li>
        <li>MM - month name long</li>
        <li>yy - year (two digit)</li>
        <li>yyyy - year (four digit)</li>
        <li>YYYY - formatted year</li>
        <li>J  - Julian date (days since January 1, 4713 BCE Greenwich noon)</li>
        <li>@  - Unix timestamp (s since 01/01/1970)</li>
        <li>!  - Windows ticks (100ns since 01/01/0001)</li>
        <li>'...' - literal text</li>
        <li>'' - single quote</li>
        </ul>
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar
        @param [format] {string} The desired format of the date (defaults to calendar format).
        @param date {CDate} The date value to format.
        @param [settings] {object} Addition options, whose attributes include:
        @property [dayNamesShort] {string[]} Abbreviated names of the days from Sunday.
        @property [dayNames] {string[]} Names of the days from Sunday.
        @property [monthNamesShort] {string[]} Abbreviated names of the months.
        @property [monthNames] {string[]} Names of the months.
        @property [calculateWeek] {CalendarsPickerCalculateWeek} Function that determines week of the year.
        @property [localNumbers=false] {boolean} <code>true</code> to localise numbers (if available),
                  <code>false</code> to use normal Arabic numerals.
        @return {string} The date in the above format.
        @throws Errors if the date is from a different calendar. */
    formatDate: function(format, date, settings) {
        if (typeof format !== 'string') {
            settings = date;
            date = format;
            format = '';
        }
        if (!date) {
            return '';
        }
        if (date.calendar() !== this) {
            throw main.local.invalidFormat || main.regionalOptions[''].invalidFormat;
        }
        format = format || this.local.dateFormat;
        settings = settings || {};
        var dayNamesShort = settings.dayNamesShort || this.local.dayNamesShort;
        var dayNames = settings.dayNames || this.local.dayNames;
        var monthNumbers = settings.monthNumbers || this.local.monthNumbers;
        var monthNamesShort = settings.monthNamesShort || this.local.monthNamesShort;
        var monthNames = settings.monthNames || this.local.monthNames;
        var calculateWeek = settings.calculateWeek || this.local.calculateWeek;
        // Check whether a format character is doubled
        var doubled = function(match, step) {
            var matches = 1;
            while (iFormat + matches < format.length && format.charAt(iFormat + matches) === match) {
                matches++;
            }
            iFormat += matches - 1;
            return Math.floor(matches / (step || 1)) > 1;
        };
        // Format a number, with leading zeroes if necessary
        var formatNumber = function(match, value, len, step) {
            var num = '' + value;
            if (doubled(match, step)) {
                while (num.length < len) {
                    num = '0' + num;
                }
            }
            return num;
        };
        // Format a name, short or long as requested
        var formatName = function(match, value, shortNames, longNames) {
            return (doubled(match) ? longNames[value] : shortNames[value]);
        };
        // Format month number
        // (e.g. Chinese calendar needs to account for intercalary months)
        var calendar = this;
        var formatMonth = function(date) {
            return (typeof monthNumbers === 'function') ?
                monthNumbers.call(calendar, date, doubled('m')) :
                localiseNumbers(formatNumber('m', date.month(), 2));
        };
        // Format a month name, short or long as requested
        var formatMonthName = function(date, useLongName) {
            if (useLongName) {
                return (typeof monthNames === 'function') ?
                    monthNames.call(calendar, date) :
                    monthNames[date.month() - calendar.minMonth];
            } else {
                return (typeof monthNamesShort === 'function') ?
                    monthNamesShort.call(calendar, date) :
                    monthNamesShort[date.month() - calendar.minMonth];
            }
        };
        // Localise numbers if requested and available
        var digits = this.local.digits;
        var localiseNumbers = function(value) {
            return (settings.localNumbers && digits ? digits(value) : value);
        };
        var output = '';
        var literal = false;
        for (var iFormat = 0; iFormat < format.length; iFormat++) {
            if (literal) {
                if (format.charAt(iFormat) === "'" && !doubled("'")) {
                    literal = false;
                }
                else {
                    output += format.charAt(iFormat);
                }
            }
            else {
                switch (format.charAt(iFormat)) {
                    case 'd': output += localiseNumbers(formatNumber('d', date.day(), 2)); break;
                    case 'D': output += formatName('D', date.dayOfWeek(),
                        dayNamesShort, dayNames); break;
                    case 'o': output += formatNumber('o', date.dayOfYear(), 3); break;
                    case 'w': output += formatNumber('w', date.weekOfYear(), 2); break;
                    case 'm': output += formatMonth(date); break;
                    case 'M': output += formatMonthName(date, doubled('M')); break;
                    case 'y':
                        output += (doubled('y', 2) ? date.year() :
                            (date.year() % 100 < 10 ? '0' : '') + date.year() % 100);
                        break;
                    case 'Y':
                        doubled('Y', 2);
                        output += date.formatYear();
                        break;
                    case 'J': output += date.toJD(); break;
                    case '@': output += (date.toJD() - this.UNIX_EPOCH) * this.SECS_PER_DAY; break;
                    case '!': output += (date.toJD() - this.TICKS_EPOCH) * this.TICKS_PER_DAY; break;
                    case "'":
                        if (doubled("'")) {
                            output += "'";
                        }
                        else {
                            literal = true;
                        }
                        break;
                    default:
                        output += format.charAt(iFormat);
                }
            }
        }
        return output;
    },

    /** Parse a string value into a date object.
        See <a href="#formatDate"><code>formatDate</code></a> for the possible formats, plus:
        <ul>
        <li>* - ignore rest of string</li>
        </ul>
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar
        @param format {string} The expected format of the date ('' for default calendar format).
        @param value {string} The date in the above format.
        @param [settings] {object} Additional options whose attributes include:
        @property [shortYearCutoff] {number} The cutoff year for determining the century.
        @property [dayNamesShort] {string[]} Abbreviated names of the days from Sunday.
        @property [dayNames] {string[]} Names of the days from Sunday.
        @property [monthNamesShort] {string[]} Abbreviated names of the months.
        @property [monthNames] {string[]} Names of the months.
        @return {CDate} The extracted date value or <code>null</code> if value is blank.
        @throws Errors if the format and/or value are missing,
                if the value doesn't match the format, or if the date is invalid. */
    parseDate: function(format, value, settings) {
        if (value == null) {
            throw main.local.invalidArguments || main.regionalOptions[''].invalidArguments;
        }
        value = (typeof value === 'object' ? value.toString() : value + '');
        if (value === '') {
            return null;
        }
        format = format || this.local.dateFormat;
        settings = settings || {};
        var shortYearCutoff = settings.shortYearCutoff || this.shortYearCutoff;
        shortYearCutoff = (typeof shortYearCutoff !== 'string' ? shortYearCutoff :
            this.today().year() % 100 + parseInt(shortYearCutoff, 10));
        var dayNamesShort = settings.dayNamesShort || this.local.dayNamesShort;
        var dayNames = settings.dayNames || this.local.dayNames;
        var parseMonth = settings.parseMonth || this.local.parseMonth;
        var monthNumbers = settings.monthNumbers || this.local.monthNumbers;
        var monthNamesShort = settings.monthNamesShort || this.local.monthNamesShort;
        var monthNames = settings.monthNames || this.local.monthNames;
        var jd = -1;
        var year = -1;
        var month = -1;
        var day = -1;
        var doy = -1;
        var shortYear = false;
        var literal = false;
        // Check whether a format character is doubled
        var doubled = function(match, step) {
            var matches = 1;
            while (iFormat + matches < format.length && format.charAt(iFormat + matches) === match) {
                matches++;
            }
            iFormat += matches - 1;
            return Math.floor(matches / (step || 1)) > 1;
        };
        // Extract a number from the string value
        var getNumber = function(match, step) {
            var isDoubled = doubled(match, step);
            var size = [2, 3, isDoubled ? 4 : 2, isDoubled ? 4 : 2, 10, 11, 20]['oyYJ@!'.indexOf(match) + 1];
            var digits = new RegExp('^-?\\d{1,' + size + '}');
            var num = value.substring(iValue).match(digits);
            if (!num) {
                throw (main.local.missingNumberAt || main.regionalOptions[''].missingNumberAt).
                    replace(/\{0\}/, iValue);
            }
            iValue += num[0].length;
            return parseInt(num[0], 10);
        };
        // Extract a month number from the string value
        var calendar = this;
        var getMonthNumber = function() {
            if (typeof monthNumbers === 'function') {
                doubled('m');  // update iFormat
                var month = monthNumbers.call(calendar, value.substring(iValue));
                iValue += month.length;
                return month;
            }

            return getNumber('m');
        };
        // Extract a name from the string value and convert to an index
        var getName = function(match, shortNames, longNames, step) {
            var names = (doubled(match, step) ? longNames : shortNames);
            for (var i = 0; i < names.length; i++) {
                if (value.substr(iValue, names[i].length).toLowerCase() === names[i].toLowerCase()) {
                    iValue += names[i].length;
                    return i + calendar.minMonth;
                }
            }
            throw (main.local.unknownNameAt || main.regionalOptions[''].unknownNameAt).
                replace(/\{0\}/, iValue);
        };
        // Extract a month number from the string value
        var getMonthName = function() {
            if (typeof monthNames === 'function') {
                var month = doubled('M') ?
                    monthNames.call(calendar, value.substring(iValue)) :
                    monthNamesShort.call(calendar, value.substring(iValue));
                iValue += month.length;
                return month;
            }

            return getName('M', monthNamesShort, monthNames);
        };
        // Confirm that a literal character matches the string value
        var checkLiteral = function() {
            if (value.charAt(iValue) !== format.charAt(iFormat)) {
                throw (main.local.unexpectedLiteralAt ||
                    main.regionalOptions[''].unexpectedLiteralAt).replace(/\{0\}/, iValue);
            }
            iValue++;
        };
        var iValue = 0;
        for (var iFormat = 0; iFormat < format.length; iFormat++) {
            if (literal) {
                if (format.charAt(iFormat) === "'" && !doubled("'")) {
                    literal = false;
                }
                else {
                    checkLiteral();
                }
            }
            else {
                switch (format.charAt(iFormat)) {
                    case 'd': day = getNumber('d'); break;
                    case 'D': getName('D', dayNamesShort, dayNames); break;
                    case 'o': doy = getNumber('o'); break;
                    case 'w': getNumber('w'); break;
                    case 'm': month = getMonthNumber(); break;
                    case 'M': month = getMonthName(); break;
                    case 'y':
                        var iSave = iFormat;
                        shortYear = !doubled('y', 2);
                        iFormat = iSave;
                        year = getNumber('y', 2);
                        break;
                    case 'Y': year = getNumber('Y', 2); break;
                    case 'J':
                        jd = getNumber('J') + 0.5;
                        if (value.charAt(iValue) === '.') {
                            iValue++;
                            getNumber('J');
                        }
                        break;
                    case '@': jd = getNumber('@') / this.SECS_PER_DAY + this.UNIX_EPOCH; break;
                    case '!': jd = getNumber('!') / this.TICKS_PER_DAY + this.TICKS_EPOCH; break;
                    case '*': iValue = value.length; break;
                    case "'":
                        if (doubled("'")) {
                            checkLiteral();
                        }
                        else {
                            literal = true;
                        }
                        break;
                    default: checkLiteral();
                }
            }
        }
        if (iValue < value.length) {
            throw main.local.unexpectedText || main.regionalOptions[''].unexpectedText;
        }
        if (year === -1) {
            year = this.today().year();
        }
        else if (year < 100 && shortYear) {
            year += (shortYearCutoff === -1 ? 1900 : this.today().year() -
                this.today().year() % 100 - (year <= shortYearCutoff ? 0 : 100));
        }
        if (typeof month === 'string') {
            month = parseMonth.call(this, year, month);
        }
        if (doy > -1) {
            month = 1;
            day = doy;
            for (var dim = this.daysInMonth(year, month); day > dim; dim = this.daysInMonth(year, month)) {
                month++;
                day -= dim;
            }
        }
        return (jd > -1 ? this.fromJD(jd) : this.newDate(year, month, day));
    },

    /** A date may be specified as an exact value or a relative one.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar
        @param dateSpec {CDate|number|string} The date as an object or string in the given format or
                an offset - numeric days from today, or string amounts and periods, e.g. '+1m +2w'.
        @param defaultDate {CDate} The date to use if no other supplied, may be <code>null</code>.
        @param currentDate {CDate} The current date as a possible basis for relative dates,
                if <code>null</code> today is used (optional)
        @param [dateFormat] {string} The expected date format - see <a href="#formatDate"><code>formatDate</code></a>.
        @param [settings] {object} Additional options whose attributes include:
        @property [shortYearCutoff] {number} The cutoff year for determining the century.
        @property [dayNamesShort] {string[]} Abbreviated names of the days from Sunday.
        @property [dayNames] {string[]} Names of the days from Sunday.
        @property [monthNamesShort] {string[]} Abbreviated names of the months.
        @property [monthNames] {string[]} Names of the months.
        @return {CDate} The decoded date. */
    determineDate: function(dateSpec, defaultDate, currentDate, dateFormat, settings) {
        if (currentDate && typeof currentDate !== 'object') {
            settings = dateFormat;
            dateFormat = currentDate;
            currentDate = null;
        }
        if (typeof dateFormat !== 'string') {
            settings = dateFormat;
            dateFormat = '';
        }
        var calendar = this;
        var offsetString = function(offset) {
            try {
                return calendar.parseDate(dateFormat, offset, settings);
            }
            catch (e) {
                // Ignore
            }
            offset = offset.toLowerCase();
            var date = (offset.match(/^c/) && currentDate ?
                currentDate.newDate() : null) || calendar.today();
            var pattern = /([+-]?[0-9]+)\s*(d|w|m|y)?/g;
            var matches = pattern.exec(offset);
            while (matches) {
                date.add(parseInt(matches[1], 10), matches[2] || 'd');
                matches = pattern.exec(offset);
            }
            return date;
        };
        defaultDate = (defaultDate ? defaultDate.newDate() : null);
        dateSpec = (dateSpec == null ? defaultDate :
            (typeof dateSpec === 'string' ? offsetString(dateSpec) : (typeof dateSpec === 'number' ?
            (isNaN(dateSpec) || dateSpec === Infinity || dateSpec === -Infinity ? defaultDate :
            calendar.today().add(dateSpec, 'd')) : calendar.newDate(dateSpec))));
        return dateSpec;
    }
});


},{"./main":552,"object-assign":443}],554:[function(_dereq_,module,exports){
module.exports = _dereq_('cwise-compiler')({
    args: ['array', {
        offset: [1],
        array: 0
    }, 'scalar', 'scalar', 'index'],
    pre: {
        "body": "{}",
        "args": [],
        "thisVars": [],
        "localVars": []
    },
    post: {
        "body": "{}",
        "args": [],
        "thisVars": [],
        "localVars": []
    },
    body: {
        "body": "{\n        var _inline_1_da = _inline_1_arg0_ - _inline_1_arg3_\n        var _inline_1_db = _inline_1_arg1_ - _inline_1_arg3_\n        if((_inline_1_da >= 0) !== (_inline_1_db >= 0)) {\n          _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n        }\n      }",
        "args": [{
            "name": "_inline_1_arg0_",
            "lvalue": false,
            "rvalue": true,
            "count": 1
        }, {
            "name": "_inline_1_arg1_",
            "lvalue": false,
            "rvalue": true,
            "count": 1
        }, {
            "name": "_inline_1_arg2_",
            "lvalue": false,
            "rvalue": true,
            "count": 1
        }, {
            "name": "_inline_1_arg3_",
            "lvalue": false,
            "rvalue": true,
            "count": 2
        }, {
            "name": "_inline_1_arg4_",
            "lvalue": false,
            "rvalue": true,
            "count": 1
        }],
        "thisVars": [],
        "localVars": ["_inline_1_da", "_inline_1_db"]
    },
    funcName: 'zeroCrossings'
})

},{"cwise-compiler":134}],555:[function(_dereq_,module,exports){
"use strict"

module.exports = findZeroCrossings

var core = _dereq_("./lib/zc-core")

function findZeroCrossings(array, level) {
  var cross = []
  level = +level || 0.0
  core(array.hi(array.shape[0]-1), cross, level)
  return cross
}
},{"./lib/zc-core":554}],556:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * All paths are tuned for maximum scalability of the arrowhead,
 * ie throughout arrowwidth=0.3..3 the head is joined smoothly
 * to the line, with the line coming from the left and ending at (0, 0).
 *
 * `backoff` is the distance to move the arrowhead and the end of the line,
 * in order that the arrowhead points to the desired place, either at
 * the tip of the arrow or (in the case of circle or square)
 * the center of the symbol.
 *
 * `noRotate`, if truthy, says that this arrowhead should not rotate with the
 * arrow. That's the case for squares, which should always be straight, and
 * circles, for which it's irrelevant.
 */

module.exports = [
    // no arrow
    {
        path: '',
        backoff: 0
    },
    // wide with flat back
    {
        path: 'M-2.4,-3V3L0.6,0Z',
        backoff: 0.6
    },
    // narrower with flat back
    {
        path: 'M-3.7,-2.5V2.5L1.3,0Z',
        backoff: 1.3
    },
    // barbed
    {
        path: 'M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z',
        backoff: 1.55
    },
    // wide line-drawn
    {
        path: 'M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z',
        backoff: 1.6
    },
    // narrower line-drawn
    {
        path: 'M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z',
        backoff: 2
    },
    // circle
    {
        path: 'M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z',
        backoff: 0,
        noRotate: true
    },
    // square
    {
        path: 'M2,2V-2H-2V2Z',
        backoff: 0,
        noRotate: true
    }
];

},{}],557:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var ARROWPATHS = _dereq_('./arrow_paths');
var fontAttrs = _dereq_('../../plots/font_attributes');
var cartesianConstants = _dereq_('../../plots/cartesian/constants');
var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;


module.exports = templatedArray('annotation', {
    visible: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'calc+arraydraw',
        
    },

    text: {
        valType: 'string',
        
        editType: 'calc+arraydraw',
        
    },
    textangle: {
        valType: 'angle',
        dflt: 0,
        
        editType: 'calc+arraydraw',
        
    },
    font: fontAttrs({
        editType: 'calc+arraydraw',
        colorEditType: 'arraydraw',
        
    }),
    width: {
        valType: 'number',
        min: 1,
        dflt: null,
        
        editType: 'calc+arraydraw',
        
    },
    height: {
        valType: 'number',
        min: 1,
        dflt: null,
        
        editType: 'calc+arraydraw',
        
    },
    opacity: {
        valType: 'number',
        min: 0,
        max: 1,
        dflt: 1,
        
        editType: 'arraydraw',
        
    },
    align: {
        valType: 'enumerated',
        values: ['left', 'center', 'right'],
        dflt: 'center',
        
        editType: 'arraydraw',
        
    },
    valign: {
        valType: 'enumerated',
        values: ['top', 'middle', 'bottom'],
        dflt: 'middle',
        
        editType: 'arraydraw',
        
    },
    bgcolor: {
        valType: 'color',
        dflt: 'rgba(0,0,0,0)',
        
        editType: 'arraydraw',
        
    },
    bordercolor: {
        valType: 'color',
        dflt: 'rgba(0,0,0,0)',
        
        editType: 'arraydraw',
        
    },
    borderpad: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'calc+arraydraw',
        
    },
    borderwidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'calc+arraydraw',
        
    },
    // arrow
    showarrow: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'calc+arraydraw',
        
    },
    arrowcolor: {
        valType: 'color',
        
        editType: 'arraydraw',
        
    },
    arrowhead: {
        valType: 'integer',
        min: 0,
        max: ARROWPATHS.length,
        dflt: 1,
        
        editType: 'arraydraw',
        
    },
    startarrowhead: {
        valType: 'integer',
        min: 0,
        max: ARROWPATHS.length,
        dflt: 1,
        
        editType: 'arraydraw',
        
    },
    arrowside: {
        valType: 'flaglist',
        flags: ['end', 'start'],
        extras: ['none'],
        dflt: 'end',
        
        editType: 'arraydraw',
        
    },
    arrowsize: {
        valType: 'number',
        min: 0.3,
        dflt: 1,
        
        editType: 'calc+arraydraw',
        
    },
    startarrowsize: {
        valType: 'number',
        min: 0.3,
        dflt: 1,
        
        editType: 'calc+arraydraw',
        
    },
    arrowwidth: {
        valType: 'number',
        min: 0.1,
        
        editType: 'calc+arraydraw',
        
    },
    standoff: {
        valType: 'number',
        min: 0,
        dflt: 0,
        
        editType: 'calc+arraydraw',
        
    },
    startstandoff: {
        valType: 'number',
        min: 0,
        dflt: 0,
        
        editType: 'calc+arraydraw',
        
    },
    ax: {
        valType: 'any',
        
        editType: 'calc+arraydraw',
        
    },
    ay: {
        valType: 'any',
        
        editType: 'calc+arraydraw',
        
    },
    axref: {
        valType: 'enumerated',
        dflt: 'pixel',
        values: [
            'pixel',
            cartesianConstants.idRegex.x.toString()
        ],
        
        editType: 'calc',
        
    },
    ayref: {
        valType: 'enumerated',
        dflt: 'pixel',
        values: [
            'pixel',
            cartesianConstants.idRegex.y.toString()
        ],
        
        editType: 'calc',
        
    },
    // positioning
    xref: {
        valType: 'enumerated',
        values: [
            'paper',
            cartesianConstants.idRegex.x.toString()
        ],
        
        editType: 'calc',
        
    },
    x: {
        valType: 'any',
        
        editType: 'calc+arraydraw',
        
    },
    xanchor: {
        valType: 'enumerated',
        values: ['auto', 'left', 'center', 'right'],
        dflt: 'auto',
        
        editType: 'calc+arraydraw',
        
    },
    xshift: {
        valType: 'number',
        dflt: 0,
        
        editType: 'calc+arraydraw',
        
    },
    yref: {
        valType: 'enumerated',
        values: [
            'paper',
            cartesianConstants.idRegex.y.toString()
        ],
        
        editType: 'calc',
        
    },
    y: {
        valType: 'any',
        
        editType: 'calc+arraydraw',
        
    },
    yanchor: {
        valType: 'enumerated',
        values: ['auto', 'top', 'middle', 'bottom'],
        dflt: 'auto',
        
        editType: 'calc+arraydraw',
        
    },
    yshift: {
        valType: 'number',
        dflt: 0,
        
        editType: 'calc+arraydraw',
        
    },
    clicktoshow: {
        valType: 'enumerated',
        values: [false, 'onoff', 'onout'],
        dflt: false,
        
        editType: 'arraydraw',
        
    },
    xclick: {
        valType: 'any',
        
        editType: 'arraydraw',
        
    },
    yclick: {
        valType: 'any',
        
        editType: 'arraydraw',
        
    },
    hovertext: {
        valType: 'string',
        
        editType: 'arraydraw',
        
    },
    hoverlabel: {
        bgcolor: {
            valType: 'color',
            
            editType: 'arraydraw',
            
        },
        bordercolor: {
            valType: 'color',
            
            editType: 'arraydraw',
            
        },
        font: fontAttrs({
            editType: 'arraydraw',
            
        }),
        editType: 'arraydraw'
    },
    captureevents: {
        valType: 'boolean',
        
        editType: 'arraydraw',
        
    },
    editType: 'calc',

    _deprecated: {
        ref: {
            valType: 'string',
            
            editType: 'calc',
            
        }
    }
});

},{"../../plot_api/plot_template":735,"../../plots/cartesian/constants":751,"../../plots/font_attributes":771,"./arrow_paths":556}],558:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');

var draw = _dereq_('./draw').draw;


module.exports = function calcAutorange(gd) {
    var fullLayout = gd._fullLayout;
    var annotationList = Lib.filterVisible(fullLayout.annotations);

    if(annotationList.length && gd._fullData.length) {
        return Lib.syncOrAsync([draw, annAutorange], gd);
    }
};

function annAutorange(gd) {
    var fullLayout = gd._fullLayout;

    // find the bounding boxes for each of these annotations'
    // relative to their anchor points
    // use the arrow and the text bg rectangle,
    // as the whole anno may include hidden text in its bbox
    Lib.filterVisible(fullLayout.annotations).forEach(function(ann) {
        var xa = Axes.getFromId(gd, ann.xref);
        var ya = Axes.getFromId(gd, ann.yref);

        ann._extremes = {};
        if(xa) calcAxisExpansion(ann, xa);
        if(ya) calcAxisExpansion(ann, ya);
    });
}

function calcAxisExpansion(ann, ax) {
    var axId = ax._id;
    var letter = axId.charAt(0);
    var pos = ann[letter];
    var apos = ann['a' + letter];
    var ref = ann[letter + 'ref'];
    var aref = ann['a' + letter + 'ref'];
    var padplus = ann['_' + letter + 'padplus'];
    var padminus = ann['_' + letter + 'padminus'];
    var shift = {x: 1, y: -1}[letter] * ann[letter + 'shift'];
    var headSize = 3 * ann.arrowsize * ann.arrowwidth || 0;
    var headPlus = headSize + shift;
    var headMinus = headSize - shift;
    var startHeadSize = 3 * ann.startarrowsize * ann.arrowwidth || 0;
    var startHeadPlus = startHeadSize + shift;
    var startHeadMinus = startHeadSize - shift;
    var extremes;

    if(aref === ref) {
        // expand for the arrowhead (padded by arrowhead)
        var extremeArrowHead = Axes.findExtremes(ax, [ax.r2c(pos)], {
            ppadplus: headPlus,
            ppadminus: headMinus
        });
        // again for the textbox (padded by textbox)
        var extremeText = Axes.findExtremes(ax, [ax.r2c(apos)], {
            ppadplus: Math.max(padplus, startHeadPlus),
            ppadminus: Math.max(padminus, startHeadMinus)
        });
        extremes = {
            min: [extremeArrowHead.min[0], extremeText.min[0]],
            max: [extremeArrowHead.max[0], extremeText.max[0]]
        };
    } else {
        startHeadPlus = apos ? startHeadPlus + apos : startHeadPlus;
        startHeadMinus = apos ? startHeadMinus - apos : startHeadMinus;
        extremes = Axes.findExtremes(ax, [ax.r2c(pos)], {
            ppadplus: Math.max(padplus, headPlus, startHeadPlus),
            ppadminus: Math.max(padminus, headMinus, startHeadMinus)
        });
    }

    ann._extremes[axId] = extremes;
}

},{"../../lib":697,"../../plots/cartesian/axes":745,"./draw":563}],559:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Registry = _dereq_('../../registry');
var arrayEditor = _dereq_('../../plot_api/plot_template').arrayEditor;

module.exports = {
    hasClickToShow: hasClickToShow,
    onClick: onClick
};

/*
 * hasClickToShow: does the given hoverData have ANY annotations which will
 * turn ON if we click here? (used by hover events to set cursor)
 *
 * gd: graphDiv
 * hoverData: a hoverData array, as included with the *plotly_hover* or
 *     *plotly_click* events in the `points` attribute
 *
 * returns: boolean
 */
function hasClickToShow(gd, hoverData) {
    var sets = getToggleSets(gd, hoverData);
    return sets.on.length > 0 || sets.explicitOff.length > 0;
}

/*
 * onClick: perform the toggling (via Plotly.update) implied by clicking
 * at this hoverData
 *
 * gd: graphDiv
 * hoverData: a hoverData array, as included with the *plotly_hover* or
 *     *plotly_click* events in the `points` attribute
 *
 * returns: Promise that the update is complete
 */
function onClick(gd, hoverData) {
    var toggleSets = getToggleSets(gd, hoverData);
    var onSet = toggleSets.on;
    var offSet = toggleSets.off.concat(toggleSets.explicitOff);
    var update = {};
    var annotationsOut = gd._fullLayout.annotations;
    var i, editHelpers;

    if(!(onSet.length || offSet.length)) return;

    for(i = 0; i < onSet.length; i++) {
        editHelpers = arrayEditor(gd.layout, 'annotations', annotationsOut[onSet[i]]);
        editHelpers.modifyItem('visible', true);
        Lib.extendFlat(update, editHelpers.getUpdateObj());
    }

    for(i = 0; i < offSet.length; i++) {
        editHelpers = arrayEditor(gd.layout, 'annotations', annotationsOut[offSet[i]]);
        editHelpers.modifyItem('visible', false);
        Lib.extendFlat(update, editHelpers.getUpdateObj());
    }

    return Registry.call('update', gd, {}, update);
}

/*
 * getToggleSets: find the annotations which will turn on or off at this
 * hoverData
 *
 * gd: graphDiv
 * hoverData: a hoverData array, as included with the *plotly_hover* or
 *     *plotly_click* events in the `points` attribute
 *
 * returns: {
 *   on: Array (indices of annotations to turn on),
 *   off: Array (indices to turn off because you're not hovering on them),
 *   explicitOff: Array (indices to turn off because you *are* hovering on them)
 * }
 */
function getToggleSets(gd, hoverData) {
    var annotations = gd._fullLayout.annotations;
    var onSet = [];
    var offSet = [];
    var explicitOffSet = [];
    var hoverLen = (hoverData || []).length;

    var i, j, anni, showMode, pointj, xa, ya, toggleType;

    for(i = 0; i < annotations.length; i++) {
        anni = annotations[i];
        showMode = anni.clicktoshow;

        if(showMode) {
            for(j = 0; j < hoverLen; j++) {
                pointj = hoverData[j];
                xa = pointj.xaxis;
                ya = pointj.yaxis;

                if(xa._id === anni.xref &&
                    ya._id === anni.yref &&
                    xa.d2r(pointj.x) === clickData2r(anni._xclick, xa) &&
                    ya.d2r(pointj.y) === clickData2r(anni._yclick, ya)
                ) {
                    // match! toggle this annotation
                    // regardless of its clicktoshow mode
                    // but if it's onout mode, off is implicit
                    if(anni.visible) {
                        if(showMode === 'onout') toggleType = offSet;
                        else toggleType = explicitOffSet;
                    }
                    else {
                        toggleType = onSet;
                    }
                    toggleType.push(i);
                    break;
                }
            }

            if(j === hoverLen) {
                // no match - only turn this annotation OFF, and only if
                // showmode is 'onout'
                if(anni.visible && showMode === 'onout') offSet.push(i);
            }
        }
    }

    return {on: onSet, off: offSet, explicitOff: explicitOffSet};
}

// to handle log axes until v2
function clickData2r(d, ax) {
    return ax.type === 'log' ? ax.l2r(d) : ax.d2r(d);
}

},{"../../lib":697,"../../plot_api/plot_template":735,"../../registry":826}],560:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Color = _dereq_('../color');

// defaults common to 'annotations' and 'annotations3d'
module.exports = function handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce) {
    coerce('opacity');
    var bgColor = coerce('bgcolor');

    var borderColor = coerce('bordercolor');
    var borderOpacity = Color.opacity(borderColor);

    coerce('borderpad');

    var borderWidth = coerce('borderwidth');
    var showArrow = coerce('showarrow');

    coerce('text', showArrow ? ' ' : fullLayout._dfltTitle.annotation);
    coerce('textangle');
    Lib.coerceFont(coerce, 'font', fullLayout.font);

    coerce('width');
    coerce('align');

    var h = coerce('height');
    if(h) coerce('valign');

    if(showArrow) {
        var arrowside = coerce('arrowside');
        var arrowhead;
        var arrowsize;

        if(arrowside.indexOf('end') !== -1) {
            arrowhead = coerce('arrowhead');
            arrowsize = coerce('arrowsize');
        }

        if(arrowside.indexOf('start') !== -1) {
            coerce('startarrowhead', arrowhead);
            coerce('startarrowsize', arrowsize);
        }
        coerce('arrowcolor', borderOpacity ? annOut.bordercolor : Color.defaultLine);
        coerce('arrowwidth', ((borderOpacity && borderWidth) || 1) * 2);
        coerce('standoff');
        coerce('startstandoff');

    }

    var hoverText = coerce('hovertext');
    var globalHoverLabel = fullLayout.hoverlabel || {};

    if(hoverText) {
        var hoverBG = coerce('hoverlabel.bgcolor', globalHoverLabel.bgcolor ||
            (Color.opacity(bgColor) ? Color.rgb(bgColor) : Color.defaultLine)
        );

        var hoverBorder = coerce('hoverlabel.bordercolor', globalHoverLabel.bordercolor ||
            Color.contrast(hoverBG)
        );

        Lib.coerceFont(coerce, 'hoverlabel.font', {
            family: globalHoverLabel.font.family,
            size: globalHoverLabel.font.size,
            color: globalHoverLabel.font.color || hoverBorder
        });
    }

    coerce('captureevents', !!hoverText);
};

},{"../../lib":697,"../color":574}],561:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var toLogRange = _dereq_('../../lib/to_log_range');

/*
 * convertCoords: when converting an axis between log and linear
 * you need to alter any annotations on that axis to keep them
 * pointing at the same data point.
 * In v2.0 this will become obsolete
 *
 * gd: the plot div
 * ax: the axis being changed
 * newType: the type it's getting
 * doExtra: function(attr, val) from inside relayout that sets the attribute.
 *     Use this to make the changes as it's aware if any other changes in the
 *     same relayout call should override this conversion.
 */
module.exports = function convertCoords(gd, ax, newType, doExtra) {
    ax = ax || {};

    var toLog = (newType === 'log') && (ax.type === 'linear');
    var fromLog = (newType === 'linear') && (ax.type === 'log');

    if(!(toLog || fromLog)) return;

    var annotations = gd._fullLayout.annotations;
    var axLetter = ax._id.charAt(0);
    var ann;
    var attrPrefix;

    function convert(attr) {
        var currentVal = ann[attr];
        var newVal = null;

        if(toLog) newVal = toLogRange(currentVal, ax.range);
        else newVal = Math.pow(10, currentVal);

        // if conversion failed, delete the value so it gets a default value
        if(!isNumeric(newVal)) newVal = null;

        doExtra(attrPrefix + attr, newVal);
    }

    for(var i = 0; i < annotations.length; i++) {
        ann = annotations[i];
        attrPrefix = 'annotations[' + i + '].';

        if(ann[axLetter + 'ref'] === ax._id) convert(axLetter);
        if(ann['a' + axLetter + 'ref'] === ax._id) convert('a' + axLetter);
    }
};

},{"../../lib/to_log_range":723,"fast-isnumeric":218}],562:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');
var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');

var handleAnnotationCommonDefaults = _dereq_('./common_defaults');
var attributes = _dereq_('./attributes');


module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
    handleArrayContainerDefaults(layoutIn, layoutOut, {
        name: 'annotations',
        handleItemDefaults: handleAnnotationDefaults
    });
};

function handleAnnotationDefaults(annIn, annOut, fullLayout) {
    function coerce(attr, dflt) {
        return Lib.coerce(annIn, annOut, attributes, attr, dflt);
    }

    var visible = coerce('visible');
    var clickToShow = coerce('clicktoshow');

    if(!(visible || clickToShow)) return;

    handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce);

    var showArrow = annOut.showarrow;

    // positioning
    var axLetters = ['x', 'y'];
    var arrowPosDflt = [-10, -30];
    var gdMock = {_fullLayout: fullLayout};

    for(var i = 0; i < 2; i++) {
        var axLetter = axLetters[i];

        // xref, yref
        var axRef = Axes.coerceRef(annIn, annOut, gdMock, axLetter, '', 'paper');

        if(axRef !== 'paper') {
            var ax = Axes.getFromId(gdMock, axRef);
            ax._annIndices.push(annOut._index);
        }

        // x, y
        Axes.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5);

        if(showArrow) {
            var arrowPosAttr = 'a' + axLetter;
            // axref, ayref
            var aaxRef = Axes.coerceRef(annIn, annOut, gdMock, arrowPosAttr, 'pixel');

            // for now the arrow can only be on the same axis or specified as pixels
            // TODO: sometime it might be interesting to allow it to be on *any* axis
            // but that would require updates to drawing & autorange code and maybe more
            if(aaxRef !== 'pixel' && aaxRef !== axRef) {
                aaxRef = annOut[arrowPosAttr] = 'pixel';
            }

            // ax, ay
            var aDflt = (aaxRef === 'pixel') ? arrowPosDflt[i] : 0.4;
            Axes.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt);
        }

        // xanchor, yanchor
        coerce(axLetter + 'anchor');

        // xshift, yshift
        coerce(axLetter + 'shift');
    }

    // if you have one coordinate you should have both
    Lib.noneOrAll(annIn, annOut, ['x', 'y']);

    // if you have one part of arrow length you should have both
    if(showArrow) {
        Lib.noneOrAll(annIn, annOut, ['ax', 'ay']);
    }

    if(clickToShow) {
        var xClick = coerce('xclick');
        var yClick = coerce('yclick');

        // put the actual click data to bind to into private attributes
        // so we don't have to do this little bit of logic on every hover event
        annOut._xclick = (xClick === undefined) ?
            annOut.x :
            Axes.cleanPosition(xClick, gdMock, annOut.xref);
        annOut._yclick = (yClick === undefined) ?
            annOut.y :
            Axes.cleanPosition(yClick, gdMock, annOut.yref);
    }
}

},{"../../lib":697,"../../plots/array_container_defaults":741,"../../plots/cartesian/axes":745,"./attributes":557,"./common_defaults":560}],563:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Registry = _dereq_('../../registry');
var Plots = _dereq_('../../plots/plots');
var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');
var Color = _dereq_('../color');
var Drawing = _dereq_('../drawing');
var Fx = _dereq_('../fx');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var setCursor = _dereq_('../../lib/setcursor');
var dragElement = _dereq_('../dragelement');
var arrayEditor = _dereq_('../../plot_api/plot_template').arrayEditor;

var drawArrowHead = _dereq_('./draw_arrow_head');

// Annotations are stored in gd.layout.annotations, an array of objects
// index can point to one item in this array,
//  or non-numeric to simply add a new one
//  or -1 to modify all existing
// opt can be the full options object, or one key (to be set to value)
//  or undefined to simply redraw
// if opt is blank, val can be 'add' or a full options object to add a new
//  annotation at that point in the array, or 'remove' to delete this one

module.exports = {
    draw: draw,
    drawOne: drawOne,
    drawRaw: drawRaw
};

/*
 * draw: draw all annotations without any new modifications
 */
function draw(gd) {
    var fullLayout = gd._fullLayout;

    fullLayout._infolayer.selectAll('.annotation').remove();

    for(var i = 0; i < fullLayout.annotations.length; i++) {
        if(fullLayout.annotations[i].visible) {
            drawOne(gd, i);
        }
    }

    return Plots.previousPromises(gd);
}

/*
 * drawOne: draw a single cartesian or paper-ref annotation, potentially with modifications
 *
 * index (int): the annotation to draw
 */
function drawOne(gd, index) {
    var fullLayout = gd._fullLayout;
    var options = fullLayout.annotations[index] || {};
    var xa = Axes.getFromId(gd, options.xref);
    var ya = Axes.getFromId(gd, options.yref);

    if(xa) xa.setScale();
    if(ya) ya.setScale();

    drawRaw(gd, options, index, false, xa, ya);
}

/**
 * drawRaw: draw a single annotation, potentially with modifications
 *
 * @param {DOM element} gd
 * @param {object} options : this annotation's fullLayout options
 * @param {integer} index : index in 'annotations' container of the annotation to draw
 * @param {string} subplotId : id of the annotation's subplot
 *  - use false for 2d (i.e. cartesian or paper-ref) annotations
 * @param {object | undefined} xa : full x-axis object to compute subplot pos-to-px
 * @param {object | undefined} ya : ... y-axis
 */
function drawRaw(gd, options, index, subplotId, xa, ya) {
    var fullLayout = gd._fullLayout;
    var gs = gd._fullLayout._size;
    var edits = gd._context.edits;

    var className, containerStr;

    if(subplotId) {
        className = 'annotation-' + subplotId;
        containerStr = subplotId + '.annotations';
    } else {
        className = 'annotation';
        containerStr = 'annotations';
    }

    var editHelpers = arrayEditor(gd.layout, containerStr, options);
    var modifyBase = editHelpers.modifyBase;
    var modifyItem = editHelpers.modifyItem;
    var getUpdateObj = editHelpers.getUpdateObj;

    // remove the existing annotation if there is one
    fullLayout._infolayer
        .selectAll('.' + className + '[data-index="' + index + '"]')
        .remove();

    var annClipID = 'clip' + fullLayout._uid + '_ann' + index;

    // this annotation is gone - quit now after deleting it
    // TODO: use d3 idioms instead of deleting and redrawing every time
    if(!options._input || options.visible === false) {
        d3.selectAll('#' + annClipID).remove();
        return;
    }

    // calculated pixel positions
    // x & y each will get text, head, and tail as appropriate
    var annPosPx = {x: {}, y: {}};
    var textangle = +options.textangle || 0;

    // create the components
    // made a single group to contain all, so opacity can work right
    // with border/arrow together this could handle a whole bunch of
    // cleanup at this point, but works for now
    var annGroup = fullLayout._infolayer.append('g')
        .classed(className, true)
        .attr('data-index', String(index))
        .style('opacity', options.opacity);

    // another group for text+background so that they can rotate together
    var annTextGroup = annGroup.append('g')
        .classed('annotation-text-g', true);

    var editTextPosition = edits[options.showarrow ? 'annotationTail' : 'annotationPosition'];
    var textEvents = options.captureevents || edits.annotationText || editTextPosition;

    var annTextGroupInner = annTextGroup.append('g')
        .style('pointer-events', textEvents ? 'all' : null)
        .call(setCursor, 'pointer')
        .on('click', function() {
            gd._dragging = false;

            var eventData = {
                index: index,
                annotation: options._input,
                fullAnnotation: options,
                event: d3.event
            };

            if(subplotId) {
                eventData.subplotId = subplotId;
            }

            gd.emit('plotly_clickannotation', eventData);
        });

    if(options.hovertext) {
        annTextGroupInner
        .on('mouseover', function() {
            var hoverOptions = options.hoverlabel;
            var hoverFont = hoverOptions.font;
            var bBox = this.getBoundingClientRect();
            var bBoxRef = gd.getBoundingClientRect();

            Fx.loneHover({
                x0: bBox.left - bBoxRef.left,
                x1: bBox.right - bBoxRef.left,
                y: (bBox.top + bBox.bottom) / 2 - bBoxRef.top,
                text: options.hovertext,
                color: hoverOptions.bgcolor,
                borderColor: hoverOptions.bordercolor,
                fontFamily: hoverFont.family,
                fontSize: hoverFont.size,
                fontColor: hoverFont.color
            }, {
                container: fullLayout._hoverlayer.node(),
                outerContainer: fullLayout._paper.node(),
                gd: gd
            });
        })
        .on('mouseout', function() {
            Fx.loneUnhover(fullLayout._hoverlayer.node());
        });
    }

    var borderwidth = options.borderwidth;
    var borderpad = options.borderpad;
    var borderfull = borderwidth + borderpad;

    var annTextBG = annTextGroupInner.append('rect')
        .attr('class', 'bg')
        .style('stroke-width', borderwidth + 'px')
        .call(Color.stroke, options.bordercolor)
        .call(Color.fill, options.bgcolor);

    var isSizeConstrained = options.width || options.height;

    var annTextClip = fullLayout._topclips
        .selectAll('#' + annClipID)
        .data(isSizeConstrained ? [0] : []);

    annTextClip.enter().append('clipPath')
        .classed('annclip', true)
        .attr('id', annClipID)
      .append('rect');
    annTextClip.exit().remove();

    var font = options.font;

    var text = fullLayout.meta ?
        Lib.templateString(options.text, {meta: fullLayout.meta}) :
        options.text;

    var annText = annTextGroupInner.append('text')
        .classed('annotation-text', true)
        .text(text);

    function textLayout(s) {
        s.call(Drawing.font, font)
        .attr({
            'text-anchor': {
                left: 'start',
                right: 'end'
            }[options.align] || 'middle'
        });

        svgTextUtils.convertToTspans(s, gd, drawGraphicalElements);
        return s;
    }

    function drawGraphicalElements() {
        // if the text has *only* a link, make the whole box into a link
        var anchor3 = annText.selectAll('a');
        if(anchor3.size() === 1 && anchor3.text() === annText.text()) {
            var wholeLink = annTextGroupInner.insert('a', ':first-child').attr({
                'xlink:xlink:href': anchor3.attr('xlink:href'),
                'xlink:xlink:show': anchor3.attr('xlink:show')
            })
            .style({cursor: 'pointer'});

            wholeLink.node().appendChild(annTextBG.node());
        }

        var mathjaxGroup = annTextGroupInner.select('.annotation-text-math-group');
        var hasMathjax = !mathjaxGroup.empty();
        var anntextBB = Drawing.bBox(
                (hasMathjax ? mathjaxGroup : annText).node());
        var textWidth = anntextBB.width;
        var textHeight = anntextBB.height;
        var annWidth = options.width || textWidth;
        var annHeight = options.height || textHeight;
        var outerWidth = Math.round(annWidth + 2 * borderfull);
        var outerHeight = Math.round(annHeight + 2 * borderfull);

        function shiftFraction(v, anchor) {
            if(anchor === 'auto') {
                if(v < 1 / 3) anchor = 'left';
                else if(v > 2 / 3) anchor = 'right';
                else anchor = 'center';
            }
            return {
                center: 0,
                middle: 0,
                left: 0.5,
                bottom: -0.5,
                right: -0.5,
                top: 0.5
            }[anchor];
        }

        var annotationIsOffscreen = false;
        var letters = ['x', 'y'];

        for(var i = 0; i < letters.length; i++) {
            var axLetter = letters[i];
            var axRef = options[axLetter + 'ref'] || axLetter;
            var tailRef = options['a' + axLetter + 'ref'];
            var ax = {x: xa, y: ya}[axLetter];
            var dimAngle = (textangle + (axLetter === 'x' ? 0 : -90)) * Math.PI / 180;
            // note that these two can be either positive or negative
            var annSizeFromWidth = outerWidth * Math.cos(dimAngle);
            var annSizeFromHeight = outerHeight * Math.sin(dimAngle);
            // but this one is the positive total size
            var annSize = Math.abs(annSizeFromWidth) + Math.abs(annSizeFromHeight);
            var anchor = options[axLetter + 'anchor'];
            var overallShift = options[axLetter + 'shift'] * (axLetter === 'x' ? 1 : -1);
            var posPx = annPosPx[axLetter];
            var basePx;
            var textPadShift;
            var alignPosition;
            var autoAlignFraction;
            var textShift;

            /*
             * calculate the *primary* pixel position
             * which is the arrowhead if there is one,
             * otherwise the text anchor point
             */
            if(ax) {
                // check if annotation is off screen, to bypass DOM manipulations
                var posFraction = ax.r2fraction(options[axLetter]);
                if(posFraction < 0 || posFraction > 1) {
                    if(tailRef === axRef) {
                        posFraction = ax.r2fraction(options['a' + axLetter]);
                        if(posFraction < 0 || posFraction > 1) {
                            annotationIsOffscreen = true;
                        }
                    } else {
                        annotationIsOffscreen = true;
                    }
                }
                basePx = ax._offset + ax.r2p(options[axLetter]);
                autoAlignFraction = 0.5;
            }
            else {
                if(axLetter === 'x') {
                    alignPosition = options[axLetter];
                    basePx = gs.l + gs.w * alignPosition;
                }
                else {
                    alignPosition = 1 - options[axLetter];
                    basePx = gs.t + gs.h * alignPosition;
                }
                autoAlignFraction = options.showarrow ? 0.5 : alignPosition;
            }

            // now translate this into pixel positions of head, tail, and text
            // as well as paddings for autorange
            if(options.showarrow) {
                posPx.head = basePx;

                var arrowLength = options['a' + axLetter];

                // with an arrow, the text rotates around the anchor point
                textShift = annSizeFromWidth * shiftFraction(0.5, options.xanchor) -
                    annSizeFromHeight * shiftFraction(0.5, options.yanchor);

                if(tailRef === axRef) {
                    posPx.tail = ax._offset + ax.r2p(arrowLength);
                    // tail is data-referenced: autorange pads the text in px from the tail
                    textPadShift = textShift;
                }
                else {
                    posPx.tail = basePx + arrowLength;
                    // tail is specified in px from head, so autorange also pads vs head
                    textPadShift = textShift + arrowLength;
                }

                posPx.text = posPx.tail + textShift;

                // constrain pixel/paper referenced so the draggers are at least
                // partially visible
                var maxPx = fullLayout[(axLetter === 'x') ? 'width' : 'height'];
                if(axRef === 'paper') {
                    posPx.head = Lib.constrain(posPx.head, 1, maxPx - 1);
                }
                if(tailRef === 'pixel') {
                    var shiftPlus = -Math.max(posPx.tail - 3, posPx.text);
                    var shiftMinus = Math.min(posPx.tail + 3, posPx.text) - maxPx;
                    if(shiftPlus > 0) {
                        posPx.tail += shiftPlus;
                        posPx.text += shiftPlus;
                    }
                    else if(shiftMinus > 0) {
                        posPx.tail -= shiftMinus;
                        posPx.text -= shiftMinus;
                    }
                }

                posPx.tail += overallShift;
                posPx.head += overallShift;
            }
            else {
                // with no arrow, the text rotates and *then* we put the anchor
                // relative to the new bounding box
                textShift = annSize * shiftFraction(autoAlignFraction, anchor);
                textPadShift = textShift;
                posPx.text = basePx + textShift;
            }

            posPx.text += overallShift;
            textShift += overallShift;
            textPadShift += overallShift;

            // padplus/minus are used by autorange
            options['_' + axLetter + 'padplus'] = (annSize / 2) + textPadShift;
            options['_' + axLetter + 'padminus'] = (annSize / 2) - textPadShift;

            // size/shift are used during dragging
            options['_' + axLetter + 'size'] = annSize;
            options['_' + axLetter + 'shift'] = textShift;
        }

        // We have everything we need for calcAutorange at this point,
        // we can safely exit - unless we're currently dragging the plot
        if(!gd._dragging && annotationIsOffscreen) {
            annTextGroupInner.remove();
            return;
        }

        var xShift = 0;
        var yShift = 0;

        if(options.align !== 'left') {
            xShift = (annWidth - textWidth) * (options.align === 'center' ? 0.5 : 1);
        }
        if(options.valign !== 'top') {
            yShift = (annHeight - textHeight) * (options.valign === 'middle' ? 0.5 : 1);
        }

        if(hasMathjax) {
            mathjaxGroup.select('svg').attr({
                x: borderfull + xShift - 1,
                y: borderfull + yShift
            })
            .call(Drawing.setClipUrl, isSizeConstrained ? annClipID : null, gd);
        }
        else {
            var texty = borderfull + yShift - anntextBB.top;
            var textx = borderfull + xShift - anntextBB.left;

            annText.call(svgTextUtils.positionText, textx, texty)
                .call(Drawing.setClipUrl, isSizeConstrained ? annClipID : null, gd);
        }

        annTextClip.select('rect').call(Drawing.setRect, borderfull, borderfull,
            annWidth, annHeight);

        annTextBG.call(Drawing.setRect, borderwidth / 2, borderwidth / 2,
            outerWidth - borderwidth, outerHeight - borderwidth);

        annTextGroupInner.call(Drawing.setTranslate,
            Math.round(annPosPx.x.text - outerWidth / 2),
            Math.round(annPosPx.y.text - outerHeight / 2));

        /*
         * rotate text and background
         * we already calculated the text center position *as rotated*
         * because we needed that for autoranging anyway, so now whether
         * we have an arrow or not, we rotate about the text center.
         */
        annTextGroup.attr({transform: 'rotate(' + textangle + ',' +
                            annPosPx.x.text + ',' + annPosPx.y.text + ')'});

        /*
         * add the arrow
         * uses options[arrowwidth,arrowcolor,arrowhead] for styling
         * dx and dy are normally zero, but when you are dragging the textbox
         * while the head stays put, dx and dy are the pixel offsets
         */
        var drawArrow = function(dx, dy) {
            annGroup
                .selectAll('.annotation-arrow-g')
                .remove();

            var headX = annPosPx.x.head;
            var headY = annPosPx.y.head;
            var tailX = annPosPx.x.tail + dx;
            var tailY = annPosPx.y.tail + dy;
            var textX = annPosPx.x.text + dx;
            var textY = annPosPx.y.text + dy;

            // find the edge of the text box, where we'll start the arrow:
            // create transform matrix to rotate the text box corners
            var transform = Lib.rotationXYMatrix(textangle, textX, textY);
            var applyTransform = Lib.apply2DTransform(transform);
            var applyTransform2 = Lib.apply2DTransform2(transform);

            // calculate and transform bounding box
            var width = +annTextBG.attr('width');
            var height = +annTextBG.attr('height');
            var xLeft = textX - 0.5 * width;
            var xRight = xLeft + width;
            var yTop = textY - 0.5 * height;
            var yBottom = yTop + height;
            var edges = [
                [xLeft, yTop, xLeft, yBottom],
                [xLeft, yBottom, xRight, yBottom],
                [xRight, yBottom, xRight, yTop],
                [xRight, yTop, xLeft, yTop]
            ].map(applyTransform2);

            // Remove the line if it ends inside the box.  Use ray
            // casting for rotated boxes: see which edges intersect a
            // line from the arrowhead to far away and reduce with xor
            // to get the parity of the number of intersections.
            if(edges.reduce(function(a, x) {
                return a ^
                    !!Lib.segmentsIntersect(headX, headY, headX + 1e6, headY + 1e6,
                            x[0], x[1], x[2], x[3]);
            }, false)) {
                // no line or arrow - so quit drawArrow now
                return;
            }

            edges.forEach(function(x) {
                var p = Lib.segmentsIntersect(tailX, tailY, headX, headY,
                            x[0], x[1], x[2], x[3]);
                if(p) {
                    tailX = p.x;
                    tailY = p.y;
                }
            });

            var strokewidth = options.arrowwidth;
            var arrowColor = options.arrowcolor;
            var arrowSide = options.arrowside;

            var arrowGroup = annGroup.append('g')
                .style({opacity: Color.opacity(arrowColor)})
                .classed('annotation-arrow-g', true);

            var arrow = arrowGroup.append('path')
                .attr('d', 'M' + tailX + ',' + tailY + 'L' + headX + ',' + headY)
                .style('stroke-width', strokewidth + 'px')
                .call(Color.stroke, Color.rgb(arrowColor));

            drawArrowHead(arrow, arrowSide, options);

            // the arrow dragger is a small square right at the head, then a line to the tail,
            // all expanded by a stroke width of 6px plus the arrow line width
            if(edits.annotationPosition && arrow.node().parentNode && !subplotId) {
                var arrowDragHeadX = headX;
                var arrowDragHeadY = headY;
                if(options.standoff) {
                    var arrowLength = Math.sqrt(Math.pow(headX - tailX, 2) + Math.pow(headY - tailY, 2));
                    arrowDragHeadX += options.standoff * (tailX - headX) / arrowLength;
                    arrowDragHeadY += options.standoff * (tailY - headY) / arrowLength;
                }
                var arrowDrag = arrowGroup.append('path')
                    .classed('annotation-arrow', true)
                    .classed('anndrag', true)
                    .classed('cursor-move', true)
                    .attr({
                        d: 'M3,3H-3V-3H3ZM0,0L' + (tailX - arrowDragHeadX) + ',' + (tailY - arrowDragHeadY),
                        transform: 'translate(' + arrowDragHeadX + ',' + arrowDragHeadY + ')'
                    })
                    .style('stroke-width', (strokewidth + 6) + 'px')
                    .call(Color.stroke, 'rgba(0,0,0,0)')
                    .call(Color.fill, 'rgba(0,0,0,0)');

                var annx0, anny0;

                // dragger for the arrow & head: translates the whole thing
                // (head/tail/text) all together
                dragElement.init({
                    element: arrowDrag.node(),
                    gd: gd,
                    prepFn: function() {
                        var pos = Drawing.getTranslate(annTextGroupInner);

                        annx0 = pos.x;
                        anny0 = pos.y;
                        if(xa && xa.autorange) {
                            modifyBase(xa._name + '.autorange', true);
                        }
                        if(ya && ya.autorange) {
                            modifyBase(ya._name + '.autorange', true);
                        }
                    },
                    moveFn: function(dx, dy) {
                        var annxy0 = applyTransform(annx0, anny0);
                        var xcenter = annxy0[0] + dx;
                        var ycenter = annxy0[1] + dy;
                        annTextGroupInner.call(Drawing.setTranslate, xcenter, ycenter);

                        modifyItem('x', xa ?
                            xa.p2r(xa.r2p(options.x) + dx) :
                            (options.x + (dx / gs.w)));
                        modifyItem('y', ya ?
                            ya.p2r(ya.r2p(options.y) + dy) :
                            (options.y - (dy / gs.h)));

                        if(options.axref === options.xref) {
                            modifyItem('ax', xa.p2r(xa.r2p(options.ax) + dx));
                        }

                        if(options.ayref === options.yref) {
                            modifyItem('ay', ya.p2r(ya.r2p(options.ay) + dy));
                        }

                        arrowGroup.attr('transform', 'translate(' + dx + ',' + dy + ')');
                        annTextGroup.attr({
                            transform: 'rotate(' + textangle + ',' +
                                   xcenter + ',' + ycenter + ')'
                        });
                    },
                    doneFn: function() {
                        Registry.call('_guiRelayout', gd, getUpdateObj());
                        var notesBox = document.querySelector('.js-notes-box-panel');
                        if(notesBox) notesBox.redraw(notesBox.selectedObj);
                    }
                });
            }
        };

        if(options.showarrow) drawArrow(0, 0);

        // user dragging the annotation (text, not arrow)
        if(editTextPosition) {
            var baseTextTransform;

            // dragger for the textbox: if there's an arrow, just drag the
            // textbox and tail, leave the head untouched
            dragElement.init({
                element: annTextGroupInner.node(),
                gd: gd,
                prepFn: function() {
                    baseTextTransform = annTextGroup.attr('transform');
                },
                moveFn: function(dx, dy) {
                    var csr = 'pointer';
                    if(options.showarrow) {
                        if(options.axref === options.xref) {
                            modifyItem('ax', xa.p2r(xa.r2p(options.ax) + dx));
                        } else {
                            modifyItem('ax', options.ax + dx);
                        }

                        if(options.ayref === options.yref) {
                            modifyItem('ay', ya.p2r(ya.r2p(options.ay) + dy));
                        } else {
                            modifyItem('ay', options.ay + dy);
                        }

                        drawArrow(dx, dy);
                    }
                    else if(!subplotId) {
                        var xUpdate, yUpdate;
                        if(xa) {
                            xUpdate = xa.p2r(xa.r2p(options.x) + dx);

                        } else {
                            var widthFraction = options._xsize / gs.w;
                            var xLeft = options.x + (options._xshift - options.xshift) / gs.w - widthFraction / 2;

                            xUpdate = dragElement.align(xLeft + dx / gs.w,
                                widthFraction, 0, 1, options.xanchor);
                        }

                        if(ya) {
                            yUpdate = ya.p2r(ya.r2p(options.y) + dy);
                        } else {
                            var heightFraction = options._ysize / gs.h;
                            var yBottom = options.y - (options._yshift + options.yshift) / gs.h - heightFraction / 2;

                            yUpdate = dragElement.align(yBottom - dy / gs.h,
                                heightFraction, 0, 1, options.yanchor);
                        }
                        modifyItem('x', xUpdate);
                        modifyItem('y', yUpdate);
                        if(!xa || !ya) {
                            csr = dragElement.getCursor(
                                xa ? 0.5 : xUpdate,
                                ya ? 0.5 : yUpdate,
                                options.xanchor, options.yanchor
                            );
                        }
                    }
                    else return;

                    annTextGroup.attr({
                        transform: 'translate(' + dx + ',' + dy + ')' + baseTextTransform
                    });

                    setCursor(annTextGroupInner, csr);
                },
                doneFn: function() {
                    setCursor(annTextGroupInner);
                    Registry.call('_guiRelayout', gd, getUpdateObj());
                    var notesBox = document.querySelector('.js-notes-box-panel');
                    if(notesBox) notesBox.redraw(notesBox.selectedObj);
                }
            });
        }
    }

    if(edits.annotationText) {
        annText.call(svgTextUtils.makeEditable, {delegate: annTextGroupInner, gd: gd})
            .call(textLayout)
            .on('edit', function(_text) {
                options.text = _text;

                this.call(textLayout);

                modifyItem('text', _text);

                if(xa && xa.autorange) {
                    modifyBase(xa._name + '.autorange', true);
                }
                if(ya && ya.autorange) {
                    modifyBase(ya._name + '.autorange', true);
                }

                Registry.call('_guiRelayout', gd, getUpdateObj());
            });
    }
    else annText.call(textLayout);
}

},{"../../lib":697,"../../lib/setcursor":717,"../../lib/svg_text_utils":721,"../../plot_api/plot_template":735,"../../plots/cartesian/axes":745,"../../plots/plots":807,"../../registry":826,"../color":574,"../dragelement":592,"../drawing":595,"../fx":613,"./draw_arrow_head":564,"d3":151}],564:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

var Color = _dereq_('../color');

var ARROWPATHS = _dereq_('./arrow_paths');

/**
 * Add arrowhead(s) to a path or line element
 *
 * @param {d3.selection} el3: a d3-selected line or path element
 *
 * @param {string} ends: 'none', 'start', 'end', or 'start+end' for which ends get arrowheads
 *
 * @param {object} options: style information. Must have all the following:
 * @param {number} options.arrowhead: end head style - see ./arrow_paths
 * @param {number} options.startarrowhead: start head style - see ./arrow_paths
 * @param {number} options.arrowsize: relative size of the end head vs line width
 * @param {number} options.startarrowsize: relative size of the start head vs line width
 * @param {number} options.standoff: distance in px to move the end arrow point from its target
 * @param {number} options.startstandoff: distance in px to move the start arrow point from its target
 * @param {number} options.arrowwidth: width of the arrow line
 * @param {string} options.arrowcolor: color of the arrow line, for the head to match
 *     Note that the opacity of this color is ignored, as it's assumed the container
 *     of both the line and head has opacity applied to it so there isn't greater opacity
 *     where they overlap.
 */
module.exports = function drawArrowHead(el3, ends, options) {
    var el = el3.node();
    var headStyle = ARROWPATHS[options.arrowhead || 0];
    var startHeadStyle = ARROWPATHS[options.startarrowhead || 0];
    var scale = (options.arrowwidth || 1) * (options.arrowsize || 1);
    var startScale = (options.arrowwidth || 1) * (options.startarrowsize || 1);
    var doStart = ends.indexOf('start') >= 0;
    var doEnd = ends.indexOf('end') >= 0;
    var backOff = headStyle.backoff * scale + options.standoff;
    var startBackOff = startHeadStyle.backoff * startScale + options.startstandoff;

    var start, end, startRot, endRot;

    if(el.nodeName === 'line') {
        start = {x: +el3.attr('x1'), y: +el3.attr('y1')};
        end = {x: +el3.attr('x2'), y: +el3.attr('y2')};

        var dx = start.x - end.x;
        var dy = start.y - end.y;

        startRot = Math.atan2(dy, dx);
        endRot = startRot + Math.PI;
        if(backOff && startBackOff) {
            if(backOff + startBackOff > Math.sqrt(dx * dx + dy * dy)) {
                hideLine();
                return;
            }
        }

        if(backOff) {
            if(backOff * backOff > dx * dx + dy * dy) {
                hideLine();
                return;
            }
            var backOffX = backOff * Math.cos(startRot);
            var backOffY = backOff * Math.sin(startRot);

            end.x += backOffX;
            end.y += backOffY;
            el3.attr({x2: end.x, y2: end.y});

        }

        if(startBackOff) {
            if(startBackOff * startBackOff > dx * dx + dy * dy) {
                hideLine();
                return;
            }
            var startBackOffX = startBackOff * Math.cos(startRot);
            var startbackOffY = startBackOff * Math.sin(startRot);

            start.x -= startBackOffX;
            start.y -= startbackOffY;
            el3.attr({x1: start.x, y1: start.y});

        }
    }
    else if(el.nodeName === 'path') {
        var pathlen = el.getTotalLength();
        // using dash to hide the backOff region of the path.
        // if we ever allow dash for the arrow we'll have to
        // do better than this hack... maybe just manually
        // combine the two
        var dashArray = '';

        if(pathlen < backOff + startBackOff) {
            hideLine();
            return;
        }


        var start0 = el.getPointAtLength(0);
        var dstart = el.getPointAtLength(0.1);

        startRot = Math.atan2(start0.y - dstart.y, start0.x - dstart.x);
        start = el.getPointAtLength(Math.min(startBackOff, pathlen));

        dashArray = '0px,' + startBackOff + 'px,';

        var end0 = el.getPointAtLength(pathlen);
        var dend = el.getPointAtLength(pathlen - 0.1);

        endRot = Math.atan2(end0.y - dend.y, end0.x - dend.x);
        end = el.getPointAtLength(Math.max(0, pathlen - backOff));

        var shortening = dashArray ? startBackOff + backOff : backOff;
        dashArray += (pathlen - shortening) + 'px,' + pathlen + 'px';

        el3.style('stroke-dasharray', dashArray);
    }

    function hideLine() { el3.style('stroke-dasharray', '0px,100px'); }

    function drawhead(arrowHeadStyle, p, rot, arrowScale) {
        if(!arrowHeadStyle.path) return;
        if(arrowHeadStyle.noRotate) rot = 0;

        d3.select(el.parentNode).append('path')
            .attr({
                'class': el3.attr('class'),
                d: arrowHeadStyle.path,
                transform:
                    'translate(' + p.x + ',' + p.y + ')' +
                    (rot ? 'rotate(' + (rot * 180 / Math.PI) + ')' : '') +
                    'scale(' + arrowScale + ')'
            })
            .style({
                fill: Color.rgb(options.arrowcolor),
                'stroke-width': 0
            });
    }

    if(doStart) drawhead(startHeadStyle, start, startRot, startScale);
    if(doEnd) drawhead(headStyle, end, endRot, scale);
};

},{"../color":574,"./arrow_paths":556,"d3":151}],565:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var drawModule = _dereq_('./draw');
var clickModule = _dereq_('./click');

module.exports = {
    moduleType: 'component',
    name: 'annotations',

    layoutAttributes: _dereq_('./attributes'),
    supplyLayoutDefaults: _dereq_('./defaults'),
    includeBasePlot: _dereq_('../../plots/cartesian/include_components')('annotations'),

    calcAutorange: _dereq_('./calc_autorange'),
    draw: drawModule.draw,
    drawOne: drawModule.drawOne,
    drawRaw: drawModule.drawRaw,

    hasClickToShow: clickModule.hasClickToShow,
    onClick: clickModule.onClick,

    convertCoords: _dereq_('./convert_coords')
};

},{"../../plots/cartesian/include_components":755,"./attributes":557,"./calc_autorange":558,"./click":559,"./convert_coords":561,"./defaults":562,"./draw":563}],566:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var annAtts = _dereq_('../annotations/attributes');
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;

module.exports = overrideAll(templatedArray('annotation', {
    visible: annAtts.visible,
    x: {
        valType: 'any',
        
        
    },
    y: {
        valType: 'any',
        
        
    },
    z: {
        valType: 'any',
        
        
    },
    ax: {
        valType: 'number',
        
        
    },
    ay: {
        valType: 'number',
        
        
    },

    xanchor: annAtts.xanchor,
    xshift: annAtts.xshift,
    yanchor: annAtts.yanchor,
    yshift: annAtts.yshift,

    text: annAtts.text,
    textangle: annAtts.textangle,
    font: annAtts.font,
    width: annAtts.width,
    height: annAtts.height,
    opacity: annAtts.opacity,
    align: annAtts.align,
    valign: annAtts.valign,
    bgcolor: annAtts.bgcolor,
    bordercolor: annAtts.bordercolor,
    borderpad: annAtts.borderpad,
    borderwidth: annAtts.borderwidth,
    showarrow: annAtts.showarrow,
    arrowcolor: annAtts.arrowcolor,
    arrowhead: annAtts.arrowhead,
    startarrowhead: annAtts.startarrowhead,
    arrowside: annAtts.arrowside,
    arrowsize: annAtts.arrowsize,
    startarrowsize: annAtts.startarrowsize,
    arrowwidth: annAtts.arrowwidth,
    standoff: annAtts.standoff,
    startstandoff: annAtts.startstandoff,
    hovertext: annAtts.hovertext,
    hoverlabel: annAtts.hoverlabel,
    captureevents: annAtts.captureevents,

    // maybes later?
    // clicktoshow: annAtts.clicktoshow,
    // xclick: annAtts.xclick,
    // yclick: annAtts.yclick,

    // not needed!
    // axref: 'pixel'
    // ayref: 'pixel'
    // xref: 'x'
    // yref: 'y
    // zref: 'z'
}), 'calc', 'from-root');

},{"../../plot_api/edit_types":728,"../../plot_api/plot_template":735,"../annotations/attributes":557}],567:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');

module.exports = function convert(scene) {
    var fullSceneLayout = scene.fullSceneLayout;
    var anns = fullSceneLayout.annotations;

    for(var i = 0; i < anns.length; i++) {
        mockAnnAxes(anns[i], scene);
    }

    scene.fullLayout._infolayer
        .selectAll('.annotation-' + scene.id)
        .remove();
};

function mockAnnAxes(ann, scene) {
    var fullSceneLayout = scene.fullSceneLayout;
    var domain = fullSceneLayout.domain;
    var size = scene.fullLayout._size;

    var base = {
        // this gets fill in on render
        pdata: null,

        // to get setConvert to not execute cleanly
        type: 'linear',

        // don't try to update them on `editable: true`
        autorange: false,

        // set infinite range so that annotation draw routine
        // does not try to remove 'outside-range' annotations,
        // this case is handled in the render loop
        range: [-Infinity, Infinity]
    };

    ann._xa = {};
    Lib.extendFlat(ann._xa, base);
    Axes.setConvert(ann._xa);
    ann._xa._offset = size.l + domain.x[0] * size.w;
    ann._xa.l2p = function() {
        return 0.5 * (1 + ann._pdata[0] / ann._pdata[3]) * size.w * (domain.x[1] - domain.x[0]);
    };

    ann._ya = {};
    Lib.extendFlat(ann._ya, base);
    Axes.setConvert(ann._ya);
    ann._ya._offset = size.t + (1 - domain.y[1]) * size.h;
    ann._ya.l2p = function() {
        return 0.5 * (1 - ann._pdata[1] / ann._pdata[3]) * size.h * (domain.y[1] - domain.y[0]);
    };
}

},{"../../lib":697,"../../plots/cartesian/axes":745}],568:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');
var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');
var handleAnnotationCommonDefaults = _dereq_('../annotations/common_defaults');
var attributes = _dereq_('./attributes');

module.exports = function handleDefaults(sceneLayoutIn, sceneLayoutOut, opts) {
    handleArrayContainerDefaults(sceneLayoutIn, sceneLayoutOut, {
        name: 'annotations',
        handleItemDefaults: handleAnnotationDefaults,
        fullLayout: opts.fullLayout
    });
};

function handleAnnotationDefaults(annIn, annOut, sceneLayout, opts) {
    function coerce(attr, dflt) {
        return Lib.coerce(annIn, annOut, attributes, attr, dflt);
    }

    function coercePosition(axLetter) {
        var axName = axLetter + 'axis';

        // mock in such way that getFromId grabs correct 3D axis
        var gdMock = { _fullLayout: {} };
        gdMock._fullLayout[axName] = sceneLayout[axName];

        return Axes.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5);
    }


    var visible = coerce('visible');
    if(!visible) return;

    handleAnnotationCommonDefaults(annIn, annOut, opts.fullLayout, coerce);

    coercePosition('x');
    coercePosition('y');
    coercePosition('z');

    // if you have one coordinate you should all three
    Lib.noneOrAll(annIn, annOut, ['x', 'y', 'z']);

    // hard-set here for completeness
    annOut.xref = 'x';
    annOut.yref = 'y';
    annOut.zref = 'z';

    coerce('xanchor');
    coerce('yanchor');
    coerce('xshift');
    coerce('yshift');

    if(annOut.showarrow) {
        annOut.axref = 'pixel';
        annOut.ayref = 'pixel';

        // TODO maybe default values should be bigger than the 2D case?
        coerce('ax', -10);
        coerce('ay', -30);

        // if you have one part of arrow length you should have both
        Lib.noneOrAll(annIn, annOut, ['ax', 'ay']);
    }
}

},{"../../lib":697,"../../plots/array_container_defaults":741,"../../plots/cartesian/axes":745,"../annotations/common_defaults":560,"./attributes":566}],569:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var drawRaw = _dereq_('../annotations/draw').drawRaw;
var project = _dereq_('../../plots/gl3d/project');
var axLetters = ['x', 'y', 'z'];

module.exports = function draw(scene) {
    var fullSceneLayout = scene.fullSceneLayout;
    var dataScale = scene.dataScale;
    var anns = fullSceneLayout.annotations;

    for(var i = 0; i < anns.length; i++) {
        var ann = anns[i];
        var annotationIsOffscreen = false;

        for(var j = 0; j < 3; j++) {
            var axLetter = axLetters[j];
            var pos = ann[axLetter];
            var ax = fullSceneLayout[axLetter + 'axis'];
            var posFraction = ax.r2fraction(pos);

            if(posFraction < 0 || posFraction > 1) {
                annotationIsOffscreen = true;
                break;
            }
        }

        if(annotationIsOffscreen) {
            scene.fullLayout._infolayer
                .select('.annotation-' + scene.id + '[data-index="' + i + '"]')
                .remove();
        } else {
            ann._pdata = project(scene.glplot.cameraParams, [
                fullSceneLayout.xaxis.r2l(ann.x) * dataScale[0],
                fullSceneLayout.yaxis.r2l(ann.y) * dataScale[1],
                fullSceneLayout.zaxis.r2l(ann.z) * dataScale[2]
            ]);

            drawRaw(scene.graphDiv, ann, i, scene.id, ann._xa, ann._ya);
        }
    }
};

},{"../../plots/gl3d/project":795,"../annotations/draw":563}],570:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');

module.exports = {
    moduleType: 'component',
    name: 'annotations3d',

    schema: {
        subplots: {
            scene: {annotations: _dereq_('./attributes')}
        }
    },

    layoutAttributes: _dereq_('./attributes'),
    handleDefaults: _dereq_('./defaults'),
    includeBasePlot: includeGL3D,

    convert: _dereq_('./convert'),
    draw: _dereq_('./draw')
};

function includeGL3D(layoutIn, layoutOut) {
    var GL3D = Registry.subplotsRegistry.gl3d;
    if(!GL3D) return;

    var attrRegex = GL3D.attrRegex;

    var keys = Object.keys(layoutIn);
    for(var i = 0; i < keys.length; i++) {
        var k = keys[i];
        if(attrRegex.test(k) && (layoutIn[k].annotations || []).length) {
            Lib.pushUnique(layoutOut._basePlotModules, GL3D);
            Lib.pushUnique(layoutOut._subplots.gl3d, k);
        }
    }
}

},{"../../lib":697,"../../registry":826,"./attributes":566,"./convert":567,"./defaults":568,"./draw":569}],571:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// a trimmed down version of:
// https://github.com/alexcjohnson/world-calendars/blob/master/dist/index.js

module.exports = _dereq_('world-calendars/dist/main');

_dereq_('world-calendars/dist/plus');

_dereq_('world-calendars/dist/calendars/chinese');
_dereq_('world-calendars/dist/calendars/coptic');
_dereq_('world-calendars/dist/calendars/discworld');
_dereq_('world-calendars/dist/calendars/ethiopian');
_dereq_('world-calendars/dist/calendars/hebrew');
_dereq_('world-calendars/dist/calendars/islamic');
_dereq_('world-calendars/dist/calendars/julian');
_dereq_('world-calendars/dist/calendars/mayan');
_dereq_('world-calendars/dist/calendars/nanakshahi');
_dereq_('world-calendars/dist/calendars/nepali');
_dereq_('world-calendars/dist/calendars/persian');
_dereq_('world-calendars/dist/calendars/taiwan');
_dereq_('world-calendars/dist/calendars/thai');
_dereq_('world-calendars/dist/calendars/ummalqura');

},{"world-calendars/dist/calendars/chinese":538,"world-calendars/dist/calendars/coptic":539,"world-calendars/dist/calendars/discworld":540,"world-calendars/dist/calendars/ethiopian":541,"world-calendars/dist/calendars/hebrew":542,"world-calendars/dist/calendars/islamic":543,"world-calendars/dist/calendars/julian":544,"world-calendars/dist/calendars/mayan":545,"world-calendars/dist/calendars/nanakshahi":546,"world-calendars/dist/calendars/nepali":547,"world-calendars/dist/calendars/persian":548,"world-calendars/dist/calendars/taiwan":549,"world-calendars/dist/calendars/thai":550,"world-calendars/dist/calendars/ummalqura":551,"world-calendars/dist/main":552,"world-calendars/dist/plus":553}],572:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var calendars = _dereq_('./calendars');

var Lib = _dereq_('../../lib');
var constants = _dereq_('../../constants/numerical');

var EPOCHJD = constants.EPOCHJD;
var ONEDAY = constants.ONEDAY;

var attributes = {
    valType: 'enumerated',
    values: Object.keys(calendars.calendars),
    
    editType: 'calc',
    dflt: 'gregorian'
};

var handleDefaults = function(contIn, contOut, attr, dflt) {
    var attrs = {};
    attrs[attr] = attributes;

    return Lib.coerce(contIn, contOut, attrs, attr, dflt);
};

var handleTraceDefaults = function(traceIn, traceOut, coords, layout) {
    for(var i = 0; i < coords.length; i++) {
        handleDefaults(traceIn, traceOut, coords[i] + 'calendar', layout.calendar);
    }
};

// each calendar needs its own default canonical tick. I would love to use
// 2000-01-01 (or even 0000-01-01) for them all but they don't necessarily
// all support either of those dates. Instead I'll use the most significant
// number they *do* support, biased toward the present day.
var CANONICAL_TICK = {
    chinese: '2000-01-01',
    coptic: '2000-01-01',
    discworld: '2000-01-01',
    ethiopian: '2000-01-01',
    hebrew: '5000-01-01',
    islamic: '1000-01-01',
    julian: '2000-01-01',
    mayan: '5000-01-01',
    nanakshahi: '1000-01-01',
    nepali: '2000-01-01',
    persian: '1000-01-01',
    jalali: '1000-01-01',
    taiwan: '1000-01-01',
    thai: '2000-01-01',
    ummalqura: '1400-01-01'
};

// Start on a Sunday - for week ticks
// Discworld and Mayan calendars don't have 7-day weeks but we're going to give them
// 7-day week ticks so start on our Sundays.
// If anyone really cares we can customize the auto tick spacings for these calendars.
var CANONICAL_SUNDAY = {
    chinese: '2000-01-02',
    coptic: '2000-01-03',
    discworld: '2000-01-03',
    ethiopian: '2000-01-05',
    hebrew: '5000-01-01',
    islamic: '1000-01-02',
    julian: '2000-01-03',
    mayan: '5000-01-01',
    nanakshahi: '1000-01-05',
    nepali: '2000-01-05',
    persian: '1000-01-01',
    jalali: '1000-01-01',
    taiwan: '1000-01-04',
    thai: '2000-01-04',
    ummalqura: '1400-01-06'
};

var DFLTRANGE = {
    chinese: ['2000-01-01', '2001-01-01'],
    coptic: ['1700-01-01', '1701-01-01'],
    discworld: ['1800-01-01', '1801-01-01'],
    ethiopian: ['2000-01-01', '2001-01-01'],
    hebrew: ['5700-01-01', '5701-01-01'],
    islamic: ['1400-01-01', '1401-01-01'],
    julian: ['2000-01-01', '2001-01-01'],
    mayan: ['5200-01-01', '5201-01-01'],
    nanakshahi: ['0500-01-01', '0501-01-01'],
    nepali: ['2000-01-01', '2001-01-01'],
    persian: ['1400-01-01', '1401-01-01'],
    jalali: ['1400-01-01', '1401-01-01'],
    taiwan: ['0100-01-01', '0101-01-01'],
    thai: ['2500-01-01', '2501-01-01'],
    ummalqura: ['1400-01-01', '1401-01-01']
};

/*
 * convert d3 templates to world-calendars templates, so our users only need
 * to know d3's specifiers. Map space padding to no padding, and unknown fields
 * to an ugly placeholder
 */
var UNKNOWN = '##';
var d3ToWorldCalendars = {
    'd': {'0': 'dd', '-': 'd'}, // 2-digit or unpadded day of month
    'e': {'0': 'd', '-': 'd'}, // alternate, always unpadded day of month
    'a': {'0': 'D', '-': 'D'}, // short weekday name
    'A': {'0': 'DD', '-': 'DD'}, // full weekday name
    'j': {'0': 'oo', '-': 'o'}, // 3-digit or unpadded day of the year
    'W': {'0': 'ww', '-': 'w'}, // 2-digit or unpadded week of the year (Monday first)
    'm': {'0': 'mm', '-': 'm'}, // 2-digit or unpadded month number
    'b': {'0': 'M', '-': 'M'}, // short month name
    'B': {'0': 'MM', '-': 'MM'}, // full month name
    'y': {'0': 'yy', '-': 'yy'}, // 2-digit year (map unpadded to zero-padded)
    'Y': {'0': 'yyyy', '-': 'yyyy'}, // 4-digit year (map unpadded to zero-padded)
    'U': UNKNOWN, // Sunday-first week of the year
    'w': UNKNOWN, // day of the week [0(sunday),6]
    // combined format, we replace the date part with the world-calendar version
    // and the %X stays there for d3 to handle with time parts
    'c': {'0': 'D M d %X yyyy', '-': 'D M d %X yyyy'},
    'x': {'0': 'mm/dd/yyyy', '-': 'mm/dd/yyyy'}
};

function worldCalFmt(fmt, x, calendar) {
    var dateJD = Math.floor((x + 0.05) / ONEDAY) + EPOCHJD;
    var cDate = getCal(calendar).fromJD(dateJD);
    var i = 0;
    var modifier, directive, directiveLen, directiveObj, replacementPart;

    while((i = fmt.indexOf('%', i)) !== -1) {
        modifier = fmt.charAt(i + 1);
        if(modifier === '0' || modifier === '-' || modifier === '_') {
            directiveLen = 3;
            directive = fmt.charAt(i + 2);
            if(modifier === '_') modifier = '-';
        }
        else {
            directive = modifier;
            modifier = '0';
            directiveLen = 2;
        }
        directiveObj = d3ToWorldCalendars[directive];
        if(!directiveObj) {
            i += directiveLen;
        }
        else {
            // code is recognized as a date part but world-calendars doesn't support it
            if(directiveObj === UNKNOWN) replacementPart = UNKNOWN;

            // format the cDate according to the translated directive
            else replacementPart = cDate.formatDate(directiveObj[modifier]);

            fmt = fmt.substr(0, i) + replacementPart + fmt.substr(i + directiveLen);
            i += replacementPart.length;
        }
    }
    return fmt;
}

// cache world calendars, so we don't have to reinstantiate
// during each date-time conversion
var allCals = {};
function getCal(calendar) {
    var calendarObj = allCals[calendar];
    if(calendarObj) return calendarObj;

    calendarObj = allCals[calendar] = calendars.instance(calendar);
    return calendarObj;
}

function makeAttrs(description) {
    return Lib.extendFlat({}, attributes, { description: description });
}

function makeTraceAttrsDescription(coord) {
    return 'Sets the calendar system to use with `' + coord + '` date data.';
}

var xAttrs = {
    xcalendar: makeAttrs(makeTraceAttrsDescription('x'))
};

var xyAttrs = Lib.extendFlat({}, xAttrs, {
    ycalendar: makeAttrs(makeTraceAttrsDescription('y'))
});

var xyzAttrs = Lib.extendFlat({}, xyAttrs, {
    zcalendar: makeAttrs(makeTraceAttrsDescription('z'))
});

var axisAttrs = makeAttrs([
    'Sets the calendar system to use for `range` and `tick0`',
    'if this is a date axis. This does not set the calendar for',
    'interpreting data on this axis, that\'s specified in the trace',
    'or via the global `layout.calendar`'
].join(' '));

module.exports = {
    moduleType: 'component',
    name: 'calendars',

    schema: {
        traces: {
            scatter: xyAttrs,
            bar: xyAttrs,
            box: xyAttrs,
            heatmap: xyAttrs,
            contour: xyAttrs,
            histogram: xyAttrs,
            histogram2d: xyAttrs,
            histogram2dcontour: xyAttrs,
            scatter3d: xyzAttrs,
            surface: xyzAttrs,
            mesh3d: xyzAttrs,
            scattergl: xyAttrs,
            ohlc: xAttrs,
            candlestick: xAttrs
        },
        layout: {
            calendar: makeAttrs([
                'Sets the default calendar system to use for interpreting and',
                'displaying dates throughout the plot.'
            ].join(' '))
        },
        subplots: {
            xaxis: {calendar: axisAttrs},
            yaxis: {calendar: axisAttrs},
            scene: {
                xaxis: {calendar: axisAttrs},
                // TODO: it's actually redundant to include yaxis and zaxis here
                // because in the scene attributes these are the same object so merging
                // into one merges into them all. However, I left them in for parity with
                // cartesian, where yaxis is unused until we Plotschema.get() when we
                // use its presence or absence to determine whether to delete attributes
                // from yaxis if they only apply to x (rangeselector/rangeslider)
                yaxis: {calendar: axisAttrs},
                zaxis: {calendar: axisAttrs}
            },
            polar: {
                radialaxis: {calendar: axisAttrs}
            }
        },
        transforms: {
            filter: {
                valuecalendar: makeAttrs([
                    'Sets the calendar system to use for `value`, if it is a date.'
                ].join(' ')),
                targetcalendar: makeAttrs([
                    'Sets the calendar system to use for `target`, if it is an',
                    'array of dates. If `target` is a string (eg *x*) we use the',
                    'corresponding trace attribute (eg `xcalendar`) if it exists,',
                    'even if `targetcalendar` is provided.'
                ].join(' '))
            }
        }
    },

    layoutAttributes: attributes,

    handleDefaults: handleDefaults,
    handleTraceDefaults: handleTraceDefaults,

    CANONICAL_SUNDAY: CANONICAL_SUNDAY,
    CANONICAL_TICK: CANONICAL_TICK,
    DFLTRANGE: DFLTRANGE,

    getCal: getCal,
    worldCalFmt: worldCalFmt
};

},{"../../constants/numerical":674,"../../lib":697,"./calendars":571}],573:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


// IMPORTANT - default colors should be in hex for compatibility
exports.defaults = [
    '#1f77b4',  // muted blue
    '#ff7f0e',  // safety orange
    '#2ca02c',  // cooked asparagus green
    '#d62728',  // brick red
    '#9467bd',  // muted purple
    '#8c564b',  // chestnut brown
    '#e377c2',  // raspberry yogurt pink
    '#7f7f7f',  // middle gray
    '#bcbd22',  // curry yellow-green
    '#17becf'   // blue-teal
];

exports.defaultLine = '#444';

exports.lightLine = '#eee';

exports.background = '#fff';

exports.borderLine = '#BEC8D9';

// with axis.color and Color.interp we aren't using lightLine
// itself anymore, instead interpolating between axis.color
// and the background color using tinycolor.mix. lightFraction
// gives back exactly lightLine if the other colors are defaults.
exports.lightFraction = 100 * (0xe - 0x4) / (0xf - 0x4);

},{}],574:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var tinycolor = _dereq_('tinycolor2');
var isNumeric = _dereq_('fast-isnumeric');

var color = module.exports = {};

var colorAttrs = _dereq_('./attributes');
color.defaults = colorAttrs.defaults;
var defaultLine = color.defaultLine = colorAttrs.defaultLine;
color.lightLine = colorAttrs.lightLine;
var background = color.background = colorAttrs.background;

/*
 * tinyRGB: turn a tinycolor into an rgb string, but
 * unlike the built-in tinycolor.toRgbString this never includes alpha
 */
color.tinyRGB = function(tc) {
    var c = tc.toRgb();
    return 'rgb(' + Math.round(c.r) + ', ' +
        Math.round(c.g) + ', ' + Math.round(c.b) + ')';
};

color.rgb = function(cstr) { return color.tinyRGB(tinycolor(cstr)); };

color.opacity = function(cstr) { return cstr ? tinycolor(cstr).getAlpha() : 0; };

color.addOpacity = function(cstr, op) {
    var c = tinycolor(cstr).toRgb();
    return 'rgba(' + Math.round(c.r) + ', ' +
        Math.round(c.g) + ', ' + Math.round(c.b) + ', ' + op + ')';
};

// combine two colors into one apparent color
// if back has transparency or is missing,
// color.background is assumed behind it
color.combine = function(front, back) {
    var fc = tinycolor(front).toRgb();
    if(fc.a === 1) return tinycolor(front).toRgbString();

    var bc = tinycolor(back || background).toRgb();
    var bcflat = bc.a === 1 ? bc : {
        r: 255 * (1 - bc.a) + bc.r * bc.a,
        g: 255 * (1 - bc.a) + bc.g * bc.a,
        b: 255 * (1 - bc.a) + bc.b * bc.a
    };
    var fcflat = {
        r: bcflat.r * (1 - fc.a) + fc.r * fc.a,
        g: bcflat.g * (1 - fc.a) + fc.g * fc.a,
        b: bcflat.b * (1 - fc.a) + fc.b * fc.a
    };
    return tinycolor(fcflat).toRgbString();
};

/*
 * Create a color that contrasts with cstr.
 *
 * If cstr is a dark color, we lighten it; if it's light, we darken.
 *
 * If lightAmount / darkAmount are used, we adjust by these percentages,
 * otherwise we go all the way to white or black.
 */
color.contrast = function(cstr, lightAmount, darkAmount) {
    var tc = tinycolor(cstr);

    if(tc.getAlpha() !== 1) tc = tinycolor(color.combine(cstr, background));

    var newColor = tc.isDark() ?
        (lightAmount ? tc.lighten(lightAmount) : background) :
        (darkAmount ? tc.darken(darkAmount) : defaultLine);

    return newColor.toString();
};

color.stroke = function(s, c) {
    var tc = tinycolor(c);
    s.style({'stroke': color.tinyRGB(tc), 'stroke-opacity': tc.getAlpha()});
};

color.fill = function(s, c) {
    var tc = tinycolor(c);
    s.style({
        'fill': color.tinyRGB(tc),
        'fill-opacity': tc.getAlpha()
    });
};

// search container for colors with the deprecated rgb(fractions) format
// and convert them to rgb(0-255 values)
color.clean = function(container) {
    if(!container || typeof container !== 'object') return;

    var keys = Object.keys(container);
    var i, j, key, val;

    for(i = 0; i < keys.length; i++) {
        key = keys[i];
        val = container[key];

        // only sanitize keys that end in "color" or "colorscale"
        if(key.substr(key.length - 5) === 'color') {
            if(Array.isArray(val)) {
                for(j = 0; j < val.length; j++) val[j] = cleanOne(val[j]);
            }
            else container[key] = cleanOne(val);
        }
        else if(key.substr(key.length - 10) === 'colorscale' && Array.isArray(val)) {
            // colorscales have the format [[0, color1], [frac, color2], ... [1, colorN]]
            for(j = 0; j < val.length; j++) {
                if(Array.isArray(val[j])) val[j][1] = cleanOne(val[j][1]);
            }
        }
        // recurse into arrays of objects, and plain objects
        else if(Array.isArray(val)) {
            var el0 = val[0];
            if(!Array.isArray(el0) && el0 && typeof el0 === 'object') {
                for(j = 0; j < val.length; j++) color.clean(val[j]);
            }
        }
        else if(val && typeof val === 'object') color.clean(val);
    }
};

function cleanOne(val) {
    if(isNumeric(val) || typeof val !== 'string') return val;

    var valTrim = val.trim();
    if(valTrim.substr(0, 3) !== 'rgb') return val;

    var match = valTrim.match(/^rgba?\s*\(([^()]*)\)$/);
    if(!match) return val;

    var parts = match[1].trim().split(/\s*[\s,]\s*/);
    var rgba = valTrim.charAt(3) === 'a' && parts.length === 4;
    if(!rgba && parts.length !== 3) return val;

    for(var i = 0; i < parts.length; i++) {
        if(!parts[i].length) return val;
        parts[i] = Number(parts[i]);

        // all parts must be non-negative numbers
        if(!(parts[i] >= 0)) return val;
        // alpha>1 gets clipped to 1
        if(i === 3) {
            if(parts[i] > 1) parts[i] = 1;
        }
        // r, g, b must be < 1 (ie 1 itself is not allowed)
        else if(parts[i] >= 1) return val;
    }

    var rgbStr = Math.round(parts[0] * 255) + ', ' +
        Math.round(parts[1] * 255) + ', ' +
        Math.round(parts[2] * 255);

    if(rgba) return 'rgba(' + rgbStr + ', ' + parts[3] + ')';
    return 'rgb(' + rgbStr + ')';
}

},{"./attributes":573,"fast-isnumeric":218,"tinycolor2":518}],575:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var axesAttrs = _dereq_('../../plots/cartesian/layout_attributes');
var fontAttrs = _dereq_('../../plots/font_attributes');
var extendFlat = _dereq_('../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;


module.exports = overrideAll({
// TODO: only right is supported currently
//     orient: {
//         valType: 'enumerated',
//         
//         values: ['left', 'right', 'top', 'bottom'],
//         dflt: 'right',
//         
//     },
    thicknessmode: {
        valType: 'enumerated',
        values: ['fraction', 'pixels'],
        
        dflt: 'pixels',
        
    },
    thickness: {
        valType: 'number',
        
        min: 0,
        dflt: 30,
        
    },
    lenmode: {
        valType: 'enumerated',
        values: ['fraction', 'pixels'],
        
        dflt: 'fraction',
        
    },
    len: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        
    },
    x: {
        valType: 'number',
        dflt: 1.02,
        min: -2,
        max: 3,
        
        
    },
    xanchor: {
        valType: 'enumerated',
        values: ['left', 'center', 'right'],
        dflt: 'left',
        
        
    },
    xpad: {
        valType: 'number',
        
        min: 0,
        dflt: 10,
        
    },
    y: {
        valType: 'number',
        
        dflt: 0.5,
        min: -2,
        max: 3,
        
    },
    yanchor: {
        valType: 'enumerated',
        values: ['top', 'middle', 'bottom'],
        
        dflt: 'middle',
        
    },
    ypad: {
        valType: 'number',
        
        min: 0,
        dflt: 10,
        
    },
    // a possible line around the bar itself
    outlinecolor: axesAttrs.linecolor,
    outlinewidth: axesAttrs.linewidth,
    // Should outlinewidth have {dflt: 0} ?
    // another possible line outside the padding and tick labels
    bordercolor: axesAttrs.linecolor,
    borderwidth: {
        valType: 'number',
        
        min: 0,
        dflt: 0,
        
    },
    bgcolor: {
        valType: 'color',
        
        dflt: 'rgba(0,0,0,0)',
        
    },
    // tick and title properties named and function exactly as in axes
    tickmode: axesAttrs.tickmode,
    nticks: axesAttrs.nticks,
    tick0: axesAttrs.tick0,
    dtick: axesAttrs.dtick,
    tickvals: axesAttrs.tickvals,
    ticktext: axesAttrs.ticktext,
    ticks: extendFlat({}, axesAttrs.ticks, {dflt: ''}),
    ticklen: axesAttrs.ticklen,
    tickwidth: axesAttrs.tickwidth,
    tickcolor: axesAttrs.tickcolor,
    showticklabels: axesAttrs.showticklabels,
    tickfont: fontAttrs({
        
    }),
    tickangle: axesAttrs.tickangle,
    tickformat: axesAttrs.tickformat,
    tickformatstops: axesAttrs.tickformatstops,
    tickprefix: axesAttrs.tickprefix,
    showtickprefix: axesAttrs.showtickprefix,
    ticksuffix: axesAttrs.ticksuffix,
    showticksuffix: axesAttrs.showticksuffix,
    separatethousands: axesAttrs.separatethousands,
    exponentformat: axesAttrs.exponentformat,
    showexponent: axesAttrs.showexponent,
    title: {
        text: {
            valType: 'string',
            
            
        },
        font: fontAttrs({
            
        }),
        side: {
            valType: 'enumerated',
            values: ['right', 'top', 'bottom'],
            
            dflt: 'top',
            
        }
    },

    _deprecated: {
        title: {
            valType: 'string',
            
            
        },
        titlefont: fontAttrs({
            
        }),
        titleside: {
            valType: 'enumerated',
            values: ['right', 'top', 'bottom'],
            
            dflt: 'top',
            
        }
    }
}, 'colorbars', 'from-root');

},{"../../lib/extend":687,"../../plot_api/edit_types":728,"../../plots/cartesian/layout_attributes":757,"../../plots/font_attributes":771}],576:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var drawColorbar = _dereq_('./draw');
var flipScale = _dereq_('../colorscale/helpers').flipScale;

/**
 * connectColorbar: create a colorbar from a trace, using its module to
 *   describe the connection.
 *
 * @param {DOM element} gd
 *
 * @param {Array} cd
 *   calcdata entry for this trace. cd[0].trace is the trace itself, and the
 *   colorbar object will be stashed in cd[0].t.cb
 *
 * @param {object|function} moduleOpts
 *   may be a function(gd, cd) to override the standard handling below. If
 *   an object, should have these keys:
 * @param {Optional(string)} moduleOpts.container
 *   name of the container inside the trace where the colorbar and colorscale
 *   attributes live (ie 'marker', 'line') - omit if they're at the trace root.
 * @param {string} moduleOpts.min
 *   name of the attribute holding the value of the minimum color
 * @param {string} moduleOpts.max
 *   name of the attribute holding the value of the maximum color
 * @param {Optional(string)} moduleOpts.vals
 *   name of the attribute holding the (numeric) color data
 *   used only if min/max fail. May be omitted if these are always
 *   pre-calculated.
 */
module.exports = function connectColorbar(gd, cd, moduleOpts) {
    if(typeof moduleOpts === 'function') return moduleOpts(gd, cd);

    var trace = cd[0].trace;
    var cbId = 'cb' + trace.uid;
    moduleOpts = Array.isArray(moduleOpts) ? moduleOpts : [moduleOpts];

    for(var i = 0; i < moduleOpts.length; i++) {
        var containerName = moduleOpts[i].container;

        var container = containerName ? trace[containerName] : trace;

        gd._fullLayout._infolayer.selectAll('.' + cbId).remove();
        if(!container || !container.showscale) continue;

        var cb = cd[0].t.cb = drawColorbar(gd, cbId);

        var scl = container.reversescale ?
            flipScale(container.colorscale) :
            container.colorscale;

        cb.fillgradient(scl)
            .zrange([container[moduleOpts[i].min], container[moduleOpts[i].max]])
            .options(container.colorbar)();

        return;
    }
};

},{"../colorscale/helpers":585,"./draw":579}],577:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    cn: {
        colorbar: 'colorbar',
        cbbg: 'cbbg',
        cbfill: 'cbfill',
        cbfills: 'cbfills',
        cbline: 'cbline',
        cblines: 'cblines',
        cbaxis: 'cbaxis',
        cbtitleunshift: 'cbtitleunshift',
        cbtitle: 'cbtitle',
        cboutline: 'cboutline',
        crisp: 'crisp',
        jsPlaceholder: 'js-placeholder'
    }
};

},{}],578:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var Template = _dereq_('../../plot_api/plot_template');

var handleTickValueDefaults = _dereq_('../../plots/cartesian/tick_value_defaults');
var handleTickMarkDefaults = _dereq_('../../plots/cartesian/tick_mark_defaults');
var handleTickLabelDefaults = _dereq_('../../plots/cartesian/tick_label_defaults');

var attributes = _dereq_('./attributes');

module.exports = function colorbarDefaults(containerIn, containerOut, layout) {
    var colorbarOut = Template.newContainer(containerOut, 'colorbar');
    var colorbarIn = containerIn.colorbar || {};

    function coerce(attr, dflt) {
        return Lib.coerce(colorbarIn, colorbarOut, attributes, attr, dflt);
    }

    var thicknessmode = coerce('thicknessmode');
    coerce('thickness', (thicknessmode === 'fraction') ?
        30 / (layout.width - layout.margin.l - layout.margin.r) :
        30
    );

    var lenmode = coerce('lenmode');
    coerce('len', (lenmode === 'fraction') ?
        1 :
        layout.height - layout.margin.t - layout.margin.b
    );

    coerce('x');
    coerce('xanchor');
    coerce('xpad');
    coerce('y');
    coerce('yanchor');
    coerce('ypad');
    Lib.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']);

    coerce('outlinecolor');
    coerce('outlinewidth');
    coerce('bordercolor');
    coerce('borderwidth');
    coerce('bgcolor');

    handleTickValueDefaults(colorbarIn, colorbarOut, coerce, 'linear');

    var opts = {outerTicks: false, font: layout.font};
    handleTickLabelDefaults(colorbarIn, colorbarOut, coerce, 'linear', opts);
    handleTickMarkDefaults(colorbarIn, colorbarOut, coerce, 'linear', opts);

    coerce('title.text', layout._dfltTitle.colorbar);
    Lib.coerceFont(coerce, 'title.font', layout.font);
    coerce('title.side');
};

},{"../../lib":697,"../../plot_api/plot_template":735,"../../plots/cartesian/tick_label_defaults":764,"../../plots/cartesian/tick_mark_defaults":765,"../../plots/cartesian/tick_value_defaults":766,"./attributes":575}],579:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var tinycolor = _dereq_('tinycolor2');

var Plots = _dereq_('../../plots/plots');
var Registry = _dereq_('../../registry');
var Axes = _dereq_('../../plots/cartesian/axes');
var dragElement = _dereq_('../dragelement');
var Lib = _dereq_('../../lib');
var extendFlat = _dereq_('../../lib/extend').extendFlat;
var setCursor = _dereq_('../../lib/setcursor');
var Drawing = _dereq_('../drawing');
var Color = _dereq_('../color');
var Titles = _dereq_('../titles');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var alignmentConstants = _dereq_('../../constants/alignment');
var LINE_SPACING = alignmentConstants.LINE_SPACING;
var FROM_TL = alignmentConstants.FROM_TL;
var FROM_BR = alignmentConstants.FROM_BR;

var handleAxisDefaults = _dereq_('../../plots/cartesian/axis_defaults');
var handleAxisPositionDefaults = _dereq_('../../plots/cartesian/position_defaults');
var axisLayoutAttrs = _dereq_('../../plots/cartesian/layout_attributes');

var attributes = _dereq_('./attributes');
var cn = _dereq_('./constants').cn;

module.exports = function draw(gd, id) {
    // opts: options object, containing everything from attributes
    // plus a few others that are the equivalent of the colorbar "data"
    var opts = {};
    for(var k in attributes) {
        opts[k] = null;
    }
    // fillcolor can be a d3 scale, domain is z values, range is colors
    // or leave it out for no fill,
    // or set to a string constant for single-color fill
    opts.fillcolor = null;
    // line.color has the same options as fillcolor
    opts.line = {color: null, width: null, dash: null};
    // levels of lines to draw.
    // note that this DOES NOT determine the extent of the bar
    // that's given by the domain of fillcolor
    // (or line.color if no fillcolor domain)
    opts.levels = {start: null, end: null, size: null};
    // separate fill levels (for example, heatmap coloring of a
    // contour map) if this is omitted, fillcolors will be
    // evaluated halfway between levels
    opts.filllevels = null;
    // for continuous colorscales: fill with a gradient instead of explicit levels
    // value should be the colorscale [[0, c0], [v1, c1], ..., [1, cEnd]]
    opts.fillgradient = null;
    // when using a gradient, we need the data range specified separately
    opts.zrange = null;

    function component() {
        var fullLayout = gd._fullLayout;
        var gs = fullLayout._size;
        if((typeof opts.fillcolor !== 'function') &&
                (typeof opts.line.color !== 'function') &&
                !opts.fillgradient) {
            fullLayout._infolayer.selectAll('g.' + id).remove();
            return;
        }
        var zrange = opts.zrange || (d3.extent(((typeof opts.fillcolor === 'function') ?
            opts.fillcolor : opts.line.color).domain()));
        var linelevels = [];
        var filllevels = [];
        var linecolormap = typeof opts.line.color === 'function' ?
            opts.line.color : function() { return opts.line.color; };
        var fillcolormap = typeof opts.fillcolor === 'function' ?
            opts.fillcolor : function() { return opts.fillcolor; };
        var l;
        var i;

        var l0 = opts.levels.end + opts.levels.size / 100;
        var ls = opts.levels.size;
        var zr0 = (1.001 * zrange[0] - 0.001 * zrange[1]);
        var zr1 = (1.001 * zrange[1] - 0.001 * zrange[0]);
        for(i = 0; i < 1e5; i++) {
            l = opts.levels.start + i * ls;
            if(ls > 0 ? (l >= l0) : (l <= l0)) break;
            if(l > zr0 && l < zr1) linelevels.push(l);
        }

        if(opts.fillgradient) {
            filllevels = [0];
        }
        else if(typeof opts.fillcolor === 'function') {
            if(opts.filllevels) {
                l0 = opts.filllevels.end + opts.filllevels.size / 100;
                ls = opts.filllevels.size;
                for(i = 0; i < 1e5; i++) {
                    l = opts.filllevels.start + i * ls;
                    if(ls > 0 ? (l >= l0) : (l <= l0)) break;
                    if(l > zrange[0] && l < zrange[1]) filllevels.push(l);
                }
            }
            else {
                filllevels = linelevels.map(function(v) {
                    return v - opts.levels.size / 2;
                });
                filllevels.push(filllevels[filllevels.length - 1] +
                    opts.levels.size);
            }
        }
        else if(opts.fillcolor && typeof opts.fillcolor === 'string') {
            // doesn't matter what this value is, with a single value
            // we'll make a single fill rect covering the whole bar
            filllevels = [0];
        }

        if(opts.levels.size < 0) {
            linelevels.reverse();
            filllevels.reverse();
        }

        // now make a Plotly Axes object to scale with and draw ticks
        // TODO: does not support orientation other than right

        // we calculate pixel sizes based on the specified graph size,
        // not the actual (in case something pushed the margins around)
        // which is a little odd but avoids an odd iterative effect
        // when the colorbar itself is pushing the margins.
        // but then the fractional size is calculated based on the
        // actual graph size, so that the axes will size correctly.
        var plotHeight = gs.h;
        var plotWidth = gs.w;
        var thickPx = Math.round(opts.thickness * (opts.thicknessmode === 'fraction' ? plotWidth : 1));
        var thickFrac = thickPx / gs.w;
        var lenPx = Math.round(opts.len * (opts.lenmode === 'fraction' ? plotHeight : 1));
        var lenFrac = lenPx / gs.h;
        var xpadFrac = opts.xpad / gs.w;
        var yExtraPx = (opts.borderwidth + opts.outlinewidth) / 2;
        var ypadFrac = opts.ypad / gs.h;

        // x positioning: do it initially just for left anchor,
        // then fix at the end (since we don't know the width yet)
        var xLeft = Math.round(opts.x * gs.w + opts.xpad);
        // for dragging... this is getting a little muddled...
        var xLeftFrac = opts.x - thickFrac * ({middle: 0.5, right: 1}[opts.xanchor]||0);

        // y positioning we can do correctly from the start
        var yBottomFrac = opts.y + lenFrac * (({top: -0.5, bottom: 0.5}[opts.yanchor] || 0) - 0.5);
        var yBottomPx = Math.round(gs.h * (1 - yBottomFrac));
        var yTopPx = yBottomPx - lenPx;

        var titleEl;

        var cbAxisIn = {
            type: 'linear',
            range: zrange,
            tickmode: opts.tickmode,
            nticks: opts.nticks,
            tick0: opts.tick0,
            dtick: opts.dtick,
            tickvals: opts.tickvals,
            ticktext: opts.ticktext,
            ticks: opts.ticks,
            ticklen: opts.ticklen,
            tickwidth: opts.tickwidth,
            tickcolor: opts.tickcolor,
            showticklabels: opts.showticklabels,
            tickfont: opts.tickfont,
            tickangle: opts.tickangle,
            tickformat: opts.tickformat,
            exponentformat: opts.exponentformat,
            separatethousands: opts.separatethousands,
            showexponent: opts.showexponent,
            showtickprefix: opts.showtickprefix,
            tickprefix: opts.tickprefix,
            showticksuffix: opts.showticksuffix,
            ticksuffix: opts.ticksuffix,
            title: opts.title,
            showline: true,
            anchor: 'free',
            side: 'right',
            position: 1
        };
        var cbAxisOut = {
            type: 'linear',
            _id: 'y' + id
        };
        var axisOptions = {
            letter: 'y',
            font: fullLayout.font,
            noHover: true,
            noTickson: true,
            calendar: fullLayout.calendar  // not really necessary (yet?)
        };

        // Coerce w.r.t. Axes layoutAttributes:
        // re-use axes.js logic without updating _fullData
        function coerce(attr, dflt) {
            return Lib.coerce(cbAxisIn, cbAxisOut, axisLayoutAttrs, attr, dflt);
        }

        // Prepare the Plotly axis object
        handleAxisDefaults(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout);
        handleAxisPositionDefaults(cbAxisIn, cbAxisOut, coerce, axisOptions);

        // position can't go in through supplyDefaults
        // because that restricts it to [0,1]
        cbAxisOut.position = opts.x + xpadFrac + thickFrac;

        // save for other callers to access this axis
        component.axis = cbAxisOut;

        if(['top', 'bottom'].indexOf(opts.title.side) !== -1) {
            cbAxisOut.title.side = opts.title.side;
            cbAxisOut.titlex = opts.x + xpadFrac;
            cbAxisOut.titley = yBottomFrac +
                (opts.title.side === 'top' ? lenFrac - ypadFrac : ypadFrac);
        }

        if(opts.line.color && opts.tickmode === 'auto') {
            cbAxisOut.tickmode = 'linear';
            cbAxisOut.tick0 = opts.levels.start;
            var dtick = opts.levels.size;
            // expand if too many contours, so we don't get too many ticks
            var autoNtick = Lib.constrain((yBottomPx - yTopPx) / 50, 4, 15) + 1;
            var dtFactor = (zrange[1] - zrange[0]) / ((opts.nticks || autoNtick) * dtick);
            if(dtFactor > 1) {
                var dtexp = Math.pow(10, Math.floor(
                    Math.log(dtFactor) / Math.LN10));
                dtick *= dtexp * Lib.roundUp(dtFactor / dtexp, [2, 5, 10]);
                // if the contours are at round multiples, reset tick0
                // so they're still at round multiples. Otherwise,
                // keep the first label on the first contour level
                if((Math.abs(opts.levels.start) /
                        opts.levels.size + 1e-6) % 1 < 2e-6) {
                    cbAxisOut.tick0 = 0;
                }
            }
            cbAxisOut.dtick = dtick;
        }

        // set domain after init, because we may want to
        // allow it outside [0,1]
        cbAxisOut.domain = [
            yBottomFrac + ypadFrac,
            yBottomFrac + lenFrac - ypadFrac
        ];
        cbAxisOut.setScale();

        // now draw the elements
        var container = Lib.ensureSingle(fullLayout._infolayer, 'g', id, function(s) {
            s.classed(cn.colorbar, true)
                .each(function() {
                    var s = d3.select(this);
                    s.append('rect').classed(cn.cbbg, true);
                    s.append('g').classed(cn.cbfills, true);
                    s.append('g').classed(cn.cblines, true);
                    s.append('g').classed(cn.cbaxis, true).classed(cn.crisp, true);
                    s.append('g').classed(cn.cbtitleunshift, true)
                        .append('g').classed(cn.cbtitle, true);
                    s.append('rect').classed(cn.cboutline, true);
                    s.select('.cbtitle').datum(0);
                });
        });

        container.attr('transform', 'translate(' + Math.round(gs.l) +
            ',' + Math.round(gs.t) + ')');
        // TODO: this opposite transform is a hack until we make it
        // more rational which items get this offset
        var titleCont = container.select('.cbtitleunshift')
            .attr('transform', 'translate(-' +
                Math.round(gs.l) + ',-' +
                Math.round(gs.t) + ')');

        var axisLayer = container.select('.cbaxis');

        var titleHeight = 0;
        if(['top', 'bottom'].indexOf(opts.title.side) !== -1) {
            // draw the title so we know how much room it needs
            // when we squish the axis. This one only applies to
            // top or bottom titles, not right side.
            var x = gs.l + (opts.x + xpadFrac) * gs.w;
            var fontSize = cbAxisOut.title.font.size;
            var y;

            if(opts.title.side === 'top') {
                y = (1 - (yBottomFrac + lenFrac - ypadFrac)) * gs.h +
                    gs.t + 3 + fontSize * 0.75;
            }
            else {
                y = (1 - (yBottomFrac + ypadFrac)) * gs.h +
                    gs.t - 3 - fontSize * 0.25;
            }
            drawTitle(cbAxisOut._id + 'title', {
                attributes: {x: x, y: y, 'text-anchor': 'start'}
            });
        }

        function drawAxis() {
            if(['top', 'bottom'].indexOf(opts.title.side) !== -1) {
                // squish the axis top to make room for the title
                var titleGroup = container.select('.cbtitle');
                var titleText = titleGroup.select('text');
                var titleTrans = [-opts.outlinewidth / 2, opts.outlinewidth / 2];
                var mathJaxNode = titleGroup
                    .select('.h' + cbAxisOut._id + 'title-math-group')
                    .node();
                var lineSize = 15.6;
                if(titleText.node()) {
                    lineSize =
                        parseInt(titleText.node().style.fontSize, 10) * LINE_SPACING;
                }
                if(mathJaxNode) {
                    titleHeight = Drawing.bBox(mathJaxNode).height;
                    if(titleHeight > lineSize) {
                        // not entirely sure how mathjax is doing
                        // vertical alignment, but this seems to work.
                        titleTrans[1] -= (titleHeight - lineSize) / 2;
                    }
                }
                else if(titleText.node() &&
                        !titleText.classed(cn.jsPlaceholder)) {
                    titleHeight = Drawing.bBox(titleText.node()).height;
                }
                if(titleHeight) {
                    // buffer btwn colorbar and title
                    // TODO: configurable
                    titleHeight += 5;

                    if(opts.title.side === 'top') {
                        cbAxisOut.domain[1] -= titleHeight / gs.h;
                        titleTrans[1] *= -1;
                    }
                    else {
                        cbAxisOut.domain[0] += titleHeight / gs.h;
                        var nlines = svgTextUtils.lineCount(titleText);
                        titleTrans[1] += (1 - nlines) * lineSize;
                    }

                    titleGroup.attr('transform',
                        'translate(' + titleTrans + ')');

                    cbAxisOut.setScale();
                }
            }

            container.selectAll('.cbfills,.cblines')
                .attr('transform', 'translate(0,' +
                    Math.round(gs.h * (1 - cbAxisOut.domain[1])) + ')');

            axisLayer.attr('transform', 'translate(0,' + Math.round(-gs.t) + ')');

            var fills = container.select('.cbfills')
                .selectAll('rect.cbfill')
                    .data(filllevels);
            fills.enter().append('rect')
                .classed(cn.cbfill, true)
                .style('stroke', 'none');
            fills.exit().remove();

            var zBounds = zrange
                .map(cbAxisOut.c2p)
                .map(Math.round)
                .sort(function(a, b) { return a - b; });

            fills.each(function(d, i) {
                var z = [
                    (i === 0) ? zrange[0] :
                        (filllevels[i] + filllevels[i - 1]) / 2,
                    (i === filllevels.length - 1) ? zrange[1] :
                        (filllevels[i] + filllevels[i + 1]) / 2
                ]
                .map(cbAxisOut.c2p)
                .map(Math.round);

                // offset the side adjoining the next rectangle so they
                // overlap, to prevent antialiasing gaps
                z[1] = Lib.constrain(z[1] + (z[1] > z[0]) ? 1 : -1, zBounds[0], zBounds[1]);

                // Colorbar cannot currently support opacities so we
                // use an opaque fill even when alpha channels present
                var fillEl = d3.select(this).attr({
                    x: xLeft,
                    width: Math.max(thickPx, 2),
                    y: d3.min(z),
                    height: Math.max(d3.max(z) - d3.min(z), 2),
                });

                if(opts.fillgradient) {
                    Drawing.gradient(fillEl, gd, id, 'vertical',
                        opts.fillgradient, 'fill');
                }
                else {
                    // Tinycolor can't handle exponents and
                    // at this scale, removing it makes no difference.
                    var colorString = fillcolormap(d).replace('e-', '');
                    fillEl.attr('fill', tinycolor(colorString).toHexString());
                }
            });

            var lines = container.select('.cblines')
                .selectAll('path.cbline')
                    .data(opts.line.color && opts.line.width ?
                        linelevels : []);
            lines.enter().append('path')
                .classed(cn.cbline, true);
            lines.exit().remove();
            lines.each(function(d) {
                d3.select(this)
                    .attr('d', 'M' + xLeft + ',' +
                        (Math.round(cbAxisOut.c2p(d)) + (opts.line.width / 2) % 1) +
                        'h' + thickPx)
                    .call(Drawing.lineGroupStyle,
                        opts.line.width, linecolormap(d), opts.line.dash);
            });

            // force full redraw of labels and ticks
            axisLayer.selectAll('g.' + cbAxisOut._id + 'tick,path').remove();

            // separate out axis and title drawing,
            // so we don't need such complicated logic in Titles.draw
            // if title is on the top or bottom, we've already drawn it
            // this title call only handles side=right
            return Lib.syncOrAsync([
                function() {
                    var shift = xLeft + thickPx +
                        (opts.outlinewidth || 0) / 2 - (opts.ticks === 'outside' ? 1 : 0);

                    var vals = Axes.calcTicks(cbAxisOut);
                    var transFn = Axes.makeTransFn(cbAxisOut);
                    var tickSign = Axes.getTickSigns(cbAxisOut)[2];

                    Axes.drawTicks(gd, cbAxisOut, {
                        vals: cbAxisOut.ticks === 'inside' ? Axes.clipEnds(cbAxisOut, vals) : vals,
                        layer: axisLayer,
                        path: Axes.makeTickPath(cbAxisOut, shift, tickSign),
                        transFn: transFn
                    });

                    return Axes.drawLabels(gd, cbAxisOut, {
                        vals: vals,
                        layer: axisLayer,
                        transFn: transFn,
                        labelFns: Axes.makeLabelFns(cbAxisOut, shift)
                    });
                },
                function() {
                    if(['top', 'bottom'].indexOf(opts.title.side) === -1) {
                        var fontSize = cbAxisOut.title.font.size;
                        var y = cbAxisOut._offset + cbAxisOut._length / 2;
                        var x = gs.l + (cbAxisOut.position || 0) * gs.w + ((cbAxisOut.side === 'right') ?
                            10 + fontSize * ((cbAxisOut.showticklabels ? 1 : 0.5)) :
                            -10 - fontSize * ((cbAxisOut.showticklabels ? 0.5 : 0)));

                        // the 'h' + is a hack to get around the fact that
                        // convertToTspans rotates any 'y...' class by 90 degrees.
                        // TODO: find a better way to control this.
                        drawTitle('h' + cbAxisOut._id + 'title', {
                            avoid: {
                                selection: d3.select(gd).selectAll('g.' + cbAxisOut._id + 'tick'),
                                side: opts.title.side,
                                offsetLeft: gs.l,
                                offsetTop: 0,
                                maxShift: fullLayout.width
                            },
                            attributes: {x: x, y: y, 'text-anchor': 'middle'},
                            transform: {rotate: '-90', offset: 0}
                        });
                    }
                }]);
        }

        function drawTitle(titleClass, titleOpts) {
            var dfltTitleOpts = {
                propContainer: cbAxisOut,
                propName: getPropName('title'),
                traceIndex: getTrace().index,
                placeholder: fullLayout._dfltTitle.colorbar,
                containerGroup: container.select('.cbtitle')
            };

            // this class-to-rotate thing with convertToTspans is
            // getting hackier and hackier... delete groups with the
            // wrong class (in case earlier the colorbar was drawn on
            // a different side, I think?)
            var otherClass = titleClass.charAt(0) === 'h' ?
                titleClass.substr(1) : ('h' + titleClass);
            container.selectAll('.' + otherClass + ',.' + otherClass + '-math-group')
                .remove();

            Titles.draw(gd, titleClass,
                extendFlat(dfltTitleOpts, titleOpts || {}));
        }

        function positionCB() {
            // wait for the axis & title to finish rendering before
            // continuing positioning
            // TODO: why are we redrawing multiple times now with this?
            // I guess autoMargin doesn't like being post-promise?
            var innerWidth = thickPx + opts.outlinewidth / 2 +
                    Drawing.bBox(axisLayer.node()).width;
            titleEl = titleCont.select('text');
            if(titleEl.node() && !titleEl.classed(cn.jsPlaceholder)) {
                var mathJaxNode = titleCont
                        .select('.h' + cbAxisOut._id + 'title-math-group')
                        .node();
                var titleWidth;
                if(mathJaxNode &&
                        ['top', 'bottom'].indexOf(opts.title.side) !== -1) {
                    titleWidth = Drawing.bBox(mathJaxNode).width;
                }
                else {
                    // note: the formula below works for all title sides,
                    // (except for top/bottom mathjax, above)
                    // but the weird gs.l is because the titleunshift
                    // transform gets removed by Drawing.bBox
                    titleWidth =
                        Drawing.bBox(titleCont.node()).right -
                        xLeft - gs.l;
                }
                innerWidth = Math.max(innerWidth, titleWidth);
            }

            var outerwidth = 2 * opts.xpad + innerWidth +
                    opts.borderwidth + opts.outlinewidth / 2;
            var outerheight = yBottomPx - yTopPx;

            container.select('.cbbg').attr({
                x: xLeft - opts.xpad -
                    (opts.borderwidth + opts.outlinewidth) / 2,
                y: yTopPx - yExtraPx,
                width: Math.max(outerwidth, 2),
                height: Math.max(outerheight + 2 * yExtraPx, 2)
            })
            .call(Color.fill, opts.bgcolor)
            .call(Color.stroke, opts.bordercolor)
            .style({'stroke-width': opts.borderwidth});

            container.selectAll('.cboutline').attr({
                x: xLeft,
                y: yTopPx + opts.ypad +
                    (opts.title.side === 'top' ? titleHeight : 0),
                width: Math.max(thickPx, 2),
                height: Math.max(outerheight - 2 * opts.ypad - titleHeight, 2)
            })
            .call(Color.stroke, opts.outlinecolor)
            .style({
                fill: 'None',
                'stroke-width': opts.outlinewidth
            });

            // fix positioning for xanchor!='left'
            var xoffset = ({center: 0.5, right: 1}[opts.xanchor] || 0) *
                outerwidth;
            container.attr('transform',
                'translate(' + (gs.l - xoffset) + ',' + gs.t + ')');

            // auto margin adjustment
            var marginOpts = {};
            var tFrac = FROM_TL[opts.yanchor];
            var bFrac = FROM_BR[opts.yanchor];
            if(opts.lenmode === 'pixels') {
                marginOpts.y = opts.y;
                marginOpts.t = outerheight * tFrac;
                marginOpts.b = outerheight * bFrac;
            }
            else {
                marginOpts.t = marginOpts.b = 0;
                marginOpts.yt = opts.y + opts.len * tFrac;
                marginOpts.yb = opts.y - opts.len * bFrac;
            }

            var lFrac = FROM_TL[opts.xanchor];
            var rFrac = FROM_BR[opts.xanchor];
            if(opts.thicknessmode === 'pixels') {
                marginOpts.x = opts.x;
                marginOpts.l = outerwidth * lFrac;
                marginOpts.r = outerwidth * rFrac;
            }
            else {
                var extraThickness = outerwidth - thickPx;
                marginOpts.l = extraThickness * lFrac;
                marginOpts.r = extraThickness * rFrac;
                marginOpts.xl = opts.x - opts.thickness * lFrac;
                marginOpts.xr = opts.x + opts.thickness * rFrac;
            }
            Plots.autoMargin(gd, id, marginOpts);
        }

        var cbDone = Lib.syncOrAsync([
            Plots.previousPromises,
            drawAxis,
            Plots.previousPromises,
            positionCB
        ], gd);

        if(cbDone && cbDone.then) (gd._promises || []).push(cbDone);

        // dragging...
        if(gd._context.edits.colorbarPosition) {
            var t0,
                xf,
                yf;

            dragElement.init({
                element: container.node(),
                gd: gd,
                prepFn: function() {
                    t0 = container.attr('transform');
                    setCursor(container);
                },
                moveFn: function(dx, dy) {
                    container.attr('transform',
                        t0 + ' ' + 'translate(' + dx + ',' + dy + ')');

                    xf = dragElement.align(xLeftFrac + (dx / gs.w), thickFrac,
                        0, 1, opts.xanchor);
                    yf = dragElement.align(yBottomFrac - (dy / gs.h), lenFrac,
                        0, 1, opts.yanchor);

                    var csr = dragElement.getCursor(xf, yf,
                        opts.xanchor, opts.yanchor);
                    setCursor(container, csr);
                },
                doneFn: function() {
                    setCursor(container);

                    if(xf !== undefined && yf !== undefined) {
                        var update = {};
                        update[getPropName('x')] = xf;
                        update[getPropName('y')] = yf;
                        Registry.call('_guiRestyle', gd, update, getTrace().index);
                    }
                }
            });
        }
        return cbDone;
    }

    function getTrace() {
        var idNum = id.substr(2);
        for(var i = 0; i < gd._fullData.length; i++) {
            var trace = gd._fullData[i];
            if(trace.uid === idNum) return trace;
        }
    }

    function getPropName(suffix) {
        var trace = getTrace();
        var propName = 'colorbar.';
        var containerName = trace._module.colorbar.container;
        if(containerName) propName = containerName + '.' + propName;
        return propName + suffix;
    }

    // setter/getters for every item defined in opts
    Object.keys(opts).forEach(function(name) {
        component[name] = function(v) {
            // getter
            if(!arguments.length) return opts[name];

            // setter - for multi-part properties,
            // set only the parts that are provided
            opts[name] = Lib.isPlainObject(opts[name]) ?
                 Lib.extendFlat(opts[name], v) :
                 v;

            return component;
        };
    });

    // or use .options to set multiple options at once via a dictionary
    component.options = function(o) {
        for(var name in o) {
            // in case something random comes through
            // that's not an option, ignore it
            if(typeof component[name] === 'function') {
                component[name](o[name]);
            }
        }
        return component;
    };

    component._opts = opts;

    return component;
};

},{"../../constants/alignment":669,"../../lib":697,"../../lib/extend":687,"../../lib/setcursor":717,"../../lib/svg_text_utils":721,"../../plots/cartesian/axes":745,"../../plots/cartesian/axis_defaults":747,"../../plots/cartesian/layout_attributes":757,"../../plots/cartesian/position_defaults":760,"../../plots/plots":807,"../../registry":826,"../color":574,"../dragelement":592,"../drawing":595,"../titles":662,"./attributes":575,"./constants":577,"d3":151,"tinycolor2":518}],580:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');


module.exports = function hasColorbar(container) {
    return Lib.isPlainObject(container.colorbar);
};

},{"../../lib":697}],581:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var palettes = _dereq_('./scales.js').scales;
var paletteStr = Object.keys(palettes);

function code(s) {
    return '`' + s + '`';
}

/**
 * Make colorscale attribute declarations for
 *
 * - colorscale,
 * - (c|z)auto, (c|z)min, (c|z)max,
 * - autocolorscale, reversescale,
 * - showscale (optionally)
 * - color (optionally)
 *
 * @param {string} context (dflt: '', i.e. from trace root):
 *     the container this is in ('', *marker*, *marker.line* etc)
 *
 * @param {object} opts:
 *   - cLetter {string} (dflt: 'c'):
 *     leading letter for 'min', 'max and 'auto' attribute (either 'z' or 'c')
 *
 *   - colorAttr {string} (dflt: 'z' if `cLetter: 'z'`, 'color' if `cLetter: 'c'`):
 *     (for descriptions) sets the name of the color attribute that maps to the colorscale.
 *
 *     N.B. if `colorAttr: 'color'`, we include the `color` declaration here.
 *
 *   - onlyIfNumerical {string} (dflt: false' if `cLetter: 'z'`, true if `cLetter: 'c'`):
 *     (for descriptions) set to true if colorscale attribute only
 *
 *   - colorscaleDflt {string}:
 *     overrides the colorscale dflt
 *
 *   - autoColorDflt {boolean} (dflt true):
 *     normally autocolorscale.dflt is `true`, but pass `false` to override
 *
 *   - noScale {boolean} (dflt: true if `context: 'marker.line'`, false otherwise):
 *     set to `false` to not include showscale attribute (e.g. for 'marker.line')
 *
 *   - showScaleDflt {boolean} (dflt: true if `cLetter: 'z'`, false otherwise)
 *
 *   - editTypeOverride {boolean} (dflt: ''):
 *     most of these attributes already require a recalc, but the ones that do not
 *     have editType *style* or *plot* unless you override (presumably with *calc*)
 *
 *   - anim {boolean) (dflt: undefined): is 'color' animatable?
 *
 * @return {object}
 */
module.exports = function colorScaleAttrs(context, opts) {
    context = context || '';
    opts = opts || {};

    var cLetter = opts.cLetter || 'c';
    var onlyIfNumerical = ('onlyIfNumerical' in opts) ? opts.onlyIfNumerical : Boolean(context);
    var noScale = ('noScale' in opts) ? opts.noScale : context === 'marker.line';
    var showScaleDflt = ('showScaleDflt' in opts) ? opts.showScaleDflt : cLetter === 'z';
    var colorscaleDflt = typeof opts.colorscaleDflt === 'string' ? palettes[opts.colorscaleDflt] : null;
    var editTypeOverride = opts.editTypeOverride || '';
    var contextHead = context ? (context + '.') : '';

    var colorAttr, colorAttrFull;

    if('colorAttr' in opts) {
        colorAttr = opts.colorAttr;
        colorAttrFull = opts.colorAttr;
    } else {
        colorAttr = {z: 'z', c: 'color'}[cLetter];
        colorAttrFull = 'in ' + code(contextHead + colorAttr);
    }

    var effectDesc = onlyIfNumerical ?
        ' Has an effect only if ' + colorAttrFull + 'is set to a numerical array.' :
        '';

    var auto = cLetter + 'auto';
    var min = cLetter + 'min';
    var max = cLetter + 'max';
    var mid = cLetter + 'mid';
    var autoFull = code(contextHead + auto);
    var minFull = code(contextHead + min);
    var maxFull = code(contextHead + max);
    var minmaxFull = minFull + ' and ' + maxFull;
    var autoImpliedEdits = {};
    autoImpliedEdits[min] = autoImpliedEdits[max] = undefined;
    var minmaxImpliedEdits = {};
    minmaxImpliedEdits[auto] = false;

    var attrs = {};

    if(colorAttr === 'color') {
        attrs.color = {
            valType: 'color',
            arrayOk: true,
            
            editType: editTypeOverride || 'style',
            
        };

        if(opts.anim) {
            attrs.color.anim = true;
        }
    }

    attrs[auto] = {
        valType: 'boolean',
        
        dflt: true,
        editType: 'calc',
        impliedEdits: autoImpliedEdits,
        
    };

    attrs[min] = {
        valType: 'number',
        
        dflt: null,
        editType: editTypeOverride || 'plot',
        impliedEdits: minmaxImpliedEdits,
        
    };

    attrs[max] = {
        valType: 'number',
        
        dflt: null,
        editType: editTypeOverride || 'plot',
        impliedEdits: minmaxImpliedEdits,
        
    };

    attrs[mid] = {
        valType: 'number',
        
        dflt: null,
        editType: 'calc',
        impliedEdits: autoImpliedEdits,
        
    };

    attrs.colorscale = {
        valType: 'colorscale',
        
        editType: 'calc',
        dflt: colorscaleDflt,
        impliedEdits: {autocolorscale: false},
        
    };

    attrs.autocolorscale = {
        valType: 'boolean',
        
        // gets overrode in 'heatmap' & 'surface' for backwards comp.
        dflt: opts.autoColorDflt === false ? false : true,
        editType: 'calc',
        impliedEdits: {colorscale: undefined},
        
    };

    attrs.reversescale = {
        valType: 'boolean',
        
        dflt: false,
        editType: 'plot',
        
    };

    if(!noScale) {
        attrs.showscale = {
            valType: 'boolean',
            
            dflt: showScaleDflt,
            editType: 'calc',
            
        };
    }

    return attrs;
};

},{"./scales.js":589}],582:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

module.exports = function calc(gd, trace, opts) {
    var fullLayout = gd._fullLayout;
    var vals = opts.vals;
    var containerStr = opts.containerStr;
    var cLetter = opts.cLetter;

    var container = containerStr ?
        Lib.nestedProperty(trace, containerStr).get() :
        trace;

    var autoAttr = cLetter + 'auto';
    var minAttr = cLetter + 'min';
    var maxAttr = cLetter + 'max';
    var midAttr = cLetter + 'mid';
    var auto = container[autoAttr];
    var min = container[minAttr];
    var max = container[maxAttr];
    var mid = container[midAttr];
    var scl = container.colorscale;

    if(auto !== false || min === undefined) {
        min = Lib.aggNums(Math.min, null, vals);
    }

    if(auto !== false || max === undefined) {
        max = Lib.aggNums(Math.max, null, vals);
    }

    if(auto !== false && mid !== undefined) {
        if(max - mid > mid - min) {
            min = mid - (max - mid);
        }
        else if(max - mid < mid - min) {
            max = mid + (mid - min);
        }
    }

    if(min === max) {
        min -= 0.5;
        max += 0.5;
    }

    container['_' + minAttr] = container[minAttr] = min;
    container['_' + maxAttr] = container[maxAttr] = max;

    if(container.autocolorscale) {
        if(min * max < 0) scl = fullLayout.colorscale.diverging;
        else if(min >= 0) scl = fullLayout.colorscale.sequential;
        else scl = fullLayout.colorscale.sequentialminus;

        container._colorscale = container.colorscale = scl;
    }
};

},{"../../lib":697}],583:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var hasColorscale = _dereq_('./helpers').hasColorscale;

module.exports = function crossTraceDefaults(fullData) {
    function replace(cont, k) {
        var val = cont['_' + k];
        if(val !== undefined) {
            cont[k] = val;
        }
    }

    function relinkColorAtts(trace, cAttrs) {
        var cont = cAttrs.container ?
            Lib.nestedProperty(trace, cAttrs.container).get() :
            trace;

        if(cont) {
            var isAuto = cont.zauto || cont.cauto;
            var minAttr = cAttrs.min;
            var maxAttr = cAttrs.max;

            if(isAuto || cont[minAttr] === undefined) {
                replace(cont, minAttr);
            }
            if(isAuto || cont[maxAttr] === undefined) {
                replace(cont, maxAttr);
            }
            if(cont.autocolorscale) {
                replace(cont, 'colorscale');
            }
        }
    }

    for(var i = 0; i < fullData.length; i++) {
        var trace = fullData[i];
        var colorbar = trace._module.colorbar;

        if(colorbar) {
            if(Array.isArray(colorbar)) {
                for(var j = 0; j < colorbar.length; j++) {
                    relinkColorAtts(trace, colorbar[j]);
                }
            } else {
                relinkColorAtts(trace, colorbar);
            }
        }

        // TODO could generalize _module.colorscale and use it here?

        if(hasColorscale(trace, 'marker.line')) {
            relinkColorAtts(trace, {
                container: 'marker.line',
                min: 'cmin',
                max: 'cmax'
            });
        }

        if(hasColorscale(trace, 'line')) {
            relinkColorAtts(trace, {
                container: 'line',
                min: 'cmin',
                max: 'cmax'
            });
        }
    }
};

},{"../../lib":697,"./helpers":585}],584:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');
var hasColorbar = _dereq_('../colorbar/has_colorbar');
var colorbarDefaults = _dereq_('../colorbar/defaults');

var isValidScale = _dereq_('./scales').isValid;

function npMaybe(cont, prefix) {
    var containerStr = prefix.slice(0, prefix.length - 1);
    return prefix ?
        Lib.nestedProperty(cont, containerStr).get() || {} :
        cont;
}

module.exports = function colorScaleDefaults(traceIn, traceOut, layout, coerce, opts) {
    var prefix = opts.prefix;
    var cLetter = opts.cLetter;
    var containerIn = npMaybe(traceIn, prefix);
    var containerOut = npMaybe(traceOut, prefix);
    var template = npMaybe(traceOut._template || {}, prefix) || {};

    var minIn = containerIn[cLetter + 'min'];
    var maxIn = containerIn[cLetter + 'max'];
    var validMinMax = isNumeric(minIn) && isNumeric(maxIn) && (minIn < maxIn);
    var auto = coerce(prefix + cLetter + 'auto', !validMinMax);

    if(auto) {
        coerce(prefix + cLetter + 'mid');
    } else {
        coerce(prefix + cLetter + 'min');
        coerce(prefix + cLetter + 'max');
    }

    // handles both the trace case (autocolorscale is false by default) and
    // the marker and marker.line case (autocolorscale is true by default)
    var sclIn = containerIn.colorscale;
    var sclTemplate = template.colorscale;
    var autoColorscaleDflt;
    if(sclIn !== undefined) autoColorscaleDflt = !isValidScale(sclIn);
    if(sclTemplate !== undefined) autoColorscaleDflt = !isValidScale(sclTemplate);
    coerce(prefix + 'autocolorscale', autoColorscaleDflt);

    coerce(prefix + 'colorscale');
    coerce(prefix + 'reversescale');

    if(!opts.noScale && prefix !== 'marker.line.') {
        // handles both the trace case where the dflt is listed in attributes and
        // the marker case where the dflt is determined by hasColorbar
        var showScaleDflt;
        if(prefix) showScaleDflt = hasColorbar(containerIn);

        var showScale = coerce(prefix + 'showscale', showScaleDflt);
        if(showScale) colorbarDefaults(containerIn, containerOut, layout);
    }
};

},{"../../lib":697,"../colorbar/defaults":578,"../colorbar/has_colorbar":580,"./scales":589,"fast-isnumeric":218}],585:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var tinycolor = _dereq_('tinycolor2');
var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');
var Color = _dereq_('../color');

var isValidScale = _dereq_('./scales').isValid;

function hasColorscale(trace, containerStr) {
    var container = containerStr ?
        Lib.nestedProperty(trace, containerStr).get() || {} :
        trace;
    var color = container.color;

    var isArrayWithOneNumber = false;
    if(Lib.isArrayOrTypedArray(color)) {
        for(var i = 0; i < color.length; i++) {
            if(isNumeric(color[i])) {
                isArrayWithOneNumber = true;
                break;
            }
        }
    }

    return (
        Lib.isPlainObject(container) && (
            isArrayWithOneNumber ||
            container.showscale === true ||
            (isNumeric(container.cmin) && isNumeric(container.cmax)) ||
            isValidScale(container.colorscale) ||
            Lib.isPlainObject(container.colorbar)
        )
    );
}

/**
 * Extract colorscale into numeric domain and color range.
 *
 * @param {object} cont colorscale container (e.g. trace, marker)
 *  - colorscale {array of arrays}
 *  - cmin/zmin {number}
 *  - cmax/zmax {number}
 *  - reversescale {boolean}
 * @param {object} opts
 *  - cLetter {string} 'c' (for cmin/cmax) or 'z' (for zmin/zmax)
 *
 * @return {object}
 *  - domain {array}
 *  - range {array}
 */
function extractScale(cont, opts) {
    var cLetter = opts.cLetter;

    var scl = cont.reversescale ?
        flipScale(cont.colorscale) :
        cont.colorscale;

    // minimum color value (used to clamp scale)
    var cmin = cont[cLetter + 'min'];
    // maximum color value (used to clamp scale)
    var cmax = cont[cLetter + 'max'];

    var N = scl.length;
    var domain = new Array(N);
    var range = new Array(N);

    for(var i = 0; i < N; i++) {
        var si = scl[i];
        domain[i] = cmin + si[0] * (cmax - cmin);
        range[i] = si[1];
    }

    return {
        domain: domain,
        range: range
    };
}

function flipScale(scl) {
    var N = scl.length;
    var sclNew = new Array(N);

    for(var i = N - 1, j = 0; i >= 0; i--, j++) {
        var si = scl[i];
        sclNew[j] = [1 - si[0], si[1]];
    }
    return sclNew;
}

/**
 * General colorscale function generator.
 *
 * @param {object} specs output of Colorscale.extractScale or precomputed domain, range.
 *  - domain {array}
 *  - range {array}
 *
 * @param {object} opts
 *  - noNumericCheck {boolean} if true, scale func bypasses numeric checks
 *  - returnArray {boolean} if true, scale func return 4-item array instead of color strings
 *
 * @return {function}
 */
function makeColorScaleFunc(specs, opts) {
    opts = opts || {};

    var domain = specs.domain;
    var range = specs.range;
    var N = range.length;
    var _range = new Array(N);

    for(var i = 0; i < N; i++) {
        var rgba = tinycolor(range[i]).toRgb();
        _range[i] = [rgba.r, rgba.g, rgba.b, rgba.a];
    }

    var _sclFunc = d3.scale.linear()
        .domain(domain)
        .range(_range)
        .clamp(true);

    var noNumericCheck = opts.noNumericCheck;
    var returnArray = opts.returnArray;
    var sclFunc;

    if(noNumericCheck && returnArray) {
        sclFunc = _sclFunc;
    }
    else if(noNumericCheck) {
        sclFunc = function(v) {
            return colorArray2rbga(_sclFunc(v));
        };
    }
    else if(returnArray) {
        sclFunc = function(v) {
            if(isNumeric(v)) return _sclFunc(v);
            else if(tinycolor(v).isValid()) return v;
            else return Color.defaultLine;
        };
    }
    else {
        sclFunc = function(v) {
            if(isNumeric(v)) return colorArray2rbga(_sclFunc(v));
            else if(tinycolor(v).isValid()) return v;
            else return Color.defaultLine;
        };
    }

    // colorbar draw looks into the d3 scale closure for domain and range

    sclFunc.domain = _sclFunc.domain;

    sclFunc.range = function() { return range; };

    return sclFunc;
}

function colorArray2rbga(colorArray) {
    var colorObj = {
        r: colorArray[0],
        g: colorArray[1],
        b: colorArray[2],
        a: colorArray[3]
    };

    return tinycolor(colorObj).toRgbString();
}

module.exports = {
    hasColorscale: hasColorscale,
    extractScale: extractScale,
    flipScale: flipScale,
    makeColorScaleFunc: makeColorScaleFunc
};

},{"../../lib":697,"../color":574,"./scales":589,"d3":151,"fast-isnumeric":218,"tinycolor2":518}],586:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scales = _dereq_('./scales');
var helpers = _dereq_('./helpers');

module.exports = {
    moduleType: 'component',
    name: 'colorscale',

    attributes: _dereq_('./attributes'),
    layoutAttributes: _dereq_('./layout_attributes'),

    supplyLayoutDefaults: _dereq_('./layout_defaults'),
    handleDefaults: _dereq_('./defaults'),
    crossTraceDefaults: _dereq_('./cross_trace_defaults'),

    calc: _dereq_('./calc'),

    // ./scales.js is required in lib/coerce.js ;
    // it needs to be a seperate module to avoid circular a dependency
    scales: scales.scales,
    defaultScale: scales.defaultScale,
    getScale: scales.get,
    isValidScale: scales.isValid,

    hasColorscale: helpers.hasColorscale,
    flipScale: helpers.flipScale,
    extractScale: helpers.extractScale,
    makeColorScaleFunc: helpers.makeColorScaleFunc
};

},{"./attributes":581,"./calc":582,"./cross_trace_defaults":583,"./defaults":584,"./helpers":585,"./layout_attributes":587,"./layout_defaults":588,"./scales":589}],587:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scales = _dereq_('./scales').scales;

var msg = 'Note that `autocolorscale` must be true for this attribute to work.';

module.exports = {
    editType: 'calc',
    sequential: {
        valType: 'colorscale',
        dflt: scales.Reds,
        
        editType: 'calc',
        
    },
    sequentialminus: {
        valType: 'colorscale',
        dflt: scales.Blues,
        
        editType: 'calc',
        
    },
    diverging: {
        valType: 'colorscale',
        dflt: scales.RdBu,
        
        editType: 'calc',
        
    }
};

},{"./scales":589}],588:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var colorscaleAttrs = _dereq_('./layout_attributes');
var Template = _dereq_('../../plot_api/plot_template');

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
    var colorscaleIn = layoutIn.colorscale;
    var colorscaleOut = Template.newContainer(layoutOut, 'colorscale');
    function coerce(attr, dflt) {
        return Lib.coerce(colorscaleIn, colorscaleOut, colorscaleAttrs, attr, dflt);
    }

    coerce('sequential');
    coerce('sequentialminus');
    coerce('diverging');
};

},{"../../lib":697,"../../plot_api/plot_template":735,"./layout_attributes":587}],589:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var tinycolor = _dereq_('tinycolor2');

var scales = {
    'Greys': [
        [0, 'rgb(0,0,0)'], [1, 'rgb(255,255,255)']
    ],

    'YlGnBu': [
        [0, 'rgb(8,29,88)'], [0.125, 'rgb(37,52,148)'],
        [0.25, 'rgb(34,94,168)'], [0.375, 'rgb(29,145,192)'],
        [0.5, 'rgb(65,182,196)'], [0.625, 'rgb(127,205,187)'],
        [0.75, 'rgb(199,233,180)'], [0.875, 'rgb(237,248,217)'],
        [1, 'rgb(255,255,217)']
    ],

    'Greens': [
        [0, 'rgb(0,68,27)'], [0.125, 'rgb(0,109,44)'],
        [0.25, 'rgb(35,139,69)'], [0.375, 'rgb(65,171,93)'],
        [0.5, 'rgb(116,196,118)'], [0.625, 'rgb(161,217,155)'],
        [0.75, 'rgb(199,233,192)'], [0.875, 'rgb(229,245,224)'],
        [1, 'rgb(247,252,245)']
    ],

    'YlOrRd': [
        [0, 'rgb(128,0,38)'], [0.125, 'rgb(189,0,38)'],
        [0.25, 'rgb(227,26,28)'], [0.375, 'rgb(252,78,42)'],
        [0.5, 'rgb(253,141,60)'], [0.625, 'rgb(254,178,76)'],
        [0.75, 'rgb(254,217,118)'], [0.875, 'rgb(255,237,160)'],
        [1, 'rgb(255,255,204)']
    ],

    'Bluered': [
        [0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']
    ],

    // modified RdBu based on
    // www.sandia.gov/~kmorel/documents/ColorMaps/ColorMapsExpanded.pdf
    'RdBu': [
        [0, 'rgb(5,10,172)'], [0.35, 'rgb(106,137,247)'],
        [0.5, 'rgb(190,190,190)'], [0.6, 'rgb(220,170,132)'],
        [0.7, 'rgb(230,145,90)'], [1, 'rgb(178,10,28)']
    ],

    // Scale for non-negative numeric values
    'Reds': [
        [0, 'rgb(220,220,220)'], [0.2, 'rgb(245,195,157)'],
        [0.4, 'rgb(245,160,105)'], [1, 'rgb(178,10,28)']
    ],

    // Scale for non-positive numeric values
    'Blues': [
        [0, 'rgb(5,10,172)'], [0.35, 'rgb(40,60,190)'],
        [0.5, 'rgb(70,100,245)'], [0.6, 'rgb(90,120,245)'],
        [0.7, 'rgb(106,137,247)'], [1, 'rgb(220,220,220)']
    ],

    'Picnic': [
        [0, 'rgb(0,0,255)'], [0.1, 'rgb(51,153,255)'],
        [0.2, 'rgb(102,204,255)'], [0.3, 'rgb(153,204,255)'],
        [0.4, 'rgb(204,204,255)'], [0.5, 'rgb(255,255,255)'],
        [0.6, 'rgb(255,204,255)'], [0.7, 'rgb(255,153,255)'],
        [0.8, 'rgb(255,102,204)'], [0.9, 'rgb(255,102,102)'],
        [1, 'rgb(255,0,0)']
    ],

    'Rainbow': [
        [0, 'rgb(150,0,90)'], [0.125, 'rgb(0,0,200)'],
        [0.25, 'rgb(0,25,255)'], [0.375, 'rgb(0,152,255)'],
        [0.5, 'rgb(44,255,150)'], [0.625, 'rgb(151,255,0)'],
        [0.75, 'rgb(255,234,0)'], [0.875, 'rgb(255,111,0)'],
        [1, 'rgb(255,0,0)']
    ],

    'Portland': [
        [0, 'rgb(12,51,131)'], [0.25, 'rgb(10,136,186)'],
        [0.5, 'rgb(242,211,56)'], [0.75, 'rgb(242,143,56)'],
        [1, 'rgb(217,30,30)']
    ],

    'Jet': [
        [0, 'rgb(0,0,131)'], [0.125, 'rgb(0,60,170)'],
        [0.375, 'rgb(5,255,255)'], [0.625, 'rgb(255,255,0)'],
        [0.875, 'rgb(250,0,0)'], [1, 'rgb(128,0,0)']
    ],

    'Hot': [
        [0, 'rgb(0,0,0)'], [0.3, 'rgb(230,0,0)'],
        [0.6, 'rgb(255,210,0)'], [1, 'rgb(255,255,255)']
    ],

    'Blackbody': [
        [0, 'rgb(0,0,0)'], [0.2, 'rgb(230,0,0)'],
        [0.4, 'rgb(230,210,0)'], [0.7, 'rgb(255,255,255)'],
        [1, 'rgb(160,200,255)']
    ],

    'Earth': [
        [0, 'rgb(0,0,130)'], [0.1, 'rgb(0,180,180)'],
        [0.2, 'rgb(40,210,40)'], [0.4, 'rgb(230,230,50)'],
        [0.6, 'rgb(120,70,20)'], [1, 'rgb(255,255,255)']
    ],

    'Electric': [
        [0, 'rgb(0,0,0)'], [0.15, 'rgb(30,0,100)'],
        [0.4, 'rgb(120,0,100)'], [0.6, 'rgb(160,90,0)'],
        [0.8, 'rgb(230,200,0)'], [1, 'rgb(255,250,220)']
    ],

    'Viridis': [
        [0, '#440154'], [0.06274509803921569, '#48186a'],
        [0.12549019607843137, '#472d7b'], [0.18823529411764706, '#424086'],
        [0.25098039215686274, '#3b528b'], [0.3137254901960784, '#33638d'],
        [0.3764705882352941, '#2c728e'], [0.4392156862745098, '#26828e'],
        [0.5019607843137255, '#21918c'], [0.5647058823529412, '#1fa088'],
        [0.6274509803921569, '#28ae80'], [0.6901960784313725, '#3fbc73'],
        [0.7529411764705882, '#5ec962'], [0.8156862745098039, '#84d44b'],
        [0.8784313725490196, '#addc30'], [0.9411764705882353, '#d8e219'],
        [1, '#fde725']
    ],

    'Cividis': [
        [0.000000, 'rgb(0,32,76)'], [0.058824, 'rgb(0,42,102)'],
        [0.117647, 'rgb(0,52,110)'], [0.176471, 'rgb(39,63,108)'],
        [0.235294, 'rgb(60,74,107)'], [0.294118, 'rgb(76,85,107)'],
        [0.352941, 'rgb(91,95,109)'], [0.411765, 'rgb(104,106,112)'],
        [0.470588, 'rgb(117,117,117)'], [0.529412, 'rgb(131,129,120)'],
        [0.588235, 'rgb(146,140,120)'], [0.647059, 'rgb(161,152,118)'],
        [0.705882, 'rgb(176,165,114)'], [0.764706, 'rgb(192,177,109)'],
        [0.823529, 'rgb(209,191,102)'], [0.882353, 'rgb(225,204,92)'],
        [0.941176, 'rgb(243,219,79)'], [1.000000, 'rgb(255,233,69)']
    ]
};

var defaultScale = scales.RdBu;

function getScale(scl, dflt) {
    if(!dflt) dflt = defaultScale;
    if(!scl) return dflt;

    function parseScale() {
        try {
            scl = scales[scl] || JSON.parse(scl);
        } catch(e) {
            scl = dflt;
        }
    }

    if(typeof scl === 'string') {
        parseScale();
        // occasionally scl is double-JSON encoded...
        if(typeof scl === 'string') parseScale();
    }

    if(!isValidScaleArray(scl)) return dflt;
    return scl;
}


function isValidScaleArray(scl) {
    var highestVal = 0;

    if(!Array.isArray(scl) || scl.length < 2) return false;

    if(!scl[0] || !scl[scl.length - 1]) return false;

    if(+scl[0][0] !== 0 || +scl[scl.length - 1][0] !== 1) return false;

    for(var i = 0; i < scl.length; i++) {
        var si = scl[i];

        if(si.length !== 2 || +si[0] < highestVal || !tinycolor(si[1]).isValid()) {
            return false;
        }

        highestVal = +si[0];
    }

    return true;
}

function isValidScale(scl) {
    if(scales[scl] !== undefined) return true;
    else return isValidScaleArray(scl);
}

module.exports = {
    scales: scales,
    defaultScale: defaultScale,

    get: getScale,
    isValid: isValidScale
};

},{"tinycolor2":518}],590:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


// for automatic alignment on dragging, <1/3 means left align,
// >2/3 means right, and between is center. Pick the right fraction
// based on where you are, and return the fraction corresponding to
// that position on the object
module.exports = function align(v, dv, v0, v1, anchor) {
    var vmin = (v - v0) / (v1 - v0);
    var vmax = vmin + dv / (v1 - v0);
    var vc = (vmin + vmax) / 2;

    // explicitly specified anchor
    if(anchor === 'left' || anchor === 'bottom') return vmin;
    if(anchor === 'center' || anchor === 'middle') return vc;
    if(anchor === 'right' || anchor === 'top') return vmax;

    // automatic based on position
    if(vmin < (2 / 3) - vc) return vmin;
    if(vmax > (4 / 3) - vc) return vmax;
    return vc;
};

},{}],591:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');


// set cursors pointing toward the closest corner/side,
// to indicate alignment
// x and y are 0-1, fractions of the plot area
var cursorset = [
    ['sw-resize', 's-resize', 'se-resize'],
    ['w-resize', 'move', 'e-resize'],
    ['nw-resize', 'n-resize', 'ne-resize']
];

module.exports = function getCursor(x, y, xanchor, yanchor) {
    if(xanchor === 'left') x = 0;
    else if(xanchor === 'center') x = 1;
    else if(xanchor === 'right') x = 2;
    else x = Lib.constrain(Math.floor(x * 3), 0, 2);

    if(yanchor === 'bottom') y = 0;
    else if(yanchor === 'middle') y = 1;
    else if(yanchor === 'top') y = 2;
    else y = Lib.constrain(Math.floor(y * 3), 0, 2);

    return cursorset[y][x];
};

},{"../../lib":697}],592:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var mouseOffset = _dereq_('mouse-event-offset');
var hasHover = _dereq_('has-hover');
var supportsPassive = _dereq_('has-passive-events');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');

var constants = _dereq_('../../plots/cartesian/constants');
var interactConstants = _dereq_('../../constants/interactions');

var dragElement = module.exports = {};

dragElement.align = _dereq_('./align');
dragElement.getCursor = _dereq_('./cursor');

var unhover = _dereq_('./unhover');
dragElement.unhover = unhover.wrapped;
dragElement.unhoverRaw = unhover.raw;


/**
 * Abstracts click & drag interactions
 *
 * During the interaction, a "coverSlip" element - a transparent
 * div covering the whole page - is created, which has two key effects:
 * - Lets you drag beyond the boundaries of the plot itself without
 *   dropping (but if you drag all the way out of the browser window the
 *   interaction will end)
 * - Freezes the cursor: whatever mouse cursor the drag element had when the
 *   interaction started gets copied to the coverSlip for use until mouseup
 *
 * If the user executes a drag bigger than MINDRAG, callbacks will fire as:
 *      prepFn, moveFn (1 or more times), doneFn
 * If the user does not drag enough, prepFn and clickFn will fire.
 *
 * Note: If you cancel contextmenu, clickFn will fire even with a right click
 * (unlike native events) so you'll get a `plotly_click` event. Cancel context eg:
 *    gd.addEventListener('contextmenu', function(e) { e.preventDefault(); });
 * TODO: we should probably turn this into a `config` parameter, so we can fix it
 * such that if you *don't* cancel contextmenu, we can prevent partial drags, which
 * put you in a weird state.
 *
 * If the user clicks multiple times quickly, clickFn will fire each time
 * but numClicks will increase to help you recognize doubleclicks.
 *
 * @param {object} options with keys:
 *      element (required) the DOM element to drag
 *      prepFn (optional) function(event, startX, startY)
 *          executed on mousedown
 *          startX and startY are the clientX and clientY pixel position
 *          of the mousedown event
 *      moveFn (optional) function(dx, dy)
 *          executed on move, ONLY after we've exceeded MINDRAG
 *          (we keep executing moveFn if you move back to where you started)
 *          dx and dy are the net pixel offset of the drag,
 *          dragged is true/false, has the mouse moved enough to
 *          constitute a drag
 *      doneFn (optional) function(e)
 *          executed on mouseup, ONLY if we exceeded MINDRAG (so you can be
 *          sure that moveFn has been called at least once)
 *          numClicks is how many clicks we've registered within
 *          a doubleclick time
 *          e is the original mouseup event
 *      clickFn (optional) function(numClicks, e)
 *          executed on mouseup if we have NOT exceeded MINDRAG (ie moveFn
 *          has not been called at all)
 *          numClicks is how many clicks we've registered within
 *          a doubleclick time
 *          e is the original mousedown event
 *      clampFn (optional, function(dx, dy) return [dx2, dy2])
 *          Provide custom clamping function for small displacements.
 *          By default, clamping is done using `minDrag` to x and y displacements
 *          independently.
 */
dragElement.init = function init(options) {
    var gd = options.gd;
    var numClicks = 1;
    var DBLCLICKDELAY = interactConstants.DBLCLICKDELAY;
    var element = options.element;

    var startX,
        startY,
        newMouseDownTime,
        cursor,
        dragCover,
        initialEvent,
        initialTarget,
        rightClick;

    if(!gd._mouseDownTime) gd._mouseDownTime = 0;

    element.style.pointerEvents = 'all';

    element.onmousedown = onStart;

    if(!supportsPassive) {
        element.ontouchstart = onStart;
    }
    else {
        if(element._ontouchstart) {
            element.removeEventListener('touchstart', element._ontouchstart);
        }
        element._ontouchstart = onStart;
        element.addEventListener('touchstart', onStart, {passive: false});
    }

    function _clampFn(dx, dy, minDrag) {
        if(Math.abs(dx) < minDrag) dx = 0;
        if(Math.abs(dy) < minDrag) dy = 0;
        return [dx, dy];
    }

    var clampFn = options.clampFn || _clampFn;

    function onStart(e) {
        // make dragging and dragged into properties of gd
        // so that others can look at and modify them
        gd._dragged = false;
        gd._dragging = true;
        var offset = pointerOffset(e);
        startX = offset[0];
        startY = offset[1];
        initialTarget = e.target;
        initialEvent = e;
        rightClick = e.buttons === 2 || e.ctrlKey;

        // fix Fx.hover for touch events
        if(typeof e.clientX === 'undefined' && typeof e.clientY === 'undefined') {
            e.clientX = startX;
            e.clientY = startY;
        }

        newMouseDownTime = (new Date()).getTime();
        if(newMouseDownTime - gd._mouseDownTime < DBLCLICKDELAY) {
            // in a click train
            numClicks += 1;
        }
        else {
            // new click train
            numClicks = 1;
            gd._mouseDownTime = newMouseDownTime;
        }

        if(options.prepFn) options.prepFn(e, startX, startY);

        if(hasHover && !rightClick) {
            dragCover = coverSlip();
            dragCover.style.cursor = window.getComputedStyle(element).cursor;
        }
        else if(!hasHover) {
            // document acts as a dragcover for mobile, bc we can't create dragcover dynamically
            dragCover = document;
            cursor = window.getComputedStyle(document.documentElement).cursor;
            document.documentElement.style.cursor = window.getComputedStyle(element).cursor;
        }

        document.addEventListener('mouseup', onDone);
        document.addEventListener('touchend', onDone);

        if(options.dragmode !== false) {
            e.preventDefault();
            document.addEventListener('mousemove', onMove);
            document.addEventListener('touchmove', onMove);
        }

        return;
    }

    function onMove(e) {
        e.preventDefault();

        var offset = pointerOffset(e);
        var minDrag = options.minDrag || constants.MINDRAG;
        var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag);
        var dx = dxdy[0];
        var dy = dxdy[1];

        if(dx || dy) {
            gd._dragged = true;
            dragElement.unhover(gd);
        }

        if(gd._dragged && options.moveFn && !rightClick) options.moveFn(dx, dy);

        return;
    }

    function onDone(e) {
        if(options.dragmode !== false) {
            e.preventDefault();
            document.removeEventListener('mousemove', onMove);
            document.removeEventListener('touchmove', onMove);
        }

        document.removeEventListener('mouseup', onDone);
        document.removeEventListener('touchend', onDone);

        if(hasHover) {
            Lib.removeElement(dragCover);
        }
        else if(cursor) {
            dragCover.documentElement.style.cursor = cursor;
            cursor = null;
        }

        if(!gd._dragging) {
            gd._dragged = false;
            return;
        }
        gd._dragging = false;

        // don't count as a dblClick unless the mouseUp is also within
        // the dblclick delay
        if((new Date()).getTime() - gd._mouseDownTime > DBLCLICKDELAY) {
            numClicks = Math.max(numClicks - 1, 1);
        }

        if(gd._dragged) {
            if(options.doneFn) options.doneFn();
        }
        else {
            if(options.clickFn) options.clickFn(numClicks, initialEvent);

            // If we haven't dragged, this should be a click. But because of the
            // coverSlip changing the element, the natural system might not generate one,
            // so we need to make our own. But right clicks don't normally generate
            // click events, only contextmenu events, which happen on mousedown.
            if(!rightClick) {
                var e2;

                try {
                    e2 = new MouseEvent('click', e);
                }
                catch(err) {
                    var offset = pointerOffset(e);
                    e2 = document.createEvent('MouseEvents');
                    e2.initMouseEvent('click',
                        e.bubbles, e.cancelable,
                        e.view, e.detail,
                        e.screenX, e.screenY,
                        offset[0], offset[1],
                        e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,
                        e.button, e.relatedTarget);
                }

                initialTarget.dispatchEvent(e2);
            }
        }

        finishDrag(gd);

        gd._dragged = false;

        return;
    }
};

function coverSlip() {
    var cover = document.createElement('div');

    cover.className = 'dragcover';
    var cStyle = cover.style;
    cStyle.position = 'fixed';
    cStyle.left = 0;
    cStyle.right = 0;
    cStyle.top = 0;
    cStyle.bottom = 0;
    cStyle.zIndex = 999999999;
    cStyle.background = 'none';

    document.body.appendChild(cover);

    return cover;
}

dragElement.coverSlip = coverSlip;

function finishDrag(gd) {
    gd._dragging = false;
    if(gd._replotPending) Registry.call('plot', gd);
}

function pointerOffset(e) {
    return mouseOffset(
        e.changedTouches ? e.changedTouches[0] : e,
        document.body
    );
}

},{"../../constants/interactions":673,"../../lib":697,"../../plots/cartesian/constants":751,"../../registry":826,"./align":590,"./cursor":591,"./unhover":593,"has-hover":399,"has-passive-events":400,"mouse-event-offset":425}],593:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


var Events = _dereq_('../../lib/events');
var throttle = _dereq_('../../lib/throttle');
var getGraphDiv = _dereq_('../../lib/get_graph_div');

var hoverConstants = _dereq_('../fx/constants');

var unhover = module.exports = {};


unhover.wrapped = function(gd, evt, subplot) {
    gd = getGraphDiv(gd);

    // Important, clear any queued hovers
    if(gd._fullLayout) {
        throttle.clear(gd._fullLayout._uid + hoverConstants.HOVERID);
    }

    unhover.raw(gd, evt, subplot);
};


// remove hover effects on mouse out, and emit unhover event
unhover.raw = function unhoverRaw(gd, evt) {
    var fullLayout = gd._fullLayout;
    var oldhoverdata = gd._hoverdata;

    if(!evt) evt = {};
    if(evt.target &&
       Events.triggerHandler(gd, 'plotly_beforehover', evt) === false) {
        return;
    }

    fullLayout._hoverlayer.selectAll('g').remove();
    fullLayout._hoverlayer.selectAll('line').remove();
    fullLayout._hoverlayer.selectAll('circle').remove();
    gd._hoverdata = undefined;

    if(evt.target && oldhoverdata) {
        gd.emit('plotly_unhover', {
            event: evt,
            points: oldhoverdata
        });
    }
};

},{"../../lib/events":686,"../../lib/get_graph_div":693,"../../lib/throttle":722,"../fx/constants":607}],594:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

exports.dash = {
    valType: 'string',
    // string type usually doesn't take values... this one should really be
    // a special type or at least a special coercion function, from the GUI
    // you only get these values but elsewhere the user can supply a list of
    // dash lengths in px, and it will be honored
    values: ['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot'],
    dflt: 'solid',
    
    editType: 'style',
    
};

},{}],595:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');
var tinycolor = _dereq_('tinycolor2');

var Registry = _dereq_('../../registry');
var Color = _dereq_('../color');
var Colorscale = _dereq_('../colorscale');
var Lib = _dereq_('../../lib');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');

var xmlnsNamespaces = _dereq_('../../constants/xmlns_namespaces');
var alignment = _dereq_('../../constants/alignment');
var LINE_SPACING = alignment.LINE_SPACING;
var DESELECTDIM = _dereq_('../../constants/interactions').DESELECTDIM;

var subTypes = _dereq_('../../traces/scatter/subtypes');
var makeBubbleSizeFn = _dereq_('../../traces/scatter/make_bubble_size_func');

var drawing = module.exports = {};

// -----------------------------------------------------
// styling functions for plot elements
// -----------------------------------------------------

drawing.font = function(s, family, size, color) {
    // also allow the form font(s, {family, size, color})
    if(Lib.isPlainObject(family)) {
        color = family.color;
        size = family.size;
        family = family.family;
    }
    if(family) s.style('font-family', family);
    if(size + 1) s.style('font-size', size + 'px');
    if(color) s.call(Color.fill, color);
};

/*
 * Positioning helpers
 * Note: do not use `setPosition` with <text> nodes modified by
 * `svgTextUtils.convertToTspans`. Use `svgTextUtils.positionText`
 * instead, so that <tspan.line> elements get updated to match.
 */
drawing.setPosition = function(s, x, y) { s.attr('x', x).attr('y', y); };
drawing.setSize = function(s, w, h) { s.attr('width', w).attr('height', h); };
drawing.setRect = function(s, x, y, w, h) {
    s.call(drawing.setPosition, x, y).call(drawing.setSize, w, h);
};

/** Translate node
 *
 * @param {object} d : calcdata point item
 * @param {sel} sel : d3 selction of node to translate
 * @param {object} xa : corresponding full xaxis object
 * @param {object} ya : corresponding full yaxis object
 *
 * @return {boolean} :
 *  true if selection got translated
 *  false if selection could not get translated
 */
drawing.translatePoint = function(d, sel, xa, ya) {
    var x = xa.c2p(d.x);
    var y = ya.c2p(d.y);

    if(isNumeric(x) && isNumeric(y) && sel.node()) {
        // for multiline text this works better
        if(sel.node().nodeName === 'text') {
            sel.attr('x', x).attr('y', y);
        } else {
            sel.attr('transform', 'translate(' + x + ',' + y + ')');
        }
    } else {
        return false;
    }

    return true;
};

drawing.translatePoints = function(s, xa, ya) {
    s.each(function(d) {
        var sel = d3.select(this);
        drawing.translatePoint(d, sel, xa, ya);
    });
};

drawing.hideOutsideRangePoint = function(d, sel, xa, ya, xcalendar, ycalendar) {
    sel.attr(
        'display',
        (xa.isPtWithinRange(d, xcalendar) && ya.isPtWithinRange(d, ycalendar)) ? null : 'none'
    );
};

drawing.hideOutsideRangePoints = function(traceGroups, subplot) {
    if(!subplot._hasClipOnAxisFalse) return;

    var xa = subplot.xaxis;
    var ya = subplot.yaxis;

    traceGroups.each(function(d) {
        var trace = d[0].trace;
        var xcalendar = trace.xcalendar;
        var ycalendar = trace.ycalendar;
        var selector = trace.type === 'bar' ? '.bartext' : '.point,.textpoint';

        traceGroups.selectAll(selector).each(function(d) {
            drawing.hideOutsideRangePoint(d, d3.select(this), xa, ya, xcalendar, ycalendar);
        });
    });
};

drawing.crispRound = function(gd, lineWidth, dflt) {
    // for lines that disable antialiasing we want to
    // make sure the width is an integer, and at least 1 if it's nonzero

    if(!lineWidth || !isNumeric(lineWidth)) return dflt || 0;

    // but not for static plots - these don't get antialiased anyway.
    if(gd._context.staticPlot) return lineWidth;

    if(lineWidth < 1) return 1;
    return Math.round(lineWidth);
};

drawing.singleLineStyle = function(d, s, lw, lc, ld) {
    s.style('fill', 'none');
    var line = (((d || [])[0] || {}).trace || {}).line || {};
    var lw1 = lw || line.width||0;
    var dash = ld || line.dash || '';

    Color.stroke(s, lc || line.color);
    drawing.dashLine(s, dash, lw1);
};

drawing.lineGroupStyle = function(s, lw, lc, ld) {
    s.style('fill', 'none')
    .each(function(d) {
        var line = (((d || [])[0] || {}).trace || {}).line || {};
        var lw1 = lw || line.width||0;
        var dash = ld || line.dash || '';

        d3.select(this)
            .call(Color.stroke, lc || line.color)
            .call(drawing.dashLine, dash, lw1);
    });
};

drawing.dashLine = function(s, dash, lineWidth) {
    lineWidth = +lineWidth || 0;

    dash = drawing.dashStyle(dash, lineWidth);

    s.style({
        'stroke-dasharray': dash,
        'stroke-width': lineWidth + 'px'
    });
};

drawing.dashStyle = function(dash, lineWidth) {
    lineWidth = +lineWidth || 1;
    var dlw = Math.max(lineWidth, 3);

    if(dash === 'solid') dash = '';
    else if(dash === 'dot') dash = dlw + 'px,' + dlw + 'px';
    else if(dash === 'dash') dash = (3 * dlw) + 'px,' + (3 * dlw) + 'px';
    else if(dash === 'longdash') dash = (5 * dlw) + 'px,' + (5 * dlw) + 'px';
    else if(dash === 'dashdot') {
        dash = (3 * dlw) + 'px,' + dlw + 'px,' + dlw + 'px,' + dlw + 'px';
    }
    else if(dash === 'longdashdot') {
        dash = (5 * dlw) + 'px,' + (2 * dlw) + 'px,' + dlw + 'px,' + (2 * dlw) + 'px';
    }
    // otherwise user wrote the dasharray themselves - leave it be

    return dash;
};

// Same as fillGroupStyle, except in this case the selection may be a transition
drawing.singleFillStyle = function(sel) {
    var node = d3.select(sel.node());
    var data = node.data();
    var fillcolor = (((data[0] || [])[0] || {}).trace || {}).fillcolor;
    if(fillcolor) {
        sel.call(Color.fill, fillcolor);
    }
};

drawing.fillGroupStyle = function(s) {
    s.style('stroke-width', 0)
    .each(function(d) {
        var shape = d3.select(this);
        // N.B. 'd' won't be a calcdata item when
        // fill !== 'none' on a segment-less and marker-less trace
        if(d[0].trace) {
            shape.call(Color.fill, d[0].trace.fillcolor);
        }
    });
};

var SYMBOLDEFS = _dereq_('./symbol_defs');

drawing.symbolNames = [];
drawing.symbolFuncs = [];
drawing.symbolNeedLines = {};
drawing.symbolNoDot = {};
drawing.symbolNoFill = {};
drawing.symbolList = [];

Object.keys(SYMBOLDEFS).forEach(function(k) {
    var symDef = SYMBOLDEFS[k];
    drawing.symbolList = drawing.symbolList.concat(
        [symDef.n, k, symDef.n + 100, k + '-open']);
    drawing.symbolNames[symDef.n] = k;
    drawing.symbolFuncs[symDef.n] = symDef.f;
    if(symDef.needLine) {
        drawing.symbolNeedLines[symDef.n] = true;
    }
    if(symDef.noDot) {
        drawing.symbolNoDot[symDef.n] = true;
    }
    else {
        drawing.symbolList = drawing.symbolList.concat(
            [symDef.n + 200, k + '-dot', symDef.n + 300, k + '-open-dot']);
    }
    if(symDef.noFill) {
        drawing.symbolNoFill[symDef.n] = true;
    }
});

var MAXSYMBOL = drawing.symbolNames.length;
// add a dot in the middle of the symbol
var DOTPATH = 'M0,0.5L0.5,0L0,-0.5L-0.5,0Z';

drawing.symbolNumber = function(v) {
    if(typeof v === 'string') {
        var vbase = 0;
        if(v.indexOf('-open') > 0) {
            vbase = 100;
            v = v.replace('-open', '');
        }
        if(v.indexOf('-dot') > 0) {
            vbase += 200;
            v = v.replace('-dot', '');
        }
        v = drawing.symbolNames.indexOf(v);
        if(v >= 0) { v += vbase; }
    }
    if((v % 100 >= MAXSYMBOL) || v >= 400) { return 0; }
    return Math.floor(Math.max(v, 0));
};

function makePointPath(symbolNumber, r) {
    var base = symbolNumber % 100;
    return drawing.symbolFuncs[base](r) + (symbolNumber >= 200 ? DOTPATH : '');
}

var HORZGRADIENT = {x1: 1, x2: 0, y1: 0, y2: 0};
var VERTGRADIENT = {x1: 0, x2: 0, y1: 1, y2: 0};
var stopFormatter = d3.format('~.1f');
var gradientInfo = {
    radial: {node: 'radialGradient'},
    radialreversed: {node: 'radialGradient', reversed: true},
    horizontal: {node: 'linearGradient', attrs: HORZGRADIENT},
    horizontalreversed: {node: 'linearGradient', attrs: HORZGRADIENT, reversed: true},
    vertical: {node: 'linearGradient', attrs: VERTGRADIENT},
    verticalreversed: {node: 'linearGradient', attrs: VERTGRADIENT, reversed: true}
};

/**
 * gradient: create and apply a gradient fill
 *
 * @param {object} sel: d3 selection to apply this gradient to
 *     You can use `selection.call(Drawing.gradient, ...)`
 * @param {DOM element} gd: the graph div `sel` is part of
 * @param {string} gradientID: a unique (within this plot) identifier
 *     for this gradient, so that we don't create unnecessary definitions
 * @param {string} type: 'radial', 'horizontal', or 'vertical', optionally with
 *     'reversed' at the end. Normally radial goes center to edge,
 *     horizontal goes right to left, and vertical goes bottom to top
 * @param {array} colorscale: as in attribute values, [[fraction, color], ...]
 * @param {string} prop: the property to apply to, 'fill' or 'stroke'
 */
drawing.gradient = function(sel, gd, gradientID, type, colorscale, prop) {
    var len = colorscale.length;
    var info = gradientInfo[type];
    var colorStops = new Array(len);
    for(var i = 0; i < len; i++) {
        if(info.reversed) {
            colorStops[len - 1 - i] = [stopFormatter((1 - colorscale[i][0]) * 100), colorscale[i][1]];
        }
        else {
            colorStops[i] = [stopFormatter(colorscale[i][0] * 100), colorscale[i][1]];
        }
    }

    var fullID = 'g' + gd._fullLayout._uid + '-' + gradientID;

    var gradient = gd._fullLayout._defs.select('.gradients')
        .selectAll('#' + fullID)
        .data([type + colorStops.join(';')], Lib.identity);

    gradient.exit().remove();

    gradient.enter()
        .append(info.node)
        .each(function() {
            var el = d3.select(this);
            if(info.attrs) el.attr(info.attrs);

            el.attr('id', fullID);

            var stops = el.selectAll('stop')
                .data(colorStops);
            stops.exit().remove();
            stops.enter().append('stop');

            stops.each(function(d) {
                var tc = tinycolor(d[1]);
                d3.select(this).attr({
                    offset: d[0] + '%',
                    'stop-color': Color.tinyRGB(tc),
                    'stop-opacity': tc.getAlpha()
                });
            });
        });

    sel.style(prop, 'url(#' + fullID + ')')
        .style(prop + '-opacity', null);
};

/*
 * Make the gradients container and clear out any previous gradients.
 * We never collect all the gradients we need in one place,
 * so we can't ever remove gradients that have stopped being useful,
 * except all at once before a full redraw.
 * The upside of this is arbitrary points can share gradient defs
 */
drawing.initGradients = function(gd) {
    var gradientsGroup = Lib.ensureSingle(gd._fullLayout._defs, 'g', 'gradients');
    gradientsGroup.selectAll('linearGradient,radialGradient').remove();
};


drawing.pointStyle = function(s, trace, gd) {
    if(!s.size()) return;

    var fns = drawing.makePointStyleFns(trace);

    s.each(function(d) {
        drawing.singlePointStyle(d, d3.select(this), trace, fns, gd);
    });
};

drawing.singlePointStyle = function(d, sel, trace, fns, gd) {
    var marker = trace.marker;
    var markerLine = marker.line;

    sel.style('opacity',
        fns.selectedOpacityFn ? fns.selectedOpacityFn(d) :
            (d.mo === undefined ? marker.opacity : d.mo)
    );

    if(fns.ms2mrc) {
        var r;

        // handle multi-trace graph edit case
        if(d.ms === 'various' || marker.size === 'various') {
            r = 3;
        } else {
            r = fns.ms2mrc(d.ms);
        }

        // store the calculated size so hover can use it
        d.mrc = r;

        if(fns.selectedSizeFn) {
            r = d.mrc = fns.selectedSizeFn(d);
        }

        // turn the symbol into a sanitized number
        var x = drawing.symbolNumber(d.mx || marker.symbol) || 0;

        // save if this marker is open
        // because that impacts how to handle colors
        d.om = x % 200 >= 100;

        sel.attr('d', makePointPath(x, r));
    }

    var perPointGradient = false;
    var fillColor, lineColor, lineWidth;

    // 'so' is suspected outliers, for box plots
    if(d.so) {
        lineWidth = markerLine.outlierwidth;
        lineColor = markerLine.outliercolor;
        fillColor = marker.outliercolor;
    } else {
        var markerLineWidth = (markerLine || {}).width;

        lineWidth = (
            d.mlw + 1 ||
            markerLineWidth + 1 ||
            // TODO: we need the latter for legends... can we get rid of it?
            (d.trace ? (d.trace.marker.line || {}).width : 0) + 1
        ) - 1 || 0;

        if('mlc' in d) lineColor = d.mlcc = fns.lineScale(d.mlc);
        // weird case: array wasn't long enough to apply to every point
        else if(Lib.isArrayOrTypedArray(markerLine.color)) lineColor = Color.defaultLine;
        else lineColor = markerLine.color;

        if(Lib.isArrayOrTypedArray(marker.color)) {
            fillColor = Color.defaultLine;
            perPointGradient = true;
        }

        if('mc' in d) {
            fillColor = d.mcc = fns.markerScale(d.mc);
        } else {
            fillColor = marker.color || 'rgba(0,0,0,0)';
        }

        if(fns.selectedColorFn) {
            fillColor = fns.selectedColorFn(d);
        }
    }

    if(d.om) {
        // open markers can't have zero linewidth, default to 1px,
        // and use fill color as stroke color
        sel.call(Color.stroke, fillColor)
            .style({
                'stroke-width': (lineWidth || 1) + 'px',
                fill: 'none'
            });
    } else {
        sel.style('stroke-width', lineWidth + 'px');

        var markerGradient = marker.gradient;

        var gradientType = d.mgt;
        if(gradientType) perPointGradient = true;
        else gradientType = markerGradient && markerGradient.type;

        // for legend - arrays will propagate through here, but we don't need
        // to treat it as per-point.
        if(Array.isArray(gradientType)) {
            gradientType = gradientType[0];
            if(!gradientInfo[gradientType]) gradientType = 0;
        }

        if(gradientType && gradientType !== 'none') {
            var gradientColor = d.mgc;
            if(gradientColor) perPointGradient = true;
            else gradientColor = markerGradient.color;

            var gradientID = trace.uid;
            if(perPointGradient) gradientID += '-' + d.i;

            drawing.gradient(sel, gd, gradientID, gradientType,
                [[0, gradientColor], [1, fillColor]], 'fill');
        } else {
            Color.fill(sel, fillColor);
        }

        if(lineWidth) {
            Color.stroke(sel, lineColor);
        }
    }
};

drawing.makePointStyleFns = function(trace) {
    var out = {};
    var marker = trace.marker;

    // allow array marker and marker line colors to be
    // scaled by given max and min to colorscales
    out.markerScale = drawing.tryColorscale(marker, '');
    out.lineScale = drawing.tryColorscale(marker, 'line');

    if(Registry.traceIs(trace, 'symbols')) {
        out.ms2mrc = subTypes.isBubble(trace) ?
            makeBubbleSizeFn(trace) :
            function() { return (marker.size || 6) / 2; };
    }

    if(trace.selectedpoints) {
        Lib.extendFlat(out, drawing.makeSelectedPointStyleFns(trace));
    }

    return out;
};

drawing.makeSelectedPointStyleFns = function(trace) {
    var out = {};

    var selectedAttrs = trace.selected || {};
    var unselectedAttrs = trace.unselected || {};

    var marker = trace.marker || {};
    var selectedMarker = selectedAttrs.marker || {};
    var unselectedMarker = unselectedAttrs.marker || {};

    var mo = marker.opacity;
    var smo = selectedMarker.opacity;
    var usmo = unselectedMarker.opacity;
    var smoIsDefined = smo !== undefined;
    var usmoIsDefined = usmo !== undefined;

    if(Lib.isArrayOrTypedArray(mo) || smoIsDefined || usmoIsDefined) {
        out.selectedOpacityFn = function(d) {
            var base = d.mo === undefined ? marker.opacity : d.mo;

            if(d.selected) {
                return smoIsDefined ? smo : base;
            } else {
                return usmoIsDefined ? usmo : DESELECTDIM * base;
            }
        };
    }

    var mc = marker.color;
    var smc = selectedMarker.color;
    var usmc = unselectedMarker.color;

    if(smc || usmc) {
        out.selectedColorFn = function(d) {
            var base = d.mcc || mc;

            if(d.selected) {
                return smc || base;
            } else {
                return usmc || base;
            }
        };
    }

    var ms = marker.size;
    var sms = selectedMarker.size;
    var usms = unselectedMarker.size;
    var smsIsDefined = sms !== undefined;
    var usmsIsDefined = usms !== undefined;

    if(Registry.traceIs(trace, 'symbols') && (smsIsDefined || usmsIsDefined)) {
        out.selectedSizeFn = function(d) {
            var base = d.mrc || ms / 2;

            if(d.selected) {
                return smsIsDefined ? sms / 2 : base;
            } else {
                return usmsIsDefined ? usms / 2 : base;
            }
        };
    }

    return out;
};

drawing.makeSelectedTextStyleFns = function(trace) {
    var out = {};

    var selectedAttrs = trace.selected || {};
    var unselectedAttrs = trace.unselected || {};

    var textFont = trace.textfont || {};
    var selectedTextFont = selectedAttrs.textfont || {};
    var unselectedTextFont = unselectedAttrs.textfont || {};

    var tc = textFont.color;
    var stc = selectedTextFont.color;
    var utc = unselectedTextFont.color;

    out.selectedTextColorFn = function(d) {
        var base = d.tc || tc;

        if(d.selected) {
            return stc || base;
        } else {
            if(utc) return utc;
            else return stc ? base : Color.addOpacity(base, DESELECTDIM);
        }
    };

    return out;
};

drawing.selectedPointStyle = function(s, trace) {
    if(!s.size() || !trace.selectedpoints) return;

    var fns = drawing.makeSelectedPointStyleFns(trace);
    var marker = trace.marker || {};
    var seq = [];

    if(fns.selectedOpacityFn) {
        seq.push(function(pt, d) {
            pt.style('opacity', fns.selectedOpacityFn(d));
        });
    }

    if(fns.selectedColorFn) {
        seq.push(function(pt, d) {
            Color.fill(pt, fns.selectedColorFn(d));
        });
    }

    if(fns.selectedSizeFn) {
        seq.push(function(pt, d) {
            var mx = d.mx || marker.symbol || 0;
            var mrc2 = fns.selectedSizeFn(d);

            pt.attr('d', makePointPath(drawing.symbolNumber(mx), mrc2));

            // save for Drawing.selectedTextStyle
            d.mrc2 = mrc2;
        });
    }

    if(seq.length) {
        s.each(function(d) {
            var pt = d3.select(this);
            for(var i = 0; i < seq.length; i++) {
                seq[i](pt, d);
            }
        });
    }
};

drawing.tryColorscale = function(marker, prefix) {
    var cont = prefix ? Lib.nestedProperty(marker, prefix).get() : marker;

    if(cont) {
        var scl = cont.colorscale;
        var colorArray = cont.color;

        if(scl && Lib.isArrayOrTypedArray(colorArray)) {
            return Colorscale.makeColorScaleFunc(
                Colorscale.extractScale(cont, {cLetter: 'c'})
            );
        }
    }
    return Lib.identity;
};

var TEXTOFFSETSIGN = {
    start: 1, end: -1, middle: 0, bottom: 1, top: -1
};

function textPointPosition(s, textPosition, fontSize, markerRadius) {
    var group = d3.select(s.node().parentNode);

    var v = textPosition.indexOf('top') !== -1 ?
        'top' :
        textPosition.indexOf('bottom') !== -1 ? 'bottom' : 'middle';
    var h = textPosition.indexOf('left') !== -1 ?
        'end' :
        textPosition.indexOf('right') !== -1 ? 'start' : 'middle';

    // if markers are shown, offset a little more than
    // the nominal marker size
    // ie 2/1.6 * nominal, bcs some markers are a bit bigger
    var r = markerRadius ? markerRadius / 0.8 + 1 : 0;

    var numLines = (svgTextUtils.lineCount(s) - 1) * LINE_SPACING + 1;
    var dx = TEXTOFFSETSIGN[h] * r;
    var dy = fontSize * 0.75 + TEXTOFFSETSIGN[v] * r +
        (TEXTOFFSETSIGN[v] - 1) * numLines * fontSize / 2;

    // fix the overall text group position
    s.attr('text-anchor', h);
    group.attr('transform', 'translate(' + dx + ',' + dy + ')');
}

function extracTextFontSize(d, trace) {
    var fontSize = d.ts || trace.textfont.size;
    return (isNumeric(fontSize) && fontSize > 0) ? fontSize : 0;
}

// draw text at points
drawing.textPointStyle = function(s, trace, gd) {
    if(!s.size()) return;

    var selectedTextColorFn;

    if(trace.selectedpoints) {
        var fns = drawing.makeSelectedTextStyleFns(trace);
        selectedTextColorFn = fns.selectedTextColorFn;
    }

    s.each(function(d) {
        var p = d3.select(this);
        var text = Lib.extractOption(d, trace, 'tx', 'text');

        if(!text && text !== 0) {
            p.remove();
            return;
        }

        var pos = d.tp || trace.textposition;
        var fontSize = extracTextFontSize(d, trace);
        var fontColor = selectedTextColorFn ?
            selectedTextColorFn(d) :
            (d.tc || trace.textfont.color);

        p.call(drawing.font,
                d.tf || trace.textfont.family,
                fontSize,
                fontColor)
            .text(text)
            .call(svgTextUtils.convertToTspans, gd)
            .call(textPointPosition, pos, fontSize, d.mrc);
    });
};

drawing.selectedTextStyle = function(s, trace) {
    if(!s.size() || !trace.selectedpoints) return;

    var fns = drawing.makeSelectedTextStyleFns(trace);

    s.each(function(d) {
        var tx = d3.select(this);
        var tc = fns.selectedTextColorFn(d);
        var tp = d.tp || trace.textposition;
        var fontSize = extracTextFontSize(d, trace);

        Color.fill(tx, tc);
        textPointPosition(tx, tp, fontSize, d.mrc2 || d.mrc);
    });
};

// generalized Catmull-Rom splines, per
// http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
var CatmullRomExp = 0.5;
drawing.smoothopen = function(pts, smoothness) {
    if(pts.length < 3) { return 'M' + pts.join('L');}
    var path = 'M' + pts[0];
    var tangents = [];
    var i;
    for(i = 1; i < pts.length - 1; i++) {
        tangents.push(makeTangent(pts[i - 1], pts[i], pts[i + 1], smoothness));
    }
    path += 'Q' + tangents[0][0] + ' ' + pts[1];
    for(i = 2; i < pts.length - 1; i++) {
        path += 'C' + tangents[i - 2][1] + ' ' + tangents[i - 1][0] + ' ' + pts[i];
    }
    path += 'Q' + tangents[pts.length - 3][1] + ' ' + pts[pts.length - 1];
    return path;
};

drawing.smoothclosed = function(pts, smoothness) {
    if(pts.length < 3) { return 'M' + pts.join('L') + 'Z'; }
    var path = 'M' + pts[0];
    var pLast = pts.length - 1;
    var tangents = [makeTangent(pts[pLast], pts[0], pts[1], smoothness)];
    var i;
    for(i = 1; i < pLast; i++) {
        tangents.push(makeTangent(pts[i - 1], pts[i], pts[i + 1], smoothness));
    }
    tangents.push(
        makeTangent(pts[pLast - 1], pts[pLast], pts[0], smoothness)
    );

    for(i = 1; i <= pLast; i++) {
        path += 'C' + tangents[i - 1][1] + ' ' + tangents[i][0] + ' ' + pts[i];
    }
    path += 'C' + tangents[pLast][1] + ' ' + tangents[0][0] + ' ' + pts[0] + 'Z';
    return path;
};

function makeTangent(prevpt, thispt, nextpt, smoothness) {
    var d1x = prevpt[0] - thispt[0];
    var d1y = prevpt[1] - thispt[1];
    var d2x = nextpt[0] - thispt[0];
    var d2y = nextpt[1] - thispt[1];
    var d1a = Math.pow(d1x * d1x + d1y * d1y, CatmullRomExp / 2);
    var d2a = Math.pow(d2x * d2x + d2y * d2y, CatmullRomExp / 2);
    var numx = (d2a * d2a * d1x - d1a * d1a * d2x) * smoothness;
    var numy = (d2a * d2a * d1y - d1a * d1a * d2y) * smoothness;
    var denom1 = 3 * d2a * (d1a + d2a);
    var denom2 = 3 * d1a * (d1a + d2a);
    return [
        [
            d3.round(thispt[0] + (denom1 && numx / denom1), 2),
            d3.round(thispt[1] + (denom1 && numy / denom1), 2)
        ], [
            d3.round(thispt[0] - (denom2 && numx / denom2), 2),
            d3.round(thispt[1] - (denom2 && numy / denom2), 2)
        ]
    ];
}

// step paths - returns a generator function for paths
// with the given step shape
var STEPPATH = {
    hv: function(p0, p1) {
        return 'H' + d3.round(p1[0], 2) + 'V' + d3.round(p1[1], 2);
    },
    vh: function(p0, p1) {
        return 'V' + d3.round(p1[1], 2) + 'H' + d3.round(p1[0], 2);
    },
    hvh: function(p0, p1) {
        return 'H' + d3.round((p0[0] + p1[0]) / 2, 2) + 'V' +
            d3.round(p1[1], 2) + 'H' + d3.round(p1[0], 2);
    },
    vhv: function(p0, p1) {
        return 'V' + d3.round((p0[1] + p1[1]) / 2, 2) + 'H' +
            d3.round(p1[0], 2) + 'V' + d3.round(p1[1], 2);
    }
};
var STEPLINEAR = function(p0, p1) {
    return 'L' + d3.round(p1[0], 2) + ',' + d3.round(p1[1], 2);
};
drawing.steps = function(shape) {
    var onestep = STEPPATH[shape] || STEPLINEAR;
    return function(pts) {
        var path = 'M' + d3.round(pts[0][0], 2) + ',' + d3.round(pts[0][1], 2);
        for(var i = 1; i < pts.length; i++) {
            path += onestep(pts[i - 1], pts[i]);
        }
        return path;
    };
};

// off-screen svg render testing element, shared by the whole page
// uses the id 'js-plotly-tester' and stores it in drawing.tester
drawing.makeTester = function() {
    var tester = Lib.ensureSingleById(d3.select('body'), 'svg', 'js-plotly-tester', function(s) {
        s.attr(xmlnsNamespaces.svgAttrs)
            .style({
                position: 'absolute',
                left: '-10000px',
                top: '-10000px',
                width: '9000px',
                height: '9000px',
                'z-index': '1'
            });
    });

    // browsers differ on how they describe the bounding rect of
    // the svg if its contents spill over... so make a 1x1px
    // reference point we can measure off of.
    var testref = Lib.ensureSingle(tester, 'path', 'js-reference-point', function(s) {
        s.attr('d', 'M0,0H1V1H0Z')
            .style({
                'stroke-width': 0,
                fill: 'black'
            });
    });

    drawing.tester = tester;
    drawing.testref = testref;
};

/*
 * use our offscreen tester to get a clientRect for an element,
 * in a reference frame where it isn't translated (or transformed) and
 * its anchor point is at (0,0)
 * always returns a copy of the bbox, so the caller can modify it safely
 *
 * @param {SVGElement} node: the element to measure. If possible this should be
 *   a <text> or MathJax <g> element that's already passed through
 *   `convertToTspans` because in that case we can cache the results, but it's
 *   possible to pass in any svg element.
 *
 * @param {boolean} inTester: is this element already in `drawing.tester`?
 *   If you are measuring a dummy element, rather than one you really intend
 *   to use on the plot, making it in `drawing.tester` in the first place
 *   allows us to test faster because it cuts out cloning and appending it.
 *
 * @param {string} hash: for internal use only, if we already know the cache key
 *   for this element beforehand.
 *
 * @return {object}: a plain object containing the width, height, left, right,
 *   top, and bottom of `node`
 */
drawing.savedBBoxes = {};
var savedBBoxesCount = 0;
var maxSavedBBoxes = 10000;

drawing.bBox = function(node, inTester, hash) {
    /*
     * Cache elements we've already measured so we don't have to
     * remeasure the same thing many times
     * We have a few bBox callers though who pass a node larger than
     * a <text> or a MathJax <g>, such as an axis group containing many labels.
     * These will not generate a hash (unless we figure out an appropriate
     * hash key for them) and thus we will not hash them.
     */
    if(!hash) hash = nodeHash(node);
    var out;
    if(hash) {
        out = drawing.savedBBoxes[hash];
        if(out) return Lib.extendFlat({}, out);
    }
    else if(node.childNodes.length === 1) {
        /*
         * If we have only one child element, which is itself hashable, make
         * a new hash from this element plus its x,y,transform
         * These bounding boxes *include* x,y,transform - mostly for use by
         * callers trying to avoid overlaps (ie titles)
         */
        var innerNode = node.childNodes[0];

        hash = nodeHash(innerNode);
        if(hash) {
            var x = +innerNode.getAttribute('x') || 0;
            var y = +innerNode.getAttribute('y') || 0;
            var transform = innerNode.getAttribute('transform');

            if(!transform) {
                // in this case, just varying x and y, don't bother caching
                // the final bBox because the alteration is quick.
                var innerBB = drawing.bBox(innerNode, false, hash);
                if(x) {
                    innerBB.left += x;
                    innerBB.right += x;
                }
                if(y) {
                    innerBB.top += y;
                    innerBB.bottom += y;
                }
                return innerBB;
            }
            /*
             * else we have a transform - rather than make a complicated
             * (and error-prone and probably slow) transform parser/calculator,
             * just continue on calculating the boundingClientRect of the group
             * and use the new composite hash to cache it.
             * That said, `innerNode.transform.baseVal` is an array of
             * `SVGTransform` objects, that *do* seem to have a nice matrix
             * multiplication interface that we could use to avoid making
             * another getBoundingClientRect call...
             */
            hash += '~' + x + '~' + y + '~' + transform;

            out = drawing.savedBBoxes[hash];
            if(out) return Lib.extendFlat({}, out);
        }
    }
    var testNode, tester;
    if(inTester) {
        testNode = node;
    }
    else {
        tester = drawing.tester.node();

        // copy the node to test into the tester
        testNode = node.cloneNode(true);
        tester.appendChild(testNode);
    }

    // standardize its position (and newline tspans if any)
    d3.select(testNode)
        .attr('transform', null)
        .call(svgTextUtils.positionText, 0, 0);

    var testRect = testNode.getBoundingClientRect();
    var refRect = drawing.testref
        .node()
        .getBoundingClientRect();

    if(!inTester) tester.removeChild(testNode);

    var bb = {
        height: testRect.height,
        width: testRect.width,
        left: testRect.left - refRect.left,
        top: testRect.top - refRect.top,
        right: testRect.right - refRect.left,
        bottom: testRect.bottom - refRect.top
    };

    // make sure we don't have too many saved boxes,
    // or a long session could overload on memory
    // by saving boxes for long-gone elements
    if(savedBBoxesCount >= maxSavedBBoxes) {
        drawing.savedBBoxes = {};
        savedBBoxesCount = 0;
    }

    // cache this bbox
    if(hash) drawing.savedBBoxes[hash] = bb;
    savedBBoxesCount++;

    return Lib.extendFlat({}, bb);
};

// capture everything about a node (at least in our usage) that
// impacts its bounding box, given that bBox clears x, y, and transform
function nodeHash(node) {
    var inputText = node.getAttribute('data-unformatted');
    if(inputText === null) return;
    return inputText +
        node.getAttribute('data-math') +
        node.getAttribute('text-anchor') +
        node.getAttribute('style');
}

/**
 * Set clipPath URL in a way that work for all situations.
 *
 * In details, graphs on pages with <base> HTML tags need to prepend
 * the clip path ids with the page's base url EXCEPT during toImage exports.
 *
 * @param {d3 selection} s : node to add clip-path attribute
 * @param {string} localId : local clip-path (w/o base url) id
 * @param {DOM element || object} gd
 * - context._baseUrl {string}
 * - context._exportedPlot {boolean}
 */
drawing.setClipUrl = function(s, localId, gd) {
    if(!localId) {
        s.attr('clip-path', null);
        return;
    }

    var context = gd._context;
    var baseUrl = context._exportedPlot ? '' : (context._baseUrl || '');

    s.attr('clip-path', 'url(' + baseUrl + '#' + localId + ')');
};

drawing.getTranslate = function(element) {
    // Note the separator [^\d] between x and y in this regex
    // We generally use ',' but IE will convert it to ' '
    var re = /.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/;
    var getter = element.attr ? 'attr' : 'getAttribute';
    var transform = element[getter]('transform') || '';

    var translate = transform.replace(re, function(match, p1, p2) {
        return [p1, p2].join(' ');
    })
    .split(' ');

    return {
        x: +translate[0] || 0,
        y: +translate[1] || 0
    };
};

drawing.setTranslate = function(element, x, y) {
    var re = /(\btranslate\(.*?\);?)/;
    var getter = element.attr ? 'attr' : 'getAttribute';
    var setter = element.attr ? 'attr' : 'setAttribute';
    var transform = element[getter]('transform') || '';

    x = x || 0;
    y = y || 0;

    transform = transform.replace(re, '').trim();
    transform += ' translate(' + x + ', ' + y + ')';
    transform = transform.trim();

    element[setter]('transform', transform);

    return transform;
};

drawing.getScale = function(element) {
    var re = /.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/;
    var getter = element.attr ? 'attr' : 'getAttribute';
    var transform = element[getter]('transform') || '';

    var translate = transform.replace(re, function(match, p1, p2) {
        return [p1, p2].join(' ');
    })
    .split(' ');

    return {
        x: +translate[0] || 1,
        y: +translate[1] || 1
    };
};

drawing.setScale = function(element, x, y) {
    var re = /(\bscale\(.*?\);?)/;
    var getter = element.attr ? 'attr' : 'getAttribute';
    var setter = element.attr ? 'attr' : 'setAttribute';
    var transform = element[getter]('transform') || '';

    x = x || 1;
    y = y || 1;

    transform = transform.replace(re, '').trim();
    transform += ' scale(' + x + ', ' + y + ')';
    transform = transform.trim();

    element[setter]('transform', transform);

    return transform;
};

var SCALE_RE = /\s*sc.*/;

drawing.setPointGroupScale = function(selection, xScale, yScale) {
    xScale = xScale || 1;
    yScale = yScale || 1;

    if(!selection) return;

    // The same scale transform for every point:
    var scale = (xScale === 1 && yScale === 1) ?
        '' :
        ' scale(' + xScale + ',' + yScale + ')';

    selection.each(function() {
        var t = (this.getAttribute('transform') || '').replace(SCALE_RE, '');
        t += scale;
        t = t.trim();
        this.setAttribute('transform', t);
    });
};

var TEXT_POINT_LAST_TRANSLATION_RE = /translate\([^)]*\)\s*$/;

drawing.setTextPointsScale = function(selection, xScale, yScale) {
    if(!selection) return;

    selection.each(function() {
        var transforms;
        var el = d3.select(this);
        var text = el.select('text');

        if(!text.node()) return;

        var x = parseFloat(text.attr('x') || 0);
        var y = parseFloat(text.attr('y') || 0);

        var existingTransform = (el.attr('transform') || '').match(TEXT_POINT_LAST_TRANSLATION_RE);

        if(xScale === 1 && yScale === 1) {
            transforms = [];
        } else {
            transforms = [
                'translate(' + x + ',' + y + ')',
                'scale(' + xScale + ',' + yScale + ')',
                'translate(' + (-x) + ',' + (-y) + ')',
            ];
        }

        if(existingTransform) {
            transforms.push(existingTransform);
        }

        el.attr('transform', transforms.join(' '));
    });
};

},{"../../constants/alignment":669,"../../constants/interactions":673,"../../constants/xmlns_namespaces":675,"../../lib":697,"../../lib/svg_text_utils":721,"../../registry":826,"../../traces/scatter/make_bubble_size_func":1065,"../../traces/scatter/subtypes":1072,"../color":574,"../colorscale":586,"./symbol_defs":596,"d3":151,"fast-isnumeric":218,"tinycolor2":518}],596:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

/** Marker symbol definitions
 * users can specify markers either by number or name
 * add 100 (or '-open') and you get an open marker
 *  open markers have no fill and use line color as the stroke color
 * add 200 (or '-dot') and you get a dot in the middle
 * add both and you get both
 */

module.exports = {
    circle: {
        n: 0,
        f: function(r) {
            var rs = d3.round(r, 2);
            return 'M' + rs + ',0A' + rs + ',' + rs + ' 0 1,1 0,-' + rs +
                'A' + rs + ',' + rs + ' 0 0,1 ' + rs + ',0Z';
        }
    },
    square: {
        n: 1,
        f: function(r) {
            var rs = d3.round(r, 2);
            return 'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z';
        }
    },
    diamond: {
        n: 2,
        f: function(r) {
            var rd = d3.round(r * 1.3, 2);
            return 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z';
        }
    },
    cross: {
        n: 3,
        f: function(r) {
            var rc = d3.round(r * 0.4, 2);
            var rc2 = d3.round(r * 1.2, 2);
            return 'M' + rc2 + ',' + rc + 'H' + rc + 'V' + rc2 + 'H-' + rc +
                'V' + rc + 'H-' + rc2 + 'V-' + rc + 'H-' + rc + 'V-' + rc2 +
                'H' + rc + 'V-' + rc + 'H' + rc2 + 'Z';
        }
    },
    x: {
        n: 4,
        f: function(r) {
            var rx = d3.round(r * 0.8 / Math.sqrt(2), 2);
            var ne = 'l' + rx + ',' + rx;
            var se = 'l' + rx + ',-' + rx;
            var sw = 'l-' + rx + ',-' + rx;
            var nw = 'l-' + rx + ',' + rx;
            return 'M0,' + rx + ne + se + sw + se + sw + nw + sw + nw + ne + nw + ne + 'Z';
        }
    },
    'triangle-up': {
        n: 5,
        f: function(r) {
            var rt = d3.round(r * 2 / Math.sqrt(3), 2);
            var r2 = d3.round(r / 2, 2);
            var rs = d3.round(r, 2);
            return 'M-' + rt + ',' + r2 + 'H' + rt + 'L0,-' + rs + 'Z';
        }
    },
    'triangle-down': {
        n: 6,
        f: function(r) {
            var rt = d3.round(r * 2 / Math.sqrt(3), 2);
            var r2 = d3.round(r / 2, 2);
            var rs = d3.round(r, 2);
            return 'M-' + rt + ',-' + r2 + 'H' + rt + 'L0,' + rs + 'Z';
        }
    },
    'triangle-left': {
        n: 7,
        f: function(r) {
            var rt = d3.round(r * 2 / Math.sqrt(3), 2);
            var r2 = d3.round(r / 2, 2);
            var rs = d3.round(r, 2);
            return 'M' + r2 + ',-' + rt + 'V' + rt + 'L-' + rs + ',0Z';
        }
    },
    'triangle-right': {
        n: 8,
        f: function(r) {
            var rt = d3.round(r * 2 / Math.sqrt(3), 2);
            var r2 = d3.round(r / 2, 2);
            var rs = d3.round(r, 2);
            return 'M-' + r2 + ',-' + rt + 'V' + rt + 'L' + rs + ',0Z';
        }
    },
    'triangle-ne': {
        n: 9,
        f: function(r) {
            var r1 = d3.round(r * 0.6, 2);
            var r2 = d3.round(r * 1.2, 2);
            return 'M-' + r2 + ',-' + r1 + 'H' + r1 + 'V' + r2 + 'Z';
        }
    },
    'triangle-se': {
        n: 10,
        f: function(r) {
            var r1 = d3.round(r * 0.6, 2);
            var r2 = d3.round(r * 1.2, 2);
            return 'M' + r1 + ',-' + r2 + 'V' + r1 + 'H-' + r2 + 'Z';
        }
    },
    'triangle-sw': {
        n: 11,
        f: function(r) {
            var r1 = d3.round(r * 0.6, 2);
            var r2 = d3.round(r * 1.2, 2);
            return 'M' + r2 + ',' + r1 + 'H-' + r1 + 'V-' + r2 + 'Z';
        }
    },
    'triangle-nw': {
        n: 12,
        f: function(r) {
            var r1 = d3.round(r * 0.6, 2);
            var r2 = d3.round(r * 1.2, 2);
            return 'M-' + r1 + ',' + r2 + 'V-' + r1 + 'H' + r2 + 'Z';
        }
    },
    pentagon: {
        n: 13,
        f: function(r) {
            var x1 = d3.round(r * 0.951, 2);
            var x2 = d3.round(r * 0.588, 2);
            var y0 = d3.round(-r, 2);
            var y1 = d3.round(r * -0.309, 2);
            var y2 = d3.round(r * 0.809, 2);
            return 'M' + x1 + ',' + y1 + 'L' + x2 + ',' + y2 + 'H-' + x2 +
                'L-' + x1 + ',' + y1 + 'L0,' + y0 + 'Z';
        }
    },
    hexagon: {
        n: 14,
        f: function(r) {
            var y0 = d3.round(r, 2);
            var y1 = d3.round(r / 2, 2);
            var x = d3.round(r * Math.sqrt(3) / 2, 2);
            return 'M' + x + ',-' + y1 + 'V' + y1 + 'L0,' + y0 +
                'L-' + x + ',' + y1 + 'V-' + y1 + 'L0,-' + y0 + 'Z';
        }
    },
    hexagon2: {
        n: 15,
        f: function(r) {
            var x0 = d3.round(r, 2);
            var x1 = d3.round(r / 2, 2);
            var y = d3.round(r * Math.sqrt(3) / 2, 2);
            return 'M-' + x1 + ',' + y + 'H' + x1 + 'L' + x0 +
                ',0L' + x1 + ',-' + y + 'H-' + x1 + 'L-' + x0 + ',0Z';
        }
    },
    octagon: {
        n: 16,
        f: function(r) {
            var a = d3.round(r * 0.924, 2);
            var b = d3.round(r * 0.383, 2);
            return 'M-' + b + ',-' + a + 'H' + b + 'L' + a + ',-' + b + 'V' + b +
                'L' + b + ',' + a + 'H-' + b + 'L-' + a + ',' + b + 'V-' + b + 'Z';
        }
    },
    star: {
        n: 17,
        f: function(r) {
            var rs = r * 1.4;
            var x1 = d3.round(rs * 0.225, 2);
            var x2 = d3.round(rs * 0.951, 2);
            var x3 = d3.round(rs * 0.363, 2);
            var x4 = d3.round(rs * 0.588, 2);
            var y0 = d3.round(-rs, 2);
            var y1 = d3.round(rs * -0.309, 2);
            var y3 = d3.round(rs * 0.118, 2);
            var y4 = d3.round(rs * 0.809, 2);
            var y5 = d3.round(rs * 0.382, 2);
            return 'M' + x1 + ',' + y1 + 'H' + x2 + 'L' + x3 + ',' + y3 +
                'L' + x4 + ',' + y4 + 'L0,' + y5 + 'L-' + x4 + ',' + y4 +
                'L-' + x3 + ',' + y3 + 'L-' + x2 + ',' + y1 + 'H-' + x1 +
                'L0,' + y0 + 'Z';
        }
    },
    hexagram: {
        n: 18,
        f: function(r) {
            var y = d3.round(r * 0.66, 2);
            var x1 = d3.round(r * 0.38, 2);
            var x2 = d3.round(r * 0.76, 2);
            return 'M-' + x2 + ',0l-' + x1 + ',-' + y + 'h' + x2 +
                'l' + x1 + ',-' + y + 'l' + x1 + ',' + y + 'h' + x2 +
                'l-' + x1 + ',' + y + 'l' + x1 + ',' + y + 'h-' + x2 +
                'l-' + x1 + ',' + y + 'l-' + x1 + ',-' + y + 'h-' + x2 + 'Z';
        }
    },
    'star-triangle-up': {
        n: 19,
        f: function(r) {
            var x = d3.round(r * Math.sqrt(3) * 0.8, 2);
            var y1 = d3.round(r * 0.8, 2);
            var y2 = d3.round(r * 1.6, 2);
            var rc = d3.round(r * 4, 2);
            var aPart = 'A ' + rc + ',' + rc + ' 0 0 1 ';
            return 'M-' + x + ',' + y1 + aPart + x + ',' + y1 +
                aPart + '0,-' + y2 + aPart + '-' + x + ',' + y1 + 'Z';
        }
    },
    'star-triangle-down': {
        n: 20,
        f: function(r) {
            var x = d3.round(r * Math.sqrt(3) * 0.8, 2);
            var y1 = d3.round(r * 0.8, 2);
            var y2 = d3.round(r * 1.6, 2);
            var rc = d3.round(r * 4, 2);
            var aPart = 'A ' + rc + ',' + rc + ' 0 0 1 ';
            return 'M' + x + ',-' + y1 + aPart + '-' + x + ',-' + y1 +
                aPart + '0,' + y2 + aPart + x + ',-' + y1 + 'Z';
        }
    },
    'star-square': {
        n: 21,
        f: function(r) {
            var rp = d3.round(r * 1.1, 2);
            var rc = d3.round(r * 2, 2);
            var aPart = 'A ' + rc + ',' + rc + ' 0 0 1 ';
            return 'M-' + rp + ',-' + rp + aPart + '-' + rp + ',' + rp +
                aPart + rp + ',' + rp + aPart + rp + ',-' + rp +
                aPart + '-' + rp + ',-' + rp + 'Z';
        }
    },
    'star-diamond': {
        n: 22,
        f: function(r) {
            var rp = d3.round(r * 1.4, 2);
            var rc = d3.round(r * 1.9, 2);
            var aPart = 'A ' + rc + ',' + rc + ' 0 0 1 ';
            return 'M-' + rp + ',0' + aPart + '0,' + rp +
                aPart + rp + ',0' + aPart + '0,-' + rp +
                aPart + '-' + rp + ',0' + 'Z';
        }
    },
    'diamond-tall': {
        n: 23,
        f: function(r) {
            var x = d3.round(r * 0.7, 2);
            var y = d3.round(r * 1.4, 2);
            return 'M0,' + y + 'L' + x + ',0L0,-' + y + 'L-' + x + ',0Z';
        }
    },
    'diamond-wide': {
        n: 24,
        f: function(r) {
            var x = d3.round(r * 1.4, 2);
            var y = d3.round(r * 0.7, 2);
            return 'M0,' + y + 'L' + x + ',0L0,-' + y + 'L-' + x + ',0Z';
        }
    },
    hourglass: {
        n: 25,
        f: function(r) {
            var rs = d3.round(r, 2);
            return 'M' + rs + ',' + rs + 'H-' + rs + 'L' + rs + ',-' + rs + 'H-' + rs + 'Z';
        },
        noDot: true
    },
    bowtie: {
        n: 26,
        f: function(r) {
            var rs = d3.round(r, 2);
            return 'M' + rs + ',' + rs + 'V-' + rs + 'L-' + rs + ',' + rs + 'V-' + rs + 'Z';
        },
        noDot: true
    },
    'circle-cross': {
        n: 27,
        f: function(r) {
            var rs = d3.round(r, 2);
            return 'M0,' + rs + 'V-' + rs + 'M' + rs + ',0H-' + rs +
                'M' + rs + ',0A' + rs + ',' + rs + ' 0 1,1 0,-' + rs +
                'A' + rs + ',' + rs + ' 0 0,1 ' + rs + ',0Z';
        },
        needLine: true,
        noDot: true
    },
    'circle-x': {
        n: 28,
        f: function(r) {
            var rs = d3.round(r, 2);
            var rc = d3.round(r / Math.sqrt(2), 2);
            return 'M' + rc + ',' + rc + 'L-' + rc + ',-' + rc +
                'M' + rc + ',-' + rc + 'L-' + rc + ',' + rc +
                'M' + rs + ',0A' + rs + ',' + rs + ' 0 1,1 0,-' + rs +
                'A' + rs + ',' + rs + ' 0 0,1 ' + rs + ',0Z';
        },
        needLine: true,
        noDot: true
    },
    'square-cross': {
        n: 29,
        f: function(r) {
            var rs = d3.round(r, 2);
            return 'M0,' + rs + 'V-' + rs + 'M' + rs + ',0H-' + rs +
                'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z';
        },
        needLine: true,
        noDot: true
    },
    'square-x': {
        n: 30,
        f: function(r) {
            var rs = d3.round(r, 2);
            return 'M' + rs + ',' + rs + 'L-' + rs + ',-' + rs +
                'M' + rs + ',-' + rs + 'L-' + rs + ',' + rs +
                'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z';
        },
        needLine: true,
        noDot: true
    },
    'diamond-cross': {
        n: 31,
        f: function(r) {
            var rd = d3.round(r * 1.3, 2);
            return 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z' +
                'M0,-' + rd + 'V' + rd + 'M-' + rd + ',0H' + rd;
        },
        needLine: true,
        noDot: true
    },
    'diamond-x': {
        n: 32,
        f: function(r) {
            var rd = d3.round(r * 1.3, 2);
            var r2 = d3.round(r * 0.65, 2);
            return 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z' +
                'M-' + r2 + ',-' + r2 + 'L' + r2 + ',' + r2 +
                'M-' + r2 + ',' + r2 + 'L' + r2 + ',-' + r2;
        },
        needLine: true,
        noDot: true
    },
    'cross-thin': {
        n: 33,
        f: function(r) {
            var rc = d3.round(r * 1.4, 2);
            return 'M0,' + rc + 'V-' + rc + 'M' + rc + ',0H-' + rc;
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'x-thin': {
        n: 34,
        f: function(r) {
            var rx = d3.round(r, 2);
            return 'M' + rx + ',' + rx + 'L-' + rx + ',-' + rx +
                'M' + rx + ',-' + rx + 'L-' + rx + ',' + rx;
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    asterisk: {
        n: 35,
        f: function(r) {
            var rc = d3.round(r * 1.2, 2);
            var rs = d3.round(r * 0.85, 2);
            return 'M0,' + rc + 'V-' + rc + 'M' + rc + ',0H-' + rc +
                'M' + rs + ',' + rs + 'L-' + rs + ',-' + rs +
                'M' + rs + ',-' + rs + 'L-' + rs + ',' + rs;
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    hash: {
        n: 36,
        f: function(r) {
            var r1 = d3.round(r / 2, 2);
            var r2 = d3.round(r, 2);
            return 'M' + r1 + ',' + r2 + 'V-' + r2 +
                'm-' + r2 + ',0V' + r2 +
                'M' + r2 + ',' + r1 + 'H-' + r2 +
                'm0,-' + r2 + 'H' + r2;
        },
        needLine: true,
        noFill: true
    },
    'y-up': {
        n: 37,
        f: function(r) {
            var x = d3.round(r * 1.2, 2);
            var y0 = d3.round(r * 1.6, 2);
            var y1 = d3.round(r * 0.8, 2);
            return 'M-' + x + ',' + y1 + 'L0,0M' + x + ',' + y1 + 'L0,0M0,-' + y0 + 'L0,0';
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'y-down': {
        n: 38,
        f: function(r) {
            var x = d3.round(r * 1.2, 2);
            var y0 = d3.round(r * 1.6, 2);
            var y1 = d3.round(r * 0.8, 2);
            return 'M-' + x + ',-' + y1 + 'L0,0M' + x + ',-' + y1 + 'L0,0M0,' + y0 + 'L0,0';
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'y-left': {
        n: 39,
        f: function(r) {
            var y = d3.round(r * 1.2, 2);
            var x0 = d3.round(r * 1.6, 2);
            var x1 = d3.round(r * 0.8, 2);
            return 'M' + x1 + ',' + y + 'L0,0M' + x1 + ',-' + y + 'L0,0M-' + x0 + ',0L0,0';
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'y-right': {
        n: 40,
        f: function(r) {
            var y = d3.round(r * 1.2, 2);
            var x0 = d3.round(r * 1.6, 2);
            var x1 = d3.round(r * 0.8, 2);
            return 'M-' + x1 + ',' + y + 'L0,0M-' + x1 + ',-' + y + 'L0,0M' + x0 + ',0L0,0';
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'line-ew': {
        n: 41,
        f: function(r) {
            var rc = d3.round(r * 1.4, 2);
            return 'M' + rc + ',0H-' + rc;
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'line-ns': {
        n: 42,
        f: function(r) {
            var rc = d3.round(r * 1.4, 2);
            return 'M0,' + rc + 'V-' + rc;
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'line-ne': {
        n: 43,
        f: function(r) {
            var rx = d3.round(r, 2);
            return 'M' + rx + ',-' + rx + 'L-' + rx + ',' + rx;
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'line-nw': {
        n: 44,
        f: function(r) {
            var rx = d3.round(r, 2);
            return 'M' + rx + ',' + rx + 'L-' + rx + ',-' + rx;
        },
        needLine: true,
        noDot: true,
        noFill: true
    }
};

},{"d3":151}],597:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    visible: {
        valType: 'boolean',
        
        editType: 'calc',
        
    },
    type: {
        valType: 'enumerated',
        values: ['percent', 'constant', 'sqrt', 'data'],
        
        editType: 'calc',
        
    },
    symmetric: {
        valType: 'boolean',
        
        editType: 'calc',
        
    },
    array: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    arrayminus: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    value: {
        valType: 'number',
        min: 0,
        dflt: 10,
        
        editType: 'calc',
        
    },
    valueminus: {
        valType: 'number',
        min: 0,
        dflt: 10,
        
        editType: 'calc',
        
    },
    traceref: {
        valType: 'integer',
        min: 0,
        dflt: 0,
        
        editType: 'style'
    },
    tracerefminus: {
        valType: 'integer',
        min: 0,
        dflt: 0,
        
        editType: 'style'
    },
    copy_ystyle: {
        valType: 'boolean',
        
        editType: 'plot'
    },
    copy_zstyle: {
        valType: 'boolean',
        
        editType: 'style'
    },
    color: {
        valType: 'color',
        
        editType: 'style',
        
    },
    thickness: {
        valType: 'number',
        min: 0,
        dflt: 2,
        
        editType: 'style',
        
    },
    width: {
        valType: 'number',
        min: 0,
        
        editType: 'plot',
        
    },
    editType: 'calc',

    _deprecated: {
        opacity: {
            valType: 'number',
            
            editType: 'style',
            
        }
    }
};

},{}],598:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var Registry = _dereq_('../../registry');
var Axes = _dereq_('../../plots/cartesian/axes');
var Lib = _dereq_('../../lib');

var makeComputeError = _dereq_('./compute_error');

module.exports = function calc(gd) {
    var calcdata = gd.calcdata;

    for(var i = 0; i < calcdata.length; i++) {
        var calcTrace = calcdata[i];
        var trace = calcTrace[0].trace;

        if(trace.visible === true && Registry.traceIs(trace, 'errorBarsOK')) {
            var xa = Axes.getFromId(gd, trace.xaxis);
            var ya = Axes.getFromId(gd, trace.yaxis);
            calcOneAxis(calcTrace, trace, xa, 'x');
            calcOneAxis(calcTrace, trace, ya, 'y');
        }
    }
};

function calcOneAxis(calcTrace, trace, axis, coord) {
    var opts = trace['error_' + coord] || {};
    var isVisible = (opts.visible && ['linear', 'log'].indexOf(axis.type) !== -1);
    var vals = [];

    if(!isVisible) return;

    var computeError = makeComputeError(opts);

    for(var i = 0; i < calcTrace.length; i++) {
        var calcPt = calcTrace[i];

        var iIn = calcPt.i;

        // for types that don't include `i` in each calcdata point
        if(iIn === undefined) iIn = i;

        // for stacked area inserted points
        // TODO: errorbars have been tested cursorily with stacked area,
        // but not thoroughly. It's not even really clear what you want to do:
        // Should it just be calculated based on that trace's size data?
        // Should you add errors from below in quadrature?
        // And what about normalization, where in principle the errors shrink
        // again when you get up to the top end?
        // One option would be to forbid errorbars with stacking until we
        // decide how to handle these questions.
        else if(iIn === null) continue;

        var calcCoord = calcPt[coord];

        if(!isNumeric(axis.c2l(calcCoord))) continue;

        var errors = computeError(calcCoord, iIn);
        if(isNumeric(errors[0]) && isNumeric(errors[1])) {
            var shoe = calcPt[coord + 's'] = calcCoord - errors[0];
            var hat = calcPt[coord + 'h'] = calcCoord + errors[1];
            vals.push(shoe, hat);
        }
    }

    var axId = axis._id;
    var baseExtremes = trace._extremes[axId];
    var extremes = Axes.findExtremes(
        axis,
        vals,
        Lib.extendFlat({tozero: baseExtremes.opts.tozero}, {padded: true})
    );
    baseExtremes.min = baseExtremes.min.concat(extremes.min);
    baseExtremes.max = baseExtremes.max.concat(extremes.max);
}

},{"../../lib":697,"../../plots/cartesian/axes":745,"../../registry":826,"./compute_error":599,"fast-isnumeric":218}],599:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


/**
 * Error bar computing function generator
 *
 * N.B. The generated function does not clean the dataPt entries. Non-numeric
 * entries result in undefined error magnitudes.
 *
 * @param {object} opts error bar attributes
 *
 * @return {function} :
 *      @param {numeric} dataPt data point from where to compute the error magnitude
 *      @param {number} index index of dataPt in its corresponding data array
 *      @return {array}
 *        - error[0] : error magnitude in the negative direction
 *        - error[1] : " " " " positive "
 */
module.exports = function makeComputeError(opts) {
    var type = opts.type;
    var symmetric = opts.symmetric;

    if(type === 'data') {
        var array = opts.array || [];

        if(symmetric) {
            return function computeError(dataPt, index) {
                var val = +(array[index]);
                return [val, val];
            };
        }
        else {
            var arrayminus = opts.arrayminus || [];
            return function computeError(dataPt, index) {
                var val = +array[index];
                var valMinus = +arrayminus[index];
                // in case one is present and the other is missing, fill in 0
                // so we still see the present one. Mostly useful during manual
                // data entry.
                if(!isNaN(val) || !isNaN(valMinus)) {
                    return [valMinus || 0, val || 0];
                }
                return [NaN, NaN];
            };
        }
    }
    else {
        var computeErrorValue = makeComputeErrorValue(type, opts.value);
        var computeErrorValueMinus = makeComputeErrorValue(type, opts.valueminus);

        if(symmetric || opts.valueminus === undefined) {
            return function computeError(dataPt) {
                var val = computeErrorValue(dataPt);
                return [val, val];
            };
        }
        else {
            return function computeError(dataPt) {
                return [
                    computeErrorValueMinus(dataPt),
                    computeErrorValue(dataPt)
                ];
            };
        }
    }
};

/**
 * Compute error bar magnitude (for all types except data)
 *
 * @param {string} type error bar type
 * @param {numeric} value error bar value
 *
 * @return {function} :
 *      @param {numeric} dataPt
 */
function makeComputeErrorValue(type, value) {
    if(type === 'percent') {
        return function(dataPt) {
            return Math.abs(dataPt * value / 100);
        };
    }
    if(type === 'constant') {
        return function() {
            return Math.abs(value);
        };
    }
    if(type === 'sqrt') {
        return function(dataPt) {
            return Math.sqrt(Math.abs(dataPt));
        };
    }
}

},{}],600:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Template = _dereq_('../../plot_api/plot_template');

var attributes = _dereq_('./attributes');


module.exports = function(traceIn, traceOut, defaultColor, opts) {
    var objName = 'error_' + opts.axis;
    var containerOut = Template.newContainer(traceOut, objName);
    var containerIn = traceIn[objName] || {};

    function coerce(attr, dflt) {
        return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
    }

    var hasErrorBars = (
        containerIn.array !== undefined ||
        containerIn.value !== undefined ||
        containerIn.type === 'sqrt'
    );

    var visible = coerce('visible', hasErrorBars);

    if(visible === false) return;

    var type = coerce('type', 'array' in containerIn ? 'data' : 'percent');
    var symmetric = true;

    if(type !== 'sqrt') {
        symmetric = coerce('symmetric',
            !((type === 'data' ? 'arrayminus' : 'valueminus') in containerIn));
    }

    if(type === 'data') {
        coerce('array');
        coerce('traceref');
        if(!symmetric) {
            coerce('arrayminus');
            coerce('tracerefminus');
        }
    }
    else if(type === 'percent' || type === 'constant') {
        coerce('value');
        if(!symmetric) coerce('valueminus');
    }

    var copyAttr = 'copy_' + opts.inherit + 'style';
    if(opts.inherit) {
        var inheritObj = traceOut['error_' + opts.inherit];
        if((inheritObj || {}).visible) {
            coerce(copyAttr, !(containerIn.color ||
                               isNumeric(containerIn.thickness) ||
                               isNumeric(containerIn.width)));
        }
    }
    if(!opts.inherit || !containerOut[copyAttr]) {
        coerce('color', defaultColor);
        coerce('thickness');
        coerce('width', Registry.traceIs(traceOut, 'gl3d') ? 0 : 4);
    }
};

},{"../../lib":697,"../../plot_api/plot_template":735,"../../registry":826,"./attributes":597,"fast-isnumeric":218}],601:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;

var attributes = _dereq_('./attributes');

var xyAttrs = {
    error_x: Lib.extendFlat({}, attributes),
    error_y: Lib.extendFlat({}, attributes)
};
delete xyAttrs.error_x.copy_zstyle;
delete xyAttrs.error_y.copy_zstyle;
delete xyAttrs.error_y.copy_ystyle;

var xyzAttrs = {
    error_x: Lib.extendFlat({}, attributes),
    error_y: Lib.extendFlat({}, attributes),
    error_z: Lib.extendFlat({}, attributes)
};
delete xyzAttrs.error_x.copy_ystyle;
delete xyzAttrs.error_y.copy_ystyle;
delete xyzAttrs.error_z.copy_ystyle;
delete xyzAttrs.error_z.copy_zstyle;

module.exports = {
    moduleType: 'component',
    name: 'errorbars',

    schema: {
        traces: {
            scatter: xyAttrs,
            bar: xyAttrs,
            histogram: xyAttrs,
            scatter3d: overrideAll(xyzAttrs, 'calc', 'nested'),
            scattergl: overrideAll(xyAttrs, 'calc', 'nested')
        }
    },

    supplyDefaults: _dereq_('./defaults'),

    calc: _dereq_('./calc'),
    makeComputeError: _dereq_('./compute_error'),

    plot: _dereq_('./plot'),
    style: _dereq_('./style'),
    hoverInfo: hoverInfo
};

function hoverInfo(calcPoint, trace, hoverPoint) {
    if((trace.error_y || {}).visible) {
        hoverPoint.yerr = calcPoint.yh - calcPoint.y;
        if(!trace.error_y.symmetric) hoverPoint.yerrneg = calcPoint.y - calcPoint.ys;
    }
    if((trace.error_x || {}).visible) {
        hoverPoint.xerr = calcPoint.xh - calcPoint.x;
        if(!trace.error_x.symmetric) hoverPoint.xerrneg = calcPoint.x - calcPoint.xs;
    }
}

},{"../../lib":697,"../../plot_api/edit_types":728,"./attributes":597,"./calc":598,"./compute_error":599,"./defaults":600,"./plot":602,"./style":603}],602:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');

var Drawing = _dereq_('../drawing');
var subTypes = _dereq_('../../traces/scatter/subtypes');

module.exports = function plot(gd, traces, plotinfo, transitionOpts) {
    var isNew;

    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    var hasAnimation = transitionOpts && transitionOpts.duration > 0;

    traces.each(function(d) {
        var trace = d[0].trace;
        // || {} is in case the trace (specifically scatterternary)
        // doesn't support error bars at all, but does go through
        // the scatter.plot mechanics, which calls ErrorBars.plot
        // internally
        var xObj = trace.error_x || {};
        var yObj = trace.error_y || {};

        var keyFunc;

        if(trace.ids) {
            keyFunc = function(d) {return d.id;};
        }

        var sparse = (
            subTypes.hasMarkers(trace) &&
            trace.marker.maxdisplayed > 0
        );

        if(!yObj.visible && !xObj.visible) d = [];

        var errorbars = d3.select(this).selectAll('g.errorbar')
            .data(d, keyFunc);

        errorbars.exit().remove();

        if(!d.length) return;

        if(!xObj.visible) errorbars.selectAll('path.xerror').remove();
        if(!yObj.visible) errorbars.selectAll('path.yerror').remove();

        errorbars.style('opacity', 1);

        var enter = errorbars.enter().append('g')
            .classed('errorbar', true);

        if(hasAnimation) {
            enter.style('opacity', 0).transition()
                .duration(transitionOpts.duration)
                .style('opacity', 1);
        }

        Drawing.setClipUrl(errorbars, plotinfo.layerClipId, gd);

        errorbars.each(function(d) {
            var errorbar = d3.select(this);
            var coords = errorCoords(d, xa, ya);

            if(sparse && !d.vis) return;

            var path;

            var yerror = errorbar.select('path.yerror');
            if(yObj.visible && isNumeric(coords.x) &&
                    isNumeric(coords.yh) &&
                    isNumeric(coords.ys)) {
                var yw = yObj.width;

                path = 'M' + (coords.x - yw) + ',' +
                    coords.yh + 'h' + (2 * yw) + // hat
                    'm-' + yw + ',0V' + coords.ys; // bar


                if(!coords.noYS) path += 'm-' + yw + ',0h' + (2 * yw); // shoe

                isNew = !yerror.size();

                if(isNew) {
                    yerror = errorbar.append('path')
                        .style('vector-effect', 'non-scaling-stroke')
                        .classed('yerror', true);
                } else if(hasAnimation) {
                    yerror = yerror
                        .transition()
                            .duration(transitionOpts.duration)
                            .ease(transitionOpts.easing);
                }

                yerror.attr('d', path);
            }
            else yerror.remove();

            var xerror = errorbar.select('path.xerror');
            if(xObj.visible && isNumeric(coords.y) &&
                    isNumeric(coords.xh) &&
                    isNumeric(coords.xs)) {
                var xw = (xObj.copy_ystyle ? yObj : xObj).width;

                path = 'M' + coords.xh + ',' +
                    (coords.y - xw) + 'v' + (2 * xw) + // hat
                    'm0,-' + xw + 'H' + coords.xs; // bar

                if(!coords.noXS) path += 'm0,-' + xw + 'v' + (2 * xw); // shoe

                isNew = !xerror.size();

                if(isNew) {
                    xerror = errorbar.append('path')
                        .style('vector-effect', 'non-scaling-stroke')
                        .classed('xerror', true);
                } else if(hasAnimation) {
                    xerror = xerror
                        .transition()
                            .duration(transitionOpts.duration)
                            .ease(transitionOpts.easing);
                }

                xerror.attr('d', path);
            }
            else xerror.remove();
        });
    });
};

// compute the coordinates of the error-bar objects
function errorCoords(d, xa, ya) {
    var out = {
        x: xa.c2p(d.x),
        y: ya.c2p(d.y)
    };

    // calculate the error bar size and hat and shoe locations
    if(d.yh !== undefined) {
        out.yh = ya.c2p(d.yh);
        out.ys = ya.c2p(d.ys);

        // if the shoes go off-scale (ie log scale, error bars past zero)
        // clip the bar and hide the shoes
        if(!isNumeric(out.ys)) {
            out.noYS = true;
            out.ys = ya.c2p(d.ys, true);
        }
    }

    if(d.xh !== undefined) {
        out.xh = xa.c2p(d.xh);
        out.xs = xa.c2p(d.xs);

        if(!isNumeric(out.xs)) {
            out.noXS = true;
            out.xs = xa.c2p(d.xs, true);
        }
    }

    return out;
}

},{"../../traces/scatter/subtypes":1072,"../drawing":595,"d3":151,"fast-isnumeric":218}],603:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

var Color = _dereq_('../color');


module.exports = function style(traces) {
    traces.each(function(d) {
        var trace = d[0].trace;
        var yObj = trace.error_y || {};
        var xObj = trace.error_x || {};

        var s = d3.select(this);

        s.selectAll('path.yerror')
            .style('stroke-width', yObj.thickness + 'px')
            .call(Color.stroke, yObj.color);

        if(xObj.copy_ystyle) xObj = yObj;

        s.selectAll('path.xerror')
            .style('stroke-width', xObj.thickness + 'px')
            .call(Color.stroke, xObj.color);
    });
};

},{"../color":574,"d3":151}],604:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = _dereq_('../../plots/font_attributes');

module.exports = {
    hoverlabel: {
        bgcolor: {
            valType: 'color',
            
            arrayOk: true,
            editType: 'none',
            
        },
        bordercolor: {
            valType: 'color',
            
            arrayOk: true,
            editType: 'none',
            
        },
        font: fontAttrs({
            arrayOk: true,
            editType: 'none',
            
        }),
        namelength: {
            valType: 'integer',
            min: -1,
            arrayOk: true,
            
            editType: 'none',
            
        },
        editType: 'calc'
    }
};

},{"../../plots/font_attributes":771}],605:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Registry = _dereq_('../../registry');

module.exports = function calc(gd) {
    var calcdata = gd.calcdata;
    var fullLayout = gd._fullLayout;

    function makeCoerceHoverInfo(trace) {
        return function(val) {
            return Lib.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout);
        };
    }

    for(var i = 0; i < calcdata.length; i++) {
        var cd = calcdata[i];
        var trace = cd[0].trace;

        // don't include hover calc fields for pie traces
        // as calcdata items might be sorted by value and
        // won't match the data array order.
        if(Registry.traceIs(trace, 'pie')) continue;

        var fillFn = Registry.traceIs(trace, '2dMap') ? paste : Lib.fillArray;

        fillFn(trace.hoverinfo, cd, 'hi', makeCoerceHoverInfo(trace));

        if(trace.hovertemplate) fillFn(trace.hovertemplate, cd, 'ht');

        if(!trace.hoverlabel) continue;

        fillFn(trace.hoverlabel.bgcolor, cd, 'hbg');
        fillFn(trace.hoverlabel.bordercolor, cd, 'hbc');
        fillFn(trace.hoverlabel.font.size, cd, 'hts');
        fillFn(trace.hoverlabel.font.color, cd, 'htc');
        fillFn(trace.hoverlabel.font.family, cd, 'htf');
        fillFn(trace.hoverlabel.namelength, cd, 'hnl');
    }
};

function paste(traceAttr, cd, cdAttr, fn) {
    fn = fn || Lib.identity;

    if(Array.isArray(traceAttr)) {
        cd[0][cdAttr] = fn(traceAttr);
    }
}

},{"../../lib":697,"../../registry":826}],606:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');
var hover = _dereq_('./hover').hover;

module.exports = function click(gd, evt, subplot) {
    var annotationsDone = Registry.getComponentMethod('annotations', 'onClick')(gd, gd._hoverdata);

    // fallback to fail-safe in case the plot type's hover method doesn't pass the subplot.
    // Ternary, for example, didn't, but it was caught because tested.
    if(subplot !== undefined) {
        // The true flag at the end causes it to re-run the hover computation to figure out *which*
        // point is being clicked. Without this, clicking is somewhat unreliable.
        hover(gd, evt, subplot, true);
    }

    function emitClick() { gd.emit('plotly_click', {points: gd._hoverdata, event: evt}); }

    if(gd._hoverdata && evt && evt.target) {
        if(annotationsDone && annotationsDone.then) {
            annotationsDone.then(emitClick);
        }
        else emitClick();

        // why do we get a double event without this???
        if(evt.stopImmediatePropagation) evt.stopImmediatePropagation();
    }
};

},{"../../registry":826,"./hover":610}],607:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    // hover labels for multiple horizontal bars get tilted by this angle
    YANGLE: 60,

    // size and display constants for hover text

    // pixel size of hover arrows
    HOVERARROWSIZE: 6,
    // pixels padding around text
    HOVERTEXTPAD: 3,
    // hover font
    HOVERFONTSIZE: 13,
    HOVERFONT: 'Arial, sans-serif',

    // minimum time (msec) between hover calls
    HOVERMINTIME: 50,

    // ID suffix (with fullLayout._uid) for hover events in the throttle cache
    HOVERID: '-hover'
};

},{}],608:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var attributes = _dereq_('./attributes');
var handleHoverLabelDefaults = _dereq_('./hoverlabel_defaults');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    handleHoverLabelDefaults(traceIn, traceOut, coerce, layout.hoverlabel);
};

},{"../../lib":697,"./attributes":604,"./hoverlabel_defaults":611}],609:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

// look for either subplot or xaxis and yaxis attributes
// does not handle splom case
exports.getSubplot = function getSubplot(trace) {
    return trace.subplot || (trace.xaxis + trace.yaxis) || trace.geo;
};

// is trace in given list of subplots?
// does handle splom case
exports.isTraceInSubplots = function isTraceInSubplot(trace, subplots) {
    if(trace.type === 'splom') {
        var xaxes = trace.xaxes || [];
        var yaxes = trace.yaxes || [];
        for(var i = 0; i < xaxes.length; i++) {
            for(var j = 0; j < yaxes.length; j++) {
                if(subplots.indexOf(xaxes[i] + yaxes[j]) !== -1) {
                    return true;
                }
            }
        }
        return false;
    }

    return subplots.indexOf(exports.getSubplot(trace)) !== -1;
};

// convenience functions for mapping all relevant axes
exports.flat = function flat(subplots, v) {
    var out = new Array(subplots.length);
    for(var i = 0; i < subplots.length; i++) {
        out[i] = v;
    }
    return out;
};

exports.p2c = function p2c(axArray, v) {
    var out = new Array(axArray.length);
    for(var i = 0; i < axArray.length; i++) {
        out[i] = axArray[i].p2c(v);
    }
    return out;
};

exports.getDistanceFunction = function getDistanceFunction(mode, dx, dy, dxy) {
    if(mode === 'closest') return dxy || exports.quadrature(dx, dy);
    return mode === 'x' ? dx : dy;
};

exports.getClosest = function getClosest(cd, distfn, pointData) {
    // do we already have a point number? (array mode only)
    if(pointData.index !== false) {
        if(pointData.index >= 0 && pointData.index < cd.length) {
            pointData.distance = 0;
        }
        else pointData.index = false;
    }
    else {
        // apply the distance function to each data point
        // this is the longest loop... if this bogs down, we may need
        // to create pre-sorted data (by x or y), not sure how to
        // do this for 'closest'
        for(var i = 0; i < cd.length; i++) {
            var newDistance = distfn(cd[i]);
            if(newDistance <= pointData.distance) {
                pointData.index = i;
                pointData.distance = newDistance;
            }
        }
    }
    return pointData;
};

/*
 * pseudo-distance function for hover effects on areas: inside the region
 * distance is finite (`passVal`), outside it's Infinity.
 *
 * @param {number} v0: signed difference between the current position and the left edge
 * @param {number} v1: signed difference between the current position and the right edge
 * @param {number} passVal: the value to return on success
 */
exports.inbox = function inbox(v0, v1, passVal) {
    return (v0 * v1 < 0 || v0 === 0) ? passVal : Infinity;
};

exports.quadrature = function quadrature(dx, dy) {
    return function(di) {
        var x = dx(di);
        var y = dy(di);
        return Math.sqrt(x * x + y * y);
    };
};

/** Fill event data point object for hover and selection.
 *  Invokes _module.eventData if present.
 *
 * N.B. note that point 'index' corresponds to input data array index
 *  whereas 'number' is its post-transform version.
 *
 * If the hovered/selected pt corresponds to an multiple input points
 * (e.g. for histogram and transformed traces), 'pointNumbers` and 'pointIndices'
 * are include in the event data.
 *
 * @param {object} pt
 * @param {object} trace
 * @param {object} cd
 * @return {object}
 */
exports.makeEventData = function makeEventData(pt, trace, cd) {
    // hover uses 'index', select uses 'pointNumber'
    var pointNumber = 'index' in pt ? pt.index : pt.pointNumber;

    var out = {
        data: trace._input,
        fullData: trace,
        curveNumber: trace.index,
        pointNumber: pointNumber
    };

    if(trace._indexToPoints) {
        var pointIndices = trace._indexToPoints[pointNumber];

        if(pointIndices.length === 1) {
            out.pointIndex = pointIndices[0];
        } else {
            out.pointIndices = pointIndices;
        }
    } else {
        out.pointIndex = pointNumber;
    }

    if(trace._module.eventData) {
        out = trace._module.eventData(out, pt, trace, cd, pointNumber);
    } else {
        if('xVal' in pt) out.x = pt.xVal;
        else if('x' in pt) out.x = pt.x;

        if('yVal' in pt) out.y = pt.yVal;
        else if('y' in pt) out.y = pt.y;

        if(pt.xa) out.xaxis = pt.xa;
        if(pt.ya) out.yaxis = pt.ya;
        if(pt.zLabelVal !== undefined) out.z = pt.zLabelVal;
    }

    exports.appendArrayPointValue(out, trace, pointNumber);

    return out;
};

/** Appends values inside array attributes corresponding to given point number
 *
 * @param {object} pointData : point data object (gets mutated here)
 * @param {object} trace : full trace object
 * @param {number|Array(number)} pointNumber : point number. May be a length-2 array
 *     [row, col] to dig into 2D arrays
 */
exports.appendArrayPointValue = function(pointData, trace, pointNumber) {
    var arrayAttrs = trace._arrayAttrs;

    if(!arrayAttrs) {
        return;
    }

    for(var i = 0; i < arrayAttrs.length; i++) {
        var astr = arrayAttrs[i];
        var key = getPointKey(astr);

        if(pointData[key] === undefined) {
            var val = Lib.nestedProperty(trace, astr).get();
            var pointVal = getPointData(val, pointNumber);

            if(pointVal !== undefined) pointData[key] = pointVal;
        }
    }
};

/**
 * Appends values inside array attributes corresponding to given point number array
 * For use when pointData references a plot entity that arose (or potentially arose)
 * from multiple points in the input data
 *
 * @param {object} pointData : point data object (gets mutated here)
 * @param {object} trace : full trace object
 * @param {Array(number)|Array(Array(number))} pointNumbers : Array of point numbers.
 *     Each entry in the array may itself be a length-2 array [row, col] to dig into 2D arrays
 */
exports.appendArrayMultiPointValues = function(pointData, trace, pointNumbers) {
    var arrayAttrs = trace._arrayAttrs;

    if(!arrayAttrs) {
        return;
    }

    for(var i = 0; i < arrayAttrs.length; i++) {
        var astr = arrayAttrs[i];
        var key = getPointKey(astr);

        if(pointData[key] === undefined) {
            var val = Lib.nestedProperty(trace, astr).get();
            var keyVal = new Array(pointNumbers.length);

            for(var j = 0; j < pointNumbers.length; j++) {
                keyVal[j] = getPointData(val, pointNumbers[j]);
            }
            pointData[key] = keyVal;
        }
    }
};

var pointKeyMap = {
    ids: 'id',
    locations: 'location',
    labels: 'label',
    values: 'value',
    'marker.colors': 'color'
};

function getPointKey(astr) {
    return pointKeyMap[astr] || astr;
}

function getPointData(val, pointNumber) {
    if(Array.isArray(pointNumber)) {
        if(Array.isArray(val) && Array.isArray(val[pointNumber[0]])) {
            return val[pointNumber[0]][pointNumber[1]];
        }
    } else {
        return val[pointNumber];
    }
}

},{"../../lib":697}],610:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');
var tinycolor = _dereq_('tinycolor2');

var Lib = _dereq_('../../lib');
var Events = _dereq_('../../lib/events');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var overrideCursor = _dereq_('../../lib/override_cursor');
var Drawing = _dereq_('../drawing');
var Color = _dereq_('../color');
var dragElement = _dereq_('../dragelement');
var Axes = _dereq_('../../plots/cartesian/axes');
var Registry = _dereq_('../../registry');

var helpers = _dereq_('./helpers');
var constants = _dereq_('./constants');

// hover labels for multiple horizontal bars get tilted by some angle,
// then need to be offset differently if they overlap
var YANGLE = constants.YANGLE;
var YA_RADIANS = Math.PI * YANGLE / 180;

// expansion of projected height
var YFACTOR = 1 / Math.sin(YA_RADIANS);

// to make the appropriate post-rotation x offset,
// you need both x and y offsets
var YSHIFTX = Math.cos(YA_RADIANS);
var YSHIFTY = Math.sin(YA_RADIANS);

// size and display constants for hover text
var HOVERARROWSIZE = constants.HOVERARROWSIZE;
var HOVERTEXTPAD = constants.HOVERTEXTPAD;

// fx.hover: highlight data on hover
// evt can be a mousemove event, or an object with data about what points
//   to hover on
//      {xpx,ypx[,hovermode]} - pixel locations from top left
//          (with optional overriding hovermode)
//      {xval,yval[,hovermode]} - data values
//      [{curveNumber,(pointNumber|xval and/or yval)}] -
//              array of specific points to highlight
//          pointNumber is a single integer if gd.data[curveNumber] is 1D,
//              or a two-element array if it's 2D
//          xval and yval are data values,
//              1D data may specify either or both,
//              2D data must specify both
// subplot is an id string (default "xy")
// makes use of gl.hovermode, which can be:
//      x (find the points with the closest x values, ie a column),
//      closest (find the single closest point)
//    internally there are two more that occasionally get used:
//      y (pick out a row - only used for multiple horizontal bar charts)
//      array (used when the user specifies an explicit
//          array of points to hover on)
//
// We wrap the hovers in a timer, to limit their frequency.
// The actual rendering is done by private function _hover.
exports.hover = function hover(gd, evt, subplot, noHoverEvent) {
    gd = Lib.getGraphDiv(gd);

    Lib.throttle(
        gd._fullLayout._uid + constants.HOVERID,
        constants.HOVERMINTIME,
        function() { _hover(gd, evt, subplot, noHoverEvent); }
    );
};

/*
 * Draw a single hover item in a pre-existing svg container somewhere
 * hoverItem should have keys:
 *    - x and y (or x0, x1, y0, and y1):
 *      the pixel position to mark, relative to opts.container
 *    - xLabel, yLabel, zLabel, text, and name:
 *      info to go in the label
 *    - color:
 *      the background color for the label.
 *    - idealAlign (optional):
 *      'left' or 'right' for which side of the x/y box to try to put this on first
 *    - borderColor (optional):
 *      color for the border, defaults to strongest contrast with color
 *    - fontFamily (optional):
 *      string, the font for this label, defaults to constants.HOVERFONT
 *    - fontSize (optional):
 *      the label font size, defaults to constants.HOVERFONTSIZE
 *    - fontColor (optional):
 *      defaults to borderColor
 * opts should have keys:
 *    - bgColor:
 *      the background color this is against, used if the trace is
 *      non-opaque, and for the name, which goes outside the box
 *    - container:
 *      a <svg> or <g> element to add the hover label to
 *    - outerContainer:
 *      normally a parent of `container`, sets the bounding box to use to
 *      constrain the hover label and determine whether to show it on the left or right
 */
exports.loneHover = function loneHover(hoverItem, opts) {
    var pointData = {
        color: hoverItem.color || Color.defaultLine,
        x0: hoverItem.x0 || hoverItem.x || 0,
        x1: hoverItem.x1 || hoverItem.x || 0,
        y0: hoverItem.y0 || hoverItem.y || 0,
        y1: hoverItem.y1 || hoverItem.y || 0,
        xLabel: hoverItem.xLabel,
        yLabel: hoverItem.yLabel,
        zLabel: hoverItem.zLabel,
        text: hoverItem.text,
        name: hoverItem.name,
        idealAlign: hoverItem.idealAlign,

        // optional extra bits of styling
        borderColor: hoverItem.borderColor,
        fontFamily: hoverItem.fontFamily,
        fontSize: hoverItem.fontSize,
        fontColor: hoverItem.fontColor,

        // filler to make createHoverText happy
        trace: hoverItem.trace || {
            index: 0,
            hoverinfo: ''
        },
        xa: {_offset: 0},
        ya: {_offset: 0},
        index: 0,

        hovertemplate: hoverItem.hovertemplate || false,
        eventData: hoverItem.eventData || false,
        hovertemplateLabels: hoverItem.hovertemplateLabels || false,
    };

    var container3 = d3.select(opts.container);
    var outerContainer3 = opts.outerContainer ?
        d3.select(opts.outerContainer) : container3;

    var fullOpts = {
        hovermode: 'closest',
        rotateLabels: false,
        bgColor: opts.bgColor || Color.background,
        container: container3,
        outerContainer: outerContainer3
    };
    var hoverLabel = createHoverText([pointData], fullOpts, opts.gd);
    alignHoverText(hoverLabel, fullOpts.rotateLabels);

    return hoverLabel.node();
};

exports.multiHovers = function multiHovers(hoverItems, opts) {

    if(!Array.isArray(hoverItems)) {
        hoverItems = [hoverItems];
    }

    var pointsData = hoverItems.map(function(hoverItem) {
        return {
            color: hoverItem.color || Color.defaultLine,
            x0: hoverItem.x0 || hoverItem.x || 0,
            x1: hoverItem.x1 || hoverItem.x || 0,
            y0: hoverItem.y0 || hoverItem.y || 0,
            y1: hoverItem.y1 || hoverItem.y || 0,
            xLabel: hoverItem.xLabel,
            yLabel: hoverItem.yLabel,
            zLabel: hoverItem.zLabel,
            text: hoverItem.text,
            name: hoverItem.name,
            idealAlign: hoverItem.idealAlign,

            // optional extra bits of styling
            borderColor: hoverItem.borderColor,
            fontFamily: hoverItem.fontFamily,
            fontSize: hoverItem.fontSize,
            fontColor: hoverItem.fontColor,

            // filler to make createHoverText happy
            trace: hoverItem.trace || {
                index: 0,
                hoverinfo: ''
            },
            xa: {_offset: 0},
            ya: {_offset: 0},
            index: 0,

            hovertemplate: hoverItem.hovertemplate || false,
            eventData: hoverItem.eventData || false,
            hovertemplateLabels: hoverItem.hovertemplateLabels || false,
        };
    });


    var container3 = d3.select(opts.container);
    var outerContainer3 = opts.outerContainer ? d3.select(opts.outerContainer) : container3;

    var fullOpts = {
        hovermode: 'closest',
        rotateLabels: false,
        bgColor: opts.bgColor || Color.background,
        container: container3,
        outerContainer: outerContainer3
    };

    var hoverLabel = createHoverText(pointsData, fullOpts, opts.gd);

    // Fix vertical overlap
    var tooltipSpacing = 5;
    var lastBottomY = 0;
    hoverLabel
        .sort(function(a, b) {return a.y0 - b.y0;})
        .each(function(d) {
            var topY = d.y0 - d.by / 2;

            if((topY - tooltipSpacing) < lastBottomY) {
                d.offset = (lastBottomY - topY) + tooltipSpacing;
            } else {
                d.offset = 0;
            }

            lastBottomY = topY + d.by + d.offset;
        });


    alignHoverText(hoverLabel, fullOpts.rotateLabels);

    return hoverLabel.node();
};

// The actual implementation is here:
function _hover(gd, evt, subplot, noHoverEvent) {
    if(!subplot) subplot = 'xy';

    // if the user passed in an array of subplots,
    // use those instead of finding overlayed plots
    var subplots = Array.isArray(subplot) ? subplot : [subplot];

    var fullLayout = gd._fullLayout;
    var plots = fullLayout._plots || [];
    var plotinfo = plots[subplot];
    var hasCartesian = fullLayout._has('cartesian');

    // list of all overlaid subplots to look at
    if(plotinfo) {
        var overlayedSubplots = plotinfo.overlays.map(function(pi) {
            return pi.id;
        });

        subplots = subplots.concat(overlayedSubplots);
    }

    var len = subplots.length;
    var xaArray = new Array(len);
    var yaArray = new Array(len);
    var supportsCompare = false;

    for(var i = 0; i < len; i++) {
        var spId = subplots[i];

        // 'cartesian' case
        var plotObj = plots[spId];
        if(plotObj) {
            supportsCompare = true;

            // TODO make sure that fullLayout_plots axis refs
            // get updated properly so that we don't have
            // to use Axes.getFromId in general.

            xaArray[i] = Axes.getFromId(gd, plotObj.xaxis._id);
            yaArray[i] = Axes.getFromId(gd, plotObj.yaxis._id);
            continue;
        }

        // other subplot types
        var _subplot = fullLayout[spId]._subplot;
        xaArray[i] = _subplot.xaxis;
        yaArray[i] = _subplot.yaxis;
    }

    var hovermode = evt.hovermode || fullLayout.hovermode;

    if(hovermode && !supportsCompare) hovermode = 'closest';

    if(['x', 'y', 'closest'].indexOf(hovermode) === -1 || !gd.calcdata ||
            gd.querySelector('.zoombox') || gd._dragging) {
        return dragElement.unhoverRaw(gd, evt);
    }

    var hoverdistance = fullLayout.hoverdistance === -1 ? Infinity : fullLayout.hoverdistance;
    var spikedistance = fullLayout.spikedistance === -1 ? Infinity : fullLayout.spikedistance;

    // hoverData: the set of candidate points we've found to highlight
    var hoverData = [];

    // searchData: the data to search in. Mostly this is just a copy of
    // gd.calcdata, filtered to the subplot and overlays we're on
    // but if a point array is supplied it will be a mapping
    // of indicated curves
    var searchData = [];

    // [x|y]valArray: the axis values of the hover event
    // mapped onto each of the currently selected overlaid subplots
    var xvalArray, yvalArray;

    var itemnum, curvenum, cd, trace, subplotId, subploti, mode,
        xval, yval, pointData, closedataPreviousLength;

    // spikePoints: the set of candidate points we've found to draw spikes to
    var spikePoints = {
        hLinePoint: null,
        vLinePoint: null
    };

    // does subplot have one (or more) horizontal traces?
    // This is used to determine whether we rotate the labels or not
    var hasOneHorizontalTrace = false;

    // Figure out what we're hovering on:
    // mouse location or user-supplied data

    if(Array.isArray(evt)) {
        // user specified an array of points to highlight
        hovermode = 'array';
        for(itemnum = 0; itemnum < evt.length; itemnum++) {
            cd = gd.calcdata[evt[itemnum].curveNumber || 0];
            if(cd) {
                trace = cd[0].trace;
                if(cd[0].trace.hoverinfo !== 'skip') {
                    searchData.push(cd);
                    if(trace.orientation === 'h') {
                        hasOneHorizontalTrace = true;
                    }
                }
            }
        }
    }
    else {
        for(curvenum = 0; curvenum < gd.calcdata.length; curvenum++) {
            cd = gd.calcdata[curvenum];
            trace = cd[0].trace;
            if(trace.hoverinfo !== 'skip' && helpers.isTraceInSubplots(trace, subplots)) {
                searchData.push(cd);
                if(trace.orientation === 'h') {
                    hasOneHorizontalTrace = true;
                }
            }
        }

        // [x|y]px: the pixels (from top left) of the mouse location
        // on the currently selected plot area
        // add pointerX|Y property for drawing the spikes in spikesnap 'cursor' situation
        var hasUserCalledHover = !evt.target;
        var xpx, ypx;

        if(hasUserCalledHover) {
            if('xpx' in evt) xpx = evt.xpx;
            else xpx = xaArray[0]._length / 2;

            if('ypx' in evt) ypx = evt.ypx;
            else ypx = yaArray[0]._length / 2;
        }
        else {
            // fire the beforehover event and quit if it returns false
            // note that we're only calling this on real mouse events, so
            // manual calls to fx.hover will always run.
            if(Events.triggerHandler(gd, 'plotly_beforehover', evt) === false) {
                return;
            }

            var dbb = evt.target.getBoundingClientRect();

            xpx = evt.clientX - dbb.left;
            ypx = evt.clientY - dbb.top;

            // in case hover was called from mouseout into hovertext,
            // it's possible you're not actually over the plot anymore
            if(xpx < 0 || xpx > xaArray[0]._length || ypx < 0 || ypx > yaArray[0]._length) {
                return dragElement.unhoverRaw(gd, evt);
            }
        }

        evt.pointerX = xpx + xaArray[0]._offset;
        evt.pointerY = ypx + yaArray[0]._offset;

        if('xval' in evt) xvalArray = helpers.flat(subplots, evt.xval);
        else xvalArray = helpers.p2c(xaArray, xpx);

        if('yval' in evt) yvalArray = helpers.flat(subplots, evt.yval);
        else yvalArray = helpers.p2c(yaArray, ypx);

        if(!isNumeric(xvalArray[0]) || !isNumeric(yvalArray[0])) {
            Lib.warn('Fx.hover failed', evt, gd);
            return dragElement.unhoverRaw(gd, evt);
        }
    }

    // the pixel distance to beat as a matching point
    // in 'x' or 'y' mode this resets for each trace
    var distance = Infinity;

    // find the closest point in each trace
    // this is minimum dx and/or dy, depending on mode
    // and the pixel position for the label (labelXpx, labelYpx)
    for(curvenum = 0; curvenum < searchData.length; curvenum++) {
        cd = searchData[curvenum];

        // filter out invisible or broken data
        if(!cd || !cd[0] || !cd[0].trace || cd[0].trace.visible !== true) continue;

        trace = cd[0].trace;

        // Explicitly bail out for these two. I don't know how to otherwise prevent
        // the rest of this function from running and failing
        if(['carpet', 'contourcarpet'].indexOf(trace._module.name) !== -1) continue;

        if(trace.type === 'splom') {
            // splom traces do not generate overlay subplots,
            // it is safe to assume here splom traces correspond to the 0th subplot
            subploti = 0;
            subplotId = subplots[subploti];
        } else {
            subplotId = helpers.getSubplot(trace);
            subploti = subplots.indexOf(subplotId);
        }

        // within one trace mode can sometimes be overridden
        mode = hovermode;

        // container for new point, also used to pass info into module.hoverPoints
        pointData = {
            // trace properties
            cd: cd,
            trace: trace,
            xa: xaArray[subploti],
            ya: yaArray[subploti],

            // max distances for hover and spikes - for points that want to show but do not
            // want to override other points, set distance/spikeDistance equal to max*Distance
            // and it will not get filtered out but it will be guaranteed to have a greater
            // distance than any point that calculated a real distance.
            maxHoverDistance: hoverdistance,
            maxSpikeDistance: spikedistance,

            // point properties - override all of these
            index: false, // point index in trace - only used by plotly.js hoverdata consumers
            distance: Math.min(distance, hoverdistance), // pixel distance or pseudo-distance

            // distance/pseudo-distance for spikes. This distance should always be calculated
            // as if in "closest" mode, and should only be set if this point should
            // generate a spike.
            spikeDistance: Infinity,

            // in some cases the spikes have different positioning from the hover label
            // they don't need x0/x1, just one position
            xSpike: undefined,
            ySpike: undefined,

            // where and how to display the hover label
            color: Color.defaultLine, // trace color
            name: trace.name,
            x0: undefined,
            x1: undefined,
            y0: undefined,
            y1: undefined,
            xLabelVal: undefined,
            yLabelVal: undefined,
            zLabelVal: undefined,
            text: undefined
        };

        // add ref to subplot object (non-cartesian case)
        if(fullLayout[subplotId]) {
            pointData.subplot = fullLayout[subplotId]._subplot;
        }
        // add ref to splom scene
        if(fullLayout._splomScenes && fullLayout._splomScenes[trace.uid]) {
            pointData.scene = fullLayout._splomScenes[trace.uid];
        }

        closedataPreviousLength = hoverData.length;

        // for a highlighting array, figure out what
        // we're searching for with this element
        if(mode === 'array') {
            var selection = evt[curvenum];
            if('pointNumber' in selection) {
                pointData.index = selection.pointNumber;
                mode = 'closest';
            }
            else {
                mode = '';
                if('xval' in selection) {
                    xval = selection.xval;
                    mode = 'x';
                }
                if('yval' in selection) {
                    yval = selection.yval;
                    mode = mode ? 'closest' : 'y';
                }
            }
        }
        else {
            xval = xvalArray[subploti];
            yval = yvalArray[subploti];
        }

        // Now if there is range to look in, find the points to hover.
        if(hoverdistance !== 0) {
            if(trace._module && trace._module.hoverPoints) {
                var newPoints = trace._module.hoverPoints(pointData, xval, yval, mode, fullLayout._hoverlayer);
                if(newPoints) {
                    var newPoint;
                    for(var newPointNum = 0; newPointNum < newPoints.length; newPointNum++) {
                        newPoint = newPoints[newPointNum];
                        if(isNumeric(newPoint.x0) && isNumeric(newPoint.y0)) {
                            hoverData.push(cleanPoint(newPoint, hovermode));
                        }
                    }
                }
            }
            else {
                Lib.log('Unrecognized trace type in hover:', trace);
            }
        }

        // in closest mode, remove any existing (farther) points
        // and don't look any farther than this latest point (or points, some
        // traces like box & violin make multiple hover labels at once)
        if(hovermode === 'closest' && hoverData.length > closedataPreviousLength) {
            hoverData.splice(0, closedataPreviousLength);
            distance = hoverData[0].distance;
        }

        // Now if there is range to look in, find the points to draw the spikelines
        // Do it only if there is no hoverData
        if(hasCartesian && (spikedistance !== 0)) {
            if(hoverData.length === 0) {
                pointData.distance = spikedistance;
                pointData.index = false;
                var closestPoints = trace._module.hoverPoints(pointData, xval, yval, 'closest', fullLayout._hoverlayer);
                if(closestPoints) {
                    closestPoints = closestPoints.filter(function(point) {
                        // some hover points, like scatter fills, do not allow spikes,
                        // so will generate a hover point but without a valid spikeDistance
                        return point.spikeDistance <= spikedistance;
                    });
                }
                if(closestPoints && closestPoints.length) {
                    var tmpPoint;
                    var closestVPoints = closestPoints.filter(function(point) {
                        return point.xa.showspikes;
                    });
                    if(closestVPoints.length) {
                        var closestVPt = closestVPoints[0];
                        if(isNumeric(closestVPt.x0) && isNumeric(closestVPt.y0)) {
                            tmpPoint = fillSpikePoint(closestVPt);
                            if(!spikePoints.vLinePoint || (spikePoints.vLinePoint.spikeDistance > tmpPoint.spikeDistance)) {
                                spikePoints.vLinePoint = tmpPoint;
                            }
                        }
                    }

                    var closestHPoints = closestPoints.filter(function(point) {
                        return point.ya.showspikes;
                    });
                    if(closestHPoints.length) {
                        var closestHPt = closestHPoints[0];
                        if(isNumeric(closestHPt.x0) && isNumeric(closestHPt.y0)) {
                            tmpPoint = fillSpikePoint(closestHPt);
                            if(!spikePoints.hLinePoint || (spikePoints.hLinePoint.spikeDistance > tmpPoint.spikeDistance)) {
                                spikePoints.hLinePoint = tmpPoint;
                            }
                        }
                    }
                }
            }
        }
    }

    function selectClosestPoint(pointsData, spikedistance) {
        var resultPoint = null;
        var minDistance = Infinity;
        var thisSpikeDistance;
        for(var i = 0; i < pointsData.length; i++) {
            thisSpikeDistance = pointsData[i].spikeDistance;
            if(thisSpikeDistance < minDistance && thisSpikeDistance <= spikedistance) {
                resultPoint = pointsData[i];
                minDistance = thisSpikeDistance;
            }
        }
        return resultPoint;
    }

    function fillSpikePoint(point) {
        if(!point) return null;
        return {
            xa: point.xa,
            ya: point.ya,
            x: point.xSpike !== undefined ? point.xSpike : (point.x0 + point.x1) / 2,
            y: point.ySpike !== undefined ? point.ySpike : (point.y0 + point.y1) / 2,
            distance: point.distance,
            spikeDistance: point.spikeDistance,
            curveNumber: point.trace.index,
            color: point.color,
            pointNumber: point.index
        };
    }

    var spikelineOpts = {
        fullLayout: fullLayout,
        container: fullLayout._hoverlayer,
        outerContainer: fullLayout._paperdiv,
        event: evt
    };
    var oldspikepoints = gd._spikepoints;
    var newspikepoints = {
        vLinePoint: spikePoints.vLinePoint,
        hLinePoint: spikePoints.hLinePoint
    };
    gd._spikepoints = newspikepoints;

    // Now if it is not restricted by spikedistance option, set the points to draw the spikelines
    if(hasCartesian && (spikedistance !== 0)) {
        if(hoverData.length !== 0) {
            var tmpHPointData = hoverData.filter(function(point) {
                return point.ya.showspikes;
            });
            var tmpHPoint = selectClosestPoint(tmpHPointData, spikedistance);
            spikePoints.hLinePoint = fillSpikePoint(tmpHPoint);

            var tmpVPointData = hoverData.filter(function(point) {
                return point.xa.showspikes;
            });
            var tmpVPoint = selectClosestPoint(tmpVPointData, spikedistance);
            spikePoints.vLinePoint = fillSpikePoint(tmpVPoint);
        }
    }

    // if hoverData is empty check for the spikes to draw and quit if there are none
    if(hoverData.length === 0) {
        var result = dragElement.unhoverRaw(gd, evt);
        if(hasCartesian && ((spikePoints.hLinePoint !== null) || (spikePoints.vLinePoint !== null))) {
            if(spikesChanged(oldspikepoints)) {
                createSpikelines(spikePoints, spikelineOpts);
            }
        }
        return result;
    }

    if(hasCartesian) {
        if(spikesChanged(oldspikepoints)) {
            createSpikelines(spikePoints, spikelineOpts);
        }
    }

    hoverData.sort(function(d1, d2) { return d1.distance - d2.distance; });

    // lastly, emit custom hover/unhover events
    var oldhoverdata = gd._hoverdata;
    var newhoverdata = [];

    // pull out just the data that's useful to
    // other people and send it to the event
    for(itemnum = 0; itemnum < hoverData.length; itemnum++) {
        var pt = hoverData[itemnum];
        var eventData = helpers.makeEventData(pt, pt.trace, pt.cd);

        var ht = false;
        if(pt.cd[pt.index] && pt.cd[pt.index].ht) ht = pt.cd[pt.index].ht;
        hoverData[itemnum].hovertemplate = ht || pt.trace.hovertemplate || false;
        hoverData[itemnum].eventData = [eventData];

        newhoverdata.push(eventData);
    }

    gd._hoverdata = newhoverdata;

    var rotateLabels = (
        (hovermode === 'y' && (searchData.length > 1 || hoverData.length > 1)) ||
        (hovermode === 'closest' && hasOneHorizontalTrace && hoverData.length > 1)
    );

    var bgColor = Color.combine(
        fullLayout.plot_bgcolor || Color.background,
        fullLayout.paper_bgcolor
    );

    var labelOpts = {
        hovermode: hovermode,
        rotateLabels: rotateLabels,
        bgColor: bgColor,
        container: fullLayout._hoverlayer,
        outerContainer: fullLayout._paperdiv,
        commonLabelOpts: fullLayout.hoverlabel,
        hoverdistance: fullLayout.hoverdistance
    };

    var hoverLabels = createHoverText(hoverData, labelOpts, gd);

    hoverAvoidOverlaps(hoverLabels, rotateLabels ? 'xa' : 'ya', fullLayout);

    alignHoverText(hoverLabels, rotateLabels);

    // TODO: tagName hack is needed to appease geo.js's hack of using evt.target=true
    // we should improve the "fx" API so other plots can use it without these hack.
    if(evt.target && evt.target.tagName) {
        var hasClickToShow = Registry.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata);
        overrideCursor(d3.select(evt.target), hasClickToShow ? 'pointer' : '');
    }

    // don't emit events if called manually
    if(!evt.target || noHoverEvent || !hoverChanged(gd, evt, oldhoverdata)) return;

    if(oldhoverdata) {
        gd.emit('plotly_unhover', {
            event: evt,
            points: oldhoverdata
        });
    }

    gd.emit('plotly_hover', {
        event: evt,
        points: gd._hoverdata,
        xaxes: xaArray,
        yaxes: yaArray,
        xvals: xvalArray,
        yvals: yvalArray
    });
}

var EXTRA_STRING_REGEX = /<extra>([\s\S]*)<\/extra>/;

function createHoverText(hoverData, opts, gd) {
    var fullLayout = gd._fullLayout;
    var hovermode = opts.hovermode;
    var rotateLabels = opts.rotateLabels;
    var bgColor = opts.bgColor;
    var container = opts.container;
    var outerContainer = opts.outerContainer;
    var commonLabelOpts = opts.commonLabelOpts || {};

    // opts.fontFamily/Size are used for the common label
    // and as defaults for each hover label, though the individual labels
    // can override this.
    var fontFamily = opts.fontFamily || constants.HOVERFONT;
    var fontSize = opts.fontSize || constants.HOVERFONTSIZE;

    var c0 = hoverData[0];
    var xa = c0.xa;
    var ya = c0.ya;
    var commonAttr = hovermode === 'y' ? 'yLabel' : 'xLabel';
    var t0 = c0[commonAttr];
    var t00 = (String(t0) || '').split(' ')[0];
    var outerContainerBB = outerContainer.node().getBoundingClientRect();
    var outerTop = outerContainerBB.top;
    var outerWidth = outerContainerBB.width;
    var outerHeight = outerContainerBB.height;

    // show the common label, if any, on the axis
    // never show a common label in array mode,
    // even if sometimes there could be one
    var showCommonLabel = (
        (t0 !== undefined) &&
        (c0.distance <= opts.hoverdistance) &&
        (hovermode === 'x' || hovermode === 'y')
    );

    // all hover traces hoverinfo must contain the hovermode
    // to have common labels
    if(showCommonLabel) {
        var allHaveZ = true;
        var i, traceHoverinfo;
        for(i = 0; i < hoverData.length; i++) {
            if(allHaveZ && hoverData[i].zLabel === undefined) allHaveZ = false;

            traceHoverinfo = hoverData[i].hoverinfo || hoverData[i].trace.hoverinfo;
            if(traceHoverinfo) {
                var parts = Array.isArray(traceHoverinfo) ? traceHoverinfo : traceHoverinfo.split('+');
                if(parts.indexOf('all') === -1 &&
                    parts.indexOf(hovermode) === -1) {
                    showCommonLabel = false;
                    break;
                }
            }
        }

        // xyz labels put all info in their main label, so have no need of a common label
        if(allHaveZ) showCommonLabel = false;
    }

    var commonLabel = container.selectAll('g.axistext')
        .data(showCommonLabel ? [0] : []);
    commonLabel.enter().append('g')
        .classed('axistext', true);
    commonLabel.exit().remove();

    commonLabel.each(function() {
        var label = d3.select(this);
        var lpath = Lib.ensureSingle(label, 'path', '', function(s) {
            s.style({'stroke-width': '1px'});
        });
        var ltext = Lib.ensureSingle(label, 'text', '', function(s) {
            // prohibit tex interpretation until we can handle
            // tex and regular text together
            s.attr('data-notex', 1);
        });

        var commonBgColor = commonLabelOpts.bgcolor || Color.defaultLine;
        var commonStroke = commonLabelOpts.bordercolor || Color.contrast(commonBgColor);
        var contrastColor = Color.contrast(commonBgColor);

        lpath.style({
            fill: commonBgColor,
            stroke: commonStroke
        });

        ltext.text(t0)
            .call(Drawing.font,
                commonLabelOpts.font.family || fontFamily,
                commonLabelOpts.font.size || fontSize,
                commonLabelOpts.font.color || contrastColor
             )
            .call(svgTextUtils.positionText, 0, 0)
            .call(svgTextUtils.convertToTspans, gd);

        label.attr('transform', '');

        var tbb = ltext.node().getBoundingClientRect();
        if(hovermode === 'x') {
            ltext.attr('text-anchor', 'middle')
                .call(svgTextUtils.positionText, 0, (xa.side === 'top' ?
                    (outerTop - tbb.bottom - HOVERARROWSIZE - HOVERTEXTPAD) :
                    (outerTop - tbb.top + HOVERARROWSIZE + HOVERTEXTPAD)));

            var topsign = xa.side === 'top' ? '-' : '';
            lpath.attr('d', 'M0,0' +
                'L' + HOVERARROWSIZE + ',' + topsign + HOVERARROWSIZE +
                'H' + (HOVERTEXTPAD + tbb.width / 2) +
                'v' + topsign + (HOVERTEXTPAD * 2 + tbb.height) +
                'H-' + (HOVERTEXTPAD + tbb.width / 2) +
                'V' + topsign + HOVERARROWSIZE + 'H-' + HOVERARROWSIZE + 'Z');

            label.attr('transform', 'translate(' +
                (xa._offset + (c0.x0 + c0.x1) / 2) + ',' +
                (ya._offset + (xa.side === 'top' ? 0 : ya._length)) + ')');
        }
        else {
            ltext.attr('text-anchor', ya.side === 'right' ? 'start' : 'end')
                .call(svgTextUtils.positionText,
                    (ya.side === 'right' ? 1 : -1) * (HOVERTEXTPAD + HOVERARROWSIZE),
                    outerTop - tbb.top - tbb.height / 2);

            var leftsign = ya.side === 'right' ? '' : '-';
            lpath.attr('d', 'M0,0' +
                'L' + leftsign + HOVERARROWSIZE + ',' + HOVERARROWSIZE +
                'V' + (HOVERTEXTPAD + tbb.height / 2) +
                'h' + leftsign + (HOVERTEXTPAD * 2 + tbb.width) +
                'V-' + (HOVERTEXTPAD + tbb.height / 2) +
                'H' + leftsign + HOVERARROWSIZE + 'V-' + HOVERARROWSIZE + 'Z');

            label.attr('transform', 'translate(' +
                (xa._offset + (ya.side === 'right' ? xa._length : 0)) + ',' +
                (ya._offset + (c0.y0 + c0.y1) / 2) + ')');
        }
        // remove the "close but not quite" points
        // because of error bars, only take up to a space
        hoverData = hoverData.filter(function(d) {
            return (d.zLabelVal !== undefined) ||
                (d[commonAttr] || '').split(' ')[0] === t00;
        });
    });

    // show all the individual labels


    // first create the objects
    var hoverLabels = container.selectAll('g.hovertext')
        .data(hoverData, function(d) {
            return [d.trace.index, d.index, d.x0, d.y0, d.name, d.attr, d.xa, d.ya || ''].join(',');
        });
    hoverLabels.enter().append('g')
        .classed('hovertext', true)
        .each(function() {
            var g = d3.select(this);
            // trace name label (rect and text.name)
            g.append('rect')
                .call(Color.fill, Color.addOpacity(bgColor, 0.8));
            g.append('text').classed('name', true);
            // trace data label (path and text.nums)
            g.append('path')
                .style('stroke-width', '1px');
            g.append('text').classed('nums', true)
                .call(Drawing.font, fontFamily, fontSize);
        });
    hoverLabels.exit().remove();

    // then put the text in, position the pointer to the data,
    // and figure out sizes
    hoverLabels.each(function(d) {
        var g = d3.select(this).attr('transform', '');
        var name = '';
        var text = '';

        // combine possible non-opaque trace color with bgColor
        var color0 = d.bgcolor || d.color;
        // color for 'nums' part of the label
        var numsColor = Color.combine(
            Color.opacity(color0) ? color0 : Color.defaultLine,
            bgColor
        );
        // color for 'name' part of the label
        var nameColor = Color.combine(
            Color.opacity(d.color) ? d.color : Color.defaultLine,
            bgColor
        );
        // find a contrasting color for border and text
        var contrastColor = d.borderColor || Color.contrast(numsColor);

        // to get custom 'name' labels pass cleanPoint
        if(d.nameOverride !== undefined) d.name = d.nameOverride;

        if(d.name) {
            if(fullLayout.meta) {
                d.name = Lib.templateString(d.name, {meta: fullLayout.meta});
            }

            name = svgTextUtils.plainText(d.name || '', {
                len: d.nameLength,
                allowedTags: ['br', 'sub', 'sup', 'b', 'i', 'em']
            });
        }

        if(d.zLabel !== undefined) {
            if(d.xLabel !== undefined) text += 'x: ' + d.xLabel + '<br>';
            if(d.yLabel !== undefined) text += 'y: ' + d.yLabel + '<br>';
            text += (text ? 'z: ' : '') + d.zLabel;
        }
        else if(showCommonLabel && d[hovermode + 'Label'] === t0) {
            text = d[(hovermode === 'x' ? 'y' : 'x') + 'Label'] || '';
        }
        else if(d.xLabel === undefined) {
            if(d.yLabel !== undefined && d.trace.type !== 'scattercarpet') text = d.yLabel;
        }
        else if(d.yLabel === undefined) text = d.xLabel;
        else text = '(' + d.xLabel + ', ' + d.yLabel + ')';

        if((d.text || d.text === 0) && !Array.isArray(d.text)) {
            text += (text ? '<br>' : '') + d.text;
        }

        // used by other modules (initially just ternary) that
        // manage their own hoverinfo independent of cleanPoint
        // the rest of this will still apply, so such modules
        // can still put things in (x|y|z)Label, text, and name
        // and hoverinfo will still determine their visibility
        if(d.extraText !== undefined) text += (text ? '<br>' : '') + d.extraText;

        // if 'text' is empty at this point,
        // and hovertemplate is not defined,
        // put 'name' in main label and don't show secondary label
        if(text === '' && !d.hovertemplate) {
            // if 'name' is also empty, remove entire label
            if(name === '') g.remove();
            text = name;
        }

        // hovertemplate
        var d3locale = gd._fullLayout._d3locale;
        var hovertemplate = d.hovertemplate || false;
        var hovertemplateLabels = d.hovertemplateLabels || d;
        var eventData = d.eventData[0] || {};
        if(hovertemplate) {
            text = Lib.hovertemplateString(
                hovertemplate,
                hovertemplateLabels,
                d3locale,
                eventData,
                {meta: fullLayout.meta}
            );

            text = text.replace(EXTRA_STRING_REGEX, function(match, extra) {
                name = extra; // Assign name for secondary text label
                return ''; // Remove from main text label
            });
        }

        // main label
        var tx = g.select('text.nums')
            .call(Drawing.font,
                d.fontFamily || fontFamily,
                d.fontSize || fontSize,
                d.fontColor || contrastColor)
            .text(text)
            .attr('data-notex', 1)
            .call(svgTextUtils.positionText, 0, 0)
            .call(svgTextUtils.convertToTspans, gd);

        var tx2 = g.select('text.name');
        var tx2width = 0;
        var tx2height = 0;

        // secondary label for non-empty 'name'
        if(name && name !== text) {
            tx2.call(Drawing.font,
                    d.fontFamily || fontFamily,
                    d.fontSize || fontSize,
                    nameColor)
                .text(name)
                .attr('data-notex', 1)
                .call(svgTextUtils.positionText, 0, 0)
                .call(svgTextUtils.convertToTspans, gd);

            var t2bb = tx2.node().getBoundingClientRect();
            tx2width = t2bb.width + 2 * HOVERTEXTPAD;
            tx2height = t2bb.height + 2 * HOVERTEXTPAD;
        } else {
            tx2.remove();
            g.select('rect').remove();
        }

        g.select('path').style({
            fill: numsColor,
            stroke: contrastColor
        });

        var tbb = tx.node().getBoundingClientRect();
        var htx = d.xa._offset + (d.x0 + d.x1) / 2;
        var hty = d.ya._offset + (d.y0 + d.y1) / 2;
        var dx = Math.abs(d.x1 - d.x0);
        var dy = Math.abs(d.y1 - d.y0);
        var txTotalWidth = tbb.width + HOVERARROWSIZE + HOVERTEXTPAD + tx2width;
        var anchorStartOK, anchorEndOK;

        d.ty0 = outerTop - tbb.top;
        d.bx = tbb.width + 2 * HOVERTEXTPAD;
        d.by = Math.max(tbb.height + 2 * HOVERTEXTPAD, tx2height);
        d.anchor = 'start';
        d.txwidth = tbb.width;
        d.tx2width = tx2width;
        d.offset = 0;

        if(rotateLabels) {
            d.pos = htx;
            anchorStartOK = hty + dy / 2 + txTotalWidth <= outerHeight;
            anchorEndOK = hty - dy / 2 - txTotalWidth >= 0;
            if((d.idealAlign === 'top' || !anchorStartOK) && anchorEndOK) {
                hty -= dy / 2;
                d.anchor = 'end';
            } else if(anchorStartOK) {
                hty += dy / 2;
                d.anchor = 'start';
            } else d.anchor = 'middle';
        }
        else {
            d.pos = hty;
            anchorStartOK = htx + dx / 2 + txTotalWidth <= outerWidth;
            anchorEndOK = htx - dx / 2 - txTotalWidth >= 0;
            if((d.idealAlign === 'left' || !anchorStartOK) && anchorEndOK) {
                htx -= dx / 2;
                d.anchor = 'end';
            } else if(anchorStartOK) {
                htx += dx / 2;
                d.anchor = 'start';
            } else d.anchor = 'middle';
        }

        tx.attr('text-anchor', d.anchor);
        if(tx2width) tx2.attr('text-anchor', d.anchor);
        g.attr('transform', 'translate(' + htx + ',' + hty + ')' +
            (rotateLabels ? 'rotate(' + YANGLE + ')' : ''));
    });

    return hoverLabels;
}

// Make groups of touching points, and within each group
// move each point so that no labels overlap, but the average
// label position is the same as it was before moving. Indicentally,
// this is equivalent to saying all the labels are on equal linear
// springs about their initial position. Initially, each point is
// its own group, but as we find overlaps we will clump the points.
//
// Also, there are hard constraints at the edges of the graphs,
// that push all groups to the middle so they are visible. I don't
// know what happens if the group spans all the way from one edge to
// the other, though it hardly matters - there's just too much
// information then.
function hoverAvoidOverlaps(hoverLabels, ax, fullLayout) {
    var nummoves = 0;
    var axSign = 1;
    var nLabels = hoverLabels.size();

    // make groups of touching points
    var pointgroups = new Array(nLabels);

    hoverLabels.each(function(d, i) {
        var axis = d[ax];
        var axIsX = axis._id.charAt(0) === 'x';
        var rng = axis.range;
        if(!i && rng && ((rng[0] > rng[1]) !== axIsX)) axSign = -1;
        pointgroups[i] = [{
            datum: d,
            i: i,
            traceIndex: d.trace.index,
            dp: 0,
            pos: d.pos,
            posref: d.posref,
            size: d.by * (axIsX ? YFACTOR : 1) / 2,
            pmin: 0,
            pmax: (axIsX ? fullLayout.width : fullLayout.height)
        }];
    });

    pointgroups.sort(function(a, b) {
        return (a[0].posref - b[0].posref) ||
            // for equal positions, sort trace indices increasing or decreasing
            // depending on whether the axis is reversed or not... so stacked
            // traces will generally keep their order even if one trace adds
            // nothing to the stack.
            (axSign * (b[0].traceIndex - a[0].traceIndex));
    });

    var donepositioning, topOverlap, bottomOverlap, i, j, pti, sumdp;

    function constrainGroup(grp) {
        var minPt = grp[0];
        var maxPt = grp[grp.length - 1];

        // overlap with the top - positive vals are overlaps
        topOverlap = minPt.pmin - minPt.pos - minPt.dp + minPt.size;

        // overlap with the bottom - positive vals are overlaps
        bottomOverlap = maxPt.pos + maxPt.dp + maxPt.size - minPt.pmax;

        // check for min overlap first, so that we always
        // see the largest labels
        // allow for .01px overlap, so we don't get an
        // infinite loop from rounding errors
        if(topOverlap > 0.01) {
            for(j = grp.length - 1; j >= 0; j--) grp[j].dp += topOverlap;
            donepositioning = false;
        }
        if(bottomOverlap < 0.01) return;
        if(topOverlap < -0.01) {
            // make sure we're not pushing back and forth
            for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap;
            donepositioning = false;
        }
        if(!donepositioning) return;

        // no room to fix positioning, delete off-screen points

        // first see how many points we need to delete
        var deleteCount = 0;
        for(i = 0; i < grp.length; i++) {
            pti = grp[i];
            if(pti.pos + pti.dp + pti.size > minPt.pmax) deleteCount++;
        }

        // start by deleting points whose data is off screen
        for(i = grp.length - 1; i >= 0; i--) {
            if(deleteCount <= 0) break;
            pti = grp[i];

            // pos has already been constrained to [pmin,pmax]
            // so look for points close to that to delete
            if(pti.pos > minPt.pmax - 1) {
                pti.del = true;
                deleteCount--;
            }
        }
        for(i = 0; i < grp.length; i++) {
            if(deleteCount <= 0) break;
            pti = grp[i];

            // pos has already been constrained to [pmin,pmax]
            // so look for points close to that to delete
            if(pti.pos < minPt.pmin + 1) {
                pti.del = true;
                deleteCount--;

                // shift the whole group minus into this new space
                bottomOverlap = pti.size * 2;
                for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap;
            }
        }
        // then delete points that go off the bottom
        for(i = grp.length - 1; i >= 0; i--) {
            if(deleteCount <= 0) break;
            pti = grp[i];
            if(pti.pos + pti.dp + pti.size > minPt.pmax) {
                pti.del = true;
                deleteCount--;
            }
        }
    }

    // loop through groups, combining them if they overlap,
    // until nothing moves
    while(!donepositioning && nummoves <= nLabels) {
        // to avoid infinite loops, don't move more times
        // than there are traces
        nummoves++;

        // assume nothing will move in this iteration,
        // reverse this if it does
        donepositioning = true;
        i = 0;
        while(i < pointgroups.length - 1) {
                // the higher (g0) and lower (g1) point group
            var g0 = pointgroups[i];
            var g1 = pointgroups[i + 1];

            // the lowest point in the higher group (p0)
            // the highest point in the lower group (p1)
            var p0 = g0[g0.length - 1];
            var p1 = g1[0];
            topOverlap = p0.pos + p0.dp + p0.size - p1.pos - p1.dp + p1.size;

            // Only group points that lie on the same axes
            if(topOverlap > 0.01 && (p0.pmin === p1.pmin) && (p0.pmax === p1.pmax)) {
                // push the new point(s) added to this group out of the way
                for(j = g1.length - 1; j >= 0; j--) g1[j].dp += topOverlap;

                // add them to the group
                g0.push.apply(g0, g1);
                pointgroups.splice(i + 1, 1);

                // adjust for minimum average movement
                sumdp = 0;
                for(j = g0.length - 1; j >= 0; j--) sumdp += g0[j].dp;
                bottomOverlap = sumdp / g0.length;
                for(j = g0.length - 1; j >= 0; j--) g0[j].dp -= bottomOverlap;
                donepositioning = false;
            }
            else i++;
        }

        // check if we're going off the plot on either side and fix
        pointgroups.forEach(constrainGroup);
    }

    // now put these offsets into hoverData
    for(i = pointgroups.length - 1; i >= 0; i--) {
        var grp = pointgroups[i];
        for(j = grp.length - 1; j >= 0; j--) {
            var pt = grp[j];
            var hoverPt = pt.datum;
            hoverPt.offset = pt.dp;
            hoverPt.del = pt.del;
        }
    }
}

function alignHoverText(hoverLabels, rotateLabels) {
    // finally set the text positioning relative to the data and draw the
    // box around it
    hoverLabels.each(function(d) {
        var g = d3.select(this);
        if(d.del) {
            g.remove();
            return;
        }

        var horzSign = d.anchor === 'end' ? -1 : 1;
        var tx = g.select('text.nums');
        var alignShift = {start: 1, end: -1, middle: 0}[d.anchor];
        var txx = alignShift * (HOVERARROWSIZE + HOVERTEXTPAD);
        var tx2x = txx + alignShift * (d.txwidth + HOVERTEXTPAD);
        var offsetX = 0;
        var offsetY = d.offset;

        if(d.anchor === 'middle') {
            txx -= d.tx2width / 2;
            tx2x += d.txwidth / 2 + HOVERTEXTPAD;
        }
        if(rotateLabels) {
            offsetY *= -YSHIFTY;
            offsetX = d.offset * YSHIFTX;
        }

        g.select('path').attr('d', d.anchor === 'middle' ?
            // middle aligned: rect centered on data
            ('M-' + (d.bx / 2 + d.tx2width / 2) + ',' + (offsetY - d.by / 2) +
              'h' + d.bx + 'v' + d.by + 'h-' + d.bx + 'Z') :
            // left or right aligned: side rect with arrow to data
            ('M0,0L' + (horzSign * HOVERARROWSIZE + offsetX) + ',' + (HOVERARROWSIZE + offsetY) +
                'v' + (d.by / 2 - HOVERARROWSIZE) +
                'h' + (horzSign * d.bx) +
                'v-' + d.by +
                'H' + (horzSign * HOVERARROWSIZE + offsetX) +
                'V' + (offsetY - HOVERARROWSIZE) +
                'Z'));

        tx.call(svgTextUtils.positionText,
            txx + offsetX, offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD);

        if(d.tx2width) {
            g.select('text.name')
                .call(svgTextUtils.positionText,
                    tx2x + alignShift * HOVERTEXTPAD + offsetX,
                    offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD);
            g.select('rect')
                .call(Drawing.setRect,
                    tx2x + (alignShift - 1) * d.tx2width / 2 + offsetX,
                    offsetY - d.by / 2 - 1,
                    d.tx2width, d.by + 2);
        }
    });
}

function cleanPoint(d, hovermode) {
    var index = d.index;
    var trace = d.trace || {};
    var cd0 = d.cd[0];
    var cd = d.cd[index] || {};

    var getVal = Array.isArray(index) ?
        function(calcKey, traceKey) {
            return Lib.castOption(cd0, index, calcKey) ||
                Lib.extractOption({}, trace, '', traceKey);
        } :
        function(calcKey, traceKey) {
            return Lib.extractOption(cd, trace, calcKey, traceKey);
        };

    function fill(key, calcKey, traceKey) {
        var val = getVal(calcKey, traceKey);
        if(val) d[key] = val;
    }

    fill('hoverinfo', 'hi', 'hoverinfo');
    fill('bgcolor', 'hbg', 'hoverlabel.bgcolor');
    fill('borderColor', 'hbc', 'hoverlabel.bordercolor');
    fill('fontFamily', 'htf', 'hoverlabel.font.family');
    fill('fontSize', 'hts', 'hoverlabel.font.size');
    fill('fontColor', 'htc', 'hoverlabel.font.color');
    fill('nameLength', 'hnl', 'hoverlabel.namelength');

    d.posref = (hovermode === 'y' || (hovermode === 'closest' && trace.orientation === 'h')) ?
        (d.xa._offset + (d.x0 + d.x1) / 2) :
        (d.ya._offset + (d.y0 + d.y1) / 2);

    // then constrain all the positions to be on the plot
    d.x0 = Lib.constrain(d.x0, 0, d.xa._length);
    d.x1 = Lib.constrain(d.x1, 0, d.xa._length);
    d.y0 = Lib.constrain(d.y0, 0, d.ya._length);
    d.y1 = Lib.constrain(d.y1, 0, d.ya._length);

    // and convert the x and y label values into formatted text
    if(d.xLabelVal !== undefined) {
        d.xLabel = ('xLabel' in d) ? d.xLabel : Axes.hoverLabelText(d.xa, d.xLabelVal);
        d.xVal = d.xa.c2d(d.xLabelVal);
    }
    if(d.yLabelVal !== undefined) {
        d.yLabel = ('yLabel' in d) ? d.yLabel : Axes.hoverLabelText(d.ya, d.yLabelVal);
        d.yVal = d.ya.c2d(d.yLabelVal);
    }

    // Traces like heatmaps generate the zLabel in their hoverPoints function
    if(d.zLabelVal !== undefined && d.zLabel === undefined) {
        d.zLabel = String(d.zLabelVal);
    }

    // for box means and error bars, add the range to the label
    if(!isNaN(d.xerr) && !(d.xa.type === 'log' && d.xerr <= 0)) {
        var xeText = Axes.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text;
        if(d.xerrneg !== undefined) {
            d.xLabel += ' +' + xeText + ' / -' +
                Axes.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text;
        }
        else d.xLabel += ' ± ' + xeText;

        // small distance penalty for error bars, so that if there are
        // traces with errors and some without, the error bar label will
        // hoist up to the point
        if(hovermode === 'x') d.distance += 1;
    }
    if(!isNaN(d.yerr) && !(d.ya.type === 'log' && d.yerr <= 0)) {
        var yeText = Axes.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text;
        if(d.yerrneg !== undefined) {
            d.yLabel += ' +' + yeText + ' / -' +
                Axes.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text;
        }
        else d.yLabel += ' ± ' + yeText;

        if(hovermode === 'y') d.distance += 1;
    }

    var infomode = d.hoverinfo || d.trace.hoverinfo;

    if(infomode && infomode !== 'all') {
        infomode = Array.isArray(infomode) ? infomode : infomode.split('+');
        if(infomode.indexOf('x') === -1) d.xLabel = undefined;
        if(infomode.indexOf('y') === -1) d.yLabel = undefined;
        if(infomode.indexOf('z') === -1) d.zLabel = undefined;
        if(infomode.indexOf('text') === -1) d.text = undefined;
        if(infomode.indexOf('name') === -1) d.name = undefined;
    }

    return d;
}

function createSpikelines(closestPoints, opts) {
    var container = opts.container;
    var fullLayout = opts.fullLayout;
    var evt = opts.event;
    var showY = !!closestPoints.hLinePoint;
    var showX = !!closestPoints.vLinePoint;

    var xa, ya;

    // Remove old spikeline items
    container.selectAll('.spikeline').remove();

    if(!(showX || showY)) return;

    var contrastColor = Color.combine(fullLayout.plot_bgcolor, fullLayout.paper_bgcolor);

    // Horizontal line (to y-axis)
    if(showY) {
        var hLinePoint = closestPoints.hLinePoint;
        var hLinePointX, hLinePointY;

        xa = hLinePoint && hLinePoint.xa;
        ya = hLinePoint && hLinePoint.ya;
        var ySnap = ya.spikesnap;

        if(ySnap === 'cursor') {
            hLinePointX = evt.pointerX;
            hLinePointY = evt.pointerY;
        } else {
            hLinePointX = xa._offset + hLinePoint.x;
            hLinePointY = ya._offset + hLinePoint.y;
        }
        var dfltHLineColor = tinycolor.readability(hLinePoint.color, contrastColor) < 1.5 ?
            Color.contrast(contrastColor) : hLinePoint.color;
        var yMode = ya.spikemode;
        var yThickness = ya.spikethickness;
        var yColor = ya.spikecolor || dfltHLineColor;
        var yBB = ya._boundingBox;
        var xEdge = ((yBB.left + yBB.right) / 2) < hLinePointX ? yBB.right : yBB.left;
        var xBase, xEndSpike;

        if(yMode.indexOf('toaxis') !== -1 || yMode.indexOf('across') !== -1) {
            if(yMode.indexOf('toaxis') !== -1) {
                xBase = xEdge;
                xEndSpike = hLinePointX;
            }
            if(yMode.indexOf('across') !== -1) {
                xBase = ya._counterSpan[0];
                xEndSpike = ya._counterSpan[1];
            }

            // Foreground horizontal line (to y-axis)
            container.insert('line', ':first-child')
                .attr({
                    x1: xBase,
                    x2: xEndSpike,
                    y1: hLinePointY,
                    y2: hLinePointY,
                    'stroke-width': yThickness,
                    stroke: yColor,
                    'stroke-dasharray': Drawing.dashStyle(ya.spikedash, yThickness)
                })
                .classed('spikeline', true)
                .classed('crisp', true);

            // Background horizontal Line (to y-axis)
            container.insert('line', ':first-child')
                .attr({
                    x1: xBase,
                    x2: xEndSpike,
                    y1: hLinePointY,
                    y2: hLinePointY,
                    'stroke-width': yThickness + 2,
                    stroke: contrastColor
                })
                .classed('spikeline', true)
                .classed('crisp', true);
        }
        // Y axis marker
        if(yMode.indexOf('marker') !== -1) {
            container.insert('circle', ':first-child')
                .attr({
                    cx: xEdge + (ya.side !== 'right' ? yThickness : -yThickness),
                    cy: hLinePointY,
                    r: yThickness,
                    fill: yColor
                })
                .classed('spikeline', true);
        }
    }

    if(showX) {
        var vLinePoint = closestPoints.vLinePoint;
        var vLinePointX, vLinePointY;

        xa = vLinePoint && vLinePoint.xa;
        ya = vLinePoint && vLinePoint.ya;
        var xSnap = xa.spikesnap;

        if(xSnap === 'cursor') {
            vLinePointX = evt.pointerX;
            vLinePointY = evt.pointerY;
        } else {
            vLinePointX = xa._offset + vLinePoint.x;
            vLinePointY = ya._offset + vLinePoint.y;
        }
        var dfltVLineColor = tinycolor.readability(vLinePoint.color, contrastColor) < 1.5 ?
            Color.contrast(contrastColor) : vLinePoint.color;
        var xMode = xa.spikemode;
        var xThickness = xa.spikethickness;
        var xColor = xa.spikecolor || dfltVLineColor;
        var xBB = xa._boundingBox;
        var yEdge = ((xBB.top + xBB.bottom) / 2) < vLinePointY ? xBB.bottom : xBB.top;
        var yBase, yEndSpike;

        if(xMode.indexOf('toaxis') !== -1 || xMode.indexOf('across') !== -1) {
            if(xMode.indexOf('toaxis') !== -1) {
                yBase = yEdge;
                yEndSpike = vLinePointY;
            }
            if(xMode.indexOf('across') !== -1) {
                yBase = xa._counterSpan[0];
                yEndSpike = xa._counterSpan[1];
            }

            // Foreground vertical line (to x-axis)
            container.insert('line', ':first-child')
                .attr({
                    x1: vLinePointX,
                    x2: vLinePointX,
                    y1: yBase,
                    y2: yEndSpike,
                    'stroke-width': xThickness,
                    stroke: xColor,
                    'stroke-dasharray': Drawing.dashStyle(xa.spikedash, xThickness)
                })
                .classed('spikeline', true)
                .classed('crisp', true);

            // Background vertical line (to x-axis)
            container.insert('line', ':first-child')
                .attr({
                    x1: vLinePointX,
                    x2: vLinePointX,
                    y1: yBase,
                    y2: yEndSpike,
                    'stroke-width': xThickness + 2,
                    stroke: contrastColor
                })
                .classed('spikeline', true)
                .classed('crisp', true);
        }

        // X axis marker
        if(xMode.indexOf('marker') !== -1) {
            container.insert('circle', ':first-child')
                .attr({
                    cx: vLinePointX,
                    cy: yEdge - (xa.side !== 'top' ? xThickness : -xThickness),
                    r: xThickness,
                    fill: xColor
                })
                .classed('spikeline', true);
        }
    }
}

function hoverChanged(gd, evt, oldhoverdata) {
    // don't emit any events if nothing changed
    if(!oldhoverdata || oldhoverdata.length !== gd._hoverdata.length) return true;

    for(var i = oldhoverdata.length - 1; i >= 0; i--) {
        var oldPt = oldhoverdata[i];
        var newPt = gd._hoverdata[i];

        if(oldPt.curveNumber !== newPt.curveNumber ||
            String(oldPt.pointNumber) !== String(newPt.pointNumber) ||
            String(oldPt.pointNumbers) !== String(newPt.pointNumbers)
        ) {
            return true;
        }
    }
    return false;
}

function spikesChanged(gd, oldspikepoints) {
    // don't relayout the plot because of new spikelines if spikelines points didn't change
    if(!oldspikepoints) return true;
    if(oldspikepoints.vLinePoint !== gd._spikepoints.vLinePoint ||
        oldspikepoints.hLinePoint !== gd._spikepoints.hLinePoint
    ) return true;
    return false;
}

},{"../../lib":697,"../../lib/events":686,"../../lib/override_cursor":708,"../../lib/svg_text_utils":721,"../../plots/cartesian/axes":745,"../../registry":826,"../color":574,"../dragelement":592,"../drawing":595,"./constants":607,"./helpers":609,"d3":151,"fast-isnumeric":218,"tinycolor2":518}],611:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

module.exports = function handleHoverLabelDefaults(contIn, contOut, coerce, opts) {
    opts = opts || {};

    coerce('hoverlabel.bgcolor', opts.bgcolor);
    coerce('hoverlabel.bordercolor', opts.bordercolor);
    coerce('hoverlabel.namelength', opts.namelength);
    Lib.coerceFont(coerce, 'hoverlabel.font', opts.font);
};

},{"../../lib":697}],612:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function(opts, extra) {
    opts = opts || {};
    extra = extra || {};

    var descPart = extra.description ? ' ' + extra.description : '';
    var keys = extra.keys || [];
    if(keys.length > 0) {
        var quotedKeys = [];
        for(var i = 0; i < keys.length; i++) {
            quotedKeys[i] = '`' + keys[i] + '`';
        }
        descPart = descPart + 'Finally, the template string has access to ';
        if(keys.length === 1) {
            descPart = 'variable ' + quotedKeys[0];
        } else {
            descPart = 'variables ' + quotedKeys.slice(0, -1).join(', ') + ' and ' + quotedKeys.slice(-1) + '.';
        }
    }

    var hovertemplate = {
        valType: 'string',
        
        dflt: '',
        editType: opts.editType || 'none',
        
    };

    if(opts.arrayOk !== false) {
        hovertemplate.arrayOk = true;
    }

    return hovertemplate;
};

},{}],613:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var Lib = _dereq_('../../lib');
var dragElement = _dereq_('../dragelement');
var helpers = _dereq_('./helpers');
var layoutAttributes = _dereq_('./layout_attributes');
var hoverModule = _dereq_('./hover');

module.exports = {
    moduleType: 'component',
    name: 'fx',

    constants: _dereq_('./constants'),
    schema: {
        layout: layoutAttributes
    },

    attributes: _dereq_('./attributes'),
    layoutAttributes: layoutAttributes,

    supplyLayoutGlobalDefaults: _dereq_('./layout_global_defaults'),
    supplyDefaults: _dereq_('./defaults'),
    supplyLayoutDefaults: _dereq_('./layout_defaults'),

    calc: _dereq_('./calc'),

    getDistanceFunction: helpers.getDistanceFunction,
    getClosest: helpers.getClosest,
    inbox: helpers.inbox,
    quadrature: helpers.quadrature,
    appendArrayPointValue: helpers.appendArrayPointValue,

    castHoverOption: castHoverOption,
    castHoverinfo: castHoverinfo,

    hover: hoverModule.hover,
    unhover: dragElement.unhover,

    loneHover: hoverModule.loneHover,
    multiHovers: hoverModule.multiHovers,
    loneUnhover: loneUnhover,

    click: _dereq_('./click')
};

function loneUnhover(containerOrSelection) {
    // duck type whether the arg is a d3 selection because ie9 doesn't
    // handle instanceof like modern browsers do.
    var selection = Lib.isD3Selection(containerOrSelection) ?
            containerOrSelection :
            d3.select(containerOrSelection);

    selection.selectAll('g.hovertext').remove();
    selection.selectAll('.spikeline').remove();
}

// helpers for traces that use Fx.loneHover

function castHoverOption(trace, ptNumber, attr) {
    return Lib.castOption(trace, ptNumber, 'hoverlabel.' + attr);
}

function castHoverinfo(trace, fullLayout, ptNumber) {
    function _coerce(val) {
        return Lib.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout);
    }

    return Lib.castOption(trace, ptNumber, 'hoverinfo', _coerce);
}

},{"../../lib":697,"../dragelement":592,"./attributes":604,"./calc":605,"./click":606,"./constants":607,"./defaults":608,"./helpers":609,"./hover":610,"./layout_attributes":614,"./layout_defaults":615,"./layout_global_defaults":616,"d3":151}],614:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var constants = _dereq_('./constants');

var fontAttrs = _dereq_('../../plots/font_attributes')({
    editType: 'none',
    
});
fontAttrs.family.dflt = constants.HOVERFONT;
fontAttrs.size.dflt = constants.HOVERFONTSIZE;

module.exports = {
    clickmode: {
        valType: 'flaglist',
        
        flags: ['event', 'select'],
        dflt: 'event',
        editType: 'plot',
        extras: ['none'],
        
    },
    dragmode: {
        valType: 'enumerated',
        
        values: ['zoom', 'pan', 'select', 'lasso', 'orbit', 'turntable', false],
        dflt: 'zoom',
        editType: 'modebar',
        
    },
    hovermode: {
        valType: 'enumerated',
        
        values: ['x', 'y', 'closest', false],
        editType: 'modebar',
        
    },
    hoverdistance: {
        valType: 'integer',
        min: -1,
        dflt: 20,
        
        editType: 'none',
        
    },
    spikedistance: {
        valType: 'integer',
        min: -1,
        dflt: 20,
        
        editType: 'none',
        
    },
    hoverlabel: {
        bgcolor: {
            valType: 'color',
            
            editType: 'none',
            
        },
        bordercolor: {
            valType: 'color',
            
            editType: 'none',
            
        },
        font: fontAttrs,
        namelength: {
            valType: 'integer',
            min: -1,
            dflt: 15,
            
            editType: 'none',
            
        },
        editType: 'none'
    },
    selectdirection: {
        valType: 'enumerated',
        
        values: ['h', 'v', 'd', 'any'],
        dflt: 'any',
        
        editType: 'none'
    }
};

},{"../../plots/font_attributes":771,"./constants":607}],615:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var layoutAttributes = _dereq_('./layout_attributes');

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
    function coerce(attr, dflt) {
        return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
    }

    var clickmode = coerce('clickmode');

    var dragMode = coerce('dragmode');
    if(dragMode === 'select') coerce('selectdirection');

    var hovermodeDflt;
    if(layoutOut._has('cartesian')) {
        if(clickmode.indexOf('select') > -1) {
            hovermodeDflt = 'closest';
        } else {
            // flag for 'horizontal' plots:
            // determines the state of the mode bar 'compare' hovermode button
            layoutOut._isHoriz = isHoriz(fullData, layoutOut);
            hovermodeDflt = layoutOut._isHoriz ? 'y' : 'x';
        }
    }
    else hovermodeDflt = 'closest';

    var hoverMode = coerce('hovermode', hovermodeDflt);
    if(hoverMode) {
        coerce('hoverdistance');
        coerce('spikedistance');
    }

    // if only mapbox or geo subplots is present on graph,
    // reset 'zoom' dragmode to 'pan' until 'zoom' is implemented,
    // so that the correct modebar button is active
    var hasMapbox = layoutOut._has('mapbox');
    var hasGeo = layoutOut._has('geo');
    var len = layoutOut._basePlotModules.length;

    if(layoutOut.dragmode === 'zoom' && (
        ((hasMapbox || hasGeo) && len === 1) ||
        (hasMapbox && hasGeo && len === 2)
    )) {
        layoutOut.dragmode = 'pan';
    }
};

function isHoriz(fullData, fullLayout) {
    var stackOpts = fullLayout._scatterStackOpts || {};

    for(var i = 0; i < fullData.length; i++) {
        var trace = fullData[i];
        var subplot = trace.xaxis + trace.yaxis;
        var subplotStackOpts = stackOpts[subplot] || {};
        var groupOpts = subplotStackOpts[trace.stackgroup] || {};

        if(trace.orientation !== 'h' && groupOpts.orientation !== 'h') {
            return false;
        }
    }

    return true;
}

},{"../../lib":697,"./layout_attributes":614}],616:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var handleHoverLabelDefaults = _dereq_('./hoverlabel_defaults');
var layoutAttributes = _dereq_('./layout_attributes');

module.exports = function supplyLayoutGlobalDefaults(layoutIn, layoutOut) {
    function coerce(attr, dflt) {
        return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
    }

    handleHoverLabelDefaults(layoutIn, layoutOut, coerce);
};

},{"../../lib":697,"./hoverlabel_defaults":611,"./layout_attributes":614}],617:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var counterRegex = _dereq_('../../lib/regex').counter;
var domainAttrs = _dereq_('../../plots/domain').attributes;
var cartesianIdRegex = _dereq_('../../plots/cartesian/constants').idRegex;
var Template = _dereq_('../../plot_api/plot_template');

var gridAttrs = {
    rows: {
        valType: 'integer',
        min: 1,
        
        editType: 'plot',
        
    },
    roworder: {
        valType: 'enumerated',
        values: ['top to bottom', 'bottom to top'],
        dflt: 'top to bottom',
        
        editType: 'plot',
        
    },
    columns: {
        valType: 'integer',
        min: 1,
        
        editType: 'plot',
        
    },
    subplots: {
        valType: 'info_array',
        freeLength: true,
        dimensions: 2,
        items: {valType: 'enumerated', values: [counterRegex('xy').toString(), ''], editType: 'plot'},
        
        editType: 'plot',
        
    },
    xaxes: {
        valType: 'info_array',
        freeLength: true,
        items: {valType: 'enumerated', values: [cartesianIdRegex.x.toString(), ''], editType: 'plot'},
        
        editType: 'plot',
        
    },
    yaxes: {
        valType: 'info_array',
        freeLength: true,
        items: {valType: 'enumerated', values: [cartesianIdRegex.y.toString(), ''], editType: 'plot'},
        
        editType: 'plot',
        
    },
    pattern: {
        valType: 'enumerated',
        values: ['independent', 'coupled'],
        dflt: 'coupled',
        
        editType: 'plot',
        
    },
    xgap: {
        valType: 'number',
        min: 0,
        max: 1,
        
        editType: 'plot',
        
    },
    ygap: {
        valType: 'number',
        min: 0,
        max: 1,
        
        editType: 'plot',
        
    },
    domain: domainAttrs({name: 'grid', editType: 'plot', noGridCell: true}, {
        
    }),
    xside: {
        valType: 'enumerated',
        values: ['bottom', 'bottom plot', 'top plot', 'top'],
        dflt: 'bottom plot',
        
        editType: 'plot',
        
    },
    yside: {
        valType: 'enumerated',
        values: ['left', 'left plot', 'right plot', 'right'],
        dflt: 'left plot',
        
        editType: 'plot',
        
    },
    editType: 'plot'
};

function getAxes(layout, grid, axLetter) {
    var gridVal = grid[axLetter + 'axes'];
    var splomVal = Object.keys((layout._splomAxes || {})[axLetter] || {});

    if(Array.isArray(gridVal)) return gridVal;
    if(splomVal.length) return splomVal;
}

// the shape of the grid - this needs to be done BEFORE supplyDataDefaults
// so that non-subplot traces can place themselves in the grid
function sizeDefaults(layoutIn, layoutOut) {
    var gridIn = layoutIn.grid || {};
    var xAxes = getAxes(layoutOut, gridIn, 'x');
    var yAxes = getAxes(layoutOut, gridIn, 'y');

    if(!layoutIn.grid && !xAxes && !yAxes) return;

    var hasSubplotGrid = Array.isArray(gridIn.subplots) && Array.isArray(gridIn.subplots[0]);
    var hasXaxes = Array.isArray(xAxes);
    var hasYaxes = Array.isArray(yAxes);
    var isSplomGenerated = (
        hasXaxes && xAxes !== gridIn.xaxes &&
        hasYaxes && yAxes !== gridIn.yaxes
    );

    var dfltRows, dfltColumns;

    if(hasSubplotGrid) {
        dfltRows = gridIn.subplots.length;
        dfltColumns = gridIn.subplots[0].length;
    }
    else {
        if(hasYaxes) dfltRows = yAxes.length;
        if(hasXaxes) dfltColumns = xAxes.length;
    }

    var gridOut = Template.newContainer(layoutOut, 'grid');

    function coerce(attr, dflt) {
        return Lib.coerce(gridIn, gridOut, gridAttrs, attr, dflt);
    }

    var rows = coerce('rows', dfltRows);
    var columns = coerce('columns', dfltColumns);

    if(!(rows * columns > 1)) {
        delete layoutOut.grid;
        return;
    }

    if(!hasSubplotGrid && !hasXaxes && !hasYaxes) {
        var useDefaultSubplots = coerce('pattern') === 'independent';
        if(useDefaultSubplots) hasSubplotGrid = true;
    }
    gridOut._hasSubplotGrid = hasSubplotGrid;

    var rowOrder = coerce('roworder');
    var reversed = rowOrder === 'top to bottom';

    var dfltGapX = hasSubplotGrid ? 0.2 : 0.1;
    var dfltGapY = hasSubplotGrid ? 0.3 : 0.1;

    var dfltSideX, dfltSideY;
    if(isSplomGenerated && layoutOut._splomGridDflt) {
        dfltSideX = layoutOut._splomGridDflt.xside;
        dfltSideY = layoutOut._splomGridDflt.yside;
    }

    gridOut._domains = {
        x: fillGridPositions('x', coerce, dfltGapX, dfltSideX, columns),
        y: fillGridPositions('y', coerce, dfltGapY, dfltSideY, rows, reversed)
    };
}

// coerce x or y sizing attributes and return an array of domains for this direction
function fillGridPositions(axLetter, coerce, dfltGap, dfltSide, len, reversed) {
    var dirGap = coerce(axLetter + 'gap', dfltGap);
    var domain = coerce('domain.' + axLetter);
    coerce(axLetter + 'side', dfltSide);

    var out = new Array(len);
    var start = domain[0];
    var step = (domain[1] - start) / (len - dirGap);
    var cellDomain = step * (1 - dirGap);
    for(var i = 0; i < len; i++) {
        var cellStart = start + step * i;
        out[reversed ? (len - 1 - i) : i] = [cellStart, cellStart + cellDomain];
    }
    return out;
}

// the (cartesian) contents of the grid - this needs to happen AFTER supplyDataDefaults
// so that we know what cartesian subplots are available
function contentDefaults(layoutIn, layoutOut) {
    var gridOut = layoutOut.grid;
    // make sure we got to the end of handleGridSizing
    if(!gridOut || !gridOut._domains) return;

    var gridIn = layoutIn.grid || {};
    var subplots = layoutOut._subplots;
    var hasSubplotGrid = gridOut._hasSubplotGrid;
    var rows = gridOut.rows;
    var columns = gridOut.columns;
    var useDefaultSubplots = gridOut.pattern === 'independent';

    var i, j, xId, yId, subplotId, subplotsOut, yPos;

    var axisMap = gridOut._axisMap = {};

    if(hasSubplotGrid) {
        var subplotsIn = gridIn.subplots || [];
        subplotsOut = gridOut.subplots = new Array(rows);
        var index = 1;

        for(i = 0; i < rows; i++) {
            var rowOut = subplotsOut[i] = new Array(columns);
            var rowIn = subplotsIn[i] || [];
            for(j = 0; j < columns; j++) {
                if(useDefaultSubplots) {
                    subplotId = (index === 1) ? 'xy' : ('x' + index + 'y' + index);
                    index++;
                }
                else subplotId = rowIn[j];

                rowOut[j] = '';

                if(subplots.cartesian.indexOf(subplotId) !== -1) {
                    yPos = subplotId.indexOf('y');
                    xId = subplotId.slice(0, yPos);
                    yId = subplotId.slice(yPos);
                    if((axisMap[xId] !== undefined && axisMap[xId] !== j) ||
                        (axisMap[yId] !== undefined && axisMap[yId] !== i)
                    ) {
                        continue;
                    }

                    rowOut[j] = subplotId;
                    axisMap[xId] = j;
                    axisMap[yId] = i;
                }
            }
        }
    }
    else {
        var xAxes = getAxes(layoutOut, gridIn, 'x');
        var yAxes = getAxes(layoutOut, gridIn, 'y');
        gridOut.xaxes = fillGridAxes(xAxes, subplots.xaxis, columns, axisMap, 'x');
        gridOut.yaxes = fillGridAxes(yAxes, subplots.yaxis, rows, axisMap, 'y');
    }

    var anchors = gridOut._anchors = {};
    var reversed = gridOut.roworder === 'top to bottom';

    for(var axisId in axisMap) {
        var axLetter = axisId.charAt(0);
        var side = gridOut[axLetter + 'side'];

        var i0, inc, iFinal;

        if(side.length < 8) {
            // grid edge -  ie not "* plot" - make these as free axes
            // since we're not guaranteed to have a subplot there at all
            anchors[axisId] = 'free';
        }
        else if(axLetter === 'x') {
            if((side.charAt(0) === 't') === reversed) {
                i0 = 0;
                inc = 1;
                iFinal = rows;
            }
            else {
                i0 = rows - 1;
                inc = -1;
                iFinal = -1;
            }
            if(hasSubplotGrid) {
                var column = axisMap[axisId];
                for(i = i0; i !== iFinal; i += inc) {
                    subplotId = subplotsOut[i][column];
                    if(!subplotId) continue;
                    yPos = subplotId.indexOf('y');
                    if(subplotId.slice(0, yPos) === axisId) {
                        anchors[axisId] = subplotId.slice(yPos);
                        break;
                    }
                }
            }
            else {
                for(i = i0; i !== iFinal; i += inc) {
                    yId = gridOut.yaxes[i];
                    if(subplots.cartesian.indexOf(axisId + yId) !== -1) {
                        anchors[axisId] = yId;
                        break;
                    }
                }
            }
        }
        else {
            if((side.charAt(0) === 'l')) {
                i0 = 0;
                inc = 1;
                iFinal = columns;
            }
            else {
                i0 = columns - 1;
                inc = -1;
                iFinal = -1;
            }
            if(hasSubplotGrid) {
                var row = axisMap[axisId];
                for(i = i0; i !== iFinal; i += inc) {
                    subplotId = subplotsOut[row][i];
                    if(!subplotId) continue;
                    yPos = subplotId.indexOf('y');
                    if(subplotId.slice(yPos) === axisId) {
                        anchors[axisId] = subplotId.slice(0, yPos);
                        break;
                    }
                }
            }
            else {
                for(i = i0; i !== iFinal; i += inc) {
                    xId = gridOut.xaxes[i];
                    if(subplots.cartesian.indexOf(xId + axisId) !== -1) {
                        anchors[axisId] = xId;
                        break;
                    }
                }
            }
        }
    }
}

function fillGridAxes(axesIn, axesAllowed, len, axisMap, axLetter) {
    var out = new Array(len);
    var i;

    function fillOneAxis(i, axisId) {
        if(axesAllowed.indexOf(axisId) !== -1 && axisMap[axisId] === undefined) {
            out[i] = axisId;
            axisMap[axisId] = i;
        }
        else out[i] = '';
    }

    if(Array.isArray(axesIn)) {
        for(i = 0; i < len; i++) {
            fillOneAxis(i, axesIn[i]);
        }
    }
    else {
        // default axis list is the first `len` axis ids
        fillOneAxis(0, axLetter);
        for(i = 1; i < len; i++) {
            fillOneAxis(i, axLetter + (i + 1));
        }
    }

    return out;
}

module.exports = {
    moduleType: 'component',
    name: 'grid',

    schema: {
        layout: {grid: gridAttrs}
    },

    layoutAttributes: gridAttrs,
    sizeDefaults: sizeDefaults,
    contentDefaults: contentDefaults
};

},{"../../lib":697,"../../lib/regex":713,"../../plot_api/plot_template":735,"../../plots/cartesian/constants":751,"../../plots/domain":770}],618:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var cartesianConstants = _dereq_('../../plots/cartesian/constants');
var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;


module.exports = templatedArray('image', {
    visible: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'arraydraw',
        
    },

    source: {
        valType: 'string',
        
        editType: 'arraydraw',
        
    },

    layer: {
        valType: 'enumerated',
        values: ['below', 'above'],
        dflt: 'above',
        
        editType: 'arraydraw',
        
    },

    sizex: {
        valType: 'number',
        
        dflt: 0,
        editType: 'arraydraw',
        
    },

    sizey: {
        valType: 'number',
        
        dflt: 0,
        editType: 'arraydraw',
        
    },

    sizing: {
        valType: 'enumerated',
        values: ['fill', 'contain', 'stretch'],
        dflt: 'contain',
        
        editType: 'arraydraw',
        
    },

    opacity: {
        valType: 'number',
        
        min: 0,
        max: 1,
        dflt: 1,
        editType: 'arraydraw',
        
    },

    x: {
        valType: 'any',
        
        dflt: 0,
        editType: 'arraydraw',
        
    },

    y: {
        valType: 'any',
        
        dflt: 0,
        editType: 'arraydraw',
        
    },

    xanchor: {
        valType: 'enumerated',
        values: ['left', 'center', 'right'],
        dflt: 'left',
        
        editType: 'arraydraw',
        
    },

    yanchor: {
        valType: 'enumerated',
        values: ['top', 'middle', 'bottom'],
        dflt: 'top',
        
        editType: 'arraydraw',
        
    },

    xref: {
        valType: 'enumerated',
        values: [
            'paper',
            cartesianConstants.idRegex.x.toString()
        ],
        dflt: 'paper',
        
        editType: 'arraydraw',
        
    },

    yref: {
        valType: 'enumerated',
        values: [
            'paper',
            cartesianConstants.idRegex.y.toString()
        ],
        dflt: 'paper',
        
        editType: 'arraydraw',
        
    },
    editType: 'arraydraw'
});

},{"../../plot_api/plot_template":735,"../../plots/cartesian/constants":751}],619:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var toLogRange = _dereq_('../../lib/to_log_range');

/*
 * convertCoords: when converting an axis between log and linear
 * you need to alter any images on that axis to keep them
 * pointing at the same data point.
 * In v2.0 this will become obsolete (or perhaps size will still need conversion?)
 * we convert size by declaring that the maximum extent *in data units* should be
 * the same, assuming the image is anchored by its center (could remove that restriction
 * if we think it's important) even though the actual left and right values will not be
 * quite the same since the scale becomes nonlinear (and central anchor means the pixel
 * center of the image, not the data units center)
 *
 * gd: the plot div
 * ax: the axis being changed
 * newType: the type it's getting
 * doExtra: function(attr, val) from inside relayout that sets the attribute.
 *     Use this to make the changes as it's aware if any other changes in the
 *     same relayout call should override this conversion.
 */
module.exports = function convertCoords(gd, ax, newType, doExtra) {
    ax = ax || {};

    var toLog = (newType === 'log') && (ax.type === 'linear');
    var fromLog = (newType === 'linear') && (ax.type === 'log');

    if(!(toLog || fromLog)) return;

    var images = gd._fullLayout.images;
    var axLetter = ax._id.charAt(0);
    var image;
    var attrPrefix;

    for(var i = 0; i < images.length; i++) {
        image = images[i];
        attrPrefix = 'images[' + i + '].';

        if(image[axLetter + 'ref'] === ax._id) {
            var currentPos = image[axLetter];
            var currentSize = image['size' + axLetter];
            var newPos = null;
            var newSize = null;

            if(toLog) {
                newPos = toLogRange(currentPos, ax.range);

                // this is the inverse of the conversion we do in fromLog below
                // so that the conversion is reversible (notice the fromLog conversion
                // is like sinh, and this one looks like arcsinh)
                var dx = currentSize / Math.pow(10, newPos) / 2;
                newSize = 2 * Math.log(dx + Math.sqrt(1 + dx * dx)) / Math.LN10;
            }
            else {
                newPos = Math.pow(10, currentPos);
                newSize = newPos * (Math.pow(10, currentSize / 2) - Math.pow(10, -currentSize / 2));
            }

            // if conversion failed, delete the value so it can get a default later on
            if(!isNumeric(newPos)) {
                newPos = null;
                newSize = null;
            }
            else if(!isNumeric(newSize)) newSize = null;

            doExtra(attrPrefix + axLetter, newPos);
            doExtra(attrPrefix + 'size' + axLetter, newSize);
        }
    }
};

},{"../../lib/to_log_range":723,"fast-isnumeric":218}],620:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');
var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');

var attributes = _dereq_('./attributes');
var name = 'images';

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
    var opts = {
        name: name,
        handleItemDefaults: imageDefaults
    };

    handleArrayContainerDefaults(layoutIn, layoutOut, opts);
};


function imageDefaults(imageIn, imageOut, fullLayout) {

    function coerce(attr, dflt) {
        return Lib.coerce(imageIn, imageOut, attributes, attr, dflt);
    }

    var source = coerce('source');
    var visible = coerce('visible', !!source);

    if(!visible) return imageOut;

    coerce('layer');
    coerce('xanchor');
    coerce('yanchor');
    coerce('sizex');
    coerce('sizey');
    coerce('sizing');
    coerce('opacity');

    var gdMock = { _fullLayout: fullLayout };
    var axLetters = ['x', 'y'];

    for(var i = 0; i < 2; i++) {
        // 'paper' is the fallback axref
        var axLetter = axLetters[i];
        var axRef = Axes.coerceRef(imageIn, imageOut, gdMock, axLetter, 'paper');

        if(axRef !== 'paper') {
            var ax = Axes.getFromId(gdMock, axRef);
            ax._imgIndices.push(imageOut._index);
        }

        Axes.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0);
    }

    return imageOut;
}

},{"../../lib":697,"../../plots/array_container_defaults":741,"../../plots/cartesian/axes":745,"./attributes":618}],621:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var Drawing = _dereq_('../drawing');
var Axes = _dereq_('../../plots/cartesian/axes');
var xmlnsNamespaces = _dereq_('../../constants/xmlns_namespaces');

module.exports = function draw(gd) {
    var fullLayout = gd._fullLayout;
    var imageDataAbove = [];
    var imageDataSubplot = {};
    var imageDataBelow = [];
    var subplot;
    var i;

    // Sort into top, subplot, and bottom layers
    for(i = 0; i < fullLayout.images.length; i++) {
        var img = fullLayout.images[i];

        if(img.visible) {
            if(img.layer === 'below' && img.xref !== 'paper' && img.yref !== 'paper') {
                subplot = img.xref + img.yref;

                var plotinfo = fullLayout._plots[subplot];

                if(!plotinfo) {
                    // Fall back to _imageLowerLayer in case the requested subplot doesn't exist.
                    // This can happen if you reference the image to an x / y axis combination
                    // that doesn't have any data on it (and layer is below)
                    imageDataBelow.push(img);
                    continue;
                }

                if(plotinfo.mainplot) {
                    subplot = plotinfo.mainplot.id;
                }

                if(!imageDataSubplot[subplot]) {
                    imageDataSubplot[subplot] = [];
                }
                imageDataSubplot[subplot].push(img);
            } else if(img.layer === 'above') {
                imageDataAbove.push(img);
            } else {
                imageDataBelow.push(img);
            }
        }
    }


    var anchors = {
        x: {
            left: { sizing: 'xMin', offset: 0 },
            center: { sizing: 'xMid', offset: -1 / 2 },
            right: { sizing: 'xMax', offset: -1 }
        },
        y: {
            top: { sizing: 'YMin', offset: 0 },
            middle: { sizing: 'YMid', offset: -1 / 2 },
            bottom: { sizing: 'YMax', offset: -1 }
        }
    };


    // Images must be converted to dataURL's for exporting.
    function setImage(d) {
        var thisImage = d3.select(this);

        if(this.img && this.img.src === d.source) {
            return;
        }

        thisImage.attr('xmlns', xmlnsNamespaces.svg);

        var imagePromise = new Promise(function(resolve) {

            var img = new Image();
            this.img = img;

            // If not set, a `tainted canvas` error is thrown
            img.setAttribute('crossOrigin', 'anonymous');
            img.onerror = errorHandler;
            img.onload = function() {
                var canvas = document.createElement('canvas');
                canvas.width = this.width;
                canvas.height = this.height;

                var ctx = canvas.getContext('2d');
                ctx.drawImage(this, 0, 0);

                var dataURL = canvas.toDataURL('image/png');

                thisImage.attr('xlink:href', dataURL);

                // resolve promise in onload handler instead of on 'load' to support IE11
                // see https://github.com/plotly/plotly.js/issues/1685
                // for more details
                resolve();
            };


            thisImage.on('error', errorHandler);

            img.src = d.source;

            function errorHandler() {
                thisImage.remove();
                resolve();
            }
        }.bind(this));

        gd._promises.push(imagePromise);
    }

    function applyAttributes(d) {
        var thisImage = d3.select(this);

        // Axes if specified
        var xa = Axes.getFromId(gd, d.xref);
        var ya = Axes.getFromId(gd, d.yref);

        var size = fullLayout._size;
        var width = xa ? Math.abs(xa.l2p(d.sizex) - xa.l2p(0)) : d.sizex * size.w;
        var height = ya ? Math.abs(ya.l2p(d.sizey) - ya.l2p(0)) : d.sizey * size.h;

        // Offsets for anchor positioning
        var xOffset = width * anchors.x[d.xanchor].offset;
        var yOffset = height * anchors.y[d.yanchor].offset;

        var sizing = anchors.x[d.xanchor].sizing + anchors.y[d.yanchor].sizing;

        // Final positions
        var xPos = (xa ? xa.r2p(d.x) + xa._offset : d.x * size.w + size.l) + xOffset;
        var yPos = (ya ? ya.r2p(d.y) + ya._offset : size.h - d.y * size.h + size.t) + yOffset;

        // Construct the proper aspectRatio attribute
        switch(d.sizing) {
            case 'fill':
                sizing += ' slice';
                break;

            case 'stretch':
                sizing = 'none';
                break;
        }

        thisImage.attr({
            x: xPos,
            y: yPos,
            width: width,
            height: height,
            preserveAspectRatio: sizing,
            opacity: d.opacity
        });


        // Set proper clipping on images
        var xId = xa ? xa._id : '';
        var yId = ya ? ya._id : '';
        var clipAxes = xId + yId;

        Drawing.setClipUrl(
            thisImage,
            clipAxes ? ('clip' + fullLayout._uid + clipAxes) : null,
            gd
        );
    }

    var imagesBelow = fullLayout._imageLowerLayer.selectAll('image')
        .data(imageDataBelow);
    var imagesAbove = fullLayout._imageUpperLayer.selectAll('image')
        .data(imageDataAbove);

    imagesBelow.enter().append('image');
    imagesAbove.enter().append('image');

    imagesBelow.exit().remove();
    imagesAbove.exit().remove();

    imagesBelow.each(function(d) {
        setImage.bind(this)(d);
        applyAttributes.bind(this)(d);
    });
    imagesAbove.each(function(d) {
        setImage.bind(this)(d);
        applyAttributes.bind(this)(d);
    });

    var allSubplots = Object.keys(fullLayout._plots);
    for(i = 0; i < allSubplots.length; i++) {
        subplot = allSubplots[i];
        var subplotObj = fullLayout._plots[subplot];

        // filter out overlaid plots (which havd their images on the main plot)
        // and gl2d plots (which don't support below images, at least not yet)
        if(!subplotObj.imagelayer) continue;

        var imagesOnSubplot = subplotObj.imagelayer.selectAll('image')
            // even if there are no images on this subplot, we need to run
            // enter and exit in case there were previously
            .data(imageDataSubplot[subplot] || []);

        imagesOnSubplot.enter().append('image');
        imagesOnSubplot.exit().remove();

        imagesOnSubplot.each(function(d) {
            setImage.bind(this)(d);
            applyAttributes.bind(this)(d);
        });
    }
};

},{"../../constants/xmlns_namespaces":675,"../../plots/cartesian/axes":745,"../drawing":595,"d3":151}],622:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'component',
    name: 'images',

    layoutAttributes: _dereq_('./attributes'),
    supplyLayoutDefaults: _dereq_('./defaults'),
    includeBasePlot: _dereq_('../../plots/cartesian/include_components')('images'),

    draw: _dereq_('./draw'),

    convertCoords: _dereq_('./convert_coords')
};

},{"../../plots/cartesian/include_components":755,"./attributes":618,"./convert_coords":619,"./defaults":620,"./draw":621}],623:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = _dereq_('../../plots/font_attributes');
var colorAttrs = _dereq_('../color/attributes');


module.exports = {
    bgcolor: {
        valType: 'color',
        
        editType: 'legend',
        
    },
    bordercolor: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'legend',
        
    },
    borderwidth: {
        valType: 'number',
        min: 0,
        dflt: 0,
        
        editType: 'legend',
        
    },
    font: fontAttrs({
        editType: 'legend',
        
    }),
    orientation: {
        valType: 'enumerated',
        values: ['v', 'h'],
        dflt: 'v',
        
        editType: 'legend',
        
    },
    traceorder: {
        valType: 'flaglist',
        flags: ['reversed', 'grouped'],
        extras: ['normal'],
        
        editType: 'legend',
        
    },
    tracegroupgap: {
        valType: 'number',
        min: 0,
        dflt: 10,
        
        editType: 'legend',
        
    },
    x: {
        valType: 'number',
        min: -2,
        max: 3,
        dflt: 1.02,
        
        editType: 'legend',
        
    },
    xanchor: {
        valType: 'enumerated',
        values: ['auto', 'left', 'center', 'right'],
        dflt: 'left',
        
        editType: 'legend',
        
    },
    y: {
        valType: 'number',
        min: -2,
        max: 3,
        dflt: 1,
        
        editType: 'legend',
        
    },
    yanchor: {
        valType: 'enumerated',
        values: ['auto', 'top', 'middle', 'bottom'],
        dflt: 'auto',
        
        editType: 'legend',
        
    },
    uirevision: {
        valType: 'any',
        
        editType: 'none',
        
    },
    valign: {
        valType: 'enumerated',
        values: ['top', 'middle', 'bottom'],
        dflt: 'middle',
        
        editType: 'legend',
        
    },
    editType: 'legend'
};

},{"../../plots/font_attributes":771,"../color/attributes":573}],624:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    scrollBarWidth: 6,
    scrollBarMinHeight: 20,
    scrollBarColor: '#808BA4',
    scrollBarMargin: 4,
    textOffsetX: 40
};

},{}],625:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Template = _dereq_('../../plot_api/plot_template');

var attributes = _dereq_('./attributes');
var basePlotLayoutAttributes = _dereq_('../../plots/layout_attributes');
var helpers = _dereq_('./helpers');


module.exports = function legendDefaults(layoutIn, layoutOut, fullData) {
    var containerIn = layoutIn.legend || {};

    var legendTraceCount = 0;
    var legendReallyHasATrace = false;
    var defaultOrder = 'normal';

    var defaultX, defaultY, defaultXAnchor, defaultYAnchor;

    for(var i = 0; i < fullData.length; i++) {
        var trace = fullData[i];

        if(!trace.visible) continue;

        // Note that we explicitly count any trace that is either shown or
        // *would* be shown by default, toward the two traces you need to
        // ensure the legend is shown by default, because this can still help
        // disambiguate.
        if(trace.showlegend || trace._dfltShowLegend) {
            legendTraceCount++;
            if(trace.showlegend) {
                legendReallyHasATrace = true;
                // Always show the legend by default if there's a pie,
                // or if there's only one trace but it's explicitly shown
                if(Registry.traceIs(trace, 'pie') ||
                    trace._input.showlegend === true
                ) {
                    legendTraceCount++;
                }
            }
        }

        if((Registry.traceIs(trace, 'bar') && layoutOut.barmode === 'stack') ||
                ['tonextx', 'tonexty'].indexOf(trace.fill) !== -1) {
            defaultOrder = helpers.isGrouped({traceorder: defaultOrder}) ?
                'grouped+reversed' : 'reversed';
        }

        if(trace.legendgroup !== undefined && trace.legendgroup !== '') {
            defaultOrder = helpers.isReversed({traceorder: defaultOrder}) ?
                'reversed+grouped' : 'grouped';
        }
    }

    var showLegend = Lib.coerce(layoutIn, layoutOut,
        basePlotLayoutAttributes, 'showlegend',
        legendReallyHasATrace && legendTraceCount > 1);

    if(showLegend === false && !containerIn.uirevision) return;

    var containerOut = Template.newContainer(layoutOut, 'legend');

    function coerce(attr, dflt) {
        return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
    }

    coerce('uirevision', layoutOut.uirevision);

    if(showLegend === false) return;

    coerce('bgcolor', layoutOut.paper_bgcolor);
    coerce('bordercolor');
    coerce('borderwidth');
    Lib.coerceFont(coerce, 'font', layoutOut.font);

    coerce('orientation');
    if(containerOut.orientation === 'h') {
        var xaxis = layoutIn.xaxis;
        if(Registry.getComponentMethod('rangeslider', 'isVisible')(xaxis)) {
            defaultX = 0;
            defaultXAnchor = 'left';
            defaultY = 1.1;
            defaultYAnchor = 'bottom';
        }
        else {
            defaultX = 0;
            defaultXAnchor = 'left';
            defaultY = -0.1;
            defaultYAnchor = 'top';
        }
    }

    coerce('traceorder', defaultOrder);
    if(helpers.isGrouped(layoutOut.legend)) coerce('tracegroupgap');

    coerce('x', defaultX);
    coerce('xanchor', defaultXAnchor);
    coerce('y', defaultY);
    coerce('yanchor', defaultYAnchor);
    coerce('valign');
    Lib.noneOrAll(containerIn, containerOut, ['x', 'y']);
};

},{"../../lib":697,"../../plot_api/plot_template":735,"../../plots/layout_attributes":798,"../../registry":826,"./attributes":623,"./helpers":629}],626:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Lib = _dereq_('../../lib');
var Plots = _dereq_('../../plots/plots');
var Registry = _dereq_('../../registry');
var Events = _dereq_('../../lib/events');
var dragElement = _dereq_('../dragelement');
var Drawing = _dereq_('../drawing');
var Color = _dereq_('../color');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var handleClick = _dereq_('./handle_click');

var constants = _dereq_('./constants');
var interactConstants = _dereq_('../../constants/interactions');
var alignmentConstants = _dereq_('../../constants/alignment');
var LINE_SPACING = alignmentConstants.LINE_SPACING;
var FROM_TL = alignmentConstants.FROM_TL;
var FROM_BR = alignmentConstants.FROM_BR;

var getLegendData = _dereq_('./get_legend_data');
var style = _dereq_('./style');
var helpers = _dereq_('./helpers');

var DBLCLICKDELAY = interactConstants.DBLCLICKDELAY;

module.exports = function draw(gd) {
    var fullLayout = gd._fullLayout;
    var clipId = 'legend' + fullLayout._uid;

    if(!fullLayout._infolayer || !gd.calcdata) return;

    if(!gd._legendMouseDownTime) gd._legendMouseDownTime = 0;

    var opts = fullLayout.legend;
    var legendData = fullLayout.showlegend && getLegendData(gd.calcdata, opts);
    var hiddenSlices = fullLayout.hiddenlabels || [];

    if(!fullLayout.showlegend || !legendData.length) {
        fullLayout._infolayer.selectAll('.legend').remove();
        fullLayout._topdefs.select('#' + clipId).remove();

        Plots.autoMargin(gd, 'legend');
        return;
    }

    var maxLength = 0;
    for(var i = 0; i < legendData.length; i++) {
        for(var j = 0; j < legendData[i].length; j++) {
            var item = legendData[i][j][0];
            var trace = item.trace;
            var isPie = Registry.traceIs(trace, 'pie');
            var name = isPie ? item.label : trace.name;
            maxLength = Math.max(maxLength, name && name.length || 0);
        }
    }

    var firstRender = false;
    var legend = Lib.ensureSingle(fullLayout._infolayer, 'g', 'legend', function(s) {
        s.attr('pointer-events', 'all');
        firstRender = true;
    });

    var clipPath = Lib.ensureSingleById(fullLayout._topdefs, 'clipPath', clipId, function(s) {
        s.append('rect');
    });

    var bg = Lib.ensureSingle(legend, 'rect', 'bg', function(s) {
        s.attr('shape-rendering', 'crispEdges');
    });

    bg.call(Color.stroke, opts.bordercolor)
        .call(Color.fill, opts.bgcolor)
        .style('stroke-width', opts.borderwidth + 'px');

    var scrollBox = Lib.ensureSingle(legend, 'g', 'scrollbox');

    var scrollBar = Lib.ensureSingle(legend, 'rect', 'scrollbar', function(s) {
        s.attr({
            rx: 20,
            ry: 3,
            width: 0,
            height: 0
        })
        .call(Color.fill, '#808BA4');
    });

    var groups = scrollBox.selectAll('g.groups')
        .data(legendData);

    groups.enter().append('g')
        .attr('class', 'groups');

    groups.exit().remove();

    var traces = groups.selectAll('g.traces')
        .data(Lib.identity);

    traces.enter().append('g').attr('class', 'traces');
    traces.exit().remove();

    traces.style('opacity', function(d) {
        var trace = d[0].trace;
        if(Registry.traceIs(trace, 'pie')) {
            return hiddenSlices.indexOf(d[0].label) !== -1 ? 0.5 : 1;
        } else {
            return trace.visible === 'legendonly' ? 0.5 : 1;
        }
    })
    .each(function() {
        d3.select(this)
            .call(drawTexts, gd, maxLength);
    })
    .call(style, gd)
    .each(function() {
        d3.select(this)
            .call(setupTraceToggle, gd);
    });

    Lib.syncOrAsync([Plots.previousPromises,
        function() {
            if(firstRender) {
                computeLegendDimensions(gd, groups, traces);
                expandMargin(gd);
            }

            // Position and size the legend
            var lxMin = 0;
            var lxMax = fullLayout.width;
            var lyMin = 0;
            var lyMax = fullLayout.height;

            computeLegendDimensions(gd, groups, traces);

            if(opts._height > lyMax) {
                // If the legend doesn't fit in the plot area,
                // do not expand the vertical margins.
                expandHorizontalMargin(gd);
            } else {
                expandMargin(gd);
            }

            // Scroll section must be executed after repositionLegend.
            // It requires the legend width, height, x and y to position the scrollbox
            // and these values are mutated in repositionLegend.
            var gs = fullLayout._size;
            var lx = gs.l + gs.w * opts.x;
            var ly = gs.t + gs.h * (1 - opts.y);

            if(Lib.isRightAnchor(opts)) {
                lx -= opts._width;
            }
            else if(Lib.isCenterAnchor(opts)) {
                lx -= opts._width / 2;
            }

            if(Lib.isBottomAnchor(opts)) {
                ly -= opts._height;
            }
            else if(Lib.isMiddleAnchor(opts)) {
                ly -= opts._height / 2;
            }

            // Make sure the legend left and right sides are visible
            var legendWidth = opts._width;
            var legendWidthMax = gs.w;

            if(legendWidth > legendWidthMax) {
                lx = gs.l;
                legendWidth = legendWidthMax;
            }
            else {
                if(lx + legendWidth > lxMax) lx = lxMax - legendWidth;
                if(lx < lxMin) lx = lxMin;
                legendWidth = Math.min(lxMax - lx, opts._width);
            }

            // Make sure the legend top and bottom are visible
            // (legends with a scroll bar are not allowed to stretch beyond the extended
            // margins)
            var legendHeight = opts._height;
            var legendHeightMax = gs.h;

            if(legendHeight > legendHeightMax) {
                ly = gs.t;
                legendHeight = legendHeightMax;
            }
            else {
                if(ly + legendHeight > lyMax) ly = lyMax - legendHeight;
                if(ly < lyMin) ly = lyMin;
                legendHeight = Math.min(lyMax - ly, opts._height);
            }

            // Set size and position of all the elements that make up a legend:
            // legend, background and border, scroll box and scroll bar
            Drawing.setTranslate(legend, lx, ly);

            // to be safe, remove previous listeners
            scrollBar.on('.drag', null);
            legend.on('wheel', null);

            if(opts._height <= legendHeight || gd._context.staticPlot) {
                // if scrollbar should not be shown.
                bg.attr({
                    width: legendWidth - opts.borderwidth,
                    height: legendHeight - opts.borderwidth,
                    x: opts.borderwidth / 2,
                    y: opts.borderwidth / 2
                });

                Drawing.setTranslate(scrollBox, 0, 0);

                clipPath.select('rect').attr({
                    width: legendWidth - 2 * opts.borderwidth,
                    height: legendHeight - 2 * opts.borderwidth,
                    x: opts.borderwidth,
                    y: opts.borderwidth
                });

                Drawing.setClipUrl(scrollBox, clipId, gd);

                Drawing.setRect(scrollBar, 0, 0, 0, 0);
                delete opts._scrollY;
            }
            else {
                var scrollBarHeight = Math.max(constants.scrollBarMinHeight,
                    legendHeight * legendHeight / opts._height);
                var scrollBarYMax = legendHeight -
                    scrollBarHeight -
                    2 * constants.scrollBarMargin;
                var scrollBoxYMax = opts._height - legendHeight;
                var scrollRatio = scrollBarYMax / scrollBoxYMax;

                var scrollBoxY = Math.min(opts._scrollY || 0, scrollBoxYMax);

                // increase the background and clip-path width
                // by the scrollbar width and margin
                bg.attr({
                    width: legendWidth -
                        2 * opts.borderwidth +
                        constants.scrollBarWidth +
                        constants.scrollBarMargin,
                    height: legendHeight - opts.borderwidth,
                    x: opts.borderwidth / 2,
                    y: opts.borderwidth / 2
                });

                clipPath.select('rect').attr({
                    width: legendWidth -
                        2 * opts.borderwidth +
                        constants.scrollBarWidth +
                        constants.scrollBarMargin,
                    height: legendHeight - 2 * opts.borderwidth,
                    x: opts.borderwidth,
                    y: opts.borderwidth + scrollBoxY
                });

                Drawing.setClipUrl(scrollBox, clipId, gd);

                scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio);

                legend.on('wheel', function() {
                    scrollBoxY = Lib.constrain(
                        opts._scrollY +
                            d3.event.deltaY / scrollBarYMax * scrollBoxYMax,
                        0, scrollBoxYMax);
                    scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio);
                    if(scrollBoxY !== 0 && scrollBoxY !== scrollBoxYMax) {
                        d3.event.preventDefault();
                    }
                });

                var eventY0, scrollBoxY0;

                var drag = d3.behavior.drag()
                .on('dragstart', function() {
                    eventY0 = d3.event.sourceEvent.clientY;
                    scrollBoxY0 = scrollBoxY;
                })
                .on('drag', function() {
                    var e = d3.event.sourceEvent;
                    if(e.buttons === 2 || e.ctrlKey) return;

                    scrollBoxY = Lib.constrain(
                        (e.clientY - eventY0) / scrollRatio + scrollBoxY0,
                        0, scrollBoxYMax);
                    scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio);
                });

                scrollBar.call(drag);
            }


            function scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio) {
                opts._scrollY = gd._fullLayout.legend._scrollY = scrollBoxY;
                Drawing.setTranslate(scrollBox, 0, -scrollBoxY);

                Drawing.setRect(
                    scrollBar,
                    legendWidth,
                    constants.scrollBarMargin + scrollBoxY * scrollRatio,
                    constants.scrollBarWidth,
                    scrollBarHeight
                );
                clipPath.select('rect').attr({
                    y: opts.borderwidth + scrollBoxY
                });
            }

            if(gd._context.edits.legendPosition) {
                var xf, yf, x0, y0;

                legend.classed('cursor-move', true);

                dragElement.init({
                    element: legend.node(),
                    gd: gd,
                    prepFn: function() {
                        var transform = Drawing.getTranslate(legend);

                        x0 = transform.x;
                        y0 = transform.y;
                    },
                    moveFn: function(dx, dy) {
                        var newX = x0 + dx;
                        var newY = y0 + dy;

                        Drawing.setTranslate(legend, newX, newY);

                        xf = dragElement.align(newX, 0, gs.l, gs.l + gs.w, opts.xanchor);
                        yf = dragElement.align(newY, 0, gs.t + gs.h, gs.t, opts.yanchor);
                    },
                    doneFn: function() {
                        if(xf !== undefined && yf !== undefined) {
                            Registry.call('_guiRelayout', gd, {'legend.x': xf, 'legend.y': yf});
                        }
                    },
                    clickFn: function(numClicks, e) {
                        var clickedTrace = fullLayout._infolayer.selectAll('g.traces').filter(function() {
                            var bbox = this.getBoundingClientRect();
                            return (
                                e.clientX >= bbox.left && e.clientX <= bbox.right &&
                                e.clientY >= bbox.top && e.clientY <= bbox.bottom
                            );
                        });
                        if(clickedTrace.size() > 0) {
                            clickOrDoubleClick(gd, legend, clickedTrace, numClicks, e);
                        }
                    }
                });
            }
        }], gd);
};

function clickOrDoubleClick(gd, legend, legendItem, numClicks, evt) {
    var trace = legendItem.data()[0][0].trace;

    var evtData = {
        event: evt,
        node: legendItem.node(),
        curveNumber: trace.index,
        expandedIndex: trace._expandedIndex,
        data: gd.data,
        layout: gd.layout,
        frames: gd._transitionData._frames,
        config: gd._context,
        fullData: gd._fullData,
        fullLayout: gd._fullLayout
    };

    if(trace._group) {
        evtData.group = trace._group;
    }
    if(trace.type === 'pie') {
        evtData.label = legendItem.datum()[0].label;
    }

    var clickVal = Events.triggerHandler(gd, 'plotly_legendclick', evtData);
    if(clickVal === false) return;

    if(numClicks === 1) {
        legend._clickTimeout = setTimeout(function() {
            handleClick(legendItem, gd, numClicks);
        }, DBLCLICKDELAY);
    }
    else if(numClicks === 2) {
        if(legend._clickTimeout) clearTimeout(legend._clickTimeout);
        gd._legendMouseDownTime = 0;

        var dblClickVal = Events.triggerHandler(gd, 'plotly_legenddoubleclick', evtData);
        if(dblClickVal !== false) handleClick(legendItem, gd, numClicks);
    }
}

function drawTexts(g, gd, maxLength) {
    var legendItem = g.data()[0][0];
    var fullLayout = gd._fullLayout;
    var trace = legendItem.trace;
    var isPie = Registry.traceIs(trace, 'pie');
    var traceIndex = trace.index;
    var isEditable = gd._context.edits.legendText && !isPie;

    var name = isPie ? legendItem.label : trace.name;
    if(fullLayout.meta) {
        name = Lib.templateString(name, {meta: fullLayout.meta});
    }

    var textEl = Lib.ensureSingle(g, 'text', 'legendtext');

    textEl.attr('text-anchor', 'start')
        .classed('user-select-none', true)
        .call(Drawing.font, fullLayout.legend.font)
        .text(isEditable ? ensureLength(name, maxLength) : name);

    svgTextUtils.positionText(textEl, constants.textOffsetX, 0);

    function textLayout(s) {
        svgTextUtils.convertToTspans(s, gd, function() {
            computeTextDimensions(g, gd);
        });
    }

    if(isEditable) {
        textEl.call(svgTextUtils.makeEditable, {gd: gd, text: name})
            .call(textLayout)
            .on('edit', function(newName) {
                this.text(ensureLength(newName, maxLength))
                    .call(textLayout);

                var fullInput = legendItem.trace._fullInput || {};
                var update = {};

                if(Registry.hasTransform(fullInput, 'groupby')) {
                    var groupbyIndices = Registry.getTransformIndices(fullInput, 'groupby');
                    var index = groupbyIndices[groupbyIndices.length - 1];

                    var kcont = Lib.keyedContainer(fullInput, 'transforms[' + index + '].styles', 'target', 'value.name');

                    kcont.set(legendItem.trace._group, newName);

                    update = kcont.constructUpdate();
                } else {
                    update.name = newName;
                }

                return Registry.call('_guiRestyle', gd, update, traceIndex);
            });
    } else {
        textLayout(textEl);
    }
}

/*
 * Make sure we have a reasonably clickable region.
 * If this string is missing or very short, pad it with spaces out to at least
 * 4 characters, up to the max length of other labels, on the assumption that
 * most characters are wider than spaces so a string of spaces will usually be
 * no wider than the real labels.
 */
function ensureLength(str, maxLength) {
    var targetLength = Math.max(4, maxLength);
    if(str && str.trim().length >= targetLength / 2) return str;
    str = str || '';
    for(var i = targetLength - str.length; i > 0; i--) str += ' ';
    return str;
}

function setupTraceToggle(g, gd) {
    var newMouseDownTime;
    var numClicks = 1;

    var traceToggle = Lib.ensureSingle(g, 'rect', 'legendtoggle', function(s) {
        s.style('cursor', 'pointer')
            .attr('pointer-events', 'all')
            .call(Color.fill, 'rgba(0,0,0,0)');
    });

    traceToggle.on('mousedown', function() {
        newMouseDownTime = (new Date()).getTime();
        if(newMouseDownTime - gd._legendMouseDownTime < DBLCLICKDELAY) {
            // in a click train
            numClicks += 1;
        }
        else {
            // new click train
            numClicks = 1;
            gd._legendMouseDownTime = newMouseDownTime;
        }
    });
    traceToggle.on('mouseup', function() {
        if(gd._dragged || gd._editing) return;
        var legend = gd._fullLayout.legend;

        if((new Date()).getTime() - gd._legendMouseDownTime > DBLCLICKDELAY) {
            numClicks = Math.max(numClicks - 1, 1);
        }

        clickOrDoubleClick(gd, legend, g, numClicks, d3.event);
    });
}

function computeTextDimensions(g, gd) {
    var legendItem = g.data()[0][0];

    if(!legendItem.trace.showlegend) {
        g.remove();
        return;
    }

    var mathjaxGroup = g.select('g[class*=math-group]');
    var mathjaxNode = mathjaxGroup.node();
    var opts = gd._fullLayout.legend;
    var lineHeight = opts.font.size * LINE_SPACING;
    var height, width;

    if(mathjaxNode) {
        var mathjaxBB = Drawing.bBox(mathjaxNode);

        height = mathjaxBB.height;
        width = mathjaxBB.width;

        Drawing.setTranslate(mathjaxGroup, 0, (height / 4));
    } else {
        var text = g.select('.legendtext');
        var textLines = svgTextUtils.lineCount(text);
        var textNode = text.node();

        height = lineHeight * textLines;
        width = textNode ? Drawing.bBox(textNode).width : 0;

        // approximation to height offset to center the font
        // to avoid getBoundingClientRect
        var textY = lineHeight * (0.3 + (1 - textLines) / 2);
        svgTextUtils.positionText(text, constants.textOffsetX, textY);
    }

    legendItem.lineHeight = lineHeight;
    legendItem.height = Math.max(height, 16) + 3;
    legendItem.width = width;
}

function computeLegendDimensions(gd, groups, traces) {
    var fullLayout = gd._fullLayout;
    var opts = fullLayout.legend;
    var borderwidth = opts.borderwidth;
    var isGrouped = helpers.isGrouped(opts);

    var extraWidth = 0;

    opts._width = 0;
    opts._height = 0;

    if(helpers.isVertical(opts)) {
        if(isGrouped) {
            groups.each(function(d, i) {
                Drawing.setTranslate(this, 0, i * opts.tracegroupgap);
            });
        }

        traces.each(function(d) {
            var legendItem = d[0];
            var textHeight = legendItem.height;
            var textWidth = legendItem.width;

            Drawing.setTranslate(this,
                borderwidth,
                (5 + borderwidth + opts._height + textHeight / 2));

            opts._height += textHeight;
            opts._width = Math.max(opts._width, textWidth);
        });

        opts._width += 45 + borderwidth * 2;
        opts._height += 10 + borderwidth * 2;

        if(isGrouped) {
            opts._height += (opts._lgroupsLength - 1) * opts.tracegroupgap;
        }

        extraWidth = 40;
    }
    else if(isGrouped) {
        var groupXOffsets = [opts._width];
        var groupData = groups.data();

        for(var i = 0, n = groupData.length; i < n; i++) {
            var textWidths = groupData[i].map(function(legendItemArray) {
                return legendItemArray[0].width;
            });

            var groupWidth = 40 + Math.max.apply(null, textWidths);

            opts._width += opts.tracegroupgap + groupWidth;

            groupXOffsets.push(opts._width);
        }

        groups.each(function(d, i) {
            Drawing.setTranslate(this, groupXOffsets[i], 0);
        });

        groups.each(function() {
            var group = d3.select(this);
            var groupTraces = group.selectAll('g.traces');
            var groupHeight = 0;

            groupTraces.each(function(d) {
                var legendItem = d[0];
                var textHeight = legendItem.height;

                Drawing.setTranslate(this,
                    0,
                    (5 + borderwidth + groupHeight + textHeight / 2));

                groupHeight += textHeight;
            });

            opts._height = Math.max(opts._height, groupHeight);
        });

        opts._height += 10 + borderwidth * 2;
        opts._width += borderwidth * 2;
    }
    else {
        var rowHeight = 0;
        var maxTraceHeight = 0;
        var maxTraceWidth = 0;
        var offsetX = 0;
        var fullTracesWidth = 0;
        var traceGap = opts.tracegroupgap || 5;

        // calculate largest width for traces and use for width of all legend items
        traces.each(function(d) {
            maxTraceWidth = Math.max(40 + d[0].width, maxTraceWidth);
            fullTracesWidth += 40 + d[0].width + traceGap;
        });

        // check if legend fits in one row
        var oneRowLegend = fullLayout._size.w > borderwidth + fullTracesWidth - traceGap;

        traces.each(function(d) {
            var legendItem = d[0];
            var traceWidth = oneRowLegend ? 40 + d[0].width : maxTraceWidth;

            if((borderwidth + offsetX + traceGap + traceWidth) > fullLayout._size.w) {
                offsetX = 0;
                rowHeight += maxTraceHeight;
                opts._height += maxTraceHeight;
                // reset for next row
                maxTraceHeight = 0;
            }

            Drawing.setTranslate(this,
                (borderwidth + offsetX),
                (5 + borderwidth + legendItem.height / 2) + rowHeight);

            opts._width += traceGap + traceWidth;

            // keep track of tallest trace in group
            offsetX += traceGap + traceWidth;
            maxTraceHeight = Math.max(legendItem.height, maxTraceHeight);
        });

        if(oneRowLegend) {
            opts._height = maxTraceHeight;
        } else {
            opts._height += maxTraceHeight;
        }

        opts._width += borderwidth * 2;
        opts._height += 10 + borderwidth * 2;
    }

    // make sure we're only getting full pixels
    opts._width = Math.ceil(opts._width);
    opts._height = Math.ceil(opts._height);

    var isEditable = (
        gd._context.edits.legendText ||
        gd._context.edits.legendPosition
    );

    traces.each(function(d) {
        var legendItem = d[0];
        var bg = d3.select(this).select('.legendtoggle');

        Drawing.setRect(bg,
            0,
            -legendItem.height / 2,
            (isEditable ? 0 : opts._width) + extraWidth,
            legendItem.height
        );
    });
}

function expandMargin(gd) {
    var fullLayout = gd._fullLayout;
    var opts = fullLayout.legend;

    var xanchor = 'left';
    if(Lib.isRightAnchor(opts)) {
        xanchor = 'right';
    }
    else if(Lib.isCenterAnchor(opts)) {
        xanchor = 'center';
    }

    var yanchor = 'top';
    if(Lib.isBottomAnchor(opts)) {
        yanchor = 'bottom';
    }
    else if(Lib.isMiddleAnchor(opts)) {
        yanchor = 'middle';
    }

    // lastly check if the margin auto-expand has changed
    Plots.autoMargin(gd, 'legend', {
        x: opts.x,
        y: opts.y,
        l: opts._width * (FROM_TL[xanchor]),
        r: opts._width * (FROM_BR[xanchor]),
        b: opts._height * (FROM_BR[yanchor]),
        t: opts._height * (FROM_TL[yanchor])
    });
}

function expandHorizontalMargin(gd) {
    var fullLayout = gd._fullLayout;
    var opts = fullLayout.legend;

    var xanchor = 'left';
    if(Lib.isRightAnchor(opts)) {
        xanchor = 'right';
    }
    else if(Lib.isCenterAnchor(opts)) {
        xanchor = 'center';
    }

    // lastly check if the margin auto-expand has changed
    Plots.autoMargin(gd, 'legend', {
        x: opts.x,
        y: 0.5,
        l: opts._width * (FROM_TL[xanchor]),
        r: opts._width * (FROM_BR[xanchor]),
        b: 0,
        t: 0
    });
}

},{"../../constants/alignment":669,"../../constants/interactions":673,"../../lib":697,"../../lib/events":686,"../../lib/svg_text_utils":721,"../../plots/plots":807,"../../registry":826,"../color":574,"../dragelement":592,"../drawing":595,"./constants":624,"./get_legend_data":627,"./handle_click":628,"./helpers":629,"./style":631,"d3":151}],627:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../../registry');
var helpers = _dereq_('./helpers');


module.exports = function getLegendData(calcdata, opts) {
    var lgroupToTraces = {};
    var lgroups = [];
    var hasOneNonBlankGroup = false;
    var slicesShown = {};
    var lgroupi = 0;
    var i, j;

    function addOneItem(legendGroup, legendItem) {
        // each '' legend group is treated as a separate group
        if(legendGroup === '' || !helpers.isGrouped(opts)) {
            var uniqueGroup = '~~i' + lgroupi; // TODO: check this against fullData legendgroups?

            lgroups.push(uniqueGroup);
            lgroupToTraces[uniqueGroup] = [[legendItem]];
            lgroupi++;
        }
        else if(lgroups.indexOf(legendGroup) === -1) {
            lgroups.push(legendGroup);
            hasOneNonBlankGroup = true;
            lgroupToTraces[legendGroup] = [[legendItem]];
        }
        else lgroupToTraces[legendGroup].push([legendItem]);
    }

    // build an { legendgroup: [cd0, cd0], ... } object
    for(i = 0; i < calcdata.length; i++) {
        var cd = calcdata[i];
        var cd0 = cd[0];
        var trace = cd0.trace;
        var lgroup = trace.legendgroup;

        if(!trace.visible || !trace.showlegend) continue;

        if(Registry.traceIs(trace, 'pie')) {
            if(!slicesShown[lgroup]) slicesShown[lgroup] = {};

            for(j = 0; j < cd.length; j++) {
                var labelj = cd[j].label;

                if(!slicesShown[lgroup][labelj]) {
                    addOneItem(lgroup, {
                        label: labelj,
                        color: cd[j].color,
                        i: cd[j].i,
                        trace: trace,
                        pts: cd[j].pts
                    });

                    slicesShown[lgroup][labelj] = true;
                }
            }
        }

        else addOneItem(lgroup, cd0);
    }

    // won't draw a legend in this case
    if(!lgroups.length) return [];

    // rearrange lgroupToTraces into a d3-friendly array of arrays
    var lgroupsLength = lgroups.length;
    var ltraces;
    var legendData;

    if(hasOneNonBlankGroup && helpers.isGrouped(opts)) {
        legendData = new Array(lgroupsLength);

        for(i = 0; i < lgroupsLength; i++) {
            ltraces = lgroupToTraces[lgroups[i]];
            legendData[i] = helpers.isReversed(opts) ? ltraces.reverse() : ltraces;
        }
    }
    else {
        // collapse all groups into one if all groups are blank
        legendData = [new Array(lgroupsLength)];

        for(i = 0; i < lgroupsLength; i++) {
            ltraces = lgroupToTraces[lgroups[i]][0];
            legendData[0][helpers.isReversed(opts) ? lgroupsLength - i - 1 : i] = ltraces;
        }
        lgroupsLength = 1;
    }

    // needed in repositionLegend
    opts._lgroupsLength = lgroupsLength;
    return legendData;
};

},{"../../registry":826,"./helpers":629}],628:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Registry = _dereq_('../../registry');

var SHOWISOLATETIP = true;

module.exports = function handleClick(g, gd, numClicks) {
    if(gd._dragged || gd._editing) return;

    var hiddenSlices = gd._fullLayout.hiddenlabels ?
        gd._fullLayout.hiddenlabels.slice() :
        [];

    var legendItem = g.data()[0][0];
    var fullData = gd._fullData;
    var fullTrace = legendItem.trace;
    var legendgroup = fullTrace.legendgroup;

    var i, j, kcont, key, keys, val;
    var attrUpdate = {};
    var attrIndices = [];
    var carrs = [];
    var carrIdx = [];

    function insertUpdate(traceIndex, key, value) {
        var attrIndex = attrIndices.indexOf(traceIndex);
        var valueArray = attrUpdate[key];
        if(!valueArray) {
            valueArray = attrUpdate[key] = [];
        }

        if(attrIndices.indexOf(traceIndex) === -1) {
            attrIndices.push(traceIndex);
            attrIndex = attrIndices.length - 1;
        }

        valueArray[attrIndex] = value;

        return attrIndex;
    }

    function setVisibility(fullTrace, visibility) {
        var fullInput = fullTrace._fullInput;
        if(Registry.hasTransform(fullInput, 'groupby')) {
            var kcont = carrs[fullInput.index];
            if(!kcont) {
                var groupbyIndices = Registry.getTransformIndices(fullInput, 'groupby');
                var lastGroupbyIndex = groupbyIndices[groupbyIndices.length - 1];
                kcont = Lib.keyedContainer(fullInput, 'transforms[' + lastGroupbyIndex + '].styles', 'target', 'value.visible');
                carrs[fullInput.index] = kcont;
            }

            var curState = kcont.get(fullTrace._group);

            // If not specified, assume visible. This happens if there are other style
            // properties set for a group but not the visibility. There are many similar
            // ways to do this (e.g. why not just `curState = fullTrace.visible`??? The
            // answer is: because it breaks other things like groupby trace names in
            // subtle ways.)
            if(curState === undefined) {
                curState = true;
            }

            if(curState !== false) {
                // true -> legendonly. All others toggle to true:
                kcont.set(fullTrace._group, visibility);
            }
            carrIdx[fullInput.index] = insertUpdate(fullInput.index, 'visible', fullInput.visible === false ? false : true);
        } else {
            // false -> false (not possible since will not be visible in legend)
            // true -> legendonly
            // legendonly -> true
            var nextVisibility = fullInput.visible === false ? false : visibility;

            insertUpdate(fullInput.index, 'visible', nextVisibility);
        }
    }

    if(numClicks === 1 && SHOWISOLATETIP && gd.data && gd._context.showTips) {
        Lib.notifier(Lib._(gd, 'Double-click on legend to isolate one trace'), 'long');
        SHOWISOLATETIP = false;
    } else {
        SHOWISOLATETIP = false;
    }

    if(Registry.traceIs(fullTrace, 'pie')) {
        var thisLabel = legendItem.label;
        var thisLabelIndex = hiddenSlices.indexOf(thisLabel);

        if(numClicks === 1) {
            if(thisLabelIndex === -1) hiddenSlices.push(thisLabel);
            else hiddenSlices.splice(thisLabelIndex, 1);
        } else if(numClicks === 2) {
            hiddenSlices = [];
            gd.calcdata[0].forEach(function(d) {
                if(thisLabel !== d.label) {
                    hiddenSlices.push(d.label);
                }
            });
            if(gd._fullLayout.hiddenlabels && gd._fullLayout.hiddenlabels.length === hiddenSlices.length && thisLabelIndex === -1) {
                hiddenSlices = [];
            }
        }

        Registry.call('_guiRelayout', gd, 'hiddenlabels', hiddenSlices);
    } else {
        var hasLegendgroup = legendgroup && legendgroup.length;
        var traceIndicesInGroup = [];
        var tracei;
        if(hasLegendgroup) {
            for(i = 0; i < fullData.length; i++) {
                tracei = fullData[i];
                if(!tracei.visible) continue;
                if(tracei.legendgroup === legendgroup) {
                    traceIndicesInGroup.push(i);
                }
            }
        }

        if(numClicks === 1) {
            var nextVisibility;

            switch(fullTrace.visible) {
                case true:
                    nextVisibility = 'legendonly';
                    break;
                case false:
                    nextVisibility = false;
                    break;
                case 'legendonly':
                    nextVisibility = true;
                    break;
            }

            if(hasLegendgroup) {
                for(i = 0; i < fullData.length; i++) {
                    if(fullData[i].visible !== false && fullData[i].legendgroup === legendgroup) {
                        setVisibility(fullData[i], nextVisibility);
                    }
                }
            } else {
                setVisibility(fullTrace, nextVisibility);
            }
        } else if(numClicks === 2) {
            // Compute the clicked index. expandedIndex does what we want for expanded traces
            // but also culls hidden traces. That means we have some work to do.
            var isClicked, isInGroup, otherState;
            var isIsolated = true;
            for(i = 0; i < fullData.length; i++) {
                isClicked = fullData[i] === fullTrace;
                if(isClicked) continue;

                isInGroup = (hasLegendgroup && fullData[i].legendgroup === legendgroup);

                if(!isInGroup && fullData[i].visible === true && !Registry.traceIs(fullData[i], 'notLegendIsolatable')) {
                    isIsolated = false;
                    break;
                }
            }

            for(i = 0; i < fullData.length; i++) {
                // False is sticky; we don't change it.
                if(fullData[i].visible === false) continue;

                if(Registry.traceIs(fullData[i], 'notLegendIsolatable')) {
                    continue;
                }

                switch(fullTrace.visible) {
                    case 'legendonly':
                        setVisibility(fullData[i], true);
                        break;
                    case true:
                        otherState = isIsolated ? true : 'legendonly';
                        isClicked = fullData[i] === fullTrace;
                        isInGroup = isClicked || (hasLegendgroup && fullData[i].legendgroup === legendgroup);
                        setVisibility(fullData[i], isInGroup ? true : otherState);
                        break;
                }
            }
        }

        for(i = 0; i < carrs.length; i++) {
            kcont = carrs[i];
            if(!kcont) continue;
            var update = kcont.constructUpdate();

            var updateKeys = Object.keys(update);
            for(j = 0; j < updateKeys.length; j++) {
                key = updateKeys[j];
                val = attrUpdate[key] = attrUpdate[key] || [];
                val[carrIdx[i]] = update[key];
            }
        }

        // The length of the value arrays should be equal and any unspecified
        // values should be explicitly undefined for them to get properly culled
        // as updates and not accidentally reset to the default value. This fills
        // out sparse arrays with the required number of undefined values:
        keys = Object.keys(attrUpdate);
        for(i = 0; i < keys.length; i++) {
            key = keys[i];
            for(j = 0; j < attrIndices.length; j++) {
                // Use hasOwnPropety to protect against falsey values:
                if(!attrUpdate[key].hasOwnProperty(j)) {
                    attrUpdate[key][j] = undefined;
                }
            }
        }

        Registry.call('_guiRestyle', gd, attrUpdate, attrIndices);
    }
};

},{"../../lib":697,"../../registry":826}],629:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

exports.isGrouped = function isGrouped(legendLayout) {
    return (legendLayout.traceorder || '').indexOf('grouped') !== -1;
};

exports.isVertical = function isVertical(legendLayout) {
    return legendLayout.orientation !== 'h';
};

exports.isReversed = function isReversed(legendLayout) {
    return (legendLayout.traceorder || '').indexOf('reversed') !== -1;
};

},{}],630:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


module.exports = {
    moduleType: 'component',
    name: 'legend',

    layoutAttributes: _dereq_('./attributes'),
    supplyLayoutDefaults: _dereq_('./defaults'),

    draw: _dereq_('./draw'),
    style: _dereq_('./style')
};

},{"./attributes":623,"./defaults":625,"./draw":626,"./style":631}],631:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Drawing = _dereq_('../drawing');
var Color = _dereq_('../color');

var subTypes = _dereq_('../../traces/scatter/subtypes');
var stylePie = _dereq_('../../traces/pie/style_one');

module.exports = function style(s, gd) {
    s.each(function(d) {
        var traceGroup = d3.select(this);

        var layers = Lib.ensureSingle(traceGroup, 'g', 'layers');
        layers.style('opacity', d[0].trace.opacity);

        // Marker vertical alignment
        var valign = gd._fullLayout.legend.valign;
        var lineHeight = d[0].lineHeight;
        var height = d[0].height;

        if(valign === 'middle' || !lineHeight || !height) {
            layers.attr('transform', null);
        } else {
            var factor = {top: 1, bottom: -1}[valign];
            var markerOffsetY = factor * (0.5 * (lineHeight - height + 3));
            layers.attr('transform', 'translate(0,' + markerOffsetY + ')');
        }

        var fill = layers
            .selectAll('g.legendfill')
                .data([d]);
        fill.enter().append('g')
            .classed('legendfill', true);

        var line = layers
            .selectAll('g.legendlines')
                .data([d]);
        line.enter().append('g')
            .classed('legendlines', true);

        var symbol = layers
            .selectAll('g.legendsymbols')
                .data([d]);
        symbol.enter().append('g')
            .classed('legendsymbols', true);

        symbol.selectAll('g.legendpoints')
            .data([d])
          .enter().append('g')
            .classed('legendpoints', true);
    })
    .each(styleBars)
    .each(styleBoxes)
    .each(stylePies)
    .each(styleLines)
    .each(stylePoints)
    .each(styleCandles)
    .each(styleOHLC);

    function styleLines(d) {
        var trace = d[0].trace;
        var showFill = trace.visible && trace.fill && trace.fill !== 'none';
        var showLine = subTypes.hasLines(trace);
        var contours = trace.contours;
        var showGradientLine = false;
        var showGradientFill = false;

        if(contours) {
            var coloring = contours.coloring;

            if(coloring === 'lines') {
                showGradientLine = true;
            }
            else {
                showLine = coloring === 'none' || coloring === 'heatmap' ||
                    contours.showlines;
            }

            if(contours.type === 'constraint') {
                showFill = contours._operation !== '=';
            }
            else if(coloring === 'fill' || coloring === 'heatmap') {
                showGradientFill = true;
            }
        }

        // with fill and no markers or text, move the line and fill up a bit
        // so it's more centered
        var markersOrText = subTypes.hasMarkers(trace) || subTypes.hasText(trace);
        var anyFill = showFill || showGradientFill;
        var anyLine = showLine || showGradientLine;
        var pathStart = (markersOrText || !anyFill) ? 'M5,0' :
            // with a line leave it slightly below center, to leave room for the
            // line thickness and because the line is usually more prominent
            anyLine ? 'M5,-2' : 'M5,-3';

        var this3 = d3.select(this);

        var fill = this3.select('.legendfill').selectAll('path')
            .data(showFill || showGradientFill ? [d] : []);
        fill.enter().append('path').classed('js-fill', true);
        fill.exit().remove();
        fill.attr('d', pathStart + 'h30v6h-30z')
            .call(showFill ? Drawing.fillGroupStyle : fillGradient);

        var line = this3.select('.legendlines').selectAll('path')
            .data(showLine || showGradientLine ? [d] : []);
        line.enter().append('path').classed('js-line', true);
        line.exit().remove();

        // this is ugly... but you can't apply a gradient to a perfectly
        // horizontal or vertical line. Presumably because then
        // the system doesn't know how to scale vertical variation, even
        // though there *is* no vertical variation in this case.
        // so add an invisibly small angle to the line
        // This issue (and workaround) exist across (Mac) Chrome, FF, and Safari
        line.attr('d', pathStart + (showGradientLine ? 'l30,0.0001' : 'h30'))
            .call(showLine ? Drawing.lineGroupStyle : lineGradient);

        function fillGradient(s) {
            if(s.size()) {
                var gradientID = 'legendfill-' + trace.uid;
                Drawing.gradient(s, gd, gradientID, 'horizontalreversed',
                    trace.colorscale, 'fill');
            }
        }

        function lineGradient(s) {
            if(s.size()) {
                var gradientID = 'legendline-' + trace.uid;
                Drawing.lineGroupStyle(s);
                Drawing.gradient(s, gd, gradientID, 'horizontalreversed',
                    trace.colorscale, 'stroke');
            }
        }

    }

    function stylePoints(d) {
        var d0 = d[0];
        var trace = d0.trace;
        var showMarkers = subTypes.hasMarkers(trace);
        var showText = subTypes.hasText(trace);
        var showLines = subTypes.hasLines(trace);
        var dMod, tMod;

        // 'scatter3d' don't use gd.calcdata,
        // use d0.trace to infer arrayOk attributes

        function boundVal(attrIn, arrayToValFn, bounds) {
            var valIn = Lib.nestedProperty(trace, attrIn).get();
            var valToBound = (Lib.isArrayOrTypedArray(valIn) && arrayToValFn) ?
                arrayToValFn(valIn) :
                valIn;

            if(bounds) {
                if(valToBound < bounds[0]) return bounds[0];
                else if(valToBound > bounds[1]) return bounds[1];
            }
            return valToBound;
        }

        function pickFirst(array) { return array[0]; }

        // constrain text, markers, etc so they'll fit on the legend
        if(showMarkers || showText || showLines) {
            var dEdit = {};
            var tEdit = {};

            if(showMarkers) {
                dEdit.mc = boundVal('marker.color', pickFirst);
                dEdit.mx = boundVal('marker.symbol', pickFirst);
                dEdit.mo = boundVal('marker.opacity', Lib.mean, [0.2, 1]);
                dEdit.mlc = boundVal('marker.line.color', pickFirst);
                dEdit.mlw = boundVal('marker.line.width', Lib.mean, [0, 5]);
                tEdit.marker = {
                    sizeref: 1,
                    sizemin: 1,
                    sizemode: 'diameter'
                };

                var ms = boundVal('marker.size', Lib.mean, [2, 16]);
                dEdit.ms = ms;
                tEdit.marker.size = ms;
            }

            if(showLines) {
                tEdit.line = {
                    width: boundVal('line.width', pickFirst, [0, 10])
                };
            }

            if(showText) {
                dEdit.tx = 'Aa';
                dEdit.tp = boundVal('textposition', pickFirst);
                dEdit.ts = 10;
                dEdit.tc = boundVal('textfont.color', pickFirst);
                dEdit.tf = boundVal('textfont.family', pickFirst);
            }

            dMod = [Lib.minExtend(d0, dEdit)];
            tMod = Lib.minExtend(trace, tEdit);

            // always show legend items in base state
            tMod.selectedpoints = null;
        }

        var ptgroup = d3.select(this).select('g.legendpoints');

        var pts = ptgroup.selectAll('path.scatterpts')
            .data(showMarkers ? dMod : []);
        // make sure marker is on the bottom, in case it enters after text
        pts.enter().insert('path', ':first-child')
            .classed('scatterpts', true)
            .attr('transform', 'translate(20,0)');
        pts.exit().remove();
        pts.call(Drawing.pointStyle, tMod, gd);

        // 'mrc' is set in pointStyle and used in textPointStyle:
        // constrain it here
        if(showMarkers) dMod[0].mrc = 3;

        var txt = ptgroup.selectAll('g.pointtext')
            .data(showText ? dMod : []);
        txt.enter()
            .append('g').classed('pointtext', true)
                .append('text').attr('transform', 'translate(20,0)');
        txt.exit().remove();
        txt.selectAll('text').call(Drawing.textPointStyle, tMod, gd);
    }

    function styleBars(d) {
        var trace = d[0].trace;
        var marker = trace.marker || {};
        var markerLine = marker.line || {};

        var barpath = d3.select(this).select('g.legendpoints')
            .selectAll('path.legendbar')
            .data(Registry.traceIs(trace, 'bar') ? [d] : []);
        barpath.enter().append('path').classed('legendbar', true)
            .attr('d', 'M6,6H-6V-6H6Z')
            .attr('transform', 'translate(20,0)');
        barpath.exit().remove();

        barpath.each(function(d) {
            var p = d3.select(this);
            var d0 = d[0];
            var w = (d0.mlw + 1 || markerLine.width + 1) - 1;

            p.style('stroke-width', w + 'px')
                .call(Color.fill, d0.mc || marker.color);

            if(w) {
                p.call(Color.stroke, d0.mlc || markerLine.color);
            }
        });
    }

    function styleBoxes(d) {
        var trace = d[0].trace;

        var pts = d3.select(this).select('g.legendpoints')
            .selectAll('path.legendbox')
            .data(Registry.traceIs(trace, 'box-violin') && trace.visible ? [d] : []);
        pts.enter().append('path').classed('legendbox', true)
            // if we want the median bar, prepend M6,0H-6
            .attr('d', 'M6,6H-6V-6H6Z')
            .attr('transform', 'translate(20,0)');
        pts.exit().remove();

        pts.each(function() {
            var w = trace.line.width;
            var p = d3.select(this);

            p.style('stroke-width', w + 'px')
                .call(Color.fill, trace.fillcolor);

            if(w) {
                Color.stroke(p, trace.line.color);
            }
        });
    }

    function styleCandles(d) {
        var trace = d[0].trace;

        var pts = d3.select(this).select('g.legendpoints')
            .selectAll('path.legendcandle')
            .data(trace.type === 'candlestick' && trace.visible ? [d, d] : []);
        pts.enter().append('path').classed('legendcandle', true)
            .attr('d', function(_, i) {
                if(i) return 'M-15,0H-8M-8,6V-6H8Z'; // increasing
                return 'M15,0H8M8,-6V6H-8Z'; // decreasing
            })
            .attr('transform', 'translate(20,0)')
            .style('stroke-miterlimit', 1);
        pts.exit().remove();

        pts.each(function(_, i) {
            var container = trace[i ? 'increasing' : 'decreasing'];
            var w = container.line.width;
            var p = d3.select(this);

            p.style('stroke-width', w + 'px')
                .call(Color.fill, container.fillcolor);

            if(w) {
                Color.stroke(p, container.line.color);
            }
        });
    }

    function styleOHLC(d) {
        var trace = d[0].trace;

        var pts = d3.select(this).select('g.legendpoints')
            .selectAll('path.legendohlc')
            .data(trace.type === 'ohlc' && trace.visible ? [d, d] : []);
        pts.enter().append('path').classed('legendohlc', true)
            .attr('d', function(_, i) {
                if(i) return 'M-15,0H0M-8,-6V0'; // increasing
                return 'M15,0H0M8,6V0'; // decreasing
            })
            .attr('transform', 'translate(20,0)')
            .style('stroke-miterlimit', 1);
        pts.exit().remove();

        pts.each(function(_, i) {
            var container = trace[i ? 'increasing' : 'decreasing'];
            var w = container.line.width;
            var p = d3.select(this);

            p.style('fill', 'none')
                .call(Drawing.dashLine, container.line.dash, w);

            if(w) {
                Color.stroke(p, container.line.color);
            }
        });
    }

    function stylePies(d) {
        var trace = d[0].trace;

        var pts = d3.select(this).select('g.legendpoints')
            .selectAll('path.legendpie')
            .data(Registry.traceIs(trace, 'pie') && trace.visible ? [d] : []);
        pts.enter().append('path').classed('legendpie', true)
            .attr('d', 'M6,6H-6V-6H6Z')
            .attr('transform', 'translate(20,0)');
        pts.exit().remove();

        if(pts.size()) pts.call(stylePie, d[0], trace);
    }
};

},{"../../lib":697,"../../registry":826,"../../traces/pie/style_one":1034,"../../traces/scatter/subtypes":1072,"../color":574,"../drawing":595,"d3":151}],632:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../../registry');
var Plots = _dereq_('../../plots/plots');
var axisIds = _dereq_('../../plots/cartesian/axis_ids');
var Lib = _dereq_('../../lib');
var Icons = _dereq_('../../../build/ploticon');

var _ = Lib._;

var modeBarButtons = module.exports = {};

/**
 * ModeBar buttons configuration
 *
 * @param {string} name
 *      name / id of the buttons (for tracking)
 * @param {string} title
 *      text that appears while hovering over the button,
 *      enter null, false or '' for no hover text
 * @param {string} icon
 *      svg icon object associated with the button
 *      can be linked to Plotly.Icons to use the default plotly icons
 * @param {string} [gravity]
 *      icon positioning
 * @param {function} click
 *      click handler associated with the button, a function of
 *      'gd' (the main graph object) and
 *      'ev' (the event object)
 * @param {string} [attr]
 *      attribute associated with button,
 *      use this with 'val' to keep track of the state
 * @param {*} [val]
 *      initial 'attr' value, can be a function of gd
 * @param {boolean} [toggle]
 *      is the button a toggle button?
 */

modeBarButtons.toImage = {
    name: 'toImage',
    title: function(gd) {
        var opts = gd._context.toImageButtonOptions || {};
        var format = opts.format || 'png';
        return format === 'png' ?
            _(gd, 'Download plot as a png') : // legacy text
            _(gd, 'Download plot'); // generic non-PNG text
    },
    icon: Icons.camera,
    click: function(gd) {
        var toImageButtonOptions = gd._context.toImageButtonOptions;
        var opts = {format: toImageButtonOptions.format || 'png'};

        Lib.notifier(_(gd, 'Taking snapshot - this may take a few seconds'), 'long');

        if(opts.format !== 'svg' && Lib.isIE()) {
            Lib.notifier(_(gd, 'IE only supports svg.  Changing format to svg.'), 'long');
            opts.format = 'svg';
        }

        ['filename', 'width', 'height', 'scale'].forEach(function(key) {
            if(toImageButtonOptions[key]) {
                opts[key] = toImageButtonOptions[key];
            }
        });

        Registry.call('downloadImage', gd, opts)
          .then(function(filename) {
              Lib.notifier(_(gd, 'Snapshot succeeded') + ' - ' + filename, 'long');
          })
          .catch(function() {
              Lib.notifier(_(gd, 'Sorry, there was a problem downloading your snapshot!'), 'long');
          });
    }
};

modeBarButtons.sendDataToCloud = {
    name: 'sendDataToCloud',
    title: function(gd) { return _(gd, 'Edit in Chart Studio'); },
    icon: Icons.disk,
    click: function(gd) {
        Plots.sendDataToCloud(gd);
    }
};

modeBarButtons.zoom2d = {
    name: 'zoom2d',
    title: function(gd) { return _(gd, 'Zoom'); },
    attr: 'dragmode',
    val: 'zoom',
    icon: Icons.zoombox,
    click: handleCartesian
};

modeBarButtons.pan2d = {
    name: 'pan2d',
    title: function(gd) { return _(gd, 'Pan'); },
    attr: 'dragmode',
    val: 'pan',
    icon: Icons.pan,
    click: handleCartesian
};

modeBarButtons.select2d = {
    name: 'select2d',
    title: function(gd) { return _(gd, 'Box Select'); },
    attr: 'dragmode',
    val: 'select',
    icon: Icons.selectbox,
    click: handleCartesian
};

modeBarButtons.lasso2d = {
    name: 'lasso2d',
    title: function(gd) { return _(gd, 'Lasso Select'); },
    attr: 'dragmode',
    val: 'lasso',
    icon: Icons.lasso,
    click: handleCartesian
};

modeBarButtons.zoomIn2d = {
    name: 'zoomIn2d',
    title: function(gd) { return _(gd, 'Zoom in'); },
    attr: 'zoom',
    val: 'in',
    icon: Icons.zoom_plus,
    click: handleCartesian
};

modeBarButtons.zoomOut2d = {
    name: 'zoomOut2d',
    title: function(gd) { return _(gd, 'Zoom out'); },
    attr: 'zoom',
    val: 'out',
    icon: Icons.zoom_minus,
    click: handleCartesian
};

modeBarButtons.autoScale2d = {
    name: 'autoScale2d',
    title: function(gd) { return _(gd, 'Autoscale'); },
    attr: 'zoom',
    val: 'auto',
    icon: Icons.autoscale,
    click: handleCartesian
};

modeBarButtons.resetScale2d = {
    name: 'resetScale2d',
    title: function(gd) { return _(gd, 'Reset axes'); },
    attr: 'zoom',
    val: 'reset',
    icon: Icons.home,
    click: handleCartesian
};

modeBarButtons.hoverClosestCartesian = {
    name: 'hoverClosestCartesian',
    title: function(gd) { return _(gd, 'Show closest data on hover'); },
    attr: 'hovermode',
    val: 'closest',
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: handleCartesian
};

modeBarButtons.hoverCompareCartesian = {
    name: 'hoverCompareCartesian',
    title: function(gd) { return _(gd, 'Compare data on hover'); },
    attr: 'hovermode',
    val: function(gd) {
        return gd._fullLayout._isHoriz ? 'y' : 'x';
    },
    icon: Icons.tooltip_compare,
    gravity: 'ne',
    click: handleCartesian
};

function handleCartesian(gd, ev) {
    var button = ev.currentTarget;
    var astr = button.getAttribute('data-attr');
    var val = button.getAttribute('data-val') || true;
    var fullLayout = gd._fullLayout;
    var aobj = {};
    var axList = axisIds.list(gd, null, true);
    var allSpikesEnabled = 'on';

    var ax, i;

    if(astr === 'zoom') {
        var mag = (val === 'in') ? 0.5 : 2;
        var r0 = (1 + mag) / 2;
        var r1 = (1 - mag) / 2;
        var axName;

        for(i = 0; i < axList.length; i++) {
            ax = axList[i];

            if(!ax.fixedrange) {
                axName = ax._name;
                if(val === 'auto') aobj[axName + '.autorange'] = true;
                else if(val === 'reset') {
                    if(ax._rangeInitial === undefined) {
                        aobj[axName + '.autorange'] = true;
                    }
                    else {
                        var rangeInitial = ax._rangeInitial.slice();
                        aobj[axName + '.range[0]'] = rangeInitial[0];
                        aobj[axName + '.range[1]'] = rangeInitial[1];
                    }
                    if(ax._showSpikeInitial !== undefined) {
                        aobj[axName + '.showspikes'] = ax._showSpikeInitial;
                        if(allSpikesEnabled === 'on' && !ax._showSpikeInitial) {
                            allSpikesEnabled = 'off';
                        }
                    }
                }
                else {
                    var rangeNow = [
                        ax.r2l(ax.range[0]),
                        ax.r2l(ax.range[1]),
                    ];

                    var rangeNew = [
                        r0 * rangeNow[0] + r1 * rangeNow[1],
                        r0 * rangeNow[1] + r1 * rangeNow[0]
                    ];

                    aobj[axName + '.range[0]'] = ax.l2r(rangeNew[0]);
                    aobj[axName + '.range[1]'] = ax.l2r(rangeNew[1]);
                }
            }
        }
        fullLayout._cartesianSpikesEnabled = allSpikesEnabled;
    }
    else {
        // if ALL traces have orientation 'h', 'hovermode': 'x' otherwise: 'y'
        if(astr === 'hovermode' && (val === 'x' || val === 'y')) {
            val = fullLayout._isHoriz ? 'y' : 'x';
            button.setAttribute('data-val', val);
        } else if(astr === 'hovermode' && val === 'closest') {
            for(i = 0; i < axList.length; i++) {
                ax = axList[i];
                if(allSpikesEnabled === 'on' && !ax.showspikes) {
                    allSpikesEnabled = 'off';
                }
            }
            fullLayout._cartesianSpikesEnabled = allSpikesEnabled;
        }

        aobj[astr] = val;
    }

    Registry.call('_guiRelayout', gd, aobj);
}

modeBarButtons.zoom3d = {
    name: 'zoom3d',
    title: function(gd) { return _(gd, 'Zoom'); },
    attr: 'scene.dragmode',
    val: 'zoom',
    icon: Icons.zoombox,
    click: handleDrag3d
};

modeBarButtons.pan3d = {
    name: 'pan3d',
    title: function(gd) { return _(gd, 'Pan'); },
    attr: 'scene.dragmode',
    val: 'pan',
    icon: Icons.pan,
    click: handleDrag3d
};

modeBarButtons.orbitRotation = {
    name: 'orbitRotation',
    title: function(gd) { return _(gd, 'Orbital rotation'); },
    attr: 'scene.dragmode',
    val: 'orbit',
    icon: Icons['3d_rotate'],
    click: handleDrag3d
};

modeBarButtons.tableRotation = {
    name: 'tableRotation',
    title: function(gd) { return _(gd, 'Turntable rotation'); },
    attr: 'scene.dragmode',
    val: 'turntable',
    icon: Icons['z-axis'],
    click: handleDrag3d
};

function handleDrag3d(gd, ev) {
    var button = ev.currentTarget;
    var attr = button.getAttribute('data-attr');
    var val = button.getAttribute('data-val') || true;
    var sceneIds = gd._fullLayout._subplots.gl3d;
    var layoutUpdate = {};

    var parts = attr.split('.');

    for(var i = 0; i < sceneIds.length; i++) {
        layoutUpdate[sceneIds[i] + '.' + parts[1]] = val;
    }

    // for multi-type subplots
    var val2d = (val === 'pan') ? val : 'zoom';
    layoutUpdate.dragmode = val2d;

    Registry.call('_guiRelayout', gd, layoutUpdate);
}

modeBarButtons.resetCameraDefault3d = {
    name: 'resetCameraDefault3d',
    title: function(gd) { return _(gd, 'Reset camera to default'); },
    attr: 'resetDefault',
    icon: Icons.home,
    click: handleCamera3d
};

modeBarButtons.resetCameraLastSave3d = {
    name: 'resetCameraLastSave3d',
    title: function(gd) { return _(gd, 'Reset camera to last save'); },
    attr: 'resetLastSave',
    icon: Icons.movie,
    click: handleCamera3d
};

function handleCamera3d(gd, ev) {
    var button = ev.currentTarget;
    var attr = button.getAttribute('data-attr');
    var fullLayout = gd._fullLayout;
    var sceneIds = fullLayout._subplots.gl3d;
    var aobj = {};

    for(var i = 0; i < sceneIds.length; i++) {
        var sceneId = sceneIds[i];
        var key = sceneId + '.camera';
        var scene = fullLayout[sceneId]._scene;

        if(attr === 'resetLastSave') {
            aobj[key + '.up'] = scene.viewInitial.up;
            aobj[key + '.eye'] = scene.viewInitial.eye;
            aobj[key + '.center'] = scene.viewInitial.center;
        } else if(attr === 'resetDefault') {
            aobj[key + '.up'] = null;
            aobj[key + '.eye'] = null;
            aobj[key + '.center'] = null;
        }
    }

    Registry.call('_guiRelayout', gd, aobj);
}

modeBarButtons.hoverClosest3d = {
    name: 'hoverClosest3d',
    title: function(gd) { return _(gd, 'Toggle show closest data on hover'); },
    attr: 'hovermode',
    val: null,
    toggle: true,
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: handleHover3d
};

function getNextHover3d(gd, ev) {
    var button = ev.currentTarget;
    var val = button._previousVal;
    var fullLayout = gd._fullLayout;
    var sceneIds = fullLayout._subplots.gl3d;

    var axes = ['xaxis', 'yaxis', 'zaxis'];

    // initialize 'current spike' object to be stored in the DOM
    var currentSpikes = {};
    var layoutUpdate = {};

    if(val) {
        layoutUpdate = val;
        button._previousVal = null;
    }
    else {
        for(var i = 0; i < sceneIds.length; i++) {
            var sceneId = sceneIds[i];
            var sceneLayout = fullLayout[sceneId];

            var hovermodeAStr = sceneId + '.hovermode';
            currentSpikes[hovermodeAStr] = sceneLayout.hovermode;
            layoutUpdate[hovermodeAStr] = false;

            // copy all the current spike attrs
            for(var j = 0; j < 3; j++) {
                var axis = axes[j];
                var spikeAStr = sceneId + '.' + axis + '.showspikes';
                layoutUpdate[spikeAStr] = false;
                currentSpikes[spikeAStr] = sceneLayout[axis].showspikes;
            }
        }

        button._previousVal = currentSpikes;
    }
    return layoutUpdate;
}

function handleHover3d(gd, ev) {
    var layoutUpdate = getNextHover3d(gd, ev);
    Registry.call('_guiRelayout', gd, layoutUpdate);
}

modeBarButtons.zoomInGeo = {
    name: 'zoomInGeo',
    title: function(gd) { return _(gd, 'Zoom in'); },
    attr: 'zoom',
    val: 'in',
    icon: Icons.zoom_plus,
    click: handleGeo
};

modeBarButtons.zoomOutGeo = {
    name: 'zoomOutGeo',
    title: function(gd) { return _(gd, 'Zoom out'); },
    attr: 'zoom',
    val: 'out',
    icon: Icons.zoom_minus,
    click: handleGeo
};

modeBarButtons.resetGeo = {
    name: 'resetGeo',
    title: function(gd) { return _(gd, 'Reset'); },
    attr: 'reset',
    val: null,
    icon: Icons.autoscale,
    click: handleGeo
};

modeBarButtons.hoverClosestGeo = {
    name: 'hoverClosestGeo',
    title: function(gd) { return _(gd, 'Toggle show closest data on hover'); },
    attr: 'hovermode',
    val: null,
    toggle: true,
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: toggleHover
};

function handleGeo(gd, ev) {
    var button = ev.currentTarget;
    var attr = button.getAttribute('data-attr');
    var val = button.getAttribute('data-val') || true;
    var fullLayout = gd._fullLayout;
    var geoIds = fullLayout._subplots.geo;

    for(var i = 0; i < geoIds.length; i++) {
        var id = geoIds[i];
        var geoLayout = fullLayout[id];

        if(attr === 'zoom') {
            var scale = geoLayout.projection.scale;
            var newScale = (val === 'in') ? 2 * scale : 0.5 * scale;

            Registry.call('_guiRelayout', gd, id + '.projection.scale', newScale);
        } else if(attr === 'reset') {
            resetView(gd, 'geo');
        }
    }
}

modeBarButtons.hoverClosestGl2d = {
    name: 'hoverClosestGl2d',
    title: function(gd) { return _(gd, 'Toggle show closest data on hover'); },
    attr: 'hovermode',
    val: null,
    toggle: true,
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: toggleHover
};

modeBarButtons.hoverClosestPie = {
    name: 'hoverClosestPie',
    title: function(gd) { return _(gd, 'Toggle show closest data on hover'); },
    attr: 'hovermode',
    val: 'closest',
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: toggleHover
};

function getNextHover(gd) {
    var fullLayout = gd._fullLayout;

    if(fullLayout.hovermode) return false;

    if(fullLayout._has('cartesian')) {
        return fullLayout._isHoriz ? 'y' : 'x';
    }
    return 'closest';
}

function toggleHover(gd) {
    var newHover = getNextHover(gd);
    Registry.call('_guiRelayout', gd, 'hovermode', newHover);
}

// buttons when more then one plot types are present

modeBarButtons.toggleHover = {
    name: 'toggleHover',
    title: function(gd) { return _(gd, 'Toggle show closest data on hover'); },
    attr: 'hovermode',
    val: null,
    toggle: true,
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: function(gd, ev) {
        var layoutUpdate = getNextHover3d(gd, ev);
        layoutUpdate.hovermode = getNextHover(gd);

        Registry.call('_guiRelayout', gd, layoutUpdate);
    }
};

modeBarButtons.resetViews = {
    name: 'resetViews',
    title: function(gd) { return _(gd, 'Reset views'); },
    icon: Icons.home,
    click: function(gd, ev) {
        var button = ev.currentTarget;

        button.setAttribute('data-attr', 'zoom');
        button.setAttribute('data-val', 'reset');
        handleCartesian(gd, ev);

        button.setAttribute('data-attr', 'resetLastSave');
        handleCamera3d(gd, ev);

        resetView(gd, 'geo');
        resetView(gd, 'mapbox');
    }
};

modeBarButtons.toggleSpikelines = {
    name: 'toggleSpikelines',
    title: function(gd) { return _(gd, 'Toggle Spike Lines'); },
    icon: Icons.spikeline,
    attr: '_cartesianSpikesEnabled',
    val: 'on',
    click: function(gd) {
        var fullLayout = gd._fullLayout;

        fullLayout._cartesianSpikesEnabled = fullLayout._cartesianSpikesEnabled === 'on' ? 'off' : 'on';

        var aobj = setSpikelineVisibility(gd);

        Registry.call('_guiRelayout', gd, aobj);
    }
};

function setSpikelineVisibility(gd) {
    var fullLayout = gd._fullLayout;
    var axList = axisIds.list(gd, null, true);
    var aobj = {};

    var ax, axName;

    for(var i = 0; i < axList.length; i++) {
        ax = axList[i];
        axName = ax._name;
        aobj[axName + '.showspikes'] = fullLayout._cartesianSpikesEnabled === 'on' ? true : ax._showSpikeInitial;
    }

    return aobj;
}

modeBarButtons.resetViewMapbox = {
    name: 'resetViewMapbox',
    title: function(gd) { return _(gd, 'Reset view'); },
    attr: 'reset',
    icon: Icons.home,
    click: function(gd) {
        resetView(gd, 'mapbox');
    }
};

function resetView(gd, subplotType) {
    var fullLayout = gd._fullLayout;
    var subplotIds = fullLayout._subplots[subplotType];
    var aObj = {};

    for(var i = 0; i < subplotIds.length; i++) {
        var id = subplotIds[i];
        var subplotObj = fullLayout[id]._subplot;
        var viewInitial = subplotObj.viewInitial;
        var viewKeys = Object.keys(viewInitial);

        for(var j = 0; j < viewKeys.length; j++) {
            var key = viewKeys[j];
            aObj[id + '.' + key] = viewInitial[key];
        }
    }

    Registry.call('_guiRelayout', gd, aObj);
}

},{"../../../build/ploticon":2,"../../lib":697,"../../plots/cartesian/axis_ids":748,"../../plots/plots":807,"../../registry":826}],633:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

exports.manage = _dereq_('./manage');

},{"./manage":634}],634:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var axisIds = _dereq_('../../plots/cartesian/axis_ids');
var scatterSubTypes = _dereq_('../../traces/scatter/subtypes');
var Registry = _dereq_('../../registry');

var createModeBar = _dereq_('./modebar');
var modeBarButtons = _dereq_('./buttons');

/**
 * ModeBar wrapper around 'create' and 'update',
 * chooses buttons to pass to ModeBar constructor based on
 * plot type and plot config.
 *
 * @param {object} gd main plot object
 *
 */
module.exports = function manageModeBar(gd) {
    var fullLayout = gd._fullLayout;
    var context = gd._context;
    var modeBar = fullLayout._modeBar;

    if(!context.displayModeBar && !context.watermark) {
        if(modeBar) {
            modeBar.destroy();
            delete fullLayout._modeBar;
        }
        return;
    }

    if(!Array.isArray(context.modeBarButtonsToRemove)) {
        throw new Error([
            '*modeBarButtonsToRemove* configuration options',
            'must be an array.'
        ].join(' '));
    }

    if(!Array.isArray(context.modeBarButtonsToAdd)) {
        throw new Error([
            '*modeBarButtonsToAdd* configuration options',
            'must be an array.'
        ].join(' '));
    }

    var customButtons = context.modeBarButtons;
    var buttonGroups;

    if(Array.isArray(customButtons) && customButtons.length) {
        buttonGroups = fillCustomButton(customButtons);
    }
    else if(!context.displayModeBar && context.watermark) {
        buttonGroups = [];
    }
    else {
        buttonGroups = getButtonGroups(
            gd,
            context.modeBarButtonsToRemove,
            context.modeBarButtonsToAdd,
            context.showSendToCloud
        );
    }

    if(modeBar) modeBar.update(gd, buttonGroups);
    else fullLayout._modeBar = createModeBar(gd, buttonGroups);
};

// logic behind which buttons are displayed by default
function getButtonGroups(gd, buttonsToRemove, buttonsToAdd, showSendToCloud) {
    var fullLayout = gd._fullLayout;
    var fullData = gd._fullData;

    var hasCartesian = fullLayout._has('cartesian');
    var hasGL3D = fullLayout._has('gl3d');
    var hasGeo = fullLayout._has('geo');
    var hasPie = fullLayout._has('pie');
    var hasGL2D = fullLayout._has('gl2d');
    var hasTernary = fullLayout._has('ternary');
    var hasMapbox = fullLayout._has('mapbox');
    var hasPolar = fullLayout._has('polar');
    var allAxesFixed = areAllAxesFixed(fullLayout);

    var groups = [];

    function addGroup(newGroup) {
        if(!newGroup.length) return;

        var out = [];

        for(var i = 0; i < newGroup.length; i++) {
            var button = newGroup[i];
            if(buttonsToRemove.indexOf(button) !== -1) continue;
            out.push(modeBarButtons[button]);
        }

        groups.push(out);
    }

    // buttons common to all plot types
    var commonGroup = ['toImage'];
    if(showSendToCloud) commonGroup.push('sendDataToCloud');
    addGroup(commonGroup);

    var zoomGroup = [];
    var hoverGroup = [];
    var resetGroup = [];
    var dragModeGroup = [];

    if((hasCartesian || hasGL2D || hasPie || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasPolar > 1) {
        // graphs with more than one plot types get 'union buttons'
        // which reset the view or toggle hover labels across all subplots.
        hoverGroup = ['toggleHover'];
        resetGroup = ['resetViews'];
    }
    else if(hasGeo) {
        zoomGroup = ['zoomInGeo', 'zoomOutGeo'];
        hoverGroup = ['hoverClosestGeo'];
        resetGroup = ['resetGeo'];
    }
    else if(hasGL3D) {
        hoverGroup = ['hoverClosest3d'];
        resetGroup = ['resetCameraDefault3d', 'resetCameraLastSave3d'];
    }
    else if(hasMapbox) {
        hoverGroup = ['toggleHover'];
        resetGroup = ['resetViewMapbox'];
    }
    else if(hasGL2D) {
        hoverGroup = ['hoverClosestGl2d'];
    }
    else if(hasPie) {
        hoverGroup = ['hoverClosestPie'];
    }
    else { // hasPolar, hasTernary
        // always show at least one hover icon.
        hoverGroup = ['toggleHover'];
    }
    // if we have cartesian, allow switching between closest and compare
    // regardless of what other types are on the plot, since they'll all
    // just treat any truthy hovermode as 'closest'
    if(hasCartesian) {
        hoverGroup = ['toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian'];
    }

    if((hasCartesian || hasGL2D) && !allAxesFixed) {
        zoomGroup = ['zoomIn2d', 'zoomOut2d', 'autoScale2d'];
        if(resetGroup[0] !== 'resetViews') resetGroup = ['resetScale2d'];
    }

    if(hasGL3D) {
        dragModeGroup = ['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation'];
    }
    else if(((hasCartesian || hasGL2D) && !allAxesFixed) || hasTernary) {
        dragModeGroup = ['zoom2d', 'pan2d'];
    }
    else if(hasMapbox || hasGeo) {
        dragModeGroup = ['pan2d'];
    }
    else if(hasPolar) {
        dragModeGroup = ['zoom2d'];
    }
    if(isSelectable(fullData)) {
        dragModeGroup.push('select2d', 'lasso2d');
    }

    addGroup(dragModeGroup);
    addGroup(zoomGroup.concat(resetGroup));
    addGroup(hoverGroup);

    return appendButtonsToGroups(groups, buttonsToAdd);
}

function areAllAxesFixed(fullLayout) {
    var axList = axisIds.list({_fullLayout: fullLayout}, null, true);

    for(var i = 0; i < axList.length; i++) {
        if(!axList[i].fixedrange) {
            return false;
        }
    }

    return true;
}

// look for traces that support selection
// to be updated as we add more selectPoints handlers
function isSelectable(fullData) {
    var selectable = false;

    for(var i = 0; i < fullData.length; i++) {
        if(selectable) break;

        var trace = fullData[i];

        if(!trace._module || !trace._module.selectPoints) continue;

        if(Registry.traceIs(trace, 'scatter-like')) {
            if(scatterSubTypes.hasMarkers(trace) || scatterSubTypes.hasText(trace)) {
                selectable = true;
            }
        } else if(Registry.traceIs(trace, 'box-violin')) {
            if(trace.boxpoints === 'all' || trace.points === 'all') {
                selectable = true;
            }
        }
        // assume that in general if the trace module has selectPoints,
        // then it's selectable. Scatter is an exception to this because it must
        // have markers or text, not just be a scatter type.
        else selectable = true;
    }

    return selectable;
}

function appendButtonsToGroups(groups, buttons) {
    if(buttons.length) {
        if(Array.isArray(buttons[0])) {
            for(var i = 0; i < buttons.length; i++) {
                groups.push(buttons[i]);
            }
        }
        else groups.push(buttons);
    }

    return groups;
}

// fill in custom buttons referring to default mode bar buttons
function fillCustomButton(customButtons) {
    for(var i = 0; i < customButtons.length; i++) {
        var buttonGroup = customButtons[i];

        for(var j = 0; j < buttonGroup.length; j++) {
            var button = buttonGroup[j];

            if(typeof button === 'string') {
                if(modeBarButtons[button] !== undefined) {
                    customButtons[i][j] = modeBarButtons[button];
                }
                else {
                    throw new Error([
                        '*modeBarButtons* configuration options',
                        'invalid button name'
                    ].join(' '));
                }
            }
        }
    }

    return customButtons;
}

},{"../../plots/cartesian/axis_ids":748,"../../registry":826,"../../traces/scatter/subtypes":1072,"./buttons":632,"./modebar":635}],635:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');
var Icons = _dereq_('../../../build/ploticon');
var Parser = new DOMParser();

/**
 * UI controller for interactive plots
 * @Class
 * @Param {object} opts
 * @Param {object} opts.buttons    nested arrays of grouped buttons config objects
 * @Param {object} opts.container  container div to append modeBar
 * @Param {object} opts.graphInfo  primary plot object containing data and layout
 */
function ModeBar(opts) {
    this.container = opts.container;
    this.element = document.createElement('div');

    this.update(opts.graphInfo, opts.buttons);

    this.container.appendChild(this.element);
}

var proto = ModeBar.prototype;

/**
 * Update modeBar (buttons and logo)
 *
 * @param {object} graphInfo  primary plot object containing data and layout
 * @param {array of arrays} buttons nested arrays of grouped buttons to initialize
 *
 */
proto.update = function(graphInfo, buttons) {
    this.graphInfo = graphInfo;

    var context = this.graphInfo._context;
    var fullLayout = this.graphInfo._fullLayout;
    var modeBarId = 'modebar-' + fullLayout._uid;

    this.element.setAttribute('id', modeBarId);
    this._uid = modeBarId;

    this.element.className = 'modebar';
    if(context.displayModeBar === 'hover') this.element.className += ' modebar--hover ease-bg';

    if(fullLayout.modebar.orientation === 'v') {
        this.element.className += ' vertical';
        buttons = buttons.reverse();
    }

    var style = fullLayout.modebar;
    var bgSelector = context.displayModeBar === 'hover' ? '.js-plotly-plot .plotly:hover ' : '';

    Lib.deleteRelatedStyleRule(modeBarId);
    Lib.addRelatedStyleRule(modeBarId, bgSelector + '#' + modeBarId + ' .modebar-group', 'background-color: ' + style.bgcolor);
    Lib.addRelatedStyleRule(modeBarId, '#' + modeBarId + ' .modebar-btn .icon path', 'fill: ' + style.color);
    Lib.addRelatedStyleRule(modeBarId, '#' + modeBarId + ' .modebar-btn:hover .icon path', 'fill: ' + style.activecolor);
    Lib.addRelatedStyleRule(modeBarId, '#' + modeBarId + ' .modebar-btn.active .icon path', 'fill: ' + style.activecolor);

    // if buttons or logo have changed, redraw modebar interior
    var needsNewButtons = !this.hasButtons(buttons);
    var needsNewLogo = (this.hasLogo !== context.displaylogo);
    var needsNewLocale = (this.locale !== context.locale);

    this.locale = context.locale;

    if(needsNewButtons || needsNewLogo || needsNewLocale) {
        this.removeAllButtons();

        this.updateButtons(buttons);

        if(context.watermark || context.displaylogo) {
            var logoGroup = this.getLogo();
            if(context.watermark) {
                logoGroup.className = logoGroup.className + ' watermark';
            }

            if(fullLayout.modebar.orientation === 'v') {
                this.element.insertBefore(logoGroup, this.element.childNodes[0]);
            } else {
                this.element.appendChild(logoGroup);
            }

            this.hasLogo = true;
        }
    }

    this.updateActiveButton();
};

proto.updateButtons = function(buttons) {
    var _this = this;

    this.buttons = buttons;
    this.buttonElements = [];
    this.buttonsNames = [];

    this.buttons.forEach(function(buttonGroup) {
        var group = _this.createGroup();

        buttonGroup.forEach(function(buttonConfig) {
            var buttonName = buttonConfig.name;
            if(!buttonName) {
                throw new Error('must provide button \'name\' in button config');
            }
            if(_this.buttonsNames.indexOf(buttonName) !== -1) {
                throw new Error('button name \'' + buttonName + '\' is taken');
            }
            _this.buttonsNames.push(buttonName);

            var button = _this.createButton(buttonConfig);
            _this.buttonElements.push(button);
            group.appendChild(button);
        });

        _this.element.appendChild(group);
    });
};

/**
 * Empty div for containing a group of buttons
 * @Return {HTMLelement}
 */
proto.createGroup = function() {
    var group = document.createElement('div');
    group.className = 'modebar-group';
    return group;
};

/**
 * Create a new button div and set constant and configurable attributes
 * @Param {object} config (see ./buttons.js for more info)
 * @Return {HTMLelement}
 */
proto.createButton = function(config) {
    var _this = this;
    var button = document.createElement('a');

    button.setAttribute('rel', 'tooltip');
    button.className = 'modebar-btn';

    var title = config.title;
    if(title === undefined) title = config.name;
    // for localization: allow title to be a callable that takes gd as arg
    else if(typeof title === 'function') title = title(this.graphInfo);

    if(title || title === 0) button.setAttribute('data-title', title);

    if(config.attr !== undefined) button.setAttribute('data-attr', config.attr);

    var val = config.val;
    if(val !== undefined) {
        if(typeof val === 'function') val = val(this.graphInfo);
        button.setAttribute('data-val', val);
    }

    var click = config.click;
    if(typeof click !== 'function') {
        throw new Error('must provide button \'click\' function in button config');
    }
    else {
        button.addEventListener('click', function(ev) {
            config.click(_this.graphInfo, ev);

            // only needed for 'hoverClosestGeo' which does not call relayout
            _this.updateActiveButton(ev.currentTarget);
        });
    }

    button.setAttribute('data-toggle', config.toggle || false);
    if(config.toggle) d3.select(button).classed('active', true);

    var icon = config.icon;
    if(typeof icon === 'function') {
        button.appendChild(icon());
    }
    else {
        button.appendChild(this.createIcon(icon || Icons.question));
    }
    button.setAttribute('data-gravity', config.gravity || 'n');

    return button;
};

/**
 * Add an icon to a button
 * @Param {object} thisIcon
 * @Param {number} thisIcon.width
 * @Param {string} thisIcon.path
 * @Param {string} thisIcon.color
 * @Return {HTMLelement}
 */
proto.createIcon = function(thisIcon) {
    var iconHeight = isNumeric(thisIcon.height) ?
        Number(thisIcon.height) :
        thisIcon.ascent - thisIcon.descent;
    var svgNS = 'http://www.w3.org/2000/svg';
    var icon;

    if(thisIcon.path) {
        icon = document.createElementNS(svgNS, 'svg');
        icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' '));
        icon.setAttribute('class', 'icon');

        var path = document.createElementNS(svgNS, 'path');
        path.setAttribute('d', thisIcon.path);

        if(thisIcon.transform) {
            path.setAttribute('transform', thisIcon.transform);
        }
        else if(thisIcon.ascent !== undefined) {
            // Legacy icon transform calculation
            path.setAttribute('transform', 'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')');
        }

        icon.appendChild(path);
    }

    if(thisIcon.svg) {
        var svgDoc = Parser.parseFromString(thisIcon.svg, 'application/xml');
        icon = svgDoc.childNodes[0];
    }

    icon.setAttribute('height', '1em');
    icon.setAttribute('width', '1em');

    return icon;
};

/**
 * Updates active button with attribute specified in layout
 * @Param {object} graphInfo plot object containing data and layout
 * @Return {HTMLelement}
 */
proto.updateActiveButton = function(buttonClicked) {
    var fullLayout = this.graphInfo._fullLayout;
    var dataAttrClicked = (buttonClicked !== undefined) ?
        buttonClicked.getAttribute('data-attr') :
        null;

    this.buttonElements.forEach(function(button) {
        var thisval = button.getAttribute('data-val') || true;
        var dataAttr = button.getAttribute('data-attr');
        var isToggleButton = (button.getAttribute('data-toggle') === 'true');
        var button3 = d3.select(button);

        // Use 'data-toggle' and 'buttonClicked' to toggle buttons
        // that have no one-to-one equivalent in fullLayout
        if(isToggleButton) {
            if(dataAttr === dataAttrClicked) {
                button3.classed('active', !button3.classed('active'));
            }
        }
        else {
            var val = (dataAttr === null) ?
                dataAttr :
                Lib.nestedProperty(fullLayout, dataAttr).get();

            button3.classed('active', val === thisval);
        }

    });
};

/**
 * Check if modeBar is configured as button configuration argument
 *
 * @Param {object} buttons 2d array of grouped button config objects
 * @Return {boolean}
 */
proto.hasButtons = function(buttons) {
    var currentButtons = this.buttons;

    if(!currentButtons) return false;

    if(buttons.length !== currentButtons.length) return false;

    for(var i = 0; i < buttons.length; ++i) {
        if(buttons[i].length !== currentButtons[i].length) return false;
        for(var j = 0; j < buttons[i].length; j++) {
            if(buttons[i][j].name !== currentButtons[i][j].name) return false;
        }
    }

    return true;
};

/**
 * @return {HTMLDivElement} The logo image wrapped in a group
 */
proto.getLogo = function() {
    var group = this.createGroup();
    var a = document.createElement('a');

    a.href = 'https://plot.ly/';
    a.target = '_blank';
    a.setAttribute('data-title', Lib._(this.graphInfo, 'Produced with Plotly'));
    a.className = 'modebar-btn plotlyjsicon modebar-btn--logo';

    a.appendChild(this.createIcon(Icons.newplotlylogo));

    group.appendChild(a);
    return group;
};

proto.removeAllButtons = function() {
    while(this.element.firstChild) {
        this.element.removeChild(this.element.firstChild);
    }

    this.hasLogo = false;
};

proto.destroy = function() {
    Lib.removeElement(this.container.querySelector('.modebar'));
    Lib.deleteRelatedStyleRule(this._uid);
};

function createModeBar(gd, buttons) {
    var fullLayout = gd._fullLayout;

    var modeBar = new ModeBar({
        graphInfo: gd,
        container: fullLayout._modebardiv.node(),
        buttons: buttons
    });

    if(fullLayout._privateplot) {
        d3.select(modeBar.element).append('span')
            .classed('badge-private float--left', true)
            .text('PRIVATE');
    }

    return modeBar;
}

module.exports = createModeBar;

},{"../../../build/ploticon":2,"../../lib":697,"d3":151,"fast-isnumeric":218}],636:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = _dereq_('../../plots/font_attributes');
var colorAttrs = _dereq_('../color/attributes');
var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;

var buttonAttrs = templatedArray('button', {
    visible: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'plot',
        
    },
    step: {
        valType: 'enumerated',
        
        values: ['month', 'year', 'day', 'hour', 'minute', 'second', 'all'],
        dflt: 'month',
        editType: 'plot',
        
    },
    stepmode: {
        valType: 'enumerated',
        
        values: ['backward', 'todate'],
        dflt: 'backward',
        editType: 'plot',
        
    },
    count: {
        valType: 'number',
        
        min: 0,
        dflt: 1,
        editType: 'plot',
        
    },
    label: {
        valType: 'string',
        
        editType: 'plot',
        
    },
    editType: 'plot',
    
});

module.exports = {
    visible: {
        valType: 'boolean',
        
        editType: 'plot',
        
    },

    buttons: buttonAttrs,

    x: {
        valType: 'number',
        min: -2,
        max: 3,
        
        editType: 'plot',
        
    },
    xanchor: {
        valType: 'enumerated',
        values: ['auto', 'left', 'center', 'right'],
        dflt: 'left',
        
        editType: 'plot',
        
    },
    y: {
        valType: 'number',
        min: -2,
        max: 3,
        
        editType: 'plot',
        
    },
    yanchor: {
        valType: 'enumerated',
        values: ['auto', 'top', 'middle', 'bottom'],
        dflt: 'bottom',
        
        editType: 'plot',
        
    },

    font: fontAttrs({
        editType: 'plot',
        
    }),

    bgcolor: {
        valType: 'color',
        dflt: colorAttrs.lightLine,
        
        editType: 'plot',
        
    },
    activecolor: {
        valType: 'color',
        
        editType: 'plot',
        
    },
    bordercolor: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'plot',
        
    },
    borderwidth: {
        valType: 'number',
        min: 0,
        dflt: 0,
        
        editType: 'plot',
        
    },
    editType: 'plot'
};

},{"../../plot_api/plot_template":735,"../../plots/font_attributes":771,"../color/attributes":573}],637:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {

    // 'y' position pad above counter axis domain
    yPad: 0.02,

    // minimum button width (regardless of text size)
    minButtonWidth: 30,

    // buttons rect radii
    rx: 3,
    ry: 3,

    // light fraction used to compute the 'activecolor' default
    lightAmount: 25,
    darkAmount: 10
};

},{}],638:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Color = _dereq_('../color');
var Template = _dereq_('../../plot_api/plot_template');
var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');

var attributes = _dereq_('./attributes');
var constants = _dereq_('./constants');


module.exports = function handleDefaults(containerIn, containerOut, layout, counterAxes, calendar) {
    var selectorIn = containerIn.rangeselector || {};
    var selectorOut = Template.newContainer(containerOut, 'rangeselector');

    function coerce(attr, dflt) {
        return Lib.coerce(selectorIn, selectorOut, attributes, attr, dflt);
    }

    var buttons = handleArrayContainerDefaults(selectorIn, selectorOut, {
        name: 'buttons',
        handleItemDefaults: buttonDefaults,
        calendar: calendar
    });

    var visible = coerce('visible', buttons.length > 0);
    if(visible) {
        var posDflt = getPosDflt(containerOut, layout, counterAxes);
        coerce('x', posDflt[0]);
        coerce('y', posDflt[1]);
        Lib.noneOrAll(containerIn, containerOut, ['x', 'y']);

        coerce('xanchor');
        coerce('yanchor');

        Lib.coerceFont(coerce, 'font', layout.font);

        var bgColor = coerce('bgcolor');
        coerce('activecolor', Color.contrast(bgColor, constants.lightAmount, constants.darkAmount));
        coerce('bordercolor');
        coerce('borderwidth');
    }
};

function buttonDefaults(buttonIn, buttonOut, selectorOut, opts) {
    var calendar = opts.calendar;

    function coerce(attr, dflt) {
        return Lib.coerce(buttonIn, buttonOut, attributes.buttons, attr, dflt);
    }

    var visible = coerce('visible');

    if(visible) {
        var step = coerce('step');
        if(step !== 'all') {
            if(calendar && calendar !== 'gregorian' && (step === 'month' || step === 'year')) {
                buttonOut.stepmode = 'backward';
            }
            else {
                coerce('stepmode');
            }

            coerce('count');
        }

        coerce('label');
    }
}

function getPosDflt(containerOut, layout, counterAxes) {
    var anchoredList = counterAxes.filter(function(ax) {
        return layout[ax].anchor === containerOut._id;
    });

    var posY = 0;
    for(var i = 0; i < anchoredList.length; i++) {
        var domain = layout[anchoredList[i]].domain;
        if(domain) posY = Math.max(domain[1], posY);
    }

    return [containerOut.domain[0], posY + constants.yPad];
}

},{"../../lib":697,"../../plot_api/plot_template":735,"../../plots/array_container_defaults":741,"../color":574,"./attributes":636,"./constants":637}],639:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Registry = _dereq_('../../registry');
var Plots = _dereq_('../../plots/plots');
var Color = _dereq_('../color');
var Drawing = _dereq_('../drawing');
var Lib = _dereq_('../../lib');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var axisIds = _dereq_('../../plots/cartesian/axis_ids');

var alignmentConstants = _dereq_('../../constants/alignment');
var LINE_SPACING = alignmentConstants.LINE_SPACING;
var FROM_TL = alignmentConstants.FROM_TL;
var FROM_BR = alignmentConstants.FROM_BR;

var constants = _dereq_('./constants');
var getUpdateObject = _dereq_('./get_update_object');

module.exports = function draw(gd) {
    var fullLayout = gd._fullLayout;

    var selectors = fullLayout._infolayer.selectAll('.rangeselector')
        .data(makeSelectorData(gd), selectorKeyFunc);

    selectors.enter().append('g')
        .classed('rangeselector', true);

    selectors.exit().remove();

    selectors.style({
        cursor: 'pointer',
        'pointer-events': 'all'
    });

    selectors.each(function(d) {
        var selector = d3.select(this);
        var axisLayout = d;
        var selectorLayout = axisLayout.rangeselector;

        var buttons = selector.selectAll('g.button')
            .data(Lib.filterVisible(selectorLayout.buttons));

        buttons.enter().append('g')
            .classed('button', true);

        buttons.exit().remove();

        buttons.each(function(d) {
            var button = d3.select(this);
            var update = getUpdateObject(axisLayout, d);

            d._isActive = isActive(axisLayout, d, update);

            button.call(drawButtonRect, selectorLayout, d);
            button.call(drawButtonText, selectorLayout, d, gd);

            button.on('click', function() {
                if(gd._dragged) return;

                Registry.call('_guiRelayout', gd, update);
            });

            button.on('mouseover', function() {
                d._isHovered = true;
                button.call(drawButtonRect, selectorLayout, d);
            });

            button.on('mouseout', function() {
                d._isHovered = false;
                button.call(drawButtonRect, selectorLayout, d);
            });
        });

        reposition(gd, buttons, selectorLayout, axisLayout._name, selector);
    });

};

function makeSelectorData(gd) {
    var axes = axisIds.list(gd, 'x', true);
    var data = [];

    for(var i = 0; i < axes.length; i++) {
        var axis = axes[i];

        if(axis.rangeselector && axis.rangeselector.visible) {
            data.push(axis);
        }
    }

    return data;
}

function selectorKeyFunc(d) {
    return d._id;
}

function isActive(axisLayout, opts, update) {
    if(opts.step === 'all') {
        return axisLayout.autorange === true;
    }
    else {
        var keys = Object.keys(update);

        return (
            axisLayout.range[0] === update[keys[0]] &&
            axisLayout.range[1] === update[keys[1]]
        );
    }
}

function drawButtonRect(button, selectorLayout, d) {
    var rect = Lib.ensureSingle(button, 'rect', 'selector-rect', function(s) {
        s.attr('shape-rendering', 'crispEdges');
    });

    rect.attr({
        'rx': constants.rx,
        'ry': constants.ry
    });

    rect.call(Color.stroke, selectorLayout.bordercolor)
        .call(Color.fill, getFillColor(selectorLayout, d))
        .style('stroke-width', selectorLayout.borderwidth + 'px');
}

function getFillColor(selectorLayout, d) {
    return (d._isActive || d._isHovered) ?
        selectorLayout.activecolor :
        selectorLayout.bgcolor;
}

function drawButtonText(button, selectorLayout, d, gd) {
    function textLayout(s) {
        svgTextUtils.convertToTspans(s, gd);
    }

    var text = Lib.ensureSingle(button, 'text', 'selector-text', function(s) {
        s.classed('user-select-none', true)
            .attr('text-anchor', 'middle');
    });

    text.call(Drawing.font, selectorLayout.font)
        .text(getLabel(d, gd._fullLayout.meta))
        .call(textLayout);
}

function getLabel(opts, meta) {
    if(opts.label) {
        return meta ?
            Lib.templateString(opts.label, {meta: meta}) :
            opts.label;
    }

    if(opts.step === 'all') return 'all';

    return opts.count + opts.step.charAt(0);
}

function reposition(gd, buttons, opts, axName, selector) {
    var width = 0;
    var height = 0;

    var borderWidth = opts.borderwidth;

    buttons.each(function() {
        var button = d3.select(this);
        var text = button.select('.selector-text');

        var tHeight = opts.font.size * LINE_SPACING;
        var hEff = Math.max(tHeight * svgTextUtils.lineCount(text), 16) + 3;

        height = Math.max(height, hEff);
    });

    buttons.each(function() {
        var button = d3.select(this);
        var rect = button.select('.selector-rect');
        var text = button.select('.selector-text');

        var tWidth = text.node() && Drawing.bBox(text.node()).width;
        var tHeight = opts.font.size * LINE_SPACING;
        var tLines = svgTextUtils.lineCount(text);

        var wEff = Math.max(tWidth + 10, constants.minButtonWidth);

        // TODO add MathJax support

        // TODO add buttongap attribute

        button.attr('transform', 'translate(' +
            (borderWidth + width) + ',' + borderWidth +
        ')');

        rect.attr({
            x: 0,
            y: 0,
            width: wEff,
            height: height
        });

        svgTextUtils.positionText(text, wEff / 2,
            height / 2 - ((tLines - 1) * tHeight / 2) + 3);

        width += wEff + 5;
    });

    var graphSize = gd._fullLayout._size;
    var lx = graphSize.l + graphSize.w * opts.x;
    var ly = graphSize.t + graphSize.h * (1 - opts.y);

    var xanchor = 'left';
    if(Lib.isRightAnchor(opts)) {
        lx -= width;
        xanchor = 'right';
    }
    if(Lib.isCenterAnchor(opts)) {
        lx -= width / 2;
        xanchor = 'center';
    }

    var yanchor = 'top';
    if(Lib.isBottomAnchor(opts)) {
        ly -= height;
        yanchor = 'bottom';
    }
    if(Lib.isMiddleAnchor(opts)) {
        ly -= height / 2;
        yanchor = 'middle';
    }

    width = Math.ceil(width);
    height = Math.ceil(height);
    lx = Math.round(lx);
    ly = Math.round(ly);

    Plots.autoMargin(gd, axName + '-range-selector', {
        x: opts.x,
        y: opts.y,
        l: width * FROM_TL[xanchor],
        r: width * FROM_BR[xanchor],
        b: height * FROM_BR[yanchor],
        t: height * FROM_TL[yanchor]
    });

    selector.attr('transform', 'translate(' + lx + ',' + ly + ')');
}

},{"../../constants/alignment":669,"../../lib":697,"../../lib/svg_text_utils":721,"../../plots/cartesian/axis_ids":748,"../../plots/plots":807,"../../registry":826,"../color":574,"../drawing":595,"./constants":637,"./get_update_object":640,"d3":151}],640:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

module.exports = function getUpdateObject(axisLayout, buttonLayout) {
    var axName = axisLayout._name;
    var update = {};

    if(buttonLayout.step === 'all') {
        update[axName + '.autorange'] = true;
    }
    else {
        var xrange = getXRange(axisLayout, buttonLayout);

        update[axName + '.range[0]'] = xrange[0];
        update[axName + '.range[1]'] = xrange[1];
    }

    return update;
};

function getXRange(axisLayout, buttonLayout) {
    var currentRange = axisLayout.range;
    var base = new Date(axisLayout.r2l(currentRange[1]));
    var step = buttonLayout.step;
    var count = buttonLayout.count;
    var range0;

    switch(buttonLayout.stepmode) {
        case 'backward':
            range0 = axisLayout.l2r(+d3.time[step].utc.offset(base, -count));
            break;

        case 'todate':
            var base2 = d3.time[step].utc.offset(base, -count);

            range0 = axisLayout.l2r(+d3.time[step].utc.ceil(base2));
            break;
    }

    var range1 = currentRange[1];

    return [range0, range1];
}

},{"d3":151}],641:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'component',
    name: 'rangeselector',

    schema: {
        subplots: {
            xaxis: {rangeselector: _dereq_('./attributes')}
        }
    },

    layoutAttributes: _dereq_('./attributes'),
    handleDefaults: _dereq_('./defaults'),

    draw: _dereq_('./draw')
};

},{"./attributes":636,"./defaults":638,"./draw":639}],642:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorAttributes = _dereq_('../color/attributes');

module.exports = {
    bgcolor: {
        valType: 'color',
        dflt: colorAttributes.background,
        
        editType: 'plot',
        
    },
    bordercolor: {
        valType: 'color',
        dflt: colorAttributes.defaultLine,
        
        editType: 'plot',
        
    },
    borderwidth: {
        valType: 'integer',
        dflt: 0,
        min: 0,
        
        editType: 'plot',
        
    },
    autorange: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'calc',
        impliedEdits: {'range[0]': undefined, 'range[1]': undefined},
        
    },
    range: {
        valType: 'info_array',
        
        items: [
            {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}},
            {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}}
        ],
        editType: 'calc',
        impliedEdits: {'autorange': false},
        
    },
    thickness: {
        valType: 'number',
        dflt: 0.15,
        min: 0,
        max: 1,
        
        editType: 'plot',
        
    },
    visible: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'calc',
        
    },
    editType: 'calc'
};

},{"../color/attributes":573}],643:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var listAxes = _dereq_('../../plots/cartesian/axis_ids').list;
var getAutoRange = _dereq_('../../plots/cartesian/autorange').getAutoRange;
var constants = _dereq_('./constants');

module.exports = function calcAutorange(gd) {
    var axes = listAxes(gd, 'x', true);

    // Compute new slider range using axis autorange if necessary.
    //
    // Copy back range to input range slider container to skip
    // this step in subsequent draw calls.

    for(var i = 0; i < axes.length; i++) {
        var ax = axes[i];
        var opts = ax[constants.name];

        if(opts && opts.visible && opts.autorange) {
            opts._input.autorange = true;
            opts._input.range = opts.range = getAutoRange(gd, ax);
        }
    }
};

},{"../../plots/cartesian/autorange":744,"../../plots/cartesian/axis_ids":748,"./constants":644}],644:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {

    // attribute container name
    name: 'rangeslider',

    // class names

    containerClassName: 'rangeslider-container',
    bgClassName: 'rangeslider-bg',
    rangePlotClassName: 'rangeslider-rangeplot',

    maskMinClassName: 'rangeslider-mask-min',
    maskMaxClassName: 'rangeslider-mask-max',
    slideBoxClassName: 'rangeslider-slidebox',

    grabberMinClassName: 'rangeslider-grabber-min',
    grabAreaMinClassName: 'rangeslider-grabarea-min',
    handleMinClassName: 'rangeslider-handle-min',

    grabberMaxClassName: 'rangeslider-grabber-max',
    grabAreaMaxClassName: 'rangeslider-grabarea-max',
    handleMaxClassName: 'rangeslider-handle-max',

    maskMinOppAxisClassName: 'rangeslider-mask-min-opp-axis',
    maskMaxOppAxisClassName: 'rangeslider-mask-max-opp-axis',

    // style constants

    maskColor: 'rgba(0,0,0,0.4)',
    maskOppAxisColor: 'rgba(0,0,0,0.2)',

    slideBoxFill: 'transparent',
    slideBoxCursor: 'ew-resize',

    grabAreaFill: 'transparent',
    grabAreaCursor: 'col-resize',
    grabAreaWidth: 10,

    handleWidth: 4,
    handleRadius: 1,
    handleStrokeWidth: 1,

    extraPad: 15
};

},{}],645:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Template = _dereq_('../../plot_api/plot_template');
var axisIds = _dereq_('../../plots/cartesian/axis_ids');

var attributes = _dereq_('./attributes');
var oppAxisAttrs = _dereq_('./oppaxis_attributes');

module.exports = function handleDefaults(layoutIn, layoutOut, axName) {
    var axIn = layoutIn[axName];
    var axOut = layoutOut[axName];

    if(!(axIn.rangeslider || layoutOut._requestRangeslider[axOut._id])) return;

    // not super proud of this (maybe store _ in axis object instead
    if(!Lib.isPlainObject(axIn.rangeslider)) {
        axIn.rangeslider = {};
    }

    var containerIn = axIn.rangeslider;
    var containerOut = Template.newContainer(axOut, 'rangeslider');

    function coerce(attr, dflt) {
        return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
    }

    var rangeContainerIn, rangeContainerOut;
    function coerceRange(attr, dflt) {
        return Lib.coerce(rangeContainerIn, rangeContainerOut, oppAxisAttrs, attr, dflt);
    }

    var visible = coerce('visible');
    if(!visible) return;

    coerce('bgcolor', layoutOut.plot_bgcolor);
    coerce('bordercolor');
    coerce('borderwidth');
    coerce('thickness');

    coerce('autorange', !axOut.isValidRange(containerIn.range));
    coerce('range');

    var subplots = layoutOut._subplots;
    if(subplots) {
        var yIds = subplots.cartesian
            .filter(function(subplotId) {
                return subplotId.substr(0, subplotId.indexOf('y')) === axisIds.name2id(axName);
            })
            .map(function(subplotId) {
                return subplotId.substr(subplotId.indexOf('y'), subplotId.length);
            });
        var yNames = Lib.simpleMap(yIds, axisIds.id2name);
        for(var i = 0; i < yNames.length; i++) {
            var yName = yNames[i];

            rangeContainerIn = containerIn[yName] || {};
            rangeContainerOut = Template.newContainer(containerOut, yName, 'yaxis');

            var yAxOut = layoutOut[yName];

            var rangemodeDflt;
            if(rangeContainerIn.range && yAxOut.isValidRange(rangeContainerIn.range)) {
                rangemodeDflt = 'fixed';
            }

            var rangeMode = coerceRange('rangemode', rangemodeDflt);
            if(rangeMode !== 'match') {
                coerceRange('range', yAxOut.range.slice());
            }
        }
    }

    // to map back range slider (auto) range
    containerOut._input = containerIn;
};

},{"../../lib":697,"../../plot_api/plot_template":735,"../../plots/cartesian/axis_ids":748,"./attributes":642,"./oppaxis_attributes":649}],646:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Registry = _dereq_('../../registry');
var Plots = _dereq_('../../plots/plots');

var Lib = _dereq_('../../lib');
var Drawing = _dereq_('../drawing');
var Color = _dereq_('../color');
var Titles = _dereq_('../titles');

var Cartesian = _dereq_('../../plots/cartesian');
var axisIDs = _dereq_('../../plots/cartesian/axis_ids');

var dragElement = _dereq_('../dragelement');
var setCursor = _dereq_('../../lib/setcursor');

var constants = _dereq_('./constants');

module.exports = function(gd) {
    var fullLayout = gd._fullLayout;
    var rangeSliderData = fullLayout._rangeSliderData;
    for(var i = 0; i < rangeSliderData.length; i++) {
        var opts = rangeSliderData[i][constants.name];
        // fullLayout._uid may not exist when we call makeData
        opts._clipId = opts._id + '-' + fullLayout._uid;
    }

    /*
     * <g container />
     *  <rect bg />
     *  < .... range plot />
     *  <rect mask-min />
     *  <rect mask-max />
     *  <rect slidebox />
     *  <g grabber-min />
     *      <rect handle-min />
     *      <rect grabare-min />
     *  <g grabber-max />
     *      <rect handle-max />
     *      <rect grabare-max />
     *
     *  ...
     */

    function keyFunction(axisOpts) {
        return axisOpts._name;
    }

    var rangeSliders = fullLayout._infolayer
        .selectAll('g.' + constants.containerClassName)
        .data(rangeSliderData, keyFunction);

    // remove exiting sliders and their corresponding clip paths
    rangeSliders.exit().each(function(axisOpts) {
        var opts = axisOpts[constants.name];
        fullLayout._topdefs.select('#' + opts._clipId).remove();
    }).remove();

    // return early if no range slider is visible
    if(rangeSliderData.length === 0) return;

    rangeSliders.enter().append('g')
        .classed(constants.containerClassName, true)
        .attr('pointer-events', 'all');

    // for all present range sliders
    rangeSliders.each(function(axisOpts) {
        var rangeSlider = d3.select(this);
        var opts = axisOpts[constants.name];
        var oppAxisOpts = fullLayout[axisIDs.id2name(axisOpts.anchor)];
        var oppAxisRangeOpts = opts[axisIDs.id2name(axisOpts.anchor)];

        // update range
        // Expand slider range to the axis range
        if(opts.range) {
            var rng = Lib.simpleMap(opts.range, axisOpts.r2l);
            var axRng = Lib.simpleMap(axisOpts.range, axisOpts.r2l);
            var newRng;

            if(axRng[0] < axRng[1]) {
                newRng = [
                    Math.min(rng[0], axRng[0]),
                    Math.max(rng[1], axRng[1])
                ];
            } else {
                newRng = [
                    Math.max(rng[0], axRng[0]),
                    Math.min(rng[1], axRng[1])
                ];
            }

            opts.range = opts._input.range = Lib.simpleMap(newRng, axisOpts.l2r);
        }

        axisOpts.cleanRange('rangeslider.range');

        // update range slider dimensions

        var margin = fullLayout.margin;
        var graphSize = fullLayout._size;
        var domain = axisOpts.domain;
        var tickHeight = opts._tickHeight;

        var oppBottom = opts._oppBottom;

        opts._width = graphSize.w * (domain[1] - domain[0]);

        var x = Math.round(margin.l + (graphSize.w * domain[0]));

        var y = Math.round(
            graphSize.t + graphSize.h * (1 - oppBottom) +
            tickHeight +
            opts._offsetShift + constants.extraPad
        );

        rangeSlider.attr('transform', 'translate(' + x + ',' + y + ')');

        // update data <--> pixel coordinate conversion methods

        var range0 = axisOpts.r2l(opts.range[0]);
        var range1 = axisOpts.r2l(opts.range[1]);
        var dist = range1 - range0;

        opts.p2d = function(v) {
            return (v / opts._width) * dist + range0;
        };

        opts.d2p = function(v) {
            return (v - range0) / dist * opts._width;
        };

        opts._rl = [range0, range1];

        if(oppAxisRangeOpts.rangemode !== 'match') {
            var range0OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[0]);
            var range1OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[1]);
            var distOppAxis = range1OppAxis - range0OppAxis;

            opts.d2pOppAxis = function(v) {
                return (v - range0OppAxis) / distOppAxis * opts._height;
            };
        }

        // update inner nodes

        rangeSlider
            .call(drawBg, gd, axisOpts, opts)
            .call(addClipPath, gd, axisOpts, opts)
            .call(drawRangePlot, gd, axisOpts, opts)
            .call(drawMasks, gd, axisOpts, opts, oppAxisRangeOpts)
            .call(drawSlideBox, gd, axisOpts, opts)
            .call(drawGrabbers, gd, axisOpts, opts);

        // setup drag element
        setupDragElement(rangeSlider, gd, axisOpts, opts);

        // update current range
        setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts);

        // title goes next to range slider instead of tick labels, so
        // just take it over and draw it from here
        if(axisOpts.side === 'bottom') {
            Titles.draw(gd, axisOpts._id + 'title', {
                propContainer: axisOpts,
                propName: axisOpts._name + '.title',
                placeholder: fullLayout._dfltTitle.x,
                attributes: {
                    x: axisOpts._offset + axisOpts._length / 2,
                    y: y + opts._height + opts._offsetShift + 10 + 1.5 * axisOpts.title.font.size,
                    'text-anchor': 'middle'
                }
            });
        }
    });
};

function setupDragElement(rangeSlider, gd, axisOpts, opts) {
    var slideBox = rangeSlider.select('rect.' + constants.slideBoxClassName).node();
    var grabAreaMin = rangeSlider.select('rect.' + constants.grabAreaMinClassName).node();
    var grabAreaMax = rangeSlider.select('rect.' + constants.grabAreaMaxClassName).node();

    rangeSlider.on('mousedown', function() {
        var event = d3.event;
        var target = event.target;
        var startX = event.clientX;
        var offsetX = startX - rangeSlider.node().getBoundingClientRect().left;
        var minVal = opts.d2p(axisOpts._rl[0]);
        var maxVal = opts.d2p(axisOpts._rl[1]);

        var dragCover = dragElement.coverSlip();

        dragCover.addEventListener('mousemove', mouseMove);
        dragCover.addEventListener('mouseup', mouseUp);

        function mouseMove(e) {
            var delta = +e.clientX - startX;
            var pixelMin, pixelMax, cursor;

            switch(target) {
                case slideBox:
                    cursor = 'ew-resize';
                    pixelMin = minVal + delta;
                    pixelMax = maxVal + delta;
                    break;

                case grabAreaMin:
                    cursor = 'col-resize';
                    pixelMin = minVal + delta;
                    pixelMax = maxVal;
                    break;

                case grabAreaMax:
                    cursor = 'col-resize';
                    pixelMin = minVal;
                    pixelMax = maxVal + delta;
                    break;

                default:
                    cursor = 'ew-resize';
                    pixelMin = offsetX;
                    pixelMax = offsetX + delta;
                    break;
            }

            if(pixelMax < pixelMin) {
                var tmp = pixelMax;
                pixelMax = pixelMin;
                pixelMin = tmp;
            }

            opts._pixelMin = pixelMin;
            opts._pixelMax = pixelMax;

            setCursor(d3.select(dragCover), cursor);
            setDataRange(rangeSlider, gd, axisOpts, opts);
        }

        function mouseUp() {
            dragCover.removeEventListener('mousemove', mouseMove);
            dragCover.removeEventListener('mouseup', mouseUp);
            Lib.removeElement(dragCover);
        }
    });
}

function setDataRange(rangeSlider, gd, axisOpts, opts) {

    function clamp(v) {
        return axisOpts.l2r(Lib.constrain(v, opts._rl[0], opts._rl[1]));
    }

    var dataMin = clamp(opts.p2d(opts._pixelMin));
    var dataMax = clamp(opts.p2d(opts._pixelMax));

    window.requestAnimationFrame(function() {
        Registry.call('_guiRelayout', gd, axisOpts._name + '.range', [dataMin, dataMax]);
    });
}

function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) {
    var hw2 = constants.handleWidth / 2;

    function clamp(v) {
        return Lib.constrain(v, 0, opts._width);
    }

    function clampOppAxis(v) {
        return Lib.constrain(v, 0, opts._height);
    }

    function clampHandle(v) {
        return Lib.constrain(v, -hw2, opts._width + hw2);
    }

    var pixelMin = clamp(opts.d2p(axisOpts._rl[0]));
    var pixelMax = clamp(opts.d2p(axisOpts._rl[1]));

    rangeSlider.select('rect.' + constants.slideBoxClassName)
        .attr('x', pixelMin)
        .attr('width', pixelMax - pixelMin);

    rangeSlider.select('rect.' + constants.maskMinClassName)
        .attr('width', pixelMin);

    rangeSlider.select('rect.' + constants.maskMaxClassName)
        .attr('x', pixelMax)
        .attr('width', opts._width - pixelMax);

    if(oppAxisRangeOpts.rangemode !== 'match') {
        var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1]));
        var pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0]));

        rangeSlider.select('rect.' + constants.maskMinOppAxisClassName)
            .attr('x', pixelMin)
            .attr('height', pixelMinOppAxis)
            .attr('width', pixelMax - pixelMin);

        rangeSlider.select('rect.' + constants.maskMaxOppAxisClassName)
            .attr('x', pixelMin)
            .attr('y', pixelMaxOppAxis)
            .attr('height', opts._height - pixelMaxOppAxis)
            .attr('width', pixelMax - pixelMin);

        rangeSlider.select('rect.' + constants.slideBoxClassName)
            .attr('y', pixelMinOppAxis)
            .attr('height', pixelMaxOppAxis - pixelMinOppAxis);
    }

    // add offset for crispier corners
    // https://github.com/plotly/plotly.js/pull/1409
    var offset = 0.5;

    var xMin = Math.round(clampHandle(pixelMin - hw2)) - offset;
    var xMax = Math.round(clampHandle(pixelMax - hw2)) + offset;

    rangeSlider.select('g.' + constants.grabberMinClassName)
        .attr('transform', 'translate(' + xMin + ',' + offset + ')');

    rangeSlider.select('g.' + constants.grabberMaxClassName)
        .attr('transform', 'translate(' + xMax + ',' + offset + ')');
}

function drawBg(rangeSlider, gd, axisOpts, opts) {
    var bg = Lib.ensureSingle(rangeSlider, 'rect', constants.bgClassName, function(s) {
        s.attr({
            x: 0,
            y: 0,
            'shape-rendering': 'crispEdges'
        });
    });

    var borderCorrect = (opts.borderwidth % 2) === 0 ?
        opts.borderwidth :
        opts.borderwidth - 1;

    var offsetShift = -opts._offsetShift;
    var lw = Drawing.crispRound(gd, opts.borderwidth);

    bg.attr({
        width: opts._width + borderCorrect,
        height: opts._height + borderCorrect,
        transform: 'translate(' + offsetShift + ',' + offsetShift + ')',
        fill: opts.bgcolor,
        stroke: opts.bordercolor,
        'stroke-width': lw
    });
}

function addClipPath(rangeSlider, gd, axisOpts, opts) {
    var fullLayout = gd._fullLayout;

    var clipPath = Lib.ensureSingleById(fullLayout._topdefs, 'clipPath', opts._clipId, function(s) {
        s.append('rect').attr({ x: 0, y: 0 });
    });

    clipPath.select('rect').attr({
        width: opts._width,
        height: opts._height
    });
}

function drawRangePlot(rangeSlider, gd, axisOpts, opts) {
    var calcData = gd.calcdata;

    var rangePlots = rangeSlider.selectAll('g.' + constants.rangePlotClassName)
        .data(axisOpts._subplotsWith, Lib.identity);

    rangePlots.enter().append('g')
        .attr('class', function(id) { return constants.rangePlotClassName + ' ' + id; })
        .call(Drawing.setClipUrl, opts._clipId, gd);

    rangePlots.order();

    rangePlots.exit().remove();

    var mainplotinfo;

    rangePlots.each(function(id, i) {
        var plotgroup = d3.select(this);
        var isMainPlot = (i === 0);

        var oppAxisOpts = axisIDs.getFromId(gd, id, 'y');
        var oppAxisName = oppAxisOpts._name;
        var oppAxisRangeOpts = opts[oppAxisName];

        var mockFigure = {
            data: [],
            layout: {
                xaxis: {
                    type: axisOpts.type,
                    domain: [0, 1],
                    range: opts.range.slice(),
                    calendar: axisOpts.calendar
                },
                width: opts._width,
                height: opts._height,
                margin: { t: 0, b: 0, l: 0, r: 0 }
            },
            _context: gd._context
        };

        mockFigure.layout[oppAxisName] = {
            type: oppAxisOpts.type,
            domain: [0, 1],
            range: oppAxisRangeOpts.rangemode !== 'match' ? oppAxisRangeOpts.range.slice() : oppAxisOpts.range.slice(),
            calendar: oppAxisOpts.calendar
        };

        Plots.supplyDefaults(mockFigure);

        var xa = mockFigure._fullLayout.xaxis;
        var ya = mockFigure._fullLayout[oppAxisName];

        xa.clearCalc();
        xa.setScale();
        ya.clearCalc();
        ya.setScale();

        var plotinfo = {
            id: id,
            plotgroup: plotgroup,
            xaxis: xa,
            yaxis: ya,
            isRangePlot: true
        };

        if(isMainPlot) mainplotinfo = plotinfo;
        else {
            plotinfo.mainplot = 'xy';
            plotinfo.mainplotinfo = mainplotinfo;
        }

        Cartesian.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id));
    });
}

function filterRangePlotCalcData(calcData, subplotId) {
    var out = [];

    for(var i = 0; i < calcData.length; i++) {
        var calcTrace = calcData[i];
        var trace = calcTrace[0].trace;

        if(trace.xaxis + trace.yaxis === subplotId) {
            out.push(calcTrace);
        }
    }

    return out;
}

function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) {
    var maskMin = Lib.ensureSingle(rangeSlider, 'rect', constants.maskMinClassName, function(s) {
        s.attr({
            x: 0,
            y: 0,
            'shape-rendering': 'crispEdges'
        });
    });

    maskMin
        .attr('height', opts._height)
        .call(Color.fill, constants.maskColor);

    var maskMax = Lib.ensureSingle(rangeSlider, 'rect', constants.maskMaxClassName, function(s) {
        s.attr({
            y: 0,
            'shape-rendering': 'crispEdges'
        });
    });

    maskMax
        .attr('height', opts._height)
        .call(Color.fill, constants.maskColor);

    // masks used for oppAxis zoom
    if(oppAxisRangeOpts.rangemode !== 'match') {
        var maskMinOppAxis = Lib.ensureSingle(rangeSlider, 'rect', constants.maskMinOppAxisClassName, function(s) {
            s.attr({
                y: 0,
                'shape-rendering': 'crispEdges'
            });
        });

        maskMinOppAxis
            .attr('width', opts._width)
            .call(Color.fill, constants.maskOppAxisColor);

        var maskMaxOppAxis = Lib.ensureSingle(rangeSlider, 'rect', constants.maskMaxOppAxisClassName, function(s) {
            s.attr({
                y: 0,
                'shape-rendering': 'crispEdges'
            });
        });

        maskMaxOppAxis
            .attr('width', opts._width)
            .style('border-top', constants.maskOppBorder)
            .call(Color.fill, constants.maskOppAxisColor);
    }
}

function drawSlideBox(rangeSlider, gd, axisOpts, opts) {
    if(gd._context.staticPlot) return;

    var slideBox = Lib.ensureSingle(rangeSlider, 'rect', constants.slideBoxClassName, function(s) {
        s.attr({
            y: 0,
            cursor: constants.slideBoxCursor,
            'shape-rendering': 'crispEdges'
        });
    });

    slideBox.attr({
        height: opts._height,
        fill: constants.slideBoxFill
    });
}

function drawGrabbers(rangeSlider, gd, axisOpts, opts) {
    // <g grabber />
    var grabberMin = Lib.ensureSingle(rangeSlider, 'g', constants.grabberMinClassName);
    var grabberMax = Lib.ensureSingle(rangeSlider, 'g', constants.grabberMaxClassName);

    // <g handle />
    var handleFixAttrs = {
        x: 0,
        width: constants.handleWidth,
        rx: constants.handleRadius,
        fill: Color.background,
        stroke: Color.defaultLine,
        'stroke-width': constants.handleStrokeWidth,
        'shape-rendering': 'crispEdges'
    };
    var handleDynamicAttrs = {
        y: Math.round(opts._height / 4),
        height: Math.round(opts._height / 2),
    };
    var handleMin = Lib.ensureSingle(grabberMin, 'rect', constants.handleMinClassName, function(s) {
        s.attr(handleFixAttrs);
    });
    handleMin.attr(handleDynamicAttrs);

    var handleMax = Lib.ensureSingle(grabberMax, 'rect', constants.handleMaxClassName, function(s) {
        s.attr(handleFixAttrs);
    });
    handleMax.attr(handleDynamicAttrs);

    // <g grabarea />
    if(gd._context.staticPlot) return;

    var grabAreaFixAttrs = {
        width: constants.grabAreaWidth,
        x: 0,
        y: 0,
        fill: constants.grabAreaFill,
        cursor: constants.grabAreaCursor
    };

    var grabAreaMin = Lib.ensureSingle(grabberMin, 'rect', constants.grabAreaMinClassName, function(s) {
        s.attr(grabAreaFixAttrs);
    });
    grabAreaMin.attr('height', opts._height);

    var grabAreaMax = Lib.ensureSingle(grabberMax, 'rect', constants.grabAreaMaxClassName, function(s) {
        s.attr(grabAreaFixAttrs);
    });
    grabAreaMax.attr('height', opts._height);
}

},{"../../lib":697,"../../lib/setcursor":717,"../../plots/cartesian":756,"../../plots/cartesian/axis_ids":748,"../../plots/plots":807,"../../registry":826,"../color":574,"../dragelement":592,"../drawing":595,"../titles":662,"./constants":644,"d3":151}],647:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var axisIDs = _dereq_('../../plots/cartesian/axis_ids');
var constants = _dereq_('./constants');
var name = constants.name;

function isVisible(ax) {
    var rangeSlider = ax && ax[name];
    return rangeSlider && rangeSlider.visible;
}
exports.isVisible = isVisible;

exports.makeData = function(fullLayout) {
    var axes = axisIDs.list({ _fullLayout: fullLayout }, 'x', true);
    var margin = fullLayout.margin;
    var rangeSliderData = [];

    if(!fullLayout._has('gl2d')) {
        for(var i = 0; i < axes.length; i++) {
            var ax = axes[i];

            if(isVisible(ax)) {
                rangeSliderData.push(ax);

                var opts = ax[name];
                opts._id = name + ax._id;
                opts._height = (fullLayout.height - margin.b - margin.t) * opts.thickness;
                opts._offsetShift = Math.floor(opts.borderwidth / 2);
            }
        }
    }

    fullLayout._rangeSliderData = rangeSliderData;
};

exports.autoMarginOpts = function(gd, ax) {
    var opts = ax[name];

    var oppBottom = Infinity;
    var counterAxes = ax._counterAxes;
    for(var j = 0; j < counterAxes.length; j++) {
        var counterId = counterAxes[j];
        var oppAxis = axisIDs.getFromId(gd, counterId);
        oppBottom = Math.min(oppBottom, oppAxis.domain[0]);
    }
    opts._oppBottom = oppBottom;

    var tickHeight = (ax.side === 'bottom' && ax._boundingBox.height) || 0;
    opts._tickHeight = tickHeight;

    return {
        x: 0,
        y: oppBottom,
        l: 0,
        r: 0,
        t: 0,
        b: opts._height + gd._fullLayout.margin.b + tickHeight,
        pad: constants.extraPad + opts._offsetShift * 2
    };
};

},{"../../plots/cartesian/axis_ids":748,"./constants":644}],648:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var attrs = _dereq_('./attributes');
var oppAxisAttrs = _dereq_('./oppaxis_attributes');
var helpers = _dereq_('./helpers');

module.exports = {
    moduleType: 'component',
    name: 'rangeslider',

    schema: {
        subplots: {
            xaxis: {
                rangeslider: Lib.extendFlat({}, attrs, {
                    yaxis: oppAxisAttrs
                })
            }
        }
    },

    layoutAttributes: _dereq_('./attributes'),
    handleDefaults: _dereq_('./defaults'),
    calcAutorange: _dereq_('./calc_autorange'),
    draw: _dereq_('./draw'),
    isVisible: helpers.isVisible,
    makeData: helpers.makeData,
    autoMarginOpts: helpers.autoMarginOpts
};

},{"../../lib":697,"./attributes":642,"./calc_autorange":643,"./defaults":645,"./draw":646,"./helpers":647,"./oppaxis_attributes":649}],649:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    // not really a 'subplot' attribute container,
    // but this is the flag we use to denote attributes that
    // support yaxis, yaxis2, yaxis3, ... counters
    _isSubplotObj: true,

    rangemode: {
        valType: 'enumerated',
        values: ['auto', 'fixed', 'match'],
        dflt: 'match',
        
        editType: 'calc',
        
    },
    range: {
        valType: 'info_array',
        
        items: [
            {valType: 'any', editType: 'plot'},
            {valType: 'any', editType: 'plot'}
        ],
        editType: 'plot',
        
    },
    editType: 'calc'
};

},{}],650:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var annAttrs = _dereq_('../annotations/attributes');
var scatterLineAttrs = _dereq_('../../traces/scatter/attributes').line;
var dash = _dereq_('../drawing/attributes').dash;
var extendFlat = _dereq_('../../lib/extend').extendFlat;
var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;

module.exports = templatedArray('shape', {
    visible: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'calc+arraydraw',
        
    },

    type: {
        valType: 'enumerated',
        values: ['circle', 'rect', 'path', 'line'],
        
        editType: 'calc+arraydraw',
        
    },

    layer: {
        valType: 'enumerated',
        values: ['below', 'above'],
        dflt: 'above',
        
        editType: 'arraydraw',
        
    },

    xref: extendFlat({}, annAttrs.xref, {
        
    }),
    xsizemode: {
        valType: 'enumerated',
        values: ['scaled', 'pixel'],
        dflt: 'scaled',
        
        editType: 'calc+arraydraw',
        
    },
    xanchor: {
        valType: 'any',
        
        editType: 'calc+arraydraw',
        
    },
    x0: {
        valType: 'any',
        
        editType: 'calc+arraydraw',
        
    },
    x1: {
        valType: 'any',
        
        editType: 'calc+arraydraw',
        
    },

    yref: extendFlat({}, annAttrs.yref, {
        
    }),
    ysizemode: {
        valType: 'enumerated',
        values: ['scaled', 'pixel'],
        dflt: 'scaled',
        
        editType: 'calc+arraydraw',
        
    },
    yanchor: {
        valType: 'any',
        
        editType: 'calc+arraydraw',
        
    },
    y0: {
        valType: 'any',
        
        editType: 'calc+arraydraw',
        
    },
    y1: {
        valType: 'any',
        
        editType: 'calc+arraydraw',
        
    },

    path: {
        valType: 'string',
        
        editType: 'calc+arraydraw',
        
    },

    opacity: {
        valType: 'number',
        min: 0,
        max: 1,
        dflt: 1,
        
        editType: 'arraydraw',
        
    },
    line: {
        color: extendFlat({}, scatterLineAttrs.color, {editType: 'arraydraw'}),
        width: extendFlat({}, scatterLineAttrs.width, {editType: 'calc+arraydraw'}),
        dash: extendFlat({}, dash, {editType: 'arraydraw'}),
        
        editType: 'calc+arraydraw'
    },
    fillcolor: {
        valType: 'color',
        dflt: 'rgba(0,0,0,0)',
        
        editType: 'arraydraw',
        
    },
    editType: 'arraydraw'
});

},{"../../lib/extend":687,"../../plot_api/plot_template":735,"../../traces/scatter/attributes":1048,"../annotations/attributes":557,"../drawing/attributes":594}],651:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');

var constants = _dereq_('./constants');
var helpers = _dereq_('./helpers');


module.exports = function calcAutorange(gd) {
    var fullLayout = gd._fullLayout;
    var shapeList = Lib.filterVisible(fullLayout.shapes);

    if(!shapeList.length || !gd._fullData.length) return;

    for(var i = 0; i < shapeList.length; i++) {
        var shape = shapeList[i];
        shape._extremes = {};

        var ax, bounds;

        if(shape.xref !== 'paper') {
            var vx0 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x0;
            var vx1 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x1;
            ax = Axes.getFromId(gd, shape.xref);

            bounds = shapeBounds(ax, vx0, vx1, shape.path, constants.paramIsX);
            if(bounds) {
                shape._extremes[ax._id] = Axes.findExtremes(ax, bounds, calcXPaddingOptions(shape));
            }
        }

        if(shape.yref !== 'paper') {
            var vy0 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y0;
            var vy1 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y1;
            ax = Axes.getFromId(gd, shape.yref);

            bounds = shapeBounds(ax, vy0, vy1, shape.path, constants.paramIsY);
            if(bounds) {
                shape._extremes[ax._id] = Axes.findExtremes(ax, bounds, calcYPaddingOptions(shape));
            }
        }
    }
};

function calcXPaddingOptions(shape) {
    return calcPaddingOptions(shape.line.width, shape.xsizemode, shape.x0, shape.x1, shape.path, false);
}

function calcYPaddingOptions(shape) {
    return calcPaddingOptions(shape.line.width, shape.ysizemode, shape.y0, shape.y1, shape.path, true);
}

function calcPaddingOptions(lineWidth, sizeMode, v0, v1, path, isYAxis) {
    var ppad = lineWidth / 2;
    var axisDirectionReverted = isYAxis;

    if(sizeMode === 'pixel') {
        var coords = path ?
            helpers.extractPathCoords(path, isYAxis ? constants.paramIsY : constants.paramIsX) :
            [v0, v1];
        var maxValue = Lib.aggNums(Math.max, null, coords);
        var minValue = Lib.aggNums(Math.min, null, coords);
        var beforePad = minValue < 0 ? Math.abs(minValue) + ppad : ppad;
        var afterPad = maxValue > 0 ? maxValue + ppad : ppad;

        return {
            ppad: ppad,
            ppadplus: axisDirectionReverted ? beforePad : afterPad,
            ppadminus: axisDirectionReverted ? afterPad : beforePad
        };
    } else {
        return {ppad: ppad};
    }
}

function shapeBounds(ax, v0, v1, path, paramsToUse) {
    var convertVal = (ax.type === 'category' || ax.type === 'multicategory') ? ax.r2c : ax.d2c;

    if(v0 !== undefined) return [convertVal(v0), convertVal(v1)];
    if(!path) return;

    var min = Infinity;
    var max = -Infinity;
    var segments = path.match(constants.segmentRE);
    var i;
    var segment;
    var drawnParam;
    var params;
    var val;

    if(ax.type === 'date') convertVal = helpers.decodeDate(convertVal);

    for(i = 0; i < segments.length; i++) {
        segment = segments[i];
        drawnParam = paramsToUse[segment.charAt(0)].drawn;
        if(drawnParam === undefined) continue;

        params = segments[i].substr(1).match(constants.paramRE);
        if(!params || params.length < drawnParam) continue;

        val = convertVal(params[drawnParam]);
        if(val < min) min = val;
        if(val > max) max = val;
    }
    if(max >= min) return [min, max];
}

},{"../../lib":697,"../../plots/cartesian/axes":745,"./constants":652,"./helpers":655}],652:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


module.exports = {
    segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g,
    paramRE: /[^\s,]+/g,

    // which numbers in each path segment are x (or y) values
    // drawn is which param is a drawn point, as opposed to a
    // control point (which doesn't count toward autorange.
    // TODO: this means curved paths could extend beyond the
    // autorange bounds. This is a bit tricky to get right
    // unless we revert to bounding boxes, but perhaps there's
    // a calculation we could do...)
    paramIsX: {
        M: {0: true, drawn: 0},
        L: {0: true, drawn: 0},
        H: {0: true, drawn: 0},
        V: {},
        Q: {0: true, 2: true, drawn: 2},
        C: {0: true, 2: true, 4: true, drawn: 4},
        T: {0: true, drawn: 0},
        S: {0: true, 2: true, drawn: 2},
        // A: {0: true, 5: true},
        Z: {}
    },

    paramIsY: {
        M: {1: true, drawn: 1},
        L: {1: true, drawn: 1},
        H: {},
        V: {0: true, drawn: 0},
        Q: {1: true, 3: true, drawn: 3},
        C: {1: true, 3: true, 5: true, drawn: 5},
        T: {1: true, drawn: 1},
        S: {1: true, 3: true, drawn: 5},
        // A: {1: true, 6: true},
        Z: {}
    },

    numParams: {
        M: 2,
        L: 2,
        H: 1,
        V: 1,
        Q: 4,
        C: 6,
        T: 2,
        S: 4,
        // A: 7,
        Z: 0
    }
};

},{}],653:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');
var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');

var attributes = _dereq_('./attributes');
var helpers = _dereq_('./helpers');


module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
    handleArrayContainerDefaults(layoutIn, layoutOut, {
        name: 'shapes',
        handleItemDefaults: handleShapeDefaults
    });
};

function handleShapeDefaults(shapeIn, shapeOut, fullLayout) {
    function coerce(attr, dflt) {
        return Lib.coerce(shapeIn, shapeOut, attributes, attr, dflt);
    }

    var visible = coerce('visible');

    if(!visible) return;

    coerce('layer');
    coerce('opacity');
    coerce('fillcolor');
    coerce('line.color');
    coerce('line.width');
    coerce('line.dash');

    var dfltType = shapeIn.path ? 'path' : 'rect';
    var shapeType = coerce('type', dfltType);
    var xSizeMode = coerce('xsizemode');
    var ySizeMode = coerce('ysizemode');

    // positioning
    var axLetters = ['x', 'y'];
    for(var i = 0; i < 2; i++) {
        var axLetter = axLetters[i];
        var attrAnchor = axLetter + 'anchor';
        var sizeMode = axLetter === 'x' ? xSizeMode : ySizeMode;
        var gdMock = {_fullLayout: fullLayout};
        var ax;
        var pos2r;
        var r2pos;

        // xref, yref
        var axRef = Axes.coerceRef(shapeIn, shapeOut, gdMock, axLetter, '', 'paper');

        if(axRef !== 'paper') {
            ax = Axes.getFromId(gdMock, axRef);
            ax._shapeIndices.push(shapeOut._index);
            r2pos = helpers.rangeToShapePosition(ax);
            pos2r = helpers.shapePositionToRange(ax);
        }
        else {
            pos2r = r2pos = Lib.identity;
        }

        // Coerce x0, x1, y0, y1
        if(shapeType !== 'path') {
            var dflt0 = 0.25;
            var dflt1 = 0.75;

            // hack until V2.0 when log has regular range behavior - make it look like other
            // ranges to send to coerce, then put it back after
            // this is all to give reasonable default position behavior on log axes, which is
            // a pretty unimportant edge case so we could just ignore this.
            var attr0 = axLetter + '0';
            var attr1 = axLetter + '1';
            var in0 = shapeIn[attr0];
            var in1 = shapeIn[attr1];
            shapeIn[attr0] = pos2r(shapeIn[attr0], true);
            shapeIn[attr1] = pos2r(shapeIn[attr1], true);

            if(sizeMode === 'pixel') {
                coerce(attr0, 0);
                coerce(attr1, 10);
            } else {
                Axes.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflt0);
                Axes.coercePosition(shapeOut, gdMock, coerce, axRef, attr1, dflt1);
            }

            // hack part 2
            shapeOut[attr0] = r2pos(shapeOut[attr0]);
            shapeOut[attr1] = r2pos(shapeOut[attr1]);
            shapeIn[attr0] = in0;
            shapeIn[attr1] = in1;
        }

        // Coerce xanchor and yanchor
        if(sizeMode === 'pixel') {
            // Hack for log axis described above
            var inAnchor = shapeIn[attrAnchor];
            shapeIn[attrAnchor] = pos2r(shapeIn[attrAnchor], true);

            Axes.coercePosition(shapeOut, gdMock, coerce, axRef, attrAnchor, 0.25);

            // Hack part 2
            shapeOut[attrAnchor] = r2pos(shapeOut[attrAnchor]);
            shapeIn[attrAnchor] = inAnchor;
        }
    }

    if(shapeType === 'path') {
        coerce('path');
    }
    else {
        Lib.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']);
    }
}

},{"../../lib":697,"../../plots/array_container_defaults":741,"../../plots/cartesian/axes":745,"./attributes":650,"./helpers":655}],654:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');
var Color = _dereq_('../color');
var Drawing = _dereq_('../drawing');
var arrayEditor = _dereq_('../../plot_api/plot_template').arrayEditor;

var dragElement = _dereq_('../dragelement');
var setCursor = _dereq_('../../lib/setcursor');

var constants = _dereq_('./constants');
var helpers = _dereq_('./helpers');


// Shapes are stored in gd.layout.shapes, an array of objects
// index can point to one item in this array,
//  or non-numeric to simply add a new one
//  or -1 to modify all existing
// opt can be the full options object, or one key (to be set to value)
//  or undefined to simply redraw
// if opt is blank, val can be 'add' or a full options object to add a new
//  annotation at that point in the array, or 'remove' to delete this one

module.exports = {
    draw: draw,
    drawOne: drawOne
};

function draw(gd) {
    var fullLayout = gd._fullLayout;

    // Remove previous shapes before drawing new in shapes in fullLayout.shapes
    fullLayout._shapeUpperLayer.selectAll('path').remove();
    fullLayout._shapeLowerLayer.selectAll('path').remove();

    for(var k in fullLayout._plots) {
        var shapelayer = fullLayout._plots[k].shapelayer;
        if(shapelayer) shapelayer.selectAll('path').remove();
    }

    for(var i = 0; i < fullLayout.shapes.length; i++) {
        if(fullLayout.shapes[i].visible) {
            drawOne(gd, i);
        }
    }

    // may need to resurrect this if we put text (LaTeX) in shapes
    // return Plots.previousPromises(gd);
}

function drawOne(gd, index) {
    // remove the existing shape if there is one.
    // because indices can change, we need to look in all shape layers
    gd._fullLayout._paperdiv
        .selectAll('.shapelayer [data-index="' + index + '"]')
        .remove();

    var options = gd._fullLayout.shapes[index] || {};

    // this shape is gone - quit now after deleting it
    // TODO: use d3 idioms instead of deleting and redrawing every time
    if(!options._input || options.visible === false) return;

    if(options.layer !== 'below') {
        drawShape(gd._fullLayout._shapeUpperLayer);
    }
    else if(options.xref === 'paper' || options.yref === 'paper') {
        drawShape(gd._fullLayout._shapeLowerLayer);
    }
    else {
        var plotinfo = gd._fullLayout._plots[options.xref + options.yref];
        if(plotinfo) {
            var mainPlot = plotinfo.mainplotinfo || plotinfo;
            drawShape(mainPlot.shapelayer);
        }
        else {
            // Fall back to _shapeLowerLayer in case the requested subplot doesn't exist.
            // This can happen if you reference the shape to an x / y axis combination
            // that doesn't have any data on it (and layer is below)
            drawShape(gd._fullLayout._shapeLowerLayer);
        }
    }

    function drawShape(shapeLayer) {
        var attrs = {
            'data-index': index,
            'fill-rule': 'evenodd',
            d: getPathString(gd, options)
        };
        var lineColor = options.line.width ? options.line.color : 'rgba(0,0,0,0)';

        var path = shapeLayer.append('path')
            .attr(attrs)
            .style('opacity', options.opacity)
            .call(Color.stroke, lineColor)
            .call(Color.fill, options.fillcolor)
            .call(Drawing.dashLine, options.line.dash, options.line.width);

        setClipPath(path, gd, options);

        if(gd._context.edits.shapePosition) setupDragElement(gd, path, options, index, shapeLayer);
    }
}

function setClipPath(shapePath, gd, shapeOptions) {
    // note that for layer="below" the clipAxes can be different from the
    // subplot we're drawing this in. This could cause problems if the shape
    // spans two subplots. See https://github.com/plotly/plotly.js/issues/1452
    var clipAxes = (shapeOptions.xref + shapeOptions.yref).replace(/paper/g, '');

    Drawing.setClipUrl(
        shapePath,
        clipAxes ? 'clip' + gd._fullLayout._uid + clipAxes : null,
        gd
    );
}

function setupDragElement(gd, shapePath, shapeOptions, index, shapeLayer) {
    var MINWIDTH = 10;
    var MINHEIGHT = 10;

    var xPixelSized = shapeOptions.xsizemode === 'pixel';
    var yPixelSized = shapeOptions.ysizemode === 'pixel';
    var isLine = shapeOptions.type === 'line';
    var isPath = shapeOptions.type === 'path';

    var editHelpers = arrayEditor(gd.layout, 'shapes', shapeOptions);
    var modifyItem = editHelpers.modifyItem;

    var x0, y0, x1, y1, xAnchor, yAnchor;
    var n0, s0, w0, e0, optN, optS, optW, optE;
    var pathIn;

    // setup conversion functions
    var xa = Axes.getFromId(gd, shapeOptions.xref);
    var ya = Axes.getFromId(gd, shapeOptions.yref);
    var x2p = helpers.getDataToPixel(gd, xa);
    var y2p = helpers.getDataToPixel(gd, ya, true);
    var p2x = helpers.getPixelToData(gd, xa);
    var p2y = helpers.getPixelToData(gd, ya, true);

    var sensoryElement = obtainSensoryElement();
    var dragOptions = {
        element: sensoryElement.node(),
        gd: gd,
        prepFn: startDrag,
        doneFn: endDrag,
        clickFn: abortDrag
    };
    var dragMode;

    dragElement.init(dragOptions);

    sensoryElement.node().onmousemove = updateDragMode;

    function obtainSensoryElement() {
        return isLine ? createLineDragHandles() : shapePath;
    }

    function createLineDragHandles() {
        var minSensoryWidth = 10;
        var sensoryWidth = Math.max(shapeOptions.line.width, minSensoryWidth);

        // Helper shapes group
        // Note that by setting the `data-index` attr, it is ensured that
        // the helper group is purged in this modules `draw` function
        var g = shapeLayer.append('g')
          .attr('data-index', index);

        // Helper path for moving
        g.append('path')
          .attr('d', shapePath.attr('d'))
          .style({
              'cursor': 'move',
              'stroke-width': sensoryWidth,
              'stroke-opacity': '0' // ensure not visible
          });

        // Helper circles for resizing
        var circleStyle = {
            'fill-opacity': '0' // ensure not visible
        };
        var circleRadius = sensoryWidth / 2 > minSensoryWidth ? sensoryWidth / 2 : minSensoryWidth;

        g.append('circle')
          .attr({
              'data-line-point': 'start-point',
              'cx': xPixelSized ? x2p(shapeOptions.xanchor) + shapeOptions.x0 : x2p(shapeOptions.x0),
              'cy': yPixelSized ? y2p(shapeOptions.yanchor) - shapeOptions.y0 : y2p(shapeOptions.y0),
              'r': circleRadius
          })
          .style(circleStyle)
          .classed('cursor-grab', true);

        g.append('circle')
          .attr({
              'data-line-point': 'end-point',
              'cx': xPixelSized ? x2p(shapeOptions.xanchor) + shapeOptions.x1 : x2p(shapeOptions.x1),
              'cy': yPixelSized ? y2p(shapeOptions.yanchor) - shapeOptions.y1 : y2p(shapeOptions.y1),
              'r': circleRadius
          })
          .style(circleStyle)
          .classed('cursor-grab', true);

        return g;
    }

    function updateDragMode(evt) {
        if(isLine) {
            if(evt.target.tagName === 'path') {
                dragMode = 'move';
            } else {
                dragMode = evt.target.attributes['data-line-point'].value === 'start-point' ?
                  'resize-over-start-point' : 'resize-over-end-point';
            }
        } else {
            // element might not be on screen at time of setup,
            // so obtain bounding box here
            var dragBBox = dragOptions.element.getBoundingClientRect();

            // choose 'move' or 'resize'
            // based on initial position of cursor within the drag element
            var w = dragBBox.right - dragBBox.left;
            var h = dragBBox.bottom - dragBBox.top;
            var x = evt.clientX - dragBBox.left;
            var y = evt.clientY - dragBBox.top;
            var cursor = (!isPath && w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey) ?
                dragElement.getCursor(x / w, 1 - y / h) :
                'move';

            setCursor(shapePath, cursor);

            // possible values 'move', 'sw', 'w', 'se', 'e', 'ne', 'n', 'nw' and 'w'
            dragMode = cursor.split('-')[0];
        }
    }

    function startDrag(evt) {
        // setup update strings and initial values
        if(xPixelSized) {
            xAnchor = x2p(shapeOptions.xanchor);
        }
        if(yPixelSized) {
            yAnchor = y2p(shapeOptions.yanchor);
        }

        if(shapeOptions.type === 'path') {
            pathIn = shapeOptions.path;
        }
        else {
            x0 = xPixelSized ? shapeOptions.x0 : x2p(shapeOptions.x0);
            y0 = yPixelSized ? shapeOptions.y0 : y2p(shapeOptions.y0);
            x1 = xPixelSized ? shapeOptions.x1 : x2p(shapeOptions.x1);
            y1 = yPixelSized ? shapeOptions.y1 : y2p(shapeOptions.y1);
        }

        if(x0 < x1) {
            w0 = x0;
            optW = 'x0';
            e0 = x1;
            optE = 'x1';
        }
        else {
            w0 = x1;
            optW = 'x1';
            e0 = x0;
            optE = 'x0';
        }

        // For fixed size shapes take opposing direction of y-axis into account.
        // Hint: For data sized shapes this is done by the y2p function.
        if((!yPixelSized && y0 < y1) || (yPixelSized && y0 > y1)) {
            n0 = y0;
            optN = 'y0';
            s0 = y1;
            optS = 'y1';
        }
        else {
            n0 = y1;
            optN = 'y1';
            s0 = y0;
            optS = 'y0';
        }

        // setup dragMode and the corresponding handler
        updateDragMode(evt);
        renderVisualCues(shapeLayer, shapeOptions);
        deactivateClipPathTemporarily(shapePath, shapeOptions, gd);
        dragOptions.moveFn = (dragMode === 'move') ? moveShape : resizeShape;
    }

    function endDrag() {
        setCursor(shapePath);
        removeVisualCues(shapeLayer);

        // Don't rely on clipPath being activated during re-layout
        setClipPath(shapePath, gd, shapeOptions);
        Registry.call('_guiRelayout', gd, editHelpers.getUpdateObj());
    }

    function abortDrag() {
        removeVisualCues(shapeLayer);
    }

    function moveShape(dx, dy) {
        if(shapeOptions.type === 'path') {
            var noOp = function(coord) { return coord; };
            var moveX = noOp;
            var moveY = noOp;

            if(xPixelSized) {
                modifyItem('xanchor', shapeOptions.xanchor = p2x(xAnchor + dx));
            } else {
                moveX = function moveX(x) { return p2x(x2p(x) + dx); };
                if(xa && xa.type === 'date') moveX = helpers.encodeDate(moveX);
            }

            if(yPixelSized) {
                modifyItem('yanchor', shapeOptions.yanchor = p2y(yAnchor + dy));
            } else {
                moveY = function moveY(y) { return p2y(y2p(y) + dy); };
                if(ya && ya.type === 'date') moveY = helpers.encodeDate(moveY);
            }

            modifyItem('path', shapeOptions.path = movePath(pathIn, moveX, moveY));
        }
        else {
            if(xPixelSized) {
                modifyItem('xanchor', shapeOptions.xanchor = p2x(xAnchor + dx));
            } else {
                modifyItem('x0', shapeOptions.x0 = p2x(x0 + dx));
                modifyItem('x1', shapeOptions.x1 = p2x(x1 + dx));
            }

            if(yPixelSized) {
                modifyItem('yanchor', shapeOptions.yanchor = p2y(yAnchor + dy));
            } else {
                modifyItem('y0', shapeOptions.y0 = p2y(y0 + dy));
                modifyItem('y1', shapeOptions.y1 = p2y(y1 + dy));
            }
        }

        shapePath.attr('d', getPathString(gd, shapeOptions));
        renderVisualCues(shapeLayer, shapeOptions);
    }

    function resizeShape(dx, dy) {
        if(isPath) {
            // TODO: implement path resize, don't forget to update dragMode code
            var noOp = function(coord) { return coord; };
            var moveX = noOp;
            var moveY = noOp;

            if(xPixelSized) {
                modifyItem('xanchor', shapeOptions.xanchor = p2x(xAnchor + dx));
            } else {
                moveX = function moveX(x) { return p2x(x2p(x) + dx); };
                if(xa && xa.type === 'date') moveX = helpers.encodeDate(moveX);
            }

            if(yPixelSized) {
                modifyItem('yanchor', shapeOptions.yanchor = p2y(yAnchor + dy));
            } else {
                moveY = function moveY(y) { return p2y(y2p(y) + dy); };
                if(ya && ya.type === 'date') moveY = helpers.encodeDate(moveY);
            }

            modifyItem('path', shapeOptions.path = movePath(pathIn, moveX, moveY));
        }
        else if(isLine) {
            if(dragMode === 'resize-over-start-point') {
                var newX0 = x0 + dx;
                var newY0 = yPixelSized ? y0 - dy : y0 + dy;
                modifyItem('x0', shapeOptions.x0 = xPixelSized ? newX0 : p2x(newX0));
                modifyItem('y0', shapeOptions.y0 = yPixelSized ? newY0 : p2y(newY0));
            } else if(dragMode === 'resize-over-end-point') {
                var newX1 = x1 + dx;
                var newY1 = yPixelSized ? y1 - dy : y1 + dy;
                modifyItem('x1', shapeOptions.x1 = xPixelSized ? newX1 : p2x(newX1));
                modifyItem('y1', shapeOptions.y1 = yPixelSized ? newY1 : p2y(newY1));
            }
        }
        else {
            var newN = (~dragMode.indexOf('n')) ? n0 + dy : n0;
            var newS = (~dragMode.indexOf('s')) ? s0 + dy : s0;
            var newW = (~dragMode.indexOf('w')) ? w0 + dx : w0;
            var newE = (~dragMode.indexOf('e')) ? e0 + dx : e0;

            // Do things in opposing direction for y-axis.
            // Hint: for data-sized shapes the reversal of axis direction is done in p2y.
            if(~dragMode.indexOf('n') && yPixelSized) newN = n0 - dy;
            if(~dragMode.indexOf('s') && yPixelSized) newS = s0 - dy;

            // Update shape eventually. Again, be aware of the
            // opposing direction of the y-axis of fixed size shapes.
            if((!yPixelSized && newS - newN > MINHEIGHT) ||
              (yPixelSized && newN - newS > MINHEIGHT)) {
                modifyItem(optN, shapeOptions[optN] = yPixelSized ? newN : p2y(newN));
                modifyItem(optS, shapeOptions[optS] = yPixelSized ? newS : p2y(newS));
            }
            if(newE - newW > MINWIDTH) {
                modifyItem(optW, shapeOptions[optW] = xPixelSized ? newW : p2x(newW));
                modifyItem(optE, shapeOptions[optE] = xPixelSized ? newE : p2x(newE));
            }
        }

        shapePath.attr('d', getPathString(gd, shapeOptions));
        renderVisualCues(shapeLayer, shapeOptions);
    }

    function renderVisualCues(shapeLayer, shapeOptions) {
        if(xPixelSized || yPixelSized) {
            renderAnchor();
        }

        function renderAnchor() {
            var isNotPath = shapeOptions.type !== 'path';

            // d3 join with dummy data to satisfy d3 data-binding
            var visualCues = shapeLayer.selectAll('.visual-cue').data([0]);

            // Enter
            var strokeWidth = 1;
            visualCues.enter()
              .append('path')
              .attr({
                  'fill': '#fff',
                  'fill-rule': 'evenodd',
                  'stroke': '#000',
                  'stroke-width': strokeWidth
              })
              .classed('visual-cue', true);

            // Update
            var posX = x2p(
              xPixelSized ?
                shapeOptions.xanchor :
                Lib.midRange(
                  isNotPath ?
                    [shapeOptions.x0, shapeOptions.x1] :
                    helpers.extractPathCoords(shapeOptions.path, constants.paramIsX))
            );
            var posY = y2p(
              yPixelSized ?
                shapeOptions.yanchor :
                Lib.midRange(
                  isNotPath ?
                    [shapeOptions.y0, shapeOptions.y1] :
                    helpers.extractPathCoords(shapeOptions.path, constants.paramIsY))
            );

            posX = helpers.roundPositionForSharpStrokeRendering(posX, strokeWidth);
            posY = helpers.roundPositionForSharpStrokeRendering(posY, strokeWidth);

            if(xPixelSized && yPixelSized) {
                var crossPath = 'M' + (posX - 1 - strokeWidth) + ',' + (posY - 1 - strokeWidth) +
                  'h-8v2h8 v8h2v-8 h8v-2h-8 v-8h-2 Z';
                visualCues.attr('d', crossPath);
            } else if(xPixelSized) {
                var vBarPath = 'M' + (posX - 1 - strokeWidth) + ',' + (posY - 9 - strokeWidth) +
                  'v18 h2 v-18 Z';
                visualCues.attr('d', vBarPath);
            } else {
                var hBarPath = 'M' + (posX - 9 - strokeWidth) + ',' + (posY - 1 - strokeWidth) +
                  'h18 v2 h-18 Z';
                visualCues.attr('d', hBarPath);
            }
        }
    }

    function removeVisualCues(shapeLayer) {
        shapeLayer.selectAll('.visual-cue').remove();
    }

    function deactivateClipPathTemporarily(shapePath, shapeOptions, gd) {
        var xref = shapeOptions.xref;
        var yref = shapeOptions.yref;
        var xa = Axes.getFromId(gd, xref);
        var ya = Axes.getFromId(gd, yref);

        var clipAxes = '';
        if(xref !== 'paper' && !xa.autorange) clipAxes += xref;
        if(yref !== 'paper' && !ya.autorange) clipAxes += yref;

        Drawing.setClipUrl(
            shapePath,
            clipAxes ? 'clip' + gd._fullLayout._uid + clipAxes : null,
            gd
        );
    }
}

function getPathString(gd, options) {
    var type = options.type;
    var xa = Axes.getFromId(gd, options.xref);
    var ya = Axes.getFromId(gd, options.yref);
    var gs = gd._fullLayout._size;
    var x2r, x2p, y2r, y2p;
    var x0, x1, y0, y1;

    if(xa) {
        x2r = helpers.shapePositionToRange(xa);
        x2p = function(v) { return xa._offset + xa.r2p(x2r(v, true)); };
    }
    else {
        x2p = function(v) { return gs.l + gs.w * v; };
    }

    if(ya) {
        y2r = helpers.shapePositionToRange(ya);
        y2p = function(v) { return ya._offset + ya.r2p(y2r(v, true)); };
    }
    else {
        y2p = function(v) { return gs.t + gs.h * (1 - v); };
    }

    if(type === 'path') {
        if(xa && xa.type === 'date') x2p = helpers.decodeDate(x2p);
        if(ya && ya.type === 'date') y2p = helpers.decodeDate(y2p);
        return convertPath(options, x2p, y2p);
    }

    if(options.xsizemode === 'pixel') {
        var xAnchorPos = x2p(options.xanchor);
        x0 = xAnchorPos + options.x0;
        x1 = xAnchorPos + options.x1;
    }
    else {
        x0 = x2p(options.x0);
        x1 = x2p(options.x1);
    }

    if(options.ysizemode === 'pixel') {
        var yAnchorPos = y2p(options.yanchor);
        y0 = yAnchorPos - options.y0;
        y1 = yAnchorPos - options.y1;
    }
    else {
        y0 = y2p(options.y0);
        y1 = y2p(options.y1);
    }

    if(type === 'line') return 'M' + x0 + ',' + y0 + 'L' + x1 + ',' + y1;
    if(type === 'rect') return 'M' + x0 + ',' + y0 + 'H' + x1 + 'V' + y1 + 'H' + x0 + 'Z';

    // circle
    var cx = (x0 + x1) / 2;
    var cy = (y0 + y1) / 2;
    var rx = Math.abs(cx - x0);
    var ry = Math.abs(cy - y0);
    var rArc = 'A' + rx + ',' + ry;
    var rightPt = (cx + rx) + ',' + cy;
    var topPt = cx + ',' + (cy - ry);
    return 'M' + rightPt + rArc + ' 0 1,1 ' + topPt +
        rArc + ' 0 0,1 ' + rightPt + 'Z';
}


function convertPath(options, x2p, y2p) {
    var pathIn = options.path;
    var xSizemode = options.xsizemode;
    var ySizemode = options.ysizemode;
    var xAnchor = options.xanchor;
    var yAnchor = options.yanchor;

    return pathIn.replace(constants.segmentRE, function(segment) {
        var paramNumber = 0;
        var segmentType = segment.charAt(0);
        var xParams = constants.paramIsX[segmentType];
        var yParams = constants.paramIsY[segmentType];
        var nParams = constants.numParams[segmentType];

        var paramString = segment.substr(1).replace(constants.paramRE, function(param) {
            if(xParams[paramNumber]) {
                if(xSizemode === 'pixel') param = x2p(xAnchor) + Number(param);
                else param = x2p(param);
            }
            else if(yParams[paramNumber]) {
                if(ySizemode === 'pixel') param = y2p(yAnchor) - Number(param);
                else param = y2p(param);
            }
            paramNumber++;

            if(paramNumber > nParams) param = 'X';
            return param;
        });

        if(paramNumber > nParams) {
            paramString = paramString.replace(/[\s,]*X.*/, '');
            Lib.log('Ignoring extra params in segment ' + segment);
        }

        return segmentType + paramString;
    });
}

function movePath(pathIn, moveX, moveY) {
    return pathIn.replace(constants.segmentRE, function(segment) {
        var paramNumber = 0;
        var segmentType = segment.charAt(0);
        var xParams = constants.paramIsX[segmentType];
        var yParams = constants.paramIsY[segmentType];
        var nParams = constants.numParams[segmentType];

        var paramString = segment.substr(1).replace(constants.paramRE, function(param) {
            if(paramNumber >= nParams) return param;

            if(xParams[paramNumber]) param = moveX(param);
            else if(yParams[paramNumber]) param = moveY(param);

            paramNumber++;

            return param;
        });

        return segmentType + paramString;
    });
}

},{"../../lib":697,"../../lib/setcursor":717,"../../plot_api/plot_template":735,"../../plots/cartesian/axes":745,"../../registry":826,"../color":574,"../dragelement":592,"../drawing":595,"./constants":652,"./helpers":655}],655:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var constants = _dereq_('./constants');

var Lib = _dereq_('../../lib');

// special position conversion functions... category axis positions can't be
// specified by their data values, because they don't make a continuous mapping.
// so these have to be specified in terms of the category serial numbers,
// but can take fractional values. Other axis types we specify position based on
// the actual data values.
// TODO: in V2.0 (when log axis ranges are in data units) range and shape position
// will be identical, so rangeToShapePosition and shapePositionToRange can be
// removed entirely.

exports.rangeToShapePosition = function(ax) {
    return (ax.type === 'log') ? ax.r2d : function(v) { return v; };
};

exports.shapePositionToRange = function(ax) {
    return (ax.type === 'log') ? ax.d2r : function(v) { return v; };
};

exports.decodeDate = function(convertToPx) {
    return function(v) {
        if(v.replace) v = v.replace('_', ' ');
        return convertToPx(v);
    };
};

exports.encodeDate = function(convertToDate) {
    return function(v) { return convertToDate(v).replace(' ', '_'); };
};

exports.extractPathCoords = function(path, paramsToUse) {
    var extractedCoordinates = [];

    var segments = path.match(constants.segmentRE);
    segments.forEach(function(segment) {
        var relevantParamIdx = paramsToUse[segment.charAt(0)].drawn;
        if(relevantParamIdx === undefined) return;

        var params = segment.substr(1).match(constants.paramRE);
        if(!params || params.length < relevantParamIdx) return;

        extractedCoordinates.push(Lib.cleanNumber(params[relevantParamIdx]));
    });

    return extractedCoordinates;
};

exports.getDataToPixel = function(gd, axis, isVertical) {
    var gs = gd._fullLayout._size;
    var dataToPixel;

    if(axis) {
        var d2r = exports.shapePositionToRange(axis);

        dataToPixel = function(v) {
            return axis._offset + axis.r2p(d2r(v, true));
        };

        if(axis.type === 'date') dataToPixel = exports.decodeDate(dataToPixel);
    }
    else if(isVertical) {
        dataToPixel = function(v) { return gs.t + gs.h * (1 - v); };
    }
    else {
        dataToPixel = function(v) { return gs.l + gs.w * v; };
    }

    return dataToPixel;
};

exports.getPixelToData = function(gd, axis, isVertical) {
    var gs = gd._fullLayout._size;
    var pixelToData;

    if(axis) {
        var r2d = exports.rangeToShapePosition(axis);
        pixelToData = function(p) { return r2d(axis.p2r(p - axis._offset)); };
    }
    else if(isVertical) {
        pixelToData = function(p) { return 1 - (p - gs.t) / gs.h; };
    }
    else {
        pixelToData = function(p) { return (p - gs.l) / gs.w; };
    }

    return pixelToData;
};

/**
 * Based on the given stroke width, rounds the passed
 * position value to represent either a full or half pixel.
 *
 * In case of an odd stroke width (e.g. 1), this measure ensures
 * that a stroke positioned at the returned position isn't rendered
 * blurry due to anti-aliasing.
 *
 * In case of an even stroke width (e.g. 2), this measure ensures
 * that the position value is transformed to a full pixel value
 * so that anti-aliasing doesn't take effect either.
 *
 * @param {number} pos The raw position value to be transformed
 * @param {number} strokeWidth The stroke width
 * @returns {number} either an integer or a .5 decimal number
 */
exports.roundPositionForSharpStrokeRendering = function(pos, strokeWidth) {
    var strokeWidthIsOdd = Math.round(strokeWidth % 2) === 1;
    var posValAsInt = Math.round(pos);

    return strokeWidthIsOdd ? posValAsInt + 0.5 : posValAsInt;
};

},{"../../lib":697,"./constants":652}],656:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var drawModule = _dereq_('./draw');

module.exports = {
    moduleType: 'component',
    name: 'shapes',

    layoutAttributes: _dereq_('./attributes'),
    supplyLayoutDefaults: _dereq_('./defaults'),
    includeBasePlot: _dereq_('../../plots/cartesian/include_components')('shapes'),

    calcAutorange: _dereq_('./calc_autorange'),
    draw: drawModule.draw,
    drawOne: drawModule.drawOne
};

},{"../../plots/cartesian/include_components":755,"./attributes":650,"./calc_autorange":651,"./defaults":653,"./draw":654}],657:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = _dereq_('../../plots/font_attributes');
var padAttrs = _dereq_('../../plots/pad_attributes');
var extendDeepAll = _dereq_('../../lib/extend').extendDeepAll;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
var animationAttrs = _dereq_('../../plots/animation_attributes');
var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;
var constants = _dereq_('./constants');

var stepsAttrs = templatedArray('step', {
    visible: {
        valType: 'boolean',
        
        dflt: true,
        
    },
    method: {
        valType: 'enumerated',
        values: ['restyle', 'relayout', 'animate', 'update', 'skip'],
        dflt: 'restyle',
        
        
    },
    args: {
        valType: 'info_array',
        
        freeLength: true,
        items: [
            { valType: 'any' },
            { valType: 'any' },
            { valType: 'any' }
        ],
        
    },
    label: {
        valType: 'string',
        
        
    },
    value: {
        valType: 'string',
        
        
    },
    execute: {
        valType: 'boolean',
        
        dflt: true,
        
    }
});

module.exports = overrideAll(templatedArray('slider', {
    visible: {
        valType: 'boolean',
        
        dflt: true,
        
    },

    active: {
        valType: 'number',
        
        min: 0,
        dflt: 0,
        
    },

    steps: stepsAttrs,

    lenmode: {
        valType: 'enumerated',
        values: ['fraction', 'pixels'],
        
        dflt: 'fraction',
        
    },
    len: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        
    },
    x: {
        valType: 'number',
        min: -2,
        max: 3,
        dflt: 0,
        
        
    },
    pad: extendDeepAll(padAttrs({editType: 'arraydraw'}), {
        
    }, {t: {dflt: 20}}),
    xanchor: {
        valType: 'enumerated',
        values: ['auto', 'left', 'center', 'right'],
        dflt: 'left',
        
        
    },
    y: {
        valType: 'number',
        min: -2,
        max: 3,
        dflt: 0,
        
        
    },
    yanchor: {
        valType: 'enumerated',
        values: ['auto', 'top', 'middle', 'bottom'],
        dflt: 'top',
        
        
    },

    transition: {
        duration: {
            valType: 'number',
            
            min: 0,
            dflt: 150,
            
        },
        easing: {
            valType: 'enumerated',
            values: animationAttrs.transition.easing.values,
            
            dflt: 'cubic-in-out',
            
        }
    },

    currentvalue: {
        visible: {
            valType: 'boolean',
            
            dflt: true,
            
        },

        xanchor: {
            valType: 'enumerated',
            values: ['left', 'center', 'right'],
            dflt: 'left',
            
            
        },

        offset: {
            valType: 'number',
            dflt: 10,
            
            
        },

        prefix: {
            valType: 'string',
            
            
        },

        suffix: {
            valType: 'string',
            
            
        },

        font: fontAttrs({
            
        })
    },

    font: fontAttrs({
        
    }),

    activebgcolor: {
        valType: 'color',
        
        dflt: constants.gripBgActiveColor,
        
    },
    bgcolor: {
        valType: 'color',
        
        dflt: constants.railBgColor,
        
    },
    bordercolor: {
        valType: 'color',
        dflt: constants.railBorderColor,
        
        
    },
    borderwidth: {
        valType: 'number',
        min: 0,
        dflt: constants.railBorderWidth,
        
        
    },
    ticklen: {
        valType: 'number',
        min: 0,
        dflt: constants.tickLength,
        
        
    },
    tickcolor: {
        valType: 'color',
        dflt: constants.tickColor,
        
        
    },
    tickwidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        
    },
    minorticklen: {
        valType: 'number',
        min: 0,
        dflt: constants.minorTickLength,
        
        
    }
}), 'arraydraw', 'from-root');

},{"../../lib/extend":687,"../../plot_api/edit_types":728,"../../plot_api/plot_template":735,"../../plots/animation_attributes":740,"../../plots/font_attributes":771,"../../plots/pad_attributes":806,"./constants":658}],658:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


module.exports = {

    // layout attribute name
    name: 'sliders',

    // class names
    containerClassName: 'slider-container',
    groupClassName: 'slider-group',
    inputAreaClass: 'slider-input-area',
    railRectClass: 'slider-rail-rect',
    railTouchRectClass: 'slider-rail-touch-rect',
    gripRectClass: 'slider-grip-rect',
    tickRectClass: 'slider-tick-rect',
    inputProxyClass: 'slider-input-proxy',
    labelsClass: 'slider-labels',
    labelGroupClass: 'slider-label-group',
    labelClass: 'slider-label',
    currentValueClass: 'slider-current-value',

    railHeight: 5,

    // DOM attribute name in button group keeping track
    // of active update menu
    menuIndexAttrName: 'slider-active-index',

    // id root pass to Plots.autoMargin
    autoMarginIdRoot: 'slider-',

    // min item width / height
    minWidth: 30,
    minHeight: 30,

    // padding around item text
    textPadX: 40,

    // arrow offset off right edge
    arrowOffsetX: 4,

    railRadius: 2,
    railWidth: 5,
    railBorder: 4,
    railBorderWidth: 1,
    railBorderColor: '#bec8d9',
    railBgColor: '#f8fafc',

    // The distance of the rail from the edge of the touchable area
    // Slightly less than the step inset because of the curved edges
    // of the rail
    railInset: 8,

    // The distance from the extremal tick marks to the edge of the
    // touchable area. This is basically the same as the grip radius,
    // but for other styles it wouldn't really need to be.
    stepInset: 10,

    gripRadius: 10,
    gripWidth: 20,
    gripHeight: 20,
    gripBorder: 20,
    gripBorderWidth: 1,
    gripBorderColor: '#bec8d9',
    gripBgColor: '#f6f8fa',
    gripBgActiveColor: '#dbdde0',

    labelPadding: 8,
    labelOffset: 0,

    tickWidth: 1,
    tickColor: '#333',
    tickOffset: 25,
    tickLength: 7,

    minorTickOffset: 25,
    minorTickColor: '#333',
    minorTickLength: 4,

    // Extra space below the current value label:
    currentValuePadding: 8,
    currentValueInset: 0,
};

},{}],659:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');

var attributes = _dereq_('./attributes');
var constants = _dereq_('./constants');

var name = constants.name;
var stepAttrs = attributes.steps;


module.exports = function slidersDefaults(layoutIn, layoutOut) {
    handleArrayContainerDefaults(layoutIn, layoutOut, {
        name: name,
        handleItemDefaults: sliderDefaults
    });
};

function sliderDefaults(sliderIn, sliderOut, layoutOut) {

    function coerce(attr, dflt) {
        return Lib.coerce(sliderIn, sliderOut, attributes, attr, dflt);
    }

    var steps = handleArrayContainerDefaults(sliderIn, sliderOut, {
        name: 'steps',
        handleItemDefaults: stepDefaults
    });

    var stepCount = 0;
    for(var i = 0; i < steps.length; i++) {
        if(steps[i].visible) stepCount++;
    }

    var visible;
    // If it has fewer than two options, it's not really a slider
    if(stepCount < 2) visible = sliderOut.visible = false;
    else visible = coerce('visible');
    if(!visible) return;

    sliderOut._stepCount = stepCount;
    var visSteps = sliderOut._visibleSteps = Lib.filterVisible(steps);

    var active = coerce('active');
    if(!(steps[active] || {}).visible) sliderOut.active = visSteps[0]._index;

    coerce('x');
    coerce('y');
    Lib.noneOrAll(sliderIn, sliderOut, ['x', 'y']);

    coerce('xanchor');
    coerce('yanchor');

    coerce('len');
    coerce('lenmode');

    coerce('pad.t');
    coerce('pad.r');
    coerce('pad.b');
    coerce('pad.l');

    Lib.coerceFont(coerce, 'font', layoutOut.font);

    var currentValueIsVisible = coerce('currentvalue.visible');

    if(currentValueIsVisible) {
        coerce('currentvalue.xanchor');
        coerce('currentvalue.prefix');
        coerce('currentvalue.suffix');
        coerce('currentvalue.offset');

        Lib.coerceFont(coerce, 'currentvalue.font', sliderOut.font);
    }

    coerce('transition.duration');
    coerce('transition.easing');

    coerce('bgcolor');
    coerce('activebgcolor');
    coerce('bordercolor');
    coerce('borderwidth');
    coerce('ticklen');
    coerce('tickwidth');
    coerce('tickcolor');
    coerce('minorticklen');
}

function stepDefaults(valueIn, valueOut) {
    function coerce(attr, dflt) {
        return Lib.coerce(valueIn, valueOut, stepAttrs, attr, dflt);
    }

    var visible;
    if(valueIn.method !== 'skip' && !Array.isArray(valueIn.args)) {
        visible = valueOut.visible = false;
    }
    else visible = coerce('visible');

    if(visible) {
        coerce('method');
        coerce('args');
        var label = coerce('label', 'step-' + valueOut._index);
        coerce('value', label);
        coerce('execute');
    }
}

},{"../../lib":697,"../../plots/array_container_defaults":741,"./attributes":657,"./constants":658}],660:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Plots = _dereq_('../../plots/plots');
var Color = _dereq_('../color');
var Drawing = _dereq_('../drawing');
var Lib = _dereq_('../../lib');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var arrayEditor = _dereq_('../../plot_api/plot_template').arrayEditor;

var constants = _dereq_('./constants');
var alignmentConstants = _dereq_('../../constants/alignment');
var LINE_SPACING = alignmentConstants.LINE_SPACING;
var FROM_TL = alignmentConstants.FROM_TL;
var FROM_BR = alignmentConstants.FROM_BR;

module.exports = function draw(gd) {
    var fullLayout = gd._fullLayout;
    var sliderData = makeSliderData(fullLayout, gd);

    // draw a container for *all* sliders:
    var sliders = fullLayout._infolayer
        .selectAll('g.' + constants.containerClassName)
        .data(sliderData.length > 0 ? [0] : []);

    sliders.enter().append('g')
        .classed(constants.containerClassName, true)
        .style('cursor', 'ew-resize');

    function clearSlider(sliderOpts) {
        if(sliderOpts._commandObserver) {
            sliderOpts._commandObserver.remove();
            delete sliderOpts._commandObserver;
        }

        // Most components don't need to explicitly remove autoMargin, because
        // marginPushers does this - but slider updates don't go through
        // a full replot so we need to explicitly remove it.
        Plots.autoMargin(gd, autoMarginId(sliderOpts));
    }

    sliders.exit().each(function() {
        d3.select(this).selectAll('g.' + constants.groupClassName)
            .each(clearSlider);
    })
    .remove();

    // Return early if no menus visible:
    if(sliderData.length === 0) return;

    var sliderGroups = sliders.selectAll('g.' + constants.groupClassName)
        .data(sliderData, keyFunction);

    sliderGroups.enter().append('g')
        .classed(constants.groupClassName, true);

    sliderGroups.exit()
        .each(clearSlider)
        .remove();

    // Find the dimensions of the sliders:
    for(var i = 0; i < sliderData.length; i++) {
        var sliderOpts = sliderData[i];
        findDimensions(gd, sliderOpts);
    }

    sliderGroups.each(function(sliderOpts) {
        var gSlider = d3.select(this);

        computeLabelSteps(sliderOpts);

        Plots.manageCommandObserver(gd, sliderOpts, sliderOpts._visibleSteps, function(data) {
            // NB: Same as below. This is *not* always the same as sliderOpts since
            // if a new set of steps comes in, the reference in this callback would
            // be invalid. We need to refetch it from the slider group, which is
            // the join data that creates this slider. So if this slider still exists,
            // the group should be valid, *to the best of my knowledge.* If not,
            // we'd have to look it up by d3 data join index/key.
            var opts = gSlider.data()[0];

            if(opts.active === data.index) return;
            if(opts._dragging) return;

            setActive(gd, gSlider, opts, data.index, false, true);
        });

        drawSlider(gd, d3.select(this), sliderOpts);
    });
};

function autoMarginId(sliderOpts) {
    return constants.autoMarginIdRoot + sliderOpts._index;
}

// This really only just filters by visibility:
function makeSliderData(fullLayout, gd) {
    var contOpts = fullLayout[constants.name];
    var sliderData = [];

    for(var i = 0; i < contOpts.length; i++) {
        var item = contOpts[i];
        if(!item.visible) continue;
        item._gd = gd;
        sliderData.push(item);
    }

    return sliderData;
}

// This is set in the defaults step:
function keyFunction(opts) {
    return opts._index;
}

// Compute the dimensions (mutates sliderOpts):
function findDimensions(gd, sliderOpts) {
    var sliderLabels = Drawing.tester.selectAll('g.' + constants.labelGroupClass)
        .data(sliderOpts._visibleSteps);

    sliderLabels.enter().append('g')
        .classed(constants.labelGroupClass, true);

    // loop over fake buttons to find width / height
    var maxLabelWidth = 0;
    var labelHeight = 0;
    sliderLabels.each(function(stepOpts) {
        var labelGroup = d3.select(this);

        var text = drawLabel(labelGroup, {step: stepOpts}, sliderOpts);

        var textNode = text.node();
        if(textNode) {
            var bBox = Drawing.bBox(textNode);
            labelHeight = Math.max(labelHeight, bBox.height);
            maxLabelWidth = Math.max(maxLabelWidth, bBox.width);
        }
    });

    sliderLabels.remove();

    var dims = sliderOpts._dims = {};

    dims.inputAreaWidth = Math.max(
        constants.railWidth,
        constants.gripHeight
    );

    // calculate some overall dimensions - some of these are needed for
    // calculating the currentValue dimensions
    var graphSize = gd._fullLayout._size;
    dims.lx = graphSize.l + graphSize.w * sliderOpts.x;
    dims.ly = graphSize.t + graphSize.h * (1 - sliderOpts.y);

    if(sliderOpts.lenmode === 'fraction') {
        // fraction:
        dims.outerLength = Math.round(graphSize.w * sliderOpts.len);
    } else {
        // pixels:
        dims.outerLength = sliderOpts.len;
    }

    // The length of the rail, *excluding* padding on either end:
    dims.inputAreaStart = 0;
    dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r);

    var textableInputLength = dims.inputAreaLength - 2 * constants.stepInset;
    var availableSpacePerLabel = textableInputLength / (sliderOpts._stepCount - 1);
    var computedSpacePerLabel = maxLabelWidth + constants.labelPadding;
    dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel));
    dims.labelHeight = labelHeight;

    // loop over all possible values for currentValue to find the
    // area we need for it
    dims.currentValueMaxWidth = 0;
    dims.currentValueHeight = 0;
    dims.currentValueTotalHeight = 0;
    dims.currentValueMaxLines = 1;

    if(sliderOpts.currentvalue.visible) {
        // Get the dimensions of the current value label:
        var dummyGroup = Drawing.tester.append('g');

        sliderLabels.each(function(stepOpts) {
            var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label);
            var curValSize = (curValPrefix.node() && Drawing.bBox(curValPrefix.node())) || {width: 0, height: 0};
            var lines = svgTextUtils.lineCount(curValPrefix);
            dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width));
            dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height));
            dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines);
        });

        dims.currentValueTotalHeight = dims.currentValueHeight + sliderOpts.currentvalue.offset;

        dummyGroup.remove();
    }

    dims.height = dims.currentValueTotalHeight + constants.tickOffset + sliderOpts.ticklen + constants.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b;

    var xanchor = 'left';
    if(Lib.isRightAnchor(sliderOpts)) {
        dims.lx -= dims.outerLength;
        xanchor = 'right';
    }
    if(Lib.isCenterAnchor(sliderOpts)) {
        dims.lx -= dims.outerLength / 2;
        xanchor = 'center';
    }

    var yanchor = 'top';
    if(Lib.isBottomAnchor(sliderOpts)) {
        dims.ly -= dims.height;
        yanchor = 'bottom';
    }
    if(Lib.isMiddleAnchor(sliderOpts)) {
        dims.ly -= dims.height / 2;
        yanchor = 'middle';
    }

    dims.outerLength = Math.ceil(dims.outerLength);
    dims.height = Math.ceil(dims.height);
    dims.lx = Math.round(dims.lx);
    dims.ly = Math.round(dims.ly);

    var marginOpts = {
        y: sliderOpts.y,
        b: dims.height * FROM_BR[yanchor],
        t: dims.height * FROM_TL[yanchor]
    };

    if(sliderOpts.lenmode === 'fraction') {
        marginOpts.l = 0;
        marginOpts.xl = sliderOpts.x - sliderOpts.len * FROM_TL[xanchor];
        marginOpts.r = 0;
        marginOpts.xr = sliderOpts.x + sliderOpts.len * FROM_BR[xanchor];
    }
    else {
        marginOpts.x = sliderOpts.x;
        marginOpts.l = dims.outerLength * FROM_TL[xanchor];
        marginOpts.r = dims.outerLength * FROM_BR[xanchor];
    }

    Plots.autoMargin(gd, autoMarginId(sliderOpts), marginOpts);
}

function drawSlider(gd, sliderGroup, sliderOpts) {
    // This is related to the other long notes in this file regarding what happens
    // when slider steps disappear. This particular fix handles what happens when
    // the *current* slider step is removed. The drawing functions will error out
    // when they fail to find it, so the fix for now is that it will just draw the
    // slider in the first position but will not execute the command.
    if(!((sliderOpts.steps[sliderOpts.active] || {}).visible)) {
        sliderOpts.active = sliderOpts._visibleSteps[0]._index;
    }

    // These are carefully ordered for proper z-ordering:
    sliderGroup
        .call(drawCurrentValue, sliderOpts)
        .call(drawRail, sliderOpts)
        .call(drawLabelGroup, sliderOpts)
        .call(drawTicks, sliderOpts)
        .call(drawTouchRect, gd, sliderOpts)
        .call(drawGrip, gd, sliderOpts);

    var dims = sliderOpts._dims;

    // Position the rectangle:
    Drawing.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t);

    sliderGroup.call(setGripPosition, sliderOpts, false);
    sliderGroup.call(drawCurrentValue, sliderOpts);

}

function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) {
    if(!sliderOpts.currentvalue.visible) return;

    var dims = sliderOpts._dims;
    var x0, textAnchor;

    switch(sliderOpts.currentvalue.xanchor) {
        case 'right':
            // This is anchored left and adjusted by the width of the longest label
            // so that the prefix doesn't move. The goal of this is to emphasize
            // what's actually changing and make the update less distracting.
            x0 = dims.inputAreaLength - constants.currentValueInset - dims.currentValueMaxWidth;
            textAnchor = 'left';
            break;
        case 'center':
            x0 = dims.inputAreaLength * 0.5;
            textAnchor = 'middle';
            break;
        default:
            x0 = constants.currentValueInset;
            textAnchor = 'left';
    }

    var text = Lib.ensureSingle(sliderGroup, 'text', constants.labelClass, function(s) {
        s.classed('user-select-none', true)
            .attr({
                'text-anchor': textAnchor,
                'data-notex': 1
            });
    });

    var str = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : '';

    if(typeof valueOverride === 'string') {
        str += valueOverride;
    } else {
        var curVal = sliderOpts.steps[sliderOpts.active].label;
        var meta = sliderOpts._gd._fullLayout.meta;
        if(meta) {
            curVal = Lib.templateString(curVal, {meta: meta});
        }
        str += curVal;
    }

    if(sliderOpts.currentvalue.suffix) {
        str += sliderOpts.currentvalue.suffix;
    }

    text.call(Drawing.font, sliderOpts.currentvalue.font)
        .text(str)
        .call(svgTextUtils.convertToTspans, sliderOpts._gd);

    var lines = svgTextUtils.lineCount(text);

    var y0 = (dims.currentValueMaxLines + 1 - lines) *
        sliderOpts.currentvalue.font.size * LINE_SPACING;

    svgTextUtils.positionText(text, x0, y0);

    return text;
}

function drawGrip(sliderGroup, gd, sliderOpts) {
    var grip = Lib.ensureSingle(sliderGroup, 'rect', constants.gripRectClass, function(s) {
        s.call(attachGripEvents, gd, sliderGroup, sliderOpts)
            .style('pointer-events', 'all');
    });

    grip.attr({
        width: constants.gripWidth,
        height: constants.gripHeight,
        rx: constants.gripRadius,
        ry: constants.gripRadius,
    })
    .call(Color.stroke, sliderOpts.bordercolor)
    .call(Color.fill, sliderOpts.bgcolor)
    .style('stroke-width', sliderOpts.borderwidth + 'px');
}

function drawLabel(item, data, sliderOpts) {
    var text = Lib.ensureSingle(item, 'text', constants.labelClass, function(s) {
        s.classed('user-select-none', true)
            .attr({
                'text-anchor': 'middle',
                'data-notex': 1
            });
    });

    var tx = data.step.label;
    var meta = sliderOpts._gd._fullLayout.meta;
    if(meta) {
        tx = Lib.templateString(tx, {meta: meta});
    }

    text.call(Drawing.font, sliderOpts.font)
        .text(tx)
        .call(svgTextUtils.convertToTspans, sliderOpts._gd);

    return text;
}

function drawLabelGroup(sliderGroup, sliderOpts) {
    var labels = Lib.ensureSingle(sliderGroup, 'g', constants.labelsClass);
    var dims = sliderOpts._dims;

    var labelItems = labels.selectAll('g.' + constants.labelGroupClass)
        .data(dims.labelSteps);

    labelItems.enter().append('g')
        .classed(constants.labelGroupClass, true);

    labelItems.exit().remove();

    labelItems.each(function(d) {
        var item = d3.select(this);

        item.call(drawLabel, d, sliderOpts);

        Drawing.setTranslate(item,
            normalizedValueToPosition(sliderOpts, d.fraction),
            constants.tickOffset +
                sliderOpts.ticklen +
                // position is the baseline of the top line of text only, even
                // if the label spans multiple lines
                sliderOpts.font.size * LINE_SPACING +
                constants.labelOffset +
                dims.currentValueTotalHeight
        );
    });

}

function handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, doTransition) {
    var quantizedPosition = Math.round(normalizedPosition * (sliderOpts._stepCount - 1));
    var quantizedIndex = sliderOpts._visibleSteps[quantizedPosition]._index;

    if(quantizedIndex !== sliderOpts.active) {
        setActive(gd, sliderGroup, sliderOpts, quantizedIndex, true, doTransition);
    }
}

function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) {
    var previousActive = sliderOpts.active;
    sliderOpts.active = index;

    // due to templating, it's possible this slider doesn't even exist yet
    arrayEditor(gd.layout, constants.name, sliderOpts)
        .applyUpdate('active', index);

    var step = sliderOpts.steps[sliderOpts.active];

    sliderGroup.call(setGripPosition, sliderOpts, doTransition);
    sliderGroup.call(drawCurrentValue, sliderOpts);

    gd.emit('plotly_sliderchange', {
        slider: sliderOpts,
        step: sliderOpts.steps[sliderOpts.active],
        interaction: doCallback,
        previousActive: previousActive
    });

    if(step && step.method && doCallback) {
        if(sliderGroup._nextMethod) {
            // If we've already queued up an update, just overwrite it with the most recent:
            sliderGroup._nextMethod.step = step;
            sliderGroup._nextMethod.doCallback = doCallback;
            sliderGroup._nextMethod.doTransition = doTransition;
        } else {
            sliderGroup._nextMethod = {step: step, doCallback: doCallback, doTransition: doTransition};
            sliderGroup._nextMethodRaf = window.requestAnimationFrame(function() {
                var _step = sliderGroup._nextMethod.step;
                if(!_step.method) return;

                if(_step.execute) {
                    Plots.executeAPICommand(gd, _step.method, _step.args);
                }

                sliderGroup._nextMethod = null;
                sliderGroup._nextMethodRaf = null;
            });
        }
    }
}

function attachGripEvents(item, gd, sliderGroup) {
    var node = sliderGroup.node();
    var $gd = d3.select(gd);

    // NB: This is *not* the same as sliderOpts itself! These callbacks
    // are in a closure so this array won't actually be correct if the
    // steps have changed since this was initialized. The sliderGroup,
    // however, has not changed since that *is* the slider, so it must
    // be present to receive mouse events.
    function getSliderOpts() {
        return sliderGroup.data()[0];
    }

    item.on('mousedown', function() {
        var sliderOpts = getSliderOpts();
        gd.emit('plotly_sliderstart', {slider: sliderOpts});

        var grip = sliderGroup.select('.' + constants.gripRectClass);

        d3.event.stopPropagation();
        d3.event.preventDefault();
        grip.call(Color.fill, sliderOpts.activebgcolor);

        var normalizedPosition = positionToNormalizedValue(sliderOpts, d3.mouse(node)[0]);
        handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true);
        sliderOpts._dragging = true;

        $gd.on('mousemove', function() {
            var sliderOpts = getSliderOpts();
            var normalizedPosition = positionToNormalizedValue(sliderOpts, d3.mouse(node)[0]);
            handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, false);
        });

        $gd.on('mouseup', function() {
            var sliderOpts = getSliderOpts();
            sliderOpts._dragging = false;
            grip.call(Color.fill, sliderOpts.bgcolor);
            $gd.on('mouseup', null);
            $gd.on('mousemove', null);

            gd.emit('plotly_sliderend', {
                slider: sliderOpts,
                step: sliderOpts.steps[sliderOpts.active]
            });
        });
    });
}

function drawTicks(sliderGroup, sliderOpts) {
    var tick = sliderGroup.selectAll('rect.' + constants.tickRectClass)
        .data(sliderOpts._visibleSteps);
    var dims = sliderOpts._dims;

    tick.enter().append('rect')
        .classed(constants.tickRectClass, true);

    tick.exit().remove();

    tick.attr({
        width: sliderOpts.tickwidth + 'px',
        'shape-rendering': 'crispEdges'
    });

    tick.each(function(d, i) {
        var isMajor = i % dims.labelStride === 0;
        var item = d3.select(this);

        item
            .attr({height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen})
            .call(Color.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor);

        Drawing.setTranslate(item,
            normalizedValueToPosition(sliderOpts, i / (sliderOpts._stepCount - 1)) - 0.5 * sliderOpts.tickwidth,
            (isMajor ? constants.tickOffset : constants.minorTickOffset) + dims.currentValueTotalHeight
        );
    });

}

function computeLabelSteps(sliderOpts) {
    var dims = sliderOpts._dims;
    dims.labelSteps = [];
    var nsteps = sliderOpts._stepCount;

    for(var i = 0; i < nsteps; i += dims.labelStride) {
        dims.labelSteps.push({
            fraction: i / (nsteps - 1),
            step: sliderOpts._visibleSteps[i]
        });
    }
}

function setGripPosition(sliderGroup, sliderOpts, doTransition) {
    var grip = sliderGroup.select('rect.' + constants.gripRectClass);

    var quantizedIndex = 0;
    for(var i = 0; i < sliderOpts._stepCount; i++) {
        if(sliderOpts._visibleSteps[i]._index === sliderOpts.active) {
            quantizedIndex = i;
            break;
        }
    }

    var x = normalizedValueToPosition(sliderOpts, quantizedIndex / (sliderOpts._stepCount - 1));

    // If this is true, then *this component* is already invoking its own command
    // and has triggered its own animation.
    if(sliderOpts._invokingCommand) return;

    var el = grip;
    if(doTransition && sliderOpts.transition.duration > 0) {
        el = el.transition()
            .duration(sliderOpts.transition.duration)
            .ease(sliderOpts.transition.easing);
    }

    // Drawing.setTranslate doesn't work here becasue of the transition duck-typing.
    // It's also not necessary because there are no other transitions to preserve.
    el.attr('transform', 'translate(' + (x - constants.gripWidth * 0.5) + ',' + (sliderOpts._dims.currentValueTotalHeight) + ')');
}

// Convert a number from [0-1] to a pixel position relative to the slider group container:
function normalizedValueToPosition(sliderOpts, normalizedPosition) {
    var dims = sliderOpts._dims;
    return dims.inputAreaStart + constants.stepInset +
        (dims.inputAreaLength - 2 * constants.stepInset) * Math.min(1, Math.max(0, normalizedPosition));
}

// Convert a position relative to the slider group to a nubmer in [0, 1]
function positionToNormalizedValue(sliderOpts, position) {
    var dims = sliderOpts._dims;
    return Math.min(1, Math.max(0, (position - constants.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * constants.stepInset - 2 * dims.inputAreaStart)));
}

function drawTouchRect(sliderGroup, gd, sliderOpts) {
    var dims = sliderOpts._dims;
    var rect = Lib.ensureSingle(sliderGroup, 'rect', constants.railTouchRectClass, function(s) {
        s.call(attachGripEvents, gd, sliderGroup, sliderOpts)
            .style('pointer-events', 'all');
    });

    rect.attr({
        width: dims.inputAreaLength,
        height: Math.max(dims.inputAreaWidth, constants.tickOffset + sliderOpts.ticklen + dims.labelHeight)
    })
        .call(Color.fill, sliderOpts.bgcolor)
        .attr('opacity', 0);

    Drawing.setTranslate(rect, 0, dims.currentValueTotalHeight);
}

function drawRail(sliderGroup, sliderOpts) {
    var dims = sliderOpts._dims;
    var computedLength = dims.inputAreaLength - constants.railInset * 2;
    var rect = Lib.ensureSingle(sliderGroup, 'rect', constants.railRectClass);

    rect.attr({
        width: computedLength,
        height: constants.railWidth,
        rx: constants.railRadius,
        ry: constants.railRadius,
        'shape-rendering': 'crispEdges'
    })
    .call(Color.stroke, sliderOpts.bordercolor)
    .call(Color.fill, sliderOpts.bgcolor)
    .style('stroke-width', sliderOpts.borderwidth + 'px');

    Drawing.setTranslate(rect,
        constants.railInset,
        (dims.inputAreaWidth - constants.railWidth) * 0.5 + dims.currentValueTotalHeight
    );
}

},{"../../constants/alignment":669,"../../lib":697,"../../lib/svg_text_utils":721,"../../plot_api/plot_template":735,"../../plots/plots":807,"../color":574,"../drawing":595,"./constants":658,"d3":151}],661:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var constants = _dereq_('./constants');

module.exports = {
    moduleType: 'component',
    name: constants.name,

    layoutAttributes: _dereq_('./attributes'),
    supplyLayoutDefaults: _dereq_('./defaults'),

    draw: _dereq_('./draw')
};

},{"./attributes":657,"./constants":658,"./defaults":659,"./draw":660}],662:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');

var Plots = _dereq_('../../plots/plots');
var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Drawing = _dereq_('../drawing');
var Color = _dereq_('../color');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var interactConstants = _dereq_('../../constants/interactions');

module.exports = {
    draw: draw
};

var numStripRE = / [XY][0-9]* /;

/**
 * Titles - (re)draw titles on the axes and plot:
 * @param {DOM element} gd - the graphDiv
 * @param {string} titleClass - the css class of this title
 * @param {object} options - how and what to draw
 *      propContainer - the layout object containing `title` and `titlefont`
 *          attributes that apply to this title
 *      propName - the full name of the title property (for Plotly.relayout)
 *      [traceIndex] - include only if this property applies to one trace
 *          (such as a colorbar title) - then editing pipes to Plotly.restyle
 *          instead of Plotly.relayout
 *      placeholder - placeholder text for an empty editable title
 *      [avoid] {object} - include if this title should move to avoid other elements
 *          selection - d3 selection of elements to avoid
 *          side - which direction to move if there is a conflict
 *          [offsetLeft] - if these elements are subject to a translation
 *              wrt the title element
 *          [offsetTop]
 *      attributes {object} - position and alignment attributes
 *          x - pixels
 *          y - pixels
 *          text-anchor - start|middle|end
 *      transform {object} - how to transform the title after positioning
 *          rotate - degrees
 *          offset - shift up/down in the rotated frame (unused?)
 *      containerGroup - if an svg <g> element already exists to hold this
 *          title, include here. Otherwise it will go in fullLayout._infolayer
 *
 *  @return {selection} d3 selection of title container group
 */
function draw(gd, titleClass, options) {
    var cont = options.propContainer;
    var prop = options.propName;
    var placeholder = options.placeholder;
    var traceIndex = options.traceIndex;
    var avoid = options.avoid || {};
    var attributes = options.attributes;
    var transform = options.transform;
    var group = options.containerGroup;

    var fullLayout = gd._fullLayout;

    var opacity = 1;
    var isplaceholder = false;
    var title = cont.title;
    var txt = (title && title.text ? title.text : '').trim();

    var font = title && title.font ? title.font : {};
    var fontFamily = font.family;
    var fontSize = font.size;
    var fontColor = font.color;

    // only make this title editable if we positively identify its property
    // as one that has editing enabled.
    var editAttr;
    if(prop === 'title.text') editAttr = 'titleText';
    else if(prop.indexOf('axis') !== -1) editAttr = 'axisTitleText';
    else if(prop.indexOf('colorbar' !== -1)) editAttr = 'colorbarTitleText';
    var editable = gd._context.edits[editAttr];

    if(txt === '') opacity = 0;
    // look for placeholder text while stripping out numbers from eg X2, Y3
    // this is just for backward compatibility with the old version that had
    // "Click to enter X2 title" and may have gotten saved in some old plots,
    // we don't want this to show up when these are displayed.
    else if(txt.replace(numStripRE, ' % ') === placeholder.replace(numStripRE, ' % ')) {
        opacity = 0.2;
        isplaceholder = true;
        if(!editable) txt = '';
    }

    if(fullLayout.meta) {
        txt = Lib.templateString(txt, {meta: fullLayout.meta});
    }

    var elShouldExist = txt || editable;

    if(!group) {
        group = Lib.ensureSingle(fullLayout._infolayer, 'g', 'g-' + titleClass);
    }

    var el = group.selectAll('text')
        .data(elShouldExist ? [0] : []);
    el.enter().append('text');
    el.text(txt)
        // this is hacky, but convertToTspans uses the class
        // to determine whether to rotate mathJax...
        // so we need to clear out any old class and put the
        // correct one (only relevant for colorbars, at least
        // for now) - ie don't use .classed
        .attr('class', titleClass);
    el.exit().remove();

    if(!elShouldExist) return group;

    function titleLayout(titleEl) {
        Lib.syncOrAsync([drawTitle, scootTitle], titleEl);
    }

    function drawTitle(titleEl) {
        var transformVal;

        if(transform) {
            transformVal = '';
            if(transform.rotate) {
                transformVal += 'rotate(' + [transform.rotate, attributes.x, attributes.y] + ')';
            }
            if(transform.offset) {
                transformVal += 'translate(0, ' + transform.offset + ')';
            }
        } else {
            transformVal = null;
        }

        titleEl.attr('transform', transformVal);

        titleEl.style({
            'font-family': fontFamily,
            'font-size': d3.round(fontSize, 2) + 'px',
            fill: Color.rgb(fontColor),
            opacity: opacity * Color.opacity(fontColor),
            'font-weight': Plots.fontWeight
        })
        .attr(attributes)
        .call(svgTextUtils.convertToTspans, gd);

        return Plots.previousPromises(gd);
    }

    function scootTitle(titleElIn) {
        var titleGroup = d3.select(titleElIn.node().parentNode);

        if(avoid && avoid.selection && avoid.side && txt) {
            titleGroup.attr('transform', null);

            // move toward avoid.side (= left, right, top, bottom) if needed
            // can include pad (pixels, default 2)
            var shift = 0;
            var backside = {
                left: 'right',
                right: 'left',
                top: 'bottom',
                bottom: 'top'
            }[avoid.side];
            var shiftSign = (['left', 'top'].indexOf(avoid.side) !== -1) ?
                    -1 : 1;
            var pad = isNumeric(avoid.pad) ? avoid.pad : 2;
            var titlebb = Drawing.bBox(titleGroup.node());
            var paperbb = {
                left: 0,
                top: 0,
                right: fullLayout.width,
                bottom: fullLayout.height
            };
            var maxshift = avoid.maxShift || (
                (paperbb[avoid.side] - titlebb[avoid.side]) *
                ((avoid.side === 'left' || avoid.side === 'top') ? -1 : 1));
            // Prevent the title going off the paper
            if(maxshift < 0) shift = maxshift;
            else {
                // so we don't have to offset each avoided element,
                // give the title the opposite offset
                var offsetLeft = avoid.offsetLeft || 0;
                var offsetTop = avoid.offsetTop || 0;
                titlebb.left -= offsetLeft;
                titlebb.right -= offsetLeft;
                titlebb.top -= offsetTop;
                titlebb.bottom -= offsetTop;

                // iterate over a set of elements (avoid.selection)
                // to avoid collisions with
                avoid.selection.each(function() {
                    var avoidbb = Drawing.bBox(this);

                    if(Lib.bBoxIntersect(titlebb, avoidbb, pad)) {
                        shift = Math.max(shift, shiftSign * (
                            avoidbb[avoid.side] - titlebb[backside]) + pad);
                    }
                });
                shift = Math.min(maxshift, shift);
            }
            if(shift > 0 || maxshift < 0) {
                var shiftTemplate = {
                    left: [-shift, 0],
                    right: [shift, 0],
                    top: [0, -shift],
                    bottom: [0, shift]
                }[avoid.side];
                titleGroup.attr('transform',
                    'translate(' + shiftTemplate + ')');
            }
        }
    }

    el.call(titleLayout);

    function setPlaceholder() {
        opacity = 0;
        isplaceholder = true;
        el.text(placeholder)
            .on('mouseover.opacity', function() {
                d3.select(this).transition()
                    .duration(interactConstants.SHOW_PLACEHOLDER).style('opacity', 1);
            })
            .on('mouseout.opacity', function() {
                d3.select(this).transition()
                    .duration(interactConstants.HIDE_PLACEHOLDER).style('opacity', 0);
            });
    }

    if(editable) {
        if(!txt) setPlaceholder();
        else el.on('.opacity', null);

        el.call(svgTextUtils.makeEditable, {gd: gd})
            .on('edit', function(text) {
                if(traceIndex !== undefined) {
                    Registry.call('_guiRestyle', gd, prop, text, traceIndex);
                } else {
                    Registry.call('_guiRelayout', gd, prop, text);
                }
            })
            .on('cancel', function() {
                this.text(this.attr('data-unformatted'))
                    .call(titleLayout);
            })
            .on('input', function(d) {
                this.text(d || ' ')
                    .call(svgTextUtils.positionText, attributes.x, attributes.y);
            });
    }
    el.classed('js-placeholder', isplaceholder);

    return group;
}

},{"../../constants/interactions":673,"../../lib":697,"../../lib/svg_text_utils":721,"../../plots/plots":807,"../../registry":826,"../color":574,"../drawing":595,"d3":151,"fast-isnumeric":218}],663:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = _dereq_('../../plots/font_attributes');
var colorAttrs = _dereq_('../color/attributes');
var extendFlat = _dereq_('../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
var padAttrs = _dereq_('../../plots/pad_attributes');
var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;

var buttonsAttrs = templatedArray('button', {
    visible: {
        valType: 'boolean',
        
        
    },
    method: {
        valType: 'enumerated',
        values: ['restyle', 'relayout', 'animate', 'update', 'skip'],
        dflt: 'restyle',
        
        
    },
    args: {
        valType: 'info_array',
        
        freeLength: true,
        items: [
            {valType: 'any'},
            {valType: 'any'},
            {valType: 'any'}
        ],
        
    },
    label: {
        valType: 'string',
        
        dflt: '',
        
    },
    execute: {
        valType: 'boolean',
        
        dflt: true,
        
    }
});

module.exports = overrideAll(templatedArray('updatemenu', {
    _arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],

    visible: {
        valType: 'boolean',
        
        
    },

    type: {
        valType: 'enumerated',
        values: ['dropdown', 'buttons'],
        dflt: 'dropdown',
        
        
    },

    direction: {
        valType: 'enumerated',
        values: ['left', 'right', 'up', 'down'],
        dflt: 'down',
        
        
    },

    active: {
        valType: 'integer',
        
        min: -1,
        dflt: 0,
        
    },

    showactive: {
        valType: 'boolean',
        
        dflt: true,
        
    },

    buttons: buttonsAttrs,

    x: {
        valType: 'number',
        min: -2,
        max: 3,
        dflt: -0.05,
        
        
    },
    xanchor: {
        valType: 'enumerated',
        values: ['auto', 'left', 'center', 'right'],
        dflt: 'right',
        
        
    },
    y: {
        valType: 'number',
        min: -2,
        max: 3,
        dflt: 1,
        
        
    },
    yanchor: {
        valType: 'enumerated',
        values: ['auto', 'top', 'middle', 'bottom'],
        dflt: 'top',
        
        
    },

    pad: extendFlat(padAttrs({editType: 'arraydraw'}), {
        
    }),

    font: fontAttrs({
        
    }),

    bgcolor: {
        valType: 'color',
        
        
    },
    bordercolor: {
        valType: 'color',
        dflt: colorAttrs.borderLine,
        
        
    },
    borderwidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'arraydraw',
        
    }
}), 'arraydraw', 'from-root');

},{"../../lib/extend":687,"../../plot_api/edit_types":728,"../../plot_api/plot_template":735,"../../plots/font_attributes":771,"../../plots/pad_attributes":806,"../color/attributes":573}],664:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


module.exports = {

    // layout attribute name
    name: 'updatemenus',

    // class names
    containerClassName: 'updatemenu-container',
    headerGroupClassName: 'updatemenu-header-group',
    headerClassName: 'updatemenu-header',
    headerArrowClassName: 'updatemenu-header-arrow',
    dropdownButtonGroupClassName: 'updatemenu-dropdown-button-group',
    dropdownButtonClassName: 'updatemenu-dropdown-button',
    buttonClassName: 'updatemenu-button',
    itemRectClassName: 'updatemenu-item-rect',
    itemTextClassName: 'updatemenu-item-text',

    // DOM attribute name in button group keeping track
    // of active update menu
    menuIndexAttrName: 'updatemenu-active-index',

    // id root pass to Plots.autoMargin
    autoMarginIdRoot: 'updatemenu-',

    // options when 'active: -1'
    blankHeaderOpts: { label: '  ' },

    // min item width / height
    minWidth: 30,
    minHeight: 30,

    // padding around item text
    textPadX: 24,
    arrowPadX: 16,

    // item rect radii
    rx: 2,
    ry: 2,

    // item  text x offset off left edge
    textOffsetX: 12,

    // item  text y offset (w.r.t. middle)
    textOffsetY: 3,

    // arrow offset off right edge
    arrowOffsetX: 4,

    // gap between header and buttons
    gapButtonHeader: 5,

    // gap between between buttons
    gapButton: 2,

    // color given to active buttons
    activeColor: '#F4FAFF',

    // color given to hovered buttons
    hoverColor: '#F4FAFF',

    // symbol for menu open arrow
    arrowSymbol: {
        left: '◄',
        right: '►',
        up: '▲',
        down: '▼'
    }
};

},{}],665:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');

var attributes = _dereq_('./attributes');
var constants = _dereq_('./constants');

var name = constants.name;
var buttonAttrs = attributes.buttons;


module.exports = function updateMenusDefaults(layoutIn, layoutOut) {
    var opts = {
        name: name,
        handleItemDefaults: menuDefaults
    };

    handleArrayContainerDefaults(layoutIn, layoutOut, opts);
};

function menuDefaults(menuIn, menuOut, layoutOut) {

    function coerce(attr, dflt) {
        return Lib.coerce(menuIn, menuOut, attributes, attr, dflt);
    }

    var buttons = handleArrayContainerDefaults(menuIn, menuOut, {
        name: 'buttons',
        handleItemDefaults: buttonDefaults
    });

    var visible = coerce('visible', buttons.length > 0);
    if(!visible) return;

    coerce('active');
    coerce('direction');
    coerce('type');
    coerce('showactive');

    coerce('x');
    coerce('y');
    Lib.noneOrAll(menuIn, menuOut, ['x', 'y']);

    coerce('xanchor');
    coerce('yanchor');

    coerce('pad.t');
    coerce('pad.r');
    coerce('pad.b');
    coerce('pad.l');

    Lib.coerceFont(coerce, 'font', layoutOut.font);

    coerce('bgcolor', layoutOut.paper_bgcolor);
    coerce('bordercolor');
    coerce('borderwidth');
}

function buttonDefaults(buttonIn, buttonOut) {
    function coerce(attr, dflt) {
        return Lib.coerce(buttonIn, buttonOut, buttonAttrs, attr, dflt);
    }

    var visible = coerce('visible',
        (buttonIn.method === 'skip' || Array.isArray(buttonIn.args)));
    if(visible) {
        coerce('method');
        coerce('args');
        coerce('label');
        coerce('execute');
    }
}

},{"../../lib":697,"../../plots/array_container_defaults":741,"./attributes":663,"./constants":664}],666:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

var Plots = _dereq_('../../plots/plots');
var Color = _dereq_('../color');
var Drawing = _dereq_('../drawing');
var Lib = _dereq_('../../lib');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var arrayEditor = _dereq_('../../plot_api/plot_template').arrayEditor;

var LINE_SPACING = _dereq_('../../constants/alignment').LINE_SPACING;

var constants = _dereq_('./constants');
var ScrollBox = _dereq_('./scrollbox');

module.exports = function draw(gd) {
    var fullLayout = gd._fullLayout;
    var menuData = Lib.filterVisible(fullLayout[constants.name]);

    /* Update menu data is bound to the header-group.
     * The items in the header group are always present.
     *
     * Upon clicking on a header its corresponding button
     * data is bound to the button-group.
     *
     * We draw all headers in one group before all buttons
     * so that the buttons *always* appear above the headers.
     *
     * Note that only one set of buttons are visible at once.
     *
     * <g container />
     *
     *     <g header-group />
     *         <g item header />
     *         <text item header-arrow />
     *     <g header-group />
     *         <g item header />
     *         <text item header-arrow />
     *     ...
     *
     *     <g button-group />
     *         <g item button />
     *         <g item button />
     *         ...
     */

    function clearAutoMargin(menuOpts) {
        Plots.autoMargin(gd, autoMarginId(menuOpts));
    }

    // draw update menu container
    var menus = fullLayout._menulayer
        .selectAll('g.' + constants.containerClassName)
        .data(menuData.length > 0 ? [0] : []);

    menus.enter().append('g')
        .classed(constants.containerClassName, true)
        .style('cursor', 'pointer');

    menus.exit().each(function() {
        // Most components don't need to explicitly remove autoMargin, because
        // marginPushers does this - but updatemenu updates don't go through
        // a full replot so we need to explicitly remove it.
        // This is for removing *all* updatemenus, removing individuals is
        // handled below, in headerGroups.exit
        d3.select(this).selectAll('g.' + constants.headerGroupClassName)
            .each(clearAutoMargin);
    }).remove();

    // return early if no update menus are visible
    if(menuData.length === 0) return;

    // join header group
    var headerGroups = menus.selectAll('g.' + constants.headerGroupClassName)
        .data(menuData, keyFunction);

    headerGroups.enter().append('g')
        .classed(constants.headerGroupClassName, true);

    // draw dropdown button container
    var gButton = Lib.ensureSingle(menus, 'g', constants.dropdownButtonGroupClassName, function(s) {
        s.style('pointer-events', 'all');
    });

    // find dimensions before plotting anything (this mutates menuOpts)
    for(var i = 0; i < menuData.length; i++) {
        var menuOpts = menuData[i];
        findDimensions(gd, menuOpts);
    }

    // setup scrollbox
    var scrollBoxId = 'updatemenus' + fullLayout._uid;
    var scrollBox = new ScrollBox(gd, gButton, scrollBoxId);

    // remove exiting header, remove dropped buttons and reset margins
    if(headerGroups.enter().size()) {
        // make sure gButton is on top of all headers
        gButton.node().parentNode.appendChild(gButton.node());
        gButton.call(removeAllButtons);
    }

    headerGroups.exit().each(function(menuOpts) {
        gButton.call(removeAllButtons);
        clearAutoMargin(menuOpts);
    }).remove();

    // draw headers!
    headerGroups.each(function(menuOpts) {
        var gHeader = d3.select(this);

        var _gButton = menuOpts.type === 'dropdown' ? gButton : null;
        Plots.manageCommandObserver(gd, menuOpts, menuOpts.buttons, function(data) {
            setActive(gd, menuOpts, menuOpts.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true);
        });

        if(menuOpts.type === 'dropdown') {
            drawHeader(gd, gHeader, gButton, scrollBox, menuOpts);

            // if this menu is active, update the dropdown container
            if(isActive(gButton, menuOpts)) {
                drawButtons(gd, gHeader, gButton, scrollBox, menuOpts);
            }
        } else {
            drawButtons(gd, gHeader, null, null, menuOpts);
        }

    });
};

// Note that '_index' is set at the default step,
// it corresponds to the menu index in the user layout update menu container.
// Because a menu can be set invisible,
// this is a more 'consistent' field than the index in the menuData.
function keyFunction(menuOpts) {
    return menuOpts._index;
}

function isFolded(gButton) {
    return +gButton.attr(constants.menuIndexAttrName) === -1;
}

function isActive(gButton, menuOpts) {
    return +gButton.attr(constants.menuIndexAttrName) === menuOpts._index;
}

function setActive(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) {
    // update 'active' attribute in menuOpts
    menuOpts.active = buttonIndex;

    // due to templating, it's possible this slider doesn't even exist yet
    arrayEditor(gd.layout, constants.name, menuOpts)
        .applyUpdate('active', buttonIndex);

    if(menuOpts.type === 'buttons') {
        drawButtons(gd, gHeader, null, null, menuOpts);
    }
    else if(menuOpts.type === 'dropdown') {
        // fold up buttons and redraw header
        gButton.attr(constants.menuIndexAttrName, '-1');

        drawHeader(gd, gHeader, gButton, scrollBox, menuOpts);

        if(!isSilentUpdate) {
            drawButtons(gd, gHeader, gButton, scrollBox, menuOpts);
        }
    }
}

function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) {
    var header = Lib.ensureSingle(gHeader, 'g', constants.headerClassName, function(s) {
        s.style('pointer-events', 'all');
    });

    var dims = menuOpts._dims;
    var active = menuOpts.active;
    var headerOpts = menuOpts.buttons[active] || constants.blankHeaderOpts;
    var posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 };
    var positionOverrides = {
        width: dims.headerWidth,
        height: dims.headerHeight
    };

    header
        .call(drawItem, menuOpts, headerOpts, gd)
        .call(setItemPosition, menuOpts, posOpts, positionOverrides);

    // draw drop arrow at the right edge
    var arrow = Lib.ensureSingle(gHeader, 'text', constants.headerArrowClassName, function(s) {
        s.classed('user-select-none', true)
            .attr('text-anchor', 'end')
            .call(Drawing.font, menuOpts.font)
            .text(constants.arrowSymbol[menuOpts.direction]);
    });

    arrow.attr({
        x: dims.headerWidth - constants.arrowOffsetX + menuOpts.pad.l,
        y: dims.headerHeight / 2 + constants.textOffsetY + menuOpts.pad.t
    });

    header.on('click', function() {
        gButton.call(removeAllButtons,
            String(isActive(gButton, menuOpts) ? -1 : menuOpts._index)
        );

        drawButtons(gd, gHeader, gButton, scrollBox, menuOpts);
    });

    header.on('mouseover', function() {
        header.call(styleOnMouseOver);
    });

    header.on('mouseout', function() {
        header.call(styleOnMouseOut, menuOpts);
    });

    // translate header group
    Drawing.setTranslate(gHeader, dims.lx, dims.ly);
}

function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) {
    // If this is a set of buttons, set pointer events = all since we play
    // some minor games with which container is which in order to simplify
    // the drawing of *either* buttons or menus
    if(!gButton) {
        gButton = gHeader;
        gButton.attr('pointer-events', 'all');
    }

    var buttonData = (!isFolded(gButton) || menuOpts.type === 'buttons') ?
        menuOpts.buttons :
        [];

    var klass = menuOpts.type === 'dropdown' ? constants.dropdownButtonClassName : constants.buttonClassName;

    var buttons = gButton.selectAll('g.' + klass)
        .data(Lib.filterVisible(buttonData));

    var enter = buttons.enter().append('g')
        .classed(klass, true);

    var exit = buttons.exit();

    if(menuOpts.type === 'dropdown') {
        enter.attr('opacity', '0')
            .transition()
            .attr('opacity', '1');

        exit.transition()
            .attr('opacity', '0')
            .remove();
    } else {
        exit.remove();
    }

    var x0 = 0;
    var y0 = 0;
    var dims = menuOpts._dims;

    var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1;

    if(menuOpts.type === 'dropdown') {
        if(isVertical) {
            y0 = dims.headerHeight + constants.gapButtonHeader;
        } else {
            x0 = dims.headerWidth + constants.gapButtonHeader;
        }
    }

    if(menuOpts.type === 'dropdown' && menuOpts.direction === 'up') {
        y0 = -constants.gapButtonHeader + constants.gapButton - dims.openHeight;
    }

    if(menuOpts.type === 'dropdown' && menuOpts.direction === 'left') {
        x0 = -constants.gapButtonHeader + constants.gapButton - dims.openWidth;
    }

    var posOpts = {
        x: dims.lx + x0 + menuOpts.pad.l,
        y: dims.ly + y0 + menuOpts.pad.t,
        yPad: constants.gapButton,
        xPad: constants.gapButton,
        index: 0,
    };

    var scrollBoxPosition = {
        l: posOpts.x + menuOpts.borderwidth,
        t: posOpts.y + menuOpts.borderwidth
    };

    buttons.each(function(buttonOpts, buttonIndex) {
        var button = d3.select(this);

        button
            .call(drawItem, menuOpts, buttonOpts, gd)
            .call(setItemPosition, menuOpts, posOpts);

        button.on('click', function() {
            // skip `dragend` events
            if(d3.event.defaultPrevented) return;

            setActive(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex);

            if(buttonOpts.execute) {
                Plots.executeAPICommand(gd, buttonOpts.method, buttonOpts.args);
            }

            gd.emit('plotly_buttonclicked', {menu: menuOpts, button: buttonOpts, active: menuOpts.active});
        });

        button.on('mouseover', function() {
            button.call(styleOnMouseOver);
        });

        button.on('mouseout', function() {
            button.call(styleOnMouseOut, menuOpts);
            buttons.call(styleButtons, menuOpts);
        });
    });

    buttons.call(styleButtons, menuOpts);

    if(isVertical) {
        scrollBoxPosition.w = Math.max(dims.openWidth, dims.headerWidth);
        scrollBoxPosition.h = posOpts.y - scrollBoxPosition.t;
    }
    else {
        scrollBoxPosition.w = posOpts.x - scrollBoxPosition.l;
        scrollBoxPosition.h = Math.max(dims.openHeight, dims.headerHeight);
    }

    scrollBoxPosition.direction = menuOpts.direction;

    if(scrollBox) {
        if(buttons.size()) {
            drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, scrollBoxPosition);
        }
        else {
            hideScrollBox(scrollBox);
        }
    }
}

function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) {
    // enable the scrollbox
    var direction = menuOpts.direction;
    var isVertical = (direction === 'up' || direction === 'down');
    var dims = menuOpts._dims;

    var active = menuOpts.active;
    var translateX, translateY;
    var i;
    if(isVertical) {
        translateY = 0;
        for(i = 0; i < active; i++) {
            translateY += dims.heights[i] + constants.gapButton;
        }
    }
    else {
        translateX = 0;
        for(i = 0; i < active; i++) {
            translateX += dims.widths[i] + constants.gapButton;
        }
    }

    scrollBox.enable(position, translateX, translateY);

    if(scrollBox.hbar) {
        scrollBox.hbar
            .attr('opacity', '0')
            .transition()
            .attr('opacity', '1');
    }

    if(scrollBox.vbar) {
        scrollBox.vbar
            .attr('opacity', '0')
            .transition()
            .attr('opacity', '1');
    }
}

function hideScrollBox(scrollBox) {
    var hasHBar = !!scrollBox.hbar;
    var hasVBar = !!scrollBox.vbar;

    if(hasHBar) {
        scrollBox.hbar
            .transition()
            .attr('opacity', '0')
            .each('end', function() {
                hasHBar = false;
                if(!hasVBar) scrollBox.disable();
            });
    }

    if(hasVBar) {
        scrollBox.vbar
            .transition()
            .attr('opacity', '0')
            .each('end', function() {
                hasVBar = false;
                if(!hasHBar) scrollBox.disable();
            });
    }
}

function drawItem(item, menuOpts, itemOpts, gd) {
    item.call(drawItemRect, menuOpts)
        .call(drawItemText, menuOpts, itemOpts, gd);
}

function drawItemRect(item, menuOpts) {
    var rect = Lib.ensureSingle(item, 'rect', constants.itemRectClassName, function(s) {
        s.attr({
            rx: constants.rx,
            ry: constants.ry,
            'shape-rendering': 'crispEdges'
        });
    });

    rect.call(Color.stroke, menuOpts.bordercolor)
        .call(Color.fill, menuOpts.bgcolor)
        .style('stroke-width', menuOpts.borderwidth + 'px');
}

function drawItemText(item, menuOpts, itemOpts, gd) {
    var text = Lib.ensureSingle(item, 'text', constants.itemTextClassName, function(s) {
        s.classed('user-select-none', true)
            .attr({
                'text-anchor': 'start',
                'data-notex': 1
            });
    });

    var tx = itemOpts.label;
    var meta = gd._fullLayout.meta;
    if(meta) {
        tx = Lib.templateString(tx, {meta: meta});
    }

    text.call(Drawing.font, menuOpts.font)
        .text(tx)
        .call(svgTextUtils.convertToTspans, gd);
}

function styleButtons(buttons, menuOpts) {
    var active = menuOpts.active;

    buttons.each(function(buttonOpts, i) {
        var button = d3.select(this);

        if(i === active && menuOpts.showactive) {
            button.select('rect.' + constants.itemRectClassName)
                .call(Color.fill, constants.activeColor);
        }
    });
}

function styleOnMouseOver(item) {
    item.select('rect.' + constants.itemRectClassName)
        .call(Color.fill, constants.hoverColor);
}

function styleOnMouseOut(item, menuOpts) {
    item.select('rect.' + constants.itemRectClassName)
        .call(Color.fill, menuOpts.bgcolor);
}

// find item dimensions (this mutates menuOpts)
function findDimensions(gd, menuOpts) {
    var dims = menuOpts._dims = {
        width1: 0,
        height1: 0,
        heights: [],
        widths: [],
        totalWidth: 0,
        totalHeight: 0,
        openWidth: 0,
        openHeight: 0,
        lx: 0,
        ly: 0
    };

    var fakeButtons = Drawing.tester.selectAll('g.' + constants.dropdownButtonClassName)
        .data(Lib.filterVisible(menuOpts.buttons));

    fakeButtons.enter().append('g')
        .classed(constants.dropdownButtonClassName, true);

    var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1;

    // loop over fake buttons to find width / height
    fakeButtons.each(function(buttonOpts, i) {
        var button = d3.select(this);

        button.call(drawItem, menuOpts, buttonOpts, gd);

        var text = button.select('.' + constants.itemTextClassName);

        // width is given by max width of all buttons
        var tWidth = text.node() && Drawing.bBox(text.node()).width;
        var wEff = Math.max(tWidth + constants.textPadX, constants.minWidth);

        // height is determined by item text
        var tHeight = menuOpts.font.size * LINE_SPACING;
        var tLines = svgTextUtils.lineCount(text);
        var hEff = Math.max(tHeight * tLines, constants.minHeight) + constants.textOffsetY;

        hEff = Math.ceil(hEff);
        wEff = Math.ceil(wEff);

        // Store per-item sizes since a row of horizontal buttons, for example,
        // don't all need to be the same width:
        dims.widths[i] = wEff;
        dims.heights[i] = hEff;

        // Height and width of individual element:
        dims.height1 = Math.max(dims.height1, hEff);
        dims.width1 = Math.max(dims.width1, wEff);

        if(isVertical) {
            dims.totalWidth = Math.max(dims.totalWidth, wEff);
            dims.openWidth = dims.totalWidth;
            dims.totalHeight += hEff + constants.gapButton;
            dims.openHeight += hEff + constants.gapButton;
        } else {
            dims.totalWidth += wEff + constants.gapButton;
            dims.openWidth += wEff + constants.gapButton;
            dims.totalHeight = Math.max(dims.totalHeight, hEff);
            dims.openHeight = dims.totalHeight;
        }
    });

    if(isVertical) {
        dims.totalHeight -= constants.gapButton;
    } else {
        dims.totalWidth -= constants.gapButton;
    }


    dims.headerWidth = dims.width1 + constants.arrowPadX;
    dims.headerHeight = dims.height1;

    if(menuOpts.type === 'dropdown') {
        if(isVertical) {
            dims.width1 += constants.arrowPadX;
            dims.totalHeight = dims.height1;
        } else {
            dims.totalWidth = dims.width1;
        }
        dims.totalWidth += constants.arrowPadX;
    }

    fakeButtons.remove();

    var paddedWidth = dims.totalWidth + menuOpts.pad.l + menuOpts.pad.r;
    var paddedHeight = dims.totalHeight + menuOpts.pad.t + menuOpts.pad.b;

    var graphSize = gd._fullLayout._size;
    dims.lx = graphSize.l + graphSize.w * menuOpts.x;
    dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y);

    var xanchor = 'left';
    if(Lib.isRightAnchor(menuOpts)) {
        dims.lx -= paddedWidth;
        xanchor = 'right';
    }
    if(Lib.isCenterAnchor(menuOpts)) {
        dims.lx -= paddedWidth / 2;
        xanchor = 'center';
    }

    var yanchor = 'top';
    if(Lib.isBottomAnchor(menuOpts)) {
        dims.ly -= paddedHeight;
        yanchor = 'bottom';
    }
    if(Lib.isMiddleAnchor(menuOpts)) {
        dims.ly -= paddedHeight / 2;
        yanchor = 'middle';
    }

    dims.totalWidth = Math.ceil(dims.totalWidth);
    dims.totalHeight = Math.ceil(dims.totalHeight);
    dims.lx = Math.round(dims.lx);
    dims.ly = Math.round(dims.ly);

    Plots.autoMargin(gd, autoMarginId(menuOpts), {
        x: menuOpts.x,
        y: menuOpts.y,
        l: paddedWidth * ({right: 1, center: 0.5}[xanchor] || 0),
        r: paddedWidth * ({left: 1, center: 0.5}[xanchor] || 0),
        b: paddedHeight * ({top: 1, middle: 0.5}[yanchor] || 0),
        t: paddedHeight * ({bottom: 1, middle: 0.5}[yanchor] || 0)
    });
}

function autoMarginId(menuOpts) {
    return constants.autoMarginIdRoot + menuOpts._index;
}

// set item positions (mutates posOpts)
function setItemPosition(item, menuOpts, posOpts, overrideOpts) {
    overrideOpts = overrideOpts || {};
    var rect = item.select('.' + constants.itemRectClassName);
    var text = item.select('.' + constants.itemTextClassName);
    var borderWidth = menuOpts.borderwidth;
    var index = posOpts.index;
    var dims = menuOpts._dims;

    Drawing.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y);

    var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1;
    var finalHeight = overrideOpts.height || (isVertical ? dims.heights[index] : dims.height1);

    rect.attr({
        x: 0,
        y: 0,
        width: overrideOpts.width || (isVertical ? dims.width1 : dims.widths[index]),
        height: finalHeight
    });

    var tHeight = menuOpts.font.size * LINE_SPACING;
    var tLines = svgTextUtils.lineCount(text);
    var spanOffset = ((tLines - 1) * tHeight / 2);

    svgTextUtils.positionText(text, constants.textOffsetX,
        finalHeight / 2 - spanOffset + constants.textOffsetY);

    if(isVertical) {
        posOpts.y += dims.heights[index] + posOpts.yPad;
    } else {
        posOpts.x += dims.widths[index] + posOpts.xPad;
    }

    posOpts.index++;
}

function removeAllButtons(gButton, newMenuIndexAttr) {
    gButton
        .attr(constants.menuIndexAttrName, newMenuIndexAttr || '-1')
        .selectAll('g.' + constants.dropdownButtonClassName).remove();
}

},{"../../constants/alignment":669,"../../lib":697,"../../lib/svg_text_utils":721,"../../plot_api/plot_template":735,"../../plots/plots":807,"../color":574,"../drawing":595,"./constants":664,"./scrollbox":668,"d3":151}],667:[function(_dereq_,module,exports){
arguments[4][661][0].apply(exports,arguments)
},{"./attributes":663,"./constants":664,"./defaults":665,"./draw":666,"dup":661}],668:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = ScrollBox;

var d3 = _dereq_('d3');

var Color = _dereq_('../color');
var Drawing = _dereq_('../drawing');

var Lib = _dereq_('../../lib');

/**
 * Helper class to setup a scroll box
 *
 * @class
 * @param           gd          Plotly's graph div
 * @param           container   Container to be scroll-boxed (as a D3 selection)
 * @param {string}  id          Id for the clip path to implement the scroll box
 */
function ScrollBox(gd, container, id) {
    this.gd = gd;
    this.container = container;
    this.id = id;

    // See ScrollBox.prototype.enable for further definition
    this.position = null;  // scrollbox position
    this.translateX = null;  // scrollbox horizontal translation
    this.translateY = null;  // scrollbox vertical translation
    this.hbar = null;  // horizontal scrollbar D3 selection
    this.vbar = null;  // vertical scrollbar D3 selection

    // <rect> element to capture pointer events
    this.bg = this.container.selectAll('rect.scrollbox-bg').data([0]);

    this.bg.exit()
        .on('.drag', null)
        .on('wheel', null)
        .remove();

    this.bg.enter().append('rect')
        .classed('scrollbox-bg', true)
        .style('pointer-events', 'all')
        .attr({
            opacity: 0,
            x: 0,
            y: 0,
            width: 0,
            height: 0
        });
}

// scroll bar dimensions
ScrollBox.barWidth = 2;
ScrollBox.barLength = 20;
ScrollBox.barRadius = 2;
ScrollBox.barPad = 1;
ScrollBox.barColor = '#808BA4';

/**
 * If needed, setup a clip path and scrollbars
 *
 * @method
 * @param {Object}  position
 * @param {number}  position.l  Left side position (in pixels)
 * @param {number}  position.t  Top side (in pixels)
 * @param {number}  position.w  Width (in pixels)
 * @param {number}  position.h  Height (in pixels)
 * @param {string}  [position.direction='down']
 *                  Either 'down', 'left', 'right' or 'up'
 * @param {number}  [translateX=0]  Horizontal offset (in pixels)
 * @param {number}  [translateY=0]  Vertical offset (in pixels)
 */
ScrollBox.prototype.enable = function enable(position, translateX, translateY) {
    var fullLayout = this.gd._fullLayout;
    var fullWidth = fullLayout.width;
    var fullHeight = fullLayout.height;

    // compute position of scrollbox
    this.position = position;

    var l = this.position.l;
    var w = this.position.w;
    var t = this.position.t;
    var h = this.position.h;
    var direction = this.position.direction;
    var isDown = (direction === 'down');
    var isLeft = (direction === 'left');
    var isRight = (direction === 'right');
    var isUp = (direction === 'up');
    var boxW = w;
    var boxH = h;
    var boxL, boxR;
    var boxT, boxB;

    if(!isDown && !isLeft && !isRight && !isUp) {
        this.position.direction = 'down';
        isDown = true;
    }

    var isVertical = isDown || isUp;
    if(isVertical) {
        boxL = l;
        boxR = boxL + boxW;

        if(isDown) {
            // anchor to top side
            boxT = t;
            boxB = Math.min(boxT + boxH, fullHeight);
            boxH = boxB - boxT;
        }
        else {
            // anchor to bottom side
            boxB = t + boxH;
            boxT = Math.max(boxB - boxH, 0);
            boxH = boxB - boxT;
        }
    }
    else {
        boxT = t;
        boxB = boxT + boxH;

        if(isLeft) {
            // anchor to right side
            boxR = l + boxW;
            boxL = Math.max(boxR - boxW, 0);
            boxW = boxR - boxL;
        }
        else {
            // anchor to left side
            boxL = l;
            boxR = Math.min(boxL + boxW, fullWidth);
            boxW = boxR - boxL;
        }
    }

    this._box = {
        l: boxL,
        t: boxT,
        w: boxW,
        h: boxH
    };

    // compute position of horizontal scroll bar
    var needsHorizontalScrollBar = (w > boxW);
    var hbarW = ScrollBox.barLength + 2 * ScrollBox.barPad;
    var hbarH = ScrollBox.barWidth + 2 * ScrollBox.barPad;
    // draw horizontal scrollbar on the bottom side
    var hbarL = l;
    var hbarT = t + h;

    if(hbarT + hbarH > fullHeight) hbarT = fullHeight - hbarH;

    var hbar = this.container.selectAll('rect.scrollbar-horizontal').data(
            (needsHorizontalScrollBar) ? [0] : []);

    hbar.exit()
        .on('.drag', null)
        .remove();

    hbar.enter().append('rect')
        .classed('scrollbar-horizontal', true)
        .call(Color.fill, ScrollBox.barColor);

    if(needsHorizontalScrollBar) {
        this.hbar = hbar.attr({
            'rx': ScrollBox.barRadius,
            'ry': ScrollBox.barRadius,
            'x': hbarL,
            'y': hbarT,
            'width': hbarW,
            'height': hbarH
        });

        // hbar center moves between hbarXMin and hbarXMin + hbarTranslateMax
        this._hbarXMin = hbarL + hbarW / 2;
        this._hbarTranslateMax = boxW - hbarW;
    }
    else {
        delete this.hbar;
        delete this._hbarXMin;
        delete this._hbarTranslateMax;
    }

    // compute position of vertical scroll bar
    var needsVerticalScrollBar = (h > boxH);
    var vbarW = ScrollBox.barWidth + 2 * ScrollBox.barPad;
    var vbarH = ScrollBox.barLength + 2 * ScrollBox.barPad;
    // draw vertical scrollbar on the right side
    var vbarL = l + w;
    var vbarT = t;

    if(vbarL + vbarW > fullWidth) vbarL = fullWidth - vbarW;

    var vbar = this.container.selectAll('rect.scrollbar-vertical').data(
            (needsVerticalScrollBar) ? [0] : []);

    vbar.exit()
        .on('.drag', null)
        .remove();

    vbar.enter().append('rect')
        .classed('scrollbar-vertical', true)
        .call(Color.fill, ScrollBox.barColor);

    if(needsVerticalScrollBar) {
        this.vbar = vbar.attr({
            'rx': ScrollBox.barRadius,
            'ry': ScrollBox.barRadius,
            'x': vbarL,
            'y': vbarT,
            'width': vbarW,
            'height': vbarH
        });

        // vbar center moves between vbarYMin and vbarYMin + vbarTranslateMax
        this._vbarYMin = vbarT + vbarH / 2;
        this._vbarTranslateMax = boxH - vbarH;
    }
    else {
        delete this.vbar;
        delete this._vbarYMin;
        delete this._vbarTranslateMax;
    }

    // setup a clip path (if scroll bars are needed)
    var clipId = this.id;
    var clipL = boxL - 0.5;
    var clipR = (needsVerticalScrollBar) ? boxR + vbarW + 0.5 : boxR + 0.5;
    var clipT = boxT - 0.5;
    var clipB = (needsHorizontalScrollBar) ? boxB + hbarH + 0.5 : boxB + 0.5;

    var clipPath = fullLayout._topdefs.selectAll('#' + clipId)
        .data((needsHorizontalScrollBar || needsVerticalScrollBar) ? [0] : []);

    clipPath.exit().remove();

    clipPath.enter()
        .append('clipPath').attr('id', clipId)
        .append('rect');

    if(needsHorizontalScrollBar || needsVerticalScrollBar) {
        this._clipRect = clipPath.select('rect').attr({
            x: Math.floor(clipL),
            y: Math.floor(clipT),
            width: Math.ceil(clipR) - Math.floor(clipL),
            height: Math.ceil(clipB) - Math.floor(clipT)
        });

        this.container.call(Drawing.setClipUrl, clipId, this.gd);

        this.bg.attr({
            x: l,
            y: t,
            width: w,
            height: h
        });
    }
    else {
        this.bg.attr({
            width: 0,
            height: 0
        });
        this.container
            .on('wheel', null)
            .on('.drag', null)
            .call(Drawing.setClipUrl, null);
        delete this._clipRect;
    }

    // set up drag listeners (if scroll bars are needed)
    if(needsHorizontalScrollBar || needsVerticalScrollBar) {
        var onBoxDrag = d3.behavior.drag()
            .on('dragstart', function() {
                d3.event.sourceEvent.preventDefault();
            })
            .on('drag', this._onBoxDrag.bind(this));

        this.container
            .on('wheel', null)
            .on('wheel', this._onBoxWheel.bind(this))
            .on('.drag', null)
            .call(onBoxDrag);

        var onBarDrag = d3.behavior.drag()
            .on('dragstart', function() {
                d3.event.sourceEvent.preventDefault();
                d3.event.sourceEvent.stopPropagation();
            })
            .on('drag', this._onBarDrag.bind(this));

        if(needsHorizontalScrollBar) {
            this.hbar
                .on('.drag', null)
                .call(onBarDrag);
        }

        if(needsVerticalScrollBar) {
            this.vbar
                .on('.drag', null)
                .call(onBarDrag);
        }
    }

    // set scrollbox translation
    this.setTranslate(translateX, translateY);
};

/**
 * If present, remove clip-path and scrollbars
 *
 * @method
 */
ScrollBox.prototype.disable = function disable() {
    if(this.hbar || this.vbar) {
        this.bg.attr({
            width: 0,
            height: 0
        });
        this.container
            .on('wheel', null)
            .on('.drag', null)
            .call(Drawing.setClipUrl, null);
        delete this._clipRect;
    }

    if(this.hbar) {
        this.hbar.on('.drag', null);
        this.hbar.remove();
        delete this.hbar;
        delete this._hbarXMin;
        delete this._hbarTranslateMax;
    }

    if(this.vbar) {
        this.vbar.on('.drag', null);
        this.vbar.remove();
        delete this.vbar;
        delete this._vbarYMin;
        delete this._vbarTranslateMax;
    }
};

/**
 * Handles scroll box drag events
 *
 * @method
 */
ScrollBox.prototype._onBoxDrag = function onBarDrag() {
    var translateX = this.translateX;
    var translateY = this.translateY;

    if(this.hbar) {
        translateX -= d3.event.dx;
    }

    if(this.vbar) {
        translateY -= d3.event.dy;
    }

    this.setTranslate(translateX, translateY);
};

/**
 * Handles scroll box wheel events
 *
 * @method
 */
ScrollBox.prototype._onBoxWheel = function onBarWheel() {
    var translateX = this.translateX;
    var translateY = this.translateY;

    if(this.hbar) {
        translateX += d3.event.deltaY;
    }

    if(this.vbar) {
        translateY += d3.event.deltaY;
    }

    this.setTranslate(translateX, translateY);
};

/**
 * Handles scroll bar drag events
 *
 * @method
 */
ScrollBox.prototype._onBarDrag = function onBarDrag() {
    var translateX = this.translateX;
    var translateY = this.translateY;

    if(this.hbar) {
        var xMin = translateX + this._hbarXMin;
        var xMax = xMin + this._hbarTranslateMax;
        var x = Lib.constrain(d3.event.x, xMin, xMax);
        var xf = (x - xMin) / (xMax - xMin);

        var translateXMax = this.position.w - this._box.w;

        translateX = xf * translateXMax;
    }

    if(this.vbar) {
        var yMin = translateY + this._vbarYMin;
        var yMax = yMin + this._vbarTranslateMax;
        var y = Lib.constrain(d3.event.y, yMin, yMax);
        var yf = (y - yMin) / (yMax - yMin);

        var translateYMax = this.position.h - this._box.h;

        translateY = yf * translateYMax;
    }

    this.setTranslate(translateX, translateY);
};

/**
 * Set clip path and scroll bar translate transform
 *
 * @method
 * @param {number}  [translateX=0]  Horizontal offset (in pixels)
 * @param {number}  [translateY=0]  Vertical offset (in pixels)
 */
ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) {
    // store translateX and translateY (needed by mouse event handlers)
    var translateXMax = this.position.w - this._box.w;
    var translateYMax = this.position.h - this._box.h;

    translateX = Lib.constrain(translateX || 0, 0, translateXMax);
    translateY = Lib.constrain(translateY || 0, 0, translateYMax);

    this.translateX = translateX;
    this.translateY = translateY;

    this.container.call(Drawing.setTranslate,
        this._box.l - this.position.l - translateX,
        this._box.t - this.position.t - translateY);

    if(this._clipRect) {
        this._clipRect.attr({
            x: Math.floor(this.position.l + translateX - 0.5),
            y: Math.floor(this.position.t + translateY - 0.5)
        });
    }

    if(this.hbar) {
        var xf = translateX / translateXMax;

        this.hbar.call(Drawing.setTranslate,
            translateX + xf * this._hbarTranslateMax,
            translateY);
    }

    if(this.vbar) {
        var yf = translateY / translateYMax;

        this.vbar.call(Drawing.setTranslate,
            translateX,
            translateY + yf * this._vbarTranslateMax);
    }
};

},{"../../lib":697,"../color":574,"../drawing":595,"d3":151}],669:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// fraction of some size to get to a named position
module.exports = {
    // from bottom left: this is the origin of our paper-reference
    // positioning system
    FROM_BL: {
        left: 0,
        center: 0.5,
        right: 1,
        bottom: 0,
        middle: 0.5,
        top: 1
    },
    // from top left: this is the screen pixel positioning origin
    FROM_TL: {
        left: 0,
        center: 0.5,
        right: 1,
        bottom: 1,
        middle: 0.5,
        top: 0
    },
    // from bottom right: sometimes you just need the opposite of ^^
    FROM_BR: {
        left: 1,
        center: 0.5,
        right: 0,
        bottom: 0,
        middle: 0.5,
        top: 1
    },
    // multiple of fontSize to get the vertical offset between lines
    LINE_SPACING: 1.3,

    // multiple of fontSize to shift from the baseline
    // to the cap (captical letter) line
    // (to use when we don't calculate this shift from Drawing.bBox)
    // This is an approximation since in reality cap height can differ
    // from font to font. However, according to Wikipedia
    //   an "average" font might have a cap height of 70% of the em
    // https://en.wikipedia.org/wiki/Em_(typography)#History
    CAP_SHIFT: 0.70,

    // half the cap height (distance between baseline and cap line)
    // of an "average" font (for more info see above).
    MID_SHIFT: 0.35,

    OPPOSITE_SIDE: {
        left: 'right',
        right: 'left',
        top: 'bottom',
        bottom: 'top'
    }
};

},{}],670:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    COMPARISON_OPS: ['=', '!=', '<', '>=', '>', '<='],
    COMPARISON_OPS2: ['=', '<', '>=', '>', '<='],
    INTERVAL_OPS: ['[]', '()', '[)', '(]', '][', ')(', '](', ')['],
    SET_OPS: ['{}', '}{'],
    CONSTRAINT_REDUCTION: {
        // for contour constraints, open/closed endpoints are equivalent
        '=': '=',

        '<': '<',
        '<=': '<',

        '>': '>',
        '>=': '>',

        '[]': '[]',
        '()': '[]',
        '[)': '[]',
        '(]': '[]',

        '][': '][',
        ')(': '][',
        '](': '][',
        ')[': ']['
    }
};

},{}],671:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = {
    solid: [[], 0],
    dot: [[0.5, 1], 200],
    dash: [[0.5, 1], 50],
    longdash: [[0.5, 1], 10],
    dashdot: [[0.5, 0.625, 0.875, 1], 50],
    longdashdot: [[0.5, 0.7, 0.8, 1], 10]
};

},{}],672:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = {
    circle: '●',
    'circle-open': '○',
    square: '■',
    'square-open': '□',
    diamond: '◆',
    'diamond-open': '◇',
    cross: '+',
    x: '❌'
};

},{}],673:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    /**
     * Timing information for interactive elements
     */
    SHOW_PLACEHOLDER: 100,
    HIDE_PLACEHOLDER: 1000,

    // ms between first mousedown and 2nd mouseup to constitute dblclick...
    // we don't seem to have access to the system setting
    DBLCLICKDELAY: 300,

    // opacity dimming fraction for points that are not in selection
    DESELECTDIM: 0.2
};

},{}],674:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    /**
     * Standardize all missing data in calcdata to use undefined
     * never null or NaN.
     * That way we can use !==undefined, or !== BADNUM,
     * to test for real data
     */
    BADNUM: undefined,

    /*
     * Limit certain operations to well below floating point max value
     * to avoid glitches: Make sure that even when you multiply it by the
     * number of pixels on a giant screen it still works
     */
    FP_SAFE: Number.MAX_VALUE / 10000,

    /*
     * conversion of date units to milliseconds
     * year and month constants are marked "AVG"
     * to remind us that not all years and months
     * have the same length
     */
    ONEAVGYEAR: 31557600000, // 365.25 days
    ONEAVGMONTH: 2629800000, // 1/12 of ONEAVGYEAR
    ONEDAY: 86400000,
    ONEHOUR: 3600000,
    ONEMIN: 60000,
    ONESEC: 1000,

    /*
     * For fast conversion btwn world calendars and epoch ms, the Julian Day Number
     * of the unix epoch. From calendars.instance().newDate(1970, 1, 1).toJD()
     */
    EPOCHJD: 2440587.5,

    /*
     * Are two values nearly equal? Compare to 1PPM
     */
    ALMOST_EQUAL: 1 - 1e-6,

    /*
     * If we're asked to clip a non-positive log value, how far off-screen
     * do we put it?
     */
    LOG_CLIP: 10,

    /*
     * not a number, but for displaying numbers: the "minus sign" symbol is
     * wider than the regular ascii dash "-"
     */
    MINUS_SIGN: '\u2212'
};

},{}],675:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


exports.xmlns = 'http://www.w3.org/2000/xmlns/';
exports.svg = 'http://www.w3.org/2000/svg';
exports.xlink = 'http://www.w3.org/1999/xlink';

// the 'old' d3 quirk got fix in v3.5.7
// https://github.com/mbostock/d3/commit/a6f66e9dd37f764403fc7c1f26be09ab4af24fed
exports.svgAttrs = {
    xmlns: exports.svg,
    'xmlns:xlink': exports.xlink
};

},{}],676:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// package version injected by `npm run preprocess`
exports.version = '1.45.3';

// inject promise polyfill
_dereq_('es6-promise').polyfill();

// inject plot css
_dereq_('../build/plotcss');

// inject default MathJax config
_dereq_('./fonts/mathjax_config')();

// include registry module and expose register method
var Registry = _dereq_('./registry');
var register = exports.register = Registry.register;

// expose plot api methods
var plotApi = _dereq_('./plot_api');
var methodNames = Object.keys(plotApi);
for(var i = 0; i < methodNames.length; i++) {
    var name = methodNames[i];
    // _ -> private API methods, but still registered for internal use
    if(name.charAt(0) !== '_') exports[name] = plotApi[name];
    register({
        moduleType: 'apiMethod',
        name: name,
        fn: plotApi[name]
    });
}

// scatter is the only trace included by default
register(_dereq_('./traces/scatter'));

// register all registrable components modules
register([
    _dereq_('./components/fx'),
    _dereq_('./components/legend'),
    _dereq_('./components/annotations'),
    _dereq_('./components/annotations3d'),
    _dereq_('./components/shapes'),
    _dereq_('./components/images'),
    _dereq_('./components/updatemenus'),
    _dereq_('./components/sliders'),
    _dereq_('./components/rangeslider'),
    _dereq_('./components/rangeselector'),
    _dereq_('./components/grid'),
    _dereq_('./components/errorbars'),
    _dereq_('./components/colorscale')
]);

// locales en and en-US are required for default behavior
register([
    _dereq_('./locale-en'),
    _dereq_('./locale-en-us')
]);

// plot icons
exports.Icons = _dereq_('../build/ploticon');

// unofficial 'beta' plot methods, use at your own risk
exports.Plots = _dereq_('./plots/plots');
exports.Fx = _dereq_('./components/fx');
exports.Snapshot = _dereq_('./snapshot');
exports.PlotSchema = _dereq_('./plot_api/plot_schema');
exports.Queue = _dereq_('./lib/queue');

// export d3 used in the bundle
exports.d3 = _dereq_('d3');

},{"../build/plotcss":1,"../build/ploticon":2,"./components/annotations":565,"./components/annotations3d":570,"./components/colorscale":586,"./components/errorbars":601,"./components/fx":613,"./components/grid":617,"./components/images":622,"./components/legend":630,"./components/rangeselector":641,"./components/rangeslider":648,"./components/shapes":656,"./components/sliders":661,"./components/updatemenus":667,"./fonts/mathjax_config":677,"./lib/queue":712,"./locale-en":726,"./locale-en-us":725,"./plot_api":730,"./plot_api/plot_schema":734,"./plots/plots":807,"./registry":826,"./snapshot":831,"./traces/scatter":1060,"d3":151,"es6-promise":207}],677:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/* global MathJax:false */

module.exports = function() {
    if(typeof MathJax !== 'undefined') {
        var globalConfig = (window.PlotlyConfig || {}).MathJaxConfig !== 'local';

        if(globalConfig) {
            MathJax.Hub.Config({
                messageStyle: 'none',
                skipStartupTypeset: true,
                displayAlign: 'left',
                tex2jax: {
                    inlineMath: [['$', '$'], ['\\(', '\\)']]
                }
            });
            MathJax.Hub.Configured();
        }
    }
};

},{}],678:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


/**
 * Determine the position anchor property of x/y xanchor/yanchor components.
 *
 * - values < 1/3 align the low side at that fraction,
 * - values [1/3, 2/3] align the center at that fraction,
 * - values > 2/3 align the right at that fraction.
 */


exports.isLeftAnchor = function isLeftAnchor(opts) {
    return (
      opts.xanchor === 'left' ||
      (opts.xanchor === 'auto' && opts.x <= 1 / 3)
    );
};

exports.isCenterAnchor = function isCenterAnchor(opts) {
    return (
        opts.xanchor === 'center' ||
        (opts.xanchor === 'auto' && opts.x > 1 / 3 && opts.x < 2 / 3)
    );
};

exports.isRightAnchor = function isRightAnchor(opts) {
    return (
      opts.xanchor === 'right' ||
      (opts.xanchor === 'auto' && opts.x >= 2 / 3)
    );
};

exports.isTopAnchor = function isTopAnchor(opts) {
    return (
        opts.yanchor === 'top' ||
        (opts.yanchor === 'auto' && opts.y >= 2 / 3)
    );
};

exports.isMiddleAnchor = function isMiddleAnchor(opts) {
    return (
        opts.yanchor === 'middle' ||
        (opts.yanchor === 'auto' && opts.y > 1 / 3 && opts.y < 2 / 3)
    );
};

exports.isBottomAnchor = function isBottomAnchor(opts) {
    return (
      opts.yanchor === 'bottom' ||
      (opts.yanchor === 'auto' && opts.y <= 1 / 3)
    );
};

},{}],679:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var modModule = _dereq_('./mod');
var mod = modModule.mod;
var modHalf = modModule.modHalf;

var PI = Math.PI;
var twoPI = 2 * PI;

function deg2rad(deg) { return deg / 180 * PI; }

function rad2deg(rad) { return rad / PI * 180; }

/**
 * is sector a full circle?
 * ... this comes up a lot in SVG path-drawing routines
 *
 * N.B. we consider all sectors that span more that 2pi 'full' circles
 *
 * @param {2-item array} aBnds : angular bounds in *radians*
 * @return {boolean}
 */
function isFullCircle(aBnds) {
    return Math.abs(aBnds[1] - aBnds[0]) > twoPI - 1e-15;
}

/**
 * angular delta between angle 'a' and 'b'
 * solution taken from: https://stackoverflow.com/a/2007279
 *
 * @param {number} a : first angle in *radians*
 * @param {number} b : second angle in *radians*
 * @return {number} angular delta in *radians*
 */
function angleDelta(a, b) {
    return modHalf(b - a, twoPI);
}

/**
 * angular distance between angle 'a' and 'b'
 *
 * @param {number} a : first angle in *radians*
 * @param {number} b : second angle in *radians*
 * @return {number} angular distance in *radians*
 */
function angleDist(a, b) {
    return Math.abs(angleDelta(a, b));
}

/**
 * is angle inside sector?
 *
 * @param {number} a : angle to test in *radians*
 * @param {2-item array} aBnds : sector's angular bounds in *radians*
 * @param {boolean}
 */
function isAngleInsideSector(a, aBnds) {
    if(isFullCircle(aBnds)) return true;

    var s0, s1;

    if(aBnds[0] < aBnds[1]) {
        s0 = aBnds[0];
        s1 = aBnds[1];
    } else {
        s0 = aBnds[1];
        s1 = aBnds[0];
    }

    s0 = mod(s0, twoPI);
    s1 = mod(s1, twoPI);
    if(s0 > s1) s1 += twoPI;

    var a0 = mod(a, twoPI);
    var a1 = a0 + twoPI;

    return (a0 >= s0 && a0 <= s1) || (a1 >= s0 && a1 <= s1);
}

/**
 * is pt (r,a) inside sector?
 *
 * @param {number} r : pt's radial coordinate
 * @param {number} a : pt's angular coordinate in *radians*
 * @param {2-item array} rBnds : sector's radial bounds
 * @param {2-item array} aBnds : sector's angular bounds in *radians*
 * @return {boolean}
 */
function isPtInsideSector(r, a, rBnds, aBnds) {
    if(!isAngleInsideSector(a, aBnds)) return false;

    var r0, r1;

    if(rBnds[0] < rBnds[1]) {
        r0 = rBnds[0];
        r1 = rBnds[1];
    } else {
        r0 = rBnds[1];
        r1 = rBnds[0];
    }

    return r >= r0 && r <= r1;
}

// common to pathArc, pathSector and pathAnnulus
function _path(r0, r1, a0, a1, cx, cy, isClosed) {
    cx = cx || 0;
    cy = cy || 0;

    var isCircle = isFullCircle([a0, a1]);
    var aStart, aMid, aEnd;
    var rStart, rEnd;

    if(isCircle) {
        aStart = 0;
        aMid = PI;
        aEnd = twoPI;
    } else {
        if(a0 < a1) {
            aStart = a0;
            aEnd = a1;
        } else {
            aStart = a1;
            aEnd = a0;
        }
    }

    if(r0 < r1) {
        rStart = r0;
        rEnd = r1;
    } else {
        rStart = r1;
        rEnd = r0;
    }

    // N.B. svg coordinates here, where y increases downward
    function pt(r, a) {
        return [r * Math.cos(a) + cx, cy - r * Math.sin(a)];
    }

    var largeArc = Math.abs(aEnd - aStart) <= PI ? 0 : 1;
    function arc(r, a, cw) {
        return 'A' + [r, r] + ' ' + [0, largeArc, cw] + ' ' + pt(r, a);
    }

    var p;

    if(isCircle) {
        if(rStart === null) {
            p = 'M' + pt(rEnd, aStart) +
                arc(rEnd, aMid, 0) +
                arc(rEnd, aEnd, 0) + 'Z';
        } else {
            p = 'M' + pt(rStart, aStart) +
                arc(rStart, aMid, 0) +
                arc(rStart, aEnd, 0) + 'Z' +
                'M' + pt(rEnd, aStart) +
                arc(rEnd, aMid, 1) +
                arc(rEnd, aEnd, 1) + 'Z';
        }
    } else {
        if(rStart === null) {
            p = 'M' + pt(rEnd, aStart) + arc(rEnd, aEnd, 0);
            if(isClosed) p += 'L0,0Z';
        } else {
            p = 'M' + pt(rStart, aStart) +
                'L' + pt(rEnd, aStart) +
                arc(rEnd, aEnd, 0) +
                'L' + pt(rStart, aEnd) +
                arc(rStart, aStart, 1) + 'Z';
        }
    }

    return p;
}

/**
 * path an arc
 *
 * @param {number} r : radius
 * @param {number} a0 : first angular coordinate in *radians*
 * @param {number} a1 : second angular coordinate in *radians*
 * @param {number (optional)} cx : x coordinate of center
 * @param {number (optional)} cy : y coordinate of center
 * @return {string} svg path
 */
function pathArc(r, a0, a1, cx, cy) {
    return _path(null, r, a0, a1, cx, cy, 0);
}

/**
 * path a sector
 *
 * @param {number} r : radius
 * @param {number} a0 : first angular coordinate in *radians*
 * @param {number} a1 : second angular coordinate in *radians*
 * @param {number (optional)} cx : x coordinate of center
 * @param {number (optional)} cy : y coordinate of center
 * @return {string} svg path
 */
function pathSector(r, a0, a1, cx, cy) {
    return _path(null, r, a0, a1, cx, cy, 1);
}

/**
 * path an annulus
 *
 * @param {number} r0 : first radial coordinate
 * @param {number} r1 : second radial coordinate
 * @param {number} a0 : first angular coordinate in *radians*
 * @param {number} a1 : second angular coordinate in *radians*
 * @param {number (optional)} cx : x coordinate of center
 * @param {number (optional)} cy : y coordinate of center
 * @return {string} svg path
 */
function pathAnnulus(r0, r1, a0, a1, cx, cy) {
    return _path(r0, r1, a0, a1, cx, cy, 1);
}

module.exports = {
    deg2rad: deg2rad,
    rad2deg: rad2deg,
    angleDelta: angleDelta,
    angleDist: angleDist,
    isFullCircle: isFullCircle,
    isAngleInsideSector: isAngleInsideSector,
    isPtInsideSector: isPtInsideSector,
    pathArc: pathArc,
    pathSector: pathSector,
    pathAnnulus: pathAnnulus
};

},{"./mod":704}],680:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isArray = Array.isArray;

// IE9 fallbacks

var ab = (typeof ArrayBuffer === 'undefined' || !ArrayBuffer.isView) ?
    {isView: function() { return false; }} :
    ArrayBuffer;

var dv = (typeof DataView === 'undefined') ?
    function() {} :
    DataView;

function isTypedArray(a) {
    return ab.isView(a) && !(a instanceof dv);
}
exports.isTypedArray = isTypedArray;

function isArrayOrTypedArray(a) {
    return isArray(a) || isTypedArray(a);
}
exports.isArrayOrTypedArray = isArrayOrTypedArray;

/*
 * Test whether an input object is 1D.
 *
 * Assumes we already know the object is an array.
 *
 * Looks only at the first element, if the dimensionality is
 * not consistent we won't figure that out here.
 */
function isArray1D(a) {
    return !isArrayOrTypedArray(a[0]);
}
exports.isArray1D = isArray1D;

/*
 * Ensures an array has the right amount of storage space. If it doesn't
 * exist, it creates an array. If it does exist, it returns it if too
 * short or truncates it in-place.
 *
 * The goal is to just reuse memory to avoid a bit of excessive garbage
 * collection.
 */
exports.ensureArray = function(out, n) {
    // TODO: typed array support here? This is only used in
    // traces/carpet/compute_control_points
    if(!isArray(out)) out = [];

    // If too long, truncate. (If too short, it will grow
    // automatically so we don't care about that case)
    out.length = n;

    return out;
};

/*
 * TypedArray-compatible concatenation of n arrays
 * if all arrays are the same type it will preserve that type,
 * otherwise it falls back on Array.
 * Also tries to avoid copying, in case one array has zero length
 * But never mutates an existing array
 */
exports.concat = function() {
    var args = [];
    var allArray = true;
    var totalLen = 0;

    var _constructor, arg0, i, argi, posi, leni, out, j;

    for(i = 0; i < arguments.length; i++) {
        argi = arguments[i];
        leni = argi.length;
        if(leni) {
            if(arg0) args.push(argi);
            else {
                arg0 = argi;
                posi = leni;
            }

            if(isArray(argi)) {
                _constructor = false;
            }
            else {
                allArray = false;
                if(!totalLen) {
                    _constructor = argi.constructor;
                }
                else if(_constructor !== argi.constructor) {
                    // TODO: in principle we could upgrade here,
                    // ie keep typed array but convert all to Float64Array?
                    _constructor = false;
                }
            }

            totalLen += leni;
        }
    }

    if(!totalLen) return [];
    if(!args.length) return arg0;

    if(allArray) return arg0.concat.apply(arg0, args);
    if(_constructor) {
        // matching typed arrays
        out = new _constructor(totalLen);
        out.set(arg0);
        for(i = 0; i < args.length; i++) {
            argi = args[i];
            out.set(argi, posi);
            posi += argi.length;
        }
        return out;
    }

    // mismatched types or Array + typed
    out = new Array(totalLen);
    for(j = 0; j < arg0.length; j++) out[j] = arg0[j];
    for(i = 0; i < args.length; i++) {
        argi = args[i];
        for(j = 0; j < argi.length; j++) out[posi + j] = argi[j];
        posi += j;
    }
    return out;
};

exports.maxRowLength = function(z) {
    return _rowLength(z, Math.max, 0);
};

exports.minRowLength = function(z) {
    return _rowLength(z, Math.min, Infinity);
};

function _rowLength(z, fn, len0) {
    if(isArrayOrTypedArray(z)) {
        if(isArrayOrTypedArray(z[0])) {
            var len = len0;
            for(var i = 0; i < z.length; i++) {
                len = fn(len, z[i].length);
            }
            return len;
        } else {
            return z.length;
        }
    }
    return 0;
}

},{}],681:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var BADNUM = _dereq_('../constants/numerical').BADNUM;

// precompile for speed
var JUNK = /^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g;

/**
 * cleanNumber: remove common leading and trailing cruft
 * Always returns either a number or BADNUM.
 */
module.exports = function cleanNumber(v) {
    if(typeof v === 'string') {
        v = v.replace(JUNK, '');
    }

    if(isNumeric(v)) return Number(v);

    return BADNUM;
};

},{"../constants/numerical":674,"fast-isnumeric":218}],682:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * Clear gl frame (if any). This is a common pattern as
 * we usually set `preserveDrawingBuffer: true` during
 * gl context creation (e.g. via `reglUtils.prepare`).
 *
 * @param {DOM node or object} gd : graph div object
 */
module.exports = function clearGlCanvases(gd) {
    var fullLayout = gd._fullLayout;

    if(fullLayout._glcanvas && fullLayout._glcanvas.size()) {
        fullLayout._glcanvas.each(function(d) {
            if(d.regl) d.regl.clear({color: true, depth: true});
        });
    }
};

},{}],683:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * Clear responsive handlers (if any).
 *
 * @param {DOM node or object} gd : graph div object
 */
module.exports = function clearResponsive(gd) {
    if(gd._responsiveChartHandler) {
        window.removeEventListener('resize', gd._responsiveChartHandler);
        delete gd._responsiveChartHandler;
    }
};

},{}],684:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var tinycolor = _dereq_('tinycolor2');

var baseTraceAttrs = _dereq_('../plots/attributes');
var scales = _dereq_('../components/colorscale/scales');
var DESELECTDIM = _dereq_('../constants/interactions').DESELECTDIM;

var nestedProperty = _dereq_('./nested_property');
var counterRegex = _dereq_('./regex').counter;
var modHalf = _dereq_('./mod').modHalf;
var isArrayOrTypedArray = _dereq_('./array').isArrayOrTypedArray;

exports.valObjectMeta = {
    data_array: {
        // You can use *dflt=[] to force said array to exist though.
        
        
        
        coerceFunction: function(v, propOut, dflt) {
            // TODO maybe `v: {type: 'float32', vals: [/* ... */]}` also
            if(isArrayOrTypedArray(v)) propOut.set(v);
            else if(dflt !== undefined) propOut.set(dflt);
        }
    },
    enumerated: {
        
        
        
        coerceFunction: function(v, propOut, dflt, opts) {
            if(opts.coerceNumber) v = +v;
            if(opts.values.indexOf(v) === -1) propOut.set(dflt);
            else propOut.set(v);
        },
        validateFunction: function(v, opts) {
            if(opts.coerceNumber) v = +v;

            var values = opts.values;
            for(var i = 0; i < values.length; i++) {
                var k = String(values[i]);

                if((k.charAt(0) === '/' && k.charAt(k.length - 1) === '/')) {
                    var regex = new RegExp(k.substr(1, k.length - 2));
                    if(regex.test(v)) return true;
                } else if(v === values[i]) return true;
            }
            return false;
        }
    },
    'boolean': {
        
        
        
        coerceFunction: function(v, propOut, dflt) {
            if(v === true || v === false) propOut.set(v);
            else propOut.set(dflt);
        }
    },
    number: {
        
        
        
        coerceFunction: function(v, propOut, dflt, opts) {
            if(!isNumeric(v) ||
                    (opts.min !== undefined && v < opts.min) ||
                    (opts.max !== undefined && v > opts.max)) {
                propOut.set(dflt);
            }
            else propOut.set(+v);
        }
    },
    integer: {
        
        
        
        coerceFunction: function(v, propOut, dflt, opts) {
            if(v % 1 || !isNumeric(v) ||
                    (opts.min !== undefined && v < opts.min) ||
                    (opts.max !== undefined && v > opts.max)) {
                propOut.set(dflt);
            }
            else propOut.set(+v);
        }
    },
    string: {
        
        
        // TODO 'values shouldn't be in there (edge case: 'dash' in Scatter)
        
        coerceFunction: function(v, propOut, dflt, opts) {
            if(typeof v !== 'string') {
                var okToCoerce = (typeof v === 'number');

                if(opts.strict === true || !okToCoerce) propOut.set(dflt);
                else propOut.set(String(v));
            }
            else if(opts.noBlank && !v) propOut.set(dflt);
            else propOut.set(v);
        }
    },
    color: {
        
        
        
        coerceFunction: function(v, propOut, dflt) {
            if(tinycolor(v).isValid()) propOut.set(v);
            else propOut.set(dflt);
        }
    },
    colorlist: {
        
        
        
        coerceFunction: function(v, propOut, dflt) {
            function isColor(color) {
                return tinycolor(color).isValid();
            }
            if(!Array.isArray(v) || !v.length) propOut.set(dflt);
            else if(v.every(isColor)) propOut.set(v);
            else propOut.set(dflt);
        }
    },
    colorscale: {
        
        
        
        coerceFunction: function(v, propOut, dflt) {
            propOut.set(scales.get(v, dflt));
        }
    },
    angle: {
        
        
        
        coerceFunction: function(v, propOut, dflt) {
            if(v === 'auto') propOut.set('auto');
            else if(!isNumeric(v)) propOut.set(dflt);
            else propOut.set(modHalf(+v, 360));
        }
    },
    subplotid: {
        
        
        
        coerceFunction: function(v, propOut, dflt, opts) {
            var regex = opts.regex || counterRegex(dflt);
            if(typeof v === 'string' && regex.test(v)) {
                propOut.set(v);
                return;
            }
            propOut.set(dflt);
        },
        validateFunction: function(v, opts) {
            var dflt = opts.dflt;

            if(v === dflt) return true;
            if(typeof v !== 'string') return false;
            if(counterRegex(dflt).test(v)) return true;

            return false;
        }
    },
    flaglist: {
        
        
        
        coerceFunction: function(v, propOut, dflt, opts) {
            if(typeof v !== 'string') {
                propOut.set(dflt);
                return;
            }
            if((opts.extras || []).indexOf(v) !== -1) {
                propOut.set(v);
                return;
            }
            var vParts = v.split('+');
            var i = 0;
            while(i < vParts.length) {
                var vi = vParts[i];
                if(opts.flags.indexOf(vi) === -1 || vParts.indexOf(vi) < i) {
                    vParts.splice(i, 1);
                }
                else i++;
            }
            if(!vParts.length) propOut.set(dflt);
            else propOut.set(vParts.join('+'));
        }
    },
    any: {
        
        
        
        coerceFunction: function(v, propOut, dflt) {
            if(v === undefined) propOut.set(dflt);
            else propOut.set(v);
        }
    },
    info_array: {
        
        
        // set `dimensions=2` for a 2D array or '1-2' for either
        // `items` may be a single object instead of an array, in which case
        // `freeLength` must be true.
        // if `dimensions='1-2'` and items is a 1D array, then the value can
        // either be a matching 1D array or an array of such matching 1D arrays
        
        coerceFunction: function(v, propOut, dflt, opts) {

            // simplified coerce function just for array items
            function coercePart(v, opts, dflt) {
                var out;
                var propPart = {set: function(v) { out = v; }};

                if(dflt === undefined) dflt = opts.dflt;

                exports.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts);

                return out;
            }

            var twoD = opts.dimensions === 2 || (opts.dimensions === '1-2' && Array.isArray(v) && Array.isArray(v[0]));

            if(!Array.isArray(v)) {
                propOut.set(dflt);
                return;
            }

            var items = opts.items;
            var vOut = [];
            var arrayItems = Array.isArray(items);
            var arrayItems2D = arrayItems && twoD && Array.isArray(items[0]);
            var innerItemsOnly = twoD && arrayItems && !arrayItems2D;
            var len = (arrayItems && !innerItemsOnly) ? items.length : v.length;

            var i, j, row, item, len2, vNew;

            dflt = Array.isArray(dflt) ? dflt : [];

            if(twoD) {
                for(i = 0; i < len; i++) {
                    vOut[i] = [];
                    row = Array.isArray(v[i]) ? v[i] : [];
                    if(innerItemsOnly) len2 = items.length;
                    else if(arrayItems) len2 = items[i].length;
                    else len2 = row.length;

                    for(j = 0; j < len2; j++) {
                        if(innerItemsOnly) item = items[j];
                        else if(arrayItems) item = items[i][j];
                        else item = items;

                        vNew = coercePart(row[j], item, (dflt[i] || [])[j]);
                        if(vNew !== undefined) vOut[i][j] = vNew;
                    }
                }
            }
            else {
                for(i = 0; i < len; i++) {
                    vNew = coercePart(v[i], arrayItems ? items[i] : items, dflt[i]);
                    if(vNew !== undefined) vOut[i] = vNew;
                }
            }

            propOut.set(vOut);
        },
        validateFunction: function(v, opts) {
            if(!Array.isArray(v)) return false;

            var items = opts.items;
            var arrayItems = Array.isArray(items);
            var twoD = opts.dimensions === 2;

            // when free length is off, input and declared lengths must match
            if(!opts.freeLength && v.length !== items.length) return false;

            // valid when all input items are valid
            for(var i = 0; i < v.length; i++) {
                if(twoD) {
                    if(!Array.isArray(v[i]) || (!opts.freeLength && v[i].length !== items[i].length)) {
                        return false;
                    }
                    for(var j = 0; j < v[i].length; j++) {
                        if(!validate(v[i][j], arrayItems ? items[i][j] : items)) {
                            return false;
                        }
                    }
                }
                else if(!validate(v[i], arrayItems ? items[i] : items)) return false;
            }

            return true;
        }
    }
};

/**
 * Ensures that container[attribute] has a valid value.
 *
 * attributes[attribute] is an object with possible keys:
 * - valType: data_array, enumerated, boolean, ... as in valObjectMeta
 * - values: (enumerated only) array of allowed vals
 * - min, max: (number, integer only) inclusive bounds on allowed vals
 *      either or both may be omitted
 * - dflt: if attribute is invalid or missing, use this default
 *      if dflt is provided as an argument to lib.coerce it takes precedence
 *      as a convenience, returns the value it finally set
 */
exports.coerce = function(containerIn, containerOut, attributes, attribute, dflt) {
    var opts = nestedProperty(attributes, attribute).get();
    var propIn = nestedProperty(containerIn, attribute);
    var propOut = nestedProperty(containerOut, attribute);
    var v = propIn.get();

    var template = containerOut._template;
    if(v === undefined && template) {
        v = nestedProperty(template, attribute).get();
        // already used the template value, so short-circuit the second check
        template = 0;
    }

    if(dflt === undefined) dflt = opts.dflt;

    /**
     * arrayOk: value MAY be an array, then we do no value checking
     * at this point, because it can be more complicated than the
     * individual form (eg. some array vals can be numbers, even if the
     * single values must be color strings)
     */
    if(opts.arrayOk && isArrayOrTypedArray(v)) {
        propOut.set(v);
        return v;
    }

    var coerceFunction = exports.valObjectMeta[opts.valType].coerceFunction;
    coerceFunction(v, propOut, dflt, opts);

    var out = propOut.get();
    // in case v was provided but invalid, try the template again so it still
    // overrides the regular default
    if(template && out === dflt && !validate(v, opts)) {
        v = nestedProperty(template, attribute).get();
        coerceFunction(v, propOut, dflt, opts);
        out = propOut.get();
    }
    return out;
};

/**
 * Variation on coerce
 *
 * Uses coerce to get attribute value if user input is valid,
 * returns attribute default if user input it not valid or
 * returns false if there is no user input.
 */
exports.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) {
    var propIn = nestedProperty(containerIn, attribute);
    var propOut = exports.coerce(containerIn, containerOut, attributes, attribute, dflt);
    var valIn = propIn.get();

    return (valIn !== undefined && valIn !== null) ? propOut : false;
};

/*
 * Shortcut to coerce the three font attributes
 *
 * 'coerce' is a lib.coerce wrapper with implied first three arguments
 */
exports.coerceFont = function(coerce, attr, dfltObj) {
    var out = {};

    dfltObj = dfltObj || {};

    out.family = coerce(attr + '.family', dfltObj.family);
    out.size = coerce(attr + '.size', dfltObj.size);
    out.color = coerce(attr + '.color', dfltObj.color);

    return out;
};

/** Coerce shortcut for 'hoverinfo'
 * handling 1-vs-multi-trace dflt logic
 *
 * @param {object} traceIn : user trace object
 * @param {object} traceOut : full trace object (requires _module ref)
 * @param {object} layoutOut : full layout object (require _dataLength ref)
 * @return {any} : the coerced value
 */
exports.coerceHoverinfo = function(traceIn, traceOut, layoutOut) {
    var moduleAttrs = traceOut._module.attributes;
    var attrs = moduleAttrs.hoverinfo ? moduleAttrs : baseTraceAttrs;

    var valObj = attrs.hoverinfo;
    var dflt;

    if(layoutOut._dataLength === 1) {
        var flags = valObj.dflt === 'all' ?
            valObj.flags.slice() :
            valObj.dflt.split('+');

        flags.splice(flags.indexOf('name'), 1);
        dflt = flags.join('+');
    }

    return exports.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt);
};

/** Coerce shortcut for [un]selected.marker.opacity,
 *  which has special default logic, to ensure that it corresponds to the
 *  default selection behavior while allowing to be overtaken by any other
 *  [un]selected attribute.
 *
 *  N.B. This must be called *after* coercing all the other [un]selected attrs,
 *  to give the intended result.
 *
 * @param {object} traceOut : fullData item
 * @param {function} coerce : lib.coerce wrapper with implied first three arguments
 */
exports.coerceSelectionMarkerOpacity = function(traceOut, coerce) {
    if(!traceOut.marker) return;

    var mo = traceOut.marker.opacity;
    // you can still have a `marker` container with no markers if there's text
    if(mo === undefined) return;

    var smoDflt;
    var usmoDflt;

    // Don't give [un]selected.marker.opacity a default value if
    // marker.opacity is an array: handle this during style step.
    //
    // Only give [un]selected.marker.opacity a default value if you don't
    // set any other [un]selected attributes.
    if(!isArrayOrTypedArray(mo) && !traceOut.selected && !traceOut.unselected) {
        smoDflt = mo;
        usmoDflt = DESELECTDIM * mo;
    }

    coerce('selected.marker.opacity', smoDflt);
    coerce('unselected.marker.opacity', usmoDflt);
};

function validate(value, opts) {
    var valObjectDef = exports.valObjectMeta[opts.valType];

    if(opts.arrayOk && isArrayOrTypedArray(value)) return true;

    if(valObjectDef.validateFunction) {
        return valObjectDef.validateFunction(value, opts);
    }

    var failed = {};
    var out = failed;
    var propMock = { set: function(v) { out = v; } };

    // 'failed' just something mutable that won't be === anything else

    valObjectDef.coerceFunction(value, propMock, failed, opts);
    return out !== failed;
}
exports.validate = validate;

},{"../components/colorscale/scales":589,"../constants/interactions":673,"../plots/attributes":742,"./array":680,"./mod":704,"./nested_property":705,"./regex":713,"fast-isnumeric":218,"tinycolor2":518}],685:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');

var Loggers = _dereq_('./loggers');
var mod = _dereq_('./mod').mod;

var constants = _dereq_('../constants/numerical');
var BADNUM = constants.BADNUM;
var ONEDAY = constants.ONEDAY;
var ONEHOUR = constants.ONEHOUR;
var ONEMIN = constants.ONEMIN;
var ONESEC = constants.ONESEC;
var EPOCHJD = constants.EPOCHJD;

var Registry = _dereq_('../registry');

var utcFormat = d3.time.format.utc;

var DATETIME_REGEXP = /^\s*(-?\d\d\d\d|\d\d)(-(\d?\d)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d:?\d\d)?)?)?)?)?\s*$/m;
// special regex for chinese calendars to support yyyy-mmi-dd etc for intercalary months
var DATETIME_REGEXP_CN = /^\s*(-?\d\d\d\d|\d\d)(-(\d?\di?)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d:?\d\d)?)?)?)?)?\s*$/m;

// for 2-digit years, the first year we map them onto
var YFIRST = new Date().getFullYear() - 70;

function isWorldCalendar(calendar) {
    return (
        calendar &&
        Registry.componentsRegistry.calendars &&
        typeof calendar === 'string' && calendar !== 'gregorian'
    );
}

/*
 * dateTick0: get the canonical tick for this calendar
 *
 * bool sunday is for week ticks, shift it to a Sunday.
 */
exports.dateTick0 = function(calendar, sunday) {
    if(isWorldCalendar(calendar)) {
        return sunday ?
            Registry.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] :
            Registry.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar];
    }
    else {
        return sunday ? '2000-01-02' : '2000-01-01';
    }
};

/*
 * dfltRange: for each calendar, give a valid default range
 */
exports.dfltRange = function(calendar) {
    if(isWorldCalendar(calendar)) {
        return Registry.getComponentMethod('calendars', 'DFLTRANGE')[calendar];
    }
    else {
        return ['2000-01-01', '2001-01-01'];
    }
};

// is an object a javascript date?
exports.isJSDate = function(v) {
    return typeof v === 'object' && v !== null && typeof v.getTime === 'function';
};

// The absolute limits of our date-time system
// This is a little weird: we use MIN_MS and MAX_MS in dateTime2ms
// but we use dateTime2ms to calculate them (after defining it!)
var MIN_MS, MAX_MS;

/**
 * dateTime2ms - turn a date object or string s into milliseconds
 * (relative to 1970-01-01, per javascript standard)
 * optional calendar (string) to use a non-gregorian calendar
 *
 * Returns BADNUM if it doesn't find a date
 *
 * strings should have the form:
 *
 *    -?YYYY-mm-dd<sep>HH:MM:SS.sss<tzInfo>?
 *
 * <sep>: space (our normal standard) or T or t (ISO-8601)
 * <tzInfo>: Z, z, or [+\-]HH:?MM and we THROW IT AWAY
 * this format comes from https://tools.ietf.org/html/rfc3339#section-5.6
 * but we allow it even with a space as the separator
 *
 * May truncate after any full field, and sss can be any length
 * even >3 digits, though javascript dates truncate to milliseconds,
 * we keep as much as javascript numeric precision can hold, but we only
 * report back up to 100 microsecond precision, because most dates support
 * this precision (close to 1970 support more, very far away support less)
 *
 * Expanded to support negative years to -9999 but you must always
 * give 4 digits, except for 2-digit positive years which we assume are
 * near the present time.
 * Note that we follow ISO 8601:2004: there *is* a year 0, which
 * is 1BC/BCE, and -1===2BC etc.
 *
 * World calendars: not all of these *have* agreed extensions to this full range,
 * if you have another calendar system but want a date range outside its validity,
 * you can use a gregorian date string prefixed with 'G' or 'g'.
 *
 * Where to cut off 2-digit years between 1900s and 2000s?
 * from http://support.microsoft.com/kb/244664:
 *   1930-2029 (the most retro of all...)
 * but in my mac chrome from eg. d=new Date(Date.parse('8/19/50')):
 *   1950-2049
 * by Java, from http://stackoverflow.com/questions/2024273/:
 *   now-80 - now+19
 * or FileMaker Pro, from
 *      http://www.filemaker.com/12help/html/add_view_data.4.21.html:
 *   now-70 - now+29
 * but python strptime etc, via
 *      http://docs.python.org/py3k/library/time.html:
 *   1969-2068 (super forward-looking, but static, not sliding!)
 *
 * lets go with now-70 to now+29, and if anyone runs into this problem
 * they can learn the hard way not to use 2-digit years, as no choice we
 * make now will cover all possibilities. mostly this will all be taken
 * care of in initial parsing, should only be an issue for hand-entered data
 * currently (2016) this range is:
 *   1946-2045
 */
exports.dateTime2ms = function(s, calendar) {
    // first check if s is a date object
    if(exports.isJSDate(s)) {
        // Convert to the UTC milliseconds that give the same
        // hours as this date has in the local timezone
        var tzOffset = s.getTimezoneOffset() * ONEMIN;
        var offsetTweak = (s.getUTCMinutes() - s.getMinutes()) * ONEMIN +
            (s.getUTCSeconds() - s.getSeconds()) * ONESEC +
            (s.getUTCMilliseconds() - s.getMilliseconds());

        if(offsetTweak) {
            var comb = 3 * ONEMIN;
            tzOffset = tzOffset - comb / 2 + mod(offsetTweak - tzOffset + comb / 2, comb);
        }
        s = Number(s) - tzOffset;
        if(s >= MIN_MS && s <= MAX_MS) return s;
        return BADNUM;
    }
    // otherwise only accept strings and numbers
    if(typeof s !== 'string' && typeof s !== 'number') return BADNUM;

    s = String(s);

    var isWorld = isWorldCalendar(calendar);

    // to handle out-of-range dates in international calendars, accept
    // 'G' as a prefix to force the built-in gregorian calendar.
    var s0 = s.charAt(0);
    if(isWorld && (s0 === 'G' || s0 === 'g')) {
        s = s.substr(1);
        calendar = '';
    }

    var isChinese = isWorld && calendar.substr(0, 7) === 'chinese';

    var match = s.match(isChinese ? DATETIME_REGEXP_CN : DATETIME_REGEXP);
    if(!match) return BADNUM;
    var y = match[1];
    var m = match[3] || '1';
    var d = Number(match[5] || 1);
    var H = Number(match[7] || 0);
    var M = Number(match[9] || 0);
    var S = Number(match[11] || 0);

    if(isWorld) {
        // disallow 2-digit years for world calendars
        if(y.length === 2) return BADNUM;
        y = Number(y);

        var cDate;
        try {
            var calInstance = Registry.getComponentMethod('calendars', 'getCal')(calendar);
            if(isChinese) {
                var isIntercalary = m.charAt(m.length - 1) === 'i';
                m = parseInt(m, 10);
                cDate = calInstance.newDate(y, calInstance.toMonthIndex(y, m, isIntercalary), d);
            }
            else {
                cDate = calInstance.newDate(y, Number(m), d);
            }
        }
        catch(e) { return BADNUM; } // Invalid ... date

        if(!cDate) return BADNUM;

        return ((cDate.toJD() - EPOCHJD) * ONEDAY) +
            (H * ONEHOUR) + (M * ONEMIN) + (S * ONESEC);
    }

    if(y.length === 2) {
        y = (Number(y) + 2000 - YFIRST) % 100 + YFIRST;
    }
    else y = Number(y);

    // new Date uses months from 0; subtract 1 here just so we
    // don't have to do it again during the validity test below
    m -= 1;

    // javascript takes new Date(0..99,m,d) to mean 1900-1999, so
    // to support years 0-99 we need to use setFullYear explicitly
    // Note that 2000 is a leap year.
    var date = new Date(Date.UTC(2000, m, d, H, M));
    date.setUTCFullYear(y);

    if(date.getUTCMonth() !== m) return BADNUM;
    if(date.getUTCDate() !== d) return BADNUM;

    return date.getTime() + S * ONESEC;
};

MIN_MS = exports.MIN_MS = exports.dateTime2ms('-9999');
MAX_MS = exports.MAX_MS = exports.dateTime2ms('9999-12-31 23:59:59.9999');

// is string s a date? (see above)
exports.isDateTime = function(s, calendar) {
    return (exports.dateTime2ms(s, calendar) !== BADNUM);
};

// pad a number with zeroes, to given # of digits before the decimal point
function lpad(val, digits) {
    return String(val + Math.pow(10, digits)).substr(1);
}

/**
 * Turn ms into string of the form YYYY-mm-dd HH:MM:SS.ssss
 * Crop any trailing zeros in time, except never stop right after hours
 * (we could choose to crop '-01' from date too but for now we always
 * show the whole date)
 * Optional range r is the data range that applies, also in ms.
 * If rng is big, the later parts of time will be omitted
 */
var NINETYDAYS = 90 * ONEDAY;
var THREEHOURS = 3 * ONEHOUR;
var FIVEMIN = 5 * ONEMIN;
exports.ms2DateTime = function(ms, r, calendar) {
    if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return BADNUM;

    if(!r) r = 0;

    var msecTenths = Math.floor(mod(ms + 0.05, 1) * 10);
    var msRounded = Math.round(ms - msecTenths / 10);
    var dateStr, h, m, s, msec10, d;

    if(isWorldCalendar(calendar)) {
        var dateJD = Math.floor(msRounded / ONEDAY) + EPOCHJD;
        var timeMs = Math.floor(mod(ms, ONEDAY));
        try {
            dateStr = Registry.getComponentMethod('calendars', 'getCal')(calendar)
                .fromJD(dateJD).formatDate('yyyy-mm-dd');
        } catch(e) {
            // invalid date in this calendar - fall back to Gyyyy-mm-dd
            dateStr = utcFormat('G%Y-%m-%d')(new Date(msRounded));
        }

        // yyyy does NOT guarantee 4-digit years. YYYY mostly does, but does
        // other things for a few calendars, so we can't trust it. Just pad
        // it manually (after the '-' if there is one)
        if(dateStr.charAt(0) === '-') {
            while(dateStr.length < 11) dateStr = '-0' + dateStr.substr(1);
        } else {
            while(dateStr.length < 10) dateStr = '0' + dateStr;
        }

        // TODO: if this is faster, we could use this block for extracting
        // the time components of regular gregorian too
        h = (r < NINETYDAYS) ? Math.floor(timeMs / ONEHOUR) : 0;
        m = (r < NINETYDAYS) ? Math.floor((timeMs % ONEHOUR) / ONEMIN) : 0;
        s = (r < THREEHOURS) ? Math.floor((timeMs % ONEMIN) / ONESEC) : 0;
        msec10 = (r < FIVEMIN) ? (timeMs % ONESEC) * 10 + msecTenths : 0;
    }
    else {
        d = new Date(msRounded);

        dateStr = utcFormat('%Y-%m-%d')(d);

        // <90 days: add hours and minutes - never *only* add hours
        h = (r < NINETYDAYS) ? d.getUTCHours() : 0;
        m = (r < NINETYDAYS) ? d.getUTCMinutes() : 0;
        // <3 hours: add seconds
        s = (r < THREEHOURS) ? d.getUTCSeconds() : 0;
        // <5 minutes: add ms (plus one extra digit, this is msec*10)
        msec10 = (r < FIVEMIN) ? d.getUTCMilliseconds() * 10 + msecTenths : 0;
    }

    return includeTime(dateStr, h, m, s, msec10);
};

// For converting old-style milliseconds to date strings,
// we use the local timezone rather than UTC like we use
// everywhere else, both for backward compatibility and
// because that's how people mostly use javasript date objects.
// Clip one extra day off our date range though so we can't get
// thrown beyond the range by the timezone shift.
exports.ms2DateTimeLocal = function(ms) {
    if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return BADNUM;

    var msecTenths = Math.floor(mod(ms + 0.05, 1) * 10);
    var d = new Date(Math.round(ms - msecTenths / 10));
    var dateStr = d3.time.format('%Y-%m-%d')(d);
    var h = d.getHours();
    var m = d.getMinutes();
    var s = d.getSeconds();
    var msec10 = d.getUTCMilliseconds() * 10 + msecTenths;

    return includeTime(dateStr, h, m, s, msec10);
};

function includeTime(dateStr, h, m, s, msec10) {
    // include each part that has nonzero data in or after it
    if(h || m || s || msec10) {
        dateStr += ' ' + lpad(h, 2) + ':' + lpad(m, 2);
        if(s || msec10) {
            dateStr += ':' + lpad(s, 2);
            if(msec10) {
                var digits = 4;
                while(msec10 % 10 === 0) {
                    digits -= 1;
                    msec10 /= 10;
                }
                dateStr += '.' + lpad(msec10, digits);
            }
        }
    }
    return dateStr;
}

// normalize date format to date string, in case it starts as
// a Date object or milliseconds
// optional dflt is the return value if cleaning fails
exports.cleanDate = function(v, dflt, calendar) {
    // let us use cleanDate to provide a missing default without an error
    if(v === BADNUM) return dflt;
    if(exports.isJSDate(v) || (typeof v === 'number' && isFinite(v))) {
        // do not allow milliseconds (old) or jsdate objects (inherently
        // described as gregorian dates) with world calendars
        if(isWorldCalendar(calendar)) {
            Loggers.error('JS Dates and milliseconds are incompatible with world calendars', v);
            return dflt;
        }

        // NOTE: if someone puts in a year as a number rather than a string,
        // this will mistakenly convert it thinking it's milliseconds from 1970
        // that is: '2012' -> Jan. 1, 2012, but 2012 -> 2012 epoch milliseconds
        v = exports.ms2DateTimeLocal(+v);
        if(!v && dflt !== undefined) return dflt;
    }
    else if(!exports.isDateTime(v, calendar)) {
        Loggers.error('unrecognized date', v);
        return dflt;
    }
    return v;
};

/*
 *  Date formatting for ticks and hovertext
 */

/*
 * modDateFormat: Support world calendars, and add one item to
 * d3's vocabulary:
 * %{n}f where n is the max number of digits of fractional seconds
 */
var fracMatch = /%\d?f/g;
function modDateFormat(fmt, x, formatter, calendar) {

    fmt = fmt.replace(fracMatch, function(match) {
        var digits = Math.min(+(match.charAt(1)) || 6, 6);
        var fracSecs = ((x / 1000 % 1) + 2)
            .toFixed(digits)
            .substr(2).replace(/0+$/, '') || '0';
        return fracSecs;
    });

    var d = new Date(Math.floor(x + 0.05));

    if(isWorldCalendar(calendar)) {
        try {
            fmt = Registry.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar);
        }
        catch(e) {
            return 'Invalid';
        }
    }
    return formatter(fmt)(d);
}

/*
 * formatTime: create a time string from:
 *   x: milliseconds
 *   tr: tickround ('M', 'S', or # digits)
 * only supports UTC times (where every day is 24 hours and 0 is at midnight)
 */
var MAXSECONDS = [59, 59.9, 59.99, 59.999, 59.9999];
function formatTime(x, tr) {
    var timePart = mod(x + 0.05, ONEDAY);

    var timeStr = lpad(Math.floor(timePart / ONEHOUR), 2) + ':' +
        lpad(mod(Math.floor(timePart / ONEMIN), 60), 2);

    if(tr !== 'M') {
        if(!isNumeric(tr)) tr = 0; // should only be 'S'

        /*
         * this is a weird one - and shouldn't come up unless people
         * monkey with tick0 in weird ways, but we need to do something!
         * IN PARTICULAR we had better not display garbage (see below)
         * for numbers we always round to the nearest increment of the
         * precision we're showing, and this seems like the right way to
         * handle seconds and milliseconds, as they have a decimal point
         * and people will interpret that to mean rounding like numbers.
         * but for larger increments we floor the value: it's always
         * 2013 until the ball drops on the new year. We could argue about
         * which field it is where we start rounding (should 12:08:59
         * round to 12:09 if we're stopping at minutes?) but for now I'll
         * say we round seconds but floor everything else. BUT that means
         * we need to never round up to 60 seconds, ie 23:59:60
         */
        var sec = Math.min(mod(x / ONESEC, 60), MAXSECONDS[tr]);

        var secStr = (100 + sec).toFixed(tr).substr(1);
        if(tr > 0) {
            secStr = secStr.replace(/0+$/, '').replace(/[\.]$/, '');
        }

        timeStr += ':' + secStr;
    }
    return timeStr;
}

/*
 * formatDate: turn a date into tick or hover label text.
 *
 *   x: milliseconds, the value to convert
 *   fmt: optional, an explicit format string (d3 format, even for world calendars)
 *   tr: tickround ('y', 'm', 'd', 'M', 'S', or # digits)
 *      used if no explicit fmt is provided
 *   formatter: locale-aware d3 date formatter for standard gregorian calendars
 *      should be the result of exports.getD3DateFormat(gd)
 *   calendar: optional string, the world calendar system to use
 *
 * returns the date/time as a string, potentially with the leading portion
 * on a separate line (after '\n')
 * Note that this means if you provide an explicit format which includes '\n'
 * the axis may choose to strip things after it when they don't change from
 * one tick to the next (as it does with automatic formatting)
 */
exports.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) {
    calendar = isWorldCalendar(calendar) && calendar;

    if(!fmt) {
        if(tr === 'y') fmt = extraFormat.year;
        else if(tr === 'm') fmt = extraFormat.month;
        else if(tr === 'd') {
            fmt = extraFormat.dayMonth + '\n' + extraFormat.year;
        }
        else {
            return formatTime(x, tr) + '\n' + modDateFormat(extraFormat.dayMonthYear, x, formatter, calendar);
        }
    }

    return modDateFormat(fmt, x, formatter, calendar);
};

/*
 * incrementMonth: make a new milliseconds value from the given one,
 * having changed the month
 *
 * special case for world calendars: multiples of 12 are treated as years,
 * even for calendar systems that don't have (always or ever) 12 months/year
 * TODO: perhaps we need a different code for year increments to support this?
 *
 * ms (number): the initial millisecond value
 * dMonth (int): the (signed) number of months to shift
 * calendar (string): the calendar system to use
 *
 * changing month does not (and CANNOT) always preserve day, since
 * months have different lengths. The worst example of this is:
 *   d = new Date(1970,0,31); d.setMonth(1) -> Feb 31 turns into Mar 3
 *
 * But we want to be able to iterate over the last day of each month,
 * regardless of what its number is.
 * So shift 3 days forward, THEN set the new month, then unshift:
 *   1/31 -> 2/28 (or 29) -> 3/31 -> 4/30 -> ...
 *
 * Note that odd behavior still exists if you start from the 26th-28th:
 *   1/28 -> 2/28 -> 3/31
 * but at least you can't shift any dates into the wrong month,
 * and ticks on these days incrementing by month would be very unusual
 */
var THREEDAYS = 3 * ONEDAY;
exports.incrementMonth = function(ms, dMonth, calendar) {
    calendar = isWorldCalendar(calendar) && calendar;

    // pull time out and operate on pure dates, then add time back at the end
    // this gives maximum precision - not that we *normally* care if we're
    // incrementing by month, but better to be safe!
    var timeMs = mod(ms, ONEDAY);
    ms = Math.round(ms - timeMs);

    if(calendar) {
        try {
            var dateJD = Math.round(ms / ONEDAY) + EPOCHJD;
            var calInstance = Registry.getComponentMethod('calendars', 'getCal')(calendar);
            var cDate = calInstance.fromJD(dateJD);

            if(dMonth % 12) calInstance.add(cDate, dMonth, 'm');
            else calInstance.add(cDate, dMonth / 12, 'y');

            return (cDate.toJD() - EPOCHJD) * ONEDAY + timeMs;
        } catch(e) {
            Loggers.error('invalid ms ' + ms + ' in calendar ' + calendar);
            // then keep going in gregorian even though the result will be 'Invalid'
        }
    }

    var y = new Date(ms + THREEDAYS);
    return y.setUTCMonth(y.getUTCMonth() + dMonth) + timeMs - THREEDAYS;
};

/*
 * findExactDates: what fraction of data is exact days, months, or years?
 *
 * data: array of millisecond values
 * calendar (string) the calendar to test against
 */
exports.findExactDates = function(data, calendar) {
    var exactYears = 0;
    var exactMonths = 0;
    var exactDays = 0;
    var blankCount = 0;
    var d;
    var di;

    var calInstance = (
        isWorldCalendar(calendar) &&
        Registry.getComponentMethod('calendars', 'getCal')(calendar)
    );

    for(var i = 0; i < data.length; i++) {
        di = data[i];

        // not date data at all
        if(!isNumeric(di)) {
            blankCount ++;
            continue;
        }

        // not an exact date
        if(di % ONEDAY) continue;

        if(calInstance) {
            try {
                d = calInstance.fromJD(di / ONEDAY + EPOCHJD);
                if(d.day() === 1) {
                    if(d.month() === 1) exactYears++;
                    else exactMonths++;
                }
                else exactDays++;
            }
            catch(e) {
                // invalid date in this calendar - ignore it here.
            }
        }
        else {
            d = new Date(di);
            if(d.getUTCDate() === 1) {
                if(d.getUTCMonth() === 0) exactYears++;
                else exactMonths++;
            }
            else exactDays++;
        }
    }
    exactMonths += exactYears;
    exactDays += exactMonths;

    var dataCount = data.length - blankCount;

    return {
        exactYears: exactYears / dataCount,
        exactMonths: exactMonths / dataCount,
        exactDays: exactDays / dataCount
    };
};

},{"../constants/numerical":674,"../registry":826,"./loggers":701,"./mod":704,"d3":151,"fast-isnumeric":218}],686:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

/* global jQuery:false */

var EventEmitter = _dereq_('events').EventEmitter;

var Events = {

    init: function(plotObj) {

        /*
         * If we have already instantiated an emitter for this plot
         * return early.
         */
        if(plotObj._ev instanceof EventEmitter) return plotObj;

        var ev = new EventEmitter();
        var internalEv = new EventEmitter();

        /*
         * Assign to plot._ev while we still live in a land
         * where plot is a DOM element with stuff attached to it.
         * In the future we can make plot the event emitter itself.
         */
        plotObj._ev = ev;

        /*
         * Create a second event handler that will manage events *internally*.
         * This allows parts of plotly to respond to thing like relayout without
         * having to use the user-facing event handler. They cannot peacefully
         * coexist on the same handler because a user invoking
         * plotObj.removeAllListeners() would detach internal events, breaking
         * plotly.
         */
        plotObj._internalEv = internalEv;

        /*
         * Assign bound methods from the ev to the plot object. These methods
         * will reference the 'this' of plot._ev even though they are methods
         * of plot. This will keep the event machinery away from the plot object
         * which currently is often a DOM element but presents an API that will
         * continue to function when plot becomes an emitter. Not all EventEmitter
         * methods have been bound to `plot` as some do not currently add value to
         * the Plotly event API.
         */
        plotObj.on = ev.on.bind(ev);
        plotObj.once = ev.once.bind(ev);
        plotObj.removeListener = ev.removeListener.bind(ev);
        plotObj.removeAllListeners = ev.removeAllListeners.bind(ev);

        /*
         * Create functions for managing internal events. These are *only* triggered
         * by the mirroring of external events via the emit function.
         */
        plotObj._internalOn = internalEv.on.bind(internalEv);
        plotObj._internalOnce = internalEv.once.bind(internalEv);
        plotObj._removeInternalListener = internalEv.removeListener.bind(internalEv);
        plotObj._removeAllInternalListeners = internalEv.removeAllListeners.bind(internalEv);

        /*
         * We must wrap emit to continue to support JQuery events. The idea
         * is to check to see if the user is using JQuery events, if they are
         * we emit JQuery events to trigger user handlers as well as the EventEmitter
         * events.
         */
        plotObj.emit = function(event, data) {
            if(typeof jQuery !== 'undefined') {
                jQuery(plotObj).trigger(event, data);
            }

            ev.emit(event, data);
            internalEv.emit(event, data);
        };

        return plotObj;
    },

    /*
     * This function behaves like jQuery's triggerHandler. It calls
     * all handlers for a particular event and returns the return value
     * of the LAST handler. This function also triggers jQuery's
     * triggerHandler for backwards compatibility.
     */
    triggerHandler: function(plotObj, event, data) {
        var jQueryHandlerValue;
        var nodeEventHandlerValue;

        /*
         * If jQuery exists run all its handlers for this event and
         * collect the return value of the LAST handler function
         */
        if(typeof jQuery !== 'undefined') {
            jQueryHandlerValue = jQuery(plotObj).triggerHandler(event, data);
        }

        /*
         * Now run all the node style event handlers
         */
        var ev = plotObj._ev;
        if(!ev) return jQueryHandlerValue;

        var handlers = ev._events[event];
        if(!handlers) return jQueryHandlerValue;

        // making sure 'this' is the EventEmitter instance
        function apply(handler) {
            // The 'once' case, we can't just call handler() as we need
            // the return value here. So,
            // - remove handler
            // - call listener and grab return value!
            // - stash 'fired' key to not call handler twice
            if(handler.listener) {
                ev.removeListener(event, handler.listener);
                if(!handler.fired) {
                    handler.fired = true;
                    return handler.listener.apply(ev, [data]);
                }
            } else {
                return handler.apply(ev, [data]);
            }
        }

        // handlers can be function or an array of functions
        handlers = Array.isArray(handlers) ? handlers : [handlers];

        var i;
        for(i = 0; i < handlers.length - 1; i++) {
            apply(handlers[i]);
        }
        // now call the final handler and collect its value
        nodeEventHandlerValue = apply(handlers[i]);

        /*
         * Return either the jQuery handler value if it exists or the
         * nodeEventHandler value. jQuery event value supersedes nodejs
         * events for backwards compatibility reasons.
         */
        return jQueryHandlerValue !== undefined ?
            jQueryHandlerValue :
            nodeEventHandlerValue;
    },

    purge: function(plotObj) {
        delete plotObj._ev;
        delete plotObj.on;
        delete plotObj.once;
        delete plotObj.removeListener;
        delete plotObj.removeAllListeners;
        delete plotObj.emit;

        delete plotObj._ev;
        delete plotObj._internalEv;
        delete plotObj._internalOn;
        delete plotObj._internalOnce;
        delete plotObj._removeInternalListener;
        delete plotObj._removeAllInternalListeners;

        return plotObj;
    }

};

module.exports = Events;

},{"events":92}],687:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isPlainObject = _dereq_('./is_plain_object.js');
var isArray = Array.isArray;

function primitivesLoopSplice(source, target) {
    var i, value;
    for(i = 0; i < source.length; i++) {
        value = source[i];
        if(value !== null && typeof(value) === 'object') {
            return false;
        }
        if(value !== void(0)) {
            target[i] = value;
        }
    }
    return true;
}

exports.extendFlat = function() {
    return _extend(arguments, false, false, false);
};

exports.extendDeep = function() {
    return _extend(arguments, true, false, false);
};

exports.extendDeepAll = function() {
    return _extend(arguments, true, true, false);
};

exports.extendDeepNoArrays = function() {
    return _extend(arguments, true, false, true);
};

/*
 * Inspired by https://github.com/justmoon/node-extend/blob/master/index.js
 * All credit to the jQuery authors for perfecting this amazing utility.
 *
 * API difference with jQuery version:
 * - No optional boolean (true -> deep extend) first argument,
 *   use `extendFlat` for first-level only extend and
 *   use `extendDeep` for a deep extend.
 *
 * Other differences with jQuery version:
 * - Uses a modern (and faster) isPlainObject routine.
 * - Expected to work with object {} and array [] arguments only.
 * - Does not check for circular structure.
 *   FYI: jQuery only does a check across one level.
 *   Warning: this might result in infinite loops.
 *
 */
function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) {
    var target = inputs[0];
    var length = inputs.length;

    var input, key, src, copy, copyIsArray, clone, allPrimitives;

    // TODO does this do the right thing for typed arrays?

    if(length === 2 && isArray(target) && isArray(inputs[1]) && target.length === 0) {

        allPrimitives = primitivesLoopSplice(inputs[1], target);

        if(allPrimitives) {
            return target;
        } else {
            target.splice(0, target.length); // reset target and continue to next block
        }
    }

    for(var i = 1; i < length; i++) {
        input = inputs[i];

        for(key in input) {
            src = target[key];
            copy = input[key];

            // Stop early and just transfer the array if array copies are disallowed:
            if(noArrayCopies && isArray(copy)) {
                target[key] = copy;
            }

            // recurse if we're merging plain objects or arrays
            else if(isDeep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
                if(copyIsArray) {
                    copyIsArray = false;
                    clone = src && isArray(src) ? src : [];
                } else {
                    clone = src && isPlainObject(src) ? src : {};
                }

                // never move original objects, clone them
                target[key] = _extend([clone, copy], isDeep, keepAllKeys, noArrayCopies);
            }

            // don't bring in undefined values, except for extendDeepAll
            else if(typeof copy !== 'undefined' || keepAllKeys) {
                target[key] = copy;
            }
        }
    }

    return target;
}

},{"./is_plain_object.js":698}],688:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


/**
 * Return news array containing only the unique items
 * found in input array.
 *
 * IMPORTANT: Note that items are considered unique
 * if `String({})` is unique. For example;
 *
 *  Lib.filterUnique([ { a: 1 }, { b: 2 } ])
 *
 *  returns [{ a: 1 }]
 *
 * and
 *
 *  Lib.filterUnique([ '1', 1 ])
 *
 *  returns ['1']
 *
 *
 * @param {array} array base array
 * @return {array} new filtered array
 */
module.exports = function filterUnique(array) {
    var seen = {};
    var out = [];
    var j = 0;

    for(var i = 0; i < array.length; i++) {
        var item = array[i];

        if(seen[item] !== 1) {
            seen[item] = 1;
            out[j++] = item;
        }
    }

    return out;
};

},{}],689:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/** Filter out object items with visible !== true
 *  insider array container.
 *
 *  @param {array of objects} container
 *  @return {array of objects} of length <= container
 *
 */
module.exports = function filterVisible(container) {
    var filterFn = isCalcData(container) ? calcDataFilter : baseFilter;
    var out = [];

    for(var i = 0; i < container.length; i++) {
        var item = container[i];
        if(filterFn(item)) out.push(item);
    }

    return out;
};

function baseFilter(item) {
    return item.visible === true;
}

function calcDataFilter(item) {
    return item[0].trace.visible === true;
}

function isCalcData(cont) {
    return (
        Array.isArray(cont) &&
        Array.isArray(cont[0]) &&
        cont[0][0] &&
        cont[0][0].trace
    );
}

},{}],690:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var countryRegex = _dereq_('country-regex');
var Lib = _dereq_('../lib');


// make list of all country iso3 ids from at runtime
var countryIds = Object.keys(countryRegex);

var locationmodeToIdFinder = {
    'ISO-3': Lib.identity,
    'USA-states': Lib.identity,
    'country names': countryNameToISO3
};

exports.locationToFeature = function(locationmode, location, features) {
    if(!location || typeof location !== 'string') return false;

    var locationId = getLocationId(locationmode, location);

    if(locationId) {
        for(var i = 0; i < features.length; i++) {
            var feature = features[i];

            if(feature.id === locationId) return feature;
        }

        Lib.log([
            'Location with id', locationId,
            'does not have a matching topojson feature at this resolution.'
        ].join(' '));
    }

    return false;
};

function getLocationId(locationmode, location) {
    var idFinder = locationmodeToIdFinder[locationmode];
    return idFinder(location);
}

function countryNameToISO3(countryName) {
    for(var i = 0; i < countryIds.length; i++) {
        var iso3 = countryIds[i];
        var regex = new RegExp(countryRegex[iso3]);

        if(regex.test(countryName.trim().toLowerCase())) return iso3;
    }

    Lib.log('Unrecognized country name: ' + countryName + '.');

    return false;
}

},{"../lib":697,"country-regex":122}],691:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var BADNUM = _dereq_('../constants/numerical').BADNUM;

/**
 * Convert calcTrace to GeoJSON 'MultiLineString' coordinate arrays
 *
 * @param {object} calcTrace
 *  gd.calcdata item.
 *  Note that calcTrace[i].lonlat is assumed to be defined
 *
 * @return {array}
 *  return line coords array (or array of arrays)
 *
 */
exports.calcTraceToLineCoords = function(calcTrace) {
    var trace = calcTrace[0].trace;
    var connectgaps = trace.connectgaps;

    var coords = [];
    var lineString = [];

    for(var i = 0; i < calcTrace.length; i++) {
        var calcPt = calcTrace[i];
        var lonlat = calcPt.lonlat;

        if(lonlat[0] !== BADNUM) {
            lineString.push(lonlat);
        } else if(!connectgaps && lineString.length > 0) {
            coords.push(lineString);
            lineString = [];
        }
    }

    if(lineString.length > 0) {
        coords.push(lineString);
    }

    return coords;
};


/**
 * Make line ('LineString' or 'MultiLineString') GeoJSON
 *
 * @param {array} coords
 *  results form calcTraceToLineCoords
 * @return {object} out
 *  GeoJSON object
 *
 */
exports.makeLine = function(coords) {
    if(coords.length === 1) {
        return {
            type: 'LineString',
            coordinates: coords[0]
        };
    } else {
        return {
            type: 'MultiLineString',
            coordinates: coords
        };
    }
};

/**
 * Make polygon ('Polygon' or 'MultiPolygon') GeoJSON
 *
 * @param {array} coords
 *  results form calcTraceToLineCoords
 * @return {object} out
 *  GeoJSON object
 */
exports.makePolygon = function(coords) {
    if(coords.length === 1) {
        return {
            type: 'Polygon',
            coordinates: coords
        };
    } else {
        var _coords = new Array(coords.length);

        for(var i = 0; i < coords.length; i++) {
            _coords[i] = [coords[i]];
        }

        return {
            type: 'MultiPolygon',
            coordinates: _coords
        };
    }
};

/**
 * Make blank GeoJSON
 *
 * @return {object}
 *  Blank GeoJSON object
 *
 */
exports.makeBlank = function() {
    return {
        type: 'Point',
        coordinates: []
    };
};

},{"../constants/numerical":674}],692:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var mod = _dereq_('./mod').mod;

/*
 * look for intersection of two line segments
 *   (1->2 and 3->4) - returns array [x,y] if they do, null if not
 */
exports.segmentsIntersect = segmentsIntersect;
function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) {
    var a = x2 - x1;
    var b = x3 - x1;
    var c = x4 - x3;
    var d = y2 - y1;
    var e = y3 - y1;
    var f = y4 - y3;
    var det = a * f - c * d;
    // parallel lines? intersection is undefined
    // ignore the case where they are colinear
    if(det === 0) return null;
    var t = (b * f - c * e) / det;
    var u = (b * d - a * e) / det;
    // segments do not intersect?
    if(u < 0 || u > 1 || t < 0 || t > 1) return null;

    return {x: x1 + a * t, y: y1 + d * t};
}

/*
 * find the minimum distance between two line segments (1->2 and 3->4)
 */
exports.segmentDistance = function segmentDistance(x1, y1, x2, y2, x3, y3, x4, y4) {
    if(segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4)) return 0;

    // the two segments and their lengths squared
    var x12 = x2 - x1;
    var y12 = y2 - y1;
    var x34 = x4 - x3;
    var y34 = y4 - y3;
    var ll12 = x12 * x12 + y12 * y12;
    var ll34 = x34 * x34 + y34 * y34;

    // calculate distance squared, then take the sqrt at the very end
    var dist2 = Math.min(
        perpDistance2(x12, y12, ll12, x3 - x1, y3 - y1),
        perpDistance2(x12, y12, ll12, x4 - x1, y4 - y1),
        perpDistance2(x34, y34, ll34, x1 - x3, y1 - y3),
        perpDistance2(x34, y34, ll34, x2 - x3, y2 - y3)
    );

    return Math.sqrt(dist2);
};

/*
 * distance squared from segment ab to point c
 * [xab, yab] is the vector b-a
 * [xac, yac] is the vector c-a
 * llab is the length squared of (b-a), just to simplify calculation
 */
function perpDistance2(xab, yab, llab, xac, yac) {
    var fcAB = (xac * xab + yac * yab);
    if(fcAB < 0) {
        // point c is closer to point a
        return xac * xac + yac * yac;
    }
    else if(fcAB > llab) {
        // point c is closer to point b
        var xbc = xac - xab;
        var ybc = yac - yab;
        return xbc * xbc + ybc * ybc;
    }
    else {
        // perpendicular distance is the shortest
        var crossProduct = xac * yab - yac * xab;
        return crossProduct * crossProduct / llab;
    }
}

// a very short-term cache for getTextLocation, just because
// we're often looping over the same locations multiple times
// invalidated as soon as we look at a different path
var locationCache, workingPath, workingTextWidth;

// turn a path and position along it into x, y, and angle for the given text
exports.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) {
    if(path !== workingPath || textWidth !== workingTextWidth) {
        locationCache = {};
        workingPath = path;
        workingTextWidth = textWidth;
    }
    if(locationCache[positionOnPath]) {
        return locationCache[positionOnPath];
    }

    // for the angle, use points on the path separated by the text width
    // even though due to curvature, the text will cover a bit more than that
    var p0 = path.getPointAtLength(mod(positionOnPath - textWidth / 2, totalPathLen));
    var p1 = path.getPointAtLength(mod(positionOnPath + textWidth / 2, totalPathLen));
    // note: atan handles 1/0 nicely
    var theta = Math.atan((p1.y - p0.y) / (p1.x - p0.x));
    // center the text at 2/3 of the center position plus 1/3 the p0/p1 midpoint
    // that's the average position of this segment, assuming it's roughly quadratic
    var pCenter = path.getPointAtLength(mod(positionOnPath, totalPathLen));
    var x = (pCenter.x * 4 + p0.x + p1.x) / 6;
    var y = (pCenter.y * 4 + p0.y + p1.y) / 6;

    var out = {x: x, y: y, theta: theta};
    locationCache[positionOnPath] = out;
    return out;
};

exports.clearLocationCache = function() {
    workingPath = null;
};

/*
 * Find the segment of `path` that's within the visible area
 * given by `bounds` {left, right, top, bottom}, to within a
 * precision of `buffer` px
 *
 * returns: undefined if nothing is visible, else object:
 * {
 *   min: position where the path first enters bounds, or 0 if it
 *        starts within bounds
 *   max: position where the path last exits bounds, or the path length
 *        if it finishes within bounds
 *   len: max - min, ie the length of visible path
 *   total: the total path length - just included so the caller doesn't
 *        need to call path.getTotalLength() again
 *   isClosed: true iff the start and end points of the path are both visible
 *        and are at the same point
 * }
 *
 * Works by starting from either end and repeatedly finding the distance from
 * that point to the plot area, and if it's outside the plot, moving along the
 * path by that distance (because the plot must be at least that far away on
 * the path). Note that if a path enters, exits, and re-enters the plot, we
 * will not capture this behavior.
 */
exports.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) {
    var left = bounds.left;
    var right = bounds.right;
    var top = bounds.top;
    var bottom = bounds.bottom;

    var pMin = 0;
    var pTotal = path.getTotalLength();
    var pMax = pTotal;

    var pt0, ptTotal;

    function getDistToPlot(len) {
        var pt = path.getPointAtLength(len);

        // hold on to the start and end points for `closed`
        if(len === 0) pt0 = pt;
        else if(len === pTotal) ptTotal = pt;

        var dx = (pt.x < left) ? left - pt.x : (pt.x > right ? pt.x - right : 0);
        var dy = (pt.y < top) ? top - pt.y : (pt.y > bottom ? pt.y - bottom : 0);
        return Math.sqrt(dx * dx + dy * dy);
    }

    var distToPlot = getDistToPlot(pMin);
    while(distToPlot) {
        pMin += distToPlot + buffer;
        if(pMin > pMax) return;
        distToPlot = getDistToPlot(pMin);
    }

    distToPlot = getDistToPlot(pMax);
    while(distToPlot) {
        pMax -= distToPlot + buffer;
        if(pMin > pMax) return;
        distToPlot = getDistToPlot(pMax);
    }

    return {
        min: pMin,
        max: pMax,
        len: pMax - pMin,
        total: pTotal,
        isClosed: pMin === 0 && pMax === pTotal &&
            Math.abs(pt0.x - ptTotal.x) < 0.1 &&
            Math.abs(pt0.y - ptTotal.y) < 0.1
    };
};

/**
 * Find point on SVG path corresponding to a given constraint coordinate
 *
 * @param {SVGPathElement} path
 * @param {Number} val : constraint coordinate value
 * @param {String} coord : 'x' or 'y' the constraint coordinate
 * @param {Object} opts :
 *  - {Number} pathLength : supply total path length before hand
 *  - {Number} tolerance
 *  - {Number} iterationLimit
 * @return {SVGPoint}
 */
exports.findPointOnPath = function findPointOnPath(path, val, coord, opts) {
    opts = opts || {};

    var pathLength = opts.pathLength || path.getTotalLength();
    var tolerance = opts.tolerance || 1e-3;
    var iterationLimit = opts.iterationLimit || 30;

    // if path starts at a val greater than the path tail (like on vertical violins),
    // we must flip the sign of the computed diff.
    var mul = path.getPointAtLength(0)[coord] > path.getPointAtLength(pathLength)[coord] ? -1 : 1;

    var i = 0;
    var b0 = 0;
    var b1 = pathLength;
    var mid;
    var pt;
    var diff;

    while(i < iterationLimit) {
        mid = (b0 + b1) / 2;
        pt = path.getPointAtLength(mid);
        diff = pt[coord] - val;

        if(Math.abs(diff) < tolerance) {
            return pt;
        } else {
            if(mul * diff > 0) {
                b1 = mid;
            } else {
                b0 = mid;
            }
            i++;
        }
    }
    return pt;
};

},{"./mod":704}],693:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * Allow referencing a graph DOM element either directly
 * or by its id string
 *
 * @param {HTMLDivElement|string} gd: a graph element or its id
 *
 * @returns {HTMLDivElement} the DOM element of the graph
 */
module.exports = function(gd) {
    var gdElement;

    if(typeof gd === 'string') {
        gdElement = document.getElementById(gd);

        if(gdElement === null) {
            throw new Error('No DOM element with id \'' + gd + '\' exists on the page.');
        }

        return gdElement;
    }
    else if(gd === null || gd === undefined) {
        throw new Error('DOM element provided is null or undefined');
    }

    return gd;  // otherwise assume that gd is a DOM element
};

},{}],694:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var tinycolor = _dereq_('tinycolor2');
var rgba = _dereq_('color-normalize');

var Colorscale = _dereq_('../components/colorscale');
var colorDflt = _dereq_('../components/color/attributes').defaultLine;
var isArrayOrTypedArray = _dereq_('./array').isArrayOrTypedArray;

var colorDfltRgba = rgba(colorDflt);
var opacityDflt = 1;

function calculateColor(colorIn, opacityIn) {
    var colorOut = colorIn;
    colorOut[3] *= opacityIn;
    return colorOut;
}

function validateColor(colorIn) {
    if(isNumeric(colorIn)) return colorDfltRgba;

    var colorOut = rgba(colorIn);

    return colorOut.length ? colorOut : colorDfltRgba;
}

function validateOpacity(opacityIn) {
    return isNumeric(opacityIn) ? opacityIn : opacityDflt;
}

function formatColor(containerIn, opacityIn, len) {
    var colorIn = containerIn.color;
    var isArrayColorIn = isArrayOrTypedArray(colorIn);
    var isArrayOpacityIn = isArrayOrTypedArray(opacityIn);
    var colorOut = [];

    var sclFunc, getColor, getOpacity, colori, opacityi;

    if(containerIn.colorscale !== undefined) {
        sclFunc = Colorscale.makeColorScaleFunc(
            Colorscale.extractScale(containerIn, {cLetter: 'c'})
        );
    }
    else {
        sclFunc = validateColor;
    }

    if(isArrayColorIn) {
        getColor = function(c, i) {
            // FIXME: there is double work, considering that sclFunc does the opposite
            return c[i] === undefined ? colorDfltRgba : rgba(sclFunc(c[i]));
        };
    }
    else getColor = validateColor;

    if(isArrayOpacityIn) {
        getOpacity = function(o, i) {
            return o[i] === undefined ? opacityDflt : validateOpacity(o[i]);
        };
    }
    else getOpacity = validateOpacity;

    if(isArrayColorIn || isArrayOpacityIn) {
        for(var i = 0; i < len; i++) {
            colori = getColor(colorIn, i);
            opacityi = getOpacity(opacityIn, i);
            colorOut[i] = calculateColor(colori, opacityi);
        }
    }
    else colorOut = calculateColor(rgba(colorIn), opacityIn);

    return colorOut;
}

function parseColorScale(cont, alpha) {
    if(alpha === undefined) alpha = 1;

    var colorscale = cont.reversescale ?
        Colorscale.flipScale(cont.colorscale) :
        cont.colorscale;

    return colorscale.map(function(elem) {
        var index = elem[0];
        var color = tinycolor(elem[1]);
        var rgb = color.toRgb();
        return {
            index: index,
            rgb: [rgb.r, rgb.g, rgb.b, alpha]
        };
    });
}

module.exports = {
    formatColor: formatColor,
    parseColorScale: parseColorScale
};

},{"../components/color/attributes":573,"../components/colorscale":586,"./array":680,"color-normalize":108,"fast-isnumeric":218,"tinycolor2":518}],695:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var identity = _dereq_('./identity');

function wrap(d) {return [d];}

module.exports = {

    // The D3 data binding concept and the General Update Pattern promotes the idea of
    // traversing into the scenegraph by using the `.data(fun, keyFun)` call.
    // The `fun` is most often a `repeat`, ie. the elements beneath a `<g>` element need
    // access to the same data, or a `descend`, which fans a scenegraph node into a bunch of
    // of elements, e.g. points, lines, rows, requiring an array as input.
    // The role of the `keyFun` is to identify what elements are being entered/exited/updated,
    // otherwise D3 reverts to using a plain index which would screw up `transition`s.
    keyFun: function(d) {return d.key;},
    repeat: wrap,
    descend: identity,

    // Plotly.js uses a convention of storing the actual contents of the `calcData` as the
    // element zero of a container array. These helpers are just used for clarity as a
    // newcomer to the codebase may not know what the `[0]` is, and whether there can be further
    // elements (not atm).
    wrap: wrap,
    unwrap: function(d) {return d[0];}
};

},{"./identity":696}],696:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// Simple helper functions
// none of these need any external deps

module.exports = function identity(d) { return d; };

},{}],697:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');

var numConstants = _dereq_('../constants/numerical');
var FP_SAFE = numConstants.FP_SAFE;
var BADNUM = numConstants.BADNUM;

var lib = module.exports = {};

lib.nestedProperty = _dereq_('./nested_property');
lib.keyedContainer = _dereq_('./keyed_container');
lib.relativeAttr = _dereq_('./relative_attr');
lib.isPlainObject = _dereq_('./is_plain_object');
lib.toLogRange = _dereq_('./to_log_range');
lib.relinkPrivateKeys = _dereq_('./relink_private');

var arrayModule = _dereq_('./array');
lib.isTypedArray = arrayModule.isTypedArray;
lib.isArrayOrTypedArray = arrayModule.isArrayOrTypedArray;
lib.isArray1D = arrayModule.isArray1D;
lib.ensureArray = arrayModule.ensureArray;
lib.concat = arrayModule.concat;
lib.maxRowLength = arrayModule.maxRowLength;
lib.minRowLength = arrayModule.minRowLength;

var modModule = _dereq_('./mod');
lib.mod = modModule.mod;
lib.modHalf = modModule.modHalf;

var coerceModule = _dereq_('./coerce');
lib.valObjectMeta = coerceModule.valObjectMeta;
lib.coerce = coerceModule.coerce;
lib.coerce2 = coerceModule.coerce2;
lib.coerceFont = coerceModule.coerceFont;
lib.coerceHoverinfo = coerceModule.coerceHoverinfo;
lib.coerceSelectionMarkerOpacity = coerceModule.coerceSelectionMarkerOpacity;
lib.validate = coerceModule.validate;

var datesModule = _dereq_('./dates');
lib.dateTime2ms = datesModule.dateTime2ms;
lib.isDateTime = datesModule.isDateTime;
lib.ms2DateTime = datesModule.ms2DateTime;
lib.ms2DateTimeLocal = datesModule.ms2DateTimeLocal;
lib.cleanDate = datesModule.cleanDate;
lib.isJSDate = datesModule.isJSDate;
lib.formatDate = datesModule.formatDate;
lib.incrementMonth = datesModule.incrementMonth;
lib.dateTick0 = datesModule.dateTick0;
lib.dfltRange = datesModule.dfltRange;
lib.findExactDates = datesModule.findExactDates;
lib.MIN_MS = datesModule.MIN_MS;
lib.MAX_MS = datesModule.MAX_MS;

var searchModule = _dereq_('./search');
lib.findBin = searchModule.findBin;
lib.sorterAsc = searchModule.sorterAsc;
lib.sorterDes = searchModule.sorterDes;
lib.distinctVals = searchModule.distinctVals;
lib.roundUp = searchModule.roundUp;
lib.sort = searchModule.sort;
lib.findIndexOfMin = searchModule.findIndexOfMin;

var statsModule = _dereq_('./stats');
lib.aggNums = statsModule.aggNums;
lib.len = statsModule.len;
lib.mean = statsModule.mean;
lib.midRange = statsModule.midRange;
lib.variance = statsModule.variance;
lib.stdev = statsModule.stdev;
lib.interp = statsModule.interp;

var matrixModule = _dereq_('./matrix');
lib.init2dArray = matrixModule.init2dArray;
lib.transposeRagged = matrixModule.transposeRagged;
lib.dot = matrixModule.dot;
lib.translationMatrix = matrixModule.translationMatrix;
lib.rotationMatrix = matrixModule.rotationMatrix;
lib.rotationXYMatrix = matrixModule.rotationXYMatrix;
lib.apply2DTransform = matrixModule.apply2DTransform;
lib.apply2DTransform2 = matrixModule.apply2DTransform2;

var anglesModule = _dereq_('./angles');
lib.deg2rad = anglesModule.deg2rad;
lib.rad2deg = anglesModule.rad2deg;
lib.angleDelta = anglesModule.angleDelta;
lib.angleDist = anglesModule.angleDist;
lib.isFullCircle = anglesModule.isFullCircle;
lib.isAngleInsideSector = anglesModule.isAngleInsideSector;
lib.isPtInsideSector = anglesModule.isPtInsideSector;
lib.pathArc = anglesModule.pathArc;
lib.pathSector = anglesModule.pathSector;
lib.pathAnnulus = anglesModule.pathAnnulus;

var anchorUtils = _dereq_('./anchor_utils');
lib.isLeftAnchor = anchorUtils.isLeftAnchor;
lib.isCenterAnchor = anchorUtils.isCenterAnchor;
lib.isRightAnchor = anchorUtils.isRightAnchor;
lib.isTopAnchor = anchorUtils.isTopAnchor;
lib.isMiddleAnchor = anchorUtils.isMiddleAnchor;
lib.isBottomAnchor = anchorUtils.isBottomAnchor;

var geom2dModule = _dereq_('./geometry2d');
lib.segmentsIntersect = geom2dModule.segmentsIntersect;
lib.segmentDistance = geom2dModule.segmentDistance;
lib.getTextLocation = geom2dModule.getTextLocation;
lib.clearLocationCache = geom2dModule.clearLocationCache;
lib.getVisibleSegment = geom2dModule.getVisibleSegment;
lib.findPointOnPath = geom2dModule.findPointOnPath;

var extendModule = _dereq_('./extend');
lib.extendFlat = extendModule.extendFlat;
lib.extendDeep = extendModule.extendDeep;
lib.extendDeepAll = extendModule.extendDeepAll;
lib.extendDeepNoArrays = extendModule.extendDeepNoArrays;

var loggersModule = _dereq_('./loggers');
lib.log = loggersModule.log;
lib.warn = loggersModule.warn;
lib.error = loggersModule.error;

var regexModule = _dereq_('./regex');
lib.counterRegex = regexModule.counter;

var throttleModule = _dereq_('./throttle');
lib.throttle = throttleModule.throttle;
lib.throttleDone = throttleModule.done;
lib.clearThrottle = throttleModule.clear;

lib.getGraphDiv = _dereq_('./get_graph_div');

lib.clearResponsive = _dereq_('./clear_responsive');

lib.makeTraceGroups = _dereq_('./make_trace_groups');

lib._ = _dereq_('./localize');

lib.notifier = _dereq_('./notifier');

lib.filterUnique = _dereq_('./filter_unique');
lib.filterVisible = _dereq_('./filter_visible');
lib.pushUnique = _dereq_('./push_unique');

lib.cleanNumber = _dereq_('./clean_number');

lib.ensureNumber = function num(v) {
    if(!isNumeric(v)) return BADNUM;
    v = Number(v);
    if(v < -FP_SAFE || v > FP_SAFE) return BADNUM;
    return isNumeric(v) ? Number(v) : BADNUM;
};

/**
 * Is v a valid array index? Accepts numeric strings as well as numbers.
 *
 * @param {any} v: the value to test
 * @param {Optional[integer]} len: the array length we are indexing
 *
 * @return {bool}: v is a valid array index
 */
lib.isIndex = function(v, len) {
    if(len !== undefined && v >= len) return false;
    return isNumeric(v) && (v >= 0) && (v % 1 === 0);
};

lib.noop = _dereq_('./noop');
lib.identity = _dereq_('./identity');

/**
 * create an array of length 'cnt' filled with 'v' at all indices
 *
 * @param {any} v
 * @param {number} cnt
 * @return {array}
 */
lib.repeat = function(v, cnt) {
    var out = new Array(cnt);
    for(var i = 0; i < cnt; i++) {
        out[i] = v;
    }
    return out;
};

/**
 * swap x and y of the same attribute in container cont
 * specify attr with a ? in place of x/y
 * you can also swap other things than x/y by providing part1 and part2
 */
lib.swapAttrs = function(cont, attrList, part1, part2) {
    if(!part1) part1 = 'x';
    if(!part2) part2 = 'y';
    for(var i = 0; i < attrList.length; i++) {
        var attr = attrList[i];
        var xp = lib.nestedProperty(cont, attr.replace('?', part1));
        var yp = lib.nestedProperty(cont, attr.replace('?', part2));
        var temp = xp.get();
        xp.set(yp.get());
        yp.set(temp);
    }
};

/**
 * SVG painter's algo worked around with reinsertion
 */
lib.raiseToTop = function raiseToTop(elem) {
    elem.parentNode.appendChild(elem);
};

/**
 * cancel a possibly pending transition; returned selection may be used by caller
 */
lib.cancelTransition = function(selection) {
    return selection.transition().duration(0);
};

// constrain - restrict a number v to be between v0 and v1
lib.constrain = function(v, v0, v1) {
    if(v0 > v1) return Math.max(v1, Math.min(v0, v));
    return Math.max(v0, Math.min(v1, v));
};

/**
 * do two bounding boxes from getBoundingClientRect,
 * ie {left,right,top,bottom,width,height}, overlap?
 * takes optional padding pixels
 */
lib.bBoxIntersect = function(a, b, pad) {
    pad = pad || 0;
    return (a.left <= b.right + pad &&
            b.left <= a.right + pad &&
            a.top <= b.bottom + pad &&
            b.top <= a.bottom + pad);
};

/*
 * simpleMap: alternative to Array.map that only
 * passes on the element and up to 2 extra args you
 * provide (but not the array index or the whole array)
 *
 * array: the array to map it to
 * func: the function to apply
 * x1, x2: optional extra args
 */
lib.simpleMap = function(array, func, x1, x2) {
    var len = array.length;
    var out = new Array(len);
    for(var i = 0; i < len; i++) out[i] = func(array[i], x1, x2);
    return out;
};

/**
 * Random string generator
 *
 * @param {object} existing
 *     pass in strings to avoid as keys with truthy values
 * @param {int} bits
 *     bits of information in the output string, default 24
 * @param {int} base
 *     base of string representation, default 16. Should be a power of 2.
 */
lib.randstr = function randstr(existing, bits, base, _recursion) {
    if(!base) base = 16;
    if(bits === undefined) bits = 24;
    if(bits <= 0) return '0';

    var digits = Math.log(Math.pow(2, bits)) / Math.log(base);
    var res = '';
    var i, b, x;

    for(i = 2; digits === Infinity; i *= 2) {
        digits = Math.log(Math.pow(2, bits / i)) / Math.log(base) * i;
    }

    var rem = digits - Math.floor(digits);

    for(i = 0; i < Math.floor(digits); i++) {
        x = Math.floor(Math.random() * base).toString(base);
        res = x + res;
    }

    if(rem) {
        b = Math.pow(base, rem);
        x = Math.floor(Math.random() * b).toString(base);
        res = x + res;
    }

    var parsed = parseInt(res, base);
    if((existing && existing[res]) ||
         (parsed !== Infinity && parsed >= Math.pow(2, bits))) {
        if(_recursion > 10) {
            lib.warn('randstr failed uniqueness');
            return res;
        }
        return randstr(existing, bits, base, (_recursion || 0) + 1);
    }
    else return res;
};

lib.OptionControl = function(opt, optname) {
    /*
     * An environment to contain all option setters and
     * getters that collectively modify opts.
     *
     * You can call up opts from any function in new object
     * as this.optname || this.opt
     *
     * See FitOpts for example of usage
     */
    if(!opt) opt = {};
    if(!optname) optname = 'opt';

    var self = {};
    self.optionList = [];

    self._newoption = function(optObj) {
        optObj[optname] = opt;
        self[optObj.name] = optObj;
        self.optionList.push(optObj);
    };

    self['_' + optname] = opt;
    return self;
};

/**
 * lib.smooth: smooth arrayIn by convolving with
 * a hann window with given full width at half max
 * bounce the ends in, so the output has the same length as the input
 */
lib.smooth = function(arrayIn, FWHM) {
    FWHM = Math.round(FWHM) || 0; // only makes sense for integers
    if(FWHM < 2) return arrayIn;

    var alen = arrayIn.length;
    var alen2 = 2 * alen;
    var wlen = 2 * FWHM - 1;
    var w = new Array(wlen);
    var arrayOut = new Array(alen);
    var i;
    var j;
    var k;
    var v;

    // first make the window array
    for(i = 0; i < wlen; i++) {
        w[i] = (1 - Math.cos(Math.PI * (i + 1) / FWHM)) / (2 * FWHM);
    }

    // now do the convolution
    for(i = 0; i < alen; i++) {
        v = 0;
        for(j = 0; j < wlen; j++) {
            k = i + j + 1 - FWHM;

            // multibounce
            if(k < -alen) k -= alen2 * Math.round(k / alen2);
            else if(k >= alen2) k -= alen2 * Math.floor(k / alen2);

            // single bounce
            if(k < 0) k = - 1 - k;
            else if(k >= alen) k = alen2 - 1 - k;

            v += arrayIn[k] * w[j];
        }
        arrayOut[i] = v;
    }

    return arrayOut;
};

/**
 * syncOrAsync: run a sequence of functions synchronously
 * as long as its returns are not promises (ie have no .then)
 * includes one argument arg to send to all functions...
 * this is mainly just to prevent us having to make wrapper functions
 * when the only purpose of the wrapper is to reference gd
 * and a final step to be executed at the end
 * TODO: if there's an error and everything is sync,
 * this doesn't happen yet because we want to make sure
 * that it gets reported
 */
lib.syncOrAsync = function(sequence, arg, finalStep) {
    var ret, fni;

    function continueAsync() {
        return lib.syncOrAsync(sequence, arg, finalStep);
    }

    while(sequence.length) {
        fni = sequence.splice(0, 1)[0];
        ret = fni(arg);

        if(ret && ret.then) {
            return ret.then(continueAsync)
                .then(undefined, lib.promiseError);
        }
    }

    return finalStep && finalStep(arg);
};


/**
 * Helper to strip trailing slash, from
 * http://stackoverflow.com/questions/6680825/return-string-without-trailing-slash
 */
lib.stripTrailingSlash = function(str) {
    if(str.substr(-1) === '/') return str.substr(0, str.length - 1);
    return str;
};

lib.noneOrAll = function(containerIn, containerOut, attrList) {
    /**
     * some attributes come together, so if you have one of them
     * in the input, you should copy the default values of the others
     * to the input as well.
     */
    if(!containerIn) return;

    var hasAny = false;
    var hasAll = true;
    var i;
    var val;

    for(i = 0; i < attrList.length; i++) {
        val = containerIn[attrList[i]];
        if(val !== undefined && val !== null) hasAny = true;
        else hasAll = false;
    }

    if(hasAny && !hasAll) {
        for(i = 0; i < attrList.length; i++) {
            containerIn[attrList[i]] = containerOut[attrList[i]];
        }
    }
};

/** merges calcdata field (given by cdAttr) with traceAttr values
 *
 * N.B. Loop over minimum of cd.length and traceAttr.length
 * i.e. it does not try to fill in beyond traceAttr.length-1
 *
 * @param {array} traceAttr : trace attribute
 * @param {object} cd : calcdata trace
 * @param {string} cdAttr : calcdata key
 */
lib.mergeArray = function(traceAttr, cd, cdAttr) {
    if(lib.isArrayOrTypedArray(traceAttr)) {
        var imax = Math.min(traceAttr.length, cd.length);
        for(var i = 0; i < imax; i++) cd[i][cdAttr] = traceAttr[i];
    }
};

/** fills calcdata field (given by cdAttr) with traceAttr values
 *  or function of traceAttr values (e.g. some fallback)
 *
 * N.B. Loops over all cd items.
 *
 * @param {array} traceAttr : trace attribute
 * @param {object} cd : calcdata trace
 * @param {string} cdAttr : calcdata key
 * @param {function} [fn] : optional function to apply to each array item
 */
lib.fillArray = function(traceAttr, cd, cdAttr, fn) {
    fn = fn || lib.identity;

    if(lib.isArrayOrTypedArray(traceAttr)) {
        for(var i = 0; i < cd.length; i++) {
            cd[i][cdAttr] = fn(traceAttr[i]);
        }
    }
};

/** Handler for trace-wide vs per-point options
 *
 * @param {object} trace : (full) trace object
 * @param {number} ptNumber : index of the point in question
 * @param {string} astr : attribute string
 * @param {function} [fn] : optional function to apply to each array item
 *
 * @return {any}
 */
lib.castOption = function(trace, ptNumber, astr, fn) {
    fn = fn || lib.identity;

    var val = lib.nestedProperty(trace, astr).get();

    if(lib.isArrayOrTypedArray(val)) {
        if(Array.isArray(ptNumber) && lib.isArrayOrTypedArray(val[ptNumber[0]])) {
            return fn(val[ptNumber[0]][ptNumber[1]]);
        } else {
            return fn(val[ptNumber]);
        }
    } else {
        return val;
    }
};

/** Extract option from calcdata item, correctly falling back to
 *  trace value if not found.
 *
 *  @param {object} calcPt : calcdata[i][j] item
 *  @param {object} trace : (full) trace object
 *  @param {string} calcKey : calcdata key
 *  @param {string} traceKey : aka trace attribute string
 *  @return {any}
 */
lib.extractOption = function(calcPt, trace, calcKey, traceKey) {
    if(calcKey in calcPt) return calcPt[calcKey];

    // fallback to trace value,
    //   must check if value isn't itself an array
    //   which means the trace attribute has a corresponding
    //   calcdata key, but its value is falsy
    var traceVal = lib.nestedProperty(trace, traceKey).get();
    if(!Array.isArray(traceVal)) return traceVal;
};

function makePtIndex2PtNumber(indexToPoints) {
    var ptIndex2ptNumber = {};
    for(var k in indexToPoints) {
        var pts = indexToPoints[k];
        for(var j = 0; j < pts.length; j++) {
            ptIndex2ptNumber[pts[j]] = +k;
        }
    }
    return ptIndex2ptNumber;
}

/** Tag selected calcdata items
 *
 * N.B. note that point 'index' corresponds to input data array index
 *  whereas 'number' is its post-transform version.
 *
 * @param {array} calcTrace
 * @param {object} trace
 *  - selectedpoints {array}
 *  - _indexToPoints {object}
 * @param {ptNumber2cdIndex} ptNumber2cdIndex (optional)
 *  optional map object for trace types that do not have 1-to-1 point number to
 *  calcdata item index correspondence (e.g. histogram)
 */
lib.tagSelected = function(calcTrace, trace, ptNumber2cdIndex) {
    var selectedpoints = trace.selectedpoints;
    var indexToPoints = trace._indexToPoints;
    var ptIndex2ptNumber;

    // make pt index-to-number map object, which takes care of transformed traces
    if(indexToPoints) {
        ptIndex2ptNumber = makePtIndex2PtNumber(indexToPoints);
    }

    function isCdIndexValid(v) {
        return v !== undefined && v < calcTrace.length;
    }

    for(var i = 0; i < selectedpoints.length; i++) {
        var ptIndex = selectedpoints[i];

        if(lib.isIndex(ptIndex)) {
            var ptNumber = ptIndex2ptNumber ? ptIndex2ptNumber[ptIndex] : ptIndex;
            var cdIndex = ptNumber2cdIndex ? ptNumber2cdIndex[ptNumber] : ptNumber;

            if(isCdIndexValid(cdIndex)) {
                calcTrace[cdIndex].selected = 1;
            }
        }
    }
};

lib.selIndices2selPoints = function(trace) {
    var selectedpoints = trace.selectedpoints;
    var indexToPoints = trace._indexToPoints;

    if(indexToPoints) {
        var ptIndex2ptNumber = makePtIndex2PtNumber(indexToPoints);
        var out = [];

        for(var i = 0; i < selectedpoints.length; i++) {
            var ptIndex = selectedpoints[i];
            if(lib.isIndex(ptIndex)) {
                var ptNumber = ptIndex2ptNumber[ptIndex];
                if(lib.isIndex(ptNumber)) {
                    out.push(ptNumber);
                }
            }
        }

        return out;
    } else {
        return selectedpoints;
    }
};

/** Returns target as set by 'target' transform attribute
 *
 * @param {object} trace : full trace object
 * @param {object} transformOpts : transform option object
 *  - target (string} :
 *      either an attribute string referencing an array in the trace object, or
 *      a set array.
 *
 * @return {array or false} : the target array (NOT a copy!!) or false if invalid
 */
lib.getTargetArray = function(trace, transformOpts) {
    var target = transformOpts.target;

    if(typeof target === 'string' && target) {
        var array = lib.nestedProperty(trace, target).get();
        return Array.isArray(array) ? array : false;
    } else if(Array.isArray(target)) {
        return target;
    }

    return false;
};

/**
 * modified version of jQuery's extend to strip out private objs and functions,
 * and cut arrays down to first <arraylen> or 1 elements
 * because extend-like algorithms are hella slow
 * obj2 is assumed to already be clean of these things (including no arrays)
 */
lib.minExtend = function(obj1, obj2) {
    var objOut = {};
    if(typeof obj2 !== 'object') obj2 = {};
    var arrayLen = 3;
    var keys = Object.keys(obj1);
    var i, k, v;

    for(i = 0; i < keys.length; i++) {
        k = keys[i];
        v = obj1[k];
        if(k.charAt(0) === '_' || typeof v === 'function') continue;
        else if(k === 'module') objOut[k] = v;
        else if(Array.isArray(v)) {
            if(k === 'colorscale') {
                objOut[k] = v.slice();
            } else {
                objOut[k] = v.slice(0, arrayLen);
            }
        }
        else if(v && (typeof v === 'object')) objOut[k] = lib.minExtend(obj1[k], obj2[k]);
        else objOut[k] = v;
    }

    keys = Object.keys(obj2);
    for(i = 0; i < keys.length; i++) {
        k = keys[i];
        v = obj2[k];
        if(typeof v !== 'object' || !(k in objOut) || typeof objOut[k] !== 'object') {
            objOut[k] = v;
        }
    }

    return objOut;
};

lib.titleCase = function(s) {
    return s.charAt(0).toUpperCase() + s.substr(1);
};

lib.containsAny = function(s, fragments) {
    for(var i = 0; i < fragments.length; i++) {
        if(s.indexOf(fragments[i]) !== -1) return true;
    }
    return false;
};

lib.isPlotDiv = function(el) {
    var el3 = d3.select(el);
    return el3.node() instanceof HTMLElement &&
        el3.size() &&
        el3.classed('js-plotly-plot');
};

lib.removeElement = function(el) {
    var elParent = el && el.parentNode;
    if(elParent) elParent.removeChild(el);
};

/**
 * for dynamically adding style rules
 * makes one stylesheet that contains all rules added
 * by all calls to this function
 */
lib.addStyleRule = function(selector, styleString) {
    lib.addRelatedStyleRule('global', selector, styleString);
};

/**
 * for dynamically adding style rules
 * to a stylesheet uniquely identified by a uid
 */
lib.addRelatedStyleRule = function(uid, selector, styleString) {
    var id = 'plotly.js-style-' + uid;
    var style = document.getElementById(id);
    if(!style) {
        style = document.createElement('style');
        style.setAttribute('id', id);
        // WebKit hack :(
        style.appendChild(document.createTextNode(''));
        document.head.appendChild(style);
    }
    var styleSheet = style.sheet;

    if(styleSheet.insertRule) {
        styleSheet.insertRule(selector + '{' + styleString + '}', 0);
    }
    else if(styleSheet.addRule) {
        styleSheet.addRule(selector, styleString, 0);
    }
    else lib.warn('addStyleRule failed');
};

/**
 * to remove from the page a stylesheet identified by a given uid
 */
lib.deleteRelatedStyleRule = function(uid) {
    var id = 'plotly.js-style-' + uid;
    var style = document.getElementById(id);
    if(style) lib.removeElement(style);
};

lib.isIE = function() {
    return typeof window.navigator.msSaveBlob !== 'undefined';
};

/**
 * Duck typing to recognize a d3 selection, mostly for IE9's benefit
 * because it doesn't handle instanceof like modern browsers
 */
lib.isD3Selection = function(obj) {
    return obj && (typeof obj.classed === 'function');
};

/**
 * Append element to DOM only if not present.
 *
 * @param {d3 selection} parent : parent selection of the element in question
 * @param {string} nodeType : node type of element to append
 * @param {string} className (optional) : class name of element in question
 * @param {fn} enterFn (optional) : optional fn applied to entering elements only
 * @return {d3 selection} selection of new layer
 *
 * Previously, we were using the following pattern:
 *
 * ```
 * var sel = parent.selectAll('.' + className)
 *     .data([0]);
 *
 * sel.enter().append(nodeType)
 *     .classed(className, true);
 *
 * return sel;
 * ```
 *
 * in numerous places in our codebase to achieve the same behavior.
 *
 * The logic below performs much better, mostly as we are using
 * `.select` instead `.selectAll` that is `querySelector` instead of
 * `querySelectorAll`.
 *
 */
lib.ensureSingle = function(parent, nodeType, className, enterFn) {
    var sel = parent.select(nodeType + (className ? '.' + className : ''));
    if(sel.size()) return sel;

    var layer = parent.append(nodeType);
    if(className) layer.classed(className, true);
    if(enterFn) layer.call(enterFn);

    return layer;
};

/**
 * Same as Lib.ensureSingle, but using id as selector.
 * This version is mostly used for clipPath nodes.
 *
 * @param {d3 selection} parent : parent selection of the element in question
 * @param {string} nodeType : node type of element to append
 * @param {string} id : id of element in question
 * @param {fn} enterFn (optional) : optional fn applied to entering elements only
 * @return {d3 selection} selection of new layer
 */
lib.ensureSingleById = function(parent, nodeType, id, enterFn) {
    var sel = parent.select(nodeType + '#' + id);
    if(sel.size()) return sel;

    var layer = parent.append(nodeType).attr('id', id);
    if(enterFn) layer.call(enterFn);

    return layer;
};

/**
 * Converts a string path to an object.
 *
 * When given a string containing an array element, it will create a `null`
 * filled array of the given size.
 *
 * @example
 * lib.objectFromPath('nested.test[2].path', 'value');
 * // returns { nested: { test: [null, null, { path: 'value' }]}
 *
 * @param   {string}    path to nested value
 * @param   {*}         any value to be set
 *
 * @return {Object} the constructed object with a full nested path
 */
lib.objectFromPath = function(path, value) {
    var keys = path.split('.');
    var tmpObj;
    var obj = tmpObj = {};

    for(var i = 0; i < keys.length; i++) {
        var key = keys[i];
        var el = null;

        var parts = keys[i].match(/(.*)\[([0-9]+)\]/);

        if(parts) {
            key = parts[1];
            el = parts[2];

            tmpObj = tmpObj[key] = [];

            if(i === keys.length - 1) {
                tmpObj[el] = value;
            } else {
                tmpObj[el] = {};
            }

            tmpObj = tmpObj[el];
        } else {

            if(i === keys.length - 1) {
                tmpObj[key] = value;
            } else {
                tmpObj[key] = {};
            }

            tmpObj = tmpObj[key];
        }
    }

    return obj;
};

/**
 * Iterate through an object in-place, converting dotted properties to objects.
 *
 * Examples:
 *
 *   lib.expandObjectPaths({'nested.test.path': 'value'});
 *     => { nested: { test: {path: 'value'}}}
 *
 * It also handles array notation, e.g.:
 *
 *   lib.expandObjectPaths({'foo[1].bar': 'value'});
 *     => { foo: [null, {bar: value}] }
 *
 * It handles merges the results when two properties are specified in parallel:
 *
 *   lib.expandObjectPaths({'foo[1].bar': 10, 'foo[0].bar': 20});
 *     => { foo: [{bar: 10}, {bar: 20}] }
 *
 * It does NOT, however, merge mulitple mutliply-nested arrays::
 *
 *   lib.expandObjectPaths({'marker[1].range[1]': 5, 'marker[1].range[0]': 4})
 *     => { marker: [null, {range: 4}] }
 */

// Store this to avoid recompiling regex on *every* prop since this may happen many
// many times for animations. Could maybe be inside the function. Not sure about
// scoping vs. recompilation tradeoff, but at least it's not just inlining it into
// the inner loop.
var dottedPropertyRegex = /^([^\[\.]+)\.(.+)?/;
var indexedPropertyRegex = /^([^\.]+)\[([0-9]+)\](\.)?(.+)?/;

lib.expandObjectPaths = function(data) {
    var match, key, prop, datum, idx, dest, trailingPath;
    if(typeof data === 'object' && !Array.isArray(data)) {
        for(key in data) {
            if(data.hasOwnProperty(key)) {
                if((match = key.match(dottedPropertyRegex))) {
                    datum = data[key];
                    prop = match[1];

                    delete data[key];

                    data[prop] = lib.extendDeepNoArrays(data[prop] || {}, lib.objectFromPath(key, lib.expandObjectPaths(datum))[prop]);
                } else if((match = key.match(indexedPropertyRegex))) {
                    datum = data[key];

                    prop = match[1];
                    idx = parseInt(match[2]);

                    delete data[key];

                    data[prop] = data[prop] || [];

                    if(match[3] === '.') {
                        // This is the case where theere are subsequent properties into which
                        // we must recurse, e.g. transforms[0].value
                        trailingPath = match[4];
                        dest = data[prop][idx] = data[prop][idx] || {};

                        // NB: Extend deep no arrays prevents this from working on multiple
                        // nested properties in the same object, e.g.
                        //
                        // {
                        //   foo[0].bar[1].range
                        //   foo[0].bar[0].range
                        // }
                        //
                        // In this case, the extendDeepNoArrays will overwrite one array with
                        // the other, so that both properties *will not* be present in the
                        // result. Fixing this would require a more intelligent tracking
                        // of changes and merging than extendDeepNoArrays currently accomplishes.
                        lib.extendDeepNoArrays(dest, lib.objectFromPath(trailingPath, lib.expandObjectPaths(datum)));
                    } else {
                        // This is the case where this property is the end of the line,
                        // e.g. xaxis.range[0]
                        data[prop][idx] = lib.expandObjectPaths(datum);
                    }
                } else {
                    data[key] = lib.expandObjectPaths(data[key]);
                }
            }
        }
    }

    return data;
};

/**
 * Converts value to string separated by the provided separators.
 *
 * @example
 * lib.numSeparate(2016, '.,');
 * // returns '2016'
 *
 * @example
 * lib.numSeparate(3000, '.,', true);
 * // returns '3,000'
 *
 * @example
 * lib.numSeparate(1234.56, '|,')
 * // returns '1,234|56'
 *
 * @param   {string|number} value       the value to be converted
 * @param   {string}    separators  string of decimal, then thousands separators
 * @param   {boolean}    separatethousands  boolean, 4-digit integers are separated if true
 *
 * @return  {string}    the value that has been separated
 */
lib.numSeparate = function(value, separators, separatethousands) {
    if(!separatethousands) separatethousands = false;

    if(typeof separators !== 'string' || separators.length === 0) {
        throw new Error('Separator string required for formatting!');
    }

    if(typeof value === 'number') {
        value = String(value);
    }

    var thousandsRe = /(\d+)(\d{3})/;
    var decimalSep = separators.charAt(0);
    var thouSep = separators.charAt(1);

    var x = value.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? decimalSep + x[1] : '';

    // Years are ignored for thousands separators
    if(thouSep && (x.length > 1 || x1.length > 4 || separatethousands)) {
        while(thousandsRe.test(x1)) {
            x1 = x1.replace(thousandsRe, '$1' + thouSep + '$2');
        }
    }

    return x1 + x2;
};

lib.TEMPLATE_STRING_REGEX = /%{([^\s%{}:]*)(:[^}]*)?}/g;
var SIMPLE_PROPERTY_REGEX = /^\w*$/;

/**
 * Substitute values from an object into a string
 *
 * Examples:
 *  Lib.templateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
 *  Lib.templateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
 *
 * @param {string}  input string containing %{...} template strings
 * @param {obj}     data object containing substitution values
 *
 * @return {string} templated string
 */
lib.templateString = function(string, obj) {
    // Not all that useful, but cache nestedProperty instantiation
    // just in case it speeds things up *slightly*:
    var getterCache = {};

    return string.replace(lib.TEMPLATE_STRING_REGEX, function(dummy, key) {
        if(SIMPLE_PROPERTY_REGEX.test(key)) {
            return obj[key] || '';
        }
        getterCache[key] = getterCache[key] || lib.nestedProperty(obj, key).get;
        return getterCache[key]() || '';
    });
};

var TEMPLATE_STRING_FORMAT_SEPARATOR = /^:/;
var numberOfHoverTemplateWarnings = 0;
var maximumNumberOfHoverTemplateWarnings = 10;
/**
 * Substitute values from an object into a string and optionally formats them using d3-format,
 * or fallback to associated labels.
 *
 * Examples:
 *  Lib.hovertemplateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
 *  Lib.hovertemplateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
 *  Lib.hovertemplateString('price: %{y:$.2f}', {y: 1}) --> 'price: $1.00'
 *
 * @param {obj}     d3 locale
 * @param {string}  input string containing %{...:...} template strings
 * @param {obj}     data object containing fallback text when no formatting is specified, ex.: {yLabel: 'formattedYValue'}
 * @param {obj}     data objects containing substitution values
 *
 * @return {string} templated string
 */
lib.hovertemplateString = function(string, labels, d3locale) {
    var args = arguments;
    // Not all that useful, but cache nestedProperty instantiation
    // just in case it speeds things up *slightly*:
    var getterCache = {};

    return string.replace(lib.TEMPLATE_STRING_REGEX, function(match, key, format) {
        var obj, value, i;
        for(i = 3; i < args.length; i++) {
            obj = args[i];
            if(obj.hasOwnProperty(key)) {
                value = obj[key];
                break;
            }

            if(!SIMPLE_PROPERTY_REGEX.test(key)) {
                value = getterCache[key] || lib.nestedProperty(obj, key).get();
                if(value) getterCache[key] = value;
            }
            if(value !== undefined) break;
        }

        if(value === undefined) {
            if(numberOfHoverTemplateWarnings < maximumNumberOfHoverTemplateWarnings) {
                lib.warn('Variable \'' + key + '\' in hovertemplate could not be found!');
                value = match;
            }

            if(numberOfHoverTemplateWarnings === maximumNumberOfHoverTemplateWarnings) {
                lib.warn('Too many hovertemplate warnings - additional warnings will be suppressed');
            }
            numberOfHoverTemplateWarnings++;
        }

        if(format) {
            var fmt;
            if(d3locale) {
                fmt = d3locale.numberFormat;
            } else {
                fmt = d3.format;
            }
            value = fmt(format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ''))(value);
        } else {
            if(labels.hasOwnProperty(key + 'Label')) value = labels[key + 'Label'];
        }
        return value;
    });
};

/*
 * alphanumeric string sort, tailored for subplot IDs like scene2, scene10, x10y13 etc
 */
var char0 = 48;
var char9 = 57;
lib.subplotSort = function(a, b) {
    var l = Math.min(a.length, b.length) + 1;
    var numA = 0;
    var numB = 0;
    for(var i = 0; i < l; i++) {
        var charA = a.charCodeAt(i) || 0;
        var charB = b.charCodeAt(i) || 0;
        var isNumA = charA >= char0 && charA <= char9;
        var isNumB = charB >= char0 && charB <= char9;

        if(isNumA) numA = 10 * numA + charA - char0;
        if(isNumB) numB = 10 * numB + charB - char0;

        if(!isNumA || !isNumB) {
            if(numA !== numB) return numA - numB;
            if(charA !== charB) return charA - charB;
        }
    }
    return numB - numA;
};

// repeatable pseudorandom generator
var randSeed = 2000000000;

lib.seedPseudoRandom = function() {
    randSeed = 2000000000;
};

lib.pseudoRandom = function() {
    var lastVal = randSeed;
    randSeed = (69069 * randSeed + 1) % 4294967296;
    // don't let consecutive vals be too close together
    // gets away from really trying to be random, in favor of better local uniformity
    if(Math.abs(randSeed - lastVal) < 429496729) return lib.pseudoRandom();
    return randSeed / 4294967296;
};

},{"../constants/numerical":674,"./anchor_utils":678,"./angles":679,"./array":680,"./clean_number":681,"./clear_responsive":683,"./coerce":684,"./dates":685,"./extend":687,"./filter_unique":688,"./filter_visible":689,"./geometry2d":692,"./get_graph_div":693,"./identity":696,"./is_plain_object":698,"./keyed_container":699,"./localize":700,"./loggers":701,"./make_trace_groups":702,"./matrix":703,"./mod":704,"./nested_property":705,"./noop":706,"./notifier":707,"./push_unique":711,"./regex":713,"./relative_attr":714,"./relink_private":715,"./search":716,"./stats":719,"./throttle":722,"./to_log_range":723,"d3":151,"fast-isnumeric":218}],698:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

// more info: http://stackoverflow.com/questions/18531624/isplainobject-thing
module.exports = function isPlainObject(obj) {

    // We need to be a little less strict in the `imagetest` container because
    // of how async image requests are handled.
    //
    // N.B. isPlainObject(new Constructor()) will return true in `imagetest`
    if(window && window.process && window.process.versions) {
        return Object.prototype.toString.call(obj) === '[object Object]';
    }

    return (
        Object.prototype.toString.call(obj) === '[object Object]' &&
        Object.getPrototypeOf(obj) === Object.prototype
    );
};

},{}],699:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var nestedProperty = _dereq_('./nested_property');

var SIMPLE_PROPERTY_REGEX = /^\w*$/;

// bitmask for deciding what's updated. Sometimes the name needs to be updated,
// sometimes the value needs to be updated, and sometimes both do. This is just
// a simple way to track what's updated such that it's a simple OR operation to
// assimilate new updates.
//
// The only exception is the UNSET bit that tracks when we need to explicitly
// unset and remove the property. This concrn arises because of the special
// way in which nestedProperty handles null/undefined. When you specify `null`,
// it prunes any unused items in the tree. I ran into some issues with it getting
// null vs undefined confused, so UNSET is just a bit that forces the property
// update to send `null`, removing the property explicitly rather than setting
// it to undefined.
var NONE = 0;
var NAME = 1;
var VALUE = 2;
var BOTH = 3;
var UNSET = 4;

module.exports = function keyedContainer(baseObj, path, keyName, valueName) {
    keyName = keyName || 'name';
    valueName = valueName || 'value';
    var i, arr, baseProp;
    var changeTypes = {};

    if(path && path.length) {
        baseProp = nestedProperty(baseObj, path);
        arr = baseProp.get();
    } else {
        arr = baseObj;
    }

    path = path || '';

    // Construct an index:
    var indexLookup = {};
    if(arr) {
        for(i = 0; i < arr.length; i++) {
            indexLookup[arr[i][keyName]] = i;
        }
    }

    var isSimpleValueProp = SIMPLE_PROPERTY_REGEX.test(valueName);

    var obj = {
        set: function(name, value) {
            var changeType = value === null ? UNSET : NONE;

            // create the base array if necessary
            if(!arr) {
                if(!baseProp || changeType === UNSET) return;

                arr = [];
                baseProp.set(arr);
            }

            var idx = indexLookup[name];
            if(idx === undefined) {
                if(changeType === UNSET) return;

                changeType = changeType | BOTH;
                idx = arr.length;
                indexLookup[name] = idx;
            } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : nestedProperty(arr[idx], valueName).get())) {
                changeType = changeType | VALUE;
            }

            var newValue = arr[idx] = arr[idx] || {};
            newValue[keyName] = name;

            if(isSimpleValueProp) {
                newValue[valueName] = value;
            } else {
                nestedProperty(newValue, valueName).set(value);
            }

            // If it's not an unset, force that bit to be unset. This is all related to the fact
            // that undefined and null are a bit specially implemented in nestedProperties.
            if(value !== null) {
                changeType = changeType & ~UNSET;
            }

            changeTypes[idx] = changeTypes[idx] | changeType;

            return obj;
        },
        get: function(name) {
            if(!arr) return;

            var idx = indexLookup[name];

            if(idx === undefined) {
                return undefined;
            } else if(isSimpleValueProp) {
                return arr[idx][valueName];
            } else {
                return nestedProperty(arr[idx], valueName).get();
            }
        },
        rename: function(name, newName) {
            var idx = indexLookup[name];

            if(idx === undefined) return obj;
            changeTypes[idx] = changeTypes[idx] | NAME;

            indexLookup[newName] = idx;
            delete indexLookup[name];

            arr[idx][keyName] = newName;

            return obj;
        },
        remove: function(name) {
            var idx = indexLookup[name];

            if(idx === undefined) return obj;

            var object = arr[idx];
            if(Object.keys(object).length > 2) {
                // This object contains more than just the key/value, so unset
                // the value without modifying the entry otherwise:
                changeTypes[idx] = changeTypes[idx] | VALUE;
                return obj.set(name, null);
            }

            if(isSimpleValueProp) {
                for(i = idx; i < arr.length; i++) {
                    changeTypes[i] = changeTypes[i] | BOTH;
                }
                for(i = idx; i < arr.length; i++) {
                    indexLookup[arr[i][keyName]]--;
                }
                arr.splice(idx, 1);
                delete(indexLookup[name]);
            } else {
                // Perform this update *strictly* so we can check whether the result's
                // been pruned. If so, it's a removal. If not, it's a value unset only.
                nestedProperty(object, valueName).set(null);

                // Now check if the top level nested property has any keys left. If so,
                // the object still has values so we only want to unset the key. If not,
                // the entire object can be removed since there's no other data.
                // var topLevelKeys = Object.keys(object[valueName.split('.')[0]] || []);

                changeTypes[idx] = changeTypes[idx] | VALUE | UNSET;
            }

            return obj;
        },
        constructUpdate: function() {
            var astr, idx;
            var update = {};
            var changed = Object.keys(changeTypes);
            for(var i = 0; i < changed.length; i++) {
                idx = changed[i];
                astr = path + '[' + idx + ']';
                if(arr[idx]) {
                    if(changeTypes[idx] & NAME) {
                        update[astr + '.' + keyName] = arr[idx][keyName];
                    }
                    if(changeTypes[idx] & VALUE) {
                        if(isSimpleValueProp) {
                            update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : arr[idx][valueName];
                        } else {
                            update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : nestedProperty(arr[idx], valueName).get();
                        }
                    }
                } else {
                    update[astr] = null;
                }
            }

            return update;
        }
    };

    return obj;
};

},{"./nested_property":705}],700:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../registry');

/**
 * localize: translate a string for the current locale
 *
 * @param {object} gd: the graphDiv for context
 *  gd._context.locale determines the language (& optional region/country)
 *  the dictionary for each locale may either be supplied in
 *  gd._context.locales or globally via Plotly.register
 * @param {string} s: the string to translate
 */
module.exports = function localize(gd, s) {
    var locale = gd._context.locale;

    /*
     * Priority of lookup:
     *     contextDicts[locale],
     *     registeredDicts[locale],
     *     contextDicts[baseLocale], (if baseLocale is distinct)
     *     registeredDicts[baseLocale]
     * Return the first translation we find.
     * This way if you have a regionalization you are allowed to specify
     * only what's different from the base locale, everything else will
     * fall back on the base.
     */
    for(var i = 0; i < 2; i++) {
        var locales = gd._context.locales;
        for(var j = 0; j < 2; j++) {
            var dict = (locales[locale] || {}).dictionary;
            if(dict) {
                var out = dict[s];
                if(out) return out;
            }
            locales = Registry.localeRegistry;
        }

        var baseLocale = locale.split('-')[0];
        if(baseLocale === locale) break;
        locale = baseLocale;
    }

    return s;
};

},{"../registry":826}],701:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/* eslint-disable no-console */

var dfltConfig = _dereq_('../plot_api/plot_config').dfltConfig;

var loggers = module.exports = {};

/**
 * ------------------------------------------
 * debugging tools
 * ------------------------------------------
 */

loggers.log = function() {
    if(dfltConfig.logging > 1) {
        var messages = ['LOG:'];

        for(var i = 0; i < arguments.length; i++) {
            messages.push(arguments[i]);
        }

        apply(console.trace || console.log, messages);
    }
};

loggers.warn = function() {
    if(dfltConfig.logging > 0) {
        var messages = ['WARN:'];

        for(var i = 0; i < arguments.length; i++) {
            messages.push(arguments[i]);
        }

        apply(console.trace || console.log, messages);
    }
};

loggers.error = function() {
    if(dfltConfig.logging > 0) {
        var messages = ['ERROR:'];

        for(var i = 0; i < arguments.length; i++) {
            messages.push(arguments[i]);
        }

        apply(console.error, messages);
    }
};

/*
 * Robust apply, for IE9 where console.log doesn't support
 * apply like other functions do
 */
function apply(f, args) {
    if(f && f.apply) {
        try {
            // `this` should always be console, since here we're always
            // applying a method of the console object.
            f.apply(console, args);
            return;
        }
        catch(e) { /* in case apply failed, fall back on the code below */ }
    }

    // no apply - just try calling the function on each arg independently
    for(var i = 0; i < args.length; i++) {
        try {
            f(args[i]);
        }
        catch(e) {
            // still fails - last resort simple console.log
            console.log(args[i]);
        }
    }
}

},{"../plot_api/plot_config":733}],702:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

/**
 * General helper to manage trace groups based on calcdata
 *
 * @param {d3.selection} traceLayer: a selection containing a single group
 *     to draw these traces into
 * @param {array} cdModule: array of calcdata items for this
 *     module and subplot combination. Assumes the calcdata item for each
 *     trace is an array with the fullData trace attached to the first item.
 * @param {string} cls: the class attribute to give each trace group
 *     so you can give multiple classes separated by spaces
 */
module.exports = function makeTraceGroups(traceLayer, cdModule, cls) {
    var traces = traceLayer.selectAll('g.' + cls.replace(/\s/g, '.'))
        .data(cdModule, function(cd) { return cd[0].trace.uid; });

    traces.exit().remove();

    traces.enter().append('g')
        .attr('class', cls);

    traces.order();

    return traces;
};

},{}],703:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


exports.init2dArray = function(rowLength, colLength) {
    var array = new Array(rowLength);
    for(var i = 0; i < rowLength; i++) array[i] = new Array(colLength);
    return array;
};

/**
 * transpose a (possibly ragged) 2d array z. inspired by
 * http://stackoverflow.com/questions/17428587/
 * transposing-a-2d-array-in-javascript
 */
exports.transposeRagged = function(z) {
    var maxlen = 0;
    var zlen = z.length;
    var i, j;
    // Maximum row length:
    for(i = 0; i < zlen; i++) maxlen = Math.max(maxlen, z[i].length);

    var t = new Array(maxlen);
    for(i = 0; i < maxlen; i++) {
        t[i] = new Array(zlen);
        for(j = 0; j < zlen; j++) t[i][j] = z[j][i];
    }

    return t;
};

// our own dot function so that we don't need to include numeric
exports.dot = function(x, y) {
    if(!(x.length && y.length) || x.length !== y.length) return null;

    var len = x.length;
    var out;
    var i;

    if(x[0].length) {
        // mat-vec or mat-mat
        out = new Array(len);
        for(i = 0; i < len; i++) out[i] = exports.dot(x[i], y);
    }
    else if(y[0].length) {
        // vec-mat
        var yTranspose = exports.transposeRagged(y);
        out = new Array(yTranspose.length);
        for(i = 0; i < yTranspose.length; i++) out[i] = exports.dot(x, yTranspose[i]);
    }
    else {
        // vec-vec
        out = 0;
        for(i = 0; i < len; i++) out += x[i] * y[i];
    }

    return out;
};

// translate by (x,y)
exports.translationMatrix = function(x, y) {
    return [[1, 0, x], [0, 1, y], [0, 0, 1]];
};

// rotate by alpha around (0,0)
exports.rotationMatrix = function(alpha) {
    var a = alpha * Math.PI / 180;
    return [[Math.cos(a), -Math.sin(a), 0],
            [Math.sin(a), Math.cos(a), 0],
            [0, 0, 1]];
};

// rotate by alpha around (x,y)
exports.rotationXYMatrix = function(a, x, y) {
    return exports.dot(
        exports.dot(exports.translationMatrix(x, y),
                    exports.rotationMatrix(a)),
        exports.translationMatrix(-x, -y));
};

// applies a 2D transformation matrix to either x and y params or an [x,y] array
exports.apply2DTransform = function(transform) {
    return function() {
        var args = arguments;
        if(args.length === 3) {
            args = args[0];
        }// from map
        var xy = arguments.length === 1 ? args[0] : [args[0], args[1]];
        return exports.dot(transform, [xy[0], xy[1], 1]).slice(0, 2);
    };
};

// applies a 2D transformation matrix to an [x1,y1,x2,y2] array (to transform a segment)
exports.apply2DTransform2 = function(transform) {
    var at = exports.apply2DTransform(transform);
    return function(xys) {
        return at(xys.slice(0, 2)).concat(at(xys.slice(2, 4)));
    };
};

},{}],704:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * sanitized modulus function that always returns in the range [0, d)
 * rather than (-d, 0] if v is negative
 */
function mod(v, d) {
    var out = v % d;
    return out < 0 ? out + d : out;
}

/**
 * sanitized modulus function that always returns in the range [-d/2, d/2]
 * rather than (-d, 0] if v is negative
 */
function modHalf(v, d) {
    return Math.abs(v) > (d / 2) ?
        v - Math.round(v / d) * d :
        v;
}

module.exports = {
    mod: mod,
    modHalf: modHalf
};

},{}],705:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var isArrayOrTypedArray = _dereq_('./array').isArrayOrTypedArray;

/**
 * convert a string s (such as 'xaxis.range[0]')
 * representing a property of nested object into set and get methods
 * also return the string and object so we don't have to keep track of them
 * allows [-1] for an array index, to set a property inside all elements
 * of an array
 * eg if obj = {arr: [{a: 1}, {a: 2}]}
 * you can do p = nestedProperty(obj, 'arr[-1].a')
 * but you cannot set the array itself this way, to do that
 * just set the whole array.
 * eg if obj = {arr: [1, 2, 3]}
 * you can't do nestedProperty(obj, 'arr[-1]').set(5)
 * but you can do nestedProperty(obj, 'arr').set([5, 5, 5])
 */
module.exports = function nestedProperty(container, propStr) {
    if(isNumeric(propStr)) propStr = String(propStr);
    else if(typeof propStr !== 'string' ||
            propStr.substr(propStr.length - 4) === '[-1]') {
        throw 'bad property string';
    }

    var j = 0;
    var propParts = propStr.split('.');
    var indexed;
    var indices;
    var i;

    // check for parts of the nesting hierarchy that are numbers (ie array elements)
    while(j < propParts.length) {
        // look for non-bracket chars, then any number of [##] blocks
        indexed = String(propParts[j]).match(/^([^\[\]]*)((\[\-?[0-9]*\])+)$/);
        if(indexed) {
            if(indexed[1]) propParts[j] = indexed[1];
            // allow propStr to start with bracketed array indices
            else if(j === 0) propParts.splice(0, 1);
            else throw 'bad property string';

            indices = indexed[2]
                .substr(1, indexed[2].length - 2)
                .split('][');

            for(i = 0; i < indices.length; i++) {
                j++;
                propParts.splice(j, 0, Number(indices[i]));
            }
        }
        j++;
    }

    if(typeof container !== 'object') {
        return badContainer(container, propStr, propParts);
    }

    return {
        set: npSet(container, propParts, propStr),
        get: npGet(container, propParts),
        astr: propStr,
        parts: propParts,
        obj: container
    };
};

function npGet(cont, parts) {
    return function() {
        var curCont = cont;
        var curPart;
        var allSame;
        var out;
        var i;
        var j;

        for(i = 0; i < parts.length - 1; i++) {
            curPart = parts[i];
            if(curPart === -1) {
                allSame = true;
                out = [];
                for(j = 0; j < curCont.length; j++) {
                    out[j] = npGet(curCont[j], parts.slice(i + 1))();
                    if(out[j] !== out[0]) allSame = false;
                }
                return allSame ? out[0] : out;
            }
            if(typeof curPart === 'number' && !isArrayOrTypedArray(curCont)) {
                return undefined;
            }
            curCont = curCont[curPart];
            if(typeof curCont !== 'object' || curCont === null) {
                return undefined;
            }
        }

        // only hit this if parts.length === 1
        if(typeof curCont !== 'object' || curCont === null) return undefined;

        out = curCont[parts[i]];
        if(out === null) return undefined;
        return out;
    };
}

/*
 * Can this value be deleted? We can delete `undefined`, and `null` except INSIDE an
 * *args* array.
 *
 * Previously we also deleted some `{}` and `[]`, in order to try and make set/unset
 * a net noop; but this causes far more complication than it's worth, and still had
 * lots of exceptions. See https://github.com/plotly/plotly.js/issues/1410
 *
 * *args* arrays get passed directly to API methods and we should respect null if
 * the user put it there, but otherwise null is deleted as we use it as code
 * in restyle/relayout/update for "delete this value" whereas undefined means
 * "ignore this edit"
 */
var ARGS_PATTERN = /(^|\.)args\[/;
function isDeletable(val, propStr) {
    return (val === undefined) || (val === null && !propStr.match(ARGS_PATTERN));
}

function npSet(cont, parts, propStr) {
    return function(val) {
        var curCont = cont;
        var propPart = '';
        var containerLevels = [[cont, propPart]];
        var toDelete = isDeletable(val, propStr);
        var curPart;
        var i;

        for(i = 0; i < parts.length - 1; i++) {
            curPart = parts[i];

            if(typeof curPart === 'number' && !isArrayOrTypedArray(curCont)) {
                throw 'array index but container is not an array';
            }

            // handle special -1 array index
            if(curPart === -1) {
                toDelete = !setArrayAll(curCont, parts.slice(i + 1), val, propStr);
                if(toDelete) break;
                else return;
            }

            if(!checkNewContainer(curCont, curPart, parts[i + 1], toDelete)) {
                break;
            }

            curCont = curCont[curPart];

            if(typeof curCont !== 'object' || curCont === null) {
                throw 'container is not an object';
            }

            propPart = joinPropStr(propPart, curPart);

            containerLevels.push([curCont, propPart]);
        }

        if(toDelete) {
            if(i === parts.length - 1) {
                delete curCont[parts[i]];

                // The one bit of pruning we still do: drop `undefined` from the end of arrays.
                // In case someone has already unset previous items, continue until we hit a
                // non-undefined value.
                if(Array.isArray(curCont) && +parts[i] === curCont.length - 1) {
                    while(curCont.length && curCont[curCont.length - 1] === undefined) {
                        curCont.pop();
                    }
                }
            }
        }
        else curCont[parts[i]] = val;
    };
}

function joinPropStr(propStr, newPart) {
    var toAdd = newPart;
    if(isNumeric(newPart)) toAdd = '[' + newPart + ']';
    else if(propStr) toAdd = '.' + newPart;

    return propStr + toAdd;
}

// handle special -1 array index
function setArrayAll(containerArray, innerParts, val, propStr) {
    var arrayVal = isArrayOrTypedArray(val);
    var allSet = true;
    var thisVal = val;
    var thisPropStr = propStr.replace('-1', 0);
    var deleteThis = arrayVal ? false : isDeletable(val, thisPropStr);
    var firstPart = innerParts[0];
    var i;

    for(i = 0; i < containerArray.length; i++) {
        thisPropStr = propStr.replace('-1', i);
        if(arrayVal) {
            thisVal = val[i % val.length];
            deleteThis = isDeletable(thisVal, thisPropStr);
        }
        if(deleteThis) allSet = false;
        if(!checkNewContainer(containerArray, i, firstPart, deleteThis)) {
            continue;
        }
        npSet(containerArray[i], innerParts, propStr.replace('-1', i))(thisVal);
    }
    return allSet;
}

/**
 * make new sub-container as needed.
 * returns false if there's no container and none is needed
 * because we're only deleting an attribute
 */
function checkNewContainer(container, part, nextPart, toDelete) {
    if(container[part] === undefined) {
        if(toDelete) return false;

        if(typeof nextPart === 'number') container[part] = [];
        else container[part] = {};
    }
    return true;
}

function badContainer(container, propStr, propParts) {
    return {
        set: function() { throw 'bad container'; },
        get: function() {},
        astr: propStr,
        parts: propParts,
        obj: container
    };
}

},{"./array":680,"fast-isnumeric":218}],706:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// Simple helper functions
// none of these need any external deps

module.exports = function noop() {};

},{}],707:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');

var NOTEDATA = [];

/**
 * notifier
 * @param {String} text The person's user name
 * @param {Number} [delay=1000] The delay time in milliseconds
 *          or 'long' which provides 2000 ms delay time.
 * @return {undefined} this function does not return a value
 */
module.exports = function(text, displayLength) {
    if(NOTEDATA.indexOf(text) !== -1) return;

    NOTEDATA.push(text);

    var ts = 1000;
    if(isNumeric(displayLength)) ts = displayLength;
    else if(displayLength === 'long') ts = 3000;

    var notifierContainer = d3.select('body')
        .selectAll('.plotly-notifier')
        .data([0]);
    notifierContainer.enter()
        .append('div')
        .classed('plotly-notifier', true);

    var notes = notifierContainer.selectAll('.notifier-note').data(NOTEDATA);

    function killNote(transition) {
        transition
            .duration(700)
            .style('opacity', 0)
            .each('end', function(thisText) {
                var thisIndex = NOTEDATA.indexOf(thisText);
                if(thisIndex !== -1) NOTEDATA.splice(thisIndex, 1);
                d3.select(this).remove();
            });
    }

    notes.enter().append('div')
        .classed('notifier-note', true)
        .style('opacity', 0)
        .each(function(thisText) {
            var note = d3.select(this);

            note.append('button')
                .classed('notifier-close', true)
                .html('&times;')
                .on('click', function() {
                    note.transition().call(killNote);
                });

            var p = note.append('p');
            var lines = thisText.split(/<br\s*\/?>/g);
            for(var i = 0; i < lines.length; i++) {
                if(i) p.append('br');
                p.append('span').text(lines[i]);
            }

            note.transition()
                    .duration(700)
                    .style('opacity', 1)
                .transition()
                    .delay(ts)
                    .call(killNote);
        });
};

},{"d3":151,"fast-isnumeric":218}],708:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var setCursor = _dereq_('./setcursor');

var STASHATTR = 'data-savedcursor';
var NO_CURSOR = '!!';

/*
 * works with our CSS cursor classes (see css/_cursor.scss)
 * to override a previous cursor set on d3 single-element selections,
 * by moving the name of the original cursor to the data-savedcursor attr.
 * omit cursor to revert to the previously set value.
 */
module.exports = function overrideCursor(el3, csr) {
    var savedCursor = el3.attr(STASHATTR);
    if(csr) {
        if(!savedCursor) {
            var classes = (el3.attr('class') || '').split(' ');
            for(var i = 0; i < classes.length; i++) {
                var cls = classes[i];
                if(cls.indexOf('cursor-') === 0) {
                    el3.attr(STASHATTR, cls.substr(7))
                        .classed(cls, false);
                }
            }
            if(!el3.attr(STASHATTR)) {
                el3.attr(STASHATTR, NO_CURSOR);
            }
        }
        setCursor(el3, csr);
    }
    else if(savedCursor) {
        el3.attr(STASHATTR, null);

        if(savedCursor === NO_CURSOR) setCursor(el3);
        else setCursor(el3, savedCursor);
    }
};

},{"./setcursor":717}],709:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var dot = _dereq_('./matrix').dot;
var BADNUM = _dereq_('../constants/numerical').BADNUM;

var polygon = module.exports = {};

/**
 * Turn an array of [x, y] pairs into a polygon object
 * that can test if points are inside it
 *
 * @param ptsIn Array of [x, y] pairs
 *
 * @returns polygon Object {xmin, xmax, ymin, ymax, pts, contains}
 *      (x|y)(min|max) are the bounding rect of the polygon
 *      pts is the original array, with the first pair repeated at the end
 *      contains is a function: (pt, omitFirstEdge)
 *          pt is the [x, y] pair to test
 *          omitFirstEdge truthy means points exactly on the first edge don't
 *              count. This is for use adding one polygon to another so we
 *              don't double-count the edge where they meet.
 *          returns boolean: is pt inside the polygon (including on its edges)
 */
polygon.tester = function tester(ptsIn) {
    var pts = ptsIn.slice();
    var xmin = pts[0][0];
    var xmax = xmin;
    var ymin = pts[0][1];
    var ymax = ymin;
    var i;

    pts.push(pts[0]);
    for(i = 1; i < pts.length; i++) {
        xmin = Math.min(xmin, pts[i][0]);
        xmax = Math.max(xmax, pts[i][0]);
        ymin = Math.min(ymin, pts[i][1]);
        ymax = Math.max(ymax, pts[i][1]);
    }

    // do we have a rectangle? Handle this here, so we can use the same
    // tester for the rectangular case without sacrificing speed

    var isRect = false;
    var rectFirstEdgeTest;

    if(pts.length === 5) {
        if(pts[0][0] === pts[1][0]) { // vert, horz, vert, horz
            if(pts[2][0] === pts[3][0] &&
                    pts[0][1] === pts[3][1] &&
                    pts[1][1] === pts[2][1]) {
                isRect = true;
                rectFirstEdgeTest = function(pt) { return pt[0] === pts[0][0]; };
            }
        }
        else if(pts[0][1] === pts[1][1]) { // horz, vert, horz, vert
            if(pts[2][1] === pts[3][1] &&
                    pts[0][0] === pts[3][0] &&
                    pts[1][0] === pts[2][0]) {
                isRect = true;
                rectFirstEdgeTest = function(pt) { return pt[1] === pts[0][1]; };
            }
        }
    }

    function rectContains(pt, omitFirstEdge) {
        var x = pt[0];
        var y = pt[1];

        if(x === BADNUM || x < xmin || x > xmax || y === BADNUM || y < ymin || y > ymax) {
            // pt is outside the bounding box of polygon
            return false;
        }
        if(omitFirstEdge && rectFirstEdgeTest(pt)) return false;

        return true;
    }

    function contains(pt, omitFirstEdge) {
        var x = pt[0];
        var y = pt[1];

        if(x === BADNUM || x < xmin || x > xmax || y === BADNUM || y < ymin || y > ymax) {
            // pt is outside the bounding box of polygon
            return false;
        }

        var imax = pts.length;
        var x1 = pts[0][0];
        var y1 = pts[0][1];
        var crossings = 0;
        var i;
        var x0;
        var y0;
        var xmini;
        var ycross;

        for(i = 1; i < imax; i++) {
            // find all crossings of a vertical line upward from pt with
            // polygon segments
            // crossings exactly at xmax don't count, unless the point is
            // exactly on the segment, then it counts as inside.
            x0 = x1;
            y0 = y1;
            x1 = pts[i][0];
            y1 = pts[i][1];
            xmini = Math.min(x0, x1);

            // outside the bounding box of this segment, it's only a crossing
            // if it's below the box.
            if(x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) {
                continue;
            }
            else if(y < Math.min(y0, y1)) {
                // don't count the left-most point of the segment as a crossing
                // because we don't want to double-count adjacent crossings
                // UNLESS the polygon turns past vertical at exactly this x
                // Note that this is repeated below, but we can't factor it out
                // because
                if(x !== xmini) crossings++;
            }
            // inside the bounding box, check the actual line intercept
            else {
                // vertical segment - we know already that the point is exactly
                // on the segment, so mark the crossing as exactly at the point.
                if(x1 === x0) ycross = y;
                // any other angle
                else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0);

                // exactly on the edge: counts as inside the polygon, unless it's the
                // first edge and we're omitting it.
                if(y === ycross) {
                    if(i === 1 && omitFirstEdge) return false;
                    return true;
                }

                if(y <= ycross && x !== xmini) crossings++;
            }
        }

        // if we've gotten this far, odd crossings means inside, even is outside
        return crossings % 2 === 1;
    }

    // detect if poly is degenerate
    var degenerate = true;
    var lastPt = pts[0];
    for(i = 1; i < pts.length; i++) {
        if(lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) {
            degenerate = false;
            break;
        }
    }

    return {
        xmin: xmin,
        xmax: xmax,
        ymin: ymin,
        ymax: ymax,
        pts: pts,
        contains: isRect ? rectContains : contains,
        isRect: isRect,
        degenerate: degenerate
    };
};

/**
 * Test if a segment of a points array is bent or straight
 *
 * @param pts Array of [x, y] pairs
 * @param start the index of the proposed start of the straight section
 * @param end the index of the proposed end point
 * @param tolerance the max distance off the line connecting start and end
 *      before the line counts as bent
 * @returns boolean: true means this segment is bent, false means straight
 */
var isBent = polygon.isSegmentBent = function isBent(pts, start, end, tolerance) {
    var startPt = pts[start];
    var segment = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]];
    var segmentSquared = dot(segment, segment);
    var segmentLen = Math.sqrt(segmentSquared);
    var unitPerp = [-segment[1] / segmentLen, segment[0] / segmentLen];
    var i;
    var part;
    var partParallel;

    for(i = start + 1; i < end; i++) {
        part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]];
        partParallel = dot(part, segment);

        if(partParallel < 0 || partParallel > segmentSquared ||
            Math.abs(dot(part, unitPerp)) > tolerance) return true;
    }
    return false;
};

/**
 * Make a filtering polygon, to minimize the number of segments
 *
 * @param pts Array of [x, y] pairs (must start with at least 1 pair)
 * @param tolerance the maximum deviation from straight allowed for
 *      removing points to simplify the polygon
 *
 * @returns Object {addPt, raw, filtered}
 *      addPt is a function(pt: [x, y] pair) to add a raw point and
 *          continue filtering
 *      raw is all the input points
 *      filtered is the resulting filtered Array of [x, y] pairs
 */
polygon.filter = function filter(pts, tolerance) {
    var ptsFiltered = [pts[0]];
    var doneRawIndex = 0;
    var doneFilteredIndex = 0;

    function addPt(pt) {
        pts.push(pt);
        var prevFilterLen = ptsFiltered.length;
        var iLast = doneRawIndex;
        ptsFiltered.splice(doneFilteredIndex + 1);

        for(var i = iLast + 1; i < pts.length; i++) {
            if(i === pts.length - 1 || isBent(pts, iLast, i + 1, tolerance)) {
                ptsFiltered.push(pts[i]);
                if(ptsFiltered.length < prevFilterLen - 2) {
                    doneRawIndex = i;
                    doneFilteredIndex = ptsFiltered.length - 1;
                }
                iLast = i;
            }
        }
    }

    if(pts.length > 1) {
        var lastPt = pts.pop();
        addPt(lastPt);
    }

    return {
        addPt: addPt,
        raw: pts,
        filtered: ptsFiltered
    };
};

},{"../constants/numerical":674,"./matrix":703}],710:[function(_dereq_,module,exports){
(function (global){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var showNoWebGlMsg = _dereq_('./show_no_webgl_msg');

// Note that this module should be ONLY required into
// files corresponding to regl trace modules
// so that bundles with non-regl only don't include
// regl and all its bytes.
var createRegl = _dereq_('regl');

/**
 * Idempotent version of createRegl. Create regl instances
 * in the correct canvases with the correct attributes and
 * options
 *
 * @param {DOM node or object} gd : graph div object
 * @param {array} extensions : list of extension to pass to createRegl
 *
 * @return {boolean} true if all createRegl calls succeeded, false otherwise
 */
module.exports = function prepareRegl(gd, extensions) {
    var fullLayout = gd._fullLayout;
    var success = true;

    fullLayout._glcanvas.each(function(d) {
        if(d.regl) return;
        // only parcoords needs pick layer
        if(d.pick && !fullLayout._has('parcoords')) return;

        try {
            d.regl = createRegl({
                canvas: this,
                attributes: {
                    antialias: !d.pick,
                    preserveDrawingBuffer: true
                },
                pixelRatio: gd._context.plotGlPixelRatio || global.devicePixelRatio,
                extensions: extensions || []
            });
        } catch(e) {
            success = false;
        }

        if(success) {
            this.addEventListener('webglcontextlost', function(event) {
                if(gd && gd.emit) {
                    gd.emit('plotly_webglcontextlost', {
                        event: event,
                        layer: d.key
                    });
                }
            }, false);
        }
    });

    if(!success) {
        showNoWebGlMsg({container: fullLayout._glcontainer.node()});
    }
    return success;
};

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./show_no_webgl_msg":718,"regl":483}],711:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * Push array with unique items
 *
 * Ignores falsy items, except 0 so we can use it to construct arrays of indices.
 *
 * @param {array} array
 *  array to be filled
 * @param {any} item
 *  item to be or not to be inserted
 * @return {array}
 *  ref to array (now possibly containing one more item)
 *
 */
module.exports = function pushUnique(array, item) {
    if(item instanceof RegExp) {
        var itemStr = item.toString();
        for(var i = 0; i < array.length; i++) {
            if(array[i] instanceof RegExp && array[i].toString() === itemStr) {
                return array;
            }
        }
        array.push(item);
    }
    else if((item || item === 0) && array.indexOf(item) === -1) array.push(item);

    return array;
};

},{}],712:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../lib');
var dfltConfig = _dereq_('../plot_api/plot_config').dfltConfig;

/**
 * Copy arg array *without* removing `undefined` values from objects.
 *
 * @param gd
 * @param args
 * @returns {Array}
 */
function copyArgArray(gd, args) {
    var copy = [];
    var arg;

    for(var i = 0; i < args.length; i++) {
        arg = args[i];

        if(arg === gd) copy[i] = arg;
        else if(typeof arg === 'object') {
            copy[i] = Array.isArray(arg) ?
                Lib.extendDeep([], arg) :
                Lib.extendDeepAll({}, arg);
        }
        else copy[i] = arg;
    }

    return copy;
}


// -----------------------------------------------------
// Undo/Redo queue for plots
// -----------------------------------------------------


var queue = {};

// TODO: disable/enable undo and redo buttons appropriately

/**
 * Add an item to the undoQueue for a graphDiv
 *
 * @param gd
 * @param undoFunc Function undo this operation
 * @param undoArgs Args to supply undoFunc with
 * @param redoFunc Function to redo this operation
 * @param redoArgs Args to supply redoFunc with
 */
queue.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) {
    var queueObj,
        queueIndex;

    // make sure we have the queue and our position in it
    gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false};
    queueIndex = gd.undoQueue.index;

    // if we're already playing an undo or redo, or if this is an auto operation
    // (like pane resize... any others?) then we don't save this to the undo queue
    if(gd.autoplay) {
        if(!gd.undoQueue.inSequence) gd.autoplay = false;
        return;
    }

    // if we're not in a sequence or are just starting, we need a new queue item
    if(!gd.undoQueue.sequence || gd.undoQueue.beginSequence) {
        queueObj = {undo: {calls: [], args: []}, redo: {calls: [], args: []}};
        gd.undoQueue.queue.splice(queueIndex, gd.undoQueue.queue.length - queueIndex, queueObj);
        gd.undoQueue.index += 1;
    } else {
        queueObj = gd.undoQueue.queue[queueIndex - 1];
    }
    gd.undoQueue.beginSequence = false;

    // we unshift to handle calls for undo in a forward for loop later
    if(queueObj) {
        queueObj.undo.calls.unshift(undoFunc);
        queueObj.undo.args.unshift(undoArgs);
        queueObj.redo.calls.push(redoFunc);
        queueObj.redo.args.push(redoArgs);
    }

    if(gd.undoQueue.queue.length > dfltConfig.queueLength) {
        gd.undoQueue.queue.shift();
        gd.undoQueue.index--;
    }
};

/**
 * Begin a sequence of undoQueue changes
 *
 * @param gd
 */
queue.startSequence = function(gd) {
    gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false};
    gd.undoQueue.sequence = true;
    gd.undoQueue.beginSequence = true;
};

/**
 * Stop a sequence of undoQueue changes
 *
 * Call this *after* you're sure your undo chain has ended
 *
 * @param gd
 */
queue.stopSequence = function(gd) {
    gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false};
    gd.undoQueue.sequence = false;
    gd.undoQueue.beginSequence = false;
};

/**
 * Move one step back in the undo queue, and undo the object there.
 *
 * @param gd
 */
queue.undo = function undo(gd) {
    var queueObj, i;

    if(gd.framework && gd.framework.isPolar) {
        gd.framework.undo();
        return;
    }
    if(gd.undoQueue === undefined ||
            isNaN(gd.undoQueue.index) ||
            gd.undoQueue.index <= 0) {
        return;
    }

    // index is pointing to next *forward* queueObj, point to the one we're undoing
    gd.undoQueue.index--;

    // get the queueObj for instructions on how to undo
    queueObj = gd.undoQueue.queue[gd.undoQueue.index];

    // this sequence keeps things from adding to the queue during undo/redo
    gd.undoQueue.inSequence = true;
    for(i = 0; i < queueObj.undo.calls.length; i++) {
        queue.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]);
    }
    gd.undoQueue.inSequence = false;
    gd.autoplay = false;
};

/**
 * Redo the current object in the undo, then move forward in the queue.
 *
 * @param gd
 */
queue.redo = function redo(gd) {
    var queueObj, i;

    if(gd.framework && gd.framework.isPolar) {
        gd.framework.redo();
        return;
    }
    if(gd.undoQueue === undefined ||
            isNaN(gd.undoQueue.index) ||
            gd.undoQueue.index >= gd.undoQueue.queue.length) {
        return;
    }

    // get the queueObj for instructions on how to undo
    queueObj = gd.undoQueue.queue[gd.undoQueue.index];

    // this sequence keeps things from adding to the queue during undo/redo
    gd.undoQueue.inSequence = true;
    for(i = 0; i < queueObj.redo.calls.length; i++) {
        queue.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]);
    }
    gd.undoQueue.inSequence = false;
    gd.autoplay = false;

    // index is pointing to the thing we just redid, move it
    gd.undoQueue.index++;
};

/**
 * Called by undo/redo to make the actual changes.
 *
 * Not meant to be called publically, but included for mocking out in tests.
 *
 * @param gd
 * @param func
 * @param args
 */
queue.plotDo = function(gd, func, args) {
    gd.autoplay = true;

    // this *won't* copy gd and it preserves `undefined` properties!
    args = copyArgArray(gd, args);

    // call the supplied function
    func.apply(null, args);
};

module.exports = queue;

},{"../lib":697,"../plot_api/plot_config":733}],713:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/*
 * make a regex for matching counter ids/names ie xaxis, xaxis2, xaxis10...
 *
 * @param {string} head: the head of the pattern, eg 'x' matches 'x', 'x2', 'x10' etc.
 *      'xy' is a special case for cartesian subplots: it matches 'x2y3' etc
 * @param {Optional(string)} tail: a fixed piece after the id
 *      eg counterRegex('scene', '.annotations') for scene2.annotations etc.
 * @param {boolean} openEnded: if true, the string may continue past the match.
 * @param {boolean} matchBeginning: if false, the string may start before the match.
 */
exports.counter = function(head, tail, openEnded, matchBeginning) {
    var fullTail = (tail || '') + (openEnded ? '' : '$');
    var startWithPrefix = matchBeginning === false ? '' : '^';
    if(head === 'xy') {
        return new RegExp(startWithPrefix + 'x([2-9]|[1-9][0-9]+)?y([2-9]|[1-9][0-9]+)?' + fullTail);
    }
    return new RegExp(startWithPrefix + head + '([2-9]|[1-9][0-9]+)?' + fullTail);
};

},{}],714:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

// ASCEND: chop off the last nesting level - either [<n>] or .<key> - to ascend
// the attribute tree. the remaining attrString is in match[1]
var ASCEND = /^(.*)(\.[^\.\[\]]+|\[\d\])$/;

// SIMPLEATTR: is this an un-nested attribute? (no dots or brackets)
var SIMPLEATTR = /^[^\.\[\]]+$/;

/*
 * calculate a relative attribute string, similar to a relative path
 *
 * @param {string} baseAttr:
 *   an attribute string, such as 'annotations[3].x'. The "current location"
 *   is the attribute string minus the last component ('annotations[3]')
 * @param {string} relativeAttr:
 *   a route to the desired attribute string, using '^' to ascend
 *
 * @return {string} attrString:
 *   for example:
 *     relativeAttr('annotations[3].x', 'y') = 'annotations[3].y'
 *     relativeAttr('annotations[3].x', '^[2].z') = 'annotations[2].z'
 *     relativeAttr('annotations[3].x', '^^margin') = 'margin'
 *     relativeAttr('annotations[3].x', '^^margin.r') = 'margin.r'
 */
module.exports = function(baseAttr, relativeAttr) {
    while(relativeAttr) {
        var match = baseAttr.match(ASCEND);

        if(match) baseAttr = match[1];
        else if(baseAttr.match(SIMPLEATTR)) baseAttr = '';
        else throw new Error('bad relativeAttr call:' + [baseAttr, relativeAttr]);

        if(relativeAttr.charAt(0) === '^') relativeAttr = relativeAttr.slice(1);
        else break;
    }

    if(baseAttr && relativeAttr.charAt(0) !== '[') {
        return baseAttr + '.' + relativeAttr;
    }
    return baseAttr + relativeAttr;
};

},{}],715:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isArrayOrTypedArray = _dereq_('./array').isArrayOrTypedArray;
var isPlainObject = _dereq_('./is_plain_object');

/**
 * Relink private _keys and keys with a function value from one container
 * to the new container.
 * Relink means copying if object is pass-by-value and adding a reference
 * if object is pass-by-ref.
 * This prevents deepCopying massive structures like a webgl context.
 */
module.exports = function relinkPrivateKeys(toContainer, fromContainer) {
    for(var k in fromContainer) {
        var fromVal = fromContainer[k];
        var toVal = toContainer[k];

        if(toVal === fromVal) {
            continue;
        }
        if(k.charAt(0) === '_' || typeof fromVal === 'function') {

            // if it already exists at this point, it's something
            // that we recreate each time around, so ignore it
            if(k in toContainer) continue;

            toContainer[k] = fromVal;
        }
        else if(isArrayOrTypedArray(fromVal) && isArrayOrTypedArray(toVal) && isPlainObject(fromVal[0])) {

            // filter out data_array items that can contain user objects
            // most of the time the toVal === fromVal check will catch these early
            // but if the user makes new ones we also don't want to recurse in.
            if(k === 'customdata' || k === 'ids') continue;

            // recurse into arrays containers
            var minLen = Math.min(fromVal.length, toVal.length);
            for(var j = 0; j < minLen; j++) {
                if((toVal[j] !== fromVal[j]) && isPlainObject(fromVal[j]) && isPlainObject(toVal[j])) {
                    relinkPrivateKeys(toVal[j], fromVal[j]);
                }
            }
        }
        else if(isPlainObject(fromVal) && isPlainObject(toVal)) {

            // recurse into objects, but only if they still exist
            relinkPrivateKeys(toVal, fromVal);

            if(!Object.keys(toVal).length) delete toContainer[k];
        }
    }
};

},{"./array":680,"./is_plain_object":698}],716:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var loggers = _dereq_('./loggers');
var identity = _dereq_('./identity');

// don't trust floating point equality - fraction of bin size to call
// "on the line" and ensure that they go the right way specified by
// linelow
var roundingError = 1e-9;


/**
 * findBin - find the bin for val - note that it can return outside the
 * bin range any pos. or neg. integer for linear bins, or -1 or
 * bins.length-1 for explicit.
 * bins is either an object {start,size,end} or an array length #bins+1
 * bins can be either increasing or decreasing but must be monotonic
 * for linear bins, we can just calculate. For listed bins, run a binary
 * search linelow (truthy) says the bin boundary should be attributed to
 * the lower bin rather than the default upper bin
 */
exports.findBin = function(val, bins, linelow) {
    if(isNumeric(bins.start)) {
        return linelow ?
            Math.ceil((val - bins.start) / bins.size - roundingError) - 1 :
            Math.floor((val - bins.start) / bins.size + roundingError);
    }
    else {
        var n1 = 0;
        var n2 = bins.length;
        var c = 0;
        var binSize = (n2 > 1) ? (bins[n2 - 1] - bins[0]) / (n2 - 1) : 1;
        var n, test;
        if(binSize >= 0) {
            test = linelow ? lessThan : lessOrEqual;
        } else {
            test = linelow ? greaterOrEqual : greaterThan;
        }
        val += binSize * roundingError * (linelow ? -1 : 1) * (binSize >= 0 ? 1 : -1);
        // c is just to avoid infinite loops if there's an error
        while(n1 < n2 && c++ < 100) {
            n = Math.floor((n1 + n2) / 2);
            if(test(bins[n], val)) n1 = n + 1;
            else n2 = n;
        }
        if(c > 90) loggers.log('Long binary search...');
        return n1 - 1;
    }
};

function lessThan(a, b) { return a < b; }
function lessOrEqual(a, b) { return a <= b; }
function greaterThan(a, b) { return a > b; }
function greaterOrEqual(a, b) { return a >= b; }

exports.sorterAsc = function(a, b) { return a - b; };
exports.sorterDes = function(a, b) { return b - a; };

/**
 * find distinct values in an array, lumping together ones that appear to
 * just be off by a rounding error
 * return the distinct values and the minimum difference between any two
 */
exports.distinctVals = function(valsIn) {
    var vals = valsIn.slice();  // otherwise we sort the original array...
    vals.sort(exports.sorterAsc);

    var l = vals.length - 1;
    var minDiff = (vals[l] - vals[0]) || 1;
    var errDiff = minDiff / (l || 1) / 10000;
    var v2 = [vals[0]];

    for(var i = 0; i < l; i++) {
        // make sure values aren't just off by a rounding error
        if(vals[i + 1] > vals[i] + errDiff) {
            minDiff = Math.min(minDiff, vals[i + 1] - vals[i]);
            v2.push(vals[i + 1]);
        }
    }

    return {vals: v2, minDiff: minDiff};
};

/**
 * return the smallest element from (sorted) array arrayIn that's bigger than val,
 * or (reverse) the largest element smaller than val
 * used to find the best tick given the minimum (non-rounded) tick
 * particularly useful for date/time where things are not powers of 10
 * binary search is probably overkill here...
 */
exports.roundUp = function(val, arrayIn, reverse) {
    var low = 0;
    var high = arrayIn.length - 1;
    var mid;
    var c = 0;
    var dlow = reverse ? 0 : 1;
    var dhigh = reverse ? 1 : 0;
    var rounded = reverse ? Math.ceil : Math.floor;
    // c is just to avoid infinite loops if there's an error
    while(low < high && c++ < 100) {
        mid = rounded((low + high) / 2);
        if(arrayIn[mid] <= val) low = mid + dlow;
        else high = mid - dhigh;
    }
    return arrayIn[low];
};

/**
 * Tweak to Array.sort(sortFn) that improves performance for pre-sorted arrays
 *
 * Note that newer browsers (such as Chrome v70+) are starting to pick up
 * on pre-sorted arrays which may render the following optimization unnecessary
 * in the future.
 *
 * Motivation: sometimes we need to sort arrays but the input is likely to
 * already be sorted. Browsers don't seem to pick up on pre-sorted arrays,
 * and in fact Chrome is actually *slower* sorting pre-sorted arrays than purely
 * random arrays. FF is at least faster if the array is pre-sorted, but still
 * not as fast as it could be.
 * Here's how this plays out sorting a length-1e6 array:
 *
 * Calls to Sort FN  |  Chrome bare  |  FF bare  |  Chrome tweak  |  FF tweak
 *                   |  v68.0 Mac    |  v61.0 Mac|                |
 * ------------------+---------------+-----------+----------------+------------
 * ordered           |  30.4e6       |  10.1e6   |  1e6           |  1e6
 * reversed          |  29.4e6       |  9.9e6    |  1e6 + reverse |  1e6 + reverse
 * random            |  ~21e6        |  ~18.7e6  |  ~21e6         |  ~18.7e6
 *
 * So this is a substantial win for pre-sorted (ordered or exactly reversed)
 * arrays. Including this wrapper on an unsorted array adds a penalty that will
 * in general be only a few calls to the sort function. The only case this
 * penalty will be significant is if the array is mostly sorted but there are
 * a few unsorted items near the end, but the penalty is still at most N calls
 * out of (for N=1e6) ~20N total calls
 *
 * @param {Array} array: the array, to be sorted in place
 * @param {function} sortFn: As in Array.sort, function(a, b) that puts
 *     item a before item b if the return is negative, a after b if positive,
 *     and no change if zero.
 * @return {Array}: the original array, sorted in place.
 */
exports.sort = function(array, sortFn) {
    var notOrdered = 0;
    var notReversed = 0;
    for(var i = 1; i < array.length; i++) {
        var pairOrder = sortFn(array[i], array[i - 1]);
        if(pairOrder < 0) notOrdered = 1;
        else if(pairOrder > 0) notReversed = 1;
        if(notOrdered && notReversed) return array.sort(sortFn);
    }
    return notReversed ? array : array.reverse();
};

/**
 * find index in array 'arr' that minimizes 'fn'
 *
 * @param {array} arr : array where to search
 * @param {fn (optional)} fn : function to minimize,
 *   if not given, fn is the identity function
 * @return {integer}
 */
exports.findIndexOfMin = function(arr, fn) {
    fn = fn || identity;

    var min = Infinity;
    var ind;

    for(var i = 0; i < arr.length; i++) {
        var v = fn(arr[i]);
        if(v < min) {
            min = v;
            ind = i;
        }
    }
    return ind;
};

},{"./identity":696,"./loggers":701,"fast-isnumeric":218}],717:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

// works with our CSS cursor classes (see css/_cursor.scss)
// to apply cursors to d3 single-element selections.
// omit cursor to revert to the default.
module.exports = function setCursor(el3, csr) {
    (el3.attr('class') || '').split(' ').forEach(function(cls) {
        if(cls.indexOf('cursor-') === 0) el3.classed(cls, false);
    });

    if(csr) el3.classed('cursor-' + csr, true);
};

},{}],718:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Color = _dereq_('../components/color');

var noop = function() {};


/**
 * Prints a no webgl error message into the scene container
 * @param {scene instance} scene
 *
 * Expects 'scene' to have property 'container'
 *
 */
module.exports = function showNoWebGlMsg(scene) {
    for(var prop in scene) {
        if(typeof scene[prop] === 'function') scene[prop] = noop;
    }

    scene.destroy = function() {
        scene.container.parentNode.removeChild(scene.container);
    };

    var div = document.createElement('div');
    div.className = 'no-webgl';
    div.style.cursor = 'pointer';
    div.style.fontSize = '24px';
    div.style.color = Color.defaults[0];
    div.style.position = 'absolute';
    div.style.left = div.style.top = '0px';
    div.style.width = div.style.height = '100%';
    div.style['background-color'] = Color.lightLine;
    div.style['z-index'] = 30;

    var p = document.createElement('p');
    p.textContent = 'WebGL is not supported by your browser - visit https://get.webgl.org for more info';
    p.style.position = 'relative';
    p.style.top = '50%';
    p.style.left = '50%';
    p.style.height = '30%';
    p.style.width = '50%';
    p.style.margin = '-15% 0 0 -25%';

    div.appendChild(p);
    scene.container.appendChild(div);
    scene.container.style.background = '#FFFFFF';
    scene.container.onclick = function() {
        window.open('https://get.webgl.org');
    };

    // return before setting up camera and onrender methods
    return false;
};

},{"../components/color":574}],719:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var isArrayOrTypedArray = _dereq_('./array').isArrayOrTypedArray;

/**
 * aggNums() returns the result of an aggregate function applied to an array of
 * values, where non-numerical values have been tossed out.
 *
 * @param {function} f - aggregation function (e.g., Math.min)
 * @param {Number} v - initial value (continuing from previous calls)
 *      if there's no continuing value, use null for selector-type
 *      functions (max,min), or 0 for summations
 * @param {Array} a - array to aggregate (may be nested, we will recurse,
 *                    but all elements must have the same dimension)
 * @param {Number} len - maximum length of a to aggregate
 * @return {Number} - result of f applied to a starting from v
 */
exports.aggNums = function(f, v, a, len) {
    var i,
        b;
    if(!len || len > a.length) len = a.length;
    if(!isNumeric(v)) v = false;
    if(isArrayOrTypedArray(a[0])) {
        b = new Array(len);
        for(i = 0; i < len; i++) b[i] = exports.aggNums(f, v, a[i]);
        a = b;
    }

    for(i = 0; i < len; i++) {
        if(!isNumeric(v)) v = a[i];
        else if(isNumeric(a[i])) v = f(+v, +a[i]);
    }
    return v;
};

/**
 * mean & std dev functions using aggNums, so it handles non-numerics nicely
 * even need to use aggNums instead of .length, to toss out non-numerics
 */
exports.len = function(data) {
    return exports.aggNums(function(a) { return a + 1; }, 0, data);
};

exports.mean = function(data, len) {
    if(!len) len = exports.len(data);
    return exports.aggNums(function(a, b) { return a + b; }, 0, data) / len;
};

exports.midRange = function(numArr) {
    if(numArr === undefined || numArr.length === 0) return undefined;
    return (exports.aggNums(Math.max, null, numArr) + exports.aggNums(Math.min, null, numArr)) / 2;
};

exports.variance = function(data, len, mean) {
    if(!len) len = exports.len(data);
    if(!isNumeric(mean)) mean = exports.mean(data, len);

    return exports.aggNums(function(a, b) {
        return a + Math.pow(b - mean, 2);
    }, 0, data) / len;
};

exports.stdev = function(data, len, mean) {
    return Math.sqrt(exports.variance(data, len, mean));
};

/**
 * interp() computes a percentile (quantile) for a given distribution.
 * We interpolate the distribution (to compute quantiles, we follow method #10 here:
 * http://www.amstat.org/publications/jse/v14n3/langford.html).
 * Typically the index or rank (n * arr.length) may be non-integer.
 * For reference: ends are clipped to the extreme values in the array;
 * For box plots: index you get is half a point too high (see
 * http://en.wikipedia.org/wiki/Percentile#Nearest_rank) but note that this definition
 * indexes from 1 rather than 0, so we subtract 1/2 (instead of add).
 *
 * @param {Array} arr - This array contains the values that make up the distribution.
 * @param {Number} n - Between 0 and 1, n = p/100 is such that we compute the p^th percentile.
 * For example, the 50th percentile (or median) corresponds to n = 0.5
 * @return {Number} - percentile
 */
exports.interp = function(arr, n) {
    if(!isNumeric(n)) throw 'n should be a finite number';
    n = n * arr.length - 0.5;
    if(n < 0) return arr[0];
    if(n > arr.length - 1) return arr[arr.length - 1];
    var frac = n % 1;
    return frac * arr[Math.ceil(n)] + (1 - frac) * arr[Math.floor(n)];
};

},{"./array":680,"fast-isnumeric":218}],720:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var rgba = _dereq_('color-normalize');

function str2RgbaArray(color) {
    if(!color) return [0, 0, 0, 1];
    return rgba(color);
}

module.exports = str2RgbaArray;

},{"color-normalize":108}],721:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

/* global MathJax:false */

var d3 = _dereq_('d3');

var Lib = _dereq_('../lib');
var xmlnsNamespaces = _dereq_('../constants/xmlns_namespaces');
var LINE_SPACING = _dereq_('../constants/alignment').LINE_SPACING;

// text converter

function getSize(_selection, _dimension) {
    return _selection.node().getBoundingClientRect()[_dimension];
}

var FIND_TEX = /([^$]*)([$]+[^$]*[$]+)([^$]*)/;

exports.convertToTspans = function(_context, gd, _callback) {
    var str = _context.text();

    // Until we get tex integrated more fully (so it can be used along with non-tex)
    // allow some elements to prohibit it by attaching 'data-notex' to the original
    var tex = (!_context.attr('data-notex')) &&
        (typeof MathJax !== 'undefined') &&
        str.match(FIND_TEX);

    var parent = d3.select(_context.node().parentNode);
    if(parent.empty()) return;
    var svgClass = (_context.attr('class')) ? _context.attr('class').split(' ')[0] : 'text';
    svgClass += '-math';
    parent.selectAll('svg.' + svgClass).remove();
    parent.selectAll('g.' + svgClass + '-group').remove();
    _context.style('display', null)
        .attr({
            // some callers use data-unformatted *from the <text> element* in 'cancel'
            // so we need it here even if we're going to turn it into math
            // these two (plus style and text-anchor attributes) form the key we're
            // going to use for Drawing.bBox
            'data-unformatted': str,
            'data-math': 'N'
        });

    function showText() {
        if(!parent.empty()) {
            svgClass = _context.attr('class') + '-math';
            parent.select('svg.' + svgClass).remove();
        }
        _context.text('')
            .style('white-space', 'pre');

        var hasLink = buildSVGText(_context.node(), str);

        if(hasLink) {
            // at least in Chrome, pointer-events does not seem
            // to be honored in children of <text> elements
            // so if we have an anchor, we have to make the
            // whole element respond
            _context.style('pointer-events', 'all');
        }

        exports.positionText(_context);

        if(_callback) _callback.call(_context);
    }

    if(tex) {
        ((gd && gd._promises) || []).push(new Promise(function(resolve) {
            _context.style('display', 'none');
            var fontSize = parseInt(_context.node().style.fontSize, 10);
            var config = {fontSize: fontSize};

            texToSVG(tex[2], config, function(_svgEl, _glyphDefs, _svgBBox) {
                parent.selectAll('svg.' + svgClass).remove();
                parent.selectAll('g.' + svgClass + '-group').remove();

                var newSvg = _svgEl && _svgEl.select('svg');
                if(!newSvg || !newSvg.node()) {
                    showText();
                    resolve();
                    return;
                }

                var mathjaxGroup = parent.append('g')
                    .classed(svgClass + '-group', true)
                    .attr({
                        'pointer-events': 'none',
                        'data-unformatted': str,
                        'data-math': 'Y'
                    });

                mathjaxGroup.node().appendChild(newSvg.node());

                // stitch the glyph defs
                if(_glyphDefs && _glyphDefs.node()) {
                    newSvg.node().insertBefore(_glyphDefs.node().cloneNode(true),
                                               newSvg.node().firstChild);
                }

                newSvg.attr({
                    'class': svgClass,
                    height: _svgBBox.height,
                    preserveAspectRatio: 'xMinYMin meet'
                })
                .style({overflow: 'visible', 'pointer-events': 'none'});

                var fill = _context.node().style.fill || 'black';
                newSvg.select('g').attr({fill: fill, stroke: fill});

                var newSvgW = getSize(newSvg, 'width');
                var newSvgH = getSize(newSvg, 'height');
                var newX = +_context.attr('x') - newSvgW *
                    {start: 0, middle: 0.5, end: 1}[_context.attr('text-anchor') || 'start'];
                // font baseline is about 1/4 fontSize below centerline
                var textHeight = fontSize || getSize(_context, 'height');
                var dy = -textHeight / 4;

                if(svgClass[0] === 'y') {
                    mathjaxGroup.attr({
                        transform: 'rotate(' + [-90, +_context.attr('x'), +_context.attr('y')] +
                        ') translate(' + [-newSvgW / 2, dy - newSvgH / 2] + ')'
                    });
                    newSvg.attr({x: +_context.attr('x'), y: +_context.attr('y')});
                }
                else if(svgClass[0] === 'l') {
                    newSvg.attr({x: _context.attr('x'), y: dy - (newSvgH / 2)});
                }
                else if(svgClass[0] === 'a' && svgClass.indexOf('atitle') !== 0) {
                    newSvg.attr({x: 0, y: dy});
                }
                else {
                    newSvg.attr({x: newX, y: (+_context.attr('y') + dy - newSvgH / 2)});
                }

                if(_callback) _callback.call(_context, mathjaxGroup);
                resolve(mathjaxGroup);
            });
        }));
    }
    else showText();

    return _context;
};


// MathJax

var LT_MATCH = /(<|&lt;|&#60;)/g;
var GT_MATCH = /(>|&gt;|&#62;)/g;

function cleanEscapesForTex(s) {
    return s.replace(LT_MATCH, '\\lt ')
        .replace(GT_MATCH, '\\gt ');
}

function texToSVG(_texString, _config, _callback) {

    var originalRenderer,
        originalConfig,
        originalProcessSectionDelay,
        tmpDiv;

    MathJax.Hub.Queue(
    function() {
        originalConfig = Lib.extendDeepAll({}, MathJax.Hub.config);

        originalProcessSectionDelay = MathJax.Hub.processSectionDelay;
        if(MathJax.Hub.processSectionDelay !== undefined) {
            // MathJax 2.5+
            MathJax.Hub.processSectionDelay = 0;
        }

        return MathJax.Hub.Config({
            messageStyle: 'none',
            tex2jax: {
                inlineMath: [['$', '$'], ['\\(', '\\)']]
            },
            displayAlign: 'left',
        });
    },
    function() {
        // Get original renderer
        originalRenderer = MathJax.Hub.config.menuSettings.renderer;
        if(originalRenderer !== 'SVG') {
            return MathJax.Hub.setRenderer('SVG');
        }
    },
    function() {
        var randomID = 'math-output-' + Lib.randstr({}, 64);
        tmpDiv = d3.select('body').append('div')
            .attr({id: randomID})
            .style({visibility: 'hidden', position: 'absolute'})
            .style({'font-size': _config.fontSize + 'px'})
            .text(cleanEscapesForTex(_texString));

        return MathJax.Hub.Typeset(tmpDiv.node());
    },
    function() {
        var glyphDefs = d3.select('body').select('#MathJax_SVG_glyphs');

        if(tmpDiv.select('.MathJax_SVG').empty() || !tmpDiv.select('svg').node()) {
            Lib.log('There was an error in the tex syntax.', _texString);
            _callback();
        }
        else {
            var svgBBox = tmpDiv.select('svg').node().getBoundingClientRect();
            _callback(tmpDiv.select('.MathJax_SVG'), glyphDefs, svgBBox);
        }

        tmpDiv.remove();

        if(originalRenderer !== 'SVG') {
            return MathJax.Hub.setRenderer(originalRenderer);
        }
    },
    function() {
        if(originalProcessSectionDelay !== undefined) {
            MathJax.Hub.processSectionDelay = originalProcessSectionDelay;
        }
        return MathJax.Hub.Config(originalConfig);
    });
}

var TAG_STYLES = {
    // would like to use baseline-shift for sub/sup but FF doesn't support it
    // so we need to use dy along with the uber hacky shift-back-to
    // baseline below
    sup: 'font-size:70%',
    sub: 'font-size:70%',
    b: 'font-weight:bold',
    i: 'font-style:italic',
    a: 'cursor:pointer',
    span: '',
    em: 'font-style:italic;font-weight:bold'
};

// baseline shifts for sub and sup
var SHIFT_DY = {
    sub: '0.3em',
    sup: '-0.6em'
};
// reset baseline by adding a tspan (empty except for a zero-width space)
// with dy of -70% * SHIFT_DY (because font-size=70%)
var RESET_DY = {
    sub: '-0.21em',
    sup: '0.42em'
};
var ZERO_WIDTH_SPACE = '\u200b';

/*
 * Whitelist of protocols in user-supplied urls. Mostly we want to avoid javascript
 * and related attack vectors. The empty items are there for IE, that in various
 * versions treats relative paths as having different flavors of no protocol, while
 * other browsers have these explicitly inherit the protocol of the page they're in.
 */
var PROTOCOLS = ['http:', 'https:', 'mailto:', '', undefined, ':'];

var NEWLINES = /(\r\n?|\n)/g;

var SPLIT_TAGS = /(<[^<>]*>)/;

var ONE_TAG = /<(\/?)([^ >]*)(\s+(.*))?>/i;

var BR_TAG = /<br(\s+.*)?>/i;

/*
 * style and href: pull them out of either single or double quotes. Also
 * - target: (_blank|_self|_parent|_top|framename)
 *     note that you can't use target to get a popup but if you use popup,
 *     a `framename` will be passed along as the name of the popup window.
 *     per the spec, cannot contain whitespace.
 *     for backward compatibility we default to '_blank'
 * - popup: a custom one for us to enable popup (new window) links. String
 *     for window.open -> strWindowFeatures, like 'menubar=yes,width=500,height=550'
 *     note that at least in Chrome, you need to give at least one property
 *     in this string or the page will open in a new tab anyway. We follow this
 *     convention and will not make a popup if this string is empty.
 *     per the spec, cannot contain whitespace.
 *
 * Because we hack in other attributes with style (sub & sup), drop any trailing
 * semicolon in user-supplied styles so we can consistently append the tag-dependent style
 *
 * These are for tag attributes; Chrome anyway will convert entities in
 * attribute values, but not in attribute names
 * you can test this by for example:
 * > p = document.createElement('p')
 * > p.innerHTML = '<span styl&#x65;="font-color:r&#x65;d;">Hi</span>'
 * > p.innerHTML
 * <- '<span styl&#x65;="font-color:red;">Hi</span>'
 */
var STYLEMATCH = /(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i;
var HREFMATCH = /(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i;
var TARGETMATCH = /(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i;
var POPUPMATCH = /(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;

// dedicated matcher for these quoted regexes, that can return their results
// in two different places
function getQuotedMatch(_str, re) {
    if(!_str) return null;
    var match = _str.match(re);
    var result = match && (match[3] || match[4]);
    return result && convertEntities(result);
}

var COLORMATCH = /(^|;)\s*color:/;

/**
 * Strip string of tags
 *
 * @param {string} _str : input string
 * @param {object} opts :
 * - maxLen {number} max length of output string
 * - allowedTags {array} list of pseudo-html tags to NOT strip
 * @return {string}
 */
exports.plainText = function(_str, opts) {
    opts = opts || {};

    var len = (opts.len !== undefined && opts.len !== -1) ? opts.len : Infinity;
    var allowedTags = opts.allowedTags !== undefined ? opts.allowedTags : ['br'];

    var ellipsis = '...';
    var eLen = ellipsis.length;

    var oldParts = _str.split(SPLIT_TAGS);
    var newParts = [];
    var prevTag = '';
    var l = 0;

    for(var i = 0; i < oldParts.length; i++) {
        var p = oldParts[i];
        var match = p.match(ONE_TAG);
        var tagType = match && match[2].toLowerCase();

        if(tagType) {
            // N.B. tags do not count towards string length
            if(allowedTags.indexOf(tagType) !== -1) {
                newParts.push(p);
                prevTag = tagType;
            }
        } else {
            var pLen = p.length;

            if((l + pLen) < len) {
                newParts.push(p);
                l += pLen;
            } else if(l < len) {
                var pLen2 = len - l;

                if(prevTag && (prevTag !== 'br' || pLen2 <= eLen || pLen <= eLen)) {
                    newParts.pop();
                }

                if(len > eLen) {
                    newParts.push(p.substr(0, pLen2 - eLen) + ellipsis);
                } else {
                    newParts.push(p.substr(0, pLen2));
                }
                break;
            }

            prevTag = '';
        }
    }

    return newParts.join('');
};

/*
 * N.B. HTML entities are listed without the leading '&' and trailing ';'
 * https://www.freeformatter.com/html-entities.html
 *
 * FWIW if we wanted to support the full set, it has 2261 entries:
 * https://www.w3.org/TR/html5/entities.json
 * though I notice that some of these are duplicates and/or are missing ";"
 * eg: "&amp;", "&amp", "&AMP;", and "&AMP" all map to "&"
 * We no longer need to include numeric entities here, these are now handled
 * by String.fromCodePoint/fromCharCode
 *
 * Anyway the only ones that are really important to allow are the HTML special
 * chars <, >, and &, because these ones can trigger special processing if not
 * replaced by the corresponding entity.
 */
var entityToUnicode = {
    mu: 'μ',
    amp: '&',
    lt: '<',
    gt: '>',
    nbsp: ' ',
    times: '×',
    plusmn: '±',
    deg: '°'
};

// NOTE: in general entities can contain uppercase too (so [a-zA-Z]) but all the
// ones we support use only lowercase. If we ever change that, update the regex.
var ENTITY_MATCH = /&(#\d+|#x[\da-fA-F]+|[a-z]+);/g;
function convertEntities(_str) {
    return _str.replace(ENTITY_MATCH, function(fullMatch, innerMatch) {
        var outChar;
        if(innerMatch.charAt(0) === '#') {
            // cannot use String.fromCodePoint in IE
            outChar = fromCodePoint(
                innerMatch.charAt(1) === 'x' ?
                    parseInt(innerMatch.substr(2), 16) :
                    parseInt(innerMatch.substr(1), 10)
            );
        }
        else outChar = entityToUnicode[innerMatch];

        // as in regular HTML, if we didn't decode the entity just
        // leave the raw text in place.
        return outChar || fullMatch;
    });
}
exports.convertEntities = convertEntities;

function fromCodePoint(code) {
    // Don't allow overflow. In Chrome this turns into � but I feel like it's
    // more useful to just not convert it at all.
    if(code > 0x10FFFF) return;
    var stringFromCodePoint = String.fromCodePoint;
    if(stringFromCodePoint) return stringFromCodePoint(code);

    // IE doesn't have String.fromCodePoint
    // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint
    var stringFromCharCode = String.fromCharCode;
    if(code <= 0xFFFF) return stringFromCharCode(code);
    return stringFromCharCode(
        (code >> 10) + 0xD7C0,
        (code % 0x400) + 0xDC00
    );
}

/*
 * buildSVGText: convert our pseudo-html into SVG tspan elements, and attach these
 * to containerNode
 *
 * @param {svg text element} containerNode: the <text> node to insert this text into
 * @param {string} str: the pseudo-html string to convert to svg
 *
 * @returns {bool}: does the result contain any links? We need to handle the text element
 *   somewhat differently if it does, so just keep track of this when it happens.
 */
function buildSVGText(containerNode, str) {
    /*
     * Normalize behavior between IE and others wrt newlines and whitespace:pre
     * this combination makes IE barf https://github.com/plotly/plotly.js/issues/746
     * Chrome and FF display \n, \r, or \r\n as a space in this mode.
     * I feel like at some point we turned these into <br> but currently we don't so
     * I'm just going to cement what we do now in Chrome and FF
     */
    str = str.replace(NEWLINES, ' ');

    var hasLink = false;

    // as we're building the text, keep track of what elements we're nested inside
    // nodeStack will be an array of {node, type, style, href, target, popup}
    // where only type: 'a' gets the last 3 and node is only added when it's created
    var nodeStack = [];
    var currentNode;
    var currentLine = -1;

    function newLine() {
        currentLine++;

        var lineNode = document.createElementNS(xmlnsNamespaces.svg, 'tspan');
        d3.select(lineNode).attr({
            class: 'line',
            dy: (currentLine * LINE_SPACING) + 'em'
        });
        containerNode.appendChild(lineNode);

        currentNode = lineNode;

        var oldNodeStack = nodeStack;
        nodeStack = [{node: lineNode}];

        if(oldNodeStack.length > 1) {
            for(var i = 1; i < oldNodeStack.length; i++) {
                enterNode(oldNodeStack[i]);
            }
        }
    }

    function enterNode(nodeSpec) {
        var type = nodeSpec.type;
        var nodeAttrs = {};
        var nodeType;

        if(type === 'a') {
            nodeType = 'a';
            var target = nodeSpec.target;
            var href = nodeSpec.href;
            var popup = nodeSpec.popup;
            if(href) {
                nodeAttrs = {
                    'xlink:xlink:show': (target === '_blank' || target.charAt(0) !== '_') ? 'new' : 'replace',
                    target: target,
                    'xlink:xlink:href': href
                };
                if(popup) {
                    // security: href and target are not inserted as code but
                    // as attributes. popup is, but limited to /[A-Za-z0-9_=,]/
                    nodeAttrs.onclick = 'window.open(this.href.baseVal,this.target.baseVal,"' +
                        popup + '");return false;';
                }
            }
        }
        else nodeType = 'tspan';

        if(nodeSpec.style) nodeAttrs.style = nodeSpec.style;

        var newNode = document.createElementNS(xmlnsNamespaces.svg, nodeType);

        if(type === 'sup' || type === 'sub') {
            addTextNode(currentNode, ZERO_WIDTH_SPACE);
            currentNode.appendChild(newNode);

            var resetter = document.createElementNS(xmlnsNamespaces.svg, 'tspan');
            addTextNode(resetter, ZERO_WIDTH_SPACE);
            d3.select(resetter).attr('dy', RESET_DY[type]);
            nodeAttrs.dy = SHIFT_DY[type];

            currentNode.appendChild(newNode);
            currentNode.appendChild(resetter);
        }
        else {
            currentNode.appendChild(newNode);
        }

        d3.select(newNode).attr(nodeAttrs);

        currentNode = nodeSpec.node = newNode;
        nodeStack.push(nodeSpec);
    }

    function addTextNode(node, text) {
        node.appendChild(document.createTextNode(text));
    }

    function exitNode(type) {
        // A bare closing tag can't close the root node. If we encounter this it
        // means there's an extra closing tag that can just be ignored:
        if(nodeStack.length === 1) {
            Lib.log('Ignoring unexpected end tag </' + type + '>.', str);
            return;
        }

        var innerNode = nodeStack.pop();

        if(type !== innerNode.type) {
            Lib.log('Start tag <' + innerNode.type + '> doesnt match end tag <' +
                type + '>. Pretending it did match.', str);
        }
        currentNode = nodeStack[nodeStack.length - 1].node;
    }

    var hasLines = BR_TAG.test(str);

    if(hasLines) newLine();
    else {
        currentNode = containerNode;
        nodeStack = [{node: containerNode}];
    }

    var parts = str.split(SPLIT_TAGS);
    for(var i = 0; i < parts.length; i++) {
        var parti = parts[i];
        var match = parti.match(ONE_TAG);
        var tagType = match && match[2].toLowerCase();
        var tagStyle = TAG_STYLES[tagType];

        if(tagType === 'br') {
            newLine();
        }
        else if(tagStyle === undefined) {
            addTextNode(currentNode, convertEntities(parti));
        }
        else {
            // tag - open or close
            if(match[1]) {
                exitNode(tagType);
            }
            else {
                var extra = match[4];

                var nodeSpec = {type: tagType};

                // now add style, from both the tag name and any extra css
                // Most of the svg css that users will care about is just like html,
                // but font color is different (uses fill). Let our users ignore this.
                var css = getQuotedMatch(extra, STYLEMATCH);
                if(css) {
                    css = css.replace(COLORMATCH, '$1 fill:');
                    if(tagStyle) css += ';' + tagStyle;
                }
                else if(tagStyle) css = tagStyle;

                if(css) nodeSpec.style = css;

                if(tagType === 'a') {
                    hasLink = true;

                    var href = getQuotedMatch(extra, HREFMATCH);

                    if(href) {
                        // check safe protocols
                        var dummyAnchor = document.createElement('a');
                        dummyAnchor.href = href;
                        if(PROTOCOLS.indexOf(dummyAnchor.protocol) !== -1) {
                            // Decode href to allow both already encoded and not encoded
                            // URIs. Without decoding prior encoding, an already encoded
                            // URI would be encoded twice producing a semantically different URI.
                            nodeSpec.href = encodeURI(decodeURI(href));
                            nodeSpec.target = getQuotedMatch(extra, TARGETMATCH) || '_blank';
                            nodeSpec.popup = getQuotedMatch(extra, POPUPMATCH);
                        }
                    }
                }

                enterNode(nodeSpec);
            }
        }
    }

    return hasLink;
}

exports.lineCount = function lineCount(s) {
    return s.selectAll('tspan.line').size() || 1;
};

exports.positionText = function positionText(s, x, y) {
    return s.each(function() {
        var text = d3.select(this);

        function setOrGet(attr, val) {
            if(val === undefined) {
                val = text.attr(attr);
                if(val === null) {
                    text.attr(attr, 0);
                    val = 0;
                }
            }
            else text.attr(attr, val);
            return val;
        }

        var thisX = setOrGet('x', x);
        var thisY = setOrGet('y', y);

        if(this.nodeName === 'text') {
            text.selectAll('tspan.line').attr({x: thisX, y: thisY});
        }
    });
};

function alignHTMLWith(_base, container, options) {
    var alignH = options.horizontalAlign;
    var alignV = options.verticalAlign || 'top';
    var bRect = _base.node().getBoundingClientRect();
    var cRect = container.node().getBoundingClientRect();
    var thisRect;
    var getTop;
    var getLeft;

    if(alignV === 'bottom') {
        getTop = function() { return bRect.bottom - thisRect.height; };
    } else if(alignV === 'middle') {
        getTop = function() { return bRect.top + (bRect.height - thisRect.height) / 2; };
    } else { // default: top
        getTop = function() { return bRect.top; };
    }

    if(alignH === 'right') {
        getLeft = function() { return bRect.right - thisRect.width; };
    } else if(alignH === 'center') {
        getLeft = function() { return bRect.left + (bRect.width - thisRect.width) / 2; };
    } else { // default: left
        getLeft = function() { return bRect.left; };
    }

    return function() {
        thisRect = this.node().getBoundingClientRect();
        this.style({
            top: (getTop() - cRect.top) + 'px',
            left: (getLeft() - cRect.left) + 'px',
            'z-index': 1000
        });
        return this;
    };
}

/*
 * Editable title
 * @param {d3.selection} context: the element being edited. Normally text,
 *   but if it isn't, you should provide the styling options
 * @param {object} options:
 *   @param {div} options.gd: graphDiv
 *   @param {d3.selection} options.delegate: item to bind events to if not this
 *   @param {boolean} options.immediate: start editing now (true) or on click (false, default)
 *   @param {string} options.fill: font color if not as shown
 *   @param {string} options.background: background color if not as shown
 *   @param {string} options.text: initial text, if not as shown
 *   @param {string} options.horizontalAlign: alignment of the edit box wrt. the bound element
 *   @param {string} options.verticalAlign: alignment of the edit box wrt. the bound element
 */

exports.makeEditable = function(context, options) {
    var gd = options.gd;
    var _delegate = options.delegate;
    var dispatch = d3.dispatch('edit', 'input', 'cancel');
    var handlerElement = _delegate || context;

    context.style({'pointer-events': _delegate ? 'none' : 'all'});

    if(context.size() !== 1) throw new Error('boo');

    function handleClick() {
        appendEditable();
        context.style({opacity: 0});
        // also hide any mathjax svg
        var svgClass = handlerElement.attr('class');
        var mathjaxClass;
        if(svgClass) mathjaxClass = '.' + svgClass.split(' ')[0] + '-math-group';
        else mathjaxClass = '[class*=-math-group]';
        if(mathjaxClass) {
            d3.select(context.node().parentNode).select(mathjaxClass).style({opacity: 0});
        }
    }

    function selectElementContents(_el) {
        var el = _el.node();
        var range = document.createRange();
        range.selectNodeContents(el);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
        el.focus();
    }

    function appendEditable() {
        var plotDiv = d3.select(gd);
        var container = plotDiv.select('.svg-container');
        var div = container.append('div');
        var cStyle = context.node().style;
        var fontSize = parseFloat(cStyle.fontSize || 12);

        var initialText = options.text;
        if(initialText === undefined) initialText = context.attr('data-unformatted');

        div.classed('plugin-editable editable', true)
            .style({
                position: 'absolute',
                'font-family': cStyle.fontFamily || 'Arial',
                'font-size': fontSize,
                color: options.fill || cStyle.fill || 'black',
                opacity: 1,
                'background-color': options.background || 'transparent',
                outline: '#ffffff33 1px solid',
                margin: [-fontSize / 8 + 1, 0, 0, -1].join('px ') + 'px',
                padding: '0',
                'box-sizing': 'border-box'
            })
            .attr({contenteditable: true})
            .text(initialText)
            .call(alignHTMLWith(context, container, options))
            .on('blur', function() {
                gd._editing = false;
                context.text(this.textContent)
                    .style({opacity: 1});
                var svgClass = d3.select(this).attr('class');
                var mathjaxClass;
                if(svgClass) mathjaxClass = '.' + svgClass.split(' ')[0] + '-math-group';
                else mathjaxClass = '[class*=-math-group]';
                if(mathjaxClass) {
                    d3.select(context.node().parentNode).select(mathjaxClass).style({opacity: 0});
                }
                var text = this.textContent;
                d3.select(this).transition().duration(0).remove();
                d3.select(document).on('mouseup', null);
                dispatch.edit.call(context, text);
            })
            .on('focus', function() {
                var editDiv = this;
                gd._editing = true;
                d3.select(document).on('mouseup', function() {
                    if(d3.event.target === editDiv) return false;
                    if(document.activeElement === div.node()) div.node().blur();
                });
            })
            .on('keyup', function() {
                if(d3.event.which === 27) {
                    gd._editing = false;
                    context.style({opacity: 1});
                    d3.select(this)
                        .style({opacity: 0})
                        .on('blur', function() { return false; })
                        .transition().remove();
                    dispatch.cancel.call(context, this.textContent);
                }
                else {
                    dispatch.input.call(context, this.textContent);
                    d3.select(this).call(alignHTMLWith(context, container, options));
                }
            })
            .on('keydown', function() {
                if(d3.event.which === 13) this.blur();
            })
            .call(selectElementContents);
    }

    if(options.immediate) handleClick();
    else handlerElement.on('click', handleClick);

    return d3.rebind(context, dispatch, 'on');
};

},{"../constants/alignment":669,"../constants/xmlns_namespaces":675,"../lib":697,"d3":151}],722:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var timerCache = {};

/**
 * Throttle a callback. `callback` executes synchronously only if
 * more than `minInterval` milliseconds have already elapsed since the latest
 * call (if any). Otherwise we wait until `minInterval` is over and execute the
 * last callback received while waiting.
 * So the first and last events in a train are always executed (eventually)
 * but some of the events in the middle can be dropped.
 *
 * @param {string} id: an identifier to mark events to throttle together
 * @param {number} minInterval: minimum time, in milliseconds, between
 *   invocations of `callback`
 * @param {function} callback: the function to throttle. `callback` itself
 *   should be a purely synchronous function.
 */
exports.throttle = function throttle(id, minInterval, callback) {
    var cache = timerCache[id];
    var now = Date.now();

    if(!cache) {
        /*
         * Throw out old items before making a new one, to prevent the cache
         * getting overgrown, for example from old plots that have been replaced.
         * 1 minute age is arbitrary.
         */
        for(var idi in timerCache) {
            if(timerCache[idi].ts < now - 60000) {
                delete timerCache[idi];
            }
        }
        cache = timerCache[id] = {ts: 0, timer: null};
    }

    _clearTimeout(cache);

    function exec() {
        callback();
        cache.ts = Date.now();
        if(cache.onDone) {
            cache.onDone();
            cache.onDone = null;
        }
    }

    if(now > cache.ts + minInterval) {
        exec();
        return;
    }

    cache.timer = setTimeout(function() {
        exec();
        cache.timer = null;
    }, minInterval);
};

exports.done = function(id) {
    var cache = timerCache[id];
    if(!cache || !cache.timer) return Promise.resolve();

    return new Promise(function(resolve) {
        var previousOnDone = cache.onDone;
        cache.onDone = function onDone() {
            if(previousOnDone) previousOnDone();
            resolve();
            cache.onDone = null;
        };
    });
};

/**
 * Clear the throttle cache for one or all timers
 * @param {optional string} id:
 *   if provided, clear just this timer
 *   if omitted, clear all timers (mainly useful for testing)
 */
exports.clear = function(id) {
    if(id) {
        _clearTimeout(timerCache[id]);
        delete timerCache[id];
    }
    else {
        for(var idi in timerCache) exports.clear(idi);
    }
};

function _clearTimeout(cache) {
    if(cache && cache.timer !== null) {
        clearTimeout(cache.timer);
        cache.timer = null;
    }
}

},{}],723:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');

/**
 * convert a linear value into a logged value, folding negative numbers into
 * the given range
 */
module.exports = function toLogRange(val, range) {
    if(val > 0) return Math.log(val) / Math.LN10;

    // move a negative value reference to a log axis - just put the
    // result at the lowest range value on the plot (or if the range also went negative,
    // one millionth of the top of the range)
    var newVal = Math.log(Math.min(range[0], range[1])) / Math.LN10;
    if(!isNumeric(newVal)) newVal = Math.log(Math.max(range[0], range[1])) / Math.LN10 - 6;
    return newVal;
};

},{"fast-isnumeric":218}],724:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var topojsonUtils = module.exports = {};

var locationmodeToLayer = _dereq_('../plots/geo/constants').locationmodeToLayer;
var topojsonFeature = _dereq_('topojson-client').feature;

topojsonUtils.getTopojsonName = function(geoLayout) {
    return [
        geoLayout.scope.replace(/ /g, '-'), '_',
        geoLayout.resolution.toString(), 'm'
    ].join('');
};

topojsonUtils.getTopojsonPath = function(topojsonURL, topojsonName) {
    return topojsonURL + topojsonName + '.json';
};

topojsonUtils.getTopojsonFeatures = function(trace, topojson) {
    var layer = locationmodeToLayer[trace.locationmode];
    var obj = topojson.objects[layer];

    return topojsonFeature(topojson, obj).features;
};

},{"../plots/geo/constants":773,"topojson-client":521}],725:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'locale',
    name: 'en-US',
    dictionary: {
        'Click to enter Colorscale title': 'Click to enter Colorscale title'
    },
    format: {
        date: '%m/%d/%Y'
    }
};

},{}],726:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'locale',
    name: 'en',
    dictionary: {
        'Click to enter Colorscale title': 'Click to enter Colourscale title'
    },
    format: {
        days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
        shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
        months: [
            'January', 'February', 'March', 'April', 'May', 'June',
            'July', 'August', 'September', 'October', 'November', 'December'
        ],
        shortMonths: [
            'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
        ],
        periods: ['AM', 'PM'],
        dateTime: '%a %b %e %X %Y',
        date: '%d/%m/%Y',
        time: '%H:%M:%S',
        decimal: '.',
        thousands: ',',
        grouping: [3],
        currency: ['$', ''],
        year: '%Y',
        month: '%b %Y',
        dayMonth: '%b %-d',
        dayMonthYear: '%b %-d, %Y'
    }
};

},{}],727:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../registry');

/*
 * containerArrayMatch: does this attribute string point into a
 * layout container array?
 *
 * @param {String} astr: an attribute string, like *annotations[2].text*
 *
 * @returns {Object | false} Returns false if `astr` doesn't match a container
 *  array. If it does, returns:
 *     {array: {String}, index: {Number}, property: {String}}
 *  ie the attribute string for the array, the index within the array (or ''
 *  if the whole array) and the property within that (or '' if the whole array
 *  or the whole object)
 */
module.exports = function containerArrayMatch(astr) {
    var rootContainers = Registry.layoutArrayContainers;
    var regexpContainers = Registry.layoutArrayRegexes;
    var rootPart = astr.split('[')[0];
    var arrayStr;
    var match;

    // look for regexp matches first, because they may be nested inside root matches
    // eg updatemenus[i].buttons is nested inside updatemenus
    for(var i = 0; i < regexpContainers.length; i++) {
        match = astr.match(regexpContainers[i]);
        if(match && match.index === 0) {
            arrayStr = match[0];
            break;
        }
    }

    // now look for root matches
    if(!arrayStr) arrayStr = rootContainers[rootContainers.indexOf(rootPart)];

    if(!arrayStr) return false;

    var tail = astr.substr(arrayStr.length);
    if(!tail) return {array: arrayStr, index: '', property: ''};

    match = tail.match(/^\[(0|[1-9][0-9]*)\](\.(.+))?$/);
    if(!match) return false;

    return {array: arrayStr, index: Number(match[1]), property: match[3] || ''};
};

},{"../registry":826}],728:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../lib');
var extendFlat = Lib.extendFlat;
var isPlainObject = Lib.isPlainObject;

var traceOpts = {
    valType: 'flaglist',
    extras: ['none'],
    flags: ['calc', 'clearAxisTypes', 'plot', 'style', 'markerSize', 'colorbars'],
    
};

var layoutOpts = {
    valType: 'flaglist',
    extras: ['none'],
    flags: [
        'calc', 'plot', 'legend', 'ticks', 'axrange',
        'layoutstyle', 'modebar', 'camera', 'arraydraw'
    ],
    
};

// flags for inside restyle/relayout include a few extras
// that shouldn't be used in attributes, to deal with certain
// combinations and conditionals efficiently
var traceEditTypeFlags = traceOpts.flags.slice()
    .concat(['fullReplot']);

var layoutEditTypeFlags = layoutOpts.flags.slice()
    .concat('layoutReplot');

module.exports = {
    traces: traceOpts,
    layout: layoutOpts,
    /*
     * default (all false) edit flags for restyle (traces)
     * creates a new object each call, so the caller can mutate freely
     */
    traceFlags: function() { return falseObj(traceEditTypeFlags); },

    /*
     * default (all false) edit flags for relayout
     * creates a new object each call, so the caller can mutate freely
     */
    layoutFlags: function() { return falseObj(layoutEditTypeFlags); },

    /*
     * update `flags` with the `editType` values found in `attr`
     */
    update: function(flags, attr) {
        var editType = attr.editType;
        if(editType && editType !== 'none') {
            var editTypeParts = editType.split('+');
            for(var i = 0; i < editTypeParts.length; i++) {
                flags[editTypeParts[i]] = true;
            }
        }
    },

    overrideAll: overrideAll
};

function falseObj(keys) {
    var out = {};
    for(var i = 0; i < keys.length; i++) out[keys[i]] = false;
    return out;
}

/**
 * For attributes that are largely copied from elsewhere into a plot type that doesn't
 * support partial redraws - overrides the editType field of all attributes in the object
 *
 * @param {object} attrs: the attributes to override. Will not be mutated.
 * @param {string} editTypeOverride: the new editType to use
 * @param {'nested'|'from-root'} overrideContainers:
 *   - 'nested' will override editType for nested containers but not the root.
 *   - 'from-root' will also override editType of the root container.
 *   Containers below the absolute top level (trace or layout root) DO need an
 *   editType even if they are not `valObject`s themselves (eg `scatter.marker`)
 *   to handle the case where you edit the whole container.
 *
 * @return {object} a new attributes object with `editType` modified as directed
 */
function overrideAll(attrs, editTypeOverride, overrideContainers) {
    var out = extendFlat({}, attrs);
    for(var key in out) {
        var attr = out[key];
        if(isPlainObject(attr)) {
            out[key] = overrideOne(attr, editTypeOverride, overrideContainers, key);
        }
    }
    if(overrideContainers === 'from-root') out.editType = editTypeOverride;

    return out;
}

function overrideOne(attr, editTypeOverride, overrideContainers, key) {
    if(attr.valType) {
        var out = extendFlat({}, attr);
        out.editType = editTypeOverride;

        if(Array.isArray(attr.items)) {
            out.items = new Array(attr.items.length);
            for(var i = 0; i < attr.items.length; i++) {
                out.items[i] = overrideOne(attr.items[i], editTypeOverride, 'from-root');
            }
        }
        return out;
    }
    else {
        // don't provide an editType for the _deprecated container
        return overrideAll(attr, editTypeOverride,
            (key.charAt(0) === '_') ? 'nested' : 'from-root');
    }
}

},{"../lib":697}],729:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var m4FromQuat = _dereq_('gl-mat4/fromQuat');

var Registry = _dereq_('../registry');
var Lib = _dereq_('../lib');
var Plots = _dereq_('../plots/plots');
var AxisIds = _dereq_('../plots/cartesian/axis_ids');
var cleanId = AxisIds.cleanId;
var getFromTrace = AxisIds.getFromTrace;
var Color = _dereq_('../components/color');


// clear the promise queue if one of them got rejected
exports.clearPromiseQueue = function(gd) {
    if(Array.isArray(gd._promises) && gd._promises.length > 0) {
        Lib.log('Clearing previous rejected promises from queue.');
    }

    gd._promises = [];
};

// make a few changes to the layout right away
// before it gets used for anything
// backward compatibility and cleanup of nonstandard options
exports.cleanLayout = function(layout) {
    var i, j;

    if(!layout) layout = {};

    // cannot have (x|y)axis1, numbering goes axis, axis2, axis3...
    if(layout.xaxis1) {
        if(!layout.xaxis) layout.xaxis = layout.xaxis1;
        delete layout.xaxis1;
    }
    if(layout.yaxis1) {
        if(!layout.yaxis) layout.yaxis = layout.yaxis1;
        delete layout.yaxis1;
    }
    if(layout.scene1) {
        if(!layout.scene) layout.scene = layout.scene1;
        delete layout.scene1;
    }

    var axisAttrRegex = (Plots.subplotsRegistry.cartesian || {}).attrRegex;
    var polarAttrRegex = (Plots.subplotsRegistry.polar || {}).attrRegex;
    var ternaryAttrRegex = (Plots.subplotsRegistry.ternary || {}).attrRegex;
    var sceneAttrRegex = (Plots.subplotsRegistry.gl3d || {}).attrRegex;

    var keys = Object.keys(layout);
    for(i = 0; i < keys.length; i++) {
        var key = keys[i];

        // modifications to cartesian axes
        if(axisAttrRegex && axisAttrRegex.test(key)) {
            var ax = layout[key];
            if(ax.anchor && ax.anchor !== 'free') {
                ax.anchor = cleanId(ax.anchor);
            }
            if(ax.overlaying) ax.overlaying = cleanId(ax.overlaying);

            // old method of axis type - isdate and islog (before category existed)
            if(!ax.type) {
                if(ax.isdate) ax.type = 'date';
                else if(ax.islog) ax.type = 'log';
                else if(ax.isdate === false && ax.islog === false) ax.type = 'linear';
            }
            if(ax.autorange === 'withzero' || ax.autorange === 'tozero') {
                ax.autorange = true;
                ax.rangemode = 'tozero';
            }
            delete ax.islog;
            delete ax.isdate;
            delete ax.categories; // replaced by _categories

            // prune empty domain arrays made before the new nestedProperty
            if(emptyContainer(ax, 'domain')) delete ax.domain;

            // autotick -> tickmode
            if(ax.autotick !== undefined) {
                if(ax.tickmode === undefined) {
                    ax.tickmode = ax.autotick ? 'auto' : 'linear';
                }
                delete ax.autotick;
            }

            cleanTitle(ax);
        }

        // modifications for polar
        else if(polarAttrRegex && polarAttrRegex.test(key)) {
            var polar = layout[key];

            cleanTitle(polar.radialaxis);
        }

        // modifications for ternary
        else if(ternaryAttrRegex && ternaryAttrRegex.test(key)) {
            var ternary = layout[key];

            cleanTitle(ternary.aaxis);
            cleanTitle(ternary.baxis);
            cleanTitle(ternary.caxis);
        }

        // modifications for 3D scenes
        else if(sceneAttrRegex && sceneAttrRegex.test(key)) {
            var scene = layout[key];

            // clean old Camera coords
            var cameraposition = scene.cameraposition;

            if(Array.isArray(cameraposition) && cameraposition[0].length === 4) {
                var rotation = cameraposition[0];
                var center = cameraposition[1];
                var radius = cameraposition[2];
                var mat = m4FromQuat([], rotation);
                var eye = [];

                for(j = 0; j < 3; ++j) {
                    eye[j] = center[j] + radius * mat[2 + 4 * j];
                }

                scene.camera = {
                    eye: {x: eye[0], y: eye[1], z: eye[2]},
                    center: {x: center[0], y: center[1], z: center[2]},
                    up: {x: 0, y: 0, z: 1} // we just ignore calculating camera z up in this case
                };

                delete scene.cameraposition;
            }

            // clean axis titles
            cleanTitle(scene.xaxis);
            cleanTitle(scene.yaxis);
            cleanTitle(scene.zaxis);
        }
    }

    var annotationsLen = Array.isArray(layout.annotations) ? layout.annotations.length : 0;
    for(i = 0; i < annotationsLen; i++) {
        var ann = layout.annotations[i];

        if(!Lib.isPlainObject(ann)) continue;

        if(ann.ref) {
            if(ann.ref === 'paper') {
                ann.xref = 'paper';
                ann.yref = 'paper';
            }
            else if(ann.ref === 'data') {
                ann.xref = 'x';
                ann.yref = 'y';
            }
            delete ann.ref;
        }

        cleanAxRef(ann, 'xref');
        cleanAxRef(ann, 'yref');
    }

    var shapesLen = Array.isArray(layout.shapes) ? layout.shapes.length : 0;
    for(i = 0; i < shapesLen; i++) {
        var shape = layout.shapes[i];

        if(!Lib.isPlainObject(shape)) continue;

        cleanAxRef(shape, 'xref');
        cleanAxRef(shape, 'yref');
    }

    var legend = layout.legend;
    if(legend) {
        // check for old-style legend positioning (x or y is +/- 100)
        if(legend.x > 3) {
            legend.x = 1.02;
            legend.xanchor = 'left';
        }
        else if(legend.x < -2) {
            legend.x = -0.02;
            legend.xanchor = 'right';
        }

        if(legend.y > 3) {
            legend.y = 1.02;
            legend.yanchor = 'bottom';
        }
        else if(legend.y < -2) {
            legend.y = -0.02;
            legend.yanchor = 'top';
        }
    }

    // clean plot title
    cleanTitle(layout);

    /*
     * Moved from rotate -> orbit for dragmode
     */
    if(layout.dragmode === 'rotate') layout.dragmode = 'orbit';

    // sanitize rgb(fractions) and rgba(fractions) that old tinycolor
    // supported, but new tinycolor does not because they're not valid css
    Color.clean(layout);

    // clean the layout container in layout.template
    if(layout.template && layout.template.layout) {
        exports.cleanLayout(layout.template.layout);
    }

    return layout;
};

function cleanAxRef(container, attr) {
    var valIn = container[attr];
    var axLetter = attr.charAt(0);
    if(valIn && valIn !== 'paper') {
        container[attr] = cleanId(valIn, axLetter);
    }
}

/**
 * Cleans up old title attribute structure (flat) in favor of the new one (nested).
 *
 * @param {Object} titleContainer - an object potentially including deprecated title attributes
 */
function cleanTitle(titleContainer) {
    if(titleContainer) {

        // title -> title.text
        // (although title used to be a string attribute,
        // numbers are accepted as well)
        if(typeof titleContainer.title === 'string' || typeof titleContainer.title === 'number') {
            titleContainer.title = {
                text: titleContainer.title
            };
        }

        rewireAttr('titlefont', 'font');
        rewireAttr('titleposition', 'position');
        rewireAttr('titleside', 'side');
        rewireAttr('titleoffset', 'offset');
    }

    function rewireAttr(oldAttrName, newAttrName) {
        var oldAttrSet = titleContainer[oldAttrName];
        var newAttrSet = titleContainer.title && titleContainer.title[newAttrName];

        if(oldAttrSet && !newAttrSet) {

            // Ensure title object exists
            if(!titleContainer.title) {
                titleContainer.title = {};
            }

            titleContainer.title[newAttrName] = titleContainer[oldAttrName];
            delete titleContainer[oldAttrName];
        }
    }
}

/*
 * cleanData: Make a few changes to the data for backward compatibility
 * before it gets used for anything. Modifies the data traces users provide.
 *
 * Important: if you're going to add something here that modifies a data array,
 * update it in place so the new array === the old one.
 */
exports.cleanData = function(data) {
    for(var tracei = 0; tracei < data.length; tracei++) {
        var trace = data[tracei];
        var i;

        // use xbins to bin data in x, and ybins to bin data in y
        if(trace.type === 'histogramy' && 'xbins' in trace && !('ybins' in trace)) {
            trace.ybins = trace.xbins;
            delete trace.xbins;
        }

        // error_y.opacity is obsolete - merge into color
        if(trace.error_y && 'opacity' in trace.error_y) {
            var dc = Color.defaults;
            var yeColor = trace.error_y.color || (Registry.traceIs(trace, 'bar') ?
                Color.defaultLine :
                dc[tracei % dc.length]);
            trace.error_y.color = Color.addOpacity(
                Color.rgb(yeColor),
                Color.opacity(yeColor) * trace.error_y.opacity);
            delete trace.error_y.opacity;
        }

        // convert bardir to orientation, and put the data into
        // the axes it's eventually going to be used with
        if('bardir' in trace) {
            if(trace.bardir === 'h' && (Registry.traceIs(trace, 'bar') ||
                     trace.type.substr(0, 9) === 'histogram')) {
                trace.orientation = 'h';
                exports.swapXYData(trace);
            }
            delete trace.bardir;
        }

        // now we have only one 1D histogram type, and whether
        // it uses x or y data depends on trace.orientation
        if(trace.type === 'histogramy') exports.swapXYData(trace);
        if(trace.type === 'histogramx' || trace.type === 'histogramy') {
            trace.type = 'histogram';
        }

        // scl->scale, reversescl->reversescale
        if('scl' in trace && !('colorscale' in trace)) {
            trace.colorscale = trace.scl;
            delete trace.scl;
        }
        if('reversescl' in trace && !('reversescale' in trace)) {
            trace.reversescale = trace.reversescl;
            delete trace.reversescl;
        }

        // axis ids x1 -> x, y1-> y
        if(trace.xaxis) trace.xaxis = cleanId(trace.xaxis, 'x');
        if(trace.yaxis) trace.yaxis = cleanId(trace.yaxis, 'y');

        // scene ids scene1 -> scene
        if(Registry.traceIs(trace, 'gl3d') && trace.scene) {
            trace.scene = Plots.subplotsRegistry.gl3d.cleanId(trace.scene);
        }

        if(!Registry.traceIs(trace, 'pie') && !Registry.traceIs(trace, 'bar')) {
            if(Array.isArray(trace.textposition)) {
                for(i = 0; i < trace.textposition.length; i++) {
                    trace.textposition[i] = cleanTextPosition(trace.textposition[i]);
                }
            }
            else if(trace.textposition) {
                trace.textposition = cleanTextPosition(trace.textposition);
            }
        }

        // fix typo in colorscale definition
        var _module = Registry.getModule(trace);
        if(_module && _module.colorbar) {
            var containerName = _module.colorbar.container;
            var container = containerName ? trace[containerName] : trace;
            if(container && container.colorscale) {
                if(container.colorscale === 'YIGnBu') container.colorscale = 'YlGnBu';
                if(container.colorscale === 'YIOrRd') container.colorscale = 'YlOrRd';
            }
        }

        // fix typo in surface 'highlight*' definitions
        if(trace.type === 'surface' && Lib.isPlainObject(trace.contours)) {
            var dims = ['x', 'y', 'z'];

            for(i = 0; i < dims.length; i++) {
                var opts = trace.contours[dims[i]];

                if(!Lib.isPlainObject(opts)) continue;

                if(opts.highlightColor) {
                    opts.highlightcolor = opts.highlightColor;
                    delete opts.highlightColor;
                }

                if(opts.highlightWidth) {
                    opts.highlightwidth = opts.highlightWidth;
                    delete opts.highlightWidth;
                }
            }
        }

        // fixes from converting finance from transforms to real trace types
        if(trace.type === 'candlestick' || trace.type === 'ohlc') {
            var increasingShowlegend = (trace.increasing || {}).showlegend !== false;
            var decreasingShowlegend = (trace.decreasing || {}).showlegend !== false;
            var increasingName = cleanFinanceDir(trace.increasing);
            var decreasingName = cleanFinanceDir(trace.decreasing);

            // now figure out something smart to do with the separate direction
            // names we removed
            if((increasingName !== false) && (decreasingName !== false)) {
                // both sub-names existed: base name previously had no effect
                // so ignore it and try to find a shared part of the sub-names

                var newName = commonPrefix(
                    increasingName, decreasingName,
                    increasingShowlegend, decreasingShowlegend
                );
                // if no common part, leave whatever name was (or wasn't) there
                if(newName) trace.name = newName;
            }
            else if((increasingName || decreasingName) && !trace.name) {
                // one sub-name existed but not the base name - just use the sub-name
                trace.name = increasingName || decreasingName;
            }
        }

        // transforms backward compatibility fixes
        if(Array.isArray(trace.transforms)) {
            var transforms = trace.transforms;

            for(i = 0; i < transforms.length; i++) {
                var transform = transforms[i];

                if(!Lib.isPlainObject(transform)) continue;

                switch(transform.type) {
                    case 'filter':
                        if(transform.filtersrc) {
                            transform.target = transform.filtersrc;
                            delete transform.filtersrc;
                        }

                        if(transform.calendar) {
                            if(!transform.valuecalendar) {
                                transform.valuecalendar = transform.calendar;
                            }
                            delete transform.calendar;
                        }
                        break;

                    case 'groupby':
                        // Name has changed from `style` to `styles`, so use `style` but prefer `styles`:
                        transform.styles = transform.styles || transform.style;

                        if(transform.styles && !Array.isArray(transform.styles)) {
                            var prevStyles = transform.styles;
                            var styleKeys = Object.keys(prevStyles);

                            transform.styles = [];
                            for(var j = 0; j < styleKeys.length; j++) {
                                transform.styles.push({
                                    target: styleKeys[j],
                                    value: prevStyles[styleKeys[j]]
                                });
                            }
                        }
                        break;
                }
            }
        }

        // prune empty containers made before the new nestedProperty
        if(emptyContainer(trace, 'line')) delete trace.line;
        if('marker' in trace) {
            if(emptyContainer(trace.marker, 'line')) delete trace.marker.line;
            if(emptyContainer(trace, 'marker')) delete trace.marker;
        }

        // sanitize rgb(fractions) and rgba(fractions) that old tinycolor
        // supported, but new tinycolor does not because they're not valid css
        Color.clean(trace);

        // remove obsolete autobin(x|y) attributes, but only if true
        // if false, this needs to happen in Histogram.calc because it
        // can be a one-time autobin so we need to know the results before
        // we can push them back into the trace.
        if(trace.autobinx) {
            delete trace.autobinx;
            delete trace.xbins;
        }
        if(trace.autobiny) {
            delete trace.autobiny;
            delete trace.ybins;
        }

        cleanTitle(trace);
        if(trace.colorbar) cleanTitle(trace.colorbar);
        if(trace.marker && trace.marker.colorbar) cleanTitle(trace.marker.colorbar);
        if(trace.line && trace.line.colorbar) cleanTitle(trace.line.colorbar);
        if(trace.aaxis) cleanTitle(trace.aaxis);
        if(trace.baxis) cleanTitle(trace.baxis);
    }
};

function cleanFinanceDir(dirContainer) {
    if(!Lib.isPlainObject(dirContainer)) return false;

    var dirName = dirContainer.name;

    delete dirContainer.name;
    delete dirContainer.showlegend;

    return (typeof dirName === 'string' || typeof dirName === 'number') && String(dirName);
}

function commonPrefix(name1, name2, show1, show2) {
    // if only one is shown in the legend, use that
    if(show1 && !show2) return name1;
    if(show2 && !show1) return name2;

    // if both or neither are in the legend, check if one is blank (or whitespace)
    // and use the other one
    // note that hover labels can still use the name even if the legend doesn't
    if(!name1.trim()) return name2;
    if(!name2.trim()) return name1;

    var minLen = Math.min(name1.length, name2.length);
    var i;
    for(i = 0; i < minLen; i++) {
        if(name1.charAt(i) !== name2.charAt(i)) break;
    }

    var out = name1.substr(0, i);
    return out.trim();
}

// textposition - support partial attributes (ie just 'top')
// and incorrect use of middle / center etc.
function cleanTextPosition(textposition) {
    var posY = 'middle';
    var posX = 'center';

    if(typeof textposition === 'string') {
        if(textposition.indexOf('top') !== -1) posY = 'top';
        else if(textposition.indexOf('bottom') !== -1) posY = 'bottom';

        if(textposition.indexOf('left') !== -1) posX = 'left';
        else if(textposition.indexOf('right') !== -1) posX = 'right';
    }

    return posY + ' ' + posX;
}

function emptyContainer(outer, innerStr) {
    return (innerStr in outer) &&
        (typeof outer[innerStr] === 'object') &&
        (Object.keys(outer[innerStr]).length === 0);
}


// swap all the data and data attributes associated with x and y
exports.swapXYData = function(trace) {
    var i;
    Lib.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']);
    if(Array.isArray(trace.z) && Array.isArray(trace.z[0])) {
        if(trace.transpose) delete trace.transpose;
        else trace.transpose = true;
    }
    if(trace.error_x && trace.error_y) {
        var errorY = trace.error_y;
        var copyYstyle = ('copy_ystyle' in errorY) ?
            errorY.copy_ystyle :
            !(errorY.color || errorY.thickness || errorY.width);
        Lib.swapAttrs(trace, ['error_?.copy_ystyle']);
        if(copyYstyle) {
            Lib.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']);
        }
    }
    if(typeof trace.hoverinfo === 'string') {
        var hoverInfoParts = trace.hoverinfo.split('+');
        for(i = 0; i < hoverInfoParts.length; i++) {
            if(hoverInfoParts[i] === 'x') hoverInfoParts[i] = 'y';
            else if(hoverInfoParts[i] === 'y') hoverInfoParts[i] = 'x';
        }
        trace.hoverinfo = hoverInfoParts.join('+');
    }
};

// coerce traceIndices input to array of trace indices
exports.coerceTraceIndices = function(gd, traceIndices) {
    if(isNumeric(traceIndices)) {
        return [traceIndices];
    }
    else if(!Array.isArray(traceIndices) || !traceIndices.length) {
        return gd.data.map(function(_, i) { return i; });
    }
    else if(Array.isArray(traceIndices)) {
        var traceIndicesOut = [];
        for(var i = 0; i < traceIndices.length; i++) {
            if(Lib.isIndex(traceIndices[i], gd.data.length)) {
                traceIndicesOut.push(traceIndices[i]);
            } else {
                Lib.warn('trace index (', traceIndices[i], ') is not a number or is out of bounds');
            }
        }
        return traceIndicesOut;
    }

    return traceIndices;
};

/**
 * Manages logic around array container item creation / deletion / update
 * that nested property alone can't handle.
 *
 * @param {Object} np
 *  nested property of update attribute string about trace or layout object
 * @param {*} newVal
 *  update value passed to restyle / relayout / update
 * @param {Object} undoit
 *  undo hash (N.B. undoit may be mutated here).
 *
 */
exports.manageArrayContainers = function(np, newVal, undoit) {
    var obj = np.obj;
    var parts = np.parts;
    var pLength = parts.length;
    var pLast = parts[pLength - 1];

    var pLastIsNumber = isNumeric(pLast);

    // delete item
    if(pLastIsNumber && newVal === null) {

        // Clear item in array container when new value is null
        var contPath = parts.slice(0, pLength - 1).join('.');
        var cont = Lib.nestedProperty(obj, contPath).get();
        cont.splice(pLast, 1);

        // Note that nested property clears null / undefined at end of
        // array container, but not within them.
    }
    // create item
    else if(pLastIsNumber && np.get() === undefined) {

        // When adding a new item, make sure undo command will remove it
        if(np.get() === undefined) undoit[np.astr] = null;

        np.set(newVal);
    }
    // update item
    else {

        // If the last part of attribute string isn't a number,
        // np.set is all we need.
        np.set(newVal);
    }
};

/*
 * Match the part to strip off to turn an attribute into its parent
 * really it should be either '.some_characters' or '[number]'
 * but we're a little more permissive here and match either
 * '.not_brackets_or_dot' or '[not_brackets_or_dot]'
 */
var ATTR_TAIL_RE = /(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/;

function getParent(attr) {
    var tail = attr.search(ATTR_TAIL_RE);
    if(tail > 0) return attr.substr(0, tail);
}

/*
 * hasParent: does an attribute object contain a parent of the given attribute?
 * for example, given 'images[2].x' do we also have 'images' or 'images[2]'?
 *
 * @param {Object} aobj
 *  update object, whose keys are attribute strings and values are their new settings
 * @param {string} attr
 *  the attribute string to test against
 * @returns {Boolean}
 *  is a parent of attr present in aobj?
 */
exports.hasParent = function(aobj, attr) {
    var attrParent = getParent(attr);
    while(attrParent) {
        if(attrParent in aobj) return true;
        attrParent = getParent(attrParent);
    }
    return false;
};

/**
 * Empty out types for all axes containing these traces so we auto-set them again
 *
 * @param {object} gd
 * @param {[integer]} traces: trace indices to search for axes to clear the types of
 * @param {object} layoutUpdate: any update being done concurrently to the layout,
 *   which may supercede clearing the axis types
 */
var axLetters = ['x', 'y', 'z'];
exports.clearAxisTypes = function(gd, traces, layoutUpdate) {
    for(var i = 0; i < traces.length; i++) {
        var trace = gd._fullData[i];
        for(var j = 0; j < 3; j++) {
            var ax = getFromTrace(gd, trace, axLetters[j]);

            // do not clear log type - that's never an auto result so must have been intentional
            if(ax && ax.type !== 'log') {
                var axAttr = ax._name;
                var sceneName = ax._id.substr(1);
                if(sceneName.substr(0, 5) === 'scene') {
                    if(layoutUpdate[sceneName] !== undefined) continue;
                    axAttr = sceneName + '.' + axAttr;
                }
                var typeAttr = axAttr + '.type';

                if(layoutUpdate[axAttr] === undefined && layoutUpdate[typeAttr] === undefined) {
                    Lib.nestedProperty(gd.layout, typeAttr).set(null);
                }
            }
        }
    }
};

},{"../components/color":574,"../lib":697,"../plots/cartesian/axis_ids":748,"../plots/plots":807,"../registry":826,"fast-isnumeric":218,"gl-mat4/fromQuat":255}],730:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var main = _dereq_('./plot_api');

exports.plot = main.plot;
exports.newPlot = main.newPlot;
exports.restyle = main.restyle;
exports.relayout = main.relayout;
exports.redraw = main.redraw;
exports.update = main.update;
exports._guiRestyle = main._guiRestyle;
exports._guiRelayout = main._guiRelayout;
exports._guiUpdate = main._guiUpdate;
exports._storeDirectGUIEdit = main._storeDirectGUIEdit;
exports.react = main.react;
exports.extendTraces = main.extendTraces;
exports.prependTraces = main.prependTraces;
exports.addTraces = main.addTraces;
exports.deleteTraces = main.deleteTraces;
exports.moveTraces = main.moveTraces;
exports.purge = main.purge;
exports.addFrames = main.addFrames;
exports.deleteFrames = main.deleteFrames;
exports.animate = main.animate;
exports.setPlotConfig = main.setPlotConfig;

exports.toImage = _dereq_('./to_image');
exports.validate = _dereq_('./validate');
exports.downloadImage = _dereq_('../snapshot/download');

var templateApi = _dereq_('./template_api');
exports.makeTemplate = templateApi.makeTemplate;
exports.validateTemplate = templateApi.validateTemplate;

},{"../snapshot/download":828,"./plot_api":732,"./template_api":737,"./to_image":738,"./validate":739}],731:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isPlainObject = _dereq_('../lib/is_plain_object');
var noop = _dereq_('../lib/noop');
var Loggers = _dereq_('../lib/loggers');
var sorterAsc = _dereq_('../lib/search').sorterAsc;
var Registry = _dereq_('../registry');


exports.containerArrayMatch = _dereq_('./container_array_match');

var isAddVal = exports.isAddVal = function isAddVal(val) {
    return val === 'add' || isPlainObject(val);
};

var isRemoveVal = exports.isRemoveVal = function isRemoveVal(val) {
    return val === null || val === 'remove';
};

/*
 * applyContainerArrayChanges: for managing arrays of layout components in relayout
 * handles them all with a consistent interface.
 *
 * Here are the supported actions -> relayout calls -> edits we get here
 * (as prepared in _relayout):
 *
 * add an empty obj -> {'annotations[2]': 'add'} -> {2: {'': 'add'}}
 * add a specific obj -> {'annotations[2]': {attrs}} -> {2: {'': {attrs}}}
 * delete an obj -> {'annotations[2]': 'remove'} -> {2: {'': 'remove'}}
 *               -> {'annotations[2]': null} -> {2: {'': null}}
 * delete the whole array -> {'annotations': 'remove'} -> {'': {'': 'remove'}}
 *                        -> {'annotations': null} -> {'': {'': null}}
 * edit an object -> {'annotations[2].text': 'boo'} -> {2: {'text': 'boo'}}
 *
 * You can combine many edits to different objects. Objects are added and edited
 * in ascending order, then removed in descending order.
 * For example, starting with [a, b, c], if you want to:
 * - replace b with d:
 *   {'annotations[1]': d, 'annotations[2]': null} (b is item 2 after adding d)
 * - add a new item d between a and b, and edit b:
 *    {'annotations[1]': d, 'annotations[2].x': newX} (b is item 2 after adding d)
 * - delete b and edit c:
 *    {'annotations[1]': null, 'annotations[2].x': newX} (c is edited before b is removed)
 *
 * You CANNOT combine adding/deleting an item at index `i` with edits to the same index `i`
 * You CANNOT combine replacing/deleting the whole array with anything else (for the same array).
 *
 * @param {HTMLDivElement} gd
 *  the DOM element of the graph container div
 * @param {Lib.nestedProperty} componentType: the array we are editing
 * @param {Object} edits
 *  the changes to make; keys are indices to edit, values are themselves objects:
 *  {attr: newValue} of changes to make to that index (with add/remove behavior
 *  in special values of the empty attr)
 * @param {Object} flags
 *  the flags for which actions we're going to perform to display these (and
 *  any other) changes. If we're already `recalc`ing, we don't need to redraw
 *  individual items
 * @param {function} _nestedProperty
 *  a (possibly modified for gui edits) nestedProperty constructor
 *  The modified version takes a 3rd argument, for a prefix to the attribute
 *  string necessary for storing GUI edits
 *
 * @returns {bool} `true` if it managed to complete drawing of the changes
 *  `false` would mean the parent should replot.
 */
exports.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags, _nestedProperty) {
    var componentType = np.astr;
    var supplyComponentDefaults = Registry.getComponentMethod(componentType, 'supplyLayoutDefaults');
    var draw = Registry.getComponentMethod(componentType, 'draw');
    var drawOne = Registry.getComponentMethod(componentType, 'drawOne');
    var replotLater = flags.replot || flags.recalc || (supplyComponentDefaults === noop) || (draw === noop);
    var layout = gd.layout;
    var fullLayout = gd._fullLayout;

    if(edits['']) {
        if(Object.keys(edits).length > 1) {
            Loggers.warn('Full array edits are incompatible with other edits',
                componentType);
        }

        var fullVal = edits[''][''];

        if(isRemoveVal(fullVal)) np.set(null);
        else if(Array.isArray(fullVal)) np.set(fullVal);
        else {
            Loggers.warn('Unrecognized full array edit value', componentType, fullVal);
            return true;
        }

        if(replotLater) return false;

        supplyComponentDefaults(layout, fullLayout);
        draw(gd);
        return true;
    }

    var componentNums = Object.keys(edits).map(Number).sort(sorterAsc);
    var componentArrayIn = np.get();
    var componentArray = componentArrayIn || [];
    // componentArrayFull is used just to keep splices in line between
    // full and input arrays, so private keys can be copied over after
    // redoing supplyDefaults
    // TODO: this assumes componentArray is in gd.layout - which will not be
    // true after we extend this to restyle
    var componentArrayFull = _nestedProperty(fullLayout, componentType).get();

    var deletes = [];
    var firstIndexChange = -1;
    var maxIndex = componentArray.length;
    var i;
    var j;
    var componentNum;
    var objEdits;
    var objKeys;
    var objVal;
    var adding, prefix;

    // first make the add and edit changes
    for(i = 0; i < componentNums.length; i++) {
        componentNum = componentNums[i];
        objEdits = edits[componentNum];
        objKeys = Object.keys(objEdits);
        objVal = objEdits[''],
        adding = isAddVal(objVal);

        if(componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) {
            Loggers.warn('index out of range', componentType, componentNum);
            continue;
        }

        if(objVal !== undefined) {
            if(objKeys.length > 1) {
                Loggers.warn(
                    'Insertion & removal are incompatible with edits to the same index.',
                    componentType, componentNum);
            }

            if(isRemoveVal(objVal)) {
                deletes.push(componentNum);
            }
            else if(adding) {
                if(objVal === 'add') objVal = {};
                componentArray.splice(componentNum, 0, objVal);
                if(componentArrayFull) componentArrayFull.splice(componentNum, 0, {});
            }
            else {
                Loggers.warn('Unrecognized full object edit value',
                    componentType, componentNum, objVal);
            }

            if(firstIndexChange === -1) firstIndexChange = componentNum;
        }
        else {
            for(j = 0; j < objKeys.length; j++) {
                prefix = componentType + '[' + componentNum + '].';
                _nestedProperty(componentArray[componentNum], objKeys[j], prefix)
                    .set(objEdits[objKeys[j]]);
            }
        }
    }

    // now do deletes
    for(i = deletes.length - 1; i >= 0; i--) {
        componentArray.splice(deletes[i], 1);
        // TODO: this drops private keys that had been stored in componentArrayFull
        // does this have any ill effects?
        if(componentArrayFull) componentArrayFull.splice(deletes[i], 1);
    }

    if(!componentArray.length) np.set(null);
    else if(!componentArrayIn) np.set(componentArray);

    if(replotLater) return false;

    supplyComponentDefaults(layout, fullLayout);

    // finally draw all the components we need to
    // if we added or removed any, redraw all after it
    if(drawOne !== noop) {
        var indicesToDraw;
        if(firstIndexChange === -1) {
            // there's no re-indexing to do, so only redraw components that changed
            indicesToDraw = componentNums;
        }
        else {
            // in case the component array was shortened, we still need do call
            // drawOne on the latter items so they get properly removed
            maxIndex = Math.max(componentArray.length, maxIndex);
            indicesToDraw = [];
            for(i = 0; i < componentNums.length; i++) {
                componentNum = componentNums[i];
                if(componentNum >= firstIndexChange) break;
                indicesToDraw.push(componentNum);
            }
            for(i = firstIndexChange; i < maxIndex; i++) {
                indicesToDraw.push(i);
            }
        }
        for(i = 0; i < indicesToDraw.length; i++) {
            drawOne(gd, indicesToDraw[i]);
        }
    }
    else draw(gd);

    return true;
};

},{"../lib/is_plain_object":698,"../lib/loggers":701,"../lib/noop":706,"../lib/search":716,"../registry":826,"./container_array_match":727}],732:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');
var hasHover = _dereq_('has-hover');

var Lib = _dereq_('../lib');
var nestedProperty = Lib.nestedProperty;

var Events = _dereq_('../lib/events');
var Queue = _dereq_('../lib/queue');

var Registry = _dereq_('../registry');
var PlotSchema = _dereq_('./plot_schema');
var Plots = _dereq_('../plots/plots');
var Polar = _dereq_('../plots/polar/legacy');

var Axes = _dereq_('../plots/cartesian/axes');
var Drawing = _dereq_('../components/drawing');
var Color = _dereq_('../components/color');
var connectColorbar = _dereq_('../components/colorbar/connect');
var initInteractions = _dereq_('../plots/cartesian/graph_interact').initInteractions;
var xmlnsNamespaces = _dereq_('../constants/xmlns_namespaces');
var svgTextUtils = _dereq_('../lib/svg_text_utils');
var clearSelect = _dereq_('../plots/cartesian/select').clearSelect;

var dfltConfig = _dereq_('./plot_config').dfltConfig;
var manageArrays = _dereq_('./manage_arrays');
var helpers = _dereq_('./helpers');
var subroutines = _dereq_('./subroutines');
var editTypes = _dereq_('./edit_types');

var AX_NAME_PATTERN = _dereq_('../plots/cartesian/constants').AX_NAME_PATTERN;

var numericNameWarningCount = 0;
var numericNameWarningCountLimit = 5;

/**
 * Main plot-creation function
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 * @param {array of objects} data
 *      array of traces, containing the data and display information for each trace
 * @param {object} layout
 *      object describing the overall display of the plot,
 *      all the stuff that doesn't pertain to any individual trace
 * @param {object} config
 *      configuration options (see ./plot_config.js for more info)
 *
 * OR
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 * @param {object} figure
 *      object containing `data`, `layout`, `config`, and `frames` members
 *
 */
exports.plot = function(gd, data, layout, config) {
    var frames;

    gd = Lib.getGraphDiv(gd);

    // Events.init is idempotent and bails early if gd has already been init'd
    Events.init(gd);

    if(Lib.isPlainObject(data)) {
        var obj = data;
        data = obj.data;
        layout = obj.layout;
        config = obj.config;
        frames = obj.frames;
    }

    var okToPlot = Events.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]);
    if(okToPlot === false) return Promise.reject();

    // if there's no data or layout, and this isn't yet a plotly plot
    // container, log a warning to help plotly.js users debug
    if(!data && !layout && !Lib.isPlotDiv(gd)) {
        Lib.warn('Calling Plotly.plot as if redrawing ' +
            'but this container doesn\'t yet have a plot.', gd);
    }

    function addFrames() {
        if(frames) {
            return exports.addFrames(gd, frames);
        }
    }

    // transfer configuration options to gd until we move over to
    // a more OO like model
    setPlotContext(gd, config);

    if(!layout) layout = {};

    // hook class for plots main container (in case of plotly.js
    // this won't be #embedded-graph or .js-tab-contents)
    d3.select(gd).classed('js-plotly-plot', true);

    // off-screen getBoundingClientRect testing space,
    // in #js-plotly-tester (and stored as Drawing.tester)
    // so we can share cached text across tabs
    Drawing.makeTester();

    // collect promises for any async actions during plotting
    // any part of the plotting code can push to gd._promises, then
    // before we move to the next step, we check that they're all
    // complete, and empty out the promise list again.
    if(!Array.isArray(gd._promises)) gd._promises = [];

    var graphWasEmpty = ((gd.data || []).length === 0 && Array.isArray(data));

    // if there is already data on the graph, append the new data
    // if you only want to redraw, pass a non-array for data
    if(Array.isArray(data)) {
        helpers.cleanData(data);

        if(graphWasEmpty) gd.data = data;
        else gd.data.push.apply(gd.data, data);

        // for routines outside graph_obj that want a clean tab
        // (rather than appending to an existing one) gd.empty
        // is used to determine whether to make a new tab
        gd.empty = false;
    }

    if(!gd.layout || graphWasEmpty) gd.layout = helpers.cleanLayout(layout);

    // if the user is trying to drag the axes, allow new data and layout
    // to come in but don't allow a replot.
    if(gd._dragging && !gd._transitioning) {
        // signal to drag handler that after everything else is done
        // we need to replot, because something has changed
        gd._replotPending = true;
        return Promise.reject();
    } else {
        // we're going ahead with a replot now
        gd._replotPending = false;
    }

    Plots.supplyDefaults(gd);

    var fullLayout = gd._fullLayout;
    var hasCartesian = fullLayout._has('cartesian');

    // Legacy polar plots
    if(!fullLayout._has('polar') && data && data[0] && data[0].r) {
        Lib.log('Legacy polar charts are deprecated!');
        return plotLegacyPolar(gd, data, layout);
    }

    // so we don't try to re-call Plotly.plot from inside
    // legend and colorbar, if margins changed
    fullLayout._replotting = true;

    // make or remake the framework if we need to
    if(graphWasEmpty) makePlotFramework(gd);

    // polar need a different framework
    if(gd.framework !== makePlotFramework) {
        gd.framework = makePlotFramework;
        makePlotFramework(gd);
    }

    // clear gradient defs on each .plot call, because we know we'll loop through all traces
    Drawing.initGradients(gd);

    // save initial show spikes once per graph
    if(graphWasEmpty) Axes.saveShowSpikeInitial(gd);

    // prepare the data and find the autorange

    // generate calcdata, if we need to
    // to force redoing calcdata, just delete it before calling Plotly.plot
    var recalc = !gd.calcdata || gd.calcdata.length !== (gd._fullData || []).length;
    if(recalc) Plots.doCalcdata(gd);

    // in case it has changed, attach fullData traces to calcdata
    for(var i = 0; i < gd.calcdata.length; i++) {
        gd.calcdata[i][0].trace = gd._fullData[i];
    }

    // make the figure responsive
    if(gd._context.responsive) {
        if(!gd._responsiveChartHandler) {
            // Keep a reference to the resize handler to purge it down the road
            gd._responsiveChartHandler = function() {Plots.resize(gd);};

            // Listen to window resize
            window.addEventListener('resize', gd._responsiveChartHandler);
        }
    } else {
        Lib.clearResponsive(gd);
    }

    /*
     * start async-friendly code - now we're actually drawing things
     */

    var oldmargins = JSON.stringify(fullLayout._size);

    // draw framework first so that margin-pushing
    // components can position themselves correctly
    var drawFrameworkCalls = 0;
    function drawFramework() {
        var basePlotModules = fullLayout._basePlotModules;

        for(var i = 0; i < basePlotModules.length; i++) {
            if(basePlotModules[i].drawFramework) {
                basePlotModules[i].drawFramework(gd);
            }
        }

        if(!fullLayout._glcanvas && fullLayout._has('gl')) {
            fullLayout._glcanvas = fullLayout._glcontainer.selectAll('.gl-canvas').data([{
                key: 'contextLayer',
                context: true,
                pick: false
            }, {
                key: 'focusLayer',
                context: false,
                pick: false
            }, {
                key: 'pickLayer',
                context: false,
                pick: true
            }], function(d) { return d.key; });

            fullLayout._glcanvas.enter().append('canvas')
                .attr('class', function(d) {
                    return 'gl-canvas gl-canvas-' + d.key.replace('Layer', '');
                })
                .style({
                    'position': 'absolute',
                    'top': 0,
                    'left': 0,
                    'overflow': 'visible',
                    'pointer-events': 'none'
                });
        }

        if(fullLayout._glcanvas) {
            fullLayout._glcanvas
                .attr('width', fullLayout.width)
                .attr('height', fullLayout.height);

            var regl = fullLayout._glcanvas.data()[0].regl;
            if(regl) {
                // Unfortunately, this can happen when relayouting to large
                // width/height on some browsers.
                if(Math.floor(fullLayout.width) !== regl._gl.drawingBufferWidth ||
                    Math.floor(fullLayout.height) !== regl._gl.drawingBufferHeight
                 ) {
                    var msg = 'WebGL context buffer and canvas dimensions do not match due to browser/WebGL bug.';
                    if(drawFrameworkCalls) {
                        Lib.error(msg);
                    } else {
                        Lib.log(msg + ' Clearing graph and plotting again.');
                        Plots.cleanPlot([], {}, gd._fullData, fullLayout);
                        Plots.supplyDefaults(gd);
                        fullLayout = gd._fullLayout;
                        Plots.doCalcdata(gd);
                        drawFrameworkCalls++;
                        return drawFramework();
                    }
                }
            }
        }

        if(fullLayout.modebar.orientation === 'h') {
            fullLayout._modebardiv
              .style('height', null)
              .style('width', '100%');
        } else {
            fullLayout._modebardiv
              .style('width', null)
              .style('height', fullLayout.height + 'px');
        }

        return Plots.previousPromises(gd);
    }

    // draw anything that can affect margins.
    function marginPushers() {
        var calcdata = gd.calcdata;
        var i, cd, trace;

        // First reset the list of things that are allowed to change the margins
        // So any deleted traces or components will be wiped out of the
        // automargin calculation.
        // This means *every* margin pusher must be listed here, even if it
        // doesn't actually try to push the margins until later.
        Plots.clearAutoMarginIds(gd);

        subroutines.drawMarginPushers(gd);
        Axes.allowAutoMargin(gd);

        for(i = 0; i < calcdata.length; i++) {
            cd = calcdata[i];
            trace = cd[0].trace;
            var colorbarOpts = trace._module.colorbar;
            if(trace.visible !== true || !colorbarOpts) {
                Plots.autoMargin(gd, 'cb' + trace.uid);
            }
            else connectColorbar(gd, cd, colorbarOpts);
        }

        Plots.doAutoMargin(gd);
        return Plots.previousPromises(gd);
    }

    // in case the margins changed, draw margin pushers again
    function marginPushersAgain() {
        if(JSON.stringify(fullLayout._size) === oldmargins) return;

        return Lib.syncOrAsync([
            marginPushers,
            subroutines.layoutStyles
        ], gd);
    }

    function positionAndAutorange() {
        if(!recalc) {
            doAutoRangeAndConstraints();
            return;
        }

        // TODO: autosize extra for text markers and images
        // see https://github.com/plotly/plotly.js/issues/1111
        return Lib.syncOrAsync([
            Registry.getComponentMethod('shapes', 'calcAutorange'),
            Registry.getComponentMethod('annotations', 'calcAutorange'),
            doAutoRangeAndConstraints
        ], gd);
    }

    function doAutoRangeAndConstraints() {
        if(gd._transitioning) return;

        subroutines.doAutoRangeAndConstraints(gd);

        // store initial ranges *after* enforcing constraints, otherwise
        // we will never look like we're at the initial ranges
        if(graphWasEmpty) Axes.saveRangeInitial(gd);

        // this one is different from shapes/annotations calcAutorange
        // the others incorporate those components into ax._extremes,
        // this one actually sets the ranges in rangesliders.
        Registry.getComponentMethod('rangeslider', 'calcAutorange')(gd);
    }

    // draw ticks, titles, and calculate axis scaling (._b, ._m)
    function drawAxes() {
        return Axes.draw(gd, graphWasEmpty ? '' : 'redraw');
    }

    var seq = [
        Plots.previousPromises,
        addFrames,
        drawFramework,
        marginPushers,
        marginPushersAgain
    ];

    if(hasCartesian) seq.push(positionAndAutorange);

    seq.push(subroutines.layoutStyles);
    if(hasCartesian) seq.push(drawAxes);

    seq.push(
        subroutines.drawData,
        subroutines.finalDraw,
        initInteractions,
        Plots.addLinks,
        Plots.rehover,
        // TODO: doAutoMargin is only needed here for axis automargin, which
        // happens outside of marginPushers where all the other automargins are
        // calculated. Would be much better to separate margin calculations from
        // component drawing - see https://github.com/plotly/plotly.js/issues/2704
        Plots.doAutoMargin,
        Plots.previousPromises
    );

    // even if everything we did was synchronous, return a promise
    // so that the caller doesn't care which route we took
    var plotDone = Lib.syncOrAsync(seq, gd);
    if(!plotDone || !plotDone.then) plotDone = Promise.resolve();

    return plotDone.then(function() {
        emitAfterPlot(gd);
        return gd;
    });
};

function emitAfterPlot(gd) {
    var fullLayout = gd._fullLayout;

    if(fullLayout._redrawFromAutoMarginCount) {
        fullLayout._redrawFromAutoMarginCount--;
    } else {
        gd.emit('plotly_afterplot');
    }
}

exports.setPlotConfig = function setPlotConfig(obj) {
    return Lib.extendFlat(dfltConfig, obj);
};

function setBackground(gd, bgColor) {
    try {
        gd._fullLayout._paper.style('background', bgColor);
    } catch(e) {
        Lib.error(e);
    }
}

function opaqueSetBackground(gd, bgColor) {
    var blend = Color.combine(bgColor, 'white');
    setBackground(gd, blend);
}

function setPlotContext(gd, config) {
    if(!gd._context) {
        gd._context = Lib.extendDeep({}, dfltConfig);

        // stash <base> href, used to make robust clipPath URLs
        var base = d3.select('base');
        gd._context._baseUrl = base.size() && base.attr('href') ?
            window.location.href.split('#')[0] :
            '';
    }

    var context = gd._context;

    var i, keys, key;

    if(config) {
        keys = Object.keys(config);
        for(i = 0; i < keys.length; i++) {
            key = keys[i];
            if(key === 'editable' || key === 'edits') continue;
            if(key in context) {
                if(key === 'setBackground' && config[key] === 'opaque') {
                    context[key] = opaqueSetBackground;
                } else {
                    context[key] = config[key];
                }
            }
        }

        // map plot3dPixelRatio to plotGlPixelRatio for backward compatibility
        if(config.plot3dPixelRatio && !context.plotGlPixelRatio) {
            context.plotGlPixelRatio = context.plot3dPixelRatio;
        }

        // now deal with editable and edits - first editable overrides
        // everything, then edits refines
        var editable = config.editable;
        if(editable !== undefined) {
            // we're not going to *use* context.editable, we're only going to
            // use context.edits... but keep it for the record
            context.editable = editable;

            keys = Object.keys(context.edits);
            for(i = 0; i < keys.length; i++) {
                context.edits[keys[i]] = editable;
            }
        }
        if(config.edits) {
            keys = Object.keys(config.edits);
            for(i = 0; i < keys.length; i++) {
                key = keys[i];
                if(key in context.edits) {
                    context.edits[key] = config.edits[key];
                }
            }
        }

        // not part of the user-facing config options
        context._exportedPlot = config._exportedPlot;
    }

    // staticPlot forces a bunch of others:
    if(context.staticPlot) {
        context.editable = false;
        context.edits = {};
        context.autosizable = false;
        context.scrollZoom = false;
        context.doubleClick = false;
        context.showTips = false;
        context.showLink = false;
        context.displayModeBar = false;
    }

    // make sure hover-only devices have mode bar visible
    if(context.displayModeBar === 'hover' && !hasHover) {
        context.displayModeBar = true;
    }

    // default and fallback for setBackground
    if(context.setBackground === 'transparent' || typeof context.setBackground !== 'function') {
        context.setBackground = setBackground;
    }

    // Check if gd has a specified widht/height to begin with
    context._hasZeroHeight = context._hasZeroHeight || gd.clientHeight === 0;
    context._hasZeroWidth = context._hasZeroWidth || gd.clientWidth === 0;

    // fill context._scrollZoom helper to help manage scrollZoom flaglist
    var szIn = context.scrollZoom;
    var szOut = context._scrollZoom = {};
    if(szIn === true) {
        szOut.cartesian = 1;
        szOut.gl3d = 1;
        szOut.geo = 1;
        szOut.mapbox = 1;
    } else if(typeof szIn === 'string') {
        var parts = szIn.split('+');
        for(i = 0; i < parts.length; i++) {
            szOut[parts[i]] = 1;
        }
    } else if(szIn !== false) {
        szOut.gl3d = 1;
        szOut.geo = 1;
        szOut.mapbox = 1;
    }
}

function plotLegacyPolar(gd, data, layout) {
    // build or reuse the container skeleton
    var plotContainer = d3.select(gd).selectAll('.plot-container')
        .data([0]);
    plotContainer.enter()
        .insert('div', ':first-child')
        .classed('plot-container plotly', true);
    var paperDiv = plotContainer.selectAll('.svg-container')
        .data([0]);
    paperDiv.enter().append('div')
        .classed('svg-container', true)
        .style('position', 'relative');

    // empty it everytime for now
    paperDiv.html('');

    // fulfill gd requirements
    if(data) gd.data = data;
    if(layout) gd.layout = layout;
    Polar.manager.fillLayout(gd);

    // resize canvas
    paperDiv.style({
        width: gd._fullLayout.width + 'px',
        height: gd._fullLayout.height + 'px'
    });

    // instantiate framework
    gd.framework = Polar.manager.framework(gd);

    // plot
    gd.framework({data: gd.data, layout: gd.layout}, paperDiv.node());

    // set undo point
    gd.framework.setUndoPoint();

    // get the resulting svg for extending it
    var polarPlotSVG = gd.framework.svg();

    // editable title
    var opacity = 1;
    var txt = gd._fullLayout.title ? gd._fullLayout.title.text : '';
    if(txt === '' || !txt) opacity = 0;

    var titleLayout = function() {
        this.call(svgTextUtils.convertToTspans, gd);
        // TODO: html/mathjax
        // TODO: center title
    };

    var title = polarPlotSVG.select('.title-group text')
        .call(titleLayout);

    if(gd._context.edits.titleText) {
        var placeholderText = Lib._(gd, 'Click to enter Plot title');
        if(!txt || txt === placeholderText) {
            opacity = 0.2;
            // placeholder is not going through convertToTspans
            // so needs explicit data-unformatted
            title.attr({'data-unformatted': placeholderText})
                .text(placeholderText)
                .style({opacity: opacity})
                .on('mouseover.opacity', function() {
                    d3.select(this).transition().duration(100)
                        .style('opacity', 1);
                })
                .on('mouseout.opacity', function() {
                    d3.select(this).transition().duration(1000)
                        .style('opacity', 0);
                });
        }

        var setContenteditable = function() {
            this.call(svgTextUtils.makeEditable, {gd: gd})
                .on('edit', function(text) {
                    gd.framework({layout: {title: {text: text}}});
                    this.text(text)
                        .call(titleLayout);
                    this.call(setContenteditable);
                })
                .on('cancel', function() {
                    var txt = this.attr('data-unformatted');
                    this.text(txt).call(titleLayout);
                });
        };
        title.call(setContenteditable);
    }

    gd._context.setBackground(gd, gd._fullLayout.paper_bgcolor);
    Plots.addLinks(gd);

    return Promise.resolve();
}

// convenience function to force a full redraw, mostly for use by plotly.js
exports.redraw = function(gd) {
    gd = Lib.getGraphDiv(gd);

    if(!Lib.isPlotDiv(gd)) {
        throw new Error('This element is not a Plotly plot: ' + gd);
    }

    helpers.cleanData(gd.data);
    helpers.cleanLayout(gd.layout);

    gd.calcdata = undefined;
    return exports.plot(gd).then(function() {
        gd.emit('plotly_redraw');
        return gd;
    });
};

/**
 * Convenience function to make idempotent plot option obvious to users.
 *
 * @param gd
 * @param {Object[]} data
 * @param {Object} layout
 * @param {Object} config
 */
exports.newPlot = function(gd, data, layout, config) {
    gd = Lib.getGraphDiv(gd);

    // remove gl contexts
    Plots.cleanPlot([], {}, gd._fullData || [], gd._fullLayout || {});

    Plots.purge(gd);
    return exports.plot(gd, data, layout, config);
};

/**
 * Wrap negative indicies to their positive counterparts.
 *
 * @param {Number[]} indices An array of indices
 * @param {Number} maxIndex The maximum index allowable (arr.length - 1)
 */
function positivifyIndices(indices, maxIndex) {
    var parentLength = maxIndex + 1;
    var positiveIndices = [];
    var i;
    var index;

    for(i = 0; i < indices.length; i++) {
        index = indices[i];
        if(index < 0) {
            positiveIndices.push(parentLength + index);
        } else {
            positiveIndices.push(index);
        }
    }
    return positiveIndices;
}

/**
 * Ensures that an index array for manipulating gd.data is valid.
 *
 * Intended for use with addTraces, deleteTraces, and moveTraces.
 *
 * @param gd
 * @param indices
 * @param arrayName
 */
function assertIndexArray(gd, indices, arrayName) {
    var i,
        index;

    for(i = 0; i < indices.length; i++) {
        index = indices[i];

        // validate that indices are indeed integers
        if(index !== parseInt(index, 10)) {
            throw new Error('all values in ' + arrayName + ' must be integers');
        }

        // check that all indices are in bounds for given gd.data array length
        if(index >= gd.data.length || index < -gd.data.length) {
            throw new Error(arrayName + ' must be valid indices for gd.data.');
        }

        // check that indices aren't repeated
        if(indices.indexOf(index, i + 1) > -1 ||
                index >= 0 && indices.indexOf(-gd.data.length + index) > -1 ||
                index < 0 && indices.indexOf(gd.data.length + index) > -1) {
            throw new Error('each index in ' + arrayName + ' must be unique.');
        }
    }
}

/**
 * Private function used by Plotly.moveTraces to check input args
 *
 * @param gd
 * @param currentIndices
 * @param newIndices
 */
function checkMoveTracesArgs(gd, currentIndices, newIndices) {

    // check that gd has attribute 'data' and 'data' is array
    if(!Array.isArray(gd.data)) {
        throw new Error('gd.data must be an array.');
    }

    // validate currentIndices array
    if(typeof currentIndices === 'undefined') {
        throw new Error('currentIndices is a required argument.');
    } else if(!Array.isArray(currentIndices)) {
        currentIndices = [currentIndices];
    }
    assertIndexArray(gd, currentIndices, 'currentIndices');

    // validate newIndices array if it exists
    if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {
        newIndices = [newIndices];
    }
    if(typeof newIndices !== 'undefined') {
        assertIndexArray(gd, newIndices, 'newIndices');
    }

    // check currentIndices and newIndices are the same length if newIdices exists
    if(typeof newIndices !== 'undefined' && currentIndices.length !== newIndices.length) {
        throw new Error('current and new indices must be of equal length.');
    }

}
/**
 * A private function to reduce the type checking clutter in addTraces.
 *
 * @param gd
 * @param traces
 * @param newIndices
 */
function checkAddTracesArgs(gd, traces, newIndices) {
    var i, value;

    // check that gd has attribute 'data' and 'data' is array
    if(!Array.isArray(gd.data)) {
        throw new Error('gd.data must be an array.');
    }

    // make sure traces exists
    if(typeof traces === 'undefined') {
        throw new Error('traces must be defined.');
    }

    // make sure traces is an array
    if(!Array.isArray(traces)) {
        traces = [traces];
    }

    // make sure each value in traces is an object
    for(i = 0; i < traces.length; i++) {
        value = traces[i];
        if(typeof value !== 'object' || (Array.isArray(value) || value === null)) {
            throw new Error('all values in traces array must be non-array objects');
        }
    }

    // make sure we have an index for each trace
    if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {
        newIndices = [newIndices];
    }
    if(typeof newIndices !== 'undefined' && newIndices.length !== traces.length) {
        throw new Error(
            'if indices is specified, traces.length must equal indices.length'
        );
    }
}

/**
 * A private function to reduce the type checking clutter in spliceTraces.
 * Get all update Properties from gd.data. Validate inputs and outputs.
 * Used by prependTrace and extendTraces
 *
 * @param gd
 * @param update
 * @param indices
 * @param maxPoints
 */
function assertExtendTracesArgs(gd, update, indices, maxPoints) {

    var maxPointsIsObject = Lib.isPlainObject(maxPoints);

    if(!Array.isArray(gd.data)) {
        throw new Error('gd.data must be an array');
    }
    if(!Lib.isPlainObject(update)) {
        throw new Error('update must be a key:value object');
    }

    if(typeof indices === 'undefined') {
        throw new Error('indices must be an integer or array of integers');
    }

    assertIndexArray(gd, indices, 'indices');

    for(var key in update) {

        /*
         * Verify that the attribute to be updated contains as many trace updates
         * as indices. Failure must result in throw and no-op
         */
        if(!Array.isArray(update[key]) || update[key].length !== indices.length) {
            throw new Error('attribute ' + key + ' must be an array of length equal to indices array length');
        }

        /*
         * if maxPoints is an object it must match keys and array lengths of 'update' 1:1
         */
        if(maxPointsIsObject &&
            (!(key in maxPoints) || !Array.isArray(maxPoints[key]) ||
            maxPoints[key].length !== update[key].length)) {
            throw new Error('when maxPoints is set as a key:value object it must contain a 1:1 ' +
                            'corrispondence with the keys and number of traces in the update object');
        }
    }
}

/**
 * A private function to reduce the type checking clutter in spliceTraces.
 *
 * @param {Object|HTMLDivElement} gd
 * @param {Object} update
 * @param {Number[]} indices
 * @param {Number||Object} maxPoints
 * @return {Object[]}
 */
function getExtendProperties(gd, update, indices, maxPoints) {

    var maxPointsIsObject = Lib.isPlainObject(maxPoints);
    var updateProps = [];
    var trace, target, prop, insert, maxp;

    // allow scalar index to represent a single trace position
    if(!Array.isArray(indices)) indices = [indices];

    // negative indices are wrapped around to their positive value. Equivalent to python indexing.
    indices = positivifyIndices(indices, gd.data.length - 1);

    // loop through all update keys and traces and harvest validated data.
    for(var key in update) {

        for(var j = 0; j < indices.length; j++) {

            /*
             * Choose the trace indexed by the indices map argument and get the prop setter-getter
             * instance that references the key and value for this particular trace.
             */
            trace = gd.data[indices[j]];
            prop = nestedProperty(trace, key);

            /*
             * Target is the existing gd.data.trace.dataArray value like "x" or "marker.size"
             * Target must exist as an Array to allow the extend operation to be performed.
             */
            target = prop.get();
            insert = update[key][j];

            if(!Lib.isArrayOrTypedArray(insert)) {
                throw new Error('attribute: ' + key + ' index: ' + j + ' must be an array');
            }
            if(!Lib.isArrayOrTypedArray(target)) {
                throw new Error('cannot extend missing or non-array attribute: ' + key);
            }
            if(target.constructor !== insert.constructor) {
                throw new Error('cannot extend array with an array of a different type: ' + key);
            }

            /*
             * maxPoints may be an object map or a scalar. If object select the key:value, else
             * Use the scalar maxPoints for all key and trace combinations.
             */
            maxp = maxPointsIsObject ? maxPoints[key][j] : maxPoints;

            // could have chosen null here, -1 just tells us to not take a window
            if(!isNumeric(maxp)) maxp = -1;

            /*
             * Wrap the nestedProperty in an object containing required data
             * for lengthening and windowing this particular trace - key combination.
             * Flooring maxp mirrors the behaviour of floats in the Array.slice JSnative function.
             */
            updateProps.push({
                prop: prop,
                target: target,
                insert: insert,
                maxp: Math.floor(maxp)
            });
        }
    }

    // all target and insertion data now validated
    return updateProps;
}

/**
 * A private function to key Extend and Prepend traces DRY
 *
 * @param {Object|HTMLDivElement} gd
 * @param {Object} update
 * @param {Number[]} indices
 * @param {Number||Object} maxPoints
 * @param {Function} updateArray
 * @return {Object}
 */
function spliceTraces(gd, update, indices, maxPoints, updateArray) {
    assertExtendTracesArgs(gd, update, indices, maxPoints);

    var updateProps = getExtendProperties(gd, update, indices, maxPoints);
    var undoUpdate = {};
    var undoPoints = {};

    for(var i = 0; i < updateProps.length; i++) {
        var prop = updateProps[i].prop;
        var maxp = updateProps[i].maxp;

        // return new array and remainder
        var out = updateArray(updateProps[i].target, updateProps[i].insert, maxp);
        prop.set(out[0]);

        // build the inverse update object for the undo operation
        if(!Array.isArray(undoUpdate[prop.astr])) undoUpdate[prop.astr] = [];
        undoUpdate[prop.astr].push(out[1]);

         // build the matching maxPoints undo object containing original trace lengths
        if(!Array.isArray(undoPoints[prop.astr])) undoPoints[prop.astr] = [];
        undoPoints[prop.astr].push(updateProps[i].target.length);
    }

    return {update: undoUpdate, maxPoints: undoPoints};
}

function concatTypedArray(arr0, arr1) {
    var arr2 = new arr0.constructor(arr0.length + arr1.length);
    arr2.set(arr0);
    arr2.set(arr1, arr0.length);
    return arr2;
}

/**
 * extend && prepend traces at indices with update arrays, window trace lengths to maxPoints
 *
 * Extend and Prepend have identical APIs. Prepend inserts an array at the head while Extend
 * inserts an array off the tail. Prepend truncates the tail of the array - counting maxPoints
 * from the head, whereas Extend truncates the head of the array, counting backward maxPoints
 * from the tail.
 *
 * If maxPoints is undefined, nonNumeric, negative or greater than extended trace length no
 * truncation / windowing will be performed. If its zero, well the whole trace is truncated.
 *
 * @param {Object|HTMLDivElement} gd The graph div
 * @param {Object} update The key:array map of target attributes to extend
 * @param {Number|Number[]} indices The locations of traces to be extended
 * @param {Number|Object} [maxPoints] Number of points for trace window after lengthening.
 *
 */
exports.extendTraces = function extendTraces(gd, update, indices, maxPoints) {
    gd = Lib.getGraphDiv(gd);

    function updateArray(target, insert, maxp) {
        var newArray, remainder;

        if(Lib.isTypedArray(target)) {
            if(maxp < 0) {
                var none = new target.constructor(0);
                var both = concatTypedArray(target, insert);

                if(maxp < 0) {
                    newArray = both;
                    remainder = none;
                } else {
                    newArray = none;
                    remainder = both;
                }
            } else {
                newArray = new target.constructor(maxp);
                remainder = new target.constructor(target.length + insert.length - maxp);

                if(maxp === insert.length) {
                    newArray.set(insert);
                    remainder.set(target);
                } else if(maxp < insert.length) {
                    var numberOfItemsFromInsert = insert.length - maxp;

                    newArray.set(insert.subarray(numberOfItemsFromInsert));
                    remainder.set(target);
                    remainder.set(insert.subarray(0, numberOfItemsFromInsert), target.length);
                } else {
                    var numberOfItemsFromTarget = maxp - insert.length;
                    var targetBegin = target.length - numberOfItemsFromTarget;

                    newArray.set(target.subarray(targetBegin));
                    newArray.set(insert, numberOfItemsFromTarget);
                    remainder.set(target.subarray(0, targetBegin));
                }
            }
        } else {
            newArray = target.concat(insert);
            remainder = (maxp >= 0 && maxp < newArray.length) ?
                newArray.splice(0, newArray.length - maxp) :
                [];
        }

        return [newArray, remainder];
    }

    var undo = spliceTraces(gd, update, indices, maxPoints, updateArray);
    var promise = exports.redraw(gd);
    var undoArgs = [gd, undo.update, indices, undo.maxPoints];
    Queue.add(gd, exports.prependTraces, undoArgs, extendTraces, arguments);

    return promise;
};

exports.prependTraces = function prependTraces(gd, update, indices, maxPoints) {
    gd = Lib.getGraphDiv(gd);

    function updateArray(target, insert, maxp) {
        var newArray, remainder;

        if(Lib.isTypedArray(target)) {
            if(maxp <= 0) {
                var none = new target.constructor(0);
                var both = concatTypedArray(insert, target);

                if(maxp < 0) {
                    newArray = both;
                    remainder = none;
                } else {
                    newArray = none;
                    remainder = both;
                }
            } else {
                newArray = new target.constructor(maxp);
                remainder = new target.constructor(target.length + insert.length - maxp);

                if(maxp === insert.length) {
                    newArray.set(insert);
                    remainder.set(target);
                } else if(maxp < insert.length) {
                    var numberOfItemsFromInsert = insert.length - maxp;

                    newArray.set(insert.subarray(0, numberOfItemsFromInsert));
                    remainder.set(insert.subarray(numberOfItemsFromInsert));
                    remainder.set(target, numberOfItemsFromInsert);
                } else {
                    var numberOfItemsFromTarget = maxp - insert.length;

                    newArray.set(insert);
                    newArray.set(target.subarray(0, numberOfItemsFromTarget), insert.length);
                    remainder.set(target.subarray(numberOfItemsFromTarget));
                }
            }
        } else {
            newArray = insert.concat(target);
            remainder = (maxp >= 0 && maxp < newArray.length) ?
                newArray.splice(maxp, newArray.length) :
                [];
        }

        return [newArray, remainder];
    }

    var undo = spliceTraces(gd, update, indices, maxPoints, updateArray);
    var promise = exports.redraw(gd);
    var undoArgs = [gd, undo.update, indices, undo.maxPoints];
    Queue.add(gd, exports.extendTraces, undoArgs, prependTraces, arguments);

    return promise;
};

/**
 * Add data traces to an existing graph div.
 *
 * @param {Object|HTMLDivElement} gd The graph div
 * @param {Object[]} gd.data The array of traces we're adding to
 * @param {Object[]|Object} traces The object or array of objects to add
 * @param {Number[]|Number} [newIndices=[gd.data.length]] Locations to add traces
 *
 */
exports.addTraces = function addTraces(gd, traces, newIndices) {
    gd = Lib.getGraphDiv(gd);

    var currentIndices = [];
    var undoFunc = exports.deleteTraces;
    var redoFunc = addTraces;
    var undoArgs = [gd, currentIndices];
    var redoArgs = [gd, traces];  // no newIndices here
    var i;
    var promise;

    // all validation is done elsewhere to remove clutter here
    checkAddTracesArgs(gd, traces, newIndices);

    // make sure traces is an array
    if(!Array.isArray(traces)) {
        traces = [traces];
    }

    // make sure traces do not repeat existing ones
    traces = traces.map(function(trace) {
        return Lib.extendFlat({}, trace);
    });

    helpers.cleanData(traces);

    // add the traces to gd.data (no redrawing yet!)
    for(i = 0; i < traces.length; i++) {
        gd.data.push(traces[i]);
    }

    // to continue, we need to call moveTraces which requires currentIndices
    for(i = 0; i < traces.length; i++) {
        currentIndices.push(-traces.length + i);
    }

    // if the user didn't define newIndices, they just want the traces appended
    // i.e., we can simply redraw and be done
    if(typeof newIndices === 'undefined') {
        promise = exports.redraw(gd);
        Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
        return promise;
    }

    // make sure indices is property defined
    if(!Array.isArray(newIndices)) {
        newIndices = [newIndices];
    }

    try {

        // this is redundant, but necessary to not catch later possible errors!
        checkMoveTracesArgs(gd, currentIndices, newIndices);
    }
    catch(error) {

        // something went wrong, reset gd to be safe and rethrow error
        gd.data.splice(gd.data.length - traces.length, traces.length);
        throw error;
    }

    // if we're here, the user has defined specific places to place the new traces
    // this requires some extra work that moveTraces will do
    Queue.startSequence(gd);
    Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
    promise = exports.moveTraces(gd, currentIndices, newIndices);
    Queue.stopSequence(gd);
    return promise;
};

/**
 * Delete traces at `indices` from gd.data array.
 *
 * @param {Object|HTMLDivElement} gd The graph div
 * @param {Object[]} gd.data The array of traces we're removing from
 * @param {Number|Number[]} indices The indices
 */
exports.deleteTraces = function deleteTraces(gd, indices) {
    gd = Lib.getGraphDiv(gd);

    var traces = [];
    var undoFunc = exports.addTraces;
    var redoFunc = deleteTraces;
    var undoArgs = [gd, traces, indices];
    var redoArgs = [gd, indices];
    var i;
    var deletedTrace;

    // make sure indices are defined
    if(typeof indices === 'undefined') {
        throw new Error('indices must be an integer or array of integers.');
    } else if(!Array.isArray(indices)) {
        indices = [indices];
    }
    assertIndexArray(gd, indices, 'indices');

    // convert negative indices to positive indices
    indices = positivifyIndices(indices, gd.data.length - 1);

    // we want descending here so that splicing later doesn't affect indexing
    indices.sort(Lib.sorterDes);
    for(i = 0; i < indices.length; i += 1) {
        deletedTrace = gd.data.splice(indices[i], 1)[0];
        traces.push(deletedTrace);
    }

    var promise = exports.redraw(gd);
    Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);

    return promise;
};

/**
 * Move traces at currentIndices array to locations in newIndices array.
 *
 * If newIndices is omitted, currentIndices will be moved to the end. E.g.,
 * these are equivalent:
 *
 * Plotly.moveTraces(gd, [1, 2, 3], [-3, -2, -1])
 * Plotly.moveTraces(gd, [1, 2, 3])
 *
 * @param {Object|HTMLDivElement} gd The graph div
 * @param {Object[]} gd.data The array of traces we're removing from
 * @param {Number|Number[]} currentIndices The locations of traces to be moved
 * @param {Number|Number[]} [newIndices] The locations to move traces to
 *
 * Example calls:
 *
 *      // move trace i to location x
 *      Plotly.moveTraces(gd, i, x)
 *
 *      // move trace i to end of array
 *      Plotly.moveTraces(gd, i)
 *
 *      // move traces i, j, k to end of array (i != j != k)
 *      Plotly.moveTraces(gd, [i, j, k])
 *
 *      // move traces [i, j, k] to [x, y, z] (i != j != k) (x != y != z)
 *      Plotly.moveTraces(gd, [i, j, k], [x, y, z])
 *
 *      // reorder all traces (assume there are 5--a, b, c, d, e)
 *      Plotly.moveTraces(gd, [b, d, e, a, c])  // same as 'move to end'
 */
exports.moveTraces = function moveTraces(gd, currentIndices, newIndices) {
    gd = Lib.getGraphDiv(gd);

    var newData = [];
    var movingTraceMap = [];
    var undoFunc = moveTraces;
    var redoFunc = moveTraces;
    var undoArgs = [gd, newIndices, currentIndices];
    var redoArgs = [gd, currentIndices, newIndices];
    var i;

    // to reduce complexity here, check args elsewhere
    // this throws errors where appropriate
    checkMoveTracesArgs(gd, currentIndices, newIndices);

    // make sure currentIndices is an array
    currentIndices = Array.isArray(currentIndices) ? currentIndices : [currentIndices];

    // if undefined, define newIndices to point to the end of gd.data array
    if(typeof newIndices === 'undefined') {
        newIndices = [];
        for(i = 0; i < currentIndices.length; i++) {
            newIndices.push(-currentIndices.length + i);
        }
    }

    // make sure newIndices is an array if it's user-defined
    newIndices = Array.isArray(newIndices) ? newIndices : [newIndices];

    // convert negative indices to positive indices (they're the same length)
    currentIndices = positivifyIndices(currentIndices, gd.data.length - 1);
    newIndices = positivifyIndices(newIndices, gd.data.length - 1);

    // at this point, we've coerced the index arrays into predictable forms

    // get the traces that aren't being moved around
    for(i = 0; i < gd.data.length; i++) {

        // if index isn't in currentIndices, include it in ignored!
        if(currentIndices.indexOf(i) === -1) {
            newData.push(gd.data[i]);
        }
    }

    // get a mapping of indices to moving traces
    for(i = 0; i < currentIndices.length; i++) {
        movingTraceMap.push({newIndex: newIndices[i], trace: gd.data[currentIndices[i]]});
    }

    // reorder this mapping by newIndex, ascending
    movingTraceMap.sort(function(a, b) {
        return a.newIndex - b.newIndex;
    });

    // now, add the moving traces back in, in order!
    for(i = 0; i < movingTraceMap.length; i += 1) {
        newData.splice(movingTraceMap[i].newIndex, 0, movingTraceMap[i].trace);
    }

    gd.data = newData;

    var promise = exports.redraw(gd);
    Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);

    return promise;
};

/**
 * restyle: update trace attributes of an existing plot
 *
 * Can be called two ways.
 *
 * Signature 1:
 * @param {String | HTMLDivElement} gd
 *  the id or DOM element of the graph container div
 * @param {String} astr
 *  attribute string (like `'marker.symbol'`) to update
 * @param {*} val
 *  value to give this attribute
 * @param {Number[] | Number} [traces]
 *  integer or array of integers for the traces to alter (all if omitted)
 *
 * Signature 2:
 * @param {String | HTMLDivElement} gd
 *  (as in signature 1)
 * @param {Object} aobj
 *  attribute object `{astr1: val1, astr2: val2 ...}`
 *  allows setting multiple attributes simultaneously
 * @param {Number[] | Number} [traces]
 *  (as in signature 1)
 *
 * `val` (or `val1`, `val2` ... in the object form) can be an array,
 * to apply different values to each trace.
 *
 * If the array is too short, it will wrap around (useful for
 * style files that want to specify cyclical default values).
 */
function restyle(gd, astr, val, _traces) {
    gd = Lib.getGraphDiv(gd);
    helpers.clearPromiseQueue(gd);

    var aobj = {};
    if(typeof astr === 'string') aobj[astr] = val;
    else if(Lib.isPlainObject(astr)) {
        // the 3-arg form
        aobj = Lib.extendFlat({}, astr);
        if(_traces === undefined) _traces = val;
    }
    else {
        Lib.warn('Restyle fail.', astr, val, _traces);
        return Promise.reject();
    }

    if(Object.keys(aobj).length) gd.changed = true;

    var traces = helpers.coerceTraceIndices(gd, _traces);

    var specs = _restyle(gd, aobj, traces);
    var flags = specs.flags;

    // clear calcdata and/or axis types if required so they get regenerated
    if(flags.calc) gd.calcdata = undefined;
    if(flags.clearAxisTypes) helpers.clearAxisTypes(gd, traces, {});

    // fill in redraw sequence
    var seq = [];

    if(flags.fullReplot) {
        seq.push(exports.plot);
    } else {
        seq.push(Plots.previousPromises);

        // maybe only call Plots.supplyDataDefaults in the splom case,
        // to skip over long and slow axes defaults
        Plots.supplyDefaults(gd);

        if(flags.markerSize) {
            Plots.doCalcdata(gd);
            addAxRangeSequence(seq);

            // TODO
            // if all axes have autorange:false, then
            // proceed to subroutines.doTraceStyle(),
            // otherwise we must go through addAxRangeSequence,
            // which in general must redraws 'all' axes
        }

        if(flags.style) seq.push(subroutines.doTraceStyle);
        if(flags.colorbars) seq.push(subroutines.doColorBars);

        seq.push(emitAfterPlot);
    }

    seq.push(Plots.rehover);

    Queue.add(gd,
        restyle, [gd, specs.undoit, specs.traces],
        restyle, [gd, specs.redoit, specs.traces]
    );

    var plotDone = Lib.syncOrAsync(seq, gd);
    if(!plotDone || !plotDone.then) plotDone = Promise.resolve();

    return plotDone.then(function() {
        gd.emit('plotly_restyle', specs.eventData);
        return gd;
    });
}
exports.restyle = restyle;

// for undo: undefined initial vals must be turned into nulls
// so that we unset rather than ignore them
function undefinedToNull(val) {
    if(val === undefined) return null;
    return val;
}

/**
 * Factory function to wrap nestedProperty with GUI edits if necessary
 * with GUI edits we add an optional prefix to the nestedProperty constructor
 * to prepend to the attribute string in the preGUI store.
 */
function makeNP(preGUI, guiEditFlag) {
    if(!guiEditFlag) return nestedProperty;

    return function(container, attr, prefix) {
        var np = nestedProperty(container, attr);
        var npSet = np.set;
        np.set = function(val) {
            var fullAttr = (prefix || '') + attr;
            storeCurrent(fullAttr, np.get(), val, preGUI);
            npSet(val);
        };
        return np;
    };
}

function storeCurrent(attr, val, newVal, preGUI) {
    if(Array.isArray(val) || Array.isArray(newVal)) {
        var arrayVal = Array.isArray(val) ? val : [];
        var arrayNew = Array.isArray(newVal) ? newVal : [];
        var maxLen = Math.max(arrayVal.length, arrayNew.length);
        for(var i = 0; i < maxLen; i++) {
            storeCurrent(attr + '[' + i + ']', arrayVal[i], arrayNew[i], preGUI);
        }
    }
    else if(Lib.isPlainObject(val) || Lib.isPlainObject(newVal)) {
        var objVal = Lib.isPlainObject(val) ? val : {};
        var objNew = Lib.isPlainObject(newVal) ? newVal : {};
        var objBoth = Lib.extendFlat({}, objVal, objNew);
        for(var key in objBoth) {
            storeCurrent(attr + '.' + key, objVal[key], objNew[key], preGUI);
        }
    }
    else if(preGUI[attr] === undefined) {
        preGUI[attr] = undefinedToNull(val);
    }
}

/**
 * storeDirectGUIEdit: for routines that skip restyle/relayout and mock it
 * by emitting a plotly_restyle or plotly_relayout event, this routine
 * keeps track of the initial state in _preGUI for use by uirevision
 * Does *not* apply these changes to data/layout - that's the responsibility
 * of the calling routine.
 *
 * @param {object} container: the input attributes container (eg `layout` or a `trace`)
 * @param {object} preGUI: where original values should be stored, either
 *     `layout._preGUI` or `layout._tracePreGUI[uid]`
 * @param {object} edits: the {attr: val} object as normally passed to `relayout` etc
 */
exports._storeDirectGUIEdit = function(container, preGUI, edits) {
    for(var attr in edits) {
        var np = nestedProperty(container, attr);
        storeCurrent(attr, np.get(), edits[attr], preGUI);
    }
};

function _restyle(gd, aobj, traces) {
    var fullLayout = gd._fullLayout;
    var fullData = gd._fullData;
    var data = gd.data;
    var guiEditFlag = fullLayout._guiEditing;
    var layoutNP = makeNP(fullLayout._preGUI, guiEditFlag);
    var eventData = Lib.extendDeepAll({}, aobj);
    var i;

    cleanDeprecatedAttributeKeys(aobj);

    // initialize flags
    var flags = editTypes.traceFlags();

    // copies of the change (and previous values of anything affected)
    // for the undo / redo queue
    var redoit = {};
    var undoit = {};
    var axlist;

    // make a new empty vals array for undoit
    function a0() { return traces.map(function() { return undefined; }); }

    // for autoranging multiple axes
    function addToAxlist(axid) {
        var axName = Axes.id2name(axid);
        if(axlist.indexOf(axName) === -1) axlist.push(axName);
    }

    function autorangeAttr(axName) { return 'LAYOUT' + axName + '.autorange'; }

    function rangeAttr(axName) { return 'LAYOUT' + axName + '.range'; }

    function getFullTrace(traceIndex) {
        // usually fullData maps 1:1 onto data, but with groupby transforms
        // the fullData index can be greater. Take the *first* matching trace.
        for(var j = traceIndex; j < fullData.length; j++) {
            if(fullData[j]._input === data[traceIndex]) return fullData[j];
        }
        // should never get here - and if we *do* it should cause an error
        // later on undefined fullTrace is passed to nestedProperty.
    }

    // for attrs that interact (like scales & autoscales), save the
    // old vals before making the change
    // val=undefined will not set a value, just record what the value was.
    // val=null will delete the attribute
    // attr can be an array to set several at once (all to the same val)
    function doextra(attr, val, i) {
        if(Array.isArray(attr)) {
            attr.forEach(function(a) { doextra(a, val, i); });
            return;
        }
        // quit if explicitly setting this elsewhere
        if(attr in aobj || helpers.hasParent(aobj, attr)) return;

        var extraparam;
        if(attr.substr(0, 6) === 'LAYOUT') {
            extraparam = layoutNP(gd.layout, attr.replace('LAYOUT', ''));
        } else {
            var tracei = traces[i];
            var preGUI = fullLayout._tracePreGUI[getFullTrace(tracei)._fullInput.uid];
            extraparam = makeNP(preGUI, guiEditFlag)(data[tracei], attr);
        }

        if(!(attr in undoit)) {
            undoit[attr] = a0();
        }
        if(undoit[attr][i] === undefined) {
            undoit[attr][i] = undefinedToNull(extraparam.get());
        }
        if(val !== undefined) {
            extraparam.set(val);
        }
    }

    function allBins(binAttr) {
        return function(j) {
            return fullData[j][binAttr];
        };
    }

    function arrayBins(binAttr) {
        return function(vij, j) {
            return vij === false ? fullData[traces[j]][binAttr] : null;
        };
    }

    // now make the changes to gd.data (and occasionally gd.layout)
    // and figure out what kind of graphics update we need to do
    for(var ai in aobj) {
        if(helpers.hasParent(aobj, ai)) {
            throw new Error('cannot set ' + ai + ' and a parent attribute simultaneously');
        }

        var vi = aobj[ai];
        var cont;
        var contFull;
        var param;
        var oldVal;
        var newVal;
        var valObject;

        // Backward compatibility shim for turning histogram autobin on,
        // or freezing previous autobinned values.
        // Replace obsolete `autobin(x|y): true` with `(x|y)bins: null`
        // and `autobin(x|y): false` with the `(x|y)bins` in `fullData`
        if(ai === 'autobinx' || ai === 'autobiny') {
            ai = ai.charAt(ai.length - 1) + 'bins';
            if(Array.isArray(vi)) vi = vi.map(arrayBins(ai));
            else if(vi === false) vi = traces.map(allBins(ai));
            else vi = null;
        }

        redoit[ai] = vi;

        if(ai.substr(0, 6) === 'LAYOUT') {
            param = layoutNP(gd.layout, ai.replace('LAYOUT', ''));
            undoit[ai] = [undefinedToNull(param.get())];
            // since we're allowing val to be an array, allow it here too,
            // even though that's meaningless
            param.set(Array.isArray(vi) ? vi[0] : vi);
            // ironically, the layout attrs in restyle only require replot,
            // not relayout
            flags.calc = true;
            continue;
        }

        // set attribute in gd.data
        undoit[ai] = a0();
        for(i = 0; i < traces.length; i++) {
            cont = data[traces[i]];
            contFull = getFullTrace(traces[i]);
            var preGUI = fullLayout._tracePreGUI[contFull._fullInput.uid];
            param = makeNP(preGUI, guiEditFlag)(cont, ai);
            oldVal = param.get();
            newVal = Array.isArray(vi) ? vi[i % vi.length] : vi;

            if(newVal === undefined) continue;

            var finalPart = param.parts[param.parts.length - 1];
            var prefix = ai.substr(0, ai.length - finalPart.length - 1);
            var prefixDot = prefix ? prefix + '.' : '';
            var innerContFull = prefix ?
                nestedProperty(contFull, prefix).get() : contFull;

            valObject = PlotSchema.getTraceValObject(contFull, param.parts);

            if(valObject && valObject.impliedEdits && newVal !== null) {
                for(var impliedKey in valObject.impliedEdits) {
                    doextra(Lib.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i);
                }
            }

            // changing colorbar size modes,
            // make the resulting size not change
            // note that colorbar fractional sizing is based on the
            // original plot size, before anything (like a colorbar)
            // increases the margins
            else if((finalPart === 'thicknessmode' || finalPart === 'lenmode') &&
                    oldVal !== newVal &&
                    (newVal === 'fraction' || newVal === 'pixels') &&
                    innerContFull
            ) {
                var gs = fullLayout._size;
                var orient = innerContFull.orient;
                var topOrBottom = (orient === 'top') || (orient === 'bottom');
                if(finalPart === 'thicknessmode') {
                    var thicknorm = topOrBottom ? gs.h : gs.w;
                    doextra(prefixDot + 'thickness', innerContFull.thickness *
                        (newVal === 'fraction' ? 1 / thicknorm : thicknorm), i);
                }
                else {
                    var lennorm = topOrBottom ? gs.w : gs.h;
                    doextra(prefixDot + 'len', innerContFull.len *
                        (newVal === 'fraction' ? 1 / lennorm : lennorm), i);
                }
            }

            else if(ai === 'type' && (newVal === 'pie') !== (oldVal === 'pie')) {
                var labelsTo = 'x';
                var valuesTo = 'y';
                if((newVal === 'bar' || oldVal === 'bar') && cont.orientation === 'h') {
                    labelsTo = 'y';
                    valuesTo = 'x';
                }
                Lib.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo);
                Lib.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo);
                Lib.swapAttrs(cont, ['?', '?src'], 'values', valuesTo);

                if(oldVal === 'pie') {
                    nestedProperty(cont, 'marker.color')
                        .set(nestedProperty(cont, 'marker.colors').get());

                    // super kludgy - but if all pies are gone we won't remove them otherwise
                    fullLayout._pielayer.selectAll('g.trace').remove();
                } else if(Registry.traceIs(cont, 'cartesian')) {
                    nestedProperty(cont, 'marker.colors')
                        .set(nestedProperty(cont, 'marker.color').get());
                }
            }

            undoit[ai][i] = undefinedToNull(oldVal);
            // set the new value - if val is an array, it's one el per trace
            // first check for attributes that get more complex alterations
            var swapAttrs = [
                'swapxy', 'swapxyaxes', 'orientation', 'orientationaxes'
            ];
            if(swapAttrs.indexOf(ai) !== -1) {
                // setting an orientation: make sure it's changing
                // before we swap everything else
                if(ai === 'orientation') {
                    param.set(newVal);
                    // obnoxious that we need this level of coupling... but in order to
                    // properly handle setting orientation to `null` we need to mimic
                    // the logic inside Bars.supplyDefaults for default orientation
                    var defaultOrientation = (cont.x && !cont.y) ? 'h' : 'v';
                    if((param.get() || defaultOrientation) === contFull.orientation) {
                        continue;
                    }
                }
                // orientationaxes has no value,
                // it flips everything and the axes
                else if(ai === 'orientationaxes') {
                    cont.orientation =
                        {v: 'h', h: 'v'}[contFull.orientation];
                }
                helpers.swapXYData(cont);
                flags.calc = flags.clearAxisTypes = true;
            }
            else if(Plots.dataArrayContainers.indexOf(param.parts[0]) !== -1) {
                // TODO: use manageArrays.applyContainerArrayChanges here too
                helpers.manageArrayContainers(param, newVal, undoit);
                flags.calc = true;
            }
            else {
                if(valObject) {
                    // must redo calcdata when restyling array values of arrayOk attributes
                    // ... but no need to this for regl-based traces
                    if(valObject.arrayOk &&
                        !Registry.traceIs(contFull, 'regl') &&
                        (Lib.isArrayOrTypedArray(newVal) || Lib.isArrayOrTypedArray(oldVal))
                    ) {
                        flags.calc = true;
                    }
                    else editTypes.update(flags, valObject);
                }
                else {
                    /*
                     * if we couldn't find valObject,  assume a full recalc.
                     * This can happen if you're changing type and making
                     * some other edits too, so the modules we're
                     * looking at don't have these attributes in them.
                     */
                    flags.calc = true;
                }

                // all the other ones, just modify that one attribute
                param.set(newVal);
            }
        }

        // swap the data attributes of the relevant x and y axes?
        if(['swapxyaxes', 'orientationaxes'].indexOf(ai) !== -1) {
            Axes.swap(gd, traces);
        }

        // swap hovermode if set to "compare x/y data"
        if(ai === 'orientationaxes') {
            var hovermode = nestedProperty(gd.layout, 'hovermode');
            if(hovermode.get() === 'x') {
                hovermode.set('y');
            } else if(hovermode.get() === 'y') {
                hovermode.set('x');
            }
        }

        // Major enough changes deserve autoscale and
        // non-reversed axes so people don't get confused
        //
        // Note: autobin (or its new analog bin clearing) is not included here
        // since we're not pushing bins back to gd.data, so if we have bin
        // info it was explicitly provided by the user.
        if(['orientation', 'type'].indexOf(ai) !== -1) {
            axlist = [];
            for(i = 0; i < traces.length; i++) {
                var trace = data[traces[i]];

                if(Registry.traceIs(trace, 'cartesian')) {
                    addToAxlist(trace.xaxis || 'x');
                    addToAxlist(trace.yaxis || 'y');
                }
            }

            doextra(axlist.map(autorangeAttr), true, 0);
            doextra(axlist.map(rangeAttr), [0, 1], 0);
        }
    }

    if(flags.calc || flags.plot) {
        flags.fullReplot = true;
    }

    return {
        flags: flags,
        undoit: undoit,
        redoit: redoit,
        traces: traces,
        eventData: Lib.extendDeepNoArrays([], [eventData, traces])
    };
}

/**
 * Converts deprecated attribute keys to
 * the current API to ensure backwards compatibility.
 *
 * This is needed for the update mechanism to determine which
 * subroutines to run based on the actual attribute
 * definitions (that don't include the deprecated ones).
 *
 * E.g. Maps {'xaxis.title': 'A chart'} to {'xaxis.title.text': 'A chart'}
 * and {titlefont: {...}} to {'title.font': {...}}.
 *
 * @param aobj
 */
function cleanDeprecatedAttributeKeys(aobj) {
    var oldAxisTitleRegex = Lib.counterRegex('axis', '\.title', false, false);
    var colorbarRegex = /colorbar\.title$/;
    var keys = Object.keys(aobj);
    var i, key, value;

    for(i = 0; i < keys.length; i++) {
        key = keys[i];
        value = aobj[key];

        if((key === 'title' || oldAxisTitleRegex.test(key) || colorbarRegex.test(key)) &&
          (typeof value === 'string' || typeof value === 'number')) {
            replace(key, key.replace('title', 'title.text'));
        } else if(key.indexOf('titlefont') > -1) {
            replace(key, key.replace('titlefont', 'title.font'));
        } else if(key.indexOf('titleposition') > -1) {
            replace(key, key.replace('titleposition', 'title.position'));
        } else if(key.indexOf('titleside') > -1) {
            replace(key, key.replace('titleside', 'title.side'));
        } else if(key.indexOf('titleoffset') > -1) {
            replace(key, key.replace('titleoffset', 'title.offset'));
        }
    }

    function replace(oldAttrStr, newAttrStr) {
        aobj[newAttrStr] = aobj[oldAttrStr];
        delete aobj[oldAttrStr];
    }
}

/**
 * relayout: update layout attributes of an existing plot
 *
 * Can be called two ways:
 *
 * Signature 1:
 * @param {String | HTMLDivElement} gd
 *  the id or dom element of the graph container div
 * @param {String} astr
 *  attribute string (like `'xaxis.range[0]'`) to update
 * @param {*} val
 *  value to give this attribute
 *
 * Signature 2:
 * @param {String | HTMLDivElement} gd
 *  (as in signature 1)
 * @param {Object} aobj
 *  attribute object `{astr1: val1, astr2: val2 ...}`
 *  allows setting multiple attributes simultaneously
 */
function relayout(gd, astr, val) {
    gd = Lib.getGraphDiv(gd);
    helpers.clearPromiseQueue(gd);

    if(gd.framework && gd.framework.isPolar) {
        return Promise.resolve(gd);
    }

    var aobj = {};
    if(typeof astr === 'string') {
        aobj[astr] = val;
    } else if(Lib.isPlainObject(astr)) {
        aobj = Lib.extendFlat({}, astr);
    } else {
        Lib.warn('Relayout fail.', astr, val);
        return Promise.reject();
    }

    if(Object.keys(aobj).length) gd.changed = true;

    var specs = _relayout(gd, aobj);
    var flags = specs.flags;

    // clear calcdata if required
    if(flags.calc) gd.calcdata = undefined;

    // fill in redraw sequence

    // even if we don't have anything left in aobj,
    // something may have happened within relayout that we
    // need to wait for
    var seq = [Plots.previousPromises];

    if(flags.layoutReplot) {
        seq.push(subroutines.layoutReplot);
    }
    else if(Object.keys(aobj).length) {
        axRangeSupplyDefaultsByPass(gd, flags, specs) || Plots.supplyDefaults(gd);

        if(flags.legend) seq.push(subroutines.doLegend);
        if(flags.layoutstyle) seq.push(subroutines.layoutStyles);
        if(flags.axrange) addAxRangeSequence(seq, specs.rangesAltered);
        if(flags.ticks) seq.push(subroutines.doTicksRelayout);
        if(flags.modebar) seq.push(subroutines.doModeBar);
        if(flags.camera) seq.push(subroutines.doCamera);

        seq.push(emitAfterPlot);
    }

    seq.push(Plots.rehover);

    Queue.add(gd,
        relayout, [gd, specs.undoit],
        relayout, [gd, specs.redoit]
    );

    var plotDone = Lib.syncOrAsync(seq, gd);
    if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd);

    return plotDone.then(function() {
        gd.emit('plotly_relayout', specs.eventData);
        return gd;
    });
}
exports.relayout = relayout;

// Optimization mostly for large splom traces where
// Plots.supplyDefaults can take > 100ms
function axRangeSupplyDefaultsByPass(gd, flags, specs) {
    var fullLayout = gd._fullLayout;

    if(!flags.axrange) return false;

    for(var k in flags) {
        if(k !== 'axrange' && flags[k]) return false;
    }

    for(var axId in specs.rangesAltered) {
        var axName = Axes.id2name(axId);
        var axIn = gd.layout[axName];
        var axOut = fullLayout[axName];
        axOut.autorange = axIn.autorange;
        axOut.range = axIn.range.slice();
        axOut.cleanRange();

        if(axOut._matchGroup) {
            for(var axId2 in axOut._matchGroup) {
                if(axId2 !== axId) {
                    var ax2 = fullLayout[Axes.id2name(axId2)];
                    ax2.autorange = axOut.autorange;
                    ax2.range = axOut.range.slice();
                    ax2._input.range = axOut.range.slice();
                }
            }
        }
    }

    return true;
}

function addAxRangeSequence(seq, rangesAltered) {
    // N.B. leave as sequence of subroutines (for now) instead of
    // subroutine of its own so that finalDraw always gets
    // executed after drawData
    var drawAxes = rangesAltered ?
        function(gd) {
            var axIds = [];
            var skipTitle = true;

            for(var id in rangesAltered) {
                var ax = Axes.getFromId(gd, id);
                axIds.push(id);

                if(ax._matchGroup) {
                    for(var id2 in ax._matchGroup) {
                        if(!rangesAltered[id2]) {
                            axIds.push(id2);
                        }
                    }
                }

                if(ax.automargin) skipTitle = false;
            }

            return Axes.draw(gd, axIds, {skipTitle: skipTitle});
        } :
        function(gd) {
            return Axes.draw(gd, 'redraw');
        };

    var _clearSelect = function(gd) {
        var zoomlayer = gd._fullLayout._zoomlayer;
        if(zoomlayer) clearSelect(zoomlayer);
    };

    seq.push(
        _clearSelect,
        subroutines.doAutoRangeAndConstraints,
        drawAxes,
        subroutines.drawData,
        subroutines.finalDraw
    );
}

var AX_RANGE_RE = /^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/;
var AX_AUTORANGE_RE = /^[xyz]axis[0-9]*\.autorange$/;
var AX_DOMAIN_RE = /^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/;

function _relayout(gd, aobj) {
    var layout = gd.layout;
    var fullLayout = gd._fullLayout;
    var guiEditFlag = fullLayout._guiEditing;
    var layoutNP = makeNP(fullLayout._preGUI, guiEditFlag);
    var keys = Object.keys(aobj);
    var axes = Axes.list(gd);
    var eventData = Lib.extendDeepAll({}, aobj);
    var arrayEdits = {};

    var arrayStr, i, j;

    cleanDeprecatedAttributeKeys(aobj);
    keys = Object.keys(aobj);

    // look for 'allaxes', split out into all axes
    // in case of 3D the axis are nested within a scene which is held in _id
    for(i = 0; i < keys.length; i++) {
        if(keys[i].indexOf('allaxes') === 0) {
            for(j = 0; j < axes.length; j++) {
                var scene = axes[j]._id.substr(1);
                var axisAttr = (scene.indexOf('scene') !== -1) ? (scene + '.') : '';
                var newkey = keys[i].replace('allaxes', axisAttr + axes[j]._name);

                if(!aobj[newkey]) aobj[newkey] = aobj[keys[i]];
            }

            delete aobj[keys[i]];
        }
    }

    // initialize flags
    var flags = editTypes.layoutFlags();

    // copies of the change (and previous values of anything affected)
    // for the undo / redo queue
    var redoit = {};
    var undoit = {};

    // for attrs that interact (like scales & autoscales), save the
    // old vals before making the change
    // val=undefined will not set a value, just record what the value was.
    // attr can be an array to set several at once (all to the same val)
    function doextra(attr, val) {
        if(Array.isArray(attr)) {
            attr.forEach(function(a) { doextra(a, val); });
            return;
        }

        // if we have another value for this attribute (explicitly or
        // via a parent) do not override with this auto-generated extra
        if(attr in aobj || helpers.hasParent(aobj, attr)) return;

        var p = layoutNP(layout, attr);
        if(!(attr in undoit)) {
            undoit[attr] = undefinedToNull(p.get());
        }
        if(val !== undefined) p.set(val);
    }

    // for constraint enforcement: keep track of all axes (as {id: name})
    // we're editing the (auto)range of, so we can tell the others constrained
    // to scale with them that it's OK for them to shrink
    var rangesAltered = {};
    var axId;

    function recordAlteredAxis(pleafPlus) {
        var axId = Axes.name2id(pleafPlus.split('.')[0]);
        rangesAltered[axId] = 1;
        return axId;
    }

    // alter gd.layout
    for(var ai in aobj) {
        if(helpers.hasParent(aobj, ai)) {
            throw new Error('cannot set ' + ai + ' and a parent attribute simultaneously');
        }

        var p = layoutNP(layout, ai);
        var vi = aobj[ai];
        var plen = p.parts.length;
        // p.parts may end with an index integer if the property is an array
        var pend = plen - 1;
        while(pend > 0 && typeof p.parts[pend] !== 'string') pend--;
        // last property in chain (leaf node)
        var pleaf = p.parts[pend];
        // leaf plus immediate parent
        var pleafPlus = p.parts[pend - 1] + '.' + pleaf;
        // trunk nodes (everything except the leaf)
        var ptrunk = p.parts.slice(0, pend).join('.');
        var parentIn = nestedProperty(gd.layout, ptrunk).get();
        var parentFull = nestedProperty(fullLayout, ptrunk).get();
        var vOld = p.get();

        if(vi === undefined) continue;

        redoit[ai] = vi;

        // axis reverse is special - it is its own inverse
        // op and has no flag.
        undoit[ai] = (pleaf === 'reverse') ? vi : undefinedToNull(vOld);

        var valObject = PlotSchema.getLayoutValObject(fullLayout, p.parts);

        if(valObject && valObject.impliedEdits && vi !== null) {
            for(var impliedKey in valObject.impliedEdits) {
                doextra(Lib.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]);
            }
        }

        // Setting width or height to null must reset the graph's width / height
        // back to its initial value as computed during the first pass in Plots.plotAutoSize.
        //
        // To do so, we must manually set them back here using the _initialAutoSize cache.
        // can't use impliedEdits for this because behavior depends on vi
        if(['width', 'height'].indexOf(ai) !== -1) {
            if(vi) {
                doextra('autosize', null);
                // currently we don't support autosize one dim only - so
                // explicitly set the other one. Note that doextra will
                // ignore this if the same relayout call also provides oppositeAttr
                var oppositeAttr = ai === 'height' ? 'width' : 'height';
                doextra(oppositeAttr, fullLayout[oppositeAttr]);
            }
            else {
                fullLayout[ai] = gd._initialAutoSize[ai];
            }
        }
        else if(ai === 'autosize') {
            // depends on vi here too, so again can't use impliedEdits
            doextra('width', vi ? null : fullLayout.width);
            doextra('height', vi ? null : fullLayout.height);
        }
        // check autorange vs range
        else if(pleafPlus.match(AX_RANGE_RE)) {
            recordAlteredAxis(pleafPlus);
            nestedProperty(fullLayout, ptrunk + '._inputRange').set(null);
        }
        else if(pleafPlus.match(AX_AUTORANGE_RE)) {
            recordAlteredAxis(pleafPlus);
            nestedProperty(fullLayout, ptrunk + '._inputRange').set(null);
            var axFull = nestedProperty(fullLayout, ptrunk).get();
            if(axFull._inputDomain) {
                // if we're autoranging and this axis has a constrained domain,
                // reset it so we don't get locked into a shrunken size
                axFull._input.domain = axFull._inputDomain.slice();
            }
        }
        else if(pleafPlus.match(AX_DOMAIN_RE)) {
            nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null);
        }

        // toggling axis type between log and linear: we need to convert
        // positions for components that are still using linearized values,
        // not data values like newer components.
        // previously we did this for log <-> not-log, but now only do it
        // for log <-> linear
        if(pleaf === 'type') {
            var ax = parentIn;
            var toLog = parentFull.type === 'linear' && vi === 'log';
            var fromLog = parentFull.type === 'log' && vi === 'linear';

            if(toLog || fromLog) {
                if(!ax || !ax.range) {
                    // 2D never gets here, but 3D does
                    // I don't think this is needed, but left here in case there
                    // are edge cases I'm not thinking of.
                    doextra(ptrunk + '.autorange', true);
                }
                else if(!parentFull.autorange) {
                    // toggling log without autorange: need to also recalculate ranges
                    // because log axes use linearized values for range endpoints
                    var r0 = ax.range[0];
                    var r1 = ax.range[1];
                    if(toLog) {
                        // if both limits are negative, autorange
                        if(r0 <= 0 && r1 <= 0) {
                            doextra(ptrunk + '.autorange', true);
                        }
                        // if one is negative, set it 6 orders below the other.
                        if(r0 <= 0) r0 = r1 / 1e6;
                        else if(r1 <= 0) r1 = r0 / 1e6;
                        // now set the range values as appropriate
                        doextra(ptrunk + '.range[0]', Math.log(r0) / Math.LN10);
                        doextra(ptrunk + '.range[1]', Math.log(r1) / Math.LN10);
                    }
                    else {
                        doextra(ptrunk + '.range[0]', Math.pow(10, r0));
                        doextra(ptrunk + '.range[1]', Math.pow(10, r1));
                    }
                }
                else if(toLog) {
                    // just make sure the range is positive and in the right
                    // order, it'll get recalculated later
                    ax.range = (ax.range[1] > ax.range[0]) ? [1, 2] : [2, 1];
                }

                // clear polar view initial stash for radial range so that
                // value get recomputed in correct units
                if(Array.isArray(fullLayout._subplots.polar) &&
                    fullLayout._subplots.polar.length &&
                    fullLayout[p.parts[0]] &&
                    p.parts[1] === 'radialaxis'
                ) {
                    delete fullLayout[p.parts[0]]._subplot.viewInitial['radialaxis.range'];
                }

                // Annotations and images also need to convert to/from linearized coords
                // Shapes do not need this :)
                Registry.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra);
                Registry.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra);
            }
            else {
                // any other type changes: the range from the previous type
                // will not make sense, so autorange it.
                doextra(ptrunk + '.autorange', true);
                doextra(ptrunk + '.range', null);
            }
            nestedProperty(fullLayout, ptrunk + '._inputRange').set(null);
        }
        else if(pleaf.match(AX_NAME_PATTERN)) {
            var fullProp = nestedProperty(fullLayout, ai).get();
            var newType = (vi || {}).type;

            // This can potentially cause strange behavior if the autotype is not
            // numeric (linear, because we don't auto-log) but the previous type
            // was log. That's a very strange edge case though
            if(!newType || newType === '-') newType = 'linear';
            Registry.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra);
            Registry.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra);
        }

        // alter gd.layout

        // collect array component edits for execution all together
        // so we can ensure consistent behavior adding/removing items
        // and order-independence for add/remove/edit all together in
        // one relayout call
        var containerArrayMatch = manageArrays.containerArrayMatch(ai);
        if(containerArrayMatch) {
            arrayStr = containerArrayMatch.array;
            i = containerArrayMatch.index;
            var propStr = containerArrayMatch.property;
            var updateValObject = valObject || {editType: 'calc'};

            if(i !== '' && propStr === '') {
                // special handling of undoit if we're adding or removing an element
                // ie 'annotations[2]' which can be {...} (add) or null,
                // does not work when replacing the entire array
                if(manageArrays.isAddVal(vi)) {
                    undoit[ai] = null;
                } else if(manageArrays.isRemoveVal(vi)) {
                    undoit[ai] = (nestedProperty(layout, arrayStr).get() || [])[i];
                } else {
                    Lib.warn('unrecognized full object value', aobj);
                }
            }
            editTypes.update(flags, updateValObject);

            // prepare the edits object we'll send to applyContainerArrayChanges
            if(!arrayEdits[arrayStr]) arrayEdits[arrayStr] = {};
            var objEdits = arrayEdits[arrayStr][i];
            if(!objEdits) objEdits = arrayEdits[arrayStr][i] = {};
            objEdits[propStr] = vi;

            delete aobj[ai];
        }
        // handle axis reversal explicitly, as there's no 'reverse' attribute
        else if(pleaf === 'reverse') {
            if(parentIn.range) parentIn.range.reverse();
            else {
                doextra(ptrunk + '.autorange', true);
                parentIn.range = [1, 0];
            }

            if(parentFull.autorange) flags.calc = true;
            else flags.plot = true;
        }
        else {
            if((fullLayout._has('scatter-like') && fullLayout._has('regl')) &&
                (ai === 'dragmode' &&
                (vi === 'lasso' || vi === 'select') &&
                !(vOld === 'lasso' || vOld === 'select'))
            ) {
                flags.plot = true;
            }
            else if(fullLayout._has('gl2d')) {
                flags.plot = true;
            }
            else if(valObject) editTypes.update(flags, valObject);
            else flags.calc = true;

            p.set(vi);
        }
    }

    // now we've collected component edits - execute them all together
    for(arrayStr in arrayEdits) {
        var finished = manageArrays.applyContainerArrayChanges(gd,
            layoutNP(layout, arrayStr), arrayEdits[arrayStr], flags, layoutNP);
        if(!finished) flags.plot = true;
    }

    // figure out if we need to recalculate axis constraints
    var constraints = fullLayout._axisConstraintGroups || [];
    for(axId in rangesAltered) {
        for(i = 0; i < constraints.length; i++) {
            var group = constraints[i];
            if(group[axId]) {
                // Always recalc if we're changing constrained ranges.
                // Otherwise it's possible to violate the constraints by
                // specifying arbitrary ranges for all axes in the group.
                // this way some ranges may expand beyond what's specified,
                // as they do at first draw, to satisfy the constraints.
                flags.calc = true;
                for(var groupAxId in group) {
                    if(!rangesAltered[groupAxId]) {
                        Axes.getFromId(gd, groupAxId)._constraintShrinkable = true;
                    }
                }
            }
        }
    }

    // If the autosize changed or height or width was explicitly specified,
    // this triggers a redraw
    // TODO: do we really need special aobj.height/width handling here?
    // couldn't editType do this?
    if(updateAutosize(gd) || aobj.height || aobj.width) flags.plot = true;

    if(flags.plot || flags.calc) {
        flags.layoutReplot = true;
    }

    // now all attribute mods are done, as are
    // redo and undo so we can save them

    return {
        flags: flags,
        rangesAltered: rangesAltered,
        undoit: undoit,
        redoit: redoit,
        eventData: eventData
    };
}

/*
 * updateAutosize: we made a change, does it change the autosize result?
 * puts the new size into fullLayout
 * returns true if either height or width changed
 */
function updateAutosize(gd) {
    var fullLayout = gd._fullLayout;
    var oldWidth = fullLayout.width;
    var oldHeight = fullLayout.height;

    // calculate autosizing
    if(gd.layout.autosize) Plots.plotAutoSize(gd, gd.layout, fullLayout);

    return (fullLayout.width !== oldWidth) || (fullLayout.height !== oldHeight);
}

/**
 * update: update trace and layout attributes of an existing plot
 *
 * @param {String | HTMLDivElement} gd
 *  the id or DOM element of the graph container div
 * @param {Object} traceUpdate
 *  attribute object `{astr1: val1, astr2: val2 ...}`
 *  corresponding to updates in the plot's traces
 * @param {Object} layoutUpdate
 *  attribute object `{astr1: val1, astr2: val2 ...}`
 *  corresponding to updates in the plot's layout
 * @param {Number[] | Number} [traces]
 *  integer or array of integers for the traces to alter (all if omitted)
 *
 */
function update(gd, traceUpdate, layoutUpdate, _traces) {
    gd = Lib.getGraphDiv(gd);
    helpers.clearPromiseQueue(gd);

    if(gd.framework && gd.framework.isPolar) {
        return Promise.resolve(gd);
    }

    if(!Lib.isPlainObject(traceUpdate)) traceUpdate = {};
    if(!Lib.isPlainObject(layoutUpdate)) layoutUpdate = {};

    if(Object.keys(traceUpdate).length) gd.changed = true;
    if(Object.keys(layoutUpdate).length) gd.changed = true;

    var traces = helpers.coerceTraceIndices(gd, _traces);

    var restyleSpecs = _restyle(gd, Lib.extendFlat({}, traceUpdate), traces);
    var restyleFlags = restyleSpecs.flags;

    var relayoutSpecs = _relayout(gd, Lib.extendFlat({}, layoutUpdate));
    var relayoutFlags = relayoutSpecs.flags;

    // clear calcdata and/or axis types if required
    if(restyleFlags.calc || relayoutFlags.calc) gd.calcdata = undefined;
    if(restyleFlags.clearAxisTypes) helpers.clearAxisTypes(gd, traces, layoutUpdate);

    // fill in redraw sequence
    var seq = [];

    if(restyleFlags.fullReplot && relayoutFlags.layoutReplot) {
        var data = gd.data;
        var layout = gd.layout;

        // clear existing data/layout on gd
        // so that Plotly.plot doesn't try to extend them
        gd.data = undefined;
        gd.layout = undefined;

        seq.push(function() { return exports.plot(gd, data, layout); });
    }
    else if(restyleFlags.fullReplot) {
        seq.push(exports.plot);
    }
    else if(relayoutFlags.layoutReplot) {
        seq.push(subroutines.layoutReplot);
    }
    else {
        seq.push(Plots.previousPromises);
        axRangeSupplyDefaultsByPass(gd, relayoutFlags, relayoutSpecs) || Plots.supplyDefaults(gd);

        if(restyleFlags.style) seq.push(subroutines.doTraceStyle);
        if(restyleFlags.colorbars) seq.push(subroutines.doColorBars);
        if(relayoutFlags.legend) seq.push(subroutines.doLegend);
        if(relayoutFlags.layoutstyle) seq.push(subroutines.layoutStyles);
        if(relayoutFlags.axrange) addAxRangeSequence(seq, relayoutSpecs.rangesAltered);
        if(relayoutFlags.ticks) seq.push(subroutines.doTicksRelayout);
        if(relayoutFlags.modebar) seq.push(subroutines.doModeBar);
        if(relayoutFlags.camera) seq.push(subroutines.doCamera);

        seq.push(emitAfterPlot);
    }

    seq.push(Plots.rehover);

    Queue.add(gd,
        update, [gd, restyleSpecs.undoit, relayoutSpecs.undoit, restyleSpecs.traces],
        update, [gd, restyleSpecs.redoit, relayoutSpecs.redoit, restyleSpecs.traces]
    );

    var plotDone = Lib.syncOrAsync(seq, gd);
    if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd);

    return plotDone.then(function() {
        gd.emit('plotly_update', {
            data: restyleSpecs.eventData,
            layout: relayoutSpecs.eventData
        });

        return gd;
    });
}
exports.update = update;

/*
 * internal-use-only restyle/relayout/update variants that record the initial
 * values in (fullLayout|fullTrace)._preGUI so changes can be persisted across
 * Plotly.react data updates, dependent on uirevision attributes
 */
function guiEdit(func) {
    return function wrappedEdit(gd) {
        gd._fullLayout._guiEditing = true;
        var p = func.apply(null, arguments);
        gd._fullLayout._guiEditing = false;
        return p;
    };
}
exports._guiRestyle = guiEdit(restyle);
exports._guiRelayout = guiEdit(relayout);
exports._guiUpdate = guiEdit(update);

// For connecting edited layout attributes to uirevision attrs
// If no `attr` we use `match[1] + '.uirevision'`
// Ordered by most common edits first, to minimize our search time
var layoutUIControlPatterns = [
    {pattern: /^hiddenlabels/, attr: 'legend.uirevision'},
    {pattern: /^((x|y)axis\d*)\.((auto)?range|title\.text)/},

    // showspikes and modes include those nested inside scenes
    {pattern: /axis\d*\.showspikes$/, attr: 'modebar.uirevision'},
    {pattern: /(hover|drag)mode$/, attr: 'modebar.uirevision'},

    {pattern: /^(scene\d*)\.camera/},
    {pattern: /^(geo\d*)\.(projection|center)/},
    {pattern: /^(ternary\d*\.[abc]axis)\.(min|title\.text)$/},
    {pattern: /^(polar\d*\.radialaxis)\.((auto)?range|angle|title\.text)/},
    {pattern: /^(polar\d*\.angularaxis)\.rotation/},
    {pattern: /^(mapbox\d*)\.(center|zoom|bearing|pitch)/},

    {pattern: /^legend\.(x|y)$/, attr: 'editrevision'},
    {pattern: /^(shapes|annotations)/, attr: 'editrevision'},
    {pattern: /^title\.text$/, attr: 'editrevision'}
];

// same for trace attributes: if `attr` is given it's in layout,
// or with no `attr` we use `trace.uirevision`
var traceUIControlPatterns = [
    {pattern: /^selectedpoints$/, attr: 'selectionrevision'},
    // "visible" includes trace.transforms[i].styles[j].value.visible
    {pattern: /(^|value\.)visible$/, attr: 'legend.uirevision'},
    {pattern: /^dimensions\[\d+\]\.constraintrange/},

    // below this you must be in editable: true mode
    // TODO: I still put name and title with `trace.uirevision`
    // reasonable or should these be `editrevision`?
    // Also applies to axis titles up in the layout section

    // "name" also includes transform.styles
    {pattern: /(^|value\.)name$/},
    // including nested colorbar attributes (ie marker.colorbar)
    {pattern: /colorbar\.title\.text$/},
    {pattern: /colorbar\.(x|y)$/, attr: 'editrevision'}
];

function findUIPattern(key, patternSpecs) {
    for(var i = 0; i < patternSpecs.length; i++) {
        var spec = patternSpecs[i];
        var match = key.match(spec.pattern);
        if(match) {
            return {head: match[1], attr: spec.attr};
        }
    }
}

// We're finding the new uirevision before supplyDefaults, so do the
// inheritance manually. Note that only `undefined` inherits - other
// falsy values are returned.
function getNewRev(revAttr, container) {
    var newRev = nestedProperty(container, revAttr).get();
    if(newRev !== undefined) return newRev;

    var parts = revAttr.split('.');
    parts.pop();
    while(parts.length > 1) {
        parts.pop();
        newRev = nestedProperty(container, parts.join('.') + '.uirevision').get();
        if(newRev !== undefined) return newRev;
    }

    return container.uirevision;
}

function getFullTraceIndexFromUid(uid, fullData) {
    for(var i = 0; i < fullData.length; i++) {
        if(fullData[i]._fullInput.uid === uid) return i;
    }
    return -1;
}

function getTraceIndexFromUid(uid, data, tracei) {
    for(var i = 0; i < data.length; i++) {
        if(data[i].uid === uid) return i;
    }
    // fall back on trace order, but only if user didn't provide a uid for that trace
    return (!data[tracei] || data[tracei].uid) ? -1 : tracei;
}

function valsMatch(v1, v2) {
    var v1IsObj = Lib.isPlainObject(v1);
    var v1IsArray = Array.isArray(v1);
    if(v1IsObj || v1IsArray) {
        return (
            (v1IsObj && Lib.isPlainObject(v2)) ||
            (v1IsArray && Array.isArray(v2))
        ) && JSON.stringify(v1) === JSON.stringify(v2);
    }
    return v1 === v2;
}

function applyUIRevisions(data, layout, oldFullData, oldFullLayout) {
    var layoutPreGUI = oldFullLayout._preGUI;
    var key, revAttr, oldRev, newRev, match, preGUIVal, newNP, newVal;
    var bothInheritAutorange = [];
    var newRangeAccepted = {};
    for(key in layoutPreGUI) {
        match = findUIPattern(key, layoutUIControlPatterns);
        if(match) {
            revAttr = match.attr || (match.head + '.uirevision');
            oldRev = nestedProperty(oldFullLayout, revAttr).get();
            newRev = oldRev && getNewRev(revAttr, layout);
            if(newRev && (newRev === oldRev)) {
                preGUIVal = layoutPreGUI[key];
                if(preGUIVal === null) preGUIVal = undefined;
                newNP = nestedProperty(layout, key);
                newVal = newNP.get();
                if(valsMatch(newVal, preGUIVal)) {
                    if(newVal === undefined && key.substr(key.length - 9) === 'autorange') {
                        bothInheritAutorange.push(key.substr(0, key.length - 10));
                    }
                    newNP.set(undefinedToNull(nestedProperty(oldFullLayout, key).get()));
                    continue;
                }
            }
        }
        else {
            Lib.warn('unrecognized GUI edit: ' + key);
        }
        // if we got this far, the new value was accepted as the new starting
        // point (either because it changed or revision changed)
        // so remove it from _preGUI for next time.
        delete layoutPreGUI[key];

        if(key.substr(key.length - 8, 6) === 'range[') {
            newRangeAccepted[key.substr(0, key.length - 9)] = 1;
        }
    }

    // Special logic for `autorange`, since it interacts with `range`:
    // If the new figure's matching `range` was kept, and `autorange`
    // wasn't supplied explicitly in either the original or the new figure,
    // we shouldn't alter that - but we may just have done that, so fix it.
    for(var i = 0; i < bothInheritAutorange.length; i++) {
        var axAttr = bothInheritAutorange[i];
        if(newRangeAccepted[axAttr]) {
            var newAx = nestedProperty(layout, axAttr).get();
            if(newAx) delete newAx.autorange;
        }
    }

    // Now traces - try to match them up by uid (in case we added/deleted in
    // the middle), then fall back on index.
    var allTracePreGUI = oldFullLayout._tracePreGUI;
    for(var uid in allTracePreGUI) {
        var tracePreGUI = allTracePreGUI[uid];
        var newTrace = null;
        var fullInput;
        for(key in tracePreGUI) {
            // wait until we know we have preGUI values to look for traces
            // but if we don't find both, stop looking at this uid
            if(!newTrace) {
                var fulli = getFullTraceIndexFromUid(uid, oldFullData);
                if(fulli < 0) {
                    // Somehow we didn't even have this trace in oldFullData...
                    // I guess this could happen with `deleteTraces` or something
                    delete allTracePreGUI[uid];
                    break;
                }
                var fullTrace = oldFullData[fulli];
                fullInput = fullTrace._fullInput;

                var newTracei = getTraceIndexFromUid(uid, data, fullInput.index);
                if(newTracei < 0) {
                    // No match in new data
                    delete allTracePreGUI[uid];
                    break;
                }
                newTrace = data[newTracei];
            }

            match = findUIPattern(key, traceUIControlPatterns);
            if(match) {
                if(match.attr) {
                    oldRev = nestedProperty(oldFullLayout, match.attr).get();
                    newRev = oldRev && getNewRev(match.attr, layout);
                }
                else {
                    oldRev = fullInput.uirevision;
                    // inheritance for trace.uirevision is simple, just layout.uirevision
                    newRev = newTrace.uirevision;
                    if(newRev === undefined) newRev = layout.uirevision;
                }

                if(newRev && newRev === oldRev) {
                    preGUIVal = tracePreGUI[key];
                    if(preGUIVal === null) preGUIVal = undefined;
                    newNP = nestedProperty(newTrace, key);
                    newVal = newNP.get();
                    if(valsMatch(newVal, preGUIVal)) {
                        newNP.set(undefinedToNull(nestedProperty(fullInput, key).get()));
                        continue;
                    }
                }
            }
            else {
                Lib.warn('unrecognized GUI edit: ' + key + ' in trace uid ' + uid);
            }
            delete tracePreGUI[key];
        }
    }
}

/**
 * Plotly.react:
 * A plot/update method that takes the full plot state (same API as plot/newPlot)
 * and diffs to determine the minimal update pathway
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 * @param {array of objects} data
 *      array of traces, containing the data and display information for each trace
 * @param {object} layout
 *      object describing the overall display of the plot,
 *      all the stuff that doesn't pertain to any individual trace
 * @param {object} config
 *      configuration options (see ./plot_config.js for more info)
 *
 * OR
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 * @param {object} figure
 *      object containing `data`, `layout`, `config`, and `frames` members
 *
 */
exports.react = function(gd, data, layout, config) {
    var frames, plotDone;

    function addFrames() { return exports.addFrames(gd, frames); }

    gd = Lib.getGraphDiv(gd);

    var oldFullData = gd._fullData;
    var oldFullLayout = gd._fullLayout;

    // you can use this as the initial draw as well as to update
    if(!Lib.isPlotDiv(gd) || !oldFullData || !oldFullLayout) {
        plotDone = exports.newPlot(gd, data, layout, config);
    }
    else {

        if(Lib.isPlainObject(data)) {
            var obj = data;
            data = obj.data;
            layout = obj.layout;
            config = obj.config;
            frames = obj.frames;
        }

        var configChanged = false;
        // assume that if there's a config at all, we're reacting to it too,
        // and completely replace the previous config
        if(config) {
            var oldConfig = Lib.extendDeep({}, gd._context);
            gd._context = undefined;
            setPlotContext(gd, config);
            configChanged = diffConfig(oldConfig, gd._context);
        }

        gd.data = data || [];
        helpers.cleanData(gd.data);
        gd.layout = layout || {};
        helpers.cleanLayout(gd.layout);

        applyUIRevisions(gd.data, gd.layout, oldFullData, oldFullLayout);

        // "true" skips updating calcdata and remapping arrays from calcTransforms,
        // which supplyDefaults usually does at the end, but we may need to NOT do
        // if the diff (which we haven't determined yet) says we'll recalc
        Plots.supplyDefaults(gd, {skipUpdateCalc: true});

        var newFullData = gd._fullData;
        var newFullLayout = gd._fullLayout;
        var immutable = newFullLayout.datarevision === undefined;
        var transition = newFullLayout.transition;

        var relayoutFlags = diffLayout(gd, oldFullLayout, newFullLayout, immutable, transition);
        var newDataRevision = relayoutFlags.newDataRevision;
        var restyleFlags = diffData(gd, oldFullData, newFullData, immutable, transition, newDataRevision);

        // TODO: how to translate this part of relayout to Plotly.react?
        // // Setting width or height to null must reset the graph's width / height
        // // back to its initial value as computed during the first pass in Plots.plotAutoSize.
        // //
        // // To do so, we must manually set them back here using the _initialAutoSize cache.
        // if(['width', 'height'].indexOf(ai) !== -1 && vi === null) {
        //     fullLayout[ai] = gd._initialAutoSize[ai];
        // }

        if(updateAutosize(gd)) relayoutFlags.layoutReplot = true;

        // clear calcdata if required
        if(restyleFlags.calc || relayoutFlags.calc) gd.calcdata = undefined;
        // otherwise do the calcdata updates and calcTransform array remaps that we skipped earlier
        else Plots.supplyDefaultsUpdateCalc(gd.calcdata, newFullData);

        // Note: what restyle/relayout use impliedEdits and clearAxisTypes for
        // must be handled by the user when using Plotly.react.

        // fill in redraw sequence
        var seq = [];

        if(frames) {
            gd._transitionData = {};
            Plots.createTransitionData(gd);
            seq.push(addFrames);
        }

        // Transition pathway,
        // only used when 'transition' is set by user and
        // when at least one animatable attribute has changed,
        // N.B. config changed aren't animatable
        if(newFullLayout.transition && !configChanged && (restyleFlags.anim || relayoutFlags.anim)) {
            Plots.doCalcdata(gd);
            subroutines.doAutoRangeAndConstraints(gd);

            seq.push(function() {
                return Plots.transitionFromReact(gd, restyleFlags, relayoutFlags, oldFullLayout);
            });
        }
        else if(restyleFlags.fullReplot || relayoutFlags.layoutReplot || configChanged) {
            gd._fullLayout._skipDefaults = true;
            seq.push(exports.plot);
        }
        else {
            for(var componentType in relayoutFlags.arrays) {
                var indices = relayoutFlags.arrays[componentType];
                if(indices.length) {
                    var drawOne = Registry.getComponentMethod(componentType, 'drawOne');
                    if(drawOne !== Lib.noop) {
                        for(var i = 0; i < indices.length; i++) {
                            drawOne(gd, indices[i]);
                        }
                    }
                    else {
                        var draw = Registry.getComponentMethod(componentType, 'draw');
                        if(draw === Lib.noop) {
                            throw new Error('cannot draw components: ' + componentType);
                        }
                        draw(gd);
                    }
                }
            }

            seq.push(Plots.previousPromises);
            if(restyleFlags.style) seq.push(subroutines.doTraceStyle);
            if(restyleFlags.colorbars) seq.push(subroutines.doColorBars);
            if(relayoutFlags.legend) seq.push(subroutines.doLegend);
            if(relayoutFlags.layoutstyle) seq.push(subroutines.layoutStyles);
            if(relayoutFlags.axrange) addAxRangeSequence(seq);
            if(relayoutFlags.ticks) seq.push(subroutines.doTicksRelayout);
            if(relayoutFlags.modebar) seq.push(subroutines.doModeBar);
            if(relayoutFlags.camera) seq.push(subroutines.doCamera);
            seq.push(emitAfterPlot);
        }

        seq.push(Plots.rehover);

        plotDone = Lib.syncOrAsync(seq, gd);
        if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd);
    }

    return plotDone.then(function() {
        gd.emit('plotly_react', {
            data: data,
            layout: layout
        });

        return gd;
    });

};

function diffData(gd, oldFullData, newFullData, immutable, transition, newDataRevision) {
    var sameTraceLength = oldFullData.length === newFullData.length;

    if(!transition && !sameTraceLength) {
        return {
            fullReplot: true,
            calc: true
        };
    }

    var flags = editTypes.traceFlags();
    flags.arrays = {};
    flags.nChanges = 0;
    flags.nChangesAnim = 0;

    var i, trace;

    function getTraceValObject(parts) {
        return PlotSchema.getTraceValObject(trace, parts);
    }

    var diffOpts = {
        getValObject: getTraceValObject,
        flags: flags,
        immutable: immutable,
        transition: transition,
        newDataRevision: newDataRevision,
        gd: gd
    };

    var seenUIDs = {};

    for(i = 0; i < oldFullData.length; i++) {
        if(newFullData[i]) {
            trace = newFullData[i]._fullInput;
            if(Plots.hasMakesDataTransform(trace)) trace = newFullData[i];
            if(seenUIDs[trace.uid]) continue;
            seenUIDs[trace.uid] = 1;

            getDiffFlags(oldFullData[i]._fullInput, trace, [], diffOpts);
        }
    }

    if(flags.calc || flags.plot) {
        flags.fullReplot = true;
    }

    if(transition && flags.nChanges && flags.nChangesAnim) {
        flags.anim = (flags.nChanges === flags.nChangesAnim) && sameTraceLength ? 'all' : 'some';
    }

    return flags;
}

function diffLayout(gd, oldFullLayout, newFullLayout, immutable, transition) {
    var flags = editTypes.layoutFlags();
    flags.arrays = {};
    flags.rangesAltered = {};
    flags.nChanges = 0;
    flags.nChangesAnim = 0;

    function getLayoutValObject(parts) {
        return PlotSchema.getLayoutValObject(newFullLayout, parts);
    }

    var diffOpts = {
        getValObject: getLayoutValObject,
        flags: flags,
        immutable: immutable,
        transition: transition,
        gd: gd
    };

    getDiffFlags(oldFullLayout, newFullLayout, [], diffOpts);

    if(flags.plot || flags.calc) {
        flags.layoutReplot = true;
    }

    if(transition && flags.nChanges && flags.nChangesAnim) {
        flags.anim = flags.nChanges === flags.nChangesAnim ? 'all' : 'some';
    }

    return flags;
}

function getDiffFlags(oldContainer, newContainer, outerparts, opts) {
    var valObject, key, astr;

    var getValObject = opts.getValObject;
    var flags = opts.flags;
    var immutable = opts.immutable;
    var inArray = opts.inArray;
    var arrayIndex = opts.arrayIndex;

    function changed() {
        var editType = valObject.editType;
        if(inArray && editType.indexOf('arraydraw') !== -1) {
            Lib.pushUnique(flags.arrays[inArray], arrayIndex);
            return;
        }
        editTypes.update(flags, valObject);

        if(editType !== 'none') {
            flags.nChanges++;
        }

        // track animatable changes
        if(opts.transition && valObject.anim) {
            flags.nChangesAnim++;
        }

        // track cartesian axes with altered ranges
        if(AX_RANGE_RE.test(astr) || AX_AUTORANGE_RE.test(astr)) {
            flags.rangesAltered[outerparts[0]] = 1;
        }

        // clear _inputDomain on cartesian axes with altered domains
        if(AX_DOMAIN_RE.test(astr)) {
            nestedProperty(newContainer, '_inputDomain').set(null);
        }

        // track datarevision changes
        if(key === 'datarevision') {
            flags.newDataRevision = 1;
        }
    }

    function valObjectCanBeDataArray(valObject) {
        return valObject.valType === 'data_array' || valObject.arrayOk;
    }

    for(key in oldContainer) {
        // short-circuit based on previous calls or previous keys that already maximized the pathway
        if(flags.calc && !opts.transition) return;

        var oldVal = oldContainer[key];
        var newVal = newContainer[key];
        var parts = outerparts.concat(key);
        astr = parts.join('.');

        if(key.charAt(0) === '_' || typeof oldVal === 'function' || oldVal === newVal) continue;

        // FIXME: ax.tick0 and dtick get filled in during plotting (except for geo subplots),
        // and unlike other auto values they don't make it back into the input,
        // so newContainer won't have them.
        if((key === 'tick0' || key === 'dtick') && outerparts[0] !== 'geo') {
            var tickMode = newContainer.tickmode;
            if(tickMode === 'auto' || tickMode === 'array' || !tickMode) continue;
        }
        // FIXME: Similarly for axis ranges for 3D
        // contourcarpet doesn't HAVE zmin/zmax, they're just auto-added. It needs them.
        if(key === 'range' && newContainer.autorange) continue;
        if((key === 'zmin' || key === 'zmax') && newContainer.type === 'contourcarpet') continue;

        valObject = getValObject(parts);

        // in case type changed, we may not even *have* a valObject.
        if(!valObject) continue;

        if(valObject._compareAsJSON && JSON.stringify(oldVal) === JSON.stringify(newVal)) continue;

        var valType = valObject.valType;
        var i;

        var canBeDataArray = valObjectCanBeDataArray(valObject);
        var wasArray = Array.isArray(oldVal);
        var nowArray = Array.isArray(newVal);

        // hack for traces that modify the data in supplyDefaults, like
        // converting 1D to 2D arrays, which will always create new objects
        if(wasArray && nowArray) {
            var inputKey = '_input_' + key;
            var oldValIn = oldContainer[inputKey];
            var newValIn = newContainer[inputKey];
            if(Array.isArray(oldValIn) && oldValIn === newValIn) continue;
        }

        if(newVal === undefined) {
            if(canBeDataArray && wasArray) flags.calc = true;
            else changed();
        }
        else if(valObject._isLinkedToArray) {
            var arrayEditIndices = [];
            var extraIndices = false;
            if(!inArray) flags.arrays[key] = arrayEditIndices;

            var minLen = Math.min(oldVal.length, newVal.length);
            var maxLen = Math.max(oldVal.length, newVal.length);
            if(minLen !== maxLen) {
                if(valObject.editType === 'arraydraw') {
                    extraIndices = true;
                }
                else {
                    changed();
                    continue;
                }
            }

            for(i = 0; i < minLen; i++) {
                getDiffFlags(oldVal[i], newVal[i], parts.concat(i),
                    // add array indices, but not if we're already in an array
                    Lib.extendFlat({inArray: key, arrayIndex: i}, opts));
            }

            // put this at the end so that we know our collected array indices are sorted
            // but the check for length changes happens up front so we can short-circuit
            // diffing if appropriate
            if(extraIndices) {
                for(i = minLen; i < maxLen; i++) {
                    arrayEditIndices.push(i);
                }
            }
        }
        else if(!valType && Lib.isPlainObject(oldVal)) {
            getDiffFlags(oldVal, newVal, parts, opts);
        }
        else if(canBeDataArray) {
            if(wasArray && nowArray) {

                // don't try to diff two data arrays. If immutable we know the data changed,
                // if not, assume it didn't and let `layout.datarevision` tell us if it did
                if(immutable) {
                    flags.calc = true;
                }

                // look for animatable attributes when the data changed
                if(immutable || opts.newDataRevision) {
                    changed();
                }
            }
            else if(wasArray !== nowArray) {
                flags.calc = true;
            }
            else changed();
        }
        else if(wasArray && nowArray) {
            // info array, colorscale, 'any' - these are short, just stringify.
            // I don't *think* that covers up any real differences post-validation, does it?
            // otherwise we need to dive in 1 (info_array) or 2 (colorscale) levels and compare
            // all elements.
            if(oldVal.length !== newVal.length || String(oldVal) !== String(newVal)) {
                changed();
            }
        }
        else {
            changed();
        }
    }

    for(key in newContainer) {
        if(!(key in oldContainer || key.charAt(0) === '_' || typeof newContainer[key] === 'function')) {
            valObject = getValObject(outerparts.concat(key));

            if(valObjectCanBeDataArray(valObject) && Array.isArray(newContainer[key])) {
                flags.calc = true;
                return;
            }
            else changed();
        }
    }
}

/*
 * simple diff for config - for now, just treat all changes as equivalent
 */
function diffConfig(oldConfig, newConfig) {
    var key;

    for(key in oldConfig) {
        if(key.charAt(0) === '_') continue;
        var oldVal = oldConfig[key];
        var newVal = newConfig[key];
        if(oldVal !== newVal) {
            if(Lib.isPlainObject(oldVal) && Lib.isPlainObject(newVal)) {
                if(diffConfig(oldVal, newVal)) {
                    return true;
                }
            }
            else if(Array.isArray(oldVal) && Array.isArray(newVal)) {
                if(oldVal.length !== newVal.length) {
                    return true;
                }
                for(var i = 0; i < oldVal.length; i++) {
                    if(oldVal[i] !== newVal[i]) {
                        if(Lib.isPlainObject(oldVal[i]) && Lib.isPlainObject(newVal[i])) {
                            if(diffConfig(oldVal[i], newVal[i])) {
                                return true;
                            }
                        }
                        else {
                            return true;
                        }
                    }
                }
            }
            else {
                return true;
            }
        }
    }
}

/**
 * Animate to a frame, sequence of frame, frame group, or frame definition
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 *
 * @param {string or object or array of strings or array of objects} frameOrGroupNameOrFrameList
 *      a single frame, array of frames, or group to which to animate. The intent is
 *      inferred by the type of the input. Valid inputs are:
 *
 *      - string, e.g. 'groupname': animate all frames of a given `group` in the order
 *            in which they are defined via `Plotly.addFrames`.
 *
 *      - array of strings, e.g. ['frame1', frame2']: a list of frames by name to which
 *            to animate in sequence
 *
 *      - object: {data: ...}: a frame definition to which to animate. The frame is not
 *            and does not need to be added via `Plotly.addFrames`. It may contain any of
 *            the properties of a frame, including `data`, `layout`, and `traces`. The
 *            frame is used as provided and does not use the `baseframe` property.
 *
 *      - array of objects, e.g. [{data: ...}, {data: ...}]: a list of frame objects,
 *            each following the same rules as a single `object`.
 *
 * @param {object} animationOpts
 *      configuration for the animation
 */
exports.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts) {
    gd = Lib.getGraphDiv(gd);

    if(!Lib.isPlotDiv(gd)) {
        throw new Error(
            'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' +
            'to create a plot before animating it. For more details, see ' +
            'https://plot.ly/javascript/animations/'
        );
    }

    var trans = gd._transitionData;

    // This is the queue of frames that will be animated as soon as possible. They
    // are popped immediately upon the *start* of a transition:
    if(!trans._frameQueue) {
        trans._frameQueue = [];
    }

    animationOpts = Plots.supplyAnimationDefaults(animationOpts);
    var transitionOpts = animationOpts.transition;
    var frameOpts = animationOpts.frame;

    // Since frames are popped immediately, an empty queue only means all frames have
    // *started* to transition, not that the animation is complete. To solve that,
    // track a separate counter that increments at the same time as frames are added
    // to the queue, but decrements only when the transition is complete.
    if(trans._frameWaitingCnt === undefined) {
        trans._frameWaitingCnt = 0;
    }

    function getTransitionOpts(i) {
        if(Array.isArray(transitionOpts)) {
            if(i >= transitionOpts.length) {
                return transitionOpts[0];
            } else {
                return transitionOpts[i];
            }
        } else {
            return transitionOpts;
        }
    }

    function getFrameOpts(i) {
        if(Array.isArray(frameOpts)) {
            if(i >= frameOpts.length) {
                return frameOpts[0];
            } else {
                return frameOpts[i];
            }
        } else {
            return frameOpts;
        }
    }

    // Execute a callback after the wrapper function has been called n times.
    // This is used to defer the resolution until a transition has resovled *and*
    // the frame has completed. If it's not done this way, then we get a race
    // condition in which the animation might resolve before a transition is complete
    // or vice versa.
    function callbackOnNthTime(cb, n) {
        var cnt = 0;
        return function() {
            if(cb && ++cnt === n) {
                return cb();
            }
        };
    }

    return new Promise(function(resolve, reject) {
        function discardExistingFrames() {
            if(trans._frameQueue.length === 0) {
                return;
            }

            while(trans._frameQueue.length) {
                var next = trans._frameQueue.pop();
                if(next.onInterrupt) {
                    next.onInterrupt();
                }
            }

            gd.emit('plotly_animationinterrupted', []);
        }

        function queueFrames(frameList) {
            if(frameList.length === 0) return;

            for(var i = 0; i < frameList.length; i++) {
                var computedFrame;

                if(frameList[i].type === 'byname') {
                    // If it's a named frame, compute it:
                    computedFrame = Plots.computeFrame(gd, frameList[i].name);
                } else {
                    // Otherwise we must have been given a simple object, so treat
                    // the input itself as the computed frame.
                    computedFrame = frameList[i].data;
                }

                var frameOpts = getFrameOpts(i);
                var transitionOpts = getTransitionOpts(i);

                // It doesn't make much sense for the transition duration to be greater than
                // the frame duration, so limit it:
                transitionOpts.duration = Math.min(transitionOpts.duration, frameOpts.duration);

                var nextFrame = {
                    frame: computedFrame,
                    name: frameList[i].name,
                    frameOpts: frameOpts,
                    transitionOpts: transitionOpts,
                };
                if(i === frameList.length - 1) {
                    // The last frame in this .animate call stores the promise resolve
                    // and reject callbacks. This is how we ensure that the animation
                    // loop (which may exist as a result of a *different* .animate call)
                    // still resolves or rejecdts this .animate call's promise. once it's
                    // complete.
                    nextFrame.onComplete = callbackOnNthTime(resolve, 2);
                    nextFrame.onInterrupt = reject;
                }

                trans._frameQueue.push(nextFrame);
            }

            // Set it as never having transitioned to a frame. This will cause the animation
            // loop to immediately transition to the next frame (which, for immediate mode,
            // is the first frame in the list since all others would have been discarded
            // below)
            if(animationOpts.mode === 'immediate') {
                trans._lastFrameAt = -Infinity;
            }

            // Only it's not already running, start a RAF loop. This could be avoided in the
            // case that there's only one frame, but it significantly complicated the logic
            // and only sped things up by about 5% or so for a lorenz attractor simulation.
            // It would be a fine thing to implement, but the benefit of that optimization
            // doesn't seem worth the extra complexity.
            if(!trans._animationRaf) {
                beginAnimationLoop();
            }
        }

        function stopAnimationLoop() {
            gd.emit('plotly_animated');

            // Be sure to unset also since it's how we know whether a loop is already running:
            window.cancelAnimationFrame(trans._animationRaf);
            trans._animationRaf = null;
        }

        function nextFrame() {
            if(trans._currentFrame && trans._currentFrame.onComplete) {
                // Execute the callback and unset it to ensure it doesn't
                // accidentally get called twice
                trans._currentFrame.onComplete();
            }

            var newFrame = trans._currentFrame = trans._frameQueue.shift();

            if(newFrame) {
                // Since it's sometimes necessary to do deep digging into frame data,
                // we'll consider it not 100% impossible for nulls or numbers to sneak through,
                // so check when casting the name, just to be absolutely certain:
                var stringName = newFrame.name ? newFrame.name.toString() : null;
                gd._fullLayout._currentFrame = stringName;

                trans._lastFrameAt = Date.now();
                trans._timeToNext = newFrame.frameOpts.duration;

                // This is simply called and it's left to .transition to decide how to manage
                // interrupting current transitions. That means we don't need to worry about
                // how it resolves or what happens after this:
                Plots.transition(gd,
                    newFrame.frame.data,
                    newFrame.frame.layout,
                    helpers.coerceTraceIndices(gd, newFrame.frame.traces),
                    newFrame.frameOpts,
                    newFrame.transitionOpts
                ).then(function() {
                    if(newFrame.onComplete) {
                        newFrame.onComplete();
                    }

                });

                gd.emit('plotly_animatingframe', {
                    name: stringName,
                    frame: newFrame.frame,
                    animation: {
                        frame: newFrame.frameOpts,
                        transition: newFrame.transitionOpts,
                    }
                });
            } else {
                // If there are no more frames, then stop the RAF loop:
                stopAnimationLoop();
            }
        }

        function beginAnimationLoop() {
            gd.emit('plotly_animating');

            // If no timer is running, then set last frame = long ago so that the next
            // frame is immediately transitioned:
            trans._lastFrameAt = -Infinity;
            trans._timeToNext = 0;
            trans._runningTransitions = 0;
            trans._currentFrame = null;

            var doFrame = function() {
                // This *must* be requested before nextFrame since nextFrame may decide
                // to cancel it if there's nothing more to animated:
                trans._animationRaf = window.requestAnimationFrame(doFrame);

                // Check if we're ready for a new frame:
                if(Date.now() - trans._lastFrameAt > trans._timeToNext) {
                    nextFrame();
                }
            };

            doFrame();
        }

        // This is an animate-local counter that helps match up option input list
        // items with the particular frame.
        var configCounter = 0;
        function setTransitionConfig(frame) {
            if(Array.isArray(transitionOpts)) {
                if(configCounter >= transitionOpts.length) {
                    frame.transitionOpts = transitionOpts[configCounter];
                } else {
                    frame.transitionOpts = transitionOpts[0];
                }
            } else {
                frame.transitionOpts = transitionOpts;
            }
            configCounter++;
            return frame;
        }

        // Disambiguate what's sort of frames have been received
        var i, frame;
        var frameList = [];
        var allFrames = frameOrGroupNameOrFrameList === undefined || frameOrGroupNameOrFrameList === null;
        var isFrameArray = Array.isArray(frameOrGroupNameOrFrameList);
        var isSingleFrame = !allFrames && !isFrameArray && Lib.isPlainObject(frameOrGroupNameOrFrameList);

        if(isSingleFrame) {
            // In this case, a simple object has been passed to animate.
            frameList.push({
                type: 'object',
                data: setTransitionConfig(Lib.extendFlat({}, frameOrGroupNameOrFrameList))
            });
        } else if(allFrames || ['string', 'number'].indexOf(typeof frameOrGroupNameOrFrameList) !== -1) {
            // In this case, null or undefined has been passed so that we want to
            // animate *all* currently defined frames
            for(i = 0; i < trans._frames.length; i++) {
                frame = trans._frames[i];

                if(!frame) continue;

                if(allFrames || String(frame.group) === String(frameOrGroupNameOrFrameList)) {
                    frameList.push({
                        type: 'byname',
                        name: String(frame.name),
                        data: setTransitionConfig({name: frame.name})
                    });
                }
            }
        } else if(isFrameArray) {
            for(i = 0; i < frameOrGroupNameOrFrameList.length; i++) {
                var frameOrName = frameOrGroupNameOrFrameList[i];
                if(['number', 'string'].indexOf(typeof frameOrName) !== -1) {
                    frameOrName = String(frameOrName);
                    // In this case, there's an array and this frame is a string name:
                    frameList.push({
                        type: 'byname',
                        name: frameOrName,
                        data: setTransitionConfig({name: frameOrName})
                    });
                } else if(Lib.isPlainObject(frameOrName)) {
                    frameList.push({
                        type: 'object',
                        data: setTransitionConfig(Lib.extendFlat({}, frameOrName))
                    });
                }
            }
        }

        // Verify that all of these frames actually exist; return and reject if not:
        for(i = 0; i < frameList.length; i++) {
            frame = frameList[i];
            if(frame.type === 'byname' && !trans._frameHash[frame.data.name]) {
                Lib.warn('animate failure: frame not found: "' + frame.data.name + '"');
                reject();
                return;
            }
        }

        // If the mode is either next or immediate, then all currently queued frames must
        // be dumped and the corresponding .animate promises rejected.
        if(['next', 'immediate'].indexOf(animationOpts.mode) !== -1) {
            discardExistingFrames();
        }

        if(animationOpts.direction === 'reverse') {
            frameList.reverse();
        }

        var currentFrame = gd._fullLayout._currentFrame;
        if(currentFrame && animationOpts.fromcurrent) {
            var idx = -1;
            for(i = 0; i < frameList.length; i++) {
                frame = frameList[i];
                if(frame.type === 'byname' && frame.name === currentFrame) {
                    idx = i;
                    break;
                }
            }

            if(idx > 0 && idx < frameList.length - 1) {
                var filteredFrameList = [];
                for(i = 0; i < frameList.length; i++) {
                    frame = frameList[i];
                    if(frameList[i].type !== 'byname' || i > idx) {
                        filteredFrameList.push(frame);
                    }
                }
                frameList = filteredFrameList;
            }
        }

        if(frameList.length > 0) {
            queueFrames(frameList);
        } else {
            // This is the case where there were simply no frames. It's a little strange
            // since there's not much to do:
            gd.emit('plotly_animated');
            resolve();
        }
    });
};

/**
 * Register new frames
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 *
 * @param {array of objects} frameList
 *      list of frame definitions, in which each object includes any of:
 *      - name: {string} name of frame to add
 *      - data: {array of objects} trace data
 *      - layout {object} layout definition
 *      - traces {array} trace indices
 *      - baseframe {string} name of frame from which this frame gets defaults
 *
 *  @param {array of integers} indices
 *      an array of integer indices matching the respective frames in `frameList`. If not
 *      provided, an index will be provided in serial order. If already used, the frame
 *      will be overwritten.
 */
exports.addFrames = function(gd, frameList, indices) {
    gd = Lib.getGraphDiv(gd);

    if(frameList === null || frameList === undefined) {
        return Promise.resolve();
    }

    if(!Lib.isPlotDiv(gd)) {
        throw new Error(
            'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' +
            'to create a plot before adding frames. For more details, see ' +
            'https://plot.ly/javascript/animations/'
        );
    }

    var i, frame, j, idx;
    var _frames = gd._transitionData._frames;
    var _frameHash = gd._transitionData._frameHash;


    if(!Array.isArray(frameList)) {
        throw new Error('addFrames failure: frameList must be an Array of frame definitions' + frameList);
    }

    // Create a sorted list of insertions since we run into lots of problems if these
    // aren't in ascending order of index:
    //
    // Strictly for sorting. Make sure this is guaranteed to never collide with any
    // already-exisisting indices:
    var bigIndex = _frames.length + frameList.length * 2;

    var insertions = [];
    var _frameHashLocal = {};
    for(i = frameList.length - 1; i >= 0; i--) {
        if(!Lib.isPlainObject(frameList[i])) continue;

        // The entire logic for checking for this type of name collision can be removed once we migrate to ES6 and
        // use a Map instead of an Object instance, as Map keys aren't converted to strings.
        var lookupName = frameList[i].name;
        var name = (_frameHash[lookupName] || _frameHashLocal[lookupName] || {}).name;
        var newName = frameList[i].name;
        var collisionPresent = _frameHash[name] || _frameHashLocal[name];

        if(name && newName && typeof newName === 'number' && collisionPresent && numericNameWarningCount < numericNameWarningCountLimit) {
            numericNameWarningCount++;

            Lib.warn('addFrames: overwriting frame "' + (_frameHash[name] || _frameHashLocal[name]).name +
                '" with a frame whose name of type "number" also equates to "' +
                name + '". This is valid but may potentially lead to unexpected ' +
                'behavior since all plotly.js frame names are stored internally ' +
                'as strings.');

            if(numericNameWarningCount === numericNameWarningCountLimit) {
                Lib.warn('addFrames: This API call has yielded too many of these warnings. ' +
                    'For the rest of this call, further warnings about numeric frame ' +
                    'names will be suppressed.');
            }
        }

        _frameHashLocal[lookupName] = {name: lookupName};

        insertions.push({
            frame: Plots.supplyFrameDefaults(frameList[i]),
            index: (indices && indices[i] !== undefined && indices[i] !== null) ? indices[i] : bigIndex + i
        });
    }

    // Sort this, taking note that undefined insertions end up at the end:
    insertions.sort(function(a, b) {
        if(a.index > b.index) return -1;
        if(a.index < b.index) return 1;
        return 0;
    });

    var ops = [];
    var revops = [];
    var frameCount = _frames.length;

    for(i = insertions.length - 1; i >= 0; i--) {
        frame = insertions[i].frame;

        if(typeof frame.name === 'number') {
            Lib.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' +
                'implicitly cast to strings');

        }

        if(!frame.name) {
            // Repeatedly assign a default name, incrementing the counter each time until
            // we get a name that's not in the hashed lookup table:
            while(_frameHash[(frame.name = 'frame ' + gd._transitionData._counter++)]);
        }

        if(_frameHash[frame.name]) {
            // If frame is present, overwrite its definition:
            for(j = 0; j < _frames.length; j++) {
                if((_frames[j] || {}).name === frame.name) break;
            }
            ops.push({type: 'replace', index: j, value: frame});
            revops.unshift({type: 'replace', index: j, value: _frames[j]});
        } else {
            // Otherwise insert it at the end of the list:
            idx = Math.max(0, Math.min(insertions[i].index, frameCount));

            ops.push({type: 'insert', index: idx, value: frame});
            revops.unshift({type: 'delete', index: idx});
            frameCount++;
        }
    }

    var undoFunc = Plots.modifyFrames;
    var redoFunc = Plots.modifyFrames;
    var undoArgs = [gd, revops];
    var redoArgs = [gd, ops];

    if(Queue) Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);

    return Plots.modifyFrames(gd, ops);
};

/**
 * Delete frame
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 *
 * @param {array of integers} frameList
 *      list of integer indices of frames to be deleted
 */
exports.deleteFrames = function(gd, frameList) {
    gd = Lib.getGraphDiv(gd);

    if(!Lib.isPlotDiv(gd)) {
        throw new Error('This element is not a Plotly plot: ' + gd);
    }

    var i, idx;
    var _frames = gd._transitionData._frames;
    var ops = [];
    var revops = [];

    if(!frameList) {
        frameList = [];
        for(i = 0; i < _frames.length; i++) {
            frameList.push(i);
        }
    }

    frameList = frameList.slice(0);
    frameList.sort();

    for(i = frameList.length - 1; i >= 0; i--) {
        idx = frameList[i];
        ops.push({type: 'delete', index: idx});
        revops.unshift({type: 'insert', index: idx, value: _frames[idx]});
    }

    var undoFunc = Plots.modifyFrames;
    var redoFunc = Plots.modifyFrames;
    var undoArgs = [gd, revops];
    var redoArgs = [gd, ops];

    if(Queue) Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);

    return Plots.modifyFrames(gd, ops);
};

/**
 * Purge a graph container div back to its initial pre-Plotly.plot state
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 */
exports.purge = function purge(gd) {
    gd = Lib.getGraphDiv(gd);

    var fullLayout = gd._fullLayout || {};
    var fullData = gd._fullData || [];

    // remove gl contexts
    Plots.cleanPlot([], {}, fullData, fullLayout);

    // purge properties
    Plots.purge(gd);

    // purge event emitter methods
    Events.purge(gd);

    // remove plot container
    if(fullLayout._container) fullLayout._container.remove();

    // in contrast to Plotly.Plots.purge which does NOT clear _context!
    delete gd._context;

    return gd;
};

// -------------------------------------------------------
// makePlotFramework: Create the plot container and axes
// -------------------------------------------------------
function makePlotFramework(gd) {
    var gd3 = d3.select(gd);
    var fullLayout = gd._fullLayout;

    // Plot container
    fullLayout._container = gd3.selectAll('.plot-container').data([0]);
    fullLayout._container.enter().insert('div', ':first-child')
        .classed('plot-container', true)
        .classed('plotly', true);

    // Make the svg container
    fullLayout._paperdiv = fullLayout._container.selectAll('.svg-container').data([0]);
    fullLayout._paperdiv.enter().append('div')
        .classed('svg-container', true)
        .style('position', 'relative');

    // Make the graph containers
    // start fresh each time we get here, so we know the order comes out
    // right, rather than enter/exit which can muck up the order
    // TODO: sort out all the ordering so we don't have to
    // explicitly delete anything
    // FIXME: parcoords reuses this object, not the best pattern
    fullLayout._glcontainer = fullLayout._paperdiv.selectAll('.gl-container')
        .data([{}]);

    fullLayout._glcontainer.enter().append('div')
        .classed('gl-container', true);

    fullLayout._paperdiv.selectAll('.main-svg').remove();

    fullLayout._paper = fullLayout._paperdiv.insert('svg', ':first-child')
        .classed('main-svg', true);

    fullLayout._toppaper = fullLayout._paperdiv.append('svg')
        .classed('main-svg', true);

    if(!fullLayout._uid) {
        var otherUids = {};
        d3.selectAll('defs').each(function() {
            if(this.id) otherUids[this.id.split('-')[1]] = 1;
        });
        fullLayout._uid = Lib.randstr(otherUids);
    }

    fullLayout._paperdiv.selectAll('.main-svg')
        .attr(xmlnsNamespaces.svgAttrs);

    fullLayout._defs = fullLayout._paper.append('defs')
        .attr('id', 'defs-' + fullLayout._uid);

    fullLayout._clips = fullLayout._defs.append('g')
        .classed('clips', true);

    fullLayout._topdefs = fullLayout._toppaper.append('defs')
        .attr('id', 'topdefs-' + fullLayout._uid);

    fullLayout._topclips = fullLayout._topdefs.append('g')
        .classed('clips', true);

    fullLayout._bgLayer = fullLayout._paper.append('g')
        .classed('bglayer', true);

    fullLayout._draggers = fullLayout._paper.append('g')
        .classed('draglayer', true);

    // lower shape/image layer - note that this is behind
    // all subplots data/grids but above the backgrounds
    // except inset subplots, whose backgrounds are drawn
    // inside their own group so that they appear above
    // the data for the main subplot
    // lower shapes and images which are fully referenced to
    // a subplot still get drawn within the subplot's group
    // so they will work correctly on insets
    var layerBelow = fullLayout._paper.append('g')
        .classed('layer-below', true);
    fullLayout._imageLowerLayer = layerBelow.append('g')
        .classed('imagelayer', true);
    fullLayout._shapeLowerLayer = layerBelow.append('g')
        .classed('shapelayer', true);

    // single cartesian layer for the whole plot
    fullLayout._cartesianlayer = fullLayout._paper.append('g').classed('cartesianlayer', true);

    // single polar layer for the whole plot
    fullLayout._polarlayer = fullLayout._paper.append('g').classed('polarlayer', true);

    // single ternary layer for the whole plot
    fullLayout._ternarylayer = fullLayout._paper.append('g').classed('ternarylayer', true);

    // single geo layer for the whole plot
    fullLayout._geolayer = fullLayout._paper.append('g').classed('geolayer', true);

    // single pie layer for the whole plot
    fullLayout._pielayer = fullLayout._paper.append('g').classed('pielayer', true);

    // fill in image server scrape-svg
    fullLayout._glimages = fullLayout._paper.append('g').classed('glimages', true);

    // lastly upper shapes, info (legend, annotations) and hover layers go on top
    // these are in a different svg element normally, but get collapsed into a single
    // svg when exporting (after inserting 3D)
    // upper shapes/images are only those drawn above the whole plot, including subplots
    var layerAbove = fullLayout._toppaper.append('g')
        .classed('layer-above', true);
    fullLayout._imageUpperLayer = layerAbove.append('g')
        .classed('imagelayer', true);
    fullLayout._shapeUpperLayer = layerAbove.append('g')
        .classed('shapelayer', true);

    fullLayout._infolayer = fullLayout._toppaper.append('g').classed('infolayer', true);
    fullLayout._menulayer = fullLayout._toppaper.append('g').classed('menulayer', true);
    fullLayout._zoomlayer = fullLayout._toppaper.append('g').classed('zoomlayer', true);
    fullLayout._hoverlayer = fullLayout._toppaper.append('g').classed('hoverlayer', true);

    // Make the modebar container
    fullLayout._modebardiv = fullLayout._paperdiv.selectAll('.modebar-container').data([0]);
    fullLayout._modebardiv.enter().append('div')
        .classed('modebar-container', true)
        .style('position', 'absolute')
        .style('top', '0px')
        .style('right', '0px');

    gd.emit('plotly_framework');
}

},{"../components/color":574,"../components/colorbar/connect":576,"../components/drawing":595,"../constants/xmlns_namespaces":675,"../lib":697,"../lib/events":686,"../lib/queue":712,"../lib/svg_text_utils":721,"../plots/cartesian/axes":745,"../plots/cartesian/constants":751,"../plots/cartesian/graph_interact":754,"../plots/cartesian/select":762,"../plots/plots":807,"../plots/polar/legacy":815,"../registry":826,"./edit_types":728,"./helpers":729,"./manage_arrays":731,"./plot_config":733,"./plot_schema":734,"./subroutines":736,"d3":151,"fast-isnumeric":218,"has-hover":399}],733:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * This will be transferred over to gd and overridden by
 * config args to Plotly.plot.
 *
 * The defaults are the appropriate settings for plotly.js,
 * so we get the right experience without any config argument.
 *
 * N.B. the config options are not coerced using Lib.coerce so keys
 * like `valType` and `values` are only set for documentation purposes
 * at the moment.
 */

var configAttributes = {
    staticPlot: {
        valType: 'boolean',
        dflt: false,
        
    },

    plotlyServerURL: {
        valType: 'string',
        dflt: 'https://plot.ly',
        
    },

    editable: {
        valType: 'boolean',
        dflt: false,
        
    },
    edits: {
        annotationPosition: {
            valType: 'boolean',
            dflt: false,
            
        },
        annotationTail: {
            valType: 'boolean',
            dflt: false,
            
        },
        annotationText: {
            valType: 'boolean',
            dflt: false,
            
        },
        axisTitleText: {
            valType: 'boolean',
            dflt: false,
            
        },
        colorbarPosition: {
            valType: 'boolean',
            dflt: false,
            
        },
        colorbarTitleText: {
            valType: 'boolean',
            dflt: false,
            
        },
        legendPosition: {
            valType: 'boolean',
            dflt: false,
            
        },
        legendText: {
            valType: 'boolean',
            dflt: false,
            
        },
        shapePosition: {
            valType: 'boolean',
            dflt: false,
            
        },
        titleText: {
            valType: 'boolean',
            dflt: false,
            
        }
    },

    autosizable: {
        valType: 'boolean',
        dflt: false,
        
    },
    responsive: {
        valType: 'boolean',
        dflt: false,
        
    },
    fillFrame: {
        valType: 'boolean',
        dflt: false,
        
    },
    frameMargins: {
        valType: 'number',
        dflt: 0,
        min: 0,
        max: 0.5,
        
    },

    scrollZoom: {
        valType: 'flaglist',
        flags: ['cartesian', 'gl3d', 'geo', 'mapbox'],
        extras: [true, false],
        dflt: 'gl3d+geo+mapbox',
        
    },
    doubleClick: {
        valType: 'enumerated',
        values: [false, 'reset', 'autosize', 'reset+autosize'],
        dflt: 'reset+autosize',
        
    },

    showAxisDragHandles: {
        valType: 'boolean',
        dflt: true,
        
    },
    showAxisRangeEntryBoxes: {
        valType: 'boolean',
        dflt: true,
        
    },

    showTips: {
        valType: 'boolean',
        dflt: true,
        
    },

    showLink: {
        valType: 'boolean',
        dflt: false,
        
    },
    linkText: {
        valType: 'string',
        dflt: 'Edit chart',
        noBlank: true,
        
    },
    sendData: {
        valType: 'boolean',
        dflt: true,
        
    },
    showSources: {
        valType: 'any',
        dflt: false,
        
    },

    displayModeBar: {
        valType: 'enumerated',
        values: ['hover', true, false],
        dflt: 'hover',
        
    },
    showSendToCloud: {
        valType: 'boolean',
        dflt: false,
        
    },
    modeBarButtonsToRemove: {
        valType: 'any',
        dflt: [],
        
    },
    modeBarButtonsToAdd: {
        valType: 'any',
        dflt: [],
        
    },
    modeBarButtons: {
        valType: 'any',
        dflt: false,
        
    },
    toImageButtonOptions: {
        valType: 'any',
        dflt: {},
        
    },
    displaylogo: {
        valType: 'boolean',
        dflt: true,
        
    },
    watermark: {
        valType: 'boolean',
        dflt: false,
        
    },

    plotGlPixelRatio: {
        valType: 'number',
        dflt: 2,
        min: 1,
        max: 4,
        
    },

    setBackground: {
        valType: 'any',
        dflt: 'transparent',
        
    },

    topojsonURL: {
        valType: 'string',
        noBlank: true,
        dflt: 'https://cdn.plot.ly/',
        
    },

    mapboxAccessToken: {
        valType: 'string',
        dflt: null,
        
    },

    logging: {
        valType: 'boolean',
        dflt: 1,
        
    },

    queueLength: {
        valType: 'integer',
        min: 0,
        dflt: 0,
        
    },

    globalTransforms: {
        valType: 'any',
        dflt: [],
        
    },

    locale: {
        valType: 'string',
        dflt: 'en-US',
        
    },

    locales: {
        valType: 'any',
        dflt: {},
        
    }
};

var dfltConfig = {};

function crawl(src, target) {
    for(var k in src) {
        var obj = src[k];
        if(obj.valType) {
            target[k] = obj.dflt;
        } else {
            if(!target[k]) {
                target[k] = {};
            }
            crawl(obj, target[k]);
        }
    }
}

crawl(configAttributes, dfltConfig);

module.exports = {
    configAttributes: configAttributes,
    dfltConfig: dfltConfig
};

},{}],734:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../registry');
var Lib = _dereq_('../lib');

var baseAttributes = _dereq_('../plots/attributes');
var baseLayoutAttributes = _dereq_('../plots/layout_attributes');
var frameAttributes = _dereq_('../plots/frame_attributes');
var animationAttributes = _dereq_('../plots/animation_attributes');
var configAttributes = _dereq_('./plot_config').configAttributes;

// polar attributes are not part of the Registry yet
var polarAreaAttrs = _dereq_('../plots/polar/legacy/area_attributes');
var polarAxisAttrs = _dereq_('../plots/polar/legacy/axis_attributes');

var editTypes = _dereq_('./edit_types');

var extendFlat = Lib.extendFlat;
var extendDeepAll = Lib.extendDeepAll;
var isPlainObject = Lib.isPlainObject;

var IS_SUBPLOT_OBJ = '_isSubplotObj';
var IS_LINKED_TO_ARRAY = '_isLinkedToArray';
var ARRAY_ATTR_REGEXPS = '_arrayAttrRegexps';
var DEPRECATED = '_deprecated';
var UNDERSCORE_ATTRS = [IS_SUBPLOT_OBJ, IS_LINKED_TO_ARRAY, ARRAY_ATTR_REGEXPS, DEPRECATED];

exports.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ;
exports.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY;
exports.DEPRECATED = DEPRECATED;
exports.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS;

/** Outputs the full plotly.js plot schema
 *
 * @return {object}
 *  - defs
 *  - traces
 *  - layout
 *  - transforms
 *  - frames
 *  - animations
 *  - config
 */
exports.get = function() {
    var traces = {};

    Registry.allTypes.concat('area').forEach(function(type) {
        traces[type] = getTraceAttributes(type);
    });

    var transforms = {};

    Object.keys(Registry.transformsRegistry).forEach(function(type) {
        transforms[type] = getTransformAttributes(type);
    });

    return {
        defs: {
            valObjects: Lib.valObjectMeta,
            metaKeys: UNDERSCORE_ATTRS.concat(['description', 'role', 'editType', 'impliedEdits']),
            editType: {
                traces: editTypes.traces,
                layout: editTypes.layout
            },
            impliedEdits: {
                
            }
        },

        traces: traces,
        layout: getLayoutAttributes(),

        transforms: transforms,

        frames: getFramesAttributes(),
        animation: formatAttributes(animationAttributes),

        config: formatAttributes(configAttributes)
    };
};

/**
 * Crawl the attribute tree, recursively calling a callback function
 *
 * @param {object} attrs
 *  The node of the attribute tree (e.g. the root) from which recursion originates
 * @param {Function} callback
 *  A callback function with the signature:
 *          @callback callback
 *          @param {object} attr an attribute
 *          @param {String} attrName name string
 *          @param {object[]} attrs all the attributes
 *          @param {Number} level the recursion level, 0 at the root
 *          @param {String} fullAttrString full attribute name (ie 'marker.line')
 * @param {Number} [specifiedLevel]
 *  The level in the tree, in order to let the callback function detect descend or backtrack,
 *  typically unsupplied (implied 0), just used by the self-recursive call.
 *  The necessity arises because the tree traversal is not controlled by callback return values.
 *  The decision to not use callback return values for controlling tree pruning arose from
 *  the goal of keeping the crawler backwards compatible. Observe that one of the pruning conditions
 *  precedes the callback call.
 * @param {string} [attrString]
 *  the path to the current attribute, as an attribute string (ie 'marker.line')
 *  typically unsupplied, but you may supply it if you want to disambiguate which attrs tree you
 *  are starting from
 *
 * @return {object} transformOut
 *  copy of transformIn that contains attribute defaults
 */
exports.crawl = function(attrs, callback, specifiedLevel, attrString) {
    var level = specifiedLevel || 0;
    attrString = attrString || '';

    Object.keys(attrs).forEach(function(attrName) {
        var attr = attrs[attrName];

        if(UNDERSCORE_ATTRS.indexOf(attrName) !== -1) return;

        var fullAttrString = (attrString ? attrString + '.' : '') + attrName;
        callback(attr, attrName, attrs, level, fullAttrString);

        if(exports.isValObject(attr)) return;

        if(isPlainObject(attr) && attrName !== 'impliedEdits') {
            exports.crawl(attr, callback, level + 1, fullAttrString);
        }
    });
};

/** Is object a value object (or a container object)?
 *
 * @param {object} obj
 * @return {boolean}
 *  returns true for a valid value object and
 *  false for tree nodes in the attribute hierarchy
 */
exports.isValObject = function(obj) {
    return obj && obj.valType !== undefined;
};

/**
 * Find all data array attributes in a given trace object - including
 * `arrayOk` attributes.
 *
 * @param {object} trace
 *  full trace object that contains a reference to `_module.attributes`
 *
 * @return {array} arrayAttributes
 *  list of array attributes for the given trace
 */
exports.findArrayAttributes = function(trace) {
    var arrayAttributes = [];
    var stack = [];
    var isArrayStack = [];
    var baseContainer, baseAttrName;

    function callback(attr, attrName, attrs, level) {
        stack = stack.slice(0, level).concat([attrName]);
        isArrayStack = isArrayStack.slice(0, level).concat([attr && attr._isLinkedToArray]);

        var splittableAttr = (
            attr &&
            (attr.valType === 'data_array' || attr.arrayOk === true) &&
            !(stack[level - 1] === 'colorbar' && (attrName === 'ticktext' || attrName === 'tickvals'))
        );

        // Manually exclude 'colorbar.tickvals' and 'colorbar.ticktext' for now
        // which are declared as `valType: 'data_array'` but scale independently of
        // the coordinate arrays.
        //
        // Down the road, we might want to add a schema field (e.g `uncorrelatedArray: true`)
        // to distinguish attributes of the likes.

        if(!splittableAttr) return;

        crawlIntoTrace(baseContainer, 0, '');
    }

    function crawlIntoTrace(container, i, astrPartial) {
        var item = container[stack[i]];
        var newAstrPartial = astrPartial + stack[i];
        if(i === stack.length - 1) {
            if(Lib.isArrayOrTypedArray(item)) {
                arrayAttributes.push(baseAttrName + newAstrPartial);
            }
        }
        else {
            if(isArrayStack[i]) {
                if(Array.isArray(item)) {
                    for(var j = 0; j < item.length; j++) {
                        if(Lib.isPlainObject(item[j])) {
                            crawlIntoTrace(item[j], i + 1, newAstrPartial + '[' + j + '].');
                        }
                    }
                }
            }
            else if(Lib.isPlainObject(item)) {
                crawlIntoTrace(item, i + 1, newAstrPartial + '.');
            }
        }
    }

    baseContainer = trace;
    baseAttrName = '';
    exports.crawl(baseAttributes, callback);
    if(trace._module && trace._module.attributes) {
        exports.crawl(trace._module.attributes, callback);
    }

    var transforms = trace.transforms;
    if(transforms) {
        for(var i = 0; i < transforms.length; i++) {
            var transform = transforms[i];
            var module = transform._module;

            if(module) {
                baseAttrName = 'transforms[' + i + '].';
                baseContainer = transform;

                exports.crawl(module.attributes, callback);
            }
        }
    }

    return arrayAttributes;
};

/*
 * Find the valObject for one attribute in an existing trace
 *
 * @param {object} trace
 *  full trace object that contains a reference to `_module.attributes`
 * @param {object} parts
 *  an array of parts, like ['transforms', 1, 'value']
 *  typically from nestedProperty(...).parts
 *
 * @return {object|false}
 *  the valObject for this attribute, or the last found parent
 *  in some cases the innermost valObject will not exist, for example
 *  `valType: 'any'` attributes where we might set a part of the attribute.
 *  In that case, stop at the deepest valObject we *do* find.
 */
exports.getTraceValObject = function(trace, parts) {
    var head = parts[0];
    var i = 1; // index to start recursing from
    var moduleAttrs, valObject;

    if(head === 'transforms') {
        if(parts.length === 1) {
            return baseAttributes.transforms;
        }
        var transforms = trace.transforms;
        if(!Array.isArray(transforms) || !transforms.length) return false;
        var tNum = parts[1];
        if(!isIndex(tNum) || tNum >= transforms.length) {
            return false;
        }
        moduleAttrs = (Registry.transformsRegistry[transforms[tNum].type] || {}).attributes;
        valObject = moduleAttrs && moduleAttrs[parts[2]];
        i = 3; // start recursing only inside the transform
    }
    else if(trace.type === 'area') {
        valObject = polarAreaAttrs[head];
    }
    else {
        // first look in the module for this trace
        // components have already merged their trace attributes in here
        var _module = trace._module;
        if(!_module) _module = (Registry.modules[trace.type || baseAttributes.type.dflt] || {})._module;
        if(!_module) return false;

        moduleAttrs = _module.attributes;
        valObject = moduleAttrs && moduleAttrs[head];

        // then look in the subplot attributes
        if(!valObject) {
            var subplotModule = _module.basePlotModule;
            if(subplotModule && subplotModule.attributes) {
                valObject = subplotModule.attributes[head];
            }
        }

        // finally look in the global attributes
        if(!valObject) valObject = baseAttributes[head];
    }

    return recurseIntoValObject(valObject, parts, i);
};

/*
 * Find the valObject for one layout attribute
 *
 * @param {array} parts
 *  an array of parts, like ['annotations', 1, 'x']
 *  typically from nestedProperty(...).parts
 *
 * @return {object|false}
 *  the valObject for this attribute, or the last found parent
 *  in some cases the innermost valObject will not exist, for example
 *  `valType: 'any'` attributes where we might set a part of the attribute.
 *  In that case, stop at the deepest valObject we *do* find.
 */
exports.getLayoutValObject = function(fullLayout, parts) {
    var valObject = layoutHeadAttr(fullLayout, parts[0]);

    return recurseIntoValObject(valObject, parts, 1);
};

function layoutHeadAttr(fullLayout, head) {
    var i, key, _module, attributes;

    // look for attributes of the subplot types used on the plot
    var basePlotModules = fullLayout._basePlotModules;
    if(basePlotModules) {
        var out;
        for(i = 0; i < basePlotModules.length; i++) {
            _module = basePlotModules[i];
            if(_module.attrRegex && _module.attrRegex.test(head)) {
                // if a module defines overrides, these take precedence
                // initially this is to allow gl2d different editTypes from svg cartesian
                if(_module.layoutAttrOverrides) return _module.layoutAttrOverrides;

                // otherwise take the first attributes we find
                if(!out && _module.layoutAttributes) out = _module.layoutAttributes;
            }

            // a module can also override the behavior of base (and component) module layout attrs
            // again see gl2d for initial use case
            var baseOverrides = _module.baseLayoutAttrOverrides;
            if(baseOverrides && head in baseOverrides) return baseOverrides[head];
        }
        if(out) return out;
    }

    // look for layout attributes contributed by traces on the plot
    var modules = fullLayout._modules;
    if(modules) {
        for(i = 0; i < modules.length; i++) {
            attributes = modules[i].layoutAttributes;
            if(attributes && head in attributes) {
                return attributes[head];
            }
        }
    }

    /*
     * Next look in components.
     * Components that define a schema have already merged this into
     * base and subplot attribute defs, so ignore these.
     * Others (older style) all put all their attributes
     * inside a container matching the module `name`
     * eg `attributes` (array) or `legend` (object)
     */
    for(key in Registry.componentsRegistry) {
        _module = Registry.componentsRegistry[key];
        if(!_module.schema && (head === _module.name)) {
            return _module.layoutAttributes;
        }
    }

    if(head in baseLayoutAttributes) return baseLayoutAttributes[head];

    // Polar doesn't populate _modules or _basePlotModules
    // just fall back on these when the others fail
    if(head === 'radialaxis' || head === 'angularaxis') {
        return polarAxisAttrs[head];
    }
    return polarAxisAttrs.layout[head] || false;
}

function recurseIntoValObject(valObject, parts, i) {
    if(!valObject) return false;

    if(valObject._isLinkedToArray) {
        // skip array index, abort if we try to dive into an array without an index
        if(isIndex(parts[i])) i++;
        else if(i < parts.length) return false;
    }

    // now recurse as far as we can. Occasionally we have an attribute
    // setting an internal part below what's in the schema; just return
    // the innermost schema item we find.
    for(; i < parts.length; i++) {
        var newValObject = valObject[parts[i]];
        if(isPlainObject(newValObject)) valObject = newValObject;
        else break;

        if(i === parts.length - 1) break;

        if(valObject._isLinkedToArray) {
            i++;
            if(!isIndex(parts[i])) return false;
        }
        else if(valObject.valType === 'info_array') {
            i++;
            var index = parts[i];
            if(!isIndex(index)) return false;

            var items = valObject.items;
            if(Array.isArray(items)) {
                if(index >= items.length) return false;
                if(valObject.dimensions === 2) {
                    i++;
                    if(parts.length === i) return valObject;
                    var index2 = parts[i];
                    if(!isIndex(index2)) return false;
                    valObject = items[index][index2];
                }
                else valObject = items[index];
            }
            else {
                valObject = items;
            }
        }
    }

    return valObject;
}

// note: this is different from Lib.isIndex, this one doesn't accept numeric
// strings, only actual numbers.
function isIndex(val) {
    return val === Math.round(val) && val >= 0;
}

function getTraceAttributes(type) {
    var _module, basePlotModule;

    if(type === 'area') {
        _module = { attributes: polarAreaAttrs };
        basePlotModule = {};
    }
    else {
        _module = Registry.modules[type]._module,
        basePlotModule = _module.basePlotModule;
    }

    var attributes = {};

    // make 'type' the first attribute in the object
    attributes.type = null;


    var copyBaseAttributes = extendDeepAll({}, baseAttributes);
    var copyModuleAttributes = extendDeepAll({}, _module.attributes);

    // prune global-level trace attributes that are already defined in a trace
    exports.crawl(copyModuleAttributes, function(attr, attrName, attrs, level, fullAttrString) {
        Lib.nestedProperty(copyBaseAttributes, fullAttrString).set(undefined);
        // Prune undefined attributes
        if(attr === undefined) Lib.nestedProperty(copyModuleAttributes, fullAttrString).set(undefined);
    });

    // base attributes (same for all trace types)
    extendDeepAll(attributes, copyBaseAttributes);

    // module attributes
    extendDeepAll(attributes, copyModuleAttributes);

    // subplot attributes
    if(basePlotModule.attributes) {
        extendDeepAll(attributes, basePlotModule.attributes);
    }

    // 'type' gets overwritten by baseAttributes; reset it here
    attributes.type = type;

    var out = {
        meta: _module.meta || {},
        attributes: formatAttributes(attributes),
    };

    // trace-specific layout attributes
    if(_module.layoutAttributes) {
        var layoutAttributes = {};

        extendDeepAll(layoutAttributes, _module.layoutAttributes);
        out.layoutAttributes = formatAttributes(layoutAttributes);
    }

    return out;
}

function getLayoutAttributes() {
    var layoutAttributes = {};
    var key, _module;

    // global layout attributes
    extendDeepAll(layoutAttributes, baseLayoutAttributes);

    // add base plot module layout attributes
    for(key in Registry.subplotsRegistry) {
        _module = Registry.subplotsRegistry[key];

        if(!_module.layoutAttributes) continue;

        if(Array.isArray(_module.attr)) {
            for(var i = 0; i < _module.attr.length; i++) {
                handleBasePlotModule(layoutAttributes, _module, _module.attr[i]);
            }
        } else {
            var astr = _module.attr === 'subplot' ? _module.name : _module.attr;
            handleBasePlotModule(layoutAttributes, _module, astr);
        }
    }

    // polar layout attributes
    layoutAttributes = assignPolarLayoutAttrs(layoutAttributes);

    // add registered components layout attributes
    for(key in Registry.componentsRegistry) {
        _module = Registry.componentsRegistry[key];
        var schema = _module.schema;

        /*
         * Components with defined schema have already been merged in at register time
         * but a few components define attributes that apply only to xaxis
         * not yaxis (rangeselector, rangeslider) - delete from y schema.
         * Note that the input attributes for xaxis/yaxis are the same object
         * so it's not possible to only add them to xaxis from the start.
         * If we ever have such asymmetry the other way, or anywhere else,
         * we will need to extend both this code and mergeComponentAttrsToSubplot
         * (which will not find yaxis only for example)
         */
        if(schema && (schema.subplots || schema.layout)) {
            var subplots = schema.subplots;
            if(subplots && subplots.xaxis && !subplots.yaxis) {
                for(var xkey in subplots.xaxis) delete layoutAttributes.yaxis[xkey];
            }
        }
        // older style without schema need to be explicitly merged in now
        else if(_module.layoutAttributes) {
            insertAttrs(layoutAttributes, _module.layoutAttributes, _module.name);
        }
    }

    return {
        layoutAttributes: formatAttributes(layoutAttributes)
    };
}

function getTransformAttributes(type) {
    var _module = Registry.transformsRegistry[type];
    var attributes = extendDeepAll({}, _module.attributes);

    // add registered components transform attributes
    Object.keys(Registry.componentsRegistry).forEach(function(k) {
        var _module = Registry.componentsRegistry[k];

        if(_module.schema && _module.schema.transforms && _module.schema.transforms[type]) {
            Object.keys(_module.schema.transforms[type]).forEach(function(v) {
                insertAttrs(attributes, _module.schema.transforms[type][v], v);
            });
        }
    });

    return {
        attributes: formatAttributes(attributes)
    };
}

function getFramesAttributes() {
    var attrs = {
        frames: Lib.extendDeepAll({}, frameAttributes)
    };

    formatAttributes(attrs);

    return attrs.frames;
}

function formatAttributes(attrs) {
    mergeValTypeAndRole(attrs);
    formatArrayContainers(attrs);
    stringify(attrs);

    return attrs;
}

function mergeValTypeAndRole(attrs) {

    function makeSrcAttr(attrName) {
        return {
            valType: 'string',
            
            
            editType: 'none'
        };
    }

    function callback(attr, attrName, attrs) {
        if(exports.isValObject(attr)) {
            if(attr.valType === 'data_array') {
                // all 'data_array' attrs have role 'data'
                attr.role = 'data';
                // all 'data_array' attrs have a corresponding 'src' attr
                attrs[attrName + 'src'] = makeSrcAttr(attrName);
            }
            else if(attr.arrayOk === true) {
                // all 'arrayOk' attrs have a corresponding 'src' attr
                attrs[attrName + 'src'] = makeSrcAttr(attrName);
            }
        }
        else if(isPlainObject(attr)) {
            // all attrs container objects get role 'object'
            attr.role = 'object';
        }
    }

    exports.crawl(attrs, callback);
}

function formatArrayContainers(attrs) {

    function callback(attr, attrName, attrs) {
        if(!attr) return;

        var itemName = attr[IS_LINKED_TO_ARRAY];

        if(!itemName) return;

        delete attr[IS_LINKED_TO_ARRAY];

        attrs[attrName] = { items: {} };
        attrs[attrName].items[itemName] = attr;
        attrs[attrName].role = 'object';
    }

    exports.crawl(attrs, callback);
}

// this can take around 10ms and should only be run from PlotSchema.get(),
// to ensure JSON.stringify(PlotSchema.get()) gives the intended result.
function stringify(attrs) {
    function walk(attr) {
        for(var k in attr) {
            if(isPlainObject(attr[k])) {
                walk(attr[k]);
            } else if(Array.isArray(attr[k])) {
                for(var i = 0; i < attr[k].length; i++) {
                    walk(attr[k][i]);
                }
            } else {
                // as JSON.stringify(/test/) // => {}
                if(attr[k] instanceof RegExp) {
                    attr[k] = attr[k].toString();
                }
            }
        }
    }

    walk(attrs);
}

function assignPolarLayoutAttrs(layoutAttributes) {
    extendFlat(layoutAttributes, {
        radialaxis: polarAxisAttrs.radialaxis,
        angularaxis: polarAxisAttrs.angularaxis
    });

    extendFlat(layoutAttributes, polarAxisAttrs.layout);

    return layoutAttributes;
}

function handleBasePlotModule(layoutAttributes, _module, astr) {
    var np = Lib.nestedProperty(layoutAttributes, astr);
    var attrs = extendDeepAll({}, _module.layoutAttributes);

    attrs[IS_SUBPLOT_OBJ] = true;
    np.set(attrs);
}

function insertAttrs(baseAttrs, newAttrs, astr) {
    var np = Lib.nestedProperty(baseAttrs, astr);

    np.set(extendDeepAll(np.get() || {}, newAttrs));
}

},{"../lib":697,"../plots/animation_attributes":740,"../plots/attributes":742,"../plots/frame_attributes":772,"../plots/layout_attributes":798,"../plots/polar/legacy/area_attributes":813,"../plots/polar/legacy/axis_attributes":814,"../registry":826,"./edit_types":728,"./plot_config":733}],735:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../lib');
var plotAttributes = _dereq_('../plots/attributes');

var TEMPLATEITEMNAME = 'templateitemname';

var templateAttrs = {
    name: {
        valType: 'string',
        
        editType: 'none',
        
    }
};
templateAttrs[TEMPLATEITEMNAME] = {
    valType: 'string',
    
    editType: 'calc',
    
};

/**
 * templatedArray: decorate an attributes object with templating (and array)
 * properties.
 *
 * @param {string} name: the singular form of the array name. Sets
 *     `_isLinkedToArray` to this, so the schema knows to treat this as an array.
 * @param {object} attrs: the item attributes. Since all callers are expected
 *     to be constructing this object on the spot, we mutate it here for
 *     performance, rather than extending a new object with it.
 *
 * @returns {object}: the decorated `attrs` object
 */
exports.templatedArray = function(name, attrs) {
    attrs._isLinkedToArray = name;
    attrs.name = templateAttrs.name;
    attrs[TEMPLATEITEMNAME] = templateAttrs[TEMPLATEITEMNAME];
    return attrs;
};

/**
 * traceTemplater: logic for matching traces to trace templates
 *
 * @param {object} dataTemplate: collection of {traceType: [{template}, ...]}
 *     ie each type the template applies to contains a list of template objects,
 *     to be provided cyclically to data traces of that type.
 *
 * @returns {object}: {newTrace}, a function:
 *     newTrace(traceIn): that takes the input traceIn, coerces its type, then
 *         uses that type to find the next template to apply. returns the output
 *         traceOut with template attached, ready to continue supplyDefaults.
 */
exports.traceTemplater = function(dataTemplate) {
    var traceCounts = {};
    var traceType, typeTemplates;

    for(traceType in dataTemplate) {
        typeTemplates = dataTemplate[traceType];
        if(Array.isArray(typeTemplates) && typeTemplates.length) {
            traceCounts[traceType] = 0;
        }
    }

    function newTrace(traceIn) {
        traceType = Lib.coerce(traceIn, {}, plotAttributes, 'type');
        var traceOut = {type: traceType, _template: null};
        if(traceType in traceCounts) {
            typeTemplates = dataTemplate[traceType];
            // cycle through traces in the template set for this type
            var typei = traceCounts[traceType] % typeTemplates.length;
            traceCounts[traceType]++;
            traceOut._template = typeTemplates[typei];
        }
        else {
            // TODO: anything we should do for types missing from the template?
            // try to apply some other type? Or just bail as we do here?
            // Actually I think yes, we should apply other types; would be nice
            // if all scatter* could inherit from each other, and if histogram
            // could inherit from bar, etc... but how to specify this? And do we
            // compose them, or if a type is present require it to be complete?
            // Actually this could apply to layout too - 3D annotations
            // inheriting from 2D, axes of different types inheriting from each
            // other...
        }
        return traceOut;
    }

    return {
        newTrace: newTrace
        // TODO: function to figure out what's left & what didn't work
    };
};

/**
 * newContainer: Create a new sub-container inside `container` and propagate any
 * applicable template to it. If there's no template, still propagates
 * `undefined` so relinkPrivate will not retain an old template!
 *
 * @param {object} container: the outer container, should already have _template
 *     if there *is* a template for this plot
 * @param {string} name: the key of the new container to make
 * @param {string} baseName: if applicable, a base attribute to take the
 *     template from, ie for xaxis3 the base would be xaxis
 *
 * @returns {object}: an object for inclusion _full*, empty except for the
 *     appropriate template piece
 */
exports.newContainer = function(container, name, baseName) {
    var template = container._template;
    var part = template && (template[name] || (baseName && template[baseName]));
    if(!Lib.isPlainObject(part)) part = null;

    var out = container[name] = {_template: part};
    return out;
};

/**
 * arrayTemplater: special logic for templating both defaults and specific items
 * in a container array (annotations etc)
 *
 * @param {object} container: the outer container, should already have _template
 *     if there *is* a template for this plot
 * @param {string} name: the name of the array to template (ie 'annotations')
 *     will be used to find default ('annotationdefaults' object) and specific
 *     ('annotations' array) template specs.
 * @param {string} inclusionAttr: the attribute determining this item's
 *     inclusion in the output, usually 'visible' or 'enabled'
 *
 * @returns {object}: {newItem, defaultItems}, both functions:
 *     newItem(itemIn): create an output item, bare except for the correct
 *         template and name(s), as the base for supplyDefaults
 *     defaultItems(): to be called after all newItem calls, return any
 *         specific template items that have not already beeen included,
 *         also as bare output items ready for supplyDefaults.
 */
exports.arrayTemplater = function(container, name, inclusionAttr) {
    var template = container._template;
    var defaultsTemplate = template && template[arrayDefaultKey(name)];
    var templateItems = template && template[name];
    if(!Array.isArray(templateItems) || !templateItems.length) {
        templateItems = [];
    }

    var usedNames = {};

    function newItem(itemIn) {
        // include name and templateitemname in the output object for ALL
        // container array items. Note: you could potentially use different
        // name and templateitemname, if you're using one template to make
        // another template. templateitemname would be the name in the original
        // template, and name is the new "subclassed" item name.
        var out = {name: itemIn.name, _input: itemIn};
        var templateItemName = out[TEMPLATEITEMNAME] = itemIn[TEMPLATEITEMNAME];

        // no itemname: use the default template
        if(!validItemName(templateItemName)) {
            out._template = defaultsTemplate;
            return out;
        }

        // look for an item matching this itemname
        // note these do not inherit from the default template, only the item.
        for(var i = 0; i < templateItems.length; i++) {
            var templateItem = templateItems[i];
            if(templateItem.name === templateItemName) {
                // Note: it's OK to use a template item more than once
                // but using it at least once will stop it from generating
                // a default item at the end.
                usedNames[templateItemName] = 1;
                out._template = templateItem;
                return out;
            }
        }

        // Didn't find a matching template item, so since this item is intended
        // to only be modifications it's most likely broken. Hide it unless
        // it's explicitly marked visible - in which case it gets NO template,
        // not even the default.
        out[inclusionAttr] = itemIn[inclusionAttr] || false;
        // special falsy value we can look for in validateTemplate
        out._template = false;
        return out;
    }

    function defaultItems() {
        var out = [];
        for(var i = 0; i < templateItems.length; i++) {
            var templateItem = templateItems[i];
            var name = templateItem.name;
            // only allow named items to be added as defaults,
            // and only allow each name once
            if(validItemName(name) && !usedNames[name]) {
                var outi = {
                    _template: templateItem,
                    name: name,
                    _input: {_templateitemname: name}
                };
                outi[TEMPLATEITEMNAME] = templateItem[TEMPLATEITEMNAME];
                out.push(outi);
                usedNames[name] = 1;
            }
        }
        return out;
    }

    return {
        newItem: newItem,
        defaultItems: defaultItems
    };
};

function validItemName(name) {
    return name && typeof name === 'string';
}

function arrayDefaultKey(name) {
    var lastChar = name.length - 1;
    if(name.charAt(lastChar) !== 's') {
        Lib.warn('bad argument to arrayDefaultKey: ' + name);
    }
    return name.substr(0, name.length - 1) + 'defaults';
}
exports.arrayDefaultKey = arrayDefaultKey;

/**
 * arrayEditor: helper for editing array items that may have come from
 *     template defaults (in which case they will not exist in the input yet)
 *
 * @param {object} parentIn: the input container (eg gd.layout)
 * @param {string} containerStr: the attribute string for the container inside
 *     `parentIn`.
 * @param {object} itemOut: the _full* item (eg gd._fullLayout.annotations[0])
 *     that we'll be editing. Assumed to have been created by `arrayTemplater`.
 *
 * @returns {object}: {modifyBase, modifyItem, getUpdateObj, applyUpdate}, all functions:
 *     modifyBase(attr, value): Add an update that's *not* related to the item.
 *         `attr` is the full attribute string.
 *     modifyItem(attr, value): Add an update to the item. `attr` is just the
 *         portion of the attribute string inside the item.
 *     getUpdateObj(): Get the final constructed update object, to use in
 *         `restyle` or `relayout`. Also resets the update object in case this
 *         update was canceled.
 *     applyUpdate(attr, value): optionally add an update `attr: value`,
 *         then apply it to `parent` which should be the parent of `containerIn`,
 *         ie the object to which `containerStr` is the attribute string.
 */
exports.arrayEditor = function(parentIn, containerStr, itemOut) {
    var lengthIn = (Lib.nestedProperty(parentIn, containerStr).get() || []).length;
    var index = itemOut._index;
    // Check that we are indeed off the end of this container.
    // Otherwise a devious user could put a key `_templateitemname` in their
    // own input and break lots of things.
    var templateItemName = (index >= lengthIn) && (itemOut._input || {})._templateitemname;
    if(templateItemName) index = lengthIn;
    var itemStr = containerStr + '[' + index + ']';

    var update;
    function resetUpdate() {
        update = {};
        if(templateItemName) {
            update[itemStr] = {};
            update[itemStr][TEMPLATEITEMNAME] = templateItemName;
        }
    }
    resetUpdate();

    function modifyBase(attr, value) {
        update[attr] = value;
    }

    function modifyItem(attr, value) {
        if(templateItemName) {
            // we're making a new object: edit that object
            Lib.nestedProperty(update[itemStr], attr).set(value);
        }
        else {
            // we're editing an existing object: include *just* the edit
            update[itemStr + '.' + attr] = value;
        }
    }

    function getUpdateObj() {
        var updateOut = update;
        resetUpdate();
        return updateOut;
    }

    function applyUpdate(attr, value) {
        if(attr) modifyItem(attr, value);
        var updateToApply = getUpdateObj();
        for(var key in updateToApply) {
            Lib.nestedProperty(parentIn, key).set(updateToApply[key]);
        }
    }

    return {
        modifyBase: modifyBase,
        modifyItem: modifyItem,
        getUpdateObj: getUpdateObj,
        applyUpdate: applyUpdate
    };
};

},{"../lib":697,"../plots/attributes":742}],736:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var Registry = _dereq_('../registry');
var Plots = _dereq_('../plots/plots');

var Lib = _dereq_('../lib');
var clearGlCanvases = _dereq_('../lib/clear_gl_canvases');

var Color = _dereq_('../components/color');
var Drawing = _dereq_('../components/drawing');
var Titles = _dereq_('../components/titles');
var ModeBar = _dereq_('../components/modebar');

var Axes = _dereq_('../plots/cartesian/axes');
var alignmentConstants = _dereq_('../constants/alignment');
var axisConstraints = _dereq_('../plots/cartesian/constraints');
var enforceAxisConstraints = axisConstraints.enforce;
var cleanAxisConstraints = axisConstraints.clean;
var doAutoRange = _dereq_('../plots/cartesian/autorange').doAutoRange;

var SVG_TEXT_ANCHOR_START = 'start';
var SVG_TEXT_ANCHOR_MIDDLE = 'middle';
var SVG_TEXT_ANCHOR_END = 'end';

exports.layoutStyles = function(gd) {
    return Lib.syncOrAsync([Plots.doAutoMargin, lsInner], gd);
};

function overlappingDomain(xDomain, yDomain, domains) {
    for(var i = 0; i < domains.length; i++) {
        var existingX = domains[i][0];
        var existingY = domains[i][1];

        if(existingX[0] >= xDomain[1] || existingX[1] <= xDomain[0]) {
            continue;
        }
        if(existingY[0] < yDomain[1] && existingY[1] > yDomain[0]) {
            return true;
        }
    }
    return false;
}

function lsInner(gd) {
    var fullLayout = gd._fullLayout;
    var gs = fullLayout._size;
    var pad = gs.p;
    var axList = Axes.list(gd, '', true);
    var i, subplot, plotinfo, ax, xa, ya;

    fullLayout._paperdiv.style({
        width: (gd._context.responsive && fullLayout.autosize && !gd._context._hasZeroWidth && !gd.layout.width) ? '100%' : fullLayout.width + 'px',
        height: (gd._context.responsive && fullLayout.autosize && !gd._context._hasZeroHeight && !gd.layout.height) ? '100%' : fullLayout.height + 'px'
    })
    .selectAll('.main-svg')
    .call(Drawing.setSize, fullLayout.width, fullLayout.height);
    gd._context.setBackground(gd, fullLayout.paper_bgcolor);

    exports.drawMainTitle(gd);
    ModeBar.manage(gd);

    // _has('cartesian') means SVG specifically, not GL2D - but GL2D
    // can still get here because it makes some of the SVG structure
    // for shared features like selections.
    if(!fullLayout._has('cartesian')) {
        return gd._promises.length && Promise.all(gd._promises);
    }

    function getLinePosition(ax, counterAx, side) {
        var lwHalf = ax._lw / 2;

        if(ax._id.charAt(0) === 'x') {
            if(!counterAx) return gs.t + gs.h * (1 - (ax.position || 0)) + (lwHalf % 1);
            else if(side === 'top') return counterAx._offset - pad - lwHalf;
            return counterAx._offset + counterAx._length + pad + lwHalf;
        }

        if(!counterAx) return gs.l + gs.w * (ax.position || 0) + (lwHalf % 1);
        else if(side === 'right') return counterAx._offset + counterAx._length + pad + lwHalf;
        return counterAx._offset - pad - lwHalf;
    }

    // some preparation of axis position info
    for(i = 0; i < axList.length; i++) {
        ax = axList[i];

        var counterAx = ax._anchorAxis;

        // clear axis line positions, to be set in the subplot loop below
        ax._linepositions = {};

        // stash crispRounded linewidth so we don't need to pass gd all over the place
        ax._lw = Drawing.crispRound(gd, ax.linewidth, 1);

        // figure out the main axis line and main mirror line position.
        // it's easier to follow the logic if we handle these separately from
        // ax._linepositions, which are only used by mirror=allticks
        // for non-main-subplot ticks, and mirror=all(ticks)? for zero line
        // hiding logic
        ax._mainLinePosition = getLinePosition(ax, counterAx, ax.side);
        ax._mainMirrorPosition = (ax.mirror && counterAx) ?
            getLinePosition(ax, counterAx,
                alignmentConstants.OPPOSITE_SIDE[ax.side]) : null;
    }

    // figure out which backgrounds we need to draw,
    // and in which layers to put them
    var lowerBackgroundIDs = [];
    var backgroundIds = [];
    var lowerDomains = [];
    // no need to draw background when paper and plot color are the same color,
    // activate mode just for large splom (which benefit the most from this
    // optimization), but this could apply to all cartesian subplots.
    var noNeedForBg = (
        Color.opacity(fullLayout.paper_bgcolor) === 1 &&
        Color.opacity(fullLayout.plot_bgcolor) === 1 &&
        fullLayout.paper_bgcolor === fullLayout.plot_bgcolor
    );

    for(subplot in fullLayout._plots) {
        plotinfo = fullLayout._plots[subplot];

        if(plotinfo.mainplot) {
            // mainplot is a reference to the main plot this one is overlaid on
            // so if it exists, this is an overlaid plot and we don't need to
            // give it its own background
            if(plotinfo.bg) {
                plotinfo.bg.remove();
            }
            plotinfo.bg = undefined;
        } else {
            var xDomain = plotinfo.xaxis.domain;
            var yDomain = plotinfo.yaxis.domain;
            var plotgroup = plotinfo.plotgroup;

            if(overlappingDomain(xDomain, yDomain, lowerDomains)) {
                var pgNode = plotgroup.node();
                var plotgroupBg = plotinfo.bg = Lib.ensureSingle(plotgroup, 'rect', 'bg');
                pgNode.insertBefore(plotgroupBg.node(), pgNode.childNodes[0]);
                backgroundIds.push(subplot);
            } else {
                plotgroup.select('rect.bg').remove();
                lowerDomains.push([xDomain, yDomain]);
                if(!noNeedForBg) {
                    lowerBackgroundIDs.push(subplot);
                    backgroundIds.push(subplot);
                }
            }
        }
    }

    // now create all the lower-layer backgrounds at once now that
    // we have the list of subplots that need them
    var lowerBackgrounds = fullLayout._bgLayer.selectAll('.bg')
        .data(lowerBackgroundIDs);

    lowerBackgrounds.enter().append('rect')
        .classed('bg', true);

    lowerBackgrounds.exit().remove();

    lowerBackgrounds.each(function(subplot) {
        fullLayout._plots[subplot].bg = d3.select(this);
    });

    // style all backgrounds
    for(i = 0; i < backgroundIds.length; i++) {
        plotinfo = fullLayout._plots[backgroundIds[i]];
        xa = plotinfo.xaxis;
        ya = plotinfo.yaxis;

        if(plotinfo.bg) {
            plotinfo.bg
                .call(Drawing.setRect,
                    xa._offset - pad, ya._offset - pad,
                    xa._length + 2 * pad, ya._length + 2 * pad)
                .call(Color.fill, fullLayout.plot_bgcolor)
                .style('stroke-width', 0);
        }
    }

    if(!fullLayout._hasOnlyLargeSploms) {
        for(subplot in fullLayout._plots) {
            plotinfo = fullLayout._plots[subplot];
            xa = plotinfo.xaxis;
            ya = plotinfo.yaxis;

            // Clip so that data only shows up on the plot area.
            var clipId = plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot';

            var plotClip = Lib.ensureSingleById(fullLayout._clips, 'clipPath', clipId, function(s) {
                s.classed('plotclip', true)
                    .append('rect');
            });

            plotinfo.clipRect = plotClip.select('rect').attr({
                width: xa._length,
                height: ya._length
            });

            Drawing.setTranslate(plotinfo.plot, xa._offset, ya._offset);

            var plotClipId;
            var layerClipId;

            if(plotinfo._hasClipOnAxisFalse) {
                plotClipId = null;
                layerClipId = clipId;
            } else {
                plotClipId = clipId;
                layerClipId = null;
            }

            Drawing.setClipUrl(plotinfo.plot, plotClipId, gd);

            // stash layer clipId value (null or same as clipId)
            // to DRY up Drawing.setClipUrl calls on trace-module and trace layers
            // downstream
            plotinfo.layerClipId = layerClipId;
        }
    }

    var xLinesXLeft, xLinesXRight, xLinesYBottom, xLinesYTop,
        leftYLineWidth, rightYLineWidth;
    var yLinesYBottom, yLinesYTop, yLinesXLeft, yLinesXRight,
        connectYBottom, connectYTop;
    var extraSubplot;

    function xLinePath(y) {
        return 'M' + xLinesXLeft + ',' + y + 'H' + xLinesXRight;
    }

    function xLinePathFree(y) {
        return 'M' + xa._offset + ',' + y + 'h' + xa._length;
    }

    function yLinePath(x) {
        return 'M' + x + ',' + yLinesYTop + 'V' + yLinesYBottom;
    }

    function yLinePathFree(x) {
        return 'M' + x + ',' + ya._offset + 'v' + ya._length;
    }

    function mainPath(ax, pathFn, pathFnFree) {
        if(!ax.showline || subplot !== ax._mainSubplot) return '';
        if(!ax._anchorAxis) return pathFnFree(ax._mainLinePosition);
        var out = pathFn(ax._mainLinePosition);
        if(ax.mirror) out += pathFn(ax._mainMirrorPosition);
        return out;
    }

    for(subplot in fullLayout._plots) {
        plotinfo = fullLayout._plots[subplot];
        xa = plotinfo.xaxis;
        ya = plotinfo.yaxis;

        /*
         * x lines get longer where they meet y lines, to make a crisp corner.
         * The x lines get the padding (margin.pad) plus the y line width to
         * fill up the corner nicely. Free x lines are excluded - they always
         * span exactly the data area of the plot
         *
         *  | XXXXX
         *  | XXXXX
         *  |
         *  +------
         *     x1
         *    -----
         *     x2
         */
        var xPath = 'M0,0';
        if(shouldShowLinesOrTicks(xa, subplot)) {
            leftYLineWidth = findCounterAxisLineWidth(xa, 'left', ya, axList);
            xLinesXLeft = xa._offset - (leftYLineWidth ? (pad + leftYLineWidth) : 0);
            rightYLineWidth = findCounterAxisLineWidth(xa, 'right', ya, axList);
            xLinesXRight = xa._offset + xa._length + (rightYLineWidth ? (pad + rightYLineWidth) : 0);
            xLinesYBottom = getLinePosition(xa, ya, 'bottom');
            xLinesYTop = getLinePosition(xa, ya, 'top');

            // save axis line positions for extra ticks to reference
            // each subplot that gets ticks from "allticks" gets an entry:
            //    [left or bottom, right or top]
            extraSubplot = (!xa._anchorAxis || subplot !== xa._mainSubplot);
            if(extraSubplot && (xa.mirror === 'allticks' || xa.mirror === 'all')) {
                xa._linepositions[subplot] = [xLinesYBottom, xLinesYTop];
            }

            xPath = mainPath(xa, xLinePath, xLinePathFree);
            if(extraSubplot && xa.showline && (xa.mirror === 'all' || xa.mirror === 'allticks')) {
                xPath += xLinePath(xLinesYBottom) + xLinePath(xLinesYTop);
            }

            plotinfo.xlines
                .style('stroke-width', xa._lw + 'px')
                .call(Color.stroke, xa.showline ?
                    xa.linecolor : 'rgba(0,0,0,0)');
        }
        plotinfo.xlines.attr('d', xPath);

        /*
         * y lines that meet x axes get longer only by margin.pad, because
         * the x axes fill in the corner space. Free y axes, like free x axes,
         * always span exactly the data area of the plot
         *
         *   |   | XXXX
         * y2| y1| XXXX
         *   |   | XXXX
         *       |
         *       +-----
         */
        var yPath = 'M0,0';
        if(shouldShowLinesOrTicks(ya, subplot)) {
            connectYBottom = findCounterAxisLineWidth(ya, 'bottom', xa, axList);
            yLinesYBottom = ya._offset + ya._length + (connectYBottom ? pad : 0);
            connectYTop = findCounterAxisLineWidth(ya, 'top', xa, axList);
            yLinesYTop = ya._offset - (connectYTop ? pad : 0);
            yLinesXLeft = getLinePosition(ya, xa, 'left');
            yLinesXRight = getLinePosition(ya, xa, 'right');

            extraSubplot = (!ya._anchorAxis || subplot !== ya._mainSubplot);
            if(extraSubplot && (ya.mirror === 'allticks' || ya.mirror === 'all')) {
                ya._linepositions[subplot] = [yLinesXLeft, yLinesXRight];
            }

            yPath = mainPath(ya, yLinePath, yLinePathFree);
            if(extraSubplot && ya.showline && (ya.mirror === 'all' || ya.mirror === 'allticks')) {
                yPath += yLinePath(yLinesXLeft) + yLinePath(yLinesXRight);
            }

            plotinfo.ylines
                .style('stroke-width', ya._lw + 'px')
                .call(Color.stroke, ya.showline ?
                    ya.linecolor : 'rgba(0,0,0,0)');
        }
        plotinfo.ylines.attr('d', yPath);
    }

    Axes.makeClipPaths(gd);

    return gd._promises.length && Promise.all(gd._promises);
}

function shouldShowLinesOrTicks(ax, subplot) {
    return (ax.ticks || ax.showline) &&
        (subplot === ax._mainSubplot || ax.mirror === 'all' || ax.mirror === 'allticks');
}

/*
 * should we draw a line on counterAx at this side of ax?
 * It's assumed that counterAx is known to overlay the subplot we're working on
 * but it may not be its main axis.
 */
function shouldShowLineThisSide(ax, side, counterAx) {
    // does counterAx get a line at all?
    if(!counterAx.showline || !counterAx._lw) return false;

    // are we drawing *all* lines for counterAx?
    if(counterAx.mirror === 'all' || counterAx.mirror === 'allticks') return true;

    var anchorAx = counterAx._anchorAxis;

    // is this a free axis? free axes can only have a subplot side-line with all(ticks)? mirroring
    if(!anchorAx) return false;

    // in order to handle cases where the user forgot to anchor this axis correctly
    // (because its default anchor has the same domain on the relevant end)
    // check whether the relevant position is the same.
    var sideIndex = alignmentConstants.FROM_BL[side];
    if(counterAx.side === side) {
        return anchorAx.domain[sideIndex] === ax.domain[sideIndex];
    }
    return counterAx.mirror && anchorAx.domain[1 - sideIndex] === ax.domain[1 - sideIndex];
}

/*
 * Is there another axis intersecting `side` end of `ax`?
 * First look at `counterAx` (the axis for this subplot),
 * then at all other potential counteraxes on or overlaying this subplot.
 * Take the line width from the first one that has a line.
 */
function findCounterAxisLineWidth(ax, side, counterAx, axList) {
    if(shouldShowLineThisSide(ax, side, counterAx)) {
        return counterAx._lw;
    }
    for(var i = 0; i < axList.length; i++) {
        var axi = axList[i];
        if(axi._mainAxis === counterAx._mainAxis && shouldShowLineThisSide(ax, side, axi)) {
            return axi._lw;
        }
    }
    return 0;
}

exports.drawMainTitle = function(gd) {
    var fullLayout = gd._fullLayout;

    var textAnchor = getMainTitleTextAnchor(fullLayout);
    var dy = getMainTitleDy(fullLayout);

    Titles.draw(gd, 'gtitle', {
        propContainer: fullLayout,
        propName: 'title.text',
        placeholder: fullLayout._dfltTitle.plot,
        attributes: {
            x: getMainTitleX(fullLayout, textAnchor),
            y: getMainTitleY(fullLayout, dy),
            'text-anchor': textAnchor,
            dy: dy
        }
    });
};

function getMainTitleX(fullLayout, textAnchor) {
    var title = fullLayout.title;
    var gs = fullLayout._size;
    var hPadShift = 0;

    if(textAnchor === SVG_TEXT_ANCHOR_START) {
        hPadShift = title.pad.l;
    } else if(textAnchor === SVG_TEXT_ANCHOR_END) {
        hPadShift = -title.pad.r;
    }

    switch(title.xref) {
        case 'paper':
            return gs.l + gs.w * title.x + hPadShift;
        case 'container':
        default:
            return fullLayout.width * title.x + hPadShift;
    }
}

function getMainTitleY(fullLayout, dy) {
    var title = fullLayout.title;
    var gs = fullLayout._size;
    var vPadShift = 0;

    if(dy === '0em' || !dy) {
        vPadShift = -title.pad.b;
    } else if(dy === alignmentConstants.CAP_SHIFT + 'em') {
        vPadShift = title.pad.t;
    }

    if(title.y === 'auto') {
        return gs.t / 2;
    } else {
        switch(title.yref) {
            case 'paper':
                return gs.t + gs.h - gs.h * title.y + vPadShift;
            case 'container':
            default:
                return fullLayout.height - fullLayout.height * title.y + vPadShift;
        }
    }
}

function getMainTitleTextAnchor(fullLayout) {
    var title = fullLayout.title;

    var textAnchor = SVG_TEXT_ANCHOR_MIDDLE;
    if(Lib.isRightAnchor(title)) {
        textAnchor = SVG_TEXT_ANCHOR_END;
    } else if(Lib.isLeftAnchor(title)) {
        textAnchor = SVG_TEXT_ANCHOR_START;
    }

    return textAnchor;
}

function getMainTitleDy(fullLayout) {
    var title = fullLayout.title;

    var dy = '0em';
    if(Lib.isTopAnchor(title)) {
        dy = alignmentConstants.CAP_SHIFT + 'em';
    } else if(Lib.isMiddleAnchor(title)) {
        dy = alignmentConstants.MID_SHIFT + 'em';
    }

    return dy;
}

exports.doTraceStyle = function(gd) {
    var calcdata = gd.calcdata;
    var editStyleCalls = [];
    var i;

    for(i = 0; i < calcdata.length; i++) {
        var cd = calcdata[i];
        var cd0 = cd[0] || {};
        var trace = cd0.trace || {};
        var _module = trace._module || {};

        // See if we need to do arraysToCalcdata
        // call it regardless of what change we made, in case
        // supplyDefaults brought in an array that was already
        // in gd.data but not in gd._fullData previously
        var arraysToCalcdata = _module.arraysToCalcdata;
        if(arraysToCalcdata) arraysToCalcdata(cd, trace);

        var editStyle = _module.editStyle;
        if(editStyle) editStyleCalls.push({fn: editStyle, cd0: cd0});
    }

    if(editStyleCalls.length) {
        for(i = 0; i < editStyleCalls.length; i++) {
            var edit = editStyleCalls[i];
            edit.fn(gd, edit.cd0);
        }
        clearGlCanvases(gd);
        exports.redrawReglTraces(gd);
    }

    Plots.style(gd);
    Registry.getComponentMethod('legend', 'draw')(gd);

    return Plots.previousPromises(gd);
};

exports.doColorBars = function(gd) {
    for(var i = 0; i < gd.calcdata.length; i++) {
        var cdi0 = gd.calcdata[i][0];

        if((cdi0.t || {}).cb) {
            var trace = cdi0.trace;
            var cb = cdi0.t.cb;

            if(Registry.traceIs(trace, 'contour')) {
                cb.line({
                    width: trace.contours.showlines !== false ?
                        trace.line.width : 0,
                    dash: trace.line.dash,
                    color: trace.contours.coloring === 'line' ?
                        cb._opts.line.color : trace.line.color
                });
            }
            var moduleOpts = trace._module.colorbar;
            var containerName = moduleOpts.container;
            var opts = (containerName ? trace[containerName] : trace).colorbar;
            cb.options(opts)();
        }
    }

    return Plots.previousPromises(gd);
};

// force plot() to redo the layout and replot with the modified layout
exports.layoutReplot = function(gd) {
    var layout = gd.layout;
    gd.layout = undefined;
    return Registry.call('plot', gd, '', layout);
};

exports.doLegend = function(gd) {
    Registry.getComponentMethod('legend', 'draw')(gd);
    return Plots.previousPromises(gd);
};

exports.doTicksRelayout = function(gd) {
    Axes.draw(gd, 'redraw');

    if(gd._fullLayout._hasOnlyLargeSploms) {
        Registry.subplotsRegistry.splom.updateGrid(gd);
        clearGlCanvases(gd);
        exports.redrawReglTraces(gd);
    }

    exports.drawMainTitle(gd);
    return Plots.previousPromises(gd);
};

exports.doModeBar = function(gd) {
    var fullLayout = gd._fullLayout;

    ModeBar.manage(gd);

    for(var i = 0; i < fullLayout._basePlotModules.length; i++) {
        var updateFx = fullLayout._basePlotModules[i].updateFx;
        if(updateFx) updateFx(gd);
    }

    return Plots.previousPromises(gd);
};

exports.doCamera = function(gd) {
    var fullLayout = gd._fullLayout;
    var sceneIds = fullLayout._subplots.gl3d;

    for(var i = 0; i < sceneIds.length; i++) {
        var sceneLayout = fullLayout[sceneIds[i]];
        var scene = sceneLayout._scene;

        var cameraData = sceneLayout.camera;
        scene.setCamera(cameraData);
    }
};

exports.drawData = function(gd) {
    var fullLayout = gd._fullLayout;
    var calcdata = gd.calcdata;
    var i;

    // remove old colorbars explicitly
    for(i = 0; i < calcdata.length; i++) {
        var trace = calcdata[i][0].trace;
        if(trace.visible !== true || !trace._module.colorbar) {
            fullLayout._infolayer.select('.cb' + trace.uid).remove();
        }
    }

    clearGlCanvases(gd);

    // loop over the base plot modules present on graph
    var basePlotModules = fullLayout._basePlotModules;
    for(i = 0; i < basePlotModules.length; i++) {
        basePlotModules[i].plot(gd);
    }

    exports.redrawReglTraces(gd);

    // styling separate from drawing
    Plots.style(gd);

    // show annotations and shapes
    Registry.getComponentMethod('shapes', 'draw')(gd);
    Registry.getComponentMethod('annotations', 'draw')(gd);

    // Mark the first render as complete
    fullLayout._replotting = false;

    return Plots.previousPromises(gd);
};

// Draw (or redraw) all regl-based traces in one go,
// useful during drag and selection where buffers of targeted traces are updated,
// but all traces need to be redrawn following clearGlCanvases.
//
// Note that _module.plot for regl trace does NOT draw things
// on the canvas, they only update the buffers.
// Drawing is perform here.
//
// TODO try adding per-subplot option using gl.SCISSOR_TEST for
// non-overlaying, disjoint subplots.
//
// TODO try to include parcoords in here.
// https://github.com/plotly/plotly.js/issues/3069
exports.redrawReglTraces = function(gd) {
    var fullLayout = gd._fullLayout;

    if(fullLayout._has('regl')) {
        var fullData = gd._fullData;
        var cartesianIds = [];
        var polarIds = [];
        var i, sp;

        if(fullLayout._hasOnlyLargeSploms) {
            fullLayout._splomGrid.draw();
        }

        // N.B.
        // - Loop over fullData (not _splomScenes) to preserve splom trace-to-trace ordering
        // - Fill list if subplot ids (instead of fullLayout._subplots) to handle cases where all traces
        //   of a given module are `visible !== true`
        for(i = 0; i < fullData.length; i++) {
            var trace = fullData[i];

            if(trace.visible === true) {
                if(trace.type === 'splom') {
                    fullLayout._splomScenes[trace.uid].draw();
                } else if(trace.type === 'scattergl') {
                    Lib.pushUnique(cartesianIds, trace.xaxis + trace.yaxis);
                } else if(trace.type === 'scatterpolargl') {
                    Lib.pushUnique(polarIds, trace.subplot);
                }
            }
        }

        for(i = 0; i < cartesianIds.length; i++) {
            sp = fullLayout._plots[cartesianIds[i]];
            if(sp._scene) sp._scene.draw();
        }

        for(i = 0; i < polarIds.length; i++) {
            sp = fullLayout[polarIds[i]]._subplot;
            if(sp._scene) sp._scene.draw();
        }
    }
};

exports.doAutoRangeAndConstraints = function(gd) {
    var fullLayout = gd._fullLayout;
    var axList = Axes.list(gd, '', true);
    var matchGroups = fullLayout._axisMatchGroups || [];
    var ax;

    for(var i = 0; i < axList.length; i++) {
        ax = axList[i];
        cleanAxisConstraints(gd, ax);
        doAutoRange(gd, ax);
    }

    enforceAxisConstraints(gd);

    groupLoop:
    for(var j = 0; j < matchGroups.length; j++) {
        var group = matchGroups[j];
        var rng = null;
        var id;

        for(id in group) {
            ax = Axes.getFromId(gd, id);
            if(ax.autorange === false) continue groupLoop;

            if(rng) {
                if(rng[0] < rng[1]) {
                    rng[0] = Math.min(rng[0], ax.range[0]);
                    rng[1] = Math.max(rng[1], ax.range[1]);
                } else {
                    rng[0] = Math.max(rng[0], ax.range[0]);
                    rng[1] = Math.min(rng[1], ax.range[1]);
                }
            } else {
                rng = ax.range;
            }
        }

        for(id in group) {
            ax = Axes.getFromId(gd, id);
            ax.range = rng.slice();
            ax._input.range = rng.slice();
            ax.setScale();
        }
    }
};

// An initial paint must be completed before these components can be
// correctly sized and the whole plot re-margined. fullLayout._replotting must
// be set to false before these will work properly.
exports.finalDraw = function(gd) {
    Registry.getComponentMethod('shapes', 'draw')(gd);
    Registry.getComponentMethod('images', 'draw')(gd);
    Registry.getComponentMethod('annotations', 'draw')(gd);
    // TODO: rangesliders really belong in marginPushers but they need to be
    // drawn after data - can we at least get the margin pushing part separated
    // out and done earlier?
    Registry.getComponentMethod('rangeslider', 'draw')(gd);
    // TODO: rangeselector only needs to be here (in addition to drawMarginPushers)
    // because the margins need to be fully determined before we can call
    // autorange and update axis ranges (which rangeselector needs to know which
    // button is active). Can we break out its automargin step from its draw step?
    Registry.getComponentMethod('rangeselector', 'draw')(gd);
};

exports.drawMarginPushers = function(gd) {
    Registry.getComponentMethod('legend', 'draw')(gd);
    Registry.getComponentMethod('rangeselector', 'draw')(gd);
    Registry.getComponentMethod('sliders', 'draw')(gd);
    Registry.getComponentMethod('updatemenus', 'draw')(gd);
};

},{"../components/color":574,"../components/drawing":595,"../components/modebar":633,"../components/titles":662,"../constants/alignment":669,"../lib":697,"../lib/clear_gl_canvases":682,"../plots/cartesian/autorange":744,"../plots/cartesian/axes":745,"../plots/cartesian/constraints":752,"../plots/plots":807,"../registry":826,"d3":151}],737:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../lib');
var isPlainObject = Lib.isPlainObject;
var PlotSchema = _dereq_('./plot_schema');
var Plots = _dereq_('../plots/plots');
var plotAttributes = _dereq_('../plots/attributes');
var Template = _dereq_('./plot_template');
var dfltConfig = _dereq_('./plot_config').dfltConfig;

/**
 * Plotly.makeTemplate: create a template off an existing figure to reuse
 * style attributes on other figures.
 *
 * Note: separated from the rest of templates because otherwise we get circular
 * references due to PlotSchema.
 *
 * @param {object|DOM element|string} figure: The figure to base the template on
 *     should contain a trace array `figure.data`
 *     and a layout object `figure.layout`
 * @returns {object} template: the extracted template - can then be used as
 *     `layout.template` in another figure.
 */
exports.makeTemplate = function(figure) {
    figure = Lib.isPlainObject(figure) ? figure : Lib.getGraphDiv(figure);
    figure = Lib.extendDeep({_context: dfltConfig}, {data: figure.data, layout: figure.layout});
    Plots.supplyDefaults(figure);
    var data = figure.data || [];
    var layout = figure.layout || {};
    // copy over a few items to help follow the schema
    layout._basePlotModules = figure._fullLayout._basePlotModules;
    layout._modules = figure._fullLayout._modules;

    var template = {
        data: {},
        layout: {}
    };

    /*
     * Note: we do NOT validate template values, we just take what's in the
     * user inputs data and layout, not the validated values in fullData and
     * fullLayout. Even if we were to validate here, there's no guarantee that
     * these values would still be valid when applied to a new figure, which
     * may contain different trace modes, different axes, etc. So it's
     * important that when applying a template we still validate the template
     * values, rather than just using them as defaults.
     */

    data.forEach(function(trace) {
        // TODO: What if no style info is extracted for this trace. We may
        // not want an empty object as the null value.
        // TODO: allow transforms to contribute to templates?
        // as it stands they are ignored, which may be for the best...

        var traceTemplate = {};
        walkStyleKeys(trace, traceTemplate, getTraceInfo.bind(null, trace));

        var traceType = Lib.coerce(trace, {}, plotAttributes, 'type');
        var typeTemplates = template.data[traceType];
        if(!typeTemplates) typeTemplates = template.data[traceType] = [];
        typeTemplates.push(traceTemplate);
    });

    walkStyleKeys(layout, template.layout, getLayoutInfo.bind(null, layout));

    /*
     * Compose the new template with an existing one to the same effect
     *
     * NOTE: there's a possibility of slightly different behavior: if the plot
     * has an invalid value and the old template has a valid value for the same
     * attribute, the plot will use the old template value but this routine
     * will pull the invalid value (resulting in the original default).
     * In the general case it's not possible to solve this with a single value,
     * since valid options can be context-dependent. It could be solved with
     * a *list* of values, but that would be huge complexity for little gain.
     */
    delete template.layout.template;
    var oldTemplate = layout.template;
    if(isPlainObject(oldTemplate)) {
        var oldLayoutTemplate = oldTemplate.layout;

        var i, traceType, oldTypeTemplates, oldTypeLen, typeTemplates, typeLen;

        if(isPlainObject(oldLayoutTemplate)) {
            mergeTemplates(oldLayoutTemplate, template.layout);
        }
        var oldDataTemplate = oldTemplate.data;
        if(isPlainObject(oldDataTemplate)) {
            for(traceType in template.data) {
                oldTypeTemplates = oldDataTemplate[traceType];
                if(Array.isArray(oldTypeTemplates)) {
                    typeTemplates = template.data[traceType];
                    typeLen = typeTemplates.length;
                    oldTypeLen = oldTypeTemplates.length;
                    for(i = 0; i < typeLen; i++) {
                        mergeTemplates(oldTypeTemplates[i % oldTypeLen], typeTemplates[i]);
                    }
                    for(i = typeLen; i < oldTypeLen; i++) {
                        typeTemplates.push(Lib.extendDeep({}, oldTypeTemplates[i]));
                    }
                }
            }
            for(traceType in oldDataTemplate) {
                if(!(traceType in template.data)) {
                    template.data[traceType] = Lib.extendDeep([], oldDataTemplate[traceType]);
                }
            }
        }
    }

    return template;
};

function mergeTemplates(oldTemplate, newTemplate) {
    // we don't care about speed here, just make sure we have a totally
    // distinct object from the previous template
    oldTemplate = Lib.extendDeep({}, oldTemplate);

    // sort keys so we always get annotationdefaults before annotations etc
    // so arrayTemplater will work right
    var oldKeys = Object.keys(oldTemplate).sort();
    var i, j;

    function mergeOne(oldVal, newVal, key) {
        if(isPlainObject(newVal) && isPlainObject(oldVal)) {
            mergeTemplates(oldVal, newVal);
        }
        else if(Array.isArray(newVal) && Array.isArray(oldVal)) {
            // Note: omitted `inclusionAttr` from arrayTemplater here,
            // it's irrelevant as we only want the resulting `_template`.
            var templater = Template.arrayTemplater({_template: oldTemplate}, key);
            for(j = 0; j < newVal.length; j++) {
                var item = newVal[j];
                var oldItem = templater.newItem(item)._template;
                if(oldItem) mergeTemplates(oldItem, item);
            }
            var defaultItems = templater.defaultItems();
            for(j = 0; j < defaultItems.length; j++) newVal.push(defaultItems[j]._template);

            // templateitemname only applies to receiving plots
            for(j = 0; j < newVal.length; j++) delete newVal[j].templateitemname;
        }
    }

    for(i = 0; i < oldKeys.length; i++) {
        var key = oldKeys[i];
        var oldVal = oldTemplate[key];
        if(key in newTemplate) {
            mergeOne(oldVal, newTemplate[key], key);
        }
        else newTemplate[key] = oldVal;

        // if this is a base key from the old template (eg xaxis), look for
        // extended keys (eg xaxis2) in the new template to merge into
        if(getBaseKey(key) === key) {
            for(var key2 in newTemplate) {
                var baseKey2 = getBaseKey(key2);
                if(key2 !== baseKey2 && baseKey2 === key && !(key2 in oldTemplate)) {
                    mergeOne(oldVal, newTemplate[key2], key);
                }
            }
        }
    }
}

function getBaseKey(key) {
    return key.replace(/[0-9]+$/, '');
}

function walkStyleKeys(parent, templateOut, getAttributeInfo, path, basePath) {
    var pathAttr = basePath && getAttributeInfo(basePath);
    for(var key in parent) {
        var child = parent[key];
        var nextPath = getNextPath(parent, key, path);
        var nextBasePath = getNextPath(parent, key, basePath);
        var attr = getAttributeInfo(nextBasePath);
        if(!attr) {
            var baseKey = getBaseKey(key);
            if(baseKey !== key) {
                nextBasePath = getNextPath(parent, baseKey, basePath);
                attr = getAttributeInfo(nextBasePath);
            }
        }

        // we'll get an attr if path starts with a valid part, then has an
        // invalid ending. Make sure we got all the way to the end.
        if(pathAttr && (pathAttr === attr)) continue;

        if(!attr || attr._noTemplating ||
            attr.valType === 'data_array' ||
            (attr.arrayOk && Array.isArray(child))
        ) {
            continue;
        }

        if(!attr.valType && isPlainObject(child)) {
            walkStyleKeys(child, templateOut, getAttributeInfo, nextPath, nextBasePath);
        }
        else if(attr._isLinkedToArray && Array.isArray(child)) {
            var dfltDone = false;
            var namedIndex = 0;
            var usedNames = {};
            for(var i = 0; i < child.length; i++) {
                var item = child[i];
                if(isPlainObject(item)) {
                    var name = item.name;
                    if(name) {
                        if(!usedNames[name]) {
                            // named array items: allow all attributes except data arrays
                            walkStyleKeys(item, templateOut, getAttributeInfo,
                                getNextPath(child, namedIndex, nextPath),
                                getNextPath(child, namedIndex, nextBasePath));
                            namedIndex++;
                            usedNames[name] = 1;
                        }
                    }
                    else if(!dfltDone) {
                        var dfltKey = Template.arrayDefaultKey(key);
                        var dfltPath = getNextPath(parent, dfltKey, path);

                        // getAttributeInfo will fail if we try to use dfltKey directly.
                        // Instead put this item into the next array element, then
                        // pull it out and move it to dfltKey.
                        var pathInArray = getNextPath(child, namedIndex, nextPath);
                        walkStyleKeys(item, templateOut, getAttributeInfo, pathInArray,
                            getNextPath(child, namedIndex, nextBasePath));
                        var itemPropInArray = Lib.nestedProperty(templateOut, pathInArray);
                        var dfltProp = Lib.nestedProperty(templateOut, dfltPath);
                        dfltProp.set(itemPropInArray.get());
                        itemPropInArray.set(null);

                        dfltDone = true;
                    }
                }
            }
        }
        else {
            var templateProp = Lib.nestedProperty(templateOut, nextPath);
            templateProp.set(child);
        }
    }
}

function getLayoutInfo(layout, path) {
    return PlotSchema.getLayoutValObject(
        layout, Lib.nestedProperty({}, path).parts
    );
}

function getTraceInfo(trace, path) {
    return PlotSchema.getTraceValObject(
        trace, Lib.nestedProperty({}, path).parts
    );
}

function getNextPath(parent, key, path) {
    var nextPath;
    if(!path) nextPath = key;
    else if(Array.isArray(parent)) nextPath = path + '[' + key + ']';
    else nextPath = path + '.' + key;

    return nextPath;
}

/**
 * validateTemplate: Test for consistency between the given figure and
 * a template, either already included in the figure or given separately.
 * Note that not every issue we identify here is necessarily a problem,
 * it depends on what you're using the template for.
 *
 * @param {object|DOM element} figure: the plot, with {data, layout} members,
 *     to test the template against
 * @param {Optional(object)} template: the template, with its own {data, layout},
 *     to test. If omitted, we will look for a template already attached as the
 *     plot's `layout.template` attribute.
 *
 * @returns {array} array of error objects each containing:
 *  - {string} code
 *      error code ('missing', 'unused', 'reused', 'noLayout', 'noData')
 *  - {string} msg
 *      a full readable description of the issue.
 */
exports.validateTemplate = function(figureIn, template) {
    var figure = Lib.extendDeep({}, {
        _context: dfltConfig,
        data: figureIn.data,
        layout: figureIn.layout
    });
    var layout = figure.layout || {};
    if(!isPlainObject(template)) template = layout.template || {};
    var layoutTemplate = template.layout;
    var dataTemplate = template.data;
    var errorList = [];

    figure.layout = layout;
    figure.layout.template = template;
    Plots.supplyDefaults(figure);

    var fullLayout = figure._fullLayout;
    var fullData = figure._fullData;

    var layoutPaths = {};
    function crawlLayoutForContainers(obj, paths) {
        for(var key in obj) {
            if(key.charAt(0) !== '_' && isPlainObject(obj[key])) {
                var baseKey = getBaseKey(key);
                var nextPaths = [];
                var i;
                for(i = 0; i < paths.length; i++) {
                    nextPaths.push(getNextPath(obj, key, paths[i]));
                    if(baseKey !== key) nextPaths.push(getNextPath(obj, baseKey, paths[i]));
                }
                for(i = 0; i < nextPaths.length; i++) {
                    layoutPaths[nextPaths[i]] = 1;
                }
                crawlLayoutForContainers(obj[key], nextPaths);
            }
        }
    }

    function crawlLayoutTemplateForContainers(obj, path) {
        for(var key in obj) {
            if(key.indexOf('defaults') === -1 && isPlainObject(obj[key])) {
                var nextPath = getNextPath(obj, key, path);
                if(layoutPaths[nextPath]) {
                    crawlLayoutTemplateForContainers(obj[key], nextPath);
                }
                else {
                    errorList.push({code: 'unused', path: nextPath});
                }
            }
        }
    }

    if(!isPlainObject(layoutTemplate)) {
        errorList.push({code: 'layout'});
    }
    else {
        crawlLayoutForContainers(fullLayout, ['layout']);
        crawlLayoutTemplateForContainers(layoutTemplate, 'layout');
    }

    if(!isPlainObject(dataTemplate)) {
        errorList.push({code: 'data'});
    }
    else {
        var typeCount = {};
        var traceType;
        for(var i = 0; i < fullData.length; i++) {
            var fullTrace = fullData[i];
            traceType = fullTrace.type;
            typeCount[traceType] = (typeCount[traceType] || 0) + 1;
            if(!fullTrace._fullInput._template) {
                // this takes care of the case of traceType in the data but not
                // the template
                errorList.push({
                    code: 'missing',
                    index: fullTrace._fullInput.index,
                    traceType: traceType
                });
            }
        }
        for(traceType in dataTemplate) {
            var templateCount = dataTemplate[traceType].length;
            var dataCount = typeCount[traceType] || 0;
            if(templateCount > dataCount) {
                errorList.push({
                    code: 'unused',
                    traceType: traceType,
                    templateCount: templateCount,
                    dataCount: dataCount
                });
            }
            else if(dataCount > templateCount) {
                errorList.push({
                    code: 'reused',
                    traceType: traceType,
                    templateCount: templateCount,
                    dataCount: dataCount
                });
            }
        }
    }

    // _template: false is when someone tried to modify an array item
    // but there was no template with matching name
    function crawlForMissingTemplates(obj, path) {
        for(var key in obj) {
            if(key.charAt(0) === '_') continue;
            var val = obj[key];
            var nextPath = getNextPath(obj, key, path);
            if(isPlainObject(val)) {
                if(Array.isArray(obj) && val._template === false && val.templateitemname) {
                    errorList.push({
                        code: 'missing',
                        path: nextPath,
                        templateitemname: val.templateitemname
                    });
                }
                crawlForMissingTemplates(val, nextPath);
            }
            else if(Array.isArray(val) && hasPlainObject(val)) {
                crawlForMissingTemplates(val, nextPath);
            }
        }
    }
    crawlForMissingTemplates({data: fullData, layout: fullLayout}, '');

    if(errorList.length) return errorList.map(format);
};

function hasPlainObject(arr) {
    for(var i = 0; i < arr.length; i++) {
        if(isPlainObject(arr[i])) return true;
    }
}

function format(opts) {
    var msg;
    switch(opts.code) {
        case 'data':
            msg = 'The template has no key data.';
            break;
        case 'layout':
            msg = 'The template has no key layout.';
            break;
        case 'missing':
            if(opts.path) {
                msg = 'There are no templates for item ' + opts.path +
                    ' with name ' + opts.templateitemname;
            }
            else {
                msg = 'There are no templates for trace ' + opts.index +
                    ', of type ' + opts.traceType + '.';
            }
            break;
        case 'unused':
            if(opts.path) {
                msg = 'The template item at ' + opts.path +
                    ' was not used in constructing the plot.';
            }
            else if(opts.dataCount) {
                msg = 'Some of the templates of type ' + opts.traceType +
                    ' were not used. The template has ' + opts.templateCount +
                    ' traces, the data only has ' + opts.dataCount +
                    ' of this type.';
            }
            else {
                msg = 'The template has ' + opts.templateCount +
                    ' traces of type ' + opts.traceType +
                    ' but there are none in the data.';
            }
            break;
        case 'reused':
            msg = 'Some of the templates of type ' + opts.traceType +
                ' were used more than once. The template has ' +
                opts.templateCount + ' traces, the data has ' +
                opts.dataCount + ' of this type.';
            break;
    }
    opts.msg = msg;

    return opts;
}

},{"../lib":697,"../plots/attributes":742,"../plots/plots":807,"./plot_config":733,"./plot_schema":734,"./plot_template":735}],738:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var plotApi = _dereq_('./plot_api');
var Lib = _dereq_('../lib');

var helpers = _dereq_('../snapshot/helpers');
var toSVG = _dereq_('../snapshot/tosvg');
var svgToImg = _dereq_('../snapshot/svgtoimg');

var attrs = {
    format: {
        valType: 'enumerated',
        values: ['png', 'jpeg', 'webp', 'svg'],
        dflt: 'png',
        
    },
    width: {
        valType: 'number',
        min: 1,
        
    },
    height: {
        valType: 'number',
        min: 1,
        
    },
    scale: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
    },
    setBackground: {
        valType: 'any',
        dflt: false,
        
    },
    imageDataOnly: {
        valType: 'boolean',
        dflt: false,
        
    }
};

var IMAGE_URL_PREFIX = /^data:image\/\w+;base64,/;

/** Plotly.toImage
 *
 * @param {object | string | HTML div} gd
 *   can either be a data/layout/config object
 *   or an existing graph <div>
 *   or an id to an existing graph <div>
 * @param {object} opts (see above)
 * @return {promise}
 */
function toImage(gd, opts) {
    opts = opts || {};

    var data;
    var layout;
    var config;

    if(Lib.isPlainObject(gd)) {
        data = gd.data || [];
        layout = gd.layout || {};
        config = gd.config || {};
    } else {
        gd = Lib.getGraphDiv(gd);
        data = Lib.extendDeep([], gd.data);
        layout = Lib.extendDeep({}, gd.layout);
        config = gd._context;
    }

    function isImpliedOrValid(attr) {
        return !(attr in opts) || Lib.validate(opts[attr], attrs[attr]);
    }

    if(!isImpliedOrValid('width') || !isImpliedOrValid('height')) {
        throw new Error('Height and width should be pixel values.');
    }

    if(!isImpliedOrValid('format')) {
        throw new Error('Image format is not jpeg, png, svg or webp.');
    }

    var fullOpts = {};

    function coerce(attr, dflt) {
        return Lib.coerce(opts, fullOpts, attrs, attr, dflt);
    }

    var format = coerce('format');
    var width = coerce('width');
    var height = coerce('height');
    var scale = coerce('scale');
    var setBackground = coerce('setBackground');
    var imageDataOnly = coerce('imageDataOnly');

    // put the cloned div somewhere off screen before attaching to DOM
    var clonedGd = document.createElement('div');
    clonedGd.style.position = 'absolute';
    clonedGd.style.left = '-5000px';
    document.body.appendChild(clonedGd);

    // extend layout with image options
    var layoutImage = Lib.extendFlat({}, layout);
    if(width) layoutImage.width = width;
    if(height) layoutImage.height = height;

    // extend config for static plot
    var configImage = Lib.extendFlat({}, config, {
        _exportedPlot: true,
        staticPlot: true,
        setBackground: setBackground
    });

    var redrawFunc = helpers.getRedrawFunc(clonedGd);

    function wait() {
        return new Promise(function(resolve) {
            setTimeout(resolve, helpers.getDelay(clonedGd._fullLayout));
        });
    }

    function convert() {
        return new Promise(function(resolve, reject) {
            var svg = toSVG(clonedGd, format, scale);
            var width = clonedGd._fullLayout.width;
            var height = clonedGd._fullLayout.height;

            plotApi.purge(clonedGd);
            document.body.removeChild(clonedGd);

            if(format === 'svg') {
                if(imageDataOnly) {
                    return resolve(svg);
                } else {
                    return resolve('data:image/svg+xml,' + encodeURIComponent(svg));
                }
            }

            var canvas = document.createElement('canvas');
            canvas.id = Lib.randstr();

            svgToImg({
                format: format,
                width: width,
                height: height,
                scale: scale,
                canvas: canvas,
                svg: svg,
                // ask svgToImg to return a Promise
                //  rather than EventEmitter
                //  leave EventEmitter for backward
                //  compatibility
                promise: true
            })
            .then(resolve)
            .catch(reject);
        });
    }

    function urlToImageData(url) {
        if(imageDataOnly) {
            return url.replace(IMAGE_URL_PREFIX, '');
        } else {
            return url;
        }
    }

    return new Promise(function(resolve, reject) {
        plotApi.plot(clonedGd, data, layoutImage, configImage)
            .then(redrawFunc)
            .then(wait)
            .then(convert)
            .then(function(url) { resolve(urlToImageData(url)); })
            .catch(function(err) { reject(err); });
    });
}

module.exports = toImage;

},{"../lib":697,"../snapshot/helpers":830,"../snapshot/svgtoimg":832,"../snapshot/tosvg":834,"./plot_api":732}],739:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../lib');
var Plots = _dereq_('../plots/plots');
var PlotSchema = _dereq_('./plot_schema');
var dfltConfig = _dereq_('./plot_config').dfltConfig;

var isPlainObject = Lib.isPlainObject;
var isArray = Array.isArray;
var isArrayOrTypedArray = Lib.isArrayOrTypedArray;

/**
 * Validate a data array and layout object.
 *
 * @param {array} data
 * @param {object} layout
 *
 * @return {array} array of error objects each containing:
 *  - {string} code
 *      error code ('object', 'array', 'schema', 'unused', 'invisible' or 'value')
 *  - {string} container
 *      container where the error occurs ('data' or 'layout')
 *  - {number} trace
 *      trace index of the 'data' container where the error occurs
 *  - {array} path
 *      nested path to the key that causes the error
 *  - {string} astr
 *      attribute string variant of 'path' compatible with Plotly.restyle and
 *      Plotly.relayout.
 *  - {string} msg
 *      error message (shown in console in logger config argument is enable)
 */
module.exports = function validate(data, layout) {
    var schema = PlotSchema.get();
    var errorList = [];
    var gd = {_context: Lib.extendFlat({}, dfltConfig)};

    var dataIn, layoutIn;

    if(isArray(data)) {
        gd.data = Lib.extendDeep([], data);
        dataIn = data;
    }
    else {
        gd.data = [];
        dataIn = [];
        errorList.push(format('array', 'data'));
    }

    if(isPlainObject(layout)) {
        gd.layout = Lib.extendDeep({}, layout);
        layoutIn = layout;
    }
    else {
        gd.layout = {};
        layoutIn = {};
        if(arguments.length > 1) {
            errorList.push(format('object', 'layout'));
        }
    }

    // N.B. dataIn and layoutIn are in general not the same as
    // gd.data and gd.layout after supplyDefaults as some attributes
    // in gd.data and gd.layout (still) get mutated during this step.

    Plots.supplyDefaults(gd);

    var dataOut = gd._fullData;
    var len = dataIn.length;

    for(var i = 0; i < len; i++) {
        var traceIn = dataIn[i];
        var base = ['data', i];

        if(!isPlainObject(traceIn)) {
            errorList.push(format('object', base));
            continue;
        }

        var traceOut = dataOut[i];
        var traceType = traceOut.type;
        var traceSchema = schema.traces[traceType].attributes;

        // PlotSchema does something fancy with trace 'type', reset it here
        // to make the trace schema compatible with Lib.validate.
        traceSchema.type = {
            valType: 'enumerated',
            values: [traceType]
        };

        if(traceOut.visible === false && traceIn.visible !== false) {
            errorList.push(format('invisible', base));
        }

        crawl(traceIn, traceOut, traceSchema, errorList, base);

        var transformsIn = traceIn.transforms;
        var transformsOut = traceOut.transforms;

        if(transformsIn) {
            if(!isArray(transformsIn)) {
                errorList.push(format('array', base, ['transforms']));
            }

            base.push('transforms');

            for(var j = 0; j < transformsIn.length; j++) {
                var path = ['transforms', j];
                var transformType = transformsIn[j].type;

                if(!isPlainObject(transformsIn[j])) {
                    errorList.push(format('object', base, path));
                    continue;
                }

                var transformSchema = schema.transforms[transformType] ?
                    schema.transforms[transformType].attributes :
                    {};

                // add 'type' to transform schema to validate the transform type
                transformSchema.type = {
                    valType: 'enumerated',
                    values: Object.keys(schema.transforms)
                };

                crawl(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path);
            }
        }
    }

    var layoutOut = gd._fullLayout;
    var layoutSchema = fillLayoutSchema(schema, dataOut);

    crawl(layoutIn, layoutOut, layoutSchema, errorList, 'layout');

    // return undefined if no validation errors were found
    return (errorList.length === 0) ? void(0) : errorList;
};

function crawl(objIn, objOut, schema, list, base, path) {
    path = path || [];

    var keys = Object.keys(objIn);

    for(var i = 0; i < keys.length; i++) {
        var k = keys[i];

        // transforms are handled separately
        if(k === 'transforms') continue;

        var p = path.slice();
        p.push(k);

        var valIn = objIn[k];
        var valOut = objOut[k];

        var nestedSchema = getNestedSchema(schema, k);
        var isInfoArray = (nestedSchema || {}).valType === 'info_array';
        var isColorscale = (nestedSchema || {}).valType === 'colorscale';
        var items = (nestedSchema || {}).items;

        if(!isInSchema(schema, k)) {
            list.push(format('schema', base, p));
        }
        else if(isPlainObject(valIn) && isPlainObject(valOut)) {
            crawl(valIn, valOut, nestedSchema, list, base, p);
        }
        else if(isInfoArray && isArray(valIn)) {
            if(valIn.length > valOut.length) {
                list.push(format('unused', base, p.concat(valOut.length)));
            }
            var len = valOut.length;
            var arrayItems = Array.isArray(items);
            if(arrayItems) len = Math.min(len, items.length);
            var m, n, item, valInPart, valOutPart;
            if(nestedSchema.dimensions === 2) {
                for(n = 0; n < len; n++) {
                    if(isArray(valIn[n])) {
                        if(valIn[n].length > valOut[n].length) {
                            list.push(format('unused', base, p.concat(n, valOut[n].length)));
                        }
                        var len2 = valOut[n].length;
                        for(m = 0; m < (arrayItems ? Math.min(len2, items[n].length) : len2); m++) {
                            item = arrayItems ? items[n][m] : items;
                            valInPart = valIn[n][m];
                            valOutPart = valOut[n][m];
                            if(!Lib.validate(valInPart, item)) {
                                list.push(format('value', base, p.concat(n, m), valInPart));
                            }
                            else if(valOutPart !== valInPart && valOutPart !== +valInPart) {
                                list.push(format('dynamic', base, p.concat(n, m), valInPart, valOutPart));
                            }
                        }
                    }
                    else {
                        list.push(format('array', base, p.concat(n), valIn[n]));
                    }
                }
            }
            else {
                for(n = 0; n < len; n++) {
                    item = arrayItems ? items[n] : items;
                    valInPart = valIn[n];
                    valOutPart = valOut[n];
                    if(!Lib.validate(valInPart, item)) {
                        list.push(format('value', base, p.concat(n), valInPart));
                    }
                    else if(valOutPart !== valInPart && valOutPart !== +valInPart) {
                        list.push(format('dynamic', base, p.concat(n), valInPart, valOutPart));
                    }
                }
            }
        }
        else if(nestedSchema.items && !isInfoArray && isArray(valIn)) {
            var _nestedSchema = items[Object.keys(items)[0]];
            var indexList = [];

            var j, _p;

            // loop over valOut items while keeping track of their
            // corresponding input container index (given by _index)
            for(j = 0; j < valOut.length; j++) {
                var _index = valOut[j]._index || j;

                _p = p.slice();
                _p.push(_index);

                if(isPlainObject(valIn[_index]) && isPlainObject(valOut[j])) {
                    indexList.push(_index);
                    var valInj = valIn[_index];
                    var valOutj = valOut[j];
                    if(isPlainObject(valInj) && valInj.visible !== false && valOutj.visible === false) {
                        list.push(format('invisible', base, _p));
                    }
                    else crawl(valInj, valOutj, _nestedSchema, list, base, _p);
                }
            }

            // loop over valIn to determine where it went wrong for some items
            for(j = 0; j < valIn.length; j++) {
                _p = p.slice();
                _p.push(j);

                if(!isPlainObject(valIn[j])) {
                    list.push(format('object', base, _p, valIn[j]));
                }
                else if(indexList.indexOf(j) === -1) {
                    list.push(format('unused', base, _p));
                }
            }
        }
        else if(!isPlainObject(valIn) && isPlainObject(valOut)) {
            list.push(format('object', base, p, valIn));
        }
        else if(!isArrayOrTypedArray(valIn) && isArrayOrTypedArray(valOut) && !isInfoArray && !isColorscale) {
            list.push(format('array', base, p, valIn));
        }
        else if(!(k in objOut)) {
            list.push(format('unused', base, p, valIn));
        }
        else if(!Lib.validate(valIn, nestedSchema)) {
            list.push(format('value', base, p, valIn));
        }
        else if(nestedSchema.valType === 'enumerated' &&
            ((nestedSchema.coerceNumber && valIn !== +valOut) || valIn !== valOut)
        ) {
            list.push(format('dynamic', base, p, valIn, valOut));
        }
    }

    return list;
}

// the 'full' layout schema depends on the traces types presents
function fillLayoutSchema(schema, dataOut) {
    var layoutSchema = schema.layout.layoutAttributes;

    for(var i = 0; i < dataOut.length; i++) {
        var traceOut = dataOut[i];
        var traceSchema = schema.traces[traceOut.type];
        var traceLayoutAttr = traceSchema.layoutAttributes;

        if(traceLayoutAttr) {
            if(traceOut.subplot) {
                Lib.extendFlat(layoutSchema[traceSchema.attributes.subplot.dflt], traceLayoutAttr);
            } else {
                Lib.extendFlat(layoutSchema, traceLayoutAttr);
            }
        }
    }

    return layoutSchema;
}

// validation error codes
var code2msgFunc = {
    object: function(base, astr) {
        var prefix;

        if(base === 'layout' && astr === '') prefix = 'The layout argument';
        else if(base[0] === 'data' && astr === '') {
            prefix = 'Trace ' + base[1] + ' in the data argument';
        }
        else prefix = inBase(base) + 'key ' + astr;

        return prefix + ' must be linked to an object container';
    },
    array: function(base, astr) {
        var prefix;

        if(base === 'data') prefix = 'The data argument';
        else prefix = inBase(base) + 'key ' + astr;

        return prefix + ' must be linked to an array container';
    },
    schema: function(base, astr) {
        return inBase(base) + 'key ' + astr + ' is not part of the schema';
    },
    unused: function(base, astr, valIn) {
        var target = isPlainObject(valIn) ? 'container' : 'key';

        return inBase(base) + target + ' ' + astr + ' did not get coerced';
    },
    dynamic: function(base, astr, valIn, valOut) {
        return [
            inBase(base) + 'key',
            astr,
            '(set to \'' + valIn + '\')',
            'got reset to',
            '\'' + valOut + '\'',
            'during defaults.'
        ].join(' ');
    },
    invisible: function(base, astr) {
        return (
            astr ? (inBase(base) + 'item ' + astr) : ('Trace ' + base[1])
        ) + ' got defaulted to be not visible';
    },
    value: function(base, astr, valIn) {
        return [
            inBase(base) + 'key ' + astr,
            'is set to an invalid value (' + valIn + ')'
        ].join(' ');
    }
};

function inBase(base) {
    if(isArray(base)) return 'In data trace ' + base[1] + ', ';

    return 'In ' + base + ', ';
}

function format(code, base, path, valIn, valOut) {
    path = path || '';

    var container, trace;

    // container is either 'data' or 'layout
    // trace is the trace index if 'data', null otherwise

    if(isArray(base)) {
        container = base[0];
        trace = base[1];
    }
    else {
        container = base;
        trace = null;
    }

    var astr = convertPathToAttributeString(path);
    var msg = code2msgFunc[code](base, astr, valIn, valOut);

    // log to console if logger config option is enabled
    Lib.log(msg);

    return {
        code: code,
        container: container,
        trace: trace,
        path: path,
        astr: astr,
        msg: msg
    };
}

function isInSchema(schema, key) {
    var parts = splitKey(key);
    var keyMinusId = parts.keyMinusId;
    var id = parts.id;

    if((keyMinusId in schema) && schema[keyMinusId]._isSubplotObj && id) {
        return true;
    }

    return (key in schema);
}

function getNestedSchema(schema, key) {
    if(key in schema) return schema[key];

    var parts = splitKey(key);

    return schema[parts.keyMinusId];
}

var idRegex = Lib.counterRegex('([a-z]+)');

function splitKey(key) {
    var idMatch = key.match(idRegex);

    return {
        keyMinusId: idMatch && idMatch[1],
        id: idMatch && idMatch[2]
    };
}

function convertPathToAttributeString(path) {
    if(!isArray(path)) return String(path);

    var astr = '';

    for(var i = 0; i < path.length; i++) {
        var p = path[i];

        if(typeof p === 'number') {
            astr = astr.substr(0, astr.length - 1) + '[' + p + ']';
        }
        else {
            astr += p;
        }

        if(i < path.length - 1) astr += '.';
    }

    return astr;
}

},{"../lib":697,"../plots/plots":807,"./plot_config":733,"./plot_schema":734}],740:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    mode: {
        valType: 'enumerated',
        dflt: 'afterall',
        
        values: ['immediate', 'next', 'afterall'],
        
    },
    direction: {
        valType: 'enumerated',
        
        values: ['forward', 'reverse'],
        dflt: 'forward',
        
    },
    fromcurrent: {
        valType: 'boolean',
        dflt: false,
        
        
    },
    frame: {
        duration: {
            valType: 'number',
            
            min: 0,
            dflt: 500,
            
        },
        redraw: {
            valType: 'boolean',
            
            dflt: true,
            
        },
    },
    transition: {
        duration: {
            valType: 'number',
            
            min: 0,
            dflt: 500,
            editType: 'none',
            
        },
        easing: {
            valType: 'enumerated',
            dflt: 'cubic-in-out',
            values: [
                'linear',
                'quad',
                'cubic',
                'sin',
                'exp',
                'circle',
                'elastic',
                'back',
                'bounce',
                'linear-in',
                'quad-in',
                'cubic-in',
                'sin-in',
                'exp-in',
                'circle-in',
                'elastic-in',
                'back-in',
                'bounce-in',
                'linear-out',
                'quad-out',
                'cubic-out',
                'sin-out',
                'exp-out',
                'circle-out',
                'elastic-out',
                'back-out',
                'bounce-out',
                'linear-in-out',
                'quad-in-out',
                'cubic-in-out',
                'sin-in-out',
                'exp-in-out',
                'circle-in-out',
                'elastic-in-out',
                'back-in-out',
                'bounce-in-out'
            ],
            
            editType: 'none',
            
        },
        ordering: {
            valType: 'enumerated',
            values: ['layout first', 'traces first'],
            dflt: 'layout first',
            
            editType: 'none',
            
        }
    }
};

},{}],741:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../lib');
var Template = _dereq_('../plot_api/plot_template');

/** Convenience wrapper for making array container logic DRY and consistent
 *
 * @param {object} parentObjIn
 *  user input object where the container in question is linked
 *  (i.e. either a user trace object or the user layout object)
 *
 * @param {object} parentObjOut
 *  full object where the coerced container will be linked
 *  (i.e. either a full trace object or the full layout object)
 *
 * @param {object} opts
 *  options object:
 *   - name {string}
 *      name of the key linking the container in question
 *   - inclusionAttr {string}
 *      name of the item attribute for inclusion/exclusion. Default is 'visible'.
 *      Since inclusion is true, use eg 'enabled' instead of 'disabled'.
 *   - handleItemDefaults {function}
 *      defaults method to be called on each item in the array container in question
 *
 *      Its arguments are:
 *          - itemIn {object} item in user layout
 *          - itemOut {object} item in full layout
 *          - parentObj {object} (as in closure)
 *          - opts {object} (as in closure)
 * N.B.
 *
 *  - opts is passed to handleItemDefaults so it can also store
 *    links to supplementary data (e.g. fullData for layout components)
 *
 */
module.exports = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) {
    var name = opts.name;
    var inclusionAttr = opts.inclusionAttr || 'visible';

    var previousContOut = parentObjOut[name];

    var contIn = Lib.isArrayOrTypedArray(parentObjIn[name]) ? parentObjIn[name] : [];
    var contOut = parentObjOut[name] = [];
    var templater = Template.arrayTemplater(parentObjOut, name, inclusionAttr);
    var i, itemOut;

    for(i = 0; i < contIn.length; i++) {
        var itemIn = contIn[i];

        if(!Lib.isPlainObject(itemIn)) {
            itemOut = templater.newItem({});
            itemOut[inclusionAttr] = false;
        }
        else {
            itemOut = templater.newItem(itemIn);
        }

        itemOut._index = i;

        if(itemOut[inclusionAttr] !== false) {
            opts.handleItemDefaults(itemIn, itemOut, parentObjOut, opts);
        }

        contOut.push(itemOut);
    }

    var defaultItems = templater.defaultItems();
    for(i = 0; i < defaultItems.length; i++) {
        itemOut = defaultItems[i];
        itemOut._index = contOut.length;
        opts.handleItemDefaults({}, itemOut, parentObjOut, opts, {});
        contOut.push(itemOut);
    }

    // in case this array gets its defaults rebuilt independent of the whole layout,
    // relink the private keys just for this array.
    if(Lib.isArrayOrTypedArray(previousContOut)) {
        var len = Math.min(previousContOut.length, contOut.length);
        for(i = 0; i < len; i++) {
            Lib.relinkPrivateKeys(contOut[i], previousContOut[i]);
        }
    }

    return contOut;
};

},{"../lib":697,"../plot_api/plot_template":735}],742:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fxAttrs = _dereq_('../components/fx/attributes');

module.exports = {
    type: {
        valType: 'enumerated',
        
        values: [],     // listed dynamically
        dflt: 'scatter',
        editType: 'calc+clearAxisTypes',
        _noTemplating: true // we handle this at a higher level
    },
    visible: {
        valType: 'enumerated',
        values: [true, false, 'legendonly'],
        
        dflt: true,
        editType: 'calc',
        
    },
    showlegend: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'style',
        
    },
    legendgroup: {
        valType: 'string',
        
        dflt: '',
        editType: 'style',
        
    },
    opacity: {
        valType: 'number',
        
        min: 0,
        max: 1,
        dflt: 1,
        editType: 'style',
        
    },
    name: {
        valType: 'string',
        
        editType: 'style',
        
    },
    uid: {
        valType: 'string',
        
        editType: 'plot',
        anim: true,
        
    },
    ids: {
        valType: 'data_array',
        editType: 'calc',
        anim: true,
        
    },
    customdata: {
        valType: 'data_array',
        editType: 'calc',
        
    },

    // N.B. these cannot be 'data_array' as they do not have the same length as
    // other data arrays and arrayOk attributes in general
    //
    // Maybe add another valType:
    // https://github.com/plotly/plotly.js/issues/1894
    selectedpoints: {
        valType: 'any',
        
        editType: 'calc',
        
    },

    hoverinfo: {
        valType: 'flaglist',
        
        flags: ['x', 'y', 'z', 'text', 'name'],
        extras: ['all', 'none', 'skip'],
        arrayOk: true,
        dflt: 'all',
        editType: 'none',
        
    },
    hoverlabel: fxAttrs.hoverlabel,
    stream: {
        token: {
            valType: 'string',
            noBlank: true,
            strict: true,
            
            editType: 'calc',
            
        },
        maxpoints: {
            valType: 'number',
            min: 0,
            max: 10000,
            dflt: 500,
            
            editType: 'calc',
            
        },
        editType: 'calc'
    },
    transforms: {
        _isLinkedToArray: 'transform',
        editType: 'calc',
        
    },
    uirevision: {
        valType: 'any',
        
        editType: 'none',
        
    }
};

},{"../components/fx/attributes":604}],743:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    xaxis: {
        valType: 'subplotid',
        
        dflt: 'x',
        editType: 'calc+clearAxisTypes',
        
    },
    yaxis: {
        valType: 'subplotid',
        
        dflt: 'y',
        editType: 'calc+clearAxisTypes',
        
    }
};

},{}],744:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');
var FP_SAFE = _dereq_('../../constants/numerical').FP_SAFE;
var Registry = _dereq_('../../registry');

module.exports = {
    getAutoRange: getAutoRange,
    makePadFn: makePadFn,
    doAutoRange: doAutoRange,
    findExtremes: findExtremes,
    concatExtremes: concatExtremes
};

/**
 * getAutoRange
 *
 * Collects all _extremes values corresponding to a given axis
 * and computes its auto range.
 *
 * Note that getAutoRange uses return values from findExtremes.
 *
 * @param {object} gd:
 *   graph div object with filled-in fullData and fullLayout, in particular
 *   with filled-in '_extremes' containers:
 *   {
 *      val: calcdata value,
 *      pad: extra pixels beyond this value,
 *      extrapad: bool, does this point want 5% extra padding
 *   }
 * @param {object} ax:
 *   full axis object, in particular with filled-in '_traceIndices'
 *   and '_annIndices' / '_shapeIndices' if applicable
 * @return {array}
 *   an array of [min, max]. These are calcdata for log and category axes
 *   and data for linear and date axes.
 *
 * TODO: we want to change log to data as well, but it's hard to do this
 * maintaining backward compatibility. category will always have to use calcdata
 * though, because otherwise values between categories (or outside all categories)
 * would be impossible.
 */
function getAutoRange(gd, ax) {
    var i, j;
    var newRange = [];

    var getPad = makePadFn(ax);
    var extremes = concatExtremes(gd, ax);
    var minArray = extremes.min;
    var maxArray = extremes.max;

    if(minArray.length === 0 || maxArray.length === 0) {
        return Lib.simpleMap(ax.range, ax.r2l);
    }

    var minmin = minArray[0].val;
    var maxmax = maxArray[0].val;

    for(i = 1; i < minArray.length; i++) {
        if(minmin !== maxmax) break;
        minmin = Math.min(minmin, minArray[i].val);
    }
    for(i = 1; i < maxArray.length; i++) {
        if(minmin !== maxmax) break;
        maxmax = Math.max(maxmax, maxArray[i].val);
    }

    var axReverse = false;

    if(ax.range) {
        var rng = Lib.simpleMap(ax.range, ax.r2l);
        axReverse = rng[1] < rng[0];
    }
    // one-time setting to easily reverse the axis
    // when plotting from code
    if(ax.autorange === 'reversed') {
        axReverse = true;
        ax.autorange = true;
    }

    var rangeMode = ax.rangemode;
    var toZero = rangeMode === 'tozero';
    var nonNegative = rangeMode === 'nonnegative';
    var axLen = ax._length;
    // don't allow padding to reduce the data to < 10% of the length
    var minSpan = axLen / 10;

    var mbest = 0;
    var minpt, maxpt, minbest, maxbest, dp, dv;

    for(i = 0; i < minArray.length; i++) {
        minpt = minArray[i];
        for(j = 0; j < maxArray.length; j++) {
            maxpt = maxArray[j];
            dv = maxpt.val - minpt.val;
            if(dv > 0) {
                dp = axLen - getPad(minpt) - getPad(maxpt);
                if(dp > minSpan) {
                    if(dv / dp > mbest) {
                        minbest = minpt;
                        maxbest = maxpt;
                        mbest = dv / dp;
                    }
                }
                else if(dv / axLen > mbest) {
                    // in case of padding longer than the axis
                    // at least include the unpadded data values.
                    minbest = {val: minpt.val, pad: 0};
                    maxbest = {val: maxpt.val, pad: 0};
                    mbest = dv / axLen;
                }
            }
        }
    }

    function getMaxPad(prev, pt) {
        return Math.max(prev, getPad(pt));
    }

    if(minmin === maxmax) {
        var lower = minmin - 1;
        var upper = minmin + 1;
        if(toZero) {
            if(minmin === 0) {
                // The only value we have on this axis is 0, and we want to
                // autorange so zero is one end.
                // In principle this could be [0, 1] or [-1, 0] but usually
                // 'tozero' pins 0 to the low end, so follow that.
                newRange = [0, 1];
            }
            else {
                var maxPad = (minmin > 0 ? maxArray : minArray).reduce(getMaxPad, 0);
                // we're pushing a single value away from the edge due to its
                // padding, with the other end clamped at zero
                // 0.5 means don't push it farther than the center.
                var rangeEnd = minmin / (1 - Math.min(0.5, maxPad / axLen));
                newRange = minmin > 0 ? [0, rangeEnd] : [rangeEnd, 0];
            }
        } else if(nonNegative) {
            newRange = [Math.max(0, lower), Math.max(1, upper)];
        } else {
            newRange = [lower, upper];
        }
    }
    else {
        if(toZero) {
            if(minbest.val >= 0) {
                minbest = {val: 0, pad: 0};
            }
            if(maxbest.val <= 0) {
                maxbest = {val: 0, pad: 0};
            }
        }
        else if(nonNegative) {
            if(minbest.val - mbest * getPad(minbest) < 0) {
                minbest = {val: 0, pad: 0};
            }
            if(maxbest.val <= 0) {
                maxbest = {val: 1, pad: 0};
            }
        }

        // in case it changed again...
        mbest = (maxbest.val - minbest.val) /
            (axLen - getPad(minbest) - getPad(maxbest));

        newRange = [
            minbest.val - mbest * getPad(minbest),
            maxbest.val + mbest * getPad(maxbest)
        ];
    }

    // maintain reversal
    if(axReverse) newRange.reverse();

    return Lib.simpleMap(newRange, ax.l2r || Number);
}

/*
 * calculate the pixel padding for ax._min and ax._max entries with
 * optional extrapad as 5% of the total axis length
 */
function makePadFn(ax) {
    // 5% padding for points that specify extrapad: true
    var extrappad = ax._length / 20;

    // domain-constrained axes: base extrappad on the unconstrained
    // domain so it's consistent as the domain changes
    if((ax.constrain === 'domain') && ax._inputDomain) {
        extrappad *= (ax._inputDomain[1] - ax._inputDomain[0]) /
            (ax.domain[1] - ax.domain[0]);
    }

    return function getPad(pt) { return pt.pad + (pt.extrapad ? extrappad : 0); };
}

function concatExtremes(gd, ax) {
    var axId = ax._id;
    var fullData = gd._fullData;
    var fullLayout = gd._fullLayout;
    var minArray = [];
    var maxArray = [];
    var i, j, d;

    function _concat(cont, indices) {
        for(i = 0; i < indices.length; i++) {
            var item = cont[indices[i]];
            var extremes = (item._extremes || {})[axId];
            if(item.visible === true && extremes) {
                for(j = 0; j < extremes.min.length; j++) {
                    d = extremes.min[j];
                    collapseMinArray(minArray, d.val, d.pad, {extrapad: d.extrapad});
                }
                for(j = 0; j < extremes.max.length; j++) {
                    d = extremes.max[j];
                    collapseMaxArray(maxArray, d.val, d.pad, {extrapad: d.extrapad});
                }
            }
        }
    }

    _concat(fullData, ax._traceIndices);
    _concat(fullLayout.annotations || [], ax._annIndices || []);
    _concat(fullLayout.shapes || [], ax._shapeIndices || []);

    return {min: minArray, max: maxArray};
}

function doAutoRange(gd, ax) {
    ax.setScale();

    if(ax.autorange) {
        ax.range = getAutoRange(gd, ax);

        ax._r = ax.range.slice();
        ax._rl = Lib.simpleMap(ax._r, ax.r2l);

        // doAutoRange will get called on fullLayout,
        // but we want to report its results back to layout

        var axIn = ax._input;

        // before we edit _input, store preGUI values
        var edits = {};
        edits[ax._attr + '.range'] = ax.range;
        edits[ax._attr + '.autorange'] = ax.autorange;
        Registry.call('_storeDirectGUIEdit', gd.layout, gd._fullLayout._preGUI, edits);

        axIn.range = ax.range.slice();
        axIn.autorange = ax.autorange;
    }

    var anchorAx = ax._anchorAxis;

    if(anchorAx && anchorAx.rangeslider) {
        var axeRangeOpts = anchorAx.rangeslider[ax._name];
        if(axeRangeOpts) {
            if(axeRangeOpts.rangemode === 'auto') {
                axeRangeOpts.range = getAutoRange(gd, ax);
            }
        }
        anchorAx._input.rangeslider[ax._name] = Lib.extendFlat({}, axeRangeOpts);
    }
}

/**
 * findExtremes
 *
 * Find min/max extremes of an array of coordinates on a given axis.
 *
 * Note that findExtremes is called during `calc`, when we don't yet know the axis
 * length; all the inputs should be based solely on the trace data, nothing
 * about the axis layout.
 *
 * Note that `ppad` and `vpad` as well as their asymmetric variants refer to
 * the before and after padding of the passed `data` array, not to the whole axis.
 *
 * @param {object} ax: full axis object
 *   relies on
 *   - ax.type
 *   - ax._m (just its sign)
 *   - ax.d2l
 * @param {array} data:
 *  array of numbers (i.e. already run though ax.d2c)
 * @param {object} opts:
 *  available keys are:
 *      vpad: (number or number array) pad values (data value +-vpad)
 *      ppad: (number or number array) pad pixels (pixel location +-ppad)
 *      ppadplus, ppadminus, vpadplus, vpadminus:
 *          separate padding for each side, overrides symmetric
 *      padded: (boolean) add 5% padding to both ends
 *          (unless one end is overridden by tozero)
 *      tozero: (boolean) make sure to include zero if axis is linear,
 *          and make it a tight bound if possible
 *
 * @return {object}
 *  - min {array of objects}
 *  - max {array of objects}
 *  each object item has fields:
 *    - val {number}
 *    - pad {number}
 *    - extrappad {number}
 *  - opts {object}: a ref to the passed "options" object
 */
function findExtremes(ax, data, opts) {
    if(!opts) opts = {};
    if(!ax._m) ax.setScale();

    var minArray = [];
    var maxArray = [];

    var len = data.length;
    var extrapad = opts.padded || false;
    var tozero = opts.tozero && (ax.type === 'linear' || ax.type === '-');
    var isLog = ax.type === 'log';
    var hasArrayOption = false;
    var i, v, di, dmin, dmax, ppadiplus, ppadiminus, vmin, vmax;

    function makePadAccessor(item) {
        if(Array.isArray(item)) {
            hasArrayOption = true;
            return function(i) { return Math.max(Number(item[i]||0), 0); };
        }
        else {
            var v = Math.max(Number(item||0), 0);
            return function() { return v; };
        }
    }

    var ppadplus = makePadAccessor((ax._m > 0 ?
        opts.ppadplus : opts.ppadminus) || opts.ppad || 0);
    var ppadminus = makePadAccessor((ax._m > 0 ?
        opts.ppadminus : opts.ppadplus) || opts.ppad || 0);
    var vpadplus = makePadAccessor(opts.vpadplus || opts.vpad);
    var vpadminus = makePadAccessor(opts.vpadminus || opts.vpad);

    if(!hasArrayOption) {
        // with no arrays other than `data` we don't need to consider
        // every point, only the extreme data points
        vmin = Infinity;
        vmax = -Infinity;

        if(isLog) {
            for(i = 0; i < len; i++) {
                v = data[i];
                // data is not linearized yet so we still have to filter out negative logs
                if(v < vmin && v > 0) vmin = v;
                if(v > vmax && v < FP_SAFE) vmax = v;
            }
        } else {
            for(i = 0; i < len; i++) {
                v = data[i];
                if(v < vmin && v > -FP_SAFE) vmin = v;
                if(v > vmax && v < FP_SAFE) vmax = v;
            }
        }

        data = [vmin, vmax];
        len = 2;
    }

    var collapseOpts = {tozero: tozero, extrapad: extrapad};

    function addItem(i) {
        di = data[i];
        if(!isNumeric(di)) return;
        ppadiplus = ppadplus(i);
        ppadiminus = ppadminus(i);
        vmin = di - vpadminus(i);
        vmax = di + vpadplus(i);
        // special case for log axes: if vpad makes this object span
        // more than an order of mag, clip it to one order. This is so
        // we don't have non-positive errors or absurdly large lower
        // range due to rounding errors
        if(isLog && vmin < vmax / 10) vmin = vmax / 10;

        dmin = ax.c2l(vmin);
        dmax = ax.c2l(vmax);

        if(tozero) {
            dmin = Math.min(0, dmin);
            dmax = Math.max(0, dmax);
        }
        if(goodNumber(dmin)) {
            collapseMinArray(minArray, dmin, ppadiminus, collapseOpts);
        }
        if(goodNumber(dmax)) {
            collapseMaxArray(maxArray, dmax, ppadiplus, collapseOpts);
        }
    }

    // For efficiency covering monotonic or near-monotonic data,
    // check a few points at both ends first and then sweep
    // through the middle
    var iMax = Math.min(6, len);
    for(i = 0; i < iMax; i++) addItem(i);
    for(i = len - 1; i >= iMax; i--) addItem(i);

    return {
        min: minArray,
        max: maxArray,
        opts: opts
    };
}

function collapseMinArray(array, newVal, newPad, opts) {
    collapseArray(array, newVal, newPad, opts, lessOrEqual);
}

function collapseMaxArray(array, newVal, newPad, opts) {
    collapseArray(array, newVal, newPad, opts, greaterOrEqual);
}

/**
 * collapseArray
 *
 * Takes items from 'array' and compares them to 'newVal', 'newPad'.
 *
 * @param {array} array:
 *  current set of min or max extremes
 * @param {number} newVal:
 *  new value to compare against
 * @param {number} newPad:
 *  pad value associated with 'newVal'
 * @param {object} opts:
 *  - tozero {boolean}
 *  - extrapad {number}
 * @param {function} atLeastAsExtreme:
 *  comparison function, use
 *  - lessOrEqual for min 'array' and
 *  - greaterOrEqual for max 'array'
 *
 * In practice, 'array' is either
 *  - 'extremes[ax._id].min' or
 *  - 'extremes[ax._id].max
 *  found in traces and layout items that affect autorange.
 *
 * Since we don't yet know the relationship between pixels and values
 * (that's what we're trying to figure out!) AND we don't yet know how
 * many pixels `extrapad` represents (it's going to be 5% of the length,
 * but we don't want to have to redo calc just because length changed)
 * two point must satisfy three criteria simultaneously for one to supersede the other:
 *  - at least as extreme a `val`
 *  - at least as big a `pad`
 *  - an unpadded point cannot supersede a padded point, but any other combination can
 *
 * Then:
 * - If the item supersedes the new point, set includeThis false
 * - If the new pt supersedes the item, delete it from 'array'
 */
function collapseArray(array, newVal, newPad, opts, atLeastAsExtreme) {
    var tozero = opts.tozero;
    var extrapad = opts.extrapad;
    var includeThis = true;

    for(var j = 0; j < array.length && includeThis; j++) {
        var v = array[j];
        if(atLeastAsExtreme(v.val, newVal) && v.pad >= newPad && (v.extrapad || !extrapad)) {
            includeThis = false;
            break;
        } else if(atLeastAsExtreme(newVal, v.val) && v.pad <= newPad && (extrapad || !v.extrapad)) {
            array.splice(j, 1);
            j--;
        }
    }
    if(includeThis) {
        var clipAtZero = (tozero && newVal === 0);
        array.push({
            val: newVal,
            pad: clipAtZero ? 0 : newPad,
            extrapad: clipAtZero ? false : extrapad
        });
    }
}

// In order to stop overflow errors, don't consider points
// too close to the limits of js floating point
function goodNumber(v) {
    return isNumeric(v) && Math.abs(v) < FP_SAFE;
}

function lessOrEqual(v0, v1) { return v0 <= v1; }
function greaterOrEqual(v0, v1) { return v0 >= v1; }

},{"../../constants/numerical":674,"../../lib":697,"../../registry":826,"fast-isnumeric":218}],745:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');
var Plots = _dereq_('../../plots/plots');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var Titles = _dereq_('../../components/titles');
var Color = _dereq_('../../components/color');
var Drawing = _dereq_('../../components/drawing');

var axAttrs = _dereq_('./layout_attributes');
var cleanTicks = _dereq_('./clean_ticks');

var constants = _dereq_('../../constants/numerical');
var ONEAVGYEAR = constants.ONEAVGYEAR;
var ONEAVGMONTH = constants.ONEAVGMONTH;
var ONEDAY = constants.ONEDAY;
var ONEHOUR = constants.ONEHOUR;
var ONEMIN = constants.ONEMIN;
var ONESEC = constants.ONESEC;
var MINUS_SIGN = constants.MINUS_SIGN;
var BADNUM = constants.BADNUM;

var MID_SHIFT = _dereq_('../../constants/alignment').MID_SHIFT;
var LINE_SPACING = _dereq_('../../constants/alignment').LINE_SPACING;

var axes = module.exports = {};

axes.setConvert = _dereq_('./set_convert');
var autoType = _dereq_('./axis_autotype');

var axisIds = _dereq_('./axis_ids');
axes.id2name = axisIds.id2name;
axes.name2id = axisIds.name2id;
axes.cleanId = axisIds.cleanId;
axes.list = axisIds.list;
axes.listIds = axisIds.listIds;
axes.getFromId = axisIds.getFromId;
axes.getFromTrace = axisIds.getFromTrace;

var autorange = _dereq_('./autorange');
axes.getAutoRange = autorange.getAutoRange;
axes.findExtremes = autorange.findExtremes;

/*
 * find the list of possible axes to reference with an xref or yref attribute
 * and coerce it to that list
 *
 * attr: the attribute we're generating a reference for. Should end in 'x' or 'y'
 *     but can be prefixed, like 'ax' for annotation's arrow x
 * dflt: the default to coerce to, or blank to use the first axis (falling back on
 *     extraOption if there is no axis)
 * extraOption: aside from existing axes with this letter, what non-axis value is allowed?
 *     Only required if it's different from `dflt`
 */
axes.coerceRef = function(containerIn, containerOut, gd, attr, dflt, extraOption) {
    var axLetter = attr.charAt(attr.length - 1);
    var axlist = gd._fullLayout._subplots[axLetter + 'axis'];
    var refAttr = attr + 'ref';
    var attrDef = {};

    if(!dflt) dflt = axlist[0] || extraOption;
    if(!extraOption) extraOption = dflt;

    // data-ref annotations are not supported in gl2d yet

    attrDef[refAttr] = {
        valType: 'enumerated',
        values: axlist.concat(extraOption ? [extraOption] : []),
        dflt: dflt
    };

    // xref, yref
    return Lib.coerce(containerIn, containerOut, attrDef, refAttr);
};

/*
 * coerce position attributes (range-type) that can be either on axes or absolute
 * (paper or pixel) referenced. The biggest complication here is that we don't know
 * before looking at the axis whether the value must be a number or not (it may be
 * a date string), so we can't use the regular valType='number' machinery
 *
 * axRef (string): the axis this position is referenced to, or:
 *     paper: fraction of the plot area
 *     pixel: pixels relative to some starting position
 * attr (string): the attribute in containerOut we are coercing
 * dflt (number): the default position, as a fraction or pixels. If the attribute
 *     is to be axis-referenced, this will be converted to an axis data value
 *
 * Also cleans the values, since the attribute definition itself has to say
 * valType: 'any' to handle date axes. This allows us to accept:
 * - for category axes: category names, and convert them here into serial numbers.
 *   Note that this will NOT work for axis range endpoints, because we don't know
 *   the category list yet (it's set by ax.makeCalcdata during calc)
 *   but it works for component (note, shape, images) positions.
 * - for date axes: JS Dates or milliseconds, and convert to date strings
 * - for other types: coerce them to numbers
 */
axes.coercePosition = function(containerOut, gd, coerce, axRef, attr, dflt) {
    var cleanPos, pos;

    if(axRef === 'paper' || axRef === 'pixel') {
        cleanPos = Lib.ensureNumber;
        pos = coerce(attr, dflt);
    } else {
        var ax = axes.getFromId(gd, axRef);
        dflt = ax.fraction2r(dflt);
        pos = coerce(attr, dflt);
        cleanPos = ax.cleanPos;
    }

    containerOut[attr] = cleanPos(pos);
};

axes.cleanPosition = function(pos, gd, axRef) {
    var cleanPos = (axRef === 'paper' || axRef === 'pixel') ?
        Lib.ensureNumber :
        axes.getFromId(gd, axRef).cleanPos;

    return cleanPos(pos);
};

axes.redrawComponents = function(gd, axIds) {
    axIds = axIds ? axIds : axes.listIds(gd);

    var fullLayout = gd._fullLayout;

    function _redrawOneComp(moduleName, methodName, stashName, shortCircuit) {
        var method = Registry.getComponentMethod(moduleName, methodName);
        var stash = {};

        for(var i = 0; i < axIds.length; i++) {
            var ax = fullLayout[axes.id2name(axIds[i])];
            var indices = ax[stashName];

            for(var j = 0; j < indices.length; j++) {
                var ind = indices[j];

                if(!stash[ind]) {
                    method(gd, ind);
                    stash[ind] = 1;
                    // once is enough for images (which doesn't use the `i` arg anyway)
                    if(shortCircuit) return;
                }
            }
        }
    }

    // annotations and shapes 'draw' method is slow,
    // use the finer-grained 'drawOne' method instead
    _redrawOneComp('annotations', 'drawOne', '_annIndices');
    _redrawOneComp('shapes', 'drawOne', '_shapeIndices');
    _redrawOneComp('images', 'draw', '_imgIndices', true);
};

var getDataConversions = axes.getDataConversions = function(gd, trace, target, targetArray) {
    var ax;

    // If target points to an axis, use the type we already have for that
    // axis to find the data type. Otherwise use the values to autotype.
    var d2cTarget = (target === 'x' || target === 'y' || target === 'z') ?
        target :
        targetArray;

    // In the case of an array target, make a mock data array
    // and call supplyDefaults to the data type and
    // setup the data-to-calc method.
    if(Array.isArray(d2cTarget)) {
        ax = {
            type: autoType(targetArray),
            _categories: []
        };
        axes.setConvert(ax);

        // build up ax._categories (usually done during ax.makeCalcdata()
        if(ax.type === 'category') {
            for(var i = 0; i < targetArray.length; i++) {
                ax.d2c(targetArray[i]);
            }
        }
        // TODO what to do for transforms?
    } else {
        ax = axes.getFromTrace(gd, trace, d2cTarget);
    }

    // if 'target' has corresponding axis
    // -> use setConvert method
    if(ax) return {d2c: ax.d2c, c2d: ax.c2d};

    // special case for 'ids'
    // -> cast to String
    if(d2cTarget === 'ids') return {d2c: toString, c2d: toString};

    // otherwise (e.g. numeric-array of 'marker.color' or 'marker.size')
    // -> cast to Number

    return {d2c: toNum, c2d: toNum};
};

function toNum(v) { return +v; }
function toString(v) { return String(v); }

axes.getDataToCoordFunc = function(gd, trace, target, targetArray) {
    return getDataConversions(gd, trace, target, targetArray).d2c;
};

// get counteraxis letter for this axis (name or id)
// this can also be used as the id for default counter axis
axes.counterLetter = function(id) {
    var axLetter = id.charAt(0);
    if(axLetter === 'x') return 'y';
    if(axLetter === 'y') return 'x';
};

// incorporate a new minimum difference and first tick into
// forced
// note that _forceTick0 is linearized, so needs to be turned into
// a range value for setting tick0
axes.minDtick = function(ax, newDiff, newFirst, allow) {
    // doesn't make sense to do forced min dTick on log or category axes,
    // and the plot itself may decide to cancel (ie non-grouped bars)
    if(['log', 'category', 'multicategory'].indexOf(ax.type) !== -1 || !allow) {
        ax._minDtick = 0;
    }
    // undefined means there's nothing there yet
    else if(ax._minDtick === undefined) {
        ax._minDtick = newDiff;
        ax._forceTick0 = newFirst;
    }
    else if(ax._minDtick) {
        // existing minDtick is an integer multiple of newDiff
        // (within rounding err)
        // and forceTick0 can be shifted to newFirst
        if((ax._minDtick / newDiff + 1e-6) % 1 < 2e-6 &&
                (((newFirst - ax._forceTick0) / newDiff % 1) +
                    1.000001) % 1 < 2e-6) {
            ax._minDtick = newDiff;
            ax._forceTick0 = newFirst;
        }
        // if the converse is true (newDiff is a multiple of minDtick and
        // newFirst can be shifted to forceTick0) then do nothing - same
        // forcing stands. Otherwise, cancel forced minimum
        else if((newDiff / ax._minDtick + 1e-6) % 1 > 2e-6 ||
                (((newFirst - ax._forceTick0) / ax._minDtick % 1) +
                    1.000001) % 1 > 2e-6) {
            ax._minDtick = 0;
        }
    }
};

// save a copy of the initial axis ranges in fullLayout
// use them in mode bar and dblclick events
axes.saveRangeInitial = function(gd, overwrite) {
    var axList = axes.list(gd, '', true);
    var hasOneAxisChanged = false;

    for(var i = 0; i < axList.length; i++) {
        var ax = axList[i];
        var isNew = (ax._rangeInitial === undefined);
        var hasChanged = isNew || !(
            ax.range[0] === ax._rangeInitial[0] &&
            ax.range[1] === ax._rangeInitial[1]
        );

        if((isNew && ax.autorange === false) || (overwrite && hasChanged)) {
            ax._rangeInitial = ax.range.slice();
            hasOneAxisChanged = true;
        }
    }

    return hasOneAxisChanged;
};

// save a copy of the initial spike visibility
axes.saveShowSpikeInitial = function(gd, overwrite) {
    var axList = axes.list(gd, '', true);
    var hasOneAxisChanged = false;
    var allSpikesEnabled = 'on';

    for(var i = 0; i < axList.length; i++) {
        var ax = axList[i];
        var isNew = (ax._showSpikeInitial === undefined);
        var hasChanged = isNew || !(ax.showspikes === ax._showspikes);

        if(isNew || (overwrite && hasChanged)) {
            ax._showSpikeInitial = ax.showspikes;
            hasOneAxisChanged = true;
        }

        if(allSpikesEnabled === 'on' && !ax.showspikes) {
            allSpikesEnabled = 'off';
        }
    }
    gd._fullLayout._cartesianSpikesEnabled = allSpikesEnabled;
    return hasOneAxisChanged;
};

axes.autoBin = function(data, ax, nbins, is2d, calendar, size) {
    var dataMin = Lib.aggNums(Math.min, null, data);
    var dataMax = Lib.aggNums(Math.max, null, data);

    if(ax.type === 'category' || ax.type === 'multicategory') {
        return {
            start: dataMin - 0.5,
            end: dataMax + 0.5,
            size: Math.max(1, Math.round(size) || 1),
            _dataSpan: dataMax - dataMin,
        };
    }

    if(!calendar) calendar = ax.calendar;

    // piggyback off tick code to make "nice" bin sizes and edges
    var dummyAx;
    if(ax.type === 'log') {
        dummyAx = {
            type: 'linear',
            range: [dataMin, dataMax]
        };
    } else {
        dummyAx = {
            type: ax.type,
            range: Lib.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar),
            calendar: calendar
        };
    }
    axes.setConvert(dummyAx);

    size = size && cleanTicks.dtick(size, dummyAx.type);

    if(size) {
        dummyAx.dtick = size;
        dummyAx.tick0 = cleanTicks.tick0(undefined, dummyAx.type, calendar);
    }
    else {
        var size0;
        if(nbins) size0 = ((dataMax - dataMin) / nbins);
        else {
            // totally auto: scale off std deviation so the highest bin is
            // somewhat taller than the total number of bins, but don't let
            // the size get smaller than the 'nice' rounded down minimum
            // difference between values
            var distinctData = Lib.distinctVals(data);
            var msexp = Math.pow(10, Math.floor(
                Math.log(distinctData.minDiff) / Math.LN10));
            var minSize = msexp * Lib.roundUp(
                distinctData.minDiff / msexp, [0.9, 1.9, 4.9, 9.9], true);
            size0 = Math.max(minSize, 2 * Lib.stdev(data) /
                Math.pow(data.length, is2d ? 0.25 : 0.4));

            // fallback if ax.d2c output BADNUMs
            // e.g. when user try to plot categorical bins
            // on a layout.xaxis.type: 'linear'
            if(!isNumeric(size0)) size0 = 1;
        }

        axes.autoTicks(dummyAx, size0);
    }


    var finalSize = dummyAx.dtick;
    var binStart = axes.tickIncrement(
            axes.tickFirst(dummyAx), finalSize, 'reverse', calendar);
    var binEnd, bincount;

    // check for too many data points right at the edges of bins
    // (>50% within 1% of bin edges) or all data points integral
    // and offset the bins accordingly
    if(typeof finalSize === 'number') {
        binStart = autoShiftNumericBins(binStart, data, dummyAx, dataMin, dataMax);

        bincount = 1 + Math.floor((dataMax - binStart) / finalSize);
        binEnd = binStart + bincount * finalSize;
    }
    else {
        // month ticks - should be the only nonlinear kind we have at this point.
        // dtick (as supplied by axes.autoTick) only has nonlinear values on
        // date and log axes, but even if you display a histogram on a log axis
        // we bin it on a linear axis (which one could argue against, but that's
        // a separate issue)
        if(dummyAx.dtick.charAt(0) === 'M') {
            binStart = autoShiftMonthBins(binStart, data, finalSize, dataMin, calendar);
        }

        // calculate the endpoint for nonlinear ticks - you have to
        // just increment until you're done
        binEnd = binStart;
        bincount = 0;
        while(binEnd <= dataMax) {
            binEnd = axes.tickIncrement(binEnd, finalSize, false, calendar);
            bincount++;
        }
    }

    return {
        start: ax.c2r(binStart, 0, calendar),
        end: ax.c2r(binEnd, 0, calendar),
        size: finalSize,
        _dataSpan: dataMax - dataMin
    };
};


function autoShiftNumericBins(binStart, data, ax, dataMin, dataMax) {
    var edgecount = 0;
    var midcount = 0;
    var intcount = 0;
    var blankCount = 0;

    function nearEdge(v) {
        // is a value within 1% of a bin edge?
        return (1 + (v - binStart) * 100 / ax.dtick) % 100 < 2;
    }

    for(var i = 0; i < data.length; i++) {
        if(data[i] % 1 === 0) intcount++;
        else if(!isNumeric(data[i])) blankCount++;

        if(nearEdge(data[i])) edgecount++;
        if(nearEdge(data[i] + ax.dtick / 2)) midcount++;
    }
    var dataCount = data.length - blankCount;

    if(intcount === dataCount && ax.type !== 'date') {
        // all integers: if bin size is <1, it's because
        // that was specifically requested (large nbins)
        // so respect that... but center the bins containing
        // integers on those integers
        if(ax.dtick < 1) {
            binStart = dataMin - 0.5 * ax.dtick;
        }
        // otherwise start half an integer down regardless of
        // the bin size, just enough to clear up endpoint
        // ambiguity about which integers are in which bins.
        else {
            binStart -= 0.5;
            if(binStart + ax.dtick < dataMin) binStart += ax.dtick;
        }
    }
    else if(midcount < dataCount * 0.1) {
        if(edgecount > dataCount * 0.3 ||
                nearEdge(dataMin) || nearEdge(dataMax)) {
            // lots of points at the edge, not many in the middle
            // shift half a bin
            var binshift = ax.dtick / 2;
            binStart += (binStart + binshift < dataMin) ? binshift : -binshift;
        }
    }
    return binStart;
}


function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) {
    var stats = Lib.findExactDates(data, calendar);
    // number of data points that needs to be an exact value
    // to shift that increment to (near) the bin center
    var threshold = 0.8;

    if(stats.exactDays > threshold) {
        var numMonths = Number(dtick.substr(1));

        if((stats.exactYears > threshold) && (numMonths % 12 === 0)) {
            // The exact middle of a non-leap-year is 1.5 days into July
            // so if we start the bins here, all but leap years will
            // get hover-labeled as exact years.
            binStart = axes.tickIncrement(binStart, 'M6', 'reverse') + ONEDAY * 1.5;
        }
        else if(stats.exactMonths > threshold) {
            // Months are not as clean, but if we shift half the *longest*
            // month (31/2 days) then 31-day months will get labeled exactly
            // and shorter months will get labeled with the correct month
            // but shifted 12-36 hours into it.
            binStart = axes.tickIncrement(binStart, 'M1', 'reverse') + ONEDAY * 15.5;
        }
        else {
            // Shifting half a day is exact, but since these are month bins it
            // will always give a somewhat odd-looking label, until we do something
            // smarter like showing the bin boundaries (or the bounds of the actual
            // data in each bin)
            binStart -= ONEDAY / 2;
        }
        var nextBinStart = axes.tickIncrement(binStart, dtick);

        if(nextBinStart <= dataMin) return nextBinStart;
    }
    return binStart;
}

// ----------------------------------------------------
// Ticks and grids
// ----------------------------------------------------

// ensure we have tick0, dtick, and tick rounding calculated
axes.prepTicks = function(ax) {
    var rng = Lib.simpleMap(ax.range, ax.r2l);

    // calculate max number of (auto) ticks to display based on plot size
    if(ax.tickmode === 'auto' || !ax.dtick) {
        var nt = ax.nticks;
        var minPx;

        if(!nt) {
            if(ax.type === 'category' || ax.type === 'multicategory') {
                minPx = ax.tickfont ? (ax.tickfont.size || 12) * 1.2 : 15;
                nt = ax._length / minPx;
            } else {
                minPx = ax._id.charAt(0) === 'y' ? 40 : 80;
                nt = Lib.constrain(ax._length / minPx, 4, 9) + 1;
            }

            // radial axes span half their domain,
            // multiply nticks value by two to get correct number of auto ticks.
            if(ax._name === 'radialaxis') nt *= 2;
        }

        // add a couple of extra digits for filling in ticks when we
        // have explicit tickvals without tick text
        if(ax.tickmode === 'array') nt *= 100;

        axes.autoTicks(ax, Math.abs(rng[1] - rng[0]) / nt);
        // check for a forced minimum dtick
        if(ax._minDtick > 0 && ax.dtick < ax._minDtick * 2) {
            ax.dtick = ax._minDtick;
            ax.tick0 = ax.l2r(ax._forceTick0);
        }
    }

    // check for missing tick0
    if(!ax.tick0) {
        ax.tick0 = (ax.type === 'date') ? '2000-01-01' : 0;
    }

    // ensure we don't try to make ticks below our minimum precision
    // see https://github.com/plotly/plotly.js/issues/2892
    if(ax.type === 'date' && ax.dtick < 0.1) ax.dtick = 0.1;

    // now figure out rounding of tick values
    autoTickRound(ax);
};

// calculate the ticks: text, values, positioning
// if ticks are set to automatic, determine the right values (tick0,dtick)
// in any case, set tickround to # of digits to round tick labels to,
// or codes to this effect for log and date scales
axes.calcTicks = function calcTicks(ax) {
    axes.prepTicks(ax);
    var rng = Lib.simpleMap(ax.range, ax.r2l);

    // now that we've figured out the auto values for formatting
    // in case we're missing some ticktext, we can break out for array ticks
    if(ax.tickmode === 'array') return arrayTicks(ax);

    // find the first tick
    ax._tmin = axes.tickFirst(ax);

    // add a tiny bit so we get ticks which may have rounded out
    var startTick = rng[0] * 1.0001 - rng[1] * 0.0001;
    var endTick = rng[1] * 1.0001 - rng[0] * 0.0001;
    // check for reversed axis
    var axrev = (rng[1] < rng[0]);

    // No visible ticks? Quit.
    // I've only seen this on category axes with all categories off the edge.
    if((ax._tmin < startTick) !== axrev) return [];

    // return the full set of tick vals
    var vals = [];
    if(ax.type === 'category' || ax.type === 'multicategory') {
        endTick = (axrev) ? Math.max(-0.5, endTick) :
            Math.min(ax._categories.length - 0.5, endTick);
    }

    var xPrevious = null;
    var maxTicks = Math.max(1000, ax._length || 0);
    for(var x = ax._tmin;
            (axrev) ? (x >= endTick) : (x <= endTick);
            x = axes.tickIncrement(x, ax.dtick, axrev, ax.calendar)) {
        // prevent infinite loops - no more than one tick per pixel,
        // and make sure each value is different from the previous
        if(vals.length > maxTicks || x === xPrevious) break;
        xPrevious = x;

        vals.push(x);
    }

    // If same angle over a full circle, the last tick vals is a duplicate.
    // TODO must do something similar for angular date axes.
    if(isAngular(ax) && Math.abs(rng[1] - rng[0]) === 360) {
        vals.pop();
    }

    // save the last tick as well as first, so we can
    // show the exponent only on the last one
    ax._tmax = vals[vals.length - 1];

    // for showing the rest of a date when the main tick label is only the
    // latter part: ax._prevDateHead holds what we showed most recently.
    // Start with it cleared and mark that we're in calcTicks (ie calculating a
    // whole string of these so we should care what the previous date head was!)
    ax._prevDateHead = '';
    ax._inCalcTicks = true;

    var ticksOut = new Array(vals.length);
    for(var i = 0; i < vals.length; i++) ticksOut[i] = axes.tickText(ax, vals[i]);

    ax._inCalcTicks = false;

    return ticksOut;
};

function arrayTicks(ax) {
    var vals = ax.tickvals;
    var text = ax.ticktext;
    var ticksOut = new Array(vals.length);
    var rng = Lib.simpleMap(ax.range, ax.r2l);
    var r0expanded = rng[0] * 1.0001 - rng[1] * 0.0001;
    var r1expanded = rng[1] * 1.0001 - rng[0] * 0.0001;
    var tickMin = Math.min(r0expanded, r1expanded);
    var tickMax = Math.max(r0expanded, r1expanded);
    var j = 0;

    // without a text array, just format the given values as any other ticks
    // except with more precision to the numbers
    if(!Array.isArray(text)) text = [];

    // make sure showing ticks doesn't accidentally add new categories
    // TODO multicategory, if we allow ticktext / tickvals
    var tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l;

    // array ticks on log axes always show the full number
    // (if no explicit ticktext overrides it)
    if(ax.type === 'log' && String(ax.dtick).charAt(0) !== 'L') {
        ax.dtick = 'L' + Math.pow(10, Math.floor(Math.min(ax.range[0], ax.range[1])) - 1);
    }

    for(var i = 0; i < vals.length; i++) {
        var vali = tickVal2l(vals[i]);
        if(vali > tickMin && vali < tickMax) {
            if(text[i] === undefined) ticksOut[j] = axes.tickText(ax, vali);
            else ticksOut[j] = tickTextObj(ax, vali, String(text[i]));
            j++;
        }
    }

    if(j < vals.length) ticksOut.splice(j, vals.length - j);

    return ticksOut;
}

var roundBase10 = [2, 5, 10];
var roundBase24 = [1, 2, 3, 6, 12];
var roundBase60 = [1, 2, 5, 10, 15, 30];
// 2&3 day ticks are weird, but need something btwn 1&7
var roundDays = [1, 2, 3, 7, 14];
// approx. tick positions for log axes, showing all (1) and just 1, 2, 5 (2)
// these don't have to be exact, just close enough to round to the right value
var roundLog1 = [-0.046, 0, 0.301, 0.477, 0.602, 0.699, 0.778, 0.845, 0.903, 0.954, 1];
var roundLog2 = [-0.301, 0, 0.301, 0.699, 1];
// N.B. `thetaunit; 'radians' angular axes must be converted to degrees
var roundAngles = [15, 30, 45, 90, 180];

function roundDTick(roughDTick, base, roundingSet) {
    return base * Lib.roundUp(roughDTick / base, roundingSet);
}

// autoTicks: calculate best guess at pleasant ticks for this axis
// inputs:
//      ax - an axis object
//      roughDTick - rough tick spacing (to be turned into a nice round number)
// outputs (into ax):
//   tick0: starting point for ticks (not necessarily on the graph)
//      usually 0 for numeric (=10^0=1 for log) or jan 1, 2000 for dates
//   dtick: the actual, nice round tick spacing, usually a little larger than roughDTick
//      if the ticks are spaced linearly (linear scale, categories,
//          log with only full powers, date ticks < month),
//          this will just be a number
//      months: M#
//      years: M# where # is 12*number of years
//      log with linear ticks: L# where # is the linear tick spacing
//      log showing powers plus some intermediates:
//          D1 shows all digits, D2 shows 2 and 5
axes.autoTicks = function(ax, roughDTick) {
    var base;

    function getBase(v) {
        return Math.pow(v, Math.floor(Math.log(roughDTick) / Math.LN10));
    }

    if(ax.type === 'date') {
        ax.tick0 = Lib.dateTick0(ax.calendar);
        // the criteria below are all based on the rough spacing we calculate
        // being > half of the final unit - so precalculate twice the rough val
        var roughX2 = 2 * roughDTick;

        if(roughX2 > ONEAVGYEAR) {
            roughDTick /= ONEAVGYEAR;
            base = getBase(10);
            ax.dtick = 'M' + (12 * roundDTick(roughDTick, base, roundBase10));
        }
        else if(roughX2 > ONEAVGMONTH) {
            roughDTick /= ONEAVGMONTH;
            ax.dtick = 'M' + roundDTick(roughDTick, 1, roundBase24);
        }
        else if(roughX2 > ONEDAY) {
            ax.dtick = roundDTick(roughDTick, ONEDAY, roundDays);
            // get week ticks on sunday
            // this will also move the base tick off 2000-01-01 if dtick is
            // 2 or 3 days... but that's a weird enough case that we'll ignore it.
            ax.tick0 = Lib.dateTick0(ax.calendar, true);
        }
        else if(roughX2 > ONEHOUR) {
            ax.dtick = roundDTick(roughDTick, ONEHOUR, roundBase24);
        }
        else if(roughX2 > ONEMIN) {
            ax.dtick = roundDTick(roughDTick, ONEMIN, roundBase60);
        }
        else if(roughX2 > ONESEC) {
            ax.dtick = roundDTick(roughDTick, ONESEC, roundBase60);
        }
        else {
            // milliseconds
            base = getBase(10);
            ax.dtick = roundDTick(roughDTick, base, roundBase10);
        }
    }
    else if(ax.type === 'log') {
        ax.tick0 = 0;
        var rng = Lib.simpleMap(ax.range, ax.r2l);

        if(roughDTick > 0.7) {
            // only show powers of 10
            ax.dtick = Math.ceil(roughDTick);
        }
        else if(Math.abs(rng[1] - rng[0]) < 1) {
            // span is less than one power of 10
            var nt = 1.5 * Math.abs((rng[1] - rng[0]) / roughDTick);

            // ticks on a linear scale, labeled fully
            roughDTick = Math.abs(Math.pow(10, rng[1]) -
                Math.pow(10, rng[0])) / nt;
            base = getBase(10);
            ax.dtick = 'L' + roundDTick(roughDTick, base, roundBase10);
        }
        else {
            // include intermediates between powers of 10,
            // labeled with small digits
            // ax.dtick = "D2" (show 2 and 5) or "D1" (show all digits)
            ax.dtick = (roughDTick > 0.3) ? 'D2' : 'D1';
        }
    }
    else if(ax.type === 'category' || ax.type === 'multicategory') {
        ax.tick0 = 0;
        ax.dtick = Math.ceil(Math.max(roughDTick, 1));
    }
    else if(isAngular(ax)) {
        ax.tick0 = 0;
        base = 1;
        ax.dtick = roundDTick(roughDTick, base, roundAngles);
    }
    else {
        // auto ticks always start at 0
        ax.tick0 = 0;
        base = getBase(10);
        ax.dtick = roundDTick(roughDTick, base, roundBase10);
    }

    // prevent infinite loops
    if(ax.dtick === 0) ax.dtick = 1;

    // TODO: this is from log axis histograms with autorange off
    if(!isNumeric(ax.dtick) && typeof ax.dtick !== 'string') {
        var olddtick = ax.dtick;
        ax.dtick = 1;
        throw 'ax.dtick error: ' + String(olddtick);
    }
};

// after dtick is already known, find tickround = precision
// to display in tick labels
//   for numeric ticks, integer # digits after . to round to
//   for date ticks, the last date part to show (y,m,d,H,M,S)
//      or an integer # digits past seconds
function autoTickRound(ax) {
    var dtick = ax.dtick;

    ax._tickexponent = 0;
    if(!isNumeric(dtick) && typeof dtick !== 'string') {
        dtick = 1;
    }

    if(ax.type === 'category' || ax.type === 'multicategory') {
        ax._tickround = null;
    }
    if(ax.type === 'date') {
        // If tick0 is unusual, give tickround a bit more information
        // not necessarily *all* the information in tick0 though, if it's really odd
        // minimal string length for tick0: 'd' is 10, 'M' is 16, 'S' is 19
        // take off a leading minus (year < 0) and i (intercalary month) so length is consistent
        var tick0ms = ax.r2l(ax.tick0);
        var tick0str = ax.l2r(tick0ms).replace(/(^-|i)/g, '');
        var tick0len = tick0str.length;

        if(String(dtick).charAt(0) === 'M') {
            // any tick0 more specific than a year: alway show the full date
            if(tick0len > 10 || tick0str.substr(5) !== '01-01') ax._tickround = 'd';
            // show the month unless ticks are full multiples of a year
            else ax._tickround = (+(dtick.substr(1)) % 12 === 0) ? 'y' : 'm';
        }
        else if((dtick >= ONEDAY && tick0len <= 10) || (dtick >= ONEDAY * 15)) ax._tickround = 'd';
        else if((dtick >= ONEMIN && tick0len <= 16) || (dtick >= ONEHOUR)) ax._tickround = 'M';
        else if((dtick >= ONESEC && tick0len <= 19) || (dtick >= ONEMIN)) ax._tickround = 'S';
        else {
            // tickround is a number of digits of fractional seconds
            // of any two adjacent ticks, at least one will have the maximum fractional digits
            // of all possible ticks - so take the max. length of tick0 and the next one
            var tick1len = ax.l2r(tick0ms + dtick).replace(/^-/, '').length;
            ax._tickround = Math.max(tick0len, tick1len) - 20;

            // We shouldn't get here... but in case there's a situation I'm
            // not thinking of where tick0str and tick1str are identical or
            // something, fall back on maximum precision
            if(ax._tickround < 0) ax._tickround = 4;
        }
    }
    else if(isNumeric(dtick) || dtick.charAt(0) === 'L') {
        // linear or log (except D1, D2)
        var rng = ax.range.map(ax.r2d || Number);
        if(!isNumeric(dtick)) dtick = Number(dtick.substr(1));
        // 2 digits past largest digit of dtick
        ax._tickround = 2 - Math.floor(Math.log(dtick) / Math.LN10 + 0.01);

        var maxend = Math.max(Math.abs(rng[0]), Math.abs(rng[1]));

        var rangeexp = Math.floor(Math.log(maxend) / Math.LN10 + 0.01);
        if(Math.abs(rangeexp) > 3) {
            if(isSIFormat(ax.exponentformat) && !beyondSI(rangeexp)) {
                ax._tickexponent = 3 * Math.round((rangeexp - 1) / 3);
            }
            else ax._tickexponent = rangeexp;
        }
    }
    // D1 or D2 (log)
    else ax._tickround = null;
}

// months and years don't have constant millisecond values
// (but a year is always 12 months so we only need months)
// log-scale ticks are also not consistently spaced, except
// for pure powers of 10
// numeric ticks always have constant differences, other datetime ticks
// can all be calculated as constant number of milliseconds
axes.tickIncrement = function(x, dtick, axrev, calendar) {
    var axSign = axrev ? -1 : 1;

    // includes linear, all dates smaller than month, and pure 10^n in log
    if(isNumeric(dtick)) return x + axSign * dtick;

    // everything else is a string, one character plus a number
    var tType = dtick.charAt(0);
    var dtSigned = axSign * Number(dtick.substr(1));

    // Dates: months (or years - see Lib.incrementMonth)
    if(tType === 'M') return Lib.incrementMonth(x, dtSigned, calendar);

    // Log scales: Linear, Digits
    else if(tType === 'L') return Math.log(Math.pow(10, x) + dtSigned) / Math.LN10;

    // log10 of 2,5,10, or all digits (logs just have to be
    // close enough to round)
    else if(tType === 'D') {
        var tickset = (dtick === 'D2') ? roundLog2 : roundLog1;
        var x2 = x + axSign * 0.01;
        var frac = Lib.roundUp(Lib.mod(x2, 1), tickset, axrev);

        return Math.floor(x2) +
            Math.log(d3.round(Math.pow(10, frac), 1)) / Math.LN10;
    }
    else throw 'unrecognized dtick ' + String(dtick);
};

// calculate the first tick on an axis
axes.tickFirst = function(ax) {
    var r2l = ax.r2l || Number;
    var rng = Lib.simpleMap(ax.range, r2l);
    var axrev = rng[1] < rng[0];
    var sRound = axrev ? Math.floor : Math.ceil;
    // add a tiny extra bit to make sure we get ticks
    // that may have been rounded out
    var r0 = rng[0] * 1.0001 - rng[1] * 0.0001;
    var dtick = ax.dtick;
    var tick0 = r2l(ax.tick0);

    if(isNumeric(dtick)) {
        var tmin = sRound((r0 - tick0) / dtick) * dtick + tick0;

        // make sure no ticks outside the category list
        if(ax.type === 'category' || ax.type === 'multicategory') {
            tmin = Lib.constrain(tmin, 0, ax._categories.length - 1);
        }
        return tmin;
    }

    var tType = dtick.charAt(0);
    var dtNum = Number(dtick.substr(1));

    // Dates: months (or years)
    if(tType === 'M') {
        var cnt = 0;
        var t0 = tick0;
        var t1, mult, newDTick;

        // This algorithm should work for *any* nonlinear (but close to linear!)
        // tick spacing. Limit to 10 iterations, for gregorian months it's normally <=3.
        while(cnt < 10) {
            t1 = axes.tickIncrement(t0, dtick, axrev, ax.calendar);
            if((t1 - r0) * (t0 - r0) <= 0) {
                // t1 and t0 are on opposite sides of r0! we've succeeded!
                if(axrev) return Math.min(t0, t1);
                return Math.max(t0, t1);
            }
            mult = (r0 - ((t0 + t1) / 2)) / (t1 - t0);
            newDTick = tType + ((Math.abs(Math.round(mult)) || 1) * dtNum);
            t0 = axes.tickIncrement(t0, newDTick, mult < 0 ? !axrev : axrev, ax.calendar);
            cnt++;
        }
        Lib.error('tickFirst did not converge', ax);
        return t0;
    }

    // Log scales: Linear, Digits
    else if(tType === 'L') {
        return Math.log(sRound(
            (Math.pow(10, r0) - tick0) / dtNum) * dtNum + tick0) / Math.LN10;
    }
    else if(tType === 'D') {
        var tickset = (dtick === 'D2') ? roundLog2 : roundLog1;
        var frac = Lib.roundUp(Lib.mod(r0, 1), tickset, axrev);

        return Math.floor(r0) +
            Math.log(d3.round(Math.pow(10, frac), 1)) / Math.LN10;
    }
    else throw 'unrecognized dtick ' + String(dtick);
};

// draw the text for one tick.
// px,py are the location on gd.paper
// prefix is there so the x axis ticks can be dropped a line
// ax is the axis layout, x is the tick value
// hover is a (truthy) flag for whether to show numbers with a bit
// more precision for hovertext
axes.tickText = function(ax, x, hover) {
    var out = tickTextObj(ax, x);
    var arrayMode = ax.tickmode === 'array';
    var extraPrecision = hover || arrayMode;
    var axType = ax.type;
    // TODO multicategory, if we allow ticktext / tickvals
    var tickVal2l = axType === 'category' ? ax.d2l_noadd : ax.d2l;
    var i;

    if(arrayMode && Array.isArray(ax.ticktext)) {
        var rng = Lib.simpleMap(ax.range, ax.r2l);
        var minDiff = Math.abs(rng[1] - rng[0]) / 10000;

        for(i = 0; i < ax.ticktext.length; i++) {
            if(Math.abs(x - tickVal2l(ax.tickvals[i])) < minDiff) break;
        }
        if(i < ax.ticktext.length) {
            out.text = String(ax.ticktext[i]);
            return out;
        }
    }

    function isHidden(showAttr) {
        if(showAttr === undefined) return true;
        if(hover) return showAttr === 'none';

        var firstOrLast = {
            first: ax._tmin,
            last: ax._tmax
        }[showAttr];

        return showAttr !== 'all' && x !== firstOrLast;
    }

    var hideexp = hover ?
        'never' :
        ax.exponentformat !== 'none' && isHidden(ax.showexponent) ? 'hide' : '';

    if(axType === 'date') formatDate(ax, out, hover, extraPrecision);
    else if(axType === 'log') formatLog(ax, out, hover, extraPrecision, hideexp);
    else if(axType === 'category') formatCategory(ax, out);
    else if(axType === 'multicategory') formatMultiCategory(ax, out, hover);
    else if(isAngular(ax)) formatAngle(ax, out, hover, extraPrecision, hideexp);
    else formatLinear(ax, out, hover, extraPrecision, hideexp);

    // add prefix and suffix
    if(ax.tickprefix && !isHidden(ax.showtickprefix)) out.text = ax.tickprefix + out.text;
    if(ax.ticksuffix && !isHidden(ax.showticksuffix)) out.text += ax.ticksuffix;

    // Setup ticks and grid lines boundaries
    // at 1/2 a 'category' to the left/bottom
    if(ax.tickson === 'boundaries' || ax.showdividers) {
        var inbounds = function(v) {
            var p = ax.l2p(v);
            return p >= 0 && p <= ax._length ? v : null;
        };

        out.xbnd = [
            inbounds(out.x - 0.5),
            inbounds(out.x + ax.dtick - 0.5)
        ];
    }

    return out;
};

/**
 * create text for a hover label on this axis, with special handling of
 * log axes (where negative values can't be displayed but can appear in hover text)
 *
 * @param {object} ax: the axis to format text for
 * @param {number} val: calcdata value to format
 * @param {Optional(number)} val2: a second value to display
 *
 * @returns {string} `val` formatted as a string appropriate to this axis, or
 *     `val` and `val2` as a range (ie '<val> - <val2>') if `val2` is provided and
 *     it's different from `val`.
 */
axes.hoverLabelText = function(ax, val, val2) {
    if(val2 !== BADNUM && val2 !== val) {
        return axes.hoverLabelText(ax, val) + ' - ' + axes.hoverLabelText(ax, val2);
    }

    var logOffScale = (ax.type === 'log' && val <= 0);
    var tx = axes.tickText(ax, ax.c2l(logOffScale ? -val : val), 'hover').text;

    if(logOffScale) {
        return val === 0 ? '0' : MINUS_SIGN + tx;
    }

    // TODO: should we do something special if the axis calendar and
    // the data calendar are different? Somehow display both dates with
    // their system names? Right now it will just display in the axis calendar
    // but users could add the other one as text.
    return tx;
};

function tickTextObj(ax, x, text) {
    var tf = ax.tickfont || {};

    return {
        x: x,
        dx: 0,
        dy: 0,
        text: text || '',
        fontSize: tf.size,
        font: tf.family,
        fontColor: tf.color
    };
}

function formatDate(ax, out, hover, extraPrecision) {
    var tr = ax._tickround;
    var fmt = (hover && ax.hoverformat) || axes.getTickFormat(ax);

    if(extraPrecision) {
        // second or sub-second precision: extra always shows max digits.
        // for other fields, extra precision just adds one field.
        if(isNumeric(tr)) tr = 4;
        else tr = {y: 'm', m: 'd', d: 'M', M: 'S', S: 4}[tr];
    }

    var dateStr = Lib.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat);
    var headStr;

    var splitIndex = dateStr.indexOf('\n');
    if(splitIndex !== -1) {
        headStr = dateStr.substr(splitIndex + 1);
        dateStr = dateStr.substr(0, splitIndex);
    }

    if(extraPrecision) {
        // if extraPrecision led to trailing zeros, strip them off
        // actually, this can lead to removing even more zeros than
        // in the original rounding, but that's fine because in these
        // contexts uniformity is not so important (if there's even
        // anything to be uniform with!)

        // can we remove the whole time part?
        if(dateStr === '00:00:00' || dateStr === '00:00') {
            dateStr = headStr;
            headStr = '';
        }
        else if(dateStr.length === 8) {
            // strip off seconds if they're zero (zero fractional seconds
            // are already omitted)
            // but we never remove minutes and leave just hours
            dateStr = dateStr.replace(/:00$/, '');
        }
    }

    if(headStr) {
        if(hover) {
            // hover puts it all on one line, so headPart works best up front
            // except for year headPart: turn this into "Jan 1, 2000" etc.
            if(tr === 'd') dateStr += ', ' + headStr;
            else dateStr = headStr + (dateStr ? ', ' + dateStr : '');
        }
        else if(!ax._inCalcTicks || (headStr !== ax._prevDateHead)) {
            dateStr += '<br>' + headStr;
            ax._prevDateHead = headStr;
        }
    }

    out.text = dateStr;
}

function formatLog(ax, out, hover, extraPrecision, hideexp) {
    var dtick = ax.dtick;
    var x = out.x;
    var tickformat = ax.tickformat;
    var dtChar0 = typeof dtick === 'string' && dtick.charAt(0);

    if(hideexp === 'never') {
        // If this is a hover label, then we must *never* hide the exponent
        // for the sake of display, which could give the wrong value by
        // potentially many orders of magnitude. If hideexp was 'never', then
        // it's now succeeded by preventing the other condition from automating
        // this choice. Thus we can unset it so that the axis formatting takes
        // precedence.
        hideexp = '';
    }

    if(extraPrecision && (dtChar0 !== 'L')) {
        dtick = 'L3';
        dtChar0 = 'L';
    }

    if(tickformat || (dtChar0 === 'L')) {
        out.text = numFormat(Math.pow(10, x), ax, hideexp, extraPrecision);
    }
    else if(isNumeric(dtick) || ((dtChar0 === 'D') && (Lib.mod(x + 0.01, 1) < 0.1))) {
        var p = Math.round(x);
        var absP = Math.abs(p);
        var exponentFormat = ax.exponentformat;
        if(exponentFormat === 'power' || (isSIFormat(exponentFormat) && beyondSI(p))) {
            if(p === 0) out.text = 1;
            else if(p === 1) out.text = '10';
            else out.text = '10<sup>' + (p > 1 ? '' : MINUS_SIGN) + absP + '</sup>';

            out.fontSize *= 1.25;
        }
        else if((exponentFormat === 'e' || exponentFormat === 'E') && absP > 2) {
            out.text = '1' + exponentFormat + (p > 0 ? '+' : MINUS_SIGN) + absP;
        }
        else {
            out.text = numFormat(Math.pow(10, x), ax, '', 'fakehover');
            if(dtick === 'D1' && ax._id.charAt(0) === 'y') {
                out.dy -= out.fontSize / 6;
            }
        }
    }
    else if(dtChar0 === 'D') {
        out.text = String(Math.round(Math.pow(10, Lib.mod(x, 1))));
        out.fontSize *= 0.75;
    }
    else throw 'unrecognized dtick ' + String(dtick);

    // if 9's are printed on log scale, move the 10's away a bit
    if(ax.dtick === 'D1') {
        var firstChar = String(out.text).charAt(0);
        if(firstChar === '0' || firstChar === '1') {
            if(ax._id.charAt(0) === 'y') {
                out.dx -= out.fontSize / 4;
            }
            else {
                out.dy += out.fontSize / 2;
                out.dx += (ax.range[1] > ax.range[0] ? 1 : -1) *
                    out.fontSize * (x < 0 ? 0.5 : 0.25);
            }
        }
    }
}

function formatCategory(ax, out) {
    var tt = ax._categories[Math.round(out.x)];
    if(tt === undefined) tt = '';
    out.text = String(tt);
}

function formatMultiCategory(ax, out, hover) {
    var v = Math.round(out.x);
    var cats = ax._categories[v] || [];
    var tt = cats[1] === undefined ? '' : String(cats[1]);
    var tt2 = cats[0] === undefined ? '' : String(cats[0]);

    if(hover) {
        // TODO is this what we want?
        out.text = tt2 + ' - ' + tt;
    } else {
        // setup for secondary labels
        out.text = tt;
        out.text2 = tt2;
    }
}

function formatLinear(ax, out, hover, extraPrecision, hideexp) {
    if(hideexp === 'never') {
        // If this is a hover label, then we must *never* hide the exponent
        // for the sake of display, which could give the wrong value by
        // potentially many orders of magnitude. If hideexp was 'never', then
        // it's now succeeded by preventing the other condition from automating
        // this choice. Thus we can unset it so that the axis formatting takes
        // precedence.
        hideexp = '';
    } else if(ax.showexponent === 'all' && Math.abs(out.x / ax.dtick) < 1e-6) {
        // don't add an exponent to zero if we're showing all exponents
        // so the only reason you'd show an exponent on zero is if it's the
        // ONLY tick to get an exponent (first or last)
        hideexp = 'hide';
    }
    out.text = numFormat(out.x, ax, hideexp, extraPrecision);
}

function formatAngle(ax, out, hover, extraPrecision, hideexp) {
    if(ax.thetaunit === 'radians' && !hover) {
        var num = out.x / 180;

        if(num === 0) {
            out.text = '0';
        } else {
            var frac = num2frac(num);

            if(frac[1] >= 100) {
                out.text = numFormat(Lib.deg2rad(out.x), ax, hideexp, extraPrecision);
            } else {
                var isNeg = out.x < 0;

                if(frac[1] === 1) {
                    if(frac[0] === 1) out.text = 'π';
                    else out.text = frac[0] + 'π';
                } else {
                    out.text = [
                        '<sup>', frac[0], '</sup>',
                        '⁄',
                        '<sub>', frac[1], '</sub>',
                        'π'
                    ].join('');
                }

                if(isNeg) out.text = MINUS_SIGN + out.text;
            }
        }
    } else {
        out.text = numFormat(out.x, ax, hideexp, extraPrecision);
    }
}

// inspired by
// https://github.com/yisibl/num2fraction/blob/master/index.js
function num2frac(num) {
    function almostEq(a, b) {
        return Math.abs(a - b) <= 1e-6;
    }

    function findGCD(a, b) {
        return almostEq(b, 0) ? a : findGCD(b, a % b);
    }

    function findPrecision(n) {
        var e = 1;
        while(!almostEq(Math.round(n * e) / e, n)) {
            e *= 10;
        }
        return e;
    }

    var precision = findPrecision(num);
    var number = num * precision;
    var gcd = Math.abs(findGCD(number, precision));

    return [
        // numerator
        Math.round(number / gcd),
        // denominator
        Math.round(precision / gcd)
    ];
}

// format a number (tick value) according to the axis settings
// new, more reliable procedure than d3.round or similar:
// add half the rounding increment, then stringify and truncate
// also automatically switch to sci. notation
var SIPREFIXES = ['f', 'p', 'n', 'μ', 'm', '', 'k', 'M', 'G', 'T'];

function isSIFormat(exponentFormat) {
    return exponentFormat === 'SI' || exponentFormat === 'B';
}

// are we beyond the range of common SI prefixes?
// 10^-16 -> 1x10^-16
// 10^-15 -> 1f
// ...
// 10^14 -> 100T
// 10^15 -> 1x10^15
// 10^16 -> 1x10^16
function beyondSI(exponent) {
    return exponent > 14 || exponent < -15;
}

function numFormat(v, ax, fmtoverride, hover) {
    var isNeg = v < 0;
    // max number of digits past decimal point to show
    var tickRound = ax._tickround;
    var exponentFormat = fmtoverride || ax.exponentformat || 'B';
    var exponent = ax._tickexponent;
    var tickformat = axes.getTickFormat(ax);
    var separatethousands = ax.separatethousands;

    // special case for hover: set exponent just for this value, and
    // add a couple more digits of precision over tick labels
    if(hover) {
        // make a dummy axis obj to get the auto rounding and exponent
        var ah = {
            exponentformat: exponentFormat,
            dtick: ax.showexponent === 'none' ? ax.dtick :
                (isNumeric(v) ? Math.abs(v) || 1 : 1),
            // if not showing any exponents, don't change the exponent
            // from what we calculate
            range: ax.showexponent === 'none' ? ax.range.map(ax.r2d) : [0, v || 1]
        };
        autoTickRound(ah);
        tickRound = (Number(ah._tickround) || 0) + 4;
        exponent = ah._tickexponent;
        if(ax.hoverformat) tickformat = ax.hoverformat;
    }

    if(tickformat) return ax._numFormat(tickformat)(v).replace(/-/g, MINUS_SIGN);

    // 'epsilon' - rounding increment
    var e = Math.pow(10, -tickRound) / 2;

    // exponentFormat codes:
    // 'e' (1.2e+6, default)
    // 'E' (1.2E+6)
    // 'SI' (1.2M)
    // 'B' (same as SI except 10^9=B not G)
    // 'none' (1200000)
    // 'power' (1.2x10^6)
    // 'hide' (1.2, use 3rd argument=='hide' to eg
    //      only show exponent on last tick)
    if(exponentFormat === 'none') exponent = 0;

    // take the sign out, put it back manually at the end
    // - makes cases easier
    v = Math.abs(v);
    if(v < e) {
        // 0 is just 0, but may get exponent if it's the last tick
        v = '0';
        isNeg = false;
    }
    else {
        v += e;
        // take out a common exponent, if any
        if(exponent) {
            v *= Math.pow(10, -exponent);
            tickRound += exponent;
        }
        // round the mantissa
        if(tickRound === 0) v = String(Math.floor(v));
        else if(tickRound < 0) {
            v = String(Math.round(v));
            v = v.substr(0, v.length + tickRound);
            for(var i = tickRound; i < 0; i++) v += '0';
        }
        else {
            v = String(v);
            var dp = v.indexOf('.') + 1;
            if(dp) v = v.substr(0, dp + tickRound).replace(/\.?0+$/, '');
        }
        // insert appropriate decimal point and thousands separator
        v = Lib.numSeparate(v, ax._separators, separatethousands);
    }

    // add exponent
    if(exponent && exponentFormat !== 'hide') {
        if(isSIFormat(exponentFormat) && beyondSI(exponent)) exponentFormat = 'power';

        var signedExponent;
        if(exponent < 0) signedExponent = MINUS_SIGN + -exponent;
        else if(exponentFormat !== 'power') signedExponent = '+' + exponent;
        else signedExponent = String(exponent);

        if(exponentFormat === 'e' || exponentFormat === 'E') {
            v += exponentFormat + signedExponent;
        }
        else if(exponentFormat === 'power') {
            v += '×10<sup>' + signedExponent + '</sup>';
        }
        else if(exponentFormat === 'B' && exponent === 9) {
            v += 'B';
        }
        else if(isSIFormat(exponentFormat)) {
            v += SIPREFIXES[exponent / 3 + 5];
        }
    }

    // put sign back in and return
    // replace standard minus character (which is technically a hyphen)
    // with a true minus sign
    if(isNeg) return MINUS_SIGN + v;
    return v;
}

axes.getTickFormat = function(ax) {
    var i;

    function convertToMs(dtick) {
        return typeof dtick !== 'string' ? dtick : Number(dtick.replace('M', '')) * ONEAVGMONTH;
    }

    function compareLogTicks(left, right) {
        var priority = ['L', 'D'];
        if(typeof left === typeof right) {
            if(typeof left === 'number') {
                return left - right;
            } else {
                var leftPriority = priority.indexOf(left.charAt(0));
                var rightPriority = priority.indexOf(right.charAt(0));
                if(leftPriority === rightPriority) {
                    return Number(left.replace(/(L|D)/g, '')) - Number(right.replace(/(L|D)/g, ''));
                } else {
                    return leftPriority - rightPriority;
                }
            }
        } else {
            return typeof left === 'number' ? 1 : -1;
        }
    }

    function isProperStop(dtick, range, convert) {
        var convertFn = convert || function(x) { return x;};
        var leftDtick = range[0];
        var rightDtick = range[1];
        return ((!leftDtick && typeof leftDtick !== 'number') || convertFn(leftDtick) <= convertFn(dtick)) &&
               ((!rightDtick && typeof rightDtick !== 'number') || convertFn(rightDtick) >= convertFn(dtick));
    }

    function isProperLogStop(dtick, range) {
        var isLeftDtickNull = range[0] === null;
        var isRightDtickNull = range[1] === null;
        var isDtickInRangeLeft = compareLogTicks(dtick, range[0]) >= 0;
        var isDtickInRangeRight = compareLogTicks(dtick, range[1]) <= 0;
        return (isLeftDtickNull || isDtickInRangeLeft) && (isRightDtickNull || isDtickInRangeRight);
    }

    var tickstop, stopi;
    if(ax.tickformatstops && ax.tickformatstops.length > 0) {
        switch(ax.type) {
            case 'date':
            case 'linear': {
                for(i = 0; i < ax.tickformatstops.length; i++) {
                    stopi = ax.tickformatstops[i];
                    if(stopi.enabled && isProperStop(ax.dtick, stopi.dtickrange, convertToMs)) {
                        tickstop = stopi;
                        break;
                    }
                }
                break;
            }
            case 'log': {
                for(i = 0; i < ax.tickformatstops.length; i++) {
                    stopi = ax.tickformatstops[i];
                    if(stopi.enabled && isProperLogStop(ax.dtick, stopi.dtickrange)) {
                        tickstop = stopi;
                        break;
                    }
                }
                break;
            }
            default:
        }
    }
    return tickstop ? tickstop.value : ax.tickformat;
};

// getSubplots - extract all subplot IDs we need
// as an array of items like 'xy', 'x2y', 'x2y2'...
// sorted by x (x,x2,x3...) then y
// optionally restrict to only subplots containing axis object ax
//
// NOTE: this is currently only used OUTSIDE plotly.js (toolpanel, webapp)
// ideally we get rid of it there (or just copy this there) and remove it here
axes.getSubplots = function(gd, ax) {
    var subplotObj = gd._fullLayout._subplots;
    var allSubplots = subplotObj.cartesian.concat(subplotObj.gl2d || []);

    var out = ax ? axes.findSubplotsWithAxis(allSubplots, ax) : allSubplots;

    out.sort(function(a, b) {
        var aParts = a.substr(1).split('y');
        var bParts = b.substr(1).split('y');

        if(aParts[0] === bParts[0]) return +aParts[1] - +bParts[1];
        return +aParts[0] - +bParts[0];
    });

    return out;
};

// find all subplots with axis 'ax'
// NOTE: this is only used in axes.getSubplots (only used outside plotly.js) and
// gl2d/convert (where it restricts axis subplots to only those with gl2d)
axes.findSubplotsWithAxis = function(subplots, ax) {
    var axMatch = new RegExp(
        (ax._id.charAt(0) === 'x') ? ('^' + ax._id + 'y') : (ax._id + '$')
    );
    var subplotsWithAx = [];

    for(var i = 0; i < subplots.length; i++) {
        var sp = subplots[i];
        if(axMatch.test(sp)) subplotsWithAx.push(sp);
    }

    return subplotsWithAx;
};

// makeClipPaths: prepare clipPaths for all single axes and all possible xy pairings
axes.makeClipPaths = function(gd) {
    var fullLayout = gd._fullLayout;

    // for more info: https://github.com/plotly/plotly.js/issues/2595
    if(fullLayout._hasOnlyLargeSploms) return;

    var fullWidth = {_offset: 0, _length: fullLayout.width, _id: ''};
    var fullHeight = {_offset: 0, _length: fullLayout.height, _id: ''};
    var xaList = axes.list(gd, 'x', true);
    var yaList = axes.list(gd, 'y', true);
    var clipList = [];
    var i, j;

    for(i = 0; i < xaList.length; i++) {
        clipList.push({x: xaList[i], y: fullHeight});
        for(j = 0; j < yaList.length; j++) {
            if(i === 0) clipList.push({x: fullWidth, y: yaList[j]});
            clipList.push({x: xaList[i], y: yaList[j]});
        }
    }

    // selectors don't work right with camelCase tags,
    // have to use class instead
    // https://groups.google.com/forum/#!topic/d3-js/6EpAzQ2gU9I
    var axClips = fullLayout._clips.selectAll('.axesclip')
        .data(clipList, function(d) { return d.x._id + d.y._id; });

    axClips.enter().append('clipPath')
        .classed('axesclip', true)
        .attr('id', function(d) { return 'clip' + fullLayout._uid + d.x._id + d.y._id; })
      .append('rect');

    axClips.exit().remove();

    axClips.each(function(d) {
        d3.select(this).select('rect').attr({
            x: d.x._offset || 0,
            y: d.y._offset || 0,
            width: d.x._length || 1,
            height: d.y._length || 1
        });
    });
};

/**
 * Main multi-axis drawing routine!
 *
 * @param {DOM element} gd : graph div
 * @param {string or array of strings} arg : polymorphic argument
 * @param {object} opts:
 * - @param {boolean} skipTitle : optional flag to skip axis title draw/update
 *
 * Signature 1: Axes.draw(gd, 'redraw')
 *   use this to clear and redraw all axes on graph
 *
 * Signature 2: Axes.draw(gd, '')
 *   use this to draw all axes on graph w/o the selectAll().remove()
 *   of the 'redraw' signature
 *
 * Signature 3: Axes.draw(gd, [axId, axId2, ...])
 *   where the items are axis id string,
 *   use this to update multiple axes in one call
 *
 * N.B draw updates:
 * - ax._r (stored range for use by zoom/pan)
 * - ax._rl (stored linearized range for use by zoom/pan)
 */
axes.draw = function(gd, arg, opts) {
    var fullLayout = gd._fullLayout;

    if(arg === 'redraw') {
        fullLayout._paper.selectAll('g.subplot').each(function(d) {
            var id = d[0];
            var plotinfo = fullLayout._plots[id];
            var xa = plotinfo.xaxis;
            var ya = plotinfo.yaxis;

            plotinfo.xaxislayer.selectAll('.' + xa._id + 'tick').remove();
            plotinfo.yaxislayer.selectAll('.' + ya._id + 'tick').remove();
            plotinfo.xaxislayer.selectAll('.' + xa._id + 'tick2').remove();
            plotinfo.yaxislayer.selectAll('.' + ya._id + 'tick2').remove();
            plotinfo.xaxislayer.selectAll('.' + xa._id + 'divider').remove();
            plotinfo.yaxislayer.selectAll('.' + ya._id + 'divider').remove();

            if(plotinfo.gridlayer) plotinfo.gridlayer.selectAll('path').remove();
            if(plotinfo.zerolinelayer) plotinfo.zerolinelayer.selectAll('path').remove();

            fullLayout._infolayer.select('.g-' + xa._id + 'title').remove();
            fullLayout._infolayer.select('.g-' + ya._id + 'title').remove();
        });
    }

    var axList = (!arg || arg === 'redraw') ? axes.listIds(gd) : arg;

    return Lib.syncOrAsync(axList.map(function(axId) {
        return function() {
            if(!axId) return;

            var ax = axes.getFromId(gd, axId);
            var axDone = axes.drawOne(gd, ax, opts);

            ax._r = ax.range.slice();
            ax._rl = Lib.simpleMap(ax._r, ax.r2l);

            return axDone;
        };
    }));
};

/**
 * Draw one cartesian axis
 *
 * @param {DOM element} gd
 * @param {object} ax (full) axis object
 * @param {object} opts
 * - @param {boolean} skipTitle (set to true to skip axis title draw call)
 */
axes.drawOne = function(gd, ax, opts) {
    opts = opts || {};

    var i, sp, plotinfo;

    ax.setScale();

    var fullLayout = gd._fullLayout;
    var axId = ax._id;
    var axLetter = axId.charAt(0);
    var counterLetter = axes.counterLetter(axId);
    var mainSubplot = ax._mainSubplot;
    var mainLinePosition = ax._mainLinePosition;
    var mainMirrorPosition = ax._mainMirrorPosition;
    var mainPlotinfo = fullLayout._plots[mainSubplot];
    var mainAxLayer = mainPlotinfo[axLetter + 'axislayer'];
    var subplotsWithAx = ax._subplotsWith;

    var vals = ax._vals = axes.calcTicks(ax);

    // Add a couple of axis properties that should cause us to recreate
    // elements. Used in d3 data function.
    var axInfo = [ax.mirror, mainLinePosition, mainMirrorPosition].join('_');
    for(i = 0; i < vals.length; i++) {
        vals[i].axInfo = axInfo;
    }

    if(!ax.visible) return;

    // stash selections to avoid DOM queries e.g.
    // - stash tickLabels selection, so that drawTitle can use it to scoot title
    ax._selections = {};
    // stash tick angle (including the computed 'auto' values) per tick-label class
    ax._tickAngles = {};

    var transFn = axes.makeTransFn(ax);
    var tickVals;
    // We remove zero lines, grid lines, and inside ticks if they're within 1px of the end
    // The key case here is removing zero lines when the axis bound is zero
    var valsClipped;

    if(ax.tickson === 'boundaries') {
        var boundaryVals = getBoundaryVals(ax, vals);
        valsClipped = axes.clipEnds(ax, boundaryVals);
        tickVals = ax.ticks === 'inside' ? valsClipped : boundaryVals;
    } else {
        valsClipped = axes.clipEnds(ax, vals);
        tickVals = ax.ticks === 'inside' ? valsClipped : vals;
    }

    var gridVals = ax._gridVals = valsClipped;
    var dividerVals = getDividerVals(ax, vals);

    if(!fullLayout._hasOnlyLargeSploms) {
        // keep track of which subplots (by main conteraxis) we've already
        // drawn grids for, so we don't overdraw overlaying subplots
        var finishedGrids = {};

        for(i = 0; i < subplotsWithAx.length; i++) {
            sp = subplotsWithAx[i];
            plotinfo = fullLayout._plots[sp];

            var counterAxis = plotinfo[counterLetter + 'axis'];
            var mainCounterID = counterAxis._mainAxis._id;
            if(finishedGrids[mainCounterID]) continue;
            finishedGrids[mainCounterID] = 1;

            var gridPath = axLetter === 'x' ?
                'M0,' + counterAxis._offset + 'v' + counterAxis._length :
                'M' + counterAxis._offset + ',0h' + counterAxis._length;

            axes.drawGrid(gd, ax, {
                vals: gridVals,
                counterAxis: counterAxis,
                layer: plotinfo.gridlayer.select('.' + axId),
                path: gridPath,
                transFn: transFn
            });
            axes.drawZeroLine(gd, ax, {
                counterAxis: counterAxis,
                layer: plotinfo.zerolinelayer,
                path: gridPath,
                transFn: transFn
            });
        }
    }

    var tickSigns = axes.getTickSigns(ax);
    var tickSubplots = [];

    if(ax.ticks) {
        var mainTickPath = axes.makeTickPath(ax, mainLinePosition, tickSigns[2]);
        var mirrorTickPath;
        var fullTickPath;
        if(ax._anchorAxis && ax.mirror && ax.mirror !== true) {
            mirrorTickPath = axes.makeTickPath(ax, mainMirrorPosition, tickSigns[3]);
            fullTickPath = mainTickPath + mirrorTickPath;
        } else {
            mirrorTickPath = '';
            fullTickPath = mainTickPath;
        }

        var tickPath;
        if(ax.showdividers && ax.ticks === 'outside' && ax.tickson === 'boundaries') {
            var dividerLookup = {};
            for(i = 0; i < dividerVals.length; i++) {
                dividerLookup[dividerVals[i].x] = 1;
            }
            tickPath = function(d) {
                return dividerLookup[d.x] ? mirrorTickPath : fullTickPath;
            };
        } else {
            tickPath = fullTickPath;
        }

        axes.drawTicks(gd, ax, {
            vals: tickVals,
            layer: mainAxLayer,
            path: tickPath,
            transFn: transFn
        });

        tickSubplots = Object.keys(ax._linepositions || {});
    }

    for(i = 0; i < tickSubplots.length; i++) {
        sp = tickSubplots[i];
        plotinfo = fullLayout._plots[sp];
        // [bottom or left, top or right], free and main are handled above
        var linepositions = ax._linepositions[sp] || [];
        var spTickPath = axes.makeTickPath(ax, linepositions[0], tickSigns[0]) +
            axes.makeTickPath(ax, linepositions[1], tickSigns[1]);

        axes.drawTicks(gd, ax, {
            vals: tickVals,
            layer: plotinfo[axLetter + 'axislayer'],
            path: spTickPath,
            transFn: transFn
        });
    }

    var seq = [];

    // tick labels - for now just the main labels.
    // TODO: mirror labels, esp for subplots

    seq.push(function() {
        return axes.drawLabels(gd, ax, {
            vals: vals,
            layer: mainAxLayer,
            transFn: transFn,
            labelFns: axes.makeLabelFns(ax, mainLinePosition)
        });
    });

    if(ax.type === 'multicategory') {
        var labelLength = 0;
        var pad = {x: 2, y: 10}[axLetter];
        var sgn = tickSigns[2] * (ax.ticks === 'inside' ? -1 : 1);

        seq.push(function() {
            labelLength += getLabelLevelSpan(ax, axId + 'tick') + pad;
            labelLength += ax._tickAngles[axId + 'tick'] ? ax.tickfont.size * LINE_SPACING : 0;

            return axes.drawLabels(gd, ax, {
                vals: getSecondaryLabelVals(ax, vals),
                layer: mainAxLayer,
                cls: axId + 'tick2',
                repositionOnUpdate: true,
                secondary: true,
                transFn: transFn,
                labelFns: axes.makeLabelFns(ax, mainLinePosition + labelLength * sgn)
            });
        });

        seq.push(function() {
            labelLength += getLabelLevelSpan(ax, axId + 'tick2');
            ax._labelLength = labelLength;

            return drawDividers(gd, ax, {
                vals: dividerVals,
                layer: mainAxLayer,
                path: axes.makeTickPath(ax, mainLinePosition, sgn, labelLength),
                transFn: transFn
            });
        });
    }

    function extendRange(range, newRange) {
        range[0] = Math.min(range[0], newRange[0]);
        range[1] = Math.max(range[1], newRange[1]);
    }

    function calcBoundingBox() {
        if(ax.showticklabels) {
            var gdBB = gd.getBoundingClientRect();
            var bBox = mainAxLayer.node().getBoundingClientRect();

            /*
             * the way we're going to use this, the positioning that matters
             * is relative to the origin of gd. This is important particularly
             * if gd is scrollable, and may have been scrolled between the time
             * we calculate this and the time we use it
             */

            ax._boundingBox = {
                width: bBox.width,
                height: bBox.height,
                left: bBox.left - gdBB.left,
                right: bBox.right - gdBB.left,
                top: bBox.top - gdBB.top,
                bottom: bBox.bottom - gdBB.top
            };
        } else {
            var gs = fullLayout._size;
            var pos;

            // set dummy bbox for ticklabel-less axes

            if(axLetter === 'x') {
                pos = ax.anchor === 'free' ?
                    gs.t + gs.h * (1 - ax.position) :
                    gs.t + gs.h * (1 - ax._anchorAxis.domain[{bottom: 0, top: 1}[ax.side]]);

                ax._boundingBox = {
                    top: pos,
                    bottom: pos,
                    left: ax._offset,
                    right: ax._offset + ax._length,
                    width: ax._length,
                    height: 0
                };
            } else {
                pos = ax.anchor === 'free' ?
                    gs.l + gs.w * ax.position :
                    gs.l + gs.w * ax._anchorAxis.domain[{left: 0, right: 1}[ax.side]];

                ax._boundingBox = {
                    left: pos,
                    right: pos,
                    bottom: ax._offset + ax._length,
                    top: ax._offset,
                    height: ax._length,
                    width: 0
                };
            }
        }

        /*
         * for spikelines: what's the full domain of positions in the
         * opposite direction that are associated with this axis?
         * This means any axes that we make a subplot with, plus the
         * position of the axis itself if it's free.
         */
        if(subplotsWithAx) {
            var fullRange = ax._counterSpan = [Infinity, -Infinity];

            for(var i = 0; i < subplotsWithAx.length; i++) {
                var plotinfo = fullLayout._plots[subplotsWithAx[i]];
                var counterAxis = plotinfo[(axLetter === 'x') ? 'yaxis' : 'xaxis'];

                extendRange(fullRange, [
                    counterAxis._offset,
                    counterAxis._offset + counterAxis._length
                ]);
            }

            if(ax.anchor === 'free') {
                extendRange(fullRange, (axLetter === 'x') ?
                    [ax._boundingBox.bottom, ax._boundingBox.top] :
                    [ax._boundingBox.right, ax._boundingBox.left]);
            }
        }
    }

    var hasRangeSlider = Registry.getComponentMethod('rangeslider', 'isVisible')(ax);

    function doAutoMargins() {
        var s = ax.side.charAt(0);
        var push;
        var rangeSliderPush;

        if(hasRangeSlider) {
            rangeSliderPush = Registry.getComponentMethod('rangeslider', 'autoMarginOpts')(gd, ax);
        }
        Plots.autoMargin(gd, rangeSliderAutoMarginID(ax), rangeSliderPush);

        if(ax.automargin && (!hasRangeSlider || s !== 'b')) {
            push = {x: 0, y: 0, r: 0, l: 0, t: 0, b: 0};

            var bbox = ax._boundingBox;
            var titleOffset = getTitleOffset(gd, ax);
            var anchorAxDomainIndex;
            var offset;

            switch(axLetter + s) {
                case 'xb':
                    anchorAxDomainIndex = 0;
                    offset = bbox.top - titleOffset;
                    push[s] = bbox.height;
                    break;
                case 'xt':
                    anchorAxDomainIndex = 1;
                    offset = titleOffset - bbox.bottom;
                    push[s] = bbox.height;
                    break;
                case 'yl':
                    anchorAxDomainIndex = 0;
                    offset = titleOffset - bbox.right;
                    push[s] = bbox.width;
                    break;
                case 'yr':
                    anchorAxDomainIndex = 1;
                    offset = bbox.left - titleOffset;
                    push[s] = bbox.width;
                    break;
            }

            push[counterLetter] = ax.anchor === 'free' ?
                ax.position :
                ax._anchorAxis.domain[anchorAxDomainIndex];

            if(push[s] > 0) {
                push[s] += offset;
            }

            if(ax.title.text !== fullLayout._dfltTitle[axLetter]) {
                push[s] += ax.title.font.size;
            }

            if(axLetter === 'x' && bbox.width > 0) {
                var rExtra = bbox.right - (ax._offset + ax._length);
                if(rExtra > 0) {
                    push.x = 1;
                    push.r = rExtra;
                }
                var lExtra = ax._offset - bbox.left;
                if(lExtra > 0) {
                    push.x = 0;
                    push.l = lExtra;
                }
            } else if(axLetter === 'y' && bbox.height > 0) {
                var bExtra = bbox.bottom - (ax._offset + ax._length);
                if(bExtra > 0) {
                    push.y = 0;
                    push.b = bExtra;
                }
                var tExtra = ax._offset - bbox.top;
                if(tExtra > 0) {
                    push.y = 1;
                    push.t = tExtra;
                }
            }
        }

        Plots.autoMargin(gd, axAutoMarginID(ax), push);
    }

    seq.push(calcBoundingBox, doAutoMargins);

    if(!opts.skipTitle &&
        !(hasRangeSlider && ax._boundingBox && ax.side === 'bottom')
    ) {
        seq.push(function() { return drawTitle(gd, ax); });
    }

    return Lib.syncOrAsync(seq);
};

function getBoundaryVals(ax, vals) {
    var out = [];
    var i;

    // boundaryVals are never used for labels;
    // no need to worry about the other tickTextObj keys
    var _push = function(d, bndIndex) {
        var xb = d.xbnd[bndIndex];
        if(xb !== null) {
            out.push(Lib.extendFlat({}, d, {x: xb}));
        }
    };

    if(vals.length) {
        for(i = 0; i < vals.length; i++) {
            _push(vals[i], 0);
        }
        _push(vals[i - 1], 1);
    }

    return out;
}

function getSecondaryLabelVals(ax, vals) {
    var out = [];
    var lookup = {};

    for(var i = 0; i < vals.length; i++) {
        var d = vals[i];
        if(lookup[d.text2]) {
            lookup[d.text2].push(d.x);
        } else {
            lookup[d.text2] = [d.x];
        }
    }

    for(var k in lookup) {
        out.push(tickTextObj(ax, Lib.interp(lookup[k], 0.5), k));
    }

    return out;
}

function getDividerVals(ax, vals) {
    var out = [];
    var i, current;

    // never used for labels;
    // no need to worry about the other tickTextObj keys
    var _push = function(d, bndIndex) {
        var xb = d.xbnd[bndIndex];
        if(xb !== null) {
            out.push(Lib.extendFlat({}, d, {x: xb}));
        }
    };

    if(ax.showdividers && vals.length) {
        for(i = 0; i < vals.length; i++) {
            var d = vals[i];
            if(d.text2 !== current) {
                _push(d, 0);
            }
            current = d.text2;
        }
        _push(vals[i - 1], 1);
    }

    return out;
}

function getLabelLevelSpan(ax, cls) {
    var axLetter = ax._id.charAt(0);
    var angle = ax._tickAngles[cls] || 0;
    var rad = Lib.deg2rad(angle);
    var sinA = Math.sin(rad);
    var cosA = Math.cos(rad);
    var maxX = 0;
    var maxY = 0;

    // N.B. Drawing.bBox does not take into account rotate transforms

    ax._selections[cls].each(function() {
        var thisLabel = selectTickLabel(this);
        var bb = Drawing.bBox(thisLabel.node());
        var w = bb.width;
        var h = bb.height;
        maxX = Math.max(maxX, cosA * w, sinA * h);
        maxY = Math.max(maxY, sinA * w, cosA * h);
    });

    return {x: maxY, y: maxX}[axLetter];
}

/**
 * Which direction do the 'ax.side' values, and free ticks go?
 *
 * @param {object} ax (full) axis object
 *  - {string} _id (starting with 'x' or 'y')
 *  - {string} side
 *  - {string} ticks
 * @return {array} all entries are either -1 or 1
 *  - [0]: sign for top/right ticks (i.e. negative SVG direction)
 *  - [1]: sign for bottom/left ticks (i.e. positive SVG direction)
 *  - [2]: sign for ticks corresponding to 'ax.side'
 *  - [3]: sign for ticks mirroring 'ax.side'
 */
axes.getTickSigns = function(ax) {
    var axLetter = ax._id.charAt(0);
    var sideOpposite = {x: 'top', y: 'right'}[axLetter];
    var main = ax.side === sideOpposite ? 1 : -1;
    var out = [-1, 1, main, -main];
    // then we flip if outside XOR y axis
    if((ax.ticks !== 'inside') === (axLetter === 'x')) {
        out = out.map(function(v) { return -v; });
    }
    return out;
};

/**
 * Make axis translate transform function
 *
 * @param {object} ax (full) axis object
 *  - {string} _id
 *  - {number} _offset
 *  - {fn} l2p
 * @return {fn} function of calcTicks items
 */
axes.makeTransFn = function(ax) {
    var axLetter = ax._id.charAt(0);
    var offset = ax._offset;
    return axLetter === 'x' ?
        function(d) { return 'translate(' + (offset + ax.l2p(d.x)) + ',0)'; } :
        function(d) { return 'translate(0,' + (offset + ax.l2p(d.x)) + ')'; };
};

/**
 * Make axis tick path string
 *
 * @param {object} ax (full) axis object
 *  - {string} _id
 *  - {number} ticklen
 *  - {number} linewidth
 * @param {number} shift along direction of ticklen
 * @param {1 or -1} sng tick sign
 * @param {number (optional)} len tick length
 * @return {string}
 */
axes.makeTickPath = function(ax, shift, sgn, len) {
    len = len !== undefined ? len : ax.ticklen;

    var axLetter = ax._id.charAt(0);
    var pad = (ax.linewidth || 1) / 2;

    return axLetter === 'x' ?
        'M0,' + (shift + pad * sgn) + 'v' + (len * sgn) :
        'M' + (shift + pad * sgn) + ',0h' + (len * sgn);
};

/**
 * Make axis tick label x, y and anchor functions
 *
 * @param {object} ax (full) axis object
 *  - {string} _id
 *  - {string} ticks
 *  - {number} ticklen
 *  - {string} side
 *  - {number} linewidth
 *  - {number} tickfont.size
 *  - {boolean} showline
 * @param {number} shift
 * @param {number} angle [in degrees] ...
 * @return {object}
 *  - {fn} xFn
 *  - {fn} yFn
 *  - {fn} anchorFn
 *  - {fn} heightFn
 *  - {number} labelStandoff (gap parallel to ticks)
 *  - {number} labelShift (gap perpendicular to ticks)
 */
axes.makeLabelFns = function(ax, shift, angle) {
    var axLetter = ax._id.charAt(0);
    var ticksOnOutsideLabels = ax.tickson !== 'boundaries' && ax.ticks === 'outside';

    var labelStandoff = 0;
    var labelShift = 0;

    if(ticksOnOutsideLabels) {
        labelStandoff += ax.ticklen;
    }
    if(angle && ax.ticks === 'outside') {
        var rad = Lib.deg2rad(angle);
        labelStandoff = ax.ticklen * Math.cos(rad) + 1;
        labelShift = ax.ticklen * Math.sin(rad);
    }
    if(ax.showticklabels && (ticksOnOutsideLabels || ax.showline)) {
        labelStandoff += 0.2 * ax.tickfont.size;
    }
    labelStandoff += (ax.linewidth || 1) / 2;

    var out = {
        labelStandoff: labelStandoff,
        labelShift: labelShift
    };

    var x0, y0, ff, flipIt;

    if(axLetter === 'x') {
        flipIt = ax.side === 'bottom' ? 1 : -1;
        x0 = labelShift * flipIt;
        y0 = shift + labelStandoff * flipIt;
        ff = ax.side === 'bottom' ? 1 : -0.2;

        out.xFn = function(d) { return d.dx + x0; };
        out.yFn = function(d) { return d.dy + y0 + d.fontSize * ff; };
        out.anchorFn = function(d, a) {
            if(!isNumeric(a) || a === 0 || a === 180) {
                return 'middle';
            }
            return (a * flipIt < 0) ? 'end' : 'start';
        };
        out.heightFn = function(d, a, h) {
            return (a < -60 || a > 60) ? -0.5 * h :
                ax.side === 'top' ? -h :
                0;
        };
    } else if(axLetter === 'y') {
        flipIt = ax.side === 'right' ? 1 : -1;
        x0 = labelStandoff;
        y0 = -labelShift * flipIt;
        ff = Math.abs(ax.tickangle) === 90 ? 0.5 : 0;

        out.xFn = function(d) { return d.dx + shift + (x0 + d.fontSize * ff) * flipIt; };
        out.yFn = function(d) { return d.dy + y0 + d.fontSize * MID_SHIFT; };
        out.anchorFn = function(d, a) {
            if(isNumeric(a) && Math.abs(a) === 90) {
                return 'middle';
            }
            return ax.side === 'right' ? 'start' : 'end';
        };
        out.heightFn = function(d, a, h) {
            a *= ax.side === 'left' ? 1 : -1;
            return a < -30 ? -h :
                a < 30 ? -0.5 * h :
                0;
        };
    }

    return out;
};

function tickDataFn(d) {
    return [d.text, d.x, d.axInfo, d.font, d.fontSize, d.fontColor].join('_');
}

/**
 * Draw axis ticks
 *
 * @param {DOM element} gd
 * @param {object} ax (full) axis object
 *  - {string} _id
 *  - {string} ticks
 *  - {number} linewidth
 *  - {string} tickcolor
 * @param {object} opts
 * - {array of object} vals (calcTicks output-like)
 * - {d3 selection} layer
 * - {string or fn} path
 * - {fn} transFn
 * - {boolean} crisp (set to false to unset crisp-edge SVG rendering)
 */
axes.drawTicks = function(gd, ax, opts) {
    opts = opts || {};

    var cls = ax._id + 'tick';

    var ticks = opts.layer.selectAll('path.' + cls)
        .data(ax.ticks ? opts.vals : [], tickDataFn);

    ticks.exit().remove();

    ticks.enter().append('path')
        .classed(cls, 1)
        .classed('ticks', 1)
        .classed('crisp', opts.crisp !== false)
        .call(Color.stroke, ax.tickcolor)
        .style('stroke-width', Drawing.crispRound(gd, ax.tickwidth, 1) + 'px')
        .attr('d', opts.path);

    ticks.attr('transform', opts.transFn);
};

/**
 * Draw axis grid
 *
 * @param {DOM element} gd
 * @param {object} ax (full) axis object
 *  - {string} _id
 *  - {boolean} showgrid
 *  - {string} gridcolor
 *  - {string} gridwidth
 *  - {boolean} zeroline
 *  - {string} type
 *  - {string} dtick
 * @param {object} opts
 * - {array of object} vals (calcTicks output-like)
 * - {d3 selection} layer
 * - {object} counterAxis (full axis object corresponding to counter axis)
 *     optional - only required if this axis supports zero lines
 * - {string or fn} path
 * - {fn} transFn
 * - {boolean} crisp (set to false to unset crisp-edge SVG rendering)
 */
axes.drawGrid = function(gd, ax, opts) {
    opts = opts || {};

    var cls = ax._id + 'grid';
    var vals = opts.vals;
    var counterAx = opts.counterAxis;
    if(ax.showgrid === false) {
        vals = [];
    }
    else if(counterAx && axes.shouldShowZeroLine(gd, ax, counterAx)) {
        var isArrayMode = ax.tickmode === 'array';
        for(var i = 0; i < vals.length; i++) {
            var xi = vals[i].x;
            if(isArrayMode ? !xi : (Math.abs(xi) < ax.dtick / 100)) {
                vals = vals.slice(0, i).concat(vals.slice(i + 1));
                // In array mode you can in principle have multiple
                // ticks at 0, so test them all. Otherwise once we found
                // one we can stop.
                if(isArrayMode) i--;
                else break;
            }
        }
    }

    var grid = opts.layer.selectAll('path.' + cls)
        .data(vals, tickDataFn);

    grid.exit().remove();

    grid.enter().append('path')
        .classed(cls, 1)
        .classed('crisp', opts.crisp !== false);

    ax._gw = Drawing.crispRound(gd, ax.gridwidth, 1);

    grid.attr('transform', opts.transFn)
        .attr('d', opts.path)
        .call(Color.stroke, ax.gridcolor || '#ddd')
        .style('stroke-width', ax._gw + 'px');

    if(typeof opts.path === 'function') grid.attr('d', opts.path);
};

/**
 * Draw axis zero-line
 *
 * @param {DOM element} gd
 * @param {object} ax (full) axis object
 *  - {string} _id
 *  - {boolean} zeroline
 *  - {number} zerolinewidth
 *  - {string} zerolinecolor
 *  - {number (optional)} _gridWidthCrispRound
 * @param {object} opts
 * - {d3 selection} layer
 * - {object} counterAxis (full axis object corresponding to counter axis)
 * - {string or fn} path
 * - {fn} transFn
 * - {boolean} crisp (set to false to unset crisp-edge SVG rendering)
 */
axes.drawZeroLine = function(gd, ax, opts) {
    opts = opts || opts;

    var cls = ax._id + 'zl';
    var show = axes.shouldShowZeroLine(gd, ax, opts.counterAxis);

    var zl = opts.layer.selectAll('path.' + cls)
        .data(show ? [{x: 0, id: ax._id}] : []);

    zl.exit().remove();

    zl.enter().append('path')
        .classed(cls, 1)
        .classed('zl', 1)
        .classed('crisp', opts.crisp !== false)
        .each(function() {
            // use the fact that only one element can enter to trigger a sort.
            // If several zerolines enter at the same time we will sort once per,
            // but generally this should be a minimal overhead.
            opts.layer.selectAll('path').sort(function(da, db) {
                return axisIds.idSort(da.id, db.id);
            });
        });

    zl.attr('transform', opts.transFn)
        .attr('d', opts.path)
        .call(Color.stroke, ax.zerolinecolor || Color.defaultLine)
        .style('stroke-width', Drawing.crispRound(gd, ax.zerolinewidth, ax._gw || 1) + 'px');
};

/**
 * Draw axis tick labels
 *
 * @param {DOM element} gd
 * @param {object} ax (full) axis object
 *  - {string} _id
 *  - {boolean} showticklabels
 *  - {number} tickangle
 *  - {object (optional)} _selections
 *  - {object} (optional)} _tickAngles
 * @param {object} opts
 * - {array of object} vals (calcTicks output-like)
 * - {d3 selection} layer
 * - {string (optional)} cls (node className)
 * - {boolean} repositionOnUpdate (set to true to reposition update selection)
 * - {boolean} secondary
 * - {fn} transFn
 * - {object} labelFns
 *  + {fn} xFn
 *  + {fn} yFn
 *  + {fn} anchorFn
 *  + {fn} heightFn
 */
axes.drawLabels = function(gd, ax, opts) {
    opts = opts || {};

    var axId = ax._id;
    var axLetter = axId.charAt(0);
    var cls = opts.cls || axId + 'tick';
    var vals = opts.vals;
    var labelFns = opts.labelFns;
    var tickAngle = opts.secondary ? 0 : ax.tickangle;
    var lastAngle = (ax._tickAngles || {})[cls];

    var tickLabels = opts.layer.selectAll('g.' + cls)
        .data(ax.showticklabels ? vals : [], tickDataFn);

    var labelsReady = [];

    tickLabels.enter().append('g')
        .classed(cls, 1)
        .append('text')
            // only so tex has predictable alignment that we can
            // alter later
            .attr('text-anchor', 'middle')
            .each(function(d) {
                var thisLabel = d3.select(this);
                var newPromise = gd._promises.length;

                thisLabel
                    .call(svgTextUtils.positionText, labelFns.xFn(d), labelFns.yFn(d))
                    .call(Drawing.font, d.font, d.fontSize, d.fontColor)
                    .text(d.text)
                    .call(svgTextUtils.convertToTspans, gd);

                if(gd._promises[newPromise]) {
                    // if we have an async label, we'll deal with that
                    // all here so take it out of gd._promises and
                    // instead position the label and promise this in
                    // labelsReady
                    labelsReady.push(gd._promises.pop().then(function() {
                        positionLabels(thisLabel, tickAngle);
                    }));
                } else {
                    // sync label: just position it now.
                    positionLabels(thisLabel, tickAngle);
                }
            });

    tickLabels.exit().remove();

    if(opts.repositionOnUpdate) {
        tickLabels.each(function(d) {
            d3.select(this).select('text')
                .call(svgTextUtils.positionText, labelFns.xFn(d), labelFns.yFn(d));
        });
    }

    function positionLabels(s, angle) {
        s.each(function(d) {
            var thisLabel = d3.select(this);
            var mathjaxGroup = thisLabel.select('.text-math-group');
            var anchor = labelFns.anchorFn(d, angle);

            var transform = opts.transFn.call(thisLabel.node(), d) +
                ((isNumeric(angle) && +angle !== 0) ?
                (' rotate(' + angle + ',' + labelFns.xFn(d) + ',' +
                    (labelFns.yFn(d) - d.fontSize / 2) + ')') :
                '');

            // how much to shift a multi-line label to center it vertically.
            var nLines = svgTextUtils.lineCount(thisLabel);
            var lineHeight = LINE_SPACING * d.fontSize;
            var anchorHeight = labelFns.heightFn(d, isNumeric(angle) ? +angle : 0, (nLines - 1) * lineHeight);

            if(anchorHeight) {
                transform += ' translate(0, ' + anchorHeight + ')';
            }

            if(mathjaxGroup.empty()) {
                thisLabel.select('text').attr({
                    transform: transform,
                    'text-anchor': anchor
                });
            } else {
                var mjWidth = Drawing.bBox(mathjaxGroup.node()).width;
                var mjShift = mjWidth * {end: -0.5, start: 0.5}[anchor];
                mathjaxGroup.attr('transform', transform + (mjShift ? 'translate(' + mjShift + ',0)' : ''));
            }
        });
    }

    // make sure all labels are correctly positioned at their base angle
    // the positionLabels call above is only for newly drawn labels.
    // do this without waiting, using the last calculated angle to
    // minimize flicker, then do it again when we know all labels are
    // there, putting back the prescribed angle to check for overlaps.
    positionLabels(tickLabels, lastAngle || tickAngle);

    function allLabelsReady() {
        return labelsReady.length && Promise.all(labelsReady);
    }

    function fixLabelOverlaps() {
        positionLabels(tickLabels, tickAngle);

        var autoangle = null;

        // check for auto-angling if x labels overlap
        // don't auto-angle at all for log axes with
        // base and digit format
        if(vals.length && axLetter === 'x' && !isNumeric(tickAngle) &&
            (ax.type !== 'log' || String(ax.dtick).charAt(0) !== 'D')
        ) {
            autoangle = 0;

            var maxFontSize = 0;
            var lbbArray = [];
            var i;

            tickLabels.each(function(d) {
                maxFontSize = Math.max(maxFontSize, d.fontSize);

                var x = ax.l2p(d.x);
                var thisLabel = selectTickLabel(this);
                var bb = Drawing.bBox(thisLabel.node());

                lbbArray.push({
                    // ignore about y, just deal with x overlaps
                    top: 0,
                    bottom: 10,
                    height: 10,
                    left: x - bb.width / 2,
                    // impose a 2px gap
                    right: x + bb.width / 2 + 2,
                    width: bb.width + 2
                });
            });

            if((ax.tickson === 'boundaries' || ax.showdividers) && !opts.secondary) {
                var gap = 2;
                if(ax.ticks) gap += ax.tickwidth / 2;

                // TODO should secondary labels also fall into this fix-overlap regime?

                for(i = 0; i < lbbArray.length; i++) {
                    var xbnd = vals[i].xbnd;
                    var lbb = lbbArray[i];
                    if(
                        (xbnd[0] !== null && (lbb.left - ax.l2p(xbnd[0])) < gap) ||
                        (xbnd[1] !== null && (ax.l2p(xbnd[1]) - lbb.right) < gap)
                    ) {
                        autoangle = 90;
                        break;
                    }
                }
            } else {
                var vLen = vals.length;
                var tickSpacing = Math.abs((vals[vLen - 1].x - vals[0].x) * ax._m) / (vLen - 1);
                var rotate90 = (tickSpacing < maxFontSize * 2.5) || ax.type === 'multicategory';

                // any overlap at all - set 30 degrees or 90 degrees
                for(i = 0; i < lbbArray.length - 1; i++) {
                    if(Lib.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) {
                        autoangle = rotate90 ? 90 : 30;
                        break;
                    }
                }
            }

            if(autoangle) {
                positionLabels(tickLabels, autoangle);
            }
        }

        if(ax._tickAngles) {
            ax._tickAngles[cls] = autoangle === null ?
                (isNumeric(tickAngle) ? tickAngle : 0) :
                autoangle;
        }
    }

    if(ax._selections) {
        ax._selections[cls] = tickLabels;
    }

    var done = Lib.syncOrAsync([allLabelsReady, fixLabelOverlaps]);
    if(done && done.then) gd._promises.push(done);
    return done;
};

/**
 * Draw axis dividers
 *
 * @param {DOM element} gd
 * @param {object} ax (full) axis object
 *  - {string} _id
 *  - {string} showdividers
 *  - {number} dividerwidth
 *  - {string} dividercolor
 * @param {object} opts
 * - {array of object} vals (calcTicks output-like)
 * - {d3 selection} layer
 * - {fn} path
 * - {fn} transFn
 */
function drawDividers(gd, ax, opts) {
    var cls = ax._id + 'divider';
    var vals = opts.vals;

    var dividers = opts.layer.selectAll('path.' + cls)
        .data(vals, tickDataFn);

    dividers.exit().remove();

    dividers.enter().insert('path', ':first-child')
        .classed(cls, 1)
        .classed('crisp', 1)
        .call(Color.stroke, ax.dividercolor)
        .style('stroke-width', Drawing.crispRound(gd, ax.dividerwidth, 1) + 'px');

    dividers
        .attr('transform', opts.transFn)
        .attr('d', opts.path);
}

function getTitleOffset(gd, ax) {
    var gs = gd._fullLayout._size;
    var axLetter = ax._id.charAt(0);
    var side = ax.side;
    var anchorAxis;

    if(ax.anchor !== 'free') {
        anchorAxis = axisIds.getFromId(gd, ax.anchor);
    } else if(axLetter === 'x') {
        anchorAxis = {
            _offset: gs.t + (1 - (ax.position || 0)) * gs.h,
            _length: 0
        };
    } else if(axLetter === 'y') {
        anchorAxis = {
            _offset: gs.l + (ax.position || 0) * gs.w,
            _length: 0
        };
    }

    if(side === 'top' || side === 'left') {
        return anchorAxis._offset;
    } else if(side === 'bottom' || side === 'right') {
        return anchorAxis._offset + anchorAxis._length;
    }
}

function drawTitle(gd, ax) {
    var fullLayout = gd._fullLayout;
    var axId = ax._id;
    var axLetter = axId.charAt(0);
    var fontSize = ax.title.font.size;

    var titleStandoff;
    if(ax.type === 'multicategory') {
        titleStandoff = ax._labelLength;
    } else {
        var offsetBase = 1.5;
        titleStandoff = 10 + fontSize * offsetBase + (ax.linewidth ? ax.linewidth - 1 : 0);
    }

    var titleOffset = getTitleOffset(gd, ax);

    var transform, x, y;

    if(axLetter === 'x') {
        x = ax._offset + ax._length / 2;

        if(ax.side === 'top') {
            y = -titleStandoff - fontSize * (ax.showticklabels ? 1 : 0);
        } else {
            y = titleStandoff + fontSize * (ax.showticklabels ? 1.5 : 0.5);
        }
        y += titleOffset;
    } else {
        y = ax._offset + ax._length / 2;

        if(ax.side === 'right') {
            x = titleStandoff + fontSize * (ax.showticklabels ? 1 : 0.5);
        } else {
            x = -titleStandoff - fontSize * (ax.showticklabels ? 0.5 : 0);
        }
        x += titleOffset;

        transform = {rotate: '-90', offset: 0};
    }

    var avoid;

    if(ax.type !== 'multicategory') {
        var tickLabels = ax._selections[ax._id + 'tick'];

        avoid = {
            selection: tickLabels,
            side: ax.side
        };

        if(tickLabels && tickLabels.node() && tickLabels.node().parentNode) {
            var translation = Drawing.getTranslate(tickLabels.node().parentNode);
            avoid.offsetLeft = translation.x;
            avoid.offsetTop = translation.y;
        }
    }

    return Titles.draw(gd, axId + 'title', {
        propContainer: ax,
        propName: ax._name + '.title.text',
        placeholder: fullLayout._dfltTitle[axLetter],
        avoid: avoid,
        transform: transform,
        attributes: {x: x, y: y, 'text-anchor': 'middle'}
    });
}

axes.shouldShowZeroLine = function(gd, ax, counterAxis) {
    var rng = Lib.simpleMap(ax.range, ax.r2l);
    return (
        (rng[0] * rng[1] <= 0) &&
        ax.zeroline &&
        (ax.type === 'linear' || ax.type === '-') &&
        ax._gridVals.length &&
        (
            clipEnds(ax, 0) ||
            !anyCounterAxLineAtZero(gd, ax, counterAxis, rng) ||
            hasBarsOrFill(gd, ax)
        )
    );
};

axes.clipEnds = function(ax, vals) {
    return vals.filter(function(d) { return clipEnds(ax, d.x); });
};

function clipEnds(ax, l) {
    var p = ax.l2p(l);
    return (p > 1 && p < ax._length - 1);
}

function anyCounterAxLineAtZero(gd, ax, counterAxis, rng) {
    var mainCounterAxis = counterAxis._mainAxis;
    if(!mainCounterAxis) return;

    var fullLayout = gd._fullLayout;
    var axLetter = ax._id.charAt(0);
    var counterLetter = axes.counterLetter(ax._id);

    var zeroPosition = ax._offset + (
        ((Math.abs(rng[0]) < Math.abs(rng[1])) === (axLetter === 'x')) ?
        0 : ax._length
    );

    function lineNearZero(ax2) {
        if(!ax2.showline || !ax2.linewidth) return false;
        var tolerance = Math.max((ax2.linewidth + ax.zerolinewidth) / 2, 1);

        function closeEnough(pos2) {
            return typeof pos2 === 'number' && Math.abs(pos2 - zeroPosition) < tolerance;
        }

        if(closeEnough(ax2._mainLinePosition) || closeEnough(ax2._mainMirrorPosition)) {
            return true;
        }
        var linePositions = ax2._linepositions || {};
        for(var k in linePositions) {
            if(closeEnough(linePositions[k][0]) || closeEnough(linePositions[k][1])) {
                return true;
            }
        }
    }

    var plotinfo = fullLayout._plots[counterAxis._mainSubplot];
    if(!(plotinfo.mainplotinfo || plotinfo).overlays.length) {
        return lineNearZero(counterAxis, zeroPosition);
    }

    var counterLetterAxes = axes.list(gd, counterLetter);
    for(var i = 0; i < counterLetterAxes.length; i++) {
        var counterAxis2 = counterLetterAxes[i];
        if(
            counterAxis2._mainAxis === mainCounterAxis &&
            lineNearZero(counterAxis2, zeroPosition)
        ) {
            return true;
        }
    }
}

function hasBarsOrFill(gd, ax) {
    var fullData = gd._fullData;
    var subplot = ax._mainSubplot;
    var axLetter = ax._id.charAt(0);

    for(var i = 0; i < fullData.length; i++) {
        var trace = fullData[i];

        if(trace.visible === true &&
            (trace.xaxis + trace.yaxis) === subplot &&
            (
                Registry.traceIs(trace, 'bar') && trace.orientation === {x: 'h', y: 'v'}[axLetter] ||
                trace.fill && trace.fill.charAt(trace.fill.length - 1) === axLetter
            )
        ) {
            return true;
        }
    }
    return false;
}

function selectTickLabel(gTick) {
    var s = d3.select(gTick);
    var mj = s.select('.text-math-group');
    return mj.empty() ? s.select('text') : mj;
}

/**
 * Find all margin pushers for 2D axes and reserve them for later use
 * Both label and rangeslider automargin calculations happen later so
 * we need to explicitly allow their ids in order to not delete them.
 *
 * TODO: can we pull the actual automargin calls forward to avoid this hack?
 * We're probably also doing multiple redraws in this case, would be faster
 * if we can just do the whole calculation ahead of time and draw once.
 */
axes.allowAutoMargin = function(gd) {
    var axList = axes.list(gd, '', true);
    for(var i = 0; i < axList.length; i++) {
        var ax = axList[i];
        if(ax.automargin) {
            Plots.allowAutoMargin(gd, axAutoMarginID(ax));
        }
        if(Registry.getComponentMethod('rangeslider', 'isVisible')(ax)) {
            Plots.allowAutoMargin(gd, rangeSliderAutoMarginID(ax));
        }
    }
};

function axAutoMarginID(ax) { return ax._id + '.automargin'; }
function rangeSliderAutoMarginID(ax) { return ax._id + '.rangeslider'; }

// swap all the presentation attributes of the axes showing these traces
axes.swap = function(gd, traces) {
    var axGroups = makeAxisGroups(gd, traces);

    for(var i = 0; i < axGroups.length; i++) {
        swapAxisGroup(gd, axGroups[i].x, axGroups[i].y);
    }
};

function makeAxisGroups(gd, traces) {
    var groups = [];
    var i, j;

    for(i = 0; i < traces.length; i++) {
        var groupsi = [];
        var xi = gd._fullData[traces[i]].xaxis;
        var yi = gd._fullData[traces[i]].yaxis;
        if(!xi || !yi) continue; // not a 2D cartesian trace?

        for(j = 0; j < groups.length; j++) {
            if(groups[j].x.indexOf(xi) !== -1 || groups[j].y.indexOf(yi) !== -1) {
                groupsi.push(j);
            }
        }

        if(!groupsi.length) {
            groups.push({x: [xi], y: [yi]});
            continue;
        }

        var group0 = groups[groupsi[0]];
        var groupj;

        if(groupsi.length > 1) {
            for(j = 1; j < groupsi.length; j++) {
                groupj = groups[groupsi[j]];
                mergeAxisGroups(group0.x, groupj.x);
                mergeAxisGroups(group0.y, groupj.y);
            }
        }
        mergeAxisGroups(group0.x, [xi]);
        mergeAxisGroups(group0.y, [yi]);
    }

    return groups;
}

function mergeAxisGroups(intoSet, fromSet) {
    for(var i = 0; i < fromSet.length; i++) {
        if(intoSet.indexOf(fromSet[i]) === -1) intoSet.push(fromSet[i]);
    }
}

function swapAxisGroup(gd, xIds, yIds) {
    var xFullAxes = [];
    var yFullAxes = [];
    var layout = gd.layout;
    var i, j;

    for(i = 0; i < xIds.length; i++) xFullAxes.push(axes.getFromId(gd, xIds[i]));
    for(i = 0; i < yIds.length; i++) yFullAxes.push(axes.getFromId(gd, yIds[i]));

    var allAxKeys = Object.keys(axAttrs);

    var noSwapAttrs = [
        'anchor', 'domain', 'overlaying', 'position', 'side', 'tickangle', 'editType'
    ];
    var numericTypes = ['linear', 'log'];

    for(i = 0; i < allAxKeys.length; i++) {
        var keyi = allAxKeys[i];
        var xVal = xFullAxes[0][keyi];
        var yVal = yFullAxes[0][keyi];
        var allEqual = true;
        var coerceLinearX = false;
        var coerceLinearY = false;
        if(keyi.charAt(0) === '_' || typeof xVal === 'function' ||
                noSwapAttrs.indexOf(keyi) !== -1) {
            continue;
        }
        for(j = 1; j < xFullAxes.length && allEqual; j++) {
            var xVali = xFullAxes[j][keyi];
            if(keyi === 'type' && numericTypes.indexOf(xVal) !== -1 &&
                    numericTypes.indexOf(xVali) !== -1 && xVal !== xVali) {
                // type is special - if we find a mixture of linear and log,
                // coerce them all to linear on flipping
                coerceLinearX = true;
            }
            else if(xVali !== xVal) allEqual = false;
        }
        for(j = 1; j < yFullAxes.length && allEqual; j++) {
            var yVali = yFullAxes[j][keyi];
            if(keyi === 'type' && numericTypes.indexOf(yVal) !== -1 &&
                    numericTypes.indexOf(yVali) !== -1 && yVal !== yVali) {
                // type is special - if we find a mixture of linear and log,
                // coerce them all to linear on flipping
                coerceLinearY = true;
            }
            else if(yFullAxes[j][keyi] !== yVal) allEqual = false;
        }
        if(allEqual) {
            if(coerceLinearX) layout[xFullAxes[0]._name].type = 'linear';
            if(coerceLinearY) layout[yFullAxes[0]._name].type = 'linear';
            swapAxisAttrs(layout, keyi, xFullAxes, yFullAxes, gd._fullLayout._dfltTitle);
        }
    }

    // now swap x&y for any annotations anchored to these x & y
    for(i = 0; i < gd._fullLayout.annotations.length; i++) {
        var ann = gd._fullLayout.annotations[i];
        if(xIds.indexOf(ann.xref) !== -1 &&
                yIds.indexOf(ann.yref) !== -1) {
            Lib.swapAttrs(layout.annotations[i], ['?']);
        }
    }
}

function swapAxisAttrs(layout, key, xFullAxes, yFullAxes, dfltTitle) {
    // in case the value is the default for either axis,
    // look at the first axis in each list and see if
    // this key's value is undefined
    var np = Lib.nestedProperty;
    var xVal = np(layout[xFullAxes[0]._name], key).get();
    var yVal = np(layout[yFullAxes[0]._name], key).get();
    var i;

    if(key === 'title') {
        // special handling of placeholder titles
        if(xVal && xVal.text === dfltTitle.x) {
            xVal.text = dfltTitle.y;
        }
        if(yVal && yVal.text === dfltTitle.y) {
            yVal.text = dfltTitle.x;
        }
    }

    for(i = 0; i < xFullAxes.length; i++) {
        np(layout, xFullAxes[i]._name + '.' + key).set(yVal);
    }
    for(i = 0; i < yFullAxes.length; i++) {
        np(layout, yFullAxes[i]._name + '.' + key).set(xVal);
    }
}

function isAngular(ax) {
    return ax._id === 'angularaxis';
}

},{"../../components/color":574,"../../components/drawing":595,"../../components/titles":662,"../../constants/alignment":669,"../../constants/numerical":674,"../../lib":697,"../../lib/svg_text_utils":721,"../../plots/plots":807,"../../registry":826,"./autorange":744,"./axis_autotype":746,"./axis_ids":748,"./clean_ticks":750,"./layout_attributes":757,"./set_convert":763,"d3":151,"fast-isnumeric":218}],746:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

module.exports = function autoType(array, calendar, opts) {
    opts = opts || {};

    if(!opts.noMultiCategory && multiCategory(array)) return 'multicategory';
    if(moreDates(array, calendar)) return 'date';
    if(category(array)) return 'category';
    if(linearOK(array)) return 'linear';
    else return '-';
};

// is there at least one number in array? If not, we should leave
// ax.type empty so it can be autoset later
function linearOK(array) {
    if(!array) return false;

    for(var i = 0; i < array.length; i++) {
        if(isNumeric(array[i])) return true;
    }

    return false;
}

// does the array a have mostly dates rather than numbers?
// note: some values can be neither (such as blanks, text)
// 2- or 4-digit integers can be both, so require twice as many
// dates as non-dates, to exclude cases with mostly 2 & 4 digit
// numbers and a few dates
// as with categories, consider DISTINCT values only.
function moreDates(a, calendar) {
    // test at most 1000 points, evenly spaced
    var inc = Math.max(1, (a.length - 1) / 1000);
    var dcnt = 0;
    var ncnt = 0;
    var seen = {};

    for(var i = 0; i < a.length; i += inc) {
        var ai = a[Math.round(i)];
        var stri = String(ai);
        if(seen[stri]) continue;
        seen[stri] = 1;

        if(Lib.isDateTime(ai, calendar)) dcnt += 1;
        if(isNumeric(ai)) ncnt += 1;
    }

    return (dcnt > ncnt * 2);
}

// are the (x,y)-values in gd.data mostly text?
// require twice as many DISTINCT categories as distinct numbers
function category(a) {
    // test at most 1000 points
    var inc = Math.max(1, (a.length - 1) / 1000);
    var curvenums = 0;
    var curvecats = 0;
    var seen = {};

    for(var i = 0; i < a.length; i += inc) {
        var ai = a[Math.round(i)];
        var stri = String(ai);
        if(seen[stri]) continue;
        seen[stri] = 1;

        if(typeof ai === 'boolean') curvecats++;
        else if(Lib.cleanNumber(ai) !== BADNUM) curvenums++;
        else if(typeof ai === 'string') curvecats++;
    }

    return curvecats > curvenums * 2;
}

// very-loose requirements for multicategory,
// trace modules that should never auto-type to multicategory
// should be declared with 'noMultiCategory'
function multiCategory(a) {
    return Lib.isArrayOrTypedArray(a[0]) && Lib.isArrayOrTypedArray(a[1]);
}

},{"../../constants/numerical":674,"../../lib":697,"fast-isnumeric":218}],747:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');

var layoutAttributes = _dereq_('./layout_attributes');
var handleTickValueDefaults = _dereq_('./tick_value_defaults');
var handleTickMarkDefaults = _dereq_('./tick_mark_defaults');
var handleTickLabelDefaults = _dereq_('./tick_label_defaults');
var handleCategoryOrderDefaults = _dereq_('./category_order_defaults');
var handleLineGridDefaults = _dereq_('./line_grid_defaults');
var setConvert = _dereq_('./set_convert');

/**
 * options: object containing:
 *
 *  letter: 'x' or 'y'
 *  title: name of the axis (ie 'Colorbar') to go in default title
 *  font: the default font to inherit
 *  outerTicks: boolean, should ticks default to outside?
 *  showGrid: boolean, should gridlines be shown by default?
 *  noHover: boolean, this axis doesn't support hover effects?
 *  noTickson: boolean, this axis doesn't support 'tickson'
 *  data: the plot data, used to manage categories
 *  bgColor: the plot background color, to calculate default gridline colors
 */
module.exports = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) {
    var letter = options.letter;
    var font = options.font || {};
    var splomStash = options.splomStash || {};

    var visible = coerce('visible', !options.cheateronly);

    var axType = containerOut.type;

    if(axType === 'date') {
        var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleDefaults');
        handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar);
    }

    setConvert(containerOut, layoutOut);

    var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range));
    if(autoRange && (axType === 'linear' || axType === '-')) coerce('rangemode');

    coerce('range');
    containerOut.cleanRange();

    handleCategoryOrderDefaults(containerIn, containerOut, coerce, options);

    if(axType !== 'category' && !options.noHover) coerce('hoverformat');

    if(!visible) return containerOut;

    var dfltColor = coerce('color');
    // if axis.color was provided, use it for fonts too; otherwise,
    // inherit from global font color in case that was provided.
    // Compare to dflt rather than to containerIn, so we can provide color via
    // template too.
    var dfltFontColor = (dfltColor !== layoutAttributes.color.dflt) ? dfltColor : font.color;
    // try to get default title from splom trace, fallback to graph-wide value
    var dfltTitle = splomStash.label || layoutOut._dfltTitle[letter];

    coerce('title.text', dfltTitle);
    Lib.coerceFont(coerce, 'title.font', {
        family: font.family,
        size: Math.round(font.size * 1.2),
        color: dfltFontColor
    });

    handleTickValueDefaults(containerIn, containerOut, coerce, axType);
    handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options);
    handleTickMarkDefaults(containerIn, containerOut, coerce, options);
    handleLineGridDefaults(containerIn, containerOut, coerce, {
        dfltColor: dfltColor,
        bgColor: options.bgColor,
        showGrid: options.showGrid,
        attributes: layoutAttributes
    });

    if(containerOut.showline || containerOut.ticks) coerce('mirror');

    if(options.automargin) coerce('automargin');

    var isMultiCategory = containerOut.type === 'multicategory';

    if(!options.noTickson &&
        (containerOut.type === 'category' || isMultiCategory) &&
        (containerOut.ticks || containerOut.showgrid)
    ) {
        var ticksonDflt;
        if(isMultiCategory) ticksonDflt = 'boundaries';
        coerce('tickson', ticksonDflt);
    }

    if(isMultiCategory) {
        var showDividers = coerce('showdividers');
        if(showDividers) {
            coerce('dividercolor');
            coerce('dividerwidth');
        }
    }

    return containerOut;
};

},{"../../lib":697,"../../registry":826,"./category_order_defaults":749,"./layout_attributes":757,"./line_grid_defaults":759,"./set_convert":763,"./tick_label_defaults":764,"./tick_mark_defaults":765,"./tick_value_defaults":766}],748:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');

var constants = _dereq_('./constants');


// convert between axis names (xaxis, xaxis2, etc, elements of gd.layout)
// and axis id's (x, x2, etc). Would probably have ditched 'xaxis'
// completely in favor of just 'x' if it weren't ingrained in the API etc.
exports.id2name = function id2name(id) {
    if(typeof id !== 'string' || !id.match(constants.AX_ID_PATTERN)) return;
    var axNum = id.substr(1);
    if(axNum === '1') axNum = '';
    return id.charAt(0) + 'axis' + axNum;
};

exports.name2id = function name2id(name) {
    if(!name.match(constants.AX_NAME_PATTERN)) return;
    var axNum = name.substr(5);
    if(axNum === '1') axNum = '';
    return name.charAt(0) + axNum;
};

exports.cleanId = function cleanId(id, axLetter) {
    if(!id.match(constants.AX_ID_PATTERN)) return;
    if(axLetter && id.charAt(0) !== axLetter) return;

    var axNum = id.substr(1).replace(/^0+/, '');
    if(axNum === '1') axNum = '';
    return id.charAt(0) + axNum;
};

// get all axis objects, as restricted in listNames
exports.list = function(gd, axLetter, only2d) {
    var fullLayout = gd._fullLayout;
    if(!fullLayout) return [];

    var idList = exports.listIds(gd, axLetter);
    var out = new Array(idList.length);
    var i;

    for(i = 0; i < idList.length; i++) {
        var idi = idList[i];
        out[i] = fullLayout[idi.charAt(0) + 'axis' + idi.substr(1)];
    }

    if(!only2d) {
        var sceneIds3D = fullLayout._subplots.gl3d || [];

        for(i = 0; i < sceneIds3D.length; i++) {
            var scene = fullLayout[sceneIds3D[i]];

            if(axLetter) out.push(scene[axLetter + 'axis']);
            else out.push(scene.xaxis, scene.yaxis, scene.zaxis);
        }
    }

    return out;
};

// get all axis ids, optionally restricted by letter
// this only makes sense for 2d axes
exports.listIds = function(gd, axLetter) {
    var fullLayout = gd._fullLayout;
    if(!fullLayout) return [];

    var subplotLists = fullLayout._subplots;
    if(axLetter) return subplotLists[axLetter + 'axis'];
    return subplotLists.xaxis.concat(subplotLists.yaxis);
};

// get an axis object from its id 'x','x2' etc
// optionally, id can be a subplot (ie 'x2y3') and type gets x or y from it
exports.getFromId = function(gd, id, type) {
    var fullLayout = gd._fullLayout;

    if(type === 'x') id = id.replace(/y[0-9]*/, '');
    else if(type === 'y') id = id.replace(/x[0-9]*/, '');

    return fullLayout[exports.id2name(id)];
};

// get an axis object of specified type from the containing trace
exports.getFromTrace = function(gd, fullTrace, type) {
    var fullLayout = gd._fullLayout;
    var ax = null;

    if(Registry.traceIs(fullTrace, 'gl3d')) {
        var scene = fullTrace.scene;
        if(scene.substr(0, 5) === 'scene') {
            ax = fullLayout[scene][type + 'axis'];
        }
    }
    else {
        ax = exports.getFromId(gd, fullTrace[type + 'axis'] || type);
    }

    return ax;
};

// sort x, x2, x10, y, y2, y10...
exports.idSort = function(id1, id2) {
    var letter1 = id1.charAt(0);
    var letter2 = id2.charAt(0);
    if(letter1 !== letter2) return letter1 > letter2 ? 1 : -1;
    return +(id1.substr(1) || 1) - +(id2.substr(1) || 1);
};

exports.getAxisGroup = function getAxisGroup(fullLayout, axId) {
    var matchGroups = fullLayout._axisMatchGroups;

    for(var i = 0; i < matchGroups.length; i++) {
        var group = matchGroups[i];
        if(group[axId]) return 'g' + i;
    }
    return axId;
};

},{"../../registry":826,"./constants":751}],749:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

function findCategories(ax, opts) {
    var dataAttr = opts.dataAttr || ax._id.charAt(0);
    var lookup = {};
    var axData;
    var i, j;

    if(opts.axData) {
        // non-x/y case
        axData = opts.axData;
    } else {
        // x/y case
        axData = [];
        for(i = 0; i < opts.data.length; i++) {
            var trace = opts.data[i];
            if(trace[dataAttr + 'axis'] === ax._id) {
                axData.push(trace);
            }
        }
    }

    for(i = 0; i < axData.length; i++) {
        var vals = axData[i][dataAttr];
        for(j = 0; j < vals.length; j++) {
            var v = vals[j];
            if(v !== null && v !== undefined) {
                lookup[v] = 1;
            }
        }
    }

    return Object.keys(lookup);
}

/**
 * Fills in category* default and initial categories.
 *
 * @param {object} containerIn : input axis object
 * @param {object} containerOut : full axis object
 * @param {function} coerce : Lib.coerce fn wrapper
 * @param {object} opts :
 *   - data {array} : (full) data trace
 * OR
 *   - axData {array} : (full) data associated with axis being coerced here
 *   - dataAttr {string} : attribute name corresponding to coordinate array
 */
module.exports = function handleCategoryOrderDefaults(containerIn, containerOut, coerce, opts) {
    if(containerOut.type !== 'category') return;

    var arrayIn = containerIn.categoryarray;
    var isValidArray = (Array.isArray(arrayIn) && arrayIn.length > 0);

    // override default 'categoryorder' value when non-empty array is supplied
    var orderDefault;
    if(isValidArray) orderDefault = 'array';

    var order = coerce('categoryorder', orderDefault);
    var array;

    // coerce 'categoryarray' only in array order case
    if(order === 'array') {
        array = coerce('categoryarray');
    }

    // cannot set 'categoryorder' to 'array' with an invalid 'categoryarray'
    if(!isValidArray && order === 'array') {
        order = containerOut.categoryorder = 'trace';
    }

    // set up things for makeCalcdata
    if(order === 'trace') {
        containerOut._initialCategories = [];
    } else if(order === 'array') {
        containerOut._initialCategories = array.slice();
    } else {
        array = findCategories(containerOut, opts).sort();
        if(order === 'category ascending') {
            containerOut._initialCategories = array;
        } else if(order === 'category descending') {
            containerOut._initialCategories = array.reverse();
        }
    }
};

},{}],750:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var Lib = _dereq_('../../lib');
var ONEDAY = _dereq_('../../constants/numerical').ONEDAY;

/**
 * Return a validated dtick value for this axis
 *
 * @param {any} dtick: the candidate dtick. valid values are numbers and strings,
 *     and further constrained depending on the axis type.
 * @param {string} axType: the axis type
 */
exports.dtick = function(dtick, axType) {
    var isLog = axType === 'log';
    var isDate = axType === 'date';
    var isCat = axType === 'category';
    var dtickDflt = isDate ? ONEDAY : 1;

    if(!dtick) return dtickDflt;

    if(isNumeric(dtick)) {
        dtick = Number(dtick);
        if(dtick <= 0) return dtickDflt;
        if(isCat) {
            // category dtick must be positive integers
            return Math.max(1, Math.round(dtick));
        }
        if(isDate) {
            // date dtick must be at least 0.1ms (our current precision)
            return Math.max(0.1, dtick);
        }
        return dtick;
    }

    if(typeof dtick !== 'string' || !(isDate || isLog)) {
        return dtickDflt;
    }

    var prefix = dtick.charAt(0);
    var dtickNum = dtick.substr(1);
    dtickNum = isNumeric(dtickNum) ? Number(dtickNum) : 0;

    if((dtickNum <= 0) || !(
            // "M<n>" gives ticks every (integer) n months
            (isDate && prefix === 'M' && dtickNum === Math.round(dtickNum)) ||
            // "L<f>" gives ticks linearly spaced in data (not in position) every (float) f
            (isLog && prefix === 'L') ||
            // "D1" gives powers of 10 with all small digits between, "D2" gives only 2 and 5
            (isLog && prefix === 'D' && (dtickNum === 1 || dtickNum === 2))
        )) {
        return dtickDflt;
    }

    return dtick;
};

/**
 * Return a validated tick0 for this axis
 *
 * @param {any} tick0: the candidate tick0. Valid values are numbers and strings,
 *     further constrained depending on the axis type
 * @param {string} axType: the axis type
 * @param {string} calendar: for date axes, the calendar to validate/convert with
 * @param {any} dtick: an already valid dtick. Only used for D1 and D2 log dticks,
 *     which do not support tick0 at all.
 */
exports.tick0 = function(tick0, axType, calendar, dtick) {
    if(axType === 'date') {
        return Lib.cleanDate(tick0, Lib.dateTick0(calendar));
    }
    if(dtick === 'D1' || dtick === 'D2') {
        // D1 and D2 modes ignore tick0 entirely
        return undefined;
    }
    // Aside from date axes, tick0 must be numeric
    return isNumeric(tick0) ? Number(tick0) : 0;
};

},{"../../constants/numerical":674,"../../lib":697,"fast-isnumeric":218}],751:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';
var counterRegex = _dereq_('../../lib/regex').counter;


module.exports = {

    idRegex: {
        x: counterRegex('x'),
        y: counterRegex('y')
    },

    attrRegex: counterRegex('[xy]axis'),

    // axis match regular expression
    xAxisMatch: counterRegex('xaxis'),
    yAxisMatch: counterRegex('yaxis'),

    // pattern matching axis ids and names
    // note that this is more permissive than counterRegex, as
    // id2name, name2id, and cleanId accept "x1" etc
    AX_ID_PATTERN: /^[xyz][0-9]*$/,
    AX_NAME_PATTERN: /^[xyz]axis[0-9]*$/,

    // and for 2D subplots
    SUBPLOT_PATTERN: /^x([0-9]*)y([0-9]*)$/,

    // pixels to move mouse before you stop clamping to starting point
    MINDRAG: 8,

    // smallest dimension allowed for a select box
    MINSELECT: 12,

    // smallest dimension allowed for a zoombox
    MINZOOM: 20,

    // width of axis drag regions
    DRAGGERSIZE: 20,

    // max pixels off straight before a lasso select line counts as bent
    BENDPX: 1.5,

    // delay before a redraw (relayout) after smooth panning and zooming
    REDRAWDELAY: 50,

    // throttling limit (ms) for selectPoints calls
    SELECTDELAY: 100,

    // cache ID suffix for throttle
    SELECTID: '-select',

    // last resort axis ranges for x and y axes if we have no data
    DFLTRANGEX: [-1, 6],
    DFLTRANGEY: [-1, 4],

    // Layers to keep trace types in the right order
    // N.B. each  'unique' plot method must have its own layer
    traceLayerClasses: [
        'heatmaplayer',
        'contourcarpetlayer', 'contourlayer',
        'barlayer',
        'carpetlayer',
        'violinlayer',
        'boxlayer',
        'ohlclayer',
        'scattercarpetlayer', 'scatterlayer'
    ],

    layerValue2layerClass: {
        'above traces': 'above',
        'below traces': 'below'
    }
};

},{"../../lib/regex":713}],752:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var id2name = _dereq_('./axis_ids').id2name;
var scaleZoom = _dereq_('./scale_zoom');
var makePadFn = _dereq_('./autorange').makePadFn;
var concatExtremes = _dereq_('./autorange').concatExtremes;

var ALMOST_EQUAL = _dereq_('../../constants/numerical').ALMOST_EQUAL;
var FROM_BL = _dereq_('../../constants/alignment').FROM_BL;

exports.handleConstraintDefaults = function(containerIn, containerOut, coerce, allAxisIds, layoutOut) {
    var constraintGroups = layoutOut._axisConstraintGroups;
    var matchGroups = layoutOut._axisMatchGroups;
    var axId = containerOut._id;
    var axLetter = axId.charAt(0);
    var splomStash = ((layoutOut._splomAxes || {})[axLetter] || {})[axId] || {};
    var thisID = containerOut._id;
    var letter = thisID.charAt(0);

    // coerce the constraint mechanics even if this axis has no scaleanchor
    // because it may be the anchor of another axis.
    var constrain = coerce('constrain');
    Lib.coerce(containerIn, containerOut, {
        constraintoward: {
            valType: 'enumerated',
            values: letter === 'x' ? ['left', 'center', 'right'] : ['bottom', 'middle', 'top'],
            dflt: letter === 'x' ? 'center' : 'middle'
        }
    }, 'constraintoward');

    var matches, matchOpts;

    if((containerIn.matches || splomStash.matches) && !containerOut.fixedrange) {
        matchOpts = getConstraintOpts(matchGroups, thisID, allAxisIds, layoutOut);
        matches = Lib.coerce(containerIn, containerOut, {
            matches: {
                valType: 'enumerated',
                values: matchOpts.linkableAxes || [],
                dflt: splomStash.matches
            }
        }, 'matches');
    }

    // 'matches' wins over 'scaleanchor' (for now)
    var scaleanchor, scaleOpts;

    if(!matches && containerIn.scaleanchor && !(containerOut.fixedrange && constrain !== 'domain')) {
        scaleOpts = getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut, constrain);
        scaleanchor = Lib.coerce(containerIn, containerOut, {
            scaleanchor: {
                valType: 'enumerated',
                values: scaleOpts.linkableAxes || []
            }
        }, 'scaleanchor');
    }

    if(matches) {
        delete containerOut.constrain;
        updateConstraintGroups(matchGroups, matchOpts.thisGroup, thisID, matches, 1);
    } else if(allAxisIds.indexOf(containerIn.matches) !== -1) {
        Lib.warn('ignored ' + containerOut._name + '.matches: "' +
            containerIn.matches + '" to avoid either an infinite loop ' +
            'or because the target axis has fixed range.');
    }

    if(scaleanchor) {
        var scaleratio = coerce('scaleratio');

        // TODO: I suppose I could do attribute.min: Number.MIN_VALUE to avoid zero,
        // but that seems hacky. Better way to say "must be a positive number"?
        // Of course if you use several super-tiny values you could eventually
        // force a product of these to zero and all hell would break loose...
        // Likewise with super-huge values.
        if(!scaleratio) scaleratio = containerOut.scaleratio = 1;

        updateConstraintGroups(constraintGroups, scaleOpts.thisGroup, thisID, scaleanchor, scaleratio);
    } else if(allAxisIds.indexOf(containerIn.scaleanchor) !== -1) {
        Lib.warn('ignored ' + containerOut._name + '.scaleanchor: "' +
            containerIn.scaleanchor + '" to avoid either an infinite loop ' +
            'and possibly inconsistent scaleratios, or because the target ' +
            'axis has fixed range or this axis declares a *matches* constraint.');
    }
};

// If this axis is already part of a constraint group, we can't
// scaleanchor any other axis in that group, or we'd make a loop.
// Filter allAxisIds to enforce this, also matching axis types.
function getConstraintOpts(groups, thisID, allAxisIds, layoutOut, constrain) {
    var doesNotConstrainRange = constrain !== 'range';
    var thisType = layoutOut[id2name(thisID)].type;
    var i, j, idj, axj;

    var linkableAxes = [];
    for(j = 0; j < allAxisIds.length; j++) {
        idj = allAxisIds[j];
        if(idj === thisID) continue;

        axj = layoutOut[id2name(idj)];
        if(axj.type === thisType) {
            if(!axj.fixedrange) {
                linkableAxes.push(idj);
            } else if(doesNotConstrainRange && axj.anchor) {
                // allow domain constraints on subplots where
                // BOTH axes have fixedrange:true and constrain:domain
                var counterAxj = layoutOut[id2name(axj.anchor)];
                if(counterAxj.fixedrange) {
                    linkableAxes.push(idj);
                }
            }
        }
    }

    for(i = 0; i < groups.length; i++) {
        if(groups[i][thisID]) {
            var thisGroup = groups[i];

            var linkableAxesNoLoops = [];
            for(j = 0; j < linkableAxes.length; j++) {
                idj = linkableAxes[j];
                if(!thisGroup[idj]) linkableAxesNoLoops.push(idj);
            }
            return {linkableAxes: linkableAxesNoLoops, thisGroup: thisGroup};
        }
    }

    return {linkableAxes: linkableAxes, thisGroup: null};
}

/*
 * Add this axis to the axis constraint groups, which is the collection
 * of axes that are all constrained together on scale.
 *
 * constraintGroups: a list of objects. each object is
 * {axis_id: scale_within_group}, where scale_within_group is
 * only important relative to the rest of the group, and defines
 * the relative scales between all axes in the group
 *
 * thisGroup: the group the current axis is already in
 * thisID: the id if the current axis
 * scaleanchor: the id of the axis to scale it with
 * scaleratio: the ratio of this axis to the scaleanchor axis
 */
function updateConstraintGroups(constraintGroups, thisGroup, thisID, scaleanchor, scaleratio) {
    var i, j, groupi, keyj, thisGroupIndex;

    if(thisGroup === null) {
        thisGroup = {};
        thisGroup[thisID] = 1;
        thisGroupIndex = constraintGroups.length;
        constraintGroups.push(thisGroup);
    }
    else {
        thisGroupIndex = constraintGroups.indexOf(thisGroup);
    }

    var thisGroupKeys = Object.keys(thisGroup);

    // we know that this axis isn't in any other groups, but we don't know
    // about the scaleanchor axis. If it is, we need to merge the groups.
    for(i = 0; i < constraintGroups.length; i++) {
        groupi = constraintGroups[i];
        if(i !== thisGroupIndex && groupi[scaleanchor]) {
            var baseScale = groupi[scaleanchor];
            for(j = 0; j < thisGroupKeys.length; j++) {
                keyj = thisGroupKeys[j];
                groupi[keyj] = baseScale * scaleratio * thisGroup[keyj];
            }
            constraintGroups.splice(thisGroupIndex, 1);
            return;
        }
    }

    // otherwise, we insert the new scaleanchor axis as the base scale (1)
    // in its group, and scale the rest of the group to it
    if(scaleratio !== 1) {
        for(j = 0; j < thisGroupKeys.length; j++) {
            thisGroup[thisGroupKeys[j]] *= scaleratio;
        }
    }
    thisGroup[scaleanchor] = 1;
}

exports.enforce = function enforceAxisConstraints(gd) {
    var fullLayout = gd._fullLayout;
    var constraintGroups = fullLayout._axisConstraintGroups || [];

    var i, j, axisID, ax, normScale, mode, factor;

    for(i = 0; i < constraintGroups.length; i++) {
        var group = constraintGroups[i];
        var axisIDs = Object.keys(group);

        var minScale = Infinity;
        var maxScale = 0;
        // mostly matchScale will be the same as minScale
        // ie we expand axis ranges to encompass *everything*
        // that's currently in any of their ranges, but during
        // autorange of a subset of axes we will ignore other
        // axes for this purpose.
        var matchScale = Infinity;
        var normScales = {};
        var axes = {};
        var hasAnyDomainConstraint = false;

        // find the (normalized) scale of each axis in the group
        for(j = 0; j < axisIDs.length; j++) {
            axisID = axisIDs[j];
            axes[axisID] = ax = fullLayout[id2name(axisID)];

            if(ax._inputDomain) ax.domain = ax._inputDomain.slice();
            else ax._inputDomain = ax.domain.slice();

            if(!ax._inputRange) ax._inputRange = ax.range.slice();

            // set axis scale here so we can use _m rather than
            // having to calculate it from length and range
            ax.setScale();

            // abs: inverted scales still satisfy the constraint
            normScales[axisID] = normScale = Math.abs(ax._m) / group[axisID];
            minScale = Math.min(minScale, normScale);
            if(ax.constrain === 'domain' || !ax._constraintShrinkable) {
                matchScale = Math.min(matchScale, normScale);
            }

            // this has served its purpose, so remove it
            delete ax._constraintShrinkable;
            maxScale = Math.max(maxScale, normScale);

            if(ax.constrain === 'domain') hasAnyDomainConstraint = true;
        }

        // Do we have a constraint mismatch? Give a small buffer for rounding errors
        if(minScale > ALMOST_EQUAL * maxScale && !hasAnyDomainConstraint) continue;

        // now increase any ranges we need to until all normalized scales are equal
        for(j = 0; j < axisIDs.length; j++) {
            axisID = axisIDs[j];
            normScale = normScales[axisID];
            ax = axes[axisID];
            mode = ax.constrain;

            // even if the scale didn't change, if we're shrinking domain
            // we need to recalculate in case `constraintoward` changed
            if(normScale !== matchScale || mode === 'domain') {
                factor = normScale / matchScale;

                if(mode === 'range') {
                    scaleZoom(ax, factor);
                }
                else {
                    // mode === 'domain'

                    var inputDomain = ax._inputDomain;
                    var domainShrunk = (ax.domain[1] - ax.domain[0]) /
                        (inputDomain[1] - inputDomain[0]);
                    var rangeShrunk = (ax.r2l(ax.range[1]) - ax.r2l(ax.range[0])) /
                        (ax.r2l(ax._inputRange[1]) - ax.r2l(ax._inputRange[0]));

                    factor /= domainShrunk;

                    if(factor * rangeShrunk < 1) {
                        // we've asked to magnify the axis more than we can just by
                        // enlarging the domain - so we need to constrict range
                        ax.domain = ax._input.domain = inputDomain.slice();
                        scaleZoom(ax, factor);
                        continue;
                    }

                    if(rangeShrunk < 1) {
                        // the range has previously been constricted by ^^, but we've
                        // switched to the domain-constricted regime, so reset range
                        ax.range = ax._input.range = ax._inputRange.slice();
                        factor *= rangeShrunk;
                    }

                    if(ax.autorange) {
                        /*
                         * range & factor may need to change because range was
                         * calculated for the larger scaling, so some pixel
                         * paddings may get cut off when we reduce the domain.
                         *
                         * This is easier than the regular autorange calculation
                         * because we already know the scaling `m`, but we still
                         * need to cut out impossible constraints (like
                         * annotations with super-long arrows). That's what
                         * outerMin/Max are for - if the expansion was going to
                         * go beyond the original domain, it must be impossible
                         */
                        var rl0 = ax.r2l(ax.range[0]);
                        var rl1 = ax.r2l(ax.range[1]);
                        var rangeCenter = (rl0 + rl1) / 2;
                        var rangeMin = rangeCenter;
                        var rangeMax = rangeCenter;
                        var halfRange = Math.abs(rl1 - rangeCenter);
                        // extra tiny bit for rounding errors, in case we actually
                        // *are* expanding to the full domain
                        var outerMin = rangeCenter - halfRange * factor * 1.0001;
                        var outerMax = rangeCenter + halfRange * factor * 1.0001;
                        var getPad = makePadFn(ax);

                        updateDomain(ax, factor);
                        var m = Math.abs(ax._m);
                        var extremes = concatExtremes(gd, ax);
                        var minArray = extremes.min;
                        var maxArray = extremes.max;
                        var newVal;
                        var k;

                        for(k = 0; k < minArray.length; k++) {
                            newVal = minArray[k].val - getPad(minArray[k]) / m;
                            if(newVal > outerMin && newVal < rangeMin) {
                                rangeMin = newVal;
                            }
                        }

                        for(k = 0; k < maxArray.length; k++) {
                            newVal = maxArray[k].val + getPad(maxArray[k]) / m;
                            if(newVal < outerMax && newVal > rangeMax) {
                                rangeMax = newVal;
                            }
                        }

                        var domainExpand = (rangeMax - rangeMin) / (2 * halfRange);
                        factor /= domainExpand;

                        rangeMin = ax.l2r(rangeMin);
                        rangeMax = ax.l2r(rangeMax);
                        ax.range = ax._input.range = (rl0 < rl1) ?
                            [rangeMin, rangeMax] : [rangeMax, rangeMin];
                    }

                    updateDomain(ax, factor);
                }
            }
        }
    }
};

// For use before autoranging, check if this axis was previously constrained
// by domain but no longer is
exports.clean = function cleanConstraints(gd, ax) {
    if(ax._inputDomain) {
        var isConstrained = false;
        var axId = ax._id;
        var constraintGroups = gd._fullLayout._axisConstraintGroups;
        for(var j = 0; j < constraintGroups.length; j++) {
            if(constraintGroups[j][axId]) {
                isConstrained = true;
                break;
            }
        }
        if(!isConstrained || ax.constrain !== 'domain') {
            ax._input.domain = ax.domain = ax._inputDomain;
            delete ax._inputDomain;
        }
    }
};

function updateDomain(ax, factor) {
    var inputDomain = ax._inputDomain;
    var centerFraction = FROM_BL[ax.constraintoward];
    var center = inputDomain[0] + (inputDomain[1] - inputDomain[0]) * centerFraction;

    ax.domain = ax._input.domain = [
        center + (inputDomain[0] - center) / factor,
        center + (inputDomain[1] - center) / factor
    ];
    ax.setScale();
}

},{"../../constants/alignment":669,"../../constants/numerical":674,"../../lib":697,"./autorange":744,"./axis_ids":748,"./scale_zoom":761}],753:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var tinycolor = _dereq_('tinycolor2');
var supportsPassive = _dereq_('has-passive-events');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var Color = _dereq_('../../components/color');
var Drawing = _dereq_('../../components/drawing');
var Fx = _dereq_('../../components/fx');
var Axes = _dereq_('./axes');
var setCursor = _dereq_('../../lib/setcursor');
var dragElement = _dereq_('../../components/dragelement');
var FROM_TL = _dereq_('../../constants/alignment').FROM_TL;
var clearGlCanvases = _dereq_('../../lib/clear_gl_canvases');
var redrawReglTraces = _dereq_('../../plot_api/subroutines').redrawReglTraces;

var Plots = _dereq_('../plots');

var getFromId = _dereq_('./axis_ids').getFromId;
var prepSelect = _dereq_('./select').prepSelect;
var clearSelect = _dereq_('./select').clearSelect;
var selectOnClick = _dereq_('./select').selectOnClick;
var scaleZoom = _dereq_('./scale_zoom');

var constants = _dereq_('./constants');
var MINDRAG = constants.MINDRAG;
var MINZOOM = constants.MINZOOM;


// flag for showing "doubleclick to zoom out" only at the beginning
var SHOWZOOMOUTTIP = true;

// dragBox: create an element to drag one or more axis ends
// inputs:
//      plotinfo - which subplot are we making dragboxes on?
//      x,y,w,h - left, top, width, height of the box
//      ns - how does this drag the vertical axis?
//          'n' - top only
//          's' - bottom only
//          'ns' - top and bottom together, difference unchanged
//      ew - same for horizontal axis
function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) {
    // mouseDown stores ms of first mousedown event in the last
    // DBLCLICKDELAY ms on the drag bars
    // numClicks stores how many mousedowns have been seen
    // within DBLCLICKDELAY so we can check for click or doubleclick events
    // dragged stores whether a drag has occurred, so we don't have to
    // redraw unnecessarily, ie if no move bigger than MINDRAG or MINZOOM px
    var zoomlayer = gd._fullLayout._zoomlayer;
    var isMainDrag = (ns + ew === 'nsew');
    var singleEnd = (ns + ew).length === 1;

    // main subplot x and y (i.e. found in plotinfo - the main ones)
    var xa0, ya0;
    // {ax._id: ax} hash objects
    var xaHash, yaHash;
    // xaHash/yaHash values (arrays)
    var xaxes, yaxes;
    // main axis offsets
    var xs, ys;
    // main axis lengths
    var pw, ph;
    // contains keys 'xaHash', 'yaHash', 'xaxes', and 'yaxes'
    // which are the x/y {ax._id: ax} hash objects and their values
    // for linked axis relative to this subplot
    var links;
    // similar to `links` but for matching axes
    var matches;
    // set to ew/ns val when active, set to '' when inactive
    var xActive, yActive;
    // are all axes in this subplot are fixed?
    var allFixedRanges;
    // do we need to edit x/y ranges?
    var editX, editY;
    // graph-wide optimization flags
    var hasScatterGl, hasSplom, hasSVG;
    // collected changes to be made to the plot by relayout at the end
    var updates;

    function recomputeAxisLists() {
        xa0 = plotinfo.xaxis;
        ya0 = plotinfo.yaxis;
        pw = xa0._length;
        ph = ya0._length;
        xs = xa0._offset;
        ys = ya0._offset;

        xaHash = {};
        xaHash[xa0._id] = xa0;
        yaHash = {};
        yaHash[ya0._id] = ya0;

        // if we're dragging two axes at once, also drag overlays
        if(ns && ew) {
            var overlays = plotinfo.overlays;
            for(var i = 0; i < overlays.length; i++) {
                var xa = overlays[i].xaxis;
                xaHash[xa._id] = xa;
                var ya = overlays[i].yaxis;
                yaHash[ya._id] = ya;
            }
        }

        xaxes = hashValues(xaHash);
        yaxes = hashValues(yaHash);
        xActive = isDirectionActive(xaxes, ew);
        yActive = isDirectionActive(yaxes, ns);
        allFixedRanges = !yActive && !xActive;

        links = calcLinks(gd, gd._fullLayout._axisConstraintGroups, xaHash, yaHash);
        matches = calcLinks(gd, gd._fullLayout._axisMatchGroups, xaHash, yaHash);
        editX = ew || links.isSubplotConstrained || matches.isSubplotConstrained;
        editY = ns || links.isSubplotConstrained || matches.isSubplotConstrained;

        var fullLayout = gd._fullLayout;
        hasScatterGl = fullLayout._has('scattergl');
        hasSplom = fullLayout._has('splom');
        hasSVG = fullLayout._has('svg');
    }

    recomputeAxisLists();

    var cursor = getDragCursor(yActive + xActive, gd._fullLayout.dragmode, isMainDrag);
    var dragger = makeRectDragger(plotinfo, ns + ew + 'drag', cursor, x, y, w, h);

    // still need to make the element if the axes are disabled
    // but nuke its events (except for maindrag which needs them for hover)
    // and stop there
    if(allFixedRanges && !isMainDrag) {
        dragger.onmousedown = null;
        dragger.style.pointerEvents = 'none';
        return dragger;
    }

    var dragOptions = {
        element: dragger,
        gd: gd,
        plotinfo: plotinfo
    };

    dragOptions.prepFn = function(e, startX, startY) {
        var dragModePrev = dragOptions.dragmode;
        var dragModeNow = gd._fullLayout.dragmode;
        if(dragModeNow !== dragModePrev) {
            dragOptions.dragmode = dragModeNow;
        }

        recomputeAxisLists();

        if(!allFixedRanges) {
            if(isMainDrag) {
                // main dragger handles all drag modes, and changes
                // to pan (or to zoom if it already is pan) on shift
                if(e.shiftKey) {
                    if(dragModeNow === 'pan') dragModeNow = 'zoom';
                    else if(!isSelectOrLasso(dragModeNow)) dragModeNow = 'pan';
                }
                else if(e.ctrlKey) {
                    dragModeNow = 'pan';
                }
            }
            // all other draggers just pan
            else dragModeNow = 'pan';
        }

        if(dragModeNow === 'lasso') dragOptions.minDrag = 1;
        else dragOptions.minDrag = undefined;

        if(isSelectOrLasso(dragModeNow)) {
            dragOptions.xaxes = xaxes;
            dragOptions.yaxes = yaxes;
            // this attaches moveFn, clickFn, doneFn on dragOptions
            prepSelect(e, startX, startY, dragOptions, dragModeNow);
        } else {
            dragOptions.clickFn = clickFn;
            if(isSelectOrLasso(dragModePrev)) {
                // TODO Fix potential bug
                // Note: clearing / resetting selection state only happens, when user
                // triggers at least one interaction in pan/zoom mode. Otherwise, the
                // select/lasso outlines are deleted (in plots.js.cleanPlot) but the selection
                // cache isn't cleared. So when the user switches back to select/lasso and
                // 'adds to a selection' with Shift, the "old", seemingly removed outlines
                // are redrawn again because the selection cache still holds their coordinates.
                // However, this isn't easily solved, since plots.js would need
                // to have a reference to the dragOptions object (which holds the
                // selection cache).
                clearAndResetSelect();
            }

            if(!allFixedRanges) {
                if(dragModeNow === 'zoom') {
                    dragOptions.moveFn = zoomMove;
                    dragOptions.doneFn = zoomDone;

                    // zoomMove takes care of the threshold, but we need to
                    // minimize this so that constrained zoom boxes will flip
                    // orientation at the right place
                    dragOptions.minDrag = 1;

                    zoomPrep(e, startX, startY);
                } else if(dragModeNow === 'pan') {
                    dragOptions.moveFn = plotDrag;
                    dragOptions.doneFn = dragTail;
                }
            }
        }
    };

    function clearAndResetSelect() {
        // clear selection polygon cache (if any)
        dragOptions.plotinfo.selection = false;
        // clear selection outlines
        clearSelect(zoomlayer);
    }

    function clickFn(numClicks, evt) {
        var clickmode = gd._fullLayout.clickmode;

        removeZoombox(gd);

        if(numClicks === 2 && !singleEnd) doubleClick();

        if(isMainDrag) {
            if(clickmode.indexOf('select') > -1) {
                selectOnClick(evt, gd, xaxes, yaxes, plotinfo.id, dragOptions);
            }

            if(clickmode.indexOf('event') > -1) {
                Fx.click(gd, evt, plotinfo.id);
            }
        }
        else if(numClicks === 1 && singleEnd) {
            var ax = ns ? ya0 : xa0;
            var end = (ns === 's' || ew === 'w') ? 0 : 1;
            var attrStr = ax._name + '.range[' + end + ']';
            var initialText = getEndText(ax, end);
            var hAlign = 'left';
            var vAlign = 'middle';

            if(ax.fixedrange) return;

            if(ns) {
                vAlign = (ns === 'n') ? 'top' : 'bottom';
                if(ax.side === 'right') hAlign = 'right';
            }
            else if(ew === 'e') hAlign = 'right';

            if(gd._context.showAxisRangeEntryBoxes) {
                d3.select(dragger)
                    .call(svgTextUtils.makeEditable, {
                        gd: gd,
                        immediate: true,
                        background: gd._fullLayout.paper_bgcolor,
                        text: String(initialText),
                        fill: ax.tickfont ? ax.tickfont.color : '#444',
                        horizontalAlign: hAlign,
                        verticalAlign: vAlign
                    })
                    .on('edit', function(text) {
                        var v = ax.d2r(text);
                        if(v !== undefined) {
                            Registry.call('_guiRelayout', gd, attrStr, v);
                        }
                    });
            }
        }
    }

    dragElement.init(dragOptions);

    // x/y px position at start of drag
    var x0, y0;
    // bbox object of the zoombox
    var box;
    // luminance of bg behind zoombox
    var lum;
    // zoombox path outline
    var path0;
    // is zoombox dimmed (during drag)
    var dimmed;
    // 'x'-only, 'y' or 'xy' zooming
    var zoomMode;
    // zoombox d3 selection
    var zb;
    // zoombox corner d3 selection
    var corners;
    // zoom takes over minDrag, so it also has to take over gd._dragged
    var zoomDragged;

    function zoomPrep(e, startX, startY) {
        var dragBBox = dragger.getBoundingClientRect();
        x0 = startX - dragBBox.left;
        y0 = startY - dragBBox.top;
        box = {l: x0, r: x0, w: 0, t: y0, b: y0, h: 0};
        lum = gd._hmpixcount ?
            (gd._hmlumcount / gd._hmpixcount) :
            tinycolor(gd._fullLayout.plot_bgcolor).getLuminance();
        path0 = 'M0,0H' + pw + 'V' + ph + 'H0V0';
        dimmed = false;
        zoomMode = 'xy';
        zoomDragged = false;
        zb = makeZoombox(zoomlayer, lum, xs, ys, path0);
        corners = makeCorners(zoomlayer, xs, ys);
    }

    function zoomMove(dx0, dy0) {
        if(gd._transitioningWithDuration) {
            return false;
        }

        var x1 = Math.max(0, Math.min(pw, dx0 + x0));
        var y1 = Math.max(0, Math.min(ph, dy0 + y0));
        var dx = Math.abs(x1 - x0);
        var dy = Math.abs(y1 - y0);

        box.l = Math.min(x0, x1);
        box.r = Math.max(x0, x1);
        box.t = Math.min(y0, y1);
        box.b = Math.max(y0, y1);

        function noZoom() {
            zoomMode = '';
            box.r = box.l;
            box.t = box.b;
            corners.attr('d', 'M0,0Z');
        }

        if(links.isSubplotConstrained) {
            if(dx > MINZOOM || dy > MINZOOM) {
                zoomMode = 'xy';
                if(dx / pw > dy / ph) {
                    dy = dx * ph / pw;
                    if(y0 > y1) box.t = y0 - dy;
                    else box.b = y0 + dy;
                } else {
                    dx = dy * pw / ph;
                    if(x0 > x1) box.l = x0 - dx;
                    else box.r = x0 + dx;
                }
                corners.attr('d', xyCorners(box));
            } else {
                noZoom();
            }
        }
        else if(matches.isSubplotConstrained) {
            if(dx > MINZOOM || dy > MINZOOM) {
                zoomMode = 'xy';

                var r0 = Math.min(box.l / pw, (ph - box.b) / ph);
                var r1 = Math.max(box.r / pw, (ph - box.t) / ph);

                box.l = r0 * pw;
                box.r = r1 * pw;
                box.b = (1 - r0) * ph;
                box.t = (1 - r1) * ph;
                corners.attr('d', xyCorners(box));
            } else {
                noZoom();
            }
        }
        // look for small drags in one direction or the other,
        // and only drag the other axis
        else if(!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) {
            if(dx < MINDRAG || !xActive) {
                noZoom();
            } else {
                box.t = 0;
                box.b = ph;
                zoomMode = 'x';
                corners.attr('d', xCorners(box, y0));
            }
        }
        else if(!xActive || dx < Math.min(dy * 0.6, MINZOOM)) {
            box.l = 0;
            box.r = pw;
            zoomMode = 'y';
            corners.attr('d', yCorners(box, x0));
        }
        else {
            zoomMode = 'xy';
            corners.attr('d', xyCorners(box));
        }
        box.w = box.r - box.l;
        box.h = box.b - box.t;

        if(zoomMode) zoomDragged = true;
        gd._dragged = zoomDragged;

        updateZoombox(zb, corners, box, path0, dimmed, lum);
        dimmed = true;
    }

    function zoomDone() {
        updates = {};

        // more strict than dragged, which allows you to come back to where you started
        // and still count as dragged
        if(Math.min(box.h, box.w) < MINDRAG * 2) {
            return removeZoombox(gd);
        }

        // TODO: edit linked axes in zoomAxRanges and in dragTail
        if(zoomMode === 'xy' || zoomMode === 'x') {
            zoomAxRanges(xaxes, box.l / pw, box.r / pw, updates, links.xaxes);
            updateMatchedAxRange('x', updates);
        }
        if(zoomMode === 'xy' || zoomMode === 'y') {
            zoomAxRanges(yaxes, (ph - box.b) / ph, (ph - box.t) / ph, updates, links.yaxes);
            updateMatchedAxRange('y', updates);
        }

        removeZoombox(gd);
        dragTail();
        showDoubleClickNotifier(gd);
    }

    // scroll zoom, on all draggers except corners
    var scrollViewBox = [0, 0, pw, ph];
    // wait a little after scrolling before redrawing
    var redrawTimer = null;
    var REDRAWDELAY = constants.REDRAWDELAY;
    var mainplot = plotinfo.mainplot ? gd._fullLayout._plots[plotinfo.mainplot] : plotinfo;

    function zoomWheel(e) {
        // deactivate mousewheel scrolling on embedded graphs
        // devs can override this with layout._enablescrollzoom,
        // but _ ensures this setting won't leave their page
        if(!gd._context._scrollZoom.cartesian && !gd._fullLayout._enablescrollzoom) {
            return;
        }

        clearAndResetSelect();

        // If a transition is in progress, then disable any behavior:
        if(gd._transitioningWithDuration) {
            e.preventDefault();
            e.stopPropagation();
            return;
        }

        recomputeAxisLists();

        clearTimeout(redrawTimer);

        var wheelDelta = -e.deltaY;
        if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10;
        if(!isFinite(wheelDelta)) {
            Lib.log('Did not find wheel motion attributes: ', e);
            return;
        }

        var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200);
        var gbb = mainplot.draglayer.select('.nsewdrag').node().getBoundingClientRect();
        var xfrac = (e.clientX - gbb.left) / gbb.width;
        var yfrac = (gbb.bottom - e.clientY) / gbb.height;
        var i;

        function zoomWheelOneAxis(ax, centerFraction, zoom) {
            if(ax.fixedrange) return;

            var axRange = Lib.simpleMap(ax.range, ax.r2l);
            var v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction;
            function doZoom(v) { return ax.l2r(v0 + (v - v0) * zoom); }
            ax.range = axRange.map(doZoom);
        }

        if(editX) {
            // if we're only zooming this axis because of constraints,
            // zoom it about the center
            if(!ew) xfrac = 0.5;

            for(i = 0; i < xaxes.length; i++) {
                zoomWheelOneAxis(xaxes[i], xfrac, zoom);
            }
            updateMatchedAxRange('x');

            scrollViewBox[2] *= zoom;
            scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1);
        }
        if(editY) {
            if(!ns) yfrac = 0.5;

            for(i = 0; i < yaxes.length; i++) {
                zoomWheelOneAxis(yaxes[i], yfrac, zoom);
            }
            updateMatchedAxRange('y');

            scrollViewBox[3] *= zoom;
            scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1);
        }

        // viewbox redraw at first
        updateSubplots(scrollViewBox);
        ticksAndAnnotations();

        // then replot after a delay to make sure
        // no more scrolling is coming
        redrawTimer = setTimeout(function() {
            scrollViewBox = [0, 0, pw, ph];
            dragTail();
        }, REDRAWDELAY);

        e.preventDefault();
        return;
    }

    // everything but the corners gets wheel zoom
    if(ns.length * ew.length !== 1) {
        attachWheelEventHandler(dragger, zoomWheel);
    }

    // plotDrag: move the plot in response to a drag
    function plotDrag(dx, dy) {
        // If a transition is in progress, then disable any behavior:
        if(gd._transitioningWithDuration) {
            return;
        }

        // prevent axis drawing from monkeying with margins until we're done
        gd._fullLayout._replotting = true;

        if(xActive === 'ew' || yActive === 'ns') {
            if(xActive) {
                dragAxList(xaxes, dx);
                updateMatchedAxRange('x');
            }
            if(yActive) {
                dragAxList(yaxes, dy);
                updateMatchedAxRange('y');
            }
            updateSubplots([xActive ? -dx : 0, yActive ? -dy : 0, pw, ph]);
            ticksAndAnnotations();
            return;
        }

        // dz: set a new value for one end (0 or 1) of an axis array axArray,
        // and return a pixel shift for that end for the viewbox
        // based on pixel drag distance d
        // TODO: this makes (generally non-fatal) errors when you get
        // near floating point limits
        function dz(axArray, end, d) {
            var otherEnd = 1 - end;
            var movedAx;
            var newLinearizedEnd;
            for(var i = 0; i < axArray.length; i++) {
                var axi = axArray[i];
                if(axi.fixedrange) continue;
                movedAx = axi;
                newLinearizedEnd = axi._rl[otherEnd] +
                    (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length);
                var newEnd = axi.l2r(newLinearizedEnd);

                // if l2r comes back false or undefined, it means we've dragged off
                // the end of valid ranges - so stop.
                if(newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd;
            }
            return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) /
                (movedAx._rl[end] - movedAx._rl[otherEnd]);
        }

        if(links.isSubplotConstrained && xActive && yActive) {
            // dragging a corner of a constrained subplot:
            // respect the fixed corner, but harmonize dx and dy
            var dxySign = ((xActive === 'w') === (yActive === 'n')) ? 1 : -1;
            var dxyFraction = (dx / pw + dxySign * dy / ph) / 2;
            dx = dxyFraction * pw;
            dy = dxySign * dxyFraction * ph;
        }

        if(xActive === 'w') dx = dz(xaxes, 0, dx);
        else if(xActive === 'e') dx = dz(xaxes, 1, -dx);
        else if(!xActive) dx = 0;

        if(yActive === 'n') dy = dz(yaxes, 1, dy);
        else if(yActive === 's') dy = dz(yaxes, 0, -dy);
        else if(!yActive) dy = 0;

        var x0 = (xActive === 'w') ? dx : 0;
        var y0 = (yActive === 'n') ? dy : 0;

        if(links.isSubplotConstrained) {
            var i;
            if(!xActive && yActive.length === 1) {
                // dragging one end of the y axis of a constrained subplot
                // scale the other axis the same about its middle
                for(i = 0; i < xaxes.length; i++) {
                    xaxes[i].range = xaxes[i]._r.slice();
                    scaleZoom(xaxes[i], 1 - dy / ph);
                }
                dx = dy * pw / ph;
                x0 = dx / 2;
            }
            if(!yActive && xActive.length === 1) {
                for(i = 0; i < yaxes.length; i++) {
                    yaxes[i].range = yaxes[i]._r.slice();
                    scaleZoom(yaxes[i], 1 - dx / pw);
                }
                dy = dx * ph / pw;
                y0 = dy / 2;
            }
        }

        updateMatchedAxRange('x');
        updateMatchedAxRange('y');
        updateSubplots([x0, y0, pw - dx, ph - dy]);
        ticksAndAnnotations();
    }

    function updateMatchedAxRange(axLetter, out) {
        var matchedAxes = matches.isSubplotConstrained ?
            {x: yaxes, y: xaxes}[axLetter] :
            matches[axLetter + 'axes'];

        var constrainedAxes = matches.isSubplotConstrained ?
            {x: xaxes, y: yaxes}[axLetter] :
            [];

        for(var i = 0; i < matchedAxes.length; i++) {
            var ax = matchedAxes[i];
            var axId = ax._id;
            var axId2 = matches.xLinks[axId] || matches.yLinks[axId];
            var ax2 = constrainedAxes[0] || xaHash[axId2] || yaHash[axId2];

            if(ax2) {
                var rng = ax2.range;
                if(out) {
                    out[ax._name + '.range[0]'] = rng[0];
                    out[ax._name + '.range[1]'] = rng[1];
                } else {
                    ax.range = rng;
                }
            }
        }
    }

    // Draw ticks and annotations (and other components) when ranges change.
    // Also records the ranges that have changed for use by update at the end.
    function ticksAndAnnotations() {
        var activeAxIds = [];
        var i;

        function pushActiveAxIds(axList) {
            for(i = 0; i < axList.length; i++) {
                if(!axList[i].fixedrange) activeAxIds.push(axList[i]._id);
            }
        }

        if(editX) {
            pushActiveAxIds(xaxes);
            pushActiveAxIds(links.xaxes);
            pushActiveAxIds(matches.xaxes);
        }
        if(editY) {
            pushActiveAxIds(yaxes);
            pushActiveAxIds(links.yaxes);
            pushActiveAxIds(matches.yaxes);
        }

        updates = {};
        for(i = 0; i < activeAxIds.length; i++) {
            var axId = activeAxIds[i];
            var ax = getFromId(gd, axId);
            Axes.drawOne(gd, ax, {skipTitle: true});
            updates[ax._name + '.range[0]'] = ax.range[0];
            updates[ax._name + '.range[1]'] = ax.range[1];
        }

        Axes.redrawComponents(gd, activeAxIds);
    }

    function doubleClick() {
        if(gd._transitioningWithDuration) return;

        var doubleClickConfig = gd._context.doubleClick;

        var axList = [];
        if(xActive) axList = axList.concat(xaxes);
        if(yActive) axList = axList.concat(yaxes);
        if(matches.xaxes) axList = axList.concat(matches.xaxes);
        if(matches.yaxes) axList = axList.concat(matches.yaxes);

        var attrs = {};
        var ax, i, rangeInitial;

        // For reset+autosize mode:
        // If *any* of the main axes is not at its initial range
        // (or autoranged, if we have no initial range, to match the logic in
        // doubleClickConfig === 'reset' below), we reset.
        // If they are *all* at their initial ranges, then we autosize.
        if(doubleClickConfig === 'reset+autosize') {

            doubleClickConfig = 'autosize';

            for(i = 0; i < axList.length; i++) {
                ax = axList[i];
                if((ax._rangeInitial && (
                        ax.range[0] !== ax._rangeInitial[0] ||
                        ax.range[1] !== ax._rangeInitial[1]
                    )) ||
                    (!ax._rangeInitial && !ax.autorange)
                ) {
                    doubleClickConfig = 'reset';
                    break;
                }
            }
        }

        if(doubleClickConfig === 'autosize') {
            // don't set the linked axes here, so relayout marks them as shrinkable
            // and we autosize just to the requested axis/axes
            for(i = 0; i < axList.length; i++) {
                ax = axList[i];
                if(!ax.fixedrange) attrs[ax._name + '.autorange'] = true;
            }
        }
        else if(doubleClickConfig === 'reset') {
            // when we're resetting, reset all linked axes too, so we get back
            // to the fully-auto-with-constraints situation
            if(xActive || links.isSubplotConstrained) axList = axList.concat(links.xaxes);
            if(yActive && !links.isSubplotConstrained) axList = axList.concat(links.yaxes);

            if(links.isSubplotConstrained) {
                if(!xActive) axList = axList.concat(xaxes);
                else if(!yActive) axList = axList.concat(yaxes);
            }

            for(i = 0; i < axList.length; i++) {
                ax = axList[i];

                if(!ax.fixedrange) {
                    if(!ax._rangeInitial) {
                        attrs[ax._name + '.autorange'] = true;
                    } else {
                        rangeInitial = ax._rangeInitial;
                        attrs[ax._name + '.range[0]'] = rangeInitial[0];
                        attrs[ax._name + '.range[1]'] = rangeInitial[1];
                    }
                }
            }
        }

        gd.emit('plotly_doubleclick', null);
        Registry.call('_guiRelayout', gd, attrs);
    }

    // dragTail - finish a drag event with a redraw
    function dragTail() {
        // put the subplot viewboxes back to default (Because we're going to)
        // be repositioning the data in the relayout. But DON'T call
        // ticksAndAnnotations again - it's unnecessary and would overwrite `updates`
        updateSubplots([0, 0, pw, ph]);

        // since we may have been redrawing some things during the drag, we may have
        // accumulated MathJax promises - wait for them before we relayout.
        Lib.syncOrAsync([
            Plots.previousPromises,
            function() {
                gd._fullLayout._replotting = false;
                Registry.call('_guiRelayout', gd, updates);
            }
        ], gd);
    }

    // updateSubplots - find all plot viewboxes that should be
    // affected by this drag, and update them. look for all plots
    // sharing an affected axis (including the one being dragged),
    // includes also scattergl and splom logic.
    function updateSubplots(viewBox) {
        var fullLayout = gd._fullLayout;
        var plotinfos = fullLayout._plots;
        var subplots = fullLayout._subplots.cartesian;
        var i, sp, xa, ya;

        if(hasSplom) {
            Registry.subplotsRegistry.splom.drag(gd);
        }

        if(hasScatterGl) {
            for(i = 0; i < subplots.length; i++) {
                sp = plotinfos[subplots[i]];
                xa = sp.xaxis;
                ya = sp.yaxis;

                if(sp._scene) {
                    var xrng = Lib.simpleMap(xa.range, xa.r2l);
                    var yrng = Lib.simpleMap(ya.range, ya.r2l);
                    sp._scene.update({range: [xrng[0], yrng[0], xrng[1], yrng[1]]});
                }
            }
        }

        if(hasSplom || hasScatterGl) {
            clearGlCanvases(gd);
            redrawReglTraces(gd);
        }

        if(hasSVG) {
            var xScaleFactor = viewBox[2] / xa0._length;
            var yScaleFactor = viewBox[3] / ya0._length;

            for(i = 0; i < subplots.length; i++) {
                sp = plotinfos[subplots[i]];
                xa = sp.xaxis;
                ya = sp.yaxis;

                var editX2 = editX && !xa.fixedrange && xaHash[xa._id];
                var editY2 = editY && !ya.fixedrange && yaHash[ya._id];

                var xScaleFactor2, yScaleFactor2;
                var clipDx, clipDy;

                if(editX2) {
                    xScaleFactor2 = xScaleFactor;
                    clipDx = ew ? viewBox[0] : getShift(xa, xScaleFactor2);
                } else if(matches.xaHash[xa._id]) {
                    xScaleFactor2 = xScaleFactor;
                    clipDx = viewBox[0] * xa._length / xa0._length;
                } else if(matches.yaHash[xa._id]) {
                    xScaleFactor2 = yScaleFactor;
                    clipDx = yActive === 'ns' ?
                        -viewBox[1] * xa._length / ya0._length :
                        getShift(xa, xScaleFactor2, {n: 'top', s: 'bottom'}[yActive]);
                } else {
                    xScaleFactor2 = getLinkedScaleFactor(xa, xScaleFactor, yScaleFactor);
                    clipDx = scaleAndGetShift(xa, xScaleFactor2);
                }

                if(editY2) {
                    yScaleFactor2 = yScaleFactor;
                    clipDy = ns ? viewBox[1] : getShift(ya, yScaleFactor2);
                } else if(matches.yaHash[ya._id]) {
                    yScaleFactor2 = yScaleFactor;
                    clipDy = viewBox[1] * ya._length / ya0._length;
                } else if(matches.xaHash[ya._id]) {
                    yScaleFactor2 = xScaleFactor;
                    clipDy = xActive === 'ew' ?
                        -viewBox[0] * ya._length / xa0._length :
                        getShift(ya, yScaleFactor2, {e: 'right', w: 'left'}[xActive]);
                } else {
                    yScaleFactor2 = getLinkedScaleFactor(ya, xScaleFactor, yScaleFactor);
                    clipDy = scaleAndGetShift(ya, yScaleFactor2);
                }

                // don't scale at all if neither axis is scalable here
                if(!xScaleFactor2 && !yScaleFactor2) {
                    continue;
                }

                // but if only one is, reset the other axis scaling
                if(!xScaleFactor2) xScaleFactor2 = 1;
                if(!yScaleFactor2) yScaleFactor2 = 1;

                var plotDx = xa._offset - clipDx / xScaleFactor2;
                var plotDy = ya._offset - clipDy / yScaleFactor2;

                // TODO could be more efficient here:
                // setTranslate and setScale do a lot of extra work
                // when working independently, should perhaps combine
                // them into a single routine.
                sp.clipRect
                    .call(Drawing.setTranslate, clipDx, clipDy)
                    .call(Drawing.setScale, xScaleFactor2, yScaleFactor2);

                sp.plot
                    .call(Drawing.setTranslate, plotDx, plotDy)
                    .call(Drawing.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2);

                // apply an inverse scale to individual points to counteract
                // the scale of the trace group.
                // apply only when scale changes, as adjusting the scale of
                // all the points can be expansive.
                if(xScaleFactor2 !== sp.xScaleFactor || yScaleFactor2 !== sp.yScaleFactor) {
                    Drawing.setPointGroupScale(sp.zoomScalePts, xScaleFactor2, yScaleFactor2);
                    Drawing.setTextPointsScale(sp.zoomScaleTxt, xScaleFactor2, yScaleFactor2);
                }

                Drawing.hideOutsideRangePoints(sp.clipOnAxisFalseTraces, sp);

                // update x/y scaleFactor stash
                sp.xScaleFactor = xScaleFactor2;
                sp.yScaleFactor = yScaleFactor2;
            }
        }
    }

    // Find the appropriate scaling for this axis, if it's linked to the
    // dragged axes by constraints. 0 is special, it means this axis shouldn't
    // ever be scaled (will be converted to 1 if the other axis is scaled)
    function getLinkedScaleFactor(ax, xScaleFactor, yScaleFactor) {
        if(ax.fixedrange) return 0;

        if(editX && links.xaHash[ax._id]) {
            return xScaleFactor;
        }
        if(editY && (links.isSubplotConstrained ? links.xaHash : links.yaHash)[ax._id]) {
            return yScaleFactor;
        }
        return 0;
    }

    function scaleAndGetShift(ax, scaleFactor) {
        if(scaleFactor) {
            ax.range = ax._r.slice();
            scaleZoom(ax, scaleFactor);
            return getShift(ax, scaleFactor);
        }
        return 0;
    }

    function getShift(ax, scaleFactor, from) {
        return ax._length * (1 - scaleFactor) * FROM_TL[from || ax.constraintoward || 'middle'];
    }

    return dragger;
}

function makeDragger(plotinfo, nodeName, dragClass, cursor) {
    var dragger3 = Lib.ensureSingle(plotinfo.draglayer, nodeName, dragClass, function(s) {
        s.classed('drag', true)
            .style({fill: 'transparent', 'stroke-width': 0})
            .attr('data-subplot', plotinfo.id);
    });

    dragger3.call(setCursor, cursor);

    return dragger3.node();
}

function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) {
    var dragger = makeDragger(plotinfo, 'rect', dragClass, cursor);
    d3.select(dragger).call(Drawing.setRect, x, y, w, h);
    return dragger;
}

function isDirectionActive(axList, activeVal) {
    for(var i = 0; i < axList.length; i++) {
        if(!axList[i].fixedrange) return activeVal;
    }
    return '';
}

function getEndText(ax, end) {
    var initialVal = ax.range[end];
    var diff = Math.abs(initialVal - ax.range[1 - end]);
    var dig;

    // TODO: this should basically be ax.r2d but we're doing extra
    // rounding here... can we clean up at all?
    if(ax.type === 'date') {
        return initialVal;
    }
    else if(ax.type === 'log') {
        dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3;
        return d3.format('.' + dig + 'g')(Math.pow(10, initialVal));
    }
    else { // linear numeric (or category... but just show numbers here)
        dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) -
            Math.floor(Math.log(diff) / Math.LN10) + 4;
        return d3.format('.' + String(dig) + 'g')(initialVal);
    }
}

function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) {
    for(var i = 0; i < axList.length; i++) {
        var axi = axList[i];
        if(axi.fixedrange) continue;

        var axRangeLinear0 = axi._rl[0];
        var axRangeLinearSpan = axi._rl[1] - axRangeLinear0;
        axi.range = [
            axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction),
            axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction)
        ];

        updates[axi._name + '.range[0]'] = axi.range[0];
        updates[axi._name + '.range[1]'] = axi.range[1];
    }

    // zoom linked axes about their centers
    if(linkedAxes && linkedAxes.length) {
        var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2;
        zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates, [], []);
    }
}

function dragAxList(axList, pix) {
    for(var i = 0; i < axList.length; i++) {
        var axi = axList[i];
        if(!axi.fixedrange) {
            axi.range = [
                axi.l2r(axi._rl[0] - pix / axi._m),
                axi.l2r(axi._rl[1] - pix / axi._m)
            ];
        }
    }
}

// common transform for dragging one end of an axis
// d>0 is compressing scale (cursor is over the plot,
//  the axis end should move with the cursor)
// d<0 is expanding (cursor is off the plot, axis end moves
//  nonlinearly so you can expand far)
function dZoom(d) {
    return 1 - ((d >= 0) ? Math.min(d, 0.9) :
        1 / (1 / Math.max(d, -0.3) + 3.222));
}

function getDragCursor(nsew, dragmode, isMainDrag) {
    if(!nsew) return 'pointer';
    if(nsew === 'nsew') {
        // in this case here, clear cursor and
        // use the cursor style set on <g .draglayer>
        if(isMainDrag) return '';
        if(dragmode === 'pan') return 'move';
        return 'crosshair';
    }
    return nsew.toLowerCase() + '-resize';
}

function makeZoombox(zoomlayer, lum, xs, ys, path0) {
    return zoomlayer.append('path')
        .attr('class', 'zoombox')
        .style({
            'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)',
            'stroke-width': 0
        })
        .attr('transform', 'translate(' + xs + ', ' + ys + ')')
        .attr('d', path0 + 'Z');
}

function makeCorners(zoomlayer, xs, ys) {
    return zoomlayer.append('path')
        .attr('class', 'zoombox-corners')
        .style({
            fill: Color.background,
            stroke: Color.defaultLine,
            'stroke-width': 1,
            opacity: 0
        })
        .attr('transform', 'translate(' + xs + ', ' + ys + ')')
        .attr('d', 'M0,0Z');
}

function updateZoombox(zb, corners, box, path0, dimmed, lum) {
    zb.attr('d',
        path0 + 'M' + (box.l) + ',' + (box.t) + 'v' + (box.h) +
        'h' + (box.w) + 'v-' + (box.h) + 'h-' + (box.w) + 'Z');
    transitionZoombox(zb, corners, dimmed, lum);
}

function transitionZoombox(zb, corners, dimmed, lum) {
    if(!dimmed) {
        zb.transition()
            .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' :
                'rgba(255,255,255,0.3)')
            .duration(200);
        corners.transition()
            .style('opacity', 1)
            .duration(200);
    }
}

function removeZoombox(gd) {
    d3.select(gd)
        .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners')
        .remove();
}

function showDoubleClickNotifier(gd) {
    if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) {
        Lib.notifier(Lib._(gd, 'Double-click to zoom back out'), 'long');
        SHOWZOOMOUTTIP = false;
    }
}

function isSelectOrLasso(dragmode) {
    return dragmode === 'lasso' || dragmode === 'select';
}

function xCorners(box, y0) {
    return 'M' +
        (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) +
        'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' +
        (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) +
        'h3v' + (2 * MINZOOM + 1) + 'h-3Z';
}

function yCorners(box, x0) {
    return 'M' +
        (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) +
        'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' +
        (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) +
        'v3h' + (2 * MINZOOM + 1) + 'v-3Z';
}

function xyCorners(box) {
    var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2);
    return 'M' +
        (box.l - 3.5) + ',' + (box.t - 0.5 + clen) + 'h3v' + (-clen) +
            'h' + clen + 'v-3h-' + (clen + 3) + 'ZM' +
        (box.r + 3.5) + ',' + (box.t - 0.5 + clen) + 'h-3v' + (-clen) +
            'h' + (-clen) + 'v-3h' + (clen + 3) + 'ZM' +
        (box.r + 3.5) + ',' + (box.b + 0.5 - clen) + 'h-3v' + clen +
            'h' + (-clen) + 'v3h' + (clen + 3) + 'ZM' +
        (box.l - 3.5) + ',' + (box.b + 0.5 - clen) + 'h3v' + clen +
            'h' + clen + 'v3h-' + (clen + 3) + 'Z';
}

function calcLinks(gd, groups, xaHash, yaHash) {
    var isSubplotConstrained = false;
    var xLinks = {};
    var yLinks = {};
    var xID, yID, xLinkID, yLinkID;

    for(var i = 0; i < groups.length; i++) {
        var group = groups[i];
        // check if any of the x axes we're dragging is in this constraint group
        for(xID in xaHash) {
            if(group[xID]) {
                // put the rest of these axes into xLinks, if we're not already
                // dragging them, so we know to scale these axes automatically too
                // to match the changes in the dragged x axes
                for(xLinkID in group) {
                    if(!(xLinkID.charAt(0) === 'x' ? xaHash : yaHash)[xLinkID]) {
                        xLinks[xLinkID] = xID;
                    }
                }

                // check if the x and y axes of THIS drag are linked
                for(yID in yaHash) {
                    if(group[yID]) isSubplotConstrained = true;
                }
            }
        }

        // now check if any of the y axes we're dragging is in this constraint group
        // only look for outside links, as we've already checked for links within the dragger
        for(yID in yaHash) {
            if(group[yID]) {
                for(yLinkID in group) {
                    if(!(yLinkID.charAt(0) === 'x' ? xaHash : yaHash)[yLinkID]) {
                        yLinks[yLinkID] = yID;
                    }
                }
            }
        }
    }

    if(isSubplotConstrained) {
        // merge xLinks and yLinks if the subplot is constrained,
        // since we'll always apply both anyway and the two will contain
        // duplicates
        Lib.extendFlat(xLinks, yLinks);
        yLinks = {};
    }

    var xaHashLinked = {};
    var xaxesLinked = [];
    for(xLinkID in xLinks) {
        var xa = getFromId(gd, xLinkID);
        xaxesLinked.push(xa);
        xaHashLinked[xa._id] = xa;
    }

    var yaHashLinked = {};
    var yaxesLinked = [];
    for(yLinkID in yLinks) {
        var ya = getFromId(gd, yLinkID);
        yaxesLinked.push(ya);
        yaHashLinked[ya._id] = ya;
    }

    return {
        xaHash: xaHashLinked,
        yaHash: yaHashLinked,
        xaxes: xaxesLinked,
        yaxes: yaxesLinked,
        xLinks: xLinks,
        yLinks: yLinks,
        isSubplotConstrained: isSubplotConstrained
    };
}

// still seems to be some confusion about onwheel vs onmousewheel...
function attachWheelEventHandler(element, handler) {
    if(!supportsPassive) {
        if(element.onwheel !== undefined) element.onwheel = handler;
        else if(element.onmousewheel !== undefined) element.onmousewheel = handler;
    }
    else {
        var wheelEventName = element.onwheel !== undefined ? 'wheel' : 'mousewheel';

        if(element._onwheel) {
            element.removeEventListener(wheelEventName, element._onwheel);
        }
        element._onwheel = handler;

        element.addEventListener(wheelEventName, handler, {passive: false});
    }
}

function hashValues(hash) {
    var out = [];
    for(var k in hash) out.push(hash[k]);
    return out;
}

module.exports = {
    makeDragBox: makeDragBox,

    makeDragger: makeDragger,
    makeRectDragger: makeRectDragger,
    makeZoombox: makeZoombox,
    makeCorners: makeCorners,

    updateZoombox: updateZoombox,
    xyCorners: xyCorners,
    transitionZoombox: transitionZoombox,
    removeZoombox: removeZoombox,
    showDoubleClickNotifier: showDoubleClickNotifier,

    attachWheelEventHandler: attachWheelEventHandler
};

},{"../../components/color":574,"../../components/dragelement":592,"../../components/drawing":595,"../../components/fx":613,"../../constants/alignment":669,"../../lib":697,"../../lib/clear_gl_canvases":682,"../../lib/setcursor":717,"../../lib/svg_text_utils":721,"../../plot_api/subroutines":736,"../../registry":826,"../plots":807,"./axes":745,"./axis_ids":748,"./constants":751,"./scale_zoom":761,"./select":762,"d3":151,"has-passive-events":400,"tinycolor2":518}],754:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

var Fx = _dereq_('../../components/fx');
var dragElement = _dereq_('../../components/dragelement');
var setCursor = _dereq_('../../lib/setcursor');

var makeDragBox = _dereq_('./dragbox').makeDragBox;
var DRAGGERSIZE = _dereq_('./constants').DRAGGERSIZE;

exports.initInteractions = function initInteractions(gd) {
    var fullLayout = gd._fullLayout;

    if(gd._context.staticPlot) {
        // this sweeps up more than just cartesian drag elements...
        d3.select(gd).selectAll('.drag').remove();
        return;
    }

    if(!fullLayout._has('cartesian') && !fullLayout._has('splom')) return;

    var subplots = Object.keys(fullLayout._plots || {}).sort(function(a, b) {
        // sort overlays last, then by x axis number, then y axis number
        if((fullLayout._plots[a].mainplot && true) ===
            (fullLayout._plots[b].mainplot && true)) {
            var aParts = a.split('y');
            var bParts = b.split('y');
            return (aParts[0] === bParts[0]) ?
                (Number(aParts[1] || 1) - Number(bParts[1] || 1)) :
                (Number(aParts[0] || 1) - Number(bParts[0] || 1));
        }
        return fullLayout._plots[a].mainplot ? 1 : -1;
    });

    subplots.forEach(function(subplot) {
        var plotinfo = fullLayout._plots[subplot];
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;

        // main and corner draggers need not be repeated for
        // overlaid subplots - these draggers drag them all
        if(!plotinfo.mainplot) {
            // main dragger goes over the grids and data, so we use its
            // mousemove events for all data hover effects
            var maindrag = makeDragBox(gd, plotinfo, xa._offset, ya._offset,
                xa._length, ya._length, 'ns', 'ew');

            maindrag.onmousemove = function(evt) {
                // This is on `gd._fullLayout`, *not* fullLayout because the reference
                // changes by the time this is called again.
                gd._fullLayout._rehover = function() {
                    if(gd._fullLayout._hoversubplot === subplot) {
                        Fx.hover(gd, evt, subplot);
                    }
                };

                Fx.hover(gd, evt, subplot);

                // Note that we have *not* used the cached fullLayout variable here
                // since that may be outdated when this is called as a callback later on
                gd._fullLayout._lasthover = maindrag;
                gd._fullLayout._hoversubplot = subplot;
            };

            /*
             * IMPORTANT:
             * We must check for the presence of the drag cover here.
             * If we don't, a 'mouseout' event is triggered on the
             * maindrag before each 'click' event, which has the effect
             * of clearing the hoverdata; thus, cancelling the click event.
             */
            maindrag.onmouseout = function(evt) {
                if(gd._dragging) return;

                // When the mouse leaves this maindrag, unset the hovered subplot.
                // This may cause problems if it leaves the subplot directly *onto*
                // another subplot, but that's a tiny corner case at the moment.
                gd._fullLayout._hoversubplot = null;

                dragElement.unhover(gd, evt);
            };

            // corner draggers
            if(gd._context.showAxisDragHandles) {
                makeDragBox(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE,
                    DRAGGERSIZE, DRAGGERSIZE, 'n', 'w');
                makeDragBox(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE,
                    DRAGGERSIZE, DRAGGERSIZE, 'n', 'e');
                makeDragBox(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length,
                    DRAGGERSIZE, DRAGGERSIZE, 's', 'w');
                makeDragBox(gd, plotinfo, xa._offset + xa._length, ya._offset + ya._length,
                    DRAGGERSIZE, DRAGGERSIZE, 's', 'e');
            }
        }
        if(gd._context.showAxisDragHandles) {
            // x axis draggers - if you have overlaid plots,
            // these drag each axis separately
            if(subplot === xa._mainSubplot) {
                // the y position of the main x axis line
                var y0 = xa._mainLinePosition;
                if(xa.side === 'top') y0 -= DRAGGERSIZE;
                makeDragBox(gd, plotinfo, xa._offset + xa._length * 0.1, y0,
                    xa._length * 0.8, DRAGGERSIZE, '', 'ew');
                makeDragBox(gd, plotinfo, xa._offset, y0,
                    xa._length * 0.1, DRAGGERSIZE, '', 'w');
                makeDragBox(gd, plotinfo, xa._offset + xa._length * 0.9, y0,
                    xa._length * 0.1, DRAGGERSIZE, '', 'e');
            }
            // y axis draggers
            if(subplot === ya._mainSubplot) {
                // the x position of the main y axis line
                var x0 = ya._mainLinePosition;
                if(ya.side !== 'right') x0 -= DRAGGERSIZE;
                makeDragBox(gd, plotinfo, x0, ya._offset + ya._length * 0.1,
                    DRAGGERSIZE, ya._length * 0.8, 'ns', '');
                makeDragBox(gd, plotinfo, x0, ya._offset + ya._length * 0.9,
                    DRAGGERSIZE, ya._length * 0.1, 's', '');
                makeDragBox(gd, plotinfo, x0, ya._offset,
                    DRAGGERSIZE, ya._length * 0.1, 'n', '');
            }
        }
    });

    // In case you mousemove over some hovertext, send it to Fx.hover too
    // we do this so that we can put the hover text in front of everything,
    // but still be able to interact with everything as if it isn't there
    var hoverLayer = fullLayout._hoverlayer.node();

    hoverLayer.onmousemove = function(evt) {
        evt.target = gd._fullLayout._lasthover;
        Fx.hover(gd, evt, fullLayout._hoversubplot);
    };

    hoverLayer.onclick = function(evt) {
        evt.target = gd._fullLayout._lasthover;
        Fx.click(gd, evt);
    };

    // also delegate mousedowns... TODO: does this actually work?
    hoverLayer.onmousedown = function(evt) {
        gd._fullLayout._lasthover.onmousedown(evt);
    };

    exports.updateFx(gd);
};

// Minimal set of update needed on 'modebar' edits.
// We only need to update the <g .draglayer> cursor style.
//
// Note that changing the axis configuration and/or the fixedrange attribute
// should trigger a full initInteractions.
exports.updateFx = function(gd) {
    var fullLayout = gd._fullLayout;
    var cursor = fullLayout.dragmode === 'pan' ? 'move' : 'crosshair';
    setCursor(fullLayout._draggers, cursor);
};

},{"../../components/dragelement":592,"../../components/fx":613,"../../lib/setcursor":717,"./constants":751,"./dragbox":753,"d3":151}],755:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');

/**
 * Factory function for checking component arrays for subplot references.
 *
 * @param {string} containerArrayName: the top-level array in gd.layout to check
 *   If an item in this container is found that references a cartesian x and/or y axis,
 *   ensure cartesian is marked as a base plot module and record the axes (and subplot
 *   if both refs are axes) in gd._fullLayout
 *
 * @return {function}: with args layoutIn (gd.layout) and layoutOut (gd._fullLayout)
 * as expected of a component includeBasePlot method
 */
module.exports = function makeIncludeComponents(containerArrayName) {
    return function includeComponents(layoutIn, layoutOut) {
        var array = layoutIn[containerArrayName];
        if(!Array.isArray(array)) return;

        var Cartesian = Registry.subplotsRegistry.cartesian;
        var idRegex = Cartesian.idRegex;
        var subplots = layoutOut._subplots;
        var xaList = subplots.xaxis;
        var yaList = subplots.yaxis;
        var cartesianList = subplots.cartesian;
        var hasCartesianOrGL2D = layoutOut._has('cartesian') || layoutOut._has('gl2d');

        for(var i = 0; i < array.length; i++) {
            var itemi = array[i];
            if(!Lib.isPlainObject(itemi)) continue;

            var xref = itemi.xref;
            var yref = itemi.yref;

            var hasXref = idRegex.x.test(xref);
            var hasYref = idRegex.y.test(yref);
            if(hasXref || hasYref) {
                if(!hasCartesianOrGL2D) Lib.pushUnique(layoutOut._basePlotModules, Cartesian);

                var newAxis = false;
                if(hasXref && xaList.indexOf(xref) === -1) {
                    xaList.push(xref);
                    newAxis = true;
                }
                if(hasYref && yaList.indexOf(yref) === -1) {
                    yaList.push(yref);
                    newAxis = true;
                }

                /*
                 * Notice the logic here: only add a subplot for a component if
                 * it's referencing both x and y axes AND it's creating a new axis
                 * so for example if your plot already has xy and x2y2, an annotation
                 * on x2y or xy2 will not create a new subplot.
                 */
                if(newAxis && hasXref && hasYref) {
                    cartesianList.push(xref + yref);
                }
            }
        }
    };
};

},{"../../lib":697,"../../registry":826}],756:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Plots = _dereq_('../plots');
var Drawing = _dereq_('../../components/drawing');

var getModuleCalcData = _dereq_('../get_data').getModuleCalcData;
var axisIds = _dereq_('./axis_ids');
var constants = _dereq_('./constants');
var xmlnsNamespaces = _dereq_('../../constants/xmlns_namespaces');

var ensureSingle = Lib.ensureSingle;

function ensureSingleAndAddDatum(parent, nodeType, className) {
    return Lib.ensureSingle(parent, nodeType, className, function(s) {
        s.datum(className);
    });
}

exports.name = 'cartesian';

exports.attr = ['xaxis', 'yaxis'];

exports.idRoot = ['x', 'y'];

exports.idRegex = constants.idRegex;

exports.attrRegex = constants.attrRegex;

exports.attributes = _dereq_('./attributes');

exports.layoutAttributes = _dereq_('./layout_attributes');

exports.supplyLayoutDefaults = _dereq_('./layout_defaults');

exports.transitionAxes = _dereq_('./transition_axes');

exports.finalizeSubplots = function(layoutIn, layoutOut) {
    var subplots = layoutOut._subplots;
    var xList = subplots.xaxis;
    var yList = subplots.yaxis;
    var spSVG = subplots.cartesian;
    var spAll = spSVG.concat(subplots.gl2d || []);
    var allX = {};
    var allY = {};
    var i, xi, yi;

    for(i = 0; i < spAll.length; i++) {
        var parts = spAll[i].split('y');
        allX[parts[0]] = 1;
        allY['y' + parts[1]] = 1;
    }

    // check for x axes with no subplot, and make one from the anchor of that x axis
    for(i = 0; i < xList.length; i++) {
        xi = xList[i];
        if(!allX[xi]) {
            yi = (layoutIn[axisIds.id2name(xi)] || {}).anchor;
            if(!constants.idRegex.y.test(yi)) yi = 'y';
            spSVG.push(xi + yi);
            spAll.push(xi + yi);

            if(!allY[yi]) {
                allY[yi] = 1;
                Lib.pushUnique(yList, yi);
            }
        }
    }

    // same for y axes with no subplot
    for(i = 0; i < yList.length; i++) {
        yi = yList[i];
        if(!allY[yi]) {
            xi = (layoutIn[axisIds.id2name(yi)] || {}).anchor;
            if(!constants.idRegex.x.test(xi)) xi = 'x';
            spSVG.push(xi + yi);
            spAll.push(xi + yi);

            if(!allX[xi]) {
                allX[xi] = 1;
                Lib.pushUnique(xList, xi);
            }
        }
    }

    // finally, if we've gotten here we're supposed to show cartesian...
    // so if there are NO subplots at all, make one from the first
    // x & y axes in the input layout
    if(!spAll.length) {
        xi = '';
        yi = '';
        for(var ki in layoutIn) {
            if(constants.attrRegex.test(ki)) {
                var axLetter = ki.charAt(0);
                if(axLetter === 'x') {
                    if(!xi || (+ki.substr(5) < +xi.substr(5))) {
                        xi = ki;
                    }
                }
                else if(!yi || (+ki.substr(5) < +yi.substr(5))) {
                    yi = ki;
                }
            }
        }
        xi = xi ? axisIds.name2id(xi) : 'x';
        yi = yi ? axisIds.name2id(yi) : 'y';
        xList.push(xi);
        yList.push(yi);
        spSVG.push(xi + yi);
    }
};

/**
 * Cartesian.plot
 *
 * @param {DOM div | object} gd
 * @param {array | null} (optional) traces
 *  array of traces indices to plot
 *  if undefined, plots all cartesian traces,
 *  if null, plots no traces
 * @param {object} (optional) transitionOpts
 *  transition option object
 * @param {function} (optional) makeOnCompleteCallback
 *  transition make callback function from Plots.transition
 */
exports.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) {
    var fullLayout = gd._fullLayout;
    var subplots = fullLayout._subplots.cartesian;
    var calcdata = gd.calcdata;
    var i;

    if(traces === null) {
        // this means no updates required, must return here
        // so that plotOne doesn't remove the trace layers
        return;
    } else if(!Array.isArray(traces)) {
        // If traces is not provided, then it's a complete replot and missing
        // traces are removed
        traces = [];
        for(i = 0; i < calcdata.length; i++) traces.push(i);
    }

    for(i = 0; i < subplots.length; i++) {
        var subplot = subplots[i];
        var subplotInfo = fullLayout._plots[subplot];

        // Get all calcdata for this subplot:
        var cdSubplot = [];
        var pcd;

        for(var j = 0; j < calcdata.length; j++) {
            var cd = calcdata[j];
            var trace = cd[0].trace;

            // Skip trace if whitelist provided and it's not whitelisted:
            // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue;
            if(trace.xaxis + trace.yaxis === subplot) {
                // XXX: Should trace carpet dependencies. Only replot all carpet plots if the carpet
                // axis has actually changed:
                //
                // If this trace is specifically requested, add it to the list:
                if(traces.indexOf(trace.index) !== -1 || trace.carpet) {
                    // Okay, so example: traces 0, 1, and 2 have fill = tonext. You animate
                    // traces 0 and 2. Trace 1 also needs to be updated, otherwise its fill
                    // is outdated. So this retroactively adds the previous trace if the
                    // traces are interdependent.
                    if(
                        pcd &&
                        pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot &&
                        ['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1 &&
                        cdSubplot.indexOf(pcd) === -1
                    ) {
                        cdSubplot.push(pcd);
                    }

                    cdSubplot.push(cd);
                }

                // Track the previous trace on this subplot for the retroactive-add step
                // above:
                pcd = cd;
            }
        }

        plotOne(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback);
    }
};

function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) {
    var traceLayerClasses = constants.traceLayerClasses;
    var fullLayout = gd._fullLayout;
    var modules = fullLayout._modules;
    var _module, cdModuleAndOthers, cdModule;

    var layerData = [];
    var zoomScaleQueryParts = [];

    for(var i = 0; i < modules.length; i++) {
        _module = modules[i];
        var name = _module.name;
        var categories = Registry.modules[name].categories;

        if(categories.svg) {
            var className = (_module.layerName || name + 'layer');
            var plotMethod = _module.plot;

            // plot all visible traces of this type on this subplot at once
            cdModuleAndOthers = getModuleCalcData(cdSubplot, plotMethod);
            cdModule = cdModuleAndOthers[0];
            // don't need to search the found traces again - in fact we need to NOT
            // so that if two modules share the same plotter we don't double-plot
            cdSubplot = cdModuleAndOthers[1];

            if(cdModule.length) {
                layerData.push({
                    i: traceLayerClasses.indexOf(className),
                    className: className,
                    plotMethod: plotMethod,
                    cdModule: cdModule
                });
            }

            if(categories.zoomScale) {
                zoomScaleQueryParts.push('.' + className);
            }
        }
    }

    layerData.sort(function(a, b) { return a.i - b.i; });

    var layers = plotinfo.plot.selectAll('g.mlayer')
        .data(layerData, function(d) { return d.className; });

    layers.enter().append('g')
        .attr('class', function(d) { return d.className; })
        .classed('mlayer', true);

    layers.exit().remove();

    layers.order();

    layers.each(function(d) {
        var sel = d3.select(this);
        var className = d.className;

        d.plotMethod(
            gd, plotinfo, d.cdModule, sel,
            transitionOpts, makeOnCompleteCallback
        );

        // layers that allow `cliponaxis: false`
        if(className !== 'scatterlayer' && className !== 'barlayer') {
            Drawing.setClipUrl(sel, plotinfo.layerClipId, gd);
        }
    });

    // call Scattergl.plot separately
    if(fullLayout._has('scattergl')) {
        _module = Registry.getModule('scattergl');
        cdModule = getModuleCalcData(cdSubplot, _module)[0];
        _module.plot(gd, plotinfo, cdModule);
    }

    // stash "hot" selections for faster interaction on drag and scroll
    if(!gd._context.staticPlot) {
        if(plotinfo._hasClipOnAxisFalse) {
            plotinfo.clipOnAxisFalseTraces = plotinfo.plot
                .selectAll('.scatterlayer, .barlayer')
                .selectAll('.trace');
        }

        if(zoomScaleQueryParts.length) {
            var traces = plotinfo.plot
                .selectAll(zoomScaleQueryParts.join(','))
                .selectAll('.trace');

            plotinfo.zoomScalePts = traces.selectAll('path.point');
            plotinfo.zoomScaleTxt = traces.selectAll('.textpoint');
        }
    }
}

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var oldPlots = oldFullLayout._plots || {};
    var newPlots = newFullLayout._plots || {};
    var oldSubplotList = oldFullLayout._subplots || {};
    var plotinfo;
    var i, k;

    // when going from a large splom graph to something else,
    // we need to clear <g subplot> so that the new cartesian subplot
    // can have the correct layer ordering
    if(oldFullLayout._hasOnlyLargeSploms && !newFullLayout._hasOnlyLargeSploms) {
        for(k in oldPlots) {
            plotinfo = oldPlots[k];
            if(plotinfo.plotgroup) plotinfo.plotgroup.remove();
        }
    }

    var hadGl = (oldFullLayout._has && oldFullLayout._has('gl'));
    var hasGl = (newFullLayout._has && newFullLayout._has('gl'));

    if(hadGl && !hasGl) {
        for(k in oldPlots) {
            plotinfo = oldPlots[k];
            if(plotinfo._scene) plotinfo._scene.destroy();
        }
    }

    // delete any titles we don't need anymore
    // check if axis list has changed, and if so clear old titles
    if(oldSubplotList.xaxis && oldSubplotList.yaxis) {
        var oldAxIDs = axisIds.listIds({_fullLayout: oldFullLayout});
        for(i = 0; i < oldAxIDs.length; i++) {
            var oldAxId = oldAxIDs[i];
            if(!newFullLayout[axisIds.id2name(oldAxId)]) {
                oldFullLayout._infolayer.selectAll('.g-' + oldAxId + 'title').remove();
            }
        }
    }

    // if we've gotten rid of all cartesian traces, remove all the subplot svg items
    var hadCartesian = (oldFullLayout._has && oldFullLayout._has('cartesian'));
    var hasCartesian = (newFullLayout._has && newFullLayout._has('cartesian'));

    if(hadCartesian && !hasCartesian) {
        purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll('.subplot'), oldFullLayout);
        oldFullLayout._defs.selectAll('.axesclip').remove();
        delete oldFullLayout._axisConstraintGroups;
    }
    // otherwise look for subplots we need to remove
    else if(oldSubplotList.cartesian) {
        for(i = 0; i < oldSubplotList.cartesian.length; i++) {
            var oldSubplotId = oldSubplotList.cartesian[i];
            if(!newPlots[oldSubplotId]) {
                var selector = '.' + oldSubplotId + ',.' + oldSubplotId + '-x,.' + oldSubplotId + '-y';
                oldFullLayout._cartesianlayer.selectAll(selector).remove();
                removeSubplotExtras(oldSubplotId, oldFullLayout);
            }
        }
    }
};

exports.drawFramework = function(gd) {
    var fullLayout = gd._fullLayout;
    var subplotData = makeSubplotData(gd);

    var subplotLayers = fullLayout._cartesianlayer.selectAll('.subplot')
        .data(subplotData, String);

    subplotLayers.enter().append('g')
        .attr('class', function(d) { return 'subplot ' + d[0]; });

    subplotLayers.order();

    subplotLayers.exit()
        .call(purgeSubplotLayers, fullLayout);

    subplotLayers.each(function(d) {
        var id = d[0];
        var plotinfo = fullLayout._plots[id];

        plotinfo.plotgroup = d3.select(this);
        makeSubplotLayer(gd, plotinfo);

        // make separate drag layers for each subplot,
        // but append them to paper rather than the plot groups,
        // so they end up on top of the rest
        plotinfo.draglayer = ensureSingle(fullLayout._draggers, 'g', id);
    });
};

exports.rangePlot = function(gd, plotinfo, cdSubplot) {
    makeSubplotLayer(gd, plotinfo);
    plotOne(gd, plotinfo, cdSubplot);
    Plots.style(gd);
};

function makeSubplotData(gd) {
    var fullLayout = gd._fullLayout;
    var ids = fullLayout._subplots.cartesian;
    var len = ids.length;
    var i, j, id, plotinfo, xa, ya;

    // split 'regular' and 'overlaying' subplots
    var regulars = [];
    var overlays = [];

    for(i = 0; i < len; i++) {
        id = ids[i];
        plotinfo = fullLayout._plots[id];
        xa = plotinfo.xaxis;
        ya = plotinfo.yaxis;

        var xa2 = xa._mainAxis;
        var ya2 = ya._mainAxis;
        var mainplot = xa2._id + ya2._id;
        var mainplotinfo = fullLayout._plots[mainplot];
        plotinfo.overlays = [];

        if(mainplot !== id && mainplotinfo) {
            plotinfo.mainplot = mainplot;
            plotinfo.mainplotinfo = mainplotinfo;
            overlays.push(id);
        } else {
            plotinfo.mainplot = undefined;
            plotinfo.mainPlotinfo = undefined;
            regulars.push(id);
        }
    }

    // fill in list of overlaying subplots in 'main plot'
    for(i = 0; i < overlays.length; i++) {
        id = overlays[i];
        plotinfo = fullLayout._plots[id];
        plotinfo.mainplotinfo.overlays.push(plotinfo);
    }

    // put 'regular' subplot data before 'overlaying'
    var subplotIds = regulars.concat(overlays);
    var subplotData = new Array(len);

    for(i = 0; i < len; i++) {
        id = subplotIds[i];
        plotinfo = fullLayout._plots[id];
        xa = plotinfo.xaxis;
        ya = plotinfo.yaxis;

        // use info about axis layer and overlaying pattern
        // to clean what need to be cleaned up in exit selection
        var d = [id, xa.layer, ya.layer, xa.overlaying || '', ya.overlaying || ''];
        for(j = 0; j < plotinfo.overlays.length; j++) {
            d.push(plotinfo.overlays[j].id);
        }
        subplotData[i] = d;
    }

    return subplotData;
}

function makeSubplotLayer(gd, plotinfo) {
    var plotgroup = plotinfo.plotgroup;
    var id = plotinfo.id;
    var xLayer = constants.layerValue2layerClass[plotinfo.xaxis.layer];
    var yLayer = constants.layerValue2layerClass[plotinfo.yaxis.layer];
    var hasOnlyLargeSploms = gd._fullLayout._hasOnlyLargeSploms;

    if(!plotinfo.mainplot) {
        if(hasOnlyLargeSploms) {
            // TODO could do even better
            // - we don't need plot (but we would have to mock it in lsInner
            //   and other places
            // - we don't (x|y)lines and (x|y)axislayer for most subplots
            //   usually just the bottom x and left y axes.
            plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above');
            plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above');
            plotinfo.xaxislayer = ensureSingle(plotgroup, 'g', 'xaxislayer-above');
            plotinfo.yaxislayer = ensureSingle(plotgroup, 'g', 'yaxislayer-above');
        }
        else {
            var backLayer = ensureSingle(plotgroup, 'g', 'layer-subplot');
            plotinfo.shapelayer = ensureSingle(backLayer, 'g', 'shapelayer');
            plotinfo.imagelayer = ensureSingle(backLayer, 'g', 'imagelayer');

            plotinfo.gridlayer = ensureSingle(plotgroup, 'g', 'gridlayer');
            plotinfo.zerolinelayer = ensureSingle(plotgroup, 'g', 'zerolinelayer');

            ensureSingle(plotgroup, 'path', 'xlines-below');
            ensureSingle(plotgroup, 'path', 'ylines-below');
            plotinfo.overlinesBelow = ensureSingle(plotgroup, 'g', 'overlines-below');

            ensureSingle(plotgroup, 'g', 'xaxislayer-below');
            ensureSingle(plotgroup, 'g', 'yaxislayer-below');
            plotinfo.overaxesBelow = ensureSingle(plotgroup, 'g', 'overaxes-below');

            plotinfo.plot = ensureSingle(plotgroup, 'g', 'plot');
            plotinfo.overplot = ensureSingle(plotgroup, 'g', 'overplot');

            plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above');
            plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above');
            plotinfo.overlinesAbove = ensureSingle(plotgroup, 'g', 'overlines-above');

            ensureSingle(plotgroup, 'g', 'xaxislayer-above');
            ensureSingle(plotgroup, 'g', 'yaxislayer-above');
            plotinfo.overaxesAbove = ensureSingle(plotgroup, 'g', 'overaxes-above');

            // set refs to correct layers as determined by 'axis.layer'
            plotinfo.xlines = plotgroup.select('.xlines-' + xLayer);
            plotinfo.ylines = plotgroup.select('.ylines-' + yLayer);
            plotinfo.xaxislayer = plotgroup.select('.xaxislayer-' + xLayer);
            plotinfo.yaxislayer = plotgroup.select('.yaxislayer-' + yLayer);
        }
    }
    else {
        var mainplotinfo = plotinfo.mainplotinfo;
        var mainplotgroup = mainplotinfo.plotgroup;
        var xId = id + '-x';
        var yId = id + '-y';

        // now make the components of overlaid subplots
        // overlays don't have backgrounds, and append all
        // their other components to the corresponding
        // extra groups of their main plots.

        plotinfo.gridlayer = mainplotinfo.gridlayer;
        plotinfo.zerolinelayer = mainplotinfo.zerolinelayer;

        ensureSingle(mainplotinfo.overlinesBelow, 'path', xId);
        ensureSingle(mainplotinfo.overlinesBelow, 'path', yId);
        ensureSingle(mainplotinfo.overaxesBelow, 'g', xId);
        ensureSingle(mainplotinfo.overaxesBelow, 'g', yId);

        plotinfo.plot = ensureSingle(mainplotinfo.overplot, 'g', id);

        ensureSingle(mainplotinfo.overlinesAbove, 'path', xId);
        ensureSingle(mainplotinfo.overlinesAbove, 'path', yId);
        ensureSingle(mainplotinfo.overaxesAbove, 'g', xId);
        ensureSingle(mainplotinfo.overaxesAbove, 'g', yId);

        // set refs to correct layers as determined by 'abovetraces'
        plotinfo.xlines = mainplotgroup.select('.overlines-' + xLayer).select('.' + xId);
        plotinfo.ylines = mainplotgroup.select('.overlines-' + yLayer).select('.' + yId);
        plotinfo.xaxislayer = mainplotgroup.select('.overaxes-' + xLayer).select('.' + xId);
        plotinfo.yaxislayer = mainplotgroup.select('.overaxes-' + yLayer).select('.' + yId);
    }

    // common attributes for all subplots, overlays or not

    if(!hasOnlyLargeSploms) {
        ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.xaxis._id);
        ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.yaxis._id);
        plotinfo.gridlayer.selectAll('g')
            .map(function(d) { return d[0]; })
            .sort(axisIds.idSort);
    }

    plotinfo.xlines
        .style('fill', 'none')
        .classed('crisp', true);

    plotinfo.ylines
        .style('fill', 'none')
        .classed('crisp', true);
}

function purgeSubplotLayers(layers, fullLayout) {
    if(!layers) return;

    var overlayIdsToRemove = {};

    layers.each(function(d) {
        var id = d[0];
        var plotgroup = d3.select(this);

        plotgroup.remove();
        removeSubplotExtras(id, fullLayout);
        overlayIdsToRemove[id] = true;

        // do not remove individual axis <clipPath>s here
        // as other subplots may need them
    });

    // must remove overlaid subplot trace layers 'manually'

    for(var k in fullLayout._plots) {
        var subplotInfo = fullLayout._plots[k];
        var overlays = subplotInfo.overlays || [];

        for(var j = 0; j < overlays.length; j++) {
            var overlayInfo = overlays[j];

            if(overlayIdsToRemove[overlayInfo.id]) {
                overlayInfo.plot.selectAll('.trace').remove();
            }
        }
    }
}

function removeSubplotExtras(subplotId, fullLayout) {
    fullLayout._draggers.selectAll('g.' + subplotId).remove();
    fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove();
}

exports.toSVG = function(gd) {
    var imageRoot = gd._fullLayout._glimages;
    var root = d3.select(gd).selectAll('.svg-container');
    var canvases = root.filter(function(d, i) {return i === root.size() - 1;})
        .selectAll('.gl-canvas-context, .gl-canvas-focus');

    function canvasToImage() {
        var canvas = this;
        var imageData = canvas.toDataURL('image/png');
        var image = imageRoot.append('svg:image');

        image.attr({
            xmlns: xmlnsNamespaces.svg,
            'xlink:href': imageData,
            preserveAspectRatio: 'none',
            x: 0,
            y: 0,
            width: canvas.width,
            height: canvas.height
        });
    }

    canvases.each(canvasToImage);
};

exports.updateFx = _dereq_('./graph_interact').updateFx;

},{"../../components/drawing":595,"../../constants/xmlns_namespaces":675,"../../lib":697,"../../registry":826,"../get_data":781,"../plots":807,"./attributes":743,"./axis_ids":748,"./constants":751,"./graph_interact":754,"./layout_attributes":757,"./layout_defaults":758,"./transition_axes":767,"d3":151}],757:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = _dereq_('../font_attributes');
var colorAttrs = _dereq_('../../components/color/attributes');
var dash = _dereq_('../../components/drawing/attributes').dash;
var extendFlat = _dereq_('../../lib/extend').extendFlat;
var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;

var constants = _dereq_('./constants');


module.exports = {
    visible: {
        valType: 'boolean',
        
        editType: 'plot',
        
    },
    color: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'ticks',
        
    },
    title: {
        text: {
            valType: 'string',
            
            editType: 'ticks',
            
        },
        font: fontAttrs({
            editType: 'ticks',
            
        }),
        editType: 'ticks'
    },
    type: {
        valType: 'enumerated',
        // '-' means we haven't yet run autotype or couldn't find any data
        // it gets turned into linear in gd._fullLayout but not copied back
        // to gd.data like the others are.
        values: ['-', 'linear', 'log', 'date', 'category', 'multicategory'],
        dflt: '-',
        
        editType: 'calc',
        // we forget when an axis has been autotyped, just writing the auto
        // value back to the input - so it doesn't make sense to template this.
        // Note: we do NOT prohibit this in `coerce`, so if someone enters a
        // type in the template explicitly it will be honored as the default.
        _noTemplating: true,
        
    },
    autorange: {
        valType: 'enumerated',
        values: [true, false, 'reversed'],
        dflt: true,
        
        editType: 'axrange',
        impliedEdits: {'range[0]': undefined, 'range[1]': undefined},
        
    },
    rangemode: {
        valType: 'enumerated',
        values: ['normal', 'tozero', 'nonnegative'],
        dflt: 'normal',
        
        editType: 'plot',
        
    },
    range: {
        valType: 'info_array',
        
        items: [
            {valType: 'any', editType: 'axrange', impliedEdits: {'^autorange': false}, anim: true},
            {valType: 'any', editType: 'axrange', impliedEdits: {'^autorange': false}, anim: true}
        ],
        editType: 'axrange',
        impliedEdits: {'autorange': false},
        anim: true,
        
    },
    fixedrange: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'calc',
        
    },
    // scaleanchor: not used directly, just put here for reference
    // values are any opposite-letter axis id
    scaleanchor: {
        valType: 'enumerated',
        values: [
            constants.idRegex.x.toString(),
            constants.idRegex.y.toString()
        ],
        
        editType: 'plot',
        
    },
    scaleratio: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'plot',
        
    },
    constrain: {
        valType: 'enumerated',
        values: ['range', 'domain'],
        dflt: 'range',
        
        editType: 'plot',
        
    },
    // constraintoward: not used directly, just put here for reference
    constraintoward: {
        valType: 'enumerated',
        values: ['left', 'center', 'right', 'top', 'middle', 'bottom'],
        
        editType: 'plot',
        
    },
    matches: {
        valType: 'enumerated',
        values: [
            constants.idRegex.x.toString(),
            constants.idRegex.y.toString()
        ],
        
        editType: 'calc',
        
    },
    // ticks
    tickmode: {
        valType: 'enumerated',
        values: ['auto', 'linear', 'array'],
        
        editType: 'ticks',
        impliedEdits: {tick0: undefined, dtick: undefined},
        
    },
    nticks: {
        valType: 'integer',
        min: 0,
        dflt: 0,
        
        editType: 'ticks',
        
    },
    tick0: {
        valType: 'any',
        
        editType: 'ticks',
        impliedEdits: {tickmode: 'linear'},
        
    },
    dtick: {
        valType: 'any',
        
        editType: 'ticks',
        impliedEdits: {tickmode: 'linear'},
        
    },
    tickvals: {
        valType: 'data_array',
        editType: 'ticks',
        
    },
    ticktext: {
        valType: 'data_array',
        editType: 'ticks',
        
    },
    ticks: {
        valType: 'enumerated',
        values: ['outside', 'inside', ''],
        
        editType: 'ticks',
        
    },
    tickson: {
        valType: 'enumerated',
        values: ['labels', 'boundaries'],
        
        dflt: 'labels',
        editType: 'ticks',
        
    },
    mirror: {
        valType: 'enumerated',
        values: [true, 'ticks', false, 'all', 'allticks'],
        dflt: false,
        
        editType: 'ticks+layoutstyle',
        
    },
    ticklen: {
        valType: 'number',
        min: 0,
        dflt: 5,
        
        editType: 'ticks',
        
    },
    tickwidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'ticks',
        
    },
    tickcolor: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'ticks',
        
    },
    showticklabels: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'ticks',
        
    },
    automargin: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'ticks',
        
    },
    showspikes: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'modebar',
        
    },
    spikecolor: {
        valType: 'color',
        dflt: null,
        
        editType: 'none',
        
    },
    spikethickness: {
        valType: 'number',
        dflt: 3,
        
        editType: 'none',
        
    },
    spikedash: extendFlat({}, dash, {dflt: 'dash', editType: 'none'}),
    spikemode: {
        valType: 'flaglist',
        flags: ['toaxis', 'across', 'marker'],
        
        dflt: 'toaxis',
        editType: 'none',
        
    },
    spikesnap: {
        valType: 'enumerated',
        values: ['data', 'cursor'],
        dflt: 'data',
        
        editType: 'none',
        
    },
    tickfont: fontAttrs({
        editType: 'ticks',
        
    }),
    tickangle: {
        valType: 'angle',
        dflt: 'auto',
        
        editType: 'ticks',
        
    },
    tickprefix: {
        valType: 'string',
        dflt: '',
        
        editType: 'ticks',
        
    },
    showtickprefix: {
        valType: 'enumerated',
        values: ['all', 'first', 'last', 'none'],
        dflt: 'all',
        
        editType: 'ticks',
        
    },
    ticksuffix: {
        valType: 'string',
        dflt: '',
        
        editType: 'ticks',
        
    },
    showticksuffix: {
        valType: 'enumerated',
        values: ['all', 'first', 'last', 'none'],
        dflt: 'all',
        
        editType: 'ticks',
        
    },
    showexponent: {
        valType: 'enumerated',
        values: ['all', 'first', 'last', 'none'],
        dflt: 'all',
        
        editType: 'ticks',
        
    },
    exponentformat: {
        valType: 'enumerated',
        values: ['none', 'e', 'E', 'power', 'SI', 'B'],
        dflt: 'B',
        
        editType: 'ticks',
        
    },
    separatethousands: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'ticks',
        
    },
    tickformat: {
        valType: 'string',
        dflt: '',
        
        editType: 'ticks',
        
    },
    tickformatstops: templatedArray('tickformatstop', {
        enabled: {
            valType: 'boolean',
            
            dflt: true,
            editType: 'ticks',
            
        },
        dtickrange: {
            valType: 'info_array',
            
            items: [
                {valType: 'any', editType: 'ticks'},
                {valType: 'any', editType: 'ticks'}
            ],
            editType: 'ticks',
            
        },
        value: {
            valType: 'string',
            dflt: '',
            
            editType: 'ticks',
            
        },
        editType: 'ticks'
    }),
    hoverformat: {
        valType: 'string',
        dflt: '',
        
        editType: 'none',
        
    },
    // lines and grids
    showline: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'ticks+layoutstyle',
        
    },
    linecolor: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'layoutstyle',
        
    },
    linewidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'ticks+layoutstyle',
        
    },
    showgrid: {
        valType: 'boolean',
        
        editType: 'ticks',
        
    },
    gridcolor: {
        valType: 'color',
        dflt: colorAttrs.lightLine,
        
        editType: 'ticks',
        
    },
    gridwidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'ticks',
        
    },
    zeroline: {
        valType: 'boolean',
        
        editType: 'ticks',
        
    },
    zerolinecolor: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'ticks',
        
    },
    zerolinewidth: {
        valType: 'number',
        dflt: 1,
        
        editType: 'ticks',
        
    },

    showdividers: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'ticks',
        
    },
    dividercolor: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'ticks',
        
    },
    dividerwidth: {
        valType: 'number',
        dflt: 1,
        
        editType: 'ticks',
        
    },
    // TODO dividerlen: that would override "to label base" length?

    // positioning attributes
    // anchor: not used directly, just put here for reference
    // values are any opposite-letter axis id
    anchor: {
        valType: 'enumerated',
        values: [
            'free',
            constants.idRegex.x.toString(),
            constants.idRegex.y.toString()
        ],
        
        editType: 'plot',
        
    },
    // side: not used directly, as values depend on direction
    // values are top, bottom for x axes, and left, right for y
    side: {
        valType: 'enumerated',
        values: ['top', 'bottom', 'left', 'right'],
        
        editType: 'plot',
        
    },
    // overlaying: not used directly, just put here for reference
    // values are false and any other same-letter axis id that's not
    // itself overlaying anything
    overlaying: {
        valType: 'enumerated',
        values: [
            'free',
            constants.idRegex.x.toString(),
            constants.idRegex.y.toString()
        ],
        
        editType: 'plot',
        
    },
    layer: {
        valType: 'enumerated',
        values: ['above traces', 'below traces'],
        dflt: 'above traces',
        
        editType: 'plot',
        
    },
    domain: {
        valType: 'info_array',
        
        items: [
            {valType: 'number', min: 0, max: 1, editType: 'plot'},
            {valType: 'number', min: 0, max: 1, editType: 'plot'}
        ],
        dflt: [0, 1],
        editType: 'plot',
        
    },
    position: {
        valType: 'number',
        min: 0,
        max: 1,
        dflt: 0,
        
        editType: 'plot',
        
    },
    categoryorder: {
        valType: 'enumerated',
        values: [
            'trace', 'category ascending', 'category descending', 'array'
            /* , 'value ascending', 'value descending'*/ // value ascending / descending to be implemented later
        ],
        dflt: 'trace',
        
        editType: 'calc',
        
    },
    categoryarray: {
        valType: 'data_array',
        
        editType: 'calc',
        
    },
    uirevision: {
        valType: 'any',
        
        editType: 'none',
        
    },
    editType: 'calc',

    _deprecated: {
        autotick: {
            valType: 'boolean',
            
            editType: 'ticks',
            
        },
        title: {
            valType: 'string',
            
            editType: 'ticks',
            
        },
        titlefont: fontAttrs({
            editType: 'ticks',
            
        })
    }
};

},{"../../components/color/attributes":573,"../../components/drawing/attributes":594,"../../lib/extend":687,"../../plot_api/plot_template":735,"../font_attributes":771,"./constants":751}],758:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var Color = _dereq_('../../components/color');
var Template = _dereq_('../../plot_api/plot_template');
var basePlotLayoutAttributes = _dereq_('../layout_attributes');

var layoutAttributes = _dereq_('./layout_attributes');
var handleTypeDefaults = _dereq_('./type_defaults');
var handleAxisDefaults = _dereq_('./axis_defaults');
var handleConstraintDefaults = _dereq_('./constraints').handleConstraintDefaults;
var handlePositionDefaults = _dereq_('./position_defaults');

var axisIds = _dereq_('./axis_ids');
var id2name = axisIds.id2name;
var name2id = axisIds.name2id;

var Registry = _dereq_('../../registry');
var traceIs = Registry.traceIs;
var getComponentMethod = Registry.getComponentMethod;

function appendList(cont, k, item) {
    if(Array.isArray(cont[k])) cont[k].push(item);
    else cont[k] = [item];
}

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
    var ax2traces = {};
    var xaCheater = {};
    var xaNonCheater = {};
    var outerTicks = {};
    var noGrids = {};
    var i, j;

    // look for axes in the data
    for(i = 0; i < fullData.length; i++) {
        var trace = fullData[i];
        if(!traceIs(trace, 'cartesian') && !traceIs(trace, 'gl2d')) continue;

        var xaName;
        if(trace.xaxis) {
            xaName = id2name(trace.xaxis);
            appendList(ax2traces, xaName, trace);
        } else if(trace.xaxes) {
            for(j = 0; j < trace.xaxes.length; j++) {
                appendList(ax2traces, id2name(trace.xaxes[j]), trace);
            }
        }

        var yaName;
        if(trace.yaxis) {
            yaName = id2name(trace.yaxis);
            appendList(ax2traces, yaName, trace);
        } else if(trace.yaxes) {
            for(j = 0; j < trace.yaxes.length; j++) {
                appendList(ax2traces, id2name(trace.yaxes[j]), trace);
            }
        }

        // Two things trigger axis visibility:
        // 1. is not carpet
        // 2. carpet that's not cheater
        if(!traceIs(trace, 'carpet') || (trace.type === 'carpet' && !trace._cheater)) {
            if(xaName) xaNonCheater[xaName] = 1;
        }

        // The above check for definitely-not-cheater is not adequate. This
        // second list tracks which axes *could* be a cheater so that the
        // full condition triggering hiding is:
        //   *could* be a cheater and *is not definitely visible*
        if(trace.type === 'carpet' && trace._cheater) {
            if(xaName) xaCheater[xaName] = 1;
        }

        // check for default formatting tweaks
        if(traceIs(trace, '2dMap')) {
            outerTicks[xaName] = 1;
            outerTicks[yaName] = 1;
        }

        if(traceIs(trace, 'oriented')) {
            var positionAxis = trace.orientation === 'h' ? yaName : xaName;
            noGrids[positionAxis] = 1;
        }
    }

    var subplots = layoutOut._subplots;
    var xIds = subplots.xaxis;
    var yIds = subplots.yaxis;
    var xNames = Lib.simpleMap(xIds, id2name);
    var yNames = Lib.simpleMap(yIds, id2name);
    var axNames = xNames.concat(yNames);

    // plot_bgcolor only makes sense if there's a (2D) plot!
    // TODO: bgcolor for each subplot, to inherit from the main one
    var plotBgColor = Color.background;
    if(xIds.length && yIds.length) {
        plotBgColor = Lib.coerce(layoutIn, layoutOut, basePlotLayoutAttributes, 'plot_bgcolor');
    }

    var bgColor = Color.combine(plotBgColor, layoutOut.paper_bgcolor);

    var axName, axLetter, axLayoutIn, axLayoutOut;

    function coerce(attr, dflt) {
        return Lib.coerce(axLayoutIn, axLayoutOut, layoutAttributes, attr, dflt);
    }

    function coerce2(attr, dflt) {
        return Lib.coerce2(axLayoutIn, axLayoutOut, layoutAttributes, attr, dflt);
    }

    function getCounterAxes(axLetter) {
        return (axLetter === 'x') ? yIds : xIds;
    }

    var counterAxes = {x: getCounterAxes('x'), y: getCounterAxes('y')};
    var allAxisIds = counterAxes.x.concat(counterAxes.y);

    function getOverlayableAxes(axLetter, axName) {
        var list = (axLetter === 'x') ? xNames : yNames;
        var out = [];

        for(var j = 0; j < list.length; j++) {
            var axName2 = list[j];

            if(axName2 !== axName && !(layoutIn[axName2] || {}).overlaying) {
                out.push(name2id(axName2));
            }
        }

        return out;
    }

    // first pass creates the containers, determines types, and handles most of the settings
    for(i = 0; i < axNames.length; i++) {
        axName = axNames[i];
        axLetter = axName.charAt(0);

        if(!Lib.isPlainObject(layoutIn[axName])) {
            layoutIn[axName] = {};
        }

        axLayoutIn = layoutIn[axName];
        axLayoutOut = Template.newContainer(layoutOut, axName, axLetter + 'axis');

        var traces = ax2traces[axName] || [];
        axLayoutOut._traceIndices = traces.map(function(t) { return t._expandedIndex; });
        axLayoutOut._annIndices = [];
        axLayoutOut._shapeIndices = [];
        axLayoutOut._imgIndices = [];
        axLayoutOut._subplotsWith = [];
        axLayoutOut._counterAxes = [];

        // set up some private properties
        axLayoutOut._name = axLayoutOut._attr = axName;
        var id = axLayoutOut._id = name2id(axName);

        var overlayableAxes = getOverlayableAxes(axLetter, axName);

        var defaultOptions = {
            letter: axLetter,
            font: layoutOut.font,
            outerTicks: outerTicks[axName],
            showGrid: !noGrids[axName],
            data: traces,
            bgColor: bgColor,
            calendar: layoutOut.calendar,
            automargin: true,
            cheateronly: axLetter === 'x' && xaCheater[axName] && !xaNonCheater[axName],
            splomStash: ((layoutOut._splomAxes || {})[axLetter] || {})[id]
        };

        coerce('uirevision', layoutOut.uirevision);

        handleTypeDefaults(axLayoutIn, axLayoutOut, coerce, defaultOptions);
        handleAxisDefaults(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut);

        var spikecolor = coerce2('spikecolor');
        var spikethickness = coerce2('spikethickness');
        var spikedash = coerce2('spikedash');
        var spikemode = coerce2('spikemode');
        var spikesnap = coerce2('spikesnap');
        var showSpikes = coerce('showspikes', !!spikecolor || !!spikethickness || !!spikedash || !!spikemode || !!spikesnap);

        if(!showSpikes) {
            delete axLayoutOut.spikecolor;
            delete axLayoutOut.spikethickness;
            delete axLayoutOut.spikedash;
            delete axLayoutOut.spikemode;
            delete axLayoutOut.spikesnap;
        }

        handlePositionDefaults(axLayoutIn, axLayoutOut, coerce, {
            letter: axLetter,
            counterAxes: counterAxes[axLetter],
            overlayableAxes: overlayableAxes,
            grid: layoutOut.grid
        });

        axLayoutOut._input = axLayoutIn;
    }

    // quick second pass for range slider and selector defaults
    var rangeSliderDefaults = getComponentMethod('rangeslider', 'handleDefaults');
    var rangeSelectorDefaults = getComponentMethod('rangeselector', 'handleDefaults');

    for(i = 0; i < xNames.length; i++) {
        axName = xNames[i];
        axLayoutIn = layoutIn[axName];
        axLayoutOut = layoutOut[axName];

        rangeSliderDefaults(layoutIn, layoutOut, axName);

        if(axLayoutOut.type === 'date') {
            rangeSelectorDefaults(
                axLayoutIn,
                axLayoutOut,
                layoutOut,
                yNames,
                axLayoutOut.calendar
            );
        }

        coerce('fixedrange');
    }

    for(i = 0; i < yNames.length; i++) {
        axName = yNames[i];
        axLayoutIn = layoutIn[axName];
        axLayoutOut = layoutOut[axName];

        var anchoredAxis = layoutOut[id2name(axLayoutOut.anchor)];

        var fixedRangeDflt = getComponentMethod('rangeslider', 'isVisible')(anchoredAxis);

        coerce('fixedrange', fixedRangeDflt);
    }

    // Finally, handle scale constraints and matching axes.
    //
    // We need to do this after all axes have coerced both `type`
    // (so we link only axes of the same type) and
    // `fixedrange` (so we can avoid linking from OR TO a fixed axis).

    // sets of axes linked by `scaleanchor` along with the scaleratios compounded
    // together, populated in handleConstraintDefaults
    var constraintGroups = layoutOut._axisConstraintGroups = [];
    // similar to _axisConstraintGroups, but for matching axes
    var matchGroups = layoutOut._axisMatchGroups = [];

    for(i = 0; i < axNames.length; i++) {
        axName = axNames[i];
        axLetter = axName.charAt(0);
        axLayoutIn = layoutIn[axName];
        axLayoutOut = layoutOut[axName];

        handleConstraintDefaults(axLayoutIn, axLayoutOut, coerce, allAxisIds, layoutOut);
    }

    for(i = 0; i < matchGroups.length; i++) {
        var group = matchGroups[i];
        var rng = null;
        var autorange = null;
        var axId;

        // find 'matching' range attrs
        for(axId in group) {
            axLayoutOut = layoutOut[id2name(axId)];
            if(!axLayoutOut.matches) {
                rng = axLayoutOut.range;
                autorange = axLayoutOut.autorange;
            }
        }
        // if `ax.matches` values are reciprocal,
        // pick values of first axis in group
        if(rng === null || autorange === null) {
            for(axId in group) {
                axLayoutOut = layoutOut[id2name(axId)];
                rng = axLayoutOut.range;
                autorange = axLayoutOut.autorange;
                break;
            }
        }
        // apply matching range attrs
        for(axId in group) {
            axLayoutOut = layoutOut[id2name(axId)];
            if(axLayoutOut.matches) {
                axLayoutOut.range = rng.slice();
                axLayoutOut.autorange = autorange;
            }
            axLayoutOut._matchGroup = group;
        }

        // remove matching axis from scaleanchor constraint groups (for now)
        if(constraintGroups.length) {
            for(axId in group) {
                for(j = 0; j < constraintGroups.length; j++) {
                    var group2 = constraintGroups[j];
                    for(var axId2 in group2) {
                        if(axId === axId2) {
                            Lib.warn('Axis ' + axId2 + ' is set with both ' +
                                'a *scaleanchor* and *matches* constraint; ' +
                                'ignoring the scale constraint.');

                            delete group2[axId2];
                            if(Object.keys(group2).length < 2) {
                                constraintGroups.splice(j, 1);
                            }
                        }
                    }
                }
            }
        }
    }
};

},{"../../components/color":574,"../../lib":697,"../../plot_api/plot_template":735,"../../registry":826,"../layout_attributes":798,"./axis_defaults":747,"./axis_ids":748,"./constraints":752,"./layout_attributes":757,"./position_defaults":760,"./type_defaults":768}],759:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorMix = _dereq_('tinycolor2').mix;
var lightFraction = _dereq_('../../components/color/attributes').lightFraction;
var Lib = _dereq_('../../lib');

/**
 * @param {object} opts :
 *   - dfltColor {string} : default axis color
 *   - bgColor {string} : combined subplot bg color
 *   - blend {number, optional} : blend percentage (to compute dflt grid color)
 *   - showLine {boolean} : show line by default
 *   - showGrid {boolean} : show grid by default
 *   - noZeroLine {boolean} : don't coerce zeroline* attributes
 *   - attributes {object} : attribute object associated with input containers
 */
module.exports = function handleLineGridDefaults(containerIn, containerOut, coerce, opts) {
    opts = opts || {};

    var dfltColor = opts.dfltColor;

    function coerce2(attr, dflt) {
        return Lib.coerce2(containerIn, containerOut, opts.attributes, attr, dflt);
    }

    var lineColor = coerce2('linecolor', dfltColor);
    var lineWidth = coerce2('linewidth');
    var showLine = coerce('showline', opts.showLine || !!lineColor || !!lineWidth);

    if(!showLine) {
        delete containerOut.linecolor;
        delete containerOut.linewidth;
    }

    var gridColorDflt = colorMix(dfltColor, opts.bgColor, opts.blend || lightFraction).toRgbString();
    var gridColor = coerce2('gridcolor', gridColorDflt);
    var gridWidth = coerce2('gridwidth');
    var showGridLines = coerce('showgrid', opts.showGrid || !!gridColor || !!gridWidth);

    if(!showGridLines) {
        delete containerOut.gridcolor;
        delete containerOut.gridwidth;
    }

    if(!opts.noZeroLine) {
        var zeroLineColor = coerce2('zerolinecolor', dfltColor);
        var zeroLineWidth = coerce2('zerolinewidth');
        var showZeroLine = coerce('zeroline', opts.showGrid || !!zeroLineColor || !!zeroLineWidth);

        if(!showZeroLine) {
            delete containerOut.zerolinecolor;
            delete containerOut.zerolinewidth;
        }
    }
};

},{"../../components/color/attributes":573,"../../lib":697,"tinycolor2":518}],760:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');


module.exports = function handlePositionDefaults(containerIn, containerOut, coerce, options) {
    var counterAxes = options.counterAxes || [];
    var overlayableAxes = options.overlayableAxes || [];
    var letter = options.letter;
    var grid = options.grid;

    var dfltAnchor, dfltDomain, dfltSide, dfltPosition;

    if(grid) {
        dfltDomain = grid._domains[letter][grid._axisMap[containerOut._id]];
        dfltAnchor = grid._anchors[containerOut._id];
        if(dfltDomain) {
            dfltSide = grid[letter + 'side'].split(' ')[0];
            dfltPosition = grid.domain[letter][dfltSide === 'right' || dfltSide === 'top' ? 1 : 0];
        }
    }

    // Even if there's a grid, this axis may not be in it - fall back on non-grid defaults
    dfltDomain = dfltDomain || [0, 1];
    dfltAnchor = dfltAnchor || (isNumeric(containerIn.position) ? 'free' : (counterAxes[0] || 'free'));
    dfltSide = dfltSide || (letter === 'x' ? 'bottom' : 'left');
    dfltPosition = dfltPosition || 0;

    var anchor = Lib.coerce(containerIn, containerOut, {
        anchor: {
            valType: 'enumerated',
            values: ['free'].concat(counterAxes),
            dflt: dfltAnchor
        }
    }, 'anchor');

    if(anchor === 'free') coerce('position', dfltPosition);

    Lib.coerce(containerIn, containerOut, {
        side: {
            valType: 'enumerated',
            values: letter === 'x' ? ['bottom', 'top'] : ['left', 'right'],
            dflt: dfltSide
        }
    }, 'side');

    var overlaying = false;
    if(overlayableAxes.length) {
        overlaying = Lib.coerce(containerIn, containerOut, {
            overlaying: {
                valType: 'enumerated',
                values: [false].concat(overlayableAxes),
                dflt: false
            }
        }, 'overlaying');
    }

    if(!overlaying) {
        // TODO: right now I'm copying this domain over to overlaying axes
        // in ax.setscale()... but this means we still need (imperfect) logic
        // in the axes popover to hide domain for the overlaying axis.
        // perhaps I should make a private version _domain that all axes get???
        var domain = coerce('domain', dfltDomain);

        // according to https://www.npmjs.com/package/canvas-size
        // the minimum value of max canvas width across browsers and devices is 4096
        // which applied in the calculation below:
        if(domain[0] > domain[1] - 1 / 4096) containerOut.domain = dfltDomain;
        Lib.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain);
    }

    coerce('layer');

    return containerOut;
};

},{"../../lib":697,"fast-isnumeric":218}],761:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var FROM_BL = _dereq_('../../constants/alignment').FROM_BL;

module.exports = function scaleZoom(ax, factor, centerFraction) {
    if(centerFraction === undefined) {
        centerFraction = FROM_BL[ax.constraintoward || 'center'];
    }

    var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])];
    var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction;

    ax.range = ax._input.range = [
        ax.l2r(center + (rangeLinear[0] - center) * factor),
        ax.l2r(center + (rangeLinear[1] - center) * factor)
    ];
};

},{"../../constants/alignment":669}],762:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var polybool = _dereq_('polybooljs');

var Registry = _dereq_('../../registry');
var Color = _dereq_('../../components/color');
var Fx = _dereq_('../../components/fx');

var polygon = _dereq_('../../lib/polygon');
var throttle = _dereq_('../../lib/throttle');
var makeEventData = _dereq_('../../components/fx/helpers').makeEventData;
var getFromId = _dereq_('./axis_ids').getFromId;
var clearGlCanvases = _dereq_('../../lib/clear_gl_canvases');
var redrawReglTraces = _dereq_('../../plot_api/subroutines').redrawReglTraces;

var constants = _dereq_('./constants');
var MINSELECT = constants.MINSELECT;

var filteredPolygon = polygon.filter;
var polygonTester = polygon.tester;

function getAxId(ax) { return ax._id; }

function prepSelect(e, startX, startY, dragOptions, mode) {
    var gd = dragOptions.gd;
    var fullLayout = gd._fullLayout;
    var zoomLayer = fullLayout._zoomlayer;
    var dragBBox = dragOptions.element.getBoundingClientRect();
    var plotinfo = dragOptions.plotinfo;
    var xs = plotinfo.xaxis._offset;
    var ys = plotinfo.yaxis._offset;
    var x0 = startX - dragBBox.left;
    var y0 = startY - dragBBox.top;
    var x1 = x0;
    var y1 = y0;
    var path0 = 'M' + x0 + ',' + y0;
    var pw = dragOptions.xaxes[0]._length;
    var ph = dragOptions.yaxes[0]._length;
    var allAxes = dragOptions.xaxes.concat(dragOptions.yaxes);
    var subtract = e.altKey;

    var filterPoly, selectionTester, mergedPolygons, currentPolygon;
    var i, searchInfo, eventData;

    coerceSelectionsCache(e, gd, dragOptions);

    if(mode === 'lasso') {
        filterPoly = filteredPolygon([[x0, y0]], constants.BENDPX);
    }

    var outlines = zoomLayer.selectAll('path.select-outline-' + plotinfo.id).data([1, 2]);

    outlines.enter()
        .append('path')
        .attr('class', function(d) { return 'select-outline select-outline-' + d + ' select-outline-' + plotinfo.id; })
        .attr('transform', 'translate(' + xs + ', ' + ys + ')')
        .attr('d', path0 + 'Z');

    var corners = zoomLayer.append('path')
        .attr('class', 'zoombox-corners')
        .style({
            fill: Color.background,
            stroke: Color.defaultLine,
            'stroke-width': 1
        })
        .attr('transform', 'translate(' + xs + ', ' + ys + ')')
        .attr('d', 'M0,0Z');


    var throttleID = fullLayout._uid + constants.SELECTID;
    var selection = [];

    // find the traces to search for selection points
    var searchTraces = determineSearchTraces(gd, dragOptions.xaxes,
      dragOptions.yaxes, dragOptions.subplot);

    function axValue(ax) {
        var index = (ax._id.charAt(0) === 'y') ? 1 : 0;
        return function(v) { return ax.p2d(v[index]); };
    }

    function ascending(a, b) { return a - b; }

    // allow subplots to override fillRangeItems routine
    var fillRangeItems;

    if(plotinfo.fillRangeItems) {
        fillRangeItems = plotinfo.fillRangeItems;
    } else {
        if(mode === 'select') {
            fillRangeItems = function(eventData, poly) {
                var ranges = eventData.range = {};

                for(i = 0; i < allAxes.length; i++) {
                    var ax = allAxes[i];
                    var axLetter = ax._id.charAt(0);

                    ranges[ax._id] = [
                        ax.p2d(poly[axLetter + 'min']),
                        ax.p2d(poly[axLetter + 'max'])
                    ].sort(ascending);
                }
            };
        } else {
            fillRangeItems = function(eventData, poly, filterPoly) {
                var dataPts = eventData.lassoPoints = {};

                for(i = 0; i < allAxes.length; i++) {
                    var ax = allAxes[i];
                    dataPts[ax._id] = filterPoly.filtered.map(axValue(ax));
                }
            };
        }
    }

    dragOptions.moveFn = function(dx0, dy0) {
        x1 = Math.max(0, Math.min(pw, dx0 + x0));
        y1 = Math.max(0, Math.min(ph, dy0 + y0));

        var dx = Math.abs(x1 - x0);
        var dy = Math.abs(y1 - y0);

        if(mode === 'select') {
            var direction = fullLayout.selectdirection;

            if(fullLayout.selectdirection === 'any') {
                if(dy < Math.min(dx * 0.6, MINSELECT)) direction = 'h';
                else if(dx < Math.min(dy * 0.6, MINSELECT)) direction = 'v';
                else direction = 'd';
            }
            else {
                direction = fullLayout.selectdirection;
            }

            if(direction === 'h') {
                // horizontal motion: make a vertical box
                currentPolygon = [[x0, 0], [x0, ph], [x1, ph], [x1, 0]];
                currentPolygon.xmin = Math.min(x0, x1);
                currentPolygon.xmax = Math.max(x0, x1);
                currentPolygon.ymin = Math.min(0, ph);
                currentPolygon.ymax = Math.max(0, ph);
                // extras to guide users in keeping a straight selection
                corners.attr('d', 'M' + currentPolygon.xmin + ',' + (y0 - MINSELECT) +
                    'h-4v' + (2 * MINSELECT) + 'h4Z' +
                    'M' + (currentPolygon.xmax - 1) + ',' + (y0 - MINSELECT) +
                    'h4v' + (2 * MINSELECT) + 'h-4Z');

            }
            else if(direction === 'v') {
                // vertical motion: make a horizontal box
                currentPolygon = [[0, y0], [0, y1], [pw, y1], [pw, y0]];
                currentPolygon.xmin = Math.min(0, pw);
                currentPolygon.xmax = Math.max(0, pw);
                currentPolygon.ymin = Math.min(y0, y1);
                currentPolygon.ymax = Math.max(y0, y1);
                corners.attr('d', 'M' + (x0 - MINSELECT) + ',' + currentPolygon.ymin +
                    'v-4h' + (2 * MINSELECT) + 'v4Z' +
                    'M' + (x0 - MINSELECT) + ',' + (currentPolygon.ymax - 1) +
                    'v4h' + (2 * MINSELECT) + 'v-4Z');
            }
            else if(direction === 'd') {
                // diagonal motion
                currentPolygon = [[x0, y0], [x0, y1], [x1, y1], [x1, y0]];
                currentPolygon.xmin = Math.min(x0, x1);
                currentPolygon.xmax = Math.max(x0, x1);
                currentPolygon.ymin = Math.min(y0, y1);
                currentPolygon.ymax = Math.max(y0, y1);
                corners.attr('d', 'M0,0Z');
            }
        }
        else if(mode === 'lasso') {
            filterPoly.addPt([x1, y1]);
            currentPolygon = filterPoly.filtered;
        }

        // create outline & tester
        if(dragOptions.selectionDefs && dragOptions.selectionDefs.length) {
            mergedPolygons = mergePolygons(dragOptions.mergedPolygons, currentPolygon, subtract);
            currentPolygon.subtract = subtract;
            selectionTester = multiTester(dragOptions.selectionDefs.concat([currentPolygon]));
        }
        else {
            mergedPolygons = [currentPolygon];
            selectionTester = polygonTester(currentPolygon);
        }

        // draw selection
        drawSelection(mergedPolygons, outlines);


        throttle.throttle(
            throttleID,
            constants.SELECTDELAY,
            function() {
                selection = [];

                var thisSelection;
                var traceSelections = [];
                var traceSelection;
                for(i = 0; i < searchTraces.length; i++) {
                    searchInfo = searchTraces[i];

                    traceSelection = searchInfo._module.selectPoints(searchInfo, selectionTester);
                    traceSelections.push(traceSelection);

                    thisSelection = fillSelectionItem(traceSelection, searchInfo);

                    if(selection.length) {
                        for(var j = 0; j < thisSelection.length; j++) {
                            selection.push(thisSelection[j]);
                        }
                    }
                    else selection = thisSelection;
                }

                eventData = {points: selection};
                updateSelectedState(gd, searchTraces, eventData);
                fillRangeItems(eventData, currentPolygon, filterPoly);
                dragOptions.gd.emit('plotly_selecting', eventData);
            }
        );
    };

    dragOptions.clickFn = function(numClicks, evt) {
        var clickmode = fullLayout.clickmode;

        corners.remove();

        throttle.done(throttleID).then(function() {
            throttle.clear(throttleID);
            if(numClicks === 2) {
                // clear selection on doubleclick
                outlines.remove();
                for(i = 0; i < searchTraces.length; i++) {
                    searchInfo = searchTraces[i];
                    searchInfo._module.selectPoints(searchInfo, false);
                }

                updateSelectedState(gd, searchTraces);

                clearSelectionsCache(dragOptions);

                gd.emit('plotly_deselect', null);
            } else {
                if(clickmode.indexOf('select') > -1) {
                    selectOnClick(evt, gd, dragOptions.xaxes, dragOptions.yaxes,
                      dragOptions.subplot, dragOptions, outlines);
                }

                if(clickmode === 'event') {
                    // TODO: remove in v2 - this was probably never intended to work as it does,
                    // but in case anyone depends on it we don't want to break it now.
                    // Note that click-to-select introduced pre v2 also emitts proper
                    // event data when clickmode is having 'select' in its flag list.
                    gd.emit('plotly_selected', undefined);
                }
            }

            Fx.click(gd, evt);
        });
    };

    dragOptions.doneFn = function() {
        corners.remove();

        throttle.done(throttleID).then(function() {
            throttle.clear(throttleID);
            dragOptions.gd.emit('plotly_selected', eventData);

            if(currentPolygon && dragOptions.selectionDefs) {
                // save last polygons
                currentPolygon.subtract = subtract;
                dragOptions.selectionDefs.push(currentPolygon);

                // we have to keep reference to arrays container
                dragOptions.mergedPolygons.length = 0;
                [].push.apply(dragOptions.mergedPolygons, mergedPolygons);
            }
        });
    };
}

function selectOnClick(evt, gd, xAxes, yAxes, subplot, dragOptions, polygonOutlines) {
    var hoverData = gd._hoverdata;
    var clickmode = gd._fullLayout.clickmode;
    var sendEvents = clickmode.indexOf('event') > -1;
    var selection = [];
    var searchTraces, searchInfo, currentSelectionDef, selectionTester, traceSelection;
    var thisTracesSelection, pointOrBinSelected, subtract, eventData, i;

    if(isHoverDataSet(hoverData)) {
        coerceSelectionsCache(evt, gd, dragOptions);
        searchTraces = determineSearchTraces(gd, xAxes, yAxes, subplot);
        var clickedPtInfo = extractClickedPtInfo(hoverData, searchTraces);
        var isBinnedTrace = clickedPtInfo.pointNumbers.length > 0;


        // Note: potentially costly operation isPointOrBinSelected is
        // called as late as possible through the use of an assignment
        // in an if condition.
        if(isBinnedTrace ?
            isOnlyThisBinSelected(searchTraces, clickedPtInfo) :
            isOnlyOnePointSelected(searchTraces) &&
                (pointOrBinSelected = isPointOrBinSelected(clickedPtInfo)))
        {
            if(polygonOutlines) polygonOutlines.remove();
            for(i = 0; i < searchTraces.length; i++) {
                searchInfo = searchTraces[i];
                searchInfo._module.selectPoints(searchInfo, false);
            }

            updateSelectedState(gd, searchTraces);

            clearSelectionsCache(dragOptions);

            if(sendEvents) {
                gd.emit('plotly_deselect', null);
            }
        } else {
            subtract = evt.shiftKey &&
              (pointOrBinSelected !== undefined ?
                pointOrBinSelected :
                isPointOrBinSelected(clickedPtInfo));
            currentSelectionDef = newPointSelectionDef(clickedPtInfo.pointNumber, clickedPtInfo.searchInfo, subtract);

            var allSelectionDefs = dragOptions.selectionDefs.concat([currentSelectionDef]);
            selectionTester = multiTester(allSelectionDefs);

            for(i = 0; i < searchTraces.length; i++) {
                traceSelection = searchTraces[i]._module.selectPoints(searchTraces[i], selectionTester);
                thisTracesSelection = fillSelectionItem(traceSelection, searchTraces[i]);

                if(selection.length) {
                    for(var j = 0; j < thisTracesSelection.length; j++) {
                        selection.push(thisTracesSelection[j]);
                    }
                }
                else selection = thisTracesSelection;
            }

            eventData = {points: selection};
            updateSelectedState(gd, searchTraces, eventData);

            if(currentSelectionDef && dragOptions) {
                dragOptions.selectionDefs.push(currentSelectionDef);
            }

            if(polygonOutlines) drawSelection(dragOptions.mergedPolygons, polygonOutlines);

            if(sendEvents) {
                gd.emit('plotly_selected', eventData);
            }
        }
    }
}

/**
 * Constructs a new point selection definition object.
 */
function newPointSelectionDef(pointNumber, searchInfo, subtract) {
    return {
        pointNumber: pointNumber,
        searchInfo: searchInfo,
        subtract: subtract
    };
}

function isPointSelectionDef(o) {
    return 'pointNumber' in o && 'searchInfo' in o;
}

/*
 * Constructs a new point number tester.
 */
function newPointNumTester(pointSelectionDef) {
    return {
        xmin: 0,
        xmax: 0,
        ymin: 0,
        ymax: 0,
        pts: [],
        contains: function(pt, omitFirstEdge, pointNumber, searchInfo) {
            var idxWantedTrace = pointSelectionDef.searchInfo.cd[0].trace._expandedIndex;
            var idxActualTrace = searchInfo.cd[0].trace._expandedIndex;
            return idxActualTrace === idxWantedTrace &&
              pointNumber === pointSelectionDef.pointNumber;
        },
        isRect: false,
        degenerate: false,
        subtract: pointSelectionDef.subtract
    };
}

/**
 * Wraps multiple selection testers.
 *
 * @param {Array} list - An array of selection testers.
 *
 * @return a selection tester object with a contains function
 * that can be called to evaluate a point against all wrapped
 * selection testers that were passed in list.
 */
function multiTester(list) {
    var testers = [];
    var xmin = isPointSelectionDef(list[0]) ? 0 : list[0][0][0];
    var xmax = xmin;
    var ymin = isPointSelectionDef(list[0]) ? 0 : list[0][0][1];
    var ymax = ymin;

    for(var i = 0; i < list.length; i++) {
        if(isPointSelectionDef(list[i])) {
            testers.push(newPointNumTester(list[i]));
        } else {
            var tester = polygon.tester(list[i]);
            tester.subtract = list[i].subtract;
            testers.push(tester);
            xmin = Math.min(xmin, tester.xmin);
            xmax = Math.max(xmax, tester.xmax);
            ymin = Math.min(ymin, tester.ymin);
            ymax = Math.max(ymax, tester.ymax);
        }
    }

    /**
     * Tests if the given point is within this tester.
     *
     * @param {Array} pt - [0] is the x coordinate, [1] is the y coordinate of the point.
     * @param {*} arg - An optional parameter to pass down to wrapped testers.
     * @param {number} pointNumber - The point number of the point within the underlying data array.
     * @param {number} searchInfo - An object identifying the trace the point is contained in.
     *
     * @return {boolean} true if point is considered to be selected, false otherwise.
     */
    function contains(pt, arg, pointNumber, searchInfo) {
        var contained = false;
        for(var i = 0; i < testers.length; i++) {
            if(testers[i].contains(pt, arg, pointNumber, searchInfo)) {
                // if contained by subtract tester - exclude the point
                contained = testers[i].subtract === false;
            }
        }

        return contained;
    }

    return {
        xmin: xmin,
        xmax: xmax,
        ymin: ymin,
        ymax: ymax,
        pts: [],
        contains: contains,
        isRect: false,
        degenerate: false
    };
}

function coerceSelectionsCache(evt, gd, dragOptions) {
    var fullLayout = gd._fullLayout;
    var zoomLayer = fullLayout._zoomlayer;
    var plotinfo = dragOptions.plotinfo;

    var selectingOnSameSubplot = (
      fullLayout._lastSelectedSubplot &&
      fullLayout._lastSelectedSubplot === plotinfo.id
    );
    var hasModifierKey = evt.shiftKey || evt.altKey;
    if(selectingOnSameSubplot && hasModifierKey &&
      (plotinfo.selection && plotinfo.selection.selectionDefs) && !dragOptions.selectionDefs) {
        // take over selection definitions from prev mode, if any
        dragOptions.selectionDefs = plotinfo.selection.selectionDefs;
        dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons;
    } else if(!hasModifierKey || !plotinfo.selection) {
        clearSelectionsCache(dragOptions);
    }

    // clear selection outline when selecting a different subplot
    if(!selectingOnSameSubplot) {
        clearSelect(zoomLayer);
        fullLayout._lastSelectedSubplot = plotinfo.id;
    }
}

function clearSelectionsCache(dragOptions) {
    var plotinfo = dragOptions.plotinfo;

    plotinfo.selection = {};
    plotinfo.selection.selectionDefs = dragOptions.selectionDefs = [];
    plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = [];
}

function determineSearchTraces(gd, xAxes, yAxes, subplot) {
    var searchTraces = [];
    var xAxisIds = xAxes.map(getAxId);
    var yAxisIds = yAxes.map(getAxId);
    var cd, trace, i;

    for(i = 0; i < gd.calcdata.length; i++) {
        cd = gd.calcdata[i];
        trace = cd[0].trace;

        if(trace.visible !== true || !trace._module || !trace._module.selectPoints) continue;

        if(subplot && (trace.subplot === subplot || trace.geo === subplot)) {
            searchTraces.push(createSearchInfo(trace._module, cd, xAxes[0], yAxes[0]));
        } else if(
          trace.type === 'splom' &&
          // FIXME: make sure we don't have more than single axis for splom
          trace._xaxes[xAxisIds[0]] && trace._yaxes[yAxisIds[0]]
        ) {
            var info = createSearchInfo(trace._module, cd, xAxes[0], yAxes[0]);
            info.scene = gd._fullLayout._splomScenes[trace.uid];
            searchTraces.push(info);
        } else {
            if(xAxisIds.indexOf(trace.xaxis) === -1) continue;
            if(yAxisIds.indexOf(trace.yaxis) === -1) continue;

            searchTraces.push(createSearchInfo(trace._module, cd,
              getFromId(gd, trace.xaxis), getFromId(gd, trace.yaxis)));
        }
    }

    return searchTraces;

    function createSearchInfo(module, calcData, xaxis, yaxis) {
        return {
            _module: module,
            cd: calcData,
            xaxis: xaxis,
            yaxis: yaxis
        };
    }
}

function drawSelection(polygons, outlines) {
    var paths = [];
    var i, d;

    for(i = 0; i < polygons.length; i++) {
        var ppts = polygons[i];
        paths.push(ppts.join('L') + 'L' + ppts[0]);
    }

    d = polygons.length > 0 ?
      'M' + paths.join('M') + 'Z' :
      'M0,0Z';
    outlines.attr('d', d);
}

function isHoverDataSet(hoverData) {
    return hoverData &&
      Array.isArray(hoverData) &&
      hoverData[0].hoverOnBox !== true;
}

function extractClickedPtInfo(hoverData, searchTraces) {
    var hoverDatum = hoverData[0];
    var pointNumber = -1;
    var pointNumbers = [];
    var searchInfo, i;

    for(i = 0; i < searchTraces.length; i++) {
        searchInfo = searchTraces[i];
        if(hoverDatum.fullData._expandedIndex === searchInfo.cd[0].trace._expandedIndex) {

            // Special case for box (and violin)
            if(hoverDatum.hoverOnBox === true) {
                break;
            }

            // Hint: in some traces like histogram, one graphical element
            // doesn't correspond to one particular data point, but to
            // bins of data points. Thus, hoverDatum can have a binNumber
            // property instead of pointNumber.
            if(hoverDatum.pointNumber !== undefined) {
                pointNumber = hoverDatum.pointNumber;
            } else if(hoverDatum.binNumber !== undefined) {
                pointNumber = hoverDatum.binNumber;
                pointNumbers = hoverDatum.pointNumbers;
            }

            break;
        }
    }

    return {
        pointNumber: pointNumber,
        pointNumbers: pointNumbers,
        searchInfo: searchInfo
    };
}

function isPointOrBinSelected(clickedPtInfo) {
    var trace = clickedPtInfo.searchInfo.cd[0].trace;
    var ptNum = clickedPtInfo.pointNumber;
    var ptNums = clickedPtInfo.pointNumbers;
    var ptNumsSet = ptNums.length > 0;

    // When pointsNumbers is set (e.g. histogram's binning),
    // it is assumed that when the first point of
    // a bin is selected, all others are as well
    var ptNumToTest = ptNumsSet ? ptNums[0] : ptNum;

    // TODO potential performance improvement
    // Primarily we need this function to determine if a click adds
    // or subtracts from a selection.
    // In cases `trace.selectedpoints` is a huge array, indexOf
    // might be slow. One remedy would be to introduce a hash somewhere.
    return trace.selectedpoints ? trace.selectedpoints.indexOf(ptNumToTest) > -1 : false;
}

function isOnlyThisBinSelected(searchTraces, clickedPtInfo) {
    var tracesWithSelectedPts = [];
    var searchInfo, trace, isSameTrace, i;

    for(i = 0; i < searchTraces.length; i++) {
        searchInfo = searchTraces[i];
        if(searchInfo.cd[0].trace.selectedpoints && searchInfo.cd[0].trace.selectedpoints.length > 0) {
            tracesWithSelectedPts.push(searchInfo);
        }
    }

    if(tracesWithSelectedPts.length === 1) {
        isSameTrace = tracesWithSelectedPts[0] === clickedPtInfo.searchInfo;
        if(isSameTrace) {
            trace = clickedPtInfo.searchInfo.cd[0].trace;
            if(trace.selectedpoints.length === clickedPtInfo.pointNumbers.length) {
                for(i = 0; i < clickedPtInfo.pointNumbers.length; i++) {
                    if(trace.selectedpoints.indexOf(clickedPtInfo.pointNumbers[i]) < 0) {
                        return false;
                    }
                }
                return true;
            }
        }
    }

    return false;
}

function isOnlyOnePointSelected(searchTraces) {
    var len = 0;
    var searchInfo, trace, i;

    for(i = 0; i < searchTraces.length; i++) {
        searchInfo = searchTraces[i];
        trace = searchInfo.cd[0].trace;
        if(trace.selectedpoints) {
            if(trace.selectedpoints.length > 1) return false;

            len += trace.selectedpoints.length;
            if(len > 1) return false;
        }
    }

    return len === 1;
}

function updateSelectedState(gd, searchTraces, eventData) {
    var i, searchInfo, cd, trace;

    // before anything else, update preGUI if necessary
    for(i = 0; i < searchTraces.length; i++) {
        var fullInputTrace = searchTraces[i].cd[0].trace._fullInput;
        var tracePreGUI = gd._fullLayout._tracePreGUI[fullInputTrace.uid];
        if(tracePreGUI.selectedpoints === undefined) {
            tracePreGUI.selectedpoints = fullInputTrace._input.selectedpoints || null;
        }
    }

    if(eventData) {
        var pts = eventData.points || [];

        for(i = 0; i < searchTraces.length; i++) {
            trace = searchTraces[i].cd[0].trace;
            trace._input.selectedpoints = trace._fullInput.selectedpoints = [];
            if(trace._fullInput !== trace) trace.selectedpoints = [];
        }

        for(i = 0; i < pts.length; i++) {
            var pt = pts[i];
            var data = pt.data;
            var fullData = pt.fullData;

            if(pt.pointIndices) {
                [].push.apply(data.selectedpoints, pt.pointIndices);
                if(trace._fullInput !== trace) {
                    [].push.apply(fullData.selectedpoints, pt.pointIndices);
                }
            } else {
                data.selectedpoints.push(pt.pointIndex);
                if(trace._fullInput !== trace) {
                    fullData.selectedpoints.push(pt.pointIndex);
                }
            }
        }
    }
    else {
        for(i = 0; i < searchTraces.length; i++) {
            trace = searchTraces[i].cd[0].trace;
            delete trace.selectedpoints;
            delete trace._input.selectedpoints;
            if(trace._fullInput !== trace) {
                delete trace._fullInput.selectedpoints;
            }
        }
    }

    var hasRegl = false;

    for(i = 0; i < searchTraces.length; i++) {
        searchInfo = searchTraces[i];
        cd = searchInfo.cd;
        trace = cd[0].trace;

        if(Registry.traceIs(trace, 'regl')) {
            hasRegl = true;
        }

        var _module = searchInfo._module;
        var fn = _module.styleOnSelect || _module.style;
        if(fn) fn(gd, cd);
    }

    if(hasRegl) {
        clearGlCanvases(gd);
        redrawReglTraces(gd);
    }
}

function mergePolygons(list, poly, subtract) {
    var res;

    if(subtract) {
        res = polybool.difference({
            regions: list,
            inverted: false
        }, {
            regions: [poly],
            inverted: false
        });

        return res.regions;
    }

    res = polybool.union({
        regions: list,
        inverted: false
    }, {
        regions: [poly],
        inverted: false
    });

    return res.regions;
}

function fillSelectionItem(selection, searchInfo) {
    if(Array.isArray(selection)) {
        var cd = searchInfo.cd;
        var trace = searchInfo.cd[0].trace;

        for(var i = 0; i < selection.length; i++) {
            selection[i] = makeEventData(selection[i], trace, cd);
        }
    }

    return selection;
}

function clearSelect(zoomlayer) {
    // until we get around to persistent selections, remove the outline
    // here. The selection itself will be removed when the plot redraws
    // at the end.
    zoomlayer.selectAll('.select-outline').remove();
}

module.exports = {
    prepSelect: prepSelect,
    clearSelect: clearSelect,
    selectOnClick: selectOnClick
};

},{"../../components/color":574,"../../components/fx":613,"../../components/fx/helpers":609,"../../lib/clear_gl_canvases":682,"../../lib/polygon":709,"../../lib/throttle":722,"../../plot_api/subroutines":736,"../../registry":826,"./axis_ids":748,"./constants":751,"polybooljs":462}],763:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');
var cleanNumber = Lib.cleanNumber;
var ms2DateTime = Lib.ms2DateTime;
var dateTime2ms = Lib.dateTime2ms;
var ensureNumber = Lib.ensureNumber;
var isArrayOrTypedArray = Lib.isArrayOrTypedArray;

var numConstants = _dereq_('../../constants/numerical');
var FP_SAFE = numConstants.FP_SAFE;
var BADNUM = numConstants.BADNUM;
var LOG_CLIP = numConstants.LOG_CLIP;

var constants = _dereq_('./constants');
var axisIds = _dereq_('./axis_ids');

function fromLog(v) {
    return Math.pow(10, v);
}

function isValidCategory(v) {
    return v !== null && v !== undefined;
}

/**
 * Define the conversion functions for an axis data is used in 5 ways:
 *
 *  d: data, in whatever form it's provided
 *  c: calcdata: turned into numbers, but not linearized
 *  l: linearized - same as c except for log axes (and other nonlinear
 *      mappings later?) this is used when we need to know if it's
 *      *possible* to show some data on this axis, without caring about
 *      the current range
 *  p: pixel value - mapped to the screen with current size and zoom
 *  r: ranges, tick0, and annotation positions match one of the above
 *     but are handled differently for different types:
 *     - linear and date: data format (d)
 *     - category: calcdata format (c), and will stay that way because
 *       the data format has no continuous mapping
 *     - log: linearized (l) format
 *       TODO: in v2.0 we plan to change it to data format. At that point
 *       shapes will work the same way as ranges, tick0, and annotations
 *       so they can use this conversion too.
 *
 * Creates/updates these conversion functions, and a few more utilities
 * like cleanRange, and makeCalcdata
 *
 * also clears the autotick constraints ._minDtick, ._forceTick0
 */
module.exports = function setConvert(ax, fullLayout) {
    fullLayout = fullLayout || {};

    var axId = (ax._id || 'x');
    var axLetter = axId.charAt(0);

    function toLog(v, clip) {
        if(v > 0) return Math.log(v) / Math.LN10;

        else if(v <= 0 && clip && ax.range && ax.range.length === 2) {
            // clip NaN (ie past negative infinity) to LOG_CLIP axis
            // length past the negative edge
            var r0 = ax.range[0];
            var r1 = ax.range[1];
            return 0.5 * (r0 + r1 - 2 * LOG_CLIP * Math.abs(r0 - r1));
        }

        else return BADNUM;
    }

    /*
     * wrapped dateTime2ms that:
     * - accepts ms numbers for backward compatibility
     * - inserts a dummy arg so calendar is the 3rd arg (see notes below).
     * - defaults to ax.calendar
     */
    function dt2ms(v, _, calendar) {
        // NOTE: Changed this behavior: previously we took any numeric value
        // to be a ms, even if it was a string that could be a bare year.
        // Now we convert it as a date if at all possible, and only try
        // as (local) ms if that fails.
        var ms = dateTime2ms(v, calendar || ax.calendar);
        if(ms === BADNUM) {
            if(isNumeric(v)) {
                v = +v;
                // keep track of tenths of ms, that `new Date` will drop
                // same logic as in Lib.ms2DateTime
                var msecTenths = Math.floor(Lib.mod(v + 0.05, 1) * 10);
                var msRounded = Math.round(v - msecTenths / 10);
                ms = dateTime2ms(new Date(msRounded)) + msecTenths / 10;
            }
            else return BADNUM;
        }
        return ms;
    }

    // wrapped ms2DateTime to insert default ax.calendar
    function ms2dt(v, r, calendar) {
        return ms2DateTime(v, r, calendar || ax.calendar);
    }

    function getCategoryName(v) {
        return ax._categories[Math.round(v)];
    }

    /*
     * setCategoryIndex: return the index of category v,
     * inserting it in the list if it's not already there
     *
     * this will enter the categories in the order it
     * encounters them, ie all the categories from the
     * first data set, then all the ones from the second
     * that aren't in the first etc.
     *
     * it is assumed that this function is being invoked in the
     * already sorted category order; otherwise there would be
     * a disconnect between the array and the index returned
     */
    function setCategoryIndex(v) {
        if(isValidCategory(v)) {
            if(ax._categoriesMap === undefined) {
                ax._categoriesMap = {};
            }

            if(ax._categoriesMap[v] !== undefined) {
                return ax._categoriesMap[v];
            } else {
                ax._categories.push(v);

                var curLength = ax._categories.length - 1;
                ax._categoriesMap[v] = curLength;

                return curLength;
            }
        }
        return BADNUM;
    }

    function setMultiCategoryIndex(arrayIn, len) {
        var arrayOut = new Array(len);

        for(var i = 0; i < len; i++) {
            var v0 = (arrayIn[0] || [])[i];
            var v1 = (arrayIn[1] || [])[i];
            arrayOut[i] = getCategoryIndex([v0, v1]);
        }

        return arrayOut;
    }

    function getCategoryIndex(v) {
        if(ax._categoriesMap) {
            return ax._categoriesMap[v];
        }
    }

    function getCategoryPosition(v) {
        // d2l/d2c variant that that won't add categories but will also
        // allow numbers to be mapped to the linearized axis positions
        var index = getCategoryIndex(v);
        if(index !== undefined) return index;
        if(isNumeric(v)) return +v;
    }

    function l2p(v) {
        if(!isNumeric(v)) return BADNUM;

        // include 2 fractional digits on pixel, for PDF zooming etc
        return d3.round(ax._b + ax._m * v, 2);
    }

    function p2l(px) { return (px - ax._b) / ax._m; }

    // conversions among c/l/p are fairly simple - do them together for all axis types
    ax.c2l = (ax.type === 'log') ? toLog : ensureNumber;
    ax.l2c = (ax.type === 'log') ? fromLog : ensureNumber;

    ax.l2p = l2p;
    ax.p2l = p2l;

    ax.c2p = (ax.type === 'log') ? function(v, clip) { return l2p(toLog(v, clip)); } : l2p;
    ax.p2c = (ax.type === 'log') ? function(px) { return fromLog(p2l(px)); } : p2l;

    /*
     * now type-specific conversions for **ALL** other combinations
     * they're all written out, instead of being combinations of each other, for
     * both clarity and speed.
     */
    if(['linear', '-'].indexOf(ax.type) !== -1) {
        // all are data vals, but d and r need cleaning
        ax.d2r = ax.r2d = ax.d2c = ax.r2c = ax.d2l = ax.r2l = cleanNumber;
        ax.c2d = ax.c2r = ax.l2d = ax.l2r = ensureNumber;

        ax.d2p = ax.r2p = function(v) { return ax.l2p(cleanNumber(v)); };
        ax.p2d = ax.p2r = p2l;

        ax.cleanPos = ensureNumber;
    }
    else if(ax.type === 'log') {
        // d and c are data vals, r and l are logged (but d and r need cleaning)
        ax.d2r = ax.d2l = function(v, clip) { return toLog(cleanNumber(v), clip); };
        ax.r2d = ax.r2c = function(v) { return fromLog(cleanNumber(v)); };

        ax.d2c = ax.r2l = cleanNumber;
        ax.c2d = ax.l2r = ensureNumber;

        ax.c2r = toLog;
        ax.l2d = fromLog;

        ax.d2p = function(v, clip) { return ax.l2p(ax.d2r(v, clip)); };
        ax.p2d = function(px) { return fromLog(p2l(px)); };

        ax.r2p = function(v) { return ax.l2p(cleanNumber(v)); };
        ax.p2r = p2l;

        ax.cleanPos = ensureNumber;
    }
    else if(ax.type === 'date') {
        // r and d are date strings, l and c are ms

        /*
         * Any of these functions with r and d on either side, calendar is the
         * **3rd** argument. log has reserved the second argument.
         *
         * Unless you need the special behavior of the second arg (ms2DateTime
         * uses this to limit precision, toLog uses true to clip negatives
         * to offscreen low rather than undefined), it's safe to pass 0.
         */
        ax.d2r = ax.r2d = Lib.identity;

        ax.d2c = ax.r2c = ax.d2l = ax.r2l = dt2ms;
        ax.c2d = ax.c2r = ax.l2d = ax.l2r = ms2dt;

        ax.d2p = ax.r2p = function(v, _, calendar) { return ax.l2p(dt2ms(v, 0, calendar)); };
        ax.p2d = ax.p2r = function(px, r, calendar) { return ms2dt(p2l(px), r, calendar); };

        ax.cleanPos = function(v) { return Lib.cleanDate(v, BADNUM, ax.calendar); };
    }
    else if(ax.type === 'category') {
        // d is categories (string)
        // c and l are indices (numbers)
        // r is categories or numbers

        ax.d2c = ax.d2l = setCategoryIndex;
        ax.r2d = ax.c2d = ax.l2d = getCategoryName;

        ax.d2r = ax.d2l_noadd = getCategoryPosition;

        ax.r2c = function(v) {
            var index = getCategoryPosition(v);
            return index !== undefined ? index : ax.fraction2r(0.5);
        };

        ax.l2r = ax.c2r = ensureNumber;
        ax.r2l = getCategoryPosition;

        ax.d2p = function(v) { return ax.l2p(ax.r2c(v)); };
        ax.p2d = function(px) { return getCategoryName(p2l(px)); };
        ax.r2p = ax.d2p;
        ax.p2r = p2l;

        ax.cleanPos = function(v) {
            if(typeof v === 'string' && v !== '') return v;
            return ensureNumber(v);
        };
    }
    else if(ax.type === 'multicategory') {
        // N.B. multicategory axes don't define d2c and d2l,
        // as 'data-to-calcdata' conversion needs to take into
        // account all data array items as in ax.makeCalcdata.

        ax.r2d = ax.c2d = ax.l2d = getCategoryName;
        ax.d2r = ax.d2l_noadd = getCategoryPosition;

        ax.r2c = function(v) {
            var index = getCategoryPosition(v);
            return index !== undefined ? index : ax.fraction2r(0.5);
        };

        ax.r2c_just_indices = getCategoryIndex;

        ax.l2r = ax.c2r = ensureNumber;
        ax.r2l = getCategoryPosition;

        ax.d2p = function(v) { return ax.l2p(ax.r2c(v)); };
        ax.p2d = function(px) { return getCategoryName(p2l(px)); };
        ax.r2p = ax.d2p;
        ax.p2r = p2l;

        ax.cleanPos = function(v) {
            if(Array.isArray(v) || (typeof v === 'string' && v !== '')) return v;
            return ensureNumber(v);
        };

        ax.setupMultiCategory = function(fullData) {
            var traceIndices = ax._traceIndices;
            var i, j;

            var matchGroups = fullLayout._axisMatchGroups;
            if(matchGroups && matchGroups.length && ax._categories.length === 0) {
                for(i = 0; i < matchGroups.length; i++) {
                    var group = matchGroups[i];
                    if(group[axId]) {
                        for(var axId2 in group) {
                            if(axId2 !== axId) {
                                var ax2 = fullLayout[axisIds.id2name(axId2)];
                                traceIndices = traceIndices.concat(ax2._traceIndices);
                            }
                        }
                    }
                }
            }

            // [ [cnt, {$cat: index}], for 1,2 ]
            var seen = [[0, {}], [0, {}]];
            // [ [arrayIn[0][i], arrayIn[1][i]], for i .. N ]
            var list = [];

            for(i = 0; i < traceIndices.length; i++) {
                var trace = fullData[traceIndices[i]];

                if(axLetter in trace) {
                    var arrayIn = trace[axLetter];
                    var len = trace._length || Lib.minRowLength(arrayIn);

                    if(isArrayOrTypedArray(arrayIn[0]) && isArrayOrTypedArray(arrayIn[1])) {
                        for(j = 0; j < len; j++) {
                            var v0 = arrayIn[0][j];
                            var v1 = arrayIn[1][j];

                            if(isValidCategory(v0) && isValidCategory(v1)) {
                                list.push([v0, v1]);

                                if(!(v0 in seen[0][1])) {
                                    seen[0][1][v0] = seen[0][0]++;
                                }
                                if(!(v1 in seen[1][1])) {
                                    seen[1][1][v1] = seen[1][0]++;
                                }
                            }
                        }
                    }
                }
            }

            list.sort(function(a, b) {
                var ind0 = seen[0][1];
                var d = ind0[a[0]] - ind0[b[0]];
                if(d) return d;

                var ind1 = seen[1][1];
                return ind1[a[1]] - ind1[b[1]];
            });

            for(i = 0; i < list.length; i++) {
                setCategoryIndex(list[i]);
            }
        };
    }

    // find the range value at the specified (linear) fraction of the axis
    ax.fraction2r = function(v) {
        var rl0 = ax.r2l(ax.range[0]);
        var rl1 = ax.r2l(ax.range[1]);
        return ax.l2r(rl0 + v * (rl1 - rl0));
    };

    // find the fraction of the range at the specified range value
    ax.r2fraction = function(v) {
        var rl0 = ax.r2l(ax.range[0]);
        var rl1 = ax.r2l(ax.range[1]);
        return (ax.r2l(v) - rl0) / (rl1 - rl0);
    };

    /*
     * cleanRange: make sure range is a couplet of valid & distinct values
     * keep numbers away from the limits of floating point numbers,
     * and dates away from the ends of our date system (+/- 9999 years)
     *
     * optional param rangeAttr: operate on a different attribute, like
     * ax._r, rather than ax.range
     */
    ax.cleanRange = function(rangeAttr, opts) {
        if(!opts) opts = {};
        if(!rangeAttr) rangeAttr = 'range';

        var range = Lib.nestedProperty(ax, rangeAttr).get();
        var i, dflt;

        if(ax.type === 'date') dflt = Lib.dfltRange(ax.calendar);
        else if(axLetter === 'y') dflt = constants.DFLTRANGEY;
        else dflt = opts.dfltRange || constants.DFLTRANGEX;

        // make sure we don't later mutate the defaults
        dflt = dflt.slice();

        if(!range || range.length !== 2) {
            Lib.nestedProperty(ax, rangeAttr).set(dflt);
            return;
        }

        if(ax.type === 'date') {
            // check if milliseconds or js date objects are provided for range
            // and convert to date strings
            range[0] = Lib.cleanDate(range[0], BADNUM, ax.calendar);
            range[1] = Lib.cleanDate(range[1], BADNUM, ax.calendar);
        }

        for(i = 0; i < 2; i++) {
            if(ax.type === 'date') {
                if(!Lib.isDateTime(range[i], ax.calendar)) {
                    ax[rangeAttr] = dflt;
                    break;
                }

                if(ax.r2l(range[0]) === ax.r2l(range[1])) {
                    // split by +/- 1 second
                    var linCenter = Lib.constrain(ax.r2l(range[0]),
                        Lib.MIN_MS + 1000, Lib.MAX_MS - 1000);
                    range[0] = ax.l2r(linCenter - 1000);
                    range[1] = ax.l2r(linCenter + 1000);
                    break;
                }
            }
            else {
                if(!isNumeric(range[i])) {
                    if(isNumeric(range[1 - i])) {
                        range[i] = range[1 - i] * (i ? 10 : 0.1);
                    }
                    else {
                        ax[rangeAttr] = dflt;
                        break;
                    }
                }

                if(range[i] < -FP_SAFE) range[i] = -FP_SAFE;
                else if(range[i] > FP_SAFE) range[i] = FP_SAFE;

                if(range[0] === range[1]) {
                    // somewhat arbitrary: split by 1 or 1ppm, whichever is bigger
                    var inc = Math.max(1, Math.abs(range[0] * 1e-6));
                    range[0] -= inc;
                    range[1] += inc;
                }
            }
        }
    };

    // set scaling to pixels
    ax.setScale = function(usePrivateRange) {
        var gs = fullLayout._size;

        // make sure we have a domain (pull it in from the axis
        // this one is overlaying if necessary)
        if(ax.overlaying) {
            var ax2 = axisIds.getFromId({ _fullLayout: fullLayout }, ax.overlaying);
            ax.domain = ax2.domain;
        }

        // While transitions are occuring, occurring, we get a double-transform
        // issue if we transform the drawn layer *and* use the new axis range to
        // draw the data. This allows us to construct setConvert using the pre-
        // interaction values of the range:
        var rangeAttr = (usePrivateRange && ax._r) ? '_r' : 'range';
        var calendar = ax.calendar;
        ax.cleanRange(rangeAttr);

        var rl0 = ax.r2l(ax[rangeAttr][0], calendar);
        var rl1 = ax.r2l(ax[rangeAttr][1], calendar);

        if(axLetter === 'y') {
            ax._offset = gs.t + (1 - ax.domain[1]) * gs.h;
            ax._length = gs.h * (ax.domain[1] - ax.domain[0]);
            ax._m = ax._length / (rl0 - rl1);
            ax._b = -ax._m * rl1;
        } else {
            ax._offset = gs.l + ax.domain[0] * gs.w;
            ax._length = gs.w * (ax.domain[1] - ax.domain[0]);
            ax._m = ax._length / (rl1 - rl0);
            ax._b = -ax._m * rl0;
        }

        if(!isFinite(ax._m) || !isFinite(ax._b) || ax._length < 0) {
            fullLayout._replotting = false;
            throw new Error('Something went wrong with axis scaling');
        }
    };

    // makeCalcdata: takes an x or y array and converts it
    // to a position on the axis object "ax"
    // inputs:
    //      trace - a data object from gd.data
    //      axLetter - a string, either 'x' or 'y', for which item
    //          to convert (TODO: is this now always the same as
    //          the first letter of ax._id?)
    // in case the expected data isn't there, make a list of
    // integers based on the opposite data
    ax.makeCalcdata = function(trace, axLetter) {
        var arrayIn, arrayOut, i, len;

        var axType = ax.type;
        var cal = axType === 'date' && trace[axLetter + 'calendar'];

        if(axLetter in trace) {
            arrayIn = trace[axLetter];
            len = trace._length || Lib.minRowLength(arrayIn);

            if(Lib.isTypedArray(arrayIn) && (axType === 'linear' || axType === 'log')) {
                if(len === arrayIn.length) {
                    return arrayIn;
                } else if(arrayIn.subarray) {
                    return arrayIn.subarray(0, len);
                }
            }

            if(axType === 'multicategory') {
                return setMultiCategoryIndex(arrayIn, len);
            }

            arrayOut = new Array(len);
            for(i = 0; i < len; i++) {
                arrayOut[i] = ax.d2c(arrayIn[i], 0, cal);
            }
        }
        else {
            var v0 = ((axLetter + '0') in trace) ? ax.d2c(trace[axLetter + '0'], 0, cal) : 0;
            var dv = (trace['d' + axLetter]) ? Number(trace['d' + axLetter]) : 1;

            // the opposing data, for size if we have x and dx etc
            arrayIn = trace[{x: 'y', y: 'x'}[axLetter]];
            len = trace._length || arrayIn.length;
            arrayOut = new Array(len);

            for(i = 0; i < len; i++) {
                arrayOut[i] = v0 + i * dv;
            }
        }

        return arrayOut;
    };

    ax.isValidRange = function(range) {
        return (
            Array.isArray(range) &&
            range.length === 2 &&
            isNumeric(ax.r2l(range[0])) &&
            isNumeric(ax.r2l(range[1]))
        );
    };

    ax.isPtWithinRange = function(d, calendar) {
        var coord = ax.c2l(d[axLetter], null, calendar);
        var r0 = ax.r2l(ax.range[0]);
        var r1 = ax.r2l(ax.range[1]);

        if(r0 < r1) {
            return r0 <= coord && coord <= r1;
        } else {
            // Reversed axis case.
            return r1 <= coord && coord <= r0;
        }
    };

    // should skip if not category nor multicategory
    ax.clearCalc = function() {
        var emptyCategories = function() {
            ax._categories = [];
            ax._categoriesMap = {};
        };

        var matchGroups = fullLayout._axisMatchGroups;

        if(matchGroups && matchGroups.length) {
            var found = false;

            for(var i = 0; i < matchGroups.length; i++) {
                var group = matchGroups[i];

                if(group[axId]) {
                    found = true;
                    var categories = null;
                    var categoriesMap = null;

                    for(var axId2 in group) {
                        var ax2 = fullLayout[axisIds.id2name(axId2)];
                        if(ax2._categories) {
                            categories = ax2._categories;
                            categoriesMap = ax2._categoriesMap;
                            break;
                        }
                    }

                    if(categories && categoriesMap) {
                        ax._categories = categories;
                        ax._categoriesMap = categoriesMap;
                    } else {
                        emptyCategories();
                    }
                    break;
                }
            }
            if(!found) emptyCategories();
        } else {
            emptyCategories();
        }

        if(ax._initialCategories) {
            for(var j = 0; j < ax._initialCategories.length; j++) {
                setCategoryIndex(ax._initialCategories[j]);
            }
        }
    };

    // Propagate localization into the axis so that
    // methods in Axes can use it w/o having to pass fullLayout
    // Default (non-d3) number formatting uses separators directly
    // dates and d3-formatted numbers use the d3 locale
    // Fall back on default format for dummy axes that don't care about formatting
    var locale = fullLayout._d3locale;
    if(ax.type === 'date') {
        ax._dateFormat = locale ? locale.timeFormat.utc : d3.time.format.utc;
        ax._extraFormat = fullLayout._extraFormat;
    }
    // occasionally we need _numFormat to pass through
    // even though it won't be needed by this axis
    ax._separators = fullLayout.separators;
    ax._numFormat = locale ? locale.numberFormat : d3.format;

    // and for bar charts and box plots: reset forced minimum tick spacing
    delete ax._minDtick;
    delete ax._forceTick0;
};

},{"../../constants/numerical":674,"../../lib":697,"./axis_ids":748,"./constants":751,"d3":151,"fast-isnumeric":218}],764:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var layoutAttributes = _dereq_('./layout_attributes');
var handleArrayContainerDefaults = _dereq_('../array_container_defaults');

module.exports = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options) {
    var showAttrDflt = getShowAttrDflt(containerIn);

    var tickPrefix = coerce('tickprefix');
    if(tickPrefix) coerce('showtickprefix', showAttrDflt);

    var tickSuffix = coerce('ticksuffix', options.tickSuffixDflt);
    if(tickSuffix) coerce('showticksuffix', showAttrDflt);

    var showTickLabels = coerce('showticklabels');
    if(showTickLabels) {
        var font = options.font || {};
        var contColor = containerOut.color;
        // as with titlefont.color, inherit axis.color only if one was
        // explicitly provided
        var dfltFontColor = (contColor && contColor !== layoutAttributes.color.dflt) ?
            contColor : font.color;
        Lib.coerceFont(coerce, 'tickfont', {
            family: font.family,
            size: font.size,
            color: dfltFontColor
        });
        coerce('tickangle');

        if(axType !== 'category') {
            var tickFormat = coerce('tickformat');
            var tickformatStops = containerIn.tickformatstops;
            if(Array.isArray(tickformatStops) && tickformatStops.length) {
                handleArrayContainerDefaults(containerIn, containerOut, {
                    name: 'tickformatstops',
                    inclusionAttr: 'enabled',
                    handleItemDefaults: tickformatstopDefaults
                });
            }
            if(!tickFormat && axType !== 'date') {
                coerce('showexponent', showAttrDflt);
                coerce('exponentformat');
                coerce('separatethousands');
            }
        }
    }
};

/*
 * Attributes 'showexponent', 'showtickprefix' and 'showticksuffix'
 * share values.
 *
 * If only 1 attribute is set,
 * the remaining attributes inherit that value.
 *
 * If 2 attributes are set to the same value,
 * the remaining attribute inherits that value.
 *
 * If 2 attributes are set to different values,
 * the remaining is set to its dflt value.
 *
 */
function getShowAttrDflt(containerIn) {
    var showAttrsAll = ['showexponent', 'showtickprefix', 'showticksuffix'];
    var showAttrs = showAttrsAll.filter(function(a) {
        return containerIn[a] !== undefined;
    });
    var sameVal = function(a) {
        return containerIn[a] === containerIn[showAttrs[0]];
    };

    if(showAttrs.every(sameVal) || showAttrs.length === 1) {
        return containerIn[showAttrs[0]];
    }
}

function tickformatstopDefaults(valueIn, valueOut) {
    function coerce(attr, dflt) {
        return Lib.coerce(valueIn, valueOut, layoutAttributes.tickformatstops, attr, dflt);
    }

    var enabled = coerce('enabled');
    if(enabled) {
        coerce('dtickrange');
        coerce('value');
    }
}

},{"../../lib":697,"../array_container_defaults":741,"./layout_attributes":757}],765:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

var layoutAttributes = _dereq_('./layout_attributes');


/**
 * options: inherits outerTicks from axes.handleAxisDefaults
 */
module.exports = function handleTickDefaults(containerIn, containerOut, coerce, options) {
    var tickLen = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'ticklen');
    var tickWidth = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'tickwidth');
    var tickColor = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'tickcolor', containerOut.color);
    var showTicks = coerce('ticks', (options.outerTicks || tickLen || tickWidth || tickColor) ? 'outside' : '');

    if(!showTicks) {
        delete containerOut.ticklen;
        delete containerOut.tickwidth;
        delete containerOut.tickcolor;
    }
};

},{"../../lib":697,"./layout_attributes":757}],766:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var cleanTicks = _dereq_('./clean_ticks');

module.exports = function handleTickValueDefaults(containerIn, containerOut, coerce, axType) {
    var tickmode;

    if(containerIn.tickmode === 'array' &&
            (axType === 'log' || axType === 'date')) {
        tickmode = containerOut.tickmode = 'auto';
    } else {
        var tickmodeDefault = Array.isArray(containerIn.tickvals) ? 'array' :
            containerIn.dtick ? 'linear' :
            'auto';
        tickmode = coerce('tickmode', tickmodeDefault);
    }

    if(tickmode === 'auto') coerce('nticks');
    else if(tickmode === 'linear') {
        // dtick is usually a positive number, but there are some
        // special strings available for log or date axes
        // tick0 also has special logic
        var dtick = containerOut.dtick = cleanTicks.dtick(
            containerIn.dtick, axType);
        containerOut.tick0 = cleanTicks.tick0(
            containerIn.tick0, axType, containerOut.calendar, dtick);
    } else if(axType !== 'multicategory') {
        var tickvals = coerce('tickvals');
        if(tickvals === undefined) containerOut.tickmode = 'auto';
        else coerce('ticktext');
    }
};

},{"./clean_ticks":750}],767:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Registry = _dereq_('../../registry');
var Drawing = _dereq_('../../components/drawing');
var Axes = _dereq_('./axes');

/**
 * transitionAxes
 *
 * transition axes from one set of ranges to another, using a svg
 * transformations, similar to during panning.
 *
 * @param {DOM element | object} gd
 * @param {array} edits : array of 'edits', each item with
 * - plotinfo {object} subplot object
 * - xr0 {array} initial x-range
 * - xr1 {array} end x-range
 * - yr0 {array} initial y-range
 * - yr1 {array} end y-range
 * @param {object} transitionOpts
 * @param {function} makeOnCompleteCallback
 */
module.exports = function transitionAxes(gd, edits, transitionOpts, makeOnCompleteCallback) {
    var fullLayout = gd._fullLayout;

    // special case for redraw:false Plotly.animate that relies on this
    // to update axis-referenced layout components
    if(edits.length === 0) {
        Axes.redrawComponents(gd);
        return;
    }

    function unsetSubplotTransform(subplot) {
        var xa = subplot.xaxis;
        var ya = subplot.yaxis;

        fullLayout._defs.select('#' + subplot.clipId + '> rect')
            .call(Drawing.setTranslate, 0, 0)
            .call(Drawing.setScale, 1, 1);

        subplot.plot
            .call(Drawing.setTranslate, xa._offset, ya._offset)
            .call(Drawing.setScale, 1, 1);

        var traceGroups = subplot.plot.selectAll('.scatterlayer .trace');

        // This is specifically directed at scatter traces, applying an inverse
        // scale to individual points to counteract the scale of the trace
        // as a whole:
        traceGroups.selectAll('.point')
            .call(Drawing.setPointGroupScale, 1, 1);
        traceGroups.selectAll('.textpoint')
            .call(Drawing.setTextPointsScale, 1, 1);
        traceGroups
            .call(Drawing.hideOutsideRangePoints, subplot);
    }

    function updateSubplot(edit, progress) {
        var plotinfo = edit.plotinfo;
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;

        var xr0 = edit.xr0;
        var xr1 = edit.xr1;
        var xlen = xa._length;
        var yr0 = edit.yr0;
        var yr1 = edit.yr1;
        var ylen = ya._length;

        var editX = !!xr1;
        var editY = !!yr1;
        var viewBox = [];

        if(editX) {
            var dx0 = xr0[1] - xr0[0];
            var dx1 = xr1[1] - xr1[0];
            viewBox[0] = (xr0[0] * (1 - progress) + progress * xr1[0] - xr0[0]) / (xr0[1] - xr0[0]) * xlen;
            viewBox[2] = xlen * ((1 - progress) + progress * dx1 / dx0);
            xa.range[0] = xr0[0] * (1 - progress) + progress * xr1[0];
            xa.range[1] = xr0[1] * (1 - progress) + progress * xr1[1];
        } else {
            viewBox[0] = 0;
            viewBox[2] = xlen;
        }

        if(editY) {
            var dy0 = yr0[1] - yr0[0];
            var dy1 = yr1[1] - yr1[0];
            viewBox[1] = (yr0[1] * (1 - progress) + progress * yr1[1] - yr0[1]) / (yr0[0] - yr0[1]) * ylen;
            viewBox[3] = ylen * ((1 - progress) + progress * dy1 / dy0);
            ya.range[0] = yr0[0] * (1 - progress) + progress * yr1[0];
            ya.range[1] = yr0[1] * (1 - progress) + progress * yr1[1];
        } else {
            viewBox[1] = 0;
            viewBox[3] = ylen;
        }

        Axes.drawOne(gd, xa, {skipTitle: true});
        Axes.drawOne(gd, ya, {skipTitle: true});
        Axes.redrawComponents(gd, [xa._id, ya._id]);

        var xScaleFactor = editX ? xlen / viewBox[2] : 1;
        var yScaleFactor = editY ? ylen / viewBox[3] : 1;
        var clipDx = editX ? viewBox[0] : 0;
        var clipDy = editY ? viewBox[1] : 0;
        var fracDx = editX ? (viewBox[0] / viewBox[2] * xlen) : 0;
        var fracDy = editY ? (viewBox[1] / viewBox[3] * ylen) : 0;
        var plotDx = xa._offset - fracDx;
        var plotDy = ya._offset - fracDy;

        plotinfo.clipRect
            .call(Drawing.setTranslate, clipDx, clipDy)
            .call(Drawing.setScale, 1 / xScaleFactor, 1 / yScaleFactor);

        plotinfo.plot
            .call(Drawing.setTranslate, plotDx, plotDy)
            .call(Drawing.setScale, xScaleFactor, yScaleFactor);

        // apply an inverse scale to individual points to counteract
        // the scale of the trace group.
        Drawing.setPointGroupScale(plotinfo.zoomScalePts, 1 / xScaleFactor, 1 / yScaleFactor);
        Drawing.setTextPointsScale(plotinfo.zoomScaleTxt, 1 / xScaleFactor, 1 / yScaleFactor);
    }

    var onComplete;
    if(makeOnCompleteCallback) {
        // This module makes the choice whether or not it notifies Plotly.transition
        // about completion:
        onComplete = makeOnCompleteCallback();
    }

    function transitionComplete() {
        var aobj = {};

        for(var i = 0; i < edits.length; i++) {
            var edit = edits[i];
            if(edit.xr1) aobj[edit.plotinfo.xaxis._name + '.range'] = edit.xr1.slice();
            if(edit.yr1) aobj[edit.plotinfo.yaxis._name + '.range'] = edit.yr1.slice();
        }

        // Signal that this transition has completed:
        onComplete && onComplete();

        return Registry.call('relayout', gd, aobj).then(function() {
            for(var i = 0; i < edits.length; i++) {
                unsetSubplotTransform(edits[i].plotinfo);
            }
        });
    }

    function transitionInterrupt() {
        var aobj = {};

        for(var i = 0; i < edits.length; i++) {
            var edit = edits[i];
            if(edit.xr0) aobj[edit.plotinfo.xaxis._name + '.range'] = edit.xr0.slice();
            if(edit.yr0) aobj[edit.plotinfo.yaxis._name + '.range'] = edit.yr0.slice();
        }

        return Registry.call('relayout', gd, aobj).then(function() {
            for(var i = 0; i < edits.length; i++) {
                unsetSubplotTransform(edits[i].plotinfo);
            }
        });
    }

    var t1, t2, raf;
    var easeFn = d3.ease(transitionOpts.easing);

    gd._transitionData._interruptCallbacks.push(function() {
        window.cancelAnimationFrame(raf);
        raf = null;
        return transitionInterrupt();
    });

    function doFrame() {
        t2 = Date.now();

        var tInterp = Math.min(1, (t2 - t1) / transitionOpts.duration);
        var progress = easeFn(tInterp);

        for(var i = 0; i < edits.length; i++) {
            updateSubplot(edits[i], progress);
        }

        if(t2 - t1 > transitionOpts.duration) {
            transitionComplete();
            raf = window.cancelAnimationFrame(doFrame);
        } else {
            raf = window.requestAnimationFrame(doFrame);
        }
    }

    t1 = Date.now();
    raf = window.requestAnimationFrame(doFrame);

    return Promise.resolve();
};

},{"../../components/drawing":595,"../../registry":826,"./axes":745,"d3":151}],768:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var traceIs = _dereq_('../../registry').traceIs;
var autoType = _dereq_('./axis_autotype');

/*
 *  data: the plot data to use in choosing auto type
 *  name: axis object name (ie 'xaxis') if one should be stored
 */
module.exports = function handleTypeDefaults(containerIn, containerOut, coerce, options) {
    var axType = coerce('type', (options.splomStash || {}).type);

    if(axType === '-') {
        setAutoType(containerOut, options.data);

        if(containerOut.type === '-') {
            containerOut.type = 'linear';
        } else {
            // copy autoType back to input axis
            // note that if this object didn't exist
            // in the input layout, we have to put it in
            // this happens in the main supplyDefaults function
            containerIn.type = containerOut.type;
        }
    }
};

function setAutoType(ax, data) {
    // new logic: let people specify any type they want,
    // only autotype if type is '-'
    if(ax.type !== '-') return;

    var id = ax._id;
    var axLetter = id.charAt(0);

    // support 3d
    if(id.indexOf('scene') !== -1) id = axLetter;

    var d0 = getFirstNonEmptyTrace(data, id, axLetter);
    if(!d0) return;

    // first check for histograms, as the count direction
    // should always default to a linear axis
    if(d0.type === 'histogram' &&
            axLetter === {v: 'y', h: 'x'}[d0.orientation || 'v']) {
        ax.type = 'linear';
        return;
    }

    var calAttr = axLetter + 'calendar';
    var calendar = d0[calAttr];
    var opts = {noMultiCategory: !traceIs(d0, 'cartesian') || traceIs(d0, 'noMultiCategory')};
    var i;

    // check all boxes on this x axis to see
    // if they're dates, numbers, or categories
    if(isBoxWithoutPositionCoords(d0, axLetter)) {
        var posLetter = getBoxPosLetter(d0);
        var boxPositions = [];

        for(i = 0; i < data.length; i++) {
            var trace = data[i];
            if(!traceIs(trace, 'box-violin') || (trace[axLetter + 'axis'] || axLetter) !== id) continue;

            if(trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]);
            else if(trace.name !== undefined) boxPositions.push(trace.name);
            else boxPositions.push('text');

            if(trace[calAttr] !== calendar) calendar = undefined;
        }

        ax.type = autoType(boxPositions, calendar, opts);
    }
    else if(d0.type === 'splom') {
        var dimensions = d0.dimensions;
        var diag = d0._diag;
        for(i = 0; i < dimensions.length; i++) {
            var dim = dimensions[i];
            if(dim.visible && (diag[i][0] === id || diag[i][1] === id)) {
                ax.type = autoType(dim.values, calendar, opts);
                break;
            }
        }
    }
    else {
        ax.type = autoType(d0[axLetter] || [d0[axLetter + '0']], calendar, opts);
    }
}

function getFirstNonEmptyTrace(data, id, axLetter) {
    for(var i = 0; i < data.length; i++) {
        var trace = data[i];

        if(trace.type === 'splom' &&
                trace._length > 0 &&
                (trace['_' + axLetter + 'axes'] || {})[id]
        ) {
            return trace;
        }

        if((trace[axLetter + 'axis'] || axLetter) === id) {
            if(isBoxWithoutPositionCoords(trace, axLetter)) {
                return trace;
            }
            else if((trace[axLetter] || []).length || trace[axLetter + '0']) {
                return trace;
            }
        }
    }
}

function getBoxPosLetter(trace) {
    return {v: 'x', h: 'y'}[trace.orientation || 'v'];
}

function isBoxWithoutPositionCoords(trace, axLetter) {
    var posLetter = getBoxPosLetter(trace);
    var isBox = traceIs(trace, 'box-violin');
    var isCandlestick = traceIs(trace._fullInput || {}, 'candlestick');

    return (
        isBox &&
        !isCandlestick &&
        axLetter === posLetter &&
        trace[posLetter] === undefined &&
        trace[posLetter + '0'] === undefined
    );
}

},{"../../registry":826,"./axis_autotype":746}],769:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../registry');
var Lib = _dereq_('../lib');

/*
 * Create or update an observer. This function is designed to be
 * idempotent so that it can be called over and over as the component
 * updates, and will attach and detach listeners as needed.
 *
 * @param {optional object} container
 *      An object on which the observer is stored. This is the mechanism
 *      by which it is idempotent. If it already exists, another won't be
 *      added. Each time it's called, the value lookup table is updated.
 * @param {array} commandList
 *      An array of commands, following either `buttons` of `updatemenus`
 *      or `steps` of `sliders`.
 * @param {function} onchange
 *      A listener called when the value is changed. Receives data object
 *      with information about the new state.
 */
exports.manageCommandObserver = function(gd, container, commandList, onchange) {
    var ret = {};
    var enabled = true;

    if(container && container._commandObserver) {
        ret = container._commandObserver;
    }

    if(!ret.cache) {
        ret.cache = {};
    }

    // Either create or just recompute this:
    ret.lookupTable = {};

    var binding = exports.hasSimpleAPICommandBindings(gd, commandList, ret.lookupTable);

    if(container && container._commandObserver) {
        if(!binding) {
            // If container exists and there are no longer any bindings,
            // remove existing:
            if(container._commandObserver.remove) {
                container._commandObserver.remove();
                container._commandObserver = null;
                return ret;
            }
        } else {
            // If container exists and there *are* bindings, then the lookup
            // table should have been updated and check is already attached,
            // so there's nothing to be done:
            return ret;


        }
    }

    // Determine whether there's anything to do for this binding:

    if(binding) {
        // Build the cache:
        bindingValueHasChanged(gd, binding, ret.cache);

        ret.check = function check() {
            if(!enabled) return;

            var update = bindingValueHasChanged(gd, binding, ret.cache);

            if(update.changed && onchange) {
                // Disable checks for the duration of this command in order to avoid
                // infinite loops:
                if(ret.lookupTable[update.value] !== undefined) {
                    ret.disable();
                    Promise.resolve(onchange({
                        value: update.value,
                        type: binding.type,
                        prop: binding.prop,
                        traces: binding.traces,
                        index: ret.lookupTable[update.value]
                    })).then(ret.enable, ret.enable);
                }
            }

            return update.changed;
        };

        var checkEvents = [
            'plotly_relayout',
            'plotly_redraw',
            'plotly_restyle',
            'plotly_update',
            'plotly_animatingframe',
            'plotly_afterplot'
        ];

        for(var i = 0; i < checkEvents.length; i++) {
            gd._internalOn(checkEvents[i], ret.check);
        }

        ret.remove = function() {
            for(var i = 0; i < checkEvents.length; i++) {
                gd._removeInternalListener(checkEvents[i], ret.check);
            }
        };
    } else {
        // TODO: It'd be really neat to actually give a *reason* for this, but at least a warning
        // is a start
        Lib.log('Unable to automatically bind plot updates to API command');

        ret.lookupTable = {};
        ret.remove = function() {};
    }

    ret.disable = function disable() {
        enabled = false;
    };

    ret.enable = function enable() {
        enabled = true;
    };

    if(container) {
        container._commandObserver = ret;
    }

    return ret;
};

/*
 * This function checks to see if an array of objects containing
 * method and args properties is compatible with automatic two-way
 * binding. The criteria right now are that
 *
 *   1. multiple traces may be affected
 *   2. only one property may be affected
 *   3. the same property must be affected by all commands
 */
exports.hasSimpleAPICommandBindings = function(gd, commandList, bindingsByValue) {
    var i;
    var n = commandList.length;

    var refBinding;

    for(i = 0; i < n; i++) {
        var binding;
        var command = commandList[i];
        var method = command.method;
        var args = command.args;

        if(!Array.isArray(args)) args = [];

        // If any command has no method, refuse to bind:
        if(!method) {
            return false;
        }
        var bindings = exports.computeAPICommandBindings(gd, method, args);

        // Right now, handle one and *only* one property being set:
        if(bindings.length !== 1) {
            return false;
        }

        if(!refBinding) {
            refBinding = bindings[0];
            if(Array.isArray(refBinding.traces)) {
                refBinding.traces.sort();
            }
        } else {
            binding = bindings[0];
            if(binding.type !== refBinding.type) {
                return false;
            }
            if(binding.prop !== refBinding.prop) {
                return false;
            }
            if(Array.isArray(refBinding.traces)) {
                if(Array.isArray(binding.traces)) {
                    binding.traces.sort();
                    for(var j = 0; j < refBinding.traces.length; j++) {
                        if(refBinding.traces[j] !== binding.traces[j]) {
                            return false;
                        }
                    }
                } else {
                    return false;
                }
            } else {
                if(binding.prop !== refBinding.prop) {
                    return false;
                }
            }
        }

        binding = bindings[0];
        var value = binding.value;
        if(Array.isArray(value)) {
            if(value.length === 1) {
                value = value[0];
            } else {
                return false;
            }
        }
        if(bindingsByValue) {
            bindingsByValue[value] = i;
        }
    }

    return refBinding;
};

function bindingValueHasChanged(gd, binding, cache) {
    var container, value, obj;
    var changed = false;

    if(binding.type === 'data') {
        // If it's data, we need to get a trace. Based on the limited scope
        // of what we cover, we can just take the first trace from the list,
        // or otherwise just the first trace:
        container = gd._fullData[binding.traces !== null ? binding.traces[0] : 0];
    } else if(binding.type === 'layout') {
        container = gd._fullLayout;
    } else {
        return false;
    }

    value = Lib.nestedProperty(container, binding.prop).get();

    obj = cache[binding.type] = cache[binding.type] || {};

    if(obj.hasOwnProperty(binding.prop)) {
        if(obj[binding.prop] !== value) {
            changed = true;
        }
    }

    obj[binding.prop] = value;

    return {
        changed: changed,
        value: value
    };
}

/*
 * Execute an API command. There's really not much to this; it just provides
 * a common hook so that implementations don't need to be synchronized across
 * multiple components with the ability to invoke API commands.
 *
 * @param {string} method
 *      The name of the plotly command to execute. Must be one of 'animate',
 *      'restyle', 'relayout', 'update'.
 * @param {array} args
 *      A list of arguments passed to the API command
 */
exports.executeAPICommand = function(gd, method, args) {
    if(method === 'skip') return Promise.resolve();

    var _method = Registry.apiMethodRegistry[method];
    var allArgs = [gd];
    if(!Array.isArray(args)) args = [];

    for(var i = 0; i < args.length; i++) {
        allArgs.push(args[i]);
    }

    return _method.apply(null, allArgs).catch(function(err) {
        Lib.warn('API call to Plotly.' + method + ' rejected.', err);
        return Promise.reject(err);
    });
};

exports.computeAPICommandBindings = function(gd, method, args) {
    var bindings;

    if(!Array.isArray(args)) args = [];

    switch(method) {
        case 'restyle':
            bindings = computeDataBindings(gd, args);
            break;
        case 'relayout':
            bindings = computeLayoutBindings(gd, args);
            break;
        case 'update':
            bindings = computeDataBindings(gd, [args[0], args[2]])
                .concat(computeLayoutBindings(gd, [args[1]]));
            break;
        case 'animate':
            bindings = computeAnimateBindings(gd, args);
            break;
        default:
            // This is the case where intelligent logic about what affects
            // this command is not implemented. It causes no ill effects.
            // For example, addFrames simply won't bind to a control component.
            bindings = [];
    }
    return bindings;
};

function computeAnimateBindings(gd, args) {
    // We'll assume that the only relevant modification an animation
    // makes that's meaningfully tracked is the frame:
    if(Array.isArray(args[0]) && args[0].length === 1 && ['string', 'number'].indexOf(typeof args[0][0]) !== -1) {
        return [{type: 'layout', prop: '_currentFrame', value: args[0][0].toString()}];
    } else {
        return [];
    }
}

function computeLayoutBindings(gd, args) {
    var bindings = [];

    var astr = args[0];
    var aobj = {};
    if(typeof astr === 'string') {
        aobj[astr] = args[1];
    } else if(Lib.isPlainObject(astr)) {
        aobj = astr;
    } else {
        return bindings;
    }

    crawl(aobj, function(path, attrName, attr) {
        bindings.push({type: 'layout', prop: path, value: attr});
    }, '', 0);

    return bindings;
}

function computeDataBindings(gd, args) {
    var traces, astr, val, aobj;
    var bindings = [];

    // Logic copied from Plotly.restyle:
    astr = args[0];
    val = args[1];
    traces = args[2];
    aobj = {};
    if(typeof astr === 'string') {
        aobj[astr] = val;
    } else if(Lib.isPlainObject(astr)) {
        // the 3-arg form
        aobj = astr;

        if(traces === undefined) {
            traces = val;
        }
    } else {
        return bindings;
    }

    if(traces === undefined) {
        // Explicitly assign this to null instead of undefined:
        traces = null;
    }

    crawl(aobj, function(path, attrName, attr) {
        var thisTraces;
        if(Array.isArray(attr)) {
            var nAttr = Math.min(attr.length, gd.data.length);
            if(traces) {
                nAttr = Math.min(nAttr, traces.length);
            }
            thisTraces = [];
            for(var j = 0; j < nAttr; j++) {
                thisTraces[j] = traces ? traces[j] : j;
            }
        } else {
            thisTraces = traces ? traces.slice(0) : null;
        }

        // Convert [7] to just 7 when traces is null:
        if(thisTraces === null) {
            if(Array.isArray(attr)) {
                attr = attr[0];
            }
        } else if(Array.isArray(thisTraces)) {
            if(!Array.isArray(attr)) {
                var tmp = attr;
                attr = [];
                for(var i = 0; i < thisTraces.length; i++) {
                    attr[i] = tmp;
                }
            }
            attr.length = Math.min(thisTraces.length, attr.length);
        }

        bindings.push({
            type: 'data',
            prop: path,
            traces: thisTraces,
            value: attr
        });
    }, '', 0);

    return bindings;
}

function crawl(attrs, callback, path, depth) {
    Object.keys(attrs).forEach(function(attrName) {
        var attr = attrs[attrName];

        if(attrName[0] === '_') return;

        var thisPath = path + (depth > 0 ? '.' : '') + attrName;

        if(Lib.isPlainObject(attr)) {
            crawl(attr, callback, thisPath, depth + 1);
        } else {
            // Only execute the callback on leaf nodes:
            callback(thisPath, attrName, attr);
        }
    });
}

},{"../lib":697,"../registry":826}],770:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var extendFlat = _dereq_('../lib/extend').extendFlat;

/**
 * Make a xy domain attribute group
 *
 * @param {object} opts
 *   @param {string}
 *     opts.name: name to be inserted in the default description
 *   @param {boolean}
 *     opts.trace: set to true for trace containers
 *   @param {string}
 *     opts.editType: editType for all pieces
 *   @param {boolean}
 *     opts.noGridCell: set to true to omit `row` and `column`
 *
 * @param {object} extra
 *   @param {string}
 *     extra.description: extra description. N.B we use
 *     a separate extra container to make it compatible with
 *     the compress_attributes transform.
 *
 * @return {object} attributes object containing {x,y} as specified
 */
exports.attributes = function(opts, extra) {
    opts = opts || {};
    extra = extra || {};

    var base = {
        valType: 'info_array',
        
        editType: opts.editType,
        items: [
            {valType: 'number', min: 0, max: 1, editType: opts.editType},
            {valType: 'number', min: 0, max: 1, editType: opts.editType}
        ],
        dflt: [0, 1]
    };

    var namePart = opts.name ? opts.name + ' ' : '';
    var contPart = opts.trace ? 'trace ' : 'subplot ';
    var descPart = extra.description ? ' ' + extra.description : '';

    var out = {
        x: extendFlat({}, base, {
            
        }),
        y: extendFlat({}, base, {
            
        }),
        editType: opts.editType
    };

    if(!opts.noGridCell) {
        out.row = {
            valType: 'integer',
            min: 0,
            dflt: 0,
            
            editType: opts.editType,
            
        };
        out.column = {
            valType: 'integer',
            min: 0,
            dflt: 0,
            
            editType: opts.editType,
            
        };
    }

    return out;
};

exports.defaults = function(containerOut, layout, coerce, dfltDomains) {
    var dfltX = (dfltDomains && dfltDomains.x) || [0, 1];
    var dfltY = (dfltDomains && dfltDomains.y) || [0, 1];

    var grid = layout.grid;
    if(grid) {
        var column = coerce('domain.column');
        if(column !== undefined) {
            if(column < grid.columns) dfltX = grid._domains.x[column];
            else delete containerOut.domain.column;
        }

        var row = coerce('domain.row');
        if(row !== undefined) {
            if(row < grid.rows) dfltY = grid._domains.y[row];
            else delete containerOut.domain.row;
        }
    }

    coerce('domain.x', dfltX);
    coerce('domain.y', dfltY);
};

},{"../lib/extend":687}],771:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/*
 * make a font attribute group
 *
 * @param {object} opts
 *   @param {string}
 *     opts.description: where & how this font is used
 *   @param {optional bool} arrayOk:
 *     should each part (family, size, color) be arrayOk? default false.
 *   @param {string} editType:
 *     the editType for all pieces of this font
 *   @param {optional string} colorEditType:
 *     a separate editType just for color
 *
 * @return {object} attributes object containing {family, size, color} as specified
 */
module.exports = function(opts) {
    var editType = opts.editType;
    var colorEditType = opts.colorEditType;
    if(colorEditType === undefined) colorEditType = editType;
    var attrs = {
        family: {
            valType: 'string',
            
            noBlank: true,
            strict: true,
            editType: editType,
            
        },
        size: {
            valType: 'number',
            
            min: 1,
            editType: editType
        },
        color: {
            valType: 'color',
            
            editType: colorEditType
        },
        editType: editType,
        // blank strings so compress_attributes can remove
        // TODO - that's uber hacky... better solution?
        
    };

    if(opts.arrayOk) {
        attrs.family.arrayOk = true;
        attrs.size.arrayOk = true;
        attrs.color.arrayOk = true;
    }

    return attrs;
};

},{}],772:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    _isLinkedToArray: 'frames_entry',

    group: {
        valType: 'string',
        
        
    },
    name: {
        valType: 'string',
        
        
    },
    traces: {
        valType: 'any',
        
        
    },
    baseframe: {
        valType: 'string',
        
        
    },
    data: {
        valType: 'any',
        
        
    },
    layout: {
        valType: 'any',
        
        
    }
};

},{}],773:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// projection names to d3 function name
exports.projNames = {
    // d3.geo.projection
    'equirectangular': 'equirectangular',
    'mercator': 'mercator',
    'orthographic': 'orthographic',
    'natural earth': 'naturalEarth',
    'kavrayskiy7': 'kavrayskiy7',
    'miller': 'miller',
    'robinson': 'robinson',
    'eckert4': 'eckert4',
    'azimuthal equal area': 'azimuthalEqualArea',
    'azimuthal equidistant': 'azimuthalEquidistant',
    'conic equal area': 'conicEqualArea',
    'conic conformal': 'conicConformal',
    'conic equidistant': 'conicEquidistant',
    'gnomonic': 'gnomonic',
    'stereographic': 'stereographic',
    'mollweide': 'mollweide',
    'hammer': 'hammer',
    'transverse mercator': 'transverseMercator',
    'albers usa': 'albersUsa',
    'winkel tripel': 'winkel3',
    'aitoff': 'aitoff',
    'sinusoidal': 'sinusoidal'
};

// name of the axes
exports.axesNames = ['lonaxis', 'lataxis'];

// max longitudinal angular span (EXPERIMENTAL)
exports.lonaxisSpan = {
    'orthographic': 180,
    'azimuthal equal area': 360,
    'azimuthal equidistant': 360,
    'conic conformal': 180,
    'gnomonic': 160,
    'stereographic': 180,
    'transverse mercator': 180,
    '*': 360
};

// max latitudinal angular span (EXPERIMENTAL)
exports.lataxisSpan = {
    'conic conformal': 150,
    'stereographic': 179.5,
    '*': 180
};

// defaults for each scope
exports.scopeDefaults = {
    world: {
        lonaxisRange: [-180, 180],
        lataxisRange: [-90, 90],
        projType: 'equirectangular',
        projRotate: [0, 0, 0]
    },
    usa: {
        lonaxisRange: [-180, -50],
        lataxisRange: [15, 80],
        projType: 'albers usa'
    },
    europe: {
        lonaxisRange: [-30, 60],
        lataxisRange: [30, 85],
        projType: 'conic conformal',
        projRotate: [15, 0, 0],
        projParallels: [0, 60]
    },
    asia: {
        lonaxisRange: [22, 160],
        lataxisRange: [-15, 55],
        projType: 'mercator',
        projRotate: [0, 0, 0]
    },
    africa: {
        lonaxisRange: [-30, 60],
        lataxisRange: [-40, 40],
        projType: 'mercator',
        projRotate: [0, 0, 0]
    },
    'north america': {
        lonaxisRange: [-180, -45],
        lataxisRange: [5, 85],
        projType: 'conic conformal',
        projRotate: [-100, 0, 0],
        projParallels: [29.5, 45.5]
    },
    'south america': {
        lonaxisRange: [-100, -30],
        lataxisRange: [-60, 15],
        projType: 'mercator',
        projRotate: [0, 0, 0]
    }
};

// angular pad to avoid rounding error around clip angles
exports.clipPad = 1e-3;

// map projection precision
exports.precision = 0.1;

// default land and water fill colors
exports.landColor = '#F0DC82';
exports.waterColor = '#3399FF';

// locationmode to layer name
exports.locationmodeToLayer = {
    'ISO-3': 'countries',
    'USA-states': 'subunits',
    'country names': 'countries'
};

// SVG element for a sphere (use to frame maps)
exports.sphereSVG = {type: 'Sphere'};

// N.B. base layer names must be the same as in the topojson files

// base layer with a fill color
exports.fillLayers = {
    ocean: 1,
    land: 1,
    lakes: 1
};

// base layer with a only a line color
exports.lineLayers = {
    subunits: 1,
    countries: 1,
    coastlines: 1,
    rivers: 1,
    frame: 1
};

exports.layers = [
    'bg',
    'ocean', 'land', 'lakes',
    'subunits', 'countries', 'coastlines', 'rivers',
    'lataxis', 'lonaxis', 'frame',
    'backplot',
    'frontplot'
];

exports.layersForChoropleth = [
    'bg',
    'ocean', 'land',
    'subunits', 'countries', 'coastlines',
    'lataxis', 'lonaxis', 'frame',
    'backplot',
    'rivers', 'lakes',
    'frontplot'
];

exports.layerNameToAdjective = {
    ocean: 'ocean',
    land: 'land',
    lakes: 'lake',
    subunits: 'subunit',
    countries: 'country',
    coastlines: 'coastline',
    rivers: 'river',
    frame: 'frame'
};

},{}],774:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/* global PlotlyGeoAssets:false */

var d3 = _dereq_('d3');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Color = _dereq_('../../components/color');
var Drawing = _dereq_('../../components/drawing');
var Fx = _dereq_('../../components/fx');
var Plots = _dereq_('../plots');
var Axes = _dereq_('../cartesian/axes');
var dragElement = _dereq_('../../components/dragelement');
var prepSelect = _dereq_('../cartesian/select').prepSelect;
var selectOnClick = _dereq_('../cartesian/select').selectOnClick;

var createGeoZoom = _dereq_('./zoom');
var constants = _dereq_('./constants');

var topojsonUtils = _dereq_('../../lib/topojson_utils');
var topojsonFeature = _dereq_('topojson-client').feature;

_dereq_('./projections')(d3);

function Geo(opts) {
    this.id = opts.id;
    this.graphDiv = opts.graphDiv;
    this.container = opts.container;
    this.topojsonURL = opts.topojsonURL;
    this.isStatic = opts.staticPlot;

    this.topojsonName = null;
    this.topojson = null;

    this.projection = null;
    this.viewInitial = null;
    this.fitScale = null;
    this.bounds = null;
    this.midPt = null;

    this.hasChoropleth = false;
    this.traceHash = {};

    this.layers = {};
    this.basePaths = {};
    this.dataPaths = {};
    this.dataPoints = {};

    this.clipDef = null;
    this.clipRect = null;
    this.bgRect = null;

    this.makeFramework();
}

var proto = Geo.prototype;

module.exports = function createGeo(opts) {
    return new Geo(opts);
};

proto.plot = function(geoCalcData, fullLayout, promises) {
    var _this = this;
    var geoLayout = fullLayout[this.id];
    var topojsonNameNew = topojsonUtils.getTopojsonName(geoLayout);

    if(_this.topojson === null || topojsonNameNew !== _this.topojsonName) {
        _this.topojsonName = topojsonNameNew;

        if(PlotlyGeoAssets.topojson[_this.topojsonName] === undefined) {
            promises.push(_this.fetchTopojson().then(function(topojson) {
                PlotlyGeoAssets.topojson[_this.topojsonName] = topojson;
                _this.topojson = topojson;
                _this.update(geoCalcData, fullLayout);
            }));
        } else {
            _this.topojson = PlotlyGeoAssets.topojson[_this.topojsonName];
            _this.update(geoCalcData, fullLayout);
        }
    } else {
        _this.update(geoCalcData, fullLayout);
    }
};

proto.fetchTopojson = function() {
    var topojsonPath = topojsonUtils.getTopojsonPath(
        this.topojsonURL,
        this.topojsonName
    );
    return new Promise(function(resolve, reject) {
        d3.json(topojsonPath, function(err, topojson) {
            if(err) {
                if(err.status === 404) {
                    return reject(new Error([
                        'plotly.js could not find topojson file at',
                        topojsonPath, '.',
                        'Make sure the *topojsonURL* plot config option',
                        'is set properly.'
                    ].join(' ')));
                } else {
                    return reject(new Error([
                        'unexpected error while fetching topojson file at',
                        topojsonPath
                    ].join(' ')));
                }
            }
            resolve(topojson);
        });
    });
};

proto.update = function(geoCalcData, fullLayout) {
    var geoLayout = fullLayout[this.id];

    var hasInvalidBounds = this.updateProjection(fullLayout, geoLayout);
    if(hasInvalidBounds) return;

    // important: maps with choropleth traces have a different layer order
    this.hasChoropleth = false;
    for(var i = 0; i < geoCalcData.length; i++) {
        if(geoCalcData[i][0].trace.type === 'choropleth') {
            this.hasChoropleth = true;
            break;
        }
    }

    if(!this.viewInitial) {
        this.saveViewInitial(geoLayout);
    }

    this.updateBaseLayers(fullLayout, geoLayout);
    this.updateDims(fullLayout, geoLayout);
    this.updateFx(fullLayout, geoLayout);

    Plots.generalUpdatePerTraceModule(this.graphDiv, this, geoCalcData, geoLayout);

    var scatterLayer = this.layers.frontplot.select('.scatterlayer');
    this.dataPoints.point = scatterLayer.selectAll('.point');
    this.dataPoints.text = scatterLayer.selectAll('text');
    this.dataPaths.line = scatterLayer.selectAll('.js-line');

    var choroplethLayer = this.layers.backplot.select('.choroplethlayer');
    this.dataPaths.choropleth = choroplethLayer.selectAll('path');

    this.render();
};

proto.updateProjection = function(fullLayout, geoLayout) {
    var gs = fullLayout._size;
    var domain = geoLayout.domain;
    var projLayout = geoLayout.projection;
    var rotation = projLayout.rotation || {};
    var center = geoLayout.center || {};

    var projection = this.projection = getProjection(geoLayout);

    // set 'pre-fit' projection
    projection
        .center([center.lon - rotation.lon, center.lat - rotation.lat])
        .rotate([-rotation.lon, -rotation.lat, rotation.roll])
        .parallels(projLayout.parallels);

    // setup subplot extent [[x0,y0], [x1,y1]]
    var extent = [[
        gs.l + gs.w * domain.x[0],
        gs.t + gs.h * (1 - domain.y[1])
    ], [
        gs.l + gs.w * domain.x[1],
        gs.t + gs.h * (1 - domain.y[0])
    ]];

    var lonaxis = geoLayout.lonaxis;
    var lataxis = geoLayout.lataxis;
    var rangeBox = makeRangeBox(lonaxis.range, lataxis.range);

    // fit projection 'scale' and 'translate' to set lon/lat ranges
    projection.fitExtent(extent, rangeBox);

    var b = this.bounds = projection.getBounds(rangeBox);
    var s = this.fitScale = projection.scale();
    var t = projection.translate();

    if(
        !isFinite(b[0][0]) || !isFinite(b[0][1]) ||
        !isFinite(b[1][0]) || !isFinite(b[1][1]) ||
        isNaN(t[0]) || isNaN(t[0])
    ) {
        var gd = this.graphDiv;
        var attrToUnset = ['projection.rotation', 'center', 'lonaxis.range', 'lataxis.range'];
        var msg = 'Invalid geo settings, relayout\'ing to default view.';
        var updateObj = {};

        // clear all attribute that could cause invalid bounds,
        // clear viewInitial to update reset-view behavior

        for(var i = 0; i < attrToUnset.length; i++) {
            updateObj[this.id + '.' + attrToUnset[i]] = null;
        }

        this.viewInitial = null;

        Lib.warn(msg);
        gd._promises.push(Registry.call('relayout', gd, updateObj));
        return msg;
    }

    // px coordinates of view mid-point,
    // useful to update `geo.center` after interactions
    var midPt = this.midPt = [
        (b[0][0] + b[1][0]) / 2,
        (b[0][1] + b[1][1]) / 2
    ];

    // adjust projection to user setting
    projection
        .scale(projLayout.scale * s)
        .translate([t[0] + (midPt[0] - t[0]), t[1] + (midPt[1] - t[1])])
        .clipExtent(b);

    // the 'albers usa' projection does not expose a 'center' method
    // so here's this hack to make it respond to 'geoLayout.center'
    if(geoLayout._isAlbersUsa) {
        var centerPx = projection([center.lon, center.lat]);
        var tt = projection.translate();

        projection.translate([
            tt[0] - (centerPx[0] - tt[0]),
            tt[1] - (centerPx[1] - tt[1])
        ]);
    }
};

proto.updateBaseLayers = function(fullLayout, geoLayout) {
    var _this = this;
    var topojson = _this.topojson;
    var layers = _this.layers;
    var basePaths = _this.basePaths;

    function isAxisLayer(d) {
        return (d === 'lonaxis' || d === 'lataxis');
    }

    function isLineLayer(d) {
        return Boolean(constants.lineLayers[d]);
    }

    function isFillLayer(d) {
        return Boolean(constants.fillLayers[d]);
    }

    var allLayers = this.hasChoropleth ?
        constants.layersForChoropleth :
        constants.layers;

    var layerData = allLayers.filter(function(d) {
        return (isLineLayer(d) || isFillLayer(d)) ? geoLayout['show' + d] :
            isAxisLayer(d) ? geoLayout[d].showgrid :
            true;
    });

    var join = _this.framework.selectAll('.layer')
        .data(layerData, String);

    join.exit().each(function(d) {
        delete layers[d];
        delete basePaths[d];
        d3.select(this).remove();
    });

    join.enter().append('g')
        .attr('class', function(d) { return 'layer ' + d; })
        .each(function(d) {
            var layer = layers[d] = d3.select(this);

            if(d === 'bg') {
                _this.bgRect = layer.append('rect')
                    .style('pointer-events', 'all');
            } else if(isAxisLayer(d)) {
                basePaths[d] = layer.append('path')
                    .style('fill', 'none');
            } else if(d === 'backplot') {
                layer.append('g')
                    .classed('choroplethlayer', true);
            } else if(d === 'frontplot') {
                layer.append('g')
                    .classed('scatterlayer', true);
            } else if(isLineLayer(d)) {
                basePaths[d] = layer.append('path')
                    .style('fill', 'none')
                    .style('stroke-miterlimit', 2);
            } else if(isFillLayer(d)) {
                basePaths[d] = layer.append('path')
                    .style('stroke', 'none');
            }
        });

    join.order();

    join.each(function(d) {
        var path = basePaths[d];
        var adj = constants.layerNameToAdjective[d];

        if(d === 'frame') {
            path.datum(constants.sphereSVG);
        } else if(isLineLayer(d) || isFillLayer(d)) {
            path.datum(topojsonFeature(topojson, topojson.objects[d]));
        } else if(isAxisLayer(d)) {
            path.datum(makeGraticule(d, geoLayout))
                .call(Color.stroke, geoLayout[d].gridcolor)
                .call(Drawing.dashLine, '', geoLayout[d].gridwidth);
        }

        if(isLineLayer(d)) {
            path.call(Color.stroke, geoLayout[adj + 'color'])
                .call(Drawing.dashLine, '', geoLayout[adj + 'width']);
        } else if(isFillLayer(d)) {
            path.call(Color.fill, geoLayout[adj + 'color']);
        }
    });
};

proto.updateDims = function(fullLayout, geoLayout) {
    var b = this.bounds;
    var hFrameWidth = (geoLayout.framewidth || 0) / 2;

    var l = b[0][0] - hFrameWidth;
    var t = b[0][1] - hFrameWidth;
    var w = b[1][0] - l + hFrameWidth;
    var h = b[1][1] - t + hFrameWidth;

    Drawing.setRect(this.clipRect, l, t, w, h);

    this.bgRect
        .call(Drawing.setRect, l, t, w, h)
        .call(Color.fill, geoLayout.bgcolor);

    this.xaxis._offset = l;
    this.xaxis._length = w;

    this.yaxis._offset = t;
    this.yaxis._length = h;
};

proto.updateFx = function(fullLayout, geoLayout) {
    var _this = this;
    var gd = _this.graphDiv;
    var bgRect = _this.bgRect;
    var dragMode = fullLayout.dragmode;
    var clickMode = fullLayout.clickmode;

    if(_this.isStatic) return;

    function zoomReset() {
        var viewInitial = _this.viewInitial;
        var updateObj = {};

        for(var k in viewInitial) {
            updateObj[_this.id + '.' + k] = viewInitial[k];
        }

        Registry.call('_guiRelayout', gd, updateObj);
        gd.emit('plotly_doubleclick', null);
    }

    function invert(lonlat) {
        return _this.projection.invert([
            lonlat[0] + _this.xaxis._offset,
            lonlat[1] + _this.yaxis._offset
        ]);
    }

    var fillRangeItems;

    if(dragMode === 'select') {
        fillRangeItems = function(eventData, poly) {
            var ranges = eventData.range = {};
            ranges[_this.id] = [
                invert([poly.xmin, poly.ymin]),
                invert([poly.xmax, poly.ymax])
            ];
        };
    } else if(dragMode === 'lasso') {
        fillRangeItems = function(eventData, poly, pts) {
            var dataPts = eventData.lassoPoints = {};
            dataPts[_this.id] = pts.filtered.map(invert);
        };
    }

    // Note: dragOptions is needed to be declared for all dragmodes because
    // it's the object that holds persistent selection state.
    var dragOptions = {
        element: _this.bgRect.node(),
        gd: gd,
        plotinfo: {
            id: _this.id,
            xaxis: _this.xaxis,
            yaxis: _this.yaxis,
            fillRangeItems: fillRangeItems
        },
        xaxes: [_this.xaxis],
        yaxes: [_this.yaxis],
        subplot: _this.id,
        clickFn: function(numClicks) {
            if(numClicks === 2) {
                fullLayout._zoomlayer.selectAll('.select-outline').remove();
            }
        }
    };

    if(dragMode === 'pan') {
        bgRect.node().onmousedown = null;
        bgRect.call(createGeoZoom(_this, geoLayout));
        bgRect.on('dblclick.zoom', zoomReset);
        if(!gd._context._scrollZoom.geo) {
            bgRect.on('wheel.zoom', null);
        }
    }
    else if(dragMode === 'select' || dragMode === 'lasso') {
        bgRect.on('.zoom', null);

        dragOptions.prepFn = function(e, startX, startY) {
            prepSelect(e, startX, startY, dragOptions, dragMode);
        };

        dragElement.init(dragOptions);
    }

    bgRect.on('mousemove', function() {
        var lonlat = _this.projection.invert(d3.mouse(this));

        if(!lonlat || isNaN(lonlat[0]) || isNaN(lonlat[1])) {
            return dragElement.unhover(gd, d3.event);
        }

        _this.xaxis.p2c = function() { return lonlat[0]; };
        _this.yaxis.p2c = function() { return lonlat[1]; };

        Fx.hover(gd, d3.event, _this.id);
    });

    bgRect.on('mouseout', function() {
        if(gd._dragging) return;
        dragElement.unhover(gd, d3.event);
    });

    bgRect.on('click', function() {
        // For select and lasso the dragElement is handling clicks
        if(dragMode !== 'select' && dragMode !== 'lasso') {
            if(clickMode.indexOf('select') > -1) {
                selectOnClick(d3.event, gd, [_this.xaxis], [_this.yaxis],
                  _this.id, dragOptions);
            }

            if(clickMode.indexOf('event') > -1) {
                // TODO: like pie and mapbox, this doesn't support right-click
                // actually this one is worse, as right-click starts a pan, or leaves
                // select in a weird state.
                // Also, only tangentially related, we should cancel hover during pan
                Fx.click(gd, d3.event);
            }
        }
    });
};

proto.makeFramework = function() {
    var _this = this;
    var gd = _this.graphDiv;
    var fullLayout = gd._fullLayout;
    var clipId = 'clip' + fullLayout._uid + _this.id;

    _this.clipDef = fullLayout._clips.append('clipPath')
        .attr('id', clipId);

    _this.clipRect = _this.clipDef.append('rect');

    _this.framework = d3.select(_this.container).append('g')
        .attr('class', 'geo ' + _this.id)
        .call(Drawing.setClipUrl, clipId, gd);

    // sane lonlat to px
    _this.project = function(v) {
        var px = _this.projection(v);
        return px ?
            [px[0] - _this.xaxis._offset, px[1] - _this.yaxis._offset] :
            [null, null];
    };

    _this.xaxis = {
        _id: 'x',
        c2p: function(v) { return _this.project(v)[0]; }
    };

    _this.yaxis = {
        _id: 'y',
        c2p: function(v) { return _this.project(v)[1]; }
    };

    // mock axis for hover formatting
    _this.mockAxis = {
        type: 'linear',
        showexponent: 'all',
        exponentformat: 'B'
    };
    Axes.setConvert(_this.mockAxis, fullLayout);
};

proto.saveViewInitial = function(geoLayout) {
    var center = geoLayout.center || {};
    var projLayout = geoLayout.projection;
    var rotation = projLayout.rotation || {};

    if(geoLayout._isScoped) {
        this.viewInitial = {
            'center.lon': center.lon,
            'center.lat': center.lat,
            'projection.scale': projLayout.scale
        };
    } else if(geoLayout._isClipped) {
        this.viewInitial = {
            'projection.scale': projLayout.scale,
            'projection.rotation.lon': rotation.lon,
            'projection.rotation.lat': rotation.lat
        };
    } else {
        this.viewInitial = {
            'center.lon': center.lon,
            'center.lat': center.lat,
            'projection.scale': projLayout.scale,
            'projection.rotation.lon': rotation.lon
        };
    }
};

// [hot code path] (re)draw all paths which depend on the projection
proto.render = function() {
    var projection = this.projection;
    var pathFn = projection.getPath();
    var k;

    function translatePoints(d) {
        var lonlatPx = projection(d.lonlat);
        return lonlatPx ?
            'translate(' + lonlatPx[0] + ',' + lonlatPx[1] + ')' :
             null;
    }

    function hideShowPoints(d) {
        return projection.isLonLatOverEdges(d.lonlat) ? 'none' : null;
    }

    for(k in this.basePaths) {
        this.basePaths[k].attr('d', pathFn);
    }

    for(k in this.dataPaths) {
        this.dataPaths[k].attr('d', function(d) { return pathFn(d.geojson); });
    }

    for(k in this.dataPoints) {
        this.dataPoints[k]
            .attr('display', hideShowPoints)
            .attr('transform', translatePoints);
    }
};

// Helper that wraps d3.geo[/* projection name /*]() which:
//
// - adds 'fitExtent' (available in d3 v4)
// - adds 'getPath', 'getBounds' convenience methods
// - scopes logic related to 'clipAngle'
// - adds 'isLonLatOverEdges' method
// - sets projection precision
// - sets methods that aren't always defined depending
//   on the projection type to a dummy 'd3-esque' function,
//
// This wrapper alleviates subsequent code of (many) annoying if-statements.
function getProjection(geoLayout) {
    var projLayout = geoLayout.projection;
    var projType = projLayout.type;

    var projection = d3.geo[constants.projNames[projType]]();

    var clipAngle = geoLayout._isClipped ?
        constants.lonaxisSpan[projType] / 2 :
        null;

    var methods = ['center', 'rotate', 'parallels', 'clipExtent'];
    var dummyFn = function(_) { return _ ? projection : []; };

    for(var i = 0; i < methods.length; i++) {
        var m = methods[i];
        if(typeof projection[m] !== 'function') {
            projection[m] = dummyFn;
        }
    }

    projection.isLonLatOverEdges = function(lonlat) {
        if(projection(lonlat) === null) {
            return true;
        }

        if(clipAngle) {
            var r = projection.rotate();
            var angle = d3.geo.distance(lonlat, [-r[0], -r[1]]);
            var maxAngle = clipAngle * Math.PI / 180;
            return angle > maxAngle;
        } else {
            return false;
        }
    };

    projection.getPath = function() {
        return d3.geo.path().projection(projection);
    };

    projection.getBounds = function(object) {
        return projection.getPath().bounds(object);
    };

    // adapted from d3 v4:
    // https://github.com/d3/d3-geo/blob/master/src/projection/fit.js
    projection.fitExtent = function(extent, object) {
        var w = extent[1][0] - extent[0][0];
        var h = extent[1][1] - extent[0][1];
        var clip = projection.clipExtent && projection.clipExtent();

        projection
            .scale(150)
            .translate([0, 0]);

        if(clip) projection.clipExtent(null);

        var b = projection.getBounds(object);
        var k = Math.min(w / (b[1][0] - b[0][0]), h / (b[1][1] - b[0][1]));
        var x = +extent[0][0] + (w - k * (b[1][0] + b[0][0])) / 2;
        var y = +extent[0][1] + (h - k * (b[1][1] + b[0][1])) / 2;

        if(clip) projection.clipExtent(clip);

        return projection
            .scale(k * 150)
            .translate([x, y]);
    };

    projection.precision(constants.precision);

    if(clipAngle) {
        projection.clipAngle(clipAngle - constants.clipPad);
    }

    return projection;
}

function makeGraticule(axisName, geoLayout) {
    var axisLayout = geoLayout[axisName];
    var dtick = axisLayout.dtick;
    var scopeDefaults = constants.scopeDefaults[geoLayout.scope];
    var lonaxisRange = scopeDefaults.lonaxisRange;
    var lataxisRange = scopeDefaults.lataxisRange;
    var step = axisName === 'lonaxis' ? [dtick] : [0, dtick];

    return d3.geo.graticule()
        .extent([
            [lonaxisRange[0], lataxisRange[0]],
            [lonaxisRange[1], lataxisRange[1]]
        ])
        .step(step);
}

// Returns polygon GeoJSON corresponding to lon/lat range box
// with well-defined direction
//
// Note that clipPad padding is added around range to avoid aliasing.
function makeRangeBox(lon, lat) {
    var clipPad = constants.clipPad;
    var lon0 = lon[0] + clipPad;
    var lon1 = lon[1] - clipPad;
    var lat0 = lat[0] + clipPad;
    var lat1 = lat[1] - clipPad;

    // to cross antimeridian w/o ambiguity
    if(lon0 > 0 && lon1 < 0) lon1 += 360;

    var dlon4 = (lon1 - lon0) / 4;

    return {
        type: 'Polygon',
        coordinates: [[
            [lon0, lat0],
            [lon0, lat1],
            [lon0 + dlon4, lat1],
            [lon0 + 2 * dlon4, lat1],
            [lon0 + 3 * dlon4, lat1],
            [lon1, lat1],
            [lon1, lat0],
            [lon1 - dlon4, lat0],
            [lon1 - 2 * dlon4, lat0],
            [lon1 - 3 * dlon4, lat0],
            [lon0, lat0]
        ]]
    };
}

},{"../../components/color":574,"../../components/dragelement":592,"../../components/drawing":595,"../../components/fx":613,"../../lib":697,"../../lib/topojson_utils":724,"../../registry":826,"../cartesian/axes":745,"../cartesian/select":762,"../plots":807,"./constants":773,"./projections":779,"./zoom":780,"d3":151,"topojson-client":521}],775:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var createGeo = _dereq_('./geo');
var getSubplotCalcData = _dereq_('../../plots/get_data').getSubplotCalcData;
var counterRegex = _dereq_('../../lib').counterRegex;

var GEO = 'geo';

exports.name = GEO;

exports.attr = GEO;

exports.idRoot = GEO;

exports.idRegex = exports.attrRegex = counterRegex(GEO);

exports.attributes = _dereq_('./layout/attributes');

exports.layoutAttributes = _dereq_('./layout/layout_attributes');

exports.supplyLayoutDefaults = _dereq_('./layout/defaults');

exports.plot = function plotGeo(gd) {
    var fullLayout = gd._fullLayout;
    var calcData = gd.calcdata;
    var geoIds = fullLayout._subplots[GEO];

    /**
     * If 'plotly-geo-assets.js' is not included,
     * initialize object to keep reference to every loaded topojson
     */
    if(window.PlotlyGeoAssets === undefined) {
        window.PlotlyGeoAssets = {topojson: {}};
    }

    for(var i = 0; i < geoIds.length; i++) {
        var geoId = geoIds[i];
        var geoCalcData = getSubplotCalcData(calcData, GEO, geoId);
        var geoLayout = fullLayout[geoId];
        var geo = geoLayout._subplot;

        if(!geo) {
            geo = createGeo({
                id: geoId,
                graphDiv: gd,
                container: fullLayout._geolayer.node(),
                topojsonURL: gd._context.topojsonURL,
                staticPlot: gd._context.staticPlot
            });

            fullLayout[geoId]._subplot = geo;
        }

        geo.plot(geoCalcData, fullLayout, gd._promises);
    }
};

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var oldGeoKeys = oldFullLayout._subplots[GEO] || [];

    for(var i = 0; i < oldGeoKeys.length; i++) {
        var oldGeoKey = oldGeoKeys[i];
        var oldGeo = oldFullLayout[oldGeoKey]._subplot;

        if(!newFullLayout[oldGeoKey] && !!oldGeo) {
            oldGeo.framework.remove();
            oldGeo.clipDef.remove();
        }
    }
};

exports.updateFx = function(gd) {
    var fullLayout = gd._fullLayout;
    var subplotIds = fullLayout._subplots[GEO];

    for(var i = 0; i < subplotIds.length; i++) {
        var subplotLayout = fullLayout[subplotIds[i]];
        var subplotObj = subplotLayout._subplot;
        subplotObj.updateFx(fullLayout, subplotLayout);
    }
};

},{"../../lib":697,"../../plots/get_data":781,"./geo":774,"./layout/attributes":776,"./layout/defaults":777,"./layout/layout_attributes":778}],776:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    geo: {
        valType: 'subplotid',
        
        dflt: 'geo',
        editType: 'calc',
        
    }
};

},{}],777:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var handleSubplotDefaults = _dereq_('../../subplot_defaults');
var constants = _dereq_('../constants');
var layoutAttributes = _dereq_('./layout_attributes');

var axesNames = constants.axesNames;

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
    handleSubplotDefaults(layoutIn, layoutOut, fullData, {
        type: 'geo',
        attributes: layoutAttributes,
        handleDefaults: handleGeoDefaults,
        partition: 'y'
    });
};

function handleGeoDefaults(geoLayoutIn, geoLayoutOut, coerce) {
    var show;

    var resolution = coerce('resolution');
    var scope = coerce('scope');
    var scopeParams = constants.scopeDefaults[scope];

    var projType = coerce('projection.type', scopeParams.projType);
    var isAlbersUsa = geoLayoutOut._isAlbersUsa = projType === 'albers usa';

    // no other scopes are allowed for 'albers usa' projection
    if(isAlbersUsa) scope = geoLayoutOut.scope = 'usa';

    var isScoped = geoLayoutOut._isScoped = (scope !== 'world');
    var isConic = geoLayoutOut._isConic = projType.indexOf('conic') !== -1;
    geoLayoutOut._isClipped = !!constants.lonaxisSpan[projType];

    for(var i = 0; i < axesNames.length; i++) {
        var axisName = axesNames[i];
        var dtickDflt = [30, 10][i];
        var rangeDflt;

        if(isScoped) {
            rangeDflt = scopeParams[axisName + 'Range'];
        } else {
            var dfltSpans = constants[axisName + 'Span'];
            var hSpan = (dfltSpans[projType] || dfltSpans['*']) / 2;
            var rot = coerce(
                'projection.rotation.' + axisName.substr(0, 3),
                scopeParams.projRotate[i]
            );
            rangeDflt = [rot - hSpan, rot + hSpan];
        }

        var range = coerce(axisName + '.range', rangeDflt);

        coerce(axisName + '.tick0', range[0]);
        coerce(axisName + '.dtick', dtickDflt);

        show = coerce(axisName + '.showgrid');
        if(show) {
            coerce(axisName + '.gridcolor');
            coerce(axisName + '.gridwidth');
        }
    }

    var lonRange = geoLayoutOut.lonaxis.range;
    var latRange = geoLayoutOut.lataxis.range;

    // to cross antimeridian w/o ambiguity
    var lon0 = lonRange[0];
    var lon1 = lonRange[1];
    if(lon0 > 0 && lon1 < 0) lon1 += 360;

    var centerLon = (lon0 + lon1) / 2;
    var projLon;

    if(!isAlbersUsa) {
        var dfltProjRotate = isScoped ? scopeParams.projRotate : [centerLon, 0, 0];

        projLon = coerce('projection.rotation.lon', dfltProjRotate[0]);
        coerce('projection.rotation.lat', dfltProjRotate[1]);
        coerce('projection.rotation.roll', dfltProjRotate[2]);

        show = coerce('showcoastlines', !isScoped);
        if(show) {
            coerce('coastlinecolor');
            coerce('coastlinewidth');
        }

        show = coerce('showocean');
        if(show) coerce('oceancolor');
    }

    var centerLonDflt;
    var centerLatDflt;

    if(isAlbersUsa) {
        // 'albers usa' does not have a 'center',
        // these values were found using via:
        //   projection.invert([geoLayout.center.lon, geoLayoutIn.center.lat])
        centerLonDflt = -96.6;
        centerLatDflt = 38.7;
    } else {
        centerLonDflt = isScoped ? centerLon : projLon;
        centerLatDflt = (latRange[0] + latRange[1]) / 2;
    }

    coerce('center.lon', centerLonDflt);
    coerce('center.lat', centerLatDflt);

    if(isConic) {
        var dfltProjParallels = scopeParams.projParallels || [0, 60];
        coerce('projection.parallels', dfltProjParallels);
    }

    coerce('projection.scale');

    show = coerce('showland');
    if(show) coerce('landcolor');

    show = coerce('showlakes');
    if(show) coerce('lakecolor');

    show = coerce('showrivers');
    if(show) {
        coerce('rivercolor');
        coerce('riverwidth');
    }

    show = coerce('showcountries', isScoped && scope !== 'usa');
    if(show) {
        coerce('countrycolor');
        coerce('countrywidth');
    }

    if(scope === 'usa' || (scope === 'north america' && resolution === 50)) {
        // Only works for:
        //   USA states at 110m
        //   USA states + Canada provinces at 50m
        coerce('showsubunits', true);
        coerce('subunitcolor');
        coerce('subunitwidth');
    }

    if(!isScoped) {
        // Does not work in non-world scopes
        show = coerce('showframe', true);
        if(show) {
            coerce('framecolor');
            coerce('framewidth');
        }
    }

    coerce('bgcolor');
}

},{"../../subplot_defaults":821,"../constants":773,"./layout_attributes":778}],778:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorAttrs = _dereq_('../../../components/color/attributes');
var domainAttrs = _dereq_('../../domain').attributes;
var constants = _dereq_('../constants');
var overrideAll = _dereq_('../../../plot_api/edit_types').overrideAll;

var geoAxesAttrs = {
    range: {
        valType: 'info_array',
        
        items: [
            {valType: 'number'},
            {valType: 'number'}
        ],
        
    },
    showgrid: {
        valType: 'boolean',
        
        dflt: false,
        
    },
    tick0: {
        valType: 'number',
        
        
    },
    dtick: {
        valType: 'number',
        
        
    },
    gridcolor: {
        valType: 'color',
        
        dflt: colorAttrs.lightLine,
        
    },
    gridwidth: {
        valType: 'number',
        
        min: 0,
        dflt: 1,
        
    }
};

var attrs = module.exports = overrideAll({
    domain: domainAttrs({name: 'geo'}, {
        
    }),

    resolution: {
        valType: 'enumerated',
        values: [110, 50],
        
        dflt: 110,
        coerceNumber: true,
        
    },
    scope: {
        valType: 'enumerated',
        
        values: Object.keys(constants.scopeDefaults),
        dflt: 'world',
        
    },
    projection: {
        type: {
            valType: 'enumerated',
            
            values: Object.keys(constants.projNames),
            
        },
        rotation: {
            lon: {
                valType: 'number',
                
                
            },
            lat: {
                valType: 'number',
                
                
            },
            roll: {
                valType: 'number',
                
                
            }
        },
        parallels: {
            valType: 'info_array',
            
            items: [
                {valType: 'number'},
                {valType: 'number'}
            ],
            
        },
        scale: {
            valType: 'number',
            
            min: 0,
            dflt: 1,
            
        },
    },
    center: {
        lon: {
            valType: 'number',
            
            
        },
        lat: {
            valType: 'number',
            
            
        }
    },
    showcoastlines: {
        valType: 'boolean',
        
        
    },
    coastlinecolor: {
        valType: 'color',
        
        dflt: colorAttrs.defaultLine,
        
    },
    coastlinewidth: {
        valType: 'number',
        
        min: 0,
        dflt: 1,
        
    },
    showland: {
        valType: 'boolean',
        
        dflt: false,
        
    },
    landcolor: {
        valType: 'color',
        
        dflt: constants.landColor,
        
    },
    showocean: {
        valType: 'boolean',
        
        dflt: false,
        
    },
    oceancolor: {
        valType: 'color',
        
        dflt: constants.waterColor,
        
    },
    showlakes: {
        valType: 'boolean',
        
        dflt: false,
        
    },
    lakecolor: {
        valType: 'color',
        
        dflt: constants.waterColor,
        
    },
    showrivers: {
        valType: 'boolean',
        
        dflt: false,
        
    },
    rivercolor: {
        valType: 'color',
        
        dflt: constants.waterColor,
        
    },
    riverwidth: {
        valType: 'number',
        
        min: 0,
        dflt: 1,
        
    },
    showcountries: {
        valType: 'boolean',
        
        
    },
    countrycolor: {
        valType: 'color',
        
        dflt: colorAttrs.defaultLine,
        
    },
    countrywidth: {
        valType: 'number',
        
        min: 0,
        dflt: 1,
        
    },
    showsubunits: {
        valType: 'boolean',
        
        
    },
    subunitcolor: {
        valType: 'color',
        
        dflt: colorAttrs.defaultLine,
        
    },
    subunitwidth: {
        valType: 'number',
        
        min: 0,
        dflt: 1,
        
    },
    showframe: {
        valType: 'boolean',
        
        
    },
    framecolor: {
        valType: 'color',
        
        dflt: colorAttrs.defaultLine,
        
    },
    framewidth: {
        valType: 'number',
        
        min: 0,
        dflt: 1,
        
    },
    bgcolor: {
        valType: 'color',
        
        dflt: colorAttrs.background,
        
    },
    lonaxis: geoAxesAttrs,
    lataxis: geoAxesAttrs
}, 'plot', 'from-root');

// set uirevision outside of overrideAll so it can be `editType: 'none'`
attrs.uirevision = {
    valType: 'any',
    
    editType: 'none',
    
};

},{"../../../components/color/attributes":573,"../../../plot_api/edit_types":728,"../../domain":770,"../constants":773}],779:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

/*
 * Generated by https://github.com/etpinard/d3-geo-projection-picker
 *
 * which is hand-picks projection from https://github.com/d3/d3-geo-projection
 *
 * into a CommonJS require-able module.
 */

'use strict';

/* eslint-disable */

function addProjectionsToD3(d3) {
  d3.geo.project = function(object, projection) {
    var stream = projection.stream;
    if (!stream) throw new Error("not yet supported");
    return (object && d3_geo_projectObjectType.hasOwnProperty(object.type) ? d3_geo_projectObjectType[object.type] : d3_geo_projectGeometry)(object, stream);
  };
  function d3_geo_projectFeature(object, stream) {
    return {
      type: "Feature",
      id: object.id,
      properties: object.properties,
      geometry: d3_geo_projectGeometry(object.geometry, stream)
    };
  }
  function d3_geo_projectGeometry(geometry, stream) {
    if (!geometry) return null;
    if (geometry.type === "GeometryCollection") return {
      type: "GeometryCollection",
      geometries: object.geometries.map(function(geometry) {
        return d3_geo_projectGeometry(geometry, stream);
      })
    };
    if (!d3_geo_projectGeometryType.hasOwnProperty(geometry.type)) return null;
    var sink = d3_geo_projectGeometryType[geometry.type];
    d3.geo.stream(geometry, stream(sink));
    return sink.result();
  }
  var d3_geo_projectObjectType = {
    Feature: d3_geo_projectFeature,
    FeatureCollection: function(object, stream) {
      return {
        type: "FeatureCollection",
        features: object.features.map(function(feature) {
          return d3_geo_projectFeature(feature, stream);
        })
      };
    }
  };
  var d3_geo_projectPoints = [], d3_geo_projectLines = [];
  var d3_geo_projectPoint = {
    point: function(x, y) {
      d3_geo_projectPoints.push([ x, y ]);
    },
    result: function() {
      var result = !d3_geo_projectPoints.length ? null : d3_geo_projectPoints.length < 2 ? {
        type: "Point",
        coordinates: d3_geo_projectPoints[0]
      } : {
        type: "MultiPoint",
        coordinates: d3_geo_projectPoints
      };
      d3_geo_projectPoints = [];
      return result;
    }
  };
  var d3_geo_projectLine = {
    lineStart: d3_geo_projectNoop,
    point: function(x, y) {
      d3_geo_projectPoints.push([ x, y ]);
    },
    lineEnd: function() {
      if (d3_geo_projectPoints.length) d3_geo_projectLines.push(d3_geo_projectPoints),
      d3_geo_projectPoints = [];
    },
    result: function() {
      var result = !d3_geo_projectLines.length ? null : d3_geo_projectLines.length < 2 ? {
        type: "LineString",
        coordinates: d3_geo_projectLines[0]
      } : {
        type: "MultiLineString",
        coordinates: d3_geo_projectLines
      };
      d3_geo_projectLines = [];
      return result;
    }
  };
  var d3_geo_projectPolygon = {
    polygonStart: d3_geo_projectNoop,
    lineStart: d3_geo_projectNoop,
    point: function(x, y) {
      d3_geo_projectPoints.push([ x, y ]);
    },
    lineEnd: function() {
      var n = d3_geo_projectPoints.length;
      if (n) {
        do d3_geo_projectPoints.push(d3_geo_projectPoints[0].slice()); while (++n < 4);
        d3_geo_projectLines.push(d3_geo_projectPoints), d3_geo_projectPoints = [];
      }
    },
    polygonEnd: d3_geo_projectNoop,
    result: function() {
      if (!d3_geo_projectLines.length) return null;
      var polygons = [], holes = [];
      d3_geo_projectLines.forEach(function(ring) {
        if (d3_geo_projectClockwise(ring)) polygons.push([ ring ]); else holes.push(ring);
      });
      holes.forEach(function(hole) {
        var point = hole[0];
        polygons.some(function(polygon) {
          if (d3_geo_projectContains(polygon[0], point)) {
            polygon.push(hole);
            return true;
          }
        }) || polygons.push([ hole ]);
      });
      d3_geo_projectLines = [];
      return !polygons.length ? null : polygons.length > 1 ? {
        type: "MultiPolygon",
        coordinates: polygons
      } : {
        type: "Polygon",
        coordinates: polygons[0]
      };
    }
  };
  var d3_geo_projectGeometryType = {
    Point: d3_geo_projectPoint,
    MultiPoint: d3_geo_projectPoint,
    LineString: d3_geo_projectLine,
    MultiLineString: d3_geo_projectLine,
    Polygon: d3_geo_projectPolygon,
    MultiPolygon: d3_geo_projectPolygon,
    Sphere: d3_geo_projectPolygon
  };
  function d3_geo_projectNoop() {}
  function d3_geo_projectClockwise(ring) {
    if ((n = ring.length) < 4) return false;
    var i = 0, n, area = ring[n - 1][1] * ring[0][0] - ring[n - 1][0] * ring[0][1];
    while (++i < n) area += ring[i - 1][1] * ring[i][0] - ring[i - 1][0] * ring[i][1];
    return area <= 0;
  }
  function d3_geo_projectContains(ring, point) {
    var x = point[0], y = point[1], contains = false;
    for (var i = 0, n = ring.length, j = n - 1; i < n; j = i++) {
      var pi = ring[i], xi = pi[0], yi = pi[1], pj = ring[j], xj = pj[0], yj = pj[1];
      if (yi > y ^ yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi) contains = !contains;
    }
    return contains;
  }
  var ε = 1e-6, ε2 = ε * ε, π = Math.PI, halfπ = π / 2, sqrtπ = Math.sqrt(π), radians = π / 180, degrees = 180 / π;
  function sinci(x) {
    return x ? x / Math.sin(x) : 1;
  }
  function sgn(x) {
    return x > 0 ? 1 : x < 0 ? -1 : 0;
  }
  function asin(x) {
    return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x);
  }
  function acos(x) {
    return x > 1 ? 0 : x < -1 ? π : Math.acos(x);
  }
  function asqrt(x) {
    return x > 0 ? Math.sqrt(x) : 0;
  }
  var projection = d3.geo.projection, projectionMutator = d3.geo.projectionMutator;
  d3.geo.interrupt = function(project) {
    var lobes = [ [ [ [ -π, 0 ], [ 0, halfπ ], [ π, 0 ] ] ], [ [ [ -π, 0 ], [ 0, -halfπ ], [ π, 0 ] ] ] ];
    var bounds;
    function forward(λ, φ) {
      var sign = φ < 0 ? -1 : +1, hemilobes = lobes[+(φ < 0)];
      for (var i = 0, n = hemilobes.length - 1; i < n && λ > hemilobes[i][2][0]; ++i) ;
      var coordinates = project(λ - hemilobes[i][1][0], φ);
      coordinates[0] += project(hemilobes[i][1][0], sign * φ > sign * hemilobes[i][0][1] ? hemilobes[i][0][1] : φ)[0];
      return coordinates;
    }
    function reset() {
      bounds = lobes.map(function(hemilobes) {
        return hemilobes.map(function(lobe) {
          var x0 = project(lobe[0][0], lobe[0][1])[0], x1 = project(lobe[2][0], lobe[2][1])[0], y0 = project(lobe[1][0], lobe[0][1])[1], y1 = project(lobe[1][0], lobe[1][1])[1], t;
          if (y0 > y1) t = y0, y0 = y1, y1 = t;
          return [ [ x0, y0 ], [ x1, y1 ] ];
        });
      });
    }
    if (project.invert) forward.invert = function(x, y) {
      var hemibounds = bounds[+(y < 0)], hemilobes = lobes[+(y < 0)];
      for (var i = 0, n = hemibounds.length; i < n; ++i) {
        var b = hemibounds[i];
        if (b[0][0] <= x && x < b[1][0] && b[0][1] <= y && y < b[1][1]) {
          var coordinates = project.invert(x - project(hemilobes[i][1][0], 0)[0], y);
          coordinates[0] += hemilobes[i][1][0];
          return pointEqual(forward(coordinates[0], coordinates[1]), [ x, y ]) ? coordinates : null;
        }
      }
    };
    var projection = d3.geo.projection(forward), stream_ = projection.stream;
    projection.stream = function(stream) {
      var rotate = projection.rotate(), rotateStream = stream_(stream), sphereStream = (projection.rotate([ 0, 0 ]),
      stream_(stream));
      projection.rotate(rotate);
      rotateStream.sphere = function() {
        d3.geo.stream(sphere(), sphereStream);
      };
      return rotateStream;
    };
    projection.lobes = function(_) {
      if (!arguments.length) return lobes.map(function(lobes) {
        return lobes.map(function(lobe) {
          return [ [ lobe[0][0] * 180 / π, lobe[0][1] * 180 / π ], [ lobe[1][0] * 180 / π, lobe[1][1] * 180 / π ], [ lobe[2][0] * 180 / π, lobe[2][1] * 180 / π ] ];
        });
      });
      lobes = _.map(function(lobes) {
        return lobes.map(function(lobe) {
          return [ [ lobe[0][0] * π / 180, lobe[0][1] * π / 180 ], [ lobe[1][0] * π / 180, lobe[1][1] * π / 180 ], [ lobe[2][0] * π / 180, lobe[2][1] * π / 180 ] ];
        });
      });
      reset();
      return projection;
    };
    function sphere() {
      var ε = 1e-6, coordinates = [];
      for (var i = 0, n = lobes[0].length; i < n; ++i) {
        var lobe = lobes[0][i], λ0 = lobe[0][0] * 180 / π, φ0 = lobe[0][1] * 180 / π, φ1 = lobe[1][1] * 180 / π, λ2 = lobe[2][0] * 180 / π, φ2 = lobe[2][1] * 180 / π;
        coordinates.push(resample([ [ λ0 + ε, φ0 + ε ], [ λ0 + ε, φ1 - ε ], [ λ2 - ε, φ1 - ε ], [ λ2 - ε, φ2 + ε ] ], 30));
      }
      for (var i = lobes[1].length - 1; i >= 0; --i) {
        var lobe = lobes[1][i], λ0 = lobe[0][0] * 180 / π, φ0 = lobe[0][1] * 180 / π, φ1 = lobe[1][1] * 180 / π, λ2 = lobe[2][0] * 180 / π, φ2 = lobe[2][1] * 180 / π;
        coordinates.push(resample([ [ λ2 - ε, φ2 - ε ], [ λ2 - ε, φ1 + ε ], [ λ0 + ε, φ1 + ε ], [ λ0 + ε, φ0 - ε ] ], 30));
      }
      return {
        type: "Polygon",
        coordinates: [ d3.merge(coordinates) ]
      };
    }
    function resample(coordinates, m) {
      var i = -1, n = coordinates.length, p0 = coordinates[0], p1, dx, dy, resampled = [];
      while (++i < n) {
        p1 = coordinates[i];
        dx = (p1[0] - p0[0]) / m;
        dy = (p1[1] - p0[1]) / m;
        for (var j = 0; j < m; ++j) resampled.push([ p0[0] + j * dx, p0[1] + j * dy ]);
        p0 = p1;
      }
      resampled.push(p1);
      return resampled;
    }
    function pointEqual(a, b) {
      return Math.abs(a[0] - b[0]) < ε && Math.abs(a[1] - b[1]) < ε;
    }
    return projection;
  };
  function eckert4(λ, φ) {
    var k = (2 + halfπ) * Math.sin(φ);
    φ /= 2;
    for (var i = 0, δ = Infinity; i < 10 && Math.abs(δ) > ε; i++) {
      var cosφ = Math.cos(φ);
      φ -= δ = (φ + Math.sin(φ) * (cosφ + 2) - k) / (2 * cosφ * (1 + cosφ));
    }
    return [ 2 / Math.sqrt(π * (4 + π)) * λ * (1 + Math.cos(φ)), 2 * Math.sqrt(π / (4 + π)) * Math.sin(φ) ];
  }
  eckert4.invert = function(x, y) {
    var A = .5 * y * Math.sqrt((4 + π) / π), k = asin(A), c = Math.cos(k);
    return [ x / (2 / Math.sqrt(π * (4 + π)) * (1 + c)), asin((k + A * (c + 2)) / (2 + halfπ)) ];
  };
  (d3.geo.eckert4 = function() {
    return projection(eckert4);
  }).raw = eckert4;
  var hammerAzimuthalEqualArea = d3.geo.azimuthalEqualArea.raw;
  function hammer(A, B) {
    if (arguments.length < 2) B = A;
    if (B === 1) return hammerAzimuthalEqualArea;
    if (B === Infinity) return hammerQuarticAuthalic;
    function forward(λ, φ) {
      var coordinates = hammerAzimuthalEqualArea(λ / B, φ);
      coordinates[0] *= A;
      return coordinates;
    }
    forward.invert = function(x, y) {
      var coordinates = hammerAzimuthalEqualArea.invert(x / A, y);
      coordinates[0] *= B;
      return coordinates;
    };
    return forward;
  }
  function hammerProjection() {
    var B = 2, m = projectionMutator(hammer), p = m(B);
    p.coefficient = function(_) {
      if (!arguments.length) return B;
      return m(B = +_);
    };
    return p;
  }
  function hammerQuarticAuthalic(λ, φ) {
    return [ λ * Math.cos(φ) / Math.cos(φ /= 2), 2 * Math.sin(φ) ];
  }
  hammerQuarticAuthalic.invert = function(x, y) {
    var φ = 2 * asin(y / 2);
    return [ x * Math.cos(φ / 2) / Math.cos(φ), φ ];
  };
  (d3.geo.hammer = hammerProjection).raw = hammer;
  function kavrayskiy7(λ, φ) {
    return [ 3 * λ / (2 * π) * Math.sqrt(π * π / 3 - φ * φ), φ ];
  }
  kavrayskiy7.invert = function(x, y) {
    return [ 2 / 3 * π * x / Math.sqrt(π * π / 3 - y * y), y ];
  };
  (d3.geo.kavrayskiy7 = function() {
    return projection(kavrayskiy7);
  }).raw = kavrayskiy7;
  function miller(λ, φ) {
    return [ λ, 1.25 * Math.log(Math.tan(π / 4 + .4 * φ)) ];
  }
  miller.invert = function(x, y) {
    return [ x, 2.5 * Math.atan(Math.exp(.8 * y)) - .625 * π ];
  };
  (d3.geo.miller = function() {
    return projection(miller);
  }).raw = miller;
  function mollweideBromleyθ(Cp) {
    return function(θ) {
      var Cpsinθ = Cp * Math.sin(θ), i = 30, δ;
      do θ -= δ = (θ + Math.sin(θ) - Cpsinθ) / (1 + Math.cos(θ)); while (Math.abs(δ) > ε && --i > 0);
      return θ / 2;
    };
  }
  function mollweideBromley(Cx, Cy, Cp) {
    var θ = mollweideBromleyθ(Cp);
    function forward(λ, φ) {
      return [ Cx * λ * Math.cos(φ = θ(φ)), Cy * Math.sin(φ) ];
    }
    forward.invert = function(x, y) {
      var θ = asin(y / Cy);
      return [ x / (Cx * Math.cos(θ)), asin((2 * θ + Math.sin(2 * θ)) / Cp) ];
    };
    return forward;
  }
  var mollweideθ = mollweideBromleyθ(π), mollweide = mollweideBromley(Math.SQRT2 / halfπ, Math.SQRT2, π);
  (d3.geo.mollweide = function() {
    return projection(mollweide);
  }).raw = mollweide;
  function naturalEarth(λ, φ) {
    var φ2 = φ * φ, φ4 = φ2 * φ2;
    return [ λ * (.8707 - .131979 * φ2 + φ4 * (-.013791 + φ4 * (.003971 * φ2 - .001529 * φ4))), φ * (1.007226 + φ2 * (.015085 + φ4 * (-.044475 + .028874 * φ2 - .005916 * φ4))) ];
  }
  naturalEarth.invert = function(x, y) {
    var φ = y, i = 25, δ;
    do {
      var φ2 = φ * φ, φ4 = φ2 * φ2;
      φ -= δ = (φ * (1.007226 + φ2 * (.015085 + φ4 * (-.044475 + .028874 * φ2 - .005916 * φ4))) - y) / (1.007226 + φ2 * (.015085 * 3 + φ4 * (-.044475 * 7 + .028874 * 9 * φ2 - .005916 * 11 * φ4)));
    } while (Math.abs(δ) > ε && --i > 0);
    return [ x / (.8707 + (φ2 = φ * φ) * (-.131979 + φ2 * (-.013791 + φ2 * φ2 * φ2 * (.003971 - .001529 * φ2)))), φ ];
  };
  (d3.geo.naturalEarth = function() {
    return projection(naturalEarth);
  }).raw = naturalEarth;
  var robinsonConstants = [ [ .9986, -.062 ], [ 1, 0 ], [ .9986, .062 ], [ .9954, .124 ], [ .99, .186 ], [ .9822, .248 ], [ .973, .31 ], [ .96, .372 ], [ .9427, .434 ], [ .9216, .4958 ], [ .8962, .5571 ], [ .8679, .6176 ], [ .835, .6769 ], [ .7986, .7346 ], [ .7597, .7903 ], [ .7186, .8435 ], [ .6732, .8936 ], [ .6213, .9394 ], [ .5722, .9761 ], [ .5322, 1 ] ];
  robinsonConstants.forEach(function(d) {
    d[1] *= 1.0144;
  });
  function robinson(λ, φ) {
    var i = Math.min(18, Math.abs(φ) * 36 / π), i0 = Math.floor(i), di = i - i0, ax = (k = robinsonConstants[i0])[0], ay = k[1], bx = (k = robinsonConstants[++i0])[0], by = k[1], cx = (k = robinsonConstants[Math.min(19, ++i0)])[0], cy = k[1], k;
    return [ λ * (bx + di * (cx - ax) / 2 + di * di * (cx - 2 * bx + ax) / 2), (φ > 0 ? halfπ : -halfπ) * (by + di * (cy - ay) / 2 + di * di * (cy - 2 * by + ay) / 2) ];
  }
  robinson.invert = function(x, y) {
    var yy = y / halfπ, φ = yy * 90, i = Math.min(18, Math.abs(φ / 5)), i0 = Math.max(0, Math.floor(i));
    do {
      var ay = robinsonConstants[i0][1], by = robinsonConstants[i0 + 1][1], cy = robinsonConstants[Math.min(19, i0 + 2)][1], u = cy - ay, v = cy - 2 * by + ay, t = 2 * (Math.abs(yy) - by) / u, c = v / u, di = t * (1 - c * t * (1 - 2 * c * t));
      if (di >= 0 || i0 === 1) {
        φ = (y >= 0 ? 5 : -5) * (di + i);
        var j = 50, δ;
        do {
          i = Math.min(18, Math.abs(φ) / 5);
          i0 = Math.floor(i);
          di = i - i0;
          ay = robinsonConstants[i0][1];
          by = robinsonConstants[i0 + 1][1];
          cy = robinsonConstants[Math.min(19, i0 + 2)][1];
          φ -= (δ = (y >= 0 ? halfπ : -halfπ) * (by + di * (cy - ay) / 2 + di * di * (cy - 2 * by + ay) / 2) - y) * degrees;
        } while (Math.abs(δ) > ε2 && --j > 0);
        break;
      }
    } while (--i0 >= 0);
    var ax = robinsonConstants[i0][0], bx = robinsonConstants[i0 + 1][0], cx = robinsonConstants[Math.min(19, i0 + 2)][0];
    return [ x / (bx + di * (cx - ax) / 2 + di * di * (cx - 2 * bx + ax) / 2), φ * radians ];
  };
  (d3.geo.robinson = function() {
    return projection(robinson);
  }).raw = robinson;
  function sinusoidal(λ, φ) {
    return [ λ * Math.cos(φ), φ ];
  }
  sinusoidal.invert = function(x, y) {
    return [ x / Math.cos(y), y ];
  };
  (d3.geo.sinusoidal = function() {
    return projection(sinusoidal);
  }).raw = sinusoidal;
  function aitoff(λ, φ) {
    var cosφ = Math.cos(φ), sinciα = sinci(acos(cosφ * Math.cos(λ /= 2)));
    return [ 2 * cosφ * Math.sin(λ) * sinciα, Math.sin(φ) * sinciα ];
  }
  aitoff.invert = function(x, y) {
    if (x * x + 4 * y * y > π * π + ε) return;
    var λ = x, φ = y, i = 25;
    do {
      var sinλ = Math.sin(λ), sinλ_2 = Math.sin(λ / 2), cosλ_2 = Math.cos(λ / 2), sinφ = Math.sin(φ), cosφ = Math.cos(φ), sin_2φ = Math.sin(2 * φ), sin2φ = sinφ * sinφ, cos2φ = cosφ * cosφ, sin2λ_2 = sinλ_2 * sinλ_2, C = 1 - cos2φ * cosλ_2 * cosλ_2, E = C ? acos(cosφ * cosλ_2) * Math.sqrt(F = 1 / C) : F = 0, F, fx = 2 * E * cosφ * sinλ_2 - x, fy = E * sinφ - y, δxδλ = F * (cos2φ * sin2λ_2 + E * cosφ * cosλ_2 * sin2φ), δxδφ = F * (.5 * sinλ * sin_2φ - E * 2 * sinφ * sinλ_2), δyδλ = F * .25 * (sin_2φ * sinλ_2 - E * sinφ * cos2φ * sinλ), δyδφ = F * (sin2φ * cosλ_2 + E * sin2λ_2 * cosφ), denominator = δxδφ * δyδλ - δyδφ * δxδλ;
      if (!denominator) break;
      var δλ = (fy * δxδφ - fx * δyδφ) / denominator, δφ = (fx * δyδλ - fy * δxδλ) / denominator;
      λ -= δλ, φ -= δφ;
    } while ((Math.abs(δλ) > ε || Math.abs(δφ) > ε) && --i > 0);
    return [ λ, φ ];
  };
  (d3.geo.aitoff = function() {
    return projection(aitoff);
  }).raw = aitoff;
  function winkel3(λ, φ) {
    var coordinates = aitoff(λ, φ);
    return [ (coordinates[0] + λ / halfπ) / 2, (coordinates[1] + φ) / 2 ];
  }
  winkel3.invert = function(x, y) {
    var λ = x, φ = y, i = 25;
    do {
      var cosφ = Math.cos(φ), sinφ = Math.sin(φ), sin_2φ = Math.sin(2 * φ), sin2φ = sinφ * sinφ, cos2φ = cosφ * cosφ, sinλ = Math.sin(λ), cosλ_2 = Math.cos(λ / 2), sinλ_2 = Math.sin(λ / 2), sin2λ_2 = sinλ_2 * sinλ_2, C = 1 - cos2φ * cosλ_2 * cosλ_2, E = C ? acos(cosφ * cosλ_2) * Math.sqrt(F = 1 / C) : F = 0, F, fx = .5 * (2 * E * cosφ * sinλ_2 + λ / halfπ) - x, fy = .5 * (E * sinφ + φ) - y, δxδλ = .5 * F * (cos2φ * sin2λ_2 + E * cosφ * cosλ_2 * sin2φ) + .5 / halfπ, δxδφ = F * (sinλ * sin_2φ / 4 - E * sinφ * sinλ_2), δyδλ = .125 * F * (sin_2φ * sinλ_2 - E * sinφ * cos2φ * sinλ), δyδφ = .5 * F * (sin2φ * cosλ_2 + E * sin2λ_2 * cosφ) + .5, denominator = δxδφ * δyδλ - δyδφ * δxδλ, δλ = (fy * δxδφ - fx * δyδφ) / denominator, δφ = (fx * δyδλ - fy * δxδλ) / denominator;
      λ -= δλ, φ -= δφ;
    } while ((Math.abs(δλ) > ε || Math.abs(δφ) > ε) && --i > 0);
    return [ λ, φ ];
  };
  (d3.geo.winkel3 = function() {
    return projection(winkel3);
  }).raw = winkel3;
}

module.exports = addProjectionsToD3;

},{}],780:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var Lib = _dereq_('../../lib');
var Registry = _dereq_('../../registry');

var radians = Math.PI / 180;
var degrees = 180 / Math.PI;
var zoomstartStyle = {cursor: 'pointer'};
var zoomendStyle = {cursor: 'auto'};

function createGeoZoom(geo, geoLayout) {
    var projection = geo.projection;
    var zoomConstructor;

    if(geoLayout._isScoped) {
        zoomConstructor = zoomScoped;
    } else if(geoLayout._isClipped) {
        zoomConstructor = zoomClipped;
    } else {
        zoomConstructor = zoomNonClipped;
    }

    // TODO add a conic-specific zoom

    return zoomConstructor(geo, projection);
}

module.exports = createGeoZoom;

// common to all zoom types
function initZoom(geo, projection) {
    return d3.behavior.zoom()
        .translate(projection.translate())
        .scale(projection.scale());
}

// sync zoom updates with user & full layout
function sync(geo, projection, cb) {
    var id = geo.id;
    var gd = geo.graphDiv;
    var layout = gd.layout;
    var userOpts = layout[id];
    var fullLayout = gd._fullLayout;
    var fullOpts = fullLayout[id];

    var preGUI = {};
    var eventData = {};

    function set(propStr, val) {
        preGUI[id + '.' + propStr] = Lib.nestedProperty(userOpts, propStr).get();
        Registry.call('_storeDirectGUIEdit', layout, fullLayout._preGUI, preGUI);

        var fullNp = Lib.nestedProperty(fullOpts, propStr);
        if(fullNp.get() !== val) {
            fullNp.set(val);
            Lib.nestedProperty(userOpts, propStr).set(val);
            eventData[id + '.' + propStr] = val;
        }
    }

    cb(set);
    set('projection.scale', projection.scale() / geo.fitScale);
    gd.emit('plotly_relayout', eventData);
}

// zoom for scoped projections
function zoomScoped(geo, projection) {
    var zoom = initZoom(geo, projection);

    function handleZoomstart() {
        d3.select(this).style(zoomstartStyle);
    }

    function handleZoom() {
        projection
            .scale(d3.event.scale)
            .translate(d3.event.translate);
        geo.render();
    }

    function syncCb(set) {
        var center = projection.invert(geo.midPt);

        set('center.lon', center[0]);
        set('center.lat', center[1]);
    }

    function handleZoomend() {
        d3.select(this).style(zoomendStyle);
        sync(geo, projection, syncCb);
    }

    zoom
        .on('zoomstart', handleZoomstart)
        .on('zoom', handleZoom)
        .on('zoomend', handleZoomend);

    return zoom;
}

// zoom for non-clipped projections
function zoomNonClipped(geo, projection) {
    var zoom = initZoom(geo, projection);

    var INSIDETOLORANCEPXS = 2;

    var mouse0, rotate0, translate0, lastRotate, zoomPoint,
        mouse1, rotate1, point1, didZoom;

    function position(x) { return projection.invert(x); }

    function outside(x) {
        var pos = position(x);
        if(!pos) return true;

        var pt = projection(pos);
        return (
            Math.abs(pt[0] - x[0]) > INSIDETOLORANCEPXS ||
            Math.abs(pt[1] - x[1]) > INSIDETOLORANCEPXS
        );
    }

    function handleZoomstart() {
        d3.select(this).style(zoomstartStyle);

        mouse0 = d3.mouse(this);
        rotate0 = projection.rotate();
        translate0 = projection.translate();
        lastRotate = rotate0;
        zoomPoint = position(mouse0);
    }

    function handleZoom() {
        mouse1 = d3.mouse(this);

        if(outside(mouse0)) {
            zoom.scale(projection.scale());
            zoom.translate(projection.translate());
            return;
        }

        projection.scale(d3.event.scale);
        projection.translate([translate0[0], d3.event.translate[1]]);

        if(!zoomPoint) {
            mouse0 = mouse1;
            zoomPoint = position(mouse0);
        }
        else if(position(mouse1)) {
            point1 = position(mouse1);
            rotate1 = [lastRotate[0] + (point1[0] - zoomPoint[0]), rotate0[1], rotate0[2]];
            projection.rotate(rotate1);
            lastRotate = rotate1;
        }

        didZoom = true;
        geo.render();
    }

    function handleZoomend() {
        d3.select(this).style(zoomendStyle);
        if(didZoom) sync(geo, projection, syncCb);
    }

    function syncCb(set) {
        var rotate = projection.rotate();
        var center = projection.invert(geo.midPt);

        set('projection.rotation.lon', -rotate[0]);
        set('center.lon', center[0]);
        set('center.lat', center[1]);
    }

    zoom
        .on('zoomstart', handleZoomstart)
        .on('zoom', handleZoom)
        .on('zoomend', handleZoomend);

    return zoom;
}

// zoom for clipped projections
// inspired by https://www.jasondavies.com/maps/d3.geo.zoom.js
function zoomClipped(geo, projection) {
    var view = {r: projection.rotate(), k: projection.scale()};
    var zoom = initZoom(geo, projection);
    var event = d3eventDispatch(zoom, 'zoomstart', 'zoom', 'zoomend');
    var zooming = 0;
    var zoomOn = zoom.on;

    var zoomPoint;

    zoom.on('zoomstart', function() {
        d3.select(this).style(zoomstartStyle);

        var mouse0 = d3.mouse(this);
        var rotate0 = projection.rotate();
        var lastRotate = rotate0;
        var translate0 = projection.translate();
        var q = quaternionFromEuler(rotate0);

        zoomPoint = position(projection, mouse0);

        zoomOn.call(zoom, 'zoom', function() {
            var mouse1 = d3.mouse(this);

            projection.scale(view.k = d3.event.scale);

            if(!zoomPoint) {
                // if no zoomPoint, the mouse wasn't over the actual geography yet
                // maybe this point is the start... we'll find out next time!
                mouse0 = mouse1;
                zoomPoint = position(projection, mouse0);
            }
            // check if the point is on the map
            // if not, don't do anything new but scale
            // if it is, then we can assume between will exist below
            // so we don't need the 'bank' function, whatever that is.
            else if(position(projection, mouse1)) {
                // go back to original projection temporarily
                // except for scale... that's kind of independent?
                projection
                    .rotate(rotate0)
                    .translate(translate0);

                // calculate the new params
                var point1 = position(projection, mouse1);
                var between = rotateBetween(zoomPoint, point1);
                var newEuler = eulerFromQuaternion(multiply(q, between));
                var rotateAngles = view.r = unRoll(newEuler, zoomPoint, lastRotate);

                if(!isFinite(rotateAngles[0]) || !isFinite(rotateAngles[1]) ||
                   !isFinite(rotateAngles[2])) {
                    rotateAngles = lastRotate;
                }

                // update the projection
                projection.rotate(rotateAngles);
                lastRotate = rotateAngles;
            }

            zoomed(event.of(this, arguments));
        });

        zoomstarted(event.of(this, arguments));
    })
    .on('zoomend', function() {
        d3.select(this).style(zoomendStyle);
        zoomOn.call(zoom, 'zoom', null);
        zoomended(event.of(this, arguments));
        sync(geo, projection, syncCb);
    })
    .on('zoom.redraw', function() {
        geo.render();
    });

    function zoomstarted(dispatch) {
        if(!zooming++) dispatch({type: 'zoomstart'});
    }

    function zoomed(dispatch) {
        dispatch({type: 'zoom'});
    }

    function zoomended(dispatch) {
        if(!--zooming) dispatch({type: 'zoomend'});
    }

    function syncCb(set) {
        var _rotate = projection.rotate();
        set('projection.rotation.lon', -_rotate[0]);
        set('projection.rotation.lat', -_rotate[1]);
    }

    return d3.rebind(zoom, event, 'on');
}

// -- helper functions for zoomClipped

function position(projection, point) {
    var spherical = projection.invert(point);
    return spherical && isFinite(spherical[0]) && isFinite(spherical[1]) && cartesian(spherical);
}

function quaternionFromEuler(euler) {
    var lambda = 0.5 * euler[0] * radians;
    var phi = 0.5 * euler[1] * radians;
    var gamma = 0.5 * euler[2] * radians;
    var sinLambda = Math.sin(lambda);
    var cosLambda = Math.cos(lambda);
    var sinPhi = Math.sin(phi);
    var cosPhi = Math.cos(phi);
    var sinGamma = Math.sin(gamma);
    var cosGamma = Math.cos(gamma);
    return [
        cosLambda * cosPhi * cosGamma + sinLambda * sinPhi * sinGamma,
        sinLambda * cosPhi * cosGamma - cosLambda * sinPhi * sinGamma,
        cosLambda * sinPhi * cosGamma + sinLambda * cosPhi * sinGamma,
        cosLambda * cosPhi * sinGamma - sinLambda * sinPhi * cosGamma
    ];
}

function multiply(a, b) {
    var a0 = a[0];
    var a1 = a[1];
    var a2 = a[2];
    var a3 = a[3];
    var b0 = b[0];
    var b1 = b[1];
    var b2 = b[2];
    var b3 = b[3];
    return [
        a0 * b0 - a1 * b1 - a2 * b2 - a3 * b3,
        a0 * b1 + a1 * b0 + a2 * b3 - a3 * b2,
        a0 * b2 - a1 * b3 + a2 * b0 + a3 * b1,
        a0 * b3 + a1 * b2 - a2 * b1 + a3 * b0
    ];
}

function rotateBetween(a, b) {
    if(!a || !b) return;
    var axis = cross(a, b);
    var norm = Math.sqrt(dot(axis, axis));
    var halfgamma = 0.5 * Math.acos(Math.max(-1, Math.min(1, dot(a, b))));
    var k = Math.sin(halfgamma) / norm;
    return norm && [Math.cos(halfgamma), axis[2] * k, -axis[1] * k, axis[0] * k];
}

// input:
//   rotateAngles: a calculated set of Euler angles
//   pt: a point (cartesian in 3-space) to keep fixed
//   roll0: an initial roll, to be preserved
// output:
//   a set of Euler angles that preserve the projection of pt
//     but set roll (output[2]) equal to roll0
//     note that this doesn't depend on the particular projection,
//     just on the rotation angles
function unRoll(rotateAngles, pt, lastRotate) {
    // calculate the fixed point transformed by these Euler angles
    // but with the desired roll undone
    var ptRotated = rotateCartesian(pt, 2, rotateAngles[0]);
    ptRotated = rotateCartesian(ptRotated, 1, rotateAngles[1]);
    ptRotated = rotateCartesian(ptRotated, 0, rotateAngles[2] - lastRotate[2]);

    var x = pt[0];
    var y = pt[1];
    var z = pt[2];
    var f = ptRotated[0];
    var g = ptRotated[1];
    var h = ptRotated[2];

    // the following essentially solves:
    // ptRotated = rotateCartesian(rotateCartesian(pt, 2, newYaw), 1, newPitch)
    // for newYaw and newPitch, as best it can
    var theta = Math.atan2(y, x) * degrees;
    var a = Math.sqrt(x * x + y * y);
    var b;
    var newYaw1;

    if(Math.abs(g) > a) {
        newYaw1 = (g > 0 ? 90 : -90) - theta;
        b = 0;
    } else {
        newYaw1 = Math.asin(g / a) * degrees - theta;
        b = Math.sqrt(a * a - g * g);
    }

    var newYaw2 = 180 - newYaw1 - 2 * theta;
    var newPitch1 = (Math.atan2(h, f) - Math.atan2(z, b)) * degrees;
    var newPitch2 = (Math.atan2(h, f) - Math.atan2(z, -b)) * degrees;

    // which is closest to lastRotate[0,1]: newYaw/Pitch or newYaw2/Pitch2?
    var dist1 = angleDistance(lastRotate[0], lastRotate[1], newYaw1, newPitch1);
    var dist2 = angleDistance(lastRotate[0], lastRotate[1], newYaw2, newPitch2);

    if(dist1 <= dist2) return [newYaw1, newPitch1, lastRotate[2]];
    else return [newYaw2, newPitch2, lastRotate[2]];
}

function angleDistance(yaw0, pitch0, yaw1, pitch1) {
    var dYaw = angleMod(yaw1 - yaw0);
    var dPitch = angleMod(pitch1 - pitch0);
    return Math.sqrt(dYaw * dYaw + dPitch * dPitch);
}

// reduce an angle in degrees to [-180,180]
function angleMod(angle) {
    return (angle % 360 + 540) % 360 - 180;
}

// rotate a cartesian vector
// axis is 0 (x), 1 (y), or 2 (z)
// angle is in degrees
function rotateCartesian(vector, axis, angle) {
    var angleRads = angle * radians;
    var vectorOut = vector.slice();
    var ax1 = (axis === 0) ? 1 : 0;
    var ax2 = (axis === 2) ? 1 : 2;
    var cosa = Math.cos(angleRads);
    var sina = Math.sin(angleRads);

    vectorOut[ax1] = vector[ax1] * cosa - vector[ax2] * sina;
    vectorOut[ax2] = vector[ax2] * cosa + vector[ax1] * sina;

    return vectorOut;
}
function eulerFromQuaternion(q) {
    return [
        Math.atan2(2 * (q[0] * q[1] + q[2] * q[3]), 1 - 2 * (q[1] * q[1] + q[2] * q[2])) * degrees,
        Math.asin(Math.max(-1, Math.min(1, 2 * (q[0] * q[2] - q[3] * q[1])))) * degrees,
        Math.atan2(2 * (q[0] * q[3] + q[1] * q[2]), 1 - 2 * (q[2] * q[2] + q[3] * q[3])) * degrees
    ];
}

function cartesian(spherical) {
    var lambda = spherical[0] * radians;
    var phi = spherical[1] * radians;
    var cosPhi = Math.cos(phi);
    return [
        cosPhi * Math.cos(lambda),
        cosPhi * Math.sin(lambda),
        Math.sin(phi)
    ];
}

function dot(a, b) {
    var s = 0;
    for(var i = 0, n = a.length; i < n; ++i) s += a[i] * b[i];
    return s;
}

function cross(a, b) {
    return [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0]
    ];
}

// Like d3.dispatch, but for custom events abstracting native UI events. These
// events have a target component (such as a brush), a target element (such as
// the svg:g element containing the brush) and the standard arguments `d` (the
// target element's data) and `i` (the selection index of the target element).
function d3eventDispatch(target) {
    var i = 0;
    var n = arguments.length;
    var argumentz = [];

    while(++i < n) argumentz.push(arguments[i]);

    var dispatch = d3.dispatch.apply(null, argumentz);

    // Creates a dispatch context for the specified `thiz` (typically, the target
    // DOM element that received the source event) and `argumentz` (typically, the
    // data `d` and index `i` of the target element). The returned function can be
    // used to dispatch an event to any registered listeners; the function takes a
    // single argument as input, being the event to dispatch. The event must have
    // a "type" attribute which corresponds to a type registered in the
    // constructor. This context will automatically populate the "sourceEvent" and
    // "target" attributes of the event, as well as setting the `d3.event` global
    // for the duration of the notification.
    dispatch.of = function(thiz, argumentz) {
        return function(e1) {
            var e0;
            try {
                e0 = e1.sourceEvent = d3.event;
                e1.target = target;
                d3.event = e1;
                dispatch[e1.type].apply(thiz, argumentz);
            } finally {
                d3.event = e0;
            }
        };
    };

    return dispatch;
}

},{"../../lib":697,"../../registry":826,"d3":151}],781:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../registry');
var SUBPLOT_PATTERN = _dereq_('./cartesian/constants').SUBPLOT_PATTERN;

/**
 * Get calcdata trace(s) associated with a given subplot
 *
 * @param {array} calcData: as in gd.calcdata
 * @param {string} type: subplot type
 * @param {string} subplotId: subplot id to look for
 *
 * @return {array} array of calcdata traces
 */
exports.getSubplotCalcData = function(calcData, type, subplotId) {
    var basePlotModule = Registry.subplotsRegistry[type];
    if(!basePlotModule) return [];

    var attr = basePlotModule.attr;
    var subplotCalcData = [];

    for(var i = 0; i < calcData.length; i++) {
        var calcTrace = calcData[i];
        var trace = calcTrace[0].trace;

        if(trace[attr] === subplotId) subplotCalcData.push(calcTrace);
    }

    return subplotCalcData;
};
/**
 * Get calcdata trace(s) that can be plotted with a given module
 * NOTE: this isn't necessarily just exactly matching trace type,
 * if multiple trace types use the same plotting routine, they will be
 * collected here.
 * In order to not plot the same thing multiple times, we return two arrays,
 * the calcdata we *will* plot with this module, and the ones we *won't*
 *
 * @param {array} calcdata: as in gd.calcdata
 * @param {object|string|fn} arg1:
 *  the plotting module, or its name, or its plot method
 *
 * @return {array[array]} [foundCalcdata, remainingCalcdata]
 */
exports.getModuleCalcData = function(calcdata, arg1) {
    var moduleCalcData = [];
    var remainingCalcData = [];

    var plotMethod;
    if(typeof arg1 === 'string') {
        plotMethod = Registry.getModule(arg1).plot;
    } else if(typeof arg1 === 'function') {
        plotMethod = arg1;
    } else {
        plotMethod = arg1.plot;
    }
    if(!plotMethod) {
        return [moduleCalcData, calcdata];
    }

    for(var i = 0; i < calcdata.length; i++) {
        var cd = calcdata[i];
        var trace = cd[0].trace;
        // N.B. 'legendonly' traces do not make it past here
        if(trace.visible !== true) continue;

        // group calcdata trace not by 'module' (as the name of this function
        // would suggest), but by 'module plot method' so that if some traces
        // share the same module plot method (e.g. bar and histogram), we
        // only call it one!
        if(trace._module.plot === plotMethod) {
            moduleCalcData.push(cd);
        } else {
            remainingCalcData.push(cd);
        }
    }

    return [moduleCalcData, remainingCalcData];
};

/**
 * Get the data trace(s) associated with a given subplot.
 *
 * @param {array} data  plotly full data array.
 * @param {string} type subplot type to look for.
 * @param {string} subplotId subplot id to look for.
 *
 * @return {array} list of trace objects.
 *
 */
exports.getSubplotData = function getSubplotData(data, type, subplotId) {
    if(!Registry.subplotsRegistry[type]) return [];

    var attr = Registry.subplotsRegistry[type].attr;
    var subplotData = [];
    var trace, subplotX, subplotY;

    if(type === 'gl2d') {
        var spmatch = subplotId.match(SUBPLOT_PATTERN);
        subplotX = 'x' + spmatch[1];
        subplotY = 'y' + spmatch[2];
    }

    for(var i = 0; i < data.length; i++) {
        trace = data[i];

        if(type === 'gl2d' && Registry.traceIs(trace, 'gl2d')) {
            if(trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) {
                subplotData.push(trace);
            }
        }
        else {
            if(trace[attr] === subplotId) subplotData.push(trace);
        }
    }

    return subplotData;
};

},{"../registry":826,"./cartesian/constants":751}],782:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var mouseChange = _dereq_('mouse-change');
var mouseWheel = _dereq_('mouse-wheel');
var mouseOffset = _dereq_('mouse-event-offset');
var cartesianConstants = _dereq_('../cartesian/constants');
var hasPassive = _dereq_('has-passive-events');

module.exports = createCamera;

function Camera2D(element, plot) {
    this.element = element;
    this.plot = plot;
    this.mouseListener = null;
    this.wheelListener = null;
    this.lastInputTime = Date.now();
    this.lastPos = [0, 0];
    this.boxEnabled = false;
    this.boxInited = false;
    this.boxStart = [0, 0];
    this.boxEnd = [0, 0];
    this.dragStart = [0, 0];
}


function createCamera(scene) {
    var element = scene.mouseContainer;
    var plot = scene.glplot;
    var result = new Camera2D(element, plot);

    function unSetAutoRange() {
        scene.xaxis.autorange = false;
        scene.yaxis.autorange = false;
    }

    function getSubplotConstraint() {
        // note: this assumes we only have one x and one y axis on this subplot
        // when this constraint is lifted this block won't make sense
        var constraints = scene.graphDiv._fullLayout._axisConstraintGroups;
        var xaId = scene.xaxis._id;
        var yaId = scene.yaxis._id;
        for(var i = 0; i < constraints.length; i++) {
            if(constraints[i][xaId] !== -1) {
                if(constraints[i][yaId] !== -1) return true;
                break;
            }
        }
        return false;
    }

    result.mouseListener = mouseChange(element, handleInteraction);

    // enable simple touch interactions
    element.addEventListener('touchstart', function(ev) {
        var xy = mouseOffset(ev.changedTouches[0], element);
        handleInteraction(0, xy[0], xy[1]);
        handleInteraction(1, xy[0], xy[1]);

        ev.preventDefault();
    }, hasPassive ? {passive: false} : false);
    element.addEventListener('touchmove', function(ev) {
        ev.preventDefault();
        var xy = mouseOffset(ev.changedTouches[0], element);
        handleInteraction(1, xy[0], xy[1]);

        ev.preventDefault();
    }, hasPassive ? {passive: false} : false);
    element.addEventListener('touchend', function(ev) {
        handleInteraction(0, result.lastPos[0], result.lastPos[1]);

        ev.preventDefault();
    }, hasPassive ? {passive: false} : false);

    function handleInteraction(buttons, x, y) {
        var dataBox = scene.calcDataBox();
        var viewBox = plot.viewBox;

        var lastX = result.lastPos[0];
        var lastY = result.lastPos[1];

        var MINDRAG = cartesianConstants.MINDRAG * plot.pixelRatio;
        var MINZOOM = cartesianConstants.MINZOOM * plot.pixelRatio;

        var dx, dy;

        x *= plot.pixelRatio;
        y *= plot.pixelRatio;

        // mouseChange gives y about top; convert to about bottom
        y = (viewBox[3] - viewBox[1]) - y;

        function updateRange(i0, start, end) {
            var range0 = Math.min(start, end);
            var range1 = Math.max(start, end);

            if(range0 !== range1) {
                dataBox[i0] = range0;
                dataBox[i0 + 2] = range1;
                result.dataBox = dataBox;
                scene.setRanges(dataBox);
            }
            else {
                scene.selectBox.selectBox = [0, 0, 1, 1];
                scene.glplot.setDirty();
            }
        }

        switch(scene.fullLayout.dragmode) {
            case 'zoom':
                if(buttons) {
                    var dataX = x /
                            (viewBox[2] - viewBox[0]) * (dataBox[2] - dataBox[0]) +
                        dataBox[0];
                    var dataY = y /
                            (viewBox[3] - viewBox[1]) * (dataBox[3] - dataBox[1]) +
                        dataBox[1];

                    if(!result.boxInited) {
                        result.boxStart[0] = dataX;
                        result.boxStart[1] = dataY;
                        result.dragStart[0] = x;
                        result.dragStart[1] = y;
                    }

                    result.boxEnd[0] = dataX;
                    result.boxEnd[1] = dataY;

                    // we need to mark the box as initialized right away
                    // so that we can tell the start and end points apart
                    result.boxInited = true;

                    // but don't actually enable the box until the cursor moves
                    if(!result.boxEnabled && (
                        result.boxStart[0] !== result.boxEnd[0] ||
                        result.boxStart[1] !== result.boxEnd[1])
                    ) {
                        result.boxEnabled = true;
                    }

                    // constrain aspect ratio if the axes require it
                    var smallDx = Math.abs(result.dragStart[0] - x) < MINZOOM;
                    var smallDy = Math.abs(result.dragStart[1] - y) < MINZOOM;
                    if(getSubplotConstraint() && !(smallDx && smallDy)) {
                        dx = result.boxEnd[0] - result.boxStart[0];
                        dy = result.boxEnd[1] - result.boxStart[1];
                        var dydx = (dataBox[3] - dataBox[1]) / (dataBox[2] - dataBox[0]);

                        if(Math.abs(dx * dydx) > Math.abs(dy)) {
                            result.boxEnd[1] = result.boxStart[1] +
                                Math.abs(dx) * dydx * (dy >= 0 ? 1 : -1);

                            // gl-select-box clips to the plot area bounds,
                            // which breaks the axis constraint, so don't allow
                            // this box to go out of bounds
                            if(result.boxEnd[1] < dataBox[1]) {
                                result.boxEnd[1] = dataBox[1];
                                result.boxEnd[0] = result.boxStart[0] +
                                    (dataBox[1] - result.boxStart[1]) / Math.abs(dydx);
                            }
                            else if(result.boxEnd[1] > dataBox[3]) {
                                result.boxEnd[1] = dataBox[3];
                                result.boxEnd[0] = result.boxStart[0] +
                                    (dataBox[3] - result.boxStart[1]) / Math.abs(dydx);
                            }
                        }
                        else {
                            result.boxEnd[0] = result.boxStart[0] +
                                Math.abs(dy) / dydx * (dx >= 0 ? 1 : -1);

                            if(result.boxEnd[0] < dataBox[0]) {
                                result.boxEnd[0] = dataBox[0];
                                result.boxEnd[1] = result.boxStart[1] +
                                    (dataBox[0] - result.boxStart[0]) * Math.abs(dydx);
                            }
                            else if(result.boxEnd[0] > dataBox[2]) {
                                result.boxEnd[0] = dataBox[2];
                                result.boxEnd[1] = result.boxStart[1] +
                                    (dataBox[2] - result.boxStart[0]) * Math.abs(dydx);
                            }
                        }
                    }
                    // otherwise clamp small changes to the origin so we get 1D zoom
                    else {
                        if(smallDx) result.boxEnd[0] = result.boxStart[0];
                        if(smallDy) result.boxEnd[1] = result.boxStart[1];
                    }
                }
                else if(result.boxEnabled) {
                    dx = result.boxStart[0] !== result.boxEnd[0];
                    dy = result.boxStart[1] !== result.boxEnd[1];
                    if(dx || dy) {
                        if(dx) {
                            updateRange(0, result.boxStart[0], result.boxEnd[0]);
                            scene.xaxis.autorange = false;
                        }
                        if(dy) {
                            updateRange(1, result.boxStart[1], result.boxEnd[1]);
                            scene.yaxis.autorange = false;
                        }
                        scene.relayoutCallback();
                    }
                    else {
                        scene.glplot.setDirty();
                    }
                    result.boxEnabled = false;
                    result.boxInited = false;
                }
                // if box was inited but button released then - reset the box
                else if(result.boxInited) {
                    result.boxInited = false;
                }
                break;

            case 'pan':
                result.boxEnabled = false;
                result.boxInited = false;

                if(buttons) {
                    if(!result.panning) {
                        result.dragStart[0] = x;
                        result.dragStart[1] = y;
                    }

                    if(Math.abs(result.dragStart[0] - x) < MINDRAG) x = result.dragStart[0];
                    if(Math.abs(result.dragStart[1] - y) < MINDRAG) y = result.dragStart[1];

                    dx = (lastX - x) * (dataBox[2] - dataBox[0]) /
                        (plot.viewBox[2] - plot.viewBox[0]);
                    dy = (lastY - y) * (dataBox[3] - dataBox[1]) /
                        (plot.viewBox[3] - plot.viewBox[1]);

                    dataBox[0] += dx;
                    dataBox[2] += dx;
                    dataBox[1] += dy;
                    dataBox[3] += dy;

                    scene.setRanges(dataBox);

                    result.panning = true;
                    result.lastInputTime = Date.now();
                    unSetAutoRange();
                    scene.cameraChanged();
                    scene.handleAnnotations();
                }
                else if(result.panning) {
                    result.panning = false;
                    scene.relayoutCallback();
                }
                break;
        }

        result.lastPos[0] = x;
        result.lastPos[1] = y;
    }

    result.wheelListener = mouseWheel(element, function(dx, dy) {
        if(!scene.scrollZoom) return false;

        var dataBox = scene.calcDataBox();
        var viewBox = plot.viewBox;

        var lastX = result.lastPos[0];
        var lastY = result.lastPos[1];

        var scale = Math.exp(5.0 * dy / (viewBox[3] - viewBox[1]));

        var cx = lastX /
                (viewBox[2] - viewBox[0]) * (dataBox[2] - dataBox[0]) +
            dataBox[0];
        var cy = lastY /
                (viewBox[3] - viewBox[1]) * (dataBox[3] - dataBox[1]) +
            dataBox[1];

        dataBox[0] = (dataBox[0] - cx) * scale + cx;
        dataBox[2] = (dataBox[2] - cx) * scale + cx;
        dataBox[1] = (dataBox[1] - cy) * scale + cy;
        dataBox[3] = (dataBox[3] - cy) * scale + cy;

        scene.setRanges(dataBox);

        result.lastInputTime = Date.now();
        unSetAutoRange();
        scene.cameraChanged();
        scene.handleAnnotations();
        scene.relayoutCallback();

        return true;
    }, true);

    return result;
}

},{"../cartesian/constants":751,"has-passive-events":400,"mouse-change":424,"mouse-event-offset":425,"mouse-wheel":427}],783:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Axes = _dereq_('../cartesian/axes');

var str2RGBArray = _dereq_('../../lib/str2rgbarray');

function Axes2DOptions(scene) {
    this.scene = scene;
    this.gl = scene.gl;
    this.pixelRatio = scene.pixelRatio;

    this.screenBox = [0, 0, 1, 1];
    this.viewBox = [0, 0, 1, 1];
    this.dataBox = [-1, -1, 1, 1];

    this.borderLineEnable = [false, false, false, false];
    this.borderLineWidth = [1, 1, 1, 1];
    this.borderLineColor = [
        [0, 0, 0, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 1]
    ];

    this.ticks = [[], []];
    this.tickEnable = [true, true, false, false];
    this.tickPad = [15, 15, 15, 15];
    this.tickAngle = [0, 0, 0, 0];
    this.tickColor = [
        [0, 0, 0, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 1]
    ];
    this.tickMarkLength = [0, 0, 0, 0];
    this.tickMarkWidth = [0, 0, 0, 0];
    this.tickMarkColor = [
        [0, 0, 0, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 1]
    ];

    this.labels = ['x', 'y'];
    this.labelEnable = [true, true, false, false];
    this.labelAngle = [0, Math.PI / 2, 0, 3.0 * Math.PI / 2];
    this.labelPad = [15, 15, 15, 15];
    this.labelSize = [12, 12];
    this.labelFont = ['sans-serif', 'sans-serif'];
    this.labelColor = [
        [0, 0, 0, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 1]
    ];

    this.title = '';
    this.titleEnable = true;
    this.titleCenter = [0, 0, 0, 0];
    this.titleAngle = 0;
    this.titleColor = [0, 0, 0, 1];
    this.titleFont = 'sans-serif';
    this.titleSize = 18;

    this.gridLineEnable = [true, true];
    this.gridLineColor = [
        [0, 0, 0, 0.5],
        [0, 0, 0, 0.5]
    ];
    this.gridLineWidth = [1, 1];

    this.zeroLineEnable = [true, true];
    this.zeroLineWidth = [1, 1];
    this.zeroLineColor = [
        [0, 0, 0, 1],
        [0, 0, 0, 1]
    ];

    this.borderColor = [0, 0, 0, 0];
    this.backgroundColor = [0, 0, 0, 0];

    this.static = this.scene.staticPlot;
}

var proto = Axes2DOptions.prototype;

var AXES = ['xaxis', 'yaxis'];

proto.merge = function(options) {

    // titles are rendered in SVG
    this.titleEnable = false;
    this.backgroundColor = str2RGBArray(options.plot_bgcolor);

    var axisName, ax, axTitle, axMirror;
    var hasAxisInDfltPos, hasAxisInAltrPos, hasSharedAxis, mirrorLines, mirrorTicks;
    var i, j;

    for(i = 0; i < 2; ++i) {
        axisName = AXES[i];
        var axisLetter = axisName.charAt(0);

        // get options relevant to this subplot,
        // '_name' is e.g. xaxis, xaxis2, yaxis, yaxis4 ...
        ax = options[this.scene[axisName]._name];

        axTitle = ax.title.text === this.scene.fullLayout._dfltTitle[axisLetter] ? '' : ax.title.text;

        for(j = 0; j <= 2; j += 2) {
            this.labelEnable[i + j] = false;
            this.labels[i + j] = axTitle;
            this.labelColor[i + j] = str2RGBArray(ax.title.font.color);
            this.labelFont[i + j] = ax.title.font.family;
            this.labelSize[i + j] = ax.title.font.size;
            this.labelPad[i + j] = this.getLabelPad(axisName, ax);

            this.tickEnable[i + j] = false;
            this.tickColor[i + j] = str2RGBArray((ax.tickfont || {}).color);
            this.tickAngle[i + j] = (ax.tickangle === 'auto') ?
                0 :
                Math.PI * -ax.tickangle / 180;
            this.tickPad[i + j] = this.getTickPad(ax);

            this.tickMarkLength[i + j] = 0;
            this.tickMarkWidth[i + j] = ax.tickwidth || 0;
            this.tickMarkColor[i + j] = str2RGBArray(ax.tickcolor);

            this.borderLineEnable[i + j] = false;
            this.borderLineColor[i + j] = str2RGBArray(ax.linecolor);
            this.borderLineWidth[i + j] = ax.linewidth || 0;
        }

        hasSharedAxis = this.hasSharedAxis(ax);
        hasAxisInDfltPos = this.hasAxisInDfltPos(axisName, ax) && !hasSharedAxis;
        hasAxisInAltrPos = this.hasAxisInAltrPos(axisName, ax) && !hasSharedAxis;

        axMirror = ax.mirror || false;
        mirrorLines = hasSharedAxis ?
            (String(axMirror).indexOf('all') !== -1) :  // 'all' or 'allticks'
            !!axMirror;                                 // all but false
        mirrorTicks = hasSharedAxis ?
            (axMirror === 'allticks') :
            (String(axMirror).indexOf('ticks') !== -1); // 'ticks' or 'allticks'

        // Axis titles and tick labels can only appear of one side of the scene
        //  and are never show on subplots that share existing axes.

        if(hasAxisInDfltPos) this.labelEnable[i] = true;
        else if(hasAxisInAltrPos) this.labelEnable[i + 2] = true;

        if(hasAxisInDfltPos) this.tickEnable[i] = ax.showticklabels;
        else if(hasAxisInAltrPos) this.tickEnable[i + 2] = ax.showticklabels;

        // Grid lines and ticks can appear on both sides of the scene
        //  and can appear on subplot that share existing axes via `ax.mirror`.

        if(hasAxisInDfltPos || mirrorLines) this.borderLineEnable[i] = ax.showline;
        if(hasAxisInAltrPos || mirrorLines) this.borderLineEnable[i + 2] = ax.showline;

        if(hasAxisInDfltPos || mirrorTicks) this.tickMarkLength[i] = this.getTickMarkLength(ax);
        if(hasAxisInAltrPos || mirrorTicks) this.tickMarkLength[i + 2] = this.getTickMarkLength(ax);

        this.gridLineEnable[i] = ax.showgrid;
        this.gridLineColor[i] = str2RGBArray(ax.gridcolor);
        this.gridLineWidth[i] = ax.gridwidth;

        this.zeroLineEnable[i] = ax.zeroline;
        this.zeroLineColor[i] = str2RGBArray(ax.zerolinecolor);
        this.zeroLineWidth[i] = ax.zerolinewidth;
    }
};

// is an axis shared with an already-drawn subplot ?
proto.hasSharedAxis = function(ax) {
    var scene = this.scene;
    var subplotIds = scene.fullLayout._subplots.gl2d;
    var list = Axes.findSubplotsWithAxis(subplotIds, ax);

    // if index === 0, then the subplot is already drawn as subplots
    // are drawn in order.
    return (list.indexOf(scene.id) !== 0);
};

// has an axis in default position (i.e. bottom/left) ?
proto.hasAxisInDfltPos = function(axisName, ax) {
    var axSide = ax.side;

    if(axisName === 'xaxis') return (axSide === 'bottom');
    else if(axisName === 'yaxis') return (axSide === 'left');
};

// has an axis in alternate position (i.e. top/right) ?
proto.hasAxisInAltrPos = function(axisName, ax) {
    var axSide = ax.side;

    if(axisName === 'xaxis') return (axSide === 'top');
    else if(axisName === 'yaxis') return (axSide === 'right');
};

proto.getLabelPad = function(axisName, ax) {
    var offsetBase = 1.5;
    var fontSize = ax.title.font.size;
    var showticklabels = ax.showticklabels;

    if(axisName === 'xaxis') {
        return (ax.side === 'top') ?
            -10 + fontSize * (offsetBase + (showticklabels ? 1 : 0)) :
            -10 + fontSize * (offsetBase + (showticklabels ? 0.5 : 0));
    }
    else if(axisName === 'yaxis') {
        return (ax.side === 'right') ?
            10 + fontSize * (offsetBase + (showticklabels ? 1 : 0.5)) :
            10 + fontSize * (offsetBase + (showticklabels ? 0.5 : 0));
    }
};

proto.getTickPad = function(ax) {
    return (ax.ticks === 'outside') ? 10 + ax.ticklen : 15;
};

proto.getTickMarkLength = function(ax) {
    if(!ax.ticks) return 0;

    var ticklen = ax.ticklen;

    return (ax.ticks === 'inside') ? -ticklen : ticklen;
};


function createAxes2D(scene) {
    return new Axes2DOptions(scene);
}

module.exports = createAxes2D;

},{"../../lib/str2rgbarray":720,"../cartesian/axes":745}],784:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;

var Scene2D = _dereq_('./scene2d');
var layoutGlobalAttrs = _dereq_('../layout_attributes');
var xmlnsNamespaces = _dereq_('../../constants/xmlns_namespaces');
var constants = _dereq_('../cartesian/constants');
var Cartesian = _dereq_('../cartesian');
var fxAttrs = _dereq_('../../components/fx/layout_attributes');
var getSubplotData = _dereq_('../get_data').getSubplotData;

exports.name = 'gl2d';

exports.attr = ['xaxis', 'yaxis'];

exports.idRoot = ['x', 'y'];

exports.idRegex = constants.idRegex;

exports.attrRegex = constants.attrRegex;

exports.attributes = _dereq_('../cartesian/attributes');

exports.supplyLayoutDefaults = function(layoutIn, layoutOut, fullData) {
    if(!layoutOut._has('cartesian')) {
        Cartesian.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
    }
};

// gl2d uses svg axis attributes verbatim, but overrides editType
// this could potentially be just `layoutAttributes` but it would
// still need special handling somewhere to give it precedence over
// the svg version when both are in use on one plot
exports.layoutAttrOverrides = overrideAll(Cartesian.layoutAttributes, 'plot', 'from-root');

// similar overrides for base plot attributes (and those added by components)
exports.baseLayoutAttrOverrides = overrideAll({
    plot_bgcolor: layoutGlobalAttrs.plot_bgcolor,
    hoverlabel: fxAttrs.hoverlabel
    // dragmode needs calc but only when transitioning TO lasso or select
    // so for now it's left inside _relayout
    // dragmode: fxAttrs.dragmode
}, 'plot', 'nested');

exports.plot = function plotGl2d(gd) {
    var fullLayout = gd._fullLayout;
    var fullData = gd._fullData;
    var subplotIds = fullLayout._subplots.gl2d;

    for(var i = 0; i < subplotIds.length; i++) {
        var subplotId = subplotIds[i];
        var subplotObj = fullLayout._plots[subplotId];
        var fullSubplotData = getSubplotData(fullData, 'gl2d', subplotId);

        // ref. to corresp. Scene instance
        var scene = subplotObj._scene2d;

        // If Scene is not instantiated, create one!
        if(scene === undefined) {
            scene = new Scene2D({
                id: subplotId,
                graphDiv: gd,
                container: gd.querySelector('.gl-container'),
                staticPlot: gd._context.staticPlot,
                plotGlPixelRatio: gd._context.plotGlPixelRatio
            },
                fullLayout
            );

            // set ref to Scene instance
            subplotObj._scene2d = scene;
        }

        scene.plot(fullSubplotData, gd.calcdata, fullLayout, gd.layout);
    }
};

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var oldSceneKeys = oldFullLayout._subplots.gl2d || [];

    for(var i = 0; i < oldSceneKeys.length; i++) {
        var id = oldSceneKeys[i];
        var oldSubplot = oldFullLayout._plots[id];

        // old subplot wasn't gl2d; nothing to do
        if(!oldSubplot._scene2d) continue;

        // if no traces are present, delete gl2d subplot
        var subplotData = getSubplotData(newFullData, 'gl2d', id);
        if(subplotData.length === 0) {
            oldSubplot._scene2d.destroy();
            delete oldFullLayout._plots[id];
        }
    }

    // since we use cartesian interactions, do cartesian clean
    Cartesian.clean.apply(this, arguments);
};

exports.drawFramework = function(gd) {
    if(!gd._context.staticPlot) {
        Cartesian.drawFramework(gd);
    }
};

exports.toSVG = function(gd) {
    var fullLayout = gd._fullLayout;
    var subplotIds = fullLayout._subplots.gl2d;

    for(var i = 0; i < subplotIds.length; i++) {
        var subplot = fullLayout._plots[subplotIds[i]];
        var scene = subplot._scene2d;

        var imageData = scene.toImage('png');
        var image = fullLayout._glimages.append('svg:image');

        image.attr({
            xmlns: xmlnsNamespaces.svg,
            'xlink:href': imageData,
            x: 0,
            y: 0,
            width: '100%',
            height: '100%',
            preserveAspectRatio: 'none'
        });

        scene.destroy();
    }
};

exports.updateFx = function(gd) {
    var fullLayout = gd._fullLayout;
    var subplotIds = fullLayout._subplots.gl2d;

    for(var i = 0; i < subplotIds.length; i++) {
        var subplotObj = fullLayout._plots[subplotIds[i]]._scene2d;
        subplotObj.updateFx(fullLayout.dragmode);
    }
};

},{"../../components/fx/layout_attributes":614,"../../constants/xmlns_namespaces":675,"../../plot_api/edit_types":728,"../cartesian":756,"../cartesian/attributes":743,"../cartesian/constants":751,"../get_data":781,"../layout_attributes":798,"./scene2d":785}],785:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../../registry');
var Axes = _dereq_('../../plots/cartesian/axes');
var Fx = _dereq_('../../components/fx');

var createPlot2D = _dereq_('gl-plot2d');
var createSpikes = _dereq_('gl-spikes2d');
var createSelectBox = _dereq_('gl-select-box');
var getContext = _dereq_('webgl-context');

var createOptions = _dereq_('./convert');
var createCamera = _dereq_('./camera');
var showNoWebGlMsg = _dereq_('../../lib/show_no_webgl_msg');
var axisConstraints = _dereq_('../cartesian/constraints');
var enforceAxisConstraints = axisConstraints.enforce;
var cleanAxisConstraints = axisConstraints.clean;
var doAutoRange = _dereq_('../cartesian/autorange').doAutoRange;

var AXES = ['xaxis', 'yaxis'];
var STATIC_CANVAS, STATIC_CONTEXT;

var SUBPLOT_PATTERN = _dereq_('../cartesian/constants').SUBPLOT_PATTERN;


function Scene2D(options, fullLayout) {
    this.container = options.container;
    this.graphDiv = options.graphDiv;
    this.pixelRatio = options.plotGlPixelRatio || window.devicePixelRatio;
    this.id = options.id;
    this.staticPlot = !!options.staticPlot;
    this.scrollZoom = this.graphDiv._context._scrollZoom.cartesian;

    this.fullData = null;
    this.updateRefs(fullLayout);

    this.makeFramework();
    if(this.stopped) return;

    // update options
    this.glplotOptions = createOptions(this);
    this.glplotOptions.merge(fullLayout);

    // create the plot
    this.glplot = createPlot2D(this.glplotOptions);

    // create camera
    this.camera = createCamera(this);

    // trace set
    this.traces = {};

    // create axes spikes
    this.spikes = createSpikes(this.glplot);

    this.selectBox = createSelectBox(this.glplot, {
        innerFill: false,
        outerFill: true
    });

    // last button state
    this.lastButtonState = 0;

    // last pick result
    this.pickResult = null;

    // is the mouse over the plot?
    // it's OK if this says true when it's not, so long as
    // when we get a mouseout we set it to false before handling
    this.isMouseOver = true;

    // flag to stop render loop
    this.stopped = false;

    // redraw the plot
    this.redraw = this.draw.bind(this);
    this.redraw();
}

module.exports = Scene2D;

var proto = Scene2D.prototype;

proto.makeFramework = function() {

    // create canvas and gl context
    if(this.staticPlot) {
        if(!STATIC_CONTEXT) {
            STATIC_CANVAS = document.createElement('canvas');

            STATIC_CONTEXT = getContext({
                canvas: STATIC_CANVAS,
                preserveDrawingBuffer: false,
                premultipliedAlpha: true,
                antialias: true
            });

            if(!STATIC_CONTEXT) {
                throw new Error('Error creating static canvas/context for image server');
            }
        }

        this.canvas = STATIC_CANVAS;
        this.gl = STATIC_CONTEXT;
    }
    else {
        var liveCanvas = this.container.querySelector('.gl-canvas-focus');

        var gl = getContext({
            canvas: liveCanvas,
            preserveDrawingBuffer: true,
            premultipliedAlpha: true
        });

        if(!gl) {
            showNoWebGlMsg(this);
            this.stopped = true;
            return;
        }

        this.canvas = liveCanvas;
        this.gl = gl;
    }

    // position the canvas
    var canvas = this.canvas;

    canvas.style.width = '100%';
    canvas.style.height = '100%';
    canvas.style.position = 'absolute';
    canvas.style.top = '0px';
    canvas.style.left = '0px';
    canvas.style['pointer-events'] = 'none';

    this.updateSize(canvas);

    // disabling user select on the canvas
    // sanitizes double-clicks interactions
    // ref: https://github.com/plotly/plotly.js/issues/744
    canvas.className += ' user-select-none';

    // create SVG container for hover text
    var svgContainer = this.svgContainer = document.createElementNS(
        'http://www.w3.org/2000/svg',
        'svg');
    svgContainer.style.position = 'absolute';
    svgContainer.style.top = svgContainer.style.left = '0px';
    svgContainer.style.width = svgContainer.style.height = '100%';
    svgContainer.style['z-index'] = 20;
    svgContainer.style['pointer-events'] = 'none';

    // create div to catch the mouse event
    var mouseContainer = this.mouseContainer = document.createElement('div');
    mouseContainer.style.position = 'absolute';
    mouseContainer.style['pointer-events'] = 'auto';

    this.pickCanvas = this.container.querySelector('.gl-canvas-pick');


    // append canvas, hover svg and mouse div to container
    var container = this.container;
    container.appendChild(svgContainer);
    container.appendChild(mouseContainer);

    var self = this;
    mouseContainer.addEventListener('mouseout', function() {
        self.isMouseOver = false;
        self.unhover();
    });
    mouseContainer.addEventListener('mouseover', function() {
        self.isMouseOver = true;
    });
};

proto.toImage = function(format) {
    if(!format) format = 'png';

    this.stopped = true;

    if(this.staticPlot) this.container.appendChild(STATIC_CANVAS);

    // update canvas size
    this.updateSize(this.canvas);


    // grab context and yank out pixels
    var gl = this.glplot.gl;
    var w = gl.drawingBufferWidth;
    var h = gl.drawingBufferHeight;

    // force redraw
    gl.clearColor(1, 1, 1, 0);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    this.glplot.setDirty();
    this.glplot.draw();

    gl.bindFramebuffer(gl.FRAMEBUFFER, null);

    var pixels = new Uint8Array(w * h * 4);
    gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, pixels);

    // flip pixels
    for(var j = 0, k = h - 1; j < k; ++j, --k) {
        for(var i = 0; i < w; ++i) {
            for(var l = 0; l < 4; ++l) {
                var tmp = pixels[4 * (w * j + i) + l];
                pixels[4 * (w * j + i) + l] = pixels[4 * (w * k + i) + l];
                pixels[4 * (w * k + i) + l] = tmp;
            }
        }
    }

    var canvas = document.createElement('canvas');
    canvas.width = w;
    canvas.height = h;

    var context = canvas.getContext('2d');
    var imageData = context.createImageData(w, h);
    imageData.data.set(pixels);
    context.putImageData(imageData, 0, 0);

    var dataURL;

    switch(format) {
        case 'jpeg':
            dataURL = canvas.toDataURL('image/jpeg');
            break;
        case 'webp':
            dataURL = canvas.toDataURL('image/webp');
            break;
        default:
            dataURL = canvas.toDataURL('image/png');
    }

    if(this.staticPlot) this.container.removeChild(STATIC_CANVAS);

    return dataURL;
};

proto.updateSize = function(canvas) {
    if(!canvas) canvas = this.canvas;

    var pixelRatio = this.pixelRatio;
    var fullLayout = this.fullLayout;

    var width = fullLayout.width;
    var height = fullLayout.height;
    var pixelWidth = Math.ceil(pixelRatio * width) |0;
    var pixelHeight = Math.ceil(pixelRatio * height) |0;

    // check for resize
    if(canvas.width !== pixelWidth || canvas.height !== pixelHeight) {
        canvas.width = pixelWidth;
        canvas.height = pixelHeight;
    }

    return canvas;
};

proto.computeTickMarks = function() {
    this.xaxis.setScale();
    this.yaxis.setScale();

    var nextTicks = [
        Axes.calcTicks(this.xaxis),
        Axes.calcTicks(this.yaxis)
    ];

    for(var j = 0; j < 2; ++j) {
        for(var i = 0; i < nextTicks[j].length; ++i) {
            // coercing tick value (may not be a string) to a string
            nextTicks[j][i].text = nextTicks[j][i].text + '';
        }
    }

    return nextTicks;
};

function compareTicks(a, b) {
    for(var i = 0; i < 2; ++i) {
        var aticks = a[i];
        var bticks = b[i];

        if(aticks.length !== bticks.length) return true;

        for(var j = 0; j < aticks.length; ++j) {
            if(aticks[j].x !== bticks[j].x) return true;
        }
    }

    return false;
}

proto.updateRefs = function(newFullLayout) {
    this.fullLayout = newFullLayout;

    var spmatch = this.id.match(SUBPLOT_PATTERN);
    var xaxisName = 'xaxis' + spmatch[1];
    var yaxisName = 'yaxis' + spmatch[2];

    this.xaxis = this.fullLayout[xaxisName];
    this.yaxis = this.fullLayout[yaxisName];
};

proto.relayoutCallback = function() {
    var graphDiv = this.graphDiv;
    var xaxis = this.xaxis;
    var yaxis = this.yaxis;
    var layout = graphDiv.layout;

    // make a meaningful value to be passed on to possible 'plotly_relayout' subscriber(s)
    var update = {};
    var xrange = update[xaxis._name + '.range'] = xaxis.range.slice();
    var yrange = update[yaxis._name + '.range'] = yaxis.range.slice();
    update[xaxis._name + '.autorange'] = xaxis.autorange;
    update[yaxis._name + '.autorange'] = yaxis.autorange;

    Registry.call('_storeDirectGUIEdit', graphDiv.layout, graphDiv._fullLayout._preGUI, update);

    // update the input layout
    var xaIn = layout[xaxis._name];
    xaIn.range = xrange;
    xaIn.autorange = xaxis.autorange;

    var yaIn = layout[yaxis._name];
    yaIn.range = yrange;
    yaIn.autorange = yaxis.autorange;

    // lastInputTime helps determine which one is the latest input (if async)
    update.lastInputTime = this.camera.lastInputTime;
    graphDiv.emit('plotly_relayout', update);
};

proto.cameraChanged = function() {
    var camera = this.camera;

    this.glplot.setDataBox(this.calcDataBox());

    var nextTicks = this.computeTickMarks();
    var curTicks = this.glplotOptions.ticks;

    if(compareTicks(nextTicks, curTicks)) {
        this.glplotOptions.ticks = nextTicks;
        this.glplotOptions.dataBox = camera.dataBox;
        this.glplot.update(this.glplotOptions);
        this.handleAnnotations();
    }
};

proto.handleAnnotations = function() {
    var gd = this.graphDiv;
    var annotations = this.fullLayout.annotations;

    for(var i = 0; i < annotations.length; i++) {
        var ann = annotations[i];

        if(ann.xref === this.xaxis._id && ann.yref === this.yaxis._id) {
            Registry.getComponentMethod('annotations', 'drawOne')(gd, i);
        }
    }
};

proto.destroy = function() {
    if(!this.glplot) return;

    var traces = this.traces;

    if(traces) {
        Object.keys(traces).map(function(key) {
            traces[key].dispose();
            delete traces[key];
        });
    }

    this.glplot.dispose();

    this.container.removeChild(this.svgContainer);
    this.container.removeChild(this.mouseContainer);

    this.fullData = null;
    this.glplot = null;
    this.stopped = true;
    this.camera.mouseListener.enabled = false;
    this.mouseContainer.removeEventListener('wheel', this.camera.wheelListener);
    this.camera = null;
};

proto.plot = function(fullData, calcData, fullLayout) {
    var glplot = this.glplot;

    this.updateRefs(fullLayout);
    this.xaxis.clearCalc();
    this.yaxis.clearCalc();
    this.updateTraces(fullData, calcData);
    this.updateFx(fullLayout.dragmode);

    var width = fullLayout.width;
    var height = fullLayout.height;

    this.updateSize(this.canvas);

    var options = this.glplotOptions;
    options.merge(fullLayout);
    options.screenBox = [0, 0, width, height];

    var mockGraphDiv = {_fullLayout: {
        _axisConstraintGroups: this.graphDiv._fullLayout._axisConstraintGroups,
        xaxis: this.xaxis,
        yaxis: this.yaxis
    }};

    cleanAxisConstraints(mockGraphDiv, this.xaxis);
    cleanAxisConstraints(mockGraphDiv, this.yaxis);

    var size = fullLayout._size;
    var domainX = this.xaxis.domain;
    var domainY = this.yaxis.domain;

    options.viewBox = [
        size.l + domainX[0] * size.w,
        size.b + domainY[0] * size.h,
        (width - size.r) - (1 - domainX[1]) * size.w,
        (height - size.t) - (1 - domainY[1]) * size.h
    ];

    this.mouseContainer.style.width = size.w * (domainX[1] - domainX[0]) + 'px';
    this.mouseContainer.style.height = size.h * (domainY[1] - domainY[0]) + 'px';
    this.mouseContainer.height = size.h * (domainY[1] - domainY[0]);
    this.mouseContainer.style.left = size.l + domainX[0] * size.w + 'px';
    this.mouseContainer.style.top = size.t + (1 - domainY[1]) * size.h + 'px';

    var ax, i;

    for(i = 0; i < 2; ++i) {
        ax = this[AXES[i]];
        ax._length = options.viewBox[i + 2] - options.viewBox[i];

        doAutoRange(this.graphDiv, ax);
        ax.setScale();
    }

    enforceAxisConstraints(mockGraphDiv);

    options.ticks = this.computeTickMarks();

    options.dataBox = this.calcDataBox();

    options.merge(fullLayout);
    glplot.update(options);

    // force redraw so that promise is returned when rendering is completed
    this.glplot.draw();
};

proto.calcDataBox = function() {
    var xaxis = this.xaxis;
    var yaxis = this.yaxis;
    var xrange = xaxis.range;
    var yrange = yaxis.range;
    var xr2l = xaxis.r2l;
    var yr2l = yaxis.r2l;

    return [xr2l(xrange[0]), yr2l(yrange[0]), xr2l(xrange[1]), yr2l(yrange[1])];
};

proto.setRanges = function(dataBox) {
    var xaxis = this.xaxis;
    var yaxis = this.yaxis;
    var xl2r = xaxis.l2r;
    var yl2r = yaxis.l2r;

    xaxis.range = [xl2r(dataBox[0]), xl2r(dataBox[2])];
    yaxis.range = [yl2r(dataBox[1]), yl2r(dataBox[3])];
};

proto.updateTraces = function(fullData, calcData) {
    var traceIds = Object.keys(this.traces);
    var i, j, fullTrace;

    this.fullData = fullData;

    // remove empty traces
    traceIdLoop:
    for(i = 0; i < traceIds.length; i++) {
        var oldUid = traceIds[i];
        var oldTrace = this.traces[oldUid];

        for(j = 0; j < fullData.length; j++) {
            fullTrace = fullData[j];

            if(fullTrace.uid === oldUid && fullTrace.type === oldTrace.type) {
                continue traceIdLoop;
            }
        }

        oldTrace.dispose();
        delete this.traces[oldUid];
    }

    // update / create trace objects
    for(i = 0; i < fullData.length; i++) {
        fullTrace = fullData[i];
        var calcTrace = calcData[i];
        var traceObj = this.traces[fullTrace.uid];

        if(traceObj) traceObj.update(fullTrace, calcTrace);
        else {
            traceObj = fullTrace._module.plot(this, fullTrace, calcTrace);
            this.traces[fullTrace.uid] = traceObj;
        }
    }

    // order object per traces
    this.glplot.objects.sort(function(a, b) {
        return a._trace.index - b._trace.index;
    });
};

proto.updateFx = function(dragmode) {
    // switch to svg interactions in lasso/select mode
    if(dragmode === 'lasso' || dragmode === 'select') {
        this.pickCanvas.style['pointer-events'] = 'none';
        this.mouseContainer.style['pointer-events'] = 'none';
    } else {
        this.pickCanvas.style['pointer-events'] = 'auto';
        this.mouseContainer.style['pointer-events'] = 'auto';
    }

    // set proper cursor
    if(dragmode === 'pan') {
        this.mouseContainer.style.cursor = 'move';
    }
    else if(dragmode === 'zoom') {
        this.mouseContainer.style.cursor = 'crosshair';
    }
    else {
        this.mouseContainer.style.cursor = null;
    }
};

proto.emitPointAction = function(nextSelection, eventType) {
    var uid = nextSelection.trace.uid;
    var ptNumber = nextSelection.pointIndex;
    var trace;

    for(var i = 0; i < this.fullData.length; i++) {
        if(this.fullData[i].uid === uid) {
            trace = this.fullData[i];
        }
    }

    var pointData = {
        x: nextSelection.traceCoord[0],
        y: nextSelection.traceCoord[1],
        curveNumber: trace.index,
        pointNumber: ptNumber,
        data: trace._input,
        fullData: this.fullData,
        xaxis: this.xaxis,
        yaxis: this.yaxis
    };

    Fx.appendArrayPointValue(pointData, trace, ptNumber);

    this.graphDiv.emit(eventType, {points: [pointData]});
};

proto.draw = function() {
    if(this.stopped) return;

    requestAnimationFrame(this.redraw);

    var glplot = this.glplot;
    var camera = this.camera;
    var mouseListener = camera.mouseListener;
    var mouseUp = this.lastButtonState === 1 && mouseListener.buttons === 0;
    var fullLayout = this.fullLayout;

    this.lastButtonState = mouseListener.buttons;

    this.cameraChanged();

    var x = mouseListener.x * glplot.pixelRatio;
    var y = this.canvas.height - glplot.pixelRatio * mouseListener.y;

    var result;

    if(camera.boxEnabled && fullLayout.dragmode === 'zoom') {
        this.selectBox.enabled = true;

        var selectBox = this.selectBox.selectBox = [
            Math.min(camera.boxStart[0], camera.boxEnd[0]),
            Math.min(camera.boxStart[1], camera.boxEnd[1]),
            Math.max(camera.boxStart[0], camera.boxEnd[0]),
            Math.max(camera.boxStart[1], camera.boxEnd[1])
        ];

        // 1D zoom
        for(var i = 0; i < 2; i++) {
            if(camera.boxStart[i] === camera.boxEnd[i]) {
                selectBox[i] = glplot.dataBox[i];
                selectBox[i + 2] = glplot.dataBox[i + 2];
            }
        }

        glplot.setDirty();
    }
    else if(!camera.panning && this.isMouseOver) {
        this.selectBox.enabled = false;

        var size = fullLayout._size;
        var domainX = this.xaxis.domain;
        var domainY = this.yaxis.domain;

        result = glplot.pick(
            (x / glplot.pixelRatio) + size.l + domainX[0] * size.w,
            (y / glplot.pixelRatio) - (size.t + (1 - domainY[1]) * size.h)
        );

        var nextSelection = result && result.object._trace.handlePick(result);

        if(nextSelection && mouseUp) {
            this.emitPointAction(nextSelection, 'plotly_click');
        }

        if(result && result.object._trace.hoverinfo !== 'skip' && fullLayout.hovermode) {

            if(nextSelection && (
                !this.lastPickResult ||
                this.lastPickResult.traceUid !== nextSelection.trace.uid ||
                this.lastPickResult.dataCoord[0] !== nextSelection.dataCoord[0] ||
                this.lastPickResult.dataCoord[1] !== nextSelection.dataCoord[1])
            ) {
                var selection = nextSelection;

                this.lastPickResult = {
                    traceUid: nextSelection.trace ? nextSelection.trace.uid : null,
                    dataCoord: nextSelection.dataCoord.slice()
                };
                this.spikes.update({ center: result.dataCoord });

                selection.screenCoord = [
                    ((glplot.viewBox[2] - glplot.viewBox[0]) *
                    (result.dataCoord[0] - glplot.dataBox[0]) /
                        (glplot.dataBox[2] - glplot.dataBox[0]) + glplot.viewBox[0]) /
                            glplot.pixelRatio,
                    (this.canvas.height - (glplot.viewBox[3] - glplot.viewBox[1]) *
                    (result.dataCoord[1] - glplot.dataBox[1]) /
                        (glplot.dataBox[3] - glplot.dataBox[1]) - glplot.viewBox[1]) /
                            glplot.pixelRatio
                ];

                // this needs to happen before the next block that deletes traceCoord data
                // also it's important to copy, otherwise data is lost by the time event data is read
                this.emitPointAction(nextSelection, 'plotly_hover');

                var trace = this.fullData[selection.trace.index] || {};
                var ptNumber = selection.pointIndex;
                var hoverinfo = Fx.castHoverinfo(trace, fullLayout, ptNumber);

                if(hoverinfo && hoverinfo !== 'all') {
                    var parts = hoverinfo.split('+');
                    if(parts.indexOf('x') === -1) selection.traceCoord[0] = undefined;
                    if(parts.indexOf('y') === -1) selection.traceCoord[1] = undefined;
                    if(parts.indexOf('z') === -1) selection.traceCoord[2] = undefined;
                    if(parts.indexOf('text') === -1) selection.textLabel = undefined;
                    if(parts.indexOf('name') === -1) selection.name = undefined;
                }

                Fx.loneHover({
                    x: selection.screenCoord[0],
                    y: selection.screenCoord[1],
                    xLabel: this.hoverFormatter('xaxis', selection.traceCoord[0]),
                    yLabel: this.hoverFormatter('yaxis', selection.traceCoord[1]),
                    zLabel: selection.traceCoord[2],
                    text: selection.textLabel,
                    name: selection.name,
                    color: Fx.castHoverOption(trace, ptNumber, 'bgcolor') || selection.color,
                    borderColor: Fx.castHoverOption(trace, ptNumber, 'bordercolor'),
                    fontFamily: Fx.castHoverOption(trace, ptNumber, 'font.family'),
                    fontSize: Fx.castHoverOption(trace, ptNumber, 'font.size'),
                    fontColor: Fx.castHoverOption(trace, ptNumber, 'font.color')
                }, {
                    container: this.svgContainer,
                    gd: this.graphDiv
                });
            }
        }
    }

    // Remove hover effects if we're not over a point OR
    // if we're zooming or panning (in which case result is not set)
    if(!result) {
        this.unhover();
    }

    glplot.draw();
};

proto.unhover = function() {
    if(this.lastPickResult) {
        this.spikes.update({});
        this.lastPickResult = null;
        this.graphDiv.emit('plotly_unhover');
        Fx.loneUnhover(this.svgContainer);
    }
};

proto.hoverFormatter = function(axisName, val) {
    if(val === undefined) return undefined;

    var axis = this[axisName];
    return Axes.tickText(axis, axis.c2l(val), 'hover').text;
};

},{"../../components/fx":613,"../../lib/show_no_webgl_msg":718,"../../plots/cartesian/axes":745,"../../registry":826,"../cartesian/autorange":744,"../cartesian/constants":751,"../cartesian/constraints":752,"./camera":782,"./convert":783,"gl-plot2d":280,"gl-select-box":292,"gl-spikes2d":301,"webgl-context":537}],786:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
var fxAttrs = _dereq_('../../components/fx/layout_attributes');

var Scene = _dereq_('./scene');
var getSubplotData = _dereq_('../get_data').getSubplotData;
var Lib = _dereq_('../../lib');
var xmlnsNamespaces = _dereq_('../../constants/xmlns_namespaces');

var GL3D = 'gl3d';
var SCENE = 'scene';


exports.name = GL3D;

exports.attr = SCENE;

exports.idRoot = SCENE;

exports.idRegex = exports.attrRegex = Lib.counterRegex('scene');

exports.attributes = _dereq_('./layout/attributes');

exports.layoutAttributes = _dereq_('./layout/layout_attributes');

exports.baseLayoutAttrOverrides = overrideAll({
    hoverlabel: fxAttrs.hoverlabel
}, 'plot', 'nested');

exports.supplyLayoutDefaults = _dereq_('./layout/defaults');

exports.plot = function plotGl3d(gd) {
    var fullLayout = gd._fullLayout;
    var fullData = gd._fullData;
    var sceneIds = fullLayout._subplots[GL3D];

    for(var i = 0; i < sceneIds.length; i++) {
        var sceneId = sceneIds[i];
        var fullSceneData = getSubplotData(fullData, GL3D, sceneId);
        var sceneLayout = fullLayout[sceneId];
        var camera = sceneLayout.camera;
        var scene = sceneLayout._scene;

        if(!scene) {
            scene = new Scene({
                id: sceneId,
                graphDiv: gd,
                container: gd.querySelector('.gl-container'),
                staticPlot: gd._context.staticPlot,
                plotGlPixelRatio: gd._context.plotGlPixelRatio,
                camera: camera
            },
                fullLayout
            );

            // set ref to Scene instance
            sceneLayout._scene = scene;
        }

        // save 'initial' camera view settings for modebar button
        if(!scene.viewInitial) {
            scene.viewInitial = {
                up: {
                    x: camera.up.x,
                    y: camera.up.y,
                    z: camera.up.z
                },
                eye: {
                    x: camera.eye.x,
                    y: camera.eye.y,
                    z: camera.eye.z
                },
                center: {
                    x: camera.center.x,
                    y: camera.center.y,
                    z: camera.center.z
                }
            };
        }

        scene.plot(fullSceneData, fullLayout, gd.layout);
    }
};

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var oldSceneKeys = oldFullLayout._subplots[GL3D] || [];

    for(var i = 0; i < oldSceneKeys.length; i++) {
        var oldSceneKey = oldSceneKeys[i];

        if(!newFullLayout[oldSceneKey] && !!oldFullLayout[oldSceneKey]._scene) {
            oldFullLayout[oldSceneKey]._scene.destroy();

            if(oldFullLayout._infolayer) {
                oldFullLayout._infolayer
                    .selectAll('.annotation-' + oldSceneKey)
                    .remove();
            }
        }
    }
};

exports.toSVG = function(gd) {
    var fullLayout = gd._fullLayout;
    var sceneIds = fullLayout._subplots[GL3D];
    var size = fullLayout._size;

    for(var i = 0; i < sceneIds.length; i++) {
        var sceneLayout = fullLayout[sceneIds[i]];
        var domain = sceneLayout.domain;
        var scene = sceneLayout._scene;

        var imageData = scene.toImage('png');
        var image = fullLayout._glimages.append('svg:image');

        image.attr({
            xmlns: xmlnsNamespaces.svg,
            'xlink:href': imageData,
            x: size.l + size.w * domain.x[0],
            y: size.t + size.h * (1 - domain.y[1]),
            width: size.w * (domain.x[1] - domain.x[0]),
            height: size.h * (domain.y[1] - domain.y[0]),
            preserveAspectRatio: 'none'
        });

        scene.destroy();
    }
};

// clean scene ids, 'scene1' -> 'scene'
exports.cleanId = function cleanId(id) {
    if(!id.match(/^scene[0-9]*$/)) return;

    var sceneNum = id.substr(5);
    if(sceneNum === '1') sceneNum = '';

    return SCENE + sceneNum;
};

exports.updateFx = function(gd) {
    var fullLayout = gd._fullLayout;
    var subplotIds = fullLayout._subplots[GL3D];

    for(var i = 0; i < subplotIds.length; i++) {
        var subplotObj = fullLayout[subplotIds[i]]._scene;
        subplotObj.updateFx(fullLayout.dragmode, fullLayout.hovermode);
    }
};

},{"../../components/fx/layout_attributes":614,"../../constants/xmlns_namespaces":675,"../../lib":697,"../../plot_api/edit_types":728,"../get_data":781,"./layout/attributes":787,"./layout/defaults":791,"./layout/layout_attributes":792,"./scene":796}],787:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    scene: {
        valType: 'subplotid',
        
        dflt: 'scene',
        editType: 'calc+clearAxisTypes',
        
    }
};

},{}],788:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Color = _dereq_('../../../components/color');
var axesAttrs = _dereq_('../../cartesian/layout_attributes');
var extendFlat = _dereq_('../../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../../plot_api/edit_types').overrideAll;

module.exports = overrideAll({
    visible: axesAttrs.visible,
    showspikes: {
        valType: 'boolean',
        
        dflt: true,
        
    },
    spikesides: {
        valType: 'boolean',
        
        dflt: true,
        
    },
    spikethickness: {
        valType: 'number',
        
        min: 0,
        dflt: 2,
        
    },
    spikecolor: {
        valType: 'color',
        
        dflt: Color.defaultLine,
        
    },
    showbackground: {
        valType: 'boolean',
        
        dflt: false,
        
    },
    backgroundcolor: {
        valType: 'color',
        
        dflt: 'rgba(204, 204, 204, 0.5)',
        
    },
    showaxeslabels: {
        valType: 'boolean',
        
        dflt: true,
        
    },
    color: axesAttrs.color,
    categoryorder: axesAttrs.categoryorder,
    categoryarray: axesAttrs.categoryarray,
    title: axesAttrs.title,
    type: extendFlat({}, axesAttrs.type, {
        values: ['-', 'linear', 'log', 'date', 'category']
    }),
    autorange: axesAttrs.autorange,
    rangemode: axesAttrs.rangemode,
    range: extendFlat({}, axesAttrs.range, {
        items: [
            {valType: 'any', editType: 'plot', impliedEdits: {'^autorange': false}},
            {valType: 'any', editType: 'plot', impliedEdits: {'^autorange': false}}
        ],
        anim: false
    }),
    // ticks
    tickmode: axesAttrs.tickmode,
    nticks: axesAttrs.nticks,
    tick0: axesAttrs.tick0,
    dtick: axesAttrs.dtick,
    tickvals: axesAttrs.tickvals,
    ticktext: axesAttrs.ticktext,
    ticks: axesAttrs.ticks,
    mirror: axesAttrs.mirror,
    ticklen: axesAttrs.ticklen,
    tickwidth: axesAttrs.tickwidth,
    tickcolor: axesAttrs.tickcolor,
    showticklabels: axesAttrs.showticklabels,
    tickfont: axesAttrs.tickfont,
    tickangle: axesAttrs.tickangle,
    tickprefix: axesAttrs.tickprefix,
    showtickprefix: axesAttrs.showtickprefix,
    ticksuffix: axesAttrs.ticksuffix,
    showticksuffix: axesAttrs.showticksuffix,
    showexponent: axesAttrs.showexponent,
    exponentformat: axesAttrs.exponentformat,
    separatethousands: axesAttrs.separatethousands,
    tickformat: axesAttrs.tickformat,
    tickformatstops: axesAttrs.tickformatstops,
    hoverformat: axesAttrs.hoverformat,
    // lines and grids
    showline: axesAttrs.showline,
    linecolor: axesAttrs.linecolor,
    linewidth: axesAttrs.linewidth,
    showgrid: axesAttrs.showgrid,
    gridcolor: extendFlat({}, axesAttrs.gridcolor,  // shouldn't this be on-par with 2D?
        {dflt: 'rgb(204, 204, 204)'}),
    gridwidth: axesAttrs.gridwidth,
    zeroline: axesAttrs.zeroline,
    zerolinecolor: axesAttrs.zerolinecolor,
    zerolinewidth: axesAttrs.zerolinewidth,
    _deprecated: {
        title: axesAttrs._deprecated.title,
        titlefont: axesAttrs._deprecated.titlefont
    }
}, 'plot', 'from-root');

},{"../../../components/color":574,"../../../lib/extend":687,"../../../plot_api/edit_types":728,"../../cartesian/layout_attributes":757}],789:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var colorMix = _dereq_('tinycolor2').mix;

var Lib = _dereq_('../../../lib');
var Template = _dereq_('../../../plot_api/plot_template');

var layoutAttributes = _dereq_('./axis_attributes');
var handleTypeDefaults = _dereq_('../../cartesian/type_defaults');
var handleAxisDefaults = _dereq_('../../cartesian/axis_defaults');

var axesNames = ['xaxis', 'yaxis', 'zaxis'];

// TODO: hard-coded lightness fraction based on gridline default colors
// that differ from other subplot types.
var gridLightness = 100 * (204 - 0x44) / (255 - 0x44);

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, options) {
    var containerIn, containerOut;

    function coerce(attr, dflt) {
        return Lib.coerce(containerIn, containerOut, layoutAttributes, attr, dflt);
    }

    for(var j = 0; j < axesNames.length; j++) {
        var axName = axesNames[j];
        containerIn = layoutIn[axName] || {};

        containerOut = Template.newContainer(layoutOut, axName);
        containerOut._id = axName[0] + options.scene;
        containerOut._name = axName;

        handleTypeDefaults(containerIn, containerOut, coerce, options);

        handleAxisDefaults(
            containerIn,
            containerOut,
            coerce,
            {
                font: options.font,
                letter: axName[0],
                data: options.data,
                showGrid: true,
                noTickson: true,
                bgColor: options.bgColor,
                calendar: options.calendar
            },
            options.fullLayout);

        coerce('gridcolor', colorMix(containerOut.color, options.bgColor, gridLightness).toRgbString());
        coerce('title.text', axName[0]);  // shouldn't this be on-par with 2D?

        containerOut.setScale = Lib.noop;

        if(coerce('showspikes')) {
            coerce('spikesides');
            coerce('spikethickness');
            coerce('spikecolor', containerOut.color);
        }

        coerce('showaxeslabels');
        if(coerce('showbackground')) coerce('backgroundcolor');
    }
};

},{"../../../lib":697,"../../../plot_api/plot_template":735,"../../cartesian/axis_defaults":747,"../../cartesian/type_defaults":768,"./axis_attributes":788,"tinycolor2":518}],790:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var str2RgbaArray = _dereq_('../../../lib/str2rgbarray');
var Lib = _dereq_('../../../lib');

var AXES_NAMES = ['xaxis', 'yaxis', 'zaxis'];

function AxesOptions() {
    this.bounds = [
        [-10, -10, -10],
        [10, 10, 10]
    ];

    this.ticks = [ [], [], [] ];
    this.tickEnable = [ true, true, true ];
    this.tickFont = [ 'sans-serif', 'sans-serif', 'sans-serif' ];
    this.tickSize = [ 12, 12, 12 ];
    this.tickAngle = [ 0, 0, 0 ];
    this.tickColor = [ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1] ];
    this.tickPad = [ 18, 18, 18 ];

    this.labels = [ 'x', 'y', 'z' ];
    this.labelEnable = [ true, true, true ];
    this.labelFont = ['Open Sans', 'Open Sans', 'Open Sans'];
    this.labelSize = [ 20, 20, 20 ];
    this.labelColor = [ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1] ];
    this.labelPad = [ 30, 30, 30 ];

    this.lineEnable = [ true, true, true ];
    this.lineMirror = [ false, false, false ];
    this.lineWidth = [ 1, 1, 1 ];
    this.lineColor = [ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1] ];

    this.lineTickEnable = [ true, true, true ];
    this.lineTickMirror = [ false, false, false ];
    this.lineTickLength = [ 10, 10, 10 ];
    this.lineTickWidth = [ 1, 1, 1 ];
    this.lineTickColor = [ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1] ];

    this.gridEnable = [ true, true, true ];
    this.gridWidth = [ 1, 1, 1 ];
    this.gridColor = [ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1] ];

    this.zeroEnable = [ true, true, true ];
    this.zeroLineColor = [ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1] ];
    this.zeroLineWidth = [ 2, 2, 2 ];

    this.backgroundEnable = [ true, true, true ];
    this.backgroundColor = [ [0.8, 0.8, 0.8, 0.5],
                              [0.8, 0.8, 0.8, 0.5],
                              [0.8, 0.8, 0.8, 0.5] ];

    // some default values are stored for applying model transforms
    this._defaultTickPad = this.tickPad.slice();
    this._defaultLabelPad = this.labelPad.slice();
    this._defaultLineTickLength = this.lineTickLength.slice();
}

var proto = AxesOptions.prototype;

proto.merge = function(fullLayout, sceneLayout) {
    var opts = this;
    for(var i = 0; i < 3; ++i) {
        var axes = sceneLayout[AXES_NAMES[i]];

        if(!axes.visible) {
            opts.tickEnable[i] = false;
            opts.labelEnable[i] = false;
            opts.lineEnable[i] = false;
            opts.lineTickEnable[i] = false;
            opts.gridEnable[i] = false;
            opts.zeroEnable[i] = false;
            opts.backgroundEnable[i] = false;
            continue;
        }

        // Axes labels
        opts.labels[i] = fullLayout.meta ?
            Lib.templateString(axes.title.text, {meta: fullLayout.meta}) :
            axes.title.text;

        if('font' in axes.title) {
            if(axes.title.font.color) opts.labelColor[i] = str2RgbaArray(axes.title.font.color);
            if(axes.title.font.family) opts.labelFont[i] = axes.title.font.family;
            if(axes.title.font.size) opts.labelSize[i] = axes.title.font.size;
        }

        // Lines
        if('showline' in axes) opts.lineEnable[i] = axes.showline;
        if('linecolor' in axes) opts.lineColor[i] = str2RgbaArray(axes.linecolor);
        if('linewidth' in axes) opts.lineWidth[i] = axes.linewidth;

        if('showgrid' in axes) opts.gridEnable[i] = axes.showgrid;
        if('gridcolor' in axes) opts.gridColor[i] = str2RgbaArray(axes.gridcolor);
        if('gridwidth' in axes) opts.gridWidth[i] = axes.gridwidth;

        // Remove zeroline if axis type is log
        // otherwise the zeroline is incorrectly drawn at 1 on log axes
        if(axes.type === 'log') opts.zeroEnable[i] = false;
        else if('zeroline' in axes) opts.zeroEnable[i] = axes.zeroline;
        if('zerolinecolor' in axes) opts.zeroLineColor[i] = str2RgbaArray(axes.zerolinecolor);
        if('zerolinewidth' in axes) opts.zeroLineWidth[i] = axes.zerolinewidth;

        // tick lines
        if('ticks' in axes && !!axes.ticks) opts.lineTickEnable[i] = true;
        else opts.lineTickEnable[i] = false;

        if('ticklen' in axes) {
            opts.lineTickLength[i] = opts._defaultLineTickLength[i] = axes.ticklen;
        }
        if('tickcolor' in axes) opts.lineTickColor[i] = str2RgbaArray(axes.tickcolor);
        if('tickwidth' in axes) opts.lineTickWidth[i] = axes.tickwidth;
        if('tickangle' in axes) {
            opts.tickAngle[i] = (axes.tickangle === 'auto') ?
                -3600 : // i.e. special number to set auto option
                Math.PI * -axes.tickangle / 180;
        }

        // tick labels
        if('showticklabels' in axes) opts.tickEnable[i] = axes.showticklabels;
        if('tickfont' in axes) {
            if(axes.tickfont.color) opts.tickColor[i] = str2RgbaArray(axes.tickfont.color);
            if(axes.tickfont.family) opts.tickFont[i] = axes.tickfont.family;
            if(axes.tickfont.size) opts.tickSize[i] = axes.tickfont.size;
        }

        if('mirror' in axes) {
            if(['ticks', 'all', 'allticks'].indexOf(axes.mirror) !== -1) {
                opts.lineTickMirror[i] = true;
                opts.lineMirror[i] = true;
            } else if(axes.mirror === true) {
                opts.lineTickMirror[i] = false;
                opts.lineMirror[i] = true;
            } else {
                opts.lineTickMirror[i] = false;
                opts.lineMirror[i] = false;
            }
        } else opts.lineMirror[i] = false;

        // grid background
        if('showbackground' in axes && axes.showbackground !== false) {
            opts.backgroundEnable[i] = true;
            opts.backgroundColor[i] = str2RgbaArray(axes.backgroundcolor);
        } else opts.backgroundEnable[i] = false;
    }
};


function createAxesOptions(fullLayout, sceneLayout) {
    var result = new AxesOptions();
    result.merge(fullLayout, sceneLayout);
    return result;
}

module.exports = createAxesOptions;

},{"../../../lib":697,"../../../lib/str2rgbarray":720}],791:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../../lib');
var Color = _dereq_('../../../components/color');
var Registry = _dereq_('../../../registry');

var handleSubplotDefaults = _dereq_('../../subplot_defaults');
var supplyGl3dAxisLayoutDefaults = _dereq_('./axis_defaults');
var layoutAttributes = _dereq_('./layout_attributes');
var getSubplotData = _dereq_('../../get_data').getSubplotData;

var GL3D = 'gl3d';

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
    var hasNon3D = layoutOut._basePlotModules.length > 1;

    // some layout-wide attribute are used in all scenes
    // if 3D is the only visible plot type
    function getDfltFromLayout(attr) {
        if(hasNon3D) return;

        var isValid = Lib.validate(layoutIn[attr], layoutAttributes[attr]);
        if(isValid) return layoutIn[attr];
    }

    handleSubplotDefaults(layoutIn, layoutOut, fullData, {
        type: GL3D,
        attributes: layoutAttributes,
        handleDefaults: handleGl3dDefaults,
        fullLayout: layoutOut,
        font: layoutOut.font,
        fullData: fullData,
        getDfltFromLayout: getDfltFromLayout,
        paper_bgcolor: layoutOut.paper_bgcolor,
        calendar: layoutOut.calendar
    });
};

function handleGl3dDefaults(sceneLayoutIn, sceneLayoutOut, coerce, opts) {
    /*
     * Scene numbering proceeds as follows
     * scene
     * scene2
     * scene3
     *
     * and d.scene will be undefined or some number or number string
     *
     * Also write back a blank scene object to user layout so that some
     * attributes like aspectratio can be written back dynamically.
     */

    var bgcolor = coerce('bgcolor');
    var bgColorCombined = Color.combine(bgcolor, opts.paper_bgcolor);

    var cameraKeys = ['up', 'center', 'eye'];

    for(var j = 0; j < cameraKeys.length; j++) {
        coerce('camera.' + cameraKeys[j] + '.x');
        coerce('camera.' + cameraKeys[j] + '.y');
        coerce('camera.' + cameraKeys[j] + '.z');
    }

    coerce('camera.projection.type');

    /*
     * coerce to positive number (min 0) but also do not accept 0 (>0 not >=0)
     * note that 0's go false with the !! call
     */
    var hasAspect = !!coerce('aspectratio.x') &&
                    !!coerce('aspectratio.y') &&
                    !!coerce('aspectratio.z');

    var defaultAspectMode = hasAspect ? 'manual' : 'auto';
    var aspectMode = coerce('aspectmode', defaultAspectMode);

    /*
     * We need aspectratio object in all the Layouts as it is dynamically set
     * in the calculation steps, ie, we cant set the correct data now, it happens later.
     * We must also account for the case the user sends bad ratio data with 'manual' set
     * for the mode. In this case we must force change it here as the default coerce
     * misses it above.
     */
    if(!hasAspect) {
        sceneLayoutIn.aspectratio = sceneLayoutOut.aspectratio = {x: 1, y: 1, z: 1};

        if(aspectMode === 'manual') sceneLayoutOut.aspectmode = 'auto';

        /*
         * kind of like autorange - we need the calculated aspectmode back in
         * the input layout or relayout can cause problems later
         */
        sceneLayoutIn.aspectmode = sceneLayoutOut.aspectmode;
    }

    var fullGl3dData = getSubplotData(opts.fullData, GL3D, opts.id);

    supplyGl3dAxisLayoutDefaults(sceneLayoutIn, sceneLayoutOut, {
        font: opts.font,
        scene: opts.id,
        data: fullGl3dData,
        bgColor: bgColorCombined,
        calendar: opts.calendar,
        fullLayout: opts.fullLayout
    });

    Registry.getComponentMethod('annotations3d', 'handleDefaults')(
        sceneLayoutIn, sceneLayoutOut, opts
    );

    var dragmode = opts.getDfltFromLayout('dragmode');

    if(dragmode !== false) {
        if(!dragmode) {

            dragmode = 'orbit';

            if(sceneLayoutIn.camera &&
                sceneLayoutIn.camera.up) {

                var x = sceneLayoutIn.camera.up.x;
                var y = sceneLayoutIn.camera.up.y;
                var z = sceneLayoutIn.camera.up.z;

                if(z !== 0) {
                    if(!x || !y || !z) {
                        dragmode = 'turntable';
                    } else if(z / Math.sqrt(x * x + y * y + z * z) > 0.999) {
                        dragmode = 'turntable';
                    }
                }
            } else {
                dragmode = 'turntable';
            }
        }
    }

    coerce('dragmode', dragmode);
    coerce('hovermode', opts.getDfltFromLayout('hovermode'));
}

},{"../../../components/color":574,"../../../lib":697,"../../../registry":826,"../../get_data":781,"../../subplot_defaults":821,"./axis_defaults":789,"./layout_attributes":792}],792:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var gl3dAxisAttrs = _dereq_('./axis_attributes');
var domainAttrs = _dereq_('../../domain').attributes;
var extendFlat = _dereq_('../../../lib/extend').extendFlat;
var counterRegex = _dereq_('../../../lib').counterRegex;

function makeCameraVector(x, y, z) {
    return {
        x: {
            valType: 'number',
            
            dflt: x,
            editType: 'camera'
        },
        y: {
            valType: 'number',
            
            dflt: y,
            editType: 'camera'
        },
        z: {
            valType: 'number',
            
            dflt: z,
            editType: 'camera'
        },
        editType: 'camera'
    };
}

module.exports = {
    _arrayAttrRegexps: [counterRegex('scene', '.annotations', true)],

    bgcolor: {
        valType: 'color',
        
        dflt: 'rgba(0,0,0,0)',
        editType: 'plot'
    },
    camera: {
        up: extendFlat(makeCameraVector(0, 0, 1), {
            
        }),
        center: extendFlat(makeCameraVector(0, 0, 0), {
            
        }),
        eye: extendFlat(makeCameraVector(1.25, 1.25, 1.25), {
            
        }),
        projection: {
            type: {
                valType: 'enumerated',
                
                values: ['perspective', 'orthographic'],
                dflt: 'perspective',
                editType: 'calc',
                
            },
            editType: 'calc'
        },
        editType: 'camera'
    },
    domain: domainAttrs({name: 'scene', editType: 'plot'}),
    aspectmode: {
        valType: 'enumerated',
        
        values: ['auto', 'cube', 'data', 'manual'],
        dflt: 'auto',
        editType: 'plot',
        impliedEdits: {
            'aspectratio.x': undefined,
            'aspectratio.y': undefined,
            'aspectratio.z': undefined
        },
        
    },
    aspectratio: { // must be positive (0's are coerced to 1)
        x: {
            valType: 'number',
            
            min: 0,
            editType: 'plot',
            impliedEdits: {'^aspectmode': 'manual'}
        },
        y: {
            valType: 'number',
            
            min: 0,
            editType: 'plot',
            impliedEdits: {'^aspectmode': 'manual'}
        },
        z: {
            valType: 'number',
            
            min: 0,
            editType: 'plot',
            impliedEdits: {'^aspectmode': 'manual'}
        },
        editType: 'plot',
        impliedEdits: {aspectmode: 'manual'},
        
    },

    xaxis: gl3dAxisAttrs,
    yaxis: gl3dAxisAttrs,
    zaxis: gl3dAxisAttrs,

    dragmode: {
        valType: 'enumerated',
        
        values: ['orbit', 'turntable', 'zoom', 'pan', false],
        editType: 'plot',
        
    },
    hovermode: {
        valType: 'enumerated',
        
        values: ['closest', false],
        dflt: 'closest',
        editType: 'modebar',
        
    },
    uirevision: {
        valType: 'any',
        
        editType: 'none',
        
    },
    editType: 'plot',

    _deprecated: {
        cameraposition: {
            valType: 'info_array',
            
            editType: 'camera',
            
        }
    }
};

},{"../../../lib":697,"../../../lib/extend":687,"../../domain":770,"./axis_attributes":788}],793:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var str2RGBArray = _dereq_('../../../lib/str2rgbarray');

var AXES_NAMES = ['xaxis', 'yaxis', 'zaxis'];

function SpikeOptions() {
    this.enabled = [true, true, true];
    this.colors = [[0, 0, 0, 1],
                   [0, 0, 0, 1],
                   [0, 0, 0, 1]];
    this.drawSides = [true, true, true];
    this.lineWidth = [1, 1, 1];
}

var proto = SpikeOptions.prototype;

proto.merge = function(sceneLayout) {
    for(var i = 0; i < 3; ++i) {
        var axes = sceneLayout[AXES_NAMES[i]];

        if(!axes.visible) {
            this.enabled[i] = false;
            this.drawSides[i] = false;
            continue;
        }

        this.enabled[i] = axes.showspikes;
        this.colors[i] = str2RGBArray(axes.spikecolor);
        this.drawSides[i] = axes.spikesides;
        this.lineWidth[i] = axes.spikethickness;
    }
};

function createSpikeOptions(layout) {
    var result = new SpikeOptions();
    result.merge(layout);
    return result;
}

module.exports = createSpikeOptions;

},{"../../../lib/str2rgbarray":720}],794:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

/* eslint block-scoped-var: 0*/
/* eslint no-redeclare: 0*/

'use strict';

module.exports = computeTickMarks;

var Axes = _dereq_('../../cartesian/axes');
var Lib = _dereq_('../../../lib');

var AXES_NAMES = ['xaxis', 'yaxis', 'zaxis'];

var centerPoint = [0, 0, 0];

function contourLevelsFromTicks(ticks) {
    var result = new Array(3);
    for(var i = 0; i < 3; ++i) {
        var tlevel = ticks[i];
        var clevel = new Array(tlevel.length);
        for(var j = 0; j < tlevel.length; ++j) {
            clevel[j] = tlevel[j].x;
        }
        result[i] = clevel;
    }
    return result;
}

function computeTickMarks(scene) {
    var axesOptions = scene.axesOptions;
    var glRange = scene.glplot.axesPixels;
    var sceneLayout = scene.fullSceneLayout;

    var ticks = [[], [], []];

    for(var i = 0; i < 3; ++i) {
        var axes = sceneLayout[AXES_NAMES[i]];

        axes._length = (glRange[i].hi - glRange[i].lo) *
            glRange[i].pixelsPerDataUnit / scene.dataScale[i];

        if(Math.abs(axes._length) === Infinity ||
           isNaN(axes._length)) {
            ticks[i] = [];
        } else {
            axes._input_range = axes.range.slice();
            axes.range[0] = (glRange[i].lo) / scene.dataScale[i];
            axes.range[1] = (glRange[i].hi) / scene.dataScale[i];
            axes._m = 1.0 / (scene.dataScale[i] * glRange[i].pixelsPerDataUnit);

            if(axes.range[0] === axes.range[1]) {
                axes.range[0] -= 1;
                axes.range[1] += 1;
            }
            // this is necessary to short-circuit the 'y' handling
            // in autotick part of calcTicks... Treating all axes as 'y' in this case
            // running the autoticks here, then setting
            // autoticks to false to get around the 2D handling in calcTicks.
            var tickModeCached = axes.tickmode;
            if(axes.tickmode === 'auto') {
                axes.tickmode = 'linear';
                var nticks = axes.nticks || Lib.constrain((axes._length / 40), 4, 9);
                Axes.autoTicks(axes, Math.abs(axes.range[1] - axes.range[0]) / nticks);
            }
            var dataTicks = Axes.calcTicks(axes);
            for(var j = 0; j < dataTicks.length; ++j) {
                dataTicks[j].x = dataTicks[j].x * scene.dataScale[i];

                if(axes.type === 'date') {
                    dataTicks[j].text =
                    dataTicks[j].text.replace(/\<br\>/g, ' ');
                }
            }
            ticks[i] = dataTicks;


            axes.tickmode = tickModeCached;
        }
    }

    axesOptions.ticks = ticks;

    // Calculate tick lengths dynamically
    for(var i = 0; i < 3; ++i) {
        centerPoint[i] = 0.5 * (scene.glplot.bounds[0][i] + scene.glplot.bounds[1][i]);
        for(var j = 0; j < 2; ++j) {
            axesOptions.bounds[j][i] = scene.glplot.bounds[j][i];
        }
    }

    scene.contourLevels = contourLevelsFromTicks(ticks);
}

},{"../../../lib":697,"../../cartesian/axes":745}],795:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

function xformMatrix(m, v) {
    var out = [0, 0, 0, 0];
    var i, j;

    for(i = 0; i < 4; ++i) {
        for(j = 0; j < 4; ++j) {
            out[j] += m[4 * i + j] * v[i];
        }
    }

    return out;
}

function project(camera, v) {
    var p = xformMatrix(camera.projection,
        xformMatrix(camera.view,
        xformMatrix(camera.model, [v[0], v[1], v[2], 1])));
    return p;
}

module.exports = project;

},{}],796:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var createCamera = _dereq_('gl-plot3d').createCamera;
var createPlot = _dereq_('gl-plot3d').createScene;
var getContext = _dereq_('webgl-context');
var passiveSupported = _dereq_('has-passive-events');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');

var Axes = _dereq_('../../plots/cartesian/axes');
var Fx = _dereq_('../../components/fx');

var str2RGBAarray = _dereq_('../../lib/str2rgbarray');
var showNoWebGlMsg = _dereq_('../../lib/show_no_webgl_msg');

var project = _dereq_('./project');
var createAxesOptions = _dereq_('./layout/convert');
var createSpikeOptions = _dereq_('./layout/spikes');
var computeTickMarks = _dereq_('./layout/tick_marks');


var STATIC_CANVAS, STATIC_CONTEXT;

function render(scene) {
    var trace;

    // update size of svg container
    var svgContainer = scene.svgContainer;
    var clientRect = scene.container.getBoundingClientRect();
    var width = clientRect.width;
    var height = clientRect.height;
    svgContainer.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height);
    svgContainer.setAttributeNS(null, 'width', width);
    svgContainer.setAttributeNS(null, 'height', height);

    computeTickMarks(scene);
    scene.glplot.axes.update(scene.axesOptions);

    // check if pick has changed
    var keys = Object.keys(scene.traces);
    var lastPicked = null;
    var selection = scene.glplot.selection;
    for(var i = 0; i < keys.length; ++i) {
        trace = scene.traces[keys[i]];
        if(trace.data.hoverinfo !== 'skip' && trace.handlePick(selection)) {
            lastPicked = trace;
        }

        if(trace.setContourLevels) trace.setContourLevels();
    }

    function formatter(axisName, val) {
        var axis = scene.fullSceneLayout[axisName];

        return Axes.tickText(axis, axis.d2l(val), 'hover').text;
    }

    var oldEventData;

    if(lastPicked !== null) {
        var pdata = project(scene.glplot.cameraParams, selection.dataCoordinate);
        trace = lastPicked.data;
        var ptNumber = selection.index;

        var labels = {
            xLabel: formatter('xaxis', selection.traceCoordinate[0]),
            yLabel: formatter('yaxis', selection.traceCoordinate[1]),
            zLabel: formatter('zaxis', selection.traceCoordinate[2])
        };

        var hoverinfo = Fx.castHoverinfo(trace, scene.fullLayout, ptNumber);
        var hoverinfoParts = (hoverinfo || '').split('+');
        var isHoverinfoAll = hoverinfo && hoverinfo === 'all';

        if(!trace.hovertemplate && !isHoverinfoAll) {
            if(hoverinfoParts.indexOf('x') === -1) labels.xLabel = undefined;
            if(hoverinfoParts.indexOf('y') === -1) labels.yLabel = undefined;
            if(hoverinfoParts.indexOf('z') === -1) labels.zLabel = undefined;
            if(hoverinfoParts.indexOf('text') === -1) selection.textLabel = undefined;
            if(hoverinfoParts.indexOf('name') === -1) lastPicked.name = undefined;
        }

        var tx;
        var vectorTx = [];

        if(trace.type === 'cone' || trace.type === 'streamtube') {
            labels.uLabel = formatter('xaxis', selection.traceCoordinate[3]);
            if(isHoverinfoAll || hoverinfoParts.indexOf('u') !== -1) {
                vectorTx.push('u: ' + labels.uLabel);
            }

            labels.vLabel = formatter('yaxis', selection.traceCoordinate[4]);
            if(isHoverinfoAll || hoverinfoParts.indexOf('v') !== -1) {
                vectorTx.push('v: ' + labels.vLabel);
            }

            labels.wLabel = formatter('zaxis', selection.traceCoordinate[5]);
            if(isHoverinfoAll || hoverinfoParts.indexOf('w') !== -1) {
                vectorTx.push('w: ' + labels.wLabel);
            }

            labels.normLabel = selection.traceCoordinate[6].toPrecision(3);
            if(isHoverinfoAll || hoverinfoParts.indexOf('norm') !== -1) {
                vectorTx.push('norm: ' + labels.normLabel);
            }
            if(trace.type === 'streamtube') {
                labels.divergenceLabel = selection.traceCoordinate[7].toPrecision(3);
                if(isHoverinfoAll || hoverinfoParts.indexOf('divergence') !== -1) {
                    vectorTx.push('divergence: ' + labels.divergenceLabel);
                }
            }
            if(selection.textLabel) {
                vectorTx.push(selection.textLabel);
            }
            tx = vectorTx.join('<br>');
        } else if(trace.type === 'isosurface') {
            labels.valueLabel = Axes.tickText(scene.mockAxis, scene.mockAxis.d2l(selection.traceCoordinate[3]), 'hover').text;
            vectorTx.push('value: ' + labels.valueLabel);
            if(selection.textLabel) {
                vectorTx.push(selection.textLabel);
            }
            tx = vectorTx.join('<br>');
        } else {
            tx = selection.textLabel;
        }

        var pointData = {
            x: selection.traceCoordinate[0],
            y: selection.traceCoordinate[1],
            z: selection.traceCoordinate[2],
            data: trace._input,
            fullData: trace,
            curveNumber: trace.index,
            pointNumber: ptNumber
        };

        Fx.appendArrayPointValue(pointData, trace, ptNumber);

        if(trace._module.eventData) {
            pointData = trace._module.eventData(pointData, selection, trace, {}, ptNumber);
        }

        var eventData = {points: [pointData]};

        if(scene.fullSceneLayout.hovermode) {
            Fx.loneHover({
                trace: trace,
                x: (0.5 + 0.5 * pdata[0] / pdata[3]) * width,
                y: (0.5 - 0.5 * pdata[1] / pdata[3]) * height,
                xLabel: labels.xLabel,
                yLabel: labels.yLabel,
                zLabel: labels.zLabel,
                text: tx,
                name: lastPicked.name,
                color: Fx.castHoverOption(trace, ptNumber, 'bgcolor') || lastPicked.color,
                borderColor: Fx.castHoverOption(trace, ptNumber, 'bordercolor'),
                fontFamily: Fx.castHoverOption(trace, ptNumber, 'font.family'),
                fontSize: Fx.castHoverOption(trace, ptNumber, 'font.size'),
                fontColor: Fx.castHoverOption(trace, ptNumber, 'font.color'),
                hovertemplate: Lib.castOption(trace, ptNumber, 'hovertemplate'),
                hovertemplateLabels: Lib.extendFlat({}, pointData, labels),
                eventData: [pointData]
            }, {
                container: svgContainer,
                gd: scene.graphDiv
            });
        }

        if(selection.buttons && selection.distance < 5) {
            scene.graphDiv.emit('plotly_click', eventData);
        } else {
            scene.graphDiv.emit('plotly_hover', eventData);
        }

        oldEventData = eventData;
    }
    else {
        Fx.loneUnhover(svgContainer);
        scene.graphDiv.emit('plotly_unhover', oldEventData);
    }

    scene.drawAnnotations(scene);
}

function tryCreatePlot(scene, camera, pixelRatio, canvas, gl) {

    var glplotOptions = {
        canvas: canvas,
        gl: gl,
        container: scene.container,
        axes: scene.axesOptions,
        spikes: scene.spikeOptions,
        pickRadius: 10,
        snapToData: true,
        autoScale: true,
        autoBounds: false,
        camera: camera,
        pixelRatio: pixelRatio
    };

    // for static plots, we reuse the WebGL context
    //  as WebKit doesn't collect them reliably
    if(scene.staticMode) {
        if(!STATIC_CONTEXT) {
            STATIC_CANVAS = document.createElement('canvas');
            STATIC_CONTEXT = getContext({
                canvas: STATIC_CANVAS,
                preserveDrawingBuffer: true,
                premultipliedAlpha: true,
                antialias: true
            });
            if(!STATIC_CONTEXT) {
                throw new Error('error creating static canvas/context for image server');
            }
        }
        glplotOptions.pixelRatio = scene.pixelRatio;
        glplotOptions.gl = STATIC_CONTEXT;
        glplotOptions.canvas = STATIC_CANVAS;
    }

    try {
        scene.glplot = createPlot(glplotOptions);
    }
    catch(e) {
        return false;
    }

    return true;
}

function initializeGLPlot(scene, camera, pixelRatio, canvas, gl) {

    var success = tryCreatePlot(scene, camera, pixelRatio, canvas, gl);
    /*
    * createPlot will throw when webgl is not enabled in the client.
    * Lets return an instance of the module with all functions noop'd.
    * The destroy method - which will remove the container from the DOM
    * is overridden with a function that removes the container only.
    */
    if(!success) return showNoWebGlMsg(scene);

    var gd = scene.graphDiv;

    var relayoutCallback = function(scene) {
        if(scene.fullSceneLayout.dragmode === false) return;

        var update = {};
        update[scene.id + '.camera'] = getLayoutCamera(scene.camera);
        scene.saveCamera(gd.layout);
        scene.graphDiv.emit('plotly_relayout', update);
    };

    scene.glplot.canvas.addEventListener('mouseup', function() {
        relayoutCallback(scene);
    });

    scene.glplot.canvas.addEventListener('wheel', function() {
        if(gd._context._scrollZoom.gl3d) {
            relayoutCallback(scene);
        }
    }, passiveSupported ? {passive: false} : false);

    if(!scene.staticMode) {
        scene.glplot.canvas.addEventListener('webglcontextlost', function(event) {
            if(gd && gd.emit) {
                gd.emit('plotly_webglcontextlost', {
                    event: event,
                    layer: scene.id
                });
            }
        }, false);
    }

    if(!scene.camera) scene.initializeGLCamera();

    scene.glplot.camera = scene.camera;

    scene.glplot.oncontextloss = function() {
        scene.recoverContext();
    };

    scene.glplot.onrender = render.bind(null, scene);

    // List of scene objects
    scene.traces = {};

    scene.make4thDimension();

    return true;
}

function Scene(options, fullLayout) {

    // create sub container for plot
    var sceneContainer = document.createElement('div');
    var plotContainer = options.container;

    // keep a ref to the graph div to fire hover+click events
    this.graphDiv = options.graphDiv;

    // create SVG container for hover text
    var svgContainer = document.createElementNS(
        'http://www.w3.org/2000/svg',
        'svg');
    svgContainer.style.position = 'absolute';
    svgContainer.style.top = svgContainer.style.left = '0px';
    svgContainer.style.width = svgContainer.style.height = '100%';
    svgContainer.style['z-index'] = 20;
    svgContainer.style['pointer-events'] = 'none';
    sceneContainer.appendChild(svgContainer);
    this.svgContainer = svgContainer;

    // Tag the container with the sceneID
    sceneContainer.id = options.id;
    sceneContainer.style.position = 'absolute';
    sceneContainer.style.top = sceneContainer.style.left = '0px';
    sceneContainer.style.width = sceneContainer.style.height = '100%';
    plotContainer.appendChild(sceneContainer);

    this.fullLayout = fullLayout;
    this.id = options.id || 'scene';
    this.fullSceneLayout = fullLayout[this.id];

    // Saved from last call to plot()
    this.plotArgs = [ [], {}, {} ];

    /*
     * Move this to calc step? Why does it work here?
     */
    this.axesOptions = createAxesOptions(fullLayout, fullLayout[this.id]);
    this.spikeOptions = createSpikeOptions(fullLayout[this.id]);
    this.container = sceneContainer;
    this.staticMode = !!options.staticPlot;
    this.pixelRatio = this.pixelRatio || options.plotGlPixelRatio || 2;

    // Coordinate rescaling
    this.dataScale = [1, 1, 1];

    this.contourLevels = [ [], [], [] ];

    this.convertAnnotations = Registry.getComponentMethod('annotations3d', 'convert');
    this.drawAnnotations = Registry.getComponentMethod('annotations3d', 'draw');

    var camera = fullLayout.scene.camera;

    initializeGLPlot(this, camera, this.pixelRatio);
}

var proto = Scene.prototype;

proto.initializeGLCamera = function() {

    var cameraData = this.fullSceneLayout.camera;
    var isOrtho = (cameraData.projection.type === 'orthographic');

    this.camera = createCamera(this.container, {
        center: [cameraData.center.x, cameraData.center.y, cameraData.center.z],
        eye: [cameraData.eye.x, cameraData.eye.y, cameraData.eye.z],
        up: [cameraData.up.x, cameraData.up.y, cameraData.up.z],
        _ortho: isOrtho,
        zoomMin: 0.01,
        zoomMax: 100,
        mode: 'orbit'
    });
};

proto.recoverContext = function() {
    var scene = this;
    var gl = this.glplot.gl;
    var canvas = this.glplot.canvas;
    var camera = this.glplot.camera;
    var pixelRatio = this.glplot.pixelRatio;
    this.glplot.dispose();

    function tryRecover() {
        if(gl.isContextLost()) {
            requestAnimationFrame(tryRecover);
            return;
        }
        if(!initializeGLPlot(scene, camera, pixelRatio, canvas, gl)) {
            Lib.error('Catastrophic and unrecoverable WebGL error. Context lost.');
            return;
        }
        scene.plot.apply(scene, scene.plotArgs);
    }
    requestAnimationFrame(tryRecover);
};

var axisProperties = [ 'xaxis', 'yaxis', 'zaxis' ];

function computeTraceBounds(scene, trace, bounds) {
    var sceneLayout = scene.fullSceneLayout;

    for(var d = 0; d < 3; d++) {
        var axisName = axisProperties[d];
        var axLetter = axisName.charAt(0);
        var ax = sceneLayout[axisName];
        var coords = trace[axLetter];
        var calendar = trace[axLetter + 'calendar'];
        var len = trace['_' + axLetter + 'length'];

        if(!Lib.isArrayOrTypedArray(coords)) {
            bounds[0][d] = Math.min(bounds[0][d], 0);
            bounds[1][d] = Math.max(bounds[1][d], len - 1);
        } else {
            var v;

            for(var i = 0; i < (len || coords.length); i++) {
                if(Lib.isArrayOrTypedArray(coords[i])) {
                    for(var j = 0; j < coords[i].length; ++j) {
                        v = ax.d2l(coords[i][j], 0, calendar);
                        if(!isNaN(v) && isFinite(v)) {
                            bounds[0][d] = Math.min(bounds[0][d], v);
                            bounds[1][d] = Math.max(bounds[1][d], v);
                        }
                    }
                } else {
                    v = ax.d2l(coords[i], 0, calendar);
                    if(!isNaN(v) && isFinite(v)) {
                        bounds[0][d] = Math.min(bounds[0][d], v);
                        bounds[1][d] = Math.max(bounds[1][d], v);
                    }
                }
            }
        }
    }
}

function computeAnnotationBounds(scene, bounds) {
    var sceneLayout = scene.fullSceneLayout;
    var annotations = sceneLayout.annotations || [];

    for(var d = 0; d < 3; d++) {
        var axisName = axisProperties[d];
        var axLetter = axisName.charAt(0);
        var ax = sceneLayout[axisName];

        for(var j = 0; j < annotations.length; j++) {
            var ann = annotations[j];

            if(ann.visible) {
                var pos = ax.r2l(ann[axLetter]);
                if(!isNaN(pos) && isFinite(pos)) {
                    bounds[0][d] = Math.min(bounds[0][d], pos);
                    bounds[1][d] = Math.max(bounds[1][d], pos);
                }
            }
        }
    }
}

proto.plot = function(sceneData, fullLayout, layout) {
    // Save parameters
    this.plotArgs = [sceneData, fullLayout, layout];

    if(this.glplot.contextLost) return;

    var data, trace;
    var i, j, axis, axisType;
    var fullSceneLayout = fullLayout[this.id];
    var sceneLayout = layout[this.id];

    if(fullSceneLayout.bgcolor) this.glplot.clearColor = str2RGBAarray(fullSceneLayout.bgcolor);
    else this.glplot.clearColor = [0, 0, 0, 0];

    this.glplot.snapToData = true;

    // Update layout
    this.fullLayout = fullLayout;
    this.fullSceneLayout = fullSceneLayout;

    this.glplotLayout = fullSceneLayout;
    this.axesOptions.merge(fullLayout, fullSceneLayout);
    this.spikeOptions.merge(fullSceneLayout);

    // Update camera and camera mode
    this.setCamera(fullSceneLayout.camera);
    this.updateFx(fullSceneLayout.dragmode, fullSceneLayout.hovermode);
    this.camera.enableWheel = this.graphDiv._context._scrollZoom.gl3d;

    // Update scene
    this.glplot.update({});

    // Update axes functions BEFORE updating traces
    this.setConvert(axis);

    // Convert scene data
    if(!sceneData) sceneData = [];
    else if(!Array.isArray(sceneData)) sceneData = [sceneData];

    // Compute trace bounding box
    var dataBounds = [
        [Infinity, Infinity, Infinity],
        [-Infinity, -Infinity, -Infinity]
    ];

    for(i = 0; i < sceneData.length; ++i) {
        data = sceneData[i];
        if(data.visible !== true) continue;

        computeTraceBounds(this, data, dataBounds);
    }
    computeAnnotationBounds(this, dataBounds);

    var dataScale = [1, 1, 1];
    for(j = 0; j < 3; ++j) {
        if(dataBounds[1][j] === dataBounds[0][j]) {
            dataScale[j] = 1.0;
        } else {
            dataScale[j] = 1.0 / (dataBounds[1][j] - dataBounds[0][j]);
        }
    }

    // Save scale
    this.dataScale = dataScale;

    // after computeTraceBounds where ax._categories are filled in
    this.convertAnnotations(this);

    // Update traces
    for(i = 0; i < sceneData.length; ++i) {
        data = sceneData[i];
        if(data.visible !== true) {
            continue;
        }
        trace = this.traces[data.uid];
        if(trace) {
            if(trace.data.type === data.type) {
                trace.update(data);
            } else {
                trace.dispose();
                trace = data._module.plot(this, data);
                this.traces[data.uid] = trace;
            }
        } else {
            trace = data._module.plot(this, data);
            this.traces[data.uid] = trace;
        }
        trace.name = data.name;
    }

    // Remove empty traces
    var traceIds = Object.keys(this.traces);

    traceIdLoop:
    for(i = 0; i < traceIds.length; ++i) {
        for(j = 0; j < sceneData.length; ++j) {
            if(sceneData[j].uid === traceIds[i] && sceneData[j].visible === true) {
                continue traceIdLoop;
            }
        }
        trace = this.traces[traceIds[i]];
        trace.dispose();
        delete this.traces[traceIds[i]];
    }

    // order object per trace index
    this.glplot.objects.sort(function(a, b) {
        return a._trace.data.index - b._trace.data.index;
    });

    // Update ranges (needs to be called *after* objects are added due to updates)
    var sceneBounds = [[0, 0, 0], [0, 0, 0]];
    var axisDataRange = [];
    var axisTypeRatios = {};

    for(i = 0; i < 3; ++i) {
        axis = fullSceneLayout[axisProperties[i]];
        axisType = axis.type;

        if(axisType in axisTypeRatios) {
            axisTypeRatios[axisType].acc *= dataScale[i];
            axisTypeRatios[axisType].count += 1;
        }
        else {
            axisTypeRatios[axisType] = {
                acc: dataScale[i],
                count: 1
            };
        }

        if(axis.autorange) {
            sceneBounds[0][i] = Infinity;
            sceneBounds[1][i] = -Infinity;

            var objects = this.glplot.objects;
            var annotations = this.fullSceneLayout.annotations || [];
            var axLetter = axis._name.charAt(0);

            for(j = 0; j < objects.length; j++) {
                var obj = objects[j];
                var objBounds = obj.bounds;
                var pad = obj._trace.data._pad || 0;

                if(obj.constructor.name === 'ErrorBars' && axis._lowerLogErrorBound) {
                    sceneBounds[0][i] = Math.min(sceneBounds[0][i], axis._lowerLogErrorBound);
                } else {
                    sceneBounds[0][i] = Math.min(sceneBounds[0][i], objBounds[0][i] / dataScale[i] - pad);
                }
                sceneBounds[1][i] = Math.max(sceneBounds[1][i], objBounds[1][i] / dataScale[i] + pad);
            }

            for(j = 0; j < annotations.length; j++) {
                var ann = annotations[j];

                // N.B. not taking into consideration the arrowhead
                if(ann.visible) {
                    var pos = axis.r2l(ann[axLetter]);
                    sceneBounds[0][i] = Math.min(sceneBounds[0][i], pos);
                    sceneBounds[1][i] = Math.max(sceneBounds[1][i], pos);
                }
            }

            if('rangemode' in axis && axis.rangemode === 'tozero') {
                sceneBounds[0][i] = Math.min(sceneBounds[0][i], 0);
                sceneBounds[1][i] = Math.max(sceneBounds[1][i], 0);
            }
            if(sceneBounds[0][i] > sceneBounds[1][i]) {
                sceneBounds[0][i] = -1;
                sceneBounds[1][i] = 1;
            } else {
                var d = sceneBounds[1][i] - sceneBounds[0][i];
                sceneBounds[0][i] -= d / 32.0;
                sceneBounds[1][i] += d / 32.0;
            }

            if(axis.autorange === 'reversed') {
                // swap bounds:
                var tmp = sceneBounds[0][i];
                sceneBounds[0][i] = sceneBounds[1][i];
                sceneBounds[1][i] = tmp;
            }
        } else {
            var range = axis.range;
            sceneBounds[0][i] = axis.r2l(range[0]);
            sceneBounds[1][i] = axis.r2l(range[1]);
        }
        if(sceneBounds[0][i] === sceneBounds[1][i]) {
            sceneBounds[0][i] -= 1;
            sceneBounds[1][i] += 1;
        }
        axisDataRange[i] = sceneBounds[1][i] - sceneBounds[0][i];

        // Update plot bounds
        this.glplot.bounds[0][i] = sceneBounds[0][i] * dataScale[i];
        this.glplot.bounds[1][i] = sceneBounds[1][i] * dataScale[i];
    }

    var axesScaleRatio = [1, 1, 1];

    // Compute axis scale per category
    for(i = 0; i < 3; ++i) {
        axis = fullSceneLayout[axisProperties[i]];
        axisType = axis.type;
        var axisRatio = axisTypeRatios[axisType];
        axesScaleRatio[i] = Math.pow(axisRatio.acc, 1.0 / axisRatio.count) / dataScale[i];
    }

    /*
     * Dynamically set the aspect ratio depending on the users aspect settings
     */
    var axisAutoScaleFactor = 4;
    var aspectRatio;

    if(fullSceneLayout.aspectmode === 'auto') {

        if(Math.max.apply(null, axesScaleRatio) / Math.min.apply(null, axesScaleRatio) <= axisAutoScaleFactor) {

            /*
             * USE DATA MODE WHEN AXIS RANGE DIMENSIONS ARE RELATIVELY EQUAL
             */

            aspectRatio = axesScaleRatio;
        } else {

            /*
             * USE EQUAL MODE WHEN AXIS RANGE DIMENSIONS ARE HIGHLY UNEQUAL
             */
            aspectRatio = [1, 1, 1];
        }

    } else if(fullSceneLayout.aspectmode === 'cube') {
        aspectRatio = [1, 1, 1];

    } else if(fullSceneLayout.aspectmode === 'data') {
        aspectRatio = axesScaleRatio;

    } else if(fullSceneLayout.aspectmode === 'manual') {
        var userRatio = fullSceneLayout.aspectratio;
        aspectRatio = [userRatio.x, userRatio.y, userRatio.z];

    } else {
        throw new Error('scene.js aspectRatio was not one of the enumerated types');
    }

    /*
     * Write aspect Ratio back to user data and fullLayout so that it is modifies as user
     * manipulates the aspectmode settings and the fullLayout is up-to-date.
     */
    fullSceneLayout.aspectratio.x = sceneLayout.aspectratio.x = aspectRatio[0];
    fullSceneLayout.aspectratio.y = sceneLayout.aspectratio.y = aspectRatio[1];
    fullSceneLayout.aspectratio.z = sceneLayout.aspectratio.z = aspectRatio[2];

    /*
     * Finally assign the computed aspecratio to the glplot module. This will have an effect
     * on the next render cycle.
     */
    this.glplot.aspect = aspectRatio;


    // Update frame position for multi plots
    var domain = fullSceneLayout.domain || null;
    var size = fullLayout._size || null;

    if(domain && size) {
        var containerStyle = this.container.style;
        containerStyle.position = 'absolute';
        containerStyle.left = (size.l + domain.x[0] * size.w) + 'px';
        containerStyle.top = (size.t + (1 - domain.y[1]) * size.h) + 'px';
        containerStyle.width = (size.w * (domain.x[1] - domain.x[0])) + 'px';
        containerStyle.height = (size.h * (domain.y[1] - domain.y[0])) + 'px';
    }

    // force redraw so that promise is returned when rendering is completed
    this.glplot.redraw();
};

proto.destroy = function() {
    if(!this.glplot) return;

    this.camera.mouseListener.enabled = false;
    this.container.removeEventListener('wheel', this.camera.wheelListener);
    this.camera = this.glplot.camera = null;
    this.glplot.dispose();
    this.container.parentNode.removeChild(this.container);
    this.glplot = null;
};

// getOrbitCamera :: plotly_coords -> orbit_camera_coords
// inverse of getLayoutCamera
function getOrbitCamera(camera) {
    return [
        [camera.eye.x, camera.eye.y, camera.eye.z],
        [camera.center.x, camera.center.y, camera.center.z],
        [camera.up.x, camera.up.y, camera.up.z]
    ];
}

// getLayoutCamera :: orbit_camera_coords -> plotly_coords
// inverse of getOrbitCamera
function getLayoutCamera(camera) {
    return {
        up: {x: camera.up[0], y: camera.up[1], z: camera.up[2]},
        center: {x: camera.center[0], y: camera.center[1], z: camera.center[2]},
        eye: {x: camera.eye[0], y: camera.eye[1], z: camera.eye[2]},
        projection: {type: (camera._ortho === true) ? 'orthographic' : 'perspective'}
    };
}

// get camera position in plotly coords from 'orbit-camera' coords
proto.getCamera = function getCamera() {
    this.glplot.camera.view.recalcMatrix(this.camera.view.lastT());
    return getLayoutCamera(this.glplot.camera);
};

// set camera position with a set of plotly coords
proto.setCamera = function setCamera(cameraData) {
    this.glplot.camera.lookAt.apply(this, getOrbitCamera(cameraData));

    var newOrtho = (cameraData.projection.type === 'orthographic');
    var oldOrtho = this.glplot.camera._ortho;

    if(newOrtho !== oldOrtho) {
        this.glplot.redraw();

        var pixelRatio = this.glplot.pixelRatio;

        var RGBA = this.glplot.clearColor;
        this.glplot.gl.clearColor(
            RGBA[0], RGBA[1], RGBA[2], RGBA[3]
        );
        this.glplot.gl.clear(
            this.glplot.gl.DEPTH_BUFFER_BIT |
            this.glplot.gl.COLOR_BUFFER_BIT
        );

        this.glplot.dispose();

        initializeGLPlot(this, cameraData, pixelRatio);
        this.glplot.camera._ortho = newOrtho;
    }
};

// save camera to user layout (i.e. gd.layout)
proto.saveCamera = function saveCamera(layout) {
    var fullLayout = this.fullLayout;
    var cameraData = this.getCamera();
    var cameraNestedProp = Lib.nestedProperty(layout, this.id + '.camera');
    var cameraDataLastSave = cameraNestedProp.get();
    var hasChanged = false;

    function same(x, y, i, j) {
        var vectors = ['up', 'center', 'eye'];
        var components = ['x', 'y', 'z'];
        return y[vectors[i]] && (x[vectors[i]][components[j]] === y[vectors[i]][components[j]]);
    }

    if(cameraDataLastSave === undefined) {
        hasChanged = true;
    } else {
        for(var i = 0; i < 3; i++) {
            for(var j = 0; j < 3; j++) {
                if(!same(cameraData, cameraDataLastSave, i, j)) {
                    hasChanged = true;
                    break;
                }
            }
        }

        if(!cameraDataLastSave.projection || (
            cameraData.projection &&
            cameraData.projection.type !== cameraDataLastSave.projection.type)) {

            hasChanged = true;
        }
    }

    if(hasChanged) {
        var preGUI = {};
        preGUI[this.id + '.camera'] = cameraDataLastSave;
        Registry.call('_storeDirectGUIEdit', layout, fullLayout._preGUI, preGUI);

        cameraNestedProp.set(cameraData);

        var cameraFullNP = Lib.nestedProperty(fullLayout, this.id + '.camera');
        cameraFullNP.set(cameraData);
    }

    return hasChanged;
};

proto.updateFx = function(dragmode, hovermode) {
    var camera = this.camera;

    if(camera) {
        // rotate and orbital are synonymous
        if(dragmode === 'orbit') {
            camera.mode = 'orbit';
            camera.keyBindingMode = 'rotate';

        } else if(dragmode === 'turntable') {
            camera.up = [0, 0, 1];
            camera.mode = 'turntable';
            camera.keyBindingMode = 'rotate';

            // The setter for camera.mode animates the transition to z-up,
            // but only if we *don't* explicitly set z-up earlier via the
            // relayout. So push `up` back to layout & fullLayout manually now.
            var gd = this.graphDiv;
            var fullLayout = gd._fullLayout;
            var fullCamera = this.fullSceneLayout.camera;
            var x = fullCamera.up.x;
            var y = fullCamera.up.y;
            var z = fullCamera.up.z;
            // only push `up` back to (full)layout if it's going to change
            if(z / Math.sqrt(x * x + y * y + z * z) > 0.999) return;

            var attr = this.id + '.camera.up';
            var zUp = {x: 0, y: 0, z: 1};
            var edits = {};
            edits[attr] = zUp;
            var layout = gd.layout;
            Registry.call('_storeDirectGUIEdit', layout, fullLayout._preGUI, edits);
            fullCamera.up = zUp;
            Lib.nestedProperty(layout, attr).set(zUp);
        } else {
            // none rotation modes [pan or zoom]
            camera.keyBindingMode = dragmode;
        }
    }

    // to put dragmode and hovermode on the same grounds from relayout
    this.fullSceneLayout.hovermode = hovermode;
};

proto.toImage = function(format) {
    if(!format) format = 'png';

    if(this.staticMode) this.container.appendChild(STATIC_CANVAS);

    // Force redraw
    this.glplot.redraw();

    // Grab context and yank out pixels
    var gl = this.glplot.gl;
    var w = gl.drawingBufferWidth;
    var h = gl.drawingBufferHeight;

    gl.bindFramebuffer(gl.FRAMEBUFFER, null);

    var pixels = new Uint8Array(w * h * 4);
    gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, pixels);

    // Flip pixels
    for(var j = 0, k = h - 1; j < k; ++j, --k) {
        for(var i = 0; i < w; ++i) {
            for(var l = 0; l < 4; ++l) {
                var tmp = pixels[4 * (w * j + i) + l];
                pixels[4 * (w * j + i) + l] = pixels[4 * (w * k + i) + l];
                pixels[4 * (w * k + i) + l] = tmp;
            }
        }
    }

    var canvas = document.createElement('canvas');
    canvas.width = w;
    canvas.height = h;
    var context = canvas.getContext('2d');
    var imageData = context.createImageData(w, h);
    imageData.data.set(pixels);
    context.putImageData(imageData, 0, 0);

    var dataURL;

    switch(format) {
        case 'jpeg':
            dataURL = canvas.toDataURL('image/jpeg');
            break;
        case 'webp':
            dataURL = canvas.toDataURL('image/webp');
            break;
        default:
            dataURL = canvas.toDataURL('image/png');
    }

    if(this.staticMode) this.container.removeChild(STATIC_CANVAS);

    return dataURL;
};

proto.setConvert = function() {
    for(var i = 0; i < 3; i++) {
        var ax = this.fullSceneLayout[axisProperties[i]];
        Axes.setConvert(ax, this.fullLayout);
        ax.setScale = Lib.noop;
    }
};

proto.make4thDimension = function() {

    var _this = this;
    var gd = _this.graphDiv;
    var fullLayout = gd._fullLayout;

    // mock axis for hover formatting
    _this.mockAxis = {
        type: 'linear',
        showexponent: 'all',
        exponentformat: 'B'
    };
    Axes.setConvert(_this.mockAxis, fullLayout);
};

module.exports = Scene;

},{"../../components/fx":613,"../../lib":697,"../../lib/show_no_webgl_msg":718,"../../lib/str2rgbarray":720,"../../plots/cartesian/axes":745,"../../registry":826,"./layout/convert":790,"./layout/spikes":793,"./layout/tick_marks":794,"./project":795,"gl-plot3d":283,"has-passive-events":400,"webgl-context":537}],797:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function zip3(x, y, z, len) {
    len = len || x.length;

    var result = new Array(len);
    for(var i = 0; i < len; i++) {
        result[i] = [x[i], y[i], z[i]];
    }
    return result;
};

},{}],798:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = _dereq_('./font_attributes');
var animationAttrs = _dereq_('./animation_attributes');
var colorAttrs = _dereq_('../components/color/attributes');
var colorscaleAttrs = _dereq_('../components/colorscale/layout_attributes');
var padAttrs = _dereq_('./pad_attributes');
var extendFlat = _dereq_('../lib/extend').extendFlat;

var globalFont = fontAttrs({
    editType: 'calc',
    
});
globalFont.family.dflt = '"Open Sans", verdana, arial, sans-serif';
globalFont.size.dflt = 12;
globalFont.color.dflt = colorAttrs.defaultLine;

module.exports = {
    font: globalFont,
    title: {
        text: {
            valType: 'string',
            
            editType: 'layoutstyle',
            
        },
        font: fontAttrs({
            editType: 'layoutstyle',
            
        }),
        xref: {
            valType: 'enumerated',
            dflt: 'container',
            values: ['container', 'paper'],
            
            editType: 'layoutstyle',
            
        },
        yref: {
            valType: 'enumerated',
            dflt: 'container',
            values: ['container', 'paper'],
            
            editType: 'layoutstyle',
            
        },
        x: {
            valType: 'number',
            min: 0,
            max: 1,
            dflt: 0.5,
            
            editType: 'layoutstyle',
            
        },
        y: {
            valType: 'number',
            min: 0,
            max: 1,
            dflt: 'auto',
            
            editType: 'layoutstyle',
            
        },
        xanchor: {
            valType: 'enumerated',
            dflt: 'auto',
            values: ['auto', 'left', 'center', 'right'],
            
            editType: 'layoutstyle',
            
        },
        yanchor: {
            valType: 'enumerated',
            dflt: 'auto',
            values: ['auto', 'top', 'middle', 'bottom'],
            
            editType: 'layoutstyle',
            
        },
        pad: extendFlat(padAttrs({editType: 'layoutstyle'}), {
            
        }),
        editType: 'layoutstyle'
    },
    autosize: {
        valType: 'boolean',
        
        dflt: false,
        // autosize, width, and height get special editType treatment in _relayout
        // so we can handle noop resizes more efficiently
        editType: 'none',
        
    },
    width: {
        valType: 'number',
        
        min: 10,
        dflt: 700,
        editType: 'plot',
        
    },
    height: {
        valType: 'number',
        
        min: 10,
        dflt: 450,
        editType: 'plot',
        
    },
    margin: {
        l: {
            valType: 'number',
            
            min: 0,
            dflt: 80,
            editType: 'plot',
            
        },
        r: {
            valType: 'number',
            
            min: 0,
            dflt: 80,
            editType: 'plot',
            
        },
        t: {
            valType: 'number',
            
            min: 0,
            dflt: 100,
            editType: 'plot',
            
        },
        b: {
            valType: 'number',
            
            min: 0,
            dflt: 80,
            editType: 'plot',
            
        },
        pad: {
            valType: 'number',
            
            min: 0,
            dflt: 0,
            editType: 'plot',
            
        },
        autoexpand: {
            valType: 'boolean',
            
            dflt: true,
            editType: 'plot'
        },
        editType: 'plot'
    },
    paper_bgcolor: {
        valType: 'color',
        
        dflt: colorAttrs.background,
        editType: 'plot',
        
    },
    plot_bgcolor: {
        // defined here, but set in cartesian.supplyLayoutDefaults
        // because it needs to know if there are (2D) axes or not
        valType: 'color',
        
        dflt: colorAttrs.background,
        editType: 'layoutstyle',
        
    },
    separators: {
        valType: 'string',
        
        editType: 'plot',
        
    },
    hidesources: {
        valType: 'boolean',
        
        dflt: false,
        editType: 'plot',
        
    },
    showlegend: {
        // handled in legend.supplyLayoutDefaults
        // but included here because it's not in the legend object
        valType: 'boolean',
        
        editType: 'legend',
        
    },
    colorway: {
        valType: 'colorlist',
        dflt: colorAttrs.defaults,
        
        editType: 'calc',
        
    },
    colorscale: colorscaleAttrs,
    datarevision: {
        valType: 'any',
        
        editType: 'calc',
        
    },
    uirevision: {
        valType: 'any',
        
        editType: 'none',
        
    },
    editrevision: {
        valType: 'any',
        
        editType: 'none',
        
    },
    selectionrevision: {
        valType: 'any',
        
        editType: 'none',
        
    },
    template: {
        valType: 'any',
        
        editType: 'calc',
        
    },
    modebar: {
        orientation: {
            valType: 'enumerated',
            values: ['v', 'h'],
            dflt: 'h',
            
            editType: 'modebar',
            
        },
        bgcolor: {
            valType: 'color',
            
            editType: 'modebar',
            
        },
        color: {
            valType: 'color',
            
            editType: 'modebar',
            
        },
        activecolor: {
            valType: 'color',
            
            editType: 'modebar',
            
        },
        uirevision: {
            valType: 'any',
            
            editType: 'none',
            
        },
        editType: 'modebar'
    },

    meta: {
        valType: 'data_array',
        editType: 'plot',
        
    },

    transition: extendFlat({}, animationAttrs.transition, {
        
        editType: 'none'
    }),

    _deprecated: {
        title: {
            valType: 'string',
            
            editType: 'layoutstyle',
            
        },
        titlefont: fontAttrs({
            editType: 'layoutstyle',
            
        })
    }
};

},{"../components/color/attributes":573,"../components/colorscale/layout_attributes":587,"../lib/extend":687,"./animation_attributes":740,"./font_attributes":771,"./pad_attributes":806}],799:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var requiredVersion = '0.45.0';

module.exports = {
    requiredVersion: requiredVersion,

    styleUrlPrefix: 'mapbox://styles/mapbox/',
    styleUrlSuffix: 'v9',

    controlContainerClassName: 'mapboxgl-control-container',

    wrongVersionErrorMsg: [
        'Your custom plotly.js bundle is not using the correct mapbox-gl version',
        'Please install mapbox-gl@' + requiredVersion + '.'
    ].join('\n'),

    noAccessTokenErrorMsg: [
        'Missing Mapbox access token.',
        'Mapbox trace type require a Mapbox access token to be registered.',
        'For example:',
        '  Plotly.plot(gd, data, layout, { mapboxAccessToken: \'my-access-token\' });',
        'More info here: https://www.mapbox.com/help/define-access-token/'
    ].join('\n'),

    mapOnErrorMsg: 'Mapbox error.',

    // a subset of node_modules/mapbox-gl/dist/mapbox-gl.css
    styleRules: {
        map: 'overflow:hidden;position:relative;',
        'missing-css': 'display:none',
    }
};

},{}],800:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

/**
 * Convert plotly.js 'textposition' to mapbox-gl 'anchor' and 'offset'
 * (with the help of the icon size).
 *
 * @param {string} textpostion : plotly.js textposition value
 * @param {number} iconSize : plotly.js icon size (e.g. marker.size for traces)
 *
 * @return {object}
 *      - anchor
 *      - offset
 */
module.exports = function convertTextOpts(textposition, iconSize) {
    var parts = textposition.split(' ');
    var vPos = parts[0];
    var hPos = parts[1];

    // ballpack values
    var factor = Lib.isArrayOrTypedArray(iconSize) ? Lib.mean(iconSize) : iconSize;
    var xInc = 0.5 + (factor / 100);
    var yInc = 1.5 + (factor / 100);

    var anchorVals = ['', ''];
    var offset = [0, 0];

    switch(vPos) {
        case 'top':
            anchorVals[0] = 'top';
            offset[1] = -yInc;
            break;
        case 'bottom':
            anchorVals[0] = 'bottom';
            offset[1] = yInc;
            break;
    }

    switch(hPos) {
        case 'left':
            anchorVals[1] = 'right';
            offset[0] = -xInc;
            break;
        case 'right':
            anchorVals[1] = 'left';
            offset[0] = xInc;
            break;
    }

    // Mapbox text-anchor must be one of:
    //  center, left, right, top, bottom,
    //  top-left, top-right, bottom-left, bottom-right

    var anchor;
    if(anchorVals[0] && anchorVals[1]) anchor = anchorVals.join('-');
    else if(anchorVals[0]) anchor = anchorVals[0];
    else if(anchorVals[1]) anchor = anchorVals[1];
    else anchor = 'center';

    return { anchor: anchor, offset: offset };
};

},{"../../lib":697}],801:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var mapboxgl = _dereq_('mapbox-gl');

var Lib = _dereq_('../../lib');
var getSubplotCalcData = _dereq_('../../plots/get_data').getSubplotCalcData;
var xmlnsNamespaces = _dereq_('../../constants/xmlns_namespaces');

var createMapbox = _dereq_('./mapbox');
var constants = _dereq_('./constants');

var MAPBOX = 'mapbox';

for(var k in constants.styleRules) {
    Lib.addStyleRule('.mapboxgl-' + k, constants.styleRules[k]);
}

exports.name = MAPBOX;

exports.attr = 'subplot';

exports.idRoot = MAPBOX;

exports.idRegex = exports.attrRegex = Lib.counterRegex(MAPBOX);

exports.attributes = {
    subplot: {
        valType: 'subplotid',
        
        dflt: 'mapbox',
        editType: 'calc',
        
    }
};

exports.layoutAttributes = _dereq_('./layout_attributes');

exports.supplyLayoutDefaults = _dereq_('./layout_defaults');

exports.plot = function plotMapbox(gd) {
    var fullLayout = gd._fullLayout;
    var calcData = gd.calcdata;
    var mapboxIds = fullLayout._subplots[MAPBOX];

    if(mapboxgl.version !== constants.requiredVersion) {
        throw new Error(constants.wrongVersionErrorMsg);
    }

    var accessToken = findAccessToken(gd, mapboxIds);
    mapboxgl.accessToken = accessToken;

    for(var i = 0; i < mapboxIds.length; i++) {
        var id = mapboxIds[i];
        var subplotCalcData = getSubplotCalcData(calcData, MAPBOX, id);
        var opts = fullLayout[id];
        var mapbox = opts._subplot;

        if(!mapbox) {
            mapbox = createMapbox({
                gd: gd,
                container: fullLayout._glcontainer.node(),
                id: id,
                fullLayout: fullLayout,
                staticPlot: gd._context.staticPlot
            });

            fullLayout[id]._subplot = mapbox;
        }

        if(!mapbox.viewInitial) {
            mapbox.viewInitial = {
                center: Lib.extendFlat({}, opts.center),
                zoom: opts.zoom,
                bearing: opts.bearing,
                pitch: opts.pitch
            };
        }

        mapbox.plot(subplotCalcData, fullLayout, gd._promises);
    }
};

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var oldMapboxKeys = oldFullLayout._subplots[MAPBOX] || [];

    for(var i = 0; i < oldMapboxKeys.length; i++) {
        var oldMapboxKey = oldMapboxKeys[i];

        if(!newFullLayout[oldMapboxKey] && !!oldFullLayout[oldMapboxKey]._subplot) {
            oldFullLayout[oldMapboxKey]._subplot.destroy();
        }
    }
};

exports.toSVG = function(gd) {
    var fullLayout = gd._fullLayout;
    var subplotIds = fullLayout._subplots[MAPBOX];
    var size = fullLayout._size;

    for(var i = 0; i < subplotIds.length; i++) {
        var opts = fullLayout[subplotIds[i]];
        var domain = opts.domain;
        var mapbox = opts._subplot;

        var imageData = mapbox.toImage('png');
        var image = fullLayout._glimages.append('svg:image');

        image.attr({
            xmlns: xmlnsNamespaces.svg,
            'xlink:href': imageData,
            x: size.l + size.w * domain.x[0],
            y: size.t + size.h * (1 - domain.y[1]),
            width: size.w * (domain.x[1] - domain.x[0]),
            height: size.h * (domain.y[1] - domain.y[0]),
            preserveAspectRatio: 'none'
        });

        mapbox.destroy();
    }
};

function findAccessToken(gd, mapboxIds) {
    var fullLayout = gd._fullLayout;
    var context = gd._context;

    // special case for Mapbox Atlas users
    if(context.mapboxAccessToken === '') return '';

    // Take the first token we find in a mapbox subplot.
    // These default to the context value but may be overridden.
    for(var i = 0; i < mapboxIds.length; i++) {
        var opts = fullLayout[mapboxIds[i]];

        if(opts.accesstoken) {
            return opts.accesstoken;
        }
    }

    throw new Error(constants.noAccessTokenErrorMsg);
}

exports.updateFx = function(gd) {
    var fullLayout = gd._fullLayout;
    var subplotIds = fullLayout._subplots[MAPBOX];

    for(var i = 0; i < subplotIds.length; i++) {
        var subplotObj = fullLayout[subplotIds[i]]._subplot;
        subplotObj.updateFx(fullLayout);
    }
};

},{"../../constants/xmlns_namespaces":675,"../../lib":697,"../../plots/get_data":781,"./constants":799,"./layout_attributes":803,"./layout_defaults":804,"./mapbox":805,"mapbox-gl":415}],802:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var convertTextOpts = _dereq_('./convert_text_opts');

function MapboxLayer(mapbox, index) {
    this.mapbox = mapbox;
    this.map = mapbox.map;

    this.uid = mapbox.uid + '-' + 'layer' + index;

    this.idSource = this.uid + '-source';
    this.idLayer = this.uid + '-layer';

    // some state variable to check if a remove/add step is needed
    this.sourceType = null;
    this.source = null;
    this.layerType = null;
    this.below = null;

    // is layer currently visible
    this.visible = false;
}

var proto = MapboxLayer.prototype;

proto.update = function update(opts) {
    if(!this.visible) {
        // IMPORTANT: must create source before layer to not cause errors
        this.updateSource(opts);
        this.updateLayer(opts);
    } else if(this.needsNewSource(opts)) {
        // IMPORTANT: must delete layer before source to not cause errors
        this.removeLayer();
        this.updateSource(opts);
        this.updateLayer(opts);
    } else if(this.needsNewLayer(opts)) {
        this.updateLayer(opts);
    } else {
        this.updateStyle(opts);
    }

    this.visible = isVisible(opts);
};

proto.needsNewSource = function(opts) {
    // for some reason changing layer to 'fill' or 'symbol'
    // w/o changing the source throws an exception in mapbox-gl 0.18 ;
    // stay safe and make new source on type changes
    return (
        this.sourceType !== opts.sourcetype ||
        this.source !== opts.source ||
        this.layerType !== opts.type
    );
};

proto.needsNewLayer = function(opts) {
    return (
        this.layerType !== opts.type ||
        this.below !== opts.below
    );
};

proto.updateSource = function(opts) {
    var map = this.map;

    if(map.getSource(this.idSource)) map.removeSource(this.idSource);

    this.sourceType = opts.sourcetype;
    this.source = opts.source;

    if(!isVisible(opts)) return;

    var sourceOpts = convertSourceOpts(opts);

    map.addSource(this.idSource, sourceOpts);
};

proto.updateLayer = function(opts) {
    var map = this.map;
    var convertedOpts = convertOpts(opts);

    this.removeLayer();
    this.layerType = opts.type;

    if(isVisible(opts)) {
        map.addLayer({
            id: this.idLayer,
            source: this.idSource,
            'source-layer': opts.sourcelayer || '',
            type: opts.type,
            minzoom: opts.minzoom,
            maxzoom: opts.maxzoom,
            layout: convertedOpts.layout,
            paint: convertedOpts.paint
        }, opts.below);
    }
};

proto.updateStyle = function(opts) {
    if(isVisible(opts)) {
        var convertedOpts = convertOpts(opts);
        this.mapbox.setOptions(this.idLayer, 'setLayoutProperty', convertedOpts.layout);
        this.mapbox.setOptions(this.idLayer, 'setPaintProperty', convertedOpts.paint);
    }
};

proto.removeLayer = function() {
    var map = this.map;
    if(map.getLayer(this.idLayer)) {
        map.removeLayer(this.idLayer);
    }
};

proto.dispose = function dispose() {
    var map = this.map;
    map.removeLayer(this.idLayer);
    map.removeSource(this.idSource);
};

function isVisible(opts) {
    var source = opts.source;

    return opts.visible && (
        Lib.isPlainObject(source) ||
        (typeof source === 'string' && source.length > 0)
    );
}

function convertOpts(opts) {
    var layout = {};
    var paint = {};

    switch(opts.type) {

        case 'circle':
            Lib.extendFlat(paint, {
                'circle-radius': opts.circle.radius,
                'circle-color': opts.color,
                'circle-opacity': opts.opacity
            });
            break;

        case 'line':
            Lib.extendFlat(paint, {
                'line-width': opts.line.width,
                'line-color': opts.color,
                'line-opacity': opts.opacity,
                'line-dasharray': opts.line.dash
            });
            break;

        case 'fill':
            Lib.extendFlat(paint, {
                'fill-color': opts.color,
                'fill-outline-color': opts.fill.outlinecolor,
                'fill-opacity': opts.opacity

                // no way to pass specify outline width at the moment
            });
            break;

        case 'symbol':
            var symbol = opts.symbol;
            var textOpts = convertTextOpts(symbol.textposition, symbol.iconsize);

            Lib.extendFlat(layout, {
                'icon-image': symbol.icon + '-15',
                'icon-size': symbol.iconsize / 10,

                'text-field': symbol.text,
                'text-size': symbol.textfont.size,
                'text-anchor': textOpts.anchor,
                'text-offset': textOpts.offset,
                'symbol-placement': symbol.placement,

                // TODO font family
                // 'text-font': symbol.textfont.family.split(', '),
            });

            Lib.extendFlat(paint, {
                'icon-color': opts.color,
                'text-color': symbol.textfont.color,
                'text-opacity': opts.opacity
            });
            break;
    }

    return { layout: layout, paint: paint };
}

function convertSourceOpts(opts) {
    var sourceType = opts.sourcetype;
    var source = opts.source;
    var sourceOpts = {type: sourceType};
    var field;

    if(sourceType === 'geojson') {
        field = 'data';
    } else if(sourceType === 'vector') {
        field = typeof source === 'string' ? 'url' : 'tiles';
    }

    sourceOpts[field] = source;
    return sourceOpts;
}

module.exports = function createMapboxLayer(mapbox, index, opts) {
    var mapboxLayer = new MapboxLayer(mapbox, index);

    mapboxLayer.update(opts);

    return mapboxLayer;
};

},{"../../lib":697,"./convert_text_opts":800}],803:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var defaultLine = _dereq_('../../components/color').defaultLine;
var domainAttrs = _dereq_('../domain').attributes;
var fontAttrs = _dereq_('../font_attributes');
var textposition = _dereq_('../../traces/scatter/attributes').textposition;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;

var fontAttr = fontAttrs({
    
});
fontAttr.family.dflt = 'Open Sans Regular, Arial Unicode MS Regular';

var attrs = module.exports = overrideAll({
    _arrayAttrRegexps: [Lib.counterRegex('mapbox', '.layers', true)],

    domain: domainAttrs({name: 'mapbox'}),

    accesstoken: {
        valType: 'string',
        noBlank: true,
        strict: true,
        
        
    },
    style: {
        valType: 'any',
        values: ['basic', 'streets', 'outdoors', 'light', 'dark', 'satellite', 'satellite-streets'],
        dflt: 'basic',
        
        
    },

    center: {
        lon: {
            valType: 'number',
            dflt: 0,
            
            
        },
        lat: {
            valType: 'number',
            dflt: 0,
            
            
        }
    },
    zoom: {
        valType: 'number',
        dflt: 1,
        
        
    },
    bearing: {
        valType: 'number',
        dflt: 0,
        
        
    },
    pitch: {
        valType: 'number',
        dflt: 0,
        
        
    },

    layers: templatedArray('layer', {
        visible: {
            valType: 'boolean',
            
            dflt: true,
            
        },
        sourcetype: {
            valType: 'enumerated',
            values: ['geojson', 'vector'],
            dflt: 'geojson',
            
            
        },

        source: {
            valType: 'any',
            
            
        },

        sourcelayer: {
            valType: 'string',
            dflt: '',
            
            
        },

        type: {
            valType: 'enumerated',
            values: ['circle', 'line', 'fill', 'symbol'],
            dflt: 'circle',
            
            
        },

        // attributes shared between all types
        below: {
            valType: 'string',
            dflt: '',
            
            
        },
        color: {
            valType: 'color',
            dflt: defaultLine,
            
            
        },
        opacity: {
            valType: 'number',
            min: 0,
            max: 1,
            dflt: 1,
            
            
        },
        minzoom: {
            valType: 'number',
            min: 0,
            max: 24,
            dflt: 0,
            
            
        },
        maxzoom: {
            valType: 'number',
            min: 0,
            max: 24,
            dflt: 24,
            
            
        },

        // type-specific style attributes
        circle: {
            radius: {
                valType: 'number',
                dflt: 15,
                
                
            }
        },

        line: {
            width: {
                valType: 'number',
                dflt: 2,
                
                
            },
            dash: {
                valType: 'data_array',
                
                
            }
        },

        fill: {
            outlinecolor: {
                valType: 'color',
                dflt: defaultLine,
                
                
            }
        },

        symbol: {
            icon: {
                valType: 'string',
                dflt: 'marker',
                
                
            },
            iconsize: {
                valType: 'number',
                dflt: 10,
                
                
            },
            text: {
                valType: 'string',
                dflt: '',
                
                
            },
            placement: {
                valType: 'enumerated',
                values: ['point', 'line', 'line-center'],
                dflt: 'point',
                
                
            },
            textfont: fontAttr,
            textposition: Lib.extendFlat({}, textposition, { arrayOk: false })
        }
    })
}, 'plot', 'from-root');

// set uirevision outside of overrideAll so it can be `editType: 'none'`
attrs.uirevision = {
    valType: 'any',
    
    editType: 'none',
    
};

},{"../../components/color":574,"../../lib":697,"../../plot_api/edit_types":728,"../../plot_api/plot_template":735,"../../traces/scatter/attributes":1048,"../domain":770,"../font_attributes":771}],804:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

var handleSubplotDefaults = _dereq_('../subplot_defaults');
var handleArrayContainerDefaults = _dereq_('../array_container_defaults');
var layoutAttributes = _dereq_('./layout_attributes');


module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
    handleSubplotDefaults(layoutIn, layoutOut, fullData, {
        type: 'mapbox',
        attributes: layoutAttributes,
        handleDefaults: handleDefaults,
        partition: 'y',
        accessToken: layoutOut._mapboxAccessToken
    });
};

function handleDefaults(containerIn, containerOut, coerce, opts) {
    coerce('accesstoken', opts.accessToken);
    coerce('style');
    coerce('center.lon');
    coerce('center.lat');
    coerce('zoom');
    coerce('bearing');
    coerce('pitch');

    handleArrayContainerDefaults(containerIn, containerOut, {
        name: 'layers',
        handleItemDefaults: handleLayerDefaults
    });

    // copy ref to input container to update 'center' and 'zoom' on map move
    containerOut._input = containerIn;
}

function handleLayerDefaults(layerIn, layerOut) {
    function coerce(attr, dflt) {
        return Lib.coerce(layerIn, layerOut, layoutAttributes.layers, attr, dflt);
    }

    var visible = coerce('visible');
    if(visible) {
        var sourceType = coerce('sourcetype');
        coerce('source');

        if(sourceType === 'vector') coerce('sourcelayer');

        // maybe add smart default based off GeoJSON geometry?
        var type = coerce('type');

        coerce('below');
        coerce('color');
        coerce('opacity');
        coerce('minzoom');
        coerce('maxzoom');

        if(type === 'circle') {
            coerce('circle.radius');
        }

        if(type === 'line') {
            coerce('line.width');
            coerce('line.dash');
        }

        if(type === 'fill') {
            coerce('fill.outlinecolor');
        }

        if(type === 'symbol') {
            coerce('symbol.icon');
            coerce('symbol.iconsize');

            coerce('symbol.text');
            Lib.coerceFont(coerce, 'symbol.textfont');
            coerce('symbol.textposition');
            coerce('symbol.placement');
        }
    }
}

},{"../../lib":697,"../array_container_defaults":741,"../subplot_defaults":821,"./layout_attributes":803}],805:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var mapboxgl = _dereq_('mapbox-gl');

var Fx = _dereq_('../../components/fx');
var Lib = _dereq_('../../lib');
var Registry = _dereq_('../../registry');
var dragElement = _dereq_('../../components/dragelement');
var prepSelect = _dereq_('../cartesian/select').prepSelect;
var selectOnClick = _dereq_('../cartesian/select').selectOnClick;
var constants = _dereq_('./constants');
var layoutAttributes = _dereq_('./layout_attributes');
var createMapboxLayer = _dereq_('./layers');

function Mapbox(opts) {
    this.id = opts.id;
    this.gd = opts.gd;
    this.container = opts.container;
    this.isStatic = opts.staticPlot;

    var fullLayout = opts.fullLayout;

    // unique id for this Mapbox instance
    this.uid = fullLayout._uid + '-' + this.id;

    // create framework on instantiation for a smoother first plot call
    this.div = null;
    this.xaxis = null;
    this.yaxis = null;
    this.createFramework(fullLayout);

    // state variables used to infer how and what to update
    this.map = null;
    this.accessToken = null;
    this.styleObj = null;
    this.traceHash = {};
    this.layerList = [];
}

var proto = Mapbox.prototype;

module.exports = function createMapbox(opts) {
    return new Mapbox(opts);
};

proto.plot = function(calcData, fullLayout, promises) {
    var self = this;
    var opts = fullLayout[self.id];

    // remove map and create a new map if access token has change
    if(self.map && (opts.accesstoken !== self.accessToken)) {
        self.map.remove();
        self.map = null;
        self.styleObj = null;
        self.traceHash = [];
        self.layerList = {};
    }

    var promise;

    if(!self.map) {
        promise = new Promise(function(resolve, reject) {
            self.createMap(calcData, fullLayout, resolve, reject);
        });
    } else {
        promise = new Promise(function(resolve, reject) {
            self.updateMap(calcData, fullLayout, resolve, reject);
        });
    }

    promises.push(promise);
};

proto.createMap = function(calcData, fullLayout, resolve, reject) {
    var self = this;
    var gd = self.gd;
    var opts = fullLayout[self.id];

    // store style id and URL or object
    var styleObj = self.styleObj = getStyleObj(opts.style);

    // store access token associated with this map
    self.accessToken = opts.accesstoken;

    // create the map!
    var map = self.map = new mapboxgl.Map({
        container: self.div,

        style: styleObj.style,
        center: convertCenter(opts.center),
        zoom: opts.zoom,
        bearing: opts.bearing,
        pitch: opts.pitch,

        interactive: !self.isStatic,
        preserveDrawingBuffer: self.isStatic,

        doubleClickZoom: false,
        boxZoom: false
    });

    // clear navigation container
    var className = constants.controlContainerClassName;
    var controlContainer = self.div.getElementsByClassName(className)[0];
    self.div.removeChild(controlContainer);

    // make sure canvas does not inherit left and top css
    map._canvas.style.left = '0px';
    map._canvas.style.top = '0px';

    self.rejectOnError(reject);

    map.once('load', function() {
        self.updateData(calcData);
        self.updateLayout(fullLayout);
        self.resolveOnRender(resolve);
    });

    if(self.isStatic) return;

    var wheeling = false;

    // keep track of pan / zoom in user layout and emit relayout event
    map.on('moveend', function(eventData) {
        if(!self.map) return;

        // 'moveend' gets triggered by map.setCenter, map.setZoom,
        // map.setBearing and map.setPitch.
        //
        // Here, we make sure that state updates amd 'plotly_relayout'
        // are triggered only when the 'moveend' originates from a
        // mouse target (filtering out API calls) to not
        // duplicate 'plotly_relayout' events.

        if(eventData.originalEvent || wheeling) {
            var optsNow = gd._fullLayout[self.id];
            Registry.call('_storeDirectGUIEdit', gd.layout, gd._fullLayout._preGUI, self.getViewEdits(optsNow));

            var viewNow = self.getView();
            optsNow._input.center = optsNow.center = viewNow.center;
            optsNow._input.zoom = optsNow.zoom = viewNow.zoom;
            optsNow._input.bearing = optsNow.bearing = viewNow.bearing;
            optsNow._input.pitch = optsNow.pitch = viewNow.pitch;

            gd.emit('plotly_relayout', self.getViewEdits(viewNow));
        }
        wheeling = false;
    });

    map.on('wheel', function() {
        wheeling = true;
    });

    map.on('mousemove', function(evt) {
        var bb = self.div.getBoundingClientRect();

        // some hackery to get Fx.hover to work
        evt.clientX = evt.point.x + bb.left;
        evt.clientY = evt.point.y + bb.top;

        evt.target.getBoundingClientRect = function() { return bb; };

        self.xaxis.p2c = function() { return evt.lngLat.lng; };
        self.yaxis.p2c = function() { return evt.lngLat.lat; };

        Fx.hover(gd, evt, self.id);
    });

    function unhover() {
        Fx.loneUnhover(fullLayout._toppaper);
    }

    map.on('dragstart', unhover);
    map.on('zoomstart', unhover);

    map.on('dblclick', function() {
        var optsNow = gd._fullLayout[self.id];
        Registry.call('_storeDirectGUIEdit', gd.layout, gd._fullLayout._preGUI, self.getViewEdits(optsNow));

        var viewInitial = self.viewInitial;
        map.setCenter(convertCenter(viewInitial.center));
        map.setZoom(viewInitial.zoom);
        map.setBearing(viewInitial.bearing);
        map.setPitch(viewInitial.pitch);

        var viewNow = self.getView();
        optsNow._input.center = optsNow.center = viewNow.center;
        optsNow._input.zoom = optsNow.zoom = viewNow.zoom;
        optsNow._input.bearing = optsNow.bearing = viewNow.bearing;
        optsNow._input.pitch = optsNow.pitch = viewNow.pitch;

        gd.emit('plotly_doubleclick', null);
        gd.emit('plotly_relayout', self.getViewEdits(viewNow));
    });

    // define event handlers on map creation, to keep one ref per map,
    // so that map.on / map.off in updateFx works as expected
    self.clearSelect = function() {
        gd._fullLayout._zoomlayer.selectAll('.select-outline').remove();
    };

    /**
     * Returns a click handler function that is supposed
     * to handle clicks in pan mode.
     */
    self.onClickInPanFn = function(dragOptions) {
        return function(evt) {
            var clickMode = gd._fullLayout.clickmode;

            if(clickMode.indexOf('select') > -1) {
                selectOnClick(evt.originalEvent, gd, [self.xaxis], [self.yaxis], self.id, dragOptions);
            }

            if(clickMode.indexOf('event') > -1) {
                // TODO: this does not support right-click. If we want to support it, we
                // would likely need to change mapbox to use dragElement instead of straight
                // mapbox event binding. Or perhaps better, make a simple wrapper with the
                // right mousedown, mousemove, and mouseup handlers just for a left/right click
                // pie would use this too.
                Fx.click(gd, evt.originalEvent);
            }
        };
    };
};

proto.updateMap = function(calcData, fullLayout, resolve, reject) {
    var self = this;
    var map = self.map;
    var opts = fullLayout[this.id];

    self.rejectOnError(reject);

    var styleObj = getStyleObj(opts.style);

    if(self.styleObj.id !== styleObj.id) {
        self.styleObj = styleObj;
        map.setStyle(styleObj.style);

        map.once('styledata', function() {
            // need to rebuild trace layers on reload
            // to avoid 'lost event' errors
            self.traceHash = {};
            self.updateData(calcData);
            self.updateLayout(fullLayout);
            self.resolveOnRender(resolve);
        });
    } else {
        self.updateData(calcData);
        self.updateLayout(fullLayout);
        self.resolveOnRender(resolve);
    }

    if(this.gd._context._scrollZoom.mapbox) {
        map.scrollZoom.enable();
    } else {
        map.scrollZoom.disable();
    }
};

proto.updateData = function(calcData) {
    var traceHash = this.traceHash;
    var traceObj, trace, i, j;

    // update or create trace objects
    for(i = 0; i < calcData.length; i++) {
        var calcTrace = calcData[i];

        trace = calcTrace[0].trace;
        traceObj = traceHash[trace.uid];

        if(traceObj) {
            traceObj.update(calcTrace);
        } else if(trace._module) {
            traceHash[trace.uid] = trace._module.plot(this, calcTrace);
        }
    }

    // remove empty trace objects
    var ids = Object.keys(traceHash);
    idLoop:
    for(i = 0; i < ids.length; i++) {
        var id = ids[i];

        for(j = 0; j < calcData.length; j++) {
            trace = calcData[j][0].trace;
            if(id === trace.uid) continue idLoop;
        }

        traceObj = traceHash[id];
        traceObj.dispose();
        delete traceHash[id];
    }
};

proto.updateLayout = function(fullLayout) {
    var map = this.map;
    var opts = fullLayout[this.id];

    map.setCenter(convertCenter(opts.center));
    map.setZoom(opts.zoom);
    map.setBearing(opts.bearing);
    map.setPitch(opts.pitch);

    this.updateLayers(fullLayout);
    this.updateFramework(fullLayout);
    this.updateFx(fullLayout);
    this.map.resize();
};

proto.resolveOnRender = function(resolve) {
    var map = this.map;

    map.on('render', function onRender() {
        if(map.loaded()) {
            map.off('render', onRender);
            // resolve at end of render loop
            setTimeout(resolve, 0);
        }
    });
};

proto.rejectOnError = function(reject) {
    var map = this.map;

    function handler() {
        reject(new Error(constants.mapOnErrorMsg));
    }

    map.once('error', handler);
    map.once('style.error', handler);
    map.once('source.error', handler);
    map.once('tile.error', handler);
    map.once('layer.error', handler);
};

proto.createFramework = function(fullLayout) {
    var self = this;

    var div = self.div = document.createElement('div');
    div.id = self.uid;
    div.style.position = 'absolute';
    self.container.appendChild(div);

    // create mock x/y axes for hover routine
    self.xaxis = {
        _id: 'x',
        c2p: function(v) { return self.project(v).x; }
    };
    self.yaxis = {
        _id: 'y',
        c2p: function(v) { return self.project(v).y; }
    };

    self.updateFramework(fullLayout);
};

proto.updateFx = function(fullLayout) {
    var self = this;
    var map = self.map;
    var gd = self.gd;

    if(self.isStatic) return;

    function invert(pxpy) {
        var obj = self.map.unproject(pxpy);
        return [obj.lng, obj.lat];
    }

    var dragMode = fullLayout.dragmode;
    var fillRangeItems;

    if(dragMode === 'select') {
        fillRangeItems = function(eventData, poly) {
            var ranges = eventData.range = {};
            ranges[self.id] = [
                invert([poly.xmin, poly.ymin]),
                invert([poly.xmax, poly.ymax])
            ];
        };
    } else {
        fillRangeItems = function(eventData, poly, pts) {
            var dataPts = eventData.lassoPoints = {};
            dataPts[self.id] = pts.filtered.map(invert);
        };
    }

    // Note: dragOptions is needed to be declared for all dragmodes because
    // it's the object that holds persistent selection state.
    // Merge old dragOptions with new to keep possibly initialized
    // persistent selection state.
    var oldDragOptions = self.dragOptions;
    self.dragOptions = Lib.extendDeep(oldDragOptions || {}, {
        element: self.div,
        gd: gd,
        plotinfo: {
            id: self.id,
            xaxis: self.xaxis,
            yaxis: self.yaxis,
            fillRangeItems: fillRangeItems
        },
        xaxes: [self.xaxis],
        yaxes: [self.yaxis],
        subplot: self.id
    });

    // Unregister the old handler before potentially registering
    // a new one. Otherwise multiple click handlers might
    // be registered resulting in unwanted behavior.
    map.off('click', self.onClickInPanHandler);
    if(dragMode === 'select' || dragMode === 'lasso') {
        map.dragPan.disable();
        map.on('zoomstart', self.clearSelect);

        self.dragOptions.prepFn = function(e, startX, startY) {
            prepSelect(e, startX, startY, self.dragOptions, dragMode);
        };

        dragElement.init(self.dragOptions);
    } else {
        map.dragPan.enable();
        map.off('zoomstart', self.clearSelect);
        self.div.onmousedown = null;

        // TODO: this does not support right-click. If we want to support it, we
        // would likely need to change mapbox to use dragElement instead of straight
        // mapbox event binding. Or perhaps better, make a simple wrapper with the
        // right mousedown, mousemove, and mouseup handlers just for a left/right click
        // pie would use this too.
        self.onClickInPanHandler = self.onClickInPanFn(self.dragOptions);
        map.on('click', self.onClickInPanHandler);
    }
};

proto.updateFramework = function(fullLayout) {
    var domain = fullLayout[this.id].domain;
    var size = fullLayout._size;

    var style = this.div.style;
    style.width = size.w * (domain.x[1] - domain.x[0]) + 'px';
    style.height = size.h * (domain.y[1] - domain.y[0]) + 'px';
    style.left = size.l + domain.x[0] * size.w + 'px';
    style.top = size.t + (1 - domain.y[1]) * size.h + 'px';

    this.xaxis._offset = size.l + domain.x[0] * size.w;
    this.xaxis._length = size.w * (domain.x[1] - domain.x[0]);

    this.yaxis._offset = size.t + (1 - domain.y[1]) * size.h;
    this.yaxis._length = size.h * (domain.y[1] - domain.y[0]);
};

proto.updateLayers = function(fullLayout) {
    var opts = fullLayout[this.id];
    var layers = opts.layers;
    var layerList = this.layerList;
    var i;

    // if the layer arrays don't match,
    // don't try to be smart,
    // delete them all, and start all over.

    if(layers.length !== layerList.length) {
        for(i = 0; i < layerList.length; i++) {
            layerList[i].dispose();
        }

        layerList = this.layerList = [];

        for(i = 0; i < layers.length; i++) {
            layerList.push(createMapboxLayer(this, i, layers[i]));
        }
    } else {
        for(i = 0; i < layers.length; i++) {
            layerList[i].update(layers[i]);
        }
    }
};

proto.destroy = function() {
    if(this.map) {
        this.map.remove();
        this.map = null;
        this.container.removeChild(this.div);
    }
};

proto.toImage = function() {
    this.map.stop();
    return this.map.getCanvas().toDataURL();
};

// convenience wrapper to create set multiple layer
// 'layout' or 'paint options at once.
proto.setOptions = function(id, methodName, opts) {
    for(var k in opts) {
        this.map[methodName](id, k, opts[k]);
    }
};

// convenience method to project a [lon, lat] array to pixel coords
proto.project = function(v) {
    return this.map.project(new mapboxgl.LngLat(v[0], v[1]));
};

// get map's current view values in plotly.js notation
proto.getView = function() {
    var map = this.map;
    var mapCenter = map.getCenter();
    var center = { lon: mapCenter.lng, lat: mapCenter.lat };

    return {
        center: center,
        zoom: map.getZoom(),
        bearing: map.getBearing(),
        pitch: map.getPitch()
    };
};

proto.getViewEdits = function(cont) {
    var id = this.id;
    var keys = ['center', 'zoom', 'bearing', 'pitch'];
    var obj = {};

    for(var i = 0; i < keys.length; i++) {
        var k = keys[i];
        obj[id + '.' + k] = cont[k];
    }

    return obj;
};

function getStyleObj(val) {
    var styleValues = layoutAttributes.style.values;
    var styleDflt = layoutAttributes.style.dflt;
    var styleObj = {};

    if(Lib.isPlainObject(val)) {
        styleObj.id = val.id;
        styleObj.style = val;
    } else if(typeof val === 'string') {
        styleObj.id = val;
        styleObj.style = (styleValues.indexOf(val) !== -1) ?
             convertStyleVal(val) :
             val;
    } else {
        styleObj.id = styleDflt;
        styleObj.style = convertStyleVal(styleDflt);
    }

    styleObj.transition = {duration: 0, delay: 0};

    return styleObj;
}

// if style is part of the 'official' mapbox values, add URL prefix and suffix
function convertStyleVal(val) {
    return constants.styleUrlPrefix + val + '-' + constants.styleUrlSuffix;
}

function convertCenter(center) {
    return [center.lon, center.lat];
}

},{"../../components/dragelement":592,"../../components/fx":613,"../../lib":697,"../../registry":826,"../cartesian/select":762,"./constants":799,"./layers":802,"./layout_attributes":803,"mapbox-gl":415}],806:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * Creates a set of padding attributes.
 *
 * @param {object} opts
 *   @param {string} editType:
 *     the editType for all pieces of this padding definition
 *
 * @return {object} attributes object containing {t, r, b, l} as specified
 */
module.exports = function(opts) {
    var editType = opts.editType;
    return {
        t: {
            valType: 'number',
            dflt: 0,
            
            editType: editType,
            
        },
        r: {
            valType: 'number',
            dflt: 0,
            
            editType: editType,
            
        },
        b: {
            valType: 'number',
            dflt: 0,
            
            editType: editType,
            
        },
        l: {
            valType: 'number',
            dflt: 0,
            
            editType: editType,
            
        },
        editType: editType
    };
};

},{}],807:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');

var Registry = _dereq_('../registry');
var PlotSchema = _dereq_('../plot_api/plot_schema');
var Template = _dereq_('../plot_api/plot_template');
var Lib = _dereq_('../lib');
var Color = _dereq_('../components/color');
var BADNUM = _dereq_('../constants/numerical').BADNUM;

var axisIDs = _dereq_('../plots/cartesian/axis_ids');

var animationAttrs = _dereq_('./animation_attributes');
var frameAttrs = _dereq_('./frame_attributes');

var relinkPrivateKeys = Lib.relinkPrivateKeys;
var _ = Lib._;

var plots = module.exports = {};

// Expose registry methods on Plots for backward-compatibility
Lib.extendFlat(plots, Registry);

plots.attributes = _dereq_('./attributes');
plots.attributes.type.values = plots.allTypes;
plots.fontAttrs = _dereq_('./font_attributes');
plots.layoutAttributes = _dereq_('./layout_attributes');

// TODO make this a plot attribute?
plots.fontWeight = 'normal';

var transformsRegistry = plots.transformsRegistry;

var commandModule = _dereq_('./command');
plots.executeAPICommand = commandModule.executeAPICommand;
plots.computeAPICommandBindings = commandModule.computeAPICommandBindings;
plots.manageCommandObserver = commandModule.manageCommandObserver;
plots.hasSimpleAPICommandBindings = commandModule.hasSimpleAPICommandBindings;

// in some cases the browser doesn't seem to know how big
// the text is at first, so it needs to draw it,
// then wait a little, then draw it again
plots.redrawText = function(gd) {
    gd = Lib.getGraphDiv(gd);

    // do not work if polar is present
    if((gd.data && gd.data[0] && gd.data[0].r)) return;

    return new Promise(function(resolve) {
        setTimeout(function() {
            Registry.getComponentMethod('annotations', 'draw')(gd);
            Registry.getComponentMethod('legend', 'draw')(gd);

            (gd.calcdata || []).forEach(function(d) {
                if(d[0] && d[0].t && d[0].t.cb) d[0].t.cb();
            });

            resolve(plots.previousPromises(gd));
        }, 300);
    });
};

// resize plot about the container size
plots.resize = function(gd) {
    gd = Lib.getGraphDiv(gd);

    return new Promise(function(resolve, reject) {

        function isHidden(gd) {
            var display = window.getComputedStyle(gd).display;
            return !display || display === 'none';
        }

        if(!gd || isHidden(gd)) {
            reject(new Error('Resize must be passed a displayed plot div element.'));
        }

        if(gd._redrawTimer) clearTimeout(gd._redrawTimer);

        gd._redrawTimer = setTimeout(function() {
            // return if there is nothing to resize or is hidden
            if(!gd.layout || (gd.layout.width && gd.layout.height) || isHidden(gd)) {
                resolve(gd);
                return;
            }

            delete gd.layout.width;
            delete gd.layout.height;

            // autosizing doesn't count as a change that needs saving
            var oldchanged = gd.changed;

            // nor should it be included in the undo queue
            gd.autoplay = true;

            Registry.call('relayout', gd, {autosize: true}).then(function() {
                gd.changed = oldchanged;
                resolve(gd);
            });
        }, 100);
    });
};


// for use in Lib.syncOrAsync, check if there are any
// pending promises in this plot and wait for them
plots.previousPromises = function(gd) {
    if((gd._promises || []).length) {
        return Promise.all(gd._promises)
            .then(function() { gd._promises = []; });
    }
};

/**
 * Adds the 'Edit chart' link.
 * Note that now Plotly.plot() calls this so it can regenerate whenever it replots
 *
 * Add source links to your graph inside the 'showSources' config argument.
 */
plots.addLinks = function(gd) {
    // Do not do anything if showLink and showSources are not set to true in config
    if(!gd._context.showLink && !gd._context.showSources) return;

    var fullLayout = gd._fullLayout;

    var linkContainer = Lib.ensureSingle(fullLayout._paper, 'text', 'js-plot-link-container', function(s) {
        s.style({
            'font-family': '"Open Sans", Arial, sans-serif',
            'font-size': '12px',
            'fill': Color.defaultLine,
            'pointer-events': 'all'
        })
        .each(function() {
            var links = d3.select(this);
            links.append('tspan').classed('js-link-to-tool', true);
            links.append('tspan').classed('js-link-spacer', true);
            links.append('tspan').classed('js-sourcelinks', true);
        });
    });

    // The text node inside svg
    var text = linkContainer.node();
    var attrs = {y: fullLayout._paper.attr('height') - 9};

    // If text's width is bigger than the layout
    // Check that text is a child node or document.body
    // because otherwise IE/Edge might throw an exception
    // when calling getComputedTextLength().
    // Apparently offsetParent is null for invisibles.
    if(document.body.contains(text) && text.getComputedTextLength() >= (fullLayout.width - 20)) {
        // Align the text at the left
        attrs['text-anchor'] = 'start';
        attrs.x = 5;
    }
    else {
        // Align the text at the right
        attrs['text-anchor'] = 'end';
        attrs.x = fullLayout._paper.attr('width') - 7;
    }

    linkContainer.attr(attrs);

    var toolspan = linkContainer.select('.js-link-to-tool');
    var spacespan = linkContainer.select('.js-link-spacer');
    var sourcespan = linkContainer.select('.js-sourcelinks');

    if(gd._context.showSources) gd._context.showSources(gd);

    // 'view in plotly' link for embedded plots
    if(gd._context.showLink) positionPlayWithData(gd, toolspan);

    // separator if we have both sources and tool link
    spacespan.text((toolspan.text() && sourcespan.text()) ? ' - ' : '');
};

// note that now this function is only adding the brand in
// iframes and 3rd-party apps
function positionPlayWithData(gd, container) {
    container.text('');
    var link = container.append('a')
        .attr({
            'xlink:xlink:href': '#',
            'class': 'link--impt link--embedview',
            'font-weight': 'bold'
        })
        .text(gd._context.linkText + ' ' + String.fromCharCode(187));

    if(gd._context.sendData) {
        link.on('click', function() {
            plots.sendDataToCloud(gd);
        });
    }
    else {
        var path = window.location.pathname.split('/');
        var query = window.location.search;
        link.attr({
            'xlink:xlink:show': 'new',
            'xlink:xlink:href': '/' + path[2].split('.')[0] + '/' + path[1] + query
        });
    }
}

plots.sendDataToCloud = function(gd) {
    gd.emit('plotly_beforeexport');

    var baseUrl = (window.PLOTLYENV || {}).BASE_URL || gd._context.plotlyServerURL;

    var hiddenformDiv = d3.select(gd)
        .append('div')
        .attr('id', 'hiddenform')
        .style('display', 'none');

    var hiddenform = hiddenformDiv
        .append('form')
        .attr({
            action: baseUrl + '/external',
            method: 'post',
            target: '_blank'
        });

    var hiddenformInput = hiddenform
        .append('input')
        .attr({
            type: 'text',
            name: 'data'
        });

    hiddenformInput.node().value = plots.graphJson(gd, false, 'keepdata');
    hiddenform.node().submit();
    hiddenformDiv.remove();

    gd.emit('plotly_afterexport');
    return false;
};

var d3FormatKeys = [
    'days', 'shortDays', 'months', 'shortMonths', 'periods',
    'dateTime', 'date', 'time',
    'decimal', 'thousands', 'grouping', 'currency'
];

var extraFormatKeys = [
    'year', 'month', 'dayMonth', 'dayMonthYear'
];

/*
 * Fill in default values
 * @param {DOM element} gd
 * @param {object} opts
 * @param {boolean} opts.skipUpdateCalc: normally if the existing gd.calcdata looks
 *   compatible with the new gd._fullData we finish by linking the new _fullData traces
 *   to the old gd.calcdata, so it's correctly set if we're not going to recalc. But also,
 *   if there are calcTransforms on the trace, we first remap data arrays from the old full
 *   trace into the new one. Use skipUpdateCalc to defer this (needed by Plotly.react)
 *
 * gd.data, gd.layout:
 *   are precisely what the user specified (except as modified by cleanData/cleanLayout),
 *   these fields shouldn't be modified (except for filling in some auto values)
 *   nor used directly after the supply defaults step.
 *
 * gd._fullData, gd._fullLayout:
 *   are complete descriptions of how to draw the plot,
 *   use these fields in all required computations.
 *
 * gd._fullLayout._modules
 *   is a list of all the trace modules required to draw the plot.
 *
 * gd._fullLayout._visibleModules
 *   subset of _modules, a list of modules corresponding to visible:true traces.
 *
 * gd._fullLayout._basePlotModules
 *   is a list of all the plot modules required to draw the plot.
 *
 * gd._fullLayout._transformModules
 *   is a list of all the transform modules invoked.
 *
 */
plots.supplyDefaults = function(gd, opts) {
    var skipUpdateCalc = opts && opts.skipUpdateCalc;
    var oldFullLayout = gd._fullLayout || {};

    if(oldFullLayout._skipDefaults) {
        delete oldFullLayout._skipDefaults;
        return;
    }

    var newFullLayout = gd._fullLayout = {};
    var newLayout = gd.layout || {};

    var oldFullData = gd._fullData || [];
    var newFullData = gd._fullData = [];
    var newData = gd.data || [];

    var oldCalcdata = gd.calcdata || [];

    var context = gd._context || {};

    var i;

    // Create all the storage space for frames, but only if doesn't already exist
    if(!gd._transitionData) plots.createTransitionData(gd);

    // So we only need to do this once (and since we have gd here)
    // get the translated placeholder titles.
    // These ones get used as default values so need to be known at supplyDefaults
    // others keep their blank defaults but render the placeholder as desired later
    // TODO: make these work the same way, only inserting the placeholder text at draw time?
    // The challenge is that this has slightly different behavior right now in editable mode:
    // using the placeholder as default makes this text permanently (but lightly) visible,
    // but explicit '' for these titles gives you a placeholder that's hidden until you mouse
    // over it - so you're not distracted by it if you really don't want a title, but if you do
    // and you're new to plotly you may not be able to find it.
    // When editable=false the two behave the same, no title is drawn.
    newFullLayout._dfltTitle = {
        plot: _(gd, 'Click to enter Plot title'),
        x: _(gd, 'Click to enter X axis title'),
        y: _(gd, 'Click to enter Y axis title'),
        colorbar: _(gd, 'Click to enter Colorscale title'),
        annotation: _(gd, 'new text')
    };
    newFullLayout._traceWord = _(gd, 'trace');

    var formatObj = getFormatObj(gd, d3FormatKeys);

    // stash the token from context so mapbox subplots can use it as default
    newFullLayout._mapboxAccessToken = context.mapboxAccessToken;

    // first fill in what we can of layout without looking at data
    // because fullData needs a few things from layout
    if(oldFullLayout._initialAutoSizeIsDone) {

        // coerce the updated layout while preserving width and height
        var oldWidth = oldFullLayout.width;
        var oldHeight = oldFullLayout.height;

        plots.supplyLayoutGlobalDefaults(newLayout, newFullLayout, formatObj);

        if(!newLayout.width) newFullLayout.width = oldWidth;
        if(!newLayout.height) newFullLayout.height = oldHeight;
        plots.sanitizeMargins(newFullLayout);
    }
    else {

        // coerce the updated layout and autosize if needed
        plots.supplyLayoutGlobalDefaults(newLayout, newFullLayout, formatObj);

        var missingWidthOrHeight = (!newLayout.width || !newLayout.height);
        var autosize = newFullLayout.autosize;
        var autosizable = context.autosizable;
        var initialAutoSize = missingWidthOrHeight && (autosize || autosizable);

        if(initialAutoSize) plots.plotAutoSize(gd, newLayout, newFullLayout);
        else if(missingWidthOrHeight) plots.sanitizeMargins(newFullLayout);

        // for backwards-compatibility with Plotly v1.x.x
        if(!autosize && missingWidthOrHeight) {
            newLayout.width = newFullLayout.width;
            newLayout.height = newFullLayout.height;
        }
    }

    newFullLayout._d3locale = getFormatter(formatObj, newFullLayout.separators);
    newFullLayout._extraFormat = getFormatObj(gd, extraFormatKeys);

    newFullLayout._initialAutoSizeIsDone = true;

    // keep track of how many traces are inputted
    newFullLayout._dataLength = newData.length;

    // clear the lists of trace and baseplot modules, and subplots
    newFullLayout._modules = [];
    newFullLayout._visibleModules = [];
    newFullLayout._basePlotModules = [];
    var subplots = newFullLayout._subplots = emptySubplotLists();

    // initialize axis and subplot hash objects for splom-generated grids
    var splomAxes = newFullLayout._splomAxes = {x: {}, y: {}};
    var splomSubplots = newFullLayout._splomSubplots = {};
    // initialize splom grid defaults
    newFullLayout._splomGridDflt = {};

    // for stacked area traces to share config across traces
    newFullLayout._scatterStackOpts = {};
    // for the first scatter trace on each subplot (so it knows tonext->tozero)
    newFullLayout._firstScatter = {};
    // for grouped bar/box/violin trace to share config across traces
    newFullLayout._alignmentOpts = {};

    // for traces to request a default rangeslider on their x axes
    // eg set `_requestRangeslider.x2 = true` for xaxis2
    newFullLayout._requestRangeslider = {};

    // pull uids from old data to use as new defaults
    newFullLayout._traceUids = getTraceUids(oldFullData, newData);

    // then do the data
    newFullLayout._globalTransforms = (gd._context || {}).globalTransforms;
    plots.supplyDataDefaults(newData, newFullData, newLayout, newFullLayout);

    // redo grid size defaults with info about splom x/y axes,
    // and fill in generated cartesian axes and subplots
    var splomXa = Object.keys(splomAxes.x);
    var splomYa = Object.keys(splomAxes.y);
    if(splomXa.length > 1 && splomYa.length > 1) {
        Registry.getComponentMethod('grid', 'sizeDefaults')(newLayout, newFullLayout);

        for(i = 0; i < splomXa.length; i++) {
            Lib.pushUnique(subplots.xaxis, splomXa[i]);
        }
        for(i = 0; i < splomYa.length; i++) {
            Lib.pushUnique(subplots.yaxis, splomYa[i]);
        }
        for(var k in splomSubplots) {
            Lib.pushUnique(subplots.cartesian, k);
        }
    }

    // attach helper method to check whether a plot type is present on graph
    newFullLayout._has = plots._hasPlotType.bind(newFullLayout);

    if(oldFullData.length === newFullData.length) {
        for(i = 0; i < newFullData.length; i++) {
            relinkPrivateKeys(newFullData[i], oldFullData[i]);
        }
    }

    // finally, fill in the pieces of layout that may need to look at data
    plots.supplyLayoutModuleDefaults(newLayout, newFullLayout, newFullData, gd._transitionData);

    // Special cases that introduce interactions between traces.
    // This is after relinkPrivateKeys so we can use those in crossTraceDefaults
    // and after layout module defaults, so we can use eg barmode
    var _modules = newFullLayout._visibleModules;
    var crossTraceDefaultsFuncs = [];
    for(i = 0; i < _modules.length; i++) {
        var funci = _modules[i].crossTraceDefaults;
        // some trace types share crossTraceDefaults (ie histogram2d, histogram2dcontour)
        if(funci) Lib.pushUnique(crossTraceDefaultsFuncs, funci);
    }
    for(i = 0; i < crossTraceDefaultsFuncs.length; i++) {
        crossTraceDefaultsFuncs[i](newFullData, newFullLayout);
    }
    Registry.getComponentMethod('colorscale', 'crossTraceDefaults')(newFullData, newFullLayout);

    // turn on flag to optimize large splom-only graphs
    // mostly by omitting SVG layers during Cartesian.drawFramework
    newFullLayout._hasOnlyLargeSploms = (
        newFullLayout._basePlotModules.length === 1 &&
        newFullLayout._basePlotModules[0].name === 'splom' &&
        splomXa.length > 15 &&
        splomYa.length > 15 &&
        newFullLayout.shapes.length === 0 &&
        newFullLayout.images.length === 0
    );

    // TODO remove in v2.0.0
    // add has-plot-type refs to fullLayout for backward compatibility
    newFullLayout._hasCartesian = newFullLayout._has('cartesian');
    newFullLayout._hasGeo = newFullLayout._has('geo');
    newFullLayout._hasGL3D = newFullLayout._has('gl3d');
    newFullLayout._hasGL2D = newFullLayout._has('gl2d');
    newFullLayout._hasTernary = newFullLayout._has('ternary');
    newFullLayout._hasPie = newFullLayout._has('pie');

    // relink / initialize subplot axis objects
    plots.linkSubplots(newFullData, newFullLayout, oldFullData, oldFullLayout);

    // clean subplots and other artifacts from previous plot calls
    plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout);

    // relink functions and _ attributes to promote consistency between plots
    relinkPrivateKeys(newFullLayout, oldFullLayout);

    // For persisting GUI-driven changes in layout
    // _preGUI and _tracePreGUI were already copied over in relinkPrivateKeys
    if(!newFullLayout._preGUI) newFullLayout._preGUI = {};
    // track trace GUI changes by uid rather than by trace index
    if(!newFullLayout._tracePreGUI) newFullLayout._tracePreGUI = {};
    var tracePreGUI = newFullLayout._tracePreGUI;
    var uids = {};
    var uid;
    for(uid in tracePreGUI) uids[uid] = 'old';
    for(i = 0; i < newFullData.length; i++) {
        uid = newFullData[i]._fullInput.uid;
        if(!uids[uid]) tracePreGUI[uid] = {};
        uids[uid] = 'new';
    }
    for(uid in uids) {
        if(uids[uid] === 'old') delete tracePreGUI[uid];
    }

    // set up containers for margin calculations
    initMargins(newFullLayout);

    // collect and do some initial calculations for rangesliders
    Registry.getComponentMethod('rangeslider', 'makeData')(newFullLayout);

    // update object references in calcdata
    if(!skipUpdateCalc && oldCalcdata.length === newFullData.length) {
        plots.supplyDefaultsUpdateCalc(oldCalcdata, newFullData);
    }
};

plots.supplyDefaultsUpdateCalc = function(oldCalcdata, newFullData) {
    for(var i = 0; i < newFullData.length; i++) {
        var newTrace = newFullData[i];
        var cd0 = (oldCalcdata[i] || [])[0];
        if(cd0 && cd0.trace) {
            var oldTrace = cd0.trace;
            if(oldTrace._hasCalcTransform) {
                var arrayAttrs = oldTrace._arrayAttrs;
                var j, astr, oldArrayVal;

                for(j = 0; j < arrayAttrs.length; j++) {
                    astr = arrayAttrs[j];
                    oldArrayVal = Lib.nestedProperty(oldTrace, astr).get().slice();
                    Lib.nestedProperty(newTrace, astr).set(oldArrayVal);
                }
            }
            cd0.trace = newTrace;
        }
    }
};

/**
 * Create a list of uid strings satisfying (in this order of importance):
 * 1. all unique, all strings
 * 2. matches input uids if provided
 * 3. matches previous data uids
 */
function getTraceUids(oldFullData, newData) {
    var len = newData.length;
    var oldFullInput = [];
    var i, prevFullInput;
    for(i = 0; i < oldFullData.length; i++) {
        var thisFullInput = oldFullData[i]._fullInput;
        if(thisFullInput !== prevFullInput) oldFullInput.push(thisFullInput);
        prevFullInput = thisFullInput;
    }
    var oldLen = oldFullInput.length;
    var out = new Array(len);
    var seenUids = {};

    function setUid(uid, i) {
        out[i] = uid;
        seenUids[uid] = 1;
    }

    function tryUid(uid, i) {
        if(uid && typeof uid === 'string' && !seenUids[uid]) {
            setUid(uid, i);
            return true;
        }
    }

    for(i = 0; i < len; i++) {
        var newUid = newData[i].uid;
        if(typeof newUid === 'number') newUid = String(newUid);

        if(tryUid(newUid, i)) continue;
        if(i < oldLen && tryUid(oldFullInput[i].uid, i)) continue;
        setUid(Lib.randstr(seenUids), i);
    }

    return out;
}

/**
 * Make a container for collecting subplots we need to display.
 *
 * Finds all subplot types we need to enumerate once and caches it,
 * but makes a new output object each time.
 * Single-trace subplots (which have no `id`) such as pie, table, etc
 * do not need to be collected because we just draw all visible traces.
 */
function emptySubplotLists() {
    var collectableSubplotTypes = Registry.collectableSubplotTypes;
    var out = {};
    var i, j;

    if(!collectableSubplotTypes) {
        collectableSubplotTypes = [];

        var subplotsRegistry = Registry.subplotsRegistry;

        for(var subplotType in subplotsRegistry) {
            var subplotModule = subplotsRegistry[subplotType];
            var subplotAttr = subplotModule.attr;

            if(subplotAttr) {
                collectableSubplotTypes.push(subplotType);

                // special case, currently just for cartesian:
                // we need to enumerate axes, not just subplots
                if(Array.isArray(subplotAttr)) {
                    for(j = 0; j < subplotAttr.length; j++) {
                        Lib.pushUnique(collectableSubplotTypes, subplotAttr[j]);
                    }
                }
            }
        }
    }

    for(i = 0; i < collectableSubplotTypes.length; i++) {
        out[collectableSubplotTypes[i]] = [];
    }
    return out;
}

/**
 * getFormatObj: use _context to get the format object from locale.
 * Used to get d3.locale argument object and extraFormat argument object
 *
 * Regarding d3.locale argument :
 * decimal and thousands can be overridden later by layout.separators
 * grouping and currency are not presently used by our automatic number
 * formatting system but can be used by custom formats.
 *
 * @returns {object} d3.locale format object
 */
function getFormatObj(gd, formatKeys) {
    var locale = gd._context.locale;
    if(!locale) locale === 'en-US';

    var formatDone = false;
    var formatObj = {};

    function includeFormat(newFormat) {
        var formatFinished = true;
        for(var i = 0; i < formatKeys.length; i++) {
            var formatKey = formatKeys[i];
            if(!formatObj[formatKey]) {
                if(newFormat[formatKey]) {
                    formatObj[formatKey] = newFormat[formatKey];
                }
                else formatFinished = false;
            }
        }
        if(formatFinished) formatDone = true;
    }

    // same as localize, look for format parts in each format spec in the chain
    for(var i = 0; i < 2; i++) {
        var locales = gd._context.locales;
        for(var j = 0; j < 2; j++) {
            var formatj = (locales[locale] || {}).format;
            if(formatj) {
                includeFormat(formatj);
                if(formatDone) break;
            }
            locales = Registry.localeRegistry;
        }

        var baseLocale = locale.split('-')[0];
        if(formatDone || baseLocale === locale) break;
        locale = baseLocale;
    }

    // lastly pick out defaults from english (non-US, as DMY is so much more common)
    if(!formatDone) includeFormat(Registry.localeRegistry.en.format);

    return formatObj;
}

/**
 * getFormatter: combine the final separators with the locale formatting object
 * we pulled earlier to generate number and time formatters
 * TODO: remove separators in v2, only use locale, so we don't need this step?
 *
 * @param {object} formatObj: d3.locale format object
 * @param {string} separators: length-2 string to override decimal and thousands
 *   separators in number formatting
 *
 * @returns {object} {numberFormat, timeFormat} d3 formatter factory functions
 *   for numbers and time
 */
function getFormatter(formatObj, separators) {
    formatObj.decimal = separators.charAt(0);
    formatObj.thousands = separators.charAt(1);

    return d3.locale(formatObj);
}

// Create storage for all of the data related to frames and transitions:
plots.createTransitionData = function(gd) {
    // Set up the default keyframe if it doesn't exist:
    if(!gd._transitionData) {
        gd._transitionData = {};
    }

    if(!gd._transitionData._frames) {
        gd._transitionData._frames = [];
    }

    if(!gd._transitionData._frameHash) {
        gd._transitionData._frameHash = {};
    }

    if(!gd._transitionData._counter) {
        gd._transitionData._counter = 0;
    }

    if(!gd._transitionData._interruptCallbacks) {
        gd._transitionData._interruptCallbacks = [];
    }
};

// helper function to be bound to fullLayout to check
// whether a certain plot type is present on plot
// or trace has a category
plots._hasPlotType = function(category) {
    var i;

    // check base plot modules
    var basePlotModules = this._basePlotModules || [];
    for(i = 0; i < basePlotModules.length; i++) {
        if(basePlotModules[i].name === category) return true;
    }

    // check trace modules (including non-visible:true)
    var modules = this._modules || [];
    for(i = 0; i < modules.length; i++) {
        var name = modules[i].name;
        if(name === category) return true;
        // N.B. this is modules[i] along with 'categories' as a hash object
        var _module = Registry.modules[name];
        if(_module && _module.categories[category]) return true;
    }

    return false;
};

plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var i, j;

    var basePlotModules = oldFullLayout._basePlotModules || [];
    for(i = 0; i < basePlotModules.length; i++) {
        var _module = basePlotModules[i];

        if(_module.clean) {
            _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout);
        }
    }

    var hadGl = oldFullLayout._has && oldFullLayout._has('gl');
    var hasGl = newFullLayout._has && newFullLayout._has('gl');

    if(hadGl && !hasGl) {
        if(oldFullLayout._glcontainer !== undefined) {
            oldFullLayout._glcontainer.selectAll('.gl-canvas').remove();
            oldFullLayout._glcontainer.selectAll('.no-webgl').remove();
            oldFullLayout._glcanvas = null;
        }
    }

    var hasInfoLayer = !!oldFullLayout._infolayer;

    oldLoop:
    for(i = 0; i < oldFullData.length; i++) {
        var oldTrace = oldFullData[i];
        var oldUid = oldTrace.uid;

        for(j = 0; j < newFullData.length; j++) {
            var newTrace = newFullData[j];

            if(oldUid === newTrace.uid) continue oldLoop;
        }

        // clean old colorbars
        if(hasInfoLayer) {
            oldFullLayout._infolayer.select('.cb' + oldUid).remove();
        }
    }

    if(oldFullLayout._zoomlayer) {
        oldFullLayout._zoomlayer.selectAll('.select-outline').remove();
    }
};

plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var i, j;

    var oldSubplots = oldFullLayout._plots || {};
    var newSubplots = newFullLayout._plots = {};
    var newSubplotList = newFullLayout._subplots;

    var mockGd = {
        _fullData: newFullData,
        _fullLayout: newFullLayout
    };

    var ids = newSubplotList.cartesian.concat(newSubplotList.gl2d || []);

    for(i = 0; i < ids.length; i++) {
        var id = ids[i];
        var oldSubplot = oldSubplots[id];
        var xaxis = axisIDs.getFromId(mockGd, id, 'x');
        var yaxis = axisIDs.getFromId(mockGd, id, 'y');
        var plotinfo;

        // link or create subplot object
        if(oldSubplot) {
            plotinfo = newSubplots[id] = oldSubplot;
        } else {
            plotinfo = newSubplots[id] = {};
            plotinfo.id = id;
        }

        // add these axis ids to each others' subplot lists
        xaxis._counterAxes.push(yaxis._id);
        yaxis._counterAxes.push(xaxis._id);
        xaxis._subplotsWith.push(id);
        yaxis._subplotsWith.push(id);

        // update x and y axis layout object refs
        plotinfo.xaxis = xaxis;
        plotinfo.yaxis = yaxis;

        // By default, we clip at the subplot level,
        // but if one trace on a given subplot has *cliponaxis* set to false,
        // we need to clip at the trace module layer level;
        // find this out here, once of for all.
        plotinfo._hasClipOnAxisFalse = false;

        for(j = 0; j < newFullData.length; j++) {
            var trace = newFullData[j];

            if(
                trace.xaxis === plotinfo.xaxis._id &&
                trace.yaxis === plotinfo.yaxis._id &&
                trace.cliponaxis === false
            ) {
                plotinfo._hasClipOnAxisFalse = true;
                break;
            }
        }
    }

    // while we're at it, link overlaying axes to their main axes and
    // anchored axes to the axes they're anchored to
    var axList = axisIDs.list(mockGd, null, true);
    var ax;
    for(i = 0; i < axList.length; i++) {
        ax = axList[i];
        var mainAx = null;

        if(ax.overlaying) {
            mainAx = axisIDs.getFromId(mockGd, ax.overlaying);

            // you cannot overlay an axis that's already overlaying another
            if(mainAx && mainAx.overlaying) {
                ax.overlaying = false;
                mainAx = null;
            }
        }
        ax._mainAxis = mainAx || ax;

        /*
         * For now force overlays to overlay completely... so they
         * can drag together correctly and share backgrounds.
         * Later perhaps we make separate axis domain and
         * tick/line domain or something, so they can still share
         * the (possibly larger) dragger and background but don't
         * have to both be drawn over that whole domain
         */
        if(mainAx) ax.domain = mainAx.domain.slice();

        ax._anchorAxis = ax.anchor === 'free' ?
            null :
            axisIDs.getFromId(mockGd, ax.anchor);
    }

    // finally, we can find the main subplot for each axis
    // (on which the ticks & labels are drawn)
    for(i = 0; i < axList.length; i++) {
        ax = axList[i];
        ax._counterAxes.sort(axisIDs.idSort);
        ax._subplotsWith.sort(Lib.subplotSort);
        ax._mainSubplot = findMainSubplot(ax, newFullLayout);
    }
};

function findMainSubplot(ax, fullLayout) {
    var mockGd = {_fullLayout: fullLayout};

    var isX = ax._id.charAt(0) === 'x';
    var anchorAx = ax._mainAxis._anchorAxis;
    var mainSubplotID = '';
    var nextBestMainSubplotID = '';
    var anchorID = '';

    // First try the main ID with the anchor
    if(anchorAx) {
        anchorID = anchorAx._mainAxis._id;
        mainSubplotID = isX ? (ax._id + anchorID) : (anchorID + ax._id);
    }

    // Then look for a subplot with the counteraxis overlaying the anchor
    // If that fails just use the first subplot including this axis
    if(!mainSubplotID || !fullLayout._plots[mainSubplotID]) {
        mainSubplotID = '';

        var counterIDs = ax._counterAxes;
        for(var j = 0; j < counterIDs.length; j++) {
            var counterPart = counterIDs[j];
            var id = isX ? (ax._id + counterPart) : (counterPart + ax._id);
            if(!nextBestMainSubplotID) nextBestMainSubplotID = id;
            var counterAx = axisIDs.getFromId(mockGd, counterPart);
            if(anchorID && counterAx.overlaying === anchorID) {
                mainSubplotID = id;
                break;
            }
        }
    }

    return mainSubplotID || nextBestMainSubplotID;
}

// This function clears any trace attributes with valType: color and
// no set dflt filed in the plot schema. This is needed because groupby (which
// is the only transform for which this currently applies) supplies parent
// trace defaults, then expanded trace defaults. The result is that `null`
// colors are default-supplied and inherited as a color instead of a null.
// The result is that expanded trace default colors have no effect, with
// the final result that groups are indistinguishable. This function clears
// those colors so that individual groupby groups get unique colors.
plots.clearExpandedTraceDefaultColors = function(trace) {
    var colorAttrs, path, i;

    // This uses weird closure state in order to satisfy the linter rule
    // that we can't create functions in a loop.
    function locateColorAttrs(attr, attrName, attrs, level) {
        path[level] = attrName;
        path.length = level + 1;
        if(attr.valType === 'color' && attr.dflt === undefined) {
            colorAttrs.push(path.join('.'));
        }
    }

    path = [];

    // Get the cached colorAttrs:
    colorAttrs = trace._module._colorAttrs;

    // Or else compute and cache the colorAttrs on the module:
    if(!colorAttrs) {
        trace._module._colorAttrs = colorAttrs = [];
        PlotSchema.crawl(
            trace._module.attributes,
            locateColorAttrs
        );
    }

    for(i = 0; i < colorAttrs.length; i++) {
        var origprop = Lib.nestedProperty(trace, '_input.' + colorAttrs[i]);

        if(!origprop.get()) {
            Lib.nestedProperty(trace, colorAttrs[i]).set(null);
        }
    }
};


plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) {
    var modules = fullLayout._modules;
    var visibleModules = fullLayout._visibleModules;
    var basePlotModules = fullLayout._basePlotModules;
    var cnt = 0;
    var colorCnt = 0;

    var i, fullTrace, trace;

    fullLayout._transformModules = [];

    function pushModule(fullTrace) {
        dataOut.push(fullTrace);

        var _module = fullTrace._module;
        if(!_module) return;

        Lib.pushUnique(modules, _module);
        if(fullTrace.visible === true) Lib.pushUnique(visibleModules, _module);
        Lib.pushUnique(basePlotModules, fullTrace._module.basePlotModule);
        cnt++;

        // TODO: do we really want color not to increment for explicitly invisible traces?
        // This logic is weird, but matches previous behavior: traces that you explicitly
        // set to visible:false do not increment the color, but traces WE determine to be
        // empty or invalid (and thus set to visible:false) DO increment color.
        // I kind of think we should just let all traces increment color, visible or not.
        // see mock: axes-autotype-empty vs. a test of restyling visible: false that
        // I can't find right now...
        if(fullTrace._input.visible !== false) colorCnt++;
    }

    var carpetIndex = {};
    var carpetDependents = [];
    var dataTemplate = (layout.template || {}).data || {};
    var templater = Template.traceTemplater(dataTemplate);

    for(i = 0; i < dataIn.length; i++) {
        trace = dataIn[i];

        // reuse uid we may have pulled out of oldFullData
        // Note: templater supplies trace type
        fullTrace = templater.newTrace(trace);
        fullTrace.uid = fullLayout._traceUids[i];
        plots.supplyTraceDefaults(trace, fullTrace, colorCnt, fullLayout, i);

        fullTrace.index = i;
        fullTrace._input = trace;
        fullTrace._expandedIndex = cnt;

        if(fullTrace.transforms && fullTrace.transforms.length) {
            var sdInvisible = trace.visible !== false && fullTrace.visible === false;

            var expandedTraces = applyTransforms(fullTrace, dataOut, layout, fullLayout);

            for(var j = 0; j < expandedTraces.length; j++) {
                var expandedTrace = expandedTraces[j];

                // No further templating during transforms.
                var fullExpandedTrace = {
                    _template: fullTrace._template,
                    type: fullTrace.type,
                    // set uid using parent uid and expanded index
                    // to promote consistency between update calls
                    uid: fullTrace.uid + j
                };

                // If the first supplyDefaults created `visible: false`,
                // clear it before running supplyDefaults a second time,
                // because sometimes there are items we still want to coerce
                // inside trace modules before determining that the trace is
                // again `visible: false`, for example partial visibilities
                // in `splom` traces.
                if(sdInvisible && expandedTrace.visible === false) {
                    delete expandedTrace.visible;
                }

                plots.supplyTraceDefaults(expandedTrace, fullExpandedTrace, cnt, fullLayout, i);

                // relink private (i.e. underscore) keys expanded trace to full expanded trace so
                // that transform supply-default methods can set _ keys for future use.
                relinkPrivateKeys(fullExpandedTrace, expandedTrace);

                // add info about parent data trace
                fullExpandedTrace.index = i;
                fullExpandedTrace._input = trace;
                fullExpandedTrace._fullInput = fullTrace;

                // add info about the expanded data
                fullExpandedTrace._expandedIndex = cnt;
                fullExpandedTrace._expandedInput = expandedTrace;

                pushModule(fullExpandedTrace);
            }
        }
        else {
            // add identify refs for consistency with transformed traces
            fullTrace._fullInput = fullTrace;
            fullTrace._expandedInput = fullTrace;

            pushModule(fullTrace);
        }

        if(Registry.traceIs(fullTrace, 'carpetAxis')) {
            carpetIndex[fullTrace.carpet] = fullTrace;
        }

        if(Registry.traceIs(fullTrace, 'carpetDependent')) {
            carpetDependents.push(i);
        }
    }

    for(i = 0; i < carpetDependents.length; i++) {
        fullTrace = dataOut[carpetDependents[i]];

        if(!fullTrace.visible) continue;

        var carpetAxis = carpetIndex[fullTrace.carpet];
        fullTrace._carpet = carpetAxis;

        if(!carpetAxis || !carpetAxis.visible) {
            fullTrace.visible = false;
            continue;
        }

        fullTrace.xaxis = carpetAxis.xaxis;
        fullTrace.yaxis = carpetAxis.yaxis;
    }
};

plots.supplyAnimationDefaults = function(opts) {
    opts = opts || {};
    var i;
    var optsOut = {};

    function coerce(attr, dflt) {
        return Lib.coerce(opts || {}, optsOut, animationAttrs, attr, dflt);
    }

    coerce('mode');
    coerce('direction');
    coerce('fromcurrent');

    if(Array.isArray(opts.frame)) {
        optsOut.frame = [];
        for(i = 0; i < opts.frame.length; i++) {
            optsOut.frame[i] = plots.supplyAnimationFrameDefaults(opts.frame[i] || {});
        }
    } else {
        optsOut.frame = plots.supplyAnimationFrameDefaults(opts.frame || {});
    }

    if(Array.isArray(opts.transition)) {
        optsOut.transition = [];
        for(i = 0; i < opts.transition.length; i++) {
            optsOut.transition[i] = plots.supplyAnimationTransitionDefaults(opts.transition[i] || {});
        }
    } else {
        optsOut.transition = plots.supplyAnimationTransitionDefaults(opts.transition || {});
    }

    return optsOut;
};

plots.supplyAnimationFrameDefaults = function(opts) {
    var optsOut = {};

    function coerce(attr, dflt) {
        return Lib.coerce(opts || {}, optsOut, animationAttrs.frame, attr, dflt);
    }

    coerce('duration');
    coerce('redraw');

    return optsOut;
};

plots.supplyAnimationTransitionDefaults = function(opts) {
    var optsOut = {};

    function coerce(attr, dflt) {
        return Lib.coerce(opts || {}, optsOut, animationAttrs.transition, attr, dflt);
    }

    coerce('duration');
    coerce('easing');

    return optsOut;
};

plots.supplyFrameDefaults = function(frameIn) {
    var frameOut = {};

    function coerce(attr, dflt) {
        return Lib.coerce(frameIn, frameOut, frameAttrs, attr, dflt);
    }

    coerce('group');
    coerce('name');
    coerce('traces');
    coerce('baseframe');
    coerce('data');
    coerce('layout');

    return frameOut;
};

plots.supplyTraceDefaults = function(traceIn, traceOut, colorIndex, layout, traceInIndex) {
    var colorway = layout.colorway || Color.defaults;
    var defaultColor = colorway[colorIndex % colorway.length];

    var i;

    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, plots.attributes, attr, dflt);
    }

    var visible = coerce('visible');

    coerce('type');
    coerce('name', layout._traceWord + ' ' + traceInIndex);

    coerce('uirevision', layout.uirevision);

    // we want even invisible traces to make their would-be subplots visible
    // so coerce the subplot id(s) now no matter what
    var _module = plots.getModule(traceOut);

    traceOut._module = _module;
    if(_module) {
        var basePlotModule = _module.basePlotModule;
        var subplotAttr = basePlotModule.attr;
        var subplotAttrs = basePlotModule.attributes;
        if(subplotAttr && subplotAttrs) {
            var subplots = layout._subplots;
            var subplotId = '';

            // TODO - currently if we draw an empty gl2d subplot, it draws
            // nothing then gets stuck and you can't get it back without newPlot
            // sort this out in the regl refactor? but for now just drop empty gl2d subplots
            if(basePlotModule.name !== 'gl2d' || visible) {
                if(Array.isArray(subplotAttr)) {
                    for(i = 0; i < subplotAttr.length; i++) {
                        var attri = subplotAttr[i];
                        var vali = Lib.coerce(traceIn, traceOut, subplotAttrs, attri);

                        if(subplots[attri]) Lib.pushUnique(subplots[attri], vali);
                        subplotId += vali;
                    }
                }
                else {
                    subplotId = Lib.coerce(traceIn, traceOut, subplotAttrs, subplotAttr);
                }

                if(subplots[basePlotModule.name]) {
                    Lib.pushUnique(subplots[basePlotModule.name], subplotId);
                }
            }
        }
    }

    function coerceUnlessPruned(attr, dflt, cb) {
        if(_module && (attr in _module.attributes) && _module.attributes[attr] === undefined) {
            // Pruned
        } else {
            if(cb && typeof cb === 'function') {
                cb();
            } else {
                coerce(attr, dflt);
            }
        }
    }

    if(visible) {
        coerce('customdata');
        coerce('ids');

        if(Registry.traceIs(traceOut, 'showLegend')) {
            traceOut._dfltShowLegend = true;
            coerce('showlegend');
            coerce('legendgroup');
        }
        else {
            traceOut._dfltShowLegend = false;
        }

        coerceUnlessPruned('hoverlabel', '', function() {
            Registry.getComponentMethod(
                'fx',
                'supplyDefaults'
            )(traceIn, traceOut, defaultColor, layout);
        });

        // TODO add per-base-plot-module trace defaults step

        if(_module) {
            _module.supplyDefaults(traceIn, traceOut, defaultColor, layout);
            if(!traceOut.hovertemplate) Lib.coerceHoverinfo(traceIn, traceOut, layout);
        }

        if(!Registry.traceIs(traceOut, 'noOpacity')) coerce('opacity');

        if(Registry.traceIs(traceOut, 'notLegendIsolatable')) {
            // This clears out the legendonly state for traces like carpet that
            // cannot be isolated in the legend
            traceOut.visible = !!traceOut.visible;
        }

        if(_module && _module.selectPoints) {
            coerce('selectedpoints');
        }

        plots.supplyTransformDefaults(traceIn, traceOut, layout);
    }

    return traceOut;
};

/**
 * hasMakesDataTransform: does this trace have a transform that makes its own
 * data, either by grabbing it from somewhere else or by creating it from input
 * parameters? If so, we should still keep going with supplyDefaults
 * even if the trace is invisible, which may just be because it has no data yet.
 */
function hasMakesDataTransform(trace) {
    var transforms = trace.transforms;
    if(Array.isArray(transforms) && transforms.length) {
        for(var i = 0; i < transforms.length; i++) {
            var ti = transforms[i];
            var _module = ti._module || transformsRegistry[ti.type];
            if(_module && _module.makesData) return true;
        }
    }
    return false;
}

plots.hasMakesDataTransform = hasMakesDataTransform;

plots.supplyTransformDefaults = function(traceIn, traceOut, layout) {
    // For now we only allow transforms on 1D traces, ie those that specify a _length.
    // If we were to implement 2D transforms, we'd need to have each transform
    // describe its own applicability and disable itself when it doesn't apply.
    // Also allow transforms that make their own data, but not in globalTransforms
    if(!(traceOut._length || hasMakesDataTransform(traceIn))) return;

    var globalTransforms = layout._globalTransforms || [];
    var transformModules = layout._transformModules || [];

    if(!Array.isArray(traceIn.transforms) && globalTransforms.length === 0) return;

    var containerIn = traceIn.transforms || [];
    var transformList = globalTransforms.concat(containerIn);
    var containerOut = traceOut.transforms = [];

    for(var i = 0; i < transformList.length; i++) {
        var transformIn = transformList[i];
        var type = transformIn.type;
        var _module = transformsRegistry[type];
        var transformOut;

        /*
         * Supply defaults may run twice. First pass runs all supply defaults steps
         * and adds the _module to any output transforms.
         * If transforms exist another pass is run so that any generated traces also
         * go through supply defaults. This has the effect of rerunning
         * supplyTransformDefaults. If the transform does not have a `transform`
         * function it could not have generated any new traces and the second stage
         * is unnecessary. We detect this case with the following variables.
         */
        var isFirstStage = !(transformIn._module && transformIn._module === _module);
        var doLaterStages = _module && typeof _module.transform === 'function';

        if(!_module) Lib.warn('Unrecognized transform type ' + type + '.');

        if(_module && _module.supplyDefaults && (isFirstStage || doLaterStages)) {
            transformOut = _module.supplyDefaults(transformIn, traceOut, layout, traceIn);
            transformOut.type = type;
            transformOut._module = _module;

            Lib.pushUnique(transformModules, _module);
        }
        else {
            transformOut = Lib.extendFlat({}, transformIn);
        }

        containerOut.push(transformOut);
    }
};

function applyTransforms(fullTrace, fullData, layout, fullLayout) {
    var container = fullTrace.transforms;
    var dataOut = [fullTrace];

    for(var i = 0; i < container.length; i++) {
        var transform = container[i];
        var _module = transformsRegistry[transform.type];

        if(_module && _module.transform) {
            dataOut = _module.transform(dataOut, {
                transform: transform,
                fullTrace: fullTrace,
                fullData: fullData,
                layout: layout,
                fullLayout: fullLayout,
                transformIndex: i
            });
        }
    }

    return dataOut;
}

plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) {
    function coerce(attr, dflt) {
        return Lib.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt);
    }

    var template = layoutIn.template;
    if(Lib.isPlainObject(template)) {
        layoutOut.template = template;
        layoutOut._template = template.layout;
        layoutOut._dataTemplate = template.data;
    }

    var globalFont = Lib.coerceFont(coerce, 'font');

    coerce('title.text', layoutOut._dfltTitle.plot);

    Lib.coerceFont(coerce, 'title.font', {
        family: globalFont.family,
        size: Math.round(globalFont.size * 1.4),
        color: globalFont.color
    });

    coerce('title.xref');
    coerce('title.yref');
    coerce('title.x');
    coerce('title.y');
    coerce('title.xanchor');
    coerce('title.yanchor');
    coerce('title.pad.t');
    coerce('title.pad.r');
    coerce('title.pad.b');
    coerce('title.pad.l');

    // Make sure that autosize is defaulted to *true*
    // on layouts with no set width and height for backward compatibly,
    // in particular https://plot.ly/javascript/responsive-fluid-layout/
    //
    // Before https://github.com/plotly/plotly.js/pull/635 ,
    // layouts with no set width and height were set temporary set to 'initial'
    // to pass through the autosize routine
    //
    // This behavior is subject to change in v2.
    coerce('autosize', !(layoutIn.width && layoutIn.height));

    coerce('width');
    coerce('height');
    coerce('margin.l');
    coerce('margin.r');
    coerce('margin.t');
    coerce('margin.b');
    coerce('margin.pad');
    coerce('margin.autoexpand');

    if(layoutIn.width && layoutIn.height) plots.sanitizeMargins(layoutOut);

    Registry.getComponentMethod('grid', 'sizeDefaults')(layoutIn, layoutOut);

    coerce('paper_bgcolor');

    coerce('separators', formatObj.decimal + formatObj.thousands);
    coerce('hidesources');

    coerce('colorway');

    coerce('datarevision');
    var uirevision = coerce('uirevision');
    coerce('editrevision', uirevision);
    coerce('selectionrevision', uirevision);

    coerce('modebar.orientation');
    coerce('modebar.bgcolor', Color.addOpacity(layoutOut.paper_bgcolor, 0.5));
    var modebarDefaultColor = Color.contrast(Color.rgb(layoutOut.modebar.bgcolor));
    coerce('modebar.color', Color.addOpacity(modebarDefaultColor, 0.3));
    coerce('modebar.activecolor', Color.addOpacity(modebarDefaultColor, 0.7));
    coerce('modebar.uirevision', uirevision);

    coerce('meta');

    // do not include defaults in fullLayout when users do not set transition
    if(Lib.isPlainObject(layoutIn.transition)) {
        coerce('transition.duration');
        coerce('transition.easing');
        coerce('transition.ordering');
    }

    Registry.getComponentMethod(
        'calendars',
        'handleDefaults'
    )(layoutIn, layoutOut, 'calendar');

    Registry.getComponentMethod(
        'fx',
        'supplyLayoutGlobalDefaults'
    )(layoutIn, layoutOut, coerce);
};

plots.plotAutoSize = function plotAutoSize(gd, layout, fullLayout) {
    var context = gd._context || {};
    var frameMargins = context.frameMargins;
    var newWidth;
    var newHeight;

    var isPlotDiv = Lib.isPlotDiv(gd);

    if(isPlotDiv) gd.emit('plotly_autosize');

    // embedded in an iframe - just take the full iframe size
    // if we get to this point, with no aspect ratio restrictions
    if(context.fillFrame) {
        newWidth = window.innerWidth;
        newHeight = window.innerHeight;

        // somehow we get a few extra px height sometimes...
        // just hide it
        document.body.style.overflow = 'hidden';
    }
    else {
        // plotly.js - let the developers do what they want, either
        // provide height and width for the container div,
        // specify size in layout, or take the defaults,
        // but don't enforce any ratio restrictions
        var computedStyle = isPlotDiv ? window.getComputedStyle(gd) : {};

        newWidth = parseFloat(computedStyle.width) || parseFloat(computedStyle.maxWidth) || fullLayout.width;
        newHeight = parseFloat(computedStyle.height) || parseFloat(computedStyle.maxHeight) || fullLayout.height;

        if(isNumeric(frameMargins) && frameMargins > 0) {
            var factor = 1 - 2 * frameMargins;
            newWidth = Math.round(factor * newWidth);
            newHeight = Math.round(factor * newHeight);
        }
    }

    var minWidth = plots.layoutAttributes.width.min;
    var minHeight = plots.layoutAttributes.height.min;
    if(newWidth < minWidth) newWidth = minWidth;
    if(newHeight < minHeight) newHeight = minHeight;

    var widthHasChanged = !layout.width &&
        (Math.abs(fullLayout.width - newWidth) > 1);
    var heightHasChanged = !layout.height &&
        (Math.abs(fullLayout.height - newHeight) > 1);

    if(heightHasChanged || widthHasChanged) {
        if(widthHasChanged) fullLayout.width = newWidth;
        if(heightHasChanged) fullLayout.height = newHeight;
    }

    // cache initial autosize value, used in relayout when
    // width or height values are set to null
    if(!gd._initialAutoSize) {
        gd._initialAutoSize = { width: newWidth, height: newHeight };
    }

    plots.sanitizeMargins(fullLayout);
};

plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, transitionData) {
    var componentsRegistry = Registry.componentsRegistry;
    var basePlotModules = layoutOut._basePlotModules;
    var component, i, _module;

    var Cartesian = Registry.subplotsRegistry.cartesian;

    // check if any components need to add more base plot modules
    // that weren't captured by traces
    for(component in componentsRegistry) {
        _module = componentsRegistry[component];

        if(_module.includeBasePlot) {
            _module.includeBasePlot(layoutIn, layoutOut);
        }
    }

    // make sure we *at least* have some cartesian axes
    if(!basePlotModules.length) {
        basePlotModules.push(Cartesian);
    }

    // ensure all cartesian axes have at least one subplot
    if(layoutOut._has('cartesian')) {
        Registry.getComponentMethod('grid', 'contentDefaults')(layoutIn, layoutOut);
        Cartesian.finalizeSubplots(layoutIn, layoutOut);
    }

    // sort subplot lists
    for(var subplotType in layoutOut._subplots) {
        layoutOut._subplots[subplotType].sort(Lib.subplotSort);
    }

    // base plot module layout defaults
    for(i = 0; i < basePlotModules.length; i++) {
        _module = basePlotModules[i];

        // e.g. pie does not have a layout-defaults step
        if(_module.supplyLayoutDefaults) {
            _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
        }
    }

    // trace module layout defaults
    // use _modules rather than _visibleModules so that even
    // legendonly traces can include settings - eg barmode, which affects
    // legend.traceorder default value.
    var modules = layoutOut._modules;
    for(i = 0; i < modules.length; i++) {
        _module = modules[i];

        if(_module.supplyLayoutDefaults) {
            _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
        }
    }

    // transform module layout defaults
    var transformModules = layoutOut._transformModules;
    for(i = 0; i < transformModules.length; i++) {
        _module = transformModules[i];

        if(_module.supplyLayoutDefaults) {
            _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData, transitionData);
        }
    }

    for(component in componentsRegistry) {
        _module = componentsRegistry[component];

        if(_module.supplyLayoutDefaults) {
            _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
        }
    }
};

// Remove all plotly attributes from a div so it can be replotted fresh
// TODO: these really need to be encapsulated into a much smaller set...
plots.purge = function(gd) {
    // note: we DO NOT remove _context because it doesn't change when we insert
    // a new plot, and may have been set outside of our scope.

    var fullLayout = gd._fullLayout || {};
    if(fullLayout._glcontainer !== undefined) {
        fullLayout._glcontainer.selectAll('.gl-canvas').remove();
        fullLayout._glcontainer.remove();
        fullLayout._glcanvas = null;
    }
    if(fullLayout._geocontainer !== undefined) fullLayout._geocontainer.remove();

    // remove modebar
    if(fullLayout._modeBar) fullLayout._modeBar.destroy();

    if(gd._transitionData) {
        // Ensure any dangling callbacks are simply dropped if the plot is purged.
        // This is more or less only actually important for testing.
        if(gd._transitionData._interruptCallbacks) {
            gd._transitionData._interruptCallbacks.length = 0;
        }

        if(gd._transitionData._animationRaf) {
            window.cancelAnimationFrame(gd._transitionData._animationRaf);
        }
    }

    // remove any planned throttles
    Lib.clearThrottle();

    // remove responsive handler
    Lib.clearResponsive(gd);

    // data and layout
    delete gd.data;
    delete gd.layout;
    delete gd._fullData;
    delete gd._fullLayout;
    delete gd.calcdata;
    delete gd.framework;
    delete gd.empty;

    delete gd.fid;

    delete gd.undoqueue; // action queue
    delete gd.undonum;
    delete gd.autoplay; // are we doing an action that doesn't go in undo queue?
    delete gd.changed;

    // these get recreated on Plotly.plot anyway, but just to be safe
    // (and to have a record of them...)
    delete gd._promises;
    delete gd._redrawTimer;
    delete gd._hmlumcount;
    delete gd._hmpixcount;
    delete gd._transitionData;
    delete gd._transitioning;
    delete gd._initialAutoSize;
    delete gd._transitioningWithDuration;

    // created during certain events, that *should* clean them up
    // themselves, but may not if there was an error
    delete gd._dragging;
    delete gd._dragged;
    delete gd._hoverdata;
    delete gd._snapshotInProgress;
    delete gd._editing;
    delete gd._replotPending;
    delete gd._mouseDownTime;
    delete gd._legendMouseDownTime;

    // remove all event listeners
    if(gd.removeAllListeners) gd.removeAllListeners();
};

plots.style = function(gd) {
    var _modules = gd._fullLayout._visibleModules;
    var styleModules = [];
    var i;

    // some trace modules reuse the same style method,
    // make sure to not unnecessary call them multiple times.

    for(i = 0; i < _modules.length; i++) {
        var _module = _modules[i];
        if(_module.style) {
            Lib.pushUnique(styleModules, _module.style);
        }
    }

    for(i = 0; i < styleModules.length; i++) {
        styleModules[i](gd);
    }
};

plots.sanitizeMargins = function(fullLayout) {
    // polar doesn't do margins...
    if(!fullLayout || !fullLayout.margin) return;

    var width = fullLayout.width;
    var height = fullLayout.height;
    var margin = fullLayout.margin;
    var plotWidth = width - (margin.l + margin.r);
    var plotHeight = height - (margin.t + margin.b);
    var correction;

    // if margin.l + margin.r = 0 then plotWidth > 0
    // as width >= 10 by supplyDefaults
    // similarly for margin.t + margin.b

    if(plotWidth < 0) {
        correction = (width - 1) / (margin.l + margin.r);
        margin.l = Math.floor(correction * margin.l);
        margin.r = Math.floor(correction * margin.r);
    }

    if(plotHeight < 0) {
        correction = (height - 1) / (margin.t + margin.b);
        margin.t = Math.floor(correction * margin.t);
        margin.b = Math.floor(correction * margin.b);
    }
};

plots.clearAutoMarginIds = function(gd) {
    gd._fullLayout._pushmarginIds = {};
};

plots.allowAutoMargin = function(gd, id) {
    gd._fullLayout._pushmarginIds[id] = 1;
};

function initMargins(fullLayout) {
    var margin = fullLayout.margin;

    if(!fullLayout._size) {
        var gs = fullLayout._size = {
            l: Math.round(margin.l),
            r: Math.round(margin.r),
            t: Math.round(margin.t),
            b: Math.round(margin.b),
            p: Math.round(margin.pad)
        };
        gs.w = Math.round(fullLayout.width) - gs.l - gs.r;
        gs.h = Math.round(fullLayout.height) - gs.t - gs.b;
    }
    if(!fullLayout._pushmargin) fullLayout._pushmargin = {};
    if(!fullLayout._pushmarginIds) fullLayout._pushmarginIds = {};
}

/**
 * autoMargin: called by components that may need to expand the margins to
 * be rendered on-plot.
 *
 * @param {DOM element} gd
 * @param {string} id - an identifier unique (within this plot) to this object,
 *     so we can remove a previous margin expansion from the same object.
 * @param {object} o - the margin requirements of this object, or omit to delete
 *     this entry (like if it's hidden). Keys are:
 *     x, y: plot fraction of the anchor point.
 *     xl, xr, yt, yb: if the object has an extent defined in plot fraction,
 *         you can specify both edges as plot fractions in each dimension
 *     l, r, t, b: the pixels to pad past the plot fraction x[l|r] and y[t|b]
 *     pad: extra pixels to add in all directions, default 12 (why?)
 */
plots.autoMargin = function(gd, id, o) {
    var fullLayout = gd._fullLayout;

    var pushMargin = fullLayout._pushmargin;
    var pushMarginIds = fullLayout._pushmarginIds;

    if(fullLayout.margin.autoexpand !== false) {
        if(!o) {
            delete pushMargin[id];
            delete pushMarginIds[id];
        }
        else {
            var pad = o.pad;
            if(pad === undefined) {
                var margin = fullLayout.margin;
                // if no explicit pad is given, use 12px unless there's a
                // specified margin that's smaller than that
                pad = Math.min(12, margin.l, margin.r, margin.t, margin.b);
            }

            // if the item is too big, just give it enough automargin to
            // make sure you can still grab it and bring it back
            if(o.l + o.r > fullLayout.width * 0.5) o.l = o.r = 0;
            if(o.b + o.t > fullLayout.height * 0.5) o.b = o.t = 0;

            var xl = o.xl !== undefined ? o.xl : o.x;
            var xr = o.xr !== undefined ? o.xr : o.x;
            var yt = o.yt !== undefined ? o.yt : o.y;
            var yb = o.yb !== undefined ? o.yb : o.y;

            pushMargin[id] = {
                l: {val: xl, size: o.l + pad},
                r: {val: xr, size: o.r + pad},
                b: {val: yb, size: o.b + pad},
                t: {val: yt, size: o.t + pad}
            };
            pushMarginIds[id] = 1;
        }

        if(!fullLayout._replotting) plots.doAutoMargin(gd);
    }
};

plots.doAutoMargin = function(gd) {
    var fullLayout = gd._fullLayout;
    if(!fullLayout._size) fullLayout._size = {};
    initMargins(fullLayout);

    var gs = fullLayout._size;
    var oldmargins = JSON.stringify(gs);
    var margin = fullLayout.margin;

    // adjust margins for outside components
    // fullLayout.margin is the requested margin,
    // fullLayout._size has margins and plotsize after adjustment
    var ml = margin.l;
    var mr = margin.r;
    var mt = margin.t;
    var mb = margin.b;
    var width = fullLayout.width;
    var height = fullLayout.height;
    var pushMargin = fullLayout._pushmargin;
    var pushMarginIds = fullLayout._pushmarginIds;

    if(fullLayout.margin.autoexpand !== false) {

        for(var k in pushMargin) {
            if(!pushMarginIds[k]) delete pushMargin[k];
        }

        // fill in the requested margins
        pushMargin.base = {
            l: {val: 0, size: ml},
            r: {val: 1, size: mr},
            t: {val: 1, size: mt},
            b: {val: 0, size: mb}
        };

        // now cycle through all the combinations of l and r
        // (and t and b) to find the required margins

        for(var k1 in pushMargin) {

            var pushleft = pushMargin[k1].l || {};
            var pushbottom = pushMargin[k1].b || {};
            var fl = pushleft.val;
            var pl = pushleft.size;
            var fb = pushbottom.val;
            var pb = pushbottom.size;

            for(var k2 in pushMargin) {
                if(isNumeric(pl) && pushMargin[k2].r) {
                    var fr = pushMargin[k2].r.val;
                    var pr = pushMargin[k2].r.size;

                    if(fr > fl) {
                        var newL = (pl * fr + (pr - width) * fl) / (fr - fl);
                        var newR = (pr * (1 - fl) + (pl - width) * (1 - fr)) / (fr - fl);
                        if(newL >= 0 && newR >= 0 && width - (newL + newR) > 0 && newL + newR > ml + mr) {
                            ml = newL;
                            mr = newR;
                        }
                    }
                }

                if(isNumeric(pb) && pushMargin[k2].t) {
                    var ft = pushMargin[k2].t.val;
                    var pt = pushMargin[k2].t.size;

                    if(ft > fb) {
                        var newB = (pb * ft + (pt - height) * fb) / (ft - fb);
                        var newT = (pt * (1 - fb) + (pb - height) * (1 - ft)) / (ft - fb);
                        if(newB >= 0 && newT >= 0 && height - (newT + newB) > 0 && newB + newT > mb + mt) {
                            mb = newB;
                            mt = newT;
                        }
                    }
                }
            }
        }
    }

    gs.l = Math.round(ml);
    gs.r = Math.round(mr);
    gs.t = Math.round(mt);
    gs.b = Math.round(mb);
    gs.p = Math.round(margin.pad);
    gs.w = Math.round(width) - gs.l - gs.r;
    gs.h = Math.round(height) - gs.t - gs.b;

    // if things changed and we're not already redrawing, trigger a redraw
    if(!fullLayout._replotting &&
        oldmargins !== '{}' &&
        oldmargins !== JSON.stringify(fullLayout._size)
    ) {
        if('_redrawFromAutoMarginCount' in fullLayout) {
            fullLayout._redrawFromAutoMarginCount++;
        } else {
            fullLayout._redrawFromAutoMarginCount = 1;
        }
        return Registry.call('plot', gd);
    }
};

/**
 * JSONify the graph data and layout
 *
 * This function needs to recurse because some src can be inside
 * sub-objects.
 *
 * It also strips out functions and private (starts with _) elements.
 * Therefore, we can add temporary things to data and layout that don't
 * get saved.
 *
 * @param gd The graphDiv
 * @param {Boolean} dataonly If true, don't return layout.
 * @param {'keepref'|'keepdata'|'keepall'} [mode='keepref'] Filter what's kept
 *      keepref: remove data for which there's a src present
 *          eg if there's xsrc present (and xsrc is well-formed,
 *          ie has : and some chars before it), strip out x
 *      keepdata: remove all src tags, don't remove the data itself
 *      keepall: keep data and src
 * @param {String} output If you specify 'object', the result will not be stringified
 * @param {Boolean} useDefaults If truthy, use _fullLayout and _fullData
 * @returns {Object|String}
 */
plots.graphJson = function(gd, dataonly, mode, output, useDefaults) {
    // if the defaults aren't supplied yet, we need to do that...
    if((useDefaults && dataonly && !gd._fullData) ||
            (useDefaults && !dataonly && !gd._fullLayout)) {
        plots.supplyDefaults(gd);
    }

    var data = (useDefaults) ? gd._fullData : gd.data;
    var layout = (useDefaults) ? gd._fullLayout : gd.layout;
    var frames = (gd._transitionData || {})._frames;

    function stripObj(d) {
        if(typeof d === 'function') {
            return null;
        }
        if(Lib.isPlainObject(d)) {
            var o = {};
            var v, src;
            for(v in d) {
                // remove private elements and functions
                // _ is for private, [ is a mistake ie [object Object]
                if(typeof d[v] === 'function' ||
                        ['_', '['].indexOf(v.charAt(0)) !== -1) {
                    continue;
                }

                // look for src/data matches and remove the appropriate one
                if(mode === 'keepdata') {
                    // keepdata: remove all ...src tags
                    if(v.substr(v.length - 3) === 'src') {
                        continue;
                    }
                }
                else if(mode === 'keepstream') {
                    // keep sourced data if it's being streamed.
                    // similar to keepref, but if the 'stream' object exists
                    // in a trace, we will keep the data array.
                    src = d[v + 'src'];
                    if(typeof src === 'string' && src.indexOf(':') > 0) {
                        if(!Lib.isPlainObject(d.stream)) {
                            continue;
                        }
                    }
                }
                else if(mode !== 'keepall') {
                    // keepref: remove sourced data but only
                    // if the source tag is well-formed
                    src = d[v + 'src'];
                    if(typeof src === 'string' && src.indexOf(':') > 0) {
                        continue;
                    }
                }

                // OK, we're including this... recurse into it
                o[v] = stripObj(d[v]);
            }
            return o;
        }

        if(Array.isArray(d)) {
            return d.map(stripObj);
        }

        if(Lib.isTypedArray(d)) {
            return Lib.simpleMap(d, Lib.identity);
        }

        // convert native dates to date strings...
        // mostly for external users exporting to plotly
        if(Lib.isJSDate(d)) return Lib.ms2DateTimeLocal(+d);

        return d;
    }

    var obj = {
        data: (data || []).map(function(v) {
            var d = stripObj(v);
            // fit has some little arrays in it that don't contain data,
            // just fit params and meta
            if(dataonly) { delete d.fit; }
            return d;
        })
    };
    if(!dataonly) { obj.layout = stripObj(layout); }

    if(gd.framework && gd.framework.isPolar) obj = gd.framework.getConfig();

    if(frames) obj.frames = stripObj(frames);

    return (output === 'object') ? obj : JSON.stringify(obj);
};

/**
 * Modify a keyframe using a list of operations:
 *
 * @param {array of objects} operations
 *      Sequence of operations to be performed on the keyframes
 */
plots.modifyFrames = function(gd, operations) {
    var i, op, frame;
    var _frames = gd._transitionData._frames;
    var _frameHash = gd._transitionData._frameHash;

    for(i = 0; i < operations.length; i++) {
        op = operations[i];

        switch(op.type) {
            // No reason this couldn't exist, but is currently unused/untested:
            /* case 'rename':
                frame = _frames[op.index];
                delete _frameHash[frame.name];
                _frameHash[op.name] = frame;
                frame.name = op.name;
                break;*/
            case 'replace':
                frame = op.value;
                var oldName = (_frames[op.index] || {}).name;
                var newName = frame.name;
                _frames[op.index] = _frameHash[newName] = frame;

                if(newName !== oldName) {
                    // If name has changed in addition to replacement, then update
                    // the lookup table:
                    delete _frameHash[oldName];
                    _frameHash[newName] = frame;
                }

                break;
            case 'insert':
                frame = op.value;
                _frameHash[frame.name] = frame;
                _frames.splice(op.index, 0, frame);
                break;
            case 'delete':
                frame = _frames[op.index];
                delete _frameHash[frame.name];
                _frames.splice(op.index, 1);
                break;
        }
    }

    return Promise.resolve();
};

/*
 * Compute a keyframe. Merge a keyframe into its base frame(s) and
 * expand properties.
 *
 * @param {object} frameLookup
 *      An object containing frames keyed by name (i.e. gd._transitionData._frameHash)
 * @param {string} frame
 *      The name of the keyframe to be computed
 *
 * Returns: a new object with the merged content
 */
plots.computeFrame = function(gd, frameName) {
    var frameLookup = gd._transitionData._frameHash;
    var i, traceIndices, traceIndex, destIndex;

    // Null or undefined will fail on .toString(). We'll allow numbers since we
    // make it clear frames must be given string names, but we'll allow numbers
    // here since they're otherwise fine for looking up frames as long as they're
    // properly cast to strings. We really just want to ensure here that this
    // 1) doesn't fail, and
    // 2) doens't give an incorrect answer (which String(frameName) would)
    if(!frameName) {
        throw new Error('computeFrame must be given a string frame name');
    }

    var framePtr = frameLookup[frameName.toString()];

    // Return false if the name is invalid:
    if(!framePtr) {
        return false;
    }

    var frameStack = [framePtr];
    var frameNameStack = [framePtr.name];

    // Follow frame pointers:
    while(framePtr.baseframe && (framePtr = frameLookup[framePtr.baseframe.toString()])) {
        // Avoid infinite loops:
        if(frameNameStack.indexOf(framePtr.name) !== -1) break;

        frameStack.push(framePtr);
        frameNameStack.push(framePtr.name);
    }

    // A new object for the merged result:
    var result = {};

    // Merge, starting with the last and ending with the desired frame:
    while((framePtr = frameStack.pop())) {
        if(framePtr.layout) {
            result.layout = plots.extendLayout(result.layout, framePtr.layout);
        }

        if(framePtr.data) {
            if(!result.data) {
                result.data = [];
            }
            traceIndices = framePtr.traces;

            if(!traceIndices) {
                // If not defined, assume serial order starting at zero
                traceIndices = [];
                for(i = 0; i < framePtr.data.length; i++) {
                    traceIndices[i] = i;
                }
            }

            if(!result.traces) {
                result.traces = [];
            }

            for(i = 0; i < framePtr.data.length; i++) {
                // Loop through this frames data, find out where it should go,
                // and merge it!
                traceIndex = traceIndices[i];
                if(traceIndex === undefined || traceIndex === null) {
                    continue;
                }

                destIndex = result.traces.indexOf(traceIndex);
                if(destIndex === -1) {
                    destIndex = result.data.length;
                    result.traces[destIndex] = traceIndex;
                }

                result.data[destIndex] = plots.extendTrace(result.data[destIndex], framePtr.data[i]);
            }
        }
    }

    return result;
};

/*
 * Recompute the lookup table that maps frame name -> frame object. addFrames/
 * deleteFrames already manages this data one at a time, so the only time this
 * is necessary is if you poke around manually in `gd._transitionData._frames`
 * and create and haven't updated the lookup table.
 */
plots.recomputeFrameHash = function(gd) {
    var hash = gd._transitionData._frameHash = {};
    var frames = gd._transitionData._frames;
    for(var i = 0; i < frames.length; i++) {
        var frame = frames[i];
        if(frame && frame.name) {
            hash[frame.name] = frame;
        }
    }
};

/**
 * Extend an object, treating container arrays very differently by extracting
 * their contents and merging them separately.
 *
 * This exists so that we can extendDeepNoArrays and avoid stepping into data
 * arrays without knowledge of the plot schema, but so that we may also manually
 * recurse into known container arrays, such as transforms.
 *
 * See extendTrace and extendLayout below for usage.
 */
plots.extendObjectWithContainers = function(dest, src, containerPaths) {
    var containerProp, containerVal, i, j, srcProp, destProp, srcContainer, destContainer;
    var copy = Lib.extendDeepNoArrays({}, src || {});
    var expandedObj = Lib.expandObjectPaths(copy);
    var containerObj = {};

    // Step through and extract any container properties. Otherwise extendDeepNoArrays
    // will clobber any existing properties with an empty array and then supplyDefaults
    // will reset everything to defaults.
    if(containerPaths && containerPaths.length) {
        for(i = 0; i < containerPaths.length; i++) {
            containerProp = Lib.nestedProperty(expandedObj, containerPaths[i]);
            containerVal = containerProp.get();

            if(containerVal === undefined) {
                Lib.nestedProperty(containerObj, containerPaths[i]).set(null);
            }
            else {
                containerProp.set(null);
                Lib.nestedProperty(containerObj, containerPaths[i]).set(containerVal);
            }
        }
    }

    dest = Lib.extendDeepNoArrays(dest || {}, expandedObj);

    if(containerPaths && containerPaths.length) {
        for(i = 0; i < containerPaths.length; i++) {
            srcProp = Lib.nestedProperty(containerObj, containerPaths[i]);
            srcContainer = srcProp.get();

            if(!srcContainer) continue;

            destProp = Lib.nestedProperty(dest, containerPaths[i]);
            destContainer = destProp.get();

            if(!Array.isArray(destContainer)) {
                destContainer = [];
                destProp.set(destContainer);
            }

            for(j = 0; j < srcContainer.length; j++) {
                var srcObj = srcContainer[j];

                if(srcObj === null) destContainer[j] = null;
                else {
                    destContainer[j] = plots.extendObjectWithContainers(destContainer[j], srcObj);
                }
            }

            destProp.set(destContainer);
        }
    }

    return dest;
};

plots.dataArrayContainers = ['transforms', 'dimensions'];
plots.layoutArrayContainers = Registry.layoutArrayContainers;

/*
 * Extend a trace definition. This method:
 *
 *  1. directly transfers any array references
 *  2. manually recurses into container arrays like transforms
 *
 * The result is the original object reference with the new contents merged in.
 */
plots.extendTrace = function(destTrace, srcTrace) {
    return plots.extendObjectWithContainers(destTrace, srcTrace, plots.dataArrayContainers);
};

/*
 * Extend a layout definition. This method:
 *
 *  1. directly transfers any array references (not critically important for
 *     layout since there aren't really data arrays)
 *  2. manually recurses into container arrays like annotations
 *
 * The result is the original object reference with the new contents merged in.
 */
plots.extendLayout = function(destLayout, srcLayout) {
    return plots.extendObjectWithContainers(destLayout, srcLayout, plots.layoutArrayContainers);
};

/**
 * Transition to a set of new data and layout properties from Plotly.animate
 *
 * @param {DOM element} gd
 * @param {Object[]} data
 *      an array of data objects following the normal Plotly data definition format
 * @param {Object} layout
 *      a layout object, following normal Plotly layout format
 * @param {Number[]} traces
 *      indices of the corresponding traces specified in `data`
 * @param {Object} frameOpts
 *      options for the frame (i.e. whether to redraw post-transition)
 * @param {Object} transitionOpts
 *      options for the transition
 */
plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) {
    var opts = {redraw: frameOpts.redraw};
    var transitionedTraces = [];
    var axEdits = [];

    opts.prepareFn = function() {
        var dataLength = Array.isArray(data) ? data.length : 0;
        var traceIndices = traces.slice(0, dataLength);

        for(var i = 0; i < traceIndices.length; i++) {
            var traceIdx = traceIndices[i];
            var trace = gd._fullData[traceIdx];
            var module = trace._module;

            // There's nothing to do if this module is not defined:
            if(!module) continue;

            // Don't register the trace as transitioned if it doesn't know what to do.
            // If it *is* registered, it will receive a callback that it's responsible
            // for calling in order to register the transition as having completed.
            if(module.animatable) {
                transitionedTraces.push(traceIdx);
            }

            gd.data[traceIndices[i]] = plots.extendTrace(gd.data[traceIndices[i]], data[i]);
        }

        // Follow the same procedure. Clone it so we don't mangle the input, then
        // expand any object paths so we can merge deep into gd.layout:
        var layoutUpdate = Lib.expandObjectPaths(Lib.extendDeepNoArrays({}, layout));

        // Before merging though, we need to modify the incoming layout. We only
        // know how to *transition* layout ranges, so it's imperative that a new
        // range not be sent to the layout before the transition has started. So
        // we must remove the things we can transition:
        var axisAttrRe = /^[xy]axis[0-9]*$/;
        for(var attr in layoutUpdate) {
            if(!axisAttrRe.test(attr)) continue;
            delete layoutUpdate[attr].range;
        }

        plots.extendLayout(gd.layout, layoutUpdate);

        // Supply defaults after applying the incoming properties. Note that any attempt
        // to simplify this step and reduce the amount of work resulted in the reconstruction
        // of essentially the whole supplyDefaults step, so that it seems sensible to just use
        // supplyDefaults even though it's heavier than would otherwise be desired for
        // transitions:

        // first delete calcdata so supplyDefaults knows a calc step is coming
        delete gd.calcdata;

        plots.supplyDefaults(gd);
        plots.doCalcdata(gd);

        var newLayout = Lib.expandObjectPaths(layout);

        if(newLayout) {
            var subplots = gd._fullLayout._plots;

            for(var k in subplots) {
                var plotinfo = subplots[k];
                var xa = plotinfo.xaxis;
                var ya = plotinfo.yaxis;
                var xr0 = xa.range.slice();
                var yr0 = ya.range.slice();

                var xr1;
                if(Array.isArray(newLayout[xa._name + '.range'])) {
                    xr1 = newLayout[xa._name + '.range'].slice();
                } else if(Array.isArray((newLayout[xa._name] || {}).range)) {
                    xr1 = newLayout[xa._name].range.slice();
                }

                var yr1;
                if(Array.isArray(newLayout[ya._name + '.range'])) {
                    yr1 = newLayout[ya._name + '.range'].slice();
                } else if(Array.isArray((newLayout[ya._name] || {}).range)) {
                    yr1 = newLayout[ya._name].range.slice();
                }

                var editX;
                if(xr0 && xr1 && (xr0[0] !== xr1[0] || xr0[1] !== xr1[1])) {
                    editX = {xr0: xr0, xr1: xr1};
                }

                var editY;
                if(yr0 && yr1 && (yr0[0] !== yr1[0] || yr0[1] !== yr1[1])) {
                    editY = {yr0: yr0, yr1: yr1};
                }

                if(editX || editY) {
                    axEdits.push(Lib.extendFlat({plotinfo: plotinfo}, editX, editY));
                }
            }
        }

        return Promise.resolve();
    };

    opts.runFn = function(makeCallback) {
        var traceTransitionOpts;
        var basePlotModules = gd._fullLayout._basePlotModules;
        var hasAxisTransition = axEdits.length;
        var i;

        if(layout) {
            for(i = 0; i < basePlotModules.length; i++) {
                if(basePlotModules[i].transitionAxes) {
                    basePlotModules[i].transitionAxes(gd, axEdits, transitionOpts, makeCallback);
                }
            }
        }

        // Here handle the exception that we refuse to animate scales and axes at the same
        // time. In other words, if there's an axis transition, then set the data transition
        // to instantaneous.
        if(hasAxisTransition) {
            traceTransitionOpts = Lib.extendFlat({}, transitionOpts);
            traceTransitionOpts.duration = 0;
            // This means do not transition traces,
            // this happens on layout-only (e.g. axis range) animations
            transitionedTraces = null;
        } else {
            traceTransitionOpts = transitionOpts;
        }

        for(i = 0; i < basePlotModules.length; i++) {
            // Note that we pass a callback to *create* the callback that must be invoked on completion.
            // This is since not all traces know about transitions, so it greatly simplifies matters if
            // the trace is responsible for creating a callback, if needed, and then executing it when
            // the time is right.
            basePlotModules[i].plot(gd, transitionedTraces, traceTransitionOpts, makeCallback);
        }
    };

    return _transition(gd, transitionOpts, opts);
};

/**
 * Transition to a set of new data and layout properties from Plotly.react
 *
 * @param {DOM element} gd
 * @param {object} restyleFlags
 * - anim {'all'|'some'}
 * @param {object} relayoutFlags
 * - anim {'all'|'some'}
 * @param {object} oldFullLayout : old (pre Plotly.react) fullLayout
 */
plots.transitionFromReact = function(gd, restyleFlags, relayoutFlags, oldFullLayout) {
    var fullLayout = gd._fullLayout;
    var transitionOpts = fullLayout.transition;
    var opts = {};
    var axEdits = [];

    opts.prepareFn = function() {
        var subplots = fullLayout._plots;

        // no need to redraw at end of transition,
        // if all changes are animatable
        opts.redraw = false;
        if(restyleFlags.anim === 'some') opts.redraw = true;
        if(relayoutFlags.anim === 'some') opts.redraw = true;

        for(var k in subplots) {
            var plotinfo = subplots[k];
            var xa = plotinfo.xaxis;
            var ya = plotinfo.yaxis;
            var xr0 = oldFullLayout[xa._name].range.slice();
            var yr0 = oldFullLayout[ya._name].range.slice();
            var xr1 = xa.range.slice();
            var yr1 = ya.range.slice();

            xa.setScale();
            ya.setScale();

            var editX;
            if(xr0[0] !== xr1[0] || xr0[1] !== xr1[1]) {
                editX = {xr0: xr0, xr1: xr1};
            }

            var editY;
            if(yr0[0] !== yr1[0] || yr0[1] !== yr1[1]) {
                editY = {yr0: yr0, yr1: yr1};
            }

            if(editX || editY) {
                axEdits.push(Lib.extendFlat({plotinfo: plotinfo}, editX, editY));
            }
        }

        return Promise.resolve();
    };

    opts.runFn = function(makeCallback) {
        var fullData = gd._fullData;
        var fullLayout = gd._fullLayout;
        var basePlotModules = fullLayout._basePlotModules;

        var axisTransitionOpts;
        var traceTransitionOpts;
        var transitionedTraces;

        var allTraceIndices = [];
        for(var i = 0; i < fullData.length; i++) {
            allTraceIndices.push(i);
        }

        function transitionAxes() {
            for(var j = 0; j < basePlotModules.length; j++) {
                if(basePlotModules[j].transitionAxes) {
                    basePlotModules[j].transitionAxes(gd, axEdits, axisTransitionOpts, makeCallback);
                }
            }
        }

        function transitionTraces() {
            for(var j = 0; j < basePlotModules.length; j++) {
                basePlotModules[j].plot(gd, transitionedTraces, traceTransitionOpts, makeCallback);
            }
        }

        if(axEdits.length && restyleFlags.anim) {
            if(transitionOpts.ordering === 'traces first') {
                axisTransitionOpts = Lib.extendFlat({}, transitionOpts, {duration: 0});
                transitionedTraces = allTraceIndices;
                traceTransitionOpts = transitionOpts;
                transitionTraces();
                setTimeout(transitionAxes, transitionOpts.duration);
            } else {
                axisTransitionOpts = transitionOpts;
                transitionedTraces = null;
                traceTransitionOpts = Lib.extendFlat({}, transitionOpts, {duration: 0});
                transitionAxes();
                transitionTraces();
            }
        } else if(axEdits.length) {
            axisTransitionOpts = transitionOpts;
            transitionAxes();
        } else if(restyleFlags.anim) {
            transitionedTraces = allTraceIndices;
            traceTransitionOpts = transitionOpts;
            transitionTraces();
        }
    };

    return _transition(gd, transitionOpts, opts);
};

/**
 * trace/layout transition wrapper that works
 * for transitions initiated by Plotly.animate and Plotly.react.
 *
 * @param {DOM element} gd
 * @param {object} transitionOpts
 * @param {object} opts
 * - redraw {boolean}
 * - prepareFn {function} *should return a Promise*
 * - runFn {function} ran inside executeTransitions
 */
function _transition(gd, transitionOpts, opts) {
    var aborted = false;

    function executeCallbacks(list) {
        var p = Promise.resolve();
        if(!list) return p;
        while(list.length) {
            p = p.then((list.shift()));
        }
        return p;
    }

    function flushCallbacks(list) {
        if(!list) return;
        while(list.length) {
            list.shift();
        }
    }

    function executeTransitions() {
        gd.emit('plotly_transitioning', []);

        return new Promise(function(resolve) {
            // This flag is used to disabled things like autorange:
            gd._transitioning = true;

            // When instantaneous updates are coming through quickly, it's too much to simply disable
            // all interaction, so store this flag so we can disambiguate whether mouse interactions
            // should be fully disabled or not:
            if(transitionOpts.duration > 0) {
                gd._transitioningWithDuration = true;
            }

            // If another transition is triggered, this callback will be executed simply because it's
            // in the interruptCallbacks queue. If this transition completes, it will instead flush
            // that queue and forget about this callback.
            gd._transitionData._interruptCallbacks.push(function() {
                aborted = true;
            });

            if(opts.redraw) {
                gd._transitionData._interruptCallbacks.push(function() {
                    return Registry.call('redraw', gd);
                });
            }

            // Emit this and make sure it happens last:
            gd._transitionData._interruptCallbacks.push(function() {
                gd.emit('plotly_transitioninterrupted', []);
            });

            // Construct callbacks that are executed on transition end. This ensures the d3 transitions
            // are *complete* before anything else is done.
            var numCallbacks = 0;
            var numCompleted = 0;
            function makeCallback() {
                numCallbacks++;
                return function() {
                    numCompleted++;
                    // When all are complete, perform a redraw:
                    if(!aborted && numCompleted === numCallbacks) {
                        completeTransition(resolve);
                    }
                };
            }

            opts.runFn(makeCallback);

            // If nothing else creates a callback, then this will trigger the completion in the next tick:
            setTimeout(makeCallback());
        });
    }

    function completeTransition(callback) {
        // This a simple workaround for tests which purge the graph before animations
        // have completed. That's not a very common case, so this is the simplest
        // fix.
        if(!gd._transitionData) return;

        flushCallbacks(gd._transitionData._interruptCallbacks);

        return Promise.resolve().then(function() {
            if(opts.redraw) {
                return Registry.call('redraw', gd);
            }
        }).then(function() {
            // Set transitioning false again once the redraw has occurred. This is used, for example,
            // to prevent the trailing redraw from autoranging:
            gd._transitioning = false;
            gd._transitioningWithDuration = false;

            gd.emit('plotly_transitioned', []);
        }).then(callback);
    }

    function interruptPreviousTransitions() {
        // Fail-safe against purged plot:
        if(!gd._transitionData) return;

        // If a transition is interrupted, set this to false. At the moment, the only thing that would
        // interrupt a transition is another transition, so that it will momentarily be set to true
        // again, but this determines whether autorange or dragbox work, so it's for the sake of
        // cleanliness:
        gd._transitioning = false;

        return executeCallbacks(gd._transitionData._interruptCallbacks);
    }

    var seq = [
        plots.previousPromises,
        interruptPreviousTransitions,
        opts.prepareFn,
        plots.rehover,
        executeTransitions
    ];

    var transitionStarting = Lib.syncOrAsync(seq, gd);

    if(!transitionStarting || !transitionStarting.then) {
        transitionStarting = Promise.resolve();
    }

    return transitionStarting.then(function() { return gd; });
}

plots.doCalcdata = function(gd, traces) {
    var axList = axisIDs.list(gd);
    var fullData = gd._fullData;
    var fullLayout = gd._fullLayout;

    var trace, _module, i, j;

    // XXX: Is this correct? Needs a closer look so that *some* traces can be recomputed without
    // *all* needing doCalcdata:
    var calcdata = new Array(fullData.length);
    var oldCalcdata = (gd.calcdata || []).slice(0);
    gd.calcdata = calcdata;

    // extra helper variables

    // how many box/violins plots do we have (in case they're grouped)
    fullLayout._numBoxes = 0;
    fullLayout._numViolins = 0;

    // initialize violin per-scale-group stats container
    fullLayout._violinScaleGroupStats = {};

    // for calculating avg luminosity of heatmaps
    gd._hmpixcount = 0;
    gd._hmlumcount = 0;

    // for sharing colors across pies (and for legend)
    fullLayout._piecolormap = {};

    // If traces were specified and this trace was not included,
    // then transfer it over from the old calcdata:
    for(i = 0; i < fullData.length; i++) {
        if(Array.isArray(traces) && traces.indexOf(i) === -1) {
            calcdata[i] = oldCalcdata[i];
            continue;
        }
    }

    for(i = 0; i < fullData.length; i++) {
        trace = fullData[i];

        trace._arrayAttrs = PlotSchema.findArrayAttributes(trace);

        // keep track of trace extremes (for autorange) in here
        trace._extremes = {};
    }

    // add polar axes to axis list
    var polarIds = fullLayout._subplots.polar || [];
    for(i = 0; i < polarIds.length; i++) {
        axList.push(
            fullLayout[polarIds[i]].radialaxis,
            fullLayout[polarIds[i]].angularaxis
        );
    }

    setupAxisCategories(axList, fullData);

    var hasCalcTransform = false;

    // transform loop
    for(i = 0; i < fullData.length; i++) {
        trace = fullData[i];

        if(trace.visible === true && trace.transforms) {
            _module = trace._module;

            // we need one round of trace module calc before
            // the calc transform to 'fill in' the categories list
            // used for example in the data-to-coordinate method
            if(_module && _module.calc) {
                var cdi = _module.calc(gd, trace);

                // must clear scene 'batches', so that 2nd
                // _module.calc call starts from scratch
                if(cdi[0] && cdi[0].t && cdi[0].t._scene) {
                    delete cdi[0].t._scene.dirty;
                }
            }

            for(j = 0; j < trace.transforms.length; j++) {
                var transform = trace.transforms[j];

                _module = transformsRegistry[transform.type];
                if(_module && _module.calcTransform) {
                    trace._hasCalcTransform = true;
                    hasCalcTransform = true;
                    _module.calcTransform(gd, trace, transform);
                }
            }
        }
    }

    // clear stuff that should recomputed in 'regular' loop
    if(hasCalcTransform) setupAxisCategories(axList, fullData);

    function calci(i, isContainer) {
        trace = fullData[i];
        _module = trace._module;

        if(!!_module.isContainer !== isContainer) return;

        var cd = [];

        if(trace.visible === true) {

            // clear existing ref in case it got relinked
            delete trace._indexToPoints;
            // keep ref of index-to-points map object of the *last* enabled transform,
            // this index-to-points map object is required to determine the calcdata indices
            // that correspond to input indices (e.g. from 'selectedpoints')
            var transforms = trace.transforms || [];
            for(j = transforms.length - 1; j >= 0; j--) {
                if(transforms[j].enabled) {
                    trace._indexToPoints = transforms[j]._indexToPoints;
                    break;
                }
            }

            if(_module && _module.calc) {
                cd = _module.calc(gd, trace);
            }
        }

        // Make sure there is a first point.
        //
        // This ensures there is a calcdata item for every trace,
        // even if cartesian logic doesn't handle it (for things like legends).
        if(!Array.isArray(cd) || !cd[0]) {
            cd = [{x: BADNUM, y: BADNUM}];
        }

        // add the trace-wide properties to the first point,
        // per point properties to every point
        // t is the holder for trace-wide properties
        if(!cd[0].t) cd[0].t = {};
        cd[0].trace = trace;

        calcdata[i] = cd;
    }

    // 'regular' loop - make sure container traces (eg carpet) calc before
    // contained traces (eg contourcarpet)
    for(i = 0; i < fullData.length; i++) calci(i, true);
    for(i = 0; i < fullData.length; i++) calci(i, false);

    doCrossTraceCalc(gd);

    Registry.getComponentMethod('fx', 'calc')(gd);
    Registry.getComponentMethod('errorbars', 'calc')(gd);
};

function setupAxisCategories(axList, fullData) {
    for(var i = 0; i < axList.length; i++) {
        var ax = axList[i];
        ax.clearCalc();
        if(ax.type === 'multicategory') {
            ax.setupMultiCategory(fullData);
        }
    }
}

function doCrossTraceCalc(gd) {
    var fullLayout = gd._fullLayout;
    var modules = fullLayout._visibleModules;
    var hash = {};
    var i, j, k;

    // position and range calculations for traces that
    // depend on each other ie bars (stacked or grouped)
    // and boxes (grouped) push each other out of the way

    for(j = 0; j < modules.length; j++) {
        var _module = modules[j];
        var fn = _module.crossTraceCalc;
        if(fn) {
            var spType = _module.basePlotModule.name;
            if(hash[spType]) {
                Lib.pushUnique(hash[spType], fn);
            } else {
                hash[spType] = [fn];
            }
        }
    }

    for(k in hash) {
        var methods = hash[k];
        var subplots = fullLayout._subplots[k];

        if(Array.isArray(subplots)) {
            for(i = 0; i < subplots.length; i++) {
                var sp = subplots[i];
                var spInfo = k === 'cartesian' ?
                    fullLayout._plots[sp] :
                    fullLayout[sp];

                for(j = 0; j < methods.length; j++) {
                    methods[j](gd, spInfo, sp);
                }
            }
        }
        else {
            for(j = 0; j < methods.length; j++) {
                methods[j](gd);
            }
        }
    }
}

plots.rehover = function(gd) {
    if(gd._fullLayout._rehover) {
        gd._fullLayout._rehover();
    }
};

plots.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subplotLayout) {
    var traceHashOld = subplot.traceHash;
    var traceHash = {};
    var i;

    // build up moduleName -> calcData hash
    for(i = 0; i < subplotCalcData.length; i++) {
        var calcTraces = subplotCalcData[i];
        var trace = calcTraces[0].trace;

        // skip over visible === false traces
        // as they don't have `_module` ref
        if(trace.visible) {
            traceHash[trace.type] = traceHash[trace.type] || [];
            traceHash[trace.type].push(calcTraces);
        }
    }

    // when a trace gets deleted, make sure that its module's
    // plot method is called so that it is properly
    // removed from the DOM.
    for(var moduleNameOld in traceHashOld) {
        if(!traceHash[moduleNameOld]) {
            var fakeCalcTrace = traceHashOld[moduleNameOld][0];
            var fakeTrace = fakeCalcTrace[0].trace;

            fakeTrace.visible = false;
            traceHash[moduleNameOld] = [fakeCalcTrace];
        }
    }

    // call module plot method
    for(var moduleName in traceHash) {
        var moduleCalcData = traceHash[moduleName];
        var _module = moduleCalcData[0][0].trace._module;

        _module.plot(gd, subplot, Lib.filterVisible(moduleCalcData), subplotLayout);
    }

    // update moduleName -> calcData hash
    subplot.traceHash = traceHash;
};

},{"../components/color":574,"../constants/numerical":674,"../lib":697,"../plot_api/plot_schema":734,"../plot_api/plot_template":735,"../plots/cartesian/axis_ids":748,"../registry":826,"./animation_attributes":740,"./attributes":742,"./command":769,"./font_attributes":771,"./frame_attributes":772,"./layout_attributes":798,"d3":151,"fast-isnumeric":218}],808:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    attr: 'subplot',
    name: 'polar',

    axisNames: ['angularaxis', 'radialaxis'],
    axisName2dataArray: {angularaxis: 'theta', radialaxis: 'r'},

    layerNames: [
        'draglayer',
        'plotbg',
        'backplot',
        'angular-grid',
        'radial-grid',
        'frontplot',
        'angular-line',
        'radial-line',
        'angular-axis',
        'radial-axis'
    ],

    radialDragBoxSize: 50,
    angularDragBoxSize: 30,
    cornerLen: 25,
    cornerHalfWidth: 2,

    // pixels to move mouse before you stop clamping to starting point
    MINDRAG: 8,
    // smallest radial distance [px] allowed for a zoombox
    MINZOOM: 20,
    // distance [px] off (r=0) or (r=radius) where we transition
    // from single-sided to two-sided radial zoom
    OFFEDGE: 20
};

},{}],809:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var polygonTester = _dereq_('../../lib/polygon').tester;

var findIndexOfMin = Lib.findIndexOfMin;
var isAngleInsideSector = Lib.isAngleInsideSector;
var angleDelta = Lib.angleDelta;
var angleDist = Lib.angleDist;

/**
 * is pt (r,a) inside polygon made up vertices at angles 'vangles'
 * inside a given polar sector
 *
 * @param {number} r : pt's radial coordinate
 * @param {number} a : pt's angular coordinate in *radians*
 * @param {2-item array} rBnds : sector's radial bounds
 * @param {2-item array} aBnds : sector's angular bounds *radians*
 * @param {array} vangles : angles of polygon vertices in *radians*
 * @return {boolean}
 */
function isPtInsidePolygon(r, a, rBnds, aBnds, vangles) {
    if(!isAngleInsideSector(a, aBnds)) return false;

    var r0, r1;

    if(rBnds[0] < rBnds[1]) {
        r0 = rBnds[0];
        r1 = rBnds[1];
    } else {
        r0 = rBnds[1];
        r1 = rBnds[0];
    }

    var polygonIn = polygonTester(makePolygon(r0, aBnds[0], aBnds[1], vangles));
    var polygonOut = polygonTester(makePolygon(r1, aBnds[0], aBnds[1], vangles));
    var xy = [r * Math.cos(a), r * Math.sin(a)];
    return polygonOut.contains(xy) && !polygonIn.contains(xy);
}

// find intersection of 'v0' <-> 'v1' edge with a ray at angle 'a'
// (i.e. a line that starts from the origin at angle 'a')
// given an (xp,yp) pair on the 'v0' <-> 'v1' line
// (N.B. 'v0' and 'v1' are angles in radians)
function findIntersectionXY(v0, v1, a, xpyp) {
    var xstar, ystar;

    var xp = xpyp[0];
    var yp = xpyp[1];
    var dsin = clampTiny(Math.sin(v1) - Math.sin(v0));
    var dcos = clampTiny(Math.cos(v1) - Math.cos(v0));
    var tanA = Math.tan(a);
    var cotanA = clampTiny(1 / tanA);
    var m = dsin / dcos;
    var b = yp - m * xp;

    if(cotanA) {
        if(dsin && dcos) {
            // given
            //  g(x) := v0 -> v1 line = m*x + b
            //  h(x) := ray at angle 'a' = m*x = tanA*x
            // solve g(xstar) = h(xstar)
            xstar = b / (tanA - m);
            ystar = tanA * xstar;
        } else if(dcos) {
            // horizontal v0 -> v1
            xstar = yp * cotanA;
            ystar = yp;
        } else {
            // vertical v0 -> v1
            xstar = xp;
            ystar = xp * tanA;
        }
    } else {
        // vertical ray
        if(dsin && dcos) {
            xstar = 0;
            ystar = b;
        } else if(dcos) {
            xstar = 0;
            ystar = yp;
        } else {
            // does this case exists?
            xstar = ystar = NaN;
        }
    }

    return [xstar, ystar];
}

// solves l^2 = (f(x)^2 - yp)^2 + (x - xp)^2
// rearranged into 0 = a*x^2 + b * x + c
//
// where f(x) = m*x + t + yp
// and   (x0, x1) = (-b +/- del) / (2*a)
function findXYatLength(l, m, xp, yp) {
    var t = -m * xp;
    var a = m * m + 1;
    var b = 2 * (m * t - xp);
    var c = t * t + xp * xp - l * l;
    var del = Math.sqrt(b * b - 4 * a * c);
    var x0 = (-b + del) / (2 * a);
    var x1 = (-b - del) / (2 * a);
    return [
        [x0, m * x0 + t + yp],
        [x1, m * x1 + t + yp]
    ];
}

function makeRegularPolygon(r, vangles) {
    var len = vangles.length;
    var vertices = new Array(len + 1);
    var i;
    for(i = 0; i < len; i++) {
        var va = vangles[i];
        vertices[i] = [r * Math.cos(va), r * Math.sin(va)];
    }
    vertices[i] = vertices[0].slice();
    return vertices;
}

function makeClippedPolygon(r, a0, a1, vangles) {
    var len = vangles.length;
    var vertices = [];
    var i, j;

    function a2xy(a) {
        return [r * Math.cos(a), r * Math.sin(a)];
    }

    function findXY(va0, va1, s) {
        return findIntersectionXY(va0, va1, s, a2xy(va0));
    }

    function cycleIndex(ind) {
        return Lib.mod(ind, len);
    }

    function isInside(v) {
        return isAngleInsideSector(v, [a0, a1]);
    }

    // find index in sector closest to a0
    // use it to find intersection of v[i0] <-> v[i0-1] edge with sector radius
    var i0 = findIndexOfMin(vangles, function(v) {
        return isInside(v) ? angleDist(v, a0) : Infinity;
    });
    var xy0 = findXY(vangles[i0], vangles[cycleIndex(i0 - 1)], a0);
    vertices.push(xy0);

    // fill in in-sector vertices
    for(i = i0, j = 0; j < len; i++, j++) {
        var va = vangles[cycleIndex(i)];
        if(!isInside(va)) break;
        vertices.push(a2xy(va));
    }

    // find index in sector closest to a1,
    // use it to find intersection of v[iN] <-> v[iN+1] edge with sector radius
    var iN = findIndexOfMin(vangles, function(v) {
        return isInside(v) ? angleDist(v, a1) : Infinity;
    });
    var xyN = findXY(vangles[iN], vangles[cycleIndex(iN + 1)], a1);
    vertices.push(xyN);

    vertices.push([0, 0]);
    vertices.push(vertices[0].slice());

    return vertices;
}

function makePolygon(r, a0, a1, vangles) {
    return Lib.isFullCircle([a0, a1]) ?
        makeRegularPolygon(r, vangles) :
        makeClippedPolygon(r, a0, a1, vangles);
}

function findPolygonOffset(r, a0, a1, vangles) {
    var minX = Infinity;
    var minY = Infinity;
    var vertices = makePolygon(r, a0, a1, vangles);

    for(var i = 0; i < vertices.length; i++) {
        var v = vertices[i];
        minX = Math.min(minX, v[0]);
        minY = Math.min(minY, -v[1]);
    }
    return [minX, minY];
}

/**
 * find vertex angles (in 'vangles') the enclose angle 'a'
 *
 * @param {number} a : angle in *radians*
 * @param {array} vangles : angles of polygon vertices in *radians*
 * @return {2-item array}
 */
function findEnclosingVertexAngles(a, vangles) {
    var minFn = function(v) {
        var adelta = angleDelta(v, a);
        return adelta > 0 ? adelta : Infinity;
    };
    var i0 = findIndexOfMin(vangles, minFn);
    var i1 = Lib.mod(i0 + 1, vangles.length);
    return [vangles[i0], vangles[i1]];
}

// to more easily catch 'almost zero' numbers in if-else blocks
function clampTiny(v) {
    return Math.abs(v) > 1e-10 ? v : 0;
}

function transformForSVG(pts0, cx, cy) {
    cx = cx || 0;
    cy = cy || 0;

    var len = pts0.length;
    var pts1 = new Array(len);

    for(var i = 0; i < len; i++) {
        var pt = pts0[i];
        pts1[i] = [cx + pt[0], cy - pt[1]];
    }
    return pts1;
}

/**
 * path polygon
 *
 * @param {number} r : polygon 'radius'
 * @param {number} a0 : first angular coordinate in *radians*
 * @param {number} a1 : second angular coordinate in *radians*
 * @param {array} vangles : angles of polygon vertices in *radians*
 * @param {number (optional)} cx : x coordinate of center
 * @param {number (optional)} cy : y coordinate of center
 * @return {string} svg path
 *
 */
function pathPolygon(r, a0, a1, vangles, cx, cy) {
    var poly = makePolygon(r, a0, a1, vangles);
    return 'M' + transformForSVG(poly, cx, cy).join('L');
}

/**
 * path a polygon 'annulus'
 * i.e. a polygon with a concentric hole
 *
 * N.B. this routine uses the evenodd SVG rule
 *
 * @param {number} r0 : first radial coordinate
 * @param {number} r1 : second radial coordinate
 * @param {number} a0 : first angular coordinate in *radians*
 * @param {number} a1 : second angular coordinate in *radians*
 * @param {array} vangles : angles of polygon vertices in *radians*
 * @param {number (optional)} cx : x coordinate of center
 * @param {number (optional)} cy : y coordinate of center
 * @return {string} svg path
 *
 */
function pathPolygonAnnulus(r0, r1, a0, a1, vangles, cx, cy) {
    var rStart, rEnd;

    if(r0 < r1) {
        rStart = r0;
        rEnd = r1;
    } else {
        rStart = r1;
        rEnd = r0;
    }

    var inner = transformForSVG(makePolygon(rStart, a0, a1, vangles), cx, cy);
    var outer = transformForSVG(makePolygon(rEnd, a0, a1, vangles), cx, cy);
    return 'M' + outer.reverse().join('L') + 'M' + inner.join('L');
}

module.exports = {
    isPtInsidePolygon: isPtInsidePolygon,
    findPolygonOffset: findPolygonOffset,
    findEnclosingVertexAngles: findEnclosingVertexAngles,
    findIntersectionXY: findIntersectionXY,
    findXYatLength: findXYatLength,
    clampTiny: clampTiny,
    pathPolygon: pathPolygon,
    pathPolygonAnnulus: pathPolygonAnnulus
};

},{"../../lib":697,"../../lib/polygon":709}],810:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var getSubplotCalcData = _dereq_('../get_data').getSubplotCalcData;
var counterRegex = _dereq_('../../lib').counterRegex;

var createPolar = _dereq_('./polar');
var constants = _dereq_('./constants');

var attr = constants.attr;
var name = constants.name;
var counter = counterRegex(name);

var attributes = {};
attributes[attr] = {
    valType: 'subplotid',
    
    dflt: name,
    editType: 'calc',
    
};

function plot(gd) {
    var fullLayout = gd._fullLayout;
    var calcData = gd.calcdata;
    var subplotIds = fullLayout._subplots[name];

    for(var i = 0; i < subplotIds.length; i++) {
        var id = subplotIds[i];
        var subplotCalcData = getSubplotCalcData(calcData, name, id);
        var subplot = fullLayout[id]._subplot;

        if(!subplot) {
            subplot = createPolar(gd, id);
            fullLayout[id]._subplot = subplot;
        }

        subplot.plot(subplotCalcData, fullLayout, gd._promises);
    }
}

function clean(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var oldIds = oldFullLayout._subplots[name] || [];
    var hadGl = (oldFullLayout._has && oldFullLayout._has('gl'));
    var hasGl = (newFullLayout._has && newFullLayout._has('gl'));
    var mustCleanScene = hadGl && !hasGl;

    for(var i = 0; i < oldIds.length; i++) {
        var id = oldIds[i];
        var oldSubplot = oldFullLayout[id]._subplot;

        if(!newFullLayout[id] && !!oldSubplot) {
            oldSubplot.framework.remove();
            oldSubplot.layers['radial-axis-title'].remove();

            for(var k in oldSubplot.clipPaths) {
                oldSubplot.clipPaths[k].remove();
            }
        }

        if(mustCleanScene && oldSubplot._scene) {
            oldSubplot._scene.destroy();
            oldSubplot._scene = null;
        }
    }
}

module.exports = {
    attr: attr,
    name: name,
    idRoot: name,
    idRegex: counter,
    attrRegex: counter,
    attributes: attributes,
    layoutAttributes: _dereq_('./layout_attributes'),
    supplyLayoutDefaults: _dereq_('./layout_defaults'),
    plot: plot,
    clean: clean,
    toSVG: _dereq_('../cartesian').toSVG
};

},{"../../lib":697,"../cartesian":756,"../get_data":781,"./constants":808,"./layout_attributes":811,"./layout_defaults":812,"./polar":819}],811:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorAttrs = _dereq_('../../components/color/attributes');
var axesAttrs = _dereq_('../cartesian/layout_attributes');
var domainAttrs = _dereq_('../domain').attributes;
var extendFlat = _dereq_('../../lib').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;

var axisLineGridAttr = overrideAll({
    color: axesAttrs.color,
    showline: extendFlat({}, axesAttrs.showline, {dflt: true}),
    linecolor: axesAttrs.linecolor,
    linewidth: axesAttrs.linewidth,
    showgrid: extendFlat({}, axesAttrs.showgrid, {dflt: true}),
    gridcolor: axesAttrs.gridcolor,
    gridwidth: axesAttrs.gridwidth

    // TODO add spike* attributes down the road

    // should we add zeroline* attributes?

}, 'plot', 'from-root');

var axisTickAttrs = overrideAll({
    tickmode: axesAttrs.tickmode,
    nticks: axesAttrs.nticks,
    tick0: axesAttrs.tick0,
    dtick: axesAttrs.dtick,
    tickvals: axesAttrs.tickvals,
    ticktext: axesAttrs.ticktext,
    ticks: axesAttrs.ticks,
    ticklen: axesAttrs.ticklen,
    tickwidth: axesAttrs.tickwidth,
    tickcolor: axesAttrs.tickcolor,
    showticklabels: axesAttrs.showticklabels,
    showtickprefix: axesAttrs.showtickprefix,
    tickprefix: axesAttrs.tickprefix,
    showticksuffix: axesAttrs.showticksuffix,
    ticksuffix: axesAttrs.ticksuffix,
    showexponent: axesAttrs.showexponent,
    exponentformat: axesAttrs.exponentformat,
    separatethousands: axesAttrs.separatethousands,
    tickfont: axesAttrs.tickfont,
    tickangle: axesAttrs.tickangle,
    tickformat: axesAttrs.tickformat,
    tickformatstops: axesAttrs.tickformatstops,
    layer: axesAttrs.layer
}, 'plot', 'from-root');

var radialAxisAttrs = {
    visible: extendFlat({}, axesAttrs.visible, {dflt: true}),
    type: extendFlat({}, axesAttrs.type, {
        values: ['-', 'linear', 'log', 'date', 'category']
    }),

    autorange: extendFlat({}, axesAttrs.autorange, {editType: 'plot'}),
    rangemode: {
        valType: 'enumerated',
        values: ['tozero', 'nonnegative', 'normal'],
        dflt: 'tozero',
        
        editType: 'calc',
        
    },
    range: extendFlat({}, axesAttrs.range, {
        items: [
            {valType: 'any', editType: 'plot', impliedEdits: {'^autorange': false}},
            {valType: 'any', editType: 'plot', impliedEdits: {'^autorange': false}}
        ],
        editType: 'plot'
    }),

    categoryorder: axesAttrs.categoryorder,
    categoryarray: axesAttrs.categoryarray,

    angle: {
        valType: 'angle',
        editType: 'plot',
        
        
    },

    side: {
        valType: 'enumerated',
        // TODO add 'center' for `showline: false` radial axes
        values: ['clockwise', 'counterclockwise'],
        dflt: 'clockwise',
        editType: 'plot',
        
        
    },


    title: overrideAll(axesAttrs.title, 'plot', 'from-root'),
    // might need a 'titleside' and even 'titledirection' down the road

    hoverformat: axesAttrs.hoverformat,

    uirevision: {
        valType: 'any',
        
        editType: 'none',
        
    },

    editType: 'calc',

    _deprecated: {
        title: axesAttrs._deprecated.title,
        titlefont: axesAttrs._deprecated.titlefont
    }
};

// radial title is not gui-editable, so it needs dflt: '', similar to carpet axes.
radialAxisAttrs.title.text.dflt = '';

extendFlat(
    radialAxisAttrs,

    // N.B. radialaxis grid lines are circular,
    // but radialaxis lines are straight from circle center to outer bound
    axisLineGridAttr,
    axisTickAttrs
);

var angularAxisAttrs = {
    visible: extendFlat({}, axesAttrs.visible, {dflt: true}),
    type: {
        valType: 'enumerated',
        // 'linear' should maybe be called 'angle' or 'angular' here
        // to make clear that axis here is periodic and more tightly match
        // `thetaunit`?
        //
        // skip 'date' for first push
        // no 'log' for now
        values: ['-', 'linear', 'category'],
        dflt: '-',
        
        editType: 'calc',
        _noTemplating: true,
        
    },

    categoryorder: axesAttrs.categoryorder,
    categoryarray: axesAttrs.categoryarray,

    thetaunit: {
        valType: 'enumerated',
        values: ['radians', 'degrees'],
        dflt: 'degrees',
        
        editType: 'calc',
        
    },

    period: {
        valType: 'number',
        editType: 'calc',
        min: 0,
        
        
        // Examples for date axes:
        //
        // - period that equals the timeseries length
        //  http://flowingdata.com/2017/01/24/one-dataset-visualized-25-ways/18-polar-coordinates/
        // - and 1-year periods (focusing on seasonal change0
        //  http://otexts.org/fpp2/seasonal-plots.html
        //  https://blogs.scientificamerican.com/sa-visual/why-are-so-many-babies-born-around-8-00-a-m/
        //  http://www.seasonaladjustment.com/2012/09/05/clock-plot-visualising-seasonality-using-r-and-ggplot2-part-3/
        //  https://i.pinimg.com/736x/49/b9/72/49b972ccb3206a1a6d6f870dac543280.jpg
        //  https://www.climate-lab-book.ac.uk/spirals/
    },

    direction: {
        valType: 'enumerated',
        values: ['counterclockwise', 'clockwise'],
        dflt: 'counterclockwise',
        
        editType: 'calc',
        
    },

    rotation: {
        valType: 'angle',
        editType: 'calc',
        
        
    },

    hoverformat: axesAttrs.hoverformat,

    uirevision: {
        valType: 'any',
        
        editType: 'none',
        
    },

    editType: 'calc'
};

extendFlat(
    angularAxisAttrs,

    // N.B. angular grid lines are straight lines from circle center to outer bound
    // the angular line is circular bounding the polar plot area.
    axisLineGridAttr,

    // N.B. ticksuffix defaults to '°' for angular axes with `thetaunit: 'degrees'`
    axisTickAttrs
);

module.exports = {
    // TODO for x/y/zoom system for paper-based zooming:
    // x: {},
    // y: {},
    // zoom: {},

    domain: domainAttrs({name: 'polar', editType: 'plot'}),

    sector: {
        valType: 'info_array',
        items: [
            {valType: 'number', editType: 'plot'},
            {valType: 'number', editType: 'plot'}
        ],
        dflt: [0, 360],
        
        editType: 'plot',
        
    },
    hole: {
        valType: 'number',
        min: 0,
        max: 1,
        dflt: 0,
        editType: 'plot',
        
        
    },

    bgcolor: {
        valType: 'color',
        
        editType: 'plot',
        dflt: colorAttrs.background,
        
    },

    radialaxis: radialAxisAttrs,
    angularaxis: angularAxisAttrs,

    gridshape: {
        valType: 'enumerated',
        values: ['circular', 'linear'],
        dflt: 'circular',
        
        editType: 'plot',
        
    },

    // TODO maybe?
    // annotations:

    uirevision: {
        valType: 'any',
        
        editType: 'none',
        
    },

    editType: 'calc'
};

},{"../../components/color/attributes":573,"../../lib":697,"../../plot_api/edit_types":728,"../cartesian/layout_attributes":757,"../domain":770}],812:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Color = _dereq_('../../components/color');
var Template = _dereq_('../../plot_api/plot_template');

var handleSubplotDefaults = _dereq_('../subplot_defaults');
var getSubplotData = _dereq_('../get_data').getSubplotData;

var handleTickValueDefaults = _dereq_('../cartesian/tick_value_defaults');
var handleTickMarkDefaults = _dereq_('../cartesian/tick_mark_defaults');
var handleTickLabelDefaults = _dereq_('../cartesian/tick_label_defaults');
var handleCategoryOrderDefaults = _dereq_('../cartesian/category_order_defaults');
var handleLineGridDefaults = _dereq_('../cartesian/line_grid_defaults');
var autoType = _dereq_('../cartesian/axis_autotype');

var layoutAttributes = _dereq_('./layout_attributes');
var setConvert = _dereq_('./set_convert');
var constants = _dereq_('./constants');
var axisNames = constants.axisNames;

function handleDefaults(contIn, contOut, coerce, opts) {
    var bgColor = coerce('bgcolor');
    opts.bgColor = Color.combine(bgColor, opts.paper_bgcolor);

    var sector = coerce('sector');
    coerce('hole');

    // could optimize, subplotData is not always needed!
    var subplotData = getSubplotData(opts.fullData, constants.name, opts.id);
    var layoutOut = opts.layoutOut;
    var axName;

    function coerceAxis(attr, dflt) {
        return coerce(axName + '.' + attr, dflt);
    }

    for(var i = 0; i < axisNames.length; i++) {
        axName = axisNames[i];

        if(!Lib.isPlainObject(contIn[axName])) {
            contIn[axName] = {};
        }

        var axIn = contIn[axName];
        var axOut = Template.newContainer(contOut, axName);
        axOut._id = axOut._name = axName;
        axOut._attr = opts.id + '.' + axName;
        axOut._traceIndices = subplotData.map(function(t) { return t._expandedIndex; });

        var dataAttr = constants.axisName2dataArray[axName];
        var axType = handleAxisTypeDefaults(axIn, axOut, coerceAxis, subplotData, dataAttr);

        handleCategoryOrderDefaults(axIn, axOut, coerceAxis, {
            axData: subplotData,
            dataAttr: dataAttr
        });

        var visible = coerceAxis('visible');
        setConvert(axOut, contOut, layoutOut);

        coerceAxis('uirevision', contOut.uirevision);

        var dfltColor;
        var dfltFontColor;

        if(visible) {
            dfltColor = coerceAxis('color');
            dfltFontColor = (dfltColor === axIn.color) ? dfltColor : opts.font.color;
        }

        // We don't want to make downstream code call ax.setScale,
        // as both radial and angular axes don't have a set domain.
        // Furthermore, angular axes don't have a set range.
        //
        // Mocked domains and ranges are set by the polar subplot instances,
        // but Axes.findExtremes uses the sign of _m to determine which padding value
        // to use.
        //
        // By setting, _m to 1 here, we make Axes.findExtremes think that
        // range[1] > range[0], and vice-versa for `autorange: 'reversed'` below.
        axOut._m = 1;

        switch(axName) {
            case 'radialaxis':
                var autoRange = coerceAxis('autorange', !axOut.isValidRange(axIn.range));
                axIn.autorange = autoRange;
                if(autoRange && (axType === 'linear' || axType === '-')) coerceAxis('rangemode');
                if(autoRange === 'reversed') axOut._m = -1;

                coerceAxis('range');
                axOut.cleanRange('range', {dfltRange: [0, 1]});

                if(visible) {
                    coerceAxis('side');
                    coerceAxis('angle', sector[0]);

                    coerceAxis('title.text');
                    Lib.coerceFont(coerceAxis, 'title.font', {
                        family: opts.font.family,
                        size: Math.round(opts.font.size * 1.2),
                        color: dfltFontColor
                    });
                }
                break;

            case 'angularaxis':
                // We do not support 'true' date angular axes yet,
                // users can still plot dates on angular axes by setting
                // `angularaxis.type: 'category'`.
                //
                // Here, if a date angular axes is detected, we make
                // all its corresponding traces invisible, so that
                // when we do add support for data angular axes, the new
                // behavior won't conflict with existing behavior
                if(axType === 'date') {
                    Lib.log('Polar plots do not support date angular axes yet.');

                    for(var j = 0; j < subplotData.length; j++) {
                        subplotData[j].visible = false;
                    }

                    // turn this into a 'dummy' linear axis so that
                    // the subplot still renders ok
                    axType = axIn.type = axOut.type = 'linear';
                }

                if(axType === 'linear') {
                    coerceAxis('thetaunit');
                } else {
                    coerceAxis('period');
                }

                var direction = coerceAxis('direction');
                coerceAxis('rotation', {counterclockwise: 0, clockwise: 90}[direction]);
                break;
        }

        if(visible) {
            handleTickValueDefaults(axIn, axOut, coerceAxis, axOut.type);
            handleTickLabelDefaults(axIn, axOut, coerceAxis, axOut.type, {
                tickSuffixDflt: axOut.thetaunit === 'degrees' ? '°' : undefined
            });
            handleTickMarkDefaults(axIn, axOut, coerceAxis, {outerTicks: true});

            var showTickLabels = coerceAxis('showticklabels');
            if(showTickLabels) {
                Lib.coerceFont(coerceAxis, 'tickfont', {
                    family: opts.font.family,
                    size: opts.font.size,
                    color: dfltFontColor
                });
                coerceAxis('tickangle');
                coerceAxis('tickformat');
            }

            handleLineGridDefaults(axIn, axOut, coerceAxis, {
                dfltColor: dfltColor,
                bgColor: opts.bgColor,
                // default grid color is darker here (60%, vs cartesian default ~91%)
                // because the grid is not square so the eye needs heavier cues to follow
                blend: 60,
                showLine: true,
                showGrid: true,
                noZeroLine: true,
                attributes: layoutAttributes[axName]
            });

            coerceAxis('layer');
        }

        if(axType !== 'category') coerceAxis('hoverformat');

        axOut._input = axIn;
    }

    if(contOut.angularaxis.type === 'category') {
        coerce('gridshape');
    }
}

function handleAxisTypeDefaults(axIn, axOut, coerce, subplotData, dataAttr) {
    var axType = coerce('type');

    if(axType === '-') {
        var trace;

        for(var i = 0; i < subplotData.length; i++) {
            if(subplotData[i].visible) {
                trace = subplotData[i];
                break;
            }
        }

        if(trace && trace[dataAttr]) {
            axOut.type = autoType(trace[dataAttr], 'gregorian');
        }

        if(axOut.type === '-') {
            axOut.type = 'linear';
        } else {
            // copy autoType back to input axis
            // note that if this object didn't exist
            // in the input layout, we have to put it in
            // this happens in the main supplyDefaults function
            axIn.type = axOut.type;
        }
    }

    return axOut.type;
}

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
    handleSubplotDefaults(layoutIn, layoutOut, fullData, {
        type: constants.name,
        attributes: layoutAttributes,
        handleDefaults: handleDefaults,
        font: layoutOut.font,
        paper_bgcolor: layoutOut.paper_bgcolor,
        fullData: fullData,
        layoutOut: layoutOut
    });
};

},{"../../components/color":574,"../../lib":697,"../../plot_api/plot_template":735,"../cartesian/axis_autotype":746,"../cartesian/category_order_defaults":749,"../cartesian/line_grid_defaults":759,"../cartesian/tick_label_defaults":764,"../cartesian/tick_mark_defaults":765,"../cartesian/tick_value_defaults":766,"../get_data":781,"../subplot_defaults":821,"./constants":808,"./layout_attributes":811,"./set_convert":820}],813:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterAttrs = _dereq_('../../../traces/scatter/attributes');
var scatterMarkerAttrs = scatterAttrs.marker;
var extendFlat = _dereq_('../../../lib/extend').extendFlat;

var deprecationWarning = [
    'Area traces are deprecated!',
    'Please switch to the *barpolar* trace type.'
].join(' ');

module.exports = {
    r: extendFlat({}, scatterAttrs.r, {
        
    }),
    t: extendFlat({}, scatterAttrs.t, {
        
    }),
    marker: {
        color: extendFlat({}, scatterMarkerAttrs.color, {
            
        }),
        size: extendFlat({}, scatterMarkerAttrs.size, {
            
        }),
        symbol: extendFlat({}, scatterMarkerAttrs.symbol, {
            
        }),
        opacity: extendFlat({}, scatterMarkerAttrs.opacity, {
            
        }),
        editType: 'calc'
    }
};

},{"../../../lib/extend":687,"../../../traces/scatter/attributes":1048}],814:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var axesAttrs = _dereq_('../../cartesian/layout_attributes');
var extendFlat = _dereq_('../../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../../plot_api/edit_types').overrideAll;

var deprecationWarning = [
    'Legacy polar charts are deprecated!',
    'Please switch to *polar* subplots.'
].join(' ');

var domainAttr = extendFlat({}, axesAttrs.domain, {
    
});

function mergeAttrs(axisName, nonCommonAttrs) {
    var commonAttrs = {
        showline: {
            valType: 'boolean',
            
            
        },
        showticklabels: {
            valType: 'boolean',
            
            
        },
        tickorientation: {
            valType: 'enumerated',
            values: ['horizontal', 'vertical'],
            
            
        },
        ticklen: {
            valType: 'number',
            min: 0,
            
            
        },
        tickcolor: {
            valType: 'color',
            
            
        },
        ticksuffix: {
            valType: 'string',
            
            
        },
        endpadding: {
            valType: 'number',
            
            description: deprecationWarning,
        },
        visible: {
            valType: 'boolean',
            
            
        }
    };

    return extendFlat({}, nonCommonAttrs, commonAttrs);
}

module.exports = overrideAll({
    radialaxis: mergeAttrs('radial', {
        range: {
            valType: 'info_array',
            
            items: [
                { valType: 'number' },
                { valType: 'number' }
            ],
            
        },
        domain: domainAttr,
        orientation: {
            valType: 'number',
            
            
        }
    }),

    angularaxis: mergeAttrs('angular', {
        range: {
            valType: 'info_array',
            
            items: [
                { valType: 'number', dflt: 0 },
                { valType: 'number', dflt: 360 }
            ],
            
        },
        domain: domainAttr
    }),

    // attributes that appear at layout root
    layout: {
        direction: {
            valType: 'enumerated',
            values: ['clockwise', 'counterclockwise'],
            
            
        },
        orientation: {
            valType: 'angle',
            
            
        }
    }
}, 'plot', 'nested');

},{"../../../lib/extend":687,"../../../plot_api/edit_types":728,"../../cartesian/layout_attributes":757}],815:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Polar = module.exports = _dereq_('./micropolar');

Polar.manager = _dereq_('./micropolar_manager');

},{"./micropolar":816,"./micropolar_manager":817}],816:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

var d3 = _dereq_('d3');
var Lib = _dereq_('../../../lib');
var extendDeepAll = Lib.extendDeepAll;
var MID_SHIFT = _dereq_('../../../constants/alignment').MID_SHIFT;

var µ = module.exports = { version: '0.2.2' };

µ.Axis = function module() {
    var config = {
        data: [],
        layout: {}
    }, inputConfig = {}, liveConfig = {};
    var svg, container, dispatch = d3.dispatch('hover'), radialScale, angularScale;
    var exports = {};
    function render(_container) {
        container = _container || container;
        var data = config.data;
        var axisConfig = config.layout;
        if (typeof container == 'string' || container.nodeName) container = d3.select(container);
        container.datum(data).each(function(_data, _index) {
            var dataOriginal = _data.slice();
            liveConfig = {
                data: µ.util.cloneJson(dataOriginal),
                layout: µ.util.cloneJson(axisConfig)
            };
            var colorIndex = 0;
            dataOriginal.forEach(function(d, i) {
                if (!d.color) {
                    d.color = axisConfig.defaultColorRange[colorIndex];
                    colorIndex = (colorIndex + 1) % axisConfig.defaultColorRange.length;
                }
                if (!d.strokeColor) {
                    d.strokeColor = d.geometry === 'LinePlot' ? d.color : d3.rgb(d.color).darker().toString();
                }
                liveConfig.data[i].color = d.color;
                liveConfig.data[i].strokeColor = d.strokeColor;
                liveConfig.data[i].strokeDash = d.strokeDash;
                liveConfig.data[i].strokeSize = d.strokeSize;
            });
            var data = dataOriginal.filter(function(d, i) {
                var visible = d.visible;
                return typeof visible === 'undefined' || visible === true;
            });
            var isStacked = false;
            var dataWithGroupId = data.map(function(d, i) {
                isStacked = isStacked || typeof d.groupId !== 'undefined';
                return d;
            });
            if (isStacked) {
                var grouped = d3.nest().key(function(d, i) {
                    return typeof d.groupId != 'undefined' ? d.groupId : 'unstacked';
                }).entries(dataWithGroupId);
                var dataYStack = [];
                var stacked = grouped.map(function(d, i) {
                    if (d.key === 'unstacked') return d.values; else {
                        var prevArray = d.values[0].r.map(function(d, i) {
                            return 0;
                        });
                        d.values.forEach(function(d, i, a) {
                            d.yStack = [ prevArray ];
                            dataYStack.push(prevArray);
                            prevArray = µ.util.sumArrays(d.r, prevArray);
                        });
                        return d.values;
                    }
                });
                data = d3.merge(stacked);
            }
            data.forEach(function(d, i) {
                d.t = Array.isArray(d.t[0]) ? d.t : [ d.t ];
                d.r = Array.isArray(d.r[0]) ? d.r : [ d.r ];
            });
            var radius = Math.min(axisConfig.width - axisConfig.margin.left - axisConfig.margin.right, axisConfig.height - axisConfig.margin.top - axisConfig.margin.bottom) / 2;
            radius = Math.max(10, radius);
            var chartCenter = [ axisConfig.margin.left + radius, axisConfig.margin.top + radius ];
            var extent;
            if (isStacked) {
                var highestStackedValue = d3.max(µ.util.sumArrays(µ.util.arrayLast(data).r[0], µ.util.arrayLast(dataYStack)));
                extent = [ 0, highestStackedValue ];
            } else extent = d3.extent(µ.util.flattenArray(data.map(function(d, i) {
                return d.r;
            })));
            if (axisConfig.radialAxis.domain != µ.DATAEXTENT) extent[0] = 0;
            radialScale = d3.scale.linear().domain(axisConfig.radialAxis.domain != µ.DATAEXTENT && axisConfig.radialAxis.domain ? axisConfig.radialAxis.domain : extent).range([ 0, radius ]);
            liveConfig.layout.radialAxis.domain = radialScale.domain();
            var angularDataMerged = µ.util.flattenArray(data.map(function(d, i) {
                return d.t;
            }));
            var isOrdinal = typeof angularDataMerged[0] === 'string';
            var ticks;
            if (isOrdinal) {
                angularDataMerged = µ.util.deduplicate(angularDataMerged);
                ticks = angularDataMerged.slice();
                angularDataMerged = d3.range(angularDataMerged.length);
                data = data.map(function(d, i) {
                    var result = d;
                    d.t = [ angularDataMerged ];
                    if (isStacked) result.yStack = d.yStack;
                    return result;
                });
            }
            var hasOnlyLineOrDotPlot = data.filter(function(d, i) {
                return d.geometry === 'LinePlot' || d.geometry === 'DotPlot';
            }).length === data.length;
            var needsEndSpacing = axisConfig.needsEndSpacing === null ? isOrdinal || !hasOnlyLineOrDotPlot : axisConfig.needsEndSpacing;
            var useProvidedDomain = axisConfig.angularAxis.domain && axisConfig.angularAxis.domain != µ.DATAEXTENT && !isOrdinal && axisConfig.angularAxis.domain[0] >= 0;
            var angularDomain = useProvidedDomain ? axisConfig.angularAxis.domain : d3.extent(angularDataMerged);
            var angularDomainStep = Math.abs(angularDataMerged[1] - angularDataMerged[0]);
            if (hasOnlyLineOrDotPlot && !isOrdinal) angularDomainStep = 0;
            var angularDomainWithPadding = angularDomain.slice();
            if (needsEndSpacing && isOrdinal) angularDomainWithPadding[1] += angularDomainStep;
            var tickCount = axisConfig.angularAxis.ticksCount || 4;
            if (tickCount > 8) tickCount = tickCount / (tickCount / 8) + tickCount % 8;
            if (axisConfig.angularAxis.ticksStep) {
                tickCount = (angularDomainWithPadding[1] - angularDomainWithPadding[0]) / tickCount;
            }
            var angularTicksStep = axisConfig.angularAxis.ticksStep || (angularDomainWithPadding[1] - angularDomainWithPadding[0]) / (tickCount * (axisConfig.minorTicks + 1));
            if (ticks) angularTicksStep = Math.max(Math.round(angularTicksStep), 1);
            if (!angularDomainWithPadding[2]) angularDomainWithPadding[2] = angularTicksStep;
            var angularAxisRange = d3.range.apply(this, angularDomainWithPadding);
            angularAxisRange = angularAxisRange.map(function(d, i) {
                return parseFloat(d.toPrecision(12));
            });
            angularScale = d3.scale.linear().domain(angularDomainWithPadding.slice(0, 2)).range(axisConfig.direction === 'clockwise' ? [ 0, 360 ] : [ 360, 0 ]);
            liveConfig.layout.angularAxis.domain = angularScale.domain();
            liveConfig.layout.angularAxis.endPadding = needsEndSpacing ? angularDomainStep : 0;
            svg = d3.select(this).select('svg.chart-root');
            if (typeof svg === 'undefined' || svg.empty()) {
                var skeleton = "<svg xmlns='http://www.w3.org/2000/svg' class='chart-root'>' + '<g class='outer-group'>' + '<g class='chart-group'>' + '<circle class='background-circle'></circle>' + '<g class='geometry-group'></g>' + '<g class='radial axis-group'>' + '<circle class='outside-circle'></circle>' + '</g>' + '<g class='angular axis-group'></g>' + '<g class='guides-group'><line></line><circle r='0'></circle></g>' + '</g>' + '<g class='legend-group'></g>' + '<g class='tooltips-group'></g>' + '<g class='title-group'><text></text></g>' + '</g>' + '</svg>";
                var doc = new DOMParser().parseFromString(skeleton, 'application/xml');
                var newSvg = this.appendChild(this.ownerDocument.importNode(doc.documentElement, true));
                svg = d3.select(newSvg);
            }
            svg.select('.guides-group').style({
                'pointer-events': 'none'
            });
            svg.select('.angular.axis-group').style({
                'pointer-events': 'none'
            });
            svg.select('.radial.axis-group').style({
                'pointer-events': 'none'
            });
            var chartGroup = svg.select('.chart-group');
            var lineStyle = {
                fill: 'none',
                stroke: axisConfig.tickColor
            };
            var fontStyle = {
                'font-size': axisConfig.font.size,
                'font-family': axisConfig.font.family,
                fill: axisConfig.font.color,
                'text-shadow': [ '-1px 0px', '1px -1px', '-1px 1px', '1px 1px' ].map(function(d, i) {
                    return ' ' + d + ' 0 ' + axisConfig.font.outlineColor;
                }).join(',')
            };
            var legendContainer;
            if (axisConfig.showLegend) {
                legendContainer = svg.select('.legend-group').attr({
                    transform: 'translate(' + [ radius, axisConfig.margin.top ] + ')'
                }).style({
                    display: 'block'
                });
                var elements = data.map(function(d, i) {
                    var datumClone = µ.util.cloneJson(d);
                    datumClone.symbol = d.geometry === 'DotPlot' ? d.dotType || 'circle' : d.geometry != 'LinePlot' ? 'square' : 'line';
                    datumClone.visibleInLegend = typeof d.visibleInLegend === 'undefined' || d.visibleInLegend;
                    datumClone.color = d.geometry === 'LinePlot' ? d.strokeColor : d.color;
                    return datumClone;
                });

                µ.Legend().config({
                    data: data.map(function(d, i) {
                        return d.name || 'Element' + i;
                    }),
                    legendConfig: extendDeepAll({},
                        µ.Legend.defaultConfig().legendConfig,
                        {
                            container: legendContainer,
                            elements: elements,
                            reverseOrder: axisConfig.legend.reverseOrder
                        }
                    )
                })();

                var legendBBox = legendContainer.node().getBBox();
                radius = Math.min(axisConfig.width - legendBBox.width - axisConfig.margin.left - axisConfig.margin.right, axisConfig.height - axisConfig.margin.top - axisConfig.margin.bottom) / 2;
                radius = Math.max(10, radius);
                chartCenter = [ axisConfig.margin.left + radius, axisConfig.margin.top + radius ];
                radialScale.range([ 0, radius ]);
                liveConfig.layout.radialAxis.domain = radialScale.domain();
                legendContainer.attr('transform', 'translate(' + [ chartCenter[0] + radius, chartCenter[1] - radius ] + ')');
            } else {
                legendContainer = svg.select('.legend-group').style({
                    display: 'none'
                });
            }
            svg.attr({
                width: axisConfig.width,
                height: axisConfig.height
            }).style({
                opacity: axisConfig.opacity
            });
            chartGroup.attr('transform', 'translate(' + chartCenter + ')').style({
                cursor: 'crosshair'
            });
            var centeringOffset = [ (axisConfig.width - (axisConfig.margin.left + axisConfig.margin.right + radius * 2 + (legendBBox ? legendBBox.width : 0))) / 2, (axisConfig.height - (axisConfig.margin.top + axisConfig.margin.bottom + radius * 2)) / 2 ];
            centeringOffset[0] = Math.max(0, centeringOffset[0]);
            centeringOffset[1] = Math.max(0, centeringOffset[1]);
            svg.select('.outer-group').attr('transform', 'translate(' + centeringOffset + ')');
            if (axisConfig.title && axisConfig.title.text) {
                var title = svg.select('g.title-group text').style(fontStyle).text(axisConfig.title.text);
                var titleBBox = title.node().getBBox();
                title.attr({
                    x: chartCenter[0] - titleBBox.width / 2,
                    y: chartCenter[1] - radius - 20
                });
            }
            var radialAxis = svg.select('.radial.axis-group');
            if (axisConfig.radialAxis.gridLinesVisible) {
                var gridCircles = radialAxis.selectAll('circle.grid-circle').data(radialScale.ticks(5));
                gridCircles.enter().append('circle').attr({
                    'class': 'grid-circle'
                }).style(lineStyle);
                gridCircles.attr('r', radialScale);
                gridCircles.exit().remove();
            }
            radialAxis.select('circle.outside-circle').attr({
                r: radius
            }).style(lineStyle);
            var backgroundCircle = svg.select('circle.background-circle').attr({
                r: radius
            }).style({
                fill: axisConfig.backgroundColor,
                stroke: axisConfig.stroke
            });
            function currentAngle(d, i) {
                return angularScale(d) % 360 + axisConfig.orientation;
            }
            if (axisConfig.radialAxis.visible) {
                var axis = d3.svg.axis().scale(radialScale).ticks(5).tickSize(5);
                radialAxis.call(axis).attr({
                    transform: 'rotate(' + axisConfig.radialAxis.orientation + ')'
                });
                radialAxis.selectAll('.domain').style(lineStyle);
                radialAxis.selectAll('g>text').text(function(d, i) {
                    return this.textContent + axisConfig.radialAxis.ticksSuffix;
                }).style(fontStyle).style({
                    'text-anchor': 'start'
                }).attr({
                    x: 0,
                    y: 0,
                    dx: 0,
                    dy: 0,
                    transform: function(d, i) {
                        if (axisConfig.radialAxis.tickOrientation === 'horizontal') {
                            return 'rotate(' + -axisConfig.radialAxis.orientation + ') translate(' + [ 0, fontStyle['font-size'] ] + ')';
                        } else return 'translate(' + [ 0, fontStyle['font-size'] ] + ')';
                    }
                });
                radialAxis.selectAll('g>line').style({
                    stroke: 'black'
                });
            }
            var angularAxis = svg.select('.angular.axis-group').selectAll('g.angular-tick').data(angularAxisRange);
            var angularAxisEnter = angularAxis.enter().append('g').classed('angular-tick', true);
            angularAxis.attr({
                transform: function(d, i) {
                    return 'rotate(' + currentAngle(d, i) + ')';
                }
            }).style({
                display: axisConfig.angularAxis.visible ? 'block' : 'none'
            });
            angularAxis.exit().remove();
            angularAxisEnter.append('line').classed('grid-line', true).classed('major', function(d, i) {
                return i % (axisConfig.minorTicks + 1) == 0;
            }).classed('minor', function(d, i) {
                return !(i % (axisConfig.minorTicks + 1) == 0);
            }).style(lineStyle);
            angularAxisEnter.selectAll('.minor').style({
                stroke: axisConfig.minorTickColor
            });
            angularAxis.select('line.grid-line').attr({
                x1: axisConfig.tickLength ? radius - axisConfig.tickLength : 0,
                x2: radius
            }).style({
                display: axisConfig.angularAxis.gridLinesVisible ? 'block' : 'none'
            });
            angularAxisEnter.append('text').classed('axis-text', true).style(fontStyle);
            var ticksText = angularAxis.select('text.axis-text').attr({
                x: radius + axisConfig.labelOffset,
                dy: MID_SHIFT + 'em',
                transform: function(d, i) {
                    var angle = currentAngle(d, i);
                    var rad = radius + axisConfig.labelOffset;
                    var orient = axisConfig.angularAxis.tickOrientation;
                    if (orient == 'horizontal') return 'rotate(' + -angle + ' ' + rad + ' 0)'; else if (orient == 'radial') return angle < 270 && angle > 90 ? 'rotate(180 ' + rad + ' 0)' : null; else return 'rotate(' + (angle <= 180 && angle > 0 ? -90 : 90) + ' ' + rad + ' 0)';
                }
            }).style({
                'text-anchor': 'middle',
                display: axisConfig.angularAxis.labelsVisible ? 'block' : 'none'
            }).text(function(d, i) {
                if (i % (axisConfig.minorTicks + 1) != 0) return '';
                if (ticks) {
                    return ticks[d] + axisConfig.angularAxis.ticksSuffix;
                } else return d + axisConfig.angularAxis.ticksSuffix;
            }).style(fontStyle);
            if (axisConfig.angularAxis.rewriteTicks) ticksText.text(function(d, i) {
                if (i % (axisConfig.minorTicks + 1) != 0) return '';
                return axisConfig.angularAxis.rewriteTicks(this.textContent, i);
            });
            var rightmostTickEndX = d3.max(chartGroup.selectAll('.angular-tick text')[0].map(function(d, i) {
                return d.getCTM().e + d.getBBox().width;
            }));
            legendContainer.attr({
                transform: 'translate(' + [ radius + rightmostTickEndX, axisConfig.margin.top ] + ')'
            });
            var hasGeometry = svg.select('g.geometry-group').selectAll('g').size() > 0;
            var geometryContainer = svg.select('g.geometry-group').selectAll('g.geometry').data(data);
            geometryContainer.enter().append('g').attr({
                'class': function(d, i) {
                    return 'geometry geometry' + i;
                }
            });
            geometryContainer.exit().remove();
            if (data[0] || hasGeometry) {
                var geometryConfigs = [];
                data.forEach(function(d, i) {
                    var geometryConfig = {};
                    geometryConfig.radialScale = radialScale;
                    geometryConfig.angularScale = angularScale;
                    geometryConfig.container = geometryContainer.filter(function(dB, iB) {
                        return iB == i;
                    });
                    geometryConfig.geometry = d.geometry;
                    geometryConfig.orientation = axisConfig.orientation;
                    geometryConfig.direction = axisConfig.direction;
                    geometryConfig.index = i;
                    geometryConfigs.push({
                        data: d,
                        geometryConfig: geometryConfig
                    });
                });
                var geometryConfigsGrouped = d3.nest().key(function(d, i) {
                    return typeof d.data.groupId != 'undefined' || 'unstacked';
                }).entries(geometryConfigs);
                var geometryConfigsGrouped2 = [];
                geometryConfigsGrouped.forEach(function(d, i) {
                    if (d.key === 'unstacked') geometryConfigsGrouped2 = geometryConfigsGrouped2.concat(d.values.map(function(d, i) {
                        return [ d ];
                    })); else geometryConfigsGrouped2.push(d.values);
                });
                geometryConfigsGrouped2.forEach(function(d, i) {
                    var geometry;
                    if (Array.isArray(d)) geometry = d[0].geometryConfig.geometry; else geometry = d.geometryConfig.geometry;
                    var finalGeometryConfig = d.map(function(dB, iB) {
                        return extendDeepAll(µ[geometry].defaultConfig(), dB);
                    });
                    µ[geometry]().config(finalGeometryConfig)();
                });
            }
            var guides = svg.select('.guides-group');
            var tooltipContainer = svg.select('.tooltips-group');
            var angularTooltip = µ.tooltipPanel().config({
                container: tooltipContainer,
                fontSize: 8
            })();
            var radialTooltip = µ.tooltipPanel().config({
                container: tooltipContainer,
                fontSize: 8
            })();
            var geometryTooltip = µ.tooltipPanel().config({
                container: tooltipContainer,
                hasTick: true
            })();
            var angularValue, radialValue;
            if (!isOrdinal) {
                var angularGuideLine = guides.select('line').attr({
                    x1: 0,
                    y1: 0,
                    y2: 0
                }).style({
                    stroke: 'grey',
                    'pointer-events': 'none'
                });
                chartGroup.on('mousemove.angular-guide', function(d, i) {
                    var mouseAngle = µ.util.getMousePos(backgroundCircle).angle;
                    angularGuideLine.attr({
                        x2: -radius,
                        transform: 'rotate(' + mouseAngle + ')'
                    }).style({
                        opacity: .5
                    });
                    var angleWithOriginOffset = (mouseAngle + 180 + 360 - axisConfig.orientation) % 360;
                    angularValue = angularScale.invert(angleWithOriginOffset);
                    var pos = µ.util.convertToCartesian(radius + 12, mouseAngle + 180);
                    angularTooltip.text(µ.util.round(angularValue)).move([ pos[0] + chartCenter[0], pos[1] + chartCenter[1] ]);
                }).on('mouseout.angular-guide', function(d, i) {
                    guides.select('line').style({
                        opacity: 0
                    });
                });
            }
            var angularGuideCircle = guides.select('circle').style({
                stroke: 'grey',
                fill: 'none'
            });
            chartGroup.on('mousemove.radial-guide', function(d, i) {
                var r = µ.util.getMousePos(backgroundCircle).radius;
                angularGuideCircle.attr({
                    r: r
                }).style({
                    opacity: .5
                });
                radialValue = radialScale.invert(µ.util.getMousePos(backgroundCircle).radius);
                var pos = µ.util.convertToCartesian(r, axisConfig.radialAxis.orientation);
                radialTooltip.text(µ.util.round(radialValue)).move([ pos[0] + chartCenter[0], pos[1] + chartCenter[1] ]);
            }).on('mouseout.radial-guide', function(d, i) {
                angularGuideCircle.style({
                    opacity: 0
                });
                geometryTooltip.hide();
                angularTooltip.hide();
                radialTooltip.hide();
            });
            svg.selectAll('.geometry-group .mark').on('mouseover.tooltip', function(d, i) {
                var el = d3.select(this);
                var color = this.style.fill;
                var newColor = 'black';
                var opacity = this.style.opacity || 1;
                el.attr({
                    'data-opacity': opacity
                });
                if (color && color !== 'none') {
                    el.attr({
                        'data-fill': color
                    });
                    newColor = d3.hsl(color).darker().toString();
                    el.style({
                        fill: newColor,
                        opacity: 1
                    });
                    var textData = {
                        t: µ.util.round(d[0]),
                        r: µ.util.round(d[1])
                    };
                    if (isOrdinal) textData.t = ticks[d[0]];
                    var text = 't: ' + textData.t + ', r: ' + textData.r;
                    var bbox = this.getBoundingClientRect();
                    var svgBBox = svg.node().getBoundingClientRect();
                    var pos = [ bbox.left + bbox.width / 2 - centeringOffset[0] - svgBBox.left, bbox.top + bbox.height / 2 - centeringOffset[1] - svgBBox.top ];
                    geometryTooltip.config({
                        color: newColor
                    }).text(text);
                    geometryTooltip.move(pos);
                } else {
                    color = this.style.stroke || 'black';
                    el.attr({
                        'data-stroke': color
                    });
                    newColor = d3.hsl(color).darker().toString();
                    el.style({
                        stroke: newColor,
                        opacity: 1
                    });
                }
            }).on('mousemove.tooltip', function(d, i) {
                if (d3.event.which != 0) return false;
                if (d3.select(this).attr('data-fill')) geometryTooltip.show();
            }).on('mouseout.tooltip', function(d, i) {
                geometryTooltip.hide();
                var el = d3.select(this);
                var fillColor = el.attr('data-fill');
                if (fillColor) el.style({
                    fill: fillColor,
                    opacity: el.attr('data-opacity')
                }); else el.style({
                    stroke: el.attr('data-stroke'),
                    opacity: el.attr('data-opacity')
                });
            });
        });
        return exports;
    }
    exports.render = function(_container) {
        render(_container);
        return this;
    };
    exports.config = function(_x) {
        if (!arguments.length) return config;
        var xClone = µ.util.cloneJson(_x);
        xClone.data.forEach(function(d, i) {
            if (!config.data[i]) config.data[i] = {};
            extendDeepAll(config.data[i], µ.Axis.defaultConfig().data[0]);
            extendDeepAll(config.data[i], d);
        });
        extendDeepAll(config.layout, µ.Axis.defaultConfig().layout);
        extendDeepAll(config.layout, xClone.layout);
        return this;
    };
    exports.getLiveConfig = function() {
        return liveConfig;
    };
    exports.getinputConfig = function() {
        return inputConfig;
    };
    exports.radialScale = function(_x) {
        return radialScale;
    };
    exports.angularScale = function(_x) {
        return angularScale;
    };
    exports.svg = function() {
        return svg;
    };
    d3.rebind(exports, dispatch, 'on');
    return exports;
};

µ.Axis.defaultConfig = function(d, i) {
    var config = {
        data: [ {
            t: [ 1, 2, 3, 4 ],
            r: [ 10, 11, 12, 13 ],
            name: 'Line1',
            geometry: 'LinePlot',
            color: null,
            strokeDash: 'solid',
            strokeColor: null,
            strokeSize: '1',
            visibleInLegend: true,
            opacity: 1
        } ],
        layout: {
            defaultColorRange: d3.scale.category10().range(),
            title: null,
            height: 450,
            width: 500,
            margin: {
                top: 40,
                right: 40,
                bottom: 40,
                left: 40
            },
            font: {
                size: 12,
                color: 'gray',
                outlineColor: 'white',
                family: 'Tahoma, sans-serif'
            },
            direction: 'clockwise',
            orientation: 0,
            labelOffset: 10,
            radialAxis: {
                domain: null,
                orientation: -45,
                ticksSuffix: '',
                visible: true,
                gridLinesVisible: true,
                tickOrientation: 'horizontal',
                rewriteTicks: null
            },
            angularAxis: {
                domain: [ 0, 360 ],
                ticksSuffix: '',
                visible: true,
                gridLinesVisible: true,
                labelsVisible: true,
                tickOrientation: 'horizontal',
                rewriteTicks: null,
                ticksCount: null,
                ticksStep: null
            },
            minorTicks: 0,
            tickLength: null,
            tickColor: 'silver',
            minorTickColor: '#eee',
            backgroundColor: 'none',
            needsEndSpacing: null,
            showLegend: true,
            legend: {
                reverseOrder: false
            },
            opacity: 1
        }
    };
    return config;
};

µ.util = {};

µ.DATAEXTENT = 'dataExtent';

µ.AREA = 'AreaChart';

µ.LINE = 'LinePlot';

µ.DOT = 'DotPlot';

µ.BAR = 'BarChart';

µ.util._override = function(_objA, _objB) {
    for (var x in _objA) if (x in _objB) _objB[x] = _objA[x];
};

µ.util._extend = function(_objA, _objB) {
    for (var x in _objA) _objB[x] = _objA[x];
};

µ.util._rndSnd = function() {
    return Math.random() * 2 - 1 + (Math.random() * 2 - 1) + (Math.random() * 2 - 1);
};

µ.util.dataFromEquation2 = function(_equation, _step) {
    var step = _step || 6;
    var data = d3.range(0, 360 + step, step).map(function(deg, index) {
        var theta = deg * Math.PI / 180;
        var radius = _equation(theta);
        return [ deg, radius ];
    });
    return data;
};

µ.util.dataFromEquation = function(_equation, _step, _name) {
    var step = _step || 6;
    var t = [], r = [];
    d3.range(0, 360 + step, step).forEach(function(deg, index) {
        var theta = deg * Math.PI / 180;
        var radius = _equation(theta);
        t.push(deg);
        r.push(radius);
    });
    var result = {
        t: t,
        r: r
    };
    if (_name) result.name = _name;
    return result;
};

µ.util.ensureArray = function(_val, _count) {
    if (typeof _val === 'undefined') return null;
    var arr = [].concat(_val);
    return d3.range(_count).map(function(d, i) {
        return arr[i] || arr[0];
    });
};

µ.util.fillArrays = function(_obj, _valueNames, _count) {
    _valueNames.forEach(function(d, i) {
        _obj[d] = µ.util.ensureArray(_obj[d], _count);
    });
    return _obj;
};

µ.util.cloneJson = function(json) {
    return JSON.parse(JSON.stringify(json));
};

µ.util.validateKeys = function(obj, keys) {
    if (typeof keys === 'string') keys = keys.split('.');
    var next = keys.shift();
    return obj[next] && (!keys.length || objHasKeys(obj[next], keys));
};

µ.util.sumArrays = function(a, b) {
    return d3.zip(a, b).map(function(d, i) {
        return d3.sum(d);
    });
};

µ.util.arrayLast = function(a) {
    return a[a.length - 1];
};

µ.util.arrayEqual = function(a, b) {
    var i = Math.max(a.length, b.length, 1);
    while (i-- >= 0 && a[i] === b[i]) ;
    return i === -2;
};

µ.util.flattenArray = function(arr) {
    var r = [];
    while (!µ.util.arrayEqual(r, arr)) {
        r = arr;
        arr = [].concat.apply([], arr);
    }
    return arr;
};

µ.util.deduplicate = function(arr) {
    return arr.filter(function(v, i, a) {
        return a.indexOf(v) == i;
    });
};

µ.util.convertToCartesian = function(radius, theta) {
    var thetaRadians = theta * Math.PI / 180;
    var x = radius * Math.cos(thetaRadians);
    var y = radius * Math.sin(thetaRadians);
    return [ x, y ];
};

µ.util.round = function(_value, _digits) {
    var digits = _digits || 2;
    var mult = Math.pow(10, digits);
    return Math.round(_value * mult) / mult;
};

µ.util.getMousePos = function(_referenceElement) {
    var mousePos = d3.mouse(_referenceElement.node());
    var mouseX = mousePos[0];
    var mouseY = mousePos[1];
    var mouse = {};
    mouse.x = mouseX;
    mouse.y = mouseY;
    mouse.pos = mousePos;
    mouse.angle = (Math.atan2(mouseY, mouseX) + Math.PI) * 180 / Math.PI;
    mouse.radius = Math.sqrt(mouseX * mouseX + mouseY * mouseY);
    return mouse;
};

µ.util.duplicatesCount = function(arr) {
    var uniques = {}, val;
    var dups = {};
    for (var i = 0, len = arr.length; i < len; i++) {
        val = arr[i];
        if (val in uniques) {
            uniques[val]++;
            dups[val] = uniques[val];
        } else {
            uniques[val] = 1;
        }
    }
    return dups;
};

µ.util.duplicates = function(arr) {
    return Object.keys(µ.util.duplicatesCount(arr));
};

µ.util.translator = function(obj, sourceBranch, targetBranch, reverse) {
    if (reverse) {
        var targetBranchCopy = targetBranch.slice();
        targetBranch = sourceBranch;
        sourceBranch = targetBranchCopy;
    }
    var value = sourceBranch.reduce(function(previousValue, currentValue) {
        if (typeof previousValue != 'undefined') return previousValue[currentValue];
    }, obj);
    if (typeof value === 'undefined') return;
    sourceBranch.reduce(function(previousValue, currentValue, index) {
        if (typeof previousValue == 'undefined') return;
        if (index === sourceBranch.length - 1) delete previousValue[currentValue];
        return previousValue[currentValue];
    }, obj);
    targetBranch.reduce(function(previousValue, currentValue, index) {
        if (typeof previousValue[currentValue] === 'undefined') previousValue[currentValue] = {};
        if (index === targetBranch.length - 1) previousValue[currentValue] = value;
        return previousValue[currentValue];
    }, obj);
};

µ.PolyChart = function module() {
    var config = [ µ.PolyChart.defaultConfig() ];
    var dispatch = d3.dispatch('hover');
    var dashArray = {
        solid: 'none',
        dash: [ 5, 2 ],
        dot: [ 2, 5 ]
    };
    var colorScale;
    function exports() {
        var geometryConfig = config[0].geometryConfig;
        var container = geometryConfig.container;
        if (typeof container == 'string') container = d3.select(container);
        container.datum(config).each(function(_config, _index) {
            var isStack = !!_config[0].data.yStack;
            var data = _config.map(function(d, i) {
                if (isStack) return d3.zip(d.data.t[0], d.data.r[0], d.data.yStack[0]); else return d3.zip(d.data.t[0], d.data.r[0]);
            });
            var angularScale = geometryConfig.angularScale;
            var domainMin = geometryConfig.radialScale.domain()[0];
            var generator = {};
            generator.bar = function(d, i, pI) {
                var dataConfig = _config[pI].data;
                var h = geometryConfig.radialScale(d[1]) - geometryConfig.radialScale(0);
                var stackTop = geometryConfig.radialScale(d[2] || 0);
                var w = dataConfig.barWidth;
                d3.select(this).attr({
                    'class': 'mark bar',
                    d: 'M' + [ [ h + stackTop, -w / 2 ], [ h + stackTop, w / 2 ], [ stackTop, w / 2 ], [ stackTop, -w / 2 ] ].join('L') + 'Z',
                    transform: function(d, i) {
                        return 'rotate(' + (geometryConfig.orientation + angularScale(d[0])) + ')';
                    }
                });
            };
            generator.dot = function(d, i, pI) {
                var stackedData = d[2] ? [ d[0], d[1] + d[2] ] : d;
                var symbol = d3.svg.symbol().size(_config[pI].data.dotSize).type(_config[pI].data.dotType)(d, i);
                d3.select(this).attr({
                    'class': 'mark dot',
                    d: symbol,
                    transform: function(d, i) {
                        var coord = convertToCartesian(getPolarCoordinates(stackedData));
                        return 'translate(' + [ coord.x, coord.y ] + ')';
                    }
                });
            };
            var line = d3.svg.line.radial().interpolate(_config[0].data.lineInterpolation).radius(function(d) {
                return geometryConfig.radialScale(d[1]);
            }).angle(function(d) {
                return geometryConfig.angularScale(d[0]) * Math.PI / 180;
            });
            generator.line = function(d, i, pI) {
                var lineData = d[2] ? data[pI].map(function(d, i) {
                    return [ d[0], d[1] + d[2] ];
                }) : data[pI];
                d3.select(this).each(generator['dot']).style({
                    opacity: function(dB, iB) {
                        return +_config[pI].data.dotVisible;
                    },
                    fill: markStyle.stroke(d, i, pI)
                }).attr({
                    'class': 'mark dot'
                });
                if (i > 0) return;
                var lineSelection = d3.select(this.parentNode).selectAll('path.line').data([ 0 ]);
                lineSelection.enter().insert('path');
                lineSelection.attr({
                    'class': 'line',
                    d: line(lineData),
                    transform: function(dB, iB) {
                        return 'rotate(' + (geometryConfig.orientation + 90) + ')';
                    },
                    'pointer-events': 'none'
                }).style({
                    fill: function(dB, iB) {
                        return markStyle.fill(d, i, pI);
                    },
                    'fill-opacity': 0,
                    stroke: function(dB, iB) {
                        return markStyle.stroke(d, i, pI);
                    },
                    'stroke-width': function(dB, iB) {
                        return markStyle['stroke-width'](d, i, pI);
                    },
                    'stroke-dasharray': function(dB, iB) {
                        return markStyle['stroke-dasharray'](d, i, pI);
                    },
                    opacity: function(dB, iB) {
                        return markStyle.opacity(d, i, pI);
                    },
                    display: function(dB, iB) {
                        return markStyle.display(d, i, pI);
                    }
                });
            };
            var angularRange = geometryConfig.angularScale.range();
            var triangleAngle = Math.abs(angularRange[1] - angularRange[0]) / data[0].length * Math.PI / 180;
            var arc = d3.svg.arc().startAngle(function(d) {
                return -triangleAngle / 2;
            }).endAngle(function(d) {
                return triangleAngle / 2;
            }).innerRadius(function(d) {
                return geometryConfig.radialScale(domainMin + (d[2] || 0));
            }).outerRadius(function(d) {
                return geometryConfig.radialScale(domainMin + (d[2] || 0)) + geometryConfig.radialScale(d[1]);
            });
            generator.arc = function(d, i, pI) {
                d3.select(this).attr({
                    'class': 'mark arc',
                    d: arc,
                    transform: function(d, i) {
                        return 'rotate(' + (geometryConfig.orientation + angularScale(d[0]) + 90) + ')';
                    }
                });
            };
            var markStyle = {
                fill: function(d, i, pI) {
                    return _config[pI].data.color;
                },
                stroke: function(d, i, pI) {
                    return _config[pI].data.strokeColor;
                },
                'stroke-width': function(d, i, pI) {
                    return _config[pI].data.strokeSize + 'px';
                },
                'stroke-dasharray': function(d, i, pI) {
                    return dashArray[_config[pI].data.strokeDash];
                },
                opacity: function(d, i, pI) {
                    return _config[pI].data.opacity;
                },
                display: function(d, i, pI) {
                    return typeof _config[pI].data.visible === 'undefined' || _config[pI].data.visible ? 'block' : 'none';
                }
            };
            var geometryLayer = d3.select(this).selectAll('g.layer').data(data);
            geometryLayer.enter().append('g').attr({
                'class': 'layer'
            });
            var geometry = geometryLayer.selectAll('path.mark').data(function(d, i) {
                return d;
            });
            geometry.enter().append('path').attr({
                'class': 'mark'
            });
            geometry.style(markStyle).each(generator[geometryConfig.geometryType]);
            geometry.exit().remove();
            geometryLayer.exit().remove();
            function getPolarCoordinates(d, i) {
                var r = geometryConfig.radialScale(d[1]);
                var t = (geometryConfig.angularScale(d[0]) + geometryConfig.orientation) * Math.PI / 180;
                return {
                    r: r,
                    t: t
                };
            }
            function convertToCartesian(polarCoordinates) {
                var x = polarCoordinates.r * Math.cos(polarCoordinates.t);
                var y = polarCoordinates.r * Math.sin(polarCoordinates.t);
                return {
                    x: x,
                    y: y
                };
            }
        });
    }
    exports.config = function(_x) {
        if (!arguments.length) return config;
        _x.forEach(function(d, i) {
            if (!config[i]) config[i] = {};
            extendDeepAll(config[i], µ.PolyChart.defaultConfig());
            extendDeepAll(config[i], d);
        });
        return this;
    };
    exports.getColorScale = function() {
        return colorScale;
    };
    d3.rebind(exports, dispatch, 'on');
    return exports;
};

µ.PolyChart.defaultConfig = function() {
    var config = {
        data: {
            name: 'geom1',
            t: [ [ 1, 2, 3, 4 ] ],
            r: [ [ 1, 2, 3, 4 ] ],
            dotType: 'circle',
            dotSize: 64,
            dotVisible: false,
            barWidth: 20,
            color: '#ffa500',
            strokeSize: 1,
            strokeColor: 'silver',
            strokeDash: 'solid',
            opacity: 1,
            index: 0,
            visible: true,
            visibleInLegend: true
        },
        geometryConfig: {
            geometry: 'LinePlot',
            geometryType: 'arc',
            direction: 'clockwise',
            orientation: 0,
            container: 'body',
            radialScale: null,
            angularScale: null,
            colorScale: d3.scale.category20()
        }
    };
    return config;
};

µ.BarChart = function module() {
    return µ.PolyChart();
};

µ.BarChart.defaultConfig = function() {
    var config = {
        geometryConfig: {
            geometryType: 'bar'
        }
    };
    return config;
};

µ.AreaChart = function module() {
    return µ.PolyChart();
};

µ.AreaChart.defaultConfig = function() {
    var config = {
        geometryConfig: {
            geometryType: 'arc'
        }
    };
    return config;
};

µ.DotPlot = function module() {
    return µ.PolyChart();
};

µ.DotPlot.defaultConfig = function() {
    var config = {
        geometryConfig: {
            geometryType: 'dot',
            dotType: 'circle'
        }
    };
    return config;
};

µ.LinePlot = function module() {
    return µ.PolyChart();
};

µ.LinePlot.defaultConfig = function() {
    var config = {
        geometryConfig: {
            geometryType: 'line'
        }
    };
    return config;
};

µ.Legend = function module() {
    var config = µ.Legend.defaultConfig();
    var dispatch = d3.dispatch('hover');
    function exports() {
        var legendConfig = config.legendConfig;
        var flattenData = config.data.map(function(d, i) {
            return [].concat(d).map(function(dB, iB) {
                var element = extendDeepAll({}, legendConfig.elements[i]);
                element.name = dB;
                element.color = [].concat(legendConfig.elements[i].color)[iB];
                return element;
            });
        });
        var data = d3.merge(flattenData);
        data = data.filter(function(d, i) {
            return legendConfig.elements[i] && (legendConfig.elements[i].visibleInLegend || typeof legendConfig.elements[i].visibleInLegend === 'undefined');
        });
        if (legendConfig.reverseOrder) data = data.reverse();
        var container = legendConfig.container;
        if (typeof container == 'string' || container.nodeName) container = d3.select(container);
        var colors = data.map(function(d, i) {
            return d.color;
        });
        var lineHeight = legendConfig.fontSize;
        var isContinuous = legendConfig.isContinuous == null ? typeof data[0] === 'number' : legendConfig.isContinuous;
        var height = isContinuous ? legendConfig.height : lineHeight * data.length;
        var legendContainerGroup = container.classed('legend-group', true);
        var svg = legendContainerGroup.selectAll('svg').data([ 0 ]);
        var svgEnter = svg.enter().append('svg').attr({
            width: 300,
            height: height + lineHeight,
            xmlns: 'http://www.w3.org/2000/svg',
            'xmlns:xlink': 'http://www.w3.org/1999/xlink',
            version: '1.1'
        });
        svgEnter.append('g').classed('legend-axis', true);
        svgEnter.append('g').classed('legend-marks', true);
        var dataNumbered = d3.range(data.length);
        var colorScale = d3.scale[isContinuous ? 'linear' : 'ordinal']().domain(dataNumbered).range(colors);
        var dataScale = d3.scale[isContinuous ? 'linear' : 'ordinal']().domain(dataNumbered)[isContinuous ? 'range' : 'rangePoints']([ 0, height ]);
        var shapeGenerator = function(_type, _size) {
            var squareSize = _size * 3;
            if (_type === 'line') {
                return 'M' + [ [ -_size / 2, -_size / 12 ], [ _size / 2, -_size / 12 ], [ _size / 2, _size / 12 ], [ -_size / 2, _size / 12 ] ] + 'Z';
            } else if (d3.svg.symbolTypes.indexOf(_type) != -1) return d3.svg.symbol().type(_type).size(squareSize)(); else return d3.svg.symbol().type('square').size(squareSize)();
        };
        if (isContinuous) {
            var gradient = svg.select('.legend-marks').append('defs').append('linearGradient').attr({
                id: 'grad1',
                x1: '0%',
                y1: '0%',
                x2: '0%',
                y2: '100%'
            }).selectAll('stop').data(colors);
            gradient.enter().append('stop');
            gradient.attr({
                offset: function(d, i) {
                    return i / (colors.length - 1) * 100 + '%';
                }
            }).style({
                'stop-color': function(d, i) {
                    return d;
                }
            });
            svg.append('rect').classed('legend-mark', true).attr({
                height: legendConfig.height,
                width: legendConfig.colorBandWidth,
                fill: 'url(#grad1)'
            });
        } else {
            var legendElement = svg.select('.legend-marks').selectAll('path.legend-mark').data(data);
            legendElement.enter().append('path').classed('legend-mark', true);
            legendElement.attr({
                transform: function(d, i) {
                    return 'translate(' + [ lineHeight / 2, dataScale(i) + lineHeight / 2 ] + ')';
                },
                d: function(d, i) {
                    var symbolType = d.symbol;
                    return shapeGenerator(symbolType, lineHeight);
                },
                fill: function(d, i) {
                    return colorScale(i);
                }
            });
            legendElement.exit().remove();
        }
        var legendAxis = d3.svg.axis().scale(dataScale).orient('right');
        var axis = svg.select('g.legend-axis').attr({
            transform: 'translate(' + [ isContinuous ? legendConfig.colorBandWidth : lineHeight, lineHeight / 2 ] + ')'
        }).call(legendAxis);
        axis.selectAll('.domain').style({
            fill: 'none',
            stroke: 'none'
        });
        axis.selectAll('line').style({
            fill: 'none',
            stroke: isContinuous ? legendConfig.textColor : 'none'
        });
        axis.selectAll('text').style({
            fill: legendConfig.textColor,
            'font-size': legendConfig.fontSize
        }).text(function(d, i) {
            return data[i].name;
        });
        return exports;
    }
    exports.config = function(_x) {
        if (!arguments.length) return config;
        extendDeepAll(config, _x);
        return this;
    };
    d3.rebind(exports, dispatch, 'on');
    return exports;
};

µ.Legend.defaultConfig = function(d, i) {
    var config = {
        data: [ 'a', 'b', 'c' ],
        legendConfig: {
            elements: [ {
                symbol: 'line',
                color: 'red'
            }, {
                symbol: 'square',
                color: 'yellow'
            }, {
                symbol: 'diamond',
                color: 'limegreen'
            } ],
            height: 150,
            colorBandWidth: 30,
            fontSize: 12,
            container: 'body',
            isContinuous: null,
            textColor: 'grey',
            reverseOrder: false
        }
    };
    return config;
};

µ.tooltipPanel = function() {
    var tooltipEl, tooltipTextEl, backgroundEl;
    var config = {
        container: null,
        hasTick: false,
        fontSize: 12,
        color: 'white',
        padding: 5
    };
    var id = 'tooltip-' + µ.tooltipPanel.uid++;
    var tickSize = 10;
    var exports = function() {
        tooltipEl = config.container.selectAll('g.' + id).data([ 0 ]);
        var tooltipEnter = tooltipEl.enter().append('g').classed(id, true).style({
            'pointer-events': 'none',
            display: 'none'
        });
        backgroundEl = tooltipEnter.append('path').style({
            fill: 'white',
            'fill-opacity': .9
        }).attr({
            d: 'M0 0'
        });
        tooltipTextEl = tooltipEnter.append('text').attr({
            dx: config.padding + tickSize,
            dy: +config.fontSize * .3
        });
        return exports;
    };
    exports.text = function(_text) {
        var l = d3.hsl(config.color).l;
        var strokeColor = l >= .5 ? '#aaa' : 'white';
        var fillColor = l >= .5 ? 'black' : 'white';
        var text = _text || '';
        tooltipTextEl.style({
            fill: fillColor,
            'font-size': config.fontSize + 'px'
        }).text(text);
        var padding = config.padding;
        var bbox = tooltipTextEl.node().getBBox();
        var boxStyle = {
            fill: config.color,
            stroke: strokeColor,
            'stroke-width': '2px'
        };
        var backGroundW = bbox.width + padding * 2 + tickSize;
        var backGroundH = bbox.height + padding * 2;
        backgroundEl.attr({
            d: 'M' + [ [ tickSize, -backGroundH / 2 ], [ tickSize, -backGroundH / 4 ], [ config.hasTick ? 0 : tickSize, 0 ], [ tickSize, backGroundH / 4 ], [ tickSize, backGroundH / 2 ], [ backGroundW, backGroundH / 2 ], [ backGroundW, -backGroundH / 2 ] ].join('L') + 'Z'
        }).style(boxStyle);
        tooltipEl.attr({
            transform: 'translate(' + [ tickSize, -backGroundH / 2 + padding * 2 ] + ')'
        });
        tooltipEl.style({
            display: 'block'
        });
        return exports;
    };
    exports.move = function(_pos) {
        if (!tooltipEl) return;
        tooltipEl.attr({
            transform: 'translate(' + [ _pos[0], _pos[1] ] + ')'
        }).style({
            display: 'block'
        });
        return exports;
    };
    exports.hide = function() {
        if (!tooltipEl) return;
        tooltipEl.style({
            display: 'none'
        });
        return exports;
    };
    exports.show = function() {
        if (!tooltipEl) return;
        tooltipEl.style({
            display: 'block'
        });
        return exports;
    };
    exports.config = function(_x) {
        extendDeepAll(config, _x);
        return exports;
    };
    return exports;
};

µ.tooltipPanel.uid = 1;

µ.adapter = {};

µ.adapter.plotly = function module() {
    var exports = {};
    exports.convert = function(_inputConfig, reverse) {
        var outputConfig = {};
        if (_inputConfig.data) {
            outputConfig.data = _inputConfig.data.map(function(d, i) {
                var r = extendDeepAll({}, d);
                var toTranslate = [
                    [ r, [ 'marker', 'color' ], [ 'color' ] ],
                    [ r, [ 'marker', 'opacity' ], [ 'opacity' ] ],
                    [ r, [ 'marker', 'line', 'color' ], [ 'strokeColor' ] ],
                    [ r, [ 'marker', 'line', 'dash' ], [ 'strokeDash' ] ],
                    [ r, [ 'marker', 'line', 'width' ], [ 'strokeSize' ] ],
                    [ r, [ 'marker', 'symbol' ], [ 'dotType' ] ],
                    [ r, [ 'marker', 'size' ], [ 'dotSize' ] ],
                    [ r, [ 'marker', 'barWidth' ], [ 'barWidth' ] ],
                    [ r, [ 'line', 'interpolation' ], [ 'lineInterpolation' ] ],
                    [ r, [ 'showlegend' ], [ 'visibleInLegend' ] ]
                ];
                toTranslate.forEach(function(d, i) {
                    µ.util.translator.apply(null, d.concat(reverse));
                });

                if (!reverse) delete r.marker;
                if (reverse) delete r.groupId;
                if (!reverse) {
                    if (r.type === 'scatter') {
                        if (r.mode === 'lines') r.geometry = 'LinePlot'; else if (r.mode === 'markers') r.geometry = 'DotPlot'; else if (r.mode === 'lines+markers') {
                            r.geometry = 'LinePlot';
                            r.dotVisible = true;
                        }
                    } else if (r.type === 'area') r.geometry = 'AreaChart'; else if (r.type === 'bar') r.geometry = 'BarChart';
                    delete r.mode;
                    delete r.type;
                } else {
                    if (r.geometry === 'LinePlot') {
                        r.type = 'scatter';
                        if (r.dotVisible === true) {
                            delete r.dotVisible;
                            r.mode = 'lines+markers';
                        } else r.mode = 'lines';
                    } else if (r.geometry === 'DotPlot') {
                        r.type = 'scatter';
                        r.mode = 'markers';
                    } else if (r.geometry === 'AreaChart') r.type = 'area'; else if (r.geometry === 'BarChart') r.type = 'bar';
                    delete r.geometry;
                }
                return r;
            });
            if (!reverse && _inputConfig.layout && _inputConfig.layout.barmode === 'stack') {
                var duplicates = µ.util.duplicates(outputConfig.data.map(function(d, i) {
                    return d.geometry;
                }));
                outputConfig.data.forEach(function(d, i) {
                    var idx = duplicates.indexOf(d.geometry);
                    if (idx != -1) outputConfig.data[i].groupId = idx;
                });
            }
        }
        if (_inputConfig.layout) {
            var r = extendDeepAll({}, _inputConfig.layout);
            var toTranslate = [
                [ r, [ 'plot_bgcolor' ], [ 'backgroundColor' ] ],
                [ r, [ 'showlegend' ], [ 'showLegend' ] ],
                [ r, [ 'radialaxis' ], [ 'radialAxis' ] ],
                [ r, [ 'angularaxis' ], [ 'angularAxis' ] ],
                [ r.angularaxis, [ 'showline' ], [ 'gridLinesVisible' ] ],
                [ r.angularaxis, [ 'showticklabels' ], [ 'labelsVisible' ] ],
                [ r.angularaxis, [ 'nticks' ], [ 'ticksCount' ] ],
                [ r.angularaxis, [ 'tickorientation' ], [ 'tickOrientation' ] ],
                [ r.angularaxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ],
                [ r.angularaxis, [ 'range' ], [ 'domain' ] ],
                [ r.angularaxis, [ 'endpadding' ], [ 'endPadding' ] ],
                [ r.radialaxis, [ 'showline' ], [ 'gridLinesVisible' ] ],
                [ r.radialaxis, [ 'tickorientation' ], [ 'tickOrientation' ] ],
                [ r.radialaxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ],
                [ r.radialaxis, [ 'range' ], [ 'domain' ] ],
                [ r.angularAxis, [ 'showline' ], [ 'gridLinesVisible' ] ],
                [ r.angularAxis, [ 'showticklabels' ], [ 'labelsVisible' ] ],
                [ r.angularAxis, [ 'nticks' ], [ 'ticksCount' ] ],
                [ r.angularAxis, [ 'tickorientation' ], [ 'tickOrientation' ] ],
                [ r.angularAxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ],
                [ r.angularAxis, [ 'range' ], [ 'domain' ] ],
                [ r.angularAxis, [ 'endpadding' ], [ 'endPadding' ] ],
                [ r.radialAxis, [ 'showline' ], [ 'gridLinesVisible' ] ],
                [ r.radialAxis, [ 'tickorientation' ], [ 'tickOrientation' ] ],
                [ r.radialAxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ],
                [ r.radialAxis, [ 'range' ], [ 'domain' ] ],
                [ r.font, [ 'outlinecolor' ], [ 'outlineColor' ] ],
                [ r.legend, [ 'traceorder' ], [ 'reverseOrder' ] ],
                [ r, [ 'labeloffset' ], [ 'labelOffset' ] ],
                [ r, [ 'defaultcolorrange' ], [ 'defaultColorRange' ] ]
            ];
            toTranslate.forEach(function(d, i) {
                µ.util.translator.apply(null, d.concat(reverse));
            });

            if (!reverse) {
                if (r.angularAxis && typeof r.angularAxis.ticklen !== 'undefined') r.tickLength = r.angularAxis.ticklen;
                if (r.angularAxis && typeof r.angularAxis.tickcolor !== 'undefined') r.tickColor = r.angularAxis.tickcolor;
            } else {
                if (typeof r.tickLength !== 'undefined') {
                    r.angularaxis.ticklen = r.tickLength;
                    delete r.tickLength;
                }
                if (r.tickColor) {
                    r.angularaxis.tickcolor = r.tickColor;
                    delete r.tickColor;
                }
            }
            if (r.legend && typeof r.legend.reverseOrder != 'boolean') {
                r.legend.reverseOrder = r.legend.reverseOrder != 'normal';
            }
            if (r.legend && typeof r.legend.traceorder == 'boolean') {
                r.legend.traceorder = r.legend.traceorder ? 'reversed' : 'normal';
                delete r.legend.reverseOrder;
            }
            if (r.margin && typeof r.margin.t != 'undefined') {
                var source = [ 't', 'r', 'b', 'l', 'pad' ];
                var target = [ 'top', 'right', 'bottom', 'left', 'pad' ];
                var margin = {};
                d3.entries(r.margin).forEach(function(dB, iB) {
                    margin[target[source.indexOf(dB.key)]] = dB.value;
                });
                r.margin = margin;
            }
            if (reverse) {
                delete r.needsEndSpacing;
                delete r.minorTickColor;
                delete r.minorTicks;
                delete r.angularaxis.ticksCount;
                delete r.angularaxis.ticksCount;
                delete r.angularaxis.ticksStep;
                delete r.angularaxis.rewriteTicks;
                delete r.angularaxis.nticks;
                delete r.radialaxis.ticksCount;
                delete r.radialaxis.ticksCount;
                delete r.radialaxis.ticksStep;
                delete r.radialaxis.rewriteTicks;
                delete r.radialaxis.nticks;
            }
            outputConfig.layout = r;
        }
        return outputConfig;
    };
    return exports;
};

},{"../../../constants/alignment":669,"../../../lib":697,"d3":151}],817:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

/* eslint-disable new-cap */

'use strict';

var d3 = _dereq_('d3');
var Lib = _dereq_('../../../lib');
var Color = _dereq_('../../../components/color');

var micropolar = _dereq_('./micropolar');
var UndoManager = _dereq_('./undo_manager');
var extendDeepAll = Lib.extendDeepAll;

var manager = module.exports = {};

manager.framework = function(_gd) {
    var config, previousConfigClone, plot, convertedInput, container;
    var undoManager = new UndoManager();

    function exports(_inputConfig, _container) {
        if(_container) container = _container;
        d3.select(d3.select(container).node().parentNode).selectAll('.svg-container>*:not(.chart-root)').remove();

        config = (!config) ?
            _inputConfig :
            extendDeepAll(config, _inputConfig);

        if(!plot) plot = micropolar.Axis();
        convertedInput = micropolar.adapter.plotly().convert(config);
        plot.config(convertedInput).render(container);
        _gd.data = config.data;
        _gd.layout = config.layout;
        manager.fillLayout(_gd);
        return config;
    }
    exports.isPolar = true;
    exports.svg = function() { return plot.svg(); };
    exports.getConfig = function() { return config; };
    exports.getLiveConfig = function() {
        return micropolar.adapter.plotly().convert(plot.getLiveConfig(), true);
    };
    exports.getLiveScales = function() { return {t: plot.angularScale(), r: plot.radialScale()}; };
    exports.setUndoPoint = function() {
        var that = this;
        var configClone = micropolar.util.cloneJson(config);
        (function(_configClone, _previousConfigClone) {
            undoManager.add({
                undo: function() {
                    if(_previousConfigClone) that(_previousConfigClone);
                },
                redo: function() {
                    that(_configClone);
                }
            });
        })(configClone, previousConfigClone);
        previousConfigClone = micropolar.util.cloneJson(configClone);
    };
    exports.undo = function() { undoManager.undo(); };
    exports.redo = function() { undoManager.redo(); };
    return exports;
};

manager.fillLayout = function(_gd) {
    var container = d3.select(_gd).selectAll('.plot-container');
    var paperDiv = container.selectAll('.svg-container');
    var paper = _gd.framework && _gd.framework.svg && _gd.framework.svg();
    var dflts = {
        width: 800,
        height: 600,
        paper_bgcolor: Color.background,
        _container: container,
        _paperdiv: paperDiv,
        _paper: paper
    };

    _gd._fullLayout = extendDeepAll(dflts, _gd.layout);
};

},{"../../../components/color":574,"../../../lib":697,"./micropolar":816,"./undo_manager":818,"d3":151}],818:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// Modified from https://github.com/ArthurClemens/Javascript-Undo-Manager
// Copyright (c) 2010-2013 Arthur Clemens, arthur@visiblearea.com
module.exports = function UndoManager() {
    var undoCommands = [];
    var index = -1;
    var isExecuting = false;
    var callback;

    function execute(command, action) {
        if(!command) return this;

        isExecuting = true;
        command[action]();
        isExecuting = false;

        return this;
    }

    return {
        add: function(command) {
            if(isExecuting) return this;
            undoCommands.splice(index + 1, undoCommands.length - index);
            undoCommands.push(command);
            index = undoCommands.length - 1;
            return this;
        },
        setCallback: function(callbackFunc) { callback = callbackFunc; },
        undo: function() {
            var command = undoCommands[index];
            if(!command) return this;
            execute(command, 'undo');
            index -= 1;
            if(callback) callback(command.undo);
            return this;
        },
        redo: function() {
            var command = undoCommands[index + 1];
            if(!command) return this;
            execute(command, 'redo');
            index += 1;
            if(callback) callback(command.redo);
            return this;
        },
        clear: function() {
            undoCommands = [];
            index = -1;
        },
        hasUndo: function() { return index !== -1; },
        hasRedo: function() { return index < (undoCommands.length - 1); },
        getCommands: function() { return undoCommands; },
        getPreviousCommand: function() { return undoCommands[index - 1]; },
        getIndex: function() { return index; }
    };
};

},{}],819:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var tinycolor = _dereq_('tinycolor2');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Color = _dereq_('../../components/color');
var Drawing = _dereq_('../../components/drawing');
var Plots = _dereq_('../plots');
var Axes = _dereq_('../../plots/cartesian/axes');
var setConvertCartesian = _dereq_('../cartesian/set_convert');
var setConvertPolar = _dereq_('./set_convert');
var doAutoRange = _dereq_('../cartesian/autorange').doAutoRange;
var dragBox = _dereq_('../cartesian/dragbox');
var dragElement = _dereq_('../../components/dragelement');
var Fx = _dereq_('../../components/fx');
var Titles = _dereq_('../../components/titles');
var prepSelect = _dereq_('../cartesian/select').prepSelect;
var selectOnClick = _dereq_('../cartesian/select').selectOnClick;
var clearSelect = _dereq_('../cartesian/select').clearSelect;
var setCursor = _dereq_('../../lib/setcursor');
var clearGlCanvases = _dereq_('../../lib/clear_gl_canvases');
var redrawReglTraces = _dereq_('../../plot_api/subroutines').redrawReglTraces;

var MID_SHIFT = _dereq_('../../constants/alignment').MID_SHIFT;
var constants = _dereq_('./constants');
var helpers = _dereq_('./helpers');

var _ = Lib._;
var mod = Lib.mod;
var deg2rad = Lib.deg2rad;
var rad2deg = Lib.rad2deg;

function Polar(gd, id) {
    this.id = id;
    this.gd = gd;

    this._hasClipOnAxisFalse = null;
    this.vangles = null;
    this.radialAxisAngle = null;
    this.traceHash = {};
    this.layers = {};
    this.clipPaths = {};
    this.clipIds = {};
    this.viewInitial = {};

    var fullLayout = gd._fullLayout;
    var clipIdBase = 'clip' + fullLayout._uid + id;

    this.clipIds.forTraces = clipIdBase + '-for-traces';
    this.clipPaths.forTraces = fullLayout._clips.append('clipPath')
        .attr('id', this.clipIds.forTraces);
    this.clipPaths.forTraces.append('path');

    this.framework = fullLayout._polarlayer.append('g')
        .attr('class', id);

    // unfortunately, we have to keep track of some axis tick settings
    // as polar subplots do not implement the 'ticks' editType
    this.radialTickLayout = null;
    this.angularTickLayout = null;
}

var proto = Polar.prototype;

module.exports = function createPolar(gd, id) {
    return new Polar(gd, id);
};

proto.plot = function(polarCalcData, fullLayout) {
    var _this = this;
    var polarLayout = fullLayout[_this.id];

    _this._hasClipOnAxisFalse = false;
    for(var i = 0; i < polarCalcData.length; i++) {
        var trace = polarCalcData[i][0].trace;
        if(trace.cliponaxis === false) {
            _this._hasClipOnAxisFalse = true;
            break;
        }
    }

    _this.updateLayers(fullLayout, polarLayout);
    _this.updateLayout(fullLayout, polarLayout);
    Plots.generalUpdatePerTraceModule(_this.gd, _this, polarCalcData, polarLayout);
    _this.updateFx(fullLayout, polarLayout);
};

proto.updateLayers = function(fullLayout, polarLayout) {
    var _this = this;
    var layers = _this.layers;
    var radialLayout = polarLayout.radialaxis;
    var angularLayout = polarLayout.angularaxis;
    var layerNames = constants.layerNames;

    var frontPlotIndex = layerNames.indexOf('frontplot');
    var layerData = layerNames.slice(0, frontPlotIndex);
    var isAngularAxisBelowTraces = angularLayout.layer === 'below traces';
    var isRadialAxisBelowTraces = radialLayout.layer === 'below traces';

    if(isAngularAxisBelowTraces) layerData.push('angular-line');
    if(isRadialAxisBelowTraces) layerData.push('radial-line');
    if(isAngularAxisBelowTraces) layerData.push('angular-axis');
    if(isRadialAxisBelowTraces) layerData.push('radial-axis');

    layerData.push('frontplot');

    if(!isAngularAxisBelowTraces) layerData.push('angular-line');
    if(!isRadialAxisBelowTraces) layerData.push('radial-line');
    if(!isAngularAxisBelowTraces) layerData.push('angular-axis');
    if(!isRadialAxisBelowTraces) layerData.push('radial-axis');

    var join = _this.framework.selectAll('.polarsublayer')
        .data(layerData, String);

    join.enter().append('g')
        .attr('class', function(d) { return 'polarsublayer ' + d;})
        .each(function(d) {
            var sel = layers[d] = d3.select(this);

            switch(d) {
                case 'frontplot':
                    // TODO add option to place in 'backplot' layer??
                    sel.append('g').classed('barlayer', true);
                    sel.append('g').classed('scatterlayer', true);
                    break;
                case 'backplot':
                    sel.append('g').classed('maplayer', true);
                    break;
                case 'plotbg':
                    layers.bg = sel.append('path');
                    break;
                case 'radial-grid':
                    sel.style('fill', 'none');
                    break;
                case 'angular-grid':
                    sel.style('fill', 'none');
                    break;
                case 'radial-line':
                    sel.append('line').style('fill', 'none');
                    break;
                case 'angular-line':
                    sel.append('path').style('fill', 'none');
                    break;
            }
        });

    join.order();
};

/* Polar subplots juggle with 6 'axis objects' (!), these are:
 *
 * - polarLayout.radialaxis (aka radialLayout in this file):
 * - polarLayout.angularaxis (aka angularLayout in this file):
 *   used for data -> calcdata conversions (aka d2c) during the calc step
 *
 * - this.radialAxis
 *   extends polarLayout.radialaxis, adds mocked 'domain' and
 *   few other keys in order to reuse Cartesian doAutoRange and the Axes
 *   drawing routines.
 *   used for calcdata -> geometric conversions (aka c2g) during the plot step
 *   + setGeometry setups ax.c2g for given ax.range
 *   + setScale setups ax._m,ax._b for given ax.range
 *
 * - this.angularAxis
 *   extends polarLayout.angularaxis, adds mocked 'range' and 'domain' and
 *   a few other keys in order to reuse the Axes drawing routines.
 *   used for calcdata -> geometric conversions (aka c2g) during the plot step
 *   + setGeometry setups ax.c2g given ax.rotation, ax.direction & ax._categories,
 *                 and mocks ax.range
 *   + setScale setups ax._m,ax._b with that mocked ax.range
 *
 * - this.xaxis
 * - this.yaxis
 *   setup so that polar traces can reuse plot methods of Cartesian traces
 *   which mostly rely on 2pixel methods (e.g ax.c2p)
 */
proto.updateLayout = function(fullLayout, polarLayout) {
    var _this = this;
    var layers = _this.layers;
    var gs = fullLayout._size;

    // axis attributes
    var radialLayout = polarLayout.radialaxis;
    var angularLayout = polarLayout.angularaxis;
    // layout domains
    var xDomain = polarLayout.domain.x;
    var yDomain = polarLayout.domain.y;
    // offsets from paper edge to layout domain box
    _this.xOffset = gs.l + gs.w * xDomain[0];
    _this.yOffset = gs.t + gs.h * (1 - yDomain[1]);
    // lengths of the layout domain box
    var xLength = _this.xLength = gs.w * (xDomain[1] - xDomain[0]);
    var yLength = _this.yLength = gs.h * (yDomain[1] - yDomain[0]);
    // sector to plot
    var sector = polarLayout.sector;
    _this.sectorInRad = sector.map(deg2rad);
    var sectorBBox = _this.sectorBBox = computeSectorBBox(sector);
    var dxSectorBBox = sectorBBox[2] - sectorBBox[0];
    var dySectorBBox = sectorBBox[3] - sectorBBox[1];
    // aspect ratios
    var arDomain = yLength / xLength;
    var arSector = Math.abs(dySectorBBox / dxSectorBBox);
    // actual lengths and domains of subplot box
    var xLength2, yLength2;
    var xDomain2, yDomain2;
    var gap;
    if(arDomain > arSector) {
        xLength2 = xLength;
        yLength2 = xLength * arSector;
        gap = (yLength - yLength2) / gs.h / 2;
        xDomain2 = [xDomain[0], xDomain[1]];
        yDomain2 = [yDomain[0] + gap, yDomain[1] - gap];
    } else {
        xLength2 = yLength / arSector;
        yLength2 = yLength;
        gap = (xLength - xLength2) / gs.w / 2;
        xDomain2 = [xDomain[0] + gap, xDomain[1] - gap];
        yDomain2 = [yDomain[0], yDomain[1]];
    }
    _this.xLength2 = xLength2;
    _this.yLength2 = yLength2;
    _this.xDomain2 = xDomain2;
    _this.yDomain2 = yDomain2;
    // actual offsets from paper edge to the subplot box top-left corner
    var xOffset2 = _this.xOffset2 = gs.l + gs.w * xDomain2[0];
    var yOffset2 = _this.yOffset2 = gs.t + gs.h * (1 - yDomain2[1]);
    // circle radius in px
    var radius = _this.radius = xLength2 / dxSectorBBox;
    // 'inner' radius in px (when polar.hole is set)
    var innerRadius = _this.innerRadius = polarLayout.hole * radius;
    // circle center position in px
    var cx = _this.cx = xOffset2 - radius * sectorBBox[0];
    var cy = _this.cy = yOffset2 + radius * sectorBBox[3];
    // circle center in the coordinate system of plot area
    var cxx = _this.cxx = cx - xOffset2;
    var cyy = _this.cyy = cy - yOffset2;

    _this.radialAxis = _this.mockAxis(fullLayout, polarLayout, radialLayout, {
        // make this an 'x' axis to make positioning (especially rotation) easier
        _id: 'x',
        // convert to 'x' axis equivalent
        side: {
            counterclockwise: 'top',
            clockwise: 'bottom'
        }[radialLayout.side],
        // spans length 1 radius
        domain: [innerRadius / gs.w, radius / gs.w]
    });

    _this.angularAxis = _this.mockAxis(fullLayout, polarLayout, angularLayout, {
        side: 'right',
        // to get auto nticks right
        domain: [0, Math.PI],
        // don't pass through autorange logic
        autorange: false
    });

    _this.doAutoRange(fullLayout, polarLayout);
    // N.B. this sets _this.vangles
    _this.updateAngularAxis(fullLayout, polarLayout);
    // N.B. this sets _this.radialAxisAngle
    _this.updateRadialAxis(fullLayout, polarLayout);
    _this.updateRadialAxisTitle(fullLayout, polarLayout);

    _this.xaxis = _this.mockCartesianAxis(fullLayout, polarLayout, {
        _id: 'x',
        domain: xDomain2
    });

    _this.yaxis = _this.mockCartesianAxis(fullLayout, polarLayout, {
        _id: 'y',
        domain: yDomain2
    });

    var dPath = _this.pathSubplot();

    _this.clipPaths.forTraces.select('path')
        .attr('d', dPath)
        .attr('transform', strTranslate(cxx, cyy));

    layers.frontplot
        .attr('transform', strTranslate(xOffset2, yOffset2))
        .call(Drawing.setClipUrl, _this._hasClipOnAxisFalse ? null : _this.clipIds.forTraces, _this.gd);

    layers.bg
        .attr('d', dPath)
        .attr('transform', strTranslate(cx, cy))
        .call(Color.fill, polarLayout.bgcolor);
};

proto.mockAxis = function(fullLayout, polarLayout, axLayout, opts) {
    var commonOpts = {
        // to get _boundingBox computation right when showticklabels is false
        anchor: 'free',
        position: 0
    };

    var ax = Lib.extendFlat(commonOpts, axLayout, opts);
    setConvertPolar(ax, polarLayout, fullLayout);
    return ax;
};

proto.mockCartesianAxis = function(fullLayout, polarLayout, opts) {
    var _this = this;
    var axId = opts._id;

    var ax = Lib.extendFlat({type: 'linear'}, opts);
    setConvertCartesian(ax, fullLayout);

    var bboxIndices = {
        x: [0, 2],
        y: [1, 3]
    };

    ax.setRange = function() {
        var sectorBBox = _this.sectorBBox;
        var ind = bboxIndices[axId];
        var rl = _this.radialAxis._rl;
        var drl = (rl[1] - rl[0]) / (1 - polarLayout.hole);
        ax.range = [sectorBBox[ind[0]] * drl, sectorBBox[ind[1]] * drl];
    };

    ax.isPtWithinRange = axId === 'x' ?
        function(d) { return _this.isPtInside(d); } :
        function() { return true; };

    ax.setRange();
    ax.setScale();
    return ax;
};

proto.doAutoRange = function(fullLayout, polarLayout) {
    var gd = this.gd;
    var radialAxis = this.radialAxis;
    var radialLayout = polarLayout.radialaxis;

    radialAxis.setScale();
    doAutoRange(gd, radialAxis);

    var rng = radialAxis.range;
    radialLayout.range = rng.slice();
    radialLayout._input.range = rng.slice();

    radialAxis._rl = [
        radialAxis.r2l(rng[0], null, 'gregorian'),
        radialAxis.r2l(rng[1], null, 'gregorian')
    ];
};

proto.updateRadialAxis = function(fullLayout, polarLayout) {
    var _this = this;
    var gd = _this.gd;
    var layers = _this.layers;
    var radius = _this.radius;
    var innerRadius = _this.innerRadius;
    var cx = _this.cx;
    var cy = _this.cy;
    var radialLayout = polarLayout.radialaxis;
    var a0 = mod(polarLayout.sector[0], 360);
    var ax = _this.radialAxis;
    var hasRoomForIt = innerRadius < radius;

    _this.fillViewInitialKey('radialaxis.angle', radialLayout.angle);
    _this.fillViewInitialKey('radialaxis.range', ax.range.slice());

    ax.setGeometry();

    // rotate auto tick labels by 180 if in quadrant II and III to make them
    // readable from left-to-right
    //
    // TODO try moving deeper in Axes.drawLabels for better results?
    if(ax.tickangle === 'auto' && (a0 > 90 && a0 <= 270)) {
        ax.tickangle = 180;
    }

    // easier to set rotate angle with custom translate function
    var transFn = function(d) {
        return 'translate(' + (ax.l2p(d.x) + innerRadius) + ',0)';
    };

    // set special grid path function
    var gridPathFn = function(d) {
        return _this.pathArc(ax.r2p(d.x) + innerRadius);
    };

    var newTickLayout = strTickLayout(radialLayout);
    if(_this.radialTickLayout !== newTickLayout) {
        layers['radial-axis'].selectAll('.xtick').remove();
        _this.radialTickLayout = newTickLayout;
    }

    if(hasRoomForIt) {
        ax.setScale();

        var vals = Axes.calcTicks(ax);
        var valsClipped = Axes.clipEnds(ax, vals);
        var tickSign = Axes.getTickSigns(ax)[2];

        Axes.drawTicks(gd, ax, {
            vals: vals,
            layer: layers['radial-axis'],
            path: Axes.makeTickPath(ax, 0, tickSign),
            transFn: transFn,
            crisp: false
        });

        Axes.drawGrid(gd, ax, {
            vals: valsClipped,
            layer: layers['radial-grid'],
            path: gridPathFn,
            transFn: Lib.noop,
            crisp: false
        });

        Axes.drawLabels(gd, ax, {
            vals: vals,
            layer: layers['radial-axis'],
            transFn: transFn,
            labelFns: Axes.makeLabelFns(ax, 0)
        });
    }

    // stash 'actual' radial axis angle for drag handlers (in degrees)
    var angle = _this.radialAxisAngle = _this.vangles ?
        rad2deg(snapToVertexAngle(deg2rad(radialLayout.angle), _this.vangles)) :
        radialLayout.angle;

    var tLayer = strTranslate(cx, cy);
    var tLayer2 = tLayer + strRotate(-angle);

    updateElement(
        layers['radial-axis'],
        hasRoomForIt && (radialLayout.showticklabels || radialLayout.ticks),
        {transform: tLayer2}
    );

    updateElement(
        layers['radial-grid'],
        hasRoomForIt && radialLayout.showgrid,
        {transform: tLayer}
    );

    updateElement(
        layers['radial-line'].select('line'),
        hasRoomForIt && radialLayout.showline,
        {
            x1: innerRadius,
            y1: 0,
            x2: radius,
            y2: 0,
            transform: tLayer2
        }
    )
    .attr('stroke-width', radialLayout.linewidth)
    .call(Color.stroke, radialLayout.linecolor);
};

proto.updateRadialAxisTitle = function(fullLayout, polarLayout, _angle) {
    var _this = this;
    var gd = _this.gd;
    var radius = _this.radius;
    var cx = _this.cx;
    var cy = _this.cy;
    var radialLayout = polarLayout.radialaxis;
    var titleClass = _this.id + 'title';

    var angle = _angle !== undefined ? _angle : _this.radialAxisAngle;
    var angleRad = deg2rad(angle);
    var cosa = Math.cos(angleRad);
    var sina = Math.sin(angleRad);

    var pad = 0;

    // Hint: no need to check if there is in fact a title.text set
    // because if plot is editable, pad needs to be calculated anyways
    // to properly show placeholder text when title is empty.
    if(radialLayout.title) {
        var h = Drawing.bBox(_this.layers['radial-axis'].node()).height;
        var ts = radialLayout.title.font.size;
        pad = radialLayout.side === 'counterclockwise' ?
            -h - ts * 0.4 :
            h + ts * 0.8;
    }

    _this.layers['radial-axis-title'] = Titles.draw(gd, titleClass, {
        propContainer: radialLayout,
        propName: _this.id + '.radialaxis.title',
        placeholder: _(gd, 'Click to enter radial axis title'),
        attributes: {
            x: cx + (radius / 2) * cosa + pad * sina,
            y: cy - (radius / 2) * sina + pad * cosa,
            'text-anchor': 'middle'
        },
        transform: {rotate: -angle}
    });
};

proto.updateAngularAxis = function(fullLayout, polarLayout) {
    var _this = this;
    var gd = _this.gd;
    var layers = _this.layers;
    var radius = _this.radius;
    var innerRadius = _this.innerRadius;
    var cx = _this.cx;
    var cy = _this.cy;
    var angularLayout = polarLayout.angularaxis;
    var ax = _this.angularAxis;

    _this.fillViewInitialKey('angularaxis.rotation', angularLayout.rotation);

    ax.setGeometry();
    ax.setScale();

    // 't'ick to 'g'eometric radians is used all over the place here
    var t2g = function(d) { return ax.t2g(d.x); };

    // run rad2deg on tick0 and ditck for thetaunit: 'radians' axes
    if(ax.type === 'linear' && ax.thetaunit === 'radians') {
        ax.tick0 = rad2deg(ax.tick0);
        ax.dtick = rad2deg(ax.dtick);
    }

    var _transFn = function(rad) {
        return strTranslate(cx + radius * Math.cos(rad), cy - radius * Math.sin(rad));
    };

    var transFn = function(d) {
        return _transFn(t2g(d));
    };

    var transFn2 = function(d) {
        var rad = t2g(d);
        return _transFn(rad) + strRotate(-rad2deg(rad));
    };

    var gridPathFn = function(d) {
        var rad = t2g(d);
        var cosRad = Math.cos(rad);
        var sinRad = Math.sin(rad);
        return 'M' + [cx + innerRadius * cosRad, cy - innerRadius * sinRad] +
            'L' + [cx + radius * cosRad, cy - radius * sinRad];
    };

    var out = Axes.makeLabelFns(ax, 0);
    var labelStandoff = out.labelStandoff;
    var labelFns = {};

    labelFns.xFn = function(d) {
        var rad = t2g(d);
        return Math.cos(rad) * labelStandoff;
    };

    labelFns.yFn = function(d) {
        var rad = t2g(d);
        var ff = Math.sin(rad) > 0 ? 0.2 : 1;
        return -Math.sin(rad) * (labelStandoff + d.fontSize * ff) +
            Math.abs(Math.cos(rad)) * (d.fontSize * MID_SHIFT);
    };

    labelFns.anchorFn = function(d) {
        var rad = t2g(d);
        var cos = Math.cos(rad);
        return Math.abs(cos) < 0.1 ?
            'middle' :
            (cos > 0 ? 'start' : 'end');
    };

    labelFns.heightFn = function(d, a, h) {
        var rad = t2g(d);
        return -0.5 * (1 + Math.sin(rad)) * h;
    };

    var newTickLayout = strTickLayout(angularLayout);
    if(_this.angularTickLayout !== newTickLayout) {
        layers['angular-axis'].selectAll('.' + ax._id + 'tick').remove();
        _this.angularTickLayout = newTickLayout;
    }

    var vals = Axes.calcTicks(ax);

    // angle of polygon vertices in geometric radians (null means circles)
    // TODO what to do when ax.period > ax._categories ??
    var vangles;
    if(polarLayout.gridshape === 'linear') {
        vangles = vals.map(t2g);

        // ax._vals should be always ordered, make them
        // always turn counterclockwise for convenience here
        if(Lib.angleDelta(vangles[0], vangles[1]) < 0) {
            vangles = vangles.slice().reverse();
        }
    } else {
        vangles = null;
    }
    _this.vangles = vangles;

    // Use tickval filter for category axes instead of tweaking
    // the range w.r.t sector, so that sectors that cross 360 can
    // show all their ticks.
    if(ax.type === 'category') {
        vals = vals.filter(function(d) {
            return Lib.isAngleInsideSector(t2g(d), _this.sectorInRad);
        });
    }

    if(ax.visible) {
        var tickSign = ax.ticks === 'inside' ? -1 : 1;
        var pad = (ax.linewidth || 1) / 2;

        Axes.drawTicks(gd, ax, {
            vals: vals,
            layer: layers['angular-axis'],
            path: 'M' + (tickSign * pad) + ',0h' + (tickSign * ax.ticklen),
            transFn: transFn2,
            crisp: false
        });

        Axes.drawGrid(gd, ax, {
            vals: vals,
            layer: layers['angular-grid'],
            path: gridPathFn,
            transFn: Lib.noop,
            crisp: false
        });

        Axes.drawLabels(gd, ax, {
            vals: vals,
            layer: layers['angular-axis'],
            repositionOnUpdate: true,
            transFn: transFn,
            labelFns: labelFns
        });
    }

    // TODO maybe two arcs is better here?
    // maybe split style attributes between inner and outer angular axes?

    updateElement(layers['angular-line'].select('path'), angularLayout.showline, {
        d: _this.pathSubplot(),
        transform: strTranslate(cx, cy)
    })
    .attr('stroke-width', angularLayout.linewidth)
    .call(Color.stroke, angularLayout.linecolor);
};

proto.updateFx = function(fullLayout, polarLayout) {
    if(!this.gd._context.staticPlot) {
        this.updateAngularDrag(fullLayout);
        this.updateRadialDrag(fullLayout, polarLayout, 0);
        this.updateRadialDrag(fullLayout, polarLayout, 1);
        this.updateMainDrag(fullLayout);
    }
};

proto.updateMainDrag = function(fullLayout) {
    var _this = this;
    var gd = _this.gd;
    var layers = _this.layers;
    var zoomlayer = fullLayout._zoomlayer;
    var MINZOOM = constants.MINZOOM;
    var OFFEDGE = constants.OFFEDGE;
    var radius = _this.radius;
    var innerRadius = _this.innerRadius;
    var cx = _this.cx;
    var cy = _this.cy;
    var cxx = _this.cxx;
    var cyy = _this.cyy;
    var sectorInRad = _this.sectorInRad;
    var vangles = _this.vangles;
    var radialAxis = _this.radialAxis;
    var clampTiny = helpers.clampTiny;
    var findXYatLength = helpers.findXYatLength;
    var findEnclosingVertexAngles = helpers.findEnclosingVertexAngles;
    var chw = constants.cornerHalfWidth;
    var chl = constants.cornerLen / 2;

    var mainDrag = dragBox.makeDragger(layers, 'path', 'maindrag', 'crosshair');

    d3.select(mainDrag)
        .attr('d', _this.pathSubplot())
        .attr('transform', strTranslate(cx, cy));

    var dragOpts = {
        element: mainDrag,
        gd: gd,
        subplot: _this.id,
        plotinfo: {
            id: _this.id,
            xaxis: _this.xaxis,
            yaxis: _this.yaxis
        },
        xaxes: [_this.xaxis],
        yaxes: [_this.yaxis]
    };

    // mouse px position at drag start (0), move (1)
    var x0, y0;
    // radial distance from circle center at drag start (0), move (1)
    var r0, r1;
    // zoombox persistent quantities
    var path0, dimmed, lum;
    // zoombox, corners elements
    var zb, corners;

    function norm(x, y) {
        return Math.sqrt(x * x + y * y);
    }

    function xy2r(x, y) {
        return norm(x - cxx, y - cyy);
    }

    function xy2a(x, y) {
        return Math.atan2(cyy - y, x - cxx);
    }

    function ra2xy(r, a) {
        return [r * Math.cos(a), r * Math.sin(-a)];
    }

    function pathCorner(r, a) {
        if(r === 0) return _this.pathSector(2 * chw);

        var da = chl / r;
        var am = a - da;
        var ap = a + da;
        var rb = Math.max(0, Math.min(r, radius));
        var rm = rb - chw;
        var rp = rb + chw;

        return 'M' + ra2xy(rm, am) +
            'A' + [rm, rm] + ' 0,0,0 ' + ra2xy(rm, ap) +
            'L' + ra2xy(rp, ap) +
            'A' + [rp, rp] + ' 0,0,1 ' + ra2xy(rp, am) +
            'Z';
    }

    // (x,y) is the pt at middle of the va0 <-> va1 edge
    //
    // ... we could eventually add another mode for cursor
    // angles 'close to' enough to a particular vertex.
    function pathCornerForPolygons(r, va0, va1) {
        if(r === 0) return _this.pathSector(2 * chw);

        var xy0 = ra2xy(r, va0);
        var xy1 = ra2xy(r, va1);
        var x = clampTiny((xy0[0] + xy1[0]) / 2);
        var y = clampTiny((xy0[1] + xy1[1]) / 2);
        var innerPts, outerPts;

        if(x && y) {
            var m = y / x;
            var mperp = -1 / m;
            var midPts = findXYatLength(chw, m, x, y);
            innerPts = findXYatLength(chl, mperp, midPts[0][0], midPts[0][1]);
            outerPts = findXYatLength(chl, mperp, midPts[1][0], midPts[1][1]);
        } else {
            var dx, dy;
            if(y) {
                // horizontal handles
                dx = chl;
                dy = chw;
            } else {
                // vertical handles
                dx = chw;
                dy = chl;
            }
            innerPts = [[x - dx, y - dy], [x + dx, y - dy]];
            outerPts = [[x - dx, y + dy], [x + dx, y + dy]];
        }

        return 'M' + innerPts.join('L') +
            'L' + outerPts.reverse().join('L') + 'Z';
    }

    function zoomPrep() {
        r0 = null;
        r1 = null;
        path0 = _this.pathSubplot();
        dimmed = false;

        var polarLayoutNow = gd._fullLayout[_this.id];
        lum = tinycolor(polarLayoutNow.bgcolor).getLuminance();

        zb = dragBox.makeZoombox(zoomlayer, lum, cx, cy, path0);
        zb.attr('fill-rule', 'evenodd');
        corners = dragBox.makeCorners(zoomlayer, cx, cy);
        clearSelect(zoomlayer);
    }

    // N.B. this sets scoped 'r0' and 'r1'
    // return true if 'valid' zoom distance, false otherwise
    function clampAndSetR0R1(rr0, rr1) {
        rr1 = Math.max(Math.min(rr1, radius), innerRadius);

        // starting or ending drag near center (outer edge),
        // clamps radial distance at origin (at r=radius)
        if(rr0 < OFFEDGE) rr0 = 0;
        else if((radius - rr0) < OFFEDGE) rr0 = radius;
        else if(rr1 < OFFEDGE) rr1 = 0;
        else if((radius - rr1) < OFFEDGE) rr1 = radius;

        // make sure r0 < r1,
        // to get correct fill pattern in path1 below
        if(Math.abs(rr1 - rr0) > MINZOOM) {
            if(rr0 < rr1) {
                r0 = rr0;
                r1 = rr1;
            } else {
                r0 = rr1;
                r1 = rr0;
            }
            return true;
        } else {
            r0 = null;
            r1 = null;
            return false;
        }
    }

    function applyZoomMove(path1, cpath) {
        path1 = path1 || path0;
        cpath = cpath || 'M0,0Z';

        zb.attr('d', path1);
        corners.attr('d', cpath);
        dragBox.transitionZoombox(zb, corners, dimmed, lum);
        dimmed = true;
    }

    function zoomMove(dx, dy) {
        var x1 = x0 + dx;
        var y1 = y0 + dy;
        var rr0 = xy2r(x0, y0);
        var rr1 = Math.min(xy2r(x1, y1), radius);
        var a0 = xy2a(x0, y0);
        var path1;
        var cpath;

        if(clampAndSetR0R1(rr0, rr1)) {
            path1 = path0 + _this.pathSector(r1);
            if(r0) path1 += _this.pathSector(r0);
            // keep 'starting' angle
            cpath = pathCorner(r0, a0) + pathCorner(r1, a0);
        }
        applyZoomMove(path1, cpath);
    }

    function findPolygonRadius(x, y, va0, va1) {
        var xy = helpers.findIntersectionXY(va0, va1, va0, [x - cxx, cyy - y]);
        return norm(xy[0], xy[1]);
    }

    function zoomMoveForPolygons(dx, dy) {
        var x1 = x0 + dx;
        var y1 = y0 + dy;
        var a0 = xy2a(x0, y0);
        var a1 = xy2a(x1, y1);
        var vangles0 = findEnclosingVertexAngles(a0, vangles);
        var vangles1 = findEnclosingVertexAngles(a1, vangles);
        var rr0 = findPolygonRadius(x0, y0, vangles0[0], vangles0[1]);
        var rr1 = Math.min(findPolygonRadius(x1, y1, vangles1[0], vangles1[1]), radius);
        var path1;
        var cpath;

        if(clampAndSetR0R1(rr0, rr1)) {
            path1 = path0 + _this.pathSector(r1);
            if(r0) path1 += _this.pathSector(r0);
            // keep 'starting' angle here too
            cpath = [
                pathCornerForPolygons(r0, vangles0[0], vangles0[1]),
                pathCornerForPolygons(r1, vangles0[0], vangles0[1])
            ].join(' ');
        }
        applyZoomMove(path1, cpath);
    }

    function zoomDone() {
        dragBox.removeZoombox(gd);

        if(r0 === null || r1 === null) return;

        dragBox.showDoubleClickNotifier(gd);

        var rl = radialAxis._rl;
        var m = (rl[1] - rl[0]) / (1 - innerRadius / radius) / radius;
        var newRng = [
            rl[0] + (r0 - innerRadius) * m,
            rl[0] + (r1 - innerRadius) * m
        ];
        Registry.call('_guiRelayout', gd, _this.id + '.radialaxis.range', newRng);
    }

    function zoomClick(numClicks, evt) {
        var clickMode = gd._fullLayout.clickmode;

        dragBox.removeZoombox(gd);

        // TODO double once vs twice logic (autorange vs fixed range)
        if(numClicks === 2) {
            var updateObj = {};
            for(var k in _this.viewInitial) {
                updateObj[_this.id + '.' + k] = _this.viewInitial[k];
            }

            gd.emit('plotly_doubleclick', null);
            Registry.call('_guiRelayout', gd, updateObj);
        }

        if(clickMode.indexOf('select') > -1 && numClicks === 1) {
            selectOnClick(evt, gd, [_this.xaxis], [_this.yaxis], _this.id, dragOpts);
        }

        if(clickMode.indexOf('event') > -1) {
            Fx.click(gd, evt, _this.id);
        }
    }

    dragOpts.prepFn = function(evt, startX, startY) {
        var dragModeNow = gd._fullLayout.dragmode;

        var bbox = mainDrag.getBoundingClientRect();
        x0 = startX - bbox.left;
        y0 = startY - bbox.top;

        // need to offset x/y as bbox center does not
        // match origin for asymmetric polygons
        if(vangles) {
            var offset = helpers.findPolygonOffset(radius, sectorInRad[0], sectorInRad[1], vangles);
            x0 += cxx + offset[0];
            y0 += cyy + offset[1];
        }

        switch(dragModeNow) {
            case 'zoom':
                if(vangles) {
                    dragOpts.moveFn = zoomMoveForPolygons;
                } else {
                    dragOpts.moveFn = zoomMove;
                }
                dragOpts.clickFn = zoomClick;
                dragOpts.doneFn = zoomDone;
                zoomPrep(evt, startX, startY);
                break;
            case 'select':
            case 'lasso':
                prepSelect(evt, startX, startY, dragOpts, dragModeNow);
                break;
        }
    };

    mainDrag.onmousemove = function(evt) {
        Fx.hover(gd, evt, _this.id);
        gd._fullLayout._lasthover = mainDrag;
        gd._fullLayout._hoversubplot = _this.id;
    };

    mainDrag.onmouseout = function(evt) {
        if(gd._dragging) return;
        dragElement.unhover(gd, evt);
    };

    dragElement.init(dragOpts);
};

proto.updateRadialDrag = function(fullLayout, polarLayout, rngIndex) {
    var _this = this;
    var gd = _this.gd;
    var layers = _this.layers;
    var radius = _this.radius;
    var innerRadius = _this.innerRadius;
    var cx = _this.cx;
    var cy = _this.cy;
    var radialAxis = _this.radialAxis;
    var bl = constants.radialDragBoxSize;
    var bl2 = bl / 2;

    if(!radialAxis.visible) return;

    var angle0 = deg2rad(_this.radialAxisAngle);
    var rl = radialAxis._rl;
    var rl0 = rl[0];
    var rl1 = rl[1];
    var rbase = rl[rngIndex];
    var m = 0.75 * (rl[1] - rl[0]) / (1 - polarLayout.hole) / radius;

    var tx, ty, className;
    if(rngIndex) {
        tx = cx + (radius + bl2) * Math.cos(angle0);
        ty = cy - (radius + bl2) * Math.sin(angle0);
        className = 'radialdrag';
    } else {
        // the 'inner' box can get called:
        // - when polar.hole>0
        // - when polar.sector isn't a full circle
        // otherwise it is hidden behind the main drag.
        tx = cx + (innerRadius - bl2) * Math.cos(angle0);
        ty = cy - (innerRadius - bl2) * Math.sin(angle0);
        className = 'radialdrag-inner';
    }

    var radialDrag = dragBox.makeRectDragger(layers, className, 'crosshair', -bl2, -bl2, bl, bl);
    var dragOpts = {element: radialDrag, gd: gd};

    updateElement(d3.select(radialDrag), radialAxis.visible && innerRadius < radius, {
        transform: strTranslate(tx, ty)
    });

    // move function (either rotate or re-range flavor)
    var moveFn2;
    // rotate angle on done
    var angle1;
    // re-range range[1] (or range[0]) on done
    var rprime;

    function moveFn(dx, dy) {
        if(moveFn2) {
            moveFn2(dx, dy);
        } else {
            var dvec = [dx, -dy];
            var rvec = [Math.cos(angle0), Math.sin(angle0)];
            var comp = Math.abs(Lib.dot(dvec, rvec) / Math.sqrt(Lib.dot(dvec, dvec)));

            // mostly perpendicular motions rotate,
            // mostly parallel motions re-range
            if(!isNaN(comp)) {
                moveFn2 = comp < 0.5 ? rotateMove : rerangeMove;
            }
        }
    }

    function doneFn() {
        if(angle1 !== null) {
            Registry.call('_guiRelayout', gd, _this.id + '.radialaxis.angle', angle1);
        } else if(rprime !== null) {
            Registry.call('_guiRelayout', gd, _this.id + '.radialaxis.range[' + rngIndex + ']', rprime);
        }
    }

    function rotateMove(dx, dy) {
        // disable for inner drag boxes
        if(rngIndex === 0) return;

        var x1 = tx + dx;
        var y1 = ty + dy;

        angle1 = Math.atan2(cy - y1, x1 - cx);
        if(_this.vangles) angle1 = snapToVertexAngle(angle1, _this.vangles);
        angle1 = rad2deg(angle1);

        var transform = strTranslate(cx, cy) + strRotate(-angle1);
        layers['radial-axis'].attr('transform', transform);
        layers['radial-line'].select('line').attr('transform', transform);

        var fullLayoutNow = _this.gd._fullLayout;
        var polarLayoutNow = fullLayoutNow[_this.id];
        _this.updateRadialAxisTitle(fullLayoutNow, polarLayoutNow, angle1);
    }

    function rerangeMove(dx, dy) {
        // project (dx, dy) unto unit radial axis vector
        var dr = Lib.dot([dx, -dy], [Math.cos(angle0), Math.sin(angle0)]);
        rprime = rbase - m * dr;

        // make sure rprime does not change the range[0] -> range[1] sign
        if((m > 0) !== (rngIndex ? rprime > rl0 : rprime < rl1)) {
            rprime = null;
            return;
        }

        var fullLayoutNow = gd._fullLayout;
        var polarLayoutNow = fullLayoutNow[_this.id];

        // update radial range -> update c2g -> update _m,_b
        radialAxis.range[rngIndex] = rprime;
        radialAxis._rl[rngIndex] = rprime;
        _this.updateRadialAxis(fullLayoutNow, polarLayoutNow);

        _this.xaxis.setRange();
        _this.xaxis.setScale();
        _this.yaxis.setRange();
        _this.yaxis.setScale();

        var hasRegl = false;

        for(var traceType in _this.traceHash) {
            var moduleCalcData = _this.traceHash[traceType];
            var moduleCalcDataVisible = Lib.filterVisible(moduleCalcData);
            var _module = moduleCalcData[0][0].trace._module;
            _module.plot(gd, _this, moduleCalcDataVisible, polarLayoutNow);
            if(Registry.traceIs(traceType, 'gl') && moduleCalcDataVisible.length) hasRegl = true;
        }

        if(hasRegl) {
            clearGlCanvases(gd);
            redrawReglTraces(gd);
        }
    }

    dragOpts.prepFn = function() {
        moveFn2 = null;
        angle1 = null;
        rprime = null;

        dragOpts.moveFn = moveFn;
        dragOpts.doneFn = doneFn;

        clearSelect(fullLayout._zoomlayer);
    };

    dragOpts.clampFn = function(dx, dy) {
        if(Math.sqrt(dx * dx + dy * dy) < constants.MINDRAG) {
            dx = 0;
            dy = 0;
        }
        return [dx, dy];
    };

    dragElement.init(dragOpts);
};

proto.updateAngularDrag = function(fullLayout) {
    var _this = this;
    var gd = _this.gd;
    var layers = _this.layers;
    var radius = _this.radius;
    var angularAxis = _this.angularAxis;
    var cx = _this.cx;
    var cy = _this.cy;
    var cxx = _this.cxx;
    var cyy = _this.cyy;
    var dbs = constants.angularDragBoxSize;

    var angularDrag = dragBox.makeDragger(layers, 'path', 'angulardrag', 'move');
    var dragOpts = {element: angularDrag, gd: gd};

    d3.select(angularDrag)
        .attr('d', _this.pathAnnulus(radius, radius + dbs))
        .attr('transform', strTranslate(cx, cy))
        .call(setCursor, 'move');

    function xy2a(x, y) {
        return Math.atan2(cyy + dbs - y, x - cxx - dbs);
    }

    // scatter trace, points and textpoints selections
    var scatterTraces = layers.frontplot.select('.scatterlayer').selectAll('.trace');
    var scatterPoints = scatterTraces.selectAll('.point');
    var scatterTextPoints = scatterTraces.selectAll('.textpoint');

    // mouse px position at drag start (0), move (1)
    var x0, y0;
    // angular axis angle rotation at drag start (0), move (1)
    var rot0, rot1;
    // induced radial axis rotation (only used on polygon grids)
    var rrot1;
    // angle about circle center at drag start
    var a0;

    function moveFn(dx, dy) {
        var fullLayoutNow = _this.gd._fullLayout;
        var polarLayoutNow = fullLayoutNow[_this.id];

        var x1 = x0 + dx;
        var y1 = y0 + dy;
        var a1 = xy2a(x1, y1);
        var da = rad2deg(a1 - a0);
        rot1 = rot0 + da;

        layers.frontplot.attr('transform',
            strTranslate(_this.xOffset2, _this.yOffset2) + strRotate([-da, cxx, cyy])
        );

        if(_this.vangles) {
            rrot1 = _this.radialAxisAngle + da;

            var trans = strTranslate(cx, cy) + strRotate(-da);
            var trans2 = strTranslate(cx, cy) + strRotate(-rrot1);

            layers.bg.attr('transform', trans);
            layers['radial-grid'].attr('transform', trans);
            layers['radial-axis'].attr('transform', trans2);
            layers['radial-line'].select('line').attr('transform', trans2);
            _this.updateRadialAxisTitle(fullLayoutNow, polarLayoutNow, rrot1);
        } else {
            _this.clipPaths.forTraces.select('path').attr('transform',
                strTranslate(cxx, cyy) + strRotate(da)
            );
        }

        // 'un-rotate' marker and text points
        scatterPoints.each(function() {
            var sel = d3.select(this);
            var xy = Drawing.getTranslate(sel);
            sel.attr('transform', strTranslate(xy.x, xy.y) + strRotate([da]));
        });
        scatterTextPoints.each(function() {
            var sel = d3.select(this);
            var tx = sel.select('text');
            var xy = Drawing.getTranslate(sel);
            // N.B rotate -> translate ordering matters
            sel.attr('transform', strRotate([da, tx.attr('x'), tx.attr('y')]) + strTranslate(xy.x, xy.y));
        });

        // update rotation -> range -> _m,_b
        angularAxis.rotation = Lib.modHalf(rot1, 360);
        _this.updateAngularAxis(fullLayoutNow, polarLayoutNow);

        if(_this._hasClipOnAxisFalse && !Lib.isFullCircle(_this.sectorInRad)) {
            scatterTraces.call(Drawing.hideOutsideRangePoints, _this);
        }

        var hasRegl = false;

        for(var traceType in _this.traceHash) {
            if(Registry.traceIs(traceType, 'gl')) {
                var moduleCalcData = _this.traceHash[traceType];
                var moduleCalcDataVisible = Lib.filterVisible(moduleCalcData);
                var _module = moduleCalcData[0][0].trace._module;
                _module.plot(gd, _this, moduleCalcDataVisible, polarLayoutNow);
                if(moduleCalcDataVisible.length) hasRegl = true;
            }
        }

        if(hasRegl) {
            clearGlCanvases(gd);
            redrawReglTraces(gd);
        }
    }

    function doneFn() {
        scatterTextPoints.select('text').attr('transform', null);

        var updateObj = {};
        updateObj[_this.id + '.angularaxis.rotation'] = rot1;

        if(_this.vangles) {
            updateObj[_this.id + '.radialaxis.angle'] = rrot1;
        }

        Registry.call('_guiRelayout', gd, updateObj);
    }

    dragOpts.prepFn = function(evt, startX, startY) {
        var polarLayoutNow = fullLayout[_this.id];
        rot0 = polarLayoutNow.angularaxis.rotation;

        var bbox = angularDrag.getBoundingClientRect();
        x0 = startX - bbox.left;
        y0 = startY - bbox.top;
        a0 = xy2a(x0, y0);

        dragOpts.moveFn = moveFn;
        dragOpts.doneFn = doneFn;

        clearSelect(fullLayout._zoomlayer);
    };

    // I don't what we should do in this case, skip we now
    if(_this.vangles && !Lib.isFullCircle(_this.sectorInRad)) {
        dragOpts.prepFn = Lib.noop;
        setCursor(d3.select(angularDrag), null);
    }

    dragElement.init(dragOpts);
};

proto.isPtInside = function(d) {
    var sectorInRad = this.sectorInRad;
    var vangles = this.vangles;
    var thetag = this.angularAxis.c2g(d.theta);
    var radialAxis = this.radialAxis;
    var r = radialAxis.c2l(d.r);
    var rl = radialAxis._rl;

    var fn = vangles ? helpers.isPtInsidePolygon : Lib.isPtInsideSector;
    return fn(r, thetag, rl, sectorInRad, vangles);
};

proto.pathArc = function(r) {
    var sectorInRad = this.sectorInRad;
    var vangles = this.vangles;
    var fn = vangles ? helpers.pathPolygon : Lib.pathArc;
    return fn(r, sectorInRad[0], sectorInRad[1], vangles);
};

proto.pathSector = function(r) {
    var sectorInRad = this.sectorInRad;
    var vangles = this.vangles;
    var fn = vangles ? helpers.pathPolygon : Lib.pathSector;
    return fn(r, sectorInRad[0], sectorInRad[1], vangles);
};

proto.pathAnnulus = function(r0, r1) {
    var sectorInRad = this.sectorInRad;
    var vangles = this.vangles;
    var fn = vangles ? helpers.pathPolygonAnnulus : Lib.pathAnnulus;
    return fn(r0, r1, sectorInRad[0], sectorInRad[1], vangles);
};

proto.pathSubplot = function() {
    var r0 = this.innerRadius;
    var r1 = this.radius;
    return r0 ? this.pathAnnulus(r0, r1) : this.pathSector(r1);
};

proto.fillViewInitialKey = function(key, val) {
    if(!(key in this.viewInitial)) {
        this.viewInitial[key] = val;
    }
};

function strTickLayout(axLayout) {
    var out = axLayout.ticks + String(axLayout.ticklen) + String(axLayout.showticklabels);
    if('side' in axLayout) out += axLayout.side;
    return out;
}

// Finds the bounding box of a given circle sector,
// inspired by https://math.stackexchange.com/q/1852703
//
// assumes:
// - sector[0] < sector[1]
// - counterclockwise rotation
function computeSectorBBox(sector) {
    var s0 = sector[0];
    var s1 = sector[1];
    var arc = s1 - s0;
    var a0 = mod(s0, 360);
    var a1 = a0 + arc;

    var ax0 = Math.cos(deg2rad(a0));
    var ay0 = Math.sin(deg2rad(a0));
    var ax1 = Math.cos(deg2rad(a1));
    var ay1 = Math.sin(deg2rad(a1));

    var x0, y0, x1, y1;

    if((a0 <= 90 && a1 >= 90) || (a0 > 90 && a1 >= 450)) {
        y1 = 1;
    } else if(ay0 <= 0 && ay1 <= 0) {
        y1 = 0;
    } else {
        y1 = Math.max(ay0, ay1);
    }

    if((a0 <= 180 && a1 >= 180) || (a0 > 180 && a1 >= 540)) {
        x0 = -1;
    } else if(ax0 >= 0 && ax1 >= 0) {
        x0 = 0;
    } else {
        x0 = Math.min(ax0, ax1);
    }

    if((a0 <= 270 && a1 >= 270) || (a0 > 270 && a1 >= 630)) {
        y0 = -1;
    } else if(ay0 >= 0 && ay1 >= 0) {
        y0 = 0;
    } else {
        y0 = Math.min(ay0, ay1);
    }

    if(a1 >= 360) {
        x1 = 1;
    } else if(ax0 <= 0 && ax1 <= 0) {
        x1 = 0;
    } else {
        x1 = Math.max(ax0, ax1);
    }

    return [x0, y0, x1, y1];
}

function snapToVertexAngle(a, vangles) {
    var fn = function(v) { return Lib.angleDist(a, v); };
    var ind = Lib.findIndexOfMin(vangles, fn);
    return vangles[ind];
}

function updateElement(sel, showAttr, attrs) {
    if(showAttr) {
        sel.attr('display', null);
        sel.attr(attrs);
    } else if(sel) {
        sel.attr('display', 'none');
    }
    return sel;
}

function strTranslate(x, y) {
    return 'translate(' + x + ',' + y + ')';
}

function strRotate(angle) {
    return 'rotate(' + angle + ')';
}

},{"../../components/color":574,"../../components/dragelement":592,"../../components/drawing":595,"../../components/fx":613,"../../components/titles":662,"../../constants/alignment":669,"../../lib":697,"../../lib/clear_gl_canvases":682,"../../lib/setcursor":717,"../../plot_api/subroutines":736,"../../plots/cartesian/axes":745,"../../registry":826,"../cartesian/autorange":744,"../cartesian/dragbox":753,"../cartesian/select":762,"../cartesian/set_convert":763,"../plots":807,"./constants":808,"./helpers":809,"./set_convert":820,"d3":151,"tinycolor2":518}],820:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var setConvertCartesian = _dereq_('../cartesian/set_convert');

var deg2rad = Lib.deg2rad;
var rad2deg = Lib.rad2deg;

/**
 * setConvert for polar axes!
 *
 * @param {object} ax
 *   axis in question (works for both radial and angular axes)
 * @param {object} polarLayout
 *   full polar layout of the subplot associated with 'ax'
 * @param {object} fullLayout
 *   full layout
 *
 * Here, reuse some of the Cartesian setConvert logic,
 * but we must extend some of it, as both radial and angular axes
 * don't have domains and angular axes don't have _true_ ranges.
 *
 * Moreover, we introduce two new coordinate systems:
 * - 'g' for geometric coordinates and
 * - 't' for angular ticks
 *
 * Radial axis coordinate systems:
 * - d, c and l: same as for cartesian axes
 * - g: like calcdata but translated about `radialaxis.range[0]` & `polar.hole`
 *
 * Angular axis coordinate systems:
 * - d: data, in whatever form it's provided
 * - c: calcdata, turned into radians (for linear axes)
 *      or category indices (category axes)
 * - t: tick calcdata, just like 'c' but in degrees for linear axes
 * - g: geometric calcdata, radians coordinates that take into account
 *      axis rotation and direction
 *
 * Then, 'g'eometric data is ready to be converted to (x,y).
 */
module.exports = function setConvert(ax, polarLayout, fullLayout) {
    setConvertCartesian(ax, fullLayout);

    switch(ax._id) {
        case 'x':
        case 'radialaxis':
            setConvertRadial(ax, polarLayout);
            break;
        case 'angularaxis':
            setConvertAngular(ax, polarLayout);
            break;
    }
};

function setConvertRadial(ax, polarLayout) {
    var subplot = polarLayout._subplot;

    ax.setGeometry = function() {
        var rl0 = ax._rl[0];
        var rl1 = ax._rl[1];

        var b = subplot.innerRadius;
        var m = (subplot.radius - b) / (rl1 - rl0);
        var b2 = b / m;

        var rFilter = rl0 > rl1 ?
            function(v) { return v <= 0; } :
            function(v) { return v >= 0; };

        ax.c2g = function(v) {
            var r = ax.c2l(v) - rl0;
            return (rFilter(r) ? r : 0) + b2;
        };

        ax.g2c = function(v) {
            return ax.l2c(v + rl0 - b2);
        };

        ax.g2p = function(v) { return v * m; };
        ax.c2p = function(v) { return ax.g2p(ax.c2g(v)); };
    };
}

function toRadians(v, unit) {
    return unit === 'degrees' ? deg2rad(v) : v;
}

function fromRadians(v, unit) {
    return unit === 'degrees' ? rad2deg(v) : v;
}

function setConvertAngular(ax, polarLayout) {
    var axType = ax.type;

    if(axType === 'linear') {
        var _d2c = ax.d2c;
        var _c2d = ax.c2d;

        ax.d2c = function(v, unit) { return toRadians(_d2c(v), unit); };
        ax.c2d = function(v, unit) { return _c2d(fromRadians(v, unit)); };
    }

    // override makeCalcdata to handle thetaunit and special theta0/dtheta logic
    ax.makeCalcdata = function(trace, coord) {
        var arrayIn = trace[coord];
        var len = trace._length;
        var arrayOut, i;

        var _d2c = function(v) { return ax.d2c(v, trace.thetaunit); };

        if(arrayIn) {
            if(Lib.isTypedArray(arrayIn) && axType === 'linear') {
                if(len === arrayIn.length) {
                    return arrayIn;
                } else if(arrayIn.subarray) {
                    return arrayIn.subarray(0, len);
                }
            }

            arrayOut = new Array(len);
            for(i = 0; i < len; i++) {
                arrayOut[i] = _d2c(arrayIn[i]);
            }
        } else {
            var coord0 = coord + '0';
            var dcoord = 'd' + coord;
            var v0 = (coord0 in trace) ? _d2c(trace[coord0]) : 0;
            var dv = (trace[dcoord]) ? _d2c(trace[dcoord]) : (ax.period || 2 * Math.PI) / len;

            arrayOut = new Array(len);
            for(i = 0; i < len; i++) {
                arrayOut[i] = v0 + i * dv;
            }
        }

        return arrayOut;
    };

    // N.B. we mock the axis 'range' here
    ax.setGeometry = function() {
        var sector = polarLayout.sector;
        var sectorInRad = sector.map(deg2rad);
        var dir = {clockwise: -1, counterclockwise: 1}[ax.direction];
        var rot = deg2rad(ax.rotation);

        var rad2g = function(v) { return dir * v + rot; };
        var g2rad = function(v) { return (v - rot) / dir; };

        var rad2c, c2rad;
        var rad2t, t2rad;

        switch(axType) {
            case 'linear':
                c2rad = rad2c = Lib.identity;
                t2rad = deg2rad;
                rad2t = rad2deg;

                // Set the angular range in degrees to make auto-tick computation cleaner,
                // changing rotation/direction should not affect the angular tick value.
                ax.range = Lib.isFullCircle(sectorInRad) ?
                    [sector[0], sector[0] + 360] :
                    sectorInRad.map(g2rad).map(rad2deg);
                break;

            case 'category':
                var catLen = ax._categories.length;
                var _period = ax.period ? Math.max(ax.period, catLen) : catLen;

                c2rad = t2rad = function(v) { return v * 2 * Math.PI / _period; };
                rad2c = rad2t = function(v) { return v * _period / Math.PI / 2; };

                ax.range = [0, _period];
                break;
        }

        ax.c2g = function(v) { return rad2g(c2rad(v)); };
        ax.g2c = function(v) { return rad2c(g2rad(v)); };

        ax.t2g = function(v) { return rad2g(t2rad(v)); };
        ax.g2t = function(v) { return rad2t(g2rad(v)); };
    };
}

},{"../../lib":697,"../cartesian/set_convert":763}],821:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../lib');
var Template = _dereq_('../plot_api/plot_template');
var handleDomainDefaults = _dereq_('./domain').defaults;


/**
 * Find and supply defaults to all subplots of a given type
 * This handles subplots that are contained within one container - so
 * gl3d, geo, ternary... but not 2d axes which have separate x and y axes
 * finds subplots, coerces their `domain` attributes, then calls the
 * given handleDefaults function to fill in everything else.
 *
 * layoutIn: the complete user-supplied input layout
 * layoutOut: the complete finished layout
 * fullData: the finished data array, used only to find subplots
 * opts: {
 *  type: subplot type string
 *  attributes: subplot attributes object
 *  partition: 'x' or 'y', which direction to divide domain space by default
 *      (default 'x', ie side-by-side subplots)
 *      TODO: this option is only here because 3D and geo made opposite
 *      choices in this regard previously and I didn't want to change it.
 *      Instead we should do:
 *      - something consistent
 *      - something more square (4 cuts 2x2, 5/6 cuts 2x3, etc.)
 *      - something that includes all subplot types in one arrangement,
 *        now that we can have them together!
 *  handleDefaults: function of (subplotLayoutIn, subplotLayoutOut, coerce, opts)
 *      this opts object is passed through to handleDefaults, so attach any
 *      additional items needed by this function here as well
 * }
 */
module.exports = function handleSubplotDefaults(layoutIn, layoutOut, fullData, opts) {
    var subplotType = opts.type;
    var subplotAttributes = opts.attributes;
    var handleDefaults = opts.handleDefaults;
    var partition = opts.partition || 'x';

    var ids = layoutOut._subplots[subplotType];
    var idsLength = ids.length;

    var baseId = idsLength && ids[0].replace(/\d+$/, '');

    var subplotLayoutIn, subplotLayoutOut;

    function coerce(attr, dflt) {
        return Lib.coerce(subplotLayoutIn, subplotLayoutOut, subplotAttributes, attr, dflt);
    }

    for(var i = 0; i < idsLength; i++) {
        var id = ids[i];

        // ternary traces get a layout ternary for free!
        if(layoutIn[id]) subplotLayoutIn = layoutIn[id];
        else subplotLayoutIn = layoutIn[id] = {};

        subplotLayoutOut = Template.newContainer(layoutOut, id, baseId);

        // All subplot containers get a `uirevision` inheriting from the base.
        // Currently all subplots containers have some user interaction
        // attributes, but if we ever add one that doesn't, we would need an
        // option to skip this step.
        coerce('uirevision', layoutOut.uirevision);

        var dfltDomains = {};
        dfltDomains[partition] = [i / idsLength, (i + 1) / idsLength];
        handleDomainDefaults(subplotLayoutOut, layoutOut, coerce, dfltDomains);

        opts.id = id;
        handleDefaults(subplotLayoutIn, subplotLayoutOut, coerce, opts);
    }
};

},{"../lib":697,"../plot_api/plot_template":735,"./domain":770}],822:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Ternary = _dereq_('./ternary');

var getSubplotCalcData = _dereq_('../../plots/get_data').getSubplotCalcData;
var counterRegex = _dereq_('../../lib').counterRegex;
var TERNARY = 'ternary';

exports.name = TERNARY;

var attr = exports.attr = 'subplot';

exports.idRoot = TERNARY;

exports.idRegex = exports.attrRegex = counterRegex(TERNARY);

var attributes = exports.attributes = {};
attributes[attr] = {
    valType: 'subplotid',
    
    dflt: 'ternary',
    editType: 'calc',
    
};

exports.layoutAttributes = _dereq_('./layout_attributes');

exports.supplyLayoutDefaults = _dereq_('./layout_defaults');

exports.plot = function plotTernary(gd) {
    var fullLayout = gd._fullLayout;
    var calcData = gd.calcdata;
    var ternaryIds = fullLayout._subplots[TERNARY];

    for(var i = 0; i < ternaryIds.length; i++) {
        var ternaryId = ternaryIds[i];
        var ternaryCalcData = getSubplotCalcData(calcData, TERNARY, ternaryId);
        var ternary = fullLayout[ternaryId]._subplot;

        // If ternary is not instantiated, create one!
        if(!ternary) {
            ternary = new Ternary({
                id: ternaryId,
                graphDiv: gd,
                container: fullLayout._ternarylayer.node()
            },
                fullLayout
            );

            fullLayout[ternaryId]._subplot = ternary;
        }

        ternary.plot(ternaryCalcData, fullLayout, gd._promises);
    }
};

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var oldTernaryKeys = oldFullLayout._subplots[TERNARY] || [];

    for(var i = 0; i < oldTernaryKeys.length; i++) {
        var oldTernaryKey = oldTernaryKeys[i];
        var oldTernary = oldFullLayout[oldTernaryKey]._subplot;

        if(!newFullLayout[oldTernaryKey] && !!oldTernary) {
            oldTernary.plotContainer.remove();
            oldTernary.clipDef.remove();
            oldTernary.clipDefRelative.remove();
            oldTernary.layers['a-title'].remove();
            oldTernary.layers['b-title'].remove();
            oldTernary.layers['c-title'].remove();
        }
    }
};

},{"../../lib":697,"../../plots/get_data":781,"./layout_attributes":823,"./layout_defaults":824,"./ternary":825}],823:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorAttrs = _dereq_('../../components/color/attributes');
var domainAttrs = _dereq_('../domain').attributes;
var axesAttrs = _dereq_('../cartesian/layout_attributes');

var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
var extendFlat = _dereq_('../../lib/extend').extendFlat;

var ternaryAxesAttrs = {
    title: axesAttrs.title,
    color: axesAttrs.color,
    // ticks
    tickmode: axesAttrs.tickmode,
    nticks: extendFlat({}, axesAttrs.nticks, {dflt: 6, min: 1}),
    tick0: axesAttrs.tick0,
    dtick: axesAttrs.dtick,
    tickvals: axesAttrs.tickvals,
    ticktext: axesAttrs.ticktext,
    ticks: axesAttrs.ticks,
    ticklen: axesAttrs.ticklen,
    tickwidth: axesAttrs.tickwidth,
    tickcolor: axesAttrs.tickcolor,
    showticklabels: axesAttrs.showticklabels,
    showtickprefix: axesAttrs.showtickprefix,
    tickprefix: axesAttrs.tickprefix,
    showticksuffix: axesAttrs.showticksuffix,
    ticksuffix: axesAttrs.ticksuffix,
    showexponent: axesAttrs.showexponent,
    exponentformat: axesAttrs.exponentformat,
    separatethousands: axesAttrs.separatethousands,
    tickfont: axesAttrs.tickfont,
    tickangle: axesAttrs.tickangle,
    tickformat: axesAttrs.tickformat,
    tickformatstops: axesAttrs.tickformatstops,
    hoverformat: axesAttrs.hoverformat,
    // lines and grids
    showline: extendFlat({}, axesAttrs.showline, {dflt: true}),
    linecolor: axesAttrs.linecolor,
    linewidth: axesAttrs.linewidth,
    showgrid: extendFlat({}, axesAttrs.showgrid, {dflt: true}),
    gridcolor: axesAttrs.gridcolor,
    gridwidth: axesAttrs.gridwidth,
    layer: axesAttrs.layer,
    // range
    min: {
        valType: 'number',
        dflt: 0,
        
        min: 0,
        
    },
    _deprecated: {
        title: axesAttrs._deprecated.title,
        titlefont: axesAttrs._deprecated.titlefont
    }
};

var attrs = module.exports = overrideAll({
    domain: domainAttrs({name: 'ternary'}),

    bgcolor: {
        valType: 'color',
        
        dflt: colorAttrs.background,
        
    },
    sum: {
        valType: 'number',
        
        dflt: 1,
        min: 0,
        
    },
    aaxis: ternaryAxesAttrs,
    baxis: ternaryAxesAttrs,
    caxis: ternaryAxesAttrs
}, 'plot', 'from-root');

// set uirevisions outside of `overrideAll` so we can get `editType: none`
attrs.uirevision = {
    valType: 'any',
    
    editType: 'none',
    
};

attrs.aaxis.uirevision = attrs.baxis.uirevision = attrs.caxis.uirevision = {
    valType: 'any',
    
    editType: 'none',
    
};

},{"../../components/color/attributes":573,"../../lib/extend":687,"../../plot_api/edit_types":728,"../cartesian/layout_attributes":757,"../domain":770}],824:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Color = _dereq_('../../components/color');
var Template = _dereq_('../../plot_api/plot_template');
var Lib = _dereq_('../../lib');

var handleSubplotDefaults = _dereq_('../subplot_defaults');
var handleTickLabelDefaults = _dereq_('../cartesian/tick_label_defaults');
var handleTickMarkDefaults = _dereq_('../cartesian/tick_mark_defaults');
var handleTickValueDefaults = _dereq_('../cartesian/tick_value_defaults');
var handleLineGridDefaults = _dereq_('../cartesian/line_grid_defaults');
var layoutAttributes = _dereq_('./layout_attributes');

var axesNames = ['aaxis', 'baxis', 'caxis'];

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
    handleSubplotDefaults(layoutIn, layoutOut, fullData, {
        type: 'ternary',
        attributes: layoutAttributes,
        handleDefaults: handleTernaryDefaults,
        font: layoutOut.font,
        paper_bgcolor: layoutOut.paper_bgcolor
    });
};

function handleTernaryDefaults(ternaryLayoutIn, ternaryLayoutOut, coerce, options) {
    var bgColor = coerce('bgcolor');
    var sum = coerce('sum');
    options.bgColor = Color.combine(bgColor, options.paper_bgcolor);
    var axName, containerIn, containerOut;

    // TODO: allow most (if not all) axis attributes to be set
    // in the outer container and used as defaults in the individual axes?

    for(var j = 0; j < axesNames.length; j++) {
        axName = axesNames[j];
        containerIn = ternaryLayoutIn[axName] || {};
        containerOut = Template.newContainer(ternaryLayoutOut, axName);
        containerOut._name = axName;

        handleAxisDefaults(containerIn, containerOut, options, ternaryLayoutOut);
    }

    // if the min values contradict each other, set them all to default (0)
    // and delete *all* the inputs so the user doesn't get confused later by
    // changing one and having them all change.
    var aaxis = ternaryLayoutOut.aaxis;
    var baxis = ternaryLayoutOut.baxis;
    var caxis = ternaryLayoutOut.caxis;
    if(aaxis.min + baxis.min + caxis.min >= sum) {
        aaxis.min = 0;
        baxis.min = 0;
        caxis.min = 0;
        if(ternaryLayoutIn.aaxis) delete ternaryLayoutIn.aaxis.min;
        if(ternaryLayoutIn.baxis) delete ternaryLayoutIn.baxis.min;
        if(ternaryLayoutIn.caxis) delete ternaryLayoutIn.caxis.min;
    }
}

function handleAxisDefaults(containerIn, containerOut, options, ternaryLayoutOut) {
    var axAttrs = layoutAttributes[containerOut._name];

    function coerce(attr, dflt) {
        return Lib.coerce(containerIn, containerOut, axAttrs, attr, dflt);
    }

    coerce('uirevision', ternaryLayoutOut.uirevision);

    containerOut.type = 'linear'; // no other types allowed for ternary

    var dfltColor = coerce('color');
    // if axis.color was provided, use it for fonts too; otherwise,
    // inherit from global font color in case that was provided.
    var dfltFontColor = (dfltColor !== axAttrs.color.dflt) ? dfltColor : options.font.color;

    var axName = containerOut._name;
    var letterUpper = axName.charAt(0).toUpperCase();
    var dfltTitle = 'Component ' + letterUpper;

    var title = coerce('title.text', dfltTitle);
    containerOut._hovertitle = title === dfltTitle ? title : letterUpper;

    Lib.coerceFont(coerce, 'title.font', {
        family: options.font.family,
        size: Math.round(options.font.size * 1.2),
        color: dfltFontColor
    });

    // range is just set by 'min' - max is determined by the other axes mins
    coerce('min');

    handleTickValueDefaults(containerIn, containerOut, coerce, 'linear');
    handleTickLabelDefaults(containerIn, containerOut, coerce, 'linear', {});
    handleTickMarkDefaults(containerIn, containerOut, coerce,
        { outerTicks: true });

    var showTickLabels = coerce('showticklabels');
    if(showTickLabels) {
        Lib.coerceFont(coerce, 'tickfont', {
            family: options.font.family,
            size: options.font.size,
            color: dfltFontColor
        });
        coerce('tickangle');
        coerce('tickformat');
    }

    handleLineGridDefaults(containerIn, containerOut, coerce, {
        dfltColor: dfltColor,
        bgColor: options.bgColor,
        // default grid color is darker here (60%, vs cartesian default ~91%)
        // because the grid is not square so the eye needs heavier cues to follow
        blend: 60,
        showLine: true,
        showGrid: true,
        noZeroLine: true,
        attributes: axAttrs
    });

    coerce('hoverformat');
    coerce('layer');
}

},{"../../components/color":574,"../../lib":697,"../../plot_api/plot_template":735,"../cartesian/line_grid_defaults":759,"../cartesian/tick_label_defaults":764,"../cartesian/tick_mark_defaults":765,"../cartesian/tick_value_defaults":766,"../subplot_defaults":821,"./layout_attributes":823}],825:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var tinycolor = _dereq_('tinycolor2');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var _ = Lib._;
var Color = _dereq_('../../components/color');
var Drawing = _dereq_('../../components/drawing');
var setConvert = _dereq_('../cartesian/set_convert');
var extendFlat = _dereq_('../../lib/extend').extendFlat;
var Plots = _dereq_('../plots');
var Axes = _dereq_('../cartesian/axes');
var dragElement = _dereq_('../../components/dragelement');
var Fx = _dereq_('../../components/fx');
var Titles = _dereq_('../../components/titles');
var prepSelect = _dereq_('../cartesian/select').prepSelect;
var selectOnClick = _dereq_('../cartesian/select').selectOnClick;
var clearSelect = _dereq_('../cartesian/select').clearSelect;
var constants = _dereq_('../cartesian/constants');

function Ternary(options, fullLayout) {
    this.id = options.id;
    this.graphDiv = options.graphDiv;
    this.init(fullLayout);
    this.makeFramework(fullLayout);

    // unfortunately, we have to keep track of some axis tick settings
    // as ternary subplots do not implement the 'ticks' editType
    this.aTickLayout = null;
    this.bTickLayout = null;
    this.cTickLayout = null;
}

module.exports = Ternary;

var proto = Ternary.prototype;

proto.init = function(fullLayout) {
    this.container = fullLayout._ternarylayer;
    this.defs = fullLayout._defs;
    this.layoutId = fullLayout._uid;
    this.traceHash = {};
    this.layers = {};
};

proto.plot = function(ternaryCalcData, fullLayout) {
    var _this = this;
    var ternaryLayout = fullLayout[_this.id];
    var graphSize = fullLayout._size;

    _this._hasClipOnAxisFalse = false;
    for(var i = 0; i < ternaryCalcData.length; i++) {
        var trace = ternaryCalcData[i][0].trace;

        if(trace.cliponaxis === false) {
            _this._hasClipOnAxisFalse = true;
            break;
        }
    }

    _this.updateLayers(ternaryLayout);
    _this.adjustLayout(ternaryLayout, graphSize);
    Plots.generalUpdatePerTraceModule(_this.graphDiv, _this, ternaryCalcData, ternaryLayout);
    _this.layers.plotbg.select('path').call(Color.fill, ternaryLayout.bgcolor);
};

proto.makeFramework = function(fullLayout) {
    var _this = this;
    var gd = _this.graphDiv;
    var ternaryLayout = fullLayout[_this.id];

    var clipId = _this.clipId = 'clip' + _this.layoutId + _this.id;
    var clipIdRelative = _this.clipIdRelative = 'clip-relative' + _this.layoutId + _this.id;

    // clippath for this ternary subplot
    _this.clipDef = Lib.ensureSingleById(fullLayout._clips, 'clipPath', clipId, function(s) {
        s.append('path').attr('d', 'M0,0Z');
    });

    // 'relative' clippath (i.e. no translation) for this ternary subplot
    _this.clipDefRelative = Lib.ensureSingleById(fullLayout._clips, 'clipPath', clipIdRelative, function(s) {
        s.append('path').attr('d', 'M0,0Z');
    });

    // container for everything in this ternary subplot
    _this.plotContainer = Lib.ensureSingle(_this.container, 'g', _this.id);
    _this.updateLayers(ternaryLayout);

    Drawing.setClipUrl(_this.layers.backplot, clipId, gd);
    Drawing.setClipUrl(_this.layers.grids, clipId, gd);
};

proto.updateLayers = function(ternaryLayout) {
    var _this = this;
    var layers = _this.layers;

    // inside that container, we have one container for the data, and
    // one each for the three axes around it.

    var plotLayers = ['draglayer', 'plotbg', 'backplot', 'grids'];

    if(ternaryLayout.aaxis.layer === 'below traces') {
        plotLayers.push('aaxis', 'aline');
    }
    if(ternaryLayout.baxis.layer === 'below traces') {
        plotLayers.push('baxis', 'bline');
    }
    if(ternaryLayout.caxis.layer === 'below traces') {
        plotLayers.push('caxis', 'cline');
    }

    plotLayers.push('frontplot');

    if(ternaryLayout.aaxis.layer === 'above traces') {
        plotLayers.push('aaxis', 'aline');
    }
    if(ternaryLayout.baxis.layer === 'above traces') {
        plotLayers.push('baxis', 'bline');
    }
    if(ternaryLayout.caxis.layer === 'above traces') {
        plotLayers.push('caxis', 'cline');
    }

    var toplevel = _this.plotContainer.selectAll('g.toplevel')
        .data(plotLayers, String);

    var grids = ['agrid', 'bgrid', 'cgrid'];

    toplevel.enter().append('g')
        .attr('class', function(d) { return 'toplevel ' + d; })
        .each(function(d) {
            var s = d3.select(this);
            layers[d] = s;

            // containers for different trace types.
            // NOTE - this is different from cartesian, where all traces
            // are in front of grids. Here I'm putting maps behind the grids
            // so the grids will always be visible if they're requested.
            // Perhaps we want that for cartesian too?
            if(d === 'frontplot') {
                s.append('g').classed('scatterlayer', true);
            } else if(d === 'backplot') {
                s.append('g').classed('maplayer', true);
            } else if(d === 'plotbg') {
                s.append('path').attr('d', 'M0,0Z');
            } else if(d === 'aline' || d === 'bline' || d === 'cline') {
                s.append('path');
            } else if(d === 'grids') {
                grids.forEach(function(d) {
                    layers[d] = s.append('g').classed('grid ' + d, true);
                });
            }
        });

    toplevel.order();
};

var whRatio = Math.sqrt(4 / 3);

proto.adjustLayout = function(ternaryLayout, graphSize) {
    var _this = this;
    var domain = ternaryLayout.domain;
    var xDomainCenter = (domain.x[0] + domain.x[1]) / 2;
    var yDomainCenter = (domain.y[0] + domain.y[1]) / 2;
    var xDomain = domain.x[1] - domain.x[0];
    var yDomain = domain.y[1] - domain.y[0];
    var wmax = xDomain * graphSize.w;
    var hmax = yDomain * graphSize.h;
    var sum = ternaryLayout.sum;
    var amin = ternaryLayout.aaxis.min;
    var bmin = ternaryLayout.baxis.min;
    var cmin = ternaryLayout.caxis.min;

    var x0, y0, w, h, xDomainFinal, yDomainFinal;

    if(wmax > whRatio * hmax) {
        h = hmax;
        w = h * whRatio;
    }
    else {
        w = wmax;
        h = w / whRatio;
    }

    xDomainFinal = xDomain * w / wmax;
    yDomainFinal = yDomain * h / hmax;

    x0 = graphSize.l + graphSize.w * xDomainCenter - w / 2;
    y0 = graphSize.t + graphSize.h * (1 - yDomainCenter) - h / 2;

    _this.x0 = x0;
    _this.y0 = y0;
    _this.w = w;
    _this.h = h;
    _this.sum = sum;

    // set up the x and y axis objects we'll use to lay out the points
    _this.xaxis = {
        type: 'linear',
        range: [amin + 2 * cmin - sum, sum - amin - 2 * bmin],
        domain: [
            xDomainCenter - xDomainFinal / 2,
            xDomainCenter + xDomainFinal / 2
        ],
        _id: 'x'
    };
    setConvert(_this.xaxis, _this.graphDiv._fullLayout);
    _this.xaxis.setScale();
    _this.xaxis.isPtWithinRange = function(d) {
        return (
            d.a >= _this.aaxis.range[0] &&
            d.a <= _this.aaxis.range[1] &&
            d.b >= _this.baxis.range[1] &&
            d.b <= _this.baxis.range[0] &&
            d.c >= _this.caxis.range[1] &&
            d.c <= _this.caxis.range[0]
        );
    };

    _this.yaxis = {
        type: 'linear',
        range: [amin, sum - bmin - cmin],
        domain: [
            yDomainCenter - yDomainFinal / 2,
            yDomainCenter + yDomainFinal / 2
        ],
        _id: 'y'
    };
    setConvert(_this.yaxis, _this.graphDiv._fullLayout);
    _this.yaxis.setScale();
    _this.yaxis.isPtWithinRange = function() { return true; };

    // set up the modified axes for tick drawing
    var yDomain0 = _this.yaxis.domain[0];

    // aaxis goes up the left side. Set it up as a y axis, but with
    // fictitious angles and domain, but then rotate and translate
    // it into place at the end
    var aaxis = _this.aaxis = extendFlat({}, ternaryLayout.aaxis, {
        range: [amin, sum - bmin - cmin],
        side: 'left',
        // tickangle = 'auto' means 0 anyway for a y axis, need to coerce to 0 here
        // so we can shift by 30.
        tickangle: (+ternaryLayout.aaxis.tickangle || 0) - 30,
        domain: [yDomain0, yDomain0 + yDomainFinal * whRatio],
        anchor: 'free',
        position: 0,
        _id: 'y',
        _length: w
    });
    setConvert(aaxis, _this.graphDiv._fullLayout);
    aaxis.setScale();

    // baxis goes across the bottom (backward). We can set it up as an x axis
    // without any enclosing transformation.
    var baxis = _this.baxis = extendFlat({}, ternaryLayout.baxis, {
        range: [sum - amin - cmin, bmin],
        side: 'bottom',
        domain: _this.xaxis.domain,
        anchor: 'free',
        position: 0,
        _id: 'x',
        _length: w
    });
    setConvert(baxis, _this.graphDiv._fullLayout);
    baxis.setScale();

    // caxis goes down the right side. Set it up as a y axis, with
    // post-transformation similar to aaxis
    var caxis = _this.caxis = extendFlat({}, ternaryLayout.caxis, {
        range: [sum - amin - bmin, cmin],
        side: 'right',
        tickangle: (+ternaryLayout.caxis.tickangle || 0) + 30,
        domain: [yDomain0, yDomain0 + yDomainFinal * whRatio],
        anchor: 'free',
        position: 0,
        _id: 'y',
        _length: w
    });
    setConvert(caxis, _this.graphDiv._fullLayout);
    caxis.setScale();

    var triangleClip = 'M' + x0 + ',' + (y0 + h) + 'h' + w + 'l-' + (w / 2) + ',-' + h + 'Z';
    _this.clipDef.select('path').attr('d', triangleClip);
    _this.layers.plotbg.select('path').attr('d', triangleClip);

    var triangleClipRelative = 'M0,' + h + 'h' + w + 'l-' + (w / 2) + ',-' + h + 'Z';
    _this.clipDefRelative.select('path').attr('d', triangleClipRelative);

    var plotTransform = 'translate(' + x0 + ',' + y0 + ')';
    _this.plotContainer.selectAll('.scatterlayer,.maplayer')
        .attr('transform', plotTransform);

    _this.clipDefRelative.select('path').attr('transform', null);

    // TODO: shift axes to accommodate linewidth*sin(30) tick mark angle

    // TODO: there's probably an easier way to handle these translations/offsets now...
    var bTransform = 'translate(' + (x0 - baxis._offset) + ',' + (y0 + h) + ')';

    _this.layers.baxis.attr('transform', bTransform);
    _this.layers.bgrid.attr('transform', bTransform);

    var aTransform = 'translate(' + (x0 + w / 2) + ',' + y0 +
        ')rotate(30)translate(0,' + -aaxis._offset + ')';
    _this.layers.aaxis.attr('transform', aTransform);
    _this.layers.agrid.attr('transform', aTransform);

    var cTransform = 'translate(' + (x0 + w / 2) + ',' + y0 +
        ')rotate(-30)translate(0,' + -caxis._offset + ')';
    _this.layers.caxis.attr('transform', cTransform);
    _this.layers.cgrid.attr('transform', cTransform);

    _this.drawAxes(true);

    _this.layers.aline.select('path')
        .attr('d', aaxis.showline ?
            'M' + x0 + ',' + (y0 + h) + 'l' + (w / 2) + ',-' + h : 'M0,0')
        .call(Color.stroke, aaxis.linecolor || '#000')
        .style('stroke-width', (aaxis.linewidth || 0) + 'px');
    _this.layers.bline.select('path')
        .attr('d', baxis.showline ?
            'M' + x0 + ',' + (y0 + h) + 'h' + w : 'M0,0')
        .call(Color.stroke, baxis.linecolor || '#000')
        .style('stroke-width', (baxis.linewidth || 0) + 'px');
    _this.layers.cline.select('path')
        .attr('d', caxis.showline ?
            'M' + (x0 + w / 2) + ',' + y0 + 'l' + (w / 2) + ',' + h : 'M0,0')
        .call(Color.stroke, caxis.linecolor || '#000')
        .style('stroke-width', (caxis.linewidth || 0) + 'px');

    if(!_this.graphDiv._context.staticPlot) {
        _this.initInteractions();
    }

    Drawing.setClipUrl(
        _this.layers.frontplot,
        _this._hasClipOnAxisFalse ? null : _this.clipId,
        _this.graphDiv
    );
};

proto.drawAxes = function(doTitles) {
    var _this = this;
    var gd = _this.graphDiv;
    var titlesuffix = _this.id.substr(7) + 'title';
    var layers = _this.layers;
    var aaxis = _this.aaxis;
    var baxis = _this.baxis;
    var caxis = _this.caxis;

    _this.drawAx(aaxis);
    _this.drawAx(baxis);
    _this.drawAx(caxis);

    if(doTitles) {
        var apad = Math.max(aaxis.showticklabels ? aaxis.tickfont.size / 2 : 0,
            (caxis.showticklabels ? caxis.tickfont.size * 0.75 : 0) +
            (caxis.ticks === 'outside' ? caxis.ticklen * 0.87 : 0));
        var bpad = (baxis.showticklabels ? baxis.tickfont.size : 0) +
            (baxis.ticks === 'outside' ? baxis.ticklen : 0) + 3;

        layers['a-title'] = Titles.draw(gd, 'a' + titlesuffix, {
            propContainer: aaxis,
            propName: _this.id + '.aaxis.title',
            placeholder: _(gd, 'Click to enter Component A title'),
            attributes: {
                x: _this.x0 + _this.w / 2,
                y: _this.y0 - aaxis.title.font.size / 3 - apad,
                'text-anchor': 'middle'
            }
        });
        layers['b-title'] = Titles.draw(gd, 'b' + titlesuffix, {
            propContainer: baxis,
            propName: _this.id + '.baxis.title',
            placeholder: _(gd, 'Click to enter Component B title'),
            attributes: {
                x: _this.x0 - bpad,
                y: _this.y0 + _this.h + baxis.title.font.size * 0.83 + bpad,
                'text-anchor': 'middle'
            }
        });
        layers['c-title'] = Titles.draw(gd, 'c' + titlesuffix, {
            propContainer: caxis,
            propName: _this.id + '.caxis.title',
            placeholder: _(gd, 'Click to enter Component C title'),
            attributes: {
                x: _this.x0 + _this.w + bpad,
                y: _this.y0 + _this.h + caxis.title.font.size * 0.83 + bpad,
                'text-anchor': 'middle'
            }
        });
    }
};

proto.drawAx = function(ax) {
    var _this = this;
    var gd = _this.graphDiv;
    var axName = ax._name;
    var axLetter = axName.charAt(0);
    var axId = ax._id;
    var axLayer = _this.layers[axName];
    var counterAngle = 30;

    var stashKey = axLetter + 'tickLayout';
    var newTickLayout = strTickLayout(ax);
    if(_this[stashKey] !== newTickLayout) {
        axLayer.selectAll('.' + axId + 'tick').remove();
        _this[stashKey] = newTickLayout;
    }

    ax.setScale();

    var vals = Axes.calcTicks(ax);
    var valsClipped = Axes.clipEnds(ax, vals);
    var transFn = Axes.makeTransFn(ax);
    var tickSign = Axes.getTickSigns(ax)[2];

    var caRad = Lib.deg2rad(counterAngle);
    var pad = tickSign * (ax.linewidth || 1) / 2;
    var len = tickSign * ax.ticklen;
    var w = _this.w;
    var h = _this.h;

    var tickPath = axLetter === 'b' ?
        'M0,' + pad + 'l' + (Math.sin(caRad) * len) + ',' + (Math.cos(caRad) * len) :
        'M' + pad + ',0l' + (Math.cos(caRad) * len) + ',' + (-Math.sin(caRad) * len);

    var gridPath = {
        a: 'M0,0l' + h + ',-' + (w / 2),
        b: 'M0,0l-' + (w / 2) + ',-' + h,
        c: 'M0,0l-' + h + ',' + (w / 2)
    }[axLetter];

    Axes.drawTicks(gd, ax, {
        vals: ax.ticks === 'inside' ? valsClipped : vals,
        layer: axLayer,
        path: tickPath,
        transFn: transFn,
        crisp: false
    });

    Axes.drawGrid(gd, ax, {
        vals: valsClipped,
        layer: _this.layers[axLetter + 'grid'],
        path: gridPath,
        transFn: transFn,
        crisp: false
    });

    Axes.drawLabels(gd, ax, {
        vals: vals,
        layer: axLayer,
        transFn: transFn,
        labelFns: Axes.makeLabelFns(ax, 0, counterAngle)
    });
};

function strTickLayout(axLayout) {
    return axLayout.ticks + String(axLayout.ticklen) + String(axLayout.showticklabels);
}

// hard coded paths for zoom corners
// uses the same sizing as cartesian, length is MINZOOM/2, width is 3px
var CLEN = constants.MINZOOM / 2 + 0.87;
var BLPATH = 'm-0.87,.5h' + CLEN + 'v3h-' + (CLEN + 5.2) +
    'l' + (CLEN / 2 + 2.6) + ',-' + (CLEN * 0.87 + 4.5) +
    'l2.6,1.5l-' + (CLEN / 2) + ',' + (CLEN * 0.87) + 'Z';
var BRPATH = 'm0.87,.5h-' + CLEN + 'v3h' + (CLEN + 5.2) +
    'l-' + (CLEN / 2 + 2.6) + ',-' + (CLEN * 0.87 + 4.5) +
    'l-2.6,1.5l' + (CLEN / 2) + ',' + (CLEN * 0.87) + 'Z';
var TOPPATH = 'm0,1l' + (CLEN / 2) + ',' + (CLEN * 0.87) +
    'l2.6,-1.5l-' + (CLEN / 2 + 2.6) + ',-' + (CLEN * 0.87 + 4.5) +
    'l-' + (CLEN / 2 + 2.6) + ',' + (CLEN * 0.87 + 4.5) +
    'l2.6,1.5l' + (CLEN / 2) + ',-' + (CLEN * 0.87) + 'Z';
var STARTMARKER = 'm0.5,0.5h5v-2h-5v-5h-2v5h-5v2h5v5h2Z';

// I guess this could be shared with cartesian... but for now it's separate.
var SHOWZOOMOUTTIP = true;

proto.initInteractions = function() {
    var _this = this;
    var dragger = _this.layers.plotbg.select('path').node();
    var gd = _this.graphDiv;
    var zoomContainer = gd._fullLayout._zoomlayer;

    // use plotbg for the main interactions
    var dragOptions = {
        element: dragger,
        gd: gd,
        plotinfo: {
            id: _this.id,
            xaxis: _this.xaxis,
            yaxis: _this.yaxis
        },
        subplot: _this.id,
        prepFn: function(e, startX, startY) {
            // these aren't available yet when initInteractions
            // is called
            dragOptions.xaxes = [_this.xaxis];
            dragOptions.yaxes = [_this.yaxis];
            var dragModeNow = gd._fullLayout.dragmode;

            if(dragModeNow === 'lasso') dragOptions.minDrag = 1;
            else dragOptions.minDrag = undefined;

            if(dragModeNow === 'zoom') {
                dragOptions.moveFn = zoomMove;
                dragOptions.clickFn = clickZoomPan;
                dragOptions.doneFn = zoomDone;
                zoomPrep(e, startX, startY);
            }
            else if(dragModeNow === 'pan') {
                dragOptions.moveFn = plotDrag;
                dragOptions.clickFn = clickZoomPan;
                dragOptions.doneFn = dragDone;
                panPrep();
                clearSelect(zoomContainer);
            }
            else if(dragModeNow === 'select' || dragModeNow === 'lasso') {
                prepSelect(e, startX, startY, dragOptions, dragModeNow);
            }
        }
    };

    var x0, y0, mins0, span0, mins, lum, path0, dimmed, zb, corners;

    function makeUpdate(_mins) {
        var attrs = {};
        attrs[_this.id + '.aaxis.min'] = _mins.a;
        attrs[_this.id + '.baxis.min'] = _mins.b;
        attrs[_this.id + '.caxis.min'] = _mins.c;
        return attrs;
    }

    function clickZoomPan(numClicks, evt) {
        var clickMode = gd._fullLayout.clickmode;

        removeZoombox(gd);

        if(numClicks === 2) {
            gd.emit('plotly_doubleclick', null);
            Registry.call('_guiRelayout', gd, makeUpdate({a: 0, b: 0, c: 0}));
        }

        if(clickMode.indexOf('select') > -1 && numClicks === 1) {
            selectOnClick(evt, gd, [_this.xaxis], [_this.yaxis], _this.id, dragOptions);
        }

        if(clickMode.indexOf('event') > -1) {
            Fx.click(gd, evt, _this.id);
        }
    }

    function zoomPrep(e, startX, startY) {
        var dragBBox = dragger.getBoundingClientRect();
        x0 = startX - dragBBox.left;
        y0 = startY - dragBBox.top;
        mins0 = {
            a: _this.aaxis.range[0],
            b: _this.baxis.range[1],
            c: _this.caxis.range[1]
        };
        mins = mins0;
        span0 = _this.aaxis.range[1] - mins0.a;
        lum = tinycolor(_this.graphDiv._fullLayout[_this.id].bgcolor).getLuminance();
        path0 = 'M0,' + _this.h + 'L' + (_this.w / 2) + ', 0L' + _this.w + ',' + _this.h + 'Z';
        dimmed = false;

        zb = zoomContainer.append('path')
            .attr('class', 'zoombox')
            .attr('transform', 'translate(' + _this.x0 + ', ' + _this.y0 + ')')
            .style({
                'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)',
                'stroke-width': 0
            })
            .attr('d', path0);

        corners = zoomContainer.append('path')
            .attr('class', 'zoombox-corners')
            .attr('transform', 'translate(' + _this.x0 + ', ' + _this.y0 + ')')
            .style({
                fill: Color.background,
                stroke: Color.defaultLine,
                'stroke-width': 1,
                opacity: 0
            })
            .attr('d', 'M0,0Z');

        clearSelect(zoomContainer);
    }

    function getAFrac(x, y) { return 1 - (y / _this.h); }
    function getBFrac(x, y) { return 1 - ((x + (_this.h - y) / Math.sqrt(3)) / _this.w); }
    function getCFrac(x, y) { return ((x - (_this.h - y) / Math.sqrt(3)) / _this.w); }

    function zoomMove(dx0, dy0) {
        var x1 = x0 + dx0;
        var y1 = y0 + dy0;
        var afrac = Math.max(0, Math.min(1, getAFrac(x0, y0), getAFrac(x1, y1)));
        var bfrac = Math.max(0, Math.min(1, getBFrac(x0, y0), getBFrac(x1, y1)));
        var cfrac = Math.max(0, Math.min(1, getCFrac(x0, y0), getCFrac(x1, y1)));
        var xLeft = ((afrac / 2) + cfrac) * _this.w;
        var xRight = (1 - (afrac / 2) - bfrac) * _this.w;
        var xCenter = (xLeft + xRight) / 2;
        var xSpan = xRight - xLeft;
        var yBottom = (1 - afrac) * _this.h;
        var yTop = yBottom - xSpan / whRatio;

        if(xSpan < constants.MINZOOM) {
            mins = mins0;
            zb.attr('d', path0);
            corners.attr('d', 'M0,0Z');
        }
        else {
            mins = {
                a: mins0.a + afrac * span0,
                b: mins0.b + bfrac * span0,
                c: mins0.c + cfrac * span0
            };
            zb.attr('d', path0 + 'M' + xLeft + ',' + yBottom +
                'H' + xRight + 'L' + xCenter + ',' + yTop +
                'L' + xLeft + ',' + yBottom + 'Z');
            corners.attr('d', 'M' + x0 + ',' + y0 + STARTMARKER +
                'M' + xLeft + ',' + yBottom + BLPATH +
                'M' + xRight + ',' + yBottom + BRPATH +
                'M' + xCenter + ',' + yTop + TOPPATH);
        }

        if(!dimmed) {
            zb.transition()
                .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' :
                    'rgba(255,255,255,0.3)')
                .duration(200);
            corners.transition()
                .style('opacity', 1)
                .duration(200);
            dimmed = true;
        }
    }

    function zoomDone() {
        removeZoombox(gd);

        if(mins === mins0) return;

        Registry.call('_guiRelayout', gd, makeUpdate(mins));

        if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) {
            Lib.notifier(_(gd, 'Double-click to zoom back out'), 'long');
            SHOWZOOMOUTTIP = false;
        }
    }

    function panPrep() {
        mins0 = {
            a: _this.aaxis.range[0],
            b: _this.baxis.range[1],
            c: _this.caxis.range[1]
        };
        mins = mins0;
    }

    function plotDrag(dx, dy) {
        var dxScaled = dx / _this.xaxis._m;
        var dyScaled = dy / _this.yaxis._m;
        mins = {
            a: mins0.a - dyScaled,
            b: mins0.b + (dxScaled + dyScaled) / 2,
            c: mins0.c - (dxScaled - dyScaled) / 2
        };
        var minsorted = [mins.a, mins.b, mins.c].sort();
        var minindices = {
            a: minsorted.indexOf(mins.a),
            b: minsorted.indexOf(mins.b),
            c: minsorted.indexOf(mins.c)
        };
        if(minsorted[0] < 0) {
            if(minsorted[1] + minsorted[0] / 2 < 0) {
                minsorted[2] += minsorted[0] + minsorted[1];
                minsorted[0] = minsorted[1] = 0;
            }
            else {
                minsorted[2] += minsorted[0] / 2;
                minsorted[1] += minsorted[0] / 2;
                minsorted[0] = 0;
            }
            mins = {
                a: minsorted[minindices.a],
                b: minsorted[minindices.b],
                c: minsorted[minindices.c]
            };
            dy = (mins0.a - mins.a) * _this.yaxis._m;
            dx = (mins0.c - mins.c - mins0.b + mins.b) * _this.xaxis._m;
        }

        // move the data (translate, don't redraw)
        var plotTransform = 'translate(' + (_this.x0 + dx) + ',' + (_this.y0 + dy) + ')';
        _this.plotContainer.selectAll('.scatterlayer,.maplayer')
            .attr('transform', plotTransform);

        var plotTransform2 = 'translate(' + -dx + ',' + -dy + ')';
        _this.clipDefRelative.select('path').attr('transform', plotTransform2);

        // move the ticks
        _this.aaxis.range = [mins.a, _this.sum - mins.b - mins.c];
        _this.baxis.range = [_this.sum - mins.a - mins.c, mins.b];
        _this.caxis.range = [_this.sum - mins.a - mins.b, mins.c];

        _this.drawAxes(false);

        if(_this._hasClipOnAxisFalse) {
            _this.plotContainer
                .select('.scatterlayer').selectAll('.trace')
                .call(Drawing.hideOutsideRangePoints, _this);
        }
    }

    function dragDone() {
        Registry.call('_guiRelayout', gd, makeUpdate(mins));
    }

    // finally, set up hover and click
    // these event handlers must already be set before dragElement.init
    // so it can stash them and override them.
    dragger.onmousemove = function(evt) {
        Fx.hover(gd, evt, _this.id);
        gd._fullLayout._lasthover = dragger;
        gd._fullLayout._hoversubplot = _this.id;
    };

    dragger.onmouseout = function(evt) {
        if(gd._dragging) return;

        dragElement.unhover(gd, evt);
    };

    dragElement.init(dragOptions);
};

function removeZoombox(gd) {
    d3.select(gd)
        .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners')
        .remove();
}

},{"../../components/color":574,"../../components/dragelement":592,"../../components/drawing":595,"../../components/fx":613,"../../components/titles":662,"../../lib":697,"../../lib/extend":687,"../../registry":826,"../cartesian/axes":745,"../cartesian/constants":751,"../cartesian/select":762,"../cartesian/set_convert":763,"../plots":807,"d3":151,"tinycolor2":518}],826:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Loggers = _dereq_('./lib/loggers');
var noop = _dereq_('./lib/noop');
var pushUnique = _dereq_('./lib/push_unique');
var isPlainObject = _dereq_('./lib/is_plain_object');
var ExtendModule = _dereq_('./lib/extend');

var basePlotAttributes = _dereq_('./plots/attributes');
var baseLayoutAttributes = _dereq_('./plots/layout_attributes');

var extendFlat = ExtendModule.extendFlat;
var extendDeepAll = ExtendModule.extendDeepAll;

exports.modules = {};
exports.allCategories = {};
exports.allTypes = [];
exports.subplotsRegistry = {};
exports.transformsRegistry = {};
exports.componentsRegistry = {};
exports.layoutArrayContainers = [];
exports.layoutArrayRegexes = [];
exports.traceLayoutAttributes = {};
exports.localeRegistry = {};
exports.apiMethodRegistry = {};
exports.collectableSubplotTypes = null;

/**
 * Top-level register routine, exported as Plotly.register
 *
 * @param {object array or array of objects} _modules :
 *  module object or list of module object to register.
 *
 *  A valid `moduleType: 'trace'` module has fields:
 *  - name {string} : the trace type
 *  - categories {array} : categories associated with this trace type,
 *                         tested with Register.traceIs()
 *  - meta {object} : meta info (mostly for plot-schema)
 *
 *  A valid `moduleType: 'locale'` module has fields:
 *  - name {string} : the locale name. Should be a 2-digit language string ('en', 'de')
 *                    optionally with a country/region code ('en-GB', 'de-CH'). If a country
 *                    code is used but the base language locale has not yet been supplied,
 *                    we will use this locale for the base as well.
 *  - dictionary {object} : the dictionary mapping input strings to localized strings
 *                          generally the keys should be the literal input strings, but
 *                          if default translations are provided you can use any string as a key.
 *  - format {object} : a `d3.locale` format specifier for this locale
 *                      any omitted keys we'll fall back on en-US.
 *
 *  A valid `moduleType: 'transform'` module has fields:
 *  - name {string} : transform name
 *  - transform {function} : default-level transform function
 *  - calcTransform {function} : calc-level transform function
 *  - attributes {object} : transform attributes declarations
 *  - supplyDefaults {function} : attributes default-supply function
 *
 *  A valid `moduleType: 'component'` module has fields:
 *  - name {string} : the component name, used it with Register.getComponentMethod()
 *                    to employ component method.
 *
 *  A valid `moduleType: 'apiMethod'` module has fields:
 *  - name {string} : the api method name.
 *  - fn {function} : the api method called with Register.call();
 *
 */
exports.register = function register(_modules) {
    exports.collectableSubplotTypes = null;

    if(!_modules) {
        throw new Error('No argument passed to Plotly.register.');
    } else if(_modules && !Array.isArray(_modules)) {
        _modules = [_modules];
    }

    for(var i = 0; i < _modules.length; i++) {
        var newModule = _modules[i];

        if(!newModule) {
            throw new Error('Invalid module was attempted to be registered!');
        }

        switch(newModule.moduleType) {
            case 'trace':
                registerTraceModule(newModule);
                break;
            case 'transform':
                registerTransformModule(newModule);
                break;
            case 'component':
                registerComponentModule(newModule);
                break;
            case 'locale':
                registerLocale(newModule);
                break;
            case 'apiMethod':
                var name = newModule.name;
                exports.apiMethodRegistry[name] = newModule.fn;
                break;
            default:
                throw new Error('Invalid module was attempted to be registered!');
        }
    }
};

/**
 * Get registered module using trace object or trace type
 *
 * @param {object||string} trace
 *  trace object with prop 'type' or trace type as a string
 * @return {object}
 *  module object corresponding to trace type
 */
exports.getModule = function(trace) {
    var _module = exports.modules[getTraceType(trace)];
    if(!_module) return false;
    return _module._module;
};

/**
 * Determine if this trace type is in a given category
 *
 * @param {object||string} traceType
 *  a trace (object) or trace type (string)
 * @param {string} category
 *  category in question
 * @return {boolean}
 */
exports.traceIs = function(traceType, category) {
    traceType = getTraceType(traceType);

    // old plot.ly workspace hack, nothing to see here
    if(traceType === 'various') return false;

    var _module = exports.modules[traceType];

    if(!_module) {
        if(traceType && traceType !== 'area') {
            Loggers.log('Unrecognized trace type ' + traceType + '.');
        }

        _module = exports.modules[basePlotAttributes.type.dflt];
    }

    return !!_module.categories[category];
};

/**
 * Determine if this trace has a transform of the given type and return
 * array of matching indices.
 *
 * @param {object} data
 *  a trace object (member of data or fullData)
 * @param {string} type
 *  type of trace to test
 * @return {array}
 *  array of matching indices. If none found, returns []
 */
exports.getTransformIndices = function(data, type) {
    var indices = [];
    var transforms = data.transforms || [];
    for(var i = 0; i < transforms.length; i++) {
        if(transforms[i].type === type) {
            indices.push(i);
        }
    }
    return indices;
};

/**
 * Determine if this trace has a transform of the given type
 *
 * @param {object} data
 *  a trace object (member of data or fullData)
 * @param {string} type
 *  type of trace to test
 * @return {boolean}
 */
exports.hasTransform = function(data, type) {
    var transforms = data.transforms || [];
    for(var i = 0; i < transforms.length; i++) {
        if(transforms[i].type === type) {
            return true;
        }
    }
    return false;
};

/**
 * Retrieve component module method. Falls back on noop if either the
 * module or the method is missing, so the result can always be safely called
 *
 * @param {string} name
 *  name of component (as declared in component module)
 * @param {string} method
 *  name of component module method
 * @return {function}
 */
exports.getComponentMethod = function(name, method) {
    var _module = exports.componentsRegistry[name];

    if(!_module) return noop;
    return _module[method] || noop;
};

/**
 * Call registered api method.
 *
 * @param {string} name : api method name
 * @param {...array} args : arguments passed to api method
 * @return {any} : returns api method output
 */
exports.call = function() {
    var name = arguments[0];
    var args = [].slice.call(arguments, 1);
    return exports.apiMethodRegistry[name].apply(null, args);
};

function registerTraceModule(_module) {
    var thisType = _module.name;
    var categoriesIn = _module.categories;
    var meta = _module.meta;

    if(exports.modules[thisType]) {
        Loggers.log('Type ' + thisType + ' already registered');
        return;
    }

    if(!exports.subplotsRegistry[_module.basePlotModule.name]) {
        registerSubplot(_module.basePlotModule);
    }

    var categoryObj = {};
    for(var i = 0; i < categoriesIn.length; i++) {
        categoryObj[categoriesIn[i]] = true;
        exports.allCategories[categoriesIn[i]] = true;
    }

    exports.modules[thisType] = {
        _module: _module,
        categories: categoryObj
    };

    if(meta && Object.keys(meta).length) {
        exports.modules[thisType].meta = meta;
    }

    exports.allTypes.push(thisType);

    for(var componentName in exports.componentsRegistry) {
        mergeComponentAttrsToTrace(componentName, thisType);
    }

    /*
     * Collect all trace layout attributes in one place for easier lookup later
     * but don't merge them into the base schema as it would confuse the docs
     * (at least after https://github.com/plotly/documentation/issues/202 gets done!)
     */
    if(_module.layoutAttributes) {
        extendFlat(exports.traceLayoutAttributes, _module.layoutAttributes);
    }
}

function registerSubplot(_module) {
    var plotType = _module.name;

    if(exports.subplotsRegistry[plotType]) {
        Loggers.log('Plot type ' + plotType + ' already registered.');
        return;
    }

    // relayout array handling will look for component module methods with this
    // name and won't find them because this is a subplot module... but that
    // should be fine, it will just fall back on redrawing the plot.
    findArrayRegexps(_module);

    // not sure what's best for the 'cartesian' type at this point
    exports.subplotsRegistry[plotType] = _module;

    for(var componentName in exports.componentsRegistry) {
        mergeComponentAttrsToSubplot(componentName, _module.name);
    }
}

function registerComponentModule(_module) {
    if(typeof _module.name !== 'string') {
        throw new Error('Component module *name* must be a string.');
    }

    var name = _module.name;
    exports.componentsRegistry[name] = _module;

    if(_module.layoutAttributes) {
        if(_module.layoutAttributes._isLinkedToArray) {
            pushUnique(exports.layoutArrayContainers, name);
        }
        findArrayRegexps(_module);
    }

    for(var traceType in exports.modules) {
        mergeComponentAttrsToTrace(name, traceType);
    }

    for(var subplotName in exports.subplotsRegistry) {
        mergeComponentAttrsToSubplot(name, subplotName);
    }

    for(var transformType in exports.transformsRegistry) {
        mergeComponentAttrsToTransform(name, transformType);
    }

    if(_module.schema && _module.schema.layout) {
        extendDeepAll(baseLayoutAttributes, _module.schema.layout);
    }
}

function registerTransformModule(_module) {
    if(typeof _module.name !== 'string') {
        throw new Error('Transform module *name* must be a string.');
    }

    var prefix = 'Transform module ' + _module.name;
    var hasTransform = typeof _module.transform === 'function';
    var hasCalcTransform = typeof _module.calcTransform === 'function';

    if(!hasTransform && !hasCalcTransform) {
        throw new Error(prefix + ' is missing a *transform* or *calcTransform* method.');
    }
    if(hasTransform && hasCalcTransform) {
        Loggers.log([
            prefix + ' has both a *transform* and *calcTransform* methods.',
            'Please note that all *transform* methods are executed',
            'before all *calcTransform* methods.'
        ].join(' '));
    }
    if(!isPlainObject(_module.attributes)) {
        Loggers.log(prefix + ' registered without an *attributes* object.');
    }
    if(typeof _module.supplyDefaults !== 'function') {
        Loggers.log(prefix + ' registered without a *supplyDefaults* method.');
    }

    exports.transformsRegistry[_module.name] = _module;

    for(var componentName in exports.componentsRegistry) {
        mergeComponentAttrsToTransform(componentName, _module.name);
    }
}

function registerLocale(_module) {
    var locale = _module.name;
    var baseLocale = locale.split('-')[0];

    var newDict = _module.dictionary;
    var newFormat = _module.format;
    var hasDict = newDict && Object.keys(newDict).length;
    var hasFormat = newFormat && Object.keys(newFormat).length;

    var locales = exports.localeRegistry;

    var localeObj = locales[locale];
    if(!localeObj) locales[locale] = localeObj = {};

    // Should we use this dict for the base locale?
    // In case we're overwriting a previous dict for this locale, check
    // whether the base matches the full locale dict now. If we're not
    // overwriting, locales[locale] is undefined so this just checks if
    // baseLocale already had a dict or not.
    // Same logic for dateFormats
    if(baseLocale !== locale) {
        var baseLocaleObj = locales[baseLocale];
        if(!baseLocaleObj) locales[baseLocale] = baseLocaleObj = {};

        if(hasDict && baseLocaleObj.dictionary === localeObj.dictionary) {
            baseLocaleObj.dictionary = newDict;
        }
        if(hasFormat && baseLocaleObj.format === localeObj.format) {
            baseLocaleObj.format = newFormat;
        }
    }

    if(hasDict) localeObj.dictionary = newDict;
    if(hasFormat) localeObj.format = newFormat;
}

function findArrayRegexps(_module) {
    if(_module.layoutAttributes) {
        var arrayAttrRegexps = _module.layoutAttributes._arrayAttrRegexps;
        if(arrayAttrRegexps) {
            for(var i = 0; i < arrayAttrRegexps.length; i++) {
                pushUnique(exports.layoutArrayRegexes, arrayAttrRegexps[i]);
            }
        }
    }
}

function mergeComponentAttrsToTrace(componentName, traceType) {
    var componentSchema = exports.componentsRegistry[componentName].schema;
    if(!componentSchema || !componentSchema.traces) return;

    var traceAttrs = componentSchema.traces[traceType];
    if(traceAttrs) {
        extendDeepAll(exports.modules[traceType]._module.attributes, traceAttrs);
    }
}

function mergeComponentAttrsToTransform(componentName, transformType) {
    var componentSchema = exports.componentsRegistry[componentName].schema;
    if(!componentSchema || !componentSchema.transforms) return;

    var transformAttrs = componentSchema.transforms[transformType];
    if(transformAttrs) {
        extendDeepAll(exports.transformsRegistry[transformType].attributes, transformAttrs);
    }
}

function mergeComponentAttrsToSubplot(componentName, subplotName) {
    var componentSchema = exports.componentsRegistry[componentName].schema;
    if(!componentSchema || !componentSchema.subplots) return;

    var subplotModule = exports.subplotsRegistry[subplotName];
    var subplotAttrs = subplotModule.layoutAttributes;
    var subplotAttr = subplotModule.attr === 'subplot' ? subplotModule.name : subplotModule.attr;
    if(Array.isArray(subplotAttr)) subplotAttr = subplotAttr[0];

    var componentLayoutAttrs = componentSchema.subplots[subplotAttr];
    if(subplotAttrs && componentLayoutAttrs) {
        extendDeepAll(subplotAttrs, componentLayoutAttrs);
    }
}

function getTraceType(traceType) {
    if(typeof traceType === 'object') traceType = traceType.type;
    return traceType;
}

},{"./lib/extend":687,"./lib/is_plain_object":698,"./lib/loggers":701,"./lib/noop":706,"./lib/push_unique":711,"./plots/attributes":742,"./plots/layout_attributes":798}],827:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../lib');

var extendFlat = Lib.extendFlat;
var extendDeep = Lib.extendDeep;

// Put default plotTile layouts here
function cloneLayoutOverride(tileClass) {
    var override;

    switch(tileClass) {
        case 'themes__thumb':
            override = {
                autosize: true,
                width: 150,
                height: 150,
                title: {text: ''},
                showlegend: false,
                margin: {l: 5, r: 5, t: 5, b: 5, pad: 0},
                annotations: []
            };
            break;

        case 'thumbnail':
            override = {
                title: {text: ''},
                hidesources: true,
                showlegend: false,
                borderwidth: 0,
                bordercolor: '',
                margin: {l: 1, r: 1, t: 1, b: 1, pad: 0},
                annotations: []
            };
            break;

        default:
            override = {};
    }


    return override;
}

function keyIsAxis(keyName) {
    var types = ['xaxis', 'yaxis', 'zaxis'];
    return (types.indexOf(keyName.slice(0, 5)) > -1);
}


module.exports = function clonePlot(graphObj, options) {

    // Polar plot compatibility
    if(graphObj.framework && graphObj.framework.isPolar) {
        graphObj = graphObj.framework.getConfig();
    }

    var i;
    var oldData = graphObj.data;
    var oldLayout = graphObj.layout;
    var newData = extendDeep([], oldData);
    var newLayout = extendDeep({}, oldLayout, cloneLayoutOverride(options.tileClass));
    var context = graphObj._context || {};

    if(options.width) newLayout.width = options.width;
    if(options.height) newLayout.height = options.height;

    if(options.tileClass === 'thumbnail' || options.tileClass === 'themes__thumb') {
        // kill annotations
        newLayout.annotations = [];
        var keys = Object.keys(newLayout);

        for(i = 0; i < keys.length; i++) {
            if(keyIsAxis(keys[i])) {
                newLayout[keys[i]].title = {text: ''};
            }
        }

        // kill colorbar and pie labels
        for(i = 0; i < newData.length; i++) {
            var trace = newData[i];
            trace.showscale = false;
            if(trace.marker) trace.marker.showscale = false;
            if(trace.type === 'pie') trace.textposition = 'none';
        }
    }

    if(Array.isArray(options.annotations)) {
        for(i = 0; i < options.annotations.length; i++) {
            newLayout.annotations.push(options.annotations[i]);
        }
    }

    // TODO: does this scene modification really belong here?
    // If we still need it, can it move into the gl3d module?
    var sceneIds = Object.keys(newLayout).filter(function(key) {
        return key.match(/^scene\d*$/);
    });
    if(sceneIds.length) {
        var axesImageOverride = {};
        if(options.tileClass === 'thumbnail') {
            axesImageOverride = {
                title: {text: ''},
                showaxeslabels: false,
                showticklabels: false,
                linetickenable: false
            };
        }
        for(i = 0; i < sceneIds.length; i++) {
            var scene = newLayout[sceneIds[i]];

            if(!scene.xaxis) {
                scene.xaxis = {};
            }

            if(!scene.yaxis) {
                scene.yaxis = {};
            }

            if(!scene.zaxis) {
                scene.zaxis = {};
            }

            extendFlat(scene.xaxis, axesImageOverride);
            extendFlat(scene.yaxis, axesImageOverride);
            extendFlat(scene.zaxis, axesImageOverride);

            // TODO what does this do?
            scene._scene = null;
        }
    }

    var gd = document.createElement('div');
    if(options.tileClass) gd.className = options.tileClass;

    var plotTile = {
        gd: gd,
        td: gd, // for external (image server) compatibility
        layout: newLayout,
        data: newData,
        config: {
            staticPlot: (options.staticPlot === undefined) ?
                true :
                options.staticPlot,
            plotGlPixelRatio: (options.plotGlPixelRatio === undefined) ?
                2 :
                options.plotGlPixelRatio,
            displaylogo: options.displaylogo || false,
            showLink: options.showLink || false,
            showTips: options.showTips || false,
            mapboxAccessToken: context.mapboxAccessToken
        }
    };

    if(options.setBackground !== 'transparent') {
        plotTile.config.setBackground = options.setBackground || 'opaque';
    }

    // attaching the default Layout the gd, so you can grab it later
    plotTile.gd.defaultLayout = cloneLayoutOverride(options.tileClass);

    return plotTile;
};

},{"../lib":697}],828:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var toImage = _dereq_('../plot_api/to_image');
var Lib = _dereq_('../lib'); // for isIE
var fileSaver = _dereq_('./filesaver');

/** Plotly.downloadImage
 *
 * @param {object | string | HTML div} gd
 *   can either be a data/layout/config object
 *   or an existing graph <div>
 *   or an id to an existing graph <div>
 * @param {object} opts (see ../plot_api/to_image)
 * @return {promise}
 */
function downloadImage(gd, opts) {
    var _gd;
    if(!Lib.isPlainObject(gd)) _gd = Lib.getGraphDiv(gd);

    // check for undefined opts
    opts = opts || {};
    // default to png
    opts.format = opts.format || 'png';

    return new Promise(function(resolve, reject) {
        if(_gd && _gd._snapshotInProgress) {
            reject(new Error('Snapshotting already in progress.'));
        }

        // see comments within svgtoimg for additional
        //   discussion of problems with IE
        //   can now draw to canvas, but CORS tainted canvas
        //   does not allow toDataURL
        //   svg format will work though
        if(Lib.isIE() && opts.format !== 'svg') {
            reject(new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.'));
        }

        if(_gd) _gd._snapshotInProgress = true;
        var promise = toImage(gd, opts);

        var filename = opts.filename || gd.fn || 'newplot';
        filename += '.' + opts.format;

        promise.then(function(result) {
            if(_gd) _gd._snapshotInProgress = false;
            return fileSaver(result, filename);
        }).then(function(name) {
            resolve(name);
        }).catch(function(err) {
            if(_gd) _gd._snapshotInProgress = false;
            reject(err);
        });
    });
}

module.exports = downloadImage;

},{"../lib":697,"../plot_api/to_image":738,"./filesaver":829}],829:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

/*
* substantial portions of this code from FileSaver.js
* https://github.com/eligrey/FileSaver.js
* License: https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
* FileSaver.js
* A saveAs() FileSaver implementation.
* 1.1.20160328
*
* By Eli Grey, http://eligrey.com
* License: MIT
*   See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
*/

'use strict';

var fileSaver = function(url, name) {
    var saveLink = document.createElement('a');
    var canUseSaveLink = 'download' in saveLink;
    var isSafari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent);
    var promise = new Promise(function(resolve, reject) {
        // IE <10 is explicitly unsupported
        if(typeof navigator !== 'undefined' && /MSIE [1-9]\./.test(navigator.userAgent)) {
            reject(new Error('IE < 10 unsupported'));
        }

        // First try a.download, then web filesystem, then object URLs
        if(isSafari) {
            // Safari doesn't allow downloading of blob urls
            document.location.href = 'data:application/octet-stream' + url.slice(url.search(/[,;]/));
            resolve(name);
        }

        if(!name) {
            name = 'download';
        }

        if(canUseSaveLink) {
            saveLink.href = url;
            saveLink.download = name;
            document.body.appendChild(saveLink);
            saveLink.click();
            document.body.removeChild(saveLink);
            resolve(name);
        }

        // IE 10+ (native saveAs)
        if(typeof navigator !== 'undefined' && navigator.msSaveBlob) {
            // At this point we are only dealing with a SVG encoded as
            // a data URL (since IE only supports SVG)
            var encoded = url.split(/^data:image\/svg\+xml,/)[1];
            var svg = decodeURIComponent(encoded);
            navigator.msSaveBlob(new Blob([svg]), name);
            resolve(name);
        }

        reject(new Error('download error'));
    });

    return promise;
};

module.exports = fileSaver;

},{}],830:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

exports.getDelay = function(fullLayout) {
    if(!fullLayout._has) return 0;

    return (
        fullLayout._has('gl3d') ||
        fullLayout._has('gl2d') ||
        fullLayout._has('mapbox')
    ) ? 500 : 0;
};

exports.getRedrawFunc = function(gd) {
    var fullLayout = gd._fullLayout || {};
    var hasPolar = fullLayout._has && fullLayout._has('polar');
    var hasLegacyPolar = !hasPolar && gd.data && gd.data[0] && gd.data[0].r;

    // do not work for legacy polar
    if(hasLegacyPolar) return;

    return function() {
        (gd.calcdata || []).forEach(function(d) {
            if(d[0] && d[0].t && d[0].t.cb) d[0].t.cb();
        });
    };
};

},{}],831:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var helpers = _dereq_('./helpers');

var Snapshot = {
    getDelay: helpers.getDelay,
    getRedrawFunc: helpers.getRedrawFunc,
    clone: _dereq_('./cloneplot'),
    toSVG: _dereq_('./tosvg'),
    svgToImg: _dereq_('./svgtoimg'),
    toImage: _dereq_('./toimage'),
    downloadImage: _dereq_('./download')
};

module.exports = Snapshot;

},{"./cloneplot":827,"./download":828,"./helpers":830,"./svgtoimg":832,"./toimage":833,"./tosvg":834}],832:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../lib');
var EventEmitter = _dereq_('events').EventEmitter;

function svgToImg(opts) {
    var ev = opts.emitter || new EventEmitter();

    var promise = new Promise(function(resolve, reject) {
        var Image = window.Image;
        var svg = opts.svg;
        var format = opts.format || 'png';

        // IE only support svg
        if(Lib.isIE() && format !== 'svg') {
            var ieSvgError = new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.');
            reject(ieSvgError);
            // eventually remove the ev
            //  in favor of promises
            if(!opts.promise) {
                return ev.emit('error', ieSvgError);
            } else {
                return promise;
            }
        }

        var canvas = opts.canvas;
        var scale = opts.scale || 1;
        var w0 = opts.width || 300;
        var h0 = opts.height || 150;
        var w1 = scale * w0;
        var h1 = scale * h0;

        var ctx = canvas.getContext('2d');
        var img = new Image();

        // for Safari support, eliminate createObjectURL
        //  this decision could cause problems if content
        //  is not restricted to svg
        var url = 'data:image/svg+xml,' + encodeURIComponent(svg);

        canvas.width = w1;
        canvas.height = h1;

        img.onload = function() {
            var imgData;

            // don't need to draw to canvas if svg
            //  save some time and also avoid failure on IE
            if(format !== 'svg') {
                ctx.drawImage(img, 0, 0, w1, h1);
            }

            switch(format) {
                case 'jpeg':
                    imgData = canvas.toDataURL('image/jpeg');
                    break;
                case 'png':
                    imgData = canvas.toDataURL('image/png');
                    break;
                case 'webp':
                    imgData = canvas.toDataURL('image/webp');
                    break;
                case 'svg':
                    imgData = url;
                    break;
                default:
                    var errorMsg = 'Image format is not jpeg, png, svg or webp.';
                    reject(new Error(errorMsg));
                    // eventually remove the ev
                    //  in favor of promises
                    if(!opts.promise) {
                        return ev.emit('error', errorMsg);
                    }
            }
            resolve(imgData);
            // eventually remove the ev
            //  in favor of promises
            if(!opts.promise) {
                ev.emit('success', imgData);
            }
        };

        img.onerror = function(err) {
            reject(err);
            // eventually remove the ev
            //  in favor of promises
            if(!opts.promise) {
                return ev.emit('error', err);
            }
        };

        img.src = url;
    });

    // temporary for backward compatibility
    //  move to only Promise in 2.0.0
    //  and eliminate the EventEmitter
    if(opts.promise) {
        return promise;
    }

    return ev;
}

module.exports = svgToImg;

},{"../lib":697,"events":92}],833:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var EventEmitter = _dereq_('events').EventEmitter;

var Registry = _dereq_('../registry');
var Lib = _dereq_('../lib');

var helpers = _dereq_('./helpers');
var clonePlot = _dereq_('./cloneplot');
var toSVG = _dereq_('./tosvg');
var svgToImg = _dereq_('./svgtoimg');

/**
 * @param {object} gd figure Object
 * @param {object} opts option object
 * @param opts.format 'jpeg' | 'png' | 'webp' | 'svg'
 */
function toImage(gd, opts) {

    // first clone the GD so we can operate in a clean environment
    var ev = new EventEmitter();

    var clone = clonePlot(gd, {format: 'png'});
    var clonedGd = clone.gd;

    // put the cloned div somewhere off screen before attaching to DOM
    clonedGd.style.position = 'absolute';
    clonedGd.style.left = '-5000px';
    document.body.appendChild(clonedGd);

    function wait() {
        var delay = helpers.getDelay(clonedGd._fullLayout);

        setTimeout(function() {
            var svg = toSVG(clonedGd);

            var canvas = document.createElement('canvas');
            canvas.id = Lib.randstr();

            ev = svgToImg({
                format: opts.format,
                width: clonedGd._fullLayout.width,
                height: clonedGd._fullLayout.height,
                canvas: canvas,
                emitter: ev,
                svg: svg
            });

            ev.clean = function() {
                if(clonedGd) document.body.removeChild(clonedGd);
            };

        }, delay);
    }

    var redrawFunc = helpers.getRedrawFunc(clonedGd);

    Registry.call('plot', clonedGd, clone.data, clone.layout, clone.config)
        .then(redrawFunc)
        .then(wait)
        .catch(function(err) {
            ev.emit('error', err);
        });


    return ev;
}

module.exports = toImage;

},{"../lib":697,"../registry":826,"./cloneplot":827,"./helpers":830,"./svgtoimg":832,"./tosvg":834,"events":92}],834:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

var Lib = _dereq_('../lib');
var Drawing = _dereq_('../components/drawing');
var Color = _dereq_('../components/color');

var xmlnsNamespaces = _dereq_('../constants/xmlns_namespaces');
var DOUBLEQUOTE_REGEX = /"/g;
var DUMMY_SUB = 'TOBESTRIPPED';
var DUMMY_REGEX = new RegExp('("' + DUMMY_SUB + ')|(' + DUMMY_SUB + '")', 'g');

function htmlEntityDecode(s) {
    var hiddenDiv = d3.select('body').append('div').style({display: 'none'}).html('');
    var replaced = s.replace(/(&[^;]*;)/gi, function(d) {
        if(d === '&lt;') { return '&#60;'; } // special handling for brackets
        if(d === '&rt;') { return '&#62;'; }
        if(d.indexOf('<') !== -1 || d.indexOf('>') !== -1) { return ''; }
        return hiddenDiv.html(d).text(); // everything else, let the browser decode it to unicode
    });
    hiddenDiv.remove();
    return replaced;
}

function xmlEntityEncode(str) {
    return str.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g, '&amp;');
}

module.exports = function toSVG(gd, format, scale) {
    var fullLayout = gd._fullLayout;
    var svg = fullLayout._paper;
    var toppaper = fullLayout._toppaper;
    var width = fullLayout.width;
    var height = fullLayout.height;
    var i;

    // make background color a rect in the svg, then revert after scraping
    // all other alterations have been dealt with by properly preparing the svg
    // in the first place... like setting cursors with css classes so we don't
    // have to remove them, and providing the right namespaces in the svg to
    // begin with
    svg.insert('rect', ':first-child')
        .call(Drawing.setRect, 0, 0, width, height)
        .call(Color.fill, fullLayout.paper_bgcolor);

    // subplot-specific to-SVG methods
    // which notably add the contents of the gl-container
    // into the main svg node
    var basePlotModules = fullLayout._basePlotModules || [];
    for(i = 0; i < basePlotModules.length; i++) {
        var _module = basePlotModules[i];

        if(_module.toSVG) _module.toSVG(gd);
    }

    // add top items above them assumes everything in toppaper is either
    // a group or a defs, and if it's empty (like hoverlayer) we can ignore it.
    if(toppaper) {
        var nodes = toppaper.node().childNodes;

        // make copy of nodes as childNodes prop gets mutated in loop below
        var topGroups = Array.prototype.slice.call(nodes);

        for(i = 0; i < topGroups.length; i++) {
            var topGroup = topGroups[i];

            if(topGroup.childNodes.length) svg.node().appendChild(topGroup);
        }
    }

    // remove draglayer for Adobe Illustrator compatibility
    if(fullLayout._draggers) {
        fullLayout._draggers.remove();
    }

    // in case the svg element had an explicit background color, remove this
    // we want the rect to get the color so it's the right size; svg bg will
    // fill whatever container it's displayed in regardless of plot size.
    svg.node().style.background = '';

    svg.selectAll('text')
        .attr({'data-unformatted': null, 'data-math': null})
        .each(function() {
            var txt = d3.select(this);

            // hidden text is pre-formatting mathjax, the browser ignores it
            // but in a static plot it's useless and it can confuse batik
            // we've tried to standardize on display:none but make sure we still
            // catch visibility:hidden if it ever arises
            if(this.style.visibility === 'hidden' || this.style.display === 'none') {
                txt.remove();
                return;
            }
            else {
                // clear other visibility/display values to default
                // to not potentially confuse non-browser SVG implementations
                txt.style({visibility: null, display: null});
            }

            // Font family styles break things because of quotation marks,
            // so we must remove them *after* the SVG DOM has been serialized
            // to a string (browsers convert singles back)
            var ff = this.style.fontFamily;
            if(ff && ff.indexOf('"') !== -1) {
                txt.style('font-family', ff.replace(DOUBLEQUOTE_REGEX, DUMMY_SUB));
            }
        });

    svg.selectAll('.point, .scatterpts, .legendfill>path, .legendlines>path, .cbfill').each(function() {
        var pt = d3.select(this);

        // similar to font family styles above,
        // we must remove " after the SVG DOM has been serialized
        var fill = this.style.fill;
        if(fill && fill.indexOf('url(') !== -1) {
            pt.style('fill', fill.replace(DOUBLEQUOTE_REGEX, DUMMY_SUB));
        }

        var stroke = this.style.stroke;
        if(stroke && stroke.indexOf('url(') !== -1) {
            pt.style('stroke', stroke.replace(DOUBLEQUOTE_REGEX, DUMMY_SUB));
        }
    });

    if(format === 'pdf' || format === 'eps') {
        // these formats make the extra line MathJax adds around symbols look super thick in some cases
        // it looks better if this is removed entirely.
        svg.selectAll('#MathJax_SVG_glyphs path')
            .attr('stroke-width', 0);
    }

    // fix for IE namespacing quirk?
    // http://stackoverflow.com/questions/19610089/unwanted-namespaces-on-svg-markup-when-using-xmlserializer-in-javascript-with-ie
    svg.node().setAttributeNS(xmlnsNamespaces.xmlns, 'xmlns', xmlnsNamespaces.svg);
    svg.node().setAttributeNS(xmlnsNamespaces.xmlns, 'xmlns:xlink', xmlnsNamespaces.xlink);

    if(format === 'svg' && scale) {
        svg.attr('width', scale * width);
        svg.attr('height', scale * height);
        svg.attr('viewBox', '0 0 ' + width + ' ' + height);
    }

    var s = new window.XMLSerializer().serializeToString(svg.node());
    s = htmlEntityDecode(s);
    s = xmlEntityEncode(s);

    // Fix quotations around font strings and gradient URLs
    s = s.replace(DUMMY_REGEX, '\'');

    // IE is very strict, so we will need to clean
    //  svg with the following regex
    //  yes this is messy, but do not know a better way
    // Even with this IE will not work due to tainted canvas
    //  see https://github.com/kangax/fabric.js/issues/1957
    //      http://stackoverflow.com/questions/18112047/canvas-todataurl-working-in-all-browsers-except-ie10
    // Leave here just in case the CORS/tainted IE issue gets resolved
    if(Lib.isIE()) {
        // replace double quote with single quote
        s = s.replace(/"/gi, '\'');
        // url in svg are single quoted
        //   since we changed double to single
        //   we'll need to change these to double-quoted
        s = s.replace(/(\('#)([^']*)('\))/gi, '(\"#$2\")');
        // font names with spaces will be escaped single-quoted
        //   we'll need to change these to double-quoted
        s = s.replace(/(\\')/gi, '\"');
    }

    return s;
};

},{"../components/color":574,"../components/drawing":595,"../constants/xmlns_namespaces":675,"../lib":697,"d3":151}],835:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var mergeArray = _dereq_('../../lib').mergeArray;


// arrayOk attributes, merge them into calcdata array
module.exports = function arraysToCalcdata(cd, trace) {
    for(var i = 0; i < cd.length; i++) cd[i].i = i;

    mergeArray(trace.text, cd, 'tx');
    mergeArray(trace.hovertext, cd, 'htx');

    var marker = trace.marker;
    if(marker) {
        mergeArray(marker.opacity, cd, 'mo');
        mergeArray(marker.color, cd, 'mc');

        var markerLine = marker.line;
        if(markerLine) {
            mergeArray(markerLine.color, cd, 'mlc');
            mergeArray(markerLine.width, cd, 'mlw');
        }
    }
};

},{"../../lib":697}],836:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterAttrs = _dereq_('../scatter/attributes');
var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var colorAttributes = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
var fontAttrs = _dereq_('../../plots/font_attributes');
var constants = _dereq_('./constants.js');

var extendFlat = _dereq_('../../lib/extend').extendFlat;

var textFontAttrs = fontAttrs({
    editType: 'calc',
    arrayOk: true,
    colorEditType: 'style',
    
});

var scatterMarkerAttrs = scatterAttrs.marker;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;

var markerLineWidth = extendFlat({},
    scatterMarkerLineAttrs.width, { dflt: 0 });

var markerLine = extendFlat({
    width: markerLineWidth,
    editType: 'calc'
}, colorAttributes('marker.line'));

var marker = extendFlat({
    line: markerLine,
    editType: 'calc'
}, colorAttributes('marker'), {
    colorbar: colorbarAttrs,
    opacity: {
        valType: 'number',
        arrayOk: true,
        dflt: 1,
        min: 0,
        max: 1,
        
        editType: 'style',
        
    }
});

module.exports = {
    x: scatterAttrs.x,
    x0: scatterAttrs.x0,
    dx: scatterAttrs.dx,
    y: scatterAttrs.y,
    y0: scatterAttrs.y0,
    dy: scatterAttrs.dy,

    text: scatterAttrs.text,
    hovertext: scatterAttrs.hovertext,
    hovertemplate: hovertemplateAttrs({}, {
        keys: constants.eventDataKeys
    }),

    textposition: {
        valType: 'enumerated',
        
        values: ['inside', 'outside', 'auto', 'none'],
        dflt: 'none',
        arrayOk: true,
        editType: 'calc',
        
    },

    textfont: extendFlat({}, textFontAttrs, {
        
    }),

    insidetextfont: extendFlat({}, textFontAttrs, {
        
    }),

    outsidetextfont: extendFlat({}, textFontAttrs, {
        
    }),

    constraintext: {
        valType: 'enumerated',
        values: ['inside', 'outside', 'both', 'none'],
        
        dflt: 'both',
        editType: 'calc',
        
    },

    cliponaxis: extendFlat({}, scatterAttrs.cliponaxis, {
        
    }),

    orientation: {
        valType: 'enumerated',
        
        values: ['v', 'h'],
        editType: 'calc+clearAxisTypes',
        
    },

    base: {
        valType: 'any',
        dflt: null,
        arrayOk: true,
        
        editType: 'calc',
        
    },

    offset: {
        valType: 'number',
        dflt: null,
        arrayOk: true,
        
        editType: 'calc',
        
    },

    width: {
        valType: 'number',
        dflt: null,
        min: 0,
        arrayOk: true,
        
        editType: 'calc',
        
    },

    marker: marker,

    offsetgroup: {
        valType: 'string',
        
        dflt: '',
        editType: 'calc',
        
    },
    alignmentgroup: {
        valType: 'string',
        
        dflt: '',
        editType: 'calc',
        
    },

    selected: {
        marker: {
            opacity: scatterAttrs.selected.marker.opacity,
            color: scatterAttrs.selected.marker.color,
            editType: 'style'
        },
        textfont: scatterAttrs.selected.textfont,
        editType: 'style'
    },
    unselected: {
        marker: {
            opacity: scatterAttrs.unselected.marker.opacity,
            color: scatterAttrs.unselected.marker.color,
            editType: 'style'
        },
        textfont: scatterAttrs.unselected.textfont,
        editType: 'style'
    },

    r: scatterAttrs.r,
    t: scatterAttrs.t,

    _deprecated: {
        bardir: {
            valType: 'enumerated',
            
            editType: 'calc',
            values: ['v', 'h'],
            
        }
    }
};

},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plots/font_attributes":771,"../scatter/attributes":1048,"./constants.js":838}],837:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Axes = _dereq_('../../plots/cartesian/axes');
var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
var colorscaleCalc = _dereq_('../../components/colorscale/calc');
var arraysToCalcdata = _dereq_('./arrays_to_calcdata');
var calcSelection = _dereq_('../scatter/calc_selection');

module.exports = function calc(gd, trace) {
    var xa = Axes.getFromId(gd, trace.xaxis || 'x');
    var ya = Axes.getFromId(gd, trace.yaxis || 'y');
    var size, pos;

    if(trace.orientation === 'h') {
        size = xa.makeCalcdata(trace, 'x');
        pos = ya.makeCalcdata(trace, 'y');
    } else {
        size = ya.makeCalcdata(trace, 'y');
        pos = xa.makeCalcdata(trace, 'x');
    }

    // create the "calculated data" to plot
    var serieslen = Math.min(pos.length, size.length);
    var cd = new Array(serieslen);

    // set position and size
    for(var i = 0; i < serieslen; i++) {
        cd[i] = { p: pos[i], s: size[i] };

        if(trace.ids) {
            cd[i].id = String(trace.ids[i]);
        }
    }

    // auto-z and autocolorscale if applicable
    if(hasColorscale(trace, 'marker')) {
        colorscaleCalc(gd, trace, {
            vals: trace.marker.color,
            containerStr: 'marker',
            cLetter: 'c'
        });
    }
    if(hasColorscale(trace, 'marker.line')) {
        colorscaleCalc(gd, trace, {
            vals: trace.marker.line.color,
            containerStr: 'marker.line',
            cLetter: 'c'
        });
    }

    arraysToCalcdata(cd, trace);
    calcSelection(cd, trace);

    return cd;
};

},{"../../components/colorscale/calc":582,"../../components/colorscale/helpers":585,"../../plots/cartesian/axes":745,"../scatter/calc_selection":1050,"./arrays_to_calcdata":835}],838:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = {
    eventDataKeys: []
};

},{}],839:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

var Registry = _dereq_('../../registry');
var Axes = _dereq_('../../plots/cartesian/axes');
var getAxisGroup = _dereq_('../../plots/cartesian/axis_ids').getAxisGroup;
var Sieve = _dereq_('./sieve.js');

/*
 * Bar chart stacking/grouping positioning and autoscaling calculations
 * for each direction separately calculate the ranges and positions
 * note that this handles histograms too
 * now doing this one subplot at a time
 */

function crossTraceCalc(gd, plotinfo) {
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    var fullTraces = gd._fullData;
    var calcTraces = gd.calcdata;
    var calcTracesHorizontal = [];
    var calcTracesVertical = [];

    for(var i = 0; i < fullTraces.length; i++) {
        var fullTrace = fullTraces[i];
        if(
            fullTrace.visible === true &&
            Registry.traceIs(fullTrace, 'bar') &&
            fullTrace.xaxis === xa._id &&
            fullTrace.yaxis === ya._id
        ) {
            if(fullTrace.orientation === 'h') {
                calcTracesHorizontal.push(calcTraces[i]);
            } else {
                calcTracesVertical.push(calcTraces[i]);
            }
        }
    }

    setGroupPositions(gd, xa, ya, calcTracesVertical);
    setGroupPositions(gd, ya, xa, calcTracesHorizontal);
}

function setGroupPositions(gd, pa, sa, calcTraces) {
    if(!calcTraces.length) return;

    var barmode = gd._fullLayout.barmode;
    var overlay = (barmode === 'overlay');
    var group = (barmode === 'group');
    var excluded;
    var included;
    var i, calcTrace, fullTrace;

    initBase(gd, pa, sa, calcTraces);

    if(overlay) {
        setGroupPositionsInOverlayMode(gd, pa, sa, calcTraces);
    } else if(group) {
        // exclude from the group those traces for which the user set an offset
        excluded = [];
        included = [];
        for(i = 0; i < calcTraces.length; i++) {
            calcTrace = calcTraces[i];
            fullTrace = calcTrace[0].trace;

            if(fullTrace.offset === undefined) included.push(calcTrace);
            else excluded.push(calcTrace);
        }

        if(included.length) {
            setGroupPositionsInGroupMode(gd, pa, sa, included);
        }
        if(excluded.length) {
            setGroupPositionsInOverlayMode(gd, pa, sa, excluded);
        }
    } else {
        // exclude from the stack those traces for which the user set a base
        excluded = [];
        included = [];
        for(i = 0; i < calcTraces.length; i++) {
            calcTrace = calcTraces[i];
            fullTrace = calcTrace[0].trace;

            if(fullTrace.base === undefined) included.push(calcTrace);
            else excluded.push(calcTrace);
        }

        if(included.length) {
            setGroupPositionsInStackOrRelativeMode(gd, pa, sa, included);
        }
        if(excluded.length) {
            setGroupPositionsInOverlayMode(gd, pa, sa, excluded);
        }
    }

    collectExtents(calcTraces, pa);
}

function initBase(gd, pa, sa, calcTraces) {
    var i, j;

    for(i = 0; i < calcTraces.length; i++) {
        var cd = calcTraces[i];
        var trace = cd[0].trace;
        var base = trace.base;
        var b;

        // not sure if it really makes sense to have dates for bar size data...
        // ideally if we want to make gantt charts or something we'd treat
        // the actual size (trace.x or y) as time delta but base as absolute
        // time. But included here for completeness.
        var scalendar = trace.orientation === 'h' ? trace.xcalendar : trace.ycalendar;

        // 'base' on categorical axes makes no sense
        var d2c = sa.type === 'category' || sa.type === 'multicategory' ?
            function() { return null; } :
            sa.d2c;

        if(isArrayOrTypedArray(base)) {
            for(j = 0; j < Math.min(base.length, cd.length); j++) {
                b = d2c(base[j], 0, scalendar);
                if(isNumeric(b)) {
                    cd[j].b = +b;
                    cd[j].hasB = 1;
                }
                else cd[j].b = 0;
            }
            for(; j < cd.length; j++) {
                cd[j].b = 0;
            }
        } else {
            b = d2c(base, 0, scalendar);
            var hasBase = isNumeric(b);
            b = hasBase ? b : 0;
            for(j = 0; j < cd.length; j++) {
                cd[j].b = b;
                if(hasBase) cd[j].hasB = 1;
            }
        }
    }
}

function setGroupPositionsInOverlayMode(gd, pa, sa, calcTraces) {
    var barnorm = gd._fullLayout.barnorm;
    var separateNegativeValues = false;
    var dontMergeOverlappingData = !barnorm;

    // update position axis and set bar offsets and widths
    for(var i = 0; i < calcTraces.length; i++) {
        var calcTrace = calcTraces[i];
        var sieve = new Sieve([calcTrace], separateNegativeValues, dontMergeOverlappingData);

        // set bar offsets and widths, and update position axis
        setOffsetAndWidth(gd, pa, sieve);

        // set bar bases and sizes, and update size axis
        //
        // (note that `setGroupPositionsInOverlayMode` handles the case barnorm
        // is defined, because this function is also invoked for traces that
        // can't be grouped or stacked)
        if(barnorm) {
            sieveBars(gd, sa, sieve);
            normalizeBars(gd, sa, sieve);
        } else {
            setBaseAndTop(gd, sa, sieve);
        }
    }
}

function setGroupPositionsInGroupMode(gd, pa, sa, calcTraces) {
    var fullLayout = gd._fullLayout;
    var barnorm = fullLayout.barnorm;
    var separateNegativeValues = false;
    var dontMergeOverlappingData = !barnorm;
    var sieve = new Sieve(calcTraces, separateNegativeValues, dontMergeOverlappingData);

    // set bar offsets and widths, and update position axis
    setOffsetAndWidthInGroupMode(gd, pa, sieve);

    // set bar bases and sizes, and update size axis
    if(barnorm) {
        sieveBars(gd, sa, sieve);
        normalizeBars(gd, sa, sieve);
    } else {
        setBaseAndTop(gd, sa, sieve);
    }
}

function setGroupPositionsInStackOrRelativeMode(gd, pa, sa, calcTraces) {
    var fullLayout = gd._fullLayout;
    var barmode = fullLayout.barmode;
    var stack = barmode === 'stack';
    var relative = barmode === 'relative';
    var barnorm = fullLayout.barnorm;
    var separateNegativeValues = relative;
    var dontMergeOverlappingData = !(barnorm || stack || relative);
    var sieve = new Sieve(calcTraces, separateNegativeValues, dontMergeOverlappingData);

    // set bar offsets and widths, and update position axis
    setOffsetAndWidth(gd, pa, sieve);

    // set bar bases and sizes, and update size axis
    stackBars(gd, sa, sieve);

    // flag the outmost bar (for text display purposes)
    for(var i = 0; i < calcTraces.length; i++) {
        var calcTrace = calcTraces[i];

        for(var j = 0; j < calcTrace.length; j++) {
            var bar = calcTrace[j];

            if(bar.s !== BADNUM) {
                var isOutmostBar = ((bar.b + bar.s) === sieve.get(bar.p, bar.s));
                if(isOutmostBar) bar._outmost = true;
            }
        }
    }

    // Note that marking the outmost bars has to be done
    // before `normalizeBars` changes `bar.b` and `bar.s`.
    if(barnorm) normalizeBars(gd, sa, sieve);
}

function setOffsetAndWidth(gd, pa, sieve) {
    var fullLayout = gd._fullLayout;
    var bargap = fullLayout.bargap;
    var bargroupgap = fullLayout.bargroupgap || 0;
    var minDiff = sieve.minDiff;
    var calcTraces = sieve.traces;

    // set bar offsets and widths
    var barGroupWidth = minDiff * (1 - bargap);
    var barWidthPlusGap = barGroupWidth;
    var barWidth = barWidthPlusGap * (1 - bargroupgap);

    // computer bar group center and bar offset
    var offsetFromCenter = -barWidth / 2;

    for(var i = 0; i < calcTraces.length; i++) {
        var calcTrace = calcTraces[i];
        var t = calcTrace[0].t;

        // store bar width and offset for this trace
        t.barwidth = barWidth;
        t.poffset = offsetFromCenter;
        t.bargroupwidth = barGroupWidth;
        t.bardelta = minDiff;
    }

    // stack bars that only differ by rounding
    sieve.binWidth = calcTraces[0][0].t.barwidth / 100;

    // if defined, apply trace offset and width
    applyAttributes(sieve);

    // store the bar center in each calcdata item
    setBarCenterAndWidth(gd, pa, sieve);

    // update position axes
    updatePositionAxis(gd, pa, sieve);
}

function setOffsetAndWidthInGroupMode(gd, pa, sieve) {
    var fullLayout = gd._fullLayout;
    var bargap = fullLayout.bargap;
    var bargroupgap = fullLayout.bargroupgap || 0;
    var positions = sieve.positions;
    var distinctPositions = sieve.distinctPositions;
    var minDiff = sieve.minDiff;
    var calcTraces = sieve.traces;
    var nTraces = calcTraces.length;

    // if there aren't any overlapping positions,
    // let them have full width even if mode is group
    var overlap = (positions.length !== distinctPositions.length);
    var barGroupWidth = minDiff * (1 - bargap);

    var groupId = getAxisGroup(fullLayout, pa._id) + calcTraces[0][0].trace.orientation;
    var alignmentGroups = fullLayout._alignmentOpts[groupId] || {};

    for(var i = 0; i < nTraces; i++) {
        var calcTrace = calcTraces[i];
        var trace = calcTrace[0].trace;

        var alignmentGroupOpts = alignmentGroups[trace.alignmentgroup] || {};
        var nOffsetGroups = Object.keys(alignmentGroupOpts.offsetGroups || {}).length;

        var barWidthPlusGap;
        if(nOffsetGroups) {
            barWidthPlusGap = barGroupWidth / nOffsetGroups;
        } else {
            barWidthPlusGap = overlap ? barGroupWidth / nTraces : barGroupWidth;
        }

        var barWidth = barWidthPlusGap * (1 - bargroupgap);

        var offsetFromCenter;
        if(nOffsetGroups) {
            offsetFromCenter = ((2 * trace._offsetIndex + 1 - nOffsetGroups) * barWidthPlusGap - barWidth) / 2;
        } else {
            offsetFromCenter = overlap ?
                ((2 * i + 1 - nTraces) * barWidthPlusGap - barWidth) / 2 :
                -barWidth / 2;
        }

        var t = calcTrace[0].t;
        t.barwidth = barWidth;
        t.poffset = offsetFromCenter;
        t.bargroupwidth = barGroupWidth;
        t.bardelta = minDiff;
    }

    // stack bars that only differ by rounding
    sieve.binWidth = calcTraces[0][0].t.barwidth / 100;

    // if defined, apply trace width
    applyAttributes(sieve);

    // store the bar center in each calcdata item
    setBarCenterAndWidth(gd, pa, sieve);

    // update position axes
    updatePositionAxis(gd, pa, sieve, overlap);
}

function applyAttributes(sieve) {
    var calcTraces = sieve.traces;
    var i, j;

    for(i = 0; i < calcTraces.length; i++) {
        var calcTrace = calcTraces[i];
        var calcTrace0 = calcTrace[0];
        var fullTrace = calcTrace0.trace;
        var t = calcTrace0.t;
        var offset = fullTrace._offset || fullTrace.offset;
        var initialPoffset = t.poffset;
        var newPoffset;

        if(isArrayOrTypedArray(offset)) {
            // if offset is an array, then clone it into t.poffset.
            newPoffset = Array.prototype.slice.call(offset, 0, calcTrace.length);

            // guard against non-numeric items
            for(j = 0; j < newPoffset.length; j++) {
                if(!isNumeric(newPoffset[j])) {
                    newPoffset[j] = initialPoffset;
                }
            }

            // if the length of the array is too short,
            // then extend it with the initial value of t.poffset
            for(j = newPoffset.length; j < calcTrace.length; j++) {
                newPoffset.push(initialPoffset);
            }

            t.poffset = newPoffset;
        } else if(offset !== undefined) {
            t.poffset = offset;
        }

        var width = fullTrace._width || fullTrace.width;
        var initialBarwidth = t.barwidth;

        if(isArrayOrTypedArray(width)) {
            // if width is an array, then clone it into t.barwidth.
            var newBarwidth = Array.prototype.slice.call(width, 0, calcTrace.length);

            // guard against non-numeric items
            for(j = 0; j < newBarwidth.length; j++) {
                if(!isNumeric(newBarwidth[j])) newBarwidth[j] = initialBarwidth;
            }

            // if the length of the array is too short,
            // then extend it with the initial value of t.barwidth
            for(j = newBarwidth.length; j < calcTrace.length; j++) {
                newBarwidth.push(initialBarwidth);
            }

            t.barwidth = newBarwidth;

            // if user didn't set offset,
            // then correct t.poffset to ensure bars remain centered
            if(offset === undefined) {
                newPoffset = [];
                for(j = 0; j < calcTrace.length; j++) {
                    newPoffset.push(
                        initialPoffset + (initialBarwidth - newBarwidth[j]) / 2
                    );
                }
                t.poffset = newPoffset;
            }
        } else if(width !== undefined) {
            t.barwidth = width;

            // if user didn't set offset,
            // then correct t.poffset to ensure bars remain centered
            if(offset === undefined) {
                t.poffset = initialPoffset + (initialBarwidth - width) / 2;
            }
        }
    }
}

function setBarCenterAndWidth(gd, pa, sieve) {
    var calcTraces = sieve.traces;
    var pLetter = getAxisLetter(pa);

    for(var i = 0; i < calcTraces.length; i++) {
        var calcTrace = calcTraces[i];
        var t = calcTrace[0].t;
        var poffset = t.poffset;
        var poffsetIsArray = Array.isArray(poffset);
        var barwidth = t.barwidth;
        var barwidthIsArray = Array.isArray(barwidth);

        for(var j = 0; j < calcTrace.length; j++) {
            var calcBar = calcTrace[j];

            // store the actual bar width and position, for use by hover
            var width = calcBar.w = barwidthIsArray ? barwidth[j] : barwidth;
            calcBar[pLetter] = calcBar.p + (poffsetIsArray ? poffset[j] : poffset) + width / 2;
        }
    }
}

function updatePositionAxis(gd, pa, sieve, allowMinDtick) {
    var calcTraces = sieve.traces;
    var minDiff = sieve.minDiff;
    var vpad = minDiff / 2;

    Axes.minDtick(pa, sieve.minDiff, sieve.distinctPositions[0], allowMinDtick);

    for(var i = 0; i < calcTraces.length; i++) {
        var calcTrace = calcTraces[i];
        var calcTrace0 = calcTrace[0];
        var fullTrace = calcTrace0.trace;
        var pts = [];
        var bar, l, r, j;

        for(j = 0; j < calcTrace.length; j++) {
            bar = calcTrace[j];
            l = bar.p - vpad;
            r = bar.p + vpad;
            pts.push(l, r);
        }

        if(fullTrace.width || fullTrace.offset) {
            var t = calcTrace0.t;
            var poffset = t.poffset;
            var barwidth = t.barwidth;
            var poffsetIsArray = Array.isArray(poffset);
            var barwidthIsArray = Array.isArray(barwidth);

            for(j = 0; j < calcTrace.length; j++) {
                bar = calcTrace[j];
                var calcBarOffset = poffsetIsArray ? poffset[j] : poffset;
                var calcBarWidth = barwidthIsArray ? barwidth[j] : barwidth;
                l = bar.p + calcBarOffset;
                r = l + calcBarWidth;
                pts.push(l, r);
            }
        }

        fullTrace._extremes[pa._id] = Axes.findExtremes(pa, pts, {padded: false});
    }
}

// store these bar bases and tops in calcdata
// and make sure the size axis includes zero,
// along with the bases and tops of each bar.
function setBaseAndTop(gd, sa, sieve) {
    var calcTraces = sieve.traces;
    var sLetter = getAxisLetter(sa);

    for(var i = 0; i < calcTraces.length; i++) {
        var calcTrace = calcTraces[i];
        var fullTrace = calcTrace[0].trace;
        var pts = [];
        var allBarBaseAboveZero = true;

        for(var j = 0; j < calcTrace.length; j++) {
            var bar = calcTrace[j];
            var barBase = bar.b;
            var barTop = barBase + bar.s;

            bar[sLetter] = barTop;
            pts.push(barTop);
            if(bar.hasB) pts.push(barBase);

            if(!bar.hasB || !(bar.b > 0 && bar.s > 0)) {
                allBarBaseAboveZero = false;
            }
        }

        fullTrace._extremes[sa._id] = Axes.findExtremes(sa, pts, {
            tozero: !allBarBaseAboveZero,
            padded: true
        });
    }
}

function stackBars(gd, sa, sieve) {
    var fullLayout = gd._fullLayout;
    var barnorm = fullLayout.barnorm;
    var sLetter = getAxisLetter(sa);
    var calcTraces = sieve.traces;

    for(var i = 0; i < calcTraces.length; i++) {
        var calcTrace = calcTraces[i];
        var fullTrace = calcTrace[0].trace;
        var pts = [];

        for(var j = 0; j < calcTrace.length; j++) {
            var bar = calcTrace[j];

            if(bar.s !== BADNUM) {
                // stack current bar and get previous sum
                var barBase = sieve.put(bar.p, bar.b + bar.s);
                var barTop = barBase + bar.b + bar.s;

                // store the bar base and top in each calcdata item
                bar.b = barBase;
                bar[sLetter] = barTop;

                if(!barnorm) {
                    pts.push(barTop);
                    if(bar.hasB) pts.push(barBase);
                }
            }
        }

        // if barnorm is set, let normalizeBars update the axis range
        if(!barnorm) {
            fullTrace._extremes[sa._id] = Axes.findExtremes(sa, pts, {
                // N.B. we don't stack base with 'base',
                // so set tozero:true always!
                tozero: true,
                padded: true
            });
        }
    }
}

function sieveBars(gd, sa, sieve) {
    var calcTraces = sieve.traces;

    for(var i = 0; i < calcTraces.length; i++) {
        var calcTrace = calcTraces[i];

        for(var j = 0; j < calcTrace.length; j++) {
            var bar = calcTrace[j];

            if(bar.s !== BADNUM) sieve.put(bar.p, bar.b + bar.s);
        }
    }
}

// Note:
//
// normalizeBars requires that either sieveBars or stackBars has been
// previously invoked.
function normalizeBars(gd, sa, sieve) {
    var fullLayout = gd._fullLayout;
    var calcTraces = sieve.traces;
    var sLetter = getAxisLetter(sa);
    var sTop = fullLayout.barnorm === 'fraction' ? 1 : 100;
    var sTiny = sTop / 1e9; // in case of rounding error in sum
    var sMin = sa.l2c(sa.c2l(0));
    var sMax = fullLayout.barmode === 'stack' ? sTop : sMin;

    function needsPadding(v) {
        return (
            isNumeric(sa.c2l(v)) &&
            ((v < sMin - sTiny) || (v > sMax + sTiny) || !isNumeric(sMin))
        );
    }

    for(var i = 0; i < calcTraces.length; i++) {
        var calcTrace = calcTraces[i];
        var fullTrace = calcTrace[0].trace;
        var pts = [];
        var allBarBaseAboveZero = true;
        var padded = false;

        for(var j = 0; j < calcTrace.length; j++) {
            var bar = calcTrace[j];

            if(bar.s !== BADNUM) {
                var scale = Math.abs(sTop / sieve.get(bar.p, bar.s));
                bar.b *= scale;
                bar.s *= scale;

                var barBase = bar.b;
                var barTop = barBase + bar.s;

                bar[sLetter] = barTop;
                pts.push(barTop);
                padded = padded || needsPadding(barTop);

                if(bar.hasB) {
                    pts.push(barBase);
                    padded = padded || needsPadding(barBase);
                }

                if(!bar.hasB || !(bar.b > 0 && bar.s > 0)) {
                    allBarBaseAboveZero = false;
                }
            }
        }

        fullTrace._extremes[sa._id] = Axes.findExtremes(sa, pts, {
            tozero: !allBarBaseAboveZero,
            padded: padded
        });
    }
}

// find the full position span of bars at each position
// for use by hover, to ensure labels move in if bars are
// narrower than the space they're in.
// run once per trace group (subplot & direction) and
// the same mapping is attached to all calcdata traces
function collectExtents(calcTraces, pa) {
    var pLetter = getAxisLetter(pa);
    var extents = {};
    var i, j, cd;

    var pMin = Infinity;
    var pMax = -Infinity;

    for(i = 0; i < calcTraces.length; i++) {
        cd = calcTraces[i];
        for(j = 0; j < cd.length; j++) {
            var p = cd[j].p;
            if(isNumeric(p)) {
                pMin = Math.min(pMin, p);
                pMax = Math.max(pMax, p);
            }
        }
    }

    // this is just for positioning of hover labels, and nobody will care if
    // the label is 1px too far out; so round positions to 1/10K in case
    // position values don't exactly match from trace to trace
    var roundFactor = 10000 / (pMax - pMin);
    var round = extents.round = function(p) {
        return String(Math.round(roundFactor * (p - pMin)));
    };

    for(i = 0; i < calcTraces.length; i++) {
        cd = calcTraces[i];
        cd[0].t.extents = extents;

        var poffset = cd[0].t.poffset;
        var poffsetIsArray = Array.isArray(poffset);

        for(j = 0; j < cd.length; j++) {
            var di = cd[j];
            var p0 = di[pLetter] - di.w / 2;

            if(isNumeric(p0)) {
                var p1 = di[pLetter] + di.w / 2;
                var pVal = round(di.p);
                if(extents[pVal]) {
                    extents[pVal] = [Math.min(p0, extents[pVal][0]), Math.max(p1, extents[pVal][1])];
                } else {
                    extents[pVal] = [p0, p1];
                }
            }

            di.p0 = di.p + (poffsetIsArray ? poffset[j] : poffset);
            di.p1 = di.p0 + di.w;
            di.s0 = di.b;
            di.s1 = di.s0 + di.s;
        }
    }
}

function getAxisLetter(ax) {
    return ax._id.charAt(0);
}

module.exports = {
    crossTraceCalc: crossTraceCalc,
    setGroupPositions: setGroupPositions
};

},{"../../constants/numerical":674,"../../lib":697,"../../plots/cartesian/axes":745,"../../plots/cartesian/axis_ids":748,"../../registry":826,"./sieve.js":848,"fast-isnumeric":218}],840:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Color = _dereq_('../../components/color');
var Registry = _dereq_('../../registry');

var handleXYDefaults = _dereq_('../scatter/xy_defaults');
var handleStyleDefaults = _dereq_('../bar/style_defaults');
var getAxisGroup = _dereq_('../../plots/cartesian/axis_ids').getAxisGroup;
var attributes = _dereq_('./attributes');

function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var coerceFont = Lib.coerceFont;

    var len = handleXYDefaults(traceIn, traceOut, layout, coerce);
    if(!len) {
        traceOut.visible = false;
        return;
    }

    coerce('orientation', (traceOut.x && !traceOut.y) ? 'h' : 'v');
    coerce('base');
    coerce('offset');
    coerce('width');

    coerce('text');
    coerce('hovertext');
    coerce('hovertemplate');

    var textPosition = coerce('textposition');

    var hasBoth = Array.isArray(textPosition) || textPosition === 'auto';
    var hasInside = hasBoth || textPosition === 'inside';
    var hasOutside = hasBoth || textPosition === 'outside';

    if(hasInside || hasOutside) {
        var textFont = coerceFont(coerce, 'textfont', layout.font);

        // Note that coercing `insidetextfont` is always needed –
        // even if `textposition` is `outside` for each trace – since
        // an outside label can become an inside one, for example because
        // of a bar being stacked on top of it.
        var insideTextFontDefault = Lib.extendFlat({}, textFont);
        var isTraceTextfontColorSet = traceIn.textfont && traceIn.textfont.color;
        var isColorInheritedFromLayoutFont = !isTraceTextfontColorSet;
        if(isColorInheritedFromLayoutFont) {
            delete insideTextFontDefault.color;
        }
        coerceFont(coerce, 'insidetextfont', insideTextFontDefault);

        if(hasOutside) coerceFont(coerce, 'outsidetextfont', textFont);

        coerce('constraintext');
        coerce('selected.textfont.color');
        coerce('unselected.textfont.color');
        coerce('cliponaxis');
    }

    handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout);

    var lineColor = (traceOut.marker.line || {}).color;

    // override defaultColor for error bars with defaultLine
    var errorBarsSupplyDefaults = Registry.getComponentMethod('errorbars', 'supplyDefaults');
    errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color.defaultLine, {axis: 'y'});
    errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color.defaultLine, {axis: 'x', inherit: 'y'});

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
}

function handleGroupingDefaults(traceIn, traceOut, fullLayout, coerce) {
    var orientation = traceOut.orientation;
    // N.B. grouping is done across all trace trace types that support it
    var posAxId = traceOut[{v: 'x', h: 'y'}[orientation] + 'axis'];
    var groupId = getAxisGroup(fullLayout, posAxId) + orientation;

    var alignmentOpts = fullLayout._alignmentOpts || {};
    var alignmentgroup = coerce('alignmentgroup');

    var alignmentGroups = alignmentOpts[groupId];
    if(!alignmentGroups) alignmentGroups = alignmentOpts[groupId] = {};

    var alignmentGroupOpts = alignmentGroups[alignmentgroup];

    if(alignmentGroupOpts) {
        alignmentGroupOpts.traces.push(traceOut);
    } else {
        alignmentGroupOpts = alignmentGroups[alignmentgroup] = {
            traces: [traceOut],
            alignmentIndex: Object.keys(alignmentGroups).length,
            offsetGroups: {}
        };
    }

    var offsetgroup = coerce('offsetgroup');
    var offsetGroups = alignmentGroupOpts.offsetGroups;
    var offsetGroupOpts = offsetGroups[offsetgroup];

    if(offsetgroup) {
        if(!offsetGroupOpts) {
            offsetGroupOpts = offsetGroups[offsetgroup] = {
                offsetIndex: Object.keys(offsetGroups).length
            };
        }

        traceOut._offsetIndex = offsetGroupOpts.offsetIndex;
    }
}

function crossTraceDefaults(fullData, fullLayout) {
    var traceIn, traceOut;

    function coerce(attr) {
        return Lib.coerce(traceOut._input, traceOut, attributes, attr);
    }

    for(var i = 0; i < fullData.length; i++) {
        traceOut = fullData[i];

        if(traceOut.type === 'bar') {
            traceIn = traceOut._input;
            if(fullLayout.barmode === 'group') {
                handleGroupingDefaults(traceIn, traceOut, fullLayout, coerce);
            }
        }
    }
}

module.exports = {
    supplyDefaults: supplyDefaults,
    crossTraceDefaults: crossTraceDefaults,
    handleGroupingDefaults: handleGroupingDefaults
};

},{"../../components/color":574,"../../lib":697,"../../plots/cartesian/axis_ids":748,"../../registry":826,"../bar/style_defaults":850,"../scatter/xy_defaults":1074,"./attributes":836}],841:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var tinycolor = _dereq_('tinycolor2');

exports.coerceString = function(attributeDefinition, value, defaultValue) {
    if(typeof value === 'string') {
        if(value || !attributeDefinition.noBlank) return value;
    } else if(typeof value === 'number') {
        if(!attributeDefinition.strict) return String(value);
    }

    return (defaultValue !== undefined) ?
      defaultValue :
      attributeDefinition.dflt;
};

exports.coerceNumber = function(attributeDefinition, value, defaultValue) {
    if(isNumeric(value)) {
        value = +value;

        var min = attributeDefinition.min;
        var max = attributeDefinition.max;
        var isOutOfBounds = (min !== undefined && value < min) ||
              (max !== undefined && value > max);

        if(!isOutOfBounds) return value;
    }

    return (defaultValue !== undefined) ?
      defaultValue :
      attributeDefinition.dflt;
};

exports.coerceColor = function(attributeDefinition, value, defaultValue) {
    if(tinycolor(value).isValid()) return value;

    return (defaultValue !== undefined) ?
      defaultValue :
      attributeDefinition.dflt;
};

exports.coerceEnumerated = function(attributeDefinition, value, defaultValue) {
    if(attributeDefinition.coerceNumber) value = +value;

    if(attributeDefinition.values.indexOf(value) !== -1) return value;

    return (defaultValue !== undefined) ?
      defaultValue :
      attributeDefinition.dflt;
};

exports.getValue = function(arrayOrScalar, index) {
    var value;
    if(!Array.isArray(arrayOrScalar)) value = arrayOrScalar;
    else if(index < arrayOrScalar.length) value = arrayOrScalar[index];
    return value;
};

},{"fast-isnumeric":218,"tinycolor2":518}],842:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Fx = _dereq_('../../components/fx');
var Registry = _dereq_('../../registry');
var Color = _dereq_('../../components/color');
var fillHoverText = _dereq_('../scatter/fill_hover_text');

function hoverPoints(pointData, xval, yval, hovermode) {
    var cd = pointData.cd;
    var trace = cd[0].trace;
    var t = cd[0].t;
    var isClosest = (hovermode === 'closest');
    var maxHoverDistance = pointData.maxHoverDistance;
    var maxSpikeDistance = pointData.maxSpikeDistance;

    var posVal, sizeVal, posLetter, sizeLetter, dx, dy, pRangeCalc;

    function thisBarMinPos(di) { return di[posLetter] - di.w / 2; }
    function thisBarMaxPos(di) { return di[posLetter] + di.w / 2; }

    var minPos = isClosest ?
        thisBarMinPos :
        function(di) {
            /*
             * In compare mode, accept a bar if you're on it *or* its group.
             * Nearly always it's the group that matters, but in case the bar
             * was explicitly set wider than its group we'd better accept the
             * whole bar.
             *
             * use `bardelta` instead of `bargroupwidth` so we accept hover
             * in the gap. That way hover doesn't flash on and off as you
             * mouse over the plot in compare modes.
             * In 'closest' mode though the flashing seems inevitable,
             * without far more complex logic
             */
            return Math.min(thisBarMinPos(di), di.p - t.bardelta / 2);
        };

    var maxPos = isClosest ?
        thisBarMaxPos :
        function(di) {
            return Math.max(thisBarMaxPos(di), di.p + t.bardelta / 2);
        };

    function _positionFn(_minPos, _maxPos) {
        // add a little to the pseudo-distance for wider bars, so that like scatter,
        // if you are over two overlapping bars, the narrower one wins.
        return Fx.inbox(_minPos - posVal, _maxPos - posVal,
            maxHoverDistance + Math.min(1, Math.abs(_maxPos - _minPos) / pRangeCalc) - 1);
    }

    function positionFn(di) {
        return _positionFn(minPos(di), maxPos(di));
    }

    function thisBarPositionFn(di) {
        return _positionFn(thisBarMinPos(di), thisBarMaxPos(di));
    }

    function sizeFn(di) {
        // add a gradient so hovering near the end of a
        // bar makes it a little closer match
        return Fx.inbox(di.b - sizeVal, di[sizeLetter] - sizeVal,
            maxHoverDistance + (di[sizeLetter] - sizeVal) / (di[sizeLetter] - di.b) - 1);
    }

    if(trace.orientation === 'h') {
        posVal = yval;
        sizeVal = xval;
        posLetter = 'y';
        sizeLetter = 'x';
        dx = sizeFn;
        dy = positionFn;
    }
    else {
        posVal = xval;
        sizeVal = yval;
        posLetter = 'x';
        sizeLetter = 'y';
        dy = sizeFn;
        dx = positionFn;
    }

    var pa = pointData[posLetter + 'a'];
    var sa = pointData[sizeLetter + 'a'];

    pRangeCalc = Math.abs(pa.r2c(pa.range[1]) - pa.r2c(pa.range[0]));

    function dxy(di) { return (dx(di) + dy(di)) / 2; }
    var distfn = Fx.getDistanceFunction(hovermode, dx, dy, dxy);
    Fx.getClosest(cd, distfn, pointData);

    // skip the rest (for this trace) if we didn't find a close point
    if(pointData.index === false) return;

    // if we get here and we're not in 'closest' mode, push min/max pos back
    // onto the group - even though that means occasionally the mouse will be
    // over the hover label.
    if(!isClosest) {
        minPos = function(di) {
            return Math.min(thisBarMinPos(di), di.p - t.bargroupwidth / 2);
        };
        maxPos = function(di) {
            return Math.max(thisBarMaxPos(di), di.p + t.bargroupwidth / 2);
        };
    }

    // the closest data point
    var index = pointData.index;
    var di = cd[index];

    var size = (trace.base) ? di.b + di.s : di.s;
    pointData[sizeLetter + '0'] = pointData[sizeLetter + '1'] = sa.c2p(di[sizeLetter], true);
    pointData[sizeLetter + 'LabelVal'] = size;

    var extent = t.extents[t.extents.round(di.p)];
    pointData[posLetter + '0'] = pa.c2p(isClosest ? minPos(di) : extent[0], true);
    pointData[posLetter + '1'] = pa.c2p(isClosest ? maxPos(di) : extent[1], true);
    pointData[posLetter + 'LabelVal'] = di.p;

    // spikelines always want "closest" distance regardless of hovermode
    pointData.spikeDistance = (sizeFn(di) + thisBarPositionFn(di)) / 2 + maxSpikeDistance - maxHoverDistance;
    // they also want to point to the data value, regardless of where the label goes
    // in case of bars shifted within groups
    pointData[posLetter + 'Spike'] = pa.c2p(di.p, true);

    pointData.color = getTraceColor(trace, di);
    fillHoverText(di, trace, pointData);
    Registry.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData);

    pointData.hovertemplate = trace.hovertemplate;
    return [pointData];
}

function getTraceColor(trace, di) {
    var mc = di.mcc || trace.marker.color;
    var mlc = di.mlcc || trace.marker.line.color;
    var mlw = di.mlw || trace.marker.line.width;

    if(Color.opacity(mc)) return mc;
    else if(Color.opacity(mlc) && mlw) return mlc;
}

module.exports = {
    hoverPoints: hoverPoints,
    getTraceColor: getTraceColor
};

},{"../../components/color":574,"../../components/fx":613,"../../registry":826,"../scatter/fill_hover_text":1056}],843:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Bar = {};

Bar.attributes = _dereq_('./attributes');
Bar.layoutAttributes = _dereq_('./layout_attributes');
Bar.supplyDefaults = _dereq_('./defaults').supplyDefaults;
Bar.crossTraceDefaults = _dereq_('./defaults').crossTraceDefaults;
Bar.supplyLayoutDefaults = _dereq_('./layout_defaults');
Bar.calc = _dereq_('./calc');
Bar.crossTraceCalc = _dereq_('./cross_trace_calc').crossTraceCalc;
Bar.colorbar = _dereq_('../scatter/marker_colorbar');
Bar.arraysToCalcdata = _dereq_('./arrays_to_calcdata');
Bar.plot = _dereq_('./plot');
Bar.style = _dereq_('./style').style;
Bar.styleOnSelect = _dereq_('./style').styleOnSelect;
Bar.hoverPoints = _dereq_('./hover').hoverPoints;
Bar.selectPoints = _dereq_('./select');

Bar.moduleType = 'trace';
Bar.name = 'bar';
Bar.basePlotModule = _dereq_('../../plots/cartesian');
Bar.categories = ['cartesian', 'svg', 'bar', 'oriented', 'errorBarsOK', 'showLegend', 'zoomScale'];
Bar.meta = {
    
};

module.exports = Bar;

},{"../../plots/cartesian":756,"../scatter/marker_colorbar":1066,"./arrays_to_calcdata":835,"./attributes":836,"./calc":837,"./cross_trace_calc":839,"./defaults":840,"./hover":842,"./layout_attributes":844,"./layout_defaults":845,"./plot":846,"./select":847,"./style":849}],844:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    barmode: {
        valType: 'enumerated',
        values: ['stack', 'group', 'overlay', 'relative'],
        dflt: 'group',
        
        editType: 'calc',
        
    },
    barnorm: {
        valType: 'enumerated',
        values: ['', 'fraction', 'percent'],
        dflt: '',
        
        editType: 'calc',
        
    },
    bargap: {
        valType: 'number',
        min: 0,
        max: 1,
        
        editType: 'calc',
        
    },
    bargroupgap: {
        valType: 'number',
        min: 0,
        max: 1,
        dflt: 0,
        
        editType: 'calc',
        
    }
};

},{}],845:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');
var Axes = _dereq_('../../plots/cartesian/axes');
var Lib = _dereq_('../../lib');

var layoutAttributes = _dereq_('./layout_attributes');

module.exports = function(layoutIn, layoutOut, fullData) {
    function coerce(attr, dflt) {
        return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
    }

    var hasBars = false;
    var shouldBeGapless = false;
    var gappedAnyway = false;
    var usedSubplots = {};

    for(var i = 0; i < fullData.length; i++) {
        var trace = fullData[i];
        if(Registry.traceIs(trace, 'bar') && trace.visible) hasBars = true;
        else continue;

        // if we have at least 2 grouped bar traces on the same subplot,
        // we should default to a gap anyway, even if the data is histograms
        if(layoutIn.barmode !== 'overlay' && layoutIn.barmode !== 'stack') {
            var subploti = trace.xaxis + trace.yaxis;
            if(usedSubplots[subploti]) gappedAnyway = true;
            usedSubplots[subploti] = true;
        }

        if(trace.visible && trace.type === 'histogram') {
            var pa = Axes.getFromId({_fullLayout: layoutOut},
                        trace[trace.orientation === 'v' ? 'xaxis' : 'yaxis']);
            if(pa.type !== 'category') shouldBeGapless = true;
        }
    }

    if(!hasBars) return;

    var mode = coerce('barmode');
    if(mode !== 'overlay') coerce('barnorm');

    coerce('bargap', (shouldBeGapless && !gappedAnyway) ? 0 : 0.2);
    coerce('bargroupgap');
};

},{"../../lib":697,"../../plots/cartesian/axes":745,"../../registry":826,"./layout_attributes":844}],846:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');

var Color = _dereq_('../../components/color');
var Drawing = _dereq_('../../components/drawing');
var Registry = _dereq_('../../registry');

var attributes = _dereq_('./attributes');
var attributeText = attributes.text;
var attributeTextPosition = attributes.textposition;
var helpers = _dereq_('./helpers');
var style = _dereq_('./style');

// padding in pixels around text
var TEXTPAD = 3;

module.exports = function plot(gd, plotinfo, cdbar, barLayer) {
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;
    var fullLayout = gd._fullLayout;

    var bartraces = Lib.makeTraceGroups(barLayer, cdbar, 'trace bars').each(function(cd) {
        var plotGroup = d3.select(this);
        var cd0 = cd[0];
        var trace = cd0.trace;

        if(!plotinfo.isRangePlot) cd0.node3 = plotGroup;

        var pointGroup = Lib.ensureSingle(plotGroup, 'g', 'points');

        var bars = pointGroup.selectAll('g.point').data(Lib.identity);

        bars.enter().append('g')
            .classed('point', true);

        bars.exit().remove();

        bars.each(function(di, i) {
            var bar = d3.select(this);

            // now display the bar
            // clipped xf/yf (2nd arg true): non-positive
            // log values go off-screen by plotwidth
            // so you see them continue if you drag the plot
            var x0, x1, y0, y1;
            if(trace.orientation === 'h') {
                y0 = ya.c2p(di.p0, true);
                y1 = ya.c2p(di.p1, true);
                x0 = xa.c2p(di.s0, true);
                x1 = xa.c2p(di.s1, true);

                // for selections
                di.ct = [x1, (y0 + y1) / 2];
            }
            else {
                x0 = xa.c2p(di.p0, true);
                x1 = xa.c2p(di.p1, true);
                y0 = ya.c2p(di.s0, true);
                y1 = ya.c2p(di.s1, true);

                // for selections
                di.ct = [(x0 + x1) / 2, y1];
            }

            if(!isNumeric(x0) || !isNumeric(x1) ||
                    !isNumeric(y0) || !isNumeric(y1) ||
                    x0 === x1 || y0 === y1) {
                bar.remove();
                return;
            }

            var lw = (di.mlw + 1 || trace.marker.line.width + 1 ||
                    (di.trace ? di.trace.marker.line.width : 0) + 1) - 1;
            var offset = d3.round((lw / 2) % 1, 2);

            function roundWithLine(v) {
                // if there are explicit gaps, don't round,
                // it can make the gaps look crappy
                return (fullLayout.bargap === 0 && fullLayout.bargroupgap === 0) ?
                    d3.round(Math.round(v) - offset, 2) : v;
            }

            function expandToVisible(v, vc) {
                // if it's not in danger of disappearing entirely,
                // round more precisely
                return Math.abs(v - vc) >= 2 ? roundWithLine(v) :
                // but if it's very thin, expand it so it's
                // necessarily visible, even if it might overlap
                // its neighbor
                (v > vc ? Math.ceil(v) : Math.floor(v));
            }

            if(!gd._context.staticPlot) {
                // if bars are not fully opaque or they have a line
                // around them, round to integer pixels, mainly for
                // safari so we prevent overlaps from its expansive
                // pixelation. if the bars ARE fully opaque and have
                // no line, expand to a full pixel to make sure we
                // can see them
                var op = Color.opacity(di.mc || trace.marker.color);
                var fixpx = (op < 1 || lw > 0.01) ? roundWithLine : expandToVisible;
                x0 = fixpx(x0, x1);
                x1 = fixpx(x1, x0);
                y0 = fixpx(y0, y1);
                y1 = fixpx(y1, y0);
            }

            Lib.ensureSingle(bar, 'path')
                .style('vector-effect', 'non-scaling-stroke')
                .attr('d',
                    'M' + x0 + ',' + y0 + 'V' + y1 + 'H' + x1 + 'V' + y0 + 'Z')
                .call(Drawing.setClipUrl, plotinfo.layerClipId, gd);

            appendBarText(gd, bar, cd, i, x0, x1, y0, y1);

            if(plotinfo.layerClipId) {
                Drawing.hideOutsideRangePoint(di, bar.select('text'), xa, ya, trace.xcalendar, trace.ycalendar);
            }
        });

        // lastly, clip points groups of `cliponaxis !== false` traces
        // on `plotinfo._hasClipOnAxisFalse === true` subplots
        var hasClipOnAxisFalse = cd0.trace.cliponaxis === false;
        Drawing.setClipUrl(plotGroup, hasClipOnAxisFalse ? null : plotinfo.layerClipId, gd);
    });

    // error bars are on the top
    Registry.getComponentMethod('errorbars', 'plot')(gd, bartraces, plotinfo);
};

function appendBarText(gd, bar, calcTrace, i, x0, x1, y0, y1) {
    var textPosition;

    function appendTextNode(bar, text, textFont) {
        var textSelection = Lib.ensureSingle(bar, 'text')
            .text(text)
            .attr({
                'class': 'bartext bartext-' + textPosition,
                transform: '',
                'text-anchor': 'middle',
                // prohibit tex interpretation until we can handle
                // tex and regular text together
                'data-notex': 1
            })
            .call(Drawing.font, textFont)
            .call(svgTextUtils.convertToTspans, gd);

        return textSelection;
    }

    // get trace attributes
    var trace = calcTrace[0].trace;
    var orientation = trace.orientation;

    var text = getText(trace, i);
    textPosition = getTextPosition(trace, i);

    if(!text || textPosition === 'none') {
        bar.select('text').remove();
        return;
    }

    var layoutFont = gd._fullLayout.font;
    var barColor = style.getBarColor(calcTrace[i], trace);
    var insideTextFont = style.getInsideTextFont(trace, i, layoutFont, barColor);
    var outsideTextFont = style.getOutsideTextFont(trace, i, layoutFont);

    // compute text position
    var barmode = gd._fullLayout.barmode;
    var inStackMode = (barmode === 'stack');
    var inRelativeMode = (barmode === 'relative');
    var inStackOrRelativeMode = inStackMode || inRelativeMode;

    var calcBar = calcTrace[i];
    var isOutmostBar = !inStackOrRelativeMode || calcBar._outmost;

    var barWidth = Math.abs(x1 - x0) - 2 * TEXTPAD;  // padding excluded
    var barHeight = Math.abs(y1 - y0) - 2 * TEXTPAD;  // padding excluded

    var textSelection;
    var textBB;
    var textWidth;
    var textHeight;

    if(textPosition === 'outside') {
        if(!isOutmostBar && !calcBar.hasB) textPosition = 'inside';
    }

    if(textPosition === 'auto') {
        if(isOutmostBar) {
            // draw text using insideTextFont and check if it fits inside bar
            textPosition = 'inside';
            textSelection = appendTextNode(bar, text, insideTextFont);

            textBB = Drawing.bBox(textSelection.node()),
            textWidth = textBB.width,
            textHeight = textBB.height;

            var textHasSize = (textWidth > 0 && textHeight > 0);
            var fitsInside = (textWidth <= barWidth && textHeight <= barHeight);
            var fitsInsideIfRotated = (textWidth <= barHeight && textHeight <= barWidth);
            var fitsInsideIfShrunk = (orientation === 'h') ?
                (barWidth >= textWidth * (barHeight / textHeight)) :
                (barHeight >= textHeight * (barWidth / textWidth));

            if(textHasSize &&
                    (fitsInside || fitsInsideIfRotated || fitsInsideIfShrunk)) {
                textPosition = 'inside';
            }
            else {
                textPosition = 'outside';
                textSelection.remove();
                textSelection = null;
            }
        }
        else textPosition = 'inside';
    }

    if(!textSelection) {
        textSelection = appendTextNode(bar, text,
                (textPosition === 'outside') ?
                outsideTextFont : insideTextFont);

        textBB = Drawing.bBox(textSelection.node()),
        textWidth = textBB.width,
        textHeight = textBB.height;

        if(textWidth <= 0 || textHeight <= 0) {
            textSelection.remove();
            return;
        }
    }

    // compute text transform
    var transform, constrained;
    if(textPosition === 'outside') {
        constrained = trace.constraintext === 'both' || trace.constraintext === 'outside';
        transform = getTransformToMoveOutsideBar(x0, x1, y0, y1, textBB,
            orientation, constrained);
    }
    else {
        constrained = trace.constraintext === 'both' || trace.constraintext === 'inside';
        transform = getTransformToMoveInsideBar(x0, x1, y0, y1, textBB,
            orientation, constrained);
    }

    textSelection.attr('transform', transform);
}

function getTransformToMoveInsideBar(x0, x1, y0, y1, textBB, orientation, constrained) {
    // compute text and target positions
    var textWidth = textBB.width;
    var textHeight = textBB.height;
    var textX = (textBB.left + textBB.right) / 2;
    var textY = (textBB.top + textBB.bottom) / 2;
    var barWidth = Math.abs(x1 - x0);
    var barHeight = Math.abs(y1 - y0);
    var targetWidth;
    var targetHeight;
    var targetX;
    var targetY;

    // apply text padding
    var textpad;
    if(barWidth > (2 * TEXTPAD) && barHeight > (2 * TEXTPAD)) {
        textpad = TEXTPAD;
        barWidth -= 2 * textpad;
        barHeight -= 2 * textpad;
    }
    else textpad = 0;

    // compute rotation and scale
    var rotate,
        scale;

    if(textWidth <= barWidth && textHeight <= barHeight) {
        // no scale or rotation is required
        rotate = false;
        scale = 1;
    }
    else if(textWidth <= barHeight && textHeight <= barWidth) {
        // only rotation is required
        rotate = true;
        scale = 1;
    }
    else if((textWidth < textHeight) === (barWidth < barHeight)) {
        // only scale is required
        rotate = false;
        scale = constrained ? Math.min(barWidth / textWidth, barHeight / textHeight) : 1;
    }
    else {
        // both scale and rotation are required
        rotate = true;
        scale = constrained ? Math.min(barHeight / textWidth, barWidth / textHeight) : 1;
    }

    if(rotate) rotate = 90;  // rotate clockwise

    // compute text and target positions
    if(rotate) {
        targetWidth = scale * textHeight;
        targetHeight = scale * textWidth;
    }
    else {
        targetWidth = scale * textWidth;
        targetHeight = scale * textHeight;
    }

    if(orientation === 'h') {
        if(x1 < x0) {
            // bar end is on the left hand side
            targetX = x1 + textpad + targetWidth / 2;
            targetY = (y0 + y1) / 2;
        }
        else {
            targetX = x1 - textpad - targetWidth / 2;
            targetY = (y0 + y1) / 2;
        }
    }
    else {
        if(y1 > y0) {
            // bar end is on the bottom
            targetX = (x0 + x1) / 2;
            targetY = y1 - textpad - targetHeight / 2;
        }
        else {
            targetX = (x0 + x1) / 2;
            targetY = y1 + textpad + targetHeight / 2;
        }
    }

    return getTransform(textX, textY, targetX, targetY, scale, rotate);
}

function getTransformToMoveOutsideBar(x0, x1, y0, y1, textBB, orientation, constrained) {
    var barWidth = (orientation === 'h') ?
        Math.abs(y1 - y0) :
        Math.abs(x1 - x0);
    var textpad;

    // Keep the padding so the text doesn't sit right against
    // the bars, but don't factor it into barWidth
    if(barWidth > 2 * TEXTPAD) {
        textpad = TEXTPAD;
    }

    // compute rotation and scale
    var scale = 1;
    if(constrained) {
        scale = (orientation === 'h') ?
            Math.min(1, barWidth / textBB.height) :
            Math.min(1, barWidth / textBB.width);
    }

    // compute text and target positions
    var textX = (textBB.left + textBB.right) / 2;
    var textY = (textBB.top + textBB.bottom) / 2;
    var targetWidth;
    var targetHeight;
    var targetX;
    var targetY;

    targetWidth = scale * textBB.width;
    targetHeight = scale * textBB.height;

    if(orientation === 'h') {
        if(x1 < x0) {
            // bar end is on the left hand side
            targetX = x1 - textpad - targetWidth / 2;
            targetY = (y0 + y1) / 2;
        }
        else {
            targetX = x1 + textpad + targetWidth / 2;
            targetY = (y0 + y1) / 2;
        }
    }
    else {
        if(y1 > y0) {
            // bar end is on the bottom
            targetX = (x0 + x1) / 2;
            targetY = y1 + textpad + targetHeight / 2;
        }
        else {
            targetX = (x0 + x1) / 2;
            targetY = y1 - textpad - targetHeight / 2;
        }
    }

    return getTransform(textX, textY, targetX, targetY, scale, false);
}

function getTransform(textX, textY, targetX, targetY, scale, rotate) {
    var transformScale;
    var transformRotate;
    var transformTranslate;

    if(scale < 1) transformScale = 'scale(' + scale + ') ';
    else {
        scale = 1;
        transformScale = '';
    }

    transformRotate = (rotate) ?
        'rotate(' + rotate + ' ' + textX + ' ' + textY + ') ' : '';

    // Note that scaling also affects the center of the text box
    var translateX = (targetX - scale * textX);
    var translateY = (targetY - scale * textY);
    transformTranslate = 'translate(' + translateX + ' ' + translateY + ')';

    return transformTranslate + transformScale + transformRotate;
}

function getText(trace, index) {
    var value = helpers.getValue(trace.text, index);
    return helpers.coerceString(attributeText, value);
}

function getTextPosition(trace, index) {
    var value = helpers.getValue(trace.textposition, index);
    return helpers.coerceEnumerated(attributeTextPosition, value);
}

},{"../../components/color":574,"../../components/drawing":595,"../../lib":697,"../../lib/svg_text_utils":721,"../../registry":826,"./attributes":836,"./helpers":841,"./style":849,"d3":151,"fast-isnumeric":218}],847:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function selectPoints(searchInfo, selectionTester) {
    var cd = searchInfo.cd;
    var xa = searchInfo.xaxis;
    var ya = searchInfo.yaxis;
    var selection = [];
    var i;

    if(selectionTester === false) {
        // clear selection
        for(i = 0; i < cd.length; i++) {
            cd[i].selected = 0;
        }
    } else {
        for(i = 0; i < cd.length; i++) {
            var di = cd[i];

            if(selectionTester.contains(di.ct, false, i, searchInfo)) {
                selection.push({
                    pointNumber: i,
                    x: xa.c2d(di.x),
                    y: ya.c2d(di.y)
                });
                di.selected = 1;
            } else {
                di.selected = 0;
            }
        }
    }

    return selection;
};

},{}],848:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = Sieve;

var Lib = _dereq_('../../lib');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

/**
 * Helper class to sieve data from traces into bins
 *
 * @class
 * @param {Array}   traces
 *                  Array of calculated traces
 * @param {boolean} [separateNegativeValues]
 *                  If true, then split data at the same position into a bar
 *                  for positive values and another for negative values
 * @param {boolean} [dontMergeOverlappingData]
 *                  If true, then don't merge overlapping bars into a single bar
 */
function Sieve(traces, separateNegativeValues, dontMergeOverlappingData) {
    this.traces = traces;
    this.separateNegativeValues = separateNegativeValues;
    this.dontMergeOverlappingData = dontMergeOverlappingData;

    // for single-bin histograms - see histogram/calc
    var width1 = Infinity;

    var positions = [];
    for(var i = 0; i < traces.length; i++) {
        var trace = traces[i];
        for(var j = 0; j < trace.length; j++) {
            var bar = trace[j];
            if(bar.p !== BADNUM) positions.push(bar.p);
        }
        if(trace[0] && trace[0].width1) {
            width1 = Math.min(trace[0].width1, width1);
        }
    }
    this.positions = positions;

    var dv = Lib.distinctVals(positions);
    this.distinctPositions = dv.vals;
    if(dv.vals.length === 1 && width1 !== Infinity) this.minDiff = width1;
    else this.minDiff = Math.min(dv.minDiff, width1);

    this.binWidth = this.minDiff;

    this.bins = {};
}

/**
 * Sieve datum
 *
 * @method
 * @param {number} position
 * @param {number} value
 * @returns {number} Previous bin value
 */
Sieve.prototype.put = function put(position, value) {
    var label = this.getLabel(position, value);
    var oldValue = this.bins[label] || 0;

    this.bins[label] = oldValue + value;

    return oldValue;
};

/**
 * Get current bin value for a given datum
 *
 * @method
 * @param {number} position  Position of datum
 * @param {number} [value]   Value of datum
 *                           (required if this.separateNegativeValues is true)
 * @returns {number} Current bin value
 */
Sieve.prototype.get = function put(position, value) {
    var label = this.getLabel(position, value);
    return this.bins[label] || 0;
};

/**
 * Get bin label for a given datum
 *
 * @method
 * @param {number} position  Position of datum
 * @param {number} [value]   Value of datum
 *                           (required if this.separateNegativeValues is true)
 * @returns {string} Bin label
 * (prefixed with a 'v' if value is negative and this.separateNegativeValues is
 * true; otherwise prefixed with '^')
 */
Sieve.prototype.getLabel = function getLabel(position, value) {
    var prefix = (value < 0 && this.separateNegativeValues) ? 'v' : '^';
    var label = (this.dontMergeOverlappingData) ?
        position :
        Math.round(position / this.binWidth);
    return prefix + label;
};

},{"../../constants/numerical":674,"../../lib":697}],849:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var Color = _dereq_('../../components/color');
var Drawing = _dereq_('../../components/drawing');
var Lib = _dereq_('../../lib');
var Registry = _dereq_('../../registry');

var attributes = _dereq_('./attributes');
var attributeTextFont = attributes.textfont;
var attributeInsideTextFont = attributes.insidetextfont;
var attributeOutsideTextFont = attributes.outsidetextfont;
var helpers = _dereq_('./helpers');

function style(gd, cd) {
    var s = cd ? cd[0].node3 : d3.select(gd).selectAll('g.trace.bars');
    var barcount = s.size();
    var fullLayout = gd._fullLayout;

    // trace styling
    s.style('opacity', function(d) { return d[0].trace.opacity; })

    // for gapless (either stacked or neighboring grouped) bars use
    // crispEdges to turn off antialiasing so an artificial gap
    // isn't introduced.
    .each(function(d) {
        if((fullLayout.barmode === 'stack' && barcount > 1) ||
                (fullLayout.bargap === 0 &&
                 fullLayout.bargroupgap === 0 &&
                 !d[0].trace.marker.line.width)) {
            d3.select(this).attr('shape-rendering', 'crispEdges');
        }
    });

    s.selectAll('g.points').each(function(d) {
        var sel = d3.select(this);
        var trace = d[0].trace;
        stylePoints(sel, trace, gd);
    });

    Registry.getComponentMethod('errorbars', 'style')(s);
}

function stylePoints(sel, trace, gd) {
    var pts = sel.selectAll('path');
    var txs = sel.selectAll('text');

    Drawing.pointStyle(pts, trace, gd);

    txs.each(function(d) {
        var tx = d3.select(this);
        var font = determineFont(tx, d, trace, gd);
        Drawing.font(tx, font);
    });
}

function styleOnSelect(gd, cd) {
    var s = cd[0].node3;
    var trace = cd[0].trace;

    if(trace.selectedpoints) {
        stylePointsInSelectionMode(s, trace, gd);
    } else {
        stylePoints(s, trace, gd);
    }
}

function stylePointsInSelectionMode(s, trace, gd) {
    Drawing.selectedPointStyle(s.selectAll('path'), trace);
    styleTextInSelectionMode(s.selectAll('text'), trace, gd);
}

function styleTextInSelectionMode(txs, trace, gd) {
    txs.each(function(d) {
        var tx = d3.select(this);
        var font;

        if(d.selected) {
            font = Lib.extendFlat({}, determineFont(tx, d, trace, gd));

            var selectedFontColor = trace.selected.textfont && trace.selected.textfont.color;
            if(selectedFontColor) {
                font.color = selectedFontColor;
            }

            Drawing.font(tx, font);
        } else {
            Drawing.selectedTextStyle(tx, trace);
        }
    });
}

function determineFont(tx, d, trace, gd) {
    var layoutFont = gd._fullLayout.font;
    var textFont = trace.textfont;

    if(tx.classed('bartext-inside')) {
        var barColor = getBarColor(d, trace);
        textFont = getInsideTextFont(trace, d.i, layoutFont, barColor);
    } else if(tx.classed('bartext-outside')) {
        textFont = getOutsideTextFont(trace, d.i, layoutFont);
    }

    return textFont;
}

function getTextFont(trace, index, defaultValue) {
    return getFontValue(
      attributeTextFont, trace.textfont, index, defaultValue);
}

function getInsideTextFont(trace, index, layoutFont, barColor) {
    var defaultFont = getTextFont(trace, index, layoutFont);

    var wouldFallBackToLayoutFont =
      (trace._input.textfont === undefined || trace._input.textfont.color === undefined) ||
      (Array.isArray(trace.textfont.color) && trace.textfont.color[index] === undefined);
    if(wouldFallBackToLayoutFont) {
        defaultFont = {
            color: Color.contrast(barColor),
            family: defaultFont.family,
            size: defaultFont.size
        };
    }

    return getFontValue(
      attributeInsideTextFont, trace.insidetextfont, index, defaultFont);
}

function getOutsideTextFont(trace, index, layoutFont) {
    var defaultFont = getTextFont(trace, index, layoutFont);
    return getFontValue(
      attributeOutsideTextFont, trace.outsidetextfont, index, defaultFont);
}

function getFontValue(attributeDefinition, attributeValue, index, defaultValue) {
    attributeValue = attributeValue || {};

    var familyValue = helpers.getValue(attributeValue.family, index);
    var sizeValue = helpers.getValue(attributeValue.size, index);
    var colorValue = helpers.getValue(attributeValue.color, index);

    return {
        family: helpers.coerceString(
          attributeDefinition.family, familyValue, defaultValue.family),
        size: helpers.coerceNumber(
          attributeDefinition.size, sizeValue, defaultValue.size),
        color: helpers.coerceColor(
          attributeDefinition.color, colorValue, defaultValue.color)
    };
}

function getBarColor(cd, trace) {
    return cd.mc || trace.marker.color;
}

module.exports = {
    style: style,
    styleOnSelect: styleOnSelect,
    getInsideTextFont: getInsideTextFont,
    getOutsideTextFont: getOutsideTextFont,
    getBarColor: getBarColor
};

},{"../../components/color":574,"../../components/drawing":595,"../../lib":697,"../../registry":826,"./attributes":836,"./helpers":841,"d3":151}],850:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Color = _dereq_('../../components/color');
var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');

module.exports = function handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout) {
    coerce('marker.color', defaultColor);

    if(hasColorscale(traceIn, 'marker')) {
        colorscaleDefaults(
            traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'}
        );
    }

    coerce('marker.line.color', Color.defaultLine);

    if(hasColorscale(traceIn, 'marker.line')) {
        colorscaleDefaults(
            traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'}
        );
    }

    coerce('marker.line.width');
    coerce('marker.opacity');
    coerce('selected.marker.color');
    coerce('unselected.marker.color');
};

},{"../../components/color":574,"../../components/colorscale/defaults":584,"../../components/colorscale/helpers":585}],851:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var extendFlat = _dereq_('../../lib/extend').extendFlat;
var scatterPolarAttrs = _dereq_('../scatterpolar/attributes');
var barAttrs = _dereq_('../bar/attributes');

module.exports = {
    r: scatterPolarAttrs.r,
    theta: scatterPolarAttrs.theta,
    r0: scatterPolarAttrs.r0,
    dr: scatterPolarAttrs.dr,
    theta0: scatterPolarAttrs.theta0,
    dtheta: scatterPolarAttrs.dtheta,
    thetaunit: scatterPolarAttrs.thetaunit,

    // orientation: {
    //     valType: 'enumerated',
    //     
    //     values: ['radial', 'angular'],
    //     editType: 'calc+clearAxisTypes',
    //     
    // },

    base: extendFlat({}, barAttrs.base, {
        
    }),
    offset: extendFlat({}, barAttrs.offset, {
        
    }),
    width: extendFlat({}, barAttrs.width, {
        
    }),

    text: extendFlat({}, barAttrs.text, {
        
    }),
    hovertext: extendFlat({}, barAttrs.hovertext, {
        
    }),

    // textposition: {},
    // textfont: {},
    // insidetextfont: {},
    // outsidetextfont: {},
    // constraintext: {},
    // cliponaxis: extendFlat({}, barAttrs.cliponaxis, {dflt: false}),

    marker: barAttrs.marker,

    hoverinfo: scatterPolarAttrs.hoverinfo,
    hovertemplate: hovertemplateAttrs(),

    selected: barAttrs.selected,
    unselected: barAttrs.unselected

    // error_x (error_r, error_theta)
    // error_y
};

},{"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../bar/attributes":836,"../scatterpolar/attributes":1110}],852:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
var colorscaleCalc = _dereq_('../../components/colorscale/calc');
var arraysToCalcdata = _dereq_('../bar/arrays_to_calcdata');
var setGroupPositions = _dereq_('../bar/cross_trace_calc').setGroupPositions;
var calcSelection = _dereq_('../scatter/calc_selection');
var traceIs = _dereq_('../../registry').traceIs;
var extendFlat = _dereq_('../../lib').extendFlat;

function calc(gd, trace) {
    var fullLayout = gd._fullLayout;
    var subplotId = trace.subplot;
    var radialAxis = fullLayout[subplotId].radialaxis;
    var angularAxis = fullLayout[subplotId].angularaxis;
    var rArray = radialAxis.makeCalcdata(trace, 'r');
    var thetaArray = angularAxis.makeCalcdata(trace, 'theta');
    var len = trace._length;
    var cd = new Array(len);

    // 'size' axis variables
    var sArray = rArray;
    // 'pos' axis variables
    var pArray = thetaArray;

    for(var i = 0; i < len; i++) {
        cd[i] = {p: pArray[i], s: sArray[i]};
    }

    // convert width and offset in 'c' coordinate,
    // set 'c' value(s) in trace._width and trace._offset,
    // to make Bar.crossTraceCalc "just work"
    function d2c(attr) {
        var val = trace[attr];
        if(val !== undefined) {
            trace['_' + attr] = Array.isArray(val) ?
                angularAxis.makeCalcdata(trace, attr) :
                angularAxis.d2c(val, trace.thetaunit);
        }
    }

    if(angularAxis.type === 'linear') {
        d2c('width');
        d2c('offset');
    }

    if(hasColorscale(trace, 'marker')) {
        colorscaleCalc(gd, trace, {
            vals: trace.marker.color,
            containerStr: 'marker',
            cLetter: 'c'
        });
    }
    if(hasColorscale(trace, 'marker.line')) {
        colorscaleCalc(gd, trace, {
            vals: trace.marker.line.color,
            containerStr: 'marker.line',
            cLetter: 'c'
        });
    }

    arraysToCalcdata(cd, trace);
    calcSelection(cd, trace);

    return cd;
}

function crossTraceCalc(gd, polarLayout, subplotId) {
    var calcdata = gd.calcdata;
    var barPolarCd = [];

    for(var i = 0; i < calcdata.length; i++) {
        var cdi = calcdata[i];
        var trace = cdi[0].trace;

        if(trace.visible === true && traceIs(trace, 'bar') &&
            trace.subplot === subplotId
        ) {
            barPolarCd.push(cdi);
        }
    }

    // to make _extremes is filled in correctly so that
    // polar._subplot.radialAxis can get auotrange'd
    // TODO clean up!
    // I think we want to call getAutorange on polar.radialaxis
    // NOT on polar._subplot.radialAxis
    var rAxis = extendFlat({}, polarLayout.radialaxis, {_id: 'x'});
    var aAxis = polarLayout.angularaxis;

    // 'bargap', 'barmode' are in _fullLayout.polar
    // TODO clean up setGroupPositions API instead
    var mockGd = {_fullLayout: polarLayout};

    setGroupPositions(mockGd, aAxis, rAxis, barPolarCd);
}

module.exports = {
    calc: calc,
    crossTraceCalc: crossTraceCalc
};

},{"../../components/colorscale/calc":582,"../../components/colorscale/helpers":585,"../../lib":697,"../../registry":826,"../bar/arrays_to_calcdata":835,"../bar/cross_trace_calc":839,"../scatter/calc_selection":1050}],853:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

var handleRThetaDefaults = _dereq_('../scatterpolar/defaults').handleRThetaDefaults;
var handleStyleDefaults = _dereq_('../bar/style_defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var len = handleRThetaDefaults(traceIn, traceOut, layout, coerce);
    if(!len) {
        traceOut.visible = false;
        return;
    }

    // coerce('orientation', (traceOut.theta && !traceOut.r) ? 'angular' : 'radial');

    coerce('thetaunit');
    coerce('base');
    coerce('offset');
    coerce('width');

    coerce('text');
    coerce('hovertext');
    coerce('hovertemplate');

    // var textPosition = coerce('textposition');
    // var hasBoth = Array.isArray(textPosition) || textPosition === 'auto';
    // var hasInside = hasBoth || textPosition === 'inside';
    // var hasOutside = hasBoth || textPosition === 'outside';

    // if(hasInside || hasOutside) {
    //     var textFont = coerceFont(coerce, 'textfont', layout.font);
    //     if(hasInside) coerceFont(coerce, 'insidetextfont', textFont);
    //     if(hasOutside) coerceFont(coerce, 'outsidetextfont', textFont);
    //     coerce('constraintext');
    //     coerce('selected.textfont.color');
    //     coerce('unselected.textfont.color');
    //     coerce('cliponaxis');
    // }

    handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout);

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};

},{"../../lib":697,"../bar/style_defaults":850,"../scatterpolar/defaults":1112,"./attributes":851}],854:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Fx = _dereq_('../../components/fx');
var Lib = _dereq_('../../lib');
var getTraceColor = _dereq_('../bar/hover').getTraceColor;
var fillHoverText = _dereq_('../scatter/fill_hover_text');
var makeHoverPointText = _dereq_('../scatterpolar/hover').makeHoverPointText;
var isPtInsidePolygon = _dereq_('../../plots/polar/helpers').isPtInsidePolygon;

module.exports = function hoverPoints(pointData, xval, yval) {
    var cd = pointData.cd;
    var trace = cd[0].trace;

    var subplot = pointData.subplot;
    var radialAxis = subplot.radialAxis;
    var angularAxis = subplot.angularAxis;
    var vangles = subplot.vangles;
    var inboxFn = vangles ? isPtInsidePolygon : Lib.isPtInsideSector;
    var maxHoverDistance = pointData.maxHoverDistance;
    var period = angularAxis._period || 2 * Math.PI;

    var rVal = Math.abs(radialAxis.g2p(Math.sqrt(xval * xval + yval * yval)));
    var thetaVal = Math.atan2(yval, xval);

    // polar.(x|y)axis.p2c doesn't get the reversed radial axis range case right
    if(radialAxis.range[0] > radialAxis.range[1]) {
        thetaVal += Math.PI;
    }

    var distFn = function(di) {
        if(inboxFn(rVal, thetaVal, [di.rp0, di.rp1], [di.thetag0, di.thetag1], vangles)) {
            return maxHoverDistance +
                // add a little to the pseudo-distance for wider bars, so that like scatter,
                // if you are over two overlapping bars, the narrower one wins.
                Math.min(1, Math.abs(di.thetag1 - di.thetag0) / period) - 1 +
                // add a gradient so hovering near the end of a
                // bar makes it a little closer match
                (di.rp1 - rVal) / (di.rp1 - di.rp0) - 1;
        } else {
            return Infinity;
        }
    };

    Fx.getClosest(cd, distFn, pointData);
    if(pointData.index === false) return;

    var index = pointData.index;
    var cdi = cd[index];

    pointData.x0 = pointData.x1 = cdi.ct[0];
    pointData.y0 = pointData.y1 = cdi.ct[1];

    var _cdi = Lib.extendFlat({}, cdi, {r: cdi.s, theta: cdi.p});
    fillHoverText(cdi, trace, pointData);
    makeHoverPointText(_cdi, trace, subplot, pointData);
    pointData.hovertemplate = trace.hovertemplate;
    pointData.color = getTraceColor(trace, cdi);
    pointData.xLabelVal = pointData.yLabelVal = undefined;

    if(cdi.s < 0) {
        pointData.idealAlign = 'left';
    }

    return [pointData];
};

},{"../../components/fx":613,"../../lib":697,"../../plots/polar/helpers":809,"../bar/hover":842,"../scatter/fill_hover_text":1056,"../scatterpolar/hover":1113}],855:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'trace',
    name: 'barpolar',
    basePlotModule: _dereq_('../../plots/polar'),
    categories: ['polar', 'bar', 'showLegend'],

    attributes: _dereq_('./attributes'),
    layoutAttributes: _dereq_('./layout_attributes'),
    supplyDefaults: _dereq_('./defaults'),
    supplyLayoutDefaults: _dereq_('./layout_defaults'),

    calc: _dereq_('./calc').calc,
    crossTraceCalc: _dereq_('./calc').crossTraceCalc,

    plot: _dereq_('./plot'),
    colorbar: _dereq_('../scatter/marker_colorbar'),
    style: _dereq_('../bar/style').style,

    hoverPoints: _dereq_('./hover'),
    selectPoints: _dereq_('../bar/select'),

    meta: {
        
        
    }
};

},{"../../plots/polar":810,"../bar/select":847,"../bar/style":849,"../scatter/marker_colorbar":1066,"./attributes":851,"./calc":852,"./defaults":853,"./hover":854,"./layout_attributes":856,"./layout_defaults":857,"./plot":858}],856:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    barmode: {
        valType: 'enumerated',
        values: ['stack', 'overlay'],
        dflt: 'stack',
        
        editType: 'calc',
        
    },
    bargap: {
        valType: 'number',
        dflt: 0.1,
        min: 0,
        max: 1,
        
        editType: 'calc',
        
    }
};

},{}],857:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var attrs = _dereq_('./layout_attributes');

module.exports = function(layoutIn, layoutOut, fullData) {
    var subplotsDone = {};
    var sp;

    function coerce(attr, dflt) {
        return Lib.coerce(layoutIn[sp] || {}, layoutOut[sp], attrs, attr, dflt);
    }

    for(var i = 0; i < fullData.length; i++) {
        var trace = fullData[i];
        if(trace.type === 'barpolar' && trace.visible === true) {
            sp = trace.subplot;
            if(!subplotsDone[sp]) {
                coerce('barmode');
                coerce('bargap');
                subplotsDone[sp] = 1;
            }
        }
    }
};

},{"../../lib":697,"./layout_attributes":856}],858:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');
var Drawing = _dereq_('../../components/drawing');
var helpers = _dereq_('../../plots/polar/helpers');

module.exports = function plot(gd, subplot, cdbar) {
    var xa = subplot.xaxis;
    var ya = subplot.yaxis;
    var radialAxis = subplot.radialAxis;
    var angularAxis = subplot.angularAxis;
    var pathFn = makePathFn(subplot);
    var barLayer = subplot.layers.frontplot.select('g.barlayer');

    Lib.makeTraceGroups(barLayer, cdbar, 'trace bars').each(function(cd) {
        var plotGroup = cd[0].node3 = d3.select(this);
        var pointGroup = Lib.ensureSingle(plotGroup, 'g', 'points');
        var bars = pointGroup.selectAll('g.point').data(Lib.identity);

        bars.enter().append('g')
            .style('vector-effect', 'non-scaling-stroke')
            .style('stroke-miterlimit', 2)
            .classed('point', true);

        bars.exit().remove();

        bars.each(function(di) {
            var bar = d3.select(this);

            var rp0 = di.rp0 = radialAxis.c2p(di.s0);
            var rp1 = di.rp1 = radialAxis.c2p(di.s1);
            var thetag0 = di.thetag0 = angularAxis.c2g(di.p0);
            var thetag1 = di.thetag1 = angularAxis.c2g(di.p1);

            var dPath;

            if(!isNumeric(rp0) || !isNumeric(rp1) ||
                !isNumeric(thetag0) || !isNumeric(thetag1) ||
                rp0 === rp1 || thetag0 === thetag1
            ) {
                // do not remove blank bars, to keep data-to-node
                // mapping intact during radial drag, that we
                // can skip calling _module.style during interactions
                dPath = 'M0,0Z';
            } else {
                // this 'center' pt is used for selections and hover labels
                var rg1 = radialAxis.c2g(di.s1);
                var thetagMid = (thetag0 + thetag1) / 2;
                di.ct = [
                    xa.c2p(rg1 * Math.cos(thetagMid)),
                    ya.c2p(rg1 * Math.sin(thetagMid))
                ];

                dPath = pathFn(rp0, rp1, thetag0, thetag1);
            }

            Lib.ensureSingle(bar, 'path').attr('d', dPath);
        });

        // clip plotGroup, when trace layer isn't clipped
        Drawing.setClipUrl(
            plotGroup,
            subplot._hasClipOnAxisFalse ? subplot.clipIds.forTraces : null,
            gd
        );
    });
};

function makePathFn(subplot) {
    var cxx = subplot.cxx;
    var cyy = subplot.cyy;

    if(subplot.vangles) {
        return function(r0, r1, _a0, _a1) {
            var a0, a1;

            if(Lib.angleDelta(_a0, _a1) > 0) {
                a0 = _a0;
                a1 = _a1;
            } else {
                a0 = _a1;
                a1 = _a0;
            }

            var va0 = helpers.findEnclosingVertexAngles(a0, subplot.vangles)[0];
            var va1 = helpers.findEnclosingVertexAngles(a1, subplot.vangles)[1];
            var vaBar = [va0, (a0 + a1) / 2, va1];
            return helpers.pathPolygonAnnulus(r0, r1, a0, a1, vaBar, cxx, cyy);
        };
    }

    return function(r0, r1, a0, a1) {
        return Lib.pathAnnulus(r0, r1, a0, a1, cxx, cyy);
    };
}

},{"../../components/drawing":595,"../../lib":697,"../../plots/polar/helpers":809,"d3":151,"fast-isnumeric":218}],859:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterAttrs = _dereq_('../scatter/attributes');
var barAttrs = _dereq_('../bar/attributes');
var colorAttrs = _dereq_('../../components/color/attributes');
var extendFlat = _dereq_('../../lib/extend').extendFlat;

var scatterMarkerAttrs = scatterAttrs.marker;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;

module.exports = {
    y: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },
    x: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },
    x0: {
        valType: 'any',
        
        editType: 'calc+clearAxisTypes',
        
    },
    y0: {
        valType: 'any',
        
        editType: 'calc+clearAxisTypes',
        
    },
    name: {
        valType: 'string',
        
        editType: 'calc+clearAxisTypes',
        
    },
    text: extendFlat({}, scatterAttrs.text, {
        
    }),
    hovertext: extendFlat({}, scatterAttrs.hovertext, {
        
    }),
    whiskerwidth: {
        valType: 'number',
        min: 0,
        max: 1,
        dflt: 0.5,
        
        editType: 'calc',
        
    },
    notched: {
        valType: 'boolean',
        
        editType: 'calc',
        
    },
    notchwidth: {
        valType: 'number',
        min: 0,
        max: 0.5,
        dflt: 0.25,
        
        editType: 'calc',
        
    },
    boxpoints: {
        valType: 'enumerated',
        values: ['all', 'outliers', 'suspectedoutliers', false],
        dflt: 'outliers',
        
        editType: 'calc',
        
    },
    boxmean: {
        valType: 'enumerated',
        values: [true, 'sd', false],
        dflt: false,
        
        editType: 'calc',
        
    },
    jitter: {
        valType: 'number',
        min: 0,
        max: 1,
        
        editType: 'calc',
        
    },
    pointpos: {
        valType: 'number',
        min: -2,
        max: 2,
        
        editType: 'calc',
        
    },
    orientation: {
        valType: 'enumerated',
        values: ['v', 'h'],
        
        editType: 'calc+clearAxisTypes',
        
    },

    width: {
        valType: 'number',
        min: 0,
        
        dflt: 0,
        editType: 'calc',
        
    },

    marker: {
        outliercolor: {
            valType: 'color',
            dflt: 'rgba(0, 0, 0, 0)',
            
            editType: 'style',
            
        },
        symbol: extendFlat({}, scatterMarkerAttrs.symbol,
            {arrayOk: false, editType: 'plot'}),
        opacity: extendFlat({}, scatterMarkerAttrs.opacity,
            {arrayOk: false, dflt: 1, editType: 'style'}),
        size: extendFlat({}, scatterMarkerAttrs.size,
            {arrayOk: false, editType: 'calc'}),
        color: extendFlat({}, scatterMarkerAttrs.color,
            {arrayOk: false, editType: 'style'}),
        line: {
            color: extendFlat({}, scatterMarkerLineAttrs.color,
                {arrayOk: false, dflt: colorAttrs.defaultLine, editType: 'style'}
            ),
            width: extendFlat({}, scatterMarkerLineAttrs.width,
                {arrayOk: false, dflt: 0, editType: 'style'}
            ),
            outliercolor: {
                valType: 'color',
                
                editType: 'style',
                
            },
            outlierwidth: {
                valType: 'number',
                min: 0,
                dflt: 1,
                
                editType: 'style',
                
            },
            editType: 'style'
        },
        editType: 'plot'
    },
    line: {
        color: {
            valType: 'color',
            
            editType: 'style',
            
        },
        width: {
            valType: 'number',
            
            min: 0,
            dflt: 2,
            editType: 'style',
            
        },
        editType: 'plot'
    },
    fillcolor: scatterAttrs.fillcolor,

    offsetgroup: barAttrs.offsetgroup,
    alignmentgroup: barAttrs.alignmentgroup,

    selected: {
        marker: scatterAttrs.selected.marker,
        editType: 'style'
    },
    unselected: {
        marker: scatterAttrs.unselected.marker,
        editType: 'style'
    },
    hoveron: {
        valType: 'flaglist',
        flags: ['boxes', 'points'],
        dflt: 'boxes+points',
        
        editType: 'style',
        
    }
};

},{"../../components/color/attributes":573,"../../lib/extend":687,"../bar/attributes":836,"../scatter/attributes":1048}],860:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');
var _ = Lib._;
var Axes = _dereq_('../../plots/cartesian/axes');

// outlier definition based on http://www.physics.csbsju.edu/stats/box2.html
module.exports = function calc(gd, trace) {
    var fullLayout = gd._fullLayout;
    var xa = Axes.getFromId(gd, trace.xaxis || 'x');
    var ya = Axes.getFromId(gd, trace.yaxis || 'y');
    var cd = [];

    // N.B. violin reuses same Box.calc
    var numKey = trace.type === 'violin' ? '_numViolins' : '_numBoxes';

    var i;
    var valAxis, valLetter;
    var posAxis, posLetter;

    if(trace.orientation === 'h') {
        valAxis = xa;
        valLetter = 'x';
        posAxis = ya;
        posLetter = 'y';
    } else {
        valAxis = ya;
        valLetter = 'y';
        posAxis = xa;
        posLetter = 'x';
    }

    var val = valAxis.makeCalcdata(trace, valLetter);
    var pos = getPos(trace, posLetter, posAxis, val, fullLayout[numKey]);

    var dv = Lib.distinctVals(pos);
    var posDistinct = dv.vals;
    var dPos = dv.minDiff / 2;
    var posBins = makeBins(posDistinct, dPos);

    var pLen = posDistinct.length;
    var ptsPerBin = initNestedArray(pLen);

    // bin pts info per position bins
    for(i = 0; i < trace._length; i++) {
        var v = val[i];
        if(!isNumeric(v)) continue;

        var n = Lib.findBin(pos[i], posBins);
        if(n >= 0 && n < pLen) {
            var pt = {v: v, i: i};
            arraysToCalcdata(pt, trace, i);
            ptsPerBin[n].push(pt);
        }
    }

    var cdi;
    var ptFilterFn = (trace.boxpoints || trace.points) === 'all' ?
        Lib.identity :
        function(pt) { return (pt.v < cdi.lf || pt.v > cdi.uf); };

    // build calcdata trace items, one item per distinct position
    for(i = 0; i < pLen; i++) {
        if(ptsPerBin[i].length > 0) {
            var pts = ptsPerBin[i].sort(sortByVal);
            var boxVals = pts.map(extractVal);
            var bvLen = boxVals.length;

            cdi = {};
            cdi.pos = posDistinct[i];
            cdi.pts = pts;

            cdi.min = boxVals[0];
            cdi.max = boxVals[bvLen - 1];
            cdi.mean = Lib.mean(boxVals, bvLen);
            cdi.sd = Lib.stdev(boxVals, bvLen, cdi.mean);

            // first quartile
            cdi.q1 = Lib.interp(boxVals, 0.25);
             // median
            cdi.med = Lib.interp(boxVals, 0.5);
            // third quartile
            cdi.q3 = Lib.interp(boxVals, 0.75);

            // lower and upper fences - last point inside
            // 1.5 interquartile ranges from quartiles
            cdi.lf = Math.min(
                cdi.q1,
                boxVals[Math.min(
                    Lib.findBin(2.5 * cdi.q1 - 1.5 * cdi.q3, boxVals, true) + 1,
                    bvLen - 1
                )]
            );
            cdi.uf = Math.max(
                cdi.q3,
                boxVals[Math.max(
                    Lib.findBin(2.5 * cdi.q3 - 1.5 * cdi.q1, boxVals),
                    0
                )]
            );

            // lower and upper outliers - 3 IQR out (don't clip to max/min,
            // this is only for discriminating suspected & far outliers)
            cdi.lo = 4 * cdi.q1 - 3 * cdi.q3;
            cdi.uo = 4 * cdi.q3 - 3 * cdi.q1;

            // lower and upper notches ~95% Confidence Intervals for median
            var iqr = cdi.q3 - cdi.q1;
            var mci = 1.57 * iqr / Math.sqrt(bvLen);
            cdi.ln = cdi.med - mci;
            cdi.un = cdi.med + mci;

            cdi.pts2 = pts.filter(ptFilterFn);

            cd.push(cdi);
        }
    }

    calcSelection(cd, trace);
    var extremes = Axes.findExtremes(valAxis, val, {padded: true});
    trace._extremes[valAxis._id] = extremes;

    if(cd.length > 0) {
        cd[0].t = {
            num: fullLayout[numKey],
            dPos: dPos,
            posLetter: posLetter,
            valLetter: valLetter,
            labels: {
                med: _(gd, 'median:'),
                min: _(gd, 'min:'),
                q1: _(gd, 'q1:'),
                q3: _(gd, 'q3:'),
                max: _(gd, 'max:'),
                mean: trace.boxmean === 'sd' ? _(gd, 'mean ± σ:') : _(gd, 'mean:'),
                lf: _(gd, 'lower fence:'),
                uf: _(gd, 'upper fence:')
            }
        };

        fullLayout[numKey]++;
        return cd;
    } else {
        return [{t: {empty: true}}];
    }
};

// In vertical (horizontal) box plots:
// if no x (y) data, use x0 (y0), or name
// so if you want one box
// per trace, set x0 (y0) to the x (y) value or category for this trace
// (or set x (y) to a constant array matching y (x))
function getPos(trace, posLetter, posAxis, val, num) {
    if(posLetter in trace) {
        return posAxis.makeCalcdata(trace, posLetter);
    }

    var pos0;

    if(posLetter + '0' in trace) {
        pos0 = trace[posLetter + '0'];
    } else if('name' in trace && (
        posAxis.type === 'category' || (
            isNumeric(trace.name) &&
            ['linear', 'log'].indexOf(posAxis.type) !== -1
        ) || (
            Lib.isDateTime(trace.name) &&
            posAxis.type === 'date'
        )
    )) {
        pos0 = trace.name;
    } else {
        pos0 = num;
    }

    var pos0c = posAxis.type === 'multicategory' ?
        posAxis.r2c_just_indices(pos0) :
        posAxis.d2c(pos0, 0, trace[posLetter + 'calendar']);

    return val.map(function() { return pos0c; });
}

function makeBins(x, dx) {
    var len = x.length;
    var bins = new Array(len + 1);

    for(var i = 0; i < len; i++) {
        bins[i] = x[i] - dx;
    }
    bins[len] = x[len - 1] + dx;

    return bins;
}

function initNestedArray(len) {
    var arr = new Array(len);
    for(var i = 0; i < len; i++) {
        arr[i] = [];
    }
    return arr;
}

function arraysToCalcdata(pt, trace, i) {
    var trace2calc = {
        text: 'tx',
        hovertext: 'htx'
    };

    for(var k in trace2calc) {
        if(Array.isArray(trace[k])) {
            pt[trace2calc[k]] = trace[k][i];
        }
    }
}

function calcSelection(cd, trace) {
    if(Lib.isArrayOrTypedArray(trace.selectedpoints)) {
        for(var i = 0; i < cd.length; i++) {
            var pts = cd[i].pts || [];
            var ptNumber2cdIndex = {};

            for(var j = 0; j < pts.length; j++) {
                ptNumber2cdIndex[pts[j].i] = j;
            }

            Lib.tagSelected(pts, trace, ptNumber2cdIndex);
        }
    }
}

function sortByVal(a, b) { return a.v - b.v; }

function extractVal(o) { return o.v; }

},{"../../lib":697,"../../plots/cartesian/axes":745,"fast-isnumeric":218}],861:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Axes = _dereq_('../../plots/cartesian/axes');
var Lib = _dereq_('../../lib');
var getAxisGroup = _dereq_('../../plots/cartesian/axis_ids').getAxisGroup;

var orientations = ['v', 'h'];

function crossTraceCalc(gd, plotinfo) {
    var calcdata = gd.calcdata;
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    for(var i = 0; i < orientations.length; i++) {
        var orientation = orientations[i];
        var posAxis = orientation === 'h' ? ya : xa;
        var boxList = [];

        // make list of boxes / candlesticks
        // For backward compatibility, candlesticks are treated as if they *are* box traces here
        for(var j = 0; j < calcdata.length; j++) {
            var cd = calcdata[j];
            var t = cd[0].t;
            var trace = cd[0].trace;

            if(trace.visible === true &&
                    (trace.type === 'box' || trace.type === 'candlestick') &&
                    !t.empty &&
                    (trace.orientation || 'v') === orientation &&
                    trace.xaxis === xa._id &&
                    trace.yaxis === ya._id
              ) {
                boxList.push(j);
            }
        }

        setPositionOffset('box', gd, boxList, posAxis);
    }
}

function setPositionOffset(traceType, gd, boxList, posAxis) {
    var calcdata = gd.calcdata;
    var fullLayout = gd._fullLayout;
    var axId = posAxis._id;
    var axLetter = axId.charAt(0);

    var i, j, calcTrace;
    var pointList = [];
    var shownPts = 0;

    // make list of box points
    for(i = 0; i < boxList.length; i++) {
        calcTrace = calcdata[boxList[i]];
        for(j = 0; j < calcTrace.length; j++) {
            pointList.push(calcTrace[j].pos);
            shownPts += (calcTrace[j].pts2 || []).length;
        }
    }

    if(!pointList.length) return;

    // box plots - update dPos based on multiple traces
    var boxdv = Lib.distinctVals(pointList);
    var dPos0 = boxdv.minDiff / 2;

    // check for forced minimum dtick
    Axes.minDtick(posAxis, boxdv.minDiff, boxdv.vals[0], true);

    var numKey = traceType === 'violin' ? '_numViolins' : '_numBoxes';
    var numTotal = fullLayout[numKey];
    var group = fullLayout[traceType + 'mode'] === 'group' && numTotal > 1;
    var groupFraction = 1 - fullLayout[traceType + 'gap'];
    var groupGapFraction = 1 - fullLayout[traceType + 'groupgap'];

    for(i = 0; i < boxList.length; i++) {
        calcTrace = calcdata[boxList[i]];

        var trace = calcTrace[0].trace;
        var t = calcTrace[0].t;
        var width = trace.width;
        var side = trace.side;

        // position coordinate delta
        var dPos;
        // box half width;
        var bdPos;
        // box center offset
        var bPos;
        // half-width within which to accept hover for this box/violin
        // always split the distance to the closest box/violin
        var wHover;

        if(width) {
            dPos = bdPos = wHover = width / 2;
            bPos = 0;
        } else {
            dPos = dPos0;

            if(group) {
                var groupId = getAxisGroup(fullLayout, posAxis._id) + trace.orientation;
                var alignmentGroups = fullLayout._alignmentOpts[groupId] || {};
                var alignmentGroupOpts = alignmentGroups[trace.alignmentgroup] || {};
                var nOffsetGroups = Object.keys(alignmentGroupOpts.offsetGroups || {}).length;
                var num = nOffsetGroups || numTotal;
                var shift = nOffsetGroups ? trace._offsetIndex : t.num;

                bdPos = dPos * groupFraction * groupGapFraction / num;
                bPos = 2 * dPos * (-0.5 + (shift + 0.5) / num) * groupFraction;
                wHover = dPos * groupFraction / num;
            } else {
                bdPos = dPos * groupFraction * groupGapFraction;
                bPos = 0;
                wHover = dPos;
            }
        }
        t.dPos = dPos;
        t.bPos = bPos;
        t.bdPos = bdPos;
        t.wHover = wHover;

        // box/violin-only value-space push value
        var pushplus;
        var pushminus;
        // edge of box/violin
        var edge = bPos + bdPos;
        var edgeplus;
        var edgeminus;

        if(side === 'positive') {
            pushplus = dPos * (width ? 1 : 0.5);
            edgeplus = edge;
            pushminus = edgeplus = bPos;
        } else if(side === 'negative') {
            pushplus = edgeplus = bPos;
            pushminus = dPos * (width ? 1 : 0.5);
            edgeminus = edge;
        } else {
            pushplus = pushminus = dPos;
            edgeplus = edgeminus = edge;
        }

        // value-space padding
        var vpadplus;
        var vpadminus;
        // pixel-space padding
        var ppadplus;
        var ppadminus;
        // do we add 5% of both sides (for points beyond box/violin)
        var padded = false;
        // does this trace show points?
        var hasPts = (trace.boxpoints || trace.points) && (shownPts > 0);

        if(hasPts) {
            var pointpos = trace.pointpos;
            var jitter = trace.jitter;
            var ms = trace.marker.size / 2;

            var pp = 0;
            if((pointpos + jitter) >= 0) {
                pp = edge * (pointpos + jitter);
                if(pp > pushplus) {
                    // (++) beyond plus-value, use pp
                    padded = true;
                    ppadplus = ms;
                    vpadplus = pp;
                } else if(pp > edgeplus) {
                    // (+), use push-value (it's bigger), but add px-pad
                    ppadplus = ms;
                    vpadplus = pushplus;
                }
            }
            if(pp <= pushplus) {
                // (->) fallback to push value
                vpadplus = pushplus;
            }

            var pm = 0;
            if((pointpos - jitter) <= 0) {
                pm = -edge * (pointpos - jitter);
                if(pm > pushminus) {
                    // (--) beyond plus-value, use pp
                    padded = true;
                    ppadminus = ms;
                    vpadminus = pm;
                } else if(pm > edgeminus) {
                    // (-), use push-value (it's bigger), but add px-pad
                    ppadminus = ms;
                    vpadminus = pushminus;
                }
            }
            if(pm <= pushminus) {
                // (<-) fallback to push value
                vpadminus = pushminus;
            }
        } else {
            vpadplus = pushplus;
            vpadminus = pushminus;
        }

        var pos = new Array(calcTrace.length);
        for(j = 0; j < calcTrace.length; j++) {
            pos[j] = calcTrace[j].pos;
        }

        trace._extremes[axId] = Axes.findExtremes(posAxis, pos, {
            padded: padded,
            vpadminus: vpadminus,
            vpadplus: vpadplus,
            // N.B. SVG px-space positive/negative
            ppadminus: {x: ppadminus, y: ppadplus}[axLetter],
            ppadplus: {x: ppadplus, y: ppadminus}[axLetter],
        });
    }
}

module.exports = {
    crossTraceCalc: crossTraceCalc,
    setPositionOffset: setPositionOffset
};

},{"../../lib":697,"../../plots/cartesian/axes":745,"../../plots/cartesian/axis_ids":748}],862:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Registry = _dereq_('../../registry');
var Color = _dereq_('../../components/color');
var handleGroupingDefaults = _dereq_('../bar/defaults').handleGroupingDefaults;
var attributes = _dereq_('./attributes');

function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    handleSampleDefaults(traceIn, traceOut, coerce, layout);
    if(traceOut.visible === false) return;

    coerce('line.color', (traceIn.marker || {}).color || defaultColor);
    coerce('line.width');
    coerce('fillcolor', Color.addOpacity(traceOut.line.color, 0.5));

    coerce('whiskerwidth');
    coerce('boxmean');
    coerce('width');

    var notched = coerce('notched', traceIn.notchwidth !== undefined);
    if(notched) coerce('notchwidth');

    handlePointsDefaults(traceIn, traceOut, coerce, {prefix: 'box'});
}

function handleSampleDefaults(traceIn, traceOut, coerce, layout) {
    var y = coerce('y');
    var x = coerce('x');
    var hasX = x && x.length;

    var defaultOrientation, len;

    if(y && y.length) {
        defaultOrientation = 'v';
        if(hasX) {
            len = Math.min(Lib.minRowLength(x), Lib.minRowLength(y));
        } else {
            coerce('x0');
            len = Lib.minRowLength(y);
        }
    } else if(hasX) {
        defaultOrientation = 'h';
        coerce('y0');
        len = Lib.minRowLength(x);
    } else {
        traceOut.visible = false;
        return;
    }
    traceOut._length = len;

    var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
    handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout);

    coerce('orientation', defaultOrientation);
}

function handlePointsDefaults(traceIn, traceOut, coerce, opts) {
    var prefix = opts.prefix;

    var outlierColorDflt = Lib.coerce2(traceIn, traceOut, attributes, 'marker.outliercolor');
    var lineoutliercolor = coerce('marker.line.outliercolor');

    var points = coerce(
        prefix + 'points',
        (outlierColorDflt || lineoutliercolor) ? 'suspectedoutliers' : undefined
    );

    if(points) {
        coerce('jitter', points === 'all' ? 0.3 : 0);
        coerce('pointpos', points === 'all' ? -1.5 : 0);

        coerce('marker.symbol');
        coerce('marker.opacity');
        coerce('marker.size');
        coerce('marker.color', traceOut.line.color);
        coerce('marker.line.color');
        coerce('marker.line.width');

        if(points === 'suspectedoutliers') {
            coerce('marker.line.outliercolor', traceOut.marker.color);
            coerce('marker.line.outlierwidth');
        }

        coerce('selected.marker.color');
        coerce('unselected.marker.color');
        coerce('selected.marker.size');
        coerce('unselected.marker.size');

        coerce('text');
        coerce('hovertext');
    } else {
        delete traceOut.marker;
    }

    coerce('hoveron');

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
}

function crossTraceDefaults(fullData, fullLayout) {
    var traceIn, traceOut;

    function coerce(attr) {
        return Lib.coerce(traceOut._input, traceOut, attributes, attr);
    }

    for(var i = 0; i < fullData.length; i++) {
        traceOut = fullData[i];
        var traceType = traceOut.type;

        if(traceType === 'box' || traceType === 'violin') {
            traceIn = traceOut._input;
            if(fullLayout[traceType + 'mode'] === 'group') {
                handleGroupingDefaults(traceIn, traceOut, fullLayout, coerce);
            }
        }
    }
}

module.exports = {
    supplyDefaults: supplyDefaults,
    crossTraceDefaults: crossTraceDefaults,

    handleSampleDefaults: handleSampleDefaults,
    handlePointsDefaults: handlePointsDefaults
};

},{"../../components/color":574,"../../lib":697,"../../registry":826,"../bar/defaults":840,"./attributes":859}],863:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function eventData(out, pt) {

    // Note: hoverOnBox property is needed for click-to-select
    // to ignore when a box was clicked. This is the reason box
    // implements this custom eventData function.
    if(pt.hoverOnBox) out.hoverOnBox = pt.hoverOnBox;

    if('xVal' in pt) out.x = pt.xVal;
    if('yVal' in pt) out.y = pt.yVal;
    if(pt.xa) out.xaxis = pt.xa;
    if(pt.ya) out.yaxis = pt.ya;

    return out;
};

},{}],864:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Axes = _dereq_('../../plots/cartesian/axes');
var Lib = _dereq_('../../lib');
var Fx = _dereq_('../../components/fx');
var Color = _dereq_('../../components/color');
var fillHoverText = _dereq_('../scatter/fill_hover_text');

function hoverPoints(pointData, xval, yval, hovermode) {
    var cd = pointData.cd;
    var trace = cd[0].trace;
    var hoveron = trace.hoveron;
    var closeBoxData = [];
    var closePtData;

    if(hoveron.indexOf('boxes') !== -1) {
        closeBoxData = closeBoxData.concat(hoverOnBoxes(pointData, xval, yval, hovermode));
    }

    if(hoveron.indexOf('points') !== -1) {
        closePtData = hoverOnPoints(pointData, xval, yval);
    }

    // If there's a point in range and hoveron has points, show the best single point only.
    // If hoveron has boxes and there's no point in range (or hoveron doesn't have points), show the box stats.
    if(hovermode === 'closest') {
        if(closePtData) return [closePtData];
        return closeBoxData;
    }

    // Otherwise in compare mode, allow a point AND the box stats to be labeled
    // If there are multiple boxes in range (ie boxmode = 'overlay') we'll see stats for all of them.
    if(closePtData) {
        closeBoxData.push(closePtData);
        return closeBoxData;
    }
    return closeBoxData;
}

function hoverOnBoxes(pointData, xval, yval, hovermode) {
    var cd = pointData.cd;
    var xa = pointData.xa;
    var ya = pointData.ya;
    var trace = cd[0].trace;
    var t = cd[0].t;
    var isViolin = trace.type === 'violin';
    var closeBoxData = [];

    var pLetter, vLetter, pAxis, vAxis, vVal, pVal, dx, dy, dPos,
        hoverPseudoDistance, spikePseudoDistance;

    var boxDelta = t.bdPos;
    var posAcceptance = t.wHover;
    var shiftPos = function(di) { return di.pos + t.bPos - pVal; };

    if(isViolin && trace.side !== 'both') {
        if(trace.side === 'positive') {
            dPos = function(di) {
                var pos = shiftPos(di);
                return Fx.inbox(pos, pos + posAcceptance, hoverPseudoDistance);
            };
        }
        if(trace.side === 'negative') {
            dPos = function(di) {
                var pos = shiftPos(di);
                return Fx.inbox(pos - posAcceptance, pos, hoverPseudoDistance);
            };
        }
    } else {
        dPos = function(di) {
            var pos = shiftPos(di);
            return Fx.inbox(pos - posAcceptance, pos + posAcceptance, hoverPseudoDistance);
        };
    }

    var dVal;

    if(isViolin) {
        dVal = function(di) {
            return Fx.inbox(di.span[0] - vVal, di.span[1] - vVal, hoverPseudoDistance);
        };
    } else {
        dVal = function(di) {
            return Fx.inbox(di.min - vVal, di.max - vVal, hoverPseudoDistance);
        };
    }

    if(trace.orientation === 'h') {
        vVal = xval;
        pVal = yval;
        dx = dVal;
        dy = dPos;
        pLetter = 'y';
        pAxis = ya;
        vLetter = 'x';
        vAxis = xa;
    } else {
        vVal = yval;
        pVal = xval;
        dx = dPos;
        dy = dVal;
        pLetter = 'x';
        pAxis = xa;
        vLetter = 'y';
        vAxis = ya;
    }

    // if two boxes are overlaying, let the narrowest one win
    var pseudoDistance = Math.min(1, boxDelta / Math.abs(pAxis.r2c(pAxis.range[1]) - pAxis.r2c(pAxis.range[0])));
    hoverPseudoDistance = pointData.maxHoverDistance - pseudoDistance;
    spikePseudoDistance = pointData.maxSpikeDistance - pseudoDistance;

    function dxy(di) { return (dx(di) + dy(di)) / 2; }
    var distfn = Fx.getDistanceFunction(hovermode, dx, dy, dxy);
    Fx.getClosest(cd, distfn, pointData);

    // skip the rest (for this trace) if we didn't find a close point
    // and create the item(s) in closedata for this point
    if(pointData.index === false) return [];

    var di = cd[pointData.index];
    var lc = trace.line.color;
    var mc = (trace.marker || {}).color;

    if(Color.opacity(lc) && trace.line.width) pointData.color = lc;
    else if(Color.opacity(mc) && trace.boxpoints) pointData.color = mc;
    else pointData.color = trace.fillcolor;

    pointData[pLetter + '0'] = pAxis.c2p(di.pos + t.bPos - boxDelta, true);
    pointData[pLetter + '1'] = pAxis.c2p(di.pos + t.bPos + boxDelta, true);

    pointData[pLetter + 'LabelVal'] = di.pos;

    var spikePosAttr = pLetter + 'Spike';
    pointData.spikeDistance = dxy(di) * spikePseudoDistance / hoverPseudoDistance;
    pointData[spikePosAttr] = pAxis.c2p(di.pos, true);

    // box plots: each "point" gets many labels
    var usedVals = {};
    var attrs = ['med', 'min', 'q1', 'q3', 'max'];

    if(trace.boxmean || (trace.meanline || {}).visible) {
        attrs.push('mean');
    }
    if(trace.boxpoints || trace.points) {
        attrs.push('lf', 'uf');
    }

    for(var i = 0; i < attrs.length; i++) {
        var attr = attrs[i];

        if(!(attr in di) || (di[attr] in usedVals)) continue;
        usedVals[di[attr]] = true;

        // copy out to a new object for each value to label
        var val = di[attr];
        var valPx = vAxis.c2p(val, true);
        var pointData2 = Lib.extendFlat({}, pointData);

        pointData2[vLetter + '0'] = pointData2[vLetter + '1'] = valPx;
        pointData2[vLetter + 'LabelVal'] = val;
        pointData2[vLetter + 'Label'] = (t.labels ? t.labels[attr] + ' ' : '') + Axes.hoverLabelText(vAxis, val);

        // Note: introduced to be able to distinguish a
        // clicked point from a box during click-to-select
        pointData2.hoverOnBox = true;

        if(attr === 'mean' && ('sd' in di) && trace.boxmean === 'sd') {
            pointData2[vLetter + 'err'] = di.sd;
        }
        // only keep name and spikes on the first item (median)
        pointData.name = '';
        pointData.spikeDistance = undefined;
        pointData[spikePosAttr] = undefined;

        closeBoxData.push(pointData2);
    }

    return closeBoxData;
}

function hoverOnPoints(pointData, xval, yval) {
    var cd = pointData.cd;
    var xa = pointData.xa;
    var ya = pointData.ya;
    var trace = cd[0].trace;
    var xPx = xa.c2p(xval);
    var yPx = ya.c2p(yval);
    var closePtData;

    var dx = function(di) {
        var rad = Math.max(3, di.mrc || 0);
        return Math.max(Math.abs(xa.c2p(di.x) - xPx) - rad, 1 - 3 / rad);
    };
    var dy = function(di) {
        var rad = Math.max(3, di.mrc || 0);
        return Math.max(Math.abs(ya.c2p(di.y) - yPx) - rad, 1 - 3 / rad);
    };
    var distfn = Fx.quadrature(dx, dy);

    // show one point per trace
    var ijClosest = false;
    var di, pt;

    for(var i = 0; i < cd.length; i++) {
        di = cd[i];

        for(var j = 0; j < (di.pts || []).length; j++) {
            pt = di.pts[j];

            var newDistance = distfn(pt);
            if(newDistance <= pointData.distance) {
                pointData.distance = newDistance;
                ijClosest = [i, j];
            }
        }
    }

    if(!ijClosest) return false;

    di = cd[ijClosest[0]];
    pt = di.pts[ijClosest[1]];

    var xc = xa.c2p(pt.x, true);
    var yc = ya.c2p(pt.y, true);
    var rad = pt.mrc || 1;

    closePtData = Lib.extendFlat({}, pointData, {
        // corresponds to index in x/y input data array
        index: pt.i,
        color: (trace.marker || {}).color,
        name: trace.name,
        x0: xc - rad,
        x1: xc + rad,
        y0: yc - rad,
        y1: yc + rad,
        spikeDistance: pointData.distance
    });

    var pa;
    if(trace.orientation === 'h') {
        pa = ya;
        closePtData.xLabelVal = pt.x;
        closePtData.yLabelVal = di.pos;
    } else {
        pa = xa;
        closePtData.xLabelVal = di.pos;
        closePtData.yLabelVal = pt.y;
    }

    var pLetter = pa._id.charAt(0);
    closePtData[pLetter + 'Spike'] = pa.c2p(di.pos, true);

    fillHoverText(pt, trace, closePtData);

    return closePtData;
}

module.exports = {
    hoverPoints: hoverPoints,
    hoverOnBoxes: hoverOnBoxes,
    hoverOnPoints: hoverOnPoints
};

},{"../../components/color":574,"../../components/fx":613,"../../lib":697,"../../plots/cartesian/axes":745,"../scatter/fill_hover_text":1056}],865:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Box = {};

Box.attributes = _dereq_('./attributes');
Box.layoutAttributes = _dereq_('./layout_attributes');
Box.supplyDefaults = _dereq_('./defaults').supplyDefaults;
Box.crossTraceDefaults = _dereq_('./defaults').crossTraceDefaults;
Box.supplyLayoutDefaults = _dereq_('./layout_defaults').supplyLayoutDefaults;
Box.calc = _dereq_('./calc');
Box.crossTraceCalc = _dereq_('./cross_trace_calc').crossTraceCalc;
Box.plot = _dereq_('./plot').plot;
Box.style = _dereq_('./style').style;
Box.styleOnSelect = _dereq_('./style').styleOnSelect;
Box.hoverPoints = _dereq_('./hover').hoverPoints;
Box.eventData = _dereq_('./event_data');
Box.selectPoints = _dereq_('./select');

Box.moduleType = 'trace';
Box.name = 'box';
Box.basePlotModule = _dereq_('../../plots/cartesian');
Box.categories = ['cartesian', 'svg', 'symbols', 'oriented', 'box-violin', 'showLegend', 'boxLayout', 'zoomScale'];
Box.meta = {
    
};

module.exports = Box;

},{"../../plots/cartesian":756,"./attributes":859,"./calc":860,"./cross_trace_calc":861,"./defaults":862,"./event_data":863,"./hover":864,"./layout_attributes":866,"./layout_defaults":867,"./plot":868,"./select":869,"./style":870}],866:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    boxmode: {
        valType: 'enumerated',
        values: ['group', 'overlay'],
        dflt: 'overlay',
        
        editType: 'calc',
        
    },
    boxgap: {
        valType: 'number',
        min: 0,
        max: 1,
        dflt: 0.3,
        
        editType: 'calc',
        
    },
    boxgroupgap: {
        valType: 'number',
        min: 0,
        max: 1,
        dflt: 0.3,
        
        editType: 'calc',
        
    }
};

},{}],867:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var layoutAttributes = _dereq_('./layout_attributes');

function _supply(layoutIn, layoutOut, fullData, coerce, traceType) {
    var category = traceType + 'Layout';
    var hasTraceType = false;

    for(var i = 0; i < fullData.length; i++) {
        var trace = fullData[i];

        if(Registry.traceIs(trace, category)) {
            hasTraceType = true;
            break;
        }
    }
    if(!hasTraceType) return;

    coerce(traceType + 'mode');
    coerce(traceType + 'gap');
    coerce(traceType + 'groupgap');
}

function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
    function coerce(attr, dflt) {
        return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
    }
    _supply(layoutIn, layoutOut, fullData, coerce, 'box');
}

module.exports = {
    supplyLayoutDefaults: supplyLayoutDefaults,
    _supply: _supply
};

},{"../../lib":697,"../../registry":826,"./layout_attributes":866}],868:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Lib = _dereq_('../../lib');
var Drawing = _dereq_('../../components/drawing');

// constants for dynamic jitter (ie less jitter for sparser points)
var JITTERCOUNT = 5; // points either side of this to include
var JITTERSPREAD = 0.01; // fraction of IQR to count as "dense"

function plot(gd, plotinfo, cdbox, boxLayer) {
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    Lib.makeTraceGroups(boxLayer, cdbox, 'trace boxes').each(function(cd) {
        var plotGroup = d3.select(this);
        var cd0 = cd[0];
        var t = cd0.t;
        var trace = cd0.trace;
        if(!plotinfo.isRangePlot) cd0.node3 = plotGroup;

        // whisker width
        t.wdPos = t.bdPos * trace.whiskerwidth;

        if(trace.visible !== true || t.empty) {
            plotGroup.remove();
            return;
        }

        var posAxis, valAxis;

        if(trace.orientation === 'h') {
            posAxis = ya;
            valAxis = xa;
        } else {
            posAxis = xa;
            valAxis = ya;
        }

        plotBoxAndWhiskers(plotGroup, {pos: posAxis, val: valAxis}, trace, t);
        plotPoints(plotGroup, {x: xa, y: ya}, trace, t);
        plotBoxMean(plotGroup, {pos: posAxis, val: valAxis}, trace, t);
    });
}

function plotBoxAndWhiskers(sel, axes, trace, t) {
    var posAxis = axes.pos;
    var valAxis = axes.val;
    var bPos = t.bPos;
    var wdPos = t.wdPos || 0;
    var bPosPxOffset = t.bPosPxOffset || 0;
    var whiskerWidth = trace.whiskerwidth || 0;
    var notched = trace.notched || false;
    var nw = notched ? 1 - 2 * trace.notchwidth : 1;

    // to support for one-sided box
    var bdPos0;
    var bdPos1;
    if(Array.isArray(t.bdPos)) {
        bdPos0 = t.bdPos[0];
        bdPos1 = t.bdPos[1];
    } else {
        bdPos0 = t.bdPos;
        bdPos1 = t.bdPos;
    }

    var paths = sel.selectAll('path.box').data((
        trace.type !== 'violin' ||
        trace.box.visible
    ) ? Lib.identity : []);

    paths.enter().append('path')
        .style('vector-effect', 'non-scaling-stroke')
        .attr('class', 'box');

    paths.exit().remove();

    paths.each(function(d) {
        if(d.empty) return 'M0,0Z';

        var pos = d.pos;
        var posc = posAxis.c2p(pos + bPos, true) + bPosPxOffset;
        var pos0 = posAxis.c2p(pos + bPos - bdPos0, true) + bPosPxOffset;
        var pos1 = posAxis.c2p(pos + bPos + bdPos1, true) + bPosPxOffset;
        var posw0 = posAxis.c2p(pos + bPos - wdPos, true) + bPosPxOffset;
        var posw1 = posAxis.c2p(pos + bPos + wdPos, true) + bPosPxOffset;
        var posm0 = posAxis.c2p(pos + bPos - bdPos0 * nw, true) + bPosPxOffset;
        var posm1 = posAxis.c2p(pos + bPos + bdPos1 * nw, true) + bPosPxOffset;
        var q1 = valAxis.c2p(d.q1, true);
        var q3 = valAxis.c2p(d.q3, true);
        // make sure median isn't identical to either of the
        // quartiles, so we can see it
        var m = Lib.constrain(
            valAxis.c2p(d.med, true),
            Math.min(q1, q3) + 1, Math.max(q1, q3) - 1
        );

        // for compatibility with box, violin, and candlestick
        // perhaps we should put this into cd0.t instead so it's more explicit,
        // but what we have now is:
        // - box always has d.lf, but boxpoints can be anything
        // - violin has d.lf and should always use it (boxpoints is undefined)
        // - candlestick has only min/max
        var useExtremes = (d.lf === undefined) || (trace.boxpoints === false);
        var lf = valAxis.c2p(useExtremes ? d.min : d.lf, true);
        var uf = valAxis.c2p(useExtremes ? d.max : d.uf, true);
        var ln = valAxis.c2p(d.ln, true);
        var un = valAxis.c2p(d.un, true);

        if(trace.orientation === 'h') {
            d3.select(this).attr('d',
                'M' + m + ',' + posm0 + 'V' + posm1 + // median line
                'M' + q1 + ',' + pos0 + 'V' + pos1 + // left edge
                (notched ? 'H' + ln + 'L' + m + ',' + posm1 + 'L' + un + ',' + pos1 : '') + // top notched edge
                'H' + q3 + // end of the top edge
                'V' + pos0 + // right edge
                (notched ? 'H' + un + 'L' + m + ',' + posm0 + 'L' + ln + ',' + pos0 : '') + // bottom notched edge
                'Z' + // end of the box
                'M' + q1 + ',' + posc + 'H' + lf + 'M' + q3 + ',' + posc + 'H' + uf + // whiskers
                ((whiskerWidth === 0) ? '' : // whisker caps
                    'M' + lf + ',' + posw0 + 'V' + posw1 + 'M' + uf + ',' + posw0 + 'V' + posw1));
        } else {
            d3.select(this).attr('d',
                'M' + posm0 + ',' + m + 'H' + posm1 + // median line
                'M' + pos0 + ',' + q1 + 'H' + pos1 + // top of the box
                (notched ? 'V' + ln + 'L' + posm1 + ',' + m + 'L' + pos1 + ',' + un : '') + // notched right edge
                'V' + q3 + // end of the right edge
                'H' + pos0 + // bottom of the box
                (notched ? 'V' + un + 'L' + posm0 + ',' + m + 'L' + pos0 + ',' + ln : '') + // notched left edge
                'Z' + // end of the box
                'M' + posc + ',' + q1 + 'V' + lf + 'M' + posc + ',' + q3 + 'V' + uf + // whiskers
                ((whiskerWidth === 0) ? '' : // whisker caps
                    'M' + posw0 + ',' + lf + 'H' + posw1 + 'M' + posw0 + ',' + uf + 'H' + posw1));
        }
    });
}

function plotPoints(sel, axes, trace, t) {
    var xa = axes.x;
    var ya = axes.y;
    var bdPos = t.bdPos;
    var bPos = t.bPos;

    // to support violin points
    var mode = trace.boxpoints || trace.points;

    // repeatable pseudo-random number generator
    Lib.seedPseudoRandom();

    // since box plot points get an extra level of nesting, each
    // box needs the trace styling info
    var fn = function(d) {
        d.forEach(function(v) {
            v.t = t;
            v.trace = trace;
        });
        return d;
    };

    var gPoints = sel.selectAll('g.points')
        .data(mode ? fn : []);

    gPoints.enter().append('g')
        .attr('class', 'points');

    gPoints.exit().remove();

    var paths = gPoints.selectAll('path')
        .data(function(d) {
            var i;
            var pts = d.pts2;

            // normally use IQR, but if this is 0 or too small, use max-min
            var typicalSpread = Math.max((d.max - d.min) / 10, d.q3 - d.q1);
            var minSpread = typicalSpread * 1e-9;
            var spreadLimit = typicalSpread * JITTERSPREAD;
            var jitterFactors = [];
            var maxJitterFactor = 0;
            var newJitter;

            // dynamic jitter
            if(trace.jitter) {
                if(typicalSpread === 0) {
                    // edge case of no spread at all: fall back to max jitter
                    maxJitterFactor = 1;
                    jitterFactors = new Array(pts.length);
                    for(i = 0; i < pts.length; i++) {
                        jitterFactors[i] = 1;
                    }
                } else {
                    for(i = 0; i < pts.length; i++) {
                        var i0 = Math.max(0, i - JITTERCOUNT);
                        var pmin = pts[i0].v;
                        var i1 = Math.min(pts.length - 1, i + JITTERCOUNT);
                        var pmax = pts[i1].v;

                        if(mode !== 'all') {
                            if(pts[i].v < d.lf) pmax = Math.min(pmax, d.lf);
                            else pmin = Math.max(pmin, d.uf);
                        }

                        var jitterFactor = Math.sqrt(spreadLimit * (i1 - i0) / (pmax - pmin + minSpread)) || 0;
                        jitterFactor = Lib.constrain(Math.abs(jitterFactor), 0, 1);

                        jitterFactors.push(jitterFactor);
                        maxJitterFactor = Math.max(jitterFactor, maxJitterFactor);
                    }
                }
                newJitter = trace.jitter * 2 / (maxJitterFactor || 1);
            }

            // fills in 'x' and 'y' in calcdata 'pts' item
            for(i = 0; i < pts.length; i++) {
                var pt = pts[i];
                var v = pt.v;

                var jitterOffset = trace.jitter ?
                    (newJitter * jitterFactors[i] * (Lib.pseudoRandom() - 0.5)) :
                    0;

                var posPx = d.pos + bPos + bdPos * (trace.pointpos + jitterOffset);

                if(trace.orientation === 'h') {
                    pt.y = posPx;
                    pt.x = v;
                } else {
                    pt.x = posPx;
                    pt.y = v;
                }

                // tag suspected outliers
                if(mode === 'suspectedoutliers' && v < d.uo && v > d.lo) {
                    pt.so = true;
                }
            }

            return pts;
        });

    paths.enter().append('path')
        .classed('point', true);

    paths.exit().remove();

    paths.call(Drawing.translatePoints, xa, ya);
}

function plotBoxMean(sel, axes, trace, t) {
    var posAxis = axes.pos;
    var valAxis = axes.val;
    var bPos = t.bPos;
    var bPosPxOffset = t.bPosPxOffset || 0;

    // to support violin mean lines
    var mode = trace.boxmean || (trace.meanline || {}).visible;

    // to support for one-sided box
    var bdPos0;
    var bdPos1;
    if(Array.isArray(t.bdPos)) {
        bdPos0 = t.bdPos[0];
        bdPos1 = t.bdPos[1];
    } else {
        bdPos0 = t.bdPos;
        bdPos1 = t.bdPos;
    }

    var paths = sel.selectAll('path.mean').data((
        (trace.type === 'box' && trace.boxmean) ||
        (trace.type === 'violin' && trace.box.visible && trace.meanline.visible)
    ) ? Lib.identity : []);

    paths.enter().append('path')
        .attr('class', 'mean')
        .style({
            fill: 'none',
            'vector-effect': 'non-scaling-stroke'
        });

    paths.exit().remove();

    paths.each(function(d) {
        var posc = posAxis.c2p(d.pos + bPos, true) + bPosPxOffset;
        var pos0 = posAxis.c2p(d.pos + bPos - bdPos0, true) + bPosPxOffset;
        var pos1 = posAxis.c2p(d.pos + bPos + bdPos1, true) + bPosPxOffset;
        var m = valAxis.c2p(d.mean, true);
        var sl = valAxis.c2p(d.mean - d.sd, true);
        var sh = valAxis.c2p(d.mean + d.sd, true);

        if(trace.orientation === 'h') {
            d3.select(this).attr('d',
                'M' + m + ',' + pos0 + 'V' + pos1 +
                (mode === 'sd' ?
                    'm0,0L' + sl + ',' + posc + 'L' + m + ',' + pos0 + 'L' + sh + ',' + posc + 'Z' :
                    '')
            );
        } else {
            d3.select(this).attr('d',
                'M' + pos0 + ',' + m + 'H' + pos1 +
                (mode === 'sd' ?
                    'm0,0L' + posc + ',' + sl + 'L' + pos0 + ',' + m + 'L' + posc + ',' + sh + 'Z' :
                    '')
            );
        }
    });
}

module.exports = {
    plot: plot,
    plotBoxAndWhiskers: plotBoxAndWhiskers,
    plotPoints: plotPoints,
    plotBoxMean: plotBoxMean
};

},{"../../components/drawing":595,"../../lib":697,"d3":151}],869:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function selectPoints(searchInfo, selectionTester) {
    var cd = searchInfo.cd;
    var xa = searchInfo.xaxis;
    var ya = searchInfo.yaxis;
    var selection = [];
    var i, j;

    if(selectionTester === false) {
        for(i = 0; i < cd.length; i++) {
            for(j = 0; j < (cd[i].pts || []).length; j++) {
                // clear selection
                cd[i].pts[j].selected = 0;
            }
        }
    } else {
        for(i = 0; i < cd.length; i++) {
            for(j = 0; j < (cd[i].pts || []).length; j++) {
                var pt = cd[i].pts[j];
                var x = xa.c2p(pt.x);
                var y = ya.c2p(pt.y);

                if(selectionTester.contains([x, y], null, pt.i, searchInfo)) {
                    selection.push({
                        pointNumber: pt.i,
                        x: xa.c2d(pt.x),
                        y: ya.c2d(pt.y)
                    });
                    pt.selected = 1;
                } else {
                    pt.selected = 0;
                }
            }
        }
    }

    return selection;
};

},{}],870:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var Color = _dereq_('../../components/color');
var Drawing = _dereq_('../../components/drawing');

function style(gd, cd) {
    var s = cd ? cd[0].node3 : d3.select(gd).selectAll('g.trace.boxes');

    s.style('opacity', function(d) { return d[0].trace.opacity; });

    s.each(function(d) {
        var el = d3.select(this);
        var trace = d[0].trace;
        var lineWidth = trace.line.width;

        function styleBox(boxSel, lineWidth, lineColor, fillColor) {
            boxSel.style('stroke-width', lineWidth + 'px')
                .call(Color.stroke, lineColor)
                .call(Color.fill, fillColor);
        }

        var allBoxes = el.selectAll('path.box');

        if(trace.type === 'candlestick') {
            allBoxes.each(function(boxData) {
                if(boxData.empty) return;

                var thisBox = d3.select(this);
                var container = trace[boxData.dir]; // dir = 'increasing' or 'decreasing'
                styleBox(thisBox, container.line.width, container.line.color, container.fillcolor);
                // TODO: custom selection style for candlesticks
                thisBox.style('opacity', trace.selectedpoints && !boxData.selected ? 0.3 : 1);
            });
        } else {
            styleBox(allBoxes, lineWidth, trace.line.color, trace.fillcolor);
            el.selectAll('path.mean')
                .style({
                    'stroke-width': lineWidth,
                    'stroke-dasharray': (2 * lineWidth) + 'px,' + lineWidth + 'px'
                })
                .call(Color.stroke, trace.line.color);

            var pts = el.selectAll('path.point');
            Drawing.pointStyle(pts, trace, gd);
        }
    });
}

function styleOnSelect(gd, cd) {
    var s = cd[0].node3;
    var trace = cd[0].trace;
    var pts = s.selectAll('path.point');

    if(trace.selectedpoints) {
        Drawing.selectedPointStyle(pts, trace);
    } else {
        Drawing.pointStyle(pts, trace, gd);
    }
}

module.exports = {
    style: style,
    styleOnSelect: styleOnSelect
};

},{"../../components/color":574,"../../components/drawing":595,"d3":151}],871:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var extendFlat = _dereq_('../../lib').extendFlat;
var OHLCattrs = _dereq_('../ohlc/attributes');
var boxAttrs = _dereq_('../box/attributes');

function directionAttrs(lineColorDefault) {
    return {
        line: {
            color: extendFlat({}, boxAttrs.line.color, {dflt: lineColorDefault}),
            width: boxAttrs.line.width,
            editType: 'style'
        },

        fillcolor: boxAttrs.fillcolor,
        editType: 'style'
    };
}

module.exports = {
    x: OHLCattrs.x,
    open: OHLCattrs.open,
    high: OHLCattrs.high,
    low: OHLCattrs.low,
    close: OHLCattrs.close,

    line: {
        width: extendFlat({}, boxAttrs.line.width, {
            
        }),
        editType: 'style'
    },

    increasing: directionAttrs(OHLCattrs.increasing.line.color.dflt),

    decreasing: directionAttrs(OHLCattrs.decreasing.line.color.dflt),

    text: OHLCattrs.text,
    hovertext: OHLCattrs.hovertext,
    whiskerwidth: extendFlat({}, boxAttrs.whiskerwidth, { dflt: 0 }),

    hoverlabel: OHLCattrs.hoverlabel,
};

},{"../../lib":697,"../box/attributes":859,"../ohlc/attributes":996}],872:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');

var calcCommon = _dereq_('../ohlc/calc').calcCommon;

module.exports = function(gd, trace) {
    var fullLayout = gd._fullLayout;
    var xa = Axes.getFromId(gd, trace.xaxis);
    var ya = Axes.getFromId(gd, trace.yaxis);

    var x = xa.makeCalcdata(trace, 'x');

    var cd = calcCommon(gd, trace, x, ya, ptFunc);

    if(cd.length) {
        Lib.extendFlat(cd[0].t, {
            num: fullLayout._numBoxes,
            dPos: Lib.distinctVals(x).minDiff / 2,
            posLetter: 'x',
            valLetter: 'y',
        });

        fullLayout._numBoxes++;
        return cd;
    } else {
        return [{t: {empty: true}}];
    }
};

function ptFunc(o, h, l, c) {
    return {
        min: l,
        q1: Math.min(o, c),
        med: c,
        q3: Math.max(o, c),
        max: h,
    };
}

},{"../../lib":697,"../../plots/cartesian/axes":745,"../ohlc/calc":997}],873:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var Color = _dereq_('../../components/color');
var handleOHLC = _dereq_('../ohlc/ohlc_defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var len = handleOHLC(traceIn, traceOut, coerce, layout);
    if(!len) {
        traceOut.visible = false;
        return;
    }

    coerce('line.width');

    handleDirection(traceIn, traceOut, coerce, 'increasing');
    handleDirection(traceIn, traceOut, coerce, 'decreasing');

    coerce('text');
    coerce('hovertext');
    coerce('whiskerwidth');

    layout._requestRangeslider[traceOut.xaxis] = true;
};

function handleDirection(traceIn, traceOut, coerce, direction) {
    var lineColor = coerce(direction + '.line.color');
    coerce(direction + '.line.width', traceOut.line.width);
    coerce(direction + '.fillcolor', Color.addOpacity(lineColor, 0.5));
}

},{"../../components/color":574,"../../lib":697,"../ohlc/ohlc_defaults":1001,"./attributes":871}],874:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'trace',
    name: 'candlestick',
    basePlotModule: _dereq_('../../plots/cartesian'),
    categories: ['cartesian', 'svg', 'showLegend', 'candlestick', 'boxLayout'],
    meta: {
        
    },

    attributes: _dereq_('./attributes'),
    layoutAttributes: _dereq_('../box/layout_attributes'),
    supplyLayoutDefaults: _dereq_('../box/layout_defaults').supplyLayoutDefaults,
    crossTraceCalc: _dereq_('../box/cross_trace_calc').crossTraceCalc,
    supplyDefaults: _dereq_('./defaults'),
    calc: _dereq_('./calc'),
    plot: _dereq_('../box/plot').plot,
    layerName: 'boxlayer',
    style: _dereq_('../box/style').style,
    hoverPoints: _dereq_('../ohlc/hover').hoverPoints,
    selectPoints: _dereq_('../ohlc/select')
};

},{"../../plots/cartesian":756,"../box/cross_trace_calc":861,"../box/layout_attributes":866,"../box/layout_defaults":867,"../box/plot":868,"../box/style":870,"../ohlc/hover":999,"../ohlc/select":1003,"./attributes":871,"./calc":872,"./defaults":873}],875:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var handleAxisDefaults = _dereq_('./axis_defaults');
var Template = _dereq_('../../plot_api/plot_template');

module.exports = function handleABDefaults(traceIn, traceOut, fullLayout, coerce, dfltColor) {
    var a = coerce('a');

    if(!a) {
        coerce('da');
        coerce('a0');
    }

    var b = coerce('b');

    if(!b) {
        coerce('db');
        coerce('b0');
    }

    mimickAxisDefaults(traceIn, traceOut, fullLayout, dfltColor);
};

function mimickAxisDefaults(traceIn, traceOut, fullLayout, dfltColor) {
    var axesList = ['aaxis', 'baxis'];

    axesList.forEach(function(axName) {
        var axLetter = axName.charAt(0);
        var axIn = traceIn[axName] || {};
        var axOut = Template.newContainer(traceOut, axName);

        var defaultOptions = {
            tickfont: 'x',
            id: axLetter + 'axis',
            letter: axLetter,
            font: traceOut.font,
            name: axName,
            data: traceIn[axLetter],
            calendar: traceOut.calendar,
            dfltColor: dfltColor,
            bgColor: fullLayout.paper_bgcolor,
            fullLayout: fullLayout
        };

        handleAxisDefaults(axIn, axOut, defaultOptions);
        axOut._categories = axOut._categories || [];

        // so we don't have to repeat autotype unnecessarily,
        // copy an autotype back to traceIn
        if(!traceIn[axName] && axIn.type !== '-') {
            traceIn[axName] = {type: axIn.type};
        }
    });
}

},{"../../plot_api/plot_template":735,"./axis_defaults":880}],876:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;

module.exports = function(a) {
    return minMax(a, 0);
};

function minMax(a, depth) {
    // Limit to ten dimensional datasets. This seems *exceedingly* unlikely to
    // ever cause problems or even be a concern. It's include strictly so that
    // circular arrays could never cause this to loop.
    if(!isArrayOrTypedArray(a) || depth >= 10) {
        return null;
    }

    var min = Infinity;
    var max = -Infinity;
    var n = a.length;
    for(var i = 0; i < n; i++) {
        var datum = a[i];

        if(isArrayOrTypedArray(datum)) {
            var result = minMax(datum, depth + 1);

            if(result) {
                min = Math.min(result[0], min);
                max = Math.max(result[1], max);
            }
        } else {
            min = Math.min(datum, min);
            max = Math.max(datum, max);
        }
    }

    return [min, max];
}

},{"../../lib":697}],877:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = _dereq_('../../plots/font_attributes');
var axisAttrs = _dereq_('./axis_attributes');
var colorAttrs = _dereq_('../../components/color/attributes');

var carpetFont = fontAttrs({
    editType: 'calc',
    
});
// TODO: inherit from global font
carpetFont.family.dflt = '"Open Sans", verdana, arial, sans-serif';
carpetFont.size.dflt = 12;
carpetFont.color.dflt = colorAttrs.defaultLine;

module.exports = {
    carpet: {
        valType: 'string',
        
        editType: 'calc',
        
    },
    x: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },
    y: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },
    a: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    a0: {
        valType: 'number',
        dflt: 0,
        
        editType: 'calc',
        
    },
    da: {
        valType: 'number',
        dflt: 1,
        
        editType: 'calc',
        
    },
    b: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    b0: {
        valType: 'number',
        dflt: 0,
        
        editType: 'calc',
        
    },
    db: {
        valType: 'number',
        dflt: 1,
        
        editType: 'calc',
        
    },
    cheaterslope: {
        valType: 'number',
        
        dflt: 1,
        editType: 'calc',
        
    },
    aaxis: axisAttrs,
    baxis: axisAttrs,
    font: carpetFont,
    color: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'plot',
        
    },
    transforms: undefined
};

},{"../../components/color/attributes":573,"../../plots/font_attributes":771,"./axis_attributes":879}],878:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;

/* This function retrns a set of control points that define a curve aligned along
 * either the a or b axis. Exactly one of a or b must be an array defining the range
 * spanned.
 *
 * Honestly this is the most complicated function I've implemente here so far because
 * of the way it handles knot insertion and direction/axis-agnostic slices.
 */
module.exports = function(carpet, carpetcd, a, b) {
    var idx, tangent, tanIsoIdx, tanIsoPar, segment, refidx;
    var p0, p1, v0, v1, start, end, range;

    var axis = isArrayOrTypedArray(a) ? 'a' : 'b';
    var ax = axis === 'a' ? carpet.aaxis : carpet.baxis;
    var smoothing = ax.smoothing;
    var toIdx = axis === 'a' ? carpet.a2i : carpet.b2j;
    var pt = axis === 'a' ? a : b;
    var iso = axis === 'a' ? b : a;
    var n = axis === 'a' ? carpetcd.a.length : carpetcd.b.length;
    var m = axis === 'a' ? carpetcd.b.length : carpetcd.a.length;
    var isoIdx = Math.floor(axis === 'a' ? carpet.b2j(iso) : carpet.a2i(iso));

    var xy = axis === 'a' ? function(value) {
        return carpet.evalxy([], value, isoIdx);
    } : function(value) {
        return carpet.evalxy([], isoIdx, value);
    };

    if(smoothing) {
        tanIsoIdx = Math.max(0, Math.min(m - 2, isoIdx));
        tanIsoPar = isoIdx - tanIsoIdx;
        tangent = axis === 'a' ? function(i, ti) {
            return carpet.dxydi([], i, tanIsoIdx, ti, tanIsoPar);
        } : function(j, tj) {
            return carpet.dxydj([], tanIsoIdx, j, tanIsoPar, tj);
        };
    }

    var vstart = toIdx(pt[0]);
    var vend = toIdx(pt[1]);

    // So that we can make this work in two directions, flip all of the
    // math functions if the direction is from higher to lower indices:
    //
    // Note that the tolerance is directional!
    var dir = vstart < vend ? 1 : -1;
    var tol = (vend - vstart) * 1e-8;
    var dirfloor = dir > 0 ? Math.floor : Math.ceil;
    var dirceil = dir > 0 ? Math.ceil : Math.floor;
    var dirmin = dir > 0 ? Math.min : Math.max;
    var dirmax = dir > 0 ? Math.max : Math.min;

    var idx0 = dirfloor(vstart + tol);
    var idx1 = dirceil(vend - tol);

    p0 = xy(vstart);
    var segments = [[p0]];

    for(idx = idx0; idx * dir < idx1 * dir; idx += dir) {
        segment = [];
        start = dirmax(vstart, idx);
        end = dirmin(vend, idx + dir);
        range = end - start;

        // In order to figure out which cell we're in for the derivative (remember,
        // the derivatives are *not* constant across grid lines), let's just average
        // the start and end points. This cuts out just a tiny bit of logic and
        // there's really no computational difference:
        refidx = Math.max(0, Math.min(n - 2, Math.floor(0.5 * (start + end))));

        p1 = xy(end);
        if(smoothing) {
            v0 = tangent(refidx, start - refidx);
            v1 = tangent(refidx, end - refidx);

            segment.push([
                p0[0] + v0[0] / 3 * range,
                p0[1] + v0[1] / 3 * range
            ]);

            segment.push([
                p1[0] - v1[0] / 3 * range,
                p1[1] - v1[1] / 3 * range
            ]);
        }

        segment.push(p1);

        segments.push(segment);
        p0 = p1;
    }

    return segments;
};

},{"../../lib":697}],879:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = _dereq_('../../plots/font_attributes');
var colorAttrs = _dereq_('../../components/color/attributes');
var axesAttrs = _dereq_('../../plots/cartesian/layout_attributes');
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;

module.exports = {
    color: {
        valType: 'color',
        
        editType: 'calc',
        
    },
    smoothing: {
        valType: 'number',
        dflt: 1,
        min: 0,
        max: 1.3,
        
        editType: 'calc'
    },
    title: {
        text: {
            valType: 'string',
            dflt: '',
            
            editType: 'calc',
            
        },
        font: fontAttrs({
            editType: 'calc',
            
        }),
        offset: {
            valType: 'number',
            
            dflt: 10,
            editType: 'calc',
            
        },
        editType: 'calc',
    },
    type: {
        valType: 'enumerated',
        // '-' means we haven't yet run autotype or couldn't find any data
        // it gets turned into linear in gd._fullLayout but not copied back
        // to gd.data like the others are.
        values: ['-', 'linear', 'date', 'category'],
        dflt: '-',
        
        editType: 'calc',
        
    },
    autorange: {
        valType: 'enumerated',
        values: [true, false, 'reversed'],
        dflt: true,
        
        editType: 'calc',
        
    },
    rangemode: {
        valType: 'enumerated',
        values: ['normal', 'tozero', 'nonnegative'],
        dflt: 'normal',
        
        editType: 'calc',
        
    },
    range: {
        valType: 'info_array',
        
        editType: 'calc',
        items: [
            {valType: 'any', editType: 'calc'},
            {valType: 'any', editType: 'calc'}
        ],
        
    },

    fixedrange: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'calc',
        
    },
    cheatertype: {
        valType: 'enumerated',
        values: ['index', 'value'],
        dflt: 'value',
        
        editType: 'calc'
    },
    tickmode: {
        valType: 'enumerated',
        values: ['linear', 'array'],
        dflt: 'array',
        
        editType: 'calc'
    },
    nticks: {
        valType: 'integer',
        min: 0,
        dflt: 0,
        
        editType: 'calc',
        
    },
    tickvals: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    ticktext: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    showticklabels: {
        valType: 'enumerated',
        values: ['start', 'end', 'both', 'none'],
        dflt: 'start',
        
        editType: 'calc',
        
    },
    tickfont: fontAttrs({
        editType: 'calc',
        
    }),
    tickangle: {
        valType: 'angle',
        dflt: 'auto',
        
        editType: 'calc',
        
    },
    tickprefix: {
        valType: 'string',
        dflt: '',
        
        editType: 'calc',
        
    },
    showtickprefix: {
        valType: 'enumerated',
        values: ['all', 'first', 'last', 'none'],
        dflt: 'all',
        
        editType: 'calc',
        
    },
    ticksuffix: {
        valType: 'string',
        dflt: '',
        
        editType: 'calc',
        
    },
    showticksuffix: {
        valType: 'enumerated',
        values: ['all', 'first', 'last', 'none'],
        dflt: 'all',
        
        editType: 'calc',
        
    },
    showexponent: {
        valType: 'enumerated',
        values: ['all', 'first', 'last', 'none'],
        dflt: 'all',
        
        editType: 'calc',
        
    },
    exponentformat: {
        valType: 'enumerated',
        values: ['none', 'e', 'E', 'power', 'SI', 'B'],
        dflt: 'B',
        
        editType: 'calc',
        
    },
    separatethousands: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'calc',
        
    },
    tickformat: {
        valType: 'string',
        dflt: '',
        
        editType: 'calc',
        
    },
    tickformatstops: overrideAll(axesAttrs.tickformatstops, 'calc', 'from-root'),
    categoryorder: {
        valType: 'enumerated',
        values: [
            'trace', 'category ascending', 'category descending', 'array'
            /* , 'value ascending', 'value descending'*/ // value ascending / descending to be implemented later
        ],
        dflt: 'trace',
        
        editType: 'calc',
        
    },
    categoryarray: {
        valType: 'data_array',
        
        editType: 'calc',
        
    },
    labelpadding: {
        valType: 'integer',
        
        dflt: 10,
        editType: 'calc',
        
    },
    labelprefix: {
        valType: 'string',
        
        editType: 'calc',
        
    },
    labelsuffix: {
        valType: 'string',
        dflt: '',
        
        editType: 'calc',
        
    },
    // lines and grids
    showline: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'calc',
        
    },
    linecolor: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'calc',
        
    },
    linewidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'calc',
        
    },
    gridcolor: {
        valType: 'color',
        
        editType: 'calc',
        
    },
    gridwidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'calc',
        
    },
    showgrid: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'calc',
        
    },
    minorgridcount: {
        valType: 'integer',
        min: 0,
        dflt: 0,
        
        editType: 'calc',
        
    },
    minorgridwidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'calc',
        
    },
    minorgridcolor: {
        valType: 'color',
        dflt: colorAttrs.lightLine,
        
        editType: 'calc',
        
    },
    startline: {
        valType: 'boolean',
        
        editType: 'calc',
        
    },
    startlinecolor: {
        valType: 'color',
        
        editType: 'calc',
        
    },
    startlinewidth: {
        valType: 'number',
        dflt: 1,
        
        editType: 'calc',
        
    },
    endline: {
        valType: 'boolean',
        
        editType: 'calc',
        
    },
    endlinewidth: {
        valType: 'number',
        dflt: 1,
        
        editType: 'calc',
        
    },
    endlinecolor: {
        valType: 'color',
        
        editType: 'calc',
        
    },
    tick0: {
        valType: 'number',
        min: 0,
        dflt: 0,
        
        editType: 'calc',
        
    },
    dtick: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'calc',
        
    },
    arraytick0: {
        valType: 'integer',
        min: 0,
        dflt: 0,
        
        editType: 'calc',
        
    },
    arraydtick: {
        valType: 'integer',
        min: 1,
        dflt: 1,
        
        editType: 'calc',
        
    },

    _deprecated: {
        title: {
            valType: 'string',
            
            editType: 'calc',
            
        },
        titlefont: fontAttrs({
            editType: 'calc',
            
        }),
        titleoffset: {
            valType: 'number',
            
            dflt: 10,
            editType: 'calc',
            
        }
    },

    editType: 'calc'
};

},{"../../components/color/attributes":573,"../../plot_api/edit_types":728,"../../plots/cartesian/layout_attributes":757,"../../plots/font_attributes":771}],880:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var carpetAttrs = _dereq_('./attributes');

var addOpacity = _dereq_('../../components/color').addOpacity;
var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var handleTickValueDefaults = _dereq_('../../plots/cartesian/tick_value_defaults');
var handleTickLabelDefaults = _dereq_('../../plots/cartesian/tick_label_defaults');
var handleCategoryOrderDefaults = _dereq_('../../plots/cartesian/category_order_defaults');
var setConvert = _dereq_('../../plots/cartesian/set_convert');
var autoType = _dereq_('../../plots/cartesian/axis_autotype');

/**
 * options: object containing:
 *
 *  letter: 'a' or 'b'
 *  title: name of the axis (ie 'Colorbar') to go in default title
 *  name: axis object name (ie 'xaxis') if one should be stored
 *  font: the default font to inherit
 *  outerTicks: boolean, should ticks default to outside?
 *  showGrid: boolean, should gridlines be shown by default?
 *  data: the plot data to use in choosing auto type
 *  bgColor: the plot background color, to calculate default gridline colors
 */
module.exports = function handleAxisDefaults(containerIn, containerOut, options) {
    var letter = options.letter;
    var font = options.font || {};
    var attributes = carpetAttrs[letter + 'axis'];

    function coerce(attr, dflt) {
        return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
    }

    function coerce2(attr, dflt) {
        return Lib.coerce2(containerIn, containerOut, attributes, attr, dflt);
    }

    // set up some private properties
    if(options.name) {
        containerOut._name = options.name;
        containerOut._id = options.name;
    }

    // now figure out type and do some more initialization
    var axType = coerce('type');
    if(axType === '-') {
        if(options.data) setAutoType(containerOut, options.data);

        if(containerOut.type === '-') {
            containerOut.type = 'linear';
        }
        else {
            // copy autoType back to input axis
            // note that if this object didn't exist
            // in the input layout, we have to put it in
            // this happens in the main supplyDefaults function
            axType = containerIn.type = containerOut.type;
        }
    }

    coerce('smoothing');
    coerce('cheatertype');

    coerce('showticklabels');
    coerce('labelprefix', letter + ' = ');
    coerce('labelsuffix');
    coerce('showtickprefix');
    coerce('showticksuffix');

    coerce('separatethousands');
    coerce('tickformat');
    coerce('exponentformat');
    coerce('showexponent');
    coerce('categoryorder');

    coerce('tickmode');
    coerce('tickvals');
    coerce('ticktext');
    coerce('tick0');
    coerce('dtick');

    if(containerOut.tickmode === 'array') {
        coerce('arraytick0');
        coerce('arraydtick');
    }

    coerce('labelpadding');

    containerOut._hovertitle = letter;


    if(axType === 'date') {
        var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleDefaults');
        handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar);
    }

    // we need some of the other functions setConvert attaches, but for
    // path finding, override pixel scaling to simple passthrough (identity)
    setConvert(containerOut, options.fullLayout);
    containerOut.c2p = Lib.identity;

    var dfltColor = coerce('color', options.dfltColor);
    // if axis.color was provided, use it for fonts too; otherwise,
    // inherit from global font color in case that was provided.
    var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color;

    var title = coerce('title.text');
    if(title) {
        Lib.coerceFont(coerce, 'title.font', {
            family: font.family,
            size: Math.round(font.size * 1.2),
            color: dfltFontColor
        });
        coerce('title.offset');
    }

    coerce('tickangle');

    var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range));

    if(autoRange) coerce('rangemode');

    coerce('range');
    containerOut.cleanRange();

    coerce('fixedrange');

    handleTickValueDefaults(containerIn, containerOut, coerce, axType);
    handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options);
    handleCategoryOrderDefaults(containerIn, containerOut, coerce, {
        data: options.data,
        dataAttr: letter
    });

    var gridColor = coerce2('gridcolor', addOpacity(dfltColor, 0.3));
    var gridWidth = coerce2('gridwidth');
    var showGrid = coerce('showgrid');

    if(!showGrid) {
        delete containerOut.gridcolor;
        delete containerOut.gridwidth;
    }

    var startLineColor = coerce2('startlinecolor', dfltColor);
    var startLineWidth = coerce2('startlinewidth', gridWidth);
    var showStartLine = coerce('startline', containerOut.showgrid || !!startLineColor || !!startLineWidth);

    if(!showStartLine) {
        delete containerOut.startlinecolor;
        delete containerOut.startlinewidth;
    }

    var endLineColor = coerce2('endlinecolor', dfltColor);
    var endLineWidth = coerce2('endlinewidth', gridWidth);
    var showEndLine = coerce('endline', containerOut.showgrid || !!endLineColor || !!endLineWidth);

    if(!showEndLine) {
        delete containerOut.endlinecolor;
        delete containerOut.endlinewidth;
    }

    if(!showGrid) {
        delete containerOut.gridcolor;
        delete containerOut.gridWidth;
    } else {
        coerce('minorgridcount');
        coerce('minorgridwidth', gridWidth);
        coerce('minorgridcolor', addOpacity(gridColor, 0.06));

        if(!containerOut.minorgridcount) {
            delete containerOut.minorgridwidth;
            delete containerOut.minorgridcolor;
        }
    }

    if(containerOut.showticklabels === 'none') {
        delete containerOut.tickfont;
        delete containerOut.tickangle;
        delete containerOut.showexponent;
        delete containerOut.exponentformat;
        delete containerOut.tickformat;
        delete containerOut.showticksuffix;
        delete containerOut.showtickprefix;
    }

    if(!containerOut.showticksuffix) {
        delete containerOut.ticksuffix;
    }

    if(!containerOut.showtickprefix) {
        delete containerOut.tickprefix;
    }

    // It needs to be coerced, then something above overrides this deep in the axis code,
    // but no, we *actually* want to coerce this.
    coerce('tickmode');

    return containerOut;
};

function setAutoType(ax, data) {
    // new logic: let people specify any type they want,
    // only autotype if type is '-'
    if(ax.type !== '-') return;

    var id = ax._id;
    var axLetter = id.charAt(0);

    var calAttr = axLetter + 'calendar';
    var calendar = ax[calAttr];

    ax.type = autoType(data, calendar);
}

},{"../../components/color":574,"../../lib":697,"../../plots/cartesian/axis_autotype":746,"../../plots/cartesian/category_order_defaults":749,"../../plots/cartesian/set_convert":763,"../../plots/cartesian/tick_label_defaults":764,"../../plots/cartesian/tick_value_defaults":766,"../../registry":826,"./attributes":877}],881:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Axes = _dereq_('../../plots/cartesian/axes');
var isArray1D = _dereq_('../../lib').isArray1D;
var cheaterBasis = _dereq_('./cheater_basis');
var arrayMinmax = _dereq_('./array_minmax');
var calcGridlines = _dereq_('./calc_gridlines');
var calcLabels = _dereq_('./calc_labels');
var calcClipPath = _dereq_('./calc_clippath');
var clean2dArray = _dereq_('../heatmap/clean_2d_array');
var smoothFill2dArray = _dereq_('./smooth_fill_2d_array');
var convertColumnData = _dereq_('../heatmap/convert_column_xyz');
var setConvert = _dereq_('./set_convert');

module.exports = function calc(gd, trace) {
    var xa = Axes.getFromId(gd, trace.xaxis);
    var ya = Axes.getFromId(gd, trace.yaxis);
    var aax = trace.aaxis;
    var bax = trace.baxis;

    var x = trace.x;
    var y = trace.y;
    var cols = [];
    if(x && isArray1D(x)) cols.push('x');
    if(y && isArray1D(y)) cols.push('y');

    if(cols.length) {
        convertColumnData(trace, aax, bax, 'a', 'b', cols);
    }

    var a = trace._a = trace._a || trace.a;
    var b = trace._b = trace._b || trace.b;
    x = trace._x || trace.x;
    y = trace._y || trace.y;

    var t = {};

    if(trace._cheater) {
        var avals = aax.cheatertype === 'index' ? a.length : a;
        var bvals = bax.cheatertype === 'index' ? b.length : b;
        x = cheaterBasis(avals, bvals, trace.cheaterslope);
    }

    trace._x = x = clean2dArray(x);
    trace._y = y = clean2dArray(y);

    // Fill in any undefined values with elliptic smoothing. This doesn't take
    // into account the spacing of the values. That is, the derivatives should
    // be modified to use a and b values. It's not that hard, but this is already
    // moderate overkill for just filling in missing values.
    smoothFill2dArray(x, a, b);
    smoothFill2dArray(y, a, b);

    setConvert(trace);

    // create conversion functions that depend on the data
    trace.setScale();

    // This is a rather expensive scan. Nothing guarantees monotonicity,
    // so we need to scan through all data to get proper ranges:
    var xrange = arrayMinmax(x);
    var yrange = arrayMinmax(y);

    var dx = 0.5 * (xrange[1] - xrange[0]);
    var xc = 0.5 * (xrange[1] + xrange[0]);

    var dy = 0.5 * (yrange[1] - yrange[0]);
    var yc = 0.5 * (yrange[1] + yrange[0]);

    // Expand the axes to fit the plot, except just grow it by a factor of 1.3
    // because the labels should be taken into account except that's difficult
    // hence 1.3.
    var grow = 1.3;
    xrange = [xc - dx * grow, xc + dx * grow];
    yrange = [yc - dy * grow, yc + dy * grow];

    trace._extremes[xa._id] = Axes.findExtremes(xa, xrange, {padded: true});
    trace._extremes[ya._id] = Axes.findExtremes(ya, yrange, {padded: true});

    // Enumerate the gridlines, both major and minor, and store them on the trace
    // object:
    calcGridlines(trace, 'a', 'b');
    calcGridlines(trace, 'b', 'a');

    // Calculate the text labels for each major gridline and store them on the
    // trace object:
    calcLabels(trace, aax);
    calcLabels(trace, bax);

    // Tabulate points for the four segments that bound the axes so that we can
    // map to pixel coordinates in the plot function and create a clip rect:
    t.clipsegments = calcClipPath(trace._xctrl, trace._yctrl, aax, bax);

    t.x = x;
    t.y = y;
    t.a = a;
    t.b = b;

    return [t];
};

},{"../../lib":697,"../../plots/cartesian/axes":745,"../heatmap/clean_2d_array":947,"../heatmap/convert_column_xyz":949,"./array_minmax":876,"./calc_clippath":882,"./calc_gridlines":883,"./calc_labels":884,"./cheater_basis":886,"./set_convert":899,"./smooth_fill_2d_array":900}],882:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = function makeClipPath(xctrl, yctrl, aax, bax) {
    var i, x, y;
    var segments = [];

    var asmoothing = !!aax.smoothing;
    var bsmoothing = !!bax.smoothing;
    var nea1 = xctrl[0].length - 1;
    var neb1 = xctrl.length - 1;

    // Along the lower a axis:
    for(i = 0, x = [], y = []; i <= nea1; i++) {
        x[i] = xctrl[0][i];
        y[i] = yctrl[0][i];
    }
    segments.push({x: x, y: y, bicubic: asmoothing});

    // Along the upper b axis:
    for(i = 0, x = [], y = []; i <= neb1; i++) {
        x[i] = xctrl[i][nea1];
        y[i] = yctrl[i][nea1];
    }
    segments.push({x: x, y: y, bicubic: bsmoothing});

    // Backwards along the upper a axis:
    for(i = nea1, x = [], y = []; i >= 0; i--) {
        x[nea1 - i] = xctrl[neb1][i];
        y[nea1 - i] = yctrl[neb1][i];
    }
    segments.push({x: x, y: y, bicubic: asmoothing});

    // Backwards along the lower b axis:
    for(i = neb1, x = [], y = []; i >= 0; i--) {
        x[neb1 - i] = xctrl[i][0];
        y[neb1 - i] = yctrl[i][0];
    }
    segments.push({x: x, y: y, bicubic: bsmoothing});

    return segments;
};

},{}],883:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Axes = _dereq_('../../plots/cartesian/axes');
var extendFlat = _dereq_('../../lib/extend').extendFlat;

module.exports = function calcGridlines(trace, axisLetter, crossAxisLetter) {
    var i, j, j0;
    var eps, bounds, n1, n2, n, value, v;
    var j1, v0, v1, d;

    var data = trace['_' + axisLetter];
    var axis = trace[axisLetter + 'axis'];

    var gridlines = axis._gridlines = [];
    var minorgridlines = axis._minorgridlines = [];
    var boundarylines = axis._boundarylines = [];

    var crossData = trace['_' + crossAxisLetter];
    var crossAxis = trace[crossAxisLetter + 'axis'];

    if(axis.tickmode === 'array') {
        axis.tickvals = data.slice();
    }

    var xcp = trace._xctrl;
    var ycp = trace._yctrl;
    var nea = xcp[0].length;
    var neb = xcp.length;
    var na = trace._a.length;
    var nb = trace._b.length;

    Axes.prepTicks(axis);

    // don't leave tickvals in axis looking like an attribute
    if(axis.tickmode === 'array') delete axis.tickvals;

    // The default is an empty array that will cause the join to remove the gridline if
    // it's just disappeared:
    // axis._startline = axis._endline = [];

    // If the cross axis uses bicubic interpolation, then the grid
    // lines fall once every three expanded grid row/cols:
    var stride = axis.smoothing ? 3 : 1;

    function constructValueGridline(value) {
        var i, j, j0, tj, pxy, i0, ti, xy, dxydi0, dxydi1, dxydj0, dxydj1;
        var xpoints = [];
        var ypoints = [];
        var ret = {};
        // Search for the fractional grid index giving this line:
        if(axisLetter === 'b') {
            // For the position we use just the i-j coordinates:
            j = trace.b2j(value);

            // The derivatives for catmull-rom splines are discontinuous across cell
            // boundaries though, so we need to provide both the cell and the position
            // within the cell separately:
            j0 = Math.floor(Math.max(0, Math.min(nb - 2, j)));
            tj = j - j0;

            ret.length = nb;
            ret.crossLength = na;

            ret.xy = function(i) {
                return trace.evalxy([], i, j);
            };

            ret.dxy = function(i0, ti) {
                return trace.dxydi([], i0, j0, ti, tj);
            };

            for(i = 0; i < na; i++) {
                i0 = Math.min(na - 2, i);
                ti = i - i0;
                xy = trace.evalxy([], i, j);

                if(crossAxis.smoothing && i > 0) {
                    // First control point:
                    dxydi0 = trace.dxydi([], i - 1, j0, 0, tj);
                    xpoints.push(pxy[0] + dxydi0[0] / 3);
                    ypoints.push(pxy[1] + dxydi0[1] / 3);

                    // Second control point:
                    dxydi1 = trace.dxydi([], i - 1, j0, 1, tj);
                    xpoints.push(xy[0] - dxydi1[0] / 3);
                    ypoints.push(xy[1] - dxydi1[1] / 3);
                }

                xpoints.push(xy[0]);
                ypoints.push(xy[1]);

                pxy = xy;
            }
        } else {
            i = trace.a2i(value);
            i0 = Math.floor(Math.max(0, Math.min(na - 2, i)));
            ti = i - i0;

            ret.length = na;
            ret.crossLength = nb;

            ret.xy = function(j) {
                return trace.evalxy([], i, j);
            };

            ret.dxy = function(j0, tj) {
                return trace.dxydj([], i0, j0, ti, tj);
            };

            for(j = 0; j < nb; j++) {
                j0 = Math.min(nb - 2, j);
                tj = j - j0;
                xy = trace.evalxy([], i, j);

                if(crossAxis.smoothing && j > 0) {
                    // First control point:
                    dxydj0 = trace.dxydj([], i0, j - 1, ti, 0);
                    xpoints.push(pxy[0] + dxydj0[0] / 3);
                    ypoints.push(pxy[1] + dxydj0[1] / 3);

                    // Second control point:
                    dxydj1 = trace.dxydj([], i0, j - 1, ti, 1);
                    xpoints.push(xy[0] - dxydj1[0] / 3);
                    ypoints.push(xy[1] - dxydj1[1] / 3);
                }

                xpoints.push(xy[0]);
                ypoints.push(xy[1]);

                pxy = xy;
            }
        }

        ret.axisLetter = axisLetter;
        ret.axis = axis;
        ret.crossAxis = crossAxis;
        ret.value = value;
        ret.constvar = crossAxisLetter;
        ret.index = n;
        ret.x = xpoints;
        ret.y = ypoints;
        ret.smoothing = crossAxis.smoothing;

        return ret;
    }

    function constructArrayGridline(idx) {
        var j, i0, j0, ti, tj;
        var xpoints = [];
        var ypoints = [];
        var ret = {};
        ret.length = data.length;
        ret.crossLength = crossData.length;

        if(axisLetter === 'b') {
            j0 = Math.max(0, Math.min(nb - 2, idx));
            tj = Math.min(1, Math.max(0, idx - j0));

            ret.xy = function(i) {
                return trace.evalxy([], i, idx);
            };

            ret.dxy = function(i0, ti) {
                return trace.dxydi([], i0, j0, ti, tj);
            };

            // In the tickmode: array case, this operation is a simple
            // transfer of data:
            for(j = 0; j < nea; j++) {
                xpoints[j] = xcp[idx * stride][j];
                ypoints[j] = ycp[idx * stride][j];
            }
        } else {
            i0 = Math.max(0, Math.min(na - 2, idx));
            ti = Math.min(1, Math.max(0, idx - i0));

            ret.xy = function(j) {
                return trace.evalxy([], idx, j);
            };

            ret.dxy = function(j0, tj) {
                return trace.dxydj([], i0, j0, ti, tj);
            };

            // In the tickmode: array case, this operation is a simple
            // transfer of data:
            for(j = 0; j < neb; j++) {
                xpoints[j] = xcp[j][idx * stride];
                ypoints[j] = ycp[j][idx * stride];
            }
        }

        ret.axisLetter = axisLetter;
        ret.axis = axis;
        ret.crossAxis = crossAxis;
        ret.value = data[idx];
        ret.constvar = crossAxisLetter;
        ret.index = idx;
        ret.x = xpoints;
        ret.y = ypoints;
        ret.smoothing = crossAxis.smoothing;

        return ret;
    }

    if(axis.tickmode === 'array') {
        // var j0 = axis.startline ? 1 : 0;
        // var j1 = data.length - (axis.endline ? 1 : 0);

        eps = 5e-15;
        bounds = [
            Math.floor(((data.length - 1) - axis.arraytick0) / axis.arraydtick * (1 + eps)),
            Math.ceil((- axis.arraytick0) / axis.arraydtick / (1 + eps))
        ].sort(function(a, b) {return a - b;});

        // Unpack sorted values so we can be sure to avoid infinite loops if something
        // is backwards:
        n1 = bounds[0] - 1;
        n2 = bounds[1] + 1;

        // If the axes fall along array lines, then this is a much simpler process since
        // we already have all the control points we need
        for(n = n1; n < n2; n++) {
            j = axis.arraytick0 + axis.arraydtick * n;
            if(j < 0 || j > data.length - 1) continue;
            gridlines.push(extendFlat(constructArrayGridline(j), {
                color: axis.gridcolor,
                width: axis.gridwidth
            }));
        }

        for(n = n1; n < n2; n++) {
            j0 = axis.arraytick0 + axis.arraydtick * n;
            j1 = Math.min(j0 + axis.arraydtick, data.length - 1);

            // TODO: fix the bounds computation so we don't have to do a large range and then throw
            // out unneeded numbers
            if(j0 < 0 || j0 > data.length - 1) continue;
            if(j1 < 0 || j1 > data.length - 1) continue;

            v0 = data[j0];
            v1 = data[j1];

            for(i = 0; i < axis.minorgridcount; i++) {
                d = j1 - j0;

                // TODO: fix the bounds computation so we don't have to do a large range and then throw
                // out unneeded numbers
                if(d <= 0) continue;

                // XXX: This calculation isn't quite right. Off by one somewhere?
                v = v0 + (v1 - v0) * (i + 1) / (axis.minorgridcount + 1) * (axis.arraydtick / d);

                // TODO: fix the bounds computation so we don't have to do a large range and then throw
                // out unneeded numbers
                if(v < data[0] || v > data[data.length - 1]) continue;
                minorgridlines.push(extendFlat(constructValueGridline(v), {
                    color: axis.minorgridcolor,
                    width: axis.minorgridwidth
                }));
            }
        }

        if(axis.startline) {
            boundarylines.push(extendFlat(constructArrayGridline(0), {
                color: axis.startlinecolor,
                width: axis.startlinewidth
            }));
        }

        if(axis.endline) {
            boundarylines.push(extendFlat(constructArrayGridline(data.length - 1), {
                color: axis.endlinecolor,
                width: axis.endlinewidth
            }));
        }
    } else {
        // If the lines do not fall along the axes, then we have to interpolate
        // the contro points and so some math to figure out where the lines are
        // in the first place.

        // Compute the integer boudns of tick0 + n * dtick that fall within the range
        // (roughly speaking):
        // Give this a nice generous epsilon. We use at as * (1 + eps) in order to make
        // inequalities a little tolerant in a more or less correct manner:
        eps = 5e-15;
        bounds = [
            Math.floor((data[data.length - 1] - axis.tick0) / axis.dtick * (1 + eps)),
            Math.ceil((data[0] - axis.tick0) / axis.dtick / (1 + eps))
        ].sort(function(a, b) {return a - b;});

        // Unpack sorted values so we can be sure to avoid infinite loops if something
        // is backwards:
        n1 = bounds[0];
        n2 = bounds[1];

        for(n = n1; n <= n2; n++) {
            value = axis.tick0 + axis.dtick * n;

            gridlines.push(extendFlat(constructValueGridline(value), {
                color: axis.gridcolor,
                width: axis.gridwidth
            }));
        }

        for(n = n1 - 1; n < n2 + 1; n++) {
            value = axis.tick0 + axis.dtick * n;

            for(i = 0; i < axis.minorgridcount; i++) {
                v = value + axis.dtick * (i + 1) / (axis.minorgridcount + 1);
                if(v < data[0] || v > data[data.length - 1]) continue;
                minorgridlines.push(extendFlat(constructValueGridline(v), {
                    color: axis.minorgridcolor,
                    width: axis.minorgridwidth
                }));
            }
        }

        if(axis.startline) {
            boundarylines.push(extendFlat(constructValueGridline(data[0]), {
                color: axis.startlinecolor,
                width: axis.startlinewidth
            }));
        }

        if(axis.endline) {
            boundarylines.push(extendFlat(constructValueGridline(data[data.length - 1]), {
                color: axis.endlinecolor,
                width: axis.endlinewidth
            }));
        }
    }
};

},{"../../lib/extend":687,"../../plots/cartesian/axes":745}],884:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Axes = _dereq_('../../plots/cartesian/axes');
var extendFlat = _dereq_('../../lib/extend').extendFlat;

module.exports = function calcLabels(trace, axis) {
    var i, tobj, prefix, suffix, gridline;

    var labels = axis._labels = [];
    var gridlines = axis._gridlines;

    for(i = 0; i < gridlines.length; i++) {
        gridline = gridlines[i];

        if(['start', 'both'].indexOf(axis.showticklabels) !== -1) {
            tobj = Axes.tickText(axis, gridline.value);

            extendFlat(tobj, {
                prefix: prefix,
                suffix: suffix,
                endAnchor: true,
                xy: gridline.xy(0),
                dxy: gridline.dxy(0, 0),
                axis: gridline.axis,
                length: gridline.crossAxis.length,
                font: gridline.axis.tickfont,
                isFirst: i === 0,
                isLast: i === gridlines.length - 1
            });

            labels.push(tobj);
        }

        if(['end', 'both'].indexOf(axis.showticklabels) !== -1) {
            tobj = Axes.tickText(axis, gridline.value);

            extendFlat(tobj, {
                endAnchor: false,
                xy: gridline.xy(gridline.crossLength - 1),
                dxy: gridline.dxy(gridline.crossLength - 2, 1),
                axis: gridline.axis,
                length: gridline.crossAxis.length,
                font: gridline.axis.tickfont,
                isFirst: i === 0,
                isLast: i === gridlines.length - 1
            });

            labels.push(tobj);
        }
    }
};

},{"../../lib/extend":687,"../../plots/cartesian/axes":745}],885:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/*
 * Compute the tangent vector according to catmull-rom cubic splines (centripetal,
 * I think). That differs from the control point in two ways:
 *   1. It is a vector, not a position relative to the point
 *   2. the vector is longer than the position relative to p1 by a factor of 3
 *
 * Close to the boundaries, we'll use these as *quadratic control points, so that
 * to make a nice grid, we'll need to divide the tangent by 2 instead of 3. (The
 * math works out this way if you work through the bezier derivatives)
 */
var CatmullRomExp = 0.5;
module.exports = function makeControlPoints(p0, p1, p2, smoothness) {
    var d1x = p0[0] - p1[0];
    var d1y = p0[1] - p1[1];
    var d2x = p2[0] - p1[0];
    var d2y = p2[1] - p1[1];
    var d1a = Math.pow(d1x * d1x + d1y * d1y, CatmullRomExp / 2);
    var d2a = Math.pow(d2x * d2x + d2y * d2y, CatmullRomExp / 2);
    var numx = (d2a * d2a * d1x - d1a * d1a * d2x) * smoothness;
    var numy = (d2a * d2a * d1y - d1a * d1a * d2y) * smoothness;
    var denom1 = d2a * (d1a + d2a) * 3;
    var denom2 = d1a * (d1a + d2a) * 3;

    return [[
        p1[0] + (denom1 && numx / denom1),
        p1[1] + (denom1 && numy / denom1)
    ], [
        p1[0] - (denom2 && numx / denom2),
        p1[1] - (denom2 && numy / denom2)
    ]];
};

},{}],886:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;

/*
 * Construct a 2D array of cheater values given a, b, and a slope.
 * If
 */
module.exports = function(a, b, cheaterslope) {
    var i, j, ascal, bscal, aval, bval;
    var data = [];

    var na = isArrayOrTypedArray(a) ? a.length : a;
    var nb = isArrayOrTypedArray(b) ? b.length : b;
    var adata = isArrayOrTypedArray(a) ? a : null;
    var bdata = isArrayOrTypedArray(b) ? b : null;

    // If we're using data, scale it so that for data that's just barely
    // not evenly spaced, the switch to value-based indexing is continuous.
    // This means evenly spaced data should look the same whether value
    // or index cheatertype.
    if(adata) {
        ascal = (adata.length - 1) / (adata[adata.length - 1] - adata[0]) / (na - 1);
    }

    if(bdata) {
        bscal = (bdata.length - 1) / (bdata[bdata.length - 1] - bdata[0]) / (nb - 1);
    }

    var xval;
    var xmin = Infinity;
    var xmax = -Infinity;
    for(j = 0; j < nb; j++) {
        data[j] = [];
        bval = bdata ? (bdata[j] - bdata[0]) * bscal : j / (nb - 1);
        for(i = 0; i < na; i++) {
            aval = adata ? (adata[i] - adata[0]) * ascal : i / (na - 1);
            xval = aval - bval * cheaterslope;
            xmin = Math.min(xval, xmin);
            xmax = Math.max(xval, xmax);
            data[j][i] = xval;
        }
    }

    // Normalize cheater values to the 0-1 range. This comes into play when you have
    // multiple cheater plots. After careful consideration, it seems better if cheater
    // values are normalized to a consistent range. Otherwise one cheater affects the
    // layout of other cheaters on the same axis.
    var slope = 1.0 / (xmax - xmin);
    var offset = -xmin * slope;
    for(j = 0; j < nb; j++) {
        for(i = 0; i < na; i++) {
            data[j][i] = slope * data[j][i] + offset;
        }
    }

    return data;
};

},{"../../lib":697}],887:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var makeControlPoints = _dereq_('./catmull_rom');
var ensureArray = _dereq_('../../lib').ensureArray;

/*
 * Turns a coarse grid into a fine grid with control points.
 *
 * Here's an ASCII representation:
 *
 *       o ----- o ----- o ----- o
 *       |       |       |       |
 *       |       |       |       |
 *       |       |       |       |
 *       o ----- o ----- o ----- o
 *       |       |       |       |
 *       |       |       |       |
 *    ^  |       |       |       |
 *    |  o ----- o ----- o ----- o
 *  b |  |       |       |       |
 *    |  |       |       |       |
 *    |  |       |       |       |
 *       o ----- o ----- o ----- o
 *         ------>
 *           a
 *
 * First of all, note that we want to do this in *cartesian* space. This means
 * we might run into problems when there are extreme differences in x/y scaling,
 * but the alternative is that the topology of the contours might actually be
 * view-dependent, which seems worse. As a fallback, the only parameter that
 * actually affects the result is the *aspect ratio*, so that we can at least
 * improve the situation a bit without going all the way to screen coordinates.
 *
 * This function flattens the points + tangents  into a slightly denser grid of
 * *control points*. The resulting grid looks like this:
 *
 *       9 +--o-o--+ -o-o--+--o-o--+
 *       8 o  o o  o  o o  o  o o  o
 *         |       |       |       |
 *       7 o  o o  o  o o  o  o o  o
 *       6 +--o-o--+ -o-o--+--o-o--+
 *       5 o  o o  o  o o  o  o o  o
 *         |       |       |       |
 *    ^  4 o  o o  o  o o  o  o o  o
 *    |  3 +--o-o--+ -o-o--+--o-o--+
 *  b |  2 o  o o  o  o o  o  o o  o
 *    |    |       |       |       |
 *    |  1 o  o o  o  o o  o  o o  o
 *       0 +--o-o--+ -o-o--+--o-o--+
 *         0  1 2  3  4 5  6  7 8  9
 *         ------>
 *           a
 *
 * where `o`s represent newly-computed control points. the resulting dimension is
 *
 *     (m - 1) * 3 + 1
 *   = 3 * m - 2
 *
 * We could simply store the tangents separately, but that's a nightmare to organize
 * in two dimensions since we'll be slicing grid lines in both directions and since
 * that basically requires very nearly just as much storage as just storing the dense
 * grid.
 *
 * Wow!
 */


/*
 * Catmull-rom is biased at the boundaries toward the interior and we actually
 * can't use catmull-rom to compute the control point closest to (but inside)
 * the boundary.
 *
 * A note on plotly's spline interpolation. It uses the catmull rom control point
 * closest to the boundary *as* a quadratic control point. This seems incorrect,
 * so I've elected not to follow that. Given control points 0 and 1, regular plotly
 * splines give *equivalent* cubic control points:
 *
 * Input:
 *
 *   boundary
 *     |                    |
 *     p0           p2      p3    --> interior
 *     0.0          0.667   1.0
 *     |                    |
 *
 * Cubic-equivalent of what plotly splines draw::
 *
 *   boundary
 *     |                    |
 *     p0   p1      p2      p3    --> interior
 *     0.0  0.4444  0.8888  1.0
 *     |                    |
 *
 * What this function fills in:
 *
 *   boundary
 *     |                    |
 *     p0    p1     p2      p3    --> interior
 *     0.0   0.333  0.667   1.0
 *     |                    |
 *
 * Parameters:
 *   p0: boundary point
 *   p2: catmull rom point based on computation at p3
 *   p3: first grid point
 *
 * Of course it works whichever way it's oriented; you just need to interpret the
 * input/output accordingly.
 */
function inferCubicControlPoint(p0, p2, p3) {
    // Extend p1 away from p0 by 50%. This is the equivalent quadratic point that
    // would give the same slope as catmull rom at p0.
    var p2e0 = -0.5 * p3[0] + 1.5 * p2[0];
    var p2e1 = -0.5 * p3[1] + 1.5 * p2[1];

    return [
        (2 * p2e0 + p0[0]) / 3,
        (2 * p2e1 + p0[1]) / 3,
    ];
}

module.exports = function computeControlPoints(xe, ye, x, y, asmoothing, bsmoothing) {
    var i, j, ie, je, xej, yej, xj, yj, cp, p1;
    // At this point, we know these dimensions are correct and representative of
    // the whole 2D arrays:
    var na = x[0].length;
    var nb = x.length;

    // (n)umber of (e)xpanded points:
    var nea = asmoothing ? 3 * na - 2 : na;
    var neb = bsmoothing ? 3 * nb - 2 : nb;

    xe = ensureArray(xe, neb);
    ye = ensureArray(ye, neb);

    for(ie = 0; ie < neb; ie++) {
        xe[ie] = ensureArray(xe[ie], nea);
        ye[ie] = ensureArray(ye[ie], nea);
    }

    // This loop fills in the X'd points:
    //
    //    .       .       .       .
    //    .       .       .       .
    //    |       |       |       |
    //    |       |       |       |
    //    X ----- X ----- X ----- X
    //    |       |       |       |
    //    |       |       |       |
    //    |       |       |       |
    //    X ----- X ----- X ----- X
    //
    //
    // ie = (i) (e)xpanded:
    for(j = 0, je = 0; j < nb; j++, je += bsmoothing ? 3 : 1) {
        xej = xe[je];
        yej = ye[je];
        xj = x[j];
        yj = y[j];

        // je = (j) (e)xpanded:
        for(i = 0, ie = 0; i < na; i++, ie += asmoothing ? 3 : 1) {
            xej[ie] = xj[i];
            yej[ie] = yj[i];
        }
    }

    if(asmoothing) {
        // If there's a-smoothing, this loop fills in the X'd points with catmull-rom
        // control points computed along the a-axis:
        //     .       .       .       .
        //     .       .       .       .
        //     |       |       |       |
        //     |       |       |       |
        //     o -Y-X- o -X-X- o -X-Y- o
        //     |       |       |       |
        //     |       |       |       |
        //     |       |       |       |
        //     o -Y-X- o -X-X- o -X-Y- o
        //
        // i:  0       1       2       3
        // ie: 0  1 3  3  4 5  6  7 8  9
        //
        //           ------>
        //             a
        //
        for(j = 0, je = 0; j < nb; j++, je += bsmoothing ? 3 : 1) {
            // Fill in the points marked X for this a-row:
            for(i = 1, ie = 3; i < na - 1; i++, ie += 3) {
                cp = makeControlPoints(
                    [x[j][i - 1], y[j][i - 1]],
                    [x[j][i ], y[j][i]],
                    [x[j][i + 1], y[j][i + 1]],
                    asmoothing
                );

                xe[je][ie - 1] = cp[0][0];
                ye[je][ie - 1] = cp[0][1];
                xe[je][ie + 1] = cp[1][0];
                ye[je][ie + 1] = cp[1][1];
            }

            // The very first cubic interpolation point (to the left for i = 1 above) is
            // used as a *quadratic* interpolation point by the spline drawing function
            // which isn't really correct. But for the sake of consistency, we'll use it
            // as such. Since we're using cubic splines, that means we need to shorten the
            // tangent by 1/3 and also construct a new cubic spline control point 1/3 from
            // the original to the i = 0 point.
            p1 = inferCubicControlPoint(
                [xe[je][0], ye[je][0]],
                [xe[je][2], ye[je][2]],
                [xe[je][3], ye[je][3]]
            );
            xe[je][1] = p1[0];
            ye[je][1] = p1[1];

            // Ditto last points, sans explanation:
            p1 = inferCubicControlPoint(
                [xe[je][nea - 1], ye[je][nea - 1]],
                [xe[je][nea - 3], ye[je][nea - 3]],
                [xe[je][nea - 4], ye[je][nea - 4]]
            );
            xe[je][nea - 2] = p1[0];
            ye[je][nea - 2] = p1[1];
        }
    }

    if(bsmoothing) {
        // If there's a-smoothing, this loop fills in the X'd points with catmull-rom
        // control points computed along the b-axis:
        //     .       .       .       .
        //     X  X X  X  X X  X  X X  X
        //     |       |       |       |
        //     X  X X  X  X X  X  X X  X
        //     o -o-o- o -o-o- o -o-o- o
        //     X  X X  X  X X  X  X X  X
        //     |       |       |       |
        //     Y  Y Y  Y  Y Y  Y  Y Y  Y
        //     o -o-o- o -o-o- o -o-o- o
        //
        // i:  0       1       2       3
        // ie: 0  1 3  3  4 5  6  7 8  9
        //
        //           ------>
        //             a
        //
        for(ie = 0; ie < nea; ie++) {
            for(je = 3; je < neb - 3; je += 3) {
                cp = makeControlPoints(
                    [xe[je - 3][ie], ye[je - 3][ie]],
                    [xe[je][ie], ye[je][ie]],
                    [xe[je + 3][ie], ye[je + 3][ie]],
                    bsmoothing
                );

                xe[je - 1][ie] = cp[0][0];
                ye[je - 1][ie] = cp[0][1];
                xe[je + 1][ie] = cp[1][0];
                ye[je + 1][ie] = cp[1][1];
            }
            // Do the same boundary condition magic for these control points marked Y above:
            p1 = inferCubicControlPoint(
                [xe[0][ie], ye[0][ie]],
                [xe[2][ie], ye[2][ie]],
                [xe[3][ie], ye[3][ie]]
            );
            xe[1][ie] = p1[0];
            ye[1][ie] = p1[1];

            p1 = inferCubicControlPoint(
                [xe[neb - 1][ie], ye[neb - 1][ie]],
                [xe[neb - 3][ie], ye[neb - 3][ie]],
                [xe[neb - 4][ie], ye[neb - 4][ie]]
            );
            xe[neb - 2][ie] = p1[0];
            ye[neb - 2][ie] = p1[1];
        }
    }

    if(asmoothing && bsmoothing) {
        // Do one more pass, this time recomputing exactly what we just computed.
        // It's overdetermined since we're peforming catmull-rom in two directions,
        // so we'll just average the overdetermined. These points don't lie along the
        // grid lines, so note that only grid lines will follow normal plotly spline
        // interpolation.
        //
        // Unless of course there was no b smoothing. Then these intermediate points
        // don't actually exist and this section is bypassed.
        //     .       .       .       .
        //     o  X X  o  X X  o  X X  o
        //     |       |       |       |
        //     o  X X  o  X X  o  X X  o
        //     o -o-o- o -o-o- o -o-o- o
        //     o  X X  o  X X  o  X X  o
        //     |       |       |       |
        //     o  Y Y  o  Y Y  o  Y Y  o
        //     o -o-o- o -o-o- o -o-o- o
        //
        // i:  0       1       2       3
        // ie: 0  1 3  3  4 5  6  7 8  9
        //
        //           ------>
        //             a
        //
        for(je = 1; je < neb; je += (je + 1) % 3 === 0 ? 2 : 1) {
            // Fill in the points marked X for this a-row:
            for(ie = 3; ie < nea - 3; ie += 3) {
                cp = makeControlPoints(
                    [xe[je][ie - 3], ye[je][ie - 3]],
                    [xe[je][ie], ye[je][ie]],
                    [xe[je][ie + 3], ye[je][ie + 3]],
                    asmoothing
                );

                xe[je][ie - 1] = 0.5 * (xe[je][ie - 1] + cp[0][0]);
                ye[je][ie - 1] = 0.5 * (ye[je][ie - 1] + cp[0][1]);
                xe[je][ie + 1] = 0.5 * (xe[je][ie + 1] + cp[1][0]);
                ye[je][ie + 1] = 0.5 * (ye[je][ie + 1] + cp[1][1]);
            }

            // This case is just slightly different. The computation is the same,
            // but having computed this, we'll average with the existing result.
            p1 = inferCubicControlPoint(
                [xe[je][0], ye[je][0]],
                [xe[je][2], ye[je][2]],
                [xe[je][3], ye[je][3]]
            );
            xe[je][1] = 0.5 * (xe[je][1] + p1[0]);
            ye[je][1] = 0.5 * (ye[je][1] + p1[1]);

            p1 = inferCubicControlPoint(
                [xe[je][nea - 1], ye[je][nea - 1]],
                [xe[je][nea - 3], ye[je][nea - 3]],
                [xe[je][nea - 4], ye[je][nea - 4]]
            );
            xe[je][nea - 2] = 0.5 * (xe[je][nea - 2] + p1[0]);
            ye[je][nea - 2] = 0.5 * (ye[je][nea - 2] + p1[1]);
        }
    }

    return [xe, ye];
};

},{"../../lib":697,"./catmull_rom":885}],888:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = {
    RELATIVE_CULL_TOLERANCE: 1e-6
};

},{}],889:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/*
 * Evaluates the derivative of a list of control point arrays. That is, it expects an array or arrays
 * that are expanded relative to the raw data to include the bicubic control points, if applicable. If
 * only linear interpolation is desired, then the data points correspond 1-1 along that axis to the
 * data itself. Since it's catmull-rom splines in either direction note in particular that the
 * derivatives are discontinuous across cell boundaries. That's the reason you need both the *cell*
 * and the *point within the cell*.
 *
 * Also note that the discontinuity of the derivative is in magnitude only. The direction *is*
 * continuous across cell boundaries.
 *
 * For example, to compute the derivative of the xcoordinate halfway betwen the 7 and 8th i-gridpoints
 * and the 10th and 11th j-gridpoints given bicubic smoothing in both dimensions, you'd write:
 *
 *     var deriv = createIDerivativeEvaluator([x], 1, 1);
 *
 *     var dxdi = deriv([], 7, 10, 0.5, 0.5);
 *     // => [0.12345]
 *
 * Since there'd be a bunch of duplicate computation to compute multiple derivatives, you can double
 * this up by providing more arrays:
 *
 *     var deriv = createIDerivativeEvaluator([x, y], 1, 1);
 *
 *     var dxdi = deriv([], 7, 10, 0.5, 0.5);
 *     // => [0.12345, 0.78910]
 *
 * NB: It's presumed that at this point all data has been sanitized and is valid numerical data arrays
 * of the correct dimension.
 */
module.exports = function(arrays, asmoothing, bsmoothing) {
    if(asmoothing && bsmoothing) {
        return function(out, i0, j0, u, v) {
            if(!out) out = [];
            var f0, f1, f2, f3, ak, k;

            // Since it's a grid of control points, the actual indices are * 3:
            i0 *= 3;
            j0 *= 3;

            // Precompute some numbers:
            var u2 = u * u;
            var ou = 1 - u;
            var ou2 = ou * ou;
            var ouu2 = ou * u * 2;
            var a = -3 * ou2;
            var b = 3 * (ou2 - ouu2);
            var c = 3 * (ouu2 - u2);
            var d = 3 * u2;

            var v2 = v * v;
            var v3 = v2 * v;
            var ov = 1 - v;
            var ov2 = ov * ov;
            var ov3 = ov2 * ov;

            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];
                // Compute the derivatives in the u-direction:
                f0 = a * ak[j0 ][i0] + b * ak[j0 ][i0 + 1] + c * ak[j0 ][i0 + 2] + d * ak[j0 ][i0 + 3];
                f1 = a * ak[j0 + 1][i0] + b * ak[j0 + 1][i0 + 1] + c * ak[j0 + 1][i0 + 2] + d * ak[j0 + 1][i0 + 3];
                f2 = a * ak[j0 + 2][i0] + b * ak[j0 + 2][i0 + 1] + c * ak[j0 + 2][i0 + 2] + d * ak[j0 + 2][i0 + 3];
                f3 = a * ak[j0 + 3][i0] + b * ak[j0 + 3][i0 + 1] + c * ak[j0 + 3][i0 + 2] + d * ak[j0 + 3][i0 + 3];

                // Now just interpolate in the v-direction since it's all separable:
                out[k] = ov3 * f0 + 3 * (ov2 * v * f1 + ov * v2 * f2) + v3 * f3;
            }

            return out;
        };
    } else if(asmoothing) {
        // Handle smooth in the a-direction but linear in the b-direction by performing four
        // linear interpolations followed by one cubic interpolation of the result
        return function(out, i0, j0, u, v) {
            if(!out) out = [];
            var f0, f1, k, ak;
            i0 *= 3;
            var u2 = u * u;
            var ou = 1 - u;
            var ou2 = ou * ou;
            var ouu2 = ou * u * 2;
            var a = -3 * ou2;
            var b = 3 * (ou2 - ouu2);
            var c = 3 * (ouu2 - u2);
            var d = 3 * u2;
            var ov = 1 - v;
            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];
                f0 = a * ak[j0 ][i0] + b * ak[j0 ][i0 + 1] + c * ak[j0 ][i0 + 2] + d * ak[j0 ][i0 + 3];
                f1 = a * ak[j0 + 1][i0] + b * ak[j0 + 1][i0 + 1] + c * ak[j0 + 1][i0 + 2] + d * ak[j0 + 1][i0 + 3];

                out[k] = ov * f0 + v * f1;
            }
            return out;
        };
    } else if(bsmoothing) {
        // Same as the above case, except reversed. I've disabled the no-unused vars rule
        // so that this function is fully interpolation-agnostic. Otherwise it would need
        // to be called differently in different cases. Which wouldn't be the worst, but
        /* eslint-disable no-unused-vars */
        return function(out, i0, j0, u, v) {
        /* eslint-enable no-unused-vars */
            if(!out) out = [];
            var f0, f1, f2, f3, k, ak;
            j0 *= 3;
            var v2 = v * v;
            var v3 = v2 * v;
            var ov = 1 - v;
            var ov2 = ov * ov;
            var ov3 = ov2 * ov;
            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];
                f0 = ak[j0][i0 + 1] - ak[j0][i0];
                f1 = ak[j0 + 1][i0 + 1] - ak[j0 + 1][i0];
                f2 = ak[j0 + 2][i0 + 1] - ak[j0 + 2][i0];
                f3 = ak[j0 + 3][i0 + 1] - ak[j0 + 3][i0];

                out[k] = ov3 * f0 + 3 * (ov2 * v * f1 + ov * v2 * f2) + v3 * f3;
            }
            return out;
        };
    } else {
        // Finally, both directions are linear:
        /* eslint-disable no-unused-vars */
        return function(out, i0, j0, u, v) {
        /* eslint-enable no-unused-vars */
            if(!out) out = [];
            var f0, f1, k, ak;
            var ov = 1 - v;
            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];
                f0 = ak[j0][i0 + 1] - ak[j0][i0];
                f1 = ak[j0 + 1][i0 + 1] - ak[j0 + 1][i0];

                out[k] = ov * f0 + v * f1;
            }
            return out;
        };
    }
};

},{}],890:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function(arrays, asmoothing, bsmoothing) {
    if(asmoothing && bsmoothing) {
        return function(out, i0, j0, u, v) {
            if(!out) out = [];
            var f0, f1, f2, f3, ak, k;

            // Since it's a grid of control points, the actual indices are * 3:
            i0 *= 3;
            j0 *= 3;

            // Precompute some numbers:
            var u2 = u * u;
            var u3 = u2 * u;
            var ou = 1 - u;
            var ou2 = ou * ou;
            var ou3 = ou2 * ou;

            var v2 = v * v;
            var ov = 1 - v;
            var ov2 = ov * ov;
            var ovv2 = ov * v * 2;
            var a = -3 * ov2;
            var b = 3 * (ov2 - ovv2);
            var c = 3 * (ovv2 - v2);
            var d = 3 * v2;

            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];

                // Compute the derivatives in the v-direction:
                f0 = a * ak[j0][i0] + b * ak[j0 + 1][i0] + c * ak[j0 + 2][i0] + d * ak[j0 + 3][i0];
                f1 = a * ak[j0][i0 + 1] + b * ak[j0 + 1][i0 + 1] + c * ak[j0 + 2][i0 + 1] + d * ak[j0 + 3][i0 + 1];
                f2 = a * ak[j0][i0 + 2] + b * ak[j0 + 1][i0 + 2] + c * ak[j0 + 2][i0 + 2] + d * ak[j0 + 3][i0 + 2];
                f3 = a * ak[j0][i0 + 3] + b * ak[j0 + 1][i0 + 3] + c * ak[j0 + 2][i0 + 3] + d * ak[j0 + 3][i0 + 3];

                // Now just interpolate in the v-direction since it's all separable:
                out[k] = ou3 * f0 + 3 * (ou2 * u * f1 + ou * u2 * f2) + u3 * f3;
            }

            return out;
        };
    } else if(asmoothing) {
        // Handle smooth in the a-direction but linear in the b-direction by performing four
        // linear interpolations followed by one cubic interpolation of the result
        return function(out, i0, j0, v, u) {
            if(!out) out = [];
            var f0, f1, f2, f3, k, ak;
            i0 *= 3;
            var u2 = u * u;
            var u3 = u2 * u;
            var ou = 1 - u;
            var ou2 = ou * ou;
            var ou3 = ou2 * ou;
            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];

                f0 = ak[j0 + 1][i0] - ak[j0][i0];
                f1 = ak[j0 + 1][i0 + 1] - ak[j0][i0 + 1];
                f2 = ak[j0 + 1][i0 + 2] - ak[j0][i0 + 2];
                f3 = ak[j0 + 1][i0 + 3] - ak[j0][i0 + 3];

                out[k] = ou3 * f0 + 3 * (ou2 * u * f1 + ou * u2 * f2) + u3 * f3;

                // mathematically equivalent:
                // f0 = ou3 * ak[j0    ][i0] + 3 * (ou2 * u * ak[j0    ][i0 + 1] + ou * u2 * ak[j0    ][i0 + 2]) + u3 * ak[j0    ][i0 + 3];
                // f1 = ou3 * ak[j0 + 1][i0] + 3 * (ou2 * u * ak[j0 + 1][i0 + 1] + ou * u2 * ak[j0 + 1][i0 + 2]) + u3 * ak[j0 + 1][i0 + 3];
                // out[k] = f1 - f0;
            }
            return out;
        };
    } else if(bsmoothing) {
        // Same as the above case, except reversed:
        /* eslint-disable no-unused-vars */
        return function(out, i0, j0, u, v) {
        /* eslint-enable no-unused-vars */
            if(!out) out = [];
            var f0, f1, k, ak;
            j0 *= 3;
            var ou = 1 - u;
            var v2 = v * v;
            var ov = 1 - v;
            var ov2 = ov * ov;
            var ovv2 = ov * v * 2;
            var a = -3 * ov2;
            var b = 3 * (ov2 - ovv2);
            var c = 3 * (ovv2 - v2);
            var d = 3 * v2;
            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];
                f0 = a * ak[j0][i0] + b * ak[j0 + 1][i0] + c * ak[j0 + 2][i0] + d * ak[j0 + 3][i0];
                f1 = a * ak[j0][i0 + 1] + b * ak[j0 + 1][i0 + 1] + c * ak[j0 + 2][i0 + 1] + d * ak[j0 + 3][i0 + 1];

                out[k] = ou * f0 + u * f1;
            }
            return out;
        };
    } else {
        // Finally, both directions are linear:
        /* eslint-disable no-unused-vars */
        return function(out, i0, j0, v, u) {
        /* eslint-enable no-unused-vars */
            if(!out) out = [];
            var f0, f1, k, ak;
            var ov = 1 - v;
            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];
                f0 = ak[j0 + 1][i0] - ak[j0][i0];
                f1 = ak[j0 + 1][i0 + 1] - ak[j0][i0 + 1];

                out[k] = ov * f0 + v * f1;
            }
            return out;
        };
    }

};

},{}],891:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/*
 * Return a function that evaluates a set of linear or bicubic control points.
 * This will get evaluated a lot, so we'll at least do a bit of extra work to
 * flatten some of the choices. In particular, we'll unroll the linear/bicubic
 * combinations and we'll allow computing results in parallel to cut down
 * on repeated arithmetic.
 *
 * Take note that we don't search for the correct range in this function. The
 * reason is for consistency due to the corrresponding derivative function. In
 * particular, the derivatives aren't continuous across cells, so it's important
 * to be able control whether the derivative at a cell boundary is approached
 * from one side or the other.
 */
module.exports = function(arrays, na, nb, asmoothing, bsmoothing) {
    var imax = na - 2;
    var jmax = nb - 2;

    if(asmoothing && bsmoothing) {
        return function(out, i, j) {
            if(!out) out = [];
            var f0, f1, f2, f3, ak, k;

            var i0 = Math.max(0, Math.min(Math.floor(i), imax));
            var j0 = Math.max(0, Math.min(Math.floor(j), jmax));
            var u = Math.max(0, Math.min(1, i - i0));
            var v = Math.max(0, Math.min(1, j - j0));

            // Since it's a grid of control points, the actual indices are * 3:
            i0 *= 3;
            j0 *= 3;

            // Precompute some numbers:
            var u2 = u * u;
            var u3 = u2 * u;
            var ou = 1 - u;
            var ou2 = ou * ou;
            var ou3 = ou2 * ou;

            var v2 = v * v;
            var v3 = v2 * v;
            var ov = 1 - v;
            var ov2 = ov * ov;
            var ov3 = ov2 * ov;

            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];
                f0 = ou3 * ak[j0][i0] + 3 * (ou2 * u * ak[j0][i0 + 1] + ou * u2 * ak[j0][i0 + 2]) + u3 * ak[j0][i0 + 3];
                f1 = ou3 * ak[j0 + 1][i0] + 3 * (ou2 * u * ak[j0 + 1][i0 + 1] + ou * u2 * ak[j0 + 1][i0 + 2]) + u3 * ak[j0 + 1][i0 + 3];
                f2 = ou3 * ak[j0 + 2][i0] + 3 * (ou2 * u * ak[j0 + 2][i0 + 1] + ou * u2 * ak[j0 + 2][i0 + 2]) + u3 * ak[j0 + 2][i0 + 3];
                f3 = ou3 * ak[j0 + 3][i0] + 3 * (ou2 * u * ak[j0 + 3][i0 + 1] + ou * u2 * ak[j0 + 3][i0 + 2]) + u3 * ak[j0 + 3][i0 + 3];
                out[k] = ov3 * f0 + 3 * (ov2 * v * f1 + ov * v2 * f2) + v3 * f3;
            }

            return out;
        };
    } else if(asmoothing) {
        // Handle smooth in the a-direction but linear in the b-direction by performing four
        // linear interpolations followed by one cubic interpolation of the result
        return function(out, i, j) {
            if(!out) out = [];

            var i0 = Math.max(0, Math.min(Math.floor(i), imax));
            var j0 = Math.max(0, Math.min(Math.floor(j), jmax));
            var u = Math.max(0, Math.min(1, i - i0));
            var v = Math.max(0, Math.min(1, j - j0));

            var f0, f1, f2, f3, k, ak;
            i0 *= 3;
            var u2 = u * u;
            var u3 = u2 * u;
            var ou = 1 - u;
            var ou2 = ou * ou;
            var ou3 = ou2 * ou;
            var ov = 1 - v;
            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];
                f0 = ov * ak[j0][i0] + v * ak[j0 + 1][i0];
                f1 = ov * ak[j0][i0 + 1] + v * ak[j0 + 1][i0 + 1];
                f2 = ov * ak[j0][i0 + 2] + v * ak[j0 + 1][i0 + 1];
                f3 = ov * ak[j0][i0 + 3] + v * ak[j0 + 1][i0 + 1];

                out[k] = ou3 * f0 + 3 * (ou2 * u * f1 + ou * u2 * f2) + u3 * f3;
            }
            return out;
        };
    } else if(bsmoothing) {
        // Same as the above case, except reversed:
        return function(out, i, j) {
            if(!out) out = [];

            var i0 = Math.max(0, Math.min(Math.floor(i), imax));
            var j0 = Math.max(0, Math.min(Math.floor(j), jmax));
            var u = Math.max(0, Math.min(1, i - i0));
            var v = Math.max(0, Math.min(1, j - j0));

            var f0, f1, f2, f3, k, ak;
            j0 *= 3;
            var v2 = v * v;
            var v3 = v2 * v;
            var ov = 1 - v;
            var ov2 = ov * ov;
            var ov3 = ov2 * ov;
            var ou = 1 - u;
            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];
                f0 = ou * ak[j0][i0] + u * ak[j0][i0 + 1];
                f1 = ou * ak[j0 + 1][i0] + u * ak[j0 + 1][i0 + 1];
                f2 = ou * ak[j0 + 2][i0] + u * ak[j0 + 2][i0 + 1];
                f3 = ou * ak[j0 + 3][i0] + u * ak[j0 + 3][i0 + 1];

                out[k] = ov3 * f0 + 3 * (ov2 * v * f1 + ov * v2 * f2) + v3 * f3;
            }
            return out;
        };
    } else {
        // Finally, both directions are linear:
        return function(out, i, j) {
            if(!out) out = [];

            var i0 = Math.max(0, Math.min(Math.floor(i), imax));
            var j0 = Math.max(0, Math.min(Math.floor(j), jmax));
            var u = Math.max(0, Math.min(1, i - i0));
            var v = Math.max(0, Math.min(1, j - j0));

            var f0, f1, k, ak;
            var ov = 1 - v;
            var ou = 1 - u;
            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];
                f0 = ou * ak[j0][i0] + u * ak[j0][i0 + 1];
                f1 = ou * ak[j0 + 1][i0] + u * ak[j0 + 1][i0 + 1];

                out[k] = ov * f0 + v * f1;
            }
            return out;
        };
    }

};

},{}],892:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var handleXYDefaults = _dereq_('./xy_defaults');
var handleABDefaults = _dereq_('./ab_defaults');
var attributes = _dereq_('./attributes');
var colorAttrs = _dereq_('../../components/color/attributes');

module.exports = function supplyDefaults(traceIn, traceOut, dfltColor, fullLayout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    traceOut._clipPathId = 'clip' + traceOut.uid + 'carpet';

    var defaultColor = coerce('color', colorAttrs.defaultLine);
    Lib.coerceFont(coerce, 'font');

    coerce('carpet');

    handleABDefaults(traceIn, traceOut, fullLayout, coerce, defaultColor);

    if(!traceOut.a || !traceOut.b) {
        traceOut.visible = false;
        return;
    }

    if(traceOut.a.length < 3) {
        traceOut.aaxis.smoothing = 0;
    }

    if(traceOut.b.length < 3) {
        traceOut.baxis.smoothing = 0;
    }

    // NB: the input is x/y arrays. You should know that the *first* dimension of x and y
    // corresponds to b and the second to a. This sounds backwards but ends up making sense
    // the important part to know is that when you write y[j][i], j goes from 0 to b.length - 1
    // and i goes from 0 to a.length - 1.
    var validData = handleXYDefaults(traceIn, traceOut, coerce);
    if(!validData) {
        traceOut.visible = false;
    }

    if(traceOut._cheater) {
        coerce('cheaterslope');
    }
};

},{"../../components/color/attributes":573,"../../lib":697,"./ab_defaults":875,"./attributes":877,"./xy_defaults":901}],893:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Carpet = {};

Carpet.attributes = _dereq_('./attributes');
Carpet.supplyDefaults = _dereq_('./defaults');
Carpet.plot = _dereq_('./plot');
Carpet.calc = _dereq_('./calc');
Carpet.animatable = true;
Carpet.isContainer = true; // so carpet traces get `calc` before other traces

Carpet.moduleType = 'trace';
Carpet.name = 'carpet';
Carpet.basePlotModule = _dereq_('../../plots/cartesian');
Carpet.categories = ['cartesian', 'svg', 'carpet', 'carpetAxis', 'notLegendIsolatable', 'noMultiCategory'];
Carpet.meta = {
    
};

module.exports = Carpet;

},{"../../plots/cartesian":756,"./attributes":877,"./calc":881,"./defaults":892,"./plot":898}],894:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/*
 * Given a trace, look up the carpet axis by carpet.
 */
module.exports = function(gd, trace) {
    var n = gd._fullData.length;
    var firstAxis;
    for(var i = 0; i < n; i++) {
        var maybeCarpet = gd._fullData[i];

        if(maybeCarpet.index === trace.index) continue;

        if(maybeCarpet.type === 'carpet') {
            if(!firstAxis) {
                firstAxis = maybeCarpet;
            }

            if(maybeCarpet.carpet === trace.carpet) {
                return maybeCarpet;
            }
        }
    }

    return firstAxis;
};

},{}],895:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function makePath(xp, yp, isBicubic) {
    // Prevent d3 errors that would result otherwise:
    if(xp.length === 0) return '';

    var i;
    var path = [];
    var stride = isBicubic ? 3 : 1;
    for(i = 0; i < xp.length; i += stride) {
        path.push(xp[i] + ',' + yp[i]);

        if(isBicubic && i < xp.length - stride) {
            path.push('C');
            path.push([
                xp[i + 1] + ',' + yp[i + 1],
                xp[i + 2] + ',' + yp[i + 2] + ' ',
            ].join(' '));
        }
    }
    return path.join(isBicubic ? '' : 'L');
};

},{}],896:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;

/*
 * Map an array of x or y coordinates (c) to screen-space pixel coordinates (p).
 * The output array is optional, but if provided, it will be reused without
 * reallocation to the extent possible.
 */
module.exports = function mapArray(out, data, func) {
    var i;

    if(!isArrayOrTypedArray(out)) {
        // If not an array, make it an array:
        out = [];
    } else if(out.length > data.length) {
        // If too long, truncate. (If too short, it will grow
        // automatically so we don't care about that case)
        out = out.slice(0, data.length);
    }

    for(i = 0; i < data.length; i++) {
        out[i] = func(data[i]);
    }

    return out;
};

},{"../../lib":697}],897:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = function orientText(trace, xaxis, yaxis, xy, dxy, refDxy) {
    var dx = dxy[0] * trace.dpdx(xaxis);
    var dy = dxy[1] * trace.dpdy(yaxis);
    var flip = 1;

    var offsetMultiplier = 1.0;
    if(refDxy) {
        var l1 = Math.sqrt(dxy[0] * dxy[0] + dxy[1] * dxy[1]);
        var l2 = Math.sqrt(refDxy[0] * refDxy[0] + refDxy[1] * refDxy[1]);
        var dot = (dxy[0] * refDxy[0] + dxy[1] * refDxy[1]) / l1 / l2;
        offsetMultiplier = Math.max(0.0, dot);
    }

    var angle = Math.atan2(dy, dx) * 180 / Math.PI;
    if(angle < -90) {
        angle += 180;
        flip = -flip;
    } else if(angle > 90) {
        angle -= 180;
        flip = -flip;
    }

    return {
        angle: angle,
        flip: flip,
        p: trace.c2p(xy, xaxis, yaxis),
        offsetMultplier: offsetMultiplier
    };
};

},{}],898:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var Drawing = _dereq_('../../components/drawing');
var map1dArray = _dereq_('./map_1d_array');
var makepath = _dereq_('./makepath');
var orientText = _dereq_('./orient_text');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var Lib = _dereq_('../../lib');
var alignmentConstants = _dereq_('../../constants/alignment');

module.exports = function plot(gd, plotinfo, cdcarpet, carpetLayer) {
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;
    var fullLayout = gd._fullLayout;
    var clipLayer = fullLayout._clips;

    Lib.makeTraceGroups(carpetLayer, cdcarpet, 'trace').each(function(cd) {
        var axisLayer = d3.select(this);
        var cd0 = cd[0];
        var trace = cd0.trace;
        var aax = trace.aaxis;
        var bax = trace.baxis;

        var minorLayer = Lib.ensureSingle(axisLayer, 'g', 'minorlayer');
        var majorLayer = Lib.ensureSingle(axisLayer, 'g', 'majorlayer');
        var boundaryLayer = Lib.ensureSingle(axisLayer, 'g', 'boundarylayer');
        var labelLayer = Lib.ensureSingle(axisLayer, 'g', 'labellayer');

        axisLayer.style('opacity', trace.opacity);

        drawGridLines(xa, ya, majorLayer, aax, 'a', aax._gridlines, true);
        drawGridLines(xa, ya, majorLayer, bax, 'b', bax._gridlines, true);
        drawGridLines(xa, ya, minorLayer, aax, 'a', aax._minorgridlines, true);
        drawGridLines(xa, ya, minorLayer, bax, 'b', bax._minorgridlines, true);

        // NB: These are not ommitted if the lines are not active. The joins must be executed
        // in order for them to get cleaned up without a full redraw
        drawGridLines(xa, ya, boundaryLayer, aax, 'a-boundary', aax._boundarylines);
        drawGridLines(xa, ya, boundaryLayer, bax, 'b-boundary', bax._boundarylines);

        var labelOrientationA = drawAxisLabels(gd, xa, ya, trace, cd0, labelLayer, aax._labels, 'a-label');
        var labelOrientationB = drawAxisLabels(gd, xa, ya, trace, cd0, labelLayer, bax._labels, 'b-label');

        drawAxisTitles(gd, labelLayer, trace, cd0, xa, ya, labelOrientationA, labelOrientationB);

        drawClipPath(trace, cd0, clipLayer, xa, ya);
    });
};

function drawClipPath(trace, t, layer, xaxis, yaxis) {
    var seg, xp, yp, i;

    var clip = layer.select('#' + trace._clipPathId);

    if(!clip.size()) {
        clip = layer.append('clipPath')
            .classed('carpetclip', true);
    }

    var path = Lib.ensureSingle(clip, 'path', 'carpetboundary');
    var segments = t.clipsegments;
    var segs = [];

    for(i = 0; i < segments.length; i++) {
        seg = segments[i];
        xp = map1dArray([], seg.x, xaxis.c2p);
        yp = map1dArray([], seg.y, yaxis.c2p);
        segs.push(makepath(xp, yp, seg.bicubic));
    }

    // This could be optimized ever so slightly to avoid no-op L segments
    // at the corners, but it's so negligible that I don't think it's worth
    // the extra complexity
    var clipPathData = 'M' + segs.join('L') + 'Z';
    clip.attr('id', trace._clipPathId);
    path.attr('d', clipPathData);
}

function drawGridLines(xaxis, yaxis, layer, axis, axisLetter, gridlines) {
    var lineClass = 'const-' + axisLetter + '-lines';
    var gridJoin = layer.selectAll('.' + lineClass).data(gridlines);

    gridJoin.enter().append('path')
        .classed(lineClass, true)
        .style('vector-effect', 'non-scaling-stroke');

    gridJoin.each(function(d) {
        var gridline = d;
        var x = gridline.x;
        var y = gridline.y;

        var xp = map1dArray([], x, xaxis.c2p);
        var yp = map1dArray([], y, yaxis.c2p);

        var path = 'M' + makepath(xp, yp, gridline.smoothing);

        var el = d3.select(this);

        el.attr('d', path)
            .style('stroke-width', gridline.width)
            .style('stroke', gridline.color)
            .style('fill', 'none');
    });

    gridJoin.exit().remove();
}

function drawAxisLabels(gd, xaxis, yaxis, trace, t, layer, labels, labelClass) {
    var labelJoin = layer.selectAll('text.' + labelClass).data(labels);

    labelJoin.enter().append('text')
        .classed(labelClass, true);

    var maxExtent = 0;
    var labelOrientation = {};

    labelJoin.each(function(label, i) {
        // Most of the positioning is done in calc_labels. Only the parts that depend upon
        // the screen space representation of the x and y axes are here:
        var orientation;
        if(label.axis.tickangle === 'auto') {
            orientation = orientText(trace, xaxis, yaxis, label.xy, label.dxy);
        } else {
            var angle = (label.axis.tickangle + 180.0) * Math.PI / 180.0;
            orientation = orientText(trace, xaxis, yaxis, label.xy, [Math.cos(angle), Math.sin(angle)]);
        }

        if(!i) {
            // TODO: offsetMultiplier? Not currently used anywhere...
            labelOrientation = {angle: orientation.angle, flip: orientation.flip};
        }
        var direction = (label.endAnchor ? -1 : 1) * orientation.flip;

        var labelEl = d3.select(this)
            .attr({
                'text-anchor': direction > 0 ? 'start' : 'end',
                'data-notex': 1
            })
            .call(Drawing.font, label.font)
            .text(label.text)
            .call(svgTextUtils.convertToTspans, gd);

        var bbox = Drawing.bBox(this);

        labelEl.attr('transform',
                // Translate to the correct point:
                'translate(' + orientation.p[0] + ',' + orientation.p[1] + ') ' +
                // Rotate to line up with grid line tangent:
                'rotate(' + orientation.angle + ')' +
                // Adjust the baseline and indentation:
                'translate(' + label.axis.labelpadding * direction + ',' + bbox.height * 0.3 + ')'
            );

        maxExtent = Math.max(maxExtent, bbox.width + label.axis.labelpadding);
    });

    labelJoin.exit().remove();

    labelOrientation.maxExtent = maxExtent;
    return labelOrientation;
}

function drawAxisTitles(gd, layer, trace, t, xa, ya, labelOrientationA, labelOrientationB) {
    var a, b, xy, dxy;

    a = 0.5 * (trace.a[0] + trace.a[trace.a.length - 1]);
    b = trace.b[0];
    xy = trace.ab2xy(a, b, true);
    dxy = trace.dxyda_rough(a, b);
    if(labelOrientationA.angle === undefined) {
        Lib.extendFlat(labelOrientationA, orientText(trace, xa, ya, xy, trace.dxydb_rough(a, b)));
    }
    drawAxisTitle(gd, layer, trace, t, xy, dxy, trace.aaxis, xa, ya, labelOrientationA, 'a-title');

    a = trace.a[0];
    b = 0.5 * (trace.b[0] + trace.b[trace.b.length - 1]);
    xy = trace.ab2xy(a, b, true);
    dxy = trace.dxydb_rough(a, b);
    if(labelOrientationB.angle === undefined) {
        Lib.extendFlat(labelOrientationB, orientText(trace, xa, ya, xy, trace.dxyda_rough(a, b)));
    }
    drawAxisTitle(gd, layer, trace, t, xy, dxy, trace.baxis, xa, ya, labelOrientationB, 'b-title');
}

var lineSpacing = alignmentConstants.LINE_SPACING;
var midShift = ((1 - alignmentConstants.MID_SHIFT) / lineSpacing) + 1;

function drawAxisTitle(gd, layer, trace, t, xy, dxy, axis, xa, ya, labelOrientation, labelClass) {
    var data = [];
    if(axis.title.text) data.push(axis.title.text);
    var titleJoin = layer.selectAll('text.' + labelClass).data(data);
    var offset = labelOrientation.maxExtent;

    titleJoin.enter().append('text')
        .classed(labelClass, true);

    // There's only one, but we'll do it as a join so it's updated nicely:
    titleJoin.each(function() {
        var orientation = orientText(trace, xa, ya, xy, dxy);

        if(['start', 'both'].indexOf(axis.showticklabels) === -1) {
            offset = 0;
        }

        // In addition to the size of the labels, add on some extra padding:
        var titleSize = axis.title.font.size;
        offset += titleSize + axis.title.offset;

        var labelNorm = labelOrientation.angle + (labelOrientation.flip < 0 ? 180 : 0);
        var angleDiff = (labelNorm - orientation.angle + 450) % 360;
        var reverseTitle = angleDiff > 90 && angleDiff < 270;

        var el = d3.select(this);

        el.text(axis.title.text)
            .call(svgTextUtils.convertToTspans, gd);

        if(reverseTitle) {
            offset = (-svgTextUtils.lineCount(el) + midShift) * lineSpacing * titleSize - offset;
        }

        el.attr('transform',
                'translate(' + orientation.p[0] + ',' + orientation.p[1] + ') ' +
                'rotate(' + orientation.angle + ') ' +
                'translate(0,' + offset + ')'
            )
            .classed('user-select-none', true)
            .attr('text-anchor', 'middle')
            .call(Drawing.font, axis.title.font);
    });

    titleJoin.exit().remove();
}

},{"../../components/drawing":595,"../../constants/alignment":669,"../../lib":697,"../../lib/svg_text_utils":721,"./makepath":895,"./map_1d_array":896,"./orient_text":897,"d3":151}],899:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var constants = _dereq_('./constants');
var search = _dereq_('../../lib/search').findBin;
var computeControlPoints = _dereq_('./compute_control_points');
var createSplineEvaluator = _dereq_('./create_spline_evaluator');
var createIDerivativeEvaluator = _dereq_('./create_i_derivative_evaluator');
var createJDerivativeEvaluator = _dereq_('./create_j_derivative_evaluator');

/*
 * Create conversion functions to go from one basis to another. In particular the letter
 * abbreviations are:
 *
 *   i: i/j coordinates along the grid. Integer values correspond to data points
 *   a: real-valued coordinates along the a/b axes
 *   c: cartesian x-y coordinates
 *   p: screen-space pixel coordinates
 */
module.exports = function setConvert(trace) {
    var a = trace._a;
    var b = trace._b;
    var na = a.length;
    var nb = b.length;
    var aax = trace.aaxis;
    var bax = trace.baxis;

    // Grab the limits once rather than recomputing the bounds for every point
    // independently:
    var amin = a[0];
    var amax = a[na - 1];
    var bmin = b[0];
    var bmax = b[nb - 1];
    var arange = a[a.length - 1] - a[0];
    var brange = b[b.length - 1] - b[0];

    // Compute the tolerance so that points are visible slightly outside the
    // defined carpet axis:
    var atol = arange * constants.RELATIVE_CULL_TOLERANCE;
    var btol = brange * constants.RELATIVE_CULL_TOLERANCE;

    // Expand the limits to include the relative tolerance:
    amin -= atol;
    amax += atol;
    bmin -= btol;
    bmax += btol;

    trace.isVisible = function(a, b) {
        return a > amin && a < amax && b > bmin && b < bmax;
    };

    trace.isOccluded = function(a, b) {
        return a < amin || a > amax || b < bmin || b > bmax;
    };

    trace.setScale = function() {
        var x = trace._x;
        var y = trace._y;

        // This is potentially a very expensive step! It does the bulk of the work of constructing
        // an expanded basis of control points. Note in particular that it overwrites the existing
        // basis without creating a new array since that would potentially thrash the garbage
        // collector.
        var result = computeControlPoints(trace._xctrl, trace._yctrl, x, y, aax.smoothing, bax.smoothing);
        trace._xctrl = result[0];
        trace._yctrl = result[1];

        // This step is the second step in the process, but it's somewhat simpler. It just unrolls
        // some logic since it would be unnecessarily expensive to compute both interpolations
        // nearly identically but separately and to include a bunch of linear vs. bicubic logic in
        // every single call.
        trace.evalxy = createSplineEvaluator([trace._xctrl, trace._yctrl], na, nb, aax.smoothing, bax.smoothing);

        trace.dxydi = createIDerivativeEvaluator([trace._xctrl, trace._yctrl], aax.smoothing, bax.smoothing);
        trace.dxydj = createJDerivativeEvaluator([trace._xctrl, trace._yctrl], aax.smoothing, bax.smoothing);
    };

    /*
     * Convert from i/j data grid coordinates to a/b values. Note in particular that this
     * is *linear* interpolation, even if the data is interpolated bicubically.
     */
    trace.i2a = function(i) {
        var i0 = Math.max(0, Math.floor(i[0]), na - 2);
        var ti = i[0] - i0;
        return (1 - ti) * a[i0] + ti * a[i0 + 1];
    };

    trace.j2b = function(j) {
        var j0 = Math.max(0, Math.floor(j[1]), na - 2);
        var tj = j[1] - j0;
        return (1 - tj) * b[j0] + tj * b[j0 + 1];
    };

    trace.ij2ab = function(ij) {
        return [trace.i2a(ij[0]), trace.j2b(ij[1])];
    };

    /*
     * Convert from a/b coordinates to i/j grid-numbered coordinates. This requires searching
     * through the a/b data arrays and assumes they are monotonic, which is presumed to have
     * been enforced already.
     */
    trace.a2i = function(aval) {
        var i0 = Math.max(0, Math.min(search(aval, a), na - 2));
        var a0 = a[i0];
        var a1 = a[i0 + 1];
        return Math.max(0, Math.min(na - 1, i0 + (aval - a0) / (a1 - a0)));
    };

    trace.b2j = function(bval) {
        var j0 = Math.max(0, Math.min(search(bval, b), nb - 2));
        var b0 = b[j0];
        var b1 = b[j0 + 1];
        return Math.max(0, Math.min(nb - 1, j0 + (bval - b0) / (b1 - b0)));
    };

    trace.ab2ij = function(ab) {
        return [trace.a2i(ab[0]), trace.b2j(ab[1])];
    };

    /*
     * Convert from i/j coordinates to x/y caretesian coordinates. This means either bilinear
     * or bicubic spline evaluation, but the hard part is already done at this point.
     */
    trace.i2c = function(i, j) {
        return trace.evalxy([], i, j);
    };

    trace.ab2xy = function(aval, bval, extrapolate) {
        if(!extrapolate && (aval < a[0] || aval > a[na - 1] | bval < b[0] || bval > b[nb - 1])) {
            return [false, false];
        }
        var i = trace.a2i(aval);
        var j = trace.b2j(bval);

        var pt = trace.evalxy([], i, j);

        if(extrapolate) {
            // This section uses the boundary derivatives to extrapolate linearly outside
            // the defined range. Consider a scatter line with one point inside the carpet
            // axis and one point outside. If we don't extrapolate, we can't draw the line
            // at all.
            var iex = 0;
            var jex = 0;
            var der = [];

            var i0, ti, j0, tj;
            if(aval < a[0]) {
                i0 = 0;
                ti = 0;
                iex = (aval - a[0]) / (a[1] - a[0]);
            } else if(aval > a[na - 1]) {
                i0 = na - 2;
                ti = 1;
                iex = (aval - a[na - 1]) / (a[na - 1] - a[na - 2]);
            } else {
                i0 = Math.max(0, Math.min(na - 2, Math.floor(i)));
                ti = i - i0;
            }

            if(bval < b[0]) {
                j0 = 0;
                tj = 0;
                jex = (bval - b[0]) / (b[1] - b[0]);
            } else if(bval > b[nb - 1]) {
                j0 = nb - 2;
                tj = 1;
                jex = (bval - b[nb - 1]) / (b[nb - 1] - b[nb - 2]);
            } else {
                j0 = Math.max(0, Math.min(nb - 2, Math.floor(j)));
                tj = j - j0;
            }

            if(iex) {
                trace.dxydi(der, i0, j0, ti, tj);
                pt[0] += der[0] * iex;
                pt[1] += der[1] * iex;
            }

            if(jex) {
                trace.dxydj(der, i0, j0, ti, tj);
                pt[0] += der[0] * jex;
                pt[1] += der[1] * jex;
            }
        }

        return pt;
    };


    trace.c2p = function(xy, xa, ya) {
        return [xa.c2p(xy[0]), ya.c2p(xy[1])];
    };

    trace.p2x = function(p, xa, ya) {
        return [xa.p2c(p[0]), ya.p2c(p[1])];
    };

    trace.dadi = function(i /* , u*/) {
        // Right now only a piecewise linear a or b basis is permitted since smoother interpolation
        // would cause monotonicity problems. As a retult, u is entirely disregarded in this
        // computation, though we'll specify it as a parameter for the sake of completeness and
        // future-proofing. It would be possible to use monotonic cubic interpolation, for example.
        //
        // See: https://en.wikipedia.org/wiki/Monotone_cubic_interpolation

        // u = u || 0;

        var i0 = Math.max(0, Math.min(a.length - 2, i));

        // The step (demoninator) is implicitly 1 since that's the grid spacing.
        return a[i0 + 1] - a[i0];
    };

    trace.dbdj = function(j /* , v*/) {
        // See above caveats for dadi which also apply here
        var j0 = Math.max(0, Math.min(b.length - 2, j));

        // The step (demoninator) is implicitly 1 since that's the grid spacing.
        return b[j0 + 1] - b[j0];
    };

    // Takes: grid cell coordinate (i, j) and fractional grid cell coordinates (u, v)
    // Returns: (dx/da, dy/db)
    //
    // NB: separate grid cell + fractional grid cell coordinate format is due to the discontinuous
    // derivative, as described better in create_i_derivative_evaluator.js
    trace.dxyda = function(i0, j0, u, v) {
        var dxydi = trace.dxydi(null, i0, j0, u, v);
        var dadi = trace.dadi(i0, u);

        return [dxydi[0] / dadi, dxydi[1] / dadi];
    };

    trace.dxydb = function(i0, j0, u, v) {
        var dxydj = trace.dxydj(null, i0, j0, u, v);
        var dbdj = trace.dbdj(j0, v);

        return [dxydj[0] / dbdj, dxydj[1] / dbdj];
    };

    // Sometimes we don't care about precision and all we really want is decent rough
    // directions (as is the case with labels). In that case, we can do a very rough finite
    // difference and spare having to worry about precise grid coordinates:
    trace.dxyda_rough = function(a, b, reldiff) {
        var h = arange * (reldiff || 0.1);
        var plus = trace.ab2xy(a + h, b, true);
        var minus = trace.ab2xy(a - h, b, true);

        return [
            (plus[0] - minus[0]) * 0.5 / h,
            (plus[1] - minus[1]) * 0.5 / h
        ];
    };

    trace.dxydb_rough = function(a, b, reldiff) {
        var h = brange * (reldiff || 0.1);
        var plus = trace.ab2xy(a, b + h, true);
        var minus = trace.ab2xy(a, b - h, true);

        return [
            (plus[0] - minus[0]) * 0.5 / h,
            (plus[1] - minus[1]) * 0.5 / h
        ];
    };

    trace.dpdx = function(xa) {
        return xa._m;
    };

    trace.dpdy = function(ya) {
        return ya._m;
    };
};

},{"../../lib/search":716,"./compute_control_points":887,"./constants":888,"./create_i_derivative_evaluator":889,"./create_j_derivative_evaluator":890,"./create_spline_evaluator":891}],900:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

/*
 * Given a 2D array as well as a basis in either direction, this function fills in the
 * 2D array using a combination of smoothing and extrapolation. This is rather important
 * for carpet plots since it's used for layout so that we can't simply omit or blank out
 * points. We need a reasonable guess so that the interpolation puts points somewhere
 * even if we were to somehow represent that the data was missing later on.
 *
 * input:
 *  - data: 2D array of arrays
 *  - a: array such that a.length === data[0].length
 *  - b: array such that b.length === data.length
 */
module.exports = function smoothFill2dArray(data, a, b) {
    var i, j, k;
    var ip = [];
    var jp = [];
    // var neighborCnts = [];

    var ni = data[0].length;
    var nj = data.length;

    function avgSurrounding(i, j) {
        // As a low-quality start, we can simply average surrounding points (in a not
        // non-uniform grid aware manner):
        var sum = 0.0;
        var val;
        var cnt = 0;
        if(i > 0 && (val = data[j][i - 1]) !== undefined) {
            cnt++;
            sum += val;
        }
        if(i < ni - 1 && (val = data[j][i + 1]) !== undefined) {
            cnt++;
            sum += val;
        }
        if(j > 0 && (val = data[j - 1][i]) !== undefined) {
            cnt++;
            sum += val;
        }
        if(j < nj - 1 && (val = data[j + 1][i]) !== undefined) {
            cnt++;
            sum += val;
        }
        return sum / Math.max(1, cnt);

    }

    // This loop iterates over all cells. Any cells that are null will be noted and those
    // are the only points we will loop over and update via laplace's equation. Points with
    // any neighbors will receive the average. If there are no neighboring points, then they
    // will be set to zero. Also as we go, track the maximum magnitude so that we can scale
    // our tolerance accordingly.
    var dmax = 0.0;
    for(i = 0; i < ni; i++) {
        for(j = 0; j < nj; j++) {
            if(data[j][i] === undefined) {
                ip.push(i);
                jp.push(j);

                data[j][i] = avgSurrounding(i, j);
                // neighborCnts.push(result.neighbors);
            }
            dmax = Math.max(dmax, Math.abs(data[j][i]));
        }
    }

    if(!ip.length) return data;

    // The tolerance doesn't need to be excessive. It's just for display positioning
    var dxp, dxm, dap, dam, dbp, dbm, c, d, diff, reldiff, overrelaxation;
    var tol = 1e-5;
    var resid = 0;
    var itermax = 100;
    var iter = 0;
    var n = ip.length;
    do {
        resid = 0;
        // Normally we'd loop in two dimensions, but not all points are blank and need
        // an update, so we instead loop only over the points that were tabulated above
        for(k = 0; k < n; k++) {
            i = ip[k];
            j = jp[k];
            // neighborCnt = neighborCnts[k];

            // Track a counter for how many contributions there are. We'll use this counter
            // to average at the end, which reduces to laplace's equation with neumann boundary
            // conditions on the first derivative (second derivative is zero so that we get
            // a nice linear extrapolation at the boundaries).
            var boundaryCnt = 0;
            var newVal = 0;

            var d0, d1, x0, x1, i0, j0;
            if(i === 0) {
                // If this lies along the i = 0 boundary, extrapolate from the two points
                // to the right of this point. Note that the finite differences take into
                // account non-uniform grid spacing:
                i0 = Math.min(ni - 1, 2);
                x0 = a[i0];
                x1 = a[1];
                d0 = data[j][i0];
                d1 = data[j][1];
                newVal += d1 + (d1 - d0) * (a[0] - x1) / (x1 - x0);
                boundaryCnt++;
            } else if(i === ni - 1) {
                // If along the high i boundary, extrapolate from the two points to the
                // left of this point
                i0 = Math.max(0, ni - 3);
                x0 = a[i0];
                x1 = a[ni - 2];
                d0 = data[j][i0];
                d1 = data[j][ni - 2];
                newVal += d1 + (d1 - d0) * (a[ni - 1] - x1) / (x1 - x0);
                boundaryCnt++;
            }

            if((i === 0 || i === ni - 1) && (j > 0 && j < nj - 1)) {
                // If along the min(i) or max(i) boundaries, also smooth vertically as long
                // as we're not in a corner. Note that the finite differences used here
                // are also aware of nonuniform grid spacing:
                dxp = b[j + 1] - b[j];
                dxm = b[j] - b[j - 1];
                newVal += (dxm * data[j + 1][i] + dxp * data[j - 1][i]) / (dxm + dxp);
                boundaryCnt++;
            }

            if(j === 0) {
                // If along the j = 0 boundary, extrpolate this point from the two points
                // above it
                j0 = Math.min(nj - 1, 2);
                x0 = b[j0];
                x1 = b[1];
                d0 = data[j0][i];
                d1 = data[1][i];
                newVal += d1 + (d1 - d0) * (b[0] - x1) / (x1 - x0);
                boundaryCnt++;
            } else if(j === nj - 1) {
                // Same for the max j boundary from the cells below it:
                j0 = Math.max(0, nj - 3);
                x0 = b[j0];
                x1 = b[nj - 2];
                d0 = data[j0][i];
                d1 = data[nj - 2][i];
                newVal += d1 + (d1 - d0) * (b[nj - 1] - x1) / (x1 - x0);
                boundaryCnt++;
            }

            if((j === 0 || j === nj - 1) && (i > 0 && i < ni - 1)) {
                // Now average points to the left/right as long as not in a corner:
                dxp = a[i + 1] - a[i];
                dxm = a[i] - a[i - 1];
                newVal += (dxm * data[j][i + 1] + dxp * data[j][i - 1]) / (dxm + dxp);
                boundaryCnt++;
            }

            if(!boundaryCnt) {
                // If none of the above conditions were triggered, then this is an interior
                // point and we can just do a laplace equation update. As above, these differences
                // are aware of nonuniform grid spacing:
                dap = a[i + 1] - a[i];
                dam = a[i] - a[i - 1];
                dbp = b[j + 1] - b[j];
                dbm = b[j] - b[j - 1];

                // These are just some useful constants for the iteration, which is perfectly
                // straightforward but a little long to derive from f_xx + f_yy = 0.
                c = dap * dam * (dap + dam);
                d = dbp * dbm * (dbp + dbm);

                newVal = (c * (dbm * data[j + 1][i] + dbp * data[j - 1][i]) +
                          d * (dam * data[j][i + 1] + dap * data[j][i - 1])) /
                          (d * (dam + dap) + c * (dbm + dbp));
            } else {
                // If we did have contributions from the boundary conditions, then average
                // the result from the various contributions:
                newVal /= boundaryCnt;
            }

            // Jacobi updates are ridiculously slow to converge, so this approach uses a
            // Gauss-seidel iteration which is dramatically faster.
            diff = newVal - data[j][i];
            reldiff = diff / dmax;
            resid += reldiff * reldiff;

            // Gauss-Seidel-ish iteration, omega chosen based on heuristics and some
            // quick tests.
            //
            // NB: Don't overrelax the boundarie. Otherwise set an overrelaxation factor
            // which is a little low but safely optimal-ish:
            overrelaxation = boundaryCnt ? 0 : 0.85;

            // If there are four non-null neighbors, then we want a simple average without
            // overrelaxation. If all the surrouding points are null, then we want the full
            // overrelaxation
            //
            // Based on experiments, this actually seems to slow down convergence just a bit.
            // I'll leave it here for reference in case this needs to be revisited, but
            // it seems to work just fine without this.
            // if (overrelaxation) overrelaxation *= (4 - neighborCnt) / 4;

            data[j][i] += diff * (1 + overrelaxation);
        }

        resid = Math.sqrt(resid);
    } while(iter++ < itermax && resid > tol);

    Lib.log('Smoother converged to', resid, 'after', iter, 'iterations');

    return data;
};

},{"../../lib":697}],901:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isArray1D = _dereq_('../../lib').isArray1D;

module.exports = function handleXYDefaults(traceIn, traceOut, coerce) {
    var x = coerce('x');
    var hasX = x && x.length;
    var y = coerce('y');
    var hasY = y && y.length;
    if(!hasX && !hasY) return false;

    traceOut._cheater = !x;

    if((!hasX || isArray1D(x)) && (!hasY || isArray1D(y))) {
        var len = hasX ? x.length : Infinity;
        if(hasY) len = Math.min(len, y.length);
        if(traceOut.a && traceOut.a.length) len = Math.min(len, traceOut.a.length);
        if(traceOut.b && traceOut.b.length) len = Math.min(len, traceOut.b.length);
        traceOut._length = len;
    }
    else traceOut._length = null;

    return true;
};

},{"../../lib":697}],902:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var scatterGeoAttrs = _dereq_('../scattergeo/attributes');
var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
var plotAttrs = _dereq_('../../plots/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;

var scatterGeoMarkerLineAttrs = scatterGeoAttrs.marker.line;

module.exports = extendFlat({
    locations: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    locationmode: scatterGeoAttrs.locationmode,
    z: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    text: extendFlat({}, scatterGeoAttrs.text, {
        
    }),
    hovertext: extendFlat({}, scatterGeoAttrs.hovertext, {
        
    }),
    marker: {
        line: {
            color: scatterGeoMarkerLineAttrs.color,
            width: extendFlat({}, scatterGeoMarkerLineAttrs.width, {dflt: 1}),
            editType: 'calc'
        },
        opacity: {
            valType: 'number',
            arrayOk: true,
            min: 0,
            max: 1,
            dflt: 1,
            
            editType: 'style',
            
        },
        editType: 'calc'
    },

    selected: {
        marker: {
            opacity: scatterGeoAttrs.selected.marker.opacity,
            editType: 'plot'
        },
        editType: 'plot'
    },
    unselected: {
        marker: {
            opacity: scatterGeoAttrs.unselected.marker.opacity,
            editType: 'plot'
        },
        editType: 'plot'
    },

    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
        editType: 'calc',
        flags: ['location', 'z', 'text', 'name']
    }),
    hovertemplate: hovertemplateAttrs(),
},

    colorscaleAttrs('', {
        cLetter: 'z',
        editTypeOverride: 'calc'
    }),
    {colorbar: colorbarAttrs}
);

},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plots/attributes":742,"../scattergeo/attributes":1088}],903:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

var colorscaleCalc = _dereq_('../../components/colorscale/calc');
var arraysToCalcdata = _dereq_('../scatter/arrays_to_calcdata');
var calcSelection = _dereq_('../scatter/calc_selection');

module.exports = function calc(gd, trace) {
    var len = trace._length;
    var calcTrace = new Array(len);

    for(var i = 0; i < len; i++) {
        var calcPt = calcTrace[i] = {};
        var loc = trace.locations[i];
        var z = trace.z[i];

        calcPt.loc = typeof loc === 'string' ? loc : null;
        calcPt.z = isNumeric(z) ? z : BADNUM;
    }

    arraysToCalcdata(calcTrace, trace);
    colorscaleCalc(gd, trace, {
        vals: trace.z,
        containerStr: '',
        cLetter: 'z'
    });
    calcSelection(calcTrace, trace);

    return calcTrace;
};

},{"../../components/colorscale/calc":582,"../../constants/numerical":674,"../scatter/arrays_to_calcdata":1047,"../scatter/calc_selection":1050,"fast-isnumeric":218}],904:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var locations = coerce('locations');
    var z = coerce('z');

    if(!(locations && locations.length && Lib.isArrayOrTypedArray(z) && z.length)) {
        traceOut.visible = false;
        return;
    }
    traceOut._length = Math.min(locations.length, z.length);

    coerce('locationmode');

    coerce('text');
    coerce('hovertext');
    coerce('hovertemplate');

    coerce('marker.line.color');
    coerce('marker.line.width');
    coerce('marker.opacity');

    colorscaleDefaults(
        traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'}
    );

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};

},{"../../components/colorscale/defaults":584,"../../lib":697,"./attributes":902}],905:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = function eventData(out, pt) {
    out.location = pt.location;
    out.z = pt.z;

    return out;
};

},{}],906:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Axes = _dereq_('../../plots/cartesian/axes');
var attributes = _dereq_('./attributes');
var fillHoverText = _dereq_('../scatter/fill_hover_text');

module.exports = function hoverPoints(pointData, xval, yval) {
    var cd = pointData.cd;
    var trace = cd[0].trace;
    var geo = pointData.subplot;

    var pt, i, j, isInside;

    for(i = 0; i < cd.length; i++) {
        pt = cd[i];
        isInside = false;

        if(pt._polygons) {
            for(j = 0; j < pt._polygons.length; j++) {
                if(pt._polygons[j].contains([xval, yval])) {
                    isInside = !isInside;
                }
                // for polygons that cross antimeridian as xval is in [-180, 180]
                if(pt._polygons[j].contains([xval + 360, yval])) {
                    isInside = !isInside;
                }
            }

            if(isInside) break;
        }
    }

    if(!isInside || !pt) return;

    pointData.x0 = pointData.x1 = pointData.xa.c2p(pt.ct);
    pointData.y0 = pointData.y1 = pointData.ya.c2p(pt.ct);

    pointData.index = pt.index;
    pointData.location = pt.loc;
    pointData.z = pt.z;
    pointData.hovertemplate = pt.hovertemplate;

    makeHoverInfo(pointData, trace, pt, geo.mockAxis);

    return [pointData];
};

function makeHoverInfo(pointData, trace, pt, axis) {
    if(trace.hovertemplate) {
        return;
    }

    var hoverinfo = pt.hi || trace.hoverinfo;

    var parts = (hoverinfo === 'all') ?
        attributes.hoverinfo.flags :
        hoverinfo.split('+');

    var hasName = (parts.indexOf('name') !== -1);
    var hasLocation = (parts.indexOf('location') !== -1);
    var hasZ = (parts.indexOf('z') !== -1);
    var hasText = (parts.indexOf('text') !== -1);
    var hasIdAsNameLabel = !hasName && hasLocation;

    var text = [];

    function formatter(val) {
        return Axes.tickText(axis, axis.c2l(val), 'hover').text;
    }

    if(hasIdAsNameLabel) {
        pointData.nameOverride = pt.loc;
    } else {
        if(hasName) pointData.nameOverride = trace.name;
        if(hasLocation) text.push(pt.loc);
    }

    if(hasZ) text.push(formatter(pt.z));
    if(hasText) {
        fillHoverText(pt, trace, text);
    }

    pointData.extraText = text.join('<br>');
}

},{"../../plots/cartesian/axes":745,"../scatter/fill_hover_text":1056,"./attributes":902}],907:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Choropleth = {};

Choropleth.attributes = _dereq_('./attributes');
Choropleth.supplyDefaults = _dereq_('./defaults');
Choropleth.colorbar = _dereq_('../heatmap/colorbar');
Choropleth.calc = _dereq_('./calc');
Choropleth.plot = _dereq_('./plot');
Choropleth.style = _dereq_('./style').style;
Choropleth.styleOnSelect = _dereq_('./style').styleOnSelect;
Choropleth.hoverPoints = _dereq_('./hover');
Choropleth.eventData = _dereq_('./event_data');
Choropleth.selectPoints = _dereq_('./select');

Choropleth.moduleType = 'trace';
Choropleth.name = 'choropleth';
Choropleth.basePlotModule = _dereq_('../../plots/geo');
Choropleth.categories = ['geo', 'noOpacity'];
Choropleth.meta = {
    
};

module.exports = Choropleth;

},{"../../plots/geo":775,"../heatmap/colorbar":948,"./attributes":902,"./calc":903,"./defaults":904,"./event_data":905,"./hover":906,"./plot":908,"./select":909,"./style":910}],908:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Lib = _dereq_('../../lib');
var polygon = _dereq_('../../lib/polygon');

var getTopojsonFeatures = _dereq_('../../lib/topojson_utils').getTopojsonFeatures;
var locationToFeature = _dereq_('../../lib/geo_location_utils').locationToFeature;
var style = _dereq_('./style').style;

module.exports = function plot(gd, geo, calcData) {
    for(var i = 0; i < calcData.length; i++) {
        calcGeoJSON(calcData[i], geo.topojson);
    }

    var choroplethLayer = geo.layers.backplot.select('.choroplethlayer');
    Lib.makeTraceGroups(choroplethLayer, calcData, 'trace choropleth').each(function(calcTrace) {
        var sel = calcTrace[0].node3 = d3.select(this);

        var paths = sel.selectAll('path.choroplethlocation')
            .data(Lib.identity);

        paths.enter().append('path')
            .classed('choroplethlocation', true);

        paths.exit().remove();

        // call style here within topojson request callback
        style(gd, calcTrace);
    });
};

function calcGeoJSON(calcTrace, topojson) {
    var trace = calcTrace[0].trace;
    var len = calcTrace.length;
    var features = getTopojsonFeatures(trace, topojson);

    for(var i = 0; i < len; i++) {
        var calcPt = calcTrace[i];
        var feature = locationToFeature(trace.locationmode, calcPt.loc, features);

        if(!feature) {
            calcPt.geojson = null;
            continue;
        }


        calcPt.geojson = feature;
        calcPt.ct = feature.properties.ct;
        calcPt.index = i;
        calcPt._polygons = feature2polygons(feature);
    }
}

function feature2polygons(feature) {
    var geometry = feature.geometry;
    var coords = geometry.coordinates;
    var loc = feature.id;

    var polygons = [];
    var appendPolygon, j, k, m;

    function doesCrossAntiMerdian(pts) {
        for(var l = 0; l < pts.length - 1; l++) {
            if(pts[l][0] > 0 && pts[l + 1][0] < 0) return l;
        }
        return null;
    }

    if(loc === 'RUS' || loc === 'FJI') {
        // Russia and Fiji have landmasses that cross the antimeridian,
        // we need to add +360 to their longitude coordinates, so that
        // polygon 'contains' doesn't get confused when crossing the antimeridian.
        //
        // Note that other countries have polygons on either side of the antimeridian
        // (e.g. some Aleutian island for the USA), but those don't confuse
        // the 'contains' method; these are skipped here.
        appendPolygon = function(_pts) {
            var pts;

            if(doesCrossAntiMerdian(_pts) === null) {
                pts = _pts;
            } else {
                pts = new Array(_pts.length);
                for(m = 0; m < _pts.length; m++) {
                    // do nut mutate calcdata[i][j].geojson !!
                    pts[m] = [
                        _pts[m][0] < 0 ? _pts[m][0] + 360 : _pts[m][0],
                        _pts[m][1]
                    ];
                }
            }

            polygons.push(polygon.tester(pts));
        };
    } else if(loc === 'ATA') {
        // Antarctica has a landmass that wraps around every longitudes which
        // confuses the 'contains' methods.
        appendPolygon = function(pts) {
            var crossAntiMeridianIndex = doesCrossAntiMerdian(pts);

            // polygon that do not cross anti-meridian need no special handling
            if(crossAntiMeridianIndex === null) {
                return polygons.push(polygon.tester(pts));
            }

            // stitch polygon by adding pt over South Pole,
            // so that it covers the projected region covers all latitudes
            //
            // Note that the algorithm below only works for polygons that
            // start and end on longitude -180 (like the ones built by
            // https://github.com/etpinard/sane-topojson).
            var stitch = new Array(pts.length + 1);
            var si = 0;

            for(m = 0; m < pts.length; m++) {
                if(m > crossAntiMeridianIndex) {
                    stitch[si++] = [pts[m][0] + 360, pts[m][1]];
                } else if(m === crossAntiMeridianIndex) {
                    stitch[si++] = pts[m];
                    stitch[si++] = [pts[m][0], -90];
                } else {
                    stitch[si++] = pts[m];
                }
            }

            // polygon.tester by default appends pt[0] to the points list,
            // we must remove it here, to avoid a jump in longitude from 180 to -180,
            // that would confuse the 'contains' method
            var tester = polygon.tester(stitch);
            tester.pts.pop();
            polygons.push(tester);
        };
    } else {
        // otherwise using same array ref is fine
        appendPolygon = function(pts) {
            polygons.push(polygon.tester(pts));
        };
    }

    switch(geometry.type) {
        case 'MultiPolygon':
            for(j = 0; j < coords.length; j++) {
                for(k = 0; k < coords[j].length; k++) {
                    appendPolygon(coords[j][k]);
                }
            }
            break;
        case 'Polygon':
            for(j = 0; j < coords.length; j++) {
                appendPolygon(coords[j]);
            }
            break;
    }

    return polygons;
}

},{"../../lib":697,"../../lib/geo_location_utils":690,"../../lib/polygon":709,"../../lib/topojson_utils":724,"./style":910,"d3":151}],909:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function selectPoints(searchInfo, selectionTester) {
    var cd = searchInfo.cd;
    var xa = searchInfo.xaxis;
    var ya = searchInfo.yaxis;
    var selection = [];

    var i, di, ct, x, y;

    if(selectionTester === false) {
        for(i = 0; i < cd.length; i++) {
            cd[i].selected = 0;
        }
    } else {
        for(i = 0; i < cd.length; i++) {
            di = cd[i];
            ct = di.ct;

            if(!ct) continue;

            x = xa.c2p(ct);
            y = ya.c2p(ct);

            if(selectionTester.contains([x, y], null, i, searchInfo)) {
                selection.push({
                    pointNumber: i,
                    lon: ct[0],
                    lat: ct[1]
                });
                di.selected = 1;
            } else {
                di.selected = 0;
            }
        }
    }

    return selection;
};

},{}],910:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var Color = _dereq_('../../components/color');
var Drawing = _dereq_('../../components/drawing');
var Colorscale = _dereq_('../../components/colorscale');

function style(gd, calcTrace) {
    if(calcTrace) styleTrace(gd, calcTrace);
}

function styleTrace(gd, calcTrace) {
    var trace = calcTrace[0].trace;
    var s = calcTrace[0].node3;
    var locs = s.selectAll('.choroplethlocation');
    var marker = trace.marker || {};
    var markerLine = marker.line || {};

    var sclFunc = Colorscale.makeColorScaleFunc(
        Colorscale.extractScale(trace, {cLetter: 'z'})
    );

    locs.each(function(d) {
        d3.select(this)
            .attr('fill', sclFunc(d.z))
            .call(Color.stroke, d.mlc || markerLine.color)
            .call(Drawing.dashLine, '', d.mlw || markerLine.width || 0)
            .style('opacity', marker.opacity);
    });

    Drawing.selectedPointStyle(locs, trace, gd);
}

function styleOnSelect(gd, calcTrace) {
    var s = calcTrace[0].node3;
    var trace = calcTrace[0].trace;

    if(trace.selectedpoints) {
        Drawing.selectedPointStyle(s.selectAll('.choroplethlocation'), trace, gd);
    } else {
        styleTrace(gd, calcTrace);
    }
}

module.exports = {
    style: style,
    styleOnSelect: styleOnSelect
};

},{"../../components/color":574,"../../components/colorscale":586,"../../components/drawing":595,"d3":151}],911:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var mesh3dAttrs = _dereq_('../mesh3d/attributes');
var baseAttrs = _dereq_('../../plots/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;

var attrs = {
    x: {
        valType: 'data_array',
        
        editType: 'calc+clearAxisTypes',
        
    },
    y: {
        valType: 'data_array',
        
        editType: 'calc+clearAxisTypes',
        
    },
    z: {
        valType: 'data_array',
        
        editType: 'calc+clearAxisTypes',
        
    },

    u: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    v: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    w: {
        valType: 'data_array',
        editType: 'calc',
        
    },

    // TODO add way to specify cone positions independently of the vector field
    // provided, similar to MATLAB's coneplot Cx/Cy/Cz meshgrids,
    // see https://www.mathworks.com/help/matlab/ref/coneplot.html
    //
    // Alternatively, if our goal is only to 'fill in gaps' in the vector data,
    // we could try to extend the heatmap 'connectgaps' algorithm to 3D.
    // From AJ: this particular algorithm which amounts to a Poisson equation,
    // both for interpolation and extrapolation - is the right one to use for
    // cones too.  It makes a field with zero divergence, which is a good
    // baseline assumption for vector fields.
    //
    // cones: {
    //     // potential attributes to add:
    //     //
    //     // - meshmode: 'cartesian-product', 'pts', 'grid'
    //     //
    //     // under `meshmode: 'grid'`
    //     // - (x|y|z)grid.start
    //     // - (x|y|z)grid.end
    //     // - (x|y|z)grid.size
    //
    //     x: {
    //         valType: 'data_array',
    //         editType: 'calc',
    //         
    //     },
    //     y: {
    //         valType: 'data_array',
    //         editType: 'calc',
    //         
    //     },
    //     z: {
    //         valType: 'data_array',
    //         editType: 'calc',
    //         
    //     },
    //
    //     editType: 'calc',
    //     
    // },

    sizemode: {
        valType: 'enumerated',
        values: ['scaled', 'absolute'],
        
        editType: 'calc',
        dflt: 'scaled',
        
    },
    sizeref: {
        valType: 'number',
        
        editType: 'calc',
        min: 0,
        
    },

    anchor: {
        valType: 'enumerated',
        
        editType: 'calc',
        values: ['tip', 'tail', 'cm', 'center'],
        dflt: 'cm',
        
    },

    text: {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        editType: 'calc',
        
    },
    hovertext: {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        editType: 'calc',
        
    },
    hovertemplate: hovertemplateAttrs({editType: 'calc'}, {keys: ['norm']})
};

extendFlat(attrs, colorscaleAttrs('', {
    colorAttr: 'u/v/w norm',
    showScaleDflt: true,
    editTypeOverride: 'calc'
}), {
    colorbar: colorbarAttrs
});

var fromMesh3d = ['opacity', 'lightposition', 'lighting'];

fromMesh3d.forEach(function(k) {
    attrs[k] = mesh3dAttrs[k];
});

attrs.hoverinfo = extendFlat({}, baseAttrs.hoverinfo, {
    editType: 'calc',
    flags: ['x', 'y', 'z', 'u', 'v', 'w', 'norm', 'text', 'name'],
    dflt: 'x+y+z+norm+text+name'
});

attrs.transforms = undefined;

module.exports = attrs;

},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plots/attributes":742,"../mesh3d/attributes":991}],912:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorscaleCalc = _dereq_('../../components/colorscale/calc');

module.exports = function calc(gd, trace) {
    var u = trace.u;
    var v = trace.v;
    var w = trace.w;
    var len = Math.min(
        trace.x.length, trace.y.length, trace.z.length,
        u.length, v.length, w.length
    );
    var normMax = -Infinity;
    var normMin = Infinity;

    for(var i = 0; i < len; i++) {
        var uu = u[i];
        var vv = v[i];
        var ww = w[i];
        var norm = Math.sqrt(uu * uu + vv * vv + ww * ww);

        normMax = Math.max(normMax, norm);
        normMin = Math.min(normMin, norm);
    }

    trace._len = len;
    trace._normMax = normMax;

    colorscaleCalc(gd, trace, {
        vals: [normMin, normMax],
        containerStr: '',
        cLetter: 'c'
    });
};

},{"../../components/colorscale/calc":582}],913:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var conePlot = _dereq_('gl-cone3d');
var createConeMesh = _dereq_('gl-cone3d').createConeMesh;

var simpleMap = _dereq_('../../lib').simpleMap;
var parseColorScale = _dereq_('../../lib/gl_format_color').parseColorScale;
var zip3 = _dereq_('../../plots/gl3d/zip3');

function Cone(scene, uid) {
    this.scene = scene;
    this.uid = uid;
    this.mesh = null;
    this.data = null;
}

var proto = Cone.prototype;

proto.handlePick = function(selection) {
    if(selection.object === this.mesh) {
        var selectIndex = selection.index = selection.data.index;
        var xx = this.data.x[selectIndex];
        var yy = this.data.y[selectIndex];
        var zz = this.data.z[selectIndex];
        var uu = this.data.u[selectIndex];
        var vv = this.data.v[selectIndex];
        var ww = this.data.w[selectIndex];

        selection.traceCoordinate = [
            xx, yy, zz,
            uu, vv, ww,
            Math.sqrt(uu * uu + vv * vv + ww * ww)
        ];

        var text = this.data.hovertext || this.data.text;
        if(Array.isArray(text) && text[selectIndex] !== undefined) {
            selection.textLabel = text[selectIndex];
        } else if(text) {
            selection.textLabel = text;
        }

        return true;
    }
};

var axisName2scaleIndex = {xaxis: 0, yaxis: 1, zaxis: 2};
var anchor2coneOffset = {tip: 1, tail: 0, cm: 0.25, center: 0.5};
var anchor2coneSpan = {tip: 1, tail: 1, cm: 0.75, center: 0.5};

function convert(scene, trace) {
    var sceneLayout = scene.fullSceneLayout;
    var dataScale = scene.dataScale;
    var coneOpts = {};

    function toDataCoords(arr, axisName) {
        var ax = sceneLayout[axisName];
        var scale = dataScale[axisName2scaleIndex[axisName]];
        return simpleMap(arr, function(v) { return ax.d2l(v) * scale; });
    }

    coneOpts.vectors = zip3(
        toDataCoords(trace.u, 'xaxis'),
        toDataCoords(trace.v, 'yaxis'),
        toDataCoords(trace.w, 'zaxis'),
        trace._len
    );

    coneOpts.positions = zip3(
        toDataCoords(trace.x, 'xaxis'),
        toDataCoords(trace.y, 'yaxis'),
        toDataCoords(trace.z, 'zaxis'),
        trace._len
    );

    coneOpts.colormap = parseColorScale(trace);
    coneOpts.vertexIntensityBounds = [trace.cmin / trace._normMax, trace.cmax / trace._normMax];
    coneOpts.coneOffset = anchor2coneOffset[trace.anchor];

    if(trace.sizemode === 'scaled') {
        // unitless sizeref
        coneOpts.coneSize = trace.sizeref || 0.5;
    } else {
        // sizeref here has unit of velocity
        coneOpts.coneSize = trace.sizeref && trace._normMax ?
            trace.sizeref / trace._normMax :
            0.5;
    }

    var meshData = conePlot(coneOpts);

    // pass gl-mesh3d lighting attributes
    var lp = trace.lightposition;
    meshData.lightPosition = [lp.x, lp.y, lp.z];
    meshData.ambient = trace.lighting.ambient;
    meshData.diffuse = trace.lighting.diffuse;
    meshData.specular = trace.lighting.specular;
    meshData.roughness = trace.lighting.roughness;
    meshData.fresnel = trace.lighting.fresnel;
    meshData.opacity = trace.opacity;

    // stash autorange pad value
    trace._pad = anchor2coneSpan[trace.anchor] * meshData.vectorScale * meshData.coneScale * trace._normMax;

    return meshData;
}

proto.update = function(data) {
    this.data = data;

    var meshData = convert(this.scene, data);
    this.mesh.update(meshData);
};

proto.dispose = function() {
    this.scene.glplot.remove(this.mesh);
    this.mesh.dispose();
};

function createConeTrace(scene, data) {
    var gl = scene.glplot.gl;

    var meshData = convert(scene, data);
    var mesh = createConeMesh(gl, meshData);

    var cone = new Cone(scene, data.uid);
    cone.mesh = mesh;
    cone.data = data;
    mesh._trace = cone;

    scene.glplot.add(mesh);

    return cone;
}

module.exports = createConeTrace;

},{"../../lib":697,"../../lib/gl_format_color":694,"../../plots/gl3d/zip3":797,"gl-cone3d":235}],914:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var u = coerce('u');
    var v = coerce('v');
    var w = coerce('w');

    var x = coerce('x');
    var y = coerce('y');
    var z = coerce('z');

    if(
        !u || !u.length || !v || !v.length || !w || !w.length ||
        !x || !x.length || !y || !y.length || !z || !z.length
    ) {
        traceOut.visible = false;
        return;
    }

    coerce('sizeref');
    coerce('sizemode');

    coerce('anchor');

    coerce('lighting.ambient');
    coerce('lighting.diffuse');
    coerce('lighting.specular');
    coerce('lighting.roughness');
    coerce('lighting.fresnel');
    coerce('lightposition.x');
    coerce('lightposition.y');
    coerce('lightposition.z');

    colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'c'});

    coerce('text');
    coerce('hovertext');
    coerce('hovertemplate');

    // disable 1D transforms (for now)
    traceOut._length = null;
};

},{"../../components/colorscale/defaults":584,"../../lib":697,"./attributes":911}],915:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'trace',
    name: 'cone',
    basePlotModule: _dereq_('../../plots/gl3d'),
    categories: ['gl3d'],

    attributes: _dereq_('./attributes'),
    supplyDefaults: _dereq_('./defaults'),
    colorbar: {
        min: 'cmin',
        max: 'cmax'
    },
    calc: _dereq_('./calc'),
    plot: _dereq_('./convert'),
    eventData: function(out, pt) {
        out.norm = pt.traceCoordinate[6];
        return out;
    },

    meta: {
        
    }
};

},{"../../plots/gl3d":786,"./attributes":911,"./calc":912,"./convert":913,"./defaults":914}],916:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var heatmapAttrs = _dereq_('../heatmap/attributes');
var scatterAttrs = _dereq_('../scatter/attributes');
var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
var dash = _dereq_('../../components/drawing/attributes').dash;
var fontAttrs = _dereq_('../../plots/font_attributes');
var extendFlat = _dereq_('../../lib/extend').extendFlat;

var filterOps = _dereq_('../../constants/filter_ops');
var COMPARISON_OPS2 = filterOps.COMPARISON_OPS2;
var INTERVAL_OPS = filterOps.INTERVAL_OPS;

var scatterLineAttrs = scatterAttrs.line;

module.exports = extendFlat({
    z: heatmapAttrs.z,
    x: heatmapAttrs.x,
    x0: heatmapAttrs.x0,
    dx: heatmapAttrs.dx,
    y: heatmapAttrs.y,
    y0: heatmapAttrs.y0,
    dy: heatmapAttrs.dy,
    text: heatmapAttrs.text,
    hovertext: heatmapAttrs.hovertext,
    transpose: heatmapAttrs.transpose,
    xtype: heatmapAttrs.xtype,
    ytype: heatmapAttrs.ytype,
    zhoverformat: heatmapAttrs.zhoverformat,
    hovertemplate: heatmapAttrs.hovertemplate,

    connectgaps: heatmapAttrs.connectgaps,

    fillcolor: {
        valType: 'color',
        
        editType: 'calc',
        
    },

    autocontour: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'calc',
        impliedEdits: {
            'contours.start': undefined,
            'contours.end': undefined,
            'contours.size': undefined
        },
        
    },
    ncontours: {
        valType: 'integer',
        dflt: 15,
        min: 1,
        
        editType: 'calc',
        
    },

    contours: {
        type: {
            valType: 'enumerated',
            values: ['levels', 'constraint'],
            dflt: 'levels',
            
            editType: 'calc',
            
        },
        start: {
            valType: 'number',
            dflt: null,
            
            editType: 'plot',
            impliedEdits: {'^autocontour': false},
            
        },
        end: {
            valType: 'number',
            dflt: null,
            
            editType: 'plot',
            impliedEdits: {'^autocontour': false},
            
        },
        size: {
            valType: 'number',
            dflt: null,
            min: 0,
            
            editType: 'plot',
            impliedEdits: {'^autocontour': false},
            
        },
        coloring: {
            valType: 'enumerated',
            values: ['fill', 'heatmap', 'lines', 'none'],
            dflt: 'fill',
            
            editType: 'calc',
            
        },
        showlines: {
            valType: 'boolean',
            dflt: true,
            
            editType: 'plot',
            
        },
        showlabels: {
            valType: 'boolean',
            dflt: false,
            
            editType: 'plot',
            
        },
        labelfont: fontAttrs({
            editType: 'plot',
            colorEditType: 'style',
            
        }),
        labelformat: {
            valType: 'string',
            dflt: '',
            
            editType: 'plot',
            
        },
        operation: {
            valType: 'enumerated',
            values: [].concat(COMPARISON_OPS2).concat(INTERVAL_OPS),
            
            dflt: '=',
            editType: 'calc',
            
        },
        value: {
            valType: 'any',
            dflt: 0,
            
            editType: 'calc',
            
        },
        editType: 'calc',
        impliedEdits: {'autocontour': false}
    },

    line: {
        color: extendFlat({}, scatterLineAttrs.color, {
            editType: 'style+colorbars',
            
        }),
        width: extendFlat({}, scatterLineAttrs.width, {
            editType: 'style+colorbars'
        }),
        dash: dash,
        smoothing: extendFlat({}, scatterLineAttrs.smoothing, {
            
        }),
        editType: 'plot'
    }
},
    colorscaleAttrs('', {
        cLetter: 'z',
        autoColorDflt: false,
        editTypeOverride: 'calc'
    }),
    { colorbar: colorbarAttrs }
);

},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/drawing/attributes":594,"../../constants/filter_ops":670,"../../lib/extend":687,"../../plots/font_attributes":771,"../heatmap/attributes":945,"../scatter/attributes":1048}],917:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var heatmapCalc = _dereq_('../heatmap/calc');
var setContours = _dereq_('./set_contours');

// most is the same as heatmap calc, then adjust it
// though a few things inside heatmap calc still look for
// contour maps, because the makeBoundArray calls are too entangled
module.exports = function calc(gd, trace) {
    var cd = heatmapCalc(gd, trace);
    setContours(trace);
    return cd;
};

},{"../heatmap/calc":946,"./set_contours":935}],918:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function(pathinfo, operation, perimeter, trace) {
    // Abandon all hope, ye who enter here.
    var i, v1, v2;
    var pi0 = pathinfo[0];
    var na = pi0.x.length;
    var nb = pi0.y.length;
    var z = pi0.z;
    var contours = trace.contours;

    var boundaryMax = -Infinity;
    var boundaryMin = Infinity;

    for(i = 0; i < nb; i++) {
        boundaryMin = Math.min(boundaryMin, z[i][0]);
        boundaryMin = Math.min(boundaryMin, z[i][na - 1]);
        boundaryMax = Math.max(boundaryMax, z[i][0]);
        boundaryMax = Math.max(boundaryMax, z[i][na - 1]);
    }

    for(i = 1; i < na - 1; i++) {
        boundaryMin = Math.min(boundaryMin, z[0][i]);
        boundaryMin = Math.min(boundaryMin, z[nb - 1][i]);
        boundaryMax = Math.max(boundaryMax, z[0][i]);
        boundaryMax = Math.max(boundaryMax, z[nb - 1][i]);
    }

    pi0.prefixBoundary = false;

    switch(operation) {
        case '>':
            if(contours.value > boundaryMax) {
                pi0.prefixBoundary = true;
            }
            break;
        case '<':
            if(contours.value < boundaryMin) {
                pi0.prefixBoundary = true;
            }
            break;
        case '[]':
            v1 = Math.min.apply(null, contours.value);
            v2 = Math.max.apply(null, contours.value);
            if(v2 < boundaryMin || v1 > boundaryMax) {
                pi0.prefixBoundary = true;
            }
            break;
        case '][':
            v1 = Math.min.apply(null, contours.value);
            v2 = Math.max.apply(null, contours.value);
            if(v1 < boundaryMin && v2 > boundaryMax) {
                pi0.prefixBoundary = true;
            }
            break;
    }
};

},{}],919:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var drawColorbar = _dereq_('../../components/colorbar/draw');

var makeColorMap = _dereq_('./make_color_map');
var endPlus = _dereq_('./end_plus');


module.exports = function colorbar(gd, cd) {
    var trace = cd[0].trace;
    var cbId = 'cb' + trace.uid;

    gd._fullLayout._infolayer.selectAll('.' + cbId).remove();

    if(!trace.showscale) return;

    var cb = cd[0].t.cb = drawColorbar(gd, cbId);

    var contours = trace.contours;
    var line = trace.line;
    var cs = contours.size || 1;
    var coloring = contours.coloring;

    var colorMap = makeColorMap(trace, {isColorbar: true});

    cb.fillgradient(coloring === 'heatmap' ? trace.colorscale : '')
        .zrange(coloring === 'heatmap' ? [trace.zmin, trace.zmax] : '')
        .fillcolor((coloring === 'fill') ? colorMap : '')
        .line({
            color: coloring === 'lines' ? colorMap : line.color,
            width: contours.showlines !== false ? line.width : 0,
            dash: line.dash
        })
        .levels({
            start: contours.start,
            end: endPlus(contours),
            size: cs
        })
        .options(trace.colorbar)();
};

},{"../../components/colorbar/draw":579,"./end_plus":927,"./make_color_map":932}],920:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';
module.exports = {
    // some constants to help with marching squares algorithm
    // where does the path start for each index?
    BOTTOMSTART: [1, 9, 13, 104, 713],
    TOPSTART: [4, 6, 7, 104, 713],
    LEFTSTART: [8, 12, 14, 208, 1114],
    RIGHTSTART: [2, 3, 11, 208, 1114],

    // which way [dx,dy] do we leave a given index?
    // saddles are already disambiguated
    NEWDELTA: [
        null, [-1, 0], [0, -1], [-1, 0],
        [1, 0], null, [0, -1], [-1, 0],
        [0, 1], [0, 1], null, [0, 1],
        [1, 0], [1, 0], [0, -1]
    ],

    // for each saddle, the first index here is used
    // for dx||dy<0, the second for dx||dy>0
    CHOOSESADDLE: {
        104: [4, 1],
        208: [2, 8],
        713: [7, 13],
        1114: [11, 14]
    },

    // after one index has been used for a saddle, which do we
    // substitute to be used up later?
    SADDLEREMAINDER: {1: 4, 2: 8, 4: 1, 7: 13, 8: 2, 11: 14, 13: 7, 14: 11},

    // length of a contour, as a multiple of the plot area diagonal, per label
    LABELDISTANCE: 2,

    // number of contour levels after which we start increasing the number of
    // labels we draw. Many contours means they will generally be close
    // together, so it will be harder to follow a long way to find a label
    LABELINCREASE: 10,

    // minimum length of a contour line, as a multiple of the label length,
    // at which we draw *any* labels
    LABELMIN: 3,

    // max number of labels to draw on a single contour path, no matter how long
    LABELMAX: 10,

    // constants for the label position cost function
    LABELOPTIMIZER: {
        // weight given to edge proximity
        EDGECOST: 1,
        // weight given to the angle off horizontal
        ANGLECOST: 1,
        // weight given to distance from already-placed labels
        NEIGHBORCOST: 5,
        // cost multiplier for labels on the same level
        SAMELEVELFACTOR: 10,
        // minimum distance (as a multiple of the label length)
        // for labels on the same level
        SAMELEVELDISTANCE: 5,
        // maximum cost before we won't even place the label
        MAXCOST: 100,
        // number of evenly spaced points to look at in the first
        // iteration of the search
        INITIALSEARCHPOINTS: 10,
        // number of binary search iterations after the initial wide search
        ITERATIONS: 5
    }
};

},{}],921:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';
var isNumeric = _dereq_('fast-isnumeric');

var handleLabelDefaults = _dereq_('./label_defaults');

var Color = _dereq_('../../components/color');
var addOpacity = Color.addOpacity;
var opacity = Color.opacity;

var filterOps = _dereq_('../../constants/filter_ops');
var CONSTRAINT_REDUCTION = filterOps.CONSTRAINT_REDUCTION;
var COMPARISON_OPS2 = filterOps.COMPARISON_OPS2;

module.exports = function handleConstraintDefaults(traceIn, traceOut, coerce, layout, defaultColor, opts) {
    var contours = traceOut.contours;
    var showLines, lineColor, fillColor;

    var operation = coerce('contours.operation');
    contours._operation = CONSTRAINT_REDUCTION[operation];

    handleConstraintValueDefaults(coerce, contours);

    if(operation === '=') {
        showLines = contours.showlines = true;
    }
    else {
        showLines = coerce('contours.showlines');
        fillColor = coerce('fillcolor', addOpacity(
            (traceIn.line || {}).color || defaultColor, 0.5
        ));
    }

    if(showLines) {
        var lineDfltColor = fillColor && opacity(fillColor) ?
            addOpacity(traceOut.fillcolor, 1) :
            defaultColor;
        lineColor = coerce('line.color', lineDfltColor);
        coerce('line.width', 2);
        coerce('line.dash');
    }

    coerce('line.smoothing');

    handleLabelDefaults(coerce, layout, lineColor, opts);
};

function handleConstraintValueDefaults(coerce, contours) {
    var zvalue;

    if(COMPARISON_OPS2.indexOf(contours.operation) === -1) {
        // Requires an array of two numbers:
        coerce('contours.value', [0, 1]);

        if(!Array.isArray(contours.value)) {
            if(isNumeric(contours.value)) {
                zvalue = parseFloat(contours.value);
                contours.value = [zvalue, zvalue + 1];
            }
        } else if(contours.value.length > 2) {
            contours.value = contours.value.slice(2);
        } else if(contours.length === 0) {
            contours.value = [0, 1];
        } else if(contours.length < 2) {
            zvalue = parseFloat(contours.value[0]);
            contours.value = [zvalue, zvalue + 1];
        } else {
            contours.value = [
                parseFloat(contours.value[0]),
                parseFloat(contours.value[1])
            ];
        }
    } else {
        // Requires a single scalar:
        coerce('contours.value', 0);

        if(!isNumeric(contours.value)) {
            if(Array.isArray(contours.value)) {
                contours.value = parseFloat(contours.value[0]);
            } else {
                contours.value = 0;
            }
        }
    }
}

},{"../../components/color":574,"../../constants/filter_ops":670,"./label_defaults":931,"fast-isnumeric":218}],922:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var filterOps = _dereq_('../../constants/filter_ops');
var isNumeric = _dereq_('fast-isnumeric');

// This syntax conforms to the existing filter transform syntax, but we don't care
// about open vs. closed intervals for simply drawing contours constraints:
module.exports = {
    '[]': makeRangeSettings('[]'),
    '][': makeRangeSettings(']['),
    '>': makeInequalitySettings('>'),
    '<': makeInequalitySettings('<'),
    '=': makeInequalitySettings('=')
};

// This does not in any way shape or form support calendars. It's adapted from
// transforms/filter.js.
function coerceValue(operation, value) {
    var hasArrayValue = Array.isArray(value);

    var coercedValue;

    function coerce(value) {
        return isNumeric(value) ? (+value) : null;
    }

    if(filterOps.COMPARISON_OPS2.indexOf(operation) !== -1) {
        coercedValue = hasArrayValue ? coerce(value[0]) : coerce(value);
    } else if(filterOps.INTERVAL_OPS.indexOf(operation) !== -1) {
        coercedValue = hasArrayValue ?
            [coerce(value[0]), coerce(value[1])] :
            [coerce(value), coerce(value)];
    } else if(filterOps.SET_OPS.indexOf(operation) !== -1) {
        coercedValue = hasArrayValue ? value.map(coerce) : [coerce(value)];
    }

    return coercedValue;
}

// Returns a parabola scaled so that the min/max is either +/- 1 and zero at the two values
// provided. The data is mapped by this function when constructing intervals so that it's
// very easy to construct contours as normal.
function makeRangeSettings(operation) {
    return function(value) {
        value = coerceValue(operation, value);

        // Ensure proper ordering:
        var min = Math.min(value[0], value[1]);
        var max = Math.max(value[0], value[1]);

        return {
            start: min,
            end: max,
            size: max - min
        };
    };
}

function makeInequalitySettings(operation) {
    return function(value) {
        value = coerceValue(operation, value);

        return {
            start: value,
            end: Infinity,
            size: Infinity
        };
    };
}

},{"../../constants/filter_ops":670,"fast-isnumeric":218}],923:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function handleContourDefaults(traceIn, traceOut, coerce, coerce2) {
    var contourStart = coerce2('contours.start');
    var contourEnd = coerce2('contours.end');
    var missingEnd = (contourStart === false) || (contourEnd === false);

    // normally we only need size if autocontour is off. But contour.calc
    // pushes its calculated contour size back to the input trace, so for
    // things like restyle that can call supplyDefaults without calc
    // after the initial draw, we can just reuse the previous calculation
    var contourSize = coerce('contours.size');
    var autoContour;

    if(missingEnd) autoContour = traceOut.autocontour = true;
    else autoContour = coerce('autocontour', false);

    if(autoContour || !contourSize) coerce('ncontours');
};

},{}],924:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

// The contour extraction is great, except it totally fails for constraints because we
// need weird range loops and flipped contours instead of the usual format. This function
// does some weird manipulation of the extracted pathinfo data such that it magically
// draws contours correctly *as* constraints.
module.exports = function(pathinfo, operation) {
    var i, pi0, pi1;

    var op0 = function(arr) { return arr.reverse(); };
    var op1 = function(arr) { return arr; };

    switch(operation) {
        case '=':
        case '<':
            return pathinfo;
        case '>':
            if(pathinfo.length !== 1) {
                Lib.warn('Contour data invalid for the specified inequality operation.');
            }

            // In this case there should be exactly two contour levels in pathinfo. We
            // simply concatenate the info into one pathinfo and flip all of the data
            // in one. This will draw the contour as closed.
            pi0 = pathinfo[0];

            for(i = 0; i < pi0.edgepaths.length; i++) {
                pi0.edgepaths[i] = op0(pi0.edgepaths[i]);
            }

            for(i = 0; i < pi0.paths.length; i++) {
                pi0.paths[i] = op0(pi0.paths[i]);
            }
            return pathinfo;
        case '][':
            var tmp = op0;
            op0 = op1;
            op1 = tmp;
            // It's a nice rule, except this definitely *is* what's intended here.
            /* eslint-disable: no-fallthrough */
        case '[]':
            /* eslint-enable: no-fallthrough */
            if(pathinfo.length !== 2) {
                Lib.warn('Contour data invalid for the specified inequality range operation.');
            }

            // In this case there should be exactly two contour levels in pathinfo. We
            // simply concatenate the info into one pathinfo and flip all of the data
            // in one. This will draw the contour as closed.
            pi0 = copyPathinfo(pathinfo[0]);
            pi1 = copyPathinfo(pathinfo[1]);

            for(i = 0; i < pi0.edgepaths.length; i++) {
                pi0.edgepaths[i] = op0(pi0.edgepaths[i]);
            }

            for(i = 0; i < pi0.paths.length; i++) {
                pi0.paths[i] = op0(pi0.paths[i]);
            }

            while(pi1.edgepaths.length) {
                pi0.edgepaths.push(op1(pi1.edgepaths.shift()));
            }
            while(pi1.paths.length) {
                pi0.paths.push(op1(pi1.paths.shift()));
            }
            return [pi0];
    }
};

function copyPathinfo(pi) {
    return Lib.extendFlat({}, pi, {
        edgepaths: Lib.extendDeep([], pi.edgepaths),
        paths: Lib.extendDeep([], pi.paths)
    });
}

},{"../../lib":697}],925:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

var handleXYZDefaults = _dereq_('../heatmap/xyz_defaults');
var handleConstraintDefaults = _dereq_('./constraint_defaults');
var handleContoursDefaults = _dereq_('./contours_defaults');
var handleStyleDefaults = _dereq_('./style_defaults');
var attributes = _dereq_('./attributes');


module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    function coerce2(attr) {
        return Lib.coerce2(traceIn, traceOut, attributes, attr);
    }

    var len = handleXYZDefaults(traceIn, traceOut, coerce, layout);
    if(!len) {
        traceOut.visible = false;
        return;
    }

    coerce('text');
    coerce('hovertext');
    coerce('hovertemplate');

    var isConstraint = (coerce('contours.type') === 'constraint');
    coerce('connectgaps', Lib.isArray1D(traceOut.z));

    if(isConstraint) {
        handleConstraintDefaults(traceIn, traceOut, coerce, layout, defaultColor);
    }
    else {
        handleContoursDefaults(traceIn, traceOut, coerce, coerce2);
        handleStyleDefaults(traceIn, traceOut, coerce, layout);
    }
};

},{"../../lib":697,"../heatmap/xyz_defaults":959,"./attributes":916,"./constraint_defaults":921,"./contours_defaults":923,"./style_defaults":937}],926:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var constraintMapping = _dereq_('./constraint_mapping');
var endPlus = _dereq_('./end_plus');

module.exports = function emptyPathinfo(contours, plotinfo, cd0) {
    var contoursFinal = (contours.type === 'constraint') ?
        constraintMapping[contours._operation](contours.value) :
        contours;

    var cs = contoursFinal.size;
    var pathinfo = [];
    var end = endPlus(contoursFinal);

    var carpet = cd0.trace._carpetTrace;

    var basePathinfo = carpet ? {
        // store axes so we can convert to px
        xaxis: carpet.aaxis,
        yaxis: carpet.baxis,
        // full data arrays to use for interpolation
        x: cd0.a,
        y: cd0.b
    } : {
        xaxis: plotinfo.xaxis,
        yaxis: plotinfo.yaxis,
        x: cd0.x,
        y: cd0.y
    };

    for(var ci = contoursFinal.start; ci < end; ci += cs) {
        pathinfo.push(Lib.extendFlat({
            level: ci,
            // all the cells with nontrivial marching index
            crossings: {},
            // starting points on the edges of the lattice for each contour
            starts: [],
            // all unclosed paths (may have less items than starts,
            // if a path is closed by rounding)
            edgepaths: [],
            // all closed paths
            paths: [],
            z: cd0.z,
            smoothing: cd0.trace.line.smoothing
        }, basePathinfo));

        if(pathinfo.length > 1000) {
            Lib.warn('Too many contours, clipping at 1000', contours);
            break;
        }
    }
    return pathinfo;
};

},{"../../lib":697,"./constraint_mapping":922,"./end_plus":927}],927:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

/*
 * tiny helper to move the end of the contours a little to prevent
 * losing the last contour to rounding errors
 */
module.exports = function endPlus(contours) {
    return contours.end + contours.size / 1e6;
};

},{}],928:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var constants = _dereq_('./constants');

module.exports = function findAllPaths(pathinfo, xtol, ytol) {
    var cnt,
        startLoc,
        i,
        pi,
        j;

    // Default just passes these values through as they were before:
    xtol = xtol || 0.01;
    ytol = ytol || 0.01;

    for(i = 0; i < pathinfo.length; i++) {
        pi = pathinfo[i];

        for(j = 0; j < pi.starts.length; j++) {
            startLoc = pi.starts[j];
            makePath(pi, startLoc, 'edge', xtol, ytol);
        }

        cnt = 0;
        while(Object.keys(pi.crossings).length && cnt < 10000) {
            cnt++;
            startLoc = Object.keys(pi.crossings)[0].split(',').map(Number);
            makePath(pi, startLoc, undefined, xtol, ytol);
        }
        if(cnt === 10000) Lib.log('Infinite loop in contour?');
    }
};

function equalPts(pt1, pt2, xtol, ytol) {
    return Math.abs(pt1[0] - pt2[0]) < xtol &&
           Math.abs(pt1[1] - pt2[1]) < ytol;
}

// distance in index units - uses the 3rd and 4th items in points
function ptDist(pt1, pt2) {
    var dx = pt1[2] - pt2[2];
    var dy = pt1[3] - pt2[3];
    return Math.sqrt(dx * dx + dy * dy);
}

function makePath(pi, loc, edgeflag, xtol, ytol) {
    var startLocStr = loc.join(',');
    var locStr = startLocStr;
    var mi = pi.crossings[locStr];
    var marchStep = startStep(mi, edgeflag, loc);
    // start by going backward a half step and finding the crossing point
    var pts = [getInterpPx(pi, loc, [-marchStep[0], -marchStep[1]])];
    var startStepStr = marchStep.join(',');
    var m = pi.z.length;
    var n = pi.z[0].length;
    var cnt;

    // now follow the path
    for(cnt = 0; cnt < 10000; cnt++) { // just to avoid infinite loops
        if(mi > 20) {
            mi = constants.CHOOSESADDLE[mi][(marchStep[0] || marchStep[1]) < 0 ? 0 : 1];
            pi.crossings[locStr] = constants.SADDLEREMAINDER[mi];
        }
        else {
            delete pi.crossings[locStr];
        }

        marchStep = constants.NEWDELTA[mi];
        if(!marchStep) {
            Lib.log('Found bad marching index:', mi, loc, pi.level);
            break;
        }

        // find the crossing a half step forward, and then take the full step
        pts.push(getInterpPx(pi, loc, marchStep));
        loc[0] += marchStep[0];
        loc[1] += marchStep[1];

        // don't include the same point multiple times
        if(equalPts(pts[pts.length - 1], pts[pts.length - 2], xtol, ytol)) pts.pop();
        locStr = loc.join(',');

        var atEdge = (marchStep[0] && (loc[0] < 0 || loc[0] > n - 2)) ||
                (marchStep[1] && (loc[1] < 0 || loc[1] > m - 2));
        var closedLoop = (locStr === startLocStr) && (marchStep.join(',') === startStepStr);

        // have we completed a loop, or reached an edge?
        if((closedLoop) || (edgeflag && atEdge)) break;

        mi = pi.crossings[locStr];
    }

    if(cnt === 10000) {
        Lib.log('Infinite loop in contour?');
    }
    var closedpath = equalPts(pts[0], pts[pts.length - 1], xtol, ytol);
    var totaldist = 0;
    var distThresholdFactor = 0.2 * pi.smoothing;
    var alldists = [];
    var cropstart = 0;
    var distgroup, cnt2, cnt3, newpt, ptcnt, ptavg, thisdist,
        i, j, edgepathi, edgepathj;

    /*
     * Check for points that are too close together (<1/5 the average dist
     * *in grid index units* (important for log axes and nonuniform grids),
     * less if less smoothed) and just take the center (or avg of center 2).
     * This cuts down on funny behavior when a point is very close to a
     * contour level.
     */
    for(cnt = 1; cnt < pts.length; cnt++) {
        thisdist = ptDist(pts[cnt], pts[cnt - 1]);
        totaldist += thisdist;
        alldists.push(thisdist);
    }

    var distThreshold = totaldist / alldists.length * distThresholdFactor;

    function getpt(i) { return pts[i % pts.length]; }

    for(cnt = pts.length - 2; cnt >= cropstart; cnt--) {
        distgroup = alldists[cnt];
        if(distgroup < distThreshold) {
            cnt3 = 0;
            for(cnt2 = cnt - 1; cnt2 >= cropstart; cnt2--) {
                if(distgroup + alldists[cnt2] < distThreshold) {
                    distgroup += alldists[cnt2];
                }
                else break;
            }

            // closed path with close points wrapping around the boundary?
            if(closedpath && cnt === pts.length - 2) {
                for(cnt3 = 0; cnt3 < cnt2; cnt3++) {
                    if(distgroup + alldists[cnt3] < distThreshold) {
                        distgroup += alldists[cnt3];
                    }
                    else break;
                }
            }
            ptcnt = cnt - cnt2 + cnt3 + 1;
            ptavg = Math.floor((cnt + cnt2 + cnt3 + 2) / 2);

            // either endpoint included: keep the endpoint
            if(!closedpath && cnt === pts.length - 2) newpt = pts[pts.length - 1];
            else if(!closedpath && cnt2 === -1) newpt = pts[0];

            // odd # of points - just take the central one
            else if(ptcnt % 2) newpt = getpt(ptavg);

            // even # of pts - average central two
            else {
                newpt = [(getpt(ptavg)[0] + getpt(ptavg + 1)[0]) / 2,
                    (getpt(ptavg)[1] + getpt(ptavg + 1)[1]) / 2];
            }

            pts.splice(cnt2 + 1, cnt - cnt2 + 1, newpt);
            cnt = cnt2 + 1;
            if(cnt3) cropstart = cnt3;
            if(closedpath) {
                if(cnt === pts.length - 2) pts[cnt3] = pts[pts.length - 1];
                else if(cnt === 0) pts[pts.length - 1] = pts[0];
            }
        }
    }
    pts.splice(0, cropstart);

    // done with the index parts - remove them so path generation works right
    // because it depends on only having [xpx, ypx]
    for(cnt = 0; cnt < pts.length; cnt++) pts[cnt].length = 2;

    // don't return single-point paths (ie all points were the same
    // so they got deleted?)
    if(pts.length < 2) return;
    else if(closedpath) {
        pts.pop();
        pi.paths.push(pts);
    }
    else {
        if(!edgeflag) {
            Lib.log('Unclosed interior contour?',
                pi.level, startLocStr, pts.join('L'));
        }

        // edge path - does it start where an existing edge path ends, or vice versa?
        var merged = false;
        for(i = 0; i < pi.edgepaths.length; i++) {
            edgepathi = pi.edgepaths[i];
            if(!merged && equalPts(edgepathi[0], pts[pts.length - 1], xtol, ytol)) {
                pts.pop();
                merged = true;

                // now does it ALSO meet the end of another (or the same) path?
                var doublemerged = false;
                for(j = 0; j < pi.edgepaths.length; j++) {
                    edgepathj = pi.edgepaths[j];
                    if(equalPts(edgepathj[edgepathj.length - 1], pts[0], xtol, ytol)) {
                        doublemerged = true;
                        pts.shift();
                        pi.edgepaths.splice(i, 1);
                        if(j === i) {
                            // the path is now closed
                            pi.paths.push(pts.concat(edgepathj));
                        }
                        else {
                            if(j > i) j--;
                            pi.edgepaths[j] = edgepathj.concat(pts, edgepathi);
                        }
                        break;
                    }
                }
                if(!doublemerged) {
                    pi.edgepaths[i] = pts.concat(edgepathi);
                }
            }
        }
        for(i = 0; i < pi.edgepaths.length; i++) {
            if(merged) break;
            edgepathi = pi.edgepaths[i];
            if(equalPts(edgepathi[edgepathi.length - 1], pts[0], xtol, ytol)) {
                pts.shift();
                pi.edgepaths[i] = edgepathi.concat(pts);
                merged = true;
            }
        }

        if(!merged) pi.edgepaths.push(pts);
    }
}

// special function to get the marching step of the
// first point in the path (leading to loc)
function startStep(mi, edgeflag, loc) {
    var dx = 0;
    var dy = 0;
    if(mi > 20 && edgeflag) {
        // these saddles start at +/- x
        if(mi === 208 || mi === 1114) {
            // if we're starting at the left side, we must be going right
            dx = loc[0] === 0 ? 1 : -1;
        }
        else {
            // if we're starting at the bottom, we must be going up
            dy = loc[1] === 0 ? 1 : -1;
        }
    }
    else if(constants.BOTTOMSTART.indexOf(mi) !== -1) dy = 1;
    else if(constants.LEFTSTART.indexOf(mi) !== -1) dx = 1;
    else if(constants.TOPSTART.indexOf(mi) !== -1) dy = -1;
    else dx = -1;
    return [dx, dy];
}

/*
 * Find the pixel coordinates of a particular crossing
 *
 * @param {object} pi: the pathinfo object at this level
 * @param {array} loc: the grid index [x, y] of the crossing
 * @param {array} step: the direction [dx, dy] we're moving on the grid
 *
 * @return {array} [xpx, ypx, xi, yi]: the first two are the pixel location,
 *   the next two are the interpolated grid indices, which we use for
 *   distance calculations to delete points that are too close together.
 *   This is important when the grid is nonuniform (and most dramatically when
 *   we're on log axes and include invalid (0 or negative) values.
 *   It's crucial to delete these extra two before turning an array of these
 *   points into a path, because those routines require length-2 points.
 */
function getInterpPx(pi, loc, step) {
    var locx = loc[0] + Math.max(step[0], 0);
    var locy = loc[1] + Math.max(step[1], 0);
    var zxy = pi.z[locy][locx];
    var xa = pi.xaxis;
    var ya = pi.yaxis;

    if(step[1]) {
        var dx = (pi.level - zxy) / (pi.z[locy][locx + 1] - zxy);

        return [xa.c2p((1 - dx) * pi.x[locx] + dx * pi.x[locx + 1], true),
            ya.c2p(pi.y[locy], true),
            locx + dx, locy];
    }
    else {
        var dy = (pi.level - zxy) / (pi.z[locy + 1][locx] - zxy);
        return [xa.c2p(pi.x[locx], true),
            ya.c2p((1 - dy) * pi.y[locy] + dy * pi.y[locy + 1], true),
            locx, locy + dy];
    }
}

},{"../../lib":697,"./constants":920}],929:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Color = _dereq_('../../components/color');

var heatmapHoverPoints = _dereq_('../heatmap/hover');

module.exports = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer) {
    var hoverData = heatmapHoverPoints(pointData, xval, yval, hovermode, hoverLayer, true);

    if(hoverData) {
        hoverData.forEach(function(hoverPt) {
            var trace = hoverPt.trace;
            if(trace.contours.type === 'constraint') {
                if(trace.fillcolor && Color.opacity(trace.fillcolor)) {
                    hoverPt.color = Color.addOpacity(trace.fillcolor, 1);
                }
                else if(trace.contours.showlines && Color.opacity(trace.line.color)) {
                    hoverPt.color = Color.addOpacity(trace.line.color, 1);
                }
            }
        });
    }

    return hoverData;
};

},{"../../components/color":574,"../heatmap/hover":952}],930:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Contour = {};

Contour.attributes = _dereq_('./attributes');
Contour.supplyDefaults = _dereq_('./defaults');
Contour.calc = _dereq_('./calc');
Contour.plot = _dereq_('./plot').plot;
Contour.style = _dereq_('./style');
Contour.colorbar = _dereq_('./colorbar');
Contour.hoverPoints = _dereq_('./hover');

Contour.moduleType = 'trace';
Contour.name = 'contour';
Contour.basePlotModule = _dereq_('../../plots/cartesian');
Contour.categories = ['cartesian', 'svg', '2dMap', 'contour', 'showLegend'];
Contour.meta = {
    
};

module.exports = Contour;

},{"../../plots/cartesian":756,"./attributes":916,"./calc":917,"./colorbar":919,"./defaults":925,"./hover":929,"./plot":934,"./style":936}],931:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

module.exports = function handleLabelDefaults(coerce, layout, lineColor, opts) {
    if(!opts) opts = {};
    var showLabels = coerce('contours.showlabels');
    if(showLabels) {
        var globalFont = layout.font;
        Lib.coerceFont(coerce, 'contours.labelfont', {
            family: globalFont.family,
            size: globalFont.size,
            color: lineColor
        });
        coerce('contours.labelformat');
    }

    if(opts.hasHover !== false) coerce('zhoverformat');
};

},{"../../lib":697}],932:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var Colorscale = _dereq_('../../components/colorscale');
var endPlus = _dereq_('./end_plus');

module.exports = function makeColorMap(trace) {
    var contours = trace.contours;
    var start = contours.start;
    var end = endPlus(contours);
    var cs = contours.size || 1;
    var nc = Math.floor((end - start) / cs) + 1;
    var extra = contours.coloring === 'lines' ? 0 : 1;

    if(!isFinite(cs)) {
        cs = 1;
        nc = 1;
    }

    var scl = trace.reversescale ?
        Colorscale.flipScale(trace.colorscale) :
        trace.colorscale;

    var len = scl.length;
    var domain = new Array(len);
    var range = new Array(len);

    var si, i;

    if(contours.coloring === 'heatmap') {
        if(trace.zauto && trace.autocontour === false) {
            trace.zmin = start - cs / 2;
            trace.zmax = trace.zmin + nc * cs;
        }

        for(i = 0; i < len; i++) {
            si = scl[i];

            domain[i] = si[0] * (trace.zmax - trace.zmin) + trace.zmin;
            range[i] = si[1];
        }

        // do the contours extend beyond the colorscale?
        // if so, extend the colorscale with constants
        var zRange = d3.extent([
            trace.zmin,
            trace.zmax,
            contours.start,
            contours.start + cs * (nc - 1)
        ]);
        var zmin = zRange[trace.zmin < trace.zmax ? 0 : 1];
        var zmax = zRange[trace.zmin < trace.zmax ? 1 : 0];

        if(zmin !== trace.zmin) {
            domain.splice(0, 0, zmin);
            range.splice(0, 0, Range[0]);
        }

        if(zmax !== trace.zmax) {
            domain.push(zmax);
            range.push(range[range.length - 1]);
        }
    }
    else {
        for(i = 0; i < len; i++) {
            si = scl[i];

            domain[i] = (si[0] * (nc + extra - 1) - (extra / 2)) * cs + start;
            range[i] = si[1];
        }
    }

    return Colorscale.makeColorScaleFunc({
        domain: domain,
        range: range,
    }, {
        noNumericCheck: true
    });
};

},{"../../components/colorscale":586,"./end_plus":927,"d3":151}],933:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var constants = _dereq_('./constants');

// Calculate all the marching indices, for ALL levels at once.
// since we want to be exhaustive we'll check for contour crossings
// at every intersection, rather than just following a path
// TODO: shorten the inner loop to only the relevant levels
module.exports = function makeCrossings(pathinfo) {
    var z = pathinfo[0].z;
    var m = z.length;
    var n = z[0].length; // we already made sure z isn't ragged in interp2d
    var twoWide = m === 2 || n === 2;
    var xi;
    var yi;
    var startIndices;
    var ystartIndices;
    var label;
    var corners;
    var mi;
    var pi;
    var i;

    for(yi = 0; yi < m - 1; yi++) {
        ystartIndices = [];
        if(yi === 0) ystartIndices = ystartIndices.concat(constants.BOTTOMSTART);
        if(yi === m - 2) ystartIndices = ystartIndices.concat(constants.TOPSTART);

        for(xi = 0; xi < n - 1; xi++) {
            startIndices = ystartIndices.slice();
            if(xi === 0) startIndices = startIndices.concat(constants.LEFTSTART);
            if(xi === n - 2) startIndices = startIndices.concat(constants.RIGHTSTART);

            label = xi + ',' + yi;
            corners = [[z[yi][xi], z[yi][xi + 1]],
                       [z[yi + 1][xi], z[yi + 1][xi + 1]]];
            for(i = 0; i < pathinfo.length; i++) {
                pi = pathinfo[i];
                mi = getMarchingIndex(pi.level, corners);
                if(!mi) continue;

                pi.crossings[label] = mi;
                if(startIndices.indexOf(mi) !== -1) {
                    pi.starts.push([xi, yi]);
                    if(twoWide && startIndices.indexOf(mi,
                            startIndices.indexOf(mi) + 1) !== -1) {
                        // the same square has starts from opposite sides
                        // it's not possible to have starts on opposite edges
                        // of a corner, only a start and an end...
                        // but if the array is only two points wide (either way)
                        // you can have starts on opposite sides.
                        pi.starts.push([xi, yi]);
                    }
                }
            }
        }
    }
};

// modified marching squares algorithm,
// so we disambiguate the saddle points from the start
// and we ignore the cases with no crossings
// the index I'm using is based on:
// http://en.wikipedia.org/wiki/Marching_squares
// except that the saddles bifurcate and I represent them
// as the decimal combination of the two appropriate
// non-saddle indices
function getMarchingIndex(val, corners) {
    var mi = (corners[0][0] > val ? 0 : 1) +
             (corners[0][1] > val ? 0 : 2) +
             (corners[1][1] > val ? 0 : 4) +
             (corners[1][0] > val ? 0 : 8);
    if(mi === 5 || mi === 10) {
        var avg = (corners[0][0] + corners[0][1] +
                   corners[1][0] + corners[1][1]) / 4;
        // two peaks with a big valley
        if(val > avg) return (mi === 5) ? 713 : 1114;
        // two valleys with a big ridge
        return (mi === 5) ? 104 : 208;
    }
    return (mi === 15) ? 0 : mi;
}

},{"./constants":920}],934:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

var Lib = _dereq_('../../lib');
var Drawing = _dereq_('../../components/drawing');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var Axes = _dereq_('../../plots/cartesian/axes');
var setConvert = _dereq_('../../plots/cartesian/set_convert');

var heatmapPlot = _dereq_('../heatmap/plot');
var makeCrossings = _dereq_('./make_crossings');
var findAllPaths = _dereq_('./find_all_paths');
var emptyPathinfo = _dereq_('./empty_pathinfo');
var convertToConstraints = _dereq_('./convert_to_constraints');
var closeBoundaries = _dereq_('./close_boundaries');
var constants = _dereq_('./constants');
var costConstants = constants.LABELOPTIMIZER;

exports.plot = function plot(gd, plotinfo, cdcontours, contourLayer) {
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    Lib.makeTraceGroups(contourLayer, cdcontours, 'contour').each(function(cd) {
        var plotGroup = d3.select(this);
        var cd0 = cd[0];
        var trace = cd0.trace;
        var x = cd0.x;
        var y = cd0.y;
        var contours = trace.contours;
        var pathinfo = emptyPathinfo(contours, plotinfo, cd0);

        // use a heatmap to fill - draw it behind the lines
        var heatmapColoringLayer = Lib.ensureSingle(plotGroup, 'g', 'heatmapcoloring');
        var cdheatmaps = [];
        if(contours.coloring === 'heatmap') {
            if(trace.zauto && (trace.autocontour === false)) {
                trace._input.zmin = trace.zmin =
                    contours.start - contours.size / 2;
                trace._input.zmax = trace.zmax =
                    trace.zmin + pathinfo.length * contours.size;
            }
            cdheatmaps = [cd];
        }
        heatmapPlot(gd, plotinfo, cdheatmaps, heatmapColoringLayer);

        makeCrossings(pathinfo);
        findAllPaths(pathinfo);

        var leftedge = xa.c2p(x[0], true);
        var rightedge = xa.c2p(x[x.length - 1], true);
        var bottomedge = ya.c2p(y[0], true);
        var topedge = ya.c2p(y[y.length - 1], true);
        var perimeter = [
            [leftedge, topedge],
            [rightedge, topedge],
            [rightedge, bottomedge],
            [leftedge, bottomedge]
        ];

        var fillPathinfo = pathinfo;
        if(contours.type === 'constraint') {
            fillPathinfo = convertToConstraints(pathinfo, contours._operation);
            closeBoundaries(fillPathinfo, contours._operation, perimeter, trace);
        }

        // draw everything
        makeBackground(plotGroup, perimeter, contours);
        makeFills(plotGroup, fillPathinfo, perimeter, contours);
        makeLinesAndLabels(plotGroup, pathinfo, gd, cd0, contours, perimeter);
        clipGaps(plotGroup, plotinfo, gd, cd0, perimeter);
    });
};

function makeBackground(plotgroup, perimeter, contours) {
    var bggroup = Lib.ensureSingle(plotgroup, 'g', 'contourbg');

    var bgfill = bggroup.selectAll('path')
        .data(contours.coloring === 'fill' ? [0] : []);
    bgfill.enter().append('path');
    bgfill.exit().remove();
    bgfill
        .attr('d', 'M' + perimeter.join('L') + 'Z')
        .style('stroke', 'none');
}

function makeFills(plotgroup, pathinfo, perimeter, contours) {
    var fillgroup = Lib.ensureSingle(plotgroup, 'g', 'contourfill');

    var fillitems = fillgroup.selectAll('path')
        .data(contours.coloring === 'fill' || (contours.type === 'constraint' && contours._operation !== '=') ? pathinfo : []);
    fillitems.enter().append('path');
    fillitems.exit().remove();
    fillitems.each(function(pi) {
        // join all paths for this level together into a single path
        // first follow clockwise around the perimeter to close any open paths
        // if the whole perimeter is above this level, start with a path
        // enclosing the whole thing. With all that, the parity should mean
        // that we always fill everything above the contour, nothing below
        var fullpath = joinAllPaths(pi, perimeter);

        if(!fullpath) d3.select(this).remove();
        else d3.select(this).attr('d', fullpath).style('stroke', 'none');
    });
}

function initFullPath(pi, perimeter) {
    var prefixBoundary = pi.prefixBoundary;
    if(prefixBoundary === undefined) {
        var edgeVal2 = Math.min(pi.z[0][0], pi.z[0][1]);
        prefixBoundary = (!pi.edgepaths.length && edgeVal2 > pi.level);
    }

    if(prefixBoundary) {
        // TODO: why does ^^ not work for constraints?
        // pi.prefixBoundary gets set by closeBoundaries
        return 'M' + perimeter.join('L') + 'Z';
    }
    return '';
}

function joinAllPaths(pi, perimeter) {
    var fullpath = initFullPath(pi, perimeter);
    var i = 0;
    var startsleft = pi.edgepaths.map(function(v, i) { return i; });
    var newloop = true;
    var endpt;
    var newendpt;
    var cnt;
    var nexti;
    var possiblei;
    var addpath;

    function istop(pt) { return Math.abs(pt[1] - perimeter[0][1]) < 0.01; }
    function isbottom(pt) { return Math.abs(pt[1] - perimeter[2][1]) < 0.01; }
    function isleft(pt) { return Math.abs(pt[0] - perimeter[0][0]) < 0.01; }
    function isright(pt) { return Math.abs(pt[0] - perimeter[2][0]) < 0.01; }

    while(startsleft.length) {
        addpath = Drawing.smoothopen(pi.edgepaths[i], pi.smoothing);
        fullpath += newloop ? addpath : addpath.replace(/^M/, 'L');
        startsleft.splice(startsleft.indexOf(i), 1);
        endpt = pi.edgepaths[i][pi.edgepaths[i].length - 1];
        nexti = -1;

        // now loop through sides, moving our endpoint until we find a new start
        for(cnt = 0; cnt < 4; cnt++) { // just to prevent infinite loops
            if(!endpt) {
                Lib.log('Missing end?', i, pi);
                break;
            }

            if(istop(endpt) && !isright(endpt)) newendpt = perimeter[1]; // right top
            else if(isleft(endpt)) newendpt = perimeter[0]; // left top
            else if(isbottom(endpt)) newendpt = perimeter[3]; // right bottom
            else if(isright(endpt)) newendpt = perimeter[2]; // left bottom

            for(possiblei = 0; possiblei < pi.edgepaths.length; possiblei++) {
                var ptNew = pi.edgepaths[possiblei][0];
                // is ptNew on the (horz. or vert.) segment from endpt to newendpt?
                if(Math.abs(endpt[0] - newendpt[0]) < 0.01) {
                    if(Math.abs(endpt[0] - ptNew[0]) < 0.01 &&
                            (ptNew[1] - endpt[1]) * (newendpt[1] - ptNew[1]) >= 0) {
                        newendpt = ptNew;
                        nexti = possiblei;
                    }
                }
                else if(Math.abs(endpt[1] - newendpt[1]) < 0.01) {
                    if(Math.abs(endpt[1] - ptNew[1]) < 0.01 &&
                            (ptNew[0] - endpt[0]) * (newendpt[0] - ptNew[0]) >= 0) {
                        newendpt = ptNew;
                        nexti = possiblei;
                    }
                }
                else {
                    Lib.log('endpt to newendpt is not vert. or horz.',
                        endpt, newendpt, ptNew);
                }
            }

            endpt = newendpt;

            if(nexti >= 0) break;
            fullpath += 'L' + newendpt;
        }

        if(nexti === pi.edgepaths.length) {
            Lib.log('unclosed perimeter path');
            break;
        }

        i = nexti;

        // if we closed back on a loop we already included,
        // close it and start a new loop
        newloop = (startsleft.indexOf(i) === -1);
        if(newloop) {
            i = startsleft[0];
            fullpath += 'Z';
        }
    }

    // finally add the interior paths
    for(i = 0; i < pi.paths.length; i++) {
        fullpath += Drawing.smoothclosed(pi.paths[i], pi.smoothing);
    }

    return fullpath;
}

function makeLinesAndLabels(plotgroup, pathinfo, gd, cd0, contours, perimeter) {
    var lineContainer = Lib.ensureSingle(plotgroup, 'g', 'contourlines');
    var showLines = contours.showlines !== false;
    var showLabels = contours.showlabels;
    var clipLinesForLabels = showLines && showLabels;

    // Even if we're not going to show lines, we need to create them
    // if we're showing labels, because the fill paths include the perimeter
    // so can't be used to position the labels correctly.
    // In this case we'll remove the lines after making the labels.
    var linegroup = exports.createLines(lineContainer, showLines || showLabels, pathinfo);

    var lineClip = exports.createLineClip(lineContainer, clipLinesForLabels, gd, cd0.trace.uid);

    var labelGroup = plotgroup.selectAll('g.contourlabels')
        .data(showLabels ? [0] : []);

    labelGroup.exit().remove();

    labelGroup.enter().append('g')
        .classed('contourlabels', true);

    if(showLabels) {
        var labelClipPathData = [];
        var labelData = [];

        // invalidate the getTextLocation cache in case paths changed
        Lib.clearLocationCache();

        var contourFormat = exports.labelFormatter(contours, cd0.t.cb, gd._fullLayout);

        var dummyText = Drawing.tester.append('text')
            .attr('data-notex', 1)
            .call(Drawing.font, contours.labelfont);

        var xa = pathinfo[0].xaxis;
        var ya = pathinfo[0].yaxis;
        var xLen = xa._length;
        var yLen = ya._length;
        var xRng = xa.range;
        var yRng = ya.range;
        var x0 = Math.max(perimeter[0][0], 0);
        var x1 = Math.min(perimeter[2][0], xLen);
        var y0 = Math.max(perimeter[0][1], 0);
        var y1 = Math.min(perimeter[2][1], yLen);

        // visible bounds of the contour trace (and the midpoints, to
        // help with cost calculations)
        var bounds = {};

        if(xRng[0] < xRng[1]) {
            bounds.left = x0;
            bounds.right = x1;
        } else {
            bounds.left = x1;
            bounds.right = x0;
        }

        if(yRng[0] < yRng[1]) {
            bounds.top = y0;
            bounds.bottom = y1;
        } else {
            bounds.top = y1;
            bounds.bottom = y0;
        }

        bounds.middle = (bounds.top + bounds.bottom) / 2;
        bounds.center = (bounds.left + bounds.right) / 2;

        labelClipPathData.push([
            [bounds.left, bounds.top],
            [bounds.right, bounds.top],
            [bounds.right, bounds.bottom],
            [bounds.left, bounds.bottom]
        ]);

        var plotDiagonal = Math.sqrt(xLen * xLen + yLen * yLen);

        // the path length to use to scale the number of labels to draw:
        var normLength = constants.LABELDISTANCE * plotDiagonal /
            Math.max(1, pathinfo.length / constants.LABELINCREASE);

        linegroup.each(function(d) {
            var textOpts = exports.calcTextOpts(d.level, contourFormat, dummyText, gd);

            d3.select(this).selectAll('path').each(function() {
                var path = this;
                var pathBounds = Lib.getVisibleSegment(path, bounds, textOpts.height / 2);
                if(!pathBounds) return;

                if(pathBounds.len < (textOpts.width + textOpts.height) * constants.LABELMIN) return;

                var maxLabels = Math.min(Math.ceil(pathBounds.len / normLength),
                    constants.LABELMAX);

                for(var i = 0; i < maxLabels; i++) {
                    var loc = exports.findBestTextLocation(path, pathBounds, textOpts,
                        labelData, bounds);

                    if(!loc) break;

                    exports.addLabelData(loc, textOpts, labelData, labelClipPathData);
                }
            });
        });

        dummyText.remove();

        exports.drawLabels(labelGroup, labelData, gd, lineClip,
            clipLinesForLabels ? labelClipPathData : null);
    }

    if(showLabels && !showLines) linegroup.remove();
}

exports.createLines = function(lineContainer, makeLines, pathinfo) {
    var smoothing = pathinfo[0].smoothing;

    var linegroup = lineContainer.selectAll('g.contourlevel')
        .data(makeLines ? pathinfo : []);

    linegroup.exit().remove();
    linegroup.enter().append('g')
        .classed('contourlevel', true);

    if(makeLines) {
        // pedgepaths / ppaths are used by contourcarpet, for the paths transformed from a/b to x/y
        // edgepaths / paths are used by contour since it's in x/y from the start
        var opencontourlines = linegroup.selectAll('path.openline')
            .data(function(d) { return d.pedgepaths || d.edgepaths; });

        opencontourlines.exit().remove();
        opencontourlines.enter().append('path')
            .classed('openline', true);

        opencontourlines
            .attr('d', function(d) {
                return Drawing.smoothopen(d, smoothing);
            })
            .style('stroke-miterlimit', 1)
            .style('vector-effect', 'non-scaling-stroke');

        var closedcontourlines = linegroup.selectAll('path.closedline')
            .data(function(d) { return d.ppaths || d.paths; });

        closedcontourlines.exit().remove();
        closedcontourlines.enter().append('path')
            .classed('closedline', true);

        closedcontourlines
            .attr('d', function(d) {
                return Drawing.smoothclosed(d, smoothing);
            })
            .style('stroke-miterlimit', 1)
            .style('vector-effect', 'non-scaling-stroke');
    }

    return linegroup;
};

exports.createLineClip = function(lineContainer, clipLinesForLabels, gd, uid) {
    var clips = gd._fullLayout._clips;
    var clipId = clipLinesForLabels ? ('clipline' + uid) : null;

    var lineClip = clips.selectAll('#' + clipId)
        .data(clipLinesForLabels ? [0] : []);
    lineClip.exit().remove();

    lineClip.enter().append('clipPath')
        .classed('contourlineclip', true)
        .attr('id', clipId);

    Drawing.setClipUrl(lineContainer, clipId, gd);

    return lineClip;
};

exports.labelFormatter = function(contours, colorbar, fullLayout) {
    if(contours.labelformat) {
        return fullLayout._d3locale.numberFormat(contours.labelformat);
    }
    else {
        var formatAxis;
        if(colorbar) {
            formatAxis = colorbar.axis;
        }
        else {
            formatAxis = {
                type: 'linear',
                _id: 'ycontour',
                showexponent: 'all',
                exponentformat: 'B'
            };

            if(contours.type === 'constraint') {
                var value = contours.value;
                if(Array.isArray(value)) {
                    formatAxis.range = [value[0], value[value.length - 1]];
                }
                else formatAxis.range = [value, value];
            }
            else {
                formatAxis.range = [contours.start, contours.end];
                formatAxis.nticks = (contours.end - contours.start) / contours.size;
            }

            if(formatAxis.range[0] === formatAxis.range[1]) {
                formatAxis.range[1] += formatAxis.range[0] || 1;
            }
            if(!formatAxis.nticks) formatAxis.nticks = 1000;

            setConvert(formatAxis, fullLayout);
            Axes.prepTicks(formatAxis);
            formatAxis._tmin = null;
            formatAxis._tmax = null;
        }
        return function(v) {
            return Axes.tickText(formatAxis, v).text;
        };
    }
};

exports.calcTextOpts = function(level, contourFormat, dummyText, gd) {
    var text = contourFormat(level);
    dummyText.text(text)
        .call(svgTextUtils.convertToTspans, gd);
    var bBox = Drawing.bBox(dummyText.node(), true);

    return {
        text: text,
        width: bBox.width,
        height: bBox.height,
        level: level,
        dy: (bBox.top + bBox.bottom) / 2
    };
};

exports.findBestTextLocation = function(path, pathBounds, textOpts, labelData, plotBounds) {
    var textWidth = textOpts.width;

    var p0, dp, pMax, pMin, loc;
    if(pathBounds.isClosed) {
        dp = pathBounds.len / costConstants.INITIALSEARCHPOINTS;
        p0 = pathBounds.min + dp / 2;
        pMax = pathBounds.max;
    }
    else {
        dp = (pathBounds.len - textWidth) / (costConstants.INITIALSEARCHPOINTS + 1);
        p0 = pathBounds.min + dp + textWidth / 2;
        pMax = pathBounds.max - (dp + textWidth) / 2;
    }

    var cost = Infinity;
    for(var j = 0; j < costConstants.ITERATIONS; j++) {
        for(var p = p0; p < pMax; p += dp) {
            var newLocation = Lib.getTextLocation(path, pathBounds.total, p, textWidth);
            var newCost = locationCost(newLocation, textOpts, labelData, plotBounds);
            if(newCost < cost) {
                cost = newCost;
                loc = newLocation;
                pMin = p;
            }
        }
        if(cost > costConstants.MAXCOST * 2) break;

        // subsequent iterations just look half steps away from the
        // best we found in the previous iteration
        if(j) dp /= 2;
        p0 = pMin - dp / 2;
        pMax = p0 + dp * 1.5;
    }
    if(cost <= costConstants.MAXCOST) return loc;
};

/*
 * locationCost: a cost function for label locations
 * composed of three kinds of penalty:
 * - for open paths, being close to the end of the path
 * - the angle away from horizontal
 * - being too close to already placed neighbors
 */
function locationCost(loc, textOpts, labelData, bounds) {
    var halfWidth = textOpts.width / 2;
    var halfHeight = textOpts.height / 2;
    var x = loc.x;
    var y = loc.y;
    var theta = loc.theta;
    var dx = Math.cos(theta) * halfWidth;
    var dy = Math.sin(theta) * halfWidth;

    // cost for being near an edge
    var normX = ((x > bounds.center) ? (bounds.right - x) : (x - bounds.left)) /
        (dx + Math.abs(Math.sin(theta) * halfHeight));
    var normY = ((y > bounds.middle) ? (bounds.bottom - y) : (y - bounds.top)) /
        (Math.abs(dy) + Math.cos(theta) * halfHeight);
    if(normX < 1 || normY < 1) return Infinity;
    var cost = costConstants.EDGECOST * (1 / (normX - 1) + 1 / (normY - 1));

    // cost for not being horizontal
    cost += costConstants.ANGLECOST * theta * theta;

    // cost for being close to other labels
    var x1 = x - dx;
    var y1 = y - dy;
    var x2 = x + dx;
    var y2 = y + dy;
    for(var i = 0; i < labelData.length; i++) {
        var labeli = labelData[i];
        var dxd = Math.cos(labeli.theta) * labeli.width / 2;
        var dyd = Math.sin(labeli.theta) * labeli.width / 2;
        var dist = Lib.segmentDistance(
            x1, y1,
            x2, y2,
            labeli.x - dxd, labeli.y - dyd,
            labeli.x + dxd, labeli.y + dyd
        ) * 2 / (textOpts.height + labeli.height);

        var sameLevel = labeli.level === textOpts.level;
        var distOffset = sameLevel ? costConstants.SAMELEVELDISTANCE : 1;

        if(dist <= distOffset) return Infinity;

        var distFactor = costConstants.NEIGHBORCOST *
            (sameLevel ? costConstants.SAMELEVELFACTOR : 1);

        cost += distFactor / (dist - distOffset);
    }

    return cost;
}

exports.addLabelData = function(loc, textOpts, labelData, labelClipPathData) {
    var halfWidth = textOpts.width / 2;
    var halfHeight = textOpts.height / 2;

    var x = loc.x;
    var y = loc.y;
    var theta = loc.theta;

    var sin = Math.sin(theta);
    var cos = Math.cos(theta);
    var dxw = halfWidth * cos;
    var dxh = halfHeight * sin;
    var dyw = halfWidth * sin;
    var dyh = -halfHeight * cos;
    var bBoxPts = [
        [x - dxw - dxh, y - dyw - dyh],
        [x + dxw - dxh, y + dyw - dyh],
        [x + dxw + dxh, y + dyw + dyh],
        [x - dxw + dxh, y - dyw + dyh],
    ];

    labelData.push({
        text: textOpts.text,
        x: x,
        y: y,
        dy: textOpts.dy,
        theta: theta,
        level: textOpts.level,
        width: textOpts.width,
        height: textOpts.height
    });

    labelClipPathData.push(bBoxPts);
};

exports.drawLabels = function(labelGroup, labelData, gd, lineClip, labelClipPathData) {
    var labels = labelGroup.selectAll('text')
        .data(labelData, function(d) {
            return d.text + ',' + d.x + ',' + d.y + ',' + d.theta;
        });

    labels.exit().remove();

    labels.enter().append('text')
        .attr({
            'data-notex': 1,
            'text-anchor': 'middle'
        })
        .each(function(d) {
            var x = d.x + Math.sin(d.theta) * d.dy;
            var y = d.y - Math.cos(d.theta) * d.dy;
            d3.select(this)
                .text(d.text)
                .attr({
                    x: x,
                    y: y,
                    transform: 'rotate(' + (180 * d.theta / Math.PI) + ' ' + x + ' ' + y + ')'
                })
                .call(svgTextUtils.convertToTspans, gd);
        });

    if(labelClipPathData) {
        var clipPath = '';
        for(var i = 0; i < labelClipPathData.length; i++) {
            clipPath += 'M' + labelClipPathData[i].join('L') + 'Z';
        }

        var lineClipPath = Lib.ensureSingle(lineClip, 'path', '');
        lineClipPath.attr('d', clipPath);
    }
};

function clipGaps(plotGroup, plotinfo, gd, cd0, perimeter) {
    var clips = gd._fullLayout._clips;
    var clipId = 'clip' + cd0.trace.uid;

    var clipPath = clips.selectAll('#' + clipId)
        .data(cd0.trace.connectgaps ? [] : [0]);
    clipPath.enter().append('clipPath')
        .classed('contourclip', true)
        .attr('id', clipId);
    clipPath.exit().remove();

    if(cd0.trace.connectgaps === false) {
        var clipPathInfo = {
            // fraction of the way from missing to present point
            // to draw the boundary.
            // if you make this 1 (or 1-epsilon) then a point in
            // a sea of missing data will disappear entirely.
            level: 0.9,
            crossings: {},
            starts: [],
            edgepaths: [],
            paths: [],
            xaxis: plotinfo.xaxis,
            yaxis: plotinfo.yaxis,
            x: cd0.x,
            y: cd0.y,
            // 0 = no data, 1 = data
            z: makeClipMask(cd0),
            smoothing: 0
        };

        makeCrossings([clipPathInfo]);
        findAllPaths([clipPathInfo]);
        var fullpath = joinAllPaths(clipPathInfo, perimeter);

        var path = Lib.ensureSingle(clipPath, 'path', '');
        path.attr('d', fullpath);
    }
    else clipId = null;

    Drawing.setClipUrl(plotGroup, clipId, gd);
}

function makeClipMask(cd0) {
    var empties = cd0.trace._emptypoints;
    var z = [];
    var m = cd0.z.length;
    var n = cd0.z[0].length;
    var i;
    var row = [];
    var emptyPoint;

    for(i = 0; i < n; i++) row.push(1);
    for(i = 0; i < m; i++) z.push(row.slice());
    for(i = 0; i < empties.length; i++) {
        emptyPoint = empties[i];
        z[emptyPoint[0]][emptyPoint[1]] = 0;
    }
    // save this mask to determine whether to show this data in hover
    cd0.zmask = z;
    return z;
}

},{"../../components/drawing":595,"../../lib":697,"../../lib/svg_text_utils":721,"../../plots/cartesian/axes":745,"../../plots/cartesian/set_convert":763,"../heatmap/plot":956,"./close_boundaries":918,"./constants":920,"./convert_to_constraints":924,"./empty_pathinfo":926,"./find_all_paths":928,"./make_crossings":933,"d3":151}],935:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Axes = _dereq_('../../plots/cartesian/axes');
var Lib = _dereq_('../../lib');


module.exports = function setContours(trace) {
    var contours = trace.contours;

    // check if we need to auto-choose contour levels
    if(trace.autocontour) {
        var zmin = trace.zmin;
        var zmax = trace.zmax;
        if(zmin === undefined || zmax === undefined) {
            zmin = Lib.aggNums(Math.min, null, trace._z);
            zmax = Lib.aggNums(Math.max, null, trace._z);
        }
        var dummyAx = autoContours(zmin, zmax, trace.ncontours);

        contours.size = dummyAx.dtick;

        contours.start = Axes.tickFirst(dummyAx);
        dummyAx.range.reverse();
        contours.end = Axes.tickFirst(dummyAx);

        if(contours.start === zmin) contours.start += contours.size;
        if(contours.end === zmax) contours.end -= contours.size;

        // if you set a small ncontours, *and* the ends are exactly on zmin/zmax
        // there's an edge case where start > end now. Make sure there's at least
        // one meaningful contour, put it midway between the crossed values
        if(contours.start > contours.end) {
            contours.start = contours.end = (contours.start + contours.end) / 2;
        }

        // copy auto-contour info back to the source data.
        // previously we copied the whole contours object back, but that had
        // other info (coloring, showlines) that should be left to supplyDefaults
        if(!trace._input.contours) trace._input.contours = {};
        Lib.extendFlat(trace._input.contours, {
            start: contours.start,
            end: contours.end,
            size: contours.size
        });
        trace._input.autocontour = true;
    }
    else if(contours.type !== 'constraint') {
        // sanity checks on manually-supplied start/end/size
        var start = contours.start;
        var end = contours.end;
        var inputContours = trace._input.contours;

        if(start > end) {
            contours.start = inputContours.start = end;
            end = contours.end = inputContours.end = start;
            start = contours.start;
        }

        if(!(contours.size > 0)) {
            var sizeOut;
            if(start === end) sizeOut = 1;
            else sizeOut = autoContours(start, end, trace.ncontours).dtick;

            inputContours.size = contours.size = sizeOut;
        }
    }
};


/*
 * autoContours: make a dummy axis object with dtick we can use
 * as contours.size, and if needed we can use Axes.tickFirst
 * with this axis object to calculate the start and end too
 *
 * start: the value to start the contours at
 * end: the value to end at (must be > start)
 * ncontours: max number of contours to make, like roughDTick
 *
 * returns: an axis object
 */
function autoContours(start, end, ncontours) {
    var dummyAx = {
        type: 'linear',
        range: [start, end]
    };

    Axes.autoTicks(
        dummyAx,
        (end - start) / (ncontours || 15)
    );

    return dummyAx;
}

},{"../../lib":697,"../../plots/cartesian/axes":745}],936:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

var Drawing = _dereq_('../../components/drawing');
var heatmapStyle = _dereq_('../heatmap/style');

var makeColorMap = _dereq_('./make_color_map');


module.exports = function style(gd) {
    var contours = d3.select(gd).selectAll('g.contour');

    contours.style('opacity', function(d) {
        return d[0].trace.opacity;
    });

    contours.each(function(d) {
        var c = d3.select(this);
        var trace = d[0].trace;
        var contours = trace.contours;
        var line = trace.line;
        var cs = contours.size || 1;
        var start = contours.start;

        // for contourcarpet only - is this a constraint-type contour trace?
        var isConstraintType = contours.type === 'constraint';
        var colorLines = !isConstraintType && contours.coloring === 'lines';
        var colorFills = !isConstraintType && contours.coloring === 'fill';

        var colorMap = (colorLines || colorFills) ? makeColorMap(trace) : null;

        c.selectAll('g.contourlevel').each(function(d) {
            d3.select(this).selectAll('path')
                .call(Drawing.lineGroupStyle,
                    line.width,
                    colorLines ? colorMap(d.level) : line.color,
                    line.dash);
        });

        var labelFont = contours.labelfont;
        c.selectAll('g.contourlabels text').each(function(d) {
            Drawing.font(d3.select(this), {
                family: labelFont.family,
                size: labelFont.size,
                color: labelFont.color || (colorLines ? colorMap(d.level) : line.color)
            });
        });

        if(isConstraintType) {
            c.selectAll('g.contourfill path')
                .style('fill', trace.fillcolor);
        }
        else if(colorFills) {
            var firstFill;

            c.selectAll('g.contourfill path')
                .style('fill', function(d) {
                    if(firstFill === undefined) firstFill = d.level;
                    return colorMap(d.level + 0.5 * cs);
                });

            if(firstFill === undefined) firstFill = start;

            c.selectAll('g.contourbg path')
                .style('fill', colorMap(firstFill - 0.5 * cs));
        }
    });

    heatmapStyle(gd);
};

},{"../../components/drawing":595,"../heatmap/style":957,"./make_color_map":932,"d3":151}],937:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
var handleLabelDefaults = _dereq_('./label_defaults');


module.exports = function handleStyleDefaults(traceIn, traceOut, coerce, layout, opts) {
    var coloring = coerce('contours.coloring');

    var showLines;
    var lineColor = '';
    if(coloring === 'fill') showLines = coerce('contours.showlines');

    if(showLines !== false) {
        if(coloring !== 'lines') lineColor = coerce('line.color', '#000');
        coerce('line.width', 0.5);
        coerce('line.dash');
    }

    if(coloring !== 'none') {
        // plots/plots always coerces showlegend to true, but in this case
        // we default to false and (by default) show a colorbar instead
        if(traceIn.showlegend !== true) traceOut.showlegend = false;
        traceOut._dfltShowLegend = false;

        colorscaleDefaults(
            traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'}
        );
    }

    coerce('line.smoothing');

    handleLabelDefaults(coerce, layout, lineColor, opts);
};

},{"../../components/colorscale/defaults":584,"./label_defaults":931}],938:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var heatmapAttrs = _dereq_('../heatmap/attributes');
var contourAttrs = _dereq_('../contour/attributes');
var contourContourAttrs = contourAttrs.contours;
var scatterAttrs = _dereq_('../scatter/attributes');
var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;

var scatterLineAttrs = scatterAttrs.line;

module.exports = extendFlat({
    carpet: {
        valType: 'string',
        
        editType: 'calc',
        
    },
    z: heatmapAttrs.z,
    a: heatmapAttrs.x,
    a0: heatmapAttrs.x0,
    da: heatmapAttrs.dx,
    b: heatmapAttrs.y,
    b0: heatmapAttrs.y0,
    db: heatmapAttrs.dy,
    text: heatmapAttrs.text,
    hovertext: heatmapAttrs.hovertext,
    transpose: heatmapAttrs.transpose,
    atype: heatmapAttrs.xtype,
    btype: heatmapAttrs.ytype,

    fillcolor: contourAttrs.fillcolor,

    autocontour: contourAttrs.autocontour,
    ncontours: contourAttrs.ncontours,

    contours: {
        type: contourContourAttrs.type,
        start: contourContourAttrs.start,
        end: contourContourAttrs.end,
        size: contourContourAttrs.size,
        coloring: {
            // from contourAttrs.contours.coloring but no 'heatmap' option
            valType: 'enumerated',
            values: ['fill', 'lines', 'none'],
            dflt: 'fill',
            
            editType: 'calc',
            
        },
        showlines: contourContourAttrs.showlines,
        showlabels: contourContourAttrs.showlabels,
        labelfont: contourContourAttrs.labelfont,
        labelformat: contourContourAttrs.labelformat,
        operation: contourContourAttrs.operation,
        value: contourContourAttrs.value,
        editType: 'calc',
        impliedEdits: {'autocontour': false}
    },

    line: {
        color: extendFlat({}, scatterLineAttrs.color, {
            
        }),
        width: scatterLineAttrs.width,
        dash: scatterLineAttrs.dash,
        smoothing: extendFlat({}, scatterLineAttrs.smoothing, {
            
        }),
        editType: 'plot'
    },
    transforms: undefined
},

    colorscaleAttrs('', {
        cLetter: 'z',
        autoColorDflt: false
    }),
    { colorbar: colorbarAttrs }
);

},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../lib/extend":687,"../contour/attributes":916,"../heatmap/attributes":945,"../scatter/attributes":1048}],939:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorscaleCalc = _dereq_('../../components/colorscale/calc');
var Lib = _dereq_('../../lib');

var convertColumnData = _dereq_('../heatmap/convert_column_xyz');
var clean2dArray = _dereq_('../heatmap/clean_2d_array');
var interp2d = _dereq_('../heatmap/interp2d');
var findEmpties = _dereq_('../heatmap/find_empties');
var makeBoundArray = _dereq_('../heatmap/make_bound_array');
var supplyDefaults = _dereq_('./defaults');
var lookupCarpet = _dereq_('../carpet/lookup_carpetid');
var setContours = _dereq_('../contour/set_contours');

// most is the same as heatmap calc, then adjust it
// though a few things inside heatmap calc still look for
// contour maps, because the makeBoundArray calls are too entangled
module.exports = function calc(gd, trace) {
    var carpet = trace._carpetTrace = lookupCarpet(gd, trace);
    if(!carpet || !carpet.visible || carpet.visible === 'legendonly') return;

    if(!trace.a || !trace.b) {
        // Look up the original incoming carpet data:
        var carpetdata = gd.data[carpet.index];

        // Look up the incoming trace data, *except* perform a shallow
        // copy so that we're not actually modifying it when we use it
        // to supply defaults:
        var tracedata = gd.data[trace.index];
        // var tracedata = extendFlat({}, gd.data[trace.index]);

        // If the data is not specified
        if(!tracedata.a) tracedata.a = carpetdata.a;
        if(!tracedata.b) tracedata.b = carpetdata.b;

        supplyDefaults(tracedata, trace, trace._defaultColor, gd._fullLayout);
    }

    var cd = heatmappishCalc(gd, trace);

    setContours(trace);

    return cd;
};

function heatmappishCalc(gd, trace) {
    // prepare the raw data
    // run makeCalcdata on x and y even for heatmaps, in case of category mappings
    var carpet = trace._carpetTrace;
    var aax = carpet.aaxis;
    var bax = carpet.baxis;
    var a,
        a0,
        da,
        b,
        b0,
        db,
        z;

    // cancel minimum tick spacings (only applies to bars and boxes)
    aax._minDtick = 0;
    bax._minDtick = 0;

    if(Lib.isArray1D(trace.z)) convertColumnData(trace, aax, bax, 'a', 'b', ['z']);
    a = trace._a = trace._a || trace.a;
    b = trace._b = trace._b || trace.b;

    a = a ? aax.makeCalcdata(trace, '_a') : [];
    b = b ? bax.makeCalcdata(trace, '_b') : [];
    a0 = trace.a0 || 0;
    da = trace.da || 1;
    b0 = trace.b0 || 0;
    db = trace.db || 1;

    z = trace._z = clean2dArray(trace._z || trace.z, trace.transpose);

    trace._emptypoints = findEmpties(z);
    interp2d(z, trace._emptypoints);

    // create arrays of brick boundaries, to be used by autorange and heatmap.plot
    var xlen = Lib.maxRowLength(z);
    var xIn = trace.xtype === 'scaled' ? '' : a;
    var xArray = makeBoundArray(trace, xIn, a0, da, xlen, aax);
    var yIn = trace.ytype === 'scaled' ? '' : b;
    var yArray = makeBoundArray(trace, yIn, b0, db, z.length, bax);

    var cd0 = {
        a: xArray,
        b: yArray,
        z: z,
    };

    if(trace.contours.type === 'levels' && trace.contours.coloring !== 'none') {
        // auto-z and autocolorscale if applicable
        colorscaleCalc(gd, trace, {
            vals: z,
            containerStr: '',
            cLetter: 'z'
        });
    }

    return [cd0];
}

},{"../../components/colorscale/calc":582,"../../lib":697,"../carpet/lookup_carpetid":894,"../contour/set_contours":935,"../heatmap/clean_2d_array":947,"../heatmap/convert_column_xyz":949,"../heatmap/find_empties":951,"../heatmap/interp2d":954,"../heatmap/make_bound_array":955,"./defaults":940}],940:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

var handleXYZDefaults = _dereq_('../heatmap/xyz_defaults');
var attributes = _dereq_('./attributes');
var handleConstraintDefaults = _dereq_('../contour/constraint_defaults');
var handleContoursDefaults = _dereq_('../contour/contours_defaults');
var handleStyleDefaults = _dereq_('../contour/style_defaults');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    function coerce2(attr) {
        return Lib.coerce2(traceIn, traceOut, attributes, attr);
    }

    coerce('carpet');

    // If either a or b is not present, then it's not a valid trace *unless* the carpet
    // axis has the a or b values we're looking for. So if these are not found, just defer
    // that decision until the calc step.
    //
    // NB: the calc step will modify the original data input by assigning whichever of
    // a or b are missing. This is necessary because panning goes right from supplyDefaults
    // to plot (skipping calc). That means on subsequent updates, this *will* need to be
    // able to find a and b.
    //
    // The long-term proper fix is that this should perhaps use underscored attributes to
    // at least modify the user input to a slightly lesser extent. Fully removing the
    // input mutation is challenging. The underscore approach is not currently taken since
    // it requires modification to all of the functions below that expect the coerced
    // attribute name to match the property name -- except '_a' !== 'a' so that is not
    // straightforward.
    if(traceIn.a && traceIn.b) {

        var len = handleXYZDefaults(traceIn, traceOut, coerce, layout, 'a', 'b');

        if(!len) {
            traceOut.visible = false;
            return;
        }

        coerce('text');
        var isConstraint = (coerce('contours.type') === 'constraint');

        if(isConstraint) {
            handleConstraintDefaults(traceIn, traceOut, coerce, layout, defaultColor, {hasHover: false});
        } else {
            handleContoursDefaults(traceIn, traceOut, coerce, coerce2);
            handleStyleDefaults(traceIn, traceOut, coerce, layout, {hasHover: false});
        }
    } else {
        traceOut._defaultColor = defaultColor;
        traceOut._length = null;
    }
};

},{"../../lib":697,"../contour/constraint_defaults":921,"../contour/contours_defaults":923,"../contour/style_defaults":937,"../heatmap/xyz_defaults":959,"./attributes":938}],941:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var ContourCarpet = {};

ContourCarpet.attributes = _dereq_('./attributes');
ContourCarpet.supplyDefaults = _dereq_('./defaults');
ContourCarpet.colorbar = _dereq_('../contour/colorbar');
ContourCarpet.calc = _dereq_('./calc');
ContourCarpet.plot = _dereq_('./plot');
ContourCarpet.style = _dereq_('../contour/style');

ContourCarpet.moduleType = 'trace';
ContourCarpet.name = 'contourcarpet';
ContourCarpet.basePlotModule = _dereq_('../../plots/cartesian');
ContourCarpet.categories = ['cartesian', 'svg', 'carpet', 'contour', 'symbols', 'showLegend', 'hasLines', 'carpetDependent'];
ContourCarpet.meta = {
    
    
};

module.exports = ContourCarpet;

},{"../../plots/cartesian":756,"../contour/colorbar":919,"../contour/style":936,"./attributes":938,"./calc":939,"./defaults":940,"./plot":944}],942:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Drawing = _dereq_('../../components/drawing');
var axisAlignedLine = _dereq_('../carpet/axis_aligned_line');
var Lib = _dereq_('../../lib');

module.exports = function joinAllPaths(trace, pi, perimeter, ab2p, carpet, carpetcd, xa, ya) {
    var i;
    var fullpath = '';

    var startsleft = pi.edgepaths.map(function(v, i) { return i; });
    var newloop = true;
    var endpt, newendpt, cnt, nexti, possiblei, addpath;

    var atol = Math.abs(perimeter[0][0] - perimeter[2][0]) * 1e-4;
    var btol = Math.abs(perimeter[0][1] - perimeter[2][1]) * 1e-4;

    function istop(pt) { return Math.abs(pt[1] - perimeter[0][1]) < btol; }
    function isbottom(pt) { return Math.abs(pt[1] - perimeter[2][1]) < btol; }
    function isleft(pt) { return Math.abs(pt[0] - perimeter[0][0]) < atol; }
    function isright(pt) { return Math.abs(pt[0] - perimeter[2][0]) < atol; }

    function pathto(pt0, pt1) {
        var i, j, segments, axis;
        var path = '';

        if((istop(pt0) && !isright(pt0)) || (isbottom(pt0) && !isleft(pt0))) {
            axis = carpet.aaxis;
            segments = axisAlignedLine(carpet, carpetcd, [pt0[0], pt1[0]], 0.5 * (pt0[1] + pt1[1]));
        } else {
            axis = carpet.baxis;
            segments = axisAlignedLine(carpet, carpetcd, 0.5 * (pt0[0] + pt1[0]), [pt0[1], pt1[1]]);
        }

        for(i = 1; i < segments.length; i++) {
            path += axis.smoothing ? 'C' : 'L';
            for(j = 0; j < segments[i].length; j++) {
                var pt = segments[i][j];
                path += [xa.c2p(pt[0]), ya.c2p(pt[1])] + ' ';
            }
        }

        return path;
    }

    i = 0;
    endpt = null;
    while(startsleft.length) {
        var startpt = pi.edgepaths[i][0];

        if(endpt) {
            fullpath += pathto(endpt, startpt);
        }

        addpath = Drawing.smoothopen(pi.edgepaths[i].map(ab2p), pi.smoothing);
        fullpath += newloop ? addpath : addpath.replace(/^M/, 'L');
        startsleft.splice(startsleft.indexOf(i), 1);
        endpt = pi.edgepaths[i][pi.edgepaths[i].length - 1];
        nexti = -1;

        // now loop through sides, moving our endpoint until we find a new start
        for(cnt = 0; cnt < 4; cnt++) { // just to prevent infinite loops
            if(!endpt) {
                Lib.log('Missing end?', i, pi);
                break;
            }

            if(istop(endpt) && !isright(endpt)) {
                newendpt = perimeter[1]; // left top ---> right top
            } else if(isleft(endpt)) {
                newendpt = perimeter[0]; // left bottom ---> left top
            } else if(isbottom(endpt)) {
                newendpt = perimeter[3]; // right bottom
            } else if(isright(endpt)) {
                newendpt = perimeter[2]; // left bottom
            }

            for(possiblei = 0; possiblei < pi.edgepaths.length; possiblei++) {
                var ptNew = pi.edgepaths[possiblei][0];
                // is ptNew on the (horz. or vert.) segment from endpt to newendpt?
                if(Math.abs(endpt[0] - newendpt[0]) < atol) {
                    if(Math.abs(endpt[0] - ptNew[0]) < atol && (ptNew[1] - endpt[1]) * (newendpt[1] - ptNew[1]) >= 0) {
                        newendpt = ptNew;
                        nexti = possiblei;
                    }
                } else if(Math.abs(endpt[1] - newendpt[1]) < btol) {
                    if(Math.abs(endpt[1] - ptNew[1]) < btol && (ptNew[0] - endpt[0]) * (newendpt[0] - ptNew[0]) >= 0) {
                        newendpt = ptNew;
                        nexti = possiblei;
                    }
                } else {
                    Lib.log('endpt to newendpt is not vert. or horz.', endpt, newendpt, ptNew);
                }
            }

            if(nexti >= 0) break;
            fullpath += pathto(endpt, newendpt);
            endpt = newendpt;
        }

        if(nexti === pi.edgepaths.length) {
            Lib.log('unclosed perimeter path');
            break;
        }

        i = nexti;

        // if we closed back on a loop we already included,
        // close it and start a new loop
        newloop = (startsleft.indexOf(i) === -1);
        if(newloop) {
            i = startsleft[0];
            fullpath += pathto(endpt, newendpt) + 'Z';
            endpt = null;
        }
    }

    // finally add the interior paths
    for(i = 0; i < pi.paths.length; i++) {
        fullpath += Drawing.smoothclosed(pi.paths[i].map(ab2p), pi.smoothing);
    }

    return fullpath;
};

},{"../../components/drawing":595,"../../lib":697,"../carpet/axis_aligned_line":878}],943:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function mapPathinfo(pathinfo, map) {
    var i, j, k, pi, pedgepaths, ppaths, pedgepath, ppath, path;

    for(i = 0; i < pathinfo.length; i++) {
        pi = pathinfo[i];
        pedgepaths = pi.pedgepaths = [];
        ppaths = pi.ppaths = [];
        for(j = 0; j < pi.edgepaths.length; j++) {
            path = pi.edgepaths[j];
            pedgepath = [];
            for(k = 0; k < path.length; k++) {
                pedgepath[k] = map(path[k]);
            }
            pedgepaths.push(pedgepath);
        }
        for(j = 0; j < pi.paths.length; j++) {
            path = pi.paths[j];
            ppath = [];
            for(k = 0; k < path.length; k++) {
                ppath[k] = map(path[k]);
            }
            ppaths.push(ppath);
        }
    }
};

},{}],944:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var map1dArray = _dereq_('../carpet/map_1d_array');
var makepath = _dereq_('../carpet/makepath');
var Drawing = _dereq_('../../components/drawing');
var Lib = _dereq_('../../lib');

var makeCrossings = _dereq_('../contour/make_crossings');
var findAllPaths = _dereq_('../contour/find_all_paths');
var contourPlot = _dereq_('../contour/plot');
var constants = _dereq_('../contour/constants');
var convertToConstraints = _dereq_('../contour/convert_to_constraints');
var joinAllPaths = _dereq_('./join_all_paths');
var emptyPathinfo = _dereq_('../contour/empty_pathinfo');
var mapPathinfo = _dereq_('./map_pathinfo');
var lookupCarpet = _dereq_('../carpet/lookup_carpetid');
var closeBoundaries = _dereq_('../contour/close_boundaries');

module.exports = function plot(gd, plotinfo, cdcontours, contourcarpetLayer) {
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    Lib.makeTraceGroups(contourcarpetLayer, cdcontours, 'contour').each(function(cd) {
        var plotGroup = d3.select(this);
        var cd0 = cd[0];
        var trace = cd0.trace;

        var carpet = trace._carpetTrace = lookupCarpet(gd, trace);
        var carpetcd = gd.calcdata[carpet.index][0];

        if(!carpet.visible || carpet.visible === 'legendonly') return;

        var a = cd0.a;
        var b = cd0.b;
        var contours = trace.contours;
        var pathinfo = emptyPathinfo(contours, plotinfo, cd0);
        var isConstraint = contours.type === 'constraint';
        var operation = contours._operation;
        var coloring = isConstraint ? (operation === '=' ? 'lines' : 'fill') : contours.coloring;

        // Map [a, b] (data) --> [i, j] (pixels)
        function ab2p(ab) {
            var pt = carpet.ab2xy(ab[0], ab[1], true);
            return [xa.c2p(pt[0]), ya.c2p(pt[1])];
        }

        // Define the perimeter in a/b coordinates:
        var perimeter = [
            [a[0], b[b.length - 1]],
            [a[a.length - 1], b[b.length - 1]],
            [a[a.length - 1], b[0]],
            [a[0], b[0]]
        ];

        // Extract the contour levels:
        makeCrossings(pathinfo);
        var atol = (a[a.length - 1] - a[0]) * 1e-8;
        var btol = (b[b.length - 1] - b[0]) * 1e-8;
        findAllPaths(pathinfo, atol, btol);

        // Constraints might need to be draw inverted, which is not something contours
        // handle by default since they're assumed fully opaque so that they can be
        // drawn overlapping. This function flips the paths as necessary so that they're
        // drawn correctly.
        //
        // TODO: Perhaps this should be generalized and *all* paths should be drawn as
        // closed regions so that translucent contour levels would be valid.
        // See: https://github.com/plotly/plotly.js/issues/1356
        var fillPathinfo = pathinfo;
        if(contours.type === 'constraint') {
            fillPathinfo = convertToConstraints(pathinfo, operation);
            closeBoundaries(fillPathinfo, operation, perimeter, trace);
        }

        // Map the paths in a/b coordinates to pixel coordinates:
        mapPathinfo(pathinfo, ab2p);

        // draw everything

        // Compute the boundary path
        var seg, xp, yp, i;
        var segs = [];
        for(i = carpetcd.clipsegments.length - 1; i >= 0; i--) {
            seg = carpetcd.clipsegments[i];
            xp = map1dArray([], seg.x, xa.c2p);
            yp = map1dArray([], seg.y, ya.c2p);
            xp.reverse();
            yp.reverse();
            segs.push(makepath(xp, yp, seg.bicubic));
        }

        var boundaryPath = 'M' + segs.join('L') + 'Z';

        // Draw the baseline background fill that fills in the space behind any other
        // contour levels:
        makeBackground(plotGroup, carpetcd.clipsegments, xa, ya, isConstraint, coloring);

        // Draw the specific contour fills. As a simplification, they're assumed to be
        // fully opaque so that it's easy to draw them simply overlapping. The alternative
        // would be to flip adjacent paths and draw closed paths for each level instead.
        makeFills(trace, plotGroup, xa, ya, fillPathinfo, perimeter, ab2p, carpet, carpetcd, coloring, boundaryPath);

        // Draw contour lines:
        makeLinesAndLabels(plotGroup, pathinfo, gd, cd0, contours, plotinfo, carpet);

        // Clip the boundary of the plot
        Drawing.setClipUrl(plotGroup, carpet._clipPathId, gd);
    });
};

function makeLinesAndLabels(plotgroup, pathinfo, gd, cd0, contours, plotinfo, carpet) {
    var lineContainer = Lib.ensureSingle(plotgroup, 'g', 'contourlines');
    var showLines = contours.showlines !== false;
    var showLabels = contours.showlabels;
    var clipLinesForLabels = showLines && showLabels;

    // Even if we're not going to show lines, we need to create them
    // if we're showing labels, because the fill paths include the perimeter
    // so can't be used to position the labels correctly.
    // In this case we'll remove the lines after making the labels.
    var linegroup = contourPlot.createLines(lineContainer, showLines || showLabels, pathinfo);

    var lineClip = contourPlot.createLineClip(lineContainer, clipLinesForLabels, gd, cd0.trace.uid);

    var labelGroup = plotgroup.selectAll('g.contourlabels')
        .data(showLabels ? [0] : []);

    labelGroup.exit().remove();

    labelGroup.enter().append('g')
        .classed('contourlabels', true);

    if(showLabels) {
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        var xLen = xa._length;
        var yLen = ya._length;
        // for simplicity use the xy box for label clipping outline.
        var labelClipPathData = [[
            [0, 0],
            [xLen, 0],
            [xLen, yLen],
            [0, yLen]
        ]];


        var labelData = [];

        // invalidate the getTextLocation cache in case paths changed
        Lib.clearLocationCache();

        var contourFormat = contourPlot.labelFormatter(contours, cd0.t.cb, gd._fullLayout);

        var dummyText = Drawing.tester.append('text')
            .attr('data-notex', 1)
            .call(Drawing.font, contours.labelfont);

        // use `bounds` only to keep labels away from the x/y boundaries
        // `constrainToCarpet` below ensures labels don't go off the
        // carpet edges
        var bounds = {
            left: 0,
            right: xLen,
            center: xLen / 2,
            top: 0,
            bottom: yLen,
            middle: yLen / 2
        };

        var plotDiagonal = Math.sqrt(xLen * xLen + yLen * yLen);

        // the path length to use to scale the number of labels to draw:
        var normLength = constants.LABELDISTANCE * plotDiagonal /
            Math.max(1, pathinfo.length / constants.LABELINCREASE);

        linegroup.each(function(d) {
            var textOpts = contourPlot.calcTextOpts(d.level, contourFormat, dummyText, gd);

            d3.select(this).selectAll('path').each(function(pathData) {
                var path = this;
                var pathBounds = Lib.getVisibleSegment(path, bounds, textOpts.height / 2);
                if(!pathBounds) return;

                constrainToCarpet(path, pathData, d, pathBounds, carpet, textOpts.height);

                if(pathBounds.len < (textOpts.width + textOpts.height) * constants.LABELMIN) return;

                var maxLabels = Math.min(Math.ceil(pathBounds.len / normLength),
                    constants.LABELMAX);

                for(var i = 0; i < maxLabels; i++) {
                    var loc = contourPlot.findBestTextLocation(path, pathBounds, textOpts,
                        labelData, bounds);

                    if(!loc) break;

                    contourPlot.addLabelData(loc, textOpts, labelData, labelClipPathData);
                }
            });
        });

        dummyText.remove();

        contourPlot.drawLabels(labelGroup, labelData, gd, lineClip,
            clipLinesForLabels ? labelClipPathData : null);
    }

    if(showLabels && !showLines) linegroup.remove();
}

// figure out if this path goes off the edge of the carpet
// and shorten the part we call visible to keep labels away from the edge
function constrainToCarpet(path, pathData, levelData, pathBounds, carpet, textHeight) {
    var pathABData;
    for(var i = 0; i < levelData.pedgepaths.length; i++) {
        if(pathData === levelData.pedgepaths[i]) {
            pathABData = levelData.edgepaths[i];
        }
    }
    if(!pathABData) return;

    var aMin = carpet.a[0];
    var aMax = carpet.a[carpet.a.length - 1];
    var bMin = carpet.b[0];
    var bMax = carpet.b[carpet.b.length - 1];

    function getOffset(abPt, pathVector) {
        var offset = 0;
        var edgeVector;
        var dAB = 0.1;
        if(Math.abs(abPt[0] - aMin) < dAB || Math.abs(abPt[0] - aMax) < dAB) {
            edgeVector = normalizeVector(carpet.dxydb_rough(abPt[0], abPt[1], dAB));
            offset = Math.max(offset, textHeight * vectorTan(pathVector, edgeVector) / 2);
        }

        if(Math.abs(abPt[1] - bMin) < dAB || Math.abs(abPt[1] - bMax) < dAB) {
            edgeVector = normalizeVector(carpet.dxyda_rough(abPt[0], abPt[1], dAB));
            offset = Math.max(offset, textHeight * vectorTan(pathVector, edgeVector) / 2);
        }
        return offset;
    }

    var startVector = getUnitVector(path, 0, 1);
    var endVector = getUnitVector(path, pathBounds.total, pathBounds.total - 1);
    var minStart = getOffset(pathABData[0], startVector);
    var maxEnd = pathBounds.total - getOffset(pathABData[pathABData.length - 1], endVector);

    if(pathBounds.min < minStart) pathBounds.min = minStart;
    if(pathBounds.max > maxEnd) pathBounds.max = maxEnd;

    pathBounds.len = pathBounds.max - pathBounds.min;
}

function getUnitVector(path, p0, p1) {
    var pt0 = path.getPointAtLength(p0);
    var pt1 = path.getPointAtLength(p1);
    var dx = pt1.x - pt0.x;
    var dy = pt1.y - pt0.y;
    var len = Math.sqrt(dx * dx + dy * dy);
    return [dx / len, dy / len];
}

function normalizeVector(v) {
    var len = Math.sqrt(v[0] * v[0] + v[1] * v[1]);
    return [v[0] / len, v[1] / len];
}

function vectorTan(v0, v1) {
    var cos = Math.abs(v0[0] * v1[0] + v0[1] * v1[1]);
    var sin = Math.sqrt(1 - cos * cos);
    return sin / cos;
}

function makeBackground(plotgroup, clipsegments, xaxis, yaxis, isConstraint, coloring) {
    var seg, xp, yp, i;
    var bggroup = Lib.ensureSingle(plotgroup, 'g', 'contourbg');

    var bgfill = bggroup.selectAll('path')
        .data((coloring === 'fill' && !isConstraint) ? [0] : []);
    bgfill.enter().append('path');
    bgfill.exit().remove();

    var segs = [];
    for(i = 0; i < clipsegments.length; i++) {
        seg = clipsegments[i];
        xp = map1dArray([], seg.x, xaxis.c2p);
        yp = map1dArray([], seg.y, yaxis.c2p);
        segs.push(makepath(xp, yp, seg.bicubic));
    }

    bgfill
        .attr('d', 'M' + segs.join('L') + 'Z')
        .style('stroke', 'none');
}

function makeFills(trace, plotgroup, xa, ya, pathinfo, perimeter, ab2p, carpet, carpetcd, coloring, boundaryPath) {
    var fillgroup = Lib.ensureSingle(plotgroup, 'g', 'contourfill');

    var fillitems = fillgroup.selectAll('path')
        .data(coloring === 'fill' ? pathinfo : []);
    fillitems.enter().append('path');
    fillitems.exit().remove();
    fillitems.each(function(pi) {
        // join all paths for this level together into a single path
        // first follow clockwise around the perimeter to close any open paths
        // if the whole perimeter is above this level, start with a path
        // enclosing the whole thing. With all that, the parity should mean
        // that we always fill everything above the contour, nothing below
        var fullpath = joinAllPaths(trace, pi, perimeter, ab2p, carpet, carpetcd, xa, ya);

        if(pi.prefixBoundary) {
            fullpath = boundaryPath + fullpath;
        }

        if(!fullpath) {
            d3.select(this).remove();
        } else {
            d3.select(this)
                .attr('d', fullpath)
                .style('stroke', 'none');
        }
    });
}

},{"../../components/drawing":595,"../../lib":697,"../carpet/lookup_carpetid":894,"../carpet/makepath":895,"../carpet/map_1d_array":896,"../contour/close_boundaries":918,"../contour/constants":920,"../contour/convert_to_constraints":924,"../contour/empty_pathinfo":926,"../contour/find_all_paths":928,"../contour/make_crossings":933,"../contour/plot":934,"./join_all_paths":942,"./map_pathinfo":943,"d3":151}],945:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterAttrs = _dereq_('../scatter/attributes');
var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;

module.exports = extendFlat({
    z: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    x: extendFlat({}, scatterAttrs.x, {impliedEdits: {xtype: 'array'}}),
    x0: extendFlat({}, scatterAttrs.x0, {impliedEdits: {xtype: 'scaled'}}),
    dx: extendFlat({}, scatterAttrs.dx, {impliedEdits: {xtype: 'scaled'}}),
    y: extendFlat({}, scatterAttrs.y, {impliedEdits: {ytype: 'array'}}),
    y0: extendFlat({}, scatterAttrs.y0, {impliedEdits: {ytype: 'scaled'}}),
    dy: extendFlat({}, scatterAttrs.dy, {impliedEdits: {ytype: 'scaled'}}),

    text: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    hovertext: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    transpose: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'calc',
        
    },
    xtype: {
        valType: 'enumerated',
        values: ['array', 'scaled'],
        
        editType: 'calc+clearAxisTypes',
        
    },
    ytype: {
        valType: 'enumerated',
        values: ['array', 'scaled'],
        
        editType: 'calc+clearAxisTypes',
        
    },
    zsmooth: {
        valType: 'enumerated',
        values: ['fast', 'best', false],
        dflt: false,
        
        editType: 'calc',
        
    },
    connectgaps: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'calc',
        
    },
    xgap: {
        valType: 'number',
        dflt: 0,
        min: 0,
        
        editType: 'plot',
        
    },
    ygap: {
        valType: 'number',
        dflt: 0,
        min: 0,
        
        editType: 'plot',
        
    },
    zhoverformat: {
        valType: 'string',
        dflt: '',
        
        editType: 'none',
        
    },
    hovertemplate: hovertemplateAttrs()
}, {
    transforms: undefined
},
    colorscaleAttrs('', {
        cLetter: 'z',
        autoColorDflt: false
    }),
    { colorbar: colorbarAttrs }
);

},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../scatter/attributes":1048}],946:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');

var histogram2dCalc = _dereq_('../histogram2d/calc');
var colorscaleCalc = _dereq_('../../components/colorscale/calc');
var convertColumnData = _dereq_('./convert_column_xyz');
var clean2dArray = _dereq_('./clean_2d_array');
var interp2d = _dereq_('./interp2d');
var findEmpties = _dereq_('./find_empties');
var makeBoundArray = _dereq_('./make_bound_array');


module.exports = function calc(gd, trace) {
    // prepare the raw data
    // run makeCalcdata on x and y even for heatmaps, in case of category mappings
    var xa = Axes.getFromId(gd, trace.xaxis || 'x');
    var ya = Axes.getFromId(gd, trace.yaxis || 'y');
    var isContour = Registry.traceIs(trace, 'contour');
    var isHist = Registry.traceIs(trace, 'histogram');
    var isGL2D = Registry.traceIs(trace, 'gl2d');
    var zsmooth = isContour ? 'best' : trace.zsmooth;
    var x;
    var x0;
    var dx;
    var y;
    var y0;
    var dy;
    var z;
    var i;
    var binned;

    // cancel minimum tick spacings (only applies to bars and boxes)
    xa._minDtick = 0;
    ya._minDtick = 0;

    if(isHist) {
        binned = histogram2dCalc(gd, trace);
        x = binned.x;
        x0 = binned.x0;
        dx = binned.dx;
        y = binned.y;
        y0 = binned.y0;
        dy = binned.dy;
        z = binned.z;
    }
    else {
        var zIn = trace.z;
        if(Lib.isArray1D(zIn)) {
            convertColumnData(trace, xa, ya, 'x', 'y', ['z']);
            x = trace._x;
            y = trace._y;
            zIn = trace._z;
        } else {
            x = trace.x ? xa.makeCalcdata(trace, 'x') : [];
            y = trace.y ? ya.makeCalcdata(trace, 'y') : [];
        }

        x0 = trace.x0 || 0;
        dx = trace.dx || 1;
        y0 = trace.y0 || 0;
        dy = trace.dy || 1;

        z = clean2dArray(zIn, trace.transpose);

        if(isContour || trace.connectgaps) {
            trace._emptypoints = findEmpties(z);
            interp2d(z, trace._emptypoints);
        }
    }

    function noZsmooth(msg) {
        zsmooth = trace._input.zsmooth = trace.zsmooth = false;
        Lib.warn('cannot use zsmooth: "fast": ' + msg);
    }

    // check whether we really can smooth (ie all boxes are about the same size)
    if(zsmooth === 'fast') {
        if(xa.type === 'log' || ya.type === 'log') {
            noZsmooth('log axis found');
        }
        else if(!isHist) {
            if(x.length) {
                var avgdx = (x[x.length - 1] - x[0]) / (x.length - 1);
                var maxErrX = Math.abs(avgdx / 100);
                for(i = 0; i < x.length - 1; i++) {
                    if(Math.abs(x[i + 1] - x[i] - avgdx) > maxErrX) {
                        noZsmooth('x scale is not linear');
                        break;
                    }
                }
            }
            if(y.length && zsmooth === 'fast') {
                var avgdy = (y[y.length - 1] - y[0]) / (y.length - 1);
                var maxErrY = Math.abs(avgdy / 100);
                for(i = 0; i < y.length - 1; i++) {
                    if(Math.abs(y[i + 1] - y[i] - avgdy) > maxErrY) {
                        noZsmooth('y scale is not linear');
                        break;
                    }
                }
            }
        }
    }

    // create arrays of brick boundaries, to be used by autorange and heatmap.plot
    var xlen = Lib.maxRowLength(z);
    var xIn = trace.xtype === 'scaled' ? '' : x;
    var xArray = makeBoundArray(trace, xIn, x0, dx, xlen, xa);
    var yIn = trace.ytype === 'scaled' ? '' : y;
    var yArray = makeBoundArray(trace, yIn, y0, dy, z.length, ya);

    // handled in gl2d convert step
    if(!isGL2D) {
        trace._extremes[xa._id] = Axes.findExtremes(xa, xArray);
        trace._extremes[ya._id] = Axes.findExtremes(ya, yArray);
    }

    var cd0 = {
        x: xArray,
        y: yArray,
        z: z,
        text: trace._text || trace.text,
        hovertext: trace._hovertext || trace.hovertext
    };

    if(xIn && xIn.length === xArray.length - 1) cd0.xCenter = xIn;
    if(yIn && yIn.length === yArray.length - 1) cd0.yCenter = yIn;

    if(isHist) {
        cd0.xRanges = binned.xRanges;
        cd0.yRanges = binned.yRanges;
        cd0.pts = binned.pts;
    }

    // auto-z and autocolorscale if applicable
    if(!isContour || trace.contours.type !== 'constraint') {
        colorscaleCalc(gd, trace, {
            vals: z,
            containerStr: '',
            cLetter: 'z'
        });
    }

    if(isContour && trace.contours && trace.contours.coloring === 'heatmap') {
        var dummyTrace = {
            type: trace.type === 'contour' ? 'heatmap' : 'histogram2d',
            xcalendar: trace.xcalendar,
            ycalendar: trace.ycalendar
        };
        cd0.xfill = makeBoundArray(dummyTrace, xIn, x0, dx, xlen, xa);
        cd0.yfill = makeBoundArray(dummyTrace, yIn, y0, dy, z.length, ya);
    }

    return [cd0];
};

},{"../../components/colorscale/calc":582,"../../lib":697,"../../plots/cartesian/axes":745,"../../registry":826,"../histogram2d/calc":977,"./clean_2d_array":947,"./convert_column_xyz":949,"./find_empties":951,"./interp2d":954,"./make_bound_array":955}],947:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');

module.exports = function clean2dArray(zOld, transpose) {
    var rowlen, collen, getCollen, old2new, i, j;

    function cleanZvalue(v) {
        if(!isNumeric(v)) return undefined;
        return +v;
    }

    if(transpose) {
        rowlen = 0;
        for(i = 0; i < zOld.length; i++) rowlen = Math.max(rowlen, zOld[i].length);
        if(rowlen === 0) return false;
        getCollen = function(zOld) { return zOld.length; };
        old2new = function(zOld, i, j) { return zOld[j][i]; };
    }
    else {
        rowlen = zOld.length;
        getCollen = function(zOld, i) { return zOld[i].length; };
        old2new = function(zOld, i, j) { return zOld[i][j]; };
    }

    var zNew = new Array(rowlen);

    for(i = 0; i < rowlen; i++) {
        collen = getCollen(zOld, i);
        zNew[i] = new Array(collen);
        for(j = 0; j < collen; j++) zNew[i][j] = cleanZvalue(old2new(zOld, i, j));
    }

    return zNew;
};

},{"fast-isnumeric":218}],948:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    min: 'zmin',
    max: 'zmax'
};

},{}],949:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

module.exports = function convertColumnData(trace, ax1, ax2, var1Name, var2Name, arrayVarNames) {
    var colLen = trace._length;
    var col1 = ax1.makeCalcdata(trace, var1Name);
    var col2 = ax2.makeCalcdata(trace, var2Name);
    var textCol = trace.text;
    var hasColumnText = (textCol !== undefined && Lib.isArray1D(textCol));
    var hoverTextCol = trace.hovertext;
    var hasColumnHoverText = (hoverTextCol !== undefined && Lib.isArray1D(hoverTextCol));
    var i, j;

    var col1dv = Lib.distinctVals(col1);
    var col1vals = col1dv.vals;
    var col2dv = Lib.distinctVals(col2);
    var col2vals = col2dv.vals;
    var newArrays = [];
    var text;
    var hovertext;

    for(i = 0; i < arrayVarNames.length; i++) {
        newArrays[i] = Lib.init2dArray(col2vals.length, col1vals.length);
    }

    if(hasColumnText) {
        text = Lib.init2dArray(col2vals.length, col1vals.length);
    }
    if(hasColumnHoverText) {
        hovertext = Lib.init2dArray(col2vals.length, col1vals.length);
    }

    for(i = 0; i < colLen; i++) {
        if(col1[i] !== BADNUM && col2[i] !== BADNUM) {
            var i1 = Lib.findBin(col1[i] + col1dv.minDiff / 2, col1vals);
            var i2 = Lib.findBin(col2[i] + col2dv.minDiff / 2, col2vals);

            for(j = 0; j < arrayVarNames.length; j++) {
                var arrayVarName = arrayVarNames[j];
                var arrayVar = trace[arrayVarName];
                var newArray = newArrays[j];
                newArray[i2][i1] = arrayVar[i];
            }

            if(hasColumnText) text[i2][i1] = textCol[i];
            if(hasColumnHoverText) hovertext[i2][i1] = hoverTextCol[i];
        }
    }

    trace['_' + var1Name] = col1vals;
    trace['_' + var2Name] = col2vals;
    for(j = 0; j < arrayVarNames.length; j++) {
        trace['_' + arrayVarNames[j]] = newArrays[j];
    }
    if(hasColumnText) trace._text = text;
    if(hasColumnHoverText) trace._hovertext = hovertext;
};

},{"../../constants/numerical":674,"../../lib":697}],950:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

var handleXYZDefaults = _dereq_('./xyz_defaults');
var handleStyleDefaults = _dereq_('./style_defaults');
var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
var attributes = _dereq_('./attributes');


module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var validData = handleXYZDefaults(traceIn, traceOut, coerce, layout);
    if(!validData) {
        traceOut.visible = false;
        return;
    }

    coerce('text');
    coerce('hovertext');
    coerce('hovertemplate');

    handleStyleDefaults(traceIn, traceOut, coerce, layout);

    coerce('connectgaps', Lib.isArray1D(traceOut.z) && (traceOut.zsmooth !== false));

    colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'});
};

},{"../../components/colorscale/defaults":584,"../../lib":697,"./attributes":945,"./style_defaults":958,"./xyz_defaults":959}],951:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var maxRowLength = _dereq_('../../lib').maxRowLength;

/* Return a list of empty points in 2D array z
 * each empty point z[i][j] gives an array [i, j, neighborCount]
 * neighborCount is the count of 4 nearest neighbors that DO exist
 * this is to give us an order of points to evaluate for interpolation.
 * if no neighbors exist, we iteratively look for neighbors that HAVE
 * neighbors, and add a fractional neighborCount
 */
module.exports = function findEmpties(z) {
    var empties = [];
    var neighborHash = {};
    var noNeighborList = [];
    var nextRow = z[0];
    var row = [];
    var blank = [0, 0, 0];
    var rowLength = maxRowLength(z);
    var prevRow;
    var i;
    var j;
    var thisPt;
    var p;
    var neighborCount;
    var newNeighborHash;
    var foundNewNeighbors;

    for(i = 0; i < z.length; i++) {
        prevRow = row;
        row = nextRow;
        nextRow = z[i + 1] || [];
        for(j = 0; j < rowLength; j++) {
            if(row[j] === undefined) {
                neighborCount = (row[j - 1] !== undefined ? 1 : 0) +
                    (row[j + 1] !== undefined ? 1 : 0) +
                    (prevRow[j] !== undefined ? 1 : 0) +
                    (nextRow[j] !== undefined ? 1 : 0);

                if(neighborCount) {
                    // for this purpose, don't count off-the-edge points
                    // as undefined neighbors
                    if(i === 0) neighborCount++;
                    if(j === 0) neighborCount++;
                    if(i === z.length - 1) neighborCount++;
                    if(j === row.length - 1) neighborCount++;

                    // if all neighbors that could exist do, we don't
                    // need this for finding farther neighbors
                    if(neighborCount < 4) {
                        neighborHash[[i, j]] = [i, j, neighborCount];
                    }

                    empties.push([i, j, neighborCount]);
                }
                else noNeighborList.push([i, j]);
            }
        }
    }

    while(noNeighborList.length) {
        newNeighborHash = {};
        foundNewNeighbors = false;

        // look for cells that now have neighbors but didn't before
        for(p = noNeighborList.length - 1; p >= 0; p--) {
            thisPt = noNeighborList[p];
            i = thisPt[0];
            j = thisPt[1];

            neighborCount = ((neighborHash[[i - 1, j]] || blank)[2] +
                (neighborHash[[i + 1, j]] || blank)[2] +
                (neighborHash[[i, j - 1]] || blank)[2] +
                (neighborHash[[i, j + 1]] || blank)[2]) / 20;

            if(neighborCount) {
                newNeighborHash[thisPt] = [i, j, neighborCount];
                noNeighborList.splice(p, 1);
                foundNewNeighbors = true;
            }
        }

        if(!foundNewNeighbors) {
            throw 'findEmpties iterated with no new neighbors';
        }

        // put these new cells into the main neighbor list
        for(thisPt in newNeighborHash) {
            neighborHash[thisPt] = newNeighborHash[thisPt];
            empties.push(newNeighborHash[thisPt]);
        }
    }

    // sort the full list in descending order of neighbor count
    return empties.sort(function(a, b) { return b[2] - a[2]; });
};

},{"../../lib":697}],952:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Fx = _dereq_('../../components/fx');
var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');

module.exports = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer, contour) {
    var cd0 = pointData.cd[0];
    var trace = cd0.trace;
    var xa = pointData.xa;
    var ya = pointData.ya;
    var x = cd0.x;
    var y = cd0.y;
    var z = cd0.z;
    var xc = cd0.xCenter;
    var yc = cd0.yCenter;
    var zmask = cd0.zmask;
    var range = [trace.zmin, trace.zmax];
    var zhoverformat = trace.zhoverformat;
    var x2 = x;
    var y2 = y;

    var xl, yl, nx, ny;

    if(pointData.index !== false) {
        try {
            nx = Math.round(pointData.index[1]);
            ny = Math.round(pointData.index[0]);
        }
        catch(e) {
            Lib.error('Error hovering on heatmap, ' +
                'pointNumber must be [row,col], found:', pointData.index);
            return;
        }
        if(nx < 0 || nx >= z[0].length || ny < 0 || ny > z.length) {
            return;
        }
    }
    else if(Fx.inbox(xval - x[0], xval - x[x.length - 1], 0) > 0 ||
            Fx.inbox(yval - y[0], yval - y[y.length - 1], 0) > 0) {
        return;
    }
    else {
        if(contour) {
            var i2;
            x2 = [2 * x[0] - x[1]];

            for(i2 = 1; i2 < x.length; i2++) {
                x2.push((x[i2] + x[i2 - 1]) / 2);
            }
            x2.push([2 * x[x.length - 1] - x[x.length - 2]]);

            y2 = [2 * y[0] - y[1]];
            for(i2 = 1; i2 < y.length; i2++) {
                y2.push((y[i2] + y[i2 - 1]) / 2);
            }
            y2.push([2 * y[y.length - 1] - y[y.length - 2]]);
        }
        nx = Math.max(0, Math.min(x2.length - 2, Lib.findBin(xval, x2)));
        ny = Math.max(0, Math.min(y2.length - 2, Lib.findBin(yval, y2)));
    }

    var x0 = xa.c2p(x[nx]);
    var x1 = xa.c2p(x[nx + 1]);
    var y0 = ya.c2p(y[ny]);
    var y1 = ya.c2p(y[ny + 1]);

    if(contour) {
        x1 = x0;
        xl = x[nx];
        y1 = y0;
        yl = y[ny];
    }
    else {
        xl = xc ? xc[nx] : ((x[nx] + x[nx + 1]) / 2);
        yl = yc ? yc[ny] : ((y[ny] + y[ny + 1]) / 2);
        if(trace.zsmooth) {
            x0 = x1 = xa.c2p(xl);
            y0 = y1 = ya.c2p(yl);
        }
    }

    var zVal = z[ny][nx];
    if(zmask && !zmask[ny][nx]) zVal = undefined;

    var text;
    if(Array.isArray(cd0.hovertext) && Array.isArray(cd0.hovertext[ny])) {
        text = cd0.hovertext[ny][nx];
    } else if(Array.isArray(cd0.text) && Array.isArray(cd0.text[ny])) {
        text = cd0.text[ny][nx];
    }

    var zLabel;
    // dummy axis for formatting the z value
    var dummyAx = {
        type: 'linear',
        range: range,
        hoverformat: zhoverformat,
        _separators: xa._separators,
        _numFormat: xa._numFormat
    };
    var zLabelObj = Axes.tickText(dummyAx, zVal, 'hover');
    zLabel = zLabelObj.text;

    return [Lib.extendFlat(pointData, {
        index: [ny, nx],
        // never let a 2D override 1D type as closest point
        distance: pointData.maxHoverDistance,
        spikeDistance: pointData.maxSpikeDistance,
        x0: x0,
        x1: x1,
        y0: y0,
        y1: y1,
        xLabelVal: xl,
        yLabelVal: yl,
        zLabelVal: zVal,
        zLabel: zLabel,
        text: text
    })];
};

},{"../../components/fx":613,"../../lib":697,"../../plots/cartesian/axes":745}],953:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Heatmap = {};

Heatmap.attributes = _dereq_('./attributes');
Heatmap.supplyDefaults = _dereq_('./defaults');
Heatmap.calc = _dereq_('./calc');
Heatmap.plot = _dereq_('./plot');
Heatmap.colorbar = _dereq_('./colorbar');
Heatmap.style = _dereq_('./style');
Heatmap.hoverPoints = _dereq_('./hover');

Heatmap.moduleType = 'trace';
Heatmap.name = 'heatmap';
Heatmap.basePlotModule = _dereq_('../../plots/cartesian');
Heatmap.categories = ['cartesian', 'svg', '2dMap'];
Heatmap.meta = {
    
};

module.exports = Heatmap;

},{"../../plots/cartesian":756,"./attributes":945,"./calc":946,"./colorbar":948,"./defaults":950,"./hover":952,"./plot":956,"./style":957}],954:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

var INTERPTHRESHOLD = 1e-2;
var NEIGHBORSHIFTS = [[-1, 0], [1, 0], [0, -1], [0, 1]];

function correctionOvershoot(maxFractionalChange) {
    // start with less overshoot, until we know it's converging,
    // then ramp up the overshoot for faster convergence
    return 0.5 - 0.25 * Math.min(1, maxFractionalChange * 0.5);
}

/*
 * interp2d: Fill in missing data from a 2D array using an iterative
 *   poisson equation solver with zero-derivative BC at edges.
 *   Amazingly, this just amounts to repeatedly averaging all the existing
 *   nearest neighbors, at least if we don't take x/y scaling into account,
 *   which is the right approach here where x and y may not even have the
 *   same units.
 *
 * @param {array of arrays} z
 *      The 2D array to fill in. Will be mutated here. Assumed to already be
 *      cleaned, so all entries are numbers except gaps, which are `undefined`.
 * @param {array of arrays} emptyPoints
 *      Each entry [i, j, neighborCount] for empty points z[i][j] and the number
 *      of neighbors that are *not* missing. Assumed to be sorted from most to
 *      least neighbors, as produced by heatmap/find_empties.
 */
module.exports = function interp2d(z, emptyPoints) {
    var maxFractionalChange = 1;
    var i;

    // one pass to fill in a starting value for all the empties
    iterateInterp2d(z, emptyPoints);

    // we're don't need to iterate lone empties - remove them
    for(i = 0; i < emptyPoints.length; i++) {
        if(emptyPoints[i][2] < 4) break;
    }
    // but don't remove these points from the original array,
    // we'll use them for masking, so make a copy.
    emptyPoints = emptyPoints.slice(i);

    for(i = 0; i < 100 && maxFractionalChange > INTERPTHRESHOLD; i++) {
        maxFractionalChange = iterateInterp2d(z, emptyPoints,
            correctionOvershoot(maxFractionalChange));
    }
    if(maxFractionalChange > INTERPTHRESHOLD) {
        Lib.log('interp2d didn\'t converge quickly', maxFractionalChange);
    }

    return z;
};

function iterateInterp2d(z, emptyPoints, overshoot) {
    var maxFractionalChange = 0;
    var thisPt;
    var i;
    var j;
    var p;
    var q;
    var neighborShift;
    var neighborRow;
    var neighborVal;
    var neighborCount;
    var neighborSum;
    var initialVal;
    var minNeighbor;
    var maxNeighbor;

    for(p = 0; p < emptyPoints.length; p++) {
        thisPt = emptyPoints[p];
        i = thisPt[0];
        j = thisPt[1];
        initialVal = z[i][j];
        neighborSum = 0;
        neighborCount = 0;

        for(q = 0; q < 4; q++) {
            neighborShift = NEIGHBORSHIFTS[q];
            neighborRow = z[i + neighborShift[0]];
            if(!neighborRow) continue;
            neighborVal = neighborRow[j + neighborShift[1]];
            if(neighborVal !== undefined) {
                if(neighborSum === 0) {
                    minNeighbor = maxNeighbor = neighborVal;
                }
                else {
                    minNeighbor = Math.min(minNeighbor, neighborVal);
                    maxNeighbor = Math.max(maxNeighbor, neighborVal);
                }
                neighborCount++;
                neighborSum += neighborVal;
            }
        }

        if(neighborCount === 0) {
            throw 'iterateInterp2d order is wrong: no defined neighbors';
        }

        // this is the laplace equation interpolation:
        // each point is just the average of its neighbors
        // note that this ignores differential x/y scaling
        // which I think is the right approach, since we
        // don't know what that scaling means
        z[i][j] = neighborSum / neighborCount;

        if(initialVal === undefined) {
            if(neighborCount < 4) maxFractionalChange = 1;
        }
        else {
            // we can make large empty regions converge faster
            // if we overshoot the change vs the previous value
            z[i][j] = (1 + overshoot) * z[i][j] - overshoot * initialVal;

            if(maxNeighbor > minNeighbor) {
                maxFractionalChange = Math.max(maxFractionalChange,
                    Math.abs(z[i][j] - initialVal) / (maxNeighbor - minNeighbor));
            }
        }
    }

    return maxFractionalChange;
}

},{"../../lib":697}],955:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');
var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;

module.exports = function makeBoundArray(trace, arrayIn, v0In, dvIn, numbricks, ax) {
    var arrayOut = [];
    var isContour = Registry.traceIs(trace, 'contour');
    var isHist = Registry.traceIs(trace, 'histogram');
    var isGL2D = Registry.traceIs(trace, 'gl2d');
    var v0;
    var dv;
    var i;

    var isArrayOfTwoItemsOrMore = isArrayOrTypedArray(arrayIn) && arrayIn.length > 1;

    if(isArrayOfTwoItemsOrMore && !isHist && (ax.type !== 'category')) {
        var len = arrayIn.length;

        // given vals are brick centers
        // hopefully length === numbricks, but use this method even if too few are supplied
        // and extend it linearly based on the last two points
        if(len <= numbricks) {
            // contour plots only want the centers
            if(isContour || isGL2D) arrayOut = arrayIn.slice(0, numbricks);
            else if(numbricks === 1) {
                arrayOut = [arrayIn[0] - 0.5, arrayIn[0] + 0.5];
            }
            else {
                arrayOut = [1.5 * arrayIn[0] - 0.5 * arrayIn[1]];

                for(i = 1; i < len; i++) {
                    arrayOut.push((arrayIn[i - 1] + arrayIn[i]) * 0.5);
                }

                arrayOut.push(1.5 * arrayIn[len - 1] - 0.5 * arrayIn[len - 2]);
            }

            if(len < numbricks) {
                var lastPt = arrayOut[arrayOut.length - 1];
                var delta = lastPt - arrayOut[arrayOut.length - 2];

                for(i = len; i < numbricks; i++) {
                    lastPt += delta;
                    arrayOut.push(lastPt);
                }
            }
        }
        else {
            // hopefully length === numbricks+1, but do something regardless:
            // given vals are brick boundaries
            return isContour ?
                arrayIn.slice(0, numbricks) :  // we must be strict for contours
                arrayIn.slice(0, numbricks + 1);
        }
    }
    else {
        dv = dvIn || 1;

        var calendar = trace[ax._id.charAt(0) + 'calendar'];

        if(isHist || ax.type === 'category' || ax.type === 'multicategory') {
            v0 = ax.r2c(v0In, 0, calendar) || 0;
        } else if(isArrayOrTypedArray(arrayIn) && arrayIn.length === 1) {
            v0 = arrayIn[0];
        } else if(v0In === undefined) {
            v0 = 0;
        } else {
            v0 = ax.d2c(v0In, 0, calendar);
        }

        for(i = (isContour || isGL2D) ? 0 : -0.5; i < numbricks; i++) {
            arrayOut.push(v0 + dv * i);
        }
    }

    return arrayOut;
};

},{"../../lib":697,"../../registry":826}],956:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var tinycolor = _dereq_('tinycolor2');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Colorscale = _dereq_('../../components/colorscale');
var xmlnsNamespaces = _dereq_('../../constants/xmlns_namespaces');

module.exports = function(gd, plotinfo, cdheatmaps, heatmapLayer) {
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    Lib.makeTraceGroups(heatmapLayer, cdheatmaps, 'hm').each(function(cd) {
        var plotGroup = d3.select(this);
        var cd0 = cd[0];
        var trace = cd0.trace;

        var z = cd0.z;
        var x = cd0.x;
        var y = cd0.y;
        var xc = cd0.xCenter;
        var yc = cd0.yCenter;
        var isContour = Registry.traceIs(trace, 'contour');
        var zsmooth = isContour ? 'best' : trace.zsmooth;

        // get z dims
        var m = z.length;
        var n = Lib.maxRowLength(z);
        var xrev = false;
        var yrev = false;

        var left, right, temp, top, bottom, i;

        // TODO: if there are multiple overlapping categorical heatmaps,
        // or if we allow category sorting, then the categories may not be
        // sequential... may need to reorder and/or expand z

        // Get edges of png in pixels (xa.c2p() maps axes coordinates to pixel coordinates)
        // figure out if either axis is reversed (y is usually reversed, in pixel coords)
        // also clip the image to maximum 50% outside the visible plot area
        // bigger image lets you pan more naturally, but slows performance.
        // TODO: use low-resolution images outside the visible plot for panning
        // these while loops find the first and last brick bounds that are defined
        // (in case of log of a negative)
        i = 0;
        while(left === undefined && i < x.length - 1) {
            left = xa.c2p(x[i]);
            i++;
        }
        i = x.length - 1;
        while(right === undefined && i > 0) {
            right = xa.c2p(x[i]);
            i--;
        }

        if(right < left) {
            temp = right;
            right = left;
            left = temp;
            xrev = true;
        }

        i = 0;
        while(top === undefined && i < y.length - 1) {
            top = ya.c2p(y[i]);
            i++;
        }
        i = y.length - 1;
        while(bottom === undefined && i > 0) {
            bottom = ya.c2p(y[i]);
            i--;
        }

        if(bottom < top) {
            temp = top;
            top = bottom;
            bottom = temp;
            yrev = true;
        }

        // for contours with heatmap fill, we generate the boundaries based on
        // brick centers but then use the brick edges for drawing the bricks
        if(isContour) {
            xc = x;
            yc = y;
            x = cd0.xfill;
            y = cd0.yfill;
        }

        // make an image that goes at most half a screen off either side, to keep
        // time reasonable when you zoom in. if zsmooth is true/fast, don't worry
        // about this, because zooming doesn't increase number of pixels
        // if zsmooth is best, don't include anything off screen because it takes too long
        if(zsmooth !== 'fast') {
            var extra = zsmooth === 'best' ? 0 : 0.5;
            left = Math.max(-extra * xa._length, left);
            right = Math.min((1 + extra) * xa._length, right);
            top = Math.max(-extra * ya._length, top);
            bottom = Math.min((1 + extra) * ya._length, bottom);
        }

        var imageWidth = Math.round(right - left);
        var imageHeight = Math.round(bottom - top);

        // setup image nodes

        // if image is entirely off-screen, don't even draw it
        var isOffScreen = (imageWidth <= 0 || imageHeight <= 0);

        if(isOffScreen) {
            var noImage = plotGroup.selectAll('image').data([]);
            noImage.exit().remove();
            return;
        }

        // generate image data

        var canvasW, canvasH;
        if(zsmooth === 'fast') {
            canvasW = n;
            canvasH = m;
        } else {
            canvasW = imageWidth;
            canvasH = imageHeight;
        }

        var canvas = document.createElement('canvas');
        canvas.width = canvasW;
        canvas.height = canvasH;
        var context = canvas.getContext('2d');

        var sclFunc = Colorscale.makeColorScaleFunc(
            Colorscale.extractScale(trace, {cLetter: 'z'}),
            { noNumericCheck: true, returnArray: true }
        );

        // map brick boundaries to image pixels
        var xpx,
            ypx;
        if(zsmooth === 'fast') {
            xpx = xrev ?
                function(index) { return n - 1 - index; } :
                Lib.identity;
            ypx = yrev ?
                function(index) { return m - 1 - index; } :
                Lib.identity;
        }
        else {
            xpx = function(index) {
                return Lib.constrain(Math.round(xa.c2p(x[index]) - left),
                    0, imageWidth);
            };
            ypx = function(index) {
                return Lib.constrain(Math.round(ya.c2p(y[index]) - top),
                    0, imageHeight);
            };
        }

        // build the pixel map brick-by-brick
        // cruise through z-matrix row-by-row
        // build a brick at each z-matrix value
        var yi = ypx(0);
        var yb = [yi, yi];
        var xbi = xrev ? 0 : 1;
        var ybi = yrev ? 0 : 1;
        // for collecting an average luminosity of the heatmap
        var pixcount = 0;
        var rcount = 0;
        var gcount = 0;
        var bcount = 0;

        var xb, j, xi, v, row, c;

        function setColor(v, pixsize) {
            if(v !== undefined) {
                var c = sclFunc(v);
                c[0] = Math.round(c[0]);
                c[1] = Math.round(c[1]);
                c[2] = Math.round(c[2]);

                pixcount += pixsize;
                rcount += c[0] * pixsize;
                gcount += c[1] * pixsize;
                bcount += c[2] * pixsize;
                return c;
            }
            return [0, 0, 0, 0];
        }

        function interpColor(r0, r1, xinterp, yinterp) {
            var z00 = r0[xinterp.bin0];
            if(z00 === undefined) return setColor(undefined, 1);

            var z01 = r0[xinterp.bin1];
            var z10 = r1[xinterp.bin0];
            var z11 = r1[xinterp.bin1];
            var dx = (z01 - z00) || 0;
            var dy = (z10 - z00) || 0;
            var dxy;

            // the bilinear interpolation term needs different calculations
            // for all the different permutations of missing data
            // among the neighbors of the main point, to ensure
            // continuity across brick boundaries.
            if(z01 === undefined) {
                if(z11 === undefined) dxy = 0;
                else if(z10 === undefined) dxy = 2 * (z11 - z00);
                else dxy = (2 * z11 - z10 - z00) * 2 / 3;
            }
            else if(z11 === undefined) {
                if(z10 === undefined) dxy = 0;
                else dxy = (2 * z00 - z01 - z10) * 2 / 3;
            }
            else if(z10 === undefined) dxy = (2 * z11 - z01 - z00) * 2 / 3;
            else dxy = (z11 + z00 - z01 - z10);

            return setColor(z00 + xinterp.frac * dx + yinterp.frac * (dy + xinterp.frac * dxy));
        }

        if(zsmooth) { // best or fast, works fastest with imageData
            var pxIndex = 0;
            var pixels;

            try {
                pixels = new Uint8Array(imageWidth * imageHeight * 4);
            } catch(e) {
                pixels = new Array(imageWidth * imageHeight * 4);
            }

            if(zsmooth === 'best') {
                var xForPx = xc || x;
                var yForPx = yc || y;
                var xPixArray = new Array(xForPx.length);
                var yPixArray = new Array(yForPx.length);
                var xinterpArray = new Array(imageWidth);
                var findInterpX = xc ? findInterpFromCenters : findInterp;
                var findInterpY = yc ? findInterpFromCenters : findInterp;
                var yinterp, r0, r1;

                // first make arrays of x and y pixel locations of brick boundaries
                for(i = 0; i < xForPx.length; i++) xPixArray[i] = Math.round(xa.c2p(xForPx[i]) - left);
                for(i = 0; i < yForPx.length; i++) yPixArray[i] = Math.round(ya.c2p(yForPx[i]) - top);

                // then make arrays of interpolations
                // (bin0=closest, bin1=next, frac=fractional dist.)
                for(i = 0; i < imageWidth; i++) xinterpArray[i] = findInterpX(i, xPixArray);

                // now do the interpolations and fill the png
                for(j = 0; j < imageHeight; j++) {
                    yinterp = findInterpY(j, yPixArray);
                    r0 = z[yinterp.bin0];
                    r1 = z[yinterp.bin1];
                    for(i = 0; i < imageWidth; i++, pxIndex += 4) {
                        c = interpColor(r0, r1, xinterpArray[i], yinterp);
                        putColor(pixels, pxIndex, c);
                    }
                }
            }
            else { // zsmooth = fast
                for(j = 0; j < m; j++) {
                    row = z[j];
                    yb = ypx(j);
                    for(i = 0; i < imageWidth; i++) {
                        c = setColor(row[i], 1);
                        pxIndex = (yb * imageWidth + xpx(i)) * 4;
                        putColor(pixels, pxIndex, c);
                    }
                }
            }

            var imageData = context.createImageData(imageWidth, imageHeight);
            try {
                imageData.data.set(pixels);
            } catch(e) {
                var pxArray = imageData.data;
                var dlen = pxArray.length;
                for(j = 0; j < dlen; j ++) {
                    pxArray[j] = pixels[j];
                }
            }

            context.putImageData(imageData, 0, 0);
        } else { // zsmooth = false -> filling potentially large bricks works fastest with fillRect

            // gaps do not need to be exact integers, but if they *are* we will get
            // cleaner edges by rounding at least one edge
            var xGap = trace.xgap;
            var yGap = trace.ygap;
            var xGapLeft = Math.floor(xGap / 2);
            var yGapTop = Math.floor(yGap / 2);

            for(j = 0; j < m; j++) {
                row = z[j];
                yb.reverse();
                yb[ybi] = ypx(j + 1);
                if(yb[0] === yb[1] || yb[0] === undefined || yb[1] === undefined) {
                    continue;
                }
                xi = xpx(0);
                xb = [xi, xi];
                for(i = 0; i < n; i++) {
                    // build one color brick!
                    xb.reverse();
                    xb[xbi] = xpx(i + 1);
                    if(xb[0] === xb[1] || xb[0] === undefined || xb[1] === undefined) {
                        continue;
                    }
                    v = row[i];
                    c = setColor(v, (xb[1] - xb[0]) * (yb[1] - yb[0]));
                    context.fillStyle = 'rgba(' + c.join(',') + ')';

                    context.fillRect(xb[0] + xGapLeft, yb[0] + yGapTop,
                        xb[1] - xb[0] - xGap, yb[1] - yb[0] - yGap);
                }
            }
        }

        rcount = Math.round(rcount / pixcount);
        gcount = Math.round(gcount / pixcount);
        bcount = Math.round(bcount / pixcount);
        var avgColor = tinycolor('rgb(' + rcount + ',' + gcount + ',' + bcount + ')');

        gd._hmpixcount = (gd._hmpixcount||0) + pixcount;
        gd._hmlumcount = (gd._hmlumcount||0) + pixcount * avgColor.getLuminance();

        var image3 = plotGroup.selectAll('image')
            .data(cd);

        image3.enter().append('svg:image').attr({
            xmlns: xmlnsNamespaces.svg,
            preserveAspectRatio: 'none'
        });

        image3.attr({
            height: imageHeight,
            width: imageWidth,
            x: left,
            y: top,
            'xlink:href': canvas.toDataURL('image/png')
        });
    });
};

// get interpolated bin value. Returns {bin0:closest bin, frac:fractional dist to next, bin1:next bin}
function findInterp(pixel, pixArray) {
    var maxBin = pixArray.length - 2;
    var bin = Lib.constrain(Lib.findBin(pixel, pixArray), 0, maxBin);
    var pix0 = pixArray[bin];
    var pix1 = pixArray[bin + 1];
    var interp = Lib.constrain(bin + (pixel - pix0) / (pix1 - pix0) - 0.5, 0, maxBin);
    var bin0 = Math.round(interp);
    var frac = Math.abs(interp - bin0);

    if(!interp || interp === maxBin || !frac) {
        return {
            bin0: bin0,
            bin1: bin0,
            frac: 0
        };
    }
    return {
        bin0: bin0,
        frac: frac,
        bin1: Math.round(bin0 + frac / (interp - bin0))
    };
}

function findInterpFromCenters(pixel, centerPixArray) {
    var maxBin = centerPixArray.length - 1;
    var bin = Lib.constrain(Lib.findBin(pixel, centerPixArray), 0, maxBin);
    var pix0 = centerPixArray[bin];
    var pix1 = centerPixArray[bin + 1];
    var frac = ((pixel - pix0) / (pix1 - pix0)) || 0;
    if(frac <= 0) {
        return {
            bin0: bin,
            bin1: bin,
            frac: 0
        };
    }
    if(frac < 0.5) {
        return {
            bin0: bin,
            bin1: bin + 1,
            frac: frac
        };
    }
    return {
        bin0: bin + 1,
        bin1: bin,
        frac: 1 - frac
    };
}

function putColor(pixels, pxIndex, c) {
    pixels[pxIndex] = c[0];
    pixels[pxIndex + 1] = c[1];
    pixels[pxIndex + 2] = c[2];
    pixels[pxIndex + 3] = Math.round(c[3] * 255);
}

},{"../../components/colorscale":586,"../../constants/xmlns_namespaces":675,"../../lib":697,"../../registry":826,"d3":151,"tinycolor2":518}],957:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

module.exports = function style(gd) {
    d3.select(gd).selectAll('.hm image')
        .style('opacity', function(d) {
            return d.trace.opacity;
        });
};

},{"d3":151}],958:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = function handleStyleDefaults(traceIn, traceOut, coerce) {
    var zsmooth = coerce('zsmooth');
    if(zsmooth === false) {
        // ensure that xgap and ygap are coerced only when zsmooth allows them to have an effect.
        coerce('xgap');
        coerce('ygap');
    }

    coerce('zhoverformat');
};

},{}],959:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var Lib = _dereq_('../../lib');

var Registry = _dereq_('../../registry');

module.exports = function handleXYZDefaults(traceIn, traceOut, coerce, layout, xName, yName) {
    var z = coerce('z');
    xName = xName || 'x';
    yName = yName || 'y';
    var x, y;

    if(z === undefined || !z.length) return 0;

    if(Lib.isArray1D(traceIn.z)) {
        x = coerce(xName);
        y = coerce(yName);

        var xlen = Lib.minRowLength(x);
        var ylen = Lib.minRowLength(y);

        // column z must be accompanied by xName and yName arrays
        if(xlen === 0 || ylen === 0) return 0;

        traceOut._length = Math.min(xlen, ylen, z.length);
    }
    else {
        x = coordDefaults(xName, coerce);
        y = coordDefaults(yName, coerce);

        // TODO put z validation elsewhere
        if(!isValidZ(z)) return 0;

        coerce('transpose');

        traceOut._length = null;
    }

    var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
    handleCalendarDefaults(traceIn, traceOut, [xName, yName], layout);

    return true;
};

function coordDefaults(coordStr, coerce) {
    var coord = coerce(coordStr);
    var coordType = coord ? coerce(coordStr + 'type', 'array') : 'scaled';

    if(coordType === 'scaled') {
        coerce(coordStr + '0');
        coerce('d' + coordStr);
    }

    return coord;
}

function isValidZ(z) {
    var allRowsAreArrays = true;
    var oneRowIsFilled = false;
    var hasOneNumber = false;
    var zi;

    /*
     * Without this step:
     *
     * hasOneNumber = false breaks contour but not heatmap
     * allRowsAreArrays = false breaks contour but not heatmap
     * oneRowIsFilled = false breaks both
     */

    for(var i = 0; i < z.length; i++) {
        zi = z[i];
        if(!Lib.isArrayOrTypedArray(zi)) {
            allRowsAreArrays = false;
            break;
        }
        if(zi.length > 0) oneRowIsFilled = true;
        for(var j = 0; j < zi.length; j++) {
            if(isNumeric(zi[j])) {
                hasOneNumber = true;
                break;
            }
        }
    }

    return (allRowsAreArrays && oneRowIsFilled && hasOneNumber);
}

},{"../../lib":697,"../../registry":826,"fast-isnumeric":218}],960:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


var heatmapAttrs = _dereq_('../heatmap/attributes');
var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;


var commonList = [
    'z',
    'x', 'x0', 'dx',
    'y', 'y0', 'dy',
    'text', 'transpose',
    'xtype', 'ytype'
];

var attrs = {};

for(var i = 0; i < commonList.length; i++) {
    var k = commonList[i];
    attrs[k] = heatmapAttrs[k];
}

extendFlat(
    attrs,
    colorscaleAttrs('', {cLetter: 'z', autoColorDflt: false}),
    {colorbar: colorbarAttrs}
);

module.exports = overrideAll(attrs, 'calc', 'nested');

},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../lib/extend":687,"../../plot_api/edit_types":728,"../heatmap/attributes":945}],961:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var createHeatmap2D = _dereq_('gl-heatmap2d');
var Axes = _dereq_('../../plots/cartesian/axes');
var str2RGBArray = _dereq_('../../lib/str2rgbarray');


function Heatmap(scene, uid) {
    this.scene = scene;
    this.uid = uid;
    this.type = 'heatmapgl';

    this.name = '';
    this.hoverinfo = 'all';

    this.xData = [];
    this.yData = [];
    this.zData = [];
    this.textLabels = [];

    this.idToIndex = [];
    this.bounds = [0, 0, 0, 0];

    this.options = {
        z: [],
        x: [],
        y: [],
        shape: [0, 0],
        colorLevels: [0],
        colorValues: [0, 0, 0, 1]
    };

    this.heatmap = createHeatmap2D(scene.glplot, this.options);
    this.heatmap._trace = this;
}

var proto = Heatmap.prototype;

proto.handlePick = function(pickResult) {
    var options = this.options;
    var shape = options.shape;
    var index = pickResult.pointId;
    var xIndex = index % shape[0];
    var yIndex = Math.floor(index / shape[0]);
    var zIndex = index;

    return {
        trace: this,
        dataCoord: pickResult.dataCoord,
        traceCoord: [
            options.x[xIndex],
            options.y[yIndex],
            options.z[zIndex]
        ],
        textLabel: this.textLabels[index],
        name: this.name,
        pointIndex: [yIndex, xIndex],
        hoverinfo: this.hoverinfo
    };
};

proto.update = function(fullTrace, calcTrace) {
    var calcPt = calcTrace[0];

    this.index = fullTrace.index;
    this.name = fullTrace.name;
    this.hoverinfo = fullTrace.hoverinfo;

    // convert z from 2D -> 1D
    var z = calcPt.z;
    this.options.z = [].concat.apply([], z);

    var rowLen = z[0].length;
    var colLen = z.length;
    this.options.shape = [rowLen, colLen];

    this.options.x = calcPt.x;
    this.options.y = calcPt.y;

    var colorOptions = convertColorscale(fullTrace);
    this.options.colorLevels = colorOptions.colorLevels;
    this.options.colorValues = colorOptions.colorValues;

    // convert text from 2D -> 1D
    this.textLabels = [].concat.apply([], fullTrace.text);

    this.heatmap.update(this.options);

    var xa = this.scene.xaxis;
    var ya = this.scene.yaxis;
    fullTrace._extremes[xa._id] = Axes.findExtremes(xa, calcPt.x);
    fullTrace._extremes[ya._id] = Axes.findExtremes(ya, calcPt.y);
};

proto.dispose = function() {
    this.heatmap.dispose();
};

function convertColorscale(fullTrace) {
    var scl = fullTrace.colorscale;
    var zmin = fullTrace.zmin;
    var zmax = fullTrace.zmax;

    var N = scl.length;
    var domain = new Array(N);
    var range = new Array(4 * N);

    for(var i = 0; i < N; i++) {
        var si = scl[i];
        var color = str2RGBArray(si[1]);

        domain[i] = zmin + si[0] * (zmax - zmin);

        for(var j = 0; j < 4; j++) {
            range[(4 * i) + j] = color[j];
        }
    }

    return {
        colorLevels: domain,
        colorValues: range
    };
}

function createHeatmap(scene, fullTrace, calcTrace) {
    var plot = new Heatmap(scene, fullTrace.uid);
    plot.update(fullTrace, calcTrace);
    return plot;
}

module.exports = createHeatmap;

},{"../../lib/str2rgbarray":720,"../../plots/cartesian/axes":745,"gl-heatmap2d":244}],962:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var HeatmapGl = {};

HeatmapGl.attributes = _dereq_('./attributes');
HeatmapGl.supplyDefaults = _dereq_('../heatmap/defaults');
HeatmapGl.colorbar = _dereq_('../heatmap/colorbar');

HeatmapGl.calc = _dereq_('../heatmap/calc');
HeatmapGl.plot = _dereq_('./convert');

HeatmapGl.moduleType = 'trace';
HeatmapGl.name = 'heatmapgl';
HeatmapGl.basePlotModule = _dereq_('../../plots/gl2d');
HeatmapGl.categories = ['gl', 'gl2d', '2dMap'];
HeatmapGl.meta = {
    
};

module.exports = HeatmapGl;

},{"../../plots/gl2d":784,"../heatmap/calc":946,"../heatmap/colorbar":948,"../heatmap/defaults":950,"./attributes":960,"./convert":961}],963:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var barAttrs = _dereq_('../bar/attributes');
var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var makeBinAttrs = _dereq_('./bin_attributes');
var constants = _dereq_('./constants');
var extendFlat = _dereq_('../../lib/extend').extendFlat;

module.exports = {
    x: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },
    y: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },

    text: extendFlat({}, barAttrs.text, {
        
    }),
    hovertext: extendFlat({}, barAttrs.hovertext, {
        
    }),
    orientation: barAttrs.orientation,

    histfunc: {
        valType: 'enumerated',
        values: ['count', 'sum', 'avg', 'min', 'max'],
        
        dflt: 'count',
        editType: 'calc',
        
    },
    histnorm: {
        valType: 'enumerated',
        values: ['', 'percent', 'probability', 'density', 'probability density'],
        dflt: '',
        
        editType: 'calc',
        
    },

    cumulative: {
        enabled: {
            valType: 'boolean',
            dflt: false,
            
            editType: 'calc',
            
        },

        direction: {
            valType: 'enumerated',
            values: ['increasing', 'decreasing'],
            dflt: 'increasing',
            
            editType: 'calc',
            
        },

        currentbin: {
            valType: 'enumerated',
            values: ['include', 'exclude', 'half'],
            dflt: 'include',
            
            editType: 'calc',
            
        },
        editType: 'calc'
    },
    nbinsx: {
        valType: 'integer',
        min: 0,
        dflt: 0,
        
        editType: 'calc',
        
    },
    xbins: makeBinAttrs('x', true),

    nbinsy: {
        valType: 'integer',
        min: 0,
        dflt: 0,
        
        editType: 'calc',
        
    },
    ybins: makeBinAttrs('y', true),
    autobinx: {
        valType: 'boolean',
        dflt: null,
        
        editType: 'calc',
        
    },
    autobiny: {
        valType: 'boolean',
        dflt: null,
        
        editType: 'calc',
        
    },

    hovertemplate: hovertemplateAttrs({}, {
        keys: constants.eventDataKeys
    }),

    marker: barAttrs.marker,

    offsetgroup: barAttrs.offsetgroup,
    alignmentgroup: barAttrs.alignmentgroup,

    selected: barAttrs.selected,
    unselected: barAttrs.unselected,

    _deprecated: {
        bardir: barAttrs._deprecated.bardir
    }
};

},{"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../bar/attributes":836,"./bin_attributes":965,"./constants":969}],964:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


module.exports = function doAvg(size, counts) {
    var nMax = size.length;
    var total = 0;
    for(var i = 0; i < nMax; i++) {
        if(counts[i]) {
            size[i] /= counts[i];
            total += size[i];
        }
        else size[i] = null;
    }
    return total;
};

},{}],965:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function makeBinAttrs(axLetter, match) {
    return {
        start: {
            valType: 'any', // for date axes
            
            editType: 'calc',
            
        },
        end: {
            valType: 'any', // for date axes
            
            editType: 'calc',
            
        },
        size: {
            valType: 'any', // for date axes
            
            editType: 'calc',
            
        },
        editType: 'calc'
    };
};

},{}],966:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');


module.exports = {
    count: function(n, i, size) {
        size[n]++;
        return 1;
    },

    sum: function(n, i, size, counterData) {
        var v = counterData[i];
        if(isNumeric(v)) {
            v = Number(v);
            size[n] += v;
            return v;
        }
        return 0;
    },

    avg: function(n, i, size, counterData, counts) {
        var v = counterData[i];
        if(isNumeric(v)) {
            v = Number(v);
            size[n] += v;
            counts[n]++;
        }
        return 0;
    },

    min: function(n, i, size, counterData) {
        var v = counterData[i];
        if(isNumeric(v)) {
            v = Number(v);
            if(!isNumeric(size[n])) {
                size[n] = v;
                return v;
            }
            else if(size[n] > v) {
                var delta = v - size[n];
                size[n] = v;
                return delta;
            }
        }
        return 0;
    },

    max: function(n, i, size, counterData) {
        var v = counterData[i];
        if(isNumeric(v)) {
            v = Number(v);
            if(!isNumeric(size[n])) {
                size[n] = v;
                return v;
            }
            else if(size[n] < v) {
                var delta = v - size[n];
                size[n] = v;
                return delta;
            }
        }
        return 0;
    }
};

},{"fast-isnumeric":218}],967:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var numConstants = _dereq_('../../constants/numerical');
var oneYear = numConstants.ONEAVGYEAR;
var oneMonth = numConstants.ONEAVGMONTH;
var oneDay = numConstants.ONEDAY;
var oneHour = numConstants.ONEHOUR;
var oneMin = numConstants.ONEMIN;
var oneSec = numConstants.ONESEC;
var tickIncrement = _dereq_('../../plots/cartesian/axes').tickIncrement;


/*
 * make a function that will find rounded bin edges
 * @param {number} leftGap: how far from the left edge of any bin is the closest data value?
 * @param {number} rightGap: how far from the right edge of any bin is the closest data value?
 * @param {Array[number]} binEdges: the actual edge values used in binning
 * @param {object} pa: the position axis
 * @param {string} calendar: the data calendar
 *
 * @return {function(v, isRightEdge)}:
 *   find the start (isRightEdge is falsy) or end (truthy) label value for a bin edge `v`
 */
module.exports = function getBinSpanLabelRound(leftGap, rightGap, binEdges, pa, calendar) {
    // the rounding digit is the largest digit that changes in *all* of 4 regions:
    // - inside the rightGap before binEdges[0] (shifted 10% to the left)
    // - inside the leftGap after binEdges[0] (expanded by 10% of rightGap on each end)
    // - same for binEdges[1]
    var dv0 = -1.1 * rightGap;
    var dv1 = -0.1 * rightGap;
    var dv2 = leftGap - dv1;
    var edge0 = binEdges[0];
    var edge1 = binEdges[1];
    var leftDigit = Math.min(
        biggestDigitChanged(edge0 + dv1, edge0 + dv2, pa, calendar),
        biggestDigitChanged(edge1 + dv1, edge1 + dv2, pa, calendar)
    );
    var rightDigit = Math.min(
        biggestDigitChanged(edge0 + dv0, edge0 + dv1, pa, calendar),
        biggestDigitChanged(edge1 + dv0, edge1 + dv1, pa, calendar)
    );

    // normally we try to make the label for the right edge different from
    // the left edge label, so it's unambiguous which bin gets data on the edge.
    // but if this results in more than 3 extra digits (or for dates, more than
    // 2 fields ie hr&min or min&sec, which is 3600x), it'll be more clutter than
    // useful so keep the label cleaner instead
    var digit, disambiguateEdges;
    if(leftDigit > rightDigit && rightDigit < Math.abs(edge1 - edge0) / 4000) {
        digit = leftDigit;
        disambiguateEdges = false;
    }
    else {
        digit = Math.min(leftDigit, rightDigit);
        disambiguateEdges = true;
    }

    if(pa.type === 'date' && digit > oneDay) {
        var dashExclude = (digit === oneYear) ? 1 : 6;
        var increment = (digit === oneYear) ? 'M12' : 'M1';

        return function(v, isRightEdge) {
            var dateStr = pa.c2d(v, oneYear, calendar);
            var dashPos = dateStr.indexOf('-', dashExclude);
            if(dashPos > 0) dateStr = dateStr.substr(0, dashPos);
            var roundedV = pa.d2c(dateStr, 0, calendar);

            if(roundedV < v) {
                var nextV = tickIncrement(roundedV, increment, false, calendar);
                if((roundedV + nextV) / 2 < v + leftGap) roundedV = nextV;
            }

            if(isRightEdge && disambiguateEdges) {
                return tickIncrement(roundedV, increment, true, calendar);
            }

            return roundedV;
        };
    }

    return function(v, isRightEdge) {
        var roundedV = digit * Math.round(v / digit);
        // if we rounded down and we could round up and still be < leftGap
        // (or what leftGap values round to), do that
        if(roundedV + (digit / 10) < v && roundedV + (digit * 0.9) < v + leftGap) {
            roundedV += digit;
        }
        // finally for the right edge back off one digit - but only if we can do that
        // and not clip off any data that's potentially in the bin
        if(isRightEdge && disambiguateEdges) {
            roundedV -= digit;
        }
        return roundedV;
    };
};

/*
 * Find the largest digit that changes within a (calcdata) region [v1, v2]
 * if dates, "digit" means date/time part when it's bigger than a second
 * returns the unit value to round to this digit, eg 0.01 to round to hundredths, or
 * 100 to round to hundreds. returns oneMonth or oneYear for month or year rounding,
 * so that Math.min will work, rather than 'M1' and 'M12'
 */
function biggestDigitChanged(v1, v2, pa, calendar) {
    // are we crossing zero? can't say anything.
    // in principle this doesn't apply to dates but turns out this doesn't matter.
    if(v1 * v2 <= 0) return Infinity;

    var dv = Math.abs(v2 - v1);
    var isDate = pa.type === 'date';
    var digit = biggestGuaranteedDigitChanged(dv, isDate);
    // see if a larger digit also changed
    for(var i = 0; i < 10; i++) {
        // numbers: next digit needs to be >10x but <100x then gets rounded down.
        // dates: next digit can be as much as 60x (then rounded down)
        var nextDigit = biggestGuaranteedDigitChanged(digit * 80, isDate);
        // if we get to years, the chain stops
        if(digit === nextDigit) break;
        if(didDigitChange(nextDigit, v1, v2, isDate, pa, calendar)) digit = nextDigit;
        else break;
    }
    return digit;
}

/*
 * Find the largest digit that *definitely* changes in a region [v, v + dv] for any v
 * for nonuniform date regions (months/years) pick the largest
 */
function biggestGuaranteedDigitChanged(dv, isDate) {
    if(isDate && dv > oneSec) {
        // this is supposed to be the biggest *guaranteed* change
        // so compare to the longest month and year across any calendar,
        // and we'll iterate back up later
        // note: does not support rounding larger than one year. We could add
        // that if anyone wants it, but seems unusual and not strictly necessary.
        if(dv > oneDay) {
            if(dv > oneYear * 1.1) return oneYear;
            if(dv > oneMonth * 1.1) return oneMonth;
            return oneDay;
        }

        if(dv > oneHour) return oneHour;
        if(dv > oneMin) return oneMin;
        return oneSec;
    }
    return Math.pow(10, Math.floor(Math.log(dv) / Math.LN10));
}

function didDigitChange(digit, v1, v2, isDate, pa, calendar) {
    if(isDate && digit > oneDay) {
        var dateParts1 = dateParts(v1, pa, calendar);
        var dateParts2 = dateParts(v2, pa, calendar);
        var parti = (digit === oneYear) ? 0 : 1;
        return dateParts1[parti] !== dateParts2[parti];

    }
    return Math.floor(v2 / digit) - Math.floor(v1 / digit) > 0.1;
}

function dateParts(v, pa, calendar) {
    var parts = pa.c2d(v, oneYear, calendar).split('-');
    if(parts[0] === '') {
        parts.unshift();
        parts[0] = '-' + parts[0];
    }
    return parts;
}

},{"../../constants/numerical":674,"../../plots/cartesian/axes":745}],968:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');

var arraysToCalcdata = _dereq_('../bar/arrays_to_calcdata');
var binFunctions = _dereq_('./bin_functions');
var normFunctions = _dereq_('./norm_functions');
var doAvg = _dereq_('./average');
var getBinSpanLabelRound = _dereq_('./bin_label_vals');

module.exports = function calc(gd, trace) {
    // ignore as much processing as possible (and including in autorange) if not visible
    if(trace.visible !== true) return;

    // depending on orientation, set position and size axes and data ranges
    // note: this logic for choosing orientation is duplicated in graph_obj->setstyles
    var pos = [];
    var size = [];
    var pa = Axes.getFromId(gd, trace.orientation === 'h' ?
        (trace.yaxis || 'y') : (trace.xaxis || 'x'));
    var mainData = trace.orientation === 'h' ? 'y' : 'x';
    var counterData = {x: 'y', y: 'x'}[mainData];
    var calendar = trace[mainData + 'calendar'];
    var cumulativeSpec = trace.cumulative;
    var i;

    var binsAndPos = calcAllAutoBins(gd, trace, pa, mainData);
    var binSpec = binsAndPos[0];
    var pos0 = binsAndPos[1];

    var nonuniformBins = typeof binSpec.size === 'string';
    var binEdges = [];
    var bins = nonuniformBins ? binEdges : binSpec;
    // make the empty bin array
    var inc = [];
    var counts = [];
    var inputPoints = [];
    var total = 0;
    var norm = trace.histnorm;
    var func = trace.histfunc;
    var densityNorm = norm.indexOf('density') !== -1;
    var i2, binEnd, n;

    if(cumulativeSpec.enabled && densityNorm) {
        // we treat "cumulative" like it means "integral" if you use a density norm,
        // which in the end means it's the same as without "density"
        norm = norm.replace(/ ?density$/, '');
        densityNorm = false;
    }

    var extremeFunc = func === 'max' || func === 'min';
    var sizeInit = extremeFunc ? null : 0;
    var binFunc = binFunctions.count;
    var normFunc = normFunctions[norm];
    var isAvg = false;
    var pr2c = function(v) { return pa.r2c(v, 0, calendar); };
    var rawCounterData;

    if(Lib.isArrayOrTypedArray(trace[counterData]) && func !== 'count') {
        rawCounterData = trace[counterData];
        isAvg = func === 'avg';
        binFunc = binFunctions[func];
    }

    // create the bins (and any extra arrays needed)
    // assume more than 1e6 bins is an error, so we don't crash the browser
    i = pr2c(binSpec.start);

    // decrease end a little in case of rounding errors
    binEnd = pr2c(binSpec.end) + (i - Axes.tickIncrement(i, binSpec.size, false, calendar)) / 1e6;

    while(i < binEnd && pos.length < 1e6) {
        i2 = Axes.tickIncrement(i, binSpec.size, false, calendar);
        pos.push((i + i2) / 2);
        size.push(sizeInit);
        inputPoints.push([]);
        // nonuniform bins (like months) we need to search,
        // rather than straight calculate the bin we're in
        binEdges.push(i);
        // nonuniform bins also need nonuniform normalization factors
        if(densityNorm) inc.push(1 / (i2 - i));
        if(isAvg) counts.push(0);
        // break to avoid infinite loops
        if(i2 <= i) break;
        i = i2;
    }
    binEdges.push(i);

    // for date axes we need bin bounds to be calcdata. For nonuniform bins
    // we already have this, but uniform with start/end/size they're still strings.
    if(!nonuniformBins && pa.type === 'date') {
        bins = {
            start: pr2c(bins.start),
            end: pr2c(bins.end),
            size: bins.size
        };
    }

    // bin the data
    // and make histogram-specific pt-number-to-cd-index map object
    var nMax = size.length;
    var uniqueValsPerBin = true;
    var leftGap = Infinity;
    var rightGap = Infinity;
    var ptNumber2cdIndex = {};
    for(i = 0; i < pos0.length; i++) {
        var posi = pos0[i];
        n = Lib.findBin(posi, bins);
        if(n >= 0 && n < nMax) {
            total += binFunc(n, i, size, rawCounterData, counts);
            if(uniqueValsPerBin && inputPoints[n].length && posi !== pos0[inputPoints[n][0]]) {
                uniqueValsPerBin = false;
            }
            inputPoints[n].push(i);
            ptNumber2cdIndex[i] = n;

            leftGap = Math.min(leftGap, posi - binEdges[n]);
            rightGap = Math.min(rightGap, binEdges[n + 1] - posi);
        }
    }

    var roundFn;
    if(!uniqueValsPerBin) {
        roundFn = getBinSpanLabelRound(leftGap, rightGap, binEdges, pa, calendar);
    }

    // average and/or normalize the data, if needed
    if(isAvg) total = doAvg(size, counts);
    if(normFunc) normFunc(size, total, inc);

    // after all normalization etc, now we can accumulate if desired
    if(cumulativeSpec.enabled) cdf(size, cumulativeSpec.direction, cumulativeSpec.currentbin);


    var seriesLen = Math.min(pos.length, size.length);
    var cd = [];
    var firstNonzero = 0;
    var lastNonzero = seriesLen - 1;

    // look for empty bins at the ends to remove, so autoscale omits them
    for(i = 0; i < seriesLen; i++) {
        if(size[i]) {
            firstNonzero = i;
            break;
        }
    }
    for(i = seriesLen - 1; i >= firstNonzero; i--) {
        if(size[i]) {
            lastNonzero = i;
            break;
        }
    }

    // create the "calculated data" to plot
    for(i = firstNonzero; i <= lastNonzero; i++) {
        if((isNumeric(pos[i]) && isNumeric(size[i]))) {
            var cdi = {
                p: pos[i],
                s: size[i],
                b: 0
            };

            // setup hover and event data fields,
            // N.B. pts and "hover" positions ph0/ph1 don't seem to make much sense
            // for cumulative distributions
            if(!cumulativeSpec.enabled) {
                cdi.pts = inputPoints[i];
                if(uniqueValsPerBin) {
                    cdi.ph0 = cdi.ph1 = (inputPoints[i].length) ? pos0[inputPoints[i][0]] : pos[i];
                }
                else {
                    cdi.ph0 = roundFn(binEdges[i]);
                    cdi.ph1 = roundFn(binEdges[i + 1], true);
                }
            }
            cd.push(cdi);
        }
    }

    if(cd.length === 1) {
        // when we collapse to a single bin, calcdata no longer describes bin size
        // so we need to explicitly specify it
        cd[0].width1 = Axes.tickIncrement(cd[0].p, binSpec.size, false, calendar) - cd[0].p;
    }

    arraysToCalcdata(cd, trace);

    if(Lib.isArrayOrTypedArray(trace.selectedpoints)) {
        Lib.tagSelected(cd, trace, ptNumber2cdIndex);
    }

    return cd;
};

/*
 * calcAllAutoBins: we want all histograms on the same axes to share bin specs
 * if they're grouped or stacked. If the user has explicitly specified differing
 * bin specs, there's nothing we can do, but if possible we will try to use the
 * smallest bins of any of the auto values for all histograms grouped/stacked
 * together.
 */
function calcAllAutoBins(gd, trace, pa, mainData, _overlayEdgeCase) {
    var binAttr = mainData + 'bins';
    var fullLayout = gd._fullLayout;
    var isOverlay = fullLayout.barmode === 'overlay';
    var i, traces, tracei, calendar, pos0, autoVals, cumulativeSpec;

    var cleanBound = (pa.type === 'date') ?
        function(v) { return (v || v === 0) ? Lib.cleanDate(v, null, pa.calendar) : null; } :
        function(v) { return isNumeric(v) ? Number(v) : null; };

    function setBound(attr, bins, newBins) {
        if(bins[attr + 'Found']) {
            bins[attr] = cleanBound(bins[attr]);
            if(bins[attr] === null) bins[attr] = newBins[attr];
        }
        else {
            autoVals[attr] = bins[attr] = newBins[attr];
            Lib.nestedProperty(traces[0], binAttr + '.' + attr).set(newBins[attr]);
        }
    }

    var binOpts = fullLayout._histogramBinOpts[trace._groupName];

    // all but the first trace in this group has already been marked finished
    // clear this flag, so next time we run calc we will run autobin again
    if(trace._autoBinFinished) {
        delete trace._autoBinFinished;
    }
    else {
        traces = binOpts.traces;
        var sizeFound = binOpts.sizeFound;
        var allPos = [];
        autoVals = traces[0]._autoBin = {};
        // Note: we're including `legendonly` traces here for autobin purposes,
        // so that showing & hiding from the legend won't affect bins.
        // But this complicates things a bit since those traces don't `calc`,
        // hence `isFirstVisible`.
        var isFirstVisible = true;
        for(i = 0; i < traces.length; i++) {
            tracei = traces[i];
            if(tracei.visible) {
                pos0 = tracei._pos0 = pa.makeCalcdata(tracei, mainData);
                allPos = Lib.concat(allPos, pos0);
                delete tracei._autoBinFinished;
                if(trace.visible === true) {
                    if(isFirstVisible) {
                        isFirstVisible = false;
                    }
                    else {
                        delete tracei._autoBin;
                        tracei._autoBinFinished = 1;
                    }
                }
            }
        }
        calendar = traces[0][mainData + 'calendar'];
        var newBinSpec = Axes.autoBin(
            allPos, pa, binOpts.nbins, false, calendar, sizeFound && binOpts.size);

        // Edge case: single-valued histogram overlaying others
        // Use them all together to calculate the bin size for the single-valued one
        if(isOverlay && newBinSpec._dataSpan === 0 &&
            pa.type !== 'category' && pa.type !== 'multicategory') {
            // Several single-valued histograms! Stop infinite recursion,
            // just return an extra flag that tells handleSingleValueOverlays
            // to sort out this trace too
            if(_overlayEdgeCase) return [newBinSpec, pos0, true];

            newBinSpec = handleSingleValueOverlays(gd, trace, pa, mainData, binAttr);
        }

        // adjust for CDF edge cases
        cumulativeSpec = tracei.cumulative;
        if(cumulativeSpec.enabled && (cumulativeSpec.currentbin !== 'include')) {
            if(cumulativeSpec.direction === 'decreasing') {
                newBinSpec.start = pa.c2r(Axes.tickIncrement(
                    pa.r2c(newBinSpec.start, 0, calendar),
                    newBinSpec.size, true, calendar
                ));
            }
            else {
                newBinSpec.end = pa.c2r(Axes.tickIncrement(
                    pa.r2c(newBinSpec.end, 0, calendar),
                    newBinSpec.size, false, calendar
                ));
            }
        }

        binOpts.size = newBinSpec.size;
        if(!sizeFound) {
            autoVals.size = newBinSpec.size;
            Lib.nestedProperty(traces[0], binAttr + '.size').set(newBinSpec.size);
        }

        setBound('start', binOpts, newBinSpec);
        setBound('end', binOpts, newBinSpec);
    }

    pos0 = trace._pos0;
    delete trace._pos0;

    // Each trace can specify its own start/end, or if omitted
    // we ensure they're beyond the bounds of this trace's data,
    // and we need to make sure start is aligned with the main start
    var traceInputBins = trace._input[binAttr] || {};
    var traceBinOptsCalc = Lib.extendFlat({}, binOpts);
    var mainStart = binOpts.start;
    var startIn = pa.r2l(traceInputBins.start);
    var hasStart = startIn !== undefined;
    if((binOpts.startFound || hasStart) && startIn !== pa.r2l(mainStart)) {
        // We have an explicit start to reconcile across traces
        // if this trace has an explicit start, shift it down to a bin edge
        // if another trace had an explicit start, shift it down to a
        // bin edge past our data
        var traceStart = hasStart ?
            startIn :
            Lib.aggNums(Math.min, null, pos0);

        var dummyAx = {
            type: (pa.type === 'category' || pa.type === 'multicategory') ? 'linear' : pa.type,
            r2l: pa.r2l,
            dtick: binOpts.size,
            tick0: mainStart,
            calendar: calendar,
            range: ([traceStart, Axes.tickIncrement(traceStart, binOpts.size, false, calendar)]).map(pa.l2r)
        };
        var newStart = Axes.tickFirst(dummyAx);
        if(newStart > pa.r2l(traceStart)) {
            newStart = Axes.tickIncrement(newStart, binOpts.size, true, calendar);
        }
        traceBinOptsCalc.start = pa.l2r(newStart);
        if(!hasStart) Lib.nestedProperty(trace, binAttr + '.start').set(traceBinOptsCalc.start);
    }

    var mainEnd = binOpts.end;
    var endIn = pa.r2l(traceInputBins.end);
    var hasEnd = endIn !== undefined;
    if((binOpts.endFound || hasEnd) && endIn !== pa.r2l(mainEnd)) {
        // Reconciling an explicit end is easier, as it doesn't need to
        // match bin edges
        var traceEnd = hasEnd ?
            endIn :
            Lib.aggNums(Math.max, null, pos0);

        traceBinOptsCalc.end = pa.l2r(traceEnd);
        if(!hasEnd) Lib.nestedProperty(trace, binAttr + '.start').set(traceBinOptsCalc.end);
    }

    // Backward compatibility for one-time autobinning.
    // autobin: true is handled in cleanData, but autobin: false
    // needs to be here where we have determined the values.
    var autoBinAttr = 'autobin' + mainData;
    if(trace._input[autoBinAttr] === false) {
        trace._input[binAttr] = Lib.extendFlat({}, trace[binAttr] || {});
        delete trace._input[autoBinAttr];
        delete trace[autoBinAttr];
    }

    return [traceBinOptsCalc, pos0];
}

/*
 * Adjust single-value histograms in overlay mode to make as good a
 * guess as we can at autobin values the user would like.
 *
 * Returns the binSpec for the trace that sparked all this
 */
function handleSingleValueOverlays(gd, trace, pa, mainData, binAttr) {
    var overlaidTraceGroup = getConnectedHistograms(gd, trace);
    var pastThisTrace = false;
    var minSize = Infinity;
    var singleValuedTraces = [trace];
    var i, tracei;

    // first collect all the:
    // - min bin size from all multi-valued traces
    // - single-valued traces
    for(i = 0; i < overlaidTraceGroup.length; i++) {
        tracei = overlaidTraceGroup[i];
        if(tracei === trace) pastThisTrace = true;
        else if(!pastThisTrace) {
            // This trace has already had its autobins calculated
            // (so must not have been single-valued).
            minSize = Math.min(minSize, tracei[binAttr].size);
        }
        else {
            var resulti = calcAllAutoBins(gd, tracei, pa, mainData, true);
            var binSpeci = resulti[0];
            var isSingleValued = resulti[2];

            // so we can use this result when we get to tracei in the normal
            // course of events, mark it as done and put _pos0 back
            tracei._autoBinFinished = 1;
            tracei._pos0 = resulti[1];

            if(isSingleValued) {
                singleValuedTraces.push(tracei);
            }
            else {
                minSize = Math.min(minSize, binSpeci.size);
            }
        }
    }

    // find the real data values for each single-valued trace
    // hunt through pos0 for the first valid value
    var dataVals = new Array(singleValuedTraces.length);
    for(i = 0; i < singleValuedTraces.length; i++) {
        var pos0 = singleValuedTraces[i]._pos0;
        for(var j = 0; j < pos0.length; j++) {
            if(pos0[j] !== undefined) {
                dataVals[i] = pos0[j];
                break;
            }
        }
    }

    // are ALL traces are single-valued? use the min difference between
    // all of their values (which defaults to 1 if there's still only one)
    if(!isFinite(minSize)) {
        minSize = Lib.distinctVals(dataVals).minDiff;
    }

    // now apply the min size we found to all single-valued traces
    for(i = 0; i < singleValuedTraces.length; i++) {
        tracei = singleValuedTraces[i];
        var calendar = tracei[mainData + 'calendar'];

        tracei._input[binAttr] = tracei[binAttr] = {
            start: pa.c2r(dataVals[i] - minSize / 2, 0, calendar),
            end: pa.c2r(dataVals[i] + minSize / 2, 0, calendar),
            size: minSize
        };
    }

    return trace[binAttr];
}

/*
 * Return an array of histograms that share axes and orientation.
 *
 * Only considers histograms. In principle we could include bars in a
 * similar way to how we do manually binned histograms, though this
 * would have tons of edge cases and value judgments to make.
 */
function getConnectedHistograms(gd, trace) {
    var xid = trace.xaxis;
    var yid = trace.yaxis;
    var orientation = trace.orientation;

    var out = [];
    var fullData = gd._fullData;
    for(var i = 0; i < fullData.length; i++) {
        var tracei = fullData[i];
        if(tracei.type === 'histogram' &&
            tracei.visible === true &&
            tracei.orientation === orientation &&
            tracei.xaxis === xid && tracei.yaxis === yid
        ) {
            out.push(tracei);
        }
    }

    return out;
}


function cdf(size, direction, currentBin) {
    var i, vi, prevSum;

    function firstHalfPoint(i) {
        prevSum = size[i];
        size[i] /= 2;
    }

    function nextHalfPoint(i) {
        vi = size[i];
        size[i] = prevSum + vi / 2;
        prevSum += vi;
    }

    if(currentBin === 'half') {

        if(direction === 'increasing') {
            firstHalfPoint(0);
            for(i = 1; i < size.length; i++) {
                nextHalfPoint(i);
            }
        }
        else {
            firstHalfPoint(size.length - 1);
            for(i = size.length - 2; i >= 0; i--) {
                nextHalfPoint(i);
            }
        }
    }
    else if(direction === 'increasing') {
        for(i = 1; i < size.length; i++) {
            size[i] += size[i - 1];
        }

        // 'exclude' is identical to 'include' just shifted one bin over
        if(currentBin === 'exclude') {
            size.unshift(0);
            size.pop();
        }
    }
    else {
        for(i = size.length - 2; i >= 0; i--) {
            size[i] += size[i + 1];
        }

        if(currentBin === 'exclude') {
            size.push(0);
            size.shift();
        }
    }
}

},{"../../lib":697,"../../plots/cartesian/axes":745,"../bar/arrays_to_calcdata":835,"./average":964,"./bin_functions":966,"./bin_label_vals":967,"./norm_functions":975,"fast-isnumeric":218}],969:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = {
    eventDataKeys: ['binNumber']
};

},{}],970:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var nestedProperty = Lib.nestedProperty;

var handleGroupingDefaults = _dereq_('../bar/defaults').handleGroupingDefaults;
var getAxisGroup = _dereq_('../../plots/cartesian/axis_ids').getAxisGroup;
var attributes = _dereq_('./attributes');

var BINATTRS = {
    x: [
        {aStr: 'xbins.start', name: 'start'},
        {aStr: 'xbins.end', name: 'end'},
        {aStr: 'xbins.size', name: 'size'},
        {aStr: 'nbinsx', name: 'nbins'}
    ],
    y: [
        {aStr: 'ybins.start', name: 'start'},
        {aStr: 'ybins.end', name: 'end'},
        {aStr: 'ybins.size', name: 'size'},
        {aStr: 'nbinsy', name: 'nbins'}
    ]
};

// handle bin attrs and relink auto-determined values so fullData is complete
module.exports = function crossTraceDefaults(fullData, fullLayout) {
    var allBinOpts = fullLayout._histogramBinOpts = {};
    var isOverlay = fullLayout.barmode === 'overlay';
    var i, j, traceOut, traceIn, binDirection, group, binOpts;

    function coerce(attr) {
        return Lib.coerce(traceOut._input, traceOut, attributes, attr);
    }

    for(i = 0; i < fullData.length; i++) {
        traceOut = fullData[i];
        if(traceOut.type !== 'histogram') continue;

        // TODO: this shouldn't be relinked as it's only used within calc
        // https://github.com/plotly/plotly.js/issues/749
        delete traceOut._autoBinFinished;

        binDirection = traceOut.orientation === 'v' ? 'x' : 'y';
        // in overlay mode make a separate group for each trace
        // otherwise collect all traces of the same subplot & orientation
        group = traceOut._groupName = isOverlay ? traceOut.uid : (
            getAxisGroup(fullLayout, traceOut.xaxis) +
            getAxisGroup(fullLayout, traceOut.yaxis) +
            binDirection
        );
        binOpts = allBinOpts[group];

        if(binOpts) {
            binOpts.traces.push(traceOut);
        } else {
            binOpts = allBinOpts[group] = {
                traces: [traceOut],
                direction: binDirection
            };
        }

        handleGroupingDefaults(traceOut._input, traceOut, fullLayout, coerce);
    }

    for(group in allBinOpts) {
        binOpts = allBinOpts[group];
        binDirection = binOpts.direction;
        var attrs = BINATTRS[binDirection];
        for(j = 0; j < attrs.length; j++) {
            var attrSpec = attrs[j];
            var attr = attrSpec.name;

            // nbins(x|y) is moot if we have a size. This depends on
            // nbins coming after size in binAttrs.
            if(attr === 'nbins' && binOpts.sizeFound) continue;

            var aStr = attrSpec.aStr;
            for(i = 0; i < binOpts.traces.length; i++) {
                traceOut = binOpts.traces[i];
                traceIn = traceOut._input;
                if(nestedProperty(traceIn, aStr).get() !== undefined) {
                    binOpts[attr] = coerce(aStr);
                    binOpts[attr + 'Found'] = true;
                    break;
                }
                var autoVals = traceOut._autoBin;
                if(autoVals && autoVals[attr]) {
                    // if this is the *first* autoval
                    nestedProperty(traceOut, aStr).set(autoVals[attr]);
                }
            }
            // start and end we need to coerce anyway, after having collected the
            // first of each into binOpts, in case a trace wants to restrict its
            // data to a certain range
            if(attr === 'start' || attr === 'end') {
                for(; i < binOpts.traces.length; i++) {
                    traceOut = binOpts.traces[i];
                    coerce(aStr, (traceOut._autoBin || {})[attr]);
                }
            }

            if(attr === 'nbins' && !binOpts.sizeFound && !binOpts.nbinsFound) {
                traceOut = binOpts.traces[0];
                binOpts[attr] = coerce(aStr);
            }
        }
    }
};

},{"../../lib":697,"../../plots/cartesian/axis_ids":748,"../bar/defaults":840,"./attributes":963}],971:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Color = _dereq_('../../components/color');

var handleStyleDefaults = _dereq_('../bar/style_defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var x = coerce('x');
    var y = coerce('y');

    var cumulative = coerce('cumulative.enabled');
    if(cumulative) {
        coerce('cumulative.direction');
        coerce('cumulative.currentbin');
    }

    coerce('text');
    coerce('hovertext');
    coerce('hovertemplate');

    var orientation = coerce('orientation', (y && !x) ? 'h' : 'v');
    var sampleLetter = orientation === 'v' ? 'x' : 'y';
    var aggLetter = orientation === 'v' ? 'y' : 'x';

    var len = (x && y) ?
        Math.min(Lib.minRowLength(x) && Lib.minRowLength(y)) :
        Lib.minRowLength(traceOut[sampleLetter] || []);

    if(!len) {
        traceOut.visible = false;
        return;
    }

    traceOut._length = len;

    var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
    handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout);

    var hasAggregationData = traceOut[aggLetter];
    if(hasAggregationData) coerce('histfunc');
    coerce('histnorm');

    // Note: bin defaults are now handled in Histogram.crossTraceDefaults
    // autobin(x|y) are only included here to appease Plotly.validate
    coerce('autobin' + sampleLetter);

    handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout);

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);

    var lineColor = (traceOut.marker.line || {}).color;

    // override defaultColor for error bars with defaultLine
    var errorBarsSupplyDefaults = Registry.getComponentMethod('errorbars', 'supplyDefaults');
    errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color.defaultLine, {axis: 'y'});
    errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color.defaultLine, {axis: 'x', inherit: 'y'});
};

},{"../../components/color":574,"../../lib":697,"../../registry":826,"../bar/style_defaults":850,"./attributes":963}],972:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function eventData(out, pt, trace, cd, pointNumber) {
    // standard cartesian event data
    out.x = 'xVal' in pt ? pt.xVal : pt.x;
    out.y = 'yVal' in pt ? pt.yVal : pt.y;

    // for 2d histograms
    if('zLabelVal' in pt) out.z = pt.zLabelVal;

    if(pt.xa) out.xaxis = pt.xa;
    if(pt.ya) out.yaxis = pt.ya;

    // specific to histogram - CDFs do not have pts (yet?)
    if(!(trace.cumulative || {}).enabled) {
        var pts = Array.isArray(pointNumber) ?
            cd[0].pts[pointNumber[0]][pointNumber[1]] :
            cd[pointNumber].pts;

        out.pointNumbers = pts;
        out.binNumber = out.pointNumber;
        delete out.pointNumber;
        delete out.pointIndex;

        var pointIndices;
        if(trace._indexToPoints) {
            pointIndices = [];
            for(var i = 0; i < pts.length; i++) {
                pointIndices = pointIndices.concat(trace._indexToPoints[pts[i]]);
            }
        } else {
            pointIndices = pts;
        }

        out.pointIndices = pointIndices;
    }

    return out;
};

},{}],973:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var barHover = _dereq_('../bar/hover').hoverPoints;
var hoverLabelText = _dereq_('../../plots/cartesian/axes').hoverLabelText;

module.exports = function hoverPoints(pointData, xval, yval, hovermode) {
    var pts = barHover(pointData, xval, yval, hovermode);

    if(!pts) return;

    pointData = pts[0];
    var di = pointData.cd[pointData.index];
    var trace = pointData.cd[0].trace;

    if(!trace.cumulative.enabled) {
        var posLetter = trace.orientation === 'h' ? 'y' : 'x';

        pointData[posLetter + 'Label'] = hoverLabelText(pointData[posLetter + 'a'], di.ph0, di.ph1);
    }

    if(trace.hovermplate) pointData.hovertemplate = trace.hovertemplate;

    return pts;
};

},{"../../plots/cartesian/axes":745,"../bar/hover":842}],974:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

/**
 * Histogram has its own attribute, defaults and calc steps,
 * but uses bar's plot to display
 * and bar's crossTraceCalc (formerly known as setPositions) for stacking and grouping
 */

/**
 * histogram errorBarsOK is debatable, but it's put in for backward compat.
 * there are use cases for it - sqrt for a simple histogram works right now,
 * constant and % work but they're not so meaningful. I guess it could be cool
 * to allow quadrature combination of errors in summed histograms...
 */


var Histogram = {};

Histogram.attributes = _dereq_('./attributes');
Histogram.layoutAttributes = _dereq_('../bar/layout_attributes');
Histogram.supplyDefaults = _dereq_('./defaults');
Histogram.crossTraceDefaults = _dereq_('./cross_trace_defaults');
Histogram.supplyLayoutDefaults = _dereq_('../bar/layout_defaults');
Histogram.calc = _dereq_('./calc');
Histogram.crossTraceCalc = _dereq_('../bar/cross_trace_calc').crossTraceCalc;
Histogram.plot = _dereq_('../bar/plot');
Histogram.layerName = 'barlayer';
Histogram.style = _dereq_('../bar/style').style;
Histogram.styleOnSelect = _dereq_('../bar/style').styleOnSelect;
Histogram.colorbar = _dereq_('../scatter/marker_colorbar');
Histogram.hoverPoints = _dereq_('./hover');
Histogram.selectPoints = _dereq_('../bar/select');
Histogram.eventData = _dereq_('./event_data');

Histogram.moduleType = 'trace';
Histogram.name = 'histogram';
Histogram.basePlotModule = _dereq_('../../plots/cartesian');
Histogram.categories = ['cartesian', 'svg', 'bar', 'histogram', 'oriented', 'errorBarsOK', 'showLegend'];
Histogram.meta = {
    
};

module.exports = Histogram;

},{"../../plots/cartesian":756,"../bar/cross_trace_calc":839,"../bar/layout_attributes":844,"../bar/layout_defaults":845,"../bar/plot":846,"../bar/select":847,"../bar/style":849,"../scatter/marker_colorbar":1066,"./attributes":963,"./calc":968,"./cross_trace_defaults":970,"./defaults":971,"./event_data":972,"./hover":973}],975:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


module.exports = {
    percent: function(size, total) {
        var nMax = size.length;
        var norm = 100 / total;
        for(var n = 0; n < nMax; n++) size[n] *= norm;
    },
    probability: function(size, total) {
        var nMax = size.length;
        for(var n = 0; n < nMax; n++) size[n] /= total;
    },
    density: function(size, total, inc, yinc) {
        var nMax = size.length;
        yinc = yinc || 1;
        for(var n = 0; n < nMax; n++) size[n] *= inc[n] * yinc;
    },
    'probability density': function(size, total, inc, yinc) {
        var nMax = size.length;
        if(yinc) total /= yinc;
        for(var n = 0; n < nMax; n++) size[n] *= inc[n] / total;
    }
};

},{}],976:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var histogramAttrs = _dereq_('../histogram/attributes');
var makeBinAttrs = _dereq_('../histogram/bin_attributes');
var heatmapAttrs = _dereq_('../heatmap/attributes');
var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;

module.exports = extendFlat(
    {
        x: histogramAttrs.x,
        y: histogramAttrs.y,

        z: {
            valType: 'data_array',
            editType: 'calc',
            
        },
        marker: {
            color: {
                valType: 'data_array',
                editType: 'calc',
                
            },
            editType: 'calc'
        },

        histnorm: histogramAttrs.histnorm,
        histfunc: histogramAttrs.histfunc,
        nbinsx: histogramAttrs.nbinsx,
        xbins: makeBinAttrs('x'),
        nbinsy: histogramAttrs.nbinsy,
        ybins: makeBinAttrs('y'),
        autobinx: histogramAttrs.autobinx,
        autobiny: histogramAttrs.autobiny,

        xgap: heatmapAttrs.xgap,
        ygap: heatmapAttrs.ygap,
        zsmooth: heatmapAttrs.zsmooth,
        zhoverformat: heatmapAttrs.zhoverformat,
        hovertemplate: hovertemplateAttrs({}, {keys: 'z'})
    },
    colorscaleAttrs('', {
        cLetter: 'z',
        autoColorDflt: false
    }),
    { colorbar: colorbarAttrs }
);

},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../heatmap/attributes":945,"../histogram/attributes":963,"../histogram/bin_attributes":965}],977:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');

var binFunctions = _dereq_('../histogram/bin_functions');
var normFunctions = _dereq_('../histogram/norm_functions');
var doAvg = _dereq_('../histogram/average');
var getBinSpanLabelRound = _dereq_('../histogram/bin_label_vals');


module.exports = function calc(gd, trace) {
    var xa = Axes.getFromId(gd, trace.xaxis || 'x');
    var x = trace.x ? xa.makeCalcdata(trace, 'x') : [];
    var ya = Axes.getFromId(gd, trace.yaxis || 'y');
    var y = trace.y ? ya.makeCalcdata(trace, 'y') : [];
    var xcalendar = trace.xcalendar;
    var ycalendar = trace.ycalendar;
    var xr2c = function(v) { return xa.r2c(v, 0, xcalendar); };
    var yr2c = function(v) { return ya.r2c(v, 0, ycalendar); };
    var xc2r = function(v) { return xa.c2r(v, 0, xcalendar); };
    var yc2r = function(v) { return ya.c2r(v, 0, ycalendar); };

    var i, j, n, m;

    var serieslen = trace._length;
    if(x.length > serieslen) x.splice(serieslen, x.length - serieslen);
    if(y.length > serieslen) y.splice(serieslen, y.length - serieslen);

    // calculate the bins
    doAutoBin(trace, 'x', x, xa, xr2c, xc2r, xcalendar);
    doAutoBin(trace, 'y', y, ya, yr2c, yc2r, ycalendar);

    // make the empty bin array & scale the map
    var z = [];
    var onecol = [];
    var zerocol = [];
    var nonuniformBinsX = (typeof(trace.xbins.size) === 'string');
    var nonuniformBinsY = (typeof(trace.ybins.size) === 'string');
    var xEdges = [];
    var yEdges = [];
    var xbins = nonuniformBinsX ? xEdges : trace.xbins;
    var ybins = nonuniformBinsY ? yEdges : trace.ybins;
    var total = 0;
    var counts = [];
    var inputPoints = [];
    var norm = trace.histnorm;
    var func = trace.histfunc;
    var densitynorm = (norm.indexOf('density') !== -1);
    var extremefunc = (func === 'max' || func === 'min');
    var sizeinit = (extremefunc ? null : 0);
    var binfunc = binFunctions.count;
    var normfunc = normFunctions[norm];
    var doavg = false;
    var xinc = [];
    var yinc = [];

    // set a binning function other than count?
    // for binning functions: check first for 'z',
    // then 'mc' in case we had a colored scatter plot
    // and want to transfer these colors to the 2D histo
    // TODO: axe this, make it the responsibility of the app changing type? or an impliedEdit?
    var rawCounterData = ('z' in trace) ?
        trace.z :
        (('marker' in trace && Array.isArray(trace.marker.color)) ?
            trace.marker.color : '');
    if(rawCounterData && func !== 'count') {
        doavg = func === 'avg';
        binfunc = binFunctions[func];
    }

    // decrease end a little in case of rounding errors
    var binSpec = trace.xbins;
    var binStart = xr2c(binSpec.start);
    var binEnd = xr2c(binSpec.end) +
        (binStart - Axes.tickIncrement(binStart, binSpec.size, false, xcalendar)) / 1e6;

    for(i = binStart; i < binEnd; i = Axes.tickIncrement(i, binSpec.size, false, xcalendar)) {
        onecol.push(sizeinit);
        xEdges.push(i);
        if(doavg) zerocol.push(0);
    }
    xEdges.push(i);

    var nx = onecol.length;
    var x0c = xr2c(trace.xbins.start);
    var dx = (i - x0c) / nx;
    var x0 = xc2r(x0c + dx / 2);

    binSpec = trace.ybins;
    binStart = yr2c(binSpec.start);
    binEnd = yr2c(binSpec.end) +
        (binStart - Axes.tickIncrement(binStart, binSpec.size, false, ycalendar)) / 1e6;

    for(i = binStart; i < binEnd; i = Axes.tickIncrement(i, binSpec.size, false, ycalendar)) {
        z.push(onecol.slice());
        yEdges.push(i);
        var ipCol = new Array(nx);
        for(j = 0; j < nx; j++) ipCol[j] = [];
        inputPoints.push(ipCol);
        if(doavg) counts.push(zerocol.slice());
    }
    yEdges.push(i);

    var ny = z.length;
    var y0c = yr2c(trace.ybins.start);
    var dy = (i - y0c) / ny;
    var y0 = yc2r(y0c + dy / 2);

    if(densitynorm) {
        xinc = makeIncrements(onecol.length, xbins, dx, nonuniformBinsX);
        yinc = makeIncrements(z.length, ybins, dy, nonuniformBinsY);
    }

    // for date axes we need bin bounds to be calcdata. For nonuniform bins
    // we already have this, but uniform with start/end/size they're still strings.
    if(!nonuniformBinsX && xa.type === 'date') xbins = binsToCalc(xr2c, xbins);
    if(!nonuniformBinsY && ya.type === 'date') ybins = binsToCalc(yr2c, ybins);

    // put data into bins
    var uniqueValsPerX = true;
    var uniqueValsPerY = true;
    var xVals = new Array(nx);
    var yVals = new Array(ny);
    var xGapLow = Infinity;
    var xGapHigh = Infinity;
    var yGapLow = Infinity;
    var yGapHigh = Infinity;
    for(i = 0; i < serieslen; i++) {
        var xi = x[i];
        var yi = y[i];
        n = Lib.findBin(xi, xbins);
        m = Lib.findBin(yi, ybins);
        if(n >= 0 && n < nx && m >= 0 && m < ny) {
            total += binfunc(n, i, z[m], rawCounterData, counts[m]);
            inputPoints[m][n].push(i);

            if(uniqueValsPerX) {
                if(xVals[n] === undefined) xVals[n] = xi;
                else if(xVals[n] !== xi) uniqueValsPerX = false;
            }
            if(uniqueValsPerY) {
                if(yVals[n] === undefined) yVals[n] = yi;
                else if(yVals[n] !== yi) uniqueValsPerY = false;
            }

            xGapLow = Math.min(xGapLow, xi - xEdges[n]);
            xGapHigh = Math.min(xGapHigh, xEdges[n + 1] - xi);
            yGapLow = Math.min(yGapLow, yi - yEdges[m]);
            yGapHigh = Math.min(yGapHigh, yEdges[m + 1] - yi);
        }
    }
    // normalize, if needed
    if(doavg) {
        for(m = 0; m < ny; m++) total += doAvg(z[m], counts[m]);
    }
    if(normfunc) {
        for(m = 0; m < ny; m++) normfunc(z[m], total, xinc, yinc[m]);
    }

    return {
        x: x,
        xRanges: getRanges(xEdges, uniqueValsPerX && xVals, xGapLow, xGapHigh, xa, xcalendar),
        x0: x0,
        dx: dx,
        y: y,
        yRanges: getRanges(yEdges, uniqueValsPerY && yVals, yGapLow, yGapHigh, ya, ycalendar),
        y0: y0,
        dy: dy,
        z: z,
        pts: inputPoints
    };
};

function doAutoBin(trace, axLetter, data, ax, r2c, c2r, calendar) {
    var binAttr = axLetter + 'bins';
    var binSpec = trace[binAttr];
    if(!binSpec) binSpec = trace[binAttr] = {};
    var inputBinSpec = trace._input[binAttr] || {};
    var autoBin = trace._autoBin = {};

    // clear out any previously added autobin info
    if(!inputBinSpec.size) delete binSpec.size;
    if(inputBinSpec.start === undefined) delete binSpec.start;
    if(inputBinSpec.end === undefined) delete binSpec.end;

    var autoSize = !binSpec.size;
    var autoStart = binSpec.start === undefined;
    var autoEnd = binSpec.end === undefined;

    if(autoSize || autoStart || autoEnd) {
        var newBinSpec = Axes.autoBin(data, ax, trace['nbins' + axLetter], '2d', calendar, binSpec.size);
        if(trace.type === 'histogram2dcontour') {
            // the "true" 2nd argument reverses the tick direction (which we can't
            // just do with a minus sign because of month bins)
            if(autoStart) {
                newBinSpec.start = c2r(Axes.tickIncrement(
                    r2c(newBinSpec.start), newBinSpec.size, true, calendar));
            }
            if(autoEnd) {
                newBinSpec.end = c2r(Axes.tickIncrement(
                    r2c(newBinSpec.end), newBinSpec.size, false, calendar));
            }
        }
        if(autoSize) binSpec.size = autoBin.size = newBinSpec.size;
        if(autoStart) binSpec.start = autoBin.start = newBinSpec.start;
        if(autoEnd) binSpec.end = autoBin.end = newBinSpec.end;
    }

    // Backward compatibility for one-time autobinning.
    // autobin: true is handled in cleanData, but autobin: false
    // needs to be here where we have determined the values.
    var autoBinAttr = 'autobin' + axLetter;
    if(trace._input[autoBinAttr] === false) {
        trace._input[binAttr] = Lib.extendFlat({}, binSpec);
        delete trace._input[autoBinAttr];
        delete trace[autoBinAttr];
    }
}

function makeIncrements(len, bins, dv, nonuniform) {
    var out = new Array(len);
    var i;
    if(nonuniform) {
        for(i = 0; i < len; i++) out[i] = 1 / (bins[i + 1] - bins[i]);
    }
    else {
        var inc = 1 / dv;
        for(i = 0; i < len; i++) out[i] = inc;
    }
    return out;
}

function binsToCalc(r2c, bins) {
    return {
        start: r2c(bins.start),
        end: r2c(bins.end),
        size: bins.size
    };
}

function getRanges(edges, uniqueVals, gapLow, gapHigh, ax, calendar) {
    var i;
    var len = edges.length - 1;
    var out = new Array(len);
    if(uniqueVals) {
        for(i = 0; i < len; i++) out[i] = [uniqueVals[i], uniqueVals[i]];
    }
    else {
        var roundFn = getBinSpanLabelRound(gapLow, gapHigh, edges, ax, calendar);
        for(i = 0; i < len; i++) out[i] = [roundFn(edges[i]), roundFn(edges[i + 1], true)];
    }
    return out;
}

},{"../../lib":697,"../../plots/cartesian/axes":745,"../histogram/average":964,"../histogram/bin_functions":966,"../histogram/bin_label_vals":967,"../histogram/norm_functions":975}],978:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


var isNumeric = _dereq_('fast-isnumeric');

var BADNUM = _dereq_('../../constants/numerical').BADNUM;
var axisIds = _dereq_('../../plots/cartesian/axis_ids');
var Lib = _dereq_('../../lib');

var attributes = _dereq_('./attributes');

var BINDIRECTIONS = ['x', 'y'];

// Handle bin attrs and relink auto-determined values so fullData is complete
// does not have cross-trace coupling, but moved out here so we have axis types
// and relinked trace._autoBin
module.exports = function crossTraceDefaults(fullData, fullLayout) {
    var i, j, traceOut, binDirection;

    function coerce(attr) {
        return Lib.coerce(traceOut._input, traceOut, attributes, attr);
    }

    for(i = 0; i < fullData.length; i++) {
        traceOut = fullData[i];
        var type = traceOut.type;
        if(type !== 'histogram2d' && type !== 'histogram2dcontour') continue;

        for(j = 0; j < BINDIRECTIONS.length; j++) {
            binDirection = BINDIRECTIONS[j];
            var binAttr = binDirection + 'bins';
            var autoBins = (traceOut._autoBin || {})[binDirection] || {};
            coerce(binAttr + '.start', autoBins.start);
            coerce(binAttr + '.end', autoBins.end);
            coerce(binAttr + '.size', autoBins.size);

            cleanBins(traceOut, binDirection, fullLayout, autoBins);

            if(!(traceOut[binAttr] || {}).size) coerce('nbins' + binDirection);
        }
    }
};

function cleanBins(trace, binDirection, fullLayout, autoBins) {
    var ax = fullLayout[axisIds.id2name(trace[binDirection + 'axis'])];
    var axType = ax.type;
    var binAttr = binDirection + 'bins';
    var bins = trace[binAttr];
    var calendar = trace[binDirection + 'calendar'];

    if(!bins) bins = trace[binAttr] = {};

    var cleanBound = (axType === 'date') ?
        function(v, dflt) { return (v || v === 0) ? Lib.cleanDate(v, BADNUM, calendar) : dflt; } :
        function(v, dflt) { return isNumeric(v) ? Number(v) : dflt; };

    bins.start = cleanBound(bins.start, autoBins.start);
    bins.end = cleanBound(bins.end, autoBins.end);

    // logic for bin size is very similar to dtick (cartesian/tick_value_defaults)
    // but without the extra string options for log axes
    // ie the only strings we accept are M<n> for months
    var sizeDflt = autoBins.size;
    var binSize = bins.size;

    if(isNumeric(binSize)) {
        bins.size = (binSize > 0) ? Number(binSize) : sizeDflt;
    }
    else if(typeof binSize !== 'string') {
        bins.size = sizeDflt;
    }
    else {
        // date special case: "M<n>" gives bins every (integer) n months
        var prefix = binSize.charAt(0);
        var sizeNum = binSize.substr(1);

        sizeNum = isNumeric(sizeNum) ? Number(sizeNum) : 0;
        if((sizeNum <= 0) || !(
                axType === 'date' && prefix === 'M' && sizeNum === Math.round(sizeNum)
            )) {
            bins.size = sizeDflt;
        }
    }
}

},{"../../constants/numerical":674,"../../lib":697,"../../plots/cartesian/axis_ids":748,"./attributes":976,"fast-isnumeric":218}],979:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

var handleSampleDefaults = _dereq_('./sample_defaults');
var handleStyleDefaults = _dereq_('../heatmap/style_defaults');
var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
var attributes = _dereq_('./attributes');


module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    handleSampleDefaults(traceIn, traceOut, coerce, layout);
    if(traceOut.visible === false) return;

    handleStyleDefaults(traceIn, traceOut, coerce, layout);
    colorscaleDefaults(
        traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'}
    );
    coerce('hovertemplate');
};

},{"../../components/colorscale/defaults":584,"../../lib":697,"../heatmap/style_defaults":958,"./attributes":976,"./sample_defaults":982}],980:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var heatmapHover = _dereq_('../heatmap/hover');
var hoverLabelText = _dereq_('../../plots/cartesian/axes').hoverLabelText;

module.exports = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer, contour) {
    var pts = heatmapHover(pointData, xval, yval, hovermode, hoverLayer, contour);

    if(!pts) return;

    pointData = pts[0];
    var indices = pointData.index;
    var ny = indices[0];
    var nx = indices[1];
    var cd0 = pointData.cd[0];
    var xRange = cd0.xRanges[nx];
    var yRange = cd0.yRanges[ny];

    pointData.xLabel = hoverLabelText(pointData.xa, xRange[0], xRange[1]);
    pointData.yLabel = hoverLabelText(pointData.ya, yRange[0], yRange[1]);

    return pts;
};

},{"../../plots/cartesian/axes":745,"../heatmap/hover":952}],981:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Histogram2D = {};

Histogram2D.attributes = _dereq_('./attributes');
Histogram2D.supplyDefaults = _dereq_('./defaults');
Histogram2D.crossTraceDefaults = _dereq_('./cross_trace_defaults');
Histogram2D.calc = _dereq_('../heatmap/calc');
Histogram2D.plot = _dereq_('../heatmap/plot');
Histogram2D.layerName = 'heatmaplayer';
Histogram2D.colorbar = _dereq_('../heatmap/colorbar');
Histogram2D.style = _dereq_('../heatmap/style');
Histogram2D.hoverPoints = _dereq_('./hover');
Histogram2D.eventData = _dereq_('../histogram/event_data');

Histogram2D.moduleType = 'trace';
Histogram2D.name = 'histogram2d';
Histogram2D.basePlotModule = _dereq_('../../plots/cartesian');
Histogram2D.categories = ['cartesian', 'svg', '2dMap', 'histogram'];
Histogram2D.meta = {
    
    
};

module.exports = Histogram2D;

},{"../../plots/cartesian":756,"../heatmap/calc":946,"../heatmap/colorbar":948,"../heatmap/plot":956,"../heatmap/style":957,"../histogram/event_data":972,"./attributes":976,"./cross_trace_defaults":978,"./defaults":979,"./hover":980}],982:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');

module.exports = function handleSampleDefaults(traceIn, traceOut, coerce, layout) {
    var x = coerce('x');
    var y = coerce('y');
    var xlen = Lib.minRowLength(x);
    var ylen = Lib.minRowLength(y);

    // we could try to accept x0 and dx, etc...
    // but that's a pretty weird use case.
    // for now require both x and y explicitly specified.
    if(!xlen || !ylen) {
        traceOut.visible = false;
        return;
    }

    traceOut._length = Math.min(xlen, ylen);

    var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
    handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout);

    // if marker.color is an array, we can use it in aggregation instead of z
    var hasAggregationData = coerce('z') || coerce('marker.color');

    if(hasAggregationData) coerce('histfunc');
    coerce('histnorm');

    // Note: bin defaults are now handled in Histogram2D.crossTraceDefaults
    // autobin(x|y) are only included here to appease Plotly.validate
    coerce('autobinx');
    coerce('autobiny');
};

},{"../../lib":697,"../../registry":826}],983:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var histogram2dAttrs = _dereq_('../histogram2d/attributes');
var contourAttrs = _dereq_('../contour/attributes');
var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;

module.exports = extendFlat({
    x: histogram2dAttrs.x,
    y: histogram2dAttrs.y,
    z: histogram2dAttrs.z,
    marker: histogram2dAttrs.marker,

    histnorm: histogram2dAttrs.histnorm,
    histfunc: histogram2dAttrs.histfunc,
    nbinsx: histogram2dAttrs.nbinsx,
    xbins: histogram2dAttrs.xbins,
    nbinsy: histogram2dAttrs.nbinsy,
    ybins: histogram2dAttrs.ybins,
    autobinx: histogram2dAttrs.autobinx,
    autobiny: histogram2dAttrs.autobiny,

    autocontour: contourAttrs.autocontour,
    ncontours: contourAttrs.ncontours,
    contours: contourAttrs.contours,
    line: contourAttrs.line,
    zhoverformat: histogram2dAttrs.zhoverformat,
    hovertemplate: histogram2dAttrs.hovertemplate
},
    colorscaleAttrs('', {
        cLetter: 'z',
        editTypeOverride: 'calc'
    }),
    { colorbar: colorbarAttrs }
);

},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../lib/extend":687,"../contour/attributes":916,"../histogram2d/attributes":976}],984:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

var handleSampleDefaults = _dereq_('../histogram2d/sample_defaults');
var handleContoursDefaults = _dereq_('../contour/contours_defaults');
var handleStyleDefaults = _dereq_('../contour/style_defaults');
var attributes = _dereq_('./attributes');


module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    function coerce2(attr) {
        return Lib.coerce2(traceIn, traceOut, attributes, attr);
    }

    handleSampleDefaults(traceIn, traceOut, coerce, layout);
    if(traceOut.visible === false) return;

    handleContoursDefaults(traceIn, traceOut, coerce, coerce2);
    handleStyleDefaults(traceIn, traceOut, coerce, layout);
    coerce('hovertemplate');
};

},{"../../lib":697,"../contour/contours_defaults":923,"../contour/style_defaults":937,"../histogram2d/sample_defaults":982,"./attributes":983}],985:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Histogram2dContour = {};

Histogram2dContour.attributes = _dereq_('./attributes');
Histogram2dContour.supplyDefaults = _dereq_('./defaults');
Histogram2dContour.crossTraceDefaults = _dereq_('../histogram2d/cross_trace_defaults');
Histogram2dContour.calc = _dereq_('../contour/calc');
Histogram2dContour.plot = _dereq_('../contour/plot').plot;
Histogram2dContour.layerName = 'contourlayer';
Histogram2dContour.style = _dereq_('../contour/style');
Histogram2dContour.colorbar = _dereq_('../contour/colorbar');
Histogram2dContour.hoverPoints = _dereq_('../contour/hover');

Histogram2dContour.moduleType = 'trace';
Histogram2dContour.name = 'histogram2dcontour';
Histogram2dContour.basePlotModule = _dereq_('../../plots/cartesian');
Histogram2dContour.categories = ['cartesian', 'svg', '2dMap', 'contour', 'histogram', 'showLegend'];
Histogram2dContour.meta = {
    
    
};

module.exports = Histogram2dContour;

},{"../../plots/cartesian":756,"../contour/calc":917,"../contour/colorbar":919,"../contour/hover":929,"../contour/plot":934,"../contour/style":936,"../histogram2d/cross_trace_defaults":978,"./attributes":983,"./defaults":984}],986:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var meshAttrs = _dereq_('../mesh3d/attributes');
var baseAttrs = _dereq_('../../plots/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;

function makeSliceAttr(axLetter) {
    return {
        show: {
            valType: 'boolean',
            
            dflt: false,
            
        },
        locations: {
            valType: 'data_array',
            dflt: [],
            
            
        },
        fill: {
            valType: 'number',
            
            min: 0,
            max: 1,
            dflt: 1,
            
        }
    };
}

function makeCapAttr(axLetter) {
    return {
        show: {
            valType: 'boolean',
            
            dflt: true,
            
        },
        fill: {
            valType: 'number',
            
            min: 0,
            max: 1,
            dflt: 1,
            
        }
    };
}

var attrs = module.exports = overrideAll(extendFlat({
    x: {
        valType: 'data_array',
        
        
    },
    y: {
        valType: 'data_array',
        
        
    },
    z: {
        valType: 'data_array',
        
        
    },
    value: {
        valType: 'data_array',
        
        
    },
    isomin: {
        valType: 'number',
        
        
    },
    isomax: {
        valType: 'number',
        
        
    },

    surface: {
        show: {
            valType: 'boolean',
            
            dflt: true,
            
        },
        count: {
            valType: 'integer',
            
            dflt: 2,
            min: 1,
            
        },
        fill: {
            valType: 'number',
            
            min: 0,
            max: 1,
            dflt: 1,
            
        },
        pattern: {
            valType: 'flaglist',
            flags: ['A', 'B', 'C', 'D', 'E'],
            extras: ['all', 'odd', 'even'],
            dflt: 'all',
            
            
        }
    },

    spaceframe: {
        show: {
            valType: 'boolean',
            
            dflt: false,
            
        },
        fill: {
            valType: 'number',
            
            min: 0,
            max: 1,
            dflt: 0.15,
            
        }
    },

    slices: {
        x: makeSliceAttr('x'),
        y: makeSliceAttr('y'),
        z: makeSliceAttr('z')
    },

    caps: {
        x: makeCapAttr('x'),
        y: makeCapAttr('y'),
        z: makeCapAttr('z')
    },

    text: {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        
    },
    hovertext: {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        
    },
    hovertemplate: hovertemplateAttrs()
},

colorscaleAttrs('', {
    colorAttr: '`value`',
    showScaleDflt: true,
    editTypeOverride: 'calc'
}), {

    colorbar: colorbarAttrs,

    opacity: meshAttrs.opacity,
    lightposition: meshAttrs.lightposition,
    lighting: meshAttrs.lighting,
    flatshading: meshAttrs.flatshading,
    contour: meshAttrs.contour,

    hoverinfo: extendFlat({}, baseAttrs.hoverinfo)
}), 'calc', 'nested');

// required defaults to speed up surface normal calculations
attrs.flatshading.dflt = true; attrs.lighting.facenormalsepsilon.dflt = 0;

attrs.x.editType = attrs.y.editType = attrs.z.editType = attrs.value.editType = 'calc+clearAxisTypes';
attrs.transforms = undefined;

},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plot_api/edit_types":728,"../../plots/attributes":742,"../mesh3d/attributes":991}],987:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorscaleCalc = _dereq_('../../components/colorscale/calc');

module.exports = function calc(gd, trace) {

    trace._len = Math.min(trace.x.length, trace.y.length, trace.z.length, trace.value.length);

    var min = Infinity;
    var max = -Infinity;
    var len = trace.value.length;
    for(var i = 0; i < len; i++) {
        var v = trace.value[i];
        min = Math.min(min, v);
        max = Math.max(max, v);
    }

    trace._minValues = min;
    trace._maxValues = max;

    trace._vMin = (trace.isomin === undefined || trace.isomin === null) ? min : trace.isomin;
    trace._vMax = (trace.isomax === undefined || trace.isomin === null) ? max : trace.isomax;

    colorscaleCalc(gd, trace, {
        vals: [trace._vMin, trace._vMax],
        containerStr: '',
        cLetter: 'c'
    });
};

},{"../../components/colorscale/calc":582}],988:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var createMesh = _dereq_('gl-mesh3d');

var parseColorScale = _dereq_('../../lib/gl_format_color').parseColorScale;
var str2RgbaArray = _dereq_('../../lib/str2rgbarray');
var zip3 = _dereq_('../../plots/gl3d/zip3');
var Lib = _dereq_('../../lib');

function distinctVals(col) {
    return Lib.distinctVals(col).vals;
}

function IsosurfaceTrace(scene, mesh, uid) {
    this.scene = scene;
    this.uid = uid;
    this.mesh = mesh;
    this.name = '';
    this.data = null;
    this.showContour = false;
}

var proto = IsosurfaceTrace.prototype;

function findNearestOnAxis(w, arr) {
    for(var q = arr.length - 1; q > 0; q--) {
        var min = Math.min(arr[q], arr[q - 1]);
        var max = Math.max(arr[q], arr[q - 1]);
        if(max > min && min < w && w <= max) {
            return {
                id: q,
                distRatio: (max - w) / (max - min)
            };
        }
    }
    return {
        id: 0,
        distRatio: 0
    };
}

proto.handlePick = function(selection) {
    if(selection.object === this.mesh) {

        var rawId = selection.data.index;

        var x = this.data._x[rawId];
        var y = this.data._y[rawId];
        var z = this.data._z[rawId];

        var height = this.data._Ys.length;
        var depth = this.data._Zs.length;

        var i = findNearestOnAxis(x, this.data._Xs).id;
        var j = findNearestOnAxis(y, this.data._Ys).id;
        var k = findNearestOnAxis(z, this.data._Zs).id;

        var selectIndex = selection.index = k + depth * j + depth * height * i;

        selection.traceCoordinate = [
            this.data._x[selectIndex],
            this.data._y[selectIndex],
            this.data._z[selectIndex],
            this.data.value[selectIndex]
        ];

        var text = this.data.hovertext || this.data.text;
        if(Array.isArray(text) && text[selectIndex] !== undefined) {
            selection.textLabel = text[selectIndex];
        } else if(text) {
            selection.textLabel = text;
        }

        return true;
    }
};

proto.update = function(data) {
    var scene = this.scene;
    var layout = scene.fullSceneLayout;

    this.data = generateIsosurfaceMesh(data);

    // Unpack position data
    function toDataCoords(axis, coord, scale, calendar) {
        return coord.map(function(x) {
            return axis.d2l(x, 0, calendar) * scale;
        });
    }

    var positions = zip3(
        toDataCoords(layout.xaxis, data._x, scene.dataScale[0], data.xcalendar),
        toDataCoords(layout.yaxis, data._y, scene.dataScale[1], data.ycalendar),
        toDataCoords(layout.zaxis, data._z, scene.dataScale[2], data.zcalendar));

    var cells = zip3(data._i, data._j, data._k);

    var config = {
        positions: positions,
        cells: cells,
        lightPosition: [data.lightposition.x, data.lightposition.y, data.lightposition.z],
        ambient: data.lighting.ambient,
        diffuse: data.lighting.diffuse,
        specular: data.lighting.specular,
        roughness: data.lighting.roughness,
        fresnel: data.lighting.fresnel,
        vertexNormalsEpsilon: data.lighting.vertexnormalsepsilon,
        faceNormalsEpsilon: data.lighting.facenormalsepsilon,
        opacity: data.opacity,
        contourEnable: data.contour.show,
        contourColor: str2RgbaArray(data.contour.color).slice(0, 3),
        contourWidth: data.contour.width,
        useFacetNormals: data.flatshading
    };

    config.vertexIntensity = data._intensity;
    config.vertexIntensityBounds = [data.cmin, data.cmax];
    config.colormap = parseColorScale(data);

    // Update mesh
    this.mesh.update(config);
};

proto.dispose = function() {
    this.scene.glplot.remove(this.mesh);
    this.mesh.dispose();
};

function generateIsosurfaceMesh(data) {

    data._i = [];
    data._j = [];
    data._k = [];

    var showSurface = data.surface.show;
    var showSpaceframe = data.spaceframe.show;

    var surfaceFill = data.surface.fill;
    var spaceframeFill = data.spaceframe.fill;

    var drawingSurface = false;
    var drawingSpaceframe = false;

    var numFaces = 0;
    var numVertices;
    var beginVertextLength;

    var Xs = distinctVals(data.x.slice(0, data._len));
    var Ys = distinctVals(data.y.slice(0, data._len));
    var Zs = distinctVals(data.z.slice(0, data._len));

    var width = Xs.length;
    var height = Ys.length;
    var depth = Zs.length;

    function getIndex(i, j, k) {
        return k + depth * j + depth * height * i;
    }

    var minValues = data._minValues;
    var maxValues = data._maxValues;

    var vMin = data._vMin;
    var vMax = data._vMax;

    var allXs;
    var allYs;
    var allZs;
    var allVs;

    function findVertexId(x, y, z) {
        // could be used to find the vertex id of previously generated vertex within the group

        var len = allVs.length;
        for(var f = beginVertextLength; f < len; f++) {
            if(
                x === allXs[f] &&
                y === allYs[f] &&
                z === allZs[f]
            ) {
                return f;
            }
        }
        return -1;
    }

    function beginGroup() {
        beginVertextLength = numVertices;
    }

    function emptyVertices() {
        allXs = [];
        allYs = [];
        allZs = [];
        allVs = [];
        numVertices = 0;

        beginGroup();
    }

    function addVertex(x, y, z, v) {
        allXs.push(x);
        allYs.push(y);
        allZs.push(z);
        allVs.push(v);
        numVertices++;

        return numVertices - 1;
    }

    function addFace(a, b, c) {
        data._i.push(a);
        data._j.push(b);
        data._k.push(c);
        numFaces++;

        return numFaces - 1;
    }

    function getCenter(A, B, C) {
        var M = [];
        for(var i = 0; i < A.length; i++) {
            M[i] = (A[i] + B[i] + C[i]) / 3.0;
        }
        return M;
    }

    function getBetween(A, B, r) {
        var M = [];
        for(var i = 0; i < A.length; i++) {
            M[i] = A[i] * (1 - r) + r * B[i];
        }
        return M;
    }

    var activeFill;
    function setFill(fill) {
        activeFill = fill;
    }

    function createOpenTri(xyzv, abc) {
        var A = xyzv[0];
        var B = xyzv[1];
        var C = xyzv[2];
        var G = getCenter(A, B, C);

        var r = Math.sqrt(1 - activeFill);
        var p1 = getBetween(G, A, r);
        var p2 = getBetween(G, B, r);
        var p3 = getBetween(G, C, r);

        var a = abc[0];
        var b = abc[1];
        var c = abc[2];

        return {
            xyzv: [
                [A, B, p2], [p2, p1, A],
                [B, C, p3], [p3, p2, B],
                [C, A, p1], [p1, p3, C]
            ],
            abc: [
                [a, b, -1], [-1, -1, a],
                [b, c, -1], [-1, -1, b],
                [c, a, -1], [-1, -1, c]
            ]
        };
    }

    function styleIncludes(style, char) {
        if(style === 'all' || style === null) return true;
        return (style.indexOf(char) > -1);
    }

    function mapValue(style, value) {
        if(style === null) return value;
        return style;
    }

    function drawTri(style, xyzv, abc) {

        beginGroup();

        var allXYZVs = [xyzv];
        var allABCs = [abc];
        if(activeFill >= 1) {
            allXYZVs = [xyzv];
            allABCs = [abc];
        } else if(activeFill > 0) {
            var openTri = createOpenTri(xyzv, abc);
            allXYZVs = openTri.xyzv;
            allABCs = openTri.abc;
        }

        for(var f = 0; f < allXYZVs.length; f++) {

            xyzv = allXYZVs[f];
            abc = allABCs[f];

            var pnts = [];
            for(var i = 0; i < 3; i++) {

                var x = xyzv[i][0];
                var y = xyzv[i][1];
                var z = xyzv[i][2];
                var v = xyzv[i][3];

                var id = (abc[i] > -1) ? abc[i] : findVertexId(x, y, z);
                if(id > -1) {
                    pnts[i] = id;
                } else {
                    pnts[i] = addVertex(x, y, z, mapValue(style, v));
                }
            }

            addFace(pnts[0], pnts[1], pnts[2]);
        }
    }

    function drawQuad(style, xyzv, abcd) {
        var makeTri = function(i, j, k) {
            drawTri(style, [xyzv[i], xyzv[j], xyzv[k]], [abcd[i], abcd[j], abcd[k]]);
        };

        makeTri(0, 1, 2);
        makeTri(2, 3, 0);
    }

    function drawTetra(style, xyzv, abcd) {
        var makeTri = function(i, j, k) {
            drawTri(style, [xyzv[i], xyzv[j], xyzv[k]], [abcd[i], abcd[j], abcd[k]]);
        };

        makeTri(0, 1, 2);
        makeTri(3, 0, 1);
        makeTri(2, 3, 0);
        makeTri(1, 2, 3);
    }

    function calcIntersection(pointOut, pointIn, min, max) {
        var value = pointOut[3];

        if(value < min) value = min;
        if(value > max) value = max;

        var ratio = (pointOut[3] - value) / (pointOut[3] - pointIn[3] + 0.000000001); // we had to add this error to force solve the tiny caps

        var result = [];
        for(var s = 0; s < 4; s++) {
            result[s] = (1 - ratio) * pointOut[s] + ratio * pointIn[s];
        }
        return result;
    }

    function inRange(value, min, max) {
        return (
            value >= min &&
            value <= max
        );
    }

    function almostInFinalRange(value) {
        var vErr = 0.001 * (vMax - vMin);
        return (
            value >= vMin - vErr &&
            value <= vMax + vErr
        );
    }

    function getXYZV(indecies) {
        var xyzv = [];
        for(var q = 0; q < 4; q++) {
            var index = indecies[q];
            xyzv.push(
                [
                    data.x[index],
                    data.y[index],
                    data.z[index],
                    data.value[index]
                ]
            );
        }

        return xyzv;
    }

    var MAX_PASS = 3;

    function tryCreateTri(style, xyzv, abc, min, max, nPass) {

        if(!nPass) nPass = 1;

        abc = [-1, -1, -1]; // Note: for the moment we override indices
        // to run faster! But it is possible to comment this line
        // to reduce the number of vertices.

        var result = false;

        var ok = [
            inRange(xyzv[0][3], min, max),
            inRange(xyzv[1][3], min, max),
            inRange(xyzv[2][3], min, max)
        ];

        if(!ok[0] && !ok[1] && !ok[2]) {
            return false;
        }

        var tryDrawTri = function(style, xyzv, abc) {
            if( // we check here if the points are in `real` iso-min/max range
                almostInFinalRange(xyzv[0][3]) &&
                almostInFinalRange(xyzv[1][3]) &&
                almostInFinalRange(xyzv[2][3])
            ) {
                drawTri(style, xyzv, abc);
                return true;
            } else if(nPass < MAX_PASS) {
                return tryCreateTri(style, xyzv, abc, vMin, vMax, ++nPass); // i.e. second pass using actual vMin vMax bounds
            }
            return false;
        };

        if(ok[0] && ok[1] && ok[2]) {
            return tryDrawTri(style, xyzv, abc) || result;
        }

        var interpolated = false;

        [
            [0, 1, 2],
            [2, 0, 1],
            [1, 2, 0]
        ].forEach(function(e) {
            if(ok[e[0]] && ok[e[1]] && !ok[e[2]]) {
                var A = xyzv[e[0]];
                var B = xyzv[e[1]];
                var C = xyzv[e[2]];

                var p1 = calcIntersection(C, A, min, max);
                var p2 = calcIntersection(C, B, min, max);

                result = tryDrawTri(style, [p2, p1, A], [-1, -1, abc[e[0]]]) || result;
                result = tryDrawTri(style, [A, B, p2], [abc[e[0]], abc[e[1]], -1]) || result;

                interpolated = true;
            }
        });
        if(interpolated) return result;

        [
            [0, 1, 2],
            [1, 2, 0],
            [2, 0, 1]
        ].forEach(function(e) {
            if(ok[e[0]] && !ok[e[1]] && !ok[e[2]]) {
                var A = xyzv[e[0]];
                var B = xyzv[e[1]];
                var C = xyzv[e[2]];

                var p1 = calcIntersection(B, A, min, max);
                var p2 = calcIntersection(C, A, min, max);

                result = tryDrawTri(style, [p2, p1, A], [-1, -1, abc[e[0]]]) || result;

                interpolated = true;
            }
        });
        return result;
    }

    function tryCreateTetra(style, abcd, min, max) {

        var result = false;

        var xyzv = getXYZV(abcd);

        var ok = [
            inRange(xyzv[0][3], min, max),
            inRange(xyzv[1][3], min, max),
            inRange(xyzv[2][3], min, max),
            inRange(xyzv[3][3], min, max)
        ];

        if(!ok[0] && !ok[1] && !ok[2] && !ok[3]) {
            return result;
        }

        if(ok[0] && ok[1] && ok[2] && ok[3]) {
            if(drawingSpaceframe) {
                result = drawTetra(style, xyzv, abcd) || result;
            }
            return result;
        }

        var interpolated = false;

        [
            [0, 1, 2, 3],
            [3, 0, 1, 2],
            [2, 3, 0, 1],
            [1, 2, 3, 0]
        ].forEach(function(e) {
            if(ok[e[0]] && ok[e[1]] && ok[e[2]] && !ok[e[3]]) {
                var A = xyzv[e[0]];
                var B = xyzv[e[1]];
                var C = xyzv[e[2]];
                var D = xyzv[e[3]];

                if(drawingSpaceframe) {
                    result = drawTri(style, [A, B, C], [abcd[e[0]], abcd[e[1]], abcd[e[2]]]) || result;
                } else {
                    var p1 = calcIntersection(D, A, min, max);
                    var p2 = calcIntersection(D, B, min, max);
                    var p3 = calcIntersection(D, C, min, max);

                    result = drawTri(null, [p1, p2, p3], [-1, -1, -1]) || result;
                }

                interpolated = true;
            }
        });
        if(interpolated) return result;

        [
            [0, 1, 2, 3],
            [1, 2, 3, 0],
            [2, 3, 0, 1],
            [3, 0, 1, 2],
            [0, 2, 3, 1],
            [1, 3, 2, 0]
        ].forEach(function(e) {
            if(ok[e[0]] && ok[e[1]] && !ok[e[2]] && !ok[e[3]]) {
                var A = xyzv[e[0]];
                var B = xyzv[e[1]];
                var C = xyzv[e[2]];
                var D = xyzv[e[3]];

                var p1 = calcIntersection(C, A, min, max);
                var p2 = calcIntersection(C, B, min, max);
                var p3 = calcIntersection(D, B, min, max);
                var p4 = calcIntersection(D, A, min, max);

                if(drawingSpaceframe) {
                    result = drawTri(style, [A, p4, p1], [abcd[e[0]], -1, -1]) || result;
                    result = drawTri(style, [B, p2, p3], [abcd[e[1]], -1, -1]) || result;
                } else {
                    result = drawQuad(null, [p1, p2, p3, p4], [-1, -1, -1, -1]) || result;
                }

                interpolated = true;
            }
        });
        if(interpolated) return result;

        [
            [0, 1, 2, 3],
            [1, 2, 3, 0],
            [2, 3, 0, 1],
            [3, 0, 1, 2]
        ].forEach(function(e) {
            if(ok[e[0]] && !ok[e[1]] && !ok[e[2]] && !ok[e[3]]) {
                var A = xyzv[e[0]];
                var B = xyzv[e[1]];
                var C = xyzv[e[2]];
                var D = xyzv[e[3]];

                var p1 = calcIntersection(B, A, min, max);
                var p2 = calcIntersection(C, A, min, max);
                var p3 = calcIntersection(D, A, min, max);

                if(drawingSpaceframe) {
                    result = drawTri(style, [A, p1, p2], [abcd[e[0]], -1, -1]) || result;
                    result = drawTri(style, [A, p2, p3], [abcd[e[0]], -1, -1]) || result;
                    result = drawTri(style, [A, p3, p1], [abcd[e[0]], -1, -1]) || result;
                } else {
                    result = drawTri(null, [p1, p2, p3], [-1, -1, -1]) || result;
                }

                interpolated = true;
            }
        });
        return result;
    }

    function addCube(style, p000, p001, p010, p011, p100, p101, p110, p111, min, max) {
        var result = false;

        if(drawingSurface) {
            if(styleIncludes(style, 'A')) {
                result = tryCreateTetra(null, [p000, p001, p010, p100], min, max) || result;
            }
            if(styleIncludes(style, 'B')) {
                result = tryCreateTetra(null, [p001, p010, p011, p111], min, max) || result;
            }
            if(styleIncludes(style, 'C')) {
                result = tryCreateTetra(null, [p001, p100, p101, p111], min, max) || result;
            }
            if(styleIncludes(style, 'D')) {
                result = tryCreateTetra(null, [p010, p100, p110, p111], min, max) || result;
            }
            if(styleIncludes(style, 'E')) {
                result = tryCreateTetra(null, [p001, p010, p100, p111], min, max) || result;
            }
        }

        if(drawingSpaceframe) {
            result = tryCreateTetra(style, [p001, p010, p100, p111], min, max) || result;
        }

        return result;
    }

    function addRect(style, a, b, c, d, min, max, previousResult) {
        return [
            (previousResult[0] === true) ? true :
            tryCreateTri(style, getXYZV([a, b, c]), [a, b, c], min, max),
            (previousResult[1] === true) ? true :
            tryCreateTri(style, getXYZV([c, d, a]), [c, d, a], min, max)
        ];
    }

    function begin2dCell(style, p00, p01, p10, p11, min, max, isEven, previousResult) {
        // used to create caps and/or slices on exact axis points
        if(isEven) {
            return addRect(style, p00, p01, p11, p10, min, max, previousResult);
        } else {
            return addRect(style, p01, p11, p10, p00, min, max, previousResult);
        }
    }

    function beginSection(style, i, j, k, min, max, distRatios) {
        // used to create slices between axis points

        var result = false;
        var A, B, C, D;

        var makeSection = function() {
            result = tryCreateTri(style, [A, B, C], [-1, -1, -1], min, max) || result;
            result = tryCreateTri(style, [C, D, A], [-1, -1, -1], min, max) || result;
        };

        var rX = distRatios[0];
        var rY = distRatios[1];
        var rZ = distRatios[2];

        if(rX) {
            A = getBetween(getXYZV([getIndex(i, j - 0, k - 0)])[0], getXYZV([getIndex(i - 1, j - 0, k - 0)])[0], rX);
            B = getBetween(getXYZV([getIndex(i, j - 0, k - 1)])[0], getXYZV([getIndex(i - 1, j - 0, k - 1)])[0], rX);
            C = getBetween(getXYZV([getIndex(i, j - 1, k - 1)])[0], getXYZV([getIndex(i - 1, j - 1, k - 1)])[0], rX);
            D = getBetween(getXYZV([getIndex(i, j - 1, k - 0)])[0], getXYZV([getIndex(i - 1, j - 1, k - 0)])[0], rX);
            makeSection();
        }

        if(rY) {
            A = getBetween(getXYZV([getIndex(i - 0, j, k - 0)])[0], getXYZV([getIndex(i - 0, j - 1, k - 0)])[0], rY);
            B = getBetween(getXYZV([getIndex(i - 0, j, k - 1)])[0], getXYZV([getIndex(i - 0, j - 1, k - 1)])[0], rY);
            C = getBetween(getXYZV([getIndex(i - 1, j, k - 1)])[0], getXYZV([getIndex(i - 1, j - 1, k - 1)])[0], rY);
            D = getBetween(getXYZV([getIndex(i - 1, j, k - 0)])[0], getXYZV([getIndex(i - 1, j - 1, k - 0)])[0], rY);
            makeSection();
        }

        if(rZ) {
            A = getBetween(getXYZV([getIndex(i - 0, j - 0, k)])[0], getXYZV([getIndex(i - 0, j - 0, k - 1)])[0], rZ);
            B = getBetween(getXYZV([getIndex(i - 0, j - 1, k)])[0], getXYZV([getIndex(i - 0, j - 1, k - 1)])[0], rZ);
            C = getBetween(getXYZV([getIndex(i - 1, j - 1, k)])[0], getXYZV([getIndex(i - 1, j - 1, k - 1)])[0], rZ);
            D = getBetween(getXYZV([getIndex(i - 1, j - 0, k)])[0], getXYZV([getIndex(i - 1, j - 0, k - 1)])[0], rZ);
            makeSection();
        }

        return result;
    }

    function begin3dCell(style, p000, p001, p010, p011, p100, p101, p110, p111, min, max, isEven) {
        // used to create spaceframe and/or iso-surfaces

        var cellStyle = style;
        if(isEven) {
            if(drawingSurface && style === 'even') cellStyle = null;
            return addCube(cellStyle, p000, p001, p010, p011, p100, p101, p110, p111, min, max);
        } else {
            if(drawingSurface && style === 'odd') cellStyle = null;
            return addCube(cellStyle, p111, p110, p101, p100, p011, p010, p001, p000, min, max);
        }
    }

    function draw2dX(style, items, min, max, previousResult) {
        var result = [];
        var n = 0;
        for(var q = 0; q < items.length; q++) {
            var i = items[q];
            for(var k = 1; k < depth; k++) {
                for(var j = 1; j < height; j++) {
                    result.push(
                        begin2dCell(style,
                            getIndex(i, j - 1, k - 1),
                            getIndex(i, j - 1, k),
                            getIndex(i, j, k - 1),
                            getIndex(i, j, k),
                            min,
                            max,
                            (i + j + k) % 2,
                            (previousResult && previousResult[n]) ? previousResult[n] : []
                        )
                    );
                    n++;
                }
            }
        }
        return result;
    }

    function draw2dY(style, items, min, max, previousResult) {
        var result = [];
        var n = 0;
        for(var q = 0; q < items.length; q++) {
            var j = items[q];
            for(var i = 1; i < width; i++) {
                for(var k = 1; k < depth; k++) {
                    result.push(
                        begin2dCell(style,
                            getIndex(i - 1, j, k - 1),
                            getIndex(i, j, k - 1),
                            getIndex(i - 1, j, k),
                            getIndex(i, j, k),
                            min,
                            max,
                            (i + j + k) % 2,
                            (previousResult && previousResult[n]) ? previousResult[n] : []
                        )
                    );
                    n++;
                }
            }
        }
        return result;
    }

    function draw2dZ(style, items, min, max, previousResult) {
        var result = [];
        var n = 0;
        for(var q = 0; q < items.length; q++) {
            var k = items[q];
            for(var j = 1; j < height; j++) {
                for(var i = 1; i < width; i++) {
                    result.push(
                        begin2dCell(style,
                            getIndex(i - 1, j - 1, k),
                            getIndex(i - 1, j, k),
                            getIndex(i, j - 1, k),
                            getIndex(i, j, k),
                            min,
                            max,
                            (i + j + k) % 2,
                            (previousResult && previousResult[n]) ? previousResult[n] : []
                        )
                    );
                    n++;
                }
            }
        }
        return result;
    }

    function draw3d(style, min, max) {
        for(var k = 1; k < depth; k++) {
            for(var j = 1; j < height; j++) {
                for(var i = 1; i < width; i++) {
                    begin3dCell(style,
                        getIndex(i - 1, j - 1, k - 1),
                        getIndex(i - 1, j - 1, k),
                        getIndex(i - 1, j, k - 1),
                        getIndex(i - 1, j, k),
                        getIndex(i, j - 1, k - 1),
                        getIndex(i, j - 1, k),
                        getIndex(i, j, k - 1),
                        getIndex(i, j, k),
                        min,
                        max,
                        (i + j + k) % 2
                    );
                }
            }
        }
    }

    function drawSpaceframe(style, min, max) {
        drawingSpaceframe = true;
        draw3d(style, min, max);
        drawingSpaceframe = false;
    }

    function drawSurface(style, min, max) {
        drawingSurface = true;
        draw3d(style, min, max);
        drawingSurface = false;
    }

    function drawSectionX(style, items, min, max, distRatios, previousResult) {
        var result = [];
        var n = 0;
        for(var q = 0; q < items.length; q++) {
            var i = items[q];
            for(var k = 1; k < depth; k++) {
                for(var j = 1; j < height; j++) {
                    result.push(
                        beginSection(style, i, j, k, min, max, distRatios[q],
                            (previousResult && previousResult[n]) ? previousResult[n] : []
                        )
                    );
                    n++;
                }
            }
        }
        return result;
    }

    function drawSectionY(style, items, min, max, distRatios, previousResult) {
        var result = [];
        var n = 0;
        for(var q = 0; q < items.length; q++) {
            var j = items[q];
            for(var i = 1; i < width; i++) {
                for(var k = 1; k < depth; k++) {
                    result.push(
                        beginSection(style, i, j, k, min, max, distRatios[q],
                            (previousResult && previousResult[n]) ? previousResult[n] : []
                        )
                    );
                    n++;
                }
            }
        }
        return result;
    }

    function drawSectionZ(style, items, min, max, distRatios, previousResult) {
        var result = [];
        var n = 0;
        for(var q = 0; q < items.length; q++) {
            var k = items[q];
            for(var j = 1; j < height; j++) {
                for(var i = 1; i < width; i++) {
                    result.push(
                        beginSection(style, i, j, k, min, max, distRatios[q],
                            (previousResult && previousResult[n]) ? previousResult[n] : []
                        )
                    );
                    n++;
                }
            }
        }
        return result;
    }

    function createRange(a, b) {
        var range = [];
        for(var q = a; q < b; q++) {
            range.push(q);
        }
        return range;
    }

    function insertGridPoints() {
        for(var i = 0; i < width; i++) {
            for(var j = 0; j < height; j++) {
                for(var k = 0; k < depth; k++) {
                    var index = getIndex(i, j, k);
                    addVertex(
                        data.x[index],
                        data.y[index],
                        data.z[index],
                        data.value[index]
                    );
                }
            }
        }
    }

    function drawAll() {

        emptyVertices();

        // insert grid points
        insertGridPoints();

        var activeStyle = null;

        // draw spaceframes
        if(showSpaceframe && spaceframeFill) {
            setFill(spaceframeFill);

            drawSpaceframe(activeStyle, vMin, vMax);
        }

        // draw iso-surfaces
        if(showSurface && surfaceFill) {
            setFill(surfaceFill);

            var surfacePattern = data.surface.pattern;
            var surfaceCount = data.surface.count;
            for(var q = 0; q < surfaceCount; q++) {
                var ratio = (surfaceCount === 1) ? 0.5 : q / (surfaceCount - 1);
                var level = (1 - ratio) * vMin + ratio * vMax;

                var d1 = Math.abs(level - minValues);
                var d2 = Math.abs(level - maxValues);
                var ranges = (d1 > d2) ?
                    [minValues, level] :
                    [level, maxValues];

                drawSurface(surfacePattern, ranges[0], ranges[1]);
            }
        }

        var setupMinMax = [
            [ Math.min(vMin, maxValues), Math.max(vMin, maxValues) ],
            [ Math.min(minValues, vMax), Math.max(minValues, vMax) ]
        ];

        ['x', 'y', 'z'].forEach(function(e) {
            var preRes = [];
            for(var s = 0; s < setupMinMax.length; s++) {
                var count = 0;

                var activeMin = setupMinMax[s][0];
                var activeMax = setupMinMax[s][1];

                // draw slices
                var slice = data.slices[e];
                if(slice.show && slice.fill) {
                    setFill(slice.fill);

                    var exactIndices = [];
                    var ceilIndices = [];
                    var distRatios = [];
                    if(slice.locations.length) {

                        for(var q = 0; q < slice.locations.length; q++) {

                            var near = findNearestOnAxis(
                                slice.locations[q],
                                (e === 'x') ? Xs :
                                (e === 'y') ? Ys : Zs
                            );

                            if(near.distRatio === 0) {
                                exactIndices.push(near.id);
                            } else if(near.id > 0) {
                                ceilIndices.push(near.id);
                                if(e === 'x') {
                                    distRatios.push([near.distRatio, 0, 0]);
                                } else if(e === 'y') {
                                    distRatios.push([0, near.distRatio, 0]);
                                } else {
                                    distRatios.push([0, 0, near.distRatio]);
                                }
                            }
                        }
                    } else {
                        if(e === 'x') {
                            exactIndices = createRange(1, width - 1);
                        } else if(e === 'y') {
                            exactIndices = createRange(1, height - 1);
                        } else {
                            exactIndices = createRange(1, depth - 1);
                        }
                    }

                    if(ceilIndices.length > 0) {
                        if(e === 'x') {
                            preRes[count] = drawSectionX(activeStyle, ceilIndices, activeMin, activeMax, distRatios, preRes[count]);
                        } else if(e === 'y') {
                            preRes[count] = drawSectionY(activeStyle, ceilIndices, activeMin, activeMax, distRatios, preRes[count]);
                        } else {
                            preRes[count] = drawSectionZ(activeStyle, ceilIndices, activeMin, activeMax, distRatios, preRes[count]);
                        }
                        count++;
                    }

                    if(exactIndices.length > 0) {
                        if(e === 'x') {
                            preRes[count] = draw2dX(activeStyle, exactIndices, activeMin, activeMax, preRes[count]);
                        } else if(e === 'y') {
                            preRes[count] = draw2dY(activeStyle, exactIndices, activeMin, activeMax, preRes[count]);
                        } else {
                            preRes[count] = draw2dZ(activeStyle, exactIndices, activeMin, activeMax, preRes[count]);
                        }
                        count++;
                    }
                }

                // draw caps
                var cap = data.caps[e];
                if(cap.show && cap.fill) {
                    setFill(cap.fill);
                    if(e === 'x') {
                        preRes[count] = draw2dX(activeStyle, [0, width - 1], activeMin, activeMax, preRes[count]);
                    } else if(e === 'y') {
                        preRes[count] = draw2dY(activeStyle, [0, height - 1], activeMin, activeMax, preRes[count]);
                    } else {
                        preRes[count] = draw2dZ(activeStyle, [0, depth - 1], activeMin, activeMax, preRes[count]);
                    }
                    count++;
                }
            }
        });

        // remove vertices arrays (i.e. grid points) in case no face was created.
        if(numFaces === 0) {
            emptyVertices();
        }

        data._x = allXs;
        data._y = allYs;
        data._z = allZs;
        data._intensity = allVs;

        data._Xs = Xs;
        data._Ys = Ys;
        data._Zs = Zs;
    }

    drawAll();

    return data;
}

function createIsosurfaceTrace(scene, data) {

    var gl = scene.glplot.gl;
    var mesh = createMesh({gl: gl});
    var result = new IsosurfaceTrace(scene, mesh, data.uid);

    mesh._trace = result;
    result.update(data);
    scene.glplot.add(mesh);
    return result;
}

module.exports = createIsosurfaceTrace;

},{"../../lib":697,"../../lib/gl_format_color":694,"../../lib/str2rgbarray":720,"../../plots/gl3d/zip3":797,"gl-mesh3d":273}],989:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var isomin = coerce('isomin');
    var isomax = coerce('isomax');

    if(isomax !== undefined && isomax !== null &&
        isomin !== undefined && isomin !== null &&
         isomin > isomax) {
        // applying default values in this case:
        traceOut.isomin = null;
        traceOut.isomax = null;
    }

    var x = coerce('x');
    var y = coerce('y');
    var z = coerce('z');
    var value = coerce('value');

    if(
        !x || !x.length ||
        !y || !y.length ||
        !z || !z.length ||
        !value || !value.length
    ) {
        traceOut.visible = false;
        return;
    }

    var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
    handleCalendarDefaults(traceIn, traceOut, ['x', 'y', 'z'], layout);

    ['x', 'y', 'z'].forEach(function(dim) {

        var capDim = 'caps.' + dim;
        var showCap = coerce(capDim + '.show');
        if(showCap) {
            coerce(capDim + '.fill');
        }

        var sliceDim = 'slices.' + dim;
        var showSlice = coerce(sliceDim + '.show');
        if(showSlice) {
            coerce(sliceDim + '.fill');
            coerce(sliceDim + '.locations');
        }
    });

    var showSpaceframe = coerce('spaceframe.show');
    if(showSpaceframe) {
        coerce('spaceframe.fill');
    }

    var showSurface = coerce('surface.show');
    if(showSurface) {
        coerce('surface.count');
        coerce('surface.fill');
        coerce('surface.pattern');
    }

    var showContour = coerce('contour.show');
    if(showContour) {
        coerce('contour.color');
        coerce('contour.width');
    }

    // Coerce remaining properties
    [
        'text',
        'hovertext',
        'hovertemplate',
        'lighting.ambient',
        'lighting.diffuse',
        'lighting.specular',
        'lighting.roughness',
        'lighting.fresnel',
        'lighting.vertexnormalsepsilon',
        'lighting.facenormalsepsilon',
        'lightposition.x',
        'lightposition.y',
        'lightposition.z',
        'flatshading',
        'opacity'
    ].forEach(function(x) { coerce(x); });

    colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'c'});

    // disable 1D transforms (for now)
    traceOut._length = null;
};

},{"../../components/colorscale/defaults":584,"../../lib":697,"../../registry":826,"./attributes":986}],990:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Isosurface = {};

Isosurface.attributes = _dereq_('./attributes');
Isosurface.supplyDefaults = _dereq_('./defaults');
Isosurface.calc = _dereq_('./calc');
Isosurface.colorbar = {
    min: 'cmin',
    max: 'cmax'
};
Isosurface.plot = _dereq_('./convert');

Isosurface.moduleType = 'trace';
Isosurface.name = 'isosurface',
Isosurface.basePlotModule = _dereq_('../../plots/gl3d');
Isosurface.categories = ['gl3d'];
Isosurface.meta = {
    
};

module.exports = Isosurface;

},{"../../plots/gl3d":786,"./attributes":986,"./calc":987,"./convert":988,"./defaults":989}],991:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var surfaceAtts = _dereq_('../surface/attributes');
var baseAttrs = _dereq_('../../plots/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;

module.exports = extendFlat({
    x: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },
    y: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },
    z: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },

    i: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    j: {
        valType: 'data_array',
        editType: 'calc',
        

    },
    k: {
        valType: 'data_array',
        editType: 'calc',
        

    },

    text: {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        editType: 'calc',
        
    },
    hovertext: {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        editType: 'calc',
        
    },
    hovertemplate: hovertemplateAttrs({editType: 'calc'}),

    delaunayaxis: {
        valType: 'enumerated',
        
        values: [ 'x', 'y', 'z' ],
        dflt: 'z',
        editType: 'calc',
        
    },

    alphahull: {
        valType: 'number',
        
        dflt: -1,
        editType: 'calc',
        
    },

    intensity: {
        valType: 'data_array',
        editType: 'calc',
        
    },

    // Color field
    color: {
        valType: 'color',
        
        editType: 'calc',
        
    },
    vertexcolor: {
        valType: 'data_array',
        
        editType: 'calc',
        
    },
    facecolor: {
        valType: 'data_array',
        
        editType: 'calc',
        
    },
    transforms: undefined
},

colorscaleAttrs('', {
    colorAttr: '`intensity`',
    showScaleDflt: true,
    editTypeOverride: 'calc'
}), {

    colorbar: colorbarAttrs,

    opacity: surfaceAtts.opacity,

    // Flat shaded mode
    flatshading: {
        valType: 'boolean',
        
        dflt: false,
        editType: 'calc',
        
    },

    contour: {
        show: extendFlat({}, surfaceAtts.contours.x.show, {
            
        }),
        color: surfaceAtts.contours.x.color,
        width: surfaceAtts.contours.x.width,
        editType: 'calc'
    },

    lightposition: {
        x: extendFlat({}, surfaceAtts.lightposition.x, {dflt: 1e5}),
        y: extendFlat({}, surfaceAtts.lightposition.y, {dflt: 1e5}),
        z: extendFlat({}, surfaceAtts.lightposition.z, {dflt: 0}),
        editType: 'calc'
    },
    lighting: extendFlat({
        vertexnormalsepsilon: {
            valType: 'number',
            
            min: 0.00,
            max: 1,
            dflt: 1e-12, // otherwise finely tessellated things eg. the brain will have no specular light reflection
            editType: 'calc',
            
        },
        facenormalsepsilon: {
            valType: 'number',
            
            min: 0.00,
            max: 1,
            dflt: 1e-6, // even the brain model doesn't appear to need finer than this
            editType: 'calc',
            
        },
        editType: 'calc'
    }, surfaceAtts.lighting),

    hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {editType: 'calc'})
});

},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plots/attributes":742,"../surface/attributes":1135}],992:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorscaleCalc = _dereq_('../../components/colorscale/calc');

module.exports = function calc(gd, trace) {
    if(trace.intensity) {
        colorscaleCalc(gd, trace, {
            vals: trace.intensity,
            containerStr: '',
            cLetter: 'c'
        });
    }
};

},{"../../components/colorscale/calc":582}],993:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var createMesh = _dereq_('gl-mesh3d');
var triangulate = _dereq_('delaunay-triangulate');
var alphaShape = _dereq_('alpha-shape');
var convexHull = _dereq_('convex-hull');

var parseColorScale = _dereq_('../../lib/gl_format_color').parseColorScale;
var str2RgbaArray = _dereq_('../../lib/str2rgbarray');
var zip3 = _dereq_('../../plots/gl3d/zip3');

function Mesh3DTrace(scene, mesh, uid) {
    this.scene = scene;
    this.uid = uid;
    this.mesh = mesh;
    this.name = '';
    this.color = '#fff';
    this.data = null;
    this.showContour = false;
}

var proto = Mesh3DTrace.prototype;

proto.handlePick = function(selection) {
    if(selection.object === this.mesh) {
        var selectIndex = selection.index = selection.data.index;

        selection.traceCoordinate = [
            this.data.x[selectIndex],
            this.data.y[selectIndex],
            this.data.z[selectIndex]
        ];

        var text = this.data.hovertext || this.data.text;
        if(Array.isArray(text) && text[selectIndex] !== undefined) {
            selection.textLabel = text[selectIndex];
        } else if(text) {
            selection.textLabel = text;
        }

        return true;
    }
};

function parseColorArray(colors) {
    var b = [];
    var len = colors.length;
    for(var i = 0; i < len; i++) {
        b[i] = str2RgbaArray(colors[i]);
    }
    return b;
}

// Unpack position data
function toDataCoords(axis, coord, scale, calendar) {
    var b = [];
    var len = coord.length;
    for(var i = 0; i < len; i++) {
        b[i] = axis.d2l(coord[i], 0, calendar) * scale;
    }
    return b;
}

// Round indices if passed as floats
function toRoundIndex(a) {
    var b = [];
    var len = a.length;
    for(var i = 0; i < len; i++) {
        b[i] = Math.round(a[i]);
    }
    return b;
}

function delaunayCells(delaunayaxis, positions) {
    var d = ['x', 'y', 'z'].indexOf(delaunayaxis);
    var b = [];
    var len = positions.length;
    for(var i = 0; i < len; i++) {
        b[i] = [positions[i][(d + 1) % 3], positions[i][(d + 2) % 3]];
    }
    return triangulate(b);
}

// Validate indices
function hasValidIndices(list, numVertices) {
    var len = list.length;
    for(var i = 0; i < len; i++) {
        if(list[i] <= -0.5 || list[i] >= numVertices - 0.5) { // Note: the indices would be rounded -0.49 is valid.
            return false;
        }
    }
    return true;
}

proto.update = function(data) {
    var scene = this.scene;
    var layout = scene.fullSceneLayout;

    this.data = data;

    var numVertices = data.x.length;

    var positions = zip3(
        toDataCoords(layout.xaxis, data.x, scene.dataScale[0], data.xcalendar),
        toDataCoords(layout.yaxis, data.y, scene.dataScale[1], data.ycalendar),
        toDataCoords(layout.zaxis, data.z, scene.dataScale[2], data.zcalendar)
    );

    var cells;
    if(data.i && data.j && data.k) {

        if(
            data.i.length !== data.j.length ||
            data.j.length !== data.k.length ||
            !hasValidIndices(data.i, numVertices) ||
            !hasValidIndices(data.j, numVertices) ||
            !hasValidIndices(data.k, numVertices)
        ) {
            return;
        }
        cells = zip3(
            toRoundIndex(data.i),
            toRoundIndex(data.j),
            toRoundIndex(data.k)
        );
    } else if(data.alphahull === 0) {
        cells = convexHull(positions);
    } else if(data.alphahull > 0) {
        cells = alphaShape(data.alphahull, positions);
    } else {
        cells = delaunayCells(data.delaunayaxis, positions);
    }

    var config = {
        positions: positions,
        cells: cells,
        lightPosition: [data.lightposition.x, data.lightposition.y, data.lightposition.z],
        ambient: data.lighting.ambient,
        diffuse: data.lighting.diffuse,
        specular: data.lighting.specular,
        roughness: data.lighting.roughness,
        fresnel: data.lighting.fresnel,
        vertexNormalsEpsilon: data.lighting.vertexnormalsepsilon,
        faceNormalsEpsilon: data.lighting.facenormalsepsilon,
        opacity: data.opacity,
        contourEnable: data.contour.show,
        contourColor: str2RgbaArray(data.contour.color).slice(0, 3),
        contourWidth: data.contour.width,
        useFacetNormals: data.flatshading
    };

    if(data.intensity) {
        this.color = '#fff';
        config.vertexIntensity = data.intensity;
        config.vertexIntensityBounds = [data.cmin, data.cmax];
        config.colormap = parseColorScale(data);
    } else if(data.vertexcolor) {
        this.color = data.vertexcolor[0];
        config.vertexColors = parseColorArray(data.vertexcolor);
    } else if(data.facecolor) {
        this.color = data.facecolor[0];
        config.cellColors = parseColorArray(data.facecolor);
    } else {
        this.color = data.color;
        config.meshColor = str2RgbaArray(data.color);
    }

    // Update mesh
    this.mesh.update(config);
};

proto.dispose = function() {
    this.scene.glplot.remove(this.mesh);
    this.mesh.dispose();
};

function createMesh3DTrace(scene, data) {
    var gl = scene.glplot.gl;
    var mesh = createMesh({gl: gl});
    var result = new Mesh3DTrace(scene, mesh, data.uid);
    mesh._trace = result;
    result.update(data);
    scene.glplot.add(mesh);
    return result;
}

module.exports = createMesh3DTrace;

},{"../../lib/gl_format_color":694,"../../lib/str2rgbarray":720,"../../plots/gl3d/zip3":797,"alpha-shape":52,"convex-hull":118,"delaunay-triangulate":153,"gl-mesh3d":273}],994:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    // read in face/vertex properties
    function readComponents(array) {
        var ret = array.map(function(attr) {
            var result = coerce(attr);

            if(result && Lib.isArrayOrTypedArray(result)) return result;
            return null;
        });

        return ret.every(function(x) {
            return x && x.length === ret[0].length;
        }) && ret;
    }

    var coords = readComponents(['x', 'y', 'z']);
    if(!coords) {
        traceOut.visible = false;
        return;
    }

    readComponents(['i', 'j', 'k']);
    // three indices should be all provided or not
    if(
        (traceOut.i && (!traceOut.j || !traceOut.k)) ||
        (traceOut.j && (!traceOut.k || !traceOut.i)) ||
        (traceOut.k && (!traceOut.i || !traceOut.j))
    ) {
        traceOut.visible = false;
        return;
    }

    var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
    handleCalendarDefaults(traceIn, traceOut, ['x', 'y', 'z'], layout);

    // Coerce remaining properties
    [
        'lighting.ambient',
        'lighting.diffuse',
        'lighting.specular',
        'lighting.roughness',
        'lighting.fresnel',
        'lighting.vertexnormalsepsilon',
        'lighting.facenormalsepsilon',
        'lightposition.x',
        'lightposition.y',
        'lightposition.z',
        'contour.show',
        'contour.color',
        'contour.width',
        'colorscale',
        'reversescale',
        'flatshading',
        'alphahull',
        'delaunayaxis',
        'opacity'
    ].forEach(function(x) { coerce(x); });

    if('intensity' in traceIn) {
        coerce('intensity');
        colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'c'});
    } else {
        traceOut.showscale = false;

        if('facecolor' in traceIn) coerce('facecolor');
        else if('vertexcolor' in traceIn) coerce('vertexcolor');
        else coerce('color', defaultColor);
    }

    coerce('text');
    coerce('hovertext');
    coerce('hovertemplate');

    // disable 1D transforms
    // x/y/z should match lengths, and i/j/k should match as well, but
    // the two sets have different lengths so transforms wouldn't work.
    traceOut._length = null;
};

},{"../../components/colorscale/defaults":584,"../../lib":697,"../../registry":826,"./attributes":991}],995:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Mesh3D = {};

Mesh3D.attributes = _dereq_('./attributes');
Mesh3D.supplyDefaults = _dereq_('./defaults');
Mesh3D.calc = _dereq_('./calc');
Mesh3D.colorbar = {
    min: 'cmin',
    max: 'cmax'
};
Mesh3D.plot = _dereq_('./convert');

Mesh3D.moduleType = 'trace';
Mesh3D.name = 'mesh3d',
Mesh3D.basePlotModule = _dereq_('../../plots/gl3d');
Mesh3D.categories = ['gl3d'];
Mesh3D.meta = {
    
};

module.exports = Mesh3D;

},{"../../plots/gl3d":786,"./attributes":991,"./calc":992,"./convert":993,"./defaults":994}],996:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var extendFlat = _dereq_('../../lib').extendFlat;
var scatterAttrs = _dereq_('../scatter/attributes');
var dash = _dereq_('../../components/drawing/attributes').dash;
var fxAttrs = _dereq_('../../components/fx/attributes');

var INCREASING_COLOR = '#3D9970';
var DECREASING_COLOR = '#FF4136';

var lineAttrs = scatterAttrs.line;

function directionAttrs(lineColorDefault) {
    return {
        line: {
            color: extendFlat({}, lineAttrs.color, {dflt: lineColorDefault}),
            width: lineAttrs.width,
            dash: dash,
            editType: 'style'
        },
        editType: 'style'
    };
}

module.exports = {

    x: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },

    open: {
        valType: 'data_array',
        editType: 'calc',
        
    },

    high: {
        valType: 'data_array',
        editType: 'calc',
        
    },

    low: {
        valType: 'data_array',
        editType: 'calc',
        
    },

    close: {
        valType: 'data_array',
        editType: 'calc',
        
    },

    line: {
        width: extendFlat({}, lineAttrs.width, {
            
        }),
        dash: extendFlat({}, dash, {
            
        }),
        editType: 'style'
    },

    increasing: directionAttrs(INCREASING_COLOR),

    decreasing: directionAttrs(DECREASING_COLOR),

    text: {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        editType: 'calc',
        
    },
    hovertext: {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        editType: 'calc',
        
    },

    tickwidth: {
        valType: 'number',
        min: 0,
        max: 0.5,
        dflt: 0.3,
        
        editType: 'calc',
        
    },

    hoverlabel: extendFlat({}, fxAttrs.hoverlabel, {
        split: {
            valType: 'boolean',
            
            dflt: false,
            editType: 'style',
            
        }
    }),
};

},{"../../components/drawing/attributes":594,"../../components/fx/attributes":604,"../../lib":697,"../scatter/attributes":1048}],997:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var _ = Lib._;
var Axes = _dereq_('../../plots/cartesian/axes');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

function calc(gd, trace) {
    var xa = Axes.getFromId(gd, trace.xaxis);
    var ya = Axes.getFromId(gd, trace.yaxis);

    var tickLen = convertTickWidth(gd, xa, trace);
    var minDiff = trace._minDiff;
    trace._minDiff = null;
    var x = trace._xcalc;
    trace._xcalc = null;

    var cd = calcCommon(gd, trace, x, ya, ptFunc);

    trace._extremes[xa._id] = Axes.findExtremes(xa, x, {vpad: minDiff / 2});
    if(cd.length) {
        Lib.extendFlat(cd[0].t, {
            wHover: minDiff / 2,
            tickLen: tickLen
        });
        return cd;
    } else {
        return [{t: {empty: true}}];
    }
}

function ptFunc(o, h, l, c) {
    return {
        o: o,
        h: h,
        l: l,
        c: c
    };
}


// shared between OHLC and candlestick
// ptFunc makes a calcdata point specific to each trace type, from oi, hi, li, ci
function calcCommon(gd, trace, x, ya, ptFunc) {
    var o = ya.makeCalcdata(trace, 'open');
    var h = ya.makeCalcdata(trace, 'high');
    var l = ya.makeCalcdata(trace, 'low');
    var c = ya.makeCalcdata(trace, 'close');

    var hasTextArray = Array.isArray(trace.text);
    var hasHovertextArray = Array.isArray(trace.hovertext);

    // we're optimists - before we have any changing data, assume increasing
    var increasing = true;
    var cPrev = null;

    var cd = [];
    for(var i = 0; i < x.length; i++) {
        var xi = x[i];
        var oi = o[i];
        var hi = h[i];
        var li = l[i];
        var ci = c[i];

        if(xi !== BADNUM && oi !== BADNUM && hi !== BADNUM && li !== BADNUM && ci !== BADNUM) {
            if(ci === oi) {
                // if open == close, look for a change from the previous close
                if(cPrev !== null && ci !== cPrev) increasing = ci > cPrev;
                // else (c === cPrev or cPrev is null) no change
            }
            else increasing = ci > oi;

            cPrev = ci;

            var pt = ptFunc(oi, hi, li, ci);

            pt.pos = xi;
            pt.yc = (oi + ci) / 2;
            pt.i = i;
            pt.dir = increasing ? 'increasing' : 'decreasing';

            if(hasTextArray) pt.tx = trace.text[i];
            if(hasHovertextArray) pt.htx = trace.hovertext[i];

            cd.push(pt);
        } else {
            cd.push({pos: xi, empty: true});
        }
    }

    trace._extremes[ya._id] = Axes.findExtremes(ya, Lib.concat(l, h), {padded: true});

    if(cd.length) {
        cd[0].t = {
            labels: {
                open: _(gd, 'open:') + ' ',
                high: _(gd, 'high:') + ' ',
                low: _(gd, 'low:') + ' ',
                close: _(gd, 'close:') + ' '
            }
        };
    }

    return cd;
}

/*
 * find min x-coordinates difference of all traces
 * attached to this x-axis and stash the result in _minDiff
 * in all traces; when a trace uses this in its
 * calc step it deletes _minDiff, so that next calc this is
 * done again in case the data changed.
 * also since we need it here, stash _xcalc on the trace
 */
function convertTickWidth(gd, xa, trace) {
    var minDiff = trace._minDiff;

    if(!minDiff) {
        var fullData = gd._fullData;
        var ohlcTracesOnThisXaxis = [];

        minDiff = Infinity;

        var i;

        for(i = 0; i < fullData.length; i++) {
            var tracei = fullData[i];

            if(tracei.type === 'ohlc' &&
                tracei.visible === true &&
                tracei.xaxis === xa._id
            ) {
                ohlcTracesOnThisXaxis.push(tracei);

                var xcalc = xa.makeCalcdata(tracei, 'x');
                tracei._xcalc = xcalc;

                var _minDiff = Lib.distinctVals(xcalc).minDiff;
                if(_minDiff && isFinite(_minDiff)) {
                    minDiff = Math.min(minDiff, _minDiff);
                }
            }
        }

        // if minDiff is still Infinity here, set it to 1
        if(minDiff === Infinity) minDiff = 1;

        for(i = 0; i < ohlcTracesOnThisXaxis.length; i++) {
            ohlcTracesOnThisXaxis[i]._minDiff = minDiff;
        }
    }

    return minDiff * trace.tickwidth;
}

module.exports = {
    calc: calc,
    calcCommon: calcCommon
};

},{"../../constants/numerical":674,"../../lib":697,"../../plots/cartesian/axes":745}],998:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var handleOHLC = _dereq_('./ohlc_defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var len = handleOHLC(traceIn, traceOut, coerce, layout);
    if(!len) {
        traceOut.visible = false;
        return;
    }

    coerce('line.width');
    coerce('line.dash');

    handleDirection(traceIn, traceOut, coerce, 'increasing');
    handleDirection(traceIn, traceOut, coerce, 'decreasing');

    coerce('text');
    coerce('hovertext');
    coerce('tickwidth');

    layout._requestRangeslider[traceOut.xaxis] = true;
};

function handleDirection(traceIn, traceOut, coerce, direction) {
    coerce(direction + '.line.color');
    coerce(direction + '.line.width', traceOut.line.width);
    coerce(direction + '.line.dash', traceOut.line.dash);
}

},{"../../lib":697,"./attributes":996,"./ohlc_defaults":1001}],999:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Axes = _dereq_('../../plots/cartesian/axes');
var Lib = _dereq_('../../lib');
var Fx = _dereq_('../../components/fx');
var Color = _dereq_('../../components/color');
var fillHoverText = _dereq_('../scatter/fill_hover_text');

var DIRSYMBOL = {
    increasing: '▲',
    decreasing: '▼'
};

function hoverPoints(pointData, xval, yval, hovermode) {
    var cd = pointData.cd;
    var trace = cd[0].trace;

    if(trace.hoverlabel.split) {
        return hoverSplit(pointData, xval, yval, hovermode);
    }

    return hoverOnPoints(pointData, xval, yval, hovermode);
}

function getClosestPoint(pointData, xval, yval, hovermode) {
    var cd = pointData.cd;
    var xa = pointData.xa;
    var trace = cd[0].trace;
    var t = cd[0].t;

    var type = trace.type;
    var minAttr = type === 'ohlc' ? 'l' : 'min';
    var maxAttr = type === 'ohlc' ? 'h' : 'max';

    var hoverPseudoDistance, spikePseudoDistance;

    // potentially shift xval for grouped candlesticks
    var centerShift = t.bPos || 0;
    var shiftPos = function(di) { return di.pos + centerShift - xval; };

    // ohlc and candlestick call displayHalfWidth different things...
    var displayHalfWidth = t.bdPos || t.tickLen;
    var hoverHalfWidth = t.wHover;

    // if two figures are overlaying, let the narrowest one win
    var pseudoDistance = Math.min(1, displayHalfWidth / Math.abs(xa.r2c(xa.range[1]) - xa.r2c(xa.range[0])));
    hoverPseudoDistance = pointData.maxHoverDistance - pseudoDistance;
    spikePseudoDistance = pointData.maxSpikeDistance - pseudoDistance;

    function dx(di) {
        var pos = shiftPos(di);
        return Fx.inbox(pos - hoverHalfWidth, pos + hoverHalfWidth, hoverPseudoDistance);
    }

    function dy(di) {
        var min = di[minAttr];
        var max = di[maxAttr];
        return min === max || Fx.inbox(min - yval, max - yval, hoverPseudoDistance);
    }

    function dxy(di) { return (dx(di) + dy(di)) / 2; }

    var distfn = Fx.getDistanceFunction(hovermode, dx, dy, dxy);
    Fx.getClosest(cd, distfn, pointData);

    if(pointData.index === false) return null;

    var di = cd[pointData.index];

    if(di.empty) return null;

    var dir = di.dir;
    var container = trace[dir];
    var lc = container.line.color;

    if(Color.opacity(lc) && container.line.width) pointData.color = lc;
    else pointData.color = container.fillcolor;

    pointData.x0 = xa.c2p(di.pos + centerShift - displayHalfWidth, true);
    pointData.x1 = xa.c2p(di.pos + centerShift + displayHalfWidth, true);

    pointData.xLabelVal = di.pos;

    pointData.spikeDistance = dxy(di) * spikePseudoDistance / hoverPseudoDistance;
    pointData.xSpike = xa.c2p(di.pos, true);

    return pointData;
}

function hoverSplit(pointData, xval, yval, hovermode) {
    var cd = pointData.cd;
    var ya = pointData.ya;
    var trace = cd[0].trace;
    var t = cd[0].t;
    var closeBoxData = [];

    var closestPoint = getClosestPoint(pointData, xval, yval, hovermode);
    // skip the rest (for this trace) if we didn't find a close point
    if(!closestPoint) return [];

    var cdIndex = closestPoint.index;
    var di = cd[cdIndex];
    var hoverinfo = di.hi || trace.hoverinfo;
    var hoverParts = hoverinfo.split('+');
    var isAll = hoverinfo === 'all';
    var hasY = isAll || hoverParts.indexOf('y') !== -1;

    // similar to hoverOnPoints, we return nothing
    // if all or y is not present.
    if(!hasY) return [];

    var attrs = ['high', 'open', 'close', 'low'];

    // several attributes can have the same y-coordinate. We will
    // bunch them together in a single text block. For this, we keep
    // a dictionary mapping y-coord -> point data.
    var usedVals = {};

    for(var i = 0; i < attrs.length; i++) {
        var attr = attrs[i];

        var val = trace[attr][closestPoint.index];
        var valPx = ya.c2p(val, true);
        var pointData2;
        if(val in usedVals) {
            pointData2 = usedVals[val];
            pointData2.yLabel += '<br>' + t.labels[attr] + Axes.hoverLabelText(ya, val);
        }
        else {
            // copy out to a new object for each new y-value to label
            pointData2 = Lib.extendFlat({}, closestPoint);

            pointData2.y0 = pointData2.y1 = valPx;
            pointData2.yLabelVal = val;
            pointData2.yLabel = t.labels[attr] + Axes.hoverLabelText(ya, val);

            pointData2.name = '';

            closeBoxData.push(pointData2);
            usedVals[val] = pointData2;
        }
    }

    return closeBoxData;
}

function hoverOnPoints(pointData, xval, yval, hovermode) {
    var cd = pointData.cd;
    var ya = pointData.ya;
    var trace = cd[0].trace;
    var t = cd[0].t;

    var closestPoint = getClosestPoint(pointData, xval, yval, hovermode);
    // skip the rest (for this trace) if we didn't find a close point
    if(!closestPoint) return [];

    // we don't make a calcdata point if we're missing any piece (x/o/h/l/c)
    // so we need to fix the index here to point to the data arrays
    var cdIndex = closestPoint.index;
    var di = cd[cdIndex];
    var i = closestPoint.index = di.i;
    var dir = di.dir;

    function getLabelLine(attr) {
        return t.labels[attr] + Axes.hoverLabelText(ya, trace[attr][i]);
    }

    var hoverinfo = di.hi || trace.hoverinfo;
    var hoverParts = hoverinfo.split('+');
    var isAll = hoverinfo === 'all';
    var hasY = isAll || hoverParts.indexOf('y') !== -1;
    var hasText = isAll || hoverParts.indexOf('text') !== -1;

    var textParts = hasY ? [
        getLabelLine('open'),
        getLabelLine('high'),
        getLabelLine('low'),
        getLabelLine('close') + '  ' + DIRSYMBOL[dir]
    ] : [];
    if(hasText) fillHoverText(di, trace, textParts);

    // don't make .yLabelVal or .text, since we're managing hoverinfo
    // put it all in .extraText
    closestPoint.extraText = textParts.join('<br>');

    // this puts the label *and the spike* at the midpoint of the box, ie
    // halfway between open and close, not between high and low.
    closestPoint.y0 = closestPoint.y1 = ya.c2p(di.yc, true);

    return [closestPoint];
}

module.exports = {
    hoverPoints: hoverPoints,
    hoverSplit: hoverSplit,
    hoverOnPoints: hoverOnPoints
};

},{"../../components/color":574,"../../components/fx":613,"../../lib":697,"../../plots/cartesian/axes":745,"../scatter/fill_hover_text":1056}],1000:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'trace',
    name: 'ohlc',
    basePlotModule: _dereq_('../../plots/cartesian'),
    categories: ['cartesian', 'svg', 'showLegend'],
    meta: {
        
    },

    attributes: _dereq_('./attributes'),
    supplyDefaults: _dereq_('./defaults'),
    calc: _dereq_('./calc').calc,
    plot: _dereq_('./plot'),
    style: _dereq_('./style'),
    hoverPoints: _dereq_('./hover').hoverPoints,
    selectPoints: _dereq_('./select')
};

},{"../../plots/cartesian":756,"./attributes":996,"./calc":997,"./defaults":998,"./hover":999,"./plot":1002,"./select":1003,"./style":1004}],1001:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');

module.exports = function handleOHLC(traceIn, traceOut, coerce, layout) {
    var x = coerce('x');
    var open = coerce('open');
    var high = coerce('high');
    var low = coerce('low');
    var close = coerce('close');

    coerce('hoverlabel.split');

    var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
    handleCalendarDefaults(traceIn, traceOut, ['x'], layout);

    if(!(open && high && low && close)) return;

    var len = Math.min(open.length, high.length, low.length, close.length);
    if(x) len = Math.min(len, Lib.minRowLength(x));
    traceOut._length = len;

    return len;
};

},{"../../lib":697,"../../registry":826}],1002:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Lib = _dereq_('../../lib');

module.exports = function plot(gd, plotinfo, cdOHLC, ohlcLayer) {
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    Lib.makeTraceGroups(ohlcLayer, cdOHLC, 'trace ohlc').each(function(cd) {
        var plotGroup = d3.select(this);
        var cd0 = cd[0];
        var t = cd0.t;
        var trace = cd0.trace;
        if(!plotinfo.isRangePlot) cd0.node3 = plotGroup;

        if(trace.visible !== true || t.empty) {
            plotGroup.remove();
            return;
        }

        var tickLen = t.tickLen;

        var paths = plotGroup.selectAll('path').data(Lib.identity);

        paths.enter().append('path');

        paths.exit().remove();

        paths.attr('d', function(d) {
            if(d.empty) return 'M0,0Z';

            var x = xa.c2p(d.pos, true);
            var xo = xa.c2p(d.pos - tickLen, true);
            var xc = xa.c2p(d.pos + tickLen, true);

            var yo = ya.c2p(d.o, true);
            var yh = ya.c2p(d.h, true);
            var yl = ya.c2p(d.l, true);
            var yc = ya.c2p(d.c, true);

            return 'M' + xo + ',' + yo + 'H' + x +
                'M' + x + ',' + yh + 'V' + yl +
                'M' + xc + ',' + yc + 'H' + x;
        });
    });
};

},{"../../lib":697,"d3":151}],1003:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function selectPoints(searchInfo, selectionTester) {
    var cd = searchInfo.cd;
    var xa = searchInfo.xaxis;
    var ya = searchInfo.yaxis;
    var selection = [];
    var i;
    // for (potentially grouped) candlesticks
    var posOffset = cd[0].t.bPos || 0;

    if(selectionTester === false) {
        // clear selection
        for(i = 0; i < cd.length; i++) {
            cd[i].selected = 0;
        }
    } else {
        for(i = 0; i < cd.length; i++) {
            var di = cd[i];

            if(selectionTester.contains([xa.c2p(di.pos + posOffset), ya.c2p(di.yc)], null, di.i, searchInfo)) {
                selection.push({
                    pointNumber: di.i,
                    x: xa.c2d(di.pos),
                    y: ya.c2d(di.yc)
                });
                di.selected = 1;
            } else {
                di.selected = 0;
            }
        }
    }

    return selection;
};

},{}],1004:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var Drawing = _dereq_('../../components/drawing');
var Color = _dereq_('../../components/color');

module.exports = function style(gd, cd) {
    var s = cd ? cd[0].node3 : d3.select(gd).selectAll('g.ohlclayer').selectAll('g.trace');

    s.style('opacity', function(d) {
        return d[0].trace.opacity;
    });

    s.each(function(d) {
        var trace = d[0].trace;

        d3.select(this).selectAll('path').each(function(di) {
            if(di.empty) return;

            var dirLine = trace[di.dir].line;
            d3.select(this)
                .style('fill', 'none')
                .call(Color.stroke, dirLine.color)
                .call(Drawing.dashLine, dirLine.dash, dirLine.width)
                // TODO: custom selection style for OHLC
                .style('opacity', trace.selectedpoints && !di.selected ? 0.3 : 1);
        });
    });
};

},{"../../components/color":574,"../../components/drawing":595,"d3":151}],1005:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var extendFlat = _dereq_('../../lib/extend').extendFlat;
var plotAttrs = _dereq_('../../plots/attributes');
var fontAttrs = _dereq_('../../plots/font_attributes');
var colorAttributes = _dereq_('../../components/colorscale/attributes');
var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var domainAttrs = _dereq_('../../plots/domain').attributes;
var scatterAttrs = _dereq_('../scatter/attributes');
var scatterLineAttrs = scatterAttrs.line;
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');

var line = extendFlat({
    editType: 'calc'
}, colorAttributes('line', {editType: 'calc'}),
    {
        showscale: scatterLineAttrs.showscale,
        colorbar: colorbarAttrs,
        shape: {
            valType: 'enumerated',
            values: ['linear', 'hspline'],
            dflt: 'linear',
            
            editType: 'plot',
            
        },

        hovertemplate: hovertemplateAttrs({
            editType: 'plot',
            arrayOk: false
        }, {
            keys: ['count', 'probability'],
            
        })
    });

module.exports = {
    domain: domainAttrs({name: 'parcats', trace: true, editType: 'calc'}),

    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
        flags: ['count', 'probability'],
        editType: 'plot',
        arrayOk: false
    }),
    hoveron: {
        valType: 'enumerated',
        values: ['category', 'color', 'dimension'],
        dflt: 'category',
        
        editType: 'plot',
        
    },
    hovertemplate: hovertemplateAttrs({
        editType: 'plot',
        arrayOk: false
    }, {
        keys: [
            'count', 'probability', 'category',
            'categorycount', 'colorcount', 'bandcolorcount'
        ],
        
    }),

    arrangement: {
        valType: 'enumerated',
        values: ['perpendicular', 'freeform', 'fixed'],
        dflt: 'perpendicular',
        
        editType: 'plot',
        
    },
    bundlecolors: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'plot',
        
    },
    sortpaths: {
        valType: 'enumerated',
        values: ['forward', 'backward'],
        dflt: 'forward',
        
        editType: 'plot',
        
    },
    labelfont: fontAttrs({
        editType: 'calc',
        
    }),

    tickfont: fontAttrs({
        editType: 'calc',
        
    }),

    dimensions: {
        _isLinkedToArray: 'dimension',
        label: {
            valType: 'string',
            
            editType: 'calc',
            
        },
        categoryorder: {
            valType: 'enumerated',
            values: [
                'trace', 'category ascending', 'category descending', 'array'
            ],
            dflt: 'trace',
            
            editType: 'calc',
            
        },
        categoryarray: {
            valType: 'data_array',
            
            editType: 'calc',
            
        },
        ticktext: {
            valType: 'data_array',
            
            editType: 'calc',
            
        },
        values: {
            valType: 'data_array',
            
            dflt: [],
            editType: 'calc',
            
        },
        displayindex: {
            valType: 'integer',
            
            editType: 'calc',
            
        },
        editType: 'calc',
        
        visible: {
            valType: 'boolean',
            dflt: true,
            
            editType: 'calc',
            
        }
    },

    line: line,
    counts: {
        valType: 'number',
        min: 0,
        dflt: 1,
        arrayOk: true,
        
        editType: 'calc',
        
    },

    // Hide unsupported top-level properties from plot-schema
    customdata: undefined,
    hoverlabel: undefined,
    ids: undefined,
    legendgroup: undefined,
    opacity: undefined,
    selectedpoints: undefined,
    showlegend: undefined
};

},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plots/attributes":742,"../../plots/domain":770,"../../plots/font_attributes":771,"../scatter/attributes":1048}],1006:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var getModuleCalcData = _dereq_('../../plots/get_data').getModuleCalcData;
var parcatsPlot = _dereq_('./plot');

var PARCATS = 'parcats';
exports.name = PARCATS;

exports.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) {

    var cdModuleAndOthers = getModuleCalcData(gd.calcdata, PARCATS);

    if(cdModuleAndOthers.length) {
        var calcData = cdModuleAndOthers[0];
        parcatsPlot(gd, calcData, transitionOpts, makeOnCompleteCallback);
    }
};

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var hadTable = (oldFullLayout._has && oldFullLayout._has('parcats'));
    var hasTable = (newFullLayout._has && newFullLayout._has('parcats'));

    if(hadTable && !hasTable) {
        oldFullLayout._paperdiv.selectAll('.parcats').remove();
    }
};

},{"../../plots/get_data":781,"./plot":1011}],1007:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// Requirements
// ============
var wrap = _dereq_('../../lib/gup').wrap;
var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
var colorscaleCalc = _dereq_('../../components/colorscale/calc');
var filterUnique = _dereq_('../../lib/filter_unique.js');
var Drawing = _dereq_('../../components/drawing');
var Lib = _dereq_('../../lib');

/**
 * Create a wrapped ParcatsModel object from trace
 *
 * Note: trace defaults have already been applied
 * @param {Object} gd
 * @param {Object} trace
 * @return {Array.<ParcatsModel>}
 */
module.exports = function calc(gd, trace) {
    var visibleDims = Lib.filterVisible(trace.dimensions);

    if(visibleDims.length === 0) return [];

    var uniqueInfoDims = visibleDims.map(function(dim) {
        var categoryValues;
        if(dim.categoryorder === 'trace') {
            // Use order of first occurrence in trace
            categoryValues = null;
        } else if(dim.categoryorder === 'array') {
            // Use categories specified in `categoryarray` first,
            // then add extra to the end in trace order
            categoryValues = dim.categoryarray;
        } else {
            // Get all categories up front so we can order them
            // Should we check for numbers as sort numerically?
            categoryValues = filterUnique(dim.values).sort();
            if(dim.categoryorder === 'category descending') {
                categoryValues = categoryValues.reverse();
            }
        }
        return getUniqueInfo(dim.values, categoryValues);
    });

    var counts,
        count,
        totalCount;
    if(Lib.isArrayOrTypedArray(trace.counts)) {
        counts = trace.counts;
    } else {
        counts = [trace.counts];
    }

    validateDimensionDisplayInds(visibleDims);

    visibleDims.forEach(function(dim, dimInd) {
        validateCategoryProperties(dim, uniqueInfoDims[dimInd]);
    });

    // Handle path colors
    // ------------------
    var line = trace.line;
    var markerColorscale;

    // Process colorscale
    if(line) {
        if(hasColorscale(trace, 'line')) {
            colorscaleCalc(gd, trace, {
                vals: trace.line.color,
                containerStr: 'line',
                cLetter: 'c'
            });
        }
        markerColorscale = Drawing.tryColorscale(line);
    } else {
        markerColorscale = Lib.identity;
    }

    // Build color generation function
    function getMarkerColorInfo(index) {
        var value;
        if(Lib.isArrayOrTypedArray(line.color)) {
            value = line.color[index % line.color.length];
        } else {
            value = line.color;
        }

        return {color: markerColorscale(value), rawColor: value};
    }

    // Number of values and counts
    // ---------------------------
    var numValues = visibleDims[0].values.length;

    // Build path info
    // ---------------
    // Mapping from category inds to PathModel objects
    var pathModels = {};

    // Category inds array for each dimension
    var categoryIndsDims = uniqueInfoDims.map(function(di) {return di.inds;});

    // Initialize total count
    totalCount = 0;
    var valueInd;
    var d;

    for(valueInd = 0; valueInd < numValues; valueInd++) {

        // Category inds for this input value across dimensions
        var categoryIndsPath = [];
        for(d = 0; d < categoryIndsDims.length; d++) {
            categoryIndsPath.push(categoryIndsDims[d][valueInd]);
        }

        // Count
        count = counts[valueInd % counts.length];

        // Update total count
        totalCount += count;

        // Path color
        var pathColorInfo = getMarkerColorInfo(valueInd);

        // path key
        var pathKey = categoryIndsPath + '-' + pathColorInfo.rawColor;

        // Create / Update PathModel
        if(pathModels[pathKey] === undefined) {
            pathModels[pathKey] = createPathModel(categoryIndsPath,
                pathColorInfo.color,
                pathColorInfo.rawColor);
        }
        updatePathModel(pathModels[pathKey], valueInd, count);
    }

    var dimensionModels = visibleDims.map(function(di, i) {
        return createDimensionModel(i, di._index, di._displayindex, di.label, totalCount);
    });


    for(valueInd = 0; valueInd < numValues; valueInd++) {

        count = counts[valueInd % counts.length];

        for(d = 0; d < dimensionModels.length; d++) {
            var containerInd = dimensionModels[d].containerInd;
            var catInd = uniqueInfoDims[d].inds[valueInd];
            var cats = dimensionModels[d].categories;

            if(cats[catInd] === undefined) {
                var catValue = trace.dimensions[containerInd]._categoryarray[catInd];
                var catLabel = trace.dimensions[containerInd]._ticktext[catInd];
                cats[catInd] = createCategoryModel(d, catInd, catValue, catLabel);
            }

            updateCategoryModel(cats[catInd], valueInd, count);
        }
    }

    // Compute unique
    return wrap(createParcatsModel(dimensionModels, pathModels, totalCount));
};

// Models
// ======

// Parcats Model
// -------------
/**
 * @typedef {Object} ParcatsModel
 *  Object containing calculated information about a parcats trace
 *
 * @property {Array.<DimensionModel>} dimensions
 *  Array of dimension models
 * @property {Object.<string,PathModel>} paths
 *  Dictionary from category inds string (e.g. "1,2,1,1") to path model
 * @property {Number} maxCats
 *  The maximum number of categories of any dimension in the diagram
 * @property {Number} count
 *  Total number of input values
 * @property {Object} trace
 */

/**
 * Create and new ParcatsModel object
 * @param {Array.<DimensionModel>} dimensions
 * @param {Object.<string,PathModel>} paths
 * @param {Number} count
 * @return {ParcatsModel}
 */
function createParcatsModel(dimensions, paths, count) {
    var maxCats = dimensions
        .map(function(d) {return d.categories.length;})
        .reduce(function(v1, v2) {return Math.max(v1, v2);});
    return {dimensions: dimensions, paths: paths, trace: undefined, maxCats: maxCats, count: count};
}

// Dimension Model
// ---------------
/**
 * @typedef {Object} DimensionModel
 *  Object containing calculated information about a single dimension
 *
 * @property {Number} dimensionInd
 *  The index of this dimension among the *visible* dimensions
 * @property {Number} containerInd
 *  The index of this dimension in the original dimensions container,
 *  irrespective of dimension visibility
 * @property {Number} displayInd
 *  The display index of this dimension (where 0 is the left most dimension)
 * @property {String} dimensionLabel
 *  The label of this dimension
 * @property {Number} count
 *  Total number of input values
 * @property {Array.<CategoryModel>} categories
 * @property {Number|null} dragX
 *  The x position of dimension that is currently being dragged. null if not being dragged
 */

/**
 * Create and new DimensionModel object with an empty categories array
 * @param {Number} dimensionInd
 * @param {Number} containerInd
 * @param {Number} displayInd
 * @param {String} dimensionLabel
 * @param {Number} count
 *  Total number of input values
 * @return {DimensionModel}
 */
function createDimensionModel(dimensionInd, containerInd, displayInd, dimensionLabel, count) {
    return {
        dimensionInd: dimensionInd,
        containerInd: containerInd,
        displayInd: displayInd,
        dimensionLabel: dimensionLabel,
        count: count,
        categories: [],
        dragX: null
    };
}

// Category Model
// --------------
/**
 * @typedef {Object} CategoryModel
 *  Object containing calculated information about a single category.
 *
 * @property {Number} dimensionInd
 *  The index of this categories dimension
 * @property {Number} categoryInd
 *  The index of this category
 * @property {Number} displayInd
 *  The display index of this category (where 0 is the topmost category)
 * @property {String} categoryLabel
 *  The name of this category
 * @property categoryValue: Raw value of the category
 * @property {Array} valueInds
 *  Array of indices (into the original value array) of all samples in this category
 * @property {Number} count
 *  The number of elements from the original array in this path
 * @property {Number|null} dragY
 *  The y position of category that is currently being dragged. null if not being dragged
 */

/**
 * Create and return a new CategoryModel object
 * @param {Number} dimensionInd
 * @param {Number} categoryInd
 *  The display index of this category (where 0 is the topmost category)
 * @param {String} categoryValue
 * @param {String} categoryLabel
 * @return {CategoryModel}
 */
function createCategoryModel(dimensionInd, categoryInd, categoryValue, categoryLabel) {
    return {
        dimensionInd: dimensionInd,
        categoryInd: categoryInd,
        categoryValue: categoryValue,
        displayInd: categoryInd,
        categoryLabel: categoryLabel,
        valueInds: [],
        count: 0,
        dragY: null
    };
}

/**
 * Update a CategoryModel object with a new value index
 * Note: The calling parameter is modified in place.
 *
 * @param {CategoryModel} categoryModel
 * @param {Number} valueInd
 * @param {Number} count
 */
function updateCategoryModel(categoryModel, valueInd, count) {
    categoryModel.valueInds.push(valueInd);
    categoryModel.count += count;
}


// Path Model
// ----------
/**
 * @typedef {Object} PathModel
 *  Object containing calculated information about the samples in a path.
 *
 * @property {Array} categoryInds
 *  Array of category indices for each dimension (length `numDimensions`)
 * @param {String} pathColor
 *  Color of this path. (Note: Any colorscaling has already taken place)
 * @property {Array} valueInds
 *  Array of indices (into the original value array) of all samples in this path
 * @property {Number} count
 *  The number of elements from the original array in this path
 * @property {String} color
 *  The path's color (ass CSS color string)
 * @property rawColor
 *  The raw color value specified by the user. May be a CSS color string or a Number
 */

/**
 * Create and return a new PathModel object
 * @param {Array} categoryInds
 * @param color
 * @param rawColor
 * @return {PathModel}
 */
function createPathModel(categoryInds, color, rawColor) {
    return {
        categoryInds: categoryInds,
        color: color,
        rawColor: rawColor,
        valueInds: [],
        count: 0
    };
}

/**
 * Update a PathModel object with a new value index
 * Note: The calling parameter is modified in place.
 *
 * @param {PathModel} pathModel
 * @param {Number} valueInd
 * @param {Number} count
 */
function updatePathModel(pathModel, valueInd, count) {
    pathModel.valueInds.push(valueInd);
    pathModel.count += count;
}

// Unique calculations
// ===================
/**
 * @typedef {Object} UniqueInfo
 *  Object containing information about the unique values of an input array
 *
 * @property {Array} uniqueValues
 *  The unique values in the input array
 * @property {Array} uniqueCounts
 *  The number of times each entry in uniqueValues occurs in input array.
 *  This has the same length as `uniqueValues`
 * @property {Array} inds
 *  Indices into uniqueValues that would reproduce original input array
 */

/**
 * Compute unique value information for an array
 *
 * IMPORTANT: Note that values are considered unique
 * if their string representations are unique.
 *
 * @param {Array} values
 * @param {Array|undefined} uniqueValues
 *  Array of expected unique values. The uniqueValues property of the resulting UniqueInfo object will begin with
 *  these entries. Entries are included even if there are zero occurrences in the values array. Entries found in
 *  the values array that are not present in uniqueValues will be included at the end of the array in the
 *  UniqueInfo object.
 * @return {UniqueInfo}
 */
function getUniqueInfo(values, uniqueValues) {

    // Initialize uniqueValues if not specified
    if(uniqueValues === undefined || uniqueValues === null) {
        uniqueValues = [];
    } else {
        // Shallow copy so append below doesn't alter input array
        uniqueValues = uniqueValues.map(function(e) {return e;});
    }

    // Initialize Variables
    var uniqueValueCounts = {};
    var uniqueValueInds = {};
    var inds = [];

    // Initialize uniqueValueCounts and
    uniqueValues.forEach(function(uniqueVal, valInd) {
        uniqueValueCounts[uniqueVal] = 0;
        uniqueValueInds[uniqueVal] = valInd;
    });

    // Compute the necessary unique info in a single pass
    for(var i = 0; i < values.length; i++) {
        var item = values[i];
        var itemInd;

        if(uniqueValueCounts[item] === undefined) {
            // This item has a previously unseen value
            uniqueValueCounts[item] = 1;
            itemInd = uniqueValues.push(item) - 1;
            uniqueValueInds[item] = itemInd;
        } else {
            // Increment count for this item
            uniqueValueCounts[item]++;
            itemInd = uniqueValueInds[item];
        }
        inds.push(itemInd);
    }

    // Build UniqueInfo
    var uniqueCounts = uniqueValues.map(function(v) { return uniqueValueCounts[v]; });

    return {
        uniqueValues: uniqueValues,
        uniqueCounts: uniqueCounts,
        inds: inds
    };
}


/**
 * Validate the requested display order for the dimensions.
 * If the display order is a permutation of 0 through dimensions.length - 1, link to _displayindex
 * Otherwise, replace the display order with the dimension order
 * @param {Object} trace
 */
function validateDimensionDisplayInds(visibleDims) {
    var displayInds = visibleDims.map(function(d) { return d.displayindex; });
    var i;

    if(isRangePermutation(displayInds)) {
        for(i = 0; i < visibleDims.length; i++) {
            visibleDims[i]._displayindex = visibleDims[i].displayindex;
        }
    } else {
        for(i = 0; i < visibleDims.length; i++) {
            visibleDims[i]._displayindex = i;
        }
    }
}


/**
 * Update category properties based on the unique values found for this dimension
 * @param {Object} dim
 * @param {UniqueInfo} uniqueInfoDim
 */
function validateCategoryProperties(dim, uniqueInfoDim) {

    // Update categoryarray
    dim._categoryarray = uniqueInfoDim.uniqueValues;

    // Handle ticktext
    if(dim.ticktext === null || dim.ticktext === undefined) {
        dim._ticktext = [];
    } else {
        // Shallow copy to avoid modifying input array
        dim._ticktext = dim.ticktext.slice();
    }

    // Extend ticktext with elements from uniqueInfoDim.uniqueValues
    for(var i = dim._ticktext.length; i < uniqueInfoDim.uniqueValues.length; i++) {
        dim._ticktext.push(uniqueInfoDim.uniqueValues[i]);
    }
}

/**
 * Determine whether an array contains a permutation of the integers from 0 to the array's length - 1
 * @param {Array} inds
 * @return {boolean}
 */
function isRangePermutation(inds) {
    var indsSpecified = new Array(inds.length);

    for(var i = 0; i < inds.length; i++) {
        // Check for out of bounds
        if(inds[i] < 0 || inds[i] >= inds.length) {
            return false;
        }

        // Check for collisions with already specified index
        if(indsSpecified[inds[i]] !== undefined) {
            return false;
        }

        indsSpecified[inds[i]] = true;
    }

    // Nothing out of bounds and no collisions. We have a permutation
    return true;
}

},{"../../components/colorscale/calc":582,"../../components/colorscale/helpers":585,"../../components/drawing":595,"../../lib":697,"../../lib/filter_unique.js":688,"../../lib/gup":695}],1008:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
var handleDomainDefaults = _dereq_('../../plots/domain').defaults;
var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');

var attributes = _dereq_('./attributes');
var mergeLength = _dereq_('../parcoords/merge_length');

function handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce) {
    coerce('line.shape');
    coerce('line.hovertemplate');

    var lineColor = coerce('line.color', layout.colorway[0]);
    if(hasColorscale(traceIn, 'line') && Lib.isArrayOrTypedArray(lineColor)) {
        if(lineColor.length) {
            coerce('line.colorscale');
            colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'});
            return lineColor.length;
        }
        else {
            traceOut.line.color = defaultColor;
        }
    }
    return Infinity;
}

function dimensionDefaults(dimensionIn, dimensionOut) {
    function coerce(attr, dflt) {
        return Lib.coerce(dimensionIn, dimensionOut, attributes.dimensions, attr, dflt);
    }

    var values = coerce('values');
    var visible = coerce('visible');
    if(!(values && values.length)) {
        visible = dimensionOut.visible = false;
    }

    if(visible) {
        // Dimension level
        coerce('label');
        coerce('displayindex', dimensionOut._index);

        // Category level
        var arrayIn = dimensionIn.categoryarray;
        var isValidArray = (Array.isArray(arrayIn) && arrayIn.length > 0);

        var orderDefault;
        if(isValidArray) orderDefault = 'array';
        var order = coerce('categoryorder', orderDefault);

        // coerce 'categoryarray' only in array order case
        if(order === 'array') {
            coerce('categoryarray');
            coerce('ticktext');
        } else {
            delete dimensionIn.categoryarray;
            delete dimensionIn.ticktext;
        }

        // cannot set 'categoryorder' to 'array' with an invalid 'categoryarray'
        if(!isValidArray && order === 'array') {
            dimensionOut.categoryorder = 'trace';
        }
    }
}

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {

    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var dimensions = handleArrayContainerDefaults(traceIn, traceOut, {
        name: 'dimensions',
        handleItemDefaults: dimensionDefaults
    });

    var len = handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);

    handleDomainDefaults(traceOut, layout, coerce);

    if(!Array.isArray(dimensions) || !dimensions.length) {
        traceOut.visible = false;
    }

    mergeLength(traceOut, dimensions, 'values', len);

    coerce('hoveron');
    coerce('hovertemplate');
    coerce('arrangement');
    coerce('bundlecolors');
    coerce('sortpaths');
    coerce('counts');

    var labelfontDflt = {
        family: layout.font.family,
        size: Math.round(layout.font.size),
        color: layout.font.color
    };

    Lib.coerceFont(coerce, 'labelfont', labelfontDflt);

    var categoryfontDefault = {
        family: layout.font.family,
        size: Math.round(layout.font.size / 1.2),
        color: layout.font.color
    };

    Lib.coerceFont(coerce, 'tickfont', categoryfontDefault);
};

},{"../../components/colorscale/defaults":584,"../../components/colorscale/helpers":585,"../../lib":697,"../../plots/array_container_defaults":741,"../../plots/domain":770,"../parcoords/merge_length":1020,"./attributes":1005}],1009:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Parcats = {};

Parcats.attributes = _dereq_('./attributes');
Parcats.supplyDefaults = _dereq_('./defaults');
Parcats.calc = _dereq_('./calc');
Parcats.plot = _dereq_('./plot');
Parcats.colorbar = {
    container: 'line',
    min: 'cmin',
    max: 'cmax'
};

Parcats.moduleType = 'trace';
Parcats.name = 'parcats';
Parcats.basePlotModule = _dereq_('./base_plot');
Parcats.categories = ['noOpacity'];
Parcats.meta = {
    
};

module.exports = Parcats;

},{"./attributes":1005,"./base_plot":1006,"./calc":1007,"./defaults":1008,"./plot":1011}],1010:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var Plotly = _dereq_('../../plot_api/plot_api');
var Fx = _dereq_('../../components/fx');
var Lib = _dereq_('../../lib');
var Drawing = _dereq_('../../components/drawing');
var tinycolor = _dereq_('tinycolor2');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');

function performPlot(parcatsModels, graphDiv, layout, svg) {

    var viewModels = parcatsModels.map(createParcatsViewModel.bind(0, graphDiv, layout));

    // Get (potentially empty) parcatslayer selection with bound data to single element array
    var layerSelection = svg.selectAll('g.parcatslayer').data([null]);

    // Initialize single parcatslayer group if it doesn't exist
    layerSelection.enter()
        .append('g')
        .attr('class', 'parcatslayer')
        .style('pointer-events', 'all');

    // Bind data to children of layerSelection and get reference to traceSelection
    var traceSelection = layerSelection
        .selectAll('g.trace.parcats')
        .data(viewModels, key);

    // Initialize group for each trace/dimensions
    var traceEnter = traceSelection.enter()
        .append('g')
        .attr('class', 'trace parcats');

    // Update properties for each trace
    traceSelection
        .attr('transform', function(d) {
            return 'translate(' + d.x + ', ' + d.y + ')';
        });

    // Initialize paths group
    traceEnter
        .append('g')
        .attr('class', 'paths');

    // Update paths transform
    var pathsSelection = traceSelection
        .select('g.paths');

    // Get paths selection
    var pathSelection = pathsSelection
        .selectAll('path.path')
        .data(function(d) {
            return d.paths;
        }, key);

    // Update existing path colors
    pathSelection
        .attr('fill', function(d) {
            return d.model.color;
        });

    // Create paths
    var pathSelectionEnter = pathSelection
        .enter()
        .append('path')
        .attr('class', 'path')
        .attr('stroke-opacity', 0)
        .attr('fill', function(d) {
            return d.model.color;
        })
        .attr('fill-opacity', 0);

    stylePathsNoHover(pathSelectionEnter);

    // Set path geometry
    pathSelection
        .attr('d', function(d) {
            return d.svgD;
        });

    // sort paths
    if(!pathSelectionEnter.empty()) {
        // Only sort paths if there has been a change.
        // Otherwise paths are already sorted or a hover operation may be in progress
        pathSelection.sort(compareRawColor);
    }

    // Remove any old paths
    pathSelection.exit().remove();

    // Path hover
    pathSelection
        .on('mouseover', mouseoverPath)
        .on('mouseout', mouseoutPath)
        .on('click', clickPath);

    // Initialize dimensions group
    traceEnter.append('g').attr('class', 'dimensions');

    // Update dimensions transform
    var dimensionsSelection = traceSelection
        .select('g.dimensions');

    // Get dimension selection
    var dimensionSelection = dimensionsSelection
        .selectAll('g.dimension')
        .data(function(d) {
            return d.dimensions;
        }, key);

    // Create dimension groups
    dimensionSelection.enter()
        .append('g')
        .attr('class', 'dimension');

    // Update dimension group transforms
    dimensionSelection.attr('transform', function(d) {
        return 'translate(' + d.x + ', 0)';
    });

    // Remove any old dimensions
    dimensionSelection.exit().remove();

    // Get category selection
    var categorySelection = dimensionSelection
        .selectAll('g.category')
        .data(function(d) {
            return d.categories;
        }, key);

    // Initialize category groups
    var categoryGroupEnterSelection = categorySelection
        .enter()
        .append('g')
        .attr('class', 'category');

    // Update category transforms
    categorySelection
        .attr('transform', function(d) {
            return 'translate(0, ' + d.y + ')';
        });


    // Initialize rectangle
    categoryGroupEnterSelection
        .append('rect')
        .attr('class', 'catrect')
        .attr('pointer-events', 'none');


    // Update rectangle
    categorySelection.select('rect.catrect')
        .attr('fill', 'none')
        .attr('width', function(d) {
            return d.width;
        })
        .attr('height', function(d) {
            return d.height;
        });

    styleCategoriesNoHover(categoryGroupEnterSelection);

    // Initialize color band rects
    var bandSelection = categorySelection
        .selectAll('rect.bandrect')
        .data(
            /** @param {CategoryViewModel} catViewModel*/
            function(catViewModel) {
                return catViewModel.bands;
            }, key);

    // Raise all update bands to the top so that fading enter/exit bands will be behind
    bandSelection.each(function() {Lib.raiseToTop(this);});

    // Update band color
    bandSelection
        .attr('fill', function(d) {
            return d.color;
        });

    var bandsSelectionEnter = bandSelection.enter()
        .append('rect')
        .attr('class', 'bandrect')
        .attr('stroke-opacity', 0)
        .attr('fill', function(d) {
            return d.color;
        })
        .attr('fill-opacity', 0);

    bandSelection
        .attr('fill', function(d) {
            return d.color;
        })
        .attr('width', function(d) {
            return d.width;
        })
        .attr('height', function(d) {
            return d.height;
        })
        .attr('y', function(d) {
            return d.y;
        })
        .attr('cursor',
            /** @param {CategoryBandViewModel} bandModel*/
            function(bandModel) {
                if(bandModel.parcatsViewModel.arrangement === 'fixed') {
                    return 'default';
                } else if(bandModel.parcatsViewModel.arrangement === 'perpendicular') {
                    return 'ns-resize';
                } else {
                    return 'move';
                }
            });

    styleBandsNoHover(bandsSelectionEnter);

    bandSelection.exit().remove();

    // Initialize category label
    categoryGroupEnterSelection
        .append('text')
        .attr('class', 'catlabel')
        .attr('pointer-events', 'none');

    var paperColor = graphDiv._fullLayout.paper_bgcolor;

    // Update category label
    categorySelection.select('text.catlabel')
        .attr('text-anchor',
            function(d) {
                if(catInRightDim(d)) {
                    // Place label to the right of category
                    return 'start';
                } else {
                    // Place label to the left of category
                    return 'end';
                }
            })
        .attr('alignment-baseline', 'middle')

        .style('text-shadow',
            paperColor + ' -1px  1px 2px, ' +
            paperColor + ' 1px  1px 2px, ' +
            paperColor + '  1px -1px 2px, ' +
            paperColor + ' -1px -1px 2px')
        .style('fill', 'rgb(0, 0, 0)')
        .attr('x',
            function(d) {
                if(catInRightDim(d)) {
                    // Place label to the right of category
                    return d.width + 5;
                } else {
                    // Place label to the left of category
                    return -5;
                }
            })
        .attr('y', function(d) {
            return d.height / 2;
        })
        .text(function(d) {
            return d.model.categoryLabel;
        })
        .each(
            /** @param {CategoryViewModel} catModel*/
            function(catModel) {
                Drawing.font(d3.select(this), catModel.parcatsViewModel.categorylabelfont);
                svgTextUtils.convertToTspans(d3.select(this), graphDiv);
            });

    // Initialize dimension label
    categoryGroupEnterSelection
        .append('text')
        .attr('class', 'dimlabel');

    // Update dimension label
    categorySelection.select('text.dimlabel')
        .attr('text-anchor', 'middle')
        .attr('alignment-baseline', 'baseline')
        .attr('cursor',
             /** @param {CategoryViewModel} catModel*/
            function(catModel) {
                if(catModel.parcatsViewModel.arrangement === 'fixed') {
                    return 'default';
                } else {
                    return 'ew-resize';
                }
            })
        .attr('x', function(d) {
            return d.width / 2;
        })
        .attr('y', -5)
        .text(function(d, i) {
            if(i === 0) {
                // Add dimension label above topmost category
                return d.parcatsViewModel.model.dimensions[d.model.dimensionInd].dimensionLabel;
            } else {
                return null;
            }
        })
        .each(
            /** @param {CategoryViewModel} catModel*/
            function(catModel) {
                Drawing.font(d3.select(this), catModel.parcatsViewModel.labelfont);
            });

    // Category hover
    // categorySelection.select('rect.catrect')
    categorySelection.selectAll('rect.bandrect')
        .on('mouseover', mouseoverCategoryBand)
        .on('mouseout', mouseoutCategory);

    // Remove unused categories
    categorySelection.exit().remove();

    // Setup drag
    dimensionSelection.call(d3.behavior.drag()
        .origin(function(d) {
            return {x: d.x, y: 0};
        })
        .on('dragstart', dragDimensionStart)
        .on('drag', dragDimension)
        .on('dragend', dragDimensionEnd));


    // Save off selections to view models
    traceSelection.each(function(d) {
        d.traceSelection = d3.select(this);
        d.pathSelection = d3.select(this).selectAll('g.paths').selectAll('path.path');
        d.dimensionSelection = d3.select(this).selectAll('g.dimensions').selectAll('g.dimension');
    });

    // Remove any orphan traces
    traceSelection.exit().remove();
}

/**
 * Create / update parcat traces
 *
 * @param {Object} graphDiv
 * @param {Object} svg
 * @param {Array.<ParcatsModel>} parcatsModels
 * @param {Layout} layout
 */
module.exports = function(graphDiv, svg, parcatsModels, layout) {
    performPlot(parcatsModels, graphDiv, layout, svg);
};

/**
 * Function the returns the key property of an object for use with as D3 join function
 * @param d
 */
function key(d) {
    return d.key;
}

 /** True if a category view model is in the right-most display dimension
  * @param {CategoryViewModel} d */
function catInRightDim(d) {
    var numDims = d.parcatsViewModel.dimensions.length;
    var leftDimInd = d.parcatsViewModel.dimensions[numDims - 1].model.dimensionInd;
    return d.model.dimensionInd === leftDimInd;
}

/**
 * @param {PathViewModel} a
 * @param {PathViewModel} b
 */
function compareRawColor(a, b) {
    if(a.model.rawColor > b.model.rawColor) {
        return 1;
    } else if(a.model.rawColor < b.model.rawColor) {
        return -1;
    } else {
        return 0;
    }
}

/**
 * Handle path mouseover
 * @param {PathViewModel} d
 */
function mouseoverPath(d) {

    if(!d.parcatsViewModel.dragDimension) {
        // We're not currently dragging

        if(d.parcatsViewModel.hoverinfoItems.indexOf('skip') === -1) {
            // hoverinfo is not skip, so we at least style the paths and emit interaction events

            // Raise path to top
            Lib.raiseToTop(this);

            stylePathsHover(d3.select(this));

            // Emit hover event
            var points = buildPointsArrayForPath(d);
            d.parcatsViewModel.graphDiv.emit('plotly_hover', {points: points, event: d3.event});

            // Handle hover label
            if(d.parcatsViewModel.hoverinfoItems.indexOf('none') === -1) {
                // hoverinfo is a combination of 'count' and 'probability'

                // Mouse
                var hoverX = d3.mouse(this)[0];

                // Label
                var gd = d.parcatsViewModel.graphDiv;
                var trace = d.parcatsViewModel.trace;
                var fullLayout = gd._fullLayout;
                var rootBBox = fullLayout._paperdiv.node().getBoundingClientRect();
                var graphDivBBox = d.parcatsViewModel.graphDiv.getBoundingClientRect();

                // Find path center in path coordinates
                var pathCenterX,
                    pathCenterY,
                    dimInd;

                for(dimInd = 0; dimInd < (d.leftXs.length - 1); dimInd++) {
                    if(d.leftXs[dimInd] + d.dimWidths[dimInd] - 2 <= hoverX && hoverX <= d.leftXs[dimInd + 1] + 2) {
                        var leftDim = d.parcatsViewModel.dimensions[dimInd];
                        var rightDim = d.parcatsViewModel.dimensions[dimInd + 1];
                        pathCenterX = (leftDim.x + leftDim.width + rightDim.x) / 2;
                        pathCenterY = (d.topYs[dimInd] + d.topYs[dimInd + 1] + d.height) / 2;
                        break;
                    }
                }

                // Find path center in root coordinates
                var hoverCenterX = d.parcatsViewModel.x + pathCenterX;
                var hoverCenterY = d.parcatsViewModel.y + pathCenterY;

                var textColor = tinycolor.mostReadable(d.model.color, ['black', 'white']);

                var count = d.model.count;
                var prob = count / d.parcatsViewModel.model.count;
                var labels = {
                    countLabel: count,
                    probabilityLabel: prob.toFixed(3)
                };

                // Build hover text
                var hovertextParts = [];
                if(d.parcatsViewModel.hoverinfoItems.indexOf('count') !== -1) {
                    hovertextParts.push(['Count:', labels.countLabel].join(' '));
                }
                if(d.parcatsViewModel.hoverinfoItems.indexOf('probability') !== -1) {
                    hovertextParts.push(['P:', labels.probabilityLabel].join(' '));
                }

                var hovertext = hovertextParts.join('<br>');
                var mouseX = d3.mouse(gd)[0];

                Fx.loneHover({
                    trace: trace,
                    x: hoverCenterX - rootBBox.left + graphDivBBox.left,
                    y: hoverCenterY - rootBBox.top + graphDivBBox.top,
                    text: hovertext,
                    color: d.model.color,
                    borderColor: 'black',
                    fontFamily: 'Monaco, "Courier New", monospace',
                    fontSize: 10,
                    fontColor: textColor,
                    idealAlign: mouseX < hoverCenterX ? 'right' : 'left',
                    hovertemplate: (trace.line || {}).hovertemplate,
                    hovertemplateLabels: labels,
                    eventData: [{
                        data: trace._input,
                        fullData: trace,
                        count: count,
                        probability: prob
                    }]
                }, {
                    container: fullLayout._hoverlayer.node(),
                    outerContainer: fullLayout._paper.node(),
                    gd: gd
                });
            }
        }
    }
}

/**
 * Handle path mouseout
 * @param {PathViewModel} d
 */
function mouseoutPath(d) {
    if(!d.parcatsViewModel.dragDimension) {
        // We're not currently dragging
        stylePathsNoHover(d3.select(this));

        // Remove and hover label
        Fx.loneUnhover(d.parcatsViewModel.graphDiv._fullLayout._hoverlayer.node());

        // Restore path order
        d.parcatsViewModel.pathSelection.sort(compareRawColor);

        // Emit unhover event
        if(d.parcatsViewModel.hoverinfoItems.indexOf('skip') === -1) {
            var points = buildPointsArrayForPath(d);
            d.parcatsViewModel.graphDiv.emit('plotly_unhover', {points: points, event: d3.event});
        }
    }
}

/**
 * Build array of point objects for a path
 *
 * For use in click/hover events
 * @param {PathViewModel} d
 */
function buildPointsArrayForPath(d) {
    var points = [];
    var curveNumber = getTraceIndex(d.parcatsViewModel);

    for(var i = 0; i < d.model.valueInds.length; i++) {
        var pointNumber = d.model.valueInds[i];
        points.push({
            curveNumber: curveNumber,
            pointNumber: pointNumber
        });
    }
    return points;
}

/**
 * Handle path click
 * @param {PathViewModel} d
 */
function clickPath(d) {
    if(d.parcatsViewModel.hoverinfoItems.indexOf('skip') === -1) {
        // hoverinfo it's skip, so interaction events aren't disabled
        var points = buildPointsArrayForPath(d);
        d.parcatsViewModel.graphDiv.emit('plotly_click', {points: points, event: d3.event});
    }
}

function stylePathsNoHover(pathSelection) {
    pathSelection
        .attr('fill', function(d) {
            return d.model.color;
        })
        .attr('fill-opacity', 0.6)
        .attr('stroke', 'lightgray')
        .attr('stroke-width', 0.2)
        .attr('stroke-opacity', 1.0);
}

function stylePathsHover(pathSelection) {
    pathSelection
        .attr('fill-opacity', 0.8)
        .attr('stroke', function(d) {
            return tinycolor.mostReadable(d.model.color, ['black', 'white']);
        })
        .attr('stroke-width', 0.3);
}

function styleCategoryHover(categorySelection) {
    categorySelection
        .select('rect.catrect')
        .attr('stroke', 'black')
        .attr('stroke-width', 2.5);
}

function styleCategoriesNoHover(categorySelection) {
    categorySelection
        .select('rect.catrect')
        .attr('stroke', 'black')
        .attr('stroke-width', 1)
        .attr('stroke-opacity', 1);
}

function styleBandsHover(bandsSelection) {
    bandsSelection
        .attr('stroke', 'black')
        .attr('stroke-width', 1.5);
}

function styleBandsNoHover(bandsSelection) {
    bandsSelection
        .attr('stroke', 'black')
        .attr('stroke-width', 0.2)
        .attr('stroke-opacity', 1.0)
        .attr('fill-opacity', 1.0);
}

/**
 * Return selection of all paths that pass through the specified category
 * @param {CategoryBandViewModel} catBandViewModel
 */
function selectPathsThroughCategoryBandColor(catBandViewModel) {

    var allPaths = catBandViewModel.parcatsViewModel.pathSelection;
    var dimInd = catBandViewModel.categoryViewModel.model.dimensionInd;
    var catInd = catBandViewModel.categoryViewModel.model.categoryInd;

    return allPaths
        .filter(
            /** @param {PathViewModel} pathViewModel */
            function(pathViewModel) {
                return pathViewModel.model.categoryInds[dimInd] === catInd &&
                    pathViewModel.model.color === catBandViewModel.color;
            });
}


/**
 * Perform hover styling for all paths that pass though the specified band element's category
 *
 * @param {HTMLElement} bandElement
 *  HTML element for band
 *
 */
function styleForCategoryHovermode(bandElement) {

    // Get all bands in the current category
    var bandSel = d3.select(bandElement.parentNode).selectAll('rect.bandrect');

    // Raise and style paths
    bandSel.each(function(bvm) {
        var paths = selectPathsThroughCategoryBandColor(bvm);
        stylePathsHover(paths);
        paths.each(function() {
            // Raise path to top
            Lib.raiseToTop(this);
        });
    });

    // Style category
    styleCategoryHover(d3.select(bandElement.parentNode));
}

/**
 * Perform hover styling for all paths that pass though the category of the specified band element and share the
 * same color
 *
 * @param {HTMLElement} bandElement
 *  HTML element for band
 *
 */
function styleForColorHovermode(bandElement) {
    var bandViewModel = d3.select(bandElement).datum();
    var catPaths = selectPathsThroughCategoryBandColor(bandViewModel);
    stylePathsHover(catPaths);
    catPaths.each(function() {
        // Raise path to top
        Lib.raiseToTop(this);
    });

    // Style category for drag
    d3.select(bandElement.parentNode)
        .selectAll('rect.bandrect')
        .filter(function(b) {return b.color === bandViewModel.color;})
        .each(function() {
            Lib.raiseToTop(this);
            styleBandsHover(d3.select(this));
        });
}


/**
 * @param {HTMLElement} bandElement
 *  HTML element for band
 * @param eventName
 *  Event name (plotly_hover or plotly_click)
 * @param event
 *  Mouse Event
 */
function emitPointsEventCategoryHovermode(bandElement, eventName, event) {
    // Get all bands in the current category
    var bandViewModel = d3.select(bandElement).datum();
    var gd = bandViewModel.parcatsViewModel.graphDiv;
    var bandSel = d3.select(bandElement.parentNode).selectAll('rect.bandrect');

    var points = [];
    bandSel.each(function(bvm) {
        var paths = selectPathsThroughCategoryBandColor(bvm);
        paths.each(function(pathViewModel) {
            // Extend points array
            Array.prototype.push.apply(points, buildPointsArrayForPath(pathViewModel));
        });
    });

    gd.emit(eventName, {points: points, event: event});
}

/**
 * @param {HTMLElement} bandElement
 *  HTML element for band
 * @param eventName
 *  Event name (plotly_hover or plotly_click)
 * @param event
 *  Mouse Event
 */
function emitPointsEventColorHovermode(bandElement, eventName, event) {
    var bandViewModel = d3.select(bandElement).datum();
    var gd = bandViewModel.parcatsViewModel.graphDiv;
    var paths = selectPathsThroughCategoryBandColor(bandViewModel);

    var points = [];
    paths.each(function(pathViewModel) {
        // Extend points array
        Array.prototype.push.apply(points, buildPointsArrayForPath(pathViewModel));
    });

    gd.emit(eventName, {points: points, event: event});
}

/**
 * Create hover label for a band element's category (for use when hoveron === 'category')
 *
 * @param {ClientRect} rootBBox
 *  Client bounding box for root of figure
 * @param {HTMLElement} bandElement
 *  HTML element for band
 *
 */
function createHoverLabelForCategoryHovermode(rootBBox, bandElement) {
    // Selections
    var rectSelection = d3.select(bandElement.parentNode).select('rect.catrect');
    var rectBoundingBox = rectSelection.node().getBoundingClientRect();

    // Models
    /** @type {CategoryViewModel} */
    var catViewModel = rectSelection.datum();
    var parcatsViewModel = catViewModel.parcatsViewModel;
    var dimensionModel = parcatsViewModel.model.dimensions[catViewModel.model.dimensionInd];
    var trace = parcatsViewModel.trace;

    // Positions
    var hoverCenterY = rectBoundingBox.top + rectBoundingBox.height / 2;
    var hoverCenterX,
        hoverLabelIdealAlign;

    if(parcatsViewModel.dimensions.length > 1 &&
        dimensionModel.displayInd === parcatsViewModel.dimensions.length - 1) {

        // right most dimension
        hoverCenterX = rectBoundingBox.left;
        hoverLabelIdealAlign = 'left';
    } else {
        hoverCenterX = rectBoundingBox.left + rectBoundingBox.width;
        hoverLabelIdealAlign = 'right';
    }

    var count = catViewModel.model.count;
    var catLabel = catViewModel.model.categoryLabel;
    var prob = count / catViewModel.parcatsViewModel.model.count;
    var labels = {
        countLabel: count,
        categoryLabel: catLabel,
        probabilityLabel: prob.toFixed(3)
    };

    // Hover label text
    var hoverinfoParts = [];
    if(catViewModel.parcatsViewModel.hoverinfoItems.indexOf('count') !== -1) {
        hoverinfoParts.push(['Count:', labels.countLabel].join(' '));
    }
    if(catViewModel.parcatsViewModel.hoverinfoItems.indexOf('probability') !== -1) {
        hoverinfoParts.push(['P(' + labels.categoryLabel + '):', labels.probabilityLabel].join(' '));
    }

    var hovertext = hoverinfoParts.join('<br>');
    return {
        trace: trace,
        x: hoverCenterX - rootBBox.left,
        y: hoverCenterY - rootBBox.top,
        text: hovertext,
        color: 'lightgray',
        borderColor: 'black',
        fontFamily: 'Monaco, "Courier New", monospace',
        fontSize: 12,
        fontColor: 'black',
        idealAlign: hoverLabelIdealAlign,
        hovertemplate: trace.hovertemplate,
        hovertemplateLabels: labels,
        eventData: [{
            data: trace._input,
            fullData: trace,
            count: count,
            category: catLabel,
            probability: prob
        }]
    };
}

/**
 * Create hover label for a band element's category (for use when hoveron === 'category')
 *
 * @param {ClientRect} rootBBox
 *  Client bounding box for root of figure
 * @param {HTMLElement} bandElement
 *  HTML element for band
 *
 */
function createHoverLabelForDimensionHovermode(rootBBox, bandElement) {

    var allHoverlabels = [];

    d3.select(bandElement.parentNode.parentNode)
        .selectAll('g.category')
        .select('rect.catrect')
        .each(function() {
            var bandNode = this;
            allHoverlabels.push(createHoverLabelForCategoryHovermode(rootBBox, bandNode));
        });

    return allHoverlabels;
}

/**
 * Create hover labels for a band element's category (for use when hoveron === 'dimension')
 *
 * @param {ClientRect} rootBBox
 *  Client bounding box for root of figure
 * @param {HTMLElement} bandElement
 *  HTML element for band
 *
 */
function createHoverLabelForColorHovermode(rootBBox, bandElement) {

    var bandBoundingBox = bandElement.getBoundingClientRect();

    // Models
    /** @type {CategoryBandViewModel} */
    var bandViewModel = d3.select(bandElement).datum();
    var catViewModel = bandViewModel.categoryViewModel;
    var parcatsViewModel = catViewModel.parcatsViewModel;
    var dimensionModel = parcatsViewModel.model.dimensions[catViewModel.model.dimensionInd];
    var trace = parcatsViewModel.trace;

    // positions
    var hoverCenterY = bandBoundingBox.y + bandBoundingBox.height / 2;

    var hoverCenterX,
        hoverLabelIdealAlign;
    if(parcatsViewModel.dimensions.length > 1 &&
        dimensionModel.displayInd === parcatsViewModel.dimensions.length - 1) {
        // right most dimension
        hoverCenterX = bandBoundingBox.left;
        hoverLabelIdealAlign = 'left';
    } else {
        hoverCenterX = bandBoundingBox.left + bandBoundingBox.width;
        hoverLabelIdealAlign = 'right';
    }

    // Labels
    var catLabel = catViewModel.model.categoryLabel;

    // Counts
    var totalCount = bandViewModel.parcatsViewModel.model.count;

    var bandColorCount = 0;
    bandViewModel.categoryViewModel.bands.forEach(function(b) {
        if(b.color === bandViewModel.color) {
            bandColorCount += b.count;
        }
    });

    var catCount = catViewModel.model.count;

    var colorCount = 0;
    parcatsViewModel.pathSelection.each(
        /** @param {PathViewModel} pathViewModel */
        function(pathViewModel) {
            if(pathViewModel.model.color === bandViewModel.color) {
                colorCount += pathViewModel.model.count;
            }
        });

    var pColorAndCat = bandColorCount / totalCount;
    var pCatGivenColor = bandColorCount / colorCount;
    var pColorGivenCat = bandColorCount / catCount;

    var labels = {
        countLabel: totalCount,
        categoryLabel: catLabel,
        probabilityLabel: pColorAndCat.toFixed(3)
    };

    // Hover label text
    var hoverinfoParts = [];
    if(catViewModel.parcatsViewModel.hoverinfoItems.indexOf('count') !== -1) {
        hoverinfoParts.push(['Count:', labels.countLabel].join(' '));
    }
    if(catViewModel.parcatsViewModel.hoverinfoItems.indexOf('probability') !== -1) {
        hoverinfoParts.push('P(color ∩ ' + catLabel + '): ' + labels.probabilityLabel);
        hoverinfoParts.push('P(' + catLabel + ' | color): ' + pCatGivenColor.toFixed(3));
        hoverinfoParts.push('P(color | ' + catLabel + '): ' + pColorGivenCat.toFixed(3));
    }

    var hovertext = hoverinfoParts.join('<br>');

    // Compute text color
    var textColor = tinycolor.mostReadable(bandViewModel.color, ['black', 'white']);

    return {
        trace: trace,
        x: hoverCenterX - rootBBox.left,
        y: hoverCenterY - rootBBox.top,
        // name: 'NAME',
        text: hovertext,
        color: bandViewModel.color,
        borderColor: 'black',
        fontFamily: 'Monaco, "Courier New", monospace',
        fontColor: textColor,
        fontSize: 10,
        idealAlign: hoverLabelIdealAlign,
        hovertemplate: trace.hovertemplate,
        hovertemplateLabels: labels,
        eventData: [{
            data: trace._input,
            fullData: trace,
            category: catLabel,
            count: totalCount,
            probability: pColorAndCat,
            categorycount: catCount,
            colorcount: colorCount,
            bandcolorcount: bandColorCount
        }]
    };
}

/**
 * Handle dimension mouseover
 * @param {CategoryBandViewModel} bandViewModel
 */
function mouseoverCategoryBand(bandViewModel) {
    if(!bandViewModel.parcatsViewModel.dragDimension) {
        // We're not currently dragging

        if(bandViewModel.parcatsViewModel.hoverinfoItems.indexOf('skip') === -1) {
            // hoverinfo is not skip, so we at least style the bands and emit interaction events

            // Mouse
            var mouseY = d3.mouse(this)[1];
            if(mouseY < -1) {
                // Hover is above above the category rectangle (probably the dimension title text)
                return;
            }

            var gd = bandViewModel.parcatsViewModel.graphDiv;
            var fullLayout = gd._fullLayout;
            var rootBBox = fullLayout._paperdiv.node().getBoundingClientRect();
            var hoveron = bandViewModel.parcatsViewModel.hoveron;

            /** @type {HTMLElement} */
            var bandElement = this;

            // Handle style and events
            if(hoveron === 'color') {
                styleForColorHovermode(bandElement);
                emitPointsEventColorHovermode(bandElement, 'plotly_hover', d3.event);
            } else {
                styleForCategoryHovermode(bandElement);
                emitPointsEventCategoryHovermode(bandElement, 'plotly_hover', d3.event);
            }

            // Handle hover label
            if(bandViewModel.parcatsViewModel.hoverinfoItems.indexOf('none') === -1) {
                var hoverItems;
                if(hoveron === 'category') {
                    hoverItems = createHoverLabelForCategoryHovermode(rootBBox, bandElement);
                } else if(hoveron === 'color') {
                    hoverItems = createHoverLabelForColorHovermode(rootBBox, bandElement);
                } else if(hoveron === 'dimension') {
                    hoverItems = createHoverLabelForDimensionHovermode(rootBBox, bandElement);
                }

                if(hoverItems) {
                    Fx.multiHovers(hoverItems, {
                        container: fullLayout._hoverlayer.node(),
                        outerContainer: fullLayout._paper.node(),
                        gd: gd
                    });
                }
            }
        }
    }
}


/**
 * Handle dimension mouseover
 * @param {CategoryBandViewModel} bandViewModel
 */
function mouseoutCategory(bandViewModel) {

    var parcatsViewModel = bandViewModel.parcatsViewModel;

    if(!parcatsViewModel.dragDimension) {
        // We're not dragging anything

        // Reset unhovered styles
        stylePathsNoHover(parcatsViewModel.pathSelection);
        styleCategoriesNoHover(parcatsViewModel.dimensionSelection.selectAll('g.category'));
        styleBandsNoHover(parcatsViewModel.dimensionSelection.selectAll('g.category').selectAll('rect.bandrect'));

        // Remove hover label
        Fx.loneUnhover(parcatsViewModel.graphDiv._fullLayout._hoverlayer.node());

        // Restore path order
        parcatsViewModel.pathSelection.sort(compareRawColor);

        // Emit unhover event
        if(parcatsViewModel.hoverinfoItems.indexOf('skip') === -1) {

            var hoveron = bandViewModel.parcatsViewModel.hoveron;
            var bandElement = this;

            // Handle style and events
            if(hoveron === 'color') {
                emitPointsEventColorHovermode(bandElement, 'plotly_unhover', d3.event);
            } else {
                emitPointsEventCategoryHovermode(bandElement, 'plotly_unhover', d3.event);
            }
        }
    }
}


/**
 * Handle dimension drag start
 * @param {DimensionViewModel} d
 */
function dragDimensionStart(d) {

    // Check if dragging is supported
    if(d.parcatsViewModel.arrangement === 'fixed') {
        return;
    }

    // Save off initial drag indexes for dimension
    d.dragDimensionDisplayInd = d.model.displayInd;
    d.initialDragDimensionDisplayInds = d.parcatsViewModel.model.dimensions.map(function(d) {return d.displayInd;});
    d.dragHasMoved = false;

    // Check for category hit
    d.dragCategoryDisplayInd = null;
    d3.select(this)
        .selectAll('g.category')
        .select('rect.catrect')
        .each(
            /** @param {CategoryViewModel} catViewModel */
            function(catViewModel) {
                var catMouseX = d3.mouse(this)[0];
                var catMouseY = d3.mouse(this)[1];


                if(-2 <= catMouseX && catMouseX <= catViewModel.width + 2 &&
                    -2 <= catMouseY && catMouseY <= catViewModel.height + 2) {

                    // Save off initial drag indexes for categories
                    d.dragCategoryDisplayInd = catViewModel.model.displayInd;
                    d.initialDragCategoryDisplayInds = d.model.categories.map(function(c) {
                        return c.displayInd;
                    });

                    // Initialize categories dragY to be the current y position
                    catViewModel.model.dragY = catViewModel.y;

                    // Raise category
                    Lib.raiseToTop(this.parentNode);

                    // Get band element
                    d3.select(this.parentNode)
                        .selectAll('rect.bandrect')
                        /** @param {CategoryBandViewModel} bandViewModel */
                        .each(function(bandViewModel) {
                            if(bandViewModel.y < catMouseY && catMouseY <= bandViewModel.y + bandViewModel.height) {
                                d.potentialClickBand = this;
                            }
                        });
                }
            });

    // Update toplevel drag dimension
    d.parcatsViewModel.dragDimension = d;

    // Remove hover label if any
    Fx.loneUnhover(d.parcatsViewModel.graphDiv._fullLayout._hoverlayer.node());
}

/**
 * Handle dimension drag
 * @param {DimensionViewModel} d
 */
function dragDimension(d) {

    // Check if dragging is supported
    if(d.parcatsViewModel.arrangement === 'fixed') {
        return;
    }

    d.dragHasMoved = true;

    if(d.dragDimensionDisplayInd === null) {
        return;
    }

    var dragDimInd = d.dragDimensionDisplayInd;
    var prevDimInd = dragDimInd - 1;
    var nextDimInd = dragDimInd + 1;

    var dragDimension = d.parcatsViewModel
        .dimensions[dragDimInd];

    // Update category
    if(d.dragCategoryDisplayInd !== null) {

        var dragCategory = dragDimension.categories[d.dragCategoryDisplayInd];

        // Update dragY by dy
        dragCategory.model.dragY += d3.event.dy;
        var categoryY = dragCategory.model.dragY;

        // Check for category drag swaps
        var catDisplayInd = dragCategory.model.displayInd;
        var dimCategoryViews = dragDimension.categories;

        var catAbove = dimCategoryViews[catDisplayInd - 1];
        var catBelow = dimCategoryViews[catDisplayInd + 1];

        // Check for overlap above
        if(catAbove !== undefined) {

            if(categoryY < (catAbove.y + catAbove.height / 2.0)) {

                // Swap display inds
                dragCategory.model.displayInd = catAbove.model.displayInd;
                catAbove.model.displayInd = catDisplayInd;
            }
        }

        if(catBelow !== undefined) {

            if((categoryY + dragCategory.height) > (catBelow.y + catBelow.height / 2.0)) {

                // Swap display inds
                dragCategory.model.displayInd = catBelow.model.displayInd;
                catBelow.model.displayInd = catDisplayInd;
            }
        }

        // Update category drag display index
        d.dragCategoryDisplayInd = dragCategory.model.displayInd;
    }

    // Update dimension position
    if(d.dragCategoryDisplayInd === null || d.parcatsViewModel.arrangement === 'freeform') {
        dragDimension.model.dragX = d3.event.x;

        // Check for dimension swaps
        var prevDimension = d.parcatsViewModel.dimensions[prevDimInd];
        var nextDimension = d.parcatsViewModel.dimensions[nextDimInd];

        if(prevDimension !== undefined) {
            if(dragDimension.model.dragX < (prevDimension.x + prevDimension.width)) {

                // Swap display inds
                dragDimension.model.displayInd = prevDimension.model.displayInd;
                prevDimension.model.displayInd = dragDimInd;
            }
        }

        if(nextDimension !== undefined) {
            if((dragDimension.model.dragX + dragDimension.width) > nextDimension.x) {

                // Swap display inds
                dragDimension.model.displayInd = nextDimension.model.displayInd;
                nextDimension.model.displayInd = d.dragDimensionDisplayInd;
            }
        }

        // Update drag display index
        d.dragDimensionDisplayInd = dragDimension.model.displayInd;
    }

    // Update view models
    updateDimensionViewModels(d.parcatsViewModel);
    updatePathViewModels(d.parcatsViewModel);

    // Update svg geometry
    updateSvgCategories(d.parcatsViewModel);
    updateSvgPaths(d.parcatsViewModel);
}


/**
 * Handle dimension drag end
 * @param {DimensionViewModel} d
 */
function dragDimensionEnd(d) {

    // Check if dragging is supported
    if(d.parcatsViewModel.arrangement === 'fixed') {
        return;
    }

    if(d.dragDimensionDisplayInd === null) {
        return;
    }

    d3.select(this).selectAll('text').attr('font-weight', 'normal');

    // Compute restyle command
    // -----------------------
    var restyleData = {};
    var traceInd = getTraceIndex(d.parcatsViewModel);

    // ### Handle dimension reordering ###
    var finalDragDimensionDisplayInds = d.parcatsViewModel.model.dimensions.map(function(d) {return d.displayInd;});
    var anyDimsReordered = d.initialDragDimensionDisplayInds.some(function(initDimDisplay, dimInd) {
        return initDimDisplay !== finalDragDimensionDisplayInds[dimInd];
    });

    if(anyDimsReordered) {
        finalDragDimensionDisplayInds.forEach(function(finalDimDisplay, dimInd) {
            var containerInd = d.parcatsViewModel.model.dimensions[dimInd].containerInd;
            restyleData['dimensions[' + containerInd + '].displayindex'] = finalDimDisplay;
        });
    }

    // ### Handle category reordering ###
    var anyCatsReordered = false;
    if(d.dragCategoryDisplayInd !== null) {
        var finalDragCategoryDisplayInds = d.model.categories.map(function(c) {
            return c.displayInd;
        });

        anyCatsReordered = d.initialDragCategoryDisplayInds.some(function(initCatDisplay, catInd) {
            return initCatDisplay !== finalDragCategoryDisplayInds[catInd];
        });

        if(anyCatsReordered) {

            // Sort a shallow copy of the category models by display index
            var sortedCategoryModels = d.model.categories.slice().sort(
                function(a, b) { return a.displayInd - b.displayInd; });

            // Get new categoryarray and ticktext values
            var newCategoryArray = sortedCategoryModels.map(function(v) { return v.categoryValue; });
            var newCategoryLabels = sortedCategoryModels.map(function(v) { return v.categoryLabel; });

            restyleData['dimensions[' + d.model.containerInd + '].categoryarray'] = [newCategoryArray];
            restyleData['dimensions[' + d.model.containerInd + '].ticktext'] = [newCategoryLabels];
            restyleData['dimensions[' + d.model.containerInd + '].categoryorder'] = 'array';
        }
    }

    // Handle potential click event
    // ----------------------------
    if(d.parcatsViewModel.hoverinfoItems.indexOf('skip') === -1) {
        if(!d.dragHasMoved && d.potentialClickBand) {
            if(d.parcatsViewModel.hoveron === 'color') {
                emitPointsEventColorHovermode(d.potentialClickBand, 'plotly_click', d3.event.sourceEvent);
            } else {
                emitPointsEventCategoryHovermode(d.potentialClickBand, 'plotly_click', d3.event.sourceEvent);
            }
        }
    }

    // Nullify drag states
    // -------------------
    d.model.dragX = null;
    if(d.dragCategoryDisplayInd !== null) {
        var dragCategory = d.parcatsViewModel
            .dimensions[d.dragDimensionDisplayInd]
            .categories[d.dragCategoryDisplayInd];

        dragCategory.model.dragY = null;
        d.dragCategoryDisplayInd = null;
    }

    d.dragDimensionDisplayInd = null;
    d.parcatsViewModel.dragDimension = null;
    d.dragHasMoved = null;
    d.potentialClickBand = null;

    // Update view models
    // ------------------
    updateDimensionViewModels(d.parcatsViewModel);
    updatePathViewModels(d.parcatsViewModel);

    // Perform transition
    // ------------------
    var transition = d3.transition()
        .duration(300)
        .ease('cubic-in-out');

    transition
        .each(function() {
            updateSvgCategories(d.parcatsViewModel, true);
            updateSvgPaths(d.parcatsViewModel, true);
        })
        .each('end', function() {
            if(anyDimsReordered || anyCatsReordered) {
                // Perform restyle if the order of categories or dimensions changed
                Plotly.restyle(d.parcatsViewModel.graphDiv, restyleData, [traceInd]);
            }
        });
}

/**
 *
 * @param {ParcatsViewModel} parcatsViewModel
 */
function getTraceIndex(parcatsViewModel) {
    var traceInd;
    var allTraces = parcatsViewModel.graphDiv._fullData;
    for(var i = 0; i < allTraces.length; i++) {
        if(parcatsViewModel.key === allTraces[i].uid) {
            traceInd = i;
            break;
        }
    }
    return traceInd;
}

/** Update the svg paths for view model
 * @param {ParcatsViewModel} parcatsViewModel
 * @param {boolean} hasTransition Whether to update element with transition
 */
function updateSvgPaths(parcatsViewModel, hasTransition) {

    if(hasTransition === undefined) {
        hasTransition = false;
    }

    function transition(selection) {
        return hasTransition ? selection.transition() : selection;
    }

    // Update binding
    parcatsViewModel.pathSelection.data(function(d) {
        return d.paths;
    }, key);

    // Update paths
    transition(parcatsViewModel.pathSelection).attr('d', function(d) {
        return d.svgD;
    });
}

/** Update the svg paths for view model
 * @param {ParcatsViewModel} parcatsViewModel
 * @param {boolean} hasTransition Whether to update element with transition
 */
function updateSvgCategories(parcatsViewModel, hasTransition) {

    if(hasTransition === undefined) {
        hasTransition = false;
    }

    function transition(selection) {
        return hasTransition ? selection.transition() : selection;
    }

    // Update binding
    parcatsViewModel.dimensionSelection
        .data(function(d) {
            return d.dimensions;}, key);

    var categorySelection = parcatsViewModel.dimensionSelection
        .selectAll('g.category')
        .data(function(d) {return d.categories;}, key);

    // Update dimension position
    transition(parcatsViewModel.dimensionSelection)
        .attr('transform', function(d) {
            return 'translate(' + d.x + ', 0)';
        });

    // Update category position
    transition(categorySelection)
        .attr('transform', function(d) {
            return 'translate(0, ' + d.y + ')';
        });

    var dimLabelSelection = categorySelection.select('.dimlabel');

    // ### Update dimension label
    // Only the top-most display category should have the dimension label
    dimLabelSelection
        .text(function(d, i) {
            if(i === 0) {
                // Add dimension label above topmost category
                return d.parcatsViewModel.model.dimensions[d.model.dimensionInd].dimensionLabel;
            } else {
                return null;
            }
        });

    // Update category label
    // Categories in the right-most display dimension have their labels on
    // the right, all others on the left
    var catLabelSelection = categorySelection.select('.catlabel');
    catLabelSelection
        .attr('text-anchor',
            function(d) {
                if(catInRightDim(d)) {
                    // Place label to the right of category
                    return 'start';
                } else {
                    // Place label to the left of category
                    return 'end';
                }
            })
        .attr('x',
            function(d) {
                if(catInRightDim(d)) {
                    // Place label to the right of category
                    return d.width + 5;
                } else {
                    // Place label to the left of category
                    return -5;
                }
            })
        .each(function(d) {
            // Update attriubutes of <tspan> elements
            var newX;
            var newAnchor;
            if(catInRightDim(d)) {
                // Place label to the right of category
                newX = d.width + 5;
                newAnchor = 'start';
            } else {
                // Place label to the left of category
                newX = -5;
                newAnchor = 'end';
            }
            d3.select(this)
                .selectAll('tspan')
                .attr('x', newX)
                .attr('text-anchor', newAnchor);
        });

    // Update bands
    // Initialize color band rects
    var bandSelection = categorySelection
        .selectAll('rect.bandrect')
        .data(
            /** @param {CategoryViewModel} catViewModel*/
            function(catViewModel) {
                return catViewModel.bands;
            }, key);

    var bandsSelectionEnter = bandSelection.enter()
        .append('rect')
        .attr('class', 'bandrect')
        .attr('cursor', 'move')
        .attr('stroke-opacity', 0)
        .attr('fill', function(d) {
            return d.color;
        })
        .attr('fill-opacity', 0);

    bandSelection
        .attr('fill', function(d) {
            return d.color;
        })
        .attr('width', function(d) {
            return d.width;
        })
        .attr('height', function(d) {
            return d.height;
        })
        .attr('y', function(d) {
            return d.y;
        });

    styleBandsNoHover(bandsSelectionEnter);

    // Raise bands to the top
    bandSelection.each(function() {Lib.raiseToTop(this);});

    // Remove unused bands
    bandSelection.exit().remove();
}

/**
 * Create a ParcatsViewModel traces
 * @param {Object} graphDiv
 *  Top-level graph div element
 * @param {Layout} layout
 *  SVG layout object
 * @param {Array.<ParcatsModel>} wrappedParcatsModel
 *  Wrapped ParcatsModel for this trace
 * @return {ParcatsViewModel}
 */
function createParcatsViewModel(graphDiv, layout, wrappedParcatsModel) {
    // Unwrap model
    var parcatsModel = wrappedParcatsModel[0];

    // Compute margin
    var margin = layout.margin || {l: 80, r: 80, t: 100, b: 80};

    // Compute pixel position/extents
    var trace = parcatsModel.trace;
    var domain = trace.domain;
    var figureWidth = layout.width;
    var figureHeight = layout.height;
    var traceWidth = Math.floor(figureWidth * (domain.x[1] - domain.x[0]));
    var traceHeight = Math.floor(figureHeight * (domain.y[1] - domain.y[0]));
    var traceX = domain.x[0] * figureWidth + margin.l;
    var traceY = layout.height - domain.y[1] * layout.height + margin.t;

    // Handle path shape
    // -----------------
    var pathShape = trace.line.shape;

    // Handle hover info
    // -----------------
    var hoverinfoItems;
    if(trace.hoverinfo === 'all') {
        hoverinfoItems = ['count', 'probability'];
    } else {
        hoverinfoItems = (trace.hoverinfo || '').split('+');
    }

    // Construct parcatsViewModel
    // --------------------------
    var parcatsViewModel = {
        trace: trace,
        key: trace.uid,
        model: parcatsModel,
        x: traceX,
        y: traceY,
        width: traceWidth,
        height: traceHeight,
        hoveron: trace.hoveron,
        hoverinfoItems: hoverinfoItems,
        arrangement: trace.arrangement,
        bundlecolors: trace.bundlecolors,
        sortpaths: trace.sortpaths,
        labelfont: trace.labelfont,
        categorylabelfont: trace.tickfont,
        pathShape: pathShape,
        dragDimension: null,
        margin: margin,
        paths: [],
        dimensions: [],
        graphDiv: graphDiv,
        traceSelection: null,
        pathSelection: null,
        dimensionSelection: null
    };

    // Update dimension view models if we have at least 1 dimension
    if(parcatsModel.dimensions) {
        updateDimensionViewModels(parcatsViewModel);

        // Update path view models if we have at least 2 dimensions
        updatePathViewModels(parcatsViewModel);
    }
    // Inside a categories view model
    return parcatsViewModel;
}

/**
 * Build the SVG string to represents a parallel categories path
 * @param {Array.<Number>} leftXPositions
 *  Array of the x positions of the left edge of each dimension (in display order)
 * @param {Array.<Number>} pathYs
 *  Array of the y positions of the top of the path at each dimension (in display order)
 * @param {Array.<Number>} dimWidths
 *  Array of the widths of each dimension in display order
 * @param {Number} pathHeight
 *  The height of the path in pixels
 * @param {Number} curvature
 *  The curvature factor for the path. 0 results in a straight line and values greater than zero result in curved paths
 * @return {string}
 */
function buildSvgPath(leftXPositions, pathYs, dimWidths, pathHeight, curvature) {

    // Compute the x midpoint of each path segment
    var xRefPoints1 = [];
    var xRefPoints2 = [];
    var refInterpolator;
    var d;

    for(d = 0; d < dimWidths.length - 1; d++) {
        refInterpolator = d3.interpolateNumber(dimWidths[d] + leftXPositions[d], leftXPositions[d + 1]);
        xRefPoints1.push(refInterpolator(curvature));
        xRefPoints2.push(refInterpolator(1 - curvature));
    }

    // Move to top of path on left edge of left-most category
    var svgD = 'M ' + leftXPositions[0] + ',' + pathYs[0];

    // Horizontal line to right edge
    svgD += 'l' + dimWidths[0] + ',0 ';

    // Horizontal line to right edge
    for(d = 1; d < dimWidths.length; d++) {

        // Curve to left edge of category
        svgD += 'C' + xRefPoints1[d - 1] + ',' + pathYs[d - 1] +
              ' ' + xRefPoints2[d - 1] + ',' + pathYs[d] +
              ' ' + leftXPositions[d] + ',' + pathYs[d];

        // svgD += 'L' + leftXPositions[d] + ',' + pathYs[d];

        // Horizontal line to right edge
        svgD += 'l' + dimWidths[d] + ',0 ';
    }

    // Line down
    svgD += 'l' + '0,' + pathHeight + ' ';

    // Line to left edge of right-most category
    svgD += 'l -' + dimWidths[dimWidths.length - 1] + ',0 ';

    for(d = dimWidths.length - 2; d >= 0; d--) {

        // Curve to right edge of category
        svgD += 'C' + xRefPoints2[d] + ',' + (pathYs[d + 1] + pathHeight) +
             ' ' + xRefPoints1[d] + ',' + (pathYs[d] + pathHeight) +
             ' ' + (leftXPositions[d] + dimWidths[d]) + ',' + (pathYs[d] + pathHeight);

        // svgD += 'L' + (leftXPositions[d] + dimWidths[d]) + ',' + (pathYs[d] + pathHeight);

        // Horizontal line to right edge
        svgD += 'l-' + dimWidths[d] + ',0 ';
    }

    // Close path
    svgD += 'Z';
    return svgD;
}

/**
 * Update the path view models based on the dimension view models in a ParcatsViewModel
 *
 * @param {ParcatsViewModel} parcatsViewModel
 *  View model for trace
 */
function updatePathViewModels(parcatsViewModel) {

    // Initialize an array of the y position of the top of the next path to be added to each category.
    //
    // nextYPositions[d][c] is the y position of the next path through category with index c of dimension with index d
    var dimensionViewModels = parcatsViewModel.dimensions;
    var parcatsModel = parcatsViewModel.model;
    var nextYPositions = dimensionViewModels.map(
        function(d) {
            return d.categories.map(
                function(c) {
                    return c.y;
                });
        });

    // Array from category index to category display index for each true dimension index
    var catToDisplayIndPerDim = parcatsViewModel.model.dimensions.map(
        function(d) {
            return d.categories.map(function(c) {return c.displayInd;});
        });

    // Array from true dimension index to dimension display index
    var dimToDisplayInd = parcatsViewModel.model.dimensions.map(function(d) {return d.displayInd;});
    var displayToDimInd = parcatsViewModel.dimensions.map(function(d) {return d.model.dimensionInd;});

    // Array of the x position of the left edge of the rectangles for each dimension
    var leftXPositions = dimensionViewModels.map(
        function(d) {
            return d.x;
        });

    // Compute dimension widths
    var dimWidths = dimensionViewModels.map(function(d) {return d.width;});

    // Build sorted Array of PathModel objects
    var pathModels = [];
    for(var p in parcatsModel.paths) {
        if(parcatsModel.paths.hasOwnProperty(p)) {
            pathModels.push(parcatsModel.paths[p]);
        }
    }

    // Compute category display inds to use for sorting paths
    function pathDisplayCategoryInds(pathModel) {
        var dimensionInds = pathModel.categoryInds.map(function(catInd, dimInd) {return catToDisplayIndPerDim[dimInd][catInd];});
        var displayInds = displayToDimInd.map(function(dimInd) {
            return dimensionInds[dimInd];
        });
        return displayInds;
    }

    // Sort in ascending order by display index array
    pathModels.sort(function(v1, v2) {

        // Build display inds for each path
        var sortArray1 = pathDisplayCategoryInds(v1);
        var sortArray2 = pathDisplayCategoryInds(v2);

        // Handle path sort order
        if(parcatsViewModel.sortpaths === 'backward') {
            sortArray1.reverse();
            sortArray2.reverse();
        }

        // Append the first value index of the path to break ties
        sortArray1.push(v1.valueInds[0]);
        sortArray2.push(v2.valueInds[0]);

        // Handle color bundling
        if(parcatsViewModel.bundlecolors) {
            // Prepend sort array with the raw color value
            sortArray1.unshift(v1.rawColor);
            sortArray2.unshift(v2.rawColor);
        }

        // colors equal, sort by display categories
        if(sortArray1 < sortArray2) {
            return -1;
        }
        if(sortArray1 > sortArray2) {
            return 1;
        }

        return 0;
    });

    // Create path models
    var pathViewModels = new Array(pathModels.length);
    var totalCount = dimensionViewModels[0].model.count;
    var totalHeight = dimensionViewModels[0].categories
        .map(function(c) { return c.height; })
        .reduce(function(v1, v2) { return v1 + v2; });


    for(var pathNumber = 0; pathNumber < pathModels.length; pathNumber++) {
        var pathModel = pathModels[pathNumber];

        var pathHeight;
        if(totalCount > 0) {
            pathHeight = totalHeight * (pathModel.count / totalCount);
        } else {
            pathHeight = 0;
        }

        // Build path y coords
        var pathYs = new Array(nextYPositions.length);
        for(var d = 0; d < pathModel.categoryInds.length; d++) {
            var catInd = pathModel.categoryInds[d];
            var catDisplayInd = catToDisplayIndPerDim[d][catInd];
            var dimDisplayInd = dimToDisplayInd[d];

            // Update next y position
            pathYs[dimDisplayInd] = nextYPositions[dimDisplayInd][catDisplayInd];
            nextYPositions[dimDisplayInd][catDisplayInd] += pathHeight;

            // Update category color information
            var catViewModle = parcatsViewModel.dimensions[dimDisplayInd].categories[catDisplayInd];
            var numBands = catViewModle.bands.length;
            var lastCatBand = catViewModle.bands[numBands - 1];

            if(lastCatBand === undefined || pathModel.rawColor !== lastCatBand.rawColor) {
                // Create a new band
                var bandY = lastCatBand === undefined ? 0 : lastCatBand.y + lastCatBand.height;
                catViewModle.bands.push({
                    key: bandY,
                    color: pathModel.color,
                    rawColor: pathModel.rawColor,
                    height: pathHeight,
                    width: catViewModle.width,
                    count: pathModel.count,
                    y: bandY,
                    categoryViewModel: catViewModle,
                    parcatsViewModel: parcatsViewModel
                });
            } else {
                // Extend current band
                var currentBand = catViewModle.bands[numBands - 1];
                currentBand.height += pathHeight;
                currentBand.count += pathModel.count;
            }
        }

        // build svg path
        var svgD;
        if(parcatsViewModel.pathShape === 'hspline') {
            svgD = buildSvgPath(leftXPositions, pathYs, dimWidths, pathHeight, 0.5);
        } else {
            svgD = buildSvgPath(leftXPositions, pathYs, dimWidths, pathHeight, 0);
        }

        pathViewModels[pathNumber] = {
            key: pathModel.valueInds[0],
            model: pathModel,
            height: pathHeight,
            leftXs: leftXPositions,
            topYs: pathYs,
            dimWidths: dimWidths,
            svgD: svgD,
            parcatsViewModel: parcatsViewModel
        };
    }

    parcatsViewModel.paths = pathViewModels;

 // * @property key
 // *  Unique key for this model
 // * @property {PathModel} model
 // *  Source path model
 // * @property {Number} height
 // *  Height of this path (pixels)
 // * @property {String} svgD
 // *  SVG path "d" attribute string
}

/**
 * Update the dimension view models based on the dimension models in a ParcatsViewModel
 *
 * @param {ParcatsViewModel} parcatsViewModel
 *  View model for trace
 */
function updateDimensionViewModels(parcatsViewModel) {

    // Compute dimension ordering
    var dimensionsIndInfo = parcatsViewModel.model.dimensions.map(function(d) {
        return {displayInd: d.displayInd, dimensionInd: d.dimensionInd};
    });

    dimensionsIndInfo.sort(function(a, b) {
        return a.displayInd - b.displayInd;
    });

    var dimensions = [];
    for(var displayInd in dimensionsIndInfo) {
        var dimensionInd = dimensionsIndInfo[displayInd].dimensionInd;
        var dimModel = parcatsViewModel.model.dimensions[dimensionInd];
        dimensions.push(createDimensionViewModel(parcatsViewModel, dimModel));
    }

    parcatsViewModel.dimensions = dimensions;
}

/**
 * Create a parcats DimensionViewModel
 *
 * @param {ParcatsViewModel} parcatsViewModel
 *  View model for trace
 * @param {DimensionModel} dimensionModel
 * @return {DimensionViewModel}
 */
function createDimensionViewModel(parcatsViewModel, dimensionModel) {

    // Compute dimension x position
    var categoryLabelPad = 40;
    var dimWidth = 16;
    var numDimensions = parcatsViewModel.model.dimensions.length;
    var displayInd = dimensionModel.displayInd;

    // Compute x coordinate values
    var dimDx;
    var dimX0;
    var dimX;

    if(numDimensions > 1) {
        dimDx = (parcatsViewModel.width - 2 * categoryLabelPad - dimWidth) / (numDimensions - 1);
    } else {
        dimDx = 0;
    }
    dimX0 = categoryLabelPad;
    dimX = dimX0 + dimDx * displayInd;

    // Compute categories
    var categories = [];
    var maxCats = parcatsViewModel.model.maxCats;
    var numCats = dimensionModel.categories.length;
    var catSpacing = 8;
    var totalCount = dimensionModel.count;
    var totalHeight = parcatsViewModel.height - catSpacing * (maxCats - 1);
    var nextCatHeight;
    var nextCatModel;
    var nextCat;
    var catInd;
    var catDisplayInd;

    // Compute starting Y offset
    var nextCatY = (maxCats - numCats) * catSpacing / 2.0;

    // Compute category ordering
    var categoryIndInfo = dimensionModel.categories.map(function(c) {
        return {displayInd: c.displayInd, categoryInd: c.categoryInd};
    });

    categoryIndInfo.sort(function(a, b) {
        return a.displayInd - b.displayInd;
    });

    for(catDisplayInd = 0; catDisplayInd < numCats; catDisplayInd++) {
        catInd = categoryIndInfo[catDisplayInd].categoryInd;
        nextCatModel = dimensionModel.categories[catInd];

        if(totalCount > 0) {
            nextCatHeight = (nextCatModel.count / totalCount) * totalHeight;
        } else {
            nextCatHeight = 0;
        }

        nextCat = {
            key: nextCatModel.valueInds[0],
            model: nextCatModel,
            width: dimWidth,
            height: nextCatHeight,
            y: nextCatModel.dragY !== null ? nextCatModel.dragY : nextCatY,
            bands: [],
            parcatsViewModel: parcatsViewModel
        };

        nextCatY = nextCatY + nextCatHeight + catSpacing;
        categories.push(nextCat);
    }

    return {
        key: dimensionModel.dimensionInd,
        x: dimensionModel.dragX !== null ? dimensionModel.dragX : dimX,
        y: 0,
        width: dimWidth,
        model: dimensionModel,
        categories: categories,
        parcatsViewModel: parcatsViewModel,
        dragCategoryDisplayInd: null,
        dragDimensionDisplayInd: null,
        initialDragDimensionDisplayInds: null,
        initialDragCategoryDisplayInds: null,
        dragHasMoved: null,
        potentialClickBand: null
    };
}

// JSDoc typedefs
// ==============
/**
 * @typedef {Object} Layout
 *  Object containing svg layout information
 *
 * @property {Number} width (pixels)
 *  Usable width for Figure (after margins are removed)
 * @property {Number} height (pixels)
 *  Usable height for Figure (after margins are removed)
 * @property {Margin} margin
 *  Margin around the Figure (pixels)
 */

/**
 * @typedef {Object} Margin
 *  Object containing padding information in pixels
 *
 * @property {Number} t
 *  Top margin
 * @property {Number} r
 *  Right margin
 * @property {Number} b
 *  Bottom margin
 * @property {Number} l
 *  Left margin
 */

/**
 * @typedef {Object} Font
 *  Object containing font information
 *
 * @property {Number} size: Font size
 * @property {String} color: Font color
 * @property {String} family: Font family
 */

/**
 * @typedef {Object} ParcatsViewModel
 *  Object containing calculated parcats view information
 *
 *  These are quantities that require Layout information to calculate
 * @property key
 *  Unique key for this model
 * @property {ParcatsModel} model
 *  Source parcats model
 * @property {Array.<DimensionViewModel>} dimensions
 *  Array of dimension view models
 * @property {Number} width
 *  Width for this trace (pixels)
 * @property {Number} height
 *  Height for this trace (pixels)
 * @property {Number} x
 *  X position of this trace with respect to the Figure (pixels)
 * @property {Number} y
 *  Y position of this trace with respect to the Figure (pixels)
 * @property {String} hoveron
 *  Hover interaction mode. One of: 'category', 'color', or 'dimension'
 * @property {Array.<String>} hoverinfoItems
 *  Info to display on hover. Array with a combination of 'counts' and/or 'probabilities', or 'none', or 'skip'
 * @property {String} arrangement
 *  Category arrangement. One of: 'perpendicular', 'freeform', or 'fixed'
 * @property {Boolean} bundlecolors
 *  Whether paths should be sorted so that like colors are bundled together as they pass through categories
 * @property {String} sortpaths
 *  If 'forward' then sort paths based on dimensions from left to right. If 'backward' sort based on dimensions
 *  from right to left
 * @property {Font} labelfont
 *  Font for the dimension labels
 * @property {Font} categorylabelfont
 *  Font for the category labels
 * @property {String} pathShape
 *  The shape of the paths. Either 'linear' or 'hspline'.
 * @property {DimensionViewModel|null} dragDimension
 *  Dimension currently being dragged. Null if no drag in progress
 * @property {Margin} margin
 *  Margin around the Figure
 * @property {Object} graphDiv
 *  Top-level graph div element
 * @property {Object} traceSelection
 *  D3 selection of this view models trace group element
 * @property {Object} pathSelection
 *  D3 selection of this view models path elements
 * @property {Object} dimensionSelection
 *  D3 selection of this view models dimension group element
 */

/**
 * @typedef {Object} DimensionViewModel
 *  Object containing calculated parcats dimension view information
 *
 *  These are quantities that require Layout information to calculate
 * @property key
 *  Unique key for this model
 * @property {DimensionModel} model
 *  Source dimension model
 * @property {Number} x
 *  X position of the center of this dimension with respect to the Figure (pixels)
 * @property {Number} y
 *  Y position of the top of this dimension with respect to the Figure (pixels)
 * @property {Number} width
 *  Width of categories in this dimension (pixels)
 * @property {ParcatsViewModel} parcatsViewModel
 *  The parent trace's view model
 * @property {Array.<CategoryViewModel>} categories
 *  Dimensions category view models
 * @property {Number|null} dragCategoryDisplayInd
 *  Display index of category currently being dragged. null if no category is being dragged
 * @property {Number|null} dragDimensionDisplayInd
 *  Display index of the dimension being dragged. null if no dimension is being dragged
 * @property {Array.<Number>|null} initialDragDimensionDisplayInds
 *  Dimensions display indexes at the beginning of the current drag. null if no dimension is being dragged
 * @property {Array.<Number>|null} initialDragCategoryDisplayInds
 *  Category display indexes for the at the beginning of the current drag. null if no category is being dragged
 * @property {HTMLElement} potentialClickBand
 *  Band under mouse when current drag began. If no drag movement takes place then a click will be emitted for this
 *  band. Null if not drag in progress.
 * @property {Boolean} dragHasMoved
 *  True if there is an active drag and the drag has moved. If drag doesn't move before being ended then
 *  this may be interpreted as a click. Null if no drag in progress
 */

/**
 * @typedef {Object} CategoryViewModel
 *  Object containing calculated parcats category view information
 *
 *  These are quantities that require Layout information to calculate
 * @property key
 *  Unique key for this model
 * @property {CategoryModel} model
 *  Source category model
 * @property {Number} width
 *  Width for this category (pixels)
 * @property {Number} height
 *  Height for this category (pixels)
 * @property {Number} y
 *  Y position of this cateogry with respect to the Figure (pixels)
 * @property {Array.<CategoryBandViewModel>} bands
 *  Array of color bands inside the category
 * @property {ParcatsViewModel} parcatsViewModel
 *  The parent trace's view model
 */

/**
 * @typedef {Object} CategoryBandViewModel
 *  Object containing calculated category band information. A category band is a region inside a category covering
 *  paths of a single color
 *
 * @property key
 *  Unique key for this model
 * @property color
 *  Band color
 * @property rawColor
 *  Raw color value for band
 * @property {Number} width
 *  Band width
 * @property {Number} height
 *  Band height
 * @property {Number} y
 *  Y position of top of the band with respect to the category
 * @property {Number} count
 *  The number of samples represented by the band
 * @property {CategoryViewModel} categoryViewModel
 *  The parent categorie's view model
 * @property {ParcatsViewModel} parcatsViewModel
 *  The parent trace's view model
 */

/**
 * @typedef {Object} PathViewModel
 *  Object containing calculated parcats path view information
 *
 *  These are quantities that require Layout information to calculate
 * @property key
 *  Unique key for this model
 * @property {PathModel} model
 *  Source path model
 * @property {Number} height
 *  Height of this path (pixels)
 * @property {Array.<Number>} leftXs
 *  The x position of the left edge of each display dimension
 * @property {Array.<Number>} topYs
 *  The y position of the top of the path for each display dimension
 * @property {Array.<Number>} dimWidths
 *  The width of each display dimension
 * @property {String} svgD
 *  SVG path "d" attribute string
 * @property {ParcatsViewModel} parcatsViewModel
 *  The parent trace's view model
 */

},{"../../components/drawing":595,"../../components/fx":613,"../../lib":697,"../../lib/svg_text_utils":721,"../../plot_api/plot_api":732,"d3":151,"tinycolor2":518}],1011:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


var parcats = _dereq_('./parcats');

/**
 * Create / update parcat traces
 *
 * @param {Object} graphDiv
 * @param {Array.<ParcatsModel>} parcatsModels
 */
module.exports = function plot(graphDiv, parcatsModels, transitionOpts, makeOnCompleteCallback) {
    var fullLayout = graphDiv._fullLayout;
    var svg = fullLayout._paper;
    var size = fullLayout._size;

    parcats(
        graphDiv,
        svg,
        parcatsModels,
        {
            width: size.w,
            height: size.h,
            margin: {
                t: size.t,
                r: size.r,
                b: size.b,
                l: size.l
            }
        },
        transitionOpts,
        makeOnCompleteCallback
    );
};

},{"./parcats":1010}],1012:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorAttributes = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
var axesAttrs = _dereq_('../../plots/cartesian/layout_attributes');
var fontAttrs = _dereq_('../../plots/font_attributes');
var domainAttrs = _dereq_('../../plots/domain').attributes;

var extendFlat = _dereq_('../../lib/extend').extendFlat;
var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;

module.exports = {
    domain: domainAttrs({name: 'parcoords', trace: true, editType: 'calc'}),

    hoverlabel: undefined,

    labelfont: fontAttrs({
        editType: 'calc',
        
    }),
    tickfont: fontAttrs({
        editType: 'calc',
        
    }),
    rangefont: fontAttrs({
        editType: 'calc',
        
    }),

    dimensions: templatedArray('dimension', {
        label: {
            valType: 'string',
            
            editType: 'calc',
            
        },
        // TODO: better way to determine ordinal vs continuous axes,
        // so users can use tickvals/ticktext with a continuous axis.
        tickvals: extendFlat({}, axesAttrs.tickvals, {editType: 'calc'}),
        ticktext: extendFlat({}, axesAttrs.ticktext, {editType: 'calc'}),
        tickformat: {
            valType: 'string',
            dflt: '3s',
            
            editType: 'calc',
            
        },
        visible: {
            valType: 'boolean',
            dflt: true,
            
            editType: 'calc',
            
        },
        range: {
            valType: 'info_array',
            
            items: [
                {valType: 'number', editType: 'calc'},
                {valType: 'number', editType: 'calc'}
            ],
            editType: 'calc',
            
        },
        constraintrange: {
            valType: 'info_array',
            
            freeLength: true,
            dimensions: '1-2',
            items: [
                {valType: 'number', editType: 'calc'},
                {valType: 'number', editType: 'calc'}
            ],
            editType: 'calc',
            
        },
        multiselect: {
            valType: 'boolean',
            dflt: true,
            
            editType: 'calc',
            
        },
        values: {
            valType: 'data_array',
            
            editType: 'calc',
            
        },
        editType: 'calc',
        
    }),

    line: extendFlat(
        colorAttributes('line', {
            // the default autocolorscale isn't quite usable for parcoords due to context ambiguity around 0 (grey, off-white)
            // autocolorscale therefore defaults to false too, to avoid being overridden by the  blue-white-red autocolor palette
            colorscaleDflt: 'Viridis',
            autoColorDflt: false,
            editTypeOverride: 'calc'
        }), {
            colorbar: colorbarAttrs,
            editType: 'calc'
        })
};

},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../lib/extend":687,"../../plot_api/plot_template":735,"../../plots/cartesian/layout_attributes":757,"../../plots/domain":770,"../../plots/font_attributes":771}],1013:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var c = _dereq_('./constants');
var d3 = _dereq_('d3');
var keyFun = _dereq_('../../lib/gup').keyFun;
var repeat = _dereq_('../../lib/gup').repeat;
var sortAsc = _dereq_('../../lib').sorterAsc;

var snapRatio = c.bar.snapRatio;
function snapOvershoot(v, vAdjacent) { return v * (1 - snapRatio) + vAdjacent * snapRatio; }

var snapClose = c.bar.snapClose;
function closeToCovering(v, vAdjacent) { return v * (1 - snapClose) + vAdjacent * snapClose; }

// snap for the low end of a range on an ordinal scale
// on an ordinal scale, always show some overshoot from the exact value,
// so it's clear we're covering it
// find the interval we're in, and snap to 1/4 the distance to the next
// these two could be unified at a slight loss of readability / perf
function ordinalScaleSnapLo(a, v, existingRanges) {
    if(overlappingExisting(v, existingRanges)) return v;

    var aPrev = a[0];
    var aPrevPrev = aPrev;
    for(var i = 1; i < a.length; i++) {
        var aNext = a[i];

        // very close to the previous - snap down to it
        if(v < closeToCovering(aPrev, aNext)) return snapOvershoot(aPrev, aPrevPrev);
        if(v < aNext || i === a.length - 1) return snapOvershoot(aNext, aPrev);

        aPrevPrev = aPrev;
        aPrev = aNext;
    }
}

function ordinalScaleSnapHi(a, v, existingRanges) {
    if(overlappingExisting(v, existingRanges)) return v;

    var aPrev = a[a.length - 1];
    var aPrevPrev = aPrev;
    for(var i = a.length - 2; i >= 0; i--) {
        var aNext = a[i];

        // very close to the previous - snap down to it
        if(v > closeToCovering(aPrev, aNext)) return snapOvershoot(aPrev, aPrevPrev);
        if(v > aNext || i === a.length - 1) return snapOvershoot(aNext, aPrev);

        aPrevPrev = aPrev;
        aPrev = aNext;
    }
}

function overlappingExisting(v, existingRanges) {
    for(var i = 0; i < existingRanges.length; i++) {
        if(v >= existingRanges[i][0] && v <= existingRanges[i][1]) return true;
    }
    return false;
}

function barHorizontalSetup(selection) {
    selection
        .attr('x', -c.bar.captureWidth / 2)
        .attr('width', c.bar.captureWidth);
}

function backgroundBarHorizontalSetup(selection) {
    selection
        .attr('visibility', 'visible')
        .style('visibility', 'visible')
        .attr('fill', 'yellow')
        .attr('opacity', 0);
}

function setHighlight(d) {
    if(!d.brush.filterSpecified) {
        return '0,' + d.height;
    }
    var pixelRanges = unitToPx(d.brush.filter.getConsolidated(), d.height);
    var dashArray = [0]; // we start with a 0 length selection as filter ranges are inclusive, not exclusive
    var p, sectionHeight, iNext;
    var currentGap = pixelRanges.length ? pixelRanges[0][0] : null;
    for(var i = 0; i < pixelRanges.length; i++) {
        p = pixelRanges[i];
        sectionHeight = p[1] - p[0];
        dashArray.push(currentGap);
        dashArray.push(sectionHeight);
        iNext = i + 1;
        if(iNext < pixelRanges.length) {
            currentGap = pixelRanges[iNext][0] - p[1];
        }
    }
    dashArray.push(d.height);
    // d.height is added at the end to ensure that (1) we have an even number of dasharray points, MDN page says
    // "If an odd number of values is provided, then the list of values is repeated to yield an even number of values."
    // and (2) it's _at least_ as long as the full height (even if range is minuscule and at the bottom) though this
    // may not be necessary, maybe duplicating the last point would do too. But no harm in a longer dasharray than line.
    return dashArray;
}

function unitToPx(unitRanges, height) {
    return unitRanges.map(function(pr) {
        return pr.map(function(v) { return v * height; }).sort(sortAsc);
    });
}

// is the cursor over the north, middle, or south of a bar?
// the end handles extend over the last 10% of the bar
function getRegion(fPix, y) {
    var pad = c.bar.handleHeight;
    if(y > fPix[1] + pad || y < fPix[0] - pad) return;
    if(y >= 0.9 * fPix[1] + 0.1 * fPix[0]) return 'n';
    if(y <= 0.9 * fPix[0] + 0.1 * fPix[1]) return 's';
    return 'ns';
}

function clearCursor() {
    d3.select(document.body)
        .style('cursor', null);
}

function styleHighlight(selection) {
    // stroke-dasharray is used to minimize the number of created DOM nodes, because the requirement calls for up to
    // 1000 individual selections on an axis, and there can be 60 axes per parcoords, and multiple parcoords per
    // dashboard. The technique is similar to https://codepen.io/monfera/pen/rLYqWR and using a `polyline` with
    // multiple sections, or a `path` element via its `d` attribute would also be DOM-sparing alternatives.
    selection.attr('stroke-dasharray', setHighlight);
}

function renderHighlight(root, tweenCallback) {
    var bar = d3.select(root).selectAll('.highlight, .highlight-shadow');
    var barToStyle = tweenCallback ? bar.transition().duration(c.bar.snapDuration).each('end', tweenCallback) : bar;
    styleHighlight(barToStyle);
}

function getInterval(d, y) {
    var b = d.brush;
    var active = b.filterSpecified;
    var closestInterval = NaN;
    var out = {};
    var i;

    if(active) {
        var height = d.height;
        var intervals = b.filter.getConsolidated();
        var pixIntervals = unitToPx(intervals, height);
        var hoveredInterval = NaN;
        var previousInterval = NaN;
        var nextInterval = NaN;
        for(i = 0; i <= pixIntervals.length; i++) {
            var p = pixIntervals[i];
            if(p && p[0] <= y && y <= p[1]) {
                // over a bar
                hoveredInterval = i;
                break;
            } else {
                // between bars, or before/after the first/last bar
                previousInterval = i ? i - 1 : NaN;
                if(p && p[0] > y) {
                    nextInterval = i;
                    break; // no point continuing as intervals are non-overlapping and sorted; could use log search
                }
            }
        }

        closestInterval = hoveredInterval;
        if(isNaN(closestInterval)) {
            if(isNaN(previousInterval) || isNaN(nextInterval)) {
                closestInterval = isNaN(previousInterval) ? nextInterval : previousInterval;
            }
            else {
                closestInterval = (y - pixIntervals[previousInterval][1] < pixIntervals[nextInterval][0] - y) ?
                    previousInterval : nextInterval;
            }
        }

        if(!isNaN(closestInterval)) {
            var fPix = pixIntervals[closestInterval];
            var region = getRegion(fPix, y);

            if(region) {
                out.interval = intervals[closestInterval];
                out.intervalPix = fPix;
                out.region = region;
            }
        }
    }

    if(d.ordinal && !out.region) {
        var a = d.unitTickvals;
        var unitLocation = d.unitToPaddedPx.invert(y);
        for(i = 0; i < a.length; i++) {
            var rangei = [
                a[Math.max(i - 1, 0)] * 0.25 + a[i] * 0.75,
                a[Math.min(i + 1, a.length - 1)] * 0.25 + a[i] * 0.75
            ];
            if(unitLocation >= rangei[0] && unitLocation <= rangei[1]) {
                out.clickableOrdinalRange = rangei;
                break;
            }
        }
    }

    return out;
}

function attachDragBehavior(selection) {
    // There's some fiddling with pointer cursor styling so that the cursor preserves its shape while dragging a brush
    // even if the cursor strays from the interacting bar, which is bound to happen as bars are thin and the user
    // will inevitably leave the hotspot strip. In this regard, it does something similar to what the D3 brush would do.
    selection
        .on('mousemove', function(d) {
            d3.event.preventDefault();
            if(!d.parent.inBrushDrag) {
                var y = d.height - d3.mouse(this)[1] - 2 * c.verticalPadding;
                var interval = getInterval(d, y);

                var cursor = 'crosshair';
                if(interval.clickableOrdinalRange) cursor = 'pointer';
                else if(interval.region) cursor = interval.region + '-resize';
                d3.select(document.body)
                    .style('cursor', cursor);
            }
        })
        .on('mouseleave', function(d) {
            if(!d.parent.inBrushDrag) clearCursor();
        })
        .call(d3.behavior.drag()
            .on('dragstart', function(d) {
                d3.event.sourceEvent.stopPropagation();
                var y = d.height - d3.mouse(this)[1] - 2 * c.verticalPadding;
                var unitLocation = d.unitToPaddedPx.invert(y);
                var b = d.brush;
                var interval = getInterval(d, y);
                var unitRange = interval.interval;
                var s = b.svgBrush;
                s.wasDragged = false; // we start assuming there won't be a drag - useful for reset
                s.grabbingBar = interval.region === 'ns';
                if(s.grabbingBar) {
                    var pixelRange = unitRange.map(d.unitToPaddedPx);
                    s.grabPoint = y - pixelRange[0] - c.verticalPadding;
                    s.barLength = pixelRange[1] - pixelRange[0];
                }
                s.clickableOrdinalRange = interval.clickableOrdinalRange;
                s.stayingIntervals = (d.multiselect && b.filterSpecified) ? b.filter.getConsolidated() : [];
                if(unitRange) {
                    s.stayingIntervals = s.stayingIntervals.filter(function(int2) {
                        return int2[0] !== unitRange[0] && int2[1] !== unitRange[1];
                    });
                }
                s.startExtent = interval.region ? unitRange[interval.region === 's' ? 1 : 0] : unitLocation;
                d.parent.inBrushDrag = true;
                s.brushStartCallback();
            })
            .on('drag', function(d) {
                d3.event.sourceEvent.stopPropagation();
                var y = d.height - d3.mouse(this)[1] - 2 * c.verticalPadding;
                var s = d.brush.svgBrush;
                s.wasDragged = true;

                if(s.grabbingBar) { // moving the bar
                    s.newExtent = [y - s.grabPoint, y + s.barLength - s.grabPoint].map(d.unitToPaddedPx.invert);
                } else { // south/north drag or new bar creation
                    s.newExtent = [s.startExtent, d.unitToPaddedPx.invert(y)].sort(sortAsc);
                }

                // take care of the parcoords axis height constraint: bar can't breach it
                var bottomViolation = Math.max(0, -s.newExtent[0]);
                var topViolation = Math.max(0, s.newExtent[1] - 1);
                s.newExtent[0] += bottomViolation;
                s.newExtent[1] -= topViolation;
                if(s.grabbingBar) {
                    // in case of bar dragging (non-resizing interaction, unlike north/south resize or new bar creation)
                    // the constraint adjustment must apply to the other end of the bar as well, otherwise it'd
                    // shorten or lengthen
                    s.newExtent[1] += bottomViolation;
                    s.newExtent[0] -= topViolation;
                }

                d.brush.filterSpecified = true;
                s.extent = s.stayingIntervals.concat([s.newExtent]);
                s.brushCallback(d);
                renderHighlight(this.parentNode);
            })
            .on('dragend', function(d) {
                var e = d3.event;
                e.sourceEvent.stopPropagation();
                var brush = d.brush;
                var filter = brush.filter;
                var s = brush.svgBrush;
                var grabbingBar = s.grabbingBar;
                s.grabbingBar = false;
                s.grabLocation = undefined;
                d.parent.inBrushDrag = false;
                clearCursor(); // instead of clearing, a nicer thing would be to set it according to current location
                if(!s.wasDragged) { // a click+release on the same spot (ie. w/o dragging) means a bar or full reset
                    s.wasDragged = undefined; // logic-wise unneeded, just shows `wasDragged` has no longer a meaning
                    if(s.clickableOrdinalRange) {
                        if(brush.filterSpecified && d.multiselect) {
                            s.extent.push(s.clickableOrdinalRange);
                        }
                        else {
                            s.extent = [s.clickableOrdinalRange];
                            brush.filterSpecified = true;
                        }
                    }
                    else if(grabbingBar) {
                        s.extent = s.stayingIntervals;
                        if(s.extent.length === 0) {
                            brushClear(brush);
                        }
                    } else {
                        brushClear(brush);
                    }
                    s.brushCallback(d);
                    renderHighlight(this.parentNode);
                    s.brushEndCallback(brush.filterSpecified ? filter.getConsolidated() : []);
                    return; // no need to fuse intervals or snap to ordinals, so we can bail early
                }

                var mergeIntervals = function() {
                    // Key piece of logic: once the button is released, possibly overlapping intervals will be fused:
                    // Here it's done immediately on click release while on ordinal snap transition it's done at the end
                    filter.set(filter.getConsolidated());
                };

                if(d.ordinal) {
                    var a = d.unitTickvals;
                    if(a[a.length - 1] < a[0]) a.reverse();
                    s.newExtent = [
                        ordinalScaleSnapLo(a, s.newExtent[0], s.stayingIntervals),
                        ordinalScaleSnapHi(a, s.newExtent[1], s.stayingIntervals)
                    ];
                    var hasNewExtent = s.newExtent[1] > s.newExtent[0];
                    s.extent = s.stayingIntervals.concat(hasNewExtent ? [s.newExtent] : []);
                    if(!s.extent.length) {
                        brushClear(brush);
                    }
                    s.brushCallback(d);
                    if(hasNewExtent) {
                        // merging intervals post the snap tween
                        renderHighlight(this.parentNode, mergeIntervals);
                    }
                    else {
                        // if no new interval, don't animate, just redraw the highlight immediately
                        mergeIntervals();
                        renderHighlight(this.parentNode);
                    }
                } else {
                    mergeIntervals(); // merging intervals immediately
                }
                s.brushEndCallback(brush.filterSpecified ? filter.getConsolidated() : []);
            })
        );
}

function startAsc(a, b) { return a[0] - b[0]; }

function renderAxisBrush(axisBrush) {

    var background = axisBrush.selectAll('.background').data(repeat);

    background.enter()
        .append('rect')
        .classed('background', true)
        .call(barHorizontalSetup)
        .call(backgroundBarHorizontalSetup)
        .style('pointer-events', 'auto') // parent pointer events are disabled; we must have it to register events
        .attr('transform', 'translate(0 ' + c.verticalPadding + ')');

    background
        .call(attachDragBehavior)
        .attr('height', function(d) {
            return d.height - c.verticalPadding;
        });

    var highlightShadow = axisBrush.selectAll('.highlight-shadow').data(repeat); // we have a set here, can't call it `extent`

    highlightShadow.enter()
        .append('line')
        .classed('highlight-shadow', true)
        .attr('x', -c.bar.width / 2)
        .attr('stroke-width', c.bar.width + c.bar.strokeWidth)
        .attr('stroke', c.bar.strokeColor)
        .attr('opacity', c.bar.strokeOpacity)
        .attr('stroke-linecap', 'butt');

    highlightShadow
        .attr('y1', function(d) { return d.height; })
        .call(styleHighlight);

    var highlight = axisBrush.selectAll('.highlight').data(repeat); // we have a set here, can't call it `extent`

    highlight.enter()
        .append('line')
        .classed('highlight', true)
        .attr('x', -c.bar.width / 2)
        .attr('stroke-width', c.bar.width - c.bar.strokeWidth)
        .attr('stroke', c.bar.fillColor)
        .attr('opacity', c.bar.fillOpacity)
        .attr('stroke-linecap', 'butt');

    highlight
        .attr('y1', function(d) { return d.height; })
        .call(styleHighlight);
}

function ensureAxisBrush(axisOverlays) {
    var axisBrush = axisOverlays.selectAll('.' + c.cn.axisBrush)
        .data(repeat, keyFun);

    axisBrush.enter()
        .append('g')
        .classed(c.cn.axisBrush, true);

    renderAxisBrush(axisBrush);
}

function getBrushExtent(brush) {
    return brush.svgBrush.extent.map(function(e) {return e.slice();});
}

function brushClear(brush) {
    brush.filterSpecified = false;
    brush.svgBrush.extent = [[0, 1]];
}

function axisBrushMoved(callback) {
    return function axisBrushMoved(dimension) {
        var brush = dimension.brush;
        var extent = getBrushExtent(brush);
        var newExtent = extent.slice();
        brush.filter.set(newExtent);
        callback();
    };
}

function dedupeRealRanges(intervals) {
    // Fuses elements of intervals if they overlap, yielding discontiguous intervals, results.length <= intervals.length
    // Currently uses closed intervals, ie. dedupeRealRanges([[400, 800], [300, 400]]) -> [300, 800]
    var queue = intervals.slice();
    var result = [];
    var currentInterval;
    var current = queue.shift();
    while(current) { // [].shift === undefined, so we don't descend into an empty array
        currentInterval = current.slice();
        while((current = queue.shift()) && current[0] <= /* right-open interval would need `<` */ currentInterval[1]) {
            currentInterval[1] = Math.max(currentInterval[1], current[1]);
        }
        result.push(currentInterval);
    }
    return result;
}

function makeFilter() {
    var filter = [];
    var consolidated;
    var bounds;
    return {
        set: function(a) {
            filter = a
                .map(function(d) { return d.slice().sort(sortAsc); })
                .sort(startAsc);
            consolidated = dedupeRealRanges(filter);
            bounds = filter.reduce(function(p, n) {
                return [Math.min(p[0], n[0]), Math.max(p[1], n[1])];
            }, [Infinity, -Infinity]);
        },
        get: function() { return filter.slice(); },
        getConsolidated: function() { return consolidated; },
        getBounds: function() { return bounds; }
    };
}

function makeBrush(state, rangeSpecified, initialRange, brushStartCallback, brushCallback, brushEndCallback) {
    var filter = makeFilter();
    filter.set(initialRange);
    return {
        filter: filter,
        filterSpecified: rangeSpecified, // there's a difference between not filtering and filtering a non-proper subset
        svgBrush: {
            extent: [], // this is where the svgBrush writes contents into
            brushStartCallback: brushStartCallback,
            brushCallback: axisBrushMoved(brushCallback),
            brushEndCallback: brushEndCallback
        }
    };
}

// for use by supplyDefaults, but it needed tons of pieces from here so
// seemed to make more sense just to put the whole routine here
function cleanRanges(ranges, dimension) {
    if(Array.isArray(ranges[0])) {
        ranges = ranges.map(function(ri) { return ri.sort(sortAsc); });

        if(!dimension.multiselect) ranges = [ranges[0]];
        else ranges = dedupeRealRanges(ranges.sort(startAsc));
    }
    else ranges = [ranges.sort(sortAsc)];

    // ordinal snapping
    if(dimension.tickvals) {
        var sortedTickVals = dimension.tickvals.slice().sort(sortAsc);
        ranges = ranges.map(function(ri) {
            var rSnapped = [
                ordinalScaleSnapLo(sortedTickVals, ri[0], []),
                ordinalScaleSnapHi(sortedTickVals, ri[1], [])
            ];
            if(rSnapped[1] > rSnapped[0]) return rSnapped;
        })
        .filter(function(ri) { return ri; });

        if(!ranges.length) return;
    }
    return ranges.length > 1 ? ranges : ranges[0];
}

module.exports = {
    makeBrush: makeBrush,
    ensureAxisBrush: ensureAxisBrush,
    cleanRanges: cleanRanges
};

},{"../../lib":697,"../../lib/gup":695,"./constants":1016,"d3":151}],1014:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var getModuleCalcData = _dereq_('../../plots/get_data').getModuleCalcData;
var parcoordsPlot = _dereq_('./plot');
var xmlnsNamespaces = _dereq_('../../constants/xmlns_namespaces');

var PARCOORDS = 'parcoords';

exports.name = PARCOORDS;

exports.plot = function(gd) {
    var calcData = getModuleCalcData(gd.calcdata, PARCOORDS)[0];
    if(calcData.length) parcoordsPlot(gd, calcData);
};

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var hadParcoords = (oldFullLayout._has && oldFullLayout._has(PARCOORDS));
    var hasParcoords = (newFullLayout._has && newFullLayout._has(PARCOORDS));

    if(hadParcoords && !hasParcoords) {
        oldFullLayout._paperdiv.selectAll('.parcoords').remove();
        oldFullLayout._glimages.selectAll('*').remove();
    }
};

exports.toSVG = function(gd) {
    var imageRoot = gd._fullLayout._glimages;
    var root = d3.select(gd).selectAll('.svg-container');
    var canvases = root.filter(function(d, i) {return i === root.size() - 1;})
        .selectAll('.gl-canvas-context, .gl-canvas-focus');

    function canvasToImage() {
        var canvas = this;
        var imageData = canvas.toDataURL('image/png');
        var image = imageRoot.append('svg:image');

        image.attr({
            xmlns: xmlnsNamespaces.svg,
            'xlink:href': imageData,
            preserveAspectRatio: 'none',
            x: 0,
            y: 0,
            width: canvas.width,
            height: canvas.height
        });
    }

    canvases.each(canvasToImage);

    // Chrome / Safari bug workaround - browser apparently loses connection to the defined pattern
    // Without the workaround, these browsers 'lose' the filter brush styling (color etc.) after a snapshot
    // on a subsequent interaction.
    // Firefox works fine without this workaround
    window.setTimeout(function() {
        d3.selectAll('#filterBarPattern')
            .attr('id', 'filterBarPattern');
    }, 60);
};

},{"../../constants/xmlns_namespaces":675,"../../plots/get_data":781,"./plot":1022,"d3":151}],1015:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
var calcColorscale = _dereq_('../../components/colorscale/calc');
var Lib = _dereq_('../../lib');
var wrap = _dereq_('../../lib/gup').wrap;

module.exports = function calc(gd, trace) {

    for(var i = 0; i < trace.dimensions.length; i++) {
        trace.dimensions[i].values = convertTypedArray(trace.dimensions[i].values);
    }
    trace.line.color = convertTypedArray(trace.line.color);

    var cs = !!trace.line.colorscale && Array.isArray(trace.line.color);
    var color = cs ? trace.line.color : constHalf(trace._length);
    var cscale = cs ? trace.line.colorscale : [[0, trace.line.color], [1, trace.line.color]];

    if(hasColorscale(trace, 'line')) {
        calcColorscale(gd, trace, {
            vals: color,
            containerStr: 'line',
            cLetter: 'c'
        });
    }

    return wrap({
        lineColor: color,
        cscale: cscale
    });
};

function constHalf(len) {
    var out = new Array(len);
    for(var i = 0; i < len; i++) {
        out[i] = 0.5;
    }
    return out;
}

function convertTypedArray(a) {
    return (Lib.isTypedArray(a)) ? Array.prototype.slice.call(a) : a;
}

},{"../../components/colorscale/calc":582,"../../components/colorscale/helpers":585,"../../lib":697,"../../lib/gup":695}],1016:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    maxDimensionCount: 60, // this cannot be increased without WebGL code refactoring
    overdrag: 45,
    verticalPadding: 2, // otherwise, horizontal lines on top or bottom are of lower width
    tickDistance: 50,
    canvasPixelRatio: 1,
    blockLineCount: 5000,
    layers: ['contextLineLayer', 'focusLineLayer', 'pickLineLayer'],
    axisTitleOffset: 28,
    axisExtentOffset: 10,
    bar: {
        width: 4, // Visible width of the filter bar
        captureWidth: 10, // Mouse-sensitive width for interaction (Fitts law)
        fillColor: 'magenta', // Color of the filter bar fill
        fillOpacity: 1, // Filter bar fill opacity
        snapDuration: 150, // tween duration in ms for brush snap for ordinal axes
        snapRatio: 0.25, // ratio of bar extension relative to the distance between two adjacent ordinal values
        snapClose: 0.01, // fraction of inter-value distance to snap to the closer one, even if you're not over it
        strokeColor: 'white', // Color of the filter bar side lines
        strokeOpacity: 1, // Filter bar side stroke opacity
        strokeWidth: 1, // Filter bar side stroke width in pixels
        handleHeight: 8, // Height of the filter bar vertical resize areas on top and bottom
        handleOpacity: 1, // Opacity of the filter bar vertical resize areas on top and bottom
        handleOverlap: 0 // A larger than 0 value causes overlaps with the filter bar, represented as pixels
    },
    cn: {
        axisExtentText: 'axis-extent-text',
        parcoordsLineLayers: 'parcoords-line-layers',
        parcoordsLineLayer: 'parcoords-lines',
        parcoords: 'parcoords',
        parcoordsControlView: 'parcoords-control-view',
        yAxis: 'y-axis',
        axisOverlays: 'axis-overlays',
        axis: 'axis',
        axisHeading: 'axis-heading',
        axisTitle: 'axis-title',
        axisExtent: 'axis-extent',
        axisExtentTop: 'axis-extent-top',
        axisExtentTopText: 'axis-extent-top-text',
        axisExtentBottom: 'axis-extent-bottom',
        axisExtentBottomText: 'axis-extent-bottom-text',
        axisBrush: 'axis-brush'
    },
    id: {
        filterBarPattern: 'filter-bar-pattern'

    }
};

},{}],1017:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
var handleDomainDefaults = _dereq_('../../plots/domain').defaults;
var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');

var attributes = _dereq_('./attributes');
var axisBrush = _dereq_('./axisbrush');
var maxDimensionCount = _dereq_('./constants').maxDimensionCount;
var mergeLength = _dereq_('./merge_length');

function handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce) {
    var lineColor = coerce('line.color', defaultColor);

    if(hasColorscale(traceIn, 'line') && Lib.isArrayOrTypedArray(lineColor)) {
        if(lineColor.length) {
            coerce('line.colorscale');
            colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'});
            // TODO: I think it would be better to keep showing lines beyond the last line color
            // but I'm not sure what color to give these lines - probably black or white
            // depending on the background color?
            return lineColor.length;
        }
        else {
            traceOut.line.color = defaultColor;
        }
    }
    return Infinity;
}

function dimensionDefaults(dimensionIn, dimensionOut) {
    function coerce(attr, dflt) {
        return Lib.coerce(dimensionIn, dimensionOut, attributes.dimensions, attr, dflt);
    }

    var values = coerce('values');
    var visible = coerce('visible');
    if(!(values && values.length)) {
        visible = dimensionOut.visible = false;
    }

    if(visible) {
        coerce('label');
        coerce('tickvals');
        coerce('ticktext');
        coerce('tickformat');
        coerce('range');

        coerce('multiselect');
        var constraintRange = coerce('constraintrange');
        if(constraintRange) {
            dimensionOut.constraintrange = axisBrush.cleanRanges(constraintRange, dimensionOut);
        }
    }
}

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var dimensionsIn = traceIn.dimensions;
    if(Array.isArray(dimensionsIn) && dimensionsIn.length > maxDimensionCount) {
        Lib.log('parcoords traces support up to ' + maxDimensionCount + ' dimensions at the moment');
        dimensionsIn.splice(maxDimensionCount);
    }

    var dimensions = handleArrayContainerDefaults(traceIn, traceOut, {
        name: 'dimensions',
        handleItemDefaults: dimensionDefaults
    });

    var len = handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);

    handleDomainDefaults(traceOut, layout, coerce);

    if(!Array.isArray(dimensions) || !dimensions.length) {
        traceOut.visible = false;
    }

    mergeLength(traceOut, dimensions, 'values', len);

    // make default font size 10px (default is 12),
    // scale linearly with global font size
    var fontDflt = {
        family: layout.font.family,
        size: Math.round(layout.font.size / 1.2),
        color: layout.font.color
    };

    Lib.coerceFont(coerce, 'labelfont', fontDflt);
    Lib.coerceFont(coerce, 'tickfont', fontDflt);
    Lib.coerceFont(coerce, 'rangefont', fontDflt);
};

},{"../../components/colorscale/defaults":584,"../../components/colorscale/helpers":585,"../../lib":697,"../../plots/array_container_defaults":741,"../../plots/domain":770,"./attributes":1012,"./axisbrush":1013,"./constants":1016,"./merge_length":1020}],1018:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Parcoords = {};

Parcoords.attributes = _dereq_('./attributes');
Parcoords.supplyDefaults = _dereq_('./defaults');
Parcoords.calc = _dereq_('./calc');
Parcoords.plot = _dereq_('./plot');
Parcoords.colorbar = {
    container: 'line',
    min: 'cmin',
    max: 'cmax'
};

Parcoords.moduleType = 'trace';
Parcoords.name = 'parcoords';
Parcoords.basePlotModule = _dereq_('./base_plot');
Parcoords.categories = ['gl', 'regl', 'noOpacity'];
Parcoords.meta = {
    
};

module.exports = Parcoords;

},{"./attributes":1012,"./base_plot":1014,"./calc":1015,"./defaults":1017,"./plot":1022}],1019:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var glslify = _dereq_('glslify');
var vertexShaderSource = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n               p4, p5, p6, p7,\n               p8, p9, pa, pb,\n               pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n             loA, hiA, loB, hiB, loC, hiC, loD, hiD;\n\nuniform vec2 resolution,\n             viewBoxPosition,\n             viewBoxSize;\n\nuniform sampler2D palette;\nuniform sampler2D mask;\nuniform float maskHeight;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec4 unit_1 = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n    return dot(matrixCompMult(p, v) * unit_1, unit_1);\n}\n\nfloat axisY(\n        float x,\n        mat4 d[4],\n        mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n    ) {\n\n    float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n    float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n    return y1 * (1.0 - x) + y2 * x;\n}\n\nconst int bitsPerByte = 8;\n\nint mod2(int a) {\n    return a - 2 * (a / 2);\n}\n\nint mod8(int a) {\n    return a - 8 * (a / 8);\n}\n\nvec4 zero = vec4(0, 0, 0, 0);\nvec4 unit_0 = vec4(1, 1, 1, 1);\nvec2 xyProjection = vec2(1, 1);\n\nmat4 mclamp(mat4 m, mat4 lo, mat4 hi) {\n    return mat4(clamp(m[0], lo[0], hi[0]),\n                clamp(m[1], lo[1], hi[1]),\n                clamp(m[2], lo[2], hi[2]),\n                clamp(m[3], lo[3], hi[3]));\n}\n\nbool mshow(mat4 p, mat4 lo, mat4 hi) {\n    return mclamp(p, lo, hi) == p;\n}\n\nbool withinBoundingBox(\n        mat4 d[4],\n        mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD\n    ) {\n\n    return mshow(d[0], loA, hiA) &&\n           mshow(d[1], loB, hiB) &&\n           mshow(d[2], loC, hiC) &&\n           mshow(d[3], loD, hiD);\n}\n\nbool withinRasterMask(mat4 d[4], sampler2D mask, float height) {\n    bool result = true;\n    int bitInByteStepper;\n    float valY, valueY, scaleX;\n    int hit, bitmask, valX;\n    for(int i = 0; i < 4; i++) {\n        for(int j = 0; j < 4; j++) {\n            for(int k = 0; k < 4; k++) {\n                bitInByteStepper = mod8(j * 4 + k);\n                valX = i * 2 + j / 2;\n                valY = d[i][j][k];\n                valueY = valY * (height - 1.0) + 0.5;\n                scaleX = (float(valX) + 0.5) / 8.0;\n                hit = int(texture2D(mask, vec2(scaleX, (valueY + 0.5) / height))[3] * 255.0) / int(pow(2.0, float(bitInByteStepper)));\n                result = result && mod2(hit) == 1;\n            }\n        }\n    }\n    return result;\n}\n\nvec4 position(\n        float depth,\n        vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n        mat4 dims[4],\n        float signum,\n        mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D,\n        mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD,\n        sampler2D mask, float maskHeight\n    ) {\n\n    float x = 0.5 * signum + 0.5;\n    float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n    float show = float(\n                            withinBoundingBox(dims, loA, hiA, loB, hiB, loC, hiC, loD, hiD)\n                         && withinRasterMask(dims, mask, maskHeight)\n                      );\n\n    vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n    float depthOrHide = depth + 2.0 * (1.0 - show);\n\n    return vec4(\n        xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n        depthOrHide,\n        1.0\n    );\n}\n\nvoid main() {\n\n    float prominence = abs(pf[3]);\n\n    mat4 p[4];\n    p[0] = mat4(p0, p1, p2, p3);\n    p[1] = mat4(p4, p5, p6, p7);\n    p[2] = mat4(p8, p9, pa, pb);\n    p[3] = mat4(pc, pd, pe, abs(pf));\n\n    gl_Position = position(\n        1.0 - prominence,\n        resolution, viewBoxPosition, viewBoxSize,\n        p,\n        sign(pf[3]),\n        dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n        loA, hiA, loB, hiB, loC, hiC, loD, hiD,\n        mask, maskHeight\n    );\n\n    float clampedColorIndex = clamp((prominence - colorClamp[0]) / (colorClamp[1] - colorClamp[0]), 0.0, 1.0);\n    fragColor = texture2D(palette, vec2((clampedColorIndex * 255.0 + 0.5) / 256.0, 0.5));\n}\n"]);
var contextShaderSource = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n               p4, p5, p6, p7,\n               p8, p9, pa, pb,\n               pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D;\n\nuniform vec2 resolution,\n             viewBoxPosition,\n             viewBoxSize;\n\nuniform sampler2D palette;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec2 xyProjection = vec2(1, 1);\n\nvec4 unit = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n    return dot(matrixCompMult(p, v) * unit, unit);\n}\n\nfloat axisY(\n        float x,\n        mat4 d[4],\n        mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n    ) {\n\n    float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n    float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n    return y1 * (1.0 - x) + y2 * x;\n}\n\nvec4 position(\n        float depth,\n        vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n        mat4 dims[4],\n        float signum,\n        mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n    ) {\n\n    float x = 0.5 * signum + 0.5;\n    float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n    vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n\n    return vec4(\n        xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n        depth,\n        1.0\n    );\n}\n\nvoid main() {\n\n    float prominence = abs(pf[3]);\n\n    mat4 p[4];\n    p[0] = mat4(p0, p1, p2, p3);\n    p[1] = mat4(p4, p5, p6, p7);\n    p[2] = mat4(p8, p9, pa, pb);\n    p[3] = mat4(pc, pd, pe, abs(pf));\n\n    gl_Position = position(\n        1.0 - prominence,\n        resolution, viewBoxPosition, viewBoxSize,\n        p,\n        sign(pf[3]),\n        dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D\n    );\n\n    float clampedColorIndex = clamp((prominence - colorClamp[0]) / (colorClamp[1] - colorClamp[0]), 0.0, 1.0);\n    fragColor = texture2D(palette, vec2((clampedColorIndex * 255.0 + 0.5) / 256.0, 0.5));\n}\n"]);
var pickVertexShaderSource = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n               p4, p5, p6, p7,\n               p8, p9, pa, pb,\n               pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n             loA, hiA, loB, hiB, loC, hiC, loD, hiD;\n\nuniform vec2 resolution,\n             viewBoxPosition,\n             viewBoxSize;\n\nuniform sampler2D mask;\nuniform float maskHeight;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec4 unit_1 = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n    return dot(matrixCompMult(p, v) * unit_1, unit_1);\n}\n\nfloat axisY(\n        float x,\n        mat4 d[4],\n        mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n    ) {\n\n    float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n    float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n    return y1 * (1.0 - x) + y2 * x;\n}\n\nconst int bitsPerByte = 8;\n\nint mod2(int a) {\n    return a - 2 * (a / 2);\n}\n\nint mod8(int a) {\n    return a - 8 * (a / 8);\n}\n\nvec4 zero = vec4(0, 0, 0, 0);\nvec4 unit_0 = vec4(1, 1, 1, 1);\nvec2 xyProjection = vec2(1, 1);\n\nmat4 mclamp(mat4 m, mat4 lo, mat4 hi) {\n    return mat4(clamp(m[0], lo[0], hi[0]),\n                clamp(m[1], lo[1], hi[1]),\n                clamp(m[2], lo[2], hi[2]),\n                clamp(m[3], lo[3], hi[3]));\n}\n\nbool mshow(mat4 p, mat4 lo, mat4 hi) {\n    return mclamp(p, lo, hi) == p;\n}\n\nbool withinBoundingBox(\n        mat4 d[4],\n        mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD\n    ) {\n\n    return mshow(d[0], loA, hiA) &&\n           mshow(d[1], loB, hiB) &&\n           mshow(d[2], loC, hiC) &&\n           mshow(d[3], loD, hiD);\n}\n\nbool withinRasterMask(mat4 d[4], sampler2D mask, float height) {\n    bool result = true;\n    int bitInByteStepper;\n    float valY, valueY, scaleX;\n    int hit, bitmask, valX;\n    for(int i = 0; i < 4; i++) {\n        for(int j = 0; j < 4; j++) {\n            for(int k = 0; k < 4; k++) {\n                bitInByteStepper = mod8(j * 4 + k);\n                valX = i * 2 + j / 2;\n                valY = d[i][j][k];\n                valueY = valY * (height - 1.0) + 0.5;\n                scaleX = (float(valX) + 0.5) / 8.0;\n                hit = int(texture2D(mask, vec2(scaleX, (valueY + 0.5) / height))[3] * 255.0) / int(pow(2.0, float(bitInByteStepper)));\n                result = result && mod2(hit) == 1;\n            }\n        }\n    }\n    return result;\n}\n\nvec4 position(\n        float depth,\n        vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n        mat4 dims[4],\n        float signum,\n        mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D,\n        mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD,\n        sampler2D mask, float maskHeight\n    ) {\n\n    float x = 0.5 * signum + 0.5;\n    float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n    float show = float(\n                            withinBoundingBox(dims, loA, hiA, loB, hiB, loC, hiC, loD, hiD)\n                         && withinRasterMask(dims, mask, maskHeight)\n                      );\n\n    vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n    float depthOrHide = depth + 2.0 * (1.0 - show);\n\n    return vec4(\n        xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n        depthOrHide,\n        1.0\n    );\n}\n\nvoid main() {\n\n    float prominence = abs(pf[3]);\n\n    mat4 p[4];\n    p[0] = mat4(p0, p1, p2, p3);\n    p[1] = mat4(p4, p5, p6, p7);\n    p[2] = mat4(p8, p9, pa, pb);\n    p[3] = mat4(pc, pd, pe, abs(pf));\n\n    gl_Position = position(\n        1.0 - prominence,\n        resolution, viewBoxPosition, viewBoxSize,\n        p,\n        sign(pf[3]),\n        dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n        loA, hiA, loB, hiB, loC, hiC, loD, hiD,\n        mask, maskHeight\n    );\n\n    fragColor = vec4(pf.rgb, 1.0);\n}\n"]);
var fragmentShaderSource = glslify(["precision lowp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n    gl_FragColor = fragColor;\n}\n"]);

var Lib = _dereq_('../../lib');

// don't change; otherwise near/far plane lines are lost
var depthLimitEpsilon = 1e-6;
// just enough buffer for an extra bit at single-precision floating point
// which on [0, 1] is 6e-8 (1/2^24)
var filterEpsilon = 1e-7;

// precision of multiselect is the full range divided into this many parts
var maskHeight = 2048;

var gpuDimensionCount = 64;
var sectionVertexCount = 2;
var vec4NumberCount = 4;
var bitsPerByte = 8;
var channelCount = gpuDimensionCount / bitsPerByte; // == 8 bytes needed to have 64 bits

var contextColor = [119, 119, 119]; // middle gray to not drawn the focus; looks good on a black or white background

var dummyPixel = new Uint8Array(4);
var pickPixel = new Uint8Array(4);

var paletteTextureConfig = {
    shape: [256, 1],
    format: 'rgba',
    type: 'uint8',
    mag: 'nearest',
    min: 'nearest'
};

function ensureDraw(regl) {
    regl.read({
        x: 0,
        y: 0,
        width: 1,
        height: 1,
        data: dummyPixel
    });
}

function clear(regl, x, y, width, height) {
    var gl = regl._gl;
    gl.enable(gl.SCISSOR_TEST);
    gl.scissor(x, y, width, height);
    regl.clear({color: [0, 0, 0, 0], depth: 1}); // clearing is done in scissored panel only
}

function renderBlock(regl, glAes, renderState, blockLineCount, sampleCount, item) {

    var rafKey = item.key;

    function render(blockNumber) {

        var count;

        count = Math.min(blockLineCount, sampleCount - blockNumber * blockLineCount);

        item.offset = sectionVertexCount * blockNumber * blockLineCount;
        item.count = sectionVertexCount * count;
        if(blockNumber === 0) {
            // stop drawing possibly stale glyphs before clearing
            window.cancelAnimationFrame(renderState.currentRafs[rafKey]);
            delete renderState.currentRafs[rafKey];
            clear(regl, item.scissorX, item.scissorY, item.scissorWidth, item.viewBoxSize[1]);
        }

        if(renderState.clearOnly) {
            return;
        }

        glAes(item);

        if(blockNumber * blockLineCount + count < sampleCount) {
            renderState.currentRafs[rafKey] = window.requestAnimationFrame(function() {
                render(blockNumber + 1);
            });
        }

        renderState.drawCompleted = false;
    }

    if(!renderState.drawCompleted) {
        ensureDraw(regl);
        renderState.drawCompleted = true;
    }

    // start with rendering item 0; recursion handles the rest
    render(0);
}

function adjustDepth(d) {
    // WebGL matrix operations use floats with limited precision, potentially causing a number near a border of [0, 1]
    // to end up slightly outside the border. With an epsilon, we reduce the chance that a line gets clipped by the
    // near or the far plane.
    return Math.max(depthLimitEpsilon, Math.min(1 - depthLimitEpsilon, d));
}

function palette(unitToColor, context, opacity) {
    var result = [];
    for(var j = 0; j < 256; j++) {
        var c = unitToColor(j / 255);
        result.push((context ? contextColor : c).concat(opacity));
    }

    return result;
}

// Maps the sample index [0...sampleCount - 1] to a range of [0, 1] as the shader expects colors in the [0, 1] range.
// but first it shifts the sample index by 0, 8 or 16 bits depending on rgbIndex [0..2]
// with the end result that each line will be of a unique color, making it possible for the pick handler
// to uniquely identify which line is hovered over (bijective mapping).
// The inverse, i.e. readPixel is invoked from 'parcoords.js'
function calcPickColor(j, rgbIndex) {
    return (j >>> 8 * rgbIndex) % 256 / 255;
}

function makePoints(sampleCount, dimensions, color) {
    var dimensionCount = dimensions.length;

    var points = [];
    for(var j = 0; j < sampleCount; j++) {
        for(var i = 0; i < gpuDimensionCount; i++) {
            points.push(i < dimensionCount ?
                dimensions[i].paddedUnitValues[j] :
                i === (gpuDimensionCount - 1) ?
                    adjustDepth(color[j]) :
                    i >= gpuDimensionCount - 4 ?
                        calcPickColor(j, gpuDimensionCount - 2 - i) :
                        0.5);
        }
    }

    return points;
}

function makeVecAttr(sampleCount, points, vecIndex) {
    var i, j, k;
    var pointPairs = [];

    for(j = 0; j < sampleCount; j++) {
        for(k = 0; k < sectionVertexCount; k++) {
            for(i = 0; i < vec4NumberCount; i++) {
                pointPairs.push(points[j * gpuDimensionCount + vecIndex * vec4NumberCount + i]);
                if(vecIndex * vec4NumberCount + i === gpuDimensionCount - 1 && k % 2 === 0) {
                    pointPairs[pointPairs.length - 1] *= -1;
                }
            }
        }
    }

    return pointPairs;
}

function setAttributes(attributes, sampleCount, points) {
    for(var i = 0; i < 16; i++) {
        attributes['p' + i.toString(16)](makeVecAttr(sampleCount, points, i));
    }
}

function emptyAttributes(regl) {
    var attributes = {};
    for(var i = 0; i < 16; i++) {
        attributes['p' + i.toString(16)] = regl.buffer({usage: 'dynamic', type: 'float', data: new Uint8Array(0)});
    }
    return attributes;
}

module.exports = function(canvasGL, d) {
    // context & pick describe which canvas we're talking about - won't change with new data
    var context = d.context;
    var pick = d.pick;

    var regl = d.regl;

    var renderState = {
        currentRafs: {},
        drawCompleted: true,
        clearOnly: false
    };

    // state to be set by update and used later
    var model;
    var vm;
    var initialDims;
    var sampleCount;
    var attributes = emptyAttributes(regl);
    var maskTexture;
    var paletteTexture = regl.texture(paletteTextureConfig);

    update(d);

    var glAes = regl({

        profile: false,

        blend: {
            enable: context,
            func: {
                srcRGB: 'src alpha',
                dstRGB: 'one minus src alpha',
                srcAlpha: 1,
                dstAlpha: 1 // 'one minus src alpha'
            },
            equation: {
                rgb: 'add',
                alpha: 'add'
            },
            color: [0, 0, 0, 0]
        },

        depth: {
            enable: !context,
            mask: true,
            func: 'less',
            range: [0, 1]
        },

        // for polygons
        cull: {
            enable: true,
            face: 'back'
        },

        scissor: {
            enable: true,
            box: {
                x: regl.prop('scissorX'),
                y: regl.prop('scissorY'),
                width: regl.prop('scissorWidth'),
                height: regl.prop('scissorHeight')
            }
        },

        viewport: {
            x: regl.prop('viewportX'),
            y: regl.prop('viewportY'),
            width: regl.prop('viewportWidth'),
            height: regl.prop('viewportHeight')
        },

        dither: false,

        vert: pick ? pickVertexShaderSource : context ? contextShaderSource : vertexShaderSource,

        frag: fragmentShaderSource,

        primitive: 'lines',
        lineWidth: 1,
        attributes: attributes,
        uniforms: {
            resolution: regl.prop('resolution'),
            viewBoxPosition: regl.prop('viewBoxPosition'),
            viewBoxSize: regl.prop('viewBoxSize'),
            dim1A: regl.prop('dim1A'),
            dim2A: regl.prop('dim2A'),
            dim1B: regl.prop('dim1B'),
            dim2B: regl.prop('dim2B'),
            dim1C: regl.prop('dim1C'),
            dim2C: regl.prop('dim2C'),
            dim1D: regl.prop('dim1D'),
            dim2D: regl.prop('dim2D'),
            loA: regl.prop('loA'),
            hiA: regl.prop('hiA'),
            loB: regl.prop('loB'),
            hiB: regl.prop('hiB'),
            loC: regl.prop('loC'),
            hiC: regl.prop('hiC'),
            loD: regl.prop('loD'),
            hiD: regl.prop('hiD'),
            palette: paletteTexture,
            mask: regl.prop('maskTexture'),
            maskHeight: regl.prop('maskHeight'),
            colorClamp: regl.prop('colorClamp')
        },
        offset: regl.prop('offset'),
        count: regl.prop('count')
    });

    function update(dNew) {
        model = dNew.model;
        vm = dNew.viewModel;
        initialDims = vm.dimensions.slice();
        sampleCount = initialDims[0] ? initialDims[0].values.length : 0;

        var lines = model.lines;
        var color = pick ? lines.color.map(function(_, i) {return i / lines.color.length;}) : lines.color;
        var contextOpacity = Math.max(1 / 255, Math.pow(1 / color.length, 1 / 3));

        var points = makePoints(sampleCount, initialDims, color);
        setAttributes(attributes, sampleCount, points);

        paletteTexture = regl.texture(Lib.extendFlat({
            data: palette(model.unitToColor, context, Math.round((context ? contextOpacity : 1) * 255))
        }, paletteTextureConfig));
    }

    var colorClamp = [0, 1];

    function setColorDomain(unitDomain) {
        colorClamp[0] = unitDomain[0];
        colorClamp[1] = unitDomain[1];
    }

    var previousAxisOrder = [];

    function makeItem(i, ii, x, y, panelSizeX, canvasPanelSizeY, crossfilterDimensionIndex, I, leftmost, rightmost, constraints) {
        var loHi, abcd, d, index;
        var leftRight = [i, ii];

        var dims = [0, 1].map(function() {return [0, 1, 2, 3].map(function() {return new Float32Array(16);});});

        for(loHi = 0; loHi < 2; loHi++) {
            index = leftRight[loHi];
            for(abcd = 0; abcd < 4; abcd++) {
                for(d = 0; d < 16; d++) {
                    dims[loHi][abcd][d] = d + 16 * abcd === index ? 1 : 0;
                }
            }
        }

        var overdrag = model.lines.canvasOverdrag;
        var domain = model.domain;
        var canvasWidth = model.canvasWidth;
        var canvasHeight = model.canvasHeight;

        var itemModel = Lib.extendFlat({
            key: crossfilterDimensionIndex,
            resolution: [canvasWidth, canvasHeight],
            viewBoxPosition: [x + overdrag, y],
            viewBoxSize: [panelSizeX, canvasPanelSizeY],
            i: i,
            ii: ii,

            dim1A: dims[0][0],
            dim1B: dims[0][1],
            dim1C: dims[0][2],
            dim1D: dims[0][3],
            dim2A: dims[1][0],
            dim2B: dims[1][1],
            dim2C: dims[1][2],
            dim2D: dims[1][3],

            colorClamp: colorClamp,

            scissorX: (I === leftmost ? 0 : x + overdrag) + (model.pad.l - overdrag) + model.layoutWidth * domain.x[0],
            scissorWidth: (I === rightmost ? canvasWidth - x + overdrag : panelSizeX + 0.5) + (I === leftmost ? x + overdrag : 0),
            scissorY: y + model.pad.b + model.layoutHeight * domain.y[0],
            scissorHeight: canvasPanelSizeY,

            viewportX: model.pad.l - overdrag + model.layoutWidth * domain.x[0],
            viewportY: model.pad.b + model.layoutHeight * domain.y[0],
            viewportWidth: canvasWidth,
            viewportHeight: canvasHeight
        }, constraints);

        return itemModel;
    }

    function makeConstraints() {
        var loHi, abcd, d;

        var lims = [0, 1].map(function() {return [0, 1, 2, 3].map(function() {return new Float32Array(16);});});

        for(loHi = 0; loHi < 2; loHi++) {
            for(abcd = 0; abcd < 4; abcd++) {
                for(d = 0; d < 16; d++) {
                    var dimP = d + 16 * abcd;
                    var lim;
                    if(dimP < initialDims.length) {
                        lim = initialDims[dimP].brush.filter.getBounds()[loHi];
                    }
                    else lim = loHi;
                    lims[loHi][abcd][d] = lim + (2 * loHi - 1) * filterEpsilon;
                }
            }
        }

        function expandedPixelRange(dim, bounds) {
            var maskHMinus = maskHeight - 1;
            return [
                Math.max(0, Math.floor(bounds[0] * maskHMinus)),
                Math.min(maskHMinus, Math.ceil(bounds[1] * maskHMinus))
            ];
        }

        var mask = Array.apply(null, new Array(maskHeight * channelCount)).map(function() {
            return 255;
        });
        for(var dimIndex = 0; dimIndex < initialDims.length; dimIndex++) {
            var bitIndex = dimIndex % bitsPerByte;
            var byteIndex = (dimIndex - bitIndex) / bitsPerByte;
            var bitMask = Math.pow(2, bitIndex);
            var dim = initialDims[dimIndex];
            var ranges = dim.brush.filter.get();
            if(ranges.length < 2) continue; // bail if the bounding box based filter is sufficient

            var prevEnd = expandedPixelRange(dim, ranges[0])[1];
            for(var ri = 1; ri < ranges.length; ri++) {
                var nextRange = expandedPixelRange(dim, ranges[ri]);
                for(var pi = prevEnd + 1; pi < nextRange[0]; pi++) {
                    mask[pi * channelCount + byteIndex] &= ~bitMask;
                }
                prevEnd = Math.max(prevEnd, nextRange[1]);
            }
        }

        var textureData = {
            // 8 units x 8 bits = 64 bits, just sufficient for the almost 64 dimensions we support
            shape: [channelCount, maskHeight],
            format: 'alpha',
            type: 'uint8',
            mag: 'nearest',
            min: 'nearest',
            data: mask
        };
        if(maskTexture) maskTexture(textureData);
        else maskTexture = regl.texture(textureData);

        return {
            maskTexture: maskTexture,
            maskHeight: maskHeight,
            loA: lims[0][0],
            loB: lims[0][1],
            loC: lims[0][2],
            loD: lims[0][3],
            hiA: lims[1][0],
            hiB: lims[1][1],
            hiC: lims[1][2],
            hiD: lims[1][3]
        };
    }

    function renderGLParcoords(panels, setChanged, clearOnly) {
        var panelCount = panels.length;
        var I;

        var leftmost;
        var rightmost;
        var lowestX = Infinity;
        var highestX = -Infinity;

        for(I = 0; I < panelCount; I++) {
            if(panels[I].dim2.canvasX > highestX) {
                highestX = panels[I].dim2.canvasX;
                rightmost = I;
            }
            if(panels[I].dim1.canvasX < lowestX) {
                lowestX = panels[I].dim1.canvasX;
                leftmost = I;
            }
        }

        if(panelCount === 0) {
            // clear canvas here, as the panel iteration below will not enter the loop body
            clear(regl, 0, 0, model.canvasWidth, model.canvasHeight);
        }
        var constraints = context ? {} : makeConstraints();

        for(I = 0; I < panelCount; I++) {
            var panel = panels[I];
            var dim1 = panel.dim1;
            var i = dim1.crossfilterDimensionIndex;
            var x = panel.canvasX;
            var y = panel.canvasY;
            var dim2 = panel.dim2;
            var ii = dim2.crossfilterDimensionIndex;
            var panelSizeX = panel.panelSizeX;
            var panelSizeY = panel.panelSizeY;
            var xTo = x + panelSizeX;
            if(setChanged || !previousAxisOrder[i] || previousAxisOrder[i][0] !== x || previousAxisOrder[i][1] !== xTo) {
                previousAxisOrder[i] = [x, xTo];
                var item = makeItem(i, ii, x, y, panelSizeX, panelSizeY, dim1.crossfilterDimensionIndex, I, leftmost, rightmost, constraints);
                renderState.clearOnly = clearOnly;
                renderBlock(regl, glAes, renderState, setChanged ? model.lines.blockLineCount : sampleCount, sampleCount, item);
            }
        }
    }

    function readPixel(canvasX, canvasY) {
        regl.read({
            x: canvasX,
            y: canvasY,
            width: 1,
            height: 1,
            data: pickPixel
        });
        return pickPixel;
    }

    function readPixels(canvasX, canvasY, width, height) {
        var pixelArray = new Uint8Array(4 * width * height);
        regl.read({
            x: canvasX,
            y: canvasY,
            width: width,
            height: height,
            data: pixelArray
        });
        return pixelArray;
    }

    function destroy() {
        canvasGL.style['pointer-events'] = 'none';
        paletteTexture.destroy();
        if(maskTexture) maskTexture.destroy();
        for(var k in attributes) attributes[k].destroy();
    }

    return {
        setColorDomain: setColorDomain,
        render: renderGLParcoords,
        readPixel: readPixel,
        readPixels: readPixels,
        destroy: destroy,
        update: update
    };
};

},{"../../lib":697,"glslify":398}],1020:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * mergeLength: set trace length as the minimum of all dimension data lengths
 *     and propagates this length into each dimension
 *
 * @param {object} traceOut: the fullData trace
 * @param {Array(object)} dimensions: array of dimension objects
 * @param {string} dataAttr: the attribute of each dimension containing the data
 * @param {integer} len: an already-existing length from other attributes
 */
module.exports = function(traceOut, dimensions, dataAttr, len) {
    if(!len) len = Infinity;
    var i, dimi;
    for(i = 0; i < dimensions.length; i++) {
        dimi = dimensions[i];
        if(dimi.visible) len = Math.min(len, dimi[dataAttr].length);
    }
    if(len === Infinity) len = 0;

    traceOut._length = len;
    for(i = 0; i < dimensions.length; i++) {
        dimi = dimensions[i];
        if(dimi.visible) dimi._length = len;
    }

    return len;
};

},{}],1021:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Lib = _dereq_('../../lib');
var Drawing = _dereq_('../../components/drawing');
var Colorscale = _dereq_('../../components/colorscale');

var gup = _dereq_('../../lib/gup');
var keyFun = gup.keyFun;
var repeat = gup.repeat;
var unwrap = gup.unwrap;

var c = _dereq_('./constants');
var brush = _dereq_('./axisbrush');
var lineLayerMaker = _dereq_('./lines');

function visible(dimension) { return !('visible' in dimension) || dimension.visible; }

function dimensionExtent(dimension) {

    var lo = dimension.range ? dimension.range[0] : Lib.aggNums(Math.min, null, dimension.values, dimension._length);
    var hi = dimension.range ? dimension.range[1] : Lib.aggNums(Math.max, null, dimension.values, dimension._length);

    if(isNaN(lo) || !isFinite(lo)) {
        lo = 0;
    }

    if(isNaN(hi) || !isFinite(hi)) {
        hi = 0;
    }

    // avoid a degenerate (zero-width) domain
    if(lo === hi) {
        if(lo === 0) {
            // no use to multiplying zero, so add/subtract in this case
            lo -= 1;
            hi += 1;
        } else {
            // this keeps the range in the order of magnitude of the data
            lo *= 0.9;
            hi *= 1.1;
        }
    }

    return [lo, hi];
}

function toText(formatter, texts) {
    if(texts) {
        return function(v, i) {
            var text = texts[i];
            if(text === null || text === undefined) return formatter(v);
            return text;
        };
    }
    return formatter;
}

function domainScale(height, padding, dimension, tickvals, ticktext) {
    var extent = dimensionExtent(dimension);
    if(tickvals) {
        return d3.scale.ordinal()
            .domain(tickvals.map(toText(d3.format(dimension.tickformat), ticktext)))
            .range(tickvals
                .map(function(d) {
                    var unitVal = (d - extent[0]) / (extent[1] - extent[0]);
                    return (height - padding + unitVal * (2 * padding - height));
                })
            );
    }
    return d3.scale.linear()
        .domain(extent)
        .range([height - padding, padding]);
}

function unitToPaddedPx(height, padding) { return d3.scale.linear().range([padding, height - padding]); }

function domainToPaddedUnitScale(dimension, padFraction) {
    return d3.scale.linear()
        .domain(dimensionExtent(dimension))
        .range([padFraction, 1 - padFraction]);
}

function ordinalScale(dimension) {
    if(!dimension.tickvals) return;

    var extent = dimensionExtent(dimension);
    return d3.scale.ordinal()
        .domain(dimension.tickvals)
        .range(dimension.tickvals.map(function(d) {
            return (d - extent[0]) / (extent[1] - extent[0]);
        }));
}

function unitToColorScale(cscale) {

    var colorStops = cscale.map(function(d) { return d[0]; });
    var colorTuples = cscale.map(function(d) { return d3.rgb(d[1]); });
    var prop = function(n) { return function(o) { return o[n]; }; };

    // We can't use d3 color interpolation as we may have non-uniform color palette raster
    // (various color stop distances).
    var polylinearUnitScales = 'rgb'.split('').map(function(key) {
        return d3.scale.linear()
            .clamp(true)
            .domain(colorStops)
            .range(colorTuples.map(prop(key)));
    });

    return function(d) {
        return polylinearUnitScales.map(function(s) {
            return s(d);
        });
    };
}

function someFiltersActive(view) {
    return view.dimensions.some(function(p) {
        return p.brush.filterSpecified;
    });
}

function model(layout, d, i) {
    var cd0 = unwrap(d);
    var trace = cd0.trace;
    var lineColor = cd0.lineColor;
    var line = trace.line;
    var cscale = line.reversescale ? Colorscale.flipScale(cd0.cscale) : cd0.cscale;
    var domain = trace.domain;
    var dimensions = trace.dimensions;
    var width = layout.width;
    var labelFont = trace.labelfont;
    var tickFont = trace.tickfont;
    var rangeFont = trace.rangefont;

    var lines = Lib.extendDeepNoArrays({}, line, {
        color: lineColor.map(d3.scale.linear().domain(dimensionExtent({
            values: lineColor,
            range: [line.cmin, line.cmax],
            _length: trace._length
        }))),
        blockLineCount: c.blockLineCount,
        canvasOverdrag: c.overdrag * c.canvasPixelRatio
    });

    var groupWidth = Math.floor(width * (domain.x[1] - domain.x[0]));
    var groupHeight = Math.floor(layout.height * (domain.y[1] - domain.y[0]));

    var pad = layout.margin || {l: 80, r: 80, t: 100, b: 80};
    var rowContentWidth = groupWidth;
    var rowHeight = groupHeight;

    return {
        key: i,
        colCount: dimensions.filter(visible).length,
        dimensions: dimensions,
        tickDistance: c.tickDistance,
        unitToColor: unitToColorScale(cscale),
        lines: lines,
        labelFont: labelFont,
        tickFont: tickFont,
        rangeFont: rangeFont,
        layoutWidth: width,
        layoutHeight: layout.height,
        domain: domain,
        translateX: domain.x[0] * width,
        translateY: layout.height - domain.y[1] * layout.height,
        pad: pad,
        canvasWidth: rowContentWidth * c.canvasPixelRatio + 2 * lines.canvasOverdrag,
        canvasHeight: rowHeight * c.canvasPixelRatio,
        width: rowContentWidth,
        height: rowHeight,
        canvasPixelRatio: c.canvasPixelRatio
    };
}

function viewModel(state, callbacks, model) {

    var width = model.width;
    var height = model.height;
    var dimensions = model.dimensions;
    var canvasPixelRatio = model.canvasPixelRatio;

    var xScale = function(d) {return width * d / Math.max(1, model.colCount - 1);};

    var unitPad = c.verticalPadding / height;
    var _unitToPaddedPx = unitToPaddedPx(height, c.verticalPadding);

    var viewModel = {
        key: model.key,
        xScale: xScale,
        model: model,
        inBrushDrag: false // consider factoring it out and putting it in a centralized global-ish gesture state object
    };

    var uniqueKeys = {};

    viewModel.dimensions = dimensions.filter(visible).map(function(dimension, i) {
        var domainToPaddedUnit = domainToPaddedUnitScale(dimension, unitPad);
        var foundKey = uniqueKeys[dimension.label];
        uniqueKeys[dimension.label] = (foundKey || 0) + 1;
        var key = dimension.label + (foundKey ? '__' + foundKey : '');
        var specifiedConstraint = dimension.constraintrange;
        var filterRangeSpecified = specifiedConstraint && specifiedConstraint.length;
        if(filterRangeSpecified && !Array.isArray(specifiedConstraint[0])) {
            specifiedConstraint = [specifiedConstraint];
        }
        var filterRange = filterRangeSpecified ?
            specifiedConstraint.map(function(d) { return d.map(domainToPaddedUnit); }) :
            [[0, 1]];
        var brushMove = function() {
            var p = viewModel;
            p.focusLayer && p.focusLayer.render(p.panels, true);
            var filtersActive = someFiltersActive(p);
            if(!state.contextShown() && filtersActive) {
                p.contextLayer && p.contextLayer.render(p.panels, true);
                state.contextShown(true);
            } else if(state.contextShown() && !filtersActive) {
                p.contextLayer && p.contextLayer.render(p.panels, true, true);
                state.contextShown(false);
            }
        };

        var truncatedValues = dimension.values;
        if(truncatedValues.length > dimension._length) {
            truncatedValues = truncatedValues.slice(0, dimension._length);
        }

        var tickvals = dimension.tickvals;
        var ticktext;
        function makeTickItem(v, i) { return {val: v, text: ticktext[i]}; }
        function sortTickItem(a, b) { return a.val - b.val; }
        if(Array.isArray(tickvals) && tickvals.length) {
            ticktext = dimension.ticktext;

            // ensure ticktext and tickvals have same length
            if(!Array.isArray(ticktext) || !ticktext.length) {
                ticktext = tickvals.map(d3.format(dimension.tickformat));
            }
            else if(ticktext.length > tickvals.length) {
                ticktext = ticktext.slice(0, tickvals.length);
            }
            else if(tickvals.length > ticktext.length) {
                tickvals = tickvals.slice(0, ticktext.length);
            }

            // check if we need to sort tickvals/ticktext
            for(var j = 1; j < tickvals.length; j++) {
                if(tickvals[j] < tickvals[j - 1]) {
                    var tickItems = tickvals.map(makeTickItem).sort(sortTickItem);
                    for(var k = 0; k < tickvals.length; k++) {
                        tickvals[k] = tickItems[k].val;
                        ticktext[k] = tickItems[k].text;
                    }
                    break;
                }
            }
        }
        else tickvals = undefined;

        return {
            key: key,
            label: dimension.label,
            tickFormat: dimension.tickformat,
            tickvals: tickvals,
            ticktext: ticktext,
            ordinal: !!tickvals,
            multiselect: dimension.multiselect,
            xIndex: i,
            crossfilterDimensionIndex: i,
            visibleIndex: dimension._index,
            height: height,
            values: truncatedValues,
            paddedUnitValues: truncatedValues.map(domainToPaddedUnit),
            unitTickvals: tickvals && tickvals.map(domainToPaddedUnit),
            xScale: xScale,
            x: xScale(i),
            canvasX: xScale(i) * canvasPixelRatio,
            unitToPaddedPx: _unitToPaddedPx,
            domainScale: domainScale(height, c.verticalPadding, dimension, tickvals, ticktext),
            ordinalScale: ordinalScale(dimension),
            parent: viewModel,
            model: model,
            brush: brush.makeBrush(
                state,
                filterRangeSpecified,
                filterRange,
                function() {
                    state.linePickActive(false);
                },
                brushMove,
                function(f) {
                    var p = viewModel;
                    p.focusLayer.render(p.panels, true);
                    p.pickLayer && p.pickLayer.render(p.panels, true);
                    state.linePickActive(true);
                    if(callbacks && callbacks.filterChanged) {
                        var invScale = domainToPaddedUnit.invert;

                        // update gd.data as if a Plotly.restyle were fired
                        var newRanges = f.map(function(r) {
                            return r.map(invScale).sort(Lib.sorterAsc);
                        }).sort(function(a, b) { return a[0] - b[0]; });
                        callbacks.filterChanged(p.key, dimension._index, newRanges);
                    }
                }
            )
        };
    });

    return viewModel;
}

function styleExtentTexts(selection) {
    selection
        .classed(c.cn.axisExtentText, true)
        .attr('text-anchor', 'middle')
        .style('cursor', 'default')
        .style('user-select', 'none');
}

function parcoordsInteractionState() {
    var linePickActive = true;
    var contextShown = false;
    return {
        linePickActive: function(val) {return arguments.length ? linePickActive = !!val : linePickActive;},
        contextShown: function(val) {return arguments.length ? contextShown = !!val : contextShown;}
    };
}

module.exports = function(root, svg, parcoordsLineLayers, styledData, layout, callbacks) {

    var state = parcoordsInteractionState();

    var vm = styledData
        .filter(function(d) { return unwrap(d).trace.visible; })
        .map(model.bind(0, layout))
        .map(viewModel.bind(0, state, callbacks));

    parcoordsLineLayers.each(function(d, i) {
        return Lib.extendFlat(d, vm[i]);
    });

    var parcoordsLineLayer = parcoordsLineLayers.selectAll('.gl-canvas')
        .each(function(d) {
            // FIXME: figure out how to handle multiple instances
            d.viewModel = vm[0];
            d.model = d.viewModel ? d.viewModel.model : null;
        });

    var lastHovered = null;

    var pickLayer = parcoordsLineLayer.filter(function(d) {return d.pick;});

    // emit hover / unhover event
    pickLayer
        .style('pointer-events', 'auto')
        .on('mousemove', function(d) {
            if(state.linePickActive() && d.lineLayer && callbacks && callbacks.hover) {
                var event = d3.event;
                var cw = this.width;
                var ch = this.height;
                var pointer = d3.mouse(this);
                var x = pointer[0];
                var y = pointer[1];

                if(x < 0 || y < 0 || x >= cw || y >= ch) {
                    return;
                }
                var pixel = d.lineLayer.readPixel(x, ch - 1 - y);
                var found = pixel[3] !== 0;
                // inverse of the calcPickColor in `lines.js`; detailed comment there
                var curveNumber = found ? pixel[2] + 256 * (pixel[1] + 256 * pixel[0]) : null;
                var eventData = {
                    x: x,
                    y: y,
                    clientX: event.clientX,
                    clientY: event.clientY,
                    dataIndex: d.model.key,
                    curveNumber: curveNumber
                };
                if(curveNumber !== lastHovered) { // don't unnecessarily repeat the same hit (or miss)
                    if(found) {
                        callbacks.hover(eventData);
                    } else if(callbacks.unhover) {
                        callbacks.unhover(eventData);
                    }
                    lastHovered = curveNumber;
                }
            }
        });

    parcoordsLineLayer
        .style('opacity', function(d) {return d.pick ? 0.01 : 1;});

    svg.style('background', 'rgba(255, 255, 255, 0)');
    var parcoordsControlOverlay = svg.selectAll('.' + c.cn.parcoords)
        .data(vm, keyFun);

    parcoordsControlOverlay.exit().remove();

    parcoordsControlOverlay.enter()
        .append('g')
        .classed(c.cn.parcoords, true)
        .style('shape-rendering', 'crispEdges')
        .style('pointer-events', 'none');

    parcoordsControlOverlay.attr('transform', function(d) {
        return 'translate(' + d.model.translateX + ',' + d.model.translateY + ')';
    });

    var parcoordsControlView = parcoordsControlOverlay.selectAll('.' + c.cn.parcoordsControlView)
        .data(repeat, keyFun);

    parcoordsControlView.enter()
        .append('g')
        .classed(c.cn.parcoordsControlView, true);

    parcoordsControlView.attr('transform', function(d) {
        return 'translate(' + d.model.pad.l + ',' + d.model.pad.t + ')';
    });

    var yAxis = parcoordsControlView.selectAll('.' + c.cn.yAxis)
        .data(function(vm) { return vm.dimensions; }, keyFun);

    function updatePanelLayout(yAxis, vm) {
        var panels = vm.panels || (vm.panels = []);
        var dimData = yAxis.data();
        var panelCount = dimData.length - 1;
        for(var p = 0; p < panelCount; p++) {
            var panel = panels[p] || (panels[p] = {});
            var dim1 = dimData[p];
            var dim2 = dimData[p + 1];
            panel.dim1 = dim1;
            panel.dim2 = dim2;
            panel.canvasX = dim1.canvasX;
            panel.panelSizeX = dim2.canvasX - dim1.canvasX;
            panel.panelSizeY = vm.model.canvasHeight;
            panel.y = 0;
            panel.canvasY = 0;
        }
    }

    yAxis.enter()
        .append('g')
        .classed(c.cn.yAxis, true);

    parcoordsControlView.each(function(vm) {
        updatePanelLayout(yAxis, vm);
    });

    parcoordsLineLayer
        .each(function(d) {
            if(d.viewModel) {
                if(!d.lineLayer || callbacks) { // recreate in case of having callbacks e.g. restyle. Should we test for callback to be a restyle?
                    d.lineLayer = lineLayerMaker(this, d);
                } else d.lineLayer.update(d);

                if(d.key || d.key === 0) d.viewModel[d.key] = d.lineLayer;

                var setChanged = (!d.context || // don't update background
                                  callbacks);   // unless there is a callback on the context layer. Should we test the callback?

                d.lineLayer.render(d.viewModel.panels, setChanged);
            }
        });

    yAxis.attr('transform', function(d) {
        return 'translate(' + d.xScale(d.xIndex) + ', 0)';
    });

    // drag column for reordering columns
    yAxis.call(d3.behavior.drag()
        .origin(function(d) { return d; })
        .on('drag', function(d) {
            var p = d.parent;
            state.linePickActive(false);
            d.x = Math.max(-c.overdrag, Math.min(d.model.width + c.overdrag, d3.event.x));
            d.canvasX = d.x * d.model.canvasPixelRatio;
            yAxis
                .sort(function(a, b) { return a.x - b.x; })
                .each(function(dd, i) {
                    dd.xIndex = i;
                    dd.x = d === dd ? dd.x : dd.xScale(dd.xIndex);
                    dd.canvasX = dd.x * dd.model.canvasPixelRatio;
                });

            updatePanelLayout(yAxis, p);

            yAxis.filter(function(dd) { return Math.abs(d.xIndex - dd.xIndex) !== 0; })
                .attr('transform', function(d) { return 'translate(' + d.xScale(d.xIndex) + ', 0)'; });
            d3.select(this).attr('transform', 'translate(' + d.x + ', 0)');
            yAxis.each(function(dd, i, ii) { if(ii === d.parent.key) p.dimensions[i] = dd; });
            p.contextLayer && p.contextLayer.render(p.panels, false, !someFiltersActive(p));
            p.focusLayer.render && p.focusLayer.render(p.panels);
        })
        .on('dragend', function(d) {
            var p = d.parent;
            d.x = d.xScale(d.xIndex);
            d.canvasX = d.x * d.model.canvasPixelRatio;
            updatePanelLayout(yAxis, p);
            d3.select(this)
                .attr('transform', function(d) { return 'translate(' + d.x + ', 0)'; });
            p.contextLayer && p.contextLayer.render(p.panels, false, !someFiltersActive(p));
            p.focusLayer && p.focusLayer.render(p.panels);
            p.pickLayer && p.pickLayer.render(p.panels, true);
            state.linePickActive(true);

            if(callbacks && callbacks.axesMoved) {
                callbacks.axesMoved(p.key, p.dimensions.map(function(dd) {return dd.crossfilterDimensionIndex;}));
            }
        })
    );

    yAxis.exit()
        .remove();

    var axisOverlays = yAxis.selectAll('.' + c.cn.axisOverlays)
        .data(repeat, keyFun);

    axisOverlays.enter()
        .append('g')
        .classed(c.cn.axisOverlays, true);

    axisOverlays.selectAll('.' + c.cn.axis).remove();

    var axis = axisOverlays.selectAll('.' + c.cn.axis)
        .data(repeat, keyFun);

    axis.enter()
        .append('g')
        .classed(c.cn.axis, true);

    axis
        .each(function(d) {
            var wantedTickCount = d.model.height / d.model.tickDistance;
            var scale = d.domainScale;
            var sdom = scale.domain();
            d3.select(this)
                .call(d3.svg.axis()
                    .orient('left')
                    .tickSize(4)
                    .outerTickSize(2)
                    .ticks(wantedTickCount, d.tickFormat) // works for continuous scales only...
                    .tickValues(d.ordinal ? // and this works for ordinal scales
                        sdom :
                        null)
                    .tickFormat(d.ordinal ? function(d) { return d; } : null)
                    .scale(scale));
            Drawing.font(axis.selectAll('text'), d.model.tickFont);
        });

    axis.selectAll('.domain, .tick>line')
        .attr('fill', 'none')
        .attr('stroke', 'black')
        .attr('stroke-opacity', 0.25)
        .attr('stroke-width', '1px');

    axis.selectAll('text')
        .style('text-shadow', '1px 1px 1px #fff, -1px -1px 1px #fff, 1px -1px 1px #fff, -1px 1px 1px #fff')
        .style('cursor', 'default')
        .style('user-select', 'none');

    var axisHeading = axisOverlays.selectAll('.' + c.cn.axisHeading)
        .data(repeat, keyFun);

    axisHeading.enter()
        .append('g')
        .classed(c.cn.axisHeading, true);

    var axisTitle = axisHeading.selectAll('.' + c.cn.axisTitle)
        .data(repeat, keyFun);

    axisTitle.enter()
        .append('text')
        .classed(c.cn.axisTitle, true)
        .attr('text-anchor', 'middle')
        .style('cursor', 'ew-resize')
        .style('user-select', 'none')
        .style('pointer-events', 'auto');

    axisTitle
        .attr('transform', 'translate(0,' + -c.axisTitleOffset + ')')
        .text(function(d) { return d.label; })
        .each(function(d) { Drawing.font(d3.select(this), d.model.labelFont); });

    var axisExtent = axisOverlays.selectAll('.' + c.cn.axisExtent)
        .data(repeat, keyFun);

    axisExtent.enter()
        .append('g')
        .classed(c.cn.axisExtent, true);

    var axisExtentTop = axisExtent.selectAll('.' + c.cn.axisExtentTop)
        .data(repeat, keyFun);

    axisExtentTop.enter()
        .append('g')
        .classed(c.cn.axisExtentTop, true);

    axisExtentTop
        .attr('transform', 'translate(' + 0 + ',' + -c.axisExtentOffset + ')');

    var axisExtentTopText = axisExtentTop.selectAll('.' + c.cn.axisExtentTopText)
        .data(repeat, keyFun);

    function extremeText(d, isTop) {
        if(d.ordinal) return '';
        var domain = d.domainScale.domain();
        return d3.format(d.tickFormat)(domain[isTop ? domain.length - 1 : 0]);
    }

    axisExtentTopText.enter()
        .append('text')
        .classed(c.cn.axisExtentTopText, true)
        .call(styleExtentTexts);

    axisExtentTopText
        .text(function(d) { return extremeText(d, true); })
        .each(function(d) { Drawing.font(d3.select(this), d.model.rangeFont); });

    var axisExtentBottom = axisExtent.selectAll('.' + c.cn.axisExtentBottom)
        .data(repeat, keyFun);

    axisExtentBottom.enter()
        .append('g')
        .classed(c.cn.axisExtentBottom, true);

    axisExtentBottom
        .attr('transform', function(d) {
            return 'translate(' + 0 + ',' + (d.model.height + c.axisExtentOffset) + ')';
        });

    var axisExtentBottomText = axisExtentBottom.selectAll('.' + c.cn.axisExtentBottomText)
        .data(repeat, keyFun);

    axisExtentBottomText.enter()
        .append('text')
        .classed(c.cn.axisExtentBottomText, true)
        .attr('dy', '0.75em')
        .call(styleExtentTexts);

    axisExtentBottomText
        .text(function(d) { return extremeText(d); })
        .each(function(d) { Drawing.font(d3.select(this), d.model.rangeFont); });

    brush.ensureAxisBrush(axisOverlays);
};

},{"../../components/colorscale":586,"../../components/drawing":595,"../../lib":697,"../../lib/gup":695,"./axisbrush":1013,"./constants":1016,"./lines":1019,"d3":151}],1022:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var parcoords = _dereq_('./parcoords');
var prepareRegl = _dereq_('../../lib/prepare_regl');

module.exports = function plot(gd, cdparcoords) {
    var fullLayout = gd._fullLayout;
    var svg = fullLayout._toppaper;
    var root = fullLayout._paperdiv;
    var container = fullLayout._glcontainer;

    var success = prepareRegl(gd);
    if(!success) return;

    var gdDimensions = {};
    var gdDimensionsOriginalOrder = {};
    var fullIndices = {};
    var inputIndices = {};

    var size = fullLayout._size;

    cdparcoords.forEach(function(d, i) {
        var trace = d[0].trace;
        fullIndices[i] = trace.index;
        var iIn = inputIndices[i] = trace._fullInput.index;
        gdDimensions[i] = gd.data[iIn].dimensions;
        gdDimensionsOriginalOrder[i] = gd.data[iIn].dimensions.slice();
    });

    var filterChanged = function(i, originalDimensionIndex, newRanges) {

        // Have updated `constraintrange` data on `gd.data` and raise `Plotly.restyle` event
        // without having to incur heavy UI blocking due to an actual `Plotly.restyle` call

        var gdDimension = gdDimensionsOriginalOrder[i][originalDimensionIndex];
        var newConstraints = newRanges.map(function(r) { return r.slice(); });

        // Store constraint range in preGUI
        // This one doesn't work if it's stored in pieces in _storeDirectGUIEdit
        // because it's an array of variable dimensionality. So store the whole
        // thing at once manually.
        var aStr = 'dimensions[' + originalDimensionIndex + '].constraintrange';
        var preGUI = fullLayout._tracePreGUI[gd._fullData[fullIndices[i]]._fullInput.uid];
        if(preGUI[aStr] === undefined) {
            var initialVal = gdDimension.constraintrange;
            preGUI[aStr] = initialVal || null;
        }

        var fullDimension = gd._fullData[fullIndices[i]].dimensions[originalDimensionIndex];

        if(!newConstraints.length) {
            delete gdDimension.constraintrange;
            delete fullDimension.constraintrange;
            newConstraints = null;
        }
        else {
            if(newConstraints.length === 1) newConstraints = newConstraints[0];
            gdDimension.constraintrange = newConstraints;
            fullDimension.constraintrange = newConstraints.slice();
            // wrap in another array for restyle event data
            newConstraints = [newConstraints];
        }

        var restyleData = {};
        restyleData[aStr] = newConstraints;
        gd.emit('plotly_restyle', [restyleData, [inputIndices[i]]]);
    };

    var hover = function(eventData) {
        gd.emit('plotly_hover', eventData);
    };

    var unhover = function(eventData) {
        gd.emit('plotly_unhover', eventData);
    };

    var axesMoved = function(i, visibleIndices) {

        // Have updated order data on `gd.data` and raise `Plotly.restyle` event
        // without having to incur heavy UI blocking due to an actual `Plotly.restyle` call

        function visible(dimension) {return !('visible' in dimension) || dimension.visible;}

        function newIdx(visibleIndices, orig, dim) {
            var origIndex = orig.indexOf(dim);
            var currentIndex = visibleIndices.indexOf(origIndex);
            if(currentIndex === -1) {
                // invisible dimensions initially go to the end
                currentIndex += orig.length;
            }
            return currentIndex;
        }

        function sorter(orig) {
            return function sorter(d1, d2) {
                var i1 = newIdx(visibleIndices, orig, d1);
                var i2 = newIdx(visibleIndices, orig, d2);
                return i1 - i2;
            };
        }

        // drag&drop sorting of the visible dimensions
        var orig = sorter(gdDimensionsOriginalOrder[i].filter(visible));
        gdDimensions[i].sort(orig);

        // invisible dimensions are not interpreted in the context of drag&drop sorting as an invisible dimension
        // cannot be dragged; they're interspersed into their original positions by this subsequent merging step
        gdDimensionsOriginalOrder[i].filter(function(d) {return !visible(d);})
             .sort(function(d) {
                 // subsequent splicing to be done left to right, otherwise indices may be incorrect
                 return gdDimensionsOriginalOrder[i].indexOf(d);
             })
            .forEach(function(d) {
                gdDimensions[i].splice(gdDimensions[i].indexOf(d), 1); // remove from the end
                gdDimensions[i].splice(gdDimensionsOriginalOrder[i].indexOf(d), 0, d); // insert at original index
            });

        // TODO: we can't really store this part of the interaction state
        // directly as below, since it incudes data arrays. If we want to
        // persist column order we may have to do something special for this
        // case to just store the order itself.
        // Registry.call('_storeDirectGUIEdit',
        //     gd.data[inputIndices[i]],
        //     fullLayout._tracePreGUI[gd._fullData[fullIndices[i]]._fullInput.uid],
        //     {dimensions: gdDimensions[i]}
        // );

        gd.emit('plotly_restyle', [{dimensions: [gdDimensions[i]]}, [inputIndices[i]]]);
    };

    parcoords(
        root,
        svg,
        container,
        cdparcoords,
        {
            width: size.w,
            height: size.h,
            margin: {
                t: size.t,
                r: size.r,
                b: size.b,
                l: size.l
            }
        },
        {
            filterChanged: filterChanged,
            hover: hover,
            unhover: unhover,
            axesMoved: axesMoved
        });
};

},{"../../lib/prepare_regl":710,"./parcoords":1021}],1023:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorAttrs = _dereq_('../../components/color/attributes');
var fontAttrs = _dereq_('../../plots/font_attributes');
var plotAttrs = _dereq_('../../plots/attributes');
var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var domainAttrs = _dereq_('../../plots/domain').attributes;

var extendFlat = _dereq_('../../lib/extend').extendFlat;

var textFontAttrs = fontAttrs({
    editType: 'calc',
    arrayOk: true,
    colorEditType: 'plot',
    
});

module.exports = {
    labels: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    // equivalent of x0 and dx, if label is missing
    label0: {
        valType: 'number',
        
        dflt: 0,
        editType: 'calc',
        
    },
    dlabel: {
        valType: 'number',
        
        dflt: 1,
        editType: 'calc',
        
    },

    values: {
        valType: 'data_array',
        editType: 'calc',
        
    },

    marker: {
        colors: {
            valType: 'data_array',  // TODO 'color_array' ?
            editType: 'calc',
            
        },

        line: {
            color: {
                valType: 'color',
                
                dflt: colorAttrs.defaultLine,
                arrayOk: true,
                editType: 'style',
                
            },
            width: {
                valType: 'number',
                
                min: 0,
                dflt: 0,
                arrayOk: true,
                editType: 'style',
                
            },
            editType: 'calc'
        },
        editType: 'calc'
    },

    text: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    hovertext: {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        editType: 'style',
        
    },

// 'see eg:'
// 'https://www.e-education.psu.edu/natureofgeoinfo/sites/www.e-education.psu.edu.natureofgeoinfo/files/image/hisp_pies.gif',
// '(this example involves a map too - may someday be a whole trace type',
// 'of its own. but the point is the size of the whole pie is important.)'
    scalegroup: {
        valType: 'string',
        
        dflt: '',
        editType: 'calc',
        
    },

    // labels (legend is handled by plots.attributes.showlegend and layout.hiddenlabels)
    textinfo: {
        valType: 'flaglist',
        
        flags: ['label', 'text', 'value', 'percent'],
        extras: ['none'],
        editType: 'calc',
        
    },
    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
        flags: ['label', 'text', 'value', 'percent', 'name']
    }),
    hovertemplate: hovertemplateAttrs({}, {
        keys: ['label', 'color', 'value', 'percent', 'text']
    }),
    textposition: {
        valType: 'enumerated',
        
        values: ['inside', 'outside', 'auto', 'none'],
        dflt: 'auto',
        arrayOk: true,
        editType: 'calc',
        
    },
    textfont: extendFlat({}, textFontAttrs, {
        
    }),
    insidetextfont: extendFlat({}, textFontAttrs, {
        
    }),
    outsidetextfont: extendFlat({}, textFontAttrs, {
        
    }),

    title: {
        text: {
            valType: 'string',
            dflt: '',
            
            editType: 'calc',
            
        },
        font: extendFlat({}, textFontAttrs, {
            
        }),
        position: {
            valType: 'enumerated',
            values: [
                'top left', 'top center', 'top right',
                'middle center',
                'bottom left', 'bottom center', 'bottom right'
            ],
            
            editType: 'calc',
            
        },

        editType: 'calc'
    },

    // position and shape
    domain: domainAttrs({name: 'pie', trace: true, editType: 'calc'}),

    hole: {
        valType: 'number',
        
        min: 0,
        max: 1,
        dflt: 0,
        editType: 'calc',
        
    },

    // ordering and direction
    sort: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'calc',
        
    },
    direction: {
        /**
         * there are two common conventions, both of which place the first
         * (largest, if sorted) slice with its left edge at 12 o'clock but
         * succeeding slices follow either cw or ccw from there.
         *
         * see http://visage.co/data-visualization-101-pie-charts/
         */
        valType: 'enumerated',
        values: ['clockwise', 'counterclockwise'],
        
        dflt: 'counterclockwise',
        editType: 'calc',
        
    },
    rotation: {
        valType: 'number',
        
        min: -360,
        max: 360,
        dflt: 0,
        editType: 'calc',
        
    },

    pull: {
        valType: 'number',
        
        min: 0,
        max: 1,
        dflt: 0,
        arrayOk: true,
        editType: 'calc',
        
    },

    _deprecated: {
        title: {
            valType: 'string',
            dflt: '',
            
            editType: 'calc',
            
        },
        titlefont: extendFlat({}, textFontAttrs, {
            
        }),
        titleposition: {
            valType: 'enumerated',
            values: [
                'top left', 'top center', 'top right',
                'middle center',
                'bottom left', 'bottom center', 'bottom right'
            ],
            
            editType: 'calc',
            
        }
    }
};

},{"../../components/color/attributes":573,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plots/attributes":742,"../../plots/domain":770,"../../plots/font_attributes":771}],1024:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');
var getModuleCalcData = _dereq_('../../plots/get_data').getModuleCalcData;

exports.name = 'pie';

exports.plot = function(gd) {
    var Pie = Registry.getModule('pie');
    var cdPie = getModuleCalcData(gd.calcdata, Pie)[0];

    if(cdPie.length) Pie.plot(gd, cdPie);
};

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var hadPie = (oldFullLayout._has && oldFullLayout._has('pie'));
    var hasPie = (newFullLayout._has && newFullLayout._has('pie'));

    if(hadPie && !hasPie) {
        oldFullLayout._pielayer.selectAll('g.trace').remove();
    }
};

},{"../../plots/get_data":781,"../../registry":826}],1025:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;
var tinycolor = _dereq_('tinycolor2');

var Color = _dereq_('../../components/color');
var helpers = _dereq_('./helpers');

exports.calc = function calc(gd, trace) {
    var vals = trace.values;
    var hasVals = isArrayOrTypedArray(vals) && vals.length;
    var labels = trace.labels;
    var colors = trace.marker.colors || [];
    var cd = [];
    var fullLayout = gd._fullLayout;
    var colorMap = fullLayout._piecolormap;
    var allThisTraceLabels = {};
    var vTotal = 0;
    var hiddenLabels = fullLayout.hiddenlabels || [];

    var i, v, label, hidden, pt;

    if(trace.dlabel) {
        labels = new Array(vals.length);
        for(i = 0; i < vals.length; i++) {
            labels[i] = String(trace.label0 + i * trace.dlabel);
        }
    }

    function pullColor(color, label) {
        if(!color) return false;

        color = tinycolor(color);
        if(!color.isValid()) return false;

        color = Color.addOpacity(color, color.getAlpha());
        if(!colorMap[label]) colorMap[label] = color;

        return color;
    }

    var seriesLen = (hasVals ? vals : labels).length;

    for(i = 0; i < seriesLen; i++) {
        if(hasVals) {
            v = vals[i];
            if(!isNumeric(v)) continue;
            v = +v;
            if(v < 0) continue;
        }
        else v = 1;

        label = labels[i];
        if(label === undefined || label === '') label = i;
        label = String(label);

        var thisLabelIndex = allThisTraceLabels[label];
        if(thisLabelIndex === undefined) {
            allThisTraceLabels[label] = cd.length;

            hidden = hiddenLabels.indexOf(label) !== -1;

            if(!hidden) vTotal += v;

            cd.push({
                v: v,
                label: label,
                color: pullColor(colors[i], label),
                i: i,
                pts: [i],
                hidden: hidden
            });
        }
        else {
            pt = cd[thisLabelIndex];
            pt.v += v;
            pt.pts.push(i);
            if(!pt.hidden) vTotal += v;

            if(pt.color === false && colors[i]) {
                pt.color = pullColor(colors[i], label);
            }
        }
    }

    if(trace.sort) cd.sort(function(a, b) { return b.v - a.v; });

    // include the sum of all values in the first point
    if(cd[0]) cd[0].vTotal = vTotal;

    // now insert text
    if(trace.textinfo && trace.textinfo !== 'none') {
        var hasLabel = trace.textinfo.indexOf('label') !== -1;
        var hasText = trace.textinfo.indexOf('text') !== -1;
        var hasValue = trace.textinfo.indexOf('value') !== -1;
        var hasPercent = trace.textinfo.indexOf('percent') !== -1;
        var separators = fullLayout.separators;

        var thisText;

        for(i = 0; i < cd.length; i++) {
            pt = cd[i];
            thisText = hasLabel ? [pt.label] : [];
            if(hasText) {
                var texti = helpers.getFirstFilled(trace.text, pt.pts);
                if(texti) thisText.push(texti);
            }
            if(hasValue) thisText.push(helpers.formatPieValue(pt.v, separators));
            if(hasPercent) thisText.push(helpers.formatPiePercent(pt.v / vTotal, separators));
            pt.text = thisText.join('<br>');
        }
    }

    return cd;
};

/*
 * `calc` filled in (and collated) explicit colors.
 * Now we need to propagate these explicit colors to other traces,
 * and fill in default colors.
 * This is done after sorting, so we pick defaults
 * in the order slices will be displayed
 */
exports.crossTraceCalc = function(gd) {
    var fullLayout = gd._fullLayout;
    var calcdata = gd.calcdata;
    var pieColorWay = fullLayout.piecolorway;
    var colorMap = fullLayout._piecolormap;

    if(fullLayout.extendpiecolors) {
        pieColorWay = generateExtendedColors(pieColorWay);
    }
    var dfltColorCount = 0;

    var i, j, cd, pt;
    for(i = 0; i < calcdata.length; i++) {
        cd = calcdata[i];
        if(cd[0].trace.type !== 'pie') continue;

        for(j = 0; j < cd.length; j++) {
            pt = cd[j];
            if(pt.color === false) {
                // have we seen this label and assigned a color to it in a previous trace?
                if(colorMap[pt.label]) {
                    pt.color = colorMap[pt.label];
                }
                else {
                    colorMap[pt.label] = pt.color = pieColorWay[dfltColorCount % pieColorWay.length];
                    dfltColorCount++;
                }
            }
        }
    }
};

/**
 * pick a default color from the main default set, augmented by
 * itself lighter then darker before repeating
 */
var extendedColorWays = {};

function generateExtendedColors(colorList) {
    var i;
    var colorString = JSON.stringify(colorList);
    var pieColors = extendedColorWays[colorString];
    if(!pieColors) {
        pieColors = colorList.slice();

        for(i = 0; i < colorList.length; i++) {
            pieColors.push(tinycolor(colorList[i]).lighten(20).toHexString());
        }

        for(i = 0; i < colorList.length; i++) {
            pieColors.push(tinycolor(colorList[i]).darken(20).toHexString());
        }
        extendedColorWays[colorString] = pieColors;
    }

    return pieColors;
}

},{"../../components/color":574,"../../lib":697,"./helpers":1028,"fast-isnumeric":218,"tinycolor2":518}],1026:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var attributes = _dereq_('./attributes');
var handleDomainDefaults = _dereq_('../../plots/domain').defaults;

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var coerceFont = Lib.coerceFont;
    var len;

    var vals = coerce('values');
    var hasVals = Lib.isArrayOrTypedArray(vals);
    var labels = coerce('labels');
    if(Array.isArray(labels)) {
        len = labels.length;
        if(hasVals) len = Math.min(len, vals.length);
    }
    else if(hasVals) {
        len = vals.length;

        coerce('label0');
        coerce('dlabel');
    }

    if(!len) {
        traceOut.visible = false;
        return;
    }
    traceOut._length = len;

    var lineWidth = coerce('marker.line.width');
    if(lineWidth) coerce('marker.line.color');

    coerce('marker.colors');

    coerce('scalegroup');
    // TODO: hole needs to be coerced to the same value within a scaleegroup

    var textData = coerce('text');
    var textInfo = coerce('textinfo', Array.isArray(textData) ? 'text+percent' : 'percent');
    coerce('hovertext');
    coerce('hovertemplate');

    if(textInfo && textInfo !== 'none') {
        var textPosition = coerce('textposition');
        var hasBoth = Array.isArray(textPosition) || textPosition === 'auto';
        var hasInside = hasBoth || textPosition === 'inside';
        var hasOutside = hasBoth || textPosition === 'outside';

        if(hasInside || hasOutside) {
            var dfltFont = coerceFont(coerce, 'textfont', layout.font);
            if(hasInside) {
                var insideTextFontDefault = Lib.extendFlat({}, dfltFont);
                var isTraceTextfontColorSet = traceIn.textfont && traceIn.textfont.color;
                var isColorInheritedFromLayoutFont = !isTraceTextfontColorSet;
                if(isColorInheritedFromLayoutFont) {
                    delete insideTextFontDefault.color;
                }
                coerceFont(coerce, 'insidetextfont', insideTextFontDefault);
            }
            if(hasOutside) coerceFont(coerce, 'outsidetextfont', dfltFont);
        }
    }

    handleDomainDefaults(traceOut, layout, coerce);

    var hole = coerce('hole');
    var title = coerce('title.text');
    if(title) {
        var titlePosition = coerce('title.position', hole ? 'middle center' : 'top center');
        if(!hole && titlePosition === 'middle center') traceOut.title.position = 'top center';
        coerceFont(coerce, 'title.font', layout.font);
    }

    coerce('sort');
    coerce('direction');
    coerce('rotation');

    coerce('pull');
};

},{"../../lib":697,"../../plots/domain":770,"./attributes":1023}],1027:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var appendArrayMultiPointValues = _dereq_('../../components/fx/helpers').appendArrayMultiPointValues;


// Note: like other eventData routines, this creates the data for hover/unhover/click events
// but it has a different API and goes through a totally different pathway.
// So to ensure it doesn't get misused, it's not attached to the Pie module.
module.exports = function eventData(pt, trace) {
    var out = {
        curveNumber: trace.index,
        pointNumbers: pt.pts,
        data: trace._input,
        fullData: trace,
        label: pt.label,
        color: pt.color,
        value: pt.v,
        percent: pt.percent,
        text: pt.text,

        // pt.v (and pt.i below) for backward compatibility
        v: pt.v
    };

    // Only include pointNumber if it's unambiguous
    if(pt.pts.length === 1) out.pointNumber = out.i = pt.pts[0];

    // Add extra data arrays to the output
    // notice that this is the multi-point version ('s' on the end!)
    // so added data will be arrays matching the pointNumbers array.
    appendArrayMultiPointValues(out, trace, pt.pts);

    return out;
};

},{"../../components/fx/helpers":609}],1028:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

exports.formatPiePercent = function formatPiePercent(v, separators) {
    var vRounded = (v * 100).toPrecision(3);
    if(vRounded.lastIndexOf('.') !== -1) {
        vRounded = vRounded.replace(/[.]?0+$/, '');
    }
    return Lib.numSeparate(vRounded, separators) + '%';
};

exports.formatPieValue = function formatPieValue(v, separators) {
    var vRounded = v.toPrecision(10);
    if(vRounded.lastIndexOf('.') !== -1) {
        vRounded = vRounded.replace(/[.]?0+$/, '');
    }
    return Lib.numSeparate(vRounded, separators);
};

exports.getFirstFilled = function getFirstFilled(array, indices) {
    if(!Array.isArray(array)) return;
    for(var i = 0; i < indices.length; i++) {
        var v = array[indices[i]];
        if(v || v === 0) return v;
    }
};

exports.castOption = function castOption(item, indices) {
    if(Array.isArray(item)) return exports.getFirstFilled(item, indices);
    else if(item) return item;
};

},{"../../lib":697}],1029:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Pie = {};

Pie.attributes = _dereq_('./attributes');
Pie.supplyDefaults = _dereq_('./defaults');
Pie.supplyLayoutDefaults = _dereq_('./layout_defaults');
Pie.layoutAttributes = _dereq_('./layout_attributes');

var calcModule = _dereq_('./calc');
Pie.calc = calcModule.calc;
Pie.crossTraceCalc = calcModule.crossTraceCalc;

Pie.plot = _dereq_('./plot');
Pie.style = _dereq_('./style');
Pie.styleOne = _dereq_('./style_one');

Pie.moduleType = 'trace';
Pie.name = 'pie';
Pie.basePlotModule = _dereq_('./base_plot');
Pie.categories = ['pie', 'showLegend'];
Pie.meta = {
    
};

module.exports = Pie;

},{"./attributes":1023,"./base_plot":1024,"./calc":1025,"./defaults":1026,"./layout_attributes":1030,"./layout_defaults":1031,"./plot":1032,"./style":1033,"./style_one":1034}],1030:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    /**
     * hiddenlabels is the pie chart analog of visible:'legendonly'
     * but it can contain many labels, and can hide slices
     * from several pies simultaneously
     */
    hiddenlabels: {
        valType: 'data_array',
        editType: 'calc'
    },
    piecolorway: {
        valType: 'colorlist',
        
        editType: 'calc',
        
    },
    extendpiecolors: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'calc',
        
    }
};

},{}],1031:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

var layoutAttributes = _dereq_('./layout_attributes');

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
    function coerce(attr, dflt) {
        return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
    }
    coerce('hiddenlabels');
    coerce('piecolorway', layoutOut.colorway);
    coerce('extendpiecolors');
};

},{"../../lib":697,"./layout_attributes":1030}],1032:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Fx = _dereq_('../../components/fx');
var Color = _dereq_('../../components/color');
var Drawing = _dereq_('../../components/drawing');
var Lib = _dereq_('../../lib');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');

var helpers = _dereq_('./helpers');
var eventData = _dereq_('./event_data');

module.exports = function plot(gd, cdpie) {
    var fullLayout = gd._fullLayout;

    prerenderTitles(cdpie, gd);
    scalePies(cdpie, fullLayout._size);

    var pieGroups = Lib.makeTraceGroups(fullLayout._pielayer, cdpie, 'trace').each(function(cd) {
        var pieGroup = d3.select(this);
        var cd0 = cd[0];
        var trace = cd0.trace;

        setCoords(cd);

        // TODO: miter might look better but can sometimes cause problems
        // maybe miter with a small-ish stroke-miterlimit?
        pieGroup.attr('stroke-linejoin', 'round');

        pieGroup.each(function() {
            var slices = d3.select(this).selectAll('g.slice').data(cd);

            slices.enter().append('g')
                .classed('slice', true);
            slices.exit().remove();

            var quadrants = [
                [[], []], // y<0: x<0, x>=0
                [[], []] // y>=0: x<0, x>=0
            ];
            var hasOutsideText = false;

            slices.each(function(pt) {
                if(pt.hidden) {
                    d3.select(this).selectAll('path,g').remove();
                    return;
                }

                // to have consistent event data compared to other traces
                pt.pointNumber = pt.i;
                pt.curveNumber = trace.index;

                quadrants[pt.pxmid[1] < 0 ? 0 : 1][pt.pxmid[0] < 0 ? 0 : 1].push(pt);

                var cx = cd0.cx;
                var cy = cd0.cy;
                var sliceTop = d3.select(this);
                var slicePath = sliceTop.selectAll('path.surface').data([pt]);

                // hover state vars
                // have we drawn a hover label, so it should be cleared later
                var hasHoverLabel = false;
                // have we emitted a hover event, so later an unhover event should be emitted
                // note that click events do not depend on this - you can still get them
                // with hovermode: false or if you were earlier dragging, then clicked
                // in the same slice that you moused up in
                var hasHoverEvent = false;

                function handleMouseOver() {
                    // in case fullLayout or fullData has changed without a replot
                    var fullLayout2 = gd._fullLayout;
                    var trace2 = gd._fullData[trace.index];

                    if(gd._dragging || fullLayout2.hovermode === false) return;

                    var hoverinfo = trace2.hoverinfo;
                    if(Array.isArray(hoverinfo)) {
                        // super hacky: we need to pull out the *first* hoverinfo from
                        // pt.pts, then put it back into an array in a dummy trace
                        // and call castHoverinfo on that.
                        // TODO: do we want to have Fx.castHoverinfo somehow handle this?
                        // it already takes an array for index, for 2D, so this seems tricky.
                        hoverinfo = Fx.castHoverinfo({
                            hoverinfo: [helpers.castOption(hoverinfo, pt.pts)],
                            _module: trace._module
                        }, fullLayout2, 0);
                    }

                    if(hoverinfo === 'all') hoverinfo = 'label+text+value+percent+name';

                    // in case we dragged over the pie from another subplot,
                    // or if hover is turned off
                    if(trace2.hovertemplate || (hoverinfo !== 'none' && hoverinfo !== 'skip' && hoverinfo)) {
                        var rInscribed = getInscribedRadiusFraction(pt, cd0);
                        var hoverCenterX = cx + pt.pxmid[0] * (1 - rInscribed);
                        var hoverCenterY = cy + pt.pxmid[1] * (1 - rInscribed);
                        var separators = fullLayout.separators;
                        var thisText = [];

                        if(hoverinfo && hoverinfo.indexOf('label') !== -1) thisText.push(pt.label);
                        pt.text = helpers.castOption(trace2.hovertext || trace2.text, pt.pts);
                        if(hoverinfo && hoverinfo.indexOf('text') !== -1) {
                            var texti = pt.text;
                            if(texti) thisText.push(texti);
                        }
                        pt.value = pt.v;
                        pt.valueLabel = helpers.formatPieValue(pt.v, separators);
                        if(hoverinfo && hoverinfo.indexOf('value') !== -1) thisText.push(pt.valueLabel);
                        pt.percent = pt.v / cd0.vTotal;
                        pt.percentLabel = helpers.formatPiePercent(pt.percent, separators);
                        if(hoverinfo && hoverinfo.indexOf('percent') !== -1) thisText.push(pt.percentLabel);

                        var hoverLabel = trace.hoverlabel;
                        var hoverFont = hoverLabel.font;

                        Fx.loneHover({
                            x0: hoverCenterX - rInscribed * cd0.r,
                            x1: hoverCenterX + rInscribed * cd0.r,
                            y: hoverCenterY,
                            text: thisText.join('<br>'),
                            name: (trace2.hovertemplate || hoverinfo.indexOf('name') !== -1) ? trace2.name : undefined,
                            idealAlign: pt.pxmid[0] < 0 ? 'left' : 'right',
                            color: helpers.castOption(hoverLabel.bgcolor, pt.pts) || pt.color,
                            borderColor: helpers.castOption(hoverLabel.bordercolor, pt.pts),
                            fontFamily: helpers.castOption(hoverFont.family, pt.pts),
                            fontSize: helpers.castOption(hoverFont.size, pt.pts),
                            fontColor: helpers.castOption(hoverFont.color, pt.pts),

                            trace: trace2,
                            hovertemplate: helpers.castOption(trace2.hovertemplate, pt.pts),
                            hovertemplateLabels: pt,
                            eventData: [eventData(pt, trace2)]
                        }, {
                            container: fullLayout2._hoverlayer.node(),
                            outerContainer: fullLayout2._paper.node(),
                            gd: gd
                        });

                        hasHoverLabel = true;
                    }

                    gd.emit('plotly_hover', {
                        points: [eventData(pt, trace2)],
                        event: d3.event
                    });
                    hasHoverEvent = true;
                }

                function handleMouseOut(evt) {
                    var fullLayout2 = gd._fullLayout;
                    var trace2 = gd._fullData[trace.index];

                    if(hasHoverEvent) {
                        evt.originalEvent = d3.event;
                        gd.emit('plotly_unhover', {
                            points: [eventData(pt, trace2)],
                            event: d3.event
                        });
                        hasHoverEvent = false;
                    }

                    if(hasHoverLabel) {
                        Fx.loneUnhover(fullLayout2._hoverlayer.node());
                        hasHoverLabel = false;
                    }
                }

                function handleClick() {
                    // TODO: this does not support right-click. If we want to support it, we
                    // would likely need to change pie to use dragElement instead of straight
                    // mapbox event binding. Or perhaps better, make a simple wrapper with the
                    // right mousedown, mousemove, and mouseup handlers just for a left/right click
                    // mapbox would use this too.
                    var fullLayout2 = gd._fullLayout;
                    var trace2 = gd._fullData[trace.index];

                    if(gd._dragging || fullLayout2.hovermode === false) return;

                    gd._hoverdata = [eventData(pt, trace2)];
                    Fx.click(gd, d3.event);
                }

                slicePath.enter().append('path')
                    .classed('surface', true)
                    .style({'pointer-events': 'all'});

                sliceTop.select('path.textline').remove();

                sliceTop
                    .on('mouseover', handleMouseOver)
                    .on('mouseout', handleMouseOut)
                    .on('click', handleClick);

                if(trace.pull) {
                    var pull = +helpers.castOption(trace.pull, pt.pts) || 0;
                    if(pull > 0) {
                        cx += pull * pt.pxmid[0];
                        cy += pull * pt.pxmid[1];
                    }
                }

                pt.cxFinal = cx;
                pt.cyFinal = cy;

                function arc(start, finish, cw, scale) {
                    return 'a' + (scale * cd0.r) + ',' + (scale * cd0.r) + ' 0 ' +
                        pt.largeArc + (cw ? ' 1 ' : ' 0 ') +
                        (scale * (finish[0] - start[0])) + ',' + (scale * (finish[1] - start[1]));
                }

                var hole = trace.hole;
                if(pt.v === cd0.vTotal) { // 100% fails bcs arc start and end are identical
                    var outerCircle = 'M' + (cx + pt.px0[0]) + ',' + (cy + pt.px0[1]) +
                        arc(pt.px0, pt.pxmid, true, 1) +
                        arc(pt.pxmid, pt.px0, true, 1) + 'Z';
                    if(hole) {
                        slicePath.attr('d',
                            'M' + (cx + hole * pt.px0[0]) + ',' + (cy + hole * pt.px0[1]) +
                            arc(pt.px0, pt.pxmid, false, hole) +
                            arc(pt.pxmid, pt.px0, false, hole) +
                            'Z' + outerCircle);
                    }
                    else slicePath.attr('d', outerCircle);
                } else {

                    var outerArc = arc(pt.px0, pt.px1, true, 1);

                    if(hole) {
                        var rim = 1 - hole;
                        slicePath.attr('d',
                            'M' + (cx + hole * pt.px1[0]) + ',' + (cy + hole * pt.px1[1]) +
                            arc(pt.px1, pt.px0, false, hole) +
                            'l' + (rim * pt.px0[0]) + ',' + (rim * pt.px0[1]) +
                            outerArc +
                            'Z');
                    } else {
                        slicePath.attr('d',
                            'M' + cx + ',' + cy +
                            'l' + pt.px0[0] + ',' + pt.px0[1] +
                            outerArc +
                            'Z');
                    }
                }

                // add text
                var textPosition = helpers.castOption(trace.textposition, pt.pts);
                var sliceTextGroup = sliceTop.selectAll('g.slicetext')
                    .data(pt.text && (textPosition !== 'none') ? [0] : []);

                sliceTextGroup.enter().append('g')
                    .classed('slicetext', true);
                sliceTextGroup.exit().remove();

                sliceTextGroup.each(function() {
                    var sliceText = Lib.ensureSingle(d3.select(this), 'text', '', function(s) {
                        // prohibit tex interpretation until we can handle
                        // tex and regular text together
                        s.attr('data-notex', 1);
                    });

                    sliceText.text(pt.text)
                        .attr({
                            'class': 'slicetext',
                            transform: '',
                            'text-anchor': 'middle'
                        })
                        .call(Drawing.font, textPosition === 'outside' ?
                          determineOutsideTextFont(trace, pt, gd._fullLayout.font) :
                          determineInsideTextFont(trace, pt, gd._fullLayout.font))
                        .call(svgTextUtils.convertToTspans, gd);

                    // position the text relative to the slice
                    var textBB = Drawing.bBox(sliceText.node());
                    var transform;

                    if(textPosition === 'outside') {
                        transform = transformOutsideText(textBB, pt);
                    } else {
                        transform = transformInsideText(textBB, pt, cd0);
                        if(textPosition === 'auto' && transform.scale < 1) {
                            sliceText.call(Drawing.font, trace.outsidetextfont);
                            if(trace.outsidetextfont.family !== trace.insidetextfont.family ||
                                    trace.outsidetextfont.size !== trace.insidetextfont.size) {
                                textBB = Drawing.bBox(sliceText.node());
                            }
                            transform = transformOutsideText(textBB, pt);
                        }
                    }

                    var translateX = cx + pt.pxmid[0] * transform.rCenter + (transform.x || 0);
                    var translateY = cy + pt.pxmid[1] * transform.rCenter + (transform.y || 0);

                    // save some stuff to use later ensure no labels overlap
                    if(transform.outside) {
                        pt.yLabelMin = translateY - textBB.height / 2;
                        pt.yLabelMid = translateY;
                        pt.yLabelMax = translateY + textBB.height / 2;
                        pt.labelExtraX = 0;
                        pt.labelExtraY = 0;
                        hasOutsideText = true;
                    }

                    sliceText.attr('transform',
                        'translate(' + translateX + ',' + translateY + ')' +
                        (transform.scale < 1 ? ('scale(' + transform.scale + ')') : '') +
                        (transform.rotate ? ('rotate(' + transform.rotate + ')') : '') +
                        'translate(' +
                            (-(textBB.left + textBB.right) / 2) + ',' +
                            (-(textBB.top + textBB.bottom) / 2) +
                        ')');
                });
            });

            // add the title
            var titleTextGroup = d3.select(this).selectAll('g.titletext')
                .data(trace.title.text ? [0] : []);

            titleTextGroup.enter().append('g')
                .classed('titletext', true);
            titleTextGroup.exit().remove();

            titleTextGroup.each(function() {
                var titleText = Lib.ensureSingle(d3.select(this), 'text', '', function(s) {
                    // prohibit tex interpretation as above
                    s.attr('data-notex', 1);
                });

                var txt = fullLayout.meta ?
                    Lib.templateString(trace.title.text, {meta: fullLayout.meta}) :
                    trace.title.text;

                titleText.text(txt)
                    .attr({
                        'class': 'titletext',
                        transform: '',
                        'text-anchor': 'middle',
                    })
                .call(Drawing.font, trace.title.font)
                .call(svgTextUtils.convertToTspans, gd);

                var transform;

                if(trace.title.position === 'middle center') {
                    transform = positionTitleInside(cd0);
                } else {
                    transform = positionTitleOutside(cd0, fullLayout._size);
                }

                titleText.attr('transform',
                    'translate(' + transform.x + ',' + transform.y + ')' +
                    (transform.scale < 1 ? ('scale(' + transform.scale + ')') : '') +
                    'translate(' + transform.tx + ',' + transform.ty + ')');
            });

            // now make sure no labels overlap (at least within one pie)
            if(hasOutsideText) scootLabels(quadrants, trace);
            slices.each(function(pt) {
                if(pt.labelExtraX || pt.labelExtraY) {
                    // first move the text to its new location
                    var sliceTop = d3.select(this);
                    var sliceText = sliceTop.select('g.slicetext text');

                    sliceText.attr('transform', 'translate(' + pt.labelExtraX + ',' + pt.labelExtraY + ')' +
                        sliceText.attr('transform'));

                    // then add a line to the new location
                    var lineStartX = pt.cxFinal + pt.pxmid[0];
                    var lineStartY = pt.cyFinal + pt.pxmid[1];
                    var textLinePath = 'M' + lineStartX + ',' + lineStartY;
                    var finalX = (pt.yLabelMax - pt.yLabelMin) * (pt.pxmid[0] < 0 ? -1 : 1) / 4;

                    if(pt.labelExtraX) {
                        var yFromX = pt.labelExtraX * pt.pxmid[1] / pt.pxmid[0];
                        var yNet = pt.yLabelMid + pt.labelExtraY - (pt.cyFinal + pt.pxmid[1]);

                        if(Math.abs(yFromX) > Math.abs(yNet)) {
                            textLinePath +=
                                'l' + (yNet * pt.pxmid[0] / pt.pxmid[1]) + ',' + yNet +
                                'H' + (lineStartX + pt.labelExtraX + finalX);
                        } else {
                            textLinePath += 'l' + pt.labelExtraX + ',' + yFromX +
                                'v' + (yNet - yFromX) +
                                'h' + finalX;
                        }
                    } else {
                        textLinePath +=
                            'V' + (pt.yLabelMid + pt.labelExtraY) +
                            'h' + finalX;
                    }

                    sliceTop.append('path')
                        .classed('textline', true)
                        .call(Color.stroke, trace.outsidetextfont.color)
                        .attr({
                            'stroke-width': Math.min(2, trace.outsidetextfont.size / 8),
                            d: textLinePath,
                            fill: 'none'
                        });
                }
            });
        });
    });

    // This is for a bug in Chrome (as of 2015-07-22, and does not affect FF)
    // if insidetextfont and outsidetextfont are different sizes, sometimes the size
    // of an "em" gets taken from the wrong element at first so lines are
    // spaced wrong. You just have to tell it to try again later and it gets fixed.
    // I have no idea why we haven't seen this in other contexts. Also, sometimes
    // it gets the initial draw correct but on redraw it gets confused.
    setTimeout(function() {
        pieGroups.selectAll('tspan').each(function() {
            var s = d3.select(this);
            if(s.attr('dy')) s.attr('dy', s.attr('dy'));
        });
    }, 0);
};

function determineOutsideTextFont(trace, pt, layoutFont) {
    var color = helpers.castOption(trace.outsidetextfont.color, pt.pts) ||
      helpers.castOption(trace.textfont.color, pt.pts) ||
      layoutFont.color;

    var family = helpers.castOption(trace.outsidetextfont.family, pt.pts) ||
      helpers.castOption(trace.textfont.family, pt.pts) ||
      layoutFont.family;

    var size = helpers.castOption(trace.outsidetextfont.size, pt.pts) ||
      helpers.castOption(trace.textfont.size, pt.pts) ||
      layoutFont.size;

    return {
        color: color,
        family: family,
        size: size
    };
}

function determineInsideTextFont(trace, pt, layoutFont) {
    var customColor = helpers.castOption(trace.insidetextfont.color, pt.pts);
    if(!customColor && trace._input.textfont) {

        // Why not simply using trace.textfont? Because if not set, it
        // defaults to layout.font which has a default color. But if
        // textfont.color and insidetextfont.color don't supply a value,
        // a contrasting color shall be used.
        customColor = helpers.castOption(trace._input.textfont.color, pt.pts);
    }

    var family = helpers.castOption(trace.insidetextfont.family, pt.pts) ||
      helpers.castOption(trace.textfont.family, pt.pts) ||
      layoutFont.family;

    var size = helpers.castOption(trace.insidetextfont.size, pt.pts) ||
      helpers.castOption(trace.textfont.size, pt.pts) ||
      layoutFont.size;

    return {
        color: customColor || Color.contrast(pt.color),
        family: family,
        size: size
    };
}

function prerenderTitles(cdpie, gd) {
    var fullLayout = gd._fullLayout;

    var cd0, trace;
    // Determine the width and height of the title for each pie.
    for(var i = 0; i < cdpie.length; i++) {
        cd0 = cdpie[i][0];
        trace = cd0.trace;

        if(trace.title.text) {
            var txt = fullLayout.meta ?
                Lib.templateString(trace.title.text, {meta: fullLayout.meta}) :
                trace.title.text;

            var dummyTitle = Drawing.tester.append('text')
              .attr('data-notex', 1)
              .text(txt)
              .call(Drawing.font, trace.title.font)
              .call(svgTextUtils.convertToTspans, gd);
            var bBox = Drawing.bBox(dummyTitle.node(), true);
            cd0.titleBox = {
                width: bBox.width,
                height: bBox.height,
            };
            dummyTitle.remove();
        }
    }
}

function transformInsideText(textBB, pt, cd0) {
    var textDiameter = Math.sqrt(textBB.width * textBB.width + textBB.height * textBB.height);
    var textAspect = textBB.width / textBB.height;
    var halfAngle = Math.PI * Math.min(pt.v / cd0.vTotal, 0.5);
    var ring = 1 - cd0.trace.hole;
    var rInscribed = getInscribedRadiusFraction(pt, cd0);

    // max size text can be inserted inside without rotating it
    // this inscribes the text rectangle in a circle, which is then inscribed
    // in the slice, so it will be an underestimate, which some day we may want
    // to improve so this case can get more use
    var transform = {
        scale: rInscribed * cd0.r * 2 / textDiameter,

        // and the center position and rotation in this case
        rCenter: 1 - rInscribed,
        rotate: 0
    };

    if(transform.scale >= 1) return transform;

        // max size if text is rotated radially
    var Qr = textAspect + 1 / (2 * Math.tan(halfAngle));
    var maxHalfHeightRotRadial = cd0.r * Math.min(
        1 / (Math.sqrt(Qr * Qr + 0.5) + Qr),
        ring / (Math.sqrt(textAspect * textAspect + ring / 2) + textAspect)
    );
    var radialTransform = {
        scale: maxHalfHeightRotRadial * 2 / textBB.height,
        rCenter: Math.cos(maxHalfHeightRotRadial / cd0.r) -
            maxHalfHeightRotRadial * textAspect / cd0.r,
        rotate: (180 / Math.PI * pt.midangle + 720) % 180 - 90
    };

        // max size if text is rotated tangentially
    var aspectInv = 1 / textAspect;
    var Qt = aspectInv + 1 / (2 * Math.tan(halfAngle));
    var maxHalfWidthTangential = cd0.r * Math.min(
        1 / (Math.sqrt(Qt * Qt + 0.5) + Qt),
        ring / (Math.sqrt(aspectInv * aspectInv + ring / 2) + aspectInv)
    );
    var tangentialTransform = {
        scale: maxHalfWidthTangential * 2 / textBB.width,
        rCenter: Math.cos(maxHalfWidthTangential / cd0.r) -
            maxHalfWidthTangential / textAspect / cd0.r,
        rotate: (180 / Math.PI * pt.midangle + 810) % 180 - 90
    };
    // if we need a rotated transform, pick the biggest one
    // even if both are bigger than 1
    var rotatedTransform = tangentialTransform.scale > radialTransform.scale ?
            tangentialTransform : radialTransform;

    if(transform.scale < 1 && rotatedTransform.scale > transform.scale) return rotatedTransform;
    return transform;
}

function getInscribedRadiusFraction(pt, cd0) {
    if(pt.v === cd0.vTotal && !cd0.trace.hole) return 1;// special case of 100% with no hole

    var halfAngle = Math.PI * Math.min(pt.v / cd0.vTotal, 0.5);
    return Math.min(1 / (1 + 1 / Math.sin(halfAngle)), (1 - cd0.trace.hole) / 2);
}

function transformOutsideText(textBB, pt) {
    var x = pt.pxmid[0];
    var y = pt.pxmid[1];
    var dx = textBB.width / 2;
    var dy = textBB.height / 2;

    if(x < 0) dx *= -1;
    if(y < 0) dy *= -1;

    return {
        scale: 1,
        rCenter: 1,
        rotate: 0,
        x: dx + Math.abs(dy) * (dx > 0 ? 1 : -1) / 2,
        y: dy / (1 + x * x / (y * y)),
        outside: true
    };
}

function positionTitleInside(cd0) {
    var textDiameter =
        Math.sqrt(cd0.titleBox.width * cd0.titleBox.width + cd0.titleBox.height * cd0.titleBox.height);
    return {
        x: cd0.cx,
        y: cd0.cy,
        scale: cd0.trace.hole * cd0.r * 2 / textDiameter,
        tx: 0,
        ty: - cd0.titleBox.height / 2 + cd0.trace.title.font.size
    };
}

function positionTitleOutside(cd0, plotSize) {
    var scaleX = 1;
    var scaleY = 1;
    var maxWidth, maxPull;

    var trace = cd0.trace;
    // position of the baseline point of the text box in the plot, before scaling.
    // we anchored the text in the middle, so the baseline is on the bottom middle
    // of the first line of text.
    var topMiddle = {
        x: cd0.cx,
        y: cd0.cy
    };
    // relative translation of the text box after scaling
    var translate = {
        tx: 0,
        ty: 0
    };

    // we reason below as if the baseline is the top middle point of the text box.
    // so we must add the font size to approximate the y-coord. of the top.
    // note that this correction must happen after scaling.
    translate.ty += trace.title.font.size;
    maxPull = getMaxPull(trace);

    if(trace.title.position.indexOf('top') !== -1) {
        topMiddle.y -= (1 + maxPull) * cd0.r;
        translate.ty -= cd0.titleBox.height;
    }
    else if(trace.title.position.indexOf('bottom') !== -1) {
        topMiddle.y += (1 + maxPull) * cd0.r;
    }

    if(trace.title.position.indexOf('left') !== -1) {
        // we start the text at the left edge of the pie
        maxWidth = plotSize.w * (trace.domain.x[1] - trace.domain.x[0]) / 2 + cd0.r;
        topMiddle.x -= (1 + maxPull) * cd0.r;
        translate.tx += cd0.titleBox.width / 2;
    } else if(trace.title.position.indexOf('center') !== -1) {
        maxWidth = plotSize.w * (trace.domain.x[1] - trace.domain.x[0]);
    } else if(trace.title.position.indexOf('right') !== -1) {
        maxWidth = plotSize.w * (trace.domain.x[1] - trace.domain.x[0]) / 2 + cd0.r;
        topMiddle.x += (1 + maxPull) * cd0.r;
        translate.tx -= cd0.titleBox.width / 2;
    }
    scaleX = maxWidth / cd0.titleBox.width;
    scaleY = getTitleSpace(cd0, plotSize) / cd0.titleBox.height;
    return {
        x: topMiddle.x,
        y: topMiddle.y,
        scale: Math.min(scaleX, scaleY),
        tx: translate.tx,
        ty: translate.ty
    };
}

function getTitleSpace(cd0, plotSize) {
    var trace = cd0.trace;
    var pieBoxHeight = plotSize.h * (trace.domain.y[1] - trace.domain.y[0]);
    // use at most half of the plot for the title
    return Math.min(cd0.titleBox.height, pieBoxHeight / 2);
}

function getMaxPull(trace) {
    var maxPull = trace.pull;
    var j;
    if(Array.isArray(maxPull)) {
        maxPull = 0;
        for(j = 0; j < trace.pull.length; j++) {
            if(trace.pull[j] > maxPull) maxPull = trace.pull[j];
        }
    }
    return maxPull;
}

function scootLabels(quadrants, trace) {
    var xHalf, yHalf, equatorFirst, farthestX, farthestY,
        xDiffSign, yDiffSign, thisQuad, oppositeQuad,
        wholeSide, i, thisQuadOutside, firstOppositeOutsidePt;

    function topFirst(a, b) { return a.pxmid[1] - b.pxmid[1]; }
    function bottomFirst(a, b) { return b.pxmid[1] - a.pxmid[1]; }

    function scootOneLabel(thisPt, prevPt) {
        if(!prevPt) prevPt = {};

        var prevOuterY = prevPt.labelExtraY + (yHalf ? prevPt.yLabelMax : prevPt.yLabelMin);
        var thisInnerY = yHalf ? thisPt.yLabelMin : thisPt.yLabelMax;
        var thisOuterY = yHalf ? thisPt.yLabelMax : thisPt.yLabelMin;
        var thisSliceOuterY = thisPt.cyFinal + farthestY(thisPt.px0[1], thisPt.px1[1]);
        var newExtraY = prevOuterY - thisInnerY;

        var xBuffer, i, otherPt, otherOuterY, otherOuterX, newExtraX;

        // make sure this label doesn't overlap other labels
        // this *only* has us move these labels vertically
        if(newExtraY * yDiffSign > 0) thisPt.labelExtraY = newExtraY;

        // make sure this label doesn't overlap any slices
        if(!Array.isArray(trace.pull)) return; // this can only happen with array pulls

        for(i = 0; i < wholeSide.length; i++) {
            otherPt = wholeSide[i];

            // overlap can only happen if the other point is pulled more than this one
            if(otherPt === thisPt || (
                (helpers.castOption(trace.pull, thisPt.pts) || 0) >=
                (helpers.castOption(trace.pull, otherPt.pts) || 0))
            ) {
                continue;
            }

            if((thisPt.pxmid[1] - otherPt.pxmid[1]) * yDiffSign > 0) {
                // closer to the equator - by construction all of these happen first
                // move the text vertically to get away from these slices
                otherOuterY = otherPt.cyFinal + farthestY(otherPt.px0[1], otherPt.px1[1]);
                newExtraY = otherOuterY - thisInnerY - thisPt.labelExtraY;

                if(newExtraY * yDiffSign > 0) thisPt.labelExtraY += newExtraY;

            } else if((thisOuterY + thisPt.labelExtraY - thisSliceOuterY) * yDiffSign > 0) {
                // farther from the equator - happens after we've done all the
                // vertical moving we're going to do
                // move horizontally to get away from these more polar slices

                // if we're moving horz. based on a slice that's several slices away from this one
                // then we need some extra space for the lines to labels between them
                xBuffer = 3 * xDiffSign * Math.abs(i - wholeSide.indexOf(thisPt));

                otherOuterX = otherPt.cxFinal + farthestX(otherPt.px0[0], otherPt.px1[0]);
                newExtraX = otherOuterX + xBuffer - (thisPt.cxFinal + thisPt.pxmid[0]) - thisPt.labelExtraX;

                if(newExtraX * xDiffSign > 0) thisPt.labelExtraX += newExtraX;
            }
        }
    }

    for(yHalf = 0; yHalf < 2; yHalf++) {
        equatorFirst = yHalf ? topFirst : bottomFirst;
        farthestY = yHalf ? Math.max : Math.min;
        yDiffSign = yHalf ? 1 : -1;

        for(xHalf = 0; xHalf < 2; xHalf++) {
            farthestX = xHalf ? Math.max : Math.min;
            xDiffSign = xHalf ? 1 : -1;

            // first sort the array
            // note this is a copy of cd, so cd itself doesn't get sorted
            // but we can still modify points in place.
            thisQuad = quadrants[yHalf][xHalf];
            thisQuad.sort(equatorFirst);

            oppositeQuad = quadrants[1 - yHalf][xHalf];
            wholeSide = oppositeQuad.concat(thisQuad);

            thisQuadOutside = [];
            for(i = 0; i < thisQuad.length; i++) {
                if(thisQuad[i].yLabelMid !== undefined) thisQuadOutside.push(thisQuad[i]);
            }

            firstOppositeOutsidePt = false;
            for(i = 0; yHalf && i < oppositeQuad.length; i++) {
                if(oppositeQuad[i].yLabelMid !== undefined) {
                    firstOppositeOutsidePt = oppositeQuad[i];
                    break;
                }
            }

            // each needs to avoid the previous
            for(i = 0; i < thisQuadOutside.length; i++) {
                var prevPt = i && thisQuadOutside[i - 1];
                // bottom half needs to avoid the first label of the top half
                // top half we still need to call scootOneLabel on the first slice
                // so we can avoid other slices, but we don't pass a prevPt
                if(firstOppositeOutsidePt && !i) prevPt = firstOppositeOutsidePt;
                scootOneLabel(thisQuadOutside[i], prevPt);
            }
        }
    }
}

function scalePies(cdpie, plotSize) {
    var scaleGroups = [];

    var pieBoxWidth, pieBoxHeight, i, j, cd0, trace,
        maxPull, scaleGroup, minPxPerValUnit;

    // first figure out the center and maximum radius for each pie
    for(i = 0; i < cdpie.length; i++) {
        cd0 = cdpie[i][0];
        trace = cd0.trace;

        pieBoxWidth = plotSize.w * (trace.domain.x[1] - trace.domain.x[0]);
        pieBoxHeight = plotSize.h * (trace.domain.y[1] - trace.domain.y[0]);
        // leave some space for the title, if it will be displayed outside
        if(trace.title.text && trace.title.position !== 'middle center') {
            pieBoxHeight -= getTitleSpace(cd0, plotSize);
        }

        maxPull = getMaxPull(trace);

        cd0.r = Math.min(pieBoxWidth, pieBoxHeight) / (2 + 2 * maxPull);

        cd0.cx = plotSize.l + plotSize.w * (trace.domain.x[1] + trace.domain.x[0]) / 2;
        cd0.cy = plotSize.t + plotSize.h * (1 - trace.domain.y[0]) - pieBoxHeight / 2;
        if(trace.title.text && trace.title.position.indexOf('bottom') !== -1) {
            cd0.cy -= getTitleSpace(cd0, plotSize);
        }

        if(trace.scalegroup && scaleGroups.indexOf(trace.scalegroup) === -1) {
            scaleGroups.push(trace.scalegroup);
        }
    }

    // Then scale any pies that are grouped
    for(j = 0; j < scaleGroups.length; j++) {
        minPxPerValUnit = Infinity;
        scaleGroup = scaleGroups[j];

        for(i = 0; i < cdpie.length; i++) {
            cd0 = cdpie[i][0];
            if(cd0.trace.scalegroup === scaleGroup) {
                minPxPerValUnit = Math.min(minPxPerValUnit,
                    cd0.r * cd0.r / cd0.vTotal);
            }
        }

        for(i = 0; i < cdpie.length; i++) {
            cd0 = cdpie[i][0];
            if(cd0.trace.scalegroup === scaleGroup) {
                cd0.r = Math.sqrt(minPxPerValUnit * cd0.vTotal);
            }
        }
    }

}

function setCoords(cd) {
    var cd0 = cd[0];
    var trace = cd0.trace;
    var currentAngle = trace.rotation * Math.PI / 180;
    var angleFactor = 2 * Math.PI / cd0.vTotal;
    var firstPt = 'px0';
    var lastPt = 'px1';

    var i, cdi, currentCoords;

    if(trace.direction === 'counterclockwise') {
        for(i = 0; i < cd.length; i++) {
            if(!cd[i].hidden) break; // find the first non-hidden slice
        }
        if(i === cd.length) return; // all slices hidden

        currentAngle += angleFactor * cd[i].v;
        angleFactor *= -1;
        firstPt = 'px1';
        lastPt = 'px0';
    }

    function getCoords(angle) {
        return [cd0.r * Math.sin(angle), -cd0.r * Math.cos(angle)];
    }

    currentCoords = getCoords(currentAngle);

    for(i = 0; i < cd.length; i++) {
        cdi = cd[i];
        if(cdi.hidden) continue;

        cdi[firstPt] = currentCoords;

        currentAngle += angleFactor * cdi.v / 2;
        cdi.pxmid = getCoords(currentAngle);
        cdi.midangle = currentAngle;

        currentAngle += angleFactor * cdi.v / 2;
        currentCoords = getCoords(currentAngle);

        cdi[lastPt] = currentCoords;

        cdi.largeArc = (cdi.v > cd0.vTotal / 2) ? 1 : 0;
    }
}

},{"../../components/color":574,"../../components/drawing":595,"../../components/fx":613,"../../lib":697,"../../lib/svg_text_utils":721,"./event_data":1027,"./helpers":1028,"d3":151}],1033:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var styleOne = _dereq_('./style_one');

module.exports = function style(gd) {
    gd._fullLayout._pielayer.selectAll('.trace').each(function(cd) {
        var cd0 = cd[0];
        var trace = cd0.trace;
        var traceSelection = d3.select(this);

        traceSelection.style({opacity: trace.opacity});

        traceSelection.selectAll('path.surface').each(function(pt) {
            d3.select(this).call(styleOne, pt, trace);
        });
    });
};

},{"./style_one":1034,"d3":151}],1034:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Color = _dereq_('../../components/color');
var castOption = _dereq_('./helpers').castOption;

module.exports = function styleOne(s, pt, trace) {
    var line = trace.marker.line;
    var lineColor = castOption(line.color, pt.pts) || Color.defaultLine;
    var lineWidth = castOption(line.width, pt.pts) || 0;

    s.style({'stroke-width': lineWidth})
        .call(Color.fill, pt.color)
        .call(Color.stroke, lineColor);
};

},{"../../components/color":574,"./helpers":1028}],1035:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterglAttrs = _dereq_('../scatter/attributes');

module.exports = {
    x: scatterglAttrs.x,
    y: scatterglAttrs.y,
    xy: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    indices: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    xbounds: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    ybounds: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    text: scatterglAttrs.text,
    marker: {
        color: {
            valType: 'color',
            arrayOk: false,
            
            editType: 'calc',
            
        },
        opacity: {
            valType: 'number',
            min: 0,
            max: 1,
            dflt: 1,
            arrayOk: false,
            
            editType: 'calc',
            
        },
        blend: {
            valType: 'boolean',
            dflt: null,
            
            editType: 'calc',
            
        },
        sizemin: {
            valType: 'number',
            min: 0.1,
            max: 2,
            dflt: 0.5,
            
            editType: 'calc',
            
        },
        sizemax: {
            valType: 'number',
            min: 0.1,
            dflt: 20,
            
            editType: 'calc',
            
        },
        border: {
            color: {
                valType: 'color',
                arrayOk: false,
                
                editType: 'calc',
                
            },
            arearatio: {
                valType: 'number',
                min: 0,
                max: 1,
                dflt: 0,
                
                editType: 'calc',
                
            },
            editType: 'calc'
        },
        editType: 'calc'
    },
    transforms: undefined
};

},{"../scatter/attributes":1048}],1036:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var createPointCloudRenderer = _dereq_('gl-pointcloud2d');

var str2RGBArray = _dereq_('../../lib/str2rgbarray');
var findExtremes = _dereq_('../../plots/cartesian/autorange').findExtremes;
var getTraceColor = _dereq_('../scatter/get_trace_color');

function Pointcloud(scene, uid) {
    this.scene = scene;
    this.uid = uid;
    this.type = 'pointcloud';

    this.pickXData = [];
    this.pickYData = [];
    this.xData = [];
    this.yData = [];
    this.textLabels = [];
    this.color = 'rgb(0, 0, 0)';
    this.name = '';
    this.hoverinfo = 'all';

    this.idToIndex = new Int32Array(0);
    this.bounds = [0, 0, 0, 0];

    this.pointcloudOptions = {
        positions: new Float32Array(0),
        idToIndex: this.idToIndex,
        sizemin: 0.5,
        sizemax: 12,
        color: [0, 0, 0, 1],
        areaRatio: 1,
        borderColor: [0, 0, 0, 1]
    };
    this.pointcloud = createPointCloudRenderer(scene.glplot, this.pointcloudOptions);
    this.pointcloud._trace = this; // scene2d requires this prop
}

var proto = Pointcloud.prototype;

proto.handlePick = function(pickResult) {
    var index = this.idToIndex[pickResult.pointId];

    // prefer the readout from XY, if present
    return {
        trace: this,
        dataCoord: pickResult.dataCoord,
        traceCoord: this.pickXYData ?
            [this.pickXYData[index * 2], this.pickXYData[index * 2 + 1]] :
            [this.pickXData[index], this.pickYData[index]],
        textLabel: Array.isArray(this.textLabels) ?
            this.textLabels[index] :
            this.textLabels,
        color: this.color,
        name: this.name,
        pointIndex: index,
        hoverinfo: this.hoverinfo
    };
};

proto.update = function(options) {
    this.index = options.index;
    this.textLabels = options.text;
    this.name = options.name;
    this.hoverinfo = options.hoverinfo;
    this.bounds = [Infinity, Infinity, -Infinity, -Infinity];

    this.updateFast(options);

    this.color = getTraceColor(options, {});
};

proto.updateFast = function(options) {
    var x = this.xData = this.pickXData = options.x;
    var y = this.yData = this.pickYData = options.y;
    var xy = this.pickXYData = options.xy;

    var userBounds = options.xbounds && options.ybounds;
    var index = options.indices;

    var len;
    var idToIndex;
    var positions;
    var bounds = this.bounds;

    var xx, yy, i;

    if(xy) {

        positions = xy;

        // dividing xy.length by 2 and truncating to integer if xy.length was not even
        len = xy.length >>> 1;

        if(userBounds) {

            bounds[0] = options.xbounds[0];
            bounds[2] = options.xbounds[1];
            bounds[1] = options.ybounds[0];
            bounds[3] = options.ybounds[1];

        } else {

            for(i = 0; i < len; i++) {

                xx = positions[i * 2];
                yy = positions[i * 2 + 1];

                if(xx < bounds[0]) bounds[0] = xx;
                if(xx > bounds[2]) bounds[2] = xx;
                if(yy < bounds[1]) bounds[1] = yy;
                if(yy > bounds[3]) bounds[3] = yy;
            }

        }

        if(index) {

            idToIndex = index;

        } else {

            idToIndex = new Int32Array(len);

            for(i = 0; i < len; i++) {

                idToIndex[i] = i;

            }

        }

    } else {

        len = x.length;

        positions = new Float32Array(2 * len);
        idToIndex = new Int32Array(len);

        for(i = 0; i < len; i++) {
            xx = x[i];
            yy = y[i];

            idToIndex[i] = i;

            positions[i * 2] = xx;
            positions[i * 2 + 1] = yy;

            if(xx < bounds[0]) bounds[0] = xx;
            if(xx > bounds[2]) bounds[2] = xx;
            if(yy < bounds[1]) bounds[1] = yy;
            if(yy > bounds[3]) bounds[3] = yy;
        }

    }

    this.idToIndex = idToIndex;
    this.pointcloudOptions.idToIndex = idToIndex;

    this.pointcloudOptions.positions = positions;

    var markerColor = str2RGBArray(options.marker.color);
    var borderColor = str2RGBArray(options.marker.border.color);
    var opacity = options.opacity * options.marker.opacity;

    markerColor[3] *= opacity;
    this.pointcloudOptions.color = markerColor;

    // detect blending from the number of points, if undefined
    // because large data with blending hits performance
    var blend = options.marker.blend;
    if(blend === null) {
        var maxPoints = 100;
        blend = x.length < maxPoints || y.length < maxPoints;
    }
    this.pointcloudOptions.blend = blend;

    borderColor[3] *= opacity;
    this.pointcloudOptions.borderColor = borderColor;

    var markerSizeMin = options.marker.sizemin;
    var markerSizeMax = Math.max(options.marker.sizemax, options.marker.sizemin);
    this.pointcloudOptions.sizeMin = markerSizeMin;
    this.pointcloudOptions.sizeMax = markerSizeMax;
    this.pointcloudOptions.areaRatio = options.marker.border.arearatio;

    this.pointcloud.update(this.pointcloudOptions);

    // add item for autorange routine
    var xa = this.scene.xaxis;
    var ya = this.scene.yaxis;
    var pad = markerSizeMax / 2 || 0.5;
    options._extremes[xa._id] = findExtremes(xa, [bounds[0], bounds[2]], {ppad: pad});
    options._extremes[ya._id] = findExtremes(ya, [bounds[1], bounds[3]], {ppad: pad});
};

proto.dispose = function() {
    this.pointcloud.dispose();
};

function createPointcloud(scene, data) {
    var plot = new Pointcloud(scene, data.uid);
    plot.update(data);
    return plot;
}

module.exports = createPointcloud;

},{"../../lib/str2rgbarray":720,"../../plots/cartesian/autorange":744,"../scatter/get_trace_color":1058,"gl-pointcloud2d":285}],1037:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    coerce('x');
    coerce('y');

    coerce('xbounds');
    coerce('ybounds');

    if(traceIn.xy && traceIn.xy instanceof Float32Array) {
        traceOut.xy = traceIn.xy;
    }

    if(traceIn.indices && traceIn.indices instanceof Int32Array) {
        traceOut.indices = traceIn.indices;
    }

    coerce('text');
    coerce('marker.color', defaultColor);
    coerce('marker.opacity');
    coerce('marker.blend');
    coerce('marker.sizemin');
    coerce('marker.sizemax');
    coerce('marker.border.color', defaultColor);
    coerce('marker.border.arearatio');

    // disable 1D transforms - that would defeat the purpose of this trace type, performance!
    traceOut._length = null;
};

},{"../../lib":697,"./attributes":1035}],1038:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var pointcloud = {};

pointcloud.attributes = _dereq_('./attributes');
pointcloud.supplyDefaults = _dereq_('./defaults');

// reuse the Scatter3D 'dummy' calc step so that legends know what to do
pointcloud.calc = _dereq_('../scatter3d/calc');
pointcloud.plot = _dereq_('./convert');

pointcloud.moduleType = 'trace';
pointcloud.name = 'pointcloud';
pointcloud.basePlotModule = _dereq_('../../plots/gl2d');
pointcloud.categories = ['gl', 'gl2d', 'showLegend'];
pointcloud.meta = {
    
};

module.exports = pointcloud;

},{"../../plots/gl2d":784,"../scatter3d/calc":1076,"./attributes":1035,"./convert":1036,"./defaults":1037}],1039:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = _dereq_('../../plots/font_attributes');
var plotAttrs = _dereq_('../../plots/attributes');
var colorAttrs = _dereq_('../../components/color/attributes');
var fxAttrs = _dereq_('../../components/fx/attributes');
var domainAttrs = _dereq_('../../plots/domain').attributes;
var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var colorAttributes = _dereq_('../../components/colorscale/attributes');
var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;

var extendFlat = _dereq_('../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;

var attrs = module.exports = overrideAll({
    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
        flags: [],
        arrayOk: false,
        
    }),
    hoverlabel: fxAttrs.hoverlabel,
    domain: domainAttrs({name: 'sankey', trace: true}),

    orientation: {
        valType: 'enumerated',
        values: ['v', 'h'],
        dflt: 'h',
        
        
    },

    valueformat: {
        valType: 'string',
        dflt: '.3s',
        
        
    },

    valuesuffix: {
        valType: 'string',
        dflt: '',
        
        
    },

    arrangement: {
        valType: 'enumerated',
        values: ['snap', 'perpendicular', 'freeform', 'fixed'],
        dflt: 'snap',
        
        
    },

    textfont: fontAttrs({
        
    }),

    node: {
        label: {
            valType: 'data_array',
            dflt: [],
            
            
        },
        groups: {
            valType: 'info_array',
            dimensions: 2,
            freeLength: true,
            dflt: [],
            items: {valType: 'number', editType: 'calc'},
            
            
        },
        color: {
            valType: 'color',
            
            arrayOk: true,
            
        },
        line: {
            color: {
                valType: 'color',
                
                dflt: colorAttrs.defaultLine,
                arrayOk: true,
                
            },
            width: {
                valType: 'number',
                
                min: 0,
                dflt: 0.5,
                arrayOk: true,
                
            }
        },
        pad: {
            valType: 'number',
            arrayOk: false,
            min: 0,
            dflt: 20,
            
            
        },
        thickness: {
            valType: 'number',
            arrayOk: false,
            min: 1,
            dflt: 20,
            
            
        },
        hoverinfo: {
            valType: 'enumerated',
            values: ['all', 'none', 'skip'],
            dflt: 'all',
            
            
        },
        hoverlabel: fxAttrs.hoverlabel, // needs editType override,
        hovertemplate: hovertemplateAttrs({}, {
            
            keys: ['value', 'label']
        }),
        
    },

    link: {
        label: {
            valType: 'data_array',
            dflt: [],
            
            
        },
        color: {
            valType: 'color',
            
            arrayOk: true,
            
        },
        line: {
            color: {
                valType: 'color',
                
                dflt: colorAttrs.defaultLine,
                arrayOk: true,
                
            },
            width: {
                valType: 'number',
                
                min: 0,
                dflt: 0,
                arrayOk: true,
                
            }
        },
        source: {
            valType: 'data_array',
            
            dflt: [],
            
        },
        target: {
            valType: 'data_array',
            
            dflt: [],
            
        },
        value: {
            valType: 'data_array',
            dflt: [],
            
            
        },
        hoverinfo: {
            valType: 'enumerated',
            values: ['all', 'none', 'skip'],
            dflt: 'all',
            
            
        },
        hoverlabel: fxAttrs.hoverlabel, // needs editType override,
        hovertemplate: hovertemplateAttrs({}, {
            
            keys: ['value', 'label']
        }),
        colorscales: templatedArray('concentrationscales', {
            editType: 'calc',
            label: {
                valType: 'string',
                
                editType: 'calc',
                
                dflt: ''
            },
            cmax: {
                valType: 'number',
                
                editType: 'calc',
                dflt: 1,
                
            },
            cmin: {
                valType: 'number',
                
                editType: 'calc',
                dflt: 0,
                
            },
            colorscale: extendFlat(colorAttributes().colorscale, {dflt: [[0, 'white'], [1, 'black']]})
        }),
        
        
    }
}, 'calc', 'nested');
attrs.transforms = undefined;

},{"../../components/color/attributes":573,"../../components/colorscale/attributes":581,"../../components/fx/attributes":604,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plot_api/edit_types":728,"../../plot_api/plot_template":735,"../../plots/attributes":742,"../../plots/domain":770,"../../plots/font_attributes":771}],1040:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
var getModuleCalcData = _dereq_('../../plots/get_data').getModuleCalcData;
var plot = _dereq_('./plot');
var fxAttrs = _dereq_('../../components/fx/layout_attributes');

var SANKEY = 'sankey';

exports.name = SANKEY;

exports.baseLayoutAttrOverrides = overrideAll({
    hoverlabel: fxAttrs.hoverlabel
}, 'plot', 'nested');

exports.plot = function(gd) {
    var calcData = getModuleCalcData(gd.calcdata, SANKEY)[0];
    plot(gd, calcData);
};

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var hadPlot = (oldFullLayout._has && oldFullLayout._has(SANKEY));
    var hasPlot = (newFullLayout._has && newFullLayout._has(SANKEY));

    if(hadPlot && !hasPlot) {
        oldFullLayout._paperdiv.selectAll('.sankey').remove();
    }
};

},{"../../components/fx/layout_attributes":614,"../../plot_api/edit_types":728,"../../plots/get_data":781,"./plot":1045}],1041:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var tarjan = _dereq_('strongly-connected-components');
var Lib = _dereq_('../../lib');
var wrap = _dereq_('../../lib/gup').wrap;

var isArrayOrTypedArray = Lib.isArrayOrTypedArray;
var isIndex = Lib.isIndex;
var Colorscale = _dereq_('../../components/colorscale');

function convertToD3Sankey(trace) {
    var nodeSpec = trace.node;
    var linkSpec = trace.link;

    var links = [];
    var hasLinkColorArray = isArrayOrTypedArray(linkSpec.color);
    var linkedNodes = {};

    var components = {};
    var componentCount = linkSpec.colorscales.length;
    var i;
    for(i = 0; i < componentCount; i++) {
        var cscale = linkSpec.colorscales[i];
        var specs = Colorscale.extractScale(cscale, {cLetter: 'c'});
        var scale = Colorscale.makeColorScaleFunc(specs);
        components[cscale.label] = scale;
    }

    var maxNodeId = 0;
    for(i = 0; i < linkSpec.value.length; i++) {
        if(linkSpec.source[i] > maxNodeId) maxNodeId = linkSpec.source[i];
        if(linkSpec.target[i] > maxNodeId) maxNodeId = linkSpec.target[i];
    }
    var nodeCount = maxNodeId + 1;

    // Group nodes
    var j;
    var groups = trace.node.groups;
    var groupLookup = {};
    for(i = 0; i < groups.length; i++) {
        var group = groups[i];
        // Build a lookup table to quickly find in which group a node is
        for(j = 0; j < group.length; j++) {
            var nodeIndex = group[j];
            var groupIndex = nodeCount + i;
            if(groupLookup.hasOwnProperty(nodeIndex)) {
                Lib.warn('Node ' + nodeIndex + ' is already part of a group.');
            } else {
                groupLookup[nodeIndex] = groupIndex;
            }
        }
    }

    // Process links
    var groupedLinks = {
        source: [],
        target: []
    };
    for(i = 0; i < linkSpec.value.length; i++) {
        var val = linkSpec.value[i];
        // remove negative values, but keep zeros with special treatment
        var source = linkSpec.source[i];
        var target = linkSpec.target[i];
        if(!(val > 0 && isIndex(source, nodeCount) && isIndex(target, nodeCount))) {
            continue;
        }

        // Remove links that are within the same group
        if(groupLookup.hasOwnProperty(source) && groupLookup.hasOwnProperty(target) && groupLookup[source] === groupLookup[target]) {
            continue;
        }

        // if link targets a node in the group, relink target to that group
        if(groupLookup.hasOwnProperty(target)) {
            target = groupLookup[target];
        }

        // if link originates from a node in a group, relink source to that group
        if(groupLookup.hasOwnProperty(source)) {
            source = groupLookup[source];
        }

        source = +source;
        target = +target;
        linkedNodes[source] = linkedNodes[target] = true;

        var label = '';
        if(linkSpec.label && linkSpec.label[i]) label = linkSpec.label[i];

        var concentrationscale = null;
        if(label && components.hasOwnProperty(label)) concentrationscale = components[label];

        links.push({
            pointNumber: i,
            label: label,
            color: hasLinkColorArray ? linkSpec.color[i] : linkSpec.color,
            concentrationscale: concentrationscale,
            source: source,
            target: target,
            value: +val
        });

        groupedLinks.source.push(source);
        groupedLinks.target.push(target);
    }

    // Process nodes
    var totalCount = nodeCount + groups.length;
    var hasNodeColorArray = isArrayOrTypedArray(nodeSpec.color);
    var nodes = [];
    for(i = 0; i < totalCount; i++) {
        if(!linkedNodes[i]) continue;
        var l = nodeSpec.label[i];

        nodes.push({
            group: (i > nodeCount - 1),
            childrenNodes: [],
            pointNumber: i,
            label: l,
            color: hasNodeColorArray ? nodeSpec.color[i] : nodeSpec.color
        });
    }

    // Check if we have circularity on the resulting graph
    var circular = false;
    if(circularityPresent(totalCount, groupedLinks.source, groupedLinks.target)) {
        circular = true;
    }

    return {
        circular: circular,
        links: links,
        nodes: nodes,

        // Data structure for groups
        groups: groups,
        groupLookup: groupLookup
    };
}

function circularityPresent(nodeLen, sources, targets) {
    var nodes = Lib.init2dArray(nodeLen, 0);

    for(var i = 0; i < Math.min(sources.length, targets.length); i++) {
        if(Lib.isIndex(sources[i], nodeLen) && Lib.isIndex(targets[i], nodeLen)) {
            if(sources[i] === targets[i]) {
                return true; // self-link which is also a scc of one
            }
            nodes[sources[i]].push(targets[i]);
        }
    }

    var scc = tarjan(nodes);

    // Tarján's strongly connected components algorithm coded by Mikola Lysenko
    // returns at least one non-singular component if there's circularity in the graph
    return scc.components.some(function(c) {
        return c.length > 1;
    });
}

module.exports = function calc(gd, trace) {
    var result = convertToD3Sankey(trace);

    return wrap({
        circular: result.circular,
        _nodes: result.nodes,
        _links: result.links,

        // Data structure for grouping
        _groups: result.groups,
        _groupLookup: result.groupLookup,
    });
};

},{"../../components/colorscale":586,"../../lib":697,"../../lib/gup":695,"strongly-connected-components":511}],1042:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    nodeTextOffsetHorizontal: 4,
    nodeTextOffsetVertical: 3,
    nodePadAcross: 10,
    sankeyIterations: 50,
    forceIterations: 5,
    forceTicksPerFrame: 10,
    duration: 500,
    ease: 'linear',
    cn: {
        sankey: 'sankey',
        sankeyLinks: 'sankey-links',
        sankeyLink: 'sankey-link',
        sankeyNodeSet: 'sankey-node-set',
        sankeyNode: 'sankey-node',
        nodeRect: 'node-rect',
        nodeCapture: 'node-capture',
        nodeCentered: 'node-entered',
        nodeLabelGuide: 'node-label-guide',
        nodeLabel: 'node-label',
        nodeLabelTextPath: 'node-label-text-path'
    }
};

},{}],1043:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var attributes = _dereq_('./attributes');
var Color = _dereq_('../../components/color');
var tinycolor = _dereq_('tinycolor2');
var handleDomainDefaults = _dereq_('../../plots/domain').defaults;
var handleHoverLabelDefaults = _dereq_('../../components/fx/hoverlabel_defaults');
var Template = _dereq_('../../plot_api/plot_template');
var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var hoverlabelDefault = Lib.extendDeep(layout.hoverlabel, traceIn.hoverlabel);

    // node attributes
    var nodeIn = traceIn.node;
    var nodeOut = Template.newContainer(traceOut, 'node');

    function coerceNode(attr, dflt) {
        return Lib.coerce(nodeIn, nodeOut, attributes.node, attr, dflt);
    }
    coerceNode('label');
    coerceNode('groups');
    coerceNode('pad');
    coerceNode('thickness');
    coerceNode('line.color');
    coerceNode('line.width');
    coerceNode('hoverinfo', traceIn.hoverinfo);
    handleHoverLabelDefaults(nodeIn, nodeOut, coerceNode, hoverlabelDefault);
    coerceNode('hovertemplate');

    var colors = layout.colorway;

    var defaultNodePalette = function(i) {return colors[i % colors.length];};

    coerceNode('color', nodeOut.label.map(function(d, i) {
        return Color.addOpacity(defaultNodePalette(i), 0.8);
    }));

    // link attributes
    var linkIn = traceIn.link || {};
    var linkOut = Template.newContainer(traceOut, 'link');

    function coerceLink(attr, dflt) {
        return Lib.coerce(linkIn, linkOut, attributes.link, attr, dflt);
    }
    coerceLink('label');
    coerceLink('source');
    coerceLink('target');
    coerceLink('value');
    coerceLink('line.color');
    coerceLink('line.width');
    coerceLink('hoverinfo', traceIn.hoverinfo);
    handleHoverLabelDefaults(linkIn, linkOut, coerceLink, hoverlabelDefault);
    coerceLink('hovertemplate');

    var defaultLinkColor = tinycolor(layout.paper_bgcolor).getLuminance() < 0.333 ?
                'rgba(255, 255, 255, 0.6)' :
                'rgba(0, 0, 0, 0.2)';

    coerceLink('color', Lib.repeat(defaultLinkColor, linkOut.value.length));

    handleArrayContainerDefaults(linkIn, linkOut, {
        name: 'colorscales',
        handleItemDefaults: concentrationscalesDefaults
    });

    handleDomainDefaults(traceOut, layout, coerce);

    coerce('orientation');
    coerce('valueformat');
    coerce('valuesuffix');
    coerce('arrangement');

    Lib.coerceFont(coerce, 'textfont', Lib.extendFlat({}, layout.font));

    // disable 1D transforms - arrays here are 1D but their lengths/meanings
    // don't match, between nodes and links
    traceOut._length = null;
};

function concentrationscalesDefaults(In, Out) {
    function coerce(attr, dflt) {
        return Lib.coerce(In, Out, attributes.link.colorscales, attr, dflt);
    }

    coerce('label');
    coerce('cmin');
    coerce('cmax');
    coerce('colorscale');
}

},{"../../components/color":574,"../../components/fx/hoverlabel_defaults":611,"../../lib":697,"../../plot_api/plot_template":735,"../../plots/array_container_defaults":741,"../../plots/domain":770,"./attributes":1039,"tinycolor2":518}],1044:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Plot = {};

Plot.attributes = _dereq_('./attributes');
Plot.supplyDefaults = _dereq_('./defaults');
Plot.calc = _dereq_('./calc');
Plot.plot = _dereq_('./plot');

Plot.moduleType = 'trace';
Plot.name = 'sankey';
Plot.basePlotModule = _dereq_('./base_plot');
Plot.categories = ['noOpacity'];
Plot.meta = {
    
};

module.exports = Plot;

},{"./attributes":1039,"./base_plot":1040,"./calc":1041,"./defaults":1043,"./plot":1045}],1045:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var render = _dereq_('./render');
var Fx = _dereq_('../../components/fx');
var Color = _dereq_('../../components/color');
var Lib = _dereq_('../../lib');
var cn = _dereq_('./constants').cn;

var _ = Lib._;

function renderableValuePresent(d) {return d !== '';}

function ownTrace(selection, d) {
    return selection.filter(function(s) {return s.key === d.traceId;});
}

function makeTranslucent(element, alpha) {
    d3.select(element)
        .select('path')
        .style('fill-opacity', alpha);
    d3.select(element)
        .select('rect')
        .style('fill-opacity', alpha);
}

function makeTextContrasty(element) {
    d3.select(element)
        .select('text.name')
        .style('fill', 'black');
}

function relatedLinks(d) {
    return function(l) {
        return d.node.sourceLinks.indexOf(l.link) !== -1 || d.node.targetLinks.indexOf(l.link) !== -1;
    };
}

function relatedNodes(l) {
    return function(d) {
        return d.node.sourceLinks.indexOf(l.link) !== -1 || d.node.targetLinks.indexOf(l.link) !== -1;
    };
}

function nodeHoveredStyle(sankeyNode, d, sankey) {
    if(d && sankey) {
        ownTrace(sankey, d)
            .selectAll('.' + cn.sankeyLink)
            .filter(relatedLinks(d))
            .call(linkHoveredStyle.bind(0, d, sankey, false));
    }
}

function nodeNonHoveredStyle(sankeyNode, d, sankey) {
    if(d && sankey) {
        ownTrace(sankey, d)
            .selectAll('.' + cn.sankeyLink)
            .filter(relatedLinks(d))
            .call(linkNonHoveredStyle.bind(0, d, sankey, false));
    }
}

function linkHoveredStyle(d, sankey, visitNodes, sankeyLink) {

    var label = sankeyLink.datum().link.label;

    sankeyLink.style('fill-opacity', function(l) {
        if(!l.link.concentrationscale) {
            return 0.4;
        }
    });

    if(label) {
        ownTrace(sankey, d)
            .selectAll('.' + cn.sankeyLink)
            .filter(function(l) {return l.link.label === label;})
            .style('fill-opacity', function(l) {
                if(!l.link.concentrationscale) {
                    return 0.4;
                }
            });
    }

    if(visitNodes) {
        ownTrace(sankey, d)
            .selectAll('.' + cn.sankeyNode)
            .filter(relatedNodes(d))
            .call(nodeHoveredStyle);
    }
}

function linkNonHoveredStyle(d, sankey, visitNodes, sankeyLink) {

    var label = sankeyLink.datum().link.label;

    sankeyLink.style('fill-opacity', function(d) {return d.tinyColorAlpha;});
    if(label) {
        ownTrace(sankey, d)
            .selectAll('.' + cn.sankeyLink)
            .filter(function(l) {return l.link.label === label;})
            .style('fill-opacity', function(d) {return d.tinyColorAlpha;});
    }

    if(visitNodes) {
        ownTrace(sankey, d)
            .selectAll(cn.sankeyNode)
            .filter(relatedNodes(d))
            .call(nodeNonHoveredStyle);
    }
}

// does not support array values for now
function castHoverOption(trace, attr) {
    var labelOpts = trace.hoverlabel || {};
    var val = Lib.nestedProperty(labelOpts, attr).get();
    return Array.isArray(val) ? false : val;
}

module.exports = function plot(gd, calcData) {
    var fullLayout = gd._fullLayout;
    var svg = fullLayout._paper;
    var size = fullLayout._size;

    var linkSelect = function(element, d) {
        var evt = d.link;
        evt.originalEvent = d3.event;
        gd._hoverdata = [evt];
        Fx.click(gd, { target: true });
    };

    var linkHover = function(element, d, sankey) {
        if(gd._fullLayout.hovermode === false) return;
        d3.select(element).call(linkHoveredStyle.bind(0, d, sankey, true));
        if(d.link.trace.link.hoverinfo !== 'skip') {
            d.link.fullData = d.link.trace;
            gd.emit('plotly_hover', {
                event: d3.event,
                points: [d.link]
            });
        }

    };

    var sourceLabel = _(gd, 'source:') + ' ';
    var targetLabel = _(gd, 'target:') + ' ';
    var concentrationLabel = _(gd, 'concentration:') + ' ';
    var incomingLabel = _(gd, 'incoming flow count:') + ' ';
    var outgoingLabel = _(gd, 'outgoing flow count:') + ' ';

    var linkHoverFollow = function(element, d) {
        if(gd._fullLayout.hovermode === false) return;
        var obj = d.link.trace.link;
        if(obj.hoverinfo === 'none' || obj.hoverinfo === 'skip') return;
        var rootBBox = gd._fullLayout._paperdiv.node().getBoundingClientRect();
        var hoverCenterX;
        var hoverCenterY;
        if(d.link.circular) {
            hoverCenterX = (d.link.circularPathData.leftInnerExtent + d.link.circularPathData.rightInnerExtent) / 2 + d.parent.translateX;
            hoverCenterY = d.link.circularPathData.verticalFullExtent + d.parent.translateY;
        } else {
            var boundingBox = element.getBoundingClientRect();
            hoverCenterX = boundingBox.left + boundingBox.width / 2 - rootBBox.left;
            hoverCenterY = boundingBox.top + boundingBox.height / 2 - rootBBox.top;
        }

        var hovertemplateLabels = {valueLabel: d3.format(d.valueFormat)(d.link.value) + d.valueSuffix};
        d.link.fullData = d.link.trace;

        var tooltip = Fx.loneHover({
            x: hoverCenterX,
            y: hoverCenterY,
            name: hovertemplateLabels.valueLabel,
            text: [
                d.link.label || '',
                sourceLabel + d.link.source.label,
                targetLabel + d.link.target.label,
                d.link.concentrationscale ? concentrationLabel + d3.format('%0.2f')(d.link.flow.labelConcentration) : ''
            ].filter(renderableValuePresent).join('<br>'),
            color: castHoverOption(obj, 'bgcolor') || Color.addOpacity(d.tinyColorHue, 1),
            borderColor: castHoverOption(obj, 'bordercolor'),
            fontFamily: castHoverOption(obj, 'font.family'),
            fontSize: castHoverOption(obj, 'font.size'),
            fontColor: castHoverOption(obj, 'font.color'),
            idealAlign: d3.event.x < hoverCenterX ? 'right' : 'left',

            hovertemplate: obj.hovertemplate,
            hovertemplateLabels: hovertemplateLabels,
            eventData: [d.link]
        }, {
            container: fullLayout._hoverlayer.node(),
            outerContainer: fullLayout._paper.node(),
            gd: gd
        });

        if(!d.link.concentrationscale) {
            makeTranslucent(tooltip, 0.65);
        }
        makeTextContrasty(tooltip);
    };

    var linkUnhover = function(element, d, sankey) {
        if(gd._fullLayout.hovermode === false) return;
        d3.select(element).call(linkNonHoveredStyle.bind(0, d, sankey, true));
        if(d.link.trace.link.hoverinfo !== 'skip') {
            d.link.fullData = d.link.trace;
            gd.emit('plotly_unhover', {
                event: d3.event,
                points: [d.link]
            });
        }

        Fx.loneUnhover(fullLayout._hoverlayer.node());
    };

    var nodeSelect = function(element, d, sankey) {
        var evt = d.node;
        evt.originalEvent = d3.event;
        gd._hoverdata = [evt];
        d3.select(element).call(nodeNonHoveredStyle, d, sankey);
        Fx.click(gd, { target: true });
    };

    var nodeHover = function(element, d, sankey) {
        if(gd._fullLayout.hovermode === false) return;
        d3.select(element).call(nodeHoveredStyle, d, sankey);
        if(d.node.trace.node.hoverinfo !== 'skip') {
            d.node.fullData = d.node.trace;
            gd.emit('plotly_hover', {
                event: d3.event,
                points: [d.node]
            });
        }
    };

    var nodeHoverFollow = function(element, d) {
        if(gd._fullLayout.hovermode === false) return;

        var obj = d.node.trace.node;
        if(obj.hoverinfo === 'none' || obj.hoverinfo === 'skip') return;
        var nodeRect = d3.select(element).select('.' + cn.nodeRect);
        var rootBBox = gd._fullLayout._paperdiv.node().getBoundingClientRect();
        var boundingBox = nodeRect.node().getBoundingClientRect();
        var hoverCenterX0 = boundingBox.left - 2 - rootBBox.left;
        var hoverCenterX1 = boundingBox.right + 2 - rootBBox.left;
        var hoverCenterY = boundingBox.top + boundingBox.height / 4 - rootBBox.top;

        var hovertemplateLabels = {valueLabel: d3.format(d.valueFormat)(d.node.value) + d.valueSuffix};
        d.node.fullData = d.node.trace;

        var tooltip = Fx.loneHover({
            x0: hoverCenterX0,
            x1: hoverCenterX1,
            y: hoverCenterY,
            name: d3.format(d.valueFormat)(d.node.value) + d.valueSuffix,
            text: [
                d.node.label,
                incomingLabel + d.node.targetLinks.length,
                outgoingLabel + d.node.sourceLinks.length
            ].filter(renderableValuePresent).join('<br>'),
            color: castHoverOption(obj, 'bgcolor') || d.tinyColorHue,
            borderColor: castHoverOption(obj, 'bordercolor'),
            fontFamily: castHoverOption(obj, 'font.family'),
            fontSize: castHoverOption(obj, 'font.size'),
            fontColor: castHoverOption(obj, 'font.color'),
            idealAlign: 'left',

            hovertemplate: obj.hovertemplate,
            hovertemplateLabels: hovertemplateLabels,
            eventData: [d.node]
        }, {
            container: fullLayout._hoverlayer.node(),
            outerContainer: fullLayout._paper.node(),
            gd: gd
        });

        makeTranslucent(tooltip, 0.85);
        makeTextContrasty(tooltip);
    };

    var nodeUnhover = function(element, d, sankey) {
        if(gd._fullLayout.hovermode === false) return;
        d3.select(element).call(nodeNonHoveredStyle, d, sankey);
        if(d.node.trace.node.hoverinfo !== 'skip') {
            d.node.fullData = d.node.trace;
            gd.emit('plotly_unhover', {
                event: d3.event,
                points: [d.node]
            });
        }

        Fx.loneUnhover(fullLayout._hoverlayer.node());
    };

    render(
        gd,
        svg,
        calcData,
        {
            width: size.w,
            height: size.h,
            margin: {
                t: size.t,
                r: size.r,
                b: size.b,
                l: size.l
            }
        },
        {
            linkEvents: {
                hover: linkHover,
                follow: linkHoverFollow,
                unhover: linkUnhover,
                select: linkSelect
            },
            nodeEvents: {
                hover: nodeHover,
                follow: nodeHoverFollow,
                unhover: nodeUnhover,
                select: nodeSelect
            }
        }
    );
};

},{"../../components/color":574,"../../components/fx":613,"../../lib":697,"./constants":1042,"./render":1046,"d3":151}],1046:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var c = _dereq_('./constants');
var d3 = _dereq_('d3');
var tinycolor = _dereq_('tinycolor2');
var Color = _dereq_('../../components/color');
var Drawing = _dereq_('../../components/drawing');
var d3Sankey = _dereq_('@plotly/d3-sankey');
var d3SankeyCircular = _dereq_('d3-sankey-circular');
var d3Force = _dereq_('d3-force');
var Lib = _dereq_('../../lib');
var gup = _dereq_('../../lib/gup');
var keyFun = gup.keyFun;
var repeat = gup.repeat;
var unwrap = gup.unwrap;
var interpolateNumber = _dereq_('d3-interpolate').interpolateNumber;

// view models

function sankeyModel(layout, d, traceIndex) {
    var calcData = unwrap(d);
    var trace = calcData.trace;
    var domain = trace.domain;
    var horizontal = trace.orientation === 'h';
    var nodePad = trace.node.pad;
    var nodeThickness = trace.node.thickness;

    var width = layout.width * (domain.x[1] - domain.x[0]);
    var height = layout.height * (domain.y[1] - domain.y[0]);

    var nodes = calcData._nodes;
    var links = calcData._links;
    var circular = calcData.circular;

    // Select Sankey generator
    var sankey;
    if(circular) {
        sankey = d3SankeyCircular
            .sankeyCircular()
            .circularLinkGap(0);
    } else {
        sankey = d3Sankey.sankey();
    }

    sankey
      .iterations(c.sankeyIterations)
      .size(horizontal ? [width, height] : [height, width])
      .nodeWidth(nodeThickness)
      .nodePadding(nodePad)
      .nodeId(function(d) {
          return d.pointNumber;
      })
      .nodes(nodes)
      .links(links);

    var graph = sankey();

    if(sankey.nodePadding() < nodePad) {
        Lib.warn('node.pad was reduced to ', sankey.nodePadding(), ' to fit within the figure.');
    }

    // Create transient nodes for animations
    for(var nodePointNumber in calcData._groupLookup) {
        var groupIndex = parseInt(calcData._groupLookup[nodePointNumber]);

        // Find node representing groupIndex
        var groupingNode;
        for(var i = 0; i < graph.nodes.length; i++) {
            if(graph.nodes[i].pointNumber === groupIndex) {
                groupingNode = graph.nodes[i];
                break;
            }
        }
        // If groupinNode is undefined, no links are targeting this group
        if(!groupingNode) continue;

        var child = {
            pointNumber: parseInt(nodePointNumber),
            x0: groupingNode.x0,
            x1: groupingNode.x1,
            y0: groupingNode.y0,
            y1: groupingNode.y1,
            partOfGroup: true,
            sourceLinks: [],
            targetLinks: []
        };

        graph.nodes.unshift(child);
        groupingNode.childrenNodes.unshift(child);
    }

    function computeLinkConcentrations() {
        var i, j, k;
        for(i = 0; i < graph.nodes.length; i++) {
            var node = graph.nodes[i];
            // Links connecting the same two nodes are part of a flow
            var flows = {};
            var flowKey;
            var link;
            for(j = 0; j < node.targetLinks.length; j++) {
                link = node.targetLinks[j];
                flowKey = link.source.pointNumber + ':' + link.target.pointNumber;
                if(!flows.hasOwnProperty(flowKey)) flows[flowKey] = [];
                flows[flowKey].push(link);
            }

            // Compute statistics for each flow
            var keys = Object.keys(flows);
            for(j = 0; j < keys.length; j++) {
                flowKey = keys[j];
                var flowLinks = flows[flowKey];

                // Find the total size of the flow and total size per label
                var total = 0;
                var totalPerLabel = {};
                for(k = 0; k < flowLinks.length; k++) {
                    link = flowLinks[k];
                    if(!totalPerLabel[link.label]) totalPerLabel[link.label] = 0;
                    totalPerLabel[link.label] += link.value;
                    total += link.value;
                }

                // Find the ratio of the link's value and the size of the flow
                for(k = 0; k < flowLinks.length; k++) {
                    link = flowLinks[k];
                    link.flow = {
                        value: total,
                        labelConcentration: totalPerLabel[link.label] / total,
                        concentration: link.value / total,
                        links: flowLinks
                    };
                }
            }

            // Gather statistics of all links at current node
            var totalOutflow = 0;
            for(j = 0; j < node.sourceLinks.length; j++) {
                totalOutflow += node.sourceLinks[j].value;
            }
            for(j = 0; j < node.sourceLinks.length; j++) {
                link = node.sourceLinks[j];
                link.concentrationOut = link.value / totalOutflow;
            }

            var totalInflow = 0;
            for(j = 0; j < node.targetLinks.length; j++) {
                totalInflow += node.targetLinks[j].value;
            }

            for(j = 0; j < node.targetLinks.length; j++) {
                link = node.targetLinks[j];
                link.concenrationIn = link.value / totalInflow;
            }
        }
    }
    computeLinkConcentrations();

    return {
        circular: circular,
        key: traceIndex,
        trace: trace,
        guid: Lib.randstr(),
        horizontal: horizontal,
        width: width,
        height: height,
        nodePad: trace.node.pad,
        nodeLineColor: trace.node.line.color,
        nodeLineWidth: trace.node.line.width,
        linkLineColor: trace.link.line.color,
        linkLineWidth: trace.link.line.width,
        valueFormat: trace.valueformat,
        valueSuffix: trace.valuesuffix,
        textFont: trace.textfont,
        translateX: domain.x[0] * layout.width + layout.margin.l,
        translateY: layout.height - domain.y[1] * layout.height + layout.margin.t,
        dragParallel: horizontal ? height : width,
        dragPerpendicular: horizontal ? width : height,
        arrangement: trace.arrangement,
        sankey: sankey,
        graph: graph,
        forceLayouts: {},
        interactionState: {
            dragInProgress: false,
            hovered: false
        }
    };
}

function linkModel(d, l, i) {
    var tc = tinycolor(l.color);
    if(l.concentrationscale) {
        tc = tinycolor(l.concentrationscale(l.flow.labelConcentration));
    }
    var basicKey = l.source.label + '|' + l.target.label;
    var key = basicKey + '__' + i;

    // for event data
    l.trace = d.trace;
    l.curveNumber = d.trace.index;

    return {
        circular: d.circular,
        key: key,
        traceId: d.key,
        pointNumber: l.pointNumber,
        link: l,
        tinyColorHue: Color.tinyRGB(tc),
        tinyColorAlpha: tc.getAlpha(),
        linkPath: linkPath,
        linkLineColor: d.linkLineColor,
        linkLineWidth: d.linkLineWidth,
        valueFormat: d.valueFormat,
        valueSuffix: d.valueSuffix,
        sankey: d.sankey,
        parent: d,
        interactionState: d.interactionState,
        flow: l.flow
    };
}

function createCircularClosedPathString(link) {
    // Using coordinates computed by d3-sankey-circular
    var pathString = '';
    var offset = link.width / 2;
    var coords = link.circularPathData;
    if(link.circularLinkType === 'top') {
        // Top path
        pathString =
          // start at the left of the target node
          'M ' +
          coords.targetX + ' ' + (coords.targetY + offset) + ' ' +
          'L' +
          coords.rightInnerExtent + ' ' + (coords.targetY + offset) +
          'A' +
          (coords.rightLargeArcRadius + offset) + ' ' + (coords.rightSmallArcRadius + offset) + ' 0 0 1 ' +
          (coords.rightFullExtent - offset) + ' ' + (coords.targetY - coords.rightSmallArcRadius) +
          'L' +
          (coords.rightFullExtent - offset) + ' ' + coords.verticalRightInnerExtent +
          'A' +
          (coords.rightLargeArcRadius + offset) + ' ' + (coords.rightLargeArcRadius + offset) + ' 0 0 1 ' +
          coords.rightInnerExtent + ' ' + (coords.verticalFullExtent - offset) +
          'L' +
          coords.leftInnerExtent + ' ' + (coords.verticalFullExtent - offset) +
          'A' +
          (coords.leftLargeArcRadius + offset) + ' ' + (coords.leftLargeArcRadius + offset) + ' 0 0 1 ' +
          (coords.leftFullExtent + offset) + ' ' + coords.verticalLeftInnerExtent +
          'L' +
          (coords.leftFullExtent + offset) + ' ' + (coords.sourceY - coords.leftSmallArcRadius) +
          'A' +
          (coords.leftLargeArcRadius + offset) + ' ' + (coords.leftSmallArcRadius + offset) + ' 0 0 1 ' +
          coords.leftInnerExtent + ' ' + (coords.sourceY + offset) +
          'L' +
          coords.sourceX + ' ' + (coords.sourceY + offset) +

          // Walking back
          'L' +
          coords.sourceX + ' ' + (coords.sourceY - offset) +
          'L' +
          coords.leftInnerExtent + ' ' + (coords.sourceY - offset) +
          'A' +
          (coords.leftLargeArcRadius - offset) + ' ' + (coords.leftSmallArcRadius - offset) + ' 0 0 0 ' +
          (coords.leftFullExtent - offset) + ' ' + (coords.sourceY - coords.leftSmallArcRadius) +
          'L' +
          (coords.leftFullExtent - offset) + ' ' + coords.verticalLeftInnerExtent +
          'A' +
          (coords.leftLargeArcRadius - offset) + ' ' + (coords.leftLargeArcRadius - offset) + ' 0 0 0 ' +
          coords.leftInnerExtent + ' ' + (coords.verticalFullExtent + offset) +
          'L' +
          coords.rightInnerExtent + ' ' + (coords.verticalFullExtent + offset) +
          'A' +
          (coords.rightLargeArcRadius - offset) + ' ' + (coords.rightLargeArcRadius - offset) + ' 0 0 0 ' +
          (coords.rightFullExtent + offset) + ' ' + coords.verticalRightInnerExtent +
          'L' +
          (coords.rightFullExtent + offset) + ' ' + (coords.targetY - coords.rightSmallArcRadius) +
          'A' +
          (coords.rightLargeArcRadius - offset) + ' ' + (coords.rightSmallArcRadius - offset) + ' 0 0 0 ' +
          coords.rightInnerExtent + ' ' + (coords.targetY - offset) +
          'L' +
          coords.targetX + ' ' + (coords.targetY - offset) +
          'Z';
    } else {
        // Bottom path
        pathString =
          // start at the left of the target node
          'M ' +
          coords.targetX + ' ' + (coords.targetY - offset) + ' ' +
          'L' +
          coords.rightInnerExtent + ' ' + (coords.targetY - offset) +
          'A' +
          (coords.rightLargeArcRadius + offset) + ' ' + (coords.rightSmallArcRadius + offset) + ' 0 0 0 ' +
          (coords.rightFullExtent - offset) + ' ' + (coords.targetY + coords.rightSmallArcRadius) +
          'L' +
          (coords.rightFullExtent - offset) + ' ' + coords.verticalRightInnerExtent +
          'A' +
          (coords.rightLargeArcRadius + offset) + ' ' + (coords.rightLargeArcRadius + offset) + ' 0 0 0 ' +
          coords.rightInnerExtent + ' ' + (coords.verticalFullExtent + offset) +
          'L' +
          coords.leftInnerExtent + ' ' + (coords.verticalFullExtent + offset) +
          'A' +
          (coords.leftLargeArcRadius + offset) + ' ' + (coords.leftLargeArcRadius + offset) + ' 0 0 0 ' +
          (coords.leftFullExtent + offset) + ' ' + coords.verticalLeftInnerExtent +
          'L' +
          (coords.leftFullExtent + offset) + ' ' + (coords.sourceY + coords.leftSmallArcRadius) +
          'A' +
          (coords.leftLargeArcRadius + offset) + ' ' + (coords.leftSmallArcRadius + offset) + ' 0 0 0 ' +
          coords.leftInnerExtent + ' ' + (coords.sourceY - offset) +
          'L' +
          coords.sourceX + ' ' + (coords.sourceY - offset) +

          // Walking back
          'L' +
          coords.sourceX + ' ' + (coords.sourceY + offset) +
          'L' +
          coords.leftInnerExtent + ' ' + (coords.sourceY + offset) +
          'A' +
          (coords.leftLargeArcRadius - offset) + ' ' + (coords.leftSmallArcRadius - offset) + ' 0 0 1 ' +
          (coords.leftFullExtent - offset) + ' ' + (coords.sourceY + coords.leftSmallArcRadius) +
          'L' +
          (coords.leftFullExtent - offset) + ' ' + coords.verticalLeftInnerExtent +
          'A' +
          (coords.leftLargeArcRadius - offset) + ' ' + (coords.leftLargeArcRadius - offset) + ' 0 0 1 ' +
          coords.leftInnerExtent + ' ' + (coords.verticalFullExtent - offset) +
          'L' +
          coords.rightInnerExtent + ' ' + (coords.verticalFullExtent - offset) +
          'A' +
          (coords.rightLargeArcRadius - offset) + ' ' + (coords.rightLargeArcRadius - offset) + ' 0 0 1 ' +
          (coords.rightFullExtent + offset) + ' ' + coords.verticalRightInnerExtent +
          'L' +
          (coords.rightFullExtent + offset) + ' ' + (coords.targetY + coords.rightSmallArcRadius) +
          'A' +
          (coords.rightLargeArcRadius - offset) + ' ' + (coords.rightSmallArcRadius - offset) + ' 0 0 1 ' +
          coords.rightInnerExtent + ' ' + (coords.targetY + offset) +
          'L' +
          coords.targetX + ' ' + (coords.targetY + offset) +
          'Z';
    }
    return pathString;
}

function linkPath() {
    var curvature = 0.5;
    function path(d) {
        if(d.link.circular) {
            return createCircularClosedPathString(d.link);
        } else {
            var x0 = d.link.source.x1;
            var x1 = d.link.target.x0;
            var xi = interpolateNumber(x0, x1);
            var x2 = xi(curvature);
            var x3 = xi(1 - curvature);
            var y0a = d.link.y0 - d.link.width / 2;
            var y0b = d.link.y0 + d.link.width / 2;
            var y1a = d.link.y1 - d.link.width / 2;
            var y1b = d.link.y1 + d.link.width / 2;
            return 'M' + x0 + ',' + y0a +
                 'C' + x2 + ',' + y0a +
                 ' ' + x3 + ',' + y1a +
                 ' ' + x1 + ',' + y1a +
                 'L' + x1 + ',' + y1b +
                 'C' + x3 + ',' + y1b +
                 ' ' + x2 + ',' + y0b +
                 ' ' + x0 + ',' + y0b +
                 'Z';
        }
    }
    return path;
}

function nodeModel(d, n) {
    var tc = tinycolor(n.color);
    var zoneThicknessPad = c.nodePadAcross;
    var zoneLengthPad = d.nodePad / 2;
    n.dx = n.x1 - n.x0;
    n.dy = n.y1 - n.y0;
    var visibleThickness = n.dx;
    var visibleLength = Math.max(0.5, n.dy);

    var key = 'node_' + n.pointNumber;
    // If it's a group, it's mutable and should be unique
    if(n.group) {
        key = Lib.randstr();
    }

    // for event data
    n.trace = d.trace;
    n.curveNumber = d.trace.index;

    return {
        index: n.pointNumber,
        key: key,
        partOfGroup: n.partOfGroup || false,
        group: n.group,
        traceId: d.key,
        node: n,
        nodePad: d.nodePad,
        nodeLineColor: d.nodeLineColor,
        nodeLineWidth: d.nodeLineWidth,
        textFont: d.textFont,
        size: d.horizontal ? d.height : d.width,
        visibleWidth: Math.ceil(visibleThickness),
        visibleHeight: visibleLength,
        zoneX: -zoneThicknessPad,
        zoneY: -zoneLengthPad,
        zoneWidth: visibleThickness + 2 * zoneThicknessPad,
        zoneHeight: visibleLength + 2 * zoneLengthPad,
        labelY: d.horizontal ? n.dy / 2 + 1 : n.dx / 2 + 1,
        left: n.originalLayer === 1,
        sizeAcross: d.width,
        forceLayouts: d.forceLayouts,
        horizontal: d.horizontal,
        darkBackground: tc.getBrightness() <= 128,
        tinyColorHue: Color.tinyRGB(tc),
        tinyColorAlpha: tc.getAlpha(),
        valueFormat: d.valueFormat,
        valueSuffix: d.valueSuffix,
        sankey: d.sankey,
        graph: d.graph,
        arrangement: d.arrangement,
        uniqueNodeLabelPathId: [d.guid, d.key, key].join('_'),
        interactionState: d.interactionState
    };
}

// rendering snippets

function updateNodePositions(sankeyNode) {
    sankeyNode
        .attr('transform', function(d) {
            return 'translate(' + d.node.x0.toFixed(3) + ', ' + (d.node.y0).toFixed(3) + ')';
        });
}

function updateNodeShapes(sankeyNode) {
    sankeyNode.call(updateNodePositions);
}

function updateShapes(sankeyNode, sankeyLink) {
    sankeyNode.call(updateNodeShapes);
    sankeyLink.attr('d', linkPath());
}

function sizeNode(rect) {
    rect
      .attr('width', function(d) {return d.node.x1 - d.node.x0;})
      .attr('height', function(d) {return d.visibleHeight;});
}

function salientEnough(d) {return (d.link.width > 1 || d.linkLineWidth > 0);}

function sankeyTransform(d) {
    var offset = 'translate(' + d.translateX + ',' + d.translateY + ')';
    return offset + (d.horizontal ? 'matrix(1 0 0 1 0 0)' : 'matrix(0 1 1 0 0 0)');
}

function nodeCentering(d) {
    return 'translate(' + (d.horizontal ? 0 : d.labelY) + ' ' + (d.horizontal ? d.labelY : 0) + ')';
}

function textGuidePath(d) {
    return d3.svg.line()([
        [d.horizontal ? (d.left ? -d.sizeAcross : d.visibleWidth + c.nodeTextOffsetHorizontal) : c.nodeTextOffsetHorizontal, 0],
        [d.horizontal ? (d.left ? - c.nodeTextOffsetHorizontal : d.sizeAcross) : d.visibleHeight - c.nodeTextOffsetHorizontal, 0]
    ]);}

function sankeyInverseTransform(d) {return d.horizontal ? 'matrix(1 0 0 1 0 0)' : 'matrix(0 1 1 0 0 0)';}
function textFlip(d) {return d.horizontal ? 'scale(1 1)' : 'scale(-1 1)';}
function nodeTextColor(d) {return d.darkBackground && !d.horizontal ? 'rgb(255,255,255)' : 'rgb(0,0,0)';}
function nodeTextOffset(d) {return d.horizontal && d.left ? '100%' : '0%';}

// event handling

function attachPointerEvents(selection, sankey, eventSet) {
    selection
        .on('.basic', null) // remove any preexisting handlers
        .on('mouseover.basic', function(d) {
            if(!d.interactionState.dragInProgress && !d.partOfGroup) {
                eventSet.hover(this, d, sankey);
                d.interactionState.hovered = [this, d];
            }
        })
        .on('mousemove.basic', function(d) {
            if(!d.interactionState.dragInProgress && !d.partOfGroup) {
                eventSet.follow(this, d);
                d.interactionState.hovered = [this, d];
            }
        })
        .on('mouseout.basic', function(d) {
            if(!d.interactionState.dragInProgress && !d.partOfGroup) {
                eventSet.unhover(this, d, sankey);
                d.interactionState.hovered = false;
            }
        })
        .on('click.basic', function(d) {
            if(d.interactionState.hovered) {
                eventSet.unhover(this, d, sankey);
                d.interactionState.hovered = false;
            }
            if(!d.interactionState.dragInProgress && !d.partOfGroup) {
                eventSet.select(this, d, sankey);
            }
        });
}

function attachDragHandler(sankeyNode, sankeyLink, callbacks) {
    var dragBehavior = d3.behavior.drag()
        .origin(function(d) {
            return {
                x: d.node.x0 + d.visibleWidth / 2,
                y: d.node.y0 + d.visibleHeight / 2
            };
        })

        .on('dragstart', function(d) {
            if(d.arrangement === 'fixed') return;
            Lib.raiseToTop(this);
            d.interactionState.dragInProgress = d.node;

            saveCurrentDragPosition(d.node);
            if(d.interactionState.hovered) {
                callbacks.nodeEvents.unhover.apply(0, d.interactionState.hovered);
                d.interactionState.hovered = false;
            }
            if(d.arrangement === 'snap') {
                var forceKey = d.traceId + '|' + d.key;
                if(d.forceLayouts[forceKey]) {
                    d.forceLayouts[forceKey].alpha(1);
                } else { // make a forceLayout if needed
                    attachForce(sankeyNode, forceKey, d);
                }
                startForce(sankeyNode, sankeyLink, d, forceKey);
            }
        })

        .on('drag', function(d) {
            if(d.arrangement === 'fixed') return;
            var x = d3.event.x;
            var y = d3.event.y;
            if(d.arrangement === 'snap') {
                d.node.x0 = x - d.visibleWidth / 2;
                d.node.x1 = x + d.visibleWidth / 2;
                d.node.y0 = y - d.visibleHeight / 2;
                d.node.y1 = y + d.visibleHeight / 2;
            } else {
                if(d.arrangement === 'freeform') {
                    d.node.x0 = x - d.visibleWidth / 2;
                    d.node.x1 = x + d.visibleWidth / 2;
                }
                d.node.y0 = Math.max(0, Math.min(d.size - d.visibleHeight, y));
                d.node.y1 = d.node.y0 + d.visibleHeight;
            }

            saveCurrentDragPosition(d.node);
            if(d.arrangement !== 'snap') {
                d.sankey.update(d.graph);
                updateShapes(sankeyNode.filter(sameLayer(d)), sankeyLink);
            }
        })

        .on('dragend', function(d) {
            d.interactionState.dragInProgress = false;
            for(var i = 0; i < d.node.childrenNodes.length; i++) {
                d.node.childrenNodes[i].x = d.node.x;
                d.node.childrenNodes[i].y = d.node.y;
            }
        });

    sankeyNode
        .on('.drag', null) // remove possible previous handlers
        .call(dragBehavior);
}

function attachForce(sankeyNode, forceKey, d) {
    // Attach force to nodes in the same column (same x coordinate)
    switchToForceFormat(d.graph.nodes);
    var nodes = d.graph.nodes
        .filter(function(n) {return n.originalX === d.node.originalX;})
        // Filter out children
        .filter(function(n) {return !n.partOfGroup;});
    d.forceLayouts[forceKey] = d3Force.forceSimulation(nodes)
        .alphaDecay(0)
        .force('collide', d3Force.forceCollide()
            .radius(function(n) {return n.dy / 2 + d.nodePad / 2;})
            .strength(1)
            .iterations(c.forceIterations))
        .force('constrain', snappingForce(sankeyNode, forceKey, nodes, d))
        .stop();
}

function startForce(sankeyNode, sankeyLink, d, forceKey) {
    window.requestAnimationFrame(function faster() {
        var i;
        for(i = 0; i < c.forceTicksPerFrame; i++) {
            d.forceLayouts[forceKey].tick();
        }

        var nodes = d.graph.nodes;
        switchToSankeyFormat(nodes);

        d.sankey.update(d.graph);
        updateShapes(sankeyNode.filter(sameLayer(d)), sankeyLink);

        if(d.forceLayouts[forceKey].alpha() > 0) {
            window.requestAnimationFrame(faster);
        }
    });
}

function snappingForce(sankeyNode, forceKey, nodes, d) {
    return function _snappingForce() {
        var maxVelocity = 0;
        for(var i = 0; i < nodes.length; i++) {
            var n = nodes[i];
            if(n === d.interactionState.dragInProgress) { // constrain node position to the dragging pointer
                n.x = n.lastDraggedX;
                n.y = n.lastDraggedY;
            } else {
                n.vx = (n.originalX - n.x) / c.forceTicksPerFrame; // snap to layer
                n.y = Math.min(d.size - n.dy / 2, Math.max(n.dy / 2, n.y)); // constrain to extent
            }
            maxVelocity = Math.max(maxVelocity, Math.abs(n.vx), Math.abs(n.vy));
        }
        if(!d.interactionState.dragInProgress && maxVelocity < 0.1 && d.forceLayouts[forceKey].alpha() > 0) {
            d.forceLayouts[forceKey].alpha(0);
        }
    };
}

// basic data utilities

function persistOriginalPlace(nodes) {
    var distinctLayerPositions = [];
    var i;
    for(i = 0; i < nodes.length; i++) {
        nodes[i].originalX = (nodes[i].x0 + nodes[i].x1) / 2;
        nodes[i].originalY = (nodes[i].y0 + nodes[i].y1) / 2;
        if(distinctLayerPositions.indexOf(nodes[i].originalX) === -1) {
            distinctLayerPositions.push(nodes[i].originalX);
        }
    }
    distinctLayerPositions.sort(function(a, b) {return a - b;});
    for(i = 0; i < nodes.length; i++) {
        nodes[i].originalLayerIndex = distinctLayerPositions.indexOf(nodes[i].originalX);
        nodes[i].originalLayer = nodes[i].originalLayerIndex / (distinctLayerPositions.length - 1);
    }
}

function saveCurrentDragPosition(d) {
    d.lastDraggedX = d.x0 + d.dx / 2;
    d.lastDraggedY = d.y0 + d.dy / 2;
}

function sameLayer(d) {
    return function(n) {return n.node.originalX === d.node.originalX;};
}

function switchToForceFormat(nodes) {
    // force uses x, y as centers
    for(var i = 0; i < nodes.length; i++) {
        nodes[i].y = nodes[i].y0 + nodes[i].dy / 2;
        nodes[i].x = nodes[i].x0 + nodes[i].dx / 2;
    }
}

function switchToSankeyFormat(nodes) {
    // sankey uses x0, x1, y0, y1
    for(var i = 0; i < nodes.length; i++) {
        nodes[i].y0 = nodes[i].y - nodes[i].dy / 2;
        nodes[i].y1 = nodes[i].y0 + nodes[i].dy;

        nodes[i].x0 = nodes[i].x - nodes[i].dx / 2;
        nodes[i].x1 = nodes[i].x0 + nodes[i].dx;
    }
}

// scene graph
module.exports = function(gd, svg, calcData, layout, callbacks) {
    // To prevent animation on first render
    var firstRender = false;
    Lib.ensureSingle(gd._fullLayout._infolayer, 'g', 'first-render', function() {
        firstRender = true;
    });

    var styledData = calcData
            .filter(function(d) {return unwrap(d).trace.visible;})
            .map(sankeyModel.bind(null, layout));

    var sankey = svg.selectAll('.' + c.cn.sankey)
        .data(styledData, keyFun);

    sankey.exit()
        .remove();

    sankey.enter()
        .append('g')
        .classed(c.cn.sankey, true)
        .style('box-sizing', 'content-box')
        .style('position', 'absolute')
        .style('left', 0)
        .style('shape-rendering', 'geometricPrecision')
        .style('pointer-events', 'auto')
        .attr('transform', sankeyTransform);

    sankey.transition()
        .ease(c.ease).duration(c.duration)
        .attr('transform', sankeyTransform);

    var sankeyLinks = sankey.selectAll('.' + c.cn.sankeyLinks)
        .data(repeat, keyFun);

    sankeyLinks.enter()
        .append('g')
        .classed(c.cn.sankeyLinks, true)
        .style('fill', 'none');

    var sankeyLink = sankeyLinks.selectAll('.' + c.cn.sankeyLink)
          .data(function(d) {
              var links = d.graph.links;
              return links
                .filter(function(l) {return l.value;})
                .map(linkModel.bind(null, d));
          }, keyFun);

    sankeyLink
          .enter().append('path')
          .classed(c.cn.sankeyLink, true)
          .call(attachPointerEvents, sankey, callbacks.linkEvents);

    sankeyLink
        .style('stroke', function(d) {
            return salientEnough(d) ? Color.tinyRGB(tinycolor(d.linkLineColor)) : d.tinyColorHue;
        })
        .style('stroke-opacity', function(d) {
            return salientEnough(d) ? Color.opacity(d.linkLineColor) : d.tinyColorAlpha;
        })
        .style('fill', function(d) {
            return d.tinyColorHue;
        })
        .style('fill-opacity', function(d) {
            return d.tinyColorAlpha;
        })
        .style('stroke-width', function(d) {
            return salientEnough(d) ? d.linkLineWidth : 1;
        })
        .attr('d', linkPath());

    sankeyLink
        .style('opacity', function() { return (gd._context.staticPlot || firstRender) ? 1 : 0;})
        .transition()
        .ease(c.ease).duration(c.duration)
        .style('opacity', 1);

    sankeyLink.exit()
        .transition()
        .ease(c.ease).duration(c.duration)
        .style('opacity', 0)
        .remove();

    var sankeyNodeSet = sankey.selectAll('.' + c.cn.sankeyNodeSet)
        .data(repeat, keyFun);

    sankeyNodeSet.enter()
        .append('g')
        .classed(c.cn.sankeyNodeSet, true);

    sankeyNodeSet
        .style('cursor', function(d) {
            switch(d.arrangement) {
                case 'fixed': return 'default';
                case 'perpendicular': return 'ns-resize';
                default: return 'move';
            }
        });

    var sankeyNode = sankeyNodeSet.selectAll('.' + c.cn.sankeyNode)
        .data(function(d) {
            var nodes = d.graph.nodes;
            persistOriginalPlace(nodes);
            return nodes
              .map(nodeModel.bind(null, d));
        }, keyFun);

    sankeyNode.enter()
        .append('g')
        .classed(c.cn.sankeyNode, true)
        .call(updateNodePositions)
        .style('opacity', function(n) { return ((gd._context.staticPlot || firstRender) && !n.partOfGroup) ? 1 : 0;});

    sankeyNode
        .call(attachPointerEvents, sankey, callbacks.nodeEvents)
        .call(attachDragHandler, sankeyLink, callbacks); // has to be here as it binds sankeyLink

    sankeyNode.transition()
        .ease(c.ease).duration(c.duration)
        .call(updateNodePositions)
        .style('opacity', function(n) { return n.partOfGroup ? 0 : 1;});

    sankeyNode.exit()
        .transition()
        .ease(c.ease).duration(c.duration)
        .style('opacity', 0)
        .remove();

    var nodeRect = sankeyNode.selectAll('.' + c.cn.nodeRect)
        .data(repeat);

    nodeRect.enter()
        .append('rect')
        .classed(c.cn.nodeRect, true)
        .call(sizeNode);

    nodeRect
        .style('stroke-width', function(d) {return d.nodeLineWidth;})
        .style('stroke', function(d) {return Color.tinyRGB(tinycolor(d.nodeLineColor));})
        .style('stroke-opacity', function(d) {return Color.opacity(d.nodeLineColor);})
        .style('fill', function(d) {return d.tinyColorHue;})
        .style('fill-opacity', function(d) {return d.tinyColorAlpha;});

    nodeRect.transition()
        .ease(c.ease).duration(c.duration)
        .call(sizeNode);

    var nodeCapture = sankeyNode.selectAll('.' + c.cn.nodeCapture)
        .data(repeat);

    nodeCapture.enter()
        .append('rect')
        .classed(c.cn.nodeCapture, true)
        .style('fill-opacity', 0);

    nodeCapture
        .attr('x', function(d) {return d.zoneX;})
        .attr('y', function(d) {return d.zoneY;})
        .attr('width', function(d) {return d.zoneWidth;})
        .attr('height', function(d) {return d.zoneHeight;});

    var nodeCentered = sankeyNode.selectAll('.' + c.cn.nodeCentered)
        .data(repeat);

    nodeCentered.enter()
        .append('g')
        .classed(c.cn.nodeCentered, true)
        .attr('transform', nodeCentering);

    nodeCentered
        .transition()
        .ease(c.ease).duration(c.duration)
        .attr('transform', nodeCentering);

    var nodeLabelGuide = nodeCentered.selectAll('.' + c.cn.nodeLabelGuide)
        .data(repeat);

    nodeLabelGuide.enter()
        .append('path')
        .classed(c.cn.nodeLabelGuide, true)
        .attr('id', function(d) {return d.uniqueNodeLabelPathId;})
        .attr('d', textGuidePath)
        .attr('transform', sankeyInverseTransform);

    nodeLabelGuide
        .transition()
        .ease(c.ease).duration(c.duration)
        .attr('d', textGuidePath)
        .attr('transform', sankeyInverseTransform);

    var nodeLabel = nodeCentered.selectAll('.' + c.cn.nodeLabel)
        .data(repeat);

    nodeLabel.enter()
        .append('text')
        .classed(c.cn.nodeLabel, true)
        .attr('transform', textFlip)
        .style('user-select', 'none')
        .style('cursor', 'default')
        .style('fill', 'black');

    nodeLabel
        .style('text-shadow', function(d) {
            return d.horizontal ? '-1px 1px 1px #fff, 1px 1px 1px #fff, 1px -1px 1px #fff, -1px -1px 1px #fff' : 'none';
        })
        .each(function(d) {Drawing.font(nodeLabel, d.textFont);});

    nodeLabel
        .transition()
        .ease(c.ease).duration(c.duration)
        .attr('transform', textFlip);

    var nodeLabelTextPath = nodeLabel.selectAll('.' + c.cn.nodeLabelTextPath)
        .data(repeat);

    nodeLabelTextPath.enter()
        .append('textPath')
        .classed(c.cn.nodeLabelTextPath, true)
        .attr('alignment-baseline', 'middle')
        .attr('xlink:href', function(d) {return '#' + d.uniqueNodeLabelPathId;})
        .attr('startOffset', nodeTextOffset)
        .style('fill', nodeTextColor);

    nodeLabelTextPath
        .text(function(d) {return d.horizontal || d.node.dy > 5 ? d.node.label : '';})
        .attr('text-anchor', function(d) {return d.horizontal && d.left ? 'end' : 'start';});

    nodeLabelTextPath
        .transition()
        .ease(c.ease).duration(c.duration)
        .attr('startOffset', nodeTextOffset)
        .style('fill', nodeTextColor);
};

},{"../../components/color":574,"../../components/drawing":595,"../../lib":697,"../../lib/gup":695,"./constants":1042,"@plotly/d3-sankey":46,"d3":151,"d3-force":144,"d3-interpolate":145,"d3-sankey-circular":148,"tinycolor2":518}],1047:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');


// arrayOk attributes, merge them into calcdata array
module.exports = function arraysToCalcdata(cd, trace) {

    // so each point knows which index it originally came from
    for(var i = 0; i < cd.length; i++) cd[i].i = i;

    Lib.mergeArray(trace.text, cd, 'tx');
    Lib.mergeArray(trace.hovertext, cd, 'htx');
    Lib.mergeArray(trace.customdata, cd, 'data');
    Lib.mergeArray(trace.textposition, cd, 'tp');
    if(trace.textfont) {
        Lib.mergeArray(trace.textfont.size, cd, 'ts');
        Lib.mergeArray(trace.textfont.color, cd, 'tc');
        Lib.mergeArray(trace.textfont.family, cd, 'tf');
    }

    var marker = trace.marker;
    if(marker) {
        Lib.mergeArray(marker.size, cd, 'ms');
        Lib.mergeArray(marker.opacity, cd, 'mo');
        Lib.mergeArray(marker.symbol, cd, 'mx');
        Lib.mergeArray(marker.color, cd, 'mc');

        var markerLine = marker.line;
        if(marker.line) {
            Lib.mergeArray(markerLine.color, cd, 'mlc');
            Lib.mergeArray(markerLine.width, cd, 'mlw');
        }

        var markerGradient = marker.gradient;
        if(markerGradient && markerGradient.type !== 'none') {
            Lib.mergeArray(markerGradient.type, cd, 'mgt');
            Lib.mergeArray(markerGradient.color, cd, 'mgc');
        }
    }
};

},{"../../lib":697}],1048:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var colorAttributes = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
var fontAttrs = _dereq_('../../plots/font_attributes');
var dash = _dereq_('../../components/drawing/attributes').dash;

var Drawing = _dereq_('../../components/drawing');
var constants = _dereq_('./constants');
var extendFlat = _dereq_('../../lib/extend').extendFlat;

module.exports = {
    x: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        anim: true,
        
    },
    x0: {
        valType: 'any',
        dflt: 0,
        
        editType: 'calc+clearAxisTypes',
        anim: true,
        
    },
    dx: {
        valType: 'number',
        dflt: 1,
        
        editType: 'calc',
        anim: true,
        
    },
    y: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        anim: true,
        
    },
    y0: {
        valType: 'any',
        dflt: 0,
        
        editType: 'calc+clearAxisTypes',
        anim: true,
        
    },
    dy: {
        valType: 'number',
        dflt: 1,
        
        editType: 'calc',
        anim: true,
        
    },

    stackgroup: {
        valType: 'string',
        
        dflt: '',
        editType: 'calc',
        
    },
    orientation: {
        valType: 'enumerated',
        
        values: ['v', 'h'],
        editType: 'calc',
        
    },
    groupnorm: {
        valType: 'enumerated',
        values: ['', 'fraction', 'percent'],
        dflt: '',
        
        editType: 'calc',
        
    },
    stackgaps: {
        valType: 'enumerated',
        values: ['infer zero', 'interpolate'],
        dflt: 'infer zero',
        
        editType: 'calc',
        
    },

    text: {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        editType: 'calc',
        
    },
    hovertext: {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        editType: 'style',
        
    },
    mode: {
        valType: 'flaglist',
        flags: ['lines', 'markers', 'text'],
        extras: ['none'],
        
        editType: 'calc',
        
    },
    hoveron: {
        valType: 'flaglist',
        flags: ['points', 'fills'],
        
        editType: 'style',
        
    },
    hovertemplate: hovertemplateAttrs({}, {
        keys: constants.eventDataKeys
    }),
    line: {
        color: {
            valType: 'color',
            
            editType: 'style',
            anim: true,
            
        },
        width: {
            valType: 'number',
            min: 0,
            dflt: 2,
            
            editType: 'style',
            anim: true,
            
        },
        shape: {
            valType: 'enumerated',
            values: ['linear', 'spline', 'hv', 'vh', 'hvh', 'vhv'],
            dflt: 'linear',
            
            editType: 'plot',
            
        },
        smoothing: {
            valType: 'number',
            min: 0,
            max: 1.3,
            dflt: 1,
            
            editType: 'plot',
            
        },
        dash: extendFlat({}, dash, {editType: 'style'}),
        simplify: {
            valType: 'boolean',
            dflt: true,
            
            editType: 'plot',
            
        },
        editType: 'plot'
    },

    connectgaps: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'calc',
        
    },
    cliponaxis: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'plot',
        
    },

    fill: {
        valType: 'enumerated',
        values: ['none', 'tozeroy', 'tozerox', 'tonexty', 'tonextx', 'toself', 'tonext'],
        
        editType: 'calc',
        
    },
    fillcolor: {
        valType: 'color',
        
        editType: 'style',
        anim: true,
        
    },
    marker: extendFlat({
        symbol: {
            valType: 'enumerated',
            values: Drawing.symbolList,
            dflt: 'circle',
            arrayOk: true,
            
            editType: 'style',
            
        },
        opacity: {
            valType: 'number',
            min: 0,
            max: 1,
            arrayOk: true,
            
            editType: 'style',
            anim: true,
            
        },
        size: {
            valType: 'number',
            min: 0,
            dflt: 6,
            arrayOk: true,
            
            editType: 'calc',
            anim: true,
            
        },
        maxdisplayed: {
            valType: 'number',
            min: 0,
            dflt: 0,
            
            editType: 'plot',
            
        },
        sizeref: {
            valType: 'number',
            dflt: 1,
            
            editType: 'calc',
            
        },
        sizemin: {
            valType: 'number',
            min: 0,
            dflt: 0,
            
            editType: 'calc',
            
        },
        sizemode: {
            valType: 'enumerated',
            values: ['diameter', 'area'],
            dflt: 'diameter',
            
            editType: 'calc',
            
        },

        colorbar: colorbarAttrs,

        line: extendFlat({
            width: {
                valType: 'number',
                min: 0,
                arrayOk: true,
                
                editType: 'style',
                anim: true,
                
            },
            editType: 'calc'
        },
            colorAttributes('marker.line', {anim: true})
        ),
        gradient: {
            type: {
                valType: 'enumerated',
                values: ['radial', 'horizontal', 'vertical', 'none'],
                arrayOk: true,
                dflt: 'none',
                
                editType: 'calc',
                
            },
            color: {
                valType: 'color',
                arrayOk: true,
                
                editType: 'calc',
                
            },
            editType: 'calc'
        },
        editType: 'calc'
    },
        colorAttributes('marker', {anim: true})
    ),
    selected: {
        marker: {
            opacity: {
                valType: 'number',
                min: 0,
                max: 1,
                
                editType: 'style',
                
            },
            color: {
                valType: 'color',
                
                editType: 'style',
                
            },
            size: {
                valType: 'number',
                min: 0,
                
                editType: 'style',
                
            },
            editType: 'style'
        },
        textfont: {
            color: {
                valType: 'color',
                
                editType: 'style',
                
            },
            editType: 'style'
        },
        editType: 'style'
    },
    unselected: {
        marker: {
            opacity: {
                valType: 'number',
                min: 0,
                max: 1,
                
                editType: 'style',
                
            },
            color: {
                valType: 'color',
                
                editType: 'style',
                
            },
            size: {
                valType: 'number',
                min: 0,
                
                editType: 'style',
                
            },
            editType: 'style'
        },
        textfont: {
            color: {
                valType: 'color',
                
                editType: 'style',
                
            },
            editType: 'style'
        },
        editType: 'style'
    },

    textposition: {
        valType: 'enumerated',
        values: [
            'top left', 'top center', 'top right',
            'middle left', 'middle center', 'middle right',
            'bottom left', 'bottom center', 'bottom right'
        ],
        dflt: 'middle center',
        arrayOk: true,
        
        editType: 'calc',
        
    },
    textfont: fontAttrs({
        editType: 'calc',
        colorEditType: 'style',
        arrayOk: true,
        
    }),

    r: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    t: {
        valType: 'data_array',
        editType: 'calc',
        
    }
};

},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/drawing":595,"../../components/drawing/attributes":594,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plots/font_attributes":771,"./constants":1052}],1049:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var Lib = _dereq_('../../lib');

var Axes = _dereq_('../../plots/cartesian/axes');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

var subTypes = _dereq_('./subtypes');
var calcColorscale = _dereq_('./colorscale_calc');
var arraysToCalcdata = _dereq_('./arrays_to_calcdata');
var calcSelection = _dereq_('./calc_selection');

function calc(gd, trace) {
    var fullLayout = gd._fullLayout;
    var xa = Axes.getFromId(gd, trace.xaxis || 'x');
    var ya = Axes.getFromId(gd, trace.yaxis || 'y');
    var x = xa.makeCalcdata(trace, 'x');
    var y = ya.makeCalcdata(trace, 'y');
    var serieslen = trace._length;
    var cd = new Array(serieslen);
    var ids = trace.ids;
    var stackGroupOpts = getStackOpts(trace, fullLayout, xa, ya);
    var interpolateGaps = false;
    var isV, i, j, k, interpolate, vali;

    setFirstScatter(fullLayout, trace);

    var xAttr = 'x';
    var yAttr = 'y';
    var posAttr;
    if(stackGroupOpts) {
        stackGroupOpts.traceIndices.push(trace.index);
        isV = stackGroupOpts.orientation === 'v';
        // size, like we use for bar
        if(isV) {
            yAttr = 's';
            posAttr = 'x';
        }
        else {
            xAttr = 's';
            posAttr = 'y';
        }
        interpolate = stackGroupOpts.stackgaps === 'interpolate';
    }
    else {
        var ppad = calcMarkerSize(trace, serieslen);
        calcAxisExpansion(gd, trace, xa, ya, x, y, ppad);
    }

    for(i = 0; i < serieslen; i++) {
        var cdi = cd[i] = {};
        var xValid = isNumeric(x[i]);
        var yValid = isNumeric(y[i]);
        if(xValid && yValid) {
            cdi[xAttr] = x[i];
            cdi[yAttr] = y[i];
        }
        // if we're stacking we need to hold on to all valid positions
        // even with invalid sizes
        else if(stackGroupOpts && (isV ? xValid : yValid)) {
            cdi[posAttr] = isV ? x[i] : y[i];
            cdi.gap = true;
            if(interpolate) {
                cdi.s = BADNUM;
                interpolateGaps = true;
            }
            else {
                cdi.s = 0;
            }
        }
        else {
            cdi[xAttr] = cdi[yAttr] = BADNUM;
        }

        if(ids) {
            cdi.id = String(ids[i]);
        }
    }

    arraysToCalcdata(cd, trace);
    calcColorscale(gd, trace);
    calcSelection(cd, trace);

    if(stackGroupOpts) {
        // remove bad positions and sort
        // note that original indices get added to cd in arraysToCalcdata
        i = 0;
        while(i < cd.length) {
            if(cd[i][posAttr] === BADNUM) {
                cd.splice(i, 1);
            }
            else i++;
        }

        Lib.sort(cd, function(a, b) {
            return (a[posAttr] - b[posAttr]) || (a.i - b.i);
        });

        if(interpolateGaps) {
            // first fill the beginning with constant from the first point
            i = 0;
            while(i < cd.length - 1 && cd[i].gap) {
                i++;
            }
            vali = cd[i].s;
            if(!vali) vali = cd[i].s = 0; // in case of no data AT ALL in this trace - use 0
            for(j = 0; j < i; j++) {
                cd[j].s = vali;
            }
            // then fill the end with constant from the last point
            k = cd.length - 1;
            while(k > i && cd[k].gap) {
                k--;
            }
            vali = cd[k].s;
            for(j = cd.length - 1; j > k; j--) {
                cd[j].s = vali;
            }
            // now interpolate internal gaps linearly
            while(i < k) {
                i++;
                if(cd[i].gap) {
                    j = i + 1;
                    while(cd[j].gap) {
                        j++;
                    }
                    var pos0 = cd[i - 1][posAttr];
                    var size0 = cd[i - 1].s;
                    var m = (cd[j].s - size0) / (cd[j][posAttr] - pos0);
                    while(i < j) {
                        cd[i].s = size0 + (cd[i][posAttr] - pos0) * m;
                        i++;
                    }
                }
            }
        }
    }

    return cd;
}

function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) {
    var serieslen = trace._length;
    var fullLayout = gd._fullLayout;
    var xId = xa._id;
    var yId = ya._id;
    var firstScatter = fullLayout._firstScatter[firstScatterGroup(trace)] === trace.uid;
    var stackOrientation = (getStackOpts(trace, fullLayout, xa, ya) || {}).orientation;
    var fill = trace.fill;

    // cancel minimum tick spacings (only applies to bars and boxes)
    xa._minDtick = 0;
    ya._minDtick = 0;

    // check whether bounds should be tight, padded, extended to zero...
    // most cases both should be padded on both ends, so start with that.
    var xOptions = {padded: true};
    var yOptions = {padded: true};

    if(ppad) {
        xOptions.ppad = yOptions.ppad = ppad;
    }

    // TODO: text size

    var openEnded = serieslen < 2 || (x[0] !== x[serieslen - 1]) || (y[0] !== y[serieslen - 1]);

    // include zero (tight) and extremes (padded) if fill to zero
    // (unless the shape is closed, then it's just filling the shape regardless)
    if(openEnded && (
        (fill === 'tozerox') ||
        ((fill === 'tonextx') && (firstScatter || stackOrientation === 'h'))
    )) {
        xOptions.tozero = true;
    }

    // if no error bars, markers or text, or fill to y=0 remove x padding
    else if(!(trace.error_y || {}).visible && (
            (fill === 'tonexty' || fill === 'tozeroy') ||
            (!subTypes.hasMarkers(trace) && !subTypes.hasText(trace))
        )) {
        xOptions.padded = false;
        xOptions.ppad = 0;
    }

    // now check for y - rather different logic, though still mostly padded both ends
    // include zero (tight) and extremes (padded) if fill to zero
    // (unless the shape is closed, then it's just filling the shape regardless)
    if(openEnded && (
        (fill === 'tozeroy') ||
        ((fill === 'tonexty') && (firstScatter || stackOrientation === 'v'))
    )) {
        yOptions.tozero = true;
    }

    // tight y: any x fill
    else if(fill === 'tonextx' || fill === 'tozerox') {
        yOptions.padded = false;
    }

    // N.B. asymmetric splom traces call this with blank {} xa or ya
    if(xId) trace._extremes[xId] = Axes.findExtremes(xa, x, xOptions);
    if(yId) trace._extremes[yId] = Axes.findExtremes(ya, y, yOptions);
}

function calcMarkerSize(trace, serieslen) {
    if(!subTypes.hasMarkers(trace)) return;

    // Treat size like x or y arrays --- Run d2c
    // this needs to go before ppad computation
    var marker = trace.marker;
    var sizeref = 1.6 * (trace.marker.sizeref || 1);
    var markerTrans;

    if(trace.marker.sizemode === 'area') {
        markerTrans = function(v) {
            return Math.max(Math.sqrt((v || 0) / sizeref), 3);
        };
    } else {
        markerTrans = function(v) {
            return Math.max((v || 0) / sizeref, 3);
        };
    }

    if(Lib.isArrayOrTypedArray(marker.size)) {
        // I tried auto-type but category and dates dont make much sense.
        var ax = {type: 'linear'};
        Axes.setConvert(ax);

        var s = ax.makeCalcdata(trace.marker, 'size');

        var sizeOut = new Array(serieslen);
        for(var i = 0; i < serieslen; i++) {
            sizeOut[i] = markerTrans(s[i]);
        }
        return sizeOut;

    } else {
        return markerTrans(marker.size);
    }
}

/**
 * mark the first scatter trace for each subplot
 * note that scatter and scattergl each get their own first trace
 * note also that I'm doing this during calc rather than supplyDefaults
 * so I don't need to worry about transforms, but if we ever do
 * per-trace calc this will get confused.
 */
function setFirstScatter(fullLayout, trace) {
    var group = firstScatterGroup(trace);
    var firstScatter = fullLayout._firstScatter;
    if(!firstScatter[group]) firstScatter[group] = trace.uid;
}

function firstScatterGroup(trace) {
    var stackGroup = trace.stackgroup;
    return trace.xaxis + trace.yaxis + trace.type +
        (stackGroup ? '-' + stackGroup : '');
}

function getStackOpts(trace, fullLayout, xa, ya) {
    var stackGroup = trace.stackgroup;
    if(!stackGroup) return;
    var stackOpts = fullLayout._scatterStackOpts[xa._id + ya._id][stackGroup];
    var stackAx = stackOpts.orientation === 'v' ? ya : xa;
    // Allow stacking only on numeric axes
    // calc is a little late to be figuring this out, but during supplyDefaults
    // we don't know the axis type yet
    if(stackAx.type === 'linear' || stackAx.type === 'log') return stackOpts;
}

module.exports = {
    calc: calc,
    calcMarkerSize: calcMarkerSize,
    calcAxisExpansion: calcAxisExpansion,
    setFirstScatter: setFirstScatter,
    getStackOpts: getStackOpts
};

},{"../../constants/numerical":674,"../../lib":697,"../../plots/cartesian/axes":745,"./arrays_to_calcdata":1047,"./calc_selection":1050,"./colorscale_calc":1051,"./subtypes":1072,"fast-isnumeric":218}],1050:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

module.exports = function calcSelection(cd, trace) {
    if(Lib.isArrayOrTypedArray(trace.selectedpoints)) {
        Lib.tagSelected(cd, trace);
    }
};

},{"../../lib":697}],1051:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
var calcColorscale = _dereq_('../../components/colorscale/calc');

var subTypes = _dereq_('./subtypes');

module.exports = function calcMarkerColorscale(gd, trace) {
    if(subTypes.hasLines(trace) && hasColorscale(trace, 'line')) {
        calcColorscale(gd, trace, {
            vals: trace.line.color,
            containerStr: 'line',
            cLetter: 'c'
        });
    }

    if(subTypes.hasMarkers(trace)) {
        if(hasColorscale(trace, 'marker')) {
            calcColorscale(gd, trace, {
                vals: trace.marker.color,
                containerStr: 'marker',
                cLetter: 'c'
            });
        }
        if(hasColorscale(trace, 'marker.line')) {
            calcColorscale(gd, trace, {
                vals: trace.marker.line.color,
                containerStr: 'marker.line',
                cLetter: 'c'
            });
        }
    }
};

},{"../../components/colorscale/calc":582,"../../components/colorscale/helpers":585,"./subtypes":1072}],1052:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = {
    PTS_LINESONLY: 20,

    // fixed parameters of clustering and clipping algorithms

    // fraction of clustering tolerance "so close we don't even consider it a new point"
    minTolerance: 0.2,
    // how fast does clustering tolerance increase as you get away from the visible region
    toleranceGrowth: 10,

    // number of viewport sizes away from the visible region
    // at which we clip all lines to the perimeter
    maxScreensAway: 20,

    eventDataKeys: []
};

},{}],1053:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var calc = _dereq_('./calc');

/*
 * Scatter stacking & normalization calculations
 * runs per subplot, and can handle multiple stacking groups
 */

module.exports = function crossTraceCalc(gd, plotinfo) {
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;
    var subplot = xa._id + ya._id;

    var subplotStackOpts = gd._fullLayout._scatterStackOpts[subplot];
    if(!subplotStackOpts) return;

    var calcTraces = gd.calcdata;

    var i, j, k, i2, cd, cd0, posj, sumj, norm;
    var groupOpts, interpolate, groupnorm, posAttr, valAttr;
    var hasAnyBlanks;

    for(var stackGroup in subplotStackOpts) {
        groupOpts = subplotStackOpts[stackGroup];
        var indices = groupOpts.traceIndices;

        // can get here with no indices if the stack axis is non-numeric
        if(!indices.length) continue;

        interpolate = groupOpts.stackgaps === 'interpolate';
        groupnorm = groupOpts.groupnorm;
        if(groupOpts.orientation === 'v') {
            posAttr = 'x';
            valAttr = 'y';
        }
        else {
            posAttr = 'y';
            valAttr = 'x';
        }
        hasAnyBlanks = new Array(indices.length);
        for(i = 0; i < hasAnyBlanks.length; i++) {
            hasAnyBlanks[i] = false;
        }

        // Collect the complete set of all positions across ALL traces.
        // Start with the first trace, then interleave items from later traces
        // as needed.
        // Fill in mising items as we go.
        cd0 = calcTraces[indices[0]];
        var allPositions = new Array(cd0.length);
        for(i = 0; i < cd0.length; i++) {
            allPositions[i] = cd0[i][posAttr];
        }

        for(i = 1; i < indices.length; i++) {
            cd = calcTraces[indices[i]];

            for(j = k = 0; j < cd.length; j++) {
                posj = cd[j][posAttr];
                for(; posj > allPositions[k] && k < allPositions.length; k++) {
                    // the current trace is missing a position from some previous trace(s)
                    insertBlank(cd, j, allPositions[k], i, hasAnyBlanks, interpolate, posAttr);
                    j++;
                }
                if(posj !== allPositions[k]) {
                    // previous trace(s) are missing a position from the current trace
                    for(i2 = 0; i2 < i; i2++) {
                        insertBlank(calcTraces[indices[i2]], k, posj, i2, hasAnyBlanks, interpolate, posAttr);
                    }
                    allPositions.splice(k, 0, posj);
                }
                k++;
            }
            for(; k < allPositions.length; k++) {
                insertBlank(cd, j, allPositions[k], i, hasAnyBlanks, interpolate, posAttr);
                j++;
            }
        }

        var serieslen = allPositions.length;

        // stack (and normalize)!
        for(j = 0; j < cd0.length; j++) {
            sumj = cd0[j][valAttr] = cd0[j].s;
            for(i = 1; i < indices.length; i++) {
                cd = calcTraces[indices[i]];
                cd[0].trace._rawLength = cd[0].trace._length;
                cd[0].trace._length = serieslen;
                sumj += cd[j].s;
                cd[j][valAttr] = sumj;
            }

            if(groupnorm) {
                norm = ((groupnorm === 'fraction') ? sumj : (sumj / 100)) || 1;
                for(i = 0; i < indices.length; i++) {
                    var cdj = calcTraces[indices[i]][j];
                    cdj[valAttr] /= norm;
                    cdj.sNorm = cdj.s / norm;
                }
            }
        }

        // autorange
        for(i = 0; i < indices.length; i++) {
            cd = calcTraces[indices[i]];
            var trace = cd[0].trace;
            var ppad = calc.calcMarkerSize(trace, trace._rawLength);
            var arrayPad = Array.isArray(ppad);
            if((ppad && hasAnyBlanks[i]) || arrayPad) {
                var ppadRaw = ppad;
                ppad = new Array(serieslen);
                for(j = 0; j < serieslen; j++) {
                    ppad[j] = cd[j].gap ? 0 : (arrayPad ? ppadRaw[cd[j].i] : ppadRaw);
                }
            }
            var x = new Array(serieslen);
            var y = new Array(serieslen);
            for(j = 0; j < serieslen; j++) {
                x[j] = cd[j].x;
                y[j] = cd[j].y;
            }
            calc.calcAxisExpansion(gd, trace, xa, ya, x, y, ppad);

            // while we're here (in a loop over all traces in the stack)
            // record the orientation, so hover can find it easily
            cd[0].t.orientation = groupOpts.orientation;
        }
    }
};

function insertBlank(calcTrace, index, position, traceIndex, hasAnyBlanks, interpolate, posAttr) {
    hasAnyBlanks[traceIndex] = true;
    var newEntry = {
        i: null,
        gap: true,
        s: 0
    };
    newEntry[posAttr] = position;
    calcTrace.splice(index, 0, newEntry);
    // Even if we're not interpolating, if one trace has multiple
    // values at the same position and this trace only has one value there,
    // we just duplicate that one value rather than insert a zero.
    // We also make it look like a real point - because it's ambiguous which
    // one really is the real one!
    if(index && position === calcTrace[index - 1][posAttr]) {
        var prevEntry = calcTrace[index - 1];
        newEntry.s = prevEntry.s;
        // TODO is it going to cause any problems to have multiple
        // calcdata points with the same index?
        newEntry.i = prevEntry.i;
        newEntry.gap = prevEntry.gap;
    }
    else if(interpolate) {
        newEntry.s = getInterp(calcTrace, index, position, posAttr);
    }
    if(!index) {
        // t and trace need to stay on the first cd entry
        calcTrace[0].t = calcTrace[1].t;
        calcTrace[0].trace = calcTrace[1].trace;
        delete calcTrace[1].t;
        delete calcTrace[1].trace;
    }
}

function getInterp(calcTrace, index, position, posAttr) {
    var pt0 = calcTrace[index - 1];
    var pt1 = calcTrace[index + 1];
    if(!pt1) return pt0.s;
    if(!pt0) return pt1.s;
    return pt0.s + (pt1.s - pt0.s) * (position - pt0[posAttr]) / (pt1[posAttr] - pt0[posAttr]);
}

},{"./calc":1049}],1054:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


// remove opacity for any trace that has a fill or is filled to
module.exports = function crossTraceDefaults(fullData) {
    for(var i = 0; i < fullData.length; i++) {
        var tracei = fullData[i];
        if(tracei.type !== 'scatter') continue;

        var filli = tracei.fill;
        if(filli === 'none' || filli === 'toself') continue;

        tracei.opacity = undefined;

        if(filli === 'tonexty' || filli === 'tonextx') {
            for(var j = i - 1; j >= 0; j--) {
                var tracej = fullData[j];

                if((tracej.type === 'scatter') &&
                        (tracej.xaxis === tracei.xaxis) &&
                        (tracej.yaxis === tracei.yaxis)) {
                    tracej.opacity = undefined;
                    break;
                }
            }
        }
    }
};

},{}],1055:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Registry = _dereq_('../../registry');

var attributes = _dereq_('./attributes');
var constants = _dereq_('./constants');
var subTypes = _dereq_('./subtypes');
var handleXYDefaults = _dereq_('./xy_defaults');
var handleStackDefaults = _dereq_('./stack_defaults');
var handleMarkerDefaults = _dereq_('./marker_defaults');
var handleLineDefaults = _dereq_('./line_defaults');
var handleLineShapeDefaults = _dereq_('./line_shape_defaults');
var handleTextDefaults = _dereq_('./text_defaults');
var handleFillColorDefaults = _dereq_('./fillcolor_defaults');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var len = handleXYDefaults(traceIn, traceOut, layout, coerce);
    if(!len) traceOut.visible = false;

    if(!traceOut.visible) return;

    var stackGroupOpts = handleStackDefaults(traceIn, traceOut, layout, coerce);

    var defaultMode = !stackGroupOpts && (len < constants.PTS_LINESONLY) ?
        'lines+markers' : 'lines';
    coerce('text');
    coerce('hovertext');
    coerce('mode', defaultMode);

    if(subTypes.hasLines(traceOut)) {
        handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
        handleLineShapeDefaults(traceIn, traceOut, coerce);
        coerce('connectgaps');
        coerce('line.simplify');
    }

    if(subTypes.hasMarkers(traceOut)) {
        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true});
    }

    if(subTypes.hasText(traceOut)) {
        handleTextDefaults(traceIn, traceOut, layout, coerce);
    }

    var dfltHoverOn = [];

    if(subTypes.hasMarkers(traceOut) || subTypes.hasText(traceOut)) {
        coerce('cliponaxis');
        coerce('marker.maxdisplayed');
        dfltHoverOn.push('points');
    }

    // It's possible for this default to be changed by a later trace.
    // We handle that case in some hacky code inside handleStackDefaults.
    coerce('fill', stackGroupOpts ? stackGroupOpts.fillDflt : 'none');
    if(traceOut.fill !== 'none') {
        handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
        if(!subTypes.hasLines(traceOut)) handleLineShapeDefaults(traceIn, traceOut, coerce);
    }

    var lineColor = (traceOut.line || {}).color;
    var markerColor = (traceOut.marker || {}).color;

    if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') {
        dfltHoverOn.push('fills');
    }
    coerce('hoveron', dfltHoverOn.join('+') || 'points');
    if(traceOut.hoveron !== 'fills') coerce('hovertemplate');
    var errorBarsSupplyDefaults = Registry.getComponentMethod('errorbars', 'supplyDefaults');
    errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, {axis: 'y'});
    errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, {axis: 'x', inherit: 'y'});

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};

},{"../../lib":697,"../../registry":826,"./attributes":1048,"./constants":1052,"./fillcolor_defaults":1057,"./line_defaults":1061,"./line_shape_defaults":1063,"./marker_defaults":1067,"./stack_defaults":1070,"./subtypes":1072,"./text_defaults":1073,"./xy_defaults":1074}],1056:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

/** Fill hover 'pointData' container with 'correct' hover text value
 *
 * - If trace hoverinfo contains a 'text' flag and hovertext is not set,
 *   the text elements will be seen in the hover labels.
 *
 * - If trace hoverinfo contains a 'text' flag and hovertext is set,
 *   hovertext takes precedence over text
 *   i.e. the hoverinfo elements will be seen in the hover labels
 *
 *  @param {object} calcPt
 *  @param {object} trace
 *  @param {object || array} contOut (mutated here)
 */
module.exports = function fillHoverText(calcPt, trace, contOut) {
    var fill = Array.isArray(contOut) ?
        function(v) { contOut.push(v); } :
        function(v) { contOut.text = v; };

    var htx = Lib.extractOption(calcPt, trace, 'htx', 'hovertext');
    if(isValid(htx)) return fill(htx);

    var tx = Lib.extractOption(calcPt, trace, 'tx', 'text');
    if(isValid(tx)) return fill(tx);
};

// accept all truthy values and 0 (which gets cast to '0' in the hover labels)
function isValid(v) {
    return v || v === 0;
}

},{"../../lib":697}],1057:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Color = _dereq_('../../components/color');
var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;

module.exports = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) {
    var inheritColorFromMarker = false;

    if(traceOut.marker) {
        // don't try to inherit a color array
        var markerColor = traceOut.marker.color;
        var markerLineColor = (traceOut.marker.line || {}).color;

        if(markerColor && !isArrayOrTypedArray(markerColor)) {
            inheritColorFromMarker = markerColor;
        }
        else if(markerLineColor && !isArrayOrTypedArray(markerLineColor)) {
            inheritColorFromMarker = markerLineColor;
        }
    }

    coerce('fillcolor', Color.addOpacity(
        (traceOut.line || {}).color ||
        inheritColorFromMarker ||
        defaultColor, 0.5
    ));
};

},{"../../components/color":574,"../../lib":697}],1058:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Color = _dereq_('../../components/color');
var subtypes = _dereq_('./subtypes');


module.exports = function getTraceColor(trace, di) {
    var lc, tc;

    // TODO: text modes

    if(trace.mode === 'lines') {
        lc = trace.line.color;
        return (lc && Color.opacity(lc)) ?
            lc : trace.fillcolor;
    }
    else if(trace.mode === 'none') {
        return trace.fill ? trace.fillcolor : '';
    }
    else {
        var mc = di.mcc || (trace.marker || {}).color;
        var mlc = di.mlcc || ((trace.marker || {}).line || {}).color;

        tc = (mc && Color.opacity(mc)) ? mc :
            (mlc && Color.opacity(mlc) &&
                (di.mlw || ((trace.marker || {}).line || {}).width)) ? mlc : '';

        if(tc) {
            // make sure the points aren't TOO transparent
            if(Color.opacity(tc) < 0.3) {
                return Color.addOpacity(tc, 0.3);
            }
            else return tc;
        }
        else {
            lc = (trace.line || {}).color;
            return (lc && Color.opacity(lc) &&
                subtypes.hasLines(trace) && trace.line.width) ?
                    lc : trace.fillcolor;
        }
    }
};

},{"../../components/color":574,"./subtypes":1072}],1059:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Fx = _dereq_('../../components/fx');
var Registry = _dereq_('../../registry');
var getTraceColor = _dereq_('./get_trace_color');
var Color = _dereq_('../../components/color');
var fillHoverText = _dereq_('./fill_hover_text');

module.exports = function hoverPoints(pointData, xval, yval, hovermode) {
    var cd = pointData.cd;
    var trace = cd[0].trace;
    var xa = pointData.xa;
    var ya = pointData.ya;
    var xpx = xa.c2p(xval);
    var ypx = ya.c2p(yval);
    var pt = [xpx, ypx];
    var hoveron = trace.hoveron || '';
    var minRad = (trace.mode.indexOf('markers') !== -1) ? 3 : 0.5;

    // look for points to hover on first, then take fills only if we
    // didn't find a point
    if(hoveron.indexOf('points') !== -1) {
        var dx = function(di) {
            // dx and dy are used in compare modes - here we want to always
            // prioritize the closest data point, at least as long as markers are
            // the same size or nonexistent, but still try to prioritize small markers too.
            var rad = Math.max(3, di.mrc || 0);
            var kink = 1 - 1 / rad;
            var dxRaw = Math.abs(xa.c2p(di.x) - xpx);
            var d = (dxRaw < rad) ? (kink * dxRaw / rad) : (dxRaw - rad + kink);
            return d;
        };
        var dy = function(di) {
            var rad = Math.max(3, di.mrc || 0);
            var kink = 1 - 1 / rad;
            var dyRaw = Math.abs(ya.c2p(di.y) - ypx);
            return (dyRaw < rad) ? (kink * dyRaw / rad) : (dyRaw - rad + kink);
        };
        var dxy = function(di) {
            // scatter points: d.mrc is the calculated marker radius
            // adjust the distance so if you're inside the marker it
            // always will show up regardless of point size, but
            // prioritize smaller points
            var rad = Math.max(minRad, di.mrc || 0);
            var dx = xa.c2p(di.x) - xpx;
            var dy = ya.c2p(di.y) - ypx;
            return Math.max(Math.sqrt(dx * dx + dy * dy) - rad, 1 - minRad / rad);
        };
        var distfn = Fx.getDistanceFunction(hovermode, dx, dy, dxy);

        Fx.getClosest(cd, distfn, pointData);

        // skip the rest (for this trace) if we didn't find a close point
        if(pointData.index !== false) {

            // the closest data point
            var di = cd[pointData.index];
            var xc = xa.c2p(di.x, true);
            var yc = ya.c2p(di.y, true);
            var rad = di.mrc || 1;

            // now we're done using the whole `calcdata` array, replace the
            // index with the original index (in case of inserted point from
            // stacked area)
            pointData.index = di.i;

            var orientation = cd[0].t.orientation;
            // TODO: for scatter and bar, option to show (sub)totals and
            // raw data? Currently stacked and/or normalized bars just show
            // the normalized individual sizes, so that's what I'm doing here
            // for now.
            var sizeVal = orientation && (di.sNorm || di.s);
            var xLabelVal = (orientation === 'h') ? sizeVal : di.x;
            var yLabelVal = (orientation === 'v') ? sizeVal : di.y;

            Lib.extendFlat(pointData, {
                color: getTraceColor(trace, di),

                x0: xc - rad,
                x1: xc + rad,
                xLabelVal: xLabelVal,

                y0: yc - rad,
                y1: yc + rad,
                yLabelVal: yLabelVal,

                spikeDistance: dxy(di),
                hovertemplate: trace.hovertemplate
            });

            fillHoverText(di, trace, pointData);
            Registry.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData);

            return [pointData];
        }
    }

    // even if hoveron is 'fills', only use it if we have polygons too
    if(hoveron.indexOf('fills') !== -1 && trace._polygons) {
        var polygons = trace._polygons;
        var polygonsIn = [];
        var inside = false;
        var xmin = Infinity;
        var xmax = -Infinity;
        var ymin = Infinity;
        var ymax = -Infinity;

        var i, j, polygon, pts, xCross, x0, x1, y0, y1;

        for(i = 0; i < polygons.length; i++) {
            polygon = polygons[i];
            // TODO: this is not going to work right for curved edges, it will
            // act as though they're straight. That's probably going to need
            // the elements themselves to capture the events. Worth it?
            if(polygon.contains(pt)) {
                inside = !inside;
                // TODO: need better than just the overall bounding box
                polygonsIn.push(polygon);
                ymin = Math.min(ymin, polygon.ymin);
                ymax = Math.max(ymax, polygon.ymax);
            }
        }

        if(inside) {
            // constrain ymin/max to the visible plot, so the label goes
            // at the middle of the piece you can see
            ymin = Math.max(ymin, 0);
            ymax = Math.min(ymax, ya._length);

            // find the overall left-most and right-most points of the
            // polygon(s) we're inside at their combined vertical midpoint.
            // This is where we will draw the hover label.
            // Note that this might not be the vertical midpoint of the
            // whole trace, if it's disjoint.
            var yAvg = (ymin + ymax) / 2;
            for(i = 0; i < polygonsIn.length; i++) {
                pts = polygonsIn[i].pts;
                for(j = 1; j < pts.length; j++) {
                    y0 = pts[j - 1][1];
                    y1 = pts[j][1];
                    if((y0 > yAvg) !== (y1 >= yAvg)) {
                        x0 = pts[j - 1][0];
                        x1 = pts[j][0];
                        if(y1 - y0) {
                            xCross = x0 + (x1 - x0) * (yAvg - y0) / (y1 - y0);
                            xmin = Math.min(xmin, xCross);
                            xmax = Math.max(xmax, xCross);
                        }
                    }
                }
            }

            // constrain xmin/max to the visible plot now too
            xmin = Math.max(xmin, 0);
            xmax = Math.min(xmax, xa._length);

            // get only fill or line color for the hover color
            var color = Color.defaultLine;
            if(Color.opacity(trace.fillcolor)) color = trace.fillcolor;
            else if(Color.opacity((trace.line || {}).color)) {
                color = trace.line.color;
            }

            Lib.extendFlat(pointData, {
                // never let a 2D override 1D type as closest point
                // also: no spikeDistance, it's not allowed for fills
                distance: pointData.maxHoverDistance,
                x0: xmin,
                x1: xmax,
                y0: yAvg,
                y1: yAvg,
                color: color,
                hovertemplate: '%{name}'
            });

            delete pointData.index;

            if(trace.text && !Array.isArray(trace.text)) {
                pointData.text = String(trace.text);
            }
            else pointData.text = trace.name;

            return [pointData];
        }
    }
};

},{"../../components/color":574,"../../components/fx":613,"../../lib":697,"../../registry":826,"./fill_hover_text":1056,"./get_trace_color":1058}],1060:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Scatter = {};

var subtypes = _dereq_('./subtypes');
Scatter.hasLines = subtypes.hasLines;
Scatter.hasMarkers = subtypes.hasMarkers;
Scatter.hasText = subtypes.hasText;
Scatter.isBubble = subtypes.isBubble;

Scatter.attributes = _dereq_('./attributes');
Scatter.supplyDefaults = _dereq_('./defaults');
Scatter.crossTraceDefaults = _dereq_('./cross_trace_defaults');
Scatter.calc = _dereq_('./calc').calc;
Scatter.crossTraceCalc = _dereq_('./cross_trace_calc');
Scatter.arraysToCalcdata = _dereq_('./arrays_to_calcdata');
Scatter.plot = _dereq_('./plot');
Scatter.colorbar = _dereq_('./marker_colorbar');
Scatter.style = _dereq_('./style').style;
Scatter.styleOnSelect = _dereq_('./style').styleOnSelect;
Scatter.hoverPoints = _dereq_('./hover');
Scatter.selectPoints = _dereq_('./select');
Scatter.animatable = true;

Scatter.moduleType = 'trace';
Scatter.name = 'scatter';
Scatter.basePlotModule = _dereq_('../../plots/cartesian');
Scatter.categories = [
    'cartesian', 'svg', 'symbols', 'errorBarsOK', 'showLegend', 'scatter-like',
    'zoomScale'
];
Scatter.meta = {
    
};

module.exports = Scatter;

},{"../../plots/cartesian":756,"./arrays_to_calcdata":1047,"./attributes":1048,"./calc":1049,"./cross_trace_calc":1053,"./cross_trace_defaults":1054,"./defaults":1055,"./hover":1059,"./marker_colorbar":1066,"./plot":1068,"./select":1069,"./style":1071,"./subtypes":1072}],1061:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;
var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');

module.exports = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) {
    var markerColor = (traceIn.marker || {}).color;

    coerce('line.color', defaultColor);

    if(hasColorscale(traceIn, 'line')) {
        colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'});
    } else {
        var lineColorDflt = (isArrayOrTypedArray(markerColor) ? false : markerColor) || defaultColor;
        coerce('line.color', lineColorDflt);
    }

    coerce('line.width');
    if(!(opts || {}).noDash) coerce('line.dash');
};

},{"../../components/colorscale/defaults":584,"../../components/colorscale/helpers":585,"../../lib":697}],1062:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var numConstants = _dereq_('../../constants/numerical');
var BADNUM = numConstants.BADNUM;
var LOG_CLIP = numConstants.LOG_CLIP;
var LOG_CLIP_PLUS = LOG_CLIP + 0.5;
var LOG_CLIP_MINUS = LOG_CLIP - 0.5;
var Lib = _dereq_('../../lib');
var segmentsIntersect = Lib.segmentsIntersect;
var constrain = Lib.constrain;
var constants = _dereq_('./constants');


module.exports = function linePoints(d, opts) {
    var xa = opts.xaxis;
    var ya = opts.yaxis;
    var xLog = xa.type === 'log';
    var yLog = ya.type === 'log';
    var xLen = xa._length;
    var yLen = ya._length;
    var connectGaps = opts.connectGaps;
    var baseTolerance = opts.baseTolerance;
    var shape = opts.shape;
    var linear = shape === 'linear';
    var segments = [];
    var minTolerance = constants.minTolerance;
    var pts = new Array(d.length);
    var pti = 0;

    var i;

    // pt variables are pixel coordinates [x,y] of one point
    // these four are the outputs of clustering on a line
    var clusterStartPt, clusterEndPt, clusterHighPt, clusterLowPt;

    // "this" is the next point we're considering adding to the cluster
    var thisPt;

    // did we encounter the high point first, then a low point, or vice versa?
    var clusterHighFirst;

    // the first two points in the cluster determine its unit vector
    // so the second is always in the "High" direction
    var clusterUnitVector;

    // the pixel delta from clusterStartPt
    var thisVector;

    // val variables are (signed) pixel distances along the cluster vector
    var clusterRefDist, clusterHighVal, clusterLowVal, thisVal;

    // deviation variables are (signed) pixel distances normal to the cluster vector
    var clusterMinDeviation, clusterMaxDeviation, thisDeviation;

    // turn one calcdata point into pixel coordinates
    function getPt(index) {
        var di = d[index];
        if(!di) return false;
        var x = xa.c2p(di.x);
        var y = ya.c2p(di.y);

        // if non-positive log values, set them VERY far off-screen
        // so the line looks essentially straight from the previous point.
        if(x === BADNUM) {
            if(xLog) x = xa.c2p(di.x, true);
            if(x === BADNUM) return false;
            // If BOTH were bad log values, make the line follow a constant
            // exponent rather than a constant slope
            if(yLog && y === BADNUM) {
                x *= Math.abs(xa._m * yLen * (xa._m > 0 ? LOG_CLIP_PLUS : LOG_CLIP_MINUS) /
                    (ya._m * xLen * (ya._m > 0 ? LOG_CLIP_PLUS : LOG_CLIP_MINUS)));
            }
            x *= 1000;
        }
        if(y === BADNUM) {
            if(yLog) y = ya.c2p(di.y, true);
            if(y === BADNUM) return false;
            y *= 1000;
        }
        return [x, y];
    }

    function crossesViewport(xFrac0, yFrac0, xFrac1, yFrac1) {
        var dx = xFrac1 - xFrac0;
        var dy = yFrac1 - yFrac0;
        var dx0 = 0.5 - xFrac0;
        var dy0 = 0.5 - yFrac0;
        var norm2 = dx * dx + dy * dy;
        var dot = dx * dx0 + dy * dy0;
        if(dot > 0 && dot < norm2) {
            var cross = dx0 * dy - dy0 * dx;
            if(cross * cross < norm2) return true;
        }
    }

    var latestXFrac, latestYFrac;
    // if we're off-screen, increase tolerance over baseTolerance
    function getTolerance(pt, nextPt) {
        var xFrac = pt[0] / xLen;
        var yFrac = pt[1] / yLen;
        var offScreenFraction = Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1);
        if(offScreenFraction && (latestXFrac !== undefined) &&
            crossesViewport(xFrac, yFrac, latestXFrac, latestYFrac)
        ) {
            offScreenFraction = 0;
        }
        if(offScreenFraction && nextPt &&
            crossesViewport(xFrac, yFrac, nextPt[0] / xLen, nextPt[1] / yLen)
        ) {
            offScreenFraction = 0;
        }

        return (1 + constants.toleranceGrowth * offScreenFraction) * baseTolerance;
    }

    function ptDist(pt1, pt2) {
        var dx = pt1[0] - pt2[0];
        var dy = pt1[1] - pt2[1];
        return Math.sqrt(dx * dx + dy * dy);
    }

    // last bit of filtering: clip paths that are VERY far off-screen
    // so we don't get near the browser's hard limit (+/- 2^29 px in Chrome and FF)

    var maxScreensAway = constants.maxScreensAway;

    // find the intersections between the segment from pt1 to pt2
    // and the large rectangle maxScreensAway around the viewport
    // if one of pt1 and pt2 is inside and the other outside, there
    // will be only one intersection.
    // if both are outside there will be 0 or 2 intersections
    // (or 1 if it's right at a corner - we'll treat that like 0)
    // returns an array of intersection pts
    var xEdge0 = -xLen * maxScreensAway;
    var xEdge1 = xLen * (1 + maxScreensAway);
    var yEdge0 = -yLen * maxScreensAway;
    var yEdge1 = yLen * (1 + maxScreensAway);
    var edges = [
        [xEdge0, yEdge0, xEdge1, yEdge0],
        [xEdge1, yEdge0, xEdge1, yEdge1],
        [xEdge1, yEdge1, xEdge0, yEdge1],
        [xEdge0, yEdge1, xEdge0, yEdge0]
    ];
    var xEdge, yEdge, lastXEdge, lastYEdge, lastFarPt, edgePt;

    // for linear line shape, edge intersections should be linearly interpolated
    // spline uses this too, which isn't precisely correct but is actually pretty
    // good, because Catmull-Rom weights far-away points less in creating the curvature
    function getLinearEdgeIntersections(pt1, pt2) {
        var out = [];
        var ptCount = 0;
        for(var i = 0; i < 4; i++) {
            var edge = edges[i];
            var ptInt = segmentsIntersect(pt1[0], pt1[1], pt2[0], pt2[1],
                edge[0], edge[1], edge[2], edge[3]);
            if(ptInt && (!ptCount ||
                Math.abs(ptInt.x - out[0][0]) > 1 ||
                Math.abs(ptInt.y - out[0][1]) > 1
            )) {
                ptInt = [ptInt.x, ptInt.y];
                // if we have 2 intersections, make sure the closest one to pt1 comes first
                if(ptCount && ptDist(ptInt, pt1) < ptDist(out[0], pt1)) out.unshift(ptInt);
                else out.push(ptInt);
                ptCount++;
            }
        }
        return out;
    }

    function onlyConstrainedPoint(pt) {
        if(pt[0] < xEdge0 || pt[0] > xEdge1 || pt[1] < yEdge0 || pt[1] > yEdge1) {
            return [constrain(pt[0], xEdge0, xEdge1), constrain(pt[1], yEdge0, yEdge1)];
        }
    }

    function sameEdge(pt1, pt2) {
        if(pt1[0] === pt2[0] && (pt1[0] === xEdge0 || pt1[0] === xEdge1)) return true;
        if(pt1[1] === pt2[1] && (pt1[1] === yEdge0 || pt1[1] === yEdge1)) return true;
    }

    // for line shapes hv and vh, movement in the two dimensions is decoupled,
    // so all we need to do is constrain each dimension independently
    function getHVEdgeIntersections(pt1, pt2) {
        var out = [];
        var ptInt1 = onlyConstrainedPoint(pt1);
        var ptInt2 = onlyConstrainedPoint(pt2);
        if(ptInt1 && ptInt2 && sameEdge(ptInt1, ptInt2)) return out;

        if(ptInt1) out.push(ptInt1);
        if(ptInt2) out.push(ptInt2);
        return out;
    }

    // hvh and vhv we sometimes have to move one of the intersection points
    // out BEYOND the clipping rect, by a maximum of a factor of 2, so that
    // the midpoint line is drawn in the right place
    function getABAEdgeIntersections(dim, limit0, limit1) {
        return function(pt1, pt2) {
            var ptInt1 = onlyConstrainedPoint(pt1);
            var ptInt2 = onlyConstrainedPoint(pt2);

            var out = [];
            if(ptInt1 && ptInt2 && sameEdge(ptInt1, ptInt2)) return out;

            if(ptInt1) out.push(ptInt1);
            if(ptInt2) out.push(ptInt2);

            var midShift = 2 * Lib.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) -
                ((ptInt1 || pt1)[dim] + (ptInt2 || pt2)[dim]);
            if(midShift) {
                var ptToAlter;
                if(ptInt1 && ptInt2) {
                    ptToAlter = (midShift > 0 === ptInt1[dim] > ptInt2[dim]) ? ptInt1 : ptInt2;
                }
                else ptToAlter = ptInt1 || ptInt2;

                ptToAlter[dim] += midShift;
            }

            return out;
        };
    }

    var getEdgeIntersections;
    if(shape === 'linear' || shape === 'spline') {
        getEdgeIntersections = getLinearEdgeIntersections;
    }
    else if(shape === 'hv' || shape === 'vh') {
        getEdgeIntersections = getHVEdgeIntersections;
    }
    else if(shape === 'hvh') getEdgeIntersections = getABAEdgeIntersections(0, xEdge0, xEdge1);
    else if(shape === 'vhv') getEdgeIntersections = getABAEdgeIntersections(1, yEdge0, yEdge1);

    // a segment pt1->pt2 entirely outside the nearby region:
    // find the corner it gets closest to touching
    function getClosestCorner(pt1, pt2) {
        var dx = pt2[0] - pt1[0];
        var m = (pt2[1] - pt1[1]) / dx;
        var b = (pt1[1] * pt2[0] - pt2[1] * pt1[0]) / dx;

        if(b > 0) return [m > 0 ? xEdge0 : xEdge1, yEdge1];
        else return [m > 0 ? xEdge1 : xEdge0, yEdge0];
    }

    function updateEdge(pt) {
        var x = pt[0];
        var y = pt[1];
        var xSame = x === pts[pti - 1][0];
        var ySame = y === pts[pti - 1][1];
        // duplicate point?
        if(xSame && ySame) return;
        if(pti > 1) {
            // backtracking along an edge?
            var xSame2 = x === pts[pti - 2][0];
            var ySame2 = y === pts[pti - 2][1];
            if(xSame && (x === xEdge0 || x === xEdge1) && xSame2) {
                if(ySame2) pti--; // backtracking exactly - drop prev pt and don't add
                else pts[pti - 1] = pt; // not exact: replace the prev pt
            }
            else if(ySame && (y === yEdge0 || y === yEdge1) && ySame2) {
                if(xSame2) pti--;
                else pts[pti - 1] = pt;
            }
            else pts[pti++] = pt;
        }
        else pts[pti++] = pt;
    }

    function updateEdgesForReentry(pt) {
        // if we're outside the nearby region and going back in,
        // we may need to loop around a corner point
        if(pts[pti - 1][0] !== pt[0] && pts[pti - 1][1] !== pt[1]) {
            updateEdge([lastXEdge, lastYEdge]);
        }
        updateEdge(pt);
        lastFarPt = null;
        lastXEdge = lastYEdge = 0;
    }

    function addPt(pt) {
        latestXFrac = pt[0] / xLen;
        latestYFrac = pt[1] / yLen;
        // Are we more than maxScreensAway off-screen any direction?
        // if so, clip to this box, but in such a way that on-screen
        // drawing is unchanged
        xEdge = (pt[0] < xEdge0) ? xEdge0 : (pt[0] > xEdge1) ? xEdge1 : 0;
        yEdge = (pt[1] < yEdge0) ? yEdge0 : (pt[1] > yEdge1) ? yEdge1 : 0;
        if(xEdge || yEdge) {
            // to get fills right - if first point is far, push it toward the
            // screen in whichever direction(s) are far
            if(!pti) {
                pts[pti++] = [xEdge || pt[0], yEdge || pt[1]];
            }
            else if(lastFarPt) {
                // both this point and the last are outside the nearby region
                // check if we're crossing the nearby region
                var intersections = getEdgeIntersections(lastFarPt, pt);
                if(intersections.length > 1) {
                    updateEdgesForReentry(intersections[0]);
                    pts[pti++] = intersections[1];
                }
            }
            // we're leaving the nearby region - add the point where we left it
            else {
                edgePt = getEdgeIntersections(pts[pti - 1], pt)[0];
                pts[pti++] = edgePt;
            }

            var lastPt = pts[pti - 1];
            if(xEdge && yEdge && (lastPt[0] !== xEdge || lastPt[1] !== yEdge)) {
                // we've gone out beyond a new corner: add the corner too
                // so that the next point will take the right winding
                if(lastFarPt) {
                    if(lastXEdge !== xEdge && lastYEdge !== yEdge) {
                        if(lastXEdge && lastYEdge) {
                            // we've gone around to an opposite corner - we
                            // need to add the correct extra corner
                            // in order to get the right winding
                            updateEdge(getClosestCorner(lastFarPt, pt));
                        }
                        else {
                            // we're coming from a far edge - the extra corner
                            // we need is determined uniquely by the sectors
                            updateEdge([lastXEdge || xEdge, lastYEdge || yEdge]);
                        }
                    }
                    else if(lastXEdge && lastYEdge) {
                        updateEdge([lastXEdge, lastYEdge]);
                    }
                }
                updateEdge([xEdge, yEdge]);
            }
            else if((lastXEdge - xEdge) && (lastYEdge - yEdge)) {
                // we're coming from an edge or far corner to an edge - again the
                // extra corner we need is uniquely determined by the sectors
                updateEdge([xEdge || lastXEdge, yEdge || lastYEdge]);
            }
            lastFarPt = pt;
            lastXEdge = xEdge;
            lastYEdge = yEdge;
        }
        else {
            if(lastFarPt) {
                // this point is in range but the previous wasn't: add its entry pt first
                updateEdgesForReentry(getEdgeIntersections(lastFarPt, pt)[0]);
            }

            pts[pti++] = pt;
        }
    }

    // loop over ALL points in this trace
    for(i = 0; i < d.length; i++) {
        clusterStartPt = getPt(i);
        if(!clusterStartPt) continue;

        pti = 0;
        lastFarPt = null;
        addPt(clusterStartPt);

        // loop over one segment of the trace
        for(i++; i < d.length; i++) {
            clusterHighPt = getPt(i);
            if(!clusterHighPt) {
                if(connectGaps) continue;
                else break;
            }

            // can't decimate if nonlinear line shape
            // TODO: we *could* decimate [hv]{2,3} shapes if we restricted clusters to horz or vert again
            // but spline would be verrry awkward to decimate
            if(!linear || !opts.simplify) {
                addPt(clusterHighPt);
                continue;
            }

            var nextPt = getPt(i + 1);

            clusterRefDist = ptDist(clusterHighPt, clusterStartPt);

            if(clusterRefDist < getTolerance(clusterHighPt, nextPt) * minTolerance) continue;

            clusterUnitVector = [
                (clusterHighPt[0] - clusterStartPt[0]) / clusterRefDist,
                (clusterHighPt[1] - clusterStartPt[1]) / clusterRefDist
            ];

            clusterLowPt = clusterStartPt;
            clusterHighVal = clusterRefDist;
            clusterLowVal = clusterMinDeviation = clusterMaxDeviation = 0;
            clusterHighFirst = false;
            clusterEndPt = clusterHighPt;

            // loop over one cluster of points that collapse onto one line
            for(i++; i < d.length; i++) {
                thisPt = nextPt;
                nextPt = getPt(i + 1);
                if(!thisPt) {
                    if(connectGaps) continue;
                    else break;
                }
                thisVector = [
                    thisPt[0] - clusterStartPt[0],
                    thisPt[1] - clusterStartPt[1]
                ];
                // cross product (or dot with normal to the cluster vector)
                thisDeviation = thisVector[0] * clusterUnitVector[1] - thisVector[1] * clusterUnitVector[0];
                clusterMinDeviation = Math.min(clusterMinDeviation, thisDeviation);
                clusterMaxDeviation = Math.max(clusterMaxDeviation, thisDeviation);

                if(clusterMaxDeviation - clusterMinDeviation > getTolerance(thisPt, nextPt)) break;

                clusterEndPt = thisPt;
                thisVal = thisVector[0] * clusterUnitVector[0] + thisVector[1] * clusterUnitVector[1];

                if(thisVal > clusterHighVal) {
                    clusterHighVal = thisVal;
                    clusterHighPt = thisPt;
                    clusterHighFirst = false;
                } else if(thisVal < clusterLowVal) {
                    clusterLowVal = thisVal;
                    clusterLowPt = thisPt;
                    clusterHighFirst = true;
                }
            }

            // insert this cluster into pts
            // we've already inserted the start pt, now check if we have high and low pts
            if(clusterHighFirst) {
                addPt(clusterHighPt);
                if(clusterEndPt !== clusterLowPt) addPt(clusterLowPt);
            } else {
                if(clusterLowPt !== clusterStartPt) addPt(clusterLowPt);
                if(clusterEndPt !== clusterHighPt) addPt(clusterHighPt);
            }
            // and finally insert the end pt
            addPt(clusterEndPt);

            // have we reached the end of this segment?
            if(i >= d.length || !thisPt) break;

            // otherwise we have an out-of-cluster point to insert as next clusterStartPt
            addPt(thisPt);
            clusterStartPt = thisPt;
        }

        // to get fills right - repeat what we did at the start
        if(lastFarPt) updateEdge([lastXEdge || lastFarPt[0], lastYEdge || lastFarPt[1]]);

        segments.push(pts.slice(0, pti));
    }

    return segments;
};

},{"../../constants/numerical":674,"../../lib":697,"./constants":1052}],1063:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


// common to 'scatter' and 'scatterternary'
module.exports = function handleLineShapeDefaults(traceIn, traceOut, coerce) {
    var shape = coerce('line.shape');
    if(shape === 'spline') coerce('line.smoothing');
};

},{}],1064:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var LINKEDFILLS = {tonextx: 1, tonexty: 1, tonext: 1};

module.exports = function linkTraces(gd, plotinfo, cdscatter) {
    var trace, i, group, prevtrace, groupIndex;

    // first sort traces to keep stacks & filled-together groups together
    var groupIndices = {};
    var needsSort = false;
    var prevGroupIndex = -1;
    var nextGroupIndex = 0;
    var prevUnstackedGroupIndex = -1;
    for(i = 0; i < cdscatter.length; i++) {
        trace = cdscatter[i][0].trace;
        group = trace.stackgroup || '';
        if(group) {
            if(group in groupIndices) {
                groupIndex = groupIndices[group];
            }
            else {
                groupIndex = groupIndices[group] = nextGroupIndex;
                nextGroupIndex++;
            }
        }
        else if(trace.fill in LINKEDFILLS && prevUnstackedGroupIndex >= 0) {
            groupIndex = prevUnstackedGroupIndex;
        }
        else {
            groupIndex = prevUnstackedGroupIndex = nextGroupIndex;
            nextGroupIndex++;
        }

        if(groupIndex < prevGroupIndex) needsSort = true;
        trace._groupIndex = prevGroupIndex = groupIndex;
    }

    var cdscatterSorted = cdscatter.slice();
    if(needsSort) {
        cdscatterSorted.sort(function(a, b) {
            var traceA = a[0].trace;
            var traceB = b[0].trace;
            return (traceA._groupIndex - traceB._groupIndex) ||
                (traceA.index - traceB.index);
        });
    }

    // now link traces to each other
    var prevtraces = {};
    for(i = 0; i < cdscatterSorted.length; i++) {
        trace = cdscatterSorted[i][0].trace;
        group = trace.stackgroup || '';

        // Note: The check which ensures all cdscatter here are for the same axis and
        // are either cartesian or scatterternary has been removed. This code assumes
        // the passed scattertraces have been filtered to the proper plot types and
        // the proper subplots.
        if(trace.visible === true) {
            trace._nexttrace = null;

            if(trace.fill in LINKEDFILLS) {
                prevtrace = prevtraces[group];
                trace._prevtrace = prevtrace || null;

                if(prevtrace) {
                    prevtrace._nexttrace = trace;
                }
            }

            trace._ownfill = (trace.fill && (
                trace.fill.substr(0, 6) === 'tozero' ||
                trace.fill === 'toself' ||
                (trace.fill.substr(0, 2) === 'to' && !trace._prevtrace)
            ));

            prevtraces[group] = trace;
        } else {
            trace._prevtrace = trace._nexttrace = trace._ownfill = null;
        }
    }

    return cdscatterSorted;
};

},{}],1065:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');


// used in the drawing step for 'scatter' and 'scattegeo' and
// in the convert step for 'scatter3d'
module.exports = function makeBubbleSizeFn(trace) {
    var marker = trace.marker;
    var sizeRef = marker.sizeref || 1;
    var sizeMin = marker.sizemin || 0;

    // for bubble charts, allow scaling the provided value linearly
    // and by area or diameter.
    // Note this only applies to the array-value sizes

    var baseFn = (marker.sizemode === 'area') ?
        function(v) { return Math.sqrt(v / sizeRef); } :
        function(v) { return v / sizeRef; };

    // TODO add support for position/negative bubbles?
    // TODO add 'sizeoffset' attribute?
    return function(v) {
        var baseSize = baseFn(v / 2);

        // don't show non-numeric and negative sizes
        return (isNumeric(baseSize) && (baseSize > 0)) ?
            Math.max(baseSize, sizeMin) :
            0;
    };
};

},{"fast-isnumeric":218}],1066:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = {
    container: 'marker',
    min: 'cmin',
    max: 'cmax'
};

},{}],1067:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Color = _dereq_('../../components/color');
var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');

var subTypes = _dereq_('./subtypes');

/*
 * opts: object of flags to control features not all marker users support
 *   noLine: caller does not support marker lines
 *   gradient: caller supports gradients
 *   noSelect: caller does not support selected/unselected attribute containers
 */
module.exports = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) {
    var isBubble = subTypes.isBubble(traceIn);
    var lineColor = (traceIn.line || {}).color;
    var defaultMLC;

    opts = opts || {};

    // marker.color inherit from line.color (even if line.color is an array)
    if(lineColor) defaultColor = lineColor;

    coerce('marker.symbol');
    coerce('marker.opacity', isBubble ? 0.7 : 1);
    coerce('marker.size');

    coerce('marker.color', defaultColor);
    if(hasColorscale(traceIn, 'marker')) {
        colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'});
    }

    if(!opts.noSelect) {
        coerce('selected.marker.color');
        coerce('unselected.marker.color');
        coerce('selected.marker.size');
        coerce('unselected.marker.size');
    }

    if(!opts.noLine) {
        // if there's a line with a different color than the marker, use
        // that line color as the default marker line color
        // (except when it's an array)
        // mostly this is for transparent markers to behave nicely
        if(lineColor && !Array.isArray(lineColor) && (traceOut.marker.color !== lineColor)) {
            defaultMLC = lineColor;
        }
        else if(isBubble) defaultMLC = Color.background;
        else defaultMLC = Color.defaultLine;

        coerce('marker.line.color', defaultMLC);
        if(hasColorscale(traceIn, 'marker.line')) {
            colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'});
        }

        coerce('marker.line.width', isBubble ? 1 : 0);
    }

    if(isBubble) {
        coerce('marker.sizeref');
        coerce('marker.sizemin');
        coerce('marker.sizemode');
    }

    if(opts.gradient) {
        var gradientType = coerce('marker.gradient.type');
        if(gradientType !== 'none') {
            coerce('marker.gradient.color');
        }
    }
};

},{"../../components/color":574,"../../components/colorscale/defaults":584,"../../components/colorscale/helpers":585,"./subtypes":1072}],1068:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var ensureSingle = Lib.ensureSingle;
var identity = Lib.identity;
var Drawing = _dereq_('../../components/drawing');

var subTypes = _dereq_('./subtypes');
var linePoints = _dereq_('./line_points');
var linkTraces = _dereq_('./link_traces');
var polygonTester = _dereq_('../../lib/polygon').tester;

module.exports = function plot(gd, plotinfo, cdscatter, scatterLayer, transitionOpts, makeOnCompleteCallback) {
    var join, onComplete;

    // If transition config is provided, then it is only a partial replot and traces not
    // updated are removed.
    var isFullReplot = !transitionOpts;
    var hasTransition = !!transitionOpts && transitionOpts.duration > 0;

    // Link traces so the z-order of fill layers is correct
    var cdscatterSorted = linkTraces(gd, plotinfo, cdscatter);

    join = scatterLayer.selectAll('g.trace')
        .data(cdscatterSorted, function(d) { return d[0].trace.uid; });

    // Append new traces:
    join.enter().append('g')
        .attr('class', function(d) {
            return 'trace scatter trace' + d[0].trace.uid;
        })
        .style('stroke-miterlimit', 2);
    join.order();

    createFills(gd, join, plotinfo);

    if(hasTransition) {
        if(makeOnCompleteCallback) {
            // If it was passed a callback to register completion, make a callback. If
            // this is created, then it must be executed on completion, otherwise the
            // pos-transition redraw will not execute:
            onComplete = makeOnCompleteCallback();
        }

        var transition = d3.transition()
            .duration(transitionOpts.duration)
            .ease(transitionOpts.easing)
            .each('end', function() {
                onComplete && onComplete();
            })
            .each('interrupt', function() {
                onComplete && onComplete();
            });

        transition.each(function() {
            // Must run the selection again since otherwise enters/updates get grouped together
            // and these get executed out of order. Except we need them in order!
            scatterLayer.selectAll('g.trace').each(function(d, i) {
                plotOne(gd, i, plotinfo, d, cdscatterSorted, this, transitionOpts);
            });
        });
    } else {
        join.each(function(d, i) {
            plotOne(gd, i, plotinfo, d, cdscatterSorted, this, transitionOpts);
        });
    }

    if(isFullReplot) {
        join.exit().remove();
    }

    // remove paths that didn't get used
    scatterLayer.selectAll('path:not([d])').remove();
};

function createFills(gd, traceJoin, plotinfo) {
    traceJoin.each(function(d) {
        var fills = ensureSingle(d3.select(this), 'g', 'fills');
        Drawing.setClipUrl(fills, plotinfo.layerClipId, gd);

        var trace = d[0].trace;

        var fillData = [];
        if(trace._ownfill) fillData.push('_ownFill');
        if(trace._nexttrace) fillData.push('_nextFill');

        var fillJoin = fills.selectAll('g').data(fillData, identity);

        fillJoin.enter().append('g');

        fillJoin.exit()
            .each(function(d) { trace[d] = null; })
            .remove();

        fillJoin.order().each(function(d) {
            // make a path element inside the fill group, just so
            // we can give it its own data later on and the group can
            // keep its simple '_*Fill' data
            trace[d] = ensureSingle(d3.select(this), 'path', 'js-fill');
        });
    });
}

function plotOne(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) {
    var i;

    // Since this has been reorganized and we're executing this on individual traces,
    // we need to pass it the full list of cdscatter as well as this trace's index (idx)
    // since it does an internal n^2 loop over comparisons with other traces:
    selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll);

    var hasTransition = !!transitionOpts && transitionOpts.duration > 0;

    function transition(selection) {
        return hasTransition ? selection.transition() : selection;
    }

    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    var trace = cdscatter[0].trace;
    var line = trace.line;
    var tr = d3.select(element);

    var errorBarGroup = ensureSingle(tr, 'g', 'errorbars');
    var lines = ensureSingle(tr, 'g', 'lines');
    var points = ensureSingle(tr, 'g', 'points');
    var text = ensureSingle(tr, 'g', 'text');

    // error bars are at the bottom
    Registry.getComponentMethod('errorbars', 'plot')(gd, errorBarGroup, plotinfo, transitionOpts);

    if(trace.visible !== true) return;

    transition(tr).style('opacity', trace.opacity);

    // BUILD LINES AND FILLS
    var ownFillEl3, tonext;
    var ownFillDir = trace.fill.charAt(trace.fill.length - 1);
    if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = '';

    // store node for tweaking by selectPoints
    if(!plotinfo.isRangePlot) cdscatter[0].node3 = tr;

    var prevRevpath = '';
    var prevPolygons = [];
    var prevtrace = trace._prevtrace;

    if(prevtrace) {
        prevRevpath = prevtrace._prevRevpath || '';
        tonext = prevtrace._nextFill;
        prevPolygons = prevtrace._polygons;
    }

    var thispath;
    var thisrevpath;
    // fullpath is all paths for this curve, joined together straight
    // across gaps, for filling
    var fullpath = '';
    // revpath is fullpath reversed, for fill-to-next
    var revpath = '';
    // functions for converting a point array to a path
    var pathfn, revpathbase, revpathfn;
    // variables used before and after the data join
    var pt0, lastSegment, pt1, thisPolygons;

    // initialize line join data / method
    var segments = [];
    var makeUpdate = Lib.noop;

    ownFillEl3 = trace._ownFill;

    if(subTypes.hasLines(trace) || trace.fill !== 'none') {

        if(tonext) {
            // This tells .style which trace to use for fill information:
            tonext.datum(cdscatter);
        }

        if(['hv', 'vh', 'hvh', 'vhv'].indexOf(line.shape) !== -1) {
            pathfn = Drawing.steps(line.shape);
            revpathbase = Drawing.steps(
                line.shape.split('').reverse().join('')
            );
        }
        else if(line.shape === 'spline') {
            pathfn = revpathbase = function(pts) {
                var pLast = pts[pts.length - 1];
                if(pts.length > 1 && pts[0][0] === pLast[0] && pts[0][1] === pLast[1]) {
                    // identical start and end points: treat it as a
                    // closed curve so we don't get a kink
                    return Drawing.smoothclosed(pts.slice(1), line.smoothing);
                }
                else {
                    return Drawing.smoothopen(pts, line.smoothing);
                }
            };
        }
        else {
            pathfn = revpathbase = function(pts) {
                return 'M' + pts.join('L');
            };
        }

        revpathfn = function(pts) {
            // note: this is destructive (reverses pts in place) so can't use pts after this
            return revpathbase(pts.reverse());
        };

        segments = linePoints(cdscatter, {
            xaxis: xa,
            yaxis: ya,
            connectGaps: trace.connectgaps,
            baseTolerance: Math.max(line.width || 1, 3) / 4,
            shape: line.shape,
            simplify: line.simplify
        });

        // since we already have the pixel segments here, use them to make
        // polygons for hover on fill
        // TODO: can we skip this if hoveron!=fills? That would mean we
        // need to redraw when you change hoveron...
        thisPolygons = trace._polygons = new Array(segments.length);
        for(i = 0; i < segments.length; i++) {
            trace._polygons[i] = polygonTester(segments[i]);
        }

        if(segments.length) {
            pt0 = segments[0][0];
            lastSegment = segments[segments.length - 1];
            pt1 = lastSegment[lastSegment.length - 1];
        }

        makeUpdate = function(isEnter) {
            return function(pts) {
                thispath = pathfn(pts);
                thisrevpath = revpathfn(pts);
                if(!fullpath) {
                    fullpath = thispath;
                    revpath = thisrevpath;
                }
                else if(ownFillDir) {
                    fullpath += 'L' + thispath.substr(1);
                    revpath = thisrevpath + ('L' + revpath.substr(1));
                }
                else {
                    fullpath += 'Z' + thispath;
                    revpath = thisrevpath + 'Z' + revpath;
                }

                if(subTypes.hasLines(trace) && pts.length > 1) {
                    var el = d3.select(this);

                    // This makes the coloring work correctly:
                    el.datum(cdscatter);

                    if(isEnter) {
                        transition(el.style('opacity', 0)
                            .attr('d', thispath)
                            .call(Drawing.lineGroupStyle))
                                .style('opacity', 1);
                    } else {
                        var sel = transition(el);
                        sel.attr('d', thispath);
                        Drawing.singleLineStyle(cdscatter, sel);
                    }
                }
            };
        };
    }

    var lineJoin = lines.selectAll('.js-line').data(segments);

    transition(lineJoin.exit())
        .style('opacity', 0)
        .remove();

    lineJoin.each(makeUpdate(false));

    lineJoin.enter().append('path')
        .classed('js-line', true)
        .style('vector-effect', 'non-scaling-stroke')
        .call(Drawing.lineGroupStyle)
        .each(makeUpdate(true));

    Drawing.setClipUrl(lineJoin, plotinfo.layerClipId, gd);

    function clearFill(selection) {
        transition(selection).attr('d', 'M0,0Z');
    }

    if(segments.length) {
        if(ownFillEl3) {
            ownFillEl3.datum(cdscatter);
            if(pt0 && pt1) {
                if(ownFillDir) {
                    if(ownFillDir === 'y') {
                        pt0[1] = pt1[1] = ya.c2p(0, true);
                    }
                    else if(ownFillDir === 'x') {
                        pt0[0] = pt1[0] = xa.c2p(0, true);
                    }

                    // fill to zero: full trace path, plus extension of
                    // the endpoints to the appropriate axis
                    // For the sake of animations, wrap the points around so that
                    // the points on the axes are the first two points. Otherwise
                    // animations get a little crazy if the number of points changes.
                    transition(ownFillEl3).attr('d', 'M' + pt1 + 'L' + pt0 + 'L' + fullpath.substr(1))
                        .call(Drawing.singleFillStyle);
                } else {
                    // fill to self: just join the path to itself
                    transition(ownFillEl3).attr('d', fullpath + 'Z')
                        .call(Drawing.singleFillStyle);
                }
            }
        }
        else if(tonext) {
            if(trace.fill.substr(0, 6) === 'tonext' && fullpath && prevRevpath) {
                // fill to next: full trace path, plus the previous path reversed
                if(trace.fill === 'tonext') {
                    // tonext: for use by concentric shapes, like manually constructed
                    // contours, we just add the two paths closed on themselves.
                    // This makes strange results if one path is *not* entirely
                    // inside the other, but then that is a strange usage.
                    transition(tonext).attr('d', fullpath + 'Z' + prevRevpath + 'Z')
                        .call(Drawing.singleFillStyle);
                }
                else {
                    // tonextx/y: for now just connect endpoints with lines. This is
                    // the correct behavior if the endpoints are at the same value of
                    // y/x, but if they *aren't*, we should ideally do more complicated
                    // things depending on whether the new endpoint projects onto the
                    // existing curve or off the end of it
                    transition(tonext).attr('d', fullpath + 'L' + prevRevpath.substr(1) + 'Z')
                        .call(Drawing.singleFillStyle);
                }
                trace._polygons = trace._polygons.concat(prevPolygons);
            }
            else {
                clearFill(tonext);
                trace._polygons = null;
            }
        }
        trace._prevRevpath = revpath;
        trace._prevPolygons = thisPolygons;
    }
    else {
        if(ownFillEl3) clearFill(ownFillEl3);
        else if(tonext) clearFill(tonext);
        trace._polygons = trace._prevRevpath = trace._prevPolygons = null;
    }


    function visFilter(d) {
        return d.filter(function(v) { return !v.gap && v.vis; });
    }

    function visFilterWithGaps(d) {
        return d.filter(function(v) { return v.vis; });
    }

    function gapFilter(d) {
        return d.filter(function(v) { return !v.gap; });
    }

    function keyFunc(d) {
        return d.id;
    }

    // Returns a function if the trace is keyed, otherwise returns undefined
    function getKeyFunc(trace) {
        if(trace.ids) {
            return keyFunc;
        }
    }

    function hideFilter() {
        return false;
    }

    function makePoints(points, text, cdscatter) {
        var join, selection, hasNode;

        var trace = cdscatter[0].trace;
        var showMarkers = subTypes.hasMarkers(trace);
        var showText = subTypes.hasText(trace);

        var keyFunc = getKeyFunc(trace);
        var markerFilter = hideFilter;
        var textFilter = hideFilter;

        if(showMarkers || showText) {
            var showFilter = identity;
            // if we're stacking, "infer zero" gap mode gets markers in the
            // gap points - because we've inferred a zero there - but other
            // modes (currently "interpolate", later "interrupt" hopefully)
            // we don't draw generated markers
            var stackGroup = trace.stackgroup;
            var isInferZero = stackGroup && (
                gd._fullLayout._scatterStackOpts[xa._id + ya._id][stackGroup].stackgaps === 'infer zero');
            if(trace.marker.maxdisplayed || trace._needsCull) {
                showFilter = isInferZero ? visFilterWithGaps : visFilter;
            }
            else if(stackGroup && !isInferZero) {
                showFilter = gapFilter;
            }

            if(showMarkers) markerFilter = showFilter;
            if(showText) textFilter = showFilter;
        }

        // marker points

        selection = points.selectAll('path.point');

        join = selection.data(markerFilter, keyFunc);

        var enter = join.enter().append('path')
            .classed('point', true);

        if(hasTransition) {
            enter
                .call(Drawing.pointStyle, trace, gd)
                .call(Drawing.translatePoints, xa, ya)
                .style('opacity', 0)
                .transition()
                .style('opacity', 1);
        }

        join.order();

        var styleFns;
        if(showMarkers) {
            styleFns = Drawing.makePointStyleFns(trace);
        }

        join.each(function(d) {
            var el = d3.select(this);
            var sel = transition(el);
            hasNode = Drawing.translatePoint(d, sel, xa, ya);

            if(hasNode) {
                Drawing.singlePointStyle(d, sel, trace, styleFns, gd);

                if(plotinfo.layerClipId) {
                    Drawing.hideOutsideRangePoint(d, sel, xa, ya, trace.xcalendar, trace.ycalendar);
                }

                if(trace.customdata) {
                    el.classed('plotly-customdata', d.data !== null && d.data !== undefined);
                }
            } else {
                sel.remove();
            }
        });

        if(hasTransition) {
            join.exit().transition()
                .style('opacity', 0)
                .remove();
        } else {
            join.exit().remove();
        }

        // text points
        selection = text.selectAll('g');
        join = selection.data(textFilter, keyFunc);

        // each text needs to go in its own 'g' in case
        // it gets converted to mathjax
        join.enter().append('g').classed('textpoint', true).append('text');

        join.order();

        join.each(function(d) {
            var g = d3.select(this);
            var sel = transition(g.select('text'));
            hasNode = Drawing.translatePoint(d, sel, xa, ya);

            if(hasNode) {
                if(plotinfo.layerClipId) {
                    Drawing.hideOutsideRangePoint(d, g, xa, ya, trace.xcalendar, trace.ycalendar);
                }
            } else {
                g.remove();
            }
        });

        join.selectAll('text')
            .call(Drawing.textPointStyle, trace, gd)
            .each(function(d) {
                // This just *has* to be totally custom becuase of SVG text positioning :(
                // It's obviously copied from translatePoint; we just can't use that
                var x = xa.c2p(d.x);
                var y = ya.c2p(d.y);

                d3.select(this).selectAll('tspan.line').each(function() {
                    transition(d3.select(this)).attr({x: x, y: y});
                });
            });

        join.exit().remove();
    }

    points.datum(cdscatter);
    text.datum(cdscatter);
    makePoints(points, text, cdscatter);

    // lastly, clip points groups of `cliponaxis !== false` traces
    // on `plotinfo._hasClipOnAxisFalse === true` subplots
    var hasClipOnAxisFalse = trace.cliponaxis === false;
    var clipUrl = hasClipOnAxisFalse ? null : plotinfo.layerClipId;
    Drawing.setClipUrl(points, clipUrl, gd);
    Drawing.setClipUrl(text, clipUrl, gd);
}

function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) {
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;
    var xr = d3.extent(Lib.simpleMap(xa.range, xa.r2c));
    var yr = d3.extent(Lib.simpleMap(ya.range, ya.r2c));

    var trace = cdscatter[0].trace;
    if(!subTypes.hasMarkers(trace)) return;
    // if marker.maxdisplayed is used, select a maximum of
    // mnum markers to show, from the set that are in the viewport
    var mnum = trace.marker.maxdisplayed;

    // TODO: remove some as we get away from the viewport?
    if(mnum === 0) return;

    var cd = cdscatter.filter(function(v) {
        return v.x >= xr[0] && v.x <= xr[1] && v.y >= yr[0] && v.y <= yr[1];
    });
    var inc = Math.ceil(cd.length / mnum);
    var tnum = 0;
    cdscatterAll.forEach(function(cdj, j) {
        var tracei = cdj[0].trace;
        if(subTypes.hasMarkers(tracei) &&
                tracei.marker.maxdisplayed > 0 && j < idx) {
            tnum++;
        }
    });

    // if multiple traces use maxdisplayed, stagger which markers we
    // display this formula offsets successive traces by 1/3 of the
    // increment, adding an extra small amount after each triplet so
    // it's not quite periodic
    var i0 = Math.round(tnum * inc / 3 + Math.floor(tnum / 3) * inc / 7.1);

    // for error bars: save in cd which markers to show
    // so we don't have to repeat this
    cdscatter.forEach(function(v) { delete v.vis; });
    cd.forEach(function(v, i) {
        if(Math.round((i + i0) % inc) === 0) v.vis = true;
    });
}

},{"../../components/drawing":595,"../../lib":697,"../../lib/polygon":709,"../../registry":826,"./line_points":1062,"./link_traces":1064,"./subtypes":1072,"d3":151}],1069:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var subtypes = _dereq_('./subtypes');

module.exports = function selectPoints(searchInfo, selectionTester) {
    var cd = searchInfo.cd;
    var xa = searchInfo.xaxis;
    var ya = searchInfo.yaxis;
    var selection = [];
    var trace = cd[0].trace;
    var i;
    var di;
    var x;
    var y;

    var hasOnlyLines = (!subtypes.hasMarkers(trace) && !subtypes.hasText(trace));
    if(hasOnlyLines) return [];

    if(selectionTester === false) { // clear selection
        for(i = 0; i < cd.length; i++) {
            cd[i].selected = 0;
        }
    }
    else {
        for(i = 0; i < cd.length; i++) {
            di = cd[i];
            x = xa.c2p(di.x);
            y = ya.c2p(di.y);

            if((di.i !== null) && selectionTester.contains([x, y], false, i, searchInfo)) {
                selection.push({
                    pointNumber: di.i,
                    x: xa.c2d(di.x),
                    y: ya.c2d(di.y)
                });
                di.selected = 1;
            } else {
                di.selected = 0;
            }
        }
    }

    return selection;
};

},{"./subtypes":1072}],1070:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var perStackAttrs = ['orientation', 'groupnorm', 'stackgaps'];

module.exports = function handleStackDefaults(traceIn, traceOut, layout, coerce) {
    var stackOpts = layout._scatterStackOpts;

    var stackGroup = coerce('stackgroup');
    if(stackGroup) {
        // use independent stacking options per subplot
        var subplot = traceOut.xaxis + traceOut.yaxis;
        var subplotStackOpts = stackOpts[subplot];
        if(!subplotStackOpts) subplotStackOpts = stackOpts[subplot] = {};

        var groupOpts = subplotStackOpts[stackGroup];
        var firstTrace = false;
        if(groupOpts) {
            groupOpts.traces.push(traceOut);
        }
        else {
            groupOpts = subplotStackOpts[stackGroup] = {
                // keep track of trace indices for use during stacking calculations
                // this will be filled in during `calc` and used during `crossTraceCalc`
                // so it's OK if we don't recreate it during a non-calc edit
                traceIndices: [],
                // Hold on to the whole set of prior traces
                // First one is most important, so we can clear defaults
                // there if we find explicit values only in later traces.
                // We're only going to *use* the values stored in groupOpts,
                // but for the editor and validate we want things self-consistent
                // The full set of traces is used only to fix `fill` default if
                // we find `orientation: 'h'` beyond the first trace
                traces: [traceOut]
            };
            firstTrace = true;
        }
        // TODO: how is this going to work with groupby transforms?
        // in principle it should be OK I guess, as long as explicit group styles
        // don't override explicit base-trace styles?

        var dflts = {
            orientation: (traceOut.x && !traceOut.y) ? 'h' : 'v'
        };

        for(var i = 0; i < perStackAttrs.length; i++) {
            var attr = perStackAttrs[i];
            var attrFound = attr + 'Found';
            if(!groupOpts[attrFound]) {
                var traceHasAttr = traceIn[attr] !== undefined;
                var isOrientation = attr === 'orientation';
                if(traceHasAttr || firstTrace) {
                    groupOpts[attr] = coerce(attr, dflts[attr]);

                    if(isOrientation) {
                        groupOpts.fillDflt = groupOpts[attr] === 'h' ?
                            'tonextx' : 'tonexty';
                    }

                    if(traceHasAttr) {
                        // Note: this will show a value here even if it's invalid
                        // in which case it will revert to default.
                        groupOpts[attrFound] = true;

                        // Note: only one trace in the stack will get a _fullData
                        // entry for a given stack-wide attribute. If no traces
                        // (or the first trace) specify that attribute, the
                        // first trace will get it. If the first trace does NOT
                        // specify it but some later trace does, then it gets
                        // removed from the first trace and only included in the
                        // one that specified it. This is mostly important for
                        // editors (that want to see the full values to know
                        // what settings are available) and Plotly.react diffing.
                        // Editors may want to use fullLayout._scatterStackOpts
                        // directly and make these settings available from all
                        // traces in the stack... then set the new value into
                        // the first trace, and clear all later traces.
                        if(!firstTrace) {
                            delete groupOpts.traces[0][attr];

                            // orientation can affect default fill of previous traces
                            if(isOrientation) {
                                for(var j = 0; j < groupOpts.traces.length - 1; j++) {
                                    var trace2 = groupOpts.traces[j];
                                    if(trace2._input.fill !== trace2.fill) {
                                        trace2.fill = groupOpts.fillDflt;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return groupOpts;
    }
};

},{}],1071:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var Drawing = _dereq_('../../components/drawing');
var Registry = _dereq_('../../registry');

function style(gd, cd) {
    var s = cd ? cd[0].node3 : d3.select(gd).selectAll('g.trace.scatter');

    s.style('opacity', function(d) {
        return d[0].trace.opacity;
    });

    s.selectAll('g.points').each(function(d) {
        var sel = d3.select(this);
        var trace = d.trace || d[0].trace;
        stylePoints(sel, trace, gd);
    });

    s.selectAll('g.text').each(function(d) {
        var sel = d3.select(this);
        var trace = d.trace || d[0].trace;
        styleText(sel, trace, gd);
    });

    s.selectAll('g.trace path.js-line')
        .call(Drawing.lineGroupStyle);

    s.selectAll('g.trace path.js-fill')
        .call(Drawing.fillGroupStyle);

    Registry.getComponentMethod('errorbars', 'style')(s);
}

function stylePoints(sel, trace, gd) {
    Drawing.pointStyle(sel.selectAll('path.point'), trace, gd);
}

function styleText(sel, trace, gd) {
    Drawing.textPointStyle(sel.selectAll('text'), trace, gd);
}

function styleOnSelect(gd, cd) {
    var s = cd[0].node3;
    var trace = cd[0].trace;

    if(trace.selectedpoints) {
        Drawing.selectedPointStyle(s.selectAll('path.point'), trace);
        Drawing.selectedTextStyle(s.selectAll('text'), trace);
    } else {
        stylePoints(s, trace, gd);
        styleText(s, trace, gd);
    }
}

module.exports = {
    style: style,
    stylePoints: stylePoints,
    styleText: styleText,
    styleOnSelect: styleOnSelect
};

},{"../../components/drawing":595,"../../registry":826,"d3":151}],1072:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

module.exports = {
    hasLines: function(trace) {
        return trace.visible && trace.mode &&
            trace.mode.indexOf('lines') !== -1;
    },

    hasMarkers: function(trace) {
        return trace.visible && (
            (trace.mode && trace.mode.indexOf('markers') !== -1) ||
            // until splom implements 'mode'
            trace.type === 'splom'
        );
    },

    hasText: function(trace) {
        return trace.visible && trace.mode &&
            trace.mode.indexOf('text') !== -1;
    },

    isBubble: function(trace) {
        return Lib.isPlainObject(trace.marker) &&
            Lib.isArrayOrTypedArray(trace.marker.size);
    }
};

},{"../../lib":697}],1073:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

/*
 * opts: object of flags to control features not all text users support
 *   noSelect: caller does not support selected/unselected attribute containers
 */
module.exports = function(traceIn, traceOut, layout, coerce, opts) {
    opts = opts || {};

    coerce('textposition');
    Lib.coerceFont(coerce, 'textfont', layout.font);

    if(!opts.noSelect) {
        coerce('selected.textfont.color');
        coerce('unselected.textfont.color');
    }
};

},{"../../lib":697}],1074:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Registry = _dereq_('../../registry');

module.exports = function handleXYDefaults(traceIn, traceOut, layout, coerce) {
    var x = coerce('x');
    var y = coerce('y');
    var len;

    var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
    handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout);

    if(x) {
        var xlen = Lib.minRowLength(x);
        if(y) {
            len = Math.min(xlen, Lib.minRowLength(y));
        } else {
            len = xlen;
            coerce('y0');
            coerce('dy');
        }
    } else {
        if(!y) return 0;

        len = Lib.minRowLength(y);
        coerce('x0');
        coerce('dx');
    }

    traceOut._length = len;

    return len;
};

},{"../../lib":697,"../../registry":826}],1075:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterAttrs = _dereq_('../scatter/attributes');
var colorAttributes = _dereq_('../../components/colorscale/attributes');
var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var baseAttrs = _dereq_('../../plots/attributes');
var DASHES = _dereq_('../../constants/gl3d_dashes');

var MARKER_SYMBOLS = _dereq_('../../constants/gl3d_markers');
var extendFlat = _dereq_('../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;

var scatterLineAttrs = scatterAttrs.line;
var scatterMarkerAttrs = scatterAttrs.marker;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;

var lineAttrs = extendFlat({
    width: scatterLineAttrs.width,
    dash: {
        valType: 'enumerated',
        values: Object.keys(DASHES),
        dflt: 'solid',
        
        
    }
}, colorAttributes('line'));

function makeProjectionAttr(axLetter) {
    return {
        show: {
            valType: 'boolean',
            
            dflt: false,
            
        },
        opacity: {
            valType: 'number',
            
            min: 0,
            max: 1,
            dflt: 1,
            
        },
        scale: {
            valType: 'number',
            
            min: 0,
            max: 10,
            dflt: 2 / 3,
            
        }
    };
}

var attrs = module.exports = overrideAll({
    x: scatterAttrs.x,
    y: scatterAttrs.y,
    z: {
        valType: 'data_array',
        
    },

    text: extendFlat({}, scatterAttrs.text, {
        
    }),
    hovertext: extendFlat({}, scatterAttrs.hovertext, {
        
    }),
    hovertemplate: hovertemplateAttrs(),

    mode: extendFlat({}, scatterAttrs.mode,  // shouldn't this be on-par with 2D?
        {dflt: 'lines+markers'}),
    surfaceaxis: {
        valType: 'enumerated',
        
        values: [-1, 0, 1, 2],
        dflt: -1,
        
    },
    surfacecolor: {
        valType: 'color',
        
        
    },
    projection: {
        x: makeProjectionAttr('x'),
        y: makeProjectionAttr('y'),
        z: makeProjectionAttr('z')
    },

    connectgaps: scatterAttrs.connectgaps,
    line: lineAttrs,

    marker: extendFlat({  // Parity with scatter.js?
        symbol: {
            valType: 'enumerated',
            values: Object.keys(MARKER_SYMBOLS),
            
            dflt: 'circle',
            arrayOk: true,
            
        },
        size: extendFlat({}, scatterMarkerAttrs.size, {dflt: 8}),
        sizeref: scatterMarkerAttrs.sizeref,
        sizemin: scatterMarkerAttrs.sizemin,
        sizemode: scatterMarkerAttrs.sizemode,
        opacity: extendFlat({}, scatterMarkerAttrs.opacity, {
            arrayOk: false,
            
        }),
        colorbar: scatterMarkerAttrs.colorbar,

        line: extendFlat({
            width: extendFlat({}, scatterMarkerLineAttrs.width, {arrayOk: false})
        },
            colorAttributes('marker.line')
        )
    },
        colorAttributes('marker')
    ),

    textposition: extendFlat({}, scatterAttrs.textposition, {dflt: 'top center'}),
    textfont: {
        color: scatterAttrs.textfont.color,
        size: scatterAttrs.textfont.size,
        family: extendFlat({}, scatterAttrs.textfont.family, {arrayOk: false})
    },

    hoverinfo: extendFlat({}, baseAttrs.hoverinfo)
}, 'calc', 'nested');

attrs.x.editType = attrs.y.editType = attrs.z.editType = 'calc+clearAxisTypes';

},{"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../constants/gl3d_dashes":671,"../../constants/gl3d_markers":672,"../../lib/extend":687,"../../plot_api/edit_types":728,"../../plots/attributes":742,"../scatter/attributes":1048}],1076:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var arraysToCalcdata = _dereq_('../scatter/arrays_to_calcdata');
var calcColorscale = _dereq_('../scatter/colorscale_calc');

/**
 * This is a kludge to put the array attributes into
 * calcdata the way Scatter.plot does, so that legends and
 * popovers know what to do with them.
 */
module.exports = function calc(gd, trace) {
    var cd = [{x: false, y: false, trace: trace, t: {}}];

    arraysToCalcdata(cd, trace);
    calcColorscale(gd, trace);

    return cd;
};

},{"../scatter/arrays_to_calcdata":1047,"../scatter/colorscale_calc":1051}],1077:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');

function calculateAxisErrors(data, params, scaleFactor, axis) {
    if(!params || !params.visible) return null;

    var computeError = Registry.getComponentMethod('errorbars', 'makeComputeError')(params);
    var result = new Array(data.length);

    for(var i = 0; i < data.length; i++) {
        var errors = computeError(+data[i], i);

        if(axis.type === 'log') {
            var point = axis.c2l(data[i]);
            var min = data[i] - errors[0];
            var max = data[i] + errors[1];

            result[i] = [
                (axis.c2l(min, true) - point) * scaleFactor,
                (axis.c2l(max, true) - point) * scaleFactor
            ];

            // Keep track of the lower error bound which isn't negative!
            if(min > 0) {
                var lower = axis.c2l(min);
                if(!axis._lowerLogErrorBound) axis._lowerLogErrorBound = lower;
                axis._lowerErrorBound = Math.min(axis._lowerLogErrorBound, lower);
            }
        } else {
            result[i] = [
                -errors[0] * scaleFactor,
                errors[1] * scaleFactor
            ];
        }
    }

    return result;
}

function dataLength(array) {
    for(var i = 0; i < array.length; i++) {
        if(array[i]) return array[i].length;
    }
    return 0;
}

function calculateErrors(data, scaleFactor, sceneLayout) {
    var errors = [
        calculateAxisErrors(data.x, data.error_x, scaleFactor[0], sceneLayout.xaxis),
        calculateAxisErrors(data.y, data.error_y, scaleFactor[1], sceneLayout.yaxis),
        calculateAxisErrors(data.z, data.error_z, scaleFactor[2], sceneLayout.zaxis)
    ];

    var n = dataLength(errors);
    if(n === 0) return null;

    var errorBounds = new Array(n);

    for(var i = 0; i < n; i++) {
        var bound = [[0, 0, 0], [0, 0, 0]];

        for(var j = 0; j < 3; j++) {
            if(errors[j]) {
                for(var k = 0; k < 2; k++) {
                    bound[k][j] = errors[j][i][k];
                }
            }
        }

        errorBounds[i] = bound;
    }

    return errorBounds;
}

module.exports = calculateErrors;

},{"../../registry":826}],1078:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var createLinePlot = _dereq_('gl-line3d');
var createScatterPlot = _dereq_('gl-scatter3d');
var createErrorBars = _dereq_('gl-error3d');
var createMesh = _dereq_('gl-mesh3d');
var triangulate = _dereq_('delaunay-triangulate');

var Lib = _dereq_('../../lib');
var str2RgbaArray = _dereq_('../../lib/str2rgbarray');
var formatColor = _dereq_('../../lib/gl_format_color').formatColor;
var makeBubbleSizeFn = _dereq_('../scatter/make_bubble_size_func');
var DASH_PATTERNS = _dereq_('../../constants/gl3d_dashes');
var MARKER_SYMBOLS = _dereq_('../../constants/gl3d_markers');

var calculateError = _dereq_('./calc_errors');

function LineWithMarkers(scene, uid) {
    this.scene = scene;
    this.uid = uid;
    this.linePlot = null;
    this.scatterPlot = null;
    this.errorBars = null;
    this.textMarkers = null;
    this.delaunayMesh = null;
    this.color = null;
    this.mode = '';
    this.dataPoints = [];
    this.axesBounds = [
        [-Infinity, -Infinity, -Infinity],
        [Infinity, Infinity, Infinity]
    ];
    this.textLabels = null;
    this.data = null;
}

var proto = LineWithMarkers.prototype;

proto.handlePick = function(selection) {
    if(selection.object &&
        (selection.object === this.linePlot ||
         selection.object === this.delaunayMesh ||
         selection.object === this.textMarkers ||
         selection.object === this.scatterPlot)
    ) {
        var ind = selection.index = selection.data.index;

        if(selection.object.highlight) {
            selection.object.highlight(null);
        }
        if(this.scatterPlot) {
            selection.object = this.scatterPlot;
            this.scatterPlot.highlight(selection.data);
        }

        selection.textLabel = '';
        if(this.textLabels) {
            if(Array.isArray(this.textLabels)) {
                if(this.textLabels[ind] || this.textLabels[ind] === 0) {
                    selection.textLabel = this.textLabels[ind];
                }
            } else {
                selection.textLabel = this.textLabels;
            }
        }

        selection.traceCoordinate = [
            this.data.x[ind],
            this.data.y[ind],
            this.data.z[ind]
        ];

        return true;
    }
};

function constructDelaunay(points, color, axis) {
    var u = (axis + 1) % 3;
    var v = (axis + 2) % 3;
    var filteredPoints = [];
    var filteredIds = [];
    var i;

    for(i = 0; i < points.length; ++i) {
        var p = points[i];
        if(isNaN(p[u]) || !isFinite(p[u]) ||
           isNaN(p[v]) || !isFinite(p[v])) {
            continue;
        }
        filteredPoints.push([p[u], p[v]]);
        filteredIds.push(i);
    }
    var cells = triangulate(filteredPoints);
    for(i = 0; i < cells.length; ++i) {
        var c = cells[i];
        for(var j = 0; j < c.length; ++j) {
            c[j] = filteredIds[c[j]];
        }
    }
    return {
        positions: points,
        cells: cells,
        meshColor: color
    };
}

function calculateErrorParams(errors) {
    var capSize = [0.0, 0.0, 0.0];
    var color = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
    var lineWidth = [1.0, 1.0, 1.0];

    for(var i = 0; i < 3; i++) {
        var e = errors[i];

        if(e && e.copy_zstyle !== false && errors[2].visible !== false) e = errors[2];
        if(!e || !e.visible) continue;

        capSize[i] = e.width / 2;  // ballpark rescaling
        color[i] = str2RgbaArray(e.color);
        lineWidth[i] = e.thickness;

    }

    return {capSize: capSize, color: color, lineWidth: lineWidth};
}

function parseAlignmentX(a) {
    if(a === null || a === undefined) return 0;

    return (a.indexOf('left') > -1) ? -1 :
           (a.indexOf('right') > -1) ? 1 : 0;
}

function parseAlignmentY(a) {
    if(a === null || a === undefined) return 0;

    return (a.indexOf('top') > -1) ? -1 :
           (a.indexOf('bottom') > -1) ? 1 : 0;
}

function calculateTextOffset(tp) {
    // Read out text properties

    var defaultAlignmentX = 0;
    var defaultAlignmentY = 0;

    var textOffset = [
        defaultAlignmentX,
        defaultAlignmentY
    ];

    if(Array.isArray(tp)) {
        for(var i = 0; i < tp.length; i++) {
            textOffset[i] = [
                defaultAlignmentX,
                defaultAlignmentY
            ];
            if(tp[i]) {
                textOffset[i][0] = parseAlignmentX(tp[i]);
                textOffset[i][1] = parseAlignmentY(tp[i]);
            }
        }
    } else {
        textOffset[0] = parseAlignmentX(tp);
        textOffset[1] = parseAlignmentY(tp);
    }

    return textOffset;
}


function calculateSize(sizeIn, sizeFn) {
    // rough parity with Plotly 2D markers
    return sizeFn(sizeIn * 4);
}

function calculateSymbol(symbolIn) {
    return MARKER_SYMBOLS[symbolIn];
}

function formatParam(paramIn, len, calculate, dflt, extraFn) {
    var paramOut = null;

    if(Lib.isArrayOrTypedArray(paramIn)) {
        paramOut = [];

        for(var i = 0; i < len; i++) {
            if(paramIn[i] === undefined) paramOut[i] = dflt;
            else paramOut[i] = calculate(paramIn[i], extraFn);
        }

    }
    else paramOut = calculate(paramIn, Lib.identity);

    return paramOut;
}


function convertPlotlyOptions(scene, data) {
    var points = [];
    var sceneLayout = scene.fullSceneLayout;
    var scaleFactor = scene.dataScale;
    var xaxis = sceneLayout.xaxis;
    var yaxis = sceneLayout.yaxis;
    var zaxis = sceneLayout.zaxis;
    var marker = data.marker;
    var line = data.line;
    var x = data.x || [];
    var y = data.y || [];
    var z = data.z || [];
    var len = x.length;
    var xcalendar = data.xcalendar;
    var ycalendar = data.ycalendar;
    var zcalendar = data.zcalendar;
    var xc, yc, zc;
    var params, i;
    var text;

    // Convert points
    for(i = 0; i < len; i++) {
        // sanitize numbers and apply transforms based on axes.type
        xc = xaxis.d2l(x[i], 0, xcalendar) * scaleFactor[0];
        yc = yaxis.d2l(y[i], 0, ycalendar) * scaleFactor[1];
        zc = zaxis.d2l(z[i], 0, zcalendar) * scaleFactor[2];

        points[i] = [xc, yc, zc];
    }

    // convert text
    if(Array.isArray(data.text)) text = data.text;
    else if(data.text !== undefined) {
        text = new Array(len);
        for(i = 0; i < len; i++) text[i] = data.text;
    }

    // Build object parameters
    params = {
        position: points,
        mode: data.mode,
        text: text
    };

    if('line' in data) {
        params.lineColor = formatColor(line, 1, len);
        params.lineWidth = line.width;
        params.lineDashes = line.dash;
    }

    if('marker' in data) {
        var sizeFn = makeBubbleSizeFn(data);

        params.scatterColor = formatColor(marker, 1, len);
        params.scatterSize = formatParam(marker.size, len, calculateSize, 20, sizeFn);
        params.scatterMarker = formatParam(marker.symbol, len, calculateSymbol, '●');
        params.scatterLineWidth = marker.line.width;  // arrayOk === false
        params.scatterLineColor = formatColor(marker.line, 1, len);
        params.scatterAngle = 0;
    }

    if('textposition' in data) {
        params.textOffset = calculateTextOffset(data.textposition);
        params.textColor = formatColor(data.textfont, 1, len);
        params.textSize = formatParam(data.textfont.size, len, Lib.identity, 12);
        params.textFont = data.textfont.family;  // arrayOk === false
        params.textAngle = 0;
    }

    var dims = ['x', 'y', 'z'];
    params.project = [false, false, false];
    params.projectScale = [1, 1, 1];
    params.projectOpacity = [1, 1, 1];
    for(i = 0; i < 3; ++i) {
        var projection = data.projection[dims[i]];
        if((params.project[i] = projection.show)) {
            params.projectOpacity[i] = projection.opacity;
            params.projectScale[i] = projection.scale;
        }
    }

    params.errorBounds = calculateError(data, scaleFactor, sceneLayout);

    var errorParams = calculateErrorParams([data.error_x, data.error_y, data.error_z]);
    params.errorColor = errorParams.color;
    params.errorLineWidth = errorParams.lineWidth;
    params.errorCapSize = errorParams.capSize;

    params.delaunayAxis = data.surfaceaxis;
    params.delaunayColor = str2RgbaArray(data.surfacecolor);

    return params;
}

function arrayToColor(color) {
    if(Array.isArray(color)) {
        var c = color[0];

        if(Array.isArray(c)) color = c;

        return 'rgb(' + color.slice(0, 3).map(function(x) {
            return Math.round(x * 255);
        }) + ')';
    }

    return null;
}

proto.update = function(data) {
    var gl = this.scene.glplot.gl;
    var lineOptions;
    var scatterOptions;
    var errorOptions;
    var textOptions;
    var dashPattern = DASH_PATTERNS.solid;

    // Save data
    this.data = data;

    // Run data conversion
    var options = convertPlotlyOptions(this.scene, data);

    if('mode' in options) {
        this.mode = options.mode;
    }
    if('lineDashes' in options) {
        if(options.lineDashes in DASH_PATTERNS) {
            dashPattern = DASH_PATTERNS[options.lineDashes];
        }
    }

    this.color = arrayToColor(options.scatterColor) ||
                 arrayToColor(options.lineColor);

    // Save data points
    this.dataPoints = options.position;

    lineOptions = {
        gl: this.scene.glplot.gl,
        position: options.position,
        color: options.lineColor,
        lineWidth: options.lineWidth || 1,
        dashes: dashPattern[0],
        dashScale: dashPattern[1],
        opacity: data.opacity,
        connectGaps: data.connectgaps
    };

    if(this.mode.indexOf('lines') !== -1) {
        if(this.linePlot) this.linePlot.update(lineOptions);
        else {
            this.linePlot = createLinePlot(lineOptions);
            this.linePlot._trace = this;
            this.scene.glplot.add(this.linePlot);
        }
    } else if(this.linePlot) {
        this.scene.glplot.remove(this.linePlot);
        this.linePlot.dispose();
        this.linePlot = null;
    }

    // N.B. marker.opacity must be a scalar for performance
    var scatterOpacity = data.opacity;
    if(data.marker && data.marker.opacity) scatterOpacity *= data.marker.opacity;

    scatterOptions = {
        gl: this.scene.glplot.gl,
        position: options.position,
        color: options.scatterColor,
        size: options.scatterSize,
        glyph: options.scatterMarker,
        opacity: scatterOpacity,
        orthographic: true,
        lineWidth: options.scatterLineWidth,
        lineColor: options.scatterLineColor,
        project: options.project,
        projectScale: options.projectScale,
        projectOpacity: options.projectOpacity
    };

    if(this.mode.indexOf('markers') !== -1) {
        if(this.scatterPlot) this.scatterPlot.update(scatterOptions);
        else {
            this.scatterPlot = createScatterPlot(scatterOptions);
            this.scatterPlot._trace = this;
            this.scatterPlot.highlightScale = 1;
            this.scene.glplot.add(this.scatterPlot);
        }
    } else if(this.scatterPlot) {
        this.scene.glplot.remove(this.scatterPlot);
        this.scatterPlot.dispose();
        this.scatterPlot = null;
    }

    textOptions = {
        gl: this.scene.glplot.gl,
        position: options.position,
        glyph: options.text,
        color: options.textColor,
        size: options.textSize,
        angle: options.textAngle,
        alignment: options.textOffset,
        font: options.textFont,
        orthographic: true,
        lineWidth: 0,
        project: false,
        opacity: data.opacity
    };

    this.textLabels = data.hovertext || data.text;

    if(this.mode.indexOf('text') !== -1) {
        if(this.textMarkers) this.textMarkers.update(textOptions);
        else {
            this.textMarkers = createScatterPlot(textOptions);
            this.textMarkers._trace = this;
            this.textMarkers.highlightScale = 1;
            this.scene.glplot.add(this.textMarkers);
        }
    } else if(this.textMarkers) {
        this.scene.glplot.remove(this.textMarkers);
        this.textMarkers.dispose();
        this.textMarkers = null;
    }

    errorOptions = {
        gl: this.scene.glplot.gl,
        position: options.position,
        color: options.errorColor,
        error: options.errorBounds,
        lineWidth: options.errorLineWidth,
        capSize: options.errorCapSize,
        opacity: data.opacity
    };
    if(this.errorBars) {
        if(options.errorBounds) {
            this.errorBars.update(errorOptions);
        } else {
            this.scene.glplot.remove(this.errorBars);
            this.errorBars.dispose();
            this.errorBars = null;
        }
    } else if(options.errorBounds) {
        this.errorBars = createErrorBars(errorOptions);
        this.errorBars._trace = this;
        this.scene.glplot.add(this.errorBars);
    }

    if(options.delaunayAxis >= 0) {
        var delaunayOptions = constructDelaunay(
            options.position,
            options.delaunayColor,
            options.delaunayAxis
        );
        delaunayOptions.opacity = data.opacity;

        if(this.delaunayMesh) {
            this.delaunayMesh.update(delaunayOptions);
        } else {
            delaunayOptions.gl = gl;
            this.delaunayMesh = createMesh(delaunayOptions);
            this.delaunayMesh._trace = this;
            this.scene.glplot.add(this.delaunayMesh);
        }
    } else if(this.delaunayMesh) {
        this.scene.glplot.remove(this.delaunayMesh);
        this.delaunayMesh.dispose();
        this.delaunayMesh = null;
    }
};

proto.dispose = function() {
    if(this.linePlot) {
        this.scene.glplot.remove(this.linePlot);
        this.linePlot.dispose();
    }
    if(this.scatterPlot) {
        this.scene.glplot.remove(this.scatterPlot);
        this.scatterPlot.dispose();
    }
    if(this.errorBars) {
        this.scene.glplot.remove(this.errorBars);
        this.errorBars.dispose();
    }
    if(this.textMarkers) {
        this.scene.glplot.remove(this.textMarkers);
        this.textMarkers.dispose();
    }
    if(this.delaunayMesh) {
        this.scene.glplot.remove(this.delaunayMesh);
        this.delaunayMesh.dispose();
    }
};

function createLineWithMarkers(scene, data) {
    var plot = new LineWithMarkers(scene, data.uid);
    plot.update(data);
    return plot;
}

module.exports = createLineWithMarkers;

},{"../../constants/gl3d_dashes":671,"../../constants/gl3d_markers":672,"../../lib":697,"../../lib/gl_format_color":694,"../../lib/str2rgbarray":720,"../scatter/make_bubble_size_func":1065,"./calc_errors":1077,"delaunay-triangulate":153,"gl-error3d":240,"gl-line3d":248,"gl-mesh3d":273,"gl-scatter3d":290}],1079:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');

var subTypes = _dereq_('../scatter/subtypes');
var handleMarkerDefaults = _dereq_('../scatter/marker_defaults');
var handleLineDefaults = _dereq_('../scatter/line_defaults');
var handleTextDefaults = _dereq_('../scatter/text_defaults');

var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {

    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var len = handleXYZDefaults(traceIn, traceOut, coerce, layout);
    if(!len) {
        traceOut.visible = false;
        return;
    }

    coerce('text');
    coerce('hovertext');
    coerce('hovertemplate');
    coerce('mode');

    if(subTypes.hasLines(traceOut)) {
        coerce('connectgaps');
        handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
    }

    if(subTypes.hasMarkers(traceOut)) {
        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {noSelect: true});
    }

    if(subTypes.hasText(traceOut)) {
        handleTextDefaults(traceIn, traceOut, layout, coerce, {noSelect: true});
    }

    var lineColor = (traceOut.line || {}).color;
    var markerColor = (traceOut.marker || {}).color;
    if(coerce('surfaceaxis') >= 0) coerce('surfacecolor', lineColor || markerColor);

    var dims = ['x', 'y', 'z'];
    for(var i = 0; i < 3; ++i) {
        var projection = 'projection.' + dims[i];
        if(coerce(projection + '.show')) {
            coerce(projection + '.opacity');
            coerce(projection + '.scale');
        }
    }

    var errorBarsSupplyDefaults = Registry.getComponentMethod('errorbars', 'supplyDefaults');
    errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, {axis: 'z'});
    errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, {axis: 'y', inherit: 'z'});
    errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, {axis: 'x', inherit: 'z'});
};

function handleXYZDefaults(traceIn, traceOut, coerce, layout) {
    var len = 0;
    var x = coerce('x');
    var y = coerce('y');
    var z = coerce('z');

    var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
    handleCalendarDefaults(traceIn, traceOut, ['x', 'y', 'z'], layout);

    if(x && y && z) {
        // TODO: what happens if one is missing?
        len = Math.min(x.length, y.length, z.length);
        traceOut._length = traceOut._xlength = traceOut._ylength = traceOut._zlength = len;
    }

    return len;
}

},{"../../lib":697,"../../registry":826,"../scatter/line_defaults":1061,"../scatter/marker_defaults":1067,"../scatter/subtypes":1072,"../scatter/text_defaults":1073,"./attributes":1075}],1080:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Scatter3D = {};

Scatter3D.plot = _dereq_('./convert');
Scatter3D.attributes = _dereq_('./attributes');
Scatter3D.markerSymbols = _dereq_('../../constants/gl3d_markers');
Scatter3D.supplyDefaults = _dereq_('./defaults');
Scatter3D.colorbar = [
    {
        container: 'marker',
        min: 'cmin',
        max: 'cmax'
    }, {
        container: 'line',
        min: 'cmin',
        max: 'cmax'
    }
];
Scatter3D.calc = _dereq_('./calc');

Scatter3D.moduleType = 'trace';
Scatter3D.name = 'scatter3d';
Scatter3D.basePlotModule = _dereq_('../../plots/gl3d');
Scatter3D.categories = ['gl3d', 'symbols', 'showLegend'];
Scatter3D.meta = {
    
    
};

module.exports = Scatter3D;

},{"../../constants/gl3d_markers":672,"../../plots/gl3d":786,"./attributes":1075,"./calc":1076,"./convert":1078,"./defaults":1079}],1081:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterAttrs = _dereq_('../scatter/attributes');
var plotAttrs = _dereq_('../../plots/attributes');
var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var colorAttributes = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;

var scatterMarkerAttrs = scatterAttrs.marker;
var scatterLineAttrs = scatterAttrs.line;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;

module.exports = {
    carpet: {
        valType: 'string',
        
        editType: 'calc',
        
    },
    a: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    b: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    mode: extendFlat({}, scatterAttrs.mode, {dflt: 'markers'}),
    text: extendFlat({}, scatterAttrs.text, {
        
    }),
    hovertext: extendFlat({}, scatterAttrs.hovertext, {
        
    }),
    line: {
        color: scatterLineAttrs.color,
        width: scatterLineAttrs.width,
        dash: scatterLineAttrs.dash,
        shape: extendFlat({}, scatterLineAttrs.shape,
            {values: ['linear', 'spline']}),
        smoothing: scatterLineAttrs.smoothing,
        editType: 'calc'
    },
    connectgaps: scatterAttrs.connectgaps,
    fill: extendFlat({}, scatterAttrs.fill, {
        values: ['none', 'toself', 'tonext'],
        dflt: 'none',
        
    }),
    fillcolor: scatterAttrs.fillcolor,
    marker: extendFlat({
        symbol: scatterMarkerAttrs.symbol,
        opacity: scatterMarkerAttrs.opacity,
        maxdisplayed: scatterMarkerAttrs.maxdisplayed,
        size: scatterMarkerAttrs.size,
        sizeref: scatterMarkerAttrs.sizeref,
        sizemin: scatterMarkerAttrs.sizemin,
        sizemode: scatterMarkerAttrs.sizemode,
        line: extendFlat({
            width: scatterMarkerLineAttrs.width,
            editType: 'calc'
        },
            colorAttributes('marker.line')
        ),
        gradient: scatterMarkerAttrs.gradient,
        editType: 'calc'
    }, colorAttributes('marker'), {
        colorbar: colorbarAttrs
    }),

    textfont: scatterAttrs.textfont,
    textposition: scatterAttrs.textposition,

    selected: scatterAttrs.selected,
    unselected: scatterAttrs.unselected,

    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
        flags: ['a', 'b', 'text', 'name']
    }),
    hoveron: scatterAttrs.hoveron,
    hovertemplate: hovertemplateAttrs()
};

},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plots/attributes":742,"../scatter/attributes":1048}],1082:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var calcColorscale = _dereq_('../scatter/colorscale_calc');
var arraysToCalcdata = _dereq_('../scatter/arrays_to_calcdata');
var calcSelection = _dereq_('../scatter/calc_selection');
var calcMarkerSize = _dereq_('../scatter/calc').calcMarkerSize;
var lookupCarpet = _dereq_('../carpet/lookup_carpetid');

module.exports = function calc(gd, trace) {
    var carpet = trace._carpetTrace = lookupCarpet(gd, trace);
    if(!carpet || !carpet.visible || carpet.visible === 'legendonly') return;
    var i;

    // Transfer this over from carpet before plotting since this is a necessary
    // condition in order for cartesian to actually plot this trace:
    trace.xaxis = carpet.xaxis;
    trace.yaxis = carpet.yaxis;

    // make the calcdata array
    var serieslen = trace._length;
    var cd = new Array(serieslen);
    var a, b;
    var needsCull = false;
    for(i = 0; i < serieslen; i++) {
        a = trace.a[i];
        b = trace.b[i];
        if(isNumeric(a) && isNumeric(b)) {
            var xy = carpet.ab2xy(+a, +b, true);
            var visible = carpet.isVisible(+a, +b);
            if(!visible) needsCull = true;
            cd[i] = {x: xy[0], y: xy[1], a: a, b: b, vis: visible};
        }
        else cd[i] = {x: false, y: false};
    }

    trace._needsCull = needsCull;

    cd[0].carpet = carpet;
    cd[0].trace = trace;

    calcMarkerSize(trace, serieslen);
    calcColorscale(gd, trace);
    arraysToCalcdata(cd, trace);
    calcSelection(cd, trace);

    return cd;
};

},{"../carpet/lookup_carpetid":894,"../scatter/arrays_to_calcdata":1047,"../scatter/calc":1049,"../scatter/calc_selection":1050,"../scatter/colorscale_calc":1051,"fast-isnumeric":218}],1083:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

var constants = _dereq_('../scatter/constants');
var subTypes = _dereq_('../scatter/subtypes');
var handleMarkerDefaults = _dereq_('../scatter/marker_defaults');
var handleLineDefaults = _dereq_('../scatter/line_defaults');
var handleLineShapeDefaults = _dereq_('../scatter/line_shape_defaults');
var handleTextDefaults = _dereq_('../scatter/text_defaults');
var handleFillColorDefaults = _dereq_('../scatter/fillcolor_defaults');

var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    coerce('carpet');

    // XXX: Don't hard code this
    traceOut.xaxis = 'x';
    traceOut.yaxis = 'y';

    var a = coerce('a');
    var b = coerce('b');
    var len = Math.min(a.length, b.length);

    if(!len) {
        traceOut.visible = false;
        return;
    }

    traceOut._length = len;

    coerce('text');
    coerce('hovertext');

    var defaultMode = len < constants.PTS_LINESONLY ? 'lines+markers' : 'lines';
    coerce('mode', defaultMode);

    if(subTypes.hasLines(traceOut)) {
        handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
        handleLineShapeDefaults(traceIn, traceOut, coerce);
        coerce('connectgaps');
    }

    if(subTypes.hasMarkers(traceOut)) {
        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true});
    }

    if(subTypes.hasText(traceOut)) {
        handleTextDefaults(traceIn, traceOut, layout, coerce);
    }

    var dfltHoverOn = [];

    if(subTypes.hasMarkers(traceOut) || subTypes.hasText(traceOut)) {
        coerce('marker.maxdisplayed');
        dfltHoverOn.push('points');
    }

    coerce('fill');
    if(traceOut.fill !== 'none') {
        handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
        if(!subTypes.hasLines(traceOut)) handleLineShapeDefaults(traceIn, traceOut, coerce);
    }

    if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') {
        dfltHoverOn.push('fills');
    }

    var hoverOn = coerce('hoveron', dfltHoverOn.join('+') || 'points');
    if(hoverOn !== 'fills') coerce('hovertemplate');

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};

},{"../../lib":697,"../scatter/constants":1052,"../scatter/fillcolor_defaults":1057,"../scatter/line_defaults":1061,"../scatter/line_shape_defaults":1063,"../scatter/marker_defaults":1067,"../scatter/subtypes":1072,"../scatter/text_defaults":1073,"./attributes":1081}],1084:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function eventData(out, pt, trace, cd, pointNumber) {
    var cdi = cd[pointNumber];

    out.a = cdi.a;
    out.b = cdi.b;
    out.y = cdi.y;

    return out;
};

},{}],1085:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterHover = _dereq_('../scatter/hover');
var fillHoverText = _dereq_('../scatter/fill_hover_text');

module.exports = function hoverPoints(pointData, xval, yval, hovermode) {
    var scatterPointData = scatterHover(pointData, xval, yval, hovermode);
    if(!scatterPointData || scatterPointData[0].index === false) return;

    var newPointData = scatterPointData[0];

    // if hovering on a fill, we don't show any point data so the label is
    // unchanged from what scatter gives us - except that it needs to
    // be constrained to the trianglular plot area, not just the rectangular
    // area defined by the synthetic x and y axes
    // TODO: in some cases the vertical middle of the shape is not within
    // the triangular viewport at all, so the label can become disconnected
    // from the shape entirely. But calculating what portion of the shape
    // is actually visible, as constrained by the diagonal axis lines, is not
    // so easy and anyway we lost the information we would have needed to do
    // this inside scatterHover.
    if(newPointData.index === undefined) {
        var yFracUp = 1 - (newPointData.y0 / pointData.ya._length);
        var xLen = pointData.xa._length;
        var xMin = xLen * yFracUp / 2;
        var xMax = xLen - xMin;
        newPointData.x0 = Math.max(Math.min(newPointData.x0, xMax), xMin);
        newPointData.x1 = Math.max(Math.min(newPointData.x1, xMax), xMin);
        return scatterPointData;
    }

    var cdi = newPointData.cd[newPointData.index];

    newPointData.a = cdi.a;
    newPointData.b = cdi.b;

    newPointData.xLabelVal = undefined;
    newPointData.yLabelVal = undefined;
    // TODO: nice formatting, and label by axis title, for a, b, and c?

    var trace = newPointData.trace;
    var carpet = trace._carpet;

    var ij = carpet.ab2ij([cdi.a, cdi.b]);
    var i0 = Math.floor(ij[0]);
    var ti = ij[0] - i0;
    var j0 = Math.floor(ij[1]);
    var tj = ij[1] - j0;
    var xy = carpet.evalxy([], i0, j0, ti, tj);
    newPointData.yLabel = xy[1].toFixed(3);

    delete newPointData.text;
    var text = [];

    function textPart(ax, val) {
        var prefix;

        if(ax.labelprefix && ax.labelprefix.length > 0) {
            prefix = ax.labelprefix.replace(/ = $/, '');
        } else {
            prefix = ax._hovertitle;
        }

        text.push(prefix + ': ' + val.toFixed(3) + ax.labelsuffix);
    }


    if(!trace.hovertemplate) {
        var hoverinfo = cdi.hi || trace.hoverinfo;
        var parts = hoverinfo.split('+');

        if(parts.indexOf('all') !== -1) parts = ['a', 'b', 'text'];
        if(parts.indexOf('a') !== -1) textPart(carpet.aaxis, cdi.a);
        if(parts.indexOf('b') !== -1) textPart(carpet.baxis, cdi.b);

        text.push('y: ' + newPointData.yLabel);

        if(parts.indexOf('text') !== -1) {
            fillHoverText(cdi, trace, text);
        }

        newPointData.extraText = text.join('<br>');
    }

    return scatterPointData;
};

},{"../scatter/fill_hover_text":1056,"../scatter/hover":1059}],1086:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var ScatterCarpet = {};

ScatterCarpet.attributes = _dereq_('./attributes');
ScatterCarpet.supplyDefaults = _dereq_('./defaults');
ScatterCarpet.colorbar = _dereq_('../scatter/marker_colorbar');
ScatterCarpet.calc = _dereq_('./calc');
ScatterCarpet.plot = _dereq_('./plot');
ScatterCarpet.style = _dereq_('../scatter/style').style;
ScatterCarpet.styleOnSelect = _dereq_('../scatter/style').styleOnSelect;
ScatterCarpet.hoverPoints = _dereq_('./hover');
ScatterCarpet.selectPoints = _dereq_('../scatter/select');
ScatterCarpet.eventData = _dereq_('./event_data');

ScatterCarpet.moduleType = 'trace';
ScatterCarpet.name = 'scattercarpet';
ScatterCarpet.basePlotModule = _dereq_('../../plots/cartesian');
ScatterCarpet.categories = ['svg', 'carpet', 'symbols', 'showLegend', 'carpetDependent', 'zoomScale'];
ScatterCarpet.meta = {
    
    
};

module.exports = ScatterCarpet;

},{"../../plots/cartesian":756,"../scatter/marker_colorbar":1066,"../scatter/select":1069,"../scatter/style":1071,"./attributes":1081,"./calc":1082,"./defaults":1083,"./event_data":1084,"./hover":1085,"./plot":1087}],1087:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var scatterPlot = _dereq_('../scatter/plot');
var Axes = _dereq_('../../plots/cartesian/axes');
var Drawing = _dereq_('../../components/drawing');

module.exports = function plot(gd, plotinfoproxy, data, layer) {
    var i, trace, node;

    var carpet = data[0][0].carpet;
    // mimic cartesian plotinfo
    var plotinfo = {
        xaxis: Axes.getFromId(gd, carpet.xaxis || 'x'),
        yaxis: Axes.getFromId(gd, carpet.yaxis || 'y'),
        plot: plotinfoproxy.plot,
    };

    scatterPlot(gd, plotinfo, data, layer);

    for(i = 0; i < data.length; i++) {
        trace = data[i][0].trace;

        // Note: .select is adequate but seems to mutate the node data,
        // which is at least a bit suprising and causes problems elsewhere
        node = layer.selectAll('g.trace' + trace.uid + ' .js-line');

        // Note: it would be more efficient if this didn't need to be applied
        // separately to all scattercarpet traces, but that would require
        // lots of reorganization of scatter traces that is otherwise not
        // necessary. That makes this a potential optimization.
        Drawing.setClipUrl(node, data[i][0].carpet._clipPathId, gd);
    }
};

},{"../../components/drawing":595,"../../plots/cartesian/axes":745,"../scatter/plot":1068}],1088:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var scatterAttrs = _dereq_('../scatter/attributes');
var plotAttrs = _dereq_('../../plots/attributes');
var colorAttributes = _dereq_('../../components/colorscale/attributes');
var dash = _dereq_('../../components/drawing/attributes').dash;

var extendFlat = _dereq_('../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;

var scatterMarkerAttrs = scatterAttrs.marker;
var scatterLineAttrs = scatterAttrs.line;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;

module.exports = overrideAll({
    lon: {
        valType: 'data_array',
        
    },
    lat: {
        valType: 'data_array',
        
    },

    locations: {
        valType: 'data_array',
        
    },
    locationmode: {
        valType: 'enumerated',
        values: ['ISO-3', 'USA-states', 'country names'],
        
        dflt: 'ISO-3',
        
    },

    mode: extendFlat({}, scatterAttrs.mode, {dflt: 'markers'}),

    text: extendFlat({}, scatterAttrs.text, {
        
    }),
    hovertext: extendFlat({}, scatterAttrs.hovertext, {
        
    }),

    textfont: scatterAttrs.textfont,
    textposition: scatterAttrs.textposition,

    line: {
        color: scatterLineAttrs.color,
        width: scatterLineAttrs.width,
        dash: dash
    },
    connectgaps: scatterAttrs.connectgaps,

    marker: extendFlat({
        symbol: scatterMarkerAttrs.symbol,
        opacity: scatterMarkerAttrs.opacity,
        size: scatterMarkerAttrs.size,
        sizeref: scatterMarkerAttrs.sizeref,
        sizemin: scatterMarkerAttrs.sizemin,
        sizemode: scatterMarkerAttrs.sizemode,
        colorbar: scatterMarkerAttrs.colorbar,
        line: extendFlat({
            width: scatterMarkerLineAttrs.width
        },
            colorAttributes('marker.line')
        ),
        gradient: scatterMarkerAttrs.gradient
    },
        colorAttributes('marker')
    ),

    fill: {
        valType: 'enumerated',
        values: ['none', 'toself'],
        dflt: 'none',
        
        
    },
    fillcolor: scatterAttrs.fillcolor,

    selected: scatterAttrs.selected,
    unselected: scatterAttrs.unselected,

    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
        flags: ['lon', 'lat', 'location', 'text', 'name']
    }),
    hovertemplate: hovertemplateAttrs(),
}, 'calc', 'nested');

},{"../../components/colorscale/attributes":581,"../../components/drawing/attributes":594,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plot_api/edit_types":728,"../../plots/attributes":742,"../scatter/attributes":1048}],1089:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

var calcMarkerColorscale = _dereq_('../scatter/colorscale_calc');
var arraysToCalcdata = _dereq_('../scatter/arrays_to_calcdata');
var calcSelection = _dereq_('../scatter/calc_selection');

var _ = _dereq_('../../lib')._;

module.exports = function calc(gd, trace) {
    var hasLocationData = Array.isArray(trace.locations);
    var len = hasLocationData ? trace.locations.length : trace._length;
    var calcTrace = new Array(len);

    for(var i = 0; i < len; i++) {
        var calcPt = calcTrace[i] = {};

        if(hasLocationData) {
            var loc = trace.locations[i];
            calcPt.loc = typeof loc === 'string' ? loc : null;
        } else {
            var lon = trace.lon[i];
            var lat = trace.lat[i];

            if(isNumeric(lon) && isNumeric(lat)) calcPt.lonlat = [+lon, +lat];
            else calcPt.lonlat = [BADNUM, BADNUM];
        }
    }

    arraysToCalcdata(calcTrace, trace);
    calcMarkerColorscale(gd, trace);
    calcSelection(calcTrace, trace);

    if(len) {
        calcTrace[0].t = {
            labels: {
                lat: _(gd, 'lat:') + ' ',
                lon: _(gd, 'lon:') + ' '
            }
        };
    }

    return calcTrace;
};

},{"../../constants/numerical":674,"../../lib":697,"../scatter/arrays_to_calcdata":1047,"../scatter/calc_selection":1050,"../scatter/colorscale_calc":1051,"fast-isnumeric":218}],1090:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

var subTypes = _dereq_('../scatter/subtypes');
var handleMarkerDefaults = _dereq_('../scatter/marker_defaults');
var handleLineDefaults = _dereq_('../scatter/line_defaults');
var handleTextDefaults = _dereq_('../scatter/text_defaults');
var handleFillColorDefaults = _dereq_('../scatter/fillcolor_defaults');

var attributes = _dereq_('./attributes');


module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var len = handleLonLatLocDefaults(traceIn, traceOut, coerce);
    if(!len) {
        traceOut.visible = false;
        return;
    }

    coerce('text');
    coerce('hovertext');
    coerce('hovertemplate');
    coerce('mode');

    if(subTypes.hasLines(traceOut)) {
        handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
        coerce('connectgaps');
    }

    if(subTypes.hasMarkers(traceOut)) {
        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true});
    }

    if(subTypes.hasText(traceOut)) {
        handleTextDefaults(traceIn, traceOut, layout, coerce);
    }

    coerce('fill');
    if(traceOut.fill !== 'none') {
        handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
    }

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};

function handleLonLatLocDefaults(traceIn, traceOut, coerce) {
    var len = 0;
    var locations = coerce('locations');

    var lon, lat;

    if(locations) {
        coerce('locationmode');
        len = locations.length;
        return len;
    }

    lon = coerce('lon') || [];
    lat = coerce('lat') || [];
    len = Math.min(lon.length, lat.length);
    traceOut._length = len;

    return len;
}

},{"../../lib":697,"../scatter/fillcolor_defaults":1057,"../scatter/line_defaults":1061,"../scatter/marker_defaults":1067,"../scatter/subtypes":1072,"../scatter/text_defaults":1073,"./attributes":1088}],1091:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


module.exports = function eventData(out, pt) {
    out.lon = pt.lon;
    out.lat = pt.lat;
    out.location = pt.loc ? pt.loc : null;

    return out;
};

},{}],1092:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Fx = _dereq_('../../components/fx');
var Axes = _dereq_('../../plots/cartesian/axes');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

var getTraceColor = _dereq_('../scatter/get_trace_color');
var fillHoverText = _dereq_('../scatter/fill_hover_text');
var attributes = _dereq_('./attributes');

module.exports = function hoverPoints(pointData, xval, yval) {
    var cd = pointData.cd;
    var trace = cd[0].trace;
    var xa = pointData.xa;
    var ya = pointData.ya;
    var geo = pointData.subplot;

    var isLonLatOverEdges = geo.projection.isLonLatOverEdges;
    var project = geo.project;

    function distFn(d) {
        var lonlat = d.lonlat;

        if(lonlat[0] === BADNUM) return Infinity;
        if(isLonLatOverEdges(lonlat)) return Infinity;

        var pt = project(lonlat);
        var px = project([xval, yval]);
        var dx = Math.abs(pt[0] - px[0]);
        var dy = Math.abs(pt[1] - px[1]);
        var rad = Math.max(3, d.mrc || 0);

        // N.B. d.mrc is the calculated marker radius
        // which is only set for trace with 'markers' mode.

        return Math.max(Math.sqrt(dx * dx + dy * dy) - rad, 1 - 3 / rad);
    }

    Fx.getClosest(cd, distFn, pointData);

    // skip the rest (for this trace) if we didn't find a close point
    if(pointData.index === false) return;

    var di = cd[pointData.index];
    var lonlat = di.lonlat;
    var pos = [xa.c2p(lonlat), ya.c2p(lonlat)];
    var rad = di.mrc || 1;

    pointData.x0 = pos[0] - rad;
    pointData.x1 = pos[0] + rad;
    pointData.y0 = pos[1] - rad;
    pointData.y1 = pos[1] + rad;

    pointData.loc = di.loc;
    pointData.lon = lonlat[0];
    pointData.lat = lonlat[1];

    pointData.color = getTraceColor(trace, di);
    pointData.extraText = getExtraText(trace, di, geo.mockAxis, cd[0].t.labels);
    pointData.hovertemplate = trace.hovertemplate;

    return [pointData];
};

function getExtraText(trace, pt, axis, labels) {
    if(trace.hovertemplate) {
        return;
    }

    var hoverinfo = pt.hi || trace.hoverinfo;

    var parts = hoverinfo === 'all' ?
        attributes.hoverinfo.flags :
        hoverinfo.split('+');

    var hasLocation = parts.indexOf('location') !== -1 && Array.isArray(trace.locations);
    var hasLon = (parts.indexOf('lon') !== -1);
    var hasLat = (parts.indexOf('lat') !== -1);
    var hasText = (parts.indexOf('text') !== -1);
    var text = [];

    function format(val) {
        return Axes.tickText(axis, axis.c2l(val), 'hover').text + '\u00B0';
    }

    if(hasLocation) {
        text.push(pt.loc);
    } else if(hasLon && hasLat) {
        text.push('(' + format(pt.lonlat[0]) + ', ' + format(pt.lonlat[1]) + ')');
    } else if(hasLon) {
        text.push(labels.lon + format(pt.lonlat[0]));
    } else if(hasLat) {
        text.push(labels.lat + format(pt.lonlat[1]));
    }

    if(hasText) {
        fillHoverText(pt, trace, text);
    }

    return text.join('<br>');
}

},{"../../components/fx":613,"../../constants/numerical":674,"../../plots/cartesian/axes":745,"../scatter/fill_hover_text":1056,"../scatter/get_trace_color":1058,"./attributes":1088}],1093:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var ScatterGeo = {};

ScatterGeo.attributes = _dereq_('./attributes');
ScatterGeo.supplyDefaults = _dereq_('./defaults');
ScatterGeo.colorbar = _dereq_('../scatter/marker_colorbar');
ScatterGeo.calc = _dereq_('./calc');
ScatterGeo.plot = _dereq_('./plot');
ScatterGeo.style = _dereq_('./style');
ScatterGeo.styleOnSelect = _dereq_('../scatter/style').styleOnSelect;
ScatterGeo.hoverPoints = _dereq_('./hover');
ScatterGeo.eventData = _dereq_('./event_data');
ScatterGeo.selectPoints = _dereq_('./select');

ScatterGeo.moduleType = 'trace';
ScatterGeo.name = 'scattergeo';
ScatterGeo.basePlotModule = _dereq_('../../plots/geo');
ScatterGeo.categories = ['geo', 'symbols', 'showLegend', 'scatter-like'];
ScatterGeo.meta = {
    
    
};

module.exports = ScatterGeo;

},{"../../plots/geo":775,"../scatter/marker_colorbar":1066,"../scatter/style":1071,"./attributes":1088,"./calc":1089,"./defaults":1090,"./event_data":1091,"./hover":1092,"./plot":1094,"./select":1095,"./style":1096}],1094:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

var Lib = _dereq_('../../lib');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;
var getTopojsonFeatures = _dereq_('../../lib/topojson_utils').getTopojsonFeatures;
var locationToFeature = _dereq_('../../lib/geo_location_utils').locationToFeature;
var geoJsonUtils = _dereq_('../../lib/geojson_utils');
var subTypes = _dereq_('../scatter/subtypes');
var style = _dereq_('./style');

module.exports = function plot(gd, geo, calcData) {
    for(var i = 0; i < calcData.length; i++) {
        calcGeoJSON(calcData[i], geo.topojson);
    }

    function removeBADNUM(d, node) {
        if(d.lonlat[0] === BADNUM) {
            d3.select(node).remove();
        }
    }

    var scatterLayer = geo.layers.frontplot.select('.scatterlayer');
    var gTraces = Lib.makeTraceGroups(scatterLayer, calcData, 'trace scattergeo');

    // TODO find a way to order the inner nodes on update
    gTraces.selectAll('*').remove();

    gTraces.each(function(calcTrace) {
        var s = calcTrace[0].node3 = d3.select(this);
        var trace = calcTrace[0].trace;

        if(subTypes.hasLines(trace) || trace.fill !== 'none') {
            var lineCoords = geoJsonUtils.calcTraceToLineCoords(calcTrace);

            var lineData = (trace.fill !== 'none') ?
                geoJsonUtils.makePolygon(lineCoords) :
                geoJsonUtils.makeLine(lineCoords);

            s.selectAll('path.js-line')
                .data([{geojson: lineData, trace: trace}])
              .enter().append('path')
                .classed('js-line', true)
                .style('stroke-miterlimit', 2);
        }

        if(subTypes.hasMarkers(trace)) {
            s.selectAll('path.point')
                .data(Lib.identity)
             .enter().append('path')
                .classed('point', true)
                .each(function(calcPt) { removeBADNUM(calcPt, this); });
        }

        if(subTypes.hasText(trace)) {
            s.selectAll('g')
                .data(Lib.identity)
              .enter().append('g')
                .append('text')
                .each(function(calcPt) { removeBADNUM(calcPt, this); });
        }

        // call style here within topojson request callback
        style(gd, calcTrace);
    });
};

function calcGeoJSON(calcTrace, topojson) {
    var trace = calcTrace[0].trace;

    if(!Array.isArray(trace.locations)) return;

    var features = getTopojsonFeatures(trace, topojson);
    var locationmode = trace.locationmode;

    for(var i = 0; i < calcTrace.length; i++) {
        var calcPt = calcTrace[i];
        var feature = locationToFeature(locationmode, calcPt.loc, features);

        calcPt.lonlat = feature ? feature.properties.ct : [BADNUM, BADNUM];
    }
}

},{"../../constants/numerical":674,"../../lib":697,"../../lib/geo_location_utils":690,"../../lib/geojson_utils":691,"../../lib/topojson_utils":724,"../scatter/subtypes":1072,"./style":1096,"d3":151}],1095:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var subtypes = _dereq_('../scatter/subtypes');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

module.exports = function selectPoints(searchInfo, selectionTester) {
    var cd = searchInfo.cd;
    var xa = searchInfo.xaxis;
    var ya = searchInfo.yaxis;
    var selection = [];
    var trace = cd[0].trace;

    var di, lonlat, x, y, i;

    var hasOnlyLines = (!subtypes.hasMarkers(trace) && !subtypes.hasText(trace));
    if(hasOnlyLines) return [];

    if(selectionTester === false) {
        for(i = 0; i < cd.length; i++) {
            cd[i].selected = 0;
        }
    } else {
        for(i = 0; i < cd.length; i++) {
            di = cd[i];
            lonlat = di.lonlat;

            // some projection types can't handle BADNUMs
            if(lonlat[0] === BADNUM) continue;

            x = xa.c2p(lonlat);
            y = ya.c2p(lonlat);

            if(selectionTester.contains([x, y], null, i, searchInfo)) {
                selection.push({
                    pointNumber: i,
                    lon: lonlat[0],
                    lat: lonlat[1]
                });
                di.selected = 1;
            } else {
                di.selected = 0;
            }
        }
    }

    return selection;
};

},{"../../constants/numerical":674,"../scatter/subtypes":1072}],1096:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var Drawing = _dereq_('../../components/drawing');
var Color = _dereq_('../../components/color');

var scatterStyle = _dereq_('../scatter/style');
var stylePoints = scatterStyle.stylePoints;
var styleText = scatterStyle.styleText;

module.exports = function style(gd, calcTrace) {
    if(calcTrace) styleTrace(gd, calcTrace);
};

function styleTrace(gd, calcTrace) {
    var trace = calcTrace[0].trace;
    var s = calcTrace[0].node3;

    s.style('opacity', calcTrace[0].trace.opacity);

    stylePoints(s, trace, gd);
    styleText(s, trace, gd);

    // this part is incompatible with Drawing.lineGroupStyle
    s.selectAll('path.js-line')
        .style('fill', 'none')
        .each(function(d) {
            var path = d3.select(this);
            var trace = d.trace;
            var line = trace.line || {};

            path.call(Color.stroke, line.color)
                .call(Drawing.dashLine, line.dash || '', line.width || 0);

            if(trace.fill !== 'none') {
                path.call(Color.fill, trace.fillcolor);
            }
        });
}

},{"../../components/color":574,"../../components/drawing":595,"../scatter/style":1071,"d3":151}],1097:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var plotAttrs = _dereq_('../../plots/attributes');
var scatterAttrs = _dereq_('../scatter/attributes');
var colorAttrs = _dereq_('../../components/colorscale/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
var DASHES = _dereq_('./constants').DASHES;

var scatterLineAttrs = scatterAttrs.line;
var scatterMarkerAttrs = scatterAttrs.marker;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;

var attrs = module.exports = overrideAll({
    x: scatterAttrs.x,
    x0: scatterAttrs.x0,
    dx: scatterAttrs.dx,
    y: scatterAttrs.y,
    y0: scatterAttrs.y0,
    dy: scatterAttrs.dy,

    text: scatterAttrs.text,
    hovertext: scatterAttrs.hovertext,

    textposition: scatterAttrs.textposition,
    textfont: scatterAttrs.textfont,

    mode: {
        valType: 'flaglist',
        flags: ['lines', 'markers', 'text'],
        extras: ['none'],
        
        
    },
    line: {
        color: scatterLineAttrs.color,
        width: scatterLineAttrs.width,
        shape: {
            valType: 'enumerated',
            values: ['linear', 'hv', 'vh', 'hvh', 'vhv'],
            dflt: 'linear',
            
            editType: 'plot',
            
        },
        dash: {
            valType: 'enumerated',
            values: Object.keys(DASHES),
            dflt: 'solid',
            
            
        }
    },
    marker: extendFlat({}, colorAttrs('marker'), {
        symbol: scatterMarkerAttrs.symbol,
        size: scatterMarkerAttrs.size,
        sizeref: scatterMarkerAttrs.sizeref,
        sizemin: scatterMarkerAttrs.sizemin,
        sizemode: scatterMarkerAttrs.sizemode,
        opacity: scatterMarkerAttrs.opacity,
        colorbar: scatterMarkerAttrs.colorbar,
        line: extendFlat({}, colorAttrs('marker.line'), {
            width: scatterMarkerLineAttrs.width
        })
    }),
    connectgaps: scatterAttrs.connectgaps,
    fill: extendFlat({}, scatterAttrs.fill, {dflt: 'none'}),
    fillcolor: scatterAttrs.fillcolor,

    // no hoveron

    selected: {
        marker: scatterAttrs.selected.marker,
        textfont: scatterAttrs.selected.textfont
    },
    unselected: {
        marker: scatterAttrs.unselected.marker,
        textfont: scatterAttrs.unselected.textfont
    },

    opacity: plotAttrs.opacity

}, 'calc', 'nested');

attrs.x.editType = attrs.y.editType = attrs.x0.editType = attrs.y0.editType = 'calc+clearAxisTypes';
attrs.hovertemplate = scatterAttrs.hovertemplate;

},{"../../components/colorscale/attributes":581,"../../lib/extend":687,"../../plot_api/edit_types":728,"../../plots/attributes":742,"../scatter/attributes":1048,"./constants":1098}],1098:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var SYMBOL_SIZE = 20;

module.exports = {
    TOO_MANY_POINTS: 1e5,

    SYMBOL_SDF_SIZE: 200,
    SYMBOL_SIZE: SYMBOL_SIZE,
    SYMBOL_STROKE: SYMBOL_SIZE / 20,

    DOT_RE: /-dot/,
    OPEN_RE: /-open/,

    DASHES: {
        solid: [1],
        dot: [1, 1],
        dash: [4, 1],
        longdash: [8, 1],
        dashdot: [4, 1, 1, 1],
        longdashdot: [8, 1, 1, 1]
    }
};

},{}],1099:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var svgSdf = _dereq_('svg-path-sdf');
var rgba = _dereq_('color-normalize');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Drawing = _dereq_('../../components/drawing');
var AxisIDs = _dereq_('../../plots/cartesian/axis_ids');

var formatColor = _dereq_('../../lib/gl_format_color').formatColor;
var subTypes = _dereq_('../scatter/subtypes');
var makeBubbleSizeFn = _dereq_('../scatter/make_bubble_size_func');

var constants = _dereq_('./constants');
var DESELECTDIM = _dereq_('../../constants/interactions').DESELECTDIM;

var TEXTOFFSETSIGN = {
    start: 1, left: 1, end: -1, right: -1, middle: 0, center: 0, bottom: 1, top: -1
};

function convertStyle(gd, trace) {
    var i;

    var opts = {
        marker: undefined,
        markerSel: undefined,
        markerUnsel: undefined,
        line: undefined,
        fill: undefined,
        errorX: undefined,
        errorY: undefined,
        text: undefined,
        textSel: undefined,
        textUnsel: undefined
    };

    if(trace.visible !== true) return opts;

    if(subTypes.hasText(trace)) {
        opts.text = convertTextStyle(trace);
        opts.textSel = convertTextSelection(trace, trace.selected);
        opts.textUnsel = convertTextSelection(trace, trace.unselected);
    }

    if(subTypes.hasMarkers(trace)) {
        opts.marker = convertMarkerStyle(trace);
        opts.markerSel = convertMarkerSelection(trace, trace.selected);
        opts.markerUnsel = convertMarkerSelection(trace, trace.unselected);

        if(!trace.unselected && Array.isArray(trace.marker.opacity)) {
            var mo = trace.marker.opacity;
            opts.markerUnsel.opacity = new Array(mo.length);
            for(i = 0; i < mo.length; i++) {
                opts.markerUnsel.opacity[i] = DESELECTDIM * mo[i];
            }
        }
    }

    if(subTypes.hasLines(trace)) {
        opts.line = {
            overlay: true,
            thickness: trace.line.width,
            color: trace.line.color,
            opacity: trace.opacity
        };

        var dashes = (constants.DASHES[trace.line.dash] || [1]).slice();
        for(i = 0; i < dashes.length; ++i) {
            dashes[i] *= trace.line.width;
        }
        opts.line.dashes = dashes;
    }

    if(trace.error_x && trace.error_x.visible) {
        opts.errorX = convertErrorBarStyle(trace, trace.error_x);
    }

    if(trace.error_y && trace.error_y.visible) {
        opts.errorY = convertErrorBarStyle(trace, trace.error_y);
    }

    if(!!trace.fill && trace.fill !== 'none') {
        opts.fill = {
            closed: true,
            fill: trace.fillcolor,
            thickness: 0
        };
    }

    return opts;
}

function convertTextStyle(trace) {
    var count = trace._length;
    var textfontIn = trace.textfont;
    var textpositionIn = trace.textposition;
    var textPos = Array.isArray(textpositionIn) ? textpositionIn : [textpositionIn];
    var tfc = textfontIn.color;
    var tfs = textfontIn.size;
    var tff = textfontIn.family;
    var optsOut = {};
    var i;

    optsOut.text = trace.text;
    optsOut.opacity = trace.opacity;
    optsOut.font = {};
    optsOut.align = [];
    optsOut.baseline = [];

    for(i = 0; i < textPos.length; i++) {
        var tp = textPos[i].split(/\s+/);

        switch(tp[1]) {
            case 'left':
                optsOut.align.push('right');
                break;
            case 'right':
                optsOut.align.push('left');
                break;
            default:
                optsOut.align.push(tp[1]);
        }
        switch(tp[0]) {
            case 'top':
                optsOut.baseline.push('bottom');
                break;
            case 'bottom':
                optsOut.baseline.push('top');
                break;
            default:
                optsOut.baseline.push(tp[0]);
        }
    }

    if(Array.isArray(tfc)) {
        optsOut.color = new Array(count);
        for(i = 0; i < count; i++) {
            optsOut.color[i] = tfc[i];
        }
    } else {
        optsOut.color = tfc;
    }

    if(Array.isArray(tfs) || Array.isArray(tff)) {
        // if any textfont param is array - make render a batch
        optsOut.font = new Array(count);
        for(i = 0; i < count; i++) {
            var fonti = optsOut.font[i] = {};

            fonti.size = Array.isArray(tfs) ?
                (isNumeric(tfs[i]) ? tfs[i] : 0) :
                tfs;

            fonti.family = Array.isArray(tff) ? tff[i] : tff;
        }
    } else {
        // if both are single values, make render fast single-value
        optsOut.font = {size: tfs, family: tff};
    }

    return optsOut;
}


function convertMarkerStyle(trace) {
    var count = trace._length;
    var optsIn = trace.marker;
    var optsOut = {};
    var i;

    var multiSymbol = Array.isArray(optsIn.symbol);
    var multiColor = Lib.isArrayOrTypedArray(optsIn.color);
    var multiLineColor = Lib.isArrayOrTypedArray(optsIn.line.color);
    var multiOpacity = Lib.isArrayOrTypedArray(optsIn.opacity);
    var multiSize = Lib.isArrayOrTypedArray(optsIn.size);
    var multiLineWidth = Lib.isArrayOrTypedArray(optsIn.line.width);

    var isOpen;
    if(!multiSymbol) isOpen = constants.OPEN_RE.test(optsIn.symbol);

    // prepare colors
    if(multiSymbol || multiColor || multiLineColor || multiOpacity) {
        optsOut.colors = new Array(count);
        optsOut.borderColors = new Array(count);

        var colors = formatColor(optsIn, optsIn.opacity, count);
        var borderColors = formatColor(optsIn.line, optsIn.opacity, count);

        if(!Array.isArray(borderColors[0])) {
            var borderColor = borderColors;
            borderColors = Array(count);
            for(i = 0; i < count; i++) {
                borderColors[i] = borderColor;
            }
        }
        if(!Array.isArray(colors[0])) {
            var color = colors;
            colors = Array(count);
            for(i = 0; i < count; i++) {
                colors[i] = color;
            }
        }

        optsOut.colors = colors;
        optsOut.borderColors = borderColors;

        for(i = 0; i < count; i++) {
            if(multiSymbol) {
                var symbol = optsIn.symbol[i];
                isOpen = constants.OPEN_RE.test(symbol);
            }
            if(isOpen) {
                borderColors[i] = colors[i].slice();
                colors[i] = colors[i].slice();
                colors[i][3] = 0;
            }
        }

        optsOut.opacity = trace.opacity;
    } else {
        if(isOpen) {
            optsOut.color = rgba(optsIn.color, 'uint8');
            optsOut.color[3] = 0;
            optsOut.borderColor = rgba(optsIn.color, 'uint8');
        } else {
            optsOut.color = rgba(optsIn.color, 'uint8');
            optsOut.borderColor = rgba(optsIn.line.color, 'uint8');
        }

        optsOut.opacity = trace.opacity * optsIn.opacity;
    }

    // prepare symbols
    if(multiSymbol) {
        optsOut.markers = new Array(count);
        for(i = 0; i < count; i++) {
            optsOut.markers[i] = getSymbolSdf(optsIn.symbol[i]);
        }
    } else {
        optsOut.marker = getSymbolSdf(optsIn.symbol);
    }

    // prepare sizes
    var markerSizeFunc = makeBubbleSizeFn(trace);
    var s;

    if(multiSize || multiLineWidth) {
        var sizes = optsOut.sizes = new Array(count);
        var borderSizes = optsOut.borderSizes = new Array(count);
        var sizeTotal = 0;
        var sizeAvg;

        if(multiSize) {
            for(i = 0; i < count; i++) {
                sizes[i] = markerSizeFunc(optsIn.size[i]);
                sizeTotal += sizes[i];
            }
            sizeAvg = sizeTotal / count;
        } else {
            s = markerSizeFunc(optsIn.size);
            for(i = 0; i < count; i++) {
                sizes[i] = s;
            }
        }

        // See  https://github.com/plotly/plotly.js/pull/1781#discussion_r121820798
        if(multiLineWidth) {
            for(i = 0; i < count; i++) {
                borderSizes[i] = optsIn.line.width[i] / 2;
            }
        } else {
            s = optsIn.line.width / 2;
            for(i = 0; i < count; i++) {
                borderSizes[i] = s;
            }
        }

        optsOut.sizeAvg = sizeAvg;
    } else {
        optsOut.size = markerSizeFunc(optsIn && optsIn.size || 10);
        optsOut.borderSizes = markerSizeFunc(optsIn.line.width);
    }

    return optsOut;
}

function convertMarkerSelection(trace, target) {
    var optsIn = trace.marker;
    var optsOut = {};

    if(!target) return optsOut;

    if(target.marker && target.marker.symbol) {
        optsOut = convertMarkerStyle(Lib.extendFlat({}, optsIn, target.marker));
    } else if(target.marker) {
        if(target.marker.size) optsOut.size = target.marker.size / 2;
        if(target.marker.color) optsOut.colors = target.marker.color;
        if(target.marker.opacity !== undefined) optsOut.opacity = target.marker.opacity;
    }

    return optsOut;
}

function convertTextSelection(trace, target) {
    var optsOut = {};

    if(!target) return optsOut;

    if(target.textfont) {
        var optsIn = {
            opacity: 1,
            text: trace.text,
            textposition: trace.textposition,
            textfont: Lib.extendFlat({}, trace.textfont)
        };
        if(target.textfont) {
            Lib.extendFlat(optsIn.textfont, target.textfont);
        }
        optsOut = convertTextStyle(optsIn);
    }

    return optsOut;
}

function convertErrorBarStyle(trace, target) {
    var optsOut = {
        capSize: target.width * 2,
        lineWidth: target.thickness,
        color: target.color
    };

    if(target.copy_ystyle) {
        optsOut = trace.error_y;
    }

    return optsOut;
}

var SYMBOL_SDF_SIZE = constants.SYMBOL_SDF_SIZE;
var SYMBOL_SIZE = constants.SYMBOL_SIZE;
var SYMBOL_STROKE = constants.SYMBOL_STROKE;
var SYMBOL_SDF = {};
var SYMBOL_SVG_CIRCLE = Drawing.symbolFuncs[0](SYMBOL_SIZE * 0.05);

function getSymbolSdf(symbol) {
    if(symbol === 'circle') return null;

    var symbolPath, symbolSdf;
    var symbolNumber = Drawing.symbolNumber(symbol);
    var symbolFunc = Drawing.symbolFuncs[symbolNumber % 100];
    var symbolNoDot = !!Drawing.symbolNoDot[symbolNumber % 100];
    var symbolNoFill = !!Drawing.symbolNoFill[symbolNumber % 100];

    var isDot = constants.DOT_RE.test(symbol);

    // get symbol sdf from cache or generate it
    if(SYMBOL_SDF[symbol]) return SYMBOL_SDF[symbol];

    if(isDot && !symbolNoDot) {
        symbolPath = symbolFunc(SYMBOL_SIZE * 1.1) + SYMBOL_SVG_CIRCLE;
    }
    else {
        symbolPath = symbolFunc(SYMBOL_SIZE);
    }

    symbolSdf = svgSdf(symbolPath, {
        w: SYMBOL_SDF_SIZE,
        h: SYMBOL_SDF_SIZE,
        viewBox: [-SYMBOL_SIZE, -SYMBOL_SIZE, SYMBOL_SIZE, SYMBOL_SIZE],
        stroke: symbolNoFill ? SYMBOL_STROKE : -SYMBOL_STROKE
    });
    SYMBOL_SDF[symbol] = symbolSdf;

    return symbolSdf || null;
}

function convertLinePositions(gd, trace, positions) {
    var len = positions.length;
    var count = len / 2;
    var linePositions;
    var i;

    if(subTypes.hasLines(trace) && count) {
        if(trace.line.shape === 'hv') {
            linePositions = [];
            for(i = 0; i < count - 1; i++) {
                if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) {
                    linePositions.push(NaN, NaN, NaN, NaN);
                } else {
                    linePositions.push(positions[i * 2], positions[i * 2 + 1]);
                    if(!isNaN(positions[i * 2 + 2]) && !isNaN(positions[i * 2 + 3])) {
                        linePositions.push(positions[i * 2 + 2], positions[i * 2 + 1]);
                    } else {
                        linePositions.push(NaN, NaN);
                    }
                }
            }
            linePositions.push(positions[len - 2], positions[len - 1]);
        } else if(trace.line.shape === 'hvh') {
            linePositions = [];
            for(i = 0; i < count - 1; i++) {
                if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1]) || isNaN(positions[i * 2 + 2]) || isNaN(positions[i * 2 + 3])) {
                    if(!isNaN(positions[i * 2]) && !isNaN(positions[i * 2 + 1])) {
                        linePositions.push(positions[i * 2], positions[i * 2 + 1]);
                    } else {
                        linePositions.push(NaN, NaN);
                    }
                    linePositions.push(NaN, NaN);
                }
                else {
                    var midPtX = (positions[i * 2] + positions[i * 2 + 2]) / 2;
                    linePositions.push(
                        positions[i * 2],
                        positions[i * 2 + 1],
                        midPtX,
                        positions[i * 2 + 1],
                        midPtX,
                        positions[i * 2 + 3]
                    );
                }
            }
            linePositions.push(positions[len - 2], positions[len - 1]);
        } else if(trace.line.shape === 'vhv') {
            linePositions = [];
            for(i = 0; i < count - 1; i++) {
                if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1]) || isNaN(positions[i * 2 + 2]) || isNaN(positions[i * 2 + 3])) {
                    if(!isNaN(positions[i * 2]) && !isNaN(positions[i * 2 + 1])) {
                        linePositions.push(positions[i * 2], positions[i * 2 + 1]);
                    } else {
                        linePositions.push(NaN, NaN);
                    }
                    linePositions.push(NaN, NaN);
                }
                else {
                    var midPtY = (positions[i * 2 + 1] + positions[i * 2 + 3]) / 2;
                    linePositions.push(
                        positions[i * 2],
                        positions[i * 2 + 1],
                        positions[i * 2],
                        midPtY,
                        positions[i * 2 + 2],
                        midPtY
                    );
                }
            }
            linePositions.push(positions[len - 2], positions[len - 1]);
        } else if(trace.line.shape === 'vh') {
            linePositions = [];
            for(i = 0; i < count - 1; i++) {
                if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) {
                    linePositions.push(NaN, NaN, NaN, NaN);
                }
                else {
                    linePositions.push(positions[i * 2], positions[i * 2 + 1]);
                    if(!isNaN(positions[i * 2 + 2]) && !isNaN(positions[i * 2 + 3])) {
                        linePositions.push(positions[i * 2], positions[i * 2 + 3]);
                    } else {
                        linePositions.push(NaN, NaN);
                    }
                }
            }
            linePositions.push(positions[len - 2], positions[len - 1]);
        } else {
            linePositions = positions;
        }
    }

    // If we have data with gaps, we ought to use rect joins
    // FIXME: get rid of this
    var hasNaN = false;
    for(i = 0; i < linePositions.length; i++) {
        if(isNaN(linePositions[i])) {
            hasNaN = true;
            break;
        }
    }

    var join = (hasNaN || linePositions.length > constants.TOO_MANY_POINTS) ? 'rect' :
        subTypes.hasMarkers(trace) ? 'rect' : 'round';

    // fill gaps
    if(hasNaN && trace.connectgaps) {
        var lastX = linePositions[0];
        var lastY = linePositions[1];

        for(i = 0; i < linePositions.length; i += 2) {
            if(isNaN(linePositions[i]) || isNaN(linePositions[i + 1])) {
                linePositions[i] = lastX;
                linePositions[i + 1] = lastY;
            }
            else {
                lastX = linePositions[i];
                lastY = linePositions[i + 1];
            }
        }
    }

    return {
        join: join,
        positions: linePositions
    };
}

function convertErrorBarPositions(gd, trace, positions, x, y) {
    var makeComputeError = Registry.getComponentMethod('errorbars', 'makeComputeError');
    var xa = AxisIDs.getFromId(gd, trace.xaxis);
    var ya = AxisIDs.getFromId(gd, trace.yaxis);
    var count = positions.length / 2;
    var out = {};

    function convertOneAxis(coords, ax) {
        var axLetter = ax._id.charAt(0);
        var opts = trace['error_' + axLetter];

        if(opts && opts.visible && (ax.type === 'linear' || ax.type === 'log')) {
            var computeError = makeComputeError(opts);
            var pOffset = {x: 0, y: 1}[axLetter];
            var eOffset = {x: [0, 1, 2, 3], y: [2, 3, 0, 1]}[axLetter];
            var errors = new Float64Array(4 * count);
            var minShoe = Infinity;
            var maxHat = -Infinity;

            for(var i = 0, j = 0; i < count; i++, j += 4) {
                var dc = coords[i];

                if(isNumeric(dc)) {
                    var dl = positions[i * 2 + pOffset];
                    var vals = computeError(dc, i);
                    var lv = vals[0];
                    var hv = vals[1];

                    if(isNumeric(lv) && isNumeric(hv)) {
                        var shoe = dc - lv;
                        var hat = dc + hv;

                        errors[j + eOffset[0]] = dl - ax.c2l(shoe);
                        errors[j + eOffset[1]] = ax.c2l(hat) - dl;
                        errors[j + eOffset[2]] = 0;
                        errors[j + eOffset[3]] = 0;

                        minShoe = Math.min(minShoe, dc - lv);
                        maxHat = Math.max(maxHat, dc + hv);
                    }
                }
            }

            out[axLetter] = {
                positions: positions,
                errors: errors,
                _bnds: [minShoe, maxHat]
            };
        }
    }

    convertOneAxis(x, xa);
    convertOneAxis(y, ya);
    return out;
}

function convertTextPosition(gd, trace, textOpts, markerOpts) {
    var count = trace._length;
    var out = {};
    var i;

    // corresponds to textPointPosition from component.drawing
    if(subTypes.hasMarkers(trace)) {
        var fontOpts = textOpts.font;
        var align = textOpts.align;
        var baseline = textOpts.baseline;
        out.offset = new Array(count);

        for(i = 0; i < count; i++) {
            var ms = markerOpts.sizes ? markerOpts.sizes[i] : markerOpts.size;
            var fs = Array.isArray(fontOpts) ? fontOpts[i].size : fontOpts.size;

            var a = Array.isArray(align) ?
                (align.length > 1 ? align[i] : align[0]) :
                align;
            var b = Array.isArray(baseline) ?
                (baseline.length > 1 ? baseline[i] : baseline[0]) :
                baseline;

            var hSign = TEXTOFFSETSIGN[a];
            var vSign = TEXTOFFSETSIGN[b];
            var xPad = ms ? ms / 0.8 + 1 : 0;
            var yPad = -vSign * xPad - vSign * 0.5;
            out.offset[i] = [hSign * xPad / fs, yPad / fs];
        }
    }

    return out;
}

module.exports = {
    style: convertStyle,

    markerStyle: convertMarkerStyle,
    markerSelection: convertMarkerSelection,

    linePositions: convertLinePositions,
    errorBarPositions: convertErrorBarPositions,
    textPosition: convertTextPosition
};

},{"../../components/drawing":595,"../../constants/interactions":673,"../../lib":697,"../../lib/gl_format_color":694,"../../plots/cartesian/axis_ids":748,"../../registry":826,"../scatter/make_bubble_size_func":1065,"../scatter/subtypes":1072,"./constants":1098,"color-normalize":108,"fast-isnumeric":218,"svg-path-sdf":516}],1100:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Registry = _dereq_('../../registry');

var attributes = _dereq_('./attributes');
var constants = _dereq_('../scatter/constants');
var subTypes = _dereq_('../scatter/subtypes');
var handleXYDefaults = _dereq_('../scatter/xy_defaults');
var handleMarkerDefaults = _dereq_('../scatter/marker_defaults');
var handleLineDefaults = _dereq_('../scatter/line_defaults');
var handleFillColorDefaults = _dereq_('../scatter/fillcolor_defaults');
var handleTextDefaults = _dereq_('../scatter/text_defaults');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var isOpen = traceIn.marker ? /-open/.test(traceIn.marker.symbol) : false;
    var isBubble = subTypes.isBubble(traceIn);

    var len = handleXYDefaults(traceIn, traceOut, layout, coerce);
    if(!len) {
        traceOut.visible = false;
        return;
    }
    var defaultMode = len < constants.PTS_LINESONLY ? 'lines+markers' : 'lines';

    coerce('text');
    coerce('hovertext');
    coerce('hovertemplate');
    coerce('mode', defaultMode);

    if(subTypes.hasLines(traceOut)) {
        coerce('connectgaps');
        handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
        coerce('line.shape');
    }

    if(subTypes.hasMarkers(traceOut)) {
        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce);
        coerce('marker.line.width', isOpen || isBubble ? 1 : 0);
    }

    if(subTypes.hasText(traceOut)) {
        handleTextDefaults(traceIn, traceOut, layout, coerce);
    }

    var lineColor = (traceOut.line || {}).color;
    var markerColor = (traceOut.marker || {}).color;

    coerce('fill');
    if(traceOut.fill !== 'none') {
        handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
    }

    var errorBarsSupplyDefaults = Registry.getComponentMethod('errorbars', 'supplyDefaults');
    errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, {axis: 'y'});
    errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, {axis: 'x', inherit: 'y'});

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};

},{"../../lib":697,"../../registry":826,"../scatter/constants":1052,"../scatter/fillcolor_defaults":1057,"../scatter/line_defaults":1061,"../scatter/marker_defaults":1067,"../scatter/subtypes":1072,"../scatter/text_defaults":1073,"../scatter/xy_defaults":1074,"./attributes":1097}],1101:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var createScatter = _dereq_('regl-scatter2d');
var createLine = _dereq_('regl-line2d');
var createError = _dereq_('regl-error2d');
var cluster = _dereq_('point-cluster');
var arrayRange = _dereq_('array-range');
var Text = _dereq_('gl-text');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var prepareRegl = _dereq_('../../lib/prepare_regl');
var AxisIDs = _dereq_('../../plots/cartesian/axis_ids');
var findExtremes = _dereq_('../../plots/cartesian/autorange').findExtremes;
var Color = _dereq_('../../components/color');

var subTypes = _dereq_('../scatter/subtypes');
var scatterCalc = _dereq_('../scatter/calc');
var calcMarkerSize = scatterCalc.calcMarkerSize;
var calcAxisExpansion = scatterCalc.calcAxisExpansion;
var setFirstScatter = scatterCalc.setFirstScatter;
var calcColorscale = _dereq_('../scatter/colorscale_calc');
var linkTraces = _dereq_('../scatter/link_traces');
var getTraceColor = _dereq_('../scatter/get_trace_color');
var fillHoverText = _dereq_('../scatter/fill_hover_text');
var convert = _dereq_('./convert');

var BADNUM = _dereq_('../../constants/numerical').BADNUM;
var TOO_MANY_POINTS = _dereq_('./constants').TOO_MANY_POINTS;
var DESELECTDIM = _dereq_('../../constants/interactions').DESELECTDIM;

function calc(gd, trace) {
    var fullLayout = gd._fullLayout;
    var xa = AxisIDs.getFromId(gd, trace.xaxis);
    var ya = AxisIDs.getFromId(gd, trace.yaxis);
    var subplot = fullLayout._plots[trace.xaxis + trace.yaxis];
    var len = trace._length;
    var hasTooManyPoints = len >= TOO_MANY_POINTS;
    var len2 = len * 2;
    var stash = {};
    var i, xx, yy;

    var x = xa.makeCalcdata(trace, 'x');
    var y = ya.makeCalcdata(trace, 'y');

    // we need hi-precision for scatter2d,
    // regl-scatter2d uses NaNs for bad/missing values
    var positions = new Array(len2);
    for(i = 0; i < len; i++) {
        xx = x[i];
        yy = y[i];
        positions[i * 2] = xx === BADNUM ? NaN : xx;
        positions[i * 2 + 1] = yy === BADNUM ? NaN : yy;
    }

    if(xa.type === 'log') {
        for(i = 0; i < len2; i += 2) {
            positions[i] = xa.c2l(positions[i]);
        }
    }
    if(ya.type === 'log') {
        for(i = 1; i < len2; i += 2) {
            positions[i] = ya.c2l(positions[i]);
        }
    }

    // we don't build a tree for log axes since it takes long to convert log2px
    // and it is also
    if(hasTooManyPoints && (xa.type !== 'log' && ya.type !== 'log')) {
        // FIXME: delegate this to webworker
        stash.tree = cluster(positions);
    } else {
        var ids = stash.ids = new Array(len);
        for(i = 0; i < len; i++) {
            ids[i] = i;
        }
    }

    // create scene options and scene
    calcColorscale(gd, trace);
    var opts = sceneOptions(gd, subplot, trace, positions, x, y);
    var scene = sceneUpdate(gd, subplot);

    // Reuse SVG scatter axis expansion routine.
    // For graphs with very large number of points and array marker.size,
    // use average marker size instead to speed things up.
    setFirstScatter(fullLayout, trace);
    var ppad;
    if(!hasTooManyPoints) {
        ppad = calcMarkerSize(trace, len);
    } else if(opts.marker) {
        ppad = 2 * (opts.marker.sizeAvg || Math.max(opts.marker.size, 3));
    }
    calcAxisExpansion(gd, trace, xa, ya, x, y, ppad);
    if(opts.errorX) expandForErrorBars(trace, xa, opts.errorX);
    if(opts.errorY) expandForErrorBars(trace, ya, opts.errorY);

    // set flags to create scene renderers
    if(opts.fill && !scene.fill2d) scene.fill2d = true;
    if(opts.marker && !scene.scatter2d) scene.scatter2d = true;
    if(opts.line && !scene.line2d) scene.line2d = true;
    if((opts.errorX || opts.errorY) && !scene.error2d) scene.error2d = true;
    if(opts.text && !scene.glText) scene.glText = true;

    // FIXME: organize it in a more appropriate manner, probably in sceneOptions
    // put point-cluster instance for optimized regl calc
    if(opts.marker) {
        opts.marker.snap = stash.tree || TOO_MANY_POINTS;
    }

    // save scene opts batch
    scene.lineOptions.push(opts.line);
    scene.errorXOptions.push(opts.errorX);
    scene.errorYOptions.push(opts.errorY);
    scene.fillOptions.push(opts.fill);
    scene.markerOptions.push(opts.marker);
    scene.markerSelectedOptions.push(opts.markerSel);
    scene.markerUnselectedOptions.push(opts.markerUnsel);
    scene.textOptions.push(opts.text);
    scene.textSelectedOptions.push(opts.textSel);
    scene.textUnselectedOptions.push(opts.textUnsel);

    // stash scene ref
    stash._scene = scene;
    stash.index = scene.count;
    stash.x = x;
    stash.y = y;
    stash.positions = positions;
    scene.count++;

    return [{x: false, y: false, t: stash, trace: trace}];
}

function expandForErrorBars(trace, ax, opts) {
    var extremes = trace._extremes[ax._id];
    var errExt = findExtremes(ax, opts._bnds, {padded: true});
    extremes.min = extremes.min.concat(errExt.min);
    extremes.max = extremes.max.concat(errExt.max);
}

// create scene options
function sceneOptions(gd, subplot, trace, positions, x, y) {
    var opts = convert.style(gd, trace);

    if(opts.marker) {
        opts.marker.positions = positions;
    }

    if(opts.line && positions.length > 1) {
        Lib.extendFlat(
            opts.line,
            convert.linePositions(gd, trace, positions)
        );
    }

    if(opts.errorX || opts.errorY) {
        var errors = convert.errorBarPositions(gd, trace, positions, x, y);

        if(opts.errorX) {
            Lib.extendFlat(opts.errorX, errors.x);
        }
        if(opts.errorY) {
            Lib.extendFlat(opts.errorY, errors.y);
        }
    }

    if(opts.text) {
        Lib.extendFlat(
            opts.text,
            {positions: positions},
            convert.textPosition(gd, trace, opts.text, opts.marker)
        );
        Lib.extendFlat(
            opts.textSel,
            {positions: positions},
            convert.textPosition(gd, trace, opts.text, opts.markerSel)
        );
        Lib.extendFlat(
            opts.textUnsel,
            {positions: positions},
            convert.textPosition(gd, trace, opts.text, opts.markerUnsel)
        );
    }

    return opts;
}


// make sure scene exists on subplot, return it
function sceneUpdate(gd, subplot) {
    var scene = subplot._scene;

    var resetOpts = {
        // number of traces in subplot, since scene:subplot → 1:1
        count: 0,
        // whether scene requires init hook in plot call (dirty plot call)
        dirty: true,
        // last used options
        lineOptions: [],
        fillOptions: [],
        markerOptions: [],
        markerSelectedOptions: [],
        markerUnselectedOptions: [],
        errorXOptions: [],
        errorYOptions: [],
        textOptions: [],
        textSelectedOptions: [],
        textUnselectedOptions: []
    };

    var initOpts = {
        selectBatch: null,
        unselectBatch: null,
        // regl- component stubs, initialized in dirty plot call
        fill2d: false,
        scatter2d: false,
        error2d: false,
        line2d: false,
        glText: false,
        select2d: null
    };

    if(!subplot._scene) {
        scene = subplot._scene = {};

        scene.init = function init() {
            Lib.extendFlat(scene, initOpts, resetOpts);
        };

        scene.init();

        // apply new option to all regl components (used on drag)
        scene.update = function update(opt) {
            var opts = Lib.repeat(opt, scene.count);

            if(scene.fill2d) scene.fill2d.update(opts);
            if(scene.scatter2d) scene.scatter2d.update(opts);
            if(scene.line2d) scene.line2d.update(opts);
            if(scene.error2d) scene.error2d.update(opts.concat(opts));
            if(scene.select2d) scene.select2d.update(opts);
            if(scene.glText) {
                for(var i = 0; i < scene.count; i++) {
                    scene.glText[i].update(opt);
                }
            }
        };

        // draw traces in proper order
        scene.draw = function draw() {
            var count = scene.count;
            var fill2d = scene.fill2d;
            var error2d = scene.error2d;
            var line2d = scene.line2d;
            var scatter2d = scene.scatter2d;
            var glText = scene.glText;
            var select2d = scene.select2d;
            var selectBatch = scene.selectBatch;
            var unselectBatch = scene.unselectBatch;

            for(var i = 0; i < count; i++) {
                if(fill2d && scene.fillOrder[i]) {
                    fill2d.draw(scene.fillOrder[i]);
                }
                if(line2d && scene.lineOptions[i]) {
                    line2d.draw(i);
                }
                if(error2d) {
                    if(scene.errorXOptions[i]) error2d.draw(i);
                    if(scene.errorYOptions[i]) error2d.draw(i + count);
                }
                if(scatter2d && scene.markerOptions[i] && (!selectBatch || !selectBatch[i])) {
                    scatter2d.draw(i);
                }
                if(glText[i] && scene.textOptions[i]) {
                    glText[i].render();
                }
            }

            if(scatter2d && select2d && selectBatch) {
                select2d.draw(selectBatch);
                scatter2d.draw(unselectBatch);
            }

            scene.dirty = false;
        };

        // remove scene resources
        scene.destroy = function destroy() {
            if(scene.fill2d && scene.fill2d.destroy) scene.fill2d.destroy();
            if(scene.scatter2d && scene.scatter2d.destroy) scene.scatter2d.destroy();
            if(scene.error2d && scene.error2d.destroy) scene.error2d.destroy();
            if(scene.line2d && scene.line2d.destroy) scene.line2d.destroy();
            if(scene.select2d && scene.select2d.destroy) scene.select2d.destroy();
            if(scene.glText) {
                scene.glText.forEach(function(text) {
                    if(text.destroy) text.destroy();
                });
            }

            scene.lineOptions = null;
            scene.fillOptions = null;
            scene.markerOptions = null;
            scene.markerSelectedOptions = null;
            scene.markerUnselectedOptions = null;
            scene.errorXOptions = null;
            scene.errorYOptions = null;
            scene.textOptions = null;
            scene.textSelectedOptions = null;
            scene.textUnselectedOptions = null;

            scene.selectBatch = null;
            scene.unselectBatch = null;

            // we can't just delete _scene, because `destroy` is called in the
            // middle of supplyDefaults, before relinkPrivateKeys which will put it back.
            subplot._scene = null;
        };
    }

    // In case if we have scene from the last calc - reset data
    if(!scene.dirty) {
        Lib.extendFlat(scene, resetOpts);
    }

    return scene;
}

function getViewport(fullLayout, xaxis, yaxis) {
    var gs = fullLayout._size;
    var width = fullLayout.width;
    var height = fullLayout.height;
    return [
        gs.l + xaxis.domain[0] * gs.w,
        gs.b + yaxis.domain[0] * gs.h,
        (width - gs.r) - (1 - xaxis.domain[1]) * gs.w,
        (height - gs.t) - (1 - yaxis.domain[1]) * gs.h
    ];
}

function plot(gd, subplot, cdata) {
    if(!cdata.length) return;

    var fullLayout = gd._fullLayout;
    var scene = subplot._scene;
    var xaxis = subplot.xaxis;
    var yaxis = subplot.yaxis;
    var i, j;

    // we may have more subplots than initialized data due to Axes.getSubplots method
    if(!scene) return;

    var success = prepareRegl(gd, ['ANGLE_instanced_arrays', 'OES_element_index_uint']);
    if(!success) {
        scene.init();
        return;
    }

    var regl = fullLayout._glcanvas.data()[0].regl;

    // that is needed for fills
    linkTraces(gd, subplot, cdata);

    if(scene.dirty) {
        // make sure scenes are created
        if(scene.error2d === true) {
            scene.error2d = createError(regl);
        }
        if(scene.line2d === true) {
            scene.line2d = createLine(regl);
        }
        if(scene.scatter2d === true) {
            scene.scatter2d = createScatter(regl);
        }
        if(scene.fill2d === true) {
            scene.fill2d = createLine(regl);
        }
        if(scene.glText === true) {
            scene.glText = new Array(scene.count);
            for(i = 0; i < scene.count; i++) {
                scene.glText[i] = new Text(regl);
            }
        }

        // update main marker options
        if(scene.glText) {
            if(scene.count > scene.glText.length) {
                // add gl text marker
                var textsToAdd = scene.count - scene.glText.length;
                for(i = 0; i < textsToAdd; i++) {
                    scene.glText.push(new Text(regl));
                }
            } else if(scene.count < scene.glText.length) {
                // remove gl text marker
                var textsToRemove = scene.glText.length - scene.count;
                var removedTexts = scene.glText.splice(scene.count, textsToRemove);
                removedTexts.forEach(function(text) { text.destroy(); });
            }

            for(i = 0; i < scene.count; i++) {
                scene.glText[i].update(scene.textOptions[i]);
            }
        }
        if(scene.line2d) {
            scene.line2d.update(scene.lineOptions);
            scene.lineOptions = scene.lineOptions.map(function(lineOptions) {
                if(lineOptions && lineOptions.positions) {
                    var srcPos = lineOptions.positions;

                    var firstptdef = 0;
                    while(firstptdef < srcPos.length && (isNaN(srcPos[firstptdef]) || isNaN(srcPos[firstptdef + 1]))) {
                        firstptdef += 2;
                    }
                    var lastptdef = srcPos.length - 2;
                    while(lastptdef > firstptdef && (isNaN(srcPos[lastptdef]) || isNaN(srcPos[lastptdef + 1]))) {
                        lastptdef -= 2;
                    }
                    lineOptions.positions = srcPos.slice(firstptdef, lastptdef + 2);
                }
                return lineOptions;
            });
            scene.line2d.update(scene.lineOptions);
        }
        if(scene.error2d) {
            var errorBatch = (scene.errorXOptions || []).concat(scene.errorYOptions || []);
            scene.error2d.update(errorBatch);
        }
        if(scene.scatter2d) {
            scene.scatter2d.update(scene.markerOptions);
        }

        // fill requires linked traces, so we generate it's positions here
        scene.fillOrder = Lib.repeat(null, scene.count);
        if(scene.fill2d) {
            scene.fillOptions = scene.fillOptions.map(function(fillOptions, i) {
                var cdscatter = cdata[i];
                if(!fillOptions || !cdscatter || !cdscatter[0] || !cdscatter[0].trace) return;
                var cd = cdscatter[0];
                var trace = cd.trace;
                var stash = cd.t;
                var lineOptions = scene.lineOptions[i];
                var last, j;

                var fillData = [];
                if(trace._ownfill) fillData.push(i);
                if(trace._nexttrace) fillData.push(i + 1);
                if(fillData.length) scene.fillOrder[i] = fillData;

                var pos = [];
                var srcPos = (lineOptions && lineOptions.positions) || stash.positions;
                var firstptdef, lastptdef;

                if(trace.fill === 'tozeroy') {
                    firstptdef = 0;
                    while(firstptdef < srcPos.length && isNaN(srcPos[firstptdef + 1])) {
                        firstptdef += 2;
                    }
                    lastptdef = srcPos.length - 2;
                    while(lastptdef > firstptdef && isNaN(srcPos[lastptdef + 1])) {
                        lastptdef -= 2;
                    }
                    if(srcPos[firstptdef + 1] !== 0) {
                        pos = [srcPos[firstptdef], 0];
                    }
                    pos = pos.concat(srcPos.slice(firstptdef, lastptdef + 2));
                    if(srcPos[lastptdef + 1] !== 0) {
                        pos = pos.concat([srcPos[lastptdef], 0]);
                    }
                }
                else if(trace.fill === 'tozerox') {
                    firstptdef = 0;
                    while(firstptdef < srcPos.length && isNaN(srcPos[firstptdef])) {
                        firstptdef += 2;
                    }
                    lastptdef = srcPos.length - 2;
                    while(lastptdef > firstptdef && isNaN(srcPos[lastptdef])) {
                        lastptdef -= 2;
                    }
                    if(srcPos[firstptdef] !== 0) {
                        pos = [0, srcPos[firstptdef + 1]];
                    }
                    pos = pos.concat(srcPos.slice(firstptdef, lastptdef + 2));
                    if(srcPos[lastptdef] !== 0) {
                        pos = pos.concat([ 0, srcPos[lastptdef + 1]]);
                    }
                }
                else if(trace.fill === 'toself' || trace.fill === 'tonext') {
                    pos = [];
                    last = 0;
                    for(j = 0; j < srcPos.length; j += 2) {
                        if(isNaN(srcPos[j]) || isNaN(srcPos[j + 1])) {
                            pos = pos.concat(srcPos.slice(last, j));
                            pos.push(srcPos[last], srcPos[last + 1]);
                            last = j + 2;
                        }
                    }
                    pos = pos.concat(srcPos.slice(last));
                    if(last) {
                        pos.push(srcPos[last], srcPos[last + 1]);
                    }
                }
                else {
                    var nextTrace = trace._nexttrace;

                    if(nextTrace) {
                        var nextOptions = scene.lineOptions[i + 1];

                        if(nextOptions) {
                            var nextPos = nextOptions.positions;
                            if(trace.fill === 'tonexty') {
                                pos = srcPos.slice();

                                for(i = Math.floor(nextPos.length / 2); i--;) {
                                    var xx = nextPos[i * 2];
                                    var yy = nextPos[i * 2 + 1];
                                    if(isNaN(xx) || isNaN(yy)) continue;
                                    pos.push(xx, yy);
                                }
                                fillOptions.fill = nextTrace.fillcolor;
                            }
                        }
                    }
                }

                // detect prev trace positions to exclude from current fill
                if(trace._prevtrace && trace._prevtrace.fill === 'tonext') {
                    var prevLinePos = scene.lineOptions[i - 1].positions;

                    // FIXME: likely this logic should be tested better
                    var offset = pos.length / 2;
                    last = offset;
                    var hole = [last];
                    for(j = 0; j < prevLinePos.length; j += 2) {
                        if(isNaN(prevLinePos[j]) || isNaN(prevLinePos[j + 1])) {
                            hole.push(j / 2 + offset + 1);
                            last = j + 2;
                        }
                    }

                    pos = pos.concat(prevLinePos);
                    fillOptions.hole = hole;
                }
                fillOptions.fillmode = trace.fill;
                fillOptions.opacity = trace.opacity;
                fillOptions.positions = pos;

                return fillOptions;
            });

            scene.fill2d.update(scene.fillOptions);
        }
    }

    // form batch arrays, and check for selected points
    scene.selectBatch = null;
    scene.unselectBatch = null;
    var dragmode = fullLayout.dragmode;
    var selectMode = dragmode === 'lasso' || dragmode === 'select';
    var clickSelectEnabled = fullLayout.clickmode.indexOf('select') > -1;

    for(i = 0; i < cdata.length; i++) {
        var cd0 = cdata[i][0];
        var trace = cd0.trace;
        var stash = cd0.t;
        var index = stash.index;
        var len = trace._length;
        var x = stash.x;
        var y = stash.y;

        if(trace.selectedpoints || selectMode || clickSelectEnabled) {
            if(!selectMode) selectMode = true;

            if(!scene.selectBatch) {
                scene.selectBatch = [];
                scene.unselectBatch = [];
            }

            // regenerate scene batch, if traces number changed during selection
            if(trace.selectedpoints) {
                var selPts = scene.selectBatch[index] = Lib.selIndices2selPoints(trace);

                var selDict = {};
                for(j = 0; j < selPts.length; j++) {
                    selDict[selPts[j]] = 1;
                }
                var unselPts = [];
                for(j = 0; j < len; j++) {
                    if(!selDict[j]) unselPts.push(j);
                }
                scene.unselectBatch[index] = unselPts;
            }

            // precalculate px coords since we are not going to pan during select
            // TODO, could do better here e.g.
            // - spin that in a webworker
            // - compute selection from polygons in data coordinates
            //   (maybe just for linear axes)
            var xpx = stash.xpx = new Array(len);
            var ypx = stash.ypx = new Array(len);
            for(j = 0; j < len; j++) {
                xpx[j] = xaxis.c2p(x[j]);
                ypx[j] = yaxis.c2p(y[j]);
            }
        } else {
            stash.xpx = stash.ypx = null;
        }
    }


    if(selectMode) {
        // create select2d
        if(!scene.select2d) {
            // create scatter instance by cloning scatter2d
            scene.select2d = createScatter(fullLayout._glcanvas.data()[1].regl);
        }

        if(scene.scatter2d && scene.selectBatch && scene.selectBatch.length) {
            // update only traces with selection
            scene.scatter2d.update(scene.markerUnselectedOptions.map(function(opts, i) {
                return scene.selectBatch[i] ? opts : null;
            }));
        }

        if(scene.select2d) {
            scene.select2d.update(scene.markerOptions);
            scene.select2d.update(scene.markerSelectedOptions);
        }

        if(scene.glText) {
            cdata.forEach(function(cdscatter) {
                var trace = ((cdscatter || [])[0] || {}).trace || {};
                if(subTypes.hasText(trace)) {
                    styleTextSelection(cdscatter);
                }
            });
        }
    } else {
        if(scene.scatter2d) {
            // reset scatter2d opts to base opts,
            // thus unsetting markerUnselectedOptions from selection
            scene.scatter2d.update(scene.markerOptions);
        }
    }

    // provide viewport and range
    var vpRange0 = {
        viewport: getViewport(fullLayout, xaxis, yaxis),
        // TODO do we need those fallbacks?
        range: [
            (xaxis._rl || xaxis.range)[0],
            (yaxis._rl || yaxis.range)[0],
            (xaxis._rl || xaxis.range)[1],
            (yaxis._rl || yaxis.range)[1]
        ]
    };
    var vpRange = Lib.repeat(vpRange0, scene.count);

    // upload viewport/range data to GPU
    if(scene.fill2d) {
        scene.fill2d.update(vpRange);
    }
    if(scene.line2d) {
        scene.line2d.update(vpRange);
    }
    if(scene.error2d) {
        scene.error2d.update(vpRange.concat(vpRange));
    }
    if(scene.scatter2d) {
        scene.scatter2d.update(vpRange);
    }
    if(scene.select2d) {
        scene.select2d.update(vpRange);
    }
    if(scene.glText) {
        scene.glText.forEach(function(text) { text.update(vpRange0); });
    }
}


function hoverPoints(pointData, xval, yval, hovermode) {
    var cd = pointData.cd;
    var stash = cd[0].t;
    var trace = cd[0].trace;
    var xa = pointData.xa;
    var ya = pointData.ya;
    var x = stash.x;
    var y = stash.y;
    var xpx = xa.c2p(xval);
    var ypx = ya.c2p(yval);
    var maxDistance = pointData.distance;
    var ids;

    // FIXME: make sure this is a proper way to calc search radius
    if(stash.tree) {
        var xl = xa.p2c(xpx - maxDistance);
        var xr = xa.p2c(xpx + maxDistance);
        var yl = ya.p2c(ypx - maxDistance);
        var yr = ya.p2c(ypx + maxDistance);

        if(hovermode === 'x') {
            ids = stash.tree.range(
                Math.min(xl, xr), Math.min(ya._rl[0], ya._rl[1]),
                Math.max(xl, xr), Math.max(ya._rl[0], ya._rl[1])
            );
        }
        else {
            ids = stash.tree.range(
                Math.min(xl, xr), Math.min(yl, yr),
                Math.max(xl, xr), Math.max(yl, yr)
            );
        }
    }
    else if(stash.ids) {
        ids = stash.ids;
    }
    else return [pointData];

    // pick the id closest to the point
    // note that point possibly may not be found
    var id, ptx, pty, i, dx, dy, dist, dxy;

    var minDist = maxDistance;
    if(hovermode === 'x') {
        for(i = 0; i < ids.length; i++) {
            ptx = x[ids[i]];
            dx = Math.abs(xa.c2p(ptx) - xpx);
            if(dx < minDist) {
                minDist = dx;
                dy = ya.c2p(y[ids[i]]) - ypx;
                dxy = Math.sqrt(dx * dx + dy * dy);
                id = ids[i];
            }
        }
    }
    else {
        for(i = 0; i < ids.length; i++) {
            ptx = x[ids[i]];
            pty = y[ids[i]];
            dx = xa.c2p(ptx) - xpx;
            dy = ya.c2p(pty) - ypx;

            dist = Math.sqrt(dx * dx + dy * dy);
            if(dist < minDist) {
                minDist = dxy = dist;
                id = ids[i];
            }
        }
    }

    pointData.index = id;
    pointData.distance = minDist;
    pointData.dxy = dxy;

    if(id === undefined) return [pointData];

    calcHover(pointData, x, y, trace);

    return [pointData];
}


function calcHover(pointData, x, y, trace) {
    var xa = pointData.xa;
    var ya = pointData.ya;
    var minDist = pointData.distance;
    var dxy = pointData.dxy;
    var id = pointData.index;

    // the closest data point
    var di = {
        pointNumber: id,
        x: x[id],
        y: y[id]
    };

    // that is single-item arrays_to_calcdata excerpt, since we are doing it for a single point and we don't have to do it beforehead for 1e6 points
    di.tx = Array.isArray(trace.text) ? trace.text[id] : trace.text;
    di.htx = Array.isArray(trace.hovertext) ? trace.hovertext[id] : trace.hovertext;
    di.data = Array.isArray(trace.customdata) ? trace.customdata[id] : trace.customdata;
    di.tp = Array.isArray(trace.textposition) ? trace.textposition[id] : trace.textposition;

    var font = trace.textfont;
    if(font) {
        di.ts = Array.isArray(font.size) ? font.size[id] : font.size;
        di.tc = Array.isArray(font.color) ? font.color[id] : font.color;
        di.tf = Array.isArray(font.family) ? font.family[id] : font.family;
    }

    var marker = trace.marker;
    if(marker) {
        di.ms = Lib.isArrayOrTypedArray(marker.size) ? marker.size[id] : marker.size;
        di.mo = Lib.isArrayOrTypedArray(marker.opacity) ? marker.opacity[id] : marker.opacity;
        di.mx = Array.isArray(marker.symbol) ? marker.symbol[id] : marker.symbol;
        di.mc = Lib.isArrayOrTypedArray(marker.color) ? marker.color[id] : marker.color;
    }

    var line = marker && marker.line;
    if(line) {
        di.mlc = Array.isArray(line.color) ? line.color[id] : line.color;
        di.mlw = Lib.isArrayOrTypedArray(line.width) ? line.width[id] : line.width;
    }

    var grad = marker && marker.gradient;
    if(grad && grad.type !== 'none') {
        di.mgt = Array.isArray(grad.type) ? grad.type[id] : grad.type;
        di.mgc = Array.isArray(grad.color) ? grad.color[id] : grad.color;
    }

    var xp = xa.c2p(di.x, true);
    var yp = ya.c2p(di.y, true);
    var rad = di.mrc || 1;

    var hoverlabel = trace.hoverlabel;

    if(hoverlabel) {
        di.hbg = Array.isArray(hoverlabel.bgcolor) ? hoverlabel.bgcolor[id] : hoverlabel.bgcolor;
        di.hbc = Array.isArray(hoverlabel.bordercolor) ? hoverlabel.bordercolor[id] : hoverlabel.bordercolor;
        di.hts = Array.isArray(hoverlabel.font.size) ? hoverlabel.font.size[id] : hoverlabel.font.size;
        di.htc = Array.isArray(hoverlabel.font.color) ? hoverlabel.font.color[id] : hoverlabel.font.color;
        di.htf = Array.isArray(hoverlabel.font.family) ? hoverlabel.font.family[id] : hoverlabel.font.family;
        di.hnl = Array.isArray(hoverlabel.namelength) ? hoverlabel.namelength[id] : hoverlabel.namelength;
    }
    var hoverinfo = trace.hoverinfo;
    if(hoverinfo) {
        di.hi = Array.isArray(hoverinfo) ? hoverinfo[id] : hoverinfo;
    }

    var hovertemplate = trace.hovertemplate;
    if(hovertemplate) {
        di.ht = Array.isArray(hovertemplate) ? hovertemplate[id] : hovertemplate;
    }

    var fakeCd = {};
    fakeCd[pointData.index] = di;

    Lib.extendFlat(pointData, {
        color: getTraceColor(trace, di),

        x0: xp - rad,
        x1: xp + rad,
        xLabelVal: di.x,

        y0: yp - rad,
        y1: yp + rad,
        yLabelVal: di.y,

        cd: fakeCd,
        distance: minDist,
        spikeDistance: dxy,

        hovertemplate: di.ht
    });

    if(di.htx) pointData.text = di.htx;
    else if(di.tx) pointData.text = di.tx;
    else if(trace.text) pointData.text = trace.text;

    fillHoverText(di, trace, pointData);
    Registry.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData);

    return pointData;
}


function selectPoints(searchInfo, selectionTester) {
    var cd = searchInfo.cd;
    var selection = [];
    var trace = cd[0].trace;
    var stash = cd[0].t;
    var len = trace._length;
    var x = stash.x;
    var y = stash.y;
    var scene = stash._scene;

    if(!scene) return selection;

    var hasText = subTypes.hasText(trace);
    var hasMarkers = subTypes.hasMarkers(trace);
    var hasOnlyLines = !hasMarkers && !hasText;
    if(trace.visible !== true || hasOnlyLines) return selection;

    // degenerate polygon does not enable selection
    // filter out points by visible scatter ones
    var els = null;
    var unels = null;
    // FIXME: clearing selection does not work here
    var i;
    if(selectionTester !== false && !selectionTester.degenerate) {
        els = [], unels = [];
        for(i = 0; i < len; i++) {
            if(selectionTester.contains([stash.xpx[i], stash.ypx[i]], false, i, searchInfo)) {
                els.push(i);
                selection.push({
                    pointNumber: i,
                    x: x[i],
                    y: y[i]
                });
            }
            else {
                unels.push(i);
            }
        }
    } else {
        unels = arrayRange(len);
    }

    // make sure selectBatch is created
    if(!scene.selectBatch) {
        scene.selectBatch = [];
        scene.unselectBatch = [];
    }

    if(!scene.selectBatch[stash.index]) {
        // enter every trace select mode
        for(i = 0; i < scene.count; i++) {
            scene.selectBatch[i] = [];
            scene.unselectBatch[i] = [];
        }
        // we should turn scatter2d into unselected once we have any points selected
        if(hasMarkers) {
            scene.scatter2d.update(scene.markerUnselectedOptions);
        }
    }

    scene.selectBatch[stash.index] = els;
    scene.unselectBatch[stash.index] = unels;

    // update text options
    if(hasText) {
        styleTextSelection(cd);
    }

    return selection;
}

function styleTextSelection(cd) {
    var cd0 = cd[0];
    var trace = cd0.trace;
    var stash = cd0.t;
    var scene = stash._scene;
    var index = stash.index;
    var els = scene.selectBatch[index];
    var unels = scene.unselectBatch[index];
    var baseOpts = scene.textOptions[index];
    var selOpts = scene.textSelectedOptions[index] || {};
    var unselOpts = scene.textUnselectedOptions[index] || {};
    var opts = Lib.extendFlat({}, baseOpts);
    var i, j;

    if(els && unels) {
        var stc = selOpts.color;
        var utc = unselOpts.color;
        var base = baseOpts.color;
        var hasArrayBase = Array.isArray(base);
        opts.color = new Array(trace._length);

        for(i = 0; i < els.length; i++) {
            j = els[i];
            opts.color[j] = stc || (hasArrayBase ? base[j] : base);
        }
        for(i = 0; i < unels.length; i++) {
            j = unels[i];
            var basej = hasArrayBase ? base[j] : base;
            opts.color[j] = utc ? utc :
                stc ? basej : Color.addOpacity(basej, DESELECTDIM);
        }
    }

    scene.glText[index].update(opts);
}

module.exports = {
    moduleType: 'trace',
    name: 'scattergl',
    basePlotModule: _dereq_('../../plots/cartesian'),
    categories: ['gl', 'regl', 'cartesian', 'symbols', 'errorBarsOK', 'showLegend', 'scatter-like'],

    attributes: _dereq_('./attributes'),
    supplyDefaults: _dereq_('./defaults'),
    crossTraceDefaults: _dereq_('../scatter/cross_trace_defaults'),
    colorbar: _dereq_('../scatter/marker_colorbar'),
    calc: calc,
    plot: plot,
    hoverPoints: hoverPoints,
    selectPoints: selectPoints,

    sceneUpdate: sceneUpdate,
    calcHover: calcHover,

    meta: {
        
        
    }
};

},{"../../components/color":574,"../../constants/interactions":673,"../../constants/numerical":674,"../../lib":697,"../../lib/prepare_regl":710,"../../plots/cartesian":756,"../../plots/cartesian/autorange":744,"../../plots/cartesian/axis_ids":748,"../../registry":826,"../scatter/calc":1049,"../scatter/colorscale_calc":1051,"../scatter/cross_trace_defaults":1054,"../scatter/fill_hover_text":1056,"../scatter/get_trace_color":1058,"../scatter/link_traces":1064,"../scatter/marker_colorbar":1066,"../scatter/subtypes":1072,"./attributes":1097,"./constants":1098,"./convert":1099,"./defaults":1100,"array-range":55,"gl-text":310,"point-cluster":458,"regl-error2d":479,"regl-line2d":480,"regl-scatter2d":481}],1102:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var scatterGeoAttrs = _dereq_('../scattergeo/attributes');
var scatterAttrs = _dereq_('../scatter/attributes');
var mapboxAttrs = _dereq_('../../plots/mapbox/layout_attributes');
var plotAttrs = _dereq_('../../plots/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;

var lineAttrs = scatterGeoAttrs.line;
var markerAttrs = scatterGeoAttrs.marker;

module.exports = overrideAll({
    lon: scatterGeoAttrs.lon,
    lat: scatterGeoAttrs.lat,

    // locations
    // locationmode

    mode: extendFlat({}, scatterAttrs.mode, {
        dflt: 'markers',
        
    }),

    text: extendFlat({}, scatterAttrs.text, {
        
    }),
    hovertext: extendFlat({}, scatterAttrs.hovertext, {
        
    }),

    line: {
        color: lineAttrs.color,
        width: lineAttrs.width

        // TODO
        // dash: dash
    },

    connectgaps: scatterAttrs.connectgaps,

    marker: {
        symbol: {
            valType: 'string',
            dflt: 'circle',
            
            arrayOk: true,
            
        },
        opacity: markerAttrs.opacity,
        size: markerAttrs.size,
        sizeref: markerAttrs.sizeref,
        sizemin: markerAttrs.sizemin,
        sizemode: markerAttrs.sizemode,
        color: markerAttrs.color,
        colorscale: markerAttrs.colorscale,
        cauto: markerAttrs.cauto,
        cmax: markerAttrs.cmax,
        cmin: markerAttrs.cmin,
        cmid: markerAttrs.cmid,
        autocolorscale: markerAttrs.autocolorscale,
        reversescale: markerAttrs.reversescale,
        showscale: markerAttrs.showscale,
        colorbar: colorbarAttrs,

        // line
    },

    fill: scatterGeoAttrs.fill,
    fillcolor: scatterAttrs.fillcolor,

    textfont: mapboxAttrs.layers.symbol.textfont,
    textposition: mapboxAttrs.layers.symbol.textposition,

    selected: {
        marker: scatterAttrs.selected.marker
    },
    unselected: {
        marker: scatterAttrs.unselected.marker
    },

    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
        flags: ['lon', 'lat', 'text', 'name']
    }),
    hovertemplate: hovertemplateAttrs(),
}, 'calc', 'nested');

},{"../../components/colorbar/attributes":575,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plot_api/edit_types":728,"../../plots/attributes":742,"../../plots/mapbox/layout_attributes":803,"../scatter/attributes":1048,"../scattergeo/attributes":1088}],1103:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;
var geoJsonUtils = _dereq_('../../lib/geojson_utils');

var Colorscale = _dereq_('../../components/colorscale');
var Drawing = _dereq_('../../components/drawing');
var makeBubbleSizeFn = _dereq_('../scatter/make_bubble_size_func');
var subTypes = _dereq_('../scatter/subtypes');
var convertTextOpts = _dereq_('../../plots/mapbox/convert_text_opts');

module.exports = function convert(calcTrace) {
    var trace = calcTrace[0].trace;

    var isVisible = (trace.visible === true);
    var hasFill = (trace.fill !== 'none');
    var hasLines = subTypes.hasLines(trace);
    var hasMarkers = subTypes.hasMarkers(trace);
    var hasText = subTypes.hasText(trace);
    var hasCircles = (hasMarkers && trace.marker.symbol === 'circle');
    var hasSymbols = (hasMarkers && trace.marker.symbol !== 'circle');

    var fill = initContainer();
    var line = initContainer();
    var circle = initContainer();
    var symbol = initContainer();

    var opts = {
        fill: fill,
        line: line,
        circle: circle,
        symbol: symbol
    };

    // early return if not visible or placeholder
    if(!isVisible) return opts;

    // fill layer and line layer use the same coords
    var lineCoords;
    if(hasFill || hasLines) {
        lineCoords = geoJsonUtils.calcTraceToLineCoords(calcTrace);
    }

    if(hasFill) {
        fill.geojson = geoJsonUtils.makePolygon(lineCoords);
        fill.layout.visibility = 'visible';

        Lib.extendFlat(fill.paint, {
            'fill-color': trace.fillcolor
        });
    }

    if(hasLines) {
        line.geojson = geoJsonUtils.makeLine(lineCoords);
        line.layout.visibility = 'visible';

        Lib.extendFlat(line.paint, {
            'line-width': trace.line.width,
            'line-color': trace.line.color,
            'line-opacity': trace.opacity
        });

        // TODO convert line.dash into line-dasharray
    }

    if(hasCircles) {
        var circleOpts = makeCircleOpts(calcTrace);
        circle.geojson = circleOpts.geojson;
        circle.layout.visibility = 'visible';

        Lib.extendFlat(circle.paint, {
            'circle-color': circleOpts.mcc,
            'circle-radius': circleOpts.mrc,
            'circle-opacity': circleOpts.mo
        });
    }

    if(hasSymbols || hasText) {
        symbol.geojson = makeSymbolGeoJSON(calcTrace);

        Lib.extendFlat(symbol.layout, {
            visibility: 'visible',
            'icon-image': '{symbol}-15',
            'text-field': '{text}'
        });

        if(hasSymbols) {
            Lib.extendFlat(symbol.layout, {
                'icon-size': trace.marker.size / 10
            });

            Lib.extendFlat(symbol.paint, {
                'icon-opacity': trace.opacity * trace.marker.opacity,

                // TODO does not work ??
                'icon-color': trace.marker.color
            });
        }

        if(hasText) {
            var iconSize = (trace.marker || {}).size;
            var textOpts = convertTextOpts(trace.textposition, iconSize);

            // all data-driven below !!

            Lib.extendFlat(symbol.layout, {
                'text-size': trace.textfont.size,
                'text-anchor': textOpts.anchor,
                'text-offset': textOpts.offset

                // TODO font family
                // 'text-font': symbol.textfont.family.split(', '),
            });

            Lib.extendFlat(symbol.paint, {
                'text-color': trace.textfont.color,
                'text-opacity': trace.opacity
            });
        }
    }

    return opts;
};

function initContainer() {
    return {
        geojson: geoJsonUtils.makeBlank(),
        layout: { visibility: 'none' },
        paint: {}
    };
}

function makeCircleOpts(calcTrace) {
    var trace = calcTrace[0].trace;
    var marker = trace.marker;
    var selectedpoints = trace.selectedpoints;
    var arrayColor = Lib.isArrayOrTypedArray(marker.color);
    var arraySize = Lib.isArrayOrTypedArray(marker.size);
    var arrayOpacity = Lib.isArrayOrTypedArray(marker.opacity);
    var i;

    function addTraceOpacity(o) { return trace.opacity * o; }

    function size2radius(s) { return s / 2; }

    var colorFn;
    if(arrayColor) {
        if(Colorscale.hasColorscale(trace, 'marker')) {
            colorFn = Colorscale.makeColorScaleFunc(
                 Colorscale.extractScale(marker, {cLetter: 'c'})
             );
        } else {
            colorFn = Lib.identity;
        }
    }

    var sizeFn;
    if(arraySize) {
        sizeFn = makeBubbleSizeFn(trace);
    }

    var opacityFn;
    if(arrayOpacity) {
        opacityFn = function(mo) {
            var mo2 = isNumeric(mo) ? +Lib.constrain(mo, 0, 1) : 0;
            return addTraceOpacity(mo2);
        };
    }

    var features = [];
    for(i = 0; i < calcTrace.length; i++) {
        var calcPt = calcTrace[i];
        var lonlat = calcPt.lonlat;

        if(isBADNUM(lonlat)) continue;

        var props = {};
        if(colorFn) props.mcc = calcPt.mcc = colorFn(calcPt.mc);
        if(sizeFn) props.mrc = calcPt.mrc = sizeFn(calcPt.ms);
        if(opacityFn) props.mo = opacityFn(calcPt.mo);
        if(selectedpoints) props.selected = calcPt.selected || 0;

        features.push({
            type: 'Feature',
            geometry: {type: 'Point', coordinates: lonlat},
            properties: props
        });
    }

    var fns;
    if(selectedpoints) {
        fns = Drawing.makeSelectedPointStyleFns(trace);

        for(i = 0; i < features.length; i++) {
            var d = features[i].properties;

            if(fns.selectedOpacityFn) {
                d.mo = addTraceOpacity(fns.selectedOpacityFn(d));
            }
            if(fns.selectedColorFn) {
                d.mcc = fns.selectedColorFn(d);
            }
            if(fns.selectedSizeFn) {
                d.mrc = fns.selectedSizeFn(d);
            }
        }
    }

    return {
        geojson: {type: 'FeatureCollection', features: features},
        mcc: arrayColor || (fns && fns.selectedColorFn) ?
            {type: 'identity', property: 'mcc'} :
            marker.color,
        mrc: arraySize || (fns && fns.selectedSizeFn) ?
            {type: 'identity', property: 'mrc'} :
            size2radius(marker.size),
        mo: arrayOpacity || (fns && fns.selectedOpacityFn) ?
            {type: 'identity', property: 'mo'} :
            addTraceOpacity(marker.opacity)
    };
}

function makeSymbolGeoJSON(calcTrace) {
    var trace = calcTrace[0].trace;

    var marker = trace.marker || {};
    var symbol = marker.symbol;
    var text = trace.text;

    var fillSymbol = (symbol !== 'circle') ?
        getFillFunc(symbol) :
        blankFillFunc;

    var fillText = subTypes.hasText(trace) ?
        getFillFunc(text) :
        blankFillFunc;

    var features = [];

    for(var i = 0; i < calcTrace.length; i++) {
        var calcPt = calcTrace[i];

        if(isBADNUM(calcPt.lonlat)) continue;

        features.push({
            type: 'Feature',
            geometry: {
                type: 'Point',
                coordinates: calcPt.lonlat
            },
            properties: {
                symbol: fillSymbol(calcPt.mx),
                text: fillText(calcPt.tx)
            }
        });
    }

    return {
        type: 'FeatureCollection',
        features: features
    };
}

function getFillFunc(attr) {
    if(Lib.isArrayOrTypedArray(attr)) {
        return function(v) { return v; };
    }
    else if(attr) {
        return function() { return attr; };
    }
    else {
        return blankFillFunc;
    }
}

function blankFillFunc() { return ''; }

// only need to check lon (OR lat)
function isBADNUM(lonlat) {
    return lonlat[0] === BADNUM;
}

},{"../../components/colorscale":586,"../../components/drawing":595,"../../constants/numerical":674,"../../lib":697,"../../lib/geojson_utils":691,"../../plots/mapbox/convert_text_opts":800,"../scatter/make_bubble_size_func":1065,"../scatter/subtypes":1072,"fast-isnumeric":218}],1104:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

var subTypes = _dereq_('../scatter/subtypes');
var handleMarkerDefaults = _dereq_('../scatter/marker_defaults');
var handleLineDefaults = _dereq_('../scatter/line_defaults');
var handleTextDefaults = _dereq_('../scatter/text_defaults');
var handleFillColorDefaults = _dereq_('../scatter/fillcolor_defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var len = handleLonLatDefaults(traceIn, traceOut, coerce);
    if(!len) {
        traceOut.visible = false;
        return;
    }

    coerce('text');
    coerce('hovertext');
    coerce('hovertemplate');
    coerce('mode');

    if(subTypes.hasLines(traceOut)) {
        handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce, {noDash: true});
        coerce('connectgaps');
    }

    if(subTypes.hasMarkers(traceOut)) {
        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {noLine: true});

        // array marker.size and marker.color are only supported with circles
        var marker = traceOut.marker;
        if(marker.symbol !== 'circle') {
            if(Lib.isArrayOrTypedArray(marker.size)) marker.size = marker.size[0];
            if(Lib.isArrayOrTypedArray(marker.color)) marker.color = marker.color[0];
        }
    }

    if(subTypes.hasText(traceOut)) {
        handleTextDefaults(traceIn, traceOut, layout, coerce, {noSelect: true});
    }

    coerce('fill');
    if(traceOut.fill !== 'none') {
        handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
    }

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};

function handleLonLatDefaults(traceIn, traceOut, coerce) {
    var lon = coerce('lon') || [];
    var lat = coerce('lat') || [];
    var len = Math.min(lon.length, lat.length);
    traceOut._length = len;

    return len;
}

},{"../../lib":697,"../scatter/fillcolor_defaults":1057,"../scatter/line_defaults":1061,"../scatter/marker_defaults":1067,"../scatter/subtypes":1072,"../scatter/text_defaults":1073,"./attributes":1102}],1105:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


module.exports = function eventData(out, pt) {
    out.lon = pt.lon;
    out.lat = pt.lat;

    return out;
};

},{}],1106:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Fx = _dereq_('../../components/fx');
var Lib = _dereq_('../../lib');
var getTraceColor = _dereq_('../scatter/get_trace_color');
var fillHoverText = _dereq_('../scatter/fill_hover_text');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

module.exports = function hoverPoints(pointData, xval, yval) {
    var cd = pointData.cd;
    var trace = cd[0].trace;
    var xa = pointData.xa;
    var ya = pointData.ya;
    var subplot = pointData.subplot;

    // compute winding number about [-180, 180] globe
    var winding = (xval >= 0) ?
        Math.floor((xval + 180) / 360) :
        Math.ceil((xval - 180) / 360);

    // shift longitude to [-180, 180] to determine closest point
    var lonShift = winding * 360;
    var xval2 = xval - lonShift;

    function distFn(d) {
        var lonlat = d.lonlat;
        if(lonlat[0] === BADNUM) return Infinity;

        var lon = Lib.modHalf(lonlat[0], 360);
        var lat = lonlat[1];
        var pt = subplot.project([lon, lat]);
        var dx = pt.x - xa.c2p([xval2, lat]);
        var dy = pt.y - ya.c2p([lon, yval]);
        var rad = Math.max(3, d.mrc || 0);

        return Math.max(Math.sqrt(dx * dx + dy * dy) - rad, 1 - 3 / rad);
    }

    Fx.getClosest(cd, distFn, pointData);

    // skip the rest (for this trace) if we didn't find a close point
    if(pointData.index === false) return;

    var di = cd[pointData.index];
    var lonlat = di.lonlat;
    var lonlatShifted = [Lib.modHalf(lonlat[0], 360) + lonShift, lonlat[1]];

    // shift labels back to original winded globe
    var xc = xa.c2p(lonlatShifted);
    var yc = ya.c2p(lonlatShifted);
    var rad = di.mrc || 1;

    pointData.x0 = xc - rad;
    pointData.x1 = xc + rad;
    pointData.y0 = yc - rad;
    pointData.y1 = yc + rad;

    pointData.color = getTraceColor(trace, di);
    pointData.extraText = getExtraText(trace, di, cd[0].t.labels);
    pointData.hovertemplate = trace.hovertemplate;

    return [pointData];
};

function getExtraText(trace, di, labels) {
    if(trace.hovertemplate) {
        return;
    }

    var hoverinfo = di.hi || trace.hoverinfo;
    var parts = hoverinfo.split('+');
    var isAll = parts.indexOf('all') !== -1;
    var hasLon = parts.indexOf('lon') !== -1;
    var hasLat = parts.indexOf('lat') !== -1;
    var lonlat = di.lonlat;
    var text = [];

    // TODO should we use a mock axis to format hover?
    // If so, we'll need to make precision be zoom-level dependent
    function format(v) {
        return v + '\u00B0';
    }

    if(isAll || (hasLon && hasLat)) {
        text.push('(' + format(lonlat[0]) + ', ' + format(lonlat[1]) + ')');
    } else if(hasLon) {
        text.push(labels.lon + format(lonlat[0]));
    } else if(hasLat) {
        text.push(labels.lat + format(lonlat[1]));
    }

    if(isAll || parts.indexOf('text') !== -1) {
        fillHoverText(di, trace, text);
    }

    return text.join('<br>');
}

},{"../../components/fx":613,"../../constants/numerical":674,"../../lib":697,"../scatter/fill_hover_text":1056,"../scatter/get_trace_color":1058}],1107:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


var ScatterMapbox = {};

ScatterMapbox.attributes = _dereq_('./attributes');
ScatterMapbox.supplyDefaults = _dereq_('./defaults');
ScatterMapbox.colorbar = _dereq_('../scatter/marker_colorbar');
ScatterMapbox.calc = _dereq_('../scattergeo/calc');
ScatterMapbox.plot = _dereq_('./plot');
ScatterMapbox.hoverPoints = _dereq_('./hover');
ScatterMapbox.eventData = _dereq_('./event_data');
ScatterMapbox.selectPoints = _dereq_('./select');

ScatterMapbox.style = function(_, cd) {
    if(cd) {
        var trace = cd[0].trace;
        trace._glTrace.update(cd);
    }
};

ScatterMapbox.moduleType = 'trace';
ScatterMapbox.name = 'scattermapbox';
ScatterMapbox.basePlotModule = _dereq_('../../plots/mapbox');
ScatterMapbox.categories = ['mapbox', 'gl', 'symbols', 'showLegend', 'scatterlike'];
ScatterMapbox.meta = {
    
    
};

module.exports = ScatterMapbox;

},{"../../plots/mapbox":801,"../scatter/marker_colorbar":1066,"../scattergeo/calc":1089,"./attributes":1102,"./defaults":1104,"./event_data":1105,"./hover":1106,"./plot":1108,"./select":1109}],1108:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var convert = _dereq_('./convert');

function ScatterMapbox(subplot, uid) {
    this.subplot = subplot;
    this.uid = uid;

    this.sourceIds = {
        fill: uid + '-source-fill',
        line: uid + '-source-line',
        circle: uid + '-source-circle',
        symbol: uid + '-source-symbol'
    };

    this.layerIds = {
        fill: uid + '-layer-fill',
        line: uid + '-layer-line',
        circle: uid + '-layer-circle',
        symbol: uid + '-layer-symbol'
    };

    this.order = ['fill', 'line', 'circle', 'symbol'];

    // We could merge the 'fill' source with the 'line' source and
    // the 'circle' source with the 'symbol' source if ever having
    // for up-to 4 sources per 'scattermapbox' traces becomes a problem.
}

var proto = ScatterMapbox.prototype;

proto.addSource = function(k, opts) {
    this.subplot.map.addSource(this.sourceIds[k], {
        type: 'geojson',
        data: opts.geojson
    });
};

proto.setSourceData = function(k, opts) {
    this.subplot.map
        .getSource(this.sourceIds[k])
        .setData(opts.geojson);
};

proto.addLayer = function(k, opts) {
    this.subplot.map.addLayer({
        type: k,
        id: this.layerIds[k],
        source: this.sourceIds[k],
        layout: opts.layout,
        paint: opts.paint
    });
};

proto.update = function update(calcTrace) {
    var subplot = this.subplot;
    var optsAll = convert(calcTrace);

    for(var i = 0; i < this.order.length; i++) {
        var k = this.order[i];
        var opts = optsAll[k];

        subplot.setOptions(this.layerIds[k], 'setLayoutProperty', opts.layout);

        if(opts.layout.visibility === 'visible') {
            this.setSourceData(k, opts);
            subplot.setOptions(this.layerIds[k], 'setPaintProperty', opts.paint);
        }
    }

    // link ref for quick update during selections
    calcTrace[0].trace._glTrace = this;
};

proto.dispose = function dispose() {
    var map = this.subplot.map;

    for(var i = 0; i < this.order.length; i++) {
        var k = this.order[i];
        map.removeLayer(this.layerIds[k]);
        map.removeSource(this.sourceIds[k]);
    }
};

module.exports = function createScatterMapbox(subplot, calcTrace) {
    var trace = calcTrace[0].trace;
    var scatterMapbox = new ScatterMapbox(subplot, trace.uid);
    var optsAll = convert(calcTrace);

    for(var i = 0; i < scatterMapbox.order.length; i++) {
        var k = scatterMapbox.order[i];
        var opts = optsAll[k];

        scatterMapbox.addSource(k, opts);
        scatterMapbox.addLayer(k, opts);
    }

    // link ref for quick update during selections
    calcTrace[0].trace._glTrace = scatterMapbox;

    return scatterMapbox;
};

},{"./convert":1103}],1109:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var subtypes = _dereq_('../scatter/subtypes');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

module.exports = function selectPoints(searchInfo, selectionTester) {
    var cd = searchInfo.cd;
    var xa = searchInfo.xaxis;
    var ya = searchInfo.yaxis;
    var selection = [];
    var trace = cd[0].trace;
    var i;

    if(!subtypes.hasMarkers(trace)) return [];

    if(selectionTester === false) {
        for(i = 0; i < cd.length; i++) {
            cd[i].selected = 0;
        }
    } else {
        for(i = 0; i < cd.length; i++) {
            var di = cd[i];
            var lonlat = di.lonlat;

            if(lonlat[0] !== BADNUM) {
                var lonlat2 = [Lib.modHalf(lonlat[0], 360), lonlat[1]];
                var xy = [xa.c2p(lonlat2), ya.c2p(lonlat2)];

                if(selectionTester.contains(xy, null, i, searchInfo)) {
                    selection.push({
                        pointNumber: i,
                        lon: lonlat[0],
                        lat: lonlat[1]
                    });
                    di.selected = 1;
                } else {
                    di.selected = 0;
                }
            }
        }
    }

    return selection;
};

},{"../../constants/numerical":674,"../../lib":697,"../scatter/subtypes":1072}],1110:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var extendFlat = _dereq_('../../lib/extend').extendFlat;
var scatterAttrs = _dereq_('../scatter/attributes');
var plotAttrs = _dereq_('../../plots/attributes');
var lineAttrs = scatterAttrs.line;

module.exports = {
    mode: scatterAttrs.mode,

    r: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },

    theta: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },

    r0: {
        valType: 'any',
        dflt: 0,
        
        editType: 'calc+clearAxisTypes',
        
    },
    dr: {
        valType: 'number',
        dflt: 1,
        
        editType: 'calc',
        
    },

    theta0: {
        valType: 'any',
        dflt: 0,
        
        editType: 'calc+clearAxisTypes',
        
    },
    dtheta: {
        valType: 'number',
        
        editType: 'calc',
        
    },

    thetaunit: {
        valType: 'enumerated',
        values: ['radians', 'degrees', 'gradians'],
        dflt: 'degrees',
        
        editType: 'calc+clearAxisTypes',
        
    },

    text: scatterAttrs.text,
    hovertext: scatterAttrs.hovertext,

    line: {
        color: lineAttrs.color,
        width: lineAttrs.width,
        dash: lineAttrs.dash,
        shape: extendFlat({}, lineAttrs.shape, {
            values: ['linear', 'spline']
        }),
        smoothing: lineAttrs.smoothing,
        editType: 'calc'
    },
    connectgaps: scatterAttrs.connectgaps,

    marker: scatterAttrs.marker,
    cliponaxis: extendFlat({}, scatterAttrs.cliponaxis, {dflt: false}),

    textposition: scatterAttrs.textposition,
    textfont: scatterAttrs.textfont,

    fill: extendFlat({}, scatterAttrs.fill, {
        values: ['none', 'toself', 'tonext'],
        dflt: 'none',
        
    }),
    fillcolor: scatterAttrs.fillcolor,

    // TODO error bars
    // https://stackoverflow.com/a/26597487/4068492
    // error_x (error_r, error_theta)
    // error_y

    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
        flags: ['r', 'theta', 'text', 'name']
    }),
    hoveron: scatterAttrs.hoveron,
    hovertemplate: hovertemplateAttrs(),

    selected: scatterAttrs.selected,
    unselected: scatterAttrs.unselected
};

},{"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plots/attributes":742,"../scatter/attributes":1048}],1111:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

var Axes = _dereq_('../../plots/cartesian/axes');

var calcColorscale = _dereq_('../scatter/colorscale_calc');
var arraysToCalcdata = _dereq_('../scatter/arrays_to_calcdata');
var calcSelection = _dereq_('../scatter/calc_selection');
var calcMarkerSize = _dereq_('../scatter/calc').calcMarkerSize;

module.exports = function calc(gd, trace) {
    var fullLayout = gd._fullLayout;
    var subplotId = trace.subplot;
    var radialAxis = fullLayout[subplotId].radialaxis;
    var angularAxis = fullLayout[subplotId].angularaxis;
    var rArray = radialAxis.makeCalcdata(trace, 'r');
    var thetaArray = angularAxis.makeCalcdata(trace, 'theta');
    var len = trace._length;
    var cd = new Array(len);

    for(var i = 0; i < len; i++) {
        var r = rArray[i];
        var theta = thetaArray[i];
        var cdi = cd[i] = {};

        if(isNumeric(r) && isNumeric(theta)) {
            cdi.r = r;
            cdi.theta = theta;
        } else {
            cdi.r = BADNUM;
        }
    }

    var ppad = calcMarkerSize(trace, len);
    trace._extremes.x = Axes.findExtremes(radialAxis, rArray, {ppad: ppad});

    calcColorscale(gd, trace);
    arraysToCalcdata(cd, trace);
    calcSelection(cd, trace);

    return cd;
};

},{"../../constants/numerical":674,"../../plots/cartesian/axes":745,"../scatter/arrays_to_calcdata":1047,"../scatter/calc":1049,"../scatter/calc_selection":1050,"../scatter/colorscale_calc":1051,"fast-isnumeric":218}],1112:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

var subTypes = _dereq_('../scatter/subtypes');
var handleMarkerDefaults = _dereq_('../scatter/marker_defaults');
var handleLineDefaults = _dereq_('../scatter/line_defaults');
var handleLineShapeDefaults = _dereq_('../scatter/line_shape_defaults');
var handleTextDefaults = _dereq_('../scatter/text_defaults');
var handleFillColorDefaults = _dereq_('../scatter/fillcolor_defaults');
var PTS_LINESONLY = _dereq_('../scatter/constants').PTS_LINESONLY;

var attributes = _dereq_('./attributes');

function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var len = handleRThetaDefaults(traceIn, traceOut, layout, coerce);
    if(!len) {
        traceOut.visible = false;
        return;
    }

    coerce('thetaunit');
    coerce('mode', len < PTS_LINESONLY ? 'lines+markers' : 'lines');
    coerce('text');
    coerce('hovertext');
    if(traceOut.hoveron !== 'fills') coerce('hovertemplate');

    if(subTypes.hasLines(traceOut)) {
        handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
        handleLineShapeDefaults(traceIn, traceOut, coerce);
        coerce('connectgaps');
    }

    if(subTypes.hasMarkers(traceOut)) {
        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true});
    }

    if(subTypes.hasText(traceOut)) {
        handleTextDefaults(traceIn, traceOut, layout, coerce);
    }

    var dfltHoverOn = [];

    if(subTypes.hasMarkers(traceOut) || subTypes.hasText(traceOut)) {
        coerce('cliponaxis');
        coerce('marker.maxdisplayed');
        dfltHoverOn.push('points');
    }

    coerce('fill');

    if(traceOut.fill !== 'none') {
        handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
        if(!subTypes.hasLines(traceOut)) handleLineShapeDefaults(traceIn, traceOut, coerce);
    }

    if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') {
        dfltHoverOn.push('fills');
    }
    coerce('hoveron', dfltHoverOn.join('+') || 'points');

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
}

function handleRThetaDefaults(traceIn, traceOut, layout, coerce) {
    var r = coerce('r');
    var theta = coerce('theta');
    var len;

    if(r) {
        if(theta) {
            len = Math.min(r.length, theta.length);
        } else {
            len = r.length;
            coerce('theta0');
            coerce('dtheta');
        }
    } else {
        if(!theta) return 0;
        len = traceOut.theta.length;
        coerce('r0');
        coerce('dr');
    }

    traceOut._length = len;
    return len;
}

module.exports = {
    handleRThetaDefaults: handleRThetaDefaults,
    supplyDefaults: supplyDefaults
};

},{"../../lib":697,"../scatter/constants":1052,"../scatter/fillcolor_defaults":1057,"../scatter/line_defaults":1061,"../scatter/line_shape_defaults":1063,"../scatter/marker_defaults":1067,"../scatter/subtypes":1072,"../scatter/text_defaults":1073,"./attributes":1110}],1113:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterHover = _dereq_('../scatter/hover');
var Axes = _dereq_('../../plots/cartesian/axes');
var Lib = _dereq_('../../lib');

function hoverPoints(pointData, xval, yval, hovermode) {
    var scatterPointData = scatterHover(pointData, xval, yval, hovermode);
    if(!scatterPointData || scatterPointData[0].index === false) return;

    var newPointData = scatterPointData[0];

    // hovering on fill case
    if(newPointData.index === undefined) {
        return scatterPointData;
    }

    var subplot = pointData.subplot;
    var cdi = newPointData.cd[newPointData.index];
    var trace = newPointData.trace;

    if(!subplot.isPtInside(cdi)) return;

    newPointData.xLabelVal = undefined;
    newPointData.yLabelVal = undefined;
    makeHoverPointText(cdi, trace, subplot, newPointData);
    newPointData.hovertemplate = trace.hovertemplate;
    return scatterPointData;
}

function makeHoverPointText(cdi, trace, subplot, pointData) {

    var radialAxis = subplot.radialAxis;
    var angularAxis = subplot.angularAxis;
    radialAxis._hovertitle = 'r';
    angularAxis._hovertitle = 'θ';

    var hoverinfo = cdi.hi || trace.hoverinfo;
    var text = [];
    function textPart(ax, val) {
        text.push(ax._hovertitle + ': ' + Axes.tickText(ax, val, 'hover').text);
    }

    if(!trace.hovertemplate) {
        var parts = hoverinfo.split('+');

        if(parts.indexOf('all') !== -1) parts = ['r', 'theta', 'text'];
        if(parts.indexOf('r') !== -1) {
            textPart(radialAxis, radialAxis.c2l(cdi.r));
        }
        if(parts.indexOf('theta') !== -1) {
            var theta = cdi.theta;
            textPart(
                angularAxis,
                angularAxis.thetaunit === 'degrees' ? Lib.rad2deg(theta) : theta
            );
        }
        if(parts.indexOf('text') !== -1 && pointData.text) {
            text.push(pointData.text);
            delete pointData.text;
        }

        pointData.extraText = text.join('<br>');
    }
}

module.exports = {
    hoverPoints: hoverPoints,
    makeHoverPointText: makeHoverPointText
};

},{"../../lib":697,"../../plots/cartesian/axes":745,"../scatter/hover":1059}],1114:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'trace',
    name: 'scatterpolar',
    basePlotModule: _dereq_('../../plots/polar'),
    categories: ['polar', 'symbols', 'showLegend', 'scatter-like'],

    attributes: _dereq_('./attributes'),
    supplyDefaults: _dereq_('./defaults').supplyDefaults,
    colorbar: _dereq_('../scatter/marker_colorbar'),
    calc: _dereq_('./calc'),
    plot: _dereq_('./plot'),
    style: _dereq_('../scatter/style').style,
    hoverPoints: _dereq_('./hover').hoverPoints,
    selectPoints: _dereq_('../scatter/select'),

    meta: {
        
        
    }
};

},{"../../plots/polar":810,"../scatter/marker_colorbar":1066,"../scatter/select":1069,"../scatter/style":1071,"./attributes":1110,"./calc":1111,"./defaults":1112,"./hover":1113,"./plot":1115}],1115:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterPlot = _dereq_('../scatter/plot');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

module.exports = function plot(gd, subplot, moduleCalcData) {
    var mlayer = subplot.layers.frontplot.select('g.scatterlayer');

    var plotinfo = {
        xaxis: subplot.xaxis,
        yaxis: subplot.yaxis,
        plot: subplot.framework,
        layerClipId: subplot._hasClipOnAxisFalse ? subplot.clipIds.forTraces : null
    };

    var radialAxis = subplot.radialAxis;
    var angularAxis = subplot.angularAxis;

    // convert:
    // 'c' (r,theta) -> 'geometric' (r,theta) -> (x,y)
    for(var i = 0; i < moduleCalcData.length; i++) {
        var cdi = moduleCalcData[i];

        for(var j = 0; j < cdi.length; j++) {
            var cd = cdi[j];
            var r = cd.r;

            if(r === BADNUM) {
                cd.x = cd.y = BADNUM;
            } else {
                var rg = radialAxis.c2g(r);
                var thetag = angularAxis.c2g(cd.theta);
                cd.x = rg * Math.cos(thetag);
                cd.y = rg * Math.sin(thetag);
            }
        }
    }

    scatterPlot(gd, plotinfo, moduleCalcData, mlayer);
};

},{"../../constants/numerical":674,"../scatter/plot":1068}],1116:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterPolarAttrs = _dereq_('../scatterpolar/attributes');
var scatterGlAttrs = _dereq_('../scattergl/attributes');

module.exports = {
    mode: scatterPolarAttrs.mode,
    r: scatterPolarAttrs.r,
    theta: scatterPolarAttrs.theta,
    r0: scatterPolarAttrs.r0,
    dr: scatterPolarAttrs.dr,
    theta0: scatterPolarAttrs.theta0,
    dtheta: scatterPolarAttrs.dtheta,
    thetaunit: scatterPolarAttrs.thetaunit,

    text: scatterPolarAttrs.text,
    hovertext: scatterPolarAttrs.hovertext,
    hovertemplate: scatterPolarAttrs.hovertemplate,

    line: scatterGlAttrs.line,
    connectgaps: scatterGlAttrs.connectgaps,

    marker: scatterGlAttrs.marker,
    // no cliponaxis

    fill: scatterGlAttrs.fill,
    fillcolor: scatterGlAttrs.fillcolor,

    textposition: scatterGlAttrs.textposition,
    textfont: scatterGlAttrs.textfont,

    hoverinfo: scatterPolarAttrs.hoverinfo,
    // no hoveron

    selected: scatterPolarAttrs.selected,
    unselected: scatterPolarAttrs.unselected
};

},{"../scattergl/attributes":1097,"../scatterpolar/attributes":1110}],1117:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

var subTypes = _dereq_('../scatter/subtypes');
var handleRThetaDefaults = _dereq_('../scatterpolar/defaults').handleRThetaDefaults;
var handleMarkerDefaults = _dereq_('../scatter/marker_defaults');
var handleLineDefaults = _dereq_('../scatter/line_defaults');
var handleTextDefaults = _dereq_('../scatter/text_defaults');
var handleFillColorDefaults = _dereq_('../scatter/fillcolor_defaults');
var PTS_LINESONLY = _dereq_('../scatter/constants').PTS_LINESONLY;

var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var len = handleRThetaDefaults(traceIn, traceOut, layout, coerce);
    if(!len) {
        traceOut.visible = false;
        return;
    }

    coerce('thetaunit');
    coerce('mode', len < PTS_LINESONLY ? 'lines+markers' : 'lines');
    coerce('text');
    coerce('hovertext');
    if(traceOut.hoveron !== 'fills') coerce('hovertemplate');

    if(subTypes.hasLines(traceOut)) {
        handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
        coerce('connectgaps');
    }

    if(subTypes.hasMarkers(traceOut)) {
        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce);
    }

    if(subTypes.hasText(traceOut)) {
        handleTextDefaults(traceIn, traceOut, layout, coerce);
    }

    coerce('fill');
    if(traceOut.fill !== 'none') {
        handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
    }

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};

},{"../../lib":697,"../scatter/constants":1052,"../scatter/fillcolor_defaults":1057,"../scatter/line_defaults":1061,"../scatter/marker_defaults":1067,"../scatter/subtypes":1072,"../scatter/text_defaults":1073,"../scatterpolar/defaults":1112,"./attributes":1116}],1118:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var cluster = _dereq_('point-cluster');
var isNumeric = _dereq_('fast-isnumeric');

var ScatterGl = _dereq_('../scattergl');
var calcColorscale = _dereq_('../scatter/colorscale_calc');
var calcMarkerSize = _dereq_('../scatter/calc').calcMarkerSize;
var convert = _dereq_('../scattergl/convert');

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');
var makeHoverPointText = _dereq_('../scatterpolar/hover').makeHoverPointText;

var TOO_MANY_POINTS = _dereq_('../scattergl/constants').TOO_MANY_POINTS;

function calc(gd, trace) {
    var fullLayout = gd._fullLayout;
    var subplotId = trace.subplot;
    var radialAxis = fullLayout[subplotId].radialaxis;
    var angularAxis = fullLayout[subplotId].angularaxis;
    var rArray = radialAxis.makeCalcdata(trace, 'r');
    var thetaArray = angularAxis.makeCalcdata(trace, 'theta');
    var len = trace._length;
    var stash = {};

    if(len < rArray.length) rArray = rArray.slice(0, len);
    if(len < thetaArray.length) thetaArray = thetaArray.slice(0, len);

    stash.r = rArray;
    stash.theta = thetaArray;

    calcColorscale(gd, trace);

    // only compute 'style' options in calc, as position options
    // depend on the radial range and must be set in plot
    var opts = stash.opts = convert.style(gd, trace);

    // For graphs with very large number of points and array marker.size,
    // use average marker size instead to speed things up.
    var ppad;
    if(len < TOO_MANY_POINTS) {
        ppad = calcMarkerSize(trace, len);
    } else if(opts.marker) {
        ppad = 2 * (opts.marker.sizeAvg || Math.max(opts.marker.size, 3));
    }
    trace._extremes.x = Axes.findExtremes(radialAxis, rArray, {ppad: ppad});

    return [{x: false, y: false, t: stash, trace: trace}];
}

function plot(gd, subplot, cdata) {
    if(!cdata.length) return;

    var radialAxis = subplot.radialAxis;
    var angularAxis = subplot.angularAxis;
    var scene = ScatterGl.sceneUpdate(gd, subplot);

    cdata.forEach(function(cdscatter) {
        if(!cdscatter || !cdscatter[0] || !cdscatter[0].trace) return;
        var cd = cdscatter[0];
        var trace = cd.trace;
        var stash = cd.t;
        var len = trace._length;
        var rArray = stash.r;
        var thetaArray = stash.theta;
        var opts = stash.opts;
        var i;

        var subRArray = rArray.slice();
        var subThetaArray = thetaArray.slice();

        // filter out by range
        for(i = 0; i < rArray.length; i++) {
            if(!subplot.isPtInside({r: rArray[i], theta: thetaArray[i]})) {
                subRArray[i] = NaN;
                subThetaArray[i] = NaN;
            }
        }

        var positions = new Array(len * 2);
        var x = Array(len);
        var y = Array(len);

        for(i = 0; i < len; i++) {
            var r = subRArray[i];
            var xx, yy;

            if(isNumeric(r)) {
                var rg = radialAxis.c2g(r);
                var thetag = angularAxis.c2g(subThetaArray[i], trace.thetaunit);
                xx = rg * Math.cos(thetag);
                yy = rg * Math.sin(thetag);
            } else {
                xx = yy = NaN;
            }
            x[i] = positions[i * 2] = xx;
            y[i] = positions[i * 2 + 1] = yy;
        }

        stash.tree = cluster(positions);

        // FIXME: see scattergl.js#109
        if(opts.marker && len >= TOO_MANY_POINTS) {
            opts.marker.cluster = stash.tree;
        }

        if(opts.marker) {
            opts.markerSel.positions = opts.markerUnsel.positions = opts.marker.positions = positions;
        }

        if(opts.line && positions.length > 1) {
            Lib.extendFlat(
                opts.line,
                convert.linePositions(gd, trace, positions)
            );
        }

        if(opts.text) {
            Lib.extendFlat(
                opts.text,
                {positions: positions},
                convert.textPosition(gd, trace, opts.text, opts.marker)
            );
            Lib.extendFlat(
                opts.textSel,
                {positions: positions},
                convert.textPosition(gd, trace, opts.text, opts.markerSel)
            );
            Lib.extendFlat(
                opts.textUnsel,
                {positions: positions},
                convert.textPosition(gd, trace, opts.text, opts.markerUnsel)
            );
        }

        if(opts.fill && !scene.fill2d) scene.fill2d = true;
        if(opts.marker && !scene.scatter2d) scene.scatter2d = true;
        if(opts.line && !scene.line2d) scene.line2d = true;
        if(opts.text && !scene.glText) scene.glText = true;

        scene.lineOptions.push(opts.line);
        scene.fillOptions.push(opts.fill);
        scene.markerOptions.push(opts.marker);
        scene.markerSelectedOptions.push(opts.markerSel);
        scene.markerUnselectedOptions.push(opts.markerUnsel);
        scene.textOptions.push(opts.text);
        scene.textSelectedOptions.push(opts.textSel);
        scene.textUnselectedOptions.push(opts.textUnsel);

        stash.x = x;
        stash.y = y;
        stash.rawx = x;
        stash.rawy = y;
        stash.r = rArray;
        stash.theta = thetaArray;
        stash.positions = positions;
        stash._scene = scene;
        stash.index = scene.count;
        scene.count++;
    });

    return ScatterGl.plot(gd, subplot, cdata);
}

function hoverPoints(pointData, xval, yval, hovermode) {
    var cd = pointData.cd;
    var stash = cd[0].t;
    var rArray = stash.r;
    var thetaArray = stash.theta;

    var scatterPointData = ScatterGl.hoverPoints(pointData, xval, yval, hovermode);
    if(!scatterPointData || scatterPointData[0].index === false) return;

    var newPointData = scatterPointData[0];

    if(newPointData.index === undefined) {
        return scatterPointData;
    }

    var subplot = pointData.subplot;
    var cdi = newPointData.cd[newPointData.index];
    var trace = newPointData.trace;

    // augment pointData with r/theta param
    cdi.r = rArray[newPointData.index];
    cdi.theta = thetaArray[newPointData.index];

    if(!subplot.isPtInside(cdi)) return;

    newPointData.xLabelVal = undefined;
    newPointData.yLabelVal = undefined;
    makeHoverPointText(cdi, trace, subplot, newPointData);

    return scatterPointData;
}

module.exports = {
    moduleType: 'trace',
    name: 'scatterpolargl',
    basePlotModule: _dereq_('../../plots/polar'),
    categories: ['gl', 'regl', 'polar', 'symbols', 'showLegend', 'scatter-like'],

    attributes: _dereq_('./attributes'),
    supplyDefaults: _dereq_('./defaults'),
    colorbar: _dereq_('../scatter/marker_colorbar'),

    calc: calc,
    plot: plot,
    hoverPoints: hoverPoints,
    selectPoints: ScatterGl.selectPoints,

    meta: {
        
        
    }
};

},{"../../lib":697,"../../plots/cartesian/axes":745,"../../plots/polar":810,"../scatter/calc":1049,"../scatter/colorscale_calc":1051,"../scatter/marker_colorbar":1066,"../scattergl":1101,"../scattergl/constants":1098,"../scattergl/convert":1099,"../scatterpolar/hover":1113,"./attributes":1116,"./defaults":1117,"fast-isnumeric":218,"point-cluster":458}],1119:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var scatterAttrs = _dereq_('../scatter/attributes');
var plotAttrs = _dereq_('../../plots/attributes');
var colorAttributes = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
var dash = _dereq_('../../components/drawing/attributes').dash;

var extendFlat = _dereq_('../../lib/extend').extendFlat;

var scatterMarkerAttrs = scatterAttrs.marker;
var scatterLineAttrs = scatterAttrs.line;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;

module.exports = {
    a: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    b: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    c: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    sum: {
        valType: 'number',
        
        dflt: 0,
        min: 0,
        editType: 'calc',
        
    },
    mode: extendFlat({}, scatterAttrs.mode, {dflt: 'markers'}),
    text: extendFlat({}, scatterAttrs.text, {
        
    }),
    hovertext: extendFlat({}, scatterAttrs.hovertext, {
        
    }),
    line: {
        color: scatterLineAttrs.color,
        width: scatterLineAttrs.width,
        dash: dash,
        shape: extendFlat({}, scatterLineAttrs.shape,
            {values: ['linear', 'spline']}),
        smoothing: scatterLineAttrs.smoothing,
        editType: 'calc'
    },
    connectgaps: scatterAttrs.connectgaps,
    cliponaxis: scatterAttrs.cliponaxis,
    fill: extendFlat({}, scatterAttrs.fill, {
        values: ['none', 'toself', 'tonext'],
        dflt: 'none',
        
    }),
    fillcolor: scatterAttrs.fillcolor,
    marker: extendFlat({
        symbol: scatterMarkerAttrs.symbol,
        opacity: scatterMarkerAttrs.opacity,
        maxdisplayed: scatterMarkerAttrs.maxdisplayed,
        size: scatterMarkerAttrs.size,
        sizeref: scatterMarkerAttrs.sizeref,
        sizemin: scatterMarkerAttrs.sizemin,
        sizemode: scatterMarkerAttrs.sizemode,
        line: extendFlat({
            width: scatterMarkerLineAttrs.width,
            editType: 'calc'
        },
            colorAttributes('marker.line')
        ),
        gradient: scatterMarkerAttrs.gradient,
        editType: 'calc'
    }, colorAttributes('marker'), {
        colorbar: colorbarAttrs
    }),

    textfont: scatterAttrs.textfont,
    textposition: scatterAttrs.textposition,

    selected: scatterAttrs.selected,
    unselected: scatterAttrs.unselected,

    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
        flags: ['a', 'b', 'c', 'text', 'name']
    }),
    hoveron: scatterAttrs.hoveron,
    hovertemplate: hovertemplateAttrs(),
};

},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/drawing/attributes":594,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plots/attributes":742,"../scatter/attributes":1048}],1120:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var calcColorscale = _dereq_('../scatter/colorscale_calc');
var arraysToCalcdata = _dereq_('../scatter/arrays_to_calcdata');
var calcSelection = _dereq_('../scatter/calc_selection');
var calcMarkerSize = _dereq_('../scatter/calc').calcMarkerSize;

var dataArrays = ['a', 'b', 'c'];
var arraysToFill = {a: ['b', 'c'], b: ['a', 'c'], c: ['a', 'b']};

module.exports = function calc(gd, trace) {
    var ternary = gd._fullLayout[trace.subplot];
    var displaySum = ternary.sum;
    var normSum = trace.sum || displaySum;
    var arrays = {a: trace.a, b: trace.b, c: trace.c};

    var i, j, dataArray, newArray, fillArray1, fillArray2;

    // fill in one missing component
    for(i = 0; i < dataArrays.length; i++) {
        dataArray = dataArrays[i];
        if(arrays[dataArray]) continue;

        fillArray1 = arrays[arraysToFill[dataArray][0]];
        fillArray2 = arrays[arraysToFill[dataArray][1]];
        newArray = new Array(fillArray1.length);
        for(j = 0; j < fillArray1.length; j++) {
            newArray[j] = normSum - fillArray1[j] - fillArray2[j];
        }
        arrays[dataArray] = newArray;
    }

    // make the calcdata array
    var serieslen = trace._length;
    var cd = new Array(serieslen);
    var a, b, c, norm, x, y;
    for(i = 0; i < serieslen; i++) {
        a = arrays.a[i];
        b = arrays.b[i];
        c = arrays.c[i];
        if(isNumeric(a) && isNumeric(b) && isNumeric(c)) {
            a = +a;
            b = +b;
            c = +c;
            norm = displaySum / (a + b + c);
            if(norm !== 1) {
                a *= norm;
                b *= norm;
                c *= norm;
            }
            // map a, b, c onto x and y where the full scale of y
            // is [0, sum], and x is [-sum, sum]
            // TODO: this makes `a` always the top, `b` the bottom left,
            // and `c` the bottom right. Do we want options to rearrange
            // these?
            y = a;
            x = c - b;
            cd[i] = {x: x, y: y, a: a, b: b, c: c};
        }
        else cd[i] = {x: false, y: false};
    }

    calcMarkerSize(trace, serieslen);
    calcColorscale(gd, trace);
    arraysToCalcdata(cd, trace);
    calcSelection(cd, trace);

    return cd;
};

},{"../scatter/arrays_to_calcdata":1047,"../scatter/calc":1049,"../scatter/calc_selection":1050,"../scatter/colorscale_calc":1051,"fast-isnumeric":218}],1121:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

var constants = _dereq_('../scatter/constants');
var subTypes = _dereq_('../scatter/subtypes');
var handleMarkerDefaults = _dereq_('../scatter/marker_defaults');
var handleLineDefaults = _dereq_('../scatter/line_defaults');
var handleLineShapeDefaults = _dereq_('../scatter/line_shape_defaults');
var handleTextDefaults = _dereq_('../scatter/text_defaults');
var handleFillColorDefaults = _dereq_('../scatter/fillcolor_defaults');

var attributes = _dereq_('./attributes');


module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var a = coerce('a');
    var b = coerce('b');
    var c = coerce('c');
    var len;

    // allow any one array to be missing, len is the minimum length of those
    // present. Note that after coerce data_array's are either Arrays (which
    // are truthy even if empty) or undefined. As in scatter, an empty array
    // is different from undefined, because it can signify that this data is
    // not known yet but expected in the future
    if(a) {
        len = a.length;
        if(b) {
            len = Math.min(len, b.length);
            if(c) len = Math.min(len, c.length);
        }
        else if(c) len = Math.min(len, c.length);
        else len = 0;
    }
    else if(b && c) {
        len = Math.min(b.length, c.length);
    }

    if(!len) {
        traceOut.visible = false;
        return;
    }

    traceOut._length = len;

    coerce('sum');

    coerce('text');
    coerce('hovertext');
    if(traceOut.hoveron !== 'fills') coerce('hovertemplate');

    var defaultMode = len < constants.PTS_LINESONLY ? 'lines+markers' : 'lines';
    coerce('mode', defaultMode);

    if(subTypes.hasLines(traceOut)) {
        handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
        handleLineShapeDefaults(traceIn, traceOut, coerce);
        coerce('connectgaps');
    }

    if(subTypes.hasMarkers(traceOut)) {
        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true});
    }

    if(subTypes.hasText(traceOut)) {
        handleTextDefaults(traceIn, traceOut, layout, coerce);
    }

    var dfltHoverOn = [];

    if(subTypes.hasMarkers(traceOut) || subTypes.hasText(traceOut)) {
        coerce('cliponaxis');
        coerce('marker.maxdisplayed');
        dfltHoverOn.push('points');
    }

    coerce('fill');
    if(traceOut.fill !== 'none') {
        handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
        if(!subTypes.hasLines(traceOut)) handleLineShapeDefaults(traceIn, traceOut, coerce);
    }

    if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') {
        dfltHoverOn.push('fills');
    }
    coerce('hoveron', dfltHoverOn.join('+') || 'points');

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};

},{"../../lib":697,"../scatter/constants":1052,"../scatter/fillcolor_defaults":1057,"../scatter/line_defaults":1061,"../scatter/line_shape_defaults":1063,"../scatter/marker_defaults":1067,"../scatter/subtypes":1072,"../scatter/text_defaults":1073,"./attributes":1119}],1122:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function eventData(out, pt, trace, cd, pointNumber) {
    if(pt.xa) out.xaxis = pt.xa;
    if(pt.ya) out.yaxis = pt.ya;

    if(cd[pointNumber]) {
        var cdi = cd[pointNumber];

        // N.B. These are the normalized coordinates.
        out.a = cdi.a;
        out.b = cdi.b;
        out.c = cdi.c;
    } else {
        // for fill-hover only
        out.a = pt.a;
        out.b = pt.b;
        out.c = pt.c;
    }

    return out;
};

},{}],1123:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var scatterHover = _dereq_('../scatter/hover');
var Axes = _dereq_('../../plots/cartesian/axes');


module.exports = function hoverPoints(pointData, xval, yval, hovermode) {
    var scatterPointData = scatterHover(pointData, xval, yval, hovermode);
    if(!scatterPointData || scatterPointData[0].index === false) return;

    var newPointData = scatterPointData[0];

    // if hovering on a fill, we don't show any point data so the label is
    // unchanged from what scatter gives us - except that it needs to
    // be constrained to the trianglular plot area, not just the rectangular
    // area defined by the synthetic x and y axes
    // TODO: in some cases the vertical middle of the shape is not within
    // the triangular viewport at all, so the label can become disconnected
    // from the shape entirely. But calculating what portion of the shape
    // is actually visible, as constrained by the diagonal axis lines, is not
    // so easy and anyway we lost the information we would have needed to do
    // this inside scatterHover.
    if(newPointData.index === undefined) {
        var yFracUp = 1 - (newPointData.y0 / pointData.ya._length);
        var xLen = pointData.xa._length;
        var xMin = xLen * yFracUp / 2;
        var xMax = xLen - xMin;
        newPointData.x0 = Math.max(Math.min(newPointData.x0, xMax), xMin);
        newPointData.x1 = Math.max(Math.min(newPointData.x1, xMax), xMin);
        return scatterPointData;
    }

    var cdi = newPointData.cd[newPointData.index];

    newPointData.a = cdi.a;
    newPointData.b = cdi.b;
    newPointData.c = cdi.c;

    newPointData.xLabelVal = undefined;
    newPointData.yLabelVal = undefined;
    // TODO: nice formatting, and label by axis title, for a, b, and c?

    var trace = newPointData.trace;
    var ternary = newPointData.subplot;
    var hoverinfo = cdi.hi || trace.hoverinfo;
    var text = [];
    function textPart(ax, val) {
        text.push(ax._hovertitle + ': ' + Axes.tickText(ax, val, 'hover').text);
    }
    if(!trace.hovertemplate) {
        var parts = hoverinfo.split('+');
        if(parts.indexOf('all') !== -1) parts = ['a', 'b', 'c'];
        if(parts.indexOf('a') !== -1) textPart(ternary.aaxis, cdi.a);
        if(parts.indexOf('b') !== -1) textPart(ternary.baxis, cdi.b);
        if(parts.indexOf('c') !== -1) textPart(ternary.caxis, cdi.c);
    }
    newPointData.extraText = text.join('<br>');
    newPointData.hovertemplate = trace.hovertemplate;
    return scatterPointData;
};

},{"../../plots/cartesian/axes":745,"../scatter/hover":1059}],1124:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var ScatterTernary = {};

ScatterTernary.attributes = _dereq_('./attributes');
ScatterTernary.supplyDefaults = _dereq_('./defaults');
ScatterTernary.colorbar = _dereq_('../scatter/marker_colorbar');
ScatterTernary.calc = _dereq_('./calc');
ScatterTernary.plot = _dereq_('./plot');
ScatterTernary.style = _dereq_('../scatter/style').style;
ScatterTernary.styleOnSelect = _dereq_('../scatter/style').styleOnSelect;
ScatterTernary.hoverPoints = _dereq_('./hover');
ScatterTernary.selectPoints = _dereq_('../scatter/select');
ScatterTernary.eventData = _dereq_('./event_data');

ScatterTernary.moduleType = 'trace';
ScatterTernary.name = 'scatterternary';
ScatterTernary.basePlotModule = _dereq_('../../plots/ternary');
ScatterTernary.categories = ['ternary', 'symbols', 'showLegend', 'scatter-like'];
ScatterTernary.meta = {
    
    
};

module.exports = ScatterTernary;

},{"../../plots/ternary":822,"../scatter/marker_colorbar":1066,"../scatter/select":1069,"../scatter/style":1071,"./attributes":1119,"./calc":1120,"./defaults":1121,"./event_data":1122,"./hover":1123,"./plot":1125}],1125:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var scatterPlot = _dereq_('../scatter/plot');

module.exports = function plot(gd, ternary, moduleCalcData) {
    var plotContainer = ternary.plotContainer;

    // remove all nodes inside the scatter layer
    plotContainer.select('.scatterlayer').selectAll('*').remove();

    // mimic cartesian plotinfo
    var plotinfo = {
        xaxis: ternary.xaxis,
        yaxis: ternary.yaxis,
        plot: plotContainer,
        layerClipId: ternary._hasClipOnAxisFalse ? ternary.clipIdRelative : null
    };

    var scatterLayer = ternary.layers.frontplot.select('g.scatterlayer');

    scatterPlot(gd, plotinfo, moduleCalcData, scatterLayer);
};

},{"../scatter/plot":1068}],1126:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterAttrs = _dereq_('../scatter/attributes');
var colorAttrs = _dereq_('../../components/colorscale/attributes');
var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var scatterGlAttrs = _dereq_('../scattergl/attributes');
var cartesianIdRegex = _dereq_('../../plots/cartesian/constants').idRegex;
var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;
var extendFlat = _dereq_('../../lib/extend').extendFlat;

var scatterMarkerAttrs = scatterAttrs.marker;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;

var markerLineAttrs = extendFlat(colorAttrs('marker.line', {editTypeOverride: 'calc'}), {
    width: extendFlat({}, scatterMarkerLineAttrs.width, {editType: 'calc'}),
    editType: 'calc'
});

var markerAttrs = extendFlat(colorAttrs('marker'), {
    symbol: scatterMarkerAttrs.symbol,
    size: extendFlat({}, scatterMarkerAttrs.size, {editType: 'markerSize'}),
    sizeref: scatterMarkerAttrs.sizeref,
    sizemin: scatterMarkerAttrs.sizemin,
    sizemode: scatterMarkerAttrs.sizemode,
    opacity: scatterMarkerAttrs.opacity,
    colorbar: scatterMarkerAttrs.colorbar,
    line: markerLineAttrs,
    editType: 'calc'
});

markerAttrs.color.editType = markerAttrs.cmin.editType = markerAttrs.cmax.editType = 'style';

function makeAxesValObject(axLetter) {
    return {
        valType: 'info_array',
        freeLength: true,
        
        editType: 'calc',
        items: {
            valType: 'subplotid',
            regex: cartesianIdRegex[axLetter],
            editType: 'plot'
        },
        
    };
}

module.exports = {
    dimensions: templatedArray('dimension', {
        visible: {
            valType: 'boolean',
            
            dflt: true,
            editType: 'calc',
            
        },
        label: {
            valType: 'string',
            
            editType: 'calc',
            
        },
        values: {
            valType: 'data_array',
            
            editType: 'calc+clearAxisTypes',
            
        },

        axis: {
            type: {
                valType: 'enumerated',
                values: ['linear', 'log', 'date', 'category'],
                
                editType: 'calc+clearAxisTypes',
                
            },

            // TODO make 'true' the default in v2?
            matches: {
                valType: 'boolean',
                dflt: false,
                
                editType: 'calc',
                
            },

            editType: 'calc+clearAxisTypes'
        },

        // TODO should add an attribute to pin down x only vars and y only vars
        // like https://seaborn.pydata.org/generated/seaborn.pairplot.html
        // x_vars and y_vars

        // maybe more axis defaulting option e.g. `showgrid: false`

        editType: 'calc+clearAxisTypes'
    }),

    // mode: {}, (only 'markers' for now)

    text: extendFlat({}, scatterGlAttrs.text, {
        
    }),
    hovertext: extendFlat({}, scatterGlAttrs.hovertext, {
        
    }),

    hovertemplate: hovertemplateAttrs(),

    marker: markerAttrs,

    xaxes: makeAxesValObject('x'),
    yaxes: makeAxesValObject('y'),

    diagonal: {
        visible: {
            valType: 'boolean',
            
            dflt: true,
            editType: 'calc',
            
        },

        // type: 'scattergl' | 'histogram' | 'box' | 'violin'
        // ...
        // more options

        editType: 'calc'
    },

    showupperhalf: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'calc',
        
    },
    showlowerhalf: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'calc',
        
    },

    selected: {
        marker: scatterGlAttrs.selected.marker,
        editType: 'calc'
    },
    unselected: {
        marker: scatterGlAttrs.unselected.marker,
        editType: 'calc'
    },

    opacity: scatterGlAttrs.opacity
};

},{"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plot_api/plot_template":735,"../../plots/cartesian/constants":751,"../scatter/attributes":1048,"../scattergl/attributes":1097}],1127:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var createLine = _dereq_('regl-line2d');

var Registry = _dereq_('../../registry');
var prepareRegl = _dereq_('../../lib/prepare_regl');
var getModuleCalcData = _dereq_('../../plots/get_data').getModuleCalcData;
var Cartesian = _dereq_('../../plots/cartesian');
var getFromId = _dereq_('../../plots/cartesian/axis_ids').getFromId;
var shouldShowZeroLine = _dereq_('../../plots/cartesian/axes').shouldShowZeroLine;

var SPLOM = 'splom';

function plot(gd) {
    var fullLayout = gd._fullLayout;
    var _module = Registry.getModule(SPLOM);
    var splomCalcData = getModuleCalcData(gd.calcdata, _module)[0];

    var success = prepareRegl(gd, ['ANGLE_instanced_arrays', 'OES_element_index_uint']);
    if(!success) return;

    if(fullLayout._hasOnlyLargeSploms) {
        updateGrid(gd);
    }

    _module.plot(gd, {}, splomCalcData);
}

function drag(gd) {
    var cd = gd.calcdata;
    var fullLayout = gd._fullLayout;

    if(fullLayout._hasOnlyLargeSploms) {
        updateGrid(gd);
    }

    for(var i = 0; i < cd.length; i++) {
        var cd0 = cd[i][0];
        var trace = cd0.trace;
        var scene = fullLayout._splomScenes[trace.uid];

        if(trace.type === 'splom' && scene && scene.matrix) {
            dragOne(gd, trace, scene);
        }
    }
}

function dragOne(gd, trace, scene) {
    var visibleLength = scene.matrixOptions.data.length;
    var visibleDims = trace._visibleDims;
    var ranges = scene.viewOpts.ranges = new Array(visibleLength);

    for(var k = 0; k < visibleDims.length; k++) {
        var i = visibleDims[k];
        var rng = ranges[k] = new Array(4);

        var xa = getFromId(gd, trace._diag[i][0]);
        if(xa) {
            rng[0] = xa.r2l(xa.range[0]);
            rng[2] = xa.r2l(xa.range[1]);
        }

        var ya = getFromId(gd, trace._diag[i][1]);
        if(ya) {
            rng[1] = ya.r2l(ya.range[0]);
            rng[3] = ya.r2l(ya.range[1]);
        }
    }

    if(scene.selectBatch) {
        scene.matrix.update({ranges: ranges}, {ranges: ranges});
    } else {
        scene.matrix.update({ranges: ranges});
    }
}

function updateGrid(gd) {
    var fullLayout = gd._fullLayout;
    var regl = fullLayout._glcanvas.data()[0].regl;
    var splomGrid = fullLayout._splomGrid;

    if(!splomGrid) {
        splomGrid = fullLayout._splomGrid = createLine(regl);
    }
    splomGrid.update(makeGridData(gd));
}

function makeGridData(gd) {
    var fullLayout = gd._fullLayout;
    var gs = fullLayout._size;
    var fullView = [0, 0, fullLayout.width, fullLayout.height];
    var lookup = {};
    var k;

    function push(prefix, ax, x0, x1, y0, y1) {
        var lcolor = ax[prefix + 'color'];
        var lwidth = ax[prefix + 'width'];
        var key = String(lcolor + lwidth);

        if(key in lookup) {
            lookup[key].data.push(NaN, NaN, x0, x1, y0, y1);
        } else {
            lookup[key] = {
                data: [x0, x1, y0, y1],
                join: 'rect',
                thickness: lwidth,
                color: lcolor,
                viewport: fullView,
                range: fullView,
                overlay: false
            };
        }
    }

    for(k in fullLayout._splomSubplots) {
        var sp = fullLayout._plots[k];
        var xa = sp.xaxis;
        var ya = sp.yaxis;
        var xVals = xa._vals;
        var yVals = ya._vals;
        // ya.l2p assumes top-to-bottom coordinate system (a la SVG),
        // we need to compute bottom-to-top offsets and slopes:
        var yOffset = gs.b + ya.domain[0] * gs.h;
        var ym = -ya._m;
        var yb = -ym * ya.r2l(ya.range[0], ya.calendar);
        var x, y;

        if(xa.showgrid) {
            for(k = 0; k < xVals.length; k++) {
                x = xa._offset + xa.l2p(xVals[k].x);
                push('grid', xa, x, yOffset, x, yOffset + ya._length);
            }
        }
        if(ya.showgrid) {
            for(k = 0; k < yVals.length; k++) {
                y = yOffset + yb + ym * yVals[k].x;
                push('grid', ya, xa._offset, y, xa._offset + xa._length, y);
            }
        }
        if(shouldShowZeroLine(gd, xa, ya)) {
            x = xa._offset + xa.l2p(0);
            push('zeroline', xa, x, yOffset, x, yOffset + ya._length);
        }
        if(shouldShowZeroLine(gd, ya, xa)) {
            y = yOffset + yb + 0;
            push('zeroline', ya, xa._offset, y, xa._offset + xa._length, y);
        }
    }

    var gridBatches = [];
    for(k in lookup) {
        gridBatches.push(lookup[k]);
    }

    return gridBatches;
}

function clean(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var lookup = {};
    var i;

    if(oldFullLayout._splomScenes) {
        for(i = 0; i < newFullData.length; i++) {
            var newTrace = newFullData[i];
            if(newTrace.type === 'splom') {
                lookup[newTrace.uid] = 1;
            }
        }
        for(i = 0; i < oldFullData.length; i++) {
            var oldTrace = oldFullData[i];
            if(!lookup[oldTrace.uid]) {
                var scene = oldFullLayout._splomScenes[oldTrace.uid];
                if(scene && scene.destroy) scene.destroy();
                // must first set scene to null in order to get garbage collected
                oldFullLayout._splomScenes[oldTrace.uid] = null;
                delete oldFullLayout._splomScenes[oldTrace.uid];
            }
        }
    }

    if(Object.keys(oldFullLayout._splomScenes || {}).length === 0) {
        delete oldFullLayout._splomScenes;
    }

    if(oldFullLayout._splomGrid &&
        (!newFullLayout._hasOnlyLargeSploms && oldFullLayout._hasOnlyLargeSploms)) {
        // must first set scene to null in order to get garbage collected
        oldFullLayout._splomGrid.destroy();
        oldFullLayout._splomGrid = null;
        delete oldFullLayout._splomGrid;
    }

    Cartesian.clean(newFullData, newFullLayout, oldFullData, oldFullLayout);
}

function updateFx(gd) {
    Cartesian.updateFx(gd);

    var fullLayout = gd._fullLayout;
    var dragmode = fullLayout.dragmode;

    // unset selection styles when coming out of a selection mode
    if(dragmode === 'zoom' || dragmode === 'pan') {
        var cd = gd.calcdata;

        for(var i = 0; i < cd.length; i++) {
            var cd0 = cd[i][0];
            var trace = cd0.trace;

            if(trace.type === 'splom') {
                var scene = fullLayout._splomScenes[trace.uid];
                if(scene.selectBatch === null) {
                    scene.matrix.update(scene.matrixOptions, null);
                }
            }
        }
    }
}

module.exports = {
    name: SPLOM,
    attr: Cartesian.attr,
    attrRegex: Cartesian.attrRegex,
    layoutAttributes: Cartesian.layoutAttributes,
    supplyLayoutDefaults: Cartesian.supplyLayoutDefaults,
    drawFramework: Cartesian.drawFramework,
    plot: plot,
    drag: drag,
    updateGrid: updateGrid,
    clean: clean,
    updateFx: updateFx,
    toSVG: Cartesian.toSVG
};

},{"../../lib/prepare_regl":710,"../../plots/cartesian":756,"../../plots/cartesian/axes":745,"../../plots/cartesian/axis_ids":748,"../../plots/get_data":781,"../../registry":826,"regl-line2d":480}],1128:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');

var attributes = _dereq_('./attributes');
var subTypes = _dereq_('../scatter/subtypes');
var handleMarkerDefaults = _dereq_('../scatter/marker_defaults');
var mergeLength = _dereq_('../parcoords/merge_length');
var OPEN_RE = /-open/;

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var dimensions = handleArrayContainerDefaults(traceIn, traceOut, {
        name: 'dimensions',
        handleItemDefaults: dimensionDefaults
    });

    var showDiag = coerce('diagonal.visible');
    var showUpper = coerce('showupperhalf');
    var showLower = coerce('showlowerhalf');

    var dimLength = mergeLength(traceOut, dimensions, 'values');

    if(!dimLength || (!showDiag && !showUpper && !showLower)) {
        traceOut.visible = false;
        return;
    }

    coerce('text');
    coerce('hovertext');
    coerce('hovertemplate');

    handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce);

    var isOpen = OPEN_RE.test(traceOut.marker.symbol);
    var isBubble = subTypes.isBubble(traceOut);
    coerce('marker.line.width', isOpen || isBubble ? 1 : 0);

    handleAxisDefaults(traceIn, traceOut, layout, coerce);

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};

function dimensionDefaults(dimIn, dimOut) {
    function coerce(attr, dflt) {
        return Lib.coerce(dimIn, dimOut, attributes.dimensions, attr, dflt);
    }

    coerce('label');
    var values = coerce('values');

    if(!(values && values.length)) dimOut.visible = false;
    else coerce('visible');

    coerce('axis.type');
    coerce('axis.matches');
}

function handleAxisDefaults(traceIn, traceOut, layout, coerce) {
    var dimensions = traceOut.dimensions;
    var dimLength = dimensions.length;
    var showUpper = traceOut.showupperhalf;
    var showLower = traceOut.showlowerhalf;
    var showDiag = traceOut.diagonal.visible;
    var i, j;

    var xAxesDflt = new Array(dimLength);
    var yAxesDflt = new Array(dimLength);

    for(i = 0; i < dimLength; i++) {
        var suffix = i ? i + 1 : '';
        xAxesDflt[i] = 'x' + suffix;
        yAxesDflt[i] = 'y' + suffix;
    }

    var xaxes = coerce('xaxes', xAxesDflt);
    var yaxes = coerce('yaxes', yAxesDflt);

    // build list of [x,y] axis corresponding to each dimensions[i],
    // very useful for passing options to regl-splom
    var diag = traceOut._diag = new Array(dimLength);

    // lookup for 'drawn' x|y axes, to avoid costly indexOf downstream
    traceOut._xaxes = {};
    traceOut._yaxes = {};

    // list of 'drawn' x|y axes, use to generate list of subplots
    var xList = [];
    var yList = [];

    function fillAxisStashes(axId, counterAxId, dim, list) {
        if(!axId) return;

        var axLetter = axId.charAt(0);
        var stash = layout._splomAxes[axLetter];

        traceOut['_' + axLetter + 'axes'][axId] = 1;
        list.push(axId);

        if(!(axId in stash)) {
            var s = stash[axId] = {};
            if(dim) {
                s.label = dim.label || '';
                if(dim.visible && dim.axis) {
                    if(dim.axis.type) s.type = dim.axis.type;
                    if(dim.axis.matches) s.matches = counterAxId;
                }
            }
        }
    }

    // cases where showDiag and showLower or showUpper are false
    // no special treatment as the 'drawn' x-axes and y-axes no longer match
    // the dimensions items and xaxes|yaxes 1-to-1
    var mustShiftX = !showDiag && !showLower;
    var mustShiftY = !showDiag && !showUpper;

    for(i = 0; i < dimLength; i++) {
        var dim = dimensions[i];
        var i0 = i === 0;
        var iN = i === dimLength - 1;

        var xaId = (i0 && mustShiftX) || (iN && mustShiftY) ?
            undefined :
            xaxes[i];

        var yaId = (i0 && mustShiftY) || (iN && mustShiftX) ?
            undefined :
            yaxes[i];

        fillAxisStashes(xaId, yaId, dim, xList);
        fillAxisStashes(yaId, xaId, dim, yList);
        diag[i] = [xaId, yaId];
    }

    // fill in splom subplot keys
    for(i = 0; i < xList.length; i++) {
        for(j = 0; j < yList.length; j++) {
            var id = xList[i] + yList[j];

            if(i > j && showUpper) {
                layout._splomSubplots[id] = 1;
            } else if(i < j && showLower) {
                layout._splomSubplots[id] = 1;
            } else if(i === j && (showDiag || !showLower || !showUpper)) {
                // need to include diagonal subplots when
                // hiding one half and the diagonal
                layout._splomSubplots[id] = 1;
            }
        }
    }

    // when lower half is omitted, or when just the diagonal is gone,
    // override grid default to make sure axes remain on
    // the left/bottom of the plot area
    if(!showLower || (!showDiag && showUpper && showLower)) {
        layout._splomGridDflt.xside = 'bottom';
        layout._splomGridDflt.yside = 'left';
    }
}

},{"../../lib":697,"../../plots/array_container_defaults":741,"../parcoords/merge_length":1020,"../scatter/marker_defaults":1067,"../scatter/subtypes":1072,"./attributes":1126}],1129:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var createMatrix = _dereq_('regl-splom');
var arrayRange = _dereq_('array-range');

var Registry = _dereq_('../../registry');
var Grid = _dereq_('../../components/grid');
var Lib = _dereq_('../../lib');
var AxisIDs = _dereq_('../../plots/cartesian/axis_ids');

var subTypes = _dereq_('../scatter/subtypes');
var calcMarkerSize = _dereq_('../scatter/calc').calcMarkerSize;
var calcAxisExpansion = _dereq_('../scatter/calc').calcAxisExpansion;
var calcColorscale = _dereq_('../scatter/colorscale_calc');
var convertMarkerSelection = _dereq_('../scattergl/convert').markerSelection;
var convertMarkerStyle = _dereq_('../scattergl/convert').markerStyle;
var calcHover = _dereq_('../scattergl').calcHover;

var BADNUM = _dereq_('../../constants/numerical').BADNUM;
var TOO_MANY_POINTS = _dereq_('../scattergl/constants').TOO_MANY_POINTS;

function calc(gd, trace) {
    var dimensions = trace.dimensions;
    var commonLength = trace._length;
    var opts = {};
    // 'c' for calculated, 'l' for linear,
    // only differ here for log axes, pass ldata to createMatrix as 'data'
    var cdata = opts.cdata = [];
    var ldata = opts.data = [];
    // keep track of visible dimensions
    var visibleDims = trace._visibleDims = [];
    var i, k, dim, xa, ya;

    function makeCalcdata(ax, dim) {
        // call makeCalcdata with fake input
        var ccol = ax.makeCalcdata({
            v: dim.values,
            vcalendar: trace.calendar
        }, 'v');

        for(var j = 0; j < ccol.length; j++) {
            ccol[j] = ccol[j] === BADNUM ? NaN : ccol[j];
        }
        cdata.push(ccol);
        ldata.push(ax.type === 'log' ? Lib.simpleMap(ccol, ax.c2l) : ccol);
    }

    for(i = 0; i < dimensions.length; i++) {
        dim = dimensions[i];

        if(dim.visible) {
            xa = AxisIDs.getFromId(gd, trace._diag[i][0]);
            ya = AxisIDs.getFromId(gd, trace._diag[i][1]);

            // if corresponding x & y axes don't have matching types, skip dim
            if(xa && ya && xa.type !== ya.type) {
                Lib.log('Skipping splom dimension ' + i + ' with conflicting axis types');
                continue;
            }

            if(xa) {
                makeCalcdata(xa, dim);
                if(ya && ya.type === 'category') {
                    ya._categories = xa._categories.slice();
                }
            } else {
                // should not make it here, if both xa and ya undefined
                makeCalcdata(ya, dim);
            }

            visibleDims.push(i);
        }
    }

    calcColorscale(gd, trace);
    Lib.extendFlat(opts, convertMarkerStyle(trace));

    var visibleLength = cdata.length;
    var hasTooManyPoints = (visibleLength * commonLength) > TOO_MANY_POINTS;

    // Reuse SVG scatter axis expansion routine.
    // For graphs with very large number of points and array marker.size,
    // use average marker size instead to speed things up.
    var ppad;
    if(hasTooManyPoints) {
        ppad = 2 * (opts.sizeAvg || Math.max(opts.size, 3));
    } else {
        ppad = calcMarkerSize(trace, commonLength);
    }

    for(k = 0; k < visibleDims.length; k++) {
        i = visibleDims[k];
        dim = dimensions[i];
        xa = AxisIDs.getFromId(gd, trace._diag[i][0]) || {};
        ya = AxisIDs.getFromId(gd, trace._diag[i][1]) || {};
        calcAxisExpansion(gd, trace, xa, ya, cdata[k], cdata[k], ppad);
    }

    var scene = sceneUpdate(gd, trace);
    if(!scene.matrix) scene.matrix = true;
    scene.matrixOptions = opts;

    scene.selectedOptions = convertMarkerSelection(trace, trace.selected);
    scene.unselectedOptions = convertMarkerSelection(trace, trace.unselected);

    return [{x: false, y: false, t: {}, trace: trace}];
}

function sceneUpdate(gd, trace) {
    var fullLayout = gd._fullLayout;
    var uid = trace.uid;

    // must place ref to 'scene' in fullLayout, so that:
    // - it can be relinked properly on updates
    // - it can be destroyed properly when needed
    var splomScenes = fullLayout._splomScenes;
    if(!splomScenes) splomScenes = fullLayout._splomScenes = {};

    var reset = {dirty: true};

    var first = {
        selectBatch: null,
        unselectBatch: null,
        matrix: false,
        select: null
    };

    var scene = splomScenes[trace.uid];

    if(!scene) {
        scene = splomScenes[uid] = Lib.extendFlat({}, reset, first);

        scene.draw = function draw() {
            if(scene.matrix && scene.matrix.draw) {
                if(scene.selectBatch) {
                    scene.matrix.draw(scene.unselectBatch, scene.selectBatch);
                } else {
                    scene.matrix.draw();
                }
            }

            scene.dirty = false;
        };

        // remove scene resources
        scene.destroy = function destroy() {
            if(scene.matrix && scene.matrix.destroy) {
                scene.matrix.destroy();
            }
            scene.matrixOptions = null;
            scene.selectBatch = null;
            scene.unselectBatch = null;
            scene = null;
        };
    }

    // In case if we have scene from the last calc - reset data
    if(!scene.dirty) {
        Lib.extendFlat(scene, reset);
    }

    return scene;
}

function plot(gd, _, splomCalcData) {
    if(!splomCalcData.length) return;

    for(var i = 0; i < splomCalcData.length; i++) {
        plotOne(gd, splomCalcData[i][0]);
    }
}

function plotOne(gd, cd0) {
    var fullLayout = gd._fullLayout;
    var gs = fullLayout._size;
    var trace = cd0.trace;
    var stash = cd0.t;
    var scene = fullLayout._splomScenes[trace.uid];
    var matrixOpts = scene.matrixOptions;
    var cdata = matrixOpts.cdata;
    var regl = fullLayout._glcanvas.data()[0].regl;
    var dragmode = fullLayout.dragmode;
    var xa, ya;
    var i, j, k;

    if(cdata.length === 0) return;

    // augment options with proper upper/lower halves
    // regl-splom's default grid starts from bottom-left
    matrixOpts.lower = trace.showupperhalf;
    matrixOpts.upper = trace.showlowerhalf;
    matrixOpts.diagonal = trace.diagonal.visible;

    var visibleDims = trace._visibleDims;
    var visibleLength = cdata.length;
    var viewOpts = scene.viewOpts = {};
    viewOpts.ranges = new Array(visibleLength);
    viewOpts.domains = new Array(visibleLength);

    for(k = 0; k < visibleDims.length; k++) {
        i = visibleDims[k];

        var rng = viewOpts.ranges[k] = new Array(4);
        var dmn = viewOpts.domains[k] = new Array(4);

        xa = AxisIDs.getFromId(gd, trace._diag[i][0]);
        if(xa) {
            rng[0] = xa._rl[0];
            rng[2] = xa._rl[1];
            dmn[0] = xa.domain[0];
            dmn[2] = xa.domain[1];
        }

        ya = AxisIDs.getFromId(gd, trace._diag[i][1]);
        if(ya) {
            rng[1] = ya._rl[0];
            rng[3] = ya._rl[1];
            dmn[1] = ya.domain[0];
            dmn[3] = ya.domain[1];
        }
    }

    viewOpts.viewport = [gs.l, gs.b, gs.w + gs.l, gs.h + gs.b];

    if(scene.matrix === true) {
        scene.matrix = createMatrix(regl);
    }

    var clickSelectEnabled = fullLayout.clickmode.indexOf('select') > -1;
    var selectMode = dragmode === 'lasso' || dragmode === 'select' ||
      !!trace.selectedpoints || clickSelectEnabled;
    scene.selectBatch = null;
    scene.unselectBatch = null;

    if(selectMode) {
        var commonLength = trace._length;

        if(!scene.selectBatch) {
            scene.selectBatch = [];
            scene.unselectBatch = [];
        }

        // regenerate scene batch, if traces number changed during selection
        if(trace.selectedpoints) {
            scene.selectBatch = trace.selectedpoints;

            var selPts = trace.selectedpoints;
            var selDict = {};
            for(i = 0; i < selPts.length; i++) {
                selDict[selPts[i]] = true;
            }
            var unselPts = [];
            for(i = 0; i < commonLength; i++) {
                if(!selDict[i]) unselPts.push(i);
            }
            scene.unselectBatch = unselPts;
        }

        // precalculate px coords since we are not going to pan during select
        var xpx = stash.xpx = new Array(visibleLength);
        var ypx = stash.ypx = new Array(visibleLength);

        for(k = 0; k < visibleDims.length; k++) {
            i = visibleDims[k];

            xa = AxisIDs.getFromId(gd, trace._diag[i][0]);
            if(xa) {
                xpx[k] = new Array(commonLength);
                for(j = 0; j < commonLength; j++) {
                    xpx[k][j] = xa.c2p(cdata[k][j]);
                }
            }

            ya = AxisIDs.getFromId(gd, trace._diag[i][1]);
            if(ya) {
                ypx[k] = new Array(commonLength);
                for(j = 0; j < commonLength; j++) {
                    ypx[k][j] = ya.c2p(cdata[k][j]);
                }
            }
        }

        if(scene.selectBatch) {
            scene.matrix.update(matrixOpts, matrixOpts);
            scene.matrix.update(scene.unselectedOptions, scene.selectedOptions);
            scene.matrix.update(viewOpts, viewOpts);
        }
        else {
            // delete selection pass
            scene.matrix.update(viewOpts, null);
        }
    }
    else {
        var opts = Lib.extendFlat({}, matrixOpts, viewOpts);
        scene.matrix.update(opts, null);
        stash.xpx = stash.ypx = null;
    }
}

function editStyle(gd, cd0) {
    var trace = cd0.trace;
    var scene = gd._fullLayout._splomScenes[trace.uid];

    if(scene) {
        calcColorscale(gd, trace);

        Lib.extendFlat(scene.matrixOptions, convertMarkerStyle(trace));
        // TODO [un]selected styles?

        var opts = Lib.extendFlat({}, scene.matrixOptions, scene.viewOpts);

        // TODO this is too long for arrayOk attributes!
        scene.matrix.update(opts, null);
    }
}

function hoverPoints(pointData, xval, yval) {
    var cd = pointData.cd;
    var trace = cd[0].trace;
    var scene = pointData.scene;
    var cdata = scene.matrixOptions.cdata;
    var xa = pointData.xa;
    var ya = pointData.ya;
    var xpx = xa.c2p(xval);
    var ypx = ya.c2p(yval);
    var maxDistance = pointData.distance;

    var xi = getDimIndex(trace, xa);
    var yi = getDimIndex(trace, ya);
    if(xi === false || yi === false) return [pointData];

    var x = cdata[xi];
    var y = cdata[yi];

    var id, dxy;
    var minDist = maxDistance;

    for(var i = 0; i < x.length; i++) {
        var ptx = x[i];
        var pty = y[i];
        var dx = xa.c2p(ptx) - xpx;
        var dy = ya.c2p(pty) - ypx;
        var dist = Math.sqrt(dx * dx + dy * dy);

        if(dist < minDist) {
            minDist = dxy = dist;
            id = i;
        }
    }

    pointData.index = id;
    pointData.distance = minDist;
    pointData.dxy = dxy;

    if(id === undefined) return [pointData];

    calcHover(pointData, x, y, trace);

    return [pointData];
}

function selectPoints(searchInfo, selectionTester) {
    var cd = searchInfo.cd;
    var trace = cd[0].trace;
    var stash = cd[0].t;
    var scene = searchInfo.scene;
    var cdata = scene.matrixOptions.cdata;
    var xa = searchInfo.xaxis;
    var ya = searchInfo.yaxis;
    var selection = [];
    var i;

    if(!scene) return selection;

    var hasOnlyLines = (!subTypes.hasMarkers(trace) && !subTypes.hasText(trace));
    if(trace.visible !== true || hasOnlyLines) return selection;

    var xi = getDimIndex(trace, xa);
    var yi = getDimIndex(trace, ya);
    if(xi === false || yi === false) return selection;

    var xpx = stash.xpx[xi];
    var ypx = stash.ypx[yi];
    var x = cdata[xi];
    var y = cdata[yi];

    // degenerate polygon does not enable selection
    // filter out points by visible scatter ones
    var els = null;
    var unels = null;
    if(selectionTester !== false && !selectionTester.degenerate) {
        els = [], unels = [];
        for(i = 0; i < x.length; i++) {
            if(selectionTester.contains([xpx[i], ypx[i]], null, i, searchInfo)) {
                els.push(i);
                selection.push({
                    pointNumber: i,
                    x: x[i],
                    y: y[i]
                });
            }
            else {
                unels.push(i);
            }
        }
    } else {
        unels = arrayRange(stash.count);
    }

    // make sure selectBatch is created
    if(!scene.selectBatch) {
        scene.selectBatch = [];
        scene.unselectBatch = [];
    }

    if(!scene.selectBatch) {
        // enter every trace select mode
        for(i = 0; i < scene.count; i++) {
            scene.selectBatch = [];
            scene.unselectBatch = [];
        }
        // we should turn scatter2d into unselected once we have any points selected
        scene.matrix.update(scene.unselectedOptions, scene.selectedOptions);
    }

    scene.selectBatch = els;
    scene.unselectBatch = unels;


    return selection;
}

function getDimIndex(trace, ax) {
    var axId = ax._id;
    var axLetter = axId.charAt(0);
    var ind = {x: 0, y: 1}[axLetter];
    var visibleDims = trace._visibleDims;

    for(var k = 0; k < visibleDims.length; k++) {
        var i = visibleDims[k];
        if(trace._diag[i][ind] === axId) return k;
    }
    return false;
}

module.exports = {
    moduleType: 'trace',
    name: 'splom',

    basePlotModule: _dereq_('./base_plot'),
    categories: ['gl', 'regl', 'cartesian', 'symbols', 'showLegend', 'scatter-like'],

    attributes: _dereq_('./attributes'),
    supplyDefaults: _dereq_('./defaults'),
    colorbar: _dereq_('../scatter/marker_colorbar'),

    calc: calc,
    plot: plot,
    hoverPoints: hoverPoints,
    selectPoints: selectPoints,
    editStyle: editStyle,

    meta: {
        
    }
};

// splom traces use the 'grid' component to generate their axes,
// register it here
Registry.register(Grid);

},{"../../components/grid":617,"../../constants/numerical":674,"../../lib":697,"../../plots/cartesian/axis_ids":748,"../../registry":826,"../scatter/calc":1049,"../scatter/colorscale_calc":1051,"../scatter/marker_colorbar":1066,"../scatter/subtypes":1072,"../scattergl":1101,"../scattergl/constants":1098,"../scattergl/convert":1099,"./attributes":1126,"./base_plot":1127,"./defaults":1128,"array-range":55,"regl-splom":482}],1130:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var mesh3dAttrs = _dereq_('../mesh3d/attributes');
var baseAttrs = _dereq_('../../plots/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;

var attrs = {
    x: {
        valType: 'data_array',
        
        editType: 'calc+clearAxisTypes',
        
    },
    y: {
        valType: 'data_array',
        
        editType: 'calc+clearAxisTypes',
        
    },
    z: {
        valType: 'data_array',
        
        editType: 'calc+clearAxisTypes',
        
    },

    u: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    v: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    w: {
        valType: 'data_array',
        editType: 'calc',
        
    },

    starts: {
        x: {
            valType: 'data_array',
            editType: 'calc',
            
        },
        y: {
            valType: 'data_array',
            editType: 'calc',
            
        },
        z: {
            valType: 'data_array',
            editType: 'calc',
            
        },
        editType: 'calc'
    },

    maxdisplayed: {
        valType: 'integer',
        min: 0,
        dflt: 1000,
        
        editType: 'calc',
        
    },

    // TODO
    //
    // Should add 'absolute' (like cone traces have), but currently gl-streamtube3d's
    // `absoluteTubeSize` doesn't behave well enough for our needs.
    //
    // 'fixed' would be a nice addition to plot stream 'lines', see
    // https://github.com/plotly/plotly.js/commit/812be20750e21e0a1831975001c248d365850f73#r29129877
    //
    // sizemode: {
    //     valType: 'enumerated',
    //     values: ['scaled', 'absolute', 'fixed'],
    //     dflt: 'scaled',
    //     
    //     editType: 'calc',
    //     
    // },

    sizeref: {
        valType: 'number',
        
        editType: 'calc',
        min: 0,
        dflt: 1,
        
    },

    text: {
        valType: 'string',
        
        dflt: '',
        editType: 'calc',
        
    },
    hovertext: {
        valType: 'string',
        
        dflt: '',
        editType: 'calc',
        
    },
    hovertemplate: hovertemplateAttrs({editType: 'calc'}, {
        keys: [
            'tubex', 'tubey', 'tubez',
            'tubeu', 'tubev', 'tubew',
            'norm', 'divergence'
        ]
    })
};

extendFlat(attrs, colorscaleAttrs('', {
    colorAttr: 'u/v/w norm',
    showScaleDflt: true,
    editTypeOverride: 'calc'
}), {
    colorbar: colorbarAttrs
});

var fromMesh3d = ['opacity', 'lightposition', 'lighting'];
fromMesh3d.forEach(function(k) {
    attrs[k] = mesh3dAttrs[k];
});

attrs.hoverinfo = extendFlat({}, baseAttrs.hoverinfo, {
    editType: 'calc',
    flags: ['x', 'y', 'z', 'u', 'v', 'w', 'norm', 'divergence', 'text', 'name'],
    dflt: 'x+y+z+norm+text+name'
});

attrs.transforms = undefined;

module.exports = attrs;

},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plots/attributes":742,"../mesh3d/attributes":991}],1131:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorscaleCalc = _dereq_('../../components/colorscale/calc');

module.exports = function calc(gd, trace) {
    var i;

    var u = trace.u;
    var v = trace.v;
    var w = trace.w;
    var x = trace.x;
    var y = trace.y;
    var z = trace.z;
    var len = Math.min(x.length, y.length, z.length, u.length, v.length, w.length);

    var slen = 0;
    var startx, starty, startz;
    if(trace.starts) {
        startx = trace.starts.x || [];
        starty = trace.starts.y || [];
        startz = trace.starts.z || [];
        slen = Math.min(startx.length, starty.length, startz.length);
    }

    var normMax = 0;
    var normMin = Infinity;

    for(i = 0; i < len; i++) {
        var uu = u[i];
        var vv = v[i];
        var ww = w[i];
        var norm = Math.sqrt(uu * uu + vv * vv + ww * ww);

        normMax = Math.max(normMax, norm);
        normMin = Math.min(normMin, norm);
    }

    colorscaleCalc(gd, trace, {
        vals: [normMin, normMax],
        containerStr: '',
        cLetter: 'c'
    });

    var xMax = -Infinity;
    var xMin = Infinity;
    var yMax = -Infinity;
    var yMin = Infinity;
    var zMax = -Infinity;
    var zMin = Infinity;

    for(i = 0; i < len; i++) {
        var xx = x[i];
        xMax = Math.max(xMax, xx);
        xMin = Math.min(xMin, xx);

        var yy = y[i];
        yMax = Math.max(yMax, yy);
        yMin = Math.min(yMin, yy);

        var zz = z[i];
        zMax = Math.max(zMax, zz);
        zMin = Math.min(zMin, zz);
    }
    for(i = 0; i < slen; i++) {
        var sx = startx[i];
        xMax = Math.max(xMax, sx);
        xMin = Math.min(xMin, sx);

        var sy = starty[i];
        yMax = Math.max(yMax, sy);
        yMin = Math.min(yMin, sy);

        var sz = startz[i];
        zMax = Math.max(zMax, sz);
        zMin = Math.min(zMin, sz);
    }

    trace._len = len;
    trace._slen = slen;
    trace._normMax = normMax;
    trace._xbnds = [xMin, xMax];
    trace._ybnds = [yMin, yMax];
    trace._zbnds = [zMin, zMax];
};

},{"../../components/colorscale/calc":582}],1132:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var tube2mesh = _dereq_('gl-streamtube3d');
var createTubeMesh = tube2mesh.createTubeMesh;

var Lib = _dereq_('../../lib');
var parseColorScale = _dereq_('../../lib/gl_format_color').parseColorScale;
var zip3 = _dereq_('../../plots/gl3d/zip3');

var axisName2scaleIndex = {xaxis: 0, yaxis: 1, zaxis: 2};

function Streamtube(scene, uid) {
    this.scene = scene;
    this.uid = uid;
    this.mesh = null;
    this.data = null;
}

var proto = Streamtube.prototype;

proto.handlePick = function(selection) {
    var sceneLayout = this.scene.fullSceneLayout;
    var dataScale = this.scene.dataScale;

    function fromDataScale(v, axisName) {
        var ax = sceneLayout[axisName];
        var scale = dataScale[axisName2scaleIndex[axisName]];
        return ax.l2c(v) / scale;
    }

    if(selection.object === this.mesh) {
        var pos = selection.data.position;
        var uvx = selection.data.velocity;

        selection.traceCoordinate = [
            fromDataScale(pos[0], 'xaxis'),
            fromDataScale(pos[1], 'yaxis'),
            fromDataScale(pos[2], 'zaxis'),

            fromDataScale(uvx[0], 'xaxis'),
            fromDataScale(uvx[1], 'yaxis'),
            fromDataScale(uvx[2], 'zaxis'),

            // u/v/w norm
            selection.data.intensity * this.data._normMax,
            // divergence
            selection.data.divergence
        ];

        selection.textLabel = this.data.hovertext || this.data.text;

        return true;
    }
};

function distinctVals(col) {
    return Lib.distinctVals(col).vals;
}

function getDfltStartingPositions(vec) {
    var len = vec.length;
    var s;

    if(len > 2) {
        s = vec.slice(1, len - 1);
    } else if(len === 2) {
        s = [(vec[0] + vec[1]) / 2];
    } else {
        s = vec;
    }
    return s;
}

function getBoundPads(vec) {
    var len = vec.length;
    if(len === 1) {
        return [0.5, 0.5];
    } else {
        return [vec[1] - vec[0], vec[len - 1] - vec[len - 2]];
    }
}

function convert(scene, trace) {
    var sceneLayout = scene.fullSceneLayout;
    var dataScale = scene.dataScale;
    var len = trace._len;
    var tubeOpts = {};

    function toDataCoords(arr, axisName) {
        var ax = sceneLayout[axisName];
        var scale = dataScale[axisName2scaleIndex[axisName]];
        return Lib.simpleMap(arr, function(v) { return ax.d2l(v) * scale; });
    }

    tubeOpts.vectors = zip3(
        toDataCoords(trace.u, 'xaxis'),
        toDataCoords(trace.v, 'yaxis'),
        toDataCoords(trace.w, 'zaxis'),
        len
    );

    var valsx = distinctVals(trace.x.slice(0, len));
    var valsy = distinctVals(trace.y.slice(0, len));
    var valsz = distinctVals(trace.z.slice(0, len));

    // Over-specified mesh case, this would error in tube2mesh
    if(valsx.length * valsy.length * valsz.length > len) {
        return {positions: [], cells: []};
    }

    var meshx = toDataCoords(valsx, 'xaxis');
    var meshy = toDataCoords(valsy, 'yaxis');
    var meshz = toDataCoords(valsz, 'zaxis');

    tubeOpts.meshgrid = [meshx, meshy, meshz];

    if(trace.starts) {
        var slen = trace._slen;
        tubeOpts.startingPositions = zip3(
            toDataCoords(trace.starts.x.slice(0, slen), 'xaxis'),
            toDataCoords(trace.starts.y.slice(0, slen), 'yaxis'),
            toDataCoords(trace.starts.z.slice(0, slen), 'zaxis')
        );
    } else {
        // Default starting positions:
        //
        // if len>2, cut xz plane at min-y,
        // takes all x/y/z pts on that plane except those on the edges
        // to generate "well-defined" tubes,
        //
        // if len=2, take position halfway between two the pts,
        //
        // if len=1, take that pt
        var sy0 = meshy[0];
        var sx = getDfltStartingPositions(meshx);
        var sz = getDfltStartingPositions(meshz);
        var startingPositions = new Array(sx.length * sz.length);
        var m = 0;

        for(var i = 0; i < sx.length; i++) {
            for(var k = 0; k < sz.length; k++) {
                startingPositions[m++] = [sx[i], sy0, sz[k]];
            }
        }
        tubeOpts.startingPositions = startingPositions;
    }

    tubeOpts.colormap = parseColorScale(trace);
    tubeOpts.tubeSize = trace.sizeref;
    tubeOpts.maxLength = trace.maxdisplayed;

    // add some padding around the bounds
    // to e.g. allow tubes starting from a slice of the x/y/z mesh
    // to go beyond bounds a little bit w/o getting clipped
    var xbnds = toDataCoords(trace._xbnds, 'xaxis');
    var ybnds = toDataCoords(trace._ybnds, 'yaxis');
    var zbnds = toDataCoords(trace._zbnds, 'zaxis');
    var xpads = getBoundPads(meshx);
    var ypads = getBoundPads(meshy);
    var zpads = getBoundPads(meshz);

    var bounds = [
        [xbnds[0] - xpads[0], ybnds[0] - ypads[0], zbnds[0] - zpads[0]],
        [xbnds[1] + xpads[1], ybnds[1] + ypads[1], zbnds[1] + zpads[1]]
    ];

    var meshData = tube2mesh(tubeOpts, bounds);

    // N.B. cmin/cmax correspond to the min/max vector norm
    // in the u/v/w arrays, which in general is NOT equal to max
    // intensity that colors the tubes.
    meshData.vertexIntensityBounds = [trace.cmin / trace._normMax, trace.cmax / trace._normMax];

    // pass gl-mesh3d lighting attributes
    var lp = trace.lightposition;
    meshData.lightPosition = [lp.x, lp.y, lp.z];
    meshData.ambient = trace.lighting.ambient;
    meshData.diffuse = trace.lighting.diffuse;
    meshData.specular = trace.lighting.specular;
    meshData.roughness = trace.lighting.roughness;
    meshData.fresnel = trace.lighting.fresnel;
    meshData.opacity = trace.opacity;

    // stash autorange pad value
    trace._pad = meshData.tubeScale * trace.sizeref * 2;

    return meshData;
}

proto.update = function(data) {
    this.data = data;

    var meshData = convert(this.scene, data);
    this.mesh.update(meshData);
};

proto.dispose = function() {
    this.scene.glplot.remove(this.mesh);
    this.mesh.dispose();
};

function createStreamtubeTrace(scene, data) {
    var gl = scene.glplot.gl;

    var meshData = convert(scene, data);
    var mesh = createTubeMesh(gl, meshData);

    var streamtube = new Streamtube(scene, data.uid);
    streamtube.mesh = mesh;
    streamtube.data = data;
    mesh._trace = streamtube;

    scene.glplot.add(mesh);

    return streamtube;
}

module.exports = createStreamtubeTrace;

},{"../../lib":697,"../../lib/gl_format_color":694,"../../plots/gl3d/zip3":797,"gl-streamtube3d":306}],1133:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var u = coerce('u');
    var v = coerce('v');
    var w = coerce('w');

    var x = coerce('x');
    var y = coerce('y');
    var z = coerce('z');

    if(
        !u || !u.length || !v || !v.length || !w || !w.length ||
        !x || !x.length || !y || !y.length || !z || !z.length
    ) {
        traceOut.visible = false;
        return;
    }

    coerce('starts.x');
    coerce('starts.y');
    coerce('starts.z');

    coerce('maxdisplayed');
    coerce('sizeref');

    coerce('lighting.ambient');
    coerce('lighting.diffuse');
    coerce('lighting.specular');
    coerce('lighting.roughness');
    coerce('lighting.fresnel');
    coerce('lightposition.x');
    coerce('lightposition.y');
    coerce('lightposition.z');

    colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'c'});

    coerce('text');
    coerce('hovertext');
    coerce('hovertemplate');

    // disable 1D transforms (for now)
    // x/y/z and u/v/w have matching lengths,
    // but they don't have to match with starts.(x|y|z)
    traceOut._length = null;
};

},{"../../components/colorscale/defaults":584,"../../lib":697,"./attributes":1130}],1134:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'trace',
    name: 'streamtube',
    basePlotModule: _dereq_('../../plots/gl3d'),
    categories: ['gl3d'],

    attributes: _dereq_('./attributes'),
    supplyDefaults: _dereq_('./defaults'),
    colorbar: {
        min: 'cmin',
        max: 'cmax'
    },
    calc: _dereq_('./calc'),
    plot: _dereq_('./convert'),
    eventData: function(out, pt) {
        out.tubex = out.x;
        out.tubey = out.y;
        out.tubez = out.z;

        out.tubeu = pt.traceCoordinate[3];
        out.tubev = pt.traceCoordinate[4];
        out.tubew = pt.traceCoordinate[5];

        out.norm = pt.traceCoordinate[6];
        out.divergence = pt.traceCoordinate[7];

        // Does not correspond to input x/y/z, so delete them
        delete out.x;
        delete out.y;
        delete out.z;

        return out;
    },

    meta: {
        
    }
};

},{"../../plots/gl3d":786,"./attributes":1130,"./calc":1131,"./convert":1132,"./defaults":1133}],1135:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Color = _dereq_('../../components/color');
var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var baseAttrs = _dereq_('../../plots/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;

function makeContourProjAttr(axLetter) {
    return {
        valType: 'boolean',
        
        dflt: false,
        
    };
}

function makeContourAttr(axLetter) {
    return {
        show: {
            valType: 'boolean',
            
            dflt: false,
            
        },
        project: {
            x: makeContourProjAttr('x'),
            y: makeContourProjAttr('y'),
            z: makeContourProjAttr('z')
        },
        color: {
            valType: 'color',
            
            dflt: Color.defaultLine,
            
        },
        usecolormap: {
            valType: 'boolean',
            
            dflt: false,
            
        },
        width: {
            valType: 'number',
            
            min: 1,
            max: 16,
            dflt: 2,
            
        },
        highlight: {
            valType: 'boolean',
            
            dflt: true,
            
        },
        highlightcolor: {
            valType: 'color',
            
            dflt: Color.defaultLine,
            
        },
        highlightwidth: {
            valType: 'number',
            
            min: 1,
            max: 16,
            dflt: 2,
            
        }
    };
}

var attrs = module.exports = overrideAll(extendFlat({
    z: {
        valType: 'data_array',
        
    },
    x: {
        valType: 'data_array',
        
    },
    y: {
        valType: 'data_array',
        
    },

    text: {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        
    },
    hovertext: {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        
    },
    hovertemplate: hovertemplateAttrs(),

    surfacecolor: {
        valType: 'data_array',
        
    },
},

colorscaleAttrs('', {
    colorAttr: 'z or surfacecolor',
    showScaleDflt: true,
    autoColorDflt: false,
    editTypeOverride: 'calc'
}), {
    colorbar: colorbarAttrs,

    contours: {
        x: makeContourAttr('x'),
        y: makeContourAttr('y'),
        z: makeContourAttr('z')
    },
    hidesurface: {
        valType: 'boolean',
        
        dflt: false,
        
    },

    lightposition: {
        x: {
            valType: 'number',
            
            min: -1e5,
            max: 1e5,
            dflt: 10,
            
        },
        y: {
            valType: 'number',
            
            min: -1e5,
            max: 1e5,
            dflt: 1e4,
            
        },
        z: {
            valType: 'number',
            
            min: -1e5,
            max: 1e5,
            dflt: 0,
            
        }
    },

    lighting: {
        ambient: {
            valType: 'number',
            
            min: 0.00,
            max: 1.0,
            dflt: 0.8,
            
        },
        diffuse: {
            valType: 'number',
            
            min: 0.00,
            max: 1.00,
            dflt: 0.8,
            
        },
        specular: {
            valType: 'number',
            
            min: 0.00,
            max: 2.00,
            dflt: 0.05,
            
        },
        roughness: {
            valType: 'number',
            
            min: 0.00,
            max: 1.00,
            dflt: 0.5,
            
        },
        fresnel: {
            valType: 'number',
            
            min: 0.00,
            max: 5.00,
            dflt: 0.2,
            
        }
    },

    opacity: {
        valType: 'number',
        
        min: 0,
        max: 1,
        dflt: 1,
        
    },

    _deprecated: {
        zauto: extendFlat({}, colorscaleAttrs.zauto, {
            
        }),
        zmin: extendFlat({}, colorscaleAttrs.zmin, {
            
        }),
        zmax: extendFlat({}, colorscaleAttrs.zmax, {
            
        })
    },

    hoverinfo: extendFlat({}, baseAttrs.hoverinfo)
}), 'calc', 'nested');

attrs.x.editType = attrs.y.editType = attrs.z.editType = 'calc+clearAxisTypes';
attrs.transforms = undefined;

},{"../../components/color":574,"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plot_api/edit_types":728,"../../plots/attributes":742}],1136:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var colorscaleCalc = _dereq_('../../components/colorscale/calc');


// Compute auto-z and autocolorscale if applicable
module.exports = function calc(gd, trace) {
    if(trace.surfacecolor) {
        colorscaleCalc(gd, trace, {
            vals: trace.surfacecolor,
            containerStr: '',
            cLetter: 'c'
        });
    } else {
        colorscaleCalc(gd, trace, {
            vals: trace.z,
            containerStr: '',
            cLetter: 'c'
        });
    }
};

},{"../../components/colorscale/calc":582}],1137:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var createSurface = _dereq_('gl-surface3d');

var ndarray = _dereq_('ndarray');
var homography = _dereq_('ndarray-homography');
var fill = _dereq_('ndarray-fill');

var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;
var parseColorScale = _dereq_('../../lib/gl_format_color').parseColorScale;
var str2RgbaArray = _dereq_('../../lib/str2rgbarray');

function SurfaceTrace(scene, surface, uid) {
    this.scene = scene;
    this.uid = uid;
    this.surface = surface;
    this.data = null;
    this.showContour = [false, false, false];
    this.minValues = [Infinity, Infinity, Infinity];
    this.maxValues = [-Infinity, -Infinity, -Infinity];
    this.dataScaleX = 1.0;
    this.dataScaleY = 1.0;
    this.refineData = true;
}

var proto = SurfaceTrace.prototype;

proto.getXat = function(a, b, calendar, axis) {
    var v = (
       (!isArrayOrTypedArray(this.data.x)) ?
            a :
       (isArrayOrTypedArray(this.data.x[0])) ?
            this.data.x[b][a] :
            this.data.x[a]
    );

    return (calendar === undefined) ? v : axis.d2l(v, 0, calendar);
};

proto.getYat = function(a, b, calendar, axis) {
    var v = (
       (!isArrayOrTypedArray(this.data.y)) ?
            b :
       (isArrayOrTypedArray(this.data.y[0])) ?
            this.data.y[b][a] :
            this.data.y[b]
    );

    return (calendar === undefined) ? v : axis.d2l(v, 0, calendar);
};

proto.getZat = function(a, b, calendar, axis) {
    var v = (
        this.data.z[b][a]
    );

    return (calendar === undefined) ? v : axis.d2l(v, 0, calendar);
};

proto.handlePick = function(selection) {
    if(selection.object === this.surface) {

        var xRatio = (selection.data.index[0] - 1) / this.dataScaleX - 1;
        var yRatio = (selection.data.index[1] - 1) / this.dataScaleY - 1;

        var j = Math.max(Math.min(Math.round(xRatio), this.data.z[0].length - 1), 0);
        var k = Math.max(Math.min(Math.round(yRatio), this.data._ylength - 1), 0);

        selection.index = [j, k];

        selection.traceCoordinate = [
            this.getXat(j, k),
            this.getYat(j, k),
            this.getZat(j, k)
        ];

        selection.dataCoordinate = [
            this.getXat(j, k, this.data.xcalendar, this.scene.fullSceneLayout.xaxis),
            this.getYat(j, k, this.data.ycalendar, this.scene.fullSceneLayout.yaxis),
            this.getZat(j, k, this.data.zcalendar, this.scene.fullSceneLayout.zaxis)
        ];

        for(var i = 0; i < 3; i++) {
            var v = selection.dataCoordinate[i];
            if(v !== null && v !== undefined) {
                selection.dataCoordinate[i] *= this.scene.dataScale[i];
            }
        }

        var text = this.data.hovertext || this.data.text;
        if(Array.isArray(text) && text[k] && text[k][j] !== undefined) {
            selection.textLabel = text[k][j];
        } else if(text) {
            selection.textLabel = text;
        } else {
            selection.textLabel = '';
        }

        selection.data.dataCoordinate = selection.dataCoordinate.slice();

        this.surface.highlight(selection.data);

        // Snap spikes to data coordinate
        this.scene.glplot.spikes.position = selection.dataCoordinate;

        return true;
    }
};

function isColormapCircular(colormap) {
    var first = colormap[0].rgb;
    var last = colormap[colormap.length - 1].rgb;

    return (
        first[0] === last[0] &&
        first[1] === last[1] &&
        first[2] === last[2] &&
        first[3] === last[3]
    );
}

var shortPrimes = [
    2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
    101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
    211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293,
    307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397,
    401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499,
    503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599,
    601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691,
    701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797,
    809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887,
    907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997,
    1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097,
    1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193,
    1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297,
    1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399,
    1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499,
    1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597,
    1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699,
    1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,
    1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889,
    1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999,
    2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099,
    2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179,
    2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297,
    2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399,
    2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477,
    2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593,
    2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699,
    2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797,
    2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897,
    2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999
];

function getPow(a, b) {
    if(a < b) return 0;
    var n = 0;
    while(Math.floor(a % b) === 0) {
        a /= b;
        n++;
    }
    return n;
}

function getFactors(a) {
    var powers = [];
    for(var i = 0; i < shortPrimes.length; i++) {
        var b = shortPrimes[i];
        powers.push(
            getPow(a, b)
        );
    }
    return powers;
}

function smallestDivisor(a) {
    var A = getFactors(a);
    var result = a;
    for(var i = 0; i < shortPrimes.length; i++) {
        if(A[i] > 0) {
            result = shortPrimes[i];
            break;
        }
    }
    return result;
}

function leastCommonMultiple(a, b) {
    if(a < 1 || b < 1) return undefined;
    var A = getFactors(a);
    var B = getFactors(b);
    var n = 1;
    for(var i = 0; i < shortPrimes.length; i++) {
        n *= Math.pow(
            shortPrimes[i], Math.max(A[i], B[i])
        );
    }
    return n;
}

function arrayLCM(A) {
    if(A.length === 0) return undefined;
    var n = 1;
    for(var i = 0; i < A.length; i++) {
        n = leastCommonMultiple(n, A[i]);
    }
    return n;
}

proto.calcXnums = function(xlen) {
    var i;
    var nums = [];
    for(i = 1; i < xlen; i++) {
        var a = this.getXat(i - 1, 0);
        var b = this.getXat(i, 0);

        if(b !== a &&
            a !== undefined && a !== null &&
            b !== undefined && b !== null) {
            nums[i - 1] = Math.abs(b - a);
        } else {
            nums[i - 1] = 0;
        }
    }

    var totalDist = 0;
    for(i = 1; i < xlen; i++) {
        totalDist += nums[i - 1];
    }

    for(i = 1; i < xlen; i++) {
        if(nums[i - 1] === 0) {
            nums[i - 1] = 1;
        } else {
            nums[i - 1] = Math.round(totalDist / nums[i - 1]);
        }
    }

    return nums;
};

proto.calcYnums = function(ylen) {
    var i;
    var nums = [];
    for(i = 1; i < ylen; i++) {
        var a = this.getYat(0, i - 1);
        var b = this.getYat(0, i);

        if(b !== a &&
            a !== undefined && a !== null &&
            b !== undefined && b !== null) {
            nums[i - 1] = Math.abs(b - a);
        } else {
            nums[i - 1] = 0;
        }
    }

    var totalDist = 0;
    for(i = 1; i < ylen; i++) {
        totalDist += nums[i - 1];
    }

    for(i = 1; i < ylen; i++) {
        if(nums[i - 1] === 0) {
            nums[i - 1] = 1;
        } else {
            nums[i - 1] = Math.round(totalDist / nums[i - 1]);
        }
    }

    return nums;
};

var highlyComposites = [1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260];

var MIN_RESOLUTION = highlyComposites[9];
var MAX_RESOLUTION = highlyComposites[13];

proto.estimateScale = function(resSrc, axis) {
    var nums = (axis === 0) ?
        this.calcXnums(resSrc) :
        this.calcYnums(resSrc);

    var resDst = 1 + arrayLCM(nums);

    while(resDst < MIN_RESOLUTION) {
        resDst *= 2;
    }

    while(resDst > MAX_RESOLUTION) {
        resDst--;
        resDst /= smallestDivisor(resDst);
        resDst++;

        if(resDst < MIN_RESOLUTION) {
         // resDst = MIN_RESOLUTION; // option 1: use min resolution
            resDst = MAX_RESOLUTION; // option 2: use max resolution
        }
    }

    var scale = Math.round(resDst / resSrc);
    return (scale > 1) ? scale : 1;
};

proto.refineCoords = function(coords) {

    var scaleW = this.dataScaleX;
    var scaleH = this.dataScaleY;

    var width = coords[0].shape[0];
    var height = coords[0].shape[1];

    var newWidth = Math.floor(coords[0].shape[0] * scaleW + 1) | 0;
    var newHeight = Math.floor(coords[0].shape[1] * scaleH + 1) | 0;

    // Pad coords by +1
    var padWidth = 1 + width + 1;
    var padHeight = 1 + height + 1;
    var padImg = ndarray(new Float32Array(padWidth * padHeight), [padWidth, padHeight]);

    for(var i = 0; i < coords.length; ++i) {

        this.surface.padField(padImg, coords[i]);

        var scaledImg = ndarray(new Float32Array(newWidth * newHeight), [newWidth, newHeight]);
        homography(scaledImg, padImg,
            [
                scaleW, 0, 0,
                0, scaleH, 0,
                0, 0, 1
            ]
        );
        coords[i] = scaledImg;
    }
};

proto.setContourLevels = function() {
    var nlevels = [[], [], []];
    var needsUpdate = false;

    for(var i = 0; i < 3; ++i) {
        if(this.showContour[i]) {
            needsUpdate = true;
            nlevels[i] = this.scene.contourLevels[i];
        }
    }

    if(needsUpdate) {
        this.surface.update({ levels: nlevels });
    }
};

proto.update = function(data) {
    var scene = this.scene;
    var sceneLayout = scene.fullSceneLayout;
    var surface = this.surface;
    var alpha = data.opacity;
    var colormap = parseColorScale(data, alpha);
    var scaleFactor = scene.dataScale;
    var xlen = data.z[0].length;
    var ylen = data._ylength;
    var contourLevels = scene.contourLevels;

    // Save data
    this.data = data;

    /*
     * Fill and transpose zdata.
     * Consistent with 'heatmap' and 'contour', plotly 'surface'
     * 'z' are such that sub-arrays correspond to y-coords
     * and that the sub-array entries correspond to a x-coords,
     * which is the transpose of 'gl-surface-plot'.
     */

    var i, j, k, v;
    var rawCoords = [];
    for(i = 0; i < 3; i++) {
        rawCoords[i] = [];
        for(j = 0; j < xlen; j++) {
            rawCoords[i][j] = [];
            /*
            for(k = 0; k < ylen; k++) {
                rawCoords[i][j][k] = undefined;
            }
            */
        }
    }

    // coords x, y & z
    for(j = 0; j < xlen; j++) {
        for(k = 0; k < ylen; k++) {
            rawCoords[0][j][k] = this.getXat(j, k, data.xcalendar, sceneLayout.xaxis);
            rawCoords[1][j][k] = this.getYat(j, k, data.ycalendar, sceneLayout.yaxis);
            rawCoords[2][j][k] = this.getZat(j, k, data.zcalendar, sceneLayout.zaxis);
        }
    }

    // Note: log axes are not defined in surfaces yet.
    // but they could be defined here...

    for(i = 0; i < 3; i++) {
        for(j = 0; j < xlen; j++) {
            for(k = 0; k < ylen; k++) {
                v = rawCoords[i][j][k];
                if(v === null || v === undefined) {
                    rawCoords[i][j][k] = NaN;
                } else {
                    v = rawCoords[i][j][k] *= scaleFactor[i];
                }
            }
        }
    }

    for(i = 0; i < 3; i++) {
        for(j = 0; j < xlen; j++) {
            for(k = 0; k < ylen; k++) {
                v = rawCoords[i][j][k];
                if(v !== null && v !== undefined) {
                    if(this.minValues[i] > v) {
                        this.minValues[i] = v;
                    }
                    if(this.maxValues[i] < v) {
                        this.maxValues[i] = v;
                    }
                }
            }
        }
    }

    for(i = 0; i < 3; i++) {
        data._objectOffset[i] = 0.5 * (this.minValues[i] + this.maxValues[i]);
    }

    for(i = 0; i < 3; i++) {
        for(j = 0; j < xlen; j++) {
            for(k = 0; k < ylen; k++) {
                v = rawCoords[i][j][k];
                if(v !== null && v !== undefined) {
                    rawCoords[i][j][k] -= data._objectOffset[i];
                }
            }
        }
    }

    // convert processed raw data to Float32 matrices
    var coords = [
        ndarray(new Float32Array(xlen * ylen), [xlen, ylen]),
        ndarray(new Float32Array(xlen * ylen), [xlen, ylen]),
        ndarray(new Float32Array(xlen * ylen), [xlen, ylen])
    ];
    fill(coords[0], function(row, col) { return rawCoords[0][row][col]; });
    fill(coords[1], function(row, col) { return rawCoords[1][row][col]; });
    fill(coords[2], function(row, col) { return rawCoords[2][row][col]; });
    rawCoords = []; // free memory

    var params = {
        colormap: colormap,
        levels: [[], [], []],
        showContour: [true, true, true],
        showSurface: !data.hidesurface,
        contourProject: [
            [false, false, false],
            [false, false, false],
            [false, false, false]
        ],
        contourWidth: [1, 1, 1],
        contourColor: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]],
        contourTint: [1, 1, 1],
        dynamicColor: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]],
        dynamicWidth: [1, 1, 1],
        dynamicTint: [1, 1, 1],
        opacity: data.opacity
    };

    params.intensityBounds = [data.cmin, data.cmax];

    // Refine surface color if necessary
    if(data.surfacecolor) {
        var intensity = ndarray(new Float32Array(xlen * ylen), [xlen, ylen]);

        fill(intensity, function(row, col) {
            return data.surfacecolor[col][row];
        });

        coords.push(intensity);
    }
    else {
        // when 'z' is used as 'intensity',
        // we must scale its value
        params.intensityBounds[0] *= scaleFactor[2];
        params.intensityBounds[1] *= scaleFactor[2];
    }

    if(MAX_RESOLUTION < coords[0].shape[0] ||
        MAX_RESOLUTION < coords[0].shape[1]) {
        this.refineData = false;
    }

    if(this.refineData === true) {
        this.dataScaleX = this.estimateScale(coords[0].shape[0], 0);
        this.dataScaleY = this.estimateScale(coords[0].shape[1], 1);
        if(this.dataScaleX !== 1 || this.dataScaleY !== 1) {
            this.refineCoords(coords);
        }
    }

    if(data.surfacecolor) {
        params.intensity = coords.pop();
    }

    var highlightEnable = [true, true, true];
    var axis = ['x', 'y', 'z'];

    for(i = 0; i < 3; ++i) {
        var contourParams = data.contours[axis[i]];
        highlightEnable[i] = contourParams.highlight;

        params.showContour[i] = contourParams.show || contourParams.highlight;
        if(!params.showContour[i]) continue;

        params.contourProject[i] = [
            contourParams.project.x,
            contourParams.project.y,
            contourParams.project.z
        ];

        if(contourParams.show) {
            this.showContour[i] = true;
            params.levels[i] = contourLevels[i];
            surface.highlightColor[i] = params.contourColor[i] = str2RgbaArray(contourParams.color);

            if(contourParams.usecolormap) {
                surface.highlightTint[i] = params.contourTint[i] = 0;
            }
            else {
                surface.highlightTint[i] = params.contourTint[i] = 1;
            }
            params.contourWidth[i] = contourParams.width;
        } else {
            this.showContour[i] = false;
        }

        if(contourParams.highlight) {
            params.dynamicColor[i] = str2RgbaArray(contourParams.highlightcolor);
            params.dynamicWidth[i] = contourParams.highlightwidth;
        }
    }

    // see https://github.com/plotly/plotly.js/issues/940
    if(isColormapCircular(colormap)) {
        params.vertexColor = true;
    }

    params.objectOffset = [
        data._objectOffset[0],
        data._objectOffset[1],
        data._objectOffset[2]
    ];

    params.coords = coords;
    surface.update(params);

    surface.visible = data.visible;
    surface.enableDynamic = highlightEnable;
    surface.enableHighlight = highlightEnable;

    surface.snapToData = true;

    if('lighting' in data) {
        surface.ambientLight = data.lighting.ambient;
        surface.diffuseLight = data.lighting.diffuse;
        surface.specularLight = data.lighting.specular;
        surface.roughness = data.lighting.roughness;
        surface.fresnel = data.lighting.fresnel;
    }

    if('lightposition' in data) {
        surface.lightPosition = [data.lightposition.x, data.lightposition.y, data.lightposition.z];
    }

    if(alpha && alpha < 1) {
        surface.supportsTransparency = true;
    }
};

proto.dispose = function() {
    this.scene.glplot.remove(this.surface);
    this.surface.dispose();
};

function createSurfaceTrace(scene, data) {
    var gl = scene.glplot.gl;
    var surface = createSurface({ gl: gl });
    var result = new SurfaceTrace(scene, surface, data.uid);
    surface._trace = result;
    result.update(data);
    scene.glplot.add(surface);
    return result;
}

module.exports = createSurfaceTrace;

},{"../../lib":697,"../../lib/gl_format_color":694,"../../lib/str2rgbarray":720,"gl-surface3d":309,"ndarray":439,"ndarray-fill":429,"ndarray-homography":431}],1138:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');

var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    var i, j;

    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var x = coerce('x');
    var y = coerce('y');

    var z = coerce('z');
    if(!z || !z.length ||
       (x ? (x.length < 1) : false) ||
       (y ? (y.length < 1) : false)
    ) {
        traceOut.visible = false;
        return;
    }

    traceOut._xlength = (Array.isArray(x) && Lib.isArrayOrTypedArray(x[0])) ? z.length : z[0].length;
    traceOut._ylength = z.length;

    traceOut._objectOffset = [0, 0, 0];

    var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
    handleCalendarDefaults(traceIn, traceOut, ['x', 'y', 'z'], layout);

    coerce('text');
    coerce('hovertext');
    coerce('hovertemplate');

    // Coerce remaining properties
    [
        'lighting.ambient',
        'lighting.diffuse',
        'lighting.specular',
        'lighting.roughness',
        'lighting.fresnel',
        'lightposition.x',
        'lightposition.y',
        'lightposition.z',
        'hidesurface',
        'opacity'
    ].forEach(function(x) { coerce(x); });

    var surfaceColor = coerce('surfacecolor');

    var dims = ['x', 'y', 'z'];
    for(i = 0; i < 3; ++i) {

        var contourDim = 'contours.' + dims[i];
        var show = coerce(contourDim + '.show');
        var highlight = coerce(contourDim + '.highlight');

        if(show || highlight) {
            for(j = 0; j < 3; ++j) {
                coerce(contourDim + '.project.' + dims[j]);
            }
        }

        if(show) {
            coerce(contourDim + '.color');
            coerce(contourDim + '.width');
            coerce(contourDim + '.usecolormap');
        }

        if(highlight) {
            coerce(contourDim + '.highlightcolor');
            coerce(contourDim + '.highlightwidth');
        }
    }

    // backward compatibility block
    if(!surfaceColor) {
        mapLegacy(traceIn, 'zmin', 'cmin');
        mapLegacy(traceIn, 'zmax', 'cmax');
        mapLegacy(traceIn, 'zauto', 'cauto');
    }

    // TODO if contours.?.usecolormap are false and hidesurface is true
    // the colorbar shouldn't be shown by default

    colorscaleDefaults(
        traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'c'}
    );

    // disable 1D transforms - currently surface does NOT support column data like heatmap does
    // you can use mesh3d for this use case, but not surface
    traceOut._length = null;
};

function mapLegacy(traceIn, oldAttr, newAttr) {
    if(oldAttr in traceIn && !(newAttr in traceIn)) {
        traceIn[newAttr] = traceIn[oldAttr];
    }
}

},{"../../components/colorscale/defaults":584,"../../lib":697,"../../registry":826,"./attributes":1135}],1139:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Surface = {};

Surface.attributes = _dereq_('./attributes');
Surface.supplyDefaults = _dereq_('./defaults');
Surface.colorbar = {
    min: 'cmin',
    max: 'cmax'
};
Surface.calc = _dereq_('./calc');
Surface.plot = _dereq_('./convert');

Surface.moduleType = 'trace';
Surface.name = 'surface';
Surface.basePlotModule = _dereq_('../../plots/gl3d');
Surface.categories = ['gl3d', '2dMap', 'noOpacity'];
Surface.meta = {
    
};

module.exports = Surface;

},{"../../plots/gl3d":786,"./attributes":1135,"./calc":1136,"./convert":1137,"./defaults":1138}],1140:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var annAttrs = _dereq_('../../components/annotations/attributes');
var extendFlat = _dereq_('../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
var fontAttrs = _dereq_('../../plots/font_attributes');
var domainAttrs = _dereq_('../../plots/domain').attributes;

var attrs = module.exports = overrideAll({
    domain: domainAttrs({name: 'table', trace: true}),

    columnwidth: {
        valType: 'number',
        arrayOk: true,
        dflt: null,
        
        
    },

    columnorder: {
        valType: 'data_array',
        
        
    },

    header: {

        values: {
            valType: 'data_array',
            
            dflt: [],
            
        },

        format: {
            valType: 'data_array',
            
            dflt: [],
            
        },

        prefix: {
            valType: 'string',
            arrayOk: true,
            dflt: null,
            
            
        },

        suffix: {
            valType: 'string',
            arrayOk: true,
            dflt: null,
            
            
        },

        height: {
            valType: 'number',
            dflt: 28,
            
            
        },

        align: extendFlat({}, annAttrs.align, {arrayOk: true}),

        line: {
            width: {
                valType: 'number',
                arrayOk: true,
                dflt: 1,
                
            },
            color: {
                valType: 'color',
                arrayOk: true,
                dflt: 'grey',
                
            }
        },

        fill: {
            color: {
                valType: 'color',
                arrayOk: true,
                dflt: 'white',
                
                
            }
        },

        font: extendFlat({}, fontAttrs({arrayOk: true}))
    },

    cells: {

        values: {
            valType: 'data_array',
            
            dflt: [],
            
        },

        format: {
            valType: 'data_array',
            
            dflt: [],
            
        },

        prefix: {
            valType: 'string',
            arrayOk: true,
            dflt: null,
            
            
        },

        suffix: {
            valType: 'string',
            arrayOk: true,
            dflt: null,
            
            
        },

        height: {
            valType: 'number',
            dflt: 20,
            
            
        },

        align: extendFlat({}, annAttrs.align, {arrayOk: true}),

        line: {
            width: {
                valType: 'number',
                arrayOk: true,
                dflt: 1,
                
            },
            color: {
                valType: 'color',
                arrayOk: true,
                dflt: 'grey',
                
            }
        },

        fill: {
            color: {
                valType: 'color',
                arrayOk: true,
                
                dflt: 'white',
                
            }
        },

        font: extendFlat({}, fontAttrs({arrayOk: true}))
    }
}, 'calc', 'from-root');
attrs.transforms = undefined;

},{"../../components/annotations/attributes":557,"../../lib/extend":687,"../../plot_api/edit_types":728,"../../plots/domain":770,"../../plots/font_attributes":771}],1141:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var getModuleCalcData = _dereq_('../../plots/get_data').getModuleCalcData;
var tablePlot = _dereq_('./plot');

var TABLE = 'table';

exports.name = TABLE;

exports.plot = function(gd) {
    var calcData = getModuleCalcData(gd.calcdata, TABLE)[0];
    if(calcData.length) tablePlot(gd, calcData);
};

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var hadTable = (oldFullLayout._has && oldFullLayout._has(TABLE));
    var hasTable = (newFullLayout._has && newFullLayout._has(TABLE));

    if(hadTable && !hasTable) {
        oldFullLayout._paperdiv.selectAll('.table').remove();
    }
};

},{"../../plots/get_data":781,"./plot":1148}],1142:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var wrap = _dereq_('../../lib/gup').wrap;

module.exports = function calc() {
    // we don't actually need to include the trace here, since that will be added
    // by Plots.doCalcdata, and that's all we actually need later.
    return wrap({});
};

},{"../../lib/gup":695}],1143:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    cellPad: 8,
    columnExtentOffset: 10,
    columnTitleOffset: 28,
    emptyHeaderHeight: 16,
    latexCheck: /^\$.*\$$/,
    goldenRatio: 1.618,
    lineBreaker: '<br>',
    maxDimensionCount: 60,
    overdrag: 45,
    releaseTransitionDuration: 120,
    releaseTransitionEase: 'cubic-out',
    scrollbarCaptureWidth: 18,
    scrollbarHideDelay: 1000,
    scrollbarHideDuration: 1000,
    scrollbarOffset: 5,
    scrollbarWidth: 8,
    transitionDuration: 100,
    transitionEase: 'cubic-out',
    uplift: 5,
    wrapSpacer: ' ',
    wrapSplitCharacter: ' ',
    cn: {
        // general class names
        table: 'table',
        tableControlView: 'table-control-view',
        scrollBackground: 'scroll-background',
        yColumn: 'y-column',
        columnBlock: 'column-block',
        scrollAreaClip: 'scroll-area-clip',
        scrollAreaClipRect: 'scroll-area-clip-rect',
        columnBoundary: 'column-boundary',
        columnBoundaryClippath: 'column-boundary-clippath',
        columnBoundaryRect: 'column-boundary-rect',
        columnCells: 'column-cells',
        columnCell: 'column-cell',
        cellRect: 'cell-rect',
        cellText: 'cell-text',
        cellTextHolder: 'cell-text-holder',

        // scroll related class names
        scrollbarKit: 'scrollbar-kit',
        scrollbar: 'scrollbar',
        scrollbarSlider: 'scrollbar-slider',
        scrollbarGlyph: 'scrollbar-glyph',
        scrollbarCaptureZone: 'scrollbar-capture-zone'
    }
};

},{}],1144:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var c = _dereq_('./constants');
var extendFlat = _dereq_('../../lib/extend').extendFlat;
var isNumeric = _dereq_('fast-isnumeric');

// pure functions, don't alter but passes on `gd` and parts of `trace` without deep copying
module.exports = function calc(gd, trace) {
    var cellsValues = squareStringMatrix(trace.cells.values);
    var slicer = function(a) {
        return a.slice(trace.header.values.length, a.length);
    };
    var headerValuesIn = squareStringMatrix(trace.header.values);
    if(headerValuesIn.length && !headerValuesIn[0].length) {
        headerValuesIn[0] = [''];
        headerValuesIn = squareStringMatrix(headerValuesIn);
    }
    var headerValues = headerValuesIn
        .concat(slicer(cellsValues).map(function() {
            return emptyStrings((headerValuesIn[0] || ['']).length);
        }));

    var domain = trace.domain;
    var groupWidth = Math.floor(gd._fullLayout._size.w * (domain.x[1] - domain.x[0]));
    var groupHeight = Math.floor(gd._fullLayout._size.h * (domain.y[1] - domain.y[0]));
    var headerRowHeights = trace.header.values.length ?
        headerValues[0].map(function() { return trace.header.height; }) :
        [c.emptyHeaderHeight];
    var rowHeights = cellsValues.length ? cellsValues[0].map(function() { return trace.cells.height; }) : [];
    var headerHeight = headerRowHeights.reduce(sum, 0);
    var scrollHeight = groupHeight - headerHeight;
    var minimumFillHeight = scrollHeight + c.uplift;
    var anchorToRowBlock = makeAnchorToRowBlock(rowHeights, minimumFillHeight);
    var anchorToHeaderRowBlock = makeAnchorToRowBlock(headerRowHeights, headerHeight);
    var headerRowBlocks = makeRowBlock(anchorToHeaderRowBlock, []);
    var rowBlocks = makeRowBlock(anchorToRowBlock, headerRowBlocks);
    var uniqueKeys = {};
    var columnOrder = trace._fullInput.columnorder.concat(slicer(cellsValues.map(function(d, i) {return i;})));
    var columnWidths = headerValues.map(function(d, i) {
        var value = Array.isArray(trace.columnwidth) ?
            trace.columnwidth[Math.min(i, trace.columnwidth.length - 1)] :
            trace.columnwidth;
        return isNumeric(value) ? Number(value) : 1;
    });
    var totalColumnWidths = columnWidths.reduce(sum, 0);

    // fit columns in the available vertical space as there's no vertical scrolling now
    columnWidths = columnWidths.map(function(d) { return d / totalColumnWidths * groupWidth; });

    var maxLineWidth = Math.max(arrayMax(trace.header.line.width), arrayMax(trace.cells.line.width));

    var calcdata = {
        // include staticPlot in the key so if it changes we delete and redraw
        key: trace.uid + gd._context.staticPlot,
        translateX: domain.x[0] * gd._fullLayout._size.w,
        translateY: gd._fullLayout._size.h * (1 - domain.y[1]),
        size: gd._fullLayout._size,
        width: groupWidth,
        maxLineWidth: maxLineWidth,
        height: groupHeight,
        columnOrder: columnOrder, // will be mutated on column move, todo use in callback
        groupHeight: groupHeight,
        rowBlocks: rowBlocks,
        headerRowBlocks: headerRowBlocks,
        scrollY: 0, // will be mutated on scroll
        cells: extendFlat({}, trace.cells, {values: cellsValues}),
        headerCells: extendFlat({}, trace.header, {values: headerValues}),
        gdColumns: headerValues.map(function(d) {return d[0];}),
        gdColumnsOriginalOrder: headerValues.map(function(d) {return d[0];}),
        prevPages: [0, 0],
        scrollbarState: {scrollbarScrollInProgress: false},
        columns: headerValues.map(function(label, i) {
            var foundKey = uniqueKeys[label];
            uniqueKeys[label] = (foundKey || 0) + 1;
            var key = label + '__' + uniqueKeys[label];
            return {
                key: key,
                label: label,
                specIndex: i,
                xIndex: columnOrder[i],
                xScale: xScale,
                x: undefined, // initialized below
                calcdata: undefined, // initialized below
                columnWidth: columnWidths[i]
            };
        })
    };

    calcdata.columns.forEach(function(col) {
        col.calcdata = calcdata;
        col.x = xScale(col);
    });

    return calcdata;
};

function arrayMax(maybeArray) {
    if(Array.isArray(maybeArray)) {
        var max = 0;
        for(var i = 0; i < maybeArray.length; i++) {
            max = Math.max(max, arrayMax(maybeArray[i]));
        }
        return max;
    }
    return maybeArray;
}

function sum(a, b) { return a + b; }

// fill matrix in place to equal lengths
// and ensure it's uniformly 2D
function squareStringMatrix(matrixIn) {
    var matrix = matrixIn.slice();
    var minLen = Infinity;
    var maxLen = 0;
    var i;
    for(i = 0; i < matrix.length; i++) {
        if(!Array.isArray(matrix[i])) matrix[i] = [matrix[i]];
        minLen = Math.min(minLen, matrix[i].length);
        maxLen = Math.max(maxLen, matrix[i].length);
    }

    if(minLen !== maxLen) {
        for(i = 0; i < matrix.length; i++) {
            var padLen = maxLen - matrix[i].length;
            if(padLen) matrix[i] = matrix[i].concat(emptyStrings(padLen));
        }
    }
    return matrix;
}

function emptyStrings(len) {
    var padArray = new Array(len);
    for(var j = 0; j < len; j++) padArray[j] = '';
    return padArray;
}

function xScale(d) {
    return d.calcdata.columns.reduce(function(prev, next) {
        return next.xIndex < d.xIndex ? prev + next.columnWidth : prev;
    }, 0);
}

function makeRowBlock(anchorToRowBlock, auxiliary) {
    var blockAnchorKeys = Object.keys(anchorToRowBlock);
    return blockAnchorKeys.map(function(k) {return extendFlat({}, anchorToRowBlock[k], {auxiliaryBlocks: auxiliary});});
}

function makeAnchorToRowBlock(rowHeights, minimumFillHeight) {

    var anchorToRowBlock = {};
    var currentRowHeight;
    var currentAnchor = 0;
    var currentBlockHeight = 0;
    var currentBlock = makeIdentity();
    var currentFirstRowIndex = 0;
    var blockCounter = 0;
    for(var i = 0; i < rowHeights.length; i++) {
        currentRowHeight = rowHeights[i];
        currentBlock.rows.push({
            rowIndex: i,
            rowHeight: currentRowHeight
        });
        currentBlockHeight += currentRowHeight;
        if(currentBlockHeight >= minimumFillHeight || i === rowHeights.length - 1) {
            anchorToRowBlock[currentAnchor] = currentBlock;
            currentBlock.key = blockCounter++;
            currentBlock.firstRowIndex = currentFirstRowIndex;
            currentBlock.lastRowIndex = i;
            currentBlock = makeIdentity();
            currentAnchor += currentBlockHeight;
            currentFirstRowIndex = i + 1;
            currentBlockHeight = 0;
        }
    }

    return anchorToRowBlock;
}

function makeIdentity() {
    return {
        firstRowIndex: null,
        lastRowIndex: null,
        rows: []
    };
}

},{"../../lib/extend":687,"./constants":1143,"fast-isnumeric":218}],1145:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var extendFlat = _dereq_('../../lib/extend').extendFlat;

// pure functions, don't alter but passes on `gd` and parts of `trace` without deep copying

exports.splitToPanels = function(d) {
    var prevPages = [0, 0];
    var headerPanel = extendFlat({}, d, {
        key: 'header',
        type: 'header',
        page: 0,
        prevPages: prevPages,
        currentRepaint: [null, null],
        dragHandle: true,
        values: d.calcdata.headerCells.values[d.specIndex],
        rowBlocks: d.calcdata.headerRowBlocks,
        calcdata: extendFlat({}, d.calcdata, {cells: d.calcdata.headerCells})
    });
    var revolverPanel1 = extendFlat({}, d, {
        key: 'cells1',
        type: 'cells',
        page: 0,
        prevPages: prevPages,
        currentRepaint: [null, null],
        dragHandle: false,
        values: d.calcdata.cells.values[d.specIndex],
        rowBlocks: d.calcdata.rowBlocks
    });
    var revolverPanel2 = extendFlat({}, d, {
        key: 'cells2',
        type: 'cells',
        page: 1,
        prevPages: prevPages,
        currentRepaint: [null, null],
        dragHandle: false,
        values: d.calcdata.cells.values[d.specIndex],
        rowBlocks: d.calcdata.rowBlocks
    });
    // order due to SVG using painter's algo:
    return [revolverPanel1, revolverPanel2, headerPanel];
};

exports.splitToCells = function(d) {
    var fromTo = rowFromTo(d);
    return (d.values || []).slice(fromTo[0], fromTo[1]).map(function(v, i) {
        // By keeping identical key, a DOM node removal, creation and addition is spared, important when visible
        // grid has a lot of elements (quadratic with xcol/ycol count).
        // But it has to be busted when `svgUtil.convertToTspans` is used as it reshapes cell subtrees asynchronously,
        // and by that time the user may have scrolled away, resulting in stale overwrites. The real solution will be
        // to turn `svgUtil.convertToTspans` into a cancelable request, in which case no key busting is needed.
        var buster = (typeof v === 'string') && v.match(/[<$&> ]/) ? '_keybuster_' + Math.random() : '';
        return {
            // keyWithinBlock: /*fromTo[0] + */i, // optimized future version - no busting
            // keyWithinBlock: fromTo[0] + i, // initial always-unoptimized version - janky scrolling with 5+ columns
            keyWithinBlock: i + buster, // current compromise: regular content is very fast; async content is possible
            key: fromTo[0] + i,
            column: d,
            calcdata: d.calcdata,
            page: d.page,
            rowBlocks: d.rowBlocks,
            value: v
        };
    });
};

function rowFromTo(d) {
    var rowBlock = d.rowBlocks[d.page];
    // fixme rowBlock truthiness check is due to ugly hack of placing 2nd panel as d.page = -1
    var rowFrom = rowBlock ? rowBlock.rows[0].rowIndex : 0;
    var rowTo = rowBlock ? rowFrom + rowBlock.rows.length : 0;
    return [rowFrom, rowTo];
}

},{"../../lib/extend":687}],1146:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var attributes = _dereq_('./attributes');
var handleDomainDefaults = _dereq_('../../plots/domain').defaults;

function defaultColumnOrder(traceOut, coerce) {
    var specifiedColumnOrder = traceOut.columnorder || [];
    var commonLength = traceOut.header.values.length;
    var truncated = specifiedColumnOrder.slice(0, commonLength);
    var sorted = truncated.slice().sort(function(a, b) {return a - b;});
    var oneStepped = truncated.map(function(d) {return sorted.indexOf(d);});
    for(var i = oneStepped.length; i < commonLength; i++) {
        oneStepped.push(i);
    }
    coerce('columnorder', oneStepped);
}

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    handleDomainDefaults(traceOut, layout, coerce);

    coerce('columnwidth');

    coerce('header.values');
    coerce('header.format');
    coerce('header.align');

    coerce('header.prefix');
    coerce('header.suffix');
    coerce('header.height');
    coerce('header.line.width');
    coerce('header.line.color');
    coerce('header.fill.color');
    Lib.coerceFont(coerce, 'header.font', Lib.extendFlat({}, layout.font));

    defaultColumnOrder(traceOut, coerce);

    coerce('cells.values');
    coerce('cells.format');
    coerce('cells.align');
    coerce('cells.prefix');
    coerce('cells.suffix');
    coerce('cells.height');
    coerce('cells.line.width');
    coerce('cells.line.color');
    coerce('cells.fill.color');
    Lib.coerceFont(coerce, 'cells.font', Lib.extendFlat({}, layout.font));

    // disable 1D transforms
    traceOut._length = null;
};

},{"../../lib":697,"../../plots/domain":770,"./attributes":1140}],1147:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Table = {};

Table.attributes = _dereq_('./attributes');
Table.supplyDefaults = _dereq_('./defaults');
Table.calc = _dereq_('./calc');
Table.plot = _dereq_('./plot');

Table.moduleType = 'trace';
Table.name = 'table';
Table.basePlotModule = _dereq_('./base_plot');
Table.categories = ['noOpacity'];
Table.meta = {
    
};

module.exports = Table;

},{"./attributes":1140,"./base_plot":1141,"./calc":1142,"./defaults":1146,"./plot":1148}],1148:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var c = _dereq_('./constants');
var d3 = _dereq_('d3');
var gup = _dereq_('../../lib/gup');
var Drawing = _dereq_('../../components/drawing');
var svgUtil = _dereq_('../../lib/svg_text_utils');
var raiseToTop = _dereq_('../../lib').raiseToTop;
var cancelEeaseColumn = _dereq_('../../lib').cancelTransition;
var prepareData = _dereq_('./data_preparation_helper');
var splitData = _dereq_('./data_split_helpers');
var Color = _dereq_('../../components/color');

module.exports = function plot(gd, wrappedTraceHolders) {
    var dynamic = !gd._context.staticPlot;

    var table = gd._fullLayout._paper.selectAll('.' + c.cn.table)
        .data(wrappedTraceHolders.map(function(wrappedTraceHolder) {
            var traceHolder = gup.unwrap(wrappedTraceHolder);
            var trace = traceHolder.trace;
            return prepareData(gd, trace);
        }), gup.keyFun);

    table.exit().remove();

    table.enter()
        .append('g')
        .classed(c.cn.table, true)
        .attr('overflow', 'visible')
        .style('box-sizing', 'content-box')
        .style('position', 'absolute')
        .style('left', 0)
        .style('overflow', 'visible')
        .style('shape-rendering', 'crispEdges')
        .style('pointer-events', 'all');

    table
        .attr('width', function(d) {return d.width + d.size.l + d.size.r;})
        .attr('height', function(d) {return d.height + d.size.t + d.size.b;})
        .attr('transform', function(d) {
            return 'translate(' + d.translateX + ',' + d.translateY + ')';
        });

    var tableControlView = table.selectAll('.' + c.cn.tableControlView)
        .data(gup.repeat, gup.keyFun);

    var cvEnter = tableControlView.enter()
        .append('g')
        .classed(c.cn.tableControlView, true)
        .style('box-sizing', 'content-box');
    if(dynamic) {
        cvEnter
            .on('mousemove', function(d) {
                tableControlView
                    .filter(function(dd) {return d === dd;})
                    .call(renderScrollbarKit, gd);
            })
            .on('mousewheel', function(d) {
                if(d.scrollbarState.wheeling) return;
                d.scrollbarState.wheeling = true;
                var newY = d.scrollY + d3.event.deltaY;
                var noChange = makeDragRow(gd, tableControlView, null, newY)(d);
                if(!noChange) {
                    d3.event.stopPropagation();
                    d3.event.preventDefault();
                }
                d.scrollbarState.wheeling = false;
            })
            .call(renderScrollbarKit, gd, true);
    }

    tableControlView
        .attr('transform', function(d) {return 'translate(' + d.size.l + ' ' + d.size.t + ')';});

    // scrollBackground merely ensures that mouse events are captured even on crazy fast scrollwheeling
    // otherwise rendering glitches may occur
    var scrollBackground = tableControlView.selectAll('.' + c.cn.scrollBackground)
        .data(gup.repeat, gup.keyFun);

    scrollBackground.enter()
        .append('rect')
        .classed(c.cn.scrollBackground, true)
        .attr('fill', 'none');

    scrollBackground
        .attr('width', function(d) {return d.width;})
        .attr('height', function(d) {return d.height;});

    tableControlView.each(function(d) {
        Drawing.setClipUrl(d3.select(this), scrollAreaBottomClipKey(gd, d), gd);
    });

    var yColumn = tableControlView.selectAll('.' + c.cn.yColumn)
        .data(function(vm) {return vm.columns;}, gup.keyFun);

    yColumn.enter()
        .append('g')
        .classed(c.cn.yColumn, true);

    yColumn.exit().remove();

    yColumn.attr('transform', function(d) {return 'translate(' + d.x + ' 0)';});

    if(dynamic) {
        yColumn.call(d3.behavior.drag()
            .origin(function(d) {
                var movedColumn = d3.select(this);
                easeColumn(movedColumn, d, -c.uplift);
                raiseToTop(this);
                d.calcdata.columnDragInProgress = true;
                renderScrollbarKit(tableControlView.filter(function(dd) {return d.calcdata.key === dd.key;}), gd);
                return d;
            })
            .on('drag', function(d) {
                var movedColumn = d3.select(this);
                var getter = function(dd) {return (d === dd ? d3.event.x : dd.x) + dd.columnWidth / 2;};
                d.x = Math.max(-c.overdrag, Math.min(d.calcdata.width + c.overdrag - d.columnWidth, d3.event.x));

                var sortableColumns = flatData(yColumn).filter(function(dd) {return dd.calcdata.key === d.calcdata.key;});
                var newOrder = sortableColumns.sort(function(a, b) {return getter(a) - getter(b);});
                newOrder.forEach(function(dd, i) {
                    dd.xIndex = i;
                    dd.x = d === dd ? dd.x : dd.xScale(dd);
                });

                yColumn.filter(function(dd) {return d !== dd;})
                    .transition()
                    .ease(c.transitionEase)
                    .duration(c.transitionDuration)
                    .attr('transform', function(d) {return 'translate(' + d.x + ' 0)';});
                movedColumn
                    .call(cancelEeaseColumn)
                    .attr('transform', 'translate(' + d.x + ' -' + c.uplift + ' )');
            })
            .on('dragend', function(d) {
                var movedColumn = d3.select(this);
                var p = d.calcdata;
                d.x = d.xScale(d);
                d.calcdata.columnDragInProgress = false;
                easeColumn(movedColumn, d, 0);
                columnMoved(gd, p, p.columns.map(function(dd) {return dd.xIndex;}));
            })
        );
    }

    yColumn.each(function(d) {
        Drawing.setClipUrl(d3.select(this), columnBoundaryClipKey(gd, d), gd);
    });

    var columnBlock = yColumn.selectAll('.' + c.cn.columnBlock)
        .data(splitData.splitToPanels, gup.keyFun);

    columnBlock.enter()
        .append('g')
        .classed(c.cn.columnBlock, true)
        .attr('id', function(d) {return d.key;});

    columnBlock
        .style('cursor', function(d) {
            return d.dragHandle ? 'ew-resize' : d.calcdata.scrollbarState.barWiggleRoom ? 'ns-resize' : 'default';
        });

    var headerColumnBlock = columnBlock.filter(headerBlock);
    var cellsColumnBlock = columnBlock.filter(cellsBlock);

    if(dynamic) {
        cellsColumnBlock.call(d3.behavior.drag()
            .origin(function(d) {
                d3.event.stopPropagation();
                return d;
            })
            .on('drag', makeDragRow(gd, tableControlView, -1))
            .on('dragend', function() {
                // fixme emit plotly notification
            })
        );
    }

    // initial rendering: header is rendered first, as it may may have async LaTeX (show header first)
    // but blocks are _entered_ the way they are due to painter's algo (header on top)
    renderColumnCellTree(gd, tableControlView, headerColumnBlock, columnBlock);
    renderColumnCellTree(gd, tableControlView, cellsColumnBlock, columnBlock);

    var scrollAreaClip = tableControlView.selectAll('.' + c.cn.scrollAreaClip)
        .data(gup.repeat, gup.keyFun);

    scrollAreaClip.enter()
        .append('clipPath')
        .classed(c.cn.scrollAreaClip, true)
        .attr('id', function(d) {return scrollAreaBottomClipKey(gd, d);});

    var scrollAreaClipRect = scrollAreaClip.selectAll('.' + c.cn.scrollAreaClipRect)
        .data(gup.repeat, gup.keyFun);

    scrollAreaClipRect.enter()
        .append('rect')
        .classed(c.cn.scrollAreaClipRect, true)
        .attr('x', -c.overdrag)
        .attr('y', -c.uplift)
        .attr('fill', 'none');

    scrollAreaClipRect
        .attr('width', function(d) {return d.width + 2 * c.overdrag;})
        .attr('height', function(d) {return d.height + c.uplift;});

    var columnBoundary = yColumn.selectAll('.' + c.cn.columnBoundary)
        .data(gup.repeat, gup.keyFun);

    columnBoundary.enter()
        .append('g')
        .classed(c.cn.columnBoundary, true);

    var columnBoundaryClippath = yColumn.selectAll('.' + c.cn.columnBoundaryClippath)
        .data(gup.repeat, gup.keyFun);

    // SVG spec doesn't mandate wrapping into a <defs> and doesn't seem to cause a speed difference
    columnBoundaryClippath.enter()
        .append('clipPath')
        .classed(c.cn.columnBoundaryClippath, true);

    columnBoundaryClippath
        .attr('id', function(d) {return columnBoundaryClipKey(gd, d);});

    var columnBoundaryRect = columnBoundaryClippath.selectAll('.' + c.cn.columnBoundaryRect)
        .data(gup.repeat, gup.keyFun);

    columnBoundaryRect.enter()
        .append('rect')
        .classed(c.cn.columnBoundaryRect, true)
        .attr('fill', 'none');

    columnBoundaryRect
        .attr('width', function(d) { return d.columnWidth + 2 * roundHalfWidth(d); })
        .attr('height', function(d) {return d.calcdata.height + 2 * roundHalfWidth(d) + c.uplift;})
        .attr('x', function(d) { return -roundHalfWidth(d); })
        .attr('y', function(d) { return -roundHalfWidth(d); });

    updateBlockYPosition(null, cellsColumnBlock, tableControlView);
};

function roundHalfWidth(d) {
    return Math.ceil(d.calcdata.maxLineWidth / 2);
}

function scrollAreaBottomClipKey(gd, d) {
    return 'clip' + gd._fullLayout._uid + '_scrollAreaBottomClip_' + d.key;
}

function columnBoundaryClipKey(gd, d) {
    return 'clip' + gd._fullLayout._uid + '_columnBoundaryClippath_' + d.calcdata.key + '_' + d.specIndex;
}

function flatData(selection) {
    return [].concat.apply([], selection.map(function(g) {return g;}))
        .map(function(g) {return g.__data__;});
}

function renderScrollbarKit(tableControlView, gd, bypassVisibleBar) {

    function calcTotalHeight(d) {
        var blocks = d.rowBlocks;
        return firstRowAnchor(blocks, blocks.length - 1) + (blocks.length ? rowsHeight(blocks[blocks.length - 1], Infinity) : 1);
    }

    var scrollbarKit = tableControlView.selectAll('.' + c.cn.scrollbarKit)
        .data(gup.repeat, gup.keyFun);

    scrollbarKit.enter()
        .append('g')
        .classed(c.cn.scrollbarKit, true)
        .style('shape-rendering', 'geometricPrecision');

    scrollbarKit
        .each(function(d) {
            var s = d.scrollbarState;
            s.totalHeight = calcTotalHeight(d);
            s.scrollableAreaHeight = d.groupHeight - headerHeight(d);
            s.currentlyVisibleHeight = Math.min(s.totalHeight, s.scrollableAreaHeight);
            s.ratio = s.currentlyVisibleHeight / s.totalHeight;
            s.barLength = Math.max(s.ratio * s.currentlyVisibleHeight, c.goldenRatio * c.scrollbarWidth);
            s.barWiggleRoom = s.currentlyVisibleHeight - s.barLength;
            s.wiggleRoom = Math.max(0, s.totalHeight - s.scrollableAreaHeight);
            s.topY = s.barWiggleRoom === 0 ? 0 : (d.scrollY / s.wiggleRoom) * s.barWiggleRoom;
            s.bottomY = s.topY + s.barLength;
            s.dragMultiplier = s.wiggleRoom / s.barWiggleRoom;
        })
        .attr('transform', function(d) {
            var xPosition = d.width + c.scrollbarWidth / 2 + c.scrollbarOffset;
            return 'translate(' + xPosition + ' ' + headerHeight(d) + ')';
        });

    var scrollbar = scrollbarKit.selectAll('.' + c.cn.scrollbar)
        .data(gup.repeat, gup.keyFun);

    scrollbar.enter()
        .append('g')
        .classed(c.cn.scrollbar, true);

    var scrollbarSlider = scrollbar.selectAll('.' + c.cn.scrollbarSlider)
        .data(gup.repeat, gup.keyFun);

    scrollbarSlider.enter()
        .append('g')
        .classed(c.cn.scrollbarSlider, true);

    scrollbarSlider
        .attr('transform', function(d) {
            return 'translate(0 ' + (d.scrollbarState.topY || 0) + ')';
        });

    var scrollbarGlyph = scrollbarSlider.selectAll('.' + c.cn.scrollbarGlyph)
        .data(gup.repeat, gup.keyFun);

    scrollbarGlyph.enter()
        .append('line')
        .classed(c.cn.scrollbarGlyph, true)
        .attr('stroke', 'black')
        .attr('stroke-width', c.scrollbarWidth)
        .attr('stroke-linecap', 'round')
        .attr('y1', c.scrollbarWidth / 2);

    scrollbarGlyph
        .attr('y2', function(d) {
            return d.scrollbarState.barLength - c.scrollbarWidth / 2;
        })
        .attr('stroke-opacity', function(d) {
            return d.columnDragInProgress || !d.scrollbarState.barWiggleRoom || bypassVisibleBar ? 0 : 0.4;
        });

    // cancel transition: possible pending (also, delayed) transition
    scrollbarGlyph
        .transition().delay(0).duration(0);

    scrollbarGlyph
        .transition().delay(c.scrollbarHideDelay).duration(c.scrollbarHideDuration)
        .attr('stroke-opacity', 0);

    var scrollbarCaptureZone = scrollbar.selectAll('.' + c.cn.scrollbarCaptureZone)
        .data(gup.repeat, gup.keyFun);

    scrollbarCaptureZone.enter()
        .append('line')
        .classed(c.cn.scrollbarCaptureZone, true)
        .attr('stroke', 'white')
        .attr('stroke-opacity', 0.01) // some browser might get rid of a 0 opacity element
        .attr('stroke-width', c.scrollbarCaptureWidth)
        .attr('stroke-linecap', 'butt')
        .attr('y1', 0)
        .on('mousedown', function(d) {
            var y = d3.event.y;
            var bbox = this.getBoundingClientRect();
            var s = d.scrollbarState;
            var pixelVal = y - bbox.top;
            var inverseScale = d3.scale.linear().domain([0, s.scrollableAreaHeight]).range([0, s.totalHeight]).clamp(true);
            if(!(s.topY <= pixelVal && pixelVal <= s.bottomY)) {
                makeDragRow(gd, tableControlView, null, inverseScale(pixelVal - s.barLength / 2))(d);
            }
        })
        .call(d3.behavior.drag()
            .origin(function(d) {
                d3.event.stopPropagation();
                d.scrollbarState.scrollbarScrollInProgress = true;
                return d;
            })
            .on('drag', makeDragRow(gd, tableControlView))
            .on('dragend', function() {
                // fixme emit Plotly event
            })
        );

    scrollbarCaptureZone
        .attr('y2', function(d) {
            return d.scrollbarState.scrollableAreaHeight;
        });

    // Remove scroll glyph and capture zone on static plots
    // as they don't render properly when converted to PDF
    // in the Chrome PDF viewer
    // https://github.com/plotly/streambed/issues/11618
    if(gd._context.staticPlot) {
        scrollbarGlyph.remove();
        scrollbarCaptureZone.remove();
    }
}

function renderColumnCellTree(gd, tableControlView, columnBlock, allColumnBlock) {
    // fixme this perf hotspot
    // this is performance critical code as scrolling calls it on every revolver switch
    // it appears sufficiently fast but there are plenty of low-hanging fruits for performance optimization

    var columnCells = renderColumnCells(columnBlock);

    var columnCell = renderColumnCell(columnCells);

    supplyStylingValues(columnCell);

    var cellRect = renderCellRect(columnCell);

    sizeAndStyleRect(cellRect);

    var cellTextHolder = renderCellTextHolder(columnCell);

    var cellText = renderCellText(cellTextHolder);

    setFont(cellText);
    populateCellText(cellText, tableControlView, allColumnBlock, gd);

    // doing this at the end when text, and text stlying are set
    setCellHeightAndPositionY(columnCell);
}

function renderColumnCells(columnBlock) {

    var columnCells = columnBlock.selectAll('.' + c.cn.columnCells)
        .data(gup.repeat, gup.keyFun);

    columnCells.enter()
        .append('g')
        .classed(c.cn.columnCells, true);

    columnCells.exit()
        .remove();

    return columnCells;
}

function renderColumnCell(columnCells) {

    var columnCell = columnCells.selectAll('.' + c.cn.columnCell)
        .data(splitData.splitToCells, function(d) {return d.keyWithinBlock;});

    columnCell.enter()
        .append('g')
        .classed(c.cn.columnCell, true);

    columnCell.exit()
        .remove();

    return columnCell;
}

function renderCellRect(columnCell) {

    var cellRect = columnCell.selectAll('.' + c.cn.cellRect)
        .data(gup.repeat, function(d) {return d.keyWithinBlock;});

    cellRect.enter()
        .append('rect')
        .classed(c.cn.cellRect, true);

    return cellRect;
}

function renderCellText(cellTextHolder) {

    var cellText = cellTextHolder.selectAll('.' + c.cn.cellText)
        .data(gup.repeat, function(d) {return d.keyWithinBlock;});

    cellText.enter()
        .append('text')
        .classed(c.cn.cellText, true)
        .style('cursor', function() {return 'auto';})
        .on('mousedown', function() {d3.event.stopPropagation();});

    return cellText;
}

function renderCellTextHolder(columnCell) {

    var cellTextHolder = columnCell.selectAll('.' + c.cn.cellTextHolder)
        .data(gup.repeat, function(d) {return d.keyWithinBlock;});

    cellTextHolder.enter()
        .append('g')
        .classed(c.cn.cellTextHolder, true)
        .style('shape-rendering', 'geometricPrecision');

    return cellTextHolder;
}

function supplyStylingValues(columnCell) {
    columnCell
        .each(function(d, i) {
            var spec = d.calcdata.cells.font;
            var col = d.column.specIndex;
            var font = {
                size: gridPick(spec.size, col, i),
                color: gridPick(spec.color, col, i),
                family: gridPick(spec.family, col, i)
            };
            d.rowNumber = d.key;
            d.align = gridPick(d.calcdata.cells.align, col, i);
            d.cellBorderWidth = gridPick(d.calcdata.cells.line.width, col, i);
            d.font = font;
        });
}

function setFont(cellText) {
    cellText
        .each(function(d) {
            Drawing.font(d3.select(this), d.font);
        });
}

function sizeAndStyleRect(cellRect) {
    cellRect
        .attr('width', function(d) {return d.column.columnWidth;})
        .attr('stroke-width', function(d) {return d.cellBorderWidth;})
        .each(function(d) {
            var atomicSelection = d3.select(this);
            Color.stroke(atomicSelection, gridPick(d.calcdata.cells.line.color, d.column.specIndex, d.rowNumber));
            Color.fill(atomicSelection, gridPick(d.calcdata.cells.fill.color, d.column.specIndex, d.rowNumber));
        });
}

function populateCellText(cellText, tableControlView, allColumnBlock, gd) {
    cellText
        .text(function(d) {

            var col = d.column.specIndex;
            var row = d.rowNumber;

            var userSuppliedContent = d.value;
            var stringSupplied = (typeof userSuppliedContent === 'string');
            var hasBreaks = stringSupplied && userSuppliedContent.match(/<br>/i);
            var userBrokenText = !stringSupplied || hasBreaks;
            d.mayHaveMarkup = stringSupplied && userSuppliedContent.match(/[<&>]/);

            var latex = isLatex(userSuppliedContent);
            d.latex = latex;

            var prefix = latex ? '' : gridPick(d.calcdata.cells.prefix, col, row) || '';
            var suffix = latex ? '' : gridPick(d.calcdata.cells.suffix, col, row) || '';
            var format = latex ? null : gridPick(d.calcdata.cells.format, col, row) || null;

            var prefixSuffixedText = prefix + (format ? d3.format(format)(d.value) : d.value) + suffix;

            var hasWrapSplitCharacter;
            d.wrappingNeeded = !d.wrapped && !userBrokenText && !latex && (hasWrapSplitCharacter = hasWrapCharacter(prefixSuffixedText));
            d.cellHeightMayIncrease = hasBreaks || latex || d.mayHaveMarkup || (hasWrapSplitCharacter === void(0) ? hasWrapCharacter(prefixSuffixedText) : hasWrapSplitCharacter);
            d.needsConvertToTspans = d.mayHaveMarkup || d.wrappingNeeded || d.latex;

            var textToRender;
            if(d.wrappingNeeded) {
                var hrefPreservedText = c.wrapSplitCharacter === ' ' ? prefixSuffixedText.replace(/<a href=/ig, '<a_href=') : prefixSuffixedText;
                var fragments = hrefPreservedText.split(c.wrapSplitCharacter);
                var hrefRestoredFragments = c.wrapSplitCharacter === ' ' ? fragments.map(function(frag) {return frag.replace(/<a_href=/ig, '<a href=');}) : fragments;
                d.fragments = hrefRestoredFragments.map(function(f) {return {text: f, width: null};});
                d.fragments.push({fragment: c.wrapSpacer, width: null});
                textToRender = hrefRestoredFragments.join(c.lineBreaker) + c.lineBreaker + c.wrapSpacer;
            } else {
                delete d.fragments;
                textToRender = prefixSuffixedText;
            }

            return textToRender;
        })
        .attr('dy', function(d) {
            return d.needsConvertToTspans ? 0 : '0.75em';
        })
        .each(function(d) {

            var element = this;
            var selection = d3.select(element);

            // finalize what's in the DOM

            var renderCallback = d.wrappingNeeded ? wrapTextMaker : updateYPositionMaker;
            if(d.needsConvertToTspans) {
                svgUtil.convertToTspans(selection, gd, renderCallback(allColumnBlock, element, tableControlView, gd, d));
            } else {
                d3.select(element.parentNode)
                    // basic cell adjustment - compliance with `cellPad`
                    .attr('transform', function(d) {return 'translate(' + xPosition(d) + ' ' + c.cellPad + ')';})
                    .attr('text-anchor', function(d) {
                        return ({
                            left: 'start',
                            center: 'middle',
                            right: 'end'
                        })[d.align];
                    });
            }
        });
}

function isLatex(content) {
    return typeof content === 'string' && content.match(c.latexCheck);
}

function hasWrapCharacter(text) {return text.indexOf(c.wrapSplitCharacter) !== -1;}

function columnMoved(gd, calcdata, indices) {
    var o = calcdata.gdColumnsOriginalOrder;
    calcdata.gdColumns.sort(function(a, b) {
        return indices[o.indexOf(a)] - indices[o.indexOf(b)];
    });

    calcdata.columnorder = indices;

    // TODO: there's no data here, but also this reordering is not reflected
    // in gd.data or even gd._fullData.
    // For now I will not attempt to persist this in _preGUI
    gd.emit('plotly_restyle');
}

function gridPick(spec, col, row) {
    if(Array.isArray(spec)) {
        var column = spec[Math.min(col, spec.length - 1)];
        if(Array.isArray(column)) {
            return column[Math.min(row, column.length - 1)];
        } else {
            return column;
        }
    } else {
        return spec;
    }
}

function easeColumn(selection, d, y) {
    selection
        .transition()
        .ease(c.releaseTransitionEase)
        .duration(c.releaseTransitionDuration)
        .attr('transform', 'translate(' + d.x + ' ' + y + ')');
}

function cellsBlock(d) {return d.type === 'cells';}
function headerBlock(d) {return d.type === 'header';}

/**
 * Revolver panel and cell contents layouting
 */

function headerHeight(d) {
    var headerBlocks = d.rowBlocks.length ? d.rowBlocks[0].auxiliaryBlocks : [];
    return headerBlocks.reduce(function(p, n) {return p + rowsHeight(n, Infinity);}, 0);
}

function findPagesAndCacheHeights(blocks, scrollY, scrollHeight) {

    var pages = [];
    var pTop = 0;

    for(var blockIndex = 0; blockIndex < blocks.length; blockIndex++) {

        var block = blocks[blockIndex];
        var blockRows = block.rows;
        var rowsHeight = 0;
        for(var i = 0; i < blockRows.length; i++) {
            rowsHeight += blockRows[i].rowHeight;
        }

        // caching allRowsHeight on the block - it's safe as this function is always called from within the code part
        // that handles increases to row heights
        block.allRowsHeight = rowsHeight;

        var pBottom = pTop + rowsHeight;
        var windowTop = scrollY;
        var windowBottom = windowTop + scrollHeight;
        if(windowTop < pBottom && windowBottom > pTop) {
            pages.push(blockIndex);
        }
        pTop += rowsHeight;

        // consider this nice final optimization; put it in `for` condition - caveat, currently the
        // block.allRowsHeight relies on being invalidated, so enabling this opt may not be safe
        // if(pages.length > 1) break;
    }

    return pages;
}

function updateBlockYPosition(gd, cellsColumnBlock, tableControlView) {
    var d = flatData(cellsColumnBlock)[0];
    if(d === undefined) return;
    var blocks = d.rowBlocks;
    var calcdata = d.calcdata;

    var bottom = firstRowAnchor(blocks, blocks.length);
    var scrollHeight = d.calcdata.groupHeight - headerHeight(d);
    var scrollY = calcdata.scrollY = Math.max(0, Math.min(bottom - scrollHeight, calcdata.scrollY));

    var pages = findPagesAndCacheHeights(blocks, scrollY, scrollHeight);
    if(pages.length === 1) {
        if(pages[0] === blocks.length - 1) {
            pages.unshift(pages[0] - 1);
        } else {
            pages.push(pages[0] + 1);
        }
    }

    // make phased out page jump by 2 while leaving stationary page intact
    if(pages[0] % 2) {
        pages.reverse();
    }

    cellsColumnBlock
        .each(function(d, i) {
            // these values will also be needed when a block is translated again due to growing cell height
            d.page = pages[i];
            d.scrollY = scrollY;
        });

    cellsColumnBlock
        .attr('transform', function(d) {
            var yTranslate = firstRowAnchor(d.rowBlocks, d.page) - d.scrollY;
            return 'translate(0 ' + yTranslate + ')';
        });

    // conditionally rerendering panel 0 and 1
    if(gd) {
        conditionalPanelRerender(gd, tableControlView, cellsColumnBlock, pages, d.prevPages, d, 0);
        conditionalPanelRerender(gd, tableControlView, cellsColumnBlock, pages, d.prevPages, d, 1);
        renderScrollbarKit(tableControlView, gd);
    }
}

function makeDragRow(gd, allTableControlView, optionalMultiplier, optionalPosition) {
    return function dragRow(eventD) {
        // may come from whichever DOM event target: drag, wheel, bar... eventD corresponds to event target
        var d = eventD.calcdata ? eventD.calcdata : eventD;
        var tableControlView = allTableControlView.filter(function(dd) {return d.key === dd.key;});
        var multiplier = optionalMultiplier || d.scrollbarState.dragMultiplier;

        var initialScrollY = d.scrollY;

        d.scrollY = optionalPosition === void(0) ? d.scrollY + multiplier * d3.event.dy : optionalPosition;
        var cellsColumnBlock = tableControlView.selectAll('.' + c.cn.yColumn).selectAll('.' + c.cn.columnBlock).filter(cellsBlock);
        updateBlockYPosition(gd, cellsColumnBlock, tableControlView);

        // return false if we've "used" the scroll, ie it did something,
        // so the event shouldn't bubble (if appropriate)
        return d.scrollY === initialScrollY;
    };
}

function conditionalPanelRerender(gd, tableControlView, cellsColumnBlock, pages, prevPages, d, revolverIndex) {
    var shouldComponentUpdate = pages[revolverIndex] !== prevPages[revolverIndex];
    if(shouldComponentUpdate) {
        clearTimeout(d.currentRepaint[revolverIndex]);
        d.currentRepaint[revolverIndex] = setTimeout(function() {
            // setTimeout might lag rendering but yields a smoother scroll, because fast scrolling makes
            // some repaints invisible ie. wasteful (DOM work blocks the main thread)
            var toRerender = cellsColumnBlock.filter(function(d, i) {return i === revolverIndex && pages[i] !== prevPages[i];});
            renderColumnCellTree(gd, tableControlView, toRerender, cellsColumnBlock);
            prevPages[revolverIndex] = pages[revolverIndex];
        });
    }
}

function wrapTextMaker(columnBlock, element, tableControlView, gd) {
    return function wrapText() {
        var cellTextHolder = d3.select(element.parentNode);
        cellTextHolder
            .each(function(d) {
                var fragments = d.fragments;
                cellTextHolder.selectAll('tspan.line').each(function(dd, i) {
                    fragments[i].width = this.getComputedTextLength();
                });
                // last element is only for measuring the separator character, so it's ignored:
                var separatorLength = fragments[fragments.length - 1].width;
                var rest = fragments.slice(0, -1);
                var currentRow = [];
                var currentAddition, currentAdditionLength;
                var currentRowLength = 0;
                var rowLengthLimit = d.column.columnWidth - 2 * c.cellPad;
                d.value = '';
                while(rest.length) {
                    currentAddition = rest.shift();
                    currentAdditionLength = currentAddition.width + separatorLength;
                    if(currentRowLength + currentAdditionLength > rowLengthLimit) {
                        d.value += currentRow.join(c.wrapSpacer) + c.lineBreaker;
                        currentRow = [];
                        currentRowLength = 0;
                    }
                    currentRow.push(currentAddition.text);
                    currentRowLength += currentAdditionLength;
                }
                if(currentRowLength) {
                    d.value += currentRow.join(c.wrapSpacer);
                }
                d.wrapped = true;
            });

        // the pre-wrapped text was rendered only for the text measurements
        cellTextHolder.selectAll('tspan.line').remove();

        // resupply text, now wrapped
        populateCellText(cellTextHolder.select('.' + c.cn.cellText), tableControlView, columnBlock, gd);
        d3.select(element.parentNode.parentNode).call(setCellHeightAndPositionY);
    };
}

function updateYPositionMaker(columnBlock, element, tableControlView, gd, d) {
    return function updateYPosition() {
        if(d.settledY) return;
        var cellTextHolder = d3.select(element.parentNode);
        var l = getBlock(d);
        var rowIndex = d.key - l.firstRowIndex;

        var declaredRowHeight = l.rows[rowIndex].rowHeight;

        var requiredHeight = d.cellHeightMayIncrease ? element.parentNode.getBoundingClientRect().height + 2 * c.cellPad : declaredRowHeight;

        var finalHeight = Math.max(requiredHeight, declaredRowHeight);
        var increase = finalHeight - l.rows[rowIndex].rowHeight;

        if(increase) {

            // current row height increased
            l.rows[rowIndex].rowHeight = finalHeight;

            columnBlock
                .selectAll('.' + c.cn.columnCell)
                .call(setCellHeightAndPositionY);

            updateBlockYPosition(null, columnBlock.filter(cellsBlock), 0);

            // if d.column.type === 'header', then the scrollbar has to be pushed downward to the scrollable area
            // if d.column.type === 'cells', it can still be relevant if total scrolling content height is less than the
            //                               scrollable window, as increases to row heights may need scrollbar updates
            renderScrollbarKit(tableControlView, gd, true);
        }

        cellTextHolder
            .attr('transform', function() {
                // this code block is only invoked for items where d.cellHeightMayIncrease is truthy
                var element = this;
                var columnCellElement = element.parentNode;
                var box = columnCellElement.getBoundingClientRect();
                var rectBox = d3.select(element.parentNode).select('.' + c.cn.cellRect).node().getBoundingClientRect();
                var currentTransform = element.transform.baseVal.consolidate();
                var yPosition = rectBox.top - box.top + (currentTransform ? currentTransform.matrix.f : c.cellPad);
                return 'translate(' + xPosition(d, d3.select(element.parentNode).select('.' + c.cn.cellTextHolder).node().getBoundingClientRect().width) + ' ' + yPosition + ')';
            });

        d.settledY = true;
    };
}

function xPosition(d, optionalWidth) {
    switch(d.align) {
        case 'left': return c.cellPad;
        case 'right': return d.column.columnWidth - (optionalWidth || 0) - c.cellPad;
        case 'center': return (d.column.columnWidth - (optionalWidth || 0)) / 2;
        default: return c.cellPad;
    }
}

function setCellHeightAndPositionY(columnCell) {
    columnCell
        .attr('transform', function(d) {
            var headerHeight = d.rowBlocks[0].auxiliaryBlocks.reduce(function(p, n) {return p + rowsHeight(n, Infinity);}, 0);
            var l = getBlock(d);
            var rowAnchor = rowsHeight(l, d.key);
            var yOffset = rowAnchor + headerHeight;
            return 'translate(0 ' + yOffset + ')';
        })
        .selectAll('.' + c.cn.cellRect)
        .attr('height', function(d) {return getRow(getBlock(d), d.key).rowHeight;});
}

function firstRowAnchor(blocks, page) {
    var total = 0;
    for(var i = page - 1; i >= 0; i--) {
        total += allRowsHeight(blocks[i]);
    }
    return total;
}

function rowsHeight(rowBlock, key) {
    var total = 0;
    for(var i = 0; i < rowBlock.rows.length && rowBlock.rows[i].rowIndex < key; i++) {
        total += rowBlock.rows[i].rowHeight;
    }
    return total;
}

function allRowsHeight(rowBlock) {
    var cached = rowBlock.allRowsHeight;

    if(cached !== void(0)) {
        return cached;
    }

    var total = 0;
    for(var i = 0; i < rowBlock.rows.length; i++) {
        total += rowBlock.rows[i].rowHeight;
    }
    rowBlock.allRowsHeight = total;

    return total;
}

function getBlock(d) {return d.rowBlocks[d.page];}
function getRow(l, i) {return l.rows[i - l.firstRowIndex];}

},{"../../components/color":574,"../../components/drawing":595,"../../lib":697,"../../lib/gup":695,"../../lib/svg_text_utils":721,"./constants":1143,"./data_preparation_helper":1144,"./data_split_helpers":1145,"d3":151}],1149:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var boxAttrs = _dereq_('../box/attributes');
var extendFlat = _dereq_('../../lib/extend').extendFlat;

module.exports = {
    y: boxAttrs.y,
    x: boxAttrs.x,
    x0: boxAttrs.x0,
    y0: boxAttrs.y0,
    name: boxAttrs.name,
    orientation: extendFlat({}, boxAttrs.orientation, {
        
    }),

    bandwidth: {
        valType: 'number',
        min: 0,
        
        editType: 'calc',
        
    },

    scalegroup: {
        valType: 'string',
        
        dflt: '',
        editType: 'calc',
        
    },
    scalemode: {
        valType: 'enumerated',
        values: ['width', 'count'],
        dflt: 'width',
        
        editType: 'calc',
        
    },

    spanmode: {
        valType: 'enumerated',
        values: ['soft', 'hard', 'manual'],
        dflt: 'soft',
        
        editType: 'calc',
        
    },
    span: {
        valType: 'info_array',
        items: [
            {valType: 'any', editType: 'calc'},
            {valType: 'any', editType: 'calc'}
        ],
        
        editType: 'calc',
        
    },

    line: {
        color: {
            valType: 'color',
            
            editType: 'style',
            
        },
        width: {
            valType: 'number',
            
            min: 0,
            dflt: 2,
            editType: 'style',
            
        },
        editType: 'plot'
    },
    fillcolor: boxAttrs.fillcolor,

    points: extendFlat({}, boxAttrs.boxpoints, {
        
    }),
    jitter: extendFlat({}, boxAttrs.jitter, {
        
    }),
    pointpos: extendFlat({}, boxAttrs.pointpos, {
        
    }),

    width: extendFlat({}, boxAttrs.width, {
        
    }),

    marker: boxAttrs.marker,
    text: boxAttrs.text,
    hovertext: boxAttrs.hovertext,

    box: {
        visible: {
            valType: 'boolean',
            dflt: false,
            
            editType: 'plot',
            
        },
        width: {
            valType: 'number',
            min: 0,
            max: 1,
            dflt: 0.25,
            
            editType: 'plot',
            
        },
        fillcolor: {
            valType: 'color',
            
            editType: 'style',
            
        },
        line: {
            color: {
                valType: 'color',
                
                editType: 'style',
                
            },
            width: {
                valType: 'number',
                min: 0,
                
                editType: 'style',
                
            },
            editType: 'style'
        },
        editType: 'plot'
    },

    meanline: {
        visible: {
            valType: 'boolean',
            dflt: false,
            
            editType: 'plot',
            
        },
        color: {
            valType: 'color',
            
            editType: 'style',
            
        },
        width: {
            valType: 'number',
            min: 0,
            
            editType: 'style',
            
        },
        editType: 'plot'
    },

    side: {
        valType: 'enumerated',
        values: ['both', 'positive', 'negative'],
        dflt: 'both',
        
        editType: 'calc',
        
    },

    offsetgroup: boxAttrs.offsetgroup,
    alignmentgroup: boxAttrs.alignmentgroup,

    selected: boxAttrs.selected,
    unselected: boxAttrs.unselected,

    hoveron: {
        valType: 'flaglist',
        flags: ['violins', 'points', 'kde'],
        dflt: 'violins+points+kde',
        extras: ['all'],
        
        editType: 'style',
        
    }
};

},{"../../lib/extend":687,"../box/attributes":859}],1150:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');
var boxCalc = _dereq_('../box/calc');
var helpers = _dereq_('./helpers');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

module.exports = function calc(gd, trace) {
    var cd = boxCalc(gd, trace);

    if(cd[0].t.empty) return cd;

    var fullLayout = gd._fullLayout;
    var valAxis = Axes.getFromId(
        gd,
        trace[trace.orientation === 'h' ? 'xaxis' : 'yaxis']
    );

    var spanMin = Infinity;
    var spanMax = -Infinity;
    var maxKDE = 0;
    var maxCount = 0;

    for(var i = 0; i < cd.length; i++) {
        var cdi = cd[i];
        var vals = cdi.pts.map(helpers.extractVal);

        var bandwidth = cdi.bandwidth = calcBandwidth(trace, cdi, vals);
        var span = cdi.span = calcSpan(trace, cdi, valAxis, bandwidth);

        // step that well covers the bandwidth and is multiple of span distance
        var dist = span[1] - span[0];
        var n = Math.ceil(dist / (bandwidth / 3));
        var step = dist / n;

        if(!isFinite(step) || !isFinite(n)) {
            Lib.error('Something went wrong with computing the violin span');
            cd[0].t.empty = true;
            return cd;
        }

        var kde = helpers.makeKDE(cdi, trace, vals);
        cdi.density = new Array(n);

        for(var k = 0, t = span[0]; t < (span[1] + step / 2); k++, t += step) {
            var v = kde(t);
            cdi.density[k] = {v: v, t: t};
            maxKDE = Math.max(maxKDE, v);
        }

        maxCount = Math.max(maxCount, vals.length);
        spanMin = Math.min(spanMin, span[0]);
        spanMax = Math.max(spanMax, span[1]);
    }

    var extremes = Axes.findExtremes(valAxis, [spanMin, spanMax], {padded: true});
    trace._extremes[valAxis._id] = extremes;

    if(trace.width) {
        cd[0].t.maxKDE = maxKDE;
    } else {
        var violinScaleGroupStats = fullLayout._violinScaleGroupStats;
        var scaleGroup = trace.scalegroup;
        var groupStats = violinScaleGroupStats[scaleGroup];

        if(groupStats) {
            groupStats.maxKDE = Math.max(groupStats.maxKDE, maxKDE);
            groupStats.maxCount = Math.max(groupStats.maxCount, maxCount);
        } else {
            violinScaleGroupStats[scaleGroup] = {
                maxKDE: maxKDE,
                maxCount: maxCount
            };
        }
    }

    cd[0].t.labels.kde = Lib._(gd, 'kde:');

    return cd;
};

// Default to Silveman's rule of thumb
// - https://stats.stackexchange.com/a/6671
// - https://en.wikipedia.org/wiki/Kernel_density_estimation#A_rule-of-thumb_bandwidth_estimator
// - https://github.com/statsmodels/statsmodels/blob/master/statsmodels/nonparametric/bandwidths.py
function silvermanRule(len, ssd, iqr) {
    var a = Math.min(ssd, iqr / 1.349);
    return 1.059 * a * Math.pow(len, -0.2);
}

function calcBandwidth(trace, cdi, vals) {
    var span = cdi.max - cdi.min;

    // plot single-value violin with bandwidth of 1
    if(!span) return 1;

    // Limit how small the bandwidth can be.
    //
    // Silverman's rule of thumb can be "very" small
    // when IQR does a poor job at describing the spread
    // of the distribution.
    // We also want to limit custom bandwidths
    // to not blow up kde computations.

    if(trace.bandwidth) {
        return Math.max(trace.bandwidth, span / 1e4);
    } else {
        var len = vals.length;
        var ssd = Lib.stdev(vals, len - 1, cdi.mean);
        return Math.max(
            silvermanRule(len, ssd, cdi.q3 - cdi.q1),
            span / 100
        );
    }
}

function calcSpan(trace, cdi, valAxis, bandwidth) {
    var spanmode = trace.spanmode;
    var spanIn = trace.span || [];
    var spanTight = [cdi.min, cdi.max];
    var spanLoose = [cdi.min - 2 * bandwidth, cdi.max + 2 * bandwidth];
    var spanOut;

    function calcSpanItem(index) {
        var s = spanIn[index];
        var sc = valAxis.type === 'multicategory' ?
            valAxis.r2c(s) :
            valAxis.d2c(s, 0, trace[cdi.valLetter + 'calendar']);
        return sc === BADNUM ? spanLoose[index] : sc;
    }

    if(spanmode === 'soft') {
        spanOut = spanLoose;
    } else if(spanmode === 'hard') {
        spanOut = spanTight;
    } else {
        spanOut = [calcSpanItem(0), calcSpanItem(1)];
    }

    // to reuse the equal-range-item block
    var dummyAx = {
        type: 'linear',
        range: spanOut
    };
    Axes.setConvert(dummyAx);
    dummyAx.cleanRange();

    return spanOut;
}

},{"../../constants/numerical":674,"../../lib":697,"../../plots/cartesian/axes":745,"../box/calc":860,"./helpers":1153}],1151:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var setPositionOffset = _dereq_('../box/cross_trace_calc').setPositionOffset;
var orientations = ['v', 'h'];

module.exports = function crossTraceCalc(gd, plotinfo) {
    var calcdata = gd.calcdata;
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    for(var i = 0; i < orientations.length; i++) {
        var orientation = orientations[i];
        var posAxis = orientation === 'h' ? ya : xa;
        var violinList = [];

        for(var j = 0; j < calcdata.length; j++) {
            var cd = calcdata[j];
            var t = cd[0].t;
            var trace = cd[0].trace;

            if(trace.visible === true && trace.type === 'violin' &&
                    !t.empty &&
                    trace.orientation === orientation &&
                    trace.xaxis === xa._id &&
                    trace.yaxis === ya._id
              ) {
                violinList.push(j);
            }
        }

        setPositionOffset('violin', gd, violinList, posAxis);
    }
};

},{"../box/cross_trace_calc":861}],1152:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Color = _dereq_('../../components/color');

var boxDefaults = _dereq_('../box/defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }
    function coerce2(attr, dflt) {
        return Lib.coerce2(traceIn, traceOut, attributes, attr, dflt);
    }

    boxDefaults.handleSampleDefaults(traceIn, traceOut, coerce, layout);
    if(traceOut.visible === false) return;

    coerce('bandwidth');
    coerce('side');

    var width = coerce('width');
    if(!width) {
        coerce('scalegroup', traceOut.name);
        coerce('scalemode');
    }

    var span = coerce('span');
    var spanmodeDflt;
    if(Array.isArray(span)) spanmodeDflt = 'manual';
    coerce('spanmode', spanmodeDflt);

    var lineColor = coerce('line.color', (traceIn.marker || {}).color || defaultColor);
    var lineWidth = coerce('line.width');
    var fillColor = coerce('fillcolor', Color.addOpacity(traceOut.line.color, 0.5));

    boxDefaults.handlePointsDefaults(traceIn, traceOut, coerce, {prefix: ''});

    var boxWidth = coerce2('box.width');
    var boxFillColor = coerce2('box.fillcolor', fillColor);
    var boxLineColor = coerce2('box.line.color', lineColor);
    var boxLineWidth = coerce2('box.line.width', lineWidth);
    var boxVisible = coerce('box.visible', Boolean(boxWidth || boxFillColor || boxLineColor || boxLineWidth));
    if(!boxVisible) traceOut.box = {visible: false};

    var meanLineColor = coerce2('meanline.color', lineColor);
    var meanLineWidth = coerce2('meanline.width', lineWidth);
    var meanLineVisible = coerce('meanline.visible', Boolean(meanLineColor || meanLineWidth));
    if(!meanLineVisible) traceOut.meanline = {visible: false};
};

},{"../../components/color":574,"../../lib":697,"../box/defaults":862,"./attributes":1149}],1153:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

// Maybe add kernels more down the road,
// but note that the default `spanmode: 'soft'` bounds might have
// to become kernel-dependent
var kernels = {
    gaussian: function(v) {
        return (1 / Math.sqrt(2 * Math.PI)) * Math.exp(-0.5 * v * v);
    }
};

exports.makeKDE = function(calcItem, trace, vals) {
    var len = vals.length;
    var kernel = kernels.gaussian;
    var bandwidth = calcItem.bandwidth;
    var factor = 1 / (len * bandwidth);

    // don't use Lib.aggNums to skip isNumeric checks
    return function(x) {
        var sum = 0;
        for(var i = 0; i < len; i++) {
            sum += kernel((x - vals[i]) / bandwidth);
        }
        return factor * sum;
    };
};

exports.getPositionOnKdePath = function(calcItem, trace, valuePx) {
    var posLetter, valLetter;

    if(trace.orientation === 'h') {
        posLetter = 'y';
        valLetter = 'x';
    } else {
        posLetter = 'x';
        valLetter = 'y';
    }

    var pointOnPath = Lib.findPointOnPath(
        calcItem.path,
        valuePx,
        valLetter,
        {pathLength: calcItem.pathLength}
    );

    var posCenterPx = calcItem.posCenterPx;
    var posOnPath0 = pointOnPath[posLetter];
    var posOnPath1 = trace.side === 'both' ?
        2 * posCenterPx - posOnPath0 :
        posCenterPx;

    return [posOnPath0, posOnPath1];
};

exports.getKdeValue = function(calcItem, trace, valueDist) {
    var vals = calcItem.pts.map(exports.extractVal);
    var kde = exports.makeKDE(calcItem, trace, vals);
    return kde(valueDist) / calcItem.posDensityScale;
};

exports.extractVal = function(o) { return o.v; };

},{"../../lib":697}],1154:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');
var boxHoverPoints = _dereq_('../box/hover');
var helpers = _dereq_('./helpers');

module.exports = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer) {
    var cd = pointData.cd;
    var trace = cd[0].trace;
    var hoveron = trace.hoveron;
    var hasHoveronViolins = hoveron.indexOf('violins') !== -1;
    var hasHoveronKDE = hoveron.indexOf('kde') !== -1;
    var closeData = [];
    var closePtData;
    var violinLineAttrs;

    if(hasHoveronViolins || hasHoveronKDE) {
        var closeBoxData = boxHoverPoints.hoverOnBoxes(pointData, xval, yval, hovermode);

        if(hasHoveronViolins) {
            closeData = closeData.concat(closeBoxData);
        }

        if(hasHoveronKDE && closeBoxData.length > 0) {
            var xa = pointData.xa;
            var ya = pointData.ya;
            var pLetter, vLetter, pAxis, vAxis, vVal;

            if(trace.orientation === 'h') {
                vVal = xval;
                pLetter = 'y';
                pAxis = ya;
                vLetter = 'x';
                vAxis = xa;
            } else {
                vVal = yval;
                pLetter = 'x';
                pAxis = xa;
                vLetter = 'y';
                vAxis = ya;
            }

            var di = cd[pointData.index];

            if(vVal >= di.span[0] && vVal <= di.span[1]) {
                var kdePointData = Lib.extendFlat({}, pointData);
                var vValPx = vAxis.c2p(vVal, true);
                var kdeVal = helpers.getKdeValue(di, trace, vVal);
                var pOnPath = helpers.getPositionOnKdePath(di, trace, vValPx);
                var paOffset = pAxis._offset;
                var paLength = pAxis._length;

                kdePointData[pLetter + '0'] = pOnPath[0];
                kdePointData[pLetter + '1'] = pOnPath[1];
                kdePointData[vLetter + '0'] = kdePointData[vLetter + '1'] = vValPx;
                kdePointData[vLetter + 'Label'] = vLetter + ': ' + Axes.hoverLabelText(vAxis, vVal) + ', ' + cd[0].t.labels.kde + ' ' + kdeVal.toFixed(3);

                // move the spike to the KDE point
                kdePointData.spikeDistance = closeBoxData[0].spikeDistance;
                var spikePosAttr = pLetter + 'Spike';
                kdePointData[spikePosAttr] = closeBoxData[0][spikePosAttr];
                closeBoxData[0].spikeDistance = undefined;
                closeBoxData[0][spikePosAttr] = undefined;

                closeData.push(kdePointData);

                violinLineAttrs = {stroke: pointData.color};
                violinLineAttrs[pLetter + '1'] = Lib.constrain(paOffset + pOnPath[0], paOffset, paOffset + paLength);
                violinLineAttrs[pLetter + '2'] = Lib.constrain(paOffset + pOnPath[1], paOffset, paOffset + paLength);
                violinLineAttrs[vLetter + '1'] = violinLineAttrs[vLetter + '2'] = vAxis._offset + vValPx;
            }
        }
    }

    if(hoveron.indexOf('points') !== -1) {
        closePtData = boxHoverPoints.hoverOnPoints(pointData, xval, yval);
    }

    // update violin line (if any)
    var violinLine = hoverLayer.selectAll('.violinline-' + trace.uid)
        .data(violinLineAttrs ? [0] : []);
    violinLine.enter().append('line')
        .classed('violinline-' + trace.uid, true)
        .attr('stroke-width', 1.5);
    violinLine.exit().remove();
    violinLine.attr(violinLineAttrs);

    // same combine logic as box hoverPoints
    if(hovermode === 'closest') {
        if(closePtData) return [closePtData];
        return closeData;
    }
    if(closePtData) {
        closeData.push(closePtData);
        return closeData;
    }
    return closeData;
};

},{"../../lib":697,"../../plots/cartesian/axes":745,"../box/hover":864,"./helpers":1153}],1155:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    attributes: _dereq_('./attributes'),
    layoutAttributes: _dereq_('./layout_attributes'),
    supplyDefaults: _dereq_('./defaults'),
    crossTraceDefaults: _dereq_('../box/defaults').crossTraceDefaults,
    supplyLayoutDefaults: _dereq_('./layout_defaults'),
    calc: _dereq_('./calc'),
    crossTraceCalc: _dereq_('./cross_trace_calc'),
    plot: _dereq_('./plot'),
    style: _dereq_('./style'),
    styleOnSelect: _dereq_('../scatter/style').styleOnSelect,
    hoverPoints: _dereq_('./hover'),
    selectPoints: _dereq_('../box/select'),

    moduleType: 'trace',
    name: 'violin',
    basePlotModule: _dereq_('../../plots/cartesian'),
    categories: ['cartesian', 'svg', 'symbols', 'oriented', 'box-violin', 'showLegend', 'violinLayout', 'zoomScale'],
    meta: {
        
    }
};

},{"../../plots/cartesian":756,"../box/defaults":862,"../box/select":869,"../scatter/style":1071,"./attributes":1149,"./calc":1150,"./cross_trace_calc":1151,"./defaults":1152,"./hover":1154,"./layout_attributes":1156,"./layout_defaults":1157,"./plot":1158,"./style":1159}],1156:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var boxLayoutAttrs = _dereq_('../box/layout_attributes');
var extendFlat = _dereq_('../../lib').extendFlat;

module.exports = {
    violinmode: extendFlat({}, boxLayoutAttrs.boxmode, {
        
    }),
    violingap: extendFlat({}, boxLayoutAttrs.boxgap, {
        
    }),
    violingroupgap: extendFlat({}, boxLayoutAttrs.boxgroupgap, {
        
    })
};

},{"../../lib":697,"../box/layout_attributes":866}],1157:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var layoutAttributes = _dereq_('./layout_attributes');
var boxLayoutDefaults = _dereq_('../box/layout_defaults');

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
    function coerce(attr, dflt) {
        return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
    }
    boxLayoutDefaults._supply(layoutIn, layoutOut, fullData, coerce, 'violin');
};

},{"../../lib":697,"../box/layout_defaults":867,"./layout_attributes":1156}],1158:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var Lib = _dereq_('../../lib');
var Drawing = _dereq_('../../components/drawing');

var boxPlot = _dereq_('../box/plot');
var linePoints = _dereq_('../scatter/line_points');
var helpers = _dereq_('./helpers');

module.exports = function plot(gd, plotinfo, cdViolins, violinLayer) {
    var fullLayout = gd._fullLayout;
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    function makePath(pts) {
        var segments = linePoints(pts, {
            xaxis: xa,
            yaxis: ya,
            connectGaps: true,
            baseTolerance: 0.75,
            shape: 'spline',
            simplify: true
        });
        return Drawing.smoothopen(segments[0], 1);
    }

    Lib.makeTraceGroups(violinLayer, cdViolins, 'trace violins').each(function(cd) {
        var plotGroup = d3.select(this);
        var cd0 = cd[0];
        var t = cd0.t;
        var trace = cd0.trace;
        if(!plotinfo.isRangePlot) cd0.node3 = plotGroup;

        if(trace.visible !== true || t.empty) {
            plotGroup.remove();
            return;
        }

        var bPos = t.bPos;
        var bdPos = t.bdPos;
        var valAxis = plotinfo[t.valLetter + 'axis'];
        var posAxis = plotinfo[t.posLetter + 'axis'];
        var hasBothSides = trace.side === 'both';
        var hasPositiveSide = hasBothSides || trace.side === 'positive';
        var hasNegativeSide = hasBothSides || trace.side === 'negative';

        var violins = plotGroup.selectAll('path.violin').data(Lib.identity);

        violins.enter().append('path')
            .style('vector-effect', 'non-scaling-stroke')
            .attr('class', 'violin');

        violins.exit().remove();

        violins.each(function(d) {
            var pathSel = d3.select(this);
            var density = d.density;
            var len = density.length;
            var posCenter = d.pos + bPos;
            var posCenterPx = posAxis.c2p(posCenter);

            var scale;
            if(trace.width) {
                scale = t.maxKDE / bdPos;
            } else {
                var groupStats = fullLayout._violinScaleGroupStats[trace.scalegroup];
                scale = trace.scalemode === 'count' ?
                    (groupStats.maxKDE / bdPos) * (groupStats.maxCount / d.pts.length) :
                    groupStats.maxKDE / bdPos;
            }

            var pathPos, pathNeg, path;
            var i, k, pts, pt;

            if(hasPositiveSide) {
                pts = new Array(len);
                for(i = 0; i < len; i++) {
                    pt = pts[i] = {};
                    pt[t.posLetter] = posCenter + (density[i].v / scale);
                    pt[t.valLetter] = density[i].t;
                }
                pathPos = makePath(pts);
            }

            if(hasNegativeSide) {
                pts = new Array(len);
                for(k = 0, i = len - 1; k < len; k++, i--) {
                    pt = pts[k] = {};
                    pt[t.posLetter] = posCenter - (density[i].v / scale);
                    pt[t.valLetter] = density[i].t;
                }
                pathNeg = makePath(pts);
            }

            if(hasBothSides) {
                path = pathPos + 'L' + pathNeg.substr(1) + 'Z';
            }
            else {
                var startPt = [posCenterPx, valAxis.c2p(density[0].t)];
                var endPt = [posCenterPx, valAxis.c2p(density[len - 1].t)];

                if(trace.orientation === 'h') {
                    startPt.reverse();
                    endPt.reverse();
                }

                if(hasPositiveSide) {
                    path = 'M' + startPt + 'L' + pathPos.substr(1) + 'L' + endPt;
                } else {
                    path = 'M' + endPt + 'L' + pathNeg.substr(1) + 'L' + startPt;
                }
            }
            pathSel.attr('d', path);

            // save a few things used in getPositionOnKdePath, getKdeValue
            // on hover and for meanline draw block below
            d.posCenterPx = posCenterPx;
            d.posDensityScale = scale * bdPos;
            d.path = pathSel.node();
            d.pathLength = d.path.getTotalLength() / (hasBothSides ? 2 : 1);
        });

        var boxAttrs = trace.box;
        var boxWidth = boxAttrs.width;
        var boxLineWidth = (boxAttrs.line || {}).width;
        var bdPosScaled;
        var bPosPxOffset;

        if(hasBothSides) {
            bdPosScaled = bdPos * boxWidth;
            bPosPxOffset = 0;
        } else if(hasPositiveSide) {
            bdPosScaled = [0, bdPos * boxWidth / 2];
            bPosPxOffset = -boxLineWidth;
        } else {
            bdPosScaled = [bdPos * boxWidth / 2, 0];
            bPosPxOffset = boxLineWidth;
        }

        // inner box
        boxPlot.plotBoxAndWhiskers(plotGroup, {pos: posAxis, val: valAxis}, trace, {
            bPos: bPos,
            bdPos: bdPosScaled,
            bPosPxOffset: bPosPxOffset
        });

        // meanline insider box
        boxPlot.plotBoxMean(plotGroup, {pos: posAxis, val: valAxis}, trace, {
            bPos: bPos,
            bdPos: bdPosScaled,
            bPosPxOffset: bPosPxOffset
        });

        var fn;
        if(!trace.box.visible && trace.meanline.visible) {
            fn = Lib.identity;
        }

        // N.B. use different class name than boxPlot.plotBoxMean,
        // to avoid selectAll conflict
        var meanPaths = plotGroup.selectAll('path.meanline').data(fn || []);
        meanPaths.enter().append('path')
            .attr('class', 'meanline')
            .style('fill', 'none')
            .style('vector-effect', 'non-scaling-stroke');
        meanPaths.exit().remove();
        meanPaths.each(function(d) {
            var v = valAxis.c2p(d.mean, true);
            var p = helpers.getPositionOnKdePath(d, trace, v);

            d3.select(this).attr('d',
                trace.orientation === 'h' ?
                    'M' + v + ',' + p[0] + 'V' + p[1] :
                    'M' + p[0] + ',' + v + 'H' + p[1]
            );
        });

        boxPlot.plotPoints(plotGroup, {x: xa, y: ya}, trace, t);
    });
};

},{"../../components/drawing":595,"../../lib":697,"../box/plot":868,"../scatter/line_points":1062,"./helpers":1153,"d3":151}],1159:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var Color = _dereq_('../../components/color');
var stylePoints = _dereq_('../scatter/style').stylePoints;

module.exports = function style(gd, cd) {
    var s = cd ? cd[0].node3 : d3.select(gd).selectAll('g.trace.violins');

    s.style('opacity', function(d) { return d[0].trace.opacity; });

    s.each(function(d) {
        var trace = d[0].trace;
        var sel = d3.select(this);
        var box = trace.box || {};
        var boxLine = box.line || {};
        var meanline = trace.meanline || {};
        var meanLineWidth = meanline.width;

        sel.selectAll('path.violin')
            .style('stroke-width', trace.line.width + 'px')
            .call(Color.stroke, trace.line.color)
            .call(Color.fill, trace.fillcolor);

        sel.selectAll('path.box')
            .style('stroke-width', boxLine.width + 'px')
            .call(Color.stroke, boxLine.color)
            .call(Color.fill, box.fillcolor);

        var meanLineStyle = {
            'stroke-width': meanLineWidth + 'px',
            'stroke-dasharray': (2 * meanLineWidth) + 'px,' + meanLineWidth + 'px'
        };

        sel.selectAll('path.mean')
            .style(meanLineStyle)
            .call(Color.stroke, meanline.color);

        sel.selectAll('path.meanline')
            .style(meanLineStyle)
            .call(Color.stroke, meanline.color);

        stylePoints(sel, trace, gd);
    });
};

},{"../../components/color":574,"../scatter/style":1071,"d3":151}],1160:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Axes = _dereq_('../plots/cartesian/axes');
var Lib = _dereq_('../lib');
var PlotSchema = _dereq_('../plot_api/plot_schema');
var pointsAccessorFunction = _dereq_('./helpers').pointsAccessorFunction;
var BADNUM = _dereq_('../constants/numerical').BADNUM;

exports.moduleType = 'transform';

exports.name = 'aggregate';

var attrs = exports.attributes = {
    enabled: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'calc',
        
    },
    groups: {
        // TODO: groupby should support string or array grouping this way too
        // currently groupby only allows a grouping array
        valType: 'string',
        strict: true,
        noBlank: true,
        arrayOk: true,
        dflt: 'x',
        
        editType: 'calc',
        
    },
    aggregations: {
        _isLinkedToArray: 'aggregation',
        target: {
            valType: 'string',
            
            editType: 'calc',
            
        },
        func: {
            valType: 'enumerated',
            values: ['count', 'sum', 'avg', 'median', 'mode', 'rms', 'stddev', 'min', 'max', 'first', 'last', 'change', 'range'],
            dflt: 'first',
            
            editType: 'calc',
            
        },
        funcmode: {
            valType: 'enumerated',
            values: ['sample', 'population'],
            dflt: 'sample',
            
            editType: 'calc',
            
        },
        enabled: {
            valType: 'boolean',
            dflt: true,
            
            editType: 'calc',
            
        },
        editType: 'calc'
    },
    editType: 'calc'
};

var aggAttrs = attrs.aggregations;

/**
 * Supply transform attributes defaults
 *
 * @param {object} transformIn
 *  object linked to trace.transforms[i] with 'func' set to exports.name
 * @param {object} traceOut
 *  the _fullData trace this transform applies to
 * @param {object} layout
 *  the plot's (not-so-full) layout
 * @param {object} traceIn
 *  the input data trace this transform applies to
 *
 * @return {object} transformOut
 *  copy of transformIn that contains attribute defaults
 */
exports.supplyDefaults = function(transformIn, traceOut) {
    var transformOut = {};
    var i;

    function coerce(attr, dflt) {
        return Lib.coerce(transformIn, transformOut, attrs, attr, dflt);
    }

    var enabled = coerce('enabled');

    if(!enabled) return transformOut;

    /*
     * Normally _arrayAttrs is calculated during doCalc, but that comes later.
     * Anyway this can change due to *count* aggregations (see below) so it's not
     * necessarily the same set.
     *
     * For performance we turn it into an object of truthy values
     * we'll use 1 for arrays we haven't aggregated yet, 0 for finished arrays,
     * as distinct from undefined which means this array isn't present in the input
     * missing arrays can still be aggregate outputs for *count* aggregations.
     */
    var arrayAttrArray = PlotSchema.findArrayAttributes(traceOut);
    var arrayAttrs = {};
    for(i = 0; i < arrayAttrArray.length; i++) arrayAttrs[arrayAttrArray[i]] = 1;

    var groups = coerce('groups');

    if(!Array.isArray(groups)) {
        if(!arrayAttrs[groups]) {
            transformOut.enabled = false;
            return transformOut;
        }
        arrayAttrs[groups] = 0;
    }

    var aggregationsIn = transformIn.aggregations || [];
    var aggregationsOut = transformOut.aggregations = new Array(aggregationsIn.length);
    var aggregationOut;

    function coercei(attr, dflt) {
        return Lib.coerce(aggregationsIn[i], aggregationOut, aggAttrs, attr, dflt);
    }

    for(i = 0; i < aggregationsIn.length; i++) {
        aggregationOut = {_index: i};
        var target = coercei('target');
        var func = coercei('func');
        var enabledi = coercei('enabled');

        // add this aggregation to the output only if it's the first instance
        // of a valid target attribute - or an unused target attribute with "count"
        if(enabledi && target && (arrayAttrs[target] || (func === 'count' && arrayAttrs[target] === undefined))) {
            if(func === 'stddev') coercei('funcmode');

            arrayAttrs[target] = 0;
            aggregationsOut[i] = aggregationOut;
        }
        else aggregationsOut[i] = {enabled: false, _index: i};
    }

    // any array attributes we haven't yet covered, fill them with the default aggregation
    for(i = 0; i < arrayAttrArray.length; i++) {
        if(arrayAttrs[arrayAttrArray[i]]) {
            aggregationsOut.push({
                target: arrayAttrArray[i],
                func: aggAttrs.func.dflt,
                enabled: true,
                _index: -1
            });
        }
    }

    return transformOut;
};


exports.calcTransform = function(gd, trace, opts) {
    if(!opts.enabled) return;

    var groups = opts.groups;

    var groupArray = Lib.getTargetArray(trace, {target: groups});
    if(!groupArray) return;

    var i, vi, groupIndex, newGrouping;

    var groupIndices = {};
    var indexToPoints = {};
    var groupings = [];

    var originalPointsAccessor = pointsAccessorFunction(trace.transforms, opts);

    var len = groupArray.length;
    if(trace._length) len = Math.min(len, trace._length);

    for(i = 0; i < len; i++) {
        vi = groupArray[i];
        groupIndex = groupIndices[vi];
        if(groupIndex === undefined) {
            groupIndices[vi] = groupings.length;
            newGrouping = [i];
            groupings.push(newGrouping);
            indexToPoints[groupIndices[vi]] = originalPointsAccessor(i);
        }
        else {
            groupings[groupIndex].push(i);
            indexToPoints[groupIndices[vi]] = (indexToPoints[groupIndices[vi]] || []).concat(originalPointsAccessor(i));
        }
    }

    opts._indexToPoints = indexToPoints;

    var aggregations = opts.aggregations;

    for(i = 0; i < aggregations.length; i++) {
        aggregateOneArray(gd, trace, groupings, aggregations[i]);
    }

    if(typeof groups === 'string') {
        aggregateOneArray(gd, trace, groupings, {
            target: groups,
            func: 'first',
            enabled: true
        });
    }

    trace._length = groupings.length;
};

function aggregateOneArray(gd, trace, groupings, aggregation) {
    if(!aggregation.enabled) return;

    var attr = aggregation.target;
    var targetNP = Lib.nestedProperty(trace, attr);
    var arrayIn = targetNP.get();
    var conversions = Axes.getDataConversions(gd, trace, attr, arrayIn);
    var func = getAggregateFunction(aggregation, conversions);

    var arrayOut = new Array(groupings.length);
    for(var i = 0; i < groupings.length; i++) {
        arrayOut[i] = func(arrayIn, groupings[i]);
    }
    targetNP.set(arrayOut);

    if(aggregation.func === 'count') {
        // count does not depend on an input array, so it's likely not part of _arrayAttrs yet
        // but after this transform it most definitely *is* an array attribute.
        Lib.pushUnique(trace._arrayAttrs, attr);
    }
}

function getAggregateFunction(opts, conversions) {
    var func = opts.func;
    var d2c = conversions.d2c;
    var c2d = conversions.c2d;

    switch(func) {
        // count, first, and last don't depend on anything about the data
        // point back to pure functions for performance
        case 'count':
            return count;
        case 'first':
            return first;
        case 'last':
            return last;

        case 'sum':
            // This will produce output in all cases even though it's nonsensical
            // for date or category data.
            return function(array, indices) {
                var total = 0;
                for(var i = 0; i < indices.length; i++) {
                    var vi = d2c(array[indices[i]]);
                    if(vi !== BADNUM) total += vi;
                }
                return c2d(total);
            };

        case 'avg':
            // Generally meaningless for category data but it still does something.
            return function(array, indices) {
                var total = 0;
                var cnt = 0;
                for(var i = 0; i < indices.length; i++) {
                    var vi = d2c(array[indices[i]]);
                    if(vi !== BADNUM) {
                        total += vi;
                        cnt++;
                    }
                }
                return cnt ? c2d(total / cnt) : BADNUM;
            };

        case 'min':
            return function(array, indices) {
                var out = Infinity;
                for(var i = 0; i < indices.length; i++) {
                    var vi = d2c(array[indices[i]]);
                    if(vi !== BADNUM) out = Math.min(out, vi);
                }
                return (out === Infinity) ? BADNUM : c2d(out);
            };

        case 'max':
            return function(array, indices) {
                var out = -Infinity;
                for(var i = 0; i < indices.length; i++) {
                    var vi = d2c(array[indices[i]]);
                    if(vi !== BADNUM) out = Math.max(out, vi);
                }
                return (out === -Infinity) ? BADNUM : c2d(out);
            };

        case 'range':
            return function(array, indices) {
                var min = Infinity;
                var max = -Infinity;
                for(var i = 0; i < indices.length; i++) {
                    var vi = d2c(array[indices[i]]);
                    if(vi !== BADNUM) {
                        min = Math.min(min, vi);
                        max = Math.max(max, vi);
                    }
                }
                return (max === -Infinity || min === Infinity) ? BADNUM : c2d(max - min);
            };

        case 'change':
            return function(array, indices) {
                var first = d2c(array[indices[0]]);
                var last = d2c(array[indices[indices.length - 1]]);
                return (first === BADNUM || last === BADNUM) ? BADNUM : c2d(last - first);
            };

        case 'median':
            return function(array, indices) {
                var sortCalc = [];
                for(var i = 0; i < indices.length; i++) {
                    var vi = d2c(array[indices[i]]);
                    if(vi !== BADNUM) sortCalc.push(vi);
                }
                if(!sortCalc.length) return BADNUM;
                sortCalc.sort();
                var mid = (sortCalc.length - 1) / 2;
                return c2d((sortCalc[Math.floor(mid)] + sortCalc[Math.ceil(mid)]) / 2);
            };

        case 'mode':
            return function(array, indices) {
                var counts = {};
                var maxCnt = 0;
                var out = BADNUM;
                for(var i = 0; i < indices.length; i++) {
                    var vi = d2c(array[indices[i]]);
                    if(vi !== BADNUM) {
                        var counti = counts[vi] = (counts[vi] || 0) + 1;
                        if(counti > maxCnt) {
                            maxCnt = counti;
                            out = vi;
                        }
                    }
                }
                return maxCnt ? c2d(out) : BADNUM;
            };

        case 'rms':
            return function(array, indices) {
                var total = 0;
                var cnt = 0;
                for(var i = 0; i < indices.length; i++) {
                    var vi = d2c(array[indices[i]]);
                    if(vi !== BADNUM) {
                        total += vi * vi;
                        cnt++;
                    }
                }
                return cnt ? c2d(Math.sqrt(total / cnt)) : BADNUM;
            };

        case 'stddev':
            return function(array, indices) {
                // balance numerical stability with performance:
                // so that we call d2c once per element but don't need to
                // store them, reference all to the first element
                var total = 0;
                var total2 = 0;
                var cnt = 1;
                var v0 = BADNUM;
                var i;
                for(i = 0; i < indices.length && v0 === BADNUM; i++) {
                    v0 = d2c(array[indices[i]]);
                }
                if(v0 === BADNUM) return BADNUM;

                for(; i < indices.length; i++) {
                    var vi = d2c(array[indices[i]]);
                    if(vi !== BADNUM) {
                        var dv = vi - v0;
                        total += dv;
                        total2 += dv * dv;
                        cnt++;
                    }
                }

                // This is population std dev, if we want sample std dev
                // we would need (...) / (cnt - 1)
                // Also note there's no c2d here - that means for dates the result
                // is a number of milliseconds, and for categories it's a number
                // of category differences, which is not generically meaningful but
                // as in other cases we don't forbid it.
                var norm = (opts.funcmode === 'sample') ? (cnt - 1) : cnt;
                // this is debatable: should a count of 1 return sample stddev of
                // 0 or undefined?
                if(!norm) return 0;
                return Math.sqrt((total2 - (total * total / cnt)) / norm);
            };
    }
}

function count(array, indices) {
    return indices.length;
}

function first(array, indices) {
    return array[indices[0]];
}

function last(array, indices) {
    return array[indices[indices.length - 1]];
}

},{"../constants/numerical":674,"../lib":697,"../plot_api/plot_schema":734,"../plots/cartesian/axes":745,"./helpers":1163}],1161:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../lib');
var Registry = _dereq_('../registry');
var Axes = _dereq_('../plots/cartesian/axes');
var pointsAccessorFunction = _dereq_('./helpers').pointsAccessorFunction;

var filterOps = _dereq_('../constants/filter_ops');
var COMPARISON_OPS = filterOps.COMPARISON_OPS;
var INTERVAL_OPS = filterOps.INTERVAL_OPS;
var SET_OPS = filterOps.SET_OPS;

exports.moduleType = 'transform';

exports.name = 'filter';

exports.attributes = {
    enabled: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'calc',
        
    },
    target: {
        valType: 'string',
        strict: true,
        noBlank: true,
        arrayOk: true,
        dflt: 'x',
        
        editType: 'calc',
        
    },
    operation: {
        valType: 'enumerated',
        values: []
            .concat(COMPARISON_OPS)
            .concat(INTERVAL_OPS)
            .concat(SET_OPS),
        dflt: '=',
        
        editType: 'calc',
        
    },
    value: {
        valType: 'any',
        dflt: 0,
        
        editType: 'calc',
        
    },
    preservegaps: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'calc',
        
    },
    editType: 'calc'
};

exports.supplyDefaults = function(transformIn) {
    var transformOut = {};

    function coerce(attr, dflt) {
        return Lib.coerce(transformIn, transformOut, exports.attributes, attr, dflt);
    }

    var enabled = coerce('enabled');

    if(enabled) {
        coerce('preservegaps');
        coerce('operation');
        coerce('value');
        coerce('target');

        var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleDefaults');
        handleCalendarDefaults(transformIn, transformOut, 'valuecalendar', null);
        handleCalendarDefaults(transformIn, transformOut, 'targetcalendar', null);
    }

    return transformOut;
};

exports.calcTransform = function(gd, trace, opts) {
    if(!opts.enabled) return;

    var targetArray = Lib.getTargetArray(trace, opts);
    if(!targetArray) return;

    var target = opts.target;

    var len = targetArray.length;
    if(trace._length) len = Math.min(len, trace._length);

    var targetCalendar = opts.targetcalendar;
    var arrayAttrs = trace._arrayAttrs;
    var preservegaps = opts.preservegaps;

    // even if you provide targetcalendar, if target is a string and there
    // is a calendar attribute matching target it will get used instead.
    if(typeof target === 'string') {
        var attrTargetCalendar = Lib.nestedProperty(trace, target + 'calendar').get();
        if(attrTargetCalendar) targetCalendar = attrTargetCalendar;
    }

    var d2c = Axes.getDataToCoordFunc(gd, trace, target, targetArray);
    var filterFunc = getFilterFunc(opts, d2c, targetCalendar);
    var originalArrays = {};
    var indexToPoints = {};
    var index = 0;

    function forAllAttrs(fn, index) {
        for(var j = 0; j < arrayAttrs.length; j++) {
            var np = Lib.nestedProperty(trace, arrayAttrs[j]);
            fn(np, index);
        }
    }

    var initFn;
    var fillFn;
    if(preservegaps) {
        initFn = function(np) {
            originalArrays[np.astr] = Lib.extendDeep([], np.get());
            np.set(new Array(len));
        };
        fillFn = function(np, index) {
            var val = originalArrays[np.astr][index];
            np.get()[index] = val;
        };
    } else {
        initFn = function(np) {
            originalArrays[np.astr] = Lib.extendDeep([], np.get());
            np.set([]);
        };
        fillFn = function(np, index) {
            var val = originalArrays[np.astr][index];
            np.get().push(val);
        };
    }

    // copy all original array attribute values, and clear arrays in trace
    forAllAttrs(initFn);

    var originalPointsAccessor = pointsAccessorFunction(trace.transforms, opts);

    // loop through filter array, fill trace arrays if passed
    for(var i = 0; i < len; i++) {
        var passed = filterFunc(targetArray[i]);
        if(passed) {
            forAllAttrs(fillFn, i);
            indexToPoints[index++] = originalPointsAccessor(i);
        }
        else if(preservegaps) index++;
    }

    opts._indexToPoints = indexToPoints;
    trace._length = index;
};

function getFilterFunc(opts, d2c, targetCalendar) {
    var operation = opts.operation;
    var value = opts.value;
    var hasArrayValue = Array.isArray(value);

    function isOperationIn(array) {
        return array.indexOf(operation) !== -1;
    }

    var d2cValue = function(v) { return d2c(v, 0, opts.valuecalendar); };
    var d2cTarget = function(v) { return d2c(v, 0, targetCalendar); };

    var coercedValue;

    if(isOperationIn(COMPARISON_OPS)) {
        coercedValue = hasArrayValue ? d2cValue(value[0]) : d2cValue(value);
    }
    else if(isOperationIn(INTERVAL_OPS)) {
        coercedValue = hasArrayValue ?
            [d2cValue(value[0]), d2cValue(value[1])] :
            [d2cValue(value), d2cValue(value)];
    }
    else if(isOperationIn(SET_OPS)) {
        coercedValue = hasArrayValue ? value.map(d2cValue) : [d2cValue(value)];
    }

    switch(operation) {

        case '=':
            return function(v) { return d2cTarget(v) === coercedValue; };

        case '!=':
            return function(v) { return d2cTarget(v) !== coercedValue; };

        case '<':
            return function(v) { return d2cTarget(v) < coercedValue; };

        case '<=':
            return function(v) { return d2cTarget(v) <= coercedValue; };

        case '>':
            return function(v) { return d2cTarget(v) > coercedValue; };

        case '>=':
            return function(v) { return d2cTarget(v) >= coercedValue; };

        case '[]':
            return function(v) {
                var cv = d2cTarget(v);
                return cv >= coercedValue[0] && cv <= coercedValue[1];
            };

        case '()':
            return function(v) {
                var cv = d2cTarget(v);
                return cv > coercedValue[0] && cv < coercedValue[1];
            };

        case '[)':
            return function(v) {
                var cv = d2cTarget(v);
                return cv >= coercedValue[0] && cv < coercedValue[1];
            };

        case '(]':
            return function(v) {
                var cv = d2cTarget(v);
                return cv > coercedValue[0] && cv <= coercedValue[1];
            };

        case '][':
            return function(v) {
                var cv = d2cTarget(v);
                return cv <= coercedValue[0] || cv >= coercedValue[1];
            };

        case ')(':
            return function(v) {
                var cv = d2cTarget(v);
                return cv < coercedValue[0] || cv > coercedValue[1];
            };

        case '](':
            return function(v) {
                var cv = d2cTarget(v);
                return cv <= coercedValue[0] || cv > coercedValue[1];
            };

        case ')[':
            return function(v) {
                var cv = d2cTarget(v);
                return cv < coercedValue[0] || cv >= coercedValue[1];
            };

        case '{}':
            return function(v) {
                return coercedValue.indexOf(d2cTarget(v)) !== -1;
            };

        case '}{':
            return function(v) {
                return coercedValue.indexOf(d2cTarget(v)) === -1;
            };
    }
}

},{"../constants/filter_ops":670,"../lib":697,"../plots/cartesian/axes":745,"../registry":826,"./helpers":1163}],1162:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../lib');
var PlotSchema = _dereq_('../plot_api/plot_schema');
var Plots = _dereq_('../plots/plots');
var pointsAccessorFunction = _dereq_('./helpers').pointsAccessorFunction;

exports.moduleType = 'transform';

exports.name = 'groupby';

exports.attributes = {
    enabled: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'calc',
        
    },
    groups: {
        valType: 'data_array',
        dflt: [],
        
        editType: 'calc',
        
    },
    nameformat: {
        valType: 'string',
        
        editType: 'calc',
        
    },
    styles: {
        _isLinkedToArray: 'style',
        target: {
            valType: 'string',
            
            editType: 'calc',
            
        },
        value: {
            valType: 'any',
            
            dflt: {},
            editType: 'calc',
            
            _compareAsJSON: true
        },
        editType: 'calc'
    },
    editType: 'calc'
};

/**
 * Supply transform attributes defaults
 *
 * @param {object} transformIn
 *  object linked to trace.transforms[i] with 'type' set to exports.name
 * @param {object} traceOut
 *  the _fullData trace this transform applies to
 * @param {object} layout
 *  the plot's (not-so-full) layout
 * @param {object} traceIn
 *  the input data trace this transform applies to
 *
 * @return {object} transformOut
 *  copy of transformIn that contains attribute defaults
 */
exports.supplyDefaults = function(transformIn, traceOut, layout) {
    var i;
    var transformOut = {};

    function coerce(attr, dflt) {
        return Lib.coerce(transformIn, transformOut, exports.attributes, attr, dflt);
    }

    var enabled = coerce('enabled');

    if(!enabled) return transformOut;

    coerce('groups');
    coerce('nameformat', layout._dataLength > 1 ? '%{group} (%{trace})' : '%{group}');

    var styleIn = transformIn.styles;
    var styleOut = transformOut.styles = [];

    if(styleIn) {
        for(i = 0; i < styleIn.length; i++) {
            var thisStyle = styleOut[i] = {};
            Lib.coerce(styleIn[i], styleOut[i], exports.attributes.styles, 'target');
            var value = Lib.coerce(styleIn[i], styleOut[i], exports.attributes.styles, 'value');

            // so that you can edit value in place and have Plotly.react notice it, or
            // rebuild it every time and have Plotly.react NOT think it changed:
            // use _compareAsJSON to say we should diff the _JSON_value
            if(Lib.isPlainObject(value)) thisStyle.value = Lib.extendDeep({}, value);
            else if(value) delete thisStyle.value;
        }
    }

    return transformOut;
};


/**
 * Apply transform !!!
 *
 * @param {array} data
 *  array of transformed traces (is [fullTrace] upon first transform)
 *
 * @param {object} state
 *  state object which includes:
 *      - transform {object} full transform attributes
 *      - fullTrace {object} full trace object which is being transformed
 *      - fullData {array} full pre-transform(s) data array
 *      - layout {object} the plot's (not-so-full) layout
 *
 * @return {object} newData
 *  array of transformed traces
 */
exports.transform = function(data, state) {
    var newTraces, i, j;
    var newData = [];

    for(i = 0; i < data.length; i++) {
        newTraces = transformOne(data[i], state);

        for(j = 0; j < newTraces.length; j++) {
            newData.push(newTraces[j]);
        }
    }

    return newData;
};

function transformOne(trace, state) {
    var i, j, k, attr, srcArray, groupName, newTrace, transforms, arrayLookup;
    var groupNameObj;

    var opts = state.transform;
    var transformIndex = state.transformIndex;
    var groups = trace.transforms[transformIndex].groups;
    var originalPointsAccessor = pointsAccessorFunction(trace.transforms, opts);

    if(!(Array.isArray(groups)) || groups.length === 0) {
        return [trace];
    }

    var groupNames = Lib.filterUnique(groups);
    var newData = new Array(groupNames.length);
    var len = groups.length;

    var arrayAttrs = PlotSchema.findArrayAttributes(trace);

    var styles = opts.styles || [];
    var styleLookup = {};
    for(i = 0; i < styles.length; i++) {
        styleLookup[styles[i].target] = styles[i].value;
    }

    if(opts.styles) {
        groupNameObj = Lib.keyedContainer(opts, 'styles', 'target', 'value.name');
    }

    // An index to map group name --> expanded trace index
    var indexLookup = {};
    var indexCnts = {};

    for(i = 0; i < groupNames.length; i++) {
        groupName = groupNames[i];
        indexLookup[groupName] = i;
        indexCnts[groupName] = 0;

        // Start with a deep extend that just copies array references.
        newTrace = newData[i] = Lib.extendDeepNoArrays({}, trace);
        newTrace._group = groupName;
        newTrace.transforms[transformIndex]._indexToPoints = {};

        var suppliedName = null;
        if(groupNameObj) {
            suppliedName = groupNameObj.get(groupName);
        }

        if(suppliedName || suppliedName === '') {
            newTrace.name = suppliedName;
        } else {
            newTrace.name = Lib.templateString(opts.nameformat, {
                trace: trace.name,
                group: groupName
            });
        }

        // In order for groups to apply correctly to other transform data (e.g.
        // a filter transform), we have to break the connection and clone the
        // transforms so that each group writes grouped values into a different
        // destination. This function does not break the array reference
        // connection between the split transforms it creates. That's handled in
        // initialize, which creates a new empty array for each arrayAttr.
        transforms = newTrace.transforms;
        newTrace.transforms = [];
        for(j = 0; j < transforms.length; j++) {
            newTrace.transforms[j] = Lib.extendDeepNoArrays({}, transforms[j]);
        }

        // Initialize empty arrays for the arrayAttrs, to be split in the next step
        for(j = 0; j < arrayAttrs.length; j++) {
            Lib.nestedProperty(newTrace, arrayAttrs[j]).set([]);
        }
    }

    // For each array attribute including those nested inside this and other
    // transforms (small note that we technically only need to do this for
    // transforms that have not yet been applied):
    for(k = 0; k < arrayAttrs.length; k++) {
        attr = arrayAttrs[k];

        // Cache all the arrays to which we'll push:
        for(j = 0, arrayLookup = []; j < groupNames.length; j++) {
            arrayLookup[j] = Lib.nestedProperty(newData[j], attr).get();
        }

        // Get the input data:
        srcArray = Lib.nestedProperty(trace, attr).get();

        // Send each data point to the appropriate expanded trace:
        for(j = 0; j < len; j++) {
            // Map group data --> trace index --> array and push data onto it
            arrayLookup[indexLookup[groups[j]]].push(srcArray[j]);
        }
    }

    for(j = 0; j < len; j++) {
        newTrace = newData[indexLookup[groups[j]]];

        var indexToPoints = newTrace.transforms[transformIndex]._indexToPoints;
        indexToPoints[indexCnts[groups[j]]] = originalPointsAccessor(j);
        indexCnts[groups[j]]++;
    }

    for(i = 0; i < groupNames.length; i++) {
        groupName = groupNames[i];
        newTrace = newData[i];

        Plots.clearExpandedTraceDefaultColors(newTrace);

        // there's no need to coerce styleLookup[groupName] here
        // as another round of supplyDefaults is done on the transformed traces
        newTrace = Lib.extendDeepNoArrays(newTrace, styleLookup[groupName] || {});
    }

    return newData;
}

},{"../lib":697,"../plot_api/plot_schema":734,"../plots/plots":807,"./helpers":1163}],1163:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

exports.pointsAccessorFunction = function(transforms, opts) {
    var tr;
    var prevIndexToPoints;
    for(var i = 0; i < transforms.length; i++) {
        tr = transforms[i];
        if(tr === opts) break;
        if(!tr._indexToPoints || tr.enabled === false) continue;
        prevIndexToPoints = tr._indexToPoints;
    }
    var originalPointsAccessor = prevIndexToPoints ?
        function(i) {return prevIndexToPoints[i];} :
        function(i) {return [i];};
    return originalPointsAccessor;
};

},{}],1164:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../lib');
var Axes = _dereq_('../plots/cartesian/axes');
var pointsAccessorFunction = _dereq_('./helpers').pointsAccessorFunction;

exports.moduleType = 'transform';

exports.name = 'sort';

exports.attributes = {
    enabled: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'calc',
        
    },
    target: {
        valType: 'string',
        strict: true,
        noBlank: true,
        arrayOk: true,
        dflt: 'x',
        
        editType: 'calc',
        
    },
    order: {
        valType: 'enumerated',
        values: ['ascending', 'descending'],
        dflt: 'ascending',
        
        editType: 'calc',
        
    },
    editType: 'calc'
};

exports.supplyDefaults = function(transformIn) {
    var transformOut = {};

    function coerce(attr, dflt) {
        return Lib.coerce(transformIn, transformOut, exports.attributes, attr, dflt);
    }

    var enabled = coerce('enabled');

    if(enabled) {
        coerce('target');
        coerce('order');
    }

    return transformOut;
};

exports.calcTransform = function(gd, trace, opts) {
    if(!opts.enabled) return;

    var targetArray = Lib.getTargetArray(trace, opts);
    if(!targetArray) return;

    var target = opts.target;

    var len = targetArray.length;
    if(trace._length) len = Math.min(len, trace._length);

    var arrayAttrs = trace._arrayAttrs;
    var d2c = Axes.getDataToCoordFunc(gd, trace, target, targetArray);
    var indices = getIndices(opts, targetArray, d2c, len);
    var originalPointsAccessor = pointsAccessorFunction(trace.transforms, opts);
    var indexToPoints = {};
    var i, j;

    for(i = 0; i < arrayAttrs.length; i++) {
        var np = Lib.nestedProperty(trace, arrayAttrs[i]);
        var arrayOld = np.get();
        var arrayNew = new Array(len);

        for(j = 0; j < len; j++) {
            arrayNew[j] = arrayOld[indices[j]];
        }

        np.set(arrayNew);
    }

    for(j = 0; j < len; j++) {
        indexToPoints[j] = originalPointsAccessor(indices[j]);
    }

    opts._indexToPoints = indexToPoints;
    trace._length = len;
};

function getIndices(opts, targetArray, d2c, len) {
    var sortedArray = new Array(len);
    var indices = new Array(len);
    var i;

    for(i = 0; i < len; i++) {
        sortedArray[i] = {v: targetArray[i], i: i};
    }

    sortedArray.sort(getSortFunc(opts, d2c));

    for(i = 0; i < len; i++) {
        indices[i] = sortedArray[i].i;
    }

    return indices;
}

function getSortFunc(opts, d2c) {
    switch(opts.order) {
        case 'ascending':
            return function(a, b) { return d2c(a.v) - d2c(b.v); };
        case 'descending':
            return function(a, b) { return d2c(b.v) - d2c(a.v); };
    }
}

},{"../lib":697,"../plots/cartesian/axes":745,"./helpers":1163}]},{},[22])(22)
});

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "+5Rf":
/*!***************************************************!*\
  !*** ./node_modules/mdi-react/ArrowExpandIcon.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var ArrowExpandIcon = function ArrowExpandIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M10,21V19H6.41L10.91,14.5L9.5,13.09L5,17.59V14H3V21H10M14.5,10.91L19,6.41V10H21V3H14V5H17.59L13.09,9.5L14.5,10.91Z' })
  );
};

module.exports = ArrowExpandIcon;


/***/ }),

/***/ "+6XX":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_listCacheHas.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var assocIndexOf = __webpack_require__(/*! ./_assocIndexOf */ "y1pI");

/**
 * 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;
}

module.exports = listCacheHas;


/***/ }),

/***/ "+7xj":
/*!*********************************************!*\
  !*** ./node_modules/mdi-react/HeartIcon.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var HeartIcon = function HeartIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M12,21.35L10.55,20.03C5.4,15.36 2,12.27 2,8.5C2,5.41 4.42,3 7.5,3C9.24,3 10.91,3.81 12,5.08C13.09,3.81 14.76,3 16.5,3C19.58,3 22,5.41 22,8.5C22,12.27 18.6,15.36 13.45,20.03L12,21.35Z' })
  );
};

module.exports = HeartIcon;


/***/ }),

/***/ "+8Ar":
/*!*****************************************************!*\
  !*** ./node_modules/fbjs/lib/hyphenateStyleName.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks
 */



var hyphenate = __webpack_require__(/*! ./hyphenate */ "+aGp");

var msPattern = /^ms-/;

/**
 * Hyphenates a camelcased CSS property name, for example:
 *
 *   > hyphenateStyleName('backgroundColor')
 *   < "background-color"
 *   > hyphenateStyleName('MozTransition')
 *   < "-moz-transition"
 *   > hyphenateStyleName('msTransition')
 *   < "-ms-transition"
 *
 * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
 * is converted to `-ms-`.
 *
 * @param {string} string
 * @return {string}
 */
function hyphenateStyleName(string) {
  return hyphenate(string).replace(msPattern, '-ms-');
}

module.exports = hyphenateStyleName;

/***/ }),

/***/ "+9U2":
/*!**************************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/container.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _declaration = __webpack_require__(/*! ./declaration */ "dUwI");

var _declaration2 = _interopRequireDefault(_declaration);

var _comment = __webpack_require__(/*! ./comment */ "aOxJ");

var _comment2 = _interopRequireDefault(_comment);

var _node = __webpack_require__(/*! ./node */ "wWcZ");

var _node2 = _interopRequireDefault(_node);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function cleanSource(nodes) {
    return nodes.map(function (i) {
        if (i.nodes) i.nodes = cleanSource(i.nodes);
        delete i.source;
        return i;
    });
}

/**
 * The {@link Root}, {@link AtRule}, and {@link Rule} container nodes
 * inherit some common methods to help work with their children.
 *
 * Note that all containers can store any content. If you write a rule inside
 * a rule, PostCSS will parse it.
 *
 * @extends Node
 * @abstract
 */

var Container = function (_Node) {
    _inherits(Container, _Node);

    function Container() {
        _classCallCheck(this, Container);

        return _possibleConstructorReturn(this, _Node.apply(this, arguments));
    }

    Container.prototype.push = function push(child) {
        child.parent = this;
        this.nodes.push(child);
        return this;
    };

    /**
     * Iterates through the container’s immediate children,
     * calling `callback` for each child.
     *
     * Returning `false` in the callback will break iteration.
     *
     * This method only iterates through the container’s immediate children.
     * If you need to recursively iterate through all the container’s descendant
     * nodes, use {@link Container#walk}.
     *
     * Unlike the for `{}`-cycle or `Array#forEach` this iterator is safe
     * if you are mutating the array of child nodes during iteration.
     * PostCSS will adjust the current index to match the mutations.
     *
     * @param {childIterator} callback - iterator receives each node and index
     *
     * @return {false|undefined} returns `false` if iteration was broke
     *
     * @example
     * const root = postcss.parse('a { color: black; z-index: 1 }');
     * const rule = root.first;
     *
     * for ( let decl of rule.nodes ) {
     *     decl.cloneBefore({ prop: '-webkit-' + decl.prop });
     *     // Cycle will be infinite, because cloneBefore moves the current node
     *     // to the next index
     * }
     *
     * rule.each(decl => {
     *     decl.cloneBefore({ prop: '-webkit-' + decl.prop });
     *     // Will be executed only for color and z-index
     * });
     */


    Container.prototype.each = function each(callback) {
        if (!this.lastEach) this.lastEach = 0;
        if (!this.indexes) this.indexes = {};

        this.lastEach += 1;
        var id = this.lastEach;
        this.indexes[id] = 0;

        if (!this.nodes) return undefined;

        var index = void 0,
            result = void 0;
        while (this.indexes[id] < this.nodes.length) {
            index = this.indexes[id];
            result = callback(this.nodes[index], index);
            if (result === false) break;

            this.indexes[id] += 1;
        }

        delete this.indexes[id];

        return result;
    };

    /**
     * Traverses the container’s descendant nodes, calling callback
     * for each node.
     *
     * Like container.each(), this method is safe to use
     * if you are mutating arrays during iteration.
     *
     * If you only need to iterate through the container’s immediate children,
     * use {@link Container#each}.
     *
     * @param {childIterator} callback - iterator receives each node and index
     *
     * @return {false|undefined} returns `false` if iteration was broke
     *
     * @example
     * root.walk(node => {
     *   // Traverses all descendant nodes.
     * });
     */


    Container.prototype.walk = function walk(callback) {
        return this.each(function (child, i) {
            var result = callback(child, i);
            if (result !== false && child.walk) {
                result = child.walk(callback);
            }
            return result;
        });
    };

    /**
     * Traverses the container’s descendant nodes, calling callback
     * for each declaration node.
     *
     * If you pass a filter, iteration will only happen over declarations
     * with matching properties.
     *
     * Like {@link Container#each}, this method is safe
     * to use if you are mutating arrays during iteration.
     *
     * @param {string|RegExp} [prop]   - string or regular expression
     *                                   to filter declarations by property name
     * @param {childIterator} callback - iterator receives each node and index
     *
     * @return {false|undefined} returns `false` if iteration was broke
     *
     * @example
     * root.walkDecls(decl => {
     *   checkPropertySupport(decl.prop);
     * });
     *
     * root.walkDecls('border-radius', decl => {
     *   decl.remove();
     * });
     *
     * root.walkDecls(/^background/, decl => {
     *   decl.value = takeFirstColorFromGradient(decl.value);
     * });
     */


    Container.prototype.walkDecls = function walkDecls(prop, callback) {
        if (!callback) {
            callback = prop;
            return this.walk(function (child, i) {
                if (child.type === 'decl') {
                    return callback(child, i);
                }
            });
        } else if (prop instanceof RegExp) {
            return this.walk(function (child, i) {
                if (child.type === 'decl' && prop.test(child.prop)) {
                    return callback(child, i);
                }
            });
        } else {
            return this.walk(function (child, i) {
                if (child.type === 'decl' && child.prop === prop) {
                    return callback(child, i);
                }
            });
        }
    };

    /**
     * Traverses the container’s descendant nodes, calling callback
     * for each rule node.
     *
     * If you pass a filter, iteration will only happen over rules
     * with matching selectors.
     *
     * Like {@link Container#each}, this method is safe
     * to use if you are mutating arrays during iteration.
     *
     * @param {string|RegExp} [selector] - string or regular expression
     *                                     to filter rules by selector
     * @param {childIterator} callback   - iterator receives each node and index
     *
     * @return {false|undefined} returns `false` if iteration was broke
     *
     * @example
     * const selectors = [];
     * root.walkRules(rule => {
     *   selectors.push(rule.selector);
     * });
     * console.log(`Your CSS uses ${selectors.length} selectors`);
     */


    Container.prototype.walkRules = function walkRules(selector, callback) {
        if (!callback) {
            callback = selector;

            return this.walk(function (child, i) {
                if (child.type === 'rule') {
                    return callback(child, i);
                }
            });
        } else if (selector instanceof RegExp) {
            return this.walk(function (child, i) {
                if (child.type === 'rule' && selector.test(child.selector)) {
                    return callback(child, i);
                }
            });
        } else {
            return this.walk(function (child, i) {
                if (child.type === 'rule' && child.selector === selector) {
                    return callback(child, i);
                }
            });
        }
    };

    /**
     * Traverses the container’s descendant nodes, calling callback
     * for each at-rule node.
     *
     * If you pass a filter, iteration will only happen over at-rules
     * that have matching names.
     *
     * Like {@link Container#each}, this method is safe
     * to use if you are mutating arrays during iteration.
     *
     * @param {string|RegExp} [name]   - string or regular expression
     *                                   to filter at-rules by name
     * @param {childIterator} callback - iterator receives each node and index
     *
     * @return {false|undefined} returns `false` if iteration was broke
     *
     * @example
     * root.walkAtRules(rule => {
     *   if ( isOld(rule.name) ) rule.remove();
     * });
     *
     * let first = false;
     * root.walkAtRules('charset', rule => {
     *   if ( !first ) {
     *     first = true;
     *   } else {
     *     rule.remove();
     *   }
     * });
     */


    Container.prototype.walkAtRules = function walkAtRules(name, callback) {
        if (!callback) {
            callback = name;
            return this.walk(function (child, i) {
                if (child.type === 'atrule') {
                    return callback(child, i);
                }
            });
        } else if (name instanceof RegExp) {
            return this.walk(function (child, i) {
                if (child.type === 'atrule' && name.test(child.name)) {
                    return callback(child, i);
                }
            });
        } else {
            return this.walk(function (child, i) {
                if (child.type === 'atrule' && child.name === name) {
                    return callback(child, i);
                }
            });
        }
    };

    /**
     * Traverses the container’s descendant nodes, calling callback
     * for each comment node.
     *
     * Like {@link Container#each}, this method is safe
     * to use if you are mutating arrays during iteration.
     *
     * @param {childIterator} callback - iterator receives each node and index
     *
     * @return {false|undefined} returns `false` if iteration was broke
     *
     * @example
     * root.walkComments(comment => {
     *   comment.remove();
     * });
     */


    Container.prototype.walkComments = function walkComments(callback) {
        return this.walk(function (child, i) {
            if (child.type === 'comment') {
                return callback(child, i);
            }
        });
    };

    /**
     * Inserts new nodes to the end of the container.
     *
     * @param {...(Node|object|string|Node[])} children - new nodes
     *
     * @return {Node} this node for methods chain
     *
     * @example
     * const decl1 = postcss.decl({ prop: 'color', value: 'black' });
     * const decl2 = postcss.decl({ prop: 'background-color', value: 'white' });
     * rule.append(decl1, decl2);
     *
     * root.append({ name: 'charset', params: '"UTF-8"' });  // at-rule
     * root.append({ selector: 'a' });                       // rule
     * rule.append({ prop: 'color', value: 'black' });       // declaration
     * rule.append({ text: 'Comment' })                      // comment
     *
     * root.append('a {}');
     * root.first.append('color: black; z-index: 1');
     */


    Container.prototype.append = function append() {
        for (var _len = arguments.length, children = Array(_len), _key = 0; _key < _len; _key++) {
            children[_key] = arguments[_key];
        }

        for (var _iterator = children, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
            var _ref;

            if (_isArray) {
                if (_i >= _iterator.length) break;
                _ref = _iterator[_i++];
            } else {
                _i = _iterator.next();
                if (_i.done) break;
                _ref = _i.value;
            }

            var child = _ref;

            var nodes = this.normalize(child, this.last);
            for (var _iterator2 = nodes, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
                var _ref2;

                if (_isArray2) {
                    if (_i2 >= _iterator2.length) break;
                    _ref2 = _iterator2[_i2++];
                } else {
                    _i2 = _iterator2.next();
                    if (_i2.done) break;
                    _ref2 = _i2.value;
                }

                var node = _ref2;
                this.nodes.push(node);
            }
        }
        return this;
    };

    /**
     * Inserts new nodes to the start of the container.
     *
     * @param {...(Node|object|string|Node[])} children - new nodes
     *
     * @return {Node} this node for methods chain
     *
     * @example
     * const decl1 = postcss.decl({ prop: 'color', value: 'black' });
     * const decl2 = postcss.decl({ prop: 'background-color', value: 'white' });
     * rule.prepend(decl1, decl2);
     *
     * root.append({ name: 'charset', params: '"UTF-8"' });  // at-rule
     * root.append({ selector: 'a' });                       // rule
     * rule.append({ prop: 'color', value: 'black' });       // declaration
     * rule.append({ text: 'Comment' })                      // comment
     *
     * root.append('a {}');
     * root.first.append('color: black; z-index: 1');
     */


    Container.prototype.prepend = function prepend() {
        for (var _len2 = arguments.length, children = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
            children[_key2] = arguments[_key2];
        }

        children = children.reverse();
        for (var _iterator3 = children, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
            var _ref3;

            if (_isArray3) {
                if (_i3 >= _iterator3.length) break;
                _ref3 = _iterator3[_i3++];
            } else {
                _i3 = _iterator3.next();
                if (_i3.done) break;
                _ref3 = _i3.value;
            }

            var child = _ref3;

            var nodes = this.normalize(child, this.first, 'prepend').reverse();
            for (var _iterator4 = nodes, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) {
                var _ref4;

                if (_isArray4) {
                    if (_i4 >= _iterator4.length) break;
                    _ref4 = _iterator4[_i4++];
                } else {
                    _i4 = _iterator4.next();
                    if (_i4.done) break;
                    _ref4 = _i4.value;
                }

                var node = _ref4;
                this.nodes.unshift(node);
            }for (var id in this.indexes) {
                this.indexes[id] = this.indexes[id] + nodes.length;
            }
        }
        return this;
    };

    Container.prototype.cleanRaws = function cleanRaws(keepBetween) {
        _Node.prototype.cleanRaws.call(this, keepBetween);
        if (this.nodes) {
            for (var _iterator5 = this.nodes, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) {
                var _ref5;

                if (_isArray5) {
                    if (_i5 >= _iterator5.length) break;
                    _ref5 = _iterator5[_i5++];
                } else {
                    _i5 = _iterator5.next();
                    if (_i5.done) break;
                    _ref5 = _i5.value;
                }

                var node = _ref5;
                node.cleanRaws(keepBetween);
            }
        }
    };

    /**
     * Insert new node before old node within the container.
     *
     * @param {Node|number} exist             - child or child’s index.
     * @param {Node|object|string|Node[]} add - new node
     *
     * @return {Node} this node for methods chain
     *
     * @example
     * rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }));
     */


    Container.prototype.insertBefore = function insertBefore(exist, add) {
        exist = this.index(exist);

        var type = exist === 0 ? 'prepend' : false;
        var nodes = this.normalize(add, this.nodes[exist], type).reverse();
        for (var _iterator6 = nodes, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : _iterator6[Symbol.iterator]();;) {
            var _ref6;

            if (_isArray6) {
                if (_i6 >= _iterator6.length) break;
                _ref6 = _iterator6[_i6++];
            } else {
                _i6 = _iterator6.next();
                if (_i6.done) break;
                _ref6 = _i6.value;
            }

            var node = _ref6;
            this.nodes.splice(exist, 0, node);
        }var index = void 0;
        for (var id in this.indexes) {
            index = this.indexes[id];
            if (exist <= index) {
                this.indexes[id] = index + nodes.length;
            }
        }

        return this;
    };

    /**
     * Insert new node after old node within the container.
     *
     * @param {Node|number} exist             - child or child’s index
     * @param {Node|object|string|Node[]} add - new node
     *
     * @return {Node} this node for methods chain
     */


    Container.prototype.insertAfter = function insertAfter(exist, add) {
        exist = this.index(exist);

        var nodes = this.normalize(add, this.nodes[exist]).reverse();
        for (var _iterator7 = nodes, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : _iterator7[Symbol.iterator]();;) {
            var _ref7;

            if (_isArray7) {
                if (_i7 >= _iterator7.length) break;
                _ref7 = _iterator7[_i7++];
            } else {
                _i7 = _iterator7.next();
                if (_i7.done) break;
                _ref7 = _i7.value;
            }

            var node = _ref7;
            this.nodes.splice(exist + 1, 0, node);
        }var index = void 0;
        for (var id in this.indexes) {
            index = this.indexes[id];
            if (exist < index) {
                this.indexes[id] = index + nodes.length;
            }
        }

        return this;
    };

    /**
     * Removes node from the container and cleans the parent properties
     * from the node and its children.
     *
     * @param {Node|number} child - child or child’s index
     *
     * @return {Node} this node for methods chain
     *
     * @example
     * rule.nodes.length  //=> 5
     * rule.removeChild(decl);
     * rule.nodes.length  //=> 4
     * decl.parent        //=> undefined
     */


    Container.prototype.removeChild = function removeChild(child) {
        child = this.index(child);
        this.nodes[child].parent = undefined;
        this.nodes.splice(child, 1);

        var index = void 0;
        for (var id in this.indexes) {
            index = this.indexes[id];
            if (index >= child) {
                this.indexes[id] = index - 1;
            }
        }

        return this;
    };

    /**
     * Removes all children from the container
     * and cleans their parent properties.
     *
     * @return {Node} this node for methods chain
     *
     * @example
     * rule.removeAll();
     * rule.nodes.length //=> 0
     */


    Container.prototype.removeAll = function removeAll() {
        for (var _iterator8 = this.nodes, _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : _iterator8[Symbol.iterator]();;) {
            var _ref8;

            if (_isArray8) {
                if (_i8 >= _iterator8.length) break;
                _ref8 = _iterator8[_i8++];
            } else {
                _i8 = _iterator8.next();
                if (_i8.done) break;
                _ref8 = _i8.value;
            }

            var node = _ref8;
            node.parent = undefined;
        }this.nodes = [];
        return this;
    };

    /**
     * Passes all declaration values within the container that match pattern
     * through callback, replacing those values with the returned result
     * of callback.
     *
     * This method is useful if you are using a custom unit or function
     * and need to iterate through all values.
     *
     * @param {string|RegExp} pattern      - replace pattern
     * @param {object} opts                - options to speed up the search
     * @param {string|string[]} opts.props - an array of property names
     * @param {string} opts.fast           - string that’s used
     *                                       to narrow down values and speed up
                                             the regexp search
     * @param {function|string} callback   - string to replace pattern
     *                                       or callback that returns a new
     *                                       value.
     *                                       The callback will receive
     *                                       the same arguments as those
     *                                       passed to a function parameter
     *                                       of `String#replace`.
     *
     * @return {Node} this node for methods chain
     *
     * @example
     * root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
     *   return 15 * parseInt(string) + 'px';
     * });
     */


    Container.prototype.replaceValues = function replaceValues(pattern, opts, callback) {
        if (!callback) {
            callback = opts;
            opts = {};
        }

        this.walkDecls(function (decl) {
            if (opts.props && opts.props.indexOf(decl.prop) === -1) return;
            if (opts.fast && decl.value.indexOf(opts.fast) === -1) return;

            decl.value = decl.value.replace(pattern, callback);
        });

        return this;
    };

    /**
     * Returns `true` if callback returns `true`
     * for all of the container’s children.
     *
     * @param {childCondition} condition - iterator returns true or false.
     *
     * @return {boolean} is every child pass condition
     *
     * @example
     * const noPrefixes = rule.every(i => i.prop[0] !== '-');
     */


    Container.prototype.every = function every(condition) {
        return this.nodes.every(condition);
    };

    /**
     * Returns `true` if callback returns `true` for (at least) one
     * of the container’s children.
     *
     * @param {childCondition} condition - iterator returns true or false.
     *
     * @return {boolean} is some child pass condition
     *
     * @example
     * const hasPrefix = rule.some(i => i.prop[0] === '-');
     */


    Container.prototype.some = function some(condition) {
        return this.nodes.some(condition);
    };

    /**
     * Returns a `child`’s index within the {@link Container#nodes} array.
     *
     * @param {Node} child - child of the current container.
     *
     * @return {number} child index
     *
     * @example
     * rule.index( rule.nodes[2] ) //=> 2
     */


    Container.prototype.index = function index(child) {
        if (typeof child === 'number') {
            return child;
        } else {
            return this.nodes.indexOf(child);
        }
    };

    /**
     * The container’s first child.
     *
     * @type {Node}
     *
     * @example
     * rule.first == rules.nodes[0];
     */


    Container.prototype.normalize = function normalize(nodes, sample) {
        var _this2 = this;

        if (typeof nodes === 'string') {
            var parse = __webpack_require__(/*! ./parse */ "ao+V");
            nodes = cleanSource(parse(nodes).nodes);
        } else if (Array.isArray(nodes)) {
            nodes = nodes.slice(0);
            for (var _iterator9 = nodes, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : _iterator9[Symbol.iterator]();;) {
                var _ref9;

                if (_isArray9) {
                    if (_i9 >= _iterator9.length) break;
                    _ref9 = _iterator9[_i9++];
                } else {
                    _i9 = _iterator9.next();
                    if (_i9.done) break;
                    _ref9 = _i9.value;
                }

                var i = _ref9;

                if (i.parent) i.parent.removeChild(i, 'ignore');
            }
        } else if (nodes.type === 'root') {
            nodes = nodes.nodes.slice(0);
            for (var _iterator10 = nodes, _isArray10 = Array.isArray(_iterator10), _i11 = 0, _iterator10 = _isArray10 ? _iterator10 : _iterator10[Symbol.iterator]();;) {
                var _ref10;

                if (_isArray10) {
                    if (_i11 >= _iterator10.length) break;
                    _ref10 = _iterator10[_i11++];
                } else {
                    _i11 = _iterator10.next();
                    if (_i11.done) break;
                    _ref10 = _i11.value;
                }

                var _i10 = _ref10;

                if (_i10.parent) _i10.parent.removeChild(_i10, 'ignore');
            }
        } else if (nodes.type) {
            nodes = [nodes];
        } else if (nodes.prop) {
            if (typeof nodes.value === 'undefined') {
                throw new Error('Value field is missed in node creation');
            } else if (typeof nodes.value !== 'string') {
                nodes.value = String(nodes.value);
            }
            nodes = [new _declaration2.default(nodes)];
        } else if (nodes.selector) {
            var Rule = __webpack_require__(/*! ./rule */ "Cx5C");
            nodes = [new Rule(nodes)];
        } else if (nodes.name) {
            var AtRule = __webpack_require__(/*! ./at-rule */ "6z8e");
            nodes = [new AtRule(nodes)];
        } else if (nodes.text) {
            nodes = [new _comment2.default(nodes)];
        } else {
            throw new Error('Unknown node type in node creation');
        }

        var processed = nodes.map(function (i) {
            if (typeof i.before !== 'function') i = _this2.rebuild(i);

            if (i.parent) i.parent.removeChild(i);
            if (typeof i.raws.before === 'undefined') {
                if (sample && typeof sample.raws.before !== 'undefined') {
                    i.raws.before = sample.raws.before.replace(/[^\s]/g, '');
                }
            }
            i.parent = _this2;
            return i;
        });

        return processed;
    };

    Container.prototype.rebuild = function rebuild(node, parent) {
        var _this3 = this;

        var fix = void 0;
        if (node.type === 'root') {
            var Root = __webpack_require__(/*! ./root */ "sYGr");
            fix = new Root();
        } else if (node.type === 'atrule') {
            var AtRule = __webpack_require__(/*! ./at-rule */ "6z8e");
            fix = new AtRule();
        } else if (node.type === 'rule') {
            var Rule = __webpack_require__(/*! ./rule */ "Cx5C");
            fix = new Rule();
        } else if (node.type === 'decl') {
            fix = new _declaration2.default();
        } else if (node.type === 'comment') {
            fix = new _comment2.default();
        }

        for (var i in node) {
            if (i === 'nodes') {
                fix.nodes = node.nodes.map(function (j) {
                    return _this3.rebuild(j, fix);
                });
            } else if (i === 'parent' && parent) {
                fix.parent = parent;
            } else if (node.hasOwnProperty(i)) {
                fix[i] = node[i];
            }
        }

        return fix;
    };

    /**
     * @memberof Container#
     * @member {Node[]} nodes - an array containing the container’s children
     *
     * @example
     * const root = postcss.parse('a { color: black }');
     * root.nodes.length           //=> 1
     * root.nodes[0].selector      //=> 'a'
     * root.nodes[0].nodes[0].prop //=> 'color'
     */

    _createClass(Container, [{
        key: 'first',
        get: function get() {
            if (!this.nodes) return undefined;
            return this.nodes[0];
        }

        /**
         * The container’s last child.
         *
         * @type {Node}
         *
         * @example
         * rule.last == rule.nodes[rule.nodes.length - 1];
         */

    }, {
        key: 'last',
        get: function get() {
            if (!this.nodes) return undefined;
            return this.nodes[this.nodes.length - 1];
        }
    }]);

    return Container;
}(_node2.default);

exports.default = Container;

/**
 * @callback childCondition
 * @param {Node} node    - container child
 * @param {number} index - child index
 * @param {Node[]} nodes - all container children
 * @return {boolean}
 */

/**
 * @callback childIterator
 * @param {Node} node    - container child
 * @param {number} index - child index
 * @return {false|undefined} returning `false` will break iteration
 */

module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64, 


/***/ }),

/***/ "+9rK":
/*!**********************************************!*\
  !*** ./node_modules/ajv/lib/compile/util.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";



module.exports = {
  copy: copy,
  checkDataType: checkDataType,
  checkDataTypes: checkDataTypes,
  coerceToTypes: coerceToTypes,
  toHash: toHash,
  getProperty: getProperty,
  escapeQuotes: escapeQuotes,
  equal: __webpack_require__(/*! ./equal */ "gQ7D"),
  ucs2length: __webpack_require__(/*! ./ucs2length */ "d17/"),
  varOccurences: varOccurences,
  varReplace: varReplace,
  cleanUpCode: cleanUpCode,
  finalCleanUpCode: finalCleanUpCode,
  schemaHasRules: schemaHasRules,
  schemaHasRulesExcept: schemaHasRulesExcept,
  toQuotedString: toQuotedString,
  getPathExpr: getPathExpr,
  getPath: getPath,
  getData: getData,
  unescapeFragment: unescapeFragment,
  escapeFragment: escapeFragment,
  escapeJsonPointer: escapeJsonPointer
};


function copy(o, to) {
  to = to || {};
  for (var key in o) to[key] = o[key];
  return to;
}


function checkDataType(dataType, data, negate) {
  var EQUAL = negate ? ' !== ' : ' === '
    , AND = negate ? ' || ' : ' && '
    , OK = negate ? '!' : ''
    , NOT = negate ? '' : '!';
  switch (dataType) {
    case 'null': return data + EQUAL + 'null';
    case 'array': return OK + 'Array.isArray(' + data + ')';
    case 'object': return '(' + OK + data + AND +
                          'typeof ' + data + EQUAL + '"object"' + AND +
                          NOT + 'Array.isArray(' + data + '))';
    case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND +
                           NOT + '(' + data + ' % 1)' +
                           AND + data + EQUAL + data + ')';
    default: return 'typeof ' + data + EQUAL + '"' + dataType + '"';
  }
}


function checkDataTypes(dataTypes, data) {
  switch (dataTypes.length) {
    case 1: return checkDataType(dataTypes[0], data, true);
    default:
      var code = '';
      var types = toHash(dataTypes);
      if (types.array && types.object) {
        code = types.null ? '(': '(!' + data + ' || ';
        code += 'typeof ' + data + ' !== "object")';
        delete types.null;
        delete types.array;
        delete types.object;
      }
      if (types.number) delete types.integer;
      for (var t in types)
        code += (code ? ' && ' : '' ) + checkDataType(t, data, true);

      return code;
  }
}


var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]);
function coerceToTypes(optionCoerceTypes, dataTypes) {
  if (Array.isArray(dataTypes)) {
    var types = [];
    for (var i=0; i<dataTypes.length; i++) {
      var t = dataTypes[i];
      if (COERCE_TO_TYPES[t]) types[types.length] = t;
      else if (optionCoerceTypes === 'array' && t === 'array') types[types.length] = t;
    }
    if (types.length) return types;
  } else if (COERCE_TO_TYPES[dataTypes]) {
    return [dataTypes];
  } else if (optionCoerceTypes === 'array' && dataTypes === 'array') {
    return ['array'];
  }
}


function toHash(arr) {
  var hash = {};
  for (var i=0; i<arr.length; i++) hash[arr[i]] = true;
  return hash;
}


var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
var SINGLE_QUOTE = /'|\\/g;
function getProperty(key) {
  return typeof key == 'number'
          ? '[' + key + ']'
          : IDENTIFIER.test(key)
            ? '.' + key
            : "['" + escapeQuotes(key) + "']";
}


function escapeQuotes(str) {
  return str.replace(SINGLE_QUOTE, '\\$&')
            .replace(/\n/g, '\\n')
            .replace(/\r/g, '\\r')
            .replace(/\f/g, '\\f')
            .replace(/\t/g, '\\t');
}


function varOccurences(str, dataVar) {
  dataVar += '[^0-9]';
  var matches = str.match(new RegExp(dataVar, 'g'));
  return matches ? matches.length : 0;
}


function varReplace(str, dataVar, expr) {
  dataVar += '([^0-9])';
  expr = expr.replace(/\$/g, '$$$$');
  return str.replace(new RegExp(dataVar, 'g'), expr + '$1');
}


var EMPTY_ELSE = /else\s*{\s*}/g
  , EMPTY_IF_NO_ELSE = /if\s*\([^)]+\)\s*\{\s*\}(?!\s*else)/g
  , EMPTY_IF_WITH_ELSE = /if\s*\(([^)]+)\)\s*\{\s*\}\s*else(?!\s*if)/g;
function cleanUpCode(out) {
  return out.replace(EMPTY_ELSE, '')
            .replace(EMPTY_IF_NO_ELSE, '')
            .replace(EMPTY_IF_WITH_ELSE, 'if (!($1))');
}


var ERRORS_REGEXP = /[^v\.]errors/g
  , REMOVE_ERRORS = /var errors = 0;|var vErrors = null;|validate.errors = vErrors;/g
  , REMOVE_ERRORS_ASYNC = /var errors = 0;|var vErrors = null;/g
  , RETURN_VALID = 'return errors === 0;'
  , RETURN_TRUE = 'validate.errors = null; return true;'
  , RETURN_ASYNC = /if \(errors === 0\) return data;\s*else throw new ValidationError\(vErrors\);/
  , RETURN_DATA_ASYNC = 'return data;'
  , ROOTDATA_REGEXP = /[^A-Za-z_$]rootData[^A-Za-z0-9_$]/g
  , REMOVE_ROOTDATA = /if \(rootData === undefined\) rootData = data;/;

function finalCleanUpCode(out, async) {
  var matches = out.match(ERRORS_REGEXP);
  if (matches && matches.length == 2) {
    out = async
          ? out.replace(REMOVE_ERRORS_ASYNC, '')
               .replace(RETURN_ASYNC, RETURN_DATA_ASYNC)
          : out.replace(REMOVE_ERRORS, '')
               .replace(RETURN_VALID, RETURN_TRUE);
  }

  matches = out.match(ROOTDATA_REGEXP);
  if (!matches || matches.length !== 3) return out;
  return out.replace(REMOVE_ROOTDATA, '');
}


function schemaHasRules(schema, rules) {
  if (typeof schema == 'boolean') return !schema;
  for (var key in schema) if (rules[key]) return true;
}


function schemaHasRulesExcept(schema, rules, exceptKeyword) {
  if (typeof schema == 'boolean') return !schema && exceptKeyword != 'not';
  for (var key in schema) if (key != exceptKeyword && rules[key]) return true;
}


function toQuotedString(str) {
  return '\'' + escapeQuotes(str) + '\'';
}


function getPathExpr(currentPath, expr, jsonPointers, isNumber) {
  var path = jsonPointers // false by default
              ? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')')
              : (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\'');
  return joinPaths(currentPath, path);
}


function getPath(currentPath, prop, jsonPointers) {
  var path = jsonPointers // false by default
              ? toQuotedString('/' + escapeJsonPointer(prop))
              : toQuotedString(getProperty(prop));
  return joinPaths(currentPath, path);
}


var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
function getData($data, lvl, paths) {
  var up, jsonPointer, data, matches;
  if ($data === '') return 'rootData';
  if ($data[0] == '/') {
    if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data);
    jsonPointer = $data;
    data = 'rootData';
  } else {
    matches = $data.match(RELATIVE_JSON_POINTER);
    if (!matches) throw new Error('Invalid JSON-pointer: ' + $data);
    up = +matches[1];
    jsonPointer = matches[2];
    if (jsonPointer == '#') {
      if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl);
      return paths[lvl - up];
    }

    if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl);
    data = 'data' + ((lvl - up) || '');
    if (!jsonPointer) return data;
  }

  var expr = data;
  var segments = jsonPointer.split('/');
  for (var i=0; i<segments.length; i++) {
    var segment = segments[i];
    if (segment) {
      data += getProperty(unescapeJsonPointer(segment));
      expr += ' && ' + data;
    }
  }
  return expr;
}


function joinPaths (a, b) {
  if (a == '""') return b;
  return (a + ' + ' + b).replace(/' \+ '/g, '');
}


function unescapeFragment(str) {
  return unescapeJsonPointer(decodeURIComponent(str));
}


function escapeFragment(str) {
  return encodeURIComponent(escapeJsonPointer(str));
}


function escapeJsonPointer(str) {
  return str.replace(/~/g, '~0').replace(/\//g, '~1');
}


function unescapeJsonPointer(str) {
  return str.replace(/~1/g, '/').replace(/~0/g, '~');
}


/***/ }),

/***/ "+JPL":
/*!******************************************************!*\
  !*** ./node_modules/babel-runtime/core-js/symbol.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = { "default": __webpack_require__(/*! core-js/library/fn/symbol */ "+SFK"), __esModule: true };

/***/ }),

/***/ "+K+b":
/*!**************************************************!*\
  !*** ./node_modules/lodash/_cloneArrayBuffer.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Uint8Array = __webpack_require__(/*! ./_Uint8Array */ "JHRd");

/**
 * 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;
}

module.exports = cloneArrayBuffer;


/***/ }),

/***/ "+KPr":
/*!**************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/cells/style/inputarea.css ***!
  \**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n/*-----------------------------------------------------------------------------\n| Input\n|----------------------------------------------------------------------------*/\n\n/* All input areas */\n.jp-InputArea {\n  display: flex;\n  flex-direction: row;\n}\n\n.jp-InputArea-editor {\n  flex: 1 1 auto;\n}\n\n.jp-InputArea-editor {\n  /* This is the non-active, default styling */\n  border: var(--jp-border-width) solid var(--jp-cell-editor-border-color);\n  border-radius: 0px;\n  background: var(--jp-cell-editor-background);\n}\n\n.jp-InputPrompt {\n  flex: 0 0 var(--jp-cell-prompt-width);\n  color: var(--jp-cell-inprompt-font-color);\n  font-family: var(--jp-cell-prompt-font-family);\n  padding: var(--jp-code-padding);\n  letter-spacing: var(--jp-cell-prompt-letter-spacing);\n  opacity: var(--jp-cell-prompt-opacity);\n  line-height: var(--jp-code-line-height);\n  font-size: var(--jp-code-font-size);\n  border: var(--jp-border-width) solid transparent;\n  opacity: var(--jp-cell-prompt-opacity);\n  /* Right align prompt text, don't wrap to handle large prompt numbers */\n  text-align: right;\n  white-space: nowrap;\n  overflow: hidden;\n  text-overflow: ellipsis;\n  /* Disable text selection */\n  -webkit-user-select: none;\n  -moz-user-select: none;\n  -ms-user-select: none;\n  user-select: none;\n}\n", ""]);

// exports


/***/ }),

/***/ "+Keh":
/*!********************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/tabpanel.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var domutils_1 = __webpack_require__(/*! @phosphor/domutils */ "XWTc");
var messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
var signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
var boxlayout_1 = __webpack_require__(/*! ./boxlayout */ "mvme");
var stackedpanel_1 = __webpack_require__(/*! ./stackedpanel */ "m3yW");
var tabbar_1 = __webpack_require__(/*! ./tabbar */ "g07C");
var widget_1 = __webpack_require__(/*! ./widget */ "FmDU");
/**
 * A widget which combines a `TabBar` and a `StackedPanel`.
 *
 * #### Notes
 * This is a simple panel which handles the common case of a tab bar
 * placed next to a content area. The selected tab controls the widget
 * which is shown in the content area.
 *
 * For use cases which require more control than is provided by this
 * panel, the `TabBar` widget may be used independently.
 */
var TabPanel = (function (_super) {
    __extends(TabPanel, _super);
    /**
     * Construct a new tab panel.
     *
     * @param options - The options for initializing the tab panel.
     */
    function TabPanel(options) {
        if (options === void 0) { options = {}; }
        var _this = _super.call(this) || this;
        _this._currentChanged = new signaling_1.Signal(_this);
        _this.addClass('p-TabPanel');
        // Create the tab bar and stacked panel.
        _this.tabBar = new tabbar_1.TabBar(options);
        _this.tabBar.addClass('p-TabPanel-tabBar');
        _this.stackedPanel = new stackedpanel_1.StackedPanel();
        _this.stackedPanel.addClass('p-TabPanel-stackedPanel');
        // Connect the tab bar signal handlers.
        _this.tabBar.tabMoved.connect(_this._onTabMoved, _this);
        _this.tabBar.currentChanged.connect(_this._onCurrentChanged, _this);
        _this.tabBar.tabCloseRequested.connect(_this._onTabCloseRequested, _this);
        _this.tabBar.tabActivateRequested.connect(_this._onTabActivateRequested, _this);
        // Connect the stacked panel signal handlers.
        _this.stackedPanel.widgetRemoved.connect(_this._onWidgetRemoved, _this);
        // Get the data related to the placement.
        _this._tabPlacement = options.tabPlacement || 'top';
        var direction = Private.directionFromPlacement(_this._tabPlacement);
        var orientation = Private.orientationFromPlacement(_this._tabPlacement);
        // Configure the tab bar for the placement.
        _this.tabBar.orientation = orientation;
        _this.tabBar.dataset['placement'] = _this._tabPlacement;
        // Create the box layout.
        var layout = new boxlayout_1.BoxLayout({ direction: direction, spacing: 0 });
        // Set the stretch factors for the child widgets.
        boxlayout_1.BoxLayout.setStretch(_this.tabBar, 0);
        boxlayout_1.BoxLayout.setStretch(_this.stackedPanel, 1);
        // Add the child widgets to the layout.
        layout.addWidget(_this.tabBar);
        layout.addWidget(_this.stackedPanel);
        // Install the layout on the tab panel.
        _this.layout = layout;
        return _this;
    }
    Object.defineProperty(TabPanel.prototype, "currentChanged", {
        /**
         * A signal emitted when the current tab is changed.
         *
         * #### Notes
         * This signal is emitted when the currently selected tab is changed
         * either through user or programmatic interaction.
         *
         * Notably, this signal is not emitted when the index of the current
         * tab changes due to tabs being inserted, removed, or moved. It is
         * only emitted when the actual current tab node is changed.
         */
        get: function () {
            return this._currentChanged;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(TabPanel.prototype, "currentIndex", {
        /**
         * Get the index of the currently selected tab.
         *
         * #### Notes
         * This will be `-1` if no tab is selected.
         */
        get: function () {
            return this.tabBar.currentIndex;
        },
        /**
         * Set the index of the currently selected tab.
         *
         * #### Notes
         * If the index is out of range, it will be set to `-1`.
         */
        set: function (value) {
            this.tabBar.currentIndex = value;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(TabPanel.prototype, "currentWidget", {
        /**
         * Get the currently selected widget.
         *
         * #### Notes
         * This will be `null` if there is no selected tab.
         */
        get: function () {
            var title = this.tabBar.currentTitle;
            return title ? title.owner : null;
        },
        /**
         * Set the currently selected widget.
         *
         * #### Notes
         * If the widget is not in the panel, it will be set to `null`.
         */
        set: function (value) {
            this.tabBar.currentTitle = value ? value.title : null;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(TabPanel.prototype, "tabsMovable", {
        /**
         * Get the whether the tabs are movable by the user.
         *
         * #### Notes
         * Tabs can always be moved programmatically.
         */
        get: function () {
            return this.tabBar.tabsMovable;
        },
        /**
         * Set the whether the tabs are movable by the user.
         *
         * #### Notes
         * Tabs can always be moved programmatically.
         */
        set: function (value) {
            this.tabBar.tabsMovable = value;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(TabPanel.prototype, "tabPlacement", {
        /**
         * Get the tab placement for the tab panel.
         *
         * #### Notes
         * This controls the position of the tab bar relative to the content.
         */
        get: function () {
            return this._tabPlacement;
        },
        /**
         * Set the tab placement for the tab panel.
         *
         * #### Notes
         * This controls the position of the tab bar relative to the content.
         */
        set: function (value) {
            // Bail if the placement does not change.
            if (this._tabPlacement === value) {
                return;
            }
            // Update the internal value.
            this._tabPlacement = value;
            // Get the values related to the placement.
            var direction = Private.directionFromPlacement(value);
            var orientation = Private.orientationFromPlacement(value);
            // Configure the tab bar for the placement.
            this.tabBar.orientation = orientation;
            this.tabBar.dataset['placement'] = value;
            // Update the layout direction.
            this.layout.direction = direction;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(TabPanel.prototype, "widgets", {
        /**
         * A read-only array of the widgets in the panel.
         */
        get: function () {
            return this.stackedPanel.widgets;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Add a widget to the end of the tab panel.
     *
     * @param widget - The widget to add to the tab panel.
     *
     * #### Notes
     * If the widget is already contained in the panel, it will be moved.
     *
     * The widget's `title` is used to populate the tab.
     */
    TabPanel.prototype.addWidget = function (widget) {
        this.insertWidget(this.widgets.length, widget);
    };
    /**
     * Insert a widget into the tab panel at a specified index.
     *
     * @param index - The index at which to insert the widget.
     *
     * @param widget - The widget to insert into to the tab panel.
     *
     * #### Notes
     * If the widget is already contained in the panel, it will be moved.
     *
     * The widget's `title` is used to populate the tab.
     */
    TabPanel.prototype.insertWidget = function (index, widget) {
        if (widget !== this.currentWidget) {
            widget.hide();
        }
        this.stackedPanel.insertWidget(index, widget);
        this.tabBar.insertTab(index, widget.title);
    };
    /**
     * Handle the `currentChanged` signal from the tab bar.
     */
    TabPanel.prototype._onCurrentChanged = function (sender, args) {
        // Extract the previous and current title from the args.
        var previousIndex = args.previousIndex, previousTitle = args.previousTitle, currentIndex = args.currentIndex, currentTitle = args.currentTitle;
        // Extract the widgets from the titles.
        var previousWidget = previousTitle ? previousTitle.owner : null;
        var currentWidget = currentTitle ? currentTitle.owner : null;
        // Hide the previous widget.
        if (previousWidget) {
            previousWidget.hide();
        }
        // Show the current widget.
        if (currentWidget) {
            currentWidget.show();
        }
        // Emit the `currentChanged` signal for the tab panel.
        this._currentChanged.emit({
            previousIndex: previousIndex, previousWidget: previousWidget, currentIndex: currentIndex, currentWidget: currentWidget
        });
        // Flush the message loop on IE and Edge to prevent flicker.
        if (domutils_1.Platform.IS_EDGE || domutils_1.Platform.IS_IE) {
            messaging_1.MessageLoop.flush();
        }
    };
    /**
     * Handle the `tabActivateRequested` signal from the tab bar.
     */
    TabPanel.prototype._onTabActivateRequested = function (sender, args) {
        args.title.owner.activate();
    };
    /**
     * Handle the `tabCloseRequested` signal from the tab bar.
     */
    TabPanel.prototype._onTabCloseRequested = function (sender, args) {
        args.title.owner.close();
    };
    /**
     * Handle the `tabMoved` signal from the tab bar.
     */
    TabPanel.prototype._onTabMoved = function (sender, args) {
        this.stackedPanel.insertWidget(args.toIndex, args.title.owner);
    };
    /**
     * Handle the `widgetRemoved` signal from the stacked panel.
     */
    TabPanel.prototype._onWidgetRemoved = function (sender, widget) {
        this.tabBar.removeTab(widget.title);
    };
    return TabPanel;
}(widget_1.Widget));
exports.TabPanel = TabPanel;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * Convert a tab placement to tab bar orientation.
     */
    function orientationFromPlacement(plc) {
        return placementToOrientationMap[plc];
    }
    Private.orientationFromPlacement = orientationFromPlacement;
    /**
     * Convert a tab placement to a box layout direction.
     */
    function directionFromPlacement(plc) {
        return placementToDirectionMap[plc];
    }
    Private.directionFromPlacement = directionFromPlacement;
    /**
     * A mapping of tab placement to tab bar orientation.
     */
    var placementToOrientationMap = {
        'top': 'horizontal',
        'left': 'vertical',
        'right': 'vertical',
        'bottom': 'horizontal'
    };
    /**
     * A mapping of tab placement to box layout direction.
     */
    var placementToDirectionMap = {
        'top': 'top-to-bottom',
        'left': 'left-to-right',
        'right': 'right-to-left',
        'bottom': 'bottom-to-top'
    };
})(Private || (Private = {}));


/***/ }),

/***/ "+Kq5":
/*!***********************************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/terminal-highlight.js ***!
  \***********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _chalk = __webpack_require__(/*! chalk */ 8);

var _chalk2 = _interopRequireDefault(_chalk);

var _tokenize = __webpack_require__(/*! ./tokenize */ "r2ia");

var _tokenize2 = _interopRequireDefault(_tokenize);

var _input = __webpack_require__(/*! ./input */ "pOV6");

var _input2 = _interopRequireDefault(_input);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var HIGHLIGHT_THEME = {
    'brackets': _chalk2.default.cyan,
    'at-word': _chalk2.default.cyan,
    'call': _chalk2.default.cyan,
    'comment': _chalk2.default.gray,
    'string': _chalk2.default.green,
    'class': _chalk2.default.yellow,
    'hash': _chalk2.default.magenta,
    '(': _chalk2.default.cyan,
    ')': _chalk2.default.cyan,
    '{': _chalk2.default.yellow,
    '}': _chalk2.default.yellow,
    '[': _chalk2.default.yellow,
    ']': _chalk2.default.yellow,
    ':': _chalk2.default.yellow,
    ';': _chalk2.default.yellow
};

function getTokenType(_ref, processor) {
    var type = _ref[0],
        value = _ref[1];

    if (type === 'word') {
        if (value[0] === '.') {
            return 'class';
        }
        if (value[0] === '#') {
            return 'hash';
        }
    }

    if (!processor.endOfFile()) {
        var next = processor.nextToken();
        processor.back(next);
        if (next[0] === 'brackets' || next[0] === '(') return 'call';
    }

    return type;
}

function terminalHighlight(css) {
    var processor = (0, _tokenize2.default)(new _input2.default(css), { ignoreErrors: true });
    var result = '';

    var _loop = function _loop() {
        var token = processor.nextToken();
        var color = HIGHLIGHT_THEME[getTokenType(token, processor)];
        if (color) {
            result += token[1].split(/\r?\n/).map(function (i) {
                return color(i);
            }).join('\n');
        } else {
            result += token[1];
        }
    };

    while (!processor.endOfFile()) {
        _loop();
    }
    return result;
}

exports.default = terminalHighlight;
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64, 


/***/ }),

/***/ "+LWr":
/*!******************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/ZoomPlusIcon.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var ZoomPlusIcon = function ZoomPlusIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 16 16' }, props),
        _react2.default.createElement('path', { d: 'M.013 1.012V15h13.999V1.012H.013zm10.999 7.995H8.013v2.999h-2V9.007h-3V7.008h3V4.01h2v2.998h2.999v1.999z' })
    );
};

exports.default = ZoomPlusIcon;

/***/ }),

/***/ "+NIl":
/*!***************************************************!*\
  !*** ./node_modules/codemirror/mode/stex/stex.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

/*
 * Author: Constantin Jucovschi (c.jucovschi@jacobs-university.de)
 * Licence: MIT
 */

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"));
  else {}
})(function(CodeMirror) {
  "use strict";

  CodeMirror.defineMode("stex", function(_config, parserConfig) {
    "use strict";

    function pushCommand(state, command) {
      state.cmdState.push(command);
    }

    function peekCommand(state) {
      if (state.cmdState.length > 0) {
        return state.cmdState[state.cmdState.length - 1];
      } else {
        return null;
      }
    }

    function popCommand(state) {
      var plug = state.cmdState.pop();
      if (plug) {
        plug.closeBracket();
      }
    }

    // returns the non-default plugin closest to the end of the list
    function getMostPowerful(state) {
      var context = state.cmdState;
      for (var i = context.length - 1; i >= 0; i--) {
        var plug = context[i];
        if (plug.name == "DEFAULT") {
          continue;
        }
        return plug;
      }
      return { styleIdentifier: function() { return null; } };
    }

    function addPluginPattern(pluginName, cmdStyle, styles) {
      return function () {
        this.name = pluginName;
        this.bracketNo = 0;
        this.style = cmdStyle;
        this.styles = styles;
        this.argument = null;   // \begin and \end have arguments that follow. These are stored in the plugin

        this.styleIdentifier = function() {
          return this.styles[this.bracketNo - 1] || null;
        };
        this.openBracket = function() {
          this.bracketNo++;
          return "bracket";
        };
        this.closeBracket = function() {};
      };
    }

    var plugins = {};

    plugins["importmodule"] = addPluginPattern("importmodule", "tag", ["string", "builtin"]);
    plugins["documentclass"] = addPluginPattern("documentclass", "tag", ["", "atom"]);
    plugins["usepackage"] = addPluginPattern("usepackage", "tag", ["atom"]);
    plugins["begin"] = addPluginPattern("begin", "tag", ["atom"]);
    plugins["end"] = addPluginPattern("end", "tag", ["atom"]);

    plugins["label"    ] = addPluginPattern("label"    , "tag", ["atom"]);
    plugins["ref"      ] = addPluginPattern("ref"      , "tag", ["atom"]);
    plugins["eqref"    ] = addPluginPattern("eqref"    , "tag", ["atom"]);
    plugins["cite"     ] = addPluginPattern("cite"     , "tag", ["atom"]);
    plugins["bibitem"  ] = addPluginPattern("bibitem"  , "tag", ["atom"]);
    plugins["Bibitem"  ] = addPluginPattern("Bibitem"  , "tag", ["atom"]);
    plugins["RBibitem" ] = addPluginPattern("RBibitem" , "tag", ["atom"]);

    plugins["DEFAULT"] = function () {
      this.name = "DEFAULT";
      this.style = "tag";

      this.styleIdentifier = this.openBracket = this.closeBracket = function() {};
    };

    function setState(state, f) {
      state.f = f;
    }

    // called when in a normal (no environment) context
    function normal(source, state) {
      var plug;
      // Do we look like '\command' ?  If so, attempt to apply the plugin 'command'
      if (source.match(/^\\[a-zA-Z@]+/)) {
        var cmdName = source.current().slice(1);
        plug = plugins[cmdName] || plugins["DEFAULT"];
        plug = new plug();
        pushCommand(state, plug);
        setState(state, beginParams);
        return plug.style;
      }

      // escape characters
      if (source.match(/^\\[$&%#{}_]/)) {
        return "tag";
      }

      // white space control characters
      if (source.match(/^\\[,;!\/\\]/)) {
        return "tag";
      }

      // find if we're starting various math modes
      if (source.match("\\[")) {
        setState(state, function(source, state){ return inMathMode(source, state, "\\]"); });
        return "keyword";
      }
      if (source.match("\\(")) {
        setState(state, function(source, state){ return inMathMode(source, state, "\\)"); });
        return "keyword";
      }
      if (source.match("$$")) {
        setState(state, function(source, state){ return inMathMode(source, state, "$$"); });
        return "keyword";
      }
      if (source.match("$")) {
        setState(state, function(source, state){ return inMathMode(source, state, "$"); });
        return "keyword";
      }

      var ch = source.next();
      if (ch == "%") {
        source.skipToEnd();
        return "comment";
      } else if (ch == '}' || ch == ']') {
        plug = peekCommand(state);
        if (plug) {
          plug.closeBracket(ch);
          setState(state, beginParams);
        } else {
          return "error";
        }
        return "bracket";
      } else if (ch == '{' || ch == '[') {
        plug = plugins["DEFAULT"];
        plug = new plug();
        pushCommand(state, plug);
        return "bracket";
      } else if (/\d/.test(ch)) {
        source.eatWhile(/[\w.%]/);
        return "atom";
      } else {
        source.eatWhile(/[\w\-_]/);
        plug = getMostPowerful(state);
        if (plug.name == 'begin') {
          plug.argument = source.current();
        }
        return plug.styleIdentifier();
      }
    }

    function inMathMode(source, state, endModeSeq) {
      if (source.eatSpace()) {
        return null;
      }
      if (endModeSeq && source.match(endModeSeq)) {
        setState(state, normal);
        return "keyword";
      }
      if (source.match(/^\\[a-zA-Z@]+/)) {
        return "tag";
      }
      if (source.match(/^[a-zA-Z]+/)) {
        return "variable-2";
      }
      // escape characters
      if (source.match(/^\\[$&%#{}_]/)) {
        return "tag";
      }
      // white space control characters
      if (source.match(/^\\[,;!\/]/)) {
        return "tag";
      }
      // special math-mode characters
      if (source.match(/^[\^_&]/)) {
        return "tag";
      }
      // non-special characters
      if (source.match(/^[+\-<>|=,\/@!*:;'"`~#?]/)) {
        return null;
      }
      if (source.match(/^(\d+\.\d*|\d*\.\d+|\d+)/)) {
        return "number";
      }
      var ch = source.next();
      if (ch == "{" || ch == "}" || ch == "[" || ch == "]" || ch == "(" || ch == ")") {
        return "bracket";
      }

      if (ch == "%") {
        source.skipToEnd();
        return "comment";
      }
      return "error";
    }

    function beginParams(source, state) {
      var ch = source.peek(), lastPlug;
      if (ch == '{' || ch == '[') {
        lastPlug = peekCommand(state);
        lastPlug.openBracket(ch);
        source.eat(ch);
        setState(state, normal);
        return "bracket";
      }
      if (/[ \t\r]/.test(ch)) {
        source.eat(ch);
        return null;
      }
      setState(state, normal);
      popCommand(state);

      return normal(source, state);
    }

    return {
      startState: function() {
        var f = parserConfig.inMathMode ? function(source, state){ return inMathMode(source, state); } : normal;
        return {
          cmdState: [],
          f: f
        };
      },
      copyState: function(s) {
        return {
          cmdState: s.cmdState.slice(),
          f: s.f
        };
      },
      token: function(stream, state) {
        return state.f(stream, state);
      },
      blankLine: function(state) {
        state.f = normal;
        state.cmdState.length = 0;
      },
      lineComment: "%"
    };
  });

  CodeMirror.defineMIME("text/x-stex", "stex");
  CodeMirror.defineMIME("text/x-latex", "stex");

});


/***/ }),

/***/ "+NTi":
/*!*************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/apputils/style/index.css ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports
exports.i(__webpack_require__(/*! -!../../../css-loader!./commandpalette.css */ "kamm"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./dialog.css */ "wSGS"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./hoverbox.css */ "ndfH"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./iframe.css */ "wkn1"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./mainareawidget.css */ "BQpX"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./materialcolors.css */ "SlFw"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./spinner.css */ "disn"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./styling.css */ "9gmq"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./toolbar.css */ "4vnq"), "");

// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, Jupyter Development Team.\n|\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n", ""]);

// exports


/***/ }),

/***/ "+P8q":
/*!**************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeContourIcon.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeContourIcon = function TraceTypeContourIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement(
            'g',
            { fill: 'none' },
            _react2.default.createElement('path', { d: 'M0 0h46v46H0z' }),
            _react2.default.createElement('path', { d: 'M40.616 19.3a16.387 16.387 0 0 0-1.352-3.904 9.836 9.836 0 0 0-4.225-4.015c-6.17-3.152-13.563-4.731-20.021-1.298a23.665 23.665 0 0 0-4.74 3.47 14.357 14.357 0 0 0-3.28 3.934c-1.636 3.205-.982 6.997-.015 10.433a7.81 7.81 0 0 0 1.083 2.555 8.344 8.344 0 0 0 2.63 2.1c2.611 1.526 5.352 2.845 8.089 4.161a13.223 13.223 0 0 0 2.59 1.028 11.867 11.867 0 0 0 3.048.229 8.678 8.678 0 0 0 3.538-.623 8.95 8.95 0 0 0 2.162-1.622l6.115-5.645c2.223-2.053 4.584-4.37 4.83-7.288a10.951 10.951 0 0 0-.452-3.515zm-5.174 2.942c-.29 1.988-1.825 3.679-3.153 4.984a88.579 88.579 0 0 1-3.648 3.367 5.915 5.915 0 0 1-1.32.94 5.617 5.617 0 0 1-2.098.423 7.835 7.835 0 0 1-1.807-.076 9.038 9.038 0 0 1-1.8-.557 31.794 31.794 0 0 1-5.487-2.889 7.104 7.104 0 0 1-1.758-1.487q-.114-.146-.212-.3a5.426 5.426 0 0 1-.622-1.396 11.172 11.172 0 0 1-.476-3.496 6.775 6.775 0 0 1 .752-2.988 9.108 9.108 0 0 1 2.07-2.44 13.848 13.848 0 0 1 3.042-2.08 11.145 11.145 0 0 1 1.363-.556c3.693-1.236 7.762-.478 11.257 1.23a7.12 7.12 0 0 1 2.765 2.381 6.918 6.918 0 0 1 .995 2.566 6.94 6.94 0 0 1 .137 2.374z', stroke: '#1d9bfb', strokeMiterlimit: '10', strokeWidth: '2' }),
            _react2.default.createElement('path', { d: 'M34.31 17.302a7.12 7.12 0 0 0-2.765-2.382c-3.495-1.709-7.564-2.466-11.257-1.23a11.145 11.145 0 0 0-1.363.556 13.848 13.848 0 0 0-3.043 2.081 9.108 9.108 0 0 0-2.07 2.44 6.775 6.775 0 0 0-.75 2.987 11.172 11.172 0 0 0 .475 3.496 5.426 5.426 0 0 0 .622 1.397q.099.153.212.3a7.104 7.104 0 0 0 1.758 1.486 31.794 31.794 0 0 0 5.486 2.889 9.038 9.038 0 0 0 1.801.558 7.835 7.835 0 0 0 1.807.075 5.617 5.617 0 0 0 2.099-.423 5.915 5.915 0 0 0 1.319-.94 88.299 88.299 0 0 0 3.648-3.366c1.328-1.306 2.863-2.996 3.153-4.985a6.94 6.94 0 0 0-.137-2.373 6.918 6.918 0 0 0-.995-2.566z', stroke: '#1d9bfb', opacity: '.25', strokeMiterlimit: '10', strokeWidth: '2' }),
            _react2.default.createElement('path', { d: 'M25.457 25.996c-1.787.083-3.494-1.142-4.914-2.724a2.032 2.032 0 0 1-.452-.69 2.44 2.44 0 0 1 .028-1.4 3.985 3.985 0 0 1 1.368-2.08 4.888 4.888 0 0 1 1.922-.854 6.99 6.99 0 0 1 5.948.96c1.604 1.233-.197 4.086-1.018 5.142a3.975 3.975 0 0 1-2.882 1.646z', stroke: '#1d9bfb', strokeMiterlimit: '10', strokeWidth: '2' })
        )
    );
};

exports.default = TraceTypeContourIcon;

/***/ }),

/***/ "+Qka":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_baseMerge.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Stack = __webpack_require__(/*! ./_Stack */ "fmRc"),
    assignMergeValue = __webpack_require__(/*! ./_assignMergeValue */ "t2Dn"),
    baseFor = __webpack_require__(/*! ./_baseFor */ "cq/+"),
    baseMergeDeep = __webpack_require__(/*! ./_baseMergeDeep */ "T1AV"),
    isObject = __webpack_require__(/*! ./isObject */ "GoyQ"),
    keysIn = __webpack_require__(/*! ./keysIn */ "mTTR"),
    safeGet = __webpack_require__(/*! ./_safeGet */ "itsj");

/**
 * 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) {
    if (isObject(srcValue)) {
      stack || (stack = new Stack);
      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;


/***/ }),

/***/ "+SFK":
/*!*********************************************************!*\
  !*** ./node_modules/core-js/library/fn/symbol/index.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(/*! ../../modules/es6.symbol */ "AUvm");
__webpack_require__(/*! ../../modules/es6.object.to-string */ "wgeU");
__webpack_require__(/*! ../../modules/es7.symbol.async-iterator */ "adOz");
__webpack_require__(/*! ../../modules/es7.symbol.observable */ "dl0q");
module.exports = __webpack_require__(/*! ../../modules/_core */ "WEpk").Symbol;


/***/ }),

/***/ "+aGp":
/*!********************************************!*\
  !*** ./node_modules/fbjs/lib/hyphenate.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks
 */

var _uppercasePattern = /([A-Z])/g;

/**
 * Hyphenates a camelcased string, for example:
 *
 *   > hyphenate('backgroundColor')
 *   < "background-color"
 *
 * For CSS style names, use `hyphenateStyleName` instead which works properly
 * with all vendor prefixes, including `ms`.
 *
 * @param {string} string
 * @return {string}
 */
function hyphenate(string) {
  return string.replace(_uppercasePattern, '-$1').toLowerCase();
}

module.exports = hyphenate;

/***/ }),

/***/ "+aMc":
/*!****************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeAnimationIcon.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeAnimationIcon = function TraceTypeAnimationIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement('path', { fill: 'none', d: 'M0 0h46v46H0z' }),
        _react2.default.createElement('circle', { cx: '13.5', cy: '31.5', r: '7', fill: '#25fdfc', opacity: '.4' }),
        _react2.default.createElement('circle', { cx: '17.875', cy: '27.125', r: '7', fill: '#23e5fc', opacity: '.55' }),
        _react2.default.createElement('circle', { cx: '22.25', cy: '22.75', r: '7', fill: '#21ccfc', opacity: '.7' }),
        _react2.default.createElement('circle', { cx: '26.625', cy: '18.375', r: '7', fill: '#1fb3fb', opacity: '.85' }),
        _react2.default.createElement('circle', { cx: '31', cy: '14', r: '7', fill: '#1d9bfb' })
    );
};

exports.default = TraceTypeAnimationIcon;

/***/ }),

/***/ "+c4W":
/*!*****************************************!*\
  !*** ./node_modules/lodash/property.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseProperty = __webpack_require__(/*! ./_baseProperty */ "711d"),
    basePropertyDeep = __webpack_require__(/*! ./_basePropertyDeep */ "4/ic"),
    isKey = __webpack_require__(/*! ./_isKey */ "9ggG"),
    toKey = __webpack_require__(/*! ./_toKey */ "9Nap");

/**
 * 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);
}

module.exports = property;


/***/ }),

/***/ "+dQi":
/*!***************************************************************!*\
  !*** ./node_modules/codemirror/mode/javascript/javascript.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"));
  else {}
})(function(CodeMirror) {
"use strict";

CodeMirror.defineMode("javascript", function(config, parserConfig) {
  var indentUnit = config.indentUnit;
  var statementIndent = parserConfig.statementIndent;
  var jsonldMode = parserConfig.jsonld;
  var jsonMode = parserConfig.json || jsonldMode;
  var isTS = parserConfig.typescript;
  var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/;

  // Tokenizer

  var keywords = function(){
    function kw(type) {return {type: type, style: "keyword"};}
    var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d");
    var operator = kw("operator"), atom = {type: "atom", style: "atom"};

    return {
      "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
      "return": D, "break": D, "continue": D, "new": kw("new"), "delete": C, "void": C, "throw": C,
      "debugger": kw("debugger"), "var": kw("var"), "const": kw("var"), "let": kw("var"),
      "function": kw("function"), "catch": kw("catch"),
      "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
      "in": operator, "typeof": operator, "instanceof": operator,
      "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom,
      "this": kw("this"), "class": kw("class"), "super": kw("atom"),
      "yield": C, "export": kw("export"), "import": kw("import"), "extends": C,
      "await": C
    };
  }();

  var isOperatorChar = /[+\-*&%=<>!?|~^@]/;
  var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;

  function readRegexp(stream) {
    var escaped = false, next, inSet = false;
    while ((next = stream.next()) != null) {
      if (!escaped) {
        if (next == "/" && !inSet) return;
        if (next == "[") inSet = true;
        else if (inSet && next == "]") inSet = false;
      }
      escaped = !escaped && next == "\\";
    }
  }

  // Used as scratch variables to communicate multiple values without
  // consing up tons of objects.
  var type, content;
  function ret(tp, style, cont) {
    type = tp; content = cont;
    return style;
  }
  function tokenBase(stream, state) {
    var ch = stream.next();
    if (ch == '"' || ch == "'") {
      state.tokenize = tokenString(ch);
      return state.tokenize(stream, state);
    } else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) {
      return ret("number", "number");
    } else if (ch == "." && stream.match("..")) {
      return ret("spread", "meta");
    } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
      return ret(ch);
    } else if (ch == "=" && stream.eat(">")) {
      return ret("=>", "operator");
    } else if (ch == "0" && stream.match(/^(?:x[\da-f]+|o[0-7]+|b[01]+)n?/i)) {
      return ret("number", "number");
    } else if (/\d/.test(ch)) {
      stream.match(/^\d*(?:n|(?:\.\d*)?(?:[eE][+\-]?\d+)?)?/);
      return ret("number", "number");
    } else if (ch == "/") {
      if (stream.eat("*")) {
        state.tokenize = tokenComment;
        return tokenComment(stream, state);
      } else if (stream.eat("/")) {
        stream.skipToEnd();
        return ret("comment", "comment");
      } else if (expressionAllowed(stream, state, 1)) {
        readRegexp(stream);
        stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/);
        return ret("regexp", "string-2");
      } else {
        stream.eat("=");
        return ret("operator", "operator", stream.current());
      }
    } else if (ch == "`") {
      state.tokenize = tokenQuasi;
      return tokenQuasi(stream, state);
    } else if (ch == "#") {
      stream.skipToEnd();
      return ret("error", "error");
    } else if (isOperatorChar.test(ch)) {
      if (ch != ">" || !state.lexical || state.lexical.type != ">") {
        if (stream.eat("=")) {
          if (ch == "!" || ch == "=") stream.eat("=")
        } else if (/[<>*+\-]/.test(ch)) {
          stream.eat(ch)
          if (ch == ">") stream.eat(ch)
        }
      }
      return ret("operator", "operator", stream.current());
    } else if (wordRE.test(ch)) {
      stream.eatWhile(wordRE);
      var word = stream.current()
      if (state.lastType != ".") {
        if (keywords.propertyIsEnumerable(word)) {
          var kw = keywords[word]
          return ret(kw.type, kw.style, word)
        }
        if (word == "async" && stream.match(/^(\s|\/\*.*?\*\/)*[\[\(\w]/, false))
          return ret("async", "keyword", word)
      }
      return ret("variable", "variable", word)
    }
  }

  function tokenString(quote) {
    return function(stream, state) {
      var escaped = false, next;
      if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
        state.tokenize = tokenBase;
        return ret("jsonld-keyword", "meta");
      }
      while ((next = stream.next()) != null) {
        if (next == quote && !escaped) break;
        escaped = !escaped && next == "\\";
      }
      if (!escaped) state.tokenize = tokenBase;
      return ret("string", "string");
    };
  }

  function tokenComment(stream, state) {
    var maybeEnd = false, ch;
    while (ch = stream.next()) {
      if (ch == "/" && maybeEnd) {
        state.tokenize = tokenBase;
        break;
      }
      maybeEnd = (ch == "*");
    }
    return ret("comment", "comment");
  }

  function tokenQuasi(stream, state) {
    var escaped = false, next;
    while ((next = stream.next()) != null) {
      if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
        state.tokenize = tokenBase;
        break;
      }
      escaped = !escaped && next == "\\";
    }
    return ret("quasi", "string-2", stream.current());
  }

  var brackets = "([{}])";
  // This is a crude lookahead trick to try and notice that we're
  // parsing the argument patterns for a fat-arrow function before we
  // actually hit the arrow token. It only works if the arrow is on
  // the same line as the arguments and there's no strange noise
  // (comments) in between. Fallback is to only notice when we hit the
  // arrow, and not declare the arguments as locals for the arrow
  // body.
  function findFatArrow(stream, state) {
    if (state.fatArrowAt) state.fatArrowAt = null;
    var arrow = stream.string.indexOf("=>", stream.start);
    if (arrow < 0) return;

    if (isTS) { // Try to skip TypeScript return type declarations after the arguments
      var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow))
      if (m) arrow = m.index
    }

    var depth = 0, sawSomething = false;
    for (var pos = arrow - 1; pos >= 0; --pos) {
      var ch = stream.string.charAt(pos);
      var bracket = brackets.indexOf(ch);
      if (bracket >= 0 && bracket < 3) {
        if (!depth) { ++pos; break; }
        if (--depth == 0) { if (ch == "(") sawSomething = true; break; }
      } else if (bracket >= 3 && bracket < 6) {
        ++depth;
      } else if (wordRE.test(ch)) {
        sawSomething = true;
      } else if (/["'\/]/.test(ch)) {
        return;
      } else if (sawSomething && !depth) {
        ++pos;
        break;
      }
    }
    if (sawSomething && !depth) state.fatArrowAt = pos;
  }

  // Parser

  var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true};

  function JSLexical(indented, column, type, align, prev, info) {
    this.indented = indented;
    this.column = column;
    this.type = type;
    this.prev = prev;
    this.info = info;
    if (align != null) this.align = align;
  }

  function inScope(state, varname) {
    for (var v = state.localVars; v; v = v.next)
      if (v.name == varname) return true;
    for (var cx = state.context; cx; cx = cx.prev) {
      for (var v = cx.vars; v; v = v.next)
        if (v.name == varname) return true;
    }
  }

  function parseJS(state, style, type, content, stream) {
    var cc = state.cc;
    // Communicate our context to the combinators.
    // (Less wasteful than consing up a hundred closures on every call.)
    cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;

    if (!state.lexical.hasOwnProperty("align"))
      state.lexical.align = true;

    while(true) {
      var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
      if (combinator(type, content)) {
        while(cc.length && cc[cc.length - 1].lex)
          cc.pop()();
        if (cx.marked) return cx.marked;
        if (type == "variable" && inScope(state, content)) return "variable-2";
        return style;
      }
    }
  }

  // Combinator utils

  var cx = {state: null, column: null, marked: null, cc: null};
  function pass() {
    for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
  }
  function cont() {
    pass.apply(null, arguments);
    return true;
  }
  function inList(name, list) {
    for (var v = list; v; v = v.next) if (v.name == name) return true
    return false;
  }
  function register(varname) {
    var state = cx.state;
    cx.marked = "def";
    if (state.context) {
      if (state.lexical.info == "var" && state.context && state.context.block) {
        // FIXME function decls are also not block scoped
        var newContext = registerVarScoped(varname, state.context)
        if (newContext != null) {
          state.context = newContext
          return
        }
      } else if (!inList(varname, state.localVars)) {
        state.localVars = new Var(varname, state.localVars)
        return
      }
    }
    // Fall through means this is global
    if (parserConfig.globalVars && !inList(varname, state.globalVars))
      state.globalVars = new Var(varname, state.globalVars)
  }
  function registerVarScoped(varname, context) {
    if (!context) {
      return null
    } else if (context.block) {
      var inner = registerVarScoped(varname, context.prev)
      if (!inner) return null
      if (inner == context.prev) return context
      return new Context(inner, context.vars, true)
    } else if (inList(varname, context.vars)) {
      return context
    } else {
      return new Context(context.prev, new Var(varname, context.vars), false)
    }
  }

  function isModifier(name) {
    return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly"
  }

  // Combinators

  function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block }
  function Var(name, next) { this.name = name; this.next = next }

  var defaultVars = new Var("this", new Var("arguments", null))
  function pushcontext() {
    cx.state.context = new Context(cx.state.context, cx.state.localVars, false)
    cx.state.localVars = defaultVars
  }
  function pushblockcontext() {
    cx.state.context = new Context(cx.state.context, cx.state.localVars, true)
    cx.state.localVars = null
  }
  function popcontext() {
    cx.state.localVars = cx.state.context.vars
    cx.state.context = cx.state.context.prev
  }
  popcontext.lex = true
  function pushlex(type, info) {
    var result = function() {
      var state = cx.state, indent = state.indented;
      if (state.lexical.type == "stat") indent = state.lexical.indented;
      else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev)
        indent = outer.indented;
      state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
    };
    result.lex = true;
    return result;
  }
  function poplex() {
    var state = cx.state;
    if (state.lexical.prev) {
      if (state.lexical.type == ")")
        state.indented = state.lexical.indented;
      state.lexical = state.lexical.prev;
    }
  }
  poplex.lex = true;

  function expect(wanted) {
    function exp(type) {
      if (type == wanted) return cont();
      else if (wanted == ";" || type == "}" || type == ")" || type == "]") return pass();
      else return cont(exp);
    };
    return exp;
  }

  function statement(type, value) {
    if (type == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex);
    if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex);
    if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
    if (type == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex);
    if (type == "debugger") return cont(expect(";"));
    if (type == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext);
    if (type == ";") return cont();
    if (type == "if") {
      if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
        cx.state.cc.pop()();
      return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse);
    }
    if (type == "function") return cont(functiondef);
    if (type == "for") return cont(pushlex("form"), forspec, statement, poplex);
    if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), className, poplex); }
    if (type == "variable") {
      if (isTS && value == "declare") {
        cx.marked = "keyword"
        return cont(statement)
      } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) {
        cx.marked = "keyword"
        if (value == "enum") return cont(enumdef);
        else if (value == "type") return cont(typeexpr, expect("operator"), typeexpr, expect(";"));
        else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex)
      } else if (isTS && value == "namespace") {
        cx.marked = "keyword"
        return cont(pushlex("form"), expression, block, poplex)
      } else if (isTS && value == "abstract") {
        cx.marked = "keyword"
        return cont(statement)
      } else {
        return cont(pushlex("stat"), maybelabel);
      }
    }
    if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext,
                                      block, poplex, poplex, popcontext);
    if (type == "case") return cont(expression, expect(":"));
    if (type == "default") return cont(expect(":"));
    if (type == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext);
    if (type == "export") return cont(pushlex("stat"), afterExport, poplex);
    if (type == "import") return cont(pushlex("stat"), afterImport, poplex);
    if (type == "async") return cont(statement)
    if (value == "@") return cont(expression, statement)
    return pass(pushlex("stat"), expression, expect(";"), poplex);
  }
  function maybeCatchBinding(type) {
    if (type == "(") return cont(funarg, expect(")"))
  }
  function expression(type, value) {
    return expressionInner(type, value, false);
  }
  function expressionNoComma(type, value) {
    return expressionInner(type, value, true);
  }
  function parenExpr(type) {
    if (type != "(") return pass()
    return cont(pushlex(")"), expression, expect(")"), poplex)
  }
  function expressionInner(type, value, noComma) {
    if (cx.state.fatArrowAt == cx.stream.start) {
      var body = noComma ? arrowBodyNoComma : arrowBody;
      if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext);
      else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
    }

    var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
    if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
    if (type == "function") return cont(functiondef, maybeop);
    if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), classExpression, poplex); }
    if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression);
    if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop);
    if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
    if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
    if (type == "{") return contCommasep(objprop, "}", null, maybeop);
    if (type == "quasi") return pass(quasi, maybeop);
    if (type == "new") return cont(maybeTarget(noComma));
    if (type == "import") return cont(expression);
    return cont();
  }
  function maybeexpression(type) {
    if (type.match(/[;\}\)\],]/)) return pass();
    return pass(expression);
  }

  function maybeoperatorComma(type, value) {
    if (type == ",") return cont(expression);
    return maybeoperatorNoComma(type, value, false);
  }
  function maybeoperatorNoComma(type, value, noComma) {
    var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
    var expr = noComma == false ? expression : expressionNoComma;
    if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
    if (type == "operator") {
      if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me);
      if (isTS && value == "<" && cx.stream.match(/^([^>]|<.*?>)*>\s*\(/, false))
        return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me);
      if (value == "?") return cont(expression, expect(":"), expr);
      return cont(expr);
    }
    if (type == "quasi") { return pass(quasi, me); }
    if (type == ";") return;
    if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
    if (type == ".") return cont(property, me);
    if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
    if (isTS && value == "as") { cx.marked = "keyword"; return cont(typeexpr, me) }
    if (type == "regexp") {
      cx.state.lastType = cx.marked = "operator"
      cx.stream.backUp(cx.stream.pos - cx.stream.start - 1)
      return cont(expr)
    }
  }
  function quasi(type, value) {
    if (type != "quasi") return pass();
    if (value.slice(value.length - 2) != "${") return cont(quasi);
    return cont(expression, continueQuasi);
  }
  function continueQuasi(type) {
    if (type == "}") {
      cx.marked = "string-2";
      cx.state.tokenize = tokenQuasi;
      return cont(quasi);
    }
  }
  function arrowBody(type) {
    findFatArrow(cx.stream, cx.state);
    return pass(type == "{" ? statement : expression);
  }
  function arrowBodyNoComma(type) {
    findFatArrow(cx.stream, cx.state);
    return pass(type == "{" ? statement : expressionNoComma);
  }
  function maybeTarget(noComma) {
    return function(type) {
      if (type == ".") return cont(noComma ? targetNoComma : target);
      else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma)
      else return pass(noComma ? expressionNoComma : expression);
    };
  }
  function target(_, value) {
    if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); }
  }
  function targetNoComma(_, value) {
    if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); }
  }
  function maybelabel(type) {
    if (type == ":") return cont(poplex, statement);
    return pass(maybeoperatorComma, expect(";"), poplex);
  }
  function property(type) {
    if (type == "variable") {cx.marked = "property"; return cont();}
  }
  function objprop(type, value) {
    if (type == "async") {
      cx.marked = "property";
      return cont(objprop);
    } else if (type == "variable" || cx.style == "keyword") {
      cx.marked = "property";
      if (value == "get" || value == "set") return cont(getterSetter);
      var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params
      if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false)))
        cx.state.fatArrowAt = cx.stream.pos + m[0].length
      return cont(afterprop);
    } else if (type == "number" || type == "string") {
      cx.marked = jsonldMode ? "property" : (cx.style + " property");
      return cont(afterprop);
    } else if (type == "jsonld-keyword") {
      return cont(afterprop);
    } else if (isTS && isModifier(value)) {
      cx.marked = "keyword"
      return cont(objprop)
    } else if (type == "[") {
      return cont(expression, maybetype, expect("]"), afterprop);
    } else if (type == "spread") {
      return cont(expressionNoComma, afterprop);
    } else if (value == "*") {
      cx.marked = "keyword";
      return cont(objprop);
    } else if (type == ":") {
      return pass(afterprop)
    }
  }
  function getterSetter(type) {
    if (type != "variable") return pass(afterprop);
    cx.marked = "property";
    return cont(functiondef);
  }
  function afterprop(type) {
    if (type == ":") return cont(expressionNoComma);
    if (type == "(") return pass(functiondef);
  }
  function commasep(what, end, sep) {
    function proceed(type, value) {
      if (sep ? sep.indexOf(type) > -1 : type == ",") {
        var lex = cx.state.lexical;
        if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
        return cont(function(type, value) {
          if (type == end || value == end) return pass()
          return pass(what)
        }, proceed);
      }
      if (type == end || value == end) return cont();
      return cont(expect(end));
    }
    return function(type, value) {
      if (type == end || value == end) return cont();
      return pass(what, proceed);
    };
  }
  function contCommasep(what, end, info) {
    for (var i = 3; i < arguments.length; i++)
      cx.cc.push(arguments[i]);
    return cont(pushlex(end, info), commasep(what, end), poplex);
  }
  function block(type) {
    if (type == "}") return cont();
    return pass(statement, block);
  }
  function maybetype(type, value) {
    if (isTS) {
      if (type == ":") return cont(typeexpr);
      if (value == "?") return cont(maybetype);
    }
  }
  function mayberettype(type) {
    if (isTS && type == ":") {
      if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr)
      else return cont(typeexpr)
    }
  }
  function isKW(_, value) {
    if (value == "is") {
      cx.marked = "keyword"
      return cont()
    }
  }
  function typeexpr(type, value) {
    if (value == "keyof" || value == "typeof") {
      cx.marked = "keyword"
      return cont(value == "keyof" ? typeexpr : expressionNoComma)
    }
    if (type == "variable" || value == "void") {
      cx.marked = "type"
      return cont(afterType)
    }
    if (type == "string" || type == "number" || type == "atom") return cont(afterType);
    if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType)
    if (type == "{") return cont(pushlex("}"), commasep(typeprop, "}", ",;"), poplex, afterType)
    if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType)
    if (type == "<") return cont(commasep(typeexpr, ">"), typeexpr)
  }
  function maybeReturnType(type) {
    if (type == "=>") return cont(typeexpr)
  }
  function typeprop(type, value) {
    if (type == "variable" || cx.style == "keyword") {
      cx.marked = "property"
      return cont(typeprop)
    } else if (value == "?") {
      return cont(typeprop)
    } else if (type == ":") {
      return cont(typeexpr)
    } else if (type == "[") {
      return cont(expression, maybetype, expect("]"), typeprop)
    }
  }
  function typearg(type, value) {
    if (type == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg)
    if (type == ":") return cont(typeexpr)
    return pass(typeexpr)
  }
  function afterType(type, value) {
    if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
    if (value == "|" || type == "." || value == "&") return cont(typeexpr)
    if (type == "[") return cont(expect("]"), afterType)
    if (value == "extends" || value == "implements") { cx.marked = "keyword"; return cont(typeexpr) }
  }
  function maybeTypeArgs(_, value) {
    if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
  }
  function typeparam() {
    return pass(typeexpr, maybeTypeDefault)
  }
  function maybeTypeDefault(_, value) {
    if (value == "=") return cont(typeexpr)
  }
  function vardef(_, value) {
    if (value == "enum") {cx.marked = "keyword"; return cont(enumdef)}
    return pass(pattern, maybetype, maybeAssign, vardefCont);
  }
  function pattern(type, value) {
    if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(pattern) }
    if (type == "variable") { register(value); return cont(); }
    if (type == "spread") return cont(pattern);
    if (type == "[") return contCommasep(pattern, "]");
    if (type == "{") return contCommasep(proppattern, "}");
  }
  function proppattern(type, value) {
    if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
      register(value);
      return cont(maybeAssign);
    }
    if (type == "variable") cx.marked = "property";
    if (type == "spread") return cont(pattern);
    if (type == "}") return pass();
    return cont(expect(":"), pattern, maybeAssign);
  }
  function maybeAssign(_type, value) {
    if (value == "=") return cont(expressionNoComma);
  }
  function vardefCont(type) {
    if (type == ",") return cont(vardef);
  }
  function maybeelse(type, value) {
    if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
  }
  function forspec(type, value) {
    if (value == "await") return cont(forspec);
    if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex);
  }
  function forspec1(type) {
    if (type == "var") return cont(vardef, expect(";"), forspec2);
    if (type == ";") return cont(forspec2);
    if (type == "variable") return cont(formaybeinof);
    return pass(expression, expect(";"), forspec2);
  }
  function formaybeinof(_type, value) {
    if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
    return cont(maybeoperatorComma, forspec2);
  }
  function forspec2(type, value) {
    if (type == ";") return cont(forspec3);
    if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
    return pass(expression, expect(";"), forspec3);
  }
  function forspec3(type) {
    if (type != ")") cont(expression);
  }
  function functiondef(type, value) {
    if (value == "*") {cx.marked = "keyword"; return cont(functiondef);}
    if (type == "variable") {register(value); return cont(functiondef);}
    if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext);
    if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef)
  }
  function funarg(type, value) {
    if (value == "@") cont(expression, funarg)
    if (type == "spread") return cont(funarg);
    if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(funarg); }
    return pass(pattern, maybetype, maybeAssign);
  }
  function classExpression(type, value) {
    // Class expressions may have an optional name.
    if (type == "variable") return className(type, value);
    return classNameAfter(type, value);
  }
  function className(type, value) {
    if (type == "variable") {register(value); return cont(classNameAfter);}
  }
  function classNameAfter(type, value) {
    if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter)
    if (value == "extends" || value == "implements" || (isTS && type == ",")) {
      if (value == "implements") cx.marked = "keyword";
      return cont(isTS ? typeexpr : expression, classNameAfter);
    }
    if (type == "{") return cont(pushlex("}"), classBody, poplex);
  }
  function classBody(type, value) {
    if (type == "async" ||
        (type == "variable" &&
         (value == "static" || value == "get" || value == "set" || (isTS && isModifier(value))) &&
         cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false))) {
      cx.marked = "keyword";
      return cont(classBody);
    }
    if (type == "variable" || cx.style == "keyword") {
      cx.marked = "property";
      return cont(isTS ? classfield : functiondef, classBody);
    }
    if (type == "[")
      return cont(expression, maybetype, expect("]"), isTS ? classfield : functiondef, classBody)
    if (value == "*") {
      cx.marked = "keyword";
      return cont(classBody);
    }
    if (type == ";") return cont(classBody);
    if (type == "}") return cont();
    if (value == "@") return cont(expression, classBody)
  }
  function classfield(type, value) {
    if (value == "?") return cont(classfield)
    if (type == ":") return cont(typeexpr, maybeAssign)
    if (value == "=") return cont(expressionNoComma)
    return pass(functiondef)
  }
  function afterExport(type, value) {
    if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); }
    if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); }
    if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";"));
    return pass(statement);
  }
  function exportField(type, value) {
    if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); }
    if (type == "variable") return pass(expressionNoComma, exportField);
  }
  function afterImport(type) {
    if (type == "string") return cont();
    if (type == "(") return pass(expression);
    return pass(importSpec, maybeMoreImports, maybeFrom);
  }
  function importSpec(type, value) {
    if (type == "{") return contCommasep(importSpec, "}");
    if (type == "variable") register(value);
    if (value == "*") cx.marked = "keyword";
    return cont(maybeAs);
  }
  function maybeMoreImports(type) {
    if (type == ",") return cont(importSpec, maybeMoreImports)
  }
  function maybeAs(_type, value) {
    if (value == "as") { cx.marked = "keyword"; return cont(importSpec); }
  }
  function maybeFrom(_type, value) {
    if (value == "from") { cx.marked = "keyword"; return cont(expression); }
  }
  function arrayLiteral(type) {
    if (type == "]") return cont();
    return pass(commasep(expressionNoComma, "]"));
  }
  function enumdef() {
    return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex)
  }
  function enummember() {
    return pass(pattern, maybeAssign);
  }

  function isContinuedStatement(state, textAfter) {
    return state.lastType == "operator" || state.lastType == "," ||
      isOperatorChar.test(textAfter.charAt(0)) ||
      /[,.]/.test(textAfter.charAt(0));
  }

  function expressionAllowed(stream, state, backUp) {
    return state.tokenize == tokenBase &&
      /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) ||
      (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))))
  }

  // Interface

  return {
    startState: function(basecolumn) {
      var state = {
        tokenize: tokenBase,
        lastType: "sof",
        cc: [],
        lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
        localVars: parserConfig.localVars,
        context: parserConfig.localVars && new Context(null, null, false),
        indented: basecolumn || 0
      };
      if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
        state.globalVars = parserConfig.globalVars;
      return state;
    },

    token: function(stream, state) {
      if (stream.sol()) {
        if (!state.lexical.hasOwnProperty("align"))
          state.lexical.align = false;
        state.indented = stream.indentation();
        findFatArrow(stream, state);
      }
      if (state.tokenize != tokenComment && stream.eatSpace()) return null;
      var style = state.tokenize(stream, state);
      if (type == "comment") return style;
      state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
      return parseJS(state, style, type, content, stream);
    },

    indent: function(state, textAfter) {
      if (state.tokenize == tokenComment) return CodeMirror.Pass;
      if (state.tokenize != tokenBase) return 0;
      var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top
      // Kludge to prevent 'maybelse' from blocking lexical scope pops
      if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
        var c = state.cc[i];
        if (c == poplex) lexical = lexical.prev;
        else if (c != maybeelse) break;
      }
      while ((lexical.type == "stat" || lexical.type == "form") &&
             (firstChar == "}" || ((top = state.cc[state.cc.length - 1]) &&
                                   (top == maybeoperatorComma || top == maybeoperatorNoComma) &&
                                   !/^[,\.=+\-*:?[\(]/.test(textAfter))))
        lexical = lexical.prev;
      if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
        lexical = lexical.prev;
      var type = lexical.type, closing = firstChar == type;

      if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0);
      else if (type == "form" && firstChar == "{") return lexical.indented;
      else if (type == "form") return lexical.indented + indentUnit;
      else if (type == "stat")
        return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);
      else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
        return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
      else if (lexical.align) return lexical.column + (closing ? 0 : 1);
      else return lexical.indented + (closing ? 0 : indentUnit);
    },

    electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
    blockCommentStart: jsonMode ? null : "/*",
    blockCommentEnd: jsonMode ? null : "*/",
    blockCommentContinue: jsonMode ? null : " * ",
    lineComment: jsonMode ? null : "//",
    fold: "brace",
    closeBrackets: "()[]{}''\"\"``",

    helperType: jsonMode ? "json" : "javascript",
    jsonldMode: jsonldMode,
    jsonMode: jsonMode,

    expressionAllowed: expressionAllowed,

    skipExpression: function(state) {
      var top = state.cc[state.cc.length - 1]
      if (top == expression || top == expressionNoComma) state.cc.pop()
    }
  };
});

CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/);

CodeMirror.defineMIME("text/javascript", "javascript");
CodeMirror.defineMIME("text/ecmascript", "javascript");
CodeMirror.defineMIME("application/javascript", "javascript");
CodeMirror.defineMIME("application/x-javascript", "javascript");
CodeMirror.defineMIME("application/ecmascript", "javascript");
CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true});
CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true});
CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });

});


/***/ }),

/***/ "+drS":
/*!************************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/relink_private.js ***!
  \************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




var isArrayOrTypedArray = __webpack_require__(/*! ./array */ "lCvc").isArrayOrTypedArray;
var isPlainObject = __webpack_require__(/*! ./is_plain_object */ "SWc2");

/**
 * Relink private _keys and keys with a function value from one container
 * to the new container.
 * Relink means copying if object is pass-by-value and adding a reference
 * if object is pass-by-ref.
 * This prevents deepCopying massive structures like a webgl context.
 */
module.exports = function relinkPrivateKeys(toContainer, fromContainer) {
    for(var k in fromContainer) {
        var fromVal = fromContainer[k];
        var toVal = toContainer[k];

        if(toVal === fromVal) {
            continue;
        }
        if(k.charAt(0) === '_' || typeof fromVal === 'function') {

            // if it already exists at this point, it's something
            // that we recreate each time around, so ignore it
            if(k in toContainer) continue;

            toContainer[k] = fromVal;
        }
        else if(isArrayOrTypedArray(fromVal) && isArrayOrTypedArray(toVal) && isPlainObject(fromVal[0])) {

            // filter out data_array items that can contain user objects
            // most of the time the toVal === fromVal check will catch these early
            // but if the user makes new ones we also don't want to recurse in.
            if(k === 'customdata' || k === 'ids') continue;

            // recurse into arrays containers
            var minLen = Math.min(fromVal.length, toVal.length);
            for(var j = 0; j < minLen; j++) {
                if((toVal[j] !== fromVal[j]) && isPlainObject(fromVal[j]) && isPlainObject(toVal[j])) {
                    relinkPrivateKeys(toVal[j], fromVal[j]);
                }
            }
        }
        else if(isPlainObject(fromVal) && isPlainObject(toVal)) {

            // recurse into objects, but only if they still exist
            relinkPrivateKeys(toVal, fromVal);

            if(!Object.keys(toVal).length) delete toContainer[k];
        }
    }
};


/***/ }),

/***/ "+iFO":
/*!*************************************************!*\
  !*** ./node_modules/lodash/_initCloneObject.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseCreate = __webpack_require__(/*! ./_baseCreate */ "dTAl"),
    getPrototype = __webpack_require__(/*! ./_getPrototype */ "LcsW"),
    isPrototype = __webpack_require__(/*! ./_isPrototype */ "6sVZ");

/**
 * 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))
    : {};
}

module.exports = initCloneObject;


/***/ }),

/***/ "+lml":
/*!*************************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/make_trace_groups.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




/**
 * General helper to manage trace groups based on calcdata
 *
 * @param {d3.selection} traceLayer: a selection containing a single group
 *     to draw these traces into
 * @param {array} cdModule: array of calcdata items for this
 *     module and subplot combination. Assumes the calcdata item for each
 *     trace is an array with the fullData trace attached to the first item.
 * @param {string} cls: the class attribute to give each trace group
 *     so you can give multiple classes separated by spaces
 */
module.exports = function makeTraceGroups(traceLayer, cdModule, cls) {
    var traces = traceLayer.selectAll('g.' + cls.replace(/\s/g, '.'))
        .data(cdModule, function(cd) { return cd[0].trace.uid; });

    traces.exit().remove();

    traces.enter().append('g')
        .attr('class', cls);

    traces.order();

    return traces;
};


/***/ }),

/***/ "+qE3":
/*!***************************************!*\
  !*** ./node_modules/events/events.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.



var R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
  ? R.apply
  : function ReflectApply(target, receiver, args) {
    return Function.prototype.apply.call(target, receiver, args);
  }

var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
  ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
  ReflectOwnKeys = function ReflectOwnKeys(target) {
    return Object.getOwnPropertyNames(target)
      .concat(Object.getOwnPropertySymbols(target));
  };
} else {
  ReflectOwnKeys = function ReflectOwnKeys(target) {
    return Object.getOwnPropertyNames(target);
  };
}

function ProcessEmitWarning(warning) {
  if (console && console.warn) console.warn(warning);
}

var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
  return value !== value;
}

function EventEmitter() {
  EventEmitter.init.call(this);
}
module.exports = EventEmitter;

// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;

EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;

// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
var defaultMaxListeners = 10;

Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  enumerable: true,
  get: function() {
    return defaultMaxListeners;
  },
  set: function(arg) {
    if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
      throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
    }
    defaultMaxListeners = arg;
  }
});

EventEmitter.init = function() {

  if (this._events === undefined ||
      this._events === Object.getPrototypeOf(this)._events) {
    this._events = Object.create(null);
    this._eventsCount = 0;
  }

  this._maxListeners = this._maxListeners || undefined;
};

// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
    throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
  }
  this._maxListeners = n;
  return this;
};

function $getMaxListeners(that) {
  if (that._maxListeners === undefined)
    return EventEmitter.defaultMaxListeners;
  return that._maxListeners;
}

EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  return $getMaxListeners(this);
};

EventEmitter.prototype.emit = function emit(type) {
  var args = [];
  for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
  var doError = (type === 'error');

  var events = this._events;
  if (events !== undefined)
    doError = (doError && events.error === undefined);
  else if (!doError)
    return false;

  // If there is no 'error' event listener then throw.
  if (doError) {
    var er;
    if (args.length > 0)
      er = args[0];
    if (er instanceof Error) {
      // Note: The comments on the `throw` lines are intentional, they show
      // up in Node's output if this results in an unhandled exception.
      throw er; // Unhandled 'error' event
    }
    // At least give some kind of context to the user
    var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
    err.context = er;
    throw err; // Unhandled 'error' event
  }

  var handler = events[type];

  if (handler === undefined)
    return false;

  if (typeof handler === 'function') {
    ReflectApply(handler, this, args);
  } else {
    var len = handler.length;
    var listeners = arrayClone(handler, len);
    for (var i = 0; i < len; ++i)
      ReflectApply(listeners[i], this, args);
  }

  return true;
};

function _addListener(target, type, listener, prepend) {
  var m;
  var events;
  var existing;

  if (typeof listener !== 'function') {
    throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
  }

  events = target._events;
  if (events === undefined) {
    events = target._events = Object.create(null);
    target._eventsCount = 0;
  } else {
    // To avoid recursion in the case that type === "newListener"! Before
    // adding it to the listeners, first emit "newListener".
    if (events.newListener !== undefined) {
      target.emit('newListener', type,
                  listener.listener ? listener.listener : listener);

      // Re-assign `events` because a newListener handler could have caused the
      // this._events to be assigned to a new object
      events = target._events;
    }
    existing = events[type];
  }

  if (existing === undefined) {
    // Optimize the case of one listener. Don't need the extra array object.
    existing = events[type] = listener;
    ++target._eventsCount;
  } else {
    if (typeof existing === 'function') {
      // Adding the second element, need to change to array.
      existing = events[type] =
        prepend ? [listener, existing] : [existing, listener];
      // If we've already got an array, just append.
    } else if (prepend) {
      existing.unshift(listener);
    } else {
      existing.push(listener);
    }

    // Check for listener leak
    m = $getMaxListeners(target);
    if (m > 0 && existing.length > m && !existing.warned) {
      existing.warned = true;
      // No error code for this since it is a Warning
      // eslint-disable-next-line no-restricted-syntax
      var w = new Error('Possible EventEmitter memory leak detected. ' +
                          existing.length + ' ' + String(type) + ' listeners ' +
                          'added. Use emitter.setMaxListeners() to ' +
                          'increase limit');
      w.name = 'MaxListenersExceededWarning';
      w.emitter = target;
      w.type = type;
      w.count = existing.length;
      ProcessEmitWarning(w);
    }
  }

  return target;
}

EventEmitter.prototype.addListener = function addListener(type, listener) {
  return _addListener(this, type, listener, false);
};

EventEmitter.prototype.on = EventEmitter.prototype.addListener;

EventEmitter.prototype.prependListener =
    function prependListener(type, listener) {
      return _addListener(this, type, listener, true);
    };

function onceWrapper() {
  var args = [];
  for (var i = 0; i < arguments.length; i++) args.push(arguments[i]);
  if (!this.fired) {
    this.target.removeListener(this.type, this.wrapFn);
    this.fired = true;
    ReflectApply(this.listener, this.target, args);
  }
}

function _onceWrap(target, type, listener) {
  var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  var wrapped = onceWrapper.bind(state);
  wrapped.listener = listener;
  state.wrapFn = wrapped;
  return wrapped;
}

EventEmitter.prototype.once = function once(type, listener) {
  if (typeof listener !== 'function') {
    throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
  }
  this.on(type, _onceWrap(this, type, listener));
  return this;
};

EventEmitter.prototype.prependOnceListener =
    function prependOnceListener(type, listener) {
      if (typeof listener !== 'function') {
        throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
      }
      this.prependListener(type, _onceWrap(this, type, listener));
      return this;
    };

// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
    function removeListener(type, listener) {
      var list, events, position, i, originalListener;

      if (typeof listener !== 'function') {
        throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
      }

      events = this._events;
      if (events === undefined)
        return this;

      list = events[type];
      if (list === undefined)
        return this;

      if (list === listener || list.listener === listener) {
        if (--this._eventsCount === 0)
          this._events = Object.create(null);
        else {
          delete events[type];
          if (events.removeListener)
            this.emit('removeListener', type, list.listener || listener);
        }
      } else if (typeof list !== 'function') {
        position = -1;

        for (i = list.length - 1; i >= 0; i--) {
          if (list[i] === listener || list[i].listener === listener) {
            originalListener = list[i].listener;
            position = i;
            break;
          }
        }

        if (position < 0)
          return this;

        if (position === 0)
          list.shift();
        else {
          spliceOne(list, position);
        }

        if (list.length === 1)
          events[type] = list[0];

        if (events.removeListener !== undefined)
          this.emit('removeListener', type, originalListener || listener);
      }

      return this;
    };

EventEmitter.prototype.off = EventEmitter.prototype.removeListener;

EventEmitter.prototype.removeAllListeners =
    function removeAllListeners(type) {
      var listeners, events, i;

      events = this._events;
      if (events === undefined)
        return this;

      // not listening for removeListener, no need to emit
      if (events.removeListener === undefined) {
        if (arguments.length === 0) {
          this._events = Object.create(null);
          this._eventsCount = 0;
        } else if (events[type] !== undefined) {
          if (--this._eventsCount === 0)
            this._events = Object.create(null);
          else
            delete events[type];
        }
        return this;
      }

      // emit removeListener for all listeners on all events
      if (arguments.length === 0) {
        var keys = Object.keys(events);
        var key;
        for (i = 0; i < keys.length; ++i) {
          key = keys[i];
          if (key === 'removeListener') continue;
          this.removeAllListeners(key);
        }
        this.removeAllListeners('removeListener');
        this._events = Object.create(null);
        this._eventsCount = 0;
        return this;
      }

      listeners = events[type];

      if (typeof listeners === 'function') {
        this.removeListener(type, listeners);
      } else if (listeners !== undefined) {
        // LIFO order
        for (i = listeners.length - 1; i >= 0; i--) {
          this.removeListener(type, listeners[i]);
        }
      }

      return this;
    };

function _listeners(target, type, unwrap) {
  var events = target._events;

  if (events === undefined)
    return [];

  var evlistener = events[type];
  if (evlistener === undefined)
    return [];

  if (typeof evlistener === 'function')
    return unwrap ? [evlistener.listener || evlistener] : [evlistener];

  return unwrap ?
    unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}

EventEmitter.prototype.listeners = function listeners(type) {
  return _listeners(this, type, true);
};

EventEmitter.prototype.rawListeners = function rawListeners(type) {
  return _listeners(this, type, false);
};

EventEmitter.listenerCount = function(emitter, type) {
  if (typeof emitter.listenerCount === 'function') {
    return emitter.listenerCount(type);
  } else {
    return listenerCount.call(emitter, type);
  }
};

EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
  var events = this._events;

  if (events !== undefined) {
    var evlistener = events[type];

    if (typeof evlistener === 'function') {
      return 1;
    } else if (evlistener !== undefined) {
      return evlistener.length;
    }
  }

  return 0;
}

EventEmitter.prototype.eventNames = function eventNames() {
  return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};

function arrayClone(arr, n) {
  var copy = new Array(n);
  for (var i = 0; i < n; ++i)
    copy[i] = arr[i];
  return copy;
}

function spliceOne(list, index) {
  for (; index + 1 < list.length; index++)
    list[index] = list[index + 1];
  list.pop();
}

function unwrapListeners(arr) {
  var ret = new Array(arr.length);
  for (var i = 0; i < ret.length; ++i) {
    ret[i] = arr[i].listener || arr[i];
  }
  return ret;
}


/***/ }),

/***/ "+s0g":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/nl.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var monthsShortWithDots = 'jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.'.split('_'),
    monthsShortWithoutDots = 'jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec'.split('_');

var monthsParse = [/^jan/i, /^feb/i, /^maart|mrt.?$/i, /^apr/i, /^mei$/i, /^jun[i.]?$/i, /^jul[i.]?$/i, /^aug/i, /^sep/i, /^okt/i, /^nov/i, /^dec/i];
var monthsRegex = /^(januari|februari|maart|april|mei|april|ju[nl]i|augustus|september|oktober|november|december|jan\.?|feb\.?|mrt\.?|apr\.?|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i;

var nl = moment.defineLocale('nl', {
    months : 'januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december'.split('_'),
    monthsShort : function (m, format) {
        if (!m) {
            return monthsShortWithDots;
        } else if (/-MMM-/.test(format)) {
            return monthsShortWithoutDots[m.month()];
        } else {
            return monthsShortWithDots[m.month()];
        }
    },

    monthsRegex: monthsRegex,
    monthsShortRegex: monthsRegex,
    monthsStrictRegex: /^(januari|februari|maart|mei|ju[nl]i|april|augustus|september|oktober|november|december)/i,
    monthsShortStrictRegex: /^(jan\.?|feb\.?|mrt\.?|apr\.?|mei|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i,

    monthsParse : monthsParse,
    longMonthsParse : monthsParse,
    shortMonthsParse : monthsParse,

    weekdays : 'zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag'.split('_'),
    weekdaysShort : 'zo._ma._di._wo._do._vr._za.'.split('_'),
    weekdaysMin : 'zo_ma_di_wo_do_vr_za'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD-MM-YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay: '[vandaag om] LT',
        nextDay: '[morgen om] LT',
        nextWeek: 'dddd [om] LT',
        lastDay: '[gisteren om] LT',
        lastWeek: '[afgelopen] dddd [om] LT',
        sameElse: 'L'
    },
    relativeTime : {
        future : 'over %s',
        past : '%s geleden',
        s : 'een paar seconden',
        ss : '%d seconden',
        m : 'één minuut',
        mm : '%d minuten',
        h : 'één uur',
        hh : '%d uur',
        d : 'één dag',
        dd : '%d dagen',
        M : 'één maand',
        MM : '%d maanden',
        y : 'één jaar',
        yy : '%d jaar'
    },
    dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/,
    ordinal : function (number) {
        return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de');
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return nl;

})));


/***/ }),

/***/ "+vba":
/*!**************************************************!*\
  !*** ./node_modules/mdi-react/CreditCardIcon.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var CreditCardIcon = function CreditCardIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M20,8H4V6H20M20,18H4V12H20M20,4H4C2.89,4 2,4.89 2,6V18C2,19.1 2.9,20 4,20H20C21.1,20 22,19.1 22,18V6C22,4.89 21.1,4 20,4Z' })
  );
};

module.exports = CreditCardIcon;


/***/ }),

/***/ "+wB9":
/*!******************************************************************!*\
  !*** ./node_modules/json-parser/node_modules/esprima/esprima.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*
  Copyright (c) jQuery Foundation, Inc. and Contributors, All Rights Reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

(function (root, factory) {
    'use strict';

    // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
    // Rhino, and plain browser loading.

    /* istanbul ignore next */
    if (true) {
        !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
    } else {}
}(this, function (exports) {
    'use strict';

    var Token,
        TokenName,
        FnExprTokens,
        Syntax,
        PlaceHolders,
        Messages,
        Regex,
        source,
        strict,
        index,
        lineNumber,
        lineStart,
        hasLineTerminator,
        lastIndex,
        lastLineNumber,
        lastLineStart,
        startIndex,
        startLineNumber,
        startLineStart,
        scanning,
        length,
        lookahead,
        state,
        extra,
        isBindingElement,
        isAssignmentTarget,
        firstCoverInitializedNameError;

    Token = {
        BooleanLiteral: 1,
        EOF: 2,
        Identifier: 3,
        Keyword: 4,
        NullLiteral: 5,
        NumericLiteral: 6,
        Punctuator: 7,
        StringLiteral: 8,
        RegularExpression: 9,
        Template: 10
    };

    TokenName = {};
    TokenName[Token.BooleanLiteral] = 'Boolean';
    TokenName[Token.EOF] = '<end>';
    TokenName[Token.Identifier] = 'Identifier';
    TokenName[Token.Keyword] = 'Keyword';
    TokenName[Token.NullLiteral] = 'Null';
    TokenName[Token.NumericLiteral] = 'Numeric';
    TokenName[Token.Punctuator] = 'Punctuator';
    TokenName[Token.StringLiteral] = 'String';
    TokenName[Token.RegularExpression] = 'RegularExpression';
    TokenName[Token.Template] = 'Template';

    // A function following one of those tokens is an expression.
    FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
                    'return', 'case', 'delete', 'throw', 'void',
                    // assignment operators
                    '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=',
                    '&=', '|=', '^=', ',',
                    // binary/unary operators
                    '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&',
                    '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
                    '<=', '<', '>', '!=', '!=='];

    Syntax = {
        AssignmentExpression: 'AssignmentExpression',
        AssignmentPattern: 'AssignmentPattern',
        ArrayExpression: 'ArrayExpression',
        ArrayPattern: 'ArrayPattern',
        ArrowFunctionExpression: 'ArrowFunctionExpression',
        BlockStatement: 'BlockStatement',
        BinaryExpression: 'BinaryExpression',
        BreakStatement: 'BreakStatement',
        CallExpression: 'CallExpression',
        CatchClause: 'CatchClause',
        ClassBody: 'ClassBody',
        ClassDeclaration: 'ClassDeclaration',
        ClassExpression: 'ClassExpression',
        ConditionalExpression: 'ConditionalExpression',
        ContinueStatement: 'ContinueStatement',
        DoWhileStatement: 'DoWhileStatement',
        DebuggerStatement: 'DebuggerStatement',
        EmptyStatement: 'EmptyStatement',
        ExportAllDeclaration: 'ExportAllDeclaration',
        ExportDefaultDeclaration: 'ExportDefaultDeclaration',
        ExportNamedDeclaration: 'ExportNamedDeclaration',
        ExportSpecifier: 'ExportSpecifier',
        ExpressionStatement: 'ExpressionStatement',
        ForStatement: 'ForStatement',
        ForOfStatement: 'ForOfStatement',
        ForInStatement: 'ForInStatement',
        FunctionDeclaration: 'FunctionDeclaration',
        FunctionExpression: 'FunctionExpression',
        Identifier: 'Identifier',
        IfStatement: 'IfStatement',
        ImportDeclaration: 'ImportDeclaration',
        ImportDefaultSpecifier: 'ImportDefaultSpecifier',
        ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
        ImportSpecifier: 'ImportSpecifier',
        Literal: 'Literal',
        LabeledStatement: 'LabeledStatement',
        LogicalExpression: 'LogicalExpression',
        MemberExpression: 'MemberExpression',
        MetaProperty: 'MetaProperty',
        MethodDefinition: 'MethodDefinition',
        NewExpression: 'NewExpression',
        ObjectExpression: 'ObjectExpression',
        ObjectPattern: 'ObjectPattern',
        Program: 'Program',
        Property: 'Property',
        RestElement: 'RestElement',
        ReturnStatement: 'ReturnStatement',
        SequenceExpression: 'SequenceExpression',
        SpreadElement: 'SpreadElement',
        Super: 'Super',
        SwitchCase: 'SwitchCase',
        SwitchStatement: 'SwitchStatement',
        TaggedTemplateExpression: 'TaggedTemplateExpression',
        TemplateElement: 'TemplateElement',
        TemplateLiteral: 'TemplateLiteral',
        ThisExpression: 'ThisExpression',
        ThrowStatement: 'ThrowStatement',
        TryStatement: 'TryStatement',
        UnaryExpression: 'UnaryExpression',
        UpdateExpression: 'UpdateExpression',
        VariableDeclaration: 'VariableDeclaration',
        VariableDeclarator: 'VariableDeclarator',
        WhileStatement: 'WhileStatement',
        WithStatement: 'WithStatement',
        YieldExpression: 'YieldExpression'
    };

    PlaceHolders = {
        ArrowParameterPlaceHolder: 'ArrowParameterPlaceHolder'
    };

    // Error messages should be identical to V8.
    Messages = {
        UnexpectedToken: 'Unexpected token %0',
        UnexpectedNumber: 'Unexpected number',
        UnexpectedString: 'Unexpected string',
        UnexpectedIdentifier: 'Unexpected identifier',
        UnexpectedReserved: 'Unexpected reserved word',
        UnexpectedTemplate: 'Unexpected quasi %0',
        UnexpectedEOS: 'Unexpected end of input',
        NewlineAfterThrow: 'Illegal newline after throw',
        InvalidRegExp: 'Invalid regular expression',
        UnterminatedRegExp: 'Invalid regular expression: missing /',
        InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
        InvalidLHSInForIn: 'Invalid left-hand side in for-in',
        InvalidLHSInForLoop: 'Invalid left-hand side in for-loop',
        MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
        NoCatchOrFinally: 'Missing catch or finally after try',
        UnknownLabel: 'Undefined label \'%0\'',
        Redeclaration: '%0 \'%1\' has already been declared',
        IllegalContinue: 'Illegal continue statement',
        IllegalBreak: 'Illegal break statement',
        IllegalReturn: 'Illegal return statement',
        StrictModeWith: 'Strict mode code may not include a with statement',
        StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
        StrictVarName: 'Variable name may not be eval or arguments in strict mode',
        StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
        StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
        StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
        StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
        StrictDelete: 'Delete of an unqualified identifier in strict mode.',
        StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
        StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
        StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
        StrictReservedWord: 'Use of future reserved word in strict mode',
        TemplateOctalLiteral: 'Octal literals are not allowed in template strings.',
        ParameterAfterRestParameter: 'Rest parameter must be last formal parameter',
        DefaultRestParameter: 'Unexpected token =',
        ObjectPatternAsRestParameter: 'Unexpected token {',
        DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals',
        ConstructorSpecialMethod: 'Class constructor may not be an accessor',
        DuplicateConstructor: 'A class may only have one constructor',
        StaticPrototype: 'Classes may not have static property named prototype',
        MissingFromClause: 'Unexpected token',
        NoAsAfterImportNamespace: 'Unexpected token',
        InvalidModuleSpecifier: 'Unexpected token',
        IllegalImportDeclaration: 'Unexpected token',
        IllegalExportDeclaration: 'Unexpected token',
        DuplicateBinding: 'Duplicate binding %0'
    };

    // See also tools/generate-unicode-regex.js.
    Regex = {
        // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierStart:
        NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]/,

        // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierPart:
        NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDD0-\uDDDA\uDE00-\uDE11\uDE13-\uDE37\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF01-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/
    };

    // Ensure the condition is true, otherwise throw an error.
    // This is only to have a better contract semantic, i.e. another safety net
    // to catch a logic error. The condition shall be fulfilled in normal case.
    // Do NOT use this to enforce a certain condition on any user input.

    function assert(condition, message) {
        /* istanbul ignore if */
        if (!condition) {
            throw new Error('ASSERT: ' + message);
        }
    }

    function isDecimalDigit(ch) {
        return (ch >= 0x30 && ch <= 0x39);   // 0..9
    }

    function isHexDigit(ch) {
        return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
    }

    function isOctalDigit(ch) {
        return '01234567'.indexOf(ch) >= 0;
    }

    function octalToDecimal(ch) {
        // \0 is not octal escape sequence
        var octal = (ch !== '0'), code = '01234567'.indexOf(ch);

        if (index < length && isOctalDigit(source[index])) {
            octal = true;
            code = code * 8 + '01234567'.indexOf(source[index++]);

            // 3 digits are only allowed when string starts
            // with 0, 1, 2, 3
            if ('0123'.indexOf(ch) >= 0 &&
                    index < length &&
                    isOctalDigit(source[index])) {
                code = code * 8 + '01234567'.indexOf(source[index++]);
            }
        }

        return {
            code: code,
            octal: octal
        };
    }

    // ECMA-262 11.2 White Space

    function isWhiteSpace(ch) {
        return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) ||
            (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0);
    }

    // ECMA-262 11.3 Line Terminators

    function isLineTerminator(ch) {
        return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029);
    }

    // ECMA-262 11.6 Identifier Names and Identifiers

    function fromCodePoint(cp) {
        return (cp < 0x10000) ? String.fromCharCode(cp) :
            String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) +
            String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023));
    }

    function isIdentifierStart(ch) {
        return (ch === 0x24) || (ch === 0x5F) ||  // $ (dollar) and _ (underscore)
            (ch >= 0x41 && ch <= 0x5A) ||         // A..Z
            (ch >= 0x61 && ch <= 0x7A) ||         // a..z
            (ch === 0x5C) ||                      // \ (backslash)
            ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)));
    }

    function isIdentifierPart(ch) {
        return (ch === 0x24) || (ch === 0x5F) ||  // $ (dollar) and _ (underscore)
            (ch >= 0x41 && ch <= 0x5A) ||         // A..Z
            (ch >= 0x61 && ch <= 0x7A) ||         // a..z
            (ch >= 0x30 && ch <= 0x39) ||         // 0..9
            (ch === 0x5C) ||                      // \ (backslash)
            ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)));
    }

    // ECMA-262 11.6.2.2 Future Reserved Words

    function isFutureReservedWord(id) {
        switch (id) {
        case 'enum':
        case 'export':
        case 'import':
        case 'super':
            return true;
        default:
            return false;
        }
    }

    function isStrictModeReservedWord(id) {
        switch (id) {
        case 'implements':
        case 'interface':
        case 'package':
        case 'private':
        case 'protected':
        case 'public':
        case 'static':
        case 'yield':
        case 'let':
            return true;
        default:
            return false;
        }
    }

    function isRestrictedWord(id) {
        return id === 'eval' || id === 'arguments';
    }

    // ECMA-262 11.6.2.1 Keywords

    function isKeyword(id) {
        switch (id.length) {
        case 2:
            return (id === 'if') || (id === 'in') || (id === 'do');
        case 3:
            return (id === 'var') || (id === 'for') || (id === 'new') ||
                (id === 'try') || (id === 'let');
        case 4:
            return (id === 'this') || (id === 'else') || (id === 'case') ||
                (id === 'void') || (id === 'with') || (id === 'enum');
        case 5:
            return (id === 'while') || (id === 'break') || (id === 'catch') ||
                (id === 'throw') || (id === 'const') || (id === 'yield') ||
                (id === 'class') || (id === 'super');
        case 6:
            return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
                (id === 'switch') || (id === 'export') || (id === 'import');
        case 7:
            return (id === 'default') || (id === 'finally') || (id === 'extends');
        case 8:
            return (id === 'function') || (id === 'continue') || (id === 'debugger');
        case 10:
            return (id === 'instanceof');
        default:
            return false;
        }
    }

    // ECMA-262 11.4 Comments

    function addComment(type, value, start, end, loc) {
        var comment;

        assert(typeof start === 'number', 'Comment must have valid position');

        state.lastCommentStart = start;

        comment = {
            type: type,
            value: value
        };
        if (extra.range) {
            comment.range = [start, end];
        }
        if (extra.loc) {
            comment.loc = loc;
        }
        extra.comments.push(comment);
        if (extra.attachComment) {
            extra.leadingComments.push(comment);
            extra.trailingComments.push(comment);
        }
        if (extra.tokenize) {
            comment.type = comment.type + 'Comment';
            if (extra.delegate) {
                comment = extra.delegate(comment);
            }
            extra.tokens.push(comment);
        }
    }

    function skipSingleLineComment(offset) {
        var start, loc, ch, comment;

        start = index - offset;
        loc = {
            start: {
                line: lineNumber,
                column: index - lineStart - offset
            }
        };

        while (index < length) {
            ch = source.charCodeAt(index);
            ++index;
            if (isLineTerminator(ch)) {
                hasLineTerminator = true;
                if (extra.comments) {
                    comment = source.slice(start + offset, index - 1);
                    loc.end = {
                        line: lineNumber,
                        column: index - lineStart - 1
                    };
                    addComment('Line', comment, start, index - 1, loc);
                }
                if (ch === 13 && source.charCodeAt(index) === 10) {
                    ++index;
                }
                ++lineNumber;
                lineStart = index;
                return;
            }
        }

        if (extra.comments) {
            comment = source.slice(start + offset, index);
            loc.end = {
                line: lineNumber,
                column: index - lineStart
            };
            addComment('Line', comment, start, index, loc);
        }
    }

    function skipMultiLineComment() {
        var start, loc, ch, comment;

        if (extra.comments) {
            start = index - 2;
            loc = {
                start: {
                    line: lineNumber,
                    column: index - lineStart - 2
                }
            };
        }

        while (index < length) {
            ch = source.charCodeAt(index);
            if (isLineTerminator(ch)) {
                if (ch === 0x0D && source.charCodeAt(index + 1) === 0x0A) {
                    ++index;
                }
                hasLineTerminator = true;
                ++lineNumber;
                ++index;
                lineStart = index;
            } else if (ch === 0x2A) {
                // Block comment ends with '*/'.
                if (source.charCodeAt(index + 1) === 0x2F) {
                    ++index;
                    ++index;
                    if (extra.comments) {
                        comment = source.slice(start + 2, index - 2);
                        loc.end = {
                            line: lineNumber,
                            column: index - lineStart
                        };
                        addComment('Block', comment, start, index, loc);
                    }
                    return;
                }
                ++index;
            } else {
                ++index;
            }
        }

        // Ran off the end of the file - the whole thing is a comment
        if (extra.comments) {
            loc.end = {
                line: lineNumber,
                column: index - lineStart
            };
            comment = source.slice(start + 2, index);
            addComment('Block', comment, start, index, loc);
        }
        tolerateUnexpectedToken();
    }

    function skipComment() {
        var ch, start;
        hasLineTerminator = false;

        start = (index === 0);
        while (index < length) {
            ch = source.charCodeAt(index);

            if (isWhiteSpace(ch)) {
                ++index;
            } else if (isLineTerminator(ch)) {
                hasLineTerminator = true;
                ++index;
                if (ch === 0x0D && source.charCodeAt(index) === 0x0A) {
                    ++index;
                }
                ++lineNumber;
                lineStart = index;
                start = true;
            } else if (ch === 0x2F) { // U+002F is '/'
                ch = source.charCodeAt(index + 1);
                if (ch === 0x2F) {
                    ++index;
                    ++index;
                    skipSingleLineComment(2);
                    start = true;
                } else if (ch === 0x2A) {  // U+002A is '*'
                    ++index;
                    ++index;
                    skipMultiLineComment();
                } else {
                    break;
                }
            } else if (start && ch === 0x2D) { // U+002D is '-'
                // U+003E is '>'
                if ((source.charCodeAt(index + 1) === 0x2D) && (source.charCodeAt(index + 2) === 0x3E)) {
                    // '-->' is a single-line comment
                    index += 3;
                    skipSingleLineComment(3);
                } else {
                    break;
                }
            } else if (ch === 0x3C) { // U+003C is '<'
                if (source.slice(index + 1, index + 4) === '!--') {
                    ++index; // `<`
                    ++index; // `!`
                    ++index; // `-`
                    ++index; // `-`
                    skipSingleLineComment(4);
                } else {
                    break;
                }
            } else {
                break;
            }
        }
    }

    function scanHexEscape(prefix) {
        var i, len, ch, code = 0;

        len = (prefix === 'u') ? 4 : 2;
        for (i = 0; i < len; ++i) {
            if (index < length && isHexDigit(source[index])) {
                ch = source[index++];
                code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
            } else {
                return '';
            }
        }
        return String.fromCharCode(code);
    }

    function scanUnicodeCodePointEscape() {
        var ch, code;

        ch = source[index];
        code = 0;

        // At least, one hex digit is required.
        if (ch === '}') {
            throwUnexpectedToken();
        }

        while (index < length) {
            ch = source[index++];
            if (!isHexDigit(ch)) {
                break;
            }
            code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
        }

        if (code > 0x10FFFF || ch !== '}') {
            throwUnexpectedToken();
        }

        return fromCodePoint(code);
    }

    function codePointAt(i) {
        var cp, first, second;

        cp = source.charCodeAt(i);
        if (cp >= 0xD800 && cp <= 0xDBFF) {
            second = source.charCodeAt(i + 1);
            if (second >= 0xDC00 && second <= 0xDFFF) {
                first = cp;
                cp = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
            }
        }

        return cp;
    }

    function getComplexIdentifier() {
        var cp, ch, id;

        cp = codePointAt(index);
        id = fromCodePoint(cp);
        index += id.length;

        // '\u' (U+005C, U+0075) denotes an escaped character.
        if (cp === 0x5C) {
            if (source.charCodeAt(index) !== 0x75) {
                throwUnexpectedToken();
            }
            ++index;
            if (source[index] === '{') {
                ++index;
                ch = scanUnicodeCodePointEscape();
            } else {
                ch = scanHexEscape('u');
                cp = ch.charCodeAt(0);
                if (!ch || ch === '\\' || !isIdentifierStart(cp)) {
                    throwUnexpectedToken();
                }
            }
            id = ch;
        }

        while (index < length) {
            cp = codePointAt(index);
            if (!isIdentifierPart(cp)) {
                break;
            }
            ch = fromCodePoint(cp);
            id += ch;
            index += ch.length;

            // '\u' (U+005C, U+0075) denotes an escaped character.
            if (cp === 0x5C) {
                id = id.substr(0, id.length - 1);
                if (source.charCodeAt(index) !== 0x75) {
                    throwUnexpectedToken();
                }
                ++index;
                if (source[index] === '{') {
                    ++index;
                    ch = scanUnicodeCodePointEscape();
                } else {
                    ch = scanHexEscape('u');
                    cp = ch.charCodeAt(0);
                    if (!ch || ch === '\\' || !isIdentifierPart(cp)) {
                        throwUnexpectedToken();
                    }
                }
                id += ch;
            }
        }

        return id;
    }

    function getIdentifier() {
        var start, ch;

        start = index++;
        while (index < length) {
            ch = source.charCodeAt(index);
            if (ch === 0x5C) {
                // Blackslash (U+005C) marks Unicode escape sequence.
                index = start;
                return getComplexIdentifier();
            } else if (ch >= 0xD800 && ch < 0xDFFF) {
                // Need to handle surrogate pairs.
                index = start;
                return getComplexIdentifier();
            }
            if (isIdentifierPart(ch)) {
                ++index;
            } else {
                break;
            }
        }

        return source.slice(start, index);
    }

    function scanIdentifier() {
        var start, id, type;

        start = index;

        // Backslash (U+005C) starts an escaped character.
        id = (source.charCodeAt(index) === 0x5C) ? getComplexIdentifier() : getIdentifier();

        // There is no keyword or literal with only one character.
        // Thus, it must be an identifier.
        if (id.length === 1) {
            type = Token.Identifier;
        } else if (isKeyword(id)) {
            type = Token.Keyword;
        } else if (id === 'null') {
            type = Token.NullLiteral;
        } else if (id === 'true' || id === 'false') {
            type = Token.BooleanLiteral;
        } else {
            type = Token.Identifier;
        }

        return {
            type: type,
            value: id,
            lineNumber: lineNumber,
            lineStart: lineStart,
            start: start,
            end: index
        };
    }


    // ECMA-262 11.7 Punctuators

    function scanPunctuator() {
        var token, str;

        token = {
            type: Token.Punctuator,
            value: '',
            lineNumber: lineNumber,
            lineStart: lineStart,
            start: index,
            end: index
        };

        // Check for most common single-character punctuators.
        str = source[index];
        switch (str) {

        case '(':
            if (extra.tokenize) {
                extra.openParenToken = extra.tokenValues.length;
            }
            ++index;
            break;

        case '{':
            if (extra.tokenize) {
                extra.openCurlyToken = extra.tokenValues.length;
            }
            state.curlyStack.push('{');
            ++index;
            break;

        case '.':
            ++index;
            if (source[index] === '.' && source[index + 1] === '.') {
                // Spread operator: ...
                index += 2;
                str = '...';
            }
            break;

        case '}':
            ++index;
            state.curlyStack.pop();
            break;
        case ')':
        case ';':
        case ',':
        case '[':
        case ']':
        case ':':
        case '?':
        case '~':
            ++index;
            break;

        default:
            // 4-character punctuator.
            str = source.substr(index, 4);
            if (str === '>>>=') {
                index += 4;
            } else {

                // 3-character punctuators.
                str = str.substr(0, 3);
                if (str === '===' || str === '!==' || str === '>>>' ||
                    str === '<<=' || str === '>>=') {
                    index += 3;
                } else {

                    // 2-character punctuators.
                    str = str.substr(0, 2);
                    if (str === '&&' || str === '||' || str === '==' || str === '!=' ||
                        str === '+=' || str === '-=' || str === '*=' || str === '/=' ||
                        str === '++' || str === '--' || str === '<<' || str === '>>' ||
                        str === '&=' || str === '|=' || str === '^=' || str === '%=' ||
                        str === '<=' || str === '>=' || str === '=>') {
                        index += 2;
                    } else {

                        // 1-character punctuators.
                        str = source[index];
                        if ('<>=!+-*%&|^/'.indexOf(str) >= 0) {
                            ++index;
                        }
                    }
                }
            }
        }

        if (index === token.start) {
            throwUnexpectedToken();
        }

        token.end = index;
        token.value = str;
        return token;
    }

    // ECMA-262 11.8.3 Numeric Literals

    function scanHexLiteral(start) {
        var number = '';

        while (index < length) {
            if (!isHexDigit(source[index])) {
                break;
            }
            number += source[index++];
        }

        if (number.length === 0) {
            throwUnexpectedToken();
        }

        if (isIdentifierStart(source.charCodeAt(index))) {
            throwUnexpectedToken();
        }

        return {
            type: Token.NumericLiteral,
            value: parseInt('0x' + number, 16),
            lineNumber: lineNumber,
            lineStart: lineStart,
            start: start,
            end: index
        };
    }

    function scanBinaryLiteral(start) {
        var ch, number;

        number = '';

        while (index < length) {
            ch = source[index];
            if (ch !== '0' && ch !== '1') {
                break;
            }
            number += source[index++];
        }

        if (number.length === 0) {
            // only 0b or 0B
            throwUnexpectedToken();
        }

        if (index < length) {
            ch = source.charCodeAt(index);
            /* istanbul ignore else */
            if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
                throwUnexpectedToken();
            }
        }

        return {
            type: Token.NumericLiteral,
            value: parseInt(number, 2),
            lineNumber: lineNumber,
            lineStart: lineStart,
            start: start,
            end: index
        };
    }

    function scanOctalLiteral(prefix, start) {
        var number, octal;

        if (isOctalDigit(prefix)) {
            octal = true;
            number = '0' + source[index++];
        } else {
            octal = false;
            ++index;
            number = '';
        }

        while (index < length) {
            if (!isOctalDigit(source[index])) {
                break;
            }
            number += source[index++];
        }

        if (!octal && number.length === 0) {
            // only 0o or 0O
            throwUnexpectedToken();
        }

        if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) {
            throwUnexpectedToken();
        }

        return {
            type: Token.NumericLiteral,
            value: parseInt(number, 8),
            octal: octal,
            lineNumber: lineNumber,
            lineStart: lineStart,
            start: start,
            end: index
        };
    }

    function isImplicitOctalLiteral() {
        var i, ch;

        // Implicit octal, unless there is a non-octal digit.
        // (Annex B.1.1 on Numeric Literals)
        for (i = index + 1; i < length; ++i) {
            ch = source[i];
            if (ch === '8' || ch === '9') {
                return false;
            }
            if (!isOctalDigit(ch)) {
                return true;
            }
        }

        return true;
    }

    function scanNumericLiteral() {
        var number, start, ch;

        ch = source[index];
        assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'),
            'Numeric literal must start with a decimal digit or a decimal point');

        start = index;
        number = '';
        if (ch !== '.') {
            number = source[index++];
            ch = source[index];

            // Hex number starts with '0x'.
            // Octal number starts with '0'.
            // Octal number in ES6 starts with '0o'.
            // Binary number in ES6 starts with '0b'.
            if (number === '0') {
                if (ch === 'x' || ch === 'X') {
                    ++index;
                    return scanHexLiteral(start);
                }
                if (ch === 'b' || ch === 'B') {
                    ++index;
                    return scanBinaryLiteral(start);
                }
                if (ch === 'o' || ch === 'O') {
                    return scanOctalLiteral(ch, start);
                }

                if (isOctalDigit(ch)) {
                    if (isImplicitOctalLiteral()) {
                        return scanOctalLiteral(ch, start);
                    }
                }
            }

            while (isDecimalDigit(source.charCodeAt(index))) {
                number += source[index++];
            }
            ch = source[index];
        }

        if (ch === '.') {
            number += source[index++];
            while (isDecimalDigit(source.charCodeAt(index))) {
                number += source[index++];
            }
            ch = source[index];
        }

        if (ch === 'e' || ch === 'E') {
            number += source[index++];

            ch = source[index];
            if (ch === '+' || ch === '-') {
                number += source[index++];
            }
            if (isDecimalDigit(source.charCodeAt(index))) {
                while (isDecimalDigit(source.charCodeAt(index))) {
                    number += source[index++];
                }
            } else {
                throwUnexpectedToken();
            }
        }

        if (isIdentifierStart(source.charCodeAt(index))) {
            throwUnexpectedToken();
        }

        return {
            type: Token.NumericLiteral,
            value: parseFloat(number),
            lineNumber: lineNumber,
            lineStart: lineStart,
            start: start,
            end: index
        };
    }

    // ECMA-262 11.8.4 String Literals

    function scanStringLiteral() {
        var str = '', quote, start, ch, unescaped, octToDec, octal = false;

        quote = source[index];
        assert((quote === '\'' || quote === '"'),
            'String literal must starts with a quote');

        start = index;
        ++index;

        while (index < length) {
            ch = source[index++];

            if (ch === quote) {
                quote = '';
                break;
            } else if (ch === '\\') {
                ch = source[index++];
                if (!ch || !isLineTerminator(ch.charCodeAt(0))) {
                    switch (ch) {
                    case 'u':
                    case 'x':
                        if (source[index] === '{') {
                            ++index;
                            str += scanUnicodeCodePointEscape();
                        } else {
                            unescaped = scanHexEscape(ch);
                            if (!unescaped) {
                                throw throwUnexpectedToken();
                            }
                            str += unescaped;
                        }
                        break;
                    case 'n':
                        str += '\n';
                        break;
                    case 'r':
                        str += '\r';
                        break;
                    case 't':
                        str += '\t';
                        break;
                    case 'b':
                        str += '\b';
                        break;
                    case 'f':
                        str += '\f';
                        break;
                    case 'v':
                        str += '\x0B';
                        break;
                    case '8':
                    case '9':
                        str += ch;
                        tolerateUnexpectedToken();
                        break;

                    default:
                        if (isOctalDigit(ch)) {
                            octToDec = octalToDecimal(ch);

                            octal = octToDec.octal || octal;
                            str += String.fromCharCode(octToDec.code);
                        } else {
                            str += ch;
                        }
                        break;
                    }
                } else {
                    ++lineNumber;
                    if (ch === '\r' && source[index] === '\n') {
                        ++index;
                    }
                    lineStart = index;
                }
            } else if (isLineTerminator(ch.charCodeAt(0))) {
                break;
            } else {
                str += ch;
            }
        }

        if (quote !== '') {
            index = start;
            throwUnexpectedToken();
        }

        return {
            type: Token.StringLiteral,
            value: str,
            octal: octal,
            lineNumber: startLineNumber,
            lineStart: startLineStart,
            start: start,
            end: index
        };
    }

    // ECMA-262 11.8.6 Template Literal Lexical Components

    function scanTemplate() {
        var cooked = '', ch, start, rawOffset, terminated, head, tail, restore, unescaped;

        terminated = false;
        tail = false;
        start = index;
        head = (source[index] === '`');
        rawOffset = 2;

        ++index;

        while (index < length) {
            ch = source[index++];
            if (ch === '`') {
                rawOffset = 1;
                tail = true;
                terminated = true;
                break;
            } else if (ch === '$') {
                if (source[index] === '{') {
                    state.curlyStack.push('${');
                    ++index;
                    terminated = true;
                    break;
                }
                cooked += ch;
            } else if (ch === '\\') {
                ch = source[index++];
                if (!isLineTerminator(ch.charCodeAt(0))) {
                    switch (ch) {
                    case 'n':
                        cooked += '\n';
                        break;
                    case 'r':
                        cooked += '\r';
                        break;
                    case 't':
                        cooked += '\t';
                        break;
                    case 'u':
                    case 'x':
                        if (source[index] === '{') {
                            ++index;
                            cooked += scanUnicodeCodePointEscape();
                        } else {
                            restore = index;
                            unescaped = scanHexEscape(ch);
                            if (unescaped) {
                                cooked += unescaped;
                            } else {
                                index = restore;
                                cooked += ch;
                            }
                        }
                        break;
                    case 'b':
                        cooked += '\b';
                        break;
                    case 'f':
                        cooked += '\f';
                        break;
                    case 'v':
                        cooked += '\v';
                        break;

                    default:
                        if (ch === '0') {
                            if (isDecimalDigit(source.charCodeAt(index))) {
                                // Illegal: \01 \02 and so on
                                throwError(Messages.TemplateOctalLiteral);
                            }
                            cooked += '\0';
                        } else if (isOctalDigit(ch)) {
                            // Illegal: \1 \2
                            throwError(Messages.TemplateOctalLiteral);
                        } else {
                            cooked += ch;
                        }
                        break;
                    }
                } else {
                    ++lineNumber;
                    if (ch === '\r' && source[index] === '\n') {
                        ++index;
                    }
                    lineStart = index;
                }
            } else if (isLineTerminator(ch.charCodeAt(0))) {
                ++lineNumber;
                if (ch === '\r' && source[index] === '\n') {
                    ++index;
                }
                lineStart = index;
                cooked += '\n';
            } else {
                cooked += ch;
            }
        }

        if (!terminated) {
            throwUnexpectedToken();
        }

        if (!head) {
            state.curlyStack.pop();
        }

        return {
            type: Token.Template,
            value: {
                cooked: cooked,
                raw: source.slice(start + 1, index - rawOffset)
            },
            head: head,
            tail: tail,
            lineNumber: lineNumber,
            lineStart: lineStart,
            start: start,
            end: index
        };
    }

    // ECMA-262 11.8.5 Regular Expression Literals

    function testRegExp(pattern, flags) {
        // The BMP character to use as a replacement for astral symbols when
        // translating an ES6 "u"-flagged pattern to an ES5-compatible
        // approximation.
        // Note: replacing with '\uFFFF' enables false positives in unlikely
        // scenarios. For example, `[\u{1044f}-\u{10440}]` is an invalid
        // pattern that would not be detected by this substitution.
        var astralSubstitute = '\uFFFF',
            tmp = pattern;

        if (flags.indexOf('u') >= 0) {
            tmp = tmp
                // Replace every Unicode escape sequence with the equivalent
                // BMP character or a constant ASCII code point in the case of
                // astral symbols. (See the above note on `astralSubstitute`
                // for more information.)
                .replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g, function ($0, $1, $2) {
                    var codePoint = parseInt($1 || $2, 16);
                    if (codePoint > 0x10FFFF) {
                        throwUnexpectedToken(null, Messages.InvalidRegExp);
                    }
                    if (codePoint <= 0xFFFF) {
                        return String.fromCharCode(codePoint);
                    }
                    return astralSubstitute;
                })
                // Replace each paired surrogate with a single ASCII symbol to
                // avoid throwing on regular expressions that are only valid in
                // combination with the "u" flag.
                .replace(
                    /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
                    astralSubstitute
                );
        }

        // First, detect invalid regular expressions.
        try {
            RegExp(tmp);
        } catch (e) {
            throwUnexpectedToken(null, Messages.InvalidRegExp);
        }

        // Return a regular expression object for this pattern-flag pair, or
        // `null` in case the current environment doesn't support the flags it
        // uses.
        try {
            return new RegExp(pattern, flags);
        } catch (exception) {
            /* istanbul ignore next */
            return null;
        }
    }

    function scanRegExpBody() {
        var ch, str, classMarker, terminated, body;

        ch = source[index];
        assert(ch === '/', 'Regular expression literal must start with a slash');
        str = source[index++];

        classMarker = false;
        terminated = false;
        while (index < length) {
            ch = source[index++];
            str += ch;
            if (ch === '\\') {
                ch = source[index++];
                // ECMA-262 7.8.5
                if (isLineTerminator(ch.charCodeAt(0))) {
                    throwUnexpectedToken(null, Messages.UnterminatedRegExp);
                }
                str += ch;
            } else if (isLineTerminator(ch.charCodeAt(0))) {
                throwUnexpectedToken(null, Messages.UnterminatedRegExp);
            } else if (classMarker) {
                if (ch === ']') {
                    classMarker = false;
                }
            } else {
                if (ch === '/') {
                    terminated = true;
                    break;
                } else if (ch === '[') {
                    classMarker = true;
                }
            }
        }

        if (!terminated) {
            throwUnexpectedToken(null, Messages.UnterminatedRegExp);
        }

        // Exclude leading and trailing slash.
        body = str.substr(1, str.length - 2);
        return {
            value: body,
            literal: str
        };
    }

    function scanRegExpFlags() {
        var ch, str, flags, restore;

        str = '';
        flags = '';
        while (index < length) {
            ch = source[index];
            if (!isIdentifierPart(ch.charCodeAt(0))) {
                break;
            }

            ++index;
            if (ch === '\\' && index < length) {
                ch = source[index];
                if (ch === 'u') {
                    ++index;
                    restore = index;
                    ch = scanHexEscape('u');
                    if (ch) {
                        flags += ch;
                        for (str += '\\u'; restore < index; ++restore) {
                            str += source[restore];
                        }
                    } else {
                        index = restore;
                        flags += 'u';
                        str += '\\u';
                    }
                    tolerateUnexpectedToken();
                } else {
                    str += '\\';
                    tolerateUnexpectedToken();
                }
            } else {
                flags += ch;
                str += ch;
            }
        }

        return {
            value: flags,
            literal: str
        };
    }

    function scanRegExp() {
        var start, body, flags, value;
        scanning = true;

        lookahead = null;
        skipComment();
        start = index;

        body = scanRegExpBody();
        flags = scanRegExpFlags();
        value = testRegExp(body.value, flags.value);
        scanning = false;
        if (extra.tokenize) {
            return {
                type: Token.RegularExpression,
                value: value,
                regex: {
                    pattern: body.value,
                    flags: flags.value
                },
                lineNumber: lineNumber,
                lineStart: lineStart,
                start: start,
                end: index
            };
        }

        return {
            literal: body.literal + flags.literal,
            value: value,
            regex: {
                pattern: body.value,
                flags: flags.value
            },
            start: start,
            end: index
        };
    }

    function collectRegex() {
        var pos, loc, regex, token;

        skipComment();

        pos = index;
        loc = {
            start: {
                line: lineNumber,
                column: index - lineStart
            }
        };

        regex = scanRegExp();

        loc.end = {
            line: lineNumber,
            column: index - lineStart
        };

        /* istanbul ignore next */
        if (!extra.tokenize) {
            // Pop the previous token, which is likely '/' or '/='
            if (extra.tokens.length > 0) {
                token = extra.tokens[extra.tokens.length - 1];
                if (token.range[0] === pos && token.type === 'Punctuator') {
                    if (token.value === '/' || token.value === '/=') {
                        extra.tokens.pop();
                    }
                }
            }

            extra.tokens.push({
                type: 'RegularExpression',
                value: regex.literal,
                regex: regex.regex,
                range: [pos, index],
                loc: loc
            });
        }

        return regex;
    }

    function isIdentifierName(token) {
        return token.type === Token.Identifier ||
            token.type === Token.Keyword ||
            token.type === Token.BooleanLiteral ||
            token.type === Token.NullLiteral;
    }

    // Using the following algorithm:
    // https://github.com/mozilla/sweet.js/wiki/design

    function advanceSlash() {
        var regex, previous, check;

        function testKeyword(value) {
            return value && (value.length > 1) && (value[0] >= 'a') && (value[0] <= 'z');
        }

        previous = extra.tokenValues[extra.tokenValues.length - 1];
        regex = (previous !== null);

        switch (previous) {
        case 'this':
        case ']':
            regex = false;
            break;

        case ')':
            check = extra.tokenValues[extra.openParenToken - 1];
            regex = (check === 'if' || check === 'while' || check === 'for' || check === 'with');
            break;

        case '}':
            // Dividing a function by anything makes little sense,
            // but we have to check for that.
            regex = false;
            if (testKeyword(extra.tokenValues[extra.openCurlyToken - 3])) {
                // Anonymous function, e.g. function(){} /42
                check = extra.tokenValues[extra.openCurlyToken - 4];
                regex = check ? (FnExprTokens.indexOf(check) < 0) : false;
            } else if (testKeyword(extra.tokenValues[extra.openCurlyToken - 4])) {
                // Named function, e.g. function f(){} /42/
                check = extra.tokenValues[extra.openCurlyToken - 5];
                regex = check ? (FnExprTokens.indexOf(check) < 0) : true;
            }
        }

        return regex ? collectRegex() : scanPunctuator();
    }

    function advance() {
        var cp, token;

        if (index >= length) {
            return {
                type: Token.EOF,
                lineNumber: lineNumber,
                lineStart: lineStart,
                start: index,
                end: index
            };
        }

        cp = source.charCodeAt(index);

        if (isIdentifierStart(cp)) {
            token = scanIdentifier();
            if (strict && isStrictModeReservedWord(token.value)) {
                token.type = Token.Keyword;
            }
            return token;
        }

        // Very common: ( and ) and ;
        if (cp === 0x28 || cp === 0x29 || cp === 0x3B) {
            return scanPunctuator();
        }

        // String literal starts with single quote (U+0027) or double quote (U+0022).
        if (cp === 0x27 || cp === 0x22) {
            return scanStringLiteral();
        }

        // Dot (.) U+002E can also start a floating-point number, hence the need
        // to check the next character.
        if (cp === 0x2E) {
            if (isDecimalDigit(source.charCodeAt(index + 1))) {
                return scanNumericLiteral();
            }
            return scanPunctuator();
        }

        if (isDecimalDigit(cp)) {
            return scanNumericLiteral();
        }

        // Slash (/) U+002F can also start a regex.
        if (extra.tokenize && cp === 0x2F) {
            return advanceSlash();
        }

        // Template literals start with ` (U+0060) for template head
        // or } (U+007D) for template middle or template tail.
        if (cp === 0x60 || (cp === 0x7D && state.curlyStack[state.curlyStack.length - 1] === '${')) {
            return scanTemplate();
        }

        // Possible identifier start in a surrogate pair.
        if (cp >= 0xD800 && cp < 0xDFFF) {
            cp = codePointAt(index);
            if (isIdentifierStart(cp)) {
                return scanIdentifier();
            }
        }

        return scanPunctuator();
    }

    function collectToken() {
        var loc, token, value, entry;

        loc = {
            start: {
                line: lineNumber,
                column: index - lineStart
            }
        };

        token = advance();
        loc.end = {
            line: lineNumber,
            column: index - lineStart
        };

        if (token.type !== Token.EOF) {
            value = source.slice(token.start, token.end);
            entry = {
                type: TokenName[token.type],
                value: value,
                range: [token.start, token.end],
                loc: loc
            };
            if (token.regex) {
                entry.regex = {
                    pattern: token.regex.pattern,
                    flags: token.regex.flags
                };
            }
            if (extra.tokenValues) {
                extra.tokenValues.push((entry.type === 'Punctuator' || entry.type === 'Keyword') ? entry.value : null);
            }
            if (extra.tokenize) {
                if (!extra.range) {
                    delete entry.range;
                }
                if (!extra.loc) {
                    delete entry.loc;
                }
                if (extra.delegate) {
                    entry = extra.delegate(entry);
                }
            }
            extra.tokens.push(entry);
        }

        return token;
    }

    function lex() {
        var token;
        scanning = true;

        lastIndex = index;
        lastLineNumber = lineNumber;
        lastLineStart = lineStart;

        skipComment();

        token = lookahead;

        startIndex = index;
        startLineNumber = lineNumber;
        startLineStart = lineStart;

        lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();
        scanning = false;
        return token;
    }

    function peek() {
        scanning = true;

        skipComment();

        lastIndex = index;
        lastLineNumber = lineNumber;
        lastLineStart = lineStart;

        startIndex = index;
        startLineNumber = lineNumber;
        startLineStart = lineStart;

        lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();
        scanning = false;
    }

    function Position() {
        this.line = startLineNumber;
        this.column = startIndex - startLineStart;
    }

    function SourceLocation() {
        this.start = new Position();
        this.end = null;
    }

    function WrappingSourceLocation(startToken) {
        this.start = {
            line: startToken.lineNumber,
            column: startToken.start - startToken.lineStart
        };
        this.end = null;
    }

    function Node() {
        if (extra.range) {
            this.range = [startIndex, 0];
        }
        if (extra.loc) {
            this.loc = new SourceLocation();
        }
    }

    function WrappingNode(startToken) {
        if (extra.range) {
            this.range = [startToken.start, 0];
        }
        if (extra.loc) {
            this.loc = new WrappingSourceLocation(startToken);
        }
    }

    WrappingNode.prototype = Node.prototype = {

        processComment: function () {
            var lastChild,
                innerComments,
                leadingComments,
                trailingComments,
                bottomRight = extra.bottomRightStack,
                i,
                comment,
                last = bottomRight[bottomRight.length - 1];

            if (this.type === Syntax.Program) {
                if (this.body.length > 0) {
                    return;
                }
            }
            /**
             * patch innnerComments for properties empty block
             * `function a() {/** comments **\/}`
             */

            if (this.type === Syntax.BlockStatement && this.body.length === 0) {
                innerComments = [];
                for (i = extra.leadingComments.length - 1; i >= 0; --i) {
                    comment = extra.leadingComments[i];
                    if (this.range[1] >= comment.range[1]) {
                        innerComments.unshift(comment);
                        extra.leadingComments.splice(i, 1);
                        extra.trailingComments.splice(i, 1);
                    }
                }
                if (innerComments.length) {
                    this.innerComments = innerComments;
                    //bottomRight.push(this);
                    return;
                }
            }

            if (extra.trailingComments.length > 0) {
                trailingComments = [];
                for (i = extra.trailingComments.length - 1; i >= 0; --i) {
                    comment = extra.trailingComments[i];
                    if (comment.range[0] >= this.range[1]) {
                        trailingComments.unshift(comment);
                        extra.trailingComments.splice(i, 1);
                    }
                }
                extra.trailingComments = [];
            } else {
                if (last && last.trailingComments && last.trailingComments[0].range[0] >= this.range[1]) {
                    trailingComments = last.trailingComments;
                    delete last.trailingComments;
                }
            }

            // Eating the stack.
            while (last && last.range[0] >= this.range[0]) {
                lastChild = bottomRight.pop();
                last = bottomRight[bottomRight.length - 1];
            }

            if (lastChild) {
                if (lastChild.leadingComments) {
                    leadingComments = [];
                    for (i = lastChild.leadingComments.length - 1; i >= 0; --i) {
                        comment = lastChild.leadingComments[i];
                        if (comment.range[1] <= this.range[0]) {
                            leadingComments.unshift(comment);
                            lastChild.leadingComments.splice(i, 1);
                        }
                    }

                    if (!lastChild.leadingComments.length) {
                        lastChild.leadingComments = undefined;
                    }
                }
            } else if (extra.leadingComments.length > 0) {
                leadingComments = [];
                for (i = extra.leadingComments.length - 1; i >= 0; --i) {
                    comment = extra.leadingComments[i];
                    if (comment.range[1] <= this.range[0]) {
                        leadingComments.unshift(comment);
                        extra.leadingComments.splice(i, 1);
                    }
                }
            }


            if (leadingComments && leadingComments.length > 0) {
                this.leadingComments = leadingComments;
            }
            if (trailingComments && trailingComments.length > 0) {
                this.trailingComments = trailingComments;
            }

            bottomRight.push(this);
        },

        finish: function () {
            if (extra.range) {
                this.range[1] = lastIndex;
            }
            if (extra.loc) {
                this.loc.end = {
                    line: lastLineNumber,
                    column: lastIndex - lastLineStart
                };
                if (extra.source) {
                    this.loc.source = extra.source;
                }
            }

            if (extra.attachComment) {
                this.processComment();
            }
        },

        finishArrayExpression: function (elements) {
            this.type = Syntax.ArrayExpression;
            this.elements = elements;
            this.finish();
            return this;
        },

        finishArrayPattern: function (elements) {
            this.type = Syntax.ArrayPattern;
            this.elements = elements;
            this.finish();
            return this;
        },

        finishArrowFunctionExpression: function (params, defaults, body, expression) {
            this.type = Syntax.ArrowFunctionExpression;
            this.id = null;
            this.params = params;
            this.defaults = defaults;
            this.body = body;
            this.generator = false;
            this.expression = expression;
            this.finish();
            return this;
        },

        finishAssignmentExpression: function (operator, left, right) {
            this.type = Syntax.AssignmentExpression;
            this.operator = operator;
            this.left = left;
            this.right = right;
            this.finish();
            return this;
        },

        finishAssignmentPattern: function (left, right) {
            this.type = Syntax.AssignmentPattern;
            this.left = left;
            this.right = right;
            this.finish();
            return this;
        },

        finishBinaryExpression: function (operator, left, right) {
            this.type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression : Syntax.BinaryExpression;
            this.operator = operator;
            this.left = left;
            this.right = right;
            this.finish();
            return this;
        },

        finishBlockStatement: function (body) {
            this.type = Syntax.BlockStatement;
            this.body = body;
            this.finish();
            return this;
        },

        finishBreakStatement: function (label) {
            this.type = Syntax.BreakStatement;
            this.label = label;
            this.finish();
            return this;
        },

        finishCallExpression: function (callee, args) {
            this.type = Syntax.CallExpression;
            this.callee = callee;
            this.arguments = args;
            this.finish();
            return this;
        },

        finishCatchClause: function (param, body) {
            this.type = Syntax.CatchClause;
            this.param = param;
            this.body = body;
            this.finish();
            return this;
        },

        finishClassBody: function (body) {
            this.type = Syntax.ClassBody;
            this.body = body;
            this.finish();
            return this;
        },

        finishClassDeclaration: function (id, superClass, body) {
            this.type = Syntax.ClassDeclaration;
            this.id = id;
            this.superClass = superClass;
            this.body = body;
            this.finish();
            return this;
        },

        finishClassExpression: function (id, superClass, body) {
            this.type = Syntax.ClassExpression;
            this.id = id;
            this.superClass = superClass;
            this.body = body;
            this.finish();
            return this;
        },

        finishConditionalExpression: function (test, consequent, alternate) {
            this.type = Syntax.ConditionalExpression;
            this.test = test;
            this.consequent = consequent;
            this.alternate = alternate;
            this.finish();
            return this;
        },

        finishContinueStatement: function (label) {
            this.type = Syntax.ContinueStatement;
            this.label = label;
            this.finish();
            return this;
        },

        finishDebuggerStatement: function () {
            this.type = Syntax.DebuggerStatement;
            this.finish();
            return this;
        },

        finishDoWhileStatement: function (body, test) {
            this.type = Syntax.DoWhileStatement;
            this.body = body;
            this.test = test;
            this.finish();
            return this;
        },

        finishEmptyStatement: function () {
            this.type = Syntax.EmptyStatement;
            this.finish();
            return this;
        },

        finishExpressionStatement: function (expression) {
            this.type = Syntax.ExpressionStatement;
            this.expression = expression;
            this.finish();
            return this;
        },

        finishForStatement: function (init, test, update, body) {
            this.type = Syntax.ForStatement;
            this.init = init;
            this.test = test;
            this.update = update;
            this.body = body;
            this.finish();
            return this;
        },

        finishForOfStatement: function (left, right, body) {
            this.type = Syntax.ForOfStatement;
            this.left = left;
            this.right = right;
            this.body = body;
            this.finish();
            return this;
        },

        finishForInStatement: function (left, right, body) {
            this.type = Syntax.ForInStatement;
            this.left = left;
            this.right = right;
            this.body = body;
            this.each = false;
            this.finish();
            return this;
        },

        finishFunctionDeclaration: function (id, params, defaults, body, generator) {
            this.type = Syntax.FunctionDeclaration;
            this.id = id;
            this.params = params;
            this.defaults = defaults;
            this.body = body;
            this.generator = generator;
            this.expression = false;
            this.finish();
            return this;
        },

        finishFunctionExpression: function (id, params, defaults, body, generator) {
            this.type = Syntax.FunctionExpression;
            this.id = id;
            this.params = params;
            this.defaults = defaults;
            this.body = body;
            this.generator = generator;
            this.expression = false;
            this.finish();
            return this;
        },

        finishIdentifier: function (name) {
            this.type = Syntax.Identifier;
            this.name = name;
            this.finish();
            return this;
        },

        finishIfStatement: function (test, consequent, alternate) {
            this.type = Syntax.IfStatement;
            this.test = test;
            this.consequent = consequent;
            this.alternate = alternate;
            this.finish();
            return this;
        },

        finishLabeledStatement: function (label, body) {
            this.type = Syntax.LabeledStatement;
            this.label = label;
            this.body = body;
            this.finish();
            return this;
        },

        finishLiteral: function (token) {
            this.type = Syntax.Literal;
            this.value = token.value;
            this.raw = source.slice(token.start, token.end);
            if (token.regex) {
                this.regex = token.regex;
            }
            this.finish();
            return this;
        },

        finishMemberExpression: function (accessor, object, property) {
            this.type = Syntax.MemberExpression;
            this.computed = accessor === '[';
            this.object = object;
            this.property = property;
            this.finish();
            return this;
        },

        finishMetaProperty: function (meta, property) {
            this.type = Syntax.MetaProperty;
            this.meta = meta;
            this.property = property;
            this.finish();
            return this;
        },

        finishNewExpression: function (callee, args) {
            this.type = Syntax.NewExpression;
            this.callee = callee;
            this.arguments = args;
            this.finish();
            return this;
        },

        finishObjectExpression: function (properties) {
            this.type = Syntax.ObjectExpression;
            this.properties = properties;
            this.finish();
            return this;
        },

        finishObjectPattern: function (properties) {
            this.type = Syntax.ObjectPattern;
            this.properties = properties;
            this.finish();
            return this;
        },

        finishPostfixExpression: function (operator, argument) {
            this.type = Syntax.UpdateExpression;
            this.operator = operator;
            this.argument = argument;
            this.prefix = false;
            this.finish();
            return this;
        },

        finishProgram: function (body, sourceType) {
            this.type = Syntax.Program;
            this.body = body;
            this.sourceType = sourceType;
            this.finish();
            return this;
        },

        finishProperty: function (kind, key, computed, value, method, shorthand) {
            this.type = Syntax.Property;
            this.key = key;
            this.computed = computed;
            this.value = value;
            this.kind = kind;
            this.method = method;
            this.shorthand = shorthand;
            this.finish();
            return this;
        },

        finishRestElement: function (argument) {
            this.type = Syntax.RestElement;
            this.argument = argument;
            this.finish();
            return this;
        },

        finishReturnStatement: function (argument) {
            this.type = Syntax.ReturnStatement;
            this.argument = argument;
            this.finish();
            return this;
        },

        finishSequenceExpression: function (expressions) {
            this.type = Syntax.SequenceExpression;
            this.expressions = expressions;
            this.finish();
            return this;
        },

        finishSpreadElement: function (argument) {
            this.type = Syntax.SpreadElement;
            this.argument = argument;
            this.finish();
            return this;
        },

        finishSwitchCase: function (test, consequent) {
            this.type = Syntax.SwitchCase;
            this.test = test;
            this.consequent = consequent;
            this.finish();
            return this;
        },

        finishSuper: function () {
            this.type = Syntax.Super;
            this.finish();
            return this;
        },

        finishSwitchStatement: function (discriminant, cases) {
            this.type = Syntax.SwitchStatement;
            this.discriminant = discriminant;
            this.cases = cases;
            this.finish();
            return this;
        },

        finishTaggedTemplateExpression: function (tag, quasi) {
            this.type = Syntax.TaggedTemplateExpression;
            this.tag = tag;
            this.quasi = quasi;
            this.finish();
            return this;
        },

        finishTemplateElement: function (value, tail) {
            this.type = Syntax.TemplateElement;
            this.value = value;
            this.tail = tail;
            this.finish();
            return this;
        },

        finishTemplateLiteral: function (quasis, expressions) {
            this.type = Syntax.TemplateLiteral;
            this.quasis = quasis;
            this.expressions = expressions;
            this.finish();
            return this;
        },

        finishThisExpression: function () {
            this.type = Syntax.ThisExpression;
            this.finish();
            return this;
        },

        finishThrowStatement: function (argument) {
            this.type = Syntax.ThrowStatement;
            this.argument = argument;
            this.finish();
            return this;
        },

        finishTryStatement: function (block, handler, finalizer) {
            this.type = Syntax.TryStatement;
            this.block = block;
            this.guardedHandlers = [];
            this.handlers = handler ? [handler] : [];
            this.handler = handler;
            this.finalizer = finalizer;
            this.finish();
            return this;
        },

        finishUnaryExpression: function (operator, argument) {
            this.type = (operator === '++' || operator === '--') ? Syntax.UpdateExpression : Syntax.UnaryExpression;
            this.operator = operator;
            this.argument = argument;
            this.prefix = true;
            this.finish();
            return this;
        },

        finishVariableDeclaration: function (declarations) {
            this.type = Syntax.VariableDeclaration;
            this.declarations = declarations;
            this.kind = 'var';
            this.finish();
            return this;
        },

        finishLexicalDeclaration: function (declarations, kind) {
            this.type = Syntax.VariableDeclaration;
            this.declarations = declarations;
            this.kind = kind;
            this.finish();
            return this;
        },

        finishVariableDeclarator: function (id, init) {
            this.type = Syntax.VariableDeclarator;
            this.id = id;
            this.init = init;
            this.finish();
            return this;
        },

        finishWhileStatement: function (test, body) {
            this.type = Syntax.WhileStatement;
            this.test = test;
            this.body = body;
            this.finish();
            return this;
        },

        finishWithStatement: function (object, body) {
            this.type = Syntax.WithStatement;
            this.object = object;
            this.body = body;
            this.finish();
            return this;
        },

        finishExportSpecifier: function (local, exported) {
            this.type = Syntax.ExportSpecifier;
            this.exported = exported || local;
            this.local = local;
            this.finish();
            return this;
        },

        finishImportDefaultSpecifier: function (local) {
            this.type = Syntax.ImportDefaultSpecifier;
            this.local = local;
            this.finish();
            return this;
        },

        finishImportNamespaceSpecifier: function (local) {
            this.type = Syntax.ImportNamespaceSpecifier;
            this.local = local;
            this.finish();
            return this;
        },

        finishExportNamedDeclaration: function (declaration, specifiers, src) {
            this.type = Syntax.ExportNamedDeclaration;
            this.declaration = declaration;
            this.specifiers = specifiers;
            this.source = src;
            this.finish();
            return this;
        },

        finishExportDefaultDeclaration: function (declaration) {
            this.type = Syntax.ExportDefaultDeclaration;
            this.declaration = declaration;
            this.finish();
            return this;
        },

        finishExportAllDeclaration: function (src) {
            this.type = Syntax.ExportAllDeclaration;
            this.source = src;
            this.finish();
            return this;
        },

        finishImportSpecifier: function (local, imported) {
            this.type = Syntax.ImportSpecifier;
            this.local = local || imported;
            this.imported = imported;
            this.finish();
            return this;
        },

        finishImportDeclaration: function (specifiers, src) {
            this.type = Syntax.ImportDeclaration;
            this.specifiers = specifiers;
            this.source = src;
            this.finish();
            return this;
        },

        finishYieldExpression: function (argument, delegate) {
            this.type = Syntax.YieldExpression;
            this.argument = argument;
            this.delegate = delegate;
            this.finish();
            return this;
        }
    };


    function recordError(error) {
        var e, existing;

        for (e = 0; e < extra.errors.length; e++) {
            existing = extra.errors[e];
            // Prevent duplicated error.
            /* istanbul ignore next */
            if (existing.index === error.index && existing.message === error.message) {
                return;
            }
        }

        extra.errors.push(error);
    }

    function constructError(msg, column) {
        var error = new Error(msg);
        try {
            throw error;
        } catch (base) {
            /* istanbul ignore else */
            if (Object.create && Object.defineProperty) {
                error = Object.create(base);
                Object.defineProperty(error, 'column', { value: column });
            }
        } finally {
            return error;
        }
    }

    function createError(line, pos, description) {
        var msg, column, error;

        msg = 'Line ' + line + ': ' + description;
        column = pos - (scanning ? lineStart : lastLineStart) + 1;
        error = constructError(msg, column);
        error.lineNumber = line;
        error.description = description;
        error.index = pos;
        return error;
    }

    // Throw an exception

    function throwError(messageFormat) {
        var args, msg;

        args = Array.prototype.slice.call(arguments, 1);
        msg = messageFormat.replace(/%(\d)/g,
            function (whole, idx) {
                assert(idx < args.length, 'Message reference must be in range');
                return args[idx];
            }
        );

        throw createError(lastLineNumber, lastIndex, msg);
    }

    function tolerateError(messageFormat) {
        var args, msg, error;

        args = Array.prototype.slice.call(arguments, 1);
        /* istanbul ignore next */
        msg = messageFormat.replace(/%(\d)/g,
            function (whole, idx) {
                assert(idx < args.length, 'Message reference must be in range');
                return args[idx];
            }
        );

        error = createError(lineNumber, lastIndex, msg);
        if (extra.errors) {
            recordError(error);
        } else {
            throw error;
        }
    }

    // Throw an exception because of the token.

    function unexpectedTokenError(token, message) {
        var value, msg = message || Messages.UnexpectedToken;

        if (token) {
            if (!message) {
                msg = (token.type === Token.EOF) ? Messages.UnexpectedEOS :
                    (token.type === Token.Identifier) ? Messages.UnexpectedIdentifier :
                    (token.type === Token.NumericLiteral) ? Messages.UnexpectedNumber :
                    (token.type === Token.StringLiteral) ? Messages.UnexpectedString :
                    (token.type === Token.Template) ? Messages.UnexpectedTemplate :
                    Messages.UnexpectedToken;

                if (token.type === Token.Keyword) {
                    if (isFutureReservedWord(token.value)) {
                        msg = Messages.UnexpectedReserved;
                    } else if (strict && isStrictModeReservedWord(token.value)) {
                        msg = Messages.StrictReservedWord;
                    }
                }
            }

            value = (token.type === Token.Template) ? token.value.raw : token.value;
        } else {
            value = 'ILLEGAL';
        }

        msg = msg.replace('%0', value);

        return (token && typeof token.lineNumber === 'number') ?
            createError(token.lineNumber, token.start, msg) :
            createError(scanning ? lineNumber : lastLineNumber, scanning ? index : lastIndex, msg);
    }

    function throwUnexpectedToken(token, message) {
        throw unexpectedTokenError(token, message);
    }

    function tolerateUnexpectedToken(token, message) {
        var error = unexpectedTokenError(token, message);
        if (extra.errors) {
            recordError(error);
        } else {
            throw error;
        }
    }

    // Expect the next token to match the specified punctuator.
    // If not, an exception will be thrown.

    function expect(value) {
        var token = lex();
        if (token.type !== Token.Punctuator || token.value !== value) {
            throwUnexpectedToken(token);
        }
    }

    /**
     * @name expectCommaSeparator
     * @description Quietly expect a comma when in tolerant mode, otherwise delegates
     * to <code>expect(value)</code>
     * @since 2.0
     */
    function expectCommaSeparator() {
        var token;

        if (extra.errors) {
            token = lookahead;
            if (token.type === Token.Punctuator && token.value === ',') {
                lex();
            } else if (token.type === Token.Punctuator && token.value === ';') {
                lex();
                tolerateUnexpectedToken(token);
            } else {
                tolerateUnexpectedToken(token, Messages.UnexpectedToken);
            }
        } else {
            expect(',');
        }
    }

    // Expect the next token to match the specified keyword.
    // If not, an exception will be thrown.

    function expectKeyword(keyword) {
        var token = lex();
        if (token.type !== Token.Keyword || token.value !== keyword) {
            throwUnexpectedToken(token);
        }
    }

    // Return true if the next token matches the specified punctuator.

    function match(value) {
        return lookahead.type === Token.Punctuator && lookahead.value === value;
    }

    // Return true if the next token matches the specified keyword

    function matchKeyword(keyword) {
        return lookahead.type === Token.Keyword && lookahead.value === keyword;
    }

    // Return true if the next token matches the specified contextual keyword
    // (where an identifier is sometimes a keyword depending on the context)

    function matchContextualKeyword(keyword) {
        return lookahead.type === Token.Identifier && lookahead.value === keyword;
    }

    // Return true if the next token is an assignment operator

    function matchAssign() {
        var op;

        if (lookahead.type !== Token.Punctuator) {
            return false;
        }
        op = lookahead.value;
        return op === '=' ||
            op === '*=' ||
            op === '/=' ||
            op === '%=' ||
            op === '+=' ||
            op === '-=' ||
            op === '<<=' ||
            op === '>>=' ||
            op === '>>>=' ||
            op === '&=' ||
            op === '^=' ||
            op === '|=';
    }

    function consumeSemicolon() {
        // Catch the very common case first: immediately a semicolon (U+003B).
        if (source.charCodeAt(startIndex) === 0x3B || match(';')) {
            lex();
            return;
        }

        if (hasLineTerminator) {
            return;
        }

        // FIXME(ikarienator): this is seemingly an issue in the previous location info convention.
        lastIndex = startIndex;
        lastLineNumber = startLineNumber;
        lastLineStart = startLineStart;

        if (lookahead.type !== Token.EOF && !match('}')) {
            throwUnexpectedToken(lookahead);
        }
    }

    // Cover grammar support.
    //
    // When an assignment expression position starts with an left parenthesis, the determination of the type
    // of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead)
    // or the first comma. This situation also defers the determination of all the expressions nested in the pair.
    //
    // There are three productions that can be parsed in a parentheses pair that needs to be determined
    // after the outermost pair is closed. They are:
    //
    //   1. AssignmentExpression
    //   2. BindingElements
    //   3. AssignmentTargets
    //
    // In order to avoid exponential backtracking, we use two flags to denote if the production can be
    // binding element or assignment target.
    //
    // The three productions have the relationship:
    //
    //   BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression
    //
    // with a single exception that CoverInitializedName when used directly in an Expression, generates
    // an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the
    // first usage of CoverInitializedName and report it when we reached the end of the parentheses pair.
    //
    // isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not
    // effect the current flags. This means the production the parser parses is only used as an expression. Therefore
    // the CoverInitializedName check is conducted.
    //
    // inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates
    // the flags outside of the parser. This means the production the parser parses is used as a part of a potential
    // pattern. The CoverInitializedName check is deferred.
    function isolateCoverGrammar(parser) {
        var oldIsBindingElement = isBindingElement,
            oldIsAssignmentTarget = isAssignmentTarget,
            oldFirstCoverInitializedNameError = firstCoverInitializedNameError,
            result;
        isBindingElement = true;
        isAssignmentTarget = true;
        firstCoverInitializedNameError = null;
        result = parser();
        if (firstCoverInitializedNameError !== null) {
            throwUnexpectedToken(firstCoverInitializedNameError);
        }
        isBindingElement = oldIsBindingElement;
        isAssignmentTarget = oldIsAssignmentTarget;
        firstCoverInitializedNameError = oldFirstCoverInitializedNameError;
        return result;
    }

    function inheritCoverGrammar(parser) {
        var oldIsBindingElement = isBindingElement,
            oldIsAssignmentTarget = isAssignmentTarget,
            oldFirstCoverInitializedNameError = firstCoverInitializedNameError,
            result;
        isBindingElement = true;
        isAssignmentTarget = true;
        firstCoverInitializedNameError = null;
        result = parser();
        isBindingElement = isBindingElement && oldIsBindingElement;
        isAssignmentTarget = isAssignmentTarget && oldIsAssignmentTarget;
        firstCoverInitializedNameError = oldFirstCoverInitializedNameError || firstCoverInitializedNameError;
        return result;
    }

    // ECMA-262 13.3.3 Destructuring Binding Patterns

    function parseArrayPattern(params, kind) {
        var node = new Node(), elements = [], rest, restNode;
        expect('[');

        while (!match(']')) {
            if (match(',')) {
                lex();
                elements.push(null);
            } else {
                if (match('...')) {
                    restNode = new Node();
                    lex();
                    params.push(lookahead);
                    rest = parseVariableIdentifier(kind);
                    elements.push(restNode.finishRestElement(rest));
                    break;
                } else {
                    elements.push(parsePatternWithDefault(params, kind));
                }
                if (!match(']')) {
                    expect(',');
                }
            }

        }

        expect(']');

        return node.finishArrayPattern(elements);
    }

    function parsePropertyPattern(params, kind) {
        var node = new Node(), key, keyToken, computed = match('['), init;
        if (lookahead.type === Token.Identifier) {
            keyToken = lookahead;
            key = parseVariableIdentifier();
            if (match('=')) {
                params.push(keyToken);
                lex();
                init = parseAssignmentExpression();

                return node.finishProperty(
                    'init', key, false,
                    new WrappingNode(keyToken).finishAssignmentPattern(key, init), false, true);
            } else if (!match(':')) {
                params.push(keyToken);
                return node.finishProperty('init', key, false, key, false, true);
            }
        } else {
            key = parseObjectPropertyKey();
        }
        expect(':');
        init = parsePatternWithDefault(params, kind);
        return node.finishProperty('init', key, computed, init, false, false);
    }

    function parseObjectPattern(params, kind) {
        var node = new Node(), properties = [];

        expect('{');

        while (!match('}')) {
            properties.push(parsePropertyPattern(params, kind));
            if (!match('}')) {
                expect(',');
            }
        }

        lex();

        return node.finishObjectPattern(properties);
    }

    function parsePattern(params, kind) {
        if (match('[')) {
            return parseArrayPattern(params, kind);
        } else if (match('{')) {
            return parseObjectPattern(params, kind);
        } else if (matchKeyword('let')) {
            if (kind === 'const' || kind === 'let') {
                tolerateUnexpectedToken(lookahead, Messages.UnexpectedToken);
            }
        }

        params.push(lookahead);
        return parseVariableIdentifier(kind);
    }

    function parsePatternWithDefault(params, kind) {
        var startToken = lookahead, pattern, previousAllowYield, right;
        pattern = parsePattern(params, kind);
        if (match('=')) {
            lex();
            previousAllowYield = state.allowYield;
            state.allowYield = true;
            right = isolateCoverGrammar(parseAssignmentExpression);
            state.allowYield = previousAllowYield;
            pattern = new WrappingNode(startToken).finishAssignmentPattern(pattern, right);
        }
        return pattern;
    }

    // ECMA-262 12.2.5 Array Initializer

    function parseArrayInitializer() {
        var elements = [], node = new Node(), restSpread;

        expect('[');

        while (!match(']')) {
            if (match(',')) {
                lex();
                elements.push(null);
            } else if (match('...')) {
                restSpread = new Node();
                lex();
                restSpread.finishSpreadElement(inheritCoverGrammar(parseAssignmentExpression));

                if (!match(']')) {
                    isAssignmentTarget = isBindingElement = false;
                    expect(',');
                }
                elements.push(restSpread);
            } else {
                elements.push(inheritCoverGrammar(parseAssignmentExpression));

                if (!match(']')) {
                    expect(',');
                }
            }
        }

        lex();

        return node.finishArrayExpression(elements);
    }

    // ECMA-262 12.2.6 Object Initializer

    function parsePropertyFunction(node, paramInfo, isGenerator) {
        var previousStrict, body;

        isAssignmentTarget = isBindingElement = false;

        previousStrict = strict;
        body = isolateCoverGrammar(parseFunctionSourceElements);

        if (strict && paramInfo.firstRestricted) {
            tolerateUnexpectedToken(paramInfo.firstRestricted, paramInfo.message);
        }
        if (strict && paramInfo.stricted) {
            tolerateUnexpectedToken(paramInfo.stricted, paramInfo.message);
        }

        strict = previousStrict;
        return node.finishFunctionExpression(null, paramInfo.params, paramInfo.defaults, body, isGenerator);
    }

    function parsePropertyMethodFunction() {
        var params, method, node = new Node(),
            previousAllowYield = state.allowYield;

        state.allowYield = false;
        params = parseParams();
        state.allowYield = previousAllowYield;

        state.allowYield = false;
        method = parsePropertyFunction(node, params, false);
        state.allowYield = previousAllowYield;

        return method;
    }

    function parseObjectPropertyKey() {
        var token, node = new Node(), expr;

        token = lex();

        // Note: This function is called only from parseObjectProperty(), where
        // EOF and Punctuator tokens are already filtered out.

        switch (token.type) {
        case Token.StringLiteral:
        case Token.NumericLiteral:
            if (strict && token.octal) {
                tolerateUnexpectedToken(token, Messages.StrictOctalLiteral);
            }
            return node.finishLiteral(token);
        case Token.Identifier:
        case Token.BooleanLiteral:
        case Token.NullLiteral:
        case Token.Keyword:
            return node.finishIdentifier(token.value);
        case Token.Punctuator:
            if (token.value === '[') {
                expr = isolateCoverGrammar(parseAssignmentExpression);
                expect(']');
                return expr;
            }
            break;
        }
        throwUnexpectedToken(token);
    }

    function lookaheadPropertyName() {
        switch (lookahead.type) {
        case Token.Identifier:
        case Token.StringLiteral:
        case Token.BooleanLiteral:
        case Token.NullLiteral:
        case Token.NumericLiteral:
        case Token.Keyword:
            return true;
        case Token.Punctuator:
            return lookahead.value === '[';
        }
        return false;
    }

    // This function is to try to parse a MethodDefinition as defined in 14.3. But in the case of object literals,
    // it might be called at a position where there is in fact a short hand identifier pattern or a data property.
    // This can only be determined after we consumed up to the left parentheses.
    //
    // In order to avoid back tracking, it returns `null` if the position is not a MethodDefinition and the caller
    // is responsible to visit other options.
    function tryParseMethodDefinition(token, key, computed, node) {
        var value, options, methodNode, params,
            previousAllowYield = state.allowYield;

        if (token.type === Token.Identifier) {
            // check for `get` and `set`;

            if (token.value === 'get' && lookaheadPropertyName()) {
                computed = match('[');
                key = parseObjectPropertyKey();
                methodNode = new Node();
                expect('(');
                expect(')');

                state.allowYield = false;
                value = parsePropertyFunction(methodNode, {
                    params: [],
                    defaults: [],
                    stricted: null,
                    firstRestricted: null,
                    message: null
                }, false);
                state.allowYield = previousAllowYield;

                return node.finishProperty('get', key, computed, value, false, false);
            } else if (token.value === 'set' && lookaheadPropertyName()) {
                computed = match('[');
                key = parseObjectPropertyKey();
                methodNode = new Node();
                expect('(');

                options = {
                    params: [],
                    defaultCount: 0,
                    defaults: [],
                    firstRestricted: null,
                    paramSet: {}
                };
                if (match(')')) {
                    tolerateUnexpectedToken(lookahead);
                } else {
                    state.allowYield = false;
                    parseParam(options);
                    state.allowYield = previousAllowYield;
                    if (options.defaultCount === 0) {
                        options.defaults = [];
                    }
                }
                expect(')');

                state.allowYield = false;
                value = parsePropertyFunction(methodNode, options, false);
                state.allowYield = previousAllowYield;

                return node.finishProperty('set', key, computed, value, false, false);
            }
        } else if (token.type === Token.Punctuator && token.value === '*' && lookaheadPropertyName()) {
            computed = match('[');
            key = parseObjectPropertyKey();
            methodNode = new Node();

            state.allowYield = true;
            params = parseParams();
            state.allowYield = previousAllowYield;

            state.allowYield = false;
            value = parsePropertyFunction(methodNode, params, true);
            state.allowYield = previousAllowYield;

            return node.finishProperty('init', key, computed, value, true, false);
        }

        if (key && match('(')) {
            value = parsePropertyMethodFunction();
            return node.finishProperty('init', key, computed, value, true, false);
        }

        // Not a MethodDefinition.
        return null;
    }

    function parseObjectProperty(hasProto) {
        var token = lookahead, node = new Node(), computed, key, maybeMethod, proto, value;

        computed = match('[');
        if (match('*')) {
            lex();
        } else {
            key = parseObjectPropertyKey();
        }
        maybeMethod = tryParseMethodDefinition(token, key, computed, node);
        if (maybeMethod) {
            return maybeMethod;
        }

        if (!key) {
            throwUnexpectedToken(lookahead);
        }

        // Check for duplicated __proto__
        if (!computed) {
            proto = (key.type === Syntax.Identifier && key.name === '__proto__') ||
                (key.type === Syntax.Literal && key.value === '__proto__');
            if (hasProto.value && proto) {
                tolerateError(Messages.DuplicateProtoProperty);
            }
            hasProto.value |= proto;
        }

        if (match(':')) {
            lex();
            value = inheritCoverGrammar(parseAssignmentExpression);
            return node.finishProperty('init', key, computed, value, false, false);
        }

        if (token.type === Token.Identifier) {
            if (match('=')) {
                firstCoverInitializedNameError = lookahead;
                lex();
                value = isolateCoverGrammar(parseAssignmentExpression);
                return node.finishProperty('init', key, computed,
                    new WrappingNode(token).finishAssignmentPattern(key, value), false, true);
            }
            return node.finishProperty('init', key, computed, key, false, true);
        }

        throwUnexpectedToken(lookahead);
    }

    function parseObjectInitializer() {
        var properties = [], hasProto = {value: false}, node = new Node();

        expect('{');

        while (!match('}')) {
            properties.push(parseObjectProperty(hasProto));

            if (!match('}')) {
                expectCommaSeparator();
            }
        }

        expect('}');

        return node.finishObjectExpression(properties);
    }

    function reinterpretExpressionAsPattern(expr) {
        var i;
        switch (expr.type) {
        case Syntax.Identifier:
        case Syntax.MemberExpression:
        case Syntax.RestElement:
        case Syntax.AssignmentPattern:
            break;
        case Syntax.SpreadElement:
            expr.type = Syntax.RestElement;
            reinterpretExpressionAsPattern(expr.argument);
            break;
        case Syntax.ArrayExpression:
            expr.type = Syntax.ArrayPattern;
            for (i = 0; i < expr.elements.length; i++) {
                if (expr.elements[i] !== null) {
                    reinterpretExpressionAsPattern(expr.elements[i]);
                }
            }
            break;
        case Syntax.ObjectExpression:
            expr.type = Syntax.ObjectPattern;
            for (i = 0; i < expr.properties.length; i++) {
                reinterpretExpressionAsPattern(expr.properties[i].value);
            }
            break;
        case Syntax.AssignmentExpression:
            expr.type = Syntax.AssignmentPattern;
            reinterpretExpressionAsPattern(expr.left);
            break;
        default:
            // Allow other node type for tolerant parsing.
            break;
        }
    }

    // ECMA-262 12.2.9 Template Literals

    function parseTemplateElement(option) {
        var node, token;

        if (lookahead.type !== Token.Template || (option.head && !lookahead.head)) {
            throwUnexpectedToken();
        }

        node = new Node();
        token = lex();

        return node.finishTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail);
    }

    function parseTemplateLiteral() {
        var quasi, quasis, expressions, node = new Node();

        quasi = parseTemplateElement({ head: true });
        quasis = [quasi];
        expressions = [];

        while (!quasi.tail) {
            expressions.push(parseExpression());
            quasi = parseTemplateElement({ head: false });
            quasis.push(quasi);
        }

        return node.finishTemplateLiteral(quasis, expressions);
    }

    // ECMA-262 12.2.10 The Grouping Operator

    function parseGroupExpression() {
        var expr, expressions, startToken, i, params = [];

        expect('(');

        if (match(')')) {
            lex();
            if (!match('=>')) {
                expect('=>');
            }
            return {
                type: PlaceHolders.ArrowParameterPlaceHolder,
                params: [],
                rawParams: []
            };
        }

        startToken = lookahead;
        if (match('...')) {
            expr = parseRestElement(params);
            expect(')');
            if (!match('=>')) {
                expect('=>');
            }
            return {
                type: PlaceHolders.ArrowParameterPlaceHolder,
                params: [expr]
            };
        }

        isBindingElement = true;
        expr = inheritCoverGrammar(parseAssignmentExpression);

        if (match(',')) {
            isAssignmentTarget = false;
            expressions = [expr];

            while (startIndex < length) {
                if (!match(',')) {
                    break;
                }
                lex();

                if (match('...')) {
                    if (!isBindingElement) {
                        throwUnexpectedToken(lookahead);
                    }
                    expressions.push(parseRestElement(params));
                    expect(')');
                    if (!match('=>')) {
                        expect('=>');
                    }
                    isBindingElement = false;
                    for (i = 0; i < expressions.length; i++) {
                        reinterpretExpressionAsPattern(expressions[i]);
                    }
                    return {
                        type: PlaceHolders.ArrowParameterPlaceHolder,
                        params: expressions
                    };
                }

                expressions.push(inheritCoverGrammar(parseAssignmentExpression));
            }

            expr = new WrappingNode(startToken).finishSequenceExpression(expressions);
        }


        expect(')');

        if (match('=>')) {
            if (expr.type === Syntax.Identifier && expr.name === 'yield') {
                return {
                    type: PlaceHolders.ArrowParameterPlaceHolder,
                    params: [expr]
                };
            }

            if (!isBindingElement) {
                throwUnexpectedToken(lookahead);
            }

            if (expr.type === Syntax.SequenceExpression) {
                for (i = 0; i < expr.expressions.length; i++) {
                    reinterpretExpressionAsPattern(expr.expressions[i]);
                }
            } else {
                reinterpretExpressionAsPattern(expr);
            }

            expr = {
                type: PlaceHolders.ArrowParameterPlaceHolder,
                params: expr.type === Syntax.SequenceExpression ? expr.expressions : [expr]
            };
        }
        isBindingElement = false;
        return expr;
    }


    // ECMA-262 12.2 Primary Expressions

    function parsePrimaryExpression() {
        var type, token, expr, node;

        if (match('(')) {
            isBindingElement = false;
            return inheritCoverGrammar(parseGroupExpression);
        }

        if (match('[')) {
            return inheritCoverGrammar(parseArrayInitializer);
        }

        if (match('{')) {
            return inheritCoverGrammar(parseObjectInitializer);
        }

        type = lookahead.type;
        node = new Node();

        if (type === Token.Identifier) {
            if (state.sourceType === 'module' && lookahead.value === 'await') {
                tolerateUnexpectedToken(lookahead);
            }
            expr = node.finishIdentifier(lex().value);
        } else if (type === Token.StringLiteral || type === Token.NumericLiteral) {
            isAssignmentTarget = isBindingElement = false;
            if (strict && lookahead.octal) {
                tolerateUnexpectedToken(lookahead, Messages.StrictOctalLiteral);
            }
            expr = node.finishLiteral(lex());
        } else if (type === Token.Keyword) {
            if (!strict && state.allowYield && matchKeyword('yield')) {
                return parseNonComputedProperty();
            }
            if (!strict && matchKeyword('let')) {
                return node.finishIdentifier(lex().value);
            }
            isAssignmentTarget = isBindingElement = false;
            if (matchKeyword('function')) {
                return parseFunctionExpression();
            }
            if (matchKeyword('this')) {
                lex();
                return node.finishThisExpression();
            }
            if (matchKeyword('class')) {
                return parseClassExpression();
            }
            throwUnexpectedToken(lex());
        } else if (type === Token.BooleanLiteral) {
            isAssignmentTarget = isBindingElement = false;
            token = lex();
            token.value = (token.value === 'true');
            expr = node.finishLiteral(token);
        } else if (type === Token.NullLiteral) {
            isAssignmentTarget = isBindingElement = false;
            token = lex();
            token.value = null;
            expr = node.finishLiteral(token);
        } else if (match('/') || match('/=')) {
            isAssignmentTarget = isBindingElement = false;
            index = startIndex;

            if (typeof extra.tokens !== 'undefined') {
                token = collectRegex();
            } else {
                token = scanRegExp();
            }
            lex();
            expr = node.finishLiteral(token);
        } else if (type === Token.Template) {
            expr = parseTemplateLiteral();
        } else {
            throwUnexpectedToken(lex());
        }

        return expr;
    }

    // ECMA-262 12.3 Left-Hand-Side Expressions

    function parseArguments() {
        var args = [], expr;

        expect('(');

        if (!match(')')) {
            while (startIndex < length) {
                if (match('...')) {
                    expr = new Node();
                    lex();
                    expr.finishSpreadElement(isolateCoverGrammar(parseAssignmentExpression));
                } else {
                    expr = isolateCoverGrammar(parseAssignmentExpression);
                }
                args.push(expr);
                if (match(')')) {
                    break;
                }
                expectCommaSeparator();
            }
        }

        expect(')');

        return args;
    }

    function parseNonComputedProperty() {
        var token, node = new Node();

        token = lex();

        if (!isIdentifierName(token)) {
            throwUnexpectedToken(token);
        }

        return node.finishIdentifier(token.value);
    }

    function parseNonComputedMember() {
        expect('.');

        return parseNonComputedProperty();
    }

    function parseComputedMember() {
        var expr;

        expect('[');

        expr = isolateCoverGrammar(parseExpression);

        expect(']');

        return expr;
    }

    // ECMA-262 12.3.3 The new Operator

    function parseNewExpression() {
        var callee, args, node = new Node();

        expectKeyword('new');

        if (match('.')) {
            lex();
            if (lookahead.type === Token.Identifier && lookahead.value === 'target') {
                if (state.inFunctionBody) {
                    lex();
                    return node.finishMetaProperty('new', 'target');
                }
            }
            throwUnexpectedToken(lookahead);
        }

        callee = isolateCoverGrammar(parseLeftHandSideExpression);
        args = match('(') ? parseArguments() : [];

        isAssignmentTarget = isBindingElement = false;

        return node.finishNewExpression(callee, args);
    }

    // ECMA-262 12.3.4 Function Calls

    function parseLeftHandSideExpressionAllowCall() {
        var quasi, expr, args, property, startToken, previousAllowIn = state.allowIn;

        startToken = lookahead;
        state.allowIn = true;

        if (matchKeyword('super') && state.inFunctionBody) {
            expr = new Node();
            lex();
            expr = expr.finishSuper();
            if (!match('(') && !match('.') && !match('[')) {
                throwUnexpectedToken(lookahead);
            }
        } else {
            expr = inheritCoverGrammar(matchKeyword('new') ? parseNewExpression : parsePrimaryExpression);
        }

        for (;;) {
            if (match('.')) {
                isBindingElement = false;
                isAssignmentTarget = true;
                property = parseNonComputedMember();
                expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property);
            } else if (match('(')) {
                isBindingElement = false;
                isAssignmentTarget = false;
                args = parseArguments();
                expr = new WrappingNode(startToken).finishCallExpression(expr, args);
            } else if (match('[')) {
                isBindingElement = false;
                isAssignmentTarget = true;
                property = parseComputedMember();
                expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property);
            } else if (lookahead.type === Token.Template && lookahead.head) {
                quasi = parseTemplateLiteral();
                expr = new WrappingNode(startToken).finishTaggedTemplateExpression(expr, quasi);
            } else {
                break;
            }
        }
        state.allowIn = previousAllowIn;

        return expr;
    }

    // ECMA-262 12.3 Left-Hand-Side Expressions

    function parseLeftHandSideExpression() {
        var quasi, expr, property, startToken;
        assert(state.allowIn, 'callee of new expression always allow in keyword.');

        startToken = lookahead;

        if (matchKeyword('super') && state.inFunctionBody) {
            expr = new Node();
            lex();
            expr = expr.finishSuper();
            if (!match('[') && !match('.')) {
                throwUnexpectedToken(lookahead);
            }
        } else {
            expr = inheritCoverGrammar(matchKeyword('new') ? parseNewExpression : parsePrimaryExpression);
        }

        for (;;) {
            if (match('[')) {
                isBindingElement = false;
                isAssignmentTarget = true;
                property = parseComputedMember();
                expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property);
            } else if (match('.')) {
                isBindingElement = false;
                isAssignmentTarget = true;
                property = parseNonComputedMember();
                expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property);
            } else if (lookahead.type === Token.Template && lookahead.head) {
                quasi = parseTemplateLiteral();
                expr = new WrappingNode(startToken).finishTaggedTemplateExpression(expr, quasi);
            } else {
                break;
            }
        }
        return expr;
    }

    // ECMA-262 12.4 Postfix Expressions

    function parsePostfixExpression() {
        var expr, token, startToken = lookahead;

        expr = inheritCoverGrammar(parseLeftHandSideExpressionAllowCall);

        if (!hasLineTerminator && lookahead.type === Token.Punctuator) {
            if (match('++') || match('--')) {
                // ECMA-262 11.3.1, 11.3.2
                if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
                    tolerateError(Messages.StrictLHSPostfix);
                }

                if (!isAssignmentTarget) {
                    tolerateError(Messages.InvalidLHSInAssignment);
                }

                isAssignmentTarget = isBindingElement = false;

                token = lex();
                expr = new WrappingNode(startToken).finishPostfixExpression(token.value, expr);
            }
        }

        return expr;
    }

    // ECMA-262 12.5 Unary Operators

    function parseUnaryExpression() {
        var token, expr, startToken;

        if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) {
            expr = parsePostfixExpression();
        } else if (match('++') || match('--')) {
            startToken = lookahead;
            token = lex();
            expr = inheritCoverGrammar(parseUnaryExpression);
            // ECMA-262 11.4.4, 11.4.5
            if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
                tolerateError(Messages.StrictLHSPrefix);
            }

            if (!isAssignmentTarget) {
                tolerateError(Messages.InvalidLHSInAssignment);
            }
            expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
            isAssignmentTarget = isBindingElement = false;
        } else if (match('+') || match('-') || match('~') || match('!')) {
            startToken = lookahead;
            token = lex();
            expr = inheritCoverGrammar(parseUnaryExpression);
            expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
            isAssignmentTarget = isBindingElement = false;
        } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
            startToken = lookahead;
            token = lex();
            expr = inheritCoverGrammar(parseUnaryExpression);
            expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
            if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
                tolerateError(Messages.StrictDelete);
            }
            isAssignmentTarget = isBindingElement = false;
        } else {
            expr = parsePostfixExpression();
        }

        return expr;
    }

    function binaryPrecedence(token, allowIn) {
        var prec = 0;

        if (token.type !== Token.Punctuator && token.type !== Token.Keyword) {
            return 0;
        }

        switch (token.value) {
        case '||':
            prec = 1;
            break;

        case '&&':
            prec = 2;
            break;

        case '|':
            prec = 3;
            break;

        case '^':
            prec = 4;
            break;

        case '&':
            prec = 5;
            break;

        case '==':
        case '!=':
        case '===':
        case '!==':
            prec = 6;
            break;

        case '<':
        case '>':
        case '<=':
        case '>=':
        case 'instanceof':
            prec = 7;
            break;

        case 'in':
            prec = allowIn ? 7 : 0;
            break;

        case '<<':
        case '>>':
        case '>>>':
            prec = 8;
            break;

        case '+':
        case '-':
            prec = 9;
            break;

        case '*':
        case '/':
        case '%':
            prec = 11;
            break;

        default:
            break;
        }

        return prec;
    }

    // ECMA-262 12.6 Multiplicative Operators
    // ECMA-262 12.7 Additive Operators
    // ECMA-262 12.8 Bitwise Shift Operators
    // ECMA-262 12.9 Relational Operators
    // ECMA-262 12.10 Equality Operators
    // ECMA-262 12.11 Binary Bitwise Operators
    // ECMA-262 12.12 Binary Logical Operators

    function parseBinaryExpression() {
        var marker, markers, expr, token, prec, stack, right, operator, left, i;

        marker = lookahead;
        left = inheritCoverGrammar(parseUnaryExpression);

        token = lookahead;
        prec = binaryPrecedence(token, state.allowIn);
        if (prec === 0) {
            return left;
        }
        isAssignmentTarget = isBindingElement = false;
        token.prec = prec;
        lex();

        markers = [marker, lookahead];
        right = isolateCoverGrammar(parseUnaryExpression);

        stack = [left, token, right];

        while ((prec = binaryPrecedence(lookahead, state.allowIn)) > 0) {

            // Reduce: make a binary expression from the three topmost entries.
            while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
                right = stack.pop();
                operator = stack.pop().value;
                left = stack.pop();
                markers.pop();
                expr = new WrappingNode(markers[markers.length - 1]).finishBinaryExpression(operator, left, right);
                stack.push(expr);
            }

            // Shift.
            token = lex();
            token.prec = prec;
            stack.push(token);
            markers.push(lookahead);
            expr = isolateCoverGrammar(parseUnaryExpression);
            stack.push(expr);
        }

        // Final reduce to clean-up the stack.
        i = stack.length - 1;
        expr = stack[i];
        markers.pop();
        while (i > 1) {
            expr = new WrappingNode(markers.pop()).finishBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
            i -= 2;
        }

        return expr;
    }


    // ECMA-262 12.13 Conditional Operator

    function parseConditionalExpression() {
        var expr, previousAllowIn, consequent, alternate, startToken;

        startToken = lookahead;

        expr = inheritCoverGrammar(parseBinaryExpression);
        if (match('?')) {
            lex();
            previousAllowIn = state.allowIn;
            state.allowIn = true;
            consequent = isolateCoverGrammar(parseAssignmentExpression);
            state.allowIn = previousAllowIn;
            expect(':');
            alternate = isolateCoverGrammar(parseAssignmentExpression);

            expr = new WrappingNode(startToken).finishConditionalExpression(expr, consequent, alternate);
            isAssignmentTarget = isBindingElement = false;
        }

        return expr;
    }

    // ECMA-262 14.2 Arrow Function Definitions

    function parseConciseBody() {
        if (match('{')) {
            return parseFunctionSourceElements();
        }
        return isolateCoverGrammar(parseAssignmentExpression);
    }

    function checkPatternParam(options, param) {
        var i;
        switch (param.type) {
        case Syntax.Identifier:
            validateParam(options, param, param.name);
            break;
        case Syntax.RestElement:
            checkPatternParam(options, param.argument);
            break;
        case Syntax.AssignmentPattern:
            checkPatternParam(options, param.left);
            break;
        case Syntax.ArrayPattern:
            for (i = 0; i < param.elements.length; i++) {
                if (param.elements[i] !== null) {
                    checkPatternParam(options, param.elements[i]);
                }
            }
            break;
        case Syntax.YieldExpression:
            break;
        default:
            assert(param.type === Syntax.ObjectPattern, 'Invalid type');
            for (i = 0; i < param.properties.length; i++) {
                checkPatternParam(options, param.properties[i].value);
            }
            break;
        }
    }
    function reinterpretAsCoverFormalsList(expr) {
        var i, len, param, params, defaults, defaultCount, options, token;

        defaults = [];
        defaultCount = 0;
        params = [expr];

        switch (expr.type) {
        case Syntax.Identifier:
            break;
        case PlaceHolders.ArrowParameterPlaceHolder:
            params = expr.params;
            break;
        default:
            return null;
        }

        options = {
            paramSet: {}
        };

        for (i = 0, len = params.length; i < len; i += 1) {
            param = params[i];
            switch (param.type) {
            case Syntax.AssignmentPattern:
                params[i] = param.left;
                if (param.right.type === Syntax.YieldExpression) {
                    if (param.right.argument) {
                        throwUnexpectedToken(lookahead);
                    }
                    param.right.type = Syntax.Identifier;
                    param.right.name = 'yield';
                    delete param.right.argument;
                    delete param.right.delegate;
                }
                defaults.push(param.right);
                ++defaultCount;
                checkPatternParam(options, param.left);
                break;
            default:
                checkPatternParam(options, param);
                params[i] = param;
                defaults.push(null);
                break;
            }
        }

        if (strict || !state.allowYield) {
            for (i = 0, len = params.length; i < len; i += 1) {
                param = params[i];
                if (param.type === Syntax.YieldExpression) {
                    throwUnexpectedToken(lookahead);
                }
            }
        }

        if (options.message === Messages.StrictParamDupe) {
            token = strict ? options.stricted : options.firstRestricted;
            throwUnexpectedToken(token, options.message);
        }

        if (defaultCount === 0) {
            defaults = [];
        }

        return {
            params: params,
            defaults: defaults,
            stricted: options.stricted,
            firstRestricted: options.firstRestricted,
            message: options.message
        };
    }

    function parseArrowFunctionExpression(options, node) {
        var previousStrict, previousAllowYield, body;

        if (hasLineTerminator) {
            tolerateUnexpectedToken(lookahead);
        }
        expect('=>');

        previousStrict = strict;
        previousAllowYield = state.allowYield;
        state.allowYield = true;

        body = parseConciseBody();

        if (strict && options.firstRestricted) {
            throwUnexpectedToken(options.firstRestricted, options.message);
        }
        if (strict && options.stricted) {
            tolerateUnexpectedToken(options.stricted, options.message);
        }

        strict = previousStrict;
        state.allowYield = previousAllowYield;

        return node.finishArrowFunctionExpression(options.params, options.defaults, body, body.type !== Syntax.BlockStatement);
    }

    // ECMA-262 14.4 Yield expression

    function parseYieldExpression() {
        var argument, expr, delegate, previousAllowYield;

        argument = null;
        expr = new Node();
        delegate = false;

        expectKeyword('yield');

        if (!hasLineTerminator) {
            previousAllowYield = state.allowYield;
            state.allowYield = false;
            delegate = match('*');
            if (delegate) {
                lex();
                argument = parseAssignmentExpression();
            } else {
                if (!match(';') && !match('}') && !match(')') && lookahead.type !== Token.EOF) {
                    argument = parseAssignmentExpression();
                }
            }
            state.allowYield = previousAllowYield;
        }

        return expr.finishYieldExpression(argument, delegate);
    }

    // ECMA-262 12.14 Assignment Operators

    function parseAssignmentExpression() {
        var token, expr, right, list, startToken;

        startToken = lookahead;
        token = lookahead;

        if (!state.allowYield && matchKeyword('yield')) {
            return parseYieldExpression();
        }

        expr = parseConditionalExpression();

        if (expr.type === PlaceHolders.ArrowParameterPlaceHolder || match('=>')) {
            isAssignmentTarget = isBindingElement = false;
            list = reinterpretAsCoverFormalsList(expr);

            if (list) {
                firstCoverInitializedNameError = null;
                return parseArrowFunctionExpression(list, new WrappingNode(startToken));
            }

            return expr;
        }

        if (matchAssign()) {
            if (!isAssignmentTarget) {
                tolerateError(Messages.InvalidLHSInAssignment);
            }

            // ECMA-262 12.1.1
            if (strict && expr.type === Syntax.Identifier) {
                if (isRestrictedWord(expr.name)) {
                    tolerateUnexpectedToken(token, Messages.StrictLHSAssignment);
                }
                if (isStrictModeReservedWord(expr.name)) {
                    tolerateUnexpectedToken(token, Messages.StrictReservedWord);
                }
            }

            if (!match('=')) {
                isAssignmentTarget = isBindingElement = false;
            } else {
                reinterpretExpressionAsPattern(expr);
            }

            token = lex();
            right = isolateCoverGrammar(parseAssignmentExpression);
            expr = new WrappingNode(startToken).finishAssignmentExpression(token.value, expr, right);
            firstCoverInitializedNameError = null;
        }

        return expr;
    }

    // ECMA-262 12.15 Comma Operator

    function parseExpression() {
        var expr, startToken = lookahead, expressions;

        expr = isolateCoverGrammar(parseAssignmentExpression);

        if (match(',')) {
            expressions = [expr];

            while (startIndex < length) {
                if (!match(',')) {
                    break;
                }
                lex();
                expressions.push(isolateCoverGrammar(parseAssignmentExpression));
            }

            expr = new WrappingNode(startToken).finishSequenceExpression(expressions);
        }

        return expr;
    }

    // ECMA-262 13.2 Block

    function parseStatementListItem() {
        if (lookahead.type === Token.Keyword) {
            switch (lookahead.value) {
            case 'export':
                if (state.sourceType !== 'module') {
                    tolerateUnexpectedToken(lookahead, Messages.IllegalExportDeclaration);
                }
                return parseExportDeclaration();
            case 'import':
                if (state.sourceType !== 'module') {
                    tolerateUnexpectedToken(lookahead, Messages.IllegalImportDeclaration);
                }
                return parseImportDeclaration();
            case 'const':
                return parseLexicalDeclaration({inFor: false});
            case 'function':
                return parseFunctionDeclaration(new Node());
            case 'class':
                return parseClassDeclaration();
            }
        }

        if (matchKeyword('let') && isLexicalDeclaration()) {
            return parseLexicalDeclaration({inFor: false});
        }

        return parseStatement();
    }

    function parseStatementList() {
        var list = [];
        while (startIndex < length) {
            if (match('}')) {
                break;
            }
            list.push(parseStatementListItem());
        }

        return list;
    }

    function parseBlock() {
        var block, node = new Node();

        expect('{');

        block = parseStatementList();

        expect('}');

        return node.finishBlockStatement(block);
    }

    // ECMA-262 13.3.2 Variable Statement

    function parseVariableIdentifier(kind) {
        var token, node = new Node();

        token = lex();

        if (token.type === Token.Keyword && token.value === 'yield') {
            if (strict) {
                tolerateUnexpectedToken(token, Messages.StrictReservedWord);
            } if (!state.allowYield) {
                throwUnexpectedToken(token);
            }
        } else if (token.type !== Token.Identifier) {
            if (strict && token.type === Token.Keyword && isStrictModeReservedWord(token.value)) {
                tolerateUnexpectedToken(token, Messages.StrictReservedWord);
            } else {
                if (strict || token.value !== 'let' || kind !== 'var') {
                    throwUnexpectedToken(token);
                }
            }
        } else if (state.sourceType === 'module' && token.type === Token.Identifier && token.value === 'await') {
            tolerateUnexpectedToken(token);
        }

        return node.finishIdentifier(token.value);
    }

    function parseVariableDeclaration(options) {
        var init = null, id, node = new Node(), params = [];

        id = parsePattern(params, 'var');

        // ECMA-262 12.2.1
        if (strict && isRestrictedWord(id.name)) {
            tolerateError(Messages.StrictVarName);
        }

        if (match('=')) {
            lex();
            init = isolateCoverGrammar(parseAssignmentExpression);
        } else if (id.type !== Syntax.Identifier && !options.inFor) {
            expect('=');
        }

        return node.finishVariableDeclarator(id, init);
    }

    function parseVariableDeclarationList(options) {
        var opt, list;

        opt = { inFor: options.inFor };
        list = [parseVariableDeclaration(opt)];

        while (match(',')) {
            lex();
            list.push(parseVariableDeclaration(opt));
        }

        return list;
    }

    function parseVariableStatement(node) {
        var declarations;

        expectKeyword('var');

        declarations = parseVariableDeclarationList({ inFor: false });

        consumeSemicolon();

        return node.finishVariableDeclaration(declarations);
    }

    // ECMA-262 13.3.1 Let and Const Declarations

    function parseLexicalBinding(kind, options) {
        var init = null, id, node = new Node(), params = [];

        id = parsePattern(params, kind);

        // ECMA-262 12.2.1
        if (strict && id.type === Syntax.Identifier && isRestrictedWord(id.name)) {
            tolerateError(Messages.StrictVarName);
        }

        if (kind === 'const') {
            if (!matchKeyword('in') && !matchContextualKeyword('of')) {
                expect('=');
                init = isolateCoverGrammar(parseAssignmentExpression);
            }
        } else if ((!options.inFor && id.type !== Syntax.Identifier) || match('=')) {
            expect('=');
            init = isolateCoverGrammar(parseAssignmentExpression);
        }

        return node.finishVariableDeclarator(id, init);
    }

    function parseBindingList(kind, options) {
        var list = [parseLexicalBinding(kind, options)];

        while (match(',')) {
            lex();
            list.push(parseLexicalBinding(kind, options));
        }

        return list;
    }


    function tokenizerState() {
        return {
            index: index,
            lineNumber: lineNumber,
            lineStart: lineStart,
            hasLineTerminator: hasLineTerminator,
            lastIndex: lastIndex,
            lastLineNumber: lastLineNumber,
            lastLineStart: lastLineStart,
            startIndex: startIndex,
            startLineNumber: startLineNumber,
            startLineStart: startLineStart,
            lookahead: lookahead,
            tokenCount: extra.tokens ? extra.tokens.length : 0
        };
    }

    function resetTokenizerState(ts) {
        index = ts.index;
        lineNumber = ts.lineNumber;
        lineStart = ts.lineStart;
        hasLineTerminator = ts.hasLineTerminator;
        lastIndex = ts.lastIndex;
        lastLineNumber = ts.lastLineNumber;
        lastLineStart = ts.lastLineStart;
        startIndex = ts.startIndex;
        startLineNumber = ts.startLineNumber;
        startLineStart = ts.startLineStart;
        lookahead = ts.lookahead;
        if (extra.tokens) {
            extra.tokens.splice(ts.tokenCount, extra.tokens.length);
        }
    }

    function isLexicalDeclaration() {
        var lexical, ts;

        ts = tokenizerState();

        lex();
        lexical = (lookahead.type === Token.Identifier) || match('[') || match('{') ||
            matchKeyword('let') || matchKeyword('yield');

        resetTokenizerState(ts);

        return lexical;
    }

    function parseLexicalDeclaration(options) {
        var kind, declarations, node = new Node();

        kind = lex().value;
        assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const');

        declarations = parseBindingList(kind, options);

        consumeSemicolon();

        return node.finishLexicalDeclaration(declarations, kind);
    }

    function parseRestElement(params) {
        var param, node = new Node();

        lex();

        if (match('{')) {
            throwError(Messages.ObjectPatternAsRestParameter);
        }

        params.push(lookahead);

        param = parseVariableIdentifier();

        if (match('=')) {
            throwError(Messages.DefaultRestParameter);
        }

        if (!match(')')) {
            throwError(Messages.ParameterAfterRestParameter);
        }

        return node.finishRestElement(param);
    }

    // ECMA-262 13.4 Empty Statement

    function parseEmptyStatement(node) {
        expect(';');
        return node.finishEmptyStatement();
    }

    // ECMA-262 12.4 Expression Statement

    function parseExpressionStatement(node) {
        var expr = parseExpression();
        consumeSemicolon();
        return node.finishExpressionStatement(expr);
    }

    // ECMA-262 13.6 If statement

    function parseIfStatement(node) {
        var test, consequent, alternate;

        expectKeyword('if');

        expect('(');

        test = parseExpression();

        expect(')');

        consequent = parseStatement();

        if (matchKeyword('else')) {
            lex();
            alternate = parseStatement();
        } else {
            alternate = null;
        }

        return node.finishIfStatement(test, consequent, alternate);
    }

    // ECMA-262 13.7 Iteration Statements

    function parseDoWhileStatement(node) {
        var body, test, oldInIteration;

        expectKeyword('do');

        oldInIteration = state.inIteration;
        state.inIteration = true;

        body = parseStatement();

        state.inIteration = oldInIteration;

        expectKeyword('while');

        expect('(');

        test = parseExpression();

        expect(')');

        if (match(';')) {
            lex();
        }

        return node.finishDoWhileStatement(body, test);
    }

    function parseWhileStatement(node) {
        var test, body, oldInIteration;

        expectKeyword('while');

        expect('(');

        test = parseExpression();

        expect(')');

        oldInIteration = state.inIteration;
        state.inIteration = true;

        body = parseStatement();

        state.inIteration = oldInIteration;

        return node.finishWhileStatement(test, body);
    }

    function parseForStatement(node) {
        var init, forIn, initSeq, initStartToken, test, update, left, right, kind, declarations,
            body, oldInIteration, previousAllowIn = state.allowIn;

        init = test = update = null;
        forIn = true;

        expectKeyword('for');

        expect('(');

        if (match(';')) {
            lex();
        } else {
            if (matchKeyword('var')) {
                init = new Node();
                lex();

                state.allowIn = false;
                declarations = parseVariableDeclarationList({ inFor: true });
                state.allowIn = previousAllowIn;

                if (declarations.length === 1 && matchKeyword('in')) {
                    init = init.finishVariableDeclaration(declarations);
                    lex();
                    left = init;
                    right = parseExpression();
                    init = null;
                } else if (declarations.length === 1 && declarations[0].init === null && matchContextualKeyword('of')) {
                    init = init.finishVariableDeclaration(declarations);
                    lex();
                    left = init;
                    right = parseAssignmentExpression();
                    init = null;
                    forIn = false;
                } else {
                    init = init.finishVariableDeclaration(declarations);
                    expect(';');
                }
            } else if (matchKeyword('const') || matchKeyword('let')) {
                init = new Node();
                kind = lex().value;

                if (!strict && lookahead.value === 'in') {
                    init = init.finishIdentifier(kind);
                    lex();
                    left = init;
                    right = parseExpression();
                    init = null;
                } else {
                    state.allowIn = false;
                    declarations = parseBindingList(kind, {inFor: true});
                    state.allowIn = previousAllowIn;

                    if (declarations.length === 1 && declarations[0].init === null && matchKeyword('in')) {
                        init = init.finishLexicalDeclaration(declarations, kind);
                        lex();
                        left = init;
                        right = parseExpression();
                        init = null;
                    } else if (declarations.length === 1 && declarations[0].init === null && matchContextualKeyword('of')) {
                        init = init.finishLexicalDeclaration(declarations, kind);
                        lex();
                        left = init;
                        right = parseAssignmentExpression();
                        init = null;
                        forIn = false;
                    } else {
                        consumeSemicolon();
                        init = init.finishLexicalDeclaration(declarations, kind);
                    }
                }
            } else {
                initStartToken = lookahead;
                state.allowIn = false;
                init = inheritCoverGrammar(parseAssignmentExpression);
                state.allowIn = previousAllowIn;

                if (matchKeyword('in')) {
                    if (!isAssignmentTarget) {
                        tolerateError(Messages.InvalidLHSInForIn);
                    }

                    lex();
                    reinterpretExpressionAsPattern(init);
                    left = init;
                    right = parseExpression();
                    init = null;
                } else if (matchContextualKeyword('of')) {
                    if (!isAssignmentTarget) {
                        tolerateError(Messages.InvalidLHSInForLoop);
                    }

                    lex();
                    reinterpretExpressionAsPattern(init);
                    left = init;
                    right = parseAssignmentExpression();
                    init = null;
                    forIn = false;
                } else {
                    if (match(',')) {
                        initSeq = [init];
                        while (match(',')) {
                            lex();
                            initSeq.push(isolateCoverGrammar(parseAssignmentExpression));
                        }
                        init = new WrappingNode(initStartToken).finishSequenceExpression(initSeq);
                    }
                    expect(';');
                }
            }
        }

        if (typeof left === 'undefined') {

            if (!match(';')) {
                test = parseExpression();
            }
            expect(';');

            if (!match(')')) {
                update = parseExpression();
            }
        }

        expect(')');

        oldInIteration = state.inIteration;
        state.inIteration = true;

        body = isolateCoverGrammar(parseStatement);

        state.inIteration = oldInIteration;

        return (typeof left === 'undefined') ?
                node.finishForStatement(init, test, update, body) :
                forIn ? node.finishForInStatement(left, right, body) :
                    node.finishForOfStatement(left, right, body);
    }

    // ECMA-262 13.8 The continue statement

    function parseContinueStatement(node) {
        var label = null, key;

        expectKeyword('continue');

        // Optimize the most common form: 'continue;'.
        if (source.charCodeAt(startIndex) === 0x3B) {
            lex();

            if (!state.inIteration) {
                throwError(Messages.IllegalContinue);
            }

            return node.finishContinueStatement(null);
        }

        if (hasLineTerminator) {
            if (!state.inIteration) {
                throwError(Messages.IllegalContinue);
            }

            return node.finishContinueStatement(null);
        }

        if (lookahead.type === Token.Identifier) {
            label = parseVariableIdentifier();

            key = '$' + label.name;
            if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
                throwError(Messages.UnknownLabel, label.name);
            }
        }

        consumeSemicolon();

        if (label === null && !state.inIteration) {
            throwError(Messages.IllegalContinue);
        }

        return node.finishContinueStatement(label);
    }

    // ECMA-262 13.9 The break statement

    function parseBreakStatement(node) {
        var label = null, key;

        expectKeyword('break');

        // Catch the very common case first: immediately a semicolon (U+003B).
        if (source.charCodeAt(lastIndex) === 0x3B) {
            lex();

            if (!(state.inIteration || state.inSwitch)) {
                throwError(Messages.IllegalBreak);
            }

            return node.finishBreakStatement(null);
        }

        if (hasLineTerminator) {
            if (!(state.inIteration || state.inSwitch)) {
                throwError(Messages.IllegalBreak);
            }
        } else if (lookahead.type === Token.Identifier) {
            label = parseVariableIdentifier();

            key = '$' + label.name;
            if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
                throwError(Messages.UnknownLabel, label.name);
            }
        }

        consumeSemicolon();

        if (label === null && !(state.inIteration || state.inSwitch)) {
            throwError(Messages.IllegalBreak);
        }

        return node.finishBreakStatement(label);
    }

    // ECMA-262 13.10 The return statement

    function parseReturnStatement(node) {
        var argument = null;

        expectKeyword('return');

        if (!state.inFunctionBody) {
            tolerateError(Messages.IllegalReturn);
        }

        // 'return' followed by a space and an identifier is very common.
        if (source.charCodeAt(lastIndex) === 0x20) {
            if (isIdentifierStart(source.charCodeAt(lastIndex + 1))) {
                argument = parseExpression();
                consumeSemicolon();
                return node.finishReturnStatement(argument);
            }
        }

        if (hasLineTerminator) {
            // HACK
            return node.finishReturnStatement(null);
        }

        if (!match(';')) {
            if (!match('}') && lookahead.type !== Token.EOF) {
                argument = parseExpression();
            }
        }

        consumeSemicolon();

        return node.finishReturnStatement(argument);
    }

    // ECMA-262 13.11 The with statement

    function parseWithStatement(node) {
        var object, body;

        if (strict) {
            tolerateError(Messages.StrictModeWith);
        }

        expectKeyword('with');

        expect('(');

        object = parseExpression();

        expect(')');

        body = parseStatement();

        return node.finishWithStatement(object, body);
    }

    // ECMA-262 13.12 The switch statement

    function parseSwitchCase() {
        var test, consequent = [], statement, node = new Node();

        if (matchKeyword('default')) {
            lex();
            test = null;
        } else {
            expectKeyword('case');
            test = parseExpression();
        }
        expect(':');

        while (startIndex < length) {
            if (match('}') || matchKeyword('default') || matchKeyword('case')) {
                break;
            }
            statement = parseStatementListItem();
            consequent.push(statement);
        }

        return node.finishSwitchCase(test, consequent);
    }

    function parseSwitchStatement(node) {
        var discriminant, cases, clause, oldInSwitch, defaultFound;

        expectKeyword('switch');

        expect('(');

        discriminant = parseExpression();

        expect(')');

        expect('{');

        cases = [];

        if (match('}')) {
            lex();
            return node.finishSwitchStatement(discriminant, cases);
        }

        oldInSwitch = state.inSwitch;
        state.inSwitch = true;
        defaultFound = false;

        while (startIndex < length) {
            if (match('}')) {
                break;
            }
            clause = parseSwitchCase();
            if (clause.test === null) {
                if (defaultFound) {
                    throwError(Messages.MultipleDefaultsInSwitch);
                }
                defaultFound = true;
            }
            cases.push(clause);
        }

        state.inSwitch = oldInSwitch;

        expect('}');

        return node.finishSwitchStatement(discriminant, cases);
    }

    // ECMA-262 13.14 The throw statement

    function parseThrowStatement(node) {
        var argument;

        expectKeyword('throw');

        if (hasLineTerminator) {
            throwError(Messages.NewlineAfterThrow);
        }

        argument = parseExpression();

        consumeSemicolon();

        return node.finishThrowStatement(argument);
    }

    // ECMA-262 13.15 The try statement

    function parseCatchClause() {
        var param, params = [], paramMap = {}, key, i, body, node = new Node();

        expectKeyword('catch');

        expect('(');
        if (match(')')) {
            throwUnexpectedToken(lookahead);
        }

        param = parsePattern(params);
        for (i = 0; i < params.length; i++) {
            key = '$' + params[i].value;
            if (Object.prototype.hasOwnProperty.call(paramMap, key)) {
                tolerateError(Messages.DuplicateBinding, params[i].value);
            }
            paramMap[key] = true;
        }

        // ECMA-262 12.14.1
        if (strict && isRestrictedWord(param.name)) {
            tolerateError(Messages.StrictCatchVariable);
        }

        expect(')');
        body = parseBlock();
        return node.finishCatchClause(param, body);
    }

    function parseTryStatement(node) {
        var block, handler = null, finalizer = null;

        expectKeyword('try');

        block = parseBlock();

        if (matchKeyword('catch')) {
            handler = parseCatchClause();
        }

        if (matchKeyword('finally')) {
            lex();
            finalizer = parseBlock();
        }

        if (!handler && !finalizer) {
            throwError(Messages.NoCatchOrFinally);
        }

        return node.finishTryStatement(block, handler, finalizer);
    }

    // ECMA-262 13.16 The debugger statement

    function parseDebuggerStatement(node) {
        expectKeyword('debugger');

        consumeSemicolon();

        return node.finishDebuggerStatement();
    }

    // 13 Statements

    function parseStatement() {
        var type = lookahead.type,
            expr,
            labeledBody,
            key,
            node;

        if (type === Token.EOF) {
            throwUnexpectedToken(lookahead);
        }

        if (type === Token.Punctuator && lookahead.value === '{') {
            return parseBlock();
        }
        isAssignmentTarget = isBindingElement = true;
        node = new Node();

        if (type === Token.Punctuator) {
            switch (lookahead.value) {
            case ';':
                return parseEmptyStatement(node);
            case '(':
                return parseExpressionStatement(node);
            default:
                break;
            }
        } else if (type === Token.Keyword) {
            switch (lookahead.value) {
            case 'break':
                return parseBreakStatement(node);
            case 'continue':
                return parseContinueStatement(node);
            case 'debugger':
                return parseDebuggerStatement(node);
            case 'do':
                return parseDoWhileStatement(node);
            case 'for':
                return parseForStatement(node);
            case 'function':
                return parseFunctionDeclaration(node);
            case 'if':
                return parseIfStatement(node);
            case 'return':
                return parseReturnStatement(node);
            case 'switch':
                return parseSwitchStatement(node);
            case 'throw':
                return parseThrowStatement(node);
            case 'try':
                return parseTryStatement(node);
            case 'var':
                return parseVariableStatement(node);
            case 'while':
                return parseWhileStatement(node);
            case 'with':
                return parseWithStatement(node);
            default:
                break;
            }
        }

        expr = parseExpression();

        // ECMA-262 12.12 Labelled Statements
        if ((expr.type === Syntax.Identifier) && match(':')) {
            lex();

            key = '$' + expr.name;
            if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
                throwError(Messages.Redeclaration, 'Label', expr.name);
            }

            state.labelSet[key] = true;
            labeledBody = parseStatement();
            delete state.labelSet[key];
            return node.finishLabeledStatement(expr, labeledBody);
        }

        consumeSemicolon();

        return node.finishExpressionStatement(expr);
    }

    // ECMA-262 14.1 Function Definition

    function parseFunctionSourceElements() {
        var statement, body = [], token, directive, firstRestricted,
            oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody,
            node = new Node();

        expect('{');

        while (startIndex < length) {
            if (lookahead.type !== Token.StringLiteral) {
                break;
            }
            token = lookahead;

            statement = parseStatementListItem();
            body.push(statement);
            if (statement.expression.type !== Syntax.Literal) {
                // this is not directive
                break;
            }
            directive = source.slice(token.start + 1, token.end - 1);
            if (directive === 'use strict') {
                strict = true;
                if (firstRestricted) {
                    tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral);
                }
            } else {
                if (!firstRestricted && token.octal) {
                    firstRestricted = token;
                }
            }
        }

        oldLabelSet = state.labelSet;
        oldInIteration = state.inIteration;
        oldInSwitch = state.inSwitch;
        oldInFunctionBody = state.inFunctionBody;

        state.labelSet = {};
        state.inIteration = false;
        state.inSwitch = false;
        state.inFunctionBody = true;

        while (startIndex < length) {
            if (match('}')) {
                break;
            }
            body.push(parseStatementListItem());
        }

        expect('}');

        state.labelSet = oldLabelSet;
        state.inIteration = oldInIteration;
        state.inSwitch = oldInSwitch;
        state.inFunctionBody = oldInFunctionBody;

        return node.finishBlockStatement(body);
    }

    function validateParam(options, param, name) {
        var key = '$' + name;
        if (strict) {
            if (isRestrictedWord(name)) {
                options.stricted = param;
                options.message = Messages.StrictParamName;
            }
            if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
                options.stricted = param;
                options.message = Messages.StrictParamDupe;
            }
        } else if (!options.firstRestricted) {
            if (isRestrictedWord(name)) {
                options.firstRestricted = param;
                options.message = Messages.StrictParamName;
            } else if (isStrictModeReservedWord(name)) {
                options.firstRestricted = param;
                options.message = Messages.StrictReservedWord;
            } else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
                options.stricted = param;
                options.message = Messages.StrictParamDupe;
            }
        }
        options.paramSet[key] = true;
    }

    function parseParam(options) {
        var token, param, params = [], i, def;

        token = lookahead;
        if (token.value === '...') {
            param = parseRestElement(params);
            validateParam(options, param.argument, param.argument.name);
            options.params.push(param);
            options.defaults.push(null);
            return false;
        }

        param = parsePatternWithDefault(params);
        for (i = 0; i < params.length; i++) {
            validateParam(options, params[i], params[i].value);
        }

        if (param.type === Syntax.AssignmentPattern) {
            def = param.right;
            param = param.left;
            ++options.defaultCount;
        }

        options.params.push(param);
        options.defaults.push(def);

        return !match(')');
    }

    function parseParams(firstRestricted) {
        var options;

        options = {
            params: [],
            defaultCount: 0,
            defaults: [],
            firstRestricted: firstRestricted
        };

        expect('(');

        if (!match(')')) {
            options.paramSet = {};
            while (startIndex < length) {
                if (!parseParam(options)) {
                    break;
                }
                expect(',');
            }
        }

        expect(')');

        if (options.defaultCount === 0) {
            options.defaults = [];
        }

        return {
            params: options.params,
            defaults: options.defaults,
            stricted: options.stricted,
            firstRestricted: options.firstRestricted,
            message: options.message
        };
    }

    function parseFunctionDeclaration(node, identifierIsOptional) {
        var id = null, params = [], defaults = [], body, token, stricted, tmp, firstRestricted, message, previousStrict,
            isGenerator, previousAllowYield;

        previousAllowYield = state.allowYield;

        expectKeyword('function');

        isGenerator = match('*');
        if (isGenerator) {
            lex();
        }

        if (!identifierIsOptional || !match('(')) {
            token = lookahead;
            id = parseVariableIdentifier();
            if (strict) {
                if (isRestrictedWord(token.value)) {
                    tolerateUnexpectedToken(token, Messages.StrictFunctionName);
                }
            } else {
                if (isRestrictedWord(token.value)) {
                    firstRestricted = token;
                    message = Messages.StrictFunctionName;
                } else if (isStrictModeReservedWord(token.value)) {
                    firstRestricted = token;
                    message = Messages.StrictReservedWord;
                }
            }
        }

        state.allowYield = !isGenerator;
        tmp = parseParams(firstRestricted);
        params = tmp.params;
        defaults = tmp.defaults;
        stricted = tmp.stricted;
        firstRestricted = tmp.firstRestricted;
        if (tmp.message) {
            message = tmp.message;
        }


        previousStrict = strict;
        body = parseFunctionSourceElements();
        if (strict && firstRestricted) {
            throwUnexpectedToken(firstRestricted, message);
        }
        if (strict && stricted) {
            tolerateUnexpectedToken(stricted, message);
        }

        strict = previousStrict;
        state.allowYield = previousAllowYield;

        return node.finishFunctionDeclaration(id, params, defaults, body, isGenerator);
    }

    function parseFunctionExpression() {
        var token, id = null, stricted, firstRestricted, message, tmp,
            params = [], defaults = [], body, previousStrict, node = new Node(),
            isGenerator, previousAllowYield;

        previousAllowYield = state.allowYield;

        expectKeyword('function');

        isGenerator = match('*');
        if (isGenerator) {
            lex();
        }

        state.allowYield = !isGenerator;
        if (!match('(')) {
            token = lookahead;
            id = (!strict && !isGenerator && matchKeyword('yield')) ? parseNonComputedProperty() : parseVariableIdentifier();
            if (strict) {
                if (isRestrictedWord(token.value)) {
                    tolerateUnexpectedToken(token, Messages.StrictFunctionName);
                }
            } else {
                if (isRestrictedWord(token.value)) {
                    firstRestricted = token;
                    message = Messages.StrictFunctionName;
                } else if (isStrictModeReservedWord(token.value)) {
                    firstRestricted = token;
                    message = Messages.StrictReservedWord;
                }
            }
        }

        tmp = parseParams(firstRestricted);
        params = tmp.params;
        defaults = tmp.defaults;
        stricted = tmp.stricted;
        firstRestricted = tmp.firstRestricted;
        if (tmp.message) {
            message = tmp.message;
        }

        previousStrict = strict;
        body = parseFunctionSourceElements();
        if (strict && firstRestricted) {
            throwUnexpectedToken(firstRestricted, message);
        }
        if (strict && stricted) {
            tolerateUnexpectedToken(stricted, message);
        }
        strict = previousStrict;
        state.allowYield = previousAllowYield;

        return node.finishFunctionExpression(id, params, defaults, body, isGenerator);
    }

    // ECMA-262 14.5 Class Definitions

    function parseClassBody() {
        var classBody, token, isStatic, hasConstructor = false, body, method, computed, key;

        classBody = new Node();

        expect('{');
        body = [];
        while (!match('}')) {
            if (match(';')) {
                lex();
            } else {
                method = new Node();
                token = lookahead;
                isStatic = false;
                computed = match('[');
                if (match('*')) {
                    lex();
                } else {
                    key = parseObjectPropertyKey();
                    if (key.name === 'static' && (lookaheadPropertyName() || match('*'))) {
                        token = lookahead;
                        isStatic = true;
                        computed = match('[');
                        if (match('*')) {
                            lex();
                        } else {
                            key = parseObjectPropertyKey();
                        }
                    }
                }
                method = tryParseMethodDefinition(token, key, computed, method);
                if (method) {
                    method['static'] = isStatic; // jscs:ignore requireDotNotation
                    if (method.kind === 'init') {
                        method.kind = 'method';
                    }
                    if (!isStatic) {
                        if (!method.computed && (method.key.name || method.key.value.toString()) === 'constructor') {
                            if (method.kind !== 'method' || !method.method || method.value.generator) {
                                throwUnexpectedToken(token, Messages.ConstructorSpecialMethod);
                            }
                            if (hasConstructor) {
                                throwUnexpectedToken(token, Messages.DuplicateConstructor);
                            } else {
                                hasConstructor = true;
                            }
                            method.kind = 'constructor';
                        }
                    } else {
                        if (!method.computed && (method.key.name || method.key.value.toString()) === 'prototype') {
                            throwUnexpectedToken(token, Messages.StaticPrototype);
                        }
                    }
                    method.type = Syntax.MethodDefinition;
                    delete method.method;
                    delete method.shorthand;
                    body.push(method);
                } else {
                    throwUnexpectedToken(lookahead);
                }
            }
        }
        lex();
        return classBody.finishClassBody(body);
    }

    function parseClassDeclaration(identifierIsOptional) {
        var id = null, superClass = null, classNode = new Node(), classBody, previousStrict = strict;
        strict = true;

        expectKeyword('class');

        if (!identifierIsOptional || lookahead.type === Token.Identifier) {
            id = parseVariableIdentifier();
        }

        if (matchKeyword('extends')) {
            lex();
            superClass = isolateCoverGrammar(parseLeftHandSideExpressionAllowCall);
        }
        classBody = parseClassBody();
        strict = previousStrict;

        return classNode.finishClassDeclaration(id, superClass, classBody);
    }

    function parseClassExpression() {
        var id = null, superClass = null, classNode = new Node(), classBody, previousStrict = strict;
        strict = true;

        expectKeyword('class');

        if (lookahead.type === Token.Identifier) {
            id = parseVariableIdentifier();
        }

        if (matchKeyword('extends')) {
            lex();
            superClass = isolateCoverGrammar(parseLeftHandSideExpressionAllowCall);
        }
        classBody = parseClassBody();
        strict = previousStrict;

        return classNode.finishClassExpression(id, superClass, classBody);
    }

    // ECMA-262 15.2 Modules

    function parseModuleSpecifier() {
        var node = new Node();

        if (lookahead.type !== Token.StringLiteral) {
            throwError(Messages.InvalidModuleSpecifier);
        }
        return node.finishLiteral(lex());
    }

    // ECMA-262 15.2.3 Exports

    function parseExportSpecifier() {
        var exported, local, node = new Node(), def;
        if (matchKeyword('default')) {
            // export {default} from 'something';
            def = new Node();
            lex();
            local = def.finishIdentifier('default');
        } else {
            local = parseVariableIdentifier();
        }
        if (matchContextualKeyword('as')) {
            lex();
            exported = parseNonComputedProperty();
        }
        return node.finishExportSpecifier(local, exported);
    }

    function parseExportNamedDeclaration(node) {
        var declaration = null,
            isExportFromIdentifier,
            src = null, specifiers = [];

        // non-default export
        if (lookahead.type === Token.Keyword) {
            // covers:
            // export var f = 1;
            switch (lookahead.value) {
                case 'let':
                case 'const':
                    declaration = parseLexicalDeclaration({inFor: false});
                    return node.finishExportNamedDeclaration(declaration, specifiers, null);
                case 'var':
                case 'class':
                case 'function':
                    declaration = parseStatementListItem();
                    return node.finishExportNamedDeclaration(declaration, specifiers, null);
            }
        }

        expect('{');
        while (!match('}')) {
            isExportFromIdentifier = isExportFromIdentifier || matchKeyword('default');
            specifiers.push(parseExportSpecifier());
            if (!match('}')) {
                expect(',');
                if (match('}')) {
                    break;
                }
            }
        }
        expect('}');

        if (matchContextualKeyword('from')) {
            // covering:
            // export {default} from 'foo';
            // export {foo} from 'foo';
            lex();
            src = parseModuleSpecifier();
            consumeSemicolon();
        } else if (isExportFromIdentifier) {
            // covering:
            // export {default}; // missing fromClause
            throwError(lookahead.value ?
                    Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
        } else {
            // cover
            // export {foo};
            consumeSemicolon();
        }
        return node.finishExportNamedDeclaration(declaration, specifiers, src);
    }

    function parseExportDefaultDeclaration(node) {
        var declaration = null,
            expression = null;

        // covers:
        // export default ...
        expectKeyword('default');

        if (matchKeyword('function')) {
            // covers:
            // export default function foo () {}
            // export default function () {}
            declaration = parseFunctionDeclaration(new Node(), true);
            return node.finishExportDefaultDeclaration(declaration);
        }
        if (matchKeyword('class')) {
            declaration = parseClassDeclaration(true);
            return node.finishExportDefaultDeclaration(declaration);
        }

        if (matchContextualKeyword('from')) {
            throwError(Messages.UnexpectedToken, lookahead.value);
        }

        // covers:
        // export default {};
        // export default [];
        // export default (1 + 2);
        if (match('{')) {
            expression = parseObjectInitializer();
        } else if (match('[')) {
            expression = parseArrayInitializer();
        } else {
            expression = parseAssignmentExpression();
        }
        consumeSemicolon();
        return node.finishExportDefaultDeclaration(expression);
    }

    function parseExportAllDeclaration(node) {
        var src;

        // covers:
        // export * from 'foo';
        expect('*');
        if (!matchContextualKeyword('from')) {
            throwError(lookahead.value ?
                    Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
        }
        lex();
        src = parseModuleSpecifier();
        consumeSemicolon();

        return node.finishExportAllDeclaration(src);
    }

    function parseExportDeclaration() {
        var node = new Node();
        if (state.inFunctionBody) {
            throwError(Messages.IllegalExportDeclaration);
        }

        expectKeyword('export');

        if (matchKeyword('default')) {
            return parseExportDefaultDeclaration(node);
        }
        if (match('*')) {
            return parseExportAllDeclaration(node);
        }
        return parseExportNamedDeclaration(node);
    }

    // ECMA-262 15.2.2 Imports

    function parseImportSpecifier() {
        // import {<foo as bar>} ...;
        var local, imported, node = new Node();

        imported = parseNonComputedProperty();
        if (matchContextualKeyword('as')) {
            lex();
            local = parseVariableIdentifier();
        }

        return node.finishImportSpecifier(local, imported);
    }

    function parseNamedImports() {
        var specifiers = [];
        // {foo, bar as bas}
        expect('{');
        while (!match('}')) {
            specifiers.push(parseImportSpecifier());
            if (!match('}')) {
                expect(',');
                if (match('}')) {
                    break;
                }
            }
        }
        expect('}');
        return specifiers;
    }

    function parseImportDefaultSpecifier() {
        // import <foo> ...;
        var local, node = new Node();

        local = parseNonComputedProperty();

        return node.finishImportDefaultSpecifier(local);
    }

    function parseImportNamespaceSpecifier() {
        // import <* as foo> ...;
        var local, node = new Node();

        expect('*');
        if (!matchContextualKeyword('as')) {
            throwError(Messages.NoAsAfterImportNamespace);
        }
        lex();
        local = parseNonComputedProperty();

        return node.finishImportNamespaceSpecifier(local);
    }

    function parseImportDeclaration() {
        var specifiers = [], src, node = new Node();

        if (state.inFunctionBody) {
            throwError(Messages.IllegalImportDeclaration);
        }

        expectKeyword('import');

        if (lookahead.type === Token.StringLiteral) {
            // import 'foo';
            src = parseModuleSpecifier();
        } else {

            if (match('{')) {
                // import {bar}
                specifiers = specifiers.concat(parseNamedImports());
            } else if (match('*')) {
                // import * as foo
                specifiers.push(parseImportNamespaceSpecifier());
            } else if (isIdentifierName(lookahead) && !matchKeyword('default')) {
                // import foo
                specifiers.push(parseImportDefaultSpecifier());
                if (match(',')) {
                    lex();
                    if (match('*')) {
                        // import foo, * as foo
                        specifiers.push(parseImportNamespaceSpecifier());
                    } else if (match('{')) {
                        // import foo, {bar}
                        specifiers = specifiers.concat(parseNamedImports());
                    } else {
                        throwUnexpectedToken(lookahead);
                    }
                }
            } else {
                throwUnexpectedToken(lex());
            }

            if (!matchContextualKeyword('from')) {
                throwError(lookahead.value ?
                        Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
            }
            lex();
            src = parseModuleSpecifier();
        }

        consumeSemicolon();
        return node.finishImportDeclaration(specifiers, src);
    }

    // ECMA-262 15.1 Scripts

    function parseScriptBody() {
        var statement, body = [], token, directive, firstRestricted;

        while (startIndex < length) {
            token = lookahead;
            if (token.type !== Token.StringLiteral) {
                break;
            }

            statement = parseStatementListItem();
            body.push(statement);
            if (statement.expression.type !== Syntax.Literal) {
                // this is not directive
                break;
            }
            directive = source.slice(token.start + 1, token.end - 1);
            if (directive === 'use strict') {
                strict = true;
                if (firstRestricted) {
                    tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral);
                }
            } else {
                if (!firstRestricted && token.octal) {
                    firstRestricted = token;
                }
            }
        }

        while (startIndex < length) {
            statement = parseStatementListItem();
            /* istanbul ignore if */
            if (typeof statement === 'undefined') {
                break;
            }
            body.push(statement);
        }
        return body;
    }

    function parseProgram() {
        var body, node;

        peek();
        node = new Node();

        body = parseScriptBody();
        return node.finishProgram(body, state.sourceType);
    }

    function filterTokenLocation() {
        var i, entry, token, tokens = [];

        for (i = 0; i < extra.tokens.length; ++i) {
            entry = extra.tokens[i];
            token = {
                type: entry.type,
                value: entry.value
            };
            if (entry.regex) {
                token.regex = {
                    pattern: entry.regex.pattern,
                    flags: entry.regex.flags
                };
            }
            if (extra.range) {
                token.range = entry.range;
            }
            if (extra.loc) {
                token.loc = entry.loc;
            }
            tokens.push(token);
        }

        extra.tokens = tokens;
    }

    function tokenize(code, options, delegate) {
        var toString,
            tokens;

        toString = String;
        if (typeof code !== 'string' && !(code instanceof String)) {
            code = toString(code);
        }

        source = code;
        index = 0;
        lineNumber = (source.length > 0) ? 1 : 0;
        lineStart = 0;
        startIndex = index;
        startLineNumber = lineNumber;
        startLineStart = lineStart;
        length = source.length;
        lookahead = null;
        state = {
            allowIn: true,
            allowYield: true,
            labelSet: {},
            inFunctionBody: false,
            inIteration: false,
            inSwitch: false,
            lastCommentStart: -1,
            curlyStack: []
        };

        extra = {};

        // Options matching.
        options = options || {};

        // Of course we collect tokens here.
        options.tokens = true;
        extra.tokens = [];
        extra.tokenValues = [];
        extra.tokenize = true;
        extra.delegate = delegate;

        // The following two fields are necessary to compute the Regex tokens.
        extra.openParenToken = -1;
        extra.openCurlyToken = -1;

        extra.range = (typeof options.range === 'boolean') && options.range;
        extra.loc = (typeof options.loc === 'boolean') && options.loc;

        if (typeof options.comment === 'boolean' && options.comment) {
            extra.comments = [];
        }
        if (typeof options.tolerant === 'boolean' && options.tolerant) {
            extra.errors = [];
        }

        try {
            peek();
            if (lookahead.type === Token.EOF) {
                return extra.tokens;
            }

            lex();
            while (lookahead.type !== Token.EOF) {
                try {
                    lex();
                } catch (lexError) {
                    if (extra.errors) {
                        recordError(lexError);
                        // We have to break on the first error
                        // to avoid infinite loops.
                        break;
                    } else {
                        throw lexError;
                    }
                }
            }

            tokens = extra.tokens;
            if (typeof extra.errors !== 'undefined') {
                tokens.errors = extra.errors;
            }
        } catch (e) {
            throw e;
        } finally {
            extra = {};
        }
        return tokens;
    }

    function parse(code, options) {
        var program, toString;

        toString = String;
        if (typeof code !== 'string' && !(code instanceof String)) {
            code = toString(code);
        }

        source = code;
        index = 0;
        lineNumber = (source.length > 0) ? 1 : 0;
        lineStart = 0;
        startIndex = index;
        startLineNumber = lineNumber;
        startLineStart = lineStart;
        length = source.length;
        lookahead = null;
        state = {
            allowIn: true,
            allowYield: true,
            labelSet: {},
            inFunctionBody: false,
            inIteration: false,
            inSwitch: false,
            lastCommentStart: -1,
            curlyStack: [],
            sourceType: 'script'
        };
        strict = false;

        extra = {};
        if (typeof options !== 'undefined') {
            extra.range = (typeof options.range === 'boolean') && options.range;
            extra.loc = (typeof options.loc === 'boolean') && options.loc;
            extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment;

            if (extra.loc && options.source !== null && options.source !== undefined) {
                extra.source = toString(options.source);
            }

            if (typeof options.tokens === 'boolean' && options.tokens) {
                extra.tokens = [];
            }
            if (typeof options.comment === 'boolean' && options.comment) {
                extra.comments = [];
            }
            if (typeof options.tolerant === 'boolean' && options.tolerant) {
                extra.errors = [];
            }
            if (extra.attachComment) {
                extra.range = true;
                extra.comments = [];
                extra.bottomRightStack = [];
                extra.trailingComments = [];
                extra.leadingComments = [];
            }
            if (options.sourceType === 'module') {
                // very restrictive condition for now
                state.sourceType = options.sourceType;
                strict = true;
            }
        }

        try {
            program = parseProgram();
            if (typeof extra.comments !== 'undefined') {
                program.comments = extra.comments;
            }
            if (typeof extra.tokens !== 'undefined') {
                filterTokenLocation();
                program.tokens = extra.tokens;
            }
            if (typeof extra.errors !== 'undefined') {
                program.errors = extra.errors;
            }
        } catch (e) {
            throw e;
        } finally {
            extra = {};
        }

        return program;
    }

    // Sync with *.json manifests.
    exports.version = '2.7.3';

    exports.tokenize = tokenize;

    exports.parse = parse;

    // Deep copy.
    /* istanbul ignore next */
    exports.Syntax = (function () {
        var name, types = {};

        if (typeof Object.create === 'function') {
            types = Object.create(null);
        }

        for (name in Syntax) {
            if (Syntax.hasOwnProperty(name)) {
                types[name] = Syntax[name];
            }
        }

        if (typeof Object.freeze === 'function') {
            Object.freeze(types);
        }

        return types;
    }());

}));
/* vim: set sw=4 ts=4 et tw=80 : */


/***/ }),

/***/ "+xTY":
/*!*************************************************!*\
  !*** ./node_modules/mdi-react/InstagramIcon.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var InstagramIcon = function InstagramIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M7.8,2H16.2C19.4,2 22,4.6 22,7.8V16.2C22,19.4 19.4,22 16.2,22H7.8C4.6,22 2,19.4 2,16.2V7.8C2,4.6 4.6,2 7.8,2M7.6,4C5.61,4 4,5.61 4,7.6V16.4C4,18.39 5.61,20 7.6,20H16.4C18.39,20 20,18.39 20,16.4V7.6C20,5.61 18.39,4 16.4,4H7.6M17.25,5.5C17.94,5.5 18.5,6.06 18.5,6.75C18.5,7.44 17.94,8 17.25,8C16.56,8 16,7.44 16,6.75C16,6.06 16.56,5.5 17.25,5.5M12,7C14.76,7 17,9.24 17,12C17,14.76 14.76,17 12,17C9.24,17 7,14.76 7,12C7,9.24 9.24,7 12,7M12,9C10.34,9 9,10.34 9,12C9,13.66 10.34,15 12,15C13.66,15 15,13.66 15,12C15,10.34 13.66,9 12,9Z' })
  );
};

module.exports = InstagramIcon;


/***/ }),

/***/ "//9w":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/se.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var se = moment.defineLocale('se', {
    months : 'ođđajagemánnu_guovvamánnu_njukčamánnu_cuoŋománnu_miessemánnu_geassemánnu_suoidnemánnu_borgemánnu_čakčamánnu_golggotmánnu_skábmamánnu_juovlamánnu'.split('_'),
    monthsShort : 'ođđj_guov_njuk_cuo_mies_geas_suoi_borg_čakč_golg_skáb_juov'.split('_'),
    weekdays : 'sotnabeaivi_vuossárga_maŋŋebárga_gaskavahkku_duorastat_bearjadat_lávvardat'.split('_'),
    weekdaysShort : 'sotn_vuos_maŋ_gask_duor_bear_láv'.split('_'),
    weekdaysMin : 's_v_m_g_d_b_L'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'MMMM D. [b.] YYYY',
        LLL : 'MMMM D. [b.] YYYY [ti.] HH:mm',
        LLLL : 'dddd, MMMM D. [b.] YYYY [ti.] HH:mm'
    },
    calendar : {
        sameDay: '[otne ti] LT',
        nextDay: '[ihttin ti] LT',
        nextWeek: 'dddd [ti] LT',
        lastDay: '[ikte ti] LT',
        lastWeek: '[ovddit] dddd [ti] LT',
        sameElse: 'L'
    },
    relativeTime : {
        future : '%s geažes',
        past : 'maŋit %s',
        s : 'moadde sekunddat',
        ss: '%d sekunddat',
        m : 'okta minuhta',
        mm : '%d minuhtat',
        h : 'okta diimmu',
        hh : '%d diimmut',
        d : 'okta beaivi',
        dd : '%d beaivvit',
        M : 'okta mánnu',
        MM : '%d mánut',
        y : 'okta jahki',
        yy : '%d jagit'
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return se;

})));


/***/ }),

/***/ "//Jx":
/*!*****************************************!*\
  !*** ./node_modules/ajv/lib/keyword.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var IDENTIFIER = /^[a-z_$][a-z0-9_$\-]*$/i;
var customRuleCode = __webpack_require__(/*! ./dotjs/custom */ "cjZW");

module.exports = {
  add: addKeyword,
  get: getKeyword,
  remove: removeKeyword
};

/**
 * Define custom keyword
 * @this  Ajv
 * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords).
 * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`.
 */
function addKeyword(keyword, definition) {
  /* jshint validthis: true */
  /* eslint no-shadow: 0 */
  var RULES = this.RULES;

  if (RULES.keywords[keyword])
    throw new Error('Keyword ' + keyword + ' is already defined');

  if (!IDENTIFIER.test(keyword))
    throw new Error('Keyword ' + keyword + ' is not a valid identifier');

  if (definition) {
    if (definition.macro && definition.valid !== undefined)
      throw new Error('"valid" option cannot be used with macro keywords');

    var dataType = definition.type;
    if (Array.isArray(dataType)) {
      var i, len = dataType.length;
      for (i=0; i<len; i++) checkDataType(dataType[i]);
      for (i=0; i<len; i++) _addRule(keyword, dataType[i], definition);
    } else {
      if (dataType) checkDataType(dataType);
      _addRule(keyword, dataType, definition);
    }

    var $data = definition.$data === true && this._opts.$data;
    if ($data && !definition.validate)
      throw new Error('$data support: "validate" function is not defined');

    var metaSchema = definition.metaSchema;
    if (metaSchema) {
      if ($data) {
        metaSchema = {
          anyOf: [
            metaSchema,
            { '$ref': 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/$data.json#' }
          ]
        };
      }
      definition.validateSchema = this.compile(metaSchema, true);
    }
  }

  RULES.keywords[keyword] = RULES.all[keyword] = true;


  function _addRule(keyword, dataType, definition) {
    var ruleGroup;
    for (var i=0; i<RULES.length; i++) {
      var rg = RULES[i];
      if (rg.type == dataType) {
        ruleGroup = rg;
        break;
      }
    }

    if (!ruleGroup) {
      ruleGroup = { type: dataType, rules: [] };
      RULES.push(ruleGroup);
    }

    var rule = {
      keyword: keyword,
      definition: definition,
      custom: true,
      code: customRuleCode,
      implements: definition.implements
    };
    ruleGroup.rules.push(rule);
    RULES.custom[keyword] = rule;
  }


  function checkDataType(dataType) {
    if (!RULES.types[dataType]) throw new Error('Unknown type ' + dataType);
  }
}


/**
 * Get keyword
 * @this  Ajv
 * @param {String} keyword pre-defined or custom keyword.
 * @return {Object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise.
 */
function getKeyword(keyword) {
  /* jshint validthis: true */
  var rule = this.RULES.custom[keyword];
  return rule ? rule.definition : this.RULES.keywords[keyword] || false;
}


/**
 * Remove keyword
 * @this  Ajv
 * @param {String} keyword pre-defined or custom keyword.
 */
function removeKeyword(keyword) {
  /* jshint validthis: true */
  var RULES = this.RULES;
  delete RULES.keywords[keyword];
  delete RULES.all[keyword];
  delete RULES.custom[keyword];
  for (var i=0; i<RULES.length; i++) {
    var rules = RULES[i].rules;
    for (var j=0; j<rules.length; j++) {
      if (rules[j].keyword == keyword) {
        rules.splice(j, 1);
        break;
      }
    }
  }
}


/***/ }),

/***/ "/0O1":
/*!***************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/walkObject.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

exports.isPlainObject = isPlainObject;
exports.makeAttrSetterPath = makeAttrSetterPath;
exports.default = walkObject;
function isPlainObject(input) {
  return input && !Array.isArray(input) && (typeof input === 'undefined' ? 'undefined' : _typeof(input)) === 'object';
}

/*
 * Helper function for _walkObject
 */
function doArrayWalk(key, value, walkArrays, walkArraysMatchingKeys) {
  if (!Array.isArray(value)) {
    return false;
  }

  if (walkArrays || walkArraysMatchingKeys && walkArraysMatchingKeys.includes(key)) {
    return true;
  }

  return false;
}

/*
 * Helper utility for path accumulation in _walkObject. Supports array
 * path accumulation and also Plotly.js nestedProperty style.
 */
function getPath() {
  var pathType = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'array';
  var _path = arguments[1];

  return {
    _path: _path || (pathType === 'array' ? [] : ''),
    set: function set(parent, key) {
      var nextPath = void 0;
      switch (pathType) {
        case 'array':
          nextPath = this._path.concat([key]);
          break;

        case 'nestedProperty':
          if (this._path.length === 0) {
            nextPath = key;
          } else if (Array.isArray(parent)) {
            nextPath = this._path + ('[' + key + ']');
          } else {
            nextPath = this._path + '.' + key;
          }
          break;

        default:
          throw new Error('unrecognized pathType ' + pathType);
      }

      return getPath(pathType, nextPath);
    },
    get: function get(parent, key) {
      // in array mode we do not return the leaf node key.
      if (pathType === 'array') {
        return this._path;
      }

      // in nestedProperty mode we return full path including final key
      return this.set(parent, key)._path;
    }
  };
}

/*
 * Helper function that transforms an array of path parts into a single path.
 * For example:
 *
 *  ['_fullData', 0, 'transforms', 3, 'type'] => 'transforms[3].type'
 *
 * Note that it strips out the _fullData part (and also _fullInput) since that's
 * usually present in the attribute path but isn't necessary in the attribute
 * string since it's usually implicitly applied through the userDataIndex.
 */
function makeAttrSetterPath(parts) {
  var path = '';

  // Truncate the leading parts that aren't intersting when applying changes:
  var i0 = 0;
  if (parts[i0] === '_fullData') {
    i0 += 2;
  }
  if (parts[i0] === '_fullInput') {
    i0++;
  }
  if (parts[i0] === '_fullLayout') {
    i0++;
  }

  for (var i = i0; i < parts.length; i++) {
    if (typeof parts[i] === 'number' || Array.isArray(parts[i])) {
      path += '[' + (Array.isArray(parts[i]) ? parts[i][0] : parts[i]) + ']';
    } else {
      path += (i > i0 ? '.' : '') + parts[i];
    }
  }
  return path;
}

/**
 * The function that walkObject calls at each node.
 *
 * @callback walkObjectCallback
 * @param {string|number} key The current key, which may be nested.
 * @param {object} parent The object which owns the 'key' as a prop.
 * @param {Array} path The keys that lead to the 'parent' object.
 * @returns {boolean} True if the value at 'key' should *not* be traversed into
 *                    if it happens to be an object. I.e., you don't need to
 *                    return anything if you want the default traversal of the
 *                    whole object.
 */

/**
 * Walks through object and recurses if necessary.
 *
 * @param {object} object The top-level or nested object we're walking through.
 * @param {walkObjectCallback} callback Called at each object node.
 * @param {Array} path The keys that lead from to top-level object to this one.
 * @param {object} config configuration object
 * @param {string} config.walkArrays flag allowing array walking
 * @param {Array} config.walkArraysMatchingKeys An array of keys permitting
 *                                              array walking
 * @param {string} config.pathType Either 'array' or 'nestedProperty'. Array
 *                                 based paths return string keys in an array up
 *                                 until the current key position.
 *                                 NestedProperty style returns a single
 *                                 concatenated "nestedProperty" style string.
 * @returns {void}
 * @private
 */
function _walkObject(object, callback, path, config) {
  var walkArrays = config.walkArrays,
      walkArraysMatchingKeys = config.walkArraysMatchingKeys;

  Object.keys(object).forEach(function (key) {
    // Callback can force traversal to stop by returning `true`.
    if (callback(key, object, path.get(object, key))) {
      return;
    }

    var value = object[key];
    if (isPlainObject(value) || doArrayWalk(key, value, walkArrays, walkArraysMatchingKeys)) {
      _walkObject(value, callback, path.set(object, key), config);
    }
  });
}

/**
 * General function to walk object and call the given callback for each node.
 *
 * @param {Object|Array} input The object or array we want to walk.
 * @param {walkObjectCallback} callback Called at each object node.
 * @param {Object} [config] configuration object
 * @param {Boolean} [config.walkArrays] flag allowing array walking
 * @param {Array} [config.walkArraysMatchingKeys] An array of keys permitting
 *                                              array walking
 * @param {String} [config.pathType] Either 'array' or 'nestedProperty'. Array
 *                                   based paths return string keys in an array
 *                                   up until the current key position.
 *                                   NestedProperty style returns a single
 *                                   concatenated "nestedProperty" style string
 *                                   with the current key included in the path.
 *                                   Defaults to "array"
 * @returns {void}
 */
function walkObject(input, callback) {
  var config = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

  if (!isPlainObject(input) && !Array.isArray(input)) {
    throw new Error('The input must be an object.');
  }
  var path = getPath(config.pathType);
  _walkObject(input, callback, path, config);
}
//# sourceMappingURL=walkObject.js.map

/***/ }),

/***/ "/3NQ":
/*!**********************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/react-chart-editor/lib/react-chart-editor.css ***!
  \**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*\n * Layout\n */\n/*\n * Typography\n */\n/*\n * SPACING\n */\n/*\n * BORDERS\n */\n/*\n * Typography\n */\n/*\n * Effects\n */\n.\\+flex {\n  display: flex; }\n\n.\\+cursor-clickable {\n  cursor: pointer; }\n\n.\\+hover-grey:hover {\n  color: var(--color-text-active); }\n\n.\\+error {\n  border-color: var(--color-sienna) !important;\n  outline-color: var(--color-sienna) !important; }\n\n@keyframes fade-in {\n  from {\n    opacity: 0; }\n  to {\n    opacity: 1; } }\n\n@keyframes fade-and-slide-in-from-bottom {\n  from {\n    opacity: 0;\n    transform: translateY(20px); }\n  to {\n    opacity: 1;\n    transform: none; } }\n\n@keyframes fsbr {\n  from {\n    opacity: 1;\n    transform: none; }\n  to {\n    opacity: 0;\n    transform: translateY(20px); } }\n\n@keyframes fade-out {\n  from {\n    opacity: 1; }\n  to {\n    opacity: 0; } }\n\n.animate--fade-in, .editor_controls .modal__backdrop {\n  opacity: 0;\n  animation: fade-in 0.1s forwards cubic-bezier(0.19, 1, 0.22, 1); }\n\n.animate--fade-out, .editor_controls .modal--animate-out .modal__backdrop {\n  opacity: 1;\n  animation: fade-out 0.1s forwards cubic-bezier(0.19, 1, 0.22, 1); }\n\n.animate--fade-and-slide-in-from-bottom, .editor_controls .modal__card {\n  opacity: 0;\n  transform: translateY(20px);\n  animation: fade-and-slide-in-from-bottom 0.1s forwards cubic-bezier(0.19, 1, 0.22, 1); }\n\n.animate--fsbr, .editor_controls .modal--animate-out .modal__card {\n  opacity: 1;\n  transform: none;\n  animation: fsbr 0.1s forwards cubic-bezier(0.19, 1, 0.22, 1); }\n\n:root {\n  --env: $ENV; }\n\n.plotly-editor--theme-provider {\n  --color-white: #ffffff;\n  --color-rhino-core: #2a3f5f;\n  --color-rhino-dark: #506784;\n  --color-rhino-medium-1: #a2b1c6;\n  --color-rhino-medium-2: #c8d4e3;\n  --color-rhino-light-1: #dfe8f3;\n  --color-rhino-light-2: #ebf0f8;\n  --color-rhino-light-3: #f3f6fa;\n  --color-rhino-light-4: #fafbfd;\n  --color-rhino-light-5: #f8f8f9;\n  --color-dodger: #119dff;\n  --color-dodger-shade: #0d76bf;\n  --color-dodger-shade-mid: #0d76bf;\n  --color-aqua: #09ffff;\n  --color-aqua-shade: #19d3f3;\n  --color-lavender: #e763fa;\n  --color-lavender-shade: #ab63fa;\n  --color-lavender-shade-mid: #934bde;\n  --color-cornflower: #636efa;\n  --color-emerald: #00cc96;\n  --color-sienna: #ef553b;\n  --color-accent: var(--color-dodger);\n  --color-accent-shade: var(--color-dodger-shade);\n  --color-accent-shade-mid: var(--color-dodger-shade-mid);\n  --color-brand: var(--color-dodger);\n  --color-hightlight-darker: var(--color-gray-blue-pale);\n  --color-text-base: var(--color-rhino-dark);\n  --color-text-light: var(--color-rhino-medium-1);\n  --color-text-dark: var(--color-rhino-core);\n  --color-text-headings: var(--color-text-dark);\n  --color-text-section-header: var(--color-text-dark);\n  --color-text-active: var(--color-rhino-core);\n  --color-text-placeholder: var(--color-rhino-medium-1);\n  --color-border-default: var(--color-rhino-medium-2);\n  --color-border-light: var(--color-rhino-light-1);\n  --color-border-dark: var(--color-rhino-medium-1);\n  --color-border-accent: var(--color-accent);\n  --color-border-accent-shade: var(--color-accent-shade);\n  --color-background: var(--color-rhino-light-2);\n  --color-background-base: var(--color-rhino-light-2);\n  --color-background-light: var(--color-rhino-light-3);\n  --color-background-medium: var(--color-rhino-light-1);\n  --color-background-dark: var(--color-rhino-medium-1);\n  --color-background-top: var(--color-white);\n  --color-background-inverse: var(--color-rhino-dark);\n  --color-background-inputs: var(--color-background-top);\n  --color-button-primary-base-fill: var(--color-accent);\n  --color-button-primary-base-border: var(--color-accent-shade);\n  --color-button-primary-base-text: var(--color-white);\n  --color-button-primary-hover-fill: var(--color-accent-shade-mid);\n  --color-button-primary-hover-border: var(--color-accent-shade);\n  --color-button-primary-hover-text: var(--color-white);\n  --color-button-primary-active-fill: var(--color-accent-shade);\n  --color-button-primary-active-border: var(--color-accent-shade);\n  --color-button-primary-active-text: var(--color-white);\n  --color-button-secondary-base-fill: transparent;\n  --color-button-secondary-base-border: var(--color-rhino-medium-2);\n  --color-button-secondary-base-text: var(--color-text-base);\n  --color-button-secondary-hover-fill: transparent;\n  --color-button-secondary-hover-border: var(--color-rhino-medium-1);\n  --color-button-secondary-hover-text: var(--color-text-dark);\n  --color-button-secondary-active-fill: transparent;\n  --color-button-secondary-active-border: var(--color-rhino-medium-1);\n  --color-button-secondary-active-text: var(--color-text-dark);\n  --color-button-tertiary-base-fill: transparent;\n  --color-button-tertiary-base-border: transparent;\n  --color-button-tertiary-base-text: var(--color-text-base);\n  --color-button-tertiary-hover-fill: transparent;\n  --color-button-tertiary-hover-border: transparent;\n  --color-button-tertiary-hover-text: var(--color-text-dark);\n  --color-button-tertiary-active-fill: transparent;\n  --color-button-tertiary-active-border: transparent;\n  --color-button-tertiary-active-text: var(--color-text-dark);\n  --color-button-default-base-fill: var(--color-background-light);\n  --color-button-default-base-border: var(--color-border-default);\n  --color-button-default-base-text: var(--color-text-base);\n  --color-button-default-hover-fill: var(--color-background-base);\n  --color-button-default-hover-border: var(--color-border-dark);\n  --color-button-default-hover-text: var(--color-text-dark);\n  --color-button-default-active-fill: var(--color-background-dark);\n  --color-button-default-active-border: var(--color-border-dark);\n  --color-button-default-active-text: var(--color-text-dark);\n  --color-button-upgrade-base-fill: var(--color-lavender-shade);\n  --color-button-upgrade-base-border: var(--color-lavender-shade-dark);\n  --color-button-upgrade-base-text: var(--color-white);\n  --color-button-upgrade-hover-fill: var(--color-lavender-shade-mid);\n  --color-button-upgrade-hover-border: var(--color-lavender-shade-dark);\n  --color-button-upgrade-hover-text: var(--color-white);\n  --color-button-upgrade-active-fill: var(--color-lavender-shade-dark);\n  --color-button-upgrade-active-border: var(--color-lavender-shade-dark);\n  --color-button-upgrade-active-text: var(--color-white);\n  --color-button-header-base-fill: transparent;\n  --color-button-header-base-border: var(--color-dodger);\n  --color-button-header-base-text: var(--color-dodger);\n  --color-button-header-hover-fill: transparent;\n  --color-button-header-hover-border: var(--color-dodger-shade-mid);\n  --color-button-header-hover-text: var(--color-dodger-shade);\n  --color-button-header-active-fill: transparent;\n  --color-button-header-active-border: var(--color-dodger-shade);\n  --color-button-header-active-text: var(--color-dodger-shade);\n  --spacing-base-unit: 24px;\n  --spacing-half-unit: 12px;\n  --spacing-quarter-unit: 6px;\n  --spacing-sixth-unit: 4px;\n  --spacing-eighth-unit: 3px;\n  --font-size-base: 13px;\n  --font-size-small: 12px;\n  --font-size-medium: 14px;\n  --font-size-large: 14px;\n  --font-size-heading-base: 24px;\n  --font-size-heading-small: 18px;\n  --font-size-heading-large: 28px;\n  --font-size-h5: 16px;\n  --font-weight-light: 400;\n  --font-weight-normal: 500;\n  --font-weight-semibold: 600;\n  --font-weight-bold: 700;\n  --font-leading-body: 1.6;\n  --font-leading-head: 1.2;\n  --font-letter-spacing-headings: 0.5px;\n  --font-family-body: \"Open Sans\", --apple-default, sans-serif;\n  --font-family-headings: \"Dosis\", \"Arial\", sans-serif;\n  --border-default: 1px solid var(--color-border-default);\n  --border-light: 1px solid var(--color-border-light);\n  --border-dark: 1px solid var(--color-border-dark);\n  --border-accent: 1px solid var(--color-border-accent);\n  --border-accent-shade: 1px solid var(--color-border-accent-shade);\n  --border-radius: 5px;\n  --border-radius-small: 3px;\n  --text-shadow-dark-color: rgba(42, 63, 95, 0.7);\n  --text-shadow-dark-ui: 0 1px 2px var(--text-shadow-dark-color);\n  --text-shadow-dark-ui-inactive: 0 1px 1px rgba(42, 63, 95, 0.4);\n  --box-shadow-base-color: rgba(80, 103, 132, 0.2);\n  --box-shadow-base: 0px 2px 9px var(--box-shadow-base-color);\n  --scrollbar-track-background: var(--color-background-base);\n  --scrollbar-thumb-color: var(--color-accent);\n  --panel-background: var(--color-background-base);\n  --panel-width: 335px;\n  --fold-header-text-color-base: var(--color-white);\n  --fold-header-text-color-closed: var(--color-white);\n  --fold-header-background-base: var(--color-rhino-dark);\n  --fold-header-background-closed: var(--color-rhino-core);\n  --fold-header-border-color-closed: var(--color-rhino-core);\n  --fold-header-border-color-base: var(--color-rhino-dark);\n  --sidebar-background: var(--color-background-top);\n  --sidebar-width: 100px;\n  --sidebar-group-background-base: var(--sidebar-background);\n  --sidebar-item-background-base: var(--color-background-light);\n  --sidebar-item-background-hover: var(--color-background-base);\n  --sidebar-item-background-active: var(--color-background-medium);\n  --editor-width: calc(\n    var(--sidebar-width) + var(--panel-width) + 1px\n  ); }\n\n.editor_controls {\n  position: relative;\n  width: var(--editor-width);\n  flex-shrink: 0;\n  overflow: hidden;\n  display: flex;\n  /* TODO: Don't inline Draft.css; load it with `systemjs`. */\n  /**\n * Draft v0.3.0\n *\n * Copyright (c) 2013-present, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n */\n  /**\n* Rangeslider\n*/\n  /**\n* Rangeslider - Horizontal slider\n*/\n  /**\n* Rangeslider - Vertical slider\n*/\n  /**\n* Rangeslider - Reverse\n*/\n  /**\n* Rangeslider - Labels\n*/\n  /* -------------------------------------------------------------------\n  Microtip\n\n  Modern, lightweight css-only tooltips\n  Just 1kb minified and gzipped\n\n  @author Ghosh\n  @package Microtip\n\n----------------------------------------------------------------------\n  1. Base Styles\n  2. Direction Modifiers\n  3. Position Modifiers\n--------------------------------------------------------------------*/\n  /* ------------------------------------------------\n  [1] Base Styles\n-------------------------------------------------*/\n  /* ------------------------------------------------\n  [2] Position Modifiers\n-------------------------------------------------*/\n  /* ------------------------------------------------\n  [2.1] Top Left\n-------------------------------------------------*/\n  /* ------------------------------------------------\n  [2.2] Top Right\n-------------------------------------------------*/\n  /* ------------------------------------------------\n  [2.3] Bottom\n-------------------------------------------------*/\n  /* ------------------------------------------------\n  [2.4] Bottom Left\n-------------------------------------------------*/\n  /* ------------------------------------------------\n  [2.5] Bottom Right\n-------------------------------------------------*/\n  /* ------------------------------------------------\n  [2.6] Left\n-------------------------------------------------*/\n  /* ------------------------------------------------\n  [2.7] Right\n-------------------------------------------------*/\n  /* ------------------------------------------------\n  [3] Size\n-------------------------------------------------*/\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale;\n  font-family: var(--font-family-body); }\n  .editor_controls .sidebar {\n    user-select: none;\n    height: 100%;\n    min-width: var(--sidebar-width);\n    width: var(--sidebar-width);\n    max-width: var(--sidebar-width);\n    text-align: center;\n    background: var(--sidebar-background);\n    overflow-y: auto;\n    overflow-x: hidden;\n    float: left;\n    border-right: var(--border-default);\n    flex-grow: 1;\n    -webkit-overflow-scrolling: touch;\n    -ms-overflow-style: none; }\n    .editor_controls .sidebar::-webkit-scrollbar {\n      background: white;\n      width: 0px; }\n    .editor_controls .sidebar::-webkit-scrollbar-track {\n      box-shadow: none;\n      background: var(--scrollbar-track-background); }\n    .editor_controls .sidebar::-webkit-scrollbar-thumb {\n      background-color: var(--scrollbar-thumb-color);\n      border-radius: 10px; }\n    .editor_controls .sidebar__group {\n      background-color: var(--sidebar-group-background-base);\n      cursor: pointer;\n      width: 100%; }\n      .editor_controls .sidebar__group__title {\n        color: var(--color-text-base);\n        font-size: var(--font-size-medium);\n        font-weight: var(--font-weight-normal);\n        padding: var(--spacing-half-unit) 0;\n        text-transform: capitalize;\n        text-align: left;\n        border-bottom: var(--border-light);\n        display: flex;\n        position: relative; }\n        .editor_controls .sidebar__group__title__label {\n          padding-left: var(--spacing-base-unit); }\n        .editor_controls .sidebar__group__title__icon {\n          position: absolute;\n          transform: scale(0.9) translateX(2px) translateY(-4px);\n          transform-origin: center center;\n          opacity: 0.5;\n          transition: all 0.15s ease-in-out; }\n          .editor_controls .sidebar__group__title__icon svg path {\n            fill: currentColor; }\n      .editor_controls .sidebar__group:hover .sidebar__group__title__icon {\n        opacity: 1; }\n      .editor_controls .sidebar__group--is-active {\n        color: var(--color-text-active);\n        cursor: default; }\n        .editor_controls .sidebar__group--is-active .sidebar__group__title__label {\n          font-weight: var(--font-weight-semibold);\n          color: var(--color-text-active); }\n        .editor_controls .sidebar__group--is-active .sidebar__group__title__icon {\n          opacity: 1; }\n          .editor_controls .sidebar__group--is-active .sidebar__group__title__icon svg path {\n            fill: var(--color-accent); }\n      .editor_controls .sidebar__group--is-expanded .sidebar__group__title__icon {\n        transform: scale(0.9) translateY(-5px) rotate(90deg);\n        opacity: 1; }\n      .editor_controls .sidebar__group--is-expanded .sidebar__group__title {\n        position: relative;\n        z-index: 4;\n        box-shadow: var(--box-shadow-base); }\n    .editor_controls .sidebar__item {\n      color: var(--color-text-base);\n      cursor: pointer;\n      font-size: var(--font-size-medium);\n      font-weight: var(--font-weight-normal);\n      line-height: var(--font-size-medium);\n      text-transform: capitalize;\n      background-color: var(--sidebar-item-background-base);\n      padding: 10px;\n      padding-left: 18px;\n      padding-right: var(--spacing-quarter-unit);\n      text-align: left;\n      border-bottom: var(--border-light);\n      position: relative;\n      overflow: hidden; }\n      .editor_controls .sidebar__item--single {\n        margin-top: 15px; }\n        .editor_controls .sidebar__item--single:last-child {\n          margin-bottom: 15px; }\n      .editor_controls .sidebar__item::before {\n        content: '';\n        position: absolute;\n        height: 100%;\n        top: 0;\n        left: 0;\n        width: 5px;\n        background-color: var(--color-accent);\n        transform: scaleX(0);\n        transform-origin: left center;\n        will-change: transform;\n        transition: all 0.15s ease-in-out; }\n      .editor_controls .sidebar__item span {\n        display: block;\n        will-change: transform;\n        transition: all 0.15s ease-in-out; }\n      .editor_controls .sidebar__item:not(.sidebar__item--is-active):hover {\n        background-color: var(--sidebar-item-background-hover); }\n      .editor_controls .sidebar__item--is-active {\n        color: var(--color-text-active);\n        font-weight: var(--font-weight-semibold);\n        cursor: default; }\n        .editor_controls .sidebar__item--is-active::before {\n          transform: none; }\n        .editor_controls .sidebar__item--is-active span {\n          transform: translateX(5px); }\n    .editor_controls .sidebar__logo {\n      height: 50px;\n      margin: 10px; }\n  .editor_controls .panel {\n    flex-grow: 1;\n    overflow-x: hidden;\n    overflow-y: auto;\n    padding: var(--spacing-half-unit);\n    box-sizing: border-box;\n    position: relative;\n    display: flex;\n    flex-direction: column;\n    width: 100%;\n    -webkit-overflow-scrolling: touch; }\n    .editor_controls .panel::-webkit-scrollbar {\n      background: white;\n      width: 5px; }\n    .editor_controls .panel::-webkit-scrollbar-track {\n      box-shadow: none;\n      background: var(--scrollbar-track-background); }\n    .editor_controls .panel::-webkit-scrollbar-thumb {\n      background-color: var(--scrollbar-thumb-color);\n      border-radius: 10px; }\n    .editor_controls__wrapper > .panel {\n      background-color: var(--panel-background);\n      border-right: var(--border-default);\n      width: calc(var(--panel-width)); }\n    .editor_controls .panel__content {\n      flex-grow: 1;\n      display: flex;\n      flex-direction: column; }\n    .editor_controls .panel__header {\n      margin-bottom: var(--spacing-half-unit);\n      display: flex;\n      flex-shrink: 0; }\n      .editor_controls .panel__header__content {\n        flex-grow: 1; }\n      .editor_controls .panel__header__actions__container {\n        width: 100%; }\n      .editor_controls .panel__header__collapse {\n        font-size: var(--font-size-medium);\n        float: left;\n        color: var(--color-text-base);\n        display: flex;\n        align-items: center;\n        height: 100%;\n        cursor: pointer; }\n        .editor_controls .panel__header__collapse svg {\n          width: 16px !important;\n          height: 16px !important;\n          fill: var(--color-text-light);\n          padding-right: 3px; }\n      .editor_controls .panel__header__action {\n        float: right; }\n    .editor_controls .panel__empty {\n      position: absolute;\n      top: 0;\n      right: 0;\n      width: var(--panel-width);\n      border-right: var(--border-default);\n      height: 100%;\n      padding: var(--spacing-half-unit);\n      background-color: var(--panel-background);\n      box-sizing: border-box;\n      z-index: 1003;\n      display: flex; }\n      .editor_controls .panel__empty__message {\n        text-align: center; }\n        .editor_controls .panel__empty__message__icon {\n          padding-top: calc(var(--spacing-base-unit) * 2);\n          margin-bottom: var(--spacing-half-unit);\n          opacity: 0.5; }\n          .editor_controls .panel__empty__message__icon svg {\n            width: 48px !important;\n            height: 48px !important; }\n            .editor_controls .panel__empty__message__icon svg path {\n              fill: var(--color-text-light); }\n        .editor_controls .panel__empty__message__heading {\n          color: var(--color-text-headings);\n          font-size: var(--font-size-heading-base);\n          font-weight: var(--font-weight-normal);\n          line-height: var(--font-leading-head);\n          font-family: var(--font-family-headings);\n          letter-spacing: var(--font-letter-spacing-headings); }\n        .editor_controls .panel__empty__message__content {\n          font-size: var(--font-size-base);\n          color: var(--color-text-base);\n          line-height: var(--font-leading-body); }\n    .editor_controls .panel--no-padding {\n      padding: 0; }\n  .editor_controls .fold .panel {\n    overflow-x: visible;\n    overflow-y: visible; }\n  .editor_controls .fold {\n    width: 100%;\n    user-select: none; }\n    .editor_controls .fold__top {\n      display: flex;\n      justify-content: space-between;\n      clear: both;\n      padding: var(--spacing-quarter-unit) var(--spacing-half-unit);\n      color: var(--fold-header-text-color-closed);\n      font-size: var(--font-size-base);\n      border: 1px solid var(--fold-header-border-color-closed);\n      background-color: var(--fold-header-background-closed);\n      height: 15px;\n      border-radius: var(--border-radius);\n      text-shadow: var(--text-shadow-dark-ui);\n      transition: background-color 0.1s ease-in-out, color 0.1s ease-in-out, border 0.1s ease-in-out; }\n      .editor_controls .fold__top:hover {\n        cursor: pointer;\n        background-color: var(--fold-header-background-closed); }\n      .editor_controls .fold__top svg {\n        width: 18px;\n        height: 18px;\n        display: block;\n        filter: drop-shadow(0 1px 2px rgba(42, 63, 95, 0.7)); }\n        .editor_controls .fold__top svg path {\n          fill: currentColor; }\n      .editor_controls .fold__top--open {\n        color: var(--fold-header-text-color-base);\n        background-color: var(--fold-header-background-base);\n        border: 1px solid var(--fold-header-border-color-base);\n        border-radius: var(--border-radius) var(--border-radius) 0 0;\n        text-shadow: var(--text-shadow-dark-ui-inactive); }\n        .editor_controls .fold__top--open svg {\n          filter: drop-shadow(0 1px 1px rgba(42, 63, 95, 0.4)); }\n        .editor_controls .fold__top--open:hover {\n          background-color: var(--fold-header-background-base); }\n      .editor_controls .fold__top__icon {\n        display: block;\n        margin-right: var(--spacing-quarter-unit);\n        transform: translateY(-1px); }\n      .editor_controls .fold__top__title {\n        margin-left: var(--spacing-half-unit)/3;\n        font-size: var(--font-size-medium);\n        line-height: var(--font-size-medium);\n        font-weight: var(--font-weight-semibold);\n        transform: translateY(1px);\n        white-space: nowrap;\n        max-width: 230px;\n        letter-spacing: 0.2px;\n        text-overflow: ellipsis;\n        overflow: hidden; }\n      .editor_controls .fold__top__arrow {\n        transform: translateX(-3px) translateY(-1px); }\n        .editor_controls .fold__top__arrow svg {\n          will-change: transform;\n          transition: transform 0.1s ease-in-out;\n          transform: rotate(-90deg);\n          font-weight: bold;\n          transform-origin: center center; }\n        .editor_controls .fold__top__arrow-title {\n          display: flex;\n          flex-grow: 1; }\n        .editor_controls .fold__top__arrow--open svg {\n          transform: rotate(0deg); }\n      .editor_controls .fold__top__delete {\n        font-size: 18px;\n        opacity: 0.75;\n        transform: translateY(-2px); }\n        .editor_controls .fold__top__delete:hover {\n          opacity: 1; }\n    .editor_controls .fold__content {\n      background: var(--color-background-top);\n      border: var(--border-default);\n      border-width: 0 1px 1px 1px;\n      border-bottom-left-radius: 5px;\n      border-bottom-right-radius: 5px; }\n      .editor_controls .fold__content__plot {\n        overflow: hidden;\n        border-bottom-left-radius: var(--border-radius);\n        border-bottom-right-radius: var(--border-radius); }\n      .editor_controls .fold__content > *:first-child {\n        border-top: 0; }\n      .editor_controls .fold__content__empty {\n        font-family: var(--font-family-headings);\n        display: flex;\n        flex-direction: column;\n        justify-content: center;\n        padding: 30px 25px; }\n        .editor_controls .fold__content__empty__icon {\n          margin: 0 auto;\n          margin-bottom: 15px;\n          width: 40px;\n          height: 40px;\n          border-radius: 50%;\n          background-color: var(--color-dodger);\n          display: flex;\n          flex-direction: column;\n          justify-content: center; }\n          .editor_controls .fold__content__empty__icon svg {\n            margin: 0 auto !important;\n            fill: white;\n            width: 23px;\n            height: 23px; }\n        .editor_controls .fold__content__empty__message__primary {\n          text-align: center;\n          margin-bottom: 20px;\n          font-size: 17px;\n          color: var(--color-text-base); }\n        .editor_controls .fold__content__empty__message__secondary {\n          font-family: var(--font-family-body);\n          font-size: var(--font-size-small);\n          text-align: center;\n          color: var(--color-text-base); }\n      .editor_controls .fold__content--noheader {\n        border-width: 1px 1px 1px 1px; }\n  .editor_controls .fold {\n    margin-bottom: var(--spacing-half-unit); }\n  .editor_controls .fold .fold:last-child {\n    margin-bottom: 0; }\n  .editor_controls .section__heading {\n    position: relative;\n    display: flex;\n    font-size: var(--font-size-base);\n    color: var(--color-text-section-header);\n    font-weight: var(--font-weight-semibold);\n    cursor: default;\n    background-color: var(--color-background-light);\n    padding: var(--spacing-quarter-unit) var(--spacing-half-unit);\n    clear: both;\n    text-transform: capitalize; }\n  .editor_controls .section:not(:first-child) .section__heading {\n    border-top: var(--border-light); }\n  .editor_controls .section:first-child .section__heading {\n    border-top: 0; }\n  .editor_controls .menupanel {\n    padding-top: 0;\n    display: flex;\n    justify-content: flex-end;\n    flex-grow: 1; }\n    .editor_controls .menupanel--ownline {\n      padding-top: var(--spacing-quarter-unit);\n      width: 100%; }\n    .editor_controls .menupanel__label {\n      font-weight: var(--font-weight-semibold);\n      padding-right: var(--spacing-quarter-unit); }\n    .editor_controls .menupanel__icon {\n      vertical-align: middle;\n      width: 15px !important;\n      height: 15px !important;\n      fill: var(--color-text-light) !important;\n      padding-left: var(--spacing-quarter-unit); }\n      .editor_controls .menupanel__icon svg {\n        display: block; }\n      .editor_controls .menupanel__icon:hover {\n        cursor: pointer;\n        fill: var(--color-accent) !important; }\n      .editor_controls .menupanel__icon-span {\n        font-size: var(--font-size-small);\n        display: flex; }\n        .editor_controls .menupanel__icon-span--question {\n          color: var(--color-text-base); }\n  .editor_controls .info__title {\n    color: var(--color-text-headings);\n    font-size: var(--font-size-heading-small);\n    font-weight: var(--font-weight-normal);\n    line-height: var(--font-leading-head);\n    font-family: var(--font-family-headings);\n    letter-spacing: var(--font-letter-spacing-headings);\n    padding: var(--spacing-half-unit) var(--spacing-half-unit) var(--spacing-quarter-unit) var(--spacing-half-unit); }\n  .editor_controls .info__text {\n    padding: var(--spacing-quarter-unit) var(--spacing-half-unit);\n    color: var(--color-text-base);\n    font-size: var(--font-size-small);\n    font-weight: var(--font-weight-normal);\n    line-height: var(--font-leading-body); }\n  .editor_controls .info__sub-text {\n    color: var(--color-text-base);\n    font-size: var(--font-size-small);\n    font-weight: var(--font-weight-normal);\n    font-style: italic;\n    line-height: var(--font-leading-body);\n    padding: var(--spacing-quarter-unit) var(--spacing-half-unit) var(--spacing-half-unit) var(--spacing-half-unit); }\n  .editor_controls .modalbox {\n    position: absolute;\n    border-radius: var(--border-radius);\n    overflow: hidden;\n    text-transform: none;\n    text-align: left;\n    border: var(--border-default);\n    align-content: center;\n    box-shadow: var(--box-shadow-base);\n    left: calc(var(--spacing-quarter-unit) * -1);\n    width: calc(100% + var(--spacing-half-unit));\n    top: calc(100% + var(--spacing-quarter-unit));\n    background-color: var(--color-background-top);\n    z-index: 9; }\n    .editor_controls .modalbox__cover {\n      position: fixed;\n      top: 0;\n      right: 0;\n      bottom: 0;\n      left: 0;\n      z-index: -1; }\n    .editor_controls .modalbox--dark {\n      background-color: var(--color-background-inverse); }\n    .editor_controls .modalbox--relative {\n      position: relative; }\n  .editor_controls .field .modalbox {\n    width: 100%;\n    left: -1px;\n    top: 100%; }\n  .editor_controls .modal {\n    box-sizing: border-box;\n    position: fixed;\n    top: 0;\n    left: 0;\n    width: 100vw;\n    height: 100vh;\n    display: flex;\n    align-items: flex-start;\n    overflow-y: auto;\n    justify-content: center;\n    z-index: 1003; }\n    .editor_controls .modal * {\n      box-sizing: border-box; }\n    .editor_controls .modal__backdrop {\n      height: 100%;\n      width: 100%;\n      left: 0;\n      top: 0;\n      position: fixed;\n      opacity: 0;\n      will-change: opacity; }\n      .editor_controls .modal__backdrop::before {\n        content: '';\n        height: 100%;\n        width: 100%;\n        left: 0;\n        opacity: 0.5;\n        top: 0;\n        background: var(--color-background-dark);\n        position: fixed; }\n    .editor_controls .modal__card {\n      background: var(--color-background-top);\n      border-radius: var(--border-radius);\n      position: relative;\n      z-index: 1003;\n      max-width: calc(100% - var(--spacing-base-unit));\n      box-shadow: var(--box-shadow-base);\n      display: flex;\n      flex-direction: column;\n      will-change: opacity, transform;\n      flex-grow: 0;\n      margin: 5vh 10vw; }\n    .editor_controls .modal__header {\n      display: flex;\n      justify-content: space-between;\n      align-items: center;\n      color: var(--color-text-base);\n      padding: var(--spacing-half-unit);\n      font-weight: var(--font-weight-semibold); }\n      .editor_controls .modal__header__close {\n        opacity: 0.5; }\n        .editor_controls .modal__header__close:hover {\n          cursor: pointer;\n          opacity: 1; }\n        .editor_controls .modal__header__close svg {\n          display: block; }\n          .editor_controls .modal__header__close svg * {\n            fill: currentColor; }\n    .editor_controls .modal__content {\n      flex-grow: 1;\n      background-color: var(--color-background-light);\n      border-bottom-left-radius: var(--border-radius);\n      border-bottom-right-radius: var(--border-radius); }\n    .editor_controls .modal__backdrop {\n      animation-duration: 1s;\n      animation-delay: 0s; }\n    .editor_controls .modal__card {\n      animation-duration: 0.85s;\n      animation-delay: 0.1s; }\n    .editor_controls .modal--animate-out {\n      pointer-events: none; }\n      .editor_controls .modal--animate-out .modal__backdrop {\n        animation-duration: 0.85s;\n        animation-delay: 0s; }\n      .editor_controls .modal--animate-out .modal__card {\n        animation-duration: 0.85s;\n        animation-delay: 0s; }\n  .editor_controls .panel .react-tabs {\n    flex-grow: 1;\n    display: flex;\n    flex-direction: column; }\n    .editor_controls .panel .react-tabs__tab {\n      flex-grow: 1;\n      flex-shrink: 0;\n      display: flex;\n      align-items: center;\n      justify-content: center;\n      padding: var(--spacing-quarter-unit);\n      color: var(--color-text-base);\n      font-size: var(--font-size-base);\n      background: var(--color-background-medium);\n      border: var(--border-default);\n      border-bottom: 0;\n      position: relative;\n      background: var(--color-background-light);\n      transition: border-color 0.15s ease-in-out; }\n      .editor_controls .panel .react-tabs__tab-list {\n        background: var(--color-background-medium);\n        margin: 0;\n        flex-shrink: 0;\n        list-style: none;\n        display: flex;\n        align-items: flex-end;\n        padding-top: var(--spacing-half-unit);\n        padding-left: var(--spacing-half-unit);\n        padding-right: var(--spacing-half-unit);\n        padding-bottom: 0;\n        height: 32px; }\n      .editor_controls .panel .react-tabs__tab:first-of-type {\n        border-top-left-radius: var(--border-radius); }\n      .editor_controls .panel .react-tabs__tab:last-of-type {\n        border-top-right-radius: var(--border-radius); }\n      .editor_controls .panel .react-tabs__tab:hover {\n        background-color: var(--color-background-base);\n        cursor: pointer; }\n      .editor_controls .panel .react-tabs__tab--selected {\n        background-color: var(--color-background-base);\n        pointer-events: none;\n        margin-top: 0;\n        color: var(--color-text-active);\n        border-top-color: var(--color-accent);\n        border-top-width: 2px; }\n        .editor_controls .panel .react-tabs__tab--selected::before {\n          position: absolute;\n          top: 100%;\n          width: 100%;\n          height: 1px;\n          content: '';\n          background-color: var(--color-background-base);\n          left: 0;\n          z-index: 4; }\n      .editor_controls .panel .react-tabs__tab:not(:first-of-type):not(:last-of-type) {\n        border-left: 0; }\n      .editor_controls .panel .react-tabs__tab:last-of-type {\n        border-left: none; }\n      .editor_controls .panel .react-tabs__tab-panel {\n        border-top: var(--border-default);\n        display: none; }\n        .editor_controls .panel .react-tabs__tab-panel--selected {\n          flex-grow: 1;\n          display: flex;\n          flex-direction: column; }\n  .editor_controls .field {\n    align-items: flex-start;\n    border-top: var(--border-light);\n    color: var(--color-text-base);\n    display: flex;\n    font-size: var(--font-size-base);\n    font-weight: var(--font-weight-normal);\n    justify-content: flex-start;\n    line-height: var(--font-size-base);\n    min-height: 32px;\n    padding: var(--spacing-quarter-unit) 0;\n    width: 100%;\n    position: relative; }\n    .editor_controls .field__no-title {\n      width: 100%;\n      padding: 0 var(--spacing-half-unit);\n      align-self: center;\n      line-height: var(--font-leading-body); }\n      .editor_controls .field__no-title--center {\n        text-align: center; }\n    .editor_controls .field__widget {\n      display: flex;\n      flex-wrap: wrap;\n      flex-basis: 0;\n      padding-right: var(--spacing-half-unit);\n      padding-left: var(--spacing-half-unit);\n      align-self: center; }\n      .editor_controls .field__widget:not(.field__widget--units) {\n        flex-grow: 1; }\n      .editor_controls .field__widget--units {\n        padding-right: 0; }\n    .editor_controls .field__units {\n      align-self: center; }\n    .editor_controls .field__title {\n      width: 80px;\n      padding-left: var(--spacing-half-unit);\n      display: block;\n      font-size: var(--font-size-small);\n      line-height: var(--font-leading-body);\n      color: var(--color-text-base);\n      padding-top: var(--spacing-quarter-unit);\n      user-select: none; }\n      .editor_controls .field__title-text {\n        text-transform: capitalize;\n        cursor: default; }\n    .editor_controls .field__delete {\n      display: flex;\n      align-items: center;\n      justify-content: center;\n      padding-left: var(--spacing-quarter-unit);\n      opacity: 0.5; }\n      .editor_controls .field__delete svg {\n        display: block; }\n        .editor_controls .field__delete svg path {\n          fill: var(--color-text-base); }\n      .editor_controls .field__delete:hover {\n        cursor: pointer;\n        opacity: 1; }\n        .editor_controls .field__delete:hover svg path {\n          fill: var(--color-sienna); }\n    .editor_controls .field__colorscale .field__widget {\n      padding-right: 0; }\n    .editor_controls .field .rect,\n    .editor_controls .field .square {\n      border-color: var(--color-accent); }\n    .editor_controls .field .rect-grid {\n      border-color: var(--panel-background) !important;\n      float: left;\n      border-top: 1px solid;\n      border-left: 1px solid; }\n    .editor_controls .field .rect-container {\n      margin: 0 auto;\n      position: relative;\n      max-width: 294px; }\n  @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {\n    .editor_controls .field__widget {\n      flex-basis: auto; } }\n  .editor_controls .field .field {\n    border-top: none; }\n    .editor_controls .field .field .field__no-title {\n      padding: 0; }\n  .editor_controls .symbol-selector__toggle {\n    border: var(--border-default);\n    border-radius: var(--border-radius);\n    width: 80px;\n    cursor: pointer;\n    padding: var(--spacing-quarter-unit) var(--spacing-quarter-unit) 3px var(--spacing-quarter-unit); }\n    .editor_controls .symbol-selector__toggle:before, .editor_controls .symbol-selector__toggle:after {\n      content: ' ';\n      display: table; }\n    .editor_controls .symbol-selector__toggle:after {\n      clear: both; }\n  .editor_controls .symbol-selector__toggle--dark {\n    background-color: var(--color-background-inverse); }\n  .editor_controls .symbol-selector__toggle__option {\n    float: left; }\n  .editor_controls .symbol-selector__toggle__caret {\n    float: right;\n    fill: var(--color-text-light);\n    padding-top: var(--spacing-eighth-unit);\n    width: 13px !important;\n    height: 13px !important; }\n  .editor_controls .symbol-selector__menu {\n    max-width: 225px;\n    position: absolute;\n    z-index: 1003;\n    border: var(--border-default);\n    padding: var(--spacing-half-unit);\n    box-shadow: 2px 2px var(--spacing-half-unit) var(--color-border-light);\n    border-radius: var(--border-radius-small);\n    left: var(--spacing-base-unit); }\n  .editor_controls .symbol-selector__item {\n    display: inline; }\n  .editor_controls .symbol-selector__symbol:hover {\n    background-color: var(--color-border-default); }\n  .editor_controls button {\n    display: inline-block;\n    padding: var(--spacing-quarter-unit) var(--spacing-half-unit);\n    line-height: 1;\n    letter-spacing: 0.5px;\n    text-transform: capitalize;\n    text-align: center;\n    cursor: pointer;\n    height: 36px;\n    outline: none;\n    user-select: none;\n    font-size: var(--font-size-medium);\n    font-weight: var(--font-weight-semibold);\n    font-family: var(--font-family-body);\n    border-width: 1px;\n    border-style: solid;\n    border-color: transparent;\n    border-radius: var(--border-radius);\n    transition: all 0.15s ease-in-out; }\n    .editor_controls button.button {\n      padding-left: 0; }\n  .editor_controls .button__wrapper {\n    display: flex;\n    align-items: center;\n    justify-content: center;\n    position: relative;\n    overflow: hidden; }\n  .editor_controls .button__label {\n    padding-left: var(--spacing-half-unit); }\n  .editor_controls .button__icon {\n    display: flex;\n    padding-left: var(--spacing-quarter-unit);\n    will-change: transform; }\n    .editor_controls .button__icon svg {\n      transform: scale(0.8);\n      transform-origin: center center;\n      display: block; }\n      .editor_controls .button__icon svg path {\n        fill: currentColor; }\n    .editor_controls .button__icon + .button__label {\n      padding-left: 0; }\n  .sidebar .button {\n    width: calc(100% - var(--spacing-base-unit));\n    margin-left: var(--spacing-half-unit);\n    margin-right: var(--spacing-half-unit); }\n  .editor_controls .button--no-text {\n    background-color: var(--color-button-default-base-fill);\n    border-color: var(--color-button-default-base-border);\n    color: var(--color-button-default-base-text);\n    padding-right: var(--spacing-quarter-unit);\n    margin-left: 5px; }\n    .editor_controls .button--no-text:hover:not(.button--no-text--disabled) {\n      background-color: var(--color-button-default-hover-fill);\n      border: 1px solid var(--color-button-default-hover-border);\n      color: var(--color-button-default-hover-text); }\n    .editor_controls .button--no-text:active:not(.button--no-text--disabled) {\n      background-color: var(--color-button-default-active-fill);\n      border: 1px solid var(--color-button-default-active-border);\n      color: var(--color-button-default-active-text); }\n    .editor_controls .button--no-text--disabled {\n      background-color: var(--color-button-default-base-fill);\n      border-color: var(--color-button-default-base-border);\n      color: var(--color-button-default-base-text);\n      padding-right: var(--spacing-quarter-unit);\n      margin-left: 5px;\n      color: #bababa;\n      cursor: default; }\n      .editor_controls .button--no-text--disabled:hover:not(.button--no-text--disabled) {\n        background-color: var(--color-button-default-hover-fill);\n        border: 1px solid var(--color-button-default-hover-border);\n        color: var(--color-button-default-hover-text); }\n      .editor_controls .button--no-text--disabled:active:not(.button--no-text--disabled) {\n        background-color: var(--color-button-default-active-fill);\n        border: 1px solid var(--color-button-default-active-border);\n        color: var(--color-button-default-active-text); }\n  .editor_controls .button--default {\n    background-color: var(--color-button-default-base-fill);\n    border-color: var(--color-button-default-base-border);\n    color: var(--color-button-default-base-text); }\n    .editor_controls .button--default:hover:not(.button--no-text--disabled) {\n      background-color: var(--color-button-default-hover-fill);\n      border: 1px solid var(--color-button-default-hover-border);\n      color: var(--color-button-default-hover-text); }\n    .editor_controls .button--default:active:not(.button--no-text--disabled) {\n      background-color: var(--color-button-default-active-fill);\n      border: 1px solid var(--color-button-default-active-border);\n      color: var(--color-button-default-active-text); }\n  .editor_controls .button--primary {\n    background-color: var(--color-button-primary-base-fill);\n    border-color: var(--color-button-primary-base-border);\n    color: var(--color-button-primary-base-text);\n    text-shadow: var(--text-shadow-dark-ui); }\n    .editor_controls .button--primary svg {\n      filter: drop-shadow(0 1px 2px rgba(42, 63, 95, 0.7)); }\n    .editor_controls .button--primary:hover:not(.button--no-text--disabled) {\n      background-color: var(--color-button-primary-hover-fill);\n      border: 1px solid var(--color-button-primary-hover-border);\n      color: var(--color-button-primary-hover-text); }\n    .editor_controls .button--primary:active:not(.button--no-text--disabled) {\n      background-color: var(--color-button-primary-active-fill);\n      border: 1px solid var(--color-button-primary-active-border);\n      color: var(--color-button-primary-active-text); }\n  .editor_controls .button--secondary {\n    background-color: var(--color-button-secondary-base-fill);\n    border-color: var(--color-button-secondary-base-border);\n    color: var(--color-button-secondary-base-text); }\n    .editor_controls .button--secondary:hover:not(.button--no-text--disabled) {\n      background-color: var(--color-button-secondary-hover-fill);\n      border: 1px solid var(--color-button-secondary-hover-border);\n      color: var(--color-button-secondary-hover-text); }\n    .editor_controls .button--secondary:active:not(.button--no-text--disabled) {\n      background-color: var(--color-button-secondary-active-fill);\n      border: 1px solid var(--color-button-secondary-active-border);\n      color: var(--color-button-secondary-active-text); }\n  .editor_controls .button--tertiary {\n    background-color: var(--color-button-tertiary-base-fill);\n    border-color: var(--color-button-tertiary-base-border);\n    color: var(--color-button-tertiary-base-text); }\n    .editor_controls .button--tertiary:hover:not(.button--no-text--disabled) {\n      background-color: var(--color-button-tertiary-hover-fill);\n      border: 1px solid var(--color-button-tertiary-hover-border);\n      color: var(--color-button-tertiary-hover-text); }\n    .editor_controls .button--tertiary:active:not(.button--no-text--disabled) {\n      background-color: var(--color-button-tertiary-active-fill);\n      border: 1px solid var(--color-button-tertiary-active-border);\n      color: var(--color-button-tertiary-active-text); }\n  .editor_controls .button--upgrade {\n    background-color: var(--color-button-upgrade-base-fill);\n    border-color: var(--color-button-upgrade-base-border);\n    color: var(--color-button-upgrade-base-text);\n    text-shadow: var(--text-shadow-dark-ui); }\n    .editor_controls .button--upgrade svg {\n      filter: drop-shadow(0 1px 2px rgba(42, 63, 95, 0.7)); }\n    .editor_controls .button--upgrade:hover:not(.button--no-text--disabled) {\n      background-color: var(--color-button-upgrade-hover-fill);\n      border: 1px solid var(--color-button-upgrade-hover-border);\n      color: var(--color-button-upgrade-hover-text); }\n    .editor_controls .button--upgrade:active:not(.button--no-text--disabled) {\n      background-color: var(--color-button-upgrade-active-fill);\n      border: 1px solid var(--color-button-upgrade-active-border);\n      color: var(--color-button-upgrade-active-text); }\n  .editor_controls .button--header {\n    background-color: var(--color-button-header-base-fill);\n    border-color: var(--color-button-header-base-border);\n    color: var(--color-button-header-base-text); }\n    .editor_controls .button--header:hover:not(.button--no-text--disabled) {\n      background-color: var(--color-button-header-hover-fill);\n      border: 1px solid var(--color-button-header-hover-border);\n      color: var(--color-button-header-hover-text); }\n    .editor_controls .button--header:active:not(.button--no-text--disabled) {\n      background-color: var(--color-button-header-active-fill);\n      border: 1px solid var(--color-button-header-active-border);\n      color: var(--color-button-header-active-text); }\n  .editor_controls .checkbox__group {\n    padding-left: var(--spacing-half-unit);\n    text-align: left; }\n  .editor_controls .checkbox__item {\n    user-select: none;\n    cursor: default;\n    padding-top: var(--spacing-eighth-unit);\n    padding-bottom: var(--spacing-eighth-unit); }\n    .editor_controls .checkbox__item--vertical {\n      display: block;\n      clear: both; }\n  .editor_controls .checkbox__box {\n    height: 18px;\n    width: 18px;\n    border: var(--border-default);\n    border-radius: var(--border-radius-small);\n    cursor: pointer;\n    display: inline-block;\n    vertical-align: middle;\n    text-align: center;\n    position: relative; }\n    .editor_controls .checkbox__box:hover {\n      background: var(--color-background-light); }\n    .editor_controls .checkbox__box--checked {\n      border: var(--border-accent-shade);\n      background: var(--color-accent); }\n      .editor_controls .checkbox__box--checked:hover {\n        background: var(--color-accent-shade); }\n      .editor_controls .checkbox__box--checked + .checkbox__label {\n        color: var(--color-text-active); }\n  .editor_controls .checkbox__check {\n    color: var(--color-text-base);\n    font-size: var(--spacing-half-unit);\n    position: absolute;\n    height: 100%;\n    width: 100%;\n    left: 0;\n    top: 0;\n    display: flex;\n    align-items: center;\n    justify-content: center; }\n    .editor_controls .checkbox__check svg {\n      filter: drop-shadow(0 1px 2px rgba(42, 63, 95, 0.7)); }\n      .editor_controls .checkbox__check svg path {\n        fill: var(--color-white); }\n  .editor_controls .checkbox__label {\n    padding-left: var(--spacing-quarter-unit);\n    font-size: var(--font-size-base);\n    color: var(--color-text-base);\n    display: inline-block;\n    line-height: 20px;\n    text-align: left;\n    vertical-align: middle;\n    cursor: pointer; }\n  .editor_controls .colorpicker__saturation, .editor_controls .colorpicker__controls .colorpicker__sliders .colorpicker__slider, .editor_controls .colorpicker__controls .colorpicker__active {\n    position: relative;\n    overflow: hidden;\n    border: var(--border-default);\n    border-radius: var(--border-radius-small);\n    cursor: pointer; }\n  .editor_controls .colorpicker {\n    display: flex;\n    width: 26px;\n    height: 26px;\n    border-radius: 100%;\n    border: var(--border-default);\n    padding: var(--spacing-eighth-unit);\n    /* Saturation wrapper style */\n    /* Wrapper style for Hue and Alpha sliders and swatch */ }\n    .editor_controls .colorpicker__outer {\n      width: 185px; }\n    .editor_controls .colorpicker__container {\n      display: flex;\n      align-items: center;\n      line-height: 2;\n      position: relative;\n      width: 185px; }\n    .editor_controls .colorpicker__selected-color {\n      margin-left: var(--spacing-half-unit);\n      color: var(--color-text-base);\n      font-weight: var(--font-weight-semibold);\n      font-size: var(--font-size-small);\n      display: inline-block;\n      vertical-align: middle;\n      text-transform: uppercase; }\n    .editor_controls .colorpicker__swatch {\n      border-radius: 50%;\n      flex-grow: 1;\n      width: 100%;\n      height: 100%; }\n    .editor_controls .colorpicker__saturation {\n      height: 100px; }\n    .editor_controls .colorpicker__custom-input {\n      padding-top: var(--spacing-eighth-unit); }\n      .editor_controls .colorpicker__custom-input input {\n        border: var(--border-default) !important;\n        box-shadow: none !important;\n        background-color: var(--color-background-inputs);\n        color: var(--color-text-dark); }\n      .editor_controls .colorpicker__custom-input input + span {\n        color: var(--color-text) !important; }\n    .editor_controls .colorpicker__controls .colorpicker__sliders {\n      width: 100%; }\n      .editor_controls .colorpicker__controls .colorpicker__sliders .colorpicker__slider {\n        margin: auto 0;\n        height: 10px;\n        margin: var(--spacing-eighth-unit) 0; }\n    .editor_controls .colorpicker__controls .colorpicker__active {\n      height: var(--spacing-base-unit);\n      width: var(--spacing-base-unit);\n      margin: var(--spacing-eighth-unit) 0 0 var(--spacing-half-unit); }\n      .editor_controls .colorpicker__controls .colorpicker__active .colorpicker__active-swatch {\n        position: absolute;\n        top: 0;\n        right: 0;\n        bottom: 0;\n        left: 0;\n        border-radius: var(--border-radius-small);\n        border: 1px solid #eee; }\n  .editor_controls .fold .fold .colorpicker__container {\n    width: calc(185px - var(--spacing-half-unit) - var(--spacing-half-unit)); }\n  .editor_controls .fold .fold .colorpicker__outer {\n    width: calc(185px - var(--spacing-half-unit) - var(--spacing-half-unit)); }\n  .editor_controls .colorscalePickerTopContainer {\n    display: none; }\n  .editor_controls .colorscaleDescription {\n    display: none; }\n  .editor_controls .colorscalePickerContainer {\n    min-width: 240px;\n    position: relative;\n    padding: 0;\n    resize: none;\n    border: none;\n    background: none;\n    max-height: none; }\n  .editor_controls .colorscalePickerContainer input:focus {\n    outline: none; }\n  @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {\n    .editor_controls .colorscalePickerContainer {\n      display: inline; } }\n  .editor_controls .colorscalePickerContainer::-webkit-scrollbar {\n    width: 5px; }\n  .editor_controls .colorscalePickerBottomContainer {\n    padding: 5px 0 0 0; }\n  .editor_controls .colorscaleControlPanel {\n    padding: 0;\n    margin: 0;\n    margin-left: 27%;\n    width: 70%; }\n  .editor_controls .customPickerContainer {\n    text-align: left;\n    width: 180px; }\n  .editor_controls .customPickerContainer__clickable {\n    margin-top: 5px;\n    min-height: 27px;\n    width: 180px; }\n  .editor_controls .customPickerContainer__expanded-content {\n    margin-top: 10px; }\n  .editor_controls .customPickerContainer__category-dropdown {\n    max-width: 100%; }\n  .editor_controls .customPickerContainer__palettes {\n    margin-left: -60px; }\n  .editor_controls .customPickerContainer__info {\n    width: 240px; }\n  .editor_controls .customPickerContainer__category-dropdown {\n    width: 180px !important; }\n  .editor_controls .dropdown-container {\n    /**\n * React Select\n * ============\n * Created by Jed Watson and Joss Mackison for KeystoneJS, http://www.keystonejs.com/\n * https://twitter.com/jedwatson https://twitter.com/jossmackison https://twitter.com/keystonejs\n * MIT License: https://github.com/JedWatson/react-select\n*/\n    flex-grow: 1; }\n\n@keyframes Select-animation-spin {\n  to {\n    transform: rotate(1turn); } }\n\n@-webkit-keyframes Select-animation-spin {\n  to {\n    -webkit-transform: rotate(1turn); } }\n    .editor_controls .dropdown-container .Select {\n      position: relative; }\n      .editor_controls .dropdown-container .Select input::-webkit-contacts-auto-fill-button,\n      .editor_controls .dropdown-container .Select input::-webkit-credentials-auto-fill-button {\n        display: none !important; }\n      .editor_controls .dropdown-container .Select input::-ms-clear {\n        display: none !important; }\n      .editor_controls .dropdown-container .Select input::-ms-reveal {\n        display: none !important; }\n      .editor_controls .dropdown-container .Select,\n      .editor_controls .dropdown-container .Select div,\n      .editor_controls .dropdown-container .Select input,\n      .editor_controls .dropdown-container .Select span {\n        -webkit-box-sizing: border-box;\n        -moz-box-sizing: border-box;\n        box-sizing: border-box; }\n      .editor_controls .dropdown-container .Select.is-disabled .Select-arrow-zone {\n        cursor: default;\n        pointer-events: none; }\n      .editor_controls .dropdown-container .Select.is-disabled > .Select-control {\n        background-color: #f9f9f9; }\n        .editor_controls .dropdown-container .Select.is-disabled > .Select-control:hover {\n          box-shadow: none; }\n      .editor_controls .dropdown-container .Select.is-searchable.is-open > .Select-control {\n        cursor: text; }\n      .editor_controls .dropdown-container .Select.is-searchable.is-focused:not(.is-open) > .Select-control {\n        cursor: text; }\n      .editor_controls .dropdown-container .Select.is-open > .Select-control {\n        border-bottom-right-radius: 0;\n        border-bottom-left-radius: 0;\n        background: #fff;\n        border-color: #b3b3b3 #ccc #d9d9d9; }\n        .editor_controls .dropdown-container .Select.is-open > .Select-control .Select-arrow {\n          top: -2px;\n          border-color: transparent transparent #999;\n          border-width: 0 5px 5px; }\n      .editor_controls .dropdown-container .Select.is-focused > .Select-control {\n        background: #fff; }\n      .editor_controls .dropdown-container .Select.is-focused:not(.is-open) > .Select-control {\n        border-color: #08c #0099e6 #0099e6;\n        box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 0 5px -1px fade(#08c, 50%); }\n      .editor_controls .dropdown-container .Select.has-value.is-clearable.Select--single > .Select-control .Select-value {\n        padding-right: 42px; }\n      .editor_controls .dropdown-container .Select.has-value.Select--single > .Select-control .Select-value .Select-value-label,\n      .editor_controls .dropdown-container .Select.has-value.is-pseudo-focused.Select--single > .Select-control .Select-value .Select-value-label {\n        color: #333; }\n      .editor_controls .dropdown-container .Select.has-value.Select--single > .Select-control .Select-value a.Select-value-label,\n      .editor_controls .dropdown-container .Select.has-value.is-pseudo-focused.Select--single > .Select-control .Select-value a.Select-value-label {\n        cursor: pointer;\n        text-decoration: none; }\n        .editor_controls .dropdown-container .Select.has-value.Select--single > .Select-control .Select-value a.Select-value-label:hover, .editor_controls .dropdown-container .Select.has-value.Select--single > .Select-control .Select-value a.Select-value-label:focus,\n        .editor_controls .dropdown-container .Select.has-value.is-pseudo-focused.Select--single > .Select-control .Select-value a.Select-value-label:hover,\n        .editor_controls .dropdown-container .Select.has-value.is-pseudo-focused.Select--single > .Select-control .Select-value a.Select-value-label:focus {\n          color: #08c;\n          outline: none;\n          text-decoration: underline; }\n        .editor_controls .dropdown-container .Select.has-value.Select--single > .Select-control .Select-value a.Select-value-label:focus,\n        .editor_controls .dropdown-container .Select.has-value.is-pseudo-focused.Select--single > .Select-control .Select-value a.Select-value-label:focus {\n          background: #fff; }\n      .editor_controls .dropdown-container .Select.has-value.is-pseudo-focused .Select-input {\n        opacity: 0; }\n      .editor_controls .dropdown-container .Select.is-open .Select-arrow,\n      .editor_controls .dropdown-container .Select .Select-arrow-zone:hover > .Select-arrow {\n        border-top-color: #666; }\n      .editor_controls .dropdown-container .Select.Select--rtl {\n        direction: rtl;\n        text-align: right; }\n    .editor_controls .dropdown-container .Select-control {\n      background-color: #fff;\n      border-color: #d9d9d9 #ccc #b3b3b3;\n      border-radius: 4px;\n      border: 1px solid #ccc;\n      color: #333;\n      cursor: default;\n      display: table;\n      border-spacing: 0;\n      border-collapse: separate;\n      height: 36px;\n      outline: none;\n      overflow: hidden;\n      position: relative;\n      width: 100%; }\n      .editor_controls .dropdown-container .Select-control:hover {\n        box-shadow: 0 1px 0 rgba(0, 0, 0, 0.06); }\n      .editor_controls .dropdown-container .Select-control .Select-input:focus {\n        outline: none;\n        background: #fff; }\n    .editor_controls .dropdown-container .Select-placeholder,\n    .editor_controls .dropdown-container .Select--single > .Select-control .Select-value {\n      bottom: 0;\n      color: #aaa;\n      left: 0;\n      line-height: 34px;\n      padding-left: 10px;\n      padding-right: 10px;\n      position: absolute;\n      right: 0;\n      top: 0;\n      max-width: 100%;\n      overflow: hidden;\n      text-overflow: ellipsis;\n      white-space: nowrap; }\n    .editor_controls .dropdown-container .Select-input {\n      height: 34px;\n      padding-left: 10px;\n      padding-right: 10px;\n      vertical-align: middle; }\n      .editor_controls .dropdown-container .Select-input > input {\n        width: 100%;\n        background: none transparent;\n        border: 0 none;\n        box-shadow: none;\n        cursor: default;\n        display: inline-block;\n        font-family: inherit;\n        font-size: inherit;\n        margin: 0;\n        outline: none;\n        line-height: 17px;\n        /* For IE 8 compatibility */\n        padding: 8px 0 12px;\n        /* For IE 8 compatibility */\n        -webkit-appearance: none; }\n        .is-focused .editor_controls .dropdown-container .Select-input > input {\n          cursor: text; }\n    .editor_controls .dropdown-container .Select-control:not(.is-searchable) > .Select-input {\n      outline: none; }\n    .editor_controls .dropdown-container .Select-loading-zone {\n      cursor: pointer;\n      display: table-cell;\n      position: relative;\n      text-align: center;\n      vertical-align: middle;\n      width: 16px; }\n    .editor_controls .dropdown-container .Select-loading {\n      -webkit-animation: Select-animation-spin 400ms infinite linear;\n      -o-animation: Select-animation-spin 400ms infinite linear;\n      animation: Select-animation-spin 400ms infinite linear;\n      width: 16px;\n      height: 16px;\n      box-sizing: border-box;\n      border-radius: 50%;\n      border: 2px solid #ccc;\n      border-right-color: #333;\n      display: inline-block;\n      position: relative;\n      vertical-align: middle; }\n    .editor_controls .dropdown-container .Select-clear-zone {\n      -webkit-animation: Select-animation-fadeIn 200ms;\n      -o-animation: Select-animation-fadeIn 200ms;\n      animation: Select-animation-fadeIn 200ms;\n      color: #999;\n      cursor: pointer;\n      display: table-cell;\n      position: relative;\n      text-align: center;\n      vertical-align: middle;\n      width: 17px; }\n      .editor_controls .dropdown-container .Select-clear-zone:hover {\n        color: #D0021B; }\n    .editor_controls .dropdown-container .Select-clear {\n      display: inline-block;\n      font-size: 18px;\n      line-height: 1; }\n    .editor_controls .dropdown-container .Select--multi .Select-clear-zone {\n      width: 17px; }\n    .editor_controls .dropdown-container .Select--multi .Select-multi-value-wrapper {\n      display: inline-block; }\n    .editor_controls .dropdown-container .Select .Select-aria-only {\n      position: absolute;\n      display: inline-block;\n      height: 1px;\n      width: 1px;\n      margin: -1px;\n      clip: rect(0, 0, 0, 0);\n      overflow: hidden;\n      float: left; }\n    .editor_controls .dropdown-container .Select-arrow-zone {\n      cursor: pointer;\n      display: table-cell;\n      position: relative;\n      text-align: center;\n      vertical-align: middle;\n      width: 25px;\n      padding-right: 5px; }\n      .Select--rtl .editor_controls .dropdown-container .Select-arrow-zone {\n        padding-right: 0;\n        padding-left: 5px; }\n    .editor_controls .dropdown-container .Select-arrow {\n      border-color: #999 transparent transparent;\n      border-style: solid;\n      border-width: 5px 5px 2.5px;\n      display: inline-block;\n      height: 0;\n      width: 0;\n      position: relative; }\n\n@-webkit-keyframes Select-animation-fadeIn {\n  from {\n    opacity: 0; }\n  to {\n    opacity: 1; } }\n\n@keyframes Select-animation-fadeIn {\n  from {\n    opacity: 0; }\n  to {\n    opacity: 1; } }\n    .editor_controls .dropdown-container .Select-menu-outer {\n      border-bottom-right-radius: 4px;\n      border-bottom-left-radius: 4px;\n      background-color: #fff;\n      border: 1px solid #ccc;\n      border-top-color: #e6e6e6;\n      box-shadow: 0 1px 0 rgba(0, 0, 0, 0.06);\n      box-sizing: border-box;\n      margin-top: -1px;\n      max-height: 200px;\n      position: absolute;\n      left: 0;\n      top: 100%;\n      width: 100%;\n      z-index: 1000;\n      -webkit-overflow-scrolling: touch; }\n    .editor_controls .dropdown-container .Select-menu {\n      max-height: 198px;\n      overflow-y: auto; }\n    .editor_controls .dropdown-container .Select-option {\n      box-sizing: border-box;\n      background-color: #fff;\n      color: #666666;\n      cursor: pointer;\n      display: block;\n      padding: 8px 10px; }\n      .editor_controls .dropdown-container .Select-option:last-child {\n        border-bottom-right-radius: 4px;\n        border-bottom-left-radius: 4px; }\n      .editor_controls .dropdown-container .Select-option.is-selected {\n        background-color: #f5faff;\n        color: #333; }\n      .editor_controls .dropdown-container .Select-option.is-focused {\n        background-color: #f2f9fc;\n        color: #333; }\n      .editor_controls .dropdown-container .Select-option.is-disabled {\n        color: #cccccc;\n        cursor: default; }\n    .editor_controls .dropdown-container .Select-noresults {\n      box-sizing: border-box;\n      color: #999999;\n      cursor: default;\n      display: block;\n      padding: 8px 10px; }\n    .editor_controls .dropdown-container .Select--multi .Select-input {\n      vertical-align: middle;\n      margin-left: 10px;\n      padding: 0; }\n    .editor_controls .dropdown-container .Select--multi.Select--rtl .Select-input {\n      margin-left: 0;\n      margin-right: 10px; }\n    .editor_controls .dropdown-container .Select--multi.has-value .Select-input {\n      margin-left: 5px; }\n    .editor_controls .dropdown-container .Select--multi .Select-value {\n      background-color: #f2f9fc;\n      border-radius: 2px;\n      border: 1px solid #c9e6f2;\n      color: #08c;\n      display: inline-block;\n      font-size: 0.9em;\n      margin-left: 5px;\n      margin-top: 5px;\n      vertical-align: top; }\n    .editor_controls .dropdown-container .Select--multi .Select-value-icon,\n    .editor_controls .dropdown-container .Select--multi .Select-value-label {\n      display: inline-block;\n      vertical-align: middle; }\n    .editor_controls .dropdown-container .Select--multi .Select-value-label {\n      border-bottom-right-radius: 2px;\n      border-top-right-radius: 2px;\n      cursor: default;\n      padding: 2px 5px; }\n    .editor_controls .dropdown-container .Select--multi a.Select-value-label {\n      color: #08c;\n      cursor: pointer;\n      text-decoration: none; }\n      .editor_controls .dropdown-container .Select--multi a.Select-value-label:hover {\n        text-decoration: underline; }\n    .editor_controls .dropdown-container .Select--multi .Select-value-icon {\n      cursor: pointer;\n      border-bottom-left-radius: 2px;\n      border-top-left-radius: 2px;\n      border-right: 1px solid #c9e6f2;\n      padding: 1px 5px 3px; }\n      .editor_controls .dropdown-container .Select--multi .Select-value-icon:hover, .editor_controls .dropdown-container .Select--multi .Select-value-icon:focus {\n        background-color: #ddeff7;\n        color: #0077b3; }\n      .editor_controls .dropdown-container .Select--multi .Select-value-icon:active {\n        background-color: #c9e6f2; }\n    .editor_controls .dropdown-container .Select--multi.Select--rtl .Select-value {\n      margin-left: 0;\n      margin-right: 5px; }\n    .editor_controls .dropdown-container .Select--multi.Select--rtl .Select-value-icon {\n      border-right: none;\n      border-left: 1px solid #c9e6f2; }\n    .editor_controls .dropdown-container .Select--multi.is-disabled .Select-value {\n      background-color: #fcfcfc;\n      border: 1px solid #e3e3e3;\n      color: #333; }\n    .editor_controls .dropdown-container .Select--multi.is-disabled .Select-value-icon {\n      cursor: not-allowed;\n      border-right: 1px solid #e3e3e3; }\n      .editor_controls .dropdown-container .Select--multi.is-disabled .Select-value-icon:hover, .editor_controls .dropdown-container .Select--multi.is-disabled .Select-value-icon:focus, .editor_controls .dropdown-container .Select--multi.is-disabled .Select-value-icon:active {\n        background-color: #fcfcfc; }\n\n@keyframes Select-animation-spin {\n  to {\n    transform: rotate(1turn); } }\n\n@-webkit-keyframes Select-animation-spin {\n  to {\n    -webkit-transform: rotate(1turn); } }\n    .editor_controls .dropdown-container:not(:last-child) {\n      margin-bottom: var(--spacing-quarter-unit); }\n    .editor_controls .dropdown-container .Select.is-focused > .Select-control {\n      background-color: var(--color-background-inputs); }\n      .editor_controls .dropdown-container .Select.is-focused > .Select-control .Select-input {\n        background-color: var(--color-background-inputs) !important; }\n    .editor_controls .dropdown-container .Select.is-open > .Select-control {\n      border-color: var(--color-border-dark);\n      background-color: var(--color-background-inputs) !important; }\n      .editor_controls .dropdown-container .Select.is-open > .Select-control .Select-input {\n        background-color: var(--color-background-inputs) !important; }\n    .editor_controls .dropdown-container .Select:not(.is-open) .Select-control {\n      background-color: var(--color-background-inputs) !important; }\n      .editor_controls .dropdown-container .Select:not(.is-open) .Select-control:hover {\n        border-color: var(--color-border-dark); }\n        .editor_controls .dropdown-container .Select:not(.is-open) .Select-control:hover .Select-arrow {\n          opacity: 1; }\n    .editor_controls .dropdown-container .Select-control {\n      background-color: var(--color-background-inputs);\n      border: var(--border-default);\n      box-shadow: none !important;\n      color: var(--color-text-base); }\n    .editor_controls .dropdown-container .Select-option {\n      color: var(--color-text-base); }\n    .editor_controls .dropdown-container .Select-menu-outer {\n      border: var(--border-default);\n      border-top-color: var(--color-border-default);\n      background-color: transparent;\n      box-shadow: var(--box-shadow-base); }\n    .editor_controls .dropdown-container .Select.is-focused:not(.is-open) > .Select-control {\n      border-color: var(--color-border-accent); }\n    .editor_controls .dropdown-container .Select.has-value.Select--single > .Select-control .Select-value .Select-value-label,\n    .editor_controls .dropdown-container .Select.has-value.is-pseudo-focused.Select--single > .Select-control .Select-value .Select-value-label {\n      color: var(--color-text-base); }\n    .editor_controls .dropdown-container .Select.is-open .Select-arrow,\n    .editor_controls .dropdown-container .editor_controls .dropdown-container .Select .Select-arrow-zone:hover > .Select-arrow {\n      border-color: transparent transparent var(--color-border-accent) !important; }\n    .editor_controls .dropdown-container .Select-arrow-zone:hover .Select-arrow {\n      border-top-color: var(--color-border-accent) !important; }\n    .editor_controls .dropdown-container .Select-arrow {\n      border-color: var(--color-border-default) transparent transparent; }\n    .editor_controls .dropdown-container .Select-option {\n      background-color: var(--color-background-inputs); }\n      .editor_controls .dropdown-container .Select-option.is-selected {\n        color: var(--color-text-active);\n        font-weight: var(--font-weight-semibold);\n        background-color: var(--color-background-light); }\n      .editor_controls .dropdown-container .Select-option.is-focused {\n        background-color: var(--color-background-light);\n        color: var(--color-text-active); }\n    .editor_controls .dropdown-container .Select-option:hover {\n      color: var(--color-text-active);\n      background-color: var(--color-background-light); }\n    .editor_controls .dropdown-container .Select-placeholder,\n    .editor_controls .dropdown-container .Select--single > .Select-control .Select-value {\n      color: var(--color-text-base); }\n    .editor_controls .dropdown-container .Select-value-label {\n      color: var(--color-text-base) !important; }\n    .editor_controls .dropdown-container .Select-placeholder {\n      color: var(--color-text-placeholder); }\n    .editor_controls .dropdown-container .dropdown--dark .Select-control {\n      background-color: var(--color-background-inverse); }\n    .editor_controls .dropdown-container .dropdown--dark .Select-option {\n      background-color: var(--color-background-inverse); }\n      .editor_controls .dropdown-container .dropdown--dark .Select-option.is-selected {\n        background-color: var(--color-border-default); }\n    .editor_controls .dropdown-container .dropdown--dark .Select.is-focused {\n      background-color: var(--color-border-light); }\n  .editor_controls ::-webkit-input-placeholder {\n    /* Chrome/Opera/Safari */\n    color: var(--color-text-placeholder); }\n  .editor_controls ::-moz-placeholder {\n    /* Firefox 19+ */\n    color: var(--color-text-placeholder); }\n  .editor_controls :-ms-input-placeholder {\n    /* IE 10+ */\n    color: var(--color-text-placeholder); }\n  .editor_controls :-moz-placeholder {\n    /* Firefox 18- */\n    color: var(--color-text-placeholder); }\n  .editor_controls .numeric-input__wrapper {\n    line-height: 20px;\n    max-width: 100%;\n    flex: 1;\n    display: flex;\n    align-items: center;\n    color: var(--color-text-base); }\n  @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {\n    .editor_controls .numeric-input__wrapper {\n      flex-basis: auto; } }\n  .editor_controls .numeric-input__number {\n    display: inline-block;\n    border: var(--border-default);\n    background: var(--color-background-inputs);\n    cursor: text;\n    overflow: hidden;\n    text-overflow: ellipsis;\n    white-space: nowrap;\n    text-align: left;\n    border-radius: var(--border-radius-small);\n    padding: var(--spacing-quarter-unit) var(--spacing-quarter-unit) var(--spacing-quarter-unit) var(--spacing-half-unit);\n    width: 62px;\n    vertical-align: middle;\n    font-size: inherit;\n    color: inherit;\n    font-family: inherit; }\n  .editor_controls .numeric-input__caret-box {\n    display: inline-block;\n    max-height: 32px;\n    margin-left: var(--spacing-quarter-unit);\n    margin-right: var(--spacing-half-unit);\n    vertical-align: middle;\n    box-sizing: border-box; }\n  .editor_controls .numeric-input__caret:first-child {\n    margin-bottom: 2px; }\n  .editor_controls .numeric-input__caret {\n    cursor: pointer;\n    background-color: var(--color-background-light);\n    border: var(--border-default);\n    border-radius: 1px;\n    line-height: var(--spacing-half-unit);\n    text-align: center; }\n  .editor_controls .numeric-top-caret-modifier {\n    width: 13px !important;\n    height: 13px !important;\n    fill: var(--color-text-base) !important; }\n  .editor_controls .numeric-bottom-caret-modifier {\n    width: 13px !important;\n    height: 13px !important;\n    fill: var(--color-text-base) !important; }\n  .editor_controls .AxisInterval-milliseconds {\n    width: 50%; }\n  .editor_controls ::-webkit-input-placeholder {\n    /* Chrome/Opera/Safari */\n    color: var(--color-text-placeholder); }\n  .editor_controls ::-moz-placeholder {\n    /* Firefox 19+ */\n    color: var(--color-text-placeholder); }\n  .editor_controls :-ms-input-placeholder {\n    /* IE 10+ */\n    color: var(--color-text-placeholder); }\n  .editor_controls :-moz-placeholder {\n    /* Firefox 18- */\n    color: var(--color-text-placeholder); }\n  .editor_controls .text-input {\n    display: inline-block;\n    border: var(--border-default);\n    background: var(--color-background-inputs);\n    cursor: text;\n    overflow: hidden;\n    text-overflow: ellipsis;\n    white-space: nowrap;\n    text-align: left;\n    border-radius: var(--border-radius-small);\n    padding: var(--spacing-quarter-unit) var(--spacing-quarter-unit) var(--spacing-quarter-unit) var(--spacing-half-unit);\n    width: 140px;\n    vertical-align: middle;\n    font-size: inherit;\n    color: inherit;\n    font-family: inherit; }\n  .editor_controls .radio-block {\n    width: 100%;\n    line-height: var(--font-leading-head);\n    display: flex; }\n    .editor_controls .radio-block__option {\n      flex-grow: 1;\n      padding: var(--spacing-quarter-unit) var(--spacing-half-unit);\n      background-color: var(--color-background-top);\n      border: var(--border-default);\n      display: inline-block;\n      cursor: pointer;\n      min-width: 0px;\n      text-align: center;\n      font-size: var(--font-size-small); }\n      .editor_controls .radio-block__option:not(.radio-block__option--active):hover {\n        background-color: var(--color-background-light);\n        color: var(--color-text-active); }\n      .editor_controls .radio-block__option--active {\n        background-color: var(--color-button-primary-base-fill);\n        color: var(--color-button-primary-base-text);\n        border: 1px solid var(--color-button-primary-base-border);\n        margin-left: -1px;\n        cursor: default;\n        text-shadow: var(--text-shadow-dark-ui);\n        font-weight: var(--font-weight-semibold); }\n        .editor_controls .radio-block__option--active:not(:first-child), .editor_controls .radio-block__option--active:last-child {\n          border-left: var(--border-accent-shade) !important; }\n      .editor_controls .radio-block__option:not(:first-child):not(:last-child) {\n        border-left: 0; }\n      .editor_controls .radio-block__option:last-child {\n        border-top-right-radius: var(--border-radius-small);\n        border-bottom-right-radius: var(--border-radius-small);\n        border-left: 0; }\n      .editor_controls .radio-block__option:first-child {\n        border-top-left-radius: var(--border-radius-small);\n        border-bottom-left-radius: var(--border-radius-small); }\n        .editor_controls .radio-block__option:first-child:not(.radio-block__option--active) {\n          border-left: var(--border-default); }\n  .editor_controls .text-editor {\n    overflow: hidden;\n    border: var(--border-default);\n    border-radius: var(--border-radius);\n    min-height: 155px;\n    display: flex;\n    flex-direction: column;\n    flex-grow: 1; }\n    .editor_controls .text-editor * {\n      box-sizing: border-box; }\n    .editor_controls .text-editor textarea[class='multi-format-editor__latex'] {\n      height: 155px;\n      width: 100%;\n      margin: 10px;\n      border: var(--border-default); }\n    .editor_controls .text-editor textarea[class='multi-format-editor__html'] {\n      height: 145px;\n      width: 100%; }\n    .editor_controls .text-editor textarea {\n      width: 100%;\n      height: 100%;\n      border: none;\n      overflow: auto;\n      outline: none;\n      box-shadow: none;\n      padding: var(--spacing-quarter-unit);\n      resize: none;\n      line-height: 24px;\n      font-size: 13px;\n      color: var(--color-text-base);\n      background-color: var(--color-background-inputs); }\n  .editor_controls .multi-format-editor__root {\n    display: flex;\n    overflow: hidden;\n    height: 205px; }\n    .editor_controls .multi-format-editor__root__wrapper {\n      flex-grow: 1;\n      display: flex;\n      flex-wrap: wrap;\n      align-items: stretch;\n      flex-direction: column; }\n  .editor_controls .multi-format-editor__tabs {\n    height: 30px;\n    display: block;\n    width: 100%; }\n  .editor_controls .multi-format-editor__tab {\n    text-align: center;\n    height: 30px;\n    line-height: 28px;\n    box-sizing: border-box; }\n    .editor_controls .multi-format-editor__tab.top-tab {\n      width: 50%;\n      overflow: hidden;\n      color: var(--color-text-base);\n      display: inline-block; }\n      .editor_controls .multi-format-editor__tab.top-tab.left {\n        border-top-left-radius: 5px;\n        border-right: var(--border-default); }\n      .editor_controls .multi-format-editor__tab.top-tab.right {\n        border-top-right-radius: 5px; }\n      .editor_controls .multi-format-editor__tab.top-tab:not(.selected) {\n        border-bottom: var(--border-default); }\n    .editor_controls .multi-format-editor__tab.bottom-tab {\n      border-top: var(--border-default);\n      width: 100%;\n      display: block;\n      color: var(--color-text-base); }\n    .editor_controls .multi-format-editor__tab.selected {\n      background: var(--color-background-light);\n      font-weight: var(--font-weight-semibold); }\n    .editor_controls .multi-format-editor__tab:hover:not(.selected) {\n      cursor: pointer;\n      color: var(--color-text-active);\n      background-color: var(--color-background-light); }\n  .editor_controls .multi-format-editor__content__wrapper__rich_text {\n    flex-grow: 1;\n    display: flex;\n    flex-direction: column; }\n  .editor_controls .multi-format-editor__content__wrapper__latex {\n    background-color: var(--color-background-light);\n    display: flex;\n    align-items: center;\n    justify-content: center; }\n  .editor_controls .multi-format-editor__content__wrapper__html {\n    display: flex;\n    align-items: center;\n    justify-content: center; }\n  .editor_controls .multi-format-editor__confirmation-panel {\n    height: 100%;\n    max-height: 100%;\n    width: 100%;\n    text-align: center;\n    display: flex;\n    flex-direction: column;\n    align-items: flex-start;\n    flex: 1; }\n    .editor_controls .multi-format-editor__confirmation-panel__header {\n      color: var(--color-text-section-header);\n      margin-top: 0;\n      margin-bottom: 5px;\n      font-weight: 600; }\n    .editor_controls .multi-format-editor__confirmation-panel__content {\n      overflow-y: auto;\n      display: flex;\n      flex-direction: column;\n      -webkit-overflow-scrolling: touch;\n      padding: var(--spacing-half-unit); }\n      .editor_controls .multi-format-editor__confirmation-panel__content::-webkit-scrollbar {\n        background: white;\n        width: 5px; }\n      .editor_controls .multi-format-editor__confirmation-panel__content::-webkit-scrollbar-track {\n        box-shadow: none;\n        background: var(--scrollbar-track-background); }\n      .editor_controls .multi-format-editor__confirmation-panel__content::-webkit-scrollbar-thumb {\n        background-color: var(--scrollbar-thumb-color);\n        border-radius: 10px; }\n    .editor_controls .multi-format-editor__confirmation-panel__actions {\n      padding: var(--spacing-half-unit);\n      width: 100%;\n      display: flex;\n      justify-content: center;\n      align-items: center;\n      border-top: 1px solid var(--color-border-light);\n      -webkit-overflow-scrolling: touch; }\n      .editor_controls .multi-format-editor__confirmation-panel__actions::-webkit-scrollbar {\n        background: white;\n        width: 5px; }\n      .editor_controls .multi-format-editor__confirmation-panel__actions::-webkit-scrollbar-track {\n        box-shadow: none;\n        background: var(--scrollbar-track-background); }\n      .editor_controls .multi-format-editor__confirmation-panel__actions::-webkit-scrollbar-thumb {\n        background-color: var(--scrollbar-thumb-color);\n        border-radius: 10px; }\n    .editor_controls .multi-format-editor__confirmation-panel__message {\n      line-height: 20px; }\n      .editor_controls .multi-format-editor__confirmation-panel__message-primary {\n        font-weight: var(--font-weight-semibold);\n        color: var(--color-text-base); }\n      .editor_controls .multi-format-editor__confirmation-panel__message-secondary {\n        color: var(--color-text-base); }\n    .editor_controls .multi-format-editor__confirmation-panel__continue-button {\n      margin-left: 10px; }\n  .editor_controls .rich-text-editor__root {\n    border-top: none;\n    width: 100%;\n    color: var(--color-text-base);\n    display: flex;\n    flex-direction: column;\n    flex-grow: 1; }\n  .editor_controls .rich-text-editor__editor {\n    cursor: text;\n    position: relative;\n    flex-grow: 1; }\n    .editor_controls .rich-text-editor__editor > div {\n      position: absolute;\n      width: 100%;\n      height: 100%;\n      max-width: 100%;\n      max-height: 100%;\n      overflow: auto;\n      flex-grow: 1;\n      left: 0;\n      top: 0; }\n  .editor_controls .rich-text-editor__controls {\n    display: flex;\n    justify-content: space-evenly;\n    background: var(--color-background-light);\n    font-size: 14px;\n    padding: 10px 0;\n    user-select: none;\n    border-bottom: var(--border-default); }\n    .editor_controls .rich-text-editor__controls .icon-link {\n      transform: translateY(3px);\n      display: inline-block;\n      fill: var(--color-text-base);\n      width: 15px !important;\n      height: 15px !important; }\n  .editor_controls .rich-text-editor__link-editor {\n    background-color: var(--color-background-light);\n    border: var(--border-default);\n    padding: var(--spacing-half-unit);\n    position: absolute;\n    z-index: 1;\n    display: flex;\n    align-items: center;\n    justify-content: center;\n    flex-direction: column; }\n    .editor_controls .rich-text-editor__link-editor__label {\n      display: block; }\n    .editor_controls .rich-text-editor__link-editor__input {\n      border: var(--border-default);\n      color: var(--color-text-base);\n      overflow: scroll;\n      padding: 0 10px;\n      width: 100%;\n      margin-top: 10px; }\n  .editor_controls .rich-text-editor__styleButton {\n    color: var(--color-text-base);\n    cursor: pointer;\n    display: inline-block;\n    margin: 0;\n    min-height: var(--spacing-base-unit);\n    min-width: var(--spacing-base-unit);\n    text-align: center;\n    background-color: transparent;\n    border: var(--border-default);\n    border-radius: var(--border-radius-small);\n    line-height: 20px;\n    position: relative; }\n    .editor_controls .rich-text-editor__styleButton__wrapper {\n      padding: 0 var(--spacing-quarter-unit); }\n    .editor_controls .rich-text-editor__styleButton--active {\n      background-color: var(--color-accent);\n      border: var(--border-accent-shade);\n      color: var(--color-white); }\n      .editor_controls .rich-text-editor__styleButton--active:hover {\n        background-color: var(--color-accent);\n        border: var(--border-accent-shade);\n        color: var(--color-white); }\n        .editor_controls .rich-text-editor__styleButton--active:hover::before {\n          transform: scaleX(0); }\n    .editor_controls .rich-text-editor__styleButton::before {\n      content: '';\n      position: absolute;\n      bottom: -1px;\n      height: 1px;\n      width: calc(100% + 2px);\n      left: -1px;\n      background: var(--color-accent);\n      will-change: transform;\n      transform-origin: center center;\n      transform: scaleX(0);\n      transition: all 0.15s ease-in-out; }\n    .editor_controls .rich-text-editor__styleButton:hover {\n      color: var(--color-text-active);\n      background-color: var(--color-background-top); }\n      .editor_controls .rich-text-editor__styleButton:hover::before {\n        transform: none; }\n  .editor_controls .rich-text-editor__editor .public-DraftEditorPlaceholder-root,\n  .editor_controls .rich-text-editor__editor .public-DraftEditor-content {\n    padding: var(--spacing-quarter-unit); }\n  .editor_controls .rich-text-editor__editor .public-DraftEditor-content {\n    min-height: 100px; }\n  .editor_controls .RichEditor-hidePlaceholder .public-DraftEditorPlaceholder-root {\n    display: none; }\n  .editor_controls .rich-text-editor__editor .RichEditor-blockquote {\n    border-left: 5px solid #eee;\n    color: #666;\n    font-style: italic;\n    margin: 16px 0;\n    padding: 10px 20px; }\n  .editor_controls .rich-text-editor__editor .public-DraftStyleDefault-pre {\n    background-color: rgba(0, 0, 0, 0.05);\n    font-size: 16px;\n    padding: 20px; }\n  .editor_controls .DraftEditor-editorContainer,\n  .editor_controls .DraftEditor-root,\n  .editor_controls .public-DraftEditor-content {\n    height: inherit;\n    text-align: initial; }\n  .editor_controls .DraftEditor-root {\n    position: relative; }\n  .editor_controls .DraftEditor-editorContainer {\n    background-color: rgba(255, 255, 255, 0);\n    border-left: 0.1px solid transparent;\n    position: relative;\n    z-index: 1; }\n  .editor_controls .public-DraftEditor-block {\n    position: relative; }\n  .editor_controls .DraftEditor-alignLeft .public-DraftStyleDefault-block {\n    text-align: left; }\n  .editor_controls .DraftEditor-alignLeft .public-DraftEditorPlaceholder-root {\n    left: 0;\n    text-align: left; }\n  .editor_controls .DraftEditor-alignCenter .public-DraftStyleDefault-block {\n    text-align: center; }\n  .editor_controls .DraftEditor-alignCenter .public-DraftEditorPlaceholder-root {\n    margin: 0 auto;\n    text-align: center;\n    width: 100%; }\n  .editor_controls .DraftEditor-alignRight .public-DraftStyleDefault-block {\n    text-align: right; }\n  .editor_controls .DraftEditor-alignRight .public-DraftEditorPlaceholder-root {\n    right: 0;\n    text-align: right; }\n  .editor_controls .public-DraftEditorPlaceholder-root {\n    color: #9197a3;\n    position: absolute;\n    z-index: 0; }\n  .editor_controls .public-DraftEditorPlaceholder-hasFocus {\n    color: #bdc1c9; }\n  .editor_controls .DraftEditorPlaceholder-hidden {\n    display: none; }\n  .editor_controls .public-DraftStyleDefault-block {\n    position: relative;\n    white-space: pre-wrap; }\n  .editor_controls .public-DraftStyleDefault-ltr {\n    direction: ltr;\n    text-align: left; }\n  .editor_controls .public-DraftStyleDefault-rtl {\n    direction: rtl;\n    text-align: right; }\n  .editor_controls .public-DraftStyleDefault-listLTR {\n    direction: ltr; }\n  .editor_controls .public-DraftStyleDefault-listRTL {\n    direction: rtl; }\n  .editor_controls .public-DraftStyleDefault-ol,\n  .editor_controls .public-DraftStyleDefault-ul {\n    margin: 16px 0;\n    padding: 0; }\n  .editor_controls .public-DraftStyleDefault-depth0.public-DraftStyleDefault-listLTR {\n    margin-left: 1.5em; }\n  .editor_controls .public-DraftStyleDefault-depth0.public-DraftStyleDefault-listRTL {\n    margin-right: 1.5em; }\n  .editor_controls .public-DraftStyleDefault-depth1.public-DraftStyleDefault-listLTR {\n    margin-left: 3em; }\n  .editor_controls .public-DraftStyleDefault-depth1.public-DraftStyleDefault-listRTL {\n    margin-right: 3em; }\n  .editor_controls .public-DraftStyleDefault-depth2.public-DraftStyleDefault-listLTR {\n    margin-left: 4.5em; }\n  .editor_controls .public-DraftStyleDefault-depth2.public-DraftStyleDefault-listRTL {\n    margin-right: 4.5em; }\n  .editor_controls .public-DraftStyleDefault-depth3.public-DraftStyleDefault-listLTR {\n    margin-left: 6em; }\n  .editor_controls .public-DraftStyleDefault-depth3.public-DraftStyleDefault-listRTL {\n    margin-right: 6em; }\n  .editor_controls .public-DraftStyleDefault-depth4.public-DraftStyleDefault-listLTR {\n    margin-left: 7.5em; }\n  .editor_controls .public-DraftStyleDefault-depth4.public-DraftStyleDefault-listRTL {\n    margin-right: 7.5em; }\n  .editor_controls .public-DraftStyleDefault-unorderedListItem {\n    list-style-type: square;\n    position: relative; }\n  .editor_controls .public-DraftStyleDefault-unorderedListItem.public-DraftStyleDefault-depth0 {\n    list-style-type: disc; }\n  .editor_controls .public-DraftStyleDefault-unorderedListItem.public-DraftStyleDefault-depth1 {\n    list-style-type: circle; }\n  .editor_controls .public-DraftStyleDefault-orderedListItem {\n    list-style-type: none;\n    position: relative; }\n  .editor_controls .public-DraftStyleDefault-orderedListItem.public-DraftStyleDefault-listLTR:before {\n    left: -36px;\n    position: absolute;\n    text-align: right;\n    width: 30px; }\n  .editor_controls .public-DraftStyleDefault-orderedListItem.public-DraftStyleDefault-listRTL:before {\n    position: absolute;\n    right: -36px;\n    text-align: left;\n    width: 30px; }\n  .editor_controls .public-DraftStyleDefault-orderedListItem:before {\n    content: counter(ol0) \". \";\n    counter-increment: ol0; }\n  .editor_controls .public-DraftStyleDefault-orderedListItem.public-DraftStyleDefault-depth1:before {\n    content: counter(ol1) \". \";\n    counter-increment: ol1; }\n  .editor_controls .public-DraftStyleDefault-orderedListItem.public-DraftStyleDefault-depth2:before {\n    content: counter(ol2) \". \";\n    counter-increment: ol2; }\n  .editor_controls .public-DraftStyleDefault-orderedListItem.public-DraftStyleDefault-depth3:before {\n    content: counter(ol3) \". \";\n    counter-increment: ol3; }\n  .editor_controls .public-DraftStyleDefault-orderedListItem.public-DraftStyleDefault-depth4:before {\n    content: counter(ol4) \". \";\n    counter-increment: ol4; }\n  .editor_controls .public-DraftStyleDefault-depth0.public-DraftStyleDefault-reset {\n    counter-reset: ol0; }\n  .editor_controls .public-DraftStyleDefault-depth1.public-DraftStyleDefault-reset {\n    counter-reset: ol1; }\n  .editor_controls .public-DraftStyleDefault-depth2.public-DraftStyleDefault-reset {\n    counter-reset: ol2; }\n  .editor_controls .public-DraftStyleDefault-depth3.public-DraftStyleDefault-reset {\n    counter-reset: ol3; }\n  .editor_controls .public-DraftStyleDefault-depth4.public-DraftStyleDefault-reset {\n    counter-reset: ol4; }\n  .editor_controls .rangeslider {\n    margin: 0 var(--spacing-quarter-unit);\n    min-width: 60px;\n    position: relative;\n    background: var(--color-background-light);\n    -ms-touch-action: none;\n    touch-action: none;\n    border: 1px solid var(--color-border-default);\n    flex-grow: 1; }\n    .editor_controls .rangeslider,\n    .editor_controls .rangeslider .rangeslider__fill {\n      display: block; }\n    .editor_controls .rangeslider .rangeslider__handle {\n      outline: 0;\n      background: #fff;\n      border: 1px solid var(--color-border-default);\n      cursor: pointer;\n      display: inline-block;\n      position: absolute; }\n      .editor_controls .rangeslider .rangeslider__handle .rangeslider__active {\n        opacity: 1; }\n    .editor_controls .rangeslider .rangeslider__handle-tooltip {\n      width: 20px;\n      height: 20px;\n      text-align: center;\n      position: absolute;\n      background-color: rgba(0, 0, 0, 0.8);\n      font-weight: normal;\n      font-size: 14px;\n      transition: all 100ms ease-in;\n      border-radius: 4px;\n      display: inline-block;\n      color: white;\n      left: 50%;\n      transform: translate3d(-50%, 0, 0); }\n      .editor_controls .rangeslider .rangeslider__handle-tooltip span {\n        margin-top: 12px;\n        display: inline-block;\n        line-height: 100%; }\n      .editor_controls .rangeslider .rangeslider__handle-tooltip:after {\n        content: ' ';\n        position: absolute;\n        width: 0;\n        height: 0; }\n  .editor_controls .rangeslider-horizontal {\n    height: 6px;\n    border-radius: 10px; }\n    .editor_controls .rangeslider-horizontal .rangeslider__fill {\n      height: 100%;\n      background-color: var(--color-accent);\n      border: var(--border-accent);\n      border-radius: 10px;\n      transform: translateY(-1px);\n      top: 0; }\n    .editor_controls .rangeslider-horizontal .rangeslider__handle {\n      width: 6.66667px;\n      height: 30px;\n      border-radius: 20px;\n      top: 50%;\n      transform: translate3d(-50%, -50%, 0);\n      display: flex;\n      align-items: center;\n      justify-content: center; }\n      .editor_controls .rangeslider-horizontal .rangeslider__handle:after {\n        content: ' ';\n        position: absolute;\n        width: 4px;\n        height: 20px;\n        border-radius: 5px;\n        background-color: var(--color-accent);\n        display: none; }\n    .editor_controls .rangeslider-horizontal .rangeslider__handle-tooltip {\n      top: -55px; }\n      .editor_controls .rangeslider-horizontal .rangeslider__handle-tooltip:after {\n        border-left: 8px solid transparent;\n        border-right: 8px solid transparent;\n        border-top: 8px solid rgba(0, 0, 0, 0.8);\n        left: 50%;\n        bottom: -8px;\n        transform: translate3d(-50%, 0, 0); }\n  .editor_controls .rangeslider-vertical {\n    margin: 20px auto;\n    height: 150px;\n    max-width: 10px;\n    background-color: transparent; }\n    .editor_controls .rangeslider-vertical .rangeslider__fill,\n    .editor_controls .rangeslider-vertical .rangeslider__handle {\n      position: absolute; }\n    .editor_controls .rangeslider-vertical .rangeslider__fill {\n      width: 100%;\n      background-color: #7cb342;\n      box-shadow: none;\n      bottom: 0; }\n    .editor_controls .rangeslider-vertical .rangeslider__handle {\n      width: 30px;\n      height: 10px;\n      left: -10px;\n      box-shadow: none; }\n    .editor_controls .rangeslider-vertical .rangeslider__handle-tooltip {\n      left: -100%;\n      top: 50%;\n      transform: translate3d(-50%, -50%, 0); }\n      .editor_controls .rangeslider-vertical .rangeslider__handle-tooltip:after {\n        border-top: 8px solid transparent;\n        border-bottom: 8px solid transparent;\n        border-left: 8px solid rgba(0, 0, 0, 0.8);\n        left: 100%;\n        top: 12px; }\n  .editor_controls .rangeslider-reverse.rangeslider-horizontal .rangeslider__fill {\n    right: 0; }\n  .editor_controls .rangeslider-reverse.rangeslider-vertical .rangeslider__fill {\n    top: 0;\n    bottom: inherit; }\n  .editor_controls .rangeslider__labels {\n    position: relative; }\n    .rangeslider-vertical .editor_controls .rangeslider__labels {\n      position: relative;\n      list-style-type: none;\n      margin: 0 0 0 24px;\n      padding: 0;\n      text-align: left;\n      width: 250px;\n      height: 100%;\n      left: 10px; }\n      .rangeslider-vertical .editor_controls .rangeslider__labels .rangeslider__label-item {\n        position: absolute;\n        transform: translate3d(0, -50%, 0); }\n        .rangeslider-vertical .editor_controls .rangeslider__labels .rangeslider__label-item::before {\n          content: '';\n          width: 10px;\n          height: 2px;\n          background: black;\n          position: absolute;\n          left: -14px;\n          top: 50%;\n          transform: translateY(-50%);\n          z-index: -1; }\n    .editor_controls .rangeslider__labels .rangeslider__label-item {\n      position: absolute;\n      font-size: 14px;\n      cursor: pointer;\n      display: inline-block;\n      top: 10px;\n      transform: translate3d(-50%, 0, 0); }\n  .editor_controls .trace-grid-single-block {\n    max-width: 460px;\n    display: flex;\n    flex-flow: wrap;\n    padding: var(--spacing-quarter-unit); }\n  .editor_controls .trace-grid {\n    display: grid;\n    grid-template-columns: repeat(4, 1fr); }\n    @media (max-width: 860px) {\n      .editor_controls .trace-grid {\n        grid-template-columns: repeat(2, 1fr); } }\n    .editor_controls .trace-grid__column {\n      text-align: center;\n      display: flex;\n      align-items: flex-start;\n      justify-content: flex-start;\n      flex-direction: column;\n      flex-shrink: 0;\n      flex-grow: 0; }\n      .editor_controls .trace-grid__column:nth-of-type(4n + 3) {\n        -ms-grid-column: 1; }\n      .editor_controls .trace-grid__column:nth-of-type(4n) {\n        -ms-grid-column: 2; }\n      .editor_controls .trace-grid__column:nth-of-type(4n + 1) {\n        -ms-grid-column: 3; }\n      .editor_controls .trace-grid__column:nth-of-type(4n + 2) {\n        -ms-grid-column: 4; }\n      .editor_controls .trace-grid__column:nth-of-type(3), .editor_controls .trace-grid__column:nth-of-type(4), .editor_controls .trace-grid__column:nth-of-type(5), .editor_controls .trace-grid__column:nth-of-type(6) {\n        -ms-grid-row: 2; }\n      .editor_controls .trace-grid__column:nth-of-type(7), .editor_controls .trace-grid__column:nth-of-type(8), .editor_controls .trace-grid__column:nth-of-type(9), .editor_controls .trace-grid__column:nth-of-type(10) {\n        -ms-grid-row: 3; }\n      .editor_controls .trace-grid__column .trace-item:nth-of-type(2n + 1) {\n        -ms-grid-column: 1; }\n      .editor_controls .trace-grid__column .trace-item:nth-of-type(2n + 2) {\n        -ms-grid-column: 2; }\n      .editor_controls .trace-grid__column .trace-item:nth-of-type(3), .editor_controls .trace-grid__column .trace-item:nth-of-type(4) {\n        -ms-grid-row: 2; }\n      .editor_controls .trace-grid__column .trace-item:nth-of-type(5), .editor_controls .trace-grid__column .trace-item:nth-of-type(6) {\n        -ms-grid-row: 3; }\n      .editor_controls .trace-grid__column .trace-item:nth-of-type(7), .editor_controls .trace-grid__column .trace-item:nth-of-type(8) {\n        -ms-grid-row: 4; }\n      .editor_controls .trace-grid__column:not(:first-of-type) {\n        position: relative; }\n        .editor_controls .trace-grid__column:not(:first-of-type)::before {\n          position: absolute;\n          width: 1px;\n          border-left: var(--border-light);\n          height: 100%;\n          top: 0;\n          left: 0;\n          content: ''; }\n        .editor_controls .trace-grid__column:not(:first-of-type) .trace-grid__column__header {\n          position: relative;\n          z-index: 99; }\n      .editor_controls .trace-grid__column--double {\n        grid-column: span 2;\n        flex-grow: 0; }\n        .editor_controls .trace-grid__column--double:nth-of-type(2n + 1) {\n          -ms-grid-column: 1; }\n        .editor_controls .trace-grid__column--double:nth-of-type(2n + 2) {\n          -ms-grid-column: 3; }\n        .editor_controls .trace-grid__column--double:nth-of-type(5), .editor_controls .trace-grid__column--double:nth-of-type(6) {\n          -ms-grid-row: 2; }\n        .editor_controls .trace-grid__column--double:nth-of-type(7), .editor_controls .trace-grid__column--double:nth-of-type(8) {\n          -ms-grid-row: 3; }\n        .editor_controls .trace-grid__column--double .trace-item:nth-of-type(4n + 1) {\n          -ms-grid-column: 1; }\n        .editor_controls .trace-grid__column--double .trace-item:nth-of-type(4n + 2) {\n          -ms-grid-column: 2; }\n        .editor_controls .trace-grid__column--double .trace-item:nth-of-type(4n + 3) {\n          -ms-grid-column: 3; }\n        .editor_controls .trace-grid__column--double .trace-item:nth-of-type(4n) {\n          -ms-grid-column: 4; }\n        .editor_controls .trace-grid__column--double .trace-item:nth-of-type(3), .editor_controls .trace-grid__column--double .trace-item:nth-of-type(4) {\n          -ms-grid-row: 1; }\n        .editor_controls .trace-grid__column--double .trace-item:nth-of-type(5), .editor_controls .trace-grid__column--double .trace-item:nth-of-type(6), .editor_controls .trace-grid__column--double .trace-item:nth-of-type(7), .editor_controls .trace-grid__column--double .trace-item:nth-of-type(8) {\n          -ms-grid-row: 2; }\n        .editor_controls .trace-grid__column--double .trace-item:nth-of-type(9), .editor_controls .trace-grid__column--double .trace-item:nth-of-type(10), .editor_controls .trace-grid__column--double .trace-item:nth-of-type(11), .editor_controls .trace-grid__column--double .trace-item:nth-of-type(12) {\n          -ms-grid-row: 3; }\n        .editor_controls .trace-grid__column--double .trace-grid__column__items {\n          display: grid;\n          grid-gap: 0;\n          grid-template-columns: repeat(4, 1fr); }\n      .editor_controls .trace-grid__column__items {\n        display: grid;\n        grid-gap: 0;\n        grid-template-columns: repeat(2, 90px);\n        grid-template-rows: repeat(2, 112px);\n        flex-grow: 1;\n        width: 100%;\n        padding: 0 var(--spacing-half-unit) var(--spacing-half-unit); }\n      .editor_controls .trace-grid__column__header {\n        text-transform: capitalize;\n        font-weight: var(--font-weight-semibold);\n        color: var(--color-text-base);\n        text-align: left;\n        display: flex;\n        align-items: center;\n        justify-content: flex-start;\n        border-top: var(--border-light);\n        width: 100%;\n        padding: var(--spacing-half-unit) var(--spacing-base-unit) 0;\n        box-sizing: border-box; }\n  .editor_controls .trace-item {\n    width: 90px;\n    display: flex;\n    flex-direction: column;\n    align-items: center;\n    justify-content: flex-start;\n    flex-grow: 0;\n    margin-top: var(--spacing-half-unit);\n    color: var(--color-text-base);\n    transition: all 0.15s ease-in-out;\n    position: relative; }\n    .editor_controls .trace-item--active .trace-item__image {\n      border-color: var(--color-accent);\n      border-width: 2px;\n      color: var(--color-accent); }\n    .editor_controls .trace-item__actions {\n      position: absolute;\n      width: calc(100%);\n      display: flex;\n      flex-direction: column;\n      top: 0;\n      left: var(--spacing-quarter-unit);\n      justify-content: flex-start;\n      align-items: flex-end;\n      z-index: 99;\n      height: 60px; }\n      .editor_controls .trace-item__actions:hover .trace-item__actions__item {\n        transform: translateX(-2px);\n        opacity: 1;\n        pointer-events: initial; }\n      .editor_controls .trace-item__actions__item {\n        transform: translateX(-10px);\n        opacity: 0;\n        pointer-events: none;\n        color: var(--color-text-light);\n        transition: all 0.15s ease-in-out; }\n        .editor_controls .trace-item__actions__item:not(:last-child) {\n          margin-bottom: var(--spacing-quarter-unit); }\n        .editor_controls .trace-item__actions__item:hover {\n          color: var(--color-accent); }\n        .editor_controls .trace-item__actions__item svg {\n          display: block;\n          width: 16px;\n          height: 16px;\n          fill: currentColor; }\n    .editor_controls .trace-item:hover {\n      cursor: pointer;\n      color: var(--color-accent); }\n      .editor_controls .trace-item:hover .trace-item__label {\n        color: var(--color-accent); }\n      .editor_controls .trace-item:hover .trace-item__image {\n        border-color: var(--color-accent); }\n    .editor_controls .trace-item__image {\n      position: relative;\n      z-index: 2;\n      border: 1px solid var(--color-border-default);\n      width: 60px;\n      height: 60px;\n      border-radius: var(--border-radius);\n      background: var(--color-background-top);\n      box-shadow: 0 2px 9px transparent;\n      display: flex;\n      align-items: center;\n      justify-content: center;\n      transition: all 0.15s ease-in-out; }\n      .editor_controls .trace-item__image__svg {\n        width: 100%;\n        flex-grow: 1;\n        padding: var(--spacing-quarter-unit); }\n      .editor_controls .trace-item__image svg {\n        display: block; }\n      .editor_controls .trace-item__image img {\n        display: block;\n        font-size: 10px;\n        color: var(--color-text-base); }\n      .editor_controls .trace-item__image__wrapper {\n        width: 100%; }\n    .editor_controls .trace-item__label {\n      font-weight: var(--font-weight-semibold);\n      width: 72px;\n      height: 34px;\n      margin-top: var(--spacing-quarter-unit);\n      color: var(--color-text-base);\n      text-transform: capitalize;\n      font-size: var(--font-size-small);\n      text-align: center; }\n  .editor_controls .trace-type-select-dropdown__wrapper > * > * {\n    pointer-events: none; }\n  .editor_controls .trace-type-select-dropdown__wrapper > *:hover {\n    cursor: pointer; }\n    .editor_controls .trace-type-select-dropdown__wrapper > *:hover .Select:not(.is-open) .Select-control {\n      border-color: var(--color-border-dark); }\n  .editor_controls .trace-type-select-button {\n    display: flex;\n    align-items: center;\n    border: var(--border-default);\n    width: 100%;\n    height: 36px;\n    border-radius: var(--border-radius);\n    padding: 0 var(--spacing-quarter-unit); }\n    .editor_controls .trace-type-select-button:hover {\n      cursor: pointer;\n      border-color: var(--color-border-dark); }\n    .editor_controls .trace-type-select-button__icon {\n      max-width: 20px;\n      width: 20px;\n      margin-right: var(--spacing-quarter-unit); }\n      .editor_controls .trace-type-select-button__icon svg {\n        max-width: 100%;\n        display: block; }\n        .editor_controls .trace-type-select-button__icon svg * {\n          fill: currentColor; }\n  .editor_controls .dropzone-container {\n    flex-grow: 1;\n    display: flex;\n    align-items: center;\n    justify-content: center;\n    border: 1px dashed var(--color-border-default);\n    height: 160px;\n    box-sizing: border-box;\n    padding: 8px;\n    border-radius: var(--border-radius); }\n    .editor_controls .dropzone-container__content {\n      width: 100%;\n      height: 100%;\n      text-align: center;\n      background-color: var(--color-rhino-light-5);\n      border-radius: var(--border-radius);\n      display: flex;\n      align-items: center;\n      justify-content: center; }\n    .editor_controls .dropzone-container__message {\n      padding: 15px; }\n    .editor_controls .dropzone-container__image {\n      width: 100%;\n      height: 100%;\n      background-size: contain;\n      background-position: center;\n      position: relative;\n      background-repeat: no-repeat; }\n    .editor_controls .dropzone-container--active {\n      border-color: var(--color-dodger); }\n    .editor_controls .dropzone-container--rejected {\n      border-color: red; }\n  .editor_controls [aria-label][role~='tooltip'] {\n    position: relative; }\n  .editor_controls [aria-label][role~='tooltip']::before,\n  .editor_controls [aria-label][role~='tooltip']::after {\n    transform: translate3d(0, 0, 0);\n    -webkit-backface-visibility: hidden;\n    backface-visibility: hidden;\n    display: none;\n    will-change: transform;\n    opacity: 0;\n    pointer-events: none;\n    transition: all var(--microtip-transition-duration, 0.18s) var(--microtip-transition-easing, ease-in-out) var(--microtip-transition-delay, 0s);\n    position: absolute;\n    box-sizing: border-box;\n    z-index: 10;\n    transform-origin: top; }\n  .editor_controls [aria-label][role~='tooltip']::before {\n    background-size: 100% auto !important;\n    content: ''; }\n  .editor_controls [aria-label][role~='tooltip']::after {\n    background: #506784;\n    border-radius: 4px;\n    color: #ffffff;\n    content: attr(aria-label);\n    font-size: var(--microtip-font-size, 13px);\n    font-weight: var(--microtip-font-weight, normal);\n    text-transform: var(--microtip-text-transform, none);\n    padding: 0.5em 1em;\n    white-space: nowrap;\n    box-sizing: content-box; }\n  .editor_controls [aria-label][role~='tooltip']:hover::before,\n  .editor_controls [aria-label][role~='tooltip']:hover::after,\n  .editor_controls [aria-label][role~='tooltip']:focus::before,\n  .editor_controls [aria-label][role~='tooltip']:focus::after {\n    opacity: 1;\n    pointer-events: auto;\n    display: block; }\n  .editor_controls [role~='tooltip'][data-microtip-position|='top']::before {\n    background: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2236px%22%20height%3D%2212px%22%3E%3Cpath%20fill%3D%22rgba%2880,%20103,%20132,%201%29%22%20transform%3D%22rotate%280%29%22%20d%3D%22M2.658,0.000%20C-13.615,0.000%2050.938,0.000%2034.662,0.000%20C28.662,0.000%2023.035,12.002%2018.660,12.002%20C14.285,12.002%208.594,0.000%202.658,0.000%20Z%22/%3E%3C/svg%3E\") no-repeat;\n    height: 6px;\n    width: 18px;\n    margin-bottom: 5px; }\n  .editor_controls [role~='tooltip'][data-microtip-position|='top']::after {\n    margin-bottom: 11px; }\n  .editor_controls [role~='tooltip'][data-microtip-position|='top']::before {\n    transform: translate3d(-50%, 0, 0);\n    bottom: 100%;\n    left: 50%; }\n  .editor_controls [role~='tooltip'][data-microtip-position|='top']:hover::before {\n    transform: translate3d(-50%, -5px, 0); }\n  .editor_controls [role~='tooltip'][data-microtip-position|='top']::after {\n    transform: translate3d(-50%, 0, 0);\n    bottom: 100%;\n    left: 50%; }\n  .editor_controls [role~='tooltip'][data-microtip-position='top']:hover::after {\n    transform: translate3d(-50%, -5px, 0); }\n  .editor_controls [role~='tooltip'][data-microtip-position='top-left']::after {\n    transform: translate3d(calc(-100% + 16px), 0, 0);\n    bottom: 100%; }\n  .editor_controls [role~='tooltip'][data-microtip-position='top-left']:hover::after {\n    transform: translate3d(calc(-100% + 16px), -5px, 0); }\n  .editor_controls [role~='tooltip'][data-microtip-position='top-right']::after {\n    transform: translate3d(calc(0% + -16px), 0, 0);\n    bottom: 100%; }\n  .editor_controls [role~='tooltip'][data-microtip-position='top-right']:hover::after {\n    transform: translate3d(calc(0% + -16px), -5px, 0); }\n  .editor_controls [role~='tooltip'][data-microtip-position|='bottom']::before {\n    background: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2236px%22%20height%3D%2212px%22%3E%3Cpath%20fill%3D%22rgba%2880,%20103,%20132,%201%29%22%20transform%3D%22rotate%28180%2018%206%29%22%20d%3D%22M2.658,0.000%20C-13.615,0.000%2050.938,0.000%2034.662,0.000%20C28.662,0.000%2023.035,12.002%2018.660,12.002%20C14.285,12.002%208.594,0.000%202.658,0.000%20Z%22/%3E%3C/svg%3E\") no-repeat;\n    height: 6px;\n    width: 18px;\n    margin-top: 5px;\n    margin-bottom: 0; }\n  .editor_controls [role~='tooltip'][data-microtip-position|='bottom']::after {\n    margin-top: 11px; }\n  .editor_controls [role~='tooltip'][data-microtip-position|='bottom']::before {\n    transform: translate3d(-50%, -10px, 0);\n    bottom: auto;\n    left: 10px;\n    top: 100%; }\n  .editor_controls [role~='tooltip'][data-microtip-position|='bottom']:hover::before {\n    transform: translate3d(-50%, 0, 0); }\n  .editor_controls [role~='tooltip'][data-microtip-position|='bottom']::after {\n    transform: translate3d(-50%, -10px, 0);\n    left: 10px;\n    top: 100%; }\n  .editor_controls [role~='tooltip'][data-microtip-position='bottom']:hover::after {\n    transform: translate3d(-50%, 0, 0); }\n  .editor_controls [role~='tooltip'][data-microtip-position='bottom-left']::after {\n    transform: translate3d(calc(-100% + 16px), -10px, 0);\n    top: 100%; }\n  .editor_controls [role~='tooltip'][data-microtip-position='bottom-left']:hover::after {\n    transform: translate3d(calc(-100% + 16px), 0, 0); }\n  .editor_controls [role~='tooltip'][data-microtip-position='bottom-right']::after {\n    transform: translate3d(calc(0% + -16px), -10px, 0);\n    top: 100%; }\n  .editor_controls [role~='tooltip'][data-microtip-position='bottom-right']:hover::after {\n    transform: translate3d(calc(0% + -16px), 0, 0); }\n  .editor_controls [role~='tooltip'][data-microtip-position='left']::before,\n  .editor_controls [role~='tooltip'][data-microtip-position='left']::after {\n    bottom: auto;\n    left: auto;\n    right: 100%;\n    top: 50%;\n    transform: translate3d(10px, -50%, 0); }\n  .editor_controls [role~='tooltip'][data-microtip-position='left']::before {\n    background: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2212px%22%20height%3D%2236px%22%3E%3Cpath%20fill%3D%22rgba%2880,%20103,%20132,%201%29%22%20transform%3D%22rotate%28-90%2018%2018%29%22%20d%3D%22M2.658,0.000%20C-13.615,0.000%2050.938,0.000%2034.662,0.000%20C28.662,0.000%2023.035,12.002%2018.660,12.002%20C14.285,12.002%208.594,0.000%202.658,0.000%20Z%22/%3E%3C/svg%3E\") no-repeat;\n    height: 18px;\n    width: 6px;\n    margin-right: 5px;\n    margin-bottom: 0; }\n  .editor_controls [role~='tooltip'][data-microtip-position='left']::after {\n    margin-right: 11px; }\n  .editor_controls [role~='tooltip'][data-microtip-position='left']:hover::before,\n  .editor_controls [role~='tooltip'][data-microtip-position='left']:hover::after {\n    transform: translate3d(0, -50%, 0); }\n  .editor_controls [role~='tooltip'][data-microtip-position='right']::before,\n  .editor_controls [role~='tooltip'][data-microtip-position='right']::after {\n    bottom: auto;\n    left: 100%;\n    top: 50%;\n    transform: translate3d(-10px, -50%, 0); }\n  .editor_controls [role~='tooltip'][data-microtip-position='right']::before {\n    background: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2212px%22%20height%3D%2236px%22%3E%3Cpath%20fill%3D%22rgba%2880,%20103,%20132,%201%29%22%20transform%3D%22rotate%2890%206%206%29%22%20d%3D%22M2.658,0.000%20C-13.615,0.000%2050.938,0.000%2034.662,0.000%20C28.662,0.000%2023.035,12.002%2018.660,12.002%20C14.285,12.002%208.594,0.000%202.658,0.000%20Z%22/%3E%3C/svg%3E\") no-repeat;\n    height: 18px;\n    width: 6px;\n    margin-bottom: 0;\n    margin-left: 5px; }\n  .editor_controls [role~='tooltip'][data-microtip-position='right']::after {\n    margin-left: 11px; }\n  .editor_controls [role~='tooltip'][data-microtip-position='right']:hover::before,\n  .editor_controls [role~='tooltip'][data-microtip-position='right']:hover::after {\n    transform: translate3d(0, -50%, 0); }\n  .editor_controls [role~='tooltip'][data-microtip-size='small']::after {\n    white-space: initial;\n    width: 80px; }\n  .editor_controls [role~='tooltip'][data-microtip-size='medium']::after {\n    white-space: initial;\n    width: 140px; }\n  .editor_controls [role~='tooltip'][data-microtip-size='large']::after {\n    white-space: initial;\n    width: 260px; }\n  .editor_controls .datetimepicker-container {\n    min-width: 176px;\n    min-height: 70px; }\n    .editor_controls .datetimepicker-container .mdi-icon {\n      width: 20px;\n      margin: 2px; }\n    .editor_controls .datetimepicker-container__content {\n      margin-top: 5px; }\n  .editor_controls .datetimepicker-datepicker-container {\n    margin-top: 5px;\n    border: 1px solid var(--color-border-default);\n    border-radius: 5px; }\n  .editor_controls .datetimepicker-datepicker-navbar {\n    width: 200px;\n    height: 30px;\n    margin: 0 auto; }\n  .editor_controls .datetimepicker-container-date-input {\n    margin-top: -20px; }\n  .editor_controls .datetimepicker-container-icons {\n    display: inline-block;\n    margin-top: 2px;\n    margin-left: 2px; }\n  .editor_controls .datetimepicker-container-time {\n    margin-top: 5px; }\n  .editor_controls .datetimepicker-container-time-input,\n  .editor_controls .datetimepicker-container-date-input {\n    width: 130px; }\n  .editor_controls .datetimepicker-time-icon--selected,\n  .editor_controls .datetimepicker-date-icon--selected {\n    fill: var(--color-accent); }\n  .editor_controls .datetimepicker-time-icon:hover,\n  .editor_controls .datetimepicker-date-icon:hover {\n    fill: #899aaf; }\n  .editor_controls .datepicker-container-rce {\n    outline: none; }\n  .editor_controls .datetimepicker-date-units {\n    padding-left: 5px; }\n  .editor_controls .DayPicker {\n    font-size: var(--font-size-body); }\n  .editor_controls .DayPicker-NavBar,\n  .editor_controls .DayPicker-Caption {\n    display: none; }\n  .editor_controls .DayPicker-Month {\n    margin: 0px; }\n  .editor_controls .DayPicker-Months {\n    margin: 2px 0;\n    outline: none; }\n  .editor_controls .DayPicker-wrapper {\n    width: 220px;\n    padding-bottom: 5px;\n    outline: none; }\n  .editor_controls .DayPicker-Day {\n    outline: none !important; }\n  .editor_controls .DayPicker-Day--highlighted {\n    background-color: var(--color-accent);\n    color: white;\n    outline: none; }\n  .editor_controls .DayPicker-Day--highlighted:hover {\n    background-color: var(--color-accent) !important; }\n  .editor_controls .DayPicker-Weekday {\n    color: #577290 !important; }\n  .editor_controls .datimepicker-yearpicker,\n  .editor_controls .datimepicker-monthpicker {\n    display: inline-block;\n    font-size: 14px; }\n  .editor_controls .datimepicker-monthpicker {\n    min-width: 120px; }\n  .editor_controls .datimepicker-yearpicker {\n    min-width: 70px !important; }\n  .editor_controls .dropdown-container.datimepicker-monthpicker div div,\n  .editor_controls .dropdown-container.datimepicker-yearpicker div div {\n    border: none; }\n  .editor_controls .DayPicker-Day--today {\n    font-weight: var(--font-weight-normal); }\n  .editor_controls .DayPicker-Day--today:not(.DayPicker-Day--highlighted) {\n    color: var(--color-text-base); }\n  .editor_controls__wrapper {\n    display: flex;\n    flex-grow: 1; }\n  .editor_controls a {\n    color: #0d76bf;\n    cursor: pointer; }\n\n.plotly_editor {\n  display: flex;\n  /*\n       We are defining the max height of the app so that the editor knows how big to be\n       currently the editor will take up whatever space it can if it is not constrained in its parent\n     */\n  flex-grow: 1;\n  height: 100%;\n  max-height: 100%;\n  width: 100%; }\n\n.plotly_editor_plot {\n  max-width: 100%;\n  height: 100%;\n  max-height: 100%;\n  overflow: auto;\n  flex-grow: 1; }\n", ""]);

// exports


/***/ }),

/***/ "/9aa":
/*!*****************************************!*\
  !*** ./node_modules/lodash/isSymbol.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseGetTag = __webpack_require__(/*! ./_baseGetTag */ "NykK"),
    isObjectLike = __webpack_require__(/*! ./isObjectLike */ "ExA7");

/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';

/**
 * 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);
}

module.exports = isSymbol;


/***/ }),

/***/ "/9oY":
/*!********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/LogoStripeIcon.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var LogoStripeIcon = function LogoStripeIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M3.563 15.313c-.688-.25-1.063-.438-1.063-.75 0-.25.188-.375.563-.375.75 0 1.438.25 1.938.5l.313-1.75c-.375-.188-1.188-.5-2.313-.5-.813 0-1.5.188-1.938.563-.5.438-.75 1-.75 1.75 0 1.25.75 1.813 2.063 2.25.813.313 1.063.5 1.063.875 0 .313-.25.438-.75.438-.563 0-1.563-.25-2.188-.625l-.313 1.75c.563.313 1.563.625 2.625.625.875 0 1.563-.188 2.063-.563.5-.438.75-1.063.75-1.813 0-1.313-.75-1.875-2.063-2.375zm7-2.75h-1.5v-2.125l-2 .313-.313 1.813-.688.125-.313 1.625h1v3.375c0 .938.25 1.5.688 1.875.375.313.938.5 1.75.5.563 0 .938-.125 1.188-.188v-1.813c-.125 0-.438.125-.688.125-.438 0-.625-.25-.625-.813v-3.063h1.188zm4.625-.063h-.438c-.625 0-1.188.313-1.375.938l-.188-.875h-2v7.375H13.5v-4.813c.313-.375.75-.438 1.313-.438h.375v-2.188zm1.75-3.125c-.688 0-1.25.563-1.25 1.188 0 .688.563 1.25 1.25 1.25s1.25-.5 1.25-1.25c0-.688-.563-1.188-1.25-1.188zm1.187 10.563v-7.375H15.75v7.375zm6.688-6.688c-.438-.563-1-.813-1.75-.813-.688 0-1.25.25-1.813.875l-.125-.75h-2.063v10.063l2.313-.375v-2.375c.375.125.75.188 1.063.188.563 0 1.438-.188 2.125-.875.625-.688.938-1.75.938-3.188 0-1.188-.25-2.188-.688-2.75zm-2 4.5c-.188.375-.438.563-.813.563-.188 0-.438-.063-.625-.125v-3.5c.438-.438.75-.5.875-.5.625 0 .938.688.938 1.938 0 .688-.125 1.25-.375 1.625zm8.625-4.312c-.5-.688-1.25-1-2.25-1-2 0-3.188 1.438-3.188 3.813 0 1.313.313 2.313.938 2.938.625.563 1.438.875 2.563.875 1 0 1.875-.25 2.5-.625l-.25-1.625c-.625.313-1.25.5-2 .5-.5 0-.813-.125-1-.313-.25-.188-.375-.563-.438-1h3.875v-.813c0-1.188-.25-2.125-.75-2.75zm-3.125 2.125c.063-1.063.313-1.563.875-1.563.5 0 .813.5.813 1.563z' })
    );
};

exports.default = LogoStripeIcon;

/***/ }),

/***/ "/9rB":
/*!*************************************************!*\
  !*** ./node_modules/codemirror/mode/sql/sql.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"));
  else {}
})(function(CodeMirror) {
"use strict";

CodeMirror.defineMode("sql", function(config, parserConfig) {
  "use strict";

  var client         = parserConfig.client || {},
      atoms          = parserConfig.atoms || {"false": true, "true": true, "null": true},
      builtin        = parserConfig.builtin || {},
      keywords       = parserConfig.keywords || {},
      operatorChars  = parserConfig.operatorChars || /^[*+\-%<>!=&|~^]/,
      support        = parserConfig.support || {},
      hooks          = parserConfig.hooks || {},
      dateSQL        = parserConfig.dateSQL || {"date" : true, "time" : true, "timestamp" : true},
      backslashStringEscapes = parserConfig.backslashStringEscapes !== false,
      brackets       = parserConfig.brackets || /^[\{}\(\)\[\]]/,
      punctuation    = parserConfig.punctuation || /^[;.,:]/

  function tokenBase(stream, state) {
    var ch = stream.next();

    // call hooks from the mime type
    if (hooks[ch]) {
      var result = hooks[ch](stream, state);
      if (result !== false) return result;
    }

    if (support.hexNumber &&
      ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/))
      || (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]+'/))) {
      // hex
      // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html
      return "number";
    } else if (support.binaryNumber &&
      (((ch == "b" || ch == "B") && stream.match(/^'[01]+'/))
      || (ch == "0" && stream.match(/^b[01]+/)))) {
      // bitstring
      // ref: http://dev.mysql.com/doc/refman/5.5/en/bit-field-literals.html
      return "number";
    } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) {
      // numbers
      // ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html
      stream.match(/^[0-9]*(\.[0-9]+)?([eE][-+]?[0-9]+)?/);
      support.decimallessFloat && stream.match(/^\.(?!\.)/);
      return "number";
    } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) {
      // placeholders
      return "variable-3";
    } else if (ch == "'" || (ch == '"' && support.doubleQuote)) {
      // strings
      // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html
      state.tokenize = tokenLiteral(ch);
      return state.tokenize(stream, state);
    } else if ((((support.nCharCast && (ch == "n" || ch == "N"))
        || (support.charsetCast && ch == "_" && stream.match(/[a-z][a-z0-9]*/i)))
        && (stream.peek() == "'" || stream.peek() == '"'))) {
      // charset casting: _utf8'str', N'str', n'str'
      // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html
      return "keyword";
    } else if (support.commentSlashSlash && ch == "/" && stream.eat("/")) {
      // 1-line comment
      stream.skipToEnd();
      return "comment";
    } else if ((support.commentHash && ch == "#")
        || (ch == "-" && stream.eat("-") && (!support.commentSpaceRequired || stream.eat(" ")))) {
      // 1-line comments
      // ref: https://kb.askmonty.org/en/comment-syntax/
      stream.skipToEnd();
      return "comment";
    } else if (ch == "/" && stream.eat("*")) {
      // multi-line comments
      // ref: https://kb.askmonty.org/en/comment-syntax/
      state.tokenize = tokenComment(1);
      return state.tokenize(stream, state);
    } else if (ch == ".") {
      // .1 for 0.1
      if (support.zerolessFloat && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i))
        return "number";
      if (stream.match(/^\.+/))
        return null
      // .table_name (ODBC)
      // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html
      if (support.ODBCdotTable && stream.match(/^[\w\d_]+/))
        return "variable-2";
    } else if (operatorChars.test(ch)) {
      // operators
      stream.eatWhile(operatorChars);
      return "operator";
    } else if (brackets.test(ch)) {
      // brackets
      stream.eatWhile(brackets);
      return "bracket";
    } else if (punctuation.test(ch)) {
      // punctuation
      stream.eatWhile(punctuation);
      return "punctuation";
    } else if (ch == '{' &&
        (stream.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/) || stream.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/))) {
      // dates (weird ODBC syntax)
      // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html
      return "number";
    } else {
      stream.eatWhile(/^[_\w\d]/);
      var word = stream.current().toLowerCase();
      // dates (standard SQL syntax)
      // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html
      if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+"[^"]*"/)))
        return "number";
      if (atoms.hasOwnProperty(word)) return "atom";
      if (builtin.hasOwnProperty(word)) return "builtin";
      if (keywords.hasOwnProperty(word)) return "keyword";
      if (client.hasOwnProperty(word)) return "string-2";
      return null;
    }
  }

  // 'string', with char specified in quote escaped by '\'
  function tokenLiteral(quote) {
    return function(stream, state) {
      var escaped = false, ch;
      while ((ch = stream.next()) != null) {
        if (ch == quote && !escaped) {
          state.tokenize = tokenBase;
          break;
        }
        escaped = backslashStringEscapes && !escaped && ch == "\\";
      }
      return "string";
    };
  }
  function tokenComment(depth) {
    return function(stream, state) {
      var m = stream.match(/^.*?(\/\*|\*\/)/)
      if (!m) stream.skipToEnd()
      else if (m[1] == "/*") state.tokenize = tokenComment(depth + 1)
      else if (depth > 1) state.tokenize = tokenComment(depth - 1)
      else state.tokenize = tokenBase
      return "comment"
    }
  }

  function pushContext(stream, state, type) {
    state.context = {
      prev: state.context,
      indent: stream.indentation(),
      col: stream.column(),
      type: type
    };
  }

  function popContext(state) {
    state.indent = state.context.indent;
    state.context = state.context.prev;
  }

  return {
    startState: function() {
      return {tokenize: tokenBase, context: null};
    },

    token: function(stream, state) {
      if (stream.sol()) {
        if (state.context && state.context.align == null)
          state.context.align = false;
      }
      if (state.tokenize == tokenBase && stream.eatSpace()) return null;

      var style = state.tokenize(stream, state);
      if (style == "comment") return style;

      if (state.context && state.context.align == null)
        state.context.align = true;

      var tok = stream.current();
      if (tok == "(")
        pushContext(stream, state, ")");
      else if (tok == "[")
        pushContext(stream, state, "]");
      else if (state.context && state.context.type == tok)
        popContext(state);
      return style;
    },

    indent: function(state, textAfter) {
      var cx = state.context;
      if (!cx) return CodeMirror.Pass;
      var closing = textAfter.charAt(0) == cx.type;
      if (cx.align) return cx.col + (closing ? 0 : 1);
      else return cx.indent + (closing ? 0 : config.indentUnit);
    },

    blockCommentStart: "/*",
    blockCommentEnd: "*/",
    lineComment: support.commentSlashSlash ? "//" : support.commentHash ? "#" : "--",
    closeBrackets: "()[]{}''\"\"``"
  };
});

(function() {
  "use strict";

  // `identifier`
  function hookIdentifier(stream) {
    // MySQL/MariaDB identifiers
    // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html
    var ch;
    while ((ch = stream.next()) != null) {
      if (ch == "`" && !stream.eat("`")) return "variable-2";
    }
    stream.backUp(stream.current().length - 1);
    return stream.eatWhile(/\w/) ? "variable-2" : null;
  }

  // "identifier"
  function hookIdentifierDoublequote(stream) {
    // Standard SQL /SQLite identifiers
    // ref: http://web.archive.org/web/20160813185132/http://savage.net.au/SQL/sql-99.bnf.html#delimited%20identifier
    // ref: http://sqlite.org/lang_keywords.html
    var ch;
    while ((ch = stream.next()) != null) {
      if (ch == "\"" && !stream.eat("\"")) return "variable-2";
    }
    stream.backUp(stream.current().length - 1);
    return stream.eatWhile(/\w/) ? "variable-2" : null;
  }

  // variable token
  function hookVar(stream) {
    // variables
    // @@prefix.varName @varName
    // varName can be quoted with ` or ' or "
    // ref: http://dev.mysql.com/doc/refman/5.5/en/user-variables.html
    if (stream.eat("@")) {
      stream.match(/^session\./);
      stream.match(/^local\./);
      stream.match(/^global\./);
    }

    if (stream.eat("'")) {
      stream.match(/^.*'/);
      return "variable-2";
    } else if (stream.eat('"')) {
      stream.match(/^.*"/);
      return "variable-2";
    } else if (stream.eat("`")) {
      stream.match(/^.*`/);
      return "variable-2";
    } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) {
      return "variable-2";
    }
    return null;
  };

  // short client keyword token
  function hookClient(stream) {
    // \N means NULL
    // ref: http://dev.mysql.com/doc/refman/5.5/en/null-values.html
    if (stream.eat("N")) {
        return "atom";
    }
    // \g, etc
    // ref: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html
    return stream.match(/^[a-zA-Z.#!?]/) ? "variable-2" : null;
  }

  // these keywords are used by all SQL dialects (however, a mode can still overwrite it)
  var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit ";

  // turn a space-separated list into an array
  function set(str) {
    var obj = {}, words = str.split(" ");
    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
    return obj;
  }

  // A generic SQL Mode. It's not a standard, it just try to support what is generally supported
  CodeMirror.defineMIME("text/x-sql", {
    name: "sql",
    keywords: set(sqlKeywords + "begin"),
    builtin: set("bool boolean bit blob enum long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision real date datetime year unsigned signed decimal numeric"),
    atoms: set("false true null unknown"),
    operatorChars: /^[*+\-%<>!=]/,
    dateSQL: set("date time timestamp"),
    support: set("ODBCdotTable doubleQuote binaryNumber hexNumber")
  });

  CodeMirror.defineMIME("text/x-mssql", {
    name: "sql",
    client: set("$partition binary_checksum checksum connectionproperty context_info current_request_id error_line error_message error_number error_procedure error_severity error_state formatmessage get_filestream_transaction_context getansinull host_id host_name isnull isnumeric min_active_rowversion newid newsequentialid rowcount_big xact_state object_id"),
    keywords: set(sqlKeywords + "begin trigger proc view index for add constraint key primary foreign collate clustered nonclustered declare exec go if use index holdlock nolock nowait paglock readcommitted readcommittedlock readpast readuncommitted repeatableread rowlock serializable snapshot tablock tablockx updlock with"),
    builtin: set("bigint numeric bit smallint decimal smallmoney int tinyint money float real char varchar text nchar nvarchar ntext binary varbinary image cursor timestamp hierarchyid uniqueidentifier sql_variant xml table "),
    atoms: set("is not null like and or in left right between inner outer join all any some cross unpivot pivot exists"),
    operatorChars: /^[*+\-%<>!=^\&|\/]/,
    brackets: /^[\{}\(\)]/,
    punctuation: /^[;.,:/]/,
    backslashStringEscapes: false,
    dateSQL: set("date datetimeoffset datetime2 smalldatetime datetime time"),
    hooks: {
      "@":   hookVar
    }
  });

  CodeMirror.defineMIME("text/x-mysql", {
    name: "sql",
    client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
    keywords: set(sqlKeywords + "accessible action add after algorithm all analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general get global grant grants group group_concat handler hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"),
    builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"),
    atoms: set("false true null unknown"),
    operatorChars: /^[*+\-%<>!=&|^]/,
    dateSQL: set("date time timestamp"),
    support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),
    hooks: {
      "@":   hookVar,
      "`":   hookIdentifier,
      "\\":  hookClient
    }
  });

  CodeMirror.defineMIME("text/x-mariadb", {
    name: "sql",
    client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
    keywords: set(sqlKeywords + "accessible action add after algorithm all always analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general generated get global grant grants group groupby_concat handler hard hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password persistent phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show shutdown signal slave slow smallint snapshot soft soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views virtual warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"),
    builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"),
    atoms: set("false true null unknown"),
    operatorChars: /^[*+\-%<>!=&|^]/,
    dateSQL: set("date time timestamp"),
    support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),
    hooks: {
      "@":   hookVar,
      "`":   hookIdentifier,
      "\\":  hookClient
    }
  });

  // provided by the phpLiteAdmin project - phpliteadmin.org
  CodeMirror.defineMIME("text/x-sqlite", {
    name: "sql",
    // commands of the official SQLite client, ref: https://www.sqlite.org/cli.html#dotcmd
    client: set("auth backup bail binary changes check clone databases dbinfo dump echo eqp exit explain fullschema headers help import imposter indexes iotrace limit lint load log mode nullvalue once open output print prompt quit read restore save scanstats schema separator session shell show stats system tables testcase timeout timer trace vfsinfo vfslist vfsname width"),
    // ref: http://sqlite.org/lang_keywords.html
    keywords: set(sqlKeywords + "abort action add after all analyze attach autoincrement before begin cascade case cast check collate column commit conflict constraint cross current_date current_time current_timestamp database default deferrable deferred detach each else end escape except exclusive exists explain fail for foreign full glob if ignore immediate index indexed initially inner instead intersect isnull key left limit match natural no notnull null of offset outer plan pragma primary query raise recursive references regexp reindex release rename replace restrict right rollback row savepoint temp temporary then to transaction trigger unique using vacuum view virtual when with without"),
    // SQLite is weakly typed, ref: http://sqlite.org/datatype3.html. This is just a list of some common types.
    builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text clob bigint int int2 int8 integer float double char varchar date datetime year unsigned signed numeric real"),
    // ref: http://sqlite.org/syntax/literal-value.html
    atoms: set("null current_date current_time current_timestamp"),
    // ref: http://sqlite.org/lang_expr.html#binaryops
    operatorChars: /^[*+\-%<>!=&|/~]/,
    // SQLite is weakly typed, ref: http://sqlite.org/datatype3.html. This is just a list of some common types.
    dateSQL: set("date time timestamp datetime"),
    support: set("decimallessFloat zerolessFloat"),
    identifierQuote: "\"",  //ref: http://sqlite.org/lang_keywords.html
    hooks: {
      // bind-parameters ref:http://sqlite.org/lang_expr.html#varparam
      "@":   hookVar,
      ":":   hookVar,
      "?":   hookVar,
      "$":   hookVar,
      // The preferred way to escape Identifiers is using double quotes, ref: http://sqlite.org/lang_keywords.html
      "\"":   hookIdentifierDoublequote,
      // there is also support for backtics, ref: http://sqlite.org/lang_keywords.html
      "`":   hookIdentifier
    }
  });

  // the query language used by Apache Cassandra is called CQL, but this mime type
  // is called Cassandra to avoid confusion with Contextual Query Language
  CodeMirror.defineMIME("text/x-cassandra", {
    name: "sql",
    client: { },
    keywords: set("add all allow alter and any apply as asc authorize batch begin by clustering columnfamily compact consistency count create custom delete desc distinct drop each_quorum exists filtering from grant if in index insert into key keyspace keyspaces level limit local_one local_quorum modify nan norecursive nosuperuser not of on one order password permission permissions primary quorum rename revoke schema select set storage superuser table three to token truncate ttl two type unlogged update use user users using values where with writetime"),
    builtin: set("ascii bigint blob boolean counter decimal double float frozen inet int list map static text timestamp timeuuid tuple uuid varchar varint"),
    atoms: set("false true infinity NaN"),
    operatorChars: /^[<>=]/,
    dateSQL: { },
    support: set("commentSlashSlash decimallessFloat"),
    hooks: { }
  });

  // this is based on Peter Raganitsch's 'plsql' mode
  CodeMirror.defineMIME("text/x-plsql", {
    name:       "sql",
    client:     set("appinfo arraysize autocommit autoprint autorecovery autotrace blockterminator break btitle cmdsep colsep compatibility compute concat copycommit copytypecheck define describe echo editfile embedded escape exec execute feedback flagger flush heading headsep instance linesize lno loboffset logsource long longchunksize markup native newpage numformat numwidth pagesize pause pno recsep recsepchar release repfooter repheader serveroutput shiftinout show showmode size spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix tab term termout time timing trimout trimspool ttitle underline verify version wrap"),
    keywords:   set("abort accept access add all alter and any array arraylen as asc assert assign at attributes audit authorization avg base_table begin between binary_integer body boolean by case cast char char_base check close cluster clusters colauth column comment commit compress connect connected constant constraint crash create current currval cursor data_base database date dba deallocate debugoff debugon decimal declare default definition delay delete desc digits dispose distinct do drop else elseif elsif enable end entry escape exception exception_init exchange exclusive exists exit external fast fetch file for force form from function generic goto grant group having identified if immediate in increment index indexes indicator initial initrans insert interface intersect into is key level library like limited local lock log logging long loop master maxextents maxtrans member minextents minus mislabel mode modify multiset new next no noaudit nocompress nologging noparallel not nowait number_base object of off offline on online only open option or order out package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior private privileges procedure public raise range raw read rebuild record ref references refresh release rename replace resource restrict return returning returns reverse revoke rollback row rowid rowlabel rownum rows run savepoint schema segment select separate session set share snapshot some space split sql start statement storage subtype successful synonym tabauth table tables tablespace task terminate then to trigger truncate type union unique unlimited unrecoverable unusable update use using validate value values variable view views when whenever where while with work"),
    builtin:    set("abs acos add_months ascii asin atan atan2 average bfile bfilename bigserial bit blob ceil character chartorowid chr clob concat convert cos cosh count dec decode deref dual dump dup_val_on_index empty error exp false float floor found glb greatest hextoraw initcap instr instrb int integer isopen last_day least length lengthb ln lower lpad ltrim lub make_ref max min mlslabel mod months_between natural naturaln nchar nclob new_time next_day nextval nls_charset_decl_len nls_charset_id nls_charset_name nls_initcap nls_lower nls_sort nls_upper nlssort no_data_found notfound null number numeric nvarchar2 nvl others power rawtohex real reftohex round rowcount rowidtochar rowtype rpad rtrim serial sign signtype sin sinh smallint soundex sqlcode sqlerrm sqrt stddev string substr substrb sum sysdate tan tanh to_char text to_date to_label to_multi_byte to_number to_single_byte translate true trunc uid unlogged upper user userenv varchar varchar2 variance varying vsize xml"),
    operatorChars: /^[*+\-%<>!=~]/,
    dateSQL:    set("date time timestamp"),
    support:    set("doubleQuote nCharCast zerolessFloat binaryNumber hexNumber")
  });

  // Created to support specific hive keywords
  CodeMirror.defineMIME("text/x-hive", {
    name: "sql",
    keywords: set("select alter $elem$ $key$ $value$ add after all analyze and archive as asc before between binary both bucket buckets by cascade case cast change cluster clustered clusterstatus collection column columns comment compute concatenate continue create cross cursor data database databases dbproperties deferred delete delimited desc describe directory disable distinct distribute drop else enable end escaped exclusive exists explain export extended external false fetch fields fileformat first format formatted from full function functions grant group having hold_ddltime idxproperties if import in index indexes inpath inputdriver inputformat insert intersect into is items join keys lateral left like limit lines load local location lock locks mapjoin materialized minus msck no_drop nocompress not of offline on option or order out outer outputdriver outputformat overwrite partition partitioned partitions percent plus preserve procedure purge range rcfile read readonly reads rebuild recordreader recordwriter recover reduce regexp rename repair replace restrict revoke right rlike row schema schemas semi sequencefile serde serdeproperties set shared show show_database sort sorted ssl statistics stored streamtable table tables tablesample tblproperties temporary terminated textfile then tmp to touch transform trigger true unarchive undo union uniquejoin unlock update use using utc utc_tmestamp view when where while with"),
    builtin: set("bool boolean long timestamp tinyint smallint bigint int float double date datetime unsigned string array struct map uniontype"),
    atoms: set("false true null unknown"),
    operatorChars: /^[*+\-%<>!=]/,
    dateSQL: set("date timestamp"),
    support: set("ODBCdotTable doubleQuote binaryNumber hexNumber")
  });

  CodeMirror.defineMIME("text/x-pgsql", {
    name: "sql",
    client: set("source"),
    // https://www.postgresql.org/docs/10/static/sql-keywords-appendix.html
    keywords: set(sqlKeywords + "a abort abs absent absolute access according action ada add admin after aggregate all allocate also always analyse analyze any are array array_agg array_max_cardinality asensitive assertion assignment asymmetric at atomic attribute attributes authorization avg backward base64 before begin begin_frame begin_partition bernoulli binary bit_length blob blocked bom both breadth c cache call called cardinality cascade cascaded case cast catalog catalog_name ceil ceiling chain characteristics characters character_length character_set_catalog character_set_name character_set_schema char_length check checkpoint class class_origin clob close cluster coalesce cobol collate collation collation_catalog collation_name collation_schema collect column columns column_name command_function command_function_code comment comments commit committed concurrently condition condition_number configuration conflict connect connection connection_name constraint constraints constraint_catalog constraint_name constraint_schema constructor contains content continue control conversion convert copy corr corresponding cost covar_pop covar_samp cross csv cube cume_dist current current_catalog current_date current_default_transform_group current_path current_role current_row current_schema current_time current_timestamp current_transform_group_for_type current_user cursor cursor_name cycle data database datalink datetime_interval_code datetime_interval_precision day db deallocate dec declare default defaults deferrable deferred defined definer degree delimiter delimiters dense_rank depth deref derived describe descriptor deterministic diagnostics dictionary disable discard disconnect dispatch dlnewcopy dlpreviouscopy dlurlcomplete dlurlcompleteonly dlurlcompletewrite dlurlpath dlurlpathonly dlurlpathwrite dlurlscheme dlurlserver dlvalue do document domain dynamic dynamic_function dynamic_function_code each element else empty enable encoding encrypted end end-exec end_frame end_partition enforced enum equals escape event every except exception exclude excluding exclusive exec execute exists exp explain expression extension external extract false family fetch file filter final first first_value flag float floor following for force foreign fortran forward found frame_row free freeze fs full function functions fusion g general generated get global go goto grant granted greatest grouping groups handler header hex hierarchy hold hour id identity if ignore ilike immediate immediately immutable implementation implicit import including increment indent index indexes indicator inherit inherits initially inline inner inout input insensitive instance instantiable instead integrity intersect intersection invoker isnull isolation k key key_member key_type label lag language large last last_value lateral lc_collate lc_ctype lead leading leakproof least left length level library like_regex link listen ln load local localtime localtimestamp location locator lock locked logged lower m map mapping match matched materialized max maxvalue max_cardinality member merge message_length message_octet_length message_text method min minute minvalue mod mode modifies module month more move multiset mumps name names namespace national natural nchar nclob nesting new next nfc nfd nfkc nfkd nil no none normalize normalized nothing notify notnull nowait nth_value ntile null nullable nullif nulls number object occurrences_regex octets octet_length of off offset oids old only open operator option options ordering ordinality others out outer output over overlaps overlay overriding owned owner p pad parallel parameter parameter_mode parameter_name parameter_ordinal_position parameter_specific_catalog parameter_specific_name parameter_specific_schema parser partial partition pascal passing passthrough password percent percentile_cont percentile_disc percent_rank period permission placing plans pli policy portion position position_regex power precedes preceding prepare prepared preserve primary prior privileges procedural procedure program public quote range rank read reads reassign recheck recovery recursive ref references referencing refresh regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy regr_syy reindex relative release rename repeatable replace replica requiring reset respect restart restore restrict restricted result return returned_cardinality returned_length returned_octet_length returned_sqlstate returning returns revoke right role rollback rollup routine routine_catalog routine_name routine_schema row rows row_count row_number rule savepoint scale schema schema_name scope scope_catalog scope_name scope_schema scroll search second section security selective self sensitive sequence sequences serializable server server_name session session_user setof sets share show similar simple size skip snapshot some source space specific specifictype specific_name sql sqlcode sqlerror sqlexception sqlstate sqlwarning sqrt stable standalone start state statement static statistics stddev_pop stddev_samp stdin stdout storage strict strip structure style subclass_origin submultiset substring substring_regex succeeds sum symmetric sysid system system_time system_user t tables tablesample tablespace table_name temp template temporary then ties timezone_hour timezone_minute to token top_level_count trailing transaction transactions_committed transactions_rolled_back transaction_active transform transforms translate translate_regex translation treat trigger trigger_catalog trigger_name trigger_schema trim trim_array true truncate trusted type types uescape unbounded uncommitted under unencrypted unique unknown unlink unlisten unlogged unnamed unnest until untyped upper uri usage user user_defined_type_catalog user_defined_type_code user_defined_type_name user_defined_type_schema using vacuum valid validate validator value value_of varbinary variadic var_pop var_samp verbose version versioning view views volatile when whenever whitespace width_bucket window within work wrapper write xmlagg xmlattributes xmlbinary xmlcast xmlcomment xmlconcat xmldeclaration xmldocument xmlelement xmlexists xmlforest xmliterate xmlnamespaces xmlparse xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltext xmlvalidate year yes loop repeat attach path depends detach zone"),
    // https://www.postgresql.org/docs/10/static/datatype.html
    builtin: set("bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float8 inet integer int int4 interval json jsonb line lseg macaddr macaddr8 money numeric decimal path pg_lsn point polygon real float4 smallint int2 smallserial serial2 serial serial4 text time without zone with timetz timestamp timestamptz tsquery tsvector txid_snapshot uuid xml"),
    atoms: set("false true null unknown"),
    operatorChars: /^[*+\-%<>!=&|^\/#@?~]/,
    dateSQL: set("date time timestamp"),
    support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast")
  });

  // Google's SQL-like query language, GQL
  CodeMirror.defineMIME("text/x-gql", {
    name: "sql",
    keywords: set("ancestor and asc by contains desc descendant distinct from group has in is limit offset on order select superset where"),
    atoms: set("false true"),
    builtin: set("blob datetime first key __key__ string integer double boolean null"),
    operatorChars: /^[*+\-%<>!=]/
  });

  // Greenplum
  CodeMirror.defineMIME("text/x-gpsql", {
    name: "sql",
    client: set("source"),
    //https://github.com/greenplum-db/gpdb/blob/master/src/include/parser/kwlist.h
    keywords: set("abort absolute access action active add admin after aggregate all also alter always analyse analyze and any array as asc assertion assignment asymmetric at authorization backward before begin between bigint binary bit boolean both by cache called cascade cascaded case cast chain char character characteristics check checkpoint class close cluster coalesce codegen collate column comment commit committed concurrency concurrently configuration connection constraint constraints contains content continue conversion copy cost cpu_rate_limit create createdb createexttable createrole createuser cross csv cube current current_catalog current_date current_role current_schema current_time current_timestamp current_user cursor cycle data database day deallocate dec decimal declare decode default defaults deferrable deferred definer delete delimiter delimiters deny desc dictionary disable discard distinct distributed do document domain double drop dxl each else enable encoding encrypted end enum errors escape every except exchange exclude excluding exclusive execute exists explain extension external extract false family fetch fields filespace fill filter first float following for force foreign format forward freeze from full function global grant granted greatest group group_id grouping handler hash having header hold host hour identity if ignore ilike immediate immutable implicit in including inclusive increment index indexes inherit inherits initially inline inner inout input insensitive insert instead int integer intersect interval into invoker is isnull isolation join key language large last leading least left level like limit list listen load local localtime localtimestamp location lock log login mapping master match maxvalue median merge minute minvalue missing mode modifies modify month move name names national natural nchar new newline next no nocreatedb nocreateexttable nocreaterole nocreateuser noinherit nologin none noovercommit nosuperuser not nothing notify notnull nowait null nullif nulls numeric object of off offset oids old on only operator option options or order ordered others out outer over overcommit overlaps overlay owned owner parser partial partition partitions passing password percent percentile_cont percentile_disc placing plans position preceding precision prepare prepared preserve primary prior privileges procedural procedure protocol queue quote randomly range read readable reads real reassign recheck recursive ref references reindex reject relative release rename repeatable replace replica reset resource restart restrict returning returns revoke right role rollback rollup rootpartition row rows rule savepoint scatter schema scroll search second security segment select sequence serializable session session_user set setof sets share show similar simple smallint some split sql stable standalone start statement statistics stdin stdout storage strict strip subpartition subpartitions substring superuser symmetric sysid system table tablespace temp template temporary text then threshold ties time timestamp to trailing transaction treat trigger trim true truncate trusted type unbounded uncommitted unencrypted union unique unknown unlisten until update user using vacuum valid validation validator value values varchar variadic varying verbose version view volatile web when where whitespace window with within without work writable write xml xmlattributes xmlconcat xmlelement xmlexists xmlforest xmlparse xmlpi xmlroot xmlserialize year yes zone"),
    builtin: set("bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float float8 inet integer int int4 interval json jsonb line lseg macaddr macaddr8 money numeric decimal path pg_lsn point polygon real float4 smallint int2 smallserial serial2 serial serial4 text time without zone with timetz timestamp timestamptz tsquery tsvector txid_snapshot uuid xml"),
    atoms: set("false true null unknown"),
    operatorChars: /^[*+\-%<>!=&|^\/#@?~]/,
    dateSQL: set("date time timestamp"),
    support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast")
  });

  // Spark SQL
  CodeMirror.defineMIME("text/x-sparksql", {
    name: "sql",
    keywords: set("add after all alter analyze and anti archive array as asc at between bucket buckets by cache cascade case cast change clear cluster clustered codegen collection column columns comment commit compact compactions compute concatenate cost create cross cube current current_date current_timestamp database databases datata dbproperties defined delete delimited deny desc describe dfs directories distinct distribute drop else end escaped except exchange exists explain export extended external false fields fileformat first following for format formatted from full function functions global grant group grouping having if ignore import in index indexes inner inpath inputformat insert intersect interval into is items join keys last lateral lazy left like limit lines list load local location lock locks logical macro map minus msck natural no not null nulls of on optimize option options or order out outer outputformat over overwrite partition partitioned partitions percent preceding principals purge range recordreader recordwriter recover reduce refresh regexp rename repair replace reset restrict revoke right rlike role roles rollback rollup row rows schema schemas select semi separated serde serdeproperties set sets show skewed sort sorted start statistics stored stratify struct table tables tablesample tblproperties temp temporary terminated then to touch transaction transactions transform true truncate unarchive unbounded uncache union unlock unset use using values view when where window with"),
    builtin: set("tinyint smallint int bigint boolean float double string binary timestamp decimal array map struct uniontype delimited serde sequencefile textfile rcfile inputformat outputformat"),
    atoms: set("false true null"),
    operatorChars: /^[*+\-%<>!=~&|^]/,
    dateSQL: set("date time timestamp"),
    support: set("ODBCdotTable doubleQuote zerolessFloat")
  });

  // Esper
  CodeMirror.defineMIME("text/x-esper", {
    name: "sql",
    client: set("source"),
    // http://www.espertech.com/esper/release-5.5.0/esper-reference/html/appendix_keywords.html
    keywords: set("alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit after all and as at asc avedev avg between by case cast coalesce count create current_timestamp day days delete define desc distinct else end escape events every exists false first from full group having hour hours in inner insert instanceof into irstream is istream join last lastweekday left limit like max match_recognize matches median measures metadatasql min minute minutes msec millisecond milliseconds not null offset on or order outer output partition pattern prev prior regexp retain-union retain-intersection right rstream sec second seconds select set some snapshot sql stddev sum then true unidirectional until update variable weekday when where window"),
    builtin: {},
    atoms: set("false true null"),
    operatorChars: /^[*+\-%<>!=&|^\/#@?~]/,
    dateSQL: set("time"),
    support: set("decimallessFloat zerolessFloat binaryNumber hexNumber")
  });
}());

});

/*
  How Properties of Mime Types are used by SQL Mode
  =================================================

  keywords:
    A list of keywords you want to be highlighted.
  builtin:
    A list of builtin types you want to be highlighted (if you want types to be of class "builtin" instead of "keyword").
  operatorChars:
    All characters that must be handled as operators.
  client:
    Commands parsed and executed by the client (not the server).
  support:
    A list of supported syntaxes which are not common, but are supported by more than 1 DBMS.
    * ODBCdotTable: .tableName
    * zerolessFloat: .1
    * doubleQuote
    * nCharCast: N'string'
    * charsetCast: _utf8'string'
    * commentHash: use # char for comments
    * commentSlashSlash: use // for comments
    * commentSpaceRequired: require a space after -- for comments
  atoms:
    Keywords that must be highlighted as atoms,. Some DBMS's support more atoms than others:
    UNKNOWN, INFINITY, UNDERFLOW, NaN...
  dateSQL:
    Used for date/time SQL standard syntax, because not all DBMS's support same temporal types.
*/


/***/ }),

/***/ "/CZE":
/*!*************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/index.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




var d3 = __webpack_require__(/*! d3 */ "bljh");
var isNumeric = __webpack_require__(/*! fast-isnumeric */ "GbLo");

var numConstants = __webpack_require__(/*! ../constants/numerical */ "6AZA");
var FP_SAFE = numConstants.FP_SAFE;
var BADNUM = numConstants.BADNUM;

var lib = module.exports = {};

lib.nestedProperty = __webpack_require__(/*! ./nested_property */ "dNZO");
lib.keyedContainer = __webpack_require__(/*! ./keyed_container */ "Xe/Q");
lib.relativeAttr = __webpack_require__(/*! ./relative_attr */ "Lj1h");
lib.isPlainObject = __webpack_require__(/*! ./is_plain_object */ "E4V0");
lib.toLogRange = __webpack_require__(/*! ./to_log_range */ "9rBw");
lib.relinkPrivateKeys = __webpack_require__(/*! ./relink_private */ "Q1hF");

var arrayModule = __webpack_require__(/*! ./array */ "avjU");
lib.isTypedArray = arrayModule.isTypedArray;
lib.isArrayOrTypedArray = arrayModule.isArrayOrTypedArray;
lib.isArray1D = arrayModule.isArray1D;
lib.ensureArray = arrayModule.ensureArray;
lib.concat = arrayModule.concat;
lib.maxRowLength = arrayModule.maxRowLength;
lib.minRowLength = arrayModule.minRowLength;

var modModule = __webpack_require__(/*! ./mod */ "09xr");
lib.mod = modModule.mod;
lib.modHalf = modModule.modHalf;

var coerceModule = __webpack_require__(/*! ./coerce */ "ZnKQ");
lib.valObjectMeta = coerceModule.valObjectMeta;
lib.coerce = coerceModule.coerce;
lib.coerce2 = coerceModule.coerce2;
lib.coerceFont = coerceModule.coerceFont;
lib.coerceHoverinfo = coerceModule.coerceHoverinfo;
lib.coerceSelectionMarkerOpacity = coerceModule.coerceSelectionMarkerOpacity;
lib.validate = coerceModule.validate;

var datesModule = __webpack_require__(/*! ./dates */ "Zhzs");
lib.dateTime2ms = datesModule.dateTime2ms;
lib.isDateTime = datesModule.isDateTime;
lib.ms2DateTime = datesModule.ms2DateTime;
lib.ms2DateTimeLocal = datesModule.ms2DateTimeLocal;
lib.cleanDate = datesModule.cleanDate;
lib.isJSDate = datesModule.isJSDate;
lib.formatDate = datesModule.formatDate;
lib.incrementMonth = datesModule.incrementMonth;
lib.dateTick0 = datesModule.dateTick0;
lib.dfltRange = datesModule.dfltRange;
lib.findExactDates = datesModule.findExactDates;
lib.MIN_MS = datesModule.MIN_MS;
lib.MAX_MS = datesModule.MAX_MS;

var searchModule = __webpack_require__(/*! ./search */ "3HVJ");
lib.findBin = searchModule.findBin;
lib.sorterAsc = searchModule.sorterAsc;
lib.sorterDes = searchModule.sorterDes;
lib.distinctVals = searchModule.distinctVals;
lib.roundUp = searchModule.roundUp;
lib.sort = searchModule.sort;
lib.findIndexOfMin = searchModule.findIndexOfMin;

var statsModule = __webpack_require__(/*! ./stats */ "oBF0");
lib.aggNums = statsModule.aggNums;
lib.len = statsModule.len;
lib.mean = statsModule.mean;
lib.midRange = statsModule.midRange;
lib.variance = statsModule.variance;
lib.stdev = statsModule.stdev;
lib.interp = statsModule.interp;

var matrixModule = __webpack_require__(/*! ./matrix */ "7CC7");
lib.init2dArray = matrixModule.init2dArray;
lib.transposeRagged = matrixModule.transposeRagged;
lib.dot = matrixModule.dot;
lib.translationMatrix = matrixModule.translationMatrix;
lib.rotationMatrix = matrixModule.rotationMatrix;
lib.rotationXYMatrix = matrixModule.rotationXYMatrix;
lib.apply2DTransform = matrixModule.apply2DTransform;
lib.apply2DTransform2 = matrixModule.apply2DTransform2;

var anglesModule = __webpack_require__(/*! ./angles */ "bkDJ");
lib.deg2rad = anglesModule.deg2rad;
lib.rad2deg = anglesModule.rad2deg;
lib.angleDelta = anglesModule.angleDelta;
lib.angleDist = anglesModule.angleDist;
lib.isFullCircle = anglesModule.isFullCircle;
lib.isAngleInsideSector = anglesModule.isAngleInsideSector;
lib.isPtInsideSector = anglesModule.isPtInsideSector;
lib.pathArc = anglesModule.pathArc;
lib.pathSector = anglesModule.pathSector;
lib.pathAnnulus = anglesModule.pathAnnulus;

var anchorUtils = __webpack_require__(/*! ./anchor_utils */ "bFr3");
lib.isLeftAnchor = anchorUtils.isLeftAnchor;
lib.isCenterAnchor = anchorUtils.isCenterAnchor;
lib.isRightAnchor = anchorUtils.isRightAnchor;
lib.isTopAnchor = anchorUtils.isTopAnchor;
lib.isMiddleAnchor = anchorUtils.isMiddleAnchor;
lib.isBottomAnchor = anchorUtils.isBottomAnchor;

var geom2dModule = __webpack_require__(/*! ./geometry2d */ "GeF/");
lib.segmentsIntersect = geom2dModule.segmentsIntersect;
lib.segmentDistance = geom2dModule.segmentDistance;
lib.getTextLocation = geom2dModule.getTextLocation;
lib.clearLocationCache = geom2dModule.clearLocationCache;
lib.getVisibleSegment = geom2dModule.getVisibleSegment;
lib.findPointOnPath = geom2dModule.findPointOnPath;

var extendModule = __webpack_require__(/*! ./extend */ "kJIm");
lib.extendFlat = extendModule.extendFlat;
lib.extendDeep = extendModule.extendDeep;
lib.extendDeepAll = extendModule.extendDeepAll;
lib.extendDeepNoArrays = extendModule.extendDeepNoArrays;

var loggersModule = __webpack_require__(/*! ./loggers */ "rhNM");
lib.log = loggersModule.log;
lib.warn = loggersModule.warn;
lib.error = loggersModule.error;

var regexModule = __webpack_require__(/*! ./regex */ "BVrX");
lib.counterRegex = regexModule.counter;

var throttleModule = __webpack_require__(/*! ./throttle */ "ffJW");
lib.throttle = throttleModule.throttle;
lib.throttleDone = throttleModule.done;
lib.clearThrottle = throttleModule.clear;

lib.getGraphDiv = __webpack_require__(/*! ./get_graph_div */ "z6H5");

lib.clearResponsive = __webpack_require__(/*! ./clear_responsive */ "oi9M");

lib.makeTraceGroups = __webpack_require__(/*! ./make_trace_groups */ "+lml");

lib._ = __webpack_require__(/*! ./localize */ "pMAR");

lib.notifier = __webpack_require__(/*! ./notifier */ "AII8");

lib.filterUnique = __webpack_require__(/*! ./filter_unique */ "VWeM");
lib.filterVisible = __webpack_require__(/*! ./filter_visible */ "b8PE");
lib.pushUnique = __webpack_require__(/*! ./push_unique */ "Whu6");

lib.cleanNumber = __webpack_require__(/*! ./clean_number */ "8trw");

lib.ensureNumber = function num(v) {
    if(!isNumeric(v)) return BADNUM;
    v = Number(v);
    if(v < -FP_SAFE || v > FP_SAFE) return BADNUM;
    return isNumeric(v) ? Number(v) : BADNUM;
};

/**
 * Is v a valid array index? Accepts numeric strings as well as numbers.
 *
 * @param {any} v: the value to test
 * @param {Optional[integer]} len: the array length we are indexing
 *
 * @return {bool}: v is a valid array index
 */
lib.isIndex = function(v, len) {
    if(len !== undefined && v >= len) return false;
    return isNumeric(v) && (v >= 0) && (v % 1 === 0);
};

lib.noop = __webpack_require__(/*! ./noop */ "t3iM");
lib.identity = __webpack_require__(/*! ./identity */ "MGx7");

/**
 * create an array of length 'cnt' filled with 'v' at all indices
 *
 * @param {any} v
 * @param {number} cnt
 * @return {array}
 */
lib.repeat = function(v, cnt) {
    var out = new Array(cnt);
    for(var i = 0; i < cnt; i++) {
        out[i] = v;
    }
    return out;
};

/**
 * swap x and y of the same attribute in container cont
 * specify attr with a ? in place of x/y
 * you can also swap other things than x/y by providing part1 and part2
 */
lib.swapAttrs = function(cont, attrList, part1, part2) {
    if(!part1) part1 = 'x';
    if(!part2) part2 = 'y';
    for(var i = 0; i < attrList.length; i++) {
        var attr = attrList[i];
        var xp = lib.nestedProperty(cont, attr.replace('?', part1));
        var yp = lib.nestedProperty(cont, attr.replace('?', part2));
        var temp = xp.get();
        xp.set(yp.get());
        yp.set(temp);
    }
};

/**
 * SVG painter's algo worked around with reinsertion
 */
lib.raiseToTop = function raiseToTop(elem) {
    elem.parentNode.appendChild(elem);
};

/**
 * cancel a possibly pending transition; returned selection may be used by caller
 */
lib.cancelTransition = function(selection) {
    return selection.transition().duration(0);
};

// constrain - restrict a number v to be between v0 and v1
lib.constrain = function(v, v0, v1) {
    if(v0 > v1) return Math.max(v1, Math.min(v0, v));
    return Math.max(v0, Math.min(v1, v));
};

/**
 * do two bounding boxes from getBoundingClientRect,
 * ie {left,right,top,bottom,width,height}, overlap?
 * takes optional padding pixels
 */
lib.bBoxIntersect = function(a, b, pad) {
    pad = pad || 0;
    return (a.left <= b.right + pad &&
            b.left <= a.right + pad &&
            a.top <= b.bottom + pad &&
            b.top <= a.bottom + pad);
};

/*
 * simpleMap: alternative to Array.map that only
 * passes on the element and up to 2 extra args you
 * provide (but not the array index or the whole array)
 *
 * array: the array to map it to
 * func: the function to apply
 * x1, x2: optional extra args
 */
lib.simpleMap = function(array, func, x1, x2) {
    var len = array.length;
    var out = new Array(len);
    for(var i = 0; i < len; i++) out[i] = func(array[i], x1, x2);
    return out;
};

/**
 * Random string generator
 *
 * @param {object} existing
 *     pass in strings to avoid as keys with truthy values
 * @param {int} bits
 *     bits of information in the output string, default 24
 * @param {int} base
 *     base of string representation, default 16. Should be a power of 2.
 */
lib.randstr = function randstr(existing, bits, base, _recursion) {
    if(!base) base = 16;
    if(bits === undefined) bits = 24;
    if(bits <= 0) return '0';

    var digits = Math.log(Math.pow(2, bits)) / Math.log(base);
    var res = '';
    var i, b, x;

    for(i = 2; digits === Infinity; i *= 2) {
        digits = Math.log(Math.pow(2, bits / i)) / Math.log(base) * i;
    }

    var rem = digits - Math.floor(digits);

    for(i = 0; i < Math.floor(digits); i++) {
        x = Math.floor(Math.random() * base).toString(base);
        res = x + res;
    }

    if(rem) {
        b = Math.pow(base, rem);
        x = Math.floor(Math.random() * b).toString(base);
        res = x + res;
    }

    var parsed = parseInt(res, base);
    if((existing && existing[res]) ||
         (parsed !== Infinity && parsed >= Math.pow(2, bits))) {
        if(_recursion > 10) {
            lib.warn('randstr failed uniqueness');
            return res;
        }
        return randstr(existing, bits, base, (_recursion || 0) + 1);
    }
    else return res;
};

lib.OptionControl = function(opt, optname) {
    /*
     * An environment to contain all option setters and
     * getters that collectively modify opts.
     *
     * You can call up opts from any function in new object
     * as this.optname || this.opt
     *
     * See FitOpts for example of usage
     */
    if(!opt) opt = {};
    if(!optname) optname = 'opt';

    var self = {};
    self.optionList = [];

    self._newoption = function(optObj) {
        optObj[optname] = opt;
        self[optObj.name] = optObj;
        self.optionList.push(optObj);
    };

    self['_' + optname] = opt;
    return self;
};

/**
 * lib.smooth: smooth arrayIn by convolving with
 * a hann window with given full width at half max
 * bounce the ends in, so the output has the same length as the input
 */
lib.smooth = function(arrayIn, FWHM) {
    FWHM = Math.round(FWHM) || 0; // only makes sense for integers
    if(FWHM < 2) return arrayIn;

    var alen = arrayIn.length;
    var alen2 = 2 * alen;
    var wlen = 2 * FWHM - 1;
    var w = new Array(wlen);
    var arrayOut = new Array(alen);
    var i;
    var j;
    var k;
    var v;

    // first make the window array
    for(i = 0; i < wlen; i++) {
        w[i] = (1 - Math.cos(Math.PI * (i + 1) / FWHM)) / (2 * FWHM);
    }

    // now do the convolution
    for(i = 0; i < alen; i++) {
        v = 0;
        for(j = 0; j < wlen; j++) {
            k = i + j + 1 - FWHM;

            // multibounce
            if(k < -alen) k -= alen2 * Math.round(k / alen2);
            else if(k >= alen2) k -= alen2 * Math.floor(k / alen2);

            // single bounce
            if(k < 0) k = - 1 - k;
            else if(k >= alen) k = alen2 - 1 - k;

            v += arrayIn[k] * w[j];
        }
        arrayOut[i] = v;
    }

    return arrayOut;
};

/**
 * syncOrAsync: run a sequence of functions synchronously
 * as long as its returns are not promises (ie have no .then)
 * includes one argument arg to send to all functions...
 * this is mainly just to prevent us having to make wrapper functions
 * when the only purpose of the wrapper is to reference gd
 * and a final step to be executed at the end
 * TODO: if there's an error and everything is sync,
 * this doesn't happen yet because we want to make sure
 * that it gets reported
 */
lib.syncOrAsync = function(sequence, arg, finalStep) {
    var ret, fni;

    function continueAsync() {
        return lib.syncOrAsync(sequence, arg, finalStep);
    }

    while(sequence.length) {
        fni = sequence.splice(0, 1)[0];
        ret = fni(arg);

        if(ret && ret.then) {
            return ret.then(continueAsync)
                .then(undefined, lib.promiseError);
        }
    }

    return finalStep && finalStep(arg);
};


/**
 * Helper to strip trailing slash, from
 * http://stackoverflow.com/questions/6680825/return-string-without-trailing-slash
 */
lib.stripTrailingSlash = function(str) {
    if(str.substr(-1) === '/') return str.substr(0, str.length - 1);
    return str;
};

lib.noneOrAll = function(containerIn, containerOut, attrList) {
    /**
     * some attributes come together, so if you have one of them
     * in the input, you should copy the default values of the others
     * to the input as well.
     */
    if(!containerIn) return;

    var hasAny = false;
    var hasAll = true;
    var i;
    var val;

    for(i = 0; i < attrList.length; i++) {
        val = containerIn[attrList[i]];
        if(val !== undefined && val !== null) hasAny = true;
        else hasAll = false;
    }

    if(hasAny && !hasAll) {
        for(i = 0; i < attrList.length; i++) {
            containerIn[attrList[i]] = containerOut[attrList[i]];
        }
    }
};

/** merges calcdata field (given by cdAttr) with traceAttr values
 *
 * N.B. Loop over minimum of cd.length and traceAttr.length
 * i.e. it does not try to fill in beyond traceAttr.length-1
 *
 * @param {array} traceAttr : trace attribute
 * @param {object} cd : calcdata trace
 * @param {string} cdAttr : calcdata key
 */
lib.mergeArray = function(traceAttr, cd, cdAttr) {
    if(lib.isArrayOrTypedArray(traceAttr)) {
        var imax = Math.min(traceAttr.length, cd.length);
        for(var i = 0; i < imax; i++) cd[i][cdAttr] = traceAttr[i];
    }
};

/** fills calcdata field (given by cdAttr) with traceAttr values
 *  or function of traceAttr values (e.g. some fallback)
 *
 * N.B. Loops over all cd items.
 *
 * @param {array} traceAttr : trace attribute
 * @param {object} cd : calcdata trace
 * @param {string} cdAttr : calcdata key
 * @param {function} [fn] : optional function to apply to each array item
 */
lib.fillArray = function(traceAttr, cd, cdAttr, fn) {
    fn = fn || lib.identity;

    if(lib.isArrayOrTypedArray(traceAttr)) {
        for(var i = 0; i < cd.length; i++) {
            cd[i][cdAttr] = fn(traceAttr[i]);
        }
    }
};

/** Handler for trace-wide vs per-point options
 *
 * @param {object} trace : (full) trace object
 * @param {number} ptNumber : index of the point in question
 * @param {string} astr : attribute string
 * @param {function} [fn] : optional function to apply to each array item
 *
 * @return {any}
 */
lib.castOption = function(trace, ptNumber, astr, fn) {
    fn = fn || lib.identity;

    var val = lib.nestedProperty(trace, astr).get();

    if(lib.isArrayOrTypedArray(val)) {
        if(Array.isArray(ptNumber) && lib.isArrayOrTypedArray(val[ptNumber[0]])) {
            return fn(val[ptNumber[0]][ptNumber[1]]);
        } else {
            return fn(val[ptNumber]);
        }
    } else {
        return val;
    }
};

/** Extract option from calcdata item, correctly falling back to
 *  trace value if not found.
 *
 *  @param {object} calcPt : calcdata[i][j] item
 *  @param {object} trace : (full) trace object
 *  @param {string} calcKey : calcdata key
 *  @param {string} traceKey : aka trace attribute string
 *  @return {any}
 */
lib.extractOption = function(calcPt, trace, calcKey, traceKey) {
    if(calcKey in calcPt) return calcPt[calcKey];

    // fallback to trace value,
    //   must check if value isn't itself an array
    //   which means the trace attribute has a corresponding
    //   calcdata key, but its value is falsy
    var traceVal = lib.nestedProperty(trace, traceKey).get();
    if(!Array.isArray(traceVal)) return traceVal;
};

function makePtIndex2PtNumber(indexToPoints) {
    var ptIndex2ptNumber = {};
    for(var k in indexToPoints) {
        var pts = indexToPoints[k];
        for(var j = 0; j < pts.length; j++) {
            ptIndex2ptNumber[pts[j]] = +k;
        }
    }
    return ptIndex2ptNumber;
}

/** Tag selected calcdata items
 *
 * N.B. note that point 'index' corresponds to input data array index
 *  whereas 'number' is its post-transform version.
 *
 * @param {array} calcTrace
 * @param {object} trace
 *  - selectedpoints {array}
 *  - _indexToPoints {object}
 * @param {ptNumber2cdIndex} ptNumber2cdIndex (optional)
 *  optional map object for trace types that do not have 1-to-1 point number to
 *  calcdata item index correspondence (e.g. histogram)
 */
lib.tagSelected = function(calcTrace, trace, ptNumber2cdIndex) {
    var selectedpoints = trace.selectedpoints;
    var indexToPoints = trace._indexToPoints;
    var ptIndex2ptNumber;

    // make pt index-to-number map object, which takes care of transformed traces
    if(indexToPoints) {
        ptIndex2ptNumber = makePtIndex2PtNumber(indexToPoints);
    }

    function isCdIndexValid(v) {
        return v !== undefined && v < calcTrace.length;
    }

    for(var i = 0; i < selectedpoints.length; i++) {
        var ptIndex = selectedpoints[i];

        if(lib.isIndex(ptIndex)) {
            var ptNumber = ptIndex2ptNumber ? ptIndex2ptNumber[ptIndex] : ptIndex;
            var cdIndex = ptNumber2cdIndex ? ptNumber2cdIndex[ptNumber] : ptNumber;

            if(isCdIndexValid(cdIndex)) {
                calcTrace[cdIndex].selected = 1;
            }
        }
    }
};

lib.selIndices2selPoints = function(trace) {
    var selectedpoints = trace.selectedpoints;
    var indexToPoints = trace._indexToPoints;

    if(indexToPoints) {
        var ptIndex2ptNumber = makePtIndex2PtNumber(indexToPoints);
        var out = [];

        for(var i = 0; i < selectedpoints.length; i++) {
            var ptIndex = selectedpoints[i];
            if(lib.isIndex(ptIndex)) {
                var ptNumber = ptIndex2ptNumber[ptIndex];
                if(lib.isIndex(ptNumber)) {
                    out.push(ptNumber);
                }
            }
        }

        return out;
    } else {
        return selectedpoints;
    }
};

/** Returns target as set by 'target' transform attribute
 *
 * @param {object} trace : full trace object
 * @param {object} transformOpts : transform option object
 *  - target (string} :
 *      either an attribute string referencing an array in the trace object, or
 *      a set array.
 *
 * @return {array or false} : the target array (NOT a copy!!) or false if invalid
 */
lib.getTargetArray = function(trace, transformOpts) {
    var target = transformOpts.target;

    if(typeof target === 'string' && target) {
        var array = lib.nestedProperty(trace, target).get();
        return Array.isArray(array) ? array : false;
    } else if(Array.isArray(target)) {
        return target;
    }

    return false;
};

/**
 * modified version of jQuery's extend to strip out private objs and functions,
 * and cut arrays down to first <arraylen> or 1 elements
 * because extend-like algorithms are hella slow
 * obj2 is assumed to already be clean of these things (including no arrays)
 */
lib.minExtend = function(obj1, obj2) {
    var objOut = {};
    if(typeof obj2 !== 'object') obj2 = {};
    var arrayLen = 3;
    var keys = Object.keys(obj1);
    var i, k, v;

    for(i = 0; i < keys.length; i++) {
        k = keys[i];
        v = obj1[k];
        if(k.charAt(0) === '_' || typeof v === 'function') continue;
        else if(k === 'module') objOut[k] = v;
        else if(Array.isArray(v)) {
            if(k === 'colorscale') {
                objOut[k] = v.slice();
            } else {
                objOut[k] = v.slice(0, arrayLen);
            }
        }
        else if(v && (typeof v === 'object')) objOut[k] = lib.minExtend(obj1[k], obj2[k]);
        else objOut[k] = v;
    }

    keys = Object.keys(obj2);
    for(i = 0; i < keys.length; i++) {
        k = keys[i];
        v = obj2[k];
        if(typeof v !== 'object' || !(k in objOut) || typeof objOut[k] !== 'object') {
            objOut[k] = v;
        }
    }

    return objOut;
};

lib.titleCase = function(s) {
    return s.charAt(0).toUpperCase() + s.substr(1);
};

lib.containsAny = function(s, fragments) {
    for(var i = 0; i < fragments.length; i++) {
        if(s.indexOf(fragments[i]) !== -1) return true;
    }
    return false;
};

lib.isPlotDiv = function(el) {
    var el3 = d3.select(el);
    return el3.node() instanceof HTMLElement &&
        el3.size() &&
        el3.classed('js-plotly-plot');
};

lib.removeElement = function(el) {
    var elParent = el && el.parentNode;
    if(elParent) elParent.removeChild(el);
};

/**
 * for dynamically adding style rules
 * makes one stylesheet that contains all rules added
 * by all calls to this function
 */
lib.addStyleRule = function(selector, styleString) {
    lib.addRelatedStyleRule('global', selector, styleString);
};

/**
 * for dynamically adding style rules
 * to a stylesheet uniquely identified by a uid
 */
lib.addRelatedStyleRule = function(uid, selector, styleString) {
    var id = 'plotly.js-style-' + uid;
    var style = document.getElementById(id);
    if(!style) {
        style = document.createElement('style');
        style.setAttribute('id', id);
        // WebKit hack :(
        style.appendChild(document.createTextNode(''));
        document.head.appendChild(style);
    }
    var styleSheet = style.sheet;

    if(styleSheet.insertRule) {
        styleSheet.insertRule(selector + '{' + styleString + '}', 0);
    }
    else if(styleSheet.addRule) {
        styleSheet.addRule(selector, styleString, 0);
    }
    else lib.warn('addStyleRule failed');
};

/**
 * to remove from the page a stylesheet identified by a given uid
 */
lib.deleteRelatedStyleRule = function(uid) {
    var id = 'plotly.js-style-' + uid;
    var style = document.getElementById(id);
    if(style) lib.removeElement(style);
};

lib.isIE = function() {
    return typeof window.navigator.msSaveBlob !== 'undefined';
};

/**
 * Duck typing to recognize a d3 selection, mostly for IE9's benefit
 * because it doesn't handle instanceof like modern browsers
 */
lib.isD3Selection = function(obj) {
    return obj && (typeof obj.classed === 'function');
};

/**
 * Append element to DOM only if not present.
 *
 * @param {d3 selection} parent : parent selection of the element in question
 * @param {string} nodeType : node type of element to append
 * @param {string} className (optional) : class name of element in question
 * @param {fn} enterFn (optional) : optional fn applied to entering elements only
 * @return {d3 selection} selection of new layer
 *
 * Previously, we were using the following pattern:
 *
 * ```
 * var sel = parent.selectAll('.' + className)
 *     .data([0]);
 *
 * sel.enter().append(nodeType)
 *     .classed(className, true);
 *
 * return sel;
 * ```
 *
 * in numerous places in our codebase to achieve the same behavior.
 *
 * The logic below performs much better, mostly as we are using
 * `.select` instead `.selectAll` that is `querySelector` instead of
 * `querySelectorAll`.
 *
 */
lib.ensureSingle = function(parent, nodeType, className, enterFn) {
    var sel = parent.select(nodeType + (className ? '.' + className : ''));
    if(sel.size()) return sel;

    var layer = parent.append(nodeType);
    if(className) layer.classed(className, true);
    if(enterFn) layer.call(enterFn);

    return layer;
};

/**
 * Same as Lib.ensureSingle, but using id as selector.
 * This version is mostly used for clipPath nodes.
 *
 * @param {d3 selection} parent : parent selection of the element in question
 * @param {string} nodeType : node type of element to append
 * @param {string} id : id of element in question
 * @param {fn} enterFn (optional) : optional fn applied to entering elements only
 * @return {d3 selection} selection of new layer
 */
lib.ensureSingleById = function(parent, nodeType, id, enterFn) {
    var sel = parent.select(nodeType + '#' + id);
    if(sel.size()) return sel;

    var layer = parent.append(nodeType).attr('id', id);
    if(enterFn) layer.call(enterFn);

    return layer;
};

/**
 * Converts a string path to an object.
 *
 * When given a string containing an array element, it will create a `null`
 * filled array of the given size.
 *
 * @example
 * lib.objectFromPath('nested.test[2].path', 'value');
 * // returns { nested: { test: [null, null, { path: 'value' }]}
 *
 * @param   {string}    path to nested value
 * @param   {*}         any value to be set
 *
 * @return {Object} the constructed object with a full nested path
 */
lib.objectFromPath = function(path, value) {
    var keys = path.split('.');
    var tmpObj;
    var obj = tmpObj = {};

    for(var i = 0; i < keys.length; i++) {
        var key = keys[i];
        var el = null;

        var parts = keys[i].match(/(.*)\[([0-9]+)\]/);

        if(parts) {
            key = parts[1];
            el = parts[2];

            tmpObj = tmpObj[key] = [];

            if(i === keys.length - 1) {
                tmpObj[el] = value;
            } else {
                tmpObj[el] = {};
            }

            tmpObj = tmpObj[el];
        } else {

            if(i === keys.length - 1) {
                tmpObj[key] = value;
            } else {
                tmpObj[key] = {};
            }

            tmpObj = tmpObj[key];
        }
    }

    return obj;
};

/**
 * Iterate through an object in-place, converting dotted properties to objects.
 *
 * Examples:
 *
 *   lib.expandObjectPaths({'nested.test.path': 'value'});
 *     => { nested: { test: {path: 'value'}}}
 *
 * It also handles array notation, e.g.:
 *
 *   lib.expandObjectPaths({'foo[1].bar': 'value'});
 *     => { foo: [null, {bar: value}] }
 *
 * It handles merges the results when two properties are specified in parallel:
 *
 *   lib.expandObjectPaths({'foo[1].bar': 10, 'foo[0].bar': 20});
 *     => { foo: [{bar: 10}, {bar: 20}] }
 *
 * It does NOT, however, merge mulitple mutliply-nested arrays::
 *
 *   lib.expandObjectPaths({'marker[1].range[1]': 5, 'marker[1].range[0]': 4})
 *     => { marker: [null, {range: 4}] }
 */

// Store this to avoid recompiling regex on *every* prop since this may happen many
// many times for animations. Could maybe be inside the function. Not sure about
// scoping vs. recompilation tradeoff, but at least it's not just inlining it into
// the inner loop.
var dottedPropertyRegex = /^([^\[\.]+)\.(.+)?/;
var indexedPropertyRegex = /^([^\.]+)\[([0-9]+)\](\.)?(.+)?/;

lib.expandObjectPaths = function(data) {
    var match, key, prop, datum, idx, dest, trailingPath;
    if(typeof data === 'object' && !Array.isArray(data)) {
        for(key in data) {
            if(data.hasOwnProperty(key)) {
                if((match = key.match(dottedPropertyRegex))) {
                    datum = data[key];
                    prop = match[1];

                    delete data[key];

                    data[prop] = lib.extendDeepNoArrays(data[prop] || {}, lib.objectFromPath(key, lib.expandObjectPaths(datum))[prop]);
                } else if((match = key.match(indexedPropertyRegex))) {
                    datum = data[key];

                    prop = match[1];
                    idx = parseInt(match[2]);

                    delete data[key];

                    data[prop] = data[prop] || [];

                    if(match[3] === '.') {
                        // This is the case where theere are subsequent properties into which
                        // we must recurse, e.g. transforms[0].value
                        trailingPath = match[4];
                        dest = data[prop][idx] = data[prop][idx] || {};

                        // NB: Extend deep no arrays prevents this from working on multiple
                        // nested properties in the same object, e.g.
                        //
                        // {
                        //   foo[0].bar[1].range
                        //   foo[0].bar[0].range
                        // }
                        //
                        // In this case, the extendDeepNoArrays will overwrite one array with
                        // the other, so that both properties *will not* be present in the
                        // result. Fixing this would require a more intelligent tracking
                        // of changes and merging than extendDeepNoArrays currently accomplishes.
                        lib.extendDeepNoArrays(dest, lib.objectFromPath(trailingPath, lib.expandObjectPaths(datum)));
                    } else {
                        // This is the case where this property is the end of the line,
                        // e.g. xaxis.range[0]
                        data[prop][idx] = lib.expandObjectPaths(datum);
                    }
                } else {
                    data[key] = lib.expandObjectPaths(data[key]);
                }
            }
        }
    }

    return data;
};

/**
 * Converts value to string separated by the provided separators.
 *
 * @example
 * lib.numSeparate(2016, '.,');
 * // returns '2016'
 *
 * @example
 * lib.numSeparate(3000, '.,', true);
 * // returns '3,000'
 *
 * @example
 * lib.numSeparate(1234.56, '|,')
 * // returns '1,234|56'
 *
 * @param   {string|number} value       the value to be converted
 * @param   {string}    separators  string of decimal, then thousands separators
 * @param   {boolean}    separatethousands  boolean, 4-digit integers are separated if true
 *
 * @return  {string}    the value that has been separated
 */
lib.numSeparate = function(value, separators, separatethousands) {
    if(!separatethousands) separatethousands = false;

    if(typeof separators !== 'string' || separators.length === 0) {
        throw new Error('Separator string required for formatting!');
    }

    if(typeof value === 'number') {
        value = String(value);
    }

    var thousandsRe = /(\d+)(\d{3})/;
    var decimalSep = separators.charAt(0);
    var thouSep = separators.charAt(1);

    var x = value.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? decimalSep + x[1] : '';

    // Years are ignored for thousands separators
    if(thouSep && (x.length > 1 || x1.length > 4 || separatethousands)) {
        while(thousandsRe.test(x1)) {
            x1 = x1.replace(thousandsRe, '$1' + thouSep + '$2');
        }
    }

    return x1 + x2;
};

var TEMPLATE_STRING_REGEX = /%{([^\s%{}:]*)(:[^}]*)?}/g;
var SIMPLE_PROPERTY_REGEX = /^\w*$/;

/**
 * Substitute values from an object into a string
 *
 * Examples:
 *  Lib.templateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
 *  Lib.templateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
 *
 * @param {string}  input string containing %{...} template strings
 * @param {obj}     data object containing substitution values
 *
 * @return {string} templated string
 */
lib.templateString = function(string, obj) {
    // Not all that useful, but cache nestedProperty instantiation
    // just in case it speeds things up *slightly*:
    var getterCache = {};

    return string.replace(TEMPLATE_STRING_REGEX, function(dummy, key) {
        if(SIMPLE_PROPERTY_REGEX.test(key)) {
            return obj[key] || '';
        }
        getterCache[key] = getterCache[key] || lib.nestedProperty(obj, key).get;
        return getterCache[key]() || '';
    });
};

var TEMPLATE_STRING_FORMAT_SEPARATOR = /^:/;
var numberOfHoverTemplateWarnings = 0;
var maximumNumberOfHoverTemplateWarnings = 10;
/**
 * Substitute values from an object into a string and optionally formats them using d3-format,
 * or fallback to associated labels.
 *
 * Examples:
 *  Lib.templateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
 *  Lib.templateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
 *  Lib.templateString('price: %{y:$.2f}', {y: 1}) --> 'price: $1.00'
 *
 * @param {string}  input string containing %{...:...} template strings
 * @param {obj}     data object containing fallback text when no formatting is specified, ex.: {yLabel: 'formattedYValue'}
 * @param {obj}     data objects containing substitution values
 *
 * @return {string} templated string
 */
lib.hovertemplateString = function(string, labels) {
    var args = arguments;
    // Not all that useful, but cache nestedProperty instantiation
    // just in case it speeds things up *slightly*:
    var getterCache = {};

    return string.replace(TEMPLATE_STRING_REGEX, function(match, key, format) {
        var obj, value, i;
        for(i = 2; i < args.length; i++) {
            obj = args[i];
            if(obj.hasOwnProperty(key)) {
                value = obj[key];
                break;
            }

            if(!SIMPLE_PROPERTY_REGEX.test(key)) {
                value = getterCache[key] || lib.nestedProperty(obj, key).get();
                if(value) getterCache[key] = value;
            }
            if(value !== undefined) break;
        }

        if(value === undefined) {
            if(numberOfHoverTemplateWarnings < maximumNumberOfHoverTemplateWarnings) {
                lib.warn('Variable \'' + key + '\' in hovertemplate could not be found!');
                value = match;
            }

            if(numberOfHoverTemplateWarnings === maximumNumberOfHoverTemplateWarnings) {
                lib.warn('Too many hovertemplate warnings - additional warnings will be suppressed');
            }
            numberOfHoverTemplateWarnings++;
        }

        if(format) {
            value = d3.format(format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ''))(value);
        } else {
            if(labels.hasOwnProperty(key + 'Label')) value = labels[key + 'Label'];
        }
        return value;
    });
};

/*
 * alphanumeric string sort, tailored for subplot IDs like scene2, scene10, x10y13 etc
 */
var char0 = 48;
var char9 = 57;
lib.subplotSort = function(a, b) {
    var l = Math.min(a.length, b.length) + 1;
    var numA = 0;
    var numB = 0;
    for(var i = 0; i < l; i++) {
        var charA = a.charCodeAt(i) || 0;
        var charB = b.charCodeAt(i) || 0;
        var isNumA = charA >= char0 && charA <= char9;
        var isNumB = charB >= char0 && charB <= char9;

        if(isNumA) numA = 10 * numA + charA - char0;
        if(isNumB) numB = 10 * numB + charB - char0;

        if(!isNumA || !isNumB) {
            if(numA !== numB) return numA - numB;
            if(charA !== charB) return charA - charB;
        }
    }
    return numB - numA;
};

// repeatable pseudorandom generator
var randSeed = 2000000000;

lib.seedPseudoRandom = function() {
    randSeed = 2000000000;
};

lib.pseudoRandom = function() {
    var lastVal = randSeed;
    randSeed = (69069 * randSeed + 1) % 4294967296;
    // don't let consecutive vals be too close together
    // gets away from really trying to be random, in favor of better local uniformity
    if(Math.abs(randSeed - lastVal) < 429496729) return lib.pseudoRandom();
    return randSeed / 4294967296;
};


/***/ }),

/***/ "/Dvf":
/*!********************************************************!*\
  !*** ./node_modules/@phosphor/domutils/lib/element.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * The namespace for element related utilities.
 */
var ElementExt;
(function (ElementExt) {
    /**
     * Compute the box sizing for an element.
     *
     * @param element - The element of interest.
     *
     * @returns The box sizing data for the specified element.
     */
    function boxSizing(element) {
        var style = window.getComputedStyle(element);
        var bt = parseFloat(style.borderTopWidth) || 0;
        var bl = parseFloat(style.borderLeftWidth) || 0;
        var br = parseFloat(style.borderRightWidth) || 0;
        var bb = parseFloat(style.borderBottomWidth) || 0;
        var pt = parseFloat(style.paddingTop) || 0;
        var pl = parseFloat(style.paddingLeft) || 0;
        var pr = parseFloat(style.paddingRight) || 0;
        var pb = parseFloat(style.paddingBottom) || 0;
        var hs = bl + pl + pr + br;
        var vs = bt + pt + pb + bb;
        return {
            borderTop: bt,
            borderLeft: bl,
            borderRight: br,
            borderBottom: bb,
            paddingTop: pt,
            paddingLeft: pl,
            paddingRight: pr,
            paddingBottom: pb,
            horizontalSum: hs,
            verticalSum: vs
        };
    }
    ElementExt.boxSizing = boxSizing;
    /**
     * Compute the size limits for an element.
     *
     * @param element - The element of interest.
     *
     * @returns The size limit data for the specified element.
     */
    function sizeLimits(element) {
        var style = window.getComputedStyle(element);
        var minWidth = parseFloat(style.minWidth) || 0;
        var minHeight = parseFloat(style.minHeight) || 0;
        var maxWidth = parseFloat(style.maxWidth) || Infinity;
        var maxHeight = parseFloat(style.maxHeight) || Infinity;
        maxWidth = Math.max(minWidth, maxWidth);
        maxHeight = Math.max(minHeight, maxHeight);
        return { minWidth: minWidth, minHeight: minHeight, maxWidth: maxWidth, maxHeight: maxHeight };
    }
    ElementExt.sizeLimits = sizeLimits;
    /**
     * Test whether a client position lies within an element.
     *
     * @param element - The DOM element of interest.
     *
     * @param clientX - The client X coordinate of interest.
     *
     * @param clientY - The client Y coordinate of interest.
     *
     * @returns Whether the point is within the given element.
     */
    function hitTest(element, clientX, clientY) {
        var rect = element.getBoundingClientRect();
        return (clientX >= rect.left &&
            clientX < rect.right &&
            clientY >= rect.top &&
            clientY < rect.bottom);
    }
    ElementExt.hitTest = hitTest;
    /**
     * Vertically scroll an element into view if needed.
     *
     * @param area - The scroll area element.
     *
     * @param element - The element of interest.
     *
     * #### Notes
     * This follows the "nearest" behavior of the native `scrollIntoView`
     * method, which is not supported by all browsers.
     * https://drafts.csswg.org/cssom-view/#element-scrolling-members
     *
     * If the element fully covers the visible area or is fully contained
     * within the visible area, no scrolling will take place. Otherwise,
     * the nearest edges of the area and element are aligned.
     */
    function scrollIntoViewIfNeeded(area, element) {
        var ar = area.getBoundingClientRect();
        var er = element.getBoundingClientRect();
        if (er.top <= ar.top && er.bottom >= ar.bottom) {
            return;
        }
        if (er.top < ar.top && er.height <= ar.height) {
            area.scrollTop -= ar.top - er.top;
            return;
        }
        if (er.bottom > ar.bottom && er.height >= ar.height) {
            area.scrollTop -= ar.top - er.top;
            return;
        }
        if (er.top < ar.top && er.height > ar.height) {
            area.scrollTop -= ar.bottom - er.bottom;
            return;
        }
        if (er.bottom > ar.bottom && er.height < ar.height) {
            area.scrollTop -= ar.bottom - er.bottom;
            return;
        }
    }
    ElementExt.scrollIntoViewIfNeeded = scrollIntoViewIfNeeded;
})(ElementExt = exports.ElementExt || (exports.ElementExt = {}));


/***/ }),

/***/ "/FUP":
/*!********************************************!*\
  !*** ./node_modules/reactcss/lib/index.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ReactCSS = exports.loop = exports.handleActive = exports.handleHover = exports.hover = undefined;

var _flattenNames = __webpack_require__(/*! ./flattenNames */ "W3HW");

var _flattenNames2 = _interopRequireDefault(_flattenNames);

var _mergeClasses = __webpack_require__(/*! ./mergeClasses */ "lreK");

var _mergeClasses2 = _interopRequireDefault(_mergeClasses);

var _autoprefix = __webpack_require__(/*! ./autoprefix */ "KfSR");

var _autoprefix2 = _interopRequireDefault(_autoprefix);

var _hover2 = __webpack_require__(/*! ./components/hover */ "VYtm");

var _hover3 = _interopRequireDefault(_hover2);

var _active = __webpack_require__(/*! ./components/active */ "XQvf");

var _active2 = _interopRequireDefault(_active);

var _loop2 = __webpack_require__(/*! ./loop */ "B5Mt");

var _loop3 = _interopRequireDefault(_loop2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.hover = _hover3.default;
exports.handleHover = _hover3.default;
exports.handleActive = _active2.default;
exports.loop = _loop3.default;
var ReactCSS = exports.ReactCSS = function ReactCSS(classes) {
  for (var _len = arguments.length, activations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    activations[_key - 1] = arguments[_key];
  }

  var activeNames = (0, _flattenNames2.default)(activations);
  var merged = (0, _mergeClasses2.default)(classes, activeNames);
  return (0, _autoprefix2.default)(merged);
};

exports.default = ReactCSS;

/***/ }),

/***/ "/GrO":
/*!******************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/codemirror/lib/codemirror.css ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/* BASICS */\n\n.CodeMirror {\n  /* Set height, width, borders, and global font properties here */\n  font-family: monospace;\n  height: 300px;\n  color: black;\n  direction: ltr;\n}\n\n/* PADDING */\n\n.CodeMirror-lines {\n  padding: 4px 0; /* Vertical padding around content */\n}\n.CodeMirror pre {\n  padding: 0 4px; /* Horizontal padding of content */\n}\n\n.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {\n  background-color: white; /* The little square between H and V scrollbars */\n}\n\n/* GUTTER */\n\n.CodeMirror-gutters {\n  border-right: 1px solid #ddd;\n  background-color: #f7f7f7;\n  white-space: nowrap;\n}\n.CodeMirror-linenumbers {}\n.CodeMirror-linenumber {\n  padding: 0 3px 0 5px;\n  min-width: 20px;\n  text-align: right;\n  color: #999;\n  white-space: nowrap;\n}\n\n.CodeMirror-guttermarker { color: black; }\n.CodeMirror-guttermarker-subtle { color: #999; }\n\n/* CURSOR */\n\n.CodeMirror-cursor {\n  border-left: 1px solid black;\n  border-right: none;\n  width: 0;\n}\n/* Shown when moving in bi-directional text */\n.CodeMirror div.CodeMirror-secondarycursor {\n  border-left: 1px solid silver;\n}\n.cm-fat-cursor .CodeMirror-cursor {\n  width: auto;\n  border: 0 !important;\n  background: #7e7;\n}\n.cm-fat-cursor div.CodeMirror-cursors {\n  z-index: 1;\n}\n.cm-fat-cursor-mark {\n  background-color: rgba(20, 255, 20, 0.5);\n  -webkit-animation: blink 1.06s steps(1) infinite;\n  -moz-animation: blink 1.06s steps(1) infinite;\n  animation: blink 1.06s steps(1) infinite;\n}\n.cm-animate-fat-cursor {\n  width: auto;\n  border: 0;\n  -webkit-animation: blink 1.06s steps(1) infinite;\n  -moz-animation: blink 1.06s steps(1) infinite;\n  animation: blink 1.06s steps(1) infinite;\n  background-color: #7e7;\n}\n@-moz-keyframes blink {\n  0% {}\n  50% { background-color: transparent; }\n  100% {}\n}\n@-webkit-keyframes blink {\n  0% {}\n  50% { background-color: transparent; }\n  100% {}\n}\n@keyframes blink {\n  0% {}\n  50% { background-color: transparent; }\n  100% {}\n}\n\n/* Can style cursor different in overwrite (non-insert) mode */\n.CodeMirror-overwrite .CodeMirror-cursor {}\n\n.cm-tab { display: inline-block; text-decoration: inherit; }\n\n.CodeMirror-rulers {\n  position: absolute;\n  left: 0; right: 0; top: -50px; bottom: -20px;\n  overflow: hidden;\n}\n.CodeMirror-ruler {\n  border-left: 1px solid #ccc;\n  top: 0; bottom: 0;\n  position: absolute;\n}\n\n/* DEFAULT THEME */\n\n.cm-s-default .cm-header {color: blue;}\n.cm-s-default .cm-quote {color: #090;}\n.cm-negative {color: #d44;}\n.cm-positive {color: #292;}\n.cm-header, .cm-strong {font-weight: bold;}\n.cm-em {font-style: italic;}\n.cm-link {text-decoration: underline;}\n.cm-strikethrough {text-decoration: line-through;}\n\n.cm-s-default .cm-keyword {color: #708;}\n.cm-s-default .cm-atom {color: #219;}\n.cm-s-default .cm-number {color: #164;}\n.cm-s-default .cm-def {color: #00f;}\n.cm-s-default .cm-variable,\n.cm-s-default .cm-punctuation,\n.cm-s-default .cm-property,\n.cm-s-default .cm-operator {}\n.cm-s-default .cm-variable-2 {color: #05a;}\n.cm-s-default .cm-variable-3, .cm-s-default .cm-type {color: #085;}\n.cm-s-default .cm-comment {color: #a50;}\n.cm-s-default .cm-string {color: #a11;}\n.cm-s-default .cm-string-2 {color: #f50;}\n.cm-s-default .cm-meta {color: #555;}\n.cm-s-default .cm-qualifier {color: #555;}\n.cm-s-default .cm-builtin {color: #30a;}\n.cm-s-default .cm-bracket {color: #997;}\n.cm-s-default .cm-tag {color: #170;}\n.cm-s-default .cm-attribute {color: #00c;}\n.cm-s-default .cm-hr {color: #999;}\n.cm-s-default .cm-link {color: #00c;}\n\n.cm-s-default .cm-error {color: #f00;}\n.cm-invalidchar {color: #f00;}\n\n.CodeMirror-composing { border-bottom: 2px solid; }\n\n/* Default styles for common addons */\n\ndiv.CodeMirror span.CodeMirror-matchingbracket {color: #0b0;}\ndiv.CodeMirror span.CodeMirror-nonmatchingbracket {color: #a22;}\n.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }\n.CodeMirror-activeline-background {background: #e8f2ff;}\n\n/* STOP */\n\n/* The rest of this file contains styles related to the mechanics of\n   the editor. You probably shouldn't touch them. */\n\n.CodeMirror {\n  position: relative;\n  overflow: hidden;\n  background: white;\n}\n\n.CodeMirror-scroll {\n  overflow: scroll !important; /* Things will break if this is overridden */\n  /* 30px is the magic margin used to hide the element's real scrollbars */\n  /* See overflow: hidden in .CodeMirror */\n  margin-bottom: -30px; margin-right: -30px;\n  padding-bottom: 30px;\n  height: 100%;\n  outline: none; /* Prevent dragging from highlighting the element */\n  position: relative;\n}\n.CodeMirror-sizer {\n  position: relative;\n  border-right: 30px solid transparent;\n}\n\n/* The fake, visible scrollbars. Used to force redraw during scrolling\n   before actual scrolling happens, thus preventing shaking and\n   flickering artifacts. */\n.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {\n  position: absolute;\n  z-index: 6;\n  display: none;\n}\n.CodeMirror-vscrollbar {\n  right: 0; top: 0;\n  overflow-x: hidden;\n  overflow-y: scroll;\n}\n.CodeMirror-hscrollbar {\n  bottom: 0; left: 0;\n  overflow-y: hidden;\n  overflow-x: scroll;\n}\n.CodeMirror-scrollbar-filler {\n  right: 0; bottom: 0;\n}\n.CodeMirror-gutter-filler {\n  left: 0; bottom: 0;\n}\n\n.CodeMirror-gutters {\n  position: absolute; left: 0; top: 0;\n  min-height: 100%;\n  z-index: 3;\n}\n.CodeMirror-gutter {\n  white-space: normal;\n  height: 100%;\n  display: inline-block;\n  vertical-align: top;\n  margin-bottom: -30px;\n}\n.CodeMirror-gutter-wrapper {\n  position: absolute;\n  z-index: 4;\n  background: none !important;\n  border: none !important;\n}\n.CodeMirror-gutter-background {\n  position: absolute;\n  top: 0; bottom: 0;\n  z-index: 4;\n}\n.CodeMirror-gutter-elt {\n  position: absolute;\n  cursor: default;\n  z-index: 4;\n}\n.CodeMirror-gutter-wrapper ::selection { background-color: transparent }\n.CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent }\n\n.CodeMirror-lines {\n  cursor: text;\n  min-height: 1px; /* prevents collapsing before first draw */\n}\n.CodeMirror pre {\n  /* Reset some styles that the rest of the page might have set */\n  -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;\n  border-width: 0;\n  background: transparent;\n  font-family: inherit;\n  font-size: inherit;\n  margin: 0;\n  white-space: pre;\n  word-wrap: normal;\n  line-height: inherit;\n  color: inherit;\n  z-index: 2;\n  position: relative;\n  overflow: visible;\n  -webkit-tap-highlight-color: transparent;\n  -webkit-font-variant-ligatures: contextual;\n  font-variant-ligatures: contextual;\n}\n.CodeMirror-wrap pre {\n  word-wrap: break-word;\n  white-space: pre-wrap;\n  word-break: normal;\n}\n\n.CodeMirror-linebackground {\n  position: absolute;\n  left: 0; right: 0; top: 0; bottom: 0;\n  z-index: 0;\n}\n\n.CodeMirror-linewidget {\n  position: relative;\n  z-index: 2;\n  padding: 0.1px; /* Force widget margins to stay inside of the container */\n}\n\n.CodeMirror-widget {}\n\n.CodeMirror-rtl pre { direction: rtl; }\n\n.CodeMirror-code {\n  outline: none;\n}\n\n/* Force content-box sizing for the elements where we expect it */\n.CodeMirror-scroll,\n.CodeMirror-sizer,\n.CodeMirror-gutter,\n.CodeMirror-gutters,\n.CodeMirror-linenumber {\n  -moz-box-sizing: content-box;\n  box-sizing: content-box;\n}\n\n.CodeMirror-measure {\n  position: absolute;\n  width: 100%;\n  height: 0;\n  overflow: hidden;\n  visibility: hidden;\n}\n\n.CodeMirror-cursor {\n  position: absolute;\n  pointer-events: none;\n}\n.CodeMirror-measure pre { position: static; }\n\ndiv.CodeMirror-cursors {\n  visibility: hidden;\n  position: relative;\n  z-index: 3;\n}\ndiv.CodeMirror-dragcursors {\n  visibility: visible;\n}\n\n.CodeMirror-focused div.CodeMirror-cursors {\n  visibility: visible;\n}\n\n.CodeMirror-selected { background: #d9d9d9; }\n.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }\n.CodeMirror-crosshair { cursor: crosshair; }\n.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; }\n.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; }\n\n.cm-searching {\n  background-color: #ffa;\n  background-color: rgba(255, 255, 0, .4);\n}\n\n/* Used to force a border model for a node */\n.cm-force-border { padding-right: .1px; }\n\n@media print {\n  /* Hide the cursor when printing */\n  .CodeMirror div.CodeMirror-cursors {\n    visibility: hidden;\n  }\n}\n\n/* See issue #2901 */\n.cm-tab-wrap-hack:after { content: ''; }\n\n/* Help users use markselection to safely style text background */\nspan.CodeMirror-selectedtext { background: none; }\n", ""]);

// exports


/***/ }),

/***/ "/Hsf":
/*!*****************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/contents/index.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const __1 = __webpack_require__(/*! .. */ "S9up");
const validate = __importStar(__webpack_require__(/*! ./validate */ "53HD"));
/**
 * The url for the default drive service.
 */
const SERVICE_DRIVE_URL = 'api/contents';
/**
 * The url for the file access.
 */
const FILES_URL = 'files';
/**
 * A namespace for contents interfaces.
 */
var Contents;
(function (Contents) {
    /**
     * Validates an IModel, thowing an error if it does not pass.
     */
    function validateContentsModel(contents) {
        validate.validateContentsModel(contents);
    }
    Contents.validateContentsModel = validateContentsModel;
    /**
     * Validates an ICheckpointModel, thowing an error if it does not pass.
     */
    function validateCheckpointModel(checkpoint) {
        validate.validateCheckpointModel(checkpoint);
    }
    Contents.validateCheckpointModel = validateCheckpointModel;
})(Contents = exports.Contents || (exports.Contents = {}));
/**
 * A contents manager that passes file operations to the server.
 * Multiple servers implementing the `IDrive` interface can be
 * attached to the contents manager, so that the same session can
 * perform file operations on multiple backends.
 *
 * This includes checkpointing with the normal file operations.
 */
class ContentsManager {
    /**
     * Construct a new contents manager object.
     *
     * @param options - The options used to initialize the object.
     */
    constructor(options = {}) {
        this._isDisposed = false;
        this._additionalDrives = new Map();
        this._fileChanged = new signaling_1.Signal(this);
        let serverSettings = (this.serverSettings =
            options.serverSettings || __1.ServerConnection.makeSettings());
        this._defaultDrive = options.defaultDrive || new Drive({ serverSettings });
        this._defaultDrive.fileChanged.connect(this._onFileChanged, this);
    }
    /**
     * A signal emitted when a file operation takes place.
     */
    get fileChanged() {
        return this._fileChanged;
    }
    /**
     * Test whether the manager has been disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources held by the manager.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        signaling_1.Signal.clearData(this);
    }
    /**
     * Add an `IDrive` to the manager.
     */
    addDrive(drive) {
        this._additionalDrives.set(drive.name, drive);
        drive.fileChanged.connect(this._onFileChanged, this);
    }
    /**
     * Given a path, get a ModelDB.IFactory from the
     * relevant backend. Returns `null` if the backend
     * does not provide one.
     */
    getModelDBFactory(path) {
        let [drive] = this._driveForPath(path);
        return (drive && drive.modelDBFactory) || null;
    }
    /**
     * Given a path of the form `drive:local/portion/of/it.txt`
     * get the local part of it.
     *
     * @param path: the path.
     *
     * @returns The local part of the path.
     */
    localPath(path) {
        const parts = path.split('/');
        const firstParts = parts[0].split(':');
        if (firstParts.length === 1 || !this._additionalDrives.has(firstParts[0])) {
            return coreutils_1.PathExt.removeSlash(path);
        }
        return coreutils_1.PathExt.join(firstParts.slice(1).join(':'), ...parts.slice(1));
    }
    /**
     * Given a path of the form `drive:local/portion/of/it.txt`
     * get the name of the drive. If the path is missing
     * a drive portion, returns an empty string.
     *
     * @param path: the path.
     *
     * @returns The drive name for the path, or the empty string.
     */
    driveName(path) {
        const parts = path.split('/');
        const firstParts = parts[0].split(':');
        if (firstParts.length === 1) {
            return '';
        }
        if (this._additionalDrives.has(firstParts[0])) {
            return firstParts[0];
        }
        return '';
    }
    /**
     * Get a file or directory.
     *
     * @param path: The path to the file.
     *
     * @param options: The options used to fetch the file.
     *
     * @returns A promise which resolves with the file content.
     */
    get(path, options) {
        let [drive, localPath] = this._driveForPath(path);
        return drive.get(localPath, options).then(contentsModel => {
            let listing = [];
            if (contentsModel.type === 'directory' && contentsModel.content) {
                algorithm_1.each(contentsModel.content, (item) => {
                    listing.push(Object.assign({}, item, { path: this._toGlobalPath(drive, item.path) }));
                });
                return Object.assign({}, contentsModel, { path: this._toGlobalPath(drive, localPath), content: listing });
            }
            else {
                return Object.assign({}, contentsModel, { path: this._toGlobalPath(drive, localPath) });
            }
        });
    }
    /**
     * Get an encoded download url given a file path.
     *
     * @param path - An absolute POSIX file path on the server.
     *
     * #### Notes
     * It is expected that the path contains no relative paths.
     */
    getDownloadUrl(path) {
        let [drive, localPath] = this._driveForPath(path);
        return drive.getDownloadUrl(localPath);
    }
    /**
     * Create a new untitled file or directory in the specified directory path.
     *
     * @param options: The options used to create the file.
     *
     * @returns A promise which resolves with the created file content when the
     *    file is created.
     */
    newUntitled(options = {}) {
        if (options.path) {
            let globalPath = Private.normalize(options.path);
            let [drive, localPath] = this._driveForPath(globalPath);
            return drive
                .newUntitled(Object.assign({}, options, { path: localPath }))
                .then(contentsModel => {
                return Object.assign({}, contentsModel, { path: coreutils_1.PathExt.join(globalPath, contentsModel.name) });
            });
        }
        else {
            return this._defaultDrive.newUntitled(options);
        }
    }
    /**
     * Delete a file.
     *
     * @param path - The path to the file.
     *
     * @returns A promise which resolves when the file is deleted.
     */
    delete(path) {
        let [drive, localPath] = this._driveForPath(path);
        return drive.delete(localPath);
    }
    /**
     * Rename a file or directory.
     *
     * @param path - The original file path.
     *
     * @param newPath - The new file path.
     *
     * @returns A promise which resolves with the new file contents model when
     *   the file is renamed.
     */
    rename(path, newPath) {
        let [drive1, path1] = this._driveForPath(path);
        let [drive2, path2] = this._driveForPath(newPath);
        if (drive1 !== drive2) {
            throw Error('ContentsManager: renaming files must occur within a Drive');
        }
        return drive1.rename(path1, path2).then(contentsModel => {
            return Object.assign({}, contentsModel, { path: this._toGlobalPath(drive1, path2) });
        });
    }
    /**
     * Save a file.
     *
     * @param path - The desired file path.
     *
     * @param options - Optional overrides to the model.
     *
     * @returns A promise which resolves with the file content model when the
     *   file is saved.
     *
     * #### Notes
     * Ensure that `model.content` is populated for the file.
     */
    save(path, options = {}) {
        const globalPath = Private.normalize(path);
        const [drive, localPath] = this._driveForPath(path);
        return drive
            .save(localPath, Object.assign({}, options, { path: localPath }))
            .then(contentsModel => {
            return Object.assign({}, contentsModel, { path: globalPath });
        });
    }
    /**
     * Copy a file into a given directory.
     *
     * @param path - The original file path.
     *
     * @param toDir - The destination directory path.
     *
     * @returns A promise which resolves with the new contents model when the
     *  file is copied.
     *
     * #### Notes
     * The server will select the name of the copied file.
     */
    copy(fromFile, toDir) {
        let [drive1, path1] = this._driveForPath(fromFile);
        let [drive2, path2] = this._driveForPath(toDir);
        if (drive1 === drive2) {
            return drive1.copy(path1, path2).then(contentsModel => {
                return Object.assign({}, contentsModel, { path: this._toGlobalPath(drive1, contentsModel.path) });
            });
        }
        else {
            throw Error('Copying files between drives is not currently implemented');
        }
    }
    /**
     * Create a checkpoint for a file.
     *
     * @param path - The path of the file.
     *
     * @returns A promise which resolves with the new checkpoint model when the
     *   checkpoint is created.
     */
    createCheckpoint(path) {
        let [drive, localPath] = this._driveForPath(path);
        return drive.createCheckpoint(localPath);
    }
    /**
     * List available checkpoints for a file.
     *
     * @param path - The path of the file.
     *
     * @returns A promise which resolves with a list of checkpoint models for
     *    the file.
     */
    listCheckpoints(path) {
        let [drive, localPath] = this._driveForPath(path);
        return drive.listCheckpoints(localPath);
    }
    /**
     * Restore a file to a known checkpoint state.
     *
     * @param path - The path of the file.
     *
     * @param checkpointID - The id of the checkpoint to restore.
     *
     * @returns A promise which resolves when the checkpoint is restored.
     */
    restoreCheckpoint(path, checkpointID) {
        let [drive, localPath] = this._driveForPath(path);
        return drive.restoreCheckpoint(localPath, checkpointID);
    }
    /**
     * Delete a checkpoint for a file.
     *
     * @param path - The path of the file.
     *
     * @param checkpointID - The id of the checkpoint to delete.
     *
     * @returns A promise which resolves when the checkpoint is deleted.
     */
    deleteCheckpoint(path, checkpointID) {
        let [drive, localPath] = this._driveForPath(path);
        return drive.deleteCheckpoint(localPath, checkpointID);
    }
    /**
     * Given a drive and a local path, construct a fully qualified
     * path. The inverse of `_driveForPath`.
     *
     * @param drive: an `IDrive`.
     *
     * @param localPath: the local path on the drive.
     *
     * @returns the fully qualified path.
     */
    _toGlobalPath(drive, localPath) {
        if (drive === this._defaultDrive) {
            return coreutils_1.PathExt.removeSlash(localPath);
        }
        else {
            return `${drive.name}:${coreutils_1.PathExt.removeSlash(localPath)}`;
        }
    }
    /**
     * Given a path, get the `IDrive to which it refers,
     * where the path satisfies the pattern
     * `'driveName:path/to/file'`. If there is no `driveName`
     * prepended to the path, it returns the default drive.
     *
     * @param path: a path to a file.
     *
     * @returns A tuple containing an `IDrive` object for the path,
     * and a local path for that drive.
     */
    _driveForPath(path) {
        const driveName = this.driveName(path);
        const localPath = this.localPath(path);
        if (driveName) {
            return [this._additionalDrives.get(driveName), localPath];
        }
        else {
            return [this._defaultDrive, localPath];
        }
    }
    /**
     * Respond to fileChanged signals from the drives attached to
     * the manager. This prepends the drive name to the path if necessary,
     * and then forwards the signal.
     */
    _onFileChanged(sender, args) {
        if (sender === this._defaultDrive) {
            this._fileChanged.emit(args);
        }
        else {
            let newValue = null;
            let oldValue = null;
            if (args.newValue && args.newValue.path) {
                newValue = Object.assign({}, args.newValue, { path: this._toGlobalPath(sender, args.newValue.path) });
            }
            if (args.oldValue && args.oldValue.path) {
                oldValue = Object.assign({}, args.oldValue, { path: this._toGlobalPath(sender, args.oldValue.path) });
            }
            this._fileChanged.emit({
                type: args.type,
                newValue,
                oldValue
            });
        }
    }
}
exports.ContentsManager = ContentsManager;
/**
 * A default implementation for an `IDrive`, talking to the
 * server using the Jupyter REST API.
 */
class Drive {
    /**
     * Construct a new contents manager object.
     *
     * @param options - The options used to initialize the object.
     */
    constructor(options = {}) {
        this._isDisposed = false;
        this._fileChanged = new signaling_1.Signal(this);
        this.name = options.name || 'Default';
        this._apiEndpoint = options.apiEndpoint || SERVICE_DRIVE_URL;
        this.serverSettings =
            options.serverSettings || __1.ServerConnection.makeSettings();
    }
    /**
     * A signal emitted when a file operation takes place.
     */
    get fileChanged() {
        return this._fileChanged;
    }
    /**
     * Test whether the manager has been disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources held by the manager.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        signaling_1.Signal.clearData(this);
    }
    /**
     * Get a file or directory.
     *
     * @param localPath: The path to the file.
     *
     * @param options: The options used to fetch the file.
     *
     * @returns A promise which resolves with the file content.
     *
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/contents) and validates the response model.
     */
    get(localPath, options) {
        let url = this._getUrl(localPath);
        if (options) {
            // The notebook type cannot take an format option.
            if (options.type === 'notebook') {
                delete options['format'];
            }
            let content = options.content ? '1' : '0';
            let params = Object.assign({}, options, { content });
            url += coreutils_1.URLExt.objectToQueryString(params);
        }
        let settings = this.serverSettings;
        return __1.ServerConnection.makeRequest(url, {}, settings)
            .then(response => {
            if (response.status !== 200) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            return response.json();
        })
            .then(data => {
            validate.validateContentsModel(data);
            return data;
        });
    }
    /**
     * Get an encoded download url given a file path.
     *
     * @param localPath - An absolute POSIX file path on the server.
     *
     * #### Notes
     * It is expected that the path contains no relative paths.
     */
    getDownloadUrl(localPath) {
        let baseUrl = this.serverSettings.baseUrl;
        return Promise.resolve(coreutils_1.URLExt.join(baseUrl, FILES_URL, coreutils_1.URLExt.encodeParts(localPath)));
    }
    /**
     * Create a new untitled file or directory in the specified directory path.
     *
     * @param options: The options used to create the file.
     *
     * @returns A promise which resolves with the created file content when the
     *    file is created.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/contents) and validates the response model.
     */
    newUntitled(options = {}) {
        let body = '{}';
        if (options) {
            if (options.ext) {
                options.ext = Private.normalizeExtension(options.ext);
            }
            body = JSON.stringify(options);
        }
        let settings = this.serverSettings;
        let url = this._getUrl(options.path || '');
        let init = {
            method: 'POST',
            body
        };
        return __1.ServerConnection.makeRequest(url, init, settings)
            .then(response => {
            if (response.status !== 201) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            return response.json();
        })
            .then(data => {
            validate.validateContentsModel(data);
            this._fileChanged.emit({
                type: 'new',
                oldValue: null,
                newValue: data
            });
            return data;
        });
    }
    /**
     * Delete a file.
     *
     * @param localPath - The path to the file.
     *
     * @returns A promise which resolves when the file is deleted.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/contents).
     */
    delete(localPath) {
        let url = this._getUrl(localPath);
        let settings = this.serverSettings;
        let init = { method: 'DELETE' };
        return __1.ServerConnection.makeRequest(url, init, settings).then(response => {
            // Translate certain errors to more specific ones.
            // TODO: update IPEP27 to specify errors more precisely, so
            // that error types can be detected here with certainty.
            if (response.status === 400) {
                return response.json().then(data => {
                    throw new __1.ServerConnection.ResponseError(response, data['message']);
                });
            }
            if (response.status !== 204) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            this._fileChanged.emit({
                type: 'delete',
                oldValue: { path: localPath },
                newValue: null
            });
        });
    }
    /**
     * Rename a file or directory.
     *
     * @param oldLocalPath - The original file path.
     *
     * @param newLocalPath - The new file path.
     *
     * @returns A promise which resolves with the new file contents model when
     *   the file is renamed.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/contents) and validates the response model.
     */
    rename(oldLocalPath, newLocalPath) {
        let settings = this.serverSettings;
        let url = this._getUrl(oldLocalPath);
        let init = {
            method: 'PATCH',
            body: JSON.stringify({ path: newLocalPath })
        };
        return __1.ServerConnection.makeRequest(url, init, settings)
            .then(response => {
            if (response.status !== 200) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            return response.json();
        })
            .then(data => {
            validate.validateContentsModel(data);
            this._fileChanged.emit({
                type: 'rename',
                oldValue: { path: oldLocalPath },
                newValue: data
            });
            return data;
        });
    }
    /**
     * Save a file.
     *
     * @param localPath - The desired file path.
     *
     * @param options - Optional overrides to the model.
     *
     * @returns A promise which resolves with the file content model when the
     *   file is saved.
     *
     * #### Notes
     * Ensure that `model.content` is populated for the file.
     *
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/contents) and validates the response model.
     */
    save(localPath, options = {}) {
        let settings = this.serverSettings;
        let url = this._getUrl(localPath);
        let init = {
            method: 'PUT',
            body: JSON.stringify(options)
        };
        return __1.ServerConnection.makeRequest(url, init, settings)
            .then(response => {
            // will return 200 for an existing file and 201 for a new file
            if (response.status !== 200 && response.status !== 201) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            return response.json();
        })
            .then(data => {
            validate.validateContentsModel(data);
            this._fileChanged.emit({
                type: 'save',
                oldValue: null,
                newValue: data
            });
            return data;
        });
    }
    /**
     * Copy a file into a given directory.
     *
     * @param localPath - The original file path.
     *
     * @param toDir - The destination directory path.
     *
     * @returns A promise which resolves with the new contents model when the
     *  file is copied.
     *
     * #### Notes
     * The server will select the name of the copied file.
     *
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/contents) and validates the response model.
     */
    copy(fromFile, toDir) {
        let settings = this.serverSettings;
        let url = this._getUrl(toDir);
        let init = {
            method: 'POST',
            body: JSON.stringify({ copy_from: fromFile })
        };
        return __1.ServerConnection.makeRequest(url, init, settings)
            .then(response => {
            if (response.status !== 201) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            return response.json();
        })
            .then(data => {
            validate.validateContentsModel(data);
            this._fileChanged.emit({
                type: 'new',
                oldValue: null,
                newValue: data
            });
            return data;
        });
    }
    /**
     * Create a checkpoint for a file.
     *
     * @param localPath - The path of the file.
     *
     * @returns A promise which resolves with the new checkpoint model when the
     *   checkpoint is created.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/contents) and validates the response model.
     */
    createCheckpoint(localPath) {
        let url = this._getUrl(localPath, 'checkpoints');
        let init = { method: 'POST' };
        return __1.ServerConnection.makeRequest(url, init, this.serverSettings)
            .then(response => {
            if (response.status !== 201) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            return response.json();
        })
            .then(data => {
            validate.validateCheckpointModel(data);
            return data;
        });
    }
    /**
     * List available checkpoints for a file.
     *
     * @param localPath - The path of the file.
     *
     * @returns A promise which resolves with a list of checkpoint models for
     *    the file.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/contents) and validates the response model.
     */
    listCheckpoints(localPath) {
        let url = this._getUrl(localPath, 'checkpoints');
        return __1.ServerConnection.makeRequest(url, {}, this.serverSettings)
            .then(response => {
            if (response.status !== 200) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            return response.json();
        })
            .then(data => {
            if (!Array.isArray(data)) {
                throw new Error('Invalid Checkpoint list');
            }
            for (let i = 0; i < data.length; i++) {
                validate.validateCheckpointModel(data[i]);
            }
            return data;
        });
    }
    /**
     * Restore a file to a known checkpoint state.
     *
     * @param localPath - The path of the file.
     *
     * @param checkpointID - The id of the checkpoint to restore.
     *
     * @returns A promise which resolves when the checkpoint is restored.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/contents).
     */
    restoreCheckpoint(localPath, checkpointID) {
        let url = this._getUrl(localPath, 'checkpoints', checkpointID);
        let init = { method: 'POST' };
        return __1.ServerConnection.makeRequest(url, init, this.serverSettings).then(response => {
            if (response.status !== 204) {
                throw new __1.ServerConnection.ResponseError(response);
            }
        });
    }
    /**
     * Delete a checkpoint for a file.
     *
     * @param localPath - The path of the file.
     *
     * @param checkpointID - The id of the checkpoint to delete.
     *
     * @returns A promise which resolves when the checkpoint is deleted.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/contents).
     */
    deleteCheckpoint(localPath, checkpointID) {
        let url = this._getUrl(localPath, 'checkpoints', checkpointID);
        let init = { method: 'DELETE' };
        return __1.ServerConnection.makeRequest(url, init, this.serverSettings).then(response => {
            if (response.status !== 204) {
                throw new __1.ServerConnection.ResponseError(response);
            }
        });
    }
    /**
     * Get a REST url for a file given a path.
     */
    _getUrl(...args) {
        let parts = args.map(path => coreutils_1.URLExt.encodeParts(path));
        let baseUrl = this.serverSettings.baseUrl;
        return coreutils_1.URLExt.join(baseUrl, this._apiEndpoint, ...parts);
    }
}
exports.Drive = Drive;
/**
 * A namespace for module private data.
 */
var Private;
(function (Private) {
    /**
     * Normalize a file extension to be of the type `'.foo'`.
     *
     * Adds a leading dot if not present and converts to lower case.
     */
    function normalizeExtension(extension) {
        if (extension.length > 0 && extension.indexOf('.') !== 0) {
            extension = `.${extension}`;
        }
        return extension;
    }
    Private.normalizeExtension = normalizeExtension;
    /**
     * Normalize a global path. Reduces '..' and '.' parts, and removes
     * leading slashes from the local part of the path, while retaining
     * the drive name if it exists.
     */
    function normalize(path) {
        const parts = path.split(':');
        if (parts.length === 1) {
            return coreutils_1.PathExt.normalize(path);
        }
        return `${parts[0]}:${coreutils_1.PathExt.normalize(parts.slice(1).join(':'))}`;
    }
    Private.normalize = normalize;
})(Private || (Private = {}));


/***/ }),

/***/ "/KN4":
/*!*********************************************************************!*\
  !*** ./node_modules/@jupyterlab/filebrowser-extension/lib/index.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const application_1 = __webpack_require__(/*! @jupyterlab/application */ "FkFl");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const docmanager_1 = __webpack_require__(/*! @jupyterlab/docmanager */ "kL29");
const filebrowser_1 = __webpack_require__(/*! @jupyterlab/filebrowser */ "my6z");
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
/**
 * The command IDs used by the file browser plugin.
 */
var CommandIDs;
(function (CommandIDs) {
    CommandIDs.copy = 'filebrowser:copy';
    CommandIDs.copyDownloadLink = 'filebrowser:copy-download-link';
    // For main browser only.
    CommandIDs.createLauncher = 'filebrowser:create-main-launcher';
    CommandIDs.cut = 'filebrowser:cut';
    CommandIDs.del = 'filebrowser:delete';
    CommandIDs.download = 'filebrowser:download';
    CommandIDs.duplicate = 'filebrowser:duplicate';
    // For main browser only.
    CommandIDs.hideBrowser = 'filebrowser:hide-main';
    CommandIDs.navigate = 'filebrowser:navigate';
    CommandIDs.open = 'filebrowser:open';
    CommandIDs.openBrowserTab = 'filebrowser:open-browser-tab';
    CommandIDs.paste = 'filebrowser:paste';
    CommandIDs.rename = 'filebrowser:rename';
    // For main browser only.
    CommandIDs.share = 'filebrowser:share-main';
    // For main browser only.
    CommandIDs.copyPath = 'filebrowser:copy-path';
    CommandIDs.showBrowser = 'filebrowser:activate';
    CommandIDs.shutdown = 'filebrowser:shutdown';
    // For main browser only.
    CommandIDs.toggleBrowser = 'filebrowser:toggle-main';
})(CommandIDs || (CommandIDs = {}));
/**
 * The default file browser extension.
 */
const browser = {
    activate: activateBrowser,
    id: '@jupyterlab/filebrowser-extension:browser',
    requires: [filebrowser_1.IFileBrowserFactory, application_1.ILayoutRestorer],
    autoStart: true
};
/**
 * The default file browser factory provider.
 */
const factory = {
    activate: activateFactory,
    id: '@jupyterlab/filebrowser-extension:factory',
    provides: filebrowser_1.IFileBrowserFactory,
    requires: [docmanager_1.IDocumentManager, coreutils_1.IStateDB]
};
/**
 * The file browser namespace token.
 */
const namespace = 'filebrowser';
/**
 * Export the plugins as default.
 */
const plugins = [factory, browser];
exports.default = plugins;
/**
 * Activate the file browser factory provider.
 */
function activateFactory(app, docManager, state) {
    const { commands } = app;
    const tracker = new apputils_1.InstanceTracker({ namespace });
    const createFileBrowser = (id, options = {}) => {
        const model = new filebrowser_1.FileBrowserModel({
            manager: docManager,
            driveName: options.driveName || '',
            refreshInterval: options.refreshInterval,
            state: options.state === null ? null : options.state || state
        });
        const widget = new filebrowser_1.FileBrowser({
            id,
            model,
            commands: options.commands || commands
        });
        // Add a launcher toolbar item.
        let launcher = new apputils_1.ToolbarButton({
            iconClassName: 'jp-AddIcon jp-Icon jp-Icon-16',
            onClick: () => {
                return createLauncher(commands, widget);
            },
            tooltip: 'New Launcher'
        });
        widget.toolbar.insertItem(0, 'launch', launcher);
        // Track the newly created file browser.
        tracker.add(widget);
        return widget;
    };
    const defaultBrowser = createFileBrowser('filebrowser');
    return { createFileBrowser, defaultBrowser, tracker };
}
/**
 * Activate the default file browser in the sidebar.
 */
function activateBrowser(app, factory, restorer) {
    const browser = factory.defaultBrowser;
    const { commands, shell } = app;
    // Let the application restorer track the primary file browser (that is
    // automatically created) for restoration of application state (e.g. setting
    // the file browser as the current side bar widget).
    //
    // All other file browsers created by using the factory function are
    // responsible for their own restoration behavior, if any.
    restorer.add(browser, namespace);
    addCommands(app, factory.tracker, browser);
    browser.title.iconClass = 'jp-FolderIcon jp-SideBar-tabIcon';
    browser.title.caption = 'File Browser';
    shell.addToLeftArea(browser, { rank: 100 });
    // If the layout is a fresh session without saved data, open file browser.
    app.restored.then(layout => {
        if (layout.fresh) {
            commands.execute(CommandIDs.showBrowser, void 0);
        }
    });
    Promise.all([app.restored, browser.model.restored]).then(() => {
        function maybeCreate() {
            // Create a launcher if there are no open items.
            if (app.shell.isEmpty('main')) {
                createLauncher(commands, browser);
            }
        }
        // When layout is modified, create a launcher if there are no open items.
        shell.layoutModified.connect(() => {
            maybeCreate();
        });
        maybeCreate();
    });
}
/**
 * Add the main file browser commands to the application's command registry.
 */
function addCommands(app, tracker, browser) {
    const registry = app.docRegistry;
    const getBrowserForPath = (path) => {
        const driveName = app.serviceManager.contents.driveName(path);
        if (driveName) {
            let browserForPath = tracker.find(fb => fb.model.driveName === driveName);
            if (!browserForPath) {
                // warn that no filebrowser could be found for this driveName
                console.warn(`${CommandIDs.navigate} failed to find filebrowser for path: ${path}`);
                return;
            }
            return browserForPath;
        }
        // if driveName is empty, assume the main filebrowser
        return browser;
    };
    const { commands } = app;
    commands.addCommand(CommandIDs.del, {
        execute: () => {
            const widget = tracker.currentWidget;
            if (widget) {
                return widget.delete();
            }
        },
        iconClass: 'jp-MaterialIcon jp-CloseIcon',
        label: 'Delete',
        mnemonic: 0
    });
    commands.addCommand(CommandIDs.copy, {
        execute: () => {
            const widget = tracker.currentWidget;
            if (widget) {
                return widget.copy();
            }
        },
        iconClass: 'jp-MaterialIcon jp-CopyIcon',
        label: 'Copy',
        mnemonic: 0
    });
    commands.addCommand(CommandIDs.cut, {
        execute: () => {
            const widget = tracker.currentWidget;
            if (widget) {
                return widget.cut();
            }
        },
        iconClass: 'jp-MaterialIcon jp-CutIcon',
        label: 'Cut'
    });
    commands.addCommand(CommandIDs.download, {
        execute: () => {
            const widget = tracker.currentWidget;
            if (widget) {
                return widget.download();
            }
        },
        iconClass: 'jp-MaterialIcon jp-DownloadIcon',
        label: 'Download'
    });
    commands.addCommand(CommandIDs.duplicate, {
        execute: () => {
            const widget = tracker.currentWidget;
            if (widget) {
                return widget.duplicate();
            }
        },
        iconClass: 'jp-MaterialIcon jp-CopyIcon',
        label: 'Duplicate'
    });
    commands.addCommand(CommandIDs.hideBrowser, {
        execute: () => {
            const widget = tracker.currentWidget;
            if (widget && !widget.isHidden) {
                app.shell.collapseLeft();
            }
        }
    });
    commands.addCommand(CommandIDs.navigate, {
        execute: args => {
            const path = args.path || '';
            const browserForPath = getBrowserForPath(path);
            const services = app.serviceManager;
            const localPath = services.contents.localPath(path);
            const failure = (reason) => {
                console.warn(`${CommandIDs.navigate} failed to open: ${path}`, reason);
            };
            return services.ready
                .then(() => services.contents.get(path))
                .then(value => {
                const { model } = browserForPath;
                const { restored } = model;
                if (value.type === 'directory') {
                    return restored.then(() => model.cd(`/${localPath}`));
                }
                return restored
                    .then(() => model.cd(`/${coreutils_1.PathExt.dirname(localPath)}`))
                    .then(() => commands.execute('docmanager:open', { path: path }));
            })
                .catch(failure);
        }
    });
    commands.addCommand(CommandIDs.open, {
        execute: args => {
            const factory = args['factory'] || void 0;
            const widget = tracker.currentWidget;
            if (!widget) {
                return;
            }
            return Promise.all(algorithm_1.toArray(algorithm_1.map(widget.selectedItems(), item => {
                if (item.type === 'directory') {
                    return widget.model.cd(item.name);
                }
                return commands.execute('docmanager:open', {
                    factory: factory,
                    path: item.path
                });
            })));
        },
        iconClass: args => {
            const factory = args['factory'] || void 0;
            if (factory) {
                // if an explicit factory is passed...
                const ft = registry.getFileType(factory);
                if (ft) {
                    // ...set an icon if the factory name corresponds to a file type name...
                    return ft.iconClass;
                }
                else {
                    // ...or leave the icon blank
                    return '';
                }
            }
            else {
                return 'jp-MaterialIcon jp-OpenFolderIcon';
            }
        },
        label: args => (args['label'] || args['factory'] || 'Open'),
        mnemonic: 0
    });
    commands.addCommand(CommandIDs.openBrowserTab, {
        execute: () => {
            const widget = tracker.currentWidget;
            if (!widget) {
                return;
            }
            return Promise.all(algorithm_1.toArray(algorithm_1.map(widget.selectedItems(), item => {
                return commands.execute('docmanager:open-browser-tab', {
                    path: item.path
                });
            })));
        },
        iconClass: 'jp-MaterialIcon jp-AddIcon',
        label: 'Open in New Browser Tab',
        mnemonic: 0
    });
    commands.addCommand(CommandIDs.copyDownloadLink, {
        execute: () => {
            const widget = tracker.currentWidget;
            if (!widget) {
                return;
            }
            return widget.model.manager.services.contents
                .getDownloadUrl(widget.selectedItems().next().path)
                .then(url => {
                apputils_1.Clipboard.copyToSystem(url);
            });
        },
        iconClass: 'jp-MaterialIcon jp-CopyIcon',
        label: 'Copy Download Link',
        mnemonic: 0
    });
    commands.addCommand(CommandIDs.paste, {
        execute: () => {
            const widget = tracker.currentWidget;
            if (widget) {
                return widget.paste();
            }
        },
        iconClass: 'jp-MaterialIcon jp-PasteIcon',
        label: 'Paste',
        mnemonic: 0
    });
    commands.addCommand(CommandIDs.rename, {
        execute: args => {
            const widget = tracker.currentWidget;
            if (widget) {
                return widget.rename();
            }
        },
        iconClass: 'jp-MaterialIcon jp-EditIcon',
        label: 'Rename',
        mnemonic: 0
    });
    commands.addCommand(CommandIDs.share, {
        execute: () => {
            const widget = tracker.currentWidget;
            if (!widget) {
                return;
            }
            const path = encodeURI(widget.selectedItems().next().path);
            const tree = coreutils_1.PageConfig.getTreeUrl({ workspace: true });
            apputils_1.Clipboard.copyToSystem(coreutils_1.URLExt.join(tree, path));
        },
        isVisible: () => tracker.currentWidget &&
            algorithm_1.toArray(tracker.currentWidget.selectedItems()).length === 1,
        iconClass: 'jp-MaterialIcon jp-LinkIcon',
        label: 'Copy Shareable Link'
    });
    commands.addCommand(CommandIDs.copyPath, {
        execute: () => {
            const widget = tracker.currentWidget;
            if (!widget) {
                return;
            }
            const item = widget.selectedItems().next();
            if (!item) {
                return;
            }
            apputils_1.Clipboard.copyToSystem(item.path);
        },
        isVisible: () => tracker.currentWidget &&
            tracker.currentWidget.selectedItems().next !== undefined,
        iconClass: 'jp-MaterialIcon jp-FileIcon',
        label: 'Copy Path'
    });
    commands.addCommand(CommandIDs.showBrowser, {
        execute: args => {
            const path = args.path || '';
            const browserForPath = getBrowserForPath(path);
            // Check for browser not found
            if (!browserForPath) {
                return;
            }
            // Shortcut if we are using the main file browser
            if (browser === browserForPath) {
                app.shell.activateById(browser.id);
                return;
            }
            else {
                const areas = ['left', 'right'];
                for (let area of areas) {
                    const it = app.shell.widgets(area);
                    let widget = it.next();
                    while (widget) {
                        if (widget.contains(browserForPath)) {
                            app.shell.activateById(widget.id);
                            return;
                        }
                        widget = it.next();
                    }
                }
            }
        }
    });
    commands.addCommand(CommandIDs.shutdown, {
        execute: () => {
            const widget = tracker.currentWidget;
            if (widget) {
                return widget.shutdownKernels();
            }
        },
        iconClass: 'jp-MaterialIcon jp-StopIcon',
        label: 'Shutdown Kernel'
    });
    commands.addCommand(CommandIDs.toggleBrowser, {
        execute: () => {
            if (browser.isHidden) {
                return commands.execute(CommandIDs.showBrowser, void 0);
            }
            return commands.execute(CommandIDs.hideBrowser, void 0);
        }
    });
    commands.addCommand(CommandIDs.createLauncher, {
        label: 'New Launcher',
        execute: () => createLauncher(commands, browser)
    });
    /**
     * A menu widget that dynamically populates with different widget factories
     * based on current filebrowser selection.
     */
    class OpenWithMenu extends widgets_1.Menu {
        onBeforeAttach(msg) {
            // clear the current menu items
            this.clearItems();
            // get the widget factories that could be used to open all of the items
            // in the current filebrowser selection
            let factories = OpenWithMenu._intersection(algorithm_1.map(tracker.currentWidget.selectedItems(), i => {
                return OpenWithMenu._getFactories(i);
            }));
            if (factories) {
                // make new menu items from the widget factories
                factories.forEach(factory => {
                    this.addItem({
                        args: { factory: factory },
                        command: CommandIDs.open
                    });
                });
            }
            super.onBeforeAttach(msg);
        }
        static _getFactories(item) {
            let factories = registry
                .preferredWidgetFactories(item.path)
                .map(f => f.name);
            const notebookFactory = registry.getWidgetFactory('notebook').name;
            if (item.type === 'notebook' &&
                factories.indexOf(notebookFactory) === -1) {
                factories.unshift(notebookFactory);
            }
            return factories;
        }
        static _intersection(iter) {
            // pop the first element of iter
            let first = iter.next();
            // first will be undefined if iter is empty
            if (!first) {
                return;
            }
            // "initialize" the intersection from first
            let isect = new Set(first);
            // reduce over the remaining elements of iter
            return algorithm_1.reduce(iter, (isect, subarr) => {
                // filter out all elements not present in both isect and subarr,
                // accumulate result in new set
                return new Set(subarr.filter(x => isect.has(x)));
            }, isect);
        }
    }
    // matches anywhere on filebrowser
    const selectorContent = '.jp-DirListing-content';
    // matches all filebrowser items
    const selectorItem = '.jp-DirListing-item[data-isdir]';
    // matches only non-directory items
    const selectorNotDir = '.jp-DirListing-item[data-isdir="false"]';
    // If the user did not click on any file, we still want to show paste,
    // so target the content rather than an item.
    app.contextMenu.addItem({
        command: CommandIDs.paste,
        selector: selectorContent,
        rank: 1
    });
    app.contextMenu.addItem({
        command: CommandIDs.open,
        selector: selectorItem,
        rank: 1
    });
    const openWith = new OpenWithMenu({ commands });
    openWith.title.label = 'Open With';
    app.contextMenu.addItem({
        type: 'submenu',
        submenu: openWith,
        selector: selectorNotDir,
        rank: 2
    });
    app.contextMenu.addItem({
        command: CommandIDs.openBrowserTab,
        selector: selectorNotDir,
        rank: 3
    });
    app.contextMenu.addItem({
        command: CommandIDs.rename,
        selector: selectorItem,
        rank: 4
    });
    app.contextMenu.addItem({
        command: CommandIDs.del,
        selector: selectorItem,
        rank: 5
    });
    app.contextMenu.addItem({
        command: CommandIDs.cut,
        selector: selectorItem,
        rank: 6
    });
    app.contextMenu.addItem({
        command: CommandIDs.copy,
        selector: selectorNotDir,
        rank: 7
    });
    app.contextMenu.addItem({
        command: CommandIDs.duplicate,
        selector: selectorNotDir,
        rank: 9
    });
    app.contextMenu.addItem({
        command: CommandIDs.download,
        selector: selectorNotDir,
        rank: 10
    });
    app.contextMenu.addItem({
        command: CommandIDs.shutdown,
        selector: selectorNotDir,
        rank: 11
    });
    app.contextMenu.addItem({
        command: CommandIDs.share,
        selector: selectorItem,
        rank: 12
    });
    app.contextMenu.addItem({
        command: CommandIDs.copyPath,
        selector: selectorItem,
        rank: 13
    });
    app.contextMenu.addItem({
        command: CommandIDs.copyDownloadLink,
        selector: selectorItem,
        rank: 14
    });
}
/**
 * Create a launcher for a given filebrowser widget.
 */
function createLauncher(commands, browser) {
    const { model } = browser;
    return commands
        .execute('launcher:create', { cwd: model.path })
        .then((launcher) => {
        model.pathChanged.connect(() => {
            launcher.content.cwd = model.path;
        }, launcher);
        return launcher;
    });
}


/***/ }),

/***/ "/MSg":
/*!*************************************************************************!*\
  !*** ./node_modules/font-awesome/fonts/fontawesome-webfont.eot?v=4.7.0 ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__.p + "674f50d287a8c48dc19ba404d20fe713.eot";

/***/ }),

/***/ "/PhR":
/*!************************************************************!*\
  !*** ./node_modules/@jupyterlab/imageviewer/lib/widget.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const docregistry_1 = __webpack_require__(/*! @jupyterlab/docregistry */ "jTF0");
const coreutils_2 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
/**
 * The class name added to a imageviewer.
 */
const IMAGE_CLASS = 'jp-ImageViewer';
/**
 * A widget for images.
 */
class ImageViewer extends widgets_1.Widget {
    /**
     * Construct a new image widget.
     */
    constructor(context) {
        super();
        this._scale = 1;
        this._matrix = [1, 0, 0, 1];
        this._colorinversion = 0;
        this._ready = new coreutils_2.PromiseDelegate();
        this.context = context;
        this.node.tabIndex = -1;
        this.addClass(IMAGE_CLASS);
        this._img = document.createElement('img');
        this.node.appendChild(this._img);
        this._onTitleChanged();
        context.pathChanged.connect(this._onTitleChanged, this);
        context.ready.then(() => {
            if (this.isDisposed) {
                return;
            }
            const contents = context.contentsModel;
            this._format = contents.format === 'base64' ? ';base64' : '';
            this._mimeType = contents.mimetype;
            this._render();
            context.model.contentChanged.connect(this.update, this);
            context.fileChanged.connect(this.update, this);
            this._ready.resolve(void 0);
        });
    }
    /**
     * A promise that resolves when the image viewer is ready.
     */
    get ready() {
        return this._ready.promise;
    }
    /**
     * The scale factor for the image.
     */
    get scale() {
        return this._scale;
    }
    set scale(value) {
        if (value === this._scale) {
            return;
        }
        this._scale = value;
        this._updateStyle();
    }
    /**
     * The color inversion of the image.
     */
    get colorinversion() {
        return this._colorinversion;
    }
    set colorinversion(value) {
        if (value === this._colorinversion) {
            return;
        }
        this._colorinversion = value;
        this._updateStyle();
    }
    /**
     * Reset rotation and flip transformations.
     */
    resetRotationFlip() {
        this._matrix = [1, 0, 0, 1];
        this._updateStyle();
    }
    /**
     * Rotate the image counter-clockwise (left).
     */
    rotateCounterclockwise() {
        this._matrix = Private.prod(this._matrix, Private.rotateCounterclockwiseMatrix);
        this._updateStyle();
    }
    /**
     * Rotate the image clockwise (right).
     */
    rotateClockwise() {
        this._matrix = Private.prod(this._matrix, Private.rotateClockwiseMatrix);
        this._updateStyle();
    }
    /**
     * Flip the image horizontally.
     */
    flipHorizontal() {
        this._matrix = Private.prod(this._matrix, Private.flipHMatrix);
        this._updateStyle();
    }
    /**
     * Flip the image vertically.
     */
    flipVertical() {
        this._matrix = Private.prod(this._matrix, Private.flipVMatrix);
        this._updateStyle();
    }
    /**
     * Handle `update-request` messages for the widget.
     */
    onUpdateRequest(msg) {
        if (this.isDisposed || !this.context.isReady) {
            return;
        }
        this._render();
    }
    /**
     * Handle `'activate-request'` messages.
     */
    onActivateRequest(msg) {
        this.node.focus();
    }
    /**
     * Handle a change to the title.
     */
    _onTitleChanged() {
        this.title.label = coreutils_1.PathExt.basename(this.context.localPath);
    }
    /**
     * Render the widget content.
     */
    _render() {
        let context = this.context;
        let cm = context.contentsModel;
        if (!cm) {
            return;
        }
        let content = context.model.toString();
        this._img.src = `data:${this._mimeType}${this._format},${content}`;
    }
    /**
     * Update the image CSS style, including the transform and filter.
     */
    _updateStyle() {
        let [a, b, c, d] = this._matrix;
        let [tX, tY] = Private.prodVec(this._matrix, [1, 1]);
        let transform = `matrix(${a}, ${b}, ${c}, ${d}, 0, 0) translate(${tX < 0 ? -100 : 0}%, ${tY < 0 ? -100 : 0}%) `;
        this._img.style.transform = `scale(${this._scale}) ${transform}`;
        this._img.style.filter = `invert(${this._colorinversion})`;
    }
}
exports.ImageViewer = ImageViewer;
/**
 * A widget factory for images.
 */
class ImageViewerFactory extends docregistry_1.ABCWidgetFactory {
    /**
     * Create a new widget given a context.
     */
    createNewWidget(context) {
        const content = new ImageViewer(context);
        const widget = new docregistry_1.DocumentWidget({ content, context });
        return widget;
    }
}
exports.ImageViewerFactory = ImageViewerFactory;
/**
 * A namespace for image widget private data.
 */
var Private;
(function (Private) {
    /**
     * Multiply 2x2 matrices.
     */
    function prod([a11, a12, a21, a22], [b11, b12, b21, b22]) {
        return [
            a11 * b11 + a12 * b21,
            a11 * b12 + a12 * b22,
            a21 * b11 + a22 * b21,
            a21 * b12 + a22 * b22
        ];
    }
    Private.prod = prod;
    /**
     * Multiply a 2x2 matrix and a 2x1 vector.
     */
    function prodVec([a11, a12, a21, a22], [b1, b2]) {
        return [a11 * b1 + a12 * b2, a21 * b1 + a22 * b2];
    }
    Private.prodVec = prodVec;
    /**
     * Clockwise rotation transformation matrix.
     */
    Private.rotateClockwiseMatrix = [0, 1, -1, 0];
    /**
     * Counter-clockwise rotation transformation matrix.
     */
    Private.rotateCounterclockwiseMatrix = [0, -1, 1, 0];
    /**
     * Horizontal flip transformation matrix.
     */
    Private.flipHMatrix = [-1, 0, 0, 1];
    /**
     * Vertical flip transformation matrix.
     */
    Private.flipVMatrix = [1, 0, 0, -1];
})(Private || (Private = {}));


/***/ }),

/***/ "/VUM":
/*!*************************************************************!*\
  !*** ./node_modules/@jupyterlab/rendermime/lib/registry.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const coreutils_2 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const mimemodel_1 = __webpack_require__(/*! ./mimemodel */ "qXhn");
/* tslint:disable */
/**
 * The rendermime token.
 */
exports.IRenderMimeRegistry = new coreutils_2.Token('@jupyterlab/rendermime:IRenderMimeRegistry');
/* tslint:enable */
/* tslint:disable */
/**
 * The latex typesetter token.
 */
exports.ILatexTypesetter = new coreutils_2.Token('@jupyterlab/rendermime:ILatexTypesetter');
/* tslint:enable */
/**
 * An object which manages mime renderer factories.
 *
 * This object is used to render mime models using registered mime
 * renderers, selecting the preferred mime renderer to render the
 * model into a widget.
 *
 * #### Notes
 * This class is not intended to be subclassed.
 */
class RenderMimeRegistry {
    /**
     * Construct a new rendermime.
     *
     * @param options - The options for initializing the instance.
     */
    constructor(options = {}) {
        this._id = 0;
        this._ranks = {};
        this._types = null;
        this._factories = {};
        // Parse the options.
        this.resolver = options.resolver || null;
        this.linkHandler = options.linkHandler || null;
        this.latexTypesetter = options.latexTypesetter || null;
        this.sanitizer = options.sanitizer || apputils_1.defaultSanitizer;
        // Add the initial factories.
        if (options.initialFactories) {
            for (let factory of options.initialFactories) {
                this.addFactory(factory);
            }
        }
    }
    /**
     * The ordered list of mimeTypes.
     */
    get mimeTypes() {
        return this._types || (this._types = Private.sortedTypes(this._ranks));
    }
    /**
     * Find the preferred mime type for a mime bundle.
     *
     * @param bundle - The bundle of mime data.
     *
     * @param safe - How to consider safe/unsafe factories. If 'ensure',
     *   it will only consider safe factories. If 'any', any factory will be
     *   considered. If 'prefer', unsafe factories will be considered, but
     *   only after the safe options have been exhausted.
     *
     * @returns The preferred mime type from the available factories,
     *   or `undefined` if the mime type cannot be rendered.
     */
    preferredMimeType(bundle, safe = 'ensure') {
        // Try to find a safe factory first, if preferred.
        if (safe === 'ensure' || safe === 'prefer') {
            for (let mt of this.mimeTypes) {
                if (mt in bundle && this._factories[mt].safe) {
                    return mt;
                }
            }
        }
        if (safe !== 'ensure') {
            // Otherwise, search for the best factory among all factories.
            for (let mt of this.mimeTypes) {
                if (mt in bundle) {
                    return mt;
                }
            }
        }
        // Otherwise, no matching mime type exists.
        return undefined;
    }
    /**
     * Create a renderer for a mime type.
     *
     * @param mimeType - The mime type of interest.
     *
     * @returns A new renderer for the given mime type.
     *
     * @throws An error if no factory exists for the mime type.
     */
    createRenderer(mimeType) {
        // Throw an error if no factory exists for the mime type.
        if (!(mimeType in this._factories)) {
            throw new Error(`No factory for mime type: '${mimeType}'`);
        }
        // Invoke the best factory for the given mime type.
        return this._factories[mimeType].createRenderer({
            mimeType,
            resolver: this.resolver,
            sanitizer: this.sanitizer,
            linkHandler: this.linkHandler,
            latexTypesetter: this.latexTypesetter
        });
    }
    /**
     * Create a new mime model.  This is a convenience method.
     *
     * @options - The options used to create the model.
     *
     * @returns A new mime model.
     */
    createModel(options = {}) {
        return new mimemodel_1.MimeModel(options);
    }
    /**
     * Create a clone of this rendermime instance.
     *
     * @param options - The options for configuring the clone.
     *
     * @returns A new independent clone of the rendermime.
     */
    clone(options = {}) {
        // Create the clone.
        let clone = new RenderMimeRegistry({
            resolver: options.resolver || this.resolver || undefined,
            sanitizer: options.sanitizer || this.sanitizer || undefined,
            linkHandler: options.linkHandler || this.linkHandler || undefined,
            latexTypesetter: options.latexTypesetter || this.latexTypesetter
        });
        // Clone the internal state.
        clone._factories = Object.assign({}, this._factories);
        clone._ranks = Object.assign({}, this._ranks);
        clone._id = this._id;
        // Return the cloned object.
        return clone;
    }
    /**
     * Get the renderer factory registered for a mime type.
     *
     * @param mimeType - The mime type of interest.
     *
     * @returns The factory for the mime type, or `undefined`.
     */
    getFactory(mimeType) {
        return this._factories[mimeType];
    }
    /**
     * Add a renderer factory to the rendermime.
     *
     * @param factory - The renderer factory of interest.
     *
     * @param rank - The rank of the renderer. A lower rank indicates
     *   a higher priority for rendering. If not given, the rank will
     *   defer to the `defaultRank` of the factory.  If no `defaultRank`
     *   is given, it will default to 100.
     *
     * #### Notes
     * The renderer will replace an existing renderer for the given
     * mimeType.
     */
    addFactory(factory, rank) {
        if (rank === undefined) {
            rank = factory.defaultRank;
            if (rank === undefined) {
                rank = 100;
            }
        }
        for (let mt of factory.mimeTypes) {
            this._factories[mt] = factory;
            this._ranks[mt] = { rank, id: this._id++ };
        }
        this._types = null;
    }
    /**
     * Remove a mime type.
     *
     * @param mimeType - The mime type of interest.
     */
    removeMimeType(mimeType) {
        delete this._factories[mimeType];
        delete this._ranks[mimeType];
        this._types = null;
    }
    /**
     * Get the rank for a given mime type.
     *
     * @param mimeType - The mime type of interest.
     *
     * @returns The rank of the mime type or undefined.
     */
    getRank(mimeType) {
        let rank = this._ranks[mimeType];
        return rank && rank.rank;
    }
    /**
     * Set the rank of a given mime type.
     *
     * @param mimeType - The mime type of interest.
     *
     * @param rank - The new rank to assign.
     *
     * #### Notes
     * This is a no-op if the mime type is not registered.
     */
    setRank(mimeType, rank) {
        if (!this._ranks[mimeType]) {
            return;
        }
        let id = this._id++;
        this._ranks[mimeType] = { rank, id };
        this._types = null;
    }
}
exports.RenderMimeRegistry = RenderMimeRegistry;
/**
 * The namespace for `RenderMimeRegistry` class statics.
 */
(function (RenderMimeRegistry) {
    /**
     * A default resolver that uses a session and a contents manager.
     */
    class UrlResolver {
        /**
         * Create a new url resolver for a console.
         */
        constructor(options) {
            this._session = options.session;
            this._contents = options.contents;
        }
        /**
         * Resolve a relative url to an absolute url path.
         */
        resolveUrl(url) {
            if (this.isLocal(url)) {
                const cwd = encodeURI(coreutils_1.PathExt.dirname(this._session.path));
                url = coreutils_1.PathExt.resolve(cwd, url);
            }
            return Promise.resolve(url);
        }
        /**
         * Get the download url of a given absolute url path.
         */
        getDownloadUrl(url) {
            if (this.isLocal(url)) {
                // decode url->path before passing to contents api
                return this._contents.getDownloadUrl(decodeURI(url));
            }
            return Promise.resolve(url);
        }
        /**
         * Whether the URL should be handled by the resolver
         * or not.
         *
         * #### Notes
         * This is similar to the `isLocal` check in `URLExt`,
         * but it also checks whether the path points to any
         * of the `IDrive`s that may be registered with the contents
         * manager.
         */
        isLocal(url) {
            const path = decodeURI(url);
            return coreutils_1.URLExt.isLocal(url) || !!this._contents.driveName(path);
        }
    }
    RenderMimeRegistry.UrlResolver = UrlResolver;
})(RenderMimeRegistry = exports.RenderMimeRegistry || (exports.RenderMimeRegistry = {}));
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * Get the mime types in the map, ordered by rank.
     */
    function sortedTypes(map) {
        return Object.keys(map).sort((a, b) => {
            let p1 = map[a];
            let p2 = map[b];
            if (p1.rank !== p2.rank) {
                return p1.rank - p2.rank;
            }
            return p1.id - p2.id;
        });
    }
    Private.sortedTypes = sortedTypes;
})(Private || (Private = {}));


/***/ }),

/***/ "/X5v":
/*!************************************************!*\
  !*** ./node_modules/moment/locale/x-pseudo.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var xPseudo = moment.defineLocale('x-pseudo', {
    months : 'J~áñúá~rý_F~ébrú~árý_~Márc~h_Áp~ríl_~Máý_~Júñé~_Júl~ý_Áú~gúst~_Sép~témb~ér_Ó~ctób~ér_Ñ~óvém~bér_~Décé~mbér'.split('_'),
    monthsShort : 'J~áñ_~Féb_~Már_~Ápr_~Máý_~Júñ_~Júl_~Áúg_~Sép_~Óct_~Ñóv_~Déc'.split('_'),
    monthsParseExact : true,
    weekdays : 'S~úñdá~ý_Mó~ñdáý~_Túé~sdáý~_Wéd~ñésd~áý_T~húrs~dáý_~Fríd~áý_S~átúr~dáý'.split('_'),
    weekdaysShort : 'S~úñ_~Móñ_~Túé_~Wéd_~Thú_~Frí_~Sát'.split('_'),
    weekdaysMin : 'S~ú_Mó~_Tú_~Wé_T~h_Fr~_Sá'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd, D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay : '[T~ódá~ý át] LT',
        nextDay : '[T~ómó~rró~w át] LT',
        nextWeek : 'dddd [át] LT',
        lastDay : '[Ý~ést~érdá~ý át] LT',
        lastWeek : '[L~ást] dddd [át] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'í~ñ %s',
        past : '%s á~gó',
        s : 'á ~féw ~sécó~ñds',
        ss : '%d s~écóñ~ds',
        m : 'á ~míñ~úté',
        mm : '%d m~íñú~tés',
        h : 'á~ñ hó~úr',
        hh : '%d h~óúrs',
        d : 'á ~dáý',
        dd : '%d d~áýs',
        M : 'á ~móñ~th',
        MM : '%d m~óñt~hs',
        y : 'á ~ýéár',
        yy : '%d ý~éárs'
    },
    dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
    ordinal : function (number) {
        var b = number % 10,
            output = (~~(number % 100 / 10) === 1) ? 'th' :
            (b === 1) ? 'st' :
            (b === 2) ? 'nd' :
            (b === 3) ? 'rd' : 'th';
        return number + output;
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return xPseudo;

})));


/***/ }),

/***/ "/aXk":
/*!******************************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils/lib/instancetracker.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const properties_1 = __webpack_require__(/*! @phosphor/properties */ "3kwb");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
/**
 * A class that keeps track of widget instances on an Application shell.
 *
 * #### Notes
 * The API surface area of this concrete implementation is substantially larger
 * than the instance tracker interface it implements. The interface is intended
 * for export by JupyterLab plugins that create widgets and have clients who may
 * wish to keep track of newly created widgets. This class, however, can be used
 * internally by plugins to restore state as well.
 */
class InstanceTracker {
    /**
     * Create a new instance tracker.
     *
     * @param options - The instantiation options for an instance tracker.
     */
    constructor(options) {
        this._restore = null;
        this._tracker = new widgets_1.FocusTracker();
        this._currentChanged = new signaling_1.Signal(this);
        this._widgetAdded = new signaling_1.Signal(this);
        this._widgetUpdated = new signaling_1.Signal(this);
        this._widgets = [];
        this._currentWidget = null;
        this._isDisposed = false;
        this.namespace = options.namespace;
        this._tracker.currentChanged.connect(this._onCurrentChanged, this);
    }
    /**
     * A signal emitted when the current widget changes.
     */
    get currentChanged() {
        return this._currentChanged;
    }
    /**
     * A signal emitted when a widget is added.
     *
     * #### Notes
     * This signal will only fire when a widget is added to the tracker. It will
     * not fire if a widget is injected into the tracker.
     */
    get widgetAdded() {
        return this._widgetAdded;
    }
    /**
     * A signal emitted when a widget is updated.
     */
    get widgetUpdated() {
        return this._widgetUpdated;
    }
    /**
     * The current widget is the most recently focused or added widget.
     *
     * #### Notes
     * It is the most recently focused widget, or the most recently added
     * widget if no widget has taken focus.
     */
    get currentWidget() {
        return this._currentWidget;
    }
    /**
     * The number of widgets held by the tracker.
     */
    get size() {
        return this._tracker.widgets.length;
    }
    /**
     * Add a new widget to the tracker.
     *
     * @param widget - The widget being added.
     */
    add(widget) {
        if (this._tracker.has(widget)) {
            let warning = `${widget.id} already exists in the tracker.`;
            console.warn(warning);
            return Promise.reject(warning);
        }
        this._tracker.add(widget);
        this._widgets.push(widget);
        let injected = Private.injectedProperty.get(widget);
        let promise = Promise.resolve(void 0);
        if (injected) {
            return promise;
        }
        widget.disposed.connect(this._onWidgetDisposed, this);
        // Handle widget state restoration.
        if (this._restore) {
            let { state } = this._restore;
            let widgetName = this._restore.name(widget);
            if (widgetName) {
                let name = `${this.namespace}:${widgetName}`;
                let data = this._restore.args(widget);
                Private.nameProperty.set(widget, name);
                promise = state.save(name, { data });
            }
        }
        // If there is no focused widget, set this as the current widget.
        if (!this._tracker.currentWidget) {
            this._currentWidget = widget;
            this.onCurrentChanged(widget);
            this._currentChanged.emit(widget);
        }
        // Emit the widget added signal.
        this._widgetAdded.emit(widget);
        return promise;
    }
    /**
     * Test whether the tracker is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources held by the tracker.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        signaling_1.Signal.clearData(this);
        this._tracker.dispose();
    }
    /**
     * Find the first widget in the tracker that satisfies a filter function.
     *
     * @param - fn The filter function to call on each widget.
     *
     * #### Notes
     * If no widget is found, the value returned is `undefined`.
     */
    find(fn) {
        return algorithm_1.find(this._tracker.widgets, fn);
    }
    /**
     * Iterate through each widget in the tracker.
     *
     * @param fn - The function to call on each widget.
     */
    forEach(fn) {
        algorithm_1.each(this._tracker.widgets, widget => {
            fn(widget);
        });
    }
    /**
     * Filter the widgets in the tracker based on a predicate.
     *
     * @param fn - The function by which to filter.
     */
    filter(fn) {
        return this._tracker.widgets.filter(fn);
    }
    /**
     * Inject a foreign widget into the instance tracker.
     *
     * @param widget - The widget to inject into the tracker.
     *
     * #### Notes
     * Any widgets injected into an instance tracker will not have their state
     * saved by the tracker. The primary use case for widget injection is for a
     * plugin that offers a sub-class of an extant plugin to have its instances
     * share the same commands as the parent plugin (since most relevant commands
     * will use the `currentWidget` of the parent plugin's instance tracker). In
     * this situation, the sub-class plugin may well have its own instance tracker
     * for layout and state restoration in addition to injecting its widgets into
     * the parent plugin's instance tracker.
     */
    inject(widget) {
        Private.injectedProperty.set(widget, true);
        this.add(widget);
    }
    /**
     * Check if this tracker has the specified widget.
     *
     * @param widget - The widget whose existence is being checked.
     */
    has(widget) {
        return this._tracker.has(widget);
    }
    /**
     * Restore the widgets in this tracker's namespace.
     *
     * @param options - The configuration options that describe restoration.
     *
     * @returns A promise that resolves when restoration has completed.
     *
     * #### Notes
     * This function should almost never be invoked by client code. Its primary
     * use case is to be invoked by a layout restorer plugin that handles
     * multiple instance trackers and, when ready, asks them each to restore their
     * respective widgets.
     */
    restore(options) {
        const { command, registry, state, when } = options;
        const namespace = this.namespace;
        const promises = when
            ? [state.fetchNamespace(namespace)].concat(when)
            : [state.fetchNamespace(namespace)];
        this._restore = options;
        return Promise.all(promises).then(([saved]) => {
            return Promise.all(saved.map(item => {
                const { id, value } = item;
                const args = value && value.data;
                if (args === undefined) {
                    return state.remove(item.id);
                }
                // Execute the command and if it fails, delete the state restore data.
                return registry.execute(command, args).catch(() => state.remove(id));
            }));
        });
    }
    /**
     * Save the restore data for a given widget.
     *
     * @param widget - The widget being saved.
     */
    save(widget) {
        const injected = Private.injectedProperty.get(widget);
        if (!this._restore || !this.has(widget) || injected) {
            return;
        }
        const { state } = this._restore;
        const widgetName = this._restore.name(widget);
        const oldName = Private.nameProperty.get(widget);
        const newName = widgetName ? `${this.namespace}:${widgetName}` : '';
        if (oldName && oldName !== newName) {
            state.remove(oldName);
        }
        // Set the name property irrespective of whether the new name is null.
        Private.nameProperty.set(widget, newName);
        if (newName) {
            const data = this._restore.args(widget);
            state.save(newName, { data });
        }
        if (oldName !== newName) {
            this._widgetUpdated.emit(widget);
        }
    }
    /**
     * Handle the current change event.
     *
     * #### Notes
     * The default implementation is a no-op.
     */
    onCurrentChanged(value) {
        /* no-op */
    }
    /**
     * Handle the current change signal from the internal focus tracker.
     */
    _onCurrentChanged(sender, args) {
        // Bail if the active widget did not change.
        if (args.newValue === this._currentWidget) {
            return;
        }
        this._currentWidget = args.newValue;
        this.onCurrentChanged(args.newValue);
        this._currentChanged.emit(args.newValue);
    }
    /**
     * Clean up after disposed widgets.
     */
    _onWidgetDisposed(widget) {
        const injected = Private.injectedProperty.get(widget);
        if (injected) {
            return;
        }
        // Handle widget removal.
        algorithm_1.ArrayExt.removeFirstOf(this._widgets, widget);
        // Handle the current widget being disposed.
        if (widget === this._currentWidget) {
            this._currentWidget =
                this._tracker.currentWidget ||
                    this._widgets[this._widgets.length - 1] ||
                    null;
            this._currentChanged.emit(this._currentWidget);
            this.onCurrentChanged(this._currentWidget);
        }
        // If there is no restore data, return.
        if (!this._restore) {
            return;
        }
        const { state } = this._restore;
        const name = Private.nameProperty.get(widget);
        if (name) {
            state.remove(name);
        }
    }
}
exports.InstanceTracker = InstanceTracker;
/*
 * A namespace for private data.
 */
var Private;
(function (Private) {
    /**
     * An attached property to indicate whether a widget has been injected.
     */
    Private.injectedProperty = new properties_1.AttachedProperty({
        name: 'injected',
        create: () => false
    });
    /**
     * An attached property for a widget's ID in the state database.
     */
    Private.nameProperty = new properties_1.AttachedProperty({
        name: 'name',
        create: () => ''
    });
})(Private || (Private = {}));


/***/ }),

/***/ "/ab2":
/*!************************************************!*\
  !*** ./node_modules/browserify-aes/browser.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var ciphers = __webpack_require__(/*! ./encrypter */ "iUdu")
var deciphers = __webpack_require__(/*! ./decrypter */ "QihY")
var modes = __webpack_require__(/*! ./modes/list.json */ "6F8h")

function getCiphers () {
  return Object.keys(modes)
}

exports.createCipher = exports.Cipher = ciphers.createCipher
exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv
exports.createDecipher = exports.Decipher = deciphers.createDecipher
exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv
exports.listCiphers = exports.getCiphers = getCiphers


/***/ }),

/***/ "/ayr":
/*!***************************************!*\
  !*** ./node_modules/brorand/index.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var r;

module.exports = function rand(len) {
  if (!r)
    r = new Rand(null);

  return r.generate(len);
};

function Rand(rand) {
  this.rand = rand;
}
module.exports.Rand = Rand;

Rand.prototype.generate = function generate(len) {
  return this._rand(len);
};

// Emulate crypto API using randy
Rand.prototype._rand = function _rand(n) {
  if (this.rand.getBytes)
    return this.rand.getBytes(n);

  var res = new Uint8Array(n);
  for (var i = 0; i < res.length; i++)
    res[i] = this.rand.getByte();
  return res;
};

if (typeof self === 'object') {
  if (self.crypto && self.crypto.getRandomValues) {
    // Modern browsers
    Rand.prototype._rand = function _rand(n) {
      var arr = new Uint8Array(n);
      self.crypto.getRandomValues(arr);
      return arr;
    };
  } else if (self.msCrypto && self.msCrypto.getRandomValues) {
    // IE
    Rand.prototype._rand = function _rand(n) {
      var arr = new Uint8Array(n);
      self.msCrypto.getRandomValues(arr);
      return arr;
    };

  // Safari's WebWorkers do not have `crypto`
  } else if (typeof window === 'object') {
    // Old junk
    Rand.prototype._rand = function() {
      throw new Error('Not implemented yet');
    };
  }
} else {
  // Node.js or Web worker with no crypto support
  try {
    var crypto = __webpack_require__(/*! crypto */ 5);
    if (typeof crypto.randomBytes !== 'function')
      throw new Error('Not supported');

    Rand.prototype._rand = function _rand(n) {
      return crypto.randomBytes(n);
    };
  } catch (e) {
  }
}


/***/ }),

/***/ "/bma":
/*!****************************************************!*\
  !*** ./node_modules/mdi-react/ChevronRightIcon.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var ChevronRightIcon = function ChevronRightIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z' })
  );
};

module.exports = ChevronRightIcon;


/***/ }),

/***/ "/kYb":
/*!**********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TooltipBasicIcon.js ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TooltipBasicIcon = function TooltipBasicIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 24 16' }, props),
        _react2.default.createElement('path', { d: 'M6 2L0 8l6 5.991V14l18-.004V2H6z' })
    );
};

exports.default = TooltipBasicIcon;

/***/ }),

/***/ "/l3u":
/*!********************************************************************!*\
  !*** ./node_modules/@jupyterlab/plotly-extension/style/plotly.svg ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB3aWR0aD0iMjFweCIgaGVpZ2h0PSIyMHB4IiB2aWV3Qm94PSIwIDAgMjEgMjAiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CiAgICA8IS0tIEdlbmVyYXRvcjogU2tldGNoIDQyICgzNjc4MSkgLSBodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2ggLS0+CiAgICA8dGl0bGU+cGxvdGx5PC90aXRsZT4KICAgIDxkZXNjPkNyZWF0ZWQgd2l0aCBTa2V0Y2guPC9kZXNjPgogICAgPGRlZnM+PC9kZWZzPgogICAgPGcgaWQ9IlBhZ2UtMSIgc3Ryb2tlPSJub25lIiBzdHJva2Utd2lkdGg9IjEiIGZpbGw9Im5vbmUiIGZpbGwtcnVsZT0iZXZlbm9kZCI+CiAgICAgICAgPGcgaWQ9InBsb3RseSIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTIuMDAwMDAwLCAtMi4wMDAwMDApIj4KICAgICAgICAgICAgPGcgaWQ9Ikdyb3VwIj4KICAgICAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbD0iIzQ0N0FEQiIgZmlsbC1ydWxlPSJub256ZXJvIiB4PSIxOS45OTA1OTkiIHk9IjE5LjE4ODMwOTkiIHdpZHRoPSIyLjM2NDQ3NzE2IiBoZWlnaHQ9IjIuODAxMDc5ODEiPjwvcmVjdD4KICAgICAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbD0iIzQ0N0FEQiIgZmlsbC1ydWxlPSJub256ZXJvIiB4PSIxNy4wMzQ5OTQ5IiB5PSIxNi4yODU5OTM3IiB3aWR0aD0iMi4zNjQ0NzcxNiIgaGVpZ2h0PSI1LjcwMzM5NTkzIj48L3JlY3Q+CiAgICAgICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLXBhdGgiIGZpbGw9IiM0NDdBREIiIGZpbGwtcnVsZT0ibm9uemVybyIgeD0iMTQuMTIzMTg3OCIgeT0iMi4wMTA2MTAzMyIgd2lkdGg9IjIuMzY0NDc3MTYiIGhlaWdodD0iMTkuOTc4Nzc5MyI+PC9yZWN0PgogICAgICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS1wYXRoIiBmaWxsPSIjNDQ3QURCIiBmaWxsLXJ1bGU9Im5vbnplcm8iIHg9IjExLjIwNzg0NzciIHk9IjcuNjk3MTM2MTUiIHdpZHRoPSIyLjM2NDQ3NzE2IiBoZWlnaHQ9IjE0LjI5MjI1MzUiPjwvcmVjdD4KICAgICAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbD0iIzQ0N0FEQiIgZmlsbC1ydWxlPSJub256ZXJvIiB4PSI4LjI4NTA4NjI5IiB5PSI0Ljg2MjMxNjEyIiB3aWR0aD0iMi4zNjQ0NzcxNiIgaGVpZ2h0PSIxNy4xMjcwNzM2Ij48L3JlY3Q+CiAgICAgICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLXBhdGgiIGZpbGw9IiM0NDdBREIiIGZpbGwtcnVsZT0ibm9uemVybyIgeD0iNS4yOTY2Mzk1OSIgeT0iMTMuNDI1ODUyOSIgd2lkdGg9IjIuMzY0NDc3MTYiIGhlaWdodD0iOC41NjM1MzY3OCI+PC9yZWN0PgogICAgICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS1wYXRoIiBmaWxsPSIjNDQ3QURCIiBmaWxsLXJ1bGU9Im5vbnplcm8iIHg9IjIuMzczODg4MzIiIHk9IjE5LjIzNjk0ODQiIHdpZHRoPSIyLjM2NDQ3NzE2IiBoZWlnaHQ9IjIuNzUyNDQxMzEiPjwvcmVjdD4KICAgICAgICAgICAgICAgIDxwb2x5Z29uIGlkPSJTaGFwZSIgcG9pbnRzPSIwIDAgMjQgMCAyNCAyNCAwIDI0Ij48L3BvbHlnb24+CiAgICAgICAgICAgIDwvZz4KICAgICAgICA8L2c+CiAgICA8L2c+Cjwvc3ZnPg=="

/***/ }),

/***/ "/lhS":
/*!***********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/MultiColorPicker.js ***!
  \***********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _ColorPicker = __webpack_require__(/*! ./ColorPicker */ "u/dz");

var _ColorPicker2 = _interopRequireDefault(_ColorPicker);

var _ColorscalePicker = __webpack_require__(/*! ./ColorscalePicker */ "t0w/");

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _Info = __webpack_require__(/*! ./Info */ "iOcY");

var _Info2 = _interopRequireDefault(_Info);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _RadioBlocks = __webpack_require__(/*! ../widgets/RadioBlocks */ "N8y9");

var _RadioBlocks2 = _interopRequireDefault(_RadioBlocks);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _nested_property = __webpack_require__(/*! plotly.js/src/lib/nested_property */ "dNZO");

var _nested_property2 = _interopRequireDefault(_nested_property);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var CustomColorscalePicker = (0, _lib.connectToContainer)(_ColorscalePicker.UnconnectedColorscalePicker, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    if (props.attr === 'marker.color' && context.fullData.filter(function (t) {
      return context.traceIndexes.includes(t.index);
    }).every(function (t) {
      return t.marker && t.marker.color;
    }) && plotProps.fullValue && typeof plotProps.fullValue === 'string') {
      plotProps.fullValue = context.fullData && context.fullData.filter(function (t) {
        return context.traceIndexes.includes(t.index);
      }).map(function (t) {
        return [0, t.marker.color];
      });
    }
  }
});

var UnconnectedMultiColorPicker = function (_Component) {
  _inherits(UnconnectedMultiColorPicker, _Component);

  function UnconnectedMultiColorPicker(props, context) {
    _classCallCheck(this, UnconnectedMultiColorPicker);

    var _this = _possibleConstructorReturn(this, (UnconnectedMultiColorPicker.__proto__ || Object.getPrototypeOf(UnconnectedMultiColorPicker)).call(this, props, context));

    _this.state = {
      selectedConstantColorOption: context.traceIndexes.length > 1 && props.fullValue && props.fullValue.every(function (v) {
        return v[1] === props.fullValue[0][1];
      }) ? 'single' : 'multiple'
    };
    _this.setColor = _this.setColor.bind(_this);
    _this.setColors = _this.setColors.bind(_this);
    return _this;
  }

  _createClass(UnconnectedMultiColorPicker, [{
    key: 'setColor',
    value: function setColor(color) {
      if (this.props.setColor) {
        this.props.setColor(color);
      } else {
        this.props.updatePlot(color);
      }
    }
  }, {
    key: 'setColors',
    value: function setColors(colorscale, colorscaleType) {
      var _this2 = this;

      var numberOfTraces = this.props.tracesToColor.length;
      var colors = colorscale.map(function (c) {
        return c[1];
      });

      var adjustedColors = colors;

      if (colorscaleType !== 'categorical') {
        adjustedColors = (0, _lib.adjustColorscale)(colors, numberOfTraces, colorscaleType);
      }

      if (adjustedColors.every(function (c) {
        return c === adjustedColors[0];
      }) || colorscaleType === 'categorical') {
        adjustedColors = (0, _lib.adjustColorscale)(colors, numberOfTraces, colorscaleType, { repeat: true });
      }

      var updates = adjustedColors.map(function (color) {
        return _defineProperty({}, _this2.props.attr, color);
      });

      this.context.updateContainer(updates);
    }
  }, {
    key: 'render',
    value: function render() {
      var _this3 = this;

      var _ = this.context.localize;
      var constantOptions = [{ label: _('Single'), value: 'single' }, { label: _('Multiple'), value: 'multiple' }];
      var selectedConstantColorOption = this.props.parentSelectedConstantColorOption ? this.props.parentSelectedConstantColorOption : this.state.selectedConstantColorOption;

      var multiMessage = this.props.multiColorMessage ? this.props.multiColorMessage : _('Each will be colored according to the selected colors.');

      var singleMessage = this.props.singleColorMessage ? this.props.singleColorMessage : _('All will be colored in the same color.');

      if (this.context.traceIndexes.length > 1) {
        return _react2.default.createElement(
          _Field2.default,
          _extends({}, this.props, { suppressMultiValuedMessage: true }),
          _react2.default.createElement(_RadioBlocks2.default, {
            options: constantOptions,
            activeOption: selectedConstantColorOption,
            onOptionChange: this.props.onConstantColorOptionChange ? this.props.onConstantColorOptionChange : function (value) {
              return _this3.setState({ selectedConstantColorOption: value });
            }
          }),
          _react2.default.createElement(
            _Info2.default,
            null,
            selectedConstantColorOption === 'single' ? singleMessage : multiMessage
          ),
          selectedConstantColorOption === 'single' ? _react2.default.createElement(_ColorPicker2.default, { attr: this.props.attr, updatePlot: this.setColor }) : _react2.default.createElement(CustomColorscalePicker, {
            suppressMultiValuedMessage: true,
            attr: this.props.attr,
            updatePlot: this.setColors,
            fullValue: this.props.fullValue,
            initialCategory: 'categorical'
          })
        );
      }

      return _react2.default.createElement(_ColorPicker2.default, { attr: this.props.attr, updatePlot: this.setColor, label: this.props.label });
    }
  }]);

  return UnconnectedMultiColorPicker;
}(_react.Component);

UnconnectedMultiColorPicker.propTypes = _extends({
  multiColorMessage: _propTypes2.default.string,
  singleColorMessage: _propTypes2.default.string,
  updatePlot: _propTypes2.default.func,
  attr: _propTypes2.default.string,
  parentSelectedConstantColorOption: _propTypes2.default.string,
  onConstantColorOptionChange: _propTypes2.default.func,
  messageKeyWordSingle: _propTypes2.default.string,
  messageKeyWordPlural: _propTypes2.default.string,
  tracesToColor: _propTypes2.default.array
}, _Field2.default.propTypes);

UnconnectedMultiColorPicker.contextTypes = {
  localize: _propTypes2.default.func,
  updateContainer: _propTypes2.default.func,
  traceIndexes: _propTypes2.default.array,
  fullData: _propTypes2.default.array
};

exports.default = (0, _lib.connectToContainer)(UnconnectedMultiColorPicker, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    if (plotProps.isVisible) {
      var colors = [];
      var tracesToColor = [];
      var dedupedTraceIndexes = [];

      context.traceIndexes.forEach(function (i) {
        if (!dedupedTraceIndexes.includes(i)) {
          dedupedTraceIndexes.push(i);
        }
      });

      dedupedTraceIndexes.forEach(function (traceIndex) {
        var traces = context.fullData.filter(function (trace) {
          return trace.index === traceIndex;
        });
        tracesToColor = tracesToColor.concat(traces);

        traces.forEach(function (t) {
          var value = (0, _nested_property2.default)(t, props.attr).get();
          if (value) {
            colors.push(value);
          }
        });
      });

      plotProps.tracesToColor = tracesToColor;
      plotProps.fullValue = colors.map(function (c) {
        return [0, c];
      });
    }
  }
});
//# sourceMappingURL=MultiColorPicker.js.map

/***/ }),

/***/ "/nst":
/*!*********************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/push_unique.js ***!
  \*********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



/**
 * Push array with unique items
 *
 * Ignores falsy items, except 0 so we can use it to construct arrays of indices.
 *
 * @param {array} array
 *  array to be filled
 * @param {any} item
 *  item to be or not to be inserted
 * @return {array}
 *  ref to array (now possibly containing one more item)
 *
 */
module.exports = function pushUnique(array, item) {
    if(item instanceof RegExp) {
        var itemStr = item.toString();
        for(var i = 0; i < array.length; i++) {
            if(array[i] instanceof RegExp && array[i].toString() === itemStr) {
                return array;
            }
        }
        array.push(item);
    }
    else if((item || item === 0) && array.indexOf(item) === -1) array.push(item);

    return array;
};


/***/ }),

/***/ "/qo6":
/*!**********************************************************!*\
  !*** ./node_modules/xterm/lib/utils/ScreenDprMonitor.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var ScreenDprMonitor = (function () {
    function ScreenDprMonitor() {
    }
    ScreenDprMonitor.prototype.setListener = function (listener) {
        var _this = this;
        if (this._listener) {
            this.clearListener();
        }
        this._listener = listener;
        this._outerListener = function () {
            _this._listener(window.devicePixelRatio, _this._currentDevicePixelRatio);
            _this._updateDpr();
        };
        this._updateDpr();
    };
    ScreenDprMonitor.prototype._updateDpr = function () {
        if (this._resolutionMediaMatchList) {
            this._resolutionMediaMatchList.removeListener(this._outerListener);
        }
        this._currentDevicePixelRatio = window.devicePixelRatio;
        this._resolutionMediaMatchList = window.matchMedia("screen and (resolution: " + window.devicePixelRatio + "dppx)");
        this._resolutionMediaMatchList.addListener(this._outerListener);
    };
    ScreenDprMonitor.prototype.clearListener = function () {
        if (!this._listener) {
            return;
        }
        this._resolutionMediaMatchList.removeListener(this._outerListener);
        this._listener = null;
        this._outerListener = null;
    };
    return ScreenDprMonitor;
}());
exports.ScreenDprMonitor = ScreenDprMonitor;

//# sourceMappingURL=ScreenDprMonitor.js.map


/***/ }),

/***/ "/w2Y":
/*!************************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils/lib/sanitizer.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
const sanitize_html_1 = __importDefault(__webpack_require__(/*! sanitize-html */ "y48C"));
/**
 * Helper class that contains regular expressions for inline CSS style validation.
 *
 * Which properties (and values) to allow is largly based on the Google Caja project:
 *   https://github.com/google/caja
 *
 * The regular expressions are largly based on the syntax definition found at
 * https://developer.mozilla.org/en-US/docs/Web/CSS.
 */
class CssProp {
    static reg(r) {
        return new RegExp('^' + r + '$', 'i');
    }
}
/*
 * Numeric base expressions used to help build more complex regular expressions
 */
CssProp.N = {
    integer: `[+-]?[0-9]+`,
    integer_pos: `[+]?[0-9]+`,
    integer_zero_ff: `([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])`,
    number: `[+-]?([0-9]*[.])?[0-9]+(e-?[0-9]*)?`,
    number_pos: `[+]?([0-9]*[.])?[0-9]+(e-?[0-9]*)?`,
    number_zero_hundred: `[+]?(([0-9]|[1-9][0-9])([.][0-9]+)?|100)`,
    number_zero_one: `[+]?(1([.][0]+)?|0([.][0-9]+)?)`
};
/*
 * Base expressions of common CSS syntax elements
 */
CssProp.B = {
    angle: `(${CssProp.N.number}(deg|rad|grad|turn)|0)`,
    frequency: `${CssProp.N.number}(Hz|kHz)`,
    ident: String.raw `-?([_a-z]|[\xA0-\xFF]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])([_a-z0-9-]|[\xA0-\xFF]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])*`,
    len_or_perc: `(0|${CssProp.N.number}(px|em|rem|ex|in|cm|mm|pt|pc|%))`,
    length: `(${CssProp.N.number}(px|em|rem|ex|in|cm|mm|pt|pc)|0)`,
    length_pos: `(${CssProp.N.number_pos}(px|em|rem|ex|in|cm|mm|pt|pc)|0)`,
    percentage: `${CssProp.N.number}%`,
    percentage_pos: `${CssProp.N.number_pos}%`,
    percentage_zero_hundred: `${CssProp.N.number_zero_hundred}%`,
    string: String.raw `(\"([^\n\r\f\\"]|\\\n|\r\n|\r|\f|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])*\")|(\'([^\n\r\f\\']|\\\n|\r\n|\r|\f|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])*\')`,
    time: `${CssProp.N.number}(s|ms)`,
    url: `url\\(.*?\\)`,
    z_index: `[+-]?[0-9]{1,7}`
};
/*
 * Atomic (i.e. not dependant on other regular expresions) sub RegEx segments
 */
CssProp.A = {
    absolute_size: `xx-small|x-small|small|medium|large|x-large|xx-large`,
    attachment: `scroll|fixed|local`,
    bg_origin: `border-box|padding-box|content-box`,
    border_style: `none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset`,
    box: `border-box|padding-box|content-box`,
    display_inside: `auto|block|table|flex|grid`,
    display_outside: `block-level|inline-level|none|table-row-group|table-header-group|table-footer-group|table-row|table-cell|table-column-group|table-column|table-caption`,
    ending_shape: `circle|ellipse`,
    generic_family: `serif|sans-serif|cursive|fantasy|monospace`,
    generic_voice: `male|female|child`,
    relative_size: `smaller|larger`,
    repeat_style: `repeat-x|repeat-y|((?:repeat|space|round|no-repeat)(?:\\s*(?:repeat|space|round|no-repeat))?)`,
    side_or_corner: `(left|right)?\\s*(top|bottom)?`,
    single_animation_direction: `normal|reverse|alternate|alternate-reverse`,
    single_animation_fill_mode: `none|forwards|backwards|both`,
    single_animation_play_state: `running|paused`
};
/*
 * Color definition sub expressions
 */
CssProp._COLOR = {
    hex: `\\#(0x)?[0-9a-f]+`,
    name: `aliceblue|antiquewhite|aqua|aquamarine|azure|beige|bisque|black|blanchedalmond|blue|blueviolet|brown|burlywood|cadetblue|chartreuse|chocolate|coral|cornflowerblue|cornsilk|crimson|cyan|darkblue|darkcyan|darkgoldenrod|darkgray|darkgreen|darkkhaki|darkmagenta|darkolivegreen|darkorange|darkorchid|darkred|darksalmon|darkseagreen|darkslateblue|darkslategray|darkturquoise|darkviolet|deeppink|deepskyblue|dimgray|dodgerblue|firebrick|floralwhite|forestgreen|fuchsia|gainsboro|ghostwhite|gold|goldenrod|gray|green|greenyellow|honeydew|hotpink|indianred|indigo|ivory|khaki|lavender|lavenderblush|lawngreen|lemonchiffon|lightblue|lightcoral|lightcyan|lightgoldenrodyellow|lightgreen|lightgrey|lightpink|lightsalmon|lightseagreen|lightskyblue|lightslategray|lightsteelblue|lightyellow|lime|limegreen|linen|magenta|maroon|mediumaquamarine|mediumblue|mediumorchid|mediumpurple|mediumseagreen|mediumslateblue|mediumspringgreen|mediumturquoise|mediumvioletred|midnightblue|mintcream|mistyrose|moccasin|navajowhite|navy|oldlace|olive|olivedrab|orange|orangered|orchid|palegoldenrod|palegreen|paleturquoise|palevioletred|papayawhip|peachpuff|peru|pink|plum|powderblue|purple|red|rosybrown|royalblue|saddlebrown|salmon|sandybrown|seagreen|seashell|sienna|silver|skyblue|slateblue|slategray|snow|springgreen|steelblue|tan|teal|thistle|tomato|turquoise|transparent|violet|wheat|white|whitesmoke|yellow|yellowgreen`,
    rgb: String.raw `rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)`,
    rgba: String.raw `rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(${CssProp.N.integer_zero_ff}|${CssProp.N.number_zero_one}|${CssProp.B.percentage_zero_hundred})\s*\)`
};
/*
 * Compound (i.e. dependant on other (sub) regular expresions) sub RegEx segments
 */
CssProp._C = {
    alpha: `${CssProp.N.integer_zero_ff}|${CssProp.N.number_zero_one}|${CssProp.B.percentage_zero_hundred}`,
    alphavalue: CssProp.N.number_zero_one,
    bg_position: `((${CssProp.B.len_or_perc}|left|center|right|top|bottom)\\s*){1,4}`,
    bg_size: `(${CssProp.B.length_pos}|${CssProp.B.percentage}|auto){1,2}|cover|contain`,
    border_width: `thin|medium|thick|${CssProp.B.length}`,
    bottom: `${CssProp.B.length}|auto`,
    color: `${CssProp._COLOR.hex}|${CssProp._COLOR.rgb}|${CssProp._COLOR.rgba}|${CssProp._COLOR.name}`,
    family_name: `${CssProp.B.string}|(${CssProp.B.ident}\\s*)+`,
    image_decl: CssProp.B.url,
    left: `${CssProp.B.length}|auto`,
    loose_quotable_words: `(${CssProp.B.ident})+`,
    margin_width: `${CssProp.B.len_or_perc}|auto`,
    padding_width: `${CssProp.B.length_pos}|${CssProp.B.percentage_pos}`,
    page_url: CssProp.B.url,
    position: `((${CssProp.B.len_or_perc}|left|center|right|top|bottom)\\s*){1,4}`,
    right: `${CssProp.B.length}|auto`,
    shadow: '',
    size: `closest-side|farthest-side|closest-corner|farthest-corner|${CssProp.B.length}|(${CssProp.B.len_or_perc})\\s+(${CssProp.B.len_or_perc})`,
    top: `${CssProp.B.length}|auto`
};
CssProp._C1 = {
    image_list: `image\\(\\s*(${CssProp.B.url})*\\s*(${CssProp.B.url}|${CssProp._C.color})\\s*\\)`,
    shadow: `((${CssProp._C.color})\\s+((${CssProp.B.length})\\s*){2,4}(\s+inset)?)|((inset\\s+)?((${CssProp.B.length})\\s*){2,4}\\s*(${CssProp._C.color})?)`
};
CssProp._C2 = {
    bg_image: `(${CssProp.B.url}|${CssProp._C1.image_list})|none`,
    image: `${CssProp.B.url}|${CssProp._C1.image_list}`,
    shape: `rect\\(\\s*(${CssProp._C.top})\\s*,\\s*(${CssProp._C.right})\\s*,\\s*(${CssProp._C.bottom})\\s*,\\s*(${CssProp._C.left})\\s*\\)`
};
CssProp.C = Object.assign({}, CssProp._C, CssProp._C1, CssProp._C2);
/*
 * Property value regular expressions not dependant on other sub expressions
 */
CssProp.AP = {
    border_collapse: `collapse|separate`,
    box: `normal|none|contents`,
    box_sizing: `content-box|padding-box|border-box`,
    caption_side: `top|bottom`,
    clear: `none|left|right|both`,
    direction: `ltr|rtl`,
    empty_cells: `show|hide`,
    float: `left|right|none`,
    font_stretch: `normal|wider|narrower|ultra-condensed|extra-condensed|condensed|semi-condensed|semi-expanded|expanded|extra-expanded|ultra-expanded`,
    font_style: `normal|italic|oblique`,
    font_variant: `normal|small-caps`,
    font_weight: `normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900`,
    list_style_position: `inside|outside`,
    list_style_type: `disc|circle|square|decimal|decimal-leading-zero|lower-roman|upper-roman|lower-greek|lower-latin|upper-latin|armenian|georgian|lower-alpha|upper-alpha|none`,
    overflow: `visible|hidden|scroll|auto`,
    overflow_wrap: `normal|break-word`,
    overflow_x: `visible|hidden|scroll|auto|no-display|no-content`,
    page_break_after: `auto|always|avoid|left|right`,
    page_break_before: `auto|always|avoid|left|right`,
    page_break_inside: `avoid|auto`,
    position: `static|relative|absolute`,
    resize: `none|both|horizontal|vertical`,
    speak: `normal|none|spell-out`,
    speak_header: `once|always`,
    speak_numeral: `digits|continuous`,
    speak_punctuation: `code|none`,
    table_layout: `auto|fixed`,
    text_align: `left|right|center|justify`,
    text_decoration: `none|((underline|overline|line-through|blink)\\s*)+`,
    text_transform: `capitalize|uppercase|lowercase|none`,
    text_wrap: `normal|unrestricted|none|suppress`,
    unicode_bidi: `normal|embed|bidi-override`,
    visibility: `visible|hidden|collapse`,
    white_space: `normal|pre|nowrap|pre-wrap|pre-line`,
    word_break: `normal|keep-all|break-all`
};
/*
 * Compound propertiy value regular expressions (i.e. dependant on other sub expressions)
 */
CssProp._CP = {
    background_attachment: `${CssProp.A.attachment}(,\\s*${CssProp.A.attachment})*`,
    background_color: CssProp.C.color,
    background_origin: `${CssProp.A.box}(,\\s*${CssProp.A.box})*`,
    background_repeat: `${CssProp.A.repeat_style}(,\\s*${CssProp.A.repeat_style})*`,
    border: `((${CssProp.C.border_width}|${CssProp.A.border_style}|${CssProp.C.color})\\s*){1,3}`,
    border_radius: `((${CssProp.B.len_or_perc})\\s*){1,4}(\\/\\s*((${CssProp.B.len_or_perc})\\s*){1,4})?`,
    border_spacing: `${CssProp.B.length}\\s*(${CssProp.B.length})?`,
    border_top_color: CssProp.C.color,
    border_top_style: CssProp.A.border_style,
    border_width: `((${CssProp.C.border_width})\\s*){1,4}`,
    color: CssProp.C.color,
    cursor: `(${CssProp.B.url}(\\s*,\\s*)?)*(auto|crosshair|default|pointer|move|e-resize|ne-resize|nw-resize|n-resize|se-resize|sw-resize|s-resize|w-resize|text|wait|help|progress|all-scroll|col-resize|hand|no-drop|not-allowed|row-resize|vertical-text)`,
    display: `inline|block|list-item|run-in|inline-list-item|inline-block|table|inline-table|table-cell|table-caption|flex|inline-flex|grid|inline-grid|${CssProp.A.display_inside}|${CssProp.A.display_outside}|inherit|inline-box|inline-stack`,
    display_outside: CssProp.A.display_outside,
    elevation: `${CssProp.B.angle}|below|level|above|higher|lower`,
    font_family: `(${CssProp.C.family_name}|${CssProp.A.generic_family})(,\\s*(${CssProp.C.family_name}|${CssProp.A.generic_family}))*`,
    height: `${CssProp.B.length}|${CssProp.B.percentage}|auto`,
    letter_spacing: `normal|${CssProp.B.length}`,
    list_style_image: `${CssProp.C.image}|none`,
    margin_right: CssProp.C.margin_width,
    max_height: `${CssProp.B.length_pos}|${CssProp.B.percentage_pos}|none|auto`,
    min_height: `${CssProp.B.length_pos}|${CssProp.B.percentage_pos}|auto`,
    opacity: CssProp.C.alphavalue,
    outline_color: `${CssProp.C.color}|invert`,
    outline_width: CssProp.C.border_width,
    padding: `((${CssProp.C.padding_width})\\s*){1,4}`,
    padding_top: CssProp.C.padding_width,
    pitch_range: CssProp.N.number,
    right: `${CssProp.B.length}|${CssProp.B.percentage}|auto`,
    stress: CssProp.N.number,
    text_indent: `${CssProp.B.length}|${CssProp.B.percentage}`,
    text_shadow: `none|${CssProp.C.shadow}(,\\s*(${CssProp.C.shadow}))*`,
    volume: `${CssProp.N.number_pos}|${CssProp.B.percentage_pos}|silent|x-soft|soft|medium|loud|x-loud`,
    word_wrap: CssProp.AP.overflow_wrap,
    zoom: `normal|${CssProp.N.number_pos}|${CssProp.B.percentage_pos}`,
    backface_visibility: CssProp.AP.visibility,
    background_clip: `${CssProp.A.box}(,\\s*(${CssProp.A.box}))*`,
    background_position: `${CssProp.C.bg_position}(,\\s*(${CssProp.C.bg_position}))*`,
    border_bottom_color: CssProp.C.color,
    border_bottom_style: CssProp.A.border_style,
    border_color: `((${CssProp.C.color})\\s*){1,4}`,
    border_left_color: CssProp.C.color,
    border_right_color: CssProp.C.color,
    border_style: `((${CssProp.A.border_style})\\s*){1,4}`,
    border_top_left_radius: `(${CssProp.B.length}|${CssProp.B.percentage})(\\s*(${CssProp.B.length}|${CssProp.B.percentage}))?`,
    border_top_width: CssProp.C.border_width,
    box_shadow: `none|${CssProp.C.shadow}(,\\s*(${CssProp.C.shadow}))*`,
    clip: `${CssProp.C.shape}|auto`,
    display_inside: CssProp.A.display_inside,
    font_size: `${CssProp.A.absolute_size}|${CssProp.A.relative_size}|${CssProp.B.length_pos}|${CssProp.B.percentage_pos}`,
    line_height: `normal|${CssProp.N.number_pos}|${CssProp.B.length_pos}|${CssProp.B.percentage_pos}`,
    margin_left: CssProp.C.margin_width,
    max_width: `${CssProp.B.length_pos}|${CssProp.B.percentage_pos}|none|auto`,
    outline_style: CssProp.A.border_style,
    padding_bottom: CssProp.C.padding_width,
    padding_right: CssProp.C.padding_width,
    perspective: `none|${CssProp.B.length}`,
    richness: CssProp.N.number,
    text_overflow: `((clip|ellipsis|${CssProp.B.string})\\s*){1,2}`,
    top: `${CssProp.B.length}|${CssProp.B.percentage}|auto`,
    width: `${CssProp.B.length_pos}|${CssProp.B.percentage_pos}|auto`,
    z_index: `auto|${CssProp.B.z_index}`,
    // Simplified background
    background: `(((${CssProp.C.bg_position}\\s*(\\/\\s*${CssProp.C.bg_size})?)|(${CssProp.A.repeat_style})|(${CssProp.A.attachment})|(${CssProp.A.bg_origin})|(${CssProp.C.bg_image})|(${CssProp.C.color}))\\s*)+`,
    background_size: `${CssProp.C.bg_size}(,\\s*${CssProp.C.bg_size})*`,
    border_bottom_left_radius: `(${CssProp.B.length}|${CssProp.B.percentage})(\\s*(${CssProp.B.length}|${CssProp.B.percentage}))?`,
    border_bottom_width: CssProp.C.border_width,
    border_left_style: CssProp.A.border_style,
    border_right_style: CssProp.A.border_style,
    border_top: `((${CssProp.C.border_width}|${CssProp.A.border_style}|${CssProp.C.color})\\s*){1,3}`,
    bottom: `${CssProp.B.len_or_perc}|auto`,
    list_style: `((${CssProp.AP.list_style_type}|${CssProp.AP.list_style_position}|${CssProp.C.image}|none})\\s*){1,3}`,
    margin_top: CssProp.C.margin_width,
    outline: `((${CssProp.C.color}|invert|${CssProp.A.border_style}|${CssProp.C.border_width})\\s*){1,3}`,
    overflow_y: CssProp.AP.overflow_x,
    pitch: `${CssProp.B.frequency}|x-low|low|medium|high|x-high`,
    vertical_align: `baseline|sub|super|top|text-top|middle|bottom|text-bottom|${CssProp.B.len_or_perc}`,
    word_spacing: `normal|${CssProp.B.length}`,
    background_image: `${CssProp.C.bg_image}(,\\s*${CssProp.C.bg_image})*`,
    border_bottom_right_radius: `(${CssProp.B.length}|${CssProp.B.percentage})(\\s*(${CssProp.B.length}|${CssProp.B.percentage}))?`,
    border_left_width: CssProp.C.border_width,
    border_right_width: CssProp.C.border_width,
    left: `${CssProp.B.len_or_perc}|auto`,
    margin_bottom: CssProp.C.margin_width,
    pause_after: `${CssProp.B.time}|${CssProp.B.percentage}`,
    speech_rate: `${CssProp.N.number}|x-slow|slow|medium|fast|x-fast|faster|slower`,
    transition_duration: `${CssProp.B.time}(,\\s*${CssProp.B.time})*`,
    border_bottom: `((${CssProp.C.border_width}|${CssProp.A.border_style}|${CssProp.C.color})\\s*){1,3}`,
    border_right: `((${CssProp.C.border_width}|${CssProp.A.border_style}|${CssProp.C.color})\\s*){1,3}`,
    margin: `((${CssProp.C.margin_width})\\s*){1,4}`,
    padding_left: CssProp.C.padding_width,
    border_left: `((${CssProp.C.border_width}|${CssProp.A.border_style}|${CssProp.C.color})\\s*){1,3}`,
    quotes: `(${CssProp.B.string}\\s*${CssProp.B.string})+|none`,
    border_top_right_radius: `(${CssProp.B.length}|${CssProp.B.percentage})(\\s*(${CssProp.B.length}|${CssProp.B.percentage}))?`,
    min_width: `${CssProp.B.length_pos}|${CssProp.B.percentage_pos}|auto`
};
CssProp._CP1 = {
    font: `(((((${CssProp.AP.font_style}|${CssProp.AP.font_variant}|${CssProp.AP.font_weight})\\s*){1,3})?\\s*(${CssProp._CP.font_size})\\s*(\\/\\s*(${CssProp._CP.line_height}))?\\s+(${CssProp._CP.font_family}))|caption|icon|menu|message-box|small-caption|status-bar)`
};
CssProp.CP = Object.assign({}, CssProp._CP, CssProp._CP1);
// CSS Property value validation regular expressions for use with sanitize-html
CssProp.BORDER_COLLAPSE = CssProp.reg(CssProp.AP.border_collapse);
CssProp.BOX = CssProp.reg(CssProp.AP.box);
CssProp.BOX_SIZING = CssProp.reg(CssProp.AP.box_sizing);
CssProp.CAPTION_SIDE = CssProp.reg(CssProp.AP.caption_side);
CssProp.CLEAR = CssProp.reg(CssProp.AP.clear);
CssProp.DIRECTION = CssProp.reg(CssProp.AP.direction);
CssProp.EMPTY_CELLS = CssProp.reg(CssProp.AP.empty_cells);
CssProp.FLOAT = CssProp.reg(CssProp.AP.float);
CssProp.FONT_STRETCH = CssProp.reg(CssProp.AP.font_stretch);
CssProp.FONT_STYLE = CssProp.reg(CssProp.AP.font_style);
CssProp.FONT_VARIANT = CssProp.reg(CssProp.AP.font_variant);
CssProp.FONT_WEIGHT = CssProp.reg(CssProp.AP.font_weight);
CssProp.LIST_STYLE_POSITION = CssProp.reg(CssProp.AP.list_style_position);
CssProp.LIST_STYLE_TYPE = CssProp.reg(CssProp.AP.list_style_type);
CssProp.OVERFLOW = CssProp.reg(CssProp.AP.overflow);
CssProp.OVERFLOW_WRAP = CssProp.reg(CssProp.AP.overflow_wrap);
CssProp.OVERFLOW_X = CssProp.reg(CssProp.AP.overflow_x);
CssProp.PAGE_BREAK_AFTER = CssProp.reg(CssProp.AP.page_break_after);
CssProp.PAGE_BREAK_BEFORE = CssProp.reg(CssProp.AP.page_break_before);
CssProp.PAGE_BREAK_INSIDE = CssProp.reg(CssProp.AP.page_break_inside);
CssProp.POSITION = CssProp.reg(CssProp.AP.position);
CssProp.RESIZE = CssProp.reg(CssProp.AP.resize);
CssProp.SPEAK = CssProp.reg(CssProp.AP.speak);
CssProp.SPEAK_HEADER = CssProp.reg(CssProp.AP.speak_header);
CssProp.SPEAK_NUMERAL = CssProp.reg(CssProp.AP.speak_numeral);
CssProp.SPEAK_PUNCTUATION = CssProp.reg(CssProp.AP.speak_punctuation);
CssProp.TABLE_LAYOUT = CssProp.reg(CssProp.AP.table_layout);
CssProp.TEXT_ALIGN = CssProp.reg(CssProp.AP.text_align);
CssProp.TEXT_DECORATION = CssProp.reg(CssProp.AP.text_decoration);
CssProp.TEXT_TRANSFORM = CssProp.reg(CssProp.AP.text_transform);
CssProp.TEXT_WRAP = CssProp.reg(CssProp.AP.text_wrap);
CssProp.UNICODE_BIDI = CssProp.reg(CssProp.AP.unicode_bidi);
CssProp.VISIBILITY = CssProp.reg(CssProp.AP.visibility);
CssProp.WHITE_SPACE = CssProp.reg(CssProp.AP.white_space);
CssProp.WORD_BREAK = CssProp.reg(CssProp.AP.word_break);
CssProp.BACKGROUND_ATTACHMENT = CssProp.reg(CssProp.CP.background_attachment);
CssProp.BACKGROUND_COLOR = CssProp.reg(CssProp.CP.background_color);
CssProp.BACKGROUND_ORIGIN = CssProp.reg(CssProp.CP.background_origin);
CssProp.BACKGROUND_REPEAT = CssProp.reg(CssProp.CP.background_repeat);
CssProp.BORDER = CssProp.reg(CssProp.CP.border);
CssProp.BORDER_RADIUS = CssProp.reg(CssProp.CP.border_radius);
CssProp.BORDER_SPACING = CssProp.reg(CssProp.CP.border_spacing);
CssProp.BORDER_TOP_COLOR = CssProp.reg(CssProp.CP.border_top_color);
CssProp.BORDER_TOP_STYLE = CssProp.reg(CssProp.CP.border_top_style);
CssProp.BORDER_WIDTH = CssProp.reg(CssProp.CP.border_width);
CssProp.COLOR = CssProp.reg(CssProp.CP.color);
CssProp.CURSOR = CssProp.reg(CssProp.CP.cursor);
CssProp.DISPLAY = CssProp.reg(CssProp.CP.display);
CssProp.DISPLAY_OUTSIDE = CssProp.reg(CssProp.CP.display_outside);
CssProp.ELEVATION = CssProp.reg(CssProp.CP.elevation);
CssProp.FONT_FAMILY = CssProp.reg(CssProp.CP.font_family);
CssProp.HEIGHT = CssProp.reg(CssProp.CP.height);
CssProp.LETTER_SPACING = CssProp.reg(CssProp.CP.letter_spacing);
CssProp.LIST_STYLE_IMAGE = CssProp.reg(CssProp.CP.list_style_image);
CssProp.MARGIN_RIGHT = CssProp.reg(CssProp.CP.margin_right);
CssProp.MAX_HEIGHT = CssProp.reg(CssProp.CP.max_height);
CssProp.MIN_HEIGHT = CssProp.reg(CssProp.CP.min_height);
CssProp.OPACITY = CssProp.reg(CssProp.CP.opacity);
CssProp.OUTLINE_COLOR = CssProp.reg(CssProp.CP.outline_color);
CssProp.OUTLINE_WIDTH = CssProp.reg(CssProp.CP.outline_width);
CssProp.PADDING = CssProp.reg(CssProp.CP.padding);
CssProp.PADDING_TOP = CssProp.reg(CssProp.CP.padding_top);
CssProp.PITCH_RANGE = CssProp.reg(CssProp.CP.pitch_range);
CssProp.RIGHT = CssProp.reg(CssProp.CP.right);
CssProp.STRESS = CssProp.reg(CssProp.CP.stress);
CssProp.TEXT_INDENT = CssProp.reg(CssProp.CP.text_indent);
CssProp.TEXT_SHADOW = CssProp.reg(CssProp.CP.text_shadow);
CssProp.VOLUME = CssProp.reg(CssProp.CP.volume);
CssProp.WORD_WRAP = CssProp.reg(CssProp.CP.word_wrap);
CssProp.ZOOM = CssProp.reg(CssProp.CP.zoom);
CssProp.BACKFACE_VISIBILITY = CssProp.reg(CssProp.CP.backface_visibility);
CssProp.BACKGROUND_CLIP = CssProp.reg(CssProp.CP.background_clip);
CssProp.BACKGROUND_POSITION = CssProp.reg(CssProp.CP.background_position);
CssProp.BORDER_BOTTOM_COLOR = CssProp.reg(CssProp.CP.border_bottom_color);
CssProp.BORDER_BOTTOM_STYLE = CssProp.reg(CssProp.CP.border_bottom_style);
CssProp.BORDER_COLOR = CssProp.reg(CssProp.CP.border_color);
CssProp.BORDER_LEFT_COLOR = CssProp.reg(CssProp.CP.border_left_color);
CssProp.BORDER_RIGHT_COLOR = CssProp.reg(CssProp.CP.border_right_color);
CssProp.BORDER_STYLE = CssProp.reg(CssProp.CP.border_style);
CssProp.BORDER_TOP_LEFT_RADIUS = CssProp.reg(CssProp.CP.border_top_left_radius);
CssProp.BORDER_TOP_WIDTH = CssProp.reg(CssProp.CP.border_top_width);
CssProp.BOX_SHADOW = CssProp.reg(CssProp.CP.box_shadow);
CssProp.CLIP = CssProp.reg(CssProp.CP.clip);
CssProp.DISPLAY_INSIDE = CssProp.reg(CssProp.CP.display_inside);
CssProp.FONT_SIZE = CssProp.reg(CssProp.CP.font_size);
CssProp.LINE_HEIGHT = CssProp.reg(CssProp.CP.line_height);
CssProp.MARGIN_LEFT = CssProp.reg(CssProp.CP.margin_left);
CssProp.MAX_WIDTH = CssProp.reg(CssProp.CP.max_width);
CssProp.OUTLINE_STYLE = CssProp.reg(CssProp.CP.outline_style);
CssProp.PADDING_BOTTOM = CssProp.reg(CssProp.CP.padding_bottom);
CssProp.PADDING_RIGHT = CssProp.reg(CssProp.CP.padding_right);
CssProp.PERSPECTIVE = CssProp.reg(CssProp.CP.perspective);
CssProp.RICHNESS = CssProp.reg(CssProp.CP.richness);
CssProp.TEXT_OVERFLOW = CssProp.reg(CssProp.CP.text_overflow);
CssProp.TOP = CssProp.reg(CssProp.CP.top);
CssProp.WIDTH = CssProp.reg(CssProp.CP.width);
CssProp.Z_INDEX = CssProp.reg(CssProp.CP.z_index);
CssProp.BACKGROUND = CssProp.reg(CssProp.CP.background);
CssProp.BACKGROUND_SIZE = CssProp.reg(CssProp.CP.background_size);
CssProp.BORDER_BOTTOM_LEFT_RADIUS = CssProp.reg(CssProp.CP.border_bottom_left_radius);
CssProp.BORDER_BOTTOM_WIDTH = CssProp.reg(CssProp.CP.border_bottom_width);
CssProp.BORDER_LEFT_STYLE = CssProp.reg(CssProp.CP.border_left_style);
CssProp.BORDER_RIGHT_STYLE = CssProp.reg(CssProp.CP.border_right_style);
CssProp.BORDER_TOP = CssProp.reg(CssProp.CP.border_top);
CssProp.BOTTOM = CssProp.reg(CssProp.CP.bottom);
CssProp.LIST_STYLE = CssProp.reg(CssProp.CP.list_style);
CssProp.MARGIN_TOP = CssProp.reg(CssProp.CP.margin_top);
CssProp.OUTLINE = CssProp.reg(CssProp.CP.outline);
CssProp.OVERFLOW_Y = CssProp.reg(CssProp.CP.overflow_y);
CssProp.PITCH = CssProp.reg(CssProp.CP.pitch);
CssProp.VERTICAL_ALIGN = CssProp.reg(CssProp.CP.vertical_align);
CssProp.WORD_SPACING = CssProp.reg(CssProp.CP.word_spacing);
CssProp.BACKGROUND_IMAGE = CssProp.reg(CssProp.CP.background_image);
CssProp.BORDER_BOTTOM_RIGHT_RADIUS = CssProp.reg(CssProp.CP.border_bottom_right_radius);
CssProp.BORDER_LEFT_WIDTH = CssProp.reg(CssProp.CP.border_left_width);
CssProp.BORDER_RIGHT_WIDTH = CssProp.reg(CssProp.CP.border_right_width);
CssProp.LEFT = CssProp.reg(CssProp.CP.left);
CssProp.MARGIN_BOTTOM = CssProp.reg(CssProp.CP.margin_bottom);
CssProp.PAUSE_AFTER = CssProp.reg(CssProp.CP.pause_after);
CssProp.SPEECH_RATE = CssProp.reg(CssProp.CP.speech_rate);
CssProp.TRANSITION_DURATION = CssProp.reg(CssProp.CP.transition_duration);
CssProp.BORDER_BOTTOM = CssProp.reg(CssProp.CP.border_bottom);
CssProp.BORDER_RIGHT = CssProp.reg(CssProp.CP.border_right);
CssProp.MARGIN = CssProp.reg(CssProp.CP.margin);
CssProp.PADDING_LEFT = CssProp.reg(CssProp.CP.padding_left);
CssProp.BORDER_LEFT = CssProp.reg(CssProp.CP.border_left);
CssProp.FONT = CssProp.reg(CssProp.CP.font);
CssProp.QUOTES = CssProp.reg(CssProp.CP.quotes);
CssProp.BORDER_TOP_RIGHT_RADIUS = CssProp.reg(CssProp.CP.border_top_right_radius);
CssProp.MIN_WIDTH = CssProp.reg(CssProp.CP.min_width);
/**
 * A class to sanitize HTML strings.
 */
class Sanitizer {
    constructor() {
        this._options = {
            // HTML tags that are allowed to be used. Tags were extracted from Google Caja
            allowedTags: [
                'a',
                'abbr',
                'acronym',
                'address',
                'area',
                'article',
                'aside',
                'audio',
                'b',
                'bdi',
                'bdo',
                'big',
                'blockquote',
                'br',
                'button',
                'canvas',
                'caption',
                'center',
                'cite',
                'code',
                'col',
                'colgroup',
                'colspan',
                'command',
                'data',
                'datalist',
                'dd',
                'del',
                'details',
                'dfn',
                'dir',
                'div',
                'dl',
                'dt',
                'em',
                'fieldset',
                'figcaption',
                'figure',
                'font',
                'footer',
                'form',
                'h1',
                'h2',
                'h3',
                'h4',
                'h5',
                'h6',
                'header',
                'hgroup',
                'hr',
                'i',
                // 'iframe' is allowed by Google Caja, but disallowed by default by sanitize-html
                // , 'iframe'
                'img',
                'input',
                'ins',
                'kbd',
                'label',
                'legend',
                'li',
                'map',
                'mark',
                'menu',
                'meter',
                'nav',
                'nobr',
                'ol',
                'optgroup',
                'option',
                'output',
                'p',
                'pre',
                'progress',
                'q',
                'rowspan',
                's',
                'samp',
                'section',
                'select',
                'small',
                'source',
                'span',
                'strike',
                'strong',
                'sub',
                'summary',
                'sup',
                'table',
                'tbody',
                'td',
                'textarea',
                'tfoot',
                'th',
                'thead',
                'time',
                'tr',
                'track',
                'tt',
                'u',
                'ul',
                'var',
                'video',
                'wbr'
            ],
            // Attributes that HTML tags are allowed to have, extracted from Google Caja.
            // See https://github.com/jupyterlab/jupyterlab/issues/1812#issuecomment-285848435
            allowedAttributes: {
                '*': [
                    'class',
                    'dir',
                    'draggable',
                    'hidden',
                    'id',
                    'inert',
                    'itemprop',
                    'itemref',
                    'itemscope',
                    'lang',
                    'spellcheck',
                    'style',
                    'title',
                    'translate'
                ],
                // 'rel' and 'target' were *not* allowed by Google Caja
                a: [
                    'accesskey',
                    'coords',
                    'href',
                    'hreflang',
                    'name',
                    'rel',
                    'shape',
                    'tabindex',
                    'target',
                    'type'
                ],
                area: [
                    'accesskey',
                    'alt',
                    'coords',
                    'href',
                    'nohref',
                    'shape',
                    'tabindex'
                ],
                // 'autoplay' was *not* allowed by Google Caja
                audio: [
                    'autoplay',
                    'controls',
                    'loop',
                    'mediagroup',
                    'muted',
                    'preload',
                    'src'
                ],
                bdo: ['dir'],
                blockquote: ['cite'],
                br: ['clear'],
                button: ['accesskey', 'disabled', 'name', 'tabindex', 'type', 'value'],
                canvas: ['height', 'width'],
                caption: ['align'],
                col: ['align', 'char', 'charoff', 'span', 'valign', 'width'],
                colgroup: ['align', 'char', 'charoff', 'span', 'valign', 'width'],
                command: [
                    'checked',
                    'command',
                    'disabled',
                    'icon',
                    'label',
                    'radiogroup',
                    'type'
                ],
                data: ['value'],
                del: ['cite', 'datetime'],
                details: ['open'],
                dir: ['compact'],
                div: ['align'],
                dl: ['compact'],
                fieldset: ['disabled'],
                font: ['color', 'face', 'size'],
                form: [
                    'accept',
                    'action',
                    'autocomplete',
                    'enctype',
                    'method',
                    'name',
                    'novalidate'
                ],
                h1: ['align'],
                h2: ['align'],
                h3: ['align'],
                h4: ['align'],
                h5: ['align'],
                h6: ['align'],
                hr: ['align', 'noshade', 'size', 'width'],
                iframe: [
                    'align',
                    'frameborder',
                    'height',
                    'marginheight',
                    'marginwidth',
                    'width'
                ],
                img: [
                    'align',
                    'alt',
                    'border',
                    'height',
                    'hspace',
                    'ismap',
                    'name',
                    'src',
                    'usemap',
                    'vspace',
                    'width'
                ],
                input: [
                    'accept',
                    'accesskey',
                    'align',
                    'alt',
                    'autocomplete',
                    'checked',
                    'disabled',
                    'inputmode',
                    'ismap',
                    'list',
                    'max',
                    'maxlength',
                    'min',
                    'multiple',
                    'name',
                    'placeholder',
                    'readonly',
                    'required',
                    'size',
                    'src',
                    'step',
                    'tabindex',
                    'type',
                    'usemap',
                    'value'
                ],
                ins: ['cite', 'datetime'],
                label: ['accesskey', 'for'],
                legend: ['accesskey', 'align'],
                li: ['type', 'value'],
                map: ['name'],
                menu: ['compact', 'label', 'type'],
                meter: ['high', 'low', 'max', 'min', 'value'],
                ol: ['compact', 'reversed', 'start', 'type'],
                optgroup: ['disabled', 'label'],
                option: ['disabled', 'label', 'selected', 'value'],
                output: ['for', 'name'],
                p: ['align'],
                pre: ['width'],
                progress: ['max', 'min', 'value'],
                q: ['cite'],
                select: [
                    'autocomplete',
                    'disabled',
                    'multiple',
                    'name',
                    'required',
                    'size',
                    'tabindex'
                ],
                source: ['type'],
                table: [
                    'align',
                    'bgcolor',
                    'border',
                    'cellpadding',
                    'cellspacing',
                    'frame',
                    'rules',
                    'summary',
                    'width'
                ],
                tbody: ['align', 'char', 'charoff', 'valign'],
                td: [
                    'abbr',
                    'align',
                    'axis',
                    'bgcolor',
                    'char',
                    'charoff',
                    'colspan',
                    'headers',
                    'height',
                    'nowrap',
                    'rowspan',
                    'scope',
                    'valign',
                    'width'
                ],
                textarea: [
                    'accesskey',
                    'autocomplete',
                    'cols',
                    'disabled',
                    'inputmode',
                    'name',
                    'placeholder',
                    'readonly',
                    'required',
                    'rows',
                    'tabindex',
                    'wrap'
                ],
                tfoot: ['align', 'char', 'charoff', 'valign'],
                th: [
                    'abbr',
                    'align',
                    'axis',
                    'bgcolor',
                    'char',
                    'charoff',
                    'colspan',
                    'headers',
                    'height',
                    'nowrap',
                    'rowspan',
                    'scope',
                    'valign',
                    'width'
                ],
                thead: ['align', 'char', 'charoff', 'valign'],
                tr: ['align', 'bgcolor', 'char', 'charoff', 'valign'],
                track: ['default', 'kind', 'label', 'srclang'],
                ul: ['compact', 'type'],
                video: [
                    'autoplay',
                    'controls',
                    'height',
                    'loop',
                    'mediagroup',
                    'muted',
                    'poster',
                    'preload',
                    'src',
                    'width'
                ]
            },
            // Inline CSS styles that HTML tags may have (and their allowed values)
            allowedStyles: {
                // To simplify the data, all styles are allowed on all tags that allow the style attribute
                '*': {
                    'backface-visibility': [CssProp.BACKFACE_VISIBILITY],
                    background: [CssProp.BACKGROUND],
                    'background-attachment': [CssProp.BACKGROUND_ATTACHMENT],
                    'background-clip': [CssProp.BACKGROUND_CLIP],
                    'background-color': [CssProp.BACKGROUND_COLOR],
                    'background-image': [CssProp.BACKGROUND_IMAGE],
                    'background-origin': [CssProp.BACKGROUND_ORIGIN],
                    'background-position': [CssProp.BACKGROUND_POSITION],
                    'background-repeat': [CssProp.BACKGROUND_REPEAT],
                    'background-size': [CssProp.BACKGROUND_SIZE],
                    border: [CssProp.BORDER],
                    'border-bottom': [CssProp.BORDER_BOTTOM],
                    'border-bottom-color': [CssProp.BORDER_BOTTOM_COLOR],
                    'border-bottom-left-radius': [CssProp.BORDER_BOTTOM_LEFT_RADIUS],
                    'border-bottom-right-radius': [CssProp.BORDER_BOTTOM_RIGHT_RADIUS],
                    'border-bottom-style': [CssProp.BORDER_BOTTOM_STYLE],
                    'border-bottom-width': [CssProp.BORDER_BOTTOM_WIDTH],
                    'border-collapse': [CssProp.BORDER_COLLAPSE],
                    'border-color': [CssProp.BORDER_COLOR],
                    'border-left': [CssProp.BORDER_LEFT],
                    'border-left-color': [CssProp.BORDER_LEFT_COLOR],
                    'border-left-style': [CssProp.BORDER_LEFT_STYLE],
                    'border-left-width': [CssProp.BORDER_LEFT_WIDTH],
                    'border-radius': [CssProp.BORDER_RADIUS],
                    'border-right': [CssProp.BORDER_RIGHT],
                    'border-right-color': [CssProp.BORDER_RIGHT_COLOR],
                    'border-right-style': [CssProp.BORDER_RIGHT_STYLE],
                    'border-right-width': [CssProp.BORDER_RIGHT_WIDTH],
                    'border-spacing': [CssProp.BORDER_SPACING],
                    'border-style': [CssProp.BORDER_STYLE],
                    'border-top': [CssProp.BORDER_TOP],
                    'border-top-color': [CssProp.BORDER_TOP_COLOR],
                    'border-top-left-radius': [CssProp.BORDER_TOP_LEFT_RADIUS],
                    'border-top-right-radius': [CssProp.BORDER_TOP_RIGHT_RADIUS],
                    'border-top-style': [CssProp.BORDER_TOP_STYLE],
                    'border-top-width': [CssProp.BORDER_TOP_WIDTH],
                    'border-width': [CssProp.BORDER_WIDTH],
                    bottom: [CssProp.BOTTOM],
                    box: [CssProp.BOX],
                    'box-shadow': [CssProp.BOX_SHADOW],
                    'box-sizing': [CssProp.BOX_SIZING],
                    'caption-side': [CssProp.CAPTION_SIDE],
                    clear: [CssProp.CLEAR],
                    clip: [CssProp.CLIP],
                    color: [CssProp.COLOR],
                    cursor: [CssProp.CURSOR],
                    direction: [CssProp.DIRECTION],
                    display: [CssProp.DISPLAY],
                    'display-inside': [CssProp.DISPLAY_INSIDE],
                    'display-outside': [CssProp.DISPLAY_OUTSIDE],
                    elevation: [CssProp.ELEVATION],
                    'empty-cells': [CssProp.EMPTY_CELLS],
                    float: [CssProp.FLOAT],
                    font: [CssProp.FONT],
                    'font-family': [CssProp.FONT_FAMILY],
                    'font-size': [CssProp.FONT_SIZE],
                    'font-stretch': [CssProp.FONT_STRETCH],
                    'font-style': [CssProp.FONT_STYLE],
                    'font-variant': [CssProp.FONT_VARIANT],
                    'font-weight': [CssProp.FONT_WEIGHT],
                    height: [CssProp.HEIGHT],
                    left: [CssProp.LEFT],
                    'letter-spacing': [CssProp.LETTER_SPACING],
                    'line-height': [CssProp.LINE_HEIGHT],
                    'list-style': [CssProp.LIST_STYLE],
                    'list-style-image': [CssProp.LIST_STYLE_IMAGE],
                    'list-style-position': [CssProp.LIST_STYLE_POSITION],
                    'list-style-type': [CssProp.LIST_STYLE_TYPE],
                    margin: [CssProp.MARGIN],
                    'margin-bottom': [CssProp.MARGIN_BOTTOM],
                    'margin-left': [CssProp.MARGIN_LEFT],
                    'margin-right': [CssProp.MARGIN_RIGHT],
                    'margin-top': [CssProp.MARGIN_TOP],
                    'max-height': [CssProp.MAX_HEIGHT],
                    'max-width': [CssProp.MAX_WIDTH],
                    'min-height': [CssProp.MIN_HEIGHT],
                    'min-width': [CssProp.MIN_WIDTH],
                    opacity: [CssProp.OPACITY],
                    outline: [CssProp.OUTLINE],
                    'outline-color': [CssProp.OUTLINE_COLOR],
                    'outline-style': [CssProp.OUTLINE_STYLE],
                    'outline-width': [CssProp.OUTLINE_WIDTH],
                    overflow: [CssProp.OVERFLOW],
                    'overflow-wrap': [CssProp.OVERFLOW_WRAP],
                    'overflow-x': [CssProp.OVERFLOW_X],
                    'overflow-y': [CssProp.OVERFLOW_Y],
                    padding: [CssProp.PADDING],
                    'padding-bottom': [CssProp.PADDING_BOTTOM],
                    'padding-left': [CssProp.PADDING_LEFT],
                    'padding-right': [CssProp.PADDING_RIGHT],
                    'padding-top': [CssProp.PADDING_TOP],
                    'page-break-after': [CssProp.PAGE_BREAK_AFTER],
                    'page-break-before': [CssProp.PAGE_BREAK_BEFORE],
                    'page-break-inside': [CssProp.PAGE_BREAK_INSIDE],
                    'pause-after': [CssProp.PAUSE_AFTER],
                    perspective: [CssProp.PERSPECTIVE],
                    pitch: [CssProp.PITCH],
                    'pitch-range': [CssProp.PITCH_RANGE],
                    position: [CssProp.POSITION],
                    quotes: [CssProp.QUOTES],
                    resize: [CssProp.RESIZE],
                    richness: [CssProp.RICHNESS],
                    right: [CssProp.RIGHT],
                    speak: [CssProp.SPEAK],
                    'speak-header': [CssProp.SPEAK_HEADER],
                    'speak-numeral': [CssProp.SPEAK_NUMERAL],
                    'speak-punctuation': [CssProp.SPEAK_PUNCTUATION],
                    'speech-rate': [CssProp.SPEECH_RATE],
                    stress: [CssProp.STRESS],
                    'table-layout': [CssProp.TABLE_LAYOUT],
                    'text-align': [CssProp.TEXT_ALIGN],
                    'text-decoration': [CssProp.TEXT_DECORATION],
                    'text-indent': [CssProp.TEXT_INDENT],
                    'text-overflow': [CssProp.TEXT_OVERFLOW],
                    'text-shadow': [CssProp.TEXT_SHADOW],
                    'text-transform': [CssProp.TEXT_TRANSFORM],
                    'text-wrap': [CssProp.TEXT_WRAP],
                    top: [CssProp.TOP],
                    'unicode-bidi': [CssProp.UNICODE_BIDI],
                    'vertical-align': [CssProp.VERTICAL_ALIGN],
                    visibility: [CssProp.VISIBILITY],
                    volume: [CssProp.VOLUME],
                    'white-space': [CssProp.WHITE_SPACE],
                    width: [CssProp.WIDTH],
                    'word-break': [CssProp.WORD_BREAK],
                    'word-spacing': [CssProp.WORD_SPACING],
                    'word-wrap': [CssProp.WORD_WRAP],
                    'z-index': [CssProp.Z_INDEX],
                    zoom: [CssProp.ZOOM]
                }
            },
            transformTags: {
                // Set the "rel" attribute for <a> tags to "nofollow".
                a: sanitize_html_1.default.simpleTransform('a', { rel: 'nofollow' }),
                // Set the "disabled" attribute for <input> tags.
                input: sanitize_html_1.default.simpleTransform('input', { disabled: 'disabled' })
            },
            allowedSchemesByTag: {
                // Allow 'attachment:' img src (used for markdown cell attachments).
                img: sanitize_html_1.default.defaults.allowedSchemes.concat(['attachment'])
            },
            // Override of the default option, so we can skip 'src' attribute validation.
            // 'src' Attributes are validated to be URIs, which does not allow for embedded (image) data.
            // Since embedded data is no longer deemed to be a threat, validation can be skipped.
            // See https://github.com/jupyterlab/jupyterlab/issues/5183
            allowedSchemesAppliedToAttributes: ['href', 'cite']
        };
    }
    /**
     * Sanitize an HTML string.
     *
     * @param dirty - The dirty text.
     *
     * @param options - The optional sanitization options.
     *
     * @returns The sanitized string.
     */
    sanitize(dirty, options) {
        return sanitize_html_1.default(dirty, Object.assign({}, this._options, (options || {})));
    }
}
/**
 * The default instance of an `ISanitizer` meant for use by user code.
 */
exports.defaultSanitizer = new Sanitizer();


/***/ }),

/***/ "/y+l":
/*!*****************************************************************!*\
  !*** ./node_modules/draft-js/lib/convertFromDraftStateToRaw.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule convertFromDraftStateToRaw
 * @format
 * 
 */



var _assign = __webpack_require__(/*! object-assign */ "MgzW");

var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var ContentBlock = __webpack_require__(/*! ./ContentBlock */ "8uQm");
var ContentBlockNode = __webpack_require__(/*! ./ContentBlockNode */ "JL7T");
var DraftStringKey = __webpack_require__(/*! ./DraftStringKey */ "dyxW");

var encodeEntityRanges = __webpack_require__(/*! ./encodeEntityRanges */ "U84a");
var encodeInlineStyleRanges = __webpack_require__(/*! ./encodeInlineStyleRanges */ "yxyD");
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");

var createRawBlock = function createRawBlock(block, entityStorageMap) {
  return {
    key: block.getKey(),
    text: block.getText(),
    type: block.getType(),
    depth: block.getDepth(),
    inlineStyleRanges: encodeInlineStyleRanges(block),
    entityRanges: encodeEntityRanges(block, entityStorageMap),
    data: block.getData().toObject()
  };
};

var insertRawBlock = function insertRawBlock(block, entityMap, rawBlocks, blockCacheRef) {
  if (block instanceof ContentBlock) {
    rawBlocks.push(createRawBlock(block, entityMap));
    return;
  }

  !(block instanceof ContentBlockNode) ?  true ? invariant(false, 'block is not a BlockNode') : undefined : void 0;

  var parentKey = block.getParentKey();
  var rawBlock = blockCacheRef[block.getKey()] = _extends({}, createRawBlock(block, entityMap), {
    children: []
  });

  if (parentKey) {
    blockCacheRef[parentKey].children.push(rawBlock);
    return;
  }

  rawBlocks.push(rawBlock);
};

var encodeRawBlocks = function encodeRawBlocks(contentState, rawState) {
  var entityMap = rawState.entityMap;


  var rawBlocks = [];

  var blockCacheRef = {};
  var entityCacheRef = {};
  var entityStorageKey = 0;

  contentState.getBlockMap().forEach(function (block) {
    block.findEntityRanges(function (character) {
      return character.getEntity() !== null;
    }, function (start) {
      var entityKey = block.getEntityAt(start);
      // Stringify to maintain order of otherwise numeric keys.
      var stringifiedEntityKey = DraftStringKey.stringify(entityKey);
      // This makes this function resilient to two entities
      // erroneously having the same key
      if (entityCacheRef[stringifiedEntityKey]) {
        return;
      }
      entityCacheRef[stringifiedEntityKey] = entityKey;
      // we need the `any` casting here since this is a temporary state
      // where we will later on flip the entity map and populate it with
      // real entity, at this stage we just need to map back the entity
      // key used by the BlockNode
      entityMap[stringifiedEntityKey] = '' + entityStorageKey;
      entityStorageKey++;
    });

    insertRawBlock(block, entityMap, rawBlocks, blockCacheRef);
  });

  return {
    blocks: rawBlocks,
    entityMap: entityMap
  };
};

// Flip storage map so that our storage keys map to global
// DraftEntity keys.
var encodeRawEntityMap = function encodeRawEntityMap(contentState, rawState) {
  var blocks = rawState.blocks,
      entityMap = rawState.entityMap;


  var rawEntityMap = {};

  Object.keys(entityMap).forEach(function (key, index) {
    var entity = contentState.getEntity(DraftStringKey.unstringify(key));
    rawEntityMap[index] = {
      type: entity.getType(),
      mutability: entity.getMutability(),
      data: entity.getData()
    };
  });

  return {
    blocks: blocks,
    entityMap: rawEntityMap
  };
};

var convertFromDraftStateToRaw = function convertFromDraftStateToRaw(contentState) {
  var rawDraftContentState = {
    entityMap: {},
    blocks: []
  };

  // add blocks
  rawDraftContentState = encodeRawBlocks(contentState, rawDraftContentState);

  // add entities
  rawDraftContentState = encodeRawEntityMap(contentState, rawDraftContentState);

  return rawDraftContentState;
};

module.exports = convertFromDraftStateToRaw;

/***/ }),

/***/ "/y0H":
/*!**********************************************************!*\
  !*** ./node_modules/draft-js/lib/DraftEntitySegments.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DraftEntitySegments
 * @format
 * 
 */



/**
 * Identify the range to delete from a segmented entity.
 *
 * Rules:
 *
 *  Example: 'John F. Kennedy'
 *
 *   - Deletion from within any non-whitespace (i.e. ['John', 'F.', 'Kennedy'])
 *     will return the range of that text.
 *
 *       'John F. Kennedy' -> 'John F.'
 *                  ^
 *
 *   - Forward deletion of whitespace will remove the following section:
 *
 *       'John F. Kennedy' -> 'John Kennedy'
 *            ^
 *
 *   - Backward deletion of whitespace will remove the previous section:
 *
 *       'John F. Kennedy' -> 'F. Kennedy'
 *            ^
 */
var DraftEntitySegments = {
  getRemovalRange: function getRemovalRange(selectionStart, selectionEnd, text, entityStart, direction) {
    var segments = text.split(' ');
    segments = segments.map(function ( /*string*/segment, /*number*/ii) {
      if (direction === 'forward') {
        if (ii > 0) {
          return ' ' + segment;
        }
      } else if (ii < segments.length - 1) {
        return segment + ' ';
      }
      return segment;
    });

    var segmentStart = entityStart;
    var segmentEnd;
    var segment;
    var removalStart = null;
    var removalEnd = null;

    for (var jj = 0; jj < segments.length; jj++) {
      segment = segments[jj];
      segmentEnd = segmentStart + segment.length;

      // Our selection overlaps this segment.
      if (selectionStart < segmentEnd && segmentStart < selectionEnd) {
        if (removalStart !== null) {
          removalEnd = segmentEnd;
        } else {
          removalStart = segmentStart;
          removalEnd = segmentEnd;
        }
      } else if (removalStart !== null) {
        break;
      }

      segmentStart = segmentEnd;
    }

    var entityEnd = entityStart + text.length;
    var atStart = removalStart === entityStart;
    var atEnd = removalEnd === entityEnd;

    if (!atStart && atEnd || atStart && !atEnd) {
      if (direction === 'forward') {
        if (removalEnd !== entityEnd) {
          removalEnd++;
        }
      } else if (removalStart !== entityStart) {
        removalStart--;
      }
    }

    return {
      start: removalStart,
      end: removalEnd
    };
  }
};

module.exports = DraftEntitySegments;

/***/ }),

/***/ "0+hG":
/*!*********************************************!*\
  !*** ./node_modules/mdi-react/TableIcon.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var TableIcon = function TableIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M5,4H19C20.1,4 21,4.9 21,6V18C21,19.1 20.1,20 19,20H5C3.9,20 3,19.1 3,18V6C3,4.9 3.9,4 5,4M5,8V12H11V8H5M13,8V12H19V8H13M5,14V18H11V14H5M13,14V18H19V14H13Z' })
  );
};

module.exports = TableIcon;


/***/ }),

/***/ "01LB":
/*!********************************************!*\
  !*** ./node_modules/comment-json/index.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.stringify = __webpack_require__(/*! ./lib/stringify */ "ubXF");
exports.parse = __webpack_require__(/*! ./lib/parse */ "fy0I");


/***/ }),

/***/ "03A+":
/*!********************************************!*\
  !*** ./node_modules/lodash/isArguments.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseIsArguments = __webpack_require__(/*! ./_baseIsArguments */ "JTzB"),
    isObjectLike = __webpack_require__(/*! ./isObjectLike */ "ExA7");

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;

/**
 * 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');
};

module.exports = isArguments;


/***/ }),

/***/ "07l2":
/*!**********************************************!*\
  !*** ./node_modules/pure-color/parse/hsl.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var extractComponents = __webpack_require__(/*! ./extractComponents */ "wQnj");
var clamp = __webpack_require__(/*! ../util/clamp */ "I0N7");

function parseHslComponent(component, i) {
  component = parseFloat(component);

  switch(i) {
    case 0:
      return clamp(component, 0, 360);
    case 1:
    case 2:
      return clamp(component, 0, 100);
    case 3:
      return clamp(component, 0, 1);
  }
}

function hsl(color) {
  return extractComponents(color).map(parseHslComponent);
}

module.exports = hsl;

/***/ }),

/***/ "08JH":
/*!**********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/GearsSettingIcon.js ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var GearsSettingIcon = function GearsSettingIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M14.938 16c0-1.188-.438-2.188-1.25-3-.813-.875-1.813-1.25-3-1.25S8.5 12.125 7.625 13c-.813.813-1.25 1.813-1.25 3s.438 2.188 1.25 3c.875.875 1.875 1.25 3.063 1.25s2.188-.375 3-1.25c.813-.813 1.25-1.813 1.25-3zm12.812 8.563a2.07 2.07 0 0 0-.625-1.5c-.438-.438-.938-.688-1.5-.688a1.9 1.9 0 0 0-1.5.688 1.9 1.9 0 0 0-.688 1.5c0 .563.25 1.063.625 1.5.438.375.938.625 1.563.625.563 0 1.063-.25 1.5-.625.375-.438.625-.938.625-1.5zm0-17.125c0-.563-.25-1.063-.625-1.5-.438-.375-.938-.625-1.5-.625a2.07 2.07 0 0 0-1.5.625c-.438.438-.688.938-.688 1.5 0 .625.25 1.125.625 1.563.438.375.938.625 1.563.625.563 0 1.063-.25 1.5-.625.375-.438.625-.938.625-1.563zM21.313 14.5v3.063c0 .125 0 .25-.125.313-.063.125-.125.188-.25.188l-2.563.375c-.125.438-.313.813-.563 1.313.375.5.875 1.125 1.5 1.875.125.125.125.25.125.375s0 .25-.125.313c-.25.313-.688.813-1.375 1.5-.625.625-1.063 1-1.313 1-.125 0-.188-.063-.313-.125l-1.938-1.5a7.424 7.424 0 0 1-1.25.5c-.125 1.188-.25 2.063-.438 2.563-.063.313-.188.438-.5.438H9.122a.482.482 0 0 1-.313-.125c-.125-.125-.188-.188-.188-.313l-.375-2.563c-.375-.125-.813-.25-1.25-.5l-2 1.5c-.063.063-.188.125-.313.125s-.25-.063-.375-.188c-1.563-1.438-2.375-2.313-2.375-2.625 0-.125.063-.25.125-.313.125-.188.313-.5.688-.875.313-.438.563-.813.75-1.063-.25-.5-.438-.938-.563-1.375L.37 18.001c-.063 0-.188-.063-.25-.188a.477.477 0 0 1-.125-.313v-3.063c0-.125.063-.25.125-.313.063-.125.188-.188.25-.188l2.563-.375c.125-.438.313-.813.563-1.313-.375-.5-.875-1.125-1.5-1.875-.063-.125-.125-.25-.125-.375s.063-.25.125-.313c.25-.313.688-.813 1.375-1.5.688-.625 1.125-1 1.313-1 .125 0 .25.063.375.125l1.875 1.5a6.37 6.37 0 0 1 1.313-.5c.125-1.188.25-2.063.375-2.563.063-.313.25-.438.5-.438h3.063c.125 0 .25.063.375.125.063.125.125.188.125.313l.438 2.563c.375.125.75.25 1.25.5l1.938-1.5c.063-.063.188-.125.313-.125s.25.063.375.188c1.625 1.438 2.375 2.313 2.375 2.625 0 .125 0 .25-.063.313-.188.188-.375.5-.75.938-.313.375-.563.75-.75 1 .25.5.438 1 .563 1.375l2.563.375c.125 0 .188.063.25.188.125.063.125.188.125.313zM32 23.375v2.313c0 .188-.813.375-2.5.5a3.993 3.993 0 0 1-.5.875c.563 1.25.875 2.063.875 2.313 0 .063 0 .063-.063.125a76.824 76.824 0 0 1-2.063 1.188c-.125 0-.375-.25-.813-.813-.375-.5-.688-.875-.813-1.125-.25.063-.438.063-.5.063-.125 0-.313 0-.5-.063-.188.25-.5.625-.875 1.125-.438.563-.688.813-.813.813 0 0-.688-.375-2.063-1.188 0-.063-.063-.063-.063-.125 0-.25.313-1.063.875-2.313a3.976 3.976 0 0 1-.5-.875c-1.688-.125-2.5-.313-2.5-.5v-2.313c0-.188.813-.375 2.5-.5.125-.375.313-.625.5-.875-.563-1.25-.875-2.063-.875-2.313 0-.063.063-.063.063-.125.063 0 .25-.125.625-.313l.938-.563c.313-.188.5-.313.5-.313.125 0 .375.313.813.813.375.5.688.875.875 1.125.188-.063.375-.063.5-.063.063 0 .25 0 .5.063.563-.813 1.063-1.438 1.5-1.875l.125-.063s.688.438 2.063 1.188c.063.063.063.063.063.125 0 .25-.313 1.063-.875 2.313.188.25.375.5.5.875 1.688.125 2.5.313 2.5.5zm0-17.062v2.313c0 .188-.813.375-2.5.5a3.993 3.993 0 0 1-.5.875c.563 1.25.875 2.063.875 2.313 0 .063 0 .063-.063.125a76.824 76.824 0 0 1-2.063 1.188c-.125 0-.375-.25-.813-.813-.375-.5-.688-.875-.813-1.125-.25.063-.438.063-.5.063-.125 0-.313 0-.5-.063-.188.25-.5.625-.875 1.125-.438.563-.688.813-.813.813 0 0-.688-.375-2.063-1.188 0-.063-.063-.063-.063-.125 0-.25.313-1.063.875-2.313a3.976 3.976 0 0 1-.5-.875c-1.688-.125-2.5-.313-2.5-.5V6.313c0-.188.813-.375 2.5-.5.125-.375.313-.625.5-.875-.563-1.25-.875-2.063-.875-2.313 0-.063.063-.063.063-.125.063 0 .25-.125.625-.313.313-.25.625-.438.938-.563.313-.188.5-.313.5-.313.125 0 .375.25.813.813.375.5.688.875.875 1.125.188-.063.375-.063.5-.063.063 0 .25 0 .5.063.563-.813 1.063-1.438 1.5-1.875l.125-.063s.688.438 2.063 1.188c.063.063.063.063.063.125 0 .25-.313 1.063-.875 2.313.188.25.375.5.5.875 1.688.125 2.5.313 2.5.5z' })
    );
};

exports.default = GearsSettingIcon;

/***/ }),

/***/ "09xr":
/*!***********************************************!*\
  !*** ./node_modules/plotly.js/src/lib/mod.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



/**
 * sanitized modulus function that always returns in the range [0, d)
 * rather than (-d, 0] if v is negative
 */
function mod(v, d) {
    var out = v % d;
    return out < 0 ? out + d : out;
}

/**
 * sanitized modulus function that always returns in the range [-d/2, d/2]
 * rather than (-d, 0] if v is negative
 */
function modHalf(v, d) {
    return Math.abs(v) > (d / 2) ?
        v - Math.round(v / d) * d :
        v;
}

module.exports = {
    mod: mod,
    modHalf: modHalf
};


/***/ }),

/***/ "0AFT":
/*!*****************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/ZoomboxIcon.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var ZoomboxIcon = function ZoomboxIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 16 16' }, props),
        _react2.default.createElement('path', { d: 'M16 14l-4-4.017A6.456 6.456 0 0 0 13 6.5a6.501 6.501 0 0 0-13 0C0 10.089 2.923 13 6.512 13a6.45 6.45 0 0 0 3.495-1L14 15.993 16 14zM3 10V3h7v7H3zm1-6h5v5H4V4z' })
    );
};

exports.default = ZoomboxIcon;

/***/ }),

/***/ "0CHe":
/*!*******************************************************************!*\
  !*** ./node_modules/xterm/lib/shared/atlas/CharAtlasGenerator.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var Types_1 = __webpack_require__(/*! ./Types */ "S8N9");
var Browser_1 = __webpack_require__(/*! ../utils/Browser */ "1XL3");
function generateCharAtlas(context, canvasFactory, config) {
    var cellWidth = config.scaledCharWidth + Types_1.CHAR_ATLAS_CELL_SPACING;
    var cellHeight = config.scaledCharHeight + Types_1.CHAR_ATLAS_CELL_SPACING;
    var canvas = canvasFactory(255 * cellWidth, (2 + 16) * cellHeight);
    var ctx = canvas.getContext('2d', { alpha: config.allowTransparency });
    ctx.fillStyle = config.colors.background.css;
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.save();
    ctx.fillStyle = config.colors.foreground.css;
    ctx.font = getFont(config.fontWeight, config);
    ctx.textBaseline = 'top';
    for (var i = 0; i < 256; i++) {
        ctx.save();
        ctx.beginPath();
        ctx.rect(i * cellWidth, 0, cellWidth, cellHeight);
        ctx.clip();
        ctx.fillText(String.fromCharCode(i), i * cellWidth, 0);
        ctx.restore();
    }
    ctx.save();
    ctx.font = getFont(config.fontWeightBold, config);
    for (var i = 0; i < 256; i++) {
        ctx.save();
        ctx.beginPath();
        ctx.rect(i * cellWidth, cellHeight, cellWidth, cellHeight);
        ctx.clip();
        ctx.fillText(String.fromCharCode(i), i * cellWidth, cellHeight);
        ctx.restore();
    }
    ctx.restore();
    ctx.font = getFont(config.fontWeight, config);
    for (var colorIndex = 0; colorIndex < 16; colorIndex++) {
        if (colorIndex === 8) {
            ctx.font = getFont(config.fontWeightBold, config);
        }
        var y = (colorIndex + 2) * cellHeight;
        for (var i = 0; i < 256; i++) {
            ctx.save();
            ctx.beginPath();
            ctx.rect(i * cellWidth, y, cellWidth, cellHeight);
            ctx.clip();
            ctx.fillStyle = config.colors.ansi[colorIndex].css;
            ctx.fillText(String.fromCharCode(i), i * cellWidth, y);
            ctx.restore();
        }
    }
    ctx.restore();
    if (!('createImageBitmap' in context) || Browser_1.isFirefox) {
        if (canvas instanceof HTMLCanvasElement) {
            return canvas;
        }
        else {
            return new Promise(function (r) { return r(canvas.transferToImageBitmap()); });
        }
    }
    var charAtlasImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    var r = config.colors.background.rgba >>> 24;
    var g = config.colors.background.rgba >>> 16 & 0xFF;
    var b = config.colors.background.rgba >>> 8 & 0xFF;
    clearColor(charAtlasImageData, r, g, b);
    return context.createImageBitmap(charAtlasImageData);
}
exports.generateCharAtlas = generateCharAtlas;
function clearColor(imageData, r, g, b) {
    for (var offset = 0; offset < imageData.data.length; offset += 4) {
        if (imageData.data[offset] === r &&
            imageData.data[offset + 1] === g &&
            imageData.data[offset + 2] === b) {
            imageData.data[offset + 3] = 0;
        }
    }
}
function getFont(fontWeight, config) {
    return fontWeight + " " + config.fontSize * config.devicePixelRatio + "px " + config.fontFamily;
}

//# sourceMappingURL=CharAtlasGenerator.js.map


/***/ }),

/***/ "0Cz8":
/*!******************************************!*\
  !*** ./node_modules/lodash/_stackSet.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var ListCache = __webpack_require__(/*! ./_ListCache */ "Xi7e"),
    Map = __webpack_require__(/*! ./_Map */ "ebwN"),
    MapCache = __webpack_require__(/*! ./_MapCache */ "e4Nc");

/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;

/**
 * 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;
}

module.exports = stackSet;


/***/ }),

/***/ "0GgG":
/*!****************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeScatter3dIcon.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeScatter3dIcon = function TraceTypeScatter3dIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement('path', { fill: 'none', d: 'M0 0h46v46H0z' }),
        _react2.default.createElement('path', { fill: '#1d9bfb', stroke: '#1d9bfb', d: 'M23.511 23.571L9.516 30.045l13.929 6.319L37 30.045l-13.489-6.474z', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2' }),
        _react2.default.createElement('circle', { cx: '11', cy: '23', r: '2', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '16', cy: '28', r: '2', fill: '#25fdfc' }),
        _react2.default.createElement('circle', { cx: '16', cy: '15', r: '2', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '26', cy: '32', r: '2', fill: '#25fdfc' }),
        _react2.default.createElement('circle', { cx: '26', cy: '26', r: '2', fill: '#25fdfc' }),
        _react2.default.createElement('circle', { cx: '26', cy: '18', r: '2', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '26', cy: '10', r: '2', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '36', cy: '25', r: '2', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '36', cy: '19', r: '2', fill: '#1d9bfb' })
    );
};

exports.default = TraceTypeScatter3dIcon;

/***/ }),

/***/ "0HMq":
/*!***********************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/index.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ZoomboxIcon = exports.ZoomPlusIcon = exports.ZoomMinusIcon = exports.TraceTypeViolinIcon = exports.TraceTypeTimeSeriesIcon = exports.TraceTypeTableIcon = exports.TraceTypeSurfaceIcon = exports.TraceTypeStreamtubeIcon = exports.TraceTypeSplomIcon = undefined;
exports.TraceTypeScatterternaryIcon = exports.TraceTypeScatterpolarIcon = exports.TraceTypeScattermapboxIcon = exports.TraceTypeScattergeoIcon = exports.TraceTypeScatterIcon = exports.TraceTypeScatter3dIcon = exports.TraceTypeSankeyIcon = exports.TraceTypeRangeSliderIcon = exports.TraceTypePieIcon = exports.TraceTypeParcoordsIcon = exports.TraceTypeOhlcIcon = exports.TraceTypeMesh3dIcon = exports.TraceTypeLineIcon = exports.TraceTypeLine3dIcon = exports.TraceTypeHistogramIcon = exports.TraceTypeHistogram2dcontourIcon = exports.TraceTypeHistogram2dIcon = exports.TraceTypeHeatmapIcon = exports.TraceTypeErrorBarsIcon = exports.TraceTypeContourIcon = exports.TraceTypeConeIcon = exports.TraceTypeChoroplethIcon = exports.TraceTypeCarpetIcon = exports.TraceTypeCandlestickIcon = exports.TraceTypeBoxIcon = exports.TraceTypeBarpolarIcon = exports.TraceTypeBarIcon = exports.TraceTypeAreaIcon = exports.TraceTypeAnimationIcon = exports.TooltipCompareIcon = exports.TooltipBasicIcon = exports.SpikelineIcon = exports.ScriptIcon = exports.PlotVolume3dIcon = exports.PlotViolinIcon = exports.PlotTube3dIcon = exports.PlotTimeSeriesIcon = exports.PlotTernaryContourIcon = exports.PlotSurfaceIcon = exports.PlotStreamtubeIcon = exports.PlotStackedAreaIcon = exports.PlotSplomIcon = exports.PlotScatterternaryIcon = exports.PlotScatterpolarIcon = exports.PlotScattermapboxIcon = exports.PlotScattergeoIcon = exports.PlotScatterMatrixIcon = exports.PlotScatterIcon = exports.PlotScatterChartIcon = exports.PlotScatterAxesIcon = exports.PlotScatter3dIcon = exports.PlotSankeyIcon = exports.PlotRadarIcon = exports.PlotPolarFilledIcon = exports.PlotPieShadedIcon = exports.PlotPieIcon = exports.PlotParcoordsIcon = exports.PlotOhlcIcon = exports.PlotMesh3dIcon = exports.PlotMapLineIcon = exports.PlotLineMarkersIcon = exports.PlotLineIcon = exports.PlotLine3dIcon = exports.PlotIsosurface3dIcon = exports.PlotIcon = exports.PlotHistogramIcon = exports.PlotHistogram2dIcon = exports.PlotHistogram2dBricksIcon = exports.PlotHeatmapIcon = exports.PlotFitIcon = exports.PlotErrorBarsIcon = exports.PlotDonutIcon = exports.PlotContourIcon = exports.PlotConeIcon = exports.PlotCone3dIcon = exports.PlotChoroplethIcon = exports.PlotCarpetIcon = exports.PlotCandlestickIcon = exports.PlotCandlestickAltIcon = exports.PlotBubblesIcon = exports.PlotBoxIcon = exports.PlotBarpolarIcon = exports.PlotBarIcon = exports.PlotBarAxesIcon = exports.PlotAreaStackedIcon = exports.PlotAreaIcon = exports.PanIcon = exports.NotebookRIcon = exports.NotebookMIconIcon = exports.NotebookIpIcon = exports.LogoVisaIcon = exports.LogoStripeIcon = exports.LogoMastercardIcon = exports.LogoAmexIcon = exports.GearsSettingIcon = exports.ForkIcon = exports.ForkEditIcon = exports.FilingCabinetIcon = exports.EmbedIconIcon = exports.AutoscaleIcon = undefined;

var _AutoscaleIcon2 = __webpack_require__(/*! ./AutoscaleIcon.js */ "e7Py");

var _AutoscaleIcon3 = _interopRequireDefault(_AutoscaleIcon2);

var _EmbedIconIcon2 = __webpack_require__(/*! ./EmbedIconIcon.js */ "rS4v");

var _EmbedIconIcon3 = _interopRequireDefault(_EmbedIconIcon2);

var _FilingCabinetIcon2 = __webpack_require__(/*! ./FilingCabinetIcon.js */ "Oau+");

var _FilingCabinetIcon3 = _interopRequireDefault(_FilingCabinetIcon2);

var _ForkEditIcon2 = __webpack_require__(/*! ./ForkEditIcon.js */ "jWph");

var _ForkEditIcon3 = _interopRequireDefault(_ForkEditIcon2);

var _ForkIcon2 = __webpack_require__(/*! ./ForkIcon.js */ "mEBQ");

var _ForkIcon3 = _interopRequireDefault(_ForkIcon2);

var _GearsSettingIcon2 = __webpack_require__(/*! ./GearsSettingIcon.js */ "08JH");

var _GearsSettingIcon3 = _interopRequireDefault(_GearsSettingIcon2);

var _LogoAmexIcon2 = __webpack_require__(/*! ./LogoAmexIcon.js */ "4j1d");

var _LogoAmexIcon3 = _interopRequireDefault(_LogoAmexIcon2);

var _LogoMastercardIcon2 = __webpack_require__(/*! ./LogoMastercardIcon.js */ "EVUy");

var _LogoMastercardIcon3 = _interopRequireDefault(_LogoMastercardIcon2);

var _LogoStripeIcon2 = __webpack_require__(/*! ./LogoStripeIcon.js */ "/9oY");

var _LogoStripeIcon3 = _interopRequireDefault(_LogoStripeIcon2);

var _LogoVisaIcon2 = __webpack_require__(/*! ./LogoVisaIcon.js */ "Ze4w");

var _LogoVisaIcon3 = _interopRequireDefault(_LogoVisaIcon2);

var _NotebookIpIcon2 = __webpack_require__(/*! ./NotebookIpIcon.js */ "jWoU");

var _NotebookIpIcon3 = _interopRequireDefault(_NotebookIpIcon2);

var _NotebookMIconIcon2 = __webpack_require__(/*! ./NotebookMIconIcon.js */ "yuBE");

var _NotebookMIconIcon3 = _interopRequireDefault(_NotebookMIconIcon2);

var _NotebookRIcon2 = __webpack_require__(/*! ./NotebookRIcon.js */ "I0Qy");

var _NotebookRIcon3 = _interopRequireDefault(_NotebookRIcon2);

var _PanIcon2 = __webpack_require__(/*! ./PanIcon.js */ "ia9w");

var _PanIcon3 = _interopRequireDefault(_PanIcon2);

var _PlotAreaIcon2 = __webpack_require__(/*! ./PlotAreaIcon.js */ "fL/d");

var _PlotAreaIcon3 = _interopRequireDefault(_PlotAreaIcon2);

var _PlotAreaStackedIcon2 = __webpack_require__(/*! ./PlotAreaStackedIcon.js */ "wKab");

var _PlotAreaStackedIcon3 = _interopRequireDefault(_PlotAreaStackedIcon2);

var _PlotBarAxesIcon2 = __webpack_require__(/*! ./PlotBarAxesIcon.js */ "h2ac");

var _PlotBarAxesIcon3 = _interopRequireDefault(_PlotBarAxesIcon2);

var _PlotBarIcon2 = __webpack_require__(/*! ./PlotBarIcon.js */ "fbbY");

var _PlotBarIcon3 = _interopRequireDefault(_PlotBarIcon2);

var _PlotBarpolarIcon2 = __webpack_require__(/*! ./PlotBarpolarIcon.js */ "1K7F");

var _PlotBarpolarIcon3 = _interopRequireDefault(_PlotBarpolarIcon2);

var _PlotBoxIcon2 = __webpack_require__(/*! ./PlotBoxIcon.js */ "GOc5");

var _PlotBoxIcon3 = _interopRequireDefault(_PlotBoxIcon2);

var _PlotBubblesIcon2 = __webpack_require__(/*! ./PlotBubblesIcon.js */ "RjN7");

var _PlotBubblesIcon3 = _interopRequireDefault(_PlotBubblesIcon2);

var _PlotCandlestickAltIcon2 = __webpack_require__(/*! ./PlotCandlestickAltIcon.js */ "HtHp");

var _PlotCandlestickAltIcon3 = _interopRequireDefault(_PlotCandlestickAltIcon2);

var _PlotCandlestickIcon2 = __webpack_require__(/*! ./PlotCandlestickIcon.js */ "4xm7");

var _PlotCandlestickIcon3 = _interopRequireDefault(_PlotCandlestickIcon2);

var _PlotCarpetIcon2 = __webpack_require__(/*! ./PlotCarpetIcon.js */ "EQzv");

var _PlotCarpetIcon3 = _interopRequireDefault(_PlotCarpetIcon2);

var _PlotChoroplethIcon2 = __webpack_require__(/*! ./PlotChoroplethIcon.js */ "6enh");

var _PlotChoroplethIcon3 = _interopRequireDefault(_PlotChoroplethIcon2);

var _PlotCone3dIcon2 = __webpack_require__(/*! ./PlotCone3dIcon.js */ "vGKN");

var _PlotCone3dIcon3 = _interopRequireDefault(_PlotCone3dIcon2);

var _PlotConeIcon2 = __webpack_require__(/*! ./PlotConeIcon.js */ "zBpB");

var _PlotConeIcon3 = _interopRequireDefault(_PlotConeIcon2);

var _PlotContourIcon2 = __webpack_require__(/*! ./PlotContourIcon.js */ "Ka7v");

var _PlotContourIcon3 = _interopRequireDefault(_PlotContourIcon2);

var _PlotDonutIcon2 = __webpack_require__(/*! ./PlotDonutIcon.js */ "8F98");

var _PlotDonutIcon3 = _interopRequireDefault(_PlotDonutIcon2);

var _PlotErrorBarsIcon2 = __webpack_require__(/*! ./PlotErrorBarsIcon.js */ "hoXd");

var _PlotErrorBarsIcon3 = _interopRequireDefault(_PlotErrorBarsIcon2);

var _PlotFitIcon2 = __webpack_require__(/*! ./PlotFitIcon.js */ "ONRs");

var _PlotFitIcon3 = _interopRequireDefault(_PlotFitIcon2);

var _PlotHeatmapIcon2 = __webpack_require__(/*! ./PlotHeatmapIcon.js */ "kdwK");

var _PlotHeatmapIcon3 = _interopRequireDefault(_PlotHeatmapIcon2);

var _PlotHistogram2dBricksIcon2 = __webpack_require__(/*! ./PlotHistogram2dBricksIcon.js */ "ANZy");

var _PlotHistogram2dBricksIcon3 = _interopRequireDefault(_PlotHistogram2dBricksIcon2);

var _PlotHistogram2dIcon2 = __webpack_require__(/*! ./PlotHistogram2dIcon.js */ "e7Ga");

var _PlotHistogram2dIcon3 = _interopRequireDefault(_PlotHistogram2dIcon2);

var _PlotHistogramIcon2 = __webpack_require__(/*! ./PlotHistogramIcon.js */ "0PYM");

var _PlotHistogramIcon3 = _interopRequireDefault(_PlotHistogramIcon2);

var _PlotIcon2 = __webpack_require__(/*! ./PlotIcon.js */ "9E94");

var _PlotIcon3 = _interopRequireDefault(_PlotIcon2);

var _PlotIsosurface3dIcon2 = __webpack_require__(/*! ./PlotIsosurface3dIcon.js */ "FcJ0");

var _PlotIsosurface3dIcon3 = _interopRequireDefault(_PlotIsosurface3dIcon2);

var _PlotLine3dIcon2 = __webpack_require__(/*! ./PlotLine3dIcon.js */ "pocu");

var _PlotLine3dIcon3 = _interopRequireDefault(_PlotLine3dIcon2);

var _PlotLineIcon2 = __webpack_require__(/*! ./PlotLineIcon.js */ "27E4");

var _PlotLineIcon3 = _interopRequireDefault(_PlotLineIcon2);

var _PlotLineMarkersIcon2 = __webpack_require__(/*! ./PlotLineMarkersIcon.js */ "1Jac");

var _PlotLineMarkersIcon3 = _interopRequireDefault(_PlotLineMarkersIcon2);

var _PlotMapLineIcon2 = __webpack_require__(/*! ./PlotMapLineIcon.js */ "gHr8");

var _PlotMapLineIcon3 = _interopRequireDefault(_PlotMapLineIcon2);

var _PlotMesh3dIcon2 = __webpack_require__(/*! ./PlotMesh3dIcon.js */ "ajAQ");

var _PlotMesh3dIcon3 = _interopRequireDefault(_PlotMesh3dIcon2);

var _PlotOhlcIcon2 = __webpack_require__(/*! ./PlotOhlcIcon.js */ "MlIt");

var _PlotOhlcIcon3 = _interopRequireDefault(_PlotOhlcIcon2);

var _PlotParcoordsIcon2 = __webpack_require__(/*! ./PlotParcoordsIcon.js */ "IXoA");

var _PlotParcoordsIcon3 = _interopRequireDefault(_PlotParcoordsIcon2);

var _PlotPieIcon2 = __webpack_require__(/*! ./PlotPieIcon.js */ "0yVM");

var _PlotPieIcon3 = _interopRequireDefault(_PlotPieIcon2);

var _PlotPieShadedIcon2 = __webpack_require__(/*! ./PlotPieShadedIcon.js */ "BIsW");

var _PlotPieShadedIcon3 = _interopRequireDefault(_PlotPieShadedIcon2);

var _PlotPolarFilledIcon2 = __webpack_require__(/*! ./PlotPolarFilledIcon.js */ "3W1w");

var _PlotPolarFilledIcon3 = _interopRequireDefault(_PlotPolarFilledIcon2);

var _PlotRadarIcon2 = __webpack_require__(/*! ./PlotRadarIcon.js */ "i9Oj");

var _PlotRadarIcon3 = _interopRequireDefault(_PlotRadarIcon2);

var _PlotSankeyIcon2 = __webpack_require__(/*! ./PlotSankeyIcon.js */ "mz0i");

var _PlotSankeyIcon3 = _interopRequireDefault(_PlotSankeyIcon2);

var _PlotScatter3dIcon2 = __webpack_require__(/*! ./PlotScatter3dIcon.js */ "CPRm");

var _PlotScatter3dIcon3 = _interopRequireDefault(_PlotScatter3dIcon2);

var _PlotScatterAxesIcon2 = __webpack_require__(/*! ./PlotScatterAxesIcon.js */ "lx3m");

var _PlotScatterAxesIcon3 = _interopRequireDefault(_PlotScatterAxesIcon2);

var _PlotScatterChartIcon2 = __webpack_require__(/*! ./PlotScatterChartIcon.js */ "wwzI");

var _PlotScatterChartIcon3 = _interopRequireDefault(_PlotScatterChartIcon2);

var _PlotScatterIcon2 = __webpack_require__(/*! ./PlotScatterIcon.js */ "4pnw");

var _PlotScatterIcon3 = _interopRequireDefault(_PlotScatterIcon2);

var _PlotScatterMatrixIcon2 = __webpack_require__(/*! ./PlotScatterMatrixIcon.js */ "0zcU");

var _PlotScatterMatrixIcon3 = _interopRequireDefault(_PlotScatterMatrixIcon2);

var _PlotScattergeoIcon2 = __webpack_require__(/*! ./PlotScattergeoIcon.js */ "zAxo");

var _PlotScattergeoIcon3 = _interopRequireDefault(_PlotScattergeoIcon2);

var _PlotScattermapboxIcon2 = __webpack_require__(/*! ./PlotScattermapboxIcon.js */ "glbb");

var _PlotScattermapboxIcon3 = _interopRequireDefault(_PlotScattermapboxIcon2);

var _PlotScatterpolarIcon2 = __webpack_require__(/*! ./PlotScatterpolarIcon.js */ "FSmo");

var _PlotScatterpolarIcon3 = _interopRequireDefault(_PlotScatterpolarIcon2);

var _PlotScatterternaryIcon2 = __webpack_require__(/*! ./PlotScatterternaryIcon.js */ "oeIe");

var _PlotScatterternaryIcon3 = _interopRequireDefault(_PlotScatterternaryIcon2);

var _PlotSplomIcon2 = __webpack_require__(/*! ./PlotSplomIcon.js */ "0QlZ");

var _PlotSplomIcon3 = _interopRequireDefault(_PlotSplomIcon2);

var _PlotStackedAreaIcon2 = __webpack_require__(/*! ./PlotStackedAreaIcon.js */ "aD8L");

var _PlotStackedAreaIcon3 = _interopRequireDefault(_PlotStackedAreaIcon2);

var _PlotStreamtubeIcon2 = __webpack_require__(/*! ./PlotStreamtubeIcon.js */ "e2yc");

var _PlotStreamtubeIcon3 = _interopRequireDefault(_PlotStreamtubeIcon2);

var _PlotSurfaceIcon2 = __webpack_require__(/*! ./PlotSurfaceIcon.js */ "3MVk");

var _PlotSurfaceIcon3 = _interopRequireDefault(_PlotSurfaceIcon2);

var _PlotTernaryContourIcon2 = __webpack_require__(/*! ./PlotTernaryContourIcon.js */ "bXTP");

var _PlotTernaryContourIcon3 = _interopRequireDefault(_PlotTernaryContourIcon2);

var _PlotTimeSeriesIcon2 = __webpack_require__(/*! ./PlotTimeSeriesIcon.js */ "GMnZ");

var _PlotTimeSeriesIcon3 = _interopRequireDefault(_PlotTimeSeriesIcon2);

var _PlotTube3dIcon2 = __webpack_require__(/*! ./PlotTube3dIcon.js */ "hVAS");

var _PlotTube3dIcon3 = _interopRequireDefault(_PlotTube3dIcon2);

var _PlotViolinIcon2 = __webpack_require__(/*! ./PlotViolinIcon.js */ "xqmc");

var _PlotViolinIcon3 = _interopRequireDefault(_PlotViolinIcon2);

var _PlotVolume3dIcon2 = __webpack_require__(/*! ./PlotVolume3dIcon.js */ "o/tr");

var _PlotVolume3dIcon3 = _interopRequireDefault(_PlotVolume3dIcon2);

var _ScriptIcon2 = __webpack_require__(/*! ./ScriptIcon.js */ "mwTM");

var _ScriptIcon3 = _interopRequireDefault(_ScriptIcon2);

var _SpikelineIcon2 = __webpack_require__(/*! ./SpikelineIcon.js */ "le5Z");

var _SpikelineIcon3 = _interopRequireDefault(_SpikelineIcon2);

var _TooltipBasicIcon2 = __webpack_require__(/*! ./TooltipBasicIcon.js */ "/kYb");

var _TooltipBasicIcon3 = _interopRequireDefault(_TooltipBasicIcon2);

var _TooltipCompareIcon2 = __webpack_require__(/*! ./TooltipCompareIcon.js */ "tKF0");

var _TooltipCompareIcon3 = _interopRequireDefault(_TooltipCompareIcon2);

var _TraceTypeAnimationIcon2 = __webpack_require__(/*! ./TraceTypeAnimationIcon.js */ "+aMc");

var _TraceTypeAnimationIcon3 = _interopRequireDefault(_TraceTypeAnimationIcon2);

var _TraceTypeAreaIcon2 = __webpack_require__(/*! ./TraceTypeAreaIcon.js */ "j/+3");

var _TraceTypeAreaIcon3 = _interopRequireDefault(_TraceTypeAreaIcon2);

var _TraceTypeBarIcon2 = __webpack_require__(/*! ./TraceTypeBarIcon.js */ "g8L2");

var _TraceTypeBarIcon3 = _interopRequireDefault(_TraceTypeBarIcon2);

var _TraceTypeBarpolarIcon2 = __webpack_require__(/*! ./TraceTypeBarpolarIcon.js */ "GWQT");

var _TraceTypeBarpolarIcon3 = _interopRequireDefault(_TraceTypeBarpolarIcon2);

var _TraceTypeBoxIcon2 = __webpack_require__(/*! ./TraceTypeBoxIcon.js */ "OTJG");

var _TraceTypeBoxIcon3 = _interopRequireDefault(_TraceTypeBoxIcon2);

var _TraceTypeCandlestickIcon2 = __webpack_require__(/*! ./TraceTypeCandlestickIcon.js */ "Jrif");

var _TraceTypeCandlestickIcon3 = _interopRequireDefault(_TraceTypeCandlestickIcon2);

var _TraceTypeCarpetIcon2 = __webpack_require__(/*! ./TraceTypeCarpetIcon.js */ "25UF");

var _TraceTypeCarpetIcon3 = _interopRequireDefault(_TraceTypeCarpetIcon2);

var _TraceTypeChoroplethIcon2 = __webpack_require__(/*! ./TraceTypeChoroplethIcon.js */ "3QZj");

var _TraceTypeChoroplethIcon3 = _interopRequireDefault(_TraceTypeChoroplethIcon2);

var _TraceTypeConeIcon2 = __webpack_require__(/*! ./TraceTypeConeIcon.js */ "aqbM");

var _TraceTypeConeIcon3 = _interopRequireDefault(_TraceTypeConeIcon2);

var _TraceTypeContourIcon2 = __webpack_require__(/*! ./TraceTypeContourIcon.js */ "+P8q");

var _TraceTypeContourIcon3 = _interopRequireDefault(_TraceTypeContourIcon2);

var _TraceTypeErrorBarsIcon2 = __webpack_require__(/*! ./TraceTypeErrorBarsIcon.js */ "y4Pm");

var _TraceTypeErrorBarsIcon3 = _interopRequireDefault(_TraceTypeErrorBarsIcon2);

var _TraceTypeHeatmapIcon2 = __webpack_require__(/*! ./TraceTypeHeatmapIcon.js */ "n8IF");

var _TraceTypeHeatmapIcon3 = _interopRequireDefault(_TraceTypeHeatmapIcon2);

var _TraceTypeHistogram2dIcon2 = __webpack_require__(/*! ./TraceTypeHistogram2dIcon.js */ "JmEZ");

var _TraceTypeHistogram2dIcon3 = _interopRequireDefault(_TraceTypeHistogram2dIcon2);

var _TraceTypeHistogram2dcontourIcon2 = __webpack_require__(/*! ./TraceTypeHistogram2dcontourIcon.js */ "s7xW");

var _TraceTypeHistogram2dcontourIcon3 = _interopRequireDefault(_TraceTypeHistogram2dcontourIcon2);

var _TraceTypeHistogramIcon2 = __webpack_require__(/*! ./TraceTypeHistogramIcon.js */ "aF6S");

var _TraceTypeHistogramIcon3 = _interopRequireDefault(_TraceTypeHistogramIcon2);

var _TraceTypeLine3dIcon2 = __webpack_require__(/*! ./TraceTypeLine3dIcon.js */ "hKML");

var _TraceTypeLine3dIcon3 = _interopRequireDefault(_TraceTypeLine3dIcon2);

var _TraceTypeLineIcon2 = __webpack_require__(/*! ./TraceTypeLineIcon.js */ "A1k/");

var _TraceTypeLineIcon3 = _interopRequireDefault(_TraceTypeLineIcon2);

var _TraceTypeMesh3dIcon2 = __webpack_require__(/*! ./TraceTypeMesh3dIcon.js */ "fFD0");

var _TraceTypeMesh3dIcon3 = _interopRequireDefault(_TraceTypeMesh3dIcon2);

var _TraceTypeOhlcIcon2 = __webpack_require__(/*! ./TraceTypeOhlcIcon.js */ "O4+9");

var _TraceTypeOhlcIcon3 = _interopRequireDefault(_TraceTypeOhlcIcon2);

var _TraceTypeParcoordsIcon2 = __webpack_require__(/*! ./TraceTypeParcoordsIcon.js */ "4YDR");

var _TraceTypeParcoordsIcon3 = _interopRequireDefault(_TraceTypeParcoordsIcon2);

var _TraceTypePieIcon2 = __webpack_require__(/*! ./TraceTypePieIcon.js */ "i2zi");

var _TraceTypePieIcon3 = _interopRequireDefault(_TraceTypePieIcon2);

var _TraceTypeRangeSliderIcon2 = __webpack_require__(/*! ./TraceTypeRangeSliderIcon.js */ "y1J4");

var _TraceTypeRangeSliderIcon3 = _interopRequireDefault(_TraceTypeRangeSliderIcon2);

var _TraceTypeSankeyIcon2 = __webpack_require__(/*! ./TraceTypeSankeyIcon.js */ "ilay");

var _TraceTypeSankeyIcon3 = _interopRequireDefault(_TraceTypeSankeyIcon2);

var _TraceTypeScatter3dIcon2 = __webpack_require__(/*! ./TraceTypeScatter3dIcon.js */ "0GgG");

var _TraceTypeScatter3dIcon3 = _interopRequireDefault(_TraceTypeScatter3dIcon2);

var _TraceTypeScatterIcon2 = __webpack_require__(/*! ./TraceTypeScatterIcon.js */ "hZ7w");

var _TraceTypeScatterIcon3 = _interopRequireDefault(_TraceTypeScatterIcon2);

var _TraceTypeScattergeoIcon2 = __webpack_require__(/*! ./TraceTypeScattergeoIcon.js */ "KQs1");

var _TraceTypeScattergeoIcon3 = _interopRequireDefault(_TraceTypeScattergeoIcon2);

var _TraceTypeScattermapboxIcon2 = __webpack_require__(/*! ./TraceTypeScattermapboxIcon.js */ "ubbP");

var _TraceTypeScattermapboxIcon3 = _interopRequireDefault(_TraceTypeScattermapboxIcon2);

var _TraceTypeScatterpolarIcon2 = __webpack_require__(/*! ./TraceTypeScatterpolarIcon.js */ "9Rdn");

var _TraceTypeScatterpolarIcon3 = _interopRequireDefault(_TraceTypeScatterpolarIcon2);

var _TraceTypeScatterternaryIcon2 = __webpack_require__(/*! ./TraceTypeScatterternaryIcon.js */ "hiFl");

var _TraceTypeScatterternaryIcon3 = _interopRequireDefault(_TraceTypeScatterternaryIcon2);

var _TraceTypeSplomIcon2 = __webpack_require__(/*! ./TraceTypeSplomIcon.js */ "zOct");

var _TraceTypeSplomIcon3 = _interopRequireDefault(_TraceTypeSplomIcon2);

var _TraceTypeStreamtubeIcon2 = __webpack_require__(/*! ./TraceTypeStreamtubeIcon.js */ "om78");

var _TraceTypeStreamtubeIcon3 = _interopRequireDefault(_TraceTypeStreamtubeIcon2);

var _TraceTypeSurfaceIcon2 = __webpack_require__(/*! ./TraceTypeSurfaceIcon.js */ "wI5Q");

var _TraceTypeSurfaceIcon3 = _interopRequireDefault(_TraceTypeSurfaceIcon2);

var _TraceTypeTableIcon2 = __webpack_require__(/*! ./TraceTypeTableIcon.js */ "TpJo");

var _TraceTypeTableIcon3 = _interopRequireDefault(_TraceTypeTableIcon2);

var _TraceTypeTimeSeriesIcon2 = __webpack_require__(/*! ./TraceTypeTimeSeriesIcon.js */ "diG1");

var _TraceTypeTimeSeriesIcon3 = _interopRequireDefault(_TraceTypeTimeSeriesIcon2);

var _TraceTypeViolinIcon2 = __webpack_require__(/*! ./TraceTypeViolinIcon.js */ "Qna6");

var _TraceTypeViolinIcon3 = _interopRequireDefault(_TraceTypeViolinIcon2);

var _ZoomMinusIcon2 = __webpack_require__(/*! ./ZoomMinusIcon.js */ "taFK");

var _ZoomMinusIcon3 = _interopRequireDefault(_ZoomMinusIcon2);

var _ZoomPlusIcon2 = __webpack_require__(/*! ./ZoomPlusIcon.js */ "+LWr");

var _ZoomPlusIcon3 = _interopRequireDefault(_ZoomPlusIcon2);

var _ZoomboxIcon2 = __webpack_require__(/*! ./ZoomboxIcon.js */ "0AFT");

var _ZoomboxIcon3 = _interopRequireDefault(_ZoomboxIcon2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.AutoscaleIcon = _AutoscaleIcon3.default;
exports.EmbedIconIcon = _EmbedIconIcon3.default;
exports.FilingCabinetIcon = _FilingCabinetIcon3.default;
exports.ForkEditIcon = _ForkEditIcon3.default;
exports.ForkIcon = _ForkIcon3.default;
exports.GearsSettingIcon = _GearsSettingIcon3.default;
exports.LogoAmexIcon = _LogoAmexIcon3.default;
exports.LogoMastercardIcon = _LogoMastercardIcon3.default;
exports.LogoStripeIcon = _LogoStripeIcon3.default;
exports.LogoVisaIcon = _LogoVisaIcon3.default;
exports.NotebookIpIcon = _NotebookIpIcon3.default;
exports.NotebookMIconIcon = _NotebookMIconIcon3.default;
exports.NotebookRIcon = _NotebookRIcon3.default;
exports.PanIcon = _PanIcon3.default;
exports.PlotAreaIcon = _PlotAreaIcon3.default;
exports.PlotAreaStackedIcon = _PlotAreaStackedIcon3.default;
exports.PlotBarAxesIcon = _PlotBarAxesIcon3.default;
exports.PlotBarIcon = _PlotBarIcon3.default;
exports.PlotBarpolarIcon = _PlotBarpolarIcon3.default;
exports.PlotBoxIcon = _PlotBoxIcon3.default;
exports.PlotBubblesIcon = _PlotBubblesIcon3.default;
exports.PlotCandlestickAltIcon = _PlotCandlestickAltIcon3.default;
exports.PlotCandlestickIcon = _PlotCandlestickIcon3.default;
exports.PlotCarpetIcon = _PlotCarpetIcon3.default;
exports.PlotChoroplethIcon = _PlotChoroplethIcon3.default;
exports.PlotCone3dIcon = _PlotCone3dIcon3.default;
exports.PlotConeIcon = _PlotConeIcon3.default;
exports.PlotContourIcon = _PlotContourIcon3.default;
exports.PlotDonutIcon = _PlotDonutIcon3.default;
exports.PlotErrorBarsIcon = _PlotErrorBarsIcon3.default;
exports.PlotFitIcon = _PlotFitIcon3.default;
exports.PlotHeatmapIcon = _PlotHeatmapIcon3.default;
exports.PlotHistogram2dBricksIcon = _PlotHistogram2dBricksIcon3.default;
exports.PlotHistogram2dIcon = _PlotHistogram2dIcon3.default;
exports.PlotHistogramIcon = _PlotHistogramIcon3.default;
exports.PlotIcon = _PlotIcon3.default;
exports.PlotIsosurface3dIcon = _PlotIsosurface3dIcon3.default;
exports.PlotLine3dIcon = _PlotLine3dIcon3.default;
exports.PlotLineIcon = _PlotLineIcon3.default;
exports.PlotLineMarkersIcon = _PlotLineMarkersIcon3.default;
exports.PlotMapLineIcon = _PlotMapLineIcon3.default;
exports.PlotMesh3dIcon = _PlotMesh3dIcon3.default;
exports.PlotOhlcIcon = _PlotOhlcIcon3.default;
exports.PlotParcoordsIcon = _PlotParcoordsIcon3.default;
exports.PlotPieIcon = _PlotPieIcon3.default;
exports.PlotPieShadedIcon = _PlotPieShadedIcon3.default;
exports.PlotPolarFilledIcon = _PlotPolarFilledIcon3.default;
exports.PlotRadarIcon = _PlotRadarIcon3.default;
exports.PlotSankeyIcon = _PlotSankeyIcon3.default;
exports.PlotScatter3dIcon = _PlotScatter3dIcon3.default;
exports.PlotScatterAxesIcon = _PlotScatterAxesIcon3.default;
exports.PlotScatterChartIcon = _PlotScatterChartIcon3.default;
exports.PlotScatterIcon = _PlotScatterIcon3.default;
exports.PlotScatterMatrixIcon = _PlotScatterMatrixIcon3.default;
exports.PlotScattergeoIcon = _PlotScattergeoIcon3.default;
exports.PlotScattermapboxIcon = _PlotScattermapboxIcon3.default;
exports.PlotScatterpolarIcon = _PlotScatterpolarIcon3.default;
exports.PlotScatterternaryIcon = _PlotScatterternaryIcon3.default;
exports.PlotSplomIcon = _PlotSplomIcon3.default;
exports.PlotStackedAreaIcon = _PlotStackedAreaIcon3.default;
exports.PlotStreamtubeIcon = _PlotStreamtubeIcon3.default;
exports.PlotSurfaceIcon = _PlotSurfaceIcon3.default;
exports.PlotTernaryContourIcon = _PlotTernaryContourIcon3.default;
exports.PlotTimeSeriesIcon = _PlotTimeSeriesIcon3.default;
exports.PlotTube3dIcon = _PlotTube3dIcon3.default;
exports.PlotViolinIcon = _PlotViolinIcon3.default;
exports.PlotVolume3dIcon = _PlotVolume3dIcon3.default;
exports.ScriptIcon = _ScriptIcon3.default;
exports.SpikelineIcon = _SpikelineIcon3.default;
exports.TooltipBasicIcon = _TooltipBasicIcon3.default;
exports.TooltipCompareIcon = _TooltipCompareIcon3.default;
exports.TraceTypeAnimationIcon = _TraceTypeAnimationIcon3.default;
exports.TraceTypeAreaIcon = _TraceTypeAreaIcon3.default;
exports.TraceTypeBarIcon = _TraceTypeBarIcon3.default;
exports.TraceTypeBarpolarIcon = _TraceTypeBarpolarIcon3.default;
exports.TraceTypeBoxIcon = _TraceTypeBoxIcon3.default;
exports.TraceTypeCandlestickIcon = _TraceTypeCandlestickIcon3.default;
exports.TraceTypeCarpetIcon = _TraceTypeCarpetIcon3.default;
exports.TraceTypeChoroplethIcon = _TraceTypeChoroplethIcon3.default;
exports.TraceTypeConeIcon = _TraceTypeConeIcon3.default;
exports.TraceTypeContourIcon = _TraceTypeContourIcon3.default;
exports.TraceTypeErrorBarsIcon = _TraceTypeErrorBarsIcon3.default;
exports.TraceTypeHeatmapIcon = _TraceTypeHeatmapIcon3.default;
exports.TraceTypeHistogram2dIcon = _TraceTypeHistogram2dIcon3.default;
exports.TraceTypeHistogram2dcontourIcon = _TraceTypeHistogram2dcontourIcon3.default;
exports.TraceTypeHistogramIcon = _TraceTypeHistogramIcon3.default;
exports.TraceTypeLine3dIcon = _TraceTypeLine3dIcon3.default;
exports.TraceTypeLineIcon = _TraceTypeLineIcon3.default;
exports.TraceTypeMesh3dIcon = _TraceTypeMesh3dIcon3.default;
exports.TraceTypeOhlcIcon = _TraceTypeOhlcIcon3.default;
exports.TraceTypeParcoordsIcon = _TraceTypeParcoordsIcon3.default;
exports.TraceTypePieIcon = _TraceTypePieIcon3.default;
exports.TraceTypeRangeSliderIcon = _TraceTypeRangeSliderIcon3.default;
exports.TraceTypeSankeyIcon = _TraceTypeSankeyIcon3.default;
exports.TraceTypeScatter3dIcon = _TraceTypeScatter3dIcon3.default;
exports.TraceTypeScatterIcon = _TraceTypeScatterIcon3.default;
exports.TraceTypeScattergeoIcon = _TraceTypeScattergeoIcon3.default;
exports.TraceTypeScattermapboxIcon = _TraceTypeScattermapboxIcon3.default;
exports.TraceTypeScatterpolarIcon = _TraceTypeScatterpolarIcon3.default;
exports.TraceTypeScatterternaryIcon = _TraceTypeScatterternaryIcon3.default;
exports.TraceTypeSplomIcon = _TraceTypeSplomIcon3.default;
exports.TraceTypeStreamtubeIcon = _TraceTypeStreamtubeIcon3.default;
exports.TraceTypeSurfaceIcon = _TraceTypeSurfaceIcon3.default;
exports.TraceTypeTableIcon = _TraceTypeTableIcon3.default;
exports.TraceTypeTimeSeriesIcon = _TraceTypeTimeSeriesIcon3.default;
exports.TraceTypeViolinIcon = _TraceTypeViolinIcon3.default;
exports.ZoomMinusIcon = _ZoomMinusIcon3.default;
exports.ZoomPlusIcon = _ZoomPlusIcon3.default;
exports.ZoomboxIcon = _ZoomboxIcon3.default;

/***/ }),

/***/ "0KId":
/*!*******************************************************************!*\
  !*** ./node_modules/@jupyterlab/coreutils/lib/settingregistry.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const ajv_1 = __importDefault(__webpack_require__(/*! ajv */ "eDuk"));
const json = __importStar(__webpack_require__(/*! comment-json */ "01LB"));
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
/**
 * The key in the schema for setting editor icon class hints.
 */
exports.ICON_CLASS_KEY = 'jupyter.lab.setting-icon-class';
/**
 * The key in the schema for setting editor icon label hints.
 */
exports.ICON_LABEL_KEY = 'jupyter.lab.setting-icon-label';
/**
 * An alias for the JSON deep copy function.
 */
const copy = coreutils_1.JSONExt.deepCopy;
/* tslint:disable */
/**
 * The setting registry token.
 */
exports.ISettingRegistry = new coreutils_1.Token('@jupyterlab/coreutils:ISettingRegistry');
/**
 * The default implementation of a schema validator.
 */
class DefaultSchemaValidator {
    /**
     * Instantiate a schema validator.
     */
    constructor() {
        this._composer = new ajv_1.default({ useDefaults: true });
        this._validator = new ajv_1.default();
        this._composer.addSchema(Private.SCHEMA, 'main');
        this._validator.addSchema(Private.SCHEMA, 'main');
    }
    /**
     * Validate a plugin's schema and user data; populate the `composite` data.
     *
     * @param plugin - The plugin being validated. Its `composite` data will be
     * populated by reference.
     *
     * @param populate - Whether plugin data should be populated, defaults to
     * `true`.
     *
     * @return A list of errors if either the schema or data fail to validate or
     * `null` if there are no errors.
     */
    validateData(plugin, populate = true) {
        const validate = this._validator.getSchema(plugin.id);
        const compose = this._composer.getSchema(plugin.id);
        // If the schemas do not exist, add them to the validator and continue.
        if (!validate || !compose) {
            const errors = this._addSchema(plugin.id, plugin.schema);
            if (errors) {
                return errors;
            }
            return this.validateData(plugin);
        }
        // Parse the raw commented JSON into a user map.
        let user;
        try {
            const strip = true;
            user = json.parse(plugin.raw, null, strip);
        }
        catch (error) {
            if (error instanceof SyntaxError) {
                return [
                    {
                        dataPath: '',
                        keyword: 'syntax',
                        schemaPath: '',
                        message: error.message
                    }
                ];
            }
            const { column, description } = error;
            const line = error.lineNumber;
            return [
                {
                    dataPath: '',
                    keyword: 'parse',
                    schemaPath: '',
                    message: `${description} (line ${line} column ${column})`
                }
            ];
        }
        if (!validate(user)) {
            return validate.errors;
        }
        // Copy the user data before merging defaults into composite map.
        const composite = copy(user);
        if (!compose(composite)) {
            return compose.errors;
        }
        if (populate) {
            plugin.data = { composite, user };
        }
        return null;
    }
    /**
     * Add a schema to the validator.
     *
     * @param plugin - The plugin ID.
     *
     * @param schema - The schema being added.
     *
     * @return A list of errors if the schema fails to validate or `null` if there
     * are no errors.
     *
     * #### Notes
     * It is safe to call this function multiple times with the same plugin name.
     */
    _addSchema(plugin, schema) {
        const composer = this._composer;
        const validator = this._validator;
        const validate = validator.getSchema('main');
        // Validate against the main schema.
        if (!validate(schema)) {
            return validate.errors;
        }
        // Validate against the JSON schema meta-schema.
        if (!validator.validateSchema(schema)) {
            return validator.errors;
        }
        // Remove if schema already exists.
        composer.removeSchema(plugin);
        validator.removeSchema(plugin);
        // Add schema to the validator and composer.
        composer.addSchema(schema, plugin);
        validator.addSchema(schema, plugin);
        return null;
    }
}
exports.DefaultSchemaValidator = DefaultSchemaValidator;
/**
 * The default concrete implementation of a setting registry.
 */
class SettingRegistry {
    /**
     * Create a new setting registry.
     */
    constructor(options) {
        /**
         * The schema of the setting registry.
         */
        this.schema = Private.SCHEMA;
        this._pluginChanged = new signaling_1.Signal(this);
        this._plugins = Object.create(null);
        this._connector = options.connector;
        this.validator = options.validator || new DefaultSchemaValidator();
    }
    /**
     * A signal that emits the name of a plugin when its settings change.
     */
    get pluginChanged() {
        return this._pluginChanged;
    }
    /**
     * Returns a list of plugin settings held in the registry.
     */
    get plugins() {
        const plugins = this._plugins;
        return Object.keys(plugins).map(p => copy(plugins[p]));
    }
    /**
     * Get an individual setting.
     *
     * @param plugin - The name of the plugin whose settings are being retrieved.
     *
     * @param key - The name of the setting being retrieved.
     *
     * @returns A promise that resolves when the setting is retrieved.
     */
    get(plugin, key) {
        const plugins = this._plugins;
        if (plugin in plugins) {
            const { composite, user } = plugins[plugin].data;
            const result = {
                composite: key in composite ? copy(composite[key]) : undefined,
                user: key in user ? copy(user[key]) : undefined
            };
            return Promise.resolve(result);
        }
        return this.load(plugin).then(() => this.get(plugin, key));
    }
    /**
     * Load a plugin's settings into the setting registry.
     *
     * @param plugin - The name of the plugin whose settings are being loaded.
     *
     * @returns A promise that resolves with a plugin settings object or rejects
     * if the plugin is not found.
     */
    load(plugin) {
        const plugins = this._plugins;
        const registry = this;
        // If the plugin exists, resolve.
        if (plugin in plugins) {
            const settings = new Settings({ plugin: plugins[plugin], registry });
            return Promise.resolve(settings);
        }
        // If the plugin needs to be loaded from the data connector, fetch.
        return this.reload(plugin);
    }
    /**
     * Reload a plugin's settings into the registry even if they already exist.
     *
     * @param plugin - The name of the plugin whose settings are being reloaded.
     *
     * @returns A promise that resolves with a plugin settings object or rejects
     * with a list of `ISchemaValidator.IError` objects if it fails.
     */
    reload(plugin) {
        const connector = this._connector;
        const plugins = this._plugins;
        const registry = this;
        // If the plugin needs to be loaded from the connector, fetch.
        return connector.fetch(plugin).then(data => {
            // Validate the response from the connector; populate `composite` field.
            try {
                this._validate(data);
            }
            catch (errors) {
                const output = [`Validating ${plugin} failed:`];
                errors.forEach((error, index) => {
                    const { dataPath, schemaPath, keyword, message } = error;
                    output.push(`${index} - schema @ ${schemaPath}, data @ ${dataPath}`);
                    output.push(`\t${keyword} ${message}`);
                });
                console.error(output.join('\n'));
                throw new Error(`Failed validating ${plugin}`);
            }
            // Emit that a plugin has changed.
            this._pluginChanged.emit(plugin);
            return new Settings({ plugin: plugins[plugin], registry });
        });
    }
    /**
     * Remove a single setting in the registry.
     *
     * @param plugin - The name of the plugin whose setting is being removed.
     *
     * @param key - The name of the setting being removed.
     *
     * @returns A promise that resolves when the setting is removed.
     */
    remove(plugin, key) {
        const plugins = this._plugins;
        if (!(plugin in plugins)) {
            return Promise.resolve(undefined);
        }
        const raw = json.parse(plugins[plugin].raw, null, true);
        // Delete both the value and any associated comment.
        delete raw[key];
        delete raw[`// ${key}`];
        plugins[plugin].raw = Private.annotatedPlugin(plugins[plugin], raw);
        return this._save(plugin);
    }
    /**
     * Set a single setting in the registry.
     *
     * @param plugin - The name of the plugin whose setting is being set.
     *
     * @param key - The name of the setting being set.
     *
     * @param value - The value of the setting being set.
     *
     * @returns A promise that resolves when the setting has been saved.
     *
     */
    set(plugin, key, value) {
        const plugins = this._plugins;
        if (!(plugin in plugins)) {
            return this.load(plugin).then(() => this.set(plugin, key, value));
        }
        const raw = json.parse(plugins[plugin].raw, null, true);
        plugins[plugin].raw = Private.annotatedPlugin(plugins[plugin], Object.assign({}, raw, { [key]: value }));
        return this._save(plugin);
    }
    /**
     * Upload a plugin's settings.
     *
     * @param plugin - The name of the plugin whose settings are being set.
     *
     * @param raw - The raw plugin settings being uploaded.
     *
     * @returns A promise that resolves when the settings have been saved.
     */
    upload(plugin, raw) {
        const plugins = this._plugins;
        if (!(plugin in plugins)) {
            return this.load(plugin).then(() => this.upload(plugin, raw));
        }
        // Set the local copy.
        plugins[plugin].raw = raw;
        return this._save(plugin);
    }
    /**
     * Save a plugin in the registry.
     */
    _save(plugin) {
        const plugins = this._plugins;
        if (!(plugin in plugins)) {
            const message = `${plugin} does not exist in setting registry.`;
            return Promise.reject(new Error(message));
        }
        try {
            this._validate(plugins[plugin]);
        }
        catch (errors) {
            const message = `${plugin} failed to validate; check console for errors.`;
            console.warn(`${plugin} validation errors:`, errors);
            return Promise.reject(new Error(message));
        }
        return this._connector.save(plugin, plugins[plugin].raw).then(() => {
            this._pluginChanged.emit(plugin);
        });
    }
    /**
     * Validate a plugin's data and schema, compose the `composite` data.
     */
    _validate(plugin) {
        // Validate the user data and create the composite data.
        const errors = this.validator.validateData(plugin);
        if (errors) {
            throw errors;
        }
        // Set the local copy.
        this._plugins[plugin.id] = plugin;
    }
}
exports.SettingRegistry = SettingRegistry;
/**
 * A manager for a specific plugin's settings.
 */
class Settings {
    /**
     * Instantiate a new plugin settings manager.
     */
    constructor(options) {
        this._changed = new signaling_1.Signal(this);
        this._composite = Object.create(null);
        this._isDisposed = false;
        this._raw = '{ }';
        this._schema = Object.create(null);
        this._user = Object.create(null);
        const { plugin } = options;
        this.plugin = plugin.id;
        this.registry = options.registry;
        this._composite = plugin.data.composite || {};
        this._raw = plugin.raw || '{ }';
        this._schema = plugin.schema || { type: 'object' };
        this._user = plugin.data.user || {};
        this.registry.pluginChanged.connect(this._onPluginChanged, this);
    }
    /**
     * A signal that emits when the plugin's settings have changed.
     */
    get changed() {
        return this._changed;
    }
    /**
     * Get the composite of user settings and extension defaults.
     */
    get composite() {
        return this._composite;
    }
    /**
     * Test whether the plugin settings manager disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Get the plugin settings schema.
     */
    get schema() {
        return this._schema;
    }
    /**
     * Get the plugin settings raw text value.
     */
    get raw() {
        return this._raw;
    }
    /**
     * Get the user settings.
     */
    get user() {
        return this._user;
    }
    /**
     * Return the defaults in a commented JSON format.
     */
    annotatedDefaults() {
        return Private.annotatedDefaults(this._schema, this.plugin);
    }
    /**
     * Calculate the default value of a setting by iterating through the schema.
     *
     * @param key - The name of the setting whose default value is calculated.
     *
     * @returns A calculated default JSON value for a specific setting.
     */
    default(key) {
        return Private.reifyDefault(this.schema, key);
    }
    /**
     * Dispose of the plugin settings resources.
     */
    dispose() {
        if (this._isDisposed) {
            return;
        }
        this._isDisposed = true;
        signaling_1.Signal.clearData(this);
    }
    /**
     * Get an individual setting.
     *
     * @param key - The name of the setting being retrieved.
     *
     * @returns The setting value.
     *
     * #### Notes
     * This method returns synchronously because it uses a cached copy of the
     * plugin settings that is synchronized with the registry.
     */
    get(key) {
        const { composite, user } = this;
        return {
            composite: key in composite ? copy(composite[key]) : undefined,
            user: key in user ? copy(user[key]) : undefined
        };
    }
    /**
     * Remove a single setting.
     *
     * @param key - The name of the setting being removed.
     *
     * @returns A promise that resolves when the setting is removed.
     *
     * #### Notes
     * This function is asynchronous because it writes to the setting registry.
     */
    remove(key) {
        return this.registry.remove(this.plugin, key);
    }
    /**
     * Save all of the plugin's user settings at once.
     */
    save(raw) {
        return this.registry.upload(this.plugin, raw);
    }
    /**
     * Set a single setting.
     *
     * @param key - The name of the setting being set.
     *
     * @param value - The value of the setting.
     *
     * @returns A promise that resolves when the setting has been saved.
     *
     * #### Notes
     * This function is asynchronous because it writes to the setting registry.
     */
    set(key, value) {
        return this.registry.set(this.plugin, key, value);
    }
    /**
     * Validates raw settings with comments.
     *
     * @param raw - The JSON with comments string being validated.
     *
     * @returns A list of errors or `null` if valid.
     */
    validate(raw) {
        const data = { composite: {}, user: {} };
        const id = this.plugin;
        const schema = this._schema;
        const validator = this.registry.validator;
        return validator.validateData({ data, id, raw, schema }, false);
    }
    /**
     * Handle plugin changes in the setting registry.
     */
    _onPluginChanged(sender, plugin) {
        if (plugin === this.plugin) {
            const found = algorithm_1.find(this.registry.plugins, p => p.id === plugin);
            if (!found) {
                return;
            }
            const { composite, user } = found.data;
            const { raw, schema } = found;
            this._composite = composite || {};
            this._raw = raw;
            this._schema = schema || { type: 'object' };
            this._user = user || {};
            this._changed.emit(undefined);
        }
    }
}
exports.Settings = Settings;
/**
 * A namespace for private module data.
 */
var Private;
(function (Private) {
    /* tslint:disable */
    /**
     * The schema for settings.
     */
    Private.SCHEMA = {
        $schema: 'http://json-schema.org/draft-06/schema',
        title: 'Jupyter Settings/Preferences Schema',
        description: 'Jupyter settings/preferences schema v0.1.0',
        type: 'object',
        additionalProperties: true,
        properties: {
            [exports.ICON_CLASS_KEY]: { type: 'string', default: 'jp-FileIcon' },
            [exports.ICON_LABEL_KEY]: { type: 'string', default: 'Plugin' }
        }
    };
    /* tslint:enable */
    /**
     * The default indentation level, uses spaces instead of tabs.
     */
    const indent = '    ';
    /**
     * Replacement text for schema properties missing a `description` field.
     */
    const nondescript = '[missing schema description]';
    /**
     * Replacement text for schema properties missing a `default` field.
     */
    const undefaulted = '[missing schema default]';
    /**
     * Replacement text for schema properties missing a `title` field.
     */
    const untitled = '[missing schema title]';
    /**
     * Returns an annotated (JSON with comments) version of a schema's defaults.
     */
    function annotatedDefaults(schema, plugin) {
        const { description, properties, title } = schema;
        const keys = Object.keys(properties).sort((a, b) => a.localeCompare(b));
        const length = Math.max((description || nondescript).length, plugin.length);
        return [
            '{',
            prefix(`${title || untitled}`),
            prefix(plugin),
            prefix(description || nondescript),
            prefix(line(length)),
            '',
            keys.map(key => defaultDocumentedValue(schema, key)).join(',\n\n'),
            '}'
        ].join('\n');
    }
    Private.annotatedDefaults = annotatedDefaults;
    /**
     * Returns an annotated (JSON with comments) version of a plugin's
     * setting data.
     */
    function annotatedPlugin(plugin, data) {
        const { description, title } = plugin.schema;
        const keys = Object.keys(data).sort((a, b) => a.localeCompare(b));
        const length = Math.max((description || nondescript).length, plugin.id.length);
        return [
            '{',
            prefix(`${title || untitled}`),
            prefix(plugin.id),
            prefix(description || nondescript),
            prefix(line(length)),
            '',
            keys
                .map(key => documentedValue(plugin.schema, key, data[key]))
                .join(',\n\n'),
            '}'
        ].join('\n');
    }
    Private.annotatedPlugin = annotatedPlugin;
    /**
     * Returns the default value-with-documentation-string for a
     * specific schema property.
     */
    function defaultDocumentedValue(schema, key) {
        const props = schema.properties && schema.properties[key];
        const description = (props && props['description']) || nondescript;
        const title = (props && props['title']) || untitled;
        const reified = reifyDefault(schema, key);
        const defaults = reified === undefined
            ? prefix(`"${key}": ${undefaulted}`)
            : prefix(`"${key}": ${JSON.stringify(reified, null, 2)}`, indent);
        return [
            prefix(`${title || untitled}`),
            prefix(description || nondescript),
            defaults
        ].join('\n');
    }
    /**
     * Returns a value-with-documentation-string for a specific schema property.
     */
    function documentedValue(schema, key, value) {
        const props = schema.properties && schema.properties[key];
        const description = (props && props['description']) || nondescript;
        const title = (props && props['title']) || untitled;
        const attribute = prefix(`"${key}": ${JSON.stringify(value, null, 2)}`, indent);
        return [prefix(title), prefix(description), attribute].join('\n');
    }
    /**
     * Returns a line of a specified length.
     */
    function line(length, ch = '*') {
        return new Array(length + 1).join(ch);
    }
    /**
     * Returns a documentation string with a comment prefix added on every line.
     */
    function prefix(source, pre = `${indent}\/\/ `) {
        return pre + source.split('\n').join(`\n${pre}`);
    }
    /**
     * Create a fully extrapolated default value for a root key in a schema.
     */
    function reifyDefault(schema, root) {
        // If the property is at the root level, traverse its schema.
        schema = (root ? schema.properties[root] : schema) || {};
        // If the property has no default or is a primitive, return.
        if (!('default' in schema) || schema.type !== 'object') {
            return schema.default;
        }
        // Make a copy of the default value to populate.
        const result = coreutils_1.JSONExt.deepCopy(schema.default);
        // Iterate through and populate each child property.
        for (let property in schema.properties || {}) {
            result[property] = reifyDefault(schema.properties[property]);
        }
        return result;
    }
    Private.reifyDefault = reifyDefault;
})(Private = exports.Private || (exports.Private = {}));


/***/ }),

/***/ "0LMu":
/*!****************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/builder/index.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const serverconnection_1 = __webpack_require__(/*! ../serverconnection */ "ZWV2");
/**
 * The url for the lab build service.
 */
const BUILD_SETTINGS_URL = 'lab/api/build';
/**
 * The build API service manager.
 */
class BuildManager {
    /**
     * Create a new setting manager.
     */
    constructor(options = {}) {
        this.serverSettings =
            options.serverSettings || serverconnection_1.ServerConnection.makeSettings();
    }
    /**
     * Test whether the build service is available.
     */
    get isAvailable() {
        return coreutils_1.PageConfig.getOption('buildAvailable').toLowerCase() === 'true';
    }
    /**
     * Test whether to check build status automatically.
     */
    get shouldCheck() {
        return coreutils_1.PageConfig.getOption('buildCheck').toLowerCase() === 'true';
    }
    /**
     * Get whether the application should be built.
     */
    getStatus() {
        const base = this.serverSettings.baseUrl;
        const url = coreutils_1.URLExt.join(base, BUILD_SETTINGS_URL);
        const { serverSettings } = this;
        const promise = serverconnection_1.ServerConnection.makeRequest(url, {}, serverSettings);
        return promise
            .then(response => {
            if (response.status !== 200) {
                throw new serverconnection_1.ServerConnection.ResponseError(response);
            }
            return response.json();
        })
            .then(data => {
            if (typeof data.status !== 'string') {
                throw new Error('Invalid data');
            }
            if (typeof data.message !== 'string') {
                throw new Error('Invalid data');
            }
            return data;
        });
    }
    /**
     * Build the application.
     */
    build() {
        const base = this.serverSettings.baseUrl;
        const url = coreutils_1.URLExt.join(base, BUILD_SETTINGS_URL);
        const { serverSettings } = this;
        const init = { method: 'POST' };
        const promise = serverconnection_1.ServerConnection.makeRequest(url, init, serverSettings);
        return promise.then(response => {
            if (response.status === 400) {
                throw new serverconnection_1.ServerConnection.ResponseError(response, 'Build aborted');
            }
            if (response.status !== 200) {
                let message = `Build failed with ${response.status}, please run 'jupyter lab build' on the server for full output`;
                throw new serverconnection_1.ServerConnection.ResponseError(response, message);
            }
        });
    }
    /**
     * Cancel an active build.
     */
    cancel() {
        const base = this.serverSettings.baseUrl;
        const url = coreutils_1.URLExt.join(base, BUILD_SETTINGS_URL);
        const { serverSettings } = this;
        const init = { method: 'DELETE' };
        const promise = serverconnection_1.ServerConnection.makeRequest(url, init, serverSettings);
        return promise.then(response => {
            if (response.status !== 204) {
                throw new serverconnection_1.ServerConnection.ResponseError(response);
            }
        });
    }
}
exports.BuildManager = BuildManager;


/***/ }),

/***/ "0PYM":
/*!***********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotHistogramIcon.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotHistogramIcon = function PlotHistogramIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 24 16' }, props),
        _react2.default.createElement('path', { d: 'M0 11.015h4.003V16H0zm5-6h4.003V16H5zM10 0h4.011v16H10zm5 5.014h4.004V16H15zm4.996 6.001H24V16h-4.004z' })
    );
};

exports.default = PlotHistogramIcon;

/***/ }),

/***/ "0QlZ":
/*!*******************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotSplomIcon.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotSplomIcon = function PlotSplomIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 1360 1360' }, props),
        _react2.default.createElement('path', { fill: 'currentColor', d: 'M1174.5 162.716H186.081c-12.743 0-23.074 10.331-23.074 23.074v321.832a23.061 23.061 0 0 0-.581 5.088c0 1.749.211 3.449.581 5.088V843.85c-.37 1.639-.581 3.338-.581 5.088s.211 3.449.581 5.088v320.184c0 12.744 10.331 23.074 23.074 23.074H1174.5c12.744 0 23.074-10.33 23.074-23.074V185.79c0-12.743-10.33-23.074-23.074-23.074zM532.198 825.863V535.784h290.078v290.079H532.198zm290.078 46.149v279.123H532.198V872.012h290.078zm-613.12-336.228h276.893v290.079H209.156V535.784zm323.042-46.148V208.865h290.078v280.771H532.198zm336.228 46.148h283v290.079h-283V535.784zm283-46.148h-283V208.865h283v280.771zM486.049 208.865v280.771H209.156V208.865h276.893zM209.156 872.012h276.893v279.123H209.156V872.012zm659.27 279.123V872.012h283v279.123h-283z' }),
        _react2.default.createElement('circle', { fill: 'currentColor', cx: '267.502', cy: '1098.284', r: '30.664' }),
        _react2.default.createElement('path', { fill: 'currentColor', d: 'M352.718 919.58c25.607-25.614 67.135-25.614 92.748 0 25.607 25.606 25.607 67.135 0 92.742-25.613 25.614-67.141 25.614-92.748 0-25.612-25.607-25.612-67.135 0-92.742z' }),
        _react2.default.createElement('circle', { fill: 'currentColor', cx: '430.5', cy: '1098.284', r: '30.664' }),
        _react2.default.createElement('circle', { fill: 'currentColor', cx: '267.502', cy: '935.286', r: '30.665' }),
        _react2.default.createElement('circle', { fill: 'currentColor', cx: '598.792', cy: '935.287', r: '30.664' }),
        _react2.default.createElement('circle', { fill: 'currentColor', cx: '598.792', cy: '1098.284', r: '30.664' }),
        _react2.default.createElement('path', { fill: 'currentColor', d: 'M783.476 1048.879c19.627 19.628 19.627 51.458 0 71.088-19.632 19.631-51.461 19.631-71.092 0-19.627-19.63-19.627-51.46 0-71.088 19.631-19.627 51.46-19.627 71.092 0z' }),
        _react2.default.createElement('circle', { fill: 'currentColor', cx: '266.756', cy: '601.798', r: '30.664' }),
        _react2.default.createElement('path', { fill: 'currentColor', d: 'M387.803 645.243c21.43 21.426 21.43 56.173 0 77.605-21.426 21.427-56.176 21.427-77.602 0-21.43-21.433-21.43-56.18 0-77.605 21.426-21.43 56.176-21.43 77.602 0z' }),
        _react2.default.createElement('circle', { fill: 'currentColor', cx: '266.755', cy: '764.796', r: '30.664' }),
        _react2.default.createElement('circle', { fill: 'currentColor', cx: '429.754', cy: '764.796', r: '30.665' }),
        _react2.default.createElement('circle', { fill: 'currentColor', cx: '1091.224', cy: '271.618', r: '30.664' }),
        _react2.default.createElement('circle', { fill: 'currentColor', cx: '928.226', cy: '271.618', r: '30.665' }),
        _react2.default.createElement('circle', { fill: 'currentColor', cx: '928.226', cy: '434.615', r: '30.665' }),
        _react2.default.createElement('path', { fill: 'currentColor', d: 'M1036.258 378.904c-14.652 14.652-38.414 14.652-53.07 0-14.653-14.655-14.653-38.417 0-53.072 14.656-14.652 38.418-14.652 53.07 0 14.653 14.655 14.653 38.418 0 53.072z' }),
        _react2.default.createElement('circle', { fill: 'currentColor', cx: '759.933', cy: '434.616', r: '30.664' }),
        _react2.default.createElement('path', { fill: 'currentColor', d: 'M681.069 348.629c-25.599-25.593-25.599-67.099 0-92.697 25.596-25.593 67.103-25.593 92.695 0 25.601 25.598 25.601 67.104 0 92.697-25.592 25.594-67.099 25.594-92.695 0z' }),
        _react2.default.createElement('circle', { fill: 'currentColor', cx: '596.936', cy: '271.618', r: '30.665' }),
        _react2.default.createElement('path', { fill: 'currentColor', d: 'M1070.287 789.785c-11.976-11.975-11.976-31.39 0-43.364 11.975-11.976 31.393-11.976 43.365 0 11.976 11.975 11.976 31.39 0 43.364-11.972 11.979-31.39 11.979-43.365 0zM994.818 700.765c-8.232-8.234-8.232-21.581 0-29.815 8.231-8.231 21.579-8.231 29.812 0 8.231 8.234 8.231 21.581 0 29.815-8.233 8.23-21.58 8.23-29.812 0zM1042.042 655.035c-19.777-19.774-19.777-51.838 0-71.613 19.772-19.77 51.837-19.77 71.609 0 19.777 19.775 19.777 51.839 0 71.613-19.772 19.771-51.837 19.771-71.609 0zM907.288 626.789c-11.972-11.975-11.972-31.393 0-43.367 11.977-11.975 31.393-11.975 43.367 0 11.974 11.975 11.974 31.393 0 43.367-11.974 11.973-31.39 11.973-43.367 0z' }),
        _react2.default.createElement('circle', { fill: 'currentColor', cx: '596.935', cy: '352.369', r: '14.516' }),
        _react2.default.createElement('circle', { fill: 'currentColor', cx: '928.973', cy: '352.369', r: '18.266' }),
        _react2.default.createElement('circle', { fill: 'currentColor', cx: '1091.969', cy: '434.615', r: '18.266' }),
        _react2.default.createElement('circle', { fill: 'currentColor', cx: '1009.724', cy: '271.617', r: '18.509' }),
        _react2.default.createElement('circle', { fill: 'currentColor', cx: '349.002', cy: '1098.283', r: '19.813' }),
        _react2.default.createElement('circle', { fill: 'currentColor', cx: '681.039', cy: '1016.035', r: '19.376' }),
        _react2.default.createElement('circle', { fill: 'currentColor', cx: '598.792', cy: '1016.036', r: '14.516' })
    );
};

exports.default = PlotSplomIcon;

/***/ }),

/***/ "0RQb":
/*!**************************************************************************!*\
  !*** ./node_modules/draft-js/lib/keyCommandMoveSelectionToEndOfBlock.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule keyCommandMoveSelectionToEndOfBlock
 * @format
 * 
 */



var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");

/**
 * See comment for `moveSelectionToStartOfBlock`.
 */
function keyCommandMoveSelectionToEndOfBlock(editorState) {
  var selection = editorState.getSelection();
  var endKey = selection.getEndKey();
  var content = editorState.getCurrentContent();
  var textLength = content.getBlockForKey(endKey).getLength();
  return EditorState.set(editorState, {
    selection: selection.merge({
      anchorKey: endKey,
      anchorOffset: textLength,
      focusKey: endKey,
      focusOffset: textLength,
      isBackward: false
    }),
    forceSelection: true
  });
}

module.exports = keyCommandMoveSelectionToEndOfBlock;

/***/ }),

/***/ "0TAD":
/*!******************************************!*\
  !*** ./node_modules/base16/lib/ocean.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'ocean',
  author: 'chris kempson (http://chriskempson.com)',
  base00: '#2b303b',
  base01: '#343d46',
  base02: '#4f5b66',
  base03: '#65737e',
  base04: '#a7adba',
  base05: '#c0c5ce',
  base06: '#dfe1e8',
  base07: '#eff1f5',
  base08: '#bf616a',
  base09: '#d08770',
  base0A: '#ebcb8b',
  base0B: '#a3be8c',
  base0C: '#96b5b4',
  base0D: '#8fa1b3',
  base0E: '#b48ead',
  base0F: '#ab7967'
};
module.exports = exports['default'];

/***/ }),

/***/ "0TRD":
/*!**************************************************************!*\
  !*** ./node_modules/draft-js/lib/DefaultDraftInlineStyle.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DefaultDraftInlineStyle
 * @format
 * 
 */



module.exports = {
  BOLD: {
    fontWeight: 'bold'
  },

  CODE: {
    fontFamily: 'monospace',
    wordWrap: 'break-word'
  },

  ITALIC: {
    fontStyle: 'italic'
  },

  STRIKETHROUGH: {
    textDecoration: 'line-through'
  },

  UNDERLINE: {
    textDecoration: 'underline'
  }
};

/***/ }),

/***/ "0XmT":
/*!**********************************************************!*\
  !*** ./node_modules/@jupyterlab/outputarea/lib/model.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const observables_1 = __webpack_require__(/*! @jupyterlab/observables */ "V4vH");
const rendermime_1 = __webpack_require__(/*! @jupyterlab/rendermime */ "Towz");
/**
 * The default implementation of the IOutputAreaModel.
 */
class OutputAreaModel {
    /**
     * Construct a new observable outputs instance.
     */
    constructor(options = {}) {
        this.clearNext = false;
        this.list = null;
        this._trusted = false;
        this._isDisposed = false;
        this._stateChanged = new signaling_1.Signal(this);
        this._changed = new signaling_1.Signal(this);
        this._modelDB = null;
        this._serialized = null;
        this._changeGuard = false;
        this._trusted = !!options.trusted;
        this.contentFactory =
            options.contentFactory || OutputAreaModel.defaultContentFactory;
        this.list = new observables_1.ObservableList();
        if (options.values) {
            algorithm_1.each(options.values, value => {
                this._add(value);
            });
        }
        this.list.changed.connect(this._onListChanged, this);
        // If we are given a IModelDB, keep an up-to-date
        // serialized copy of the OutputAreaModel in it.
        if (options.modelDB) {
            this._modelDB = options.modelDB;
            this._serialized = this._modelDB.createValue('outputs');
            if (this._serialized.get()) {
                this.fromJSON(this._serialized.get());
            }
            else {
                this._serialized.set(this.toJSON());
            }
            this._serialized.changed.connect(this._onSerializedChanged, this);
        }
    }
    /**
     * A signal emitted when the model state changes.
     */
    get stateChanged() {
        return this._stateChanged;
    }
    /**
     * A signal emitted when the model changes.
     */
    get changed() {
        return this._changed;
    }
    /**
     * Get the length of the items in the model.
     */
    get length() {
        return this.list ? this.list.length : 0;
    }
    /**
     * Get whether the model is trusted.
     */
    get trusted() {
        return this._trusted;
    }
    /**
     * Set whether the model is trusted.
     *
     * #### Notes
     * Changing the value will cause all of the models to re-set.
     */
    set trusted(value) {
        if (value === this._trusted) {
            return;
        }
        let trusted = (this._trusted = value);
        for (let i = 0; i < this.list.length; i++) {
            let item = this.list.get(i);
            let value = item.toJSON();
            item.dispose();
            item = this._createItem({ value, trusted });
            this.list.set(i, item);
        }
    }
    /**
     * Test whether the model is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources used by the model.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        this.list.dispose();
        signaling_1.Signal.clearData(this);
    }
    /**
     * Get an item at the specified index.
     */
    get(index) {
        return this.list.get(index);
    }
    /**
     * Set the value at the specified index.
     */
    set(index, value) {
        // Normalize stream data.
        this._normalize(value);
        let item = this._createItem({ value, trusted: this._trusted });
        this.list.set(index, item);
    }
    /**
     * Add an output, which may be combined with previous output.
     *
     * #### Notes
     * The output bundle is copied.
     * Contiguous stream outputs of the same `name` are combined.
     */
    add(output) {
        // If we received a delayed clear message, then clear now.
        if (this.clearNext) {
            this.clear();
            this.clearNext = false;
        }
        return this._add(output);
    }
    /**
     * Clear all of the output.
     *
     * @param wait Delay clearing the output until the next message is added.
     */
    clear(wait = false) {
        this._lastStream = '';
        if (wait) {
            this.clearNext = true;
            return;
        }
        algorithm_1.each(this.list, (item) => {
            item.dispose();
        });
        this.list.clear();
    }
    /**
     * Deserialize the model from JSON.
     *
     * #### Notes
     * This will clear any existing data.
     */
    fromJSON(values) {
        this.clear();
        algorithm_1.each(values, value => {
            this._add(value);
        });
    }
    /**
     * Serialize the model to JSON.
     */
    toJSON() {
        return algorithm_1.toArray(algorithm_1.map(this.list, (output) => output.toJSON()));
    }
    /**
     * Add an item to the list.
     */
    _add(value) {
        let trusted = this._trusted;
        // Normalize the value.
        this._normalize(value);
        // Consolidate outputs if they are stream outputs of the same kind.
        if (coreutils_1.nbformat.isStream(value) &&
            this._lastStream &&
            value.name === this._lastName) {
            // In order to get a list change event, we add the previous
            // text to the current item and replace the previous item.
            // This also replaces the metadata of the last item.
            this._lastStream += value.text;
            value.text = this._lastStream;
            this._removeOverwrittenChars(value);
            let item = this._createItem({ value, trusted });
            let index = this.length - 1;
            let prev = this.list.get(index);
            prev.dispose();
            this.list.set(index, item);
            return index;
        }
        if (coreutils_1.nbformat.isStream(value)) {
            this._removeOverwrittenChars(value);
        }
        // Create the new item.
        let item = this._createItem({ value, trusted });
        // Update the stream information.
        if (coreutils_1.nbformat.isStream(value)) {
            this._lastStream = value.text;
            this._lastName = value.name;
        }
        else {
            this._lastStream = '';
        }
        // Add the item to our list and return the new length.
        return this.list.push(item);
    }
    /**
     * Normalize an output.
     */
    _normalize(value) {
        if (coreutils_1.nbformat.isStream(value)) {
            if (Array.isArray(value.text)) {
                value.text = value.text.join('\n');
            }
        }
    }
    /**
     * Remove characters that are overridden by backspace characters.
     */
    _fixBackspace(txt) {
        let tmp = txt;
        do {
            txt = tmp;
            // Cancel out anything-but-newline followed by backspace
            tmp = txt.replace(/[^\n]\x08/gm, '');
        } while (tmp.length < txt.length);
        return txt;
    }
    /**
     * Remove chunks that should be overridden by the effect of
     * carriage return characters.
     */
    _fixCarriageReturn(txt) {
        let tmp = txt;
        // Handle multiple carriage returns before a newline
        tmp = tmp.replace(/\r\r+\n/gm, '\r\n');
        // Remove chunks that should be overridden by carriage returns
        do {
            // Remove any chunks preceding a carriage return unless carriage
            // return followed by a newline
            tmp = tmp.replace(/^[^\n]*(?:\r(?!\n))+/gm, '');
        } while (tmp.search(/\r(?!\n)/) > -1);
        do {
            // Replace remaining \r\n characters with a newline
            tmp = tmp.replace(/\r\n/gm, '\n');
        } while (tmp.indexOf('\r\n') > -1);
        return tmp;
    }
    /*
     * Remove characters overridden by backspaces and carriage returns
     */
    _removeOverwrittenChars(value) {
        let tmp = value.text;
        value.text = this._fixCarriageReturn(this._fixBackspace(tmp));
    }
    /**
     * Create an output item and hook up its signals.
     */
    _createItem(options) {
        let factory = this.contentFactory;
        let item = factory.createOutputModel(options);
        item.changed.connect(this._onGenericChange, this);
        return item;
    }
    /**
     * Handle a change to the list.
     */
    _onListChanged(sender, args) {
        if (this._serialized && !this._changeGuard) {
            this._changeGuard = true;
            this._serialized.set(this.toJSON());
            this._changeGuard = false;
        }
        this._changed.emit(args);
    }
    /**
     * If the serialized version of the outputs have changed due to a remote
     * action, then update the model accordingly.
     */
    _onSerializedChanged(sender, args) {
        if (!this._changeGuard) {
            this._changeGuard = true;
            this.fromJSON(args.newValue);
            this._changeGuard = false;
        }
    }
    /**
     * Handle a change to an item.
     */
    _onGenericChange() {
        this._stateChanged.emit(void 0);
    }
}
exports.OutputAreaModel = OutputAreaModel;
/**
 * The namespace for OutputAreaModel class statics.
 */
(function (OutputAreaModel) {
    /**
     * The default implementation of a `IModelOutputFactory`.
     */
    class ContentFactory {
        /**
         * Create an output model.
         */
        createOutputModel(options) {
            return new rendermime_1.OutputModel(options);
        }
    }
    OutputAreaModel.ContentFactory = ContentFactory;
    /**
     * The default output model factory.
     */
    OutputAreaModel.defaultContentFactory = new ContentFactory();
})(OutputAreaModel = exports.OutputAreaModel || (exports.OutputAreaModel = {}));


/***/ }),

/***/ "0XuU":
/*!***************************************************!*\
  !*** ./node_modules/readable-stream/transform.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(/*! ./readable */ "43KI").Transform


/***/ }),

/***/ "0b9Q":
/*!*****************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/TextEditor.js ***!
  \*****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UnconnectedTextEditor = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _nested_property = __webpack_require__(/*! plotly.js/src/lib/nested_property */ "dNZO");

var _nested_property2 = _interopRequireDefault(_nested_property);

var _LaTeX = __webpack_require__(/*! ../widgets/text_editors/LaTeX */ "XxHi");

var _LaTeX2 = _interopRequireDefault(_LaTeX);

var _RichText = __webpack_require__(/*! ../widgets/text_editors/RichText */ "BFJn");

var _RichText2 = _interopRequireDefault(_RichText);

var _MultiFormat = __webpack_require__(/*! ../widgets/text_editors/MultiFormat */ "1y7b");

var _MultiFormat2 = _interopRequireDefault(_MultiFormat);

var _HTML = __webpack_require__(/*! ../widgets/text_editors/HTML */ "1lSx");

var _HTML2 = _interopRequireDefault(_HTML);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

// TODO: import plotly.js regex directly: https://github.com/plotly/plotly.js/issues/3520
var TEMPLATE_STRING_REGEX = /%{([^\s%{}:]*)(:[^}]*)?}/g;
var INDEX_IN_TEMPLATE_STRING_REGEX = /%{(meta(\[(\d+)]))}/;

var UnconnectedTextEditor = exports.UnconnectedTextEditor = function (_Component) {
  _inherits(UnconnectedTextEditor, _Component);

  function UnconnectedTextEditor() {
    _classCallCheck(this, UnconnectedTextEditor);

    return _possibleConstructorReturn(this, (UnconnectedTextEditor.__proto__ || Object.getPrototypeOf(UnconnectedTextEditor)).apply(this, arguments));
  }

  _createClass(UnconnectedTextEditor, [{
    key: 'hasTemplateStrings',
    value: function hasTemplateStrings(value) {
      if (!value) {
        return false;
      }
      return value.match(TEMPLATE_STRING_REGEX);
    }
  }, {
    key: 'updatePlot',
    value: function updatePlot(value) {
      var updatePlot = this.props.updatePlot;

      var templateStrings = this.hasTemplateStrings(value);

      var adjustedValue = value;

      if (templateStrings) {
        adjustedValue = adjustedValue.replace(TEMPLATE_STRING_REGEX, function (match) {
          var index = INDEX_IN_TEMPLATE_STRING_REGEX.exec(match);
          if (index) {
            var adjustedIndex = parseInt(index[3], 10) - 1;
            if (!isNaN(adjustedIndex)) {
              return '%{meta[' + (adjustedIndex < 0 ? 0 : adjustedIndex) + ']}';
            }
          }
          return match;
        });
      }

      updatePlot(adjustedValue);
    }
  }, {
    key: 'getAdjustedFullValue',
    value: function getAdjustedFullValue(fullValue) {
      var templateStrings = this.hasTemplateStrings(fullValue);
      if (templateStrings) {
        return fullValue.replace(TEMPLATE_STRING_REGEX, function (match) {
          var index = INDEX_IN_TEMPLATE_STRING_REGEX.exec(match);
          if (index) {
            var adjustedIndex = parseInt(index[3], 10) + 1;
            if (!isNaN(adjustedIndex)) {
              return '%{meta[' + adjustedIndex + ']}';
            }
            return match;
          }
          return match;
        });
      }
      return fullValue;
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          attr = _props.attr,
          container = _props.container,
          htmlOnly = _props.htmlOnly,
          latexOnly = _props.latexOnly,
          multiValued = _props.multiValued,
          richTextOnly = _props.richTextOnly;
      var _ = this.context.localize;


      var fullValue = this.getAdjustedFullValue(this.props.fullValue);

      var placeholder = this.props.placeholder;

      if (multiValued || fullValue && (!container || !(0, _nested_property2.default)(container, attr))) {
        placeholder = fullValue;
        fullValue = '';
      }

      var editor = void 0;

      if (latexOnly) {
        placeholder = _('Enter LaTeX formatted text');
        editor = _react2.default.createElement(_LaTeX2.default, { value: fullValue, placeholder: placeholder, onChange: this.updatePlot.bind(this) });
      } else if (richTextOnly) {
        editor = _react2.default.createElement(_RichText2.default, {
          value: fullValue,
          placeholder: placeholder,
          onChange: this.updatePlot.bind(this)
        });
      } else if (htmlOnly) {
        placeholder = _('Enter html formatted text');
        editor = _react2.default.createElement(_HTML2.default, { value: fullValue, placeholder: placeholder, onChange: this.updatePlot.bind(this) });
      } else {
        editor = _react2.default.createElement(_MultiFormat2.default, {
          value: fullValue,
          placeholder: placeholder,
          onChange: this.updatePlot.bind(this)
        });
      }

      return _react2.default.createElement(
        _Field2.default,
        this.props,
        _react2.default.createElement(
          'div',
          { className: 'text-editor' },
          editor
        )
      );
    }
  }]);

  return UnconnectedTextEditor;
}(_react.Component);

UnconnectedTextEditor.propTypes = _extends({}, _Field2.default.propTypes, {
  fullValue: _propTypes2.default.any,
  htmlOnly: _propTypes2.default.bool,
  latexOnly: _propTypes2.default.bool,
  richTextOnly: _propTypes2.default.bool,
  updatePlot: _propTypes2.default.func,
  placeholder: _propTypes2.default.string
});

UnconnectedTextEditor.contextTypes = {
  localize: _propTypes2.default.func,
  fullLayout: _propTypes2.default.object
};

exports.default = (0, _lib.connectToContainer)(UnconnectedTextEditor, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    if (plotProps.isVisible && plotProps.multiValued) {
      plotProps.isVisible = false;
    }

    if (context.fullLayout && context.fullLayout._dfltTitle && Object.values(context.fullLayout._dfltTitle).includes(plotProps.fullValue)) {
      plotProps.placeholder = plotProps.fullValue;
      plotProps.fullValue = '';
    }
  }
});
//# sourceMappingURL=TextEditor.js.map

/***/ }),

/***/ "0cA8":
/*!**************************************************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils-extension/style/images/jupyter-favicon.svg ***!
  \**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjE1MnB4IiBoZWlnaHQ9IjE2NXB4IiB2aWV3Qm94PSIwIDAgMTUyIDE2NSIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj4KICAgIDwhLS0gR2VuZXJhdG9yOiBTa2V0Y2ggMzkuMSAoMzE3MjApIC0gaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoIC0tPgogICAgPHRpdGxlPmxvZ288L3RpdGxlPgogICAgPGRlc2M+Q3JlYXRlZCB3aXRoIFNrZXRjaC48L2Rlc2M+CiAgICA8ZGVmcz48L2RlZnM+CiAgICA8ZyBpZD0iUGFnZS0xIiBzdHJva2U9Im5vbmUiIHN0cm9rZS13aWR0aD0iMSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj4KICAgICAgICA8ZyBpZD0ibG9nbyIgZmlsbD0iI0YzNzcyNiI+CiAgICAgICAgICAgIDxnIGlkPSJsb2dvLnN2ZyI+CiAgICAgICAgICAgICAgICA8ZyBpZD0iQ2FudmFzIj4KICAgICAgICAgICAgICAgICAgICA8ZyBpZD0ibG9nbyI+CiAgICAgICAgICAgICAgICAgICAgICAgIDxnIGlkPSJnIj4KICAgICAgICAgICAgICAgICAgICAgICAgICAgIDxnIGlkPSJwYXRoIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgwLjAwMDAwMCwgMTA5LjgwNDg3OCkiPgogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDxnIGlkPSJwYXRoOC1maWxsIj4KICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgPGcgaWQ9InBhdGgxX2ZpbGwtbGluayIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMC4wNzg5NDcsIDAuNzc4MDQ5KSI+CiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNNzUuOTQyMjg0MiwyOS41ODA0NTYxIEM0My4zMDIzOTQ3LDI5LjU4MDQ1NjEgMTQuNzk2NzgzMiwxNy42NTM0NjM0IDAsMCBDNS41MTA4MzIxMSwxNS44NDA2ODI5IDE1Ljc4MTUzODksMjkuNTY2NzczMiAyOS4zOTA0OTQ3LDM5LjI3ODQxNzEgQzQyLjk5OTcsNDguOTg5ODUzNyA1OS4yNzM3LDU0LjIwNjc4MDUgNzUuOTYwNTc4OSw1NC4yMDY3ODA1IEM5Mi42NDc0NTc5LDU0LjIwNjc4MDUgMTA4LjkyMTQ1OCw0OC45ODk4NTM3IDEyMi41MzA2NjMsMzkuMjc4NDE3MSBDMTM2LjEzOTQ1MywyOS41NjY3NzMyIDE0Ni40MTAyODQsMTUuODQwNjgyOSAxNTEuOTIxMTU4LDAgQzEzNy4wODc4NjgsMTcuNjUzNDYzNCAxMDguNTgyNTg5LDI5LjU4MDQ1NjEgNzUuOTQyMjg0MiwyOS41ODA0NTYxIEw3NS45NDIyODQyLDI5LjU4MDQ1NjEgWiIgaWQ9InBhdGgxX2ZpbGwiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgPC9nPgogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDwvZz4KICAgICAgICAgICAgICAgICAgICAgICAgICAgIDwvZz4KICAgICAgICAgICAgICAgICAgICAgICAgICAgIDxnIGlkPSJwYXRoIj4KICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA8ZyBpZD0icGF0aDktZmlsbCI+CiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDxnIGlkPSJwYXRoMl9maWxsLWxpbmsiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDAuMDM3MzY4LCAwLjcwNDg3OCkiPgogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTc1Ljk3ODQ1NzksMjQuNjI2NDA3MyBDMTA4LjYxODc2MywyNC42MjY0MDczIDEzNy4xMjQ0NTgsMzYuNTUzNDQxNSAxNTEuOTIxMTU4LDU0LjIwNjc4MDUgQzE0Ni40MTAyODQsMzguMzY2MjIyIDEzNi4xMzk0NTMsMjQuNjQwMTMxNyAxMjIuNTMwNjYzLDE0LjkyODQ4NzggQzEwOC45MjE0NTgsNS4yMTY4NDM5IDkyLjY0NzQ1NzksMCA3NS45NjA1Nzg5LDAgQzU5LjI3MzcsMCA0Mi45OTk3LDUuMjE2ODQzOSAyOS4zOTA0OTQ3LDE0LjkyODQ4NzggQzE1Ljc4MTUzODksMjQuNjQwMTMxNyA1LjUxMDgzMjExLDM4LjM2NjIyMiAwLDU0LjIwNjc4MDUgQzE0LjgzMzA4MTYsMzYuNTg5OTI5MyA0My4zMzg1Njg0LDI0LjYyNjQwNzMgNzUuOTc4NDU3OSwyNC42MjY0MDczIEw3NS45Nzg0NTc5LDI0LjYyNjQwNzMgWiIgaWQ9InBhdGgyX2ZpbGwiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgPC9nPgogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDwvZz4KICAgICAgICAgICAgICAgICAgICAgICAgICAgIDwvZz4KICAgICAgICAgICAgICAgICAgICAgICAgPC9nPgogICAgICAgICAgICAgICAgICAgIDwvZz4KICAgICAgICAgICAgICAgIDwvZz4KICAgICAgICAgICAgPC9nPgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+"

/***/ }),

/***/ "0cit":
/*!********************************************************!*\
  !*** ./node_modules/asn1.js/lib/asn1/base/reporter.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var inherits = __webpack_require__(/*! inherits */ "P7XM");

function Reporter(options) {
  this._reporterState = {
    obj: null,
    path: [],
    options: options || {},
    errors: []
  };
}
exports.Reporter = Reporter;

Reporter.prototype.isError = function isError(obj) {
  return obj instanceof ReporterError;
};

Reporter.prototype.save = function save() {
  var state = this._reporterState;

  return { obj: state.obj, pathLen: state.path.length };
};

Reporter.prototype.restore = function restore(data) {
  var state = this._reporterState;

  state.obj = data.obj;
  state.path = state.path.slice(0, data.pathLen);
};

Reporter.prototype.enterKey = function enterKey(key) {
  return this._reporterState.path.push(key);
};

Reporter.prototype.exitKey = function exitKey(index) {
  var state = this._reporterState;

  state.path = state.path.slice(0, index - 1);
};

Reporter.prototype.leaveKey = function leaveKey(index, key, value) {
  var state = this._reporterState;

  this.exitKey(index);
  if (state.obj !== null)
    state.obj[key] = value;
};

Reporter.prototype.path = function path() {
  return this._reporterState.path.join('/');
};

Reporter.prototype.enterObject = function enterObject() {
  var state = this._reporterState;

  var prev = state.obj;
  state.obj = {};
  return prev;
};

Reporter.prototype.leaveObject = function leaveObject(prev) {
  var state = this._reporterState;

  var now = state.obj;
  state.obj = prev;
  return now;
};

Reporter.prototype.error = function error(msg) {
  var err;
  var state = this._reporterState;

  var inherited = msg instanceof ReporterError;
  if (inherited) {
    err = msg;
  } else {
    err = new ReporterError(state.path.map(function(elem) {
      return '[' + JSON.stringify(elem) + ']';
    }).join(''), msg.message || msg, msg.stack);
  }

  if (!state.options.partial)
    throw err;

  if (!inherited)
    state.errors.push(err);

  return err;
};

Reporter.prototype.wrapResult = function wrapResult(result) {
  var state = this._reporterState;
  if (!state.options.partial)
    return result;

  return {
    result: this.isError(result) ? null : result,
    errors: state.errors
  };
};

function ReporterError(path, msg) {
  this.path = path;
  this.rethrow(msg);
};
inherits(ReporterError, Error);

ReporterError.prototype.rethrow = function rethrow(msg) {
  this.message = msg + ' at: ' + (this.path || '(shallow)');
  if (Error.captureStackTrace)
    Error.captureStackTrace(this, ReporterError);

  if (!this.stack) {
    try {
      // IE only adds stack when thrown
      throw new Error(this.message);
    } catch (e) {
      this.stack = e.stack;
    }
  }
  return this;
};


/***/ }),

/***/ "0ejA":
/*!************************************************!*\
  !*** ./node_modules/htmlparser2/lib/Stream.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = Stream;

var Parser = __webpack_require__(/*! ./WritableStream.js */ "h2lD");

function Stream(options) {
    Parser.call(this, new Cbs(this), options);
}

__webpack_require__(/*! inherits */ "P7XM")(Stream, Parser);

Stream.prototype.readable = true;

function Cbs(scope) {
    this.scope = scope;
}

var EVENTS = __webpack_require__(/*! ../ */ "hS6j").EVENTS;

Object.keys(EVENTS).forEach(function(name) {
    if (EVENTS[name] === 0) {
        Cbs.prototype["on" + name] = function() {
            this.scope.emit(name);
        };
    } else if (EVENTS[name] === 1) {
        Cbs.prototype["on" + name] = function(a) {
            this.scope.emit(name, a);
        };
    } else if (EVENTS[name] === 2) {
        Cbs.prototype["on" + name] = function(a, b) {
            this.scope.emit(name, a, b);
        };
    } else {
        throw Error("wrong number of arguments!");
    }
});


/***/ }),

/***/ "0fF6":
/*!***********************************************************!*\
  !*** ./node_modules/htmlparser2/lib/CollectingHandler.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = CollectingHandler;

function CollectingHandler(cbs) {
    this._cbs = cbs || {};
    this.events = [];
}

var EVENTS = __webpack_require__(/*! ./ */ "hS6j").EVENTS;
Object.keys(EVENTS).forEach(function(name) {
    if (EVENTS[name] === 0) {
        name = "on" + name;
        CollectingHandler.prototype[name] = function() {
            this.events.push([name]);
            if (this._cbs[name]) this._cbs[name]();
        };
    } else if (EVENTS[name] === 1) {
        name = "on" + name;
        CollectingHandler.prototype[name] = function(a) {
            this.events.push([name, a]);
            if (this._cbs[name]) this._cbs[name](a);
        };
    } else if (EVENTS[name] === 2) {
        name = "on" + name;
        CollectingHandler.prototype[name] = function(a, b) {
            this.events.push([name, a, b]);
            if (this._cbs[name]) this._cbs[name](a, b);
        };
    } else {
        throw Error("wrong number of arguments");
    }
});

CollectingHandler.prototype.onreset = function() {
    this.events = [];
    if (this._cbs.onreset) this._cbs.onreset();
};

CollectingHandler.prototype.restart = function() {
    if (this._cbs.onreset) this._cbs.onreset();

    for (var i = 0, len = this.events.length; i < len; i++) {
        if (this._cbs[this.events[i][0]]) {
            var num = this.events[i].length;

            if (num === 1) {
                this._cbs[this.events[i][0]]();
            } else if (num === 2) {
                this._cbs[this.events[i][0]](this.events[i][1]);
            } else {
                this._cbs[this.events[i][0]](
                    this.events[i][1],
                    this.events[i][2]
                );
            }
        }
    }
};


/***/ }),

/***/ "0gkL":
/*!*********************************************************!*\
  !*** ./node_modules/@jupyterlab/csvviewer/lib/parse.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * Possible parser states.
 */
var STATE;
(function (STATE) {
    STATE[STATE["QUOTED_FIELD"] = 0] = "QUOTED_FIELD";
    STATE[STATE["QUOTED_FIELD_QUOTE"] = 1] = "QUOTED_FIELD_QUOTE";
    STATE[STATE["UNQUOTED_FIELD"] = 2] = "UNQUOTED_FIELD";
    STATE[STATE["NEW_FIELD"] = 3] = "NEW_FIELD";
    STATE[STATE["NEW_ROW"] = 4] = "NEW_ROW";
})(STATE || (STATE = {}));
/**
 * Possible row delimiters for the parser.
 */
var ROW_DELIMITER;
(function (ROW_DELIMITER) {
    ROW_DELIMITER[ROW_DELIMITER["CR"] = 0] = "CR";
    ROW_DELIMITER[ROW_DELIMITER["CRLF"] = 1] = "CRLF";
    ROW_DELIMITER[ROW_DELIMITER["LF"] = 2] = "LF";
})(ROW_DELIMITER || (ROW_DELIMITER = {}));
/**
 * Parse delimiter-separated data.
 *
 * @param options: The parser options
 * @returns An object giving the offsets for the rows or columns parsed.
 *
 * #### Notes
 * This implementation is based on [RFC 4180](https://tools.ietf.org/html/rfc4180).
 */
function parseDSV(options) {
    const { data, columnOffsets, delimiter = ',', startIndex = 0, maxRows = 0xffffffff, rowDelimiter = '\r\n', quote = '"' } = options;
    // ncols will be set automatically if it is undefined.
    let ncols = options.ncols;
    // The number of rows we've already parsed.
    let nrows = 0;
    // The row or column offsets we return.
    let offsets = [];
    // Set up some useful local variables.
    const CH_DELIMITER = delimiter.charCodeAt(0);
    const CH_QUOTE = quote.charCodeAt(0);
    const CH_LF = 10; // \n
    const CH_CR = 13; // \r
    const endIndex = data.length;
    const { QUOTED_FIELD, QUOTED_FIELD_QUOTE, UNQUOTED_FIELD, NEW_FIELD, NEW_ROW } = STATE;
    const { CR, LF, CRLF } = ROW_DELIMITER;
    const [rowDelimiterCode, rowDelimiterLength] = rowDelimiter === '\r\n'
        ? [CRLF, 2]
        : rowDelimiter === '\r'
            ? [CR, 1]
            : [LF, 1];
    // Always start off at the beginning of a row.
    let state = NEW_ROW;
    // Set up the starting index.
    let i = startIndex;
    // We initialize to 0 just in case we are asked to parse past the end of the
    // string. In that case, we want the number of columns to be 0.
    let col = 0;
    // Declare some useful temporaries
    let char;
    // Loop through the data string
    while (i < endIndex) {
        // i is the index of a character in the state.
        // If we just hit a new row, and there are still characters left, push a new
        // offset on and reset the column counter. We want this logic at the top of
        // the while loop rather than the bottom because we don't want a trailing
        // row delimiter at the end of the data to trigger a new row offset.
        if (state === NEW_ROW) {
            // Start a new row and reset the column counter.
            offsets.push(i);
            col = 1;
        }
        // Below, we handle this character, modify the parser state and increment the index to be consistent.
        // Get the integer code for the current character, so the comparisons below
        // are faster.
        char = data.charCodeAt(i);
        // Update the parser state. This switch statement is responsible for
        // updating the state to be consistent with the index i+1 (we increment i
        // after the switch statement). In some situations, we may increment i
        // inside this loop to skip over indices as a shortcut.
        switch (state) {
            // At the beginning of a row or field, we can have a quote, row delimiter, or field delimiter.
            case NEW_ROW:
            case NEW_FIELD:
                switch (char) {
                    // If we have a quote, we are starting an escaped field.
                    case CH_QUOTE:
                        state = QUOTED_FIELD;
                        break;
                    // A field delimiter means we are starting a new field.
                    case CH_DELIMITER:
                        state = NEW_FIELD;
                        break;
                    // A row delimiter means we are starting a new row.
                    case CH_CR:
                        if (rowDelimiterCode === CR) {
                            state = NEW_ROW;
                        }
                        else if (rowDelimiterCode === CRLF &&
                            data.charCodeAt(i + 1) === CH_LF) {
                            // If we see an expected \r\n, then increment to the end of the delimiter.
                            i++;
                            state = NEW_ROW;
                        }
                        else {
                            throw `string index ${i} (in row ${nrows}, column ${col}): carriage return found, but not as part of a row delimiter C ${data.charCodeAt(i + 1)}`;
                        }
                        break;
                    case CH_LF:
                        if (rowDelimiterCode === LF) {
                            state = NEW_ROW;
                        }
                        else {
                            throw `string index ${i} (in row ${nrows}, column ${col}): line feed found, but row delimiter starts with a carriage return`;
                        }
                        break;
                    // Otherwise, we are starting an unquoted field.
                    default:
                        state = UNQUOTED_FIELD;
                        break;
                }
                break;
            // We are in a quoted field.
            case QUOTED_FIELD:
                // Skip ahead until we see another quote, which either ends the quoted
                // field or starts an escaped quote.
                i = data.indexOf(quote, i);
                if (i < 0) {
                    throw `string index ${i} (in row ${nrows}, column ${col}): mismatched quote`;
                }
                state = QUOTED_FIELD_QUOTE;
                break;
            // We just saw a quote in a quoted field. This could be the end of the
            // field, or it could be a repeated quote (i.e., an escaped quote according
            // to RFC 4180).
            case QUOTED_FIELD_QUOTE:
                switch (char) {
                    // Another quote means we just saw an escaped quote, so we are still in
                    // the quoted field.
                    case CH_QUOTE:
                        state = QUOTED_FIELD;
                        break;
                    // A field or row delimiter means the quoted field just ended and we are
                    // going into a new field or new row.
                    case CH_DELIMITER:
                        state = NEW_FIELD;
                        break;
                    // A row delimiter means we are starting a new row in the next index.
                    case CH_CR:
                        if (rowDelimiterCode === CR) {
                            state = NEW_ROW;
                        }
                        else if (rowDelimiterCode === CRLF &&
                            data.charCodeAt(i + 1) === CH_LF) {
                            // If we see an expected \r\n, then increment to the end of the delimiter.
                            i++;
                            state = NEW_ROW;
                        }
                        else {
                            throw `string index ${i} (in row ${nrows}, column ${col}): carriage return found, but not as part of a row delimiter C ${data.charCodeAt(i + 1)}`;
                        }
                        break;
                    case CH_LF:
                        if (rowDelimiterCode === LF) {
                            state = NEW_ROW;
                        }
                        else {
                            throw `string index ${i} (in row ${nrows}, column ${col}): line feed found, but row delimiter starts with a carriage return`;
                        }
                        break;
                    default:
                        throw `string index ${i} (in row ${nrows}, column ${col}): quote in escaped field not followed by quote, delimiter, or row delimiter`;
                }
                break;
            // We are in an unquoted field, so the only thing we look for is the next
            // row or field delimiter.
            case UNQUOTED_FIELD:
                // Skip ahead to either the next field delimiter or possible start of a
                // row delimiter (CR or LF).
                while (i < endIndex) {
                    char = data.charCodeAt(i);
                    if (char === CH_DELIMITER || char === CH_LF || char === CH_CR) {
                        break;
                    }
                    i++;
                }
                // Process the character we're seeing in an unquoted field.
                switch (char) {
                    // A field delimiter means we are starting a new field.
                    case CH_DELIMITER:
                        state = NEW_FIELD;
                        break;
                    // A row delimiter means we are starting a new row in the next index.
                    case CH_CR:
                        if (rowDelimiterCode === CR) {
                            state = NEW_ROW;
                        }
                        else if (rowDelimiterCode === CRLF &&
                            data.charCodeAt(i + 1) === CH_LF) {
                            // If we see an expected \r\n, then increment to the end of the delimiter.
                            i++;
                            state = NEW_ROW;
                        }
                        else {
                            throw `string index ${i} (in row ${nrows}, column ${col}): carriage return found, but not as part of a row delimiter C ${data.charCodeAt(i + 1)}`;
                        }
                        break;
                    case CH_LF:
                        if (rowDelimiterCode === LF) {
                            state = NEW_ROW;
                        }
                        else {
                            throw `string index ${i} (in row ${nrows}, column ${col}): line feed found, but row delimiter starts with a carriage return`;
                        }
                        break;
                    // Otherwise, we continue on in the unquoted field.
                    default:
                        continue;
                }
                break;
            // We should never reach this point since the parser state is handled above,
            // so throw an error if we do.
            default:
                throw `string index ${i} (in row ${nrows}, column ${col}): state not recognized`;
        }
        // Increment i to the next character index
        i++;
        // Update return values based on state.
        switch (state) {
            case NEW_ROW:
                nrows++;
                // If we just parsed the first row and the ncols is undefined, set it to
                // the number of columns we found in the first row.
                if (nrows === 1 && ncols === undefined) {
                    ncols = col;
                }
                // Pad or truncate the column offsets in the previous row if we are
                // returning them.
                if (columnOffsets === true) {
                    if (col < ncols) {
                        // We didn't have enough columns, so add some more column offsets that
                        // point to just before the row delimiter we just saw.
                        for (; col < ncols; col++) {
                            offsets.push(i - rowDelimiterLength);
                        }
                    }
                    else if (col > ncols) {
                        // We had too many columns, so truncate them.
                        offsets.length = offsets.length - (col - ncols);
                    }
                }
                // Shortcut return if nrows reaches the maximum rows we are to parse.
                if (nrows === maxRows) {
                    return { nrows, ncols: columnOffsets ? ncols : 0, offsets };
                }
                break;
            case NEW_FIELD:
                // If we are returning column offsets, log the current index.
                if (columnOffsets === true) {
                    offsets.push(i);
                }
                // Update the column counter.
                col++;
                break;
            default:
                break;
        }
    }
    // If we finished parsing and we are *not* in the NEW_ROW state, then do the
    // column padding/truncation for the last row. Also make sure ncols is
    // defined.
    if (state !== NEW_ROW) {
        nrows++;
        if (columnOffsets === true) {
            // If ncols is *still* undefined, then we only parsed one row and didn't
            // have a newline, so set it to the number of columns we found.
            if (ncols === undefined) {
                ncols = col;
            }
            if (col < ncols) {
                // We didn't have enough columns, so add some more column offsets that
                // point to just before the row delimiter we just saw.
                for (; col < ncols; col++) {
                    offsets.push(i - (rowDelimiterLength - 1));
                }
            }
            else if (col > ncols) {
                // We had too many columns, so truncate them.
                offsets.length = offsets.length - (col - ncols);
            }
        }
    }
    return { nrows, ncols: columnOffsets ? ncols : 0, offsets };
}
exports.parseDSV = parseDSV;
/**
 * Parse delimiter-separated data where no delimiter is quoted.
 *
 * @param options: The parser options
 * @returns An object giving the offsets for the rows or columns parsed.
 *
 * #### Notes
 * This function is an optimized parser for cases where there are no field or
 * row delimiters in quotes. Note that the data can have quotes, but they are
 * not interpreted in any special way. This implementation is based on [RFC
 * 4180](https://tools.ietf.org/html/rfc4180), but disregards quotes.
 */
function parseDSVNoQuotes(options) {
    // Set option defaults.
    const { data, columnOffsets, delimiter = ',', rowDelimiter = '\r\n', startIndex = 0, maxRows = 0xffffffff } = options;
    // ncols will be set automatically if it is undefined.
    let ncols = options.ncols;
    // Set up our return variables.
    let offsets = [];
    let nrows = 0;
    // Set up various state variables.
    let rowDelimiterLength = rowDelimiter.length;
    let currRow = startIndex;
    let len = data.length;
    let nextRow;
    let col;
    let rowString;
    let colIndex;
    // The end of the current row.
    let rowEnd;
    // Start parsing at the start index.
    nextRow = startIndex;
    // Loop through rows until we run out of data or we've reached maxRows.
    while (nextRow !== -1 && nrows < maxRows && currRow < len) {
        // Store the offset for the beginning of the row and increment the rows.
        offsets.push(currRow);
        nrows++;
        // Find the next row delimiter.
        nextRow = data.indexOf(rowDelimiter, currRow);
        // If the next row delimiter is not found, set the end of the row to the
        // end of the data string.
        rowEnd = nextRow === -1 ? len : nextRow;
        // If we are returning column offsets, push them onto the array.
        if (columnOffsets === true) {
            // Find the next field delimiter. We slice the current row out so that
            // the indexOf will stop at the end of the row. It may possibly be faster
            // to just use a loop to check each character.
            col = 1;
            rowString = data.slice(currRow, rowEnd);
            colIndex = rowString.indexOf(delimiter);
            if (ncols === undefined) {
                // If we don't know how many columns we need, loop through and find all
                // of the field delimiters in this row.
                while (colIndex !== -1) {
                    offsets.push(currRow + colIndex + 1);
                    col++;
                    colIndex = rowString.indexOf(delimiter, colIndex + 1);
                }
                // Set ncols to the number of fields we found.
                ncols = col;
            }
            else {
                // If we know the number of columns we expect, find the field delimiters
                // up to that many columns.
                while (colIndex !== -1 && col < ncols) {
                    offsets.push(currRow + colIndex + 1);
                    col++;
                    colIndex = rowString.indexOf(delimiter, colIndex + 1);
                }
                // If we didn't reach the number of columns we expected, pad the offsets
                // with the offset just before the row delimiter.
                while (col < ncols) {
                    offsets.push(rowEnd);
                    col++;
                }
            }
        }
        // Skip past the row delimiter at the end of the row.
        currRow = rowEnd + rowDelimiterLength;
    }
    return { nrows, ncols: columnOffsets ? ncols : 0, offsets };
}
exports.parseDSVNoQuotes = parseDSVNoQuotes;


/***/ }),

/***/ "0jI2":
/*!*****************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/title.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
/**
 * An object which holds data related to an object's title.
 *
 * #### Notes
 * A title object is intended to hold the data necessary to display a
 * header for a particular object. A common example is the `TabPanel`,
 * which uses the widget title to populate the tab for a child widget.
 */
var Title = (function () {
    /**
     * Construct a new title.
     *
     * @param options - The options for initializing the title.
     */
    function Title(options) {
        this._label = '';
        this._caption = '';
        this._mnemonic = -1;
        this._iconClass = '';
        this._iconLabel = '';
        this._className = '';
        this._closable = false;
        this._changed = new signaling_1.Signal(this);
        this.owner = options.owner;
        if (options.label !== undefined) {
            this._label = options.label;
        }
        if (options.mnemonic !== undefined) {
            this._mnemonic = options.mnemonic;
        }
        if (options.icon !== undefined) {
            this._iconClass = options.icon;
        }
        if (options.iconClass !== undefined) {
            this._iconClass = options.iconClass;
        }
        if (options.iconLabel !== undefined) {
            this._iconLabel = options.iconLabel;
        }
        if (options.caption !== undefined) {
            this._caption = options.caption;
        }
        if (options.className !== undefined) {
            this._className = options.className;
        }
        if (options.closable !== undefined) {
            this._closable = options.closable;
        }
        this._dataset = options.dataset || {};
    }
    Object.defineProperty(Title.prototype, "changed", {
        /**
         * A signal emitted when the state of the title changes.
         */
        get: function () {
            return this._changed;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Title.prototype, "label", {
        /**
         * Get the label for the title.
         *
         * #### Notes
         * The default value is an empty string.
         */
        get: function () {
            return this._label;
        },
        /**
         * Set the label for the title.
         */
        set: function (value) {
            if (this._label === value) {
                return;
            }
            this._label = value;
            this._changed.emit(undefined);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Title.prototype, "mnemonic", {
        /**
         * Get the mnemonic index for the title.
         *
         * #### Notes
         * The default value is `-1`.
         */
        get: function () {
            return this._mnemonic;
        },
        /**
         * Set the mnemonic index for the title.
         */
        set: function (value) {
            if (this._mnemonic === value) {
                return;
            }
            this._mnemonic = value;
            this._changed.emit(undefined);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Title.prototype, "icon", {
        /**
         * @deprecated Use `iconClass` instead.
         */
        get: function () {
            return this.iconClass;
        },
        /**
         * @deprecated Use `iconClass` instead.
         */
        set: function (value) {
            this.iconClass = value;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Title.prototype, "iconClass", {
        /**
         * Get the icon class name for the title.
         *
         * #### Notes
         * The default value is an empty string.
         */
        get: function () {
            return this._iconClass;
        },
        /**
         * Set the icon class name for the title.
         *
         * #### Notes
         * Multiple class names can be separated with whitespace.
         */
        set: function (value) {
            if (this._iconClass === value) {
                return;
            }
            this._iconClass = value;
            this._changed.emit(undefined);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Title.prototype, "iconLabel", {
        /**
         * Get the icon label for the title.
         *
         * #### Notes
         * The default value is an empty string.
         */
        get: function () {
            return this._iconLabel;
        },
        /**
         * Set the icon label for the title.
         *
         * #### Notes
         * Multiple class names can be separated with whitespace.
         */
        set: function (value) {
            if (this._iconLabel === value) {
                return;
            }
            this._iconLabel = value;
            this._changed.emit(undefined);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Title.prototype, "caption", {
        /**
         * Get the caption for the title.
         *
         * #### Notes
         * The default value is an empty string.
         */
        get: function () {
            return this._caption;
        },
        /**
         * Set the caption for the title.
         */
        set: function (value) {
            if (this._caption === value) {
                return;
            }
            this._caption = value;
            this._changed.emit(undefined);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Title.prototype, "className", {
        /**
         * Get the extra class name for the title.
         *
         * #### Notes
         * The default value is an empty string.
         */
        get: function () {
            return this._className;
        },
        /**
         * Set the extra class name for the title.
         *
         * #### Notes
         * Multiple class names can be separated with whitespace.
         */
        set: function (value) {
            if (this._className === value) {
                return;
            }
            this._className = value;
            this._changed.emit(undefined);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Title.prototype, "closable", {
        /**
         * Get the closable state for the title.
         *
         * #### Notes
         * The default value is `false`.
         */
        get: function () {
            return this._closable;
        },
        /**
         * Set the closable state for the title.
         *
         * #### Notes
         * This controls the presence of a close icon when applicable.
         */
        set: function (value) {
            if (this._closable === value) {
                return;
            }
            this._closable = value;
            this._changed.emit(undefined);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Title.prototype, "dataset", {
        /**
         * Get the dataset for the title.
         *
         * #### Notes
         * The default value is an empty dataset.
         */
        get: function () {
            return this._dataset;
        },
        /**
         * Set the dataset for the title.
         *
         * #### Notes
         * This controls the data attributes when applicable.
         */
        set: function (value) {
            if (this._dataset === value) {
                return;
            }
            this._dataset = value;
            this._changed.emit(undefined);
        },
        enumerable: true,
        configurable: true
    });
    return Title;
}());
exports.Title = Title;


/***/ }),

/***/ "0ks7":
/*!****************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/kernel/kernel.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const default_1 = __webpack_require__(/*! ./default */ "YC29");
/**
 * A namespace for kernel types, interfaces, and type checker functions.
 */
var Kernel;
(function (Kernel) {
    /**
     * Find a kernel by id.
     *
     * @param id - The id of the kernel of interest.
     *
     * @param settings - The optional server settings.
     *
     * @returns A promise that resolves with the model for the kernel.
     *
     * #### Notes
     * If the kernel was already started via `startNewKernel`, we return its
     * `Kernel.IModel`. Otherwise, we attempt to find the existing kernel. The
     * promise is fulfilled when the kernel is found, otherwise the promise is
     * rejected.
     */
    function findById(id, settings) {
        return default_1.DefaultKernel.findById(id, settings);
    }
    Kernel.findById = findById;
    /**
     * Fetch all of the kernel specs.
     *
     * @param settings - The optional server settings.
     *
     * @returns A promise that resolves with the kernel specs.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernelspecs).
     */
    function getSpecs(settings) {
        return default_1.DefaultKernel.getSpecs(settings);
    }
    Kernel.getSpecs = getSpecs;
    /**
     * Fetch the running kernels.
     *
     * @param settings - The optional server settings.
     *
     * @returns A promise that resolves with the list of running kernels.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels) and validates the response model.
     *
     * The promise is fulfilled on a valid response and rejected otherwise.
     */
    function listRunning(settings) {
        return default_1.DefaultKernel.listRunning(settings);
    }
    Kernel.listRunning = listRunning;
    /**
     * Start a new kernel.
     *
     * @param options - The options used to create the kernel.
     *
     * @returns A promise that resolves with a kernel object.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels) and validates the response model.
     *
     * If no options are given or the kernel name is not given, the
     * default kernel will by started by the server.
     *
     * Wraps the result in a Kernel object. The promise is fulfilled
     * when the kernel is started by the server, otherwise the promise is rejected.
     */
    function startNew(options = {}) {
        return default_1.DefaultKernel.startNew(options);
    }
    Kernel.startNew = startNew;
    /**
     * Connect to a running kernel.
     *
     * @param model - The model of the running kernel.
     *
     * @param settings - The server settings for the request.
     *
     * @returns The kernel object.
     *
     * #### Notes
     * If the kernel was already started via `startNewKernel`, the existing
     * Kernel object info is used to create another instance.
     */
    function connectTo(model, settings) {
        return default_1.DefaultKernel.connectTo(model, settings);
    }
    Kernel.connectTo = connectTo;
    /**
     * Shut down a kernel by id.
     *
     * @param id - The id of the running kernel.
     *
     * @param settings - The server settings for the request.
     *
     * @returns A promise that resolves when the kernel is shut down.
     */
    function shutdown(id, settings) {
        return default_1.DefaultKernel.shutdown(id, settings);
    }
    Kernel.shutdown = shutdown;
    /**
     * Shut down all kernels.
     *
     * @returns A promise that resolves when all of the kernels are shut down.
     */
    function shutdownAll(settings) {
        return default_1.DefaultKernel.shutdownAll(settings);
    }
    Kernel.shutdownAll = shutdownAll;
})(Kernel = exports.Kernel || (exports.Kernel = {}));


/***/ }),

/***/ "0mo+":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/bo.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var symbolMap = {
    '1': '༡',
    '2': '༢',
    '3': '༣',
    '4': '༤',
    '5': '༥',
    '6': '༦',
    '7': '༧',
    '8': '༨',
    '9': '༩',
    '0': '༠'
},
numberMap = {
    '༡': '1',
    '༢': '2',
    '༣': '3',
    '༤': '4',
    '༥': '5',
    '༦': '6',
    '༧': '7',
    '༨': '8',
    '༩': '9',
    '༠': '0'
};

var bo = moment.defineLocale('bo', {
    months : 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split('_'),
    monthsShort : 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split('_'),
    weekdays : 'གཟའ་ཉི་མ་_གཟའ་ཟླ་བ་_གཟའ་མིག་དམར་_གཟའ་ལྷག་པ་_གཟའ་ཕུར་བུ_གཟའ་པ་སངས་_གཟའ་སྤེན་པ་'.split('_'),
    weekdaysShort : 'ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་'.split('_'),
    weekdaysMin : 'ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་'.split('_'),
    longDateFormat : {
        LT : 'A h:mm',
        LTS : 'A h:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY, A h:mm',
        LLLL : 'dddd, D MMMM YYYY, A h:mm'
    },
    calendar : {
        sameDay : '[དི་རིང] LT',
        nextDay : '[སང་ཉིན] LT',
        nextWeek : '[བདུན་ཕྲག་རྗེས་མ], LT',
        lastDay : '[ཁ་སང] LT',
        lastWeek : '[བདུན་ཕྲག་མཐའ་མ] dddd, LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : '%s ལ་',
        past : '%s སྔན་ལ',
        s : 'ལམ་སང',
        ss : '%d སྐར་ཆ།',
        m : 'སྐར་མ་གཅིག',
        mm : '%d སྐར་མ',
        h : 'ཆུ་ཚོད་གཅིག',
        hh : '%d ཆུ་ཚོད',
        d : 'ཉིན་གཅིག',
        dd : '%d ཉིན་',
        M : 'ཟླ་བ་གཅིག',
        MM : '%d ཟླ་བ',
        y : 'ལོ་གཅིག',
        yy : '%d ལོ'
    },
    preparse: function (string) {
        return string.replace(/[༡༢༣༤༥༦༧༨༩༠]/g, function (match) {
            return numberMap[match];
        });
    },
    postformat: function (string) {
        return string.replace(/\d/g, function (match) {
            return symbolMap[match];
        });
    },
    meridiemParse: /མཚན་མོ|ཞོགས་ཀས|ཉིན་གུང|དགོང་དག|མཚན་མོ/,
    meridiemHour : function (hour, meridiem) {
        if (hour === 12) {
            hour = 0;
        }
        if ((meridiem === 'མཚན་མོ' && hour >= 4) ||
                (meridiem === 'ཉིན་གུང' && hour < 5) ||
                meridiem === 'དགོང་དག') {
            return hour + 12;
        } else {
            return hour;
        }
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 4) {
            return 'མཚན་མོ';
        } else if (hour < 10) {
            return 'ཞོགས་ཀས';
        } else if (hour < 17) {
            return 'ཉིན་གུང';
        } else if (hour < 20) {
            return 'དགོང་དག';
        } else {
            return 'མཚན་མོ';
        }
    },
    week : {
        dow : 0, // Sunday is the first day of the week.
        doy : 6  // The week that contains Jan 1st is the first week of the year.
    }
});

return bo;

})));


/***/ }),

/***/ "0pX1":
/*!********************************************************************!*\
  !*** ./node_modules/@jupyterlab/settingeditor/lib/plugineditor.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const raweditor_1 = __webpack_require__(/*! ./raweditor */ "ZHg6");
const tableeditor_1 = __webpack_require__(/*! ./tableeditor */ "U45Y");
/**
 * The class name added to all plugin editors.
 */
const PLUGIN_EDITOR_CLASS = 'jp-PluginEditor';
/**
 * An individual plugin settings editor.
 */
class PluginEditor extends widgets_1.Widget {
    /**
     * Create a new plugin editor.
     *
     * @param options - The plugin editor instantiation options.
     */
    constructor(options) {
        super();
        this._editor = 'raw';
        this._settings = null;
        this._stateChanged = new signaling_1.Signal(this);
        this.addClass(PLUGIN_EDITOR_CLASS);
        const { commands, editorFactory, registry, rendermime } = options;
        const layout = (this.layout = new widgets_1.StackedLayout());
        const { onSaveError } = Private;
        this.raw = this._rawEditor = new raweditor_1.RawEditor({
            commands,
            editorFactory,
            onSaveError,
            registry,
            rendermime
        });
        this.table = this._tableEditor = new tableeditor_1.TableEditor({ onSaveError });
        this._rawEditor.handleMoved.connect(this._onStateChanged, this);
        layout.addWidget(this._rawEditor);
        layout.addWidget(this._tableEditor);
    }
    /**
     * Tests whether the settings have been modified and need saving.
     */
    get isDirty() {
        return this._rawEditor.isDirty || this._tableEditor.isDirty;
    }
    /**
     * The plugin settings being edited.
     */
    get settings() {
        return this._settings;
    }
    set settings(settings) {
        if (this._settings === settings) {
            return;
        }
        const raw = this._rawEditor;
        const table = this._tableEditor;
        this._settings = raw.settings = table.settings = settings;
        this.update();
    }
    /**
     * The plugin editor layout state.
     */
    get state() {
        const editor = this._editor;
        const plugin = this._settings ? this._settings.plugin : '';
        const { sizes } = this._rawEditor;
        return { editor, plugin, sizes };
    }
    set state(state) {
        if (coreutils_1.JSONExt.deepEqual(this.state, state)) {
            return;
        }
        this._editor = state.editor;
        this._rawEditor.sizes = state.sizes;
        this.update();
    }
    /**
     * A signal that emits when editor layout state changes and needs to be saved.
     */
    get stateChanged() {
        return this._stateChanged;
    }
    /**
     * If the editor is in a dirty state, confirm that the user wants to leave.
     */
    confirm() {
        if (this.isHidden || !this.isAttached || !this.isDirty) {
            return Promise.resolve(undefined);
        }
        return apputils_1.showDialog({
            title: 'You have unsaved changes.',
            body: 'Do you want to leave without saving?',
            buttons: [apputils_1.Dialog.cancelButton(), apputils_1.Dialog.okButton()]
        }).then(result => {
            if (!result.button.accept) {
                throw new Error('User canceled.');
            }
        });
    }
    /**
     * Dispose of the resources held by the plugin editor.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        super.dispose();
        this._rawEditor.dispose();
        this._tableEditor.dispose();
    }
    /**
     * Handle `after-attach` messages.
     */
    onAfterAttach(msg) {
        this.update();
    }
    /**
     * Handle `'update-request'` messages.
     */
    onUpdateRequest(msg) {
        const editor = this._editor;
        const raw = this._rawEditor;
        const table = this._tableEditor;
        const settings = this._settings;
        if (!settings) {
            this.hide();
            return;
        }
        this.show();
        (editor === 'raw' ? table : raw).hide();
        (editor === 'raw' ? raw : table).show();
    }
    /**
     * Handle layout state changes that need to be saved.
     */
    _onStateChanged() {
        this.stateChanged.emit(undefined);
    }
}
exports.PluginEditor = PluginEditor;
/**
 * A namespace for private module data.
 */
var Private;
(function (Private) {
    /**
     * Handle save errors.
     */
    function onSaveError(reason) {
        console.error(`Saving setting editor value failed: ${reason.message}`);
        apputils_1.showDialog({
            title: 'Your changes were not saved.',
            body: reason.message,
            buttons: [apputils_1.Dialog.okButton()]
        });
    }
    Private.onSaveError = onSaveError;
})(Private || (Private = {}));


/***/ }),

/***/ "0tRk":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/pt-br.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var ptBr = moment.defineLocale('pt-br', {
    months : 'janeiro_fevereiro_março_abril_maio_junho_julho_agosto_setembro_outubro_novembro_dezembro'.split('_'),
    monthsShort : 'jan_fev_mar_abr_mai_jun_jul_ago_set_out_nov_dez'.split('_'),
    weekdays : 'Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado'.split('_'),
    weekdaysShort : 'Dom_Seg_Ter_Qua_Qui_Sex_Sáb'.split('_'),
    weekdaysMin : 'Do_2ª_3ª_4ª_5ª_6ª_Sá'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D [de] MMMM [de] YYYY',
        LLL : 'D [de] MMMM [de] YYYY [às] HH:mm',
        LLLL : 'dddd, D [de] MMMM [de] YYYY [às] HH:mm'
    },
    calendar : {
        sameDay: '[Hoje às] LT',
        nextDay: '[Amanhã às] LT',
        nextWeek: 'dddd [às] LT',
        lastDay: '[Ontem às] LT',
        lastWeek: function () {
            return (this.day() === 0 || this.day() === 6) ?
                '[Último] dddd [às] LT' : // Saturday + Sunday
                '[Última] dddd [às] LT'; // Monday - Friday
        },
        sameElse: 'L'
    },
    relativeTime : {
        future : 'em %s',
        past : 'há %s',
        s : 'poucos segundos',
        ss : '%d segundos',
        m : 'um minuto',
        mm : '%d minutos',
        h : 'uma hora',
        hh : '%d horas',
        d : 'um dia',
        dd : '%d dias',
        M : 'um mês',
        MM : '%d meses',
        y : 'um ano',
        yy : '%d anos'
    },
    dayOfMonthOrdinalParse: /\d{1,2}º/,
    ordinal : '%dº'
});

return ptBr;

})));


/***/ }),

/***/ "0tVu":
/*!***************************************************************!*\
  !*** ./node_modules/codemirror/addon/scroll/scrollpastend.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"));
  else {}
})(function(CodeMirror) {
  "use strict";

  CodeMirror.defineOption("scrollPastEnd", false, function(cm, val, old) {
    if (old && old != CodeMirror.Init) {
      cm.off("change", onChange);
      cm.off("refresh", updateBottomMargin);
      cm.display.lineSpace.parentNode.style.paddingBottom = "";
      cm.state.scrollPastEndPadding = null;
    }
    if (val) {
      cm.on("change", onChange);
      cm.on("refresh", updateBottomMargin);
      updateBottomMargin(cm);
    }
  });

  function onChange(cm, change) {
    if (CodeMirror.changeEnd(change).line == cm.lastLine())
      updateBottomMargin(cm);
  }

  function updateBottomMargin(cm) {
    var padding = "";
    if (cm.lineCount() > 1) {
      var totalH = cm.display.scroller.clientHeight - 30,
          lastLineH = cm.getLineHandle(cm.lastLine()).height;
      padding = (totalH - lastLineH) + "px";
    }
    if (cm.state.scrollPastEndPadding != padding) {
      cm.state.scrollPastEndPadding = padding;
      cm.display.lineSpace.parentNode.style.paddingBottom = padding;
      cm.off("refresh", updateBottomMargin);
      cm.setSize();
      cm.on("refresh", updateBottomMargin);
    }
  }
});


/***/ }),

/***/ "0w4r":
/*!***************************************************!*\
  !*** ./node_modules/ajv/lib/dotjs/uniqueItems.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_uniqueItems(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  if (($schema || $isData) && it.opts.uniqueItems !== false) {
    if ($isData) {
      out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { ';
    }
    out += ' var ' + ($valid) + ' = true; if (' + ($data) + '.length > 1) { var i = ' + ($data) + '.length, j; outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } } ';
    if ($isData) {
      out += '  }  ';
    }
    out += ' if (!' + ($valid) + ') {   ';
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = ''; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema:  ';
        if ($isData) {
          out += 'validate.schema' + ($schemaPath);
        } else {
          out += '' + ($schema);
        }
        out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError([' + (__err) + ']); ';
      } else {
        out += ' validate.errors = [' + (__err) + ']; return false; ';
      }
    } else {
      out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    }
    out += ' } ';
    if ($breakOnError) {
      out += ' else { ';
    }
  } else {
    if ($breakOnError) {
      out += ' if (true) { ';
    }
  }
  return out;
}


/***/ }),

/***/ "0wH6":
/*!*****************************************************************!*\
  !*** ./node_modules/plotly.js/src/plots/cartesian/constants.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


var counterRegex = __webpack_require__(/*! ../../lib/regex */ "BVrX").counter;


module.exports = {

    idRegex: {
        x: counterRegex('x'),
        y: counterRegex('y')
    },

    attrRegex: counterRegex('[xy]axis'),

    // axis match regular expression
    xAxisMatch: counterRegex('xaxis'),
    yAxisMatch: counterRegex('yaxis'),

    // pattern matching axis ids and names
    // note that this is more permissive than counterRegex, as
    // id2name, name2id, and cleanId accept "x1" etc
    AX_ID_PATTERN: /^[xyz][0-9]*$/,
    AX_NAME_PATTERN: /^[xyz]axis[0-9]*$/,

    // and for 2D subplots
    SUBPLOT_PATTERN: /^x([0-9]*)y([0-9]*)$/,

    // pixels to move mouse before you stop clamping to starting point
    MINDRAG: 8,

    // smallest dimension allowed for a select box
    MINSELECT: 12,

    // smallest dimension allowed for a zoombox
    MINZOOM: 20,

    // width of axis drag regions
    DRAGGERSIZE: 20,

    // max pixels off straight before a lasso select line counts as bent
    BENDPX: 1.5,

    // delay before a redraw (relayout) after smooth panning and zooming
    REDRAWDELAY: 50,

    // throttling limit (ms) for selectPoints calls
    SELECTDELAY: 100,

    // cache ID suffix for throttle
    SELECTID: '-select',

    // last resort axis ranges for x and y axes if we have no data
    DFLTRANGEX: [-1, 6],
    DFLTRANGEY: [-1, 4],

    // Layers to keep trace types in the right order
    // N.B. each  'unique' plot method must have its own layer
    traceLayerClasses: [
        'heatmaplayer',
        'contourcarpetlayer', 'contourlayer',
        'barlayer',
        'carpetlayer',
        'violinlayer',
        'boxlayer',
        'ohlclayer',
        'scattercarpetlayer', 'scatterlayer'
    ],

    layerValue2layerClass: {
        'above traces': 'above',
        'below traces': 'below'
    }
};


/***/ }),

/***/ "0yVM":
/*!*****************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotPieIcon.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotPieIcon = function PlotPieIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M14.438 2.5C6.438 2.563 0 9.063 0 17c0 8.063 6.5 14.563 14.5 14.563 3.5 0 6.625-1.188 9.125-3.188l-9.188-10.813zm16.875 13.063V15c0-8.063-6.5-14.563-14.563-14.563h-.063v15.125zM32 17.75H17.437l9.125 10.813C29.75 26 31.875 22.125 32 17.75z' })
    );
};

exports.default = PlotPieIcon;

/***/ }),

/***/ "0ycA":
/*!******************************************!*\
  !*** ./node_modules/lodash/stubArray.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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 [];
}

module.exports = stubArray;


/***/ }),

/***/ "0zcU":
/*!***************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotScatterMatrixIcon.js ***!
  \***************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotScatterMatrixIcon = function PlotScatterMatrixIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M14.938 0h2v32h-2zM0 14.938h32v2H0zm2.563-1.5l-2-.125c.125-1.563.75-4.125 2.875-4.125 1.25 0 2 .688 2.688 1.188.813.688 1.063.813 1.5.688.625-.25 1.563-2.5 2.125-4.125.375-1.188.813-2.375 1.313-3.313 1.5-2.813 3.063-3.063 3.313-3.25l.313 2s-.938.313-2 2.188c-.313.75-.688 1.813-1.063 3.063-.938 2.5-1.75 4.75-3.375 5.313-1.438.5-2.5-.375-3.313-.938-.563-.375-.938-.813-1.5-.813-.5 0-.875 1.5-.875 2.25zM22 7.313c-.813 0-1.313-.5-1.313-1.313s.5-1.313 1.313-1.313 1.313.5 1.313 1.313-.5 1.313-1.313 1.313zm0-2v.688zm5.313 2C26.563 7.313 26 6.813 26 6s.563-1.313 1.313-1.313c.813 0 1.375.5 1.375 1.313s-.563 1.313-1.375 1.313zm0-2v.688zm.687-2c-.813 0-1.313-.5-1.313-1.313S27.187.687 28 .687s1.313.5 1.313 1.313-.5 1.313-1.313 1.313zm0-2v.688zM19.313 14c-.75 0-1.313-.563-1.313-1.313 0-.813.563-1.375 1.313-1.375.813 0 1.375.563 1.375 1.375 0 .75-.563 1.313-1.375 1.313zm0-2v.688zM28 12c-.813 0-1.313-.563-1.313-1.313 0-.813.5-1.375 1.313-1.375s1.313.563 1.313 1.375c0 .75-.5 1.313-1.313 1.313zm0-2v.688zm-4.687 2.688c-.75 0-1.313-.563-1.313-1.375 0-.75.563-1.313 1.313-1.313.813 0 1.375.563 1.375 1.313 0 .813-.563 1.375-1.375 1.375zm0-2v.625zm-16 14c-.75 0-1.313-.563-1.313-1.375C6 22.563 6.563 22 7.313 22c.813 0 1.375.563 1.375 1.313 0 .813-.563 1.375-1.375 1.375zm0-2v.625zm5.375 2.625c-.813 0-1.375-.5-1.375-1.313s.563-1.313 1.375-1.313c.75 0 1.313.5 1.313 1.313s-.563 1.313-1.313 1.313zm0-2v.688zm0-2.625c-.813 0-1.375-.563-1.375-1.375 0-.75.563-1.313 1.375-1.313.75 0 1.313.563 1.313 1.313 0 .813-.563 1.375-1.313 1.375zm0-2v.625zM4.688 30c-.813 0-1.375-.563-1.375-1.313 0-.813.563-1.375 1.375-1.375.75 0 1.313.563 1.313 1.375 0 .75-.563 1.313-1.313 1.313zm0-2v.688zm6.625 2c-.75 0-1.313-.563-1.313-1.313 0-.813.563-1.375 1.313-1.375.813 0 1.375.563 1.375 1.375 0 .75-.563 1.313-1.375 1.313zm0-2v.688zm18.437 2.938c-.813-2.375-2.563-6.563-3.75-7.625-.375 0-1.063 1.063-1.438 1.625-.813 1.188-1.75 2.375-3.125 2.688-.25 0-.75 0-1.313-.438-1.75-1.313-2.25-6.938-2.5-8.5l2-.125c.25 3.188 1.063 6.375 1.563 7.063.438-.313 1.188-1.25 1.625-1.875.938-1.188 1.75-2.313 2.813-2.438.375 0 .938 0 1.563.563 2 1.75 4 7.75 4.25 8.375z' })
    );
};

exports.default = PlotScatterMatrixIcon;

/***/ }),

/***/ "1+5i":
/*!**************************************!*\
  !*** ./node_modules/lodash/isSet.js ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseIsSet = __webpack_require__(/*! ./_baseIsSet */ "w/wX"),
    baseUnary = __webpack_require__(/*! ./_baseUnary */ "sEf8"),
    nodeUtil = __webpack_require__(/*! ./_nodeUtil */ "mdPL");

/* Node.js helper references. */
var nodeIsSet = nodeUtil && nodeUtil.isSet;

/**
 * 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;

module.exports = isSet;


/***/ }),

/***/ "14pl":
/*!*******************************************************************!*\
  !*** ./node_modules/@jupyterlab/observables/lib/observablemap.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
/**
 * A concrete implementation of IObservbleMap<T>.
 */
class ObservableMap {
    /**
     * Construct a new observable map.
     */
    constructor(options = {}) {
        this._map = new Map();
        this._changed = new signaling_1.Signal(this);
        this._isDisposed = false;
        this._itemCmp = options.itemCmp || Private.itemCmp;
        if (options.values) {
            for (let key in options.values) {
                this._map.set(key, options.values[key]);
            }
        }
    }
    /**
     * The type of the Observable.
     */
    get type() {
        return 'Map';
    }
    /**
     * A signal emitted when the map has changed.
     */
    get changed() {
        return this._changed;
    }
    /**
     * Whether this map has been disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * The number of key-value pairs in the map.
     */
    get size() {
        return this._map.size;
    }
    /**
     * Set a key-value pair in the map
     *
     * @param key - The key to set.
     *
     * @param value - The value for the key.
     *
     * @returns the old value for the key, or undefined
     *   if that did not exist.
     *
     * @throws if the new value is undefined.
     *
     * #### Notes
     * This is a no-op if the value does not change.
     */
    set(key, value) {
        let oldVal = this._map.get(key);
        if (value === undefined) {
            throw Error('Cannot set an undefined value, use remove');
        }
        // Bail if the value does not change.
        let itemCmp = this._itemCmp;
        if (oldVal !== undefined && itemCmp(oldVal, value)) {
            return oldVal;
        }
        this._map.set(key, value);
        this._changed.emit({
            type: oldVal ? 'change' : 'add',
            key: key,
            oldValue: oldVal,
            newValue: value
        });
        return oldVal;
    }
    /**
     * Get a value for a given key.
     *
     * @param key - the key.
     *
     * @returns the value for that key.
     */
    get(key) {
        return this._map.get(key);
    }
    /**
     * Check whether the map has a key.
     *
     * @param key - the key to check.
     *
     * @returns `true` if the map has the key, `false` otherwise.
     */
    has(key) {
        return this._map.has(key);
    }
    /**
     * Get a list of the keys in the map.
     *
     * @returns - a list of keys.
     */
    keys() {
        let keyList = [];
        this._map.forEach((v, k) => {
            keyList.push(k);
        });
        return keyList;
    }
    /**
     * Get a list of the values in the map.
     *
     * @returns - a list of values.
     */
    values() {
        let valList = [];
        this._map.forEach((v, k) => {
            valList.push(v);
        });
        return valList;
    }
    /**
     * Remove a key from the map
     *
     * @param key - the key to remove.
     *
     * @returns the value of the given key,
     *   or undefined if that does not exist.
     */
    delete(key) {
        let oldVal = this._map.get(key);
        this._map.delete(key);
        this._changed.emit({
            type: 'remove',
            key: key,
            oldValue: oldVal,
            newValue: undefined
        });
        return oldVal;
    }
    /**
     * Set the ObservableMap to an empty map.
     */
    clear() {
        // Delete one by one to emit the correct signals.
        let keyList = this.keys();
        for (let i = 0; i < keyList.length; i++) {
            this.delete(keyList[i]);
        }
    }
    /**
     * Dispose of the resources held by the map.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        signaling_1.Signal.clearData(this);
        this._map.clear();
    }
}
exports.ObservableMap = ObservableMap;
/**
 * The namespace for module private data.
 */
var Private;
(function (Private) {
    /**
     * The default strict equality item comparator.
     */
    function itemCmp(first, second) {
        return first === second;
    }
    Private.itemCmp = itemCmp;
})(Private || (Private = {}));


/***/ }),

/***/ "158f":
/*!**********************************************************!*\
  !*** ./node_modules/draft-js/lib/getRangeClientRects.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule getRangeClientRects
 * @format
 * 
 */



var UserAgent = __webpack_require__(/*! fbjs/lib/UserAgent */ "CYTE");

var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");

var isChrome = UserAgent.isBrowser('Chrome');

// In Chrome, the client rects will include the entire bounds of all nodes that
// begin (have a start tag) within the selection, even if the selection does
// not overlap the entire node. To resolve this, we split the range at each
// start tag and join the client rects together.
// https://code.google.com/p/chromium/issues/detail?id=324437
/* eslint-disable consistent-return */
function getRangeClientRectsChrome(range) {
  var tempRange = range.cloneRange();
  var clientRects = [];

  for (var ancestor = range.endContainer; ancestor != null; ancestor = ancestor.parentNode) {
    // If we've climbed up to the common ancestor, we can now use the
    // original start point and stop climbing the tree.
    var atCommonAncestor = ancestor === range.commonAncestorContainer;
    if (atCommonAncestor) {
      tempRange.setStart(range.startContainer, range.startOffset);
    } else {
      tempRange.setStart(tempRange.endContainer, 0);
    }
    var rects = Array.from(tempRange.getClientRects());
    clientRects.push(rects);
    if (atCommonAncestor) {
      var _ref;

      clientRects.reverse();
      return (_ref = []).concat.apply(_ref, clientRects);
    }
    tempRange.setEndBefore(ancestor);
  }

   true ?  true ? invariant(false, 'Found an unexpected detached subtree when getting range client rects.') : undefined : undefined;
}
/* eslint-enable consistent-return */

/**
 * Like range.getClientRects() but normalizes for browser bugs.
 */
var getRangeClientRects = isChrome ? getRangeClientRectsChrome : function (range) {
  return Array.from(range.getClientRects());
};

module.exports = getRangeClientRects;

/***/ }),

/***/ "17x9":
/*!******************************************!*\
  !*** ./node_modules/prop-types/index.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

if (true) {
  var ReactIs = __webpack_require__(/*! react-is */ "TOwV");

  // By explicitly using `prop-types` you are opting into new development behavior.
  // http://fb.me/prop-types-in-prod
  var throwOnDirectAccess = true;
  module.exports = __webpack_require__(/*! ./factoryWithTypeCheckers */ "sHIV")(ReactIs.isElement, throwOnDirectAccess);
} else {}


/***/ }),

/***/ "1CSz":
/*!********************************************!*\
  !*** ./node_modules/create-hmac/legacy.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var inherits = __webpack_require__(/*! inherits */ "P7XM")
var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer

var Base = __webpack_require__(/*! cipher-base */ "ZDAU")

var ZEROS = Buffer.alloc(128)
var blocksize = 64

function Hmac (alg, key) {
  Base.call(this, 'digest')
  if (typeof key === 'string') {
    key = Buffer.from(key)
  }

  this._alg = alg
  this._key = key

  if (key.length > blocksize) {
    key = alg(key)
  } else if (key.length < blocksize) {
    key = Buffer.concat([key, ZEROS], blocksize)
  }

  var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
  var opad = this._opad = Buffer.allocUnsafe(blocksize)

  for (var i = 0; i < blocksize; i++) {
    ipad[i] = key[i] ^ 0x36
    opad[i] = key[i] ^ 0x5C
  }

  this._hash = [ipad]
}

inherits(Hmac, Base)

Hmac.prototype._update = function (data) {
  this._hash.push(data)
}

Hmac.prototype._final = function () {
  var h = this._alg(Buffer.concat(this._hash))
  return this._alg(Buffer.concat([this._opad, h]))
}
module.exports = Hmac


/***/ }),

/***/ "1IWx":
/*!*************************************************!*\
  !*** ./node_modules/stream-browserify/index.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// Copyright Joyent, Inc. and other Node contributors.
//
// 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 = Stream;

var EE = __webpack_require__(/*! events */ "+qE3").EventEmitter;
var inherits = __webpack_require__(/*! inherits */ "P7XM");

inherits(Stream, EE);
Stream.Readable = __webpack_require__(/*! readable-stream/readable.js */ "43KI");
Stream.Writable = __webpack_require__(/*! readable-stream/writable.js */ "LGOv");
Stream.Duplex = __webpack_require__(/*! readable-stream/duplex.js */ "CWBI");
Stream.Transform = __webpack_require__(/*! readable-stream/transform.js */ "0XuU");
Stream.PassThrough = __webpack_require__(/*! readable-stream/passthrough.js */ "wq4j");

// Backwards-compat with node 0.4.x
Stream.Stream = Stream;



// old-style streams.  Note that the pipe method (the only relevant
// part of this class) is overridden in the Readable class.

function Stream() {
  EE.call(this);
}

Stream.prototype.pipe = function(dest, options) {
  var source = this;

  function ondata(chunk) {
    if (dest.writable) {
      if (false === dest.write(chunk) && source.pause) {
        source.pause();
      }
    }
  }

  source.on('data', ondata);

  function ondrain() {
    if (source.readable && source.resume) {
      source.resume();
    }
  }

  dest.on('drain', ondrain);

  // If the 'end' option is not supplied, dest.end() will be called when
  // source gets the 'end' or 'close' events.  Only dest.end() once.
  if (!dest._isStdio && (!options || options.end !== false)) {
    source.on('end', onend);
    source.on('close', onclose);
  }

  var didOnEnd = false;
  function onend() {
    if (didOnEnd) return;
    didOnEnd = true;

    dest.end();
  }


  function onclose() {
    if (didOnEnd) return;
    didOnEnd = true;

    if (typeof dest.destroy === 'function') dest.destroy();
  }

  // don't leave dangling pipes when there are errors.
  function onerror(er) {
    cleanup();
    if (EE.listenerCount(this, 'error') === 0) {
      throw er; // Unhandled stream error in pipe.
    }
  }

  source.on('error', onerror);
  dest.on('error', onerror);

  // remove all the event listeners that were added.
  function cleanup() {
    source.removeListener('data', ondata);
    dest.removeListener('drain', ondrain);

    source.removeListener('end', onend);
    source.removeListener('close', onclose);

    source.removeListener('error', onerror);
    dest.removeListener('error', onerror);

    source.removeListener('end', cleanup);
    source.removeListener('close', cleanup);

    dest.removeListener('close', cleanup);
  }

  source.on('end', cleanup);
  source.on('close', cleanup);

  dest.on('close', cleanup);

  dest.emit('pipe', source);

  // Allow for unix-like usage: A.pipe(B).pipe(C)
  return dest;
};


/***/ }),

/***/ "1Jac":
/*!*************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotLineMarkersIcon.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotLineMarkersIcon = function PlotLineMarkersIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M28.313 6.375c-1.5 0-2.75-1.188-2.688-2.75 0-1.5 1.188-2.75 2.75-2.688 1.5 0 2.75 1.188 2.688 2.75 0 1.5-1.188 2.75-2.75 2.688zm0-3.812c-.563 0-1.063.5-1.063 1.125 0 .563.5 1.063 1.063 1.063.625 0 1.063-.5 1.063-1.063 0-.625-.438-1.125-1.063-1.125zm-24.625 28.5c-1.563.063-2.75-1.188-2.75-2.688-.063-1.563 1.188-2.75 2.688-2.75 1.563-.063 2.75 1.188 2.75 2.688.063 1.563-1.188 2.75-2.688 2.75zm0-3.813c-.625 0-1.063.5-1.063 1.125 0 .563.438 1.063 1.063 1.063.563 0 1.063-.5 1.063-1.063 0-.625-.5-1.125-1.063-1.125zm1.375.188l-1.5-.75 5.063-9.375 3.25 6.125 8.188-17 3.25 6.125 3.625-8 1.563.75-5 11.063-3.375-6.25-8.188 17-3.375-6.25z' })
    );
};

exports.default = PlotLineMarkersIcon;

/***/ }),

/***/ "1Jbx":
/*!*************************************************************!*\
  !*** ./node_modules/draft-js/lib/DraftEditorEditHandler.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DraftEditorEditHandler
 * @format
 * 
 */



var onBeforeInput = __webpack_require__(/*! ./editOnBeforeInput */ "h/2P");
var onBlur = __webpack_require__(/*! ./editOnBlur */ "JI+E");
var onCompositionStart = __webpack_require__(/*! ./editOnCompositionStart */ "jH4x");
var onCopy = __webpack_require__(/*! ./editOnCopy */ "YDMw");
var onCut = __webpack_require__(/*! ./editOnCut */ "e/Ok");
var onDragOver = __webpack_require__(/*! ./editOnDragOver */ "cmQj");
var onDragStart = __webpack_require__(/*! ./editOnDragStart */ "Y/kH");
var onFocus = __webpack_require__(/*! ./editOnFocus */ "pg4M");
var onInput = __webpack_require__(/*! ./editOnInput */ "jyDg");
var onKeyDown = __webpack_require__(/*! ./editOnKeyDown */ "C9ER");
var onPaste = __webpack_require__(/*! ./editOnPaste */ "kDkJ");
var onSelect = __webpack_require__(/*! ./editOnSelect */ "WJOU");

var DraftEditorEditHandler = {
  onBeforeInput: onBeforeInput,
  onBlur: onBlur,
  onCompositionStart: onCompositionStart,
  onCopy: onCopy,
  onCut: onCut,
  onDragOver: onDragOver,
  onDragStart: onDragStart,
  onFocus: onFocus,
  onInput: onInput,
  onKeyDown: onKeyDown,
  onPaste: onPaste,
  onSelect: onSelect
};

module.exports = DraftEditorEditHandler;

/***/ }),

/***/ "1K7F":
/*!**********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotBarpolarIcon.js ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotBarpolarIcon = function PlotBarpolarIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 1360 1360' }, props),
        _react2.default.createElement('path', { fill: 'currentColor', d: 'M436.395 296.519c-.035.024-132.838 63.18-168.071 176.888l113.017 77.533c27.173-50.264 66.14-95.117 116.285-129.927 3.922-2.722 7.916-5.272 11.899-7.825M907.083 618.819C954.8 702.082 943.541 805.4 882.72 876.277l248.645 147.556c34.558-50.135 71.658-119.84 87.054-203.214 32.22-174.515-44.787-317.497-44.787-317.497l.016-.008M833.271 726.291c0 67.024-54.335 121.356-121.359 121.356-67.021 0-121.353-54.332-121.353-121.356 0-67.021 54.331-121.353 121.353-121.353 67.024 0 121.359 54.332 121.359 121.353zM710.058 216.76a517.2 517.2 0 0 1 95.797 8.937l17.614-92.353c-122.54-22.829-251.963-8.079-369.683 47.472l36.725 85.027c66.594-31.461 141.009-49.083 219.547-49.083zM195.443 731.377c0-40.25 4.629-79.417 13.37-117.007l-88.215-20.637c-33.906 147.212-12.908 306.442 68.628 444.549l77.852-44.906c-45.492-76.747-71.635-166.313-71.635-261.999zM775.236 514.777c46.584 13.589 89.045 42.3 119.402 84.678l125.302-85.87c-10.704-14.181-81.113-103.261-186.458-139.721M751.772 509.24l28.458-149.199c-77.99-14.327-160.442-4.134-234.861 32.799l60.376 139.786c45.855-24.786 97.368-32.092 146.027-23.386zM520.673 847.101c-31.415-51.376-39.778-111.009-27.389-166.175L345.361 646.32c-20.933 91.694-7.544 190.861 43.773 276.665M669.68 950.522c-46.869-9.056-90.873-32.971-124.379-70.373l-95.508 109.614c47.968 83.938 189.86 109.751 189.945 109.767l29.942-149.008zM799.638 1236.97c86.811-12.874 206.11-90.075 259.565-127.28.373-.339 1.169-1.073 2.691-2.531L859.103 899.941a226.526 226.526 0 0 1-18.856 14.63c-34.726 24.105-73.889 37.037-113.209 39.593' })
    );
};

exports.default = PlotBarpolarIcon;

/***/ }),

/***/ "1L4U":
/*!****************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/angles.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var modModule = __webpack_require__(/*! ./mod */ "74Od");
var mod = modModule.mod;
var modHalf = modModule.modHalf;

var PI = Math.PI;
var twoPI = 2 * PI;

function deg2rad(deg) { return deg / 180 * PI; }

function rad2deg(rad) { return rad / PI * 180; }

/**
 * is sector a full circle?
 * ... this comes up a lot in SVG path-drawing routines
 *
 * N.B. we consider all sectors that span more that 2pi 'full' circles
 *
 * @param {2-item array} aBnds : angular bounds in *radians*
 * @return {boolean}
 */
function isFullCircle(aBnds) {
    return Math.abs(aBnds[1] - aBnds[0]) > twoPI - 1e-15;
}

/**
 * angular delta between angle 'a' and 'b'
 * solution taken from: https://stackoverflow.com/a/2007279
 *
 * @param {number} a : first angle in *radians*
 * @param {number} b : second angle in *radians*
 * @return {number} angular delta in *radians*
 */
function angleDelta(a, b) {
    return modHalf(b - a, twoPI);
}

/**
 * angular distance between angle 'a' and 'b'
 *
 * @param {number} a : first angle in *radians*
 * @param {number} b : second angle in *radians*
 * @return {number} angular distance in *radians*
 */
function angleDist(a, b) {
    return Math.abs(angleDelta(a, b));
}

/**
 * is angle inside sector?
 *
 * @param {number} a : angle to test in *radians*
 * @param {2-item array} aBnds : sector's angular bounds in *radians*
 * @param {boolean}
 */
function isAngleInsideSector(a, aBnds) {
    if(isFullCircle(aBnds)) return true;

    var s0, s1;

    if(aBnds[0] < aBnds[1]) {
        s0 = aBnds[0];
        s1 = aBnds[1];
    } else {
        s0 = aBnds[1];
        s1 = aBnds[0];
    }

    s0 = mod(s0, twoPI);
    s1 = mod(s1, twoPI);
    if(s0 > s1) s1 += twoPI;

    var a0 = mod(a, twoPI);
    var a1 = a0 + twoPI;

    return (a0 >= s0 && a0 <= s1) || (a1 >= s0 && a1 <= s1);
}

/**
 * is pt (r,a) inside sector?
 *
 * @param {number} r : pt's radial coordinate
 * @param {number} a : pt's angular coordinate in *radians*
 * @param {2-item array} rBnds : sector's radial bounds
 * @param {2-item array} aBnds : sector's angular bounds in *radians*
 * @return {boolean}
 */
function isPtInsideSector(r, a, rBnds, aBnds) {
    if(!isAngleInsideSector(a, aBnds)) return false;

    var r0, r1;

    if(rBnds[0] < rBnds[1]) {
        r0 = rBnds[0];
        r1 = rBnds[1];
    } else {
        r0 = rBnds[1];
        r1 = rBnds[0];
    }

    return r >= r0 && r <= r1;
}

// common to pathArc, pathSector and pathAnnulus
function _path(r0, r1, a0, a1, cx, cy, isClosed) {
    cx = cx || 0;
    cy = cy || 0;

    var isCircle = isFullCircle([a0, a1]);
    var aStart, aMid, aEnd;
    var rStart, rEnd;

    if(isCircle) {
        aStart = 0;
        aMid = PI;
        aEnd = twoPI;
    } else {
        if(a0 < a1) {
            aStart = a0;
            aEnd = a1;
        } else {
            aStart = a1;
            aEnd = a0;
        }
    }

    if(r0 < r1) {
        rStart = r0;
        rEnd = r1;
    } else {
        rStart = r1;
        rEnd = r0;
    }

    // N.B. svg coordinates here, where y increases downward
    function pt(r, a) {
        return [r * Math.cos(a) + cx, cy - r * Math.sin(a)];
    }

    var largeArc = Math.abs(aEnd - aStart) <= PI ? 0 : 1;
    function arc(r, a, cw) {
        return 'A' + [r, r] + ' ' + [0, largeArc, cw] + ' ' + pt(r, a);
    }

    var p;

    if(isCircle) {
        if(rStart === null) {
            p = 'M' + pt(rEnd, aStart) +
                arc(rEnd, aMid, 0) +
                arc(rEnd, aEnd, 0) + 'Z';
        } else {
            p = 'M' + pt(rStart, aStart) +
                arc(rStart, aMid, 0) +
                arc(rStart, aEnd, 0) + 'Z' +
                'M' + pt(rEnd, aStart) +
                arc(rEnd, aMid, 1) +
                arc(rEnd, aEnd, 1) + 'Z';
        }
    } else {
        if(rStart === null) {
            p = 'M' + pt(rEnd, aStart) + arc(rEnd, aEnd, 0);
            if(isClosed) p += 'L0,0Z';
        } else {
            p = 'M' + pt(rStart, aStart) +
                'L' + pt(rEnd, aStart) +
                arc(rEnd, aEnd, 0) +
                'L' + pt(rStart, aEnd) +
                arc(rStart, aStart, 1) + 'Z';
        }
    }

    return p;
}

/**
 * path an arc
 *
 * @param {number} r : radius
 * @param {number} a0 : first angular coordinate in *radians*
 * @param {number} a1 : second angular coordinate in *radians*
 * @param {number (optional)} cx : x coordinate of center
 * @param {number (optional)} cy : y coordinate of center
 * @return {string} svg path
 */
function pathArc(r, a0, a1, cx, cy) {
    return _path(null, r, a0, a1, cx, cy, 0);
}

/**
 * path a sector
 *
 * @param {number} r : radius
 * @param {number} a0 : first angular coordinate in *radians*
 * @param {number} a1 : second angular coordinate in *radians*
 * @param {number (optional)} cx : x coordinate of center
 * @param {number (optional)} cy : y coordinate of center
 * @return {string} svg path
 */
function pathSector(r, a0, a1, cx, cy) {
    return _path(null, r, a0, a1, cx, cy, 1);
}

/**
 * path an annulus
 *
 * @param {number} r0 : first radial coordinate
 * @param {number} r1 : second radial coordinate
 * @param {number} a0 : first angular coordinate in *radians*
 * @param {number} a1 : second angular coordinate in *radians*
 * @param {number (optional)} cx : x coordinate of center
 * @param {number (optional)} cy : y coordinate of center
 * @return {string} svg path
 */
function pathAnnulus(r0, r1, a0, a1, cx, cy) {
    return _path(r0, r1, a0, a1, cx, cy, 1);
}

module.exports = {
    deg2rad: deg2rad,
    rad2deg: rad2deg,
    angleDelta: angleDelta,
    angleDist: angleDist,
    isFullCircle: isFullCircle,
    isAngleInsideSector: isAngleInsideSector,
    isPtInsideSector: isPtInsideSector,
    pathArc: pathArc,
    pathSector: pathSector,
    pathAnnulus: pathAnnulus
};


/***/ }),

/***/ "1QhW":
/*!************************************************!*\
  !*** ./node_modules/ajv/lib/dotjs/validate.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_validate(it, $keyword, $ruleType) {
  var out = '';
  var $async = it.schema.$async === true,
    $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'),
    $id = it.self._getId(it.schema);
  if (it.isTop) {
    if ($async) {
      it.async = true;
      var $es7 = it.opts.async == 'es7';
      it.yieldAwait = $es7 ? 'await' : 'yield';
    }
    out += ' var validate = ';
    if ($async) {
      if ($es7) {
        out += ' (async function ';
      } else {
        if (it.opts.async != '*') {
          out += 'co.wrap';
        }
        out += '(function* ';
      }
    } else {
      out += ' (function ';
    }
    out += ' (data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; ';
    if ($id && (it.opts.sourceCode || it.opts.processCode)) {
      out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' ';
    }
  }
  if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) {
    var $keyword = 'false schema';
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $errorKeyword;
    var $data = 'data' + ($dataLvl || '');
    var $valid = 'valid' + $lvl;
    if (it.schema === false) {
      if (it.isTop) {
        $breakOnError = true;
      } else {
        out += ' var ' + ($valid) + ' = false; ';
      }
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = ''; /* istanbul ignore else */
      if (it.createErrors !== false) {
        out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
        if (it.opts.messages !== false) {
          out += ' , message: \'boolean schema is false\' ';
        }
        if (it.opts.verbose) {
          out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
        }
        out += ' } ';
      } else {
        out += ' {} ';
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
        if (it.async) {
          out += ' throw new ValidationError([' + (__err) + ']); ';
        } else {
          out += ' validate.errors = [' + (__err) + ']; return false; ';
        }
      } else {
        out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
      }
    } else {
      if (it.isTop) {
        if ($async) {
          out += ' return data; ';
        } else {
          out += ' validate.errors = null; return true; ';
        }
      } else {
        out += ' var ' + ($valid) + ' = true; ';
      }
    }
    if (it.isTop) {
      out += ' }); return validate; ';
    }
    return out;
  }
  if (it.isTop) {
    var $top = it.isTop,
      $lvl = it.level = 0,
      $dataLvl = it.dataLevel = 0,
      $data = 'data';
    it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema));
    it.baseId = it.baseId || it.rootId;
    delete it.isTop;
    it.dataPathArr = [undefined];
    out += ' var vErrors = null; ';
    out += ' var errors = 0;     ';
    out += ' if (rootData === undefined) rootData = data; ';
  } else {
    var $lvl = it.level,
      $dataLvl = it.dataLevel,
      $data = 'data' + ($dataLvl || '');
    if ($id) it.baseId = it.resolve.url(it.baseId, $id);
    if ($async && !it.async) throw new Error('async schema in sync schema');
    out += ' var errs_' + ($lvl) + ' = errors;';
  }
  var $valid = 'valid' + $lvl,
    $breakOnError = !it.opts.allErrors,
    $closingBraces1 = '',
    $closingBraces2 = '';
  var $errorKeyword;
  var $typeSchema = it.schema.type,
    $typeIsArray = Array.isArray($typeSchema);
  if ($typeIsArray && $typeSchema.length == 1) {
    $typeSchema = $typeSchema[0];
    $typeIsArray = false;
  }
  if (it.schema.$ref && $refKeywords) {
    if (it.opts.extendRefs == 'fail') {
      throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)');
    } else if (it.opts.extendRefs !== true) {
      $refKeywords = false;
      console.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"');
    }
  }
  if ($typeSchema) {
    if (it.opts.coerceTypes) {
      var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema);
    }
    var $rulesGroup = it.RULES.types[$typeSchema];
    if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) {
      var $schemaPath = it.schemaPath + '.type',
        $errSchemaPath = it.errSchemaPath + '/type';
      var $schemaPath = it.schemaPath + '.type',
        $errSchemaPath = it.errSchemaPath + '/type',
        $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
      out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') { ';
      if ($coerceToTypes) {
        var $dataType = 'dataType' + $lvl,
          $coerced = 'coerced' + $lvl;
        out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; ';
        if (it.opts.coerceTypes == 'array') {
          out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ')) ' + ($dataType) + ' = \'array\'; ';
        }
        out += ' var ' + ($coerced) + ' = undefined; ';
        var $bracesCoercion = '';
        var arr1 = $coerceToTypes;
        if (arr1) {
          var $type, $i = -1,
            l1 = arr1.length - 1;
          while ($i < l1) {
            $type = arr1[$i += 1];
            if ($i) {
              out += ' if (' + ($coerced) + ' === undefined) { ';
              $bracesCoercion += '}';
            }
            if (it.opts.coerceTypes == 'array' && $type != 'array') {
              out += ' if (' + ($dataType) + ' == \'array\' && ' + ($data) + '.length == 1) { ' + ($coerced) + ' = ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + ';  } ';
            }
            if ($type == 'string') {
              out += ' if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; ';
            } else if ($type == 'number' || $type == 'integer') {
              out += ' if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' ';
              if ($type == 'integer') {
                out += ' && !(' + ($data) + ' % 1)';
              }
              out += ')) ' + ($coerced) + ' = +' + ($data) + '; ';
            } else if ($type == 'boolean') {
              out += ' if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; ';
            } else if ($type == 'null') {
              out += ' if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; ';
            } else if (it.opts.coerceTypes == 'array' && $type == 'array') {
              out += ' if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; ';
            }
          }
        }
        out += ' ' + ($bracesCoercion) + ' if (' + ($coerced) + ' === undefined) {   ';
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
          if ($typeIsArray) {
            out += '' + ($typeSchema.join(","));
          } else {
            out += '' + ($typeSchema);
          }
          out += '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'should be ';
            if ($typeIsArray) {
              out += '' + ($typeSchema.join(","));
            } else {
              out += '' + ($typeSchema);
            }
            out += '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += ' } else {  ';
        var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
          $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
        out += ' ' + ($data) + ' = ' + ($coerced) + '; ';
        if (!$dataLvl) {
          out += 'if (' + ($parentData) + ' !== undefined)';
        }
        out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } ';
      } else {
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
          if ($typeIsArray) {
            out += '' + ($typeSchema.join(","));
          } else {
            out += '' + ($typeSchema);
          }
          out += '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'should be ';
            if ($typeIsArray) {
              out += '' + ($typeSchema.join(","));
            } else {
              out += '' + ($typeSchema);
            }
            out += '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
      }
      out += ' } ';
    }
  }
  if (it.schema.$ref && !$refKeywords) {
    out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' ';
    if ($breakOnError) {
      out += ' } if (errors === ';
      if ($top) {
        out += '0';
      } else {
        out += 'errs_' + ($lvl);
      }
      out += ') { ';
      $closingBraces2 += '}';
    }
  } else {
    if (it.opts.v5 && it.schema.patternGroups) {
      console.warn('keyword "patternGroups" is deprecated and disabled. Use option patternGroups: true to enable.');
    }
    var arr2 = it.RULES;
    if (arr2) {
      var $rulesGroup, i2 = -1,
        l2 = arr2.length - 1;
      while (i2 < l2) {
        $rulesGroup = arr2[i2 += 1];
        if ($shouldUseGroup($rulesGroup)) {
          if ($rulesGroup.type) {
            out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data)) + ') { ';
          }
          if (it.opts.useDefaults && !it.compositeRule) {
            if ($rulesGroup.type == 'object' && it.schema.properties) {
              var $schema = it.schema.properties,
                $schemaKeys = Object.keys($schema);
              var arr3 = $schemaKeys;
              if (arr3) {
                var $propertyKey, i3 = -1,
                  l3 = arr3.length - 1;
                while (i3 < l3) {
                  $propertyKey = arr3[i3 += 1];
                  var $sch = $schema[$propertyKey];
                  if ($sch.default !== undefined) {
                    var $passData = $data + it.util.getProperty($propertyKey);
                    out += '  if (' + ($passData) + ' === undefined) ' + ($passData) + ' = ';
                    if (it.opts.useDefaults == 'shared') {
                      out += ' ' + (it.useDefault($sch.default)) + ' ';
                    } else {
                      out += ' ' + (JSON.stringify($sch.default)) + ' ';
                    }
                    out += '; ';
                  }
                }
              }
            } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) {
              var arr4 = it.schema.items;
              if (arr4) {
                var $sch, $i = -1,
                  l4 = arr4.length - 1;
                while ($i < l4) {
                  $sch = arr4[$i += 1];
                  if ($sch.default !== undefined) {
                    var $passData = $data + '[' + $i + ']';
                    out += '  if (' + ($passData) + ' === undefined) ' + ($passData) + ' = ';
                    if (it.opts.useDefaults == 'shared') {
                      out += ' ' + (it.useDefault($sch.default)) + ' ';
                    } else {
                      out += ' ' + (JSON.stringify($sch.default)) + ' ';
                    }
                    out += '; ';
                  }
                }
              }
            }
          }
          var arr5 = $rulesGroup.rules;
          if (arr5) {
            var $rule, i5 = -1,
              l5 = arr5.length - 1;
            while (i5 < l5) {
              $rule = arr5[i5 += 1];
              if ($shouldUseRule($rule)) {
                var $code = $rule.code(it, $rule.keyword, $rulesGroup.type);
                if ($code) {
                  out += ' ' + ($code) + ' ';
                  if ($breakOnError) {
                    $closingBraces1 += '}';
                  }
                }
              }
            }
          }
          if ($breakOnError) {
            out += ' ' + ($closingBraces1) + ' ';
            $closingBraces1 = '';
          }
          if ($rulesGroup.type) {
            out += ' } ';
            if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) {
              out += ' else { ';
              var $schemaPath = it.schemaPath + '.type',
                $errSchemaPath = it.errSchemaPath + '/type';
              var $$outStack = $$outStack || [];
              $$outStack.push(out);
              out = ''; /* istanbul ignore else */
              if (it.createErrors !== false) {
                out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
                if ($typeIsArray) {
                  out += '' + ($typeSchema.join(","));
                } else {
                  out += '' + ($typeSchema);
                }
                out += '\' } ';
                if (it.opts.messages !== false) {
                  out += ' , message: \'should be ';
                  if ($typeIsArray) {
                    out += '' + ($typeSchema.join(","));
                  } else {
                    out += '' + ($typeSchema);
                  }
                  out += '\' ';
                }
                if (it.opts.verbose) {
                  out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                }
                out += ' } ';
              } else {
                out += ' {} ';
              }
              var __err = out;
              out = $$outStack.pop();
              if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                if (it.async) {
                  out += ' throw new ValidationError([' + (__err) + ']); ';
                } else {
                  out += ' validate.errors = [' + (__err) + ']; return false; ';
                }
              } else {
                out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
              }
              out += ' } ';
            }
          }
          if ($breakOnError) {
            out += ' if (errors === ';
            if ($top) {
              out += '0';
            } else {
              out += 'errs_' + ($lvl);
            }
            out += ') { ';
            $closingBraces2 += '}';
          }
        }
      }
    }
  }
  if ($breakOnError) {
    out += ' ' + ($closingBraces2) + ' ';
  }
  if ($top) {
    if ($async) {
      out += ' if (errors === 0) return data;           ';
      out += ' else throw new ValidationError(vErrors); ';
    } else {
      out += ' validate.errors = vErrors; ';
      out += ' return errors === 0;       ';
    }
    out += ' }); return validate;';
  } else {
    out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';';
  }
  out = it.util.cleanUpCode(out);
  if ($top) {
    out = it.util.finalCleanUpCode(out, $async);
  }

  function $shouldUseGroup($rulesGroup) {
    var rules = $rulesGroup.rules;
    for (var i = 0; i < rules.length; i++)
      if ($shouldUseRule(rules[i])) return true;
  }

  function $shouldUseRule($rule) {
    return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImlementsSomeKeyword($rule));
  }

  function $ruleImlementsSomeKeyword($rule) {
    var impl = $rule.implements;
    for (var i = 0; i < impl.length; i++)
      if (it.schema[impl[i]] !== undefined) return true;
  }
  return out;
}


/***/ }),

/***/ "1Ub6":
/*!***********************************************!*\
  !*** ./node_modules/mdi-react/RefreshIcon.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var RefreshIcon = function RefreshIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M17.65,6.35C16.2,4.9 14.21,4 12,4C7.58,4 4,7.58 4,12C4,16.42 7.58,20 12,20C15.73,20 18.84,17.45 19.73,14H17.65C16.83,16.33 14.61,18 12,18C8.69,18 6,15.31 6,12C6,8.69 8.69,6 12,6C13.66,6 15.14,6.69 16.22,7.78L13,11H20V4L17.65,6.35Z' })
  );
};

module.exports = RefreshIcon;


/***/ }),

/***/ "1X/A":
/*!********************************************************************!*\
  !*** ./node_modules/@jupyterlab/rendermime-extension/lib/index.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const docmanager_1 = __webpack_require__(/*! @jupyterlab/docmanager */ "kL29");
const rendermime_1 = __webpack_require__(/*! @jupyterlab/rendermime */ "Towz");
var CommandIDs;
(function (CommandIDs) {
    CommandIDs.handleLink = 'rendermime:handle-local-link';
})(CommandIDs || (CommandIDs = {}));
/**
 * A plugin providing a rendermime registry.
 */
const plugin = {
    id: '@jupyterlab/rendermime-extension:plugin',
    requires: [docmanager_1.IDocumentManager],
    optional: [rendermime_1.ILatexTypesetter],
    provides: rendermime_1.IRenderMimeRegistry,
    activate: activate,
    autoStart: true
};
/**
 * Export the plugin as default.
 */
exports.default = plugin;
/**
 * Activate the rendermine plugin.
 */
function activate(app, docManager, latexTypesetter) {
    app.commands.addCommand(CommandIDs.handleLink, {
        label: 'Handle Local Link',
        execute: args => {
            const path = args['path'];
            const id = args['id'];
            if (!path) {
                return;
            }
            // First check if the path exists on the server.
            return docManager.services.contents
                .get(path, { content: false })
                .then(() => {
                // Open the link with the default rendered widget factory,
                // if applicable.
                const factory = docManager.registry.defaultRenderedWidgetFactory(path);
                const widget = docManager.openOrReveal(path, factory.name);
                if (!widget) {
                    return;
                }
                return widget.revealed.then(() => {
                    // Once the widget is ready, attempt to scroll the hash into view
                    // if one has been provided.
                    if (!id) {
                        return;
                    }
                    // Look for the an element with the hash id in the document.
                    // This id is set automatically for headers tags when
                    // we render markdown.
                    const element = widget.node.querySelector(id);
                    if (element) {
                        element.scrollIntoView();
                    }
                    return;
                });
            });
        }
    });
    return new rendermime_1.RenderMimeRegistry({
        initialFactories: rendermime_1.standardRendererFactories,
        linkHandler: {
            handleLink: (node, path, id) => {
                app.commandLinker.connectNode(node, CommandIDs.handleLink, {
                    path,
                    id
                });
            }
        },
        latexTypesetter
    });
}


/***/ }),

/***/ "1XL3":
/*!********************************************************!*\
  !*** ./node_modules/xterm/lib/shared/utils/Browser.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var isNode = (typeof navigator === 'undefined') ? true : false;
var userAgent = (isNode) ? 'node' : navigator.userAgent;
var platform = (isNode) ? 'node' : navigator.platform;
exports.isFirefox = !!~userAgent.indexOf('Firefox');
exports.isMSIE = !!~userAgent.indexOf('MSIE') || !!~userAgent.indexOf('Trident');
exports.isMac = contains(['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'], platform);
exports.isIpad = platform === 'iPad';
exports.isIphone = platform === 'iPhone';
exports.isMSWindows = contains(['Windows', 'Win16', 'Win32', 'WinCE'], platform);
exports.isLinux = platform.indexOf('Linux') >= 0;
function contains(arr, el) {
    return arr.indexOf(el) >= 0;
}

//# sourceMappingURL=Browser.js.map


/***/ }),

/***/ "1YrB":
/*!***************************************************************!*\
  !*** ./node_modules/@plotly/draft-js-export-html/lib/main.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _stateToHTML = __webpack_require__(/*! ./stateToHTML */ "TT7y");

Object.defineProperty(exports, 'stateToHTML', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_stateToHTML).default;
  }
});

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/***/ }),

/***/ "1c7f":
/*!*******************************************************!*\
  !*** ./node_modules/react-paginate/dist/BreakView.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var BreakView = function BreakView(props) {
  var label = props.breakLabel;
  var className = props.breakClassName || 'break';

  return _react2.default.createElement(
    'li',
    { className: className },
    label
  );
};

exports.default = BreakView;
//# sourceMappingURL=BreakView.js.map

/***/ }),

/***/ "1eCo":
/*!*************************************************!*\
  !*** ./node_modules/codemirror/mode/xml/xml.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"));
  else {}
})(function(CodeMirror) {
"use strict";

var htmlConfig = {
  autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
                    'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
                    'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
                    'track': true, 'wbr': true, 'menuitem': true},
  implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
                     'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
                     'th': true, 'tr': true},
  contextGrabbers: {
    'dd': {'dd': true, 'dt': true},
    'dt': {'dd': true, 'dt': true},
    'li': {'li': true},
    'option': {'option': true, 'optgroup': true},
    'optgroup': {'optgroup': true},
    'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
          'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
          'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
          'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
          'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
    'rp': {'rp': true, 'rt': true},
    'rt': {'rp': true, 'rt': true},
    'tbody': {'tbody': true, 'tfoot': true},
    'td': {'td': true, 'th': true},
    'tfoot': {'tbody': true},
    'th': {'td': true, 'th': true},
    'thead': {'tbody': true, 'tfoot': true},
    'tr': {'tr': true}
  },
  doNotIndent: {"pre": true},
  allowUnquoted: true,
  allowMissing: true,
  caseFold: true
}

var xmlConfig = {
  autoSelfClosers: {},
  implicitlyClosed: {},
  contextGrabbers: {},
  doNotIndent: {},
  allowUnquoted: false,
  allowMissing: false,
  allowMissingTagName: false,
  caseFold: false
}

CodeMirror.defineMode("xml", function(editorConf, config_) {
  var indentUnit = editorConf.indentUnit
  var config = {}
  var defaults = config_.htmlMode ? htmlConfig : xmlConfig
  for (var prop in defaults) config[prop] = defaults[prop]
  for (var prop in config_) config[prop] = config_[prop]

  // Return variables for tokenizers
  var type, setStyle;

  function inText(stream, state) {
    function chain(parser) {
      state.tokenize = parser;
      return parser(stream, state);
    }

    var ch = stream.next();
    if (ch == "<") {
      if (stream.eat("!")) {
        if (stream.eat("[")) {
          if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
          else return null;
        } else if (stream.match("--")) {
          return chain(inBlock("comment", "-->"));
        } else if (stream.match("DOCTYPE", true, true)) {
          stream.eatWhile(/[\w\._\-]/);
          return chain(doctype(1));
        } else {
          return null;
        }
      } else if (stream.eat("?")) {
        stream.eatWhile(/[\w\._\-]/);
        state.tokenize = inBlock("meta", "?>");
        return "meta";
      } else {
        type = stream.eat("/") ? "closeTag" : "openTag";
        state.tokenize = inTag;
        return "tag bracket";
      }
    } else if (ch == "&") {
      var ok;
      if (stream.eat("#")) {
        if (stream.eat("x")) {
          ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
        } else {
          ok = stream.eatWhile(/[\d]/) && stream.eat(";");
        }
      } else {
        ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
      }
      return ok ? "atom" : "error";
    } else {
      stream.eatWhile(/[^&<]/);
      return null;
    }
  }
  inText.isInText = true;

  function inTag(stream, state) {
    var ch = stream.next();
    if (ch == ">" || (ch == "/" && stream.eat(">"))) {
      state.tokenize = inText;
      type = ch == ">" ? "endTag" : "selfcloseTag";
      return "tag bracket";
    } else if (ch == "=") {
      type = "equals";
      return null;
    } else if (ch == "<") {
      state.tokenize = inText;
      state.state = baseState;
      state.tagName = state.tagStart = null;
      var next = state.tokenize(stream, state);
      return next ? next + " tag error" : "tag error";
    } else if (/[\'\"]/.test(ch)) {
      state.tokenize = inAttribute(ch);
      state.stringStartCol = stream.column();
      return state.tokenize(stream, state);
    } else {
      stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
      return "word";
    }
  }

  function inAttribute(quote) {
    var closure = function(stream, state) {
      while (!stream.eol()) {
        if (stream.next() == quote) {
          state.tokenize = inTag;
          break;
        }
      }
      return "string";
    };
    closure.isInAttribute = true;
    return closure;
  }

  function inBlock(style, terminator) {
    return function(stream, state) {
      while (!stream.eol()) {
        if (stream.match(terminator)) {
          state.tokenize = inText;
          break;
        }
        stream.next();
      }
      return style;
    }
  }

  function doctype(depth) {
    return function(stream, state) {
      var ch;
      while ((ch = stream.next()) != null) {
        if (ch == "<") {
          state.tokenize = doctype(depth + 1);
          return state.tokenize(stream, state);
        } else if (ch == ">") {
          if (depth == 1) {
            state.tokenize = inText;
            break;
          } else {
            state.tokenize = doctype(depth - 1);
            return state.tokenize(stream, state);
          }
        }
      }
      return "meta";
    };
  }

  function Context(state, tagName, startOfLine) {
    this.prev = state.context;
    this.tagName = tagName;
    this.indent = state.indented;
    this.startOfLine = startOfLine;
    if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
      this.noIndent = true;
  }
  function popContext(state) {
    if (state.context) state.context = state.context.prev;
  }
  function maybePopContext(state, nextTagName) {
    var parentTagName;
    while (true) {
      if (!state.context) {
        return;
      }
      parentTagName = state.context.tagName;
      if (!config.contextGrabbers.hasOwnProperty(parentTagName) ||
          !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
        return;
      }
      popContext(state);
    }
  }

  function baseState(type, stream, state) {
    if (type == "openTag") {
      state.tagStart = stream.column();
      return tagNameState;
    } else if (type == "closeTag") {
      return closeTagNameState;
    } else {
      return baseState;
    }
  }
  function tagNameState(type, stream, state) {
    if (type == "word") {
      state.tagName = stream.current();
      setStyle = "tag";
      return attrState;
    } else if (config.allowMissingTagName && type == "endTag") {
      setStyle = "tag bracket";
      return attrState(type, stream, state);
    } else {
      setStyle = "error";
      return tagNameState;
    }
  }
  function closeTagNameState(type, stream, state) {
    if (type == "word") {
      var tagName = stream.current();
      if (state.context && state.context.tagName != tagName &&
          config.implicitlyClosed.hasOwnProperty(state.context.tagName))
        popContext(state);
      if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) {
        setStyle = "tag";
        return closeState;
      } else {
        setStyle = "tag error";
        return closeStateErr;
      }
    } else if (config.allowMissingTagName && type == "endTag") {
      setStyle = "tag bracket";
      return closeState(type, stream, state);
    } else {
      setStyle = "error";
      return closeStateErr;
    }
  }

  function closeState(type, _stream, state) {
    if (type != "endTag") {
      setStyle = "error";
      return closeState;
    }
    popContext(state);
    return baseState;
  }
  function closeStateErr(type, stream, state) {
    setStyle = "error";
    return closeState(type, stream, state);
  }

  function attrState(type, _stream, state) {
    if (type == "word") {
      setStyle = "attribute";
      return attrEqState;
    } else if (type == "endTag" || type == "selfcloseTag") {
      var tagName = state.tagName, tagStart = state.tagStart;
      state.tagName = state.tagStart = null;
      if (type == "selfcloseTag" ||
          config.autoSelfClosers.hasOwnProperty(tagName)) {
        maybePopContext(state, tagName);
      } else {
        maybePopContext(state, tagName);
        state.context = new Context(state, tagName, tagStart == state.indented);
      }
      return baseState;
    }
    setStyle = "error";
    return attrState;
  }
  function attrEqState(type, stream, state) {
    if (type == "equals") return attrValueState;
    if (!config.allowMissing) setStyle = "error";
    return attrState(type, stream, state);
  }
  function attrValueState(type, stream, state) {
    if (type == "string") return attrContinuedState;
    if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;}
    setStyle = "error";
    return attrState(type, stream, state);
  }
  function attrContinuedState(type, stream, state) {
    if (type == "string") return attrContinuedState;
    return attrState(type, stream, state);
  }

  return {
    startState: function(baseIndent) {
      var state = {tokenize: inText,
                   state: baseState,
                   indented: baseIndent || 0,
                   tagName: null, tagStart: null,
                   context: null}
      if (baseIndent != null) state.baseIndent = baseIndent
      return state
    },

    token: function(stream, state) {
      if (!state.tagName && stream.sol())
        state.indented = stream.indentation();

      if (stream.eatSpace()) return null;
      type = null;
      var style = state.tokenize(stream, state);
      if ((style || type) && style != "comment") {
        setStyle = null;
        state.state = state.state(type || style, stream, state);
        if (setStyle)
          style = setStyle == "error" ? style + " error" : setStyle;
      }
      return style;
    },

    indent: function(state, textAfter, fullLine) {
      var context = state.context;
      // Indent multi-line strings (e.g. css).
      if (state.tokenize.isInAttribute) {
        if (state.tagStart == state.indented)
          return state.stringStartCol + 1;
        else
          return state.indented + indentUnit;
      }
      if (context && context.noIndent) return CodeMirror.Pass;
      if (state.tokenize != inTag && state.tokenize != inText)
        return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
      // Indent the starts of attribute names.
      if (state.tagName) {
        if (config.multilineTagIndentPastTag !== false)
          return state.tagStart + state.tagName.length + 2;
        else
          return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);
      }
      if (config.alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
      var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter);
      if (tagAfter && tagAfter[1]) { // Closing tag spotted
        while (context) {
          if (context.tagName == tagAfter[2]) {
            context = context.prev;
            break;
          } else if (config.implicitlyClosed.hasOwnProperty(context.tagName)) {
            context = context.prev;
          } else {
            break;
          }
        }
      } else if (tagAfter) { // Opening tag spotted
        while (context) {
          var grabbers = config.contextGrabbers[context.tagName];
          if (grabbers && grabbers.hasOwnProperty(tagAfter[2]))
            context = context.prev;
          else
            break;
        }
      }
      while (context && context.prev && !context.startOfLine)
        context = context.prev;
      if (context) return context.indent + indentUnit;
      else return state.baseIndent || 0;
    },

    electricInput: /<\/[\s\w:]+>$/,
    blockCommentStart: "<!--",
    blockCommentEnd: "-->",

    configuration: config.htmlMode ? "html" : "xml",
    helperType: config.htmlMode ? "html" : "xml",

    skipAttribute: function(state) {
      if (state.state == attrValueState)
        state.state = attrState
    }
  };
});

CodeMirror.defineMIME("text/xml", "xml");
CodeMirror.defineMIME("application/xml", "xml");
if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
  CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});

});


/***/ }),

/***/ "1hJj":
/*!******************************************!*\
  !*** ./node_modules/lodash/_SetCache.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var MapCache = __webpack_require__(/*! ./_MapCache */ "e4Nc"),
    setCacheAdd = __webpack_require__(/*! ./_setCacheAdd */ "ftKO"),
    setCacheHas = __webpack_require__(/*! ./_setCacheHas */ "3A9y");

/**
 *
 * 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]);
  }
}

// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;

module.exports = SetCache;


/***/ }),

/***/ "1hgy":
/*!*****************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/TraceMarkerSection.js ***!
  \*****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _PlotlySection = __webpack_require__(/*! ./PlotlySection */ "aR6p");

var _PlotlySection2 = _interopRequireDefault(_PlotlySection);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var TraceMarkerSection = function (_Component) {
  _inherits(TraceMarkerSection, _Component);

  function TraceMarkerSection(props, context) {
    _classCallCheck(this, TraceMarkerSection);

    var _this = _possibleConstructorReturn(this, (TraceMarkerSection.__proto__ || Object.getPrototypeOf(TraceMarkerSection)).call(this, props, context));

    _this.setLocals(context);
    return _this;
  }

  _createClass(TraceMarkerSection, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps, nextContext) {
      this.setLocals(nextContext);
    }
  }, {
    key: 'setLocals',
    value: function setLocals(context) {
      var _ = this.context.localize;
      var traceType = context.fullContainer.type;
      if (['bar', 'histogram'].includes(traceType)) {
        this.name = _('Bars');
      } else if (traceType === 'pie') {
        this.name = _('Pie Segments');
      } else {
        this.name = _('Points');
      }
    }
  }, {
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        _PlotlySection2.default,
        { name: this.name },
        this.props.children
      );
    }
  }]);

  return TraceMarkerSection;
}(_react.Component);

TraceMarkerSection.propTypes = {
  children: _propTypes2.default.node,
  name: _propTypes2.default.string
};

TraceMarkerSection.contextTypes = {
  fullContainer: _propTypes2.default.object,
  localize: _propTypes2.default.func
};

exports.default = TraceMarkerSection;
//# sourceMappingURL=TraceMarkerSection.js.map

/***/ }),

/***/ "1iyU":
/*!*******************************************************!*\
  !*** ./node_modules/@jupyterlab/console/lib/panel.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const coreutils_2 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const rendermime_1 = __webpack_require__(/*! @jupyterlab/rendermime */ "Towz");
const coreutils_3 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const widget_1 = __webpack_require__(/*! ./widget */ "wK5+");
/**
 * The class name added to console panels.
 */
const PANEL_CLASS = 'jp-ConsolePanel';
const CONSOLE_ICON_CLASS = 'jp-CodeConsoleIcon';
/**
 * A panel which contains a console and the ability to add other children.
 */
class ConsolePanel extends widgets_1.Panel {
    /**
     * Construct a console panel.
     */
    constructor(options) {
        super();
        this._executed = null;
        this._connected = null;
        this.addClass(PANEL_CLASS);
        let { rendermime, mimeTypeService, path, basePath, name, manager, modelFactory } = options;
        let contentFactory = (this.contentFactory =
            options.contentFactory || ConsolePanel.defaultContentFactory);
        let count = Private.count++;
        if (!path) {
            path = `${basePath || ''}/console-${count}-${coreutils_2.UUID.uuid4()}`;
        }
        let session = (this._session = new apputils_1.ClientSession({
            manager: manager.sessions,
            path,
            name: name || `Console ${count}`,
            type: 'console',
            kernelPreference: options.kernelPreference,
            setBusy: options.setBusy
        }));
        let resolver = new rendermime_1.RenderMimeRegistry.UrlResolver({
            session,
            contents: manager.contents
        });
        rendermime = rendermime.clone({ resolver });
        this.console = contentFactory.createConsole({
            rendermime,
            session,
            mimeTypeService,
            contentFactory,
            modelFactory
        });
        this.addWidget(this.console);
        session.initialize().then(() => {
            this._connected = new Date();
            this._updateTitle();
        });
        this.console.executed.connect(this._onExecuted, this);
        this._updateTitle();
        session.kernelChanged.connect(this._updateTitle, this);
        session.propertyChanged.connect(this._updateTitle, this);
        this.title.icon = CONSOLE_ICON_CLASS;
        this.title.closable = true;
        this.id = `console-${count}`;
    }
    /**
     * The session used by the panel.
     */
    get session() {
        return this._session;
    }
    /**
     * Dispose of the resources held by the widget.
     */
    dispose() {
        this.session.dispose();
        this.console.dispose();
        super.dispose();
    }
    /**
     * Handle `'activate-request'` messages.
     */
    onActivateRequest(msg) {
        let prompt = this.console.promptCell;
        if (prompt) {
            prompt.editor.focus();
        }
    }
    /**
     * Handle `'close-request'` messages.
     */
    onCloseRequest(msg) {
        super.onCloseRequest(msg);
        this.dispose();
    }
    /**
     * Handle a console execution.
     */
    _onExecuted(sender, args) {
        this._executed = args;
        this._updateTitle();
    }
    /**
     * Update the console panel title.
     */
    _updateTitle() {
        Private.updateTitle(this, this._connected, this._executed);
    }
}
exports.ConsolePanel = ConsolePanel;
/**
 * A namespace for ConsolePanel statics.
 */
(function (ConsolePanel) {
    /**
     * Default implementation of `IContentFactory`.
     */
    class ContentFactory extends widget_1.CodeConsole.ContentFactory {
        /**
         * Create a new console panel.
         */
        createConsole(options) {
            return new widget_1.CodeConsole(options);
        }
    }
    ConsolePanel.ContentFactory = ContentFactory;
    /**
     * A default code console content factory.
     */
    ConsolePanel.defaultContentFactory = new ContentFactory();
    /* tslint:disable */
    /**
     * The console renderer token.
     */
    ConsolePanel.IContentFactory = new coreutils_3.Token('@jupyterlab/console:IContentFactory');
    /* tslint:enable */
})(ConsolePanel = exports.ConsolePanel || (exports.ConsolePanel = {}));
/**
 * A namespace for private data.
 */
var Private;
(function (Private) {
    /**
     * The counter for new consoles.
     */
    Private.count = 1;
    /**
     * Update the title of a console panel.
     */
    function updateTitle(panel, connected, executed) {
        let session = panel.console.session;
        let caption = `Name: ${session.name}\n` +
            `Directory: ${coreutils_1.PathExt.dirname(session.path)}\n` +
            `Kernel: ${session.kernelDisplayName}`;
        if (connected) {
            caption += `\nConnected: ${coreutils_1.Time.format(connected.toISOString())}`;
        }
        if (executed) {
            caption += `\nLast Execution: ${coreutils_1.Time.format(executed.toISOString())}`;
        }
        panel.title.label = session.name || 'Console';
        panel.title.caption = caption;
    }
    Private.updateTitle = updateTitle;
})(Private || (Private = {}));


/***/ }),

/***/ "1lSx":
/*!*************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/text_editors/HTML.js ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _TextArea2 = __webpack_require__(/*! ../TextArea */ "6HQ/");

var _TextArea3 = _interopRequireDefault(_TextArea2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var HTML = function (_TextArea) {
  _inherits(HTML, _TextArea);

  function HTML() {
    _classCallCheck(this, HTML);

    return _possibleConstructorReturn(this, (HTML.__proto__ || Object.getPrototypeOf(HTML)).apply(this, arguments));
  }

  _createClass(HTML, [{
    key: 'render',
    value: function render() {
      var className = this.props.className;

      var editorClassNames = className ? className : 'text-editor__html';
      return _react2.default.createElement('textarea', {
        value: this.state.value,
        placeholder: this.props.placeholder,
        onChange: this.onChange,
        className: editorClassNames
      });
    }
  }]);

  return HTML;
}(_TextArea3.default);

HTML.propTypes = {
  className: _propTypes2.default.string
};

HTML.defaultProps = {
  placeholder: ''
};

exports.default = HTML;
//# sourceMappingURL=HTML.js.map

/***/ }),

/***/ "1ntV":
/*!*************************************************************!*\
  !*** ./node_modules/@jupyterlab/faq-extension/lib/index.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const application_1 = __webpack_require__(/*! @jupyterlab/application */ "FkFl");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const rendermime_1 = __webpack_require__(/*! @jupyterlab/rendermime */ "Towz");
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
__webpack_require__(/*! ../style/index.css */ "zdsp");
/**
 * The command IDs used by the FAQ plugin.
 */
var CommandIDs;
(function (CommandIDs) {
    CommandIDs.open = 'faq-jupyterlab:open';
})(CommandIDs || (CommandIDs = {}));
/**
 * The FAQ page extension.
 */
const plugin = {
    activate,
    id: '@jupyterlab/faq-extension:plugin',
    requires: [apputils_1.ICommandPalette, application_1.ILayoutRestorer, rendermime_1.IRenderMimeRegistry],
    autoStart: true
};
/**
 * Export the plugin as default.
 */
exports.default = plugin;
/* tslint:disable */
/**
 * The faq page source.
 */
const SOURCE = __webpack_require__(/*! ../faq.md */ "STJr");
/* tslint:enable */
/**
 * Activate the FAQ plugin.
 */
function activate(app, palette, restorer, rendermime) {
    const category = 'Help';
    const command = CommandIDs.open;
    const { commands, shell } = app;
    const tracker = new apputils_1.InstanceTracker({ namespace: 'faq' });
    // Handle state restoration.
    restorer.restore(tracker, {
        command,
        args: () => coreutils_1.JSONExt.emptyObject,
        name: () => 'faq'
    });
    let createWidget = () => {
        let content = rendermime.createRenderer('text/markdown');
        const model = rendermime.createModel({
            data: { 'text/markdown': SOURCE }
        });
        content.renderModel(model);
        content.addClass('jp-FAQ-content');
        let widget = new apputils_1.MainAreaWidget({ content });
        widget.addClass('jp-FAQ');
        widget.title.label = 'FAQ';
        return widget;
    };
    let widget;
    commands.addCommand(command, {
        label: 'Open FAQ',
        execute: () => {
            if (!widget || widget.isDisposed) {
                widget = createWidget();
            }
            if (!tracker.has(widget)) {
                tracker.add(widget);
                shell.addToMainArea(widget, { activate: false });
            }
            shell.activateById(widget.id);
        }
    });
    palette.addItem({ command, category });
}


/***/ }),

/***/ "1pyT":
/*!********************************************************************!*\
  !*** ./node_modules/draft-js-utils/lib/selectionContainsEntity.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _getSelectedBlocks = __webpack_require__(/*! ./getSelectedBlocks */ "jb54");

var _getSelectedBlocks2 = _interopRequireDefault(_getSelectedBlocks);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = function (strategy) {
  return function (editorState, selection) {
    var contentState = editorState.getCurrentContent();
    var currentSelection = selection || editorState.getSelection();
    var startKey = currentSelection.getStartKey();
    var endKey = currentSelection.getEndKey();
    var startOffset = currentSelection.getStartOffset();
    var endOffset = currentSelection.getEndOffset();

    var isSameBlock = startKey === endKey;
    var selectedBlocks = (0, _getSelectedBlocks2.default)(contentState, startKey, endKey);
    var entityFound = false;

    // We have to shift the offset to not get false positives when selecting
    // a character just before or after an entity
    var finalStartOffset = startOffset + 1;
    var finalEndOffset = endOffset - 1;

    selectedBlocks.forEach(function (block) {
      strategy(block, function (start, end) {
        if (entityFound) {
          return;
        }

        var blockKey = block.getKey();

        if (isSameBlock && (end < finalStartOffset || start > finalEndOffset)) {
          return;
        } else if (blockKey === startKey && end < finalStartOffset) {
          return;
        } else if (blockKey === endKey && start > finalEndOffset) {
          return;
        }

        entityFound = true;
      }, contentState);
    });

    return entityFound;
  };
};

/***/ }),

/***/ "1qq2":
/*!*********************************************************************!*\
  !*** ./node_modules/draft-js/lib/convertFromHTMLToContentBlocks.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule convertFromHTMLToContentBlocks
 * @format
 * 
 */



var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _knownListItemDepthCl,
    _assign = __webpack_require__(/*! object-assign */ "MgzW");

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var CharacterMetadata = __webpack_require__(/*! ./CharacterMetadata */ "lFJn");
var ContentBlock = __webpack_require__(/*! ./ContentBlock */ "8uQm");
var ContentBlockNode = __webpack_require__(/*! ./ContentBlockNode */ "JL7T");
var DefaultDraftBlockRenderMap = __webpack_require__(/*! ./DefaultDraftBlockRenderMap */ "rAV9");
var DraftEntity = __webpack_require__(/*! ./DraftEntity */ "TzU/");
var DraftFeatureFlags = __webpack_require__(/*! ./DraftFeatureFlags */ "cX45");
var Immutable = __webpack_require__(/*! immutable */ "JPcv");

var _require = __webpack_require__(/*! immutable */ "JPcv"),
    Set = _require.Set;

var URI = __webpack_require__(/*! fbjs/lib/URI */ "Z9sL");

var cx = __webpack_require__(/*! fbjs/lib/cx */ "YVIB");
var generateRandomKey = __webpack_require__(/*! ./generateRandomKey */ "rJY1");
var getSafeBodyFromHTML = __webpack_require__(/*! ./getSafeBodyFromHTML */ "xocI");
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");
var sanitizeDraftText = __webpack_require__(/*! ./sanitizeDraftText */ "HriT");

var experimentalTreeDataSupport = DraftFeatureFlags.draft_tree_data_support;

var List = Immutable.List,
    OrderedSet = Immutable.OrderedSet;


var NBSP = '&nbsp;';
var SPACE = ' ';

// Arbitrary max indent
var MAX_DEPTH = 4;

// used for replacing characters in HTML
var REGEX_CR = new RegExp('\r', 'g');
var REGEX_LF = new RegExp('\n', 'g');
var REGEX_NBSP = new RegExp(NBSP, 'g');
var REGEX_CARRIAGE = new RegExp('&#13;?', 'g');
var REGEX_ZWS = new RegExp('&#8203;?', 'g');

// https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight
var boldValues = ['bold', 'bolder', '500', '600', '700', '800', '900'];
var notBoldValues = ['light', 'lighter', '100', '200', '300', '400'];

// Block tag flow is different because LIs do not have
// a deterministic style ;_;
var inlineTags = {
  b: 'BOLD',
  code: 'CODE',
  del: 'STRIKETHROUGH',
  em: 'ITALIC',
  i: 'ITALIC',
  s: 'STRIKETHROUGH',
  strike: 'STRIKETHROUGH',
  strong: 'BOLD',
  u: 'UNDERLINE'
};

var knownListItemDepthClasses = (_knownListItemDepthCl = {}, _defineProperty(_knownListItemDepthCl, cx('public/DraftStyleDefault/depth0'), 0), _defineProperty(_knownListItemDepthCl, cx('public/DraftStyleDefault/depth1'), 1), _defineProperty(_knownListItemDepthCl, cx('public/DraftStyleDefault/depth2'), 2), _defineProperty(_knownListItemDepthCl, cx('public/DraftStyleDefault/depth3'), 3), _defineProperty(_knownListItemDepthCl, cx('public/DraftStyleDefault/depth4'), 4), _knownListItemDepthCl);

var anchorAttr = ['className', 'href', 'rel', 'target', 'title'];

var imgAttr = ['alt', 'className', 'height', 'src', 'width'];

var lastBlock = void 0;

var EMPTY_CHUNK = {
  text: '',
  inlines: [],
  entities: [],
  blocks: []
};

var EMPTY_BLOCK = {
  children: List(),
  depth: 0,
  key: '',
  type: ''
};

var getListBlockType = function getListBlockType(tag, lastList) {
  if (tag === 'li') {
    return lastList === 'ol' ? 'ordered-list-item' : 'unordered-list-item';
  }
  return null;
};

var getBlockMapSupportedTags = function getBlockMapSupportedTags(blockRenderMap) {
  var unstyledElement = blockRenderMap.get('unstyled').element;
  var tags = Set([]);

  blockRenderMap.forEach(function (draftBlock) {
    if (draftBlock.aliasedElements) {
      draftBlock.aliasedElements.forEach(function (tag) {
        tags = tags.add(tag);
      });
    }

    tags = tags.add(draftBlock.element);
  });

  return tags.filter(function (tag) {
    return tag && tag !== unstyledElement;
  }).toArray().sort();
};

// custom element conversions
var getMultiMatchedType = function getMultiMatchedType(tag, lastList, multiMatchExtractor) {
  for (var ii = 0; ii < multiMatchExtractor.length; ii++) {
    var matchType = multiMatchExtractor[ii](tag, lastList);
    if (matchType) {
      return matchType;
    }
  }
  return null;
};

var getBlockTypeForTag = function getBlockTypeForTag(tag, lastList, blockRenderMap) {
  var matchedTypes = blockRenderMap.filter(function (draftBlock) {
    return draftBlock.element === tag || draftBlock.wrapper === tag || draftBlock.aliasedElements && draftBlock.aliasedElements.some(function (alias) {
      return alias === tag;
    });
  }).keySeq().toSet().toArray().sort();

  // if we dont have any matched type, return unstyled
  // if we have one matched type return it
  // if we have multi matched types use the multi-match function to gather type
  switch (matchedTypes.length) {
    case 0:
      return 'unstyled';
    case 1:
      return matchedTypes[0];
    default:
      return getMultiMatchedType(tag, lastList, [getListBlockType]) || 'unstyled';
  }
};

var processInlineTag = function processInlineTag(tag, node, currentStyle) {
  var styleToCheck = inlineTags[tag];
  if (styleToCheck) {
    currentStyle = currentStyle.add(styleToCheck).toOrderedSet();
  } else if (node instanceof HTMLElement) {
    var htmlElement = node;
    currentStyle = currentStyle.withMutations(function (style) {
      var fontWeight = htmlElement.style.fontWeight;
      var fontStyle = htmlElement.style.fontStyle;
      var textDecoration = htmlElement.style.textDecoration;

      if (boldValues.indexOf(fontWeight) >= 0) {
        style.add('BOLD');
      } else if (notBoldValues.indexOf(fontWeight) >= 0) {
        style.remove('BOLD');
      }

      if (fontStyle === 'italic') {
        style.add('ITALIC');
      } else if (fontStyle === 'normal') {
        style.remove('ITALIC');
      }

      if (textDecoration === 'underline') {
        style.add('UNDERLINE');
      }
      if (textDecoration === 'line-through') {
        style.add('STRIKETHROUGH');
      }
      if (textDecoration === 'none') {
        style.remove('UNDERLINE');
        style.remove('STRIKETHROUGH');
      }
    }).toOrderedSet();
  }
  return currentStyle;
};

var joinChunks = function joinChunks(A, B, experimentalHasNestedBlocks) {
  // Sometimes two blocks will touch in the DOM and we need to strip the
  // extra delimiter to preserve niceness.
  var lastInA = A.text.slice(-1);
  var firstInB = B.text.slice(0, 1);

  if (lastInA === '\r' && firstInB === '\r' && !experimentalHasNestedBlocks) {
    A.text = A.text.slice(0, -1);
    A.inlines.pop();
    A.entities.pop();
    A.blocks.pop();
  }

  // Kill whitespace after blocks
  if (lastInA === '\r') {
    if (B.text === SPACE || B.text === '\n') {
      return A;
    } else if (firstInB === SPACE || firstInB === '\n') {
      B.text = B.text.slice(1);
      B.inlines.shift();
      B.entities.shift();
    }
  }

  return {
    text: A.text + B.text,
    inlines: A.inlines.concat(B.inlines),
    entities: A.entities.concat(B.entities),
    blocks: A.blocks.concat(B.blocks)
  };
};

/**
 * Check to see if we have anything like <p> <blockquote> <h1>... to create
 * block tags from. If we do, we can use those and ignore <div> tags. If we
 * don't, we can treat <div> tags as meaningful (unstyled) blocks.
 */
var containsSemanticBlockMarkup = function containsSemanticBlockMarkup(html, blockTags) {
  return blockTags.some(function (tag) {
    return html.indexOf('<' + tag) !== -1;
  });
};

var hasValidLinkText = function hasValidLinkText(link) {
  !(link instanceof HTMLAnchorElement) ?  true ? invariant(false, 'Link must be an HTMLAnchorElement.') : undefined : void 0;
  var protocol = link.protocol;
  return protocol === 'http:' || protocol === 'https:' || protocol === 'mailto:';
};

var getWhitespaceChunk = function getWhitespaceChunk(inEntity) {
  var entities = new Array(1);
  if (inEntity) {
    entities[0] = inEntity;
  }
  return _extends({}, EMPTY_CHUNK, {
    text: SPACE,
    inlines: [OrderedSet()],
    entities: entities
  });
};

var getSoftNewlineChunk = function getSoftNewlineChunk() {
  return _extends({}, EMPTY_CHUNK, {
    text: '\n',
    inlines: [OrderedSet()],
    entities: new Array(1)
  });
};

var getChunkedBlock = function getChunkedBlock() {
  var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

  return _extends({}, EMPTY_BLOCK, props);
};

var getBlockDividerChunk = function getBlockDividerChunk(block, depth) {
  var parentKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;

  return {
    text: '\r',
    inlines: [OrderedSet()],
    entities: new Array(1),
    blocks: [getChunkedBlock({
      parent: parentKey,
      key: generateRandomKey(),
      type: block,
      depth: Math.max(0, Math.min(MAX_DEPTH, depth))
    })]
  };
};

/**
 *  If we're pasting from one DraftEditor to another we can check to see if
 *  existing list item depth classes are being used and preserve this style
 */
var getListItemDepth = function getListItemDepth(node) {
  var depth = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;

  Object.keys(knownListItemDepthClasses).some(function (depthClass) {
    if (node.classList.contains(depthClass)) {
      depth = knownListItemDepthClasses[depthClass];
    }
  });
  return depth;
};

var genFragment = function genFragment(entityMap, node, inlineStyle, lastList, inBlock, blockTags, depth, blockRenderMap, inEntity, parentKey) {
  var lastLastBlock = lastBlock;
  var nodeName = node.nodeName.toLowerCase();
  var newEntityMap = entityMap;
  var nextBlockType = 'unstyled';
  var newBlock = false;
  var inBlockType = inBlock && getBlockTypeForTag(inBlock, lastList, blockRenderMap);
  var chunk = _extends({}, EMPTY_CHUNK);
  var newChunk = null;
  var blockKey = void 0;

  // Base Case
  if (nodeName === '#text') {
    var _text = node.textContent;
    var nodeTextContent = _text.trim();

    // We should not create blocks for leading spaces that are
    // existing around ol/ul and their children list items
    if (lastList && nodeTextContent === '' && node.parentElement) {
      var parentNodeName = node.parentElement.nodeName.toLowerCase();
      if (parentNodeName === 'ol' || parentNodeName === 'ul') {
        return { chunk: _extends({}, EMPTY_CHUNK), entityMap: entityMap };
      }
    }

    if (nodeTextContent === '' && inBlock !== 'pre') {
      return { chunk: getWhitespaceChunk(inEntity), entityMap: entityMap };
    }
    if (inBlock !== 'pre') {
      // Can't use empty string because MSWord
      _text = _text.replace(REGEX_LF, SPACE);
    }

    // save the last block so we can use it later
    lastBlock = nodeName;

    return {
      chunk: {
        text: _text,
        inlines: Array(_text.length).fill(inlineStyle),
        entities: Array(_text.length).fill(inEntity),
        blocks: []
      },
      entityMap: entityMap
    };
  }

  // save the last block so we can use it later
  lastBlock = nodeName;

  // BR tags
  if (nodeName === 'br') {
    if (lastLastBlock === 'br' && (!inBlock || inBlockType === 'unstyled')) {
      return {
        chunk: getBlockDividerChunk('unstyled', depth, parentKey),
        entityMap: entityMap
      };
    }
    return { chunk: getSoftNewlineChunk(), entityMap: entityMap };
  }

  // IMG tags
  if (nodeName === 'img' && node instanceof HTMLImageElement && node.attributes.getNamedItem('src') && node.attributes.getNamedItem('src').value) {
    var image = node;
    var entityConfig = {};

    imgAttr.forEach(function (attr) {
      var imageAttribute = image.getAttribute(attr);
      if (imageAttribute) {
        entityConfig[attr] = imageAttribute;
      }
    });
    // Forcing this node to have children because otherwise no entity will be
    // created for this node.
    // The child text node cannot just have a space or return as content -
    // we strip those out.
    // See https://github.com/facebook/draft-js/issues/231 for some context.
    node.textContent = '\uD83D\uDCF7';

    // TODO: update this when we remove DraftEntity entirely
    inEntity = DraftEntity.__create('IMAGE', 'MUTABLE', entityConfig || {});
  }

  // Inline tags
  inlineStyle = processInlineTag(nodeName, node, inlineStyle);

  // Handle lists
  if (nodeName === 'ul' || nodeName === 'ol') {
    if (lastList) {
      depth += 1;
    }
    lastList = nodeName;
  }

  if (!experimentalTreeDataSupport && nodeName === 'li' && node instanceof HTMLElement) {
    depth = getListItemDepth(node, depth);
  }

  var blockType = getBlockTypeForTag(nodeName, lastList, blockRenderMap);
  var inListBlock = lastList && inBlock === 'li' && nodeName === 'li';
  var inBlockOrHasNestedBlocks = (!inBlock || experimentalTreeDataSupport) && blockTags.indexOf(nodeName) !== -1;

  // Block Tags
  if (inListBlock || inBlockOrHasNestedBlocks) {
    chunk = getBlockDividerChunk(blockType, depth, parentKey);
    blockKey = chunk.blocks[0].key;
    inBlock = nodeName;
    newBlock = !experimentalTreeDataSupport;
  }

  // this is required so that we can handle 'ul' and 'ol'
  if (inListBlock) {
    nextBlockType = lastList === 'ul' ? 'unordered-list-item' : 'ordered-list-item';
  }

  // Recurse through children
  var child = node.firstChild;
  if (child != null) {
    nodeName = child.nodeName.toLowerCase();
  }

  var entityId = null;

  while (child) {
    if (child instanceof HTMLAnchorElement && child.href && hasValidLinkText(child)) {
      (function () {
        var anchor = child;
        var entityConfig = {};

        anchorAttr.forEach(function (attr) {
          var anchorAttribute = anchor.getAttribute(attr);
          if (anchorAttribute) {
            entityConfig[attr] = anchorAttribute;
          }
        });

        entityConfig.url = new URI(anchor.href).toString();
        // TODO: update this when we remove DraftEntity completely
        entityId = DraftEntity.__create('LINK', 'MUTABLE', entityConfig || {});
      })();
    } else {
      entityId = undefined;
    }

    var _genFragment = genFragment(newEntityMap, child, inlineStyle, lastList, inBlock, blockTags, depth, blockRenderMap, entityId || inEntity, experimentalTreeDataSupport ? blockKey : null),
        generatedChunk = _genFragment.chunk,
        maybeUpdatedEntityMap = _genFragment.entityMap;

    newChunk = generatedChunk;
    newEntityMap = maybeUpdatedEntityMap;

    chunk = joinChunks(chunk, newChunk, experimentalTreeDataSupport);
    var sibling = child.nextSibling;

    // Put in a newline to break up blocks inside blocks
    if (!parentKey && sibling && blockTags.indexOf(nodeName) >= 0 && inBlock) {
      chunk = joinChunks(chunk, getSoftNewlineChunk());
    }
    if (sibling) {
      nodeName = sibling.nodeName.toLowerCase();
    }
    child = sibling;
  }

  if (newBlock) {
    chunk = joinChunks(chunk, getBlockDividerChunk(nextBlockType, depth, parentKey));
  }

  return { chunk: chunk, entityMap: newEntityMap };
};

var getChunkForHTML = function getChunkForHTML(html, DOMBuilder, blockRenderMap, entityMap) {
  html = html.trim().replace(REGEX_CR, '').replace(REGEX_NBSP, SPACE).replace(REGEX_CARRIAGE, '').replace(REGEX_ZWS, '');

  var supportedBlockTags = getBlockMapSupportedTags(blockRenderMap);

  var safeBody = DOMBuilder(html);
  if (!safeBody) {
    return null;
  }
  lastBlock = null;

  // Sometimes we aren't dealing with content that contains nice semantic
  // tags. In this case, use divs to separate everything out into paragraphs
  // and hope for the best.
  var workingBlocks = containsSemanticBlockMarkup(html, supportedBlockTags) ? supportedBlockTags : ['div'];

  // Start with -1 block depth to offset the fact that we are passing in a fake
  // UL block to start with.
  var fragment = genFragment(entityMap, safeBody, OrderedSet(), 'ul', null, workingBlocks, -1, blockRenderMap);

  var chunk = fragment.chunk;
  var newEntityMap = fragment.entityMap;

  // join with previous block to prevent weirdness on paste
  if (chunk.text.indexOf('\r') === 0) {
    chunk = {
      text: chunk.text.slice(1),
      inlines: chunk.inlines.slice(1),
      entities: chunk.entities.slice(1),
      blocks: chunk.blocks
    };
  }

  // Kill block delimiter at the end
  if (chunk.text.slice(-1) === '\r') {
    chunk.text = chunk.text.slice(0, -1);
    chunk.inlines = chunk.inlines.slice(0, -1);
    chunk.entities = chunk.entities.slice(0, -1);
    chunk.blocks.pop();
  }

  // If we saw no block tags, put an unstyled one in
  if (chunk.blocks.length === 0) {
    chunk.blocks.push(_extends({}, EMPTY_CHUNK, {
      type: 'unstyled',
      depth: 0
    }));
  }

  // Sometimes we start with text that isn't in a block, which is then
  // followed by blocks. Need to fix up the blocks to add in
  // an unstyled block for this content
  if (chunk.text.split('\r').length === chunk.blocks.length + 1) {
    chunk.blocks.unshift({ type: 'unstyled', depth: 0 });
  }

  return { chunk: chunk, entityMap: newEntityMap };
};

var convertChunkToContentBlocks = function convertChunkToContentBlocks(chunk) {
  if (!chunk || !chunk.text || !Array.isArray(chunk.blocks)) {
    return null;
  }

  var initialState = {
    cacheRef: {},
    contentBlocks: []
  };

  var start = 0;

  var rawBlocks = chunk.blocks,
      rawInlines = chunk.inlines,
      rawEntities = chunk.entities;


  var BlockNodeRecord = experimentalTreeDataSupport ? ContentBlockNode : ContentBlock;

  return chunk.text.split('\r').reduce(function (acc, textBlock, index) {
    // Make absolutely certain that our text is acceptable.
    textBlock = sanitizeDraftText(textBlock);

    var block = rawBlocks[index];
    var end = start + textBlock.length;
    var inlines = rawInlines.slice(start, end);
    var entities = rawEntities.slice(start, end);
    var characterList = List(inlines.map(function (style, index) {
      var data = { style: style, entity: null };
      if (entities[index]) {
        data.entity = entities[index];
      }
      return CharacterMetadata.create(data);
    }));
    start = end + 1;

    var depth = block.depth,
        type = block.type,
        parent = block.parent;


    var key = block.key || generateRandomKey();
    var parentTextNodeKey = null; // will be used to store container text nodes

    // childrens add themselves to their parents since we are iterating in order
    if (parent) {
      var parentIndex = acc.cacheRef[parent];
      var parentRecord = acc.contentBlocks[parentIndex];

      // if parent has text we need to split it into a separate unstyled element
      if (parentRecord.getChildKeys().isEmpty() && parentRecord.getText()) {
        var parentCharacterList = parentRecord.getCharacterList();
        var parentText = parentRecord.getText();
        parentTextNodeKey = generateRandomKey();

        var textNode = new ContentBlockNode({
          key: parentTextNodeKey,
          text: parentText,
          characterList: parentCharacterList,
          parent: parent,
          nextSibling: key
        });

        acc.contentBlocks.push(textNode);

        parentRecord = parentRecord.withMutations(function (block) {
          block.set('characterList', List()).set('text', '').set('children', parentRecord.children.push(textNode.getKey()));
        });
      }

      acc.contentBlocks[parentIndex] = parentRecord.set('children', parentRecord.children.push(key));
    }

    var blockNode = new BlockNodeRecord({
      key: key,
      parent: parent,
      type: type,
      depth: depth,
      text: textBlock,
      characterList: characterList,
      prevSibling: parentTextNodeKey || (index === 0 || rawBlocks[index - 1].parent !== parent ? null : rawBlocks[index - 1].key),
      nextSibling: index === rawBlocks.length - 1 || rawBlocks[index + 1].parent !== parent ? null : rawBlocks[index + 1].key
    });

    // insert node
    acc.contentBlocks.push(blockNode);

    // cache ref for building links
    acc.cacheRef[blockNode.key] = index;

    return acc;
  }, initialState).contentBlocks;
};

var convertFromHTMLtoContentBlocks = function convertFromHTMLtoContentBlocks(html) {
  var DOMBuilder = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : getSafeBodyFromHTML;
  var blockRenderMap = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DefaultDraftBlockRenderMap;

  // Be ABSOLUTELY SURE that the dom builder you pass here won't execute
  // arbitrary code in whatever environment you're running this in. For an
  // example of how we try to do this in-browser, see getSafeBodyFromHTML.

  // TODO: replace DraftEntity with an OrderedMap here
  var chunkData = getChunkForHTML(html, DOMBuilder, blockRenderMap, DraftEntity);

  if (chunkData == null) {
    return null;
  }

  var chunk = chunkData.chunk,
      entityMap = chunkData.entityMap;

  var contentBlocks = convertChunkToContentBlocks(chunk);

  return {
    contentBlocks: contentBlocks,
    entityMap: entityMap
  };
};

module.exports = convertFromHTMLtoContentBlocks;

/***/ }),

/***/ "1rYy":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/hy-am.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var hyAm = moment.defineLocale('hy-am', {
    months : {
        format: 'հունվարի_փետրվարի_մարտի_ապրիլի_մայիսի_հունիսի_հուլիսի_օգոստոսի_սեպտեմբերի_հոկտեմբերի_նոյեմբերի_դեկտեմբերի'.split('_'),
        standalone: 'հունվար_փետրվար_մարտ_ապրիլ_մայիս_հունիս_հուլիս_օգոստոս_սեպտեմբեր_հոկտեմբեր_նոյեմբեր_դեկտեմբեր'.split('_')
    },
    monthsShort : 'հնվ_փտր_մրտ_ապր_մյս_հնս_հլս_օգս_սպտ_հկտ_նմբ_դկտ'.split('_'),
    weekdays : 'կիրակի_երկուշաբթի_երեքշաբթի_չորեքշաբթի_հինգշաբթի_ուրբաթ_շաբաթ'.split('_'),
    weekdaysShort : 'կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ'.split('_'),
    weekdaysMin : 'կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D MMMM YYYY թ.',
        LLL : 'D MMMM YYYY թ., HH:mm',
        LLLL : 'dddd, D MMMM YYYY թ., HH:mm'
    },
    calendar : {
        sameDay: '[այսօր] LT',
        nextDay: '[վաղը] LT',
        lastDay: '[երեկ] LT',
        nextWeek: function () {
            return 'dddd [օրը ժամը] LT';
        },
        lastWeek: function () {
            return '[անցած] dddd [օրը ժամը] LT';
        },
        sameElse: 'L'
    },
    relativeTime : {
        future : '%s հետո',
        past : '%s առաջ',
        s : 'մի քանի վայրկյան',
        ss : '%d վայրկյան',
        m : 'րոպե',
        mm : '%d րոպե',
        h : 'ժամ',
        hh : '%d ժամ',
        d : 'օր',
        dd : '%d օր',
        M : 'ամիս',
        MM : '%d ամիս',
        y : 'տարի',
        yy : '%d տարի'
    },
    meridiemParse: /գիշերվա|առավոտվա|ցերեկվա|երեկոյան/,
    isPM: function (input) {
        return /^(ցերեկվա|երեկոյան)$/.test(input);
    },
    meridiem : function (hour) {
        if (hour < 4) {
            return 'գիշերվա';
        } else if (hour < 12) {
            return 'առավոտվա';
        } else if (hour < 17) {
            return 'ցերեկվա';
        } else {
            return 'երեկոյան';
        }
    },
    dayOfMonthOrdinalParse: /\d{1,2}|\d{1,2}-(ին|րդ)/,
    ordinal: function (number, period) {
        switch (period) {
            case 'DDD':
            case 'w':
            case 'W':
            case 'DDDo':
                if (number === 1) {
                    return number + '-ին';
                }
                return number + '-րդ';
            default:
                return number;
        }
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return hyAm;

})));


/***/ }),

/***/ "1w4i":
/*!********************************************!*\
  !*** ./node_modules/parse-asn1/aesid.json ***!
  \********************************************/
/*! exports provided: 2.16.840.1.101.3.4.1.1, 2.16.840.1.101.3.4.1.2, 2.16.840.1.101.3.4.1.3, 2.16.840.1.101.3.4.1.4, 2.16.840.1.101.3.4.1.21, 2.16.840.1.101.3.4.1.22, 2.16.840.1.101.3.4.1.23, 2.16.840.1.101.3.4.1.24, 2.16.840.1.101.3.4.1.41, 2.16.840.1.101.3.4.1.42, 2.16.840.1.101.3.4.1.43, 2.16.840.1.101.3.4.1.44, default */
/***/ (function(module) {

module.exports = {"2.16.840.1.101.3.4.1.1":"aes-128-ecb","2.16.840.1.101.3.4.1.2":"aes-128-cbc","2.16.840.1.101.3.4.1.3":"aes-128-ofb","2.16.840.1.101.3.4.1.4":"aes-128-cfb","2.16.840.1.101.3.4.1.21":"aes-192-ecb","2.16.840.1.101.3.4.1.22":"aes-192-cbc","2.16.840.1.101.3.4.1.23":"aes-192-ofb","2.16.840.1.101.3.4.1.24":"aes-192-cfb","2.16.840.1.101.3.4.1.41":"aes-256-ecb","2.16.840.1.101.3.4.1.42":"aes-256-cbc","2.16.840.1.101.3.4.1.43":"aes-256-ofb","2.16.840.1.101.3.4.1.44":"aes-256-cfb"};

/***/ }),

/***/ "1xZ4":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/ca.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var ca = moment.defineLocale('ca', {
    months : {
        standalone: 'gener_febrer_març_abril_maig_juny_juliol_agost_setembre_octubre_novembre_desembre'.split('_'),
        format: 'de gener_de febrer_de març_d\'abril_de maig_de juny_de juliol_d\'agost_de setembre_d\'octubre_de novembre_de desembre'.split('_'),
        isFormat: /D[oD]?(\s)+MMMM/
    },
    monthsShort : 'gen._febr._març_abr._maig_juny_jul._ag._set._oct._nov._des.'.split('_'),
    monthsParseExact : true,
    weekdays : 'diumenge_dilluns_dimarts_dimecres_dijous_divendres_dissabte'.split('_'),
    weekdaysShort : 'dg._dl._dt._dc._dj._dv._ds.'.split('_'),
    weekdaysMin : 'dg_dl_dt_dc_dj_dv_ds'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'H:mm',
        LTS : 'H:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM [de] YYYY',
        ll : 'D MMM YYYY',
        LLL : 'D MMMM [de] YYYY [a les] H:mm',
        lll : 'D MMM YYYY, H:mm',
        LLLL : 'dddd D MMMM [de] YYYY [a les] H:mm',
        llll : 'ddd D MMM YYYY, H:mm'
    },
    calendar : {
        sameDay : function () {
            return '[avui a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT';
        },
        nextDay : function () {
            return '[demà a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT';
        },
        nextWeek : function () {
            return 'dddd [a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT';
        },
        lastDay : function () {
            return '[ahir a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT';
        },
        lastWeek : function () {
            return '[el] dddd [passat a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT';
        },
        sameElse : 'L'
    },
    relativeTime : {
        future : 'd\'aquí %s',
        past : 'fa %s',
        s : 'uns segons',
        ss : '%d segons',
        m : 'un minut',
        mm : '%d minuts',
        h : 'una hora',
        hh : '%d hores',
        d : 'un dia',
        dd : '%d dies',
        M : 'un mes',
        MM : '%d mesos',
        y : 'un any',
        yy : '%d anys'
    },
    dayOfMonthOrdinalParse: /\d{1,2}(r|n|t|è|a)/,
    ordinal : function (number, period) {
        var output = (number === 1) ? 'r' :
            (number === 2) ? 'n' :
            (number === 3) ? 'r' :
            (number === 4) ? 't' : 'è';
        if (period === 'w' || period === 'W') {
            output = 'a';
        }
        return number + output;
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return ca;

})));


/***/ }),

/***/ "1y7b":
/*!********************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/text_editors/MultiFormat.js ***!
  \********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _HTML = __webpack_require__(/*! ./HTML */ "1lSx");

var _HTML2 = _interopRequireDefault(_HTML);

var _LaTeX = __webpack_require__(/*! ./LaTeX */ "XxHi");

var _LaTeX2 = _interopRequireDefault(_LaTeX);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _RichText = __webpack_require__(/*! ./RichText */ "BFJn");

var _RichText2 = _interopRequireDefault(_RichText);

var _convertFormats = __webpack_require__(/*! ./convertFormats */ "C6sy");

var _classnames = __webpack_require__(/*! classnames */ "TSYQ");

var _classnames2 = _interopRequireDefault(_classnames);

var _Button = __webpack_require__(/*! ../Button */ "rZxl");

var _Button2 = _interopRequireDefault(_Button);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var MultiFormatTextEditor = function (_Component) {
  _inherits(MultiFormatTextEditor, _Component);

  function MultiFormatTextEditor(props, context) {
    _classCallCheck(this, MultiFormatTextEditor);

    var _this = _possibleConstructorReturn(this, (MultiFormatTextEditor.__proto__ || Object.getPrototypeOf(MultiFormatTextEditor)).call(this, props, context));

    var _ = context.localize;

    var editors = [{
      key: 'RICH_TEXT',
      label: _('Rich Text'),
      component: _RichText2.default
    }, {
      key: 'LATEX',
      label: _('LaTeX'),
      component: _LaTeX2.default
    }, {
      key: 'HTML',
      label: _('Edit in HTML'),
      component: _HTML2.default
    }];

    var startTab = (0, _convertFormats.isLaTeXExpr)(props.value) ? 'LATEX' : 'RICH_TEXT';

    _this.state = {
      /*
       * When nextTab is set, we are waiting for confirmation from the
       * user before switching to the next tab.
       */
      nextTab: null,
      currentTab: startTab,
      messages: []
    };

    _this.onModeChange = _this.onModeChange.bind(_this);
    _this.editors = editors;
    return _this;
  }

  /**
   * Convert a value to the format expected by the provided editor.
   *
   * @param {String} value The current value
   * @param {String} editor The editor to convert for [RICH_TEXT|LATEX]
   * @returns {String} The converted value
   */


  _createClass(MultiFormatTextEditor, [{
    key: 'convertValue',
    value: function convertValue(value, editor) {
      var currentTab = this.state.currentTab;


      if (currentTab === 'RICH_TEXT' && editor === 'LATEX') {
        return (0, _convertFormats.htmlToLaTeX)(value);
      }

      if (currentTab === 'LATEX' && editor === 'RICH_TEXT') {
        return (0, _convertFormats.laTeXToHTML)(value);
      }

      if (currentTab === 'HTML' && editor === 'LATEX') {
        return (0, _convertFormats.htmlToLaTeX)(value);
      }

      /*
       * Else we're switching from / to HTML / Rich Text Editor
       * no conversion is needed
       */
      return value;
    }
  }, {
    key: 'onModeChange',
    value: function onModeChange(nextTab) {
      var _ = this.context.localize;
      var _props = this.props,
          defaultValuePattern = _props.defaultValuePattern,
          value = _props.value,
          onChange = _props.onChange;
      var currentTab = this.state.currentTab;

      var trimmedValue = value.trim();
      var trimmedValueLength = trimmedValue.length;
      var convertedValue = this.convertValue(trimmedValue, nextTab);

      /*
       * Check against default value - we have to compare the plain
       * value, not the LaTeX format value with `\text{}` wrapping.
       */
      var isDefaultValue = (0, _convertFormats.isLaTeXExpr)(trimmedValue) ? defaultValuePattern.test(convertedValue) : defaultValuePattern.test(trimmedValue);

      var switchingBetweenRichAndHtml = currentTab === 'RICH_TEXT' && nextTab === 'HTML' || currentTab === 'HTML' && nextTab === 'RICH_TEXT';

      if (!isDefaultValue && trimmedValueLength > 0 && !switchingBetweenRichAndHtml) {
        // Show confirmation dialogue and defer tab change.
        var messages = void 0;

        if (!(0, _convertFormats.isLaTeXExpr)(value)) {
          messages = [_("LaTeX is a math typesetting language that doesn't work with rich text."), _('Continuing will convert your note to LaTeX-style text.')];
        } else if ((0, _convertFormats.hasTextExpression)(value)) {
          messages = [_('Rich text is incompatible with LaTeX.'), _('Continuing will convert your LaTeX expression into raw text.')];
        } else {
          messages = [_('Rich text is incompatible with LaTeX.'), _('Continuing will remove your expression.')];
        }

        this.setState({
          nextTab: nextTab,
          messages: messages
        });

        return;
      }

      // Show requested tab immediately.
      this.setState({
        currentTab: nextTab
      });

      // Convert the annotation and dispatch onChange action
      onChange(convertedValue);
    }
  }, {
    key: 'renderConfirmationPanel',
    value: function renderConfirmationPanel(render) {
      var _this2 = this;

      if (!render) {
        return null;
      }

      var _ = this.context.localize;
      var messages = this.state.messages;


      var onCancel = function onCancel() {
        _this2.setState({
          nextTab: null
        });
      };

      var onContinue = function onContinue() {
        var nextTab = _this2.state.nextTab;
        var _props2 = _this2.props,
            onChange = _props2.onChange,
            value = _props2.value;

        // Set next tab as active

        _this2.setState({
          currentTab: nextTab,
          nextTab: null
        });

        // Convert the annotation
        var convertedValue = _this2.convertValue(value, nextTab);
        onChange(convertedValue);
      };

      return _react2.default.createElement(
        'div',
        { className: 'multi-format-editor__confirmation-panel' },
        _react2.default.createElement(
          'div',
          { className: 'multi-format-editor__confirmation-panel__content' },
          _react2.default.createElement(
            'h3',
            { className: 'multi-format-editor__confirmation-panel__header' },
            _('Heads up!')
          ),
          _react2.default.createElement(
            'div',
            { className: 'multi-format-editor__confirmation-panel__message' },
            _react2.default.createElement(
              'p',
              { className: 'multi-format-editor__confirmation-panel__message-primary' },
              messages[0]
            ),
            _react2.default.createElement(
              'p',
              { className: 'multi-format-editor__confirmation-panel__message-secondary' },
              messages[1]
            )
          )
        ),
        _react2.default.createElement(
          'div',
          { className: 'multi-format-editor__confirmation-panel__actions' },
          _react2.default.createElement(
            _Button2.default,
            {
              variant: 'default',
              className: 'multi-format-editor__confirmation-panel__cancel-button',
              onClick: onCancel
            },
            _('Go back')
          ),
          _react2.default.createElement(
            _Button2.default,
            {
              variant: 'primary',
              className: 'multi-format-editor__confirmation-panel__continue-button',
              onClick: onContinue
            },
            _('Continue')
          )
        )
      );
    }
  }, {
    key: 'renderEditor',
    value: function renderEditor(render) {
      var _this3 = this;

      if (!render) {
        return null;
      }
      var _ = this.context.localize;
      var _props3 = this.props,
          onChange = _props3.onChange,
          placeholder = _props3.placeholder,
          value = _props3.value;
      var currentTab = this.state.currentTab;


      var richTextClassNames = (0, _classnames2.default)('multi-format-editor__tab', 'top-tab', 'left', {
        selected: currentTab === 'RICH_TEXT'
      });
      var latexClassNames = (0, _classnames2.default)('multi-format-editor__tab', 'top-tab', 'right', {
        selected: currentTab === 'LATEX'
      });
      var bottomTabClassNames = (0, _classnames2.default)('multi-format-editor__tab', 'bottom-tab');

      var Editor = this.editors.filter(function (editor) {
        return editor.key === currentTab;
      })[0].component;

      var ModeTabsText = this.editors.map(function (editor) {
        return editor.label;
      });

      var showBottomTab = currentTab === 'HTML' || currentTab === 'RICH_TEXT';
      var BottomTab = currentTab === 'HTML' ? _react2.default.createElement(
        'div',
        { className: bottomTabClassNames, onClick: function onClick() {
            return _this3.onModeChange('RICH_TEXT');
          } },
        _('Edit in Rich Text')
      ) : _react2.default.createElement(
        'div',
        { className: bottomTabClassNames, onClick: function onClick() {
            return _this3.onModeChange('HTML');
          } },
        _('Edit in HTML')
      );

      return _react2.default.createElement(
        'div',
        { className: 'multi-format-editor__root__wrapper' },
        _react2.default.createElement(
          'div',
          { className: 'multi-format-editor__tabs' },
          _react2.default.createElement(
            'div',
            { className: richTextClassNames, onClick: function onClick() {
                return _this3.onModeChange('RICH_TEXT');
              } },
            ModeTabsText[0]
          ),
          _react2.default.createElement(
            'div',
            { className: latexClassNames, onClick: function onClick() {
                return _this3.onModeChange('LATEX');
              } },
            ModeTabsText[1]
          )
        ),
        _react2.default.createElement(
          'div',
          { className: 'multi-format-editor__content__wrapper__' + currentTab.toLowerCase() },
          _react2.default.createElement(Editor, {
            className: 'multi-format-editor__' + currentTab.toLowerCase(),
            onChange: onChange,
            placeholder: placeholder,
            value: value
          })
        ),
        showBottomTab ? BottomTab : null
      );
    }
  }, {
    key: 'render',
    value: function render() {
      /*
       * `renderConfirmationPanel` and `renderEditor` are mutually
       * exclusive; only one will return a component.
       */
      var nextTab = this.state.nextTab;

      var content = this.renderConfirmationPanel(nextTab !== null) || this.renderEditor(nextTab === null);

      return _react2.default.createElement(
        'div',
        { className: 'multi-format-editor__root' },
        content
      );
    }
  }]);

  return MultiFormatTextEditor;
}(_react.Component);

MultiFormatTextEditor.propTypes = {
  defaultValuePattern: _propTypes2.default.instanceOf(RegExp),
  onChange: _propTypes2.default.func.isRequired,
  placeholder: _propTypes2.default.string,
  value: _propTypes2.default.string
};

MultiFormatTextEditor.defaultProps = {
  defaultValuePattern: /^$/,
  placeholder: '',
  value: ''
};

MultiFormatTextEditor.contextTypes = {
  localize: _propTypes2.default.func
};

exports.default = MultiFormatTextEditor;
//# sourceMappingURL=MultiFormat.js.map

/***/ }),

/***/ "2+Wn":
/*!********************************************************!*\
  !*** ./node_modules/xterm/lib/renderer/atlas/Types.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.INVERTED_DEFAULT_COLOR = -1;
exports.DIM_OPACITY = 0.5;

//# sourceMappingURL=Types.js.map


/***/ }),

/***/ "21Ld":
/*!******************************************************************!*\
  !*** ./node_modules/@jupyterlab/terminal-extension/lib/index.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const application_1 = __webpack_require__(/*! @jupyterlab/application */ "FkFl");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const launcher_1 = __webpack_require__(/*! @jupyterlab/launcher */ "78yt");
const mainmenu_1 = __webpack_require__(/*! @jupyterlab/mainmenu */ "N4Qf");
const terminal_1 = __webpack_require__(/*! @jupyterlab/terminal */ "f+Xr");
/**
 * The command IDs used by the terminal plugin.
 */
var CommandIDs;
(function (CommandIDs) {
    CommandIDs.createNew = 'terminal:create-new';
    CommandIDs.open = 'terminal:open';
    CommandIDs.refresh = 'terminal:refresh';
    CommandIDs.increaseFont = 'terminal:increase-font';
    CommandIDs.decreaseFont = 'terminal:decrease-font';
    CommandIDs.toggleTheme = 'terminal:toggle-theme';
})(CommandIDs || (CommandIDs = {}));
/**
 * The class name for the terminal icon in the default theme.
 */
const TERMINAL_ICON_CLASS = 'jp-TerminalIcon';
/**
 * The default terminal extension.
 */
const plugin = {
    activate,
    id: '@jupyterlab/terminal-extension:plugin',
    provides: terminal_1.ITerminalTracker,
    requires: [mainmenu_1.IMainMenu, apputils_1.ICommandPalette, application_1.ILayoutRestorer],
    optional: [launcher_1.ILauncher],
    autoStart: true
};
/**
 * Export the plugin as default.
 */
exports.default = plugin;
/**
 * Activate the terminal plugin.
 */
function activate(app, mainMenu, palette, restorer, launcher) {
    const { serviceManager } = app;
    const category = 'Terminal';
    const namespace = 'terminal';
    const tracker = new apputils_1.InstanceTracker({ namespace });
    // Bail if there are no terminals available.
    if (!serviceManager.terminals.isAvailable()) {
        console.log('Disabling terminals plugin because they are not available on the server');
        return tracker;
    }
    // Handle state restoration.
    restorer.restore(tracker, {
        command: CommandIDs.createNew,
        args: widget => ({ name: widget.content.session.name }),
        name: widget => widget.content.session && widget.content.session.name
    });
    addCommands(app, serviceManager, tracker);
    // Add some commands to the application view menu.
    const viewGroup = [
        CommandIDs.increaseFont,
        CommandIDs.decreaseFont,
        CommandIDs.toggleTheme
    ].map(command => {
        return { command };
    });
    mainMenu.viewMenu.addGroup(viewGroup, 30);
    // Add command palette items.
    [
        CommandIDs.createNew,
        CommandIDs.refresh,
        CommandIDs.increaseFont,
        CommandIDs.decreaseFont,
        CommandIDs.toggleTheme
    ].forEach(command => {
        palette.addItem({ command, category, args: { isPalette: true } });
    });
    // Add terminal creation to the file menu.
    mainMenu.fileMenu.newMenu.addGroup([{ command: CommandIDs.createNew }], 20);
    // Add a launcher item if the launcher is available.
    if (launcher) {
        launcher.add({
            command: CommandIDs.createNew,
            category: 'Other',
            rank: 0
        });
    }
    app.contextMenu.addItem({
        command: CommandIDs.refresh,
        selector: '.jp-Terminal',
        rank: 1
    });
    return tracker;
}
/**
 * Add the commands for the terminal.
 */
function addCommands(app, services, tracker) {
    let { commands, shell } = app;
    /**
     * Whether there is an active terminal.
     */
    function isEnabled() {
        return (tracker.currentWidget !== null &&
            tracker.currentWidget === app.shell.currentWidget);
    }
    // Add terminal commands.
    commands.addCommand(CommandIDs.createNew, {
        label: args => (args['isPalette'] ? 'New Terminal' : 'Terminal'),
        caption: 'Start a new terminal session',
        iconClass: args => (args['isPalette'] ? '' : TERMINAL_ICON_CLASS),
        execute: args => {
            const name = args['name'];
            const initialCommand = args['initialCommand'];
            const term = new terminal_1.Terminal({ initialCommand });
            const promise = name
                ? services.terminals.connectTo(name)
                : services.terminals.startNew();
            term.title.icon = TERMINAL_ICON_CLASS;
            term.title.label = '...';
            let main = new apputils_1.MainAreaWidget({ content: term });
            shell.addToMainArea(main);
            return promise
                .then(session => {
                term.session = session;
                tracker.add(main);
                shell.activateById(main.id);
                return main;
            })
                .catch(() => {
                term.dispose();
            });
        }
    });
    commands.addCommand(CommandIDs.open, {
        execute: args => {
            const name = args['name'];
            // Check for a running terminal with the given name.
            const widget = tracker.find(value => {
                let content = value.content;
                return (content.session && content.session.name === name) || false;
            });
            if (widget) {
                shell.activateById(widget.id);
            }
            else {
                // Otherwise, create a new terminal with a given name.
                return commands.execute(CommandIDs.createNew, { name });
            }
        }
    });
    commands.addCommand(CommandIDs.refresh, {
        label: 'Refresh Terminal',
        caption: 'Refresh the current terminal session',
        execute: () => {
            let current = tracker.currentWidget;
            if (!current) {
                return;
            }
            shell.activateById(current.id);
            return current.content.refresh().then(() => {
                if (current) {
                    current.content.activate();
                }
            });
        },
        isEnabled: () => tracker.currentWidget !== null
    });
    commands.addCommand(CommandIDs.increaseFont, {
        label: 'Increase Terminal Font Size',
        execute: () => {
            let options = terminal_1.Terminal.defaultOptions;
            if (options.fontSize < 72) {
                options.fontSize++;
                tracker.forEach(widget => {
                    widget.content.fontSize = options.fontSize;
                });
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.decreaseFont, {
        label: 'Decrease Terminal Font Size',
        execute: () => {
            let options = terminal_1.Terminal.defaultOptions;
            if (options.fontSize > 9) {
                options.fontSize--;
                tracker.forEach(widget => {
                    widget.content.fontSize = options.fontSize;
                });
            }
        },
        isEnabled
    });
    let terminalTheme = 'dark';
    commands.addCommand(CommandIDs.toggleTheme, {
        label: 'Use Dark Terminal Theme',
        caption: 'Whether to use the dark terminal theme',
        isToggled: () => terminalTheme === 'dark',
        execute: () => {
            terminalTheme = terminalTheme === 'dark' ? 'light' : 'dark';
            let options = terminal_1.Terminal.defaultOptions;
            options.theme = terminalTheme;
            tracker.forEach(widget => {
                if (widget.content.theme !== terminalTheme) {
                    widget.content.theme = terminalTheme;
                }
            });
            commands.notifyCommandChanged(CommandIDs.toggleTheme);
        },
        isEnabled
    });
}
exports.addCommands = addCommands;


/***/ }),

/***/ "24WU":
/*!*************************************************!*\
  !*** ./node_modules/draft-js-utils/lib/main.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _Constants = __webpack_require__(/*! ./Constants */ "XATK");

Object.keys(_Constants).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _Constants[key];
    }
  });
});
Object.defineProperty(exports, 'Constants', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Constants).default;
  }
});

var _getEntityRanges = __webpack_require__(/*! ./getEntityRanges */ "NHcn");

Object.defineProperty(exports, 'getEntityRanges', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_getEntityRanges).default;
  }
});

var _getSelectedBlocks = __webpack_require__(/*! ./getSelectedBlocks */ "jb54");

Object.defineProperty(exports, 'getSelectedBlocks', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_getSelectedBlocks).default;
  }
});

var _selectionContainsEntity = __webpack_require__(/*! ./selectionContainsEntity */ "1pyT");

Object.defineProperty(exports, 'selectionContainsEntity', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_selectionContainsEntity).default;
  }
});

var _callModifierForSelectedBlocks = __webpack_require__(/*! ./callModifierForSelectedBlocks */ "Gdy8");

Object.defineProperty(exports, 'callModifierForSelectedBlocks', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_callModifierForSelectedBlocks).default;
  }
});

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/***/ }),

/***/ "25Eh":
/*!*******************************************************!*\
  !*** ./node_modules/codemirror/mode/python/python.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"));
  else {}
})(function(CodeMirror) {
  "use strict";

  function wordRegexp(words) {
    return new RegExp("^((" + words.join(")|(") + "))\\b");
  }

  var wordOperators = wordRegexp(["and", "or", "not", "is"]);
  var commonKeywords = ["as", "assert", "break", "class", "continue",
                        "def", "del", "elif", "else", "except", "finally",
                        "for", "from", "global", "if", "import",
                        "lambda", "pass", "raise", "return",
                        "try", "while", "with", "yield", "in"];
  var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr",
                        "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod",
                        "enumerate", "eval", "filter", "float", "format", "frozenset",
                        "getattr", "globals", "hasattr", "hash", "help", "hex", "id",
                        "input", "int", "isinstance", "issubclass", "iter", "len",
                        "list", "locals", "map", "max", "memoryview", "min", "next",
                        "object", "oct", "open", "ord", "pow", "property", "range",
                        "repr", "reversed", "round", "set", "setattr", "slice",
                        "sorted", "staticmethod", "str", "sum", "super", "tuple",
                        "type", "vars", "zip", "__import__", "NotImplemented",
                        "Ellipsis", "__debug__"];
  CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins));

  function top(state) {
    return state.scopes[state.scopes.length - 1];
  }

  CodeMirror.defineMode("python", function(conf, parserConf) {
    var ERRORCLASS = "error";

    var delimiters = parserConf.delimiters || parserConf.singleDelimiters || /^[\(\)\[\]\{\}@,:`=;\.\\]/;
    //               (Backwards-compatiblity with old, cumbersome config system)
    var operators = [parserConf.singleOperators, parserConf.doubleOperators, parserConf.doubleDelimiters, parserConf.tripleDelimiters,
                     parserConf.operators || /^([-+*/%\/&|^]=?|[<>=]+|\/\/=?|\*\*=?|!=|[~!@])/]
    for (var i = 0; i < operators.length; i++) if (!operators[i]) operators.splice(i--, 1)

    var hangingIndent = parserConf.hangingIndent || conf.indentUnit;

    var myKeywords = commonKeywords, myBuiltins = commonBuiltins;
    if (parserConf.extra_keywords != undefined)
      myKeywords = myKeywords.concat(parserConf.extra_keywords);

    if (parserConf.extra_builtins != undefined)
      myBuiltins = myBuiltins.concat(parserConf.extra_builtins);

    var py3 = !(parserConf.version && Number(parserConf.version) < 3)
    if (py3) {
      // since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator
      var identifiers = parserConf.identifiers|| /^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/;
      myKeywords = myKeywords.concat(["nonlocal", "False", "True", "None", "async", "await"]);
      myBuiltins = myBuiltins.concat(["ascii", "bytes", "exec", "print"]);
      var stringPrefixes = new RegExp("^(([rbuf]|(br)|(fr))?('{3}|\"{3}|['\"]))", "i");
    } else {
      var identifiers = parserConf.identifiers|| /^[_A-Za-z][_A-Za-z0-9]*/;
      myKeywords = myKeywords.concat(["exec", "print"]);
      myBuiltins = myBuiltins.concat(["apply", "basestring", "buffer", "cmp", "coerce", "execfile",
                                      "file", "intern", "long", "raw_input", "reduce", "reload",
                                      "unichr", "unicode", "xrange", "False", "True", "None"]);
      var stringPrefixes = new RegExp("^(([rubf]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
    }
    var keywords = wordRegexp(myKeywords);
    var builtins = wordRegexp(myBuiltins);

    // tokenizers
    function tokenBase(stream, state) {
      var sol = stream.sol() && state.lastToken != "\\"
      if (sol) state.indent = stream.indentation()
      // Handle scope changes
      if (sol && top(state).type == "py") {
        var scopeOffset = top(state).offset;
        if (stream.eatSpace()) {
          var lineOffset = stream.indentation();
          if (lineOffset > scopeOffset)
            pushPyScope(state);
          else if (lineOffset < scopeOffset && dedent(stream, state) && stream.peek() != "#")
            state.errorToken = true;
          return null;
        } else {
          var style = tokenBaseInner(stream, state);
          if (scopeOffset > 0 && dedent(stream, state))
            style += " " + ERRORCLASS;
          return style;
        }
      }
      return tokenBaseInner(stream, state);
    }

    function tokenBaseInner(stream, state) {
      if (stream.eatSpace()) return null;

      // Handle Comments
      if (stream.match(/^#.*/)) return "comment";

      // Handle Number Literals
      if (stream.match(/^[0-9\.]/, false)) {
        var floatLiteral = false;
        // Floats
        if (stream.match(/^[\d_]*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
        if (stream.match(/^[\d_]+\.\d*/)) { floatLiteral = true; }
        if (stream.match(/^\.\d+/)) { floatLiteral = true; }
        if (floatLiteral) {
          // Float literals may be "imaginary"
          stream.eat(/J/i);
          return "number";
        }
        // Integers
        var intLiteral = false;
        // Hex
        if (stream.match(/^0x[0-9a-f_]+/i)) intLiteral = true;
        // Binary
        if (stream.match(/^0b[01_]+/i)) intLiteral = true;
        // Octal
        if (stream.match(/^0o[0-7_]+/i)) intLiteral = true;
        // Decimal
        if (stream.match(/^[1-9][\d_]*(e[\+\-]?[\d_]+)?/)) {
          // Decimal literals may be "imaginary"
          stream.eat(/J/i);
          // TODO - Can you have imaginary longs?
          intLiteral = true;
        }
        // Zero by itself with no other piece of number.
        if (stream.match(/^0(?![\dx])/i)) intLiteral = true;
        if (intLiteral) {
          // Integer literals may be "long"
          stream.eat(/L/i);
          return "number";
        }
      }

      // Handle Strings
      if (stream.match(stringPrefixes)) {
        var isFmtString = stream.current().toLowerCase().indexOf('f') !== -1;
        if (!isFmtString) {
          state.tokenize = tokenStringFactory(stream.current());
          return state.tokenize(stream, state);
        } else {
          state.tokenize = formatStringFactory(stream.current(), state.tokenize);
          return state.tokenize(stream, state);
        }
      }

      for (var i = 0; i < operators.length; i++)
        if (stream.match(operators[i])) return "operator"

      if (stream.match(delimiters)) return "punctuation";

      if (state.lastToken == "." && stream.match(identifiers))
        return "property";

      if (stream.match(keywords) || stream.match(wordOperators))
        return "keyword";

      if (stream.match(builtins))
        return "builtin";

      if (stream.match(/^(self|cls)\b/))
        return "variable-2";

      if (stream.match(identifiers)) {
        if (state.lastToken == "def" || state.lastToken == "class")
          return "def";
        return "variable";
      }

      // Handle non-detected items
      stream.next();
      return ERRORCLASS;
    }

    function formatStringFactory(delimiter, tokenOuter) {
      while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)
        delimiter = delimiter.substr(1);

      var singleline = delimiter.length == 1;
      var OUTCLASS = "string";

      function tokenFString(stream, state) {
        // inside f-str Expression
        if (stream.match(delimiter)) {
          // expression ends pre-maturally, but very common in editing
          // Could show error to remind users to close brace here
          state.tokenize = tokenString
          return OUTCLASS;
        } else if (stream.match('{')) {
          // starting brace, if not eaten below
          return "punctuation";
        } else if (stream.match('}')) {
          // return to regular inside string state
          state.tokenize = tokenString
          return "punctuation";
        } else {
          // use tokenBaseInner to parse the expression
          return tokenBaseInner(stream, state);
        }
      }

      function tokenString(stream, state) {
        while (!stream.eol()) {
          stream.eatWhile(/[^'"\{\}\\]/);
          if (stream.eat("\\")) {
            stream.next();
            if (singleline && stream.eol())
              return OUTCLASS;
          } else if (stream.match(delimiter)) {
            state.tokenize = tokenOuter;
            return OUTCLASS;
          } else if (stream.match('{{')) {
            // ignore {{ in f-str
            return OUTCLASS;
          } else if (stream.match('{', false)) {
            // switch to nested mode
            state.tokenize = tokenFString
            if (stream.current()) {
              return OUTCLASS;
            } else {
              // need to return something, so eat the starting {
              stream.next();
              return "punctuation";
            }
          } else if (stream.match('}}')) {
            return OUTCLASS;
          } else if (stream.match('}')) {
            // single } in f-string is an error
            return ERRORCLASS;
          } else {
            stream.eat(/['"]/);
          }
        }
        if (singleline) {
          if (parserConf.singleLineStringErrors)
            return ERRORCLASS;
          else
            state.tokenize = tokenOuter;
        }
        return OUTCLASS;
      }
      tokenString.isString = true;
      return tokenString;
    }

    function tokenStringFactory(delimiter) {
      while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)
        delimiter = delimiter.substr(1);

      var singleline = delimiter.length == 1;
      var OUTCLASS = "string";

      function tokenString(stream, state) {
        while (!stream.eol()) {
          stream.eatWhile(/[^'"\\]/);
          if (stream.eat("\\")) {
            stream.next();
            if (singleline && stream.eol())
              return OUTCLASS;
          } else if (stream.match(delimiter)) {
            state.tokenize = tokenBase;
            return OUTCLASS;
          } else {
            stream.eat(/['"]/);
          }
        }
        if (singleline) {
          if (parserConf.singleLineStringErrors)
            return ERRORCLASS;
          else
            state.tokenize = tokenBase;
        }
        return OUTCLASS;
      }
      tokenString.isString = true;
      return tokenString;
    }

    function pushPyScope(state) {
      while (top(state).type != "py") state.scopes.pop()
      state.scopes.push({offset: top(state).offset + conf.indentUnit,
                         type: "py",
                         align: null})
    }

    function pushBracketScope(stream, state, type) {
      var align = stream.match(/^([\s\[\{\(]|#.*)*$/, false) ? null : stream.column() + 1
      state.scopes.push({offset: state.indent + hangingIndent,
                         type: type,
                         align: align})
    }

    function dedent(stream, state) {
      var indented = stream.indentation();
      while (state.scopes.length > 1 && top(state).offset > indented) {
        if (top(state).type != "py") return true;
        state.scopes.pop();
      }
      return top(state).offset != indented;
    }

    function tokenLexer(stream, state) {
      if (stream.sol()) state.beginningOfLine = true;

      var style = state.tokenize(stream, state);
      var current = stream.current();

      // Handle decorators
      if (state.beginningOfLine && current == "@")
        return stream.match(identifiers, false) ? "meta" : py3 ? "operator" : ERRORCLASS;

      if (/\S/.test(current)) state.beginningOfLine = false;

      if ((style == "variable" || style == "builtin")
          && state.lastToken == "meta")
        style = "meta";

      // Handle scope changes.
      if (current == "pass" || current == "return")
        state.dedent += 1;

      if (current == "lambda") state.lambda = true;
      if (current == ":" && !state.lambda && top(state).type == "py")
        pushPyScope(state);

      if (current.length == 1 && !/string|comment/.test(style)) {
        var delimiter_index = "[({".indexOf(current);
        if (delimiter_index != -1)
          pushBracketScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1));

        delimiter_index = "])}".indexOf(current);
        if (delimiter_index != -1) {
          if (top(state).type == current) state.indent = state.scopes.pop().offset - hangingIndent
          else return ERRORCLASS;
        }
      }
      if (state.dedent > 0 && stream.eol() && top(state).type == "py") {
        if (state.scopes.length > 1) state.scopes.pop();
        state.dedent -= 1;
      }

      return style;
    }

    var external = {
      startState: function(basecolumn) {
        return {
          tokenize: tokenBase,
          scopes: [{offset: basecolumn || 0, type: "py", align: null}],
          indent: basecolumn || 0,
          lastToken: null,
          lambda: false,
          dedent: 0
        };
      },

      token: function(stream, state) {
        var addErr = state.errorToken;
        if (addErr) state.errorToken = false;
        var style = tokenLexer(stream, state);

        if (style && style != "comment")
          state.lastToken = (style == "keyword" || style == "punctuation") ? stream.current() : style;
        if (style == "punctuation") style = null;

        if (stream.eol() && state.lambda)
          state.lambda = false;
        return addErr ? style + " " + ERRORCLASS : style;
      },

      indent: function(state, textAfter) {
        if (state.tokenize != tokenBase)
          return state.tokenize.isString ? CodeMirror.Pass : 0;

        var scope = top(state), closing = scope.type == textAfter.charAt(0)
        if (scope.align != null)
          return scope.align - (closing ? 1 : 0)
        else
          return scope.offset - (closing ? hangingIndent : 0)
      },

      electricInput: /^\s*[\}\]\)]$/,
      closeBrackets: {triples: "'\""},
      lineComment: "#",
      fold: "indent"
    };
    return external;
  });

  CodeMirror.defineMIME("text/x-python", "python");

  var words = function(str) { return str.split(" "); };

  CodeMirror.defineMIME("text/x-cython", {
    name: "python",
    extra_keywords: words("by cdef cimport cpdef ctypedef enum except "+
                          "extern gil include nogil property public "+
                          "readonly struct union DEF IF ELIF ELSE")
  });

});


/***/ }),

/***/ "25UF":
/*!*************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeCarpetIcon.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeCarpetIcon = function TraceTypeCarpetIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement(
            'g',
            { fill: 'none' },
            _react2.default.createElement('path', { d: 'M0 0h46v46H0z' }),
            _react2.default.createElement('path', { stroke: '#1d9bfb', d: 'M41.5 16.469l-8.745 8.887-4.71 7.858-4.709 3.418-8.745-5.468L4.5 29.796l5.382-4.101 4.036-7.176 9.418-8.887 8.073 4.786L41.5 16.469z', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2' }),
            _react2.default.createElement('path', { stroke: '#1d9bfb', d: 'M28.045 33.214l-9.418-5.468-8.745-2.051m22.873-.339l-9.419-3.419-9.418-3.418', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2' }),
            _react2.default.createElement('path', { stroke: '#1d9bfb', d: 'M14.591 31.164l4.036-3.418 4.709-5.809 8.073-7.519', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2' })
        )
    );
};

exports.default = TraceTypeCarpetIcon;

/***/ }),

/***/ "27E4":
/*!******************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotLineIcon.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotLineIcon = function PlotLineIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M32 5.313l-9.375 14.688L6.687 5.313-.001 18.688v7.938l8-14.625 16 14.625 8-13.313z' })
    );
};

exports.default = PlotLineIcon;

/***/ }),

/***/ "29s/":
/*!*********************************************************!*\
  !*** ./node_modules/core-js/library/modules/_shared.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var core = __webpack_require__(/*! ./_core */ "WEpk");
var global = __webpack_require__(/*! ./_global */ "5T2Y");
var SHARED = '__core-js_shared__';
var store = global[SHARED] || (global[SHARED] = {});

(module.exports = function (key, value) {
  return store[key] || (store[key] = value !== undefined ? value : {});
})('versions', []).push({
  version: core.version,
  mode: __webpack_require__(/*! ./_library */ "uOPS") ? 'pure' : 'global',
  copyright: '© 2019 Denis Pushkarev (zloirock.ru)'
});


/***/ }),

/***/ "2DcK":
/*!***********************************************************!*\
  !*** ./node_modules/react-rangeslider/lib/Rangeslider.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _classnames = __webpack_require__(/*! classnames */ "TSYQ");

var _classnames2 = _interopRequireDefault(_classnames);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _resizeObserverPolyfill = __webpack_require__(/*! resize-observer-polyfill */ "bdgK");

var _resizeObserverPolyfill2 = _interopRequireDefault(_resizeObserverPolyfill);

var _utils = __webpack_require__(/*! ./utils */ "+/lC");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint no-debugger: "warn" */


/**
 * Predefined constants
 * @type {Object}
 */
var constants = {
  orientation: {
    horizontal: {
      dimension: 'width',
      direction: 'left',
      reverseDirection: 'right',
      coordinate: 'x'
    },
    vertical: {
      dimension: 'height',
      direction: 'top',
      reverseDirection: 'bottom',
      coordinate: 'y'
    }
  }
};

var Slider = function (_Component) {
  _inherits(Slider, _Component);

  function Slider(props, context) {
    _classCallCheck(this, Slider);

    var _this = _possibleConstructorReturn(this, (Slider.__proto__ || Object.getPrototypeOf(Slider)).call(this, props, context));

    _this.handleFormat = function (value) {
      var format = _this.props.format;

      return format ? format(value) : value;
    };

    _this.handleUpdate = function () {
      if (!_this.slider) {
        // for shallow rendering
        return;
      }
      var orientation = _this.props.orientation;

      var dimension = (0, _utils.capitalize)(constants.orientation[orientation].dimension);
      var sliderPos = _this.slider['offset' + dimension];
      var handlePos = _this.handle['offset' + dimension];

      _this.setState({
        limit: sliderPos - handlePos,
        grab: handlePos / 2
      });
    };

    _this.handleStart = function (e) {
      var onChangeStart = _this.props.onChangeStart;

      document.addEventListener('mousemove', _this.handleDrag);
      document.addEventListener('mouseup', _this.handleEnd);
      _this.setState({
        active: true
      }, function () {
        onChangeStart && onChangeStart(e);
      });
    };

    _this.handleDrag = function (e) {
      e.stopPropagation();
      var onChange = _this.props.onChange;
      var _e$target = e.target,
          className = _e$target.className,
          classList = _e$target.classList,
          dataset = _e$target.dataset;

      if (!onChange || className === 'rangeslider__labels') return;

      var value = _this.position(e);

      if (classList && classList.contains('rangeslider__label-item') && dataset.value) {
        value = parseFloat(dataset.value);
      }

      onChange && onChange(value, e);
    };

    _this.handleEnd = function (e) {
      var onChangeComplete = _this.props.onChangeComplete;

      _this.setState({
        active: false
      }, function () {
        onChangeComplete && onChangeComplete(e);
      });
      document.removeEventListener('mousemove', _this.handleDrag);
      document.removeEventListener('mouseup', _this.handleEnd);
    };

    _this.handleKeyDown = function (e) {
      e.preventDefault();
      var keyCode = e.keyCode;
      var _this$props = _this.props,
          value = _this$props.value,
          min = _this$props.min,
          max = _this$props.max,
          step = _this$props.step,
          onChange = _this$props.onChange;

      var sliderValue = void 0;

      switch (keyCode) {
        case 38:
        case 39:
          sliderValue = value + step > max ? max : value + step;
          onChange && onChange(sliderValue, e);
          break;
        case 37:
        case 40:
          sliderValue = value - step < min ? min : value - step;
          onChange && onChange(sliderValue, e);
          break;
      }
    };

    _this.getPositionFromValue = function (value) {
      var limit = _this.state.limit;
      var _this$props2 = _this.props,
          min = _this$props2.min,
          max = _this$props2.max;

      var diffMaxMin = max - min;
      var diffValMin = value - min;
      var percentage = diffValMin / diffMaxMin;
      var pos = Math.round(percentage * limit);

      return pos;
    };

    _this.getValueFromPosition = function (pos) {
      var limit = _this.state.limit;
      var _this$props3 = _this.props,
          orientation = _this$props3.orientation,
          min = _this$props3.min,
          max = _this$props3.max,
          step = _this$props3.step;

      var percentage = (0, _utils.clamp)(pos, 0, limit) / (limit || 1);
      var baseVal = step * Math.round(percentage * (max - min) / step);
      var value = orientation === 'horizontal' ? baseVal + min : max - baseVal;

      return (0, _utils.clamp)(value, min, max);
    };

    _this.position = function (e) {
      var grab = _this.state.grab;
      var _this$props4 = _this.props,
          orientation = _this$props4.orientation,
          reverse = _this$props4.reverse;


      var node = _this.slider;
      var coordinateStyle = constants.orientation[orientation].coordinate;
      var directionStyle = reverse ? constants.orientation[orientation].reverseDirection : constants.orientation[orientation].direction;
      var clientCoordinateStyle = 'client' + (0, _utils.capitalize)(coordinateStyle);
      var coordinate = !e.touches ? e[clientCoordinateStyle] : e.touches[0][clientCoordinateStyle];
      var direction = node.getBoundingClientRect()[directionStyle];
      var pos = reverse ? direction - coordinate - grab : coordinate - direction - grab;
      var value = _this.getValueFromPosition(pos);

      return value;
    };

    _this.coordinates = function (pos) {
      var _this$state = _this.state,
          limit = _this$state.limit,
          grab = _this$state.grab;
      var orientation = _this.props.orientation;

      var value = _this.getValueFromPosition(pos);
      var position = _this.getPositionFromValue(value);
      var handlePos = orientation === 'horizontal' ? position + grab : position;
      var fillPos = orientation === 'horizontal' ? handlePos : limit - handlePos;

      return {
        fill: fillPos,
        handle: handlePos,
        label: handlePos
      };
    };

    _this.renderLabels = function (labels) {
      return _react2.default.createElement(
        'ul',
        {
          ref: function ref(sl) {
            _this.labels = sl;
          },
          className: (0, _classnames2.default)('rangeslider__labels')
        },
        labels
      );
    };

    _this.state = {
      active: false,
      limit: 0,
      grab: 0
    };
    return _this;
  }

  _createClass(Slider, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      this.handleUpdate();
      var resizeObserver = new _resizeObserverPolyfill2.default(this.handleUpdate);
      resizeObserver.observe(this.slider);
    }

    /**
     * Format label/tooltip value
     * @param  {Number} - value
     * @return {Formatted Number}
     */


    /**
     * Update slider state on change
     * @return {void}
     */


    /**
     * Attach event listeners to mousemove/mouseup events
     * @return {void}
     */


    /**
     * Handle drag/mousemove event
     * @param  {Object} e - Event object
     * @return {void}
     */


    /**
     * Detach event listeners to mousemove/mouseup events
     * @return {void}
     */


    /**
     * Support for key events on the slider handle
     * @param  {Object} e - Event object
     * @return {void}
     */


    /**
     * Calculate position of slider based on its value
     * @param  {number} value - Current value of slider
     * @return {position} pos - Calculated position of slider based on value
     */


    /**
     * Translate position of slider to slider value
     * @param  {number} pos - Current position/coordinates of slider
     * @return {number} value - Slider value
     */


    /**
     * Calculate position of slider based on value
     * @param  {Object} e - Event object
     * @return {number} value - Slider value
     */


    /**
     * Grab coordinates of slider
     * @param  {Object} pos - Position object
     * @return {Object} - Slider fill/handle coordinates
     */

  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _props = this.props,
          value = _props.value,
          orientation = _props.orientation,
          className = _props.className,
          tooltip = _props.tooltip,
          reverse = _props.reverse,
          labels = _props.labels,
          min = _props.min,
          max = _props.max,
          handleLabel = _props.handleLabel;
      var active = this.state.active;

      var dimension = constants.orientation[orientation].dimension;
      var direction = reverse ? constants.orientation[orientation].reverseDirection : constants.orientation[orientation].direction;
      var position = this.getPositionFromValue(value);
      var coords = this.coordinates(position);
      var fillStyle = _defineProperty({}, dimension, coords.fill + 'px');
      var handleStyle = _defineProperty({}, direction, coords.handle + 'px');
      var showTooltip = tooltip && active;

      var labelItems = [];
      var labelKeys = Object.keys(labels);

      if (labelKeys.length > 0) {
        labelKeys = labelKeys.sort(function (a, b) {
          return reverse ? a - b : b - a;
        });

        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
          for (var _iterator = labelKeys[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var key = _step.value;

            var labelPosition = this.getPositionFromValue(key);
            var labelCoords = this.coordinates(labelPosition);
            var labelStyle = _defineProperty({}, direction, labelCoords.label + 'px');

            labelItems.push(_react2.default.createElement(
              'li',
              {
                key: key,
                className: (0, _classnames2.default)('rangeslider__label-item'),
                'data-value': key,
                onMouseDown: this.handleDrag,
                onTouchStart: this.handleStart,
                onTouchEnd: this.handleEnd,
                style: labelStyle
              },
              this.props.labels[key]
            ));
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator.return) {
              _iterator.return();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }
      }

      return _react2.default.createElement(
        'div',
        {
          ref: function ref(s) {
            _this2.slider = s;
          },
          className: (0, _classnames2.default)('rangeslider', 'rangeslider-' + orientation, { 'rangeslider-reverse': reverse }, className),
          onMouseDown: this.handleDrag,
          onMouseUp: this.handleEnd,
          onTouchStart: this.handleStart,
          onTouchEnd: this.handleEnd,
          'aria-valuemin': min,
          'aria-valuemax': max,
          'aria-valuenow': value,
          'aria-orientation': orientation
        },
        _react2.default.createElement('div', { className: 'rangeslider__fill', style: fillStyle }),
        _react2.default.createElement(
          'div',
          {
            ref: function ref(sh) {
              _this2.handle = sh;
            },
            className: 'rangeslider__handle',
            onMouseDown: this.handleStart,
            onTouchMove: this.handleDrag,
            onTouchEnd: this.handleEnd,
            onKeyDown: this.handleKeyDown,
            style: handleStyle,
            tabIndex: 0
          },
          showTooltip ? _react2.default.createElement(
            'div',
            {
              ref: function ref(st) {
                _this2.tooltip = st;
              },
              className: 'rangeslider__handle-tooltip'
            },
            _react2.default.createElement(
              'span',
              null,
              this.handleFormat(value)
            )
          ) : null,
          _react2.default.createElement(
            'div',
            { className: 'rangeslider__handle-label' },
            handleLabel
          )
        ),
        labels ? this.renderLabels(labelItems) : null
      );
    }
  }]);

  return Slider;
}(_react.Component);

Slider.propTypes = {
  min: _propTypes2.default.number,
  max: _propTypes2.default.number,
  step: _propTypes2.default.number,
  value: _propTypes2.default.number,
  orientation: _propTypes2.default.string,
  tooltip: _propTypes2.default.bool,
  reverse: _propTypes2.default.bool,
  labels: _propTypes2.default.object,
  handleLabel: _propTypes2.default.string,
  format: _propTypes2.default.func,
  onChangeStart: _propTypes2.default.func,
  onChange: _propTypes2.default.func,
  onChangeComplete: _propTypes2.default.func
};
Slider.defaultProps = {
  min: 0,
  max: 100,
  step: 1,
  value: 0,
  orientation: 'horizontal',
  tooltip: true,
  reverse: false,
  labels: {},
  handleLabel: ''
};
exports.default = Slider;

/***/ }),

/***/ "2F0p":
/*!********************************************************************!*\
  !*** ./node_modules/@jupyterlab/application/lib/layoutrestorer.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const properties_1 = __webpack_require__(/*! @phosphor/properties */ "3kwb");
/* tslint:disable */
/**
 * The layout restorer token.
 */
exports.ILayoutRestorer = new coreutils_1.Token('@jupyterlab/application:ILayoutRestorer');
/**
 * The state database key for restorer data.
 */
const KEY = 'layout-restorer:data';
/**
 * The default implementation of a layout restorer.
 *
 * #### Notes
 * The lifecycle for state restoration is subtle. The sequence of events is:
 *
 * 1. The layout restorer plugin is instantiated and makes a `fetch` call to
 *    the database that stores the layout restoration data. The `fetch` call
 *    returns a promise that resolves in step 6, below.
 *
 * 2. Other plugins that care about state restoration require the layout
 *    restorer as a dependency.
 *
 * 3. As each load-time plugin initializes (which happens before the lab
 *    application has `started`), it instructs the layout restorer whether
 *    the restorer ought to `restore` its state by passing in its tracker.
 *    Alternatively, a plugin that does not require its own instance tracker
 *    (because perhaps it only creates a single widget, like a command palette),
 *    can simply `add` its widget along with a persistent unique name to the
 *    layout restorer so that its layout state can be restored when the lab
 *    application restores.
 *
 * 4. After all the load-time plugins have finished initializing, the lab
 *    application `started` promise will resolve. This is the `first`
 *    promise that the layout restorer waits for. By this point, all of the
 *    plugins that care about restoration will have instructed the layout
 *    restorer to `restore` their state.
 *
 * 5. The layout restorer will then instruct each plugin's instance tracker
 *    to restore its state and reinstantiate whichever widgets it wants. The
 *    tracker returns a promise to the layout restorer that resolves when it
 *    has completed restoring the tracked widgets it cares about.
 *
 * 6. As each instance tracker finishes restoring the widget instances it cares
 *    about, it resolves the promise that was made to the layout restorer
 *    (in step 5). After all of the promises that the restorer is awaiting have
 *    resolved, the restorer then resolves the outstanding `fetch` promise
 *    (from step 1) and hands off a layout state object to the application
 *    shell's `restoreLayout` method for restoration.
 *
 * 7. Once the application shell has finished restoring the layout, the
 *    JupyterLab application's `restored` promise is resolved.
 *
 * Of particular note are steps 5 and 6: since state restoration of plugins
 * is accomplished by executing commands, the command that is used to restore
 * the state of each plugin must return a promise that only resolves when the
 * widget has been created and added to the plugin's instance tracker.
 */
class LayoutRestorer {
    /**
     * Create a layout restorer.
     */
    constructor(options) {
        this._firstDone = false;
        this._promisesDone = false;
        this._promises = [];
        this._restored = new coreutils_1.PromiseDelegate();
        this._trackers = new Set();
        this._widgets = new Map();
        this._registry = options.registry;
        this._state = options.state;
        this._first = options.first;
        this._first
            .then(() => {
            this._firstDone = true;
        })
            .then(() => Promise.all(this._promises))
            .then(() => {
            this._promisesDone = true;
            // Release the tracker set.
            this._trackers.clear();
        })
            .then(() => {
            this._restored.resolve(void 0);
        });
    }
    /**
     * A promise resolved when the layout restorer is ready to receive signals.
     */
    get restored() {
        return this._restored.promise;
    }
    /**
     * Add a widget to be tracked by the layout restorer.
     */
    add(widget, name) {
        Private.nameProperty.set(widget, name);
        this._widgets.set(name, widget);
        widget.disposed.connect(this._onWidgetDisposed, this);
    }
    /**
     * Fetch the layout state for the application.
     *
     * #### Notes
     * Fetching the layout relies on all widget restoration to be complete, so
     * calls to `fetch` are guaranteed to return after restoration is complete.
     */
    fetch() {
        const blank = {
            fresh: true,
            mainArea: null,
            leftArea: null,
            rightArea: null
        };
        let layout = this._state.fetch(KEY);
        return Promise.all([layout, this.restored])
            .then(([data]) => {
            if (!data) {
                return blank;
            }
            const { main, left, right } = data;
            // If any data exists, then this is not a fresh session.
            const fresh = false;
            // Rehydrate main area.
            const mainArea = this._rehydrateMainArea(main);
            // Rehydrate left area.
            const leftArea = this._rehydrateSideArea(left);
            // Rehydrate right area.
            const rightArea = this._rehydrateSideArea(right);
            return { fresh, mainArea, leftArea, rightArea };
        })
            .catch(() => blank); // Let fetch fail gracefully; return blank slate.
    }
    /**
     * Restore the widgets of a particular instance tracker.
     *
     * @param tracker - The instance tracker whose widgets will be restored.
     *
     * @param options - The restoration options.
     */
    restore(tracker, options) {
        const warning = 'restore() can only be called before `first` has resolved.';
        if (this._firstDone) {
            console.warn(warning);
            return Promise.reject(warning);
        }
        const { namespace } = tracker;
        if (this._trackers.has(namespace)) {
            let warning = `A tracker namespaced ${namespace} was already restored.`;
            console.warn(warning);
            return Promise.reject(warning);
        }
        const { args, command, name, when } = options;
        // Add the tracker to the private trackers collection.
        this._trackers.add(namespace);
        // Whenever a new widget is added to the tracker, record its name.
        tracker.widgetAdded.connect((sender, widget) => {
            const widgetName = name(widget);
            if (widgetName) {
                this.add(widget, `${namespace}:${widgetName}`);
            }
        }, this);
        // Whenever a widget is updated, get its new name.
        tracker.widgetUpdated.connect((sender, widget) => {
            const widgetName = name(widget);
            if (widgetName) {
                let name = `${namespace}:${widgetName}`;
                Private.nameProperty.set(widget, name);
                this._widgets.set(name, widget);
            }
        });
        const first = this._first;
        const promise = tracker
            .restore({
            args,
            command,
            name,
            registry: this._registry,
            state: this._state,
            when: when ? [first].concat(when) : first
        })
            .catch(error => {
            console.error(error);
        });
        this._promises.push(promise);
        return promise;
    }
    /**
     * Save the layout state for the application.
     */
    save(data) {
        // If there are promises that are unresolved, bail.
        if (!this._promisesDone) {
            let warning = 'save() was called prematurely.';
            console.warn(warning);
            return Promise.reject(warning);
        }
        let dehydrated = {};
        // Dehydrate main area.
        dehydrated.main = this._dehydrateMainArea(data.mainArea);
        // Dehydrate left area.
        dehydrated.left = this._dehydrateSideArea(data.leftArea);
        // Dehydrate right area.
        dehydrated.right = this._dehydrateSideArea(data.rightArea);
        return this._state.save(KEY, dehydrated);
    }
    /**
     * Dehydrate a main area description into a serializable object.
     */
    _dehydrateMainArea(area) {
        if (!area) {
            return null;
        }
        return Private.serializeMain(area);
    }
    /**
     * Reydrate a serialized main area description object.
     *
     * #### Notes
     * This function consumes data that can become corrupted, so it uses type
     * coercion to guarantee the dehydrated object is safely processed.
     */
    _rehydrateMainArea(area) {
        if (!area) {
            return null;
        }
        return Private.deserializeMain(area, this._widgets);
    }
    /**
     * Dehydrate a side area description into a serializable object.
     */
    _dehydrateSideArea(area) {
        if (!area) {
            return null;
        }
        let dehydrated = { collapsed: area.collapsed };
        if (area.currentWidget) {
            let current = Private.nameProperty.get(area.currentWidget);
            if (current) {
                dehydrated.current = current;
            }
        }
        if (area.widgets) {
            dehydrated.widgets = area.widgets
                .map(widget => Private.nameProperty.get(widget))
                .filter(name => !!name);
        }
        return dehydrated;
    }
    /**
     * Reydrate a serialized side area description object.
     *
     * #### Notes
     * This function consumes data that can become corrupted, so it uses type
     * coercion to guarantee the dehydrated object is safely processed.
     */
    _rehydrateSideArea(area) {
        if (!area) {
            return { collapsed: true, currentWidget: null, widgets: null };
        }
        let internal = this._widgets;
        const collapsed = area.hasOwnProperty('collapsed')
            ? !!area.collapsed
            : false;
        const currentWidget = area.current && internal.has(`${area.current}`)
            ? internal.get(`${area.current}`)
            : null;
        const widgets = !Array.isArray(area.widgets)
            ? null
            : area.widgets
                .map(name => (internal.has(`${name}`) ? internal.get(`${name}`) : null))
                .filter(widget => !!widget);
        return {
            collapsed,
            currentWidget: currentWidget,
            widgets: widgets
        };
    }
    /**
     * Handle a widget disposal.
     */
    _onWidgetDisposed(widget) {
        let name = Private.nameProperty.get(widget);
        this._widgets.delete(name);
    }
}
exports.LayoutRestorer = LayoutRestorer;
/*
 * A namespace for private data.
 */
var Private;
(function (Private) {
    /**
     * An attached property for a widget's ID in the state database.
     */
    Private.nameProperty = new properties_1.AttachedProperty({
        name: 'name',
        create: owner => ''
    });
    /**
     * Serialize individual areas within the main area.
     */
    function serializeArea(area) {
        if (!area || !area.type) {
            return null;
        }
        if (area.type === 'tab-area') {
            return {
                type: 'tab-area',
                currentIndex: area.currentIndex,
                widgets: area.widgets
                    .map(widget => Private.nameProperty.get(widget))
                    .filter(name => !!name)
            };
        }
        return {
            type: 'split-area',
            orientation: area.orientation,
            sizes: area.sizes,
            children: area.children.map(serializeArea).filter(area => !!area)
        };
    }
    /**
     * Return a dehydrated, serializable version of the main dock panel.
     */
    function serializeMain(area) {
        let dehydrated = {
            dock: (area && area.dock && serializeArea(area.dock.main)) || null
        };
        if (area) {
            dehydrated.mode = area.mode;
            if (area.currentWidget) {
                let current = Private.nameProperty.get(area.currentWidget);
                if (current) {
                    dehydrated.current = current;
                }
            }
        }
        return dehydrated;
    }
    Private.serializeMain = serializeMain;
    /**
     * Deserialize individual areas within the main area.
     *
     * #### Notes
     * Because this data comes from a potentially unreliable foreign source, it is
     * typed as a `JSONObject`; but the actual expected type is:
     * `ITabArea | ISplitArea`.
     *
     * For fault tolerance, types are manually checked in deserialization.
     */
    function deserializeArea(area, names) {
        if (!area) {
            return null;
        }
        // Because this data is saved to a foreign data source, its type safety is
        // not guaranteed when it is retrieved, so exhaustive checks are necessary.
        const type = area.type || 'unknown';
        if (type === 'unknown' || (type !== 'tab-area' && type !== 'split-area')) {
            console.warn(`Attempted to deserialize unknown type: ${type}`);
            return null;
        }
        if (type === 'tab-area') {
            const { currentIndex, widgets } = area;
            let hydrated = {
                type: 'tab-area',
                currentIndex: currentIndex || 0,
                widgets: (widgets &&
                    widgets
                        .map(widget => names.get(widget))
                        .filter(widget => !!widget)) ||
                    []
            };
            // Make sure the current index is within bounds.
            if (hydrated.currentIndex > hydrated.widgets.length - 1) {
                hydrated.currentIndex = 0;
            }
            return hydrated;
        }
        const { orientation, sizes, children } = area;
        let hydrated = {
            type: 'split-area',
            orientation: orientation,
            sizes: sizes || [],
            children: (children &&
                children
                    .map(child => deserializeArea(child, names))
                    .filter(widget => !!widget)) ||
                []
        };
        return hydrated;
    }
    /**
     * Return the hydrated version of the main dock panel, ready to restore.
     *
     * #### Notes
     * Because this data comes from a potentially unreliable foreign source, it is
     * typed as a `JSONObject`; but the actual expected type is: `IMainArea`.
     *
     * For fault tolerance, types are manually checked in deserialization.
     */
    function deserializeMain(area, names) {
        if (!area) {
            return null;
        }
        const name = area.current || null;
        const dock = area.dock || null;
        const mode = area.mode || null;
        return {
            currentWidget: (name && names.has(name) && names.get(name)) || null,
            dock: dock ? { main: deserializeArea(dock, names) } : null,
            mode: mode === 'multiple-document' || mode === 'single-document' ? mode : null
        };
    }
    Private.deserializeMain = deserializeMain;
})(Private || (Private = {}));


/***/ }),

/***/ "2GTP":
/*!******************************************************!*\
  !*** ./node_modules/core-js/library/modules/_ctx.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// optional / simple context binding
var aFunction = __webpack_require__(/*! ./_a-function */ "eaoh");
module.exports = function (fn, that, length) {
  aFunction(fn);
  if (that === undefined) return fn;
  switch (length) {
    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);
  };
};


/***/ }),

/***/ "2KtR":
/*!******************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/shame.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.shamefullyAdjustSizeref = exports.shamefullyDeleteRelatedAnalysisTransforms = exports.shamefullyCreateSplitStyleProps = exports.shamefullyAdjustSplitStyleTargetContainers = exports.shamefullyAddTableColumns = exports.shamefullyAdjustGeo = exports.shamefullyAdjustAxisRef = exports.shamefullyClearAxisTypes = undefined;

var _axis_ids = __webpack_require__(/*! plotly.js/src/plots/cartesian/axis_ids */ "PBw4");

var _nested_property = __webpack_require__(/*! plotly.js/src/lib/nested_property */ "dNZO");

var _nested_property2 = _interopRequireDefault(_nested_property);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

// Temporary fix for:
// https://github.com/plotly/react-chart-editor/issues/103
// We should be able to remove this once the plotly.react method has
// been integrated into react-plotly.js and released:
// https://github.com/plotly/react-plotly.js/issues/2
/*
 * DELETE THIS FILE. EVERYTHING NEEDS TO FIND A HOME.
 */
var shamefullyClearAxisTypes = exports.shamefullyClearAxisTypes = function shamefullyClearAxisTypes(graphDiv, _ref) {
  var traceIndexes = _ref.traceIndexes,
      update = _ref.update;

  if (!Array.isArray(graphDiv._fullData)) {
    return;
  }
  var hasSrc = false;
  for (var key in update) {
    if (key.substr(key.length - 3) === 'src') {
      hasSrc = true;
    }
  }
  if (hasSrc) {
    clearAxisTypes(graphDiv, traceIndexes);
  }
};

var axLetters = ['x', 'y', 'z'];
function clearAxisTypes(gd, traces) {
  for (var i = 0; i < traces.length; i++) {
    var trace = gd._fullData[i];
    for (var j = 0; j < 3; j++) {
      var type = axLetters[j];
      var ax = (0, _axis_ids.getFromId)(gd, trace[type + 'axis'] || type);

      // Do not clear log type.
      // Log type is never an auto result so must have been intentional.
      // We are also skipping clearing 3D which could cause bugs with 3D.
      if (ax && ax.type !== 'log') {
        var axAttr = ax._name;
        var typeAttr = axAttr + '.type';
        (0, _nested_property2.default)(gd.layout, typeAttr).set(null);
      }
    }
  }
}

var shamefullyAdjustAxisRef = exports.shamefullyAdjustAxisRef = function shamefullyAdjustAxisRef(graphDiv, payload) {
  if (payload.axesToBeGarbageCollected) {
    payload.axesToBeGarbageCollected.forEach(function (a) {
      var axis = a.charAt(0);
      var axisIdNumber = Number(a.slice(1));

      (0, _nested_property2.default)(graphDiv.layout, axis + 'axis' + (axisIdNumber || '')).set(null);
      Object.keys(graphDiv.layout).filter(function (key) {
        return key.startsWith(axis + 'axis');
      }).forEach(function (key) {
        if ((0, _nested_property2.default)(graphDiv.layout, key + '.overlaying').get() === a) {
          (0, _nested_property2.default)(graphDiv.layout, key + '.overlaying').set(null);
        }
      });
    });
  }
  if (payload.subplotToBeGarbageCollected) {
    (0, _nested_property2.default)(graphDiv.layout, payload.subplotToBeGarbageCollected).set(null);
  }
};

var geoRegex = /^(geo\d*)\./;
var shamefullyAdjustGeo = exports.shamefullyAdjustGeo = function shamefullyAdjustGeo(_ref2, _ref3) {
  var layout = _ref2.layout;
  var update = _ref3.update;

  Object.keys(update).forEach(function (k) {
    var geoMatch = geoRegex.exec(k);
    if (geoMatch) {
      var geo = geoMatch[1];
      if (update[geo + '.scope']) {
        update[geo + '.projection'] = {};
        update[geo + '.center'] = {};
      }

      if (
      // requesting projection change
      update[geo + '.projection.type'] && (update[geo + '.projection.type'] === 'albers usa' || layout[geo] && layout[geo].scope === 'usa')) {
        update[geo + '.scope'] = {};
        update[geo + '.center'] = {};
      }
    }
  });
};

var shamefullyAddTableColumns = exports.shamefullyAddTableColumns = function shamefullyAddTableColumns(graphDiv, _ref4) {
  var traceIndexes = _ref4.traceIndexes,
      update = _ref4.update;

  if (update['cells.values'] && (!graphDiv.data[traceIndexes[0]].header || !graphDiv.data[traceIndexes[0]].header.valuessrc)) {
    update['header.values'] = update['cells.valuessrc'];
  } else if (update['header.values'] === null) {
    update['header.values'] = graphDiv.data[traceIndexes[0]].cells.valuessrc || null;
  } else if (update['cells.values'] === null && !graphDiv.data[traceIndexes[0]].header.valuessrc) {
    update['header.values'] = null;
  }
};

var shamefullyAdjustSplitStyleTargetContainers = exports.shamefullyAdjustSplitStyleTargetContainers = function shamefullyAdjustSplitStyleTargetContainers(graphDiv, _ref5) {
  var traceIndexes = _ref5.traceIndexes,
      update = _ref5.update;

  for (var attr in update) {
    if (attr && attr.startsWith('transforms') && attr.endsWith('groups')) {
      var transformIndex = parseInt(attr.split('[')[1], 10);
      var transform = graphDiv.data[traceIndexes[0]].transforms[transformIndex];

      if (transform && transform.type === 'groupby' && transform.styles) {
        // Create style containers for all groups
        if (!transform.styles.length && update[attr]) {
          (function () {
            var dedupedGroups = [];
            update[attr].forEach(function (group) {
              if (!dedupedGroups.includes(group)) {
                dedupedGroups.push(group);
              }
            });

            var styles = dedupedGroups.map(function (groupEl) {
              return {
                target: groupEl,
                value: {}
              };
            });

            update['transforms[' + transformIndex + '].styles'] = styles;
          })();
        }

        // When clearing the data selector of groupby transforms, we want to clear
        // all the styles we've added
        if (transform.styles.length && !update[attr]) {
          update['transforms[' + transformIndex + '].styles'] = [];
        }
      }
    }
  }
};

var shamefullyCreateSplitStyleProps = exports.shamefullyCreateSplitStyleProps = function shamefullyCreateSplitStyleProps(graphDiv, attr, traceIndex, splitTraceGroup) {
  if (!Array.isArray(splitTraceGroup)) {
    splitTraceGroup = [splitTraceGroup]; // eslint-disable-line
  }

  var indexOfSplitTransform = null;

  graphDiv.data[traceIndex].transforms.forEach(function (t, i) {
    if (t.type === 'groupby') {
      indexOfSplitTransform = i;
    }
  });

  function getProp(group) {
    var indexOfStyleObject = null;

    graphDiv.data[traceIndex].transforms[indexOfSplitTransform].styles.forEach(function (s, i) {
      if (s.target.toString() === group) {
        indexOfStyleObject = i;
      }
    });

    var path = graphDiv.data[traceIndex].transforms[indexOfSplitTransform].styles[indexOfStyleObject].value;

    attr.split('.').forEach(function (p) {
      if (!path[p]) {
        path[p] = {};
      }
      path = path[p];
    });

    return (0, _nested_property2.default)(graphDiv.data[traceIndex].transforms[indexOfSplitTransform].styles[indexOfStyleObject].value, attr);
  }

  return splitTraceGroup.map(function (g) {
    return getProp(g);
  });
};

var shamefullyDeleteRelatedAnalysisTransforms = exports.shamefullyDeleteRelatedAnalysisTransforms = function shamefullyDeleteRelatedAnalysisTransforms(graphDiv, payload) {
  var parentTraceDataIndex = payload.traceIndexes[0];
  var parentUid = graphDiv.data[parentTraceDataIndex].uid;

  if (parentUid) {
    var relatedAnalysisTraceIndexes = [];
    graphDiv.data.forEach(function (d, i) {
      if (d.transforms && d.transforms.some(function (transform) {
        return ['moving-average', 'fit'].includes(transform.type) && transform.inputUid === parentUid;
      })) {
        relatedAnalysisTraceIndexes.push(i);
      }
    });

    if (relatedAnalysisTraceIndexes.length) {
      relatedAnalysisTraceIndexes.forEach(function (i) {
        graphDiv.data.splice(i, 1);
      });
    }
  }
};

var shamefullyAdjustSizeref = exports.shamefullyAdjustSizeref = function shamefullyAdjustSizeref(gd, _ref6) {
  var update = _ref6.update;
  var _update$markerSize = update['marker.size'],
      size = _update$markerSize === undefined ? null : _update$markerSize,
      _update$markerSizesr = update['marker.sizesrc'],
      src = _update$markerSizesr === undefined ? null : _update$markerSizesr;

  if (size && src) {
    var DEFAULT_MAX_AREA_PX = 45;
    var scaleFactor = DEFAULT_MAX_AREA_PX * DEFAULT_MAX_AREA_PX;
    update['marker.sizeref'] = size.reduce(function (a, b) {
      return Math.max(a, b);
    }) / scaleFactor;
    update['marker.sizemode'] = 'area';
  }
};
//# sourceMappingURL=shame.js.map

/***/ }),

/***/ "2MDZ":
/*!*********************************************************!*\
  !*** ./node_modules/@jupyterlab/csvviewer/lib/index.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__webpack_require__(/*! ../style/index.css */ "ZlA+");
__export(__webpack_require__(/*! ./model */ "EC7n"));
__export(__webpack_require__(/*! ./parse */ "0gkL"));
__export(__webpack_require__(/*! ./toolbar */ "MSdE"));
__export(__webpack_require__(/*! ./widget */ "imJ1"));


/***/ }),

/***/ "2NAh":
/*!********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/NumericInput.js ***!
  \********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DOWN_ARROW = exports.UP_ARROW = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _EditableText = __webpack_require__(/*! ./EditableText */ "Q/qy");

var _EditableText2 = _interopRequireDefault(_EditableText);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _fastIsnumeric = __webpack_require__(/*! fast-isnumeric */ "GbLo");

var _fastIsnumeric2 = _interopRequireDefault(_fastIsnumeric);

var _reactRangeslider = __webpack_require__(/*! react-rangeslider */ "k5hY");

var _reactRangeslider2 = _interopRequireDefault(_reactRangeslider);

var _plotlyIcons = __webpack_require__(/*! plotly-icons */ "hwSx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UP_ARROW = exports.UP_ARROW = 38;
var DOWN_ARROW = exports.DOWN_ARROW = 40;

var NumericInput = function (_Component) {
  _inherits(NumericInput, _Component);

  function NumericInput(props) {
    _classCallCheck(this, NumericInput);

    var _this = _possibleConstructorReturn(this, (NumericInput.__proto__ || Object.getPrototypeOf(NumericInput)).call(this, props));

    _this.state = {
      value: props.value,
      numericInputClassName: _this.getNumericInputClassName(props.value)
    };

    _this.onChange = _this.onChange.bind(_this);
    _this.updateValue = _this.updateValue.bind(_this);
    _this.onKeyDown = _this.onKeyDown.bind(_this);
    _this.onWheel = _this.onWheel.bind(_this);
    return _this;
  }

  _createClass(NumericInput, [{
    key: 'getNumericInputClassName',
    value: function getNumericInputClassName(value) {
      return (0, _fastIsnumeric2.default)(value) || value === '' ? 'numeric-input__number ' + (this.props.editableClassName ? this.props.editableClassName : '') : 'numeric-input__number +error ' + (this.props.editableClassName ? this.props.editableClassName : '');
    }
  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      if (nextProps.value !== this.state.value) {
        this.setState({ value: nextProps.value });
      }
    }
  }, {
    key: 'onKeyDown',
    value: function onKeyDown(e) {
      switch (e.keyCode) {
        case UP_ARROW:
          this.incrementValue('increase');
          break;
        case DOWN_ARROW:
          this.incrementValue('decrease');
          break;
        default:
          break;
      }
    }
  }, {
    key: 'onWheel',
    value: function onWheel(e) {
      e.stopPropagation();
      e.preventDefault();
      if (e.deltaY > 0) {
        this.incrementValue('increase');
      } else {
        this.incrementValue('decrease');
      }
    }
  }, {
    key: 'onChange',
    value: function onChange(value) {
      this.setState({ value: value, numericInputClassName: this.getNumericInputClassName(value) });
    }
  }, {
    key: 'updateValue',
    value: function updateValue(newValue) {
      var _props = this.props,
          max = _props.max,
          min = _props.min,
          integerOnly = _props.integerOnly;

      var updatedValue = newValue;

      if (updatedValue === '') {
        this.setState({
          value: this.props.value,
          numericInputClassName: this.getNumericInputClassName(this.props.value)
        });
        return;
      }

      // When the user blurs on non-numeric data reset the component
      // to the last known good value (this.props.value).
      if (!(0, _fastIsnumeric2.default)(updatedValue)) {
        this.setState({
          value: updatedValue,
          numericInputClassName: this.getNumericInputClassName(updatedValue)
        });
        return;
      }

      updatedValue = Number(updatedValue);
      if (integerOnly) {
        updatedValue = Math.floor(updatedValue);
      }

      if ((0, _fastIsnumeric2.default)(min)) {
        updatedValue = Math.max(min, updatedValue);
      }

      if ((0, _fastIsnumeric2.default)(max)) {
        updatedValue = Math.min(max, updatedValue);
      }

      this.props.onUpdate(updatedValue);
    }
  }, {
    key: 'incrementValue',
    value: function incrementValue(direction) {
      var _props2 = this.props,
          defaultValue = _props2.defaultValue,
          min = _props2.min,
          _props2$step = _props2.step,
          step = _props2$step === undefined ? 1 : _props2$step,
          _props2$stepmode = _props2.stepmode,
          stepmode = _props2$stepmode === undefined ? 'absolute' : _props2$stepmode;
      var value = this.state.value;


      var valueUpdate = void 0;
      if ((0, _fastIsnumeric2.default)(value)) {
        var x = parseFloat(value);
        var absMode = stepmode === 'absolute';
        if (direction === 'increase') {
          valueUpdate = absMode ? x + step : x * (1 + step);
        } else {
          valueUpdate = absMode ? x - step : x / (1 + step);
        }
      } else {
        // if we are multi-valued and the user is incrementing or decrementing
        // update with some sane value so we can "break" out of multi-valued mode.
        if ((0, _fastIsnumeric2.default)(defaultValue)) {
          valueUpdate = defaultValue;
        } else {
          // TODO smarter handling depending if user decrements or increments?
          valueUpdate = min || 0;
        }
      }

      // incrementers blur the line between blur and onChange.
      this.updateValue(valueUpdate);
    }
  }, {
    key: 'renderArrows',
    value: function renderArrows() {
      if (!this.props.showArrows || this.props.showSlider) {
        return null;
      }

      return _react2.default.createElement(
        'div',
        { className: 'numeric-input__caret-box' },
        _react2.default.createElement(
          'div',
          {
            className: 'numeric-input__caret js-numeric-increase',
            onClick: this.incrementValue.bind(this, 'increase')
          },
          _react2.default.createElement(_plotlyIcons.CarretUpIcon, { className: 'numeric-top-caret-modifier' })
        ),
        _react2.default.createElement(
          'div',
          {
            className: 'numeric-input__caret js-numeric-decrease',
            onClick: this.incrementValue.bind(this, 'decrease')
          },
          _react2.default.createElement(_plotlyIcons.CarretDownIcon, { className: 'numeric-bottom-caret-modifier' })
        )
      );
    }
  }, {
    key: 'renderSlider',
    value: function renderSlider() {
      if (!this.props.showSlider) {
        return null;
      }

      return _react2.default.createElement(_reactRangeslider2.default, {
        min: this.props.min,
        max: this.props.max,
        step: this.props.step,
        value: parseFloat(this.state.value),
        onChange: this.updateValue,
        tooltip: false
      });
    }
  }, {
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        'div',
        { className: 'numeric-input__wrapper' },
        _react2.default.createElement(_EditableText2.default, {
          className: this.state.numericInputClassName,
          placeholder: this.props.placeholder,
          text: this.state.value,
          type: 'text',
          onChange: this.onChange,
          onUpdate: this.updateValue,
          onKeyDown: this.onKeyDown,
          onWheel: this.onWheel
        }),
        this.renderArrows(),
        this.renderSlider()
      );
    }
  }]);

  return NumericInput;
}(_react.Component);

exports.default = NumericInput;


NumericInput.propTypes = {
  defaultValue: _propTypes2.default.any,
  editableClassName: _propTypes2.default.string,
  integerOnly: _propTypes2.default.bool,
  max: _propTypes2.default.number,
  min: _propTypes2.default.number,
  onUpdate: _propTypes2.default.func.isRequired,
  placeholder: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]),
  showArrows: _propTypes2.default.bool,
  showSlider: _propTypes2.default.bool,
  step: _propTypes2.default.number,
  stepmode: _propTypes2.default.string,
  value: _propTypes2.default.any
};

NumericInput.defaultProps = {
  showArrows: true
};
//# sourceMappingURL=NumericInput.js.map

/***/ }),

/***/ "2Nb0":
/*!************************************************************!*\
  !*** ./node_modules/core-js/library/fn/symbol/iterator.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(/*! ../../modules/es6.string.iterator */ "FlQf");
__webpack_require__(/*! ../../modules/web.dom.iterable */ "bBy9");
module.exports = __webpack_require__(/*! ../../modules/_wks-ext */ "zLkG").f('iterator');


/***/ }),

/***/ "2Nt0":
/*!********************************************************************!*\
  !*** ./node_modules/readable-stream/node_modules/isarray/index.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

var toString = {}.toString;

module.exports = Array.isArray || function (arr) {
  return toString.call(arr) == '[object Array]';
};


/***/ }),

/***/ "2NuI":
/*!********************************************!*\
  !*** ./node_modules/fbjs/lib/invariant.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */



/**
 * Use invariant() to assert state which your program assumes to be true.
 *
 * Provide sprintf-style format (only %s is supported) and arguments
 * to provide information about what broke and what you were
 * expecting.
 *
 * The invariant message will be stripped in production, but the invariant
 * will remain to ensure logic does not differ in production.
 */

var validateFormat = function validateFormat(format) {};

if (true) {
  validateFormat = function validateFormat(format) {
    if (format === undefined) {
      throw new Error('invariant requires an error message argument');
    }
  };
}

function invariant(condition, format, a, b, c, d, e, f) {
  validateFormat(format);

  if (!condition) {
    var error;
    if (format === undefined) {
      error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
    } else {
      var args = [a, b, c, d, e, f];
      var argIndex = 0;
      error = new Error(format.replace(/%s/g, function () {
        return args[argIndex++];
      }));
      error.name = 'Invariant Violation';
    }

    error.framesToPop = 1; // we don't care about invariant's own frame
    throw error;
  }
}

module.exports = invariant;

/***/ }),

/***/ "2ObX":
/*!*************************************************************!*\
  !*** ./node_modules/@jupyterlab/completer/lib/connector.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const kernelconnector_1 = __webpack_require__(/*! ./kernelconnector */ "k8wc");
const contextconnector_1 = __webpack_require__(/*! ./contextconnector */ "wLZx");
/**
 * A context+kernel connector for completion handlers.
 */
class CompletionConnector extends coreutils_1.DataConnector {
    /**
     * Create a new connector for completion requests.
     *
     * @param options - The instatiation options for the connector.
     */
    constructor(options) {
        super();
        this._kernel = new kernelconnector_1.KernelConnector(options);
        this._context = new contextconnector_1.ContextConnector(options);
    }
    /**
     * Fetch completion requests.
     *
     * @param request - The completion request text and details.
     */
    fetch(request) {
        return Promise.all([
            this._kernel.fetch(request),
            this._context.fetch(request)
        ]).then(([kernelReply, contextReply]) => {
            return Private.mergeReplies(kernelReply, contextReply);
        });
    }
}
exports.CompletionConnector = CompletionConnector;
/**
 * A namespace for private functionality.
 */
var Private;
(function (Private) {
    /**
     * Merge results from kernel and context completions.
     */
    function mergeReplies(kernel, context) {
        // If one is empty, return the other.
        if (kernel.matches.length === 0) {
            return context;
        }
        else if (context.matches.length === 0) {
            return kernel;
        }
        // They both have matches, so merge them, with a preference for the
        // kernel result.
        let matches = kernel.matches.slice();
        context.matches.forEach(match => {
            if (matches.indexOf(match) === -1) {
                matches.push(match);
            }
        });
        return Object.assign({}, kernel, { matches });
    }
    Private.mergeReplies = mergeReplies;
})(Private || (Private = {}));


/***/ }),

/***/ "2R+v":
/*!*********************************************************!*\
  !*** ./node_modules/@phosphor/application/lib/index.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var commands_1 = __webpack_require__(/*! @phosphor/commands */ "5TpB");
var coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
var widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
/**
 * A class for creating pluggable applications.
 *
 * #### Notes
 * The `Application` class is useful when creating large, complex
 * UI applications with the ability to be safely extended by third
 * party code via plugins.
 */
var Application = (function () {
    /**
     * Construct a new application.
     *
     * @param options - The options for creating the application.
     */
    function Application(options) {
        this._started = false;
        this._pluginMap = Private.createPluginMap();
        this._serviceMap = Private.createServiceMap();
        this._delegate = new coreutils_1.PromiseDelegate();
        // Create the application command registry.
        var commands = new commands_1.CommandRegistry();
        // Create the application context menu.
        var renderer = options.contextMenuRenderer;
        var contextMenu = new widgets_1.ContextMenu({ commands: commands, renderer: renderer });
        // Initialize the application state.
        this.commands = commands;
        this.contextMenu = contextMenu;
        this.shell = options.shell;
    }
    Object.defineProperty(Application.prototype, "started", {
        /**
         * A promise which resolves after the application has started.
         *
         * #### Notes
         * This promise will resolve after the `start()` method is called,
         * when all the bootstrapping and shell mounting work is complete.
         */
        get: function () {
            return this._delegate.promise;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Test whether a plugin is registered with the application.
     *
     * @param id - The id of the plugin of interest.
     *
     * @returns `true` if the plugin is registered, `false` otherwise.
     */
    Application.prototype.hasPlugin = function (id) {
        return id in this._pluginMap;
    };
    /**
     * List the IDs of the plugins registered with the application.
     *
     * @returns A new array of the registered plugin IDs.
     */
    Application.prototype.listPlugins = function () {
        return Object.keys(this._pluginMap);
    };
    /**
     * Register a plugin with the application.
     *
     * @param plugin - The plugin to register.
     *
     * #### Notes
     * An error will be thrown if a plugin with the same id is already
     * registered, or if the plugin has a circular dependency.
     *
     * If the plugin provides a service which has already been provided
     * by another plugin, the new service will override the old service.
     */
    Application.prototype.registerPlugin = function (plugin) {
        // Throw an error if the plugin id is already registered.
        if (plugin.id in this._pluginMap) {
            throw new Error("Plugin '" + plugin.id + "' is already registered.");
        }
        // Create the normalized plugin data.
        var data = Private.createPluginData(plugin);
        // Ensure the plugin does not cause a cyclic dependency.
        Private.ensureNoCycle(data, this._pluginMap, this._serviceMap);
        // Add the service token to the service map.
        if (data.provides) {
            this._serviceMap.set(data.provides, data.id);
        }
        // Add the plugin to the plugin map.
        this._pluginMap[data.id] = data;
    };
    /**
     * Register multiple plugins with the application.
     *
     * @param plugins - The plugins to register.
     *
     * #### Notes
     * This calls `registerPlugin()` for each of the given plugins.
     */
    Application.prototype.registerPlugins = function (plugins) {
        for (var _i = 0, plugins_1 = plugins; _i < plugins_1.length; _i++) {
            var plugin = plugins_1[_i];
            this.registerPlugin(plugin);
        }
    };
    /**
     * Activate the plugin with the given id.
     *
     * @param id - The ID of the plugin of interest.
     *
     * @returns A promise which resolves when the plugin is activated
     *   or rejects with an error if it cannot be activated.
     */
    Application.prototype.activatePlugin = function (id) {
        var _this = this;
        // Reject the promise if the plugin is not registered.
        var data = this._pluginMap[id];
        if (!data) {
            return Promise.reject(new Error("Plugin '" + id + "' is not registered."));
        }
        // Resolve immediately if the plugin is already activated.
        if (data.activated) {
            return Promise.resolve(undefined);
        }
        // Return the pending resolver promise if it exists.
        if (data.promise) {
            return data.promise;
        }
        // Resolve the required services for the plugin.
        var required = data.requires.map(function (t) { return _this.resolveRequiredService(t); });
        // Resolve the optional services for the plugin.
        var optional = data.optional.map(function (t) { return _this.resolveOptionalService(t); });
        // Create the array of promises to resolve.
        var promises = required.concat(optional);
        // Setup the resolver promise for the plugin.
        data.promise = Promise.all(promises).then(function (services) {
            return data.activate.apply(undefined, [_this].concat(services));
        }).then(function (service) {
            data.service = service;
            data.activated = true;
            data.promise = null;
        }).catch(function (error) {
            data.promise = null;
            throw error;
        });
        // Return the pending resolver promise.
        return data.promise;
    };
    /**
     * Resolve a required service of a given type.
     *
     * @param token - The token for the service type of interest.
     *
     * @returns A promise which resolves to an instance of the requested
     *   service, or rejects with an error if it cannot be resolved.
     *
     * #### Notes
     * Services are singletons. The same instance will be returned each
     * time a given service token is resolved.
     *
     * If the plugin which provides the service has not been activated,
     * resolving the service will automatically activate the plugin.
     *
     * User code will not typically call this method directly. Instead,
     * the required services for the user's plugins will be resolved
     * automatically when the plugin is activated.
     */
    Application.prototype.resolveRequiredService = function (token) {
        // Reject the promise if there is no provider for the type.
        var id = this._serviceMap.get(token);
        if (!id) {
            return Promise.reject(new Error("No provider for: " + token.name + "."));
        }
        // Resolve immediately if the plugin is already activated.
        var data = this._pluginMap[id];
        if (data.activated) {
            return Promise.resolve(data.service);
        }
        // Otherwise, activate the plugin and wait on the results.
        return this.activatePlugin(id).then(function () { return data.service; });
    };
    /**
     * Resolve an optional service of a given type.
     *
     * @param token - The token for the service type of interest.
     *
     * @returns A promise which resolves to an instance of the requested
     *   service, or `null` if it cannot be resolved.
     *
     * #### Notes
     * Services are singletons. The same instance will be returned each
     * time a given service token is resolved.
     *
     * If the plugin which provides the service has not been activated,
     * resolving the service will automatically activate the plugin.
     *
     * User code will not typically call this method directly. Instead,
     * the optional services for the user's plugins will be resolved
     * automatically when the plugin is activated.
     */
    Application.prototype.resolveOptionalService = function (token) {
        // Resolve with `null` if there is no provider for the type.
        var id = this._serviceMap.get(token);
        if (!id) {
            return Promise.resolve(null);
        }
        // Resolve immediately if the plugin is already activated.
        var data = this._pluginMap[id];
        if (data.activated) {
            return Promise.resolve(data.service);
        }
        // Otherwise, activate the plugin and wait on the results.
        return this.activatePlugin(id).then(function () {
            return data.service;
        }).catch(function (reason) {
            console.error(reason);
            return null;
        });
    };
    /**
     * Start the application.
     *
     * @param options - The options for starting the application.
     *
     * @returns A promise which resolves when all bootstrapping work
     *   is complete and the shell is mounted to the DOM.
     *
     * #### Notes
     * This should be called once by the application creator after all
     * initial plugins have been registered.
     *
     * If a plugin fails to the load, the error will be logged and the
     * other valid plugins will continue to be loaded.
     *
     * Bootstrapping the application consists of the following steps:
     * 1. Activate the startup plugins
     * 2. Wait for those plugins to activate
     * 3. Attach the shell widget to the DOM
     * 4. Add the application event listeners
     */
    Application.prototype.start = function (options) {
        var _this = this;
        if (options === void 0) { options = {}; }
        // Return immediately if the application is already started.
        if (this._started) {
            return this._delegate.promise;
        }
        // Mark the application as started;
        this._started = true;
        // Parse the host id for attaching the shell.
        var hostID = options.hostID || '';
        // Collect the ids of the startup plugins.
        var startups = Private.collectStartupPlugins(this._pluginMap, options);
        // Generate the activation promises.
        var promises = startups.map(function (id) {
            return _this.activatePlugin(id).catch(function (error) {
                console.error("Plugin '" + id + "' failed to activate.");
                console.error(error);
            });
        });
        // Wait for the plugins to activate, then finalize startup.
        Promise.all(promises).then(function () {
            _this.attachShell(hostID);
            _this.addEventListeners();
            _this._delegate.resolve(undefined);
        });
        // Return the pending delegate promise.
        return this._delegate.promise;
    };
    /**
     * Handle the DOM events for the application.
     *
     * @param event - The DOM event sent to the application.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events registered for the application. It
     * should not be called directly by user code.
     */
    Application.prototype.handleEvent = function (event) {
        switch (event.type) {
            case 'resize':
                this.evtResize(event);
                break;
            case 'keydown':
                this.evtKeydown(event);
                break;
            case 'contextmenu':
                this.evtContextMenu(event);
                break;
        }
    };
    /**
     * Attach the application shell to the DOM.
     *
     * @param id - The id of the host node for the shell, or `''`.
     *
     * #### Notes
     * If the id is not provided, the document body will be the host.
     *
     * A subclass may reimplement this method as needed.
     */
    Application.prototype.attachShell = function (id) {
        widgets_1.Widget.attach(this.shell, (id && document.getElementById(id)) || document.body);
    };
    /**
     * Add the application event listeners.
     *
     * #### Notes
     * The default implementation of this method adds listeners for
     * `'keydown'` and `'resize'` events.
     *
     * A subclass may reimplement this method as needed.
     */
    Application.prototype.addEventListeners = function () {
        document.addEventListener('contextmenu', this);
        document.addEventListener('keydown', this, true);
        window.addEventListener('resize', this);
    };
    /**
     * A method invoked on a document `'keydown'` event.
     *
     * #### Notes
     * The default implementation of this method invokes the key down
     * processing method of the application command registry.
     *
     * A subclass may reimplement this method as needed.
     */
    Application.prototype.evtKeydown = function (event) {
        this.commands.processKeydownEvent(event);
    };
    /**
     * A method invoked on a document `'contextmenu'` event.
     *
     * #### Notes
     * The default implementation of this method opens the application
     * `contextMenu` at the current mouse position.
     *
     * If the application context menu has no matching content *or* if
     * the shift key is pressed, the default browser context menu will
     * be opened instead.
     *
     * A subclass may reimplement this method as needed.
     */
    Application.prototype.evtContextMenu = function (event) {
        if (event.shiftKey) {
            return;
        }
        if (this.contextMenu.open(event)) {
            event.preventDefault();
            event.stopPropagation();
        }
    };
    /**
     * A method invoked on a window `'resize'` event.
     *
     * #### Notes
     * The default implementation of this method updates the shell.
     *
     * A subclass may reimplement this method as needed.
     */
    Application.prototype.evtResize = function (event) {
        this.shell.update();
    };
    return Application;
}());
exports.Application = Application;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * Create a new plugin map.
     */
    function createPluginMap() {
        return Object.create(null);
    }
    Private.createPluginMap = createPluginMap;
    /**
     * Create a new service map.
     */
    function createServiceMap() {
        return new Map();
    }
    Private.createServiceMap = createServiceMap;
    /**
     * Create a normalized plugin data object for the given plugin.
     */
    function createPluginData(plugin) {
        return {
            id: plugin.id,
            service: null,
            promise: null,
            activated: false,
            activate: plugin.activate,
            provides: plugin.provides || null,
            autoStart: plugin.autoStart || false,
            requires: plugin.requires ? plugin.requires.slice() : [],
            optional: plugin.optional ? plugin.optional.slice() : []
        };
    }
    Private.createPluginData = createPluginData;
    /**
     * Ensure no cycle is present in the plugin resolution graph.
     *
     * If a cycle is detected, an error will be thrown.
     */
    function ensureNoCycle(data, pluginMap, serviceMap) {
        // Bail early if there cannot be a cycle.
        if (!data.provides || data.requires.length === 0) {
            return;
        }
        // Setup a stack to trace service resolution.
        var trace = [data.id];
        // Throw an exception if a cycle is present.
        if (data.requires.some(visit)) {
            throw new Error("Cycle detected: " + trace.join(' -> ') + ".");
        }
        function visit(token) {
            if (token === data.provides) {
                return true;
            }
            var id = serviceMap.get(token);
            if (!id) {
                return false;
            }
            var other = pluginMap[id];
            if (other.requires.length === 0) {
                return false;
            }
            trace.push(id);
            if (other.requires.some(visit)) {
                return true;
            }
            trace.pop();
            return false;
        }
    }
    Private.ensureNoCycle = ensureNoCycle;
    /**
     * Collect the IDs of the plugins to activate on startup.
     */
    function collectStartupPlugins(pluginMap, options) {
        // Create a map to hold the plugin IDs.
        var resultMap = Object.create(null);
        // Collect the auto-start plugins.
        for (var id in pluginMap) {
            if (pluginMap[id].autoStart) {
                resultMap[id] = true;
            }
        }
        // Add the startup plugins.
        if (options.startPlugins) {
            for (var _i = 0, _a = options.startPlugins; _i < _a.length; _i++) {
                var id = _a[_i];
                resultMap[id] = true;
            }
        }
        // Remove the ignored plugins.
        if (options.ignorePlugins) {
            for (var _b = 0, _c = options.ignorePlugins; _b < _c.length; _b++) {
                var id = _c[_b];
                delete resultMap[id];
            }
        }
        // Return the final startup plugins.
        return Object.keys(resultMap);
    }
    Private.collectStartupPlugins = collectStartupPlugins;
})(Private || (Private = {}));


/***/ }),

/***/ "2Y0J":
/*!****************************************************!*\
  !*** ./node_modules/mdi-react/ShareVariantIcon.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var ShareVariantIcon = function ShareVariantIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M18,16.08C17.24,16.08 16.56,16.38 16.04,16.85L8.91,12.7C8.96,12.47 9,12.24 9,12C9,11.76 8.96,11.53 8.91,11.3L15.96,7.19C16.5,7.69 17.21,8 18,8C19.66,8 21,6.66 21,5C21,3.34 19.66,2 18,2C16.34,2 15,3.34 15,5C15,5.24 15.04,5.47 15.09,5.7L8.04,9.81C7.5,9.31 6.79,9 6,9C4.34,9 3,10.34 3,12C3,13.66 4.34,15 6,15C6.79,15 7.5,14.69 8.04,14.19L15.16,18.34C15.11,18.55 15.08,18.77 15.08,19C15.08,20.61 16.39,21.91 18,21.91C19.61,21.91 20.92,20.61 20.92,19C20.92,17.39 19.61,16.08 18,16.08Z' })
  );
};

module.exports = ShareVariantIcon;


/***/ }),

/***/ "2arF":
/*!***************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@phosphor/widgets/style/splitpanel.css ***!
  \***************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\r\n| Copyright (c) 2014-2017, PhosphorJS Contributors\r\n|\r\n| Distributed under the terms of the BSD 3-Clause License.\r\n|\r\n| The full license is in the file LICENSE, distributed with this software.\r\n|----------------------------------------------------------------------------*/\r\n\r\n\r\n.p-SplitPanel-child {\r\n  z-index: 0;\r\n}\r\n\r\n\r\n.p-SplitPanel-handle {\r\n  z-index: 1;\r\n}\r\n\r\n\r\n.p-SplitPanel-handle.p-mod-hidden {\r\n  display: none !important;\r\n}\r\n\r\n\r\n.p-SplitPanel-handle:after {\r\n  position: absolute;\r\n  top: 0;\r\n  left: 0;\r\n  width: 100%;\r\n  height: 100%;\r\n  content: '';\r\n}\r\n\r\n\r\n.p-SplitPanel[data-orientation='horizontal'] > .p-SplitPanel-handle {\r\n  cursor: ew-resize;\r\n}\r\n\r\n\r\n.p-SplitPanel[data-orientation='vertical'] > .p-SplitPanel-handle {\r\n  cursor: ns-resize;\r\n}\r\n\r\n\r\n.p-SplitPanel[data-orientation='horizontal'] > .p-SplitPanel-handle:after {\r\n  left: 50%;\r\n  min-width: 8px;\r\n  transform: translateX(-50%);\r\n}\r\n\r\n\r\n.p-SplitPanel[data-orientation='vertical'] > .p-SplitPanel-handle:after {\r\n  top: 50%;\r\n  min-height: 8px;\r\n  transform: translateY(-50%);\r\n}\r\n", ""]);

// exports


/***/ }),

/***/ "2faE":
/*!************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_object-dp.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var anObject = __webpack_require__(/*! ./_an-object */ "5K7Z");
var IE8_DOM_DEFINE = __webpack_require__(/*! ./_ie8-dom-define */ "eUtF");
var toPrimitive = __webpack_require__(/*! ./_to-primitive */ "G8Mo");
var dP = Object.defineProperty;

exports.f = __webpack_require__(/*! ./_descriptors */ "jmDH") ? Object.defineProperty : function defineProperty(O, P, Attributes) {
  anObject(O);
  P = toPrimitive(P, true);
  anObject(Attributes);
  if (IE8_DOM_DEFINE) try {
    return dP(O, P, Attributes);
  } catch (e) { /* empty */ }
  if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
  if ('value' in Attributes) O[P] = Attributes.value;
  return O;
};


/***/ }),

/***/ "2fjn":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/fr-ca.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var frCa = moment.defineLocale('fr-ca', {
    months : 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'),
    monthsShort : 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'),
    monthsParseExact : true,
    weekdays : 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),
    weekdaysShort : 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'),
    weekdaysMin : 'di_lu_ma_me_je_ve_sa'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'YYYY-MM-DD',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay : '[Aujourd’hui à] LT',
        nextDay : '[Demain à] LT',
        nextWeek : 'dddd [à] LT',
        lastDay : '[Hier à] LT',
        lastWeek : 'dddd [dernier à] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'dans %s',
        past : 'il y a %s',
        s : 'quelques secondes',
        ss : '%d secondes',
        m : 'une minute',
        mm : '%d minutes',
        h : 'une heure',
        hh : '%d heures',
        d : 'un jour',
        dd : '%d jours',
        M : 'un mois',
        MM : '%d mois',
        y : 'un an',
        yy : '%d ans'
    },
    dayOfMonthOrdinalParse: /\d{1,2}(er|e)/,
    ordinal : function (number, period) {
        switch (period) {
            // Words with masculine grammatical gender: mois, trimestre, jour
            default:
            case 'M':
            case 'Q':
            case 'D':
            case 'DDD':
            case 'd':
                return number + (number === 1 ? 'er' : 'e');

            // Words with feminine grammatical gender: semaine
            case 'w':
            case 'W':
                return number + (number === 1 ? 're' : 'e');
        }
    }
});

return frCa;

})));


/***/ }),

/***/ "2gN3":
/*!********************************************!*\
  !*** ./node_modules/lodash/_coreJsData.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var root = __webpack_require__(/*! ./_root */ "Kz5y");

/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];

module.exports = coreJsData;


/***/ }),

/***/ "2j6C":
/*!***************************************************!*\
  !*** ./node_modules/minimalistic-assert/index.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = assert;

function assert(val, msg) {
  if (!val)
    throw new Error(msg || 'Assertion failed');
}

assert.equal = function assertEqual(l, r, msg) {
  if (l != r)
    throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
};


/***/ }),

/***/ "2jsQ":
/*!***************************************************!*\
  !*** ./node_modules/ajv/lib/dotjs/_limitItems.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate__limitItems(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $op = $keyword == 'maxItems' ? '>' : '<';
  out += 'if ( ';
  if ($isData) {
    out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
  }
  out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { ';
  var $errorKeyword = $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should NOT have ';
      if ($keyword == 'maxItems') {
        out += 'more';
      } else {
        out += 'less';
      }
      out += ' than ';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + ($schema);
      }
      out += ' items\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}


/***/ }),

/***/ "2mcs":
/*!******************************************!*\
  !*** ./node_modules/fbjs/lib/warning.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2014-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */



var emptyFunction = __webpack_require__(/*! ./emptyFunction */ "ohE5");

/**
 * Similar to invariant but only logs a warning if the condition is not met.
 * This can be used to log issues in development environments in critical
 * paths. Removing the logging code for production environments will keep the
 * same logic and follow the same code paths.
 */

var warning = emptyFunction;

if (true) {
  var printWarning = function printWarning(format) {
    for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      args[_key - 1] = arguments[_key];
    }

    var argIndex = 0;
    var message = 'Warning: ' + format.replace(/%s/g, function () {
      return args[argIndex++];
    });
    if (typeof console !== 'undefined') {
      console.error(message);
    }
    try {
      // --- Welcome to debugging React ---
      // This error was thrown as a convenience so that you can use this stack
      // to find the callsite that caused this warning to fire.
      throw new Error(message);
    } catch (x) {}
  };

  warning = function warning(condition, format) {
    if (format === undefined) {
      throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
    }

    if (format.indexOf('Failed Composite propType: ') === 0) {
      return; // Ignore CompositeComponent proptype check.
    }

    if (!condition) {
      for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
        args[_key2 - 2] = arguments[_key2];
      }

      printWarning.apply(undefined, [format].concat(args));
    }
  };
}

module.exports = warning;

/***/ }),

/***/ "2mh1":
/*!************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/Logo.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Logo = function (_Component) {
  _inherits(Logo, _Component);

  function Logo() {
    _classCallCheck(this, Logo);

    return _possibleConstructorReturn(this, (Logo.__proto__ || Object.getPrototypeOf(Logo)).apply(this, arguments));
  }

  _createClass(Logo, [{
    key: 'render',
    value: function render() {
      return _react2.default.createElement('img', { className: 'sidebar__logo', src: this.props.src });
    }
  }]);

  return Logo;
}(_react.Component);

exports.default = Logo;


Logo.plotly_editor_traits = { sidebar_element: true };

Logo.propTypes = {
  src: _propTypes2.default.string
};
//# sourceMappingURL=Logo.js.map

/***/ }),

/***/ "2mql":
/*!**********************************************************************************!*\
  !*** ./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js ***!
  \**********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Copyright 2015, Yahoo! Inc.
 * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
 */
var REACT_STATICS = {
    childContextTypes: true,
    contextTypes: true,
    defaultProps: true,
    displayName: true,
    getDefaultProps: true,
    getDerivedStateFromProps: true,
    mixins: true,
    propTypes: true,
    type: true
};

var KNOWN_STATICS = {
    name: true,
    length: true,
    prototype: true,
    caller: true,
    callee: true,
    arguments: true,
    arity: true
};

var defineProperty = Object.defineProperty;
var getOwnPropertyNames = Object.getOwnPropertyNames;
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var getPrototypeOf = Object.getPrototypeOf;
var objectPrototype = getPrototypeOf && getPrototypeOf(Object);

function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {
    if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components

        if (objectPrototype) {
            var inheritedComponent = getPrototypeOf(sourceComponent);
            if (inheritedComponent && inheritedComponent !== objectPrototype) {
                hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);
            }
        }

        var keys = getOwnPropertyNames(sourceComponent);

        if (getOwnPropertySymbols) {
            keys = keys.concat(getOwnPropertySymbols(sourceComponent));
        }

        for (var i = 0; i < keys.length; ++i) {
            var key = keys[i];
            if (!REACT_STATICS[key] && !KNOWN_STATICS[key] && (!blacklist || !blacklist[key])) {
                var descriptor = getOwnPropertyDescriptor(sourceComponent, key);
                try { // Avoid failures from read-only properties
                    defineProperty(targetComponent, key, descriptor);
                } catch (e) {}
            }
        }

        return targetComponent;
    }

    return targetComponent;
}

module.exports = hoistNonReactStatics;


/***/ }),

/***/ "2q7i":
/*!***************************************!*\
  !*** ./node_modules/stylis/stylis.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/*
 *          __        ___
 *    _____/ /___  __/ (_)____
 *   / ___/ __/ / / / / / ___/
 *  (__  ) /_/ /_/ / / (__  )
 * /____/\__/\__, /_/_/____/
 *          /____/
 *
 * light - weight css preprocessor @licence MIT
 */
(function (factory) {/* eslint-disable */
	 true ? (module['exports'] = factory(null)) :
		undefined
}(/** @param {*=} options */function factory (options) {/* eslint-disable */

	'use strict'

	/**
	 * Notes
	 *
	 * The ['<method name>'] pattern is used to support closure compiler
	 * the jsdoc signatures are also used to the same effect
	 *
	 * ----
	 *
	 * int + int + int === n4 [faster]
	 *
	 * vs
	 *
	 * int === n1 && int === n2 && int === n3
	 *
	 * ----
	 *
	 * switch (int) { case ints...} [faster]
	 *
	 * vs
	 *
	 * if (int == 1 && int === 2 ...)
	 *
	 * ----
	 *
	 * The (first*n1 + second*n2 + third*n3) format used in the property parser
	 * is a simple way to hash the sequence of characters
	 * taking into account the index they occur in
	 * since any number of 3 character sequences could produce duplicates.
	 *
	 * On the other hand sequences that are directly tied to the index of the character
	 * resolve a far more accurate measure, it's also faster
	 * to evaluate one condition in a switch statement
	 * than three in an if statement regardless of the added math.
	 *
	 * This allows the vendor prefixer to be both small and fast.
	 */

	var nullptn = /^\0+/g /* matches leading null characters */
	var formatptn = /[\0\r\f]/g /* matches new line, null and formfeed characters */
	var colonptn = /: */g /* splits animation rules */
	var cursorptn = /zoo|gra/ /* assert cursor varient */
	var transformptn = /([,: ])(transform)/g /* vendor prefix transform, older webkit */
	var animationptn = /,+\s*(?![^(]*[)])/g /* splits multiple shorthand notation animations */
	var propertiesptn = / +\s*(?![^(]*[)])/g /* animation properties */
	var elementptn = / *[\0] */g /* selector elements */
	var selectorptn = /,\r+?/g /* splits selectors */
	var andptn = /([\t\r\n ])*\f?&/g /* match & */
	var escapeptn = /:global\(((?:[^\(\)\[\]]*|\[.*\]|\([^\(\)]*\))*)\)/g /* matches :global(.*) */
	var invalidptn = /\W+/g /* removes invalid characters from keyframes */
	var keyframeptn = /@(k\w+)\s*(\S*)\s*/ /* matches @keyframes $1 */
	var plcholdrptn = /::(place)/g /* match ::placeholder varient */
	var readonlyptn = /:(read-only)/g /* match :read-only varient */
	var beforeptn = /\s+(?=[{\];=:>])/g /* matches \s before ] ; = : */
	var afterptn = /([[}=:>])\s+/g /* matches \s after characters [ } = : */
	var tailptn = /(\{[^{]+?);(?=\})/g /* matches tail semi-colons ;} */
	var whiteptn = /\s{2,}/g /* matches repeating whitespace */
	var pseudoptn = /([^\(])(:+) */g /* pseudo element */
	var writingptn = /[svh]\w+-[tblr]{2}/ /* match writing mode property values */
	var gradientptn = /([\w-]+t\()/g /* match *gradient property */
	var supportsptn = /\(\s*(.*)\s*\)/g /* match supports (groups) */
	var propertyptn = /([\s\S]*?);/g /* match properties leading semicolon */
	var selfptn = /-self|flex-/g /* match flex- and -self in align-self: flex-*; */
	var pseudofmt = /[^]*?(:[rp][el]a[\w-]+)[^]*/ /* extrats :readonly or :placholder from selector */
	var trimptn = /[ \t]+$/ /* match tail whitspace */
	var dimensionptn = /stretch|:\s*\w+\-(?:conte|avail)/ /* match max/min/fit-content, fill-available */
	var imgsrcptn = /([^-])(image-set\()/

	/* vendors */
	var webkit = '-webkit-'
	var moz = '-moz-'
	var ms = '-ms-'

	/* character codes */
	var SEMICOLON = 59 /* ; */
	var CLOSEBRACES = 125 /* } */
	var OPENBRACES = 123 /* { */
	var OPENPARENTHESES = 40 /* ( */
	var CLOSEPARENTHESES = 41 /* ) */
	var OPENBRACKET = 91 /* [ */
	var CLOSEBRACKET = 93 /* ] */
	var NEWLINE = 10 /* \n */
	var CARRIAGE = 13 /* \r */
	var TAB = 9 /* \t */
	var AT = 64 /* @ */
	var SPACE = 32 /*   */
	var AND = 38 /* & */
	var DASH = 45 /* - */
	var UNDERSCORE = 95 /* _ */
	var STAR = 42 /* * */
	var COMMA = 44 /* , */
	var COLON = 58 /* : */
	var SINGLEQUOTE = 39 /* ' */
	var DOUBLEQUOTE = 34 /* " */
	var FOWARDSLASH = 47 /* / */
	var GREATERTHAN = 62 /* > */
	var PLUS = 43 /* + */
	var TILDE = 126 /* ~ */
	var NULL = 0 /* \0 */
	var FORMFEED = 12 /* \f */
	var VERTICALTAB = 11 /* \v */

	/* special identifiers */
	var KEYFRAME = 107 /* k */
	var MEDIA = 109 /* m */
	var SUPPORTS = 115 /* s */
	var PLACEHOLDER = 112 /* p */
	var READONLY = 111 /* o */
	var IMPORT = 105 /* <at>i */
	var CHARSET = 99 /* <at>c */
	var DOCUMENT = 100 /* <at>d */
	var PAGE = 112 /* <at>p */

	var column = 1 /* current column */
	var line = 1 /* current line numebr */
	var pattern = 0 /* :pattern */

	var cascade = 1 /* #id h1 h2 vs h1#id h2#id  */
	var prefix = 1 /* vendor prefix */
	var escape = 1 /* escape :global() pattern */
	var compress = 0 /* compress output */
	var semicolon = 0 /* no/semicolon option */
	var preserve = 0 /* preserve empty selectors */

	/* empty reference */
	var array = []

	/* plugins */
	var plugins = []
	var plugged = 0
	var should = null

	/* plugin context */
	var POSTS = -2
	var PREPS = -1
	var UNKWN = 0
	var PROPS = 1
	var BLCKS = 2
	var ATRUL = 3

	/* plugin newline context */
	var unkwn = 0

	/* keyframe animation */
	var keyed = 1
	var key = ''

	/* selector namespace */
	var nscopealt = ''
	var nscope = ''

	/**
	 * Compile
	 *
	 * @param {Array<string>} parent
	 * @param {Array<string>} current
	 * @param {string} body
	 * @param {number} id
	 * @param {number} depth
	 * @return {string}
	 */
	function compile (parent, current, body, id, depth) {
		var bracket = 0 /* brackets [] */
		var comment = 0 /* comments /* // or /* */
		var parentheses = 0 /* functions () */
		var quote = 0 /* quotes '', "" */

		var first = 0 /* first character code */
		var second = 0 /* second character code */
		var code = 0 /* current character code */
		var tail = 0 /* previous character code */
		var trail = 0 /* character before previous code */
		var peak = 0 /* previous non-whitespace code */

		var counter = 0 /* count sequence termination */
		var context = 0 /* track current context */
		var atrule = 0 /* track @at-rule context */
		var pseudo = 0 /* track pseudo token index */
		var caret = 0 /* current character index */
		var format = 0 /* control character formating context */
		var insert = 0 /* auto semicolon insertion */
		var invert = 0 /* inverted selector pattern */
		var length = 0 /* generic length address */
		var eof = body.length /* end of file(length) */
		var eol = eof - 1 /* end of file(characters) */

		var char = '' /* current character */
		var chars = '' /* current buffer of characters */
		var child = '' /* next buffer of characters */
		var out = '' /* compiled body */
		var children = '' /* compiled children */
		var flat = '' /* compiled leafs */
		var selector /* generic selector address */
		var result /* generic address */

		// ...build body
		while (caret < eof) {
			code = body.charCodeAt(caret)

			// eof varient
			if (caret === eol) {
				// last character + noop context, add synthetic padding for noop context to terminate
				if (comment + quote + parentheses + bracket !== 0) {
					if (comment !== 0) {
						code = comment === FOWARDSLASH ? NEWLINE : FOWARDSLASH
					}

					quote = parentheses = bracket = 0
					eof++
					eol++
				}
			}

			if (comment + quote + parentheses + bracket === 0) {
				// eof varient
				if (caret === eol) {
					if (format > 0) {
						chars = chars.replace(formatptn, '')
					}

					if (chars.trim().length > 0) {
						switch (code) {
							case SPACE:
							case TAB:
							case SEMICOLON:
							case CARRIAGE:
							case NEWLINE: {
								break
							}
							default: {
								chars += body.charAt(caret)
							}
						}

						code = SEMICOLON
					}
				}

				// auto semicolon insertion
				if (insert === 1) {
					switch (code) {
						// false flags
						case OPENBRACES:
						case CLOSEBRACES:
						case SEMICOLON:
						case DOUBLEQUOTE:
						case SINGLEQUOTE:
						case OPENPARENTHESES:
						case CLOSEPARENTHESES:
						case COMMA: {
							insert = 0
						}
						// ignore
						case TAB:
						case CARRIAGE:
						case NEWLINE:
						case SPACE: {
							break
						}
						// valid
						default: {
							insert = 0
							length = caret
							first = code
							caret--
							code = SEMICOLON

							while (length < eof) {
								switch (body.charCodeAt(length++)) {
									case NEWLINE:
									case CARRIAGE:
									case SEMICOLON: {
										++caret
										code = first
										length = eof
										break
									}
									case COLON: {
										if (format > 0) {
											++caret
											code = first
										}
									}
									case OPENBRACES: {
										length = eof
									}
								}
							}
						}
					}
				}

				// token varient
				switch (code) {
					case OPENBRACES: {
						chars = chars.trim()
						first = chars.charCodeAt(0)
						counter = 1
						length = ++caret

						while (caret < eof) {
							switch (code = body.charCodeAt(caret)) {
								case OPENBRACES: {
									counter++
									break
								}
								case CLOSEBRACES: {
									counter--
									break
								}
								case FOWARDSLASH: {
									switch (second = body.charCodeAt(caret + 1)) {
										// /*, //
										case STAR:
										case FOWARDSLASH: {
											caret = delimited(second, caret, eol, body)
										}
									}
									break
								}
								// given "[" === 91 & "]" === 93 hence forth 91 + 1 + 1 === 93
								case OPENBRACKET: {
									code++
								}
								// given "(" === 40 & ")" === 41 hence forth 40 + 1 === 41
								case OPENPARENTHESES: {
									code++
								}
								// quote tail delimiter is identical to the head delimiter hence noop,
								// fallthrough clauses have been shifted to the correct tail delimiter
								case DOUBLEQUOTE:
								case SINGLEQUOTE: {
									while (caret++ < eol) {
										if (body.charCodeAt(caret) === code) {
											break
										}
									}
								}
							}

							if (counter === 0) {
								break
							}

							caret++
						}

						child = body.substring(length, caret)

						if (first === NULL) {
							first = (chars = chars.replace(nullptn, '').trim()).charCodeAt(0)
						}

						switch (first) {
							// @at-rule
							case AT: {
								if (format > 0) {
									chars = chars.replace(formatptn, '')
								}

								second = chars.charCodeAt(1)

								switch (second) {
									case DOCUMENT:
									case MEDIA:
									case SUPPORTS:
									case DASH: {
										selector = current
										break
									}
									default: {
										selector = array
									}
								}

								child = compile(current, selector, child, second, depth+1)
								length = child.length

								// preserve empty @at-rule
								if (preserve > 0 && length === 0) {
									length = chars.length
								}

								// execute plugins, @at-rule context
								if (plugged > 0) {
									selector = select(array, chars, invert)
									result = proxy(ATRUL, child, selector, current, line, column, length, second, depth, id)
									chars = selector.join('')

									if (result !== void 0) {
										if ((length = (child = result.trim()).length) === 0) {
											second = 0
											child = ''
										}
									}
								}

								if (length > 0) {
									switch (second) {
										case SUPPORTS: {
											chars = chars.replace(supportsptn, supports)
										}
										case DOCUMENT:
										case MEDIA:
										case DASH: {
											child = chars + '{' + child + '}'
											break
										}
										case KEYFRAME: {
											chars = chars.replace(keyframeptn, '$1 $2' + (keyed > 0 ? key : ''))
											child = chars + '{' + child + '}'

											if (prefix === 1 || (prefix === 2 && vendor('@'+child, 3))) {
												child = '@' + webkit + child + '@' + child
											} else {
												child = '@' + child
											}
											break
										}
										default: {
											child = chars + child

											if (id === PAGE) {
												child = (out += child, '')
											}
										}
									}
								} else {
									child = ''
								}

								break
							}
							// selector
							default: {
								child = compile(current, select(current, chars, invert), child, id, depth+1)
							}
						}

						children += child

						// reset
						context = 0
						insert = 0
						pseudo = 0
						format = 0
						invert = 0
						atrule = 0
						chars = ''
						child = ''
						code = body.charCodeAt(++caret)
						break
					}
					case CLOSEBRACES:
					case SEMICOLON: {
						chars = (format > 0 ? chars.replace(formatptn, '') : chars).trim()

						if ((length = chars.length) > 1) {
							// monkey-patch missing colon
							if (pseudo === 0) {
								first = chars.charCodeAt(0)

								// first character is a letter or dash, buffer has a space character
								if ((first === DASH || first > 96 && first < 123)) {
									length = (chars = chars.replace(' ', ':')).length
								}
							}

							// execute plugins, property context
							if (plugged > 0) {
								if ((result = proxy(PROPS, chars, current, parent, line, column, out.length, id, depth, id)) !== void 0) {
									if ((length = (chars = result.trim()).length) === 0) {
										chars = '\0\0'
									}
								}
							}

							first = chars.charCodeAt(0)
							second = chars.charCodeAt(1)

							switch (first) {
								case NULL: {
									break
								}
								case AT: {
									if (second === IMPORT || second === CHARSET) {
										flat += chars + body.charAt(caret)
										break
									}
								}
								default: {
									if (chars.charCodeAt(length-1) === COLON) {
										break
									}

									out += property(chars, first, second, chars.charCodeAt(2))
								}
							}
						}

						// reset
						context = 0
						insert = 0
						pseudo = 0
						format = 0
						invert = 0
						chars = ''
						code = body.charCodeAt(++caret)
						break
					}
				}
			}

			// parse characters
			switch (code) {
				case CARRIAGE:
				case NEWLINE: {
					// auto insert semicolon
					if (comment + quote + parentheses + bracket + semicolon === 0) {
						// valid non-whitespace characters that
						// may precede a newline
						switch (peak) {
							case CLOSEPARENTHESES:
							case SINGLEQUOTE:
							case DOUBLEQUOTE:
							case AT:
							case TILDE:
							case GREATERTHAN:
							case STAR:
							case PLUS:
							case FOWARDSLASH:
							case DASH:
							case COLON:
							case COMMA:
							case SEMICOLON:
							case OPENBRACES:
							case CLOSEBRACES: {
								break
							}
							default: {
								// current buffer has a colon
								if (pseudo > 0) {
									insert = 1
								}
							}
						}
					}

					// terminate line comment
					if (comment === FOWARDSLASH) {
						comment = 0
					} else if (cascade + context === 0 && id !== KEYFRAME && chars.length > 0) {
						format = 1
						chars += '\0'
					}

					// execute plugins, newline context
					if (plugged * unkwn > 0) {
						proxy(UNKWN, chars, current, parent, line, column, out.length, id, depth, id)
					}

					// next line, reset column position
					column = 1
					line++
					break
				}
				case SEMICOLON:
				case CLOSEBRACES: {
					if (comment + quote + parentheses + bracket === 0) {
						column++
						break
					}
				}
				default: {
					// increment column position
					column++

					// current character
					char = body.charAt(caret)

					// remove comments, escape functions, strings, attributes and prepare selectors
					switch (code) {
						case TAB:
						case SPACE: {
							if (quote + bracket + comment === 0) {
								switch (tail) {
									case COMMA:
									case COLON:
									case TAB:
									case SPACE: {
										char = ''
										break
									}
									default: {
										if (code !== SPACE) {
											char = ' '
										}
									}
								}
							}
							break
						}
						// escape breaking control characters
						case NULL: {
							char = '\\0'
							break
						}
						case FORMFEED: {
							char = '\\f'
							break
						}
						case VERTICALTAB: {
							char = '\\v'
							break
						}
						// &
						case AND: {
							// inverted selector pattern i.e html &
							if (quote + comment + bracket === 0 && cascade > 0) {
								invert = 1
								format = 1
								char = '\f' + char
							}
							break
						}
						// ::p<l>aceholder, l
						// :read-on<l>y, l
						case 108: {
							if (quote + comment + bracket + pattern === 0 && pseudo > 0) {
								switch (caret - pseudo) {
									// ::placeholder
									case 2: {
										if (tail === PLACEHOLDER && body.charCodeAt(caret-3) === COLON) {
											pattern = tail
										}
									}
									// :read-only
									case 8: {
										if (trail === READONLY) {
											pattern = trail
										}
									}
								}
							}
							break
						}
						// :<pattern>
						case COLON: {
							if (quote + comment + bracket === 0) {
								pseudo = caret
							}
							break
						}
						// selectors
						case COMMA: {
							if (comment + parentheses + quote + bracket === 0) {
								format = 1
								char += '\r'
							}
							break
						}
						// quotes
						case DOUBLEQUOTE:
						case SINGLEQUOTE: {
							if (comment === 0) {
								quote = quote === code ? 0 : (quote === 0 ? code : quote)
							}
							break
						}
						// attributes
						case OPENBRACKET: {
							if (quote + comment + parentheses === 0) {
								bracket++
							}
							break
						}
						case CLOSEBRACKET: {
							if (quote + comment + parentheses === 0) {
								bracket--
							}
							break
						}
						// functions
						case CLOSEPARENTHESES: {
							if (quote + comment + bracket === 0) {
								parentheses--
							}
							break
						}
						case OPENPARENTHESES: {
							if (quote + comment + bracket === 0) {
								if (context === 0) {
									switch (tail*2 + trail*3) {
										// :matches
										case 533: {
											break
										}
										// :global, :not, :nth-child etc...
										default: {
											counter = 0
											context = 1
										}
									}
								}

								parentheses++
							}
							break
						}
						case AT: {
							if (comment + parentheses + quote + bracket + pseudo + atrule === 0) {
								atrule = 1
							}
							break
						}
						// block/line comments
						case STAR:
						case FOWARDSLASH: {
							if (quote + bracket + parentheses > 0) {
								break
							}

							switch (comment) {
								// initialize line/block comment context
								case 0: {
									switch (code*2 + body.charCodeAt(caret+1)*3) {
										// //
										case 235: {
											comment = FOWARDSLASH
											break
										}
										// /*
										case 220: {
											length = caret
											comment = STAR
											break
										}
									}
									break
								}
								// end block comment context
								case STAR: {
									if (code === FOWARDSLASH && tail === STAR && length + 2 !== caret) {
										// /*<!> ... */, !
										if (body.charCodeAt(length+2) === 33) {
											out += body.substring(length, caret+1)
										}
										char = ''
										comment = 0
									}
								}
							}
						}
					}

					// ignore comment blocks
					if (comment === 0) {
						// aggressive isolation mode, divide each individual selector
						// including selectors in :not function but excluding selectors in :global function
						if (cascade + quote + bracket + atrule === 0 && id !== KEYFRAME && code !== SEMICOLON) {
							switch (code) {
								case COMMA:
								case TILDE:
								case GREATERTHAN:
								case PLUS:
								case CLOSEPARENTHESES:
								case OPENPARENTHESES: {
									if (context === 0) {
										// outside of an isolated context i.e nth-child(<...>)
										switch (tail) {
											case TAB:
											case SPACE:
											case NEWLINE:
											case CARRIAGE: {
												char = char + '\0'
												break
											}
											default: {
												char = '\0' + char + (code === COMMA ? '' : '\0')
											}
										}
										format = 1
									} else {
										// within an isolated context, sleep untill it's terminated
										switch (code) {
											case OPENPARENTHESES: {
												// :globa<l>(
												if (pseudo + 7 === caret && tail === 108) {
													pseudo = 0
												}
												context = ++counter
												break
											}
											case CLOSEPARENTHESES: {
												if ((context = --counter) === 0) {
													format = 1
													char += '\0'
												}
												break
											}
										}
									}
									break
								}
								case TAB:
								case SPACE: {
									switch (tail) {
										case NULL:
										case OPENBRACES:
										case CLOSEBRACES:
										case SEMICOLON:
										case COMMA:
										case FORMFEED:
										case TAB:
										case SPACE:
										case NEWLINE:
										case CARRIAGE: {
											break
										}
										default: {
											// ignore in isolated contexts
											if (context === 0) {
												format = 1
												char += '\0'
											}
										}
									}
								}
							}
						}

						// concat buffer of characters
						chars += char

						// previous non-whitespace character code
						if (code !== SPACE && code !== TAB) {
							peak = code
						}
					}
				}
			}

			// tail character codes
			trail = tail
			tail = code

			// visit every character
			caret++
		}

		length = out.length

		// preserve empty selector
 		if (preserve > 0) {
 			if (length === 0 && children.length === 0 && (current[0].length === 0) === false) {
 				if (id !== MEDIA || (current.length === 1 && (cascade > 0 ? nscopealt : nscope) === current[0])) {
					length = current.join(',').length + 2
 				}
 			}
		}

		if (length > 0) {
			// cascade isolation mode?
			selector = cascade === 0 && id !== KEYFRAME ? isolate(current) : current

			// execute plugins, block context
			if (plugged > 0) {
				result = proxy(BLCKS, out, selector, parent, line, column, length, id, depth, id)

				if (result !== void 0 && (out = result).length === 0) {
					return flat + out + children
				}
			}

			out = selector.join(',') + '{' + out + '}'

			if (prefix*pattern !== 0) {
				if (prefix === 2 && !vendor(out, 2))
					pattern = 0

				switch (pattern) {
					// ::read-only
					case READONLY: {
						out = out.replace(readonlyptn, ':'+moz+'$1')+out
						break
					}
					// ::placeholder
					case PLACEHOLDER: {
						out = (
							out.replace(plcholdrptn, '::' + webkit + 'input-$1') +
							out.replace(plcholdrptn, '::' + moz + '$1') +
							out.replace(plcholdrptn, ':' + ms + 'input-$1') + out
						)
						break
					}
				}

				pattern = 0
			}
		}

		return flat + out + children
	}

	/**
	 * Select
	 *
	 * @param {Array<string>} parent
	 * @param {string} current
	 * @param {number} invert
	 * @return {Array<string>}
	 */
	function select (parent, current, invert) {
		var selectors = current.trim().split(selectorptn)
		var out = selectors

		var length = selectors.length
		var l = parent.length

		switch (l) {
			// 0-1 parent selectors
			case 0:
			case 1: {
				for (var i = 0, selector = l === 0 ? '' : parent[0] + ' '; i < length; ++i) {
					out[i] = scope(selector, out[i], invert, l).trim()
				}
				break
			}
			// >2 parent selectors, nested
			default: {
				for (var i = 0, j = 0, out = []; i < length; ++i) {
					for (var k = 0; k < l; ++k) {
						out[j++] = scope(parent[k] + ' ', selectors[i], invert, l).trim()
					}
				}
			}
		}

		return out
	}

	/**
	 * Scope
	 *
	 * @param {string} parent
	 * @param {string} current
	 * @param {number} invert
	 * @param {number} level
	 * @return {string}
	 */
	function scope (parent, current, invert, level) {
		var selector = current
		var code = selector.charCodeAt(0)

		// trim leading whitespace
		if (code < 33) {
			code = (selector = selector.trim()).charCodeAt(0)
		}

		switch (code) {
			// &
			case AND: {
				switch (cascade + level) {
					case 0:
					case 1: {
						if (parent.trim().length === 0) {
							break
						}
					}
					default: {
						return selector.replace(andptn, '$1'+parent.trim())
					}
				}
				break
			}
			// :
			case COLON: {
				switch (selector.charCodeAt(1)) {
					// g in :global
					case 103: {
						if (escape > 0 && cascade > 0) {
							return selector.replace(escapeptn, '$1').replace(andptn, '$1'+nscope)
						}
						break
					}
					default: {
						// :hover
						return parent.trim() + selector.replace(andptn, '$1'+parent.trim())
					}
				}
			}
			default: {
				// html &
				if (invert*cascade > 0 && selector.indexOf('\f') > 0) {
					return selector.replace(andptn, (parent.charCodeAt(0) === COLON ? '' : '$1')+parent.trim())
				}
			}
		}

		return parent + selector
	}

	/**
	 * Property
	 *
	 * @param {string} input
	 * @param {number} first
	 * @param {number} second
	 * @param {number} third
	 * @return {string}
	 */
	function property (input, first, second, third) {
		var index = 0
		var out = input + ';'
		var hash = (first*2) + (second*3) + (third*4)
		var cache

		// animation: a, n, i characters
		if (hash === 944) {
			return animation(out)
		} else if (prefix === 0 || (prefix === 2 && !vendor(out, 1))) {
			return out
		}

		// vendor prefix
		switch (hash) {
			// text-decoration/text-size-adjust/text-shadow/text-align/text-transform: t, e, x
			case 1015: {
				// text-shadow/text-align/text-transform, a
				return out.charCodeAt(10) === 97 ? webkit + out + out : out
			}
			// filter/fill f, i, l
			case 951: {
				// filter, t
				return out.charCodeAt(3) === 116 ? webkit + out + out : out
			}
			// color/column, c, o, l
			case 963: {
				// column, n
				return out.charCodeAt(5) === 110 ? webkit + out + out : out
			}
			// box-decoration-break, b, o, x
			case 1009: {
				if (out.charCodeAt(4) !== 100) {
					break
				}
			}
			// mask, m, a, s
			// clip-path, c, l, i
			case 969:
			case 942: {
				return webkit + out + out
			}
			// appearance: a, p, p
			case 978: {
				return webkit + out + moz + out + out
			}
			// hyphens: h, y, p
			// user-select: u, s, e
			case 1019:
			case 983: {
				return webkit + out + moz + out + ms + out + out
			}
			// background/backface-visibility, b, a, c
			case 883: {
				// backface-visibility, -
				if (out.charCodeAt(8) === DASH) {
					return webkit + out + out
				}

				// image-set(...)
				if (out.indexOf('image-set(', 11) > 0) {
					return out.replace(imgsrcptn, '$1'+webkit+'$2') + out
				}

				return out
			}
			// flex: f, l, e
			case 932: {
				if (out.charCodeAt(4) === DASH) {
					switch (out.charCodeAt(5)) {
						// flex-grow, g
						case 103: {
							return webkit + 'box-' + out.replace('-grow', '') + webkit + out + ms + out.replace('grow', 'positive') + out
						}
						// flex-shrink, s
						case 115: {
							return webkit + out + ms + out.replace('shrink', 'negative') + out
						}
						// flex-basis, b
						case 98: {
							return webkit + out + ms + out.replace('basis', 'preferred-size') + out
						}
					}
				}

				return webkit + out + ms + out + out
			}
			// order: o, r, d
			case 964: {
				return webkit + out + ms + 'flex' + '-' + out + out
			}
			// justify-items/justify-content, j, u, s
			case 1023: {
				// justify-content, c
				if (out.charCodeAt(8) !== 99) {
					break
				}

				cache = out.substring(out.indexOf(':', 15)).replace('flex-', '').replace('space-between', 'justify')
				return webkit + 'box-pack' + cache + webkit + out + ms + 'flex-pack' + cache + out
			}
			// cursor, c, u, r
			case 1005: {
				return cursorptn.test(out) ? out.replace(colonptn, ':' + webkit) + out.replace(colonptn, ':' + moz) + out : out
			}
			// writing-mode, w, r, i
			case 1000: {
				cache = out.substring(13).trim()
				index = cache.indexOf('-') + 1

				switch (cache.charCodeAt(0)+cache.charCodeAt(index)) {
					// vertical-lr
					case 226: {
						cache = out.replace(writingptn, 'tb')
						break
					}
					// vertical-rl
					case 232: {
						cache = out.replace(writingptn, 'tb-rl')
						break
					}
					// horizontal-tb
					case 220: {
						cache = out.replace(writingptn, 'lr')
						break
					}
					default: {
						return out
					}
				}

				return webkit + out + ms + cache + out
			}
			// position: sticky
			case 1017: {
				if (out.indexOf('sticky', 9) === -1) {
					return out
				}
			}
			// display(flex/inline-flex/inline-box): d, i, s
			case 975: {
				index = (out = input).length - 10
				cache = (out.charCodeAt(index) === 33 ? out.substring(0, index) : out).substring(input.indexOf(':', 7) + 1).trim()

				switch (hash = cache.charCodeAt(0) + (cache.charCodeAt(7)|0)) {
					// inline-
					case 203: {
						// inline-box
						if (cache.charCodeAt(8) < 111) {
							break
						}
					}
					// inline-box/sticky
					case 115: {
						out = out.replace(cache, webkit+cache)+';'+out
						break
					}
					// inline-flex
					// flex
					case 207:
					case 102: {
						out = (
							out.replace(cache, webkit+(hash > 102 ? 'inline-' : '')+'box')+';'+
							out.replace(cache, webkit+cache)+';'+
							out.replace(cache, ms+cache+'box')+';'+
							out
						)
					}
				}

				return out + ';'
			}
			// align-items, align-center, align-self: a, l, i, -
			case 938: {
				if (out.charCodeAt(5) === DASH) {
					switch (out.charCodeAt(6)) {
						// align-items, i
						case 105: {
							cache = out.replace('-items', '')
							return webkit + out + webkit + 'box-' + cache + ms + 'flex-' + cache + out
						}
						// align-self, s
						case 115: {
							return webkit + out + ms + 'flex-item-' + out.replace(selfptn, '') + out
						}
						// align-content
						default: {
							return webkit + out + ms + 'flex-line-pack' + out.replace('align-content', '').replace(selfptn, '') + out
						}
					}
				}
				break
			}
			// min/max
			case 973:
			case 989: {
				// min-/max- height/width/block-size/inline-size
				if (out.charCodeAt(3) !== DASH || out.charCodeAt(4) === 122) {
					break
				}
			}
			// height/width: min-content / width: max-content
			case 931:
			case 953: {
				if (dimensionptn.test(input) === true) {
					// stretch
					if ((cache = input.substring(input.indexOf(':') + 1)).charCodeAt(0) === 115)
						return property(input.replace('stretch', 'fill-available'), first, second, third).replace(':fill-available', ':stretch')
					else
						return out.replace(cache, webkit + cache) + out.replace(cache, moz + cache.replace('fill-', '')) + out
				}
				break
			}
			// transform, transition: t, r, a
			case 962: {
				out = webkit + out + (out.charCodeAt(5) === 102 ? ms + out : '') + out

				// transitions
				if (second + third === 211 && out.charCodeAt(13) === 105 && out.indexOf('transform', 10) > 0) {
					return out.substring(0, out.indexOf(';', 27) + 1).replace(transformptn, '$1' + webkit + '$2') + out
				}

				break
			}
		}

		return out
	}

	/**
	 * Vendor
	 *
	 * @param {string} content
	 * @param {number} context
	 * @return {boolean}
	 */
	function vendor (content, context) {
		var index = content.indexOf(context === 1 ? ':' : '{')
		var key = content.substring(0, context !== 3 ? index : 10)
		var value = content.substring(index + 1, content.length - 1)

		return should(context !== 2 ? key : key.replace(pseudofmt, '$1'), value, context)
	}

	/**
	 * Supports
	 *
	 * @param {string} match
	 * @param {string} group
	 * @return {string}
	 */
	function supports (match, group) {
		var out = property(group, group.charCodeAt(0), group.charCodeAt(1), group.charCodeAt(2))

		return out !== group+';' ? out.replace(propertyptn, ' or ($1)').substring(4) : '('+group+')'
	}

	/**
	 * Animation
	 *
	 * @param {string} input
	 * @return {string}
	 */
	function animation (input) {
		var length = input.length
		var index = input.indexOf(':', 9) + 1
		var declare = input.substring(0, index).trim()
		var out = input.substring(index, length-1).trim()

		switch (input.charCodeAt(9)*keyed) {
			case 0: {
				break
			}
			// animation-*, -
			case DASH: {
				// animation-name, n
				if (input.charCodeAt(10) !== 110) {
					break
				}
			}
			// animation/animation-name
			default: {
				// split in case of multiple animations
				var list = out.split((out = '', animationptn))

				for (var i = 0, index = 0, length = list.length; i < length; index = 0, ++i) {
					var value = list[i]
					var items = value.split(propertiesptn)

					while (value = items[index]) {
						var peak = value.charCodeAt(0)

						if (keyed === 1 && (
							// letters
							(peak > AT && peak < 90) || (peak > 96 && peak < 123) || peak === UNDERSCORE ||
							// dash but not in sequence i.e --
							(peak === DASH && value.charCodeAt(1) !== DASH)
						)) {
							// not a number/function
							switch (isNaN(parseFloat(value)) + (value.indexOf('(') !== -1)) {
								case 1: {
									switch (value) {
										// not a valid reserved keyword
										case 'infinite': case 'alternate': case 'backwards': case 'running':
										case 'normal': case 'forwards': case 'both': case 'none': case 'linear':
										case 'ease': case 'ease-in': case 'ease-out': case 'ease-in-out':
										case 'paused': case 'reverse': case 'alternate-reverse': case 'inherit':
										case 'initial': case 'unset': case 'step-start': case 'step-end': {
											break
										}
										default: {
											value += key
										}
									}
								}
							}
						}

						items[index++] = value
					}

					out += (i === 0 ? '' : ',') + items.join(' ')
				}
			}
		}

		out = declare + out + ';'

		if (prefix === 1 || (prefix === 2 && vendor(out, 1)))
			return webkit + out + out

		return out
	}

	/**
	 * Isolate
	 *
	 * @param {Array<string>} current
	 */
	function isolate (current) {
		for (var i = 0, length = current.length, selector = Array(length), padding, element; i < length; ++i) {
			// split individual elements in a selector i.e h1 h2 === [h1, h2]
			var elements = current[i].split(elementptn)
			var out = ''

			for (var j = 0, size = 0, tail = 0, code = 0, l = elements.length; j < l; ++j) {
				// empty element
				if ((size = (element = elements[j]).length) === 0 && l > 1) {
					continue
				}

				tail = out.charCodeAt(out.length-1)
				code = element.charCodeAt(0)
				padding = ''

				if (j !== 0) {
					// determine if we need padding
					switch (tail) {
						case STAR:
						case TILDE:
						case GREATERTHAN:
						case PLUS:
						case SPACE:
						case OPENPARENTHESES:  {
							break
						}
						default: {
							padding = ' '
						}
					}
				}

				switch (code) {
					case AND: {
						element = padding + nscopealt
					}
					case TILDE:
					case GREATERTHAN:
					case PLUS:
					case SPACE:
					case CLOSEPARENTHESES:
					case OPENPARENTHESES: {
						break
					}
					case OPENBRACKET: {
						element = padding + element + nscopealt
						break
					}
					case COLON: {
						switch (element.charCodeAt(1)*2 + element.charCodeAt(2)*3) {
							// :global
							case 530: {
								if (escape > 0) {
									element = padding + element.substring(8, size - 1)
									break
								}
							}
							// :hover, :nth-child(), ...
							default: {
								if (j < 1 || elements[j-1].length < 1) {
									element = padding + nscopealt + element
								}
							}
						}
						break
					}
					case COMMA: {
						padding = ''
					}
					default: {
						if (size > 1 && element.indexOf(':') > 0) {
							element = padding + element.replace(pseudoptn, '$1' + nscopealt + '$2')
						} else {
							element = padding + element + nscopealt
						}
					}
				}

				out += element
			}

			selector[i] = out.replace(formatptn, '').trim()
		}

		return selector
	}

	/**
	 * Proxy
	 *
	 * @param {number} context
	 * @param {string} content
	 * @param {Array<string>} selectors
	 * @param {Array<string>} parents
	 * @param {number} line
	 * @param {number} column
	 * @param {number} length
	 * @param {number} id
	 * @param {number} depth
	 * @param {number} at
	 * @return {(string|void|*)}
	 */
	function proxy (context, content, selectors, parents, line, column, length, id, depth, at) {
		for (var i = 0, out = content, next; i < plugged; ++i) {
			switch (next = plugins[i].call(stylis, context, out, selectors, parents, line, column, length, id, depth, at)) {
				case void 0:
				case false:
				case true:
				case null: {
					break
				}
				default: {
					out = next
				}
			}
		}
		if (out !== content) {
		  return out
		}
	}

	/**
	 * @param {number} code
	 * @param {number} index
	 * @param {number} length
	 * @param {string} body
	 * @return {number}
	 */
	function delimited (code, index, length, body) {
		for (var i = index + 1; i < length; ++i) {
			switch (body.charCodeAt(i)) {
				// /*
				case FOWARDSLASH: {
					if (code === STAR) {
						if (body.charCodeAt(i - 1) === STAR &&  index + 2 !== i) {
							return i + 1
						}
					}
					break
				}
				// //
				case NEWLINE: {
					if (code === FOWARDSLASH) {
						return i + 1
					}
				}
			}
		}

		return i
	}

	/**
	 * @param {number} type
	 * @param {number} index
	 * @param {number} length
	 * @param {number} find
	 * @param {string} body
	 * @return {number}
	 */
	function match (type, index, length, body) {
		for (var i = index + 1; i < length; ++i) {
			switch (body.charCodeAt(i)) {
				case type: {
					return i
				}
			}
		}

		return i
	}

	/**
	 * Minify
	 *
	 * @param {(string|*)} output
	 * @return {string}
	 */
	function minify (output) {
		return output
			.replace(formatptn, '')
			.replace(beforeptn, '')
			.replace(afterptn, '$1')
			.replace(tailptn, '$1')
			.replace(whiteptn, ' ')
	}

	/**
	 * Use
	 *
	 * @param {(Array<function(...?)>|function(...?)|number|void)?} plugin
	 */
	function use (plugin) {
		switch (plugin) {
			case void 0:
			case null: {
				plugged = plugins.length = 0
				break
			}
			default: {
				if (typeof plugin === 'function') {
					plugins[plugged++] = plugin
				}	else if (typeof plugin === 'object') {
					for (var i = 0, length = plugin.length; i < length; ++i) {
						use(plugin[i])
					}
				} else {
					unkwn = !!plugin|0
				}
			}
 		}

 		return use
	}

	/**
	 * Set
	 *
	 * @param {*} options
	 */
	function set (options) {
		for (var name in options) {
			var value = options[name]
			switch (name) {
				case 'keyframe': keyed = value|0; break
				case 'global': escape = value|0; break
				case 'cascade': cascade = value|0; break
				case 'compress': compress = value|0; break
				case 'semicolon': semicolon = value|0; break
				case 'preserve': preserve = value|0; break
				case 'prefix':
					should = null

					if (!value) {
						prefix = 0
					} else if (typeof value !== 'function') {
						prefix = 1
					} else {
						prefix = 2
						should = value
					}
			}
		}

		return set
	}

	/**
	 * Stylis
	 *
	 * @param {string} selector
	 * @param {string} input
	 * @return {*}
	 */
	function stylis (selector, input) {
		if (this !== void 0 && this.constructor === stylis) {
			return factory(selector)
		}

		// setup
		var ns = selector
		var code = ns.charCodeAt(0)

		// trim leading whitespace
		if (code < 33) {
			code = (ns = ns.trim()).charCodeAt(0)
		}

		// keyframe/animation namespace
		if (keyed > 0) {
			key = ns.replace(invalidptn, code === OPENBRACKET ? '' : '-')
		}

		// reset, used to assert if a plugin is moneky-patching the return value
		code = 1

		// cascade/isolate
		if (cascade === 1) {
			nscope = ns
		} else {
			nscopealt = ns
		}

		var selectors = [nscope]
		var result

		// execute plugins, pre-process context
		if (plugged > 0) {
			result = proxy(PREPS, input, selectors, selectors, line, column, 0, 0, 0, 0)

			if (result !== void 0 && typeof result === 'string') {
				input = result
			}
		}

		// build
		var output = compile(array, selectors, input, 0, 0)

		// execute plugins, post-process context
		if (plugged > 0) {
			result = proxy(POSTS, output, selectors, selectors, line, column, output.length, 0, 0, 0)

			// bypass minification
			if (result !== void 0 && typeof(output = result) !== 'string') {
				code = 0
			}
		}

		// reset
		key = ''
		nscope = ''
		nscopealt = ''
		pattern = 0
		line = 1
		column = 1

		return compress*code === 0 ? output : minify(output)
	}

	stylis['use'] = use
	stylis['set'] = set

	if (options !== void 0) {
		set(options)
	}

	return stylis
}));


/***/ }),

/***/ "2uPQ":
/*!***********************************************!*\
  !*** ./node_modules/ajv/lib/patternGroups.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var META_SCHEMA_ID = 'http://json-schema.org/draft-06/schema';

module.exports = function (ajv) {
  var defaultMeta = ajv._opts.defaultMeta;
  var metaSchemaRef = typeof defaultMeta == 'string'
                      ? { $ref: defaultMeta }
                      : ajv.getSchema(META_SCHEMA_ID)
                        ? { $ref: META_SCHEMA_ID }
                        : {};

  ajv.addKeyword('patternGroups', {
    // implemented in properties.jst
    metaSchema: {
      type: 'object',
      additionalProperties: {
        type: 'object',
        required: [ 'schema' ],
        properties: {
          maximum: {
            type: 'integer',
            minimum: 0
          },
          minimum: {
            type: 'integer',
            minimum: 0
          },
          schema: metaSchemaRef
        },
        additionalProperties: false
      }
    }
  });
  ajv.RULES.all.properties.implements.push('patternGroups');
};


/***/ }),

/***/ "2va9":
/*!**************************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/plot_api/plot_config.js ***!
  \**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



/**
 * This will be transferred over to gd and overridden by
 * config args to Plotly.plot.
 *
 * The defaults are the appropriate settings for plotly.js,
 * so we get the right experience without any config argument.
 *
 * N.B. the config options are not coerced using Lib.coerce so keys
 * like `valType` and `values` are only set for documentation purposes
 * at the moment.
 */

var configAttributes = {
    staticPlot: {
        valType: 'boolean',
        dflt: false,
        description: [
            'Determines whether the graphs are interactive or not.',
            'If *false*, no interactivity, for export or image generation.'
        ].join(' ')
    },

    plotlyServerURL: {
        valType: 'string',
        dflt: 'https://plot.ly',
        description: [
            'Sets base URL for the \'Edit in Chart Studio\' (aka sendDataToCloud) mode bar button',
            'and the showLink/sendData on-graph link'
        ].join(' ')
    },

    editable: {
        valType: 'boolean',
        dflt: false,
        description: [
            'Determines whether the graph is editable or not.',
            'Sets all pieces of `edits`',
            'unless a separate `edits` config item overrides individual parts.'
        ].join(' ')
    },
    edits: {
        annotationPosition: {
            valType: 'boolean',
            dflt: false,
            description: [
                'Determines if the main anchor of the annotation is editable.',
                'The main anchor corresponds to the',
                'text (if no arrow) or the arrow (which drags the whole thing leaving',
                'the arrow length & direction unchanged).'
            ].join(' ')
        },
        annotationTail: {
            valType: 'boolean',
            dflt: false,
            description: [
                'Has only an effect for annotations with arrows.',
                'Enables changing the length and direction of the arrow.'
            ].join(' ')
        },
        annotationText: {
            valType: 'boolean',
            dflt: false,
            description: 'Enables editing annotation text.'
        },
        axisTitleText: {
            valType: 'boolean',
            dflt: false,
            description: 'Enables editing axis title text.'
        },
        colorbarPosition: {
            valType: 'boolean',
            dflt: false,
            description: 'Enables moving colorbars.'
        },
        colorbarTitleText: {
            valType: 'boolean',
            dflt: false,
            description: 'Enables editing colorbar title text.'
        },
        legendPosition: {
            valType: 'boolean',
            dflt: false,
            description: 'Enables moving the legend.'
        },
        legendText: {
            valType: 'boolean',
            dflt: false,
            description: 'Enables editing the trace name fields from the legend'
        },
        shapePosition: {
            valType: 'boolean',
            dflt: false,
            description: 'Enables moving shapes.'
        },
        titleText: {
            valType: 'boolean',
            dflt: false,
            description: 'Enables editing the global layout title.'
        }
    },

    autosizable: {
        valType: 'boolean',
        dflt: false,
        description: [
            'Determines whether the graphs are plotted with respect to',
            'layout.autosize:true and infer its container size.'
        ].join(' ')
    },
    responsive: {
        valType: 'boolean',
        dflt: false,
        description: [
            'Determines whether to change the layout size when window is resized.',
            'In v2, this option will be removed and will always be true.'
        ].join(' ')
    },
    fillFrame: {
        valType: 'boolean',
        dflt: false,
        description: [
            'When `layout.autosize` is turned on, determines whether the graph',
            'fills the container (the default) or the screen (if set to *true*).'
        ].join(' ')
    },
    frameMargins: {
        valType: 'number',
        dflt: 0,
        min: 0,
        max: 0.5,
        description: [
            'When `layout.autosize` is turned on, set the frame margins',
            'in fraction of the graph size.'
        ].join(' ')
    },

    scrollZoom: {
        valType: 'flaglist',
        flags: ['cartesian', 'gl3d', 'geo', 'mapbox'],
        extras: [true, false],
        dflt: 'gl3d+geo+mapbox',
        description: [
            'Determines whether mouse wheel or two-finger scroll zooms is enable.',
            'Turned on by default for gl3d, geo and mapbox subplots',
            '(as these subplot types do not have zoombox via pan),',
            'but turned off by default for cartesian subplots.',
            'Set `scrollZoom` to *false* to disable scrolling for all subplots.'
        ].join(' ')
    },
    doubleClick: {
        valType: 'enumerated',
        values: [false, 'reset', 'autosize', 'reset+autosize'],
        dflt: 'reset+autosize',
        description: [
            'Sets the double click interaction mode.',
            'Has an effect only in cartesian plots.',
            'If *false*, double click is disable.',
            'If *reset*, double click resets the axis ranges to their initial values.',
            'If *autosize*, double click set the axis ranges to their autorange values.',
            'If *reset+autosize*, the odd double clicks resets the axis ranges',
            'to their initial values and even double clicks set the axis ranges',
            'to their autorange values.'
        ].join(' ')
    },

    showAxisDragHandles: {
        valType: 'boolean',
        dflt: true,
        description: [
            'Set to *false* to omit cartesian axis pan/zoom drag handles.'
        ].join(' ')
    },
    showAxisRangeEntryBoxes: {
        valType: 'boolean',
        dflt: true,
        description: [
            'Set to *false* to omit direct range entry at the pan/zoom drag points,',
            'note that `showAxisDragHandles` must be enabled to have an effect.'
        ].join(' ')
    },

    showTips: {
        valType: 'boolean',
        dflt: true,
        description: [
            'Determines whether or not tips are shown while interacting',
            'with the resulting graphs.'
        ].join(' ')
    },

    showLink: {
        valType: 'boolean',
        dflt: false,
        description: [
            'Determines whether a link to plot.ly is displayed',
            'at the bottom right corner of resulting graphs.',
            'Use with `sendData` and `linkText`.'
        ].join(' ')
    },
    linkText: {
        valType: 'string',
        dflt: 'Edit chart',
        noBlank: true,
        description: [
            'Sets the text appearing in the `showLink` link.'
        ].join(' ')
    },
    sendData: {
        valType: 'boolean',
        dflt: true,
        description: [
            'If *showLink* is true, does it contain data',
            'just link to a plot.ly file?'
        ].join(' ')
    },
    showSources: {
        valType: 'any',
        dflt: false,
        description: [
            'Adds a source-displaying function to show sources on',
            'the resulting graphs.'
        ].join(' ')
    },

    displayModeBar: {
        valType: 'enumerated',
        values: ['hover', true, false],
        dflt: 'hover',
        description: [
            'Determines the mode bar display mode.',
            'If *true*, the mode bar is always visible.',
            'If *false*, the mode bar is always hidden.',
            'If *hover*, the mode bar is visible while the mouse cursor',
            'is on the graph container.'
        ].join(' ')
    },
    showSendToCloud: {
        valType: 'boolean',
        dflt: false,
        description: [
            'Should we include a ModeBar button, labeled "Edit in Chart Studio",',
            'that sends this chart to plot.ly or another plotly server as specified',
            'by `plotlyServerURL` for editing, export, etc? Prior to version 1.43.0',
            'this button was included by default, now it is opt-in using this flag.',
            'Note that this button can (depending on `plotlyServerURL`) send your data',
            'to an external server. However that server does not persist your data',
            'until you arrive at the Chart Studio and explicitly click "Save".'
        ].join(' ')
    },
    modeBarButtonsToRemove: {
        valType: 'any',
        dflt: [],
        description: [
            'Remove mode bar buttons by name.',
            'See ./components/modebar/buttons.js for the list of names.'
        ].join(' ')
    },
    modeBarButtonsToAdd: {
        valType: 'any',
        dflt: [],
        description: [
            'Add mode bar button using config objects',
            'See ./components/modebar/buttons.js for list of arguments.'
        ].join(' ')
    },
    modeBarButtons: {
        valType: 'any',
        dflt: false,
        description: [
            'Define fully custom mode bar buttons as nested array,',
            'where the outer arrays represents button groups, and',
            'the inner arrays have buttons config objects or names of default buttons',
            'See ./components/modebar/buttons.js for more info.'
        ].join(' ')
    },
    toImageButtonOptions: {
        valType: 'any',
        dflt: {},
        description: [
            'Statically override options for toImage modebar button',
            'allowed keys are format, filename, width, height, scale',
            'see ../components/modebar/buttons.js'
        ].join(' ')
    },
    displaylogo: {
        valType: 'boolean',
        dflt: true,
        description: [
            'Determines whether or not the plotly logo is displayed',
            'on the end of the mode bar.'
        ].join(' ')
    },
    watermark: {
        valType: 'boolean',
        dflt: false,
        description: 'watermark the images with the company\'s logo'
    },

    plotGlPixelRatio: {
        valType: 'number',
        dflt: 2,
        min: 1,
        max: 4,
        description: [
            'Set the pixel ratio during WebGL image export.',
            'This config option was formerly named `plot3dPixelRatio`',
            'which is now deprecated.'
        ].join(' ')
    },

    setBackground: {
        valType: 'any',
        dflt: 'transparent',
        description: [
            'Set function to add the background color (i.e. `layout.paper_color`)',
            'to a different container.',
            'This function take the graph div as first argument and the current background',
            'color as second argument.',
            'Alternatively, set to string *opaque* to ensure there is white behind it.'
        ].join(' ')
    },

    topojsonURL: {
        valType: 'string',
        noBlank: true,
        dflt: 'https://cdn.plot.ly/',
        description: [
            'Set the URL to topojson used in geo charts.',
            'By default, the topojson files are fetched from cdn.plot.ly.',
            'For example, set this option to:',
            '<path-to-plotly.js>/dist/topojson/',
            'to render geographical feature using the topojson files',
            'that ship with the plotly.js module.'
        ].join(' ')
    },

    mapboxAccessToken: {
        valType: 'string',
        dflt: null,
        description: [
            'Mapbox access token (required to plot mapbox trace types)',
            'If using an Mapbox Atlas server, set this option to \'\'',
            'so that plotly.js won\'t attempt to authenticate to the public Mapbox server.'
        ].join(' ')
    },

    logging: {
        valType: 'boolean',
        dflt: 1,
        description: [
            'Turn all console logging on or off (errors will be thrown)',
            'This should ONLY be set via Plotly.setPlotConfig',
            'Available levels:',
            '0: no logs',
            '1: warnings and errors, but not informational messages',
            '2: verbose logs'
        ].join(' ')
    },

    queueLength: {
        valType: 'integer',
        min: 0,
        dflt: 0,
        description: 'Sets the length of the undo/redo queue.'
    },

    globalTransforms: {
        valType: 'any',
        dflt: [],
        description: [
            'Set global transform to be applied to all traces with no',
            'specification needed'
        ].join(' ')
    },

    locale: {
        valType: 'string',
        dflt: 'en-US',
        description: [
            'Which localization should we use?',
            'Should be a string like \'en\' or \'en-US\'.'
        ].join(' ')
    },

    locales: {
        valType: 'any',
        dflt: {},
        description: [
            'Localization definitions',
            'Locales can be provided either here (specific to one chart) or globally',
            'by registering them as modules.',
            'Should be an object of objects {locale: {dictionary: {...}, format: {...}}}',
            '{',
            '  da: {',
            '      dictionary: {\'Reset axes\': \'Nulstil aksler\', ...},',
            '      format: {months: [...], shortMonths: [...]}',
            '  },',
            '  ...',
            '}',
            'All parts are optional. When looking for translation or format fields, we',
            'look first for an exact match in a config locale, then in a registered',
            'module. If those fail, we strip off any regionalization (\'en-US\' -> \'en\')',
            'and try each (config, registry) again. The final fallback for translation',
            'is untranslated (which is US English) and for formats is the base English',
            '(the only consequence being the last fallback date format %x is DD/MM/YYYY',
            'instead of MM/DD/YYYY). Currently `grouping` and `currency` are ignored',
            'for our automatic number formatting, but can be used in custom formats.'
        ].join(' ')
    }
};

var dfltConfig = {};

function crawl(src, target) {
    for(var k in src) {
        var obj = src[k];
        if(obj.valType) {
            target[k] = obj.dflt;
        } else {
            if(!target[k]) {
                target[k] = {};
            }
            crawl(obj, target[k]);
        }
    }
}

crawl(configAttributes, dfltConfig);

module.exports = {
    configAttributes: configAttributes,
    dfltConfig: dfltConfig
};


/***/ }),

/***/ "2wu2":
/*!************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyter-widgets/base/css/index.css ***!
  \************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/* Copyright (c) Jupyter Development Team.\n * Distributed under the terms of the Modified BSD License.\n */\n\n .jupyter-widgets-disconnected::before {\n    content: \"\\F127\"; /* chain-broken */\n    display: inline-block;\n    font: normal normal normal 14px/1 FontAwesome;\n    font-size: inherit;\n    text-rendering: auto;\n    -webkit-font-smoothing: antialiased;\n    -moz-osx-font-smoothing: grayscale;\n    color: #d9534f;\n    padding: 3px;\n    align-self: flex-start;\n}\n", ""]);

// exports


/***/ }),

/***/ "2yMk":
/*!**********************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/plots/attributes.js ***!
  \**********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var fxAttrs = __webpack_require__(/*! ../components/fx/attributes */ "pX04");

module.exports = {
    type: {
        valType: 'enumerated',
        role: 'info',
        values: [],     // listed dynamically
        dflt: 'scatter',
        editType: 'calc+clearAxisTypes',
        _noTemplating: true // we handle this at a higher level
    },
    visible: {
        valType: 'enumerated',
        values: [true, false, 'legendonly'],
        role: 'info',
        dflt: true,
        editType: 'calc',
        description: [
            'Determines whether or not this trace is visible.',
            'If *legendonly*, the trace is not drawn,',
            'but can appear as a legend item',
            '(provided that the legend itself is visible).'
        ].join(' ')
    },
    showlegend: {
        valType: 'boolean',
        role: 'info',
        dflt: true,
        editType: 'style',
        description: [
            'Determines whether or not an item corresponding to this',
            'trace is shown in the legend.'
        ].join(' ')
    },
    legendgroup: {
        valType: 'string',
        role: 'info',
        dflt: '',
        editType: 'style',
        description: [
            'Sets the legend group for this trace.',
            'Traces part of the same legend group hide/show at the same time',
            'when toggling legend items.'
        ].join(' ')
    },
    opacity: {
        valType: 'number',
        role: 'style',
        min: 0,
        max: 1,
        dflt: 1,
        editType: 'style',
        description: 'Sets the opacity of the trace.'
    },
    name: {
        valType: 'string',
        role: 'info',
        editType: 'style',
        description: [
            'Sets the trace name.',
            'The trace name appear as the legend item and on hover.'
        ].join(' ')
    },
    uid: {
        valType: 'string',
        role: 'info',
        editType: 'plot',
        anim: true,
        description: [
            'Assign an id to this trace,',
            'Use this to provide object constancy between traces during animations',
            'and transitions.'
        ].join(' ')
    },
    ids: {
        valType: 'data_array',
        editType: 'calc',
        anim: true,
        description: [
            'Assigns id labels to each datum.',
            'These ids for object constancy of data points during animation.',
            'Should be an array of strings, not numbers or any other type.'
        ].join(' ')
    },
    customdata: {
        valType: 'data_array',
        editType: 'calc',
        description: [
            'Assigns extra data each datum.',
            'This may be useful when listening to hover, click and selection events.',
            'Note that, *scatter* traces also appends customdata items in the markers',
            'DOM elements'
        ].join(' ')
    },

    // N.B. these cannot be 'data_array' as they do not have the same length as
    // other data arrays and arrayOk attributes in general
    //
    // Maybe add another valType:
    // https://github.com/plotly/plotly.js/issues/1894
    selectedpoints: {
        valType: 'any',
        role: 'info',
        editType: 'calc',
        description: [
            'Array containing integer indices of selected points.',
            'Has an effect only for traces that support selections.',
            'Note that an empty array means an empty selection where the `unselected`',
            'are turned on for all points, whereas, any other non-array values means no',
            'selection all where the `selected` and `unselected` styles have no effect.'
        ].join(' ')
    },

    hoverinfo: {
        valType: 'flaglist',
        role: 'info',
        flags: ['x', 'y', 'z', 'text', 'name'],
        extras: ['all', 'none', 'skip'],
        arrayOk: true,
        dflt: 'all',
        editType: 'none',
        description: [
            'Determines which trace information appear on hover.',
            'If `none` or `skip` are set, no information is displayed upon hovering.',
            'But, if `none` is set, click and hover events are still fired.'
        ].join(' ')
    },
    hoverlabel: fxAttrs.hoverlabel,
    stream: {
        token: {
            valType: 'string',
            noBlank: true,
            strict: true,
            role: 'info',
            editType: 'calc',
            description: [
                'The stream id number links a data trace on a plot with a stream.',
                'See https://plot.ly/settings for more details.'
            ].join(' ')
        },
        maxpoints: {
            valType: 'number',
            min: 0,
            max: 10000,
            dflt: 500,
            role: 'info',
            editType: 'calc',
            description: [
                'Sets the maximum number of points to keep on the plots from an',
                'incoming stream.',
                'If `maxpoints` is set to *50*, only the newest 50 points will',
                'be displayed on the plot.'
            ].join(' ')
        },
        editType: 'calc'
    },
    transforms: {
        _isLinkedToArray: 'transform',
        editType: 'calc',
        description: [
            'An array of operations that manipulate the trace data,',
            'for example filtering or sorting the data arrays.'
        ].join(' ')
    },
    uirevision: {
        valType: 'any',
        role: 'info',
        editType: 'none',
        description: [
            'Controls persistence of some user-driven changes to the trace:',
            '`constraintrange` in `parcoords` traces, as well as some',
            '`editable: true` modifications such as `name` and `colorbar.title`.',
            'Defaults to `layout.uirevision`.',
            'Note that other user-driven trace attribute changes are controlled',
            'by `layout` attributes:',
            '`trace.visible` is controlled by `layout.legend.uirevision`,',
            '`selectedpoints` is controlled by `layout.selectionrevision`,',
            'and `colorbar.(x|y)` (accessible with `config: {editable: true}`)',
            'is controlled by `layout.editrevision`.',
            'Trace changes are tracked by `uid`, which only falls back on trace',
            'index if no `uid` is provided. So if your app can add/remove traces',
            'before the end of the `data` array, such that the same trace has a',
            'different index, you can still preserve user-driven changes if you',
            'give each trace a `uid` that stays with it as it moves.'
        ].join(' ')
    }
};


/***/ }),

/***/ "2ykv":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/nl-be.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var monthsShortWithDots = 'jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.'.split('_'),
    monthsShortWithoutDots = 'jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec'.split('_');

var monthsParse = [/^jan/i, /^feb/i, /^maart|mrt.?$/i, /^apr/i, /^mei$/i, /^jun[i.]?$/i, /^jul[i.]?$/i, /^aug/i, /^sep/i, /^okt/i, /^nov/i, /^dec/i];
var monthsRegex = /^(januari|februari|maart|april|mei|april|ju[nl]i|augustus|september|oktober|november|december|jan\.?|feb\.?|mrt\.?|apr\.?|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i;

var nlBe = moment.defineLocale('nl-be', {
    months : 'januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december'.split('_'),
    monthsShort : function (m, format) {
        if (!m) {
            return monthsShortWithDots;
        } else if (/-MMM-/.test(format)) {
            return monthsShortWithoutDots[m.month()];
        } else {
            return monthsShortWithDots[m.month()];
        }
    },

    monthsRegex: monthsRegex,
    monthsShortRegex: monthsRegex,
    monthsStrictRegex: /^(januari|februari|maart|mei|ju[nl]i|april|augustus|september|oktober|november|december)/i,
    monthsShortStrictRegex: /^(jan\.?|feb\.?|mrt\.?|apr\.?|mei|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i,

    monthsParse : monthsParse,
    longMonthsParse : monthsParse,
    shortMonthsParse : monthsParse,

    weekdays : 'zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag'.split('_'),
    weekdaysShort : 'zo._ma._di._wo._do._vr._za.'.split('_'),
    weekdaysMin : 'zo_ma_di_wo_do_vr_za'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay: '[vandaag om] LT',
        nextDay: '[morgen om] LT',
        nextWeek: 'dddd [om] LT',
        lastDay: '[gisteren om] LT',
        lastWeek: '[afgelopen] dddd [om] LT',
        sameElse: 'L'
    },
    relativeTime : {
        future : 'over %s',
        past : '%s geleden',
        s : 'een paar seconden',
        ss : '%d seconden',
        m : 'één minuut',
        mm : '%d minuten',
        h : 'één uur',
        hh : '%d uur',
        d : 'één dag',
        dd : '%d dagen',
        M : 'één maand',
        MM : '%d maanden',
        y : 'één jaar',
        yy : '%d jaar'
    },
    dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/,
    ordinal : function (number) {
        return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de');
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return nlBe;

})));


/***/ }),

/***/ "2zpl":
/*!********************************************************************************!*\
  !*** ./node_modules/react-color/lib/components/photoshop/PhotoshopPreviews.js ***!
  \********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.PhotoshopPreviews = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PhotoshopPreviews = exports.PhotoshopPreviews = function PhotoshopPreviews(_ref) {
  var rgb = _ref.rgb,
      currentColor = _ref.currentColor;

  var styles = (0, _reactcss2.default)({
    'default': {
      swatches: {
        border: '1px solid #B3B3B3',
        borderBottom: '1px solid #F0F0F0',
        marginBottom: '2px',
        marginTop: '1px'
      },
      new: {
        height: '34px',
        background: 'rgb(' + rgb.r + ',' + rgb.g + ', ' + rgb.b + ')',
        boxShadow: 'inset 1px 0 0 #000, inset -1px 0 0 #000, inset 0 1px 0 #000'
      },
      current: {
        height: '34px',
        background: currentColor,
        boxShadow: 'inset 1px 0 0 #000, inset -1px 0 0 #000, inset 0 -1px 0 #000'
      },
      label: {
        fontSize: '14px',
        color: '#000',
        textAlign: 'center'
      }
    }
  });

  return _react2.default.createElement(
    'div',
    null,
    _react2.default.createElement(
      'div',
      { style: styles.label },
      'new'
    ),
    _react2.default.createElement(
      'div',
      { style: styles.swatches },
      _react2.default.createElement('div', { style: styles.new }),
      _react2.default.createElement('div', { style: styles.current })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.label },
      'current'
    )
  );
};

exports.default = PhotoshopPreviews;

/***/ }),

/***/ "3+mF":
/*!************************************************************!*\
  !*** ./node_modules/xterm/lib/renderer/LinkRenderLayer.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Types_1 = __webpack_require__(/*! ../Types */ "Ltj7");
var BaseRenderLayer_1 = __webpack_require__(/*! ./BaseRenderLayer */ "HHOg");
var LinkRenderLayer = (function (_super) {
    __extends(LinkRenderLayer, _super);
    function LinkRenderLayer(container, zIndex, colors, terminal) {
        var _this = _super.call(this, container, 'link', zIndex, true, colors) || this;
        _this._state = null;
        terminal.linkifier.on(Types_1.LinkHoverEventTypes.HOVER, function (e) { return _this._onLinkHover(e); });
        terminal.linkifier.on(Types_1.LinkHoverEventTypes.LEAVE, function (e) { return _this._onLinkLeave(e); });
        return _this;
    }
    LinkRenderLayer.prototype.resize = function (terminal, dim) {
        _super.prototype.resize.call(this, terminal, dim);
        this._state = null;
    };
    LinkRenderLayer.prototype.reset = function (terminal) {
        this._clearCurrentLink();
    };
    LinkRenderLayer.prototype._clearCurrentLink = function () {
        if (this._state) {
            this.clearCells(this._state.x1, this._state.y1, this._state.cols - this._state.x1, 1);
            var middleRowCount = this._state.y2 - this._state.y1 - 1;
            if (middleRowCount > 0) {
                this.clearCells(0, this._state.y1 + 1, this._state.cols, middleRowCount);
            }
            this.clearCells(0, this._state.y2, this._state.x2, 1);
            this._state = null;
        }
    };
    LinkRenderLayer.prototype._onLinkHover = function (e) {
        this._ctx.fillStyle = this._colors.foreground.css;
        if (e.y1 === e.y2) {
            this.fillBottomLineAtCells(e.x1, e.y1, e.x2 - e.x1);
        }
        else {
            this.fillBottomLineAtCells(e.x1, e.y1, e.cols - e.x1);
            for (var y = e.y1 + 1; y < e.y2; y++) {
                this.fillBottomLineAtCells(0, y, e.cols);
            }
            this.fillBottomLineAtCells(0, e.y2, e.x2);
        }
        this._state = e;
    };
    LinkRenderLayer.prototype._onLinkLeave = function (e) {
        this._clearCurrentLink();
    };
    return LinkRenderLayer;
}(BaseRenderLayer_1.BaseRenderLayer));
exports.LinkRenderLayer = LinkRenderLayer;

//# sourceMappingURL=LinkRenderLayer.js.map


/***/ }),

/***/ "31N0":
/*!*******************************************************************!*\
  !*** ./node_modules/@jupyterlab/csvviewer-extension/lib/index.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const application_1 = __webpack_require__(/*! @jupyterlab/application */ "FkFl");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const csvviewer_1 = __webpack_require__(/*! @jupyterlab/csvviewer */ "2MDZ");
const datagrid_1 = __webpack_require__(/*! @phosphor/datagrid */ "Dblc");
/**
 * The name of the factories that creates widgets.
 */
const FACTORY_CSV = 'CSVTable';
const FACTORY_TSV = 'TSVTable';
/**
 * The CSV file handler extension.
 */
const csv = {
    activate: activateCsv,
    id: '@jupyterlab/csvviewer-extension:csv',
    requires: [application_1.ILayoutRestorer, apputils_1.IThemeManager],
    autoStart: true
};
/**
 * The TSV file handler extension.
 */
const tsv = {
    activate: activateTsv,
    id: '@jupyterlab/csvviewer-extension:tsv',
    requires: [application_1.ILayoutRestorer, apputils_1.IThemeManager],
    autoStart: true
};
/**
 * Activate cssviewer extension for CSV files
 */
function activateCsv(app, restorer, themeManager) {
    const factory = new csvviewer_1.CSVViewerFactory({
        name: FACTORY_CSV,
        fileTypes: ['csv'],
        defaultFor: ['csv'],
        readOnly: true
    });
    const tracker = new apputils_1.InstanceTracker({
        namespace: 'csvviewer'
    });
    // The current styles for the data grids.
    let style = Private.LIGHT_STYLE;
    let renderer = Private.LIGHT_RENDERER;
    // Handle state restoration.
    restorer.restore(tracker, {
        command: 'docmanager:open',
        args: widget => ({ path: widget.context.path, factory: FACTORY_CSV }),
        name: widget => widget.context.path
    });
    app.docRegistry.addWidgetFactory(factory);
    let ft = app.docRegistry.getFileType('csv');
    factory.widgetCreated.connect((sender, widget) => {
        // Track the widget.
        tracker.add(widget);
        // Notify the instance tracker if restore data needs to update.
        widget.context.pathChanged.connect(() => {
            tracker.save(widget);
        });
        if (ft) {
            widget.title.iconClass = ft.iconClass;
            widget.title.iconLabel = ft.iconLabel;
        }
        // Set the theme for the new widget.
        widget.content.style = style;
        widget.content.renderer = renderer;
    });
    // Keep the themes up-to-date.
    const updateThemes = () => {
        const isLight = themeManager.isLight(themeManager.theme);
        style = isLight ? Private.LIGHT_STYLE : Private.DARK_STYLE;
        renderer = isLight ? Private.LIGHT_RENDERER : Private.DARK_RENDERER;
        tracker.forEach(grid => {
            grid.content.style = style;
            grid.content.renderer = renderer;
        });
    };
    themeManager.themeChanged.connect(updateThemes);
}
/**
 * Activate cssviewer extension for TSV files
 */
function activateTsv(app, restorer, themeManager) {
    const factory = new csvviewer_1.TSVViewerFactory({
        name: FACTORY_TSV,
        fileTypes: ['tsv'],
        defaultFor: ['tsv'],
        readOnly: true
    });
    const tracker = new apputils_1.InstanceTracker({
        namespace: 'tsvviewer'
    });
    // The current styles for the data grids.
    let style = Private.LIGHT_STYLE;
    let renderer = Private.LIGHT_RENDERER;
    // Handle state restoration.
    restorer.restore(tracker, {
        command: 'docmanager:open',
        args: widget => ({ path: widget.context.path, factory: FACTORY_TSV }),
        name: widget => widget.context.path
    });
    app.docRegistry.addWidgetFactory(factory);
    let ft = app.docRegistry.getFileType('tsv');
    factory.widgetCreated.connect((sender, widget) => {
        // Track the widget.
        tracker.add(widget);
        // Notify the instance tracker if restore data needs to update.
        widget.context.pathChanged.connect(() => {
            tracker.save(widget);
        });
        if (ft) {
            widget.title.iconClass = ft.iconClass;
            widget.title.iconLabel = ft.iconLabel;
        }
        // Set the theme for the new widget.
        widget.content.style = style;
        widget.content.renderer = renderer;
    });
    // Keep the themes up-to-date.
    const updateThemes = () => {
        const isLight = themeManager.isLight(themeManager.theme);
        style = isLight ? Private.LIGHT_STYLE : Private.DARK_STYLE;
        renderer = isLight ? Private.LIGHT_RENDERER : Private.DARK_RENDERER;
        tracker.forEach(grid => {
            grid.content.style = style;
            grid.content.renderer = renderer;
        });
    };
    themeManager.themeChanged.connect(updateThemes);
}
/**
 * Export the plugins as default.
 */
const plugins = [csv, tsv];
exports.default = plugins;
/**
 * A namespace for private data.
 */
var Private;
(function (Private) {
    /**
     * The light theme for the data grid.
     */
    Private.LIGHT_STYLE = Object.assign({}, datagrid_1.DataGrid.defaultStyle, { voidColor: '#F3F3F3', backgroundColor: 'white', headerBackgroundColor: '#EEEEEE', gridLineColor: 'rgba(20, 20, 20, 0.15)', headerGridLineColor: 'rgba(20, 20, 20, 0.25)', rowBackgroundColor: i => (i % 2 === 0 ? '#F5F5F5' : 'white') });
    /**
     * The dark theme for the data grid.
     */
    Private.DARK_STYLE = {
        voidColor: 'black',
        backgroundColor: '#111111',
        headerBackgroundColor: '#424242',
        gridLineColor: 'rgba(235, 235, 235, 0.15)',
        headerGridLineColor: 'rgba(235, 235, 235, 0.25)',
        rowBackgroundColor: i => (i % 2 === 0 ? '#212121' : '#111111')
    };
    /**
     * The light renderer for the data grid.
     */
    Private.LIGHT_RENDERER = new datagrid_1.TextRenderer({
        textColor: '#111111',
        horizontalAlignment: 'right'
    });
    /**
     * The dark renderer for the data grid.
     */
    Private.DARK_RENDERER = new datagrid_1.TextRenderer({
        textColor: '#F5F5F5',
        horizontalAlignment: 'right'
    });
})(Private || (Private = {}));


/***/ }),

/***/ "33yf":
/*!***********************************************!*\
  !*** ./node_modules/path-browserify/index.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors.
//
// 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.

// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
  // if the path tries to go above the root, `up` ends up > 0
  var up = 0;
  for (var i = parts.length - 1; i >= 0; i--) {
    var last = parts[i];
    if (last === '.') {
      parts.splice(i, 1);
    } else if (last === '..') {
      parts.splice(i, 1);
      up++;
    } else if (up) {
      parts.splice(i, 1);
      up--;
    }
  }

  // if the path is allowed to go above the root, restore leading ..s
  if (allowAboveRoot) {
    for (; up--; up) {
      parts.unshift('..');
    }
  }

  return parts;
}

// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe =
    /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var splitPath = function(filename) {
  return splitPathRe.exec(filename).slice(1);
};

// path.resolve([from ...], to)
// posix version
exports.resolve = function() {
  var resolvedPath = '',
      resolvedAbsolute = false;

  for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    var path = (i >= 0) ? arguments[i] : process.cwd();

    // Skip empty and invalid entries
    if (typeof path !== 'string') {
      throw new TypeError('Arguments to path.resolve must be strings');
    } else if (!path) {
      continue;
    }

    resolvedPath = path + '/' + resolvedPath;
    resolvedAbsolute = path.charAt(0) === '/';
  }

  // At this point the path should be resolved to a full absolute path, but
  // handle relative paths to be safe (might happen when process.cwd() fails)

  // Normalize the path
  resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
    return !!p;
  }), !resolvedAbsolute).join('/');

  return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};

// path.normalize(path)
// posix version
exports.normalize = function(path) {
  var isAbsolute = exports.isAbsolute(path),
      trailingSlash = substr(path, -1) === '/';

  // Normalize the path
  path = normalizeArray(filter(path.split('/'), function(p) {
    return !!p;
  }), !isAbsolute).join('/');

  if (!path && !isAbsolute) {
    path = '.';
  }
  if (path && trailingSlash) {
    path += '/';
  }

  return (isAbsolute ? '/' : '') + path;
};

// posix version
exports.isAbsolute = function(path) {
  return path.charAt(0) === '/';
};

// posix version
exports.join = function() {
  var paths = Array.prototype.slice.call(arguments, 0);
  return exports.normalize(filter(paths, function(p, index) {
    if (typeof p !== 'string') {
      throw new TypeError('Arguments to path.join must be strings');
    }
    return p;
  }).join('/'));
};


// path.relative(from, to)
// posix version
exports.relative = function(from, to) {
  from = exports.resolve(from).substr(1);
  to = exports.resolve(to).substr(1);

  function trim(arr) {
    var start = 0;
    for (; start < arr.length; start++) {
      if (arr[start] !== '') break;
    }

    var end = arr.length - 1;
    for (; end >= 0; end--) {
      if (arr[end] !== '') break;
    }

    if (start > end) return [];
    return arr.slice(start, end - start + 1);
  }

  var fromParts = trim(from.split('/'));
  var toParts = trim(to.split('/'));

  var length = Math.min(fromParts.length, toParts.length);
  var samePartsLength = length;
  for (var i = 0; i < length; i++) {
    if (fromParts[i] !== toParts[i]) {
      samePartsLength = i;
      break;
    }
  }

  var outputParts = [];
  for (var i = samePartsLength; i < fromParts.length; i++) {
    outputParts.push('..');
  }

  outputParts = outputParts.concat(toParts.slice(samePartsLength));

  return outputParts.join('/');
};

exports.sep = '/';
exports.delimiter = ':';

exports.dirname = function(path) {
  var result = splitPath(path),
      root = result[0],
      dir = result[1];

  if (!root && !dir) {
    // No dirname whatsoever
    return '.';
  }

  if (dir) {
    // It has a dirname, strip trailing slash
    dir = dir.substr(0, dir.length - 1);
  }

  return root + dir;
};


exports.basename = function(path, ext) {
  var f = splitPath(path)[2];
  // TODO: make this comparison case-insensitive on windows?
  if (ext && f.substr(-1 * ext.length) === ext) {
    f = f.substr(0, f.length - ext.length);
  }
  return f;
};


exports.extname = function(path) {
  return splitPath(path)[3];
};

function filter (xs, f) {
    if (xs.filter) return xs.filter(f);
    var res = [];
    for (var i = 0; i < xs.length; i++) {
        if (f(xs[i], i, xs)) res.push(xs[i]);
    }
    return res;
}

// String.prototype.substr - negative index don't work in IE8
var substr = 'ab'.substr(-1) === 'b'
    ? function (str, start, len) { return str.substr(start, len) }
    : function (str, start, len) {
        if (start < 0) start = str.length + start;
        return str.substr(start, len);
    }
;

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../process/browser.js */ "8oxB")))

/***/ }),

/***/ "37PH":
/*!*******************************************************************!*\
  !*** ./node_modules/plotly.js/src/components/color/attributes.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




// IMPORTANT - default colors should be in hex for compatibility
exports.defaults = [
    '#1f77b4',  // muted blue
    '#ff7f0e',  // safety orange
    '#2ca02c',  // cooked asparagus green
    '#d62728',  // brick red
    '#9467bd',  // muted purple
    '#8c564b',  // chestnut brown
    '#e377c2',  // raspberry yogurt pink
    '#7f7f7f',  // middle gray
    '#bcbd22',  // curry yellow-green
    '#17becf'   // blue-teal
];

exports.defaultLine = '#444';

exports.lightLine = '#eee';

exports.background = '#fff';

exports.borderLine = '#BEC8D9';

// with axis.color and Color.interp we aren't using lightLine
// itself anymore, instead interpolating between axis.color
// and the background color using tinycolor.mix. lightFraction
// gives back exactly lightLine if the other colors are defaults.
exports.lightFraction = 100 * (0xe - 0x4) / (0xf - 0x4);


/***/ }),

/***/ "3A9y":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_setCacheHas.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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);
}

module.exports = setCacheHas;


/***/ }),

/***/ "3ASw":
/*!****************************************************!*\
  !*** ./node_modules/source-map/lib/source-node.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* -*- Mode: js; js-indent-level: 2; -*- */
/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var SourceMapGenerator = __webpack_require__(/*! ./source-map-generator */ "UCR5").SourceMapGenerator;
var util = __webpack_require__(/*! ./util */ "Cbry");

// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
// operating systems these days (capturing the result).
var REGEX_NEWLINE = /(\r?\n)/;

// Newline character code for charCodeAt() comparisons
var NEWLINE_CODE = 10;

// Private symbol for identifying `SourceNode`s when multiple versions of
// the source-map library are loaded. This MUST NOT CHANGE across
// versions!
var isSourceNode = "$$$isSourceNode$$$";

/**
 * SourceNodes provide a way to abstract over interpolating/concatenating
 * snippets of generated JavaScript source code while maintaining the line and
 * column information associated with the original source code.
 *
 * @param aLine The original line number.
 * @param aColumn The original column number.
 * @param aSource The original source's filename.
 * @param aChunks Optional. An array of strings which are snippets of
 *        generated JS, or other SourceNodes.
 * @param aName The original identifier.
 */
function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  this.children = [];
  this.sourceContents = {};
  this.line = aLine == null ? null : aLine;
  this.column = aColumn == null ? null : aColumn;
  this.source = aSource == null ? null : aSource;
  this.name = aName == null ? null : aName;
  this[isSourceNode] = true;
  if (aChunks != null) this.add(aChunks);
}

/**
 * Creates a SourceNode from generated code and a SourceMapConsumer.
 *
 * @param aGeneratedCode The generated code
 * @param aSourceMapConsumer The SourceMap for the generated code
 * @param aRelativePath Optional. The path that relative sources in the
 *        SourceMapConsumer should be relative to.
 */
SourceNode.fromStringWithSourceMap =
  function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
    // The SourceNode we want to fill with the generated code
    // and the SourceMap
    var node = new SourceNode();

    // All even indices of this array are one line of the generated code,
    // while all odd indices are the newlines between two adjacent lines
    // (since `REGEX_NEWLINE` captures its match).
    // Processed fragments are accessed by calling `shiftNextLine`.
    var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
    var remainingLinesIndex = 0;
    var shiftNextLine = function() {
      var lineContents = getNextLine();
      // The last line of a file might not have a newline.
      var newLine = getNextLine() || "";
      return lineContents + newLine;

      function getNextLine() {
        return remainingLinesIndex < remainingLines.length ?
            remainingLines[remainingLinesIndex++] : undefined;
      }
    };

    // We need to remember the position of "remainingLines"
    var lastGeneratedLine = 1, lastGeneratedColumn = 0;

    // The generate SourceNodes we need a code range.
    // To extract it current and last mapping is used.
    // Here we store the last mapping.
    var lastMapping = null;

    aSourceMapConsumer.eachMapping(function (mapping) {
      if (lastMapping !== null) {
        // We add the code from "lastMapping" to "mapping":
        // First check if there is a new line in between.
        if (lastGeneratedLine < mapping.generatedLine) {
          // Associate first line with "lastMapping"
          addMappingWithCode(lastMapping, shiftNextLine());
          lastGeneratedLine++;
          lastGeneratedColumn = 0;
          // The remaining code is added without mapping
        } else {
          // There is no new line in between.
          // Associate the code between "lastGeneratedColumn" and
          // "mapping.generatedColumn" with "lastMapping"
          var nextLine = remainingLines[remainingLinesIndex] || '';
          var code = nextLine.substr(0, mapping.generatedColumn -
                                        lastGeneratedColumn);
          remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
                                              lastGeneratedColumn);
          lastGeneratedColumn = mapping.generatedColumn;
          addMappingWithCode(lastMapping, code);
          // No more remaining code, continue
          lastMapping = mapping;
          return;
        }
      }
      // We add the generated code until the first mapping
      // to the SourceNode without any mapping.
      // Each line is added as separate string.
      while (lastGeneratedLine < mapping.generatedLine) {
        node.add(shiftNextLine());
        lastGeneratedLine++;
      }
      if (lastGeneratedColumn < mapping.generatedColumn) {
        var nextLine = remainingLines[remainingLinesIndex] || '';
        node.add(nextLine.substr(0, mapping.generatedColumn));
        remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
        lastGeneratedColumn = mapping.generatedColumn;
      }
      lastMapping = mapping;
    }, this);
    // We have processed all mappings.
    if (remainingLinesIndex < remainingLines.length) {
      if (lastMapping) {
        // Associate the remaining code in the current line with "lastMapping"
        addMappingWithCode(lastMapping, shiftNextLine());
      }
      // and add the remaining lines without any mapping
      node.add(remainingLines.splice(remainingLinesIndex).join(""));
    }

    // Copy sourcesContent into SourceNode
    aSourceMapConsumer.sources.forEach(function (sourceFile) {
      var content = aSourceMapConsumer.sourceContentFor(sourceFile);
      if (content != null) {
        if (aRelativePath != null) {
          sourceFile = util.join(aRelativePath, sourceFile);
        }
        node.setSourceContent(sourceFile, content);
      }
    });

    return node;

    function addMappingWithCode(mapping, code) {
      if (mapping === null || mapping.source === undefined) {
        node.add(code);
      } else {
        var source = aRelativePath
          ? util.join(aRelativePath, mapping.source)
          : mapping.source;
        node.add(new SourceNode(mapping.originalLine,
                                mapping.originalColumn,
                                source,
                                code,
                                mapping.name));
      }
    }
  };

/**
 * Add a chunk of generated JS to this source node.
 *
 * @param aChunk A string snippet of generated JS code, another instance of
 *        SourceNode, or an array where each member is one of those things.
 */
SourceNode.prototype.add = function SourceNode_add(aChunk) {
  if (Array.isArray(aChunk)) {
    aChunk.forEach(function (chunk) {
      this.add(chunk);
    }, this);
  }
  else if (aChunk[isSourceNode] || typeof aChunk === "string") {
    if (aChunk) {
      this.children.push(aChunk);
    }
  }
  else {
    throw new TypeError(
      "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
    );
  }
  return this;
};

/**
 * Add a chunk of generated JS to the beginning of this source node.
 *
 * @param aChunk A string snippet of generated JS code, another instance of
 *        SourceNode, or an array where each member is one of those things.
 */
SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  if (Array.isArray(aChunk)) {
    for (var i = aChunk.length-1; i >= 0; i--) {
      this.prepend(aChunk[i]);
    }
  }
  else if (aChunk[isSourceNode] || typeof aChunk === "string") {
    this.children.unshift(aChunk);
  }
  else {
    throw new TypeError(
      "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
    );
  }
  return this;
};

/**
 * Walk over the tree of JS snippets in this node and its children. The
 * walking function is called once for each snippet of JS and is passed that
 * snippet and the its original associated source's line/column location.
 *
 * @param aFn The traversal function.
 */
SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  var chunk;
  for (var i = 0, len = this.children.length; i < len; i++) {
    chunk = this.children[i];
    if (chunk[isSourceNode]) {
      chunk.walk(aFn);
    }
    else {
      if (chunk !== '') {
        aFn(chunk, { source: this.source,
                     line: this.line,
                     column: this.column,
                     name: this.name });
      }
    }
  }
};

/**
 * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
 * each of `this.children`.
 *
 * @param aSep The separator.
 */
SourceNode.prototype.join = function SourceNode_join(aSep) {
  var newChildren;
  var i;
  var len = this.children.length;
  if (len > 0) {
    newChildren = [];
    for (i = 0; i < len-1; i++) {
      newChildren.push(this.children[i]);
      newChildren.push(aSep);
    }
    newChildren.push(this.children[i]);
    this.children = newChildren;
  }
  return this;
};

/**
 * Call String.prototype.replace on the very right-most source snippet. Useful
 * for trimming whitespace from the end of a source node, etc.
 *
 * @param aPattern The pattern to replace.
 * @param aReplacement The thing to replace the pattern with.
 */
SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  var lastChild = this.children[this.children.length - 1];
  if (lastChild[isSourceNode]) {
    lastChild.replaceRight(aPattern, aReplacement);
  }
  else if (typeof lastChild === 'string') {
    this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  }
  else {
    this.children.push(''.replace(aPattern, aReplacement));
  }
  return this;
};

/**
 * Set the source content for a source file. This will be added to the SourceMapGenerator
 * in the sourcesContent field.
 *
 * @param aSourceFile The filename of the source file
 * @param aSourceContent The content of the source file
 */
SourceNode.prototype.setSourceContent =
  function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
    this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  };

/**
 * Walk over the tree of SourceNodes. The walking function is called for each
 * source file content and is passed the filename and source content.
 *
 * @param aFn The traversal function.
 */
SourceNode.prototype.walkSourceContents =
  function SourceNode_walkSourceContents(aFn) {
    for (var i = 0, len = this.children.length; i < len; i++) {
      if (this.children[i][isSourceNode]) {
        this.children[i].walkSourceContents(aFn);
      }
    }

    var sources = Object.keys(this.sourceContents);
    for (var i = 0, len = sources.length; i < len; i++) {
      aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
    }
  };

/**
 * Return the string representation of this source node. Walks over the tree
 * and concatenates all the various snippets together to one string.
 */
SourceNode.prototype.toString = function SourceNode_toString() {
  var str = "";
  this.walk(function (chunk) {
    str += chunk;
  });
  return str;
};

/**
 * Returns the string representation of this source node along with a source
 * map.
 */
SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  var generated = {
    code: "",
    line: 1,
    column: 0
  };
  var map = new SourceMapGenerator(aArgs);
  var sourceMappingActive = false;
  var lastOriginalSource = null;
  var lastOriginalLine = null;
  var lastOriginalColumn = null;
  var lastOriginalName = null;
  this.walk(function (chunk, original) {
    generated.code += chunk;
    if (original.source !== null
        && original.line !== null
        && original.column !== null) {
      if(lastOriginalSource !== original.source
         || lastOriginalLine !== original.line
         || lastOriginalColumn !== original.column
         || lastOriginalName !== original.name) {
        map.addMapping({
          source: original.source,
          original: {
            line: original.line,
            column: original.column
          },
          generated: {
            line: generated.line,
            column: generated.column
          },
          name: original.name
        });
      }
      lastOriginalSource = original.source;
      lastOriginalLine = original.line;
      lastOriginalColumn = original.column;
      lastOriginalName = original.name;
      sourceMappingActive = true;
    } else if (sourceMappingActive) {
      map.addMapping({
        generated: {
          line: generated.line,
          column: generated.column
        }
      });
      lastOriginalSource = null;
      sourceMappingActive = false;
    }
    for (var idx = 0, length = chunk.length; idx < length; idx++) {
      if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
        generated.line++;
        generated.column = 0;
        // Mappings end at eol
        if (idx + 1 === length) {
          lastOriginalSource = null;
          sourceMappingActive = false;
        } else if (sourceMappingActive) {
          map.addMapping({
            source: original.source,
            original: {
              line: original.line,
              column: original.column
            },
            generated: {
              line: generated.line,
              column: generated.column
            },
            name: original.name
          });
        }
      } else {
        generated.column++;
      }
    }
  });
  this.walkSourceContents(function (sourceFile, sourceContent) {
    map.setSourceContent(sourceFile, sourceContent);
  });

  return { code: generated.code, map: map };
};

exports.SourceNode = SourceNode;


/***/ }),

/***/ "3B+o":
/*!*************************************************!*\
  !*** ./node_modules/mdi-react/BriefcaseIcon.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var BriefcaseIcon = function BriefcaseIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M10,2H14C15.1,2 16,2.9 16,4V6H20C21.1,6 22,6.9 22,8V19C22,20.1 21.1,21 20,21H4C2.89,21 2,20.1 2,19V8C2,6.89 2.89,6 4,6H8V4C8,2.89 8.89,2 10,2M14,6V4H10V6H14Z' })
  );
};

module.exports = BriefcaseIcon;


/***/ }),

/***/ "3BRs":
/*!**************************************************************!*\
  !*** ./node_modules/readable-stream/lib/_stream_writable.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(process, setImmediate, global) {// Copyright Joyent, Inc. and other Node contributors.
//
// 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.

// A bit simpler than readable streams.
// Implement an async ._write(chunk, encoding, cb), and it'll handle all
// the drain event emission and buffering.



/*<replacement>*/

var pna = __webpack_require__(/*! process-nextick-args */ "lm0R");
/*</replacement>*/

module.exports = Writable;

/* <replacement> */
function WriteReq(chunk, encoding, cb) {
  this.chunk = chunk;
  this.encoding = encoding;
  this.callback = cb;
  this.next = null;
}

// It seems a linked list but it is not
// there will be only 2 of these for each stream
function CorkedRequest(state) {
  var _this = this;

  this.next = null;
  this.entry = null;
  this.finish = function () {
    onCorkedFinish(_this, state);
  };
}
/* </replacement> */

/*<replacement>*/
var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
/*</replacement>*/

/*<replacement>*/
var Duplex;
/*</replacement>*/

Writable.WritableState = WritableState;

/*<replacement>*/
var util = __webpack_require__(/*! core-util-is */ "Onz0");
util.inherits = __webpack_require__(/*! inherits */ "P7XM");
/*</replacement>*/

/*<replacement>*/
var internalUtil = {
  deprecate: __webpack_require__(/*! util-deprecate */ "t9FE")
};
/*</replacement>*/

/*<replacement>*/
var Stream = __webpack_require__(/*! ./internal/streams/stream */ "QpuX");
/*</replacement>*/

/*<replacement>*/

var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer;
var OurUint8Array = global.Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
  return Buffer.from(chunk);
}
function _isUint8Array(obj) {
  return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}

/*</replacement>*/

var destroyImpl = __webpack_require__(/*! ./internal/streams/destroy */ "RoFp");

util.inherits(Writable, Stream);

function nop() {}

function WritableState(options, stream) {
  Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ "sZro");

  options = options || {};

  // Duplex streams are both readable and writable, but share
  // the same options object.
  // However, some cases require setting options to different
  // values for the readable and the writable sides of the duplex stream.
  // These options can be provided separately as readableXXX and writableXXX.
  var isDuplex = stream instanceof Duplex;

  // object stream flag to indicate whether or not this stream
  // contains buffers or objects.
  this.objectMode = !!options.objectMode;

  if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;

  // the point at which write() starts returning false
  // Note: 0 is a valid value, means that we always return false if
  // the entire buffer is not flushed immediately on write()
  var hwm = options.highWaterMark;
  var writableHwm = options.writableHighWaterMark;
  var defaultHwm = this.objectMode ? 16 : 16 * 1024;

  if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;

  // cast to ints.
  this.highWaterMark = Math.floor(this.highWaterMark);

  // if _final has been called
  this.finalCalled = false;

  // drain event flag.
  this.needDrain = false;
  // at the start of calling end()
  this.ending = false;
  // when end() has been called, and returned
  this.ended = false;
  // when 'finish' is emitted
  this.finished = false;

  // has it been destroyed
  this.destroyed = false;

  // should we decode strings into buffers before passing to _write?
  // this is here so that some node-core streams can optimize string
  // handling at a lower level.
  var noDecode = options.decodeStrings === false;
  this.decodeStrings = !noDecode;

  // Crypto is kind of old and crusty.  Historically, its default string
  // encoding is 'binary' so we have to make this configurable.
  // Everything else in the universe uses 'utf8', though.
  this.defaultEncoding = options.defaultEncoding || 'utf8';

  // not an actual buffer we keep track of, but a measurement
  // of how much we're waiting to get pushed to some underlying
  // socket or file.
  this.length = 0;

  // a flag to see when we're in the middle of a write.
  this.writing = false;

  // when true all writes will be buffered until .uncork() call
  this.corked = 0;

  // a flag to be able to tell if the onwrite cb is called immediately,
  // or on a later tick.  We set this to true at first, because any
  // actions that shouldn't happen until "later" should generally also
  // not happen before the first write call.
  this.sync = true;

  // a flag to know if we're processing previously buffered items, which
  // may call the _write() callback in the same tick, so that we don't
  // end up in an overlapped onwrite situation.
  this.bufferProcessing = false;

  // the callback that's passed to _write(chunk,cb)
  this.onwrite = function (er) {
    onwrite(stream, er);
  };

  // the callback that the user supplies to write(chunk,encoding,cb)
  this.writecb = null;

  // the amount that is being written when _write is called.
  this.writelen = 0;

  this.bufferedRequest = null;
  this.lastBufferedRequest = null;

  // number of pending user-supplied write callbacks
  // this must be 0 before 'finish' can be emitted
  this.pendingcb = 0;

  // emit prefinish if the only thing we're waiting for is _write cbs
  // This is relevant for synchronous Transform streams
  this.prefinished = false;

  // True if the error was already emitted and should not be thrown again
  this.errorEmitted = false;

  // count buffered requests
  this.bufferedRequestCount = 0;

  // allocate the first CorkedRequest, there is always
  // one allocated and free to use, and we maintain at most two
  this.corkedRequestsFree = new CorkedRequest(this);
}

WritableState.prototype.getBuffer = function getBuffer() {
  var current = this.bufferedRequest;
  var out = [];
  while (current) {
    out.push(current);
    current = current.next;
  }
  return out;
};

(function () {
  try {
    Object.defineProperty(WritableState.prototype, 'buffer', {
      get: internalUtil.deprecate(function () {
        return this.getBuffer();
      }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
    });
  } catch (_) {}
})();

// Test _writableState for inheritance to account for Duplex streams,
// whose prototype chain only points to Readable.
var realHasInstance;
if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  realHasInstance = Function.prototype[Symbol.hasInstance];
  Object.defineProperty(Writable, Symbol.hasInstance, {
    value: function (object) {
      if (realHasInstance.call(this, object)) return true;
      if (this !== Writable) return false;

      return object && object._writableState instanceof WritableState;
    }
  });
} else {
  realHasInstance = function (object) {
    return object instanceof this;
  };
}

function Writable(options) {
  Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ "sZro");

  // Writable ctor is applied to Duplexes, too.
  // `realHasInstance` is necessary because using plain `instanceof`
  // would return false, as no `_writableState` property is attached.

  // Trying to use the custom `instanceof` for Writable here will also break the
  // Node.js LazyTransform implementation, which has a non-trivial getter for
  // `_writableState` that would lead to infinite recursion.
  if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
    return new Writable(options);
  }

  this._writableState = new WritableState(options, this);

  // legacy.
  this.writable = true;

  if (options) {
    if (typeof options.write === 'function') this._write = options.write;

    if (typeof options.writev === 'function') this._writev = options.writev;

    if (typeof options.destroy === 'function') this._destroy = options.destroy;

    if (typeof options.final === 'function') this._final = options.final;
  }

  Stream.call(this);
}

// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function () {
  this.emit('error', new Error('Cannot pipe, not readable'));
};

function writeAfterEnd(stream, cb) {
  var er = new Error('write after end');
  // TODO: defer error events consistently everywhere, not just the cb
  stream.emit('error', er);
  pna.nextTick(cb, er);
}

// Checks that a user-supplied chunk is valid, especially for the particular
// mode the stream is in. Currently this means that `null` is never accepted
// and undefined/non-string values are only allowed in object mode.
function validChunk(stream, state, chunk, cb) {
  var valid = true;
  var er = false;

  if (chunk === null) {
    er = new TypeError('May not write null values to stream');
  } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
    er = new TypeError('Invalid non-string/buffer chunk');
  }
  if (er) {
    stream.emit('error', er);
    pna.nextTick(cb, er);
    valid = false;
  }
  return valid;
}

Writable.prototype.write = function (chunk, encoding, cb) {
  var state = this._writableState;
  var ret = false;
  var isBuf = !state.objectMode && _isUint8Array(chunk);

  if (isBuf && !Buffer.isBuffer(chunk)) {
    chunk = _uint8ArrayToBuffer(chunk);
  }

  if (typeof encoding === 'function') {
    cb = encoding;
    encoding = null;
  }

  if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;

  if (typeof cb !== 'function') cb = nop;

  if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
    state.pendingcb++;
    ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  }

  return ret;
};

Writable.prototype.cork = function () {
  var state = this._writableState;

  state.corked++;
};

Writable.prototype.uncork = function () {
  var state = this._writableState;

  if (state.corked) {
    state.corked--;

    if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  }
};

Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  // node::ParseEncoding() requires lower case.
  if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
  this._writableState.defaultEncoding = encoding;
  return this;
};

function decodeChunk(state, chunk, encoding) {
  if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
    chunk = Buffer.from(chunk, encoding);
  }
  return chunk;
}

Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function () {
    return this._writableState.highWaterMark;
  }
});

// if we're already writing something, then just put this
// in the queue, and wait our turn.  Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  if (!isBuf) {
    var newChunk = decodeChunk(state, chunk, encoding);
    if (chunk !== newChunk) {
      isBuf = true;
      encoding = 'buffer';
      chunk = newChunk;
    }
  }
  var len = state.objectMode ? 1 : chunk.length;

  state.length += len;

  var ret = state.length < state.highWaterMark;
  // we must ensure that previous needDrain will not be reset to false.
  if (!ret) state.needDrain = true;

  if (state.writing || state.corked) {
    var last = state.lastBufferedRequest;
    state.lastBufferedRequest = {
      chunk: chunk,
      encoding: encoding,
      isBuf: isBuf,
      callback: cb,
      next: null
    };
    if (last) {
      last.next = state.lastBufferedRequest;
    } else {
      state.bufferedRequest = state.lastBufferedRequest;
    }
    state.bufferedRequestCount += 1;
  } else {
    doWrite(stream, state, false, len, chunk, encoding, cb);
  }

  return ret;
}

function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  state.writelen = len;
  state.writecb = cb;
  state.writing = true;
  state.sync = true;
  if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  state.sync = false;
}

function onwriteError(stream, state, sync, er, cb) {
  --state.pendingcb;

  if (sync) {
    // defer the callback if we are being called synchronously
    // to avoid piling up things on the stack
    pna.nextTick(cb, er);
    // this can emit finish, and it will always happen
    // after error
    pna.nextTick(finishMaybe, stream, state);
    stream._writableState.errorEmitted = true;
    stream.emit('error', er);
  } else {
    // the caller expect this to happen before if
    // it is async
    cb(er);
    stream._writableState.errorEmitted = true;
    stream.emit('error', er);
    // this can emit finish, but finish must
    // always follow error
    finishMaybe(stream, state);
  }
}

function onwriteStateUpdate(state) {
  state.writing = false;
  state.writecb = null;
  state.length -= state.writelen;
  state.writelen = 0;
}

function onwrite(stream, er) {
  var state = stream._writableState;
  var sync = state.sync;
  var cb = state.writecb;

  onwriteStateUpdate(state);

  if (er) onwriteError(stream, state, sync, er, cb);else {
    // Check if we're actually ready to finish, but don't emit yet
    var finished = needFinish(state);

    if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
      clearBuffer(stream, state);
    }

    if (sync) {
      /*<replacement>*/
      asyncWrite(afterWrite, stream, state, finished, cb);
      /*</replacement>*/
    } else {
      afterWrite(stream, state, finished, cb);
    }
  }
}

function afterWrite(stream, state, finished, cb) {
  if (!finished) onwriteDrain(stream, state);
  state.pendingcb--;
  cb();
  finishMaybe(stream, state);
}

// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
  if (state.length === 0 && state.needDrain) {
    state.needDrain = false;
    stream.emit('drain');
  }
}

// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
  state.bufferProcessing = true;
  var entry = state.bufferedRequest;

  if (stream._writev && entry && entry.next) {
    // Fast case, write everything using _writev()
    var l = state.bufferedRequestCount;
    var buffer = new Array(l);
    var holder = state.corkedRequestsFree;
    holder.entry = entry;

    var count = 0;
    var allBuffers = true;
    while (entry) {
      buffer[count] = entry;
      if (!entry.isBuf) allBuffers = false;
      entry = entry.next;
      count += 1;
    }
    buffer.allBuffers = allBuffers;

    doWrite(stream, state, true, state.length, buffer, '', holder.finish);

    // doWrite is almost always async, defer these to save a bit of time
    // as the hot path ends with doWrite
    state.pendingcb++;
    state.lastBufferedRequest = null;
    if (holder.next) {
      state.corkedRequestsFree = holder.next;
      holder.next = null;
    } else {
      state.corkedRequestsFree = new CorkedRequest(state);
    }
    state.bufferedRequestCount = 0;
  } else {
    // Slow case, write chunks one-by-one
    while (entry) {
      var chunk = entry.chunk;
      var encoding = entry.encoding;
      var cb = entry.callback;
      var len = state.objectMode ? 1 : chunk.length;

      doWrite(stream, state, false, len, chunk, encoding, cb);
      entry = entry.next;
      state.bufferedRequestCount--;
      // if we didn't call the onwrite immediately, then
      // it means that we need to wait until it does.
      // also, that means that the chunk and cb are currently
      // being processed, so move the buffer counter past them.
      if (state.writing) {
        break;
      }
    }

    if (entry === null) state.lastBufferedRequest = null;
  }

  state.bufferedRequest = entry;
  state.bufferProcessing = false;
}

Writable.prototype._write = function (chunk, encoding, cb) {
  cb(new Error('_write() is not implemented'));
};

Writable.prototype._writev = null;

Writable.prototype.end = function (chunk, encoding, cb) {
  var state = this._writableState;

  if (typeof chunk === 'function') {
    cb = chunk;
    chunk = null;
    encoding = null;
  } else if (typeof encoding === 'function') {
    cb = encoding;
    encoding = null;
  }

  if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);

  // .end() fully uncorks
  if (state.corked) {
    state.corked = 1;
    this.uncork();
  }

  // ignore unnecessary end() calls.
  if (!state.ending && !state.finished) endWritable(this, state, cb);
};

function needFinish(state) {
  return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
}
function callFinal(stream, state) {
  stream._final(function (err) {
    state.pendingcb--;
    if (err) {
      stream.emit('error', err);
    }
    state.prefinished = true;
    stream.emit('prefinish');
    finishMaybe(stream, state);
  });
}
function prefinish(stream, state) {
  if (!state.prefinished && !state.finalCalled) {
    if (typeof stream._final === 'function') {
      state.pendingcb++;
      state.finalCalled = true;
      pna.nextTick(callFinal, stream, state);
    } else {
      state.prefinished = true;
      stream.emit('prefinish');
    }
  }
}

function finishMaybe(stream, state) {
  var need = needFinish(state);
  if (need) {
    prefinish(stream, state);
    if (state.pendingcb === 0) {
      state.finished = true;
      stream.emit('finish');
    }
  }
  return need;
}

function endWritable(stream, state, cb) {
  state.ending = true;
  finishMaybe(stream, state);
  if (cb) {
    if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
  }
  state.ended = true;
  stream.writable = false;
}

function onCorkedFinish(corkReq, state, err) {
  var entry = corkReq.entry;
  corkReq.entry = null;
  while (entry) {
    var cb = entry.callback;
    state.pendingcb--;
    cb(err);
    entry = entry.next;
  }
  if (state.corkedRequestsFree) {
    state.corkedRequestsFree.next = corkReq;
  } else {
    state.corkedRequestsFree = corkReq;
  }
}

Object.defineProperty(Writable.prototype, 'destroyed', {
  get: function () {
    if (this._writableState === undefined) {
      return false;
    }
    return this._writableState.destroyed;
  },
  set: function (value) {
    // we ignore the value if the stream
    // has not been initialized yet
    if (!this._writableState) {
      return;
    }

    // backward compatibility, the user is explicitly
    // managing destroyed
    this._writableState.destroyed = value;
  }
});

Writable.prototype.destroy = destroyImpl.destroy;
Writable.prototype._undestroy = destroyImpl.undestroy;
Writable.prototype._destroy = function (err, cb) {
  this.end();
  cb(err);
};
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ "8oxB"), __webpack_require__(/*! ./../../timers-browserify/main.js */ "URgk").setImmediate, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "3Br+":
/*!***************************************************************!*\
  !*** ./node_modules/draft-js/lib/keyCommandPlainBackspace.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule keyCommandPlainBackspace
 * @format
 * 
 */



var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");
var UnicodeUtils = __webpack_require__(/*! fbjs/lib/UnicodeUtils */ "jLRO");

var moveSelectionBackward = __webpack_require__(/*! ./moveSelectionBackward */ "kWjT");
var removeTextWithStrategy = __webpack_require__(/*! ./removeTextWithStrategy */ "8d//");

/**
 * Remove the selected range. If the cursor is collapsed, remove the preceding
 * character. This operation is Unicode-aware, so removing a single character
 * will remove a surrogate pair properly as well.
 */
function keyCommandPlainBackspace(editorState) {
  var afterRemoval = removeTextWithStrategy(editorState, function (strategyState) {
    var selection = strategyState.getSelection();
    var content = strategyState.getCurrentContent();
    var key = selection.getAnchorKey();
    var offset = selection.getAnchorOffset();
    var charBehind = content.getBlockForKey(key).getText()[offset - 1];
    return moveSelectionBackward(strategyState, charBehind ? UnicodeUtils.getUTF16Length(charBehind, 0) : 1);
  }, 'backward');

  if (afterRemoval === editorState.getCurrentContent()) {
    return editorState;
  }

  var selection = editorState.getSelection();
  return EditorState.push(editorState, afterRemoval.set('selectionBefore', selection), selection.isCollapsed() ? 'backspace-character' : 'remove-range');
}

module.exports = keyCommandPlainBackspace;

/***/ }),

/***/ "3C5O":
/*!*******************************************************!*\
  !*** ./node_modules/@jupyterlab/mainmenu/lib/tabs.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const labmenu_1 = __webpack_require__(/*! ./labmenu */ "e7FE");
/**
 * An extensible Tabs menu for the application.
 */
class TabsMenu extends labmenu_1.JupyterLabMenu {
    /**
     * Construct the tabs menu.
     */
    constructor(options) {
        super(options);
        this.menu.title.label = 'Tabs';
    }
}
exports.TabsMenu = TabsMenu;


/***/ }),

/***/ "3Drf":
/*!****************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/application/style/menus.css ***!
  \****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n/*-----------------------------------------------------------------------------\n| Variables\n|----------------------------------------------------------------------------*/\n\n:root {\n  --jp-private-menubar-height: 28px;\n  --jp-private-menu-item-height: 24px;\n}\n\n/*-----------------------------------------------------------------------------\n| MenuBar\n|----------------------------------------------------------------------------*/\n\n.p-MenuBar {\n  padding-left: 5px;\n  background: var(--jp-layout-color1);\n  color: var(--jp-ui-font-color1);\n  font-size: var(--jp-ui-font-size1);\n}\n\n.p-MenuBar-menu {\n  transform: translateY(calc(-2 * var(--jp-border-width)));\n}\n\n.p-MenuBar-item {\n  padding: 0px 8px;\n  border-left: var(--jp-border-width) solid transparent;\n  border-right: var(--jp-border-width) solid transparent;\n  line-height: var(--jp-private-menubar-height);\n}\n\n.p-MenuBar-item.p-mod-active {\n  background: var(--jp-layout-color1);\n}\n\n.p-MenuBar.p-mod-active .p-MenuBar-item.p-mod-active {\n  z-index: 10001;\n  background: var(--jp-layout-color0);\n  border-left: var(--jp-border-width) solid var(--jp-border-color1);\n  border-right: var(--jp-border-width) solid var(--jp-border-color1);\n  box-shadow: var(--jp-elevation-z6);\n}\n\n.p-MenuBar-item.p-mod-disabled {\n  color: var(--jp-ui-font-color3);\n}\n\n.p-MenuBar-item.p-type-separator {\n  margin: 2px;\n  padding: 0;\n  border: none;\n  border-left: var(--jp-border-width) solid var(--jp-border-color2);\n}\n\n.p-MenuBar-itemMnemonic {\n  text-decoration: underline;\n}\n\n/*-----------------------------------------------------------------------------\n| Menu\n|----------------------------------------------------------------------------*/\n\n.p-Menu {\n  z-index: 10000;\n  padding: 4px 0px;\n  background: var(--jp-layout-color0);\n  color: var(--jp-ui-font-color1);\n  border: var(--jp-border-width) solid var(--jp-border-color1);\n  font-size: var(--jp-ui-font-size1);\n  box-shadow: var(--jp-elevation-z6);\n}\n\n.p-Menu-item {\n  min-height: var(--jp-private-menu-item-height);\n  max-height: var(--jp-private-menu-item-height);\n  padding: 0px;\n  line-height: var(--jp-private-menu-item-height);\n}\n\n.p-Menu-item.p-mod-active {\n  background: var(--jp-layout-color2);\n}\n\n.p-Menu-item.p-mod-disabled {\n  color: var(--jp-ui-font-color3);\n}\n\n.p-Menu-itemIcon {\n  width: 21px;\n  padding: 0px 2px 0px 4px;\n  margin-top: -2px;\n}\n\n.p-Menu-itemLabel {\n  padding: 0px 32px 0px 2px;\n}\n\n.p-Menu-itemMnemonic {\n  text-decoration: underline;\n}\n\n.p-Menu-itemShortcut {\n  padding: 0px;\n}\n\n.p-Menu-itemSubmenuIcon {\n  width: 18px;\n  padding: 0px 4px 0px 0px;\n}\n\n.p-Menu-item[data-type='separator'] > div {\n  padding: 0;\n  height: 9px;\n}\n\n.p-Menu-item[data-type='separator'] > div::after {\n  content: '';\n  display: block;\n  position: relative;\n  top: 4px;\n  border-top: var(--jp-border-width) solid var(--jp-layout-color2);\n}\n\n.p-Menu-itemIcon,\n.p-Menu-itemSubmenuIcon {\n  background-size: 16px;\n  background-repeat: no-repeat;\n  background-position: center;\n}\n\n.p-Menu-item.p-mod-toggled > .p-Menu-itemIcon {\n  background-image: var(--jp-icon-checkmark);\n}\n\n.p-Menu-item.p-mod-toggled.p-mod-disabled > .p-Menu-itemIcon {\n  background-image: var(--jp-icon-checkmark-disabled);\n}\n\n.p-Menu-item[data-type='submenu'] > .p-Menu-itemSubmenuIcon {\n  background-image: var(--jp-icon-caretright);\n  background-size: 18px;\n  background-repeat: no-repeat;\n  background-position: left;\n}\n", ""]);

// exports


/***/ }),

/***/ "3E1r":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/hi.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var symbolMap = {
    '1': '१',
    '2': '२',
    '3': '३',
    '4': '४',
    '5': '५',
    '6': '६',
    '7': '७',
    '8': '८',
    '9': '९',
    '0': '०'
},
numberMap = {
    '१': '1',
    '२': '2',
    '३': '3',
    '४': '4',
    '५': '5',
    '६': '6',
    '७': '7',
    '८': '8',
    '९': '9',
    '०': '0'
};

var hi = moment.defineLocale('hi', {
    months : 'जनवरी_फ़रवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितम्बर_अक्टूबर_नवम्बर_दिसम्बर'.split('_'),
    monthsShort : 'जन._फ़र._मार्च_अप्रै._मई_जून_जुल._अग._सित._अक्टू._नव._दिस.'.split('_'),
    monthsParseExact: true,
    weekdays : 'रविवार_सोमवार_मंगलवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'),
    weekdaysShort : 'रवि_सोम_मंगल_बुध_गुरू_शुक्र_शनि'.split('_'),
    weekdaysMin : 'र_सो_मं_बु_गु_शु_श'.split('_'),
    longDateFormat : {
        LT : 'A h:mm बजे',
        LTS : 'A h:mm:ss बजे',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY, A h:mm बजे',
        LLLL : 'dddd, D MMMM YYYY, A h:mm बजे'
    },
    calendar : {
        sameDay : '[आज] LT',
        nextDay : '[कल] LT',
        nextWeek : 'dddd, LT',
        lastDay : '[कल] LT',
        lastWeek : '[पिछले] dddd, LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : '%s में',
        past : '%s पहले',
        s : 'कुछ ही क्षण',
        ss : '%d सेकंड',
        m : 'एक मिनट',
        mm : '%d मिनट',
        h : 'एक घंटा',
        hh : '%d घंटे',
        d : 'एक दिन',
        dd : '%d दिन',
        M : 'एक महीने',
        MM : '%d महीने',
        y : 'एक वर्ष',
        yy : '%d वर्ष'
    },
    preparse: function (string) {
        return string.replace(/[१२३४५६७८९०]/g, function (match) {
            return numberMap[match];
        });
    },
    postformat: function (string) {
        return string.replace(/\d/g, function (match) {
            return symbolMap[match];
        });
    },
    // Hindi notation for meridiems are quite fuzzy in practice. While there exists
    // a rigid notion of a 'Pahar' it is not used as rigidly in modern Hindi.
    meridiemParse: /रात|सुबह|दोपहर|शाम/,
    meridiemHour : function (hour, meridiem) {
        if (hour === 12) {
            hour = 0;
        }
        if (meridiem === 'रात') {
            return hour < 4 ? hour : hour + 12;
        } else if (meridiem === 'सुबह') {
            return hour;
        } else if (meridiem === 'दोपहर') {
            return hour >= 10 ? hour : hour + 12;
        } else if (meridiem === 'शाम') {
            return hour + 12;
        }
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 4) {
            return 'रात';
        } else if (hour < 10) {
            return 'सुबह';
        } else if (hour < 17) {
            return 'दोपहर';
        } else if (hour < 20) {
            return 'शाम';
        } else {
            return 'रात';
        }
    },
    week : {
        dow : 0, // Sunday is the first day of the week.
        doy : 6  // The week that contains Jan 1st is the first week of the year.
    }
});

return hi;

})));


/***/ }),

/***/ "3Egu":
/*!*****************************************************************!*\
  !*** ./node_modules/@jupyterlab/vdom-extension/style/index.css ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "fHvq");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "3Fdi":
/*!******************************************!*\
  !*** ./node_modules/lodash/_toSource.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/** Used for built-in method references. */
var funcProto = Function.prototype;

/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;

/**
 * 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 '';
}

module.exports = toSource;


/***/ }),

/***/ "3GB9":
/*!***************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/outputarea/style/index.css ***!
  \***************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n/*-----------------------------------------------------------------------------\n| Private CSS variables\n|----------------------------------------------------------------------------*/\n\n:root {\n}\n\n/*-----------------------------------------------------------------------------\n| Main OutputArea\n| OutputArea has a list of Outputs\n|----------------------------------------------------------------------------*/\n\n.jp-OutputArea {\n  overflow-y: auto;\n}\n\n.jp-OutputArea-child {\n  display: flex;\n  flex-direction: row;\n}\n\n.jp-OutputPrompt {\n  flex: 0 0 var(--jp-cell-prompt-width);\n  color: var(--jp-cell-outprompt-font-color);\n  font-family: var(--jp-cell-prompt-font-family);\n  padding: var(--jp-code-padding);\n  letter-spacing: var(--jp-cell-prompt-letter-spacing);\n  line-height: var(--jp-code-line-height);\n  font-size: var(--jp-code-font-size);\n  border: var(--jp-border-width) solid transparent;\n  opacity: var(--jp-cell-prompt-opacity);\n  /* Right align prompt text, don't wrap to handle large prompt numbers */\n  text-align: right;\n  white-space: nowrap;\n  overflow: hidden;\n  text-overflow: ellipsis;\n  /* Disable text selection */\n  -webkit-user-select: none;\n  -moz-user-select: none;\n  -ms-user-select: none;\n  user-select: none;\n}\n\n.jp-OutputArea-output {\n  height: auto;\n  overflow-x: auto;\n  user-select: text;\n  -moz-user-select: text;\n  -webkit-user-select: text;\n  -ms-user-select: text;\n}\n\n.jp-OutputArea-child .jp-OutputArea-output {\n  flex-grow: 1;\n  flex-shrink: 1;\n}\n\n/**\n * Isolated output.\n */\n.jp-OutputArea-output.jp-mod-isolated {\n  width: 100%;\n  display: block;\n}\n\n/*\nWhen drag events occur, `p-mod-override-cursor` is added to the body.\nBecause iframes steal all cursor events, the following two rules are necessary\nto suppress pointer events while resize drags are occurring. There may be a\nbetter solution to this problem.\n*/\nbody.p-mod-override-cursor .jp-OutputArea-output.jp-mod-isolated {\n  position: relative;\n}\n\nbody.p-mod-override-cursor .jp-OutputArea-output.jp-mod-isolated:before {\n  content: '';\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background: transparent;\n}\n\n/* pre */\n\n.jp-OutputArea-output pre {\n  border: none;\n  margin: 0px;\n  padding: 0px;\n  overflow-x: auto;\n  overflow-y: auto;\n  word-break: break-all;\n  word-wrap: break-word;\n  white-space: pre-wrap;\n}\n\n/* tables */\n\n.jp-OutputArea-output.jp-RenderedHTMLCommon table {\n  margin-left: 0;\n  margin-right: 0;\n}\n\n/* Hide the gutter in case of\n *  - nested output areas (e.g. in the case of output widgets)\n *  - mirrored output areas\n */\n.jp-OutputArea .jp-OutputArea .jp-OutputArea-prompt {\n  display: none;\n}\n\n/*-----------------------------------------------------------------------------\n| executeResult is added to any Output-result for the display of the object\n| returned by a cell\n|----------------------------------------------------------------------------*/\n\n.jp-OutputArea-output.jp-OutputArea-executeResult {\n  margin-left: 0px;\n  flex: 1 1 auto;\n}\n\n.jp-OutputArea-executeResult.jp-RenderedText {\n  padding-top: var(--jp-code-padding);\n}\n\n/*-----------------------------------------------------------------------------\n| The Stdin output\n|----------------------------------------------------------------------------*/\n\n.jp-OutputArea-stdin {\n  line-height: var(--jp-code-line-height);\n  padding-top: var(--jp-code-padding);\n  display: flex;\n}\n\n.jp-Stdin-prompt {\n  color: var(--jp-content-font-color0);\n  padding-right: var(--jp-code-padding);\n  vertical-align: baseline;\n  flex: 0 0 auto;\n}\n\n.jp-Stdin-input {\n  font-family: var(--jp-code-font-family);\n  font-size: inherit;\n  color: inherit;\n  background-color: inherit;\n  width: auto;\n  /* make sure input baseline aligns with prompt */\n  vertical-align: baseline;\n  /* padding + margin = 0.5em between prompt and cursor */\n  padding: 0em 0.25em;\n  margin: 0em 0.25em;\n  flex: 0 0 70%;\n}\n\n.jp-Stdin-input:focus {\n  box-shadow: none;\n}\n\n/*-----------------------------------------------------------------------------\n| Output Area View\n|----------------------------------------------------------------------------*/\n\n.jp-LinkedOutputView .jp-OutputArea {\n  height: 100%;\n  display: block;\n}\n\n.jp-LinkedOutputView .jp-OutputArea-output:only-child {\n  height: 100%;\n}\n", ""]);

// exports


/***/ }),

/***/ "3GJH":
/*!**********************************************************!*\
  !*** ./node_modules/core-js/library/fn/object/create.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(/*! ../../modules/es6.object.create */ "lCc8");
var $Object = __webpack_require__(/*! ../../modules/_core */ "WEpk").Object;
module.exports = function create(P, D) {
  return $Object.create(P, D);
};


/***/ }),

/***/ "3HS5":
/*!***********************************************!*\
  !*** ./node_modules/source-map/source-map.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/*
 * Copyright 2009-2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE.txt or:
 * http://opensource.org/licenses/BSD-3-Clause
 */
exports.SourceMapGenerator = __webpack_require__(/*! ./lib/source-map-generator */ "UCR5").SourceMapGenerator;
exports.SourceMapConsumer = __webpack_require__(/*! ./lib/source-map-consumer */ "qJsZ").SourceMapConsumer;
exports.SourceNode = __webpack_require__(/*! ./lib/source-node */ "3ASw").SourceNode;


/***/ }),

/***/ "3HVJ":
/*!**************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/search.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




var isNumeric = __webpack_require__(/*! fast-isnumeric */ "GbLo");
var loggers = __webpack_require__(/*! ./loggers */ "rhNM");
var identity = __webpack_require__(/*! ./identity */ "MGx7");

// don't trust floating point equality - fraction of bin size to call
// "on the line" and ensure that they go the right way specified by
// linelow
var roundingError = 1e-9;


/**
 * findBin - find the bin for val - note that it can return outside the
 * bin range any pos. or neg. integer for linear bins, or -1 or
 * bins.length-1 for explicit.
 * bins is either an object {start,size,end} or an array length #bins+1
 * bins can be either increasing or decreasing but must be monotonic
 * for linear bins, we can just calculate. For listed bins, run a binary
 * search linelow (truthy) says the bin boundary should be attributed to
 * the lower bin rather than the default upper bin
 */
exports.findBin = function(val, bins, linelow) {
    if(isNumeric(bins.start)) {
        return linelow ?
            Math.ceil((val - bins.start) / bins.size - roundingError) - 1 :
            Math.floor((val - bins.start) / bins.size + roundingError);
    }
    else {
        var n1 = 0;
        var n2 = bins.length;
        var c = 0;
        var binSize = (n2 > 1) ? (bins[n2 - 1] - bins[0]) / (n2 - 1) : 1;
        var n, test;
        if(binSize >= 0) {
            test = linelow ? lessThan : lessOrEqual;
        } else {
            test = linelow ? greaterOrEqual : greaterThan;
        }
        val += binSize * roundingError * (linelow ? -1 : 1) * (binSize >= 0 ? 1 : -1);
        // c is just to avoid infinite loops if there's an error
        while(n1 < n2 && c++ < 100) {
            n = Math.floor((n1 + n2) / 2);
            if(test(bins[n], val)) n1 = n + 1;
            else n2 = n;
        }
        if(c > 90) loggers.log('Long binary search...');
        return n1 - 1;
    }
};

function lessThan(a, b) { return a < b; }
function lessOrEqual(a, b) { return a <= b; }
function greaterThan(a, b) { return a > b; }
function greaterOrEqual(a, b) { return a >= b; }

exports.sorterAsc = function(a, b) { return a - b; };
exports.sorterDes = function(a, b) { return b - a; };

/**
 * find distinct values in an array, lumping together ones that appear to
 * just be off by a rounding error
 * return the distinct values and the minimum difference between any two
 */
exports.distinctVals = function(valsIn) {
    var vals = valsIn.slice();  // otherwise we sort the original array...
    vals.sort(exports.sorterAsc);

    var l = vals.length - 1;
    var minDiff = (vals[l] - vals[0]) || 1;
    var errDiff = minDiff / (l || 1) / 10000;
    var v2 = [vals[0]];

    for(var i = 0; i < l; i++) {
        // make sure values aren't just off by a rounding error
        if(vals[i + 1] > vals[i] + errDiff) {
            minDiff = Math.min(minDiff, vals[i + 1] - vals[i]);
            v2.push(vals[i + 1]);
        }
    }

    return {vals: v2, minDiff: minDiff};
};

/**
 * return the smallest element from (sorted) array arrayIn that's bigger than val,
 * or (reverse) the largest element smaller than val
 * used to find the best tick given the minimum (non-rounded) tick
 * particularly useful for date/time where things are not powers of 10
 * binary search is probably overkill here...
 */
exports.roundUp = function(val, arrayIn, reverse) {
    var low = 0;
    var high = arrayIn.length - 1;
    var mid;
    var c = 0;
    var dlow = reverse ? 0 : 1;
    var dhigh = reverse ? 1 : 0;
    var rounded = reverse ? Math.ceil : Math.floor;
    // c is just to avoid infinite loops if there's an error
    while(low < high && c++ < 100) {
        mid = rounded((low + high) / 2);
        if(arrayIn[mid] <= val) low = mid + dlow;
        else high = mid - dhigh;
    }
    return arrayIn[low];
};

/**
 * Tweak to Array.sort(sortFn) that improves performance for pre-sorted arrays
 *
 * Note that newer browsers (such as Chrome v70+) are starting to pick up
 * on pre-sorted arrays which may render the following optimization unnecessary
 * in the future.
 *
 * Motivation: sometimes we need to sort arrays but the input is likely to
 * already be sorted. Browsers don't seem to pick up on pre-sorted arrays,
 * and in fact Chrome is actually *slower* sorting pre-sorted arrays than purely
 * random arrays. FF is at least faster if the array is pre-sorted, but still
 * not as fast as it could be.
 * Here's how this plays out sorting a length-1e6 array:
 *
 * Calls to Sort FN  |  Chrome bare  |  FF bare  |  Chrome tweak  |  FF tweak
 *                   |  v68.0 Mac    |  v61.0 Mac|                |
 * ------------------+---------------+-----------+----------------+------------
 * ordered           |  30.4e6       |  10.1e6   |  1e6           |  1e6
 * reversed          |  29.4e6       |  9.9e6    |  1e6 + reverse |  1e6 + reverse
 * random            |  ~21e6        |  ~18.7e6  |  ~21e6         |  ~18.7e6
 *
 * So this is a substantial win for pre-sorted (ordered or exactly reversed)
 * arrays. Including this wrapper on an unsorted array adds a penalty that will
 * in general be only a few calls to the sort function. The only case this
 * penalty will be significant is if the array is mostly sorted but there are
 * a few unsorted items near the end, but the penalty is still at most N calls
 * out of (for N=1e6) ~20N total calls
 *
 * @param {Array} array: the array, to be sorted in place
 * @param {function} sortFn: As in Array.sort, function(a, b) that puts
 *     item a before item b if the return is negative, a after b if positive,
 *     and no change if zero.
 * @return {Array}: the original array, sorted in place.
 */
exports.sort = function(array, sortFn) {
    var notOrdered = 0;
    var notReversed = 0;
    for(var i = 1; i < array.length; i++) {
        var pairOrder = sortFn(array[i], array[i - 1]);
        if(pairOrder < 0) notOrdered = 1;
        else if(pairOrder > 0) notReversed = 1;
        if(notOrdered && notReversed) return array.sort(sortFn);
    }
    return notReversed ? array : array.reverse();
};

/**
 * find index in array 'arr' that minimizes 'fn'
 *
 * @param {array} arr : array where to search
 * @param {fn (optional)} fn : function to minimize,
 *   if not given, fn is the identity function
 * @return {integer}
 */
exports.findIndexOfMin = function(arr, fn) {
    fn = fn || identity;

    var min = Infinity;
    var ind;

    for(var i = 0; i < arr.length; i++) {
        var v = fn(arr[i]);
        if(v < min) {
            min = v;
            ind = i;
        }
    }
    return ind;
};


/***/ }),

/***/ "3Jol":
/*!*****************************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/previous-map.js ***!
  \*****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {

exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _sourceMap = __webpack_require__(/*! source-map */ "3HS5");

var _sourceMap2 = _interopRequireDefault(_sourceMap);

var _path = __webpack_require__(/*! path */ "33yf");

var _path2 = _interopRequireDefault(_path);

var _fs = __webpack_require__(/*! fs */ 9);

var _fs2 = _interopRequireDefault(_fs);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function fromBase64(str) {
    if (Buffer) {
        if (Buffer.from && Buffer.from !== Uint8Array.from) {
            return Buffer.from(str, 'base64').toString();
        } else {
            return new Buffer(str, 'base64').toString();
        }
    } else {
        return window.atob(str);
    }
}

/**
 * Source map information from input CSS.
 * For example, source map after Sass compiler.
 *
 * This class will automatically find source map in input CSS or in file system
 * near input file (according `from` option).
 *
 * @example
 * const root = postcss.parse(css, { from: 'a.sass.css' });
 * root.input.map //=> PreviousMap
 */

var PreviousMap = function () {

    /**
     * @param {string}         css    - input CSS source
     * @param {processOptions} [opts] - {@link Processor#process} options
     */
    function PreviousMap(css, opts) {
        _classCallCheck(this, PreviousMap);

        this.loadAnnotation(css);
        /**
         * @member {boolean} - Was source map inlined by data-uri to input CSS.
         */
        this.inline = this.startWith(this.annotation, 'data:');

        var prev = opts.map ? opts.map.prev : undefined;
        var text = this.loadMap(opts.from, prev);
        if (text) this.text = text;
    }

    /**
     * Create a instance of `SourceMapGenerator` class
     * from the `source-map` library to work with source map information.
     *
     * It is lazy method, so it will create object only on first call
     * and then it will use cache.
     *
     * @return {SourceMapGenerator} object with source map information
     */


    PreviousMap.prototype.consumer = function consumer() {
        if (!this.consumerCache) {
            this.consumerCache = new _sourceMap2.default.SourceMapConsumer(this.text);
        }
        return this.consumerCache;
    };

    /**
     * Does source map contains `sourcesContent` with input source text.
     *
     * @return {boolean} Is `sourcesContent` present
     */


    PreviousMap.prototype.withContent = function withContent() {
        return !!(this.consumer().sourcesContent && this.consumer().sourcesContent.length > 0);
    };

    PreviousMap.prototype.startWith = function startWith(string, start) {
        if (!string) return false;
        return string.substr(0, start.length) === start;
    };

    PreviousMap.prototype.loadAnnotation = function loadAnnotation(css) {
        var match = css.match(/\/\*\s*# sourceMappingURL=(.*)\s*\*\//);
        if (match) this.annotation = match[1].trim();
    };

    PreviousMap.prototype.decodeInline = function decodeInline(text) {
        // data:application/json;charset=utf-8;base64,
        // data:application/json;charset=utf8;base64,
        // data:application/json;base64,
        var baseUri = /^data:application\/json;(?:charset=utf-?8;)?base64,/;
        var uri = 'data:application/json,';

        if (this.startWith(text, uri)) {
            return decodeURIComponent(text.substr(uri.length));
        } else if (baseUri.test(text)) {
            return fromBase64(text.substr(RegExp.lastMatch.length));
        } else {
            var encoding = text.match(/data:application\/json;([^,]+),/)[1];
            throw new Error('Unsupported source map encoding ' + encoding);
        }
    };

    PreviousMap.prototype.loadMap = function loadMap(file, prev) {
        if (prev === false) return false;

        if (prev) {
            if (typeof prev === 'string') {
                return prev;
            } else if (typeof prev === 'function') {
                var prevPath = prev(file);
                if (prevPath && _fs2.default.existsSync && _fs2.default.existsSync(prevPath)) {
                    return _fs2.default.readFileSync(prevPath, 'utf-8').toString().trim();
                } else {
                    throw new Error('Unable to load previous source map: ' + prevPath.toString());
                }
            } else if (prev instanceof _sourceMap2.default.SourceMapConsumer) {
                return _sourceMap2.default.SourceMapGenerator.fromSourceMap(prev).toString();
            } else if (prev instanceof _sourceMap2.default.SourceMapGenerator) {
                return prev.toString();
            } else if (this.isMap(prev)) {
                return JSON.stringify(prev);
            } else {
                throw new Error('Unsupported previous source map format: ' + prev.toString());
            }
        } else if (this.inline) {
            return this.decodeInline(this.annotation);
        } else if (this.annotation) {
            var map = this.annotation;
            if (file) map = _path2.default.join(_path2.default.dirname(file), map);

            this.root = _path2.default.dirname(map);
            if (_fs2.default.existsSync && _fs2.default.existsSync(map)) {
                return _fs2.default.readFileSync(map, 'utf-8').toString().trim();
            } else {
                return false;
            }
        }
    };

    PreviousMap.prototype.isMap = function isMap(map) {
        if ((typeof map === 'undefined' ? 'undefined' : _typeof(map)) !== 'object') return false;
        return typeof map.mappings === 'string' || typeof map._mappings === 'string';
    };

    return PreviousMap;
}();

exports.default = PreviousMap;
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64, 

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../buffer/index.js */ "tjlA").Buffer))

/***/ }),

/***/ "3L66":
/*!**************************************************!*\
  !*** ./node_modules/lodash/isArrayLikeObject.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isArrayLike = __webpack_require__(/*! ./isArrayLike */ "MMmD"),
    isObjectLike = __webpack_require__(/*! ./isObjectLike */ "ExA7");

/**
 * 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);
}

module.exports = isArrayLikeObject;


/***/ }),

/***/ "3LHp":
/*!******************************************************!*\
  !*** ./node_modules/react-paginate/dist/PageView.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PageView = function PageView(props) {
  var pageClassName = props.pageClassName;
  var pageLinkClassName = props.pageLinkClassName;

  var onClick = props.onClick;
  var href = props.href;

  var ariaLabel = 'Page ' + props.page + (props.extraAriaContext ? ' ' + props.extraAriaContext : '');
  var ariaCurrent = null;

  if (props.selected) {
    ariaCurrent = 'page';
    ariaLabel = 'Page ' + props.page + ' is your current page';

    if (typeof pageClassName !== 'undefined') {
      pageClassName = pageClassName + ' ' + props.activeClassName;
    } else {
      pageClassName = props.activeClassName;
    }

    if (typeof pageLinkClassName !== 'undefined') {
      pageLinkClassName = pageLinkClassName;

      if (typeof props.activeLinkClassName !== 'undefined') {
        pageLinkClassName = pageLinkClassName + ' ' + props.activeLinkClassName;
      }
    } else {
      pageLinkClassName = props.activeLinkClassName;
    }
  }

  return _react2.default.createElement(
    'li',
    { className: pageClassName },
    _react2.default.createElement(
      'a',
      { onClick: onClick,
        role: 'button',
        className: pageLinkClassName,
        href: href,
        tabIndex: '0',
        'aria-label': ariaLabel,
        'aria-current': ariaCurrent,
        onKeyPress: onClick },
      props.page
    )
  );
};

exports.default = PageView;
//# sourceMappingURL=PageView.js.map

/***/ }),

/***/ "3MVk":
/*!*********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotSurfaceIcon.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotSurfaceIcon = function PlotSurfaceIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M23.375 15.75c-1.813-.563-2.813-3-2.813-3-.063-.25-.563-1.313-.563-1.563a93.2 93.2 0 0 1-.688-2.125l-.375-.813c-.25-.5-.688-1.375-1.25-2.063l-.313-.313-.25-.188c-.375-.25-.688-.375-1.063-.375s-1.063.188-1.563.688l-.5.688a5.836 5.836 0 0 1-.313.5c-.125.25-.313.563-.438.875l.125-.25-.375.75s-.438 1.063-.563 1.563c0 0-.25.75-.313 1.125 0-.125.063-.313.063-.438l-.313 1.063c-.25.438-.5 1.125-.5 1.125-.5.688-.875 2-3.188 2.875l-2.938 1-5.25 1.813 16 8 16-8zm-11.312-4.312c0 .063-.063.125-.125.188.063-.063.063-.125.125-.188z' })
    );
};

exports.default = PlotSurfaceIcon;

/***/ }),

/***/ "3Mkv":
/*!***********************************************************************!*\
  !*** ./node_modules/@jupyterlab/codemirror/lib/codemirror-ipython.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const codemirror_1 = __importDefault(__webpack_require__(/*! codemirror */ "VrN/"));
__webpack_require__(/*! codemirror/mode/meta */ "8EBN");
__webpack_require__(/*! codemirror/mode/python/python */ "25Eh");
/**
 * Define an IPython codemirror mode.
 *
 * It is a slightly altered Python Mode with a `?` operator.
 */
codemirror_1.default.defineMode('ipython', (config, modeOptions) => {
    let pythonConf = {};
    for (let prop in modeOptions) {
        if (modeOptions.hasOwnProperty(prop)) {
            pythonConf[prop] = modeOptions[prop];
        }
    }
    pythonConf.name = 'python';
    pythonConf.singleOperators = new RegExp('^[\\+\\-\\*/%&|@\\^~<>!\\?]');
    pythonConf.identifiers = new RegExp('^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*');
    return codemirror_1.default.getMode(config, pythonConf);
}, 'python');
codemirror_1.default.defineMIME('text/x-ipython', 'ipython');
codemirror_1.default.modeInfo.push({
    ext: [],
    mime: 'text/x-ipython',
    mode: 'ipython',
    name: 'ipython'
});


/***/ }),

/***/ "3Mxs":
/*!*******************************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/text_editors/RichText/configuration.js ***!
  \*******************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.INLINE_STYLES = exports.STYLE_MAP = exports.STYLES_TO_HTML_TAGS = exports.ITALIC = exports.BOLD = exports.LINK = exports.SUBSCRIPT = exports.SUPERSCRIPT = undefined;

var _STYLES_TO_HTML_TAGS, _STYLE_MAP;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _draftJsUtils = __webpack_require__(/*! draft-js-utils */ "24WU");

var _plotlyIcons = __webpack_require__(/*! plotly-icons */ "hwSx");

var _constants = __webpack_require__(/*! ../../../../lib/constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var SUPERSCRIPT = exports.SUPERSCRIPT = 'SUPERSCRIPT';
var SUBSCRIPT = exports.SUBSCRIPT = 'SUBSCRIPT';
var LINK = exports.LINK = 'LINK';

var BOLD = _draftJsUtils.INLINE_STYLE.BOLD,
    ITALIC = _draftJsUtils.INLINE_STYLE.ITALIC;
exports.BOLD = BOLD;
exports.ITALIC = ITALIC;
var STYLES_TO_HTML_TAGS = exports.STYLES_TO_HTML_TAGS = (_STYLES_TO_HTML_TAGS = {}, _defineProperty(_STYLES_TO_HTML_TAGS, BOLD, { element: 'b' }), _defineProperty(_STYLES_TO_HTML_TAGS, ITALIC, { element: 'i' }), _defineProperty(_STYLES_TO_HTML_TAGS, SUPERSCRIPT, { element: 'sup' }), _defineProperty(_STYLES_TO_HTML_TAGS, SUBSCRIPT, { element: 'sub' }), _defineProperty(_STYLES_TO_HTML_TAGS, LINK, { element: 'a' }), _STYLES_TO_HTML_TAGS);

var STYLE_MAP = exports.STYLE_MAP = (_STYLE_MAP = {}, _defineProperty(_STYLE_MAP, BOLD, {
  fontWeight: 'bolder'
}), _defineProperty(_STYLE_MAP, ITALIC, {
  fontStyle: 'italic'
}), _defineProperty(_STYLE_MAP, SUBSCRIPT, {
  /*
       * Can't use text-align; IE renders `text-bottom` properly, but
       * FF doesn't (same height as `bottom`). Chrome doesn't understand
       * `text-align: bottom`. Use relative positioning instead.
       */
  lineHeight: 0,
  fontSize: '65%',
  position: 'relative',
  bottom: '-3px'
}), _defineProperty(_STYLE_MAP, SUPERSCRIPT, {
  /*
       * Can't use text-align; IE renders `text-top` properly, but
       * FF doesn't (same height as `top`). Chrome doesn't understand
       * `text-align: top`. Use relative positioning instead.
       */
  lineHeight: 0,
  fontSize: '65%',
  position: 'relative',
  top: '-5px'
}), _defineProperty(_STYLE_MAP, LINK, {
  color: _constants.COLORS.editorLink,
  linkDecoration: 'none',
  cursor: 'pointer'
}), _STYLE_MAP);

var INLINE_STYLES = exports.INLINE_STYLES = [{
  label: _react2.default.createElement(
    'span',
    { style: STYLE_MAP[BOLD] },
    'B'
  ),
  value: BOLD
}, {
  label: _react2.default.createElement(
    'span',
    { style: STYLE_MAP[ITALIC] },
    'I'
  ),
  value: ITALIC
}, {
  label: _react2.default.createElement(
    'span',
    null,
    'x',
    _react2.default.createElement(
      'span',
      { style: STYLE_MAP[SUBSCRIPT] },
      '2'
    )
  ),
  value: SUBSCRIPT
}, {
  label: _react2.default.createElement(
    'span',
    null,
    'x',
    _react2.default.createElement(
      'span',
      { style: STYLE_MAP[SUPERSCRIPT] },
      '2'
    )
  ),
  value: SUPERSCRIPT
}, {
  label: _react2.default.createElement(
    'span',
    null,
    _react2.default.createElement(_plotlyIcons.LinkIcon, { className: 'icon-link' })
  ),
  value: LINK
}];
//# sourceMappingURL=configuration.js.map

/***/ }),

/***/ "3QZj":
/*!*****************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeChoroplethIcon.js ***!
  \*****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeChoroplethIcon = function TraceTypeChoroplethIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement('path', { fill: 'none', d: 'M0 0h46v46H0z' }),
        _react2.default.createElement('path', { fill: '#27d1f0', stroke: '#fff', d: 'M32.05 26.375l-2.3 3.45-4.6 1.15-2.3-2.3H19.4l-6.15 1.15-3.45-2.3 3.85-4.6v-3.45h5.163l4.187 3 4.45-3 9.2 6.9h-4.6z', strokeLinecap: 'round', strokeLinejoin: 'round' }),
        _react2.default.createElement('path', { fill: '#1d9bfb', stroke: '#fff', d: 'M36.65 26.375l-9.2-6.9-4.45 3-4.187-3H13.65l-2.875-1.725v-2.3l-1.15-1.15-1.15 1.15-1.15-1.15V9.7h2.3l2.3-1.15h2.3l3.45 2.3h3.45l4.6-2.3 3.45 3.45-3.45 3.45h5.75v-2.3h3.45v1.15l1.15 1.15 1.15-1.15 3.45 3.45v3.45H36.65v5.175zm-9.775 7.475L25.725 35h-1.15l.575-4.025-2.3-2.3H19.4l-6.15 1.15 7.875 4.025v2.3l3.45 2.3h2.3l1.15-1.15V35l-1.15-1.15z', strokeLinecap: 'round', strokeLinejoin: 'round' })
    );
};

exports.default = TraceTypeChoroplethIcon;

/***/ }),

/***/ "3UD+":
/*!*******************************************!*\
  !*** (webpack)/buildin/harmony-module.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = function(originalModule) {
	if (!originalModule.webpackPolyfill) {
		var module = Object.create(originalModule);
		// module.parent = undefined by default
		if (!module.children) module.children = [];
		Object.defineProperty(module, "loaded", {
			enumerable: true,
			get: function() {
				return module.l;
			}
		});
		Object.defineProperty(module, "id", {
			enumerable: true,
			get: function() {
				return module.i;
			}
		});
		Object.defineProperty(module, "exports", {
			enumerable: true
		});
		module.webpackPolyfill = 1;
	}
	return module;
};


/***/ }),

/***/ "3W1w":
/*!*************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotPolarFilledIcon.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotPolarFilledIcon = function PlotPolarFilledIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M19.188 7.375c2.25.125 4.5 1.063 6.25 2.563l-6.25 6.313zm1.062 9.563h6.063c-.125-1.25-.75-3.125-1.75-4.313zm5.625 7c1.375-1.625 2.25-3.438 2.375-5.688h-8zM19.188 29a10.928 10.928 0 0 0 6.813-2.813l-6.813-6.813zm-1.25 1.438V19.375l-7.813 7.813a13.045 13.045 0 0 0 7.813 3.25zM4.875 18.25C5.063 21.438 6.313 24.563 8.5 27l8.625-8.75zm2.75-10.875c-2.375 2.688-3.75 6.375-3.875 9.563h13.375zm10.313-5.75c-3.563.188-7.438 1.688-10.25 4.313l10.25 10.313z' })
    );
};

exports.default = PlotPolarFilledIcon;

/***/ }),

/***/ "3WF5":
/*!************************************!*\
  !*** ./node_modules/lodash/map.js ***!
  \************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var arrayMap = __webpack_require__(/*! ./_arrayMap */ "eUgh"),
    baseIteratee = __webpack_require__(/*! ./_baseIteratee */ "ut/Y"),
    baseMap = __webpack_require__(/*! ./_baseMap */ "l9OW"),
    isArray = __webpack_require__(/*! ./isArray */ "Z0cm");

/**
 * 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, baseIteratee(iteratee, 3));
}

module.exports = map;


/***/ }),

/***/ "3Y3P":
/*!**************************************************!*\
  !*** ./node_modules/xterm/lib/SelectionModel.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var SelectionModel = (function () {
    function SelectionModel(_terminal) {
        this._terminal = _terminal;
        this.clearSelection();
    }
    SelectionModel.prototype.clearSelection = function () {
        this.selectionStart = null;
        this.selectionEnd = null;
        this.isSelectAllActive = false;
        this.selectionStartLength = 0;
    };
    Object.defineProperty(SelectionModel.prototype, "finalSelectionStart", {
        get: function () {
            if (this.isSelectAllActive) {
                return [0, 0];
            }
            if (!this.selectionEnd || !this.selectionStart) {
                return this.selectionStart;
            }
            return this.areSelectionValuesReversed() ? this.selectionEnd : this.selectionStart;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(SelectionModel.prototype, "finalSelectionEnd", {
        get: function () {
            if (this.isSelectAllActive) {
                return [this._terminal.cols, this._terminal.buffer.ybase + this._terminal.rows - 1];
            }
            if (!this.selectionStart) {
                return null;
            }
            if (!this.selectionEnd || this.areSelectionValuesReversed()) {
                return [this.selectionStart[0] + this.selectionStartLength, this.selectionStart[1]];
            }
            if (this.selectionStartLength) {
                if (this.selectionEnd[1] === this.selectionStart[1]) {
                    return [Math.max(this.selectionStart[0] + this.selectionStartLength, this.selectionEnd[0]), this.selectionEnd[1]];
                }
            }
            return this.selectionEnd;
        },
        enumerable: true,
        configurable: true
    });
    SelectionModel.prototype.areSelectionValuesReversed = function () {
        var start = this.selectionStart;
        var end = this.selectionEnd;
        if (!start || !end) {
            return false;
        }
        return start[1] > end[1] || (start[1] === end[1] && start[0] > end[0]);
    };
    SelectionModel.prototype.onTrim = function (amount) {
        if (this.selectionStart) {
            this.selectionStart[1] -= amount;
        }
        if (this.selectionEnd) {
            this.selectionEnd[1] -= amount;
        }
        if (this.selectionEnd && this.selectionEnd[1] < 0) {
            this.clearSelection();
            return true;
        }
        if (this.selectionStart && this.selectionStart[1] < 0) {
            this.selectionStart[1] = 0;
        }
        return false;
    };
    return SelectionModel;
}());
exports.SelectionModel = SelectionModel;

//# sourceMappingURL=SelectionModel.js.map


/***/ }),

/***/ "3ZTG":
/*!**************************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/stringify.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.default = stringify;

var _stringifier = __webpack_require__(/*! ./stringifier */ "ZyGS");

var _stringifier2 = _interopRequireDefault(_stringifier);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function stringify(node, builder) {
    var str = new _stringifier2.default(builder);
    str.stringify(node);
}
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInN0cmluZ2lmeS5lczYiXSwibmFtZXMiOlsic3RyaW5naWZ5Iiwibm9kZSIsImJ1aWxkZXIiLCJzdHIiLCJTdHJpbmdpZmllciJdLCJtYXBwaW5ncyI6Ijs7O2tCQUV3QkEsUzs7QUFGeEI7Ozs7OztBQUVlLFNBQVNBLFNBQVQsQ0FBbUJDLElBQW5CLEVBQXlCQyxPQUF6QixFQUFrQztBQUM3QyxRQUFJQyxNQUFNLElBQUlDLHFCQUFKLENBQWdCRixPQUFoQixDQUFWO0FBQ0FDLFFBQUlILFNBQUosQ0FBY0MsSUFBZDtBQUNIIiwiZmlsZSI6InN0cmluZ2lmeS5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBTdHJpbmdpZmllciBmcm9tICcuL3N0cmluZ2lmaWVyJztcblxuZXhwb3J0IGRlZmF1bHQgZnVuY3Rpb24gc3RyaW5naWZ5KG5vZGUsIGJ1aWxkZXIpIHtcbiAgICBsZXQgc3RyID0gbmV3IFN0cmluZ2lmaWVyKGJ1aWxkZXIpO1xuICAgIHN0ci5zdHJpbmdpZnkobm9kZSk7XG59XG4iXX0=


/***/ }),

/***/ "3cnA":
/*!******************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/UpdateMenuAccordion.js ***!
  \******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _PlotlyFold = __webpack_require__(/*! ./PlotlyFold */ "mQPs");

var _PlotlyFold2 = _interopRequireDefault(_PlotlyFold);

var _TraceRequiredPanel = __webpack_require__(/*! ./TraceRequiredPanel */ "IBvg");

var _TraceRequiredPanel2 = _interopRequireDefault(_TraceRequiredPanel);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UpdateMenuFold = (0, _lib.connectUpdateMenuToLayout)(_PlotlyFold2.default);

var UpdateMenuAccordion = function (_Component) {
  _inherits(UpdateMenuAccordion, _Component);

  function UpdateMenuAccordion() {
    _classCallCheck(this, UpdateMenuAccordion);

    return _possibleConstructorReturn(this, (UpdateMenuAccordion.__proto__ || Object.getPrototypeOf(UpdateMenuAccordion)).apply(this, arguments));
  }

  _createClass(UpdateMenuAccordion, [{
    key: 'render',
    value: function render() {
      var _context = this.context,
          _context$fullLayout$u = _context.fullLayout.updatemenus,
          updatemenus = _context$fullLayout$u === undefined ? [] : _context$fullLayout$u,
          _ = _context.localize;
      var children = this.props.children;


      var content = updatemenus.length > 0 && updatemenus.map(function (upd, i) {
        var localizedType = {
          dropdown: _('Dropdown'),
          buttons: _('Buttons')
        };
        var menuType = localizedType[upd.type] || localizedType.dropdown;
        var activeBtn = upd.buttons.filter(function (b) {
          return b._index === upd.active;
        })[0];
        var foldName = menuType + (activeBtn ? ': ' + activeBtn.label : '');

        return _react2.default.createElement(
          UpdateMenuFold,
          { key: i, updateMenuIndex: i, name: foldName },
          children
        );
      });

      return _react2.default.createElement(
        _TraceRequiredPanel2.default,
        null,
        content ? content : null
      );
    }
  }]);

  return UpdateMenuAccordion;
}(_react.Component);

UpdateMenuAccordion.contextTypes = {
  fullLayout: _propTypes2.default.object,
  localize: _propTypes2.default.func
};

UpdateMenuAccordion.propTypes = {
  children: _propTypes2.default.node
};

exports.default = UpdateMenuAccordion;
//# sourceMappingURL=UpdateMenuAccordion.js.map

/***/ }),

/***/ "3eV8":
/*!**************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/inspector/style/index.css ***!
  \**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n/*-----------------------------------------------------------------------------\n| Variables\n|----------------------------------------------------------------------------*/\n\n:root {\n  --jp-private-inspector-tab-height: 24px;\n  --jp-private-inspector-tab-width: 60px;\n}\n\n/*-----------------------------------------------------------------------------\n| Inspector\n|----------------------------------------------------------------------------*/\n\n.jp-Inspector {\n  outline: none;\n  min-width: 120px;\n  min-height: 120px;\n}\n\n/* default inspector items: hints */\n.jp-InspectorItem.jp-HintsInspectorItem,\n.jp-InspectorItem.jp-HintsInspectorItem .p-Widget {\n  background: var(--jp-layout-color1);\n}\n\n.jp-InspectorItem.jp-HintsInspectorItem .jp-Toolbar {\n  display: none;\n}\n\n/* default inspector items: details */\n.jp-InspectorItem.jp-DetailsInspectorItem .p-Widget {\n  background: var(--jp-layout-color1);\n}\n\n/*-----------------------------------------------------------------------------\n| Inspector tabs\n|----------------------------------------------------------------------------*/\n\n.jp-Inspector .p-TabBar {\n  min-width: var(--jp-sidebar-min-width);\n  min-height: var(--jp-private-inspector-tab-height);\n  color: var(--jp-ui-font-color1);\n  font-size: var(--jp-ui-font-size1);\n}\n\n.jp-Inspector .p-TabBar .p-TabBar-tab {\n  flex-basis: var(--jp-private-inspector-tab-width);\n  min-height: var(--jp-private-inspector-tab-height);\n  min-width: var(--jp-private-inspector-tab-width);\n  padding: 0px 8px;\n  background: var(--jp-layout-color1);\n  transform: none;\n  margin-right: 0px;\n  line-height: var(--jp-private-inspector-tab-height);\n}\n\n.jp-Inspector .p-TabBar .p-TabBar-tab.p-mod-current {\n  min-height: var(--jp-private-inspector-tab-height);\n  color: var(--jp-ui-font-color0);\n  transform: none;\n  background: var(--jp-layout-color2);\n}\n\n.jp-Inspector .p-TabBar-tab:hover:not(.p-mod-current) {\n  background: var(--jp-layout-color1);\n}\n\n/*-----------------------------------------------------------------------------\n| InspectorItem\n|----------------------------------------------------------------------------*/\n\n.jp-InspectorItem {\n  display: flex;\n  border: none;\n}\n\n.jp-InspectorItem-content {\n  overflow: auto;\n  padding: 8px;\n  width: 100%;\n}\n\n.jp-InspectorItem .jp-Toolbar-button.jp-InspectorItem-clear::before {\n  content: '\\F05E'; /* ban */\n}\n\n.jp-InspectorItem .jp-Toolbar-button.jp-InspectorItem-back::before {\n  content: '\\F060'; /* arrow-left */\n}\n\n.jp-InspectorItem .jp-Toolbar-button.jp-InspectorItem-forward::before {\n  content: '\\F061'; /* arrow-right */\n}\n\n.jp-InspectorItem pre {\n  white-space: pre-wrap;\n  font-size: var(--jp-code-font-size);\n  line-height: var(--jp-code-line-height);\n  margin: 0;\n}\n", ""]);

// exports


/***/ }),

/***/ "3g5F":
/*!**********************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils/lib/styling.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * A namespace for node styling.
 */
var Styling;
(function (Styling) {
    /**
     * Style a node and its child elements with the default tag names.
     *
     * @param node - The base node.
     *
     * @param className - The optional CSS class to add to styled nodes.
     */
    function styleNode(node, className = '') {
        styleNodeByTag(node, 'select', className);
        styleNodeByTag(node, 'textarea', className);
        styleNodeByTag(node, 'input', className);
        styleNodeByTag(node, 'button', className);
    }
    Styling.styleNode = styleNode;
    /**
     * Style a node and its elements that have a given tag name.
     *
     * @param node - The base node.
     *
     * @param tagName - The html tag name to style.
     *
     * @param className - The optional CSS class to add to styled nodes.
     */
    function styleNodeByTag(node, tagName, className = '') {
        if (node.localName === tagName) {
            node.classList.add('jp-mod-styled');
        }
        if (node.localName === 'select') {
            wrapSelect(node);
        }
        let nodes = node.getElementsByTagName(tagName);
        for (let i = 0; i < nodes.length; i++) {
            let child = nodes[i];
            child.classList.add('jp-mod-styled');
            if (className) {
                child.classList.add(className);
            }
            if (tagName === 'select') {
                wrapSelect(child);
            }
        }
    }
    Styling.styleNodeByTag = styleNodeByTag;
    /**
     * Wrap a select node.
     */
    function wrapSelect(node) {
        let wrapper = document.createElement('div');
        wrapper.classList.add('jp-select-wrapper');
        node.addEventListener('focus', Private.onFocus);
        node.addEventListener('blur', Private.onFocus);
        node.classList.add('jp-mod-styled');
        if (node.parentElement) {
            node.parentElement.replaceChild(wrapper, node);
        }
        wrapper.appendChild(node);
        return wrapper;
    }
    Styling.wrapSelect = wrapSelect;
})(Styling = exports.Styling || (exports.Styling = {}));
/**
 * The namespace for module private data.
 */
var Private;
(function (Private) {
    /**
     * Handle a focus event on a styled select.
     */
    function onFocus(event) {
        let target = event.target;
        let parent = target.parentElement;
        if (!parent) {
            return;
        }
        if (event.type === 'focus') {
            parent.classList.add('jp-mod-focused');
        }
        else {
            parent.classList.remove('jp-mod-focused');
        }
    }
    Private.onFocus = onFocus;
})(Private || (Private = {}));


/***/ }),

/***/ "3hqu":
/*!*******************************************************************!*\
  !*** ./node_modules/@jupyterlab/plotly-extension/style/index.css ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "U534");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "3kwb":
/*!********************************************************!*\
  !*** ./node_modules/@phosphor/properties/lib/index.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * A class which attaches a value to an external object.
 *
 * #### Notes
 * Attached properties are used to extend the state of an object with
 * semantic data from an unrelated class. They also encapsulate value
 * creation, coercion, and notification.
 *
 * Because attached property values are stored in a hash table, which
 * in turn is stored in a WeakMap keyed on the owner object, there is
 * non-trivial storage overhead involved in their use. The pattern is
 * therefore best used for the storage of rare data.
 */
var AttachedProperty = (function () {
    /**
     * Construct a new attached property.
     *
     * @param options - The options for initializing the property.
     */
    function AttachedProperty(options) {
        this._pid = Private.nextPID();
        this.name = options.name;
        this._create = options.create;
        this._coerce = options.coerce || null;
        this._compare = options.compare || null;
        this._changed = options.changed || null;
    }
    /**
     * Get the current value of the property for a given owner.
     *
     * @param owner - The property owner of interest.
     *
     * @returns The current value of the property.
     *
     * #### Notes
     * If the value has not yet been set, the default value will be
     * computed and assigned as the current value of the property.
     */
    AttachedProperty.prototype.get = function (owner) {
        var value;
        var map = Private.ensureMap(owner);
        if (this._pid in map) {
            value = map[this._pid];
        }
        else {
            value = map[this._pid] = this._createValue(owner);
        }
        return value;
    };
    /**
     * Set the current value of the property for a given owner.
     *
     * @param owner - The property owner of interest.
     *
     * @param value - The value for the property.
     *
     * #### Notes
     * If the value has not yet been set, the default value will be
     * computed and used as the previous value for the comparison.
     */
    AttachedProperty.prototype.set = function (owner, value) {
        var oldValue;
        var map = Private.ensureMap(owner);
        if (this._pid in map) {
            oldValue = map[this._pid];
        }
        else {
            oldValue = map[this._pid] = this._createValue(owner);
        }
        var newValue = this._coerceValue(owner, value);
        this._maybeNotify(owner, oldValue, map[this._pid] = newValue);
    };
    /**
     * Explicitly coerce the current property value for a given owner.
     *
     * @param owner - The property owner of interest.
     *
     * #### Notes
     * If the value has not yet been set, the default value will be
     * computed and used as the previous value for the comparison.
     */
    AttachedProperty.prototype.coerce = function (owner) {
        var oldValue;
        var map = Private.ensureMap(owner);
        if (this._pid in map) {
            oldValue = map[this._pid];
        }
        else {
            oldValue = map[this._pid] = this._createValue(owner);
        }
        var newValue = this._coerceValue(owner, oldValue);
        this._maybeNotify(owner, oldValue, map[this._pid] = newValue);
    };
    /**
     * Get or create the default value for the given owner.
     */
    AttachedProperty.prototype._createValue = function (owner) {
        var create = this._create;
        return create(owner);
    };
    /**
     * Coerce the value for the given owner.
     */
    AttachedProperty.prototype._coerceValue = function (owner, value) {
        var coerce = this._coerce;
        return coerce ? coerce(owner, value) : value;
    };
    /**
     * Compare the old value and new value for equality.
     */
    AttachedProperty.prototype._compareValue = function (oldValue, newValue) {
        var compare = this._compare;
        return compare ? compare(oldValue, newValue) : oldValue === newValue;
    };
    /**
     * Run the change notification if the given values are different.
     */
    AttachedProperty.prototype._maybeNotify = function (owner, oldValue, newValue) {
        var changed = this._changed;
        if (changed && !this._compareValue(oldValue, newValue)) {
            changed(owner, oldValue, newValue);
        }
    };
    return AttachedProperty;
}());
exports.AttachedProperty = AttachedProperty;
/**
 * The namespace for the `AttachedProperty` class statics.
 */
(function (AttachedProperty) {
    /**
     * Clear the stored property data for the given owner.
     *
     * @param owner - The property owner of interest.
     *
     * #### Notes
     * This will clear all property values for the owner, but it will
     * **not** run the change notification for any of the properties.
     */
    function clearData(owner) {
        Private.ownerData.delete(owner);
    }
    AttachedProperty.clearData = clearData;
})(AttachedProperty = exports.AttachedProperty || (exports.AttachedProperty = {}));
exports.AttachedProperty = AttachedProperty;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * A weak mapping of property owner to property map.
     */
    Private.ownerData = new WeakMap();
    /**
     * A function which computes successive unique property ids.
     */
    Private.nextPID = (function () {
        var id = 0;
        return function () {
            var rand = Math.random();
            var stem = ("" + rand).slice(2);
            return "pid-" + stem + "-" + id++;
        };
    })();
    /**
     * Lookup the data map for the property owner.
     *
     * This will create the map if one does not already exist.
     */
    function ensureMap(owner) {
        var map = Private.ownerData.get(owner);
        if (map) {
            return map;
        }
        map = Object.create(null);
        Private.ownerData.set(owner, map);
        return map;
    }
    Private.ensureMap = ensureMap;
})(Private || (Private = {}));


/***/ }),

/***/ "3sOJ":
/*!**************************************************!*\
  !*** ./node_modules/draft-js/lib/EditorState.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule EditorState
 * @format
 * 
 */



var _assign = __webpack_require__(/*! object-assign */ "MgzW");

var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var BlockTree = __webpack_require__(/*! ./BlockTree */ "L0q3");
var ContentState = __webpack_require__(/*! ./ContentState */ "LpQA");
var EditorBidiService = __webpack_require__(/*! ./EditorBidiService */ "VSmT");
var Immutable = __webpack_require__(/*! immutable */ "JPcv");
var SelectionState = __webpack_require__(/*! ./SelectionState */ "hMpd");

var OrderedSet = Immutable.OrderedSet,
    Record = Immutable.Record,
    Stack = Immutable.Stack;


var defaultRecord = {
  allowUndo: true,
  currentContent: null,
  decorator: null,
  directionMap: null,
  forceSelection: false,
  inCompositionMode: false,
  inlineStyleOverride: null,
  lastChangeType: null,
  nativelyRenderedContent: null,
  redoStack: Stack(),
  selection: null,
  treeMap: null,
  undoStack: Stack()
};

var EditorStateRecord = Record(defaultRecord);

var EditorState = function () {
  EditorState.createEmpty = function createEmpty(decorator) {
    return EditorState.createWithContent(ContentState.createFromText(''), decorator);
  };

  EditorState.createWithContent = function createWithContent(contentState, decorator) {
    var firstKey = contentState.getBlockMap().first().getKey();
    return EditorState.create({
      currentContent: contentState,
      undoStack: Stack(),
      redoStack: Stack(),
      decorator: decorator || null,
      selection: SelectionState.createEmpty(firstKey)
    });
  };

  EditorState.create = function create(config) {
    var currentContent = config.currentContent,
        decorator = config.decorator;

    var recordConfig = _extends({}, config, {
      treeMap: generateNewTreeMap(currentContent, decorator),
      directionMap: EditorBidiService.getDirectionMap(currentContent)
    });
    return new EditorState(new EditorStateRecord(recordConfig));
  };

  EditorState.set = function set(editorState, put) {
    var map = editorState.getImmutable().withMutations(function (state) {
      var existingDecorator = state.get('decorator');
      var decorator = existingDecorator;
      if (put.decorator === null) {
        decorator = null;
      } else if (put.decorator) {
        decorator = put.decorator;
      }

      var newContent = put.currentContent || editorState.getCurrentContent();

      if (decorator !== existingDecorator) {
        var treeMap = state.get('treeMap');
        var newTreeMap;
        if (decorator && existingDecorator) {
          newTreeMap = regenerateTreeForNewDecorator(newContent, newContent.getBlockMap(), treeMap, decorator, existingDecorator);
        } else {
          newTreeMap = generateNewTreeMap(newContent, decorator);
        }

        state.merge({
          decorator: decorator,
          treeMap: newTreeMap,
          nativelyRenderedContent: null
        });
        return;
      }

      var existingContent = editorState.getCurrentContent();
      if (newContent !== existingContent) {
        state.set('treeMap', regenerateTreeForNewBlocks(editorState, newContent.getBlockMap(), newContent.getEntityMap(), decorator));
      }

      state.merge(put);
    });

    return new EditorState(map);
  };

  EditorState.prototype.toJS = function toJS() {
    return this.getImmutable().toJS();
  };

  EditorState.prototype.getAllowUndo = function getAllowUndo() {
    return this.getImmutable().get('allowUndo');
  };

  EditorState.prototype.getCurrentContent = function getCurrentContent() {
    return this.getImmutable().get('currentContent');
  };

  EditorState.prototype.getUndoStack = function getUndoStack() {
    return this.getImmutable().get('undoStack');
  };

  EditorState.prototype.getRedoStack = function getRedoStack() {
    return this.getImmutable().get('redoStack');
  };

  EditorState.prototype.getSelection = function getSelection() {
    return this.getImmutable().get('selection');
  };

  EditorState.prototype.getDecorator = function getDecorator() {
    return this.getImmutable().get('decorator');
  };

  EditorState.prototype.isInCompositionMode = function isInCompositionMode() {
    return this.getImmutable().get('inCompositionMode');
  };

  EditorState.prototype.mustForceSelection = function mustForceSelection() {
    return this.getImmutable().get('forceSelection');
  };

  EditorState.prototype.getNativelyRenderedContent = function getNativelyRenderedContent() {
    return this.getImmutable().get('nativelyRenderedContent');
  };

  EditorState.prototype.getLastChangeType = function getLastChangeType() {
    return this.getImmutable().get('lastChangeType');
  };

  /**
   * While editing, the user may apply inline style commands with a collapsed
   * cursor, intending to type text that adopts the specified style. In this
   * case, we track the specified style as an "override" that takes precedence
   * over the inline style of the text adjacent to the cursor.
   *
   * If null, there is no override in place.
   */


  EditorState.prototype.getInlineStyleOverride = function getInlineStyleOverride() {
    return this.getImmutable().get('inlineStyleOverride');
  };

  EditorState.setInlineStyleOverride = function setInlineStyleOverride(editorState, inlineStyleOverride) {
    return EditorState.set(editorState, { inlineStyleOverride: inlineStyleOverride });
  };

  /**
   * Get the appropriate inline style for the editor state. If an
   * override is in place, use it. Otherwise, the current style is
   * based on the location of the selection state.
   */


  EditorState.prototype.getCurrentInlineStyle = function getCurrentInlineStyle() {
    var override = this.getInlineStyleOverride();
    if (override != null) {
      return override;
    }

    var content = this.getCurrentContent();
    var selection = this.getSelection();

    if (selection.isCollapsed()) {
      return getInlineStyleForCollapsedSelection(content, selection);
    }

    return getInlineStyleForNonCollapsedSelection(content, selection);
  };

  EditorState.prototype.getBlockTree = function getBlockTree(blockKey) {
    return this.getImmutable().getIn(['treeMap', blockKey]);
  };

  EditorState.prototype.isSelectionAtStartOfContent = function isSelectionAtStartOfContent() {
    var firstKey = this.getCurrentContent().getBlockMap().first().getKey();
    return this.getSelection().hasEdgeWithin(firstKey, 0, 0);
  };

  EditorState.prototype.isSelectionAtEndOfContent = function isSelectionAtEndOfContent() {
    var content = this.getCurrentContent();
    var blockMap = content.getBlockMap();
    var last = blockMap.last();
    var end = last.getLength();
    return this.getSelection().hasEdgeWithin(last.getKey(), end, end);
  };

  EditorState.prototype.getDirectionMap = function getDirectionMap() {
    return this.getImmutable().get('directionMap');
  };

  /**
   * Incorporate native DOM selection changes into the EditorState. This
   * method can be used when we simply want to accept whatever the DOM
   * has given us to represent selection, and we do not need to re-render
   * the editor.
   *
   * To forcibly move the DOM selection, see `EditorState.forceSelection`.
   */


  EditorState.acceptSelection = function acceptSelection(editorState, selection) {
    return updateSelection(editorState, selection, false);
  };

  /**
   * At times, we need to force the DOM selection to be where we
   * need it to be. This can occur when the anchor or focus nodes
   * are non-text nodes, for instance. In this case, we want to trigger
   * a re-render of the editor, which in turn forces selection into
   * the correct place in the DOM. The `forceSelection` method
   * accomplishes this.
   *
   * This method should be used in cases where you need to explicitly
   * move the DOM selection from one place to another without a change
   * in ContentState.
   */


  EditorState.forceSelection = function forceSelection(editorState, selection) {
    if (!selection.getHasFocus()) {
      selection = selection.set('hasFocus', true);
    }
    return updateSelection(editorState, selection, true);
  };

  /**
   * Move selection to the end of the editor without forcing focus.
   */


  EditorState.moveSelectionToEnd = function moveSelectionToEnd(editorState) {
    var content = editorState.getCurrentContent();
    var lastBlock = content.getLastBlock();
    var lastKey = lastBlock.getKey();
    var length = lastBlock.getLength();

    return EditorState.acceptSelection(editorState, new SelectionState({
      anchorKey: lastKey,
      anchorOffset: length,
      focusKey: lastKey,
      focusOffset: length,
      isBackward: false
    }));
  };

  /**
   * Force focus to the end of the editor. This is useful in scenarios
   * where we want to programmatically focus the input and it makes sense
   * to allow the user to continue working seamlessly.
   */


  EditorState.moveFocusToEnd = function moveFocusToEnd(editorState) {
    var afterSelectionMove = EditorState.moveSelectionToEnd(editorState);
    return EditorState.forceSelection(afterSelectionMove, afterSelectionMove.getSelection());
  };

  /**
   * Push the current ContentState onto the undo stack if it should be
   * considered a boundary state, and set the provided ContentState as the
   * new current content.
   */


  EditorState.push = function push(editorState, contentState, changeType) {
    if (editorState.getCurrentContent() === contentState) {
      return editorState;
    }

    var forceSelection = changeType !== 'insert-characters';
    var directionMap = EditorBidiService.getDirectionMap(contentState, editorState.getDirectionMap());

    if (!editorState.getAllowUndo()) {
      return EditorState.set(editorState, {
        currentContent: contentState,
        directionMap: directionMap,
        lastChangeType: changeType,
        selection: contentState.getSelectionAfter(),
        forceSelection: forceSelection,
        inlineStyleOverride: null
      });
    }

    var selection = editorState.getSelection();
    var currentContent = editorState.getCurrentContent();
    var undoStack = editorState.getUndoStack();
    var newContent = contentState;

    if (selection !== currentContent.getSelectionAfter() || mustBecomeBoundary(editorState, changeType)) {
      undoStack = undoStack.push(currentContent);
      newContent = newContent.set('selectionBefore', selection);
    } else if (changeType === 'insert-characters' || changeType === 'backspace-character' || changeType === 'delete-character') {
      // Preserve the previous selection.
      newContent = newContent.set('selectionBefore', currentContent.getSelectionBefore());
    }

    var inlineStyleOverride = editorState.getInlineStyleOverride();

    // Don't discard inline style overrides for the following change types:
    var overrideChangeTypes = ['adjust-depth', 'change-block-type', 'split-block'];

    if (overrideChangeTypes.indexOf(changeType) === -1) {
      inlineStyleOverride = null;
    }

    var editorStateChanges = {
      currentContent: newContent,
      directionMap: directionMap,
      undoStack: undoStack,
      redoStack: Stack(),
      lastChangeType: changeType,
      selection: contentState.getSelectionAfter(),
      forceSelection: forceSelection,
      inlineStyleOverride: inlineStyleOverride
    };

    return EditorState.set(editorState, editorStateChanges);
  };

  /**
   * Make the top ContentState in the undo stack the new current content and
   * push the current content onto the redo stack.
   */


  EditorState.undo = function undo(editorState) {
    if (!editorState.getAllowUndo()) {
      return editorState;
    }

    var undoStack = editorState.getUndoStack();
    var newCurrentContent = undoStack.peek();
    if (!newCurrentContent) {
      return editorState;
    }

    var currentContent = editorState.getCurrentContent();
    var directionMap = EditorBidiService.getDirectionMap(newCurrentContent, editorState.getDirectionMap());

    return EditorState.set(editorState, {
      currentContent: newCurrentContent,
      directionMap: directionMap,
      undoStack: undoStack.shift(),
      redoStack: editorState.getRedoStack().push(currentContent),
      forceSelection: true,
      inlineStyleOverride: null,
      lastChangeType: 'undo',
      nativelyRenderedContent: null,
      selection: currentContent.getSelectionBefore()
    });
  };

  /**
   * Make the top ContentState in the redo stack the new current content and
   * push the current content onto the undo stack.
   */


  EditorState.redo = function redo(editorState) {
    if (!editorState.getAllowUndo()) {
      return editorState;
    }

    var redoStack = editorState.getRedoStack();
    var newCurrentContent = redoStack.peek();
    if (!newCurrentContent) {
      return editorState;
    }

    var currentContent = editorState.getCurrentContent();
    var directionMap = EditorBidiService.getDirectionMap(newCurrentContent, editorState.getDirectionMap());

    return EditorState.set(editorState, {
      currentContent: newCurrentContent,
      directionMap: directionMap,
      undoStack: editorState.getUndoStack().push(currentContent),
      redoStack: redoStack.shift(),
      forceSelection: true,
      inlineStyleOverride: null,
      lastChangeType: 'redo',
      nativelyRenderedContent: null,
      selection: newCurrentContent.getSelectionAfter()
    });
  };

  /**
   * Not for public consumption.
   */


  function EditorState(immutable) {
    _classCallCheck(this, EditorState);

    this._immutable = immutable;
  }

  /**
   * Not for public consumption.
   */


  EditorState.prototype.getImmutable = function getImmutable() {
    return this._immutable;
  };

  return EditorState;
}();

/**
 * Set the supplied SelectionState as the new current selection, and set
 * the `force` flag to trigger manual selection placement by the view.
 */


function updateSelection(editorState, selection, forceSelection) {
  return EditorState.set(editorState, {
    selection: selection,
    forceSelection: forceSelection,
    nativelyRenderedContent: null,
    inlineStyleOverride: null
  });
}

/**
 * Regenerate the entire tree map for a given ContentState and decorator.
 * Returns an OrderedMap that maps all available ContentBlock objects.
 */
function generateNewTreeMap(contentState, decorator) {
  return contentState.getBlockMap().map(function (block) {
    return BlockTree.generate(contentState, block, decorator);
  }).toOrderedMap();
}

/**
 * Regenerate tree map objects for all ContentBlocks that have changed
 * between the current editorState and newContent. Returns an OrderedMap
 * with only changed regenerated tree map objects.
 */
function regenerateTreeForNewBlocks(editorState, newBlockMap, newEntityMap, decorator) {
  var contentState = editorState.getCurrentContent().set('entityMap', newEntityMap);
  var prevBlockMap = contentState.getBlockMap();
  var prevTreeMap = editorState.getImmutable().get('treeMap');
  return prevTreeMap.merge(newBlockMap.toSeq().filter(function (block, key) {
    return block !== prevBlockMap.get(key);
  }).map(function (block) {
    return BlockTree.generate(contentState, block, decorator);
  }));
}

/**
 * Generate tree map objects for a new decorator object, preserving any
 * decorations that are unchanged from the previous decorator.
 *
 * Note that in order for this to perform optimally, decoration Lists for
 * decorators should be preserved when possible to allow for direct immutable
 * List comparison.
 */
function regenerateTreeForNewDecorator(content, blockMap, previousTreeMap, decorator, existingDecorator) {
  return previousTreeMap.merge(blockMap.toSeq().filter(function (block) {
    return decorator.getDecorations(block, content) !== existingDecorator.getDecorations(block, content);
  }).map(function (block) {
    return BlockTree.generate(content, block, decorator);
  }));
}

/**
 * Return whether a change should be considered a boundary state, given
 * the previous change type. Allows us to discard potential boundary states
 * during standard typing or deletion behavior.
 */
function mustBecomeBoundary(editorState, changeType) {
  var lastChangeType = editorState.getLastChangeType();
  return changeType !== lastChangeType || changeType !== 'insert-characters' && changeType !== 'backspace-character' && changeType !== 'delete-character';
}

function getInlineStyleForCollapsedSelection(content, selection) {
  var startKey = selection.getStartKey();
  var startOffset = selection.getStartOffset();
  var startBlock = content.getBlockForKey(startKey);

  // If the cursor is not at the start of the block, look backward to
  // preserve the style of the preceding character.
  if (startOffset > 0) {
    return startBlock.getInlineStyleAt(startOffset - 1);
  }

  // The caret is at position zero in this block. If the block has any
  // text at all, use the style of the first character.
  if (startBlock.getLength()) {
    return startBlock.getInlineStyleAt(0);
  }

  // Otherwise, look upward in the document to find the closest character.
  return lookUpwardForInlineStyle(content, startKey);
}

function getInlineStyleForNonCollapsedSelection(content, selection) {
  var startKey = selection.getStartKey();
  var startOffset = selection.getStartOffset();
  var startBlock = content.getBlockForKey(startKey);

  // If there is a character just inside the selection, use its style.
  if (startOffset < startBlock.getLength()) {
    return startBlock.getInlineStyleAt(startOffset);
  }

  // Check if the selection at the end of a non-empty block. Use the last
  // style in the block.
  if (startOffset > 0) {
    return startBlock.getInlineStyleAt(startOffset - 1);
  }

  // Otherwise, look upward in the document to find the closest character.
  return lookUpwardForInlineStyle(content, startKey);
}

function lookUpwardForInlineStyle(content, fromKey) {
  var lastNonEmpty = content.getBlockMap().reverse().skipUntil(function (_, k) {
    return k === fromKey;
  }).skip(1).skipUntil(function (block, _) {
    return block.getLength();
  }).first();

  if (lastNonEmpty) return lastNonEmpty.getInlineStyleAt(lastNonEmpty.getLength() - 1);
  return OrderedSet();
}

module.exports = EditorState;

/***/ }),

/***/ "3u4H":
/*!***************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/codeeditor/style/index.css ***!
  \***************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2016, Jupyter Development Team.\n|\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.jp-JSONEditor {\n  display: flex;\n  flex-direction: column;\n  width: 100%;\n}\n\n.jp-JSONEditor-host {\n  flex: 1 1 auto;\n  border: var(--jp-border-width) solid var(--jp-input-border-color);\n  border-radius: 0px;\n  background: var(--jp-layout-color0);\n  min-height: 50px;\n  margin-left: 12px;\n  margin-right: 12px;\n  padding: 1px;\n}\n\n.jp-JSONEditor.jp-mod-error .jp-JSONEditor-host {\n  border-color: red;\n  outline-color: red;\n}\n\n.jp-JSONEditor-header {\n  display: flex;\n  flex: 1 0 auto;\n  min-height: 13px;\n  padding: 12px;\n}\n\n.jp-JSONEditor-header label {\n  flex: 0 0 auto;\n}\n\n.jp-JSONEditor-commitButton,\n.jp-JSONEditor-revertButton,\n.jp-JSONEditor-collapser.jp-mod-collapse-enabled {\n  height: 16px;\n  width: 16px;\n  background-size: 18px;\n  background-repeat: no-repeat;\n  background-position: center;\n}\n\n.jp-JSONEditor-commitButton {\n  background-image: var(--jp-icon-checkmark);\n  margin-left: 8px;\n}\n\n.jp-JSONEditor-revertButton {\n  background-image: var(--jp-icon-undo);\n}\n\n.jp-JSONEditor-collapser.jp-mod-collapse-enabled {\n  margin-left: 6px;\n  background-image: var(--jp-icon-caretup);\n}\n\n.jp-JSONEditor-collapser.jp-mod-collapse-enabled.jp-mod-collapsed {\n  margin-left: 6px;\n  background-image: var(--jp-icon-caretdown);\n}\n\n.jp-JSONEditor-host.jp-mod-collapsed {\n  display: none;\n}\n\n.jp-JSONEditor-host.jp-mod-focused {\n  background-color: var(--jp-input-active-background);\n  border: 1px solid var(--jp-input-active-border-color);\n  box-shadow: var(--jp-input-box-shadow);\n}\n", ""]);

// exports


/***/ }),

/***/ "3ujF":
/*!*********************************************************!*\
  !*** ./node_modules/xterm/lib/renderer/ColorManager.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var DEFAULT_FOREGROUND = fromHex('#ffffff');
var DEFAULT_BACKGROUND = fromHex('#000000');
var DEFAULT_CURSOR = fromHex('#ffffff');
var DEFAULT_CURSOR_ACCENT = fromHex('#000000');
var DEFAULT_SELECTION = {
    css: 'rgba(255, 255, 255, 0.3)',
    rgba: 0xFFFFFF77
};
exports.DEFAULT_ANSI_COLORS = (function () {
    var colors = [
        fromHex('#2e3436'),
        fromHex('#cc0000'),
        fromHex('#4e9a06'),
        fromHex('#c4a000'),
        fromHex('#3465a4'),
        fromHex('#75507b'),
        fromHex('#06989a'),
        fromHex('#d3d7cf'),
        fromHex('#555753'),
        fromHex('#ef2929'),
        fromHex('#8ae234'),
        fromHex('#fce94f'),
        fromHex('#729fcf'),
        fromHex('#ad7fa8'),
        fromHex('#34e2e2'),
        fromHex('#eeeeec')
    ];
    var v = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff];
    for (var i = 0; i < 216; i++) {
        var r = v[(i / 36) % 6 | 0];
        var g = v[(i / 6) % 6 | 0];
        var b = v[i % 6];
        colors.push({
            css: "#" + toPaddedHex(r) + toPaddedHex(g) + toPaddedHex(b),
            rgba: ((r << 24) | (g << 16) | (b << 8) | 0xFF) >>> 0
        });
    }
    for (var i = 0; i < 24; i++) {
        var c = 8 + i * 10;
        var ch = toPaddedHex(c);
        colors.push({
            css: "#" + ch + ch + ch,
            rgba: ((c << 24) | (c << 16) | (c << 8) | 0xFF) >>> 0
        });
    }
    return colors;
})();
function fromHex(css) {
    return {
        css: css,
        rgba: parseInt(css.slice(1), 16) << 8 | 0xFF
    };
}
function toPaddedHex(c) {
    var s = c.toString(16);
    return s.length < 2 ? '0' + s : s;
}
var ColorManager = (function () {
    function ColorManager(document, allowTransparency) {
        this.allowTransparency = allowTransparency;
        var canvas = document.createElement('canvas');
        canvas.width = 1;
        canvas.height = 1;
        this._ctx = canvas.getContext('2d');
        this._ctx.globalCompositeOperation = 'copy';
        this._litmusColor = this._ctx.createLinearGradient(0, 0, 1, 1);
        this.colors = {
            foreground: DEFAULT_FOREGROUND,
            background: DEFAULT_BACKGROUND,
            cursor: DEFAULT_CURSOR,
            cursorAccent: DEFAULT_CURSOR_ACCENT,
            selection: DEFAULT_SELECTION,
            ansi: exports.DEFAULT_ANSI_COLORS.slice()
        };
    }
    ColorManager.prototype.setTheme = function (theme) {
        this.colors.foreground = this._parseColor(theme.foreground, DEFAULT_FOREGROUND);
        this.colors.background = this._parseColor(theme.background, DEFAULT_BACKGROUND);
        this.colors.cursor = this._parseColor(theme.cursor, DEFAULT_CURSOR, true);
        this.colors.cursorAccent = this._parseColor(theme.cursorAccent, DEFAULT_CURSOR_ACCENT, true);
        this.colors.selection = this._parseColor(theme.selection, DEFAULT_SELECTION, true);
        this.colors.ansi[0] = this._parseColor(theme.black, exports.DEFAULT_ANSI_COLORS[0]);
        this.colors.ansi[1] = this._parseColor(theme.red, exports.DEFAULT_ANSI_COLORS[1]);
        this.colors.ansi[2] = this._parseColor(theme.green, exports.DEFAULT_ANSI_COLORS[2]);
        this.colors.ansi[3] = this._parseColor(theme.yellow, exports.DEFAULT_ANSI_COLORS[3]);
        this.colors.ansi[4] = this._parseColor(theme.blue, exports.DEFAULT_ANSI_COLORS[4]);
        this.colors.ansi[5] = this._parseColor(theme.magenta, exports.DEFAULT_ANSI_COLORS[5]);
        this.colors.ansi[6] = this._parseColor(theme.cyan, exports.DEFAULT_ANSI_COLORS[6]);
        this.colors.ansi[7] = this._parseColor(theme.white, exports.DEFAULT_ANSI_COLORS[7]);
        this.colors.ansi[8] = this._parseColor(theme.brightBlack, exports.DEFAULT_ANSI_COLORS[8]);
        this.colors.ansi[9] = this._parseColor(theme.brightRed, exports.DEFAULT_ANSI_COLORS[9]);
        this.colors.ansi[10] = this._parseColor(theme.brightGreen, exports.DEFAULT_ANSI_COLORS[10]);
        this.colors.ansi[11] = this._parseColor(theme.brightYellow, exports.DEFAULT_ANSI_COLORS[11]);
        this.colors.ansi[12] = this._parseColor(theme.brightBlue, exports.DEFAULT_ANSI_COLORS[12]);
        this.colors.ansi[13] = this._parseColor(theme.brightMagenta, exports.DEFAULT_ANSI_COLORS[13]);
        this.colors.ansi[14] = this._parseColor(theme.brightCyan, exports.DEFAULT_ANSI_COLORS[14]);
        this.colors.ansi[15] = this._parseColor(theme.brightWhite, exports.DEFAULT_ANSI_COLORS[15]);
    };
    ColorManager.prototype._parseColor = function (css, fallback, allowTransparency) {
        if (allowTransparency === void 0) { allowTransparency = this.allowTransparency; }
        if (!css) {
            return fallback;
        }
        this._ctx.fillStyle = this._litmusColor;
        this._ctx.fillStyle = css;
        if (typeof this._ctx.fillStyle !== 'string') {
            console.warn("Color: " + css + " is invalid using fallback " + fallback.css);
            return fallback;
        }
        this._ctx.fillRect(0, 0, 1, 1);
        var data = this._ctx.getImageData(0, 0, 1, 1).data;
        if (!allowTransparency && data[3] !== 0xFF) {
            console.warn("Color: " + css + " is using transparency, but allowTransparency is false. " +
                ("Using fallback " + fallback.css + "."));
            return fallback;
        }
        return {
            css: css,
            rgba: (data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3]) >>> 0
        };
    };
    return ColorManager;
}());
exports.ColorManager = ColorManager;

//# sourceMappingURL=ColorManager.js.map


/***/ }),

/***/ "4+N0":
/*!**********************************************!*\
  !*** ./node_modules/mdi-react/FolderIcon.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var FolderIcon = function FolderIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M10,4H4C2.89,4 2,4.89 2,6V18C2,19.1 2.9,20 4,20H20C21.1,20 22,19.1 22,18V8C22,6.89 21.1,6 20,6H12L10,4Z' })
  );
};

module.exports = FolderIcon;


/***/ }),

/***/ "4/ic":
/*!**************************************************!*\
  !*** ./node_modules/lodash/_basePropertyDeep.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseGet = __webpack_require__(/*! ./_baseGet */ "ZWtO");

/**
 * 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);
  };
}

module.exports = basePropertyDeep;


/***/ }),

/***/ "42BV":
/*!************************************************************!*\
  !*** ./node_modules/react-day-picker/lib/src/DayPicker.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ModifiersUtils = exports.LocaleUtils = exports.DateUtils = exports.DayPicker = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _Caption = __webpack_require__(/*! ./Caption */ "AV7D");

var _Caption2 = _interopRequireDefault(_Caption);

var _Navbar = __webpack_require__(/*! ./Navbar */ "l//F");

var _Navbar2 = _interopRequireDefault(_Navbar);

var _Month = __webpack_require__(/*! ./Month */ "LPzJ");

var _Month2 = _interopRequireDefault(_Month);

var _Weekday = __webpack_require__(/*! ./Weekday */ "jsC2");

var _Weekday2 = _interopRequireDefault(_Weekday);

var _Helpers = __webpack_require__(/*! ./Helpers */ "VJCR");

var Helpers = _interopRequireWildcard(_Helpers);

var _DateUtils = __webpack_require__(/*! ./DateUtils */ "mHnu");

var DateUtils = _interopRequireWildcard(_DateUtils);

var _LocaleUtils = __webpack_require__(/*! ./LocaleUtils */ "ze2x");

var LocaleUtils = _interopRequireWildcard(_LocaleUtils);

var _ModifiersUtils = __webpack_require__(/*! ./ModifiersUtils */ "KFnn");

var ModifiersUtils = _interopRequireWildcard(_ModifiersUtils);

var _classNames = __webpack_require__(/*! ./classNames */ "ZE44");

var _classNames2 = _interopRequireDefault(_classNames);

var _keys = __webpack_require__(/*! ./keys */ "VBVY");

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var DayPicker = exports.DayPicker = function (_Component) {
  _inherits(DayPicker, _Component);

  function DayPicker(props) {
    _classCallCheck(this, DayPicker);

    var _this = _possibleConstructorReturn(this, (DayPicker.__proto__ || Object.getPrototypeOf(DayPicker)).call(this, props));

    _this.dayPicker = null;

    _this.showNextMonth = function (callback) {
      if (!_this.allowNextMonth()) {
        return;
      }
      var deltaMonths = _this.props.pagedNavigation ? _this.props.numberOfMonths : 1;
      var nextMonth = DateUtils.addMonths(_this.state.currentMonth, deltaMonths);
      _this.showMonth(nextMonth, callback);
    };

    _this.showPreviousMonth = function (callback) {
      if (!_this.allowPreviousMonth()) {
        return;
      }
      var deltaMonths = _this.props.pagedNavigation ? _this.props.numberOfMonths : 1;
      var previousMonth = DateUtils.addMonths(_this.state.currentMonth, -deltaMonths);
      _this.showMonth(previousMonth, callback);
    };

    _this.handleKeyDown = function (e) {
      e.persist();

      switch (e.keyCode) {
        case _keys.LEFT:
          if (_this.props.dir === 'rtl') {
            _this.showNextMonth();
          } else {
            _this.showPreviousMonth();
          }
          Helpers.cancelEvent(e);
          break;
        case _keys.RIGHT:
          if (_this.props.dir === 'rtl') {
            _this.showPreviousMonth();
          } else {
            _this.showNextMonth();
          }
          Helpers.cancelEvent(e);
          break;
        case _keys.UP:
          _this.showPreviousYear();
          Helpers.cancelEvent(e);
          break;
        case _keys.DOWN:
          _this.showNextYear();
          Helpers.cancelEvent(e);
          break;
        default:
          break;
      }

      if (_this.props.onKeyDown) {
        _this.props.onKeyDown(e);
      }
    };

    _this.handleDayKeyDown = function (day, modifiers, e) {
      e.persist();

      switch (e.keyCode) {
        case _keys.LEFT:
          Helpers.cancelEvent(e);
          if (_this.props.dir === 'rtl') {
            _this.focusNextDay(e.target);
          } else {
            _this.focusPreviousDay(e.target);
          }
          break;
        case _keys.RIGHT:
          Helpers.cancelEvent(e);
          if (_this.props.dir === 'rtl') {
            _this.focusPreviousDay(e.target);
          } else {
            _this.focusNextDay(e.target);
          }
          break;
        case _keys.UP:
          Helpers.cancelEvent(e);
          _this.focusPreviousWeek(e.target);
          break;
        case _keys.DOWN:
          Helpers.cancelEvent(e);
          _this.focusNextWeek(e.target);
          break;
        case _keys.ENTER:
        case _keys.SPACE:
          Helpers.cancelEvent(e);
          if (_this.props.onDayClick) {
            _this.handleDayClick(day, modifiers, e);
          }
          break;
        default:
          break;
      }
      if (_this.props.onDayKeyDown) {
        _this.props.onDayKeyDown(day, modifiers, e);
      }
    };

    _this.handleDayClick = function (day, modifiers, e) {
      e.persist();

      if (modifiers[_this.props.classNames.outside] && _this.props.enableOutsideDaysClick) {
        _this.handleOutsideDayClick(day);
      }
      if (_this.props.onDayClick) {
        _this.props.onDayClick(day, modifiers, e);
      }
    };

    _this.handleTodayButtonClick = function (e) {
      var today = new Date();
      var month = new Date(today.getFullYear(), today.getMonth());
      _this.showMonth(month);
      e.target.blur();
      if (_this.props.onTodayButtonClick) {
        e.persist();
        _this.props.onTodayButtonClick(new Date(today.getFullYear(), today.getMonth(), today.getDate()), ModifiersUtils.getModifiersForDay(today, _this.props.modifiers), e);
      }
    };

    var currentMonth = _this.getCurrentMonthFromProps(props);
    _this.state = { currentMonth: currentMonth };
    return _this;
  }

  _createClass(DayPicker, [{
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps) {
      // Changing the `month` props means changing the current displayed month
      if (prevProps.month !== this.props.month && !DateUtils.isSameMonth(prevProps.month, this.props.month)) {
        var currentMonth = this.getCurrentMonthFromProps(this.props);
        // eslint-disable-next-line react/no-did-update-set-state
        this.setState({ currentMonth: currentMonth });
      }
    }

    /**
     * Return the month to be shown in the calendar based on the component props.
     *
     * @param {Object} props
     * @returns Date
     * @memberof DayPicker
     * @private
     */

  }, {
    key: 'getCurrentMonthFromProps',
    value: function getCurrentMonthFromProps(props) {
      var initialMonth = Helpers.startOfMonth(props.month || props.initialMonth);
      var currentMonth = initialMonth;

      if (props.pagedNavigation && props.numberOfMonths > 1 && props.fromMonth) {
        var fromMonth = Helpers.startOfMonth(props.fromMonth);
        var diffInMonths = Helpers.getMonthsDiff(fromMonth, currentMonth);
        currentMonth = DateUtils.addMonths(fromMonth, Math.floor(diffInMonths / props.numberOfMonths) * props.numberOfMonths);
      } else if (props.toMonth && props.numberOfMonths > 1 && Helpers.getMonthsDiff(currentMonth, props.toMonth) <= 0) {
        currentMonth = DateUtils.addMonths(Helpers.startOfMonth(props.toMonth), 1 - this.props.numberOfMonths);
      }
      return currentMonth;
    }
  }, {
    key: 'getNextNavigableMonth',
    value: function getNextNavigableMonth() {
      return DateUtils.addMonths(this.state.currentMonth, this.props.numberOfMonths);
    }
  }, {
    key: 'getPreviousNavigableMonth',
    value: function getPreviousNavigableMonth() {
      return DateUtils.addMonths(this.state.currentMonth, -1);
    }
  }, {
    key: 'allowPreviousMonth',
    value: function allowPreviousMonth() {
      var previousMonth = DateUtils.addMonths(this.state.currentMonth, -1);
      return this.allowMonth(previousMonth);
    }
  }, {
    key: 'allowNextMonth',
    value: function allowNextMonth() {
      var nextMonth = DateUtils.addMonths(this.state.currentMonth, this.props.numberOfMonths);
      return this.allowMonth(nextMonth);
    }
  }, {
    key: 'allowMonth',
    value: function allowMonth(d) {
      var _props = this.props,
          fromMonth = _props.fromMonth,
          toMonth = _props.toMonth,
          canChangeMonth = _props.canChangeMonth;

      if (!canChangeMonth || fromMonth && Helpers.getMonthsDiff(fromMonth, d) < 0 || toMonth && Helpers.getMonthsDiff(toMonth, d) > 0) {
        return false;
      }
      return true;
    }
  }, {
    key: 'allowYearChange',
    value: function allowYearChange() {
      return this.props.canChangeMonth;
    }
  }, {
    key: 'showMonth',
    value: function showMonth(d, callback) {
      var _this2 = this;

      if (!this.allowMonth(d)) {
        return;
      }
      this.setState({ currentMonth: Helpers.startOfMonth(d) }, function () {
        if (callback) {
          callback();
        }
        if (_this2.props.onMonthChange) {
          _this2.props.onMonthChange(_this2.state.currentMonth);
        }
      });
    }
  }, {
    key: 'showNextYear',
    value: function showNextYear() {
      if (!this.allowYearChange()) {
        return;
      }
      var nextMonth = DateUtils.addMonths(this.state.currentMonth, 12);
      this.showMonth(nextMonth);
    }
  }, {
    key: 'showPreviousYear',
    value: function showPreviousYear() {
      if (!this.allowYearChange()) {
        return;
      }
      var nextMonth = DateUtils.addMonths(this.state.currentMonth, -12);
      this.showMonth(nextMonth);
    }
  }, {
    key: 'focusFirstDayOfMonth',
    value: function focusFirstDayOfMonth() {
      Helpers.getDayNodes(this.dayPicker, this.props.classNames)[0].focus();
    }
  }, {
    key: 'focusLastDayOfMonth',
    value: function focusLastDayOfMonth() {
      var dayNodes = Helpers.getDayNodes(this.dayPicker, this.props.classNames);
      dayNodes[dayNodes.length - 1].focus();
    }
  }, {
    key: 'focusPreviousDay',
    value: function focusPreviousDay(dayNode) {
      var _this3 = this;

      var dayNodes = Helpers.getDayNodes(this.dayPicker, this.props.classNames);
      var dayNodeIndex = Helpers.nodeListToArray(dayNodes).indexOf(dayNode);
      if (dayNodeIndex === -1) return;
      if (dayNodeIndex === 0) {
        this.showPreviousMonth(function () {
          return _this3.focusLastDayOfMonth();
        });
      } else {
        dayNodes[dayNodeIndex - 1].focus();
      }
    }
  }, {
    key: 'focusNextDay',
    value: function focusNextDay(dayNode) {
      var _this4 = this;

      var dayNodes = Helpers.getDayNodes(this.dayPicker, this.props.classNames);
      var dayNodeIndex = Helpers.nodeListToArray(dayNodes).indexOf(dayNode);
      if (dayNodeIndex === -1) return;
      if (dayNodeIndex === dayNodes.length - 1) {
        this.showNextMonth(function () {
          return _this4.focusFirstDayOfMonth();
        });
      } else {
        dayNodes[dayNodeIndex + 1].focus();
      }
    }
  }, {
    key: 'focusNextWeek',
    value: function focusNextWeek(dayNode) {
      var _this5 = this;

      var dayNodes = Helpers.getDayNodes(this.dayPicker, this.props.classNames);
      var dayNodeIndex = Helpers.nodeListToArray(dayNodes).indexOf(dayNode);
      var isInLastWeekOfMonth = dayNodeIndex > dayNodes.length - 8;

      if (isInLastWeekOfMonth) {
        this.showNextMonth(function () {
          var daysAfterIndex = dayNodes.length - dayNodeIndex;
          var nextMonthDayNodeIndex = 7 - daysAfterIndex;
          Helpers.getDayNodes(_this5.dayPicker, _this5.props.classNames)[nextMonthDayNodeIndex].focus();
        });
      } else {
        dayNodes[dayNodeIndex + 7].focus();
      }
    }
  }, {
    key: 'focusPreviousWeek',
    value: function focusPreviousWeek(dayNode) {
      var _this6 = this;

      var dayNodes = Helpers.getDayNodes(this.dayPicker, this.props.classNames);
      var dayNodeIndex = Helpers.nodeListToArray(dayNodes).indexOf(dayNode);
      var isInFirstWeekOfMonth = dayNodeIndex <= 6;

      if (isInFirstWeekOfMonth) {
        this.showPreviousMonth(function () {
          var previousMonthDayNodes = Helpers.getDayNodes(_this6.dayPicker, _this6.props.classNames);
          var startOfLastWeekOfMonth = previousMonthDayNodes.length - 7;
          var previousMonthDayNodeIndex = startOfLastWeekOfMonth + dayNodeIndex;
          previousMonthDayNodes[previousMonthDayNodeIndex].focus();
        });
      } else {
        dayNodes[dayNodeIndex - 7].focus();
      }
    }

    // Event handlers

  }, {
    key: 'handleOutsideDayClick',
    value: function handleOutsideDayClick(day) {
      var currentMonth = this.state.currentMonth;
      var numberOfMonths = this.props.numberOfMonths;

      var diffInMonths = Helpers.getMonthsDiff(currentMonth, day);
      if (diffInMonths > 0 && diffInMonths >= numberOfMonths) {
        this.showNextMonth();
      } else if (diffInMonths < 0) {
        this.showPreviousMonth();
      }
    }
  }, {
    key: 'renderNavbar',
    value: function renderNavbar() {
      var _props2 = this.props,
          labels = _props2.labels,
          locale = _props2.locale,
          localeUtils = _props2.localeUtils,
          canChangeMonth = _props2.canChangeMonth,
          navbarElement = _props2.navbarElement,
          attributes = _objectWithoutProperties(_props2, ['labels', 'locale', 'localeUtils', 'canChangeMonth', 'navbarElement']);

      if (!canChangeMonth) return null;

      var props = {
        month: this.state.currentMonth,
        classNames: this.props.classNames,
        className: this.props.classNames.navBar,
        nextMonth: this.getNextNavigableMonth(),
        previousMonth: this.getPreviousNavigableMonth(),
        showPreviousButton: this.allowPreviousMonth(),
        showNextButton: this.allowNextMonth(),
        onNextClick: this.showNextMonth,
        onPreviousClick: this.showPreviousMonth,
        dir: attributes.dir,
        labels: labels,
        locale: locale,
        localeUtils: localeUtils
      };
      return _react2.default.isValidElement(navbarElement) ? _react2.default.cloneElement(navbarElement, props) : _react2.default.createElement(navbarElement, props);
    }
  }, {
    key: 'renderMonths',
    value: function renderMonths() {
      var months = [];
      var firstDayOfWeek = Helpers.getFirstDayOfWeekFromProps(this.props);
      for (var i = 0; i < this.props.numberOfMonths; i += 1) {
        var month = DateUtils.addMonths(this.state.currentMonth, i);
        months.push(_react2.default.createElement(_Month2.default, _extends({
          key: i
        }, this.props, {
          month: month,
          firstDayOfWeek: firstDayOfWeek,
          onDayKeyDown: this.handleDayKeyDown,
          onDayClick: this.handleDayClick
        })));
      }

      if (this.props.reverseMonths) {
        months.reverse();
      }
      return months;
    }
  }, {
    key: 'renderFooter',
    value: function renderFooter() {
      if (this.props.todayButton) {
        return _react2.default.createElement(
          'div',
          { className: this.props.classNames.footer },
          this.renderTodayButton()
        );
      }
      return null;
    }
  }, {
    key: 'renderTodayButton',
    value: function renderTodayButton() {
      return _react2.default.createElement(
        'button',
        {
          type: 'button',
          tabIndex: 0,
          className: this.props.classNames.todayButton,
          'aria-label': this.props.todayButton,
          onClick: this.handleTodayButtonClick
        },
        this.props.todayButton
      );
    }
  }, {
    key: 'render',
    value: function render() {
      var _this7 = this;

      var className = this.props.classNames.container;

      if (!this.props.onDayClick) {
        className = className + ' ' + this.props.classNames.interactionDisabled;
      }
      if (this.props.className) {
        className = className + ' ' + this.props.className;
      }
      return _react2.default.createElement(
        'div',
        _extends({}, this.props.containerProps, {
          className: className,
          ref: function ref(el) {
            return _this7.dayPicker = el;
          },
          lang: this.props.locale
        }),
        _react2.default.createElement(
          'div',
          {
            className: this.props.classNames.wrapper,
            tabIndex: this.props.canChangeMonth && typeof this.props.tabIndex !== 'undefined' ? this.props.tabIndex : -1,
            onKeyDown: this.handleKeyDown,
            onFocus: this.props.onFocus,
            onBlur: this.props.onBlur
          },
          this.renderNavbar(),
          _react2.default.createElement(
            'div',
            { className: this.props.classNames.months },
            this.renderMonths()
          ),
          this.renderFooter()
        )
      );
    }
  }]);

  return DayPicker;
}(_react.Component);

DayPicker.VERSION = '7.3.0';
DayPicker.defaultProps = {
  classNames: _classNames2.default,
  tabIndex: 0,
  initialMonth: new Date(),
  numberOfMonths: 1,
  labels: {
    previousMonth: 'Previous Month',
    nextMonth: 'Next Month'
  },
  locale: 'en',
  localeUtils: LocaleUtils,
  showOutsideDays: false,
  enableOutsideDaysClick: true,
  fixedWeeks: false,
  canChangeMonth: true,
  reverseMonths: false,
  pagedNavigation: false,
  showWeekNumbers: false,
  showWeekDays: true,
  renderDay: function renderDay(day) {
    return day.getDate();
  },
  renderWeek: function renderWeek(weekNumber) {
    return weekNumber;
  },
  weekdayElement: _react2.default.createElement(_Weekday2.default, null),
  navbarElement: _react2.default.createElement(_Navbar2.default, { classNames: _classNames2.default }),
  captionElement: _react2.default.createElement(_Caption2.default, { classNames: _classNames2.default })
};
DayPicker.propTypes =  true ? {
  // Rendering months
  initialMonth: _propTypes2.default.instanceOf(Date),
  month: _propTypes2.default.instanceOf(Date),
  numberOfMonths: _propTypes2.default.number,
  fromMonth: _propTypes2.default.instanceOf(Date),
  toMonth: _propTypes2.default.instanceOf(Date),
  canChangeMonth: _propTypes2.default.bool,
  reverseMonths: _propTypes2.default.bool,
  pagedNavigation: _propTypes2.default.bool,
  todayButton: _propTypes2.default.string,
  showWeekNumbers: _propTypes2.default.bool,
  showWeekDays: _propTypes2.default.bool,

  // Modifiers
  selectedDays: _propTypes2.default.oneOfType([_propTypes2.default.object, _propTypes2.default.func, _propTypes2.default.array]),
  disabledDays: _propTypes2.default.oneOfType([_propTypes2.default.object, _propTypes2.default.func, _propTypes2.default.array]),

  modifiers: _propTypes2.default.object,
  modifiersStyles: _propTypes2.default.object,

  // Localization
  dir: _propTypes2.default.string,
  firstDayOfWeek: _propTypes2.default.oneOf([0, 1, 2, 3, 4, 5, 6]),
  labels: _propTypes2.default.shape({
    nextMonth: _propTypes2.default.string.isRequired,
    previousMonth: _propTypes2.default.string.isRequired
  }),
  locale: _propTypes2.default.string,
  localeUtils: _propTypes2.default.shape({
    formatMonthTitle: _propTypes2.default.func,
    formatWeekdayShort: _propTypes2.default.func,
    formatWeekdayLong: _propTypes2.default.func,
    getFirstDayOfWeek: _propTypes2.default.func
  }),
  months: _propTypes2.default.arrayOf(_propTypes2.default.string),
  weekdaysLong: _propTypes2.default.arrayOf(_propTypes2.default.string),
  weekdaysShort: _propTypes2.default.arrayOf(_propTypes2.default.string),

  // Customization
  showOutsideDays: _propTypes2.default.bool,
  enableOutsideDaysClick: _propTypes2.default.bool,
  fixedWeeks: _propTypes2.default.bool,

  // CSS and HTML
  classNames: _propTypes2.default.shape({
    body: _propTypes2.default.string,
    container: _propTypes2.default.string,
    day: _propTypes2.default.string.isRequired,
    disabled: _propTypes2.default.string.isRequired,
    footer: _propTypes2.default.string,
    interactionDisabled: _propTypes2.default.string,
    months: _propTypes2.default.string,
    month: _propTypes2.default.string,
    navBar: _propTypes2.default.string,
    outside: _propTypes2.default.string.isRequired,
    selected: _propTypes2.default.string.isRequired,
    today: _propTypes2.default.string.isRequired,
    todayButton: _propTypes2.default.string,
    week: _propTypes2.default.string,
    wrapper: _propTypes2.default.string
  }),
  className: _propTypes2.default.string,
  containerProps: _propTypes2.default.object,
  tabIndex: _propTypes2.default.number,

  // Custom elements
  renderDay: _propTypes2.default.func,
  renderWeek: _propTypes2.default.func,
  weekdayElement: _propTypes2.default.oneOfType([_propTypes2.default.element, _propTypes2.default.func, _propTypes2.default.instanceOf(_react.Component)]),
  navbarElement: _propTypes2.default.oneOfType([_propTypes2.default.element, _propTypes2.default.func, _propTypes2.default.instanceOf(_react.Component)]),
  captionElement: _propTypes2.default.oneOfType([_propTypes2.default.element, _propTypes2.default.func, _propTypes2.default.instanceOf(_react.Component)]),

  // Events
  onBlur: _propTypes2.default.func,
  onFocus: _propTypes2.default.func,
  onKeyDown: _propTypes2.default.func,
  onDayClick: _propTypes2.default.func,
  onDayKeyDown: _propTypes2.default.func,
  onDayMouseEnter: _propTypes2.default.func,
  onDayMouseLeave: _propTypes2.default.func,
  onDayMouseDown: _propTypes2.default.func,
  onDayMouseUp: _propTypes2.default.func,
  onDayTouchStart: _propTypes2.default.func,
  onDayTouchEnd: _propTypes2.default.func,
  onDayFocus: _propTypes2.default.func,
  onMonthChange: _propTypes2.default.func,
  onCaptionClick: _propTypes2.default.func,
  onWeekClick: _propTypes2.default.func,
  onTodayButtonClick: _propTypes2.default.func
} : undefined;


DayPicker.DateUtils = DateUtils;
DayPicker.LocaleUtils = LocaleUtils;
DayPicker.ModifiersUtils = ModifiersUtils;

exports.DateUtils = DateUtils;
exports.LocaleUtils = LocaleUtils;
exports.ModifiersUtils = ModifiersUtils;
exports.default = DayPicker;
//# sourceMappingURL=DayPicker.js.map

/***/ }),

/***/ "43KI":
/*!**********************************************************!*\
  !*** ./node_modules/readable-stream/readable-browser.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ./lib/_stream_readable.js */ "rXFu");
exports.Stream = exports;
exports.Readable = exports;
exports.Writable = __webpack_require__(/*! ./lib/_stream_writable.js */ "3BRs");
exports.Duplex = __webpack_require__(/*! ./lib/_stream_duplex.js */ "sZro");
exports.Transform = __webpack_require__(/*! ./lib/_stream_transform.js */ "J78i");
exports.PassThrough = __webpack_require__(/*! ./lib/_stream_passthrough.js */ "eA/Y");


/***/ }),

/***/ "44Ds":
/*!****************************************!*\
  !*** ./node_modules/lodash/memoize.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var MapCache = __webpack_require__(/*! ./_MapCache */ "e4Nc");

/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';

/**
 * 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;

module.exports = memoize;


/***/ }),

/***/ "45tw":
/*!**********************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/splitpanel.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
var dragdrop_1 = __webpack_require__(/*! @phosphor/dragdrop */ "v7cI");
var panel_1 = __webpack_require__(/*! ./panel */ "RlJB");
var splitlayout_1 = __webpack_require__(/*! ./splitlayout */ "Jv9w");
/**
 * A panel which arranges its widgets into resizable sections.
 *
 * #### Notes
 * This class provides a convenience wrapper around a [[SplitLayout]].
 */
var SplitPanel = (function (_super) {
    __extends(SplitPanel, _super);
    /**
     * Construct a new split panel.
     *
     * @param options - The options for initializing the split panel.
     */
    function SplitPanel(options) {
        if (options === void 0) { options = {}; }
        var _this = _super.call(this, { layout: Private.createLayout(options) }) || this;
        _this._pressData = null;
        _this.addClass('p-SplitPanel');
        return _this;
    }
    /**
     * Dispose of the resources held by the panel.
     */
    SplitPanel.prototype.dispose = function () {
        this._releaseMouse();
        _super.prototype.dispose.call(this);
    };
    Object.defineProperty(SplitPanel.prototype, "orientation", {
        /**
         * Get the layout orientation for the split panel.
         */
        get: function () {
            return this.layout.orientation;
        },
        /**
         * Set the layout orientation for the split panel.
         */
        set: function (value) {
            this.layout.orientation = value;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(SplitPanel.prototype, "alignment", {
        /**
         * Get the content alignment for the split panel.
         *
         * #### Notes
         * This is the alignment of the widgets in the layout direction.
         *
         * The alignment has no effect if the widgets can expand to fill the
         * entire split panel.
         */
        get: function () {
            return this.layout.alignment;
        },
        /**
         * Set the content alignment for the split panel.
         *
         * #### Notes
         * This is the alignment of the widgets in the layout direction.
         *
         * The alignment has no effect if the widgets can expand to fill the
         * entire split panel.
         */
        set: function (value) {
            this.layout.alignment = value;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(SplitPanel.prototype, "spacing", {
        /**
         * Get the inter-element spacing for the split panel.
         */
        get: function () {
            return this.layout.spacing;
        },
        /**
         * Set the inter-element spacing for the split panel.
         */
        set: function (value) {
            this.layout.spacing = value;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(SplitPanel.prototype, "renderer", {
        /**
         * The renderer used by the split panel.
         */
        get: function () {
            return this.layout.renderer;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(SplitPanel.prototype, "handles", {
        /**
         * A read-only array of the split handles in the panel.
         */
        get: function () {
            return this.layout.handles;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Get the relative sizes of the widgets in the panel.
     *
     * @returns A new array of the relative sizes of the widgets.
     *
     * #### Notes
     * The returned sizes reflect the sizes of the widgets normalized
     * relative to their siblings.
     *
     * This method **does not** measure the DOM nodes.
     */
    SplitPanel.prototype.relativeSizes = function () {
        return this.layout.relativeSizes();
    };
    /**
     * Set the relative sizes for the widgets in the panel.
     *
     * @param sizes - The relative sizes for the widgets in the panel.
     *
     * #### Notes
     * Extra values are ignored, too few will yield an undefined layout.
     *
     * The actual geometry of the DOM nodes is updated asynchronously.
     */
    SplitPanel.prototype.setRelativeSizes = function (sizes) {
        this.layout.setRelativeSizes(sizes);
    };
    /**
     * Handle the DOM events for the split panel.
     *
     * @param event - The DOM event sent to the panel.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the panel's DOM node. It should
     * not be called directly by user code.
     */
    SplitPanel.prototype.handleEvent = function (event) {
        switch (event.type) {
            case 'mousedown':
                this._evtMouseDown(event);
                break;
            case 'mousemove':
                this._evtMouseMove(event);
                break;
            case 'mouseup':
                this._evtMouseUp(event);
                break;
            case 'keydown':
                this._evtKeyDown(event);
                break;
            case 'contextmenu':
                event.preventDefault();
                event.stopPropagation();
                break;
        }
    };
    /**
     * A message handler invoked on a `'before-attach'` message.
     */
    SplitPanel.prototype.onBeforeAttach = function (msg) {
        this.node.addEventListener('mousedown', this);
    };
    /**
     * A message handler invoked on an `'after-detach'` message.
     */
    SplitPanel.prototype.onAfterDetach = function (msg) {
        this.node.removeEventListener('mousedown', this);
        this._releaseMouse();
    };
    /**
     * A message handler invoked on a `'child-added'` message.
     */
    SplitPanel.prototype.onChildAdded = function (msg) {
        msg.child.addClass('p-SplitPanel-child');
        this._releaseMouse();
    };
    /**
     * A message handler invoked on a `'child-removed'` message.
     */
    SplitPanel.prototype.onChildRemoved = function (msg) {
        msg.child.removeClass('p-SplitPanel-child');
        this._releaseMouse();
    };
    /**
     * Handle the `'keydown'` event for the split panel.
     */
    SplitPanel.prototype._evtKeyDown = function (event) {
        // Stop input events during drag.
        event.preventDefault();
        event.stopPropagation();
        // Release the mouse if `Escape` is pressed.
        if (event.keyCode === 27) {
            this._releaseMouse();
        }
    };
    /**
     * Handle the `'mousedown'` event for the split panel.
     */
    SplitPanel.prototype._evtMouseDown = function (event) {
        // Do nothing if the left mouse button is not pressed.
        if (event.button !== 0) {
            return;
        }
        // Find the handle which contains the mouse target, if any.
        var layout = this.layout;
        var index = algorithm_1.ArrayExt.findFirstIndex(layout.handles, function (handle) {
            return handle.contains(event.target);
        });
        // Bail early if the mouse press was not on a handle.
        if (index === -1) {
            return;
        }
        // Stop the event when a split handle is pressed.
        event.preventDefault();
        event.stopPropagation();
        // Add the extra document listeners.
        document.addEventListener('mouseup', this, true);
        document.addEventListener('mousemove', this, true);
        document.addEventListener('keydown', this, true);
        document.addEventListener('contextmenu', this, true);
        // Compute the offset delta for the handle press.
        var delta;
        var handle = layout.handles[index];
        var rect = handle.getBoundingClientRect();
        if (layout.orientation === 'horizontal') {
            delta = event.clientX - rect.left;
        }
        else {
            delta = event.clientY - rect.top;
        }
        // Override the cursor and store the press data.
        var style = window.getComputedStyle(handle);
        var override = dragdrop_1.Drag.overrideCursor(style.cursor);
        this._pressData = { index: index, delta: delta, override: override };
    };
    /**
     * Handle the `'mousemove'` event for the split panel.
     */
    SplitPanel.prototype._evtMouseMove = function (event) {
        // Stop the event when dragging a split handle.
        event.preventDefault();
        event.stopPropagation();
        // Compute the desired offset position for the handle.
        var pos;
        var layout = this.layout;
        var rect = this.node.getBoundingClientRect();
        if (layout.orientation === 'horizontal') {
            pos = event.clientX - rect.left - this._pressData.delta;
        }
        else {
            pos = event.clientY - rect.top - this._pressData.delta;
        }
        // Move the handle as close to the desired position as possible.
        layout.moveHandle(this._pressData.index, pos);
    };
    /**
     * Handle the `'mouseup'` event for the split panel.
     */
    SplitPanel.prototype._evtMouseUp = function (event) {
        // Do nothing if the left mouse button is not released.
        if (event.button !== 0) {
            return;
        }
        // Stop the event when releasing a handle.
        event.preventDefault();
        event.stopPropagation();
        // Finalize the mouse release.
        this._releaseMouse();
    };
    /**
     * Release the mouse grab for the split panel.
     */
    SplitPanel.prototype._releaseMouse = function () {
        // Bail early if no drag is in progress.
        if (!this._pressData) {
            return;
        }
        // Clear the override cursor.
        this._pressData.override.dispose();
        this._pressData = null;
        // Remove the extra document listeners.
        document.removeEventListener('mouseup', this, true);
        document.removeEventListener('mousemove', this, true);
        document.removeEventListener('keydown', this, true);
        document.removeEventListener('contextmenu', this, true);
    };
    return SplitPanel;
}(panel_1.Panel));
exports.SplitPanel = SplitPanel;
/**
 * The namespace for the `SplitPanel` class statics.
 */
(function (SplitPanel) {
    /**
     * The default implementation of `IRenderer`.
     */
    var Renderer = (function () {
        function Renderer() {
        }
        /**
         * Create a new handle for use with a split panel.
         *
         * @returns A new handle element for a split panel.
         */
        Renderer.prototype.createHandle = function () {
            var handle = document.createElement('div');
            handle.className = 'p-SplitPanel-handle';
            return handle;
        };
        return Renderer;
    }());
    SplitPanel.Renderer = Renderer;
    /**
     * The default `Renderer` instance.
     */
    SplitPanel.defaultRenderer = new Renderer();
    /**
     * Get the split panel stretch factor for the given widget.
     *
     * @param widget - The widget of interest.
     *
     * @returns The split panel stretch factor for the widget.
     */
    function getStretch(widget) {
        return splitlayout_1.SplitLayout.getStretch(widget);
    }
    SplitPanel.getStretch = getStretch;
    /**
     * Set the split panel stretch factor for the given widget.
     *
     * @param widget - The widget of interest.
     *
     * @param value - The value for the stretch factor.
     */
    function setStretch(widget, value) {
        splitlayout_1.SplitLayout.setStretch(widget, value);
    }
    SplitPanel.setStretch = setStretch;
})(SplitPanel = exports.SplitPanel || (exports.SplitPanel = {}));
exports.SplitPanel = SplitPanel;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * Create a split layout for the given panel options.
     */
    function createLayout(options) {
        return options.layout || new splitlayout_1.SplitLayout({
            renderer: options.renderer || SplitPanel.defaultRenderer,
            orientation: options.orientation,
            alignment: options.alignment,
            spacing: options.spacing
        });
    }
    Private.createLayout = createLayout;
})(Private || (Private = {}));


/***/ }),

/***/ "4694":
/*!*******************************************************!*\
  !*** ./node_modules/react-tabs/esm/components/Tab.js ***!
  \*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Tab; });
/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! prop-types */ "17x9");
/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(prop_types__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "q1tI");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! classnames */ "TSYQ");
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(classnames__WEBPACK_IMPORTED_MODULE_2__);
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }




var DEFAULT_CLASS = 'react-tabs__tab';

var Tab =
/*#__PURE__*/
function (_Component) {
  _inheritsLoose(Tab, _Component);

  function Tab() {
    return _Component.apply(this, arguments) || this;
  }

  var _proto = Tab.prototype;

  _proto.componentDidMount = function componentDidMount() {
    this.checkFocus();
  };

  _proto.componentDidUpdate = function componentDidUpdate() {
    this.checkFocus();
  };

  _proto.checkFocus = function checkFocus() {
    var _this$props = this.props,
        selected = _this$props.selected,
        focus = _this$props.focus;

    if (selected && focus) {
      this.node.focus();
    }
  };

  _proto.render = function render() {
    var _cx,
        _this = this;

    var _this$props2 = this.props,
        children = _this$props2.children,
        className = _this$props2.className,
        disabled = _this$props2.disabled,
        disabledClassName = _this$props2.disabledClassName,
        focus = _this$props2.focus,
        id = _this$props2.id,
        panelId = _this$props2.panelId,
        selected = _this$props2.selected,
        selectedClassName = _this$props2.selectedClassName,
        tabIndex = _this$props2.tabIndex,
        tabRef = _this$props2.tabRef,
        attributes = _objectWithoutPropertiesLoose(_this$props2, ["children", "className", "disabled", "disabledClassName", "focus", "id", "panelId", "selected", "selectedClassName", "tabIndex", "tabRef"]);

    return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("li", _extends({}, attributes, {
      className: classnames__WEBPACK_IMPORTED_MODULE_2___default()(className, (_cx = {}, _cx[selectedClassName] = selected, _cx[disabledClassName] = disabled, _cx)),
      ref: function ref(node) {
        _this.node = node;
        if (tabRef) tabRef(node);
      },
      role: "tab",
      id: id,
      "aria-selected": selected ? 'true' : 'false',
      "aria-disabled": disabled ? 'true' : 'false',
      "aria-controls": panelId,
      tabIndex: tabIndex || (selected ? '0' : null)
    }), children);
  };

  return Tab;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]);

Tab.defaultProps = {
  className: DEFAULT_CLASS,
  disabledClassName: DEFAULT_CLASS + "--disabled",
  focus: false,
  id: null,
  panelId: null,
  selected: false,
  selectedClassName: DEFAULT_CLASS + "--selected"
};

Tab.propTypes =  true ? {
  children: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.array, prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.object, prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.string]),
  className: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.array, prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.object]),
  disabled: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.bool,
  tabIndex: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.string,
  disabledClassName: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.string,
  focus: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.bool,
  // private
  id: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.string,
  // private
  panelId: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.string,
  // private
  selected: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.bool,
  // private
  selectedClassName: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.string,
  tabRef: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.func // private

} : undefined;
Tab.tabsRole = 'Tab';

/***/ }),

/***/ "482I":
/*!*************************************************************!*\
  !*** ./node_modules/@jupyterlab/codemirror/style/index.css ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "Wdip");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "4Hv8":
/*!*************************************************!*\
  !*** ./node_modules/pbkdf2/lib/sync-browser.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var md5 = __webpack_require__(/*! create-hash/md5 */ "WnY+")
var RIPEMD160 = __webpack_require__(/*! ripemd160 */ "tcrS")
var sha = __webpack_require__(/*! sha.js */ "afKu")

var checkParameters = __webpack_require__(/*! ./precondition */ "fSpj")
var defaultEncoding = __webpack_require__(/*! ./default-encoding */ "n53Y")
var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer
var ZEROS = Buffer.alloc(128)
var sizes = {
  md5: 16,
  sha1: 20,
  sha224: 28,
  sha256: 32,
  sha384: 48,
  sha512: 64,
  rmd160: 20,
  ripemd160: 20
}

function Hmac (alg, key, saltLen) {
  var hash = getDigest(alg)
  var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64

  if (key.length > blocksize) {
    key = hash(key)
  } else if (key.length < blocksize) {
    key = Buffer.concat([key, ZEROS], blocksize)
  }

  var ipad = Buffer.allocUnsafe(blocksize + sizes[alg])
  var opad = Buffer.allocUnsafe(blocksize + sizes[alg])
  for (var i = 0; i < blocksize; i++) {
    ipad[i] = key[i] ^ 0x36
    opad[i] = key[i] ^ 0x5C
  }

  var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4)
  ipad.copy(ipad1, 0, 0, blocksize)
  this.ipad1 = ipad1
  this.ipad2 = ipad
  this.opad = opad
  this.alg = alg
  this.blocksize = blocksize
  this.hash = hash
  this.size = sizes[alg]
}

Hmac.prototype.run = function (data, ipad) {
  data.copy(ipad, this.blocksize)
  var h = this.hash(ipad)
  h.copy(this.opad, this.blocksize)
  return this.hash(this.opad)
}

function getDigest (alg) {
  function shaFunc (data) {
    return sha(alg).update(data).digest()
  }
  function rmd160Func (data) {
    return new RIPEMD160().update(data).digest()
  }

  if (alg === 'rmd160' || alg === 'ripemd160') return rmd160Func
  if (alg === 'md5') return md5
  return shaFunc
}

function pbkdf2 (password, salt, iterations, keylen, digest) {
  checkParameters(password, salt, iterations, keylen)

  if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding)
  if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding)

  digest = digest || 'sha1'

  var hmac = new Hmac(digest, password, salt.length)

  var DK = Buffer.allocUnsafe(keylen)
  var block1 = Buffer.allocUnsafe(salt.length + 4)
  salt.copy(block1, 0, 0, salt.length)

  var destPos = 0
  var hLen = sizes[digest]
  var l = Math.ceil(keylen / hLen)

  for (var i = 1; i <= l; i++) {
    block1.writeUInt32BE(i, salt.length)

    var T = hmac.run(block1, hmac.ipad1)
    var U = T

    for (var j = 1; j < iterations; j++) {
      U = hmac.run(U, hmac.ipad2)
      for (var k = 0; k < hLen; k++) T[k] ^= U[k]
    }

    T.copy(DK, destPos)
    destPos += hLen
  }

  return DK
}

module.exports = pbkdf2


/***/ }),

/***/ "4JlD":
/*!************************************************!*\
  !*** ./node_modules/querystring-es3/encode.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.



var stringifyPrimitive = function(v) {
  switch (typeof v) {
    case 'string':
      return v;

    case 'boolean':
      return v ? 'true' : 'false';

    case 'number':
      return isFinite(v) ? v : '';

    default:
      return '';
  }
};

module.exports = function(obj, sep, eq, name) {
  sep = sep || '&';
  eq = eq || '=';
  if (obj === null) {
    obj = undefined;
  }

  if (typeof obj === 'object') {
    return map(objectKeys(obj), function(k) {
      var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
      if (isArray(obj[k])) {
        return map(obj[k], function(v) {
          return ks + encodeURIComponent(stringifyPrimitive(v));
        }).join(sep);
      } else {
        return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
      }
    }).join(sep);

  }

  if (!name) return '';
  return encodeURIComponent(stringifyPrimitive(name)) + eq +
         encodeURIComponent(stringifyPrimitive(obj));
};

var isArray = Array.isArray || function (xs) {
  return Object.prototype.toString.call(xs) === '[object Array]';
};

function map (xs, f) {
  if (xs.map) return xs.map(f);
  var res = [];
  for (var i = 0; i < xs.length; i++) {
    res.push(f(xs[i], i));
  }
  return res;
}

var objectKeys = Object.keys || function (obj) {
  var res = [];
  for (var key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  }
  return res;
};


/***/ }),

/***/ "4MV3":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/gu.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var symbolMap = {
        '1': '૧',
        '2': '૨',
        '3': '૩',
        '4': '૪',
        '5': '૫',
        '6': '૬',
        '7': '૭',
        '8': '૮',
        '9': '૯',
        '0': '૦'
    },
    numberMap = {
        '૧': '1',
        '૨': '2',
        '૩': '3',
        '૪': '4',
        '૫': '5',
        '૬': '6',
        '૭': '7',
        '૮': '8',
        '૯': '9',
        '૦': '0'
    };

var gu = moment.defineLocale('gu', {
    months: 'જાન્યુઆરી_ફેબ્રુઆરી_માર્ચ_એપ્રિલ_મે_જૂન_જુલાઈ_ઑગસ્ટ_સપ્ટેમ્બર_ઑક્ટ્બર_નવેમ્બર_ડિસેમ્બર'.split('_'),
    monthsShort: 'જાન્યુ._ફેબ્રુ._માર્ચ_એપ્રિ._મે_જૂન_જુલા._ઑગ._સપ્ટે._ઑક્ટ્._નવે._ડિસે.'.split('_'),
    monthsParseExact: true,
    weekdays: 'રવિવાર_સોમવાર_મંગળવાર_બુધ્વાર_ગુરુવાર_શુક્રવાર_શનિવાર'.split('_'),
    weekdaysShort: 'રવિ_સોમ_મંગળ_બુધ્_ગુરુ_શુક્ર_શનિ'.split('_'),
    weekdaysMin: 'ર_સો_મં_બુ_ગુ_શુ_શ'.split('_'),
    longDateFormat: {
        LT: 'A h:mm વાગ્યે',
        LTS: 'A h:mm:ss વાગ્યે',
        L: 'DD/MM/YYYY',
        LL: 'D MMMM YYYY',
        LLL: 'D MMMM YYYY, A h:mm વાગ્યે',
        LLLL: 'dddd, D MMMM YYYY, A h:mm વાગ્યે'
    },
    calendar: {
        sameDay: '[આજ] LT',
        nextDay: '[કાલે] LT',
        nextWeek: 'dddd, LT',
        lastDay: '[ગઇકાલે] LT',
        lastWeek: '[પાછલા] dddd, LT',
        sameElse: 'L'
    },
    relativeTime: {
        future: '%s મા',
        past: '%s પેહલા',
        s: 'અમુક પળો',
        ss: '%d સેકંડ',
        m: 'એક મિનિટ',
        mm: '%d મિનિટ',
        h: 'એક કલાક',
        hh: '%d કલાક',
        d: 'એક દિવસ',
        dd: '%d દિવસ',
        M: 'એક મહિનો',
        MM: '%d મહિનો',
        y: 'એક વર્ષ',
        yy: '%d વર્ષ'
    },
    preparse: function (string) {
        return string.replace(/[૧૨૩૪૫૬૭૮૯૦]/g, function (match) {
            return numberMap[match];
        });
    },
    postformat: function (string) {
        return string.replace(/\d/g, function (match) {
            return symbolMap[match];
        });
    },
    // Gujarati notation for meridiems are quite fuzzy in practice. While there exists
    // a rigid notion of a 'Pahar' it is not used as rigidly in modern Gujarati.
    meridiemParse: /રાત|બપોર|સવાર|સાંજ/,
    meridiemHour: function (hour, meridiem) {
        if (hour === 12) {
            hour = 0;
        }
        if (meridiem === 'રાત') {
            return hour < 4 ? hour : hour + 12;
        } else if (meridiem === 'સવાર') {
            return hour;
        } else if (meridiem === 'બપોર') {
            return hour >= 10 ? hour : hour + 12;
        } else if (meridiem === 'સાંજ') {
            return hour + 12;
        }
    },
    meridiem: function (hour, minute, isLower) {
        if (hour < 4) {
            return 'રાત';
        } else if (hour < 10) {
            return 'સવાર';
        } else if (hour < 17) {
            return 'બપોર';
        } else if (hour < 20) {
            return 'સાંજ';
        } else {
            return 'રાત';
        }
    },
    week: {
        dow: 0, // Sunday is the first day of the week.
        doy: 6 // The week that contains Jan 1st is the first week of the year.
    }
});

return gu;

})));


/***/ }),

/***/ "4Pvz":
/*!*********************************************!*\
  !*** ./node_modules/xterm/lib/utils/Dom.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function addDisposableListener(node, type, handler, useCapture) {
    node.addEventListener(type, handler, useCapture);
    return {
        dispose: function () {
            if (!handler) {
                return;
            }
            node.removeEventListener(type, handler, useCapture);
            node = null;
            handler = null;
        }
    };
}
exports.addDisposableListener = addDisposableListener;

//# sourceMappingURL=Dom.js.map


/***/ }),

/***/ "4X8Z":
/*!************************************************!*\
  !*** ./node_modules/synthetic-dom/lib/main.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _SyntheticDOM = __webpack_require__(/*! ./SyntheticDOM */ "MfJx");

Object.keys(_SyntheticDOM).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _SyntheticDOM[key];
    }
  });
});

/***/ }),

/***/ "4YDR":
/*!****************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeParcoordsIcon.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeParcoordsIcon = function TraceTypeParcoordsIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement(
            'g',
            { fill: 'none' },
            _react2.default.createElement('path', { d: 'M0 0h46v46H0z' }),
            _react2.default.createElement('path', { stroke: '#25fdfc', d: 'M9 8v30m9-30v30M28 8v30m9-30v30', strokeMiterlimit: '10', strokeWidth: '2' }),
            _react2.default.createElement('path', { stroke: '#1d9bfb', d: 'M9 28.429L18 29l10-4.714L37 31M9 23.074L18 23l10-11.92L37 20', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2' }),
            _react2.default.createElement('path', { stroke: '#1d9bfb', d: 'M9 17l9 6 10 1 9-4', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2' })
        )
    );
};

exports.default = TraceTypeParcoordsIcon;

/***/ }),

/***/ "4a3i":
/*!**************************************************************************!*\
  !*** ./node_modules/@jupyterlab/codemirror/lib/codemirror-ipythongfm.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const codemirror_1 = __importDefault(__webpack_require__(/*! codemirror */ "VrN/"));
__webpack_require__(/*! codemirror/mode/stex/stex */ "+NIl");
__webpack_require__(/*! codemirror/mode/gfm/gfm */ "RKCW");
__webpack_require__(/*! codemirror/addon/mode/multiplex */ "6wyt");
/**
 * Define an IPython GFM (GitHub Flavored Markdown) mode.
 *
 * Is just a slightly altered GFM Mode with support for LaTeX.
 * LaTeX support was supported by Codemirror GFM as of
 *   https://github.com/codemirror/CodeMirror/pull/567
 *  But was later removed in
 *   https://github.com/codemirror/CodeMirror/commit/d9c9f1b1ffe984aee41307f3e927f80d1f23590c
 */
codemirror_1.default.defineMode('ipythongfm', (config, modeOptions) => {
    let gfmMode = codemirror_1.default.getMode(config, {
        name: 'gfm',
        // Override list3 with an under-used token, rather than `keyword`
        tokenTypeOverrides: { list3: 'string-2' }
    });
    let texMode = codemirror_1.default.getMode(config, {
        name: 'stex',
        inMathMode: true
    });
    return codemirror_1.default.multiplexingMode(gfmMode, {
        open: '$$',
        close: '$$',
        mode: texMode,
        delimStyle: 'delimit'
    }, {
        open: '$',
        close: '$',
        mode: texMode,
        delimStyle: 'delimit'
    }, {
        open: '\\(',
        close: '\\)',
        mode: texMode,
        delimStyle: 'delimit'
    }, {
        open: '\\[',
        close: '\\]',
        mode: texMode,
        delimStyle: 'delimit'
    }
    // .. more multiplexed styles can follow here
    );
}, 'gfm');
codemirror_1.default.defineMIME('text/x-ipythongfm', 'ipythongfm');
codemirror_1.default.modeInfo.push({
    ext: [],
    mime: 'text/x-ipythongfm',
    mode: 'ipythongfm',
    name: 'ipythongfm'
});


/***/ }),

/***/ "4cd8":
/*!*******************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/TextPosition.js ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UnconnectedTextPosition = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Dropdown = __webpack_require__(/*! ./Dropdown */ "dRXW");

var _Dropdown2 = _interopRequireDefault(_Dropdown);

var _RadioBlocks = __webpack_require__(/*! ../widgets/RadioBlocks */ "N8y9");

var _RadioBlocks2 = _interopRequireDefault(_RadioBlocks);

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _Info = __webpack_require__(/*! ./Info */ "iOcY");

var _Info2 = _interopRequireDefault(_Info);

var _DataSelector = __webpack_require__(/*! ./DataSelector */ "dv5i");

var _DataSelector2 = _interopRequireDefault(_DataSelector);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UnconnectedTextPosition = exports.UnconnectedTextPosition = function (_Component) {
  _inherits(UnconnectedTextPosition, _Component);

  function UnconnectedTextPosition(props) {
    _classCallCheck(this, UnconnectedTextPosition);

    var _this = _possibleConstructorReturn(this, (UnconnectedTextPosition.__proto__ || Object.getPrototypeOf(UnconnectedTextPosition)).call(this, props));

    _this.state = {
      posType: typeof props.fullValue === 'string' ? 'simple' : 'custom'
    };
    return _this;
  }

  _createClass(UnconnectedTextPosition, [{
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _ = this.context.localize;
      var radioOptions = [{ label: _('All'), value: 'simple' }, { label: _('Custom'), value: 'custom' }];
      var control = this.state.posType === 'simple' ? _react2.default.createElement(
        _react.Fragment,
        null,
        _react2.default.createElement(
          _Info2.default,
          null,
          _('This will position all text values on the plot according to the selected position.')
        ),
        _react2.default.createElement(_Dropdown2.default, { options: this.props.options, attr: 'textposition' })
      ) : _react2.default.createElement(
        _react.Fragment,
        null,
        _react2.default.createElement(
          _Info2.default,
          null,
          _react2.default.createElement(
            'div',
            null,
            _('This will position text values individually, according to the provided data positions array. ')
          )
        ),
        _react2.default.createElement(_DataSelector2.default, { attr: 'textposition' }),
        _react2.default.createElement(
          _Info2.default,
          null,
          _react2.default.createElement(
            'div',
            null,
            _('("Top", "Middle", "Bottom") + ("Left", "Center", "Right")')
          )
        )
      );

      return _react2.default.createElement(
        _Field2.default,
        this.props,
        _react2.default.createElement(_RadioBlocks2.default, {
          options: radioOptions,
          activeOption: this.state.posType,
          onOptionChange: function onOptionChange(value) {
            _this2.setState({ posType: value });
            if (value === 'simple') {
              _this2.props.updatePlot('middle center');
            } else {
              _this2.props.updateContainer({ textpositionsrc: null });
            }
          }
        }),
        control
      );
    }
  }]);

  return UnconnectedTextPosition;
}(_react.Component);

UnconnectedTextPosition.propTypes = _extends({}, _Field2.default.propTypes, {
  options: _propTypes2.default.array,
  fullValue: _propTypes2.default.oneOfType([_propTypes2.default.array, _propTypes2.default.string])
});

UnconnectedTextPosition.contextTypes = {
  localize: _propTypes2.default.func
};

exports.default = (0, _lib.connectToContainer)(UnconnectedTextPosition, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var _ = context.localize;

    var options = [{ label: _('Top Left'), value: 'top left' }, { label: _('Top Center'), value: 'top center' }, { label: _('Top Right'), value: 'top right' }, { label: _('Middle Left'), value: 'middle left' }, { label: _('Middle Center'), value: 'middle center' }, { label: _('Middle Right'), value: 'middle right' }, { label: _('Bottom Left'), value: 'bottom left' }, { label: _('Bottom Center'), value: 'bottom center' }, { label: _('Bottom Right'), value: 'bottom right' }];
    if (context.container.type === 'pie' || context.container.type === 'bar') {
      options = [{ label: _('Inside'), value: 'inside' }, { label: _('Outside'), value: 'outside' }, { label: _('Auto'), value: 'auto' }, { label: _('None'), value: 'none' }];
    }
    plotProps.options = options;
    plotProps.clearable = false;
  }
});
//# sourceMappingURL=TextPosition.js.map

/***/ }),

/***/ "4dMO":
/*!*********************************************!*\
  !*** ./node_modules/create-ecdh/browser.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(Buffer) {var elliptic = __webpack_require__(/*! elliptic */ "MzeL")
var BN = __webpack_require__(/*! bn.js */ "OZ/i")

module.exports = function createECDH (curve) {
  return new ECDH(curve)
}

var aliases = {
  secp256k1: {
    name: 'secp256k1',
    byteLength: 32
  },
  secp224r1: {
    name: 'p224',
    byteLength: 28
  },
  prime256v1: {
    name: 'p256',
    byteLength: 32
  },
  prime192v1: {
    name: 'p192',
    byteLength: 24
  },
  ed25519: {
    name: 'ed25519',
    byteLength: 32
  },
  secp384r1: {
    name: 'p384',
    byteLength: 48
  },
  secp521r1: {
    name: 'p521',
    byteLength: 66
  }
}

aliases.p224 = aliases.secp224r1
aliases.p256 = aliases.secp256r1 = aliases.prime256v1
aliases.p192 = aliases.secp192r1 = aliases.prime192v1
aliases.p384 = aliases.secp384r1
aliases.p521 = aliases.secp521r1

function ECDH (curve) {
  this.curveType = aliases[curve]
  if (!this.curveType) {
    this.curveType = {
      name: curve
    }
  }
  this.curve = new elliptic.ec(this.curveType.name) // eslint-disable-line new-cap
  this.keys = void 0
}

ECDH.prototype.generateKeys = function (enc, format) {
  this.keys = this.curve.genKeyPair()
  return this.getPublicKey(enc, format)
}

ECDH.prototype.computeSecret = function (other, inenc, enc) {
  inenc = inenc || 'utf8'
  if (!Buffer.isBuffer(other)) {
    other = new Buffer(other, inenc)
  }
  var otherPub = this.curve.keyFromPublic(other).getPublic()
  var out = otherPub.mul(this.keys.getPrivate()).getX()
  return formatReturnValue(out, enc, this.curveType.byteLength)
}

ECDH.prototype.getPublicKey = function (enc, format) {
  var key = this.keys.getPublic(format === 'compressed', true)
  if (format === 'hybrid') {
    if (key[key.length - 1] % 2) {
      key[0] = 7
    } else {
      key[0] = 6
    }
  }
  return formatReturnValue(key, enc)
}

ECDH.prototype.getPrivateKey = function (enc) {
  return formatReturnValue(this.keys.getPrivate(), enc)
}

ECDH.prototype.setPublicKey = function (pub, enc) {
  enc = enc || 'utf8'
  if (!Buffer.isBuffer(pub)) {
    pub = new Buffer(pub, enc)
  }
  this.keys._importPublic(pub)
  return this
}

ECDH.prototype.setPrivateKey = function (priv, enc) {
  enc = enc || 'utf8'
  if (!Buffer.isBuffer(priv)) {
    priv = new Buffer(priv, enc)
  }

  var _priv = new BN(priv)
  _priv = _priv.toString(16)
  this.keys = this.curve.genKeyPair()
  this.keys._importPrivate(_priv)
  return this
}

function formatReturnValue (bn, enc, len) {
  if (!Array.isArray(bn)) {
    bn = bn.toArray()
  }
  var buf = new Buffer(bn)
  if (len && buf.length < len) {
    var zeros = new Buffer(len - buf.length)
    zeros.fill(0)
    buf = Buffer.concat([zeros, buf])
  }
  if (!enc) {
    return buf
  } else {
    return buf.toString(enc)
  }
}

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../buffer/index.js */ "tjlA").Buffer))

/***/ }),

/***/ "4dOw":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/en-ie.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var enIe = moment.defineLocale('en-ie', {
    months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
    monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
    weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
    weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
    weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD-MM-YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay : '[Today at] LT',
        nextDay : '[Tomorrow at] LT',
        nextWeek : 'dddd [at] LT',
        lastDay : '[Yesterday at] LT',
        lastWeek : '[Last] dddd [at] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'in %s',
        past : '%s ago',
        s : 'a few seconds',
        ss : '%d seconds',
        m : 'a minute',
        mm : '%d minutes',
        h : 'an hour',
        hh : '%d hours',
        d : 'a day',
        dd : '%d days',
        M : 'a month',
        MM : '%d months',
        y : 'a year',
        yy : '%d years'
    },
    dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/,
    ordinal : function (number) {
        var b = number % 10,
            output = (~~(number % 100 / 10) === 1) ? 'th' :
            (b === 1) ? 'st' :
            (b === 2) ? 'nd' :
            (b === 3) ? 'rd' : 'th';
        return number + output;
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return enIe;

})));


/***/ }),

/***/ "4gkd":
/*!*************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/sortMenu.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = sortMenu;
function getUniqueValues(value, index, self) {
  return self.indexOf(value) === index;
}

function sortAlphabetically(a, b) {
  var sortByGroup = a.props.group === b.props.group ? 0 : a.props.group < b.props.group ? -1 : 1;
  var sortByName = a.props.name === b.props.name ? 0 : a.props.name < b.props.name ? -1 : 1;
  return sortByGroup || sortByName;
}

function sortMenu(children, order) {
  // Break out early if no order is provided
  if (!order) {
    return children;
  }

  // PART 1: only sorting panels (i.e. child with a group and name prop)
  // and not other elements (like Buttons, or Logo)
  var panelsStartIndex = null;
  var panelsEndIndex = null;
  for (var i = 0; i < children.length; i++) {
    if (children[i].props.group && children[i].props.name && !panelsStartIndex) {
      panelsStartIndex = i;
      break;
    }
  }
  for (var _i = panelsStartIndex; _i < children.length; _i++) {
    if (!children[_i].props.group && !children[_i].props.name && !panelsEndIndex) {
      panelsEndIndex = _i - 1;
      break;
    } else if (_i === children.length - 1) {
      panelsEndIndex = _i;
    }
  }

  var prePanelsChildren = panelsStartIndex === 0 ? [] : children.slice(0, panelsStartIndex);
  var panels = panelsStartIndex !== panelsEndIndex ? children.slice(panelsStartIndex, panelsEndIndex + 1) : [];
  var postPanelsChildren = panelsEndIndex === children.length ? [] : children.slice(panelsEndIndex + 1);

  // PART 2: validate order prop, if a desired panel specified in order, matches no actual panel rendered
  // in the panels array, it is excluded from ordering considerations
  // eslint-disable-next-line
  order = order.filter(function (desiredPanel) {
    return panels.some(function (actualPanel) {
      return actualPanel.props.name === desiredPanel.name && actualPanel.props.group === desiredPanel.group;
    });
  });

  var desiredGroupOrder = order.map(function (panel) {
    return panel.group;
  }).filter(getUniqueValues);

  // PART 3: Sort panels
  panels.sort(function (a, b) {
    var panelAHasGroupCustomOrder = desiredGroupOrder.includes(a.props.group);
    var panelBHasGroupCustomOrder = desiredGroupOrder.includes(b.props.group);

    // if one of the elements is not in the desiredGroupOrder array, then it goes to the end of the list
    if (panelAHasGroupCustomOrder && !panelBHasGroupCustomOrder) {
      return -1;
    }
    if (!panelAHasGroupCustomOrder && panelBHasGroupCustomOrder) {
      return 1;
    }

    // if both elements are not in the desiredGroupOrder array, they get sorted alphabetically,
    // by group, then by name
    if (!panelAHasGroupCustomOrder && !panelBHasGroupCustomOrder) {
      return sortAlphabetically(a, b);
    }

    // if both elements are in the desiredGroupOrder array, they get sorted according to their order in
    // the desiredGroupOrder, then desiredNameOrder arrays.
    if (panelAHasGroupCustomOrder && panelBHasGroupCustomOrder) {
      var indexOfGroupA = desiredGroupOrder.indexOf(a.props.group);
      var indexOfGroupB = desiredGroupOrder.indexOf(b.props.group);

      if (indexOfGroupA < indexOfGroupB) {
        return -1;
      }

      if (indexOfGroupA > indexOfGroupB) {
        return 1;
      }

      if (indexOfGroupA === indexOfGroupB) {
        // Since Subpanels names can be reused in different groups
        // we compute desired order here to get the desired index right.
        // We are filtering on unique values, just in case, even if we don't
        // have to because within a given group we'd assume that there will be
        // no 2 subpanels named the same.
        var desiredNameOrder = order.filter(function (panel) {
          return panel.group === a.props.group;
        }).map(function (panel) {
          return panel.name;
        }).filter(getUniqueValues);

        var panelAHasNameCustomOrder = desiredNameOrder.includes(a.props.name);
        var panelBHasNameCustomOrder = desiredNameOrder.includes(b.props.name);

        if (!panelAHasNameCustomOrder || !panelBHasNameCustomOrder) {
          if (panelAHasNameCustomOrder && !panelBHasNameCustomOrder) {
            return -1;
          }
          if (!panelAHasNameCustomOrder && panelBHasNameCustomOrder) {
            return 1;
          }
          if (!panelAHasNameCustomOrder && !panelBHasNameCustomOrder) {
            return sortAlphabetically(a, b);
          }
        }

        if (panelAHasNameCustomOrder && panelBHasNameCustomOrder) {
          return desiredNameOrder.indexOf(a.props.name) - desiredNameOrder.indexOf(b.props.name);
        }
      }
    }
    return 0;
  });

  // PART 4: Return all children
  return prePanelsChildren.concat(panels).concat(postPanelsChildren);
}
//# sourceMappingURL=sortMenu.js.map

/***/ }),

/***/ "4j1d":
/*!******************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/LogoAmexIcon.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var LogoAmexIcon = function LogoAmexIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M1.438 24v-8.563h1.438l.313-.75h.688l.313.75h2.75v-.563l.25.563h1.438l.25-.563v.563h6.813v-1.25h.125c.125 0 .125.063.125.188v1.063h3.5v-.313c.813.438 1.938.313 2.813.313l.313-.75h.75l.313.75h2.813v-.75l.438.75h2.313v-4.75h-2.25v.563l-.313-.563h-2.375v.563l-.25-.563h-3.188c-.438 0-.938.063-1.375.25v-.25h-2.125v.25c-.25-.188-.625-.25-.938-.25H8.442l-.563 1.188-.5-1.188h-2.5v.563l-.313-.563H2.441l-1 2.25V8h29.125v8.563h-1.563c-.313 0-.688.063-1 .25v-.25h-2.25c-.313 0-.75.063-.938.25v-.25h-4v.25c-.313-.188-.75-.25-1.125-.25h-2.625v.25c-.25-.25-.813-.25-1.125-.25h-3l-.688.75-.625-.75H7.252v4.75h4.313l.688-.75.688.75h2.625v-1.125h.313c.375 0 .75 0 1.125-.125v1.25h2.188v-1.25h.125c.125 0 .125 0 .125.188v1.063h6.688c.375 0 .813-.063 1.125-.313v.313h2.125c.375 0 .813 0 1.188-.188v2.875zm8.812-9.25h-.813v-2.688L8.249 14.75h-.688l-1.188-2.688v2.688H4.685L4.372 14H2.684l-.313.75h-.938l1.5-3.438h1.188l1.438 3.25v-3.25h1.313l1.063 2.375 1-2.375h1.313zm-6.187-1.437L3.5 11.938l-.563 1.375zM14.875 19.5v1.188H13.25l-1-1.188-1.063 1.188H7.999V17.25h3.25l1 1.125 1.063-1.125h2.625c.75 0 1.375.25 1.375 1.125 0 1.375-1.5 1.125-2.438 1.125zm-3.125-.562l-.875-1H8.812v.625h1.75v.688h-1.75v.688h2l.938-1zm1.875-4.188h-2.75v-3.438h2.75v.75h-1.938v.625h1.875v.688h-1.875v.688h1.938zm.438 5.563v-2.688l-1.25 1.313zm2.812-7.125c.5.188.563.438.563.875v.688h-.813c0-.75.188-1.25-.75-1.25H15v1.25h-.813v-3.438l1.938.063c.688 0 1.375.063 1.375.875 0 .375-.25.813-.625.938zm-.937 4.75h-1.063v.875h1.063c.25 0 .5-.125.5-.438s-.25-.438-.5-.438zm.125-5.875H15v.75h1c.313 0 .563-.063.563-.375s-.25-.375-.5-.375zm4.312 7c.5.188.563.5.563.938v.688h-.813v-.625c0-.563-.188-.625-.75-.625H18.5v1.25h-.813v-3.438h1.938c.625 0 1.375.125 1.375.938a.94.94 0 0 1-.625.875zM18.75 14.75h-.813v-3.438h.813zm.813 3.188H18.5v.75h1.063c.25 0 .5-.063.5-.375s-.25-.375-.5-.375zm8.875-3.188h-1.125l-1.563-2.563v2.563h-1.688l-.313-.75h-1.688l-.313.75h-.938c-1.125 0-1.625-.563-1.625-1.688s.5-1.75 1.688-1.75h.813v.75c-.875 0-1.688-.188-1.688 1 0 .563.125 1 .813 1h.375l1.125-2.688h1.25l1.375 3.188v-3.188h1.25l1.438 2.375v-2.375h.813v3.375zm-4.25 5.938h-2.75V17.25h2.75v.688H22.25v.625h1.875v.688H22.25v.688h1.938zm-.688-7.375l-.563-1.375-.563 1.375zm2.75 7.375h-1.625v-.75h1.625c.188 0 .438-.063.438-.313 0-.75-2.125.25-2.125-1.375 0-.688.5-1 1.188-1h1.625v.688h-1.5c-.25 0-.438.063-.438.313 0 .75 2.063-.313 2.063 1.313 0 .813-.5 1.125-1.25 1.125zm4.313-.5c-.25.375-.75.5-1.125.5h-1.563v-.75h1.563c.188 0 .438-.063.438-.313 0-.75-2.125.25-2.125-1.375 0-.688.563-1 1.188-1h1.625v.688h-1.5c-.25 0-.438.063-.438.313 0 .625 1.375 0 1.938.688v1.25z' })
    );
};

exports.default = LogoAmexIcon;

/***/ }),

/***/ "4kuk":
/*!**************************************!*\
  !*** ./node_modules/lodash/_Hash.js ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var hashClear = __webpack_require__(/*! ./_hashClear */ "SfRM"),
    hashDelete = __webpack_require__(/*! ./_hashDelete */ "Hvzi"),
    hashGet = __webpack_require__(/*! ./_hashGet */ "u8Dt"),
    hashHas = __webpack_require__(/*! ./_hashHas */ "ekgI"),
    hashSet = __webpack_require__(/*! ./_hashSet */ "JSQU");

/**
 * 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]);
  }
}

// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;

module.exports = Hash;


/***/ }),

/***/ "4oK2":
/*!****************************************!*\
  !*** ./node_modules/entities/index.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var encode = __webpack_require__(/*! ./lib/encode.js */ "BRr/"),
    decode = __webpack_require__(/*! ./lib/decode.js */ "oW49");

exports.decode = function(data, level) {
    return (!level || level <= 0 ? decode.XML : decode.HTML)(data);
};

exports.decodeStrict = function(data, level) {
    return (!level || level <= 0 ? decode.XML : decode.HTMLStrict)(data);
};

exports.encode = function(data, level) {
    return (!level || level <= 0 ? encode.XML : encode.HTML)(data);
};

exports.encodeXML = encode.XML;

exports.encodeHTML4 = exports.encodeHTML5 = exports.encodeHTML = encode.HTML;

exports.decodeXML = exports.decodeXMLStrict = decode.XML;

exports.decodeHTML4 = exports.decodeHTML5 = exports.decodeHTML = decode.HTML;

exports.decodeHTML4Strict = exports.decodeHTML5Strict = exports.decodeHTMLStrict = decode.HTMLStrict;

exports.escape = encode.escape;


/***/ }),

/***/ "4pnw":
/*!*********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotScatterIcon.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotScatterIcon = function PlotScatterIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M0 8c0 1.5 1.188 2.688 2.688 2.688C4.126 10.688 5.313 9.5 5.313 8S4.125 5.312 2.688 5.312A2.668 2.668 0 0 0 0 8zm10.688 8c0 1.5 1.188 2.688 2.625 2.688 1.5 0 2.688-1.188 2.688-2.688s-1.188-2.688-2.688-2.688c-1.438 0-2.625 1.188-2.625 2.688zM16 9.313c0 1.5 1.188 2.688 2.688 2.688 1.438 0 2.625-1.188 2.625-2.688a2.64 2.64 0 0 0-2.625-2.625c-1.5 0-2.688 1.188-2.688 2.625zM5.313 24c0 1.5 1.188 2.688 2.688 2.688S10.689 25.5 10.689 24c0-1.5-1.188-2.688-2.688-2.688S5.313 22.5 5.313 24zm16-4c0 1.5 1.188 2.688 2.688 2.688S26.689 21.5 26.689 20c0-1.5-1.188-2.688-2.688-2.688S21.313 18.5 21.313 20zm5.375-8c0 1.5 1.188 2.688 2.625 2.688 1.5 0 2.688-1.188 2.688-2.688s-1.188-2.688-2.688-2.688c-1.438 0-2.625 1.188-2.625 2.688z' })
    );
};

exports.default = PlotScatterIcon;

/***/ }),

/***/ "4qC0":
/*!*****************************************!*\
  !*** ./node_modules/lodash/isString.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseGetTag = __webpack_require__(/*! ./_baseGetTag */ "NykK"),
    isArray = __webpack_require__(/*! ./isArray */ "Z0cm"),
    isObjectLike = __webpack_require__(/*! ./isObjectLike */ "ExA7");

/** `Object#toString` result references. */
var stringTag = '[object String]';

/**
 * 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);
}

module.exports = isString;


/***/ }),

/***/ "4qD0":
/*!**************************************!*\
  !*** ./node_modules/srcset/index.js ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var numberIsNan = __webpack_require__(/*! number-is-nan */ "vzE1");
var arrayUniq = __webpack_require__(/*! array-uniq */ "a0eB");
var reInt = /^\d+$/;

function deepUnique(arr) {
	return arr.sort().filter(function (el, i) {
		return JSON.stringify(el) !== JSON.stringify(arr[i - 1]);
	});
}

exports.parse = function (str) {
	return deepUnique(str.split(',').map(function (el) {
		var ret = {};

		el.trim().split(/\s+/).forEach(function (el, i) {
			if (i === 0) {
				return ret.url = el;
			}

			var value = el.substring(0, el.length - 1);
			var postfix = el[el.length - 1];
			var intVal = parseInt(value, 10);
			var floatVal = parseFloat(value);

			if (postfix === 'w' && reInt.test(value)) {
				ret.width = intVal;
			} else if (postfix === 'h' && reInt.test(value)) {
				ret.height = intVal;
			} else if (postfix === 'x' && !numberIsNan(floatVal)) {
				ret.density = floatVal;
			} else {
				throw new Error('Invalid srcset descriptor: ' + el + '.');
			}
		});

		return ret;
	}));
}

exports.stringify = function (arr) {
	return arrayUniq(arr.map(function (el) {
		if (!el.url) {
			throw new Error('URL is required.');
		}

		var ret = [el.url];

		if (el.width) {
			ret.push(el.width + 'w');
		}

		if (el.height) {
			ret.push(el.height + 'h');
		}

		if (el.density) {
			ret.push(el.density + 'x');
		}

		return ret.join(' ');
	})).join(', ');
}


/***/ }),

/***/ "4s8G":
/*!************************************************!*\
  !*** ./node_modules/xterm/lib/InputHandler.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var EscapeSequences_1 = __webpack_require__(/*! ./EscapeSequences */ "XYdm");
var Charsets_1 = __webpack_require__(/*! ./Charsets */ "rlhY");
var Buffer_1 = __webpack_require__(/*! ./Buffer */ "MsZC");
var Types_1 = __webpack_require__(/*! ./renderer/Types */ "jVSn");
var CharWidth_1 = __webpack_require__(/*! ./CharWidth */ "oV0L");
var InputHandler = (function () {
    function InputHandler(_terminal) {
        this._terminal = _terminal;
    }
    InputHandler.prototype.addChar = function (char, code) {
        if (char >= ' ') {
            var chWidth = CharWidth_1.wcwidth(code);
            if (this._terminal.charset && this._terminal.charset[char]) {
                char = this._terminal.charset[char];
            }
            if (this._terminal.options.screenReaderMode) {
                this._terminal.emit('a11y.char', char);
            }
            var row = this._terminal.buffer.y + this._terminal.buffer.ybase;
            if (!chWidth && this._terminal.buffer.x) {
                if (this._terminal.buffer.lines.get(row)[this._terminal.buffer.x - 1]) {
                    if (!this._terminal.buffer.lines.get(row)[this._terminal.buffer.x - 1][Buffer_1.CHAR_DATA_WIDTH_INDEX]) {
                        if (this._terminal.buffer.lines.get(row)[this._terminal.buffer.x - 2]) {
                            this._terminal.buffer.lines.get(row)[this._terminal.buffer.x - 2][Buffer_1.CHAR_DATA_CHAR_INDEX] += char;
                            this._terminal.buffer.lines.get(row)[this._terminal.buffer.x - 2][3] = char.charCodeAt(0);
                        }
                    }
                    else {
                        this._terminal.buffer.lines.get(row)[this._terminal.buffer.x - 1][Buffer_1.CHAR_DATA_CHAR_INDEX] += char;
                        this._terminal.buffer.lines.get(row)[this._terminal.buffer.x - 1][3] = char.charCodeAt(0);
                    }
                    this._terminal.updateRange(this._terminal.buffer.y);
                }
                return;
            }
            if (this._terminal.buffer.x + chWidth - 1 >= this._terminal.cols) {
                if (this._terminal.wraparoundMode) {
                    this._terminal.buffer.x = 0;
                    this._terminal.buffer.y++;
                    if (this._terminal.buffer.y > this._terminal.buffer.scrollBottom) {
                        this._terminal.buffer.y--;
                        this._terminal.scroll(true);
                    }
                    else {
                        this._terminal.buffer.lines.get(this._terminal.buffer.y).isWrapped = true;
                    }
                }
                else {
                    if (chWidth === 2) {
                        return;
                    }
                }
            }
            row = this._terminal.buffer.y + this._terminal.buffer.ybase;
            if (this._terminal.insertMode) {
                for (var moves = 0; moves < chWidth; ++moves) {
                    var removed = this._terminal.buffer.lines.get(this._terminal.buffer.y + this._terminal.buffer.ybase).pop();
                    if (removed[Buffer_1.CHAR_DATA_WIDTH_INDEX] === 0
                        && this._terminal.buffer.lines.get(row)[this._terminal.cols - 2]
                        && this._terminal.buffer.lines.get(row)[this._terminal.cols - 2][Buffer_1.CHAR_DATA_WIDTH_INDEX] === 2) {
                        this._terminal.buffer.lines.get(row)[this._terminal.cols - 2] = [this._terminal.curAttr, ' ', 1, ' '.charCodeAt(0)];
                    }
                    this._terminal.buffer.lines.get(row).splice(this._terminal.buffer.x, 0, [this._terminal.curAttr, ' ', 1, ' '.charCodeAt(0)]);
                }
            }
            this._terminal.buffer.lines.get(row)[this._terminal.buffer.x] = [this._terminal.curAttr, char, chWidth, char.charCodeAt(0)];
            this._terminal.buffer.x++;
            this._terminal.updateRange(this._terminal.buffer.y);
            if (chWidth === 2) {
                this._terminal.buffer.lines.get(row)[this._terminal.buffer.x] = [this._terminal.curAttr, '', 0, undefined];
                this._terminal.buffer.x++;
            }
        }
    };
    InputHandler.prototype.bell = function () {
        this._terminal.bell();
    };
    InputHandler.prototype.lineFeed = function () {
        if (this._terminal.convertEol) {
            this._terminal.buffer.x = 0;
        }
        this._terminal.buffer.y++;
        if (this._terminal.buffer.y > this._terminal.buffer.scrollBottom) {
            this._terminal.buffer.y--;
            this._terminal.scroll();
        }
        if (this._terminal.buffer.x >= this._terminal.cols) {
            this._terminal.buffer.x--;
        }
        this._terminal.emit('linefeed');
    };
    InputHandler.prototype.carriageReturn = function () {
        this._terminal.buffer.x = 0;
    };
    InputHandler.prototype.backspace = function () {
        if (this._terminal.buffer.x > 0) {
            this._terminal.buffer.x--;
        }
    };
    InputHandler.prototype.tab = function () {
        var originalX = this._terminal.buffer.x;
        this._terminal.buffer.x = this._terminal.buffer.nextStop();
        if (this._terminal.options.screenReaderMode) {
            this._terminal.emit('a11y.tab', this._terminal.buffer.x - originalX);
        }
    };
    InputHandler.prototype.shiftOut = function () {
        this._terminal.setgLevel(1);
    };
    InputHandler.prototype.shiftIn = function () {
        this._terminal.setgLevel(0);
    };
    InputHandler.prototype.insertChars = function (params) {
        var param = params[0];
        if (param < 1)
            param = 1;
        var row = this._terminal.buffer.y + this._terminal.buffer.ybase;
        var j = this._terminal.buffer.x;
        var ch = [this._terminal.eraseAttr(), ' ', 1, 32];
        while (param-- && j < this._terminal.cols) {
            this._terminal.buffer.lines.get(row).splice(j++, 0, ch);
            this._terminal.buffer.lines.get(row).pop();
        }
    };
    InputHandler.prototype.cursorUp = function (params) {
        var param = params[0];
        if (param < 1) {
            param = 1;
        }
        this._terminal.buffer.y -= param;
        if (this._terminal.buffer.y < 0) {
            this._terminal.buffer.y = 0;
        }
    };
    InputHandler.prototype.cursorDown = function (params) {
        var param = params[0];
        if (param < 1) {
            param = 1;
        }
        this._terminal.buffer.y += param;
        if (this._terminal.buffer.y >= this._terminal.rows) {
            this._terminal.buffer.y = this._terminal.rows - 1;
        }
        if (this._terminal.buffer.x >= this._terminal.cols) {
            this._terminal.buffer.x--;
        }
    };
    InputHandler.prototype.cursorForward = function (params) {
        var param = params[0];
        if (param < 1) {
            param = 1;
        }
        this._terminal.buffer.x += param;
        if (this._terminal.buffer.x >= this._terminal.cols) {
            this._terminal.buffer.x = this._terminal.cols - 1;
        }
    };
    InputHandler.prototype.cursorBackward = function (params) {
        var param = params[0];
        if (param < 1) {
            param = 1;
        }
        if (this._terminal.buffer.x >= this._terminal.cols) {
            this._terminal.buffer.x--;
        }
        this._terminal.buffer.x -= param;
        if (this._terminal.buffer.x < 0) {
            this._terminal.buffer.x = 0;
        }
    };
    InputHandler.prototype.cursorNextLine = function (params) {
        var param = params[0];
        if (param < 1) {
            param = 1;
        }
        this._terminal.buffer.y += param;
        if (this._terminal.buffer.y >= this._terminal.rows) {
            this._terminal.buffer.y = this._terminal.rows - 1;
        }
        this._terminal.buffer.x = 0;
    };
    InputHandler.prototype.cursorPrecedingLine = function (params) {
        var param = params[0];
        if (param < 1) {
            param = 1;
        }
        this._terminal.buffer.y -= param;
        if (this._terminal.buffer.y < 0) {
            this._terminal.buffer.y = 0;
        }
        this._terminal.buffer.x = 0;
    };
    InputHandler.prototype.cursorCharAbsolute = function (params) {
        var param = params[0];
        if (param < 1) {
            param = 1;
        }
        this._terminal.buffer.x = param - 1;
    };
    InputHandler.prototype.cursorPosition = function (params) {
        var col;
        var row = params[0] - 1;
        if (params.length >= 2) {
            col = params[1] - 1;
        }
        else {
            col = 0;
        }
        if (row < 0) {
            row = 0;
        }
        else if (row >= this._terminal.rows) {
            row = this._terminal.rows - 1;
        }
        if (col < 0) {
            col = 0;
        }
        else if (col >= this._terminal.cols) {
            col = this._terminal.cols - 1;
        }
        this._terminal.buffer.x = col;
        this._terminal.buffer.y = row;
    };
    InputHandler.prototype.cursorForwardTab = function (params) {
        var param = params[0] || 1;
        while (param--) {
            this._terminal.buffer.x = this._terminal.buffer.nextStop();
        }
    };
    InputHandler.prototype.eraseInDisplay = function (params) {
        var j;
        switch (params[0]) {
            case 0:
                this._terminal.eraseRight(this._terminal.buffer.x, this._terminal.buffer.y);
                j = this._terminal.buffer.y + 1;
                for (; j < this._terminal.rows; j++) {
                    this._terminal.eraseLine(j);
                }
                break;
            case 1:
                this._terminal.eraseLeft(this._terminal.buffer.x, this._terminal.buffer.y);
                j = this._terminal.buffer.y;
                while (j--) {
                    this._terminal.eraseLine(j);
                }
                break;
            case 2:
                j = this._terminal.rows;
                while (j--)
                    this._terminal.eraseLine(j);
                break;
            case 3:
                var scrollBackSize = this._terminal.buffer.lines.length - this._terminal.rows;
                if (scrollBackSize > 0) {
                    this._terminal.buffer.lines.trimStart(scrollBackSize);
                    this._terminal.buffer.ybase = Math.max(this._terminal.buffer.ybase - scrollBackSize, 0);
                    this._terminal.buffer.ydisp = Math.max(this._terminal.buffer.ydisp - scrollBackSize, 0);
                    this._terminal.emit('scroll', 0);
                }
                break;
        }
    };
    InputHandler.prototype.eraseInLine = function (params) {
        switch (params[0]) {
            case 0:
                this._terminal.eraseRight(this._terminal.buffer.x, this._terminal.buffer.y);
                break;
            case 1:
                this._terminal.eraseLeft(this._terminal.buffer.x, this._terminal.buffer.y);
                break;
            case 2:
                this._terminal.eraseLine(this._terminal.buffer.y);
                break;
        }
    };
    InputHandler.prototype.insertLines = function (params) {
        var param = params[0];
        if (param < 1) {
            param = 1;
        }
        var row = this._terminal.buffer.y + this._terminal.buffer.ybase;
        var scrollBottomRowsOffset = this._terminal.rows - 1 - this._terminal.buffer.scrollBottom;
        var scrollBottomAbsolute = this._terminal.rows - 1 + this._terminal.buffer.ybase - scrollBottomRowsOffset + 1;
        while (param--) {
            this._terminal.buffer.lines.splice(scrollBottomAbsolute - 1, 1);
            this._terminal.buffer.lines.splice(row, 0, this._terminal.blankLine(true));
        }
        this._terminal.updateRange(this._terminal.buffer.y);
        this._terminal.updateRange(this._terminal.buffer.scrollBottom);
    };
    InputHandler.prototype.deleteLines = function (params) {
        var param = params[0];
        if (param < 1) {
            param = 1;
        }
        var row = this._terminal.buffer.y + this._terminal.buffer.ybase;
        var j;
        j = this._terminal.rows - 1 - this._terminal.buffer.scrollBottom;
        j = this._terminal.rows - 1 + this._terminal.buffer.ybase - j;
        while (param--) {
            this._terminal.buffer.lines.splice(row, 1);
            this._terminal.buffer.lines.splice(j, 0, this._terminal.blankLine(true));
        }
        this._terminal.updateRange(this._terminal.buffer.y);
        this._terminal.updateRange(this._terminal.buffer.scrollBottom);
    };
    InputHandler.prototype.deleteChars = function (params) {
        var param = params[0];
        if (param < 1) {
            param = 1;
        }
        var row = this._terminal.buffer.y + this._terminal.buffer.ybase;
        var ch = [this._terminal.eraseAttr(), ' ', 1, 32];
        while (param--) {
            this._terminal.buffer.lines.get(row).splice(this._terminal.buffer.x, 1);
            this._terminal.buffer.lines.get(row).push(ch);
        }
        this._terminal.updateRange(this._terminal.buffer.y);
    };
    InputHandler.prototype.scrollUp = function (params) {
        var param = params[0] || 1;
        while (param--) {
            this._terminal.buffer.lines.splice(this._terminal.buffer.ybase + this._terminal.buffer.scrollTop, 1);
            this._terminal.buffer.lines.splice(this._terminal.buffer.ybase + this._terminal.buffer.scrollBottom, 0, this._terminal.blankLine());
        }
        this._terminal.updateRange(this._terminal.buffer.scrollTop);
        this._terminal.updateRange(this._terminal.buffer.scrollBottom);
    };
    InputHandler.prototype.scrollDown = function (params) {
        var param = params[0] || 1;
        while (param--) {
            this._terminal.buffer.lines.splice(this._terminal.buffer.ybase + this._terminal.buffer.scrollBottom, 1);
            this._terminal.buffer.lines.splice(this._terminal.buffer.ybase + this._terminal.buffer.scrollTop, 0, this._terminal.blankLine());
        }
        this._terminal.updateRange(this._terminal.buffer.scrollTop);
        this._terminal.updateRange(this._terminal.buffer.scrollBottom);
    };
    InputHandler.prototype.eraseChars = function (params) {
        var param = params[0];
        if (param < 1) {
            param = 1;
        }
        var row = this._terminal.buffer.y + this._terminal.buffer.ybase;
        var j = this._terminal.buffer.x;
        var ch = [this._terminal.eraseAttr(), ' ', 1, 32];
        while (param-- && j < this._terminal.cols) {
            this._terminal.buffer.lines.get(row)[j++] = ch;
        }
    };
    InputHandler.prototype.cursorBackwardTab = function (params) {
        var param = params[0] || 1;
        while (param--) {
            this._terminal.buffer.x = this._terminal.buffer.prevStop();
        }
    };
    InputHandler.prototype.charPosAbsolute = function (params) {
        var param = params[0];
        if (param < 1) {
            param = 1;
        }
        this._terminal.buffer.x = param - 1;
        if (this._terminal.buffer.x >= this._terminal.cols) {
            this._terminal.buffer.x = this._terminal.cols - 1;
        }
    };
    InputHandler.prototype.HPositionRelative = function (params) {
        var param = params[0];
        if (param < 1) {
            param = 1;
        }
        this._terminal.buffer.x += param;
        if (this._terminal.buffer.x >= this._terminal.cols) {
            this._terminal.buffer.x = this._terminal.cols - 1;
        }
    };
    InputHandler.prototype.repeatPrecedingCharacter = function (params) {
        var param = params[0] || 1;
        var line = this._terminal.buffer.lines.get(this._terminal.buffer.ybase + this._terminal.buffer.y);
        var ch = line[this._terminal.buffer.x - 1] || [this._terminal.defAttr, ' ', 1, 32];
        while (param--) {
            line[this._terminal.buffer.x++] = ch;
        }
    };
    InputHandler.prototype.sendDeviceAttributes = function (params) {
        if (params[0] > 0) {
            return;
        }
        if (!this._terminal.prefix) {
            if (this._terminal.is('xterm') || this._terminal.is('rxvt-unicode') || this._terminal.is('screen')) {
                this._terminal.send(EscapeSequences_1.C0.ESC + '[?1;2c');
            }
            else if (this._terminal.is('linux')) {
                this._terminal.send(EscapeSequences_1.C0.ESC + '[?6c');
            }
        }
        else if (this._terminal.prefix === '>') {
            if (this._terminal.is('xterm')) {
                this._terminal.send(EscapeSequences_1.C0.ESC + '[>0;276;0c');
            }
            else if (this._terminal.is('rxvt-unicode')) {
                this._terminal.send(EscapeSequences_1.C0.ESC + '[>85;95;0c');
            }
            else if (this._terminal.is('linux')) {
                this._terminal.send(params[0] + 'c');
            }
            else if (this._terminal.is('screen')) {
                this._terminal.send(EscapeSequences_1.C0.ESC + '[>83;40003;0c');
            }
        }
    };
    InputHandler.prototype.linePosAbsolute = function (params) {
        var param = params[0];
        if (param < 1) {
            param = 1;
        }
        this._terminal.buffer.y = param - 1;
        if (this._terminal.buffer.y >= this._terminal.rows) {
            this._terminal.buffer.y = this._terminal.rows - 1;
        }
    };
    InputHandler.prototype.VPositionRelative = function (params) {
        var param = params[0];
        if (param < 1) {
            param = 1;
        }
        this._terminal.buffer.y += param;
        if (this._terminal.buffer.y >= this._terminal.rows) {
            this._terminal.buffer.y = this._terminal.rows - 1;
        }
        if (this._terminal.buffer.x >= this._terminal.cols) {
            this._terminal.buffer.x--;
        }
    };
    InputHandler.prototype.HVPosition = function (params) {
        if (params[0] < 1)
            params[0] = 1;
        if (params[1] < 1)
            params[1] = 1;
        this._terminal.buffer.y = params[0] - 1;
        if (this._terminal.buffer.y >= this._terminal.rows) {
            this._terminal.buffer.y = this._terminal.rows - 1;
        }
        this._terminal.buffer.x = params[1] - 1;
        if (this._terminal.buffer.x >= this._terminal.cols) {
            this._terminal.buffer.x = this._terminal.cols - 1;
        }
    };
    InputHandler.prototype.tabClear = function (params) {
        var param = params[0];
        if (param <= 0) {
            delete this._terminal.buffer.tabs[this._terminal.buffer.x];
        }
        else if (param === 3) {
            this._terminal.buffer.tabs = {};
        }
    };
    InputHandler.prototype.setMode = function (params) {
        if (params.length > 1) {
            for (var i = 0; i < params.length; i++) {
                this.setMode([params[i]]);
            }
            return;
        }
        if (!this._terminal.prefix) {
            switch (params[0]) {
                case 4:
                    this._terminal.insertMode = true;
                    break;
                case 20:
                    break;
            }
        }
        else if (this._terminal.prefix === '?') {
            switch (params[0]) {
                case 1:
                    this._terminal.applicationCursor = true;
                    break;
                case 2:
                    this._terminal.setgCharset(0, Charsets_1.DEFAULT_CHARSET);
                    this._terminal.setgCharset(1, Charsets_1.DEFAULT_CHARSET);
                    this._terminal.setgCharset(2, Charsets_1.DEFAULT_CHARSET);
                    this._terminal.setgCharset(3, Charsets_1.DEFAULT_CHARSET);
                    break;
                case 3:
                    this._terminal.savedCols = this._terminal.cols;
                    this._terminal.resize(132, this._terminal.rows);
                    break;
                case 6:
                    this._terminal.originMode = true;
                    break;
                case 7:
                    this._terminal.wraparoundMode = true;
                    break;
                case 12:
                    break;
                case 66:
                    this._terminal.log('Serial port requested application keypad.');
                    this._terminal.applicationKeypad = true;
                    this._terminal.viewport.syncScrollArea();
                    break;
                case 9:
                case 1000:
                case 1002:
                case 1003:
                    this._terminal.x10Mouse = params[0] === 9;
                    this._terminal.vt200Mouse = params[0] === 1000;
                    this._terminal.normalMouse = params[0] > 1000;
                    this._terminal.mouseEvents = true;
                    this._terminal.element.classList.add('enable-mouse-events');
                    this._terminal.selectionManager.disable();
                    this._terminal.log('Binding to mouse events.');
                    break;
                case 1004:
                    this._terminal.sendFocus = true;
                    break;
                case 1005:
                    this._terminal.utfMouse = true;
                    break;
                case 1006:
                    this._terminal.sgrMouse = true;
                    break;
                case 1015:
                    this._terminal.urxvtMouse = true;
                    break;
                case 25:
                    this._terminal.cursorHidden = false;
                    break;
                case 1049:
                case 47:
                case 1047:
                    this._terminal.buffers.activateAltBuffer();
                    this._terminal.viewport.syncScrollArea();
                    this._terminal.showCursor();
                    break;
                case 2004:
                    this._terminal.bracketedPasteMode = true;
                    break;
            }
        }
    };
    InputHandler.prototype.resetMode = function (params) {
        if (params.length > 1) {
            for (var i = 0; i < params.length; i++) {
                this.resetMode([params[i]]);
            }
            return;
        }
        if (!this._terminal.prefix) {
            switch (params[0]) {
                case 4:
                    this._terminal.insertMode = false;
                    break;
                case 20:
                    break;
            }
        }
        else if (this._terminal.prefix === '?') {
            switch (params[0]) {
                case 1:
                    this._terminal.applicationCursor = false;
                    break;
                case 3:
                    if (this._terminal.cols === 132 && this._terminal.savedCols) {
                        this._terminal.resize(this._terminal.savedCols, this._terminal.rows);
                    }
                    delete this._terminal.savedCols;
                    break;
                case 6:
                    this._terminal.originMode = false;
                    break;
                case 7:
                    this._terminal.wraparoundMode = false;
                    break;
                case 12:
                    break;
                case 66:
                    this._terminal.log('Switching back to normal keypad.');
                    this._terminal.applicationKeypad = false;
                    this._terminal.viewport.syncScrollArea();
                    break;
                case 9:
                case 1000:
                case 1002:
                case 1003:
                    this._terminal.x10Mouse = false;
                    this._terminal.vt200Mouse = false;
                    this._terminal.normalMouse = false;
                    this._terminal.mouseEvents = false;
                    this._terminal.element.classList.remove('enable-mouse-events');
                    this._terminal.selectionManager.enable();
                    break;
                case 1004:
                    this._terminal.sendFocus = false;
                    break;
                case 1005:
                    this._terminal.utfMouse = false;
                    break;
                case 1006:
                    this._terminal.sgrMouse = false;
                    break;
                case 1015:
                    this._terminal.urxvtMouse = false;
                    break;
                case 25:
                    this._terminal.cursorHidden = true;
                    break;
                case 1049:
                case 47:
                case 1047:
                    this._terminal.buffers.activateNormalBuffer();
                    this._terminal.refresh(0, this._terminal.rows - 1);
                    this._terminal.viewport.syncScrollArea();
                    this._terminal.showCursor();
                    break;
                case 2004:
                    this._terminal.bracketedPasteMode = false;
                    break;
            }
        }
    };
    InputHandler.prototype.charAttributes = function (params) {
        if (params.length === 1 && params[0] === 0) {
            this._terminal.curAttr = this._terminal.defAttr;
            return;
        }
        var l = params.length;
        var flags = this._terminal.curAttr >> 18;
        var fg = (this._terminal.curAttr >> 9) & 0x1ff;
        var bg = this._terminal.curAttr & 0x1ff;
        var p;
        for (var i = 0; i < l; i++) {
            p = params[i];
            if (p >= 30 && p <= 37) {
                fg = p - 30;
            }
            else if (p >= 40 && p <= 47) {
                bg = p - 40;
            }
            else if (p >= 90 && p <= 97) {
                p += 8;
                fg = p - 90;
            }
            else if (p >= 100 && p <= 107) {
                p += 8;
                bg = p - 100;
            }
            else if (p === 0) {
                flags = this._terminal.defAttr >> 18;
                fg = (this._terminal.defAttr >> 9) & 0x1ff;
                bg = this._terminal.defAttr & 0x1ff;
            }
            else if (p === 1) {
                flags |= Types_1.FLAGS.BOLD;
            }
            else if (p === 4) {
                flags |= Types_1.FLAGS.UNDERLINE;
            }
            else if (p === 5) {
                flags |= Types_1.FLAGS.BLINK;
            }
            else if (p === 7) {
                flags |= Types_1.FLAGS.INVERSE;
            }
            else if (p === 8) {
                flags |= Types_1.FLAGS.INVISIBLE;
            }
            else if (p === 2) {
                flags |= Types_1.FLAGS.DIM;
            }
            else if (p === 22) {
                flags &= ~Types_1.FLAGS.BOLD;
                flags &= ~Types_1.FLAGS.DIM;
            }
            else if (p === 24) {
                flags &= ~Types_1.FLAGS.UNDERLINE;
            }
            else if (p === 25) {
                flags &= ~Types_1.FLAGS.BLINK;
            }
            else if (p === 27) {
                flags &= ~Types_1.FLAGS.INVERSE;
            }
            else if (p === 28) {
                flags &= ~Types_1.FLAGS.INVISIBLE;
            }
            else if (p === 39) {
                fg = (this._terminal.defAttr >> 9) & 0x1ff;
            }
            else if (p === 49) {
                bg = this._terminal.defAttr & 0x1ff;
            }
            else if (p === 38) {
                if (params[i + 1] === 2) {
                    i += 2;
                    fg = this._terminal.matchColor(params[i] & 0xff, params[i + 1] & 0xff, params[i + 2] & 0xff);
                    if (fg === -1)
                        fg = 0x1ff;
                    i += 2;
                }
                else if (params[i + 1] === 5) {
                    i += 2;
                    p = params[i] & 0xff;
                    fg = p;
                }
            }
            else if (p === 48) {
                if (params[i + 1] === 2) {
                    i += 2;
                    bg = this._terminal.matchColor(params[i] & 0xff, params[i + 1] & 0xff, params[i + 2] & 0xff);
                    if (bg === -1)
                        bg = 0x1ff;
                    i += 2;
                }
                else if (params[i + 1] === 5) {
                    i += 2;
                    p = params[i] & 0xff;
                    bg = p;
                }
            }
            else if (p === 100) {
                fg = (this._terminal.defAttr >> 9) & 0x1ff;
                bg = this._terminal.defAttr & 0x1ff;
            }
            else {
                this._terminal.error('Unknown SGR attribute: %d.', p);
            }
        }
        this._terminal.curAttr = (flags << 18) | (fg << 9) | bg;
    };
    InputHandler.prototype.deviceStatus = function (params) {
        if (!this._terminal.prefix) {
            switch (params[0]) {
                case 5:
                    this._terminal.send(EscapeSequences_1.C0.ESC + '[0n');
                    break;
                case 6:
                    this._terminal.send(EscapeSequences_1.C0.ESC + '['
                        + (this._terminal.buffer.y + 1)
                        + ';'
                        + (this._terminal.buffer.x + 1)
                        + 'R');
                    break;
            }
        }
        else if (this._terminal.prefix === '?') {
            switch (params[0]) {
                case 6:
                    this._terminal.send(EscapeSequences_1.C0.ESC + '[?'
                        + (this._terminal.buffer.y + 1)
                        + ';'
                        + (this._terminal.buffer.x + 1)
                        + 'R');
                    break;
                case 15:
                    break;
                case 25:
                    break;
                case 26:
                    break;
                case 53:
                    break;
            }
        }
    };
    InputHandler.prototype.softReset = function (params) {
        this._terminal.cursorHidden = false;
        this._terminal.insertMode = false;
        this._terminal.originMode = false;
        this._terminal.wraparoundMode = true;
        this._terminal.applicationKeypad = false;
        this._terminal.viewport.syncScrollArea();
        this._terminal.applicationCursor = false;
        this._terminal.buffer.scrollTop = 0;
        this._terminal.buffer.scrollBottom = this._terminal.rows - 1;
        this._terminal.curAttr = this._terminal.defAttr;
        this._terminal.buffer.x = this._terminal.buffer.y = 0;
        this._terminal.charset = null;
        this._terminal.glevel = 0;
        this._terminal.charsets = [null];
    };
    InputHandler.prototype.setCursorStyle = function (params) {
        var param = params[0] < 1 ? 1 : params[0];
        switch (param) {
            case 1:
            case 2:
                this._terminal.setOption('cursorStyle', 'block');
                break;
            case 3:
            case 4:
                this._terminal.setOption('cursorStyle', 'underline');
                break;
            case 5:
            case 6:
                this._terminal.setOption('cursorStyle', 'bar');
                break;
        }
        var isBlinking = param % 2 === 1;
        this._terminal.setOption('cursorBlink', isBlinking);
    };
    InputHandler.prototype.setScrollRegion = function (params) {
        if (this._terminal.prefix)
            return;
        this._terminal.buffer.scrollTop = (params[0] || 1) - 1;
        this._terminal.buffer.scrollBottom = (params[1] && params[1] <= this._terminal.rows ? params[1] : this._terminal.rows) - 1;
        this._terminal.buffer.x = 0;
        this._terminal.buffer.y = 0;
    };
    InputHandler.prototype.saveCursor = function (params) {
        this._terminal.buffer.savedX = this._terminal.buffer.x;
        this._terminal.buffer.savedY = this._terminal.buffer.y;
    };
    InputHandler.prototype.restoreCursor = function (params) {
        this._terminal.buffer.x = this._terminal.buffer.savedX || 0;
        this._terminal.buffer.y = this._terminal.buffer.savedY || 0;
    };
    return InputHandler;
}());
exports.InputHandler = InputHandler;

//# sourceMappingURL=InputHandler.js.map


/***/ }),

/***/ "4sDh":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_hasPath.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var castPath = __webpack_require__(/*! ./_castPath */ "4uTw"),
    isArguments = __webpack_require__(/*! ./isArguments */ "03A+"),
    isArray = __webpack_require__(/*! ./isArray */ "Z0cm"),
    isIndex = __webpack_require__(/*! ./_isIndex */ "wJg7"),
    isLength = __webpack_require__(/*! ./isLength */ "shjB"),
    toKey = __webpack_require__(/*! ./_toKey */ "9Nap");

/**
 * 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));
}

module.exports = hasPath;


/***/ }),

/***/ "4uTw":
/*!******************************************!*\
  !*** ./node_modules/lodash/_castPath.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isArray = __webpack_require__(/*! ./isArray */ "Z0cm"),
    isKey = __webpack_require__(/*! ./_isKey */ "9ggG"),
    stringToPath = __webpack_require__(/*! ./_stringToPath */ "GNiM"),
    toString = __webpack_require__(/*! ./toString */ "dt0z");

/**
 * 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));
}

module.exports = castPath;


/***/ }),

/***/ "4vnq":
/*!***************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/apputils/style/toolbar.css ***!
  \***************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2016, Jupyter Development Team.\n|\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n:root {\n  --jp-private-toolbar-height: calc(\n    28px + var(--jp-border-width)\n  ); /* leave 28px for content */\n}\n\n.jp-Toolbar {\n  color: var(--jp-ui-font-color1);\n  flex: 0 0 auto;\n  display: flex;\n  flex-direction: row;\n  border-bottom: var(--jp-border-width) solid var(--jp-toolbar-border-color);\n  box-shadow: var(--jp-toolbar-box-shadow);\n  background: var(--jp-toolbar-background);\n  min-height: var(--jp-toolbar-micro-height);\n  padding: 2px;\n  z-index: 1;\n}\n\n/* Toolbar items */\n\n.jp-Toolbar > .jp-Toolbar-item.jp-Toolbar-spacer {\n  flex-grow: 1;\n  flex-shrink: 1;\n}\n\n.jp-Toolbar-item.jp-Toolbar-kernelStatus {\n  display: inline-block;\n  width: 32px;\n  background-repeat: no-repeat;\n  background-position: center;\n  background-size: 16px;\n}\n\n.jp-Toolbar > .jp-Toolbar-item {\n  flex: 0 0 auto;\n  display: flex;\n  padding-left: 1px;\n  padding-right: 1px;\n  font-size: var(--jp-ui-font-size1);\n  line-height: var(--jp-private-toolbar-height);\n  height: 100%;\n}\n\n/* Toolbar buttons */\n\n/* This is the div we use to wrap the react component into a Widget */\ndiv.jp-ToolbarButton {\n  color: transparent;\n  border: none;\n  box-sizing: border-box;\n  outline: none;\n  appearance: none;\n  -webkit-appearance: none;\n  -moz-appearance: none;\n  padding: 0px;\n  margin: 0px;\n}\n\nbutton.jp-ToolbarButtonComponent {\n  background: var(--jp-layout-color1);\n  border: none;\n  box-sizing: border-box;\n  outline: none;\n  appearance: none;\n  -webkit-appearance: none;\n  -moz-appearance: none;\n  padding: 0px 6px;\n  margin: 0px;\n  height: 24px;\n  border-radius: var(--jp-border-radius);\n  display: flex;\n  align-items: center;\n}\n\nbutton.jp-ToolbarButtonComponent:focus {\n  background: var(--jp-layout-color2);\n}\n\nbutton.jp-ToolbarButtonComponent:enabled:hover {\n  background: var(--jp-layout-color2);\n}\n\nbutton.jp-ToolbarButtonComponent:enabled:active {\n  background: var(--jp-layout-color3);\n}\n\nbutton.jp-ToolbarButtonComponent:disabled {\n  opacity: 0.4;\n}\n\nbutton.jp-ToolbarButtonComponent span {\n  padding: 0px;\n  flex: 0 0 auto;\n}\n\nbutton.jp-ToolbarButtonComponent .jp-ToolbarButtonComponent-label {\n  font-size: var(--jp-ui-font-size1);\n  line-height: 100%;\n  padding-left: 2px;\n  color: var(--jp-ui-font-color1);\n}\n", ""]);

// exports


/***/ }),

/***/ "4xXw":
/*!*******************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/react-day-picker/lib/style.css ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/* DayPicker styles */\n\n.DayPicker {\n  display: inline-block;\n  font-size: 1rem;\n}\n\n.DayPicker-wrapper {\n  position: relative;\n\n  flex-direction: row;\n  padding-bottom: 1em;\n\n  -webkit-user-select: none;\n\n     -moz-user-select: none;\n\n      -ms-user-select: none;\n\n          user-select: none;\n}\n\n.DayPicker-Months {\n  display: flex;\n  flex-wrap: wrap;\n  justify-content: center;\n}\n\n.DayPicker-Month {\n  display: table;\n  margin: 0 1em;\n  margin-top: 1em;\n  border-spacing: 0;\n  border-collapse: collapse;\n\n  -webkit-user-select: none;\n\n     -moz-user-select: none;\n\n      -ms-user-select: none;\n\n          user-select: none;\n}\n\n.DayPicker-NavBar {\n}\n\n.DayPicker-NavButton {\n  position: absolute;\n  top: 1em;\n  right: 1.5em;\n  left: auto;\n\n  display: inline-block;\n  margin-top: 2px;\n  width: 1.25em;\n  height: 1.25em;\n  background-position: center;\n  background-size: 50%;\n  background-repeat: no-repeat;\n  color: #8B9898;\n  cursor: pointer;\n}\n\n.DayPicker-NavButton:hover {\n  opacity: 0.8;\n}\n\n.DayPicker-NavButton--prev {\n  margin-right: 1.5em;\n  background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACQAAAAwCAYAAAB5R9gVAAAABGdBTUEAALGPC/xhBQAAAVVJREFUWAnN2G0KgjAYwPHpGfRkaZeqvgQaK+hY3SUHrk1YzNLay/OiEFp92I+/Mp2F2Mh2lLISWnflFjzH263RQjzMZ19wgs73ez0o1WmtW+dgA01VxrE3p6l2GLsnBy1VYQOtVSEH/atCCgqpQgKKqYIOiq2CBkqtggLKqQIKgqgCBjpJ2Y5CdJ+zrT9A7HHSTA1dxUdHgzCqJIEwq0SDsKsEg6iqBIEoq/wEcVRZBXFV+QJxV5mBtlDFB5VjYTaGZ2sf4R9PM7U9ZU+lLuaetPP/5Die3ToO1+u+MKtHs06qODB2zBnI/jBd4MPQm1VkY79Tb18gB+C62FdBFsZR6yeIo1YQiLJWMIiqVjQIu1YSCLNWFgijVjYIuhYYCKoWKAiiFgoopxYaKLUWOii2FgkophYp6F3r42W5A9s9OcgNvva8xQaysKXlFytoqdYmQH6tF3toSUo0INq9AAAAAElFTkSuQmCC');\n}\n\n.DayPicker-NavButton--next {\n  background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACQAAAAwCAYAAAB5R9gVAAAABGdBTUEAALGPC/xhBQAAAXRJREFUWAnN119ugjAcwPHWzJ1gnmxzB/BBE0n24m4xfNkTaOL7wOtsl3AXMMb+Vjaa1BG00N8fSEibPpAP3xAKKs2yjzTPH9RAjhEo9WzPr/Vm8zgE0+gXATAxxuxtqeJ9t5tIwv5AtQAApsfT6TPdbp+kUBcgVwvO51KqVhMkXKsVJFXrOkigVhCIs1Y4iKlWZxB1rX4gwlpRIIpa8SDkWmggrFq4IIRaJKCYWnSgnrXIQV1r8YD+1Vrn+bReagysIFfLABRt31v8oBu1xEBttfRbltmfjgEcWh9snUS2kNdBK6WN1vrOWxObWsz+fjxevsxmB1GQDfINWiev83nhaoiB/CoOU438oPrhXS0WpQ9xc1ZQWxWHqUYe0I0qrKCQKjygDlXIQV2r0IF6ViEBxVTBBSFUQQNhVYkHIVeJAtkNsbQ7c1LtzP6FsObhb2rCKv7NBIGoq4SDmKoEgTirXAcJVGkFSVVpgoSrXICGUMUH/QBZNSUy5XWUhwAAAABJRU5ErkJggg==');\n}\n\n.DayPicker-NavButton--interactionDisabled {\n  display: none;\n}\n\n.DayPicker-Caption {\n  display: table-caption;\n  margin-bottom: 0.5em;\n  padding: 0 0.5em;\n  text-align: left;\n}\n\n.DayPicker-Caption > div {\n  font-weight: 500;\n  font-size: 1.15em;\n}\n\n.DayPicker-Weekdays {\n  display: table-header-group;\n  margin-top: 1em;\n}\n\n.DayPicker-WeekdaysRow {\n  display: table-row;\n}\n\n.DayPicker-Weekday {\n  display: table-cell;\n  padding: 0.5em;\n  color: #8B9898;\n  text-align: center;\n  font-size: 0.875em;\n}\n\n.DayPicker-Weekday abbr[title] {\n  border-bottom: none;\n  text-decoration: none;\n}\n\n.DayPicker-Body {\n  display: table-row-group;\n}\n\n.DayPicker-Week {\n  display: table-row;\n}\n\n.DayPicker-Day {\n  display: table-cell;\n  padding: 0.5em;\n  border-radius: 50%;\n  vertical-align: middle;\n  text-align: center;\n  cursor: pointer;\n}\n\n.DayPicker-WeekNumber {\n  display: table-cell;\n  padding: 0.5em;\n  min-width: 1em;\n  border-right: 1px solid #EAECEC;\n  color: #8B9898;\n  vertical-align: middle;\n  text-align: right;\n  font-size: 0.75em;\n  cursor: pointer;\n}\n\n.DayPicker--interactionDisabled .DayPicker-Day {\n  cursor: default;\n}\n\n.DayPicker-Footer {\n  padding-top: 0.5em;\n}\n\n.DayPicker-TodayButton {\n  border: none;\n  background-color: transparent;\n  background-image: none;\n  box-shadow: none;\n  color: #4A90E2;\n  font-size: 0.875em;\n  cursor: pointer;\n}\n\n/* Default modifiers */\n\n.DayPicker-Day--today {\n  color: #D0021B;\n  font-weight: 700;\n}\n\n.DayPicker-Day--outside {\n  color: #8B9898;\n  cursor: default;\n}\n\n.DayPicker-Day--disabled {\n  color: #DCE0E0;\n  cursor: default;\n  /* background-color: #eff1f1; */\n}\n\n/* Example modifiers */\n\n.DayPicker-Day--sunday {\n  background-color: #F7F8F8;\n}\n\n.DayPicker-Day--sunday:not(.DayPicker-Day--today) {\n  color: #DCE0E0;\n}\n\n.DayPicker-Day--selected:not(.DayPicker-Day--disabled):not(.DayPicker-Day--outside) {\n  position: relative;\n\n  background-color: #4A90E2;\n  color: #F0F8FF;\n}\n\n.DayPicker-Day--selected:not(.DayPicker-Day--disabled):not(.DayPicker-Day--outside):hover {\n  background-color: #51A0FA;\n}\n\n.DayPicker:not(.DayPicker--interactionDisabled)\n  .DayPicker-Day:not(.DayPicker-Day--disabled):not(.DayPicker-Day--selected):not(.DayPicker-Day--outside):hover {\n  background-color: #F0F8FF;\n}\n\n/* DayPickerInput */\n\n.DayPickerInput {\n  display: inline-block;\n}\n\n.DayPickerInput-OverlayWrapper {\n  position: relative;\n}\n\n.DayPickerInput-Overlay {\n  position: absolute;\n  left: 0;\n  z-index: 1;\n\n  background: white;\n  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.15);\n}\n", ""]);

// exports


/***/ }),

/***/ "4xm7":
/*!*************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotCandlestickIcon.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotCandlestickIcon = function PlotCandlestickIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M11.563 4.688h-2.25v-4c.063-.188 0-.313-.125-.438C9.125.125 8.938 0 8.813 0H7.438a.71.71 0 0 0-.5.188.568.568 0 0 0-.25.5v4h-2c-.938 0-2-.438-2 1.313v20a2.26 2.26 0 0 0 2 2h2v3.313c0 .188.063.375.25.5a.71.71 0 0 0 .5.188h1.375c.125 0 .313-.125.375-.25.125-.125.188-.25.125-.438v-3.313h2.25c1-.125 1.75-1 1.75-2v-20c0-.938-.875-1.313-1.75-1.313zM11.313 26H4.688V6.687h6.625zm16.25-17.312h-2.25v-8c.063-.188 0-.313-.125-.438-.063-.125-.25-.25-.375-.25h-1.375a.71.71 0 0 0-.5.188.568.568 0 0 0-.25.5v8h-2c-.938 0-2-.438-2 1.313v12a2.26 2.26 0 0 0 2 2h2v7.313c0 .188.063.375.25.5a.71.71 0 0 0 .5.188h1.375c.125 0 .313-.125.375-.25.125-.125.188-.25.125-.438v-7.313h2.25c1-.125 1.75-1 1.75-2v-12c0-.938-.875-1.313-1.75-1.313z' })
    );
};

exports.default = PlotCandlestickIcon;

/***/ }),

/***/ "4yqh":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils/lib/domutils.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const domutils_1 = __webpack_require__(/*! @phosphor/domutils */ "XWTc");
/**
 * The namespace for DOM utilities.
 */
var DOMUtils;
(function (DOMUtils) {
    /**
     * Get the index of the node at a client position, or `-1`.
     */
    function hitTestNodes(nodes, x, y) {
        return algorithm_1.ArrayExt.findFirstIndex(nodes, node => {
            return domutils_1.ElementExt.hitTest(node, x, y);
        });
    }
    DOMUtils.hitTestNodes = hitTestNodes;
    /**
     * Find the first element matching a class name.
     */
    function findElement(parent, className) {
        return parent.querySelector(`.${className}`);
    }
    DOMUtils.findElement = findElement;
})(DOMUtils = exports.DOMUtils || (exports.DOMUtils = {}));


/***/ }),

/***/ "4zK0":
/*!***************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/stats.js ***!
  \***************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




var isNumeric = __webpack_require__(/*! fast-isnumeric */ "GbLo");
var isArrayOrTypedArray = __webpack_require__(/*! ./array */ "lCvc").isArrayOrTypedArray;

/**
 * aggNums() returns the result of an aggregate function applied to an array of
 * values, where non-numerical values have been tossed out.
 *
 * @param {function} f - aggregation function (e.g., Math.min)
 * @param {Number} v - initial value (continuing from previous calls)
 *      if there's no continuing value, use null for selector-type
 *      functions (max,min), or 0 for summations
 * @param {Array} a - array to aggregate (may be nested, we will recurse,
 *                    but all elements must have the same dimension)
 * @param {Number} len - maximum length of a to aggregate
 * @return {Number} - result of f applied to a starting from v
 */
exports.aggNums = function(f, v, a, len) {
    var i,
        b;
    if(!len || len > a.length) len = a.length;
    if(!isNumeric(v)) v = false;
    if(isArrayOrTypedArray(a[0])) {
        b = new Array(len);
        for(i = 0; i < len; i++) b[i] = exports.aggNums(f, v, a[i]);
        a = b;
    }

    for(i = 0; i < len; i++) {
        if(!isNumeric(v)) v = a[i];
        else if(isNumeric(a[i])) v = f(+v, +a[i]);
    }
    return v;
};

/**
 * mean & std dev functions using aggNums, so it handles non-numerics nicely
 * even need to use aggNums instead of .length, to toss out non-numerics
 */
exports.len = function(data) {
    return exports.aggNums(function(a) { return a + 1; }, 0, data);
};

exports.mean = function(data, len) {
    if(!len) len = exports.len(data);
    return exports.aggNums(function(a, b) { return a + b; }, 0, data) / len;
};

exports.midRange = function(numArr) {
    if(numArr === undefined || numArr.length === 0) return undefined;
    return (exports.aggNums(Math.max, null, numArr) + exports.aggNums(Math.min, null, numArr)) / 2;
};

exports.variance = function(data, len, mean) {
    if(!len) len = exports.len(data);
    if(!isNumeric(mean)) mean = exports.mean(data, len);

    return exports.aggNums(function(a, b) {
        return a + Math.pow(b - mean, 2);
    }, 0, data) / len;
};

exports.stdev = function(data, len, mean) {
    return Math.sqrt(exports.variance(data, len, mean));
};

/**
 * interp() computes a percentile (quantile) for a given distribution.
 * We interpolate the distribution (to compute quantiles, we follow method #10 here:
 * http://www.amstat.org/publications/jse/v14n3/langford.html).
 * Typically the index or rank (n * arr.length) may be non-integer.
 * For reference: ends are clipped to the extreme values in the array;
 * For box plots: index you get is half a point too high (see
 * http://en.wikipedia.org/wiki/Percentile#Nearest_rank) but note that this definition
 * indexes from 1 rather than 0, so we subtract 1/2 (instead of add).
 *
 * @param {Array} arr - This array contains the values that make up the distribution.
 * @param {Number} n - Between 0 and 1, n = p/100 is such that we compute the p^th percentile.
 * For example, the 50th percentile (or median) corresponds to n = 0.5
 * @return {Number} - percentile
 */
exports.interp = function(arr, n) {
    if(!isNumeric(n)) throw 'n should be a finite number';
    n = n * arr.length - 0.5;
    if(n < 0) return arr[0];
    if(n > arr.length - 1) return arr[arr.length - 1];
    var frac = n % 1;
    return frac * arr[Math.ceil(n)] + (1 - frac) * arr[Math.floor(n)];
};


/***/ }),

/***/ "5+Ew":
/*!********************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/react-chart-editor.css ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../css-loader!./react-chart-editor.css */ "/3NQ");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "51Cs":
/*!***********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/default_panels/StyleColorbarsPanel.js ***!
  \***********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.traceHasColorbar = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _components = __webpack_require__(/*! ../components */ "yF51");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var traceHasColorbar = exports.traceHasColorbar = function traceHasColorbar(trace, fullTrace) {
  return fullTrace.marker && fullTrace.marker.showscale !== undefined || // eslint-disable-line no-undefined
  fullTrace.showscale !== undefined;
}; // eslint-disable-line no-undefined

var StyleColorBarsPanel = function StyleColorBarsPanel(props, _ref) {
  var _ = _ref.localize;

  return _react2.default.createElement(
    _components.TraceAccordion,
    { traceFilterCondition: traceHasColorbar },
    ['', 'marker.'].map(function (prefix) {
      return _react2.default.createElement(
        _components.VisibilitySelect,
        {
          attr: prefix + 'showscale',
          key: 'x' + prefix,
          options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }],
          showOn: true
        },
        _react2.default.createElement(
          _components.PlotlyPanel,
          { key: prefix + ' panel' },
          _react2.default.createElement(
            _components.PlotlyFold,
            { name: _('Title') },
            _react2.default.createElement(_components.TextEditor, { attr: prefix + 'colorbar.title.text' }),
            _react2.default.createElement(_components.Dropdown, {
              label: _('Location'),
              attr: prefix + 'colorbar.title.side',
              options: [{ label: _('Top'), value: 'top' }, { label: _('Right'), value: 'right' }, { label: _('Bottom'), value: 'bottom' }]
            }),
            _react2.default.createElement(_components.FontSelector, { label: _('Typeface'), attr: prefix + 'colorbar.title.font.family' }),
            _react2.default.createElement(_components.Numeric, {
              label: _('Font Size'),
              attr: prefix + 'colorbar.title.font.size',
              units: 'px'
            }),
            _react2.default.createElement(_components.ColorPicker, { label: _('Font Color'), attr: prefix + 'colorbar.title.font.color' })
          ),
          _react2.default.createElement(
            _components.PlotlyFold,
            { name: _('Size and Positioning') },
            _react2.default.createElement(
              _components.PlotlySection,
              { name: _('Size'), attr: prefix + 'colorbar.len' },
              _react2.default.createElement(_components.Numeric, { label: _('Height'), attr: prefix + 'colorbar.len' }),
              _react2.default.createElement(_components.Radio, {
                attr: prefix + 'colorbar.lenmode',
                options: [{ label: _('Fraction of Plot'), value: 'fraction' }, { label: _('Pixels'), value: 'pixels' }]
              }),
              _react2.default.createElement(_components.Numeric, { label: _('Width'), attr: prefix + 'colorbar.thickness' }),
              _react2.default.createElement(_components.Radio, {
                attr: prefix + 'colorbar.thicknessmode',
                options: [{ label: _('Fraction of Plot'), value: 'fraction' }, { label: _('Pixels'), value: 'pixels' }]
              })
            ),
            _react2.default.createElement(
              _components.PlotlySection,
              { name: _('Horizontal Positioning'), attr: prefix + 'colorbar.x' },
              _react2.default.createElement(_components.Numeric, {
                label: _('Position'),
                attr: prefix + 'colorbar.x',
                showSlider: true,
                step: 0.02
              }),
              _react2.default.createElement(_components.Dropdown, {
                label: _('Anchor'),
                attr: prefix + 'colorbar.xanchor',
                options: [{ label: _('Left'), value: 'left' }, { label: _('Center'), value: 'center' }, { label: _('Right'), value: 'right' }]
              })
            ),
            _react2.default.createElement(
              _components.PlotlySection,
              { name: _('Vertical Positioning'), attr: prefix + 'colorbar.y' },
              _react2.default.createElement(_components.Numeric, {
                label: _('Position'),
                attr: prefix + 'colorbar.y',
                showSlider: true,
                step: 0.02
              }),
              _react2.default.createElement(_components.Dropdown, {
                label: _('Anchor'),
                attr: prefix + 'colorbar.yanchor',
                options: [{ label: _('Top'), value: 'top' }, { label: _('Middle'), value: 'middle' }, { label: _('Bottom'), value: 'bottom' }]
              })
            ),
            _react2.default.createElement(
              _components.PlotlySection,
              { name: _('Padding'), attr: prefix + 'colorbar.xpad' },
              _react2.default.createElement(_components.Numeric, { label: _('Vertical'), attr: prefix + 'colorbar.ypad', units: 'px' }),
              _react2.default.createElement(_components.Numeric, { label: _('Horizontal'), attr: prefix + 'colorbar.xpad', units: 'px' })
            )
          ),
          _react2.default.createElement(
            _components.PlotlyFold,
            { name: _('Labels') },
            _react2.default.createElement(
              _components.VisibilitySelect,
              {
                attr: prefix + 'colorbar.showticklabels',
                options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }],
                showOn: true,
                defaultOpt: true
              },
              _react2.default.createElement(_components.FontSelector, { label: _('Typeface'), attr: prefix + 'colorbar.tickfont.family' }),
              _react2.default.createElement(_components.Numeric, {
                label: _('Font Size'),
                attr: prefix + 'colorbar.tickfont.size',
                units: 'px'
              }),
              _react2.default.createElement(_components.ColorPicker, { label: _('Font Color'), attr: prefix + 'colorbar.tickfont.color' }),
              _react2.default.createElement(_components.Dropdown, {
                label: _('Angle'),
                attr: prefix + 'colorbar.tickangle',
                clearable: false,
                options: [{ label: _('Auto'), value: 'auto' }, { label: _('45'), value: 45 }, { label: _('90'), value: 90 }, { label: _('135'), value: 135 }, { label: _('180'), value: 180 }]
              }),
              _react2.default.createElement(_components.Dropdown, {
                label: _('Exponents'),
                attr: prefix + 'colorbar.exponentformat',
                clearable: false,
                options: [{ label: _('None'), value: '000' }, { label: _('e+6'), value: 'e' }, { label: _('E+6'), value: 'E' }, { label: _('x10^6'), value: 'power' }, { label: _('k/M/G'), value: 'SI' }, { label: _('k/M/B'), value: 'B' }]
              }),
              _react2.default.createElement(_components.DropdownCustom, {
                label: _('Label Prefix'),
                attr: prefix + 'colorbar.tickprefix',
                options: [{ label: _('None'), value: '' }, { label: _('x'), value: 'x' }, { label: _('$'), value: '$' }, { label: _('#'), value: '#' }, { label: _('@'), value: '@' }, { label: _('Custom'), value: 'custom' }],
                customOpt: 'custom',
                dafaultOpt: '',
                clearable: false
              }),
              _react2.default.createElement(_components.Dropdown, {
                label: _('Show Prefix'),
                attr: prefix + 'colorbar.showtickprefix',
                options: [{ label: _('Every label'), value: 'all' }, { label: _('First label'), value: 'first' }, { label: _('Last label'), value: 'last' }, { label: _('None label'), value: 'none' }]
              }),
              _react2.default.createElement(_components.DropdownCustom, {
                label: _('Label Suffix'),
                attr: prefix + 'colorbar.ticksuffix',
                options: [{ label: _('None'), value: '' }, { label: _('C'), value: 'C' }, { label: _('%'), value: '%' }, { label: _('^'), value: '^' }, { label: _('Custom'), value: 'custom' }],
                customOpt: 'custom',
                dafaultOpt: '',
                clearable: false
              }),
              _react2.default.createElement(_components.Dropdown, {
                label: _('Show Suffix'),
                attr: prefix + 'colorbar.showticksuffix',
                options: [{ label: _('Every label'), value: 'all' }, { label: _('First label'), value: 'first' }, { label: _('Last label'), value: 'last' }, { label: _('None label'), value: 'none' }]
              }),
              _react2.default.createElement(_components.Radio, {
                attr: prefix + 'colorbar.tickmode',
                options: [{ label: _('Auto'), value: 'auto' }, { label: _('Custom'), value: 'linear' }],
                label: _('Tick spacing')
              }),
              _react2.default.createElement(_components.NumericOrDate, { label: _('Step Offset'), attr: prefix + 'colorbar.tick0' }),
              _react2.default.createElement(_components.AxisInterval, { label: _('Step Size'), attr: prefix + 'colorbar.dtick' }),
              _react2.default.createElement(_components.Numeric, { label: _('Max Number of Labels'), attr: prefix + 'colorbar.nticks' })
            )
          ),
          _react2.default.createElement(
            _components.PlotlyFold,
            { name: _('Ticks') },
            _react2.default.createElement(
              _components.VisibilitySelect,
              {
                attr: prefix + 'colorbar.ticks',
                options: [{ label: _('Inside'), value: 'inside' }, { label: _('Outside'), value: 'outside' }, { label: _('Hide'), value: '' }],
                showOn: ['inside', 'outside'],
                defaultOpt: ''
              },
              _react2.default.createElement(_components.Numeric, { label: _('Length'), attr: prefix + 'colorbar.ticklen', units: 'px' }),
              _react2.default.createElement(_components.Numeric, { label: _('Width'), attr: prefix + 'colorbar.tickwidth', units: 'px' }),
              _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: prefix + 'colorbar.tickcolor' }),
              _react2.default.createElement(_components.Radio, {
                attr: prefix + 'colorbar.tickmode',
                options: [{ label: _('Auto'), value: 'auto' }, { label: _('Custom'), value: 'linear' }],
                label: _('Tick spacing')
              }),
              _react2.default.createElement(_components.NumericOrDate, { label: _('Step Offset'), attr: prefix + 'colorbar.tick0' }),
              _react2.default.createElement(_components.AxisInterval, { label: _('Step Size'), attr: prefix + 'colorbar.dtick' }),
              _react2.default.createElement(_components.Numeric, { label: _('Max Number of Labels'), attr: prefix + 'colorbar.nticks' })
            )
          ),
          _react2.default.createElement(
            _components.PlotlyFold,
            { name: _('Borders and Background') },
            _react2.default.createElement(
              _components.PlotlySection,
              { name: _('Color Bar'), attr: prefix + 'colorbar.outlinewidth' },
              _react2.default.createElement(_components.Numeric, { label: _('Border Width'), attr: prefix + 'colorbar.outlinewidth' }),
              _react2.default.createElement(_components.ColorPicker, { label: _('Border Color'), attr: prefix + 'colorbar.outlinecolor' })
            ),
            _react2.default.createElement(
              _components.PlotlySection,
              { name: _('Color Bar Container'), attr: prefix + 'colorbar.bgcolor' },
              _react2.default.createElement(_components.ColorPicker, { label: _('Background Color'), attr: prefix + 'colorbar.bgcolor' }),
              _react2.default.createElement(_components.Numeric, { label: _('Border Width'), attr: prefix + 'colorbar.borderwidth' }),
              _react2.default.createElement(_components.ColorPicker, { label: _('Border Color'), attr: prefix + 'colorbar.bordercolor' })
            )
          )
        )
      );
    })
  );
};

StyleColorBarsPanel.contextTypes = {
  localize: _propTypes2.default.func
};

exports.default = StyleColorBarsPanel;
//# sourceMappingURL=StyleColorbarsPanel.js.map

/***/ }),

/***/ "52JE":
/*!**************************************************!*\
  !*** ./node_modules/mdi-react/CropSquareIcon.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var CropSquareIcon = function CropSquareIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M18,18H6V6H18M18,4H6C4.9,4 4,4.9 4,6V18C4,19.1 4.9,20 6,20H18C19.1,20 20,19.1 20,18V6C20,4.89 19.1,4 18,4Z' })
  );
};

module.exports = CropSquareIcon;


/***/ }),

/***/ "53HD":
/*!********************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/contents/validate.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * Validate a property as being on an object, and optionally
 * of a given type.
 */
function validateProperty(object, name, typeName) {
    if (!object.hasOwnProperty(name)) {
        throw Error(`Missing property '${name}'`);
    }
    if (typeName !== void 0) {
        let valid = true;
        let value = object[name];
        switch (typeName) {
            case 'array':
                valid = Array.isArray(value);
                break;
            case 'object':
                valid = typeof value !== 'undefined';
                break;
            default:
                valid = typeof value === typeName;
        }
        if (!valid) {
            throw new Error(`Property '${name}' is not of type '${typeName}`);
        }
    }
}
/**
 * Validate an `Contents.IModel` object.
 */
function validateContentsModel(model) {
    validateProperty(model, 'name', 'string');
    validateProperty(model, 'path', 'string');
    validateProperty(model, 'type', 'string');
    validateProperty(model, 'created', 'string');
    validateProperty(model, 'last_modified', 'string');
    validateProperty(model, 'mimetype', 'object');
    validateProperty(model, 'content', 'object');
    validateProperty(model, 'format', 'object');
}
exports.validateContentsModel = validateContentsModel;
/**
 * Validate an `Contents.ICheckpointModel` object.
 */
function validateCheckpointModel(model) {
    validateProperty(model, 'id', 'string');
    validateProperty(model, 'last_modified', 'string');
}
exports.validateCheckpointModel = validateCheckpointModel;


/***/ }),

/***/ "53Ql":
/*!********************************************************************!*\
  !*** ./node_modules/@jupyterlab/rendermime/lib/attachmentmodel.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const observables_1 = __webpack_require__(/*! @jupyterlab/observables */ "V4vH");
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
/**
 * The default implementation of a notebook attachment model.
 */
class AttachmentModel {
    /**
     * Construct a new attachment model.
     */
    constructor(options) {
        // All attachments are untrusted
        this.trusted = false;
        this._changed = new signaling_1.Signal(this);
        this._raw = {};
        let { data } = Private.getBundleOptions(options);
        this._data = new observables_1.ObservableJSON({ values: data });
        this._rawData = data;
        // Make a copy of the data.
        let value = options.value;
        for (let key in value) {
            // Ignore data and metadata that were stripped.
            switch (key) {
                case 'data':
                    break;
                default:
                    this._raw[key] = Private.extract(value, key);
            }
        }
    }
    /**
     * A signal emitted when the attachment model changes.
     */
    get changed() {
        return this._changed;
    }
    /**
     * Dispose of the resources used by the attachment model.
     */
    dispose() {
        this._data.dispose();
        signaling_1.Signal.clearData(this);
    }
    /**
     * The data associated with the model.
     */
    get data() {
        return this._rawData;
    }
    /**
     * The metadata associated with the model.
     */
    get metadata() {
        return undefined;
    }
    /**
     * Set the data associated with the model.
     *
     * #### Notes
     * Depending on the implementation of the mime model,
     * this call may or may not have deferred effects,
     */
    setData(options) {
        if (options.data) {
            this._updateObservable(this._data, options.data);
            this._rawData = options.data;
        }
        this._changed.emit(void 0);
    }
    /**
     * Serialize the model to JSON.
     */
    toJSON() {
        let attachment = {};
        for (let key in this._raw) {
            attachment[key] = Private.extract(this._raw, key);
        }
        return attachment;
    }
    /**
     * Update an observable JSON object using a readonly JSON object.
     */
    _updateObservable(observable, data) {
        let oldKeys = observable.keys();
        let newKeys = Object.keys(data);
        // Handle removed keys.
        for (let key of oldKeys) {
            if (newKeys.indexOf(key) === -1) {
                observable.delete(key);
            }
        }
        // Handle changed data.
        for (let key of newKeys) {
            let oldValue = observable.get(key);
            let newValue = data[key];
            if (oldValue !== newValue) {
                observable.set(key, newValue);
            }
        }
    }
}
exports.AttachmentModel = AttachmentModel;
/**
 * The namespace for AttachmentModel statics.
 */
(function (AttachmentModel) {
    /**
     * Get the data for an attachment.
     *
     * @params bundle - A kernel attachment MIME bundle.
     *
     * @returns - The data for the payload.
     */
    function getData(bundle) {
        return Private.getData(bundle);
    }
    AttachmentModel.getData = getData;
})(AttachmentModel = exports.AttachmentModel || (exports.AttachmentModel = {}));
/**
 * The namespace for module private data.
 */
var Private;
(function (Private) {
    /**
     * Get the data from a notebook attachment.
     */
    function getData(bundle) {
        return convertBundle(bundle);
    }
    Private.getData = getData;
    /**
     * Get the bundle options given attachment model options.
     */
    function getBundleOptions(options) {
        let data = getData(options.value);
        return { data };
    }
    Private.getBundleOptions = getBundleOptions;
    /**
     * Extract a value from a JSONObject.
     */
    function extract(value, key) {
        let item = value[key];
        if (coreutils_1.JSONExt.isPrimitive(item)) {
            return item;
        }
        return coreutils_1.JSONExt.deepCopy(item);
    }
    Private.extract = extract;
    /**
     * Convert a mime bundle to mime data.
     */
    function convertBundle(bundle) {
        let map = Object.create(null);
        for (let mimeType in bundle) {
            map[mimeType] = extract(bundle, mimeType);
        }
        return map;
    }
})(Private || (Private = {}));


/***/ }),

/***/ "54u7":
/*!**********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/PlotlyPanel.js ***!
  \**********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Panel = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _PanelHeader = __webpack_require__(/*! ./PanelHeader */ "owo8");

var _PanelHeader2 = _interopRequireDefault(_PanelHeader);

var _PanelEmpty = __webpack_require__(/*! ./PanelEmpty */ "o21U");

var _PanelEmpty2 = _interopRequireDefault(_PanelEmpty);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _immutabilityHelper = __webpack_require__(/*! immutability-helper */ "RsOY");

var _immutabilityHelper2 = _interopRequireDefault(_immutabilityHelper);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _plotlyIcons = __webpack_require__(/*! plotly-icons */ "hwSx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var PanelErrorImpl = function (_Component) {
  _inherits(PanelErrorImpl, _Component);

  function PanelErrorImpl() {
    _classCallCheck(this, PanelErrorImpl);

    return _possibleConstructorReturn(this, (PanelErrorImpl.__proto__ || Object.getPrototypeOf(PanelErrorImpl)).apply(this, arguments));
  }

  _createClass(PanelErrorImpl, [{
    key: 'render',
    value: function render() {
      var _ = this.context.localize;


      return _react2.default.createElement(
        _PanelEmpty2.default,
        { icon: _plotlyIcons.EmbedIconIcon, heading: _('Well this is embarrassing.') },
        _react2.default.createElement(
          'p',
          null,
          _('This panel could not be displayed due to an error.')
        )
      );
    }
  }]);

  return PanelErrorImpl;
}(_react.Component);

PanelErrorImpl.contextTypes = {
  localize: _propTypes2.default.func
};

var PanelError = PanelErrorImpl;

var Panel = exports.Panel = function (_Component2) {
  _inherits(Panel, _Component2);

  function Panel(props) {
    _classCallCheck(this, Panel);

    var _this2 = _possibleConstructorReturn(this, (Panel.__proto__ || Object.getPrototypeOf(Panel)).call(this, props));

    _this2.state = {
      individualFoldStates: [],
      hasError: false
    };
    _this2.toggleFolds = _this2.toggleFolds.bind(_this2);
    _this2.toggleFold = _this2.toggleFold.bind(_this2);
    return _this2;
  }

  _createClass(Panel, [{
    key: 'getChildContext',
    value: function getChildContext() {
      return {
        deleteContainer: this.props.deleteAction ? this.props.deleteAction : null
      };
    }
  }, {
    key: 'componentDidCatch',
    value: function componentDidCatch() {
      this.setState({ hasError: true });
    }
  }, {
    key: 'toggleFolds',
    value: function toggleFolds() {
      var individualFoldStates = this.state.individualFoldStates;

      var hasOpen = individualFoldStates.length > 0 && individualFoldStates.some(function (s) {
        return s !== true;
      });
      this.setState({
        individualFoldStates: individualFoldStates.map(function () {
          return hasOpen;
        })
      });
    }
  }, {
    key: 'toggleFold',
    value: function toggleFold(index) {
      this.setState((0, _immutabilityHelper2.default)(this.state, { individualFoldStates: { $toggle: [index] } }));
    }
  }, {
    key: 'calculateFolds',
    value: function calculateFolds() {
      // to get proper number of child folds and initialize component state
      var numFolds = 0;

      _react2.default.Children.forEach(this.props.children, function (child) {
        if ((child && child.type && child.type.plotly_editor_traits || {}).foldable) {
          numFolds++;
        }
      });

      if (this.state.individualFoldStates.length !== numFolds) {
        var newFoldStates = new Array(numFolds).fill(false);
        this.setState({
          individualFoldStates: this.props.addAction ? newFoldStates.map(function (e, i) {
            return i !== numFolds - 1;
          }) : newFoldStates
        });
      }
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate() {
      this.calculateFolds();
    }
  }, {
    key: 'componentDidMount',
    value: function componentDidMount() {
      this.calculateFolds();
    }
  }, {
    key: 'render',
    value: function render() {
      var _this3 = this;

      var _state = this.state,
          individualFoldStates = _state.individualFoldStates,
          hasError = _state.hasError;


      if (hasError) {
        return _react2.default.createElement(PanelError, null);
      }

      var newChildren = _react2.default.Children.map(this.props.children, function (child, index) {
        if ((child && child.type && child.type.plotly_editor_traits || {}).foldable) {
          return (0, _react.cloneElement)(child, {
            key: index,
            folded: individualFoldStates[index] || false,
            toggleFold: function toggleFold() {
              return _this3.toggleFold(index);
            }
          });
        }
        return child;
      });

      return _react2.default.createElement(
        'div',
        { className: 'panel' + (this.props.noPadding ? ' panel--no-padding' : '') },
        _react2.default.createElement(_PanelHeader2.default, {
          addAction: this.props.addAction,
          allowCollapse: this.props.showExpandCollapse && individualFoldStates.length > 1,
          toggleFolds: this.toggleFolds,
          hasOpen: individualFoldStates.some(function (s) {
            return s === false;
          })
        }),
        _react2.default.createElement(
          'div',
          { className: (0, _lib.bem)('panel', 'content') },
          newChildren
        )
      );
    }
  }]);

  return Panel;
}(_react.Component);

Panel.propTypes = {
  addAction: _propTypes2.default.object,
  children: _propTypes2.default.node,
  deleteAction: _propTypes2.default.func,
  noPadding: _propTypes2.default.bool,
  showExpandCollapse: _propTypes2.default.bool
};

Panel.defaultProps = {
  showExpandCollapse: true
};

Panel.contextTypes = {
  localize: _propTypes2.default.func
};

Panel.childContextTypes = {
  deleteContainer: _propTypes2.default.func
};

var PlotlyPanel = function (_Panel) {
  _inherits(PlotlyPanel, _Panel);

  function PlotlyPanel() {
    _classCallCheck(this, PlotlyPanel);

    return _possibleConstructorReturn(this, (PlotlyPanel.__proto__ || Object.getPrototypeOf(PlotlyPanel)).apply(this, arguments));
  }

  return PlotlyPanel;
}(Panel);

PlotlyPanel.plotly_editor_traits = {
  no_visibility_forcing: true
};

exports.default = PlotlyPanel;
//# sourceMappingURL=PlotlyPanel.js.map

/***/ }),

/***/ "5Bkx":
/*!**************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/constants.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var baseClass = exports.baseClass = 'plotly-editor';

/*
 * Control represents multiple settings (like for several axes)
 * and the values are different.
 *
 * Because this is sometimes used in contexts where users can enter freeform
 * strings, we include a non-printable character (ESC) so it's not something
 * people could type.
 */
var MULTI_VALUED = exports.MULTI_VALUED = '\x1bMIXED_VALUES';

// how mixed values are represented in text inputs
var MULTI_VALUED_PLACEHOLDER = exports.MULTI_VALUED_PLACEHOLDER = '---';

var getMultiValueText = exports.getMultiValueText = function getMultiValueText(key, _) {
  var multiValueText = {
    title: _('Multiple Values'),
    text: _('This input has multiple values associated with it. ' + 'Changing this setting will override these custom inputs.'),
    subText: _("Common Case: An 'All' tab might display this message " + 'because the X and Y tabs contain different settings.')
  };
  return multiValueText[key];
};

var EDITOR_ACTIONS = exports.EDITOR_ACTIONS = {
  UPDATE_TRACES: 'plotly-editor-update-traces',
  ADD_TRACE: 'plotly-editor-add-trace',
  DELETE_TRACE: 'plotly-editor-delete-trace',
  UPDATE_LAYOUT: 'plotly-editor-update-layout',
  DELETE_ANNOTATION: 'plotly-editor-delete-annotation',
  DELETE_SHAPE: 'plotly-editor-delete-shape',
  DELETE_IMAGE: 'plotly-editor-delete-image',
  DELETE_RANGESELECTOR: 'plotly-editor-delete-rangeselector',
  DELETE_TRANSFORM: 'plotly-editor-delete-transform'
};

var DEFAULT_FONTS = exports.DEFAULT_FONTS = [{ label: 'Sans Serif', value: 'sans-serif' }, { label: 'Serif', value: 'serif' }, { label: 'Monospaced', value: 'monospace' }];

var RETURN_KEY = exports.RETURN_KEY = 'Enter';
var ESCAPE_KEY = exports.ESCAPE_KEY = 'Escape';
var COMMAND_KEY = exports.COMMAND_KEY = 'Meta';
var CONTROL_KEY = exports.CONTROL_KEY = 'Control';

// matches gd._fullLayout._subplots categories except for xaxis & yaxis which
// are in fact cartesian types
var TRACE_TO_AXIS = exports.TRACE_TO_AXIS = {
  cartesian: ['scatter', 'scattergl', 'box', 'violin', 'bar', 'heatmap', 'heatmapgl', 'contour', 'ohlc', 'candlestick', 'histogram', 'histogram2d', 'histogram2dcontour', 'carpet', 'scattercarpet', 'contourcarpet'],
  ternary: ['scatterternary'],
  gl3d: ['scatter3d', 'surface', 'mesh3d', 'cone', 'streamtube'],
  geo: ['scattergeo', 'choropleth'],
  mapbox: ['scattermapbox'],
  polar: ['scatterpolar', 'scatterpolargl', 'barpolar']
};

// Note: scene, and xaxis/yaxis were added for convenience sake even though they're not subplot types
var SUBPLOT_TO_ATTR = exports.SUBPLOT_TO_ATTR = {
  cartesian: { data: ['xaxis', 'yaxis'], layout: ['x', 'y'] },
  xaxis: { data: 'xaxis', layout: 'x' },
  yaxis: { data: 'yaxis', layout: 'y' },
  x: { data: 'xaxis', layout: 'x' },
  y: { data: 'yaxis', layout: 'y' },
  ternary: { data: 'subplot', layout: 'ternary' },
  gl3d: { data: 'scene', layout: 'scene' },
  scene: { data: 'scene', layout: 'scene' },
  geo: { data: 'geo', layout: 'geo' },
  mapbox: { data: 'subplot', layout: 'mapbox' },
  polar: { data: 'subplot', layout: 'polar' }
};

var subplotName = exports.subplotName = function subplotName(type, _) {
  return {
    x: _('X'),
    y: _('Y'),
    ternary: _('Ternary'),
    gl3d: _('Scene'),
    scene: _('Scene'),
    geo: _('Geo'),
    mapbox: _('Mapbox'),
    polar: _('Polar')
  }[type];
};

var TRANSFORMS_LIST = exports.TRANSFORMS_LIST = ['filter', 'groupby', 'aggregate', 'sort'];

var TRANSFORMABLE_TRACES = exports.TRANSFORMABLE_TRACES = ['scatter', 'scattergl', 'box', 'violin', 'bar', 'ohlc', 'candlestick', 'histogram', 'histogram2d'];

var TRACES_WITH_GL = exports.TRACES_WITH_GL = ['scatter', 'scatterpolar', 'scattergl', 'scatterpolargl'];

var COLORS = exports.COLORS = {
  charcoal: '#444444',
  white: '#ffffff',
  mutedBlue: '#1f77b4',
  safetyOrange: '#ff7f0e',
  cookedAsparagusGreen: '#2ca02c',
  brickRed: '#d62728',
  mutedPurple: '#9467bd',
  chestnutBrown: '#8c564b',
  raspberryYogurtPink: '#e377c2',
  middleGray: '#7f7f7f',
  curryYellowGreen: '#bcbd22',
  blueTeal: '#17becf',
  editorLink: '#447bdc',
  black: '#000000'
};

var DEFAULT_COLORS = exports.DEFAULT_COLORS = [COLORS.charcoal, COLORS.white, COLORS.mutedBlue, COLORS.safetyOrange, COLORS.cookedAsparagusGreen, COLORS.brickRed, COLORS.mutedPurple, COLORS.chestnutBrown, COLORS.raspberryYogurtPink, COLORS.middleGray, COLORS.curryYellowGreen, COLORS.blueTeal];
//# sourceMappingURL=constants.js.map

/***/ }),

/***/ "5Bud":
/*!***********************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/connectTraceToPlot.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

exports.default = connectTraceToPlot;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _nested_property = __webpack_require__(/*! plotly.js/src/lib/nested_property */ "dNZO");

var _nested_property2 = _interopRequireDefault(_nested_property);

var _lib = __webpack_require__(/*! ../lib */ "RXjw");

var _multiValues = __webpack_require__(/*! ./multiValues */ "l26e");

var _constants = __webpack_require__(/*! ./constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function connectTraceToPlot(WrappedComponent) {
  var TraceConnectedComponent = function (_Component) {
    _inherits(TraceConnectedComponent, _Component);

    function TraceConnectedComponent(props, context) {
      _classCallCheck(this, TraceConnectedComponent);

      var _this = _possibleConstructorReturn(this, (TraceConnectedComponent.__proto__ || Object.getPrototypeOf(TraceConnectedComponent)).call(this, props, context));

      _this.deleteTrace = _this.deleteTrace.bind(_this);
      _this.updateTrace = _this.updateTrace.bind(_this);
      _this.setLocals(props, context);
      return _this;
    }

    _createClass(TraceConnectedComponent, [{
      key: 'componentWillReceiveProps',
      value: function componentWillReceiveProps(nextProps, nextContext) {
        this.setLocals(nextProps, nextContext);
      }
    }, {
      key: 'setLocals',
      value: function setLocals(props, context) {
        var traceIndexes = props.traceIndexes;
        var data = context.data,
            fullData = context.fullData,
            plotly = context.plotly,
            meta = context.layout;


        var trace = data[traceIndexes[0]];
        var fullTrace = (0, _lib.getFullTrace)(props, context);

        this.childContext = {
          getValObject: function getValObject(attr) {
            return !plotly ? null : plotly.PlotSchema.getTraceValObject(fullTrace, (0, _nested_property2.default)({}, attr).parts);
          },
          updateContainer: this.updateTrace,
          deleteContainer: this.deleteTrace,
          container: trace,
          fullContainer: fullTrace,
          traceIndexes: this.props.traceIndexes
        };

        if (traceIndexes.length > 1) {
          var multiValuedFullContainer = (0, _multiValues.deepCopyPublic)(fullTrace);
          fullData.forEach(function (t) {
            return Object.keys(t).forEach(function (key) {
              return (0, _multiValues.setMultiValuedContainer)(multiValuedFullContainer, (0, _multiValues.deepCopyPublic)(t), key, {
                searchArrays: true
              });
            });
          });
          var multiValuedContainer = (0, _multiValues.deepCopyPublic)(trace);
          data.forEach(function (t) {
            return Object.keys(t).forEach(function (key) {
              return (0, _multiValues.setMultiValuedContainer)(multiValuedContainer, (0, _multiValues.deepCopyPublic)(t), key, {
                searchArrays: true
              });
            });
          });
          this.childContext.fullContainer = multiValuedFullContainer;
          this.childContext.defaultContainer = fullTrace;
          this.childContext.container = multiValuedContainer;
        }

        if (trace && fullTrace) {
          this.icon = (0, _lib.renderTraceIcon)((0, _lib.plotlyTraceToCustomTrace)(trace));
          this.name = (0, _lib.getParsedTemplateString)(fullTrace.name, meta);
        }
      }
    }, {
      key: 'getChildContext',
      value: function getChildContext() {
        return this.childContext;
      }
    }, {
      key: 'updateTrace',
      value: function updateTrace(update) {
        var _this2 = this;

        if (this.context.onUpdate) {
          var splitTraceGroup = this.props.fullDataArrayPosition ? this.props.fullDataArrayPosition.map(function (p) {
            return _this2.context.fullData[p]._group;
          }) : null;

          var containsAnSrc = Object.keys(update).filter(function (a) {
            return a.endsWith('src');
          }).length > 0;

          if (Array.isArray(update)) {
            update.forEach(function (u, i) {
              _this2.context.onUpdate({
                type: _constants.EDITOR_ACTIONS.UPDATE_TRACES,
                payload: {
                  update: u,
                  traceIndexes: [_this2.props.traceIndexes[i]],
                  splitTraceGroup: splitTraceGroup ? splitTraceGroup[i] : null
                }
              });
            });
          } else if (splitTraceGroup && !containsAnSrc) {
            this.props.traceIndexes.forEach(function (t, i) {
              _this2.context.onUpdate({
                type: _constants.EDITOR_ACTIONS.UPDATE_TRACES,
                payload: {
                  update: update,
                  traceIndexes: [_this2.props.traceIndexes[i]],
                  splitTraceGroup: splitTraceGroup ? splitTraceGroup[i] : null
                }
              });
            });
          } else {
            this.context.onUpdate({
              type: _constants.EDITOR_ACTIONS.UPDATE_TRACES,
              payload: {
                update: update,
                traceIndexes: this.props.traceIndexes
              }
            });
          }
        }
      }
    }, {
      key: 'deleteTrace',
      value: function deleteTrace() {
        var _this3 = this;

        var currentTrace = this.context.fullData[this.props.traceIndexes[0]];
        if (!currentTrace && this.context.onUpdate) {
          this.context.onUpdate({
            type: _constants.EDITOR_ACTIONS.DELETE_TRACE,
            payload: {
              traceIndexes: this.props.traceIndexes
            }
          });
          return;
        }
        var axesToBeGarbageCollected = [];
        var subplotToBeGarbageCollected = null;
        var subplotType = (0, _lib.traceTypeToAxisType)(currentTrace.type);

        if (subplotType) {
          var subplotNames = subplotType === 'cartesian' ? [currentTrace.xaxis || 'xaxis', currentTrace.yaxis || 'yaxis'] : currentTrace[_constants.SUBPLOT_TO_ATTR[subplotType].data] || _constants.SUBPLOT_TO_ATTR[subplotType].data;

          var isSubplotUsedAnywhereElse = function isSubplotUsedAnywhereElse(subplotType, subplotName) {
            return _this3.context.fullData.some(function (trace) {
              return (trace[_constants.SUBPLOT_TO_ATTR[subplotType].data] === subplotName || ((subplotType === 'xaxis' || subplotType === 'yaxis') && subplotName.charAt(1)) === '' || subplotName.split(subplotType)[1] === '' && trace[_constants.SUBPLOT_TO_ATTR[subplotType].data] === null) && trace.index !== _this3.props.traceIndexes[0];
            });
          };

          // When we delete a subplot, make sure no unused axes/subplots are left
          if (subplotType === 'cartesian') {
            if (!isSubplotUsedAnywhereElse('xaxis', subplotNames[0])) {
              axesToBeGarbageCollected.push(subplotNames[0]);
            }
            if (!isSubplotUsedAnywhereElse('yaxis', subplotNames[1])) {
              axesToBeGarbageCollected.push(subplotNames[1]);
            }
          } else {
            if (!isSubplotUsedAnywhereElse(subplotType, subplotNames)) {
              subplotToBeGarbageCollected = subplotNames;
            }
          }
        }

        if (this.context.onUpdate) {
          this.context.onUpdate({
            type: _constants.EDITOR_ACTIONS.DELETE_TRACE,
            payload: {
              axesToBeGarbageCollected: axesToBeGarbageCollected,
              subplotToBeGarbageCollected: subplotToBeGarbageCollected,
              traceIndexes: this.props.traceIndexes
            }
          });
        }
      }
    }, {
      key: 'render',
      value: function render() {
        return _react2.default.createElement(WrappedComponent, _extends({ name: this.name, icon: this.icon }, this.props));
      }
    }]);

    return TraceConnectedComponent;
  }(_react.Component);

  TraceConnectedComponent.displayName = 'TraceConnected' + (0, _lib.getDisplayName)(WrappedComponent);

  TraceConnectedComponent.propTypes = {
    traceIndexes: _propTypes2.default.arrayOf(_propTypes2.default.number).isRequired,
    fullDataArrayPosition: _propTypes2.default.arrayOf(_propTypes2.default.number)
  };

  TraceConnectedComponent.contextTypes = {
    fullData: _propTypes2.default.array,
    data: _propTypes2.default.array,
    plotly: _propTypes2.default.object,
    onUpdate: _propTypes2.default.func,
    layout: _propTypes2.default.object
  };

  TraceConnectedComponent.childContextTypes = {
    getValObject: _propTypes2.default.func,
    updateContainer: _propTypes2.default.func,
    deleteContainer: _propTypes2.default.func,
    defaultContainer: _propTypes2.default.object,
    container: _propTypes2.default.object,
    fullContainer: _propTypes2.default.object,
    traceIndexes: _propTypes2.default.array
  };

  var plotly_editor_traits = WrappedComponent.plotly_editor_traits;

  TraceConnectedComponent.plotly_editor_traits = plotly_editor_traits;

  return TraceConnectedComponent;
}
//# sourceMappingURL=connectTraceToPlot.js.map

/***/ }),

/***/ "5DOW":
/*!**********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/DateTimePicker.js ***!
  \**********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

__webpack_require__(/*! react-day-picker/lib/style.css */ "UNSI");

var _plotlyIcons = __webpack_require__(/*! plotly-icons */ "hwSx");

var _dates = __webpack_require__(/*! plotly.js/src/lib/dates */ "Zhzs");

var _reactDayPicker = __webpack_require__(/*! react-day-picker */ "BFWj");

var _reactDayPicker2 = _interopRequireDefault(_reactDayPicker);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _TextInput = __webpack_require__(/*! ./TextInput */ "CVbq");

var _TextInput2 = _interopRequireDefault(_TextInput);

var _Dropdown = __webpack_require__(/*! ./Dropdown */ "9Rtb");

var _Dropdown2 = _interopRequireDefault(_Dropdown);

var _constants = __webpack_require__(/*! ../../lib/constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var testDate = '2000-01-01';
var testTime = '00:00';
var datePlaceholder = 'yyyy-mm-dd';
var timePlaceholder = 'hh:mm:ss.xxx';

var DateTimePicker = function (_Component) {
  _inherits(DateTimePicker, _Component);

  function DateTimePicker(props, context) {
    _classCallCheck(this, DateTimePicker);

    var _this = _possibleConstructorReturn(this, (DateTimePicker.__proto__ || Object.getPrototypeOf(DateTimePicker)).call(this, props, context));

    var _this$parsePlotlyJSDa = _this.parsePlotlyJSDateTime(props.value),
        time = _this$parsePlotlyJSDa.time,
        date = _this$parsePlotlyJSDa.date;

    var isValidTime = (0, _dates.isDateTime)(testDate + ' ' + time) || ['', timePlaceholder, _constants.MULTI_VALUED_PLACEHOLDER].includes(time);
    var isValidDate = (0, _dates.isDateTime)(date + ' ' + testTime) || ['', datePlaceholder, _constants.MULTI_VALUED_PLACEHOLDER].includes(date);

    _this.state = {
      calendarOpen: false,
      dateInputClassName: isValidDate ? 'datetimepicker-container-date-input' : 'datetimepicker-container-date-input +error',
      timeInputClassName: isValidTime ? 'datetimepicker-container-time-input' : 'datetimepicker-container-time-input +error',
      timeValue: time,
      dateValue: date,
      AMPM: _this.getAMPM(date, time, context.localize)
    };

    _this.toPlotlyJSDate = _this.toPlotlyJSDate.bind(_this);
    _this.onMonthChange = _this.onMonthChange.bind(_this);
    _this.onYearChange = _this.onYearChange.bind(_this);
    _this.onTimeChange = _this.onTimeChange.bind(_this);
    _this.onDateChange = _this.onDateChange.bind(_this);
    _this.onTimeUpdate = _this.onTimeUpdate.bind(_this);
    _this.onDateUpdate = _this.onDateUpdate.bind(_this);
    return _this;
  }

  _createClass(DateTimePicker, [{
    key: 'toPlotlyJSDate',
    value: function toPlotlyJSDate(value) {
      var ms = (0, _dates.dateTime2ms)(value);
      return (0, _dates.ms2DateTime)(ms);
    }
  }, {
    key: 'getYearOptions',
    value: function getYearOptions(current) {
      // eslint-disable-next-line
      var base = 5;
      var yearAsNumber = parseInt(current, 10);

      var lastFive = new Array(base).fill(0).map(function (year, index) {
        var newOption = yearAsNumber - (base - index);
        return { label: newOption, value: newOption };
      });

      var nextFive = new Array(base).fill(0).map(function (year, index) {
        var newOption = yearAsNumber + (index + 1);
        return { label: newOption, value: newOption };
      });

      return lastFive.concat([{ label: current, value: current }]).concat(nextFive);
    }
  }, {
    key: 'getMonthOptions',
    value: function getMonthOptions() {
      var _ = this.context.localize;
      return [{ label: _('January'), value: 0 }, { label: _('February'), value: 1 }, { label: _('March'), value: 2 }, { label: _('April'), value: 3 }, { label: _('May'), value: 4 }, { label: _('June'), value: 5 }, { label: _('July'), value: 6 }, { label: _('August'), value: 7 }, { label: _('September'), value: 8 }, { label: _('October'), value: 9 }, { label: _('November'), value: 10 }, { label: _('December'), value: 11 }];
    }
  }, {
    key: 'onMonthChange',
    value: function onMonthChange(value) {
      var currentDateInJS = new Date(this.getAdjustedPlotlyJSDateTime(this.props.value));
      currentDateInJS.setMonth(value);
      var plotlyJSDate = this.toPlotlyJSDate(currentDateInJS);

      if ((0, _dates.isDateTime)(plotlyJSDate)) {
        this.props.onChange(plotlyJSDate);
      }

      var _parsePlotlyJSDateTim = this.parsePlotlyJSDateTime(plotlyJSDate),
          time = _parsePlotlyJSDateTim.time,
          date = _parsePlotlyJSDateTim.date;

      this.setState({
        timeValue: time,
        dateValue: date
      });
    }
  }, {
    key: 'onYearChange',
    value: function onYearChange(value) {
      var currentDateInJS = new Date(this.getAdjustedPlotlyJSDateTime(this.props.value));
      currentDateInJS.setFullYear(value);
      var plotlyJSDate = this.toPlotlyJSDate(currentDateInJS);

      if ((0, _dates.isDateTime)(plotlyJSDate)) {
        this.props.onChange(plotlyJSDate);
      }

      var _parsePlotlyJSDateTim2 = this.parsePlotlyJSDateTime(plotlyJSDate),
          time = _parsePlotlyJSDateTim2.time,
          date = _parsePlotlyJSDateTim2.date;

      this.setState({
        timeValue: time,
        dateValue: date
      });
    }
  }, {
    key: 'parsePlotlyJSDateTime',
    value: function parsePlotlyJSDateTime(value) {
      var parsed = value.split(' ');
      return { date: parsed[0], time: parsed[1] ? parsed[1] : '' };
    }
  }, {
    key: 'getAMPM',
    value: function getAMPM(date, time, _) {
      var plotlyJSDateTime = date + ' ' + time;
      var isValidDateTime = (0, _dates.isDateTime)(plotlyJSDateTime);
      var JSDate = new Date(this.getAdjustedPlotlyJSDateTime(plotlyJSDateTime));
      var localeTime = JSDate.toLocaleTimeString('en-US').split(' ');

      var parsedTime = time.split(':').reduce(function (timeArray, timePart) {
        var parsed = timePart.split('.');
        return timeArray.concat(parsed);
      }, []);

      var isNoon = parsedTime[0] === '12' && parsedTime.slice(1).every(function (part) {
        return parseInt(part, 10) === 0;
      });

      return !isValidDateTime || time === '' || JSDate.toDateString() === 'Invalid Date' ? '' : localeTime[1] === 'PM' ? isNoon ? _('noon') : 'PM' : 'AM';
    }
  }, {
    key: 'adjustedTime',
    value: function adjustedTime(time) {
      if (time.toString().length <= 2) {
        return time + ':00';
      }
      return time;
    }
  }, {
    key: 'onTimeChange',
    value: function onTimeChange(value) {
      var _parsePlotlyJSDateTim3 = this.parsePlotlyJSDateTime(this.props.value),
          currentDate = _parsePlotlyJSDateTim3.date;

      var isValidTime = (0, _dates.isDateTime)(testDate + ' ' + value);

      this.setState({
        timeInputClassName: isValidTime || value === '' ? 'datetimepicker-container-time-input' : 'datetimepicker-container-time-input +error',
        timeValue: value,
        AMPM: this.getAMPM(currentDate, value, this.context.localize)
      });
    }
  }, {
    key: 'onDateChange',
    value: function onDateChange(value) {
      var isValidDate = (0, _dates.isDateTime)(value + ' ' + testTime);
      this.setState({
        dateInputClassName: isValidDate || value === '' ? 'datetimepicker-container-date-input' : 'datetimepicker-container-date-input +error',
        dateValue: value
      });
    }
  }, {
    key: 'onTimeUpdate',
    value: function onTimeUpdate(value) {
      var _parsePlotlyJSDateTim4 = this.parsePlotlyJSDateTime(this.props.value),
          currentTime = _parsePlotlyJSDateTim4.time,
          currentDate = _parsePlotlyJSDateTim4.date;

      var isValidTime = (0, _dates.isDateTime)(testDate + ' ' + value);

      if (value === '') {
        this.setState({
          timeInputClassName: 'datetimepicker-container-time-input',
          timeValue: currentTime,
          AMPM: this.getAMPM(currentDate, currentTime, this.context.localize)
        });
        return;
      }

      if (isValidTime) {
        this.props.onChange(currentDate + ' ' + value);
      }
    }
  }, {
    key: 'onDateUpdate',
    value: function onDateUpdate(value) {
      var _parsePlotlyJSDateTim5 = this.parsePlotlyJSDateTime(this.props.value),
          currentDate = _parsePlotlyJSDateTim5.date,
          currentTime = _parsePlotlyJSDateTim5.time;

      var isValidDate = (0, _dates.isDateTime)(value + ' ' + testTime);

      if (isValidDate) {
        this.props.onChange(value + ' ' + currentTime);
        return;
      }

      if (value === '') {
        this.setState({
          dateValue: currentDate,
          dateInputClassName: 'datetimepicker-container-date-input'
        });
        return;
      }
    }
  }, {
    key: 'getAdjustedPlotlyJSDateTime',
    value: function getAdjustedPlotlyJSDateTime(dateTimeString) {
      var _parsePlotlyJSDateTim6 = this.parsePlotlyJSDateTime(dateTimeString),
          date = _parsePlotlyJSDateTim6.date,
          time = _parsePlotlyJSDateTim6.time;

      return date + ' ' + this.adjustedTime(time);
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var JSDate = new Date(this.getAdjustedPlotlyJSDateTime(this.state.dateValue + ' ' + testTime));
      var isValidJSDate = JSDate.toDateString() !== 'Invalid Date';
      var currentYear = isValidJSDate ? JSDate.getFullYear() : new Date().getFullYear();
      var currentMonth = isValidJSDate ? JSDate.getMonth() : new Date().getMonth();

      return _react2.default.createElement(
        'div',
        { className: 'datetimepicker-container' },
        _react2.default.createElement(_TextInput2.default, {
          value: this.state.dateValue,
          editableClassName: this.state.dateInputClassName,
          onChange: this.onDateChange,
          onUpdate: this.onDateUpdate,
          placeholder: datePlaceholder
        }),
        _react2.default.createElement(
          'div',
          { className: 'datetimepicker-container-icons' },
          _react2.default.createElement(_plotlyIcons.CalendarMultiselectIcon, {
            onClick: function onClick() {
              return _this2.setState({ calendarOpen: !_this2.state.calendarOpen });
            },
            className: this.state.calendarOpen ? 'datetimepicker-date-icon--selected' : 'datetimepicker-date-icon'
          })
        ),
        this.state.calendarOpen ? _react2.default.createElement(
          'div',
          { className: 'datetimepicker-container__content' },
          this.state.calendarOpen ? _react2.default.createElement(
            'div',
            { className: 'datetimepicker-datepicker-container' },
            _react2.default.createElement(
              'div',
              { className: 'datetimepicker-datepicker-navbar' },
              _react2.default.createElement(_Dropdown2.default, {
                options: this.getMonthOptions(),
                value: currentMonth,
                className: 'datimepicker-monthpicker',
                clearable: false,
                onChange: this.onMonthChange
              }),
              _react2.default.createElement(_Dropdown2.default, {
                options: this.getYearOptions(currentYear),
                value: currentYear,
                className: 'datimepicker-yearpicker',
                clearable: false,
                onChange: this.onYearChange
              })
            ),
            _react2.default.createElement(_reactDayPicker2.default, {
              className: 'datepicker-container-rce',
              modifiers: { highlighted: isValidJSDate ? JSDate : '' },
              month: isValidJSDate ? JSDate : new Date(),
              onDayClick: function onDayClick(value) {
                var plotlyDate = _this2.toPlotlyJSDate(value).split(' ')[0];
                _this2.onDateChange(plotlyDate);
                _this2.onDateUpdate(plotlyDate);
              }
            })
          ) : null
        ) : null,
        _react2.default.createElement(
          'div',
          { className: 'datetimepicker-container-time' },
          _react2.default.createElement(_TextInput2.default, {
            value: this.state.timeValue,
            onChange: this.onTimeChange,
            onUpdate: this.onTimeUpdate,
            placeholder: timePlaceholder,
            editableClassName: this.state.timeInputClassName
          }),
          _react2.default.createElement(
            'span',
            { className: 'datetimepicker-date-units' },
            this.state.AMPM
          )
        )
      );
    }
  }]);

  return DateTimePicker;
}(_react.Component);

exports.default = DateTimePicker;


DateTimePicker.propTypes = {
  value: _propTypes2.default.string.isRequired,
  onChange: _propTypes2.default.func.isRequired
};

DateTimePicker.contextTypes = {
  localize: _propTypes2.default.func
};
//# sourceMappingURL=DateTimePicker.js.map

/***/ }),

/***/ "5FFA":
/*!**************************************************!*\
  !*** ./node_modules/base16/lib/atelier-heath.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'atelier heath',
  author: 'bram de haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/heath)',
  base00: '#1b181b',
  base01: '#292329',
  base02: '#695d69',
  base03: '#776977',
  base04: '#9e8f9e',
  base05: '#ab9bab',
  base06: '#d8cad8',
  base07: '#f7f3f7',
  base08: '#ca402b',
  base09: '#a65926',
  base0A: '#bb8a35',
  base0B: '#379a37',
  base0C: '#159393',
  base0D: '#516aec',
  base0E: '#7b59c0',
  base0F: '#cc33cc'
};
module.exports = exports['default'];

/***/ }),

/***/ "5H19":
/*!***********************************************************!*\
  !*** ./node_modules/jupyterlab-chart-editor/lib/index.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
var React = __webpack_require__(/*! react */ "q1tI");
var ReactDOM = __webpack_require__(/*! react-dom */ "i8i4");
var Plotly = __webpack_require__(/*! plotly.js/dist/plotly */ "95T3");
var component_1 = __webpack_require__(/*! ./component */ "QTZ7");
__webpack_require__(/*! ../style/index.css */ "BzXa");
/**
 * The CSS class to add to the Plotly Editor Widget.
 */
var CSS_CLASS = 'jp-RenderedPlotlyEditor';
/**
 * The CSS class for a Plotly Editor icon.
 */
var CSS_ICON_CLASS = 'jp-MaterialIcon jp-PlotlyIcon';
/**
 * The MIME type for Plotly Editor.
 */
exports.MIME_TYPE = 'application/vnd.plotly-editor.v1+json';
var RenderedPlotlyEditor = /** @class */ (function (_super) {
    __extends(RenderedPlotlyEditor, _super);
    /**
     * Create a new widget for rendering Plotly Editor.
     */
    function RenderedPlotlyEditor(options) {
        var _this = _super.call(this) || this;
        _this.addClass(CSS_CLASS);
        _this._mimeType = options.mimeType;
        return _this;
    }
    /**
     * Dispose of the resources used by the widget.
     */
    RenderedPlotlyEditor.prototype.dispose = function () {
        ReactDOM.unmountComponentAtNode(this.node);
        _super.prototype.dispose.call(this);
    };
    /**
     * Render Plotly Editor into this widget's node.
     */
    RenderedPlotlyEditor.prototype.renderModel = function (model) {
        var _this = this;
        return new Promise(function (resolve, reject) {
            var state = model.data[_this._mimeType];
            try {
                var handleUpdate = function (state) {
                    var newData = (_a = {},
                        _a[_this._mimeType] = state,
                        _a);
                    model.setData({ data: newData });
                    var _a;
                };
                _this._ref = ReactDOM.render(React.createElement(component_1.default, { state: state, handleUpdate: handleUpdate, plotly: Plotly }), _this.node, function () {
                    resolve(undefined);
                });
            }
            catch (error) {
                reject(error);
            }
        });
    };
    /**
     * A message handler invoked on a `'resize'` message.
     */
    RenderedPlotlyEditor.prototype.onResize = function (msg) {
        this.update();
    };
    /**
     * A message handler invoked on an `'update-request'` message.
     */
    RenderedPlotlyEditor.prototype.onUpdateRequest = function () {
        if (this.isVisible && this._ref) {
            this._ref.handleResize();
        }
    };
    return RenderedPlotlyEditor;
}(widgets_1.Widget));
exports.RenderedPlotlyEditor = RenderedPlotlyEditor;
/**
 * A mime renderer factory for Plotly Editor.
 */
exports.rendererFactory = {
    safe: true,
    mimeTypes: [exports.MIME_TYPE],
    createRenderer: function (options) { return new RenderedPlotlyEditor(options); }
};
var extensions = [
    {
        id: 'jupyterlab-chart-editor:factory',
        name: 'jupyterlab-chart-editor:factory',
        rendererFactory: exports.rendererFactory,
        rank: 0,
        dataType: 'json',
        fileTypes: [
            {
                name: 'plotlyeditor',
                mimeTypes: [exports.MIME_TYPE],
                extensions: ['.plotly', '.plotly.json'],
                iconClass: CSS_ICON_CLASS
            }
        ],
        documentWidgetFactoryOptions: {
            name: 'Plotly Editor',
            primaryFileType: 'plotlyeditor',
            // The 'plotly' type is defined in @jupyterlab/plotly-extension
            fileTypes: ['plotly', 'plotlyeditor', 'json'],
            defaultFor: ['plotlyeditor']
        }
    }
];
exports.default = extensions;


/***/ }),

/***/ "5K7Z":
/*!************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_an-object.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isObject = __webpack_require__(/*! ./_is-object */ "93I4");
module.exports = function (it) {
  if (!isObject(it)) throw TypeError(it + ' is not an object!');
  return it;
};


/***/ }),

/***/ "5Luj":
/*!****************************************************!*\
  !*** ./node_modules/pure-color/convert/hsl2rgb.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

function hsl2rgb(hsl) {
  var h = hsl[0] / 360,
      s = hsl[1] / 100,
      l = hsl[2] / 100,
      t1, t2, t3, rgb, val;

  if (s == 0) {
    val = l * 255;
    return [val, val, val];
  }

  if (l < 0.5)
    t2 = l * (1 + s);
  else
    t2 = l + s - l * s;
  t1 = 2 * l - t2;

  rgb = [0, 0, 0];
  for (var i = 0; i < 3; i++) {
    t3 = h + 1 / 3 * - (i - 1);
    t3 < 0 && t3++;
    t3 > 1 && t3--;

    if (6 * t3 < 1)
      val = t1 + (t2 - t1) * 6 * t3;
    else if (2 * t3 < 1)
      val = t2;
    else if (3 * t3 < 2)
      val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
    else
      val = t1;

    rgb[i] = val * 255;
  }

  return rgb;
}

module.exports = hsl2rgb;

/***/ }),

/***/ "5M+I":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/attachments/lib/index.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(__webpack_require__(/*! ./model */ "kZHY"));


/***/ }),

/***/ "5RSi":
/*!***************************************************************!*\
  !*** ./node_modules/draft-js/lib/getUpdatedSelectionState.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule getUpdatedSelectionState
 * @format
 * 
 */



var DraftOffsetKey = __webpack_require__(/*! ./DraftOffsetKey */ "Iq8E");

var nullthrows = __webpack_require__(/*! fbjs/lib/nullthrows */ "gWRK");

function getUpdatedSelectionState(editorState, anchorKey, anchorOffset, focusKey, focusOffset) {
  var selection = nullthrows(editorState.getSelection());
  if (true) {
    if (!anchorKey || !focusKey) {
      /*eslint-disable no-console */
      console.warn('Invalid selection state.', arguments, editorState.toJS());
      /*eslint-enable no-console */
      return selection;
    }
  }

  var anchorPath = DraftOffsetKey.decode(anchorKey);
  var anchorBlockKey = anchorPath.blockKey;
  var anchorLeaf = editorState.getBlockTree(anchorBlockKey).getIn([anchorPath.decoratorKey, 'leaves', anchorPath.leafKey]);

  var focusPath = DraftOffsetKey.decode(focusKey);
  var focusBlockKey = focusPath.blockKey;
  var focusLeaf = editorState.getBlockTree(focusBlockKey).getIn([focusPath.decoratorKey, 'leaves', focusPath.leafKey]);

  var anchorLeafStart = anchorLeaf.get('start');
  var focusLeafStart = focusLeaf.get('start');

  var anchorBlockOffset = anchorLeaf ? anchorLeafStart + anchorOffset : null;
  var focusBlockOffset = focusLeaf ? focusLeafStart + focusOffset : null;

  var areEqual = selection.getAnchorKey() === anchorBlockKey && selection.getAnchorOffset() === anchorBlockOffset && selection.getFocusKey() === focusBlockKey && selection.getFocusOffset() === focusBlockOffset;

  if (areEqual) {
    return selection;
  }

  var isBackward = false;
  if (anchorBlockKey === focusBlockKey) {
    var anchorLeafEnd = anchorLeaf.get('end');
    var focusLeafEnd = focusLeaf.get('end');
    if (focusLeafStart === anchorLeafStart && focusLeafEnd === anchorLeafEnd) {
      isBackward = focusOffset < anchorOffset;
    } else {
      isBackward = focusLeafStart < anchorLeafStart;
    }
  } else {
    var startKey = editorState.getCurrentContent().getBlockMap().keySeq().skipUntil(function (v) {
      return v === anchorBlockKey || v === focusBlockKey;
    }).first();
    isBackward = startKey === focusBlockKey;
  }

  return selection.merge({
    anchorKey: anchorBlockKey,
    anchorOffset: anchorBlockOffset,
    focusKey: focusBlockKey,
    focusOffset: focusBlockOffset,
    isBackward: isBackward
  });
}

module.exports = getUpdatedSelectionState;

/***/ }),

/***/ "5Riz":
/*!************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/Radio.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UnconnectedRadio = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _RadioBlocks = __webpack_require__(/*! ../widgets/RadioBlocks */ "N8y9");

var _RadioBlocks2 = _interopRequireDefault(_RadioBlocks);

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UnconnectedRadio = exports.UnconnectedRadio = function (_Component) {
  _inherits(UnconnectedRadio, _Component);

  function UnconnectedRadio() {
    _classCallCheck(this, UnconnectedRadio);

    return _possibleConstructorReturn(this, (UnconnectedRadio.__proto__ || Object.getPrototypeOf(UnconnectedRadio)).apply(this, arguments));
  }

  _createClass(UnconnectedRadio, [{
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        _Field2.default,
        this.props,
        _react2.default.createElement(_RadioBlocks2.default, {
          options: this.props.options,
          activeOption: this.props.fullValue,
          onOptionChange: this.props.updatePlot
        })
      );
    }
  }]);

  return UnconnectedRadio;
}(_react.Component);

UnconnectedRadio.propTypes = _extends({
  center: _propTypes2.default.bool,
  fullValue: _propTypes2.default.any,
  options: _propTypes2.default.array.isRequired,
  updatePlot: _propTypes2.default.func
}, _Field2.default.propTypes);

// for better appearance <Radio> overrides <Field> {center: false}
// default prop. This can be overridden manually using props for <Radio>.
UnconnectedRadio.defaultProps = {
  center: true
};

exports.default = (0, _lib.connectToContainer)(UnconnectedRadio);
//# sourceMappingURL=Radio.js.map

/***/ }),

/***/ "5T2Y":
/*!*********************************************************!*\
  !*** ./node_modules/core-js/library/modules/_global.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
  ? window : typeof self != 'undefined' && self.Math == Math ? self
  // eslint-disable-next-line no-new-func
  : Function('return this')();
if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef


/***/ }),

/***/ "5Tg0":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_cloneBuffer.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(/*! ./_root */ "Kz5y");

/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;

/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;

/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;

/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined,
    allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;

/**
 * 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;
}

module.exports = cloneBuffer;

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/module.js */ "YuTi")(module)))

/***/ }),

/***/ "5TpB":
/*!******************************************************!*\
  !*** ./node_modules/@phosphor/commands/lib/index.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
var coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
var disposable_1 = __webpack_require__(/*! @phosphor/disposable */ "uNUc");
var domutils_1 = __webpack_require__(/*! @phosphor/domutils */ "XWTc");
var keyboard_1 = __webpack_require__(/*! @phosphor/keyboard */ "djTv");
var signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
/**
 * An object which manages a collection of commands.
 *
 * #### Notes
 * A command registry can be used to populate a variety of action-based
 * widgets, such as command palettes, menus, and toolbars.
 */
var CommandRegistry = (function () {
    /**
     * Construct a new command registry.
     */
    function CommandRegistry() {
        this._timerID = 0;
        this._replaying = false;
        this._keystrokes = [];
        this._keydownEvents = [];
        this._keyBindings = [];
        this._exactKeyMatch = null;
        this._commands = Object.create(null);
        this._commandChanged = new signaling_1.Signal(this);
        this._commandExecuted = new signaling_1.Signal(this);
        this._keyBindingChanged = new signaling_1.Signal(this);
    }
    Object.defineProperty(CommandRegistry.prototype, "commandChanged", {
        /**
         * A signal emitted when a command has changed.
         *
         * #### Notes
         * This signal is useful for visual representations of commands which
         * need to refresh when the state of a relevant command has changed.
         */
        get: function () {
            return this._commandChanged;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(CommandRegistry.prototype, "commandExecuted", {
        /**
         * A signal emitted when a command has executed.
         *
         * #### Notes
         * Care should be taken when consuming this signal. It is intended to
         * be used largely for debugging and logging purposes. It should not
         * be (ab)used for general purpose spying on command execution.
         */
        get: function () {
            return this._commandExecuted;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(CommandRegistry.prototype, "keyBindingChanged", {
        /**
         * A signal emitted when a key binding is changed.
         */
        get: function () {
            return this._keyBindingChanged;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(CommandRegistry.prototype, "keyBindings", {
        /**
         * A read-only array of the key bindings in the registry.
         */
        get: function () {
            return this._keyBindings;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * List the ids of the registered commands.
     *
     * @returns A new array of the registered command ids.
     */
    CommandRegistry.prototype.listCommands = function () {
        return Object.keys(this._commands);
    };
    /**
     * Test whether a specific command is registered.
     *
     * @param id - The id of the command of interest.
     *
     * @returns `true` if the command is registered, `false` otherwise.
     */
    CommandRegistry.prototype.hasCommand = function (id) {
        return id in this._commands;
    };
    /**
     * Add a command to the registry.
     *
     * @param id - The unique id of the command.
     *
     * @param options - The options for the command.
     *
     * @returns A disposable which will remove the command.
     *
     * @throws An error if the given `id` is already registered.
     */
    CommandRegistry.prototype.addCommand = function (id, options) {
        var _this = this;
        // Throw an error if the id is already registered.
        if (id in this._commands) {
            throw new Error("Command '" + id + "' already registered.");
        }
        // Add the command to the registry.
        this._commands[id] = Private.createCommand(options);
        // Emit the `commandChanged` signal.
        this._commandChanged.emit({ id: id, type: 'added' });
        // Return a disposable which will remove the command.
        return new disposable_1.DisposableDelegate(function () {
            // Remove the command from the registry.
            delete _this._commands[id];
            // Emit the `commandChanged` signal.
            _this._commandChanged.emit({ id: id, type: 'removed' });
        });
    };
    /**
     * Notify listeners that the state of a command has changed.
     *
     * @param id - The id of the command which has changed. If more than
     *   one command has changed, this argument should be omitted.
     *
     * @throws An error if the given `id` is not registered.
     *
     * #### Notes
     * This method should be called by the command author whenever the
     * application state changes such that the results of the command
     * metadata functions may have changed.
     *
     * This will cause the `commandChanged` signal to be emitted.
     */
    CommandRegistry.prototype.notifyCommandChanged = function (id) {
        if (id !== undefined && !(id in this._commands)) {
            throw new Error("Command '" + id + "' is not registered.");
        }
        this._commandChanged.emit({ id: id, type: id ? 'changed' : 'many-changed' });
    };
    /**
     * Get the display label for a specific command.
     *
     * @param id - The id of the command of interest.
     *
     * @param args - The arguments for the command.
     *
     * @returns The display label for the command, or an empty string
     *   if the command is not registered.
     */
    CommandRegistry.prototype.label = function (id, args) {
        if (args === void 0) { args = coreutils_1.JSONExt.emptyObject; }
        var cmd = this._commands[id];
        return cmd ? cmd.label.call(undefined, args) : '';
    };
    /**
     * Get the mnemonic index for a specific command.
     *
     * @param id - The id of the command of interest.
     *
     * @param args - The arguments for the command.
     *
     * @returns The mnemonic index for the command, or `-1` if the
     *   command is not registered.
     */
    CommandRegistry.prototype.mnemonic = function (id, args) {
        if (args === void 0) { args = coreutils_1.JSONExt.emptyObject; }
        var cmd = this._commands[id];
        return cmd ? cmd.mnemonic.call(undefined, args) : -1;
    };
    /**
     * @deprecated Use `iconClass()` instead.
     */
    CommandRegistry.prototype.icon = function (id, args) {
        if (args === void 0) { args = coreutils_1.JSONExt.emptyObject; }
        return this.iconClass(id, args);
    };
    /**
     * Get the icon class for a specific command.
     *
     * @param id - The id of the command of interest.
     *
     * @param args - The arguments for the command.
     *
     * @returns The icon class for the command, or an empty string if
     *   the command is not registered.
     */
    CommandRegistry.prototype.iconClass = function (id, args) {
        if (args === void 0) { args = coreutils_1.JSONExt.emptyObject; }
        var cmd = this._commands[id];
        return cmd ? cmd.iconClass.call(undefined, args) : '';
    };
    /**
     * Get the icon label for a specific command.
     *
     * @param id - The id of the command of interest.
     *
     * @param args - The arguments for the command.
     *
     * @returns The icon label for the command, or an empty string if
     *   the command is not registered.
     */
    CommandRegistry.prototype.iconLabel = function (id, args) {
        if (args === void 0) { args = coreutils_1.JSONExt.emptyObject; }
        var cmd = this._commands[id];
        return cmd ? cmd.iconLabel.call(undefined, args) : '';
    };
    /**
     * Get the short form caption for a specific command.
     *
     * @param id - The id of the command of interest.
     *
     * @param args - The arguments for the command.
     *
     * @returns The caption for the command, or an empty string if the
     *   command is not registered.
     */
    CommandRegistry.prototype.caption = function (id, args) {
        if (args === void 0) { args = coreutils_1.JSONExt.emptyObject; }
        var cmd = this._commands[id];
        return cmd ? cmd.caption.call(undefined, args) : '';
    };
    /**
     * Get the usage help text for a specific command.
     *
     * @param id - The id of the command of interest.
     *
     * @param args - The arguments for the command.
     *
     * @returns The usage text for the command, or an empty string if
     *   the command is not registered.
     */
    CommandRegistry.prototype.usage = function (id, args) {
        if (args === void 0) { args = coreutils_1.JSONExt.emptyObject; }
        var cmd = this._commands[id];
        return cmd ? cmd.usage.call(undefined, args) : '';
    };
    /**
     * Get the extra class name for a specific command.
     *
     * @param id - The id of the command of interest.
     *
     * @param args - The arguments for the command.
     *
     * @returns The class name for the command, or an empty string if
     *   the command is not registered.
     */
    CommandRegistry.prototype.className = function (id, args) {
        if (args === void 0) { args = coreutils_1.JSONExt.emptyObject; }
        var cmd = this._commands[id];
        return cmd ? cmd.className.call(undefined, args) : '';
    };
    /**
     * Get the dataset for a specific command.
     *
     * @param id - The id of the command of interest.
     *
     * @param args - The arguments for the command.
     *
     * @returns The dataset for the command, or an empty dataset if
     *   the command is not registered.
     */
    CommandRegistry.prototype.dataset = function (id, args) {
        if (args === void 0) { args = coreutils_1.JSONExt.emptyObject; }
        var cmd = this._commands[id];
        return cmd ? cmd.dataset.call(undefined, args) : {};
    };
    /**
     * Test whether a specific command is enabled.
     *
     * @param id - The id of the command of interest.
     *
     * @param args - The arguments for the command.
     *
     * @returns A boolean indicating whether the command is enabled,
     *   or `false` if the command is not registered.
     */
    CommandRegistry.prototype.isEnabled = function (id, args) {
        if (args === void 0) { args = coreutils_1.JSONExt.emptyObject; }
        var cmd = this._commands[id];
        return cmd ? cmd.isEnabled.call(undefined, args) : false;
    };
    /**
     * Test whether a specific command is toggled.
     *
     * @param id - The id of the command of interest.
     *
     * @param args - The arguments for the command.
     *
     * @returns A boolean indicating whether the command is toggled,
     *   or `false` if the command is not registered.
     */
    CommandRegistry.prototype.isToggled = function (id, args) {
        if (args === void 0) { args = coreutils_1.JSONExt.emptyObject; }
        var cmd = this._commands[id];
        return cmd ? cmd.isToggled.call(undefined, args) : false;
    };
    /**
     * Test whether a specific command is visible.
     *
     * @param id - The id of the command of interest.
     *
     * @param args - The arguments for the command.
     *
     * @returns A boolean indicating whether the command is visible,
     *   or `false` if the command is not registered.
     */
    CommandRegistry.prototype.isVisible = function (id, args) {
        if (args === void 0) { args = coreutils_1.JSONExt.emptyObject; }
        var cmd = this._commands[id];
        return cmd ? cmd.isVisible.call(undefined, args) : false;
    };
    /**
     * Execute a specific command.
     *
     * @param id - The id of the command of interest.
     *
     * @param args - The arguments for the command.
     *
     * @returns A promise which resolves with the result of the command.
     *
     * #### Notes
     * The promise will reject if the command throws an exception,
     * or if the command is not registered.
     */
    CommandRegistry.prototype.execute = function (id, args) {
        if (args === void 0) { args = coreutils_1.JSONExt.emptyObject; }
        // Reject if the command is not registered.
        var cmd = this._commands[id];
        if (!cmd) {
            return Promise.reject(new Error("Command '" + id + "' not registered."));
        }
        // Execute the command and reject if an exception is thrown.
        var value;
        try {
            value = cmd.execute.call(undefined, args);
        }
        catch (err) {
            value = Promise.reject(err);
        }
        // Create the return promise which resolves the result.
        var result = Promise.resolve(value);
        // Emit the command executed signal.
        this._commandExecuted.emit({ id: id, args: args, result: result });
        // Return the result promise to the caller.
        return result;
    };
    /**
     * Add a key binding to the registry.
     *
     * @param options - The options for creating the key binding.
     *
     * @returns A disposable which removes the added key binding.
     *
     * #### Notes
     * If multiple key bindings are registered for the same sequence, the
     * binding with the highest selector specificity is executed first. A
     * tie is broken by using the most recently added key binding.
     *
     * Ambiguous key bindings are resolved with a timeout. As an example,
     * suppose two key bindings are registered: one with the key sequence
     * `['Ctrl D']`, and another with `['Ctrl D', 'Ctrl W']`. If the user
     * presses `Ctrl D`, the first binding cannot be immediately executed
     * since the user may intend to complete the chord with `Ctrl W`. For
     * such cases, a timer is used to allow the chord to be completed. If
     * the chord is not completed before the timeout, the first binding
     * is executed.
     */
    CommandRegistry.prototype.addKeyBinding = function (options) {
        var _this = this;
        // Create the binding for the given options.
        var binding = Private.createKeyBinding(options);
        // Add the key binding to the bindings array.
        this._keyBindings.push(binding);
        // Emit the `bindingChanged` signal.
        this._keyBindingChanged.emit({ binding: binding, type: 'added' });
        // Return a disposable which will remove the binding.
        return new disposable_1.DisposableDelegate(function () {
            // Remove the binding from the array.
            algorithm_1.ArrayExt.removeFirstOf(_this._keyBindings, binding);
            // Emit the `bindingChanged` signal.
            _this._keyBindingChanged.emit({ binding: binding, type: 'removed' });
        });
    };
    /**
     * Process a `'keydown'` event and invoke a matching key binding.
     *
     * @param event - The event object for a `'keydown'` event.
     *
     * #### Notes
     * This should be called in response to a `'keydown'` event in order
     * to invoke the command for the best matching key binding.
     *
     * The registry **does not** install its own listener for `'keydown'`
     * events. This allows the application full control over the nodes
     * and phase for which the registry processes `'keydown'` events.
     */
    CommandRegistry.prototype.processKeydownEvent = function (event) {
        // Bail immediately if playing back keystrokes.
        if (this._replaying) {
            return;
        }
        // Get the normalized keystroke for the event.
        var keystroke = CommandRegistry.keystrokeForKeydownEvent(event);
        // If the keystroke is not valid for the keyboard layout, replay
        // any suppressed events and clear the pending state.
        if (!keystroke) {
            this._replayKeydownEvents();
            this._clearPendingState();
            return;
        }
        // Add the keystroke to the current key sequence.
        this._keystrokes.push(keystroke);
        // Find the exact and partial matches for the key sequence.
        var _a = Private.matchKeyBinding(this._keyBindings, this._keystrokes, event), exact = _a.exact, partial = _a.partial;
        // If there is no exact match and no partial match, replay
        // any suppressed events and clear the pending state.
        if (!exact && !partial) {
            this._replayKeydownEvents();
            this._clearPendingState();
            return;
        }
        // Stop propagation of the event. If there is only a partial match,
        // the event will be replayed if a final exact match never occurs.
        event.preventDefault();
        event.stopPropagation();
        // If there is an exact match but no partial match, the exact match
        // can be dispatched immediately. The pending state is cleared so
        // the next key press starts from the default state.
        if (exact && !partial) {
            this._executeKeyBinding(exact);
            this._clearPendingState();
            return;
        }
        // If there is both an exact match and a partial match, the exact
        // match is stored for future dispatch in case the timer expires
        // before a more specific match is triggered.
        if (exact) {
            this._exactKeyMatch = exact;
        }
        // Store the event for possible playback in the future.
        this._keydownEvents.push(event);
        // (Re)start the timer to dispatch the most recent exact match
        // in case the partial match fails to result in an exact match.
        this._startTimer();
    };
    /**
     * Start or restart the pending timeout.
     */
    CommandRegistry.prototype._startTimer = function () {
        var _this = this;
        this._clearTimer();
        this._timerID = setTimeout(function () {
            _this._onPendingTimeout();
        }, Private.CHORD_TIMEOUT);
    };
    /**
     * Clear the pending timeout.
     */
    CommandRegistry.prototype._clearTimer = function () {
        if (this._timerID !== 0) {
            clearTimeout(this._timerID);
            this._timerID = 0;
        }
    };
    /**
     * Replay the keydown events which were suppressed.
     */
    CommandRegistry.prototype._replayKeydownEvents = function () {
        if (this._keydownEvents.length === 0) {
            return;
        }
        this._replaying = true;
        this._keydownEvents.forEach(Private.replayKeyEvent);
        this._replaying = false;
    };
    /**
     * Execute the command for the given key binding.
     *
     * If the command is missing or disabled, a warning will be logged.
     */
    CommandRegistry.prototype._executeKeyBinding = function (binding) {
        var command = binding.command, args = binding.args;
        if (!this.hasCommand(command) || !this.isEnabled(command, args)) {
            var word = this.hasCommand(command) ? 'enabled' : 'registered';
            var keys = binding.keys.join(', ');
            var msg1 = "Cannot execute key binding '" + keys + "':";
            var msg2 = "command '" + command + "' is not " + word + ".";
            console.warn(msg1 + " " + msg2);
            return;
        }
        this.execute(command, args);
    };
    /**
     * Clear the internal pending state.
     */
    CommandRegistry.prototype._clearPendingState = function () {
        this._clearTimer();
        this._exactKeyMatch = null;
        this._keystrokes.length = 0;
        this._keydownEvents.length = 0;
    };
    /**
     * Handle the partial match timeout.
     */
    CommandRegistry.prototype._onPendingTimeout = function () {
        this._timerID = 0;
        if (this._exactKeyMatch) {
            this._executeKeyBinding(this._exactKeyMatch);
        }
        else {
            this._replayKeydownEvents();
        }
        this._clearPendingState();
    };
    return CommandRegistry;
}());
exports.CommandRegistry = CommandRegistry;
/**
 * The namespace for the `CommandRegistry` class statics.
 */
(function (CommandRegistry) {
    /**
     * Parse a keystroke into its constituent components.
     *
     * @param keystroke - The keystroke of interest.
     *
     * @returns The parsed components of the keystroke.
     *
     * #### Notes
     * The keystroke should be of the form:
     *   `[<modifier 1> [<modifier 2> [<modifier N> ]]]<primary key>`
     *
     * The supported modifiers are: `Accel`, `Alt`, `Cmd`, `Ctrl`, and
     * `Shift`. The `Accel` modifier is translated to `Cmd` on Mac and
     * `Ctrl` on all other platforms.
     *
     * The parsing is tolerant and will not throw exceptions. Notably:
     *   - Duplicate modifiers are ignored.
     *   - Extra primary keys are ignored.
     *   - The order of modifiers and primary key is irrelevant.
     *   - The keystroke parts should be separated by whitespace.
     *   - The keystroke is case sensitive.
     */
    function parseKeystroke(keystroke) {
        var key = '';
        var alt = false;
        var cmd = false;
        var ctrl = false;
        var shift = false;
        for (var _i = 0, _a = keystroke.split(/\s+/); _i < _a.length; _i++) {
            var token = _a[_i];
            if (token === 'Accel') {
                if (domutils_1.Platform.IS_MAC) {
                    cmd = true;
                }
                else {
                    ctrl = true;
                }
            }
            else if (token === 'Alt') {
                alt = true;
            }
            else if (token === 'Cmd') {
                cmd = true;
            }
            else if (token === 'Ctrl') {
                ctrl = true;
            }
            else if (token === 'Shift') {
                shift = true;
            }
            else if (token.length > 0) {
                key = token;
            }
        }
        return { cmd: cmd, ctrl: ctrl, alt: alt, shift: shift, key: key };
    }
    CommandRegistry.parseKeystroke = parseKeystroke;
    /**
     * Normalize a keystroke into a canonical representation.
     *
     * @param keystroke - The keystroke of interest.
     *
     * @returns The normalized representation of the keystroke.
     *
     * #### Notes
     * This normalizes the keystroke by removing duplicate modifiers and
     * extra primary keys, and assembling the parts in a canonical order.
     *
     * The `Cmd` modifier is ignored on non-Mac platforms.
     */
    function normalizeKeystroke(keystroke) {
        var mods = '';
        var parts = parseKeystroke(keystroke);
        if (parts.ctrl) {
            mods += 'Ctrl ';
        }
        if (parts.alt) {
            mods += 'Alt ';
        }
        if (parts.shift) {
            mods += 'Shift ';
        }
        if (parts.cmd && domutils_1.Platform.IS_MAC) {
            mods += 'Cmd ';
        }
        return mods + parts.key;
    }
    CommandRegistry.normalizeKeystroke = normalizeKeystroke;
    /**
     * Format a keystroke for display on the local system.
     */
    function formatKeystroke(keystroke) {
        var mods = '';
        var parts = parseKeystroke(keystroke);
        if (domutils_1.Platform.IS_MAC) {
            if (parts.ctrl) {
                mods += '\u2303 ';
            }
            if (parts.alt) {
                mods += '\u2325 ';
            }
            if (parts.shift) {
                mods += '\u21E7 ';
            }
            if (parts.cmd) {
                mods += '\u2318 ';
            }
        }
        else {
            if (parts.ctrl) {
                mods += 'Ctrl+';
            }
            if (parts.alt) {
                mods += 'Alt+';
            }
            if (parts.shift) {
                mods += 'Shift+';
            }
        }
        return mods + parts.key;
    }
    CommandRegistry.formatKeystroke = formatKeystroke;
    /**
     * Create a normalized keystroke for a `'keydown'` event.
     *
     * @param event - The event object for a `'keydown'` event.
     *
     * @returns A normalized keystroke, or an empty string if the event
     *   does not represent a valid keystroke for the given layout.
     */
    function keystrokeForKeydownEvent(event) {
        var key = keyboard_1.getKeyboardLayout().keyForKeydownEvent(event);
        if (!key) {
            return '';
        }
        var mods = '';
        if (event.ctrlKey) {
            mods += 'Ctrl ';
        }
        if (event.altKey) {
            mods += 'Alt ';
        }
        if (event.shiftKey) {
            mods += 'Shift ';
        }
        if (event.metaKey && domutils_1.Platform.IS_MAC) {
            mods += 'Cmd ';
        }
        return mods + key;
    }
    CommandRegistry.keystrokeForKeydownEvent = keystrokeForKeydownEvent;
})(CommandRegistry = exports.CommandRegistry || (exports.CommandRegistry = {}));
exports.CommandRegistry = CommandRegistry;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * The timeout in ms for triggering a key binding chord.
     */
    Private.CHORD_TIMEOUT = 1000;
    /**
     * Create a normalized command from an options object.
     */
    function createCommand(options) {
        return {
            execute: options.execute,
            label: asFunc(options.label, emptyStringFunc),
            mnemonic: asFunc(options.mnemonic, negativeOneFunc),
            iconClass: asFunc(options.iconClass || options.icon, emptyStringFunc),
            iconLabel: asFunc(options.iconLabel, emptyStringFunc),
            caption: asFunc(options.caption, emptyStringFunc),
            usage: asFunc(options.usage, emptyStringFunc),
            className: asFunc(options.className, emptyStringFunc),
            dataset: asFunc(options.dataset, emptyDatasetFunc),
            isEnabled: options.isEnabled || trueFunc,
            isToggled: options.isToggled || falseFunc,
            isVisible: options.isVisible || trueFunc
        };
    }
    Private.createCommand = createCommand;
    /**
     * Create a key binding object from key binding options.
     */
    function createKeyBinding(options) {
        return {
            keys: normalizeKeys(options),
            selector: validateSelector(options),
            command: options.command,
            args: options.args || coreutils_1.JSONExt.emptyObject
        };
    }
    Private.createKeyBinding = createKeyBinding;
    /**
     * Find the key bindings which match a key sequence.
     *
     * This returns a match result which contains the best exact matching
     * binding, and a flag which indicates if there are partial matches.
     */
    function matchKeyBinding(bindings, keys, event) {
        // The current best exact match.
        var exact = null;
        // Whether a partial match has been found.
        var partial = false;
        // The match distance for the exact match.
        var distance = Infinity;
        // The specificity for the exact match.
        var specificity = 0;
        // Iterate over the bindings and search for the best match.
        for (var i = 0, n = bindings.length; i < n; ++i) {
            // Lookup the current binding.
            var binding = bindings[i];
            // Check whether the key binding sequence is a match.
            var sqm = matchSequence(binding.keys, keys);
            // If there is no match, the binding is ignored.
            if (sqm === 0 /* None */) {
                continue;
            }
            // If it is a partial match and no other partial match has been
            // found, ensure the selector matches and set the partial flag.
            if (sqm === 2 /* Partial */) {
                if (!partial && targetDistance(binding.selector, event) !== -1) {
                    partial = true;
                }
                continue;
            }
            // Ignore the match if the selector doesn't match, or if the
            // matched node is farther away than the current best match.
            var td = targetDistance(binding.selector, event);
            if (td === -1 || td > distance) {
                continue;
            }
            // Get the specificity for the selector.
            var sp = domutils_1.Selector.calculateSpecificity(binding.selector);
            // Update the best match if this match is stronger.
            if (!exact || td < distance || sp >= specificity) {
                exact = binding;
                distance = td;
                specificity = sp;
            }
        }
        // Return the match result.
        return { exact: exact, partial: partial };
    }
    Private.matchKeyBinding = matchKeyBinding;
    /**
     * Replay a keyboard event.
     *
     * This synthetically dispatches a clone of the keyboard event.
     */
    function replayKeyEvent(event) {
        event.target.dispatchEvent(cloneKeyboardEvent(event));
    }
    Private.replayKeyEvent = replayKeyEvent;
    /**
     * A singleton empty string function.
     */
    var emptyStringFunc = function () { return ''; };
    /**
     * A singleton `-1` number function
     */
    var negativeOneFunc = function () { return -1; };
    /**
     * A singleton true boolean function.
     */
    var trueFunc = function () { return true; };
    /**
     * A singleton false boolean function.
     */
    var falseFunc = function () { return false; };
    /**
     * A singleton empty dataset function.
     */
    var emptyDatasetFunc = function () { return ({}); };
    /**
     * Cast a value or command func to a command func.
     */
    function asFunc(value, dfault) {
        if (value === undefined) {
            return dfault;
        }
        if (typeof value === 'function') {
            return value;
        }
        return function () { return value; };
    }
    /**
     * Get the platform-specific normalized keys for an options object.
     */
    function normalizeKeys(options) {
        var keys;
        if (domutils_1.Platform.IS_WIN) {
            keys = options.winKeys || options.keys;
        }
        else if (domutils_1.Platform.IS_MAC) {
            keys = options.macKeys || options.keys;
        }
        else {
            keys = options.linuxKeys || options.keys;
        }
        return keys.map(CommandRegistry.normalizeKeystroke);
    }
    /**
     * Validate the selector for an options object.
     *
     * This returns the validated selector, or throws if the selector is
     * invalid or contains commas.
     */
    function validateSelector(options) {
        if (options.selector.indexOf(',') !== -1) {
            throw new Error("Selector cannot contain commas: " + options.selector);
        }
        if (!domutils_1.Selector.isValid(options.selector)) {
            throw new Error("Invalid selector: " + options.selector);
        }
        return options.selector;
    }
    ;
    /**
     * Test whether a key binding sequence matches a key sequence.
     *
     * Returns a `SequenceMatch` value indicating the type of match.
     */
    function matchSequence(bindKeys, userKeys) {
        if (bindKeys.length < userKeys.length) {
            return 0 /* None */;
        }
        for (var i = 0, n = userKeys.length; i < n; ++i) {
            if (bindKeys[i] !== userKeys[i]) {
                return 0 /* None */;
            }
        }
        if (bindKeys.length > userKeys.length) {
            return 2 /* Partial */;
        }
        return 1 /* Exact */;
    }
    /**
     * Find the distance from the target node to the first matching node.
     *
     * This traverses the event path from `target` to `currentTarget` and
     * computes the distance from `target` to the first node which matches
     * the CSS selector. If no match is found, `-1` is returned.
     */
    function targetDistance(selector, event) {
        var targ = event.target;
        var curr = event.currentTarget;
        for (var dist = 0; targ !== null; targ = targ.parentElement, ++dist) {
            if (domutils_1.Selector.matches(targ, selector)) {
                return dist;
            }
            if (targ === curr) {
                return -1;
            }
        }
        return -1;
    }
    /**
     * Clone a keyboard event.
     */
    function cloneKeyboardEvent(event) {
        // A custom event is required because Chrome nulls out the
        // `keyCode` field in user-generated `KeyboardEvent` types.
        var clone = document.createEvent('Event');
        var bubbles = event.bubbles || true;
        var cancelable = event.cancelable || true;
        clone.initEvent(event.type || 'keydown', bubbles, cancelable);
        clone.key = event.key || '';
        clone.keyCode = event.keyCode || 0;
        clone.which = event.keyCode || 0;
        clone.ctrlKey = event.ctrlKey || false;
        clone.altKey = event.altKey || false;
        clone.shiftKey = event.shiftKey || false;
        clone.metaKey = event.metaKey || false;
        clone.view = event.view || window;
        return clone;
    }
})(Private || (Private = {}));


/***/ }),

/***/ "5biZ":
/*!**************************************************************************!*\
  !*** ./node_modules/core-js/library/fn/object/get-own-property-names.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(/*! ../../modules/es6.object.get-own-property-names */ "EnHN");
var $Object = __webpack_require__(/*! ../../modules/_core */ "WEpk").Object;
module.exports = function getOwnPropertyNames(it) {
  return $Object.getOwnPropertyNames(it);
};


/***/ }),

/***/ "5cFW":
/*!************************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils/lib/clipboard.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
/**
 * The clipboard interface.
 */
var Clipboard;
(function (Clipboard) {
    /**
     * Get the application clipboard instance.
     */
    function getInstance() {
        return Private.instance;
    }
    Clipboard.getInstance = getInstance;
    /**
     * Set the application clipboard instance.
     */
    function setInstance(value) {
        Private.instance = value;
    }
    Clipboard.setInstance = setInstance;
    /**
     * Copy text to the system clipboard.
     *
     * #### Notes
     * This can only be called in response to a user input event.
     */
    function copyToSystem(text) {
        let node = document.body;
        let handler = (event) => {
            let data = event.clipboardData || window.clipboardData;
            data.setData('text', text);
            event.preventDefault();
            node.removeEventListener('copy', handler);
        };
        node.addEventListener('copy', handler);
        generateEvent(node);
    }
    Clipboard.copyToSystem = copyToSystem;
    /**
     * Generate a clipboard event on a node.
     *
     * @param node - The element on which to generate the event.
     *
     * @param type - The type of event to generate.
     *   `'paste'` events cannot be programmatically generated.
     *
     * #### Notes
     * This can only be called in response to a user input event.
     */
    function generateEvent(node, type = 'copy') {
        // http://stackoverflow.com/a/5210367
        // Identify selected text.
        let sel = window.getSelection();
        // Save the current selection.
        let savedRanges = [];
        for (let i = 0, len = sel.rangeCount; i < len; ++i) {
            savedRanges[i] = sel.getRangeAt(i).cloneRange();
        }
        // Select the node content.
        let range = document.createRange();
        range.selectNodeContents(node);
        sel.removeAllRanges();
        sel.addRange(range);
        // Execute the command.
        document.execCommand(type);
        // Restore the previous selection.
        sel = window.getSelection();
        sel.removeAllRanges();
        for (let i = 0, len = savedRanges.length; i < len; ++i) {
            sel.addRange(savedRanges[i]);
        }
    }
    Clipboard.generateEvent = generateEvent;
})(Clipboard = exports.Clipboard || (exports.Clipboard = {}));
/**
 * The namespace for module private data.
 */
var Private;
(function (Private) {
    /**
     * The application clipboard instance.
     */
    Private.instance = new coreutils_1.MimeData();
})(Private || (Private = {}));


/***/ }),

/***/ "5dP4":
/*!****************************************************************!*\
  !*** ./node_modules/@jupyterlab/docmanager/lib/savehandler.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
/**
 * A class that manages the auto saving of a document.
 *
 * #### Notes
 * Implements https://github.com/ipython/ipython/wiki/IPEP-15:-Autosaving-the-IPython-Notebook.
 */
class SaveHandler {
    /**
     * Construct a new save handler.
     */
    constructor(options) {
        this._autosaveTimer = -1;
        this._minInterval = -1;
        this._interval = -1;
        this._isActive = false;
        this._inDialog = false;
        this._isDisposed = false;
        this._multiplier = 10;
        this._context = options.context;
        let interval = options.saveInterval || 120;
        this._minInterval = interval * 1000;
        this._interval = this._minInterval;
        // Restart the timer when the contents model is updated.
        this._context.fileChanged.connect(this._setTimer, this);
        this._context.disposed.connect(this.dispose, this);
    }
    /**
     * The save interval used by the timer (in seconds).
     */
    get saveInterval() {
        return this._interval / 1000;
    }
    set saveInterval(value) {
        this._minInterval = this._interval = value * 1000;
        if (this._isActive) {
            this._setTimer();
        }
    }
    /**
     * Get whether the handler is active.
     */
    get isActive() {
        return this._isActive;
    }
    /**
     * Get whether the save handler is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources used by the save handler.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        clearTimeout(this._autosaveTimer);
        signaling_1.Signal.clearData(this);
    }
    /**
     * Start the autosaver.
     */
    start() {
        this._isActive = true;
        this._setTimer();
    }
    /**
     * Stop the autosaver.
     */
    stop() {
        this._isActive = false;
        clearTimeout(this._autosaveTimer);
    }
    /**
     * Set the timer.
     */
    _setTimer() {
        clearTimeout(this._autosaveTimer);
        if (!this._isActive) {
            return;
        }
        this._autosaveTimer = window.setTimeout(() => {
            this._save();
        }, this._interval);
    }
    /**
     * Handle an autosave timeout.
     */
    _save() {
        let context = this._context;
        // Trigger the next update.
        this._setTimer();
        if (!context) {
            return;
        }
        // Bail if the model is not dirty or the file is not writable, or the dialog
        // is already showing.
        let writable = context.contentsModel && context.contentsModel.writable;
        if (!writable || !context.model.dirty || this._inDialog) {
            return;
        }
        let start = new Date().getTime();
        context
            .save()
            .then(() => {
            if (this.isDisposed) {
                return;
            }
            let duration = new Date().getTime() - start;
            // New save interval: higher of 10x save duration or min interval.
            this._interval = Math.max(this._multiplier * duration, this._minInterval);
            // Restart the update to pick up the new interval.
            this._setTimer();
        })
            .catch(err => {
            // If the user canceled the save, do nothing.
            if (err.message === 'Cancel') {
                return;
            }
            // Otherwise, log the error.
            console.error('Error in Auto-Save', err.message);
        });
    }
}
exports.SaveHandler = SaveHandler;


/***/ }),

/***/ "5og8":
/*!**************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/derived.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.HoverColor = exports.HovermodeDropdown = exports.HoveronDropdown = exports.FillDropdown = exports.HoverInfo = exports.HoverTemplateText = exports.HoverTemplateSwitch = exports.TextInfo = exports.PositioningNumeric = exports.PositioningRef = exports.AnnotationRef = exports.AnnotationArrowRef = exports.NumericReciprocal = exports.NumericFractionInverse = exports.NumericFractionDomain = exports.NumericFraction = exports.DTicksInterval = exports.DTicks = exports.NTicks = exports.AxesRange = exports.Histogram2d = exports.HistogramInfoHorizontal = exports.HistogramInfoVertical = exports.ShowInLegend = exports.TickFormat = exports.BinningDropdown = exports.ContourNumeric = exports.AxisSide = exports.RangesliderVisible = exports.AxisOverlayDropdown = exports.AxisAnchorDropdown = undefined;

var _fastIsnumeric = __webpack_require__(/*! fast-isnumeric */ "GbLo");

var _fastIsnumeric2 = _interopRequireDefault(_fastIsnumeric);

var _Dropdown = __webpack_require__(/*! ./Dropdown */ "dRXW");

var _DropdownCustom = __webpack_require__(/*! ./DropdownCustom */ "H7PE");

var _Flaglist = __webpack_require__(/*! ./Flaglist */ "fS+6");

var _Numeric = __webpack_require__(/*! ./Numeric */ "E01D");

var _NumericOrDate = __webpack_require__(/*! ./NumericOrDate */ "dZIv");

var _AxisRangeValue = __webpack_require__(/*! ./AxisRangeValue */ "eRYw");

var _Radio = __webpack_require__(/*! ./Radio */ "5Riz");

var _AxisInterval = __webpack_require__(/*! ./AxisInterval */ "eeV2");

var _Info = __webpack_require__(/*! ./Info */ "iOcY");

var _Info2 = _interopRequireDefault(_Info);

var _ColorPicker = __webpack_require__(/*! ./ColorPicker */ "u/dz");

var _TextEditor = __webpack_require__(/*! ./TextEditor */ "0b9Q");

var _VisibilitySelect = __webpack_require__(/*! ./VisibilitySelect */ "a9J7");

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var AxisAnchorDropdown = exports.AxisAnchorDropdown = (0, _lib.connectToContainer)(_Dropdown.UnconnectedDropdown, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var _ = context.localize;

    var options = [];

    if (props.attr.startsWith('xaxis')) {
      options = context.fullLayout._subplots.yaxis.map(function (axis) {
        return {
          label: (0, _lib.getAxisTitle)(context.fullLayout[(0, _lib.axisIdToAxisName)(axis)]),
          value: axis
        };
      });
    } else if (props.attr.startsWith('yaxis')) {
      options = context.fullLayout._subplots.xaxis.map(function (axis) {
        return {
          label: (0, _lib.getAxisTitle)(context.fullLayout[(0, _lib.axisIdToAxisName)(axis)]),
          value: axis
        };
      });
    }
    options.push({ label: _('Free'), value: 'free' });
    plotProps.options = options;
  }
});

var AxisOverlayDropdown = exports.AxisOverlayDropdown = (0, _lib.connectToContainer)(_Dropdown.UnconnectedDropdown, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var _ = context.localize;

    var options = [];

    if (props.attr.startsWith('xaxis')) {
      options = context.fullLayout._subplots.xaxis.map(function (axis) {
        return {
          label: (0, _lib.getAxisTitle)(context.fullLayout[(0, _lib.axisIdToAxisName)(axis)]),
          value: axis
        };
      });
    } else if (props.attr.startsWith('yaxis')) {
      options = context.fullLayout._subplots.yaxis.map(function (axis) {
        return {
          label: (0, _lib.getAxisTitle)(context.fullLayout[(0, _lib.axisIdToAxisName)(axis)]),
          value: axis
        };
      });
    }

    options.unshift({ label: _('None'), value: false });

    // filter out the current axisID, can't overlay over itself
    plotProps.options = options.filter(function (option) {
      return context.fullContainer && context.fullContainer.xaxis && context.fullContainer.yaxis && context.fullContainer.xaxis._id !== option.value && context.fullContainer.yaxis._id !== option.value;
    });

    plotProps.clearable = false;
  }
});

var RangesliderVisible = exports.RangesliderVisible = (0, _lib.connectToContainer)(_Radio.UnconnectedRadio, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    if (!plotProps.fullValue) {
      plotProps.fullValue = false;
      plotProps.visible = false;
      plotProps.isVisible = true;
      return;
    }
  }
});

var AxisSide = exports.AxisSide = (0, _lib.connectToContainer)(_Radio.UnconnectedRadio, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var _ = context.localize;

    if (plotProps.fullValue === 'left' || plotProps.fullValue === 'right') {
      plotProps.options = [{ label: _('Left'), value: 'left' }, { label: _('Right'), value: 'right' }];
      return;
    }

    if (plotProps.fullValue === 'top' || plotProps.fullValue === 'bottom') {
      plotProps.options = [{ label: _('Top'), value: 'top' }, { label: _('Bottom'), value: 'bottom' }];
      return;
    }

    if (plotProps.fullValue === 'clockwise' || plotProps.fullValue === 'counterclockwise') {
      plotProps.options = [{ label: _('Clockwise'), value: 'clockwise' }, { label: _('Counterclockwise'), value: 'counterclockwise' }];
      return;
    }

    plotProps.isVisible = false;
  }
});

var ContourNumeric = exports.ContourNumeric = (0, _lib.connectToContainer)(_Numeric.UnconnectedNumeric, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var fullContainer = plotProps.fullContainer;

    if (plotProps.isVisible && fullContainer && fullContainer.autocontour) {
      plotProps.isVisible = false;
    }
  }
});

var BinningDropdown = exports.BinningDropdown = (0, _lib.connectToContainer)(_Dropdown.UnconnectedDropdown, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var _ = context.localize;

    var axis = plotProps.fullContainer.type === 'histogram2d' ? 'Z' : plotProps.fullContainer.orientation === 'v' ? 'Y' : 'X';
    plotProps.options = [{ label: _('Count ') + axis, value: 'count' }, { label: _('Sum ') + axis, value: 'sum' }, { label: _('Average ') + axis, value: 'avg' }, { label: _('Minimum ') + axis, value: 'min' }, { label: _('Maximum ') + axis, value: 'max' }];
  }
});

var TickFormat = exports.TickFormat = (0, _lib.connectToContainer)(_DropdownCustom.UnconnectedDropdownCustom, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var _ = context.localize;

    if (plotProps.fullContainer.type === 'date') {
      plotProps.options = [{ label: _('Default'), value: '' }, { label: _('Advanced (d3-time-format)'), value: '%x' }];
      plotProps.customOpt = '%x';
    } else {
      plotProps.options = [{ label: _('Simple'), value: '' }, { label: _('Advanced (d3-format)'), value: 's' }];
      plotProps.customOpt = 's';
    }
  }
});

var ShowInLegend = exports.ShowInLegend = (0, _lib.connectToContainer)(_VisibilitySelect.UnconnectedVisibilitySelect, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    plotProps.isVisible = context.fullLayout.showlegend;
    return plotProps;
  }
});

var HistogramInfoVertical = exports.HistogramInfoVertical = (0, _lib.connectToContainer)(_Info2.default, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    plotProps.isVisible = context.fullContainer.type === 'histogram' && context.fullContainer.orientation === 'v';
    return plotProps;
  }
});

var HistogramInfoHorizontal = exports.HistogramInfoHorizontal = (0, _lib.connectToContainer)(_Info2.default, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    plotProps.isVisible = context.fullContainer.type === 'histogram' && context.fullContainer.orientation === 'h';
    return plotProps;
  }
});

var Histogram2d = exports.Histogram2d = (0, _lib.connectToContainer)(_Info2.default, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    plotProps.isVisible = context.fullContainer.type === 'histogram2d';
    return plotProps;
  }
});

var AxesRange = exports.AxesRange = (0, _lib.connectToContainer)(_AxisRangeValue.UnconnectedAxisRangeValue, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var fullContainer = plotProps.fullContainer;

    if (plotProps.isVisible && fullContainer && fullContainer.autorange) {
      plotProps.isVisible = false;
    }
    return plotProps;
  }
});

var NTicks = exports.NTicks = (0, _lib.connectToContainer)(_Numeric.UnconnectedNumeric, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var fullContainer = plotProps.fullContainer;

    if (plotProps.isVisible && fullContainer && fullContainer.tickmode !== 'auto') {
      plotProps.isVisible = false;
    }
    return plotProps;
  }
});

var DTicks = exports.DTicks = (0, _lib.connectToContainer)(_AxisRangeValue.UnconnectedAxisRangeValue, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var fullContainer = plotProps.fullContainer;

    if (fullContainer && fullContainer._name && (fullContainer._name.startsWith('lat') || fullContainer._name.startsWith('lon'))) {
      // don't mess with visibility on geo axes
      return plotProps;
    }
    if (plotProps.isVisible && fullContainer && fullContainer.tickmode !== 'linear') {
      plotProps.isVisible = false;
    }
    return plotProps;
  }
});

var DTicksInterval = exports.DTicksInterval = (0, _lib.connectToContainer)(_AxisInterval.UnconnectedAxisInterval, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var fullContainer = plotProps.fullContainer;

    if (fullContainer && fullContainer._name && (fullContainer._name.startsWith('lat') || fullContainer._name.startsWith('lon'))) {
      // don't mess with visibility on geo axes
      return plotProps;
    }
    if (plotProps.isVisible && fullContainer && fullContainer.tickmode !== 'linear') {
      plotProps.isVisible = false;
    }
    return plotProps;
  }
});

var UnconnectedNumericFraction = function (_UnconnectedNumeric) {
  _inherits(UnconnectedNumericFraction, _UnconnectedNumeric);

  function UnconnectedNumericFraction() {
    _classCallCheck(this, UnconnectedNumericFraction);

    return _possibleConstructorReturn(this, (UnconnectedNumericFraction.__proto__ || Object.getPrototypeOf(UnconnectedNumericFraction)).apply(this, arguments));
  }

  return UnconnectedNumericFraction;
}(_Numeric.UnconnectedNumeric);

UnconnectedNumericFraction.propTypes = _Numeric.UnconnectedNumeric.propTypes;
UnconnectedNumericFraction.defaultProps = {
  units: '%',
  showSlider: true
};

var numericFractionModifyPlotProps = function numericFractionModifyPlotProps(props, context, plotProps) {
  var attrMeta = plotProps.attrMeta,
      fullValue = plotProps.fullValue,
      updatePlot = plotProps.updatePlot;

  var min = attrMeta && attrMeta.min || 0;
  var max = attrMeta && attrMeta.max || 1;
  if ((0, _fastIsnumeric2.default)(fullValue)) {
    plotProps.fullValue = Math.round(100 * (fullValue - min) / (max - min));
  }

  plotProps.updatePlot = function (v) {
    if ((0, _fastIsnumeric2.default)(v)) {
      updatePlot(v / 100 * (max - min) + min);
    } else {
      updatePlot(v);
    }
  };
  plotProps.max = 100;
  plotProps.min = 0;
};

var NumericFraction = exports.NumericFraction = (0, _lib.connectToContainer)(UnconnectedNumericFraction, {
  modifyPlotProps: numericFractionModifyPlotProps
});

var NumericFractionDomain = exports.NumericFractionDomain = (0, _lib.connectToContainer)(UnconnectedNumericFraction, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    numericFractionModifyPlotProps(props, context, plotProps);
    if (context.container && context.container.overlaying) {
      plotProps.isVisible = null;
    }
  }
});

var NumericFractionInverse = exports.NumericFractionInverse = (0, _lib.connectToContainer)(UnconnectedNumericFraction, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var attrMeta = plotProps.attrMeta,
        fullValue = plotProps.fullValue,
        updatePlot = plotProps.updatePlot;

    if ((0, _fastIsnumeric2.default)(fullValue)) {
      plotProps.fullValue = Math.round((1 - fullValue) * 100);
    }

    plotProps.updatePlot = function (v) {
      if ((0, _fastIsnumeric2.default)(v)) {
        updatePlot(1 - v / 100);
      } else {
        updatePlot(v);
      }
    };

    // Also take the inverse of max and min.
    if (attrMeta) {
      if ((0, _fastIsnumeric2.default)(attrMeta.min)) {
        plotProps.max = (1 - attrMeta.min) * 100;
      }

      if ((0, _fastIsnumeric2.default)(attrMeta.max)) {
        plotProps.min = (1 - attrMeta.max) * 100;
      }
    }
  }
});

var NumericReciprocal = exports.NumericReciprocal = (0, _lib.connectToContainer)(_Numeric.UnconnectedNumeric, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var fullValue = plotProps.fullValue,
        updatePlot = plotProps.updatePlot;


    if ((0, _fastIsnumeric2.default)(fullValue)) {
      plotProps.fullValue = 1 / fullValue;
    }

    plotProps.updatePlot = function (v) {
      if ((0, _fastIsnumeric2.default)(v)) {
        updatePlot(1 / v);
      } else {
        updatePlot(v);
      }
    };

    plotProps.min = 0;
  }
});

var AnnotationArrowRef = exports.AnnotationArrowRef = (0, _lib.connectToContainer)(_Dropdown.UnconnectedDropdown, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var _ = context.localize;

    if (!context.fullContainer) {
      return;
    }
    var _context$fullContaine = context.fullContainer,
        xref = _context$fullContaine.xref,
        yref = _context$fullContaine.yref;


    var currentAxisRef = void 0;
    if (props.attr === 'axref') {
      currentAxisRef = xref;
    } else if (props.attr === 'ayref') {
      currentAxisRef = yref;
    } else {
      throw new Error(_('AnnotationArrowRef must be given either "axref" or "ayref" as attrs. Instead was given') + props.attr);
    }

    if (currentAxisRef === 'paper') {
      // If currentAxesRef is paper provide all axes options to user.

      var axes = (0, _lib.getAllAxes)(context.fullLayout).filter(function (a) {
        return a._id;
      });
      if (axes.length > 0) {
        plotProps.options = [{ label: _('in pixels'), value: 'pixel' }].concat(_toConsumableArray(computeAxesRefOptions(axes, props.attr)));
      } else {
        plotProps.isVisible = false;
      }
    } else {
      // If currentAxesRef is an actual axes then offer that value as the only
      // axes option.
      plotProps.options = [{ label: _('in pixels'), value: 'pixel' }, { label: _('according to axis'), value: currentAxisRef }];
    }

    plotProps.clearable = false;
  }
});

var AnnotationRef = exports.AnnotationRef = (0, _lib.connectToContainer)(_Dropdown.UnconnectedDropdown, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    if (!context.fullContainer) {
      return;
    }
    var _context$fullContaine2 = context.fullContainer,
        axref = _context$fullContaine2.axref,
        ayref = _context$fullContaine2.ayref,
        _ = context.localize;


    var currentOffsetRef = void 0;
    if (props.attr === 'xref') {
      currentOffsetRef = axref;
    } else if (props.attr === 'yref') {
      currentOffsetRef = ayref;
    } else {
      throw new Error(_('AnnotationRef must be given either "xref" or "yref" as attrs. Instead was given') + props.attr + '.');
    }

    var axes = (0, _lib.getAllAxes)(context.fullLayout).filter(function (a) {
      return a._id;
    });
    if (axes.length > 0) {
      plotProps.options = [{ label: _('Canvas'), value: 'paper' }].concat(_toConsumableArray(computeAxesRefOptions(axes, props.attr)));
    } else {
      plotProps.isVisible = false;
    }

    if (currentOffsetRef !== 'pixel') {
      plotProps.updatePlot = function (v) {
        if (!plotProps.updateContainer) {
          return;
        }

        /*
         * If user is changing axis also change their a[x|y]ref arrow axis
         * reference to match if the value is an axis value.
         * Behaviour copied from plot.ly/create
         */
        var update = _defineProperty({}, props.attr, v);
        if (v !== 'paper') {
          update['a' + props.attr] = v;
        }

        plotProps.updateContainer(update);
      };
    }

    plotProps.clearable = false;
  }
});

var PositioningRef = exports.PositioningRef = (0, _lib.connectToContainer)(_Dropdown.UnconnectedDropdown, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var axes = (0, _lib.getAllAxes)(context.fullLayout).filter(function (a) {
      return a._id;
    });
    if (axes.length > 0) {
      plotProps.options = [{ label: 'Canvas', value: 'paper' }].concat(_toConsumableArray(computeAxesRefOptions(axes, props.attr)));

      plotProps.clearable = false;
    } else {
      plotProps.isVisible = false;
    }
  }
});

var PositioningNumeric = exports.PositioningNumeric = (0, _lib.connectToContainer)(_NumericOrDate.UnconnectedNumericOrDate, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var fullContainer = plotProps.fullContainer,
        fullValue = plotProps.fullValue,
        updatePlot = plotProps.updatePlot;

    if (fullContainer && (fullContainer[props.attr[0] + 'ref'] === 'paper' || fullContainer[props.attr[props.attr.length - 1] + 'ref'] === 'paper')) {
      plotProps.units = '%';
      plotProps.showSlider = true;
      plotProps.max = 100;
      plotProps.min = 0;
      plotProps.step = 1;
      if ((0, _fastIsnumeric2.default)(fullValue)) {
        plotProps.fullValue = Math.round(100 * fullValue);
      }

      plotProps.updatePlot = function (v) {
        if ((0, _fastIsnumeric2.default)(v)) {
          updatePlot(v / 100);
        } else {
          updatePlot(v);
        }
      };
    }
  }
});

function computeAxesRefOptions(axes, propsAttr) {
  var options = [];
  for (var i = 0; i < axes.length; i++) {
    var ax = axes[i];
    if (ax._id.charAt(0) === propsAttr.charAt(0) || ax._id.charAt(0) === propsAttr.charAt(1)) {
      var label = (0, _lib.getAxisTitle)(ax);
      options.push({ label: label, value: ax._id });
    }
  }

  return options;
}

var TextInfo = exports.TextInfo = (0, _lib.connectToContainer)(_Flaglist.UnconnectedFlaglist, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var _ = context.localize,
        container = context.container;

    var options = [{ label: _('Label'), value: 'label' }, { label: _('Value'), value: 'value' }, { label: _('%'), value: 'percent' }];

    if (container.text) {
      options.push({ label: _('Text'), value: 'text' });
    }

    plotProps.options = options;
  }
});

var HoverTemplateSwitch = exports.HoverTemplateSwitch = (0, _lib.connectToContainer)(_Radio.UnconnectedRadio, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var _ = context.localize;


    plotProps.options = [{ label: _('Values'), value: '' }, { label: _('Template'), value: plotProps.fullValue || ' ' }];
    return plotProps;
  }
});

var HoverTemplateText = exports.HoverTemplateText = (0, _lib.connectToContainer)(_TextEditor.UnconnectedTextEditor, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    if (plotProps.isVisible && plotProps.fullValue === '') {
      plotProps.isVisible = false;
    }
    return plotProps;
  }
});

var HoverInfo = exports.HoverInfo = (0, _lib.connectToContainer)(_Flaglist.UnconnectedFlaglist, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var _ = context.localize,
        container = context.container;

    var options = [{ label: _('X'), value: 'x' }, { label: _('Y'), value: 'y' }];

    if (['heatmap', 'heatmapgl', 'histogram2d', 'histogram2dcontour', 'contour', 'contourcarpet', 'scatter3d', 'surface', 'mesh3d'].includes(container.type)) {
      options.push({ label: _('Z'), value: 'z' });
    } else if (container.type === 'choropleth') {
      options = [{ label: _('Location'), value: 'location' }, { label: _('Values'), value: 'z' }];
    } else if (container.type === 'scattergeo') {
      if (container.locations) {
        options = [{ label: _('Location'), value: 'location' }];
      } else if (container.lat || container.lon) {
        options = [{ label: _('Longitude'), value: 'lon' }, { label: _('Latitude'), value: 'lat' }];
      }
    } else if (container.type === 'scattermapbox') {
      options = [{ label: _('Longitude'), value: 'lon' }, { label: _('Latitude'), value: 'lat' }];
    } else if (container.type === 'scatterternary') {
      options = [{ label: _('A'), value: 'a' }, { label: _('B'), value: 'b' }, { label: _('C'), value: 'c' }];
    } else if (['scatterpolar', 'scatterpolargl', 'barpolar'].includes(container.type)) {
      options = [{ label: _('R'), value: 'r' }, { label: _('Theta'), value: 'theta' }];
    } else if (container.type === 'pie') {
      options = [{ label: _('Label'), value: 'label' }, { label: _('Value'), value: 'value' }, { label: _('Percent'), value: 'percent' }];
    } else if (container.type === 'table') {
      plotProps.isVisible = false;
    } else if (['cone', 'streamtube'].includes(container.type)) {
      options = [{ label: _('X'), value: 'x' }, { label: _('Y'), value: 'y' }, { label: _('Z'), value: 'z' }, { label: _('U'), value: 'u' }, { label: _('V'), value: 'v' }, { label: _('W'), value: 'w' }, { label: _('Norm'), value: 'norm' }, { label: _('Divergence'), value: 'divergence' }];
    }

    if (container.text) {
      options.push({ label: _('Text'), value: 'text' });
    }

    options.push({ label: _('Trace name'), value: 'name' });

    plotProps.options = options;
  }
});

var FillDropdown = exports.FillDropdown = (0, _lib.connectToContainer)(_Dropdown.UnconnectedDropdown, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var _ = context.localize;


    var options = [{ label: _('None'), value: 'none' }, { label: _('Y = 0'), value: 'tozeroy' }, { label: _('X = 0'), value: 'tozerox' }, { label: _('Previous Y'), value: 'tonexty' }, { label: _('Previous X'), value: 'tonextx' }];

    if (context.container.type === 'scatterternary' || context.container.type === 'scattercarpet' || context.container.type === 'scatterpolar') {
      options = [{ label: _('None'), value: 'none' }, { label: _('To Self'), value: 'toself' }, { label: _('To Next'), value: 'tonext' }];
    } else if (context.container.type === 'scattergeo' || context.container.type === 'scattermapbox') {
      options = [{ label: _('None'), value: 'none' }, { label: _('To Self'), value: 'toself' }];
    }

    plotProps.options = options;
    plotProps.clearable = false;
  }
});

var HoveronDropdown = exports.HoveronDropdown = (0, _lib.connectToContainer)(_Dropdown.UnconnectedDropdown, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var _ = context.localize;


    var options = void 0;
    if (context.container.type === 'box') {
      options = [{ label: _('Boxes'), value: 'boxes' }, { label: _('Points'), value: 'points' }, { label: _('Boxes and Points'), value: 'boxes+points' }];
    } else if (context.container.type === 'violin') {
      options = [{ label: _('Violins'), value: 'violins' }, { label: _('Points'), value: 'points' }, { label: _('KDE'), value: 'kde' }, { label: _('Violins and Points'), value: 'violins+points' }, { label: _('Violins, Points and KDE'), value: 'violins+points+kde' }];
    } else {
      options = [{ label: _('Points'), value: 'points' }, { label: _('Fills'), value: 'fills' }, { label: _('Points and Fills'), value: 'points+fills' }];
    }

    plotProps.options = options;
    plotProps.clearable = false;
  }
});

var HovermodeDropdown = exports.HovermodeDropdown = (0, _lib.connectToContainer)(_VisibilitySelect.UnconnectedVisibilitySelect, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var _ = context.localize;


    plotProps.options = context.container.xaxis && Object.keys(context.container.xaxis).length > 0 ? [{ label: _('Closest'), value: 'closest' }, { label: _('X Axis'), value: 'x' }, { label: _('Y Axis'), value: 'y' }, { label: _('Disable'), value: false }] : [{ label: _('Closest'), value: 'closest' }, { label: _('Disable'), value: false }];
    plotProps.clearable = false;
    plotProps.dropdown = true;
    plotProps.showOn = ['closest', 'x', 'y'];
  }
});

var HoverColor = exports.HoverColor = (0, _lib.connectToContainer)(_ColorPicker.UnconnectedColorPicker, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    plotProps.isVisible = Boolean(context.fullLayout.hovermode);
    return plotProps;
  }
});
//# sourceMappingURL=derived.js.map

/***/ }),

/***/ "5p9q":
/*!*****************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/cells/style/headerfooter.css ***!
  \*****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n/*-----------------------------------------------------------------------------\n| Header/Footer\n|----------------------------------------------------------------------------*/\n\n/* Hidden by zero height by default */\n.jp-CellHeader,\n.jp-CellFooter {\n  height: 0px;\n  width: 100%;\n  padding: 0px;\n  margin: 0px;\n  border: none;\n  outline: none;\n  background: transparent;\n}\n", ""]);

// exports


/***/ }),

/***/ "5pV8":
/*!******************************************************************!*\
  !*** ./node_modules/@jupyterlab/mathjax2-extension/lib/index.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const rendermime_1 = __webpack_require__(/*! @jupyterlab/rendermime */ "Towz");
const mathjax2_1 = __webpack_require__(/*! @jupyterlab/mathjax2 */ "e3q/");
/**
 * The MathJax latexTypesetter plugin.
 */
const plugin = {
    id: '@jupyterlab/mathjax2-extension:plugin',
    autoStart: true,
    provides: rendermime_1.ILatexTypesetter,
    activate: () => {
        let url = coreutils_1.PageConfig.getOption('mathjaxUrl');
        let config = coreutils_1.PageConfig.getOption('mathjaxConfig');
        return new mathjax2_1.MathJaxTypesetter({ url, config });
    }
};
/**
 * Export the plugin as default.
 */
exports.default = plugin;


/***/ }),

/***/ "5qYI":
/*!**********************************************************************!*\
  !*** ./node_modules/babel-runtime/core-js/number/is-safe-integer.js ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = { "default": __webpack_require__(/*! core-js/library/fn/number/is-safe-integer */ "lA0h"), __esModule: true };

/***/ }),

/***/ "5vMV":
/*!***********************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_object-keys-internal.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var has = __webpack_require__(/*! ./_has */ "B+OT");
var toIObject = __webpack_require__(/*! ./_to-iobject */ "NsO/");
var arrayIndexOf = __webpack_require__(/*! ./_array-includes */ "W070")(false);
var IE_PROTO = __webpack_require__(/*! ./_shared-key */ "VVlx")('IE_PROTO');

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


/***/ }),

/***/ "5vPZ":
/*!***************************************************!*\
  !*** ./node_modules/jupyterlab-dash/lib/index.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const application_1 = __webpack_require__(/*! @jupyterlab/application */ "FkFl");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const notebook_1 = __webpack_require__(/*! @jupyterlab/notebook */ "JOGU");
const console_1 = __webpack_require__(/*! @jupyterlab/console */ "DrOJ");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
__webpack_require__(/*! ../style/index.css */ "LSGn");
class DashIFrameWidget extends widgets_1.Widget {
    /**
     * Construct a new DashIFrameWidget.
     */
    constructor(uid, port) {
        super();
        this.id = uid;
        this.title.label = 'Dash';
        this.title.closable = true;
        this.addClass('jp-dashWidget');
        // Add jp-IFrame class to keep drag events from being lost to the iframe
        // See https://github.com/phosphorjs/phosphor/issues/305
        // See https://github.com/jupyterlab/jupyterlab/blob/master/packages/apputils/style/iframe.css#L17-L35
        this.addClass('jp-IFrame');
        const baseUrl = coreutils_1.PageConfig.getBaseUrl();
        const serviceUrl = `${baseUrl}proxy/${port}`;
        const iframeElement = document.createElement('iframe');
        iframeElement.setAttribute('baseURI', serviceUrl);
        this.iframe = iframeElement;
        this.iframe.src = serviceUrl;
        this.iframe.id = 'iframe-' + this.id;
        this.node.appendChild(this.iframe);
    }
    /**
     * Handle update requests for the widget.
     */
    onUpdateRequest(msg) {
        this.iframe.src += '';
    }
}
/**
 * Activate the xckd widget extension.
 */
function activate(app, restorer, notebooks, consoles) {
    console.log('JupyterLab extension jupyterlab-dash is activated!');
    // Declare a widget variable
    let widgets = new Map();
    // Watch notebook creation
    notebooks.widgetAdded.connect((sender, nbPanel) => {
        console.log('Notebook added!');
        const session = nbPanel.session;
        session.ready.then(() => {
            console.log('Notebook session ready');
            let kernel = session.kernel;
            kernel.ready.then(() => {
                console.log('Notebook kernel ready');
                // Register comm
                registerCommTarget(kernel, widgets, app);
            });
        });
    });
    // Watch console creation
    consoles.widgetAdded.connect((sender, consolePanel) => {
        console.log('Console added!');
        const session = consolePanel.session;
        session.ready.then(() => {
            console.log('Console session ready');
            let kernel = session.kernel;
            kernel.ready.then(() => {
                console.log('Console kernel ready');
                // Register comm
                registerCommTarget(kernel, widgets, app);
            });
        });
    });
}
function registerCommTarget(kernel, widgets, app) {
    kernel.registerCommTarget('dash_viewer', (comm, msg) => {
        console.log('dash_viewer comm opened!');
        comm.onMsg = (msg) => {
            console.log('dash_viewer comm message received');
            console.log(msg);
            let msgData = msg.content.data;
            console.log(msgData.type);
            if (msgData.type === 'show') {
                let widget;
                if (!widgets.has(msgData.uid)) {
                    // Create a new widget
                    console.log('Create new widget');
                    widget = new DashIFrameWidget(msgData.uid, msgData.port);
                    widget.update();
                    widgets.set(msgData.uid, widget);
                    // Add instance tracker stuff
                }
                else {
                    console.log('Found existing widget');
                    widget = widgets.get(msgData.uid);
                }
                if (!widget.isAttached) {
                    // Attach the widget to the main work area
                    // if it's not there
                    console.log('Widget was not attached, adding to main area');
                    app.shell.addToMainArea(widget);
                    widget.update();
                }
                else {
                    // Refresh the widget
                    console.log('Widget already, updating');
                    widget.update();
                }
                // Activate the widget
                app.shell.activateById(widget.id);
            }
            else if (msgData.type === 'url_request') {
                const baseUrl = coreutils_1.PageConfig.getBaseUrl();
                comm.send({ type: 'url_response', url: baseUrl });
            }
        };
    });
}
/**
 * Initialization data for the jupyterlab-dash extension.
 */
const extension = {
    id: 'jupyterlab-dash',
    autoStart: true,
    requires: [application_1.ILayoutRestorer, notebook_1.INotebookTracker, console_1.IConsoleTracker],
    activate: activate
};
exports.default = extension;


/***/ }),

/***/ "5yTg":
/*!****************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/filebrowser/style/index.css ***!
  \****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n/*-----------------------------------------------------------------------------\n| Variables\n|----------------------------------------------------------------------------*/\n\n:root {\n  --jp-private-filebrowser-button-height: 28px;\n  --jp-private-filebrowser-button-width: 48px;\n}\n\n/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.jp-FileBrowser {\n  display: flex;\n  flex-direction: column;\n  color: var(--jp-ui-font-color1);\n  background: var(--jp-layout-color1);\n  /* This is needed so that all font sizing of children done in ems is\n   * relative to this base size */\n  font-size: var(--jp-ui-font-size1);\n}\n\n.jp-FileBrowser-toolbar.jp-Toolbar {\n  border-bottom: none;\n  height: auto;\n  margin: var(--jp-toolbar-header-margin);\n  box-shadow: none;\n}\n\n.jp-BreadCrumbs {\n  flex: 0 0 auto;\n  margin: 4px 12px;\n}\n\n.jp-BreadCrumbs-item {\n  margin: 0px 2px;\n  padding: 0px 2px;\n  border-radius: var(--jp-border-radius);\n  cursor: pointer;\n}\n\n.jp-BreadCrumbs-item:hover {\n  background-color: var(--jp-layout-color2);\n}\n\n.jp-BreadCrumbs-item:first-child {\n  margin-left: 0px;\n}\n\n.jp-BreadCrumbs-item.jp-mod-dropTarget {\n  background-color: var(--jp-brand-color2);\n  opacity: 0.7;\n}\n\n/*-----------------------------------------------------------------------------\n| Buttons\n|----------------------------------------------------------------------------*/\n\n.jp-FileBrowser-toolbar.jp-Toolbar {\n  padding: 0px;\n}\n\n.jp-FileBrowser-toolbar.jp-Toolbar {\n  justify-content: space-evenly;\n}\n\n.jp-FileBrowser-toolbar.jp-Toolbar .jp-ToolbarButtonComponent {\n  padding: 0px 16px;\n}\n\n/*-----------------------------------------------------------------------------\n| DirListing\n|----------------------------------------------------------------------------*/\n\n.jp-DirListing {\n  flex: 1 1 auto;\n  display: flex;\n  flex-direction: column;\n  outline: 0;\n}\n\n.jp-DirListing-header {\n  flex: 0 0 auto;\n  display: flex;\n  flex-direction: row;\n  overflow: hidden;\n  border-top: var(--jp-border-width) solid var(--jp-border-color2);\n  border-bottom: var(--jp-border-width) solid var(--jp-border-color1);\n  box-shadow: var(--jp-toolbar-box-shadow);\n  z-index: 2;\n}\n\n.jp-DirListing-headerItem {\n  padding: 4px 12px;\n  font-weight: 500;\n}\n\n.jp-DirListing-headerItem:hover {\n  background: var(--jp-layout-color2);\n}\n\n.jp-DirListing-headerItem.jp-id-name {\n  flex: 1 0 84px;\n}\n\n.jp-DirListing-headerItem.jp-id-modified {\n  flex: 0 0 112px;\n  border-left: var(--jp-border-width) solid var(--jp-border-color2);\n  text-align: right;\n}\n\n.jp-DirListing-headerItem.jp-mod-selected {\n  font-weight: 600;\n}\n\n.jp-DirListing-headerItemIcon {\n  height: 16px;\n  width: 16px;\n  background-size: 18px;\n  background-image: 18px;\n  background-repeat: no-repeat;\n  background-position: center;\n}\n\n.jp-DirListing-headerItem.jp-mod-selected .jp-DirListing-headerItemIcon {\n  background-image: var(--jp-icon-caretup);\n}\n\n.jp-DirListing-headerItem.jp-mod-selected.jp-mod-descending\n  .jp-DirListing-headerItemIcon {\n  background-image: var(--jp-icon-caretdown);\n}\n\n.jp-DirListing-headerItem.jp-mod-selected.jp-id-name\n  .jp-DirListing-headerItemIcon {\n  float: right;\n}\n\n.jp-DirListing-headerItem.jp-mod-selected.jp-id-modified\n  .jp-DirListing-headerItemIcon {\n  float: left;\n}\n\n/* increase specificity to override bundled default */\n.jp-DirListing-content {\n  flex: 1 1 auto;\n  margin: 0;\n  padding: 0;\n  list-style-type: none;\n  overflow: auto;\n  background-color: var(--jp-layout-color1);\n}\n\n/* Style the directory listing content when a user drops a file to upload */\n.jp-DirListing.jp-mod-native-drop .jp-DirListing-content {\n  outline: 5px dashed rgba(128, 128, 128, 0.5);\n  outline-offset: -10px;\n}\n\n.jp-DirListing-item {\n  display: flex;\n  flex-direction: row;\n  padding: 4px 12px;\n  -webkit-user-select: none;\n  -moz-user-select: none;\n  -ms-user-select: none;\n  user-select: none;\n}\n\n.jp-DirListing-item.jp-mod-selected {\n  color: white;\n  background: var(--jp-brand-color1);\n}\n\n.jp-DirListing-item.jp-mod-dropTarget {\n  background: var(--jp-brand-color3);\n}\n\n.jp-DirListing-item:hover:not(.jp-mod-selected) {\n  background: var(--jp-layout-color2);\n}\n\n.jp-DirListing-itemIcon {\n  flex: 0 0 20px;\n  margin-right: 4px;\n}\n\n.jp-DirListing-itemText {\n  flex: 1 0 64px;\n  white-space: nowrap;\n  overflow: hidden;\n  text-overflow: ellipsis;\n  user-select: none;\n}\n\n.jp-DirListing-itemModified {\n  flex: 0 0 125px;\n  text-align: right;\n}\n\n.jp-DirListing-editor {\n  flex: 1 0 64px;\n  outline: none;\n  border: none;\n}\n\n.jp-DirListing-item.jp-mod-running .jp-DirListing-itemIcon:before {\n  color: limegreen;\n  content: '\\25CF';\n  font-size: 8px;\n  position: relative;\n  width: 100%;\n  height: 100%;\n  top: -2px;\n  left: -8px;\n}\n\n.jp-DirListing-item.jp-mod-selected .jp-DirListing-itemIcon.jp-NotebookIcon {\n  background-image: var(--jp-icon-book-selected);\n}\n\n.jp-DirListing-item.jp-mod-selected .jp-DirListing-itemIcon.jp-OpenFolderIcon {\n  background-image: var(--jp-icon-directory-selected);\n}\n\n.jp-DirListing-item.jp-mod-selected .jp-DirListing-itemIcon.jp-FileIcon {\n  background-image: var(--jp-icon-file-selected);\n}\n\n.jp-DirListing-item.jp-mod-selected .jp-DirListing-itemIcon.jp-YamlIcon {\n  background-image: var(--jp-icon-yaml-selected);\n}\n\n.jp-DirListing-item.jp-mod-selected .jp-DirListing-itemIcon.jp-MarkdownIcon {\n  background-image: var(--jp-icon-markdown-selected);\n}\n\n.jp-DirListing-item.jp-mod-selected .jp-DirListing-itemIcon.jp-ImageIcon {\n  background-image: var(--jp-icon-image-selected);\n}\n\n.jp-DirListing-item.jp-mod-selected .jp-DirListing-itemIcon.jp-SpreadsheetIcon {\n  background-image: var(--jp-icon-spreadsheet-selected);\n}\n\n.jp-DirListing-item.jp-mod-selected .jp-DirListing-itemIcon.jp-JSONIcon {\n  background-image: var(--jp-icon-json-selected);\n}\n\n.jp-DirListing-item.jp-mod-selected .jp-DirListing-itemIcon.jp-PythonIcon {\n  background-image: var(--jp-icon-python-selected);\n}\n\n.jp-DirListing-item.jp-mod-selected .jp-DirListing-itemIcon.jp-RKernelIcon {\n  background-image: var(--jp-icon-r-selected);\n}\n\n.jp-DirListing-item.p-mod-drag-image,\n.jp-DirListing-item.jp-mod-selected.p-mod-drag-image {\n  font-size: var(--jp-ui-font-size1);\n  padding-left: 4px;\n  margin-left: 4px;\n  width: 160px;\n  background-color: var(--jp-ui-inverse-font-color2);\n  box-shadow: var(--jp-elevation-z2);\n  border-radius: 0px;\n  color: var(--jp-ui-font-color1);\n  transform: translateX(-40%) translateY(-58%);\n}\n\n.jp-DirListing-deadSpace {\n  flex: 1 1 auto;\n  margin: 0;\n  padding: 0;\n  list-style-type: none;\n  overflow: auto;\n  background-color: var(--jp-layout-color1);\n}\n\n.jp-Document {\n  min-width: 120px;\n  min-height: 120px;\n  outline: none;\n}\n\n.jp-FileDialog.jp-mod-conflict input {\n  color: red;\n}\n\n.jp-FileDialog .jp-new-name-title {\n  margin-top: 12px;\n}\n", ""]);

// exports


/***/ }),

/***/ "6+QB":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/ms.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var ms = moment.defineLocale('ms', {
    months : 'Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember'.split('_'),
    monthsShort : 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis'.split('_'),
    weekdays : 'Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu'.split('_'),
    weekdaysShort : 'Ahd_Isn_Sel_Rab_Kha_Jum_Sab'.split('_'),
    weekdaysMin : 'Ah_Is_Sl_Rb_Km_Jm_Sb'.split('_'),
    longDateFormat : {
        LT : 'HH.mm',
        LTS : 'HH.mm.ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY [pukul] HH.mm',
        LLLL : 'dddd, D MMMM YYYY [pukul] HH.mm'
    },
    meridiemParse: /pagi|tengahari|petang|malam/,
    meridiemHour: function (hour, meridiem) {
        if (hour === 12) {
            hour = 0;
        }
        if (meridiem === 'pagi') {
            return hour;
        } else if (meridiem === 'tengahari') {
            return hour >= 11 ? hour : hour + 12;
        } else if (meridiem === 'petang' || meridiem === 'malam') {
            return hour + 12;
        }
    },
    meridiem : function (hours, minutes, isLower) {
        if (hours < 11) {
            return 'pagi';
        } else if (hours < 15) {
            return 'tengahari';
        } else if (hours < 19) {
            return 'petang';
        } else {
            return 'malam';
        }
    },
    calendar : {
        sameDay : '[Hari ini pukul] LT',
        nextDay : '[Esok pukul] LT',
        nextWeek : 'dddd [pukul] LT',
        lastDay : '[Kelmarin pukul] LT',
        lastWeek : 'dddd [lepas pukul] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'dalam %s',
        past : '%s yang lepas',
        s : 'beberapa saat',
        ss : '%d saat',
        m : 'seminit',
        mm : '%d minit',
        h : 'sejam',
        hh : '%d jam',
        d : 'sehari',
        dd : '%d hari',
        M : 'sebulan',
        MM : '%d bulan',
        y : 'setahun',
        yy : '%d tahun'
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return ms;

})));


/***/ }),

/***/ "6/1s":
/*!*******************************************************!*\
  !*** ./node_modules/core-js/library/modules/_meta.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var META = __webpack_require__(/*! ./_uid */ "YqAc")('meta');
var isObject = __webpack_require__(/*! ./_is-object */ "93I4");
var has = __webpack_require__(/*! ./_has */ "B+OT");
var setDesc = __webpack_require__(/*! ./_object-dp */ "2faE").f;
var id = 0;
var isExtensible = Object.isExtensible || function () {
  return true;
};
var FREEZE = !__webpack_require__(/*! ./_fails */ "KUxP")(function () {
  return isExtensible(Object.preventExtensions({}));
});
var setMeta = function (it) {
  setDesc(it, META, { value: {
    i: 'O' + ++id, // object ID
    w: {}          // weak collections IDs
  } });
};
var fastKey = function (it, create) {
  // return primitive with prefix
  if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
  if (!has(it, META)) {
    // can't set metadata to uncaught frozen object
    if (!isExtensible(it)) return 'F';
    // not necessary to add metadata
    if (!create) return 'E';
    // add missing metadata
    setMeta(it);
  // return object ID
  } return it[META].i;
};
var getWeak = function (it, create) {
  if (!has(it, META)) {
    // can't set metadata to uncaught frozen object
    if (!isExtensible(it)) return true;
    // not necessary to add metadata
    if (!create) return false;
    // add missing metadata
    setMeta(it);
  // return hash weak collections IDs
  } return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function (it) {
  if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it);
  return it;
};
var meta = module.exports = {
  KEY: META,
  NEED: false,
  fastKey: fastKey,
  getWeak: getWeak,
  onFreeze: onFreeze
};


/***/ }),

/***/ "6/8d":
/*!********************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/codemirror/theme/the-matrix.css ***!
  \********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, ".cm-s-the-matrix.CodeMirror { background: #000000; color: #00FF00; }\n.cm-s-the-matrix div.CodeMirror-selected { background: #2D2D2D; }\n.cm-s-the-matrix .CodeMirror-line::selection, .cm-s-the-matrix .CodeMirror-line > span::selection, .cm-s-the-matrix .CodeMirror-line > span > span::selection { background: rgba(45, 45, 45, 0.99); }\n.cm-s-the-matrix .CodeMirror-line::-moz-selection, .cm-s-the-matrix .CodeMirror-line > span::-moz-selection, .cm-s-the-matrix .CodeMirror-line > span > span::-moz-selection { background: rgba(45, 45, 45, 0.99); }\n.cm-s-the-matrix .CodeMirror-gutters { background: #060; border-right: 2px solid #00FF00; }\n.cm-s-the-matrix .CodeMirror-guttermarker { color: #0f0; }\n.cm-s-the-matrix .CodeMirror-guttermarker-subtle { color: white; }\n.cm-s-the-matrix .CodeMirror-linenumber { color: #FFFFFF; }\n.cm-s-the-matrix .CodeMirror-cursor { border-left: 1px solid #00FF00; }\n\n.cm-s-the-matrix span.cm-keyword { color: #008803; font-weight: bold; }\n.cm-s-the-matrix span.cm-atom { color: #3FF; }\n.cm-s-the-matrix span.cm-number { color: #FFB94F; }\n.cm-s-the-matrix span.cm-def { color: #99C; }\n.cm-s-the-matrix span.cm-variable { color: #F6C; }\n.cm-s-the-matrix span.cm-variable-2 { color: #C6F; }\n.cm-s-the-matrix span.cm-variable-3, .cm-s-the-matrix span.cm-type { color: #96F; }\n.cm-s-the-matrix span.cm-property { color: #62FFA0; }\n.cm-s-the-matrix span.cm-operator { color: #999; }\n.cm-s-the-matrix span.cm-comment { color: #CCCCCC; }\n.cm-s-the-matrix span.cm-string { color: #39C; }\n.cm-s-the-matrix span.cm-meta { color: #C9F; }\n.cm-s-the-matrix span.cm-qualifier { color: #FFF700; }\n.cm-s-the-matrix span.cm-builtin { color: #30a; }\n.cm-s-the-matrix span.cm-bracket { color: #cc7; }\n.cm-s-the-matrix span.cm-tag { color: #FFBD40; }\n.cm-s-the-matrix span.cm-attribute { color: #FFF700; }\n.cm-s-the-matrix span.cm-error { color: #FF0000; }\n\n.cm-s-the-matrix .CodeMirror-activeline-background { background: #040; }\n", ""]);

// exports


/***/ }),

/***/ "6805":
/*!*********************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/extensionmanager/style/index.css ***!
  \*********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*\n  Main widget layout and styling\n*/\n\n.jp-extensionmanager-view {\n  padding-bottom: 0px;\n  color: var(--jp-ui-font-color1);\n  background: var(--jp-layout-color1);\n  display: flex;\n  flex-direction: column;\n  font-size: var(--jp-ui-font-size1);\n}\n\n.jp-extensionmanager-content {\n  overflow: auto;\n}\n\n/*\n  List view layout and styling\n*/\n\n.jp-extensionmanager-listview-wrapper {\n  margin: 0;\n  padding: 0;\n  padding-bottom: 5px;\n  display: flex;\n  flex-direction: column;\n  flex: 0 0 auto;\n}\n\n.jp-extensionmanager-listview {\n  list-style-type: none;\n  margin: 0;\n  padding: 0;\n  min-height: 0;\n}\n\n/*\n  Section headers\n*/\n\n.jp-extensionmanager-view header {\n  display: flex;\n  justify-content: space-between;\n  flex: 0 0 auto;\n  margin: 0px;\n  padding: 8px 12px;\n  font-weight: 600;\n  text-transform: uppercase;\n  border-bottom: var(--jp-border-width) solid var(--jp-border-color2);\n  letter-spacing: 1px;\n  font-size: var(--jp-ui-font-size0);\n  line-height: 24px;\n  height: 24px;\n}\n\n.jp-extensionmanager-view header > .jp-ToolbarButtonComponent {\n  padding: 0px 4px;\n}\n\n.jp-extensionmanager-view header .jp-extensionmanager-headerText {\n  flex: 1 0 auto;\n  margin: 0px 2px;\n}\n\n.jp-extensionmanager-view header > .jp-ToolbarButtonComponent {\n  border: 1px solid transparent;\n  background-color: var(--jp-layout-color1);\n  color: var(--jp-ui-font-color1);\n}\n\n.jp-extensionmanager-view header > .jp-ToolbarButtonComponent:hover {\n  border: 1px solid var(--jp-brand-color1);\n}\n\n/*\n  Error messages\n*/\n.jp-extensionmanager-view .jp-extensionmanager-error pre {\n  white-space: pre-wrap;\n}\n\n/*\n  Search bar layout and styling\n*/\n\n.jp-extensionmanager-search-bar {\n  padding: 8px 8px 0px 8px;\n  background-color: var(--jp-layout-color1);\n  z-index: 2;\n  flex: 0 0 auto;\n}\n\n.jp-extensionmanager-input {\n  background: transparent;\n  width: calc(100% - 18px);\n  float: left;\n  border: none;\n  outline: none;\n  font-size: var(--jp-ui-font-size1);\n  color: var(--jp-ui-font-color0);\n  line-height: var(--jp-private-commandpalette-search-height);\n}\n\n.jp-extensionmanager-search-wrapper {\n  overflow: overlay;\n  padding: 0px 8px;\n  border: 1px solid var(--jp-border-color0);\n  background-color: var(--jp-input-active-background);\n  height: 30px;\n}\n\n.jp-extensionmanager-search-wrapper::after {\n  content: ' ';\n  color: var(--jp-ui-inverse-font-color1);\n  background-color: var(--jp-brand-color1);\n  position: absolute;\n  top: 8px;\n  right: 8px;\n  height: 32px;\n  width: 12px;\n  padding: 0px 12px;\n  background-image: var(--jp-icon-search-white);\n  background-size: 20px;\n  background-repeat: no-repeat;\n  background-position: center;\n}\n\n.jp-extensionmanager-view.p-mod-focused .jp-extensionmanager-search-wrapper {\n  border: var(--jp-border-width) solid var(--jp-brand-color1);\n  box-shadow: inset 0 0 4px var(--jp-brand-color2);\n}\n\n/*\n  List view pagination styling\n*/\n\n.jp-extensionmanager-view ul.pagination {\n  display: inline-block;\n  padding-left: 0px;\n  padding-right: 0px;\n}\n\n.jp-extensionmanager-view .pagination li {\n  display: inline-block;\n}\n\n.jp-extensionmanager-view .pagination .break a {\n  cursor: default;\n}\n\n.jp-extensionmanager-pagination {\n  display: flex;\n  justify-content: center;\n}\n\n/*\n  Entry buttons visibility\n*/\n\n.jp-extensionmanager-entry .jp-extensionmanager-install,\n.jp-extensionmanager-entry.jp-extensionmanager-entry-update\n  .jp-extensionmanager-update,\n.jp-extensionmanager-entry.jp-extensionmanager-entry-installed\n  .jp-extensionmanager-uninstall {\n  display: inline-block;\n}\n\n.jp-extensionmanager-entry .jp-extensionmanager-update,\n.jp-extensionmanager-entry .jp-extensionmanager-uninstall,\n.jp-extensionmanager-entry.jp-extensionmanager-entry-installed\n  .jp-extensionmanager-install {\n  display: none;\n}\n\n.jp-extensionmanager-entry .jp-extensionmanager-enable,\n.jp-extensionmanager-entry .jp-extensionmanager-disable,\n.jp-extensionmanager-entry.jp-extensionmanager-entry-installed.jp-extensionmanager-entry-enabled\n  .jp-extensionmanager-enable {\n  display: none;\n}\n\n.jp-extensionmanager-entry.jp-extensionmanager-entry-installed\n  .jp-extensionmanager-enable,\n.jp-extensionmanager-entry.jp-extensionmanager-entry-installed.jp-extensionmanager-entry-enabled\n  .jp-extensionmanager-disable {\n  display: inline-block;\n}\n\n/*\n  Entry layout and styling\n*/\n\n.jp-extensionmanager-entry {\n  padding: 4px 12px;\n  border-bottom: solid var(--jp-border-width) var(--jp-border-color2);\n}\n\n.jp-extensionmanager-entry-title {\n  display: flex;\n  flex-direction: row;\n}\n\n.jp-extensionmanager-entry-jupyter-org {\n  background-image: var(--jp-image-jupyter);\n  background-size: 1em;\n  background-repeat: no-repeat;\n  width: 1em;\n  display: none;\n  position: relative;\n  top: 1px;\n}\n\n.jp-extensionmanager-entry.jp-extensionmanager-entry-mod-whitelisted\n  .jp-extensionmanager-entry-jupyter-org {\n  display: inline;\n}\n\n/* Precedence order update/error/warning matters! */\n.jp-extensionmanager-entry.jp-extensionmanager-entry-update {\n  border-left: solid 8px var(--jp-brand-color2);\n  padding-left: 4px;\n}\n\n.jp-extensionmanager-entry.jp-extensionmanager-entry-error {\n  border-left: solid 8px var(--jp-error-color2);\n  padding-left: 4px;\n}\n\n.jp-extensionmanager-entry.jp-extensionmanager-entry-warning {\n}\n\n.jp-extensionmanager-entry-name {\n  font-size: var(--jp-ui-font-size1);\n  font-weight: 600;\n  padding: 0 8px 0 0;\n  margin-bottom: 4px;\n}\n\n.jp-extensionmanager-entry-name a:link {\n  color: var(--jp-content-link-color);\n  text-decoration: none;\n}\n\n.jp-extensionmanager-entry-name a:visited {\n  color: var(--jp-content-link-color);\n  text-decoration: none;\n}\n\n.jp-extensionmanager-entry-name a:hover {\n  color: var(--jp-content-link-color);\n  text-decoration: underline;\n}\n\n.jp-extensionmanager-entry-description {\n  font-size: var(--jp-ui-font-size1);\n  color: var(--jp-ui-font-color2);\n  font-weight: 400;\n}\n\n.jp-extensionmanager-loader,\n.jp-extensionmanager-error,\n.jp-extensionmanager-listview-message {\n  padding: 4px 12px;\n}\n\n.jp-extensionmanager-listview-message {\n  font-size: var(--jp-ui-font-size1);\n}\n\n.jp-extensionmanager-entry-content {\n  display: flex;\n  flex-direction: row;\n  justify-content: space-between;\n}\n\n/*\n  Pending entry progress indicator\n*/\n\n.jp-extensionmanager-pending {\n  height: 4px;\n  width: 100%;\n  position: relative;\n  overflow: hidden;\n  flex: 0 0 auto;\n  background-color: var(--jp-layout-color1);\n}\n\n.jp-extensionmanager-pending.jp-mod-hasPending:before {\n  display: block;\n  position: absolute;\n  content: '';\n  left: -200px;\n  width: 200px;\n  height: 4px;\n  border-radius: 5px;\n  background-color: var(--jp-brand-color1);\n  animation: loading 2s linear infinite;\n}\n\n@keyframes loading {\n  from {\n    left: -200px;\n    width: 30%;\n  }\n  50% {\n    width: 30%;\n  }\n  70% {\n    width: 70%;\n  }\n  80% {\n    left: 50%;\n  }\n  95% {\n    left: 120%;\n  }\n  to {\n    left: 100%;\n  }\n}\n\n/*\n  Entry buttons layout and styling\n*/\n\n.jp-extensionmanager-entry-buttons {\n  display: flex;\n  flex-direction: column;\n}\n\n.jp-extensionmanager-entry button {\n  border: solid var(--jp-border-width) var(--jp-border-color2);\n  font-size: var(--jp-ui-font-size0);\n  margin-top: 1px;\n  margin-bottom: 1px;\n  margin-right: 0px;\n  margin-left: 3px;\n  color: var(--jp-ui-font-color1);\n  background-color: var(--jp-layout-color2);\n}\n\n.jp-extensionmanager-entry button.jp-extensionmanager-uninstall:hover {\n  background-color: var(--jp-error-color2);\n}\n\n.jp-extensionmanager-entry button.jp-extensionmanager-disable:hover {\n  background-color: var(--jp-error-color3);\n}\n\n.jp-extensionmanager-entry button.jp-extensionmanager-install:hover {\n  background-color: var(--jp-success-color2);\n}\n\n.jp-extensionmanager-entry button.jp-extensionmanager-enable:hover {\n  background-color: var(--jp-success-color3);\n}\n\n.jp-extensionmanager-entry button.jp-extensionmanager-update:hover {\n  background-color: var(--jp-brand-color3);\n}\n\n/*\n  Rebuild prompt dialog\n*/\n\n.jp-extensionmanager-buildprompt {\n  background-color: var(--jp-brand-color1);\n  color: var(--jp-ui-inverse-font-color1);\n  padding: 4px 8px;\n  font-size: var(--jp-ui-font-size1);\n  font-weight: 400;\n}\n\n.jp-extensionmanager-buildprompt button {\n  border: none;\n  background-color: transparent;\n  color: var(--jp-ui-inverse-font-color1);\n  font-size: var(--jp-ui-font-size1);\n  font-weight: 600;\n  float: right;\n  margin: 3px;\n}\n\n/*\n  Companion packages dialog\n*/\n\ninput[type='checkbox'] {\n  appearance: checkbox;\n  -webkit-appearance: checkbox;\n  -moz-appearance: checkbox;\n  height: auto;\n}\n\n/*\n  Generic dialog\n*/\n.jp-extensionmanager-dialog .jp-extensionmanager-dialog-subheader {\n  font-size: var(--jp-ui-font-size1);\n  font-weight: 600;\n  color: var(--jp-ui-font-color0);\n}\n\n.jp-extensionmanager-collapseIcon {\n  background-image: var(--jp-image-caretright);\n}\n\n.jp-extensionmanager-expandIcon {\n  background-image: var(--jp-image-caretdown);\n}\n", ""]);

// exports


/***/ }),

/***/ "6AZA":
/*!***********************************************************!*\
  !*** ./node_modules/plotly.js/src/constants/numerical.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




module.exports = {
    /**
     * Standardize all missing data in calcdata to use undefined
     * never null or NaN.
     * That way we can use !==undefined, or !== BADNUM,
     * to test for real data
     */
    BADNUM: undefined,

    /*
     * Limit certain operations to well below floating point max value
     * to avoid glitches: Make sure that even when you multiply it by the
     * number of pixels on a giant screen it still works
     */
    FP_SAFE: Number.MAX_VALUE / 10000,

    /*
     * conversion of date units to milliseconds
     * year and month constants are marked "AVG"
     * to remind us that not all years and months
     * have the same length
     */
    ONEAVGYEAR: 31557600000, // 365.25 days
    ONEAVGMONTH: 2629800000, // 1/12 of ONEAVGYEAR
    ONEDAY: 86400000,
    ONEHOUR: 3600000,
    ONEMIN: 60000,
    ONESEC: 1000,

    /*
     * For fast conversion btwn world calendars and epoch ms, the Julian Day Number
     * of the unix epoch. From calendars.instance().newDate(1970, 1, 1).toJD()
     */
    EPOCHJD: 2440587.5,

    /*
     * Are two values nearly equal? Compare to 1PPM
     */
    ALMOST_EQUAL: 1 - 1e-6,

    /*
     * If we're asked to clip a non-positive log value, how far off-screen
     * do we put it?
     */
    LOG_CLIP: 10,

    /*
     * not a number, but for displaying numbers: the "minus sign" symbol is
     * wider than the regular ascii dash "-"
     */
    MINUS_SIGN: '\u2212'
};


/***/ }),

/***/ "6B0Y":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/km.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var km = moment.defineLocale('km', {
    months: 'មករា_កុម្ភៈ_មីនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ'.split('_'),
    monthsShort: 'មករា_កុម្ភៈ_មីនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ'.split('_'),
    weekdays: 'អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍'.split('_'),
    weekdaysShort: 'អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍'.split('_'),
    weekdaysMin: 'អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍'.split('_'),
    longDateFormat: {
        LT: 'HH:mm',
        LTS : 'HH:mm:ss',
        L: 'DD/MM/YYYY',
        LL: 'D MMMM YYYY',
        LLL: 'D MMMM YYYY HH:mm',
        LLLL: 'dddd, D MMMM YYYY HH:mm'
    },
    calendar: {
        sameDay: '[ថ្ងៃនេះ ម៉ោង] LT',
        nextDay: '[ស្អែក ម៉ោង] LT',
        nextWeek: 'dddd [ម៉ោង] LT',
        lastDay: '[ម្សិលមិញ ម៉ោង] LT',
        lastWeek: 'dddd [សប្តាហ៍មុន] [ម៉ោង] LT',
        sameElse: 'L'
    },
    relativeTime: {
        future: '%sទៀត',
        past: '%sមុន',
        s: 'ប៉ុន្មានវិនាទី',
        ss: '%d វិនាទី',
        m: 'មួយនាទី',
        mm: '%d នាទី',
        h: 'មួយម៉ោង',
        hh: '%d ម៉ោង',
        d: 'មួយថ្ងៃ',
        dd: '%d ថ្ងៃ',
        M: 'មួយខែ',
        MM: '%d ខែ',
        y: 'មួយឆ្នាំ',
        yy: '%d ឆ្នាំ'
    },
    week: {
        dow: 1, // Monday is the first day of the week.
        doy: 4 // The week that contains Jan 4th is the first week of the year.
    }
});

return km;

})));


/***/ }),

/***/ "6C2Z":
/*!********************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/application/style/scrollbar.css ***!
  \********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.p-ScrollBar[data-orientation='horizontal'] {\n  min-height: 16px;\n  max-height: 16px;\n  min-width: 45px;\n  border-top: 1px solid #a0a0a0;\n}\n\n.p-ScrollBar[data-orientation='vertical'] {\n  min-width: 16px;\n  max-width: 16px;\n  min-height: 45px;\n  border-left: 1px solid #a0a0a0;\n}\n\n.p-ScrollBar-button {\n  background-color: #f0f0f0;\n  background-position: center center;\n  min-height: 15px;\n  max-height: 15px;\n  min-width: 15px;\n  max-width: 15px;\n}\n\n.p-ScrollBar-button:hover {\n  background-color: #dadada;\n}\n\n.p-ScrollBar-button.p-mod-active {\n  background-color: #cdcdcd;\n}\n\n.p-ScrollBar-track {\n  background: #f0f0f0;\n}\n\n.p-ScrollBar-thumb {\n  background: #cdcdcd;\n}\n\n.p-ScrollBar-thumb:hover {\n  background: #bababa;\n}\n\n.p-ScrollBar-thumb.p-mod-active {\n  background: #a0a0a0;\n}\n\n.p-ScrollBar[data-orientation='horizontal'] .p-ScrollBar-thumb {\n  height: 100%;\n  min-width: 15px;\n  border-left: 1px solid #a0a0a0;\n  border-right: 1px solid #a0a0a0;\n}\n\n.p-ScrollBar[data-orientation='vertical'] .p-ScrollBar-thumb {\n  width: 100%;\n  min-height: 15px;\n  border-top: 1px solid #a0a0a0;\n  border-bottom: 1px solid #a0a0a0;\n}\n\n.p-ScrollBar[data-orientation='horizontal']\n  .p-ScrollBar-button[data-action='decrement'] {\n  background-image: var(--jp-image-caretleft);\n}\n\n.p-ScrollBar[data-orientation='horizontal']\n  .p-ScrollBar-button[data-action='increment'] {\n  background-image: var(--jp-image-caretright);\n}\n\n.p-ScrollBar[data-orientation='vertical']\n  .p-ScrollBar-button[data-action='decrement'] {\n  background-image: var(--jp-image-caretup);\n}\n\n.p-ScrollBar[data-orientation='vertical']\n  .p-ScrollBar-button[data-action='increment'] {\n  background-image: var(--jp-image-caretdown);\n}\n", ""]);

// exports


/***/ }),

/***/ "6F8h":
/*!*****************************************************!*\
  !*** ./node_modules/browserify-aes/modes/list.json ***!
  \*****************************************************/
/*! exports provided: aes-128-ecb, aes-192-ecb, aes-256-ecb, aes-128-cbc, aes-192-cbc, aes-256-cbc, aes128, aes192, aes256, aes-128-cfb, aes-192-cfb, aes-256-cfb, aes-128-cfb8, aes-192-cfb8, aes-256-cfb8, aes-128-cfb1, aes-192-cfb1, aes-256-cfb1, aes-128-ofb, aes-192-ofb, aes-256-ofb, aes-128-ctr, aes-192-ctr, aes-256-ctr, aes-128-gcm, aes-192-gcm, aes-256-gcm, default */
/***/ (function(module) {

module.exports = {"aes-128-ecb":{"cipher":"AES","key":128,"iv":0,"mode":"ECB","type":"block"},"aes-192-ecb":{"cipher":"AES","key":192,"iv":0,"mode":"ECB","type":"block"},"aes-256-ecb":{"cipher":"AES","key":256,"iv":0,"mode":"ECB","type":"block"},"aes-128-cbc":{"cipher":"AES","key":128,"iv":16,"mode":"CBC","type":"block"},"aes-192-cbc":{"cipher":"AES","key":192,"iv":16,"mode":"CBC","type":"block"},"aes-256-cbc":{"cipher":"AES","key":256,"iv":16,"mode":"CBC","type":"block"},"aes128":{"cipher":"AES","key":128,"iv":16,"mode":"CBC","type":"block"},"aes192":{"cipher":"AES","key":192,"iv":16,"mode":"CBC","type":"block"},"aes256":{"cipher":"AES","key":256,"iv":16,"mode":"CBC","type":"block"},"aes-128-cfb":{"cipher":"AES","key":128,"iv":16,"mode":"CFB","type":"stream"},"aes-192-cfb":{"cipher":"AES","key":192,"iv":16,"mode":"CFB","type":"stream"},"aes-256-cfb":{"cipher":"AES","key":256,"iv":16,"mode":"CFB","type":"stream"},"aes-128-cfb8":{"cipher":"AES","key":128,"iv":16,"mode":"CFB8","type":"stream"},"aes-192-cfb8":{"cipher":"AES","key":192,"iv":16,"mode":"CFB8","type":"stream"},"aes-256-cfb8":{"cipher":"AES","key":256,"iv":16,"mode":"CFB8","type":"stream"},"aes-128-cfb1":{"cipher":"AES","key":128,"iv":16,"mode":"CFB1","type":"stream"},"aes-192-cfb1":{"cipher":"AES","key":192,"iv":16,"mode":"CFB1","type":"stream"},"aes-256-cfb1":{"cipher":"AES","key":256,"iv":16,"mode":"CFB1","type":"stream"},"aes-128-ofb":{"cipher":"AES","key":128,"iv":16,"mode":"OFB","type":"stream"},"aes-192-ofb":{"cipher":"AES","key":192,"iv":16,"mode":"OFB","type":"stream"},"aes-256-ofb":{"cipher":"AES","key":256,"iv":16,"mode":"OFB","type":"stream"},"aes-128-ctr":{"cipher":"AES","key":128,"iv":16,"mode":"CTR","type":"stream"},"aes-192-ctr":{"cipher":"AES","key":192,"iv":16,"mode":"CTR","type":"stream"},"aes-256-ctr":{"cipher":"AES","key":256,"iv":16,"mode":"CTR","type":"stream"},"aes-128-gcm":{"cipher":"AES","key":128,"iv":12,"mode":"GCM","type":"auth"},"aes-192-gcm":{"cipher":"AES","key":192,"iv":12,"mode":"GCM","type":"auth"},"aes-256-gcm":{"cipher":"AES","key":256,"iv":12,"mode":"GCM","type":"auth"}};

/***/ }),

/***/ "6HQ/":
/*!****************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/TextArea.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var TextArea = function (_Component) {
  _inherits(TextArea, _Component);

  function TextArea(props) {
    _classCallCheck(this, TextArea);

    var _this = _possibleConstructorReturn(this, (TextArea.__proto__ || Object.getPrototypeOf(TextArea)).call(this, props));

    _this.state = {
      value: _this.props.value
    };

    _this.onChange = _this.onChange.bind(_this);
    return _this;
  }

  _createClass(TextArea, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      // Reset the value to the graph's actual value
      if (nextProps.value !== this.state.value) {
        this.setState({
          value: nextProps.value
        });
      }
    }
  }, {
    key: 'onChange',
    value: function onChange(e) {
      var newValue = e.target.value;
      this.setState({ value: newValue });
      this.props.onChange(newValue);
    }
  }, {
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        'span',
        null,
        _react2.default.createElement('textarea', {
          value: this.state.value,
          rows: this.props.visibleRows,
          cols: this.props.areaWidth,
          placeholder: this.props.placeholder,
          onChange: this.onChange,
          className: this.props.textareaClass
        })
      );
    }
  }]);

  return TextArea;
}(_react.Component);

exports.default = TextArea;


TextArea.propTypes = {
  value: _propTypes2.default.string.isRequired,
  onChange: _propTypes2.default.func.isRequired,
  placeholder: _propTypes2.default.string.isRequired,
  visibleRows: _propTypes2.default.number,
  areaWidth: _propTypes2.default.number,
  textareaClass: _propTypes2.default.string
};

TextArea.defaultProps = {
  visibleRows: 10,
  areaWidth: 30
};
//# sourceMappingURL=TextArea.js.map

/***/ }),

/***/ "6KKe":
/*!********************************************************!*\
  !*** ./node_modules/@jupyterlab/coreutils/lib/text.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * The namespace for text-related functions.
 */
var Text;
(function (Text) {
    // javascript stores text as utf16 and string indices use "code units",
    // which stores high-codepoint characters as "surrogate pairs",
    // which occupy two indices in the javascript string.
    // We need to translate cursor_pos in the Jupyter protocol (in characters)
    // to js offset (with surrogate pairs taking two spots).
    const HAS_SURROGATES = '𝐚'.length > 1;
    /**
     * Convert a javascript string index into a unicode character offset
     *
     * @param jsIdx - The javascript string index (counting surrogate pairs)
     *
     * @param text - The text in which the offset is calculated
     *
     * @returns The unicode character offset
     */
    function jsIndexToCharIndex(jsIdx, text) {
        if (HAS_SURROGATES) {
            // not using surrogates, nothing to do
            return jsIdx;
        }
        let charIdx = jsIdx;
        for (let i = 0; i + 1 < text.length && i < jsIdx; i++) {
            let charCode = text.charCodeAt(i);
            // check for surrogate pair
            if (charCode >= 0xd800 && charCode <= 0xdbff) {
                let nextCharCode = text.charCodeAt(i + 1);
                if (nextCharCode >= 0xdc00 && nextCharCode <= 0xdfff) {
                    charIdx--;
                    i++;
                }
            }
        }
        return charIdx;
    }
    Text.jsIndexToCharIndex = jsIndexToCharIndex;
    /**
     * Convert a unicode character offset to a javascript string index.
     *
     * @param charIdx - The index in unicode characters
     *
     * @param text - The text in which the offset is calculated
     *
     * @returns The js-native index
     */
    function charIndexToJsIndex(charIdx, text) {
        if (HAS_SURROGATES) {
            // not using surrogates, nothing to do
            return charIdx;
        }
        let jsIdx = charIdx;
        for (let i = 0; i + 1 < text.length && i < jsIdx; i++) {
            let charCode = text.charCodeAt(i);
            // check for surrogate pair
            if (charCode >= 0xd800 && charCode <= 0xdbff) {
                let nextCharCode = text.charCodeAt(i + 1);
                if (nextCharCode >= 0xdc00 && nextCharCode <= 0xdfff) {
                    jsIdx++;
                    i++;
                }
            }
        }
        return jsIdx;
    }
    Text.charIndexToJsIndex = charIndexToJsIndex;
})(Text = exports.Text || (exports.Text = {}));


/***/ }),

/***/ "6LUF":
/*!********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/default_panels/StyleLayoutPanel.js ***!
  \********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _components = __webpack_require__(/*! ../components */ "yF51");

var _derived = __webpack_require__(/*! ../components/fields/derived */ "5og8");

var _DataSelector = __webpack_require__(/*! ../components/fields/DataSelector */ "dv5i");

var _DataSelector2 = _interopRequireDefault(_DataSelector);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var StyleLayoutPanel = function StyleLayoutPanel(props, _ref) {
  var _ = _ref.localize;
  return _react2.default.createElement(
    _components.LayoutPanel,
    null,
    _react2.default.createElement(
      _components.PlotlyFold,
      { name: _('Defaults') },
      _react2.default.createElement(_components.ColorPicker, { label: _('Plot Background'), attr: 'plot_bgcolor' }),
      _react2.default.createElement(_components.ColorPicker, { label: _('Margin Color'), attr: 'paper_bgcolor' }),
      _react2.default.createElement(
        _components.PlotlySection,
        { name: _('Colorscales'), attr: 'colorway' },
        _react2.default.createElement(_components.ColorwayPicker, {
          label: _('Categorical'),
          attr: 'colorway',
          disableCategorySwitch: true,
          labelWidth: 80
        }),
        _react2.default.createElement(_components.ColorscalePicker, {
          label: _('Sequential'),
          attr: 'colorscale.sequential',
          disableCategorySwitch: true,
          labelWidth: 80
        }),
        _react2.default.createElement(_components.ColorscalePicker, {
          label: _('Diverging'),
          attr: 'colorscale.diverging',
          initialCategory: 'divergent',
          disableCategorySwitch: true,
          labelWidth: 80
        }),
        _react2.default.createElement(_components.ColorscalePicker, {
          label: _('Negative Sequential'),
          attr: 'colorscale.sequentialminus',
          disableCategorySwitch: true,
          labelWidth: 80
        })
      ),
      _react2.default.createElement(
        _components.PlotlySection,
        { name: _('Text'), attr: 'font.family' },
        _react2.default.createElement(_components.FontSelector, { label: _('Typeface'), attr: 'font.family', clearable: false }),
        _react2.default.createElement(_components.Numeric, { label: _('Font Size'), attr: 'font.size', units: 'px' }),
        _react2.default.createElement(_components.ColorPicker, { label: _('Font Color'), attr: 'font.color' }),
        _react2.default.createElement(_components.Dropdown, {
          label: _('Number format'),
          attr: 'separators',
          options: [{ label: _('1,234.56'), value: '.,' }, { label: _('1 234.56'), value: ', ' }, { label: _('1 234,56'), value: ', ' }, { label: _('1.234,56'), value: ',.' }],
          clearable: false
        })
      )
    ),
    _react2.default.createElement(
      _components.PlotlyFold,
      { name: _('Title') },
      _react2.default.createElement(_components.TextEditor, { attr: 'title.text' }),
      _react2.default.createElement(_components.FontSelector, { label: _('Typeface'), attr: 'title.font.family', clearable: false }),
      _react2.default.createElement(_components.Numeric, { label: _('Font Size'), attr: 'title.font.size', units: 'px' }),
      _react2.default.createElement(_components.ColorPicker, { label: _('Font Color'), attr: 'title.font.color' }),
      _react2.default.createElement(_components.Numeric, { label: _('Horizontal Position'), showSlider: true, step: 0.02, attr: 'title.x' })
    ),
    _react2.default.createElement(
      _components.PlotlyFold,
      { name: _('Modebar') },
      _react2.default.createElement(_components.Radio, {
        label: _('Orientation'),
        attr: 'modebar.orientation',
        options: [{ label: _('Horizontal'), value: 'h' }, { label: _('Vertical'), value: 'v' }]
      }),
      _react2.default.createElement(_components.ColorPicker, { label: _('Icon Color'), attr: 'modebar.color' }),
      _react2.default.createElement(_components.ColorPicker, { label: _('Active Icon Color'), attr: 'modebar.activecolor' }),
      _react2.default.createElement(_components.ColorPicker, { label: _('Background Color'), attr: 'modebar.bgcolor' })
    ),
    _react2.default.createElement(
      _components.PlotlyFold,
      { name: _('Size and Margins') },
      _react2.default.createElement(
        _components.VisibilitySelect,
        {
          attr: 'autosize',
          label: _('Size'),
          options: [{ label: _('Auto'), value: true }, { label: _('Custom'), value: false }],
          showOn: false,
          defaultOpt: true
        },
        _react2.default.createElement(_components.Numeric, { label: _('Fixed Width'), attr: 'width', units: 'px' }),
        _react2.default.createElement(_components.Numeric, { label: _('Fixed height'), attr: 'height', units: 'px' })
      ),
      _react2.default.createElement(_components.Numeric, { label: _('Top'), attr: 'margin.t', units: 'px' }),
      _react2.default.createElement(_components.Numeric, { label: _('Bottom'), attr: 'margin.b', units: 'px' }),
      _react2.default.createElement(_components.Numeric, { label: _('Left'), attr: 'margin.l', units: 'px' }),
      _react2.default.createElement(_components.Numeric, { label: _('Right'), attr: 'margin.r', units: 'px' }),
      _react2.default.createElement(_components.Numeric, { label: _('Padding'), attr: 'margin.pad', units: 'px' })
    ),
    _react2.default.createElement(
      _components.PlotlyFold,
      { name: _('Interactions') },
      _react2.default.createElement(
        _components.PlotlySection,
        { name: _('Drag'), attr: 'dragmode' },
        _react2.default.createElement(_components.Dropdown, {
          label: _('Mode'),
          attr: 'dragmode',
          options: [{ label: _('Zoom'), value: 'zoom' }, { label: _('Select'), value: 'select' }, { label: _('Pan'), value: 'pan' }, { label: _('Lasso'), value: 'lasso' }, { label: _('Orbit'), value: 'orbit' }, { label: _('Turntable'), value: 'turntable' }],
          clearable: false
        }),
        _react2.default.createElement(_components.Dropdown, {
          label: _('Select Direction'),
          attr: 'selectdirection',
          options: [{ label: _('Any'), value: 'any' }, { label: _('Horizontal'), value: 'h' }, { label: _('Vertical'), value: 'v' }, { label: _('Diagonal'), value: 'd' }],
          clearable: false
        })
      ),
      _react2.default.createElement(
        _components.PlotlySection,
        { name: _('Click'), attr: 'clickmode' },
        _react2.default.createElement(_components.Flaglist, {
          label: _('Mode'),
          attr: 'clickmode',
          options: [{ label: _('Click Event'), value: 'event' }, { label: _('Select Data Point'), value: 'select' }]
        })
      ),
      _react2.default.createElement(
        _components.PlotlySection,
        { name: _('Hover') },
        _react2.default.createElement(
          _components.HovermodeDropdown,
          { label: _('Mode'), attr: 'hovermode' },
          _react2.default.createElement(_derived.HoverColor, {
            label: _('Background Color'),
            attr: 'hoverlabel.bgcolor',
            defaultColor: '#FFF',
            handleEmpty: true
          }),
          _react2.default.createElement(_derived.HoverColor, {
            label: _('Border Color'),
            attr: 'hoverlabel.bordercolor',
            defaultColor: '#000',
            handleEmpty: true
          }),
          _react2.default.createElement(_components.FontSelector, { label: _('Typeface'), attr: 'hoverlabel.font.family', clearable: true }),
          _react2.default.createElement(_components.Numeric, { label: _('Font Size'), attr: 'hoverlabel.font.size' }),
          _react2.default.createElement(_derived.HoverColor, {
            label: _('Font Color'),
            attr: 'hoverlabel.font.color',
            defaultColor: '#000',
            handleEmpty: true
          })
        )
      )
    ),
    _react2.default.createElement(
      _components.PlotlyFold,
      { name: _('Meta Text') },
      _react2.default.createElement(_DataSelector2.default, { label: _('Custom Data'), attr: 'meta' }),
      _react2.default.createElement(
        _components.Info,
        null,
        _react2.default.createElement(
          'p',
          null,
          _('You can refer to the items in this column in any text fields of the editor like so: '),
          _react2.default.createElement(
            'p',
            null,
            _('Ex: '),
            _react2.default.createElement(
              'span',
              { style: { letterSpacing: '1px', fontStyle: 'italic', userSelect: 'text' } },
              _('My custom title %{meta[1]}')
            )
          )
        )
      )
    )
  );
};

StyleLayoutPanel.contextTypes = {
  localize: _propTypes2.default.func
};

exports.default = StyleLayoutPanel;
//# sourceMappingURL=StyleLayoutPanel.js.map

/***/ }),

/***/ "6MIY":
/*!********************************************!*\
  !*** ./node_modules/ajv/lib/dotjs/enum.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_enum(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $i = 'i' + $lvl,
    $vSchema = 'schema' + $lvl;
  if (!$isData) {
    out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';';
  }
  out += 'var ' + ($valid) + ';';
  if ($isData) {
    out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
  }
  out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }';
  if ($isData) {
    out += '  }  ';
  }
  out += ' if (!' + ($valid) + ') {   ';
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should be equal to one of the allowed values\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += ' }';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}


/***/ }),

/***/ "6SSc":
/*!******************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/session/manager.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const kernel_1 = __webpack_require__(/*! ../kernel */ "uxQ0");
const __1 = __webpack_require__(/*! .. */ "S9up");
const session_1 = __webpack_require__(/*! ./session */ "MZLl");
/**
 * An implementation of a session manager.
 */
class SessionManager {
    /**
     * Construct a new session manager.
     *
     * @param options - The default options for each session.
     */
    constructor(options = {}) {
        this._isDisposed = false;
        this._models = [];
        this._sessions = new Set();
        this._specs = null;
        this._modelsTimer = -1;
        this._specsTimer = -1;
        this._specsChanged = new signaling_1.Signal(this);
        this._runningChanged = new signaling_1.Signal(this);
        this.serverSettings =
            options.serverSettings || __1.ServerConnection.makeSettings();
        // Initialize internal data.
        this._readyPromise = this._refreshSpecs().then(() => {
            return this._refreshRunning();
        });
        // Set up polling.
        this._modelsTimer = setInterval(() => {
            if (typeof document !== 'undefined' && document.hidden) {
                // Don't poll when nobody's looking.
                return;
            }
            this._refreshRunning();
        }, 10000);
        this._specsTimer = setInterval(() => {
            if (typeof document !== 'undefined' && document.hidden) {
                // Don't poll when nobody's looking.
                return;
            }
            this._refreshSpecs();
        }, 61000);
    }
    /**
     * A signal emitted when the kernel specs change.
     */
    get specsChanged() {
        return this._specsChanged;
    }
    /**
     * A signal emitted when the running sessions change.
     */
    get runningChanged() {
        return this._runningChanged;
    }
    /**
     * Test whether the manager is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Get the most recently fetched kernel specs.
     */
    get specs() {
        return this._specs;
    }
    /**
     * Test whether the manager is ready.
     */
    get isReady() {
        return this._specs !== null;
    }
    /**
     * A promise that fulfills when the manager is ready.
     */
    get ready() {
        return this._readyPromise;
    }
    /**
     * Dispose of the resources used by the manager.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        clearInterval(this._modelsTimer);
        clearInterval(this._specsTimer);
        signaling_1.Signal.clearData(this);
        this._models.length = 0;
    }
    /**
     * Create an iterator over the most recent running sessions.
     *
     * @returns A new iterator over the running sessions.
     */
    running() {
        return algorithm_1.iter(this._models);
    }
    /**
     * Force a refresh of the specs from the server.
     *
     * @returns A promise that resolves when the specs are fetched.
     *
     * #### Notes
     * This is intended to be called only in response to a user action,
     * since the manager maintains its internal state.
     */
    refreshSpecs() {
        return this._refreshSpecs();
    }
    /**
     * Force a refresh of the running sessions.
     *
     * @returns A promise that with the list of running sessions.
     *
     * #### Notes
     * This is not typically meant to be called by the user, since the
     * manager maintains its own internal state.
     */
    refreshRunning() {
        return this._refreshRunning();
    }
    /**
     * Start a new session.  See also [[startNewSession]].
     *
     * @param options - Overrides for the default options, must include a
     *   `'path'`.
     */
    startNew(options) {
        let serverSettings = this.serverSettings;
        return session_1.Session.startNew(Object.assign({}, options, { serverSettings })).then(session => {
            this._onStarted(session);
            return session;
        });
    }
    /**
     * Find a session associated with a path and stop it if it is the only session
     * using that kernel.
     *
     * @param path - The path in question.
     *
     * @returns A promise that resolves when the relevant sessions are stopped.
     */
    stopIfNeeded(path) {
        return session_1.Session.listRunning(this.serverSettings)
            .then(sessions => {
            const matches = sessions.filter(value => value.path === path);
            if (matches.length === 1) {
                const id = matches[0].id;
                return this.shutdown(id).catch(() => {
                    /* no-op */
                });
            }
        })
            .catch(() => Promise.resolve(void 0)); // Always succeed.
    }
    /**
     * Find a session by id.
     */
    findById(id) {
        return session_1.Session.findById(id, this.serverSettings);
    }
    /**
     * Find a session by path.
     */
    findByPath(path) {
        return session_1.Session.findByPath(path, this.serverSettings);
    }
    /*
     * Connect to a running session.  See also [[connectToSession]].
     */
    connectTo(model) {
        const session = session_1.Session.connectTo(model, this.serverSettings);
        this._onStarted(session);
        return session;
    }
    /**
     * Shut down a session by id.
     */
    shutdown(id) {
        let index = algorithm_1.ArrayExt.findFirstIndex(this._models, value => value.id === id);
        if (index === -1) {
            return;
        }
        // Proactively remove the model.
        this._models.splice(index, 1);
        this._runningChanged.emit(this._models.slice());
        return session_1.Session.shutdown(id, this.serverSettings).then(() => {
            let toRemove = [];
            this._sessions.forEach(s => {
                if (s.id === id) {
                    s.dispose();
                    toRemove.push(s);
                }
            });
            toRemove.forEach(s => {
                this._sessions.delete(s);
            });
        });
    }
    /**
     * Shut down all sessions.
     *
     * @returns A promise that resolves when all of the sessions are shut down.
     */
    shutdownAll() {
        // Proactively remove all models.
        let models = this._models;
        if (models.length > 0) {
            this._models = [];
            this._runningChanged.emit([]);
        }
        return this._refreshRunning().then(() => {
            return Promise.all(models.map(model => {
                return session_1.Session.shutdown(model.id, this.serverSettings).then(() => {
                    let toRemove = [];
                    this._sessions.forEach(s => {
                        s.dispose();
                        toRemove.push(s);
                    });
                    toRemove.forEach(s => {
                        this._sessions.delete(s);
                    });
                });
            })).then(() => {
                return undefined;
            });
        });
    }
    /**
     * Handle a session terminating.
     */
    _onTerminated(id) {
        let index = algorithm_1.ArrayExt.findFirstIndex(this._models, value => value.id === id);
        if (index !== -1) {
            this._models.splice(index, 1);
            this._runningChanged.emit(this._models.slice());
        }
    }
    /**
     * Handle a session starting.
     */
    _onStarted(session) {
        let id = session.id;
        let index = algorithm_1.ArrayExt.findFirstIndex(this._models, value => value.id === id);
        this._sessions.add(session);
        if (index === -1) {
            this._models.push(session.model);
            this._runningChanged.emit(this._models.slice());
        }
        session.terminated.connect(s => {
            this._onTerminated(id);
        });
        session.propertyChanged.connect((sender, prop) => {
            this._onChanged(session.model);
        });
        session.kernelChanged.connect(() => {
            this._onChanged(session.model);
        });
    }
    /**
     * Handle a change to a session.
     */
    _onChanged(model) {
        let index = algorithm_1.ArrayExt.findFirstIndex(this._models, value => value.id === model.id);
        if (index !== -1) {
            this._models[index] = model;
            this._runningChanged.emit(this._models.slice());
        }
    }
    /**
     * Refresh the specs.
     */
    _refreshSpecs() {
        return kernel_1.Kernel.getSpecs(this.serverSettings).then(specs => {
            if (!coreutils_1.JSONExt.deepEqual(specs, this._specs)) {
                this._specs = specs;
                this._specsChanged.emit(specs);
            }
        });
    }
    /**
     * Refresh the running sessions.
     */
    _refreshRunning() {
        return session_1.Session.listRunning(this.serverSettings).then(models => {
            if (!coreutils_1.JSONExt.deepEqual(models, this._models)) {
                let ids = models.map(r => r.id);
                let toRemove = [];
                this._sessions.forEach(s => {
                    if (ids.indexOf(s.id) === -1) {
                        s.dispose();
                        toRemove.push(s);
                    }
                });
                toRemove.forEach(s => {
                    this._sessions.delete(s);
                });
                this._models = models.slice();
                this._runningChanged.emit(models);
            }
        });
    }
}
exports.SessionManager = SessionManager;


/***/ }),

/***/ "6VdM":
/*!********************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/bem.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = bem;

var _constants = __webpack_require__(/*! ./constants */ "5Bkx");

function bem(block, element, modifiers) {
  var i = void 0,
      modifier = void 0;
  var out = [];

  if (!block) {
    return _constants.baseClass;
  }
  if (Array.isArray(block)) {
    throw new Error('bem error: Argument `block` cannot be an array');
  } else if (Array.isArray(element)) {
    modifiers = element;
    element = null;
  }

  var className = block;

  if (element && element.length) {
    className += '__' + element;
  }

  out.push(className);
  if (modifiers) {
    for (i = 0; i < modifiers.length; i++) {
      modifier = modifiers[i];
      if (modifier && modifier.length) {
        out.push(className + '--' + modifier);
      }
    }
  }

  return out.join(' ');
} //
// BEM helper
//
// bem()                       => 'plotly-editor'
// bem('foo')                  => 'foo'
// bem('foo', 'bar')           => 'foo__bar'
// bem('foo', ['mod'])         => 'foo foo--mod'
// bem('foo', 'bar', ['mod'])  => 'foo__bar foo__bar--mod'
// bem('foo', ['mod1', mod2']) => 'foo foo--mod1 foo--mod2'

/* eslint-disable no-param-reassign */
//# sourceMappingURL=bem.js.map

/***/ }),

/***/ "6Wb8":
/*!************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/console/style/index.css ***!
  \************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.jp-ConsolePanel {\n  display: flex;\n  flex: 1 1 auto;\n  flex-direction: column;\n  margin-top: -1px;\n  min-width: 240px;\n  min-height: 120px;\n}\n\n.jp-ConsolePanel::before {\n  content: '';\n  display: block;\n  height: var(--jp-toolbar-micro-height);\n  background: var(--jp-toolbar-background);\n  border-bottom: 1px solid var(--jp-toolbar-border-color);\n  box-shadow: var(--jp-toolbar-box-shadow);\n  z-index: 1;\n}\n\n.jp-CodeConsole {\n  height: 100%;\n  padding: 0;\n  display: flex;\n  flex-direction: column;\n}\n\n.jp-CodeConsole .jp-Cell {\n  padding: var(--jp-cell-padding);\n}\n\n/*-----------------------------------------------------------------------------\n| Content (already run cells)\n|----------------------------------------------------------------------------*/\n\n.jp-CodeConsole-content {\n  background: var(--jp-layout-color0);\n  flex: 1 1 auto;\n  overflow: auto;\n  padding: var(--jp-console-padding);\n}\n\n.jp-CodeConsole-content .jp-Cell:not(.jp-mod-active) .jp-InputPrompt {\n  opacity: var(--jp-cell-prompt-not-active-opacity);\n  color: var(--jp-cell-inprompt-font-color);\n}\n\n.jp-CodeConsole-content .jp-Cell:not(.jp-mod-active) .jp-OutputPrompt {\n  opacity: var(--jp-cell-prompt-not-active-opacity);\n  color: var(--jp-cell-outprompt-font-color);\n}\n\n/* This rule is for styling cell run by another activity in this console */\n.jp-CodeConsole-content .jp-Cell.jp-CodeConsole-foreignCell {\n}\n\n.jp-CodeConsole-content .jp-InputArea-editor.jp-InputArea-editor {\n  background: transparent;\n  border: 1px solid transparent;\n}\n\n.jp-CodeConsole-content .jp-CodeConsole-banner .jp-InputPrompt {\n  display: none;\n}\n\n/* collapser is hovered */\n.jp-CodeConsole-content .jp-Cell .jp-Collapser:hover {\n  box-shadow: var(--jp-elevation-z2);\n  background: var(--jp-brand-color1);\n  opacity: var(--jp-cell-collapser-not-active-hover-opacity);\n}\n\n/*-----------------------------------------------------------------------------\n| Input/prompt cell\n|----------------------------------------------------------------------------*/\n\n.jp-CodeConsole-input {\n  max-height: 80%;\n  flex: 0 0 auto;\n  overflow: auto;\n  border-top: var(--jp-border-width) solid var(--jp-toolbar-border-color);\n  padding: var(--jp-cell-padding) var(--jp-console-padding);\n  /* This matches the box shadow on the notebook toolbar, eventually we should create\n   * CSS variables for this */\n  box-shadow: 0px 0.4px 6px 0px rgba(0, 0, 0, 0.1);\n  background: var(--jp-layout-color1);\n}\n\n.jp-CodeConsole-input .jp-CodeConsole-prompt .jp-InputArea {\n  height: 100%;\n  min-height: 100%;\n}\n\n.jp-CodeConsole-promptCell .jp-InputArea-editor.jp-mod-focused {\n  border: var(--jp-border-width) solid var(--jp-cell-editor-active-border-color);\n  box-shadow: var(--jp-input-box-shadow);\n  background-color: var(--jp-cell-editor-active-background);\n}\n\n/*-----------------------------------------------------------------------------\n| Presentation Mode (.jp-mod-presentationMode)\n|----------------------------------------------------------------------------*/\n\n.jp-mod-presentationMode .jp-CodeConsole {\n  --jp-content-font-size1: var(--jp-content-presentation-font-size1);\n  --jp-code-font-size: var(--jp-code-presentation-font-size);\n}\n\n.jp-mod-presentationMode .jp-CodeConsole .jp-Cell .jp-InputPrompt,\n.jp-mod-presentationMode .jp-CodeConsole .jp-Cell .jp-OutputPrompt {\n  flex: 0 0 110px;\n}\n", ""]);

// exports


/***/ }),

/***/ "6Xrj":
/*!****************************************!*\
  !*** ./node_modules/fbjs/lib/Style.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks
 */

var getStyleProperty = __webpack_require__(/*! ./getStyleProperty */ "S5bm");

/**
 * @param {DOMNode} element [description]
 * @param {string} name Overflow style property name.
 * @return {boolean} True if the supplied ndoe is scrollable.
 */
function _isNodeScrollable(element, name) {
  var overflow = Style.get(element, name);
  return overflow === 'auto' || overflow === 'scroll';
}

/**
 * Utilities for querying and mutating style properties.
 */
var Style = {
  /**
   * Gets the style property for the supplied node. This will return either the
   * computed style, if available, or the declared style.
   *
   * @param {DOMNode} node
   * @param {string} name Style property name.
   * @return {?string} Style property value.
   */
  get: getStyleProperty,

  /**
   * Determines the nearest ancestor of a node that is scrollable.
   *
   * NOTE: This can be expensive if used repeatedly or on a node nested deeply.
   *
   * @param {?DOMNode} node Node from which to start searching.
   * @return {?DOMWindow|DOMElement} Scroll parent of the supplied node.
   */
  getScrollParent: function getScrollParent(node) {
    if (!node) {
      return null;
    }
    var ownerDocument = node.ownerDocument;
    while (node && node !== ownerDocument.body) {
      if (_isNodeScrollable(node, 'overflow') || _isNodeScrollable(node, 'overflowY') || _isNodeScrollable(node, 'overflowX')) {
        return node;
      }
      node = node.parentNode;
    }
    return ownerDocument.defaultView || ownerDocument.parentWindow;
  }

};

module.exports = Style;

/***/ }),

/***/ "6ak3":
/*!**********************************************************!*\
  !*** ./node_modules/react-tabs/esm/helpers/propTypes.js ***!
  \**********************************************************/
/*! exports provided: childrenPropType, onSelectPropType, selectedIndexPropType */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "childrenPropType", function() { return childrenPropType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "onSelectPropType", function() { return onSelectPropType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "selectedIndexPropType", function() { return selectedIndexPropType; });
/* harmony import */ var _childrenDeepMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./childrenDeepMap */ "pMj9");
/* harmony import */ var _elementTypes__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./elementTypes */ "fxcN");


function childrenPropType(props, propName, componentName) {
  var error;
  var tabsCount = 0;
  var panelsCount = 0;
  var tabListFound = false;
  var listTabs = [];
  var children = props[propName];
  Object(_childrenDeepMap__WEBPACK_IMPORTED_MODULE_0__["deepForEach"])(children, function (child) {
    if (Object(_elementTypes__WEBPACK_IMPORTED_MODULE_1__["isTabList"])(child)) {
      if (child.props && child.props.children && typeof child.props.children === 'object') {
        Object(_childrenDeepMap__WEBPACK_IMPORTED_MODULE_0__["deepForEach"])(child.props.children, function (listChild) {
          return listTabs.push(listChild);
        });
      }

      if (tabListFound) {
        error = new Error("Found multiple 'TabList' components inside 'Tabs'. Only one is allowed.");
      }

      tabListFound = true;
    }

    if (Object(_elementTypes__WEBPACK_IMPORTED_MODULE_1__["isTab"])(child)) {
      if (!tabListFound || listTabs.indexOf(child) === -1) {
        error = new Error("Found a 'Tab' component outside of the 'TabList' component. 'Tab' components " + "have to be inside the 'TabList' component.");
      }

      tabsCount++;
    } else if (Object(_elementTypes__WEBPACK_IMPORTED_MODULE_1__["isTabPanel"])(child)) {
      panelsCount++;
    }
  });

  if (!error && tabsCount !== panelsCount) {
    error = new Error("There should be an equal number of 'Tab' and 'TabPanel' in `" + componentName + "`. " + ("Received " + tabsCount + " 'Tab' and " + panelsCount + " 'TabPanel'."));
  }

  return error;
}
function onSelectPropType(props, propName, componentName, location, propFullName) {
  var prop = props[propName];
  var name = propFullName || propName;
  var error = null;

  if (prop && typeof prop !== 'function') {
    error = new Error("Invalid " + location + " `" + name + "` of type `" + typeof prop + "` supplied " + ("to `" + componentName + "`, expected `function`."));
  } else if (props.selectedIndex != null && prop == null) {
    error = new Error("The " + location + " `" + name + "` is marked as required in `" + componentName + "`, but " + "its value is `undefined` or `null`.\n" + "`onSelect` is required when `selectedIndex` is also set. Not doing so will " + "make the tabs not do anything, as `selectedIndex` indicates that you want to " + "handle the selected tab yourself.\n" + "If you only want to set the inital tab replace `selectedIndex` with `defaultIndex`.");
  }

  return error;
}
function selectedIndexPropType(props, propName, componentName, location, propFullName) {
  var prop = props[propName];
  var name = propFullName || propName;
  var error = null;

  if (prop != null && typeof prop !== 'number') {
    error = new Error("Invalid " + location + " `" + name + "` of type `" + typeof prop + "` supplied to " + ("`" + componentName + "`, expected `number`."));
  } else if (props.defaultIndex != null && prop != null) {
    return new Error("The " + location + " `" + name + "` cannot be used together with `defaultIndex` " + ("in `" + componentName + "`.\n") + ("Either remove `" + name + "` to let `" + componentName + "` handle the selected ") + "tab internally or remove `defaultIndex` to handle it yourself.");
  }

  return error;
}

/***/ }),

/***/ "6bQy":
/*!***********************************************!*\
  !*** ./node_modules/is-string-blank/index.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Is this string all whitespace?
 * This solution kind of makes my brain hurt, but it's significantly faster
 * than !str.trim() or any other solution I could find.
 *
 * whitespace codes from: http://en.wikipedia.org/wiki/Whitespace_character
 * and verified with:
 *
 *  for(var i = 0; i < 65536; i++) {
 *      var s = String.fromCharCode(i);
 *      if(+s===0 && !s.trim()) console.log(i, s);
 *  }
 *
 * which counts a couple of these as *not* whitespace, but finds nothing else
 * that *is* whitespace. Note that charCodeAt stops at 16 bits, but it appears
 * that there are no whitespace characters above this, and code points above
 * this do not map onto white space characters.
 */

module.exports = function(str){
    var l = str.length,
        a;
    for(var i = 0; i < l; i++) {
        a = str.charCodeAt(i);
        if((a < 9 || a > 13) && (a !== 32) && (a !== 133) && (a !== 160) &&
            (a !== 5760) && (a !== 6158) && (a < 8192 || a > 8205) &&
            (a !== 8232) && (a !== 8233) && (a !== 8239) && (a !== 8287) &&
            (a !== 8288) && (a !== 12288) && (a !== 65279)) {
                return false;
        }
    }
    return true;
}


/***/ }),

/***/ "6enh":
/*!************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotChoroplethIcon.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotChoroplethIcon = function PlotChoroplethIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M29.313 0H2.688A2.668 2.668 0 0 0 0 2.688v26.625c0 1.5 1.188 2.688 2.688 2.688h26.625c1.5 0 2.688-1.188 2.688-2.688V2.688c0-1.5-1.188-2.688-2.688-2.688zM18.125 2.938c.125.125.25.125.438.125h.375c0 .125 0 .125-.125.25h-.125l-.125.125s0 .188-.188.188h.313v-.313-.125c-.125-.125-.125-.125-.313 0-.125.125-.125.125-.25 0 0 0 0-.125-.125-.125 0-.125-.125-.125-.125-.125l-.25-.125-.188-.125h-.125H18c.125.125.125.125.125.25zm-.812.125v.375l-.125.188c-.125.125-.125 0-.125-.188v-.25h-.25-.125s-.125.125 0 .125.125.125.125.313h-1.376v-.188h.188c.25 0 .375 0 .5-.125.125-.375-.125-.375-.25-.375s-.125 0-.25-.125l-.188-.125h1.75c0 .125.125.25.125.375zm-4.375 0c.125 0 .125.125.25.125 0 0 0 .25-.125.125s-.375-.125-.5-.125c-.188-.125-.313-.125-.438-.125h-.688c-.125 0-.125.125-.25.125v-.25h-.125s-.125 0-.125.125c-.125-.125-.25-.125-.375-.125h-.938s0 .125-.188.125c0 .125-.125.25-.25 0h-.625c-.188 0-.438-.125-.563-.25-.25 0-.563.125-.813.125-.125 0-.25-.125-.5-.125h-.813-.125c-.125 0-.125-.125-.313-.125h6c.313.125.438.125.563.25.125 0 .375 0 .563-.125v-.125h.125zM12 8c-.125 0-.125-.125-.125-.25s-.125-.125-.25-.125h-.188v-.188l.188.188c.125 0 .25 0 .375.125V8zM2.688 2.688h2.75s0 .125-.125.125-.25.125-.375.125-.25.125-.563.125H4s-.125.125-.125.25.125.313.25.313.25 0 .438.125c.125 0 .25.125.25.25.125 0 .125.125 0 .125-.25-.125-.438-.125-.563-.25l-.125-.125L4 3.876c-.25 0-.375.125-.563.125 0 .125.188.25.313.25.125.125.25.125.375.125h.563s0 .313-.313.313c-.125 0-.375 0-.5.125 0 .125-.125.125-.125.25.125.125.25.375.25.563 0 .125.125 0 .25 0 0 0 .125 0 .125-.188 0-.125.313-.125.188.188 0 .125 0 .25.125.25 0-.125.125-.25.125-.25l.25.25s.125-.125.125 0 0 0-.125.125-.375.125-.5.25h-.188c-.125 0-.125.125-.25.125s-.125.313 0 .313c.25 0 .563-.125.813-.313.125 0 .125.188.375 0l.125-.125c.188-.125.313-.125.313-.25.125.125.125.125.25.125h.125c.125 0 .125-.125.25-.125v-.125h-.25c.125 0 .125-.125.25-.25v-.188c0-.125.188-.125.188-.125.125 0 .125 0 0 .313-.188.25.125-.188.25-.188h.375c0-.125 0-.125.125-.125 0-.125 0-.125.125-.25.188.125.313.125.438.125s.25 0 .375.125c.125 0 .688.125.813.125.25 0 .375.188.375.438s.188.25.188.25c.125 0 .25.125.375.25 0 .188 0 .438.125.563s.25.125.438.25v-.125c0-.125 0-.125-.188-.125v-.125c0-.125.188-.125.188 0 0-.125.125 0 .25.125s.125.25.125.25 0 .438.125.438.25.125.375.25c0 0 .188.125.188.25s.125.25.125.438v.75c0 .313.125.563.25.813 0 .25 0 .563.125.688s.25.125.563.125c.125 0 .25.125.375.375 0 .438.125.563.25.813.125 0 .313.125.125.25-.125.188-.125.313 0 .313.188 0 .188-.125.313.125.125.125.125.25.25.375 0 .125.125.125.125.125.125 0 .125.313.438.313v-.188c-.188-.125-.188-.125-.313-.25 0-.125-.125-.25-.125-.25 0-.125-.125-.25-.125-.25h-.125c-.125-.125-.125-.313-.25-.438l-.188-.125s-.125-.125 0-.25c.188-.125.188.125.313.25.125.25.375.563.5.688.125.25.313.375.563.625.125.188.25.188.25.313s.125.25.125.25c0 .125 0 .25.125.375a.77.77 0 0 1 .688.438c0 .125.125.375.25.375h.438s.125.125.25 0c0-.125.125-.125.25-.125s.25.125.25.25c.188.125.313.313.438.313s.25.125.25.125c.125 0 .125 0 .25.125.188.125.313.25.188.375 0 .125.125.313.25.313.125.125.25.125.25.25.125 0 .25.125.25.125s.125.125.313.125l.125-.125v-.125h.25c.125.125.125.25.125.375.125.125.125.438.125.563s0 .25-.125.375-.25.125-.25.25c-.125.188-.25.313-.25.438v.5c-.188.125-.188.313-.188.563s.438.25.438.375.25.688.25.813c.125.25.125.375.125.688.125.25.313.375.563.375.125 0 .25.125.25.25.125.188.25.188.25.313s.125.25 0 .375c0 0 0 .688-.125.938v.813c-.125.125-.25.125-.125.25s.375.25.375.25c0 .125.188.313 0 .563 0 .125-.125.25-.125.375-.125.125-.125.313-.125.438s-.125.125-.125.25.125.125.125.25-.125.25-.125.438c0 .125 0 .25.125.375 0 .125-.125.25-.125.375-.125.188-.125.313-.125.313 0 .125.125.125.125.25 0 0 0 .125-.125.25H2.696zm26.625 26.625h-6.625v-.125-.25h-.313v-.125l.188-.125.125-.125c.125-.188.125-.313.25-.313 0 0 .125-.125.125-.25s0 0-.125 0-.125-.125-.125-.25c.125 0 .25 0 .375.125h.125v-.25-.188-.125h.688c.125 0 .125-.125.125-.25l.125-.125s.125-.125 0-.25h-.25l-.125-.125v-.188c0-.125 0-.25.125-.375 0 .25 0 .375.25.563.125.125.438 0 .563-.188l.125-.125c.125-.125.25-.25.25-.375v-.25s0-.188.125-.188l.125-.125c0-.125.188-.125.313-.25v-.25-.25l.125-.188.25-.125c.125 0 .125-.125.25-.125.188 0 .313 0 .438-.125 0-.125.125-.25.125-.375l.125-.188.125-.125c.125-.125.125-.25.125-.25v-.25c0-.125 0-.25.125-.25v-.313c0-.125 0-.25.188-.25l.625-.813c.125-.125.125-.25.313-.375l.125-.25c0-.188.125-.313.125-.438s0-.125-.125-.25c0-.125-.125-.125-.313-.25-.125 0-.25 0-.25-.188 0 0-.125 0-.125-.125l-.125-.125c-.125-.125-.25-.125-.25-.125h-.438l-.375-.25c-.125-.125-.25-.125-.438-.125-.125 0-.125-.125-.25.125 0 .125-.125.125-.125.25h-.25-.125l.125-.125v-.25-.313c0 .188-.125.188-.313.313-.25 0-.25-.125-.125-.125s.313-.188.438-.188.125-.125.125-.125c0-.125 0-.125-.125-.25s-.125-.25-.313-.375l-.25-.438c-.125-.125-.25-.25-.5-.25-.125 0-.313.25-.438 0v-.125l-.25-.25h-.25s-.313 0-.125-.188v-.125-.25-.125c0 .125-.188.125-.313.25l-.25-.25h-.25s-.125 0-.125.125v.125s0-.125-.125-.125c-.188-.125-.313-.125-.438 0 0 0-.125 0-.125-.125s-.125-.125-.125-.25h-.125c-.125 0-.125.125-.125.25s-.188.25-.188.375v-.125-.25c0-.125.188-.25 0-.25h-.125l.125.375h-.125c-.125.125-.25.125-.25.25s-.125.313-.25.313h-.125c0-.188-.125-.188-.125-.188h-.313-.125l-.25.188c-.125.125-.25 0-.438 0 0-.188-.125-.188-.125-.313v-.125-.25-.438c0-.125 0-.125-.125-.25 0-.125-.125-.125-.25-.125s-.25.125-.25.125h-.313c-.125 0 0 0 0-.125v-.125-.25c0-.125 0-.125.188-.313.125-.125.125-.25.125-.375 0 0 0-.125-.125-.125h-.563a.269.269 0 0 0-.25.25v.125c0 .125 0 .313-.125.313-.188-.188-.313-.188-.313 0 0 .125 0 0-.25-.188h-.125c-.125-.125-.25-.25-.25-.375v-.125-.438-.25-.375s0-.125.125-.125l.125-.313c.125 0 .125-.125.25-.25h.438c.125 0 .25 0 .375.125h.25v-.125s.125-.125.313-.125c.125 0 .375-.125.5-.125 0 0 .125.25.25.25.125-.125.125-.25.125 0s.188.438.313.688c0 .125.125.25.25.25.125-.125.125-.125.125-.25v-.25c0-.188-.125-.313-.125-.438 0 0 0-.125-.125-.125v-.125c0-.125.125-.25.125-.25.125-.188.125-.188.25-.313s.125-.25.313-.25c.125-.125.375-.125.25-.25s-.125-.25-.125-.563c0-.125.125-.125.125 0s.25-.125.125-.25v-.125h.125v-.125c0-.125.125-.125.25-.125h.563v-.188c0-.125-.125-.125-.125-.25v-.125c0-.125.125-.25.25-.25h.25l.125-.125h.188s0 .375.125.375.25-.125.25-.125l.375-.125c.125 0 .313 0 .438-.125v-.313s0-.125-.125-.125c0 0-.188 0-.188.125h-.125c0-.125 0-.25-.125-.25l-.125.125-.125-.125c.125 0 .125-.125 0-.25h-.25s-.125.125-.313.125c-.125 0-.125 0-.25.125C22 7.99 22 7.865 22 7.865c0-.125 0-.125.125-.125s.438-.125.563-.125c.125 0 .25 0 .25.125v.375s.375-.125.25-.125 0 0 0-.125l.125-.125h.438l.125-.125c.125 0 .125.125 0 .25s-.125.25-.25.5c-.188.188 0 .188.125.188h.375c.125 0 .125 0 .25.125h.563v-.125l-.125-.313v-.5-.125h-.125v-.188c-.125 0-.125.188-.125 0 .125-.125.125-.125.125-.25s.125-.125.125-.25v-.125a.269.269 0 0 1-.25-.25c0-.188-.188-.188-.313-.313h-.5c0-.125 0-.125-.125-.25 0 0 0-.125-.188-.125l-.125-.125-.25-.438v-.125s-.125 0-.25.25l-.125.188h-.125c-.188 0-.313-.188-.438-.313v-.125l.125-.125c-.125-.125-.25-.125-.375-.125-.125-.125-.25-.125-.563-.25h-.625c-.125.125-.125.25-.125.25v.25h-.188v.125c.188.125.313.313.313.438s0 .125-.125.25c-.188.25-.313.25-.438.25h-.125c.125.125.125.125.125.313v.5h-.25c-.125 0-.125-.125-.125-.125v-.25l-.125.125v-.25-.188c0-.125-.188-.25-.313-.25 0-.125-.125-.125-.25-.125h-.5c-.188 0-.313-.125-.438-.25h-.25-.25c0-.125 0-.125-.188-.313-.125 0 0-.125-.125-.25v-.25l.313-.125.25-.125c0-.125.125-.313.25-.313.25 0 .438.188.438.188v-.188-.25c0 .125.25.125.125.25-.125.188 0 .188 0 .188.125 0 .25-.188.25-.188s.25-.125.25 0c0 .188 0 .313.125.313s.313-.125.125-.313c-.125-.125-.25-.125-.25-.25l.25-.125h-.125-.125-.125s0-.125.125-.125h.563c.125 0 .125 0 .25-.125l.125-.125c0-.188-.125-.188-.125-.188l.125-.125h.438v-.125c.125 0 0 .25.125.125h.25c0 .125 0 .313-.125.313h-.125s-.125.125 0 .125h.25c0-.125.125-.125.125-.313h.125s.25.188.125.188l-.125.125c-.125 0-.125.125-.125.125v.125h-.25-.125-.125v.375s.125 0 .25-.125h.5c.125 0 .313.125.313.125.125 0 .125.188.25.188H22c.125 0 .125.125.125.125h.25v-.125h.188c.125.125.125.125.25.125v-.125c0-.188 0-.188-.125-.313s-.313-.125-.438-.25v-.125c.125 0 .313 0 .438.125s.25.125.25.125l.125-.125h.125l.438-.25h-.188c-.125 0-.25 0-.25-.125-.125-.188-.25-.188-.375-.313 0 0-.25.125-.25 0v-.25c0-.125 0-.125-.188-.25l-.625-.125h7.563zM19.875 8.375c0-.125-.125.313 0 .438 0 .125 0 .125-.125.25h-.125s-.188-.125-.188-.25v-.125c0-.125 0-.313-.125-.313h-.125c-.125 0-.125.188-.25.313v.625c-.125 0-.25-.125-.25-.375v-.125-.438c.125-.125.25-.125.375-.25.125 0 .375.125.375.125h.438c.125.125.25.313.25.438-.125 0-.25-.125-.25-.313zm.375.438c.313-.125.438-.125.563-.125.125.125-.125.125-.125.25-.125 0-.125.125-.313.125l-.25.125H20v.125c-.125.125-.25.125-.25.125l.25-.125v-.125zM19.063 8h-.375s-.125 0-.125-.125c-.188 0-.313 0-.313.125H18v-.125l.25-.125c.125-.125.313-.313.563-.313.125.188.25.313.375.313 0 0 0 .25-.125.25z' })
    );
};

exports.default = PlotChoroplethIcon;

/***/ }),

/***/ "6gcW":
/*!*********************************************!*\
  !*** ./node_modules/ajv/lib/dotjs/allOf.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_allOf(it, $keyword, $ruleType) {
  var out = ' ';
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $currentBaseId = $it.baseId,
    $allSchemasEmpty = true;
  var arr1 = $schema;
  if (arr1) {
    var $sch, $i = -1,
      l1 = arr1.length - 1;
    while ($i < l1) {
      $sch = arr1[$i += 1];
      if (it.util.schemaHasRules($sch, it.RULES.all)) {
        $allSchemasEmpty = false;
        $it.schema = $sch;
        $it.schemaPath = $schemaPath + '[' + $i + ']';
        $it.errSchemaPath = $errSchemaPath + '/' + $i;
        out += '  ' + (it.validate($it)) + ' ';
        $it.baseId = $currentBaseId;
        if ($breakOnError) {
          out += ' if (' + ($nextValid) + ') { ';
          $closingBraces += '}';
        }
      }
    }
  }
  if ($breakOnError) {
    if ($allSchemasEmpty) {
      out += ' if (true) { ';
    } else {
      out += ' ' + ($closingBraces.slice(0, -1)) + ' ';
    }
  }
  out = it.util.cleanUpCode(out);
  return out;
}


/***/ }),

/***/ "6jVa":
/*!*****************************************************************!*\
  !*** ./node_modules/@jupyterlab/vdom-extension/style/react.svg ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = "data:image/svg+xml;base64, "

/***/ }),

/***/ "6jo/":
/*!**********************************************!*\
  !*** ./node_modules/pure-color/parse/hex.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

function expand(hex) {
  var result = "#";

  for (var i = 1; i < hex.length; i++) {
    var val = hex.charAt(i);
    result += val + val;
  }

  return result;
}

function hex(hex) {
  // #RGB or #RGBA
  if(hex.length === 4 || hex.length === 5) {
    hex = expand(hex);
  }

  var rgb = [
    parseInt(hex.substring(1,3), 16),
    parseInt(hex.substring(3,5), 16),
    parseInt(hex.substring(5,7), 16)
  ];

  // #RRGGBBAA
  if (hex.length === 9) {
    var alpha = parseFloat((parseInt(hex.substring(7,9), 16) / 255).toFixed(2));
    rgb.push(alpha);
  }

  return rgb;
}

module.exports = hex;

/***/ }),

/***/ "6lN/":
/*!**********************************************************!*\
  !*** ./node_modules/elliptic/lib/elliptic/curve/base.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var BN = __webpack_require__(/*! bn.js */ "OZ/i");
var elliptic = __webpack_require__(/*! ../../elliptic */ "MzeL");
var utils = elliptic.utils;
var getNAF = utils.getNAF;
var getJSF = utils.getJSF;
var assert = utils.assert;

function BaseCurve(type, conf) {
  this.type = type;
  this.p = new BN(conf.p, 16);

  // Use Montgomery, when there is no fast reduction for the prime
  this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);

  // Useful for many curves
  this.zero = new BN(0).toRed(this.red);
  this.one = new BN(1).toRed(this.red);
  this.two = new BN(2).toRed(this.red);

  // Curve configuration, optional
  this.n = conf.n && new BN(conf.n, 16);
  this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);

  // Temporary arrays
  this._wnafT1 = new Array(4);
  this._wnafT2 = new Array(4);
  this._wnafT3 = new Array(4);
  this._wnafT4 = new Array(4);

  // Generalized Greg Maxwell's trick
  var adjustCount = this.n && this.p.div(this.n);
  if (!adjustCount || adjustCount.cmpn(100) > 0) {
    this.redN = null;
  } else {
    this._maxwellTrick = true;
    this.redN = this.n.toRed(this.red);
  }
}
module.exports = BaseCurve;

BaseCurve.prototype.point = function point() {
  throw new Error('Not implemented');
};

BaseCurve.prototype.validate = function validate() {
  throw new Error('Not implemented');
};

BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
  assert(p.precomputed);
  var doubles = p._getDoubles();

  var naf = getNAF(k, 1);
  var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
  I /= 3;

  // Translate into more windowed form
  var repr = [];
  for (var j = 0; j < naf.length; j += doubles.step) {
    var nafW = 0;
    for (var k = j + doubles.step - 1; k >= j; k--)
      nafW = (nafW << 1) + naf[k];
    repr.push(nafW);
  }

  var a = this.jpoint(null, null, null);
  var b = this.jpoint(null, null, null);
  for (var i = I; i > 0; i--) {
    for (var j = 0; j < repr.length; j++) {
      var nafW = repr[j];
      if (nafW === i)
        b = b.mixedAdd(doubles.points[j]);
      else if (nafW === -i)
        b = b.mixedAdd(doubles.points[j].neg());
    }
    a = a.add(b);
  }
  return a.toP();
};

BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
  var w = 4;

  // Precompute window
  var nafPoints = p._getNAFPoints(w);
  w = nafPoints.wnd;
  var wnd = nafPoints.points;

  // Get NAF form
  var naf = getNAF(k, w);

  // Add `this`*(N+1) for every w-NAF index
  var acc = this.jpoint(null, null, null);
  for (var i = naf.length - 1; i >= 0; i--) {
    // Count zeroes
    for (var k = 0; i >= 0 && naf[i] === 0; i--)
      k++;
    if (i >= 0)
      k++;
    acc = acc.dblp(k);

    if (i < 0)
      break;
    var z = naf[i];
    assert(z !== 0);
    if (p.type === 'affine') {
      // J +- P
      if (z > 0)
        acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
      else
        acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
    } else {
      // J +- J
      if (z > 0)
        acc = acc.add(wnd[(z - 1) >> 1]);
      else
        acc = acc.add(wnd[(-z - 1) >> 1].neg());
    }
  }
  return p.type === 'affine' ? acc.toP() : acc;
};

BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
                                                       points,
                                                       coeffs,
                                                       len,
                                                       jacobianResult) {
  var wndWidth = this._wnafT1;
  var wnd = this._wnafT2;
  var naf = this._wnafT3;

  // Fill all arrays
  var max = 0;
  for (var i = 0; i < len; i++) {
    var p = points[i];
    var nafPoints = p._getNAFPoints(defW);
    wndWidth[i] = nafPoints.wnd;
    wnd[i] = nafPoints.points;
  }

  // Comb small window NAFs
  for (var i = len - 1; i >= 1; i -= 2) {
    var a = i - 1;
    var b = i;
    if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
      naf[a] = getNAF(coeffs[a], wndWidth[a]);
      naf[b] = getNAF(coeffs[b], wndWidth[b]);
      max = Math.max(naf[a].length, max);
      max = Math.max(naf[b].length, max);
      continue;
    }

    var comb = [
      points[a], /* 1 */
      null, /* 3 */
      null, /* 5 */
      points[b] /* 7 */
    ];

    // Try to avoid Projective points, if possible
    if (points[a].y.cmp(points[b].y) === 0) {
      comb[1] = points[a].add(points[b]);
      comb[2] = points[a].toJ().mixedAdd(points[b].neg());
    } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
      comb[1] = points[a].toJ().mixedAdd(points[b]);
      comb[2] = points[a].add(points[b].neg());
    } else {
      comb[1] = points[a].toJ().mixedAdd(points[b]);
      comb[2] = points[a].toJ().mixedAdd(points[b].neg());
    }

    var index = [
      -3, /* -1 -1 */
      -1, /* -1 0 */
      -5, /* -1 1 */
      -7, /* 0 -1 */
      0, /* 0 0 */
      7, /* 0 1 */
      5, /* 1 -1 */
      1, /* 1 0 */
      3  /* 1 1 */
    ];

    var jsf = getJSF(coeffs[a], coeffs[b]);
    max = Math.max(jsf[0].length, max);
    naf[a] = new Array(max);
    naf[b] = new Array(max);
    for (var j = 0; j < max; j++) {
      var ja = jsf[0][j] | 0;
      var jb = jsf[1][j] | 0;

      naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
      naf[b][j] = 0;
      wnd[a] = comb;
    }
  }

  var acc = this.jpoint(null, null, null);
  var tmp = this._wnafT4;
  for (var i = max; i >= 0; i--) {
    var k = 0;

    while (i >= 0) {
      var zero = true;
      for (var j = 0; j < len; j++) {
        tmp[j] = naf[j][i] | 0;
        if (tmp[j] !== 0)
          zero = false;
      }
      if (!zero)
        break;
      k++;
      i--;
    }
    if (i >= 0)
      k++;
    acc = acc.dblp(k);
    if (i < 0)
      break;

    for (var j = 0; j < len; j++) {
      var z = tmp[j];
      var p;
      if (z === 0)
        continue;
      else if (z > 0)
        p = wnd[j][(z - 1) >> 1];
      else if (z < 0)
        p = wnd[j][(-z - 1) >> 1].neg();

      if (p.type === 'affine')
        acc = acc.mixedAdd(p);
      else
        acc = acc.add(p);
    }
  }
  // Zeroify references
  for (var i = 0; i < len; i++)
    wnd[i] = null;

  if (jacobianResult)
    return acc;
  else
    return acc.toP();
};

function BasePoint(curve, type) {
  this.curve = curve;
  this.type = type;
  this.precomputed = null;
}
BaseCurve.BasePoint = BasePoint;

BasePoint.prototype.eq = function eq(/*other*/) {
  throw new Error('Not implemented');
};

BasePoint.prototype.validate = function validate() {
  return this.curve.validate(this);
};

BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
  bytes = utils.toArray(bytes, enc);

  var len = this.p.byteLength();

  // uncompressed, hybrid-odd, hybrid-even
  if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&
      bytes.length - 1 === 2 * len) {
    if (bytes[0] === 0x06)
      assert(bytes[bytes.length - 1] % 2 === 0);
    else if (bytes[0] === 0x07)
      assert(bytes[bytes.length - 1] % 2 === 1);

    var res =  this.point(bytes.slice(1, 1 + len),
                          bytes.slice(1 + len, 1 + 2 * len));

    return res;
  } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
              bytes.length - 1 === len) {
    return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
  }
  throw new Error('Unknown point format');
};

BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
  return this.encode(enc, true);
};

BasePoint.prototype._encode = function _encode(compact) {
  var len = this.curve.p.byteLength();
  var x = this.getX().toArray('be', len);

  if (compact)
    return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);

  return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ;
};

BasePoint.prototype.encode = function encode(enc, compact) {
  return utils.encode(this._encode(compact), enc);
};

BasePoint.prototype.precompute = function precompute(power) {
  if (this.precomputed)
    return this;

  var precomputed = {
    doubles: null,
    naf: null,
    beta: null
  };
  precomputed.naf = this._getNAFPoints(8);
  precomputed.doubles = this._getDoubles(4, power);
  precomputed.beta = this._getBeta();
  this.precomputed = precomputed;

  return this;
};

BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
  if (!this.precomputed)
    return false;

  var doubles = this.precomputed.doubles;
  if (!doubles)
    return false;

  return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
};

BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
  if (this.precomputed && this.precomputed.doubles)
    return this.precomputed.doubles;

  var doubles = [ this ];
  var acc = this;
  for (var i = 0; i < power; i += step) {
    for (var j = 0; j < step; j++)
      acc = acc.dbl();
    doubles.push(acc);
  }
  return {
    step: step,
    points: doubles
  };
};

BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
  if (this.precomputed && this.precomputed.naf)
    return this.precomputed.naf;

  var res = [ this ];
  var max = (1 << wnd) - 1;
  var dbl = max === 1 ? null : this.dbl();
  for (var i = 1; i < max; i++)
    res[i] = res[i - 1].add(dbl);
  return {
    wnd: wnd,
    points: res
  };
};

BasePoint.prototype._getBeta = function _getBeta() {
  return null;
};

BasePoint.prototype.dblp = function dblp(k) {
  var r = this;
  for (var i = 0; i < k; i++)
    r = r.dbl();
  return r;
};


/***/ }),

/***/ "6pwk":
/*!***************************************!*\
  !*** ./node_modules/ajv/lib/cache.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";



var Cache = module.exports = function Cache() {
  this._cache = {};
};


Cache.prototype.put = function Cache_put(key, value) {
  this._cache[key] = value;
};


Cache.prototype.get = function Cache_get(key) {
  return this._cache[key];
};


Cache.prototype.del = function Cache_del(key) {
  delete this._cache[key];
};


Cache.prototype.clear = function Cache_clear() {
  this._cache = {};
};


/***/ }),

/***/ "6sVZ":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_isPrototype.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/** Used for built-in method references. */
var objectProto = Object.prototype;

/**
 * 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;
}

module.exports = isPrototype;


/***/ }),

/***/ "6tYh":
/*!************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_set-proto.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var isObject = __webpack_require__(/*! ./_is-object */ "93I4");
var anObject = __webpack_require__(/*! ./_an-object */ "5K7Z");
var check = function (O, proto) {
  anObject(O);
  if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
  set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
    function (test, buggy, set) {
      try {
        set = __webpack_require__(/*! ./_ctx */ "2GTP")(Function.call, __webpack_require__(/*! ./_object-gopd */ "vwuL").f(Object.prototype, '__proto__').set, 2);
        set(test, []);
        buggy = !(test instanceof Array);
      } catch (e) { buggy = true; }
      return function setPrototypeOf(O, proto) {
        check(O, proto);
        if (buggy) O.__proto__ = proto;
        else set(O, proto);
        return O;
      };
    }({}, false) : undefined),
  check: check
};


/***/ }),

/***/ "6tyx":
/*!********************************************************!*\
  !*** ./node_modules/draft-js/lib/DraftEditor.react.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DraftEditor.react
 * @format
 * 
 * @preventMunge
 */



var _assign = __webpack_require__(/*! object-assign */ "MgzW");

var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var DefaultDraftBlockRenderMap = __webpack_require__(/*! ./DefaultDraftBlockRenderMap */ "rAV9");
var DefaultDraftInlineStyle = __webpack_require__(/*! ./DefaultDraftInlineStyle */ "0TRD");
var DraftEditorCompositionHandler = __webpack_require__(/*! ./DraftEditorCompositionHandler */ "jl1W");
var DraftEditorContents = __webpack_require__(/*! ./DraftEditorContents.react */ "Idtq");
var DraftEditorDragHandler = __webpack_require__(/*! ./DraftEditorDragHandler */ "ISR0");
var DraftEditorEditHandler = __webpack_require__(/*! ./DraftEditorEditHandler */ "1Jbx");
var DraftEditorPlaceholder = __webpack_require__(/*! ./DraftEditorPlaceholder.react */ "Hdlu");
var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");
var React = __webpack_require__(/*! react */ "q1tI");
var ReactDOM = __webpack_require__(/*! react-dom */ "i8i4");
var Scroll = __webpack_require__(/*! fbjs/lib/Scroll */ "prOm");
var Style = __webpack_require__(/*! fbjs/lib/Style */ "6Xrj");
var UserAgent = __webpack_require__(/*! fbjs/lib/UserAgent */ "CYTE");

var cx = __webpack_require__(/*! fbjs/lib/cx */ "YVIB");
var emptyFunction = __webpack_require__(/*! fbjs/lib/emptyFunction */ "ohE5");
var generateRandomKey = __webpack_require__(/*! ./generateRandomKey */ "rJY1");
var getDefaultKeyBinding = __webpack_require__(/*! ./getDefaultKeyBinding */ "AyB5");
var getScrollPosition = __webpack_require__(/*! fbjs/lib/getScrollPosition */ "DeIs");
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");
var nullthrows = __webpack_require__(/*! fbjs/lib/nullthrows */ "gWRK");

var isIE = UserAgent.isBrowser('IE');

// IE does not support the `input` event on contentEditable, so we can't
// observe spellcheck behavior.
var allowSpellCheck = !isIE;

// Define a set of handler objects to correspond to each possible `mode`
// of editor behavior.
var handlerMap = {
  edit: DraftEditorEditHandler,
  composite: DraftEditorCompositionHandler,
  drag: DraftEditorDragHandler,
  cut: null,
  render: null
};

/**
 * `DraftEditor` is the root editor component. It composes a `contentEditable`
 * div, and provides a wide variety of useful function props for managing the
 * state of the editor. See `DraftEditorProps` for details.
 */
var DraftEditor = function (_React$Component) {
  _inherits(DraftEditor, _React$Component);

  function DraftEditor(props) {
    _classCallCheck(this, DraftEditor);

    var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));

    _this.focus = function (scrollPosition) {
      var editorState = _this.props.editorState;

      var alreadyHasFocus = editorState.getSelection().getHasFocus();
      var editorNode = ReactDOM.findDOMNode(_this.editor);

      if (!editorNode) {
        // once in a while people call 'focus' in a setTimeout, and the node has
        // been deleted, so it can be null in that case.
        return;
      }

      var scrollParent = Style.getScrollParent(editorNode);

      var _ref = scrollPosition || getScrollPosition(scrollParent),
          x = _ref.x,
          y = _ref.y;

      !(editorNode instanceof HTMLElement) ?  true ? invariant(false, 'editorNode is not an HTMLElement') : undefined : void 0;
      editorNode.focus();

      // Restore scroll position
      if (scrollParent === window) {
        window.scrollTo(x, y);
      } else {
        Scroll.setTop(scrollParent, y);
      }

      // On Chrome and Safari, calling focus on contenteditable focuses the
      // cursor at the first character. This is something you don't expect when
      // you're clicking on an input element but not directly on a character.
      // Put the cursor back where it was before the blur.
      if (!alreadyHasFocus) {
        _this.update(EditorState.forceSelection(editorState, editorState.getSelection()));
      }
    };

    _this.blur = function () {
      var editorNode = ReactDOM.findDOMNode(_this.editor);
      !(editorNode instanceof HTMLElement) ?  true ? invariant(false, 'editorNode is not an HTMLElement') : undefined : void 0;
      editorNode.blur();
    };

    _this.setMode = function (mode) {
      _this._handler = handlerMap[mode];
    };

    _this.exitCurrentMode = function () {
      _this.setMode('edit');
    };

    _this.restoreEditorDOM = function (scrollPosition) {
      _this.setState({ contentsKey: _this.state.contentsKey + 1 }, function () {
        _this.focus(scrollPosition);
      });
    };

    _this.setClipboard = function (clipboard) {
      _this._clipboard = clipboard;
    };

    _this.getClipboard = function () {
      return _this._clipboard;
    };

    _this.update = function (editorState) {
      _this._latestEditorState = editorState;
      _this.props.onChange(editorState);
    };

    _this.onDragEnter = function () {
      _this._dragCount++;
    };

    _this.onDragLeave = function () {
      _this._dragCount--;
      if (_this._dragCount === 0) {
        _this.exitCurrentMode();
      }
    };

    _this._blockSelectEvents = false;
    _this._clipboard = null;
    _this._handler = null;
    _this._dragCount = 0;
    _this._editorKey = props.editorKey || generateRandomKey();
    _this._placeholderAccessibilityID = 'placeholder-' + _this._editorKey;
    _this._latestEditorState = props.editorState;
    _this._latestCommittedEditorState = props.editorState;

    _this._onBeforeInput = _this._buildHandler('onBeforeInput');
    _this._onBlur = _this._buildHandler('onBlur');
    _this._onCharacterData = _this._buildHandler('onCharacterData');
    _this._onCompositionEnd = _this._buildHandler('onCompositionEnd');
    _this._onCompositionStart = _this._buildHandler('onCompositionStart');
    _this._onCopy = _this._buildHandler('onCopy');
    _this._onCut = _this._buildHandler('onCut');
    _this._onDragEnd = _this._buildHandler('onDragEnd');
    _this._onDragOver = _this._buildHandler('onDragOver');
    _this._onDragStart = _this._buildHandler('onDragStart');
    _this._onDrop = _this._buildHandler('onDrop');
    _this._onInput = _this._buildHandler('onInput');
    _this._onFocus = _this._buildHandler('onFocus');
    _this._onKeyDown = _this._buildHandler('onKeyDown');
    _this._onKeyPress = _this._buildHandler('onKeyPress');
    _this._onKeyUp = _this._buildHandler('onKeyUp');
    _this._onMouseDown = _this._buildHandler('onMouseDown');
    _this._onMouseUp = _this._buildHandler('onMouseUp');
    _this._onPaste = _this._buildHandler('onPaste');
    _this._onSelect = _this._buildHandler('onSelect');

    _this.getEditorKey = function () {
      return _this._editorKey;
    };

    // See `restoreEditorDOM()`.
    _this.state = { contentsKey: 0 };
    return _this;
  }

  /**
   * Build a method that will pass the event to the specified handler method.
   * This allows us to look up the correct handler function for the current
   * editor mode, if any has been specified.
   */


  /**
   * Define proxies that can route events to the current handler.
   */


  DraftEditor.prototype._buildHandler = function _buildHandler(eventName) {
    var _this2 = this;

    return function (e) {
      if (!_this2.props.readOnly) {
        var method = _this2._handler && _this2._handler[eventName];
        method && method(_this2, e);
      }
    };
  };

  DraftEditor.prototype._showPlaceholder = function _showPlaceholder() {
    return !!this.props.placeholder && !this.props.editorState.isInCompositionMode() && !this.props.editorState.getCurrentContent().hasText();
  };

  DraftEditor.prototype._renderPlaceholder = function _renderPlaceholder() {
    if (this._showPlaceholder()) {
      var placeHolderProps = {
        text: nullthrows(this.props.placeholder),
        editorState: this.props.editorState,
        textAlignment: this.props.textAlignment,
        accessibilityID: this._placeholderAccessibilityID
      };

      return React.createElement(DraftEditorPlaceholder, placeHolderProps);
    }
    return null;
  };

  DraftEditor.prototype.render = function render() {
    var _this3 = this;

    var _props = this.props,
        blockRenderMap = _props.blockRenderMap,
        blockRendererFn = _props.blockRendererFn,
        blockStyleFn = _props.blockStyleFn,
        customStyleFn = _props.customStyleFn,
        customStyleMap = _props.customStyleMap,
        editorState = _props.editorState,
        readOnly = _props.readOnly,
        textAlignment = _props.textAlignment,
        textDirectionality = _props.textDirectionality;


    var rootClass = cx({
      'DraftEditor/root': true,
      'DraftEditor/alignLeft': textAlignment === 'left',
      'DraftEditor/alignRight': textAlignment === 'right',
      'DraftEditor/alignCenter': textAlignment === 'center'
    });

    var contentStyle = {
      outline: 'none',
      // fix parent-draggable Safari bug. #1326
      userSelect: 'text',
      WebkitUserSelect: 'text',
      whiteSpace: 'pre-wrap',
      wordWrap: 'break-word'
    };

    // The aria-expanded and aria-haspopup properties should only be rendered
    // for a combobox.
    var ariaRole = this.props.role || 'textbox';
    var ariaExpanded = ariaRole === 'combobox' ? !!this.props.ariaExpanded : null;

    var editorContentsProps = {
      blockRenderMap: blockRenderMap,
      blockRendererFn: blockRendererFn,
      blockStyleFn: blockStyleFn,
      customStyleMap: _extends({}, DefaultDraftInlineStyle, customStyleMap),
      customStyleFn: customStyleFn,
      editorKey: this._editorKey,
      editorState: editorState,
      key: 'contents' + this.state.contentsKey,
      textDirectionality: textDirectionality
    };

    return React.createElement(
      'div',
      { className: rootClass },
      this._renderPlaceholder(),
      React.createElement(
        'div',
        {
          className: cx('DraftEditor/editorContainer'),
          ref: function ref(_ref3) {
            return _this3.editorContainer = _ref3;
          } },
        React.createElement(
          'div',
          {
            'aria-activedescendant': readOnly ? null : this.props.ariaActiveDescendantID,
            'aria-autocomplete': readOnly ? null : this.props.ariaAutoComplete,
            'aria-controls': readOnly ? null : this.props.ariaControls,
            'aria-describedby': this.props.ariaDescribedBy || this._placeholderAccessibilityID,
            'aria-expanded': readOnly ? null : ariaExpanded,
            'aria-label': this.props.ariaLabel,
            'aria-labelledby': this.props.ariaLabelledBy,
            'aria-multiline': this.props.ariaMultiline,
            autoCapitalize: this.props.autoCapitalize,
            autoComplete: this.props.autoComplete,
            autoCorrect: this.props.autoCorrect,
            className: cx({
              // Chrome's built-in translation feature mutates the DOM in ways
              // that Draft doesn't expect (ex: adding <font> tags inside
              // DraftEditorLeaf spans) and causes problems. We add notranslate
              // here which makes its autotranslation skip over this subtree.
              notranslate: !readOnly,
              'public/DraftEditor/content': true
            }),
            contentEditable: !readOnly,
            'data-testid': this.props.webDriverTestID,
            onBeforeInput: this._onBeforeInput,
            onBlur: this._onBlur,
            onCompositionEnd: this._onCompositionEnd,
            onCompositionStart: this._onCompositionStart,
            onCopy: this._onCopy,
            onCut: this._onCut,
            onDragEnd: this._onDragEnd,
            onDragEnter: this.onDragEnter,
            onDragLeave: this.onDragLeave,
            onDragOver: this._onDragOver,
            onDragStart: this._onDragStart,
            onDrop: this._onDrop,
            onFocus: this._onFocus,
            onInput: this._onInput,
            onKeyDown: this._onKeyDown,
            onKeyPress: this._onKeyPress,
            onKeyUp: this._onKeyUp,
            onMouseUp: this._onMouseUp,
            onPaste: this._onPaste,
            onSelect: this._onSelect,
            ref: function ref(_ref2) {
              return _this3.editor = _ref2;
            },
            role: readOnly ? null : ariaRole,
            spellCheck: allowSpellCheck && this.props.spellCheck,
            style: contentStyle,
            suppressContentEditableWarning: true,
            tabIndex: this.props.tabIndex },
          React.createElement(DraftEditorContents, editorContentsProps)
        )
      )
    );
  };

  DraftEditor.prototype.componentDidMount = function componentDidMount() {
    this.setMode('edit');

    /**
     * IE has a hardcoded "feature" that attempts to convert link text into
     * anchors in contentEditable DOM. This breaks the editor's expectations of
     * the DOM, and control is lost. Disable it to make IE behave.
     * See: http://blogs.msdn.com/b/ieinternals/archive/2010/09/15/
     * ie9-beta-minor-change-list.aspx
     */
    if (isIE) {
      document.execCommand('AutoUrlDetect', false, false);
    }
  };

  /**
   * Prevent selection events from affecting the current editor state. This
   * is mostly intended to defend against IE, which fires off `selectionchange`
   * events regardless of whether the selection is set via the browser or
   * programmatically. We only care about selection events that occur because
   * of browser interaction, not re-renders and forced selections.
   */


  DraftEditor.prototype.componentWillUpdate = function componentWillUpdate(nextProps) {
    this._blockSelectEvents = true;
    this._latestEditorState = nextProps.editorState;
  };

  DraftEditor.prototype.componentDidUpdate = function componentDidUpdate() {
    this._blockSelectEvents = false;
    this._latestCommittedEditorState = this.props.editorState;
  };

  /**
   * Used via `this.focus()`.
   *
   * Force focus back onto the editor node.
   *
   * We attempt to preserve scroll position when focusing. You can also pass
   * a specified scroll position (for cases like `cut` behavior where it should
   * be restored to a known position).
   */


  /**
   * Used via `this.setMode(...)`.
   *
   * Set the behavior mode for the editor component. This switches the current
   * handler module to ensure that DOM events are managed appropriately for
   * the active mode.
   */


  /**
   * Used via `this.restoreEditorDOM()`.
   *
   * Force a complete re-render of the DraftEditorContents based on the current
   * EditorState. This is useful when we know we are going to lose control of
   * the DOM state (cut command, IME) and we want to make sure that
   * reconciliation occurs on a version of the DOM that is synchronized with
   * our EditorState.
   */


  /**
   * Used via `this.setClipboard(...)`.
   *
   * Set the clipboard state for a cut/copy event.
   */


  /**
   * Used via `this.getClipboard()`.
   *
   * Retrieve the clipboard state for a cut/copy event.
   */


  /**
   * Used via `this.update(...)`.
   *
   * Propagate a new `EditorState` object to higher-level components. This is
   * the method by which event handlers inform the `DraftEditor` component of
   * state changes. A component that composes a `DraftEditor` **must** provide
   * an `onChange` prop to receive state updates passed along from this
   * function.
   */


  /**
   * Used in conjunction with `onDragLeave()`, by counting the number of times
   * a dragged element enters and leaves the editor (or any of its children),
   * to determine when the dragged element absolutely leaves the editor.
   */


  /**
   * See `onDragEnter()`.
   */


  return DraftEditor;
}(React.Component);

DraftEditor.defaultProps = {
  blockRenderMap: DefaultDraftBlockRenderMap,
  blockRendererFn: emptyFunction.thatReturnsNull,
  blockStyleFn: emptyFunction.thatReturns(''),
  keyBindingFn: getDefaultKeyBinding,
  readOnly: false,
  spellCheck: false,
  stripPastedStyles: false
};


module.exports = DraftEditor;

/***/ }),

/***/ "6ugs":
/*!********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/LineSelectors.js ***!
  \********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.LineDashSelector = exports.LineShapeSelector = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _Dropdown = __webpack_require__(/*! ./Dropdown */ "dRXW");

var _Dropdown2 = _interopRequireDefault(_Dropdown);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _nested_property = __webpack_require__(/*! plotly.js/src/lib/nested_property */ "dNZO");

var _nested_property2 = _interopRequireDefault(_nested_property);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _constants = __webpack_require__(/*! ../../lib/constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/* eslint-disable react/prop-types */
var styledRenderer = function styledRenderer(_ref) {
  var label = _ref.label;

  return _react2.default.createElement(
    'div',
    null,
    _react2.default.createElement(
      'svg',
      { width: '100', height: '16' },
      _react2.default.createElement(
        'g',
        null,
        label
      )
    )
  );
};
/* eslint-enable react/prop-types */

var strokeDashes = [{ value: 'solid', strokeDasharray: '' }, { value: 'dot', strokeDasharray: '3px, 3px' }, { value: 'dash', strokeDasharray: '9px, 9px' }, { value: 'longdash', strokeDasharray: '15px, 15px' }, { value: 'dashdot', strokeDasharray: '9px, 3px, 3px, 3px' }, { value: 'longdashdot', strokeDasharray: '15px, 6px, 3px, 6px' }];

var strokeShapes = [{ d: 'M2,14L14,2', value: 'linear' }, { d: 'M2,14C4,4 16,16 18,2', value: 'spline' }, { d: 'M2,14H14V2', value: 'hv' }, { d: 'M2,14V2H14', value: 'vh' }, { d: 'M2,14H8V2H14', value: 'hvh' }, { d: 'M2,14V8H14V2', value: 'vhv' }];

var strokeStyle = { fill: 'none', strokeWidth: '4px' };

var _computeOptions = function _computeOptions(strokeData, stroke) {
  return strokeData.map(function (_ref2) {
    var value = _ref2.value,
        strokeDasharray = _ref2.strokeDasharray,
        _ref2$d = _ref2.d,
        d = _ref2$d === undefined ? 'M0,8h100' : _ref2$d;
    return {
      label: _react2.default.createElement('path', {
        d: d,
        style: _extends({}, strokeStyle, {
          stroke: !stroke || stroke === _constants.MULTI_VALUED ? _constants.COLORS.mutedBlue : stroke,
          strokeDasharray: strokeDasharray
        })
      }),
      value: value
    };
  });
};

var LineShapeSelector = exports.LineShapeSelector = function LineShapeSelector(props) {
  return _react2.default.createElement(LineSelector, _extends({}, props, { computeOptions: _computeOptions.bind(null, strokeShapes) }));
};

var LineDashSelector = exports.LineDashSelector = function LineDashSelector(props) {
  return _react2.default.createElement(LineSelector, _extends({}, props, {
    computeOptions: function computeOptions(lineColor) {
      return _computeOptions(strokeDashes, lineColor).concat([{
        label: '',
        value: null
      }]);
    }
  }));
};

var LineSelector = function (_Component) {
  _inherits(LineSelector, _Component);

  function LineSelector(props, context) {
    _classCallCheck(this, LineSelector);

    var _this = _possibleConstructorReturn(this, (LineSelector.__proto__ || Object.getPrototypeOf(LineSelector)).call(this, props, context));

    _this.setLocals(props, context);
    return _this;
  }

  _createClass(LineSelector, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps, nextContext) {
      this.setLocals(nextProps, nextContext);
    }
  }, {
    key: 'setLocals',
    value: function setLocals(nextProps, nextContext) {
      var fullContainer = nextContext.fullContainer;

      var lineColor = (0, _nested_property2.default)(fullContainer, 'line.color').get();
      if (!this.options || this.lineColor !== lineColor) {
        this.options = this.props.computeOptions(lineColor);
        this.lineColor = lineColor;
      }
    }
  }, {
    key: 'render',
    value: function render() {
      return _react2.default.createElement(_Dropdown2.default, _extends({}, this.props, {
        options: this.options,
        valueRenderer: styledRenderer,
        optionRenderer: styledRenderer,
        backgroundDark: (0, _lib.tooLight)(this.lineColor)
      }));
    }
  }]);

  return LineSelector;
}(_react.Component);

LineSelector.propTypes = _extends({
  computeOptions: _propTypes2.default.func
}, _Dropdown2.default.propTypes);

LineSelector.defaultProps = {
  clearable: false
};

LineSelector.contextTypes = {
  fullContainer: _propTypes2.default.object
};
//# sourceMappingURL=LineSelectors.js.map

/***/ }),

/***/ "6wyt":
/*!*********************************************************!*\
  !*** ./node_modules/codemirror/addon/mode/multiplex.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"));
  else {}
})(function(CodeMirror) {
"use strict";

CodeMirror.multiplexingMode = function(outer /*, others */) {
  // Others should be {open, close, mode [, delimStyle] [, innerStyle]} objects
  var others = Array.prototype.slice.call(arguments, 1);

  function indexOf(string, pattern, from, returnEnd) {
    if (typeof pattern == "string") {
      var found = string.indexOf(pattern, from);
      return returnEnd && found > -1 ? found + pattern.length : found;
    }
    var m = pattern.exec(from ? string.slice(from) : string);
    return m ? m.index + from + (returnEnd ? m[0].length : 0) : -1;
  }

  return {
    startState: function() {
      return {
        outer: CodeMirror.startState(outer),
        innerActive: null,
        inner: null
      };
    },

    copyState: function(state) {
      return {
        outer: CodeMirror.copyState(outer, state.outer),
        innerActive: state.innerActive,
        inner: state.innerActive && CodeMirror.copyState(state.innerActive.mode, state.inner)
      };
    },

    token: function(stream, state) {
      if (!state.innerActive) {
        var cutOff = Infinity, oldContent = stream.string;
        for (var i = 0; i < others.length; ++i) {
          var other = others[i];
          var found = indexOf(oldContent, other.open, stream.pos);
          if (found == stream.pos) {
            if (!other.parseDelimiters) stream.match(other.open);
            state.innerActive = other;

            // Get the outer indent, making sure to handle CodeMirror.Pass
            var outerIndent = 0;
            if (outer.indent) {
              var possibleOuterIndent = outer.indent(state.outer, "");
              if (possibleOuterIndent !== CodeMirror.Pass) outerIndent = possibleOuterIndent;
            }

            state.inner = CodeMirror.startState(other.mode, outerIndent);
            return other.delimStyle && (other.delimStyle + " " + other.delimStyle + "-open");
          } else if (found != -1 && found < cutOff) {
            cutOff = found;
          }
        }
        if (cutOff != Infinity) stream.string = oldContent.slice(0, cutOff);
        var outerToken = outer.token(stream, state.outer);
        if (cutOff != Infinity) stream.string = oldContent;
        return outerToken;
      } else {
        var curInner = state.innerActive, oldContent = stream.string;
        if (!curInner.close && stream.sol()) {
          state.innerActive = state.inner = null;
          return this.token(stream, state);
        }
        var found = curInner.close ? indexOf(oldContent, curInner.close, stream.pos, curInner.parseDelimiters) : -1;
        if (found == stream.pos && !curInner.parseDelimiters) {
          stream.match(curInner.close);
          state.innerActive = state.inner = null;
          return curInner.delimStyle && (curInner.delimStyle + " " + curInner.delimStyle + "-close");
        }
        if (found > -1) stream.string = oldContent.slice(0, found);
        var innerToken = curInner.mode.token(stream, state.inner);
        if (found > -1) stream.string = oldContent;

        if (found == stream.pos && curInner.parseDelimiters)
          state.innerActive = state.inner = null;

        if (curInner.innerStyle) {
          if (innerToken) innerToken = innerToken + " " + curInner.innerStyle;
          else innerToken = curInner.innerStyle;
        }

        return innerToken;
      }
    },

    indent: function(state, textAfter) {
      var mode = state.innerActive ? state.innerActive.mode : outer;
      if (!mode.indent) return CodeMirror.Pass;
      return mode.indent(state.innerActive ? state.inner : state.outer, textAfter);
    },

    blankLine: function(state) {
      var mode = state.innerActive ? state.innerActive.mode : outer;
      if (mode.blankLine) {
        mode.blankLine(state.innerActive ? state.inner : state.outer);
      }
      if (!state.innerActive) {
        for (var i = 0; i < others.length; ++i) {
          var other = others[i];
          if (other.open === "\n") {
            state.innerActive = other;
            state.inner = CodeMirror.startState(other.mode, mode.indent ? mode.indent(state.outer, "") : 0);
          }
        }
      } else if (state.innerActive.close === "\n") {
        state.innerActive = state.inner = null;
      }
    },

    electricChars: outer.electricChars,

    innerMode: function(state) {
      return state.inner ? {state: state.inner, mode: state.innerActive.mode} : {state: state.outer, mode: outer};
    }
  };
};

});


/***/ }),

/***/ "6xfF":
/*!****************************************!*\
  !*** ./node_modules/base16/lib/pop.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'pop',
  author: 'chris kempson (http://chriskempson.com)',
  base00: '#000000',
  base01: '#202020',
  base02: '#303030',
  base03: '#505050',
  base04: '#b0b0b0',
  base05: '#d0d0d0',
  base06: '#e0e0e0',
  base07: '#ffffff',
  base08: '#eb008a',
  base09: '#f29333',
  base0A: '#f8ca12',
  base0B: '#37b349',
  base0C: '#00aabb',
  base0D: '#0e5a94',
  base0E: '#b31e8d',
  base0F: '#7a2d00'
};
module.exports = exports['default'];

/***/ }),

/***/ "6z8e":
/*!************************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/at-rule.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _container = __webpack_require__(/*! ./container */ "+9U2");

var _container2 = _interopRequireDefault(_container);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * Represents an at-rule.
 *
 * If it’s followed in the CSS by a {} block, this node will have
 * a nodes property representing its children.
 *
 * @extends Container
 *
 * @example
 * const root = postcss.parse('@charset "UTF-8"; @media print {}');
 *
 * const charset = root.first;
 * charset.type  //=> 'atrule'
 * charset.nodes //=> undefined
 *
 * const media = root.last;
 * media.nodes   //=> []
 */
var AtRule = function (_Container) {
  _inherits(AtRule, _Container);

  function AtRule(defaults) {
    _classCallCheck(this, AtRule);

    var _this = _possibleConstructorReturn(this, _Container.call(this, defaults));

    _this.type = 'atrule';
    return _this;
  }

  AtRule.prototype.append = function append() {
    var _Container$prototype$;

    if (!this.nodes) this.nodes = [];

    for (var _len = arguments.length, children = Array(_len), _key = 0; _key < _len; _key++) {
      children[_key] = arguments[_key];
    }

    return (_Container$prototype$ = _Container.prototype.append).call.apply(_Container$prototype$, [this].concat(children));
  };

  AtRule.prototype.prepend = function prepend() {
    var _Container$prototype$2;

    if (!this.nodes) this.nodes = [];

    for (var _len2 = arguments.length, children = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      children[_key2] = arguments[_key2];
    }

    return (_Container$prototype$2 = _Container.prototype.prepend).call.apply(_Container$prototype$2, [this].concat(children));
  };

  /**
   * @memberof AtRule#
   * @member {string} name - the at-rule’s name immediately follows the `@`
   *
   * @example
   * const root  = postcss.parse('@media print {}');
   * media.name //=> 'media'
   * const media = root.first;
   */

  /**
   * @memberof AtRule#
   * @member {string} params - the at-rule’s parameters, the values
   *                           that follow the at-rule’s name but precede
   *                           any {} block
   *
   * @example
   * const root  = postcss.parse('@media print, screen {}');
   * const media = root.first;
   * media.params //=> 'print, screen'
   */

  /**
   * @memberof AtRule#
   * @member {object} raws - Information to generate byte-to-byte equal
   *                         node string as it was in the origin input.
   *
   * Every parser saves its own properties,
   * but the default CSS parser uses:
   *
   * * `before`: the space symbols before the node. It also stores `*`
   *   and `_` symbols before the declaration (IE hack).
   * * `after`: the space symbols after the last child of the node
   *   to the end of the node.
   * * `between`: the symbols between the property and value
   *   for declarations, selector and `{` for rules, or last parameter
   *   and `{` for at-rules.
   * * `semicolon`: contains true if the last child has
   *   an (optional) semicolon.
   * * `afterName`: the space between the at-rule name and its parameters.
   *
   * PostCSS cleans at-rule parameters from comments and extra spaces,
   * but it stores origin content in raws properties.
   * As such, if you don’t change a declaration’s value,
   * PostCSS will use the raw value with comments.
   *
   * @example
   * const root = postcss.parse('  @media\nprint {\n}')
   * root.first.first.raws //=> { before: '  ',
   *                       //     between: ' ',
   *                       //     afterName: '\n',
   *                       //     after: '\n' }
   */


  return AtRule;
}(_container2.default);

exports.default = AtRule;
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64, 


/***/ }),

/***/ "7/El":
/*!************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/ColorscalePicker.js ***!
  \************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _reactColorscales = __webpack_require__(/*! react-colorscales */ "FOBs");

var _reactColorscales2 = _interopRequireDefault(_reactColorscales);

var _Dropdown = __webpack_require__(/*! ./Dropdown */ "9Rtb");

var _Dropdown2 = _interopRequireDefault(_Dropdown);

var _Info = __webpack_require__(/*! ../fields/Info */ "iOcY");

var _Info2 = _interopRequireDefault(_Info);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

// CAREFUL: needs to be the same value as $colorscalepicker-width in _colorscalepicker.scss
var colorscalepickerContainerWidth = 240;

var Scale = function (_Component) {
  _inherits(Scale, _Component);

  function Scale(props) {
    _classCallCheck(this, Scale);

    var _this = _possibleConstructorReturn(this, (Scale.__proto__ || Object.getPrototypeOf(Scale)).call(this, props));

    _this.state = {
      selectedColorscaleType: props.initialCategory || 'sequential',
      showColorscalePicker: false
    };

    _this.onChange = _this.onChange.bind(_this);
    _this.onClick = _this.onClick.bind(_this);
    return _this;
  }

  _createClass(Scale, [{
    key: 'onClick',
    value: function onClick() {
      this.setState({
        showColorscalePicker: !this.state.showColorscalePicker
      });
    }
  }, {
    key: 'onChange',
    value: function onChange(selectedColorscaleType) {
      this.setState({ selectedColorscaleType: selectedColorscaleType });
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          onColorscaleChange = _props.onColorscaleChange,
          selected = _props.selected,
          disableCategorySwitch = _props.disableCategorySwitch;
      var _state = this.state,
          selectedColorscaleType = _state.selectedColorscaleType,
          showColorscalePicker = _state.showColorscalePicker;

      var description = _reactColorscales.COLOR_PICKER_CONSTANTS.COLORSCALE_DESCRIPTIONS[selectedColorscaleType];
      var colorscaleOptions = _reactColorscales.COLOR_PICKER_CONSTANTS.COLORSCALE_TYPES.filter(function (type) {
        return type !== 'custom';
      }).map(function (type) {
        return {
          label: type + ' scales',
          value: type
        };
      });
      var _ = this.context.localize;

      return _react2.default.createElement(
        'div',
        { className: 'customPickerContainer' },
        _react2.default.createElement(
          'div',
          { className: 'customPickerContainer__clickable' },
          _react2.default.createElement(_reactColorscales.Colorscale, { colorscale: selected, onClick: this.onClick })
        ),
        showColorscalePicker ? _react2.default.createElement(
          'div',
          { className: 'customPickerContainer__expanded-content' },
          disableCategorySwitch ? null : _react2.default.createElement(_Dropdown2.default, {
            options: colorscaleOptions,
            value: selectedColorscaleType,
            onChange: this.onChange,
            clearable: false,
            searchable: false,
            placeholder: _('Select a Colorscale Type'),
            className: 'customPickerContainer__category-dropdown'
          }),
          description ? _react2.default.createElement(
            'div',
            { className: 'customPickerContainer__palettes' },
            _react2.default.createElement(_reactColorscales2.default, {
              onChange: onColorscaleChange,
              colorscale: selected,
              width: colorscalepickerContainerWidth,
              colorscaleType: this.state.selectedColorscaleType,
              onColorscaleTypeChange: this.onColorscaleTypeChange,
              disableSwatchControls: true,
              scaleLength: 7
            }),
            _react2.default.createElement(
              _Info2.default,
              { className: 'customPickerContainer__info' },
              description
            )
          ) : null
        ) : null
      );
    }
  }]);

  return Scale;
}(_react.Component);

Scale.propTypes = {
  onColorscaleChange: _propTypes2.default.func,
  selected: _propTypes2.default.array,
  label: _propTypes2.default.string,
  initialCategory: _propTypes2.default.string,
  disableCategorySwitch: _propTypes2.default.bool
};

Scale.contextTypes = {
  localize: _propTypes2.default.func
};

exports.default = Scale;
//# sourceMappingURL=ColorscalePicker.js.map

/***/ }),

/***/ "711d":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_baseProperty.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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];
  };
}

module.exports = baseProperty;


/***/ }),

/***/ "74Od":
/*!*************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/mod.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



/**
 * sanitized modulus function that always returns in the range [0, d)
 * rather than (-d, 0] if v is negative
 */
function mod(v, d) {
    var out = v % d;
    return out < 0 ? out + d : out;
}

/**
 * sanitized modulus function that always returns in the range [-d/2, d/2]
 * rather than (-d, 0] if v is negative
 */
function modHalf(v, d) {
    return Math.abs(v) > (d / 2) ?
        v - Math.round(v / d) * d :
        v;
}

module.exports = {
    mod: mod,
    modHalf: modHalf
};


/***/ }),

/***/ "75di":
/*!************************************************************!*\
  !*** ./node_modules/@jupyterlab/rendermime/lib/widgets.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const renderers = __importStar(__webpack_require__(/*! ./renderers */ "A1bG"));
/**
 * A common base class for mime renderers.
 */
class RenderedCommon extends widgets_1.Widget {
    /**
     * Construct a new rendered common widget.
     *
     * @param options - The options for initializing the widget.
     */
    constructor(options) {
        super();
        this.mimeType = options.mimeType;
        this.sanitizer = options.sanitizer;
        this.resolver = options.resolver;
        this.linkHandler = options.linkHandler;
        this.latexTypesetter = options.latexTypesetter;
        this.node.dataset['mimeType'] = this.mimeType;
    }
    /**
     * Render a mime model.
     *
     * @param model - The mime model to render.
     *
     * @returns A promise which resolves when rendering is complete.
     */
    renderModel(model) {
        // TODO compare model against old model for early bail?
        // Toggle the trusted class on the widget.
        this.toggleClass('jp-mod-trusted', model.trusted);
        // Render the actual content.
        return this.render(model);
    }
}
exports.RenderedCommon = RenderedCommon;
/**
 * A common base class for HTML mime renderers.
 */
class RenderedHTMLCommon extends RenderedCommon {
    /**
     * Construct a new rendered HTML common widget.
     *
     * @param options - The options for initializing the widget.
     */
    constructor(options) {
        super(options);
        this.addClass('jp-RenderedHTMLCommon');
    }
}
exports.RenderedHTMLCommon = RenderedHTMLCommon;
/**
 * A mime renderer for displaying HTML and math.
 */
class RenderedHTML extends RenderedHTMLCommon {
    /**
     * Construct a new rendered HTML widget.
     *
     * @param options - The options for initializing the widget.
     */
    constructor(options) {
        super(options);
        this.addClass('jp-RenderedHTML');
    }
    /**
     * Render a mime model.
     *
     * @param model - The mime model to render.
     *
     * @returns A promise which resolves when rendering is complete.
     */
    render(model) {
        return renderers.renderHTML({
            host: this.node,
            source: String(model.data[this.mimeType]),
            trusted: model.trusted,
            resolver: this.resolver,
            sanitizer: this.sanitizer,
            linkHandler: this.linkHandler,
            shouldTypeset: this.isAttached,
            latexTypesetter: this.latexTypesetter
        });
    }
    /**
     * A message handler invoked on an `'after-attach'` message.
     */
    onAfterAttach(msg) {
        if (this.latexTypesetter) {
            this.latexTypesetter.typeset(this.node);
        }
    }
}
exports.RenderedHTML = RenderedHTML;
/**
 * A mime renderer for displaying LaTeX output.
 */
class RenderedLatex extends RenderedCommon {
    /**
     * Construct a new rendered LaTeX widget.
     *
     * @param options - The options for initializing the widget.
     */
    constructor(options) {
        super(options);
        this.addClass('jp-RenderedLatex');
    }
    /**
     * Render a mime model.
     *
     * @param model - The mime model to render.
     *
     * @returns A promise which resolves when rendering is complete.
     */
    render(model) {
        return renderers.renderLatex({
            host: this.node,
            source: String(model.data[this.mimeType]),
            shouldTypeset: this.isAttached,
            latexTypesetter: this.latexTypesetter
        });
    }
    /**
     * A message handler invoked on an `'after-attach'` message.
     */
    onAfterAttach(msg) {
        if (this.latexTypesetter) {
            this.latexTypesetter.typeset(this.node);
        }
    }
}
exports.RenderedLatex = RenderedLatex;
/**
 * A mime renderer for displaying images.
 */
class RenderedImage extends RenderedCommon {
    /**
     * Construct a new rendered image widget.
     *
     * @param options - The options for initializing the widget.
     */
    constructor(options) {
        super(options);
        this.addClass('jp-RenderedImage');
    }
    /**
     * Render a mime model.
     *
     * @param model - The mime model to render.
     *
     * @returns A promise which resolves when rendering is complete.
     */
    render(model) {
        let metadata = model.metadata[this.mimeType];
        return renderers.renderImage({
            host: this.node,
            mimeType: this.mimeType,
            source: String(model.data[this.mimeType]),
            width: metadata && metadata.width,
            height: metadata && metadata.height,
            needsBackground: model.metadata['needs_background'],
            unconfined: metadata && metadata.unconfined
        });
    }
}
exports.RenderedImage = RenderedImage;
/**
 * A mime renderer for displaying Markdown with embedded latex.
 */
class RenderedMarkdown extends RenderedHTMLCommon {
    /**
     * Construct a new rendered markdown widget.
     *
     * @param options - The options for initializing the widget.
     */
    constructor(options) {
        super(options);
        this.addClass('jp-RenderedMarkdown');
    }
    /**
     * Render a mime model.
     *
     * @param model - The mime model to render.
     *
     * @returns A promise which resolves when rendering is complete.
     */
    render(model) {
        return renderers.renderMarkdown({
            host: this.node,
            source: String(model.data[this.mimeType]),
            trusted: model.trusted,
            resolver: this.resolver,
            sanitizer: this.sanitizer,
            linkHandler: this.linkHandler,
            shouldTypeset: this.isAttached,
            latexTypesetter: this.latexTypesetter
        });
    }
    /**
     * A message handler invoked on an `'after-attach'` message.
     */
    onAfterAttach(msg) {
        if (this.latexTypesetter) {
            this.latexTypesetter.typeset(this.node);
        }
    }
}
exports.RenderedMarkdown = RenderedMarkdown;
/**
 * A widget for displaying SVG content.
 */
class RenderedSVG extends RenderedCommon {
    /**
     * Construct a new rendered SVG widget.
     *
     * @param options - The options for initializing the widget.
     */
    constructor(options) {
        super(options);
        this.addClass('jp-RenderedSVG');
    }
    /**
     * Render a mime model.
     *
     * @param model - The mime model to render.
     *
     * @returns A promise which resolves when rendering is complete.
     */
    render(model) {
        let metadata = model.metadata[this.mimeType];
        return renderers.renderSVG({
            host: this.node,
            source: String(model.data[this.mimeType]),
            trusted: model.trusted,
            unconfined: metadata && metadata.unconfined
        });
    }
    /**
     * A message handler invoked on an `'after-attach'` message.
     */
    onAfterAttach(msg) {
        if (this.latexTypesetter) {
            this.latexTypesetter.typeset(this.node);
        }
    }
}
exports.RenderedSVG = RenderedSVG;
/**
 * A widget for displaying plain text and console text.
 */
class RenderedText extends RenderedCommon {
    /**
     * Construct a new rendered text widget.
     *
     * @param options - The options for initializing the widget.
     */
    constructor(options) {
        super(options);
        this.addClass('jp-RenderedText');
    }
    /**
     * Render a mime model.
     *
     * @param model - The mime model to render.
     *
     * @returns A promise which resolves when rendering is complete.
     */
    render(model) {
        return renderers.renderText({
            host: this.node,
            source: String(model.data[this.mimeType])
        });
    }
}
exports.RenderedText = RenderedText;
/**
 * A widget for displaying deprecated JavaScript output.
 */
class RenderedJavaScript extends RenderedCommon {
    /**
     * Construct a new rendered text widget.
     *
     * @param options - The options for initializing the widget.
     */
    constructor(options) {
        super(options);
        this.addClass('jp-RenderedJavaScript');
    }
    /**
     * Render a mime model.
     *
     * @param model - The mime model to render.
     *
     * @returns A promise which resolves when rendering is complete.
     */
    render(model) {
        return renderers.renderText({
            host: this.node,
            source: 'JavaScript output is disabled in JupyterLab'
        });
    }
}
exports.RenderedJavaScript = RenderedJavaScript;


/***/ }),

/***/ "77Zs":
/*!********************************************!*\
  !*** ./node_modules/lodash/_stackClear.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var ListCache = __webpack_require__(/*! ./_ListCache */ "Xi7e");

/**
 * Removes all key-value entries from the stack.
 *
 * @private
 * @name clear
 * @memberOf Stack
 */
function stackClear() {
  this.__data__ = new ListCache;
  this.size = 0;
}

module.exports = stackClear;


/***/ }),

/***/ "78yt":
/*!********************************************************!*\
  !*** ./node_modules/@jupyterlab/launcher/lib/index.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const disposable_1 = __webpack_require__(/*! @phosphor/disposable */ "uNUc");
const properties_1 = __webpack_require__(/*! @phosphor/properties */ "3kwb");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const React = __importStar(__webpack_require__(/*! react */ "q1tI"));
__webpack_require__(/*! ../style/index.css */ "D9OR");
/**
 * The class name added to Launcher instances.
 */
const LAUNCHER_CLASS = 'jp-Launcher';
/**
 * The known categories of launcher items and their default ordering.
 */
const KNOWN_CATEGORIES = ['Notebook', 'Console', 'Other'];
/**
 * These launcher item categories are known to have kernels, so the kernel icons
 * are used.
 */
const KERNEL_CATEGORIES = ['Notebook', 'Console'];
/* tslint:disable */
/**
 * The launcher token.
 */
exports.ILauncher = new coreutils_1.Token('@jupyterlab/launcher:ILauncher');
/**
 * LauncherModel keeps track of the path to working directory and has a list of
 * LauncherItems, which the Launcher will render.
 */
class LauncherModel extends apputils_1.VDomModel {
    /**
     * Create a new launcher model.
     */
    constructor() {
        super();
        this._items = [];
    }
    /**
     * Add a command item to the launcher, and trigger re-render event for parent
     * widget.
     *
     * @param options - The specification options for a launcher item.
     *
     * @returns A disposable that will remove the item from Launcher, and trigger
     * re-render event for parent widget.
     *
     */
    add(options) {
        // Create a copy of the options to circumvent mutations to the original.
        let item = Private.createItem(options);
        this._items.push(item);
        this.stateChanged.emit(void 0);
        return new disposable_1.DisposableDelegate(() => {
            algorithm_1.ArrayExt.removeFirstOf(this._items, item);
            this.stateChanged.emit(void 0);
        });
    }
    /**
     * Return an iterator of launcher items.
     */
    items() {
        return new algorithm_1.ArrayIterator(this._items);
    }
}
exports.LauncherModel = LauncherModel;
/**
 * A virtual-DOM-based widget for the Launcher.
 */
class Launcher extends apputils_1.VDomRenderer {
    /**
     * Construct a new launcher widget.
     */
    constructor(options) {
        super();
        this._pending = false;
        this._cwd = '';
        this._cwd = options.cwd;
        this._callback = options.callback;
        this._commands = options.commands;
        this.addClass(LAUNCHER_CLASS);
    }
    /**
     * The cwd of the launcher.
     */
    get cwd() {
        return this._cwd;
    }
    set cwd(value) {
        this._cwd = value;
        this.update();
    }
    /**
     * Whether there is a pending item being launched.
     */
    get pending() {
        return this._pending;
    }
    set pending(value) {
        this._pending = value;
    }
    /**
     * Render the launcher to virtual DOM nodes.
     */
    render() {
        // Bail if there is no model.
        if (!this.model) {
            return null;
        }
        // First group-by categories
        let categories = Object.create(null);
        algorithm_1.each(this.model.items(), (item, index) => {
            let cat = item.category || 'Other';
            if (!(cat in categories)) {
                categories[cat] = [];
            }
            categories[cat].push(item);
        });
        // Within each category sort by rank
        for (let cat in categories) {
            categories[cat] = categories[cat].sort((a, b) => {
                return Private.sortCmp(a, b, this._cwd, this._commands);
            });
        }
        // Variable to help create sections
        let sections = [];
        let section;
        // Assemble the final ordered list of categories, beginning with
        // KNOWN_CATEGORIES.
        let orderedCategories = [];
        algorithm_1.each(KNOWN_CATEGORIES, (cat, index) => {
            orderedCategories.push(cat);
        });
        for (let cat in categories) {
            if (KNOWN_CATEGORIES.indexOf(cat) === -1) {
                orderedCategories.push(cat);
            }
        }
        // Now create the sections for each category
        orderedCategories.forEach(cat => {
            const item = categories[cat][0];
            let iconClass = `${this._commands.iconClass(item.command, Object.assign({}, item.args, { cwd: this.cwd }))} ` + 'jp-Launcher-sectionIcon jp-Launcher-icon';
            let kernel = KERNEL_CATEGORIES.indexOf(cat) > -1;
            if (cat in categories) {
                section = (React.createElement("div", { className: "jp-Launcher-section", key: cat },
                    React.createElement("div", { className: "jp-Launcher-sectionHeader" },
                        kernel && React.createElement("div", { className: iconClass }),
                        React.createElement("h2", { className: "jp-Launcher-sectionTitle" }, cat)),
                    React.createElement("div", { className: "jp-Launcher-cardContainer" }, algorithm_1.toArray(algorithm_1.map(categories[cat], (item) => {
                        return Card(kernel, item, this, this._commands, this._callback);
                    })))));
                sections.push(section);
            }
        });
        // Wrap the sections in body and content divs.
        return (React.createElement("div", { className: "jp-Launcher-body" },
            React.createElement("div", { className: "jp-Launcher-content" },
                React.createElement("div", { className: "jp-Launcher-cwd" },
                    React.createElement("h3", null, this.cwd)),
                sections)));
    }
}
exports.Launcher = Launcher;
/**
 * A pure tsx component for a launcher card.
 *
 * @param kernel - whether the item takes uses a kernel.
 *
 * @param item - the launcher item to render.
 *
 * @param launcher - the Launcher instance to which this is added.
 *
 * @param launcherCallback - a callback to call after an item has been launched.
 *
 * @returns a vdom `VirtualElement` for the launcher card.
 */
function Card(kernel, item, launcher, commands, launcherCallback) {
    // Get some properties of the command
    const command = item.command;
    const args = Object.assign({}, item.args, { cwd: launcher.cwd });
    const label = commands.label(command, args);
    // Build the onclick handler.
    let onclick = () => {
        // If an item has already been launched,
        // don't try to launch another.
        if (launcher.pending === true) {
            return;
        }
        launcher.pending = true;
        commands
            .execute(command, Object.assign({}, item.args, { cwd: launcher.cwd }))
            .then(value => {
            launcher.pending = false;
            if (value instanceof widgets_1.Widget) {
                launcherCallback(value);
                launcher.dispose();
            }
        })
            .catch(err => {
            launcher.pending = false;
            apputils_1.showErrorMessage('Launcher Error', err);
        });
    };
    // Return the VDOM element.
    return (React.createElement("div", { className: "jp-LauncherCard", title: label, onClick: onclick, "data-category": item.category || 'Other', key: Private.keyProperty.get(item) },
        React.createElement("div", { className: "jp-LauncherCard-icon" },
            item.kernelIconUrl &&
                kernel && (React.createElement("img", { src: item.kernelIconUrl, className: "jp-Launcher-kernelIcon" })),
            !item.kernelIconUrl &&
                !kernel && (React.createElement("div", { className: `${commands.iconClass(command, args)} jp-Launcher-icon` })),
            !item.kernelIconUrl &&
                kernel && (React.createElement("div", { className: "jp-LauncherCard-noKernelIcon" }, label[0].toUpperCase()))),
        React.createElement("div", { className: "jp-LauncherCard-label", title: label }, label)));
}
/**
 * The namespace for module private data.
 */
var Private;
(function (Private) {
    /**
     * An incrementing counter for keys.
     */
    let id = 0;
    /**
     * An attached property for an item's key.
     */
    Private.keyProperty = new properties_1.AttachedProperty({
        name: 'key',
        create: () => id++
    });
    /**
     * Create a fully specified item given item options.
     */
    function createItem(options) {
        return Object.assign({}, options, { category: options.category || '', rank: options.rank !== undefined ? options.rank : Infinity });
    }
    Private.createItem = createItem;
    /**
     * A sort comparison function for a launcher item.
     */
    function sortCmp(a, b, cwd, commands) {
        // First, compare by rank.
        let r1 = a.rank;
        let r2 = b.rank;
        if (r1 !== r2 && r1 !== undefined && r2 !== undefined) {
            return r1 < r2 ? -1 : 1; // Infinity safe
        }
        // Finally, compare by display name.
        const aLabel = commands.label(a.command, Object.assign({}, a.args, { cwd }));
        const bLabel = commands.label(b.command, Object.assign({}, b.args, { cwd }));
        return aLabel.localeCompare(bLabel);
    }
    Private.sortCmp = sortCmp;
})(Private || (Private = {}));


/***/ }),

/***/ "7BjC":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/et.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


function processRelativeTime(number, withoutSuffix, key, isFuture) {
    var format = {
        's' : ['mõne sekundi', 'mõni sekund', 'paar sekundit'],
        'ss': [number + 'sekundi', number + 'sekundit'],
        'm' : ['ühe minuti', 'üks minut'],
        'mm': [number + ' minuti', number + ' minutit'],
        'h' : ['ühe tunni', 'tund aega', 'üks tund'],
        'hh': [number + ' tunni', number + ' tundi'],
        'd' : ['ühe päeva', 'üks päev'],
        'M' : ['kuu aja', 'kuu aega', 'üks kuu'],
        'MM': [number + ' kuu', number + ' kuud'],
        'y' : ['ühe aasta', 'aasta', 'üks aasta'],
        'yy': [number + ' aasta', number + ' aastat']
    };
    if (withoutSuffix) {
        return format[key][2] ? format[key][2] : format[key][1];
    }
    return isFuture ? format[key][0] : format[key][1];
}

var et = moment.defineLocale('et', {
    months        : 'jaanuar_veebruar_märts_aprill_mai_juuni_juuli_august_september_oktoober_november_detsember'.split('_'),
    monthsShort   : 'jaan_veebr_märts_apr_mai_juuni_juuli_aug_sept_okt_nov_dets'.split('_'),
    weekdays      : 'pühapäev_esmaspäev_teisipäev_kolmapäev_neljapäev_reede_laupäev'.split('_'),
    weekdaysShort : 'P_E_T_K_N_R_L'.split('_'),
    weekdaysMin   : 'P_E_T_K_N_R_L'.split('_'),
    longDateFormat : {
        LT   : 'H:mm',
        LTS : 'H:mm:ss',
        L    : 'DD.MM.YYYY',
        LL   : 'D. MMMM YYYY',
        LLL  : 'D. MMMM YYYY H:mm',
        LLLL : 'dddd, D. MMMM YYYY H:mm'
    },
    calendar : {
        sameDay  : '[Täna,] LT',
        nextDay  : '[Homme,] LT',
        nextWeek : '[Järgmine] dddd LT',
        lastDay  : '[Eile,] LT',
        lastWeek : '[Eelmine] dddd LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : '%s pärast',
        past   : '%s tagasi',
        s      : processRelativeTime,
        ss     : processRelativeTime,
        m      : processRelativeTime,
        mm     : processRelativeTime,
        h      : processRelativeTime,
        hh     : processRelativeTime,
        d      : processRelativeTime,
        dd     : '%d päeva',
        M      : processRelativeTime,
        MM     : processRelativeTime,
        y      : processRelativeTime,
        yy     : processRelativeTime
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return et;

})));


/***/ }),

/***/ "7CC7":
/*!**************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/matrix.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/





exports.init2dArray = function(rowLength, colLength) {
    var array = new Array(rowLength);
    for(var i = 0; i < rowLength; i++) array[i] = new Array(colLength);
    return array;
};

/**
 * transpose a (possibly ragged) 2d array z. inspired by
 * http://stackoverflow.com/questions/17428587/
 * transposing-a-2d-array-in-javascript
 */
exports.transposeRagged = function(z) {
    var maxlen = 0;
    var zlen = z.length;
    var i, j;
    // Maximum row length:
    for(i = 0; i < zlen; i++) maxlen = Math.max(maxlen, z[i].length);

    var t = new Array(maxlen);
    for(i = 0; i < maxlen; i++) {
        t[i] = new Array(zlen);
        for(j = 0; j < zlen; j++) t[i][j] = z[j][i];
    }

    return t;
};

// our own dot function so that we don't need to include numeric
exports.dot = function(x, y) {
    if(!(x.length && y.length) || x.length !== y.length) return null;

    var len = x.length;
    var out;
    var i;

    if(x[0].length) {
        // mat-vec or mat-mat
        out = new Array(len);
        for(i = 0; i < len; i++) out[i] = exports.dot(x[i], y);
    }
    else if(y[0].length) {
        // vec-mat
        var yTranspose = exports.transposeRagged(y);
        out = new Array(yTranspose.length);
        for(i = 0; i < yTranspose.length; i++) out[i] = exports.dot(x, yTranspose[i]);
    }
    else {
        // vec-vec
        out = 0;
        for(i = 0; i < len; i++) out += x[i] * y[i];
    }

    return out;
};

// translate by (x,y)
exports.translationMatrix = function(x, y) {
    return [[1, 0, x], [0, 1, y], [0, 0, 1]];
};

// rotate by alpha around (0,0)
exports.rotationMatrix = function(alpha) {
    var a = alpha * Math.PI / 180;
    return [[Math.cos(a), -Math.sin(a), 0],
            [Math.sin(a), Math.cos(a), 0],
            [0, 0, 1]];
};

// rotate by alpha around (x,y)
exports.rotationXYMatrix = function(a, x, y) {
    return exports.dot(
        exports.dot(exports.translationMatrix(x, y),
                    exports.rotationMatrix(a)),
        exports.translationMatrix(-x, -y));
};

// applies a 2D transformation matrix to either x and y params or an [x,y] array
exports.apply2DTransform = function(transform) {
    return function() {
        var args = arguments;
        if(args.length === 3) {
            args = args[0];
        }// from map
        var xy = arguments.length === 1 ? args[0] : [args[0], args[1]];
        return exports.dot(transform, [xy[0], xy[1], 1]).slice(0, 2);
    };
};

// applies a 2D transformation matrix to an [x1,y1,x2,y2] array (to transform a segment)
exports.apply2DTransform2 = function(transform) {
    var at = exports.apply2DTransform(transform);
    return function(xys) {
        return at(xys.slice(0, 2)).concat(at(xys.slice(2, 4)));
    };
};


/***/ }),

/***/ "7GkX":
/*!*************************************!*\
  !*** ./node_modules/lodash/keys.js ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var arrayLikeKeys = __webpack_require__(/*! ./_arrayLikeKeys */ "b80T"),
    baseKeys = __webpack_require__(/*! ./_baseKeys */ "A90E"),
    isArrayLike = __webpack_require__(/*! ./isArrayLike */ "MMmD");

/**
 * 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);
}

module.exports = keys;


/***/ }),

/***/ "7Ix3":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_nativeKeysIn.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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;
}

module.exports = nativeKeysIn;


/***/ }),

/***/ "7KeA":
/*!***************************************************!*\
  !*** ./node_modules/base16/lib/atelier-forest.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'atelier forest',
  author: 'bram de haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/forest)',
  base00: '#1b1918',
  base01: '#2c2421',
  base02: '#68615e',
  base03: '#766e6b',
  base04: '#9c9491',
  base05: '#a8a19f',
  base06: '#e6e2e0',
  base07: '#f1efee',
  base08: '#f22c40',
  base09: '#df5320',
  base0A: '#d5911a',
  base0B: '#5ab738',
  base0C: '#00ad9c',
  base0D: '#407ee7',
  base0E: '#6666ea',
  base0F: '#c33ff3'
};
module.exports = exports['default'];

/***/ }),

/***/ "7VUJ":
/*!**********************************************************!*\
  !*** ./node_modules/@jupyterlab/completer/lib/widget.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const domutils_1 = __webpack_require__(/*! @phosphor/domutils */ "XWTc");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
/**
 * The class name added to completer menu items.
 */
const ITEM_CLASS = 'jp-Completer-item';
/**
 * The class name added to an active completer menu item.
 */
const ACTIVE_CLASS = 'jp-mod-active';
/**
 * The minimum height of a completer widget.
 */
const MIN_HEIGHT = 20;
/**
 * The maximum height of a completer widget.
 */
const MAX_HEIGHT = 200;
/**
 * A flag to indicate that event handlers are caught in the capture phase.
 */
const USE_CAPTURE = true;
/**
 * The number of colors defined for the completer type annotations.
 * These are listed in completer/style/index.css#102-152.
 */
const N_COLORS = 10;
/**
 * A widget that enables text completion.
 */
class Completer extends widgets_1.Widget {
    /**
     * Construct a text completer menu widget.
     */
    constructor(options) {
        super({ node: document.createElement('ul') });
        this._activeIndex = 0;
        this._editor = null;
        this._model = null;
        this._renderer = null;
        this._resetFlag = false;
        this._selected = new signaling_1.Signal(this);
        this._visibilityChanged = new signaling_1.Signal(this);
        this._renderer = options.renderer || Completer.defaultRenderer;
        this.model = options.model || null;
        this.editor = options.editor || null;
        this.addClass('jp-Completer');
    }
    /**
     * The editor used by the completion widget.
     */
    get editor() {
        return this._editor;
    }
    set editor(newValue) {
        this._editor = newValue;
    }
    /**
     * A signal emitted when a selection is made from the completer menu.
     */
    get selected() {
        return this._selected;
    }
    /**
     * A signal emitted when the completer widget's visibility changes.
     *
     * #### Notes
     * This signal is useful when there are multiple floating widgets that may
     * contend with the same space and ought to be mutually exclusive.
     */
    get visibilityChanged() {
        return this._visibilityChanged;
    }
    /**
     * The model used by the completer widget.
     */
    get model() {
        return this._model;
    }
    set model(model) {
        if ((!model && !this._model) || model === this._model) {
            return;
        }
        if (this._model) {
            this._model.stateChanged.disconnect(this.onModelStateChanged, this);
        }
        this._model = model;
        if (this._model) {
            this._model.stateChanged.connect(this.onModelStateChanged, this);
        }
    }
    /**
     * Dispose of the resources held by the completer widget.
     */
    dispose() {
        this._model = null;
        super.dispose();
    }
    /**
     * Handle the DOM events for the widget.
     *
     * @param event - The DOM event sent to the widget.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the dock panel's node. It should
     * not be called directly by user code.
     */
    handleEvent(event) {
        if (this.isHidden || !this._editor) {
            return;
        }
        switch (event.type) {
            case 'keydown':
                this._evtKeydown(event);
                break;
            case 'mousedown':
                this._evtMousedown(event);
                break;
            case 'scroll':
                this._evtScroll(event);
                break;
            default:
                break;
        }
    }
    /**
     * Reset the widget.
     */
    reset() {
        this._activeIndex = 0;
        if (this._model) {
            this._model.reset(true);
        }
    }
    /**
     * Emit the selected signal for the current active item and reset.
     */
    selectActive() {
        let active = this.node.querySelector(`.${ACTIVE_CLASS}`);
        if (!active) {
            this.reset();
            return;
        }
        this._selected.emit(active.getAttribute('data-value'));
        this.reset();
    }
    /**
     * Handle `after-attach` messages for the widget.
     */
    onAfterAttach(msg) {
        document.addEventListener('keydown', this, USE_CAPTURE);
        document.addEventListener('mousedown', this, USE_CAPTURE);
        document.addEventListener('scroll', this, USE_CAPTURE);
    }
    /**
     * Handle `before-detach` messages for the widget.
     */
    onBeforeDetach(msg) {
        document.removeEventListener('keydown', this, USE_CAPTURE);
        document.removeEventListener('mousedown', this, USE_CAPTURE);
        document.removeEventListener('scroll', this, USE_CAPTURE);
    }
    /**
     * Handle model state changes.
     */
    onModelStateChanged() {
        if (this.isAttached) {
            this._activeIndex = 0;
            this.update();
        }
    }
    /**
     * Handle `update-request` messages.
     */
    onUpdateRequest(msg) {
        const model = this._model;
        if (!model) {
            return;
        }
        if (this._resetFlag) {
            this._resetFlag = false;
            if (!this.isHidden) {
                this.hide();
                this._visibilityChanged.emit(undefined);
            }
            return;
        }
        let items = algorithm_1.toArray(model.items());
        // If there are no items, reset and bail.
        if (!items || !items.length) {
            this._resetFlag = true;
            this.reset();
            if (!this.isHidden) {
                this.hide();
                this._visibilityChanged.emit(undefined);
            }
            return;
        }
        // If there is only one item, signal and bail.
        if (items.length === 1) {
            this._selected.emit(items[0].raw);
            this.reset();
            return;
        }
        // Clear the node.
        let node = this.node;
        node.textContent = '';
        // Compute an ordered list of all the types in the typeMap, this is computed
        // once by the model each time new data arrives for efficiency.
        let orderedTypes = model.orderedTypes();
        // Populate the completer items.
        for (let item of items) {
            let li = this._renderer.createItemNode(item, model.typeMap(), orderedTypes);
            node.appendChild(li);
        }
        let active = node.querySelectorAll(`.${ITEM_CLASS}`)[this._activeIndex];
        active.classList.add(ACTIVE_CLASS);
        // If this is the first time the current completer session has loaded,
        // populate any initial subset match.
        if (model.subsetMatch) {
            const populated = this._populateSubset();
            model.subsetMatch = false;
            if (populated) {
                this.update();
                return;
            }
        }
        if (this.isHidden) {
            this.show();
            this._setGeometry();
            this._visibilityChanged.emit(undefined);
        }
        else {
            this._setGeometry();
        }
    }
    /**
     * Cycle through the available completer items.
     *
     * #### Notes
     * When the user cycles all the way `down` to the last index, subsequent
     * `down` cycles will remain on the last index. When the user cycles `up` to
     * the first item, subsequent `up` cycles will remain on the first cycle.
     */
    _cycle(direction) {
        let items = this.node.querySelectorAll(`.${ITEM_CLASS}`);
        let index = this._activeIndex;
        let active = this.node.querySelector(`.${ACTIVE_CLASS}`);
        active.classList.remove(ACTIVE_CLASS);
        if (direction === 'up') {
            this._activeIndex = index === 0 ? index : index - 1;
        }
        else {
            this._activeIndex = index < items.length - 1 ? index + 1 : index;
        }
        active = items[this._activeIndex];
        active.classList.add(ACTIVE_CLASS);
        domutils_1.ElementExt.scrollIntoViewIfNeeded(this.node, active);
    }
    /**
     * Handle keydown events for the widget.
     */
    _evtKeydown(event) {
        if (this.isHidden || !this._editor) {
            return;
        }
        if (!this._editor.host.contains(event.target)) {
            this.reset();
            return;
        }
        switch (event.keyCode) {
            case 9: // Tab key
                event.preventDefault();
                event.stopPropagation();
                event.stopImmediatePropagation();
                let model = this._model;
                if (!model) {
                    return;
                }
                model.subsetMatch = true;
                let populated = this._populateSubset();
                model.subsetMatch = false;
                if (populated) {
                    return;
                }
                this.selectActive();
                return;
            case 27: // Esc key
                event.preventDefault();
                event.stopPropagation();
                event.stopImmediatePropagation();
                this.reset();
                return;
            case 38: // Up arrow key
            case 40: // Down arrow key
                event.preventDefault();
                event.stopPropagation();
                event.stopImmediatePropagation();
                this._cycle(event.keyCode === 38 ? 'up' : 'down');
                return;
            default:
                return;
        }
    }
    /**
     * Handle mousedown events for the widget.
     */
    _evtMousedown(event) {
        if (this.isHidden || !this._editor) {
            return;
        }
        if (Private.nonstandardClick(event)) {
            this.reset();
            return;
        }
        let target = event.target;
        while (target !== document.documentElement) {
            // If the user has made a selection, emit its value and reset the widget.
            if (target.classList.contains(ITEM_CLASS)) {
                event.preventDefault();
                event.stopPropagation();
                event.stopImmediatePropagation();
                this._selected.emit(target.getAttribute('data-value'));
                this.reset();
                return;
            }
            // If the mouse event happened anywhere else in the widget, bail.
            if (target === this.node) {
                event.preventDefault();
                event.stopPropagation();
                event.stopImmediatePropagation();
                return;
            }
            target = target.parentElement;
        }
        this.reset();
    }
    /**
     * Handle scroll events for the widget
     */
    _evtScroll(event) {
        if (this.isHidden || !this._editor) {
            return;
        }
        const { node } = this;
        // All scrolls except scrolls in the actual hover box node may cause the
        // referent editor that anchors the node to move, so the only scroll events
        // that can safely be ignored are ones that happen inside the hovering node.
        if (node.contains(event.target)) {
            return;
        }
        // Set the geometry of the node asynchronously.
        requestAnimationFrame(() => {
            this._setGeometry();
        });
    }
    /**
     * Populate the completer up to the longest initial subset of items.
     *
     * @returns `true` if a subset match was found and populated.
     */
    _populateSubset() {
        const { model } = this;
        if (!model) {
            return false;
        }
        const items = this.node.querySelectorAll(`.${ITEM_CLASS}`);
        const subset = Private.commonSubset(Private.itemValues(items));
        const { query } = model;
        // If a common subset exists and it is not the current query, highlight it.
        if (subset && subset !== query && subset.indexOf(query) === 0) {
            model.query = subset;
            return true;
        }
        return false;
    }
    /**
     * Set the visible dimensions of the widget.
     */
    _setGeometry() {
        const { node } = this;
        const model = this._model;
        const editor = this._editor;
        // This is an overly defensive test: `cursor` will always exist if
        // `original` exists, except in contrived tests. But since it is possible
        // to generate a runtime error, the check occurs here.
        if (!editor || !model || !model.original || !model.cursor) {
            return;
        }
        const start = model.cursor.start;
        const position = editor.getPositionAt(start);
        const anchor = editor.getCoordinateForPosition(position);
        const style = window.getComputedStyle(node);
        const borderLeft = parseInt(style.borderLeftWidth, 10) || 0;
        const paddingLeft = parseInt(style.paddingLeft, 10) || 0;
        // Calculate the geometry of the completer.
        apputils_1.HoverBox.setGeometry({
            anchor,
            host: editor.host,
            maxHeight: MAX_HEIGHT,
            minHeight: MIN_HEIGHT,
            node: node,
            offset: { horizontal: borderLeft + paddingLeft },
            privilege: 'below',
            style: style
        });
    }
}
exports.Completer = Completer;
(function (Completer) {
    /**
     * The default implementation of an `IRenderer`.
     */
    class Renderer {
        /**
         * Create an item node for a text completer menu.
         */
        createItemNode(item, typeMap, orderedTypes) {
            let li = document.createElement('li');
            li.className = ITEM_CLASS;
            // Set the raw, un-marked up value as a data attribute.
            li.setAttribute('data-value', item.raw);
            let matchNode = document.createElement('code');
            matchNode.className = 'jp-Completer-match';
            // Use innerHTML because search results include <mark> tags.
            matchNode.innerHTML = apputils_1.defaultSanitizer.sanitize(item.text, {
                allowedTags: ['mark']
            });
            // If there are types provided add those.
            if (!coreutils_1.JSONExt.deepEqual(typeMap, {})) {
                let typeNode = document.createElement('span');
                let type = typeMap[item.raw] || '';
                typeNode.textContent = (type[0] || '').toLowerCase();
                let colorIndex = (orderedTypes.indexOf(type) % N_COLORS) + 1;
                typeNode.className = 'jp-Completer-type';
                typeNode.setAttribute(`data-color-index`, colorIndex.toString());
                li.title = type;
                let typeExtendedNode = document.createElement('code');
                typeExtendedNode.className = 'jp-Completer-typeExtended';
                typeExtendedNode.textContent = type.toLocaleLowerCase();
                li.appendChild(typeNode);
                li.appendChild(matchNode);
                li.appendChild(typeExtendedNode);
            }
            else {
                li.appendChild(matchNode);
            }
            return li;
        }
    }
    Completer.Renderer = Renderer;
    /**
     * The default `IRenderer` instance.
     */
    Completer.defaultRenderer = new Renderer();
})(Completer = exports.Completer || (exports.Completer = {}));
/**
 * A namespace for completer widget private data.
 */
var Private;
(function (Private) {
    /**
     * Returns the common subset string that a list of strings shares.
     */
    function commonSubset(values) {
        let len = values.length;
        let subset = '';
        if (len < 2) {
            return subset;
        }
        let strlen = values[0].length;
        for (let i = 0; i < strlen; i++) {
            let ch = values[0][i];
            for (let j = 1; j < len; j++) {
                if (values[j][i] !== ch) {
                    return subset;
                }
            }
            subset += ch;
        }
        return subset;
    }
    Private.commonSubset = commonSubset;
    /**
     * Returns the list of raw item values currently in the DOM.
     */
    function itemValues(items) {
        let values = [];
        for (let i = 0, len = items.length; i < len; i++) {
            values.push(items[i].getAttribute('data-value'));
        }
        return values;
    }
    Private.itemValues = itemValues;
    /**
     * Returns true for any modified click event (i.e., not a left-click).
     */
    function nonstandardClick(event) {
        return (event.button !== 0 ||
            event.altKey ||
            event.ctrlKey ||
            event.shiftKey ||
            event.metaKey);
    }
    Private.nonstandardClick = nonstandardClick;
})(Private || (Private = {}));


/***/ }),

/***/ "7Vtj":
/*!************************************************************!*\
  !*** ./node_modules/react-json-tree/lib/JSONObjectNode.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "QbLZ");

var _extends3 = _interopRequireDefault(_extends2);

var _objectWithoutProperties2 = __webpack_require__(/*! babel-runtime/helpers/objectWithoutProperties */ "jo6Y");

var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);

var _getOwnPropertyNames = __webpack_require__(/*! babel-runtime/core-js/object/get-own-property-names */ "OyzN");

var _getOwnPropertyNames2 = _interopRequireDefault(_getOwnPropertyNames);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _JSONNestedNode = __webpack_require__(/*! ./JSONNestedNode */ "X834");

var _JSONNestedNode2 = _interopRequireDefault(_JSONNestedNode);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

// Returns the "n Items" string for this node,
// generating and caching it if it hasn't been created yet.
function createItemString(data) {
  var len = (0, _getOwnPropertyNames2['default'])(data).length;
  return len + ' ' + (len !== 1 ? 'keys' : 'key');
}

// Configures <JSONNestedNode> to render an Object
var JSONObjectNode = function JSONObjectNode(_ref) {
  var data = _ref.data,
      props = (0, _objectWithoutProperties3['default'])(_ref, ['data']);
  return _react2['default'].createElement(_JSONNestedNode2['default'], (0, _extends3['default'])({}, props, {
    data: data,
    nodeType: 'Object',
    nodeTypeIndicator: props.nodeType === 'Error' ? 'Error()' : '{}',
    createItemString: createItemString,
    expandable: (0, _getOwnPropertyNames2['default'])(data).length > 0
  }));
};

JSONObjectNode.propTypes = {
  data: _propTypes2['default'].object,
  nodeType: _propTypes2['default'].string
};

exports['default'] = JSONObjectNode;

/***/ }),

/***/ "7WuX":
/*!****************************************************************!*\
  !*** ./node_modules/@jupyterlab/rendermime/lib/outputmodel.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const coreutils_2 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const observables_1 = __webpack_require__(/*! @jupyterlab/observables */ "V4vH");
/**
 * The default implementation of a notebook output model.
 */
class OutputModel {
    /**
     * Construct a new output model.
     */
    constructor(options) {
        this._changed = new signaling_1.Signal(this);
        this._raw = {};
        let { data, metadata, trusted } = Private.getBundleOptions(options);
        this._data = new observables_1.ObservableJSON({ values: data });
        this._rawData = data;
        this._metadata = new observables_1.ObservableJSON({ values: metadata });
        this._rawMetadata = metadata;
        this.trusted = trusted;
        // Make a copy of the data.
        let value = options.value;
        for (let key in value) {
            // Ignore data and metadata that were stripped.
            switch (key) {
                case 'data':
                case 'metadata':
                    break;
                default:
                    this._raw[key] = Private.extract(value, key);
            }
        }
        this.type = value.output_type;
        if (coreutils_2.nbformat.isExecuteResult(value)) {
            this.executionCount = value.execution_count;
        }
        else {
            this.executionCount = null;
        }
    }
    /**
     * A signal emitted when the output model changes.
     */
    get changed() {
        return this._changed;
    }
    /**
     * Dispose of the resources used by the output model.
     */
    dispose() {
        this._data.dispose();
        this._metadata.dispose();
        signaling_1.Signal.clearData(this);
    }
    /**
     * The data associated with the model.
     */
    get data() {
        return this._rawData;
    }
    /**
     * The metadata associated with the model.
     */
    get metadata() {
        return this._rawMetadata;
    }
    /**
     * Set the data associated with the model.
     *
     * #### Notes
     * Depending on the implementation of the mime model,
     * this call may or may not have deferred effects,
     */
    setData(options) {
        if (options.data) {
            this._updateObservable(this._data, options.data);
            this._rawData = options.data;
        }
        if (options.metadata) {
            this._updateObservable(this._metadata, options.metadata);
            this._rawMetadata = options.metadata;
        }
        this._changed.emit(void 0);
    }
    /**
     * Serialize the model to JSON.
     */
    toJSON() {
        let output = {};
        for (let key in this._raw) {
            output[key] = Private.extract(this._raw, key);
        }
        switch (this.type) {
            case 'display_data':
            case 'execute_result':
            case 'update_display_data':
                output['data'] = this.data;
                output['metadata'] = this.metadata;
                break;
            default:
                break;
        }
        // Remove transient data.
        delete output['transient'];
        return output;
    }
    /**
     * Update an observable JSON object using a readonly JSON object.
     */
    _updateObservable(observable, data) {
        let oldKeys = observable.keys();
        let newKeys = Object.keys(data);
        // Handle removed keys.
        for (let key of oldKeys) {
            if (newKeys.indexOf(key) === -1) {
                observable.delete(key);
            }
        }
        // Handle changed data.
        for (let key of newKeys) {
            let oldValue = observable.get(key);
            let newValue = data[key];
            if (oldValue !== newValue) {
                observable.set(key, newValue);
            }
        }
    }
}
exports.OutputModel = OutputModel;
/**
 * The namespace for OutputModel statics.
 */
(function (OutputModel) {
    /**
     * Get the data for an output.
     *
     * @params output - A kernel output message payload.
     *
     * @returns - The data for the payload.
     */
    function getData(output) {
        return Private.getData(output);
    }
    OutputModel.getData = getData;
    /**
     * Get the metadata from an output message.
     *
     * @params output - A kernel output message payload.
     *
     * @returns - The metadata for the payload.
     */
    function getMetadata(output) {
        return Private.getMetadata(output);
    }
    OutputModel.getMetadata = getMetadata;
})(OutputModel = exports.OutputModel || (exports.OutputModel = {}));
/**
 * The namespace for module private data.
 */
var Private;
(function (Private) {
    /**
     * Get the data from a notebook output.
     */
    function getData(output) {
        let bundle = {};
        if (coreutils_2.nbformat.isExecuteResult(output) ||
            coreutils_2.nbformat.isDisplayData(output) ||
            coreutils_2.nbformat.isDisplayUpdate(output)) {
            bundle = output.data;
        }
        else if (coreutils_2.nbformat.isStream(output)) {
            if (output.name === 'stderr') {
                bundle['application/vnd.jupyter.stderr'] = output.text;
            }
            else {
                bundle['application/vnd.jupyter.stdout'] = output.text;
            }
        }
        else if (coreutils_2.nbformat.isError(output)) {
            let traceback = output.traceback.join('\n');
            bundle['application/vnd.jupyter.stderr'] =
                traceback || `${output.ename}: ${output.evalue}`;
        }
        return convertBundle(bundle);
    }
    Private.getData = getData;
    /**
     * Get the metadata from an output message.
     */
    function getMetadata(output) {
        let value = Object.create(null);
        if (coreutils_2.nbformat.isExecuteResult(output) || coreutils_2.nbformat.isDisplayData(output)) {
            for (let key in output.metadata) {
                value[key] = extract(output.metadata, key);
            }
        }
        return value;
    }
    Private.getMetadata = getMetadata;
    /**
     * Get the bundle options given output model options.
     */
    function getBundleOptions(options) {
        let data = getData(options.value);
        let metadata = getMetadata(options.value);
        let trusted = !!options.trusted;
        return { data, metadata, trusted };
    }
    Private.getBundleOptions = getBundleOptions;
    /**
     * Extract a value from a JSONObject.
     */
    function extract(value, key) {
        let item = value[key];
        if (coreutils_1.JSONExt.isPrimitive(item)) {
            return item;
        }
        return JSON.parse(JSON.stringify(item));
    }
    Private.extract = extract;
    /**
     * Convert a mime bundle to mime data.
     */
    function convertBundle(bundle) {
        let map = Object.create(null);
        for (let mimeType in bundle) {
            map[mimeType] = extract(bundle, mimeType);
        }
        return map;
    }
})(Private || (Private = {}));


/***/ }),

/***/ "7aV9":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/si.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


/*jshint -W100*/
var si = moment.defineLocale('si', {
    months : 'ජනවාරි_පෙබරවාරි_මාර්තු_අප්‍රේල්_මැයි_ජූනි_ජූලි_අගෝස්තු_සැප්තැම්බර්_ඔක්තෝබර්_නොවැම්බර්_දෙසැම්බර්'.split('_'),
    monthsShort : 'ජන_පෙබ_මාර්_අප්_මැයි_ජූනි_ජූලි_අගෝ_සැප්_ඔක්_නොවැ_දෙසැ'.split('_'),
    weekdays : 'ඉරිදා_සඳුදා_අඟහරුවාදා_බදාදා_බ්‍රහස්පතින්දා_සිකුරාදා_සෙනසුරාදා'.split('_'),
    weekdaysShort : 'ඉරි_සඳු_අඟ_බදා_බ්‍රහ_සිකු_සෙන'.split('_'),
    weekdaysMin : 'ඉ_ස_අ_බ_බ්‍ර_සි_සෙ'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'a h:mm',
        LTS : 'a h:mm:ss',
        L : 'YYYY/MM/DD',
        LL : 'YYYY MMMM D',
        LLL : 'YYYY MMMM D, a h:mm',
        LLLL : 'YYYY MMMM D [වැනි] dddd, a h:mm:ss'
    },
    calendar : {
        sameDay : '[අද] LT[ට]',
        nextDay : '[හෙට] LT[ට]',
        nextWeek : 'dddd LT[ට]',
        lastDay : '[ඊයේ] LT[ට]',
        lastWeek : '[පසුගිය] dddd LT[ට]',
        sameElse : 'L'
    },
    relativeTime : {
        future : '%sකින්',
        past : '%sකට පෙර',
        s : 'තත්පර කිහිපය',
        ss : 'තත්පර %d',
        m : 'මිනිත්තුව',
        mm : 'මිනිත්තු %d',
        h : 'පැය',
        hh : 'පැය %d',
        d : 'දිනය',
        dd : 'දින %d',
        M : 'මාසය',
        MM : 'මාස %d',
        y : 'වසර',
        yy : 'වසර %d'
    },
    dayOfMonthOrdinalParse: /\d{1,2} වැනි/,
    ordinal : function (number) {
        return number + ' වැනි';
    },
    meridiemParse : /පෙර වරු|පස් වරු|පෙ.ව|ප.ව./,
    isPM : function (input) {
        return input === 'ප.ව.' || input === 'පස් වරු';
    },
    meridiem : function (hours, minutes, isLower) {
        if (hours > 11) {
            return isLower ? 'ප.ව.' : 'පස් වරු';
        } else {
            return isLower ? 'පෙ.ව.' : 'පෙර වරු';
        }
    }
});

return si;

})));


/***/ }),

/***/ "7ckf":
/*!*************************************************!*\
  !*** ./node_modules/hash.js/lib/hash/common.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var utils = __webpack_require__(/*! ./utils */ "w8CP");
var assert = __webpack_require__(/*! minimalistic-assert */ "2j6C");

function BlockHash() {
  this.pending = null;
  this.pendingTotal = 0;
  this.blockSize = this.constructor.blockSize;
  this.outSize = this.constructor.outSize;
  this.hmacStrength = this.constructor.hmacStrength;
  this.padLength = this.constructor.padLength / 8;
  this.endian = 'big';

  this._delta8 = this.blockSize / 8;
  this._delta32 = this.blockSize / 32;
}
exports.BlockHash = BlockHash;

BlockHash.prototype.update = function update(msg, enc) {
  // Convert message to array, pad it, and join into 32bit blocks
  msg = utils.toArray(msg, enc);
  if (!this.pending)
    this.pending = msg;
  else
    this.pending = this.pending.concat(msg);
  this.pendingTotal += msg.length;

  // Enough data, try updating
  if (this.pending.length >= this._delta8) {
    msg = this.pending;

    // Process pending data in blocks
    var r = msg.length % this._delta8;
    this.pending = msg.slice(msg.length - r, msg.length);
    if (this.pending.length === 0)
      this.pending = null;

    msg = utils.join32(msg, 0, msg.length - r, this.endian);
    for (var i = 0; i < msg.length; i += this._delta32)
      this._update(msg, i, i + this._delta32);
  }

  return this;
};

BlockHash.prototype.digest = function digest(enc) {
  this.update(this._pad());
  assert(this.pending === null);

  return this._digest(enc);
};

BlockHash.prototype._pad = function pad() {
  var len = this.pendingTotal;
  var bytes = this._delta8;
  var k = bytes - ((len + this.padLength) % bytes);
  var res = new Array(k + this.padLength);
  res[0] = 0x80;
  for (var i = 1; i < k; i++)
    res[i] = 0;

  // Append length
  len <<= 3;
  if (this.endian === 'big') {
    for (var t = 8; t < this.padLength; t++)
      res[i++] = 0;

    res[i++] = 0;
    res[i++] = 0;
    res[i++] = 0;
    res[i++] = 0;
    res[i++] = (len >>> 24) & 0xff;
    res[i++] = (len >>> 16) & 0xff;
    res[i++] = (len >>> 8) & 0xff;
    res[i++] = len & 0xff;
  } else {
    res[i++] = len & 0xff;
    res[i++] = (len >>> 8) & 0xff;
    res[i++] = (len >>> 16) & 0xff;
    res[i++] = (len >>> 24) & 0xff;
    res[i++] = 0;
    res[i++] = 0;
    res[i++] = 0;
    res[i++] = 0;

    for (t = 8; t < this.padLength; t++)
      res[i++] = 0;
  }

  return res;
};


/***/ }),

/***/ "7dW+":
/*!******************************************************************!*\
  !*** ./node_modules/react-color/lib/components/circle/Circle.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Circle = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _map = __webpack_require__(/*! lodash/map */ "3WF5");

var _map2 = _interopRequireDefault(_map);

var _merge = __webpack_require__(/*! lodash/merge */ "QkVN");

var _merge2 = _interopRequireDefault(_merge);

var _materialColors = __webpack_require__(/*! material-colors */ "wME1");

var material = _interopRequireWildcard(_materialColors);

var _common = __webpack_require__(/*! ../common */ "TM95");

var _CircleSwatch = __webpack_require__(/*! ./CircleSwatch */ "xbjo");

var _CircleSwatch2 = _interopRequireDefault(_CircleSwatch);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var Circle = exports.Circle = function Circle(_ref) {
  var width = _ref.width,
      onChange = _ref.onChange,
      onSwatchHover = _ref.onSwatchHover,
      colors = _ref.colors,
      hex = _ref.hex,
      circleSize = _ref.circleSize,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles,
      circleSpacing = _ref.circleSpacing,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': {
      card: {
        width: width,
        display: 'flex',
        flexWrap: 'wrap',
        marginRight: -circleSpacing,
        marginBottom: -circleSpacing
      }
    }
  }, passedStyles));

  var handleChange = function handleChange(hexCode, e) {
    return onChange({ hex: hexCode, source: 'hex' }, e);
  };

  return _react2.default.createElement(
    'div',
    { style: styles.card, className: 'circle-picker ' + className },
    (0, _map2.default)(colors, function (c) {
      return _react2.default.createElement(_CircleSwatch2.default, {
        key: c,
        color: c,
        onClick: handleChange,
        onSwatchHover: onSwatchHover,
        active: hex === c.toLowerCase(),
        circleSize: circleSize,
        circleSpacing: circleSpacing
      });
    })
  );
};

Circle.propTypes = {
  width: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]),
  circleSize: _propTypes2.default.number,
  circleSpacing: _propTypes2.default.number,
  styles: _propTypes2.default.object
};

Circle.defaultProps = {
  width: 252,
  circleSize: 28,
  circleSpacing: 14,
  colors: [material.red['500'], material.pink['500'], material.purple['500'], material.deepPurple['500'], material.indigo['500'], material.blue['500'], material.lightBlue['500'], material.cyan['500'], material.teal['500'], material.green['500'], material.lightGreen['500'], material.lime['500'], material.yellow['500'], material.amber['500'], material.orange['500'], material.deepOrange['500'], material.brown['500'], material.blueGrey['500']],
  styles: {}
};

exports.default = (0, _common.ColorWrap)(Circle);

/***/ }),

/***/ "7fqy":
/*!********************************************!*\
  !*** ./node_modules/lodash/_mapToArray.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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;
}

module.exports = mapToArray;


/***/ }),

/***/ "7j9i":
/*!***********************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@phosphor/widgets/style/tabbar.css ***!
  \***********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\r\n| Copyright (c) 2014-2017, PhosphorJS Contributors\r\n|\r\n| Distributed under the terms of the BSD 3-Clause License.\r\n|\r\n| The full license is in the file LICENSE, distributed with this software.\r\n|----------------------------------------------------------------------------*/\r\n\r\n\r\n.p-TabBar {\r\n  display: flex;\r\n  -webkit-user-select: none;\r\n  -moz-user-select: none;\r\n  -ms-user-select: none;\r\n  user-select: none;\r\n}\r\n\r\n\r\n.p-TabBar[data-orientation='horizontal'] {\r\n  flex-direction: row;\r\n}\r\n\r\n\r\n.p-TabBar[data-orientation='vertical'] {\r\n  flex-direction: column;\r\n}\r\n\r\n\r\n.p-TabBar-content {\r\n  margin: 0;\r\n  padding: 0;\r\n  display: flex;\r\n  flex: 1 1 auto;\r\n  list-style-type: none;\r\n}\r\n\r\n\r\n.p-TabBar[data-orientation='horizontal'] > .p-TabBar-content {\r\n  flex-direction: row;\r\n}\r\n\r\n\r\n.p-TabBar[data-orientation='vertical'] > .p-TabBar-content {\r\n  flex-direction: column;\r\n}\r\n\r\n\r\n.p-TabBar-tab {\r\n  display: flex;\r\n  flex-direction: row;\r\n  box-sizing: border-box;\r\n  overflow: hidden;\r\n}\r\n\r\n\r\n.p-TabBar-tabIcon,\r\n.p-TabBar-tabCloseIcon {\r\n  flex: 0 0 auto;\r\n}\r\n\r\n\r\n.p-TabBar-tabLabel {\r\n  flex: 1 1 auto;\r\n  overflow: hidden;\r\n  white-space: nowrap;\r\n}\r\n\r\n\r\n.p-TabBar-tab.p-mod-hidden {\r\n  display: none !important;\r\n}\r\n\r\n\r\n.p-TabBar.p-mod-dragging .p-TabBar-tab {\r\n  position: relative;\r\n}\r\n\r\n\r\n.p-TabBar.p-mod-dragging[data-orientation='horizontal'] .p-TabBar-tab {\r\n  left: 0;\r\n  transition: left 150ms ease;\r\n}\r\n\r\n\r\n.p-TabBar.p-mod-dragging[data-orientation='vertical'] .p-TabBar-tab {\r\n  top: 0;\r\n  transition: top 150ms ease;\r\n}\r\n\r\n\r\n.p-TabBar.p-mod-dragging .p-TabBar-tab.p-mod-dragging {\r\n  transition: none;\r\n}\r\n", ""]);

// exports


/***/ }),

/***/ "7jRU":
/*!***************************************!*\
  !*** ./node_modules/indexof/index.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports) {


var indexOf = [].indexOf;

module.exports = function(arr, obj){
  if (indexOf) return arr.indexOf(obj);
  for (var i = 0; i < arr.length; ++i) {
    if (arr[i] === obj) return i;
  }
  return -1;
};

/***/ }),

/***/ "7kzI":
/*!*************************************************************!*\
  !*** ./node_modules/@jupyterlab/filebrowser/lib/factory.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
/* tslint:disable */
/**
 * The path tracker token.
 */
exports.IFileBrowserFactory = new coreutils_1.Token('@jupyterlab/filebrowser:IFileBrowserFactory');


/***/ }),

/***/ "7pOt":
/*!****************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/coerce.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var isNumeric = __webpack_require__(/*! fast-isnumeric */ "GbLo");
var tinycolor = __webpack_require__(/*! tinycolor2 */ "Zss7");

var baseTraceAttrs = __webpack_require__(/*! ../plots/attributes */ "2yMk");
var scales = __webpack_require__(/*! ../components/colorscale/scales */ "L3zP");
var DESELECTDIM = __webpack_require__(/*! ../constants/interactions */ "ztYK").DESELECTDIM;

var nestedProperty = __webpack_require__(/*! ./nested_property */ "oz8K");
var counterRegex = __webpack_require__(/*! ./regex */ "Kuxr").counter;
var modHalf = __webpack_require__(/*! ./mod */ "74Od").modHalf;
var isArrayOrTypedArray = __webpack_require__(/*! ./array */ "lCvc").isArrayOrTypedArray;

exports.valObjectMeta = {
    data_array: {
        // You can use *dflt=[] to force said array to exist though.
        description: [
            'An {array} of data.',
            'The value MUST be an {array}, or we ignore it.',
            'Note that typed arrays (e.g. Float32Array) are supported.'
        ].join(' '),
        requiredOpts: [],
        otherOpts: ['dflt'],
        coerceFunction: function(v, propOut, dflt) {
            // TODO maybe `v: {type: 'float32', vals: [/* ... */]}` also
            if(isArrayOrTypedArray(v)) propOut.set(v);
            else if(dflt !== undefined) propOut.set(dflt);
        }
    },
    enumerated: {
        description: [
            'Enumerated value type. The available values are listed',
            'in `values`.'
        ].join(' '),
        requiredOpts: ['values'],
        otherOpts: ['dflt', 'coerceNumber', 'arrayOk'],
        coerceFunction: function(v, propOut, dflt, opts) {
            if(opts.coerceNumber) v = +v;
            if(opts.values.indexOf(v) === -1) propOut.set(dflt);
            else propOut.set(v);
        },
        validateFunction: function(v, opts) {
            if(opts.coerceNumber) v = +v;

            var values = opts.values;
            for(var i = 0; i < values.length; i++) {
                var k = String(values[i]);

                if((k.charAt(0) === '/' && k.charAt(k.length - 1) === '/')) {
                    var regex = new RegExp(k.substr(1, k.length - 2));
                    if(regex.test(v)) return true;
                } else if(v === values[i]) return true;
            }
            return false;
        }
    },
    'boolean': {
        description: 'A boolean (true/false) value.',
        requiredOpts: [],
        otherOpts: ['dflt'],
        coerceFunction: function(v, propOut, dflt) {
            if(v === true || v === false) propOut.set(v);
            else propOut.set(dflt);
        }
    },
    number: {
        description: [
            'A number or a numeric value',
            '(e.g. a number inside a string).',
            'When applicable, values greater (less) than `max` (`min`)',
            'are coerced to the `dflt`.'
        ].join(' '),
        requiredOpts: [],
        otherOpts: ['dflt', 'min', 'max', 'arrayOk'],
        coerceFunction: function(v, propOut, dflt, opts) {
            if(!isNumeric(v) ||
                    (opts.min !== undefined && v < opts.min) ||
                    (opts.max !== undefined && v > opts.max)) {
                propOut.set(dflt);
            }
            else propOut.set(+v);
        }
    },
    integer: {
        description: [
            'An integer or an integer inside a string.',
            'When applicable, values greater (less) than `max` (`min`)',
            'are coerced to the `dflt`.'
        ].join(' '),
        requiredOpts: [],
        otherOpts: ['dflt', 'min', 'max', 'arrayOk'],
        coerceFunction: function(v, propOut, dflt, opts) {
            if(v % 1 || !isNumeric(v) ||
                    (opts.min !== undefined && v < opts.min) ||
                    (opts.max !== undefined && v > opts.max)) {
                propOut.set(dflt);
            }
            else propOut.set(+v);
        }
    },
    string: {
        description: [
            'A string value.',
            'Numbers are converted to strings except for attributes with',
            '`strict` set to true.'
        ].join(' '),
        requiredOpts: [],
        // TODO 'values shouldn't be in there (edge case: 'dash' in Scatter)
        otherOpts: ['dflt', 'noBlank', 'strict', 'arrayOk', 'values'],
        coerceFunction: function(v, propOut, dflt, opts) {
            if(typeof v !== 'string') {
                var okToCoerce = (typeof v === 'number');

                if(opts.strict === true || !okToCoerce) propOut.set(dflt);
                else propOut.set(String(v));
            }
            else if(opts.noBlank && !v) propOut.set(dflt);
            else propOut.set(v);
        }
    },
    color: {
        description: [
            'A string describing color.',
            'Supported formats:',
            '- hex (e.g. \'#d3d3d3\')',
            '- rgb (e.g. \'rgb(255, 0, 0)\')',
            '- rgba (e.g. \'rgb(255, 0, 0, 0.5)\')',
            '- hsl (e.g. \'hsl(0, 100%, 50%)\')',
            '- hsv (e.g. \'hsv(0, 100%, 100%)\')',
            '- named colors (full list: http://www.w3.org/TR/css3-color/#svg-color)'
        ].join(' '),
        requiredOpts: [],
        otherOpts: ['dflt', 'arrayOk'],
        coerceFunction: function(v, propOut, dflt) {
            if(tinycolor(v).isValid()) propOut.set(v);
            else propOut.set(dflt);
        }
    },
    colorlist: {
        description: [
            'A list of colors.',
            'Must be an {array} containing valid colors.',
        ].join(' '),
        requiredOpts: [],
        otherOpts: ['dflt'],
        coerceFunction: function(v, propOut, dflt) {
            function isColor(color) {
                return tinycolor(color).isValid();
            }
            if(!Array.isArray(v) || !v.length) propOut.set(dflt);
            else if(v.every(isColor)) propOut.set(v);
            else propOut.set(dflt);
        }
    },
    colorscale: {
        description: [
            'A Plotly colorscale either picked by a name:',
            '(any of', Object.keys(scales.scales).join(', '), ')',
            'customized as an {array} of 2-element {arrays} where',
            'the first element is the normalized color level value',
            '(starting at *0* and ending at *1*),',
            'and the second item is a valid color string.'
        ].join(' '),
        requiredOpts: [],
        otherOpts: ['dflt'],
        coerceFunction: function(v, propOut, dflt) {
            propOut.set(scales.get(v, dflt));
        }
    },
    angle: {
        description: [
            'A number (in degree) between -180 and 180.'
        ].join(' '),
        requiredOpts: [],
        otherOpts: ['dflt'],
        coerceFunction: function(v, propOut, dflt) {
            if(v === 'auto') propOut.set('auto');
            else if(!isNumeric(v)) propOut.set(dflt);
            else propOut.set(modHalf(+v, 360));
        }
    },
    subplotid: {
        description: [
            'An id string of a subplot type (given by dflt), optionally',
            'followed by an integer >1. e.g. if dflt=\'geo\', we can have',
            '\'geo\', \'geo2\', \'geo3\', ...'
        ].join(' '),
        requiredOpts: ['dflt'],
        otherOpts: ['regex'],
        coerceFunction: function(v, propOut, dflt, opts) {
            var regex = opts.regex || counterRegex(dflt);
            if(typeof v === 'string' && regex.test(v)) {
                propOut.set(v);
                return;
            }
            propOut.set(dflt);
        },
        validateFunction: function(v, opts) {
            var dflt = opts.dflt;

            if(v === dflt) return true;
            if(typeof v !== 'string') return false;
            if(counterRegex(dflt).test(v)) return true;

            return false;
        }
    },
    flaglist: {
        description: [
            'A string representing a combination of flags',
            '(order does not matter here).',
            'Combine any of the available `flags` with *+*.',
            '(e.g. (\'lines+markers\')).',
            'Values in `extras` cannot be combined.'
        ].join(' '),
        requiredOpts: ['flags'],
        otherOpts: ['dflt', 'extras', 'arrayOk'],
        coerceFunction: function(v, propOut, dflt, opts) {
            if(typeof v !== 'string') {
                propOut.set(dflt);
                return;
            }
            if((opts.extras || []).indexOf(v) !== -1) {
                propOut.set(v);
                return;
            }
            var vParts = v.split('+');
            var i = 0;
            while(i < vParts.length) {
                var vi = vParts[i];
                if(opts.flags.indexOf(vi) === -1 || vParts.indexOf(vi) < i) {
                    vParts.splice(i, 1);
                }
                else i++;
            }
            if(!vParts.length) propOut.set(dflt);
            else propOut.set(vParts.join('+'));
        }
    },
    any: {
        description: 'Any type.',
        requiredOpts: [],
        otherOpts: ['dflt', 'values', 'arrayOk'],
        coerceFunction: function(v, propOut, dflt) {
            if(v === undefined) propOut.set(dflt);
            else propOut.set(v);
        }
    },
    info_array: {
        description: [
            'An {array} of plot information.'
        ].join(' '),
        requiredOpts: ['items'],
        // set `dimensions=2` for a 2D array or '1-2' for either
        // `items` may be a single object instead of an array, in which case
        // `freeLength` must be true.
        // if `dimensions='1-2'` and items is a 1D array, then the value can
        // either be a matching 1D array or an array of such matching 1D arrays
        otherOpts: ['dflt', 'freeLength', 'dimensions'],
        coerceFunction: function(v, propOut, dflt, opts) {

            // simplified coerce function just for array items
            function coercePart(v, opts, dflt) {
                var out;
                var propPart = {set: function(v) { out = v; }};

                if(dflt === undefined) dflt = opts.dflt;

                exports.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts);

                return out;
            }

            var twoD = opts.dimensions === 2 || (opts.dimensions === '1-2' && Array.isArray(v) && Array.isArray(v[0]));

            if(!Array.isArray(v)) {
                propOut.set(dflt);
                return;
            }

            var items = opts.items;
            var vOut = [];
            var arrayItems = Array.isArray(items);
            var arrayItems2D = arrayItems && twoD && Array.isArray(items[0]);
            var innerItemsOnly = twoD && arrayItems && !arrayItems2D;
            var len = (arrayItems && !innerItemsOnly) ? items.length : v.length;

            var i, j, row, item, len2, vNew;

            dflt = Array.isArray(dflt) ? dflt : [];

            if(twoD) {
                for(i = 0; i < len; i++) {
                    vOut[i] = [];
                    row = Array.isArray(v[i]) ? v[i] : [];
                    if(innerItemsOnly) len2 = items.length;
                    else if(arrayItems) len2 = items[i].length;
                    else len2 = row.length;

                    for(j = 0; j < len2; j++) {
                        if(innerItemsOnly) item = items[j];
                        else if(arrayItems) item = items[i][j];
                        else item = items;

                        vNew = coercePart(row[j], item, (dflt[i] || [])[j]);
                        if(vNew !== undefined) vOut[i][j] = vNew;
                    }
                }
            }
            else {
                for(i = 0; i < len; i++) {
                    vNew = coercePart(v[i], arrayItems ? items[i] : items, dflt[i]);
                    if(vNew !== undefined) vOut[i] = vNew;
                }
            }

            propOut.set(vOut);
        },
        validateFunction: function(v, opts) {
            if(!Array.isArray(v)) return false;

            var items = opts.items;
            var arrayItems = Array.isArray(items);
            var twoD = opts.dimensions === 2;

            // when free length is off, input and declared lengths must match
            if(!opts.freeLength && v.length !== items.length) return false;

            // valid when all input items are valid
            for(var i = 0; i < v.length; i++) {
                if(twoD) {
                    if(!Array.isArray(v[i]) || (!opts.freeLength && v[i].length !== items[i].length)) {
                        return false;
                    }
                    for(var j = 0; j < v[i].length; j++) {
                        if(!validate(v[i][j], arrayItems ? items[i][j] : items)) {
                            return false;
                        }
                    }
                }
                else if(!validate(v[i], arrayItems ? items[i] : items)) return false;
            }

            return true;
        }
    }
};

/**
 * Ensures that container[attribute] has a valid value.
 *
 * attributes[attribute] is an object with possible keys:
 * - valType: data_array, enumerated, boolean, ... as in valObjectMeta
 * - values: (enumerated only) array of allowed vals
 * - min, max: (number, integer only) inclusive bounds on allowed vals
 *      either or both may be omitted
 * - dflt: if attribute is invalid or missing, use this default
 *      if dflt is provided as an argument to lib.coerce it takes precedence
 *      as a convenience, returns the value it finally set
 */
exports.coerce = function(containerIn, containerOut, attributes, attribute, dflt) {
    var opts = nestedProperty(attributes, attribute).get();
    var propIn = nestedProperty(containerIn, attribute);
    var propOut = nestedProperty(containerOut, attribute);
    var v = propIn.get();

    var template = containerOut._template;
    if(v === undefined && template) {
        v = nestedProperty(template, attribute).get();
        // already used the template value, so short-circuit the second check
        template = 0;
    }

    if(dflt === undefined) dflt = opts.dflt;

    /**
     * arrayOk: value MAY be an array, then we do no value checking
     * at this point, because it can be more complicated than the
     * individual form (eg. some array vals can be numbers, even if the
     * single values must be color strings)
     */
    if(opts.arrayOk && isArrayOrTypedArray(v)) {
        propOut.set(v);
        return v;
    }

    var coerceFunction = exports.valObjectMeta[opts.valType].coerceFunction;
    coerceFunction(v, propOut, dflt, opts);

    var out = propOut.get();
    // in case v was provided but invalid, try the template again so it still
    // overrides the regular default
    if(template && out === dflt && !validate(v, opts)) {
        v = nestedProperty(template, attribute).get();
        coerceFunction(v, propOut, dflt, opts);
        out = propOut.get();
    }
    return out;
};

/**
 * Variation on coerce
 *
 * Uses coerce to get attribute value if user input is valid,
 * returns attribute default if user input it not valid or
 * returns false if there is no user input.
 */
exports.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) {
    var propIn = nestedProperty(containerIn, attribute);
    var propOut = exports.coerce(containerIn, containerOut, attributes, attribute, dflt);
    var valIn = propIn.get();

    return (valIn !== undefined && valIn !== null) ? propOut : false;
};

/*
 * Shortcut to coerce the three font attributes
 *
 * 'coerce' is a lib.coerce wrapper with implied first three arguments
 */
exports.coerceFont = function(coerce, attr, dfltObj) {
    var out = {};

    dfltObj = dfltObj || {};

    out.family = coerce(attr + '.family', dfltObj.family);
    out.size = coerce(attr + '.size', dfltObj.size);
    out.color = coerce(attr + '.color', dfltObj.color);

    return out;
};

/** Coerce shortcut for 'hoverinfo'
 * handling 1-vs-multi-trace dflt logic
 *
 * @param {object} traceIn : user trace object
 * @param {object} traceOut : full trace object (requires _module ref)
 * @param {object} layoutOut : full layout object (require _dataLength ref)
 * @return {any} : the coerced value
 */
exports.coerceHoverinfo = function(traceIn, traceOut, layoutOut) {
    var moduleAttrs = traceOut._module.attributes;
    var attrs = moduleAttrs.hoverinfo ? moduleAttrs : baseTraceAttrs;

    var valObj = attrs.hoverinfo;
    var dflt;

    if(layoutOut._dataLength === 1) {
        var flags = valObj.dflt === 'all' ?
            valObj.flags.slice() :
            valObj.dflt.split('+');

        flags.splice(flags.indexOf('name'), 1);
        dflt = flags.join('+');
    }

    return exports.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt);
};

/** Coerce shortcut for [un]selected.marker.opacity,
 *  which has special default logic, to ensure that it corresponds to the
 *  default selection behavior while allowing to be overtaken by any other
 *  [un]selected attribute.
 *
 *  N.B. This must be called *after* coercing all the other [un]selected attrs,
 *  to give the intended result.
 *
 * @param {object} traceOut : fullData item
 * @param {function} coerce : lib.coerce wrapper with implied first three arguments
 */
exports.coerceSelectionMarkerOpacity = function(traceOut, coerce) {
    if(!traceOut.marker) return;

    var mo = traceOut.marker.opacity;
    // you can still have a `marker` container with no markers if there's text
    if(mo === undefined) return;

    var smoDflt;
    var usmoDflt;

    // Don't give [un]selected.marker.opacity a default value if
    // marker.opacity is an array: handle this during style step.
    //
    // Only give [un]selected.marker.opacity a default value if you don't
    // set any other [un]selected attributes.
    if(!isArrayOrTypedArray(mo) && !traceOut.selected && !traceOut.unselected) {
        smoDflt = mo;
        usmoDflt = DESELECTDIM * mo;
    }

    coerce('selected.marker.opacity', smoDflt);
    coerce('unselected.marker.opacity', usmoDflt);
};

function validate(value, opts) {
    var valObjectDef = exports.valObjectMeta[opts.valType];

    if(opts.arrayOk && isArrayOrTypedArray(value)) return true;

    if(valObjectDef.validateFunction) {
        return valObjectDef.validateFunction(value, opts);
    }

    var failed = {};
    var out = failed;
    var propMock = { set: function(v) { out = v; } };

    // 'failed' just something mutable that won't be === anything else

    valObjectDef.coerceFunction(value, propMock, failed, opts);
    return out !== failed;
}
exports.validate = validate;


/***/ }),

/***/ "7qpb":
/*!***************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/dates.js ***!
  \***************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




var d3 = __webpack_require__(/*! d3 */ "bljh");
var isNumeric = __webpack_require__(/*! fast-isnumeric */ "GbLo");

var Loggers = __webpack_require__(/*! ./loggers */ "B+Rx");
var mod = __webpack_require__(/*! ./mod */ "74Od").mod;

var constants = __webpack_require__(/*! ../constants/numerical */ "qrPk");
var BADNUM = constants.BADNUM;
var ONEDAY = constants.ONEDAY;
var ONEHOUR = constants.ONEHOUR;
var ONEMIN = constants.ONEMIN;
var ONESEC = constants.ONESEC;
var EPOCHJD = constants.EPOCHJD;

var Registry = __webpack_require__(/*! ../registry */ "GF7H");

var utcFormat = d3.time.format.utc;

var DATETIME_REGEXP = /^\s*(-?\d\d\d\d|\d\d)(-(\d?\d)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d:?\d\d)?)?)?)?)?\s*$/m;
// special regex for chinese calendars to support yyyy-mmi-dd etc for intercalary months
var DATETIME_REGEXP_CN = /^\s*(-?\d\d\d\d|\d\d)(-(\d?\di?)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d:?\d\d)?)?)?)?)?\s*$/m;

// for 2-digit years, the first year we map them onto
var YFIRST = new Date().getFullYear() - 70;

function isWorldCalendar(calendar) {
    return (
        calendar &&
        Registry.componentsRegistry.calendars &&
        typeof calendar === 'string' && calendar !== 'gregorian'
    );
}

/*
 * dateTick0: get the canonical tick for this calendar
 *
 * bool sunday is for week ticks, shift it to a Sunday.
 */
exports.dateTick0 = function(calendar, sunday) {
    if(isWorldCalendar(calendar)) {
        return sunday ?
            Registry.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] :
            Registry.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar];
    }
    else {
        return sunday ? '2000-01-02' : '2000-01-01';
    }
};

/*
 * dfltRange: for each calendar, give a valid default range
 */
exports.dfltRange = function(calendar) {
    if(isWorldCalendar(calendar)) {
        return Registry.getComponentMethod('calendars', 'DFLTRANGE')[calendar];
    }
    else {
        return ['2000-01-01', '2001-01-01'];
    }
};

// is an object a javascript date?
exports.isJSDate = function(v) {
    return typeof v === 'object' && v !== null && typeof v.getTime === 'function';
};

// The absolute limits of our date-time system
// This is a little weird: we use MIN_MS and MAX_MS in dateTime2ms
// but we use dateTime2ms to calculate them (after defining it!)
var MIN_MS, MAX_MS;

/**
 * dateTime2ms - turn a date object or string s into milliseconds
 * (relative to 1970-01-01, per javascript standard)
 * optional calendar (string) to use a non-gregorian calendar
 *
 * Returns BADNUM if it doesn't find a date
 *
 * strings should have the form:
 *
 *    -?YYYY-mm-dd<sep>HH:MM:SS.sss<tzInfo>?
 *
 * <sep>: space (our normal standard) or T or t (ISO-8601)
 * <tzInfo>: Z, z, or [+\-]HH:?MM and we THROW IT AWAY
 * this format comes from https://tools.ietf.org/html/rfc3339#section-5.6
 * but we allow it even with a space as the separator
 *
 * May truncate after any full field, and sss can be any length
 * even >3 digits, though javascript dates truncate to milliseconds,
 * we keep as much as javascript numeric precision can hold, but we only
 * report back up to 100 microsecond precision, because most dates support
 * this precision (close to 1970 support more, very far away support less)
 *
 * Expanded to support negative years to -9999 but you must always
 * give 4 digits, except for 2-digit positive years which we assume are
 * near the present time.
 * Note that we follow ISO 8601:2004: there *is* a year 0, which
 * is 1BC/BCE, and -1===2BC etc.
 *
 * World calendars: not all of these *have* agreed extensions to this full range,
 * if you have another calendar system but want a date range outside its validity,
 * you can use a gregorian date string prefixed with 'G' or 'g'.
 *
 * Where to cut off 2-digit years between 1900s and 2000s?
 * from http://support.microsoft.com/kb/244664:
 *   1930-2029 (the most retro of all...)
 * but in my mac chrome from eg. d=new Date(Date.parse('8/19/50')):
 *   1950-2049
 * by Java, from http://stackoverflow.com/questions/2024273/:
 *   now-80 - now+19
 * or FileMaker Pro, from
 *      http://www.filemaker.com/12help/html/add_view_data.4.21.html:
 *   now-70 - now+29
 * but python strptime etc, via
 *      http://docs.python.org/py3k/library/time.html:
 *   1969-2068 (super forward-looking, but static, not sliding!)
 *
 * lets go with now-70 to now+29, and if anyone runs into this problem
 * they can learn the hard way not to use 2-digit years, as no choice we
 * make now will cover all possibilities. mostly this will all be taken
 * care of in initial parsing, should only be an issue for hand-entered data
 * currently (2016) this range is:
 *   1946-2045
 */
exports.dateTime2ms = function(s, calendar) {
    // first check if s is a date object
    if(exports.isJSDate(s)) {
        // Convert to the UTC milliseconds that give the same
        // hours as this date has in the local timezone
        var tzOffset = s.getTimezoneOffset() * ONEMIN;
        var offsetTweak = (s.getUTCMinutes() - s.getMinutes()) * ONEMIN +
            (s.getUTCSeconds() - s.getSeconds()) * ONESEC +
            (s.getUTCMilliseconds() - s.getMilliseconds());

        if(offsetTweak) {
            var comb = 3 * ONEMIN;
            tzOffset = tzOffset - comb / 2 + mod(offsetTweak - tzOffset + comb / 2, comb);
        }
        s = Number(s) - tzOffset;
        if(s >= MIN_MS && s <= MAX_MS) return s;
        return BADNUM;
    }
    // otherwise only accept strings and numbers
    if(typeof s !== 'string' && typeof s !== 'number') return BADNUM;

    s = String(s);

    var isWorld = isWorldCalendar(calendar);

    // to handle out-of-range dates in international calendars, accept
    // 'G' as a prefix to force the built-in gregorian calendar.
    var s0 = s.charAt(0);
    if(isWorld && (s0 === 'G' || s0 === 'g')) {
        s = s.substr(1);
        calendar = '';
    }

    var isChinese = isWorld && calendar.substr(0, 7) === 'chinese';

    var match = s.match(isChinese ? DATETIME_REGEXP_CN : DATETIME_REGEXP);
    if(!match) return BADNUM;
    var y = match[1];
    var m = match[3] || '1';
    var d = Number(match[5] || 1);
    var H = Number(match[7] || 0);
    var M = Number(match[9] || 0);
    var S = Number(match[11] || 0);

    if(isWorld) {
        // disallow 2-digit years for world calendars
        if(y.length === 2) return BADNUM;
        y = Number(y);

        var cDate;
        try {
            var calInstance = Registry.getComponentMethod('calendars', 'getCal')(calendar);
            if(isChinese) {
                var isIntercalary = m.charAt(m.length - 1) === 'i';
                m = parseInt(m, 10);
                cDate = calInstance.newDate(y, calInstance.toMonthIndex(y, m, isIntercalary), d);
            }
            else {
                cDate = calInstance.newDate(y, Number(m), d);
            }
        }
        catch(e) { return BADNUM; } // Invalid ... date

        if(!cDate) return BADNUM;

        return ((cDate.toJD() - EPOCHJD) * ONEDAY) +
            (H * ONEHOUR) + (M * ONEMIN) + (S * ONESEC);
    }

    if(y.length === 2) {
        y = (Number(y) + 2000 - YFIRST) % 100 + YFIRST;
    }
    else y = Number(y);

    // new Date uses months from 0; subtract 1 here just so we
    // don't have to do it again during the validity test below
    m -= 1;

    // javascript takes new Date(0..99,m,d) to mean 1900-1999, so
    // to support years 0-99 we need to use setFullYear explicitly
    // Note that 2000 is a leap year.
    var date = new Date(Date.UTC(2000, m, d, H, M));
    date.setUTCFullYear(y);

    if(date.getUTCMonth() !== m) return BADNUM;
    if(date.getUTCDate() !== d) return BADNUM;

    return date.getTime() + S * ONESEC;
};

MIN_MS = exports.MIN_MS = exports.dateTime2ms('-9999');
MAX_MS = exports.MAX_MS = exports.dateTime2ms('9999-12-31 23:59:59.9999');

// is string s a date? (see above)
exports.isDateTime = function(s, calendar) {
    return (exports.dateTime2ms(s, calendar) !== BADNUM);
};

// pad a number with zeroes, to given # of digits before the decimal point
function lpad(val, digits) {
    return String(val + Math.pow(10, digits)).substr(1);
}

/**
 * Turn ms into string of the form YYYY-mm-dd HH:MM:SS.ssss
 * Crop any trailing zeros in time, except never stop right after hours
 * (we could choose to crop '-01' from date too but for now we always
 * show the whole date)
 * Optional range r is the data range that applies, also in ms.
 * If rng is big, the later parts of time will be omitted
 */
var NINETYDAYS = 90 * ONEDAY;
var THREEHOURS = 3 * ONEHOUR;
var FIVEMIN = 5 * ONEMIN;
exports.ms2DateTime = function(ms, r, calendar) {
    if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return BADNUM;

    if(!r) r = 0;

    var msecTenths = Math.floor(mod(ms + 0.05, 1) * 10);
    var msRounded = Math.round(ms - msecTenths / 10);
    var dateStr, h, m, s, msec10, d;

    if(isWorldCalendar(calendar)) {
        var dateJD = Math.floor(msRounded / ONEDAY) + EPOCHJD;
        var timeMs = Math.floor(mod(ms, ONEDAY));
        try {
            dateStr = Registry.getComponentMethod('calendars', 'getCal')(calendar)
                .fromJD(dateJD).formatDate('yyyy-mm-dd');
        } catch(e) {
            // invalid date in this calendar - fall back to Gyyyy-mm-dd
            dateStr = utcFormat('G%Y-%m-%d')(new Date(msRounded));
        }

        // yyyy does NOT guarantee 4-digit years. YYYY mostly does, but does
        // other things for a few calendars, so we can't trust it. Just pad
        // it manually (after the '-' if there is one)
        if(dateStr.charAt(0) === '-') {
            while(dateStr.length < 11) dateStr = '-0' + dateStr.substr(1);
        } else {
            while(dateStr.length < 10) dateStr = '0' + dateStr;
        }

        // TODO: if this is faster, we could use this block for extracting
        // the time components of regular gregorian too
        h = (r < NINETYDAYS) ? Math.floor(timeMs / ONEHOUR) : 0;
        m = (r < NINETYDAYS) ? Math.floor((timeMs % ONEHOUR) / ONEMIN) : 0;
        s = (r < THREEHOURS) ? Math.floor((timeMs % ONEMIN) / ONESEC) : 0;
        msec10 = (r < FIVEMIN) ? (timeMs % ONESEC) * 10 + msecTenths : 0;
    }
    else {
        d = new Date(msRounded);

        dateStr = utcFormat('%Y-%m-%d')(d);

        // <90 days: add hours and minutes - never *only* add hours
        h = (r < NINETYDAYS) ? d.getUTCHours() : 0;
        m = (r < NINETYDAYS) ? d.getUTCMinutes() : 0;
        // <3 hours: add seconds
        s = (r < THREEHOURS) ? d.getUTCSeconds() : 0;
        // <5 minutes: add ms (plus one extra digit, this is msec*10)
        msec10 = (r < FIVEMIN) ? d.getUTCMilliseconds() * 10 + msecTenths : 0;
    }

    return includeTime(dateStr, h, m, s, msec10);
};

// For converting old-style milliseconds to date strings,
// we use the local timezone rather than UTC like we use
// everywhere else, both for backward compatibility and
// because that's how people mostly use javasript date objects.
// Clip one extra day off our date range though so we can't get
// thrown beyond the range by the timezone shift.
exports.ms2DateTimeLocal = function(ms) {
    if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return BADNUM;

    var msecTenths = Math.floor(mod(ms + 0.05, 1) * 10);
    var d = new Date(Math.round(ms - msecTenths / 10));
    var dateStr = d3.time.format('%Y-%m-%d')(d);
    var h = d.getHours();
    var m = d.getMinutes();
    var s = d.getSeconds();
    var msec10 = d.getUTCMilliseconds() * 10 + msecTenths;

    return includeTime(dateStr, h, m, s, msec10);
};

function includeTime(dateStr, h, m, s, msec10) {
    // include each part that has nonzero data in or after it
    if(h || m || s || msec10) {
        dateStr += ' ' + lpad(h, 2) + ':' + lpad(m, 2);
        if(s || msec10) {
            dateStr += ':' + lpad(s, 2);
            if(msec10) {
                var digits = 4;
                while(msec10 % 10 === 0) {
                    digits -= 1;
                    msec10 /= 10;
                }
                dateStr += '.' + lpad(msec10, digits);
            }
        }
    }
    return dateStr;
}

// normalize date format to date string, in case it starts as
// a Date object or milliseconds
// optional dflt is the return value if cleaning fails
exports.cleanDate = function(v, dflt, calendar) {
    // let us use cleanDate to provide a missing default without an error
    if(v === BADNUM) return dflt;
    if(exports.isJSDate(v) || (typeof v === 'number' && isFinite(v))) {
        // do not allow milliseconds (old) or jsdate objects (inherently
        // described as gregorian dates) with world calendars
        if(isWorldCalendar(calendar)) {
            Loggers.error('JS Dates and milliseconds are incompatible with world calendars', v);
            return dflt;
        }

        // NOTE: if someone puts in a year as a number rather than a string,
        // this will mistakenly convert it thinking it's milliseconds from 1970
        // that is: '2012' -> Jan. 1, 2012, but 2012 -> 2012 epoch milliseconds
        v = exports.ms2DateTimeLocal(+v);
        if(!v && dflt !== undefined) return dflt;
    }
    else if(!exports.isDateTime(v, calendar)) {
        Loggers.error('unrecognized date', v);
        return dflt;
    }
    return v;
};

/*
 *  Date formatting for ticks and hovertext
 */

/*
 * modDateFormat: Support world calendars, and add one item to
 * d3's vocabulary:
 * %{n}f where n is the max number of digits of fractional seconds
 */
var fracMatch = /%\d?f/g;
function modDateFormat(fmt, x, formatter, calendar) {

    fmt = fmt.replace(fracMatch, function(match) {
        var digits = Math.min(+(match.charAt(1)) || 6, 6);
        var fracSecs = ((x / 1000 % 1) + 2)
            .toFixed(digits)
            .substr(2).replace(/0+$/, '') || '0';
        return fracSecs;
    });

    var d = new Date(Math.floor(x + 0.05));

    if(isWorldCalendar(calendar)) {
        try {
            fmt = Registry.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar);
        }
        catch(e) {
            return 'Invalid';
        }
    }
    return formatter(fmt)(d);
}

/*
 * formatTime: create a time string from:
 *   x: milliseconds
 *   tr: tickround ('M', 'S', or # digits)
 * only supports UTC times (where every day is 24 hours and 0 is at midnight)
 */
var MAXSECONDS = [59, 59.9, 59.99, 59.999, 59.9999];
function formatTime(x, tr) {
    var timePart = mod(x + 0.05, ONEDAY);

    var timeStr = lpad(Math.floor(timePart / ONEHOUR), 2) + ':' +
        lpad(mod(Math.floor(timePart / ONEMIN), 60), 2);

    if(tr !== 'M') {
        if(!isNumeric(tr)) tr = 0; // should only be 'S'

        /*
         * this is a weird one - and shouldn't come up unless people
         * monkey with tick0 in weird ways, but we need to do something!
         * IN PARTICULAR we had better not display garbage (see below)
         * for numbers we always round to the nearest increment of the
         * precision we're showing, and this seems like the right way to
         * handle seconds and milliseconds, as they have a decimal point
         * and people will interpret that to mean rounding like numbers.
         * but for larger increments we floor the value: it's always
         * 2013 until the ball drops on the new year. We could argue about
         * which field it is where we start rounding (should 12:08:59
         * round to 12:09 if we're stopping at minutes?) but for now I'll
         * say we round seconds but floor everything else. BUT that means
         * we need to never round up to 60 seconds, ie 23:59:60
         */
        var sec = Math.min(mod(x / ONESEC, 60), MAXSECONDS[tr]);

        var secStr = (100 + sec).toFixed(tr).substr(1);
        if(tr > 0) {
            secStr = secStr.replace(/0+$/, '').replace(/[\.]$/, '');
        }

        timeStr += ':' + secStr;
    }
    return timeStr;
}

/*
 * formatDate: turn a date into tick or hover label text.
 *
 *   x: milliseconds, the value to convert
 *   fmt: optional, an explicit format string (d3 format, even for world calendars)
 *   tr: tickround ('y', 'm', 'd', 'M', 'S', or # digits)
 *      used if no explicit fmt is provided
 *   formatter: locale-aware d3 date formatter for standard gregorian calendars
 *      should be the result of exports.getD3DateFormat(gd)
 *   calendar: optional string, the world calendar system to use
 *
 * returns the date/time as a string, potentially with the leading portion
 * on a separate line (after '\n')
 * Note that this means if you provide an explicit format which includes '\n'
 * the axis may choose to strip things after it when they don't change from
 * one tick to the next (as it does with automatic formatting)
 */
exports.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) {
    calendar = isWorldCalendar(calendar) && calendar;

    if(!fmt) {
        if(tr === 'y') fmt = extraFormat.year;
        else if(tr === 'm') fmt = extraFormat.month;
        else if(tr === 'd') {
            fmt = extraFormat.dayMonth + '\n' + extraFormat.year;
        }
        else {
            return formatTime(x, tr) + '\n' + modDateFormat(extraFormat.dayMonthYear, x, formatter, calendar);
        }
    }

    return modDateFormat(fmt, x, formatter, calendar);
};

/*
 * incrementMonth: make a new milliseconds value from the given one,
 * having changed the month
 *
 * special case for world calendars: multiples of 12 are treated as years,
 * even for calendar systems that don't have (always or ever) 12 months/year
 * TODO: perhaps we need a different code for year increments to support this?
 *
 * ms (number): the initial millisecond value
 * dMonth (int): the (signed) number of months to shift
 * calendar (string): the calendar system to use
 *
 * changing month does not (and CANNOT) always preserve day, since
 * months have different lengths. The worst example of this is:
 *   d = new Date(1970,0,31); d.setMonth(1) -> Feb 31 turns into Mar 3
 *
 * But we want to be able to iterate over the last day of each month,
 * regardless of what its number is.
 * So shift 3 days forward, THEN set the new month, then unshift:
 *   1/31 -> 2/28 (or 29) -> 3/31 -> 4/30 -> ...
 *
 * Note that odd behavior still exists if you start from the 26th-28th:
 *   1/28 -> 2/28 -> 3/31
 * but at least you can't shift any dates into the wrong month,
 * and ticks on these days incrementing by month would be very unusual
 */
var THREEDAYS = 3 * ONEDAY;
exports.incrementMonth = function(ms, dMonth, calendar) {
    calendar = isWorldCalendar(calendar) && calendar;

    // pull time out and operate on pure dates, then add time back at the end
    // this gives maximum precision - not that we *normally* care if we're
    // incrementing by month, but better to be safe!
    var timeMs = mod(ms, ONEDAY);
    ms = Math.round(ms - timeMs);

    if(calendar) {
        try {
            var dateJD = Math.round(ms / ONEDAY) + EPOCHJD;
            var calInstance = Registry.getComponentMethod('calendars', 'getCal')(calendar);
            var cDate = calInstance.fromJD(dateJD);

            if(dMonth % 12) calInstance.add(cDate, dMonth, 'm');
            else calInstance.add(cDate, dMonth / 12, 'y');

            return (cDate.toJD() - EPOCHJD) * ONEDAY + timeMs;
        } catch(e) {
            Loggers.error('invalid ms ' + ms + ' in calendar ' + calendar);
            // then keep going in gregorian even though the result will be 'Invalid'
        }
    }

    var y = new Date(ms + THREEDAYS);
    return y.setUTCMonth(y.getUTCMonth() + dMonth) + timeMs - THREEDAYS;
};

/*
 * findExactDates: what fraction of data is exact days, months, or years?
 *
 * data: array of millisecond values
 * calendar (string) the calendar to test against
 */
exports.findExactDates = function(data, calendar) {
    var exactYears = 0;
    var exactMonths = 0;
    var exactDays = 0;
    var blankCount = 0;
    var d;
    var di;

    var calInstance = (
        isWorldCalendar(calendar) &&
        Registry.getComponentMethod('calendars', 'getCal')(calendar)
    );

    for(var i = 0; i < data.length; i++) {
        di = data[i];

        // not date data at all
        if(!isNumeric(di)) {
            blankCount ++;
            continue;
        }

        // not an exact date
        if(di % ONEDAY) continue;

        if(calInstance) {
            try {
                d = calInstance.fromJD(di / ONEDAY + EPOCHJD);
                if(d.day() === 1) {
                    if(d.month() === 1) exactYears++;
                    else exactMonths++;
                }
                else exactDays++;
            }
            catch(e) {
                // invalid date in this calendar - ignore it here.
            }
        }
        else {
            d = new Date(di);
            if(d.getUTCDate() === 1) {
                if(d.getUTCMonth() === 0) exactYears++;
                else exactMonths++;
            }
            else exactDays++;
        }
    }
    exactMonths += exactYears;
    exactDays += exactMonths;

    var dataCount = data.length - blankCount;

    return {
        exactYears: exactYears / dataCount,
        exactMonths: exactMonths / dataCount,
        exactDays: exactDays / dataCount
    };
};


/***/ }),

/***/ "7sfO":
/*!********************************************************************!*\
  !*** ./node_modules/@jupyterlab/tabmanager-extension/lib/index.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const application_1 = __webpack_require__(/*! @jupyterlab/application */ "FkFl");
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
__webpack_require__(/*! ../style/index.css */ "Kta1");
/**
 * The default tab manager extension.
 */
const plugin = {
    id: '@jupyterlab/tabmanager-extension:plugin',
    activate: (app, restorer) => {
        const { shell } = app;
        const tabs = new widgets_1.TabBar({ orientation: 'vertical' });
        const header = document.createElement('header');
        restorer.add(tabs, 'tab-manager');
        tabs.id = 'tab-manager';
        tabs.title.iconClass = 'jp-TabIcon jp-SideBar-tabIcon';
        tabs.title.caption = 'Open Tabs';
        header.textContent = 'Open Tabs';
        tabs.node.insertBefore(header, tabs.contentNode);
        shell.addToLeftArea(tabs, { rank: 600 });
        app.restored.then(() => {
            const populate = () => {
                tabs.clearTabs();
                algorithm_1.each(shell.widgets('main'), widget => {
                    tabs.addTab(widget.title);
                });
            };
            // Connect signal handlers.
            shell.layoutModified.connect(() => {
                populate();
            });
            tabs.tabActivateRequested.connect((sender, tab) => {
                shell.activateById(tab.title.owner.id);
            });
            tabs.tabCloseRequested.connect((sender, tab) => {
                tab.title.owner.close();
            });
            // Populate the tab manager.
            populate();
        });
    },
    autoStart: true,
    requires: [application_1.ILayoutRestorer]
};
/**
 * Export the plugin as default.
 */
exports.default = plugin;


/***/ }),

/***/ "7tlc":
/*!******************************************************************!*\
  !*** ./node_modules/node-libs-browser/node_modules/util/util.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors.
//
// 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.

var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||
  function getOwnPropertyDescriptors(obj) {
    var keys = Object.keys(obj);
    var descriptors = {};
    for (var i = 0; i < keys.length; i++) {
      descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);
    }
    return descriptors;
  };

var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
  if (!isString(f)) {
    var objects = [];
    for (var i = 0; i < arguments.length; i++) {
      objects.push(inspect(arguments[i]));
    }
    return objects.join(' ');
  }

  var i = 1;
  var args = arguments;
  var len = args.length;
  var str = String(f).replace(formatRegExp, function(x) {
    if (x === '%%') return '%';
    if (i >= len) return x;
    switch (x) {
      case '%s': return String(args[i++]);
      case '%d': return Number(args[i++]);
      case '%j':
        try {
          return JSON.stringify(args[i++]);
        } catch (_) {
          return '[Circular]';
        }
      default:
        return x;
    }
  });
  for (var x = args[i]; i < len; x = args[++i]) {
    if (isNull(x) || !isObject(x)) {
      str += ' ' + x;
    } else {
      str += ' ' + inspect(x);
    }
  }
  return str;
};


// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
  if (typeof process !== 'undefined' && process.noDeprecation === true) {
    return fn;
  }

  // Allow for deprecating things in the process of starting up.
  if (typeof process === 'undefined') {
    return function() {
      return exports.deprecate(fn, msg).apply(this, arguments);
    };
  }

  var warned = false;
  function deprecated() {
    if (!warned) {
      if (process.throwDeprecation) {
        throw new Error(msg);
      } else if (process.traceDeprecation) {
        console.trace(msg);
      } else {
        console.error(msg);
      }
      warned = true;
    }
    return fn.apply(this, arguments);
  }

  return deprecated;
};


var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
  if (isUndefined(debugEnviron))
    debugEnviron = process.env.NODE_DEBUG || '';
  set = set.toUpperCase();
  if (!debugs[set]) {
    if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
      var pid = process.pid;
      debugs[set] = function() {
        var msg = exports.format.apply(exports, arguments);
        console.error('%s %d: %s', set, pid, msg);
      };
    } else {
      debugs[set] = function() {};
    }
  }
  return debugs[set];
};


/**
 * Echos the value of a value. Trys to print the value out
 * in the best way possible given the different types.
 *
 * @param {Object} obj The object to print out.
 * @param {Object} opts Optional options object that alters the output.
 */
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
  // default options
  var ctx = {
    seen: [],
    stylize: stylizeNoColor
  };
  // legacy...
  if (arguments.length >= 3) ctx.depth = arguments[2];
  if (arguments.length >= 4) ctx.colors = arguments[3];
  if (isBoolean(opts)) {
    // legacy...
    ctx.showHidden = opts;
  } else if (opts) {
    // got an "options" object
    exports._extend(ctx, opts);
  }
  // set default options
  if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  if (isUndefined(ctx.depth)) ctx.depth = 2;
  if (isUndefined(ctx.colors)) ctx.colors = false;
  if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  if (ctx.colors) ctx.stylize = stylizeWithColor;
  return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;


// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
  'bold' : [1, 22],
  'italic' : [3, 23],
  'underline' : [4, 24],
  'inverse' : [7, 27],
  'white' : [37, 39],
  'grey' : [90, 39],
  'black' : [30, 39],
  'blue' : [34, 39],
  'cyan' : [36, 39],
  'green' : [32, 39],
  'magenta' : [35, 39],
  'red' : [31, 39],
  'yellow' : [33, 39]
};

// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
  'special': 'cyan',
  'number': 'yellow',
  'boolean': 'yellow',
  'undefined': 'grey',
  'null': 'bold',
  'string': 'green',
  'date': 'magenta',
  // "name": intentionally not styling
  'regexp': 'red'
};


function stylizeWithColor(str, styleType) {
  var style = inspect.styles[styleType];

  if (style) {
    return '\u001b[' + inspect.colors[style][0] + 'm' + str +
           '\u001b[' + inspect.colors[style][1] + 'm';
  } else {
    return str;
  }
}


function stylizeNoColor(str, styleType) {
  return str;
}


function arrayToHash(array) {
  var hash = {};

  array.forEach(function(val, idx) {
    hash[val] = true;
  });

  return hash;
}


function formatValue(ctx, value, recurseTimes) {
  // Provide a hook for user-specified inspect functions.
  // Check that value is an object with an inspect function on it
  if (ctx.customInspect &&
      value &&
      isFunction(value.inspect) &&
      // Filter out the util module, it's inspect function is special
      value.inspect !== exports.inspect &&
      // Also filter out any prototype objects using the circular check.
      !(value.constructor && value.constructor.prototype === value)) {
    var ret = value.inspect(recurseTimes, ctx);
    if (!isString(ret)) {
      ret = formatValue(ctx, ret, recurseTimes);
    }
    return ret;
  }

  // Primitive types cannot have properties
  var primitive = formatPrimitive(ctx, value);
  if (primitive) {
    return primitive;
  }

  // Look up the keys of the object.
  var keys = Object.keys(value);
  var visibleKeys = arrayToHash(keys);

  if (ctx.showHidden) {
    keys = Object.getOwnPropertyNames(value);
  }

  // IE doesn't make error fields non-enumerable
  // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  if (isError(value)
      && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
    return formatError(value);
  }

  // Some type of object without properties can be shortcutted.
  if (keys.length === 0) {
    if (isFunction(value)) {
      var name = value.name ? ': ' + value.name : '';
      return ctx.stylize('[Function' + name + ']', 'special');
    }
    if (isRegExp(value)) {
      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
    }
    if (isDate(value)) {
      return ctx.stylize(Date.prototype.toString.call(value), 'date');
    }
    if (isError(value)) {
      return formatError(value);
    }
  }

  var base = '', array = false, braces = ['{', '}'];

  // Make Array say that they are Array
  if (isArray(value)) {
    array = true;
    braces = ['[', ']'];
  }

  // Make functions say that they are functions
  if (isFunction(value)) {
    var n = value.name ? ': ' + value.name : '';
    base = ' [Function' + n + ']';
  }

  // Make RegExps say that they are RegExps
  if (isRegExp(value)) {
    base = ' ' + RegExp.prototype.toString.call(value);
  }

  // Make dates with properties first say the date
  if (isDate(value)) {
    base = ' ' + Date.prototype.toUTCString.call(value);
  }

  // Make error with message first say the error
  if (isError(value)) {
    base = ' ' + formatError(value);
  }

  if (keys.length === 0 && (!array || value.length == 0)) {
    return braces[0] + base + braces[1];
  }

  if (recurseTimes < 0) {
    if (isRegExp(value)) {
      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
    } else {
      return ctx.stylize('[Object]', 'special');
    }
  }

  ctx.seen.push(value);

  var output;
  if (array) {
    output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  } else {
    output = keys.map(function(key) {
      return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
    });
  }

  ctx.seen.pop();

  return reduceToSingleString(output, base, braces);
}


function formatPrimitive(ctx, value) {
  if (isUndefined(value))
    return ctx.stylize('undefined', 'undefined');
  if (isString(value)) {
    var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
                                             .replace(/'/g, "\\'")
                                             .replace(/\\"/g, '"') + '\'';
    return ctx.stylize(simple, 'string');
  }
  if (isNumber(value))
    return ctx.stylize('' + value, 'number');
  if (isBoolean(value))
    return ctx.stylize('' + value, 'boolean');
  // For some reason typeof null is "object", so special case here.
  if (isNull(value))
    return ctx.stylize('null', 'null');
}


function formatError(value) {
  return '[' + Error.prototype.toString.call(value) + ']';
}


function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  var output = [];
  for (var i = 0, l = value.length; i < l; ++i) {
    if (hasOwnProperty(value, String(i))) {
      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
          String(i), true));
    } else {
      output.push('');
    }
  }
  keys.forEach(function(key) {
    if (!key.match(/^\d+$/)) {
      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
          key, true));
    }
  });
  return output;
}


function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  var name, str, desc;
  desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  if (desc.get) {
    if (desc.set) {
      str = ctx.stylize('[Getter/Setter]', 'special');
    } else {
      str = ctx.stylize('[Getter]', 'special');
    }
  } else {
    if (desc.set) {
      str = ctx.stylize('[Setter]', 'special');
    }
  }
  if (!hasOwnProperty(visibleKeys, key)) {
    name = '[' + key + ']';
  }
  if (!str) {
    if (ctx.seen.indexOf(desc.value) < 0) {
      if (isNull(recurseTimes)) {
        str = formatValue(ctx, desc.value, null);
      } else {
        str = formatValue(ctx, desc.value, recurseTimes - 1);
      }
      if (str.indexOf('\n') > -1) {
        if (array) {
          str = str.split('\n').map(function(line) {
            return '  ' + line;
          }).join('\n').substr(2);
        } else {
          str = '\n' + str.split('\n').map(function(line) {
            return '   ' + line;
          }).join('\n');
        }
      }
    } else {
      str = ctx.stylize('[Circular]', 'special');
    }
  }
  if (isUndefined(name)) {
    if (array && key.match(/^\d+$/)) {
      return str;
    }
    name = JSON.stringify('' + key);
    if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
      name = name.substr(1, name.length - 2);
      name = ctx.stylize(name, 'name');
    } else {
      name = name.replace(/'/g, "\\'")
                 .replace(/\\"/g, '"')
                 .replace(/(^"|"$)/g, "'");
      name = ctx.stylize(name, 'string');
    }
  }

  return name + ': ' + str;
}


function reduceToSingleString(output, base, braces) {
  var numLinesEst = 0;
  var length = output.reduce(function(prev, cur) {
    numLinesEst++;
    if (cur.indexOf('\n') >= 0) numLinesEst++;
    return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  }, 0);

  if (length > 60) {
    return braces[0] +
           (base === '' ? '' : base + '\n ') +
           ' ' +
           output.join(',\n  ') +
           ' ' +
           braces[1];
  }

  return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}


// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
  return Array.isArray(ar);
}
exports.isArray = isArray;

function isBoolean(arg) {
  return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;

function isNull(arg) {
  return arg === null;
}
exports.isNull = isNull;

function isNullOrUndefined(arg) {
  return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;

function isNumber(arg) {
  return typeof arg === 'number';
}
exports.isNumber = isNumber;

function isString(arg) {
  return typeof arg === 'string';
}
exports.isString = isString;

function isSymbol(arg) {
  return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;

function isUndefined(arg) {
  return arg === void 0;
}
exports.isUndefined = isUndefined;

function isRegExp(re) {
  return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;

function isObject(arg) {
  return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;

function isDate(d) {
  return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;

function isError(e) {
  return isObject(e) &&
      (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;

function isFunction(arg) {
  return typeof arg === 'function';
}
exports.isFunction = isFunction;

function isPrimitive(arg) {
  return arg === null ||
         typeof arg === 'boolean' ||
         typeof arg === 'number' ||
         typeof arg === 'string' ||
         typeof arg === 'symbol' ||  // ES6 symbol
         typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;

exports.isBuffer = __webpack_require__(/*! ./support/isBuffer */ "j/1Z");

function objectToString(o) {
  return Object.prototype.toString.call(o);
}


function pad(n) {
  return n < 10 ? '0' + n.toString(10) : n.toString(10);
}


var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
              'Oct', 'Nov', 'Dec'];

// 26 Feb 16:19:34
function timestamp() {
  var d = new Date();
  var time = [pad(d.getHours()),
              pad(d.getMinutes()),
              pad(d.getSeconds())].join(':');
  return [d.getDate(), months[d.getMonth()], time].join(' ');
}


// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
  console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};


/**
 * Inherit the prototype methods from one constructor into another.
 *
 * The Function.prototype.inherits from lang.js rewritten as a standalone
 * function (not on Function.prototype). NOTE: If this file is to be loaded
 * during bootstrapping this function needs to be rewritten using some native
 * functions as prototype setup using normal JavaScript does not work as
 * expected during bootstrapping (see mirror.js in r114903).
 *
 * @param {function} ctor Constructor function which needs to inherit the
 *     prototype.
 * @param {function} superCtor Constructor function to inherit prototype from.
 */
exports.inherits = __webpack_require__(/*! inherits */ "P7XM");

exports._extend = function(origin, add) {
  // Don't do anything if add isn't an object
  if (!add || !isObject(add)) return origin;

  var keys = Object.keys(add);
  var i = keys.length;
  while (i--) {
    origin[keys[i]] = add[keys[i]];
  }
  return origin;
};

function hasOwnProperty(obj, prop) {
  return Object.prototype.hasOwnProperty.call(obj, prop);
}

var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;

exports.promisify = function promisify(original) {
  if (typeof original !== 'function')
    throw new TypeError('The "original" argument must be of type Function');

  if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {
    var fn = original[kCustomPromisifiedSymbol];
    if (typeof fn !== 'function') {
      throw new TypeError('The "util.promisify.custom" argument must be of type Function');
    }
    Object.defineProperty(fn, kCustomPromisifiedSymbol, {
      value: fn, enumerable: false, writable: false, configurable: true
    });
    return fn;
  }

  function fn() {
    var promiseResolve, promiseReject;
    var promise = new Promise(function (resolve, reject) {
      promiseResolve = resolve;
      promiseReject = reject;
    });

    var args = [];
    for (var i = 0; i < arguments.length; i++) {
      args.push(arguments[i]);
    }
    args.push(function (err, value) {
      if (err) {
        promiseReject(err);
      } else {
        promiseResolve(value);
      }
    });

    try {
      original.apply(this, args);
    } catch (err) {
      promiseReject(err);
    }

    return promise;
  }

  Object.setPrototypeOf(fn, Object.getPrototypeOf(original));

  if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {
    value: fn, enumerable: false, writable: false, configurable: true
  });
  return Object.defineProperties(
    fn,
    getOwnPropertyDescriptors(original)
  );
}

exports.promisify.custom = kCustomPromisifiedSymbol

function callbackifyOnRejected(reason, cb) {
  // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).
  // Because `null` is a special error value in callbacks which means "no error
  // occurred", we error-wrap so the callback consumer can distinguish between
  // "the promise rejected with null" or "the promise fulfilled with undefined".
  if (!reason) {
    var newReason = new Error('Promise was rejected with a falsy value');
    newReason.reason = reason;
    reason = newReason;
  }
  return cb(reason);
}

function callbackify(original) {
  if (typeof original !== 'function') {
    throw new TypeError('The "original" argument must be of type Function');
  }

  // We DO NOT return the promise as it gives the user a false sense that
  // the promise is actually somehow related to the callback's execution
  // and that the callback throwing will reject the promise.
  function callbackified() {
    var args = [];
    for (var i = 0; i < arguments.length; i++) {
      args.push(arguments[i]);
    }

    var maybeCb = args.pop();
    if (typeof maybeCb !== 'function') {
      throw new TypeError('The last argument must be of type Function');
    }
    var self = this;
    var cb = function() {
      return maybeCb.apply(self, arguments);
    };
    // In true node style we process the callback on `nextTick` with all the
    // implications (stack, `uncaughtException`, `async_hooks`)
    original.apply(this, args)
      .then(function(ret) { process.nextTick(cb, null, ret) },
            function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });
  }

  Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));
  Object.defineProperties(callbackified,
                          getOwnPropertyDescriptors(original));
  return callbackified;
}
exports.callbackify = callbackify;

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../process/browser.js */ "8oxB")))

/***/ }),

/***/ "7vZz":
/*!******************************************************!*\
  !*** ./node_modules/xterm/lib/renderer/GridCache.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var GridCache = (function () {
    function GridCache() {
        this.cache = [];
    }
    GridCache.prototype.resize = function (width, height) {
        for (var x = 0; x < width; x++) {
            if (this.cache.length <= x) {
                this.cache.push([]);
            }
            for (var y = this.cache[x].length; y < height; y++) {
                this.cache[x].push(null);
            }
            this.cache[x].length = height;
        }
        this.cache.length = width;
    };
    GridCache.prototype.clear = function () {
        for (var x = 0; x < this.cache.length; x++) {
            for (var y = 0; y < this.cache[x].length; y++) {
                this.cache[x][y] = null;
            }
        }
    };
    return GridCache;
}());
exports.GridCache = GridCache;

//# sourceMappingURL=GridCache.js.map


/***/ }),

/***/ "7wDu":
/*!***************************************!*\
  !*** ./node_modules/fbjs/lib/Keys.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

module.exports = {
  BACKSPACE: 8,
  TAB: 9,
  RETURN: 13,
  ALT: 18,
  ESC: 27,
  SPACE: 32,
  PAGE_UP: 33,
  PAGE_DOWN: 34,
  END: 35,
  HOME: 36,
  LEFT: 37,
  UP: 38,
  RIGHT: 39,
  DOWN: 40,
  DELETE: 46,
  COMMA: 188,
  PERIOD: 190,
  A: 65,
  Z: 90,
  ZERO: 48,
  NUMPAD_0: 96,
  NUMPAD_9: 105
};

/***/ }),

/***/ "7zrB":
/*!**********************************************!*\
  !*** ./node_modules/asn1.js/lib/asn1/api.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var asn1 = __webpack_require__(/*! ../asn1 */ "f3pb");
var inherits = __webpack_require__(/*! inherits */ "P7XM");

var api = exports;

api.define = function define(name, body) {
  return new Entity(name, body);
};

function Entity(name, body) {
  this.name = name;
  this.body = body;

  this.decoders = {};
  this.encoders = {};
};

Entity.prototype._createNamed = function createNamed(base) {
  var named;
  try {
    named = __webpack_require__(/*! vm */ "BwZh").runInThisContext(
      '(function ' + this.name + '(entity) {\n' +
      '  this._initNamed(entity);\n' +
      '})'
    );
  } catch (e) {
    named = function (entity) {
      this._initNamed(entity);
    };
  }
  inherits(named, base);
  named.prototype._initNamed = function initnamed(entity) {
    base.call(this, entity);
  };

  return new named(this);
};

Entity.prototype._getDecoder = function _getDecoder(enc) {
  enc = enc || 'der';
  // Lazily create decoder
  if (!this.decoders.hasOwnProperty(enc))
    this.decoders[enc] = this._createNamed(asn1.decoders[enc]);
  return this.decoders[enc];
};

Entity.prototype.decode = function decode(data, enc, options) {
  return this._getDecoder(enc).decode(data, options);
};

Entity.prototype._getEncoder = function _getEncoder(enc) {
  enc = enc || 'der';
  // Lazily create encoder
  if (!this.encoders.hasOwnProperty(enc))
    this.encoders[enc] = this._createNamed(asn1.encoders[enc]);
  return this.encoders[enc];
};

Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) {
  return this._getEncoder(enc).encode(data, reporter);
};


/***/ }),

/***/ "8+Fv":
/*!*********************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils/lib/iframe.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
/**
 * A phosphor widget which wraps an IFrame.
 */
class IFrame extends widgets_1.Widget {
    /**
     * Create a new IFrame widget.
     */
    constructor() {
        super({ node: Private.createNode() });
        this.addClass('jp-IFrame');
    }
    /**
     * The url of the IFrame.
     */
    get url() {
        return this.node.querySelector('iframe').getAttribute('src') || '';
    }
    set url(url) {
        this.node.querySelector('iframe').setAttribute('src', url);
    }
}
exports.IFrame = IFrame;
/**
 * A namespace for private data.
 */
var Private;
(function (Private) {
    /**
     * Create the main content node of an iframe widget.
     */
    function createNode() {
        let node = document.createElement('div');
        let iframe = document.createElement('iframe');
        iframe.style.height = '100%';
        iframe.style.width = '100%';
        node.appendChild(iframe);
        return node;
    }
    Private.createNode = createNode;
})(Private || (Private = {}));


/***/ }),

/***/ "8/+R":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/pa-in.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var symbolMap = {
    '1': '੧',
    '2': '੨',
    '3': '੩',
    '4': '੪',
    '5': '੫',
    '6': '੬',
    '7': '੭',
    '8': '੮',
    '9': '੯',
    '0': '੦'
},
numberMap = {
    '੧': '1',
    '੨': '2',
    '੩': '3',
    '੪': '4',
    '੫': '5',
    '੬': '6',
    '੭': '7',
    '੮': '8',
    '੯': '9',
    '੦': '0'
};

var paIn = moment.defineLocale('pa-in', {
    // There are months name as per Nanakshahi Calender but they are not used as rigidly in modern Punjabi.
    months : 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'),
    monthsShort : 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'),
    weekdays : 'ਐਤਵਾਰ_ਸੋਮਵਾਰ_ਮੰਗਲਵਾਰ_ਬੁਧਵਾਰ_ਵੀਰਵਾਰ_ਸ਼ੁੱਕਰਵਾਰ_ਸ਼ਨੀਚਰਵਾਰ'.split('_'),
    weekdaysShort : 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'),
    weekdaysMin : 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'),
    longDateFormat : {
        LT : 'A h:mm ਵਜੇ',
        LTS : 'A h:mm:ss ਵਜੇ',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY, A h:mm ਵਜੇ',
        LLLL : 'dddd, D MMMM YYYY, A h:mm ਵਜੇ'
    },
    calendar : {
        sameDay : '[ਅਜ] LT',
        nextDay : '[ਕਲ] LT',
        nextWeek : 'dddd, LT',
        lastDay : '[ਕਲ] LT',
        lastWeek : '[ਪਿਛਲੇ] dddd, LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : '%s ਵਿੱਚ',
        past : '%s ਪਿਛਲੇ',
        s : 'ਕੁਝ ਸਕਿੰਟ',
        ss : '%d ਸਕਿੰਟ',
        m : 'ਇਕ ਮਿੰਟ',
        mm : '%d ਮਿੰਟ',
        h : 'ਇੱਕ ਘੰਟਾ',
        hh : '%d ਘੰਟੇ',
        d : 'ਇੱਕ ਦਿਨ',
        dd : '%d ਦਿਨ',
        M : 'ਇੱਕ ਮਹੀਨਾ',
        MM : '%d ਮਹੀਨੇ',
        y : 'ਇੱਕ ਸਾਲ',
        yy : '%d ਸਾਲ'
    },
    preparse: function (string) {
        return string.replace(/[੧੨੩੪੫੬੭੮੯੦]/g, function (match) {
            return numberMap[match];
        });
    },
    postformat: function (string) {
        return string.replace(/\d/g, function (match) {
            return symbolMap[match];
        });
    },
    // Punjabi notation for meridiems are quite fuzzy in practice. While there exists
    // a rigid notion of a 'Pahar' it is not used as rigidly in modern Punjabi.
    meridiemParse: /ਰਾਤ|ਸਵੇਰ|ਦੁਪਹਿਰ|ਸ਼ਾਮ/,
    meridiemHour : function (hour, meridiem) {
        if (hour === 12) {
            hour = 0;
        }
        if (meridiem === 'ਰਾਤ') {
            return hour < 4 ? hour : hour + 12;
        } else if (meridiem === 'ਸਵੇਰ') {
            return hour;
        } else if (meridiem === 'ਦੁਪਹਿਰ') {
            return hour >= 10 ? hour : hour + 12;
        } else if (meridiem === 'ਸ਼ਾਮ') {
            return hour + 12;
        }
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 4) {
            return 'ਰਾਤ';
        } else if (hour < 10) {
            return 'ਸਵੇਰ';
        } else if (hour < 17) {
            return 'ਦੁਪਹਿਰ';
        } else if (hour < 20) {
            return 'ਸ਼ਾਮ';
        } else {
            return 'ਰਾਤ';
        }
    },
    week : {
        dow : 0, // Sunday is the first day of the week.
        doy : 6  // The week that contains Jan 1st is the first week of the year.
    }
});

return paIn;

})));


/***/ }),

/***/ "81KI":
/*!*****************************************************************!*\
  !*** ./node_modules/draft-js/lib/insertTextIntoContentState.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule insertTextIntoContentState
 * @format
 * 
 */



var Immutable = __webpack_require__(/*! immutable */ "JPcv");

var insertIntoList = __webpack_require__(/*! ./insertIntoList */ "Zf/v");
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");

var Repeat = Immutable.Repeat;


function insertTextIntoContentState(contentState, selectionState, text, characterMetadata) {
  !selectionState.isCollapsed() ?  true ? invariant(false, '`insertText` should only be called with a collapsed range.') : undefined : void 0;

  var len = text.length;
  if (!len) {
    return contentState;
  }

  var blockMap = contentState.getBlockMap();
  var key = selectionState.getStartKey();
  var offset = selectionState.getStartOffset();
  var block = blockMap.get(key);
  var blockText = block.getText();

  var newBlock = block.merge({
    text: blockText.slice(0, offset) + text + blockText.slice(offset, block.getLength()),
    characterList: insertIntoList(block.getCharacterList(), Repeat(characterMetadata, len).toList(), offset)
  });

  var newOffset = offset + len;

  return contentState.merge({
    blockMap: blockMap.set(key, newBlock),
    selectionAfter: selectionState.merge({
      anchorOffset: newOffset,
      focusOffset: newOffset
    })
  });
}

module.exports = insertTextIntoContentState;

/***/ }),

/***/ "81by":
/*!******************************************************************************!*\
  !*** ./node_modules/react-color/lib/components/photoshop/PhotoshopFields.js ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.PhotoshopPicker = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _color = __webpack_require__(/*! ../../helpers/color */ "p8yl");

var _color2 = _interopRequireDefault(_color);

var _common = __webpack_require__(/*! ../common */ "TM95");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PhotoshopPicker = exports.PhotoshopPicker = function PhotoshopPicker(_ref) {
  var onChange = _ref.onChange,
      rgb = _ref.rgb,
      hsv = _ref.hsv,
      hex = _ref.hex;

  var styles = (0, _reactcss2.default)({
    'default': {
      fields: {
        paddingTop: '5px',
        paddingBottom: '9px',
        width: '80px',
        position: 'relative'
      },
      divider: {
        height: '5px'
      },
      RGBwrap: {
        position: 'relative'
      },
      RGBinput: {
        marginLeft: '40%',
        width: '40%',
        height: '18px',
        border: '1px solid #888888',
        boxShadow: 'inset 0 1px 1px rgba(0,0,0,.1), 0 1px 0 0 #ECECEC',
        marginBottom: '5px',
        fontSize: '13px',
        paddingLeft: '3px',
        marginRight: '10px'
      },
      RGBlabel: {
        left: '0px',
        width: '34px',
        textTransform: 'uppercase',
        fontSize: '13px',
        height: '18px',
        lineHeight: '22px',
        position: 'absolute'
      },
      HEXwrap: {
        position: 'relative'
      },
      HEXinput: {
        marginLeft: '20%',
        width: '80%',
        height: '18px',
        border: '1px solid #888888',
        boxShadow: 'inset 0 1px 1px rgba(0,0,0,.1), 0 1px 0 0 #ECECEC',
        marginBottom: '6px',
        fontSize: '13px',
        paddingLeft: '3px'
      },
      HEXlabel: {
        position: 'absolute',
        top: '0px',
        left: '0px',
        width: '14px',
        textTransform: 'uppercase',
        fontSize: '13px',
        height: '18px',
        lineHeight: '22px'
      },
      fieldSymbols: {
        position: 'absolute',
        top: '5px',
        right: '-7px',
        fontSize: '13px'
      },
      symbol: {
        height: '20px',
        lineHeight: '22px',
        paddingBottom: '7px'
      }
    }
  });

  var handleChange = function handleChange(data, e) {
    if (data['#']) {
      _color2.default.isValidHex(data['#']) && onChange({
        hex: data['#'],
        source: 'hex'
      }, e);
    } else if (data.r || data.g || data.b) {
      onChange({
        r: data.r || rgb.r,
        g: data.g || rgb.g,
        b: data.b || rgb.b,
        source: 'rgb'
      }, e);
    } else if (data.h || data.s || data.v) {
      onChange({
        h: data.h || hsv.h,
        s: data.s || hsv.s,
        v: data.v || hsv.v,
        source: 'hsv'
      }, e);
    }
  };

  return _react2.default.createElement(
    'div',
    { style: styles.fields },
    _react2.default.createElement(_common.EditableInput, {
      style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
      label: 'h',
      value: Math.round(hsv.h),
      onChange: handleChange
    }),
    _react2.default.createElement(_common.EditableInput, {
      style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
      label: 's',
      value: Math.round(hsv.s * 100),
      onChange: handleChange
    }),
    _react2.default.createElement(_common.EditableInput, {
      style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
      label: 'v',
      value: Math.round(hsv.v * 100),
      onChange: handleChange
    }),
    _react2.default.createElement('div', { style: styles.divider }),
    _react2.default.createElement(_common.EditableInput, {
      style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
      label: 'r',
      value: rgb.r,
      onChange: handleChange
    }),
    _react2.default.createElement(_common.EditableInput, {
      style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
      label: 'g',
      value: rgb.g,
      onChange: handleChange
    }),
    _react2.default.createElement(_common.EditableInput, {
      style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
      label: 'b',
      value: rgb.b,
      onChange: handleChange
    }),
    _react2.default.createElement('div', { style: styles.divider }),
    _react2.default.createElement(_common.EditableInput, {
      style: { wrap: styles.HEXwrap, input: styles.HEXinput, label: styles.HEXlabel },
      label: '#',
      value: hex.replace('#', ''),
      onChange: handleChange
    }),
    _react2.default.createElement(
      'div',
      { style: styles.fieldSymbols },
      _react2.default.createElement(
        'div',
        { style: styles.symbol },
        '\xB0'
      ),
      _react2.default.createElement(
        'div',
        { style: styles.symbol },
        '%'
      ),
      _react2.default.createElement(
        'div',
        { style: styles.symbol },
        '%'
      )
    )
  );
};

exports.default = PhotoshopPicker;

/***/ }),

/***/ "82c5":
/*!***************************************************************************!*\
  !*** ./node_modules/font-awesome/fonts/fontawesome-webfont.woff2?v=4.7.0 ***!
  \***************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__.p + "af7ae505a9eed503f8b8e6982036873e.woff2";

/***/ }),

/***/ "83KV":
/*!***********************************************************!*\
  !*** ./node_modules/fbjs/lib/getDocumentScrollElement.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks
 */



var isWebkit = typeof navigator !== 'undefined' && navigator.userAgent.indexOf('AppleWebKit') > -1;

/**
 * Gets the element with the document scroll properties such as `scrollLeft` and
 * `scrollHeight`. This may differ across different browsers.
 *
 * NOTE: The return value can be null if the DOM is not yet ready.
 *
 * @param {?DOMDocument} doc Defaults to current document.
 * @return {?DOMElement}
 */
function getDocumentScrollElement(doc) {
  doc = doc || document;
  if (doc.scrollingElement) {
    return doc.scrollingElement;
  }
  return !isWebkit && doc.compatMode === 'CSS1Compat' ? doc.documentElement : doc.body;
}

module.exports = getDocumentScrollElement;

/***/ }),

/***/ "84Sa":
/*!***********************************************************************!*\
  !*** ./node_modules/react-resizable-rotatable-draggable/lib/index.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _ResizableRect = _interopRequireDefault(__webpack_require__(/*! ./ResizableRect */ "wjpj"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var _default = _ResizableRect.default;
exports.default = _default;

/***/ }),

/***/ "84lc":
/*!**************************************************************!*\
  !*** ./node_modules/draft-js/lib/CompositeDraftDecorator.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule CompositeDraftDecorator
 * @format
 * 
 */



function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Immutable = __webpack_require__(/*! immutable */ "JPcv");

var List = Immutable.List;


var DELIMITER = '.';

/**
 * A CompositeDraftDecorator traverses through a list of DraftDecorator
 * instances to identify sections of a ContentBlock that should be rendered
 * in a "decorated" manner. For example, hashtags, mentions, and links may
 * be intended to stand out visually, be rendered as anchors, etc.
 *
 * The list of decorators supplied to the constructor will be used in the
 * order they are provided. This allows the caller to specify a priority for
 * string matching, in case of match collisions among decorators.
 *
 * For instance, I may have a link with a `#` in its text. Though this section
 * of text may match our hashtag decorator, it should not be treated as a
 * hashtag. I should therefore list my link DraftDecorator
 * before my hashtag DraftDecorator when constructing this composite
 * decorator instance.
 *
 * Thus, when a collision like this is encountered, the earlier match is
 * preserved and the new match is discarded.
 */

var CompositeDraftDecorator = function () {
  function CompositeDraftDecorator(decorators) {
    _classCallCheck(this, CompositeDraftDecorator);

    // Copy the decorator array, since we use this array order to determine
    // precedence of decoration matching. If the array is mutated externally,
    // we don't want to be affected here.
    this._decorators = decorators.slice();
  }

  CompositeDraftDecorator.prototype.getDecorations = function getDecorations(block, contentState) {
    var decorations = Array(block.getText().length).fill(null);

    this._decorators.forEach(function ( /*object*/decorator, /*number*/ii) {
      var counter = 0;
      var strategy = decorator.strategy;
      var callback = function callback( /*number*/start, /*number*/end) {
        // Find out if any of our matching range is already occupied
        // by another decorator. If so, discard the match. Otherwise, store
        // the component key for rendering.
        if (canOccupySlice(decorations, start, end)) {
          occupySlice(decorations, start, end, ii + DELIMITER + counter);
          counter++;
        }
      };
      strategy(block, callback, contentState);
    });

    return List(decorations);
  };

  CompositeDraftDecorator.prototype.getComponentForKey = function getComponentForKey(key) {
    var componentKey = parseInt(key.split(DELIMITER)[0], 10);
    return this._decorators[componentKey].component;
  };

  CompositeDraftDecorator.prototype.getPropsForKey = function getPropsForKey(key) {
    var componentKey = parseInt(key.split(DELIMITER)[0], 10);
    return this._decorators[componentKey].props;
  };

  return CompositeDraftDecorator;
}();

/**
 * Determine whether we can occupy the specified slice of the decorations
 * array.
 */


function canOccupySlice(decorations, start, end) {
  for (var ii = start; ii < end; ii++) {
    if (decorations[ii] != null) {
      return false;
    }
  }
  return true;
}

/**
 * Splice the specified component into our decoration array at the desired
 * range.
 */
function occupySlice(targetArr, start, end, componentKey) {
  for (var ii = start; ii < end; ii++) {
    targetArr[ii] = componentKey;
  }
}

module.exports = CompositeDraftDecorator;

/***/ }),

/***/ "86MQ":
/*!*****************************************************!*\
  !*** ./node_modules/elliptic/lib/elliptic/utils.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var utils = exports;
var BN = __webpack_require__(/*! bn.js */ "OZ/i");
var minAssert = __webpack_require__(/*! minimalistic-assert */ "2j6C");
var minUtils = __webpack_require__(/*! minimalistic-crypto-utils */ "dlgc");

utils.assert = minAssert;
utils.toArray = minUtils.toArray;
utils.zero2 = minUtils.zero2;
utils.toHex = minUtils.toHex;
utils.encode = minUtils.encode;

// Represent num in a w-NAF form
function getNAF(num, w) {
  var naf = [];
  var ws = 1 << (w + 1);
  var k = num.clone();
  while (k.cmpn(1) >= 0) {
    var z;
    if (k.isOdd()) {
      var mod = k.andln(ws - 1);
      if (mod > (ws >> 1) - 1)
        z = (ws >> 1) - mod;
      else
        z = mod;
      k.isubn(z);
    } else {
      z = 0;
    }
    naf.push(z);

    // Optimization, shift by word if possible
    var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;
    for (var i = 1; i < shift; i++)
      naf.push(0);
    k.iushrn(shift);
  }

  return naf;
}
utils.getNAF = getNAF;

// Represent k1, k2 in a Joint Sparse Form
function getJSF(k1, k2) {
  var jsf = [
    [],
    []
  ];

  k1 = k1.clone();
  k2 = k2.clone();
  var d1 = 0;
  var d2 = 0;
  while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {

    // First phase
    var m14 = (k1.andln(3) + d1) & 3;
    var m24 = (k2.andln(3) + d2) & 3;
    if (m14 === 3)
      m14 = -1;
    if (m24 === 3)
      m24 = -1;
    var u1;
    if ((m14 & 1) === 0) {
      u1 = 0;
    } else {
      var m8 = (k1.andln(7) + d1) & 7;
      if ((m8 === 3 || m8 === 5) && m24 === 2)
        u1 = -m14;
      else
        u1 = m14;
    }
    jsf[0].push(u1);

    var u2;
    if ((m24 & 1) === 0) {
      u2 = 0;
    } else {
      var m8 = (k2.andln(7) + d2) & 7;
      if ((m8 === 3 || m8 === 5) && m14 === 2)
        u2 = -m24;
      else
        u2 = m24;
    }
    jsf[1].push(u2);

    // Second phase
    if (2 * d1 === u1 + 1)
      d1 = 1 - d1;
    if (2 * d2 === u2 + 1)
      d2 = 1 - d2;
    k1.iushrn(1);
    k2.iushrn(1);
  }

  return jsf;
}
utils.getJSF = getJSF;

function cachedProperty(obj, name, computer) {
  var key = '_' + name;
  obj.prototype[name] = function cachedProperty() {
    return this[key] !== undefined ? this[key] :
           this[key] = computer.call(this);
  };
}
utils.cachedProperty = cachedProperty;

function parseBytes(bytes) {
  return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :
                                     bytes;
}
utils.parseBytes = parseBytes;

function intFromLE(bytes) {
  return new BN(bytes, 'hex', 'le');
}
utils.intFromLE = intFromLE;



/***/ }),

/***/ "88Gu":
/*!******************************************!*\
  !*** ./node_modules/lodash/_shortOut.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
    HOT_SPAN = 16;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeNow = Date.now;

/**
 * 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);
  };
}

module.exports = shortOut;


/***/ }),

/***/ "8943":
/*!******************************************************************!*\
  !*** ./node_modules/@jupyterlab/mainmenu-extension/lib/index.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const mainmenu_1 = __webpack_require__(/*! @jupyterlab/mainmenu */ "N4Qf");
const services_1 = __webpack_require__(/*! @jupyterlab/services */ "S9up");
/**
 * A namespace for command IDs of semantic extension points.
 */
var CommandIDs;
(function (CommandIDs) {
    CommandIDs.activatePreviouslyUsedTab = 'tabmenu:activate-previously-used-tab';
    CommandIDs.undo = 'editmenu:undo';
    CommandIDs.redo = 'editmenu:redo';
    CommandIDs.clearCurrent = 'editmenu:clear-current';
    CommandIDs.clearAll = 'editmenu:clear-all';
    CommandIDs.find = 'editmenu:find';
    CommandIDs.findAndReplace = 'editmenu:find-and-replace';
    CommandIDs.goToLine = 'editmenu:go-to-line';
    CommandIDs.closeAndCleanup = 'filemenu:close-and-cleanup';
    CommandIDs.persistAndSave = 'filemenu:persist-and-save';
    CommandIDs.createConsole = 'filemenu:create-console';
    CommandIDs.quit = 'filemenu:quit';
    CommandIDs.interruptKernel = 'kernelmenu:interrupt';
    CommandIDs.restartKernel = 'kernelmenu:restart';
    CommandIDs.restartKernelAndClear = 'kernelmenu:restart-and-clear';
    CommandIDs.changeKernel = 'kernelmenu:change';
    CommandIDs.shutdownKernel = 'kernelmenu:shutdown';
    CommandIDs.shutdownAllKernels = 'kernelmenu:shutdownAll';
    CommandIDs.wordWrap = 'viewmenu:word-wrap';
    CommandIDs.lineNumbering = 'viewmenu:line-numbering';
    CommandIDs.matchBrackets = 'viewmenu:match-brackets';
    CommandIDs.run = 'runmenu:run';
    CommandIDs.runAll = 'runmenu:run-all';
    CommandIDs.restartAndRunAll = 'runmenu:restart-and-run-all';
    CommandIDs.runAbove = 'runmenu:run-above';
    CommandIDs.runBelow = 'runmenu:run-below';
})(CommandIDs = exports.CommandIDs || (exports.CommandIDs = {}));
/**
 * A service providing an interface to the main menu.
 */
const menuPlugin = {
    id: '@jupyterlab/mainmenu-extension:plugin',
    requires: [apputils_1.ICommandPalette],
    provides: mainmenu_1.IMainMenu,
    activate: (app, palette) => {
        let menu = new mainmenu_1.MainMenu(app.commands);
        menu.id = 'jp-MainMenu';
        let logo = new widgets_1.Widget();
        logo.addClass('jp-MainAreaPortraitIcon');
        logo.addClass('jp-JupyterIcon');
        logo.id = 'jp-MainLogo';
        let quitButton = coreutils_1.PageConfig.getOption('quit_button');
        menu.fileMenu.quitEntry = quitButton === 'True';
        // Create the application menus.
        createEditMenu(app, menu.editMenu);
        createFileMenu(app, menu.fileMenu);
        createKernelMenu(app, menu.kernelMenu);
        createRunMenu(app, menu.runMenu);
        createSettingsMenu(app, menu.settingsMenu);
        createViewMenu(app, menu.viewMenu);
        createTabsMenu(app, menu.tabsMenu);
        if (menu.fileMenu.quitEntry) {
            palette.addItem({
                command: CommandIDs.quit,
                category: 'Main Area'
            });
        }
        palette.addItem({
            command: CommandIDs.shutdownAllKernels,
            category: 'Kernel Operations'
        });
        palette.addItem({
            command: CommandIDs.activatePreviouslyUsedTab,
            category: 'Main Area'
        });
        app.shell.addToTopArea(logo);
        app.shell.addToTopArea(menu);
        return menu;
    }
};
/**
 * Create the basic `Edit` menu.
 */
function createEditMenu(app, menu) {
    const commands = menu.menu.commands;
    // Add the undo/redo commands the the Edit menu.
    commands.addCommand(CommandIDs.undo, {
        label: 'Undo',
        isEnabled: Private.delegateEnabled(app, menu.undoers, 'undo'),
        execute: Private.delegateExecute(app, menu.undoers, 'undo')
    });
    commands.addCommand(CommandIDs.redo, {
        label: 'Redo',
        isEnabled: Private.delegateEnabled(app, menu.undoers, 'redo'),
        execute: Private.delegateExecute(app, menu.undoers, 'redo')
    });
    menu.addGroup([{ command: CommandIDs.undo }, { command: CommandIDs.redo }], 0);
    // Add the clear commands to the Edit menu.
    commands.addCommand(CommandIDs.clearCurrent, {
        label: () => {
            const noun = Private.delegateLabel(app, menu.clearers, 'noun');
            const enabled = Private.delegateEnabled(app, menu.clearers, 'clearCurrent')();
            return `Clear${enabled ? ` ${noun}` : ''}`;
        },
        isEnabled: Private.delegateEnabled(app, menu.clearers, 'clearCurrent'),
        execute: Private.delegateExecute(app, menu.clearers, 'clearCurrent')
    });
    commands.addCommand(CommandIDs.clearAll, {
        label: () => {
            const noun = Private.delegateLabel(app, menu.clearers, 'pluralNoun');
            const enabled = Private.delegateEnabled(app, menu.clearers, 'clearAll')();
            return `Clear All${enabled ? ` ${noun}` : ''}`;
        },
        isEnabled: Private.delegateEnabled(app, menu.clearers, 'clearAll'),
        execute: Private.delegateExecute(app, menu.clearers, 'clearAll')
    });
    menu.addGroup([{ command: CommandIDs.clearCurrent }, { command: CommandIDs.clearAll }], 10);
    // Add the find/replace commands the the Edit menu.
    commands.addCommand(CommandIDs.find, {
        label: 'Find…',
        isEnabled: Private.delegateEnabled(app, menu.findReplacers, 'find'),
        execute: Private.delegateExecute(app, menu.findReplacers, 'find')
    });
    commands.addCommand(CommandIDs.findAndReplace, {
        label: 'Find and Replace…',
        isEnabled: Private.delegateEnabled(app, menu.findReplacers, 'findAndReplace'),
        execute: Private.delegateExecute(app, menu.findReplacers, 'findAndReplace')
    });
    menu.addGroup([{ command: CommandIDs.find }, { command: CommandIDs.findAndReplace }], 200);
    commands.addCommand(CommandIDs.goToLine, {
        label: 'Go to Line…',
        isEnabled: Private.delegateEnabled(app, menu.goToLiners, 'goToLine'),
        execute: Private.delegateExecute(app, menu.goToLiners, 'goToLine')
    });
    menu.addGroup([{ command: CommandIDs.goToLine }], 200);
}
exports.createEditMenu = createEditMenu;
/**
 * Create the basic `File` menu.
 */
function createFileMenu(app, menu) {
    const commands = menu.menu.commands;
    // Add a delegator command for closing and cleaning up an activity.
    commands.addCommand(CommandIDs.closeAndCleanup, {
        label: () => {
            const action = Private.delegateLabel(app, menu.closeAndCleaners, 'action');
            const name = Private.delegateLabel(app, menu.closeAndCleaners, 'name');
            return `Close and ${action ? ` ${action} ${name}` : 'Shutdown'}`;
        },
        isEnabled: Private.delegateEnabled(app, menu.closeAndCleaners, 'closeAndCleanup'),
        execute: Private.delegateExecute(app, menu.closeAndCleaners, 'closeAndCleanup')
    });
    // Add a delegator command for persisting data then saving.
    commands.addCommand(CommandIDs.persistAndSave, {
        label: () => {
            const action = Private.delegateLabel(app, menu.persistAndSavers, 'action');
            const name = Private.delegateLabel(app, menu.persistAndSavers, 'name');
            return `Save ${name} ${action || 'with Extras'}`;
        },
        isEnabled: args => {
            return (Private.delegateEnabled(app, menu.persistAndSavers, 'persistAndSave')() && commands.isEnabled('docmanager:save', args));
        },
        execute: Private.delegateExecute(app, menu.persistAndSavers, 'persistAndSave')
    });
    // Add a delegator command for creating a console for an activity.
    commands.addCommand(CommandIDs.createConsole, {
        label: () => {
            const name = Private.delegateLabel(app, menu.consoleCreators, 'name');
            const label = `New Console for ${name ? name : 'Activity'}`;
            return label;
        },
        isEnabled: Private.delegateEnabled(app, menu.consoleCreators, 'createConsole'),
        execute: Private.delegateExecute(app, menu.consoleCreators, 'createConsole')
    });
    commands.addCommand(CommandIDs.quit, {
        label: 'Quit',
        caption: 'Quit JupyterLab',
        execute: () => {
            apputils_1.showDialog({
                title: 'Quit confirmation',
                body: 'Please confirm you want to quit JupyterLab.',
                buttons: [apputils_1.Dialog.cancelButton(), apputils_1.Dialog.warnButton({ label: 'Quit' })]
            }).then(result => {
                if (result.button.accept) {
                    let setting = services_1.ServerConnection.makeSettings();
                    let apiURL = coreutils_1.URLExt.join(setting.baseUrl, 'api/shutdown');
                    services_1.ServerConnection.makeRequest(apiURL, { method: 'POST' }, setting)
                        .then(result => {
                        if (result.ok) {
                            // Close this window if the shutdown request has been successful
                            let body = document.createElement('div');
                            body.innerHTML = `<p>You have shut down the Jupyter server. You can now close this tab.</p>
                  <p>To use JupyterLab again, you will need to relaunch it.</p>`;
                            apputils_1.showDialog({
                                title: 'Server stopped',
                                body: new widgets_1.Widget({ node: body }),
                                buttons: []
                            });
                            window.close();
                        }
                        else {
                            throw new services_1.ServerConnection.ResponseError(result);
                        }
                    })
                        .catch(data => {
                        throw new services_1.ServerConnection.NetworkError(data);
                    });
                }
            });
        }
    });
    // Add the new group
    const newGroup = [
        { type: 'submenu', submenu: menu.newMenu.menu },
        { command: 'filebrowser:create-main-launcher' }
    ];
    const newViewGroup = [
        { command: 'docmanager:clone' },
        { command: CommandIDs.createConsole },
        { command: 'docmanager:open-direct' }
    ];
    // Add the close group
    const closeGroup = [
        'docmanager:close',
        'filemenu:close-and-cleanup',
        'docmanager:close-all-files'
    ].map(command => {
        return { command };
    });
    // Add save group.
    const saveGroup = [
        'docmanager:save',
        'filemenu:persist-and-save',
        'docmanager:save-as',
        'docmanager:save-all'
    ].map(command => {
        return { command };
    });
    // Add the re group.
    const reGroup = [
        'docmanager:reload',
        'docmanager:restore-checkpoint',
        'docmanager:rename'
    ].map(command => {
        return { command };
    });
    // Add the quit group.
    const quitGroup = [{ command: 'filemenu:quit' }];
    menu.addGroup(newGroup, 0);
    menu.addGroup(newViewGroup, 1);
    menu.addGroup(closeGroup, 2);
    menu.addGroup(saveGroup, 3);
    menu.addGroup(reGroup, 4);
    if (menu.quitEntry) {
        menu.addGroup(quitGroup, 99);
    }
}
exports.createFileMenu = createFileMenu;
/**
 * Create the basic `Kernel` menu.
 */
function createKernelMenu(app, menu) {
    const commands = menu.menu.commands;
    commands.addCommand(CommandIDs.interruptKernel, {
        label: 'Interrupt Kernel',
        isEnabled: Private.delegateEnabled(app, menu.kernelUsers, 'interruptKernel'),
        execute: Private.delegateExecute(app, menu.kernelUsers, 'interruptKernel')
    });
    commands.addCommand(CommandIDs.restartKernel, {
        label: 'Restart Kernel…',
        isEnabled: Private.delegateEnabled(app, menu.kernelUsers, 'restartKernel'),
        execute: Private.delegateExecute(app, menu.kernelUsers, 'restartKernel')
    });
    commands.addCommand(CommandIDs.restartKernelAndClear, {
        label: () => {
            const noun = Private.delegateLabel(app, menu.kernelUsers, 'noun');
            const enabled = Private.delegateEnabled(app, menu.kernelUsers, 'restartKernelAndClear')();
            return `Restart Kernel and Clear${enabled ? ` ${noun}` : ''}…`;
        },
        isEnabled: Private.delegateEnabled(app, menu.kernelUsers, 'restartKernelAndClear'),
        execute: Private.delegateExecute(app, menu.kernelUsers, 'restartKernelAndClear')
    });
    commands.addCommand(CommandIDs.changeKernel, {
        label: 'Change Kernel…',
        isEnabled: Private.delegateEnabled(app, menu.kernelUsers, 'changeKernel'),
        execute: Private.delegateExecute(app, menu.kernelUsers, 'changeKernel')
    });
    commands.addCommand(CommandIDs.shutdownKernel, {
        label: 'Shutdown Kernel',
        isEnabled: Private.delegateEnabled(app, menu.kernelUsers, 'shutdownKernel'),
        execute: Private.delegateExecute(app, menu.kernelUsers, 'shutdownKernel')
    });
    commands.addCommand(CommandIDs.shutdownAllKernels, {
        label: 'Shutdown All Kernels…',
        isEnabled: () => {
            return app.serviceManager.sessions.running().next() !== undefined;
        },
        execute: () => {
            apputils_1.showDialog({
                title: 'Shutdown All?',
                body: 'Shut down all kernels?',
                buttons: [
                    apputils_1.Dialog.cancelButton(),
                    apputils_1.Dialog.warnButton({ label: 'SHUTDOWN' })
                ]
            }).then(result => {
                if (result.button.accept) {
                    return app.serviceManager.sessions.shutdownAll();
                }
            });
        }
    });
    const restartGroup = [
        CommandIDs.restartKernel,
        CommandIDs.restartKernelAndClear,
        CommandIDs.restartAndRunAll
    ].map(command => {
        return { command };
    });
    menu.addGroup([{ command: CommandIDs.interruptKernel }], 0);
    menu.addGroup(restartGroup, 1);
    menu.addGroup([
        { command: CommandIDs.shutdownKernel },
        { command: CommandIDs.shutdownAllKernels }
    ], 2);
    menu.addGroup([{ command: CommandIDs.changeKernel }], 3);
}
exports.createKernelMenu = createKernelMenu;
/**
 * Create the basic `View` menu.
 */
function createViewMenu(app, menu) {
    const commands = menu.menu.commands;
    commands.addCommand(CommandIDs.lineNumbering, {
        label: 'Show Line Numbers',
        isEnabled: Private.delegateEnabled(app, menu.editorViewers, 'toggleLineNumbers'),
        isToggled: Private.delegateToggled(app, menu.editorViewers, 'lineNumbersToggled'),
        execute: Private.delegateExecute(app, menu.editorViewers, 'toggleLineNumbers')
    });
    commands.addCommand(CommandIDs.matchBrackets, {
        label: 'Match Brackets',
        isEnabled: Private.delegateEnabled(app, menu.editorViewers, 'toggleMatchBrackets'),
        isToggled: Private.delegateToggled(app, menu.editorViewers, 'matchBracketsToggled'),
        execute: Private.delegateExecute(app, menu.editorViewers, 'toggleMatchBrackets')
    });
    commands.addCommand(CommandIDs.wordWrap, {
        label: 'Wrap Words',
        isEnabled: Private.delegateEnabled(app, menu.editorViewers, 'toggleWordWrap'),
        isToggled: Private.delegateToggled(app, menu.editorViewers, 'wordWrapToggled'),
        execute: Private.delegateExecute(app, menu.editorViewers, 'toggleWordWrap')
    });
    menu.addGroup([
        { command: 'application:toggle-left-area' },
        { command: 'application:toggle-right-area' }
    ], 0);
    const editorViewerGroup = [
        CommandIDs.lineNumbering,
        CommandIDs.matchBrackets,
        CommandIDs.wordWrap
    ].map(command => {
        return { command };
    });
    menu.addGroup(editorViewerGroup, 10);
    // Add the command for toggling single-document mode.
    menu.addGroup([
        { command: 'application:toggle-presentation-mode' },
        { command: 'application:toggle-mode' }
    ], 1000);
}
exports.createViewMenu = createViewMenu;
function createRunMenu(app, menu) {
    const commands = menu.menu.commands;
    commands.addCommand(CommandIDs.run, {
        label: () => {
            const noun = Private.delegateLabel(app, menu.codeRunners, 'noun');
            const enabled = Private.delegateEnabled(app, menu.codeRunners, 'run')();
            return `Run Selected${enabled ? ` ${noun}` : ''}`;
        },
        isEnabled: Private.delegateEnabled(app, menu.codeRunners, 'run'),
        execute: Private.delegateExecute(app, menu.codeRunners, 'run')
    });
    commands.addCommand(CommandIDs.runAll, {
        label: () => {
            const noun = Private.delegateLabel(app, menu.codeRunners, 'noun');
            const enabled = Private.delegateEnabled(app, menu.codeRunners, 'runAll')();
            return `Run All${enabled ? ` ${noun}` : ''}`;
        },
        isEnabled: Private.delegateEnabled(app, menu.codeRunners, 'runAll'),
        execute: Private.delegateExecute(app, menu.codeRunners, 'runAll')
    });
    commands.addCommand(CommandIDs.restartAndRunAll, {
        label: () => {
            const noun = Private.delegateLabel(app, menu.codeRunners, 'noun');
            const enabled = Private.delegateEnabled(app, menu.codeRunners, 'restartAndRunAll')();
            return `Restart Kernel and Run All${enabled ? ` ${noun}` : ''}…`;
        },
        isEnabled: Private.delegateEnabled(app, menu.codeRunners, 'restartAndRunAll'),
        execute: Private.delegateExecute(app, menu.codeRunners, 'restartAndRunAll')
    });
    const runAllGroup = [CommandIDs.runAll, CommandIDs.restartAndRunAll].map(command => {
        return { command };
    });
    menu.addGroup([{ command: CommandIDs.run }], 0);
    menu.addGroup(runAllGroup, 999);
}
exports.createRunMenu = createRunMenu;
function createSettingsMenu(app, menu) {
    menu.addGroup([{ command: 'settingeditor:open' }], 1000);
}
exports.createSettingsMenu = createSettingsMenu;
function createTabsMenu(app, menu) {
    const commands = app.commands;
    // Add commands for cycling the active tabs.
    menu.addGroup([
        { command: 'application:activate-next-tab' },
        { command: 'application:activate-previous-tab' },
        { command: CommandIDs.activatePreviouslyUsedTab }
    ], 0);
    // A list of the active tabs in the main area.
    const tabGroup = [];
    // A disposable for getting rid of the out-of-date tabs list.
    let disposable;
    // Utility function to create a command to activate
    // a given tab, or get it if it already exists.
    const createMenuItem = (widget) => {
        const commandID = `tabmenu:activate-${widget.id}`;
        if (!commands.hasCommand(commandID)) {
            commands.addCommand(commandID, {
                label: () => widget.title.label,
                isVisible: () => !widget.isDisposed,
                isEnabled: () => !widget.isDisposed,
                isToggled: () => app.shell.currentWidget === widget,
                execute: () => app.shell.activateById(widget.id)
            });
        }
        return { command: commandID };
    };
    let previousId = '';
    // Command to toggle between the current
    // tab and the last modified tab.
    commands.addCommand(CommandIDs.activatePreviouslyUsedTab, {
        label: 'Activate Previously Used Tab',
        isEnabled: () => !!previousId,
        execute: () => previousId && app.commands.execute(`tabmenu:activate-${previousId}`)
    });
    app.restored.then(() => {
        // Iterate over the current widgets in the
        // main area, and add them to the tab group
        // of the menu.
        const populateTabs = () => {
            // remove the previous tab list
            if (disposable && !disposable.isDisposed) {
                disposable.dispose();
            }
            tabGroup.length = 0;
            let isPreviouslyUsedTabAttached = false;
            algorithm_1.each(app.shell.widgets('main'), widget => {
                if (widget.id === previousId) {
                    isPreviouslyUsedTabAttached = true;
                }
                tabGroup.push(createMenuItem(widget));
            });
            disposable = menu.addGroup(tabGroup, 1);
            previousId = isPreviouslyUsedTabAttached ? previousId : '';
        };
        populateTabs();
        app.shell.layoutModified.connect(() => {
            populateTabs();
        });
        // Update the id of the previous active tab if
        // a new tab is selected.
        app.shell.currentChanged.connect((sender, args) => {
            let widget = args.oldValue;
            if (!widget) {
                return;
            }
            previousId = widget.id;
        });
    });
}
exports.createTabsMenu = createTabsMenu;
exports.default = menuPlugin;
/**
 * A namespace for Private data.
 */
var Private;
(function (Private) {
    /**
     * Return the first value of the iterable that satisfies the predicate
     * function.
     */
    function find(it, predicate) {
        for (let value of it) {
            if (predicate(value)) {
                return value;
            }
        }
        return undefined;
    }
    /**
     * A utility function that delegates a portion of a label to an IMenuExtender.
     */
    function delegateLabel(app, s, label) {
        let widget = app.shell.currentWidget;
        const extender = find(s, value => value.tracker.has(widget));
        if (!extender) {
            return '';
        }
        // Coerce the result to be a string. When Typedoc is updated to use
        // Typescript 2.8, we can possibly use conditional types to get Typescript
        // to recognize this is a string.
        return extender[label];
    }
    Private.delegateLabel = delegateLabel;
    /**
     * A utility function that delegates command execution
     * to an IMenuExtender.
     */
    function delegateExecute(app, s, executor) {
        return () => {
            let widget = app.shell.currentWidget;
            const extender = find(s, value => value.tracker.has(widget));
            if (!extender) {
                return Promise.resolve(void 0);
            }
            // Coerce the result to be a function. When Typedoc is updated to use
            // Typescript 2.8, we can possibly use conditional types to get Typescript
            // to recognize this is a function.
            let f = extender[executor];
            return f(widget);
        };
    }
    Private.delegateExecute = delegateExecute;
    /**
     * A utility function that delegates whether a command is enabled
     * to an IMenuExtender.
     */
    function delegateEnabled(app, s, executor) {
        return () => {
            let widget = app.shell.currentWidget;
            const extender = find(s, value => value.tracker.has(widget));
            return (!!extender &&
                !!extender[executor] &&
                (extender.isEnabled ? extender.isEnabled(widget) : true));
        };
    }
    Private.delegateEnabled = delegateEnabled;
    /**
     * A utility function that delegates whether a command is toggled
     * for an IMenuExtender.
     */
    function delegateToggled(app, s, toggled) {
        return () => {
            let widget = app.shell.currentWidget;
            const extender = find(s, value => value.tracker.has(widget));
            // Coerce extender[toggled] to be a function. When Typedoc is updated to use
            // Typescript 2.8, we can possibly use conditional types to get Typescript
            // to recognize this is a function.
            return (!!extender &&
                !!extender[toggled] &&
                !!extender[toggled](widget));
        };
    }
    Private.delegateToggled = delegateToggled;
})(Private || (Private = {}));


/***/ }),

/***/ "8EBN":
/*!**********************************************!*\
  !*** ./node_modules/codemirror/mode/meta.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../lib/codemirror */ "VrN/"));
  else {}
})(function(CodeMirror) {
  "use strict";

  CodeMirror.modeInfo = [
    {name: "APL", mime: "text/apl", mode: "apl", ext: ["dyalog", "apl"]},
    {name: "PGP", mimes: ["application/pgp", "application/pgp-encrypted", "application/pgp-keys", "application/pgp-signature"], mode: "asciiarmor", ext: ["asc", "pgp", "sig"]},
    {name: "ASN.1", mime: "text/x-ttcn-asn", mode: "asn.1", ext: ["asn", "asn1"]},
    {name: "Asterisk", mime: "text/x-asterisk", mode: "asterisk", file: /^extensions\.conf$/i},
    {name: "Brainfuck", mime: "text/x-brainfuck", mode: "brainfuck", ext: ["b", "bf"]},
    {name: "C", mime: "text/x-csrc", mode: "clike", ext: ["c", "h", "ino"]},
    {name: "C++", mime: "text/x-c++src", mode: "clike", ext: ["cpp", "c++", "cc", "cxx", "hpp", "h++", "hh", "hxx"], alias: ["cpp"]},
    {name: "Cobol", mime: "text/x-cobol", mode: "cobol", ext: ["cob", "cpy"]},
    {name: "C#", mime: "text/x-csharp", mode: "clike", ext: ["cs"], alias: ["csharp"]},
    {name: "Clojure", mime: "text/x-clojure", mode: "clojure", ext: ["clj", "cljc", "cljx"]},
    {name: "ClojureScript", mime: "text/x-clojurescript", mode: "clojure", ext: ["cljs"]},
    {name: "Closure Stylesheets (GSS)", mime: "text/x-gss", mode: "css", ext: ["gss"]},
    {name: "CMake", mime: "text/x-cmake", mode: "cmake", ext: ["cmake", "cmake.in"], file: /^CMakeLists.txt$/},
    {name: "CoffeeScript", mimes: ["application/vnd.coffeescript", "text/coffeescript", "text/x-coffeescript"], mode: "coffeescript", ext: ["coffee"], alias: ["coffee", "coffee-script"]},
    {name: "Common Lisp", mime: "text/x-common-lisp", mode: "commonlisp", ext: ["cl", "lisp", "el"], alias: ["lisp"]},
    {name: "Cypher", mime: "application/x-cypher-query", mode: "cypher", ext: ["cyp", "cypher"]},
    {name: "Cython", mime: "text/x-cython", mode: "python", ext: ["pyx", "pxd", "pxi"]},
    {name: "Crystal", mime: "text/x-crystal", mode: "crystal", ext: ["cr"]},
    {name: "CSS", mime: "text/css", mode: "css", ext: ["css"]},
    {name: "CQL", mime: "text/x-cassandra", mode: "sql", ext: ["cql"]},
    {name: "D", mime: "text/x-d", mode: "d", ext: ["d"]},
    {name: "Dart", mimes: ["application/dart", "text/x-dart"], mode: "dart", ext: ["dart"]},
    {name: "diff", mime: "text/x-diff", mode: "diff", ext: ["diff", "patch"]},
    {name: "Django", mime: "text/x-django", mode: "django"},
    {name: "Dockerfile", mime: "text/x-dockerfile", mode: "dockerfile", file: /^Dockerfile$/},
    {name: "DTD", mime: "application/xml-dtd", mode: "dtd", ext: ["dtd"]},
    {name: "Dylan", mime: "text/x-dylan", mode: "dylan", ext: ["dylan", "dyl", "intr"]},
    {name: "EBNF", mime: "text/x-ebnf", mode: "ebnf"},
    {name: "ECL", mime: "text/x-ecl", mode: "ecl", ext: ["ecl"]},
    {name: "edn", mime: "application/edn", mode: "clojure", ext: ["edn"]},
    {name: "Eiffel", mime: "text/x-eiffel", mode: "eiffel", ext: ["e"]},
    {name: "Elm", mime: "text/x-elm", mode: "elm", ext: ["elm"]},
    {name: "Embedded Javascript", mime: "application/x-ejs", mode: "htmlembedded", ext: ["ejs"]},
    {name: "Embedded Ruby", mime: "application/x-erb", mode: "htmlembedded", ext: ["erb"]},
    {name: "Erlang", mime: "text/x-erlang", mode: "erlang", ext: ["erl"]},
    {name: "Esper", mime: "text/x-esper", mode: "sql"},
    {name: "Factor", mime: "text/x-factor", mode: "factor", ext: ["factor"]},
    {name: "FCL", mime: "text/x-fcl", mode: "fcl"},
    {name: "Forth", mime: "text/x-forth", mode: "forth", ext: ["forth", "fth", "4th"]},
    {name: "Fortran", mime: "text/x-fortran", mode: "fortran", ext: ["f", "for", "f77", "f90"]},
    {name: "F#", mime: "text/x-fsharp", mode: "mllike", ext: ["fs"], alias: ["fsharp"]},
    {name: "Gas", mime: "text/x-gas", mode: "gas", ext: ["s"]},
    {name: "Gherkin", mime: "text/x-feature", mode: "gherkin", ext: ["feature"]},
    {name: "GitHub Flavored Markdown", mime: "text/x-gfm", mode: "gfm", file: /^(readme|contributing|history).md$/i},
    {name: "Go", mime: "text/x-go", mode: "go", ext: ["go"]},
    {name: "Groovy", mime: "text/x-groovy", mode: "groovy", ext: ["groovy", "gradle"], file: /^Jenkinsfile$/},
    {name: "HAML", mime: "text/x-haml", mode: "haml", ext: ["haml"]},
    {name: "Haskell", mime: "text/x-haskell", mode: "haskell", ext: ["hs"]},
    {name: "Haskell (Literate)", mime: "text/x-literate-haskell", mode: "haskell-literate", ext: ["lhs"]},
    {name: "Haxe", mime: "text/x-haxe", mode: "haxe", ext: ["hx"]},
    {name: "HXML", mime: "text/x-hxml", mode: "haxe", ext: ["hxml"]},
    {name: "ASP.NET", mime: "application/x-aspx", mode: "htmlembedded", ext: ["aspx"], alias: ["asp", "aspx"]},
    {name: "HTML", mime: "text/html", mode: "htmlmixed", ext: ["html", "htm", "handlebars", "hbs"], alias: ["xhtml"]},
    {name: "HTTP", mime: "message/http", mode: "http"},
    {name: "IDL", mime: "text/x-idl", mode: "idl", ext: ["pro"]},
    {name: "Pug", mime: "text/x-pug", mode: "pug", ext: ["jade", "pug"], alias: ["jade"]},
    {name: "Java", mime: "text/x-java", mode: "clike", ext: ["java"]},
    {name: "Java Server Pages", mime: "application/x-jsp", mode: "htmlembedded", ext: ["jsp"], alias: ["jsp"]},
    {name: "JavaScript", mimes: ["text/javascript", "text/ecmascript", "application/javascript", "application/x-javascript", "application/ecmascript"],
     mode: "javascript", ext: ["js"], alias: ["ecmascript", "js", "node"]},
    {name: "JSON", mimes: ["application/json", "application/x-json"], mode: "javascript", ext: ["json", "map"], alias: ["json5"]},
    {name: "JSON-LD", mime: "application/ld+json", mode: "javascript", ext: ["jsonld"], alias: ["jsonld"]},
    {name: "JSX", mime: "text/jsx", mode: "jsx", ext: ["jsx"]},
    {name: "Jinja2", mime: "null", mode: "jinja2"},
    {name: "Julia", mime: "text/x-julia", mode: "julia", ext: ["jl"]},
    {name: "Kotlin", mime: "text/x-kotlin", mode: "clike", ext: ["kt"]},
    {name: "LESS", mime: "text/x-less", mode: "css", ext: ["less"]},
    {name: "LiveScript", mime: "text/x-livescript", mode: "livescript", ext: ["ls"], alias: ["ls"]},
    {name: "Lua", mime: "text/x-lua", mode: "lua", ext: ["lua"]},
    {name: "Markdown", mime: "text/x-markdown", mode: "markdown", ext: ["markdown", "md", "mkd"]},
    {name: "mIRC", mime: "text/mirc", mode: "mirc"},
    {name: "MariaDB SQL", mime: "text/x-mariadb", mode: "sql"},
    {name: "Mathematica", mime: "text/x-mathematica", mode: "mathematica", ext: ["m", "nb"]},
    {name: "Modelica", mime: "text/x-modelica", mode: "modelica", ext: ["mo"]},
    {name: "MUMPS", mime: "text/x-mumps", mode: "mumps", ext: ["mps"]},
    {name: "MS SQL", mime: "text/x-mssql", mode: "sql"},
    {name: "mbox", mime: "application/mbox", mode: "mbox", ext: ["mbox"]},
    {name: "MySQL", mime: "text/x-mysql", mode: "sql"},
    {name: "Nginx", mime: "text/x-nginx-conf", mode: "nginx", file: /nginx.*\.conf$/i},
    {name: "NSIS", mime: "text/x-nsis", mode: "nsis", ext: ["nsh", "nsi"]},
    {name: "NTriples", mimes: ["application/n-triples", "application/n-quads", "text/n-triples"],
     mode: "ntriples", ext: ["nt", "nq"]},
    {name: "Objective-C", mime: "text/x-objectivec", mode: "clike", ext: ["m", "mm"], alias: ["objective-c", "objc"]},
    {name: "OCaml", mime: "text/x-ocaml", mode: "mllike", ext: ["ml", "mli", "mll", "mly"]},
    {name: "Octave", mime: "text/x-octave", mode: "octave", ext: ["m"]},
    {name: "Oz", mime: "text/x-oz", mode: "oz", ext: ["oz"]},
    {name: "Pascal", mime: "text/x-pascal", mode: "pascal", ext: ["p", "pas"]},
    {name: "PEG.js", mime: "null", mode: "pegjs", ext: ["jsonld"]},
    {name: "Perl", mime: "text/x-perl", mode: "perl", ext: ["pl", "pm"]},
    {name: "PHP", mimes: ["text/x-php", "application/x-httpd-php", "application/x-httpd-php-open"], mode: "php", ext: ["php", "php3", "php4", "php5", "php7", "phtml"]},
    {name: "Pig", mime: "text/x-pig", mode: "pig", ext: ["pig"]},
    {name: "Plain Text", mime: "text/plain", mode: "null", ext: ["txt", "text", "conf", "def", "list", "log"]},
    {name: "PLSQL", mime: "text/x-plsql", mode: "sql", ext: ["pls"]},
    {name: "PowerShell", mime: "application/x-powershell", mode: "powershell", ext: ["ps1", "psd1", "psm1"]},
    {name: "Properties files", mime: "text/x-properties", mode: "properties", ext: ["properties", "ini", "in"], alias: ["ini", "properties"]},
    {name: "ProtoBuf", mime: "text/x-protobuf", mode: "protobuf", ext: ["proto"]},
    {name: "Python", mime: "text/x-python", mode: "python", ext: ["BUILD", "bzl", "py", "pyw"], file: /^(BUCK|BUILD)$/},
    {name: "Puppet", mime: "text/x-puppet", mode: "puppet", ext: ["pp"]},
    {name: "Q", mime: "text/x-q", mode: "q", ext: ["q"]},
    {name: "R", mime: "text/x-rsrc", mode: "r", ext: ["r", "R"], alias: ["rscript"]},
    {name: "reStructuredText", mime: "text/x-rst", mode: "rst", ext: ["rst"], alias: ["rst"]},
    {name: "RPM Changes", mime: "text/x-rpm-changes", mode: "rpm"},
    {name: "RPM Spec", mime: "text/x-rpm-spec", mode: "rpm", ext: ["spec"]},
    {name: "Ruby", mime: "text/x-ruby", mode: "ruby", ext: ["rb"], alias: ["jruby", "macruby", "rake", "rb", "rbx"]},
    {name: "Rust", mime: "text/x-rustsrc", mode: "rust", ext: ["rs"]},
    {name: "SAS", mime: "text/x-sas", mode: "sas", ext: ["sas"]},
    {name: "Sass", mime: "text/x-sass", mode: "sass", ext: ["sass"]},
    {name: "Scala", mime: "text/x-scala", mode: "clike", ext: ["scala"]},
    {name: "Scheme", mime: "text/x-scheme", mode: "scheme", ext: ["scm", "ss"]},
    {name: "SCSS", mime: "text/x-scss", mode: "css", ext: ["scss"]},
    {name: "Shell", mimes: ["text/x-sh", "application/x-sh"], mode: "shell", ext: ["sh", "ksh", "bash"], alias: ["bash", "sh", "zsh"], file: /^PKGBUILD$/},
    {name: "Sieve", mime: "application/sieve", mode: "sieve", ext: ["siv", "sieve"]},
    {name: "Slim", mimes: ["text/x-slim", "application/x-slim"], mode: "slim", ext: ["slim"]},
    {name: "Smalltalk", mime: "text/x-stsrc", mode: "smalltalk", ext: ["st"]},
    {name: "Smarty", mime: "text/x-smarty", mode: "smarty", ext: ["tpl"]},
    {name: "Solr", mime: "text/x-solr", mode: "solr"},
    {name: "SML", mime: "text/x-sml", mode: "mllike", ext: ["sml", "sig", "fun", "smackspec"]},
    {name: "Soy", mime: "text/x-soy", mode: "soy", ext: ["soy"], alias: ["closure template"]},
    {name: "SPARQL", mime: "application/sparql-query", mode: "sparql", ext: ["rq", "sparql"], alias: ["sparul"]},
    {name: "Spreadsheet", mime: "text/x-spreadsheet", mode: "spreadsheet", alias: ["excel", "formula"]},
    {name: "SQL", mime: "text/x-sql", mode: "sql", ext: ["sql"]},
    {name: "SQLite", mime: "text/x-sqlite", mode: "sql"},
    {name: "Squirrel", mime: "text/x-squirrel", mode: "clike", ext: ["nut"]},
    {name: "Stylus", mime: "text/x-styl", mode: "stylus", ext: ["styl"]},
    {name: "Swift", mime: "text/x-swift", mode: "swift", ext: ["swift"]},
    {name: "sTeX", mime: "text/x-stex", mode: "stex"},
    {name: "LaTeX", mime: "text/x-latex", mode: "stex", ext: ["text", "ltx", "tex"], alias: ["tex"]},
    {name: "SystemVerilog", mime: "text/x-systemverilog", mode: "verilog", ext: ["v", "sv", "svh"]},
    {name: "Tcl", mime: "text/x-tcl", mode: "tcl", ext: ["tcl"]},
    {name: "Textile", mime: "text/x-textile", mode: "textile", ext: ["textile"]},
    {name: "TiddlyWiki ", mime: "text/x-tiddlywiki", mode: "tiddlywiki"},
    {name: "Tiki wiki", mime: "text/tiki", mode: "tiki"},
    {name: "TOML", mime: "text/x-toml", mode: "toml", ext: ["toml"]},
    {name: "Tornado", mime: "text/x-tornado", mode: "tornado"},
    {name: "troff", mime: "text/troff", mode: "troff", ext: ["1", "2", "3", "4", "5", "6", "7", "8", "9"]},
    {name: "TTCN", mime: "text/x-ttcn", mode: "ttcn", ext: ["ttcn", "ttcn3", "ttcnpp"]},
    {name: "TTCN_CFG", mime: "text/x-ttcn-cfg", mode: "ttcn-cfg", ext: ["cfg"]},
    {name: "Turtle", mime: "text/turtle", mode: "turtle", ext: ["ttl"]},
    {name: "TypeScript", mime: "application/typescript", mode: "javascript", ext: ["ts"], alias: ["ts"]},
    {name: "TypeScript-JSX", mime: "text/typescript-jsx", mode: "jsx", ext: ["tsx"], alias: ["tsx"]},
    {name: "Twig", mime: "text/x-twig", mode: "twig"},
    {name: "Web IDL", mime: "text/x-webidl", mode: "webidl", ext: ["webidl"]},
    {name: "VB.NET", mime: "text/x-vb", mode: "vb", ext: ["vb"]},
    {name: "VBScript", mime: "text/vbscript", mode: "vbscript", ext: ["vbs"]},
    {name: "Velocity", mime: "text/velocity", mode: "velocity", ext: ["vtl"]},
    {name: "Verilog", mime: "text/x-verilog", mode: "verilog", ext: ["v"]},
    {name: "VHDL", mime: "text/x-vhdl", mode: "vhdl", ext: ["vhd", "vhdl"]},
    {name: "Vue.js Component", mimes: ["script/x-vue", "text/x-vue"], mode: "vue", ext: ["vue"]},
    {name: "XML", mimes: ["application/xml", "text/xml"], mode: "xml", ext: ["xml", "xsl", "xsd", "svg"], alias: ["rss", "wsdl", "xsd"]},
    {name: "XQuery", mime: "application/xquery", mode: "xquery", ext: ["xy", "xquery"]},
    {name: "Yacas", mime: "text/x-yacas", mode: "yacas", ext: ["ys"]},
    {name: "YAML", mimes: ["text/x-yaml", "text/yaml"], mode: "yaml", ext: ["yaml", "yml"], alias: ["yml"]},
    {name: "Z80", mime: "text/x-z80", mode: "z80", ext: ["z80"]},
    {name: "mscgen", mime: "text/x-mscgen", mode: "mscgen", ext: ["mscgen", "mscin", "msc"]},
    {name: "xu", mime: "text/x-xu", mode: "mscgen", ext: ["xu"]},
    {name: "msgenny", mime: "text/x-msgenny", mode: "mscgen", ext: ["msgenny"]}
  ];
  // Ensure all modes have a mime property for backwards compatibility
  for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
    var info = CodeMirror.modeInfo[i];
    if (info.mimes) info.mime = info.mimes[0];
  }

  CodeMirror.findModeByMIME = function(mime) {
    mime = mime.toLowerCase();
    for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
      var info = CodeMirror.modeInfo[i];
      if (info.mime == mime) return info;
      if (info.mimes) for (var j = 0; j < info.mimes.length; j++)
        if (info.mimes[j] == mime) return info;
    }
    if (/\+xml$/.test(mime)) return CodeMirror.findModeByMIME("application/xml")
    if (/\+json$/.test(mime)) return CodeMirror.findModeByMIME("application/json")
  };

  CodeMirror.findModeByExtension = function(ext) {
    for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
      var info = CodeMirror.modeInfo[i];
      if (info.ext) for (var j = 0; j < info.ext.length; j++)
        if (info.ext[j] == ext) return info;
    }
  };

  CodeMirror.findModeByFileName = function(filename) {
    for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
      var info = CodeMirror.modeInfo[i];
      if (info.file && info.file.test(filename)) return info;
    }
    var dot = filename.lastIndexOf(".");
    var ext = dot > -1 && filename.substring(dot + 1, filename.length);
    if (ext) return CodeMirror.findModeByExtension(ext);
  };

  CodeMirror.findModeByName = function(name) {
    name = name.toLowerCase();
    for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
      var info = CodeMirror.modeInfo[i];
      if (info.name.toLowerCase() == name) return info;
      if (info.alias) for (var j = 0; j < info.alias.length; j++)
        if (info.alias[j].toLowerCase() == name) return info;
    }
  };
});


/***/ }),

/***/ "8F98":
/*!*******************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotDonutIcon.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotDonutIcon = function PlotDonutIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M26 5.625l-3.875 4.5A8.43 8.43 0 0 1 24.5 16a8.93 8.93 0 0 1-.188 1.813L30 19.501c.25-1.125.375-2.313.375-3.5A14.49 14.49 0 0 0 26 5.626zM12 8.5a8.622 8.622 0 0 1 4-1c1.75 0 3.313.5 4.688 1.438l3.813-4.563c-2.375-1.75-5.313-2.75-8.5-2.75-2.625 0-5.063.688-7.188 1.875zm11.625 11.125c-1.25 2.625-3.813 4.563-7 4.813v5.938a14.51 14.51 0 0 0 12.688-9.063zm-8.875 4.813c-4.188-.563-7.313-4.125-7.313-8.438 0-2.563 1.188-4.875 2.938-6.438l-3.188-5C3.749 7.25 1.499 11.375 1.499 16c0 7.563 5.875 13.75 13.25 14.375z' })
    );
};

exports.default = PlotDonutIcon;

/***/ }),

/***/ "8Fln":
/*!***********************************************************!*\
  !*** ./node_modules/react-select/dist/react-select.es.js ***!
  \***********************************************************/
/*! exports provided: Async, AsyncCreatable, Creatable, Value, Option, defaultMenuRenderer, defaultArrowRenderer, defaultClearRenderer, defaultFilterOptions, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Async", function() { return Async; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AsyncCreatable", function() { return AsyncCreatableSelect; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Creatable", function() { return CreatableSelect; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Value", function() { return Value; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Option", function() { return Option; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultMenuRenderer", function() { return menuRenderer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultArrowRenderer", function() { return arrowRenderer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultClearRenderer", function() { return clearRenderer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultFilterOptions", function() { return filterOptions; });
/* harmony import */ var react_input_autosize__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react-input-autosize */ "FUBA");
/* harmony import */ var react_input_autosize__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react_input_autosize__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! classnames */ "TSYQ");
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(classnames__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! prop-types */ "17x9");
/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(prop_types__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! react */ "q1tI");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! react-dom */ "i8i4");
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_4__);






var arrowRenderer = function arrowRenderer(_ref) {
	var onMouseDown = _ref.onMouseDown;

	return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement('span', {
		className: 'Select-arrow',
		onMouseDown: onMouseDown
	});
};

arrowRenderer.propTypes = {
	onMouseDown: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func
};

var clearRenderer = function clearRenderer() {
	return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement('span', {
		className: 'Select-clear',
		dangerouslySetInnerHTML: { __html: '&times;' }
	});
};

var map = [{ 'base': 'A', 'letters': /[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g }, { 'base': 'AA', 'letters': /[\uA732]/g }, { 'base': 'AE', 'letters': /[\u00C6\u01FC\u01E2]/g }, { 'base': 'AO', 'letters': /[\uA734]/g }, { 'base': 'AU', 'letters': /[\uA736]/g }, { 'base': 'AV', 'letters': /[\uA738\uA73A]/g }, { 'base': 'AY', 'letters': /[\uA73C]/g }, { 'base': 'B', 'letters': /[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g }, { 'base': 'C', 'letters': /[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g }, { 'base': 'D', 'letters': /[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g }, { 'base': 'DZ', 'letters': /[\u01F1\u01C4]/g }, { 'base': 'Dz', 'letters': /[\u01F2\u01C5]/g }, { 'base': 'E', 'letters': /[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g }, { 'base': 'F', 'letters': /[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g }, { 'base': 'G', 'letters': /[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g }, { 'base': 'H', 'letters': /[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g }, { 'base': 'I', 'letters': /[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g }, { 'base': 'J', 'letters': /[\u004A\u24BF\uFF2A\u0134\u0248]/g }, { 'base': 'K', 'letters': /[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g }, { 'base': 'L', 'letters': /[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g }, { 'base': 'LJ', 'letters': /[\u01C7]/g }, { 'base': 'Lj', 'letters': /[\u01C8]/g }, { 'base': 'M', 'letters': /[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g }, { 'base': 'N', 'letters': /[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g }, { 'base': 'NJ', 'letters': /[\u01CA]/g }, { 'base': 'Nj', 'letters': /[\u01CB]/g }, { 'base': 'O', 'letters': /[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g }, { 'base': 'OI', 'letters': /[\u01A2]/g }, { 'base': 'OO', 'letters': /[\uA74E]/g }, { 'base': 'OU', 'letters': /[\u0222]/g }, { 'base': 'P', 'letters': /[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g }, { 'base': 'Q', 'letters': /[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g }, { 'base': 'R', 'letters': /[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g }, { 'base': 'S', 'letters': /[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g }, { 'base': 'T', 'letters': /[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g }, { 'base': 'TZ', 'letters': /[\uA728]/g }, { 'base': 'U', 'letters': /[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g }, { 'base': 'V', 'letters': /[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g }, { 'base': 'VY', 'letters': /[\uA760]/g }, { 'base': 'W', 'letters': /[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g }, { 'base': 'X', 'letters': /[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g }, { 'base': 'Y', 'letters': /[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g }, { 'base': 'Z', 'letters': /[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g }, { 'base': 'a', 'letters': /[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g }, { 'base': 'aa', 'letters': /[\uA733]/g }, { 'base': 'ae', 'letters': /[\u00E6\u01FD\u01E3]/g }, { 'base': 'ao', 'letters': /[\uA735]/g }, { 'base': 'au', 'letters': /[\uA737]/g }, { 'base': 'av', 'letters': /[\uA739\uA73B]/g }, { 'base': 'ay', 'letters': /[\uA73D]/g }, { 'base': 'b', 'letters': /[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g }, { 'base': 'c', 'letters': /[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g }, { 'base': 'd', 'letters': /[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g }, { 'base': 'dz', 'letters': /[\u01F3\u01C6]/g }, { 'base': 'e', 'letters': /[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g }, { 'base': 'f', 'letters': /[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g }, { 'base': 'g', 'letters': /[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g }, { 'base': 'h', 'letters': /[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g }, { 'base': 'hv', 'letters': /[\u0195]/g }, { 'base': 'i', 'letters': /[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g }, { 'base': 'j', 'letters': /[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g }, { 'base': 'k', 'letters': /[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g }, { 'base': 'l', 'letters': /[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g }, { 'base': 'lj', 'letters': /[\u01C9]/g }, { 'base': 'm', 'letters': /[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g }, { 'base': 'n', 'letters': /[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g }, { 'base': 'nj', 'letters': /[\u01CC]/g }, { 'base': 'o', 'letters': /[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g }, { 'base': 'oi', 'letters': /[\u01A3]/g }, { 'base': 'ou', 'letters': /[\u0223]/g }, { 'base': 'oo', 'letters': /[\uA74F]/g }, { 'base': 'p', 'letters': /[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g }, { 'base': 'q', 'letters': /[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g }, { 'base': 'r', 'letters': /[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g }, { 'base': 's', 'letters': /[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g }, { 'base': 't', 'letters': /[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g }, { 'base': 'tz', 'letters': /[\uA729]/g }, { 'base': 'u', 'letters': /[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g }, { 'base': 'v', 'letters': /[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g }, { 'base': 'vy', 'letters': /[\uA761]/g }, { 'base': 'w', 'letters': /[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g }, { 'base': 'x', 'letters': /[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g }, { 'base': 'y', 'letters': /[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g }, { 'base': 'z', 'letters': /[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g }];

var stripDiacritics = function stripDiacritics(str) {
	for (var i = 0; i < map.length; i++) {
		str = str.replace(map[i].letters, map[i].base);
	}
	return str;
};

var trim = function trim(str) {
  return str.replace(/^\s+|\s+$/g, '');
};

var isValid = function isValid(value) {
	return typeof value !== 'undefined' && value !== null && value !== '';
};

var filterOptions = function filterOptions(options, filterValue, excludeOptions, props) {
	if (props.ignoreAccents) {
		filterValue = stripDiacritics(filterValue);
	}

	if (props.ignoreCase) {
		filterValue = filterValue.toLowerCase();
	}

	if (props.trimFilter) {
		filterValue = trim(filterValue);
	}

	if (excludeOptions) excludeOptions = excludeOptions.map(function (i) {
		return i[props.valueKey];
	});

	return options.filter(function (option) {
		if (excludeOptions && excludeOptions.indexOf(option[props.valueKey]) > -1) return false;
		if (props.filterOption) return props.filterOption.call(undefined, option, filterValue);
		if (!filterValue) return true;

		var value = option[props.valueKey];
		var label = option[props.labelKey];
		var hasValue = isValid(value);
		var hasLabel = isValid(label);

		if (!hasValue && !hasLabel) {
			return false;
		}

		var valueTest = hasValue ? String(value) : null;
		var labelTest = hasLabel ? String(label) : null;

		if (props.ignoreAccents) {
			if (valueTest && props.matchProp !== 'label') valueTest = stripDiacritics(valueTest);
			if (labelTest && props.matchProp !== 'value') labelTest = stripDiacritics(labelTest);
		}

		if (props.ignoreCase) {
			if (valueTest && props.matchProp !== 'label') valueTest = valueTest.toLowerCase();
			if (labelTest && props.matchProp !== 'value') labelTest = labelTest.toLowerCase();
		}

		return props.matchPos === 'start' ? valueTest && props.matchProp !== 'label' && valueTest.substr(0, filterValue.length) === filterValue || labelTest && props.matchProp !== 'value' && labelTest.substr(0, filterValue.length) === filterValue : valueTest && props.matchProp !== 'label' && valueTest.indexOf(filterValue) >= 0 || labelTest && props.matchProp !== 'value' && labelTest.indexOf(filterValue) >= 0;
	});
};

var menuRenderer = function menuRenderer(_ref) {
	var focusedOption = _ref.focusedOption,
	    focusOption = _ref.focusOption,
	    inputValue = _ref.inputValue,
	    instancePrefix = _ref.instancePrefix,
	    onFocus = _ref.onFocus,
	    onOptionRef = _ref.onOptionRef,
	    onSelect = _ref.onSelect,
	    optionClassName = _ref.optionClassName,
	    optionComponent = _ref.optionComponent,
	    optionRenderer = _ref.optionRenderer,
	    options = _ref.options,
	    removeValue = _ref.removeValue,
	    selectValue = _ref.selectValue,
	    valueArray = _ref.valueArray,
	    valueKey = _ref.valueKey;

	var Option = optionComponent;

	return options.map(function (option, i) {
		var isSelected = valueArray && valueArray.some(function (x) {
			return x[valueKey] === option[valueKey];
		});
		var isFocused = option === focusedOption;
		var optionClass = classnames__WEBPACK_IMPORTED_MODULE_1___default()(optionClassName, {
			'Select-option': true,
			'is-selected': isSelected,
			'is-focused': isFocused,
			'is-disabled': option.disabled
		});

		return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
			Option,
			{
				className: optionClass,
				focusOption: focusOption,
				inputValue: inputValue,
				instancePrefix: instancePrefix,
				isDisabled: option.disabled,
				isFocused: isFocused,
				isSelected: isSelected,
				key: 'option-' + i + '-' + option[valueKey],
				onFocus: onFocus,
				onSelect: onSelect,
				option: option,
				optionIndex: i,
				ref: function ref(_ref2) {
					onOptionRef(_ref2, isFocused);
				},
				removeValue: removeValue,
				selectValue: selectValue
			},
			optionRenderer(option, i, inputValue)
		);
	});
};

menuRenderer.propTypes = {
	focusOption: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func,
	focusedOption: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object,
	inputValue: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string,
	instancePrefix: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string,
	onFocus: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func,
	onOptionRef: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func,
	onSelect: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func,
	optionClassName: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string,
	optionComponent: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func,
	optionRenderer: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func,
	options: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.array,
	removeValue: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func,
	selectValue: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func,
	valueArray: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.array,
	valueKey: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string
};

var blockEvent = (function (event) {
	event.preventDefault();
	event.stopPropagation();
	if (event.target.tagName !== 'A' || !('href' in event.target)) {
		return;
	}
	if (event.target.target) {
		window.open(event.target.href, event.target.target);
	} else {
		window.location.href = event.target.href;
	}
});

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  return typeof obj;
} : function (obj) {
  return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};





var asyncGenerator = function () {
  function AwaitValue(value) {
    this.value = value;
  }

  function AsyncGenerator(gen) {
    var front, back;

    function send(key, arg) {
      return new Promise(function (resolve, reject) {
        var request = {
          key: key,
          arg: arg,
          resolve: resolve,
          reject: reject,
          next: null
        };

        if (back) {
          back = back.next = request;
        } else {
          front = back = request;
          resume(key, arg);
        }
      });
    }

    function resume(key, arg) {
      try {
        var result = gen[key](arg);
        var value = result.value;

        if (value instanceof AwaitValue) {
          Promise.resolve(value.value).then(function (arg) {
            resume("next", arg);
          }, function (arg) {
            resume("throw", arg);
          });
        } else {
          settle(result.done ? "return" : "normal", result.value);
        }
      } catch (err) {
        settle("throw", err);
      }
    }

    function settle(type, value) {
      switch (type) {
        case "return":
          front.resolve({
            value: value,
            done: true
          });
          break;

        case "throw":
          front.reject(value);
          break;

        default:
          front.resolve({
            value: value,
            done: false
          });
          break;
      }

      front = front.next;

      if (front) {
        resume(front.key, front.arg);
      } else {
        back = null;
      }
    }

    this._invoke = send;

    if (typeof gen.return !== "function") {
      this.return = undefined;
    }
  }

  if (typeof Symbol === "function" && Symbol.asyncIterator) {
    AsyncGenerator.prototype[Symbol.asyncIterator] = function () {
      return this;
    };
  }

  AsyncGenerator.prototype.next = function (arg) {
    return this._invoke("next", arg);
  };

  AsyncGenerator.prototype.throw = function (arg) {
    return this._invoke("throw", arg);
  };

  AsyncGenerator.prototype.return = function (arg) {
    return this._invoke("return", arg);
  };

  return {
    wrap: function (fn) {
      return function () {
        return new AsyncGenerator(fn.apply(this, arguments));
      };
    },
    await: function (value) {
      return new AwaitValue(value);
    }
  };
}();





var classCallCheck = function (instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
};

var createClass = function () {
  function defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor) descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }

  return function (Constructor, protoProps, staticProps) {
    if (protoProps) defineProperties(Constructor.prototype, protoProps);
    if (staticProps) defineProperties(Constructor, staticProps);
    return Constructor;
  };
}();





var defineProperty = function (obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
};

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};



var inherits = function (subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  }

  subClass.prototype = Object.create(superClass && superClass.prototype, {
    constructor: {
      value: subClass,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
  if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};









var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var possibleConstructorReturn = function (self, call) {
  if (!self) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }

  return call && (typeof call === "object" || typeof call === "function") ? call : self;
};

var Option = function (_React$Component) {
	inherits(Option, _React$Component);

	function Option(props) {
		classCallCheck(this, Option);

		var _this = possibleConstructorReturn(this, (Option.__proto__ || Object.getPrototypeOf(Option)).call(this, props));

		_this.handleMouseDown = _this.handleMouseDown.bind(_this);
		_this.handleMouseEnter = _this.handleMouseEnter.bind(_this);
		_this.handleMouseMove = _this.handleMouseMove.bind(_this);
		_this.handleTouchStart = _this.handleTouchStart.bind(_this);
		_this.handleTouchEnd = _this.handleTouchEnd.bind(_this);
		_this.handleTouchMove = _this.handleTouchMove.bind(_this);
		_this.onFocus = _this.onFocus.bind(_this);
		return _this;
	}

	createClass(Option, [{
		key: 'handleMouseDown',
		value: function handleMouseDown(event) {
			event.preventDefault();
			event.stopPropagation();
			this.props.onSelect(this.props.option, event);
		}
	}, {
		key: 'handleMouseEnter',
		value: function handleMouseEnter(event) {
			this.onFocus(event);
		}
	}, {
		key: 'handleMouseMove',
		value: function handleMouseMove(event) {
			this.onFocus(event);
		}
	}, {
		key: 'handleTouchEnd',
		value: function handleTouchEnd(event) {
			// Check if the view is being dragged, In this case
			// we don't want to fire the click event (because the user only wants to scroll)
			if (this.dragging) return;

			this.handleMouseDown(event);
		}
	}, {
		key: 'handleTouchMove',
		value: function handleTouchMove() {
			// Set a flag that the view is being dragged
			this.dragging = true;
		}
	}, {
		key: 'handleTouchStart',
		value: function handleTouchStart() {
			// Set a flag that the view is not being dragged
			this.dragging = false;
		}
	}, {
		key: 'onFocus',
		value: function onFocus(event) {
			if (!this.props.isFocused) {
				this.props.onFocus(this.props.option, event);
			}
		}
	}, {
		key: 'render',
		value: function render() {
			var _props = this.props,
			    option = _props.option,
			    instancePrefix = _props.instancePrefix,
			    optionIndex = _props.optionIndex;

			var className = classnames__WEBPACK_IMPORTED_MODULE_1___default()(this.props.className, option.className);

			return option.disabled ? react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
				'div',
				{ className: className,
					onMouseDown: blockEvent,
					onClick: blockEvent },
				this.props.children
			) : react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
				'div',
				{ className: className,
					style: option.style,
					role: 'option',
					'aria-label': option.label,
					onMouseDown: this.handleMouseDown,
					onMouseEnter: this.handleMouseEnter,
					onMouseMove: this.handleMouseMove,
					onTouchStart: this.handleTouchStart,
					onTouchMove: this.handleTouchMove,
					onTouchEnd: this.handleTouchEnd,
					id: instancePrefix + '-option-' + optionIndex,
					title: option.title },
				this.props.children
			);
		}
	}]);
	return Option;
}(react__WEBPACK_IMPORTED_MODULE_3___default.a.Component);

Option.propTypes = {
	children: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.node,
	className: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, // className (based on mouse position)
	instancePrefix: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string.isRequired, // unique prefix for the ids (used for aria)
	isDisabled: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // the option is disabled
	isFocused: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // the option is focused
	isSelected: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // the option is selected
	onFocus: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // method to handle mouseEnter on option element
	onSelect: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // method to handle click on option element
	onUnfocus: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // method to handle mouseLeave on option element
	option: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object.isRequired, // object that is base for that option
	optionIndex: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.number // index of the option, used to generate unique ids for aria
};

var Value = function (_React$Component) {
	inherits(Value, _React$Component);

	function Value(props) {
		classCallCheck(this, Value);

		var _this = possibleConstructorReturn(this, (Value.__proto__ || Object.getPrototypeOf(Value)).call(this, props));

		_this.handleMouseDown = _this.handleMouseDown.bind(_this);
		_this.onRemove = _this.onRemove.bind(_this);
		_this.handleTouchEndRemove = _this.handleTouchEndRemove.bind(_this);
		_this.handleTouchMove = _this.handleTouchMove.bind(_this);
		_this.handleTouchStart = _this.handleTouchStart.bind(_this);
		return _this;
	}

	createClass(Value, [{
		key: 'handleMouseDown',
		value: function handleMouseDown(event) {
			if (event.type === 'mousedown' && event.button !== 0) {
				return;
			}
			if (this.props.onClick) {
				event.stopPropagation();
				this.props.onClick(this.props.value, event);
				return;
			}
			if (this.props.value.href) {
				event.stopPropagation();
			}
		}
	}, {
		key: 'onRemove',
		value: function onRemove(event) {
			event.preventDefault();
			event.stopPropagation();
			this.props.onRemove(this.props.value);
		}
	}, {
		key: 'handleTouchEndRemove',
		value: function handleTouchEndRemove(event) {
			// Check if the view is being dragged, In this case
			// we don't want to fire the click event (because the user only wants to scroll)
			if (this.dragging) return;

			// Fire the mouse events
			this.onRemove(event);
		}
	}, {
		key: 'handleTouchMove',
		value: function handleTouchMove() {
			// Set a flag that the view is being dragged
			this.dragging = true;
		}
	}, {
		key: 'handleTouchStart',
		value: function handleTouchStart() {
			// Set a flag that the view is not being dragged
			this.dragging = false;
		}
	}, {
		key: 'renderRemoveIcon',
		value: function renderRemoveIcon() {
			if (this.props.disabled || !this.props.onRemove) return;
			return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
				'span',
				{ className: 'Select-value-icon',
					'aria-hidden': 'true',
					onMouseDown: this.onRemove,
					onTouchEnd: this.handleTouchEndRemove,
					onTouchStart: this.handleTouchStart,
					onTouchMove: this.handleTouchMove },
				'\xD7'
			);
		}
	}, {
		key: 'renderLabel',
		value: function renderLabel() {
			var className = 'Select-value-label';
			return this.props.onClick || this.props.value.href ? react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
				'a',
				{ className: className, href: this.props.value.href, target: this.props.value.target, onMouseDown: this.handleMouseDown, onTouchEnd: this.handleMouseDown },
				this.props.children
			) : react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
				'span',
				{ className: className, role: 'option', 'aria-selected': 'true', id: this.props.id },
				this.props.children
			);
		}
	}, {
		key: 'render',
		value: function render() {
			return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
				'div',
				{ className: classnames__WEBPACK_IMPORTED_MODULE_1___default()('Select-value', this.props.value.disabled ? 'Select-value-disabled' : '', this.props.value.className),
					style: this.props.value.style,
					title: this.props.value.title
				},
				this.renderRemoveIcon(),
				this.renderLabel()
			);
		}
	}]);
	return Value;
}(react__WEBPACK_IMPORTED_MODULE_3___default.a.Component);

Value.propTypes = {
	children: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.node,
	disabled: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // disabled prop passed to ReactSelect
	id: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, // Unique id for the value - used for aria
	onClick: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // method to handle click on value label
	onRemove: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // method to handle removal of the value
	value: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object.isRequired // the option object for this value
};

/*!
  Copyright (c) 2018 Jed Watson.
  Licensed under the MIT License (MIT), see
  http://jedwatson.github.io/react-select
*/
var stringifyValue = function stringifyValue(value) {
	return typeof value === 'string' ? value : value !== null && JSON.stringify(value) || '';
};

var stringOrNode = prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.node]);
var stringOrNumber = prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.number]);

var instanceId = 1;

var shouldShowValue = function shouldShowValue(state, props) {
	var inputValue = state.inputValue,
	    isPseudoFocused = state.isPseudoFocused,
	    isFocused = state.isFocused;
	var onSelectResetsInput = props.onSelectResetsInput;


	if (!inputValue) return true;

	if (!onSelectResetsInput) {
		return !(!isFocused && isPseudoFocused || isFocused && !isPseudoFocused);
	}

	return false;
};

var shouldShowPlaceholder = function shouldShowPlaceholder(state, props, isOpen) {
	var inputValue = state.inputValue,
	    isPseudoFocused = state.isPseudoFocused,
	    isFocused = state.isFocused;
	var onSelectResetsInput = props.onSelectResetsInput;


	return !inputValue || !onSelectResetsInput && !isOpen && !isPseudoFocused && !isFocused;
};

/**
 * Retrieve a value from the given options and valueKey
 * @param {String|Number|Array} value	- the selected value(s)
 * @param {Object}		 props	- the Select component's props (or nextProps)
 */
var expandValue = function expandValue(value, props) {
	var valueType = typeof value === 'undefined' ? 'undefined' : _typeof(value);
	if (valueType !== 'string' && valueType !== 'number' && valueType !== 'boolean') return value;
	var options = props.options,
	    valueKey = props.valueKey;

	if (!options) return;
	for (var i = 0; i < options.length; i++) {
		if (String(options[i][valueKey]) === String(value)) return options[i];
	}
};

var handleRequired = function handleRequired(value, multi) {
	if (!value) return true;
	return multi ? value.length === 0 : Object.keys(value).length === 0;
};

var Select$1 = function (_React$Component) {
	inherits(Select, _React$Component);

	function Select(props) {
		classCallCheck(this, Select);

		var _this = possibleConstructorReturn(this, (Select.__proto__ || Object.getPrototypeOf(Select)).call(this, props));

		['clearValue', 'focusOption', 'getOptionLabel', 'handleInputBlur', 'handleInputChange', 'handleInputFocus', 'handleInputValueChange', 'handleKeyDown', 'handleMenuScroll', 'handleMouseDown', 'handleMouseDownOnArrow', 'handleMouseDownOnMenu', 'handleTouchEnd', 'handleTouchEndClearValue', 'handleTouchMove', 'handleTouchOutside', 'handleTouchStart', 'handleValueClick', 'onOptionRef', 'removeValue', 'selectValue'].forEach(function (fn) {
			return _this[fn] = _this[fn].bind(_this);
		});

		_this.state = {
			inputValue: '',
			isFocused: false,
			isOpen: false,
			isPseudoFocused: false,
			required: false
		};
		return _this;
	}

	createClass(Select, [{
		key: 'componentWillMount',
		value: function componentWillMount() {
			this._instancePrefix = 'react-select-' + (this.props.instanceId || ++instanceId) + '-';
			var valueArray = this.getValueArray(this.props.value);

			if (this.props.required) {
				this.setState({
					required: handleRequired(valueArray[0], this.props.multi)
				});
			}
		}
	}, {
		key: 'componentDidMount',
		value: function componentDidMount() {
			if (typeof this.props.autofocus !== 'undefined' && typeof console !== 'undefined') {
				console.warn('Warning: The autofocus prop has changed to autoFocus, support will be removed after react-select@1.0');
			}
			if (this.props.autoFocus || this.props.autofocus) {
				this.focus();
			}
		}
	}, {
		key: 'componentWillReceiveProps',
		value: function componentWillReceiveProps(nextProps) {
			var valueArray = this.getValueArray(nextProps.value, nextProps);

			if (nextProps.required) {
				this.setState({
					required: handleRequired(valueArray[0], nextProps.multi)
				});
			} else if (this.props.required) {
				// Used to be required but it's not any more
				this.setState({ required: false });
			}

			if (this.state.inputValue && this.props.value !== nextProps.value && nextProps.onSelectResetsInput) {
				this.setState({ inputValue: this.handleInputValueChange('') });
			}
		}
	}, {
		key: 'componentDidUpdate',
		value: function componentDidUpdate(prevProps, prevState) {
			// focus to the selected option
			if (this.menu && this.focused && this.state.isOpen && !this.hasScrolledToOption) {
				var focusedOptionNode = Object(react_dom__WEBPACK_IMPORTED_MODULE_4__["findDOMNode"])(this.focused);
				var menuNode = Object(react_dom__WEBPACK_IMPORTED_MODULE_4__["findDOMNode"])(this.menu);

				var scrollTop = menuNode.scrollTop;
				var scrollBottom = scrollTop + menuNode.offsetHeight;
				var optionTop = focusedOptionNode.offsetTop;
				var optionBottom = optionTop + focusedOptionNode.offsetHeight;

				if (scrollTop > optionTop || scrollBottom < optionBottom) {
					menuNode.scrollTop = focusedOptionNode.offsetTop;
				}

				// We still set hasScrolledToOption to true even if we didn't
				// actually need to scroll, as we've still confirmed that the
				// option is in view.
				this.hasScrolledToOption = true;
			} else if (!this.state.isOpen) {
				this.hasScrolledToOption = false;
			}

			if (this._scrollToFocusedOptionOnUpdate && this.focused && this.menu) {
				this._scrollToFocusedOptionOnUpdate = false;
				var focusedDOM = Object(react_dom__WEBPACK_IMPORTED_MODULE_4__["findDOMNode"])(this.focused);
				var menuDOM = Object(react_dom__WEBPACK_IMPORTED_MODULE_4__["findDOMNode"])(this.menu);
				var focusedRect = focusedDOM.getBoundingClientRect();
				var menuRect = menuDOM.getBoundingClientRect();
				if (focusedRect.bottom > menuRect.bottom) {
					menuDOM.scrollTop = focusedDOM.offsetTop + focusedDOM.clientHeight - menuDOM.offsetHeight;
				} else if (focusedRect.top < menuRect.top) {
					menuDOM.scrollTop = focusedDOM.offsetTop;
				}
			}
			if (this.props.scrollMenuIntoView && this.menuContainer) {
				var menuContainerRect = this.menuContainer.getBoundingClientRect();
				if (window.innerHeight < menuContainerRect.bottom + this.props.menuBuffer) {
					window.scrollBy(0, menuContainerRect.bottom + this.props.menuBuffer - window.innerHeight);
				}
			}
			if (prevProps.disabled !== this.props.disabled) {
				this.setState({ isFocused: false }); // eslint-disable-line react/no-did-update-set-state
				this.closeMenu();
			}
			if (prevState.isOpen !== this.state.isOpen) {
				this.toggleTouchOutsideEvent(this.state.isOpen);
				var handler = this.state.isOpen ? this.props.onOpen : this.props.onClose;
				handler && handler();
			}
		}
	}, {
		key: 'componentWillUnmount',
		value: function componentWillUnmount() {
			this.toggleTouchOutsideEvent(false);
		}
	}, {
		key: 'toggleTouchOutsideEvent',
		value: function toggleTouchOutsideEvent(enabled) {
			var eventTogglerName = enabled ? document.addEventListener ? 'addEventListener' : 'attachEvent' : document.removeEventListener ? 'removeEventListener' : 'detachEvent';
			var pref = document.addEventListener ? '' : 'on';

			document[eventTogglerName](pref + 'touchstart', this.handleTouchOutside);
			document[eventTogglerName](pref + 'mousedown', this.handleTouchOutside);
		}
	}, {
		key: 'handleTouchOutside',
		value: function handleTouchOutside(event) {
			// handle touch outside on ios to dismiss menu
			if (this.wrapper && !this.wrapper.contains(event.target)) {
				this.closeMenu();
			}
		}
	}, {
		key: 'focus',
		value: function focus() {
			if (!this.input) return;
			this.input.focus();
		}
	}, {
		key: 'blurInput',
		value: function blurInput() {
			if (!this.input) return;
			this.input.blur();
		}
	}, {
		key: 'handleTouchMove',
		value: function handleTouchMove() {
			// Set a flag that the view is being dragged
			this.dragging = true;
		}
	}, {
		key: 'handleTouchStart',
		value: function handleTouchStart() {
			// Set a flag that the view is not being dragged
			this.dragging = false;
		}
	}, {
		key: 'handleTouchEnd',
		value: function handleTouchEnd(event) {
			// Check if the view is being dragged, In this case
			// we don't want to fire the click event (because the user only wants to scroll)
			if (this.dragging) return;

			// Fire the mouse events
			this.handleMouseDown(event);
		}
	}, {
		key: 'handleTouchEndClearValue',
		value: function handleTouchEndClearValue(event) {
			// Check if the view is being dragged, In this case
			// we don't want to fire the click event (because the user only wants to scroll)
			if (this.dragging) return;

			// Clear the value
			this.clearValue(event);
		}
	}, {
		key: 'handleMouseDown',
		value: function handleMouseDown(event) {
			// if the event was triggered by a mousedown and not the primary
			// button, or if the component is disabled, ignore it.
			if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) {
				return;
			}

			if (event.target.tagName === 'INPUT') {
				if (!this.state.isFocused) {
					this._openAfterFocus = this.props.openOnClick;
					this.focus();
				} else if (!this.state.isOpen) {
					this.setState({
						isOpen: true,
						isPseudoFocused: false,
						focusedOption: null
					});
				}

				return;
			}

			// prevent default event handlers
			event.preventDefault();

			// for the non-searchable select, toggle the menu
			if (!this.props.searchable) {
				// This code means that if a select is searchable, onClick the options menu will not appear, only on subsequent click will it open.
				this.focus();
				return this.setState({
					isOpen: !this.state.isOpen,
					focusedOption: null
				});
			}

			if (this.state.isFocused) {
				// On iOS, we can get into a state where we think the input is focused but it isn't really,
				// since iOS ignores programmatic calls to input.focus() that weren't triggered by a click event.
				// Call focus() again here to be safe.
				this.focus();

				var input = this.input;
				var toOpen = true;

				if (typeof input.getInput === 'function') {
					// Get the actual DOM input if the ref is an <AutosizeInput /> component
					input = input.getInput();
				}

				// clears the value so that the cursor will be at the end of input when the component re-renders
				input.value = '';

				if (this._focusAfterClear) {
					toOpen = false;
					this._focusAfterClear = false;
				}

				// if the input is focused, ensure the menu is open
				this.setState({
					isOpen: toOpen,
					isPseudoFocused: false,
					focusedOption: null
				});
			} else {
				// otherwise, focus the input and open the menu
				this._openAfterFocus = this.props.openOnClick;
				this.focus();
				this.setState({ focusedOption: null });
			}
		}
	}, {
		key: 'handleMouseDownOnArrow',
		value: function handleMouseDownOnArrow(event) {
			// if the event was triggered by a mousedown and not the primary
			// button, or if the component is disabled, ignore it.
			if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) {
				return;
			}

			if (this.state.isOpen) {
				// prevent default event handlers
				event.stopPropagation();
				event.preventDefault();
				// close the menu
				this.closeMenu();
			} else {
				// If the menu isn't open, let the event bubble to the main handleMouseDown
				this.setState({
					isOpen: true
				});
			}
		}
	}, {
		key: 'handleMouseDownOnMenu',
		value: function handleMouseDownOnMenu(event) {
			// if the event was triggered by a mousedown and not the primary
			// button, or if the component is disabled, ignore it.
			if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) {
				return;
			}

			event.stopPropagation();
			event.preventDefault();

			this._openAfterFocus = true;
			this.focus();
		}
	}, {
		key: 'closeMenu',
		value: function closeMenu() {
			if (this.props.onCloseResetsInput) {
				this.setState({
					inputValue: this.handleInputValueChange(''),
					isOpen: false,
					isPseudoFocused: this.state.isFocused && !this.props.multi
				});
			} else {
				this.setState({
					isOpen: false,
					isPseudoFocused: this.state.isFocused && !this.props.multi
				});
			}
			this.hasScrolledToOption = false;
		}
	}, {
		key: 'handleInputFocus',
		value: function handleInputFocus(event) {
			if (this.props.disabled) return;

			var toOpen = this.state.isOpen || this._openAfterFocus || this.props.openOnFocus;
			toOpen = this._focusAfterClear ? false : toOpen; //if focus happens after clear values, don't open dropdown yet.

			if (this.props.onFocus) {
				this.props.onFocus(event);
			}

			this.setState({
				isFocused: true,
				isOpen: !!toOpen
			});

			this._focusAfterClear = false;
			this._openAfterFocus = false;
		}
	}, {
		key: 'handleInputBlur',
		value: function handleInputBlur(event) {
			// The check for menu.contains(activeElement) is necessary to prevent IE11's scrollbar from closing the menu in certain contexts.
			if (this.menu && (this.menu === document.activeElement || this.menu.contains(document.activeElement))) {
				this.focus();
				return;
			}

			if (this.props.onBlur) {
				this.props.onBlur(event);
			}
			var onBlurredState = {
				isFocused: false,
				isOpen: false,
				isPseudoFocused: false
			};
			if (this.props.onBlurResetsInput) {
				onBlurredState.inputValue = this.handleInputValueChange('');
			}
			this.setState(onBlurredState);
		}
	}, {
		key: 'handleInputChange',
		value: function handleInputChange(event) {
			var newInputValue = event.target.value;

			if (this.state.inputValue !== event.target.value) {
				newInputValue = this.handleInputValueChange(newInputValue);
			}

			this.setState({
				inputValue: newInputValue,
				isOpen: true,
				isPseudoFocused: false
			});
		}
	}, {
		key: 'setInputValue',
		value: function setInputValue(newValue) {
			if (this.props.onInputChange) {
				var nextState = this.props.onInputChange(newValue);
				if (nextState != null && (typeof nextState === 'undefined' ? 'undefined' : _typeof(nextState)) !== 'object') {
					newValue = '' + nextState;
				}
			}
			this.setState({
				inputValue: newValue
			});
		}
	}, {
		key: 'handleInputValueChange',
		value: function handleInputValueChange(newValue) {
			if (this.props.onInputChange) {
				var nextState = this.props.onInputChange(newValue);
				// Note: != used deliberately here to catch undefined and null
				if (nextState != null && (typeof nextState === 'undefined' ? 'undefined' : _typeof(nextState)) !== 'object') {
					newValue = '' + nextState;
				}
			}
			return newValue;
		}
	}, {
		key: 'handleKeyDown',
		value: function handleKeyDown(event) {
			if (this.props.disabled) return;

			if (typeof this.props.onInputKeyDown === 'function') {
				this.props.onInputKeyDown(event);
				if (event.defaultPrevented) {
					return;
				}
			}

			switch (event.keyCode) {
				case 8:
					// backspace
					if (!this.state.inputValue && this.props.backspaceRemoves) {
						event.preventDefault();
						this.popValue();
					}
					break;
				case 9:
					// tab
					if (event.shiftKey || !this.state.isOpen || !this.props.tabSelectsValue) {
						break;
					}
					event.preventDefault();
					this.selectFocusedOption();
					break;
				case 13:
					// enter
					event.preventDefault();
					event.stopPropagation();
					if (this.state.isOpen) {
						this.selectFocusedOption();
					} else {
						this.focusNextOption();
					}
					break;
				case 27:
					// escape
					event.preventDefault();
					if (this.state.isOpen) {
						this.closeMenu();
						event.stopPropagation();
					} else if (this.props.clearable && this.props.escapeClearsValue) {
						this.clearValue(event);
						event.stopPropagation();
					}
					break;
				case 32:
					// space
					if (this.props.searchable) {
						break;
					}
					event.preventDefault();
					if (!this.state.isOpen) {
						this.focusNextOption();
						break;
					}
					event.stopPropagation();
					this.selectFocusedOption();
					break;
				case 38:
					// up
					event.preventDefault();
					this.focusPreviousOption();
					break;
				case 40:
					// down
					event.preventDefault();
					this.focusNextOption();
					break;
				case 33:
					// page up
					event.preventDefault();
					this.focusPageUpOption();
					break;
				case 34:
					// page down
					event.preventDefault();
					this.focusPageDownOption();
					break;
				case 35:
					// end key
					if (event.shiftKey) {
						break;
					}
					event.preventDefault();
					this.focusEndOption();
					break;
				case 36:
					// home key
					if (event.shiftKey) {
						break;
					}
					event.preventDefault();
					this.focusStartOption();
					break;
				case 46:
					// delete
					if (!this.state.inputValue && this.props.deleteRemoves) {
						event.preventDefault();
						this.popValue();
					}
					break;
			}
		}
	}, {
		key: 'handleValueClick',
		value: function handleValueClick(option, event) {
			if (!this.props.onValueClick) return;
			this.props.onValueClick(option, event);
		}
	}, {
		key: 'handleMenuScroll',
		value: function handleMenuScroll(event) {
			if (!this.props.onMenuScrollToBottom) return;
			var target = event.target;

			if (target.scrollHeight > target.offsetHeight && target.scrollHeight - target.offsetHeight - target.scrollTop <= 0) {
				this.props.onMenuScrollToBottom();
			}
		}
	}, {
		key: 'getOptionLabel',
		value: function getOptionLabel(op) {
			return op[this.props.labelKey];
		}

		/**
   * Turns a value into an array from the given options
   * @param {String|Number|Array} value		- the value of the select input
   * @param {Object}		nextProps	- optionally specify the nextProps so the returned array uses the latest configuration
   * @returns	{Array}	the value of the select represented in an array
   */

	}, {
		key: 'getValueArray',
		value: function getValueArray(value) {
			var nextProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;

			/** support optionally passing in the `nextProps` so `componentWillReceiveProps` updates will function as expected */
			var props = (typeof nextProps === 'undefined' ? 'undefined' : _typeof(nextProps)) === 'object' ? nextProps : this.props;
			if (props.multi) {
				if (typeof value === 'string') {
					value = value.split(props.delimiter);
				}
				if (!Array.isArray(value)) {
					if (value === null || value === undefined) return [];
					value = [value];
				}
				return value.map(function (value) {
					return expandValue(value, props);
				}).filter(function (i) {
					return i;
				});
			}
			var expandedValue = expandValue(value, props);
			return expandedValue ? [expandedValue] : [];
		}
	}, {
		key: 'setValue',
		value: function setValue(value) {
			var _this2 = this;

			if (this.props.autoBlur) {
				this.blurInput();
			}
			if (this.props.required) {
				var required = handleRequired(value, this.props.multi);
				this.setState({ required: required });
			}
			if (this.props.simpleValue && value) {
				value = this.props.multi ? value.map(function (i) {
					return i[_this2.props.valueKey];
				}).join(this.props.delimiter) : value[this.props.valueKey];
			}
			if (this.props.onChange) {
				this.props.onChange(value);
			}
		}
	}, {
		key: 'selectValue',
		value: function selectValue(value) {
			var _this3 = this;

			// NOTE: we actually add/set the value in a callback to make sure the
			// input value is empty to avoid styling issues in Chrome
			if (this.props.closeOnSelect) {
				this.hasScrolledToOption = false;
			}
			var updatedValue = this.props.onSelectResetsInput ? '' : this.state.inputValue;
			if (this.props.multi) {
				this.setState({
					focusedIndex: null,
					inputValue: this.handleInputValueChange(updatedValue),
					isOpen: !this.props.closeOnSelect
				}, function () {
					var valueArray = _this3.getValueArray(_this3.props.value);
					if (valueArray.some(function (i) {
						return i[_this3.props.valueKey] === value[_this3.props.valueKey];
					})) {
						_this3.removeValue(value);
					} else {
						_this3.addValue(value);
					}
				});
			} else {
				this.setState({
					inputValue: this.handleInputValueChange(updatedValue),
					isOpen: !this.props.closeOnSelect,
					isPseudoFocused: this.state.isFocused
				}, function () {
					_this3.setValue(value);
				});
			}
		}
	}, {
		key: 'addValue',
		value: function addValue(value) {
			var valueArray = this.getValueArray(this.props.value);
			var visibleOptions = this._visibleOptions.filter(function (val) {
				return !val.disabled;
			});
			var lastValueIndex = visibleOptions.indexOf(value);
			this.setValue(valueArray.concat(value));
			if (!this.props.closeOnSelect) {
				return;
			}
			if (visibleOptions.length - 1 === lastValueIndex) {
				// the last option was selected; focus the second-last one
				this.focusOption(visibleOptions[lastValueIndex - 1]);
			} else if (visibleOptions.length > lastValueIndex) {
				// focus the option below the selected one
				this.focusOption(visibleOptions[lastValueIndex + 1]);
			}
		}
	}, {
		key: 'popValue',
		value: function popValue() {
			var valueArray = this.getValueArray(this.props.value);
			if (!valueArray.length) return;
			if (valueArray[valueArray.length - 1].clearableValue === false) return;
			this.setValue(this.props.multi ? valueArray.slice(0, valueArray.length - 1) : null);
		}
	}, {
		key: 'removeValue',
		value: function removeValue(value) {
			var _this4 = this;

			var valueArray = this.getValueArray(this.props.value);
			this.setValue(valueArray.filter(function (i) {
				return i[_this4.props.valueKey] !== value[_this4.props.valueKey];
			}));
			this.focus();
		}
	}, {
		key: 'clearValue',
		value: function clearValue(event) {
			// if the event was triggered by a mousedown and not the primary
			// button, ignore it.
			if (event && event.type === 'mousedown' && event.button !== 0) {
				return;
			}

			event.preventDefault();

			this.setValue(this.getResetValue());
			this.setState({
				inputValue: this.handleInputValueChange(''),
				isOpen: false
			}, this.focus);

			this._focusAfterClear = true;
		}
	}, {
		key: 'getResetValue',
		value: function getResetValue() {
			if (this.props.resetValue !== undefined) {
				return this.props.resetValue;
			} else if (this.props.multi) {
				return [];
			} else {
				return null;
			}
		}
	}, {
		key: 'focusOption',
		value: function focusOption(option) {
			this.setState({
				focusedOption: option
			});
		}
	}, {
		key: 'focusNextOption',
		value: function focusNextOption() {
			this.focusAdjacentOption('next');
		}
	}, {
		key: 'focusPreviousOption',
		value: function focusPreviousOption() {
			this.focusAdjacentOption('previous');
		}
	}, {
		key: 'focusPageUpOption',
		value: function focusPageUpOption() {
			this.focusAdjacentOption('page_up');
		}
	}, {
		key: 'focusPageDownOption',
		value: function focusPageDownOption() {
			this.focusAdjacentOption('page_down');
		}
	}, {
		key: 'focusStartOption',
		value: function focusStartOption() {
			this.focusAdjacentOption('start');
		}
	}, {
		key: 'focusEndOption',
		value: function focusEndOption() {
			this.focusAdjacentOption('end');
		}
	}, {
		key: 'focusAdjacentOption',
		value: function focusAdjacentOption(dir) {
			var options = this._visibleOptions.map(function (option, index) {
				return { option: option, index: index };
			}).filter(function (option) {
				return !option.option.disabled;
			});
			this._scrollToFocusedOptionOnUpdate = true;
			if (!this.state.isOpen) {
				var newState = {
					focusedOption: this._focusedOption || (options.length ? options[dir === 'next' ? 0 : options.length - 1].option : null),
					isOpen: true
				};
				if (this.props.onSelectResetsInput) {
					newState.inputValue = '';
				}
				this.setState(newState);
				return;
			}
			if (!options.length) return;
			var focusedIndex = -1;
			for (var i = 0; i < options.length; i++) {
				if (this._focusedOption === options[i].option) {
					focusedIndex = i;
					break;
				}
			}
			if (dir === 'next' && focusedIndex !== -1) {
				focusedIndex = (focusedIndex + 1) % options.length;
			} else if (dir === 'previous') {
				if (focusedIndex > 0) {
					focusedIndex = focusedIndex - 1;
				} else {
					focusedIndex = options.length - 1;
				}
			} else if (dir === 'start') {
				focusedIndex = 0;
			} else if (dir === 'end') {
				focusedIndex = options.length - 1;
			} else if (dir === 'page_up') {
				var potentialIndex = focusedIndex - this.props.pageSize;
				if (potentialIndex < 0) {
					focusedIndex = 0;
				} else {
					focusedIndex = potentialIndex;
				}
			} else if (dir === 'page_down') {
				var _potentialIndex = focusedIndex + this.props.pageSize;
				if (_potentialIndex > options.length - 1) {
					focusedIndex = options.length - 1;
				} else {
					focusedIndex = _potentialIndex;
				}
			}

			if (focusedIndex === -1) {
				focusedIndex = 0;
			}

			this.setState({
				focusedIndex: options[focusedIndex].index,
				focusedOption: options[focusedIndex].option
			});
		}
	}, {
		key: 'getFocusedOption',
		value: function getFocusedOption() {
			return this._focusedOption;
		}
	}, {
		key: 'selectFocusedOption',
		value: function selectFocusedOption() {
			if (this._focusedOption) {
				return this.selectValue(this._focusedOption);
			}
		}
	}, {
		key: 'renderLoading',
		value: function renderLoading() {
			if (!this.props.isLoading) return;
			return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
				'span',
				{ className: 'Select-loading-zone', 'aria-hidden': 'true' },
				react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement('span', { className: 'Select-loading' })
			);
		}
	}, {
		key: 'renderValue',
		value: function renderValue(valueArray, isOpen) {
			var _this5 = this;

			var renderLabel = this.props.valueRenderer || this.getOptionLabel;
			var ValueComponent = this.props.valueComponent;
			if (!valueArray.length) {
				var showPlaceholder = shouldShowPlaceholder(this.state, this.props, isOpen);
				return showPlaceholder ? react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
					'div',
					{ className: 'Select-placeholder' },
					this.props.placeholder
				) : null;
			}
			var onClick = this.props.onValueClick ? this.handleValueClick : null;
			if (this.props.multi) {
				return valueArray.map(function (value, i) {
					return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
						ValueComponent,
						{
							disabled: _this5.props.disabled || value.clearableValue === false,
							id: _this5._instancePrefix + '-value-' + i,
							instancePrefix: _this5._instancePrefix,
							key: 'value-' + i + '-' + value[_this5.props.valueKey],
							onClick: onClick,
							onRemove: _this5.removeValue,
							placeholder: _this5.props.placeholder,
							value: value,
							values: valueArray
						},
						renderLabel(value, i),
						react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
							'span',
							{ className: 'Select-aria-only' },
							'\xA0'
						)
					);
				});
			} else if (shouldShowValue(this.state, this.props)) {
				if (isOpen) onClick = null;
				return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
					ValueComponent,
					{
						disabled: this.props.disabled,
						id: this._instancePrefix + '-value-item',
						instancePrefix: this._instancePrefix,
						onClick: onClick,
						placeholder: this.props.placeholder,
						value: valueArray[0]
					},
					renderLabel(valueArray[0])
				);
			}
		}
	}, {
		key: 'renderInput',
		value: function renderInput(valueArray, focusedOptionIndex) {
			var _classNames,
			    _this6 = this;

			var className = classnames__WEBPACK_IMPORTED_MODULE_1___default()('Select-input', this.props.inputProps.className);
			var isOpen = this.state.isOpen;

			var ariaOwns = classnames__WEBPACK_IMPORTED_MODULE_1___default()((_classNames = {}, defineProperty(_classNames, this._instancePrefix + '-list', isOpen), defineProperty(_classNames, this._instancePrefix + '-backspace-remove-message', this.props.multi && !this.props.disabled && this.state.isFocused && !this.state.inputValue), _classNames));

			var value = this.state.inputValue;
			if (value && !this.props.onSelectResetsInput && !this.state.isFocused) {
				// it hides input value when it is not focused and was not reset on select
				value = '';
			}

			var inputProps = _extends({}, this.props.inputProps, {
				'aria-activedescendant': isOpen ? this._instancePrefix + '-option-' + focusedOptionIndex : this._instancePrefix + '-value',
				'aria-describedby': this.props['aria-describedby'],
				'aria-expanded': '' + isOpen,
				'aria-haspopup': '' + isOpen,
				'aria-label': this.props['aria-label'],
				'aria-labelledby': this.props['aria-labelledby'],
				'aria-owns': ariaOwns,
				onBlur: this.handleInputBlur,
				onChange: this.handleInputChange,
				onFocus: this.handleInputFocus,
				ref: function ref(_ref) {
					return _this6.input = _ref;
				},
				role: 'combobox',
				required: this.state.required,
				tabIndex: this.props.tabIndex,
				value: value
			});

			if (this.props.inputRenderer) {
				return this.props.inputRenderer(inputProps);
			}

			if (this.props.disabled || !this.props.searchable) {
				var divProps = objectWithoutProperties(this.props.inputProps, []);


				var _ariaOwns = classnames__WEBPACK_IMPORTED_MODULE_1___default()(defineProperty({}, this._instancePrefix + '-list', isOpen));
				return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement('div', _extends({}, divProps, {
					'aria-expanded': isOpen,
					'aria-owns': _ariaOwns,
					'aria-activedescendant': isOpen ? this._instancePrefix + '-option-' + focusedOptionIndex : this._instancePrefix + '-value',
					'aria-disabled': '' + this.props.disabled,
					'aria-label': this.props['aria-label'],
					'aria-labelledby': this.props['aria-labelledby'],
					className: className,
					onBlur: this.handleInputBlur,
					onFocus: this.handleInputFocus,
					ref: function ref(_ref2) {
						return _this6.input = _ref2;
					},
					role: 'combobox',
					style: { border: 0, width: 1, display: 'inline-block' },
					tabIndex: this.props.tabIndex || 0
				}));
			}

			if (this.props.autosize) {
				return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react_input_autosize__WEBPACK_IMPORTED_MODULE_0___default.a, _extends({ id: this.props.id }, inputProps, { className: className, minWidth: '5' }));
			}
			return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
				'div',
				{ className: className, key: 'input-wrap', style: { display: 'inline-block' } },
				react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement('input', _extends({ id: this.props.id }, inputProps))
			);
		}
	}, {
		key: 'renderClear',
		value: function renderClear() {
			var valueArray = this.getValueArray(this.props.value);
			if (!this.props.clearable || !valueArray.length || this.props.disabled || this.props.isLoading) return;
			var ariaLabel = this.props.multi ? this.props.clearAllText : this.props.clearValueText;
			var clear = this.props.clearRenderer();

			return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
				'span',
				{
					'aria-label': ariaLabel,
					className: 'Select-clear-zone',
					onMouseDown: this.clearValue,
					onTouchEnd: this.handleTouchEndClearValue,
					onTouchMove: this.handleTouchMove,
					onTouchStart: this.handleTouchStart,
					title: ariaLabel
				},
				clear
			);
		}
	}, {
		key: 'renderArrow',
		value: function renderArrow() {
			if (!this.props.arrowRenderer) return;

			var onMouseDown = this.handleMouseDownOnArrow;
			var isOpen = this.state.isOpen;
			var arrow = this.props.arrowRenderer({ onMouseDown: onMouseDown, isOpen: isOpen });

			if (!arrow) {
				return null;
			}

			return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
				'span',
				{
					className: 'Select-arrow-zone',
					onMouseDown: onMouseDown
				},
				arrow
			);
		}
	}, {
		key: 'filterOptions',
		value: function filterOptions$$1(excludeOptions) {
			var filterValue = this.state.inputValue;
			var options = this.props.options || [];
			if (this.props.filterOptions) {
				// Maintain backwards compatibility with boolean attribute
				var filterOptions$$1 = typeof this.props.filterOptions === 'function' ? this.props.filterOptions : filterOptions;

				return filterOptions$$1(options, filterValue, excludeOptions, {
					filterOption: this.props.filterOption,
					ignoreAccents: this.props.ignoreAccents,
					ignoreCase: this.props.ignoreCase,
					labelKey: this.props.labelKey,
					matchPos: this.props.matchPos,
					matchProp: this.props.matchProp,
					trimFilter: this.props.trimFilter,
					valueKey: this.props.valueKey
				});
			} else {
				return options;
			}
		}
	}, {
		key: 'onOptionRef',
		value: function onOptionRef(ref, isFocused) {
			if (isFocused) {
				this.focused = ref;
			}
		}
	}, {
		key: 'renderMenu',
		value: function renderMenu(options, valueArray, focusedOption) {
			if (options && options.length) {
				return this.props.menuRenderer({
					focusedOption: focusedOption,
					focusOption: this.focusOption,
					inputValue: this.state.inputValue,
					instancePrefix: this._instancePrefix,
					labelKey: this.props.labelKey,
					onFocus: this.focusOption,
					onOptionRef: this.onOptionRef,
					onSelect: this.selectValue,
					optionClassName: this.props.optionClassName,
					optionComponent: this.props.optionComponent,
					optionRenderer: this.props.optionRenderer || this.getOptionLabel,
					options: options,
					removeValue: this.removeValue,
					selectValue: this.selectValue,
					valueArray: valueArray,
					valueKey: this.props.valueKey
				});
			} else if (this.props.noResultsText) {
				return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
					'div',
					{ className: 'Select-noresults' },
					this.props.noResultsText
				);
			} else {
				return null;
			}
		}
	}, {
		key: 'renderHiddenField',
		value: function renderHiddenField(valueArray) {
			var _this7 = this;

			if (!this.props.name) return;
			if (this.props.joinValues) {
				var value = valueArray.map(function (i) {
					return stringifyValue(i[_this7.props.valueKey]);
				}).join(this.props.delimiter);
				return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement('input', {
					disabled: this.props.disabled,
					name: this.props.name,
					ref: function ref(_ref3) {
						return _this7.value = _ref3;
					},
					type: 'hidden',
					value: value
				});
			}
			return valueArray.map(function (item, index) {
				return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement('input', {
					disabled: _this7.props.disabled,
					key: 'hidden.' + index,
					name: _this7.props.name,
					ref: 'value' + index,
					type: 'hidden',
					value: stringifyValue(item[_this7.props.valueKey])
				});
			});
		}
	}, {
		key: 'getFocusableOptionIndex',
		value: function getFocusableOptionIndex(selectedOption) {
			var options = this._visibleOptions;
			if (!options.length) return null;

			var valueKey = this.props.valueKey;
			var focusedOption = this.state.focusedOption || selectedOption;
			if (focusedOption && !focusedOption.disabled) {
				var focusedOptionIndex = -1;
				options.some(function (option, index) {
					var isOptionEqual = option[valueKey] === focusedOption[valueKey];
					if (isOptionEqual) {
						focusedOptionIndex = index;
					}
					return isOptionEqual;
				});
				if (focusedOptionIndex !== -1) {
					return focusedOptionIndex;
				}
			}

			for (var i = 0; i < options.length; i++) {
				if (!options[i].disabled) return i;
			}
			return null;
		}
	}, {
		key: 'renderOuter',
		value: function renderOuter(options, valueArray, focusedOption) {
			var _this8 = this;

			var menu = this.renderMenu(options, valueArray, focusedOption);
			if (!menu) {
				return null;
			}

			return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
				'div',
				{ ref: function ref(_ref5) {
						return _this8.menuContainer = _ref5;
					}, className: 'Select-menu-outer', style: this.props.menuContainerStyle },
				react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
					'div',
					{
						className: 'Select-menu',
						id: this._instancePrefix + '-list',
						onMouseDown: this.handleMouseDownOnMenu,
						onScroll: this.handleMenuScroll,
						ref: function ref(_ref4) {
							return _this8.menu = _ref4;
						},
						role: 'listbox',
						style: this.props.menuStyle,
						tabIndex: -1
					},
					menu
				)
			);
		}
	}, {
		key: 'render',
		value: function render() {
			var _this9 = this;

			var valueArray = this.getValueArray(this.props.value);
			var options = this._visibleOptions = this.filterOptions(this.props.multi && this.props.removeSelected ? valueArray : null);
			var isOpen = this.state.isOpen;
			if (this.props.multi && !options.length && valueArray.length && !this.state.inputValue) isOpen = false;
			var focusedOptionIndex = this.getFocusableOptionIndex(valueArray[0]);

			var focusedOption = null;
			if (focusedOptionIndex !== null) {
				focusedOption = this._focusedOption = options[focusedOptionIndex];
			} else {
				focusedOption = this._focusedOption = null;
			}
			var className = classnames__WEBPACK_IMPORTED_MODULE_1___default()('Select', this.props.className, {
				'has-value': valueArray.length,
				'is-clearable': this.props.clearable,
				'is-disabled': this.props.disabled,
				'is-focused': this.state.isFocused,
				'is-loading': this.props.isLoading,
				'is-open': isOpen,
				'is-pseudo-focused': this.state.isPseudoFocused,
				'is-searchable': this.props.searchable,
				'Select--multi': this.props.multi,
				'Select--rtl': this.props.rtl,
				'Select--single': !this.props.multi
			});

			var removeMessage = null;
			if (this.props.multi && !this.props.disabled && valueArray.length && !this.state.inputValue && this.state.isFocused && this.props.backspaceRemoves) {
				removeMessage = react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
					'span',
					{ id: this._instancePrefix + '-backspace-remove-message', className: 'Select-aria-only', 'aria-live': 'assertive' },
					this.props.backspaceToRemoveMessage.replace('{label}', valueArray[valueArray.length - 1][this.props.labelKey])
				);
			}

			return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
				'div',
				{ ref: function ref(_ref7) {
						return _this9.wrapper = _ref7;
					},
					className: className,
					style: this.props.wrapperStyle },
				this.renderHiddenField(valueArray),
				react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
					'div',
					{ ref: function ref(_ref6) {
							return _this9.control = _ref6;
						},
						className: 'Select-control',
						onKeyDown: this.handleKeyDown,
						onMouseDown: this.handleMouseDown,
						onTouchEnd: this.handleTouchEnd,
						onTouchMove: this.handleTouchMove,
						onTouchStart: this.handleTouchStart,
						style: this.props.style
					},
					react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
						'div',
						{ className: 'Select-multi-value-wrapper', id: this._instancePrefix + '-value' },
						this.renderValue(valueArray, isOpen),
						this.renderInput(valueArray, focusedOptionIndex)
					),
					removeMessage,
					this.renderLoading(),
					this.renderClear(),
					this.renderArrow()
				),
				isOpen ? this.renderOuter(options, valueArray, focusedOption) : null
			);
		}
	}]);
	return Select;
}(react__WEBPACK_IMPORTED_MODULE_3___default.a.Component);

Select$1.propTypes = {
	'aria-describedby': prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, // html id(s) of element(s) that should be used to describe this input (for assistive tech)
	'aria-label': prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, // aria label (for assistive tech)
	'aria-labelledby': prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, // html id of an element that should be used as the label (for assistive tech)
	arrowRenderer: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // create the drop-down caret element
	autoBlur: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // automatically blur the component when an option is selected
	autoFocus: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // autofocus the component on mount
	autofocus: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // deprecated; use autoFocus instead
	autosize: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // whether to enable autosizing or not
	backspaceRemoves: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // whether backspace removes an item if there is no text input
	backspaceToRemoveMessage: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, // message to use for screenreaders to press backspace to remove the current item - {label} is replaced with the item label
	className: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, // className for the outer element
	clearAllText: stringOrNode, // title for the "clear" control when multi: true
	clearRenderer: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // create clearable x element
	clearValueText: stringOrNode, // title for the "clear" control
	clearable: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // should it be possible to reset value
	closeOnSelect: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // whether to close the menu when a value is selected
	deleteRemoves: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // whether delete removes an item if there is no text input
	delimiter: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, // delimiter to use to join multiple values for the hidden field value
	disabled: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // whether the Select is disabled or not
	escapeClearsValue: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // whether escape clears the value when the menu is closed
	filterOption: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // method to filter a single option (option, filterString)
	filterOptions: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.any, // boolean to enable default filtering or function to filter the options array ([options], filterString, [values])
	id: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, // html id to set on the input element for accessibility or tests
	ignoreAccents: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // whether to strip diacritics when filtering
	ignoreCase: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // whether to perform case-insensitive filtering
	inputProps: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object, // custom attributes for the Input
	inputRenderer: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // returns a custom input component
	instanceId: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, // set the components instanceId
	isLoading: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // whether the Select is loading externally or not (such as options being loaded)
	joinValues: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // joins multiple values into a single form field with the delimiter (legacy mode)
	labelKey: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, // path of the label value in option objects
	matchPos: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, // (any|start) match the start or entire string when filtering
	matchProp: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, // (any|label|value) which option property to filter on
	menuBuffer: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.number, // optional buffer (in px) between the bottom of the viewport and the bottom of the menu
	menuContainerStyle: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object, // optional style to apply to the menu container
	menuRenderer: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // renders a custom menu with options
	menuStyle: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object, // optional style to apply to the menu
	multi: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // multi-value input
	name: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, // generates a hidden <input /> tag with this field name for html forms
	noResultsText: stringOrNode, // placeholder displayed when there are no matching search results
	onBlur: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // onBlur handler: function (event) {}
	onBlurResetsInput: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // whether input is cleared on blur
	onChange: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // onChange handler: function (newValue) {}
	onClose: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // fires when the menu is closed
	onCloseResetsInput: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // whether input is cleared when menu is closed through the arrow
	onFocus: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // onFocus handler: function (event) {}
	onInputChange: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // onInputChange handler: function (inputValue) {}
	onInputKeyDown: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // input keyDown handler: function (event) {}
	onMenuScrollToBottom: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // fires when the menu is scrolled to the bottom; can be used to paginate options
	onOpen: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // fires when the menu is opened
	onSelectResetsInput: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // whether input is cleared on select (works only for multiselect)
	onValueClick: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // onClick handler for value labels: function (value, event) {}
	openOnClick: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // boolean to control opening the menu when the control is clicked
	openOnFocus: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // always open options menu on focus
	optionClassName: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, // additional class(es) to apply to the <Option /> elements
	optionComponent: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // option component to render in dropdown
	optionRenderer: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // optionRenderer: function (option) {}
	options: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.array, // array of options
	pageSize: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.number, // number of entries to page when using page up/down keys
	placeholder: stringOrNode, // field placeholder, displayed when there's no value
	removeSelected: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // whether the selected option is removed from the dropdown on multi selects
	required: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // applies HTML5 required attribute when needed
	resetValue: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.any, // value to use when you clear the control
	rtl: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // set to true in order to use react-select in right-to-left direction
	scrollMenuIntoView: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // boolean to enable the viewport to shift so that the full menu fully visible when engaged
	searchable: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // whether to enable searching feature or not
	simpleValue: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // pass the value to onChange as a simple value (legacy pre 1.0 mode), defaults to false
	style: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object, // optional style to apply to the control
	tabIndex: stringOrNumber, // optional tab index of the control
	tabSelectsValue: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // whether to treat tabbing out while focused to be value selection
	trimFilter: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // whether to trim whitespace around filter value
	value: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.any, // initial field value
	valueComponent: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // value component to render
	valueKey: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, // path of the label value in option objects
	valueRenderer: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // valueRenderer: function (option) {}
	wrapperStyle: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object // optional style to apply to the component wrapper
};

Select$1.defaultProps = {
	arrowRenderer: arrowRenderer,
	autosize: true,
	backspaceRemoves: true,
	backspaceToRemoveMessage: 'Press backspace to remove {label}',
	clearable: true,
	clearAllText: 'Clear all',
	clearRenderer: clearRenderer,
	clearValueText: 'Clear value',
	closeOnSelect: true,
	deleteRemoves: true,
	delimiter: ',',
	disabled: false,
	escapeClearsValue: true,
	filterOptions: filterOptions,
	ignoreAccents: true,
	ignoreCase: true,
	inputProps: {},
	isLoading: false,
	joinValues: false,
	labelKey: 'label',
	matchPos: 'any',
	matchProp: 'any',
	menuBuffer: 0,
	menuRenderer: menuRenderer,
	multi: false,
	noResultsText: 'No results found',
	onBlurResetsInput: true,
	onCloseResetsInput: true,
	onSelectResetsInput: true,
	openOnClick: true,
	optionComponent: Option,
	pageSize: 5,
	placeholder: 'Select...',
	removeSelected: true,
	required: false,
	rtl: false,
	scrollMenuIntoView: true,
	searchable: true,
	simpleValue: false,
	tabSelectsValue: true,
	trimFilter: true,
	valueComponent: Value,
	valueKey: 'value'
};

var propTypes = {
	autoload: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool.isRequired, // automatically call the `loadOptions` prop on-mount; defaults to true
	cache: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.any, // object to use to cache results; set to null/false to disable caching
	children: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func.isRequired, // Child function responsible for creating the inner Select component; (props: Object): PropTypes.element
	ignoreAccents: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // strip diacritics when filtering; defaults to true
	ignoreCase: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // perform case-insensitive filtering; defaults to true
	loadOptions: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func.isRequired, // callback to load options asynchronously; (inputValue: string, callback: Function): ?Promise
	loadingPlaceholder: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.oneOfType([// replaces the placeholder while options are loading
	prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.node]),
	multi: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool, // multi-value input
	noResultsText: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.oneOfType([// field noResultsText, displayed when no options come back from the server
	prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.node]),
	onChange: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // onChange handler: function (newValue) {}
	onInputChange: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, // optional for keeping track of what is being typed
	options: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.array.isRequired, // array of options
	placeholder: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.oneOfType([// field placeholder, displayed when there's no value (shared with Select)
	prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.node]),
	searchPromptText: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.oneOfType([// label to prompt for search input
	prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.node]),
	value: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.any // initial field value
};

var defaultCache = {};

var defaultChildren = function defaultChildren(props) {
	return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(Select$1, props);
};

var defaultProps = {
	autoload: true,
	cache: defaultCache,
	children: defaultChildren,
	ignoreAccents: true,
	ignoreCase: true,
	loadingPlaceholder: 'Loading...',
	options: [],
	searchPromptText: 'Type to search'
};

var Async = function (_Component) {
	inherits(Async, _Component);

	function Async(props, context) {
		classCallCheck(this, Async);

		var _this = possibleConstructorReturn(this, (Async.__proto__ || Object.getPrototypeOf(Async)).call(this, props, context));

		_this._cache = props.cache === defaultCache ? {} : props.cache;

		_this.state = {
			inputValue: '',
			isLoading: false,
			options: props.options
		};

		_this.onInputChange = _this.onInputChange.bind(_this);
		return _this;
	}

	createClass(Async, [{
		key: 'componentDidMount',
		value: function componentDidMount() {
			var autoload = this.props.autoload;


			if (autoload) {
				this.loadOptions('');
			}
		}
	}, {
		key: 'componentWillReceiveProps',
		value: function componentWillReceiveProps(nextProps) {
			if (nextProps.options !== this.props.options) {
				this.setState({
					options: nextProps.options
				});
			}
		}
	}, {
		key: 'componentWillUnmount',
		value: function componentWillUnmount() {
			this._callback = null;
		}
	}, {
		key: 'loadOptions',
		value: function loadOptions(inputValue) {
			var _this2 = this;

			var loadOptions = this.props.loadOptions;

			var cache = this._cache;

			if (cache && Object.prototype.hasOwnProperty.call(cache, inputValue)) {
				this._callback = null;

				this.setState({
					isLoading: false,
					options: cache[inputValue]
				});

				return;
			}

			var callback = function callback(error, data) {
				var options = data && data.options || [];

				if (cache) {
					cache[inputValue] = options;
				}

				if (callback === _this2._callback) {
					_this2._callback = null;

					_this2.setState({
						isLoading: false,
						options: options
					});
				}
			};

			// Ignore all but the most recent request
			this._callback = callback;

			var promise = loadOptions(inputValue, callback);
			if (promise) {
				promise.then(function (data) {
					return callback(null, data);
				}, function (error) {
					return callback(error);
				});
			}

			if (this._callback && !this.state.isLoading) {
				this.setState({
					isLoading: true
				});
			}
		}
	}, {
		key: 'onInputChange',
		value: function onInputChange(inputValue) {
			var _props = this.props,
			    ignoreAccents = _props.ignoreAccents,
			    ignoreCase = _props.ignoreCase,
			    onInputChange = _props.onInputChange;

			var newInputValue = inputValue;

			if (onInputChange) {
				var value = onInputChange(newInputValue);
				// Note: != used deliberately here to catch undefined and null
				if (value != null && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) !== 'object') {
					newInputValue = '' + value;
				}
			}

			var transformedInputValue = newInputValue;

			if (ignoreAccents) {
				transformedInputValue = stripDiacritics(transformedInputValue);
			}

			if (ignoreCase) {
				transformedInputValue = transformedInputValue.toLowerCase();
			}

			this.setState({ inputValue: newInputValue });
			this.loadOptions(transformedInputValue);

			// Return new input value, but without applying toLowerCase() to avoid modifying the user's view case of the input while typing.
			return newInputValue;
		}
	}, {
		key: 'noResultsText',
		value: function noResultsText() {
			var _props2 = this.props,
			    loadingPlaceholder = _props2.loadingPlaceholder,
			    noResultsText = _props2.noResultsText,
			    searchPromptText = _props2.searchPromptText;
			var _state = this.state,
			    inputValue = _state.inputValue,
			    isLoading = _state.isLoading;


			if (isLoading) {
				return loadingPlaceholder;
			}
			if (inputValue && noResultsText) {
				return noResultsText;
			}
			return searchPromptText;
		}
	}, {
		key: 'focus',
		value: function focus() {
			this.select.focus();
		}
	}, {
		key: 'render',
		value: function render() {
			var _this3 = this;

			var _props3 = this.props,
			    children = _props3.children,
			    loadingPlaceholder = _props3.loadingPlaceholder,
			    placeholder = _props3.placeholder;
			var _state2 = this.state,
			    isLoading = _state2.isLoading,
			    options = _state2.options;


			var props = {
				noResultsText: this.noResultsText(),
				placeholder: isLoading ? loadingPlaceholder : placeholder,
				options: isLoading && loadingPlaceholder ? [] : options,
				ref: function ref(_ref) {
					return _this3.select = _ref;
				}
			};

			return children(_extends({}, this.props, props, {
				isLoading: isLoading,
				onInputChange: this.onInputChange
			}));
		}
	}]);
	return Async;
}(react__WEBPACK_IMPORTED_MODULE_3__["Component"]);

Async.propTypes = propTypes;
Async.defaultProps = defaultProps;

var CreatableSelect = function (_React$Component) {
	inherits(CreatableSelect, _React$Component);

	function CreatableSelect(props, context) {
		classCallCheck(this, CreatableSelect);

		var _this = possibleConstructorReturn(this, (CreatableSelect.__proto__ || Object.getPrototypeOf(CreatableSelect)).call(this, props, context));

		_this.filterOptions = _this.filterOptions.bind(_this);
		_this.menuRenderer = _this.menuRenderer.bind(_this);
		_this.onInputKeyDown = _this.onInputKeyDown.bind(_this);
		_this.onInputChange = _this.onInputChange.bind(_this);
		_this.onOptionSelect = _this.onOptionSelect.bind(_this);
		return _this;
	}

	createClass(CreatableSelect, [{
		key: 'createNewOption',
		value: function createNewOption() {
			var _props = this.props,
			    isValidNewOption = _props.isValidNewOption,
			    newOptionCreator = _props.newOptionCreator,
			    onNewOptionClick = _props.onNewOptionClick,
			    _props$options = _props.options,
			    options = _props$options === undefined ? [] : _props$options;


			if (isValidNewOption({ label: this.inputValue })) {
				var option = newOptionCreator({ label: this.inputValue, labelKey: this.labelKey, valueKey: this.valueKey });
				var _isOptionUnique = this.isOptionUnique({ option: option, options: options });

				// Don't add the same option twice.
				if (_isOptionUnique) {
					if (onNewOptionClick) {
						onNewOptionClick(option);
					} else {
						options.unshift(option);

						this.select.selectValue(option);
					}
				}
			}
		}
	}, {
		key: 'filterOptions',
		value: function filterOptions$$1() {
			var _props2 = this.props,
			    filterOptions$$1 = _props2.filterOptions,
			    isValidNewOption = _props2.isValidNewOption,
			    promptTextCreator = _props2.promptTextCreator,
			    showNewOptionAtTop = _props2.showNewOptionAtTop;

			// TRICKY Check currently selected options as well.
			// Don't display a create-prompt for a value that's selected.
			// This covers async edge-cases where a newly-created Option isn't yet in the async-loaded array.

			var excludeOptions = (arguments.length <= 2 ? undefined : arguments[2]) || [];

			var filteredOptions = filterOptions$$1.apply(undefined, arguments) || [];

			if (isValidNewOption({ label: this.inputValue })) {
				var _newOptionCreator = this.props.newOptionCreator;


				var option = _newOptionCreator({
					label: this.inputValue,
					labelKey: this.labelKey,
					valueKey: this.valueKey
				});

				// TRICKY Compare to all options (not just filtered options) in case option has already been selected).
				// For multi-selects, this would remove it from the filtered list.
				var _isOptionUnique2 = this.isOptionUnique({
					option: option,
					options: excludeOptions.concat(filteredOptions)
				});

				if (_isOptionUnique2) {
					var prompt = promptTextCreator(this.inputValue);

					this._createPlaceholderOption = _newOptionCreator({
						label: prompt,
						labelKey: this.labelKey,
						valueKey: this.valueKey
					});

					if (showNewOptionAtTop) {
						filteredOptions.unshift(this._createPlaceholderOption);
					} else {
						filteredOptions.push(this._createPlaceholderOption);
					}
				}
			}

			return filteredOptions;
		}
	}, {
		key: 'isOptionUnique',
		value: function isOptionUnique(_ref) {
			var option = _ref.option,
			    options = _ref.options;
			var isOptionUnique = this.props.isOptionUnique;


			options = options || this.props.options;

			return isOptionUnique({
				labelKey: this.labelKey,
				option: option,
				options: options,
				valueKey: this.valueKey
			});
		}
	}, {
		key: 'menuRenderer',
		value: function menuRenderer$$1(params) {
			var menuRenderer$$1 = this.props.menuRenderer;


			return menuRenderer$$1(_extends({}, params, {
				onSelect: this.onOptionSelect,
				selectValue: this.onOptionSelect
			}));
		}
	}, {
		key: 'onInputChange',
		value: function onInputChange(input) {
			var onInputChange = this.props.onInputChange;

			// This value may be needed in between Select mounts (when this.select is null)

			this.inputValue = input;

			if (onInputChange) {
				this.inputValue = onInputChange(input);
			}

			return this.inputValue;
		}
	}, {
		key: 'onInputKeyDown',
		value: function onInputKeyDown(event) {
			var _props3 = this.props,
			    shouldKeyDownEventCreateNewOption = _props3.shouldKeyDownEventCreateNewOption,
			    onInputKeyDown = _props3.onInputKeyDown;

			var focusedOption = this.select.getFocusedOption();

			if (focusedOption && focusedOption === this._createPlaceholderOption && shouldKeyDownEventCreateNewOption(event)) {
				this.createNewOption();

				// Prevent decorated Select from doing anything additional with this keyDown event
				event.preventDefault();
			} else if (onInputKeyDown) {
				onInputKeyDown(event);
			}
		}
	}, {
		key: 'onOptionSelect',
		value: function onOptionSelect(option) {
			if (option === this._createPlaceholderOption) {
				this.createNewOption();
			} else {
				this.select.selectValue(option);
			}
		}
	}, {
		key: 'focus',
		value: function focus() {
			this.select.focus();
		}
	}, {
		key: 'render',
		value: function render() {
			var _this2 = this;

			var _props4 = this.props,
			    refProp = _props4.ref,
			    restProps = objectWithoutProperties(_props4, ['ref']);
			var children = this.props.children;

			// We can't use destructuring default values to set the children,
			// because it won't apply work if `children` is null. A falsy check is
			// more reliable in real world use-cases.

			if (!children) {
				children = defaultChildren$2;
			}

			var props = _extends({}, restProps, {
				allowCreate: true,
				filterOptions: this.filterOptions,
				menuRenderer: this.menuRenderer,
				onInputChange: this.onInputChange,
				onInputKeyDown: this.onInputKeyDown,
				ref: function ref(_ref2) {
					_this2.select = _ref2;

					// These values may be needed in between Select mounts (when this.select is null)
					if (_ref2) {
						_this2.labelKey = _ref2.props.labelKey;
						_this2.valueKey = _ref2.props.valueKey;
					}
					if (refProp) {
						refProp(_ref2);
					}
				}
			});

			return children(props);
		}
	}]);
	return CreatableSelect;
}(react__WEBPACK_IMPORTED_MODULE_3___default.a.Component);

var defaultChildren$2 = function defaultChildren(props) {
	return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(Select$1, props);
};

var isOptionUnique = function isOptionUnique(_ref3) {
	var option = _ref3.option,
	    options = _ref3.options,
	    labelKey = _ref3.labelKey,
	    valueKey = _ref3.valueKey;

	if (!options || !options.length) {
		return true;
	}

	return options.filter(function (existingOption) {
		return existingOption[labelKey] === option[labelKey] || existingOption[valueKey] === option[valueKey];
	}).length === 0;
};

var isValidNewOption = function isValidNewOption(_ref4) {
	var label = _ref4.label;
	return !!label;
};

var newOptionCreator = function newOptionCreator(_ref5) {
	var label = _ref5.label,
	    labelKey = _ref5.labelKey,
	    valueKey = _ref5.valueKey;

	var option = {};
	option[valueKey] = label;
	option[labelKey] = label;
	option.className = 'Select-create-option-placeholder';

	return option;
};

var promptTextCreator = function promptTextCreator(label) {
	return 'Create option "' + label + '"';
};

var shouldKeyDownEventCreateNewOption = function shouldKeyDownEventCreateNewOption(_ref6) {
	var keyCode = _ref6.keyCode;

	switch (keyCode) {
		case 9: // TAB
		case 13: // ENTER
		case 188:
			// COMMA
			return true;
		default:
			return false;
	}
};

// Default prop methods
CreatableSelect.isOptionUnique = isOptionUnique;
CreatableSelect.isValidNewOption = isValidNewOption;
CreatableSelect.newOptionCreator = newOptionCreator;
CreatableSelect.promptTextCreator = promptTextCreator;
CreatableSelect.shouldKeyDownEventCreateNewOption = shouldKeyDownEventCreateNewOption;

CreatableSelect.defaultProps = {
	filterOptions: filterOptions,
	isOptionUnique: isOptionUnique,
	isValidNewOption: isValidNewOption,
	menuRenderer: menuRenderer,
	newOptionCreator: newOptionCreator,
	promptTextCreator: promptTextCreator,
	shouldKeyDownEventCreateNewOption: shouldKeyDownEventCreateNewOption,
	showNewOptionAtTop: true
};

CreatableSelect.propTypes = {
	// Child function responsible for creating the inner Select component
	// This component can be used to compose HOCs (eg Creatable and Async)
	// (props: Object): PropTypes.element
	children: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func,

	// See Select.propTypes.filterOptions
	filterOptions: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.any,

	// Searches for any matching option within the set of options.
	// This function prevents duplicate options from being created.
	// ({ option: Object, options: Array, labelKey: string, valueKey: string }): boolean
	isOptionUnique: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func,

	// Determines if the current input text represents a valid option.
	// ({ label: string }): boolean
	isValidNewOption: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func,

	// See Select.propTypes.menuRenderer
	menuRenderer: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.any,

	// Factory to create new option.
	// ({ label: string, labelKey: string, valueKey: string }): Object
	newOptionCreator: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func,

	// input change handler: function (inputValue) {}
	onInputChange: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func,

	// input keyDown handler: function (event) {}
	onInputKeyDown: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func,

	// new option click handler: function (option) {}
	onNewOptionClick: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func,

	// See Select.propTypes.options
	options: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.array,

	// Creates prompt/placeholder option text.
	// (filterText: string): string
	promptTextCreator: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func,

	ref: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func,

	// Decides if a keyDown event (eg its `keyCode`) should result in the creation of a new option.
	shouldKeyDownEventCreateNewOption: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func,

	// Where to show prompt/placeholder option text.
	// true: new option prompt at top of list (default)
	// false: new option prompt at bottom of list
	showNewOptionAtTop: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool
};

var AsyncCreatableSelect = function (_React$Component) {
	inherits(AsyncCreatableSelect, _React$Component);

	function AsyncCreatableSelect() {
		classCallCheck(this, AsyncCreatableSelect);
		return possibleConstructorReturn(this, (AsyncCreatableSelect.__proto__ || Object.getPrototypeOf(AsyncCreatableSelect)).apply(this, arguments));
	}

	createClass(AsyncCreatableSelect, [{
		key: 'focus',
		value: function focus() {
			this.select.focus();
		}
	}, {
		key: 'render',
		value: function render() {
			var _this2 = this;

			return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
				Async,
				this.props,
				function (_ref) {
					var ref = _ref.ref,
					    asyncProps = objectWithoutProperties(_ref, ['ref']);

					var asyncRef = ref;
					return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(
						CreatableSelect,
						asyncProps,
						function (_ref2) {
							var ref = _ref2.ref,
							    creatableProps = objectWithoutProperties(_ref2, ['ref']);

							var creatableRef = ref;
							return _this2.props.children(_extends({}, creatableProps, {
								ref: function ref(select) {
									creatableRef(select);
									asyncRef(select);
									_this2.select = select;
								}
							}));
						}
					);
				}
			);
		}
	}]);
	return AsyncCreatableSelect;
}(react__WEBPACK_IMPORTED_MODULE_3___default.a.Component);

var defaultChildren$1 = function defaultChildren(props) {
	return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(Select$1, props);
};

AsyncCreatableSelect.propTypes = {
	children: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func.isRequired // Child function responsible for creating the inner Select component; (props: Object): PropTypes.element
};

AsyncCreatableSelect.defaultProps = {
	children: defaultChildren$1
};

Select$1.Async = Async;
Select$1.AsyncCreatable = AsyncCreatableSelect;
Select$1.Creatable = CreatableSelect;
Select$1.Value = Value;
Select$1.Option = Option;


/* harmony default export */ __webpack_exports__["default"] = (Select$1);


/***/ }),

/***/ "8J/B":
/*!**************************************************************************!*\
  !*** ./node_modules/react-color/lib/components/compact/CompactFields.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CompactFields = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _common = __webpack_require__(/*! ../common */ "TM95");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var CompactFields = exports.CompactFields = function CompactFields(_ref) {
  var hex = _ref.hex,
      rgb = _ref.rgb,
      onChange = _ref.onChange;

  var styles = (0, _reactcss2.default)({
    'default': {
      fields: {
        display: 'flex',
        paddingBottom: '6px',
        paddingRight: '5px',
        position: 'relative'
      },
      active: {
        position: 'absolute',
        top: '6px',
        left: '5px',
        height: '9px',
        width: '9px',
        background: hex
      },
      HEXwrap: {
        flex: '6',
        position: 'relative'
      },
      HEXinput: {
        width: '80%',
        padding: '0px',
        paddingLeft: '20%',
        border: 'none',
        outline: 'none',
        background: 'none',
        fontSize: '12px',
        color: '#333',
        height: '16px'
      },
      HEXlabel: {
        display: 'none'
      },
      RGBwrap: {
        flex: '3',
        position: 'relative'
      },
      RGBinput: {
        width: '70%',
        padding: '0px',
        paddingLeft: '30%',
        border: 'none',
        outline: 'none',
        background: 'none',
        fontSize: '12px',
        color: '#333',
        height: '16px'
      },
      RGBlabel: {
        position: 'absolute',
        top: '3px',
        left: '0px',
        lineHeight: '16px',
        textTransform: 'uppercase',
        fontSize: '12px',
        color: '#999'
      }
    }
  });

  var handleChange = function handleChange(data, e) {
    if (data.r || data.g || data.b) {
      onChange({
        r: data.r || rgb.r,
        g: data.g || rgb.g,
        b: data.b || rgb.b,
        source: 'rgb'
      }, e);
    } else {
      onChange({
        hex: data.hex,
        source: 'hex'
      }, e);
    }
  };

  return _react2.default.createElement(
    'div',
    { style: styles.fields, className: 'flexbox-fix' },
    _react2.default.createElement('div', { style: styles.active }),
    _react2.default.createElement(_common.EditableInput, {
      style: { wrap: styles.HEXwrap, input: styles.HEXinput, label: styles.HEXlabel },
      label: 'hex',
      value: hex,
      onChange: handleChange
    }),
    _react2.default.createElement(_common.EditableInput, {
      style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
      label: 'r',
      value: rgb.r,
      onChange: handleChange
    }),
    _react2.default.createElement(_common.EditableInput, {
      style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
      label: 'g',
      value: rgb.g,
      onChange: handleChange
    }),
    _react2.default.createElement(_common.EditableInput, {
      style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
      label: 'b',
      value: rgb.b,
      onChange: handleChange
    })
  );
};

exports.default = CompactFields;

/***/ }),

/***/ "8PLQ":
/*!**************************************************!*\
  !*** ./node_modules/entities/maps/entities.json ***!
  \**************************************************/
/*! exports provided: Aacute, aacute, Abreve, abreve, ac, acd, acE, Acirc, acirc, acute, Acy, acy, AElig, aelig, af, Afr, afr, Agrave, agrave, alefsym, aleph, Alpha, alpha, Amacr, amacr, amalg, amp, AMP, andand, And, and, andd, andslope, andv, ang, ange, angle, angmsdaa, angmsdab, angmsdac, angmsdad, angmsdae, angmsdaf, angmsdag, angmsdah, angmsd, angrt, angrtvb, angrtvbd, angsph, angst, angzarr, Aogon, aogon, Aopf, aopf, apacir, ap, apE, ape, apid, apos, ApplyFunction, approx, approxeq, Aring, aring, Ascr, ascr, Assign, ast, asymp, asympeq, Atilde, atilde, Auml, auml, awconint, awint, backcong, backepsilon, backprime, backsim, backsimeq, Backslash, Barv, barvee, barwed, Barwed, barwedge, bbrk, bbrktbrk, bcong, Bcy, bcy, bdquo, becaus, because, Because, bemptyv, bepsi, bernou, Bernoullis, Beta, beta, beth, between, Bfr, bfr, bigcap, bigcirc, bigcup, bigodot, bigoplus, bigotimes, bigsqcup, bigstar, bigtriangledown, bigtriangleup, biguplus, bigvee, bigwedge, bkarow, blacklozenge, blacksquare, blacktriangle, blacktriangledown, blacktriangleleft, blacktriangleright, blank, blk12, blk14, blk34, block, bne, bnequiv, bNot, bnot, Bopf, bopf, bot, bottom, bowtie, boxbox, boxdl, boxdL, boxDl, boxDL, boxdr, boxdR, boxDr, boxDR, boxh, boxH, boxhd, boxHd, boxhD, boxHD, boxhu, boxHu, boxhU, boxHU, boxminus, boxplus, boxtimes, boxul, boxuL, boxUl, boxUL, boxur, boxuR, boxUr, boxUR, boxv, boxV, boxvh, boxvH, boxVh, boxVH, boxvl, boxvL, boxVl, boxVL, boxvr, boxvR, boxVr, boxVR, bprime, breve, Breve, brvbar, bscr, Bscr, bsemi, bsim, bsime, bsolb, bsol, bsolhsub, bull, bullet, bump, bumpE, bumpe, Bumpeq, bumpeq, Cacute, cacute, capand, capbrcup, capcap, cap, Cap, capcup, capdot, CapitalDifferentialD, caps, caret, caron, Cayleys, ccaps, Ccaron, ccaron, Ccedil, ccedil, Ccirc, ccirc, Cconint, ccups, ccupssm, Cdot, cdot, cedil, Cedilla, cemptyv, cent, centerdot, CenterDot, cfr, Cfr, CHcy, chcy, check, checkmark, Chi, chi, circ, circeq, circlearrowleft, circlearrowright, circledast, circledcirc, circleddash, CircleDot, circledR, circledS, CircleMinus, CirclePlus, CircleTimes, cir, cirE, cire, cirfnint, cirmid, cirscir, ClockwiseContourIntegral, CloseCurlyDoubleQuote, CloseCurlyQuote, clubs, clubsuit, colon, Colon, Colone, colone, coloneq, comma, commat, comp, compfn, complement, complexes, cong, congdot, Congruent, conint, Conint, ContourIntegral, copf, Copf, coprod, Coproduct, copy, COPY, copysr, CounterClockwiseContourIntegral, crarr, cross, Cross, Cscr, cscr, csub, csube, csup, csupe, ctdot, cudarrl, cudarrr, cuepr, cuesc, cularr, cularrp, cupbrcap, cupcap, CupCap, cup, Cup, cupcup, cupdot, cupor, cups, curarr, curarrm, curlyeqprec, curlyeqsucc, curlyvee, curlywedge, curren, curvearrowleft, curvearrowright, cuvee, cuwed, cwconint, cwint, cylcty, dagger, Dagger, daleth, darr, Darr, dArr, dash, Dashv, dashv, dbkarow, dblac, Dcaron, dcaron, Dcy, dcy, ddagger, ddarr, DD, dd, DDotrahd, ddotseq, deg, Del, Delta, delta, demptyv, dfisht, Dfr, dfr, dHar, dharl, dharr, DiacriticalAcute, DiacriticalDot, DiacriticalDoubleAcute, DiacriticalGrave, DiacriticalTilde, diam, diamond, Diamond, diamondsuit, diams, die, DifferentialD, digamma, disin, div, divide, divideontimes, divonx, DJcy, djcy, dlcorn, dlcrop, dollar, Dopf, dopf, Dot, dot, DotDot, doteq, doteqdot, DotEqual, dotminus, dotplus, dotsquare, doublebarwedge, DoubleContourIntegral, DoubleDot, DoubleDownArrow, DoubleLeftArrow, DoubleLeftRightArrow, DoubleLeftTee, DoubleLongLeftArrow, DoubleLongLeftRightArrow, DoubleLongRightArrow, DoubleRightArrow, DoubleRightTee, DoubleUpArrow, DoubleUpDownArrow, DoubleVerticalBar, DownArrowBar, downarrow, DownArrow, Downarrow, DownArrowUpArrow, DownBreve, downdownarrows, downharpoonleft, downharpoonright, DownLeftRightVector, DownLeftTeeVector, DownLeftVectorBar, DownLeftVector, DownRightTeeVector, DownRightVectorBar, DownRightVector, DownTeeArrow, DownTee, drbkarow, drcorn, drcrop, Dscr, dscr, DScy, dscy, dsol, Dstrok, dstrok, dtdot, dtri, dtrif, duarr, duhar, dwangle, DZcy, dzcy, dzigrarr, Eacute, eacute, easter, Ecaron, ecaron, Ecirc, ecirc, ecir, ecolon, Ecy, ecy, eDDot, Edot, edot, eDot, ee, efDot, Efr, efr, eg, Egrave, egrave, egs, egsdot, el, Element, elinters, ell, els, elsdot, Emacr, emacr, empty, emptyset, EmptySmallSquare, emptyv, EmptyVerySmallSquare, emsp13, emsp14, emsp, ENG, eng, ensp, Eogon, eogon, Eopf, eopf, epar, eparsl, eplus, epsi, Epsilon, epsilon, epsiv, eqcirc, eqcolon, eqsim, eqslantgtr, eqslantless, Equal, equals, EqualTilde, equest, Equilibrium, equiv, equivDD, eqvparsl, erarr, erDot, escr, Escr, esdot, Esim, esim, Eta, eta, ETH, eth, Euml, euml, euro, excl, exist, Exists, expectation, exponentiale, ExponentialE, fallingdotseq, Fcy, fcy, female, ffilig, fflig, ffllig, Ffr, ffr, filig, FilledSmallSquare, FilledVerySmallSquare, fjlig, flat, fllig, fltns, fnof, Fopf, fopf, forall, ForAll, fork, forkv, Fouriertrf, fpartint, frac12, frac13, frac14, frac15, frac16, frac18, frac23, frac25, frac34, frac35, frac38, frac45, frac56, frac58, frac78, frasl, frown, fscr, Fscr, gacute, Gamma, gamma, Gammad, gammad, gap, Gbreve, gbreve, Gcedil, Gcirc, gcirc, Gcy, gcy, Gdot, gdot, ge, gE, gEl, gel, geq, geqq, geqslant, gescc, ges, gesdot, gesdoto, gesdotol, gesl, gesles, Gfr, gfr, gg, Gg, ggg, gimel, GJcy, gjcy, gla, gl, glE, glj, gnap, gnapprox, gne, gnE, gneq, gneqq, gnsim, Gopf, gopf, grave, GreaterEqual, GreaterEqualLess, GreaterFullEqual, GreaterGreater, GreaterLess, GreaterSlantEqual, GreaterTilde, Gscr, gscr, gsim, gsime, gsiml, gtcc, gtcir, gt, GT, Gt, gtdot, gtlPar, gtquest, gtrapprox, gtrarr, gtrdot, gtreqless, gtreqqless, gtrless, gtrsim, gvertneqq, gvnE, Hacek, hairsp, half, hamilt, HARDcy, hardcy, harrcir, harr, hArr, harrw, Hat, hbar, Hcirc, hcirc, hearts, heartsuit, hellip, hercon, hfr, Hfr, HilbertSpace, hksearow, hkswarow, hoarr, homtht, hookleftarrow, hookrightarrow, hopf, Hopf, horbar, HorizontalLine, hscr, Hscr, hslash, Hstrok, hstrok, HumpDownHump, HumpEqual, hybull, hyphen, Iacute, iacute, ic, Icirc, icirc, Icy, icy, Idot, IEcy, iecy, iexcl, iff, ifr, Ifr, Igrave, igrave, ii, iiiint, iiint, iinfin, iiota, IJlig, ijlig, Imacr, imacr, image, ImaginaryI, imagline, imagpart, imath, Im, imof, imped, Implies, incare, in, infin, infintie, inodot, intcal, int, Int, integers, Integral, intercal, Intersection, intlarhk, intprod, InvisibleComma, InvisibleTimes, IOcy, iocy, Iogon, iogon, Iopf, iopf, Iota, iota, iprod, iquest, iscr, Iscr, isin, isindot, isinE, isins, isinsv, isinv, it, Itilde, itilde, Iukcy, iukcy, Iuml, iuml, Jcirc, jcirc, Jcy, jcy, Jfr, jfr, jmath, Jopf, jopf, Jscr, jscr, Jsercy, jsercy, Jukcy, jukcy, Kappa, kappa, kappav, Kcedil, kcedil, Kcy, kcy, Kfr, kfr, kgreen, KHcy, khcy, KJcy, kjcy, Kopf, kopf, Kscr, kscr, lAarr, Lacute, lacute, laemptyv, lagran, Lambda, lambda, lang, Lang, langd, langle, lap, Laplacetrf, laquo, larrb, larrbfs, larr, Larr, lArr, larrfs, larrhk, larrlp, larrpl, larrsim, larrtl, latail, lAtail, lat, late, lates, lbarr, lBarr, lbbrk, lbrace, lbrack, lbrke, lbrksld, lbrkslu, Lcaron, lcaron, Lcedil, lcedil, lceil, lcub, Lcy, lcy, ldca, ldquo, ldquor, ldrdhar, ldrushar, ldsh, le, lE, LeftAngleBracket, LeftArrowBar, leftarrow, LeftArrow, Leftarrow, LeftArrowRightArrow, leftarrowtail, LeftCeiling, LeftDoubleBracket, LeftDownTeeVector, LeftDownVectorBar, LeftDownVector, LeftFloor, leftharpoondown, leftharpoonup, leftleftarrows, leftrightarrow, LeftRightArrow, Leftrightarrow, leftrightarrows, leftrightharpoons, leftrightsquigarrow, LeftRightVector, LeftTeeArrow, LeftTee, LeftTeeVector, leftthreetimes, LeftTriangleBar, LeftTriangle, LeftTriangleEqual, LeftUpDownVector, LeftUpTeeVector, LeftUpVectorBar, LeftUpVector, LeftVectorBar, LeftVector, lEg, leg, leq, leqq, leqslant, lescc, les, lesdot, lesdoto, lesdotor, lesg, lesges, lessapprox, lessdot, lesseqgtr, lesseqqgtr, LessEqualGreater, LessFullEqual, LessGreater, lessgtr, LessLess, lesssim, LessSlantEqual, LessTilde, lfisht, lfloor, Lfr, lfr, lg, lgE, lHar, lhard, lharu, lharul, lhblk, LJcy, ljcy, llarr, ll, Ll, llcorner, Lleftarrow, llhard, lltri, Lmidot, lmidot, lmoustache, lmoust, lnap, lnapprox, lne, lnE, lneq, lneqq, lnsim, loang, loarr, lobrk, longleftarrow, LongLeftArrow, Longleftarrow, longleftrightarrow, LongLeftRightArrow, Longleftrightarrow, longmapsto, longrightarrow, LongRightArrow, Longrightarrow, looparrowleft, looparrowright, lopar, Lopf, lopf, loplus, lotimes, lowast, lowbar, LowerLeftArrow, LowerRightArrow, loz, lozenge, lozf, lpar, lparlt, lrarr, lrcorner, lrhar, lrhard, lrm, lrtri, lsaquo, lscr, Lscr, lsh, Lsh, lsim, lsime, lsimg, lsqb, lsquo, lsquor, Lstrok, lstrok, ltcc, ltcir, lt, LT, Lt, ltdot, lthree, ltimes, ltlarr, ltquest, ltri, ltrie, ltrif, ltrPar, lurdshar, luruhar, lvertneqq, lvnE, macr, male, malt, maltese, Map, map, mapsto, mapstodown, mapstoleft, mapstoup, marker, mcomma, Mcy, mcy, mdash, mDDot, measuredangle, MediumSpace, Mellintrf, Mfr, mfr, mho, micro, midast, midcir, mid, middot, minusb, minus, minusd, minusdu, MinusPlus, mlcp, mldr, mnplus, models, Mopf, mopf, mp, mscr, Mscr, mstpos, Mu, mu, multimap, mumap, nabla, Nacute, nacute, nang, nap, napE, napid, napos, napprox, natural, naturals, natur, nbsp, nbump, nbumpe, ncap, Ncaron, ncaron, Ncedil, ncedil, ncong, ncongdot, ncup, Ncy, ncy, ndash, nearhk, nearr, neArr, nearrow, ne, nedot, NegativeMediumSpace, NegativeThickSpace, NegativeThinSpace, NegativeVeryThinSpace, nequiv, nesear, nesim, NestedGreaterGreater, NestedLessLess, NewLine, nexist, nexists, Nfr, nfr, ngE, nge, ngeq, ngeqq, ngeqslant, nges, nGg, ngsim, nGt, ngt, ngtr, nGtv, nharr, nhArr, nhpar, ni, nis, nisd, niv, NJcy, njcy, nlarr, nlArr, nldr, nlE, nle, nleftarrow, nLeftarrow, nleftrightarrow, nLeftrightarrow, nleq, nleqq, nleqslant, nles, nless, nLl, nlsim, nLt, nlt, nltri, nltrie, nLtv, nmid, NoBreak, NonBreakingSpace, nopf, Nopf, Not, not, NotCongruent, NotCupCap, NotDoubleVerticalBar, NotElement, NotEqual, NotEqualTilde, NotExists, NotGreater, NotGreaterEqual, NotGreaterFullEqual, NotGreaterGreater, NotGreaterLess, NotGreaterSlantEqual, NotGreaterTilde, NotHumpDownHump, NotHumpEqual, notin, notindot, notinE, notinva, notinvb, notinvc, NotLeftTriangleBar, NotLeftTriangle, NotLeftTriangleEqual, NotLess, NotLessEqual, NotLessGreater, NotLessLess, NotLessSlantEqual, NotLessTilde, NotNestedGreaterGreater, NotNestedLessLess, notni, notniva, notnivb, notnivc, NotPrecedes, NotPrecedesEqual, NotPrecedesSlantEqual, NotReverseElement, NotRightTriangleBar, NotRightTriangle, NotRightTriangleEqual, NotSquareSubset, NotSquareSubsetEqual, NotSquareSuperset, NotSquareSupersetEqual, NotSubset, NotSubsetEqual, NotSucceeds, NotSucceedsEqual, NotSucceedsSlantEqual, NotSucceedsTilde, NotSuperset, NotSupersetEqual, NotTilde, NotTildeEqual, NotTildeFullEqual, NotTildeTilde, NotVerticalBar, nparallel, npar, nparsl, npart, npolint, npr, nprcue, nprec, npreceq, npre, nrarrc, nrarr, nrArr, nrarrw, nrightarrow, nRightarrow, nrtri, nrtrie, nsc, nsccue, nsce, Nscr, nscr, nshortmid, nshortparallel, nsim, nsime, nsimeq, nsmid, nspar, nsqsube, nsqsupe, nsub, nsubE, nsube, nsubset, nsubseteq, nsubseteqq, nsucc, nsucceq, nsup, nsupE, nsupe, nsupset, nsupseteq, nsupseteqq, ntgl, Ntilde, ntilde, ntlg, ntriangleleft, ntrianglelefteq, ntriangleright, ntrianglerighteq, Nu, nu, num, numero, numsp, nvap, nvdash, nvDash, nVdash, nVDash, nvge, nvgt, nvHarr, nvinfin, nvlArr, nvle, nvlt, nvltrie, nvrArr, nvrtrie, nvsim, nwarhk, nwarr, nwArr, nwarrow, nwnear, Oacute, oacute, oast, Ocirc, ocirc, ocir, Ocy, ocy, odash, Odblac, odblac, odiv, odot, odsold, OElig, oelig, ofcir, Ofr, ofr, ogon, Ograve, ograve, ogt, ohbar, ohm, oint, olarr, olcir, olcross, oline, olt, Omacr, omacr, Omega, omega, Omicron, omicron, omid, ominus, Oopf, oopf, opar, OpenCurlyDoubleQuote, OpenCurlyQuote, operp, oplus, orarr, Or, or, ord, order, orderof, ordf, ordm, origof, oror, orslope, orv, oS, Oscr, oscr, Oslash, oslash, osol, Otilde, otilde, otimesas, Otimes, otimes, Ouml, ouml, ovbar, OverBar, OverBrace, OverBracket, OverParenthesis, para, parallel, par, parsim, parsl, part, PartialD, Pcy, pcy, percnt, period, permil, perp, pertenk, Pfr, pfr, Phi, phi, phiv, phmmat, phone, Pi, pi, pitchfork, piv, planck, planckh, plankv, plusacir, plusb, pluscir, plus, plusdo, plusdu, pluse, PlusMinus, plusmn, plussim, plustwo, pm, Poincareplane, pointint, popf, Popf, pound, prap, Pr, pr, prcue, precapprox, prec, preccurlyeq, Precedes, PrecedesEqual, PrecedesSlantEqual, PrecedesTilde, preceq, precnapprox, precneqq, precnsim, pre, prE, precsim, prime, Prime, primes, prnap, prnE, prnsim, prod, Product, profalar, profline, profsurf, prop, Proportional, Proportion, propto, prsim, prurel, Pscr, pscr, Psi, psi, puncsp, Qfr, qfr, qint, qopf, Qopf, qprime, Qscr, qscr, quaternions, quatint, quest, questeq, quot, QUOT, rAarr, race, Racute, racute, radic, raemptyv, rang, Rang, rangd, range, rangle, raquo, rarrap, rarrb, rarrbfs, rarrc, rarr, Rarr, rArr, rarrfs, rarrhk, rarrlp, rarrpl, rarrsim, Rarrtl, rarrtl, rarrw, ratail, rAtail, ratio, rationals, rbarr, rBarr, RBarr, rbbrk, rbrace, rbrack, rbrke, rbrksld, rbrkslu, Rcaron, rcaron, Rcedil, rcedil, rceil, rcub, Rcy, rcy, rdca, rdldhar, rdquo, rdquor, rdsh, real, realine, realpart, reals, Re, rect, reg, REG, ReverseElement, ReverseEquilibrium, ReverseUpEquilibrium, rfisht, rfloor, rfr, Rfr, rHar, rhard, rharu, rharul, Rho, rho, rhov, RightAngleBracket, RightArrowBar, rightarrow, RightArrow, Rightarrow, RightArrowLeftArrow, rightarrowtail, RightCeiling, RightDoubleBracket, RightDownTeeVector, RightDownVectorBar, RightDownVector, RightFloor, rightharpoondown, rightharpoonup, rightleftarrows, rightleftharpoons, rightrightarrows, rightsquigarrow, RightTeeArrow, RightTee, RightTeeVector, rightthreetimes, RightTriangleBar, RightTriangle, RightTriangleEqual, RightUpDownVector, RightUpTeeVector, RightUpVectorBar, RightUpVector, RightVectorBar, RightVector, ring, risingdotseq, rlarr, rlhar, rlm, rmoustache, rmoust, rnmid, roang, roarr, robrk, ropar, ropf, Ropf, roplus, rotimes, RoundImplies, rpar, rpargt, rppolint, rrarr, Rrightarrow, rsaquo, rscr, Rscr, rsh, Rsh, rsqb, rsquo, rsquor, rthree, rtimes, rtri, rtrie, rtrif, rtriltri, RuleDelayed, ruluhar, rx, Sacute, sacute, sbquo, scap, Scaron, scaron, Sc, sc, sccue, sce, scE, Scedil, scedil, Scirc, scirc, scnap, scnE, scnsim, scpolint, scsim, Scy, scy, sdotb, sdot, sdote, searhk, searr, seArr, searrow, sect, semi, seswar, setminus, setmn, sext, Sfr, sfr, sfrown, sharp, SHCHcy, shchcy, SHcy, shcy, ShortDownArrow, ShortLeftArrow, shortmid, shortparallel, ShortRightArrow, ShortUpArrow, shy, Sigma, sigma, sigmaf, sigmav, sim, simdot, sime, simeq, simg, simgE, siml, simlE, simne, simplus, simrarr, slarr, SmallCircle, smallsetminus, smashp, smeparsl, smid, smile, smt, smte, smtes, SOFTcy, softcy, solbar, solb, sol, Sopf, sopf, spades, spadesuit, spar, sqcap, sqcaps, sqcup, sqcups, Sqrt, sqsub, sqsube, sqsubset, sqsubseteq, sqsup, sqsupe, sqsupset, sqsupseteq, square, Square, SquareIntersection, SquareSubset, SquareSubsetEqual, SquareSuperset, SquareSupersetEqual, SquareUnion, squarf, squ, squf, srarr, Sscr, sscr, ssetmn, ssmile, sstarf, Star, star, starf, straightepsilon, straightphi, strns, sub, Sub, subdot, subE, sube, subedot, submult, subnE, subne, subplus, subrarr, subset, Subset, subseteq, subseteqq, SubsetEqual, subsetneq, subsetneqq, subsim, subsub, subsup, succapprox, succ, succcurlyeq, Succeeds, SucceedsEqual, SucceedsSlantEqual, SucceedsTilde, succeq, succnapprox, succneqq, succnsim, succsim, SuchThat, sum, Sum, sung, sup1, sup2, sup3, sup, Sup, supdot, supdsub, supE, supe, supedot, Superset, SupersetEqual, suphsol, suphsub, suplarr, supmult, supnE, supne, supplus, supset, Supset, supseteq, supseteqq, supsetneq, supsetneqq, supsim, supsub, supsup, swarhk, swarr, swArr, swarrow, swnwar, szlig, Tab, target, Tau, tau, tbrk, Tcaron, tcaron, Tcedil, tcedil, Tcy, tcy, tdot, telrec, Tfr, tfr, there4, therefore, Therefore, Theta, theta, thetasym, thetav, thickapprox, thicksim, ThickSpace, ThinSpace, thinsp, thkap, thksim, THORN, thorn, tilde, Tilde, TildeEqual, TildeFullEqual, TildeTilde, timesbar, timesb, times, timesd, tint, toea, topbot, topcir, top, Topf, topf, topfork, tosa, tprime, trade, TRADE, triangle, triangledown, triangleleft, trianglelefteq, triangleq, triangleright, trianglerighteq, tridot, trie, triminus, TripleDot, triplus, trisb, tritime, trpezium, Tscr, tscr, TScy, tscy, TSHcy, tshcy, Tstrok, tstrok, twixt, twoheadleftarrow, twoheadrightarrow, Uacute, uacute, uarr, Uarr, uArr, Uarrocir, Ubrcy, ubrcy, Ubreve, ubreve, Ucirc, ucirc, Ucy, ucy, udarr, Udblac, udblac, udhar, ufisht, Ufr, ufr, Ugrave, ugrave, uHar, uharl, uharr, uhblk, ulcorn, ulcorner, ulcrop, ultri, Umacr, umacr, uml, UnderBar, UnderBrace, UnderBracket, UnderParenthesis, Union, UnionPlus, Uogon, uogon, Uopf, uopf, UpArrowBar, uparrow, UpArrow, Uparrow, UpArrowDownArrow, updownarrow, UpDownArrow, Updownarrow, UpEquilibrium, upharpoonleft, upharpoonright, uplus, UpperLeftArrow, UpperRightArrow, upsi, Upsi, upsih, Upsilon, upsilon, UpTeeArrow, UpTee, upuparrows, urcorn, urcorner, urcrop, Uring, uring, urtri, Uscr, uscr, utdot, Utilde, utilde, utri, utrif, uuarr, Uuml, uuml, uwangle, vangrt, varepsilon, varkappa, varnothing, varphi, varpi, varpropto, varr, vArr, varrho, varsigma, varsubsetneq, varsubsetneqq, varsupsetneq, varsupsetneqq, vartheta, vartriangleleft, vartriangleright, vBar, Vbar, vBarv, Vcy, vcy, vdash, vDash, Vdash, VDash, Vdashl, veebar, vee, Vee, veeeq, vellip, verbar, Verbar, vert, Vert, VerticalBar, VerticalLine, VerticalSeparator, VerticalTilde, VeryThinSpace, Vfr, vfr, vltri, vnsub, vnsup, Vopf, vopf, vprop, vrtri, Vscr, vscr, vsubnE, vsubne, vsupnE, vsupne, Vvdash, vzigzag, Wcirc, wcirc, wedbar, wedge, Wedge, wedgeq, weierp, Wfr, wfr, Wopf, wopf, wp, wr, wreath, Wscr, wscr, xcap, xcirc, xcup, xdtri, Xfr, xfr, xharr, xhArr, Xi, xi, xlarr, xlArr, xmap, xnis, xodot, Xopf, xopf, xoplus, xotime, xrarr, xrArr, Xscr, xscr, xsqcup, xuplus, xutri, xvee, xwedge, Yacute, yacute, YAcy, yacy, Ycirc, ycirc, Ycy, ycy, yen, Yfr, yfr, YIcy, yicy, Yopf, yopf, Yscr, yscr, YUcy, yucy, yuml, Yuml, Zacute, zacute, Zcaron, zcaron, Zcy, zcy, Zdot, zdot, zeetrf, ZeroWidthSpace, Zeta, zeta, zfr, Zfr, ZHcy, zhcy, zigrarr, zopf, Zopf, Zscr, zscr, zwj, zwnj, default */
/***/ (function(module) {

module.exports = {"Aacute":"Á","aacute":"á","Abreve":"Ă","abreve":"ă","ac":"∾","acd":"∿","acE":"∾̳","Acirc":"Â","acirc":"â","acute":"´","Acy":"А","acy":"а","AElig":"Æ","aelig":"æ","af":"⁡","Afr":"𝔄","afr":"𝔞","Agrave":"À","agrave":"à","alefsym":"ℵ","aleph":"ℵ","Alpha":"Α","alpha":"α","Amacr":"Ā","amacr":"ā","amalg":"⨿","amp":"&","AMP":"&","andand":"⩕","And":"⩓","and":"∧","andd":"⩜","andslope":"⩘","andv":"⩚","ang":"∠","ange":"⦤","angle":"∠","angmsdaa":"⦨","angmsdab":"⦩","angmsdac":"⦪","angmsdad":"⦫","angmsdae":"⦬","angmsdaf":"⦭","angmsdag":"⦮","angmsdah":"⦯","angmsd":"∡","angrt":"∟","angrtvb":"⊾","angrtvbd":"⦝","angsph":"∢","angst":"Å","angzarr":"⍼","Aogon":"Ą","aogon":"ą","Aopf":"𝔸","aopf":"𝕒","apacir":"⩯","ap":"≈","apE":"⩰","ape":"≊","apid":"≋","apos":"'","ApplyFunction":"⁡","approx":"≈","approxeq":"≊","Aring":"Å","aring":"å","Ascr":"𝒜","ascr":"𝒶","Assign":"≔","ast":"*","asymp":"≈","asympeq":"≍","Atilde":"Ã","atilde":"ã","Auml":"Ä","auml":"ä","awconint":"∳","awint":"⨑","backcong":"≌","backepsilon":"϶","backprime":"‵","backsim":"∽","backsimeq":"⋍","Backslash":"∖","Barv":"⫧","barvee":"⊽","barwed":"⌅","Barwed":"⌆","barwedge":"⌅","bbrk":"⎵","bbrktbrk":"⎶","bcong":"≌","Bcy":"Б","bcy":"б","bdquo":"„","becaus":"∵","because":"∵","Because":"∵","bemptyv":"⦰","bepsi":"϶","bernou":"ℬ","Bernoullis":"ℬ","Beta":"Β","beta":"β","beth":"ℶ","between":"≬","Bfr":"𝔅","bfr":"𝔟","bigcap":"⋂","bigcirc":"◯","bigcup":"⋃","bigodot":"⨀","bigoplus":"⨁","bigotimes":"⨂","bigsqcup":"⨆","bigstar":"★","bigtriangledown":"▽","bigtriangleup":"△","biguplus":"⨄","bigvee":"⋁","bigwedge":"⋀","bkarow":"⤍","blacklozenge":"⧫","blacksquare":"▪","blacktriangle":"▴","blacktriangledown":"▾","blacktriangleleft":"◂","blacktriangleright":"▸","blank":"␣","blk12":"▒","blk14":"░","blk34":"▓","block":"█","bne":"=⃥","bnequiv":"≡⃥","bNot":"⫭","bnot":"⌐","Bopf":"𝔹","bopf":"𝕓","bot":"⊥","bottom":"⊥","bowtie":"⋈","boxbox":"⧉","boxdl":"┐","boxdL":"╕","boxDl":"╖","boxDL":"╗","boxdr":"┌","boxdR":"╒","boxDr":"╓","boxDR":"╔","boxh":"─","boxH":"═","boxhd":"┬","boxHd":"╤","boxhD":"╥","boxHD":"╦","boxhu":"┴","boxHu":"╧","boxhU":"╨","boxHU":"╩","boxminus":"⊟","boxplus":"⊞","boxtimes":"⊠","boxul":"┘","boxuL":"╛","boxUl":"╜","boxUL":"╝","boxur":"└","boxuR":"╘","boxUr":"╙","boxUR":"╚","boxv":"│","boxV":"║","boxvh":"┼","boxvH":"╪","boxVh":"╫","boxVH":"╬","boxvl":"┤","boxvL":"╡","boxVl":"╢","boxVL":"╣","boxvr":"├","boxvR":"╞","boxVr":"╟","boxVR":"╠","bprime":"‵","breve":"˘","Breve":"˘","brvbar":"¦","bscr":"𝒷","Bscr":"ℬ","bsemi":"⁏","bsim":"∽","bsime":"⋍","bsolb":"⧅","bsol":"\\","bsolhsub":"⟈","bull":"•","bullet":"•","bump":"≎","bumpE":"⪮","bumpe":"≏","Bumpeq":"≎","bumpeq":"≏","Cacute":"Ć","cacute":"ć","capand":"⩄","capbrcup":"⩉","capcap":"⩋","cap":"∩","Cap":"⋒","capcup":"⩇","capdot":"⩀","CapitalDifferentialD":"ⅅ","caps":"∩︀","caret":"⁁","caron":"ˇ","Cayleys":"ℭ","ccaps":"⩍","Ccaron":"Č","ccaron":"č","Ccedil":"Ç","ccedil":"ç","Ccirc":"Ĉ","ccirc":"ĉ","Cconint":"∰","ccups":"⩌","ccupssm":"⩐","Cdot":"Ċ","cdot":"ċ","cedil":"¸","Cedilla":"¸","cemptyv":"⦲","cent":"¢","centerdot":"·","CenterDot":"·","cfr":"𝔠","Cfr":"ℭ","CHcy":"Ч","chcy":"ч","check":"✓","checkmark":"✓","Chi":"Χ","chi":"χ","circ":"ˆ","circeq":"≗","circlearrowleft":"↺","circlearrowright":"↻","circledast":"⊛","circledcirc":"⊚","circleddash":"⊝","CircleDot":"⊙","circledR":"®","circledS":"Ⓢ","CircleMinus":"⊖","CirclePlus":"⊕","CircleTimes":"⊗","cir":"○","cirE":"⧃","cire":"≗","cirfnint":"⨐","cirmid":"⫯","cirscir":"⧂","ClockwiseContourIntegral":"∲","CloseCurlyDoubleQuote":"”","CloseCurlyQuote":"’","clubs":"♣","clubsuit":"♣","colon":":","Colon":"∷","Colone":"⩴","colone":"≔","coloneq":"≔","comma":",","commat":"@","comp":"∁","compfn":"∘","complement":"∁","complexes":"ℂ","cong":"≅","congdot":"⩭","Congruent":"≡","conint":"∮","Conint":"∯","ContourIntegral":"∮","copf":"𝕔","Copf":"ℂ","coprod":"∐","Coproduct":"∐","copy":"©","COPY":"©","copysr":"℗","CounterClockwiseContourIntegral":"∳","crarr":"↵","cross":"✗","Cross":"⨯","Cscr":"𝒞","cscr":"𝒸","csub":"⫏","csube":"⫑","csup":"⫐","csupe":"⫒","ctdot":"⋯","cudarrl":"⤸","cudarrr":"⤵","cuepr":"⋞","cuesc":"⋟","cularr":"↶","cularrp":"⤽","cupbrcap":"⩈","cupcap":"⩆","CupCap":"≍","cup":"∪","Cup":"⋓","cupcup":"⩊","cupdot":"⊍","cupor":"⩅","cups":"∪︀","curarr":"↷","curarrm":"⤼","curlyeqprec":"⋞","curlyeqsucc":"⋟","curlyvee":"⋎","curlywedge":"⋏","curren":"¤","curvearrowleft":"↶","curvearrowright":"↷","cuvee":"⋎","cuwed":"⋏","cwconint":"∲","cwint":"∱","cylcty":"⌭","dagger":"†","Dagger":"‡","daleth":"ℸ","darr":"↓","Darr":"↡","dArr":"⇓","dash":"‐","Dashv":"⫤","dashv":"⊣","dbkarow":"⤏","dblac":"˝","Dcaron":"Ď","dcaron":"ď","Dcy":"Д","dcy":"д","ddagger":"‡","ddarr":"⇊","DD":"ⅅ","dd":"ⅆ","DDotrahd":"⤑","ddotseq":"⩷","deg":"°","Del":"∇","Delta":"Δ","delta":"δ","demptyv":"⦱","dfisht":"⥿","Dfr":"𝔇","dfr":"𝔡","dHar":"⥥","dharl":"⇃","dharr":"⇂","DiacriticalAcute":"´","DiacriticalDot":"˙","DiacriticalDoubleAcute":"˝","DiacriticalGrave":"`","DiacriticalTilde":"˜","diam":"⋄","diamond":"⋄","Diamond":"⋄","diamondsuit":"♦","diams":"♦","die":"¨","DifferentialD":"ⅆ","digamma":"ϝ","disin":"⋲","div":"÷","divide":"÷","divideontimes":"⋇","divonx":"⋇","DJcy":"Ђ","djcy":"ђ","dlcorn":"⌞","dlcrop":"⌍","dollar":"$","Dopf":"𝔻","dopf":"𝕕","Dot":"¨","dot":"˙","DotDot":"⃜","doteq":"≐","doteqdot":"≑","DotEqual":"≐","dotminus":"∸","dotplus":"∔","dotsquare":"⊡","doublebarwedge":"⌆","DoubleContourIntegral":"∯","DoubleDot":"¨","DoubleDownArrow":"⇓","DoubleLeftArrow":"⇐","DoubleLeftRightArrow":"⇔","DoubleLeftTee":"⫤","DoubleLongLeftArrow":"⟸","DoubleLongLeftRightArrow":"⟺","DoubleLongRightArrow":"⟹","DoubleRightArrow":"⇒","DoubleRightTee":"⊨","DoubleUpArrow":"⇑","DoubleUpDownArrow":"⇕","DoubleVerticalBar":"∥","DownArrowBar":"⤓","downarrow":"↓","DownArrow":"↓","Downarrow":"⇓","DownArrowUpArrow":"⇵","DownBreve":"̑","downdownarrows":"⇊","downharpoonleft":"⇃","downharpoonright":"⇂","DownLeftRightVector":"⥐","DownLeftTeeVector":"⥞","DownLeftVectorBar":"⥖","DownLeftVector":"↽","DownRightTeeVector":"⥟","DownRightVectorBar":"⥗","DownRightVector":"⇁","DownTeeArrow":"↧","DownTee":"⊤","drbkarow":"⤐","drcorn":"⌟","drcrop":"⌌","Dscr":"𝒟","dscr":"𝒹","DScy":"Ѕ","dscy":"ѕ","dsol":"⧶","Dstrok":"Đ","dstrok":"đ","dtdot":"⋱","dtri":"▿","dtrif":"▾","duarr":"⇵","duhar":"⥯","dwangle":"⦦","DZcy":"Џ","dzcy":"џ","dzigrarr":"⟿","Eacute":"É","eacute":"é","easter":"⩮","Ecaron":"Ě","ecaron":"ě","Ecirc":"Ê","ecirc":"ê","ecir":"≖","ecolon":"≕","Ecy":"Э","ecy":"э","eDDot":"⩷","Edot":"Ė","edot":"ė","eDot":"≑","ee":"ⅇ","efDot":"≒","Efr":"𝔈","efr":"𝔢","eg":"⪚","Egrave":"È","egrave":"è","egs":"⪖","egsdot":"⪘","el":"⪙","Element":"∈","elinters":"⏧","ell":"ℓ","els":"⪕","elsdot":"⪗","Emacr":"Ē","emacr":"ē","empty":"∅","emptyset":"∅","EmptySmallSquare":"◻","emptyv":"∅","EmptyVerySmallSquare":"▫","emsp13":" ","emsp14":" ","emsp":" ","ENG":"Ŋ","eng":"ŋ","ensp":" ","Eogon":"Ę","eogon":"ę","Eopf":"𝔼","eopf":"𝕖","epar":"⋕","eparsl":"⧣","eplus":"⩱","epsi":"ε","Epsilon":"Ε","epsilon":"ε","epsiv":"ϵ","eqcirc":"≖","eqcolon":"≕","eqsim":"≂","eqslantgtr":"⪖","eqslantless":"⪕","Equal":"⩵","equals":"=","EqualTilde":"≂","equest":"≟","Equilibrium":"⇌","equiv":"≡","equivDD":"⩸","eqvparsl":"⧥","erarr":"⥱","erDot":"≓","escr":"ℯ","Escr":"ℰ","esdot":"≐","Esim":"⩳","esim":"≂","Eta":"Η","eta":"η","ETH":"Ð","eth":"ð","Euml":"Ë","euml":"ë","euro":"€","excl":"!","exist":"∃","Exists":"∃","expectation":"ℰ","exponentiale":"ⅇ","ExponentialE":"ⅇ","fallingdotseq":"≒","Fcy":"Ф","fcy":"ф","female":"♀","ffilig":"ﬃ","fflig":"ﬀ","ffllig":"ﬄ","Ffr":"𝔉","ffr":"𝔣","filig":"ﬁ","FilledSmallSquare":"◼","FilledVerySmallSquare":"▪","fjlig":"fj","flat":"♭","fllig":"ﬂ","fltns":"▱","fnof":"ƒ","Fopf":"𝔽","fopf":"𝕗","forall":"∀","ForAll":"∀","fork":"⋔","forkv":"⫙","Fouriertrf":"ℱ","fpartint":"⨍","frac12":"½","frac13":"⅓","frac14":"¼","frac15":"⅕","frac16":"⅙","frac18":"⅛","frac23":"⅔","frac25":"⅖","frac34":"¾","frac35":"⅗","frac38":"⅜","frac45":"⅘","frac56":"⅚","frac58":"⅝","frac78":"⅞","frasl":"⁄","frown":"⌢","fscr":"𝒻","Fscr":"ℱ","gacute":"ǵ","Gamma":"Γ","gamma":"γ","Gammad":"Ϝ","gammad":"ϝ","gap":"⪆","Gbreve":"Ğ","gbreve":"ğ","Gcedil":"Ģ","Gcirc":"Ĝ","gcirc":"ĝ","Gcy":"Г","gcy":"г","Gdot":"Ġ","gdot":"ġ","ge":"≥","gE":"≧","gEl":"⪌","gel":"⋛","geq":"≥","geqq":"≧","geqslant":"⩾","gescc":"⪩","ges":"⩾","gesdot":"⪀","gesdoto":"⪂","gesdotol":"⪄","gesl":"⋛︀","gesles":"⪔","Gfr":"𝔊","gfr":"𝔤","gg":"≫","Gg":"⋙","ggg":"⋙","gimel":"ℷ","GJcy":"Ѓ","gjcy":"ѓ","gla":"⪥","gl":"≷","glE":"⪒","glj":"⪤","gnap":"⪊","gnapprox":"⪊","gne":"⪈","gnE":"≩","gneq":"⪈","gneqq":"≩","gnsim":"⋧","Gopf":"𝔾","gopf":"𝕘","grave":"`","GreaterEqual":"≥","GreaterEqualLess":"⋛","GreaterFullEqual":"≧","GreaterGreater":"⪢","GreaterLess":"≷","GreaterSlantEqual":"⩾","GreaterTilde":"≳","Gscr":"𝒢","gscr":"ℊ","gsim":"≳","gsime":"⪎","gsiml":"⪐","gtcc":"⪧","gtcir":"⩺","gt":">","GT":">","Gt":"≫","gtdot":"⋗","gtlPar":"⦕","gtquest":"⩼","gtrapprox":"⪆","gtrarr":"⥸","gtrdot":"⋗","gtreqless":"⋛","gtreqqless":"⪌","gtrless":"≷","gtrsim":"≳","gvertneqq":"≩︀","gvnE":"≩︀","Hacek":"ˇ","hairsp":" ","half":"½","hamilt":"ℋ","HARDcy":"Ъ","hardcy":"ъ","harrcir":"⥈","harr":"↔","hArr":"⇔","harrw":"↭","Hat":"^","hbar":"ℏ","Hcirc":"Ĥ","hcirc":"ĥ","hearts":"♥","heartsuit":"♥","hellip":"…","hercon":"⊹","hfr":"𝔥","Hfr":"ℌ","HilbertSpace":"ℋ","hksearow":"⤥","hkswarow":"⤦","hoarr":"⇿","homtht":"∻","hookleftarrow":"↩","hookrightarrow":"↪","hopf":"𝕙","Hopf":"ℍ","horbar":"―","HorizontalLine":"─","hscr":"𝒽","Hscr":"ℋ","hslash":"ℏ","Hstrok":"Ħ","hstrok":"ħ","HumpDownHump":"≎","HumpEqual":"≏","hybull":"⁃","hyphen":"‐","Iacute":"Í","iacute":"í","ic":"⁣","Icirc":"Î","icirc":"î","Icy":"И","icy":"и","Idot":"İ","IEcy":"Е","iecy":"е","iexcl":"¡","iff":"⇔","ifr":"𝔦","Ifr":"ℑ","Igrave":"Ì","igrave":"ì","ii":"ⅈ","iiiint":"⨌","iiint":"∭","iinfin":"⧜","iiota":"℩","IJlig":"Ĳ","ijlig":"ĳ","Imacr":"Ī","imacr":"ī","image":"ℑ","ImaginaryI":"ⅈ","imagline":"ℐ","imagpart":"ℑ","imath":"ı","Im":"ℑ","imof":"⊷","imped":"Ƶ","Implies":"⇒","incare":"℅","in":"∈","infin":"∞","infintie":"⧝","inodot":"ı","intcal":"⊺","int":"∫","Int":"∬","integers":"ℤ","Integral":"∫","intercal":"⊺","Intersection":"⋂","intlarhk":"⨗","intprod":"⨼","InvisibleComma":"⁣","InvisibleTimes":"⁢","IOcy":"Ё","iocy":"ё","Iogon":"Į","iogon":"į","Iopf":"𝕀","iopf":"𝕚","Iota":"Ι","iota":"ι","iprod":"⨼","iquest":"¿","iscr":"𝒾","Iscr":"ℐ","isin":"∈","isindot":"⋵","isinE":"⋹","isins":"⋴","isinsv":"⋳","isinv":"∈","it":"⁢","Itilde":"Ĩ","itilde":"ĩ","Iukcy":"І","iukcy":"і","Iuml":"Ï","iuml":"ï","Jcirc":"Ĵ","jcirc":"ĵ","Jcy":"Й","jcy":"й","Jfr":"𝔍","jfr":"𝔧","jmath":"ȷ","Jopf":"𝕁","jopf":"𝕛","Jscr":"𝒥","jscr":"𝒿","Jsercy":"Ј","jsercy":"ј","Jukcy":"Є","jukcy":"є","Kappa":"Κ","kappa":"κ","kappav":"ϰ","Kcedil":"Ķ","kcedil":"ķ","Kcy":"К","kcy":"к","Kfr":"𝔎","kfr":"𝔨","kgreen":"ĸ","KHcy":"Х","khcy":"х","KJcy":"Ќ","kjcy":"ќ","Kopf":"𝕂","kopf":"𝕜","Kscr":"𝒦","kscr":"𝓀","lAarr":"⇚","Lacute":"Ĺ","lacute":"ĺ","laemptyv":"⦴","lagran":"ℒ","Lambda":"Λ","lambda":"λ","lang":"⟨","Lang":"⟪","langd":"⦑","langle":"⟨","lap":"⪅","Laplacetrf":"ℒ","laquo":"«","larrb":"⇤","larrbfs":"⤟","larr":"←","Larr":"↞","lArr":"⇐","larrfs":"⤝","larrhk":"↩","larrlp":"↫","larrpl":"⤹","larrsim":"⥳","larrtl":"↢","latail":"⤙","lAtail":"⤛","lat":"⪫","late":"⪭","lates":"⪭︀","lbarr":"⤌","lBarr":"⤎","lbbrk":"❲","lbrace":"{","lbrack":"[","lbrke":"⦋","lbrksld":"⦏","lbrkslu":"⦍","Lcaron":"Ľ","lcaron":"ľ","Lcedil":"Ļ","lcedil":"ļ","lceil":"⌈","lcub":"{","Lcy":"Л","lcy":"л","ldca":"⤶","ldquo":"“","ldquor":"„","ldrdhar":"⥧","ldrushar":"⥋","ldsh":"↲","le":"≤","lE":"≦","LeftAngleBracket":"⟨","LeftArrowBar":"⇤","leftarrow":"←","LeftArrow":"←","Leftarrow":"⇐","LeftArrowRightArrow":"⇆","leftarrowtail":"↢","LeftCeiling":"⌈","LeftDoubleBracket":"⟦","LeftDownTeeVector":"⥡","LeftDownVectorBar":"⥙","LeftDownVector":"⇃","LeftFloor":"⌊","leftharpoondown":"↽","leftharpoonup":"↼","leftleftarrows":"⇇","leftrightarrow":"↔","LeftRightArrow":"↔","Leftrightarrow":"⇔","leftrightarrows":"⇆","leftrightharpoons":"⇋","leftrightsquigarrow":"↭","LeftRightVector":"⥎","LeftTeeArrow":"↤","LeftTee":"⊣","LeftTeeVector":"⥚","leftthreetimes":"⋋","LeftTriangleBar":"⧏","LeftTriangle":"⊲","LeftTriangleEqual":"⊴","LeftUpDownVector":"⥑","LeftUpTeeVector":"⥠","LeftUpVectorBar":"⥘","LeftUpVector":"↿","LeftVectorBar":"⥒","LeftVector":"↼","lEg":"⪋","leg":"⋚","leq":"≤","leqq":"≦","leqslant":"⩽","lescc":"⪨","les":"⩽","lesdot":"⩿","lesdoto":"⪁","lesdotor":"⪃","lesg":"⋚︀","lesges":"⪓","lessapprox":"⪅","lessdot":"⋖","lesseqgtr":"⋚","lesseqqgtr":"⪋","LessEqualGreater":"⋚","LessFullEqual":"≦","LessGreater":"≶","lessgtr":"≶","LessLess":"⪡","lesssim":"≲","LessSlantEqual":"⩽","LessTilde":"≲","lfisht":"⥼","lfloor":"⌊","Lfr":"𝔏","lfr":"𝔩","lg":"≶","lgE":"⪑","lHar":"⥢","lhard":"↽","lharu":"↼","lharul":"⥪","lhblk":"▄","LJcy":"Љ","ljcy":"љ","llarr":"⇇","ll":"≪","Ll":"⋘","llcorner":"⌞","Lleftarrow":"⇚","llhard":"⥫","lltri":"◺","Lmidot":"Ŀ","lmidot":"ŀ","lmoustache":"⎰","lmoust":"⎰","lnap":"⪉","lnapprox":"⪉","lne":"⪇","lnE":"≨","lneq":"⪇","lneqq":"≨","lnsim":"⋦","loang":"⟬","loarr":"⇽","lobrk":"⟦","longleftarrow":"⟵","LongLeftArrow":"⟵","Longleftarrow":"⟸","longleftrightarrow":"⟷","LongLeftRightArrow":"⟷","Longleftrightarrow":"⟺","longmapsto":"⟼","longrightarrow":"⟶","LongRightArrow":"⟶","Longrightarrow":"⟹","looparrowleft":"↫","looparrowright":"↬","lopar":"⦅","Lopf":"𝕃","lopf":"𝕝","loplus":"⨭","lotimes":"⨴","lowast":"∗","lowbar":"_","LowerLeftArrow":"↙","LowerRightArrow":"↘","loz":"◊","lozenge":"◊","lozf":"⧫","lpar":"(","lparlt":"⦓","lrarr":"⇆","lrcorner":"⌟","lrhar":"⇋","lrhard":"⥭","lrm":"‎","lrtri":"⊿","lsaquo":"‹","lscr":"𝓁","Lscr":"ℒ","lsh":"↰","Lsh":"↰","lsim":"≲","lsime":"⪍","lsimg":"⪏","lsqb":"[","lsquo":"‘","lsquor":"‚","Lstrok":"Ł","lstrok":"ł","ltcc":"⪦","ltcir":"⩹","lt":"<","LT":"<","Lt":"≪","ltdot":"⋖","lthree":"⋋","ltimes":"⋉","ltlarr":"⥶","ltquest":"⩻","ltri":"◃","ltrie":"⊴","ltrif":"◂","ltrPar":"⦖","lurdshar":"⥊","luruhar":"⥦","lvertneqq":"≨︀","lvnE":"≨︀","macr":"¯","male":"♂","malt":"✠","maltese":"✠","Map":"⤅","map":"↦","mapsto":"↦","mapstodown":"↧","mapstoleft":"↤","mapstoup":"↥","marker":"▮","mcomma":"⨩","Mcy":"М","mcy":"м","mdash":"—","mDDot":"∺","measuredangle":"∡","MediumSpace":" ","Mellintrf":"ℳ","Mfr":"𝔐","mfr":"𝔪","mho":"℧","micro":"µ","midast":"*","midcir":"⫰","mid":"∣","middot":"·","minusb":"⊟","minus":"−","minusd":"∸","minusdu":"⨪","MinusPlus":"∓","mlcp":"⫛","mldr":"…","mnplus":"∓","models":"⊧","Mopf":"𝕄","mopf":"𝕞","mp":"∓","mscr":"𝓂","Mscr":"ℳ","mstpos":"∾","Mu":"Μ","mu":"μ","multimap":"⊸","mumap":"⊸","nabla":"∇","Nacute":"Ń","nacute":"ń","nang":"∠⃒","nap":"≉","napE":"⩰̸","napid":"≋̸","napos":"ŉ","napprox":"≉","natural":"♮","naturals":"ℕ","natur":"♮","nbsp":" ","nbump":"≎̸","nbumpe":"≏̸","ncap":"⩃","Ncaron":"Ň","ncaron":"ň","Ncedil":"Ņ","ncedil":"ņ","ncong":"≇","ncongdot":"⩭̸","ncup":"⩂","Ncy":"Н","ncy":"н","ndash":"–","nearhk":"⤤","nearr":"↗","neArr":"⇗","nearrow":"↗","ne":"≠","nedot":"≐̸","NegativeMediumSpace":"​","NegativeThickSpace":"​","NegativeThinSpace":"​","NegativeVeryThinSpace":"​","nequiv":"≢","nesear":"⤨","nesim":"≂̸","NestedGreaterGreater":"≫","NestedLessLess":"≪","NewLine":"\n","nexist":"∄","nexists":"∄","Nfr":"𝔑","nfr":"𝔫","ngE":"≧̸","nge":"≱","ngeq":"≱","ngeqq":"≧̸","ngeqslant":"⩾̸","nges":"⩾̸","nGg":"⋙̸","ngsim":"≵","nGt":"≫⃒","ngt":"≯","ngtr":"≯","nGtv":"≫̸","nharr":"↮","nhArr":"⇎","nhpar":"⫲","ni":"∋","nis":"⋼","nisd":"⋺","niv":"∋","NJcy":"Њ","njcy":"њ","nlarr":"↚","nlArr":"⇍","nldr":"‥","nlE":"≦̸","nle":"≰","nleftarrow":"↚","nLeftarrow":"⇍","nleftrightarrow":"↮","nLeftrightarrow":"⇎","nleq":"≰","nleqq":"≦̸","nleqslant":"⩽̸","nles":"⩽̸","nless":"≮","nLl":"⋘̸","nlsim":"≴","nLt":"≪⃒","nlt":"≮","nltri":"⋪","nltrie":"⋬","nLtv":"≪̸","nmid":"∤","NoBreak":"⁠","NonBreakingSpace":" ","nopf":"𝕟","Nopf":"ℕ","Not":"⫬","not":"¬","NotCongruent":"≢","NotCupCap":"≭","NotDoubleVerticalBar":"∦","NotElement":"∉","NotEqual":"≠","NotEqualTilde":"≂̸","NotExists":"∄","NotGreater":"≯","NotGreaterEqual":"≱","NotGreaterFullEqual":"≧̸","NotGreaterGreater":"≫̸","NotGreaterLess":"≹","NotGreaterSlantEqual":"⩾̸","NotGreaterTilde":"≵","NotHumpDownHump":"≎̸","NotHumpEqual":"≏̸","notin":"∉","notindot":"⋵̸","notinE":"⋹̸","notinva":"∉","notinvb":"⋷","notinvc":"⋶","NotLeftTriangleBar":"⧏̸","NotLeftTriangle":"⋪","NotLeftTriangleEqual":"⋬","NotLess":"≮","NotLessEqual":"≰","NotLessGreater":"≸","NotLessLess":"≪̸","NotLessSlantEqual":"⩽̸","NotLessTilde":"≴","NotNestedGreaterGreater":"⪢̸","NotNestedLessLess":"⪡̸","notni":"∌","notniva":"∌","notnivb":"⋾","notnivc":"⋽","NotPrecedes":"⊀","NotPrecedesEqual":"⪯̸","NotPrecedesSlantEqual":"⋠","NotReverseElement":"∌","NotRightTriangleBar":"⧐̸","NotRightTriangle":"⋫","NotRightTriangleEqual":"⋭","NotSquareSubset":"⊏̸","NotSquareSubsetEqual":"⋢","NotSquareSuperset":"⊐̸","NotSquareSupersetEqual":"⋣","NotSubset":"⊂⃒","NotSubsetEqual":"⊈","NotSucceeds":"⊁","NotSucceedsEqual":"⪰̸","NotSucceedsSlantEqual":"⋡","NotSucceedsTilde":"≿̸","NotSuperset":"⊃⃒","NotSupersetEqual":"⊉","NotTilde":"≁","NotTildeEqual":"≄","NotTildeFullEqual":"≇","NotTildeTilde":"≉","NotVerticalBar":"∤","nparallel":"∦","npar":"∦","nparsl":"⫽⃥","npart":"∂̸","npolint":"⨔","npr":"⊀","nprcue":"⋠","nprec":"⊀","npreceq":"⪯̸","npre":"⪯̸","nrarrc":"⤳̸","nrarr":"↛","nrArr":"⇏","nrarrw":"↝̸","nrightarrow":"↛","nRightarrow":"⇏","nrtri":"⋫","nrtrie":"⋭","nsc":"⊁","nsccue":"⋡","nsce":"⪰̸","Nscr":"𝒩","nscr":"𝓃","nshortmid":"∤","nshortparallel":"∦","nsim":"≁","nsime":"≄","nsimeq":"≄","nsmid":"∤","nspar":"∦","nsqsube":"⋢","nsqsupe":"⋣","nsub":"⊄","nsubE":"⫅̸","nsube":"⊈","nsubset":"⊂⃒","nsubseteq":"⊈","nsubseteqq":"⫅̸","nsucc":"⊁","nsucceq":"⪰̸","nsup":"⊅","nsupE":"⫆̸","nsupe":"⊉","nsupset":"⊃⃒","nsupseteq":"⊉","nsupseteqq":"⫆̸","ntgl":"≹","Ntilde":"Ñ","ntilde":"ñ","ntlg":"≸","ntriangleleft":"⋪","ntrianglelefteq":"⋬","ntriangleright":"⋫","ntrianglerighteq":"⋭","Nu":"Ν","nu":"ν","num":"#","numero":"№","numsp":" ","nvap":"≍⃒","nvdash":"⊬","nvDash":"⊭","nVdash":"⊮","nVDash":"⊯","nvge":"≥⃒","nvgt":">⃒","nvHarr":"⤄","nvinfin":"⧞","nvlArr":"⤂","nvle":"≤⃒","nvlt":"<⃒","nvltrie":"⊴⃒","nvrArr":"⤃","nvrtrie":"⊵⃒","nvsim":"∼⃒","nwarhk":"⤣","nwarr":"↖","nwArr":"⇖","nwarrow":"↖","nwnear":"⤧","Oacute":"Ó","oacute":"ó","oast":"⊛","Ocirc":"Ô","ocirc":"ô","ocir":"⊚","Ocy":"О","ocy":"о","odash":"⊝","Odblac":"Ő","odblac":"ő","odiv":"⨸","odot":"⊙","odsold":"⦼","OElig":"Œ","oelig":"œ","ofcir":"⦿","Ofr":"𝔒","ofr":"𝔬","ogon":"˛","Ograve":"Ò","ograve":"ò","ogt":"⧁","ohbar":"⦵","ohm":"Ω","oint":"∮","olarr":"↺","olcir":"⦾","olcross":"⦻","oline":"‾","olt":"⧀","Omacr":"Ō","omacr":"ō","Omega":"Ω","omega":"ω","Omicron":"Ο","omicron":"ο","omid":"⦶","ominus":"⊖","Oopf":"𝕆","oopf":"𝕠","opar":"⦷","OpenCurlyDoubleQuote":"“","OpenCurlyQuote":"‘","operp":"⦹","oplus":"⊕","orarr":"↻","Or":"⩔","or":"∨","ord":"⩝","order":"ℴ","orderof":"ℴ","ordf":"ª","ordm":"º","origof":"⊶","oror":"⩖","orslope":"⩗","orv":"⩛","oS":"Ⓢ","Oscr":"𝒪","oscr":"ℴ","Oslash":"Ø","oslash":"ø","osol":"⊘","Otilde":"Õ","otilde":"õ","otimesas":"⨶","Otimes":"⨷","otimes":"⊗","Ouml":"Ö","ouml":"ö","ovbar":"⌽","OverBar":"‾","OverBrace":"⏞","OverBracket":"⎴","OverParenthesis":"⏜","para":"¶","parallel":"∥","par":"∥","parsim":"⫳","parsl":"⫽","part":"∂","PartialD":"∂","Pcy":"П","pcy":"п","percnt":"%","period":".","permil":"‰","perp":"⊥","pertenk":"‱","Pfr":"𝔓","pfr":"𝔭","Phi":"Φ","phi":"φ","phiv":"ϕ","phmmat":"ℳ","phone":"☎","Pi":"Π","pi":"π","pitchfork":"⋔","piv":"ϖ","planck":"ℏ","planckh":"ℎ","plankv":"ℏ","plusacir":"⨣","plusb":"⊞","pluscir":"⨢","plus":"+","plusdo":"∔","plusdu":"⨥","pluse":"⩲","PlusMinus":"±","plusmn":"±","plussim":"⨦","plustwo":"⨧","pm":"±","Poincareplane":"ℌ","pointint":"⨕","popf":"𝕡","Popf":"ℙ","pound":"£","prap":"⪷","Pr":"⪻","pr":"≺","prcue":"≼","precapprox":"⪷","prec":"≺","preccurlyeq":"≼","Precedes":"≺","PrecedesEqual":"⪯","PrecedesSlantEqual":"≼","PrecedesTilde":"≾","preceq":"⪯","precnapprox":"⪹","precneqq":"⪵","precnsim":"⋨","pre":"⪯","prE":"⪳","precsim":"≾","prime":"′","Prime":"″","primes":"ℙ","prnap":"⪹","prnE":"⪵","prnsim":"⋨","prod":"∏","Product":"∏","profalar":"⌮","profline":"⌒","profsurf":"⌓","prop":"∝","Proportional":"∝","Proportion":"∷","propto":"∝","prsim":"≾","prurel":"⊰","Pscr":"𝒫","pscr":"𝓅","Psi":"Ψ","psi":"ψ","puncsp":" ","Qfr":"𝔔","qfr":"𝔮","qint":"⨌","qopf":"𝕢","Qopf":"ℚ","qprime":"⁗","Qscr":"𝒬","qscr":"𝓆","quaternions":"ℍ","quatint":"⨖","quest":"?","questeq":"≟","quot":"\"","QUOT":"\"","rAarr":"⇛","race":"∽̱","Racute":"Ŕ","racute":"ŕ","radic":"√","raemptyv":"⦳","rang":"⟩","Rang":"⟫","rangd":"⦒","range":"⦥","rangle":"⟩","raquo":"»","rarrap":"⥵","rarrb":"⇥","rarrbfs":"⤠","rarrc":"⤳","rarr":"→","Rarr":"↠","rArr":"⇒","rarrfs":"⤞","rarrhk":"↪","rarrlp":"↬","rarrpl":"⥅","rarrsim":"⥴","Rarrtl":"⤖","rarrtl":"↣","rarrw":"↝","ratail":"⤚","rAtail":"⤜","ratio":"∶","rationals":"ℚ","rbarr":"⤍","rBarr":"⤏","RBarr":"⤐","rbbrk":"❳","rbrace":"}","rbrack":"]","rbrke":"⦌","rbrksld":"⦎","rbrkslu":"⦐","Rcaron":"Ř","rcaron":"ř","Rcedil":"Ŗ","rcedil":"ŗ","rceil":"⌉","rcub":"}","Rcy":"Р","rcy":"р","rdca":"⤷","rdldhar":"⥩","rdquo":"”","rdquor":"”","rdsh":"↳","real":"ℜ","realine":"ℛ","realpart":"ℜ","reals":"ℝ","Re":"ℜ","rect":"▭","reg":"®","REG":"®","ReverseElement":"∋","ReverseEquilibrium":"⇋","ReverseUpEquilibrium":"⥯","rfisht":"⥽","rfloor":"⌋","rfr":"𝔯","Rfr":"ℜ","rHar":"⥤","rhard":"⇁","rharu":"⇀","rharul":"⥬","Rho":"Ρ","rho":"ρ","rhov":"ϱ","RightAngleBracket":"⟩","RightArrowBar":"⇥","rightarrow":"→","RightArrow":"→","Rightarrow":"⇒","RightArrowLeftArrow":"⇄","rightarrowtail":"↣","RightCeiling":"⌉","RightDoubleBracket":"⟧","RightDownTeeVector":"⥝","RightDownVectorBar":"⥕","RightDownVector":"⇂","RightFloor":"⌋","rightharpoondown":"⇁","rightharpoonup":"⇀","rightleftarrows":"⇄","rightleftharpoons":"⇌","rightrightarrows":"⇉","rightsquigarrow":"↝","RightTeeArrow":"↦","RightTee":"⊢","RightTeeVector":"⥛","rightthreetimes":"⋌","RightTriangleBar":"⧐","RightTriangle":"⊳","RightTriangleEqual":"⊵","RightUpDownVector":"⥏","RightUpTeeVector":"⥜","RightUpVectorBar":"⥔","RightUpVector":"↾","RightVectorBar":"⥓","RightVector":"⇀","ring":"˚","risingdotseq":"≓","rlarr":"⇄","rlhar":"⇌","rlm":"‏","rmoustache":"⎱","rmoust":"⎱","rnmid":"⫮","roang":"⟭","roarr":"⇾","robrk":"⟧","ropar":"⦆","ropf":"𝕣","Ropf":"ℝ","roplus":"⨮","rotimes":"⨵","RoundImplies":"⥰","rpar":")","rpargt":"⦔","rppolint":"⨒","rrarr":"⇉","Rrightarrow":"⇛","rsaquo":"›","rscr":"𝓇","Rscr":"ℛ","rsh":"↱","Rsh":"↱","rsqb":"]","rsquo":"’","rsquor":"’","rthree":"⋌","rtimes":"⋊","rtri":"▹","rtrie":"⊵","rtrif":"▸","rtriltri":"⧎","RuleDelayed":"⧴","ruluhar":"⥨","rx":"℞","Sacute":"Ś","sacute":"ś","sbquo":"‚","scap":"⪸","Scaron":"Š","scaron":"š","Sc":"⪼","sc":"≻","sccue":"≽","sce":"⪰","scE":"⪴","Scedil":"Ş","scedil":"ş","Scirc":"Ŝ","scirc":"ŝ","scnap":"⪺","scnE":"⪶","scnsim":"⋩","scpolint":"⨓","scsim":"≿","Scy":"С","scy":"с","sdotb":"⊡","sdot":"⋅","sdote":"⩦","searhk":"⤥","searr":"↘","seArr":"⇘","searrow":"↘","sect":"§","semi":";","seswar":"⤩","setminus":"∖","setmn":"∖","sext":"✶","Sfr":"𝔖","sfr":"𝔰","sfrown":"⌢","sharp":"♯","SHCHcy":"Щ","shchcy":"щ","SHcy":"Ш","shcy":"ш","ShortDownArrow":"↓","ShortLeftArrow":"←","shortmid":"∣","shortparallel":"∥","ShortRightArrow":"→","ShortUpArrow":"↑","shy":"­","Sigma":"Σ","sigma":"σ","sigmaf":"ς","sigmav":"ς","sim":"∼","simdot":"⩪","sime":"≃","simeq":"≃","simg":"⪞","simgE":"⪠","siml":"⪝","simlE":"⪟","simne":"≆","simplus":"⨤","simrarr":"⥲","slarr":"←","SmallCircle":"∘","smallsetminus":"∖","smashp":"⨳","smeparsl":"⧤","smid":"∣","smile":"⌣","smt":"⪪","smte":"⪬","smtes":"⪬︀","SOFTcy":"Ь","softcy":"ь","solbar":"⌿","solb":"⧄","sol":"/","Sopf":"𝕊","sopf":"𝕤","spades":"♠","spadesuit":"♠","spar":"∥","sqcap":"⊓","sqcaps":"⊓︀","sqcup":"⊔","sqcups":"⊔︀","Sqrt":"√","sqsub":"⊏","sqsube":"⊑","sqsubset":"⊏","sqsubseteq":"⊑","sqsup":"⊐","sqsupe":"⊒","sqsupset":"⊐","sqsupseteq":"⊒","square":"□","Square":"□","SquareIntersection":"⊓","SquareSubset":"⊏","SquareSubsetEqual":"⊑","SquareSuperset":"⊐","SquareSupersetEqual":"⊒","SquareUnion":"⊔","squarf":"▪","squ":"□","squf":"▪","srarr":"→","Sscr":"𝒮","sscr":"𝓈","ssetmn":"∖","ssmile":"⌣","sstarf":"⋆","Star":"⋆","star":"☆","starf":"★","straightepsilon":"ϵ","straightphi":"ϕ","strns":"¯","sub":"⊂","Sub":"⋐","subdot":"⪽","subE":"⫅","sube":"⊆","subedot":"⫃","submult":"⫁","subnE":"⫋","subne":"⊊","subplus":"⪿","subrarr":"⥹","subset":"⊂","Subset":"⋐","subseteq":"⊆","subseteqq":"⫅","SubsetEqual":"⊆","subsetneq":"⊊","subsetneqq":"⫋","subsim":"⫇","subsub":"⫕","subsup":"⫓","succapprox":"⪸","succ":"≻","succcurlyeq":"≽","Succeeds":"≻","SucceedsEqual":"⪰","SucceedsSlantEqual":"≽","SucceedsTilde":"≿","succeq":"⪰","succnapprox":"⪺","succneqq":"⪶","succnsim":"⋩","succsim":"≿","SuchThat":"∋","sum":"∑","Sum":"∑","sung":"♪","sup1":"¹","sup2":"²","sup3":"³","sup":"⊃","Sup":"⋑","supdot":"⪾","supdsub":"⫘","supE":"⫆","supe":"⊇","supedot":"⫄","Superset":"⊃","SupersetEqual":"⊇","suphsol":"⟉","suphsub":"⫗","suplarr":"⥻","supmult":"⫂","supnE":"⫌","supne":"⊋","supplus":"⫀","supset":"⊃","Supset":"⋑","supseteq":"⊇","supseteqq":"⫆","supsetneq":"⊋","supsetneqq":"⫌","supsim":"⫈","supsub":"⫔","supsup":"⫖","swarhk":"⤦","swarr":"↙","swArr":"⇙","swarrow":"↙","swnwar":"⤪","szlig":"ß","Tab":"\t","target":"⌖","Tau":"Τ","tau":"τ","tbrk":"⎴","Tcaron":"Ť","tcaron":"ť","Tcedil":"Ţ","tcedil":"ţ","Tcy":"Т","tcy":"т","tdot":"⃛","telrec":"⌕","Tfr":"𝔗","tfr":"𝔱","there4":"∴","therefore":"∴","Therefore":"∴","Theta":"Θ","theta":"θ","thetasym":"ϑ","thetav":"ϑ","thickapprox":"≈","thicksim":"∼","ThickSpace":"  ","ThinSpace":" ","thinsp":" ","thkap":"≈","thksim":"∼","THORN":"Þ","thorn":"þ","tilde":"˜","Tilde":"∼","TildeEqual":"≃","TildeFullEqual":"≅","TildeTilde":"≈","timesbar":"⨱","timesb":"⊠","times":"×","timesd":"⨰","tint":"∭","toea":"⤨","topbot":"⌶","topcir":"⫱","top":"⊤","Topf":"𝕋","topf":"𝕥","topfork":"⫚","tosa":"⤩","tprime":"‴","trade":"™","TRADE":"™","triangle":"▵","triangledown":"▿","triangleleft":"◃","trianglelefteq":"⊴","triangleq":"≜","triangleright":"▹","trianglerighteq":"⊵","tridot":"◬","trie":"≜","triminus":"⨺","TripleDot":"⃛","triplus":"⨹","trisb":"⧍","tritime":"⨻","trpezium":"⏢","Tscr":"𝒯","tscr":"𝓉","TScy":"Ц","tscy":"ц","TSHcy":"Ћ","tshcy":"ћ","Tstrok":"Ŧ","tstrok":"ŧ","twixt":"≬","twoheadleftarrow":"↞","twoheadrightarrow":"↠","Uacute":"Ú","uacute":"ú","uarr":"↑","Uarr":"↟","uArr":"⇑","Uarrocir":"⥉","Ubrcy":"Ў","ubrcy":"ў","Ubreve":"Ŭ","ubreve":"ŭ","Ucirc":"Û","ucirc":"û","Ucy":"У","ucy":"у","udarr":"⇅","Udblac":"Ű","udblac":"ű","udhar":"⥮","ufisht":"⥾","Ufr":"𝔘","ufr":"𝔲","Ugrave":"Ù","ugrave":"ù","uHar":"⥣","uharl":"↿","uharr":"↾","uhblk":"▀","ulcorn":"⌜","ulcorner":"⌜","ulcrop":"⌏","ultri":"◸","Umacr":"Ū","umacr":"ū","uml":"¨","UnderBar":"_","UnderBrace":"⏟","UnderBracket":"⎵","UnderParenthesis":"⏝","Union":"⋃","UnionPlus":"⊎","Uogon":"Ų","uogon":"ų","Uopf":"𝕌","uopf":"𝕦","UpArrowBar":"⤒","uparrow":"↑","UpArrow":"↑","Uparrow":"⇑","UpArrowDownArrow":"⇅","updownarrow":"↕","UpDownArrow":"↕","Updownarrow":"⇕","UpEquilibrium":"⥮","upharpoonleft":"↿","upharpoonright":"↾","uplus":"⊎","UpperLeftArrow":"↖","UpperRightArrow":"↗","upsi":"υ","Upsi":"ϒ","upsih":"ϒ","Upsilon":"Υ","upsilon":"υ","UpTeeArrow":"↥","UpTee":"⊥","upuparrows":"⇈","urcorn":"⌝","urcorner":"⌝","urcrop":"⌎","Uring":"Ů","uring":"ů","urtri":"◹","Uscr":"𝒰","uscr":"𝓊","utdot":"⋰","Utilde":"Ũ","utilde":"ũ","utri":"▵","utrif":"▴","uuarr":"⇈","Uuml":"Ü","uuml":"ü","uwangle":"⦧","vangrt":"⦜","varepsilon":"ϵ","varkappa":"ϰ","varnothing":"∅","varphi":"ϕ","varpi":"ϖ","varpropto":"∝","varr":"↕","vArr":"⇕","varrho":"ϱ","varsigma":"ς","varsubsetneq":"⊊︀","varsubsetneqq":"⫋︀","varsupsetneq":"⊋︀","varsupsetneqq":"⫌︀","vartheta":"ϑ","vartriangleleft":"⊲","vartriangleright":"⊳","vBar":"⫨","Vbar":"⫫","vBarv":"⫩","Vcy":"В","vcy":"в","vdash":"⊢","vDash":"⊨","Vdash":"⊩","VDash":"⊫","Vdashl":"⫦","veebar":"⊻","vee":"∨","Vee":"⋁","veeeq":"≚","vellip":"⋮","verbar":"|","Verbar":"‖","vert":"|","Vert":"‖","VerticalBar":"∣","VerticalLine":"|","VerticalSeparator":"❘","VerticalTilde":"≀","VeryThinSpace":" ","Vfr":"𝔙","vfr":"𝔳","vltri":"⊲","vnsub":"⊂⃒","vnsup":"⊃⃒","Vopf":"𝕍","vopf":"𝕧","vprop":"∝","vrtri":"⊳","Vscr":"𝒱","vscr":"𝓋","vsubnE":"⫋︀","vsubne":"⊊︀","vsupnE":"⫌︀","vsupne":"⊋︀","Vvdash":"⊪","vzigzag":"⦚","Wcirc":"Ŵ","wcirc":"ŵ","wedbar":"⩟","wedge":"∧","Wedge":"⋀","wedgeq":"≙","weierp":"℘","Wfr":"𝔚","wfr":"𝔴","Wopf":"𝕎","wopf":"𝕨","wp":"℘","wr":"≀","wreath":"≀","Wscr":"𝒲","wscr":"𝓌","xcap":"⋂","xcirc":"◯","xcup":"⋃","xdtri":"▽","Xfr":"𝔛","xfr":"𝔵","xharr":"⟷","xhArr":"⟺","Xi":"Ξ","xi":"ξ","xlarr":"⟵","xlArr":"⟸","xmap":"⟼","xnis":"⋻","xodot":"⨀","Xopf":"𝕏","xopf":"𝕩","xoplus":"⨁","xotime":"⨂","xrarr":"⟶","xrArr":"⟹","Xscr":"𝒳","xscr":"𝓍","xsqcup":"⨆","xuplus":"⨄","xutri":"△","xvee":"⋁","xwedge":"⋀","Yacute":"Ý","yacute":"ý","YAcy":"Я","yacy":"я","Ycirc":"Ŷ","ycirc":"ŷ","Ycy":"Ы","ycy":"ы","yen":"¥","Yfr":"𝔜","yfr":"𝔶","YIcy":"Ї","yicy":"ї","Yopf":"𝕐","yopf":"𝕪","Yscr":"𝒴","yscr":"𝓎","YUcy":"Ю","yucy":"ю","yuml":"ÿ","Yuml":"Ÿ","Zacute":"Ź","zacute":"ź","Zcaron":"Ž","zcaron":"ž","Zcy":"З","zcy":"з","Zdot":"Ż","zdot":"ż","zeetrf":"ℨ","ZeroWidthSpace":"​","Zeta":"Ζ","zeta":"ζ","zfr":"𝔷","Zfr":"ℨ","ZHcy":"Ж","zhcy":"ж","zigrarr":"⇝","zopf":"𝕫","Zopf":"ℤ","Zscr":"𝒵","zscr":"𝓏","zwj":"‍","zwnj":"‌"};

/***/ }),

/***/ "8d//":
/*!*************************************************************!*\
  !*** ./node_modules/draft-js/lib/removeTextWithStrategy.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule removeTextWithStrategy
 * @format
 * 
 */



var DraftModifier = __webpack_require__(/*! ./DraftModifier */ "fyOY");

/**
 * For a collapsed selection state, remove text based on the specified strategy.
 * If the selection state is not collapsed, remove the entire selected range.
 */
function removeTextWithStrategy(editorState, strategy, direction) {
  var selection = editorState.getSelection();
  var content = editorState.getCurrentContent();
  var target = selection;
  if (selection.isCollapsed()) {
    if (direction === 'forward') {
      if (editorState.isSelectionAtEndOfContent()) {
        return content;
      }
    } else if (editorState.isSelectionAtStartOfContent()) {
      return content;
    }

    target = strategy(editorState);
    if (target === selection) {
      return content;
    }
  }
  return DraftModifier.removeRange(content, target, direction);
}

module.exports = removeTextWithStrategy;

/***/ }),

/***/ "8m37":
/*!********************************************!*\
  !*** ./node_modules/mdi-react/BellIcon.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var BellIcon = function BellIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M21,19V20H3V19L5,17V11C5,7.9 7.03,5.17 10,4.29C10,4.19 10,4.1 10,4C10,2.9 10.9,2 12,2C13.1,2 14,2.9 14,4C14,4.1 14,4.19 14,4.29C16.97,5.17 19,7.9 19,11V17L21,19M14,21C14,22.1 13.1,23 12,23C10.9,23 10,22.1 10,21' })
  );
};

module.exports = BellIcon;


/***/ }),

/***/ "8mBD":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/pt.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var pt = moment.defineLocale('pt', {
    months : 'janeiro_fevereiro_março_abril_maio_junho_julho_agosto_setembro_outubro_novembro_dezembro'.split('_'),
    monthsShort : 'jan_fev_mar_abr_mai_jun_jul_ago_set_out_nov_dez'.split('_'),
    weekdays : 'Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado'.split('_'),
    weekdaysShort : 'Dom_Seg_Ter_Qua_Qui_Sex_Sáb'.split('_'),
    weekdaysMin : 'Do_2ª_3ª_4ª_5ª_6ª_Sá'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D [de] MMMM [de] YYYY',
        LLL : 'D [de] MMMM [de] YYYY HH:mm',
        LLLL : 'dddd, D [de] MMMM [de] YYYY HH:mm'
    },
    calendar : {
        sameDay: '[Hoje às] LT',
        nextDay: '[Amanhã às] LT',
        nextWeek: 'dddd [às] LT',
        lastDay: '[Ontem às] LT',
        lastWeek: function () {
            return (this.day() === 0 || this.day() === 6) ?
                '[Último] dddd [às] LT' : // Saturday + Sunday
                '[Última] dddd [às] LT'; // Monday - Friday
        },
        sameElse: 'L'
    },
    relativeTime : {
        future : 'em %s',
        past : 'há %s',
        s : 'segundos',
        ss : '%d segundos',
        m : 'um minuto',
        mm : '%d minutos',
        h : 'uma hora',
        hh : '%d horas',
        d : 'um dia',
        dd : '%d dias',
        M : 'um mês',
        MM : '%d meses',
        y : 'um ano',
        yy : '%d anos'
    },
    dayOfMonthOrdinalParse: /\d{1,2}º/,
    ordinal : '%dº',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return pt;

})));


/***/ }),

/***/ "8n10":
/*!****************************************************************!*\
  !*** ./node_modules/@phosphor/datagrid/lib/graphicscontext.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/**
 * A thin caching wrapper around a 2D canvas rendering context.
 *
 * #### Notes
 * This class is mostly a transparent wrapper around a canvas rendering
 * context which improves performance when writing context state.
 *
 * For best performance, avoid reading state from the `gc`. Writes are
 * cached based on the previously written value.
 *
 * Unless otherwise specified, the API and semantics of this class are
 * identical to the builtin 2D canvas rendering context:
 * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D
 *
 * The wrapped canvas context should not be manipulated externally
 * until the wrapping `GraphicsContext` object is disposed.
 */
var GraphicsContext = (function () {
    /**
     * Create a new graphics context object.
     *
     * @param context - The 2D canvas rendering context to wrap.
     */
    function GraphicsContext(context) {
        this._disposed = false;
        this._context = context;
        this._state = Private.State.create(context);
    }
    GraphicsContext.prototype.dispose = function () {
        // Bail if the gc is already disposed.
        if (this._disposed) {
            return;
        }
        // Mark the gc as disposed.
        this._disposed = true;
        // Pop any unrestored saves.
        while (this._state.next) {
            this._state = this._state.next;
            this._context.restore();
        }
    };
    Object.defineProperty(GraphicsContext.prototype, "isDisposed", {
        get: function () {
            return !this._disposed;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GraphicsContext.prototype, "fillStyle", {
        get: function () {
            return this._context.fillStyle;
        },
        set: function (value) {
            if (this._state.fillStyle !== value) {
                this._state.fillStyle = value;
                this._context.fillStyle = value;
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GraphicsContext.prototype, "strokeStyle", {
        get: function () {
            return this._context.strokeStyle;
        },
        set: function (value) {
            if (this._state.strokeStyle !== value) {
                this._state.strokeStyle = value;
                this._context.strokeStyle = value;
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GraphicsContext.prototype, "font", {
        get: function () {
            return this._context.font;
        },
        set: function (value) {
            if (this._state.font !== value) {
                this._state.font = value;
                this._context.font = value;
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GraphicsContext.prototype, "textAlign", {
        get: function () {
            return this._context.textAlign;
        },
        set: function (value) {
            if (this._state.textAlign !== value) {
                this._state.textAlign = value;
                this._context.textAlign = value;
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GraphicsContext.prototype, "textBaseline", {
        get: function () {
            return this._context.textBaseline;
        },
        set: function (value) {
            if (this._state.textBaseline !== value) {
                this._state.textBaseline = value;
                this._context.textBaseline = value;
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GraphicsContext.prototype, "lineCap", {
        get: function () {
            return this._context.lineCap;
        },
        set: function (value) {
            if (this._state.lineCap !== value) {
                this._state.lineCap = value;
                this._context.lineCap = value;
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GraphicsContext.prototype, "lineDashOffset", {
        get: function () {
            return this._context.lineDashOffset;
        },
        set: function (value) {
            if (this._state.lineDashOffset !== value) {
                this._state.lineDashOffset = value;
                this._context.lineDashOffset = value;
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GraphicsContext.prototype, "lineJoin", {
        get: function () {
            return this._context.lineJoin;
        },
        set: function (value) {
            if (this._state.lineJoin !== value) {
                this._state.lineJoin = value;
                this._context.lineJoin = value;
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GraphicsContext.prototype, "lineWidth", {
        get: function () {
            return this._context.lineWidth;
        },
        set: function (value) {
            if (this._state.lineWidth !== value) {
                this._state.lineWidth = value;
                this._context.lineWidth = value;
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GraphicsContext.prototype, "miterLimit", {
        get: function () {
            return this._context.miterLimit;
        },
        set: function (value) {
            if (this._state.miterLimit !== value) {
                this._state.miterLimit = value;
                this._context.miterLimit = value;
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GraphicsContext.prototype, "shadowBlur", {
        get: function () {
            return this._context.shadowBlur;
        },
        set: function (value) {
            if (this._state.shadowBlur !== value) {
                this._state.shadowBlur = value;
                this._context.shadowBlur = value;
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GraphicsContext.prototype, "shadowColor", {
        get: function () {
            return this._context.shadowColor;
        },
        set: function (value) {
            if (this._state.shadowColor !== value) {
                this._state.shadowColor = value;
                this._context.shadowColor = value;
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GraphicsContext.prototype, "shadowOffsetX", {
        get: function () {
            return this._context.shadowOffsetX;
        },
        set: function (value) {
            if (this._state.shadowOffsetX !== value) {
                this._state.shadowOffsetX = value;
                this._context.shadowOffsetX = value;
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GraphicsContext.prototype, "shadowOffsetY", {
        get: function () {
            return this._context.shadowOffsetY;
        },
        set: function (value) {
            if (this._state.shadowOffsetY !== value) {
                this._state.shadowOffsetY = value;
                this._context.shadowOffsetY = value;
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GraphicsContext.prototype, "imageSmoothingEnabled", {
        get: function () {
            return this._context.imageSmoothingEnabled;
        },
        set: function (value) {
            if (this._state.imageSmoothingEnabled !== value) {
                this._state.imageSmoothingEnabled = value;
                this._context.imageSmoothingEnabled = value;
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GraphicsContext.prototype, "globalAlpha", {
        get: function () {
            return this._context.globalAlpha;
        },
        set: function (value) {
            if (this._state.globalAlpha !== value) {
                this._state.globalAlpha = value;
                this._context.globalAlpha = value;
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GraphicsContext.prototype, "globalCompositeOperation", {
        get: function () {
            return this._context.globalCompositeOperation;
        },
        set: function (value) {
            if (this._state.globalCompositeOperation !== value) {
                this._state.globalCompositeOperation = value;
                this._context.globalCompositeOperation = value;
            }
        },
        enumerable: true,
        configurable: true
    });
    GraphicsContext.prototype.getLineDash = function () {
        return this._context.getLineDash();
    };
    GraphicsContext.prototype.setLineDash = function (segments) {
        this._context.setLineDash(segments);
    };
    GraphicsContext.prototype.rotate = function (angle) {
        this._context.rotate(angle);
    };
    GraphicsContext.prototype.scale = function (x, y) {
        this._context.scale(x, y);
    };
    GraphicsContext.prototype.transform = function (m11, m12, m21, m22, dx, dy) {
        this._context.transform(m11, m12, m21, m22, dx, dy);
    };
    GraphicsContext.prototype.translate = function (x, y) {
        this._context.translate(x, y);
    };
    GraphicsContext.prototype.setTransform = function (m11, m12, m21, m22, dx, dy) {
        this._context.setTransform(m11, m12, m21, m22, dx, dy);
    };
    GraphicsContext.prototype.save = function () {
        // Clone an push the current state to the stack.
        this._state = Private.State.push(this._state);
        // Save the wrapped context state.
        this._context.save();
    };
    GraphicsContext.prototype.restore = function () {
        // Bail if there is no state to restore.
        if (!this._state.next) {
            return;
        }
        // Pop the saved state from the stack.
        this._state = Private.State.pop(this._state);
        // Restore the wrapped context state.
        this._context.restore();
    };
    GraphicsContext.prototype.beginPath = function () {
        return this._context.beginPath();
    };
    GraphicsContext.prototype.closePath = function () {
        this._context.closePath();
    };
    GraphicsContext.prototype.isPointInPath = function (x, y, fillRule) {
        var result;
        if (arguments.length === 2) {
            result = this._context.isPointInPath(x, y);
        }
        else {
            result = this._context.isPointInPath(x, y, fillRule);
        }
        return result;
    };
    GraphicsContext.prototype.arc = function (x, y, radius, startAngle, endAngle, anticlockwise) {
        if (arguments.length === 5) {
            this._context.arc(x, y, radius, startAngle, endAngle);
        }
        else {
            this._context.arc(x, y, radius, startAngle, endAngle, anticlockwise);
        }
    };
    GraphicsContext.prototype.arcTo = function (x1, y1, x2, y2, radius) {
        this._context.arcTo(x1, y1, x2, y2, radius);
    };
    GraphicsContext.prototype.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {
        this._context.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
    };
    GraphicsContext.prototype.ellipse = function (x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise) {
        if (arguments.length === 7) {
            this._context.ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle);
        }
        else {
            this._context.ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise);
        }
    };
    GraphicsContext.prototype.lineTo = function (x, y) {
        this._context.lineTo(x, y);
    };
    GraphicsContext.prototype.moveTo = function (x, y) {
        this._context.moveTo(x, y);
    };
    GraphicsContext.prototype.quadraticCurveTo = function (cpx, cpy, x, y) {
        this._context.quadraticCurveTo(cpx, cpy, x, y);
    };
    GraphicsContext.prototype.rect = function (x, y, w, h) {
        this._context.rect(x, y, w, h);
    };
    GraphicsContext.prototype.clip = function (fillRule) {
        if (arguments.length === 0) {
            this._context.clip();
        }
        else {
            this._context.clip(fillRule);
        }
    };
    GraphicsContext.prototype.fill = function (fillRule) {
        if (arguments.length === 0) {
            this._context.fill();
        }
        else {
            this._context.fill(fillRule);
        }
    };
    GraphicsContext.prototype.stroke = function () {
        this._context.stroke();
    };
    GraphicsContext.prototype.clearRect = function (x, y, w, h) {
        return this._context.clearRect(x, y, w, h);
    };
    GraphicsContext.prototype.fillRect = function (x, y, w, h) {
        this._context.fillRect(x, y, w, h);
    };
    GraphicsContext.prototype.fillText = function (text, x, y, maxWidth) {
        if (arguments.length === 3) {
            this._context.fillText(text, x, y);
        }
        else {
            this._context.fillText(text, x, y, maxWidth);
        }
    };
    GraphicsContext.prototype.strokeRect = function (x, y, w, h) {
        this._context.strokeRect(x, y, w, h);
    };
    GraphicsContext.prototype.strokeText = function (text, x, y, maxWidth) {
        if (arguments.length === 3) {
            this._context.strokeText(text, x, y);
        }
        else {
            this._context.strokeText(text, x, y, maxWidth);
        }
    };
    GraphicsContext.prototype.measureText = function (text) {
        return this._context.measureText(text);
    };
    GraphicsContext.prototype.createLinearGradient = function (x0, y0, x1, y1) {
        return this._context.createLinearGradient(x0, y0, x1, y1);
    };
    GraphicsContext.prototype.createRadialGradient = function (x0, y0, r0, x1, y1, r1) {
        return this._context.createRadialGradient(x0, y0, r0, x1, y1, r1);
    };
    GraphicsContext.prototype.createPattern = function (image, repetition) {
        return this._context.createPattern(image, repetition);
    };
    GraphicsContext.prototype.createImageData = function () {
        return this._context.createImageData.apply(this._context, arguments);
    };
    GraphicsContext.prototype.getImageData = function (sx, sy, sw, sh) {
        return this._context.getImageData(sx, sy, sw, sh);
    };
    GraphicsContext.prototype.putImageData = function () {
        this._context.putImageData.apply(this._context, arguments);
    };
    GraphicsContext.prototype.drawImage = function () {
        this._context.drawImage.apply(this._context, arguments);
    };
    GraphicsContext.prototype.drawFocusIfNeeded = function (element) {
        this._context.drawFocusIfNeeded(element);
    };
    return GraphicsContext;
}());
exports.GraphicsContext = GraphicsContext;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * The index of next valid pool object.
     */
    var pi = -1;
    /**
     * A state object allocation pool.
     */
    var pool = [];
    /**
     * An object which holds the state for a gc.
     */
    var State = (function () {
        function State() {
        }
        /**
         * Create a gc state object from a 2D canvas context.
         */
        State.create = function (context) {
            var state = pi < 0 ? new State() : pool[pi--];
            state.next = null;
            state.fillStyle = context.fillStyle;
            state.font = context.font;
            state.globalAlpha = context.globalAlpha;
            state.globalCompositeOperation = context.globalCompositeOperation;
            state.imageSmoothingEnabled = context.imageSmoothingEnabled;
            state.lineCap = context.lineCap;
            state.lineDashOffset = context.lineDashOffset;
            state.lineJoin = context.lineJoin;
            state.lineWidth = context.lineWidth;
            state.miterLimit = context.miterLimit;
            state.shadowBlur = context.shadowBlur;
            state.shadowColor = context.shadowColor;
            state.shadowOffsetX = context.shadowOffsetX;
            state.shadowOffsetY = context.shadowOffsetY;
            state.strokeStyle = context.strokeStyle;
            state.textAlign = context.textAlign;
            state.textBaseline = context.textBaseline;
            return state;
        };
        /**
         * Clone an existing gc state object and add it to the state stack.
         */
        State.push = function (other) {
            var state = pi < 0 ? new State() : pool[pi--];
            state.next = other;
            state.fillStyle = other.fillStyle;
            state.font = other.font;
            state.globalAlpha = other.globalAlpha;
            state.globalCompositeOperation = other.globalCompositeOperation;
            state.imageSmoothingEnabled = other.imageSmoothingEnabled;
            state.lineCap = other.lineCap;
            state.lineDashOffset = other.lineDashOffset;
            state.lineJoin = other.lineJoin;
            state.lineWidth = other.lineWidth;
            state.miterLimit = other.miterLimit;
            state.shadowBlur = other.shadowBlur;
            state.shadowColor = other.shadowColor;
            state.shadowOffsetX = other.shadowOffsetX;
            state.shadowOffsetY = other.shadowOffsetY;
            state.strokeStyle = other.strokeStyle;
            state.textAlign = other.textAlign;
            state.textBaseline = other.textBaseline;
            return state;
        };
        /**
         * Pop the next state object and return the current to the pool
         */
        State.pop = function (state) {
            state.fillStyle = '';
            state.strokeStyle = '';
            pool[++pi] = state;
            return state.next;
        };
        return State;
    }());
    Private.State = State;
})(Private || (Private = {}));


/***/ }),

/***/ "8n7X":
/*!****************************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils/lib/commandlinker.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
/**
 * The command data attribute added to nodes that are connected.
 */
const COMMAND_ATTR = 'commandlinker-command';
/**
 * The args data attribute added to nodes that are connected.
 */
const ARGS_ATTR = 'commandlinker-args';
/**
 * A static class that provides helper methods to generate clickable nodes that
 * execute registered commands with pre-populated arguments.
 */
class CommandLinker {
    /**
     * Instantiate a new command linker.
     */
    constructor(options) {
        this._isDisposed = false;
        this._commands = options.commands;
        document.body.addEventListener('click', this);
    }
    /**
     * Test whether the linker is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources held by the linker.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        document.body.removeEventListener('click', this);
    }
    /**
     * Connect a command/argument pair to a given node so that when it is clicked,
     * the command will execute.
     *
     * @param node - The node being connected.
     *
     * @param command - The command ID to execute upon click.
     *
     * @param args - The arguments with which to invoke the command.
     *
     * @returns The same node that was passed in, after it has been connected.
     *
     * #### Notes
     * Only `click` events will execute the command on a connected node. So, there
     * are two considerations that are relevant:
     * 1. If a node is connected, the default click action will be prevented.
     * 2. The `HTMLElement` passed in should be clickable.
     */
    connectNode(node, command, args) {
        node.setAttribute(`data-${COMMAND_ATTR}`, command);
        if (args !== void 0) {
            node.setAttribute(`data-${ARGS_ATTR}`, JSON.stringify(args));
        }
        return node;
    }
    /**
     * Disconnect a node that has been connected to execute a command on click.
     *
     * @param node - The node being disconnected.
     *
     * @returns The same node that was passed in, after it has been disconnected.
     *
     * #### Notes
     * This method is safe to call multiple times and is safe to call on nodes
     * that were never connected.
     *
     * This method can be called on rendered virtual DOM nodes that were populated
     * using the `populateVNodeDataset` method in order to disconnect them from
     * executing their command/argument pair.
     */
    disconnectNode(node) {
        node.removeAttribute(`data-${COMMAND_ATTR}`);
        node.removeAttribute(`data-${ARGS_ATTR}`);
        return node;
    }
    /**
     * Handle the DOM events for the command linker helper class.
     *
     * @param event - The DOM event sent to the class.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the panel's DOM node. It should
     * not be called directly by user code.
     */
    handleEvent(event) {
        switch (event.type) {
            case 'click':
                this._evtClick(event);
                break;
            default:
                return;
        }
    }
    /**
     * Populate the `dataset` attribute within the collection of attributes used
     * to instantiate a virtual DOM node with the values necessary for its
     * rendered DOM node to respond to clicks by executing a command/argument
     * pair.
     *
     * @param command - The command ID to execute upon click.
     *
     * @param args - The arguments with which to invoke the command.
     *
     * @returns A `dataset` collection for use within virtual node attributes.
     *
     * #### Notes
     * The return value can be used on its own as the value for the `dataset`
     * attribute of a virtual element, or it can be added to an existing `dataset`
     * as in the example below.
     *
     * #### Example
     * ```typescript
     * let command = 'some:command-id';
     * let args = { alpha: 'beta' };
     * let anchor = h.a({
     *   className: 'some-class',
     *   dataset: {
     *     foo: '1',
     *     bar: '2',
     *     ../...linker.populateVNodeDataset(command, args)
     *   }
     * }, 'some text');
     * ```
     */
    populateVNodeDataset(command, args) {
        let dataset;
        if (args !== void 0) {
            dataset = { [ARGS_ATTR]: JSON.stringify(args), [COMMAND_ATTR]: command };
        }
        else {
            dataset = { [COMMAND_ATTR]: command };
        }
        return dataset;
    }
    /**
     * The global click handler that deploys commands/argument pairs that are
     * attached to the node being clicked.
     */
    _evtClick(event) {
        let target = event.target;
        while (target && target.parentElement) {
            if (target.hasAttribute(`data-${COMMAND_ATTR}`)) {
                event.preventDefault();
                let command = target.getAttribute(`data-${COMMAND_ATTR}`);
                if (!command) {
                    return;
                }
                let argsValue = target.getAttribute(`data-${ARGS_ATTR}`);
                let args = coreutils_1.JSONExt.emptyObject;
                if (argsValue) {
                    args = JSON.parse(argsValue);
                }
                this._commands.execute(command, args);
                return;
            }
            target = target.parentElement;
        }
    }
}
exports.CommandLinker = CommandLinker;


/***/ }),

/***/ "8oxB":
/*!*****************************************!*\
  !*** ./node_modules/process/browser.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {

// shim for using process in browser
var process = module.exports = {};

// cached from whatever global is present so that test runners that stub it
// don't break things.  But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals.  It's inside a
// function because try/catches deoptimize in certain engines.

var cachedSetTimeout;
var cachedClearTimeout;

function defaultSetTimout() {
    throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
    throw new Error('clearTimeout has not been defined');
}
(function () {
    try {
        if (typeof setTimeout === 'function') {
            cachedSetTimeout = setTimeout;
        } else {
            cachedSetTimeout = defaultSetTimout;
        }
    } catch (e) {
        cachedSetTimeout = defaultSetTimout;
    }
    try {
        if (typeof clearTimeout === 'function') {
            cachedClearTimeout = clearTimeout;
        } else {
            cachedClearTimeout = defaultClearTimeout;
        }
    } catch (e) {
        cachedClearTimeout = defaultClearTimeout;
    }
} ())
function runTimeout(fun) {
    if (cachedSetTimeout === setTimeout) {
        //normal enviroments in sane situations
        return setTimeout(fun, 0);
    }
    // if setTimeout wasn't available but was latter defined
    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
        cachedSetTimeout = setTimeout;
        return setTimeout(fun, 0);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedSetTimeout(fun, 0);
    } catch(e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
            return cachedSetTimeout.call(null, fun, 0);
        } catch(e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
            return cachedSetTimeout.call(this, fun, 0);
        }
    }


}
function runClearTimeout(marker) {
    if (cachedClearTimeout === clearTimeout) {
        //normal enviroments in sane situations
        return clearTimeout(marker);
    }
    // if clearTimeout wasn't available but was latter defined
    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
        cachedClearTimeout = clearTimeout;
        return clearTimeout(marker);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedClearTimeout(marker);
    } catch (e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
            return cachedClearTimeout.call(null, marker);
        } catch (e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
            // Some versions of I.E. have different rules for clearTimeout vs setTimeout
            return cachedClearTimeout.call(this, marker);
        }
    }



}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;

function cleanUpNextTick() {
    if (!draining || !currentQueue) {
        return;
    }
    draining = false;
    if (currentQueue.length) {
        queue = currentQueue.concat(queue);
    } else {
        queueIndex = -1;
    }
    if (queue.length) {
        drainQueue();
    }
}

function drainQueue() {
    if (draining) {
        return;
    }
    var timeout = runTimeout(cleanUpNextTick);
    draining = true;

    var len = queue.length;
    while(len) {
        currentQueue = queue;
        queue = [];
        while (++queueIndex < len) {
            if (currentQueue) {
                currentQueue[queueIndex].run();
            }
        }
        queueIndex = -1;
        len = queue.length;
    }
    currentQueue = null;
    draining = false;
    runClearTimeout(timeout);
}

process.nextTick = function (fun) {
    var args = new Array(arguments.length - 1);
    if (arguments.length > 1) {
        for (var i = 1; i < arguments.length; i++) {
            args[i - 1] = arguments[i];
        }
    }
    queue.push(new Item(fun, args));
    if (queue.length === 1 && !draining) {
        runTimeout(drainQueue);
    }
};

// v8 likes predictible objects
function Item(fun, array) {
    this.fun = fun;
    this.array = array;
}
Item.prototype.run = function () {
    this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};

function noop() {}

process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;

process.listeners = function (name) { return [] }

process.binding = function (name) {
    throw new Error('process.binding is not supported');
};

process.cwd = function () { return '/' };
process.chdir = function (dir) {
    throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };


/***/ }),

/***/ "8sNi":
/*!************************************************!*\
  !*** ./node_modules/ajv/lib/compile/_rules.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//all requires must be explicit because browserify won't work with dynamic requires
module.exports = {
  '$ref': __webpack_require__(/*! ../dotjs/ref */ "bvhh"),
  allOf: __webpack_require__(/*! ../dotjs/allOf */ "6gcW"),
  anyOf: __webpack_require__(/*! ../dotjs/anyOf */ "YPXT"),
  const: __webpack_require__(/*! ../dotjs/const */ "AwJw"),
  contains: __webpack_require__(/*! ../dotjs/contains */ "XPXQ"),
  dependencies: __webpack_require__(/*! ../dotjs/dependencies */ "uSCx"),
  'enum': __webpack_require__(/*! ../dotjs/enum */ "6MIY"),
  format: __webpack_require__(/*! ../dotjs/format */ "AK1u"),
  items: __webpack_require__(/*! ../dotjs/items */ "eY4P"),
  maximum: __webpack_require__(/*! ../dotjs/_limit */ "v43d"),
  minimum: __webpack_require__(/*! ../dotjs/_limit */ "v43d"),
  maxItems: __webpack_require__(/*! ../dotjs/_limitItems */ "2jsQ"),
  minItems: __webpack_require__(/*! ../dotjs/_limitItems */ "2jsQ"),
  maxLength: __webpack_require__(/*! ../dotjs/_limitLength */ "mQYA"),
  minLength: __webpack_require__(/*! ../dotjs/_limitLength */ "mQYA"),
  maxProperties: __webpack_require__(/*! ../dotjs/_limitProperties */ "d+r/"),
  minProperties: __webpack_require__(/*! ../dotjs/_limitProperties */ "d+r/"),
  multipleOf: __webpack_require__(/*! ../dotjs/multipleOf */ "qTHO"),
  not: __webpack_require__(/*! ../dotjs/not */ "APWh"),
  oneOf: __webpack_require__(/*! ../dotjs/oneOf */ "TbEC"),
  pattern: __webpack_require__(/*! ../dotjs/pattern */ "cUtX"),
  properties: __webpack_require__(/*! ../dotjs/properties */ "vVvC"),
  propertyNames: __webpack_require__(/*! ../dotjs/propertyNames */ "bWPq"),
  required: __webpack_require__(/*! ../dotjs/required */ "t+aO"),
  uniqueItems: __webpack_require__(/*! ../dotjs/uniqueItems */ "0w4r"),
  validate: __webpack_require__(/*! ../dotjs/validate */ "1QhW")
};


/***/ }),

/***/ "8trw":
/*!********************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/clean_number.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




var isNumeric = __webpack_require__(/*! fast-isnumeric */ "GbLo");

var BADNUM = __webpack_require__(/*! ../constants/numerical */ "6AZA").BADNUM;

// precompile for speed
var JUNK = /^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g;

/**
 * cleanNumber: remove common leading and trailing cruft
 * Always returns either a number or BADNUM.
 */
module.exports = function cleanNumber(v) {
    if(typeof v === 'string') {
        v = v.replace(JUNK, '');
    }

    if(isNumeric(v)) return Number(v);

    return BADNUM;
};


/***/ }),

/***/ "8uQm":
/*!***************************************************!*\
  !*** ./node_modules/draft-js/lib/ContentBlock.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule ContentBlock
 * @format
 * 
 */



function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var CharacterMetadata = __webpack_require__(/*! ./CharacterMetadata */ "lFJn");
var Immutable = __webpack_require__(/*! immutable */ "JPcv");

var findRangesImmutable = __webpack_require__(/*! ./findRangesImmutable */ "Taje");

var List = Immutable.List,
    Map = Immutable.Map,
    OrderedSet = Immutable.OrderedSet,
    Record = Immutable.Record,
    Repeat = Immutable.Repeat;


var EMPTY_SET = OrderedSet();

var defaultRecord = {
  key: '',
  type: 'unstyled',
  text: '',
  characterList: List(),
  depth: 0,
  data: Map()
};

var ContentBlockRecord = Record(defaultRecord);

var decorateCharacterList = function decorateCharacterList(config) {
  if (!config) {
    return config;
  }

  var characterList = config.characterList,
      text = config.text;


  if (text && !characterList) {
    config.characterList = List(Repeat(CharacterMetadata.EMPTY, text.length));
  }

  return config;
};

var ContentBlock = function (_ContentBlockRecord) {
  _inherits(ContentBlock, _ContentBlockRecord);

  function ContentBlock(config) {
    _classCallCheck(this, ContentBlock);

    return _possibleConstructorReturn(this, _ContentBlockRecord.call(this, decorateCharacterList(config)));
  }

  ContentBlock.prototype.getKey = function getKey() {
    return this.get('key');
  };

  ContentBlock.prototype.getType = function getType() {
    return this.get('type');
  };

  ContentBlock.prototype.getText = function getText() {
    return this.get('text');
  };

  ContentBlock.prototype.getCharacterList = function getCharacterList() {
    return this.get('characterList');
  };

  ContentBlock.prototype.getLength = function getLength() {
    return this.getText().length;
  };

  ContentBlock.prototype.getDepth = function getDepth() {
    return this.get('depth');
  };

  ContentBlock.prototype.getData = function getData() {
    return this.get('data');
  };

  ContentBlock.prototype.getInlineStyleAt = function getInlineStyleAt(offset) {
    var character = this.getCharacterList().get(offset);
    return character ? character.getStyle() : EMPTY_SET;
  };

  ContentBlock.prototype.getEntityAt = function getEntityAt(offset) {
    var character = this.getCharacterList().get(offset);
    return character ? character.getEntity() : null;
  };

  /**
   * Execute a callback for every contiguous range of styles within the block.
   */


  ContentBlock.prototype.findStyleRanges = function findStyleRanges(filterFn, callback) {
    findRangesImmutable(this.getCharacterList(), haveEqualStyle, filterFn, callback);
  };

  /**
   * Execute a callback for every contiguous range of entities within the block.
   */


  ContentBlock.prototype.findEntityRanges = function findEntityRanges(filterFn, callback) {
    findRangesImmutable(this.getCharacterList(), haveEqualEntity, filterFn, callback);
  };

  return ContentBlock;
}(ContentBlockRecord);

function haveEqualStyle(charA, charB) {
  return charA.getStyle() === charB.getStyle();
}

function haveEqualEntity(charA, charB) {
  return charA.getEntity() === charB.getEntity();
}

module.exports = ContentBlock;

/***/ }),

/***/ "8v/U":
/*!****************************************!*\
  !*** ./node_modules/minimist/index.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = function (args, opts) {
    if (!opts) opts = {};
    
    var flags = { bools : {}, strings : {}, unknownFn: null };

    if (typeof opts['unknown'] === 'function') {
        flags.unknownFn = opts['unknown'];
    }

    if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
      flags.allBools = true;
    } else {
      [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
          flags.bools[key] = true;
      });
    }
    
    var aliases = {};
    Object.keys(opts.alias || {}).forEach(function (key) {
        aliases[key] = [].concat(opts.alias[key]);
        aliases[key].forEach(function (x) {
            aliases[x] = [key].concat(aliases[key].filter(function (y) {
                return x !== y;
            }));
        });
    });

    [].concat(opts.string).filter(Boolean).forEach(function (key) {
        flags.strings[key] = true;
        if (aliases[key]) {
            flags.strings[aliases[key]] = true;
        }
     });

    var defaults = opts['default'] || {};
    
    var argv = { _ : [] };
    Object.keys(flags.bools).forEach(function (key) {
        setArg(key, defaults[key] === undefined ? false : defaults[key]);
    });
    
    var notFlags = [];

    if (args.indexOf('--') !== -1) {
        notFlags = args.slice(args.indexOf('--')+1);
        args = args.slice(0, args.indexOf('--'));
    }

    function argDefined(key, arg) {
        return (flags.allBools && /^--[^=]+$/.test(arg)) ||
            flags.strings[key] || flags.bools[key] || aliases[key];
    }

    function setArg (key, val, arg) {
        if (arg && flags.unknownFn && !argDefined(key, arg)) {
            if (flags.unknownFn(arg) === false) return;
        }

        var value = !flags.strings[key] && isNumber(val)
            ? Number(val) : val
        ;
        setKey(argv, key.split('.'), value);
        
        (aliases[key] || []).forEach(function (x) {
            setKey(argv, x.split('.'), value);
        });
    }

    function setKey (obj, keys, value) {
        var o = obj;
        keys.slice(0,-1).forEach(function (key) {
            if (o[key] === undefined) o[key] = {};
            o = o[key];
        });

        var key = keys[keys.length - 1];
        if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
            o[key] = value;
        }
        else if (Array.isArray(o[key])) {
            o[key].push(value);
        }
        else {
            o[key] = [ o[key], value ];
        }
    }
    
    function aliasIsBoolean(key) {
      return aliases[key].some(function (x) {
          return flags.bools[x];
      });
    }

    for (var i = 0; i < args.length; i++) {
        var arg = args[i];
        
        if (/^--.+=/.test(arg)) {
            // Using [\s\S] instead of . because js doesn't support the
            // 'dotall' regex modifier. See:
            // http://stackoverflow.com/a/1068308/13216
            var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
            var key = m[1];
            var value = m[2];
            if (flags.bools[key]) {
                value = value !== 'false';
            }
            setArg(key, value, arg);
        }
        else if (/^--no-.+/.test(arg)) {
            var key = arg.match(/^--no-(.+)/)[1];
            setArg(key, false, arg);
        }
        else if (/^--.+/.test(arg)) {
            var key = arg.match(/^--(.+)/)[1];
            var next = args[i + 1];
            if (next !== undefined && !/^-/.test(next)
            && !flags.bools[key]
            && !flags.allBools
            && (aliases[key] ? !aliasIsBoolean(key) : true)) {
                setArg(key, next, arg);
                i++;
            }
            else if (/^(true|false)$/.test(next)) {
                setArg(key, next === 'true', arg);
                i++;
            }
            else {
                setArg(key, flags.strings[key] ? '' : true, arg);
            }
        }
        else if (/^-[^-]+/.test(arg)) {
            var letters = arg.slice(1,-1).split('');
            
            var broken = false;
            for (var j = 0; j < letters.length; j++) {
                var next = arg.slice(j+2);
                
                if (next === '-') {
                    setArg(letters[j], next, arg)
                    continue;
                }
                
                if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
                    setArg(letters[j], next.split('=')[1], arg);
                    broken = true;
                    break;
                }
                
                if (/[A-Za-z]/.test(letters[j])
                && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
                    setArg(letters[j], next, arg);
                    broken = true;
                    break;
                }
                
                if (letters[j+1] && letters[j+1].match(/\W/)) {
                    setArg(letters[j], arg.slice(j+2), arg);
                    broken = true;
                    break;
                }
                else {
                    setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
                }
            }
            
            var key = arg.slice(-1)[0];
            if (!broken && key !== '-') {
                if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
                && !flags.bools[key]
                && (aliases[key] ? !aliasIsBoolean(key) : true)) {
                    setArg(key, args[i+1], arg);
                    i++;
                }
                else if (args[i+1] && /true|false/.test(args[i+1])) {
                    setArg(key, args[i+1] === 'true', arg);
                    i++;
                }
                else {
                    setArg(key, flags.strings[key] ? '' : true, arg);
                }
            }
        }
        else {
            if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
                argv._.push(
                    flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
                );
            }
            if (opts.stopEarly) {
                argv._.push.apply(argv._, args.slice(i + 1));
                break;
            }
        }
    }
    
    Object.keys(defaults).forEach(function (key) {
        if (!hasKey(argv, key.split('.'))) {
            setKey(argv, key.split('.'), defaults[key]);
            
            (aliases[key] || []).forEach(function (x) {
                setKey(argv, x.split('.'), defaults[key]);
            });
        }
    });
    
    if (opts['--']) {
        argv['--'] = new Array();
        notFlags.forEach(function(key) {
            argv['--'].push(key);
        });
    }
    else {
        notFlags.forEach(function(key) {
            argv._.push(key);
        });
    }

    return argv;
};

function hasKey (obj, keys) {
    var o = obj;
    keys.slice(0,-1).forEach(function (key) {
        o = (o[key] || {});
    });

    var key = keys[keys.length - 1];
    return key in o;
}

function isNumber (x) {
    if (typeof x === 'number') return true;
    if (/^0x[0-9a-f]+$/i.test(x)) return true;
    return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
}



/***/ }),

/***/ "8x15":
/*!************************************************************!*\
  !*** ./node_modules/@jupyterlab/notebook/lib/celltools.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
const virtualdom_1 = __webpack_require__(/*! @phosphor/virtualdom */ "Gqu+");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const codeeditor_1 = __webpack_require__(/*! @jupyterlab/codeeditor */ "sLCx");
const observables_1 = __webpack_require__(/*! @jupyterlab/observables */ "V4vH");
/**
 * The class name added to a CellTools instance.
 */
const CELLTOOLS_CLASS = 'jp-CellTools';
/**
 * The class name added to a CellTools tool.
 */
const CHILD_CLASS = 'jp-CellTools-tool';
/**
 * The class name added to a CellTools active cell.
 */
const ACTIVE_CELL_CLASS = 'jp-ActiveCellTool';
/**
 * The class name added to an Editor instance.
 */
const EDITOR_CLASS = 'jp-MetadataEditorTool';
/**
 * The class name added to a KeySelector instance.
 */
const KEYSELECTOR_CLASS = 'jp-KeySelector';
/* tslint:disable */
/**
 * The main menu token.
 */
exports.ICellTools = new coreutils_1.Token('@jupyterlab/notebook:ICellTools');
/**
 * A widget that provides cell metadata tools.
 */
class CellTools extends widgets_1.Widget {
    /**
     * Construct a new CellTools object.
     */
    constructor(options) {
        super();
        this._items = [];
        this.addClass(CELLTOOLS_CLASS);
        this.layout = new widgets_1.PanelLayout();
        this._tracker = options.tracker;
        this._tracker.activeCellChanged.connect(this._onActiveCellChanged, this);
        this._tracker.selectionChanged.connect(this._onSelectionChanged, this);
        this._onActiveCellChanged();
        this._onSelectionChanged();
    }
    /**
     * The active cell widget.
     */
    get activeCell() {
        return this._tracker.activeCell;
    }
    /**
     * The currently selected cells.
     */
    get selectedCells() {
        let selected = [];
        let panel = this._tracker.currentWidget;
        if (!panel) {
            return selected;
        }
        algorithm_1.each(panel.content.widgets, widget => {
            if (panel.content.isSelectedOrActive(widget)) {
                selected.push(widget);
            }
        });
        return selected;
    }
    /**
     * Add a cell tool item.
     */
    addItem(options) {
        let tool = options.tool;
        let rank = 'rank' in options ? options.rank : 100;
        let rankItem = { tool, rank };
        let index = algorithm_1.ArrayExt.upperBound(this._items, rankItem, Private.itemCmp);
        tool.addClass(CHILD_CLASS);
        // Add the tool.
        algorithm_1.ArrayExt.insert(this._items, index, rankItem);
        let layout = this.layout;
        layout.insertWidget(index, tool);
        // Trigger the tool to update its active cell.
        messaging_1.MessageLoop.sendMessage(tool, CellTools.ActiveCellMessage);
    }
    /**
     * Handle the removal of a child
     */
    onChildRemoved(msg) {
        let index = algorithm_1.ArrayExt.findFirstIndex(this._items, item => item.tool === msg.child);
        if (index !== -1) {
            algorithm_1.ArrayExt.removeAt(this._items, index);
        }
    }
    /**
     * Handle a change to the active cell.
     */
    _onActiveCellChanged() {
        if (this._prevActive && !this._prevActive.isDisposed) {
            this._prevActive.metadata.changed.disconnect(this._onMetadataChanged, this);
        }
        let activeCell = this._tracker.activeCell;
        this._prevActive = activeCell ? activeCell.model : null;
        if (activeCell) {
            activeCell.model.metadata.changed.connect(this._onMetadataChanged, this);
        }
        algorithm_1.each(this.children(), widget => {
            messaging_1.MessageLoop.sendMessage(widget, CellTools.ActiveCellMessage);
        });
    }
    /**
     * Handle a change in the selection.
     */
    _onSelectionChanged() {
        algorithm_1.each(this.children(), widget => {
            messaging_1.MessageLoop.sendMessage(widget, CellTools.SelectionMessage);
        });
    }
    /**
     * Handle a change in the metadata.
     */
    _onMetadataChanged(sender, args) {
        let message = new observables_1.ObservableJSON.ChangeMessage(args);
        algorithm_1.each(this.children(), widget => {
            messaging_1.MessageLoop.sendMessage(widget, message);
        });
    }
}
exports.CellTools = CellTools;
/**
 * The namespace for CellTools class statics.
 */
(function (CellTools) {
    /**
     * A singleton conflatable `'activecell-changed'` message.
     */
    // tslint:disable-next-line
    CellTools.ActiveCellMessage = new messaging_1.ConflatableMessage('activecell-changed');
    /**
     * A singleton conflatable `'selection-changed'` message.
     */
    // tslint:disable-next-line
    CellTools.SelectionMessage = new messaging_1.ConflatableMessage('selection-changed');
    /**
     * The base cell tool, meant to be subclassed.
     */
    class Tool extends widgets_1.Widget {
        /**
         * Process a message sent to the widget.
         *
         * @param msg - The message sent to the widget.
         */
        processMessage(msg) {
            super.processMessage(msg);
            switch (msg.type) {
                case 'activecell-changed':
                    this.onActiveCellChanged(msg);
                    break;
                case 'selection-changed':
                    this.onSelectionChanged(msg);
                    break;
                case 'jsonvalue-changed':
                    this.onMetadataChanged(msg);
                    break;
                default:
                    break;
            }
        }
        /**
         * Handle a change to the active cell.
         *
         * #### Notes
         * The default implementation is a no-op.
         */
        onActiveCellChanged(msg) {
            /* no-op */
        }
        /**
         * Handle a change to the selection.
         *
         * #### Notes
         * The default implementation is a no-op.
         */
        onSelectionChanged(msg) {
            /* no-op */
        }
        /**
         * Handle a change to the metadata of the active cell.
         *
         * #### Notes
         * The default implementation is a no-op.
         */
        onMetadataChanged(msg) {
            /* no-op */
        }
    }
    CellTools.Tool = Tool;
    /**
     * A cell tool displaying the active cell contents.
     */
    class ActiveCellTool extends Tool {
        /**
         * Construct a new active cell tool.
         */
        constructor() {
            super();
            this._model = new codeeditor_1.CodeEditor.Model();
            this.addClass(ACTIVE_CELL_CLASS);
            this.addClass('jp-InputArea');
            this.layout = new widgets_1.PanelLayout();
        }
        /**
         * Dispose of the resources used by the tool.
         */
        dispose() {
            if (this._model === null) {
                return;
            }
            this._model.dispose();
            this._model = null;
            super.dispose();
        }
        /**
         * Handle a change to the active cell.
         */
        onActiveCellChanged() {
            let activeCell = this.parent.activeCell;
            let layout = this.layout;
            let count = layout.widgets.length;
            for (let i = 0; i < count; i++) {
                layout.widgets[0].dispose();
            }
            if (this._cellModel && !this._cellModel.isDisposed) {
                this._cellModel.value.changed.disconnect(this._onValueChanged, this);
                this._cellModel.mimeTypeChanged.disconnect(this._onMimeTypeChanged, this);
            }
            if (!activeCell) {
                let cell = new widgets_1.Widget();
                cell.addClass('jp-InputArea-editor');
                cell.addClass('jp-InputArea-editor');
                layout.addWidget(cell);
                this._cellModel = null;
                return;
            }
            let promptNode = activeCell.promptNode
                ? activeCell.promptNode.cloneNode(true)
                : null;
            let prompt = new widgets_1.Widget({ node: promptNode });
            let factory = activeCell.contentFactory.editorFactory;
            let cellModel = (this._cellModel = activeCell.model);
            cellModel.value.changed.connect(this._onValueChanged, this);
            cellModel.mimeTypeChanged.connect(this._onMimeTypeChanged, this);
            this._model.value.text = cellModel.value.text.split('\n')[0];
            this._model.mimeType = cellModel.mimeType;
            let model = this._model;
            let editorWidget = new codeeditor_1.CodeEditorWrapper({ model, factory });
            editorWidget.addClass('jp-InputArea-editor');
            editorWidget.addClass('jp-InputArea-editor');
            editorWidget.editor.setOption('readOnly', true);
            layout.addWidget(prompt);
            layout.addWidget(editorWidget);
        }
        /**
         * Handle a change to the current editor value.
         */
        _onValueChanged() {
            this._model.value.text = this._cellModel.value.text.split('\n')[0];
        }
        /**
         * Handle a change to the current editor mimetype.
         */
        _onMimeTypeChanged() {
            this._model.mimeType = this._cellModel.mimeType;
        }
    }
    CellTools.ActiveCellTool = ActiveCellTool;
    /**
     * A raw metadata editor.
     */
    class MetadataEditorTool extends Tool {
        /**
         * Construct a new raw metadata tool.
         */
        constructor(options) {
            super();
            let editorFactory = options.editorFactory;
            this.addClass(EDITOR_CLASS);
            let layout = (this.layout = new widgets_1.PanelLayout());
            this.editor = new codeeditor_1.JSONEditor({
                editorFactory,
                title: 'Edit Metadata',
                collapsible: true
            });
            layout.addWidget(this.editor);
        }
        /**
         * Handle a change to the active cell.
         */
        onActiveCellChanged(msg) {
            let cell = this.parent.activeCell;
            this.editor.source = cell ? cell.model.metadata : null;
        }
    }
    CellTools.MetadataEditorTool = MetadataEditorTool;
    /**
     * A cell tool that provides a selection for a given metadata key.
     */
    class KeySelector extends Tool {
        /**
         * Construct a new KeySelector.
         */
        constructor(options) {
            super({ node: Private.createSelectorNode(options) });
            /**
             * Get the value for the data.
             */
            this._getValue = (cell) => {
                return cell.model.metadata.get(this.key);
            };
            /**
             * Set the value for the data.
             */
            this._setValue = (cell, value) => {
                cell.model.metadata.set(this.key, value);
            };
            this._changeGuard = false;
            this.addClass(KEYSELECTOR_CLASS);
            this.key = options.key;
            this._validCellTypes = options.validCellTypes || [];
            this._getter = options.getter || this._getValue;
            this._setter = options.setter || this._setValue;
        }
        /**
         * The select node for the widget.
         */
        get selectNode() {
            return this.node.getElementsByTagName('select')[0];
        }
        /**
         * Handle the DOM events for the widget.
         *
         * @param event - The DOM event sent to the widget.
         *
         * #### Notes
         * This method implements the DOM `EventListener` interface and is
         * called in response to events on the notebook panel's node. It should
         * not be called directly by user code.
         */
        handleEvent(event) {
            switch (event.type) {
                case 'change':
                    this.onValueChanged();
                    break;
                default:
                    break;
            }
        }
        /**
         * Handle `after-attach` messages for the widget.
         */
        onAfterAttach(msg) {
            let node = this.selectNode;
            node.addEventListener('change', this);
        }
        /**
         * Handle `before-detach` messages for the widget.
         */
        onBeforeDetach(msg) {
            let node = this.selectNode;
            node.removeEventListener('change', this);
        }
        /**
         * Handle a change to the active cell.
         */
        onActiveCellChanged(msg) {
            let select = this.selectNode;
            let activeCell = this.parent.activeCell;
            if (!activeCell) {
                select.disabled = true;
                select.value = '';
                return;
            }
            let cellType = activeCell.model.type;
            if (this._validCellTypes.length &&
                this._validCellTypes.indexOf(cellType) === -1) {
                select.disabled = true;
                return;
            }
            select.disabled = false;
            this._changeGuard = true;
            let getter = this._getter;
            select.value = JSON.stringify(getter(activeCell));
            this._changeGuard = false;
        }
        /**
         * Handle a change to the metadata of the active cell.
         */
        onMetadataChanged(msg) {
            if (this._changeGuard) {
                return;
            }
            let select = this.selectNode;
            let cell = this.parent.activeCell;
            if (msg.args.key === this.key && cell) {
                this._changeGuard = true;
                let getter = this._getter;
                select.value = JSON.stringify(getter(cell));
                this._changeGuard = false;
            }
        }
        /**
         * Handle a change to the value.
         */
        onValueChanged() {
            let activeCell = this.parent.activeCell;
            if (!activeCell || this._changeGuard) {
                return;
            }
            this._changeGuard = true;
            let select = this.selectNode;
            let setter = this._setter;
            setter(activeCell, JSON.parse(select.value));
            this._changeGuard = false;
        }
    }
    CellTools.KeySelector = KeySelector;
    /**
     * Create a slideshow selector.
     */
    function createSlideShowSelector() {
        let options = {
            key: 'slideshow',
            title: 'Slide Type',
            optionsMap: {
                '-': '-',
                Slide: 'slide',
                'Sub-Slide': 'subslide',
                Fragment: 'fragment',
                Skip: 'skip',
                Notes: 'notes'
            },
            getter: cell => {
                let value = cell.model.metadata.get('slideshow');
                return value && value['slide_type'];
            },
            setter: (cell, value) => {
                let data = cell.model.metadata.get('slideshow') || Object.create(null);
                data = Object.assign({}, data, { slide_type: value });
                cell.model.metadata.set('slideshow', data);
            }
        };
        return new KeySelector(options);
    }
    CellTools.createSlideShowSelector = createSlideShowSelector;
    /**
     * Create an nbcovert selector.
     */
    function createNBConvertSelector(optionsMap) {
        return new KeySelector({
            key: 'raw_mimetype',
            title: 'Raw NBConvert Format',
            optionsMap: optionsMap,
            validCellTypes: ['raw']
        });
    }
    CellTools.createNBConvertSelector = createNBConvertSelector;
})(CellTools = exports.CellTools || (exports.CellTools = {}));
/**
 * A namespace for private data.
 */
var Private;
(function (Private) {
    /**
     * A comparator function for widget rank items.
     */
    function itemCmp(first, second) {
        return first.rank - second.rank;
    }
    Private.itemCmp = itemCmp;
    /**
     * Create the node for a KeySelector.
     */
    function createSelectorNode(options) {
        let name = options.key;
        let title = options.title || name[0].toLocaleUpperCase() + name.slice(1);
        let optionNodes = [];
        for (let label in options.optionsMap) {
            let value = JSON.stringify(options.optionsMap[label]);
            optionNodes.push(virtualdom_1.h.option({ value }, label));
        }
        let node = virtualdom_1.VirtualDOM.realize(virtualdom_1.h.div({}, virtualdom_1.h.label(title), virtualdom_1.h.select({}, optionNodes)));
        apputils_1.Styling.styleNode(node);
        return node;
    }
    Private.createSelectorNode = createSelectorNode;
})(Private || (Private = {}));


/***/ }),

/***/ "93I4":
/*!************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_is-object.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = function (it) {
  return typeof it === 'object' ? it !== null : typeof it === 'function';
};


/***/ }),

/***/ "94Z+":
/*!*****************************************!*\
  !*** ./node_modules/fbjs/lib/isNode.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks
 */

/**
 * @param {*} object The object to check.
 * @return {boolean} Whether or not the object is a DOM node.
 */
function isNode(object) {
  var doc = object ? object.ownerDocument || object : document;
  var defaultView = doc.defaultView || window;
  return !!(object && (typeof defaultView.Node === 'function' ? object instanceof defaultView.Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string'));
}

module.exports = isNode;

/***/ }),

/***/ "94vc":
/*!***************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/SubplotAccordion.js ***!
  \***************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _PlotlyFold = __webpack_require__(/*! ./PlotlyFold */ "mQPs");

var _PlotlyFold2 = _interopRequireDefault(_PlotlyFold);

var _TraceRequiredPanel = __webpack_require__(/*! ./TraceRequiredPanel */ "IBvg");

var _TraceRequiredPanel2 = _interopRequireDefault(_TraceRequiredPanel);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _constants = __webpack_require__(/*! ../../lib/constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var TraceFold = (0, _lib.connectTraceToPlot)(_PlotlyFold2.default);
var NonCartesianSubplotFold = (0, _lib.connectNonCartesianSubplotToLayout)(_PlotlyFold2.default);
var CartesianSubplotFold = (0, _lib.connectCartesianSubplotToLayout)(_PlotlyFold2.default);

var SubplotAccordion = function (_Component) {
  _inherits(SubplotAccordion, _Component);

  function SubplotAccordion() {
    _classCallCheck(this, SubplotAccordion);

    return _possibleConstructorReturn(this, (SubplotAccordion.__proto__ || Object.getPrototypeOf(SubplotAccordion)).apply(this, arguments));
  }

  _createClass(SubplotAccordion, [{
    key: 'render',
    value: function render() {
      var _context = this.context,
          _context$data = _context.data,
          data = _context$data === undefined ? [] : _context$data,
          _context$layout = _context.layout,
          layout = _context$layout === undefined ? {} : _context$layout,
          _ = _context.localize;
      var children = this.props.children;

      var subplotFolds = [];

      var allCartesianAxisCombinations = data.reduce(function (acc, curVal, inx) {
        if (_constants.TRACE_TO_AXIS.cartesian.some(function (c) {
          return c === curVal.type;
        })) {
          var xaxis = 'xaxis' + (curVal.xaxis ? curVal.xaxis.substring(1) : '');
          var yaxis = 'yaxis' + (curVal.yaxis ? curVal.yaxis.substring(1) : '');

          var existingComboIndex = acc.findIndex(function (t) {
            return t.xaxis === xaxis && t.yaxis === yaxis;
          });
          if (existingComboIndex === -1) {
            acc.push({
              xaxis: xaxis,
              yaxis: yaxis,
              xaxisName: curVal.xaxis ? (0, _lib.getSubplotTitle)(curVal.xaxis, 'x', _) : 'X 1',
              yaxisName: curVal.yaxis ? (0, _lib.getSubplotTitle)(curVal.yaxis, 'y', _) : 'Y 1',
              index: [inx]
            });
          } else {
            acc[existingComboIndex].index.push(inx);
          }
        }
        return acc;
      }, []);

      allCartesianAxisCombinations.forEach(function (d) {
        return subplotFolds[d.index[0]] = _react2.default.createElement(
          CartesianSubplotFold,
          {
            key: d.index[0],
            traceIndexes: d.index,
            canDelete: false,
            xaxis: d.xaxis,
            yaxis: d.yaxis,
            name: d.xaxisName + ' | ' + d.yaxisName
          },
          children
        );
      });

      // For each key in layout, find all traces that belong to this subplot.
      // E.g. if layout attr is 'ternary', find all traces that are of type
      // that has subplot ternary, if layout attr is 'ternary2', find traces
      // of right type that have attr 'subplot': 'ternary' in their data.

      /**
      Example: 
      {
        "data": [
          {
            "type": "scatterternary",
            "mode": "markers",
          },
          {
            "type": "scatterternary",
            "mode": "markers",
            "subplot": "ternary2"
          }
        ],
        "layout": {
          "ternary": {},
          "ternary2": {},
        },
      }
       */

      Object.keys(layout).forEach(function (layoutKey) {
        var traceIndexes = [];
        var subplotName = void 0;
        if (['geo', 'mapbox', 'polar', 'gl3d', 'ternary'].some(function (subplotType) {
          subplotName = (0, _lib.getSubplotTitle)(layoutKey, subplotType, _);
          var trIndex = _constants.SUBPLOT_TO_ATTR[subplotType].layout === layoutKey ? data.findIndex(function (trace) {
            return _constants.TRACE_TO_AXIS[subplotType].some(function (tt) {
              return tt === trace.type;
            });
          }) : data.findIndex(function (trace) {
            return trace[_constants.SUBPLOT_TO_ATTR[subplotType].data] === layoutKey;
          });
          if (trIndex !== -1) {
            traceIndexes.push(trIndex);
          }
          return layoutKey.startsWith(_constants.SUBPLOT_TO_ATTR[subplotType].layout);
        })) {
          subplotFolds[traceIndexes[0]] = _react2.default.createElement(
            NonCartesianSubplotFold,
            {
              key: layoutKey,
              traceIndexes: traceIndexes,
              canDelete: false,
              subplot: layoutKey,
              name: subplotName
            },
            children
          );
        }
      });

      var pieCounter = 0;
      var tableCounter = 0;
      data.forEach(function (d, i) {
        if (d.type === 'pie' && d.values || d.type === 'table') {
          if (d.type === 'pie') {
            pieCounter++;
          } else if (d.type === 'table') {
            tableCounter++;
          }
          subplotFolds[i] = _react2.default.createElement(
            TraceFold,
            {
              key: i,
              traceIndexes: [i],
              canDelete: false,
              name: d.type === 'pie' ? _('Pie') + ' ' + (pieCounter > 1 ? pieCounter : '') : _('Table') + ' ' + (tableCounter > 1 ? tableCounter : '')
            },
            children
          );
        }
      });

      return _react2.default.createElement(
        _TraceRequiredPanel2.default,
        null,
        subplotFolds
      );
    }
  }]);

  return SubplotAccordion;
}(_react.Component);

SubplotAccordion.contextTypes = {
  fullData: _propTypes2.default.array,
  data: _propTypes2.default.array,
  layout: _propTypes2.default.object,
  localize: _propTypes2.default.func
};

SubplotAccordion.propTypes = {
  children: _propTypes2.default.node
};

exports.default = SubplotAccordion;
//# sourceMappingURL=SubplotAccordion.js.map

/***/ }),

/***/ "95T3":
/*!***********************************************!*\
  !*** ./node_modules/plotly.js/dist/plotly.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global) {var require;var require;/**
* plotly.js v1.44.4
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
* Licensed under the MIT license
*/
(function(f){if(true){module.exports=f()}else { var g; }})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return require(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(_dereq_,module,exports){
'use strict';

var Lib = _dereq_('../src/lib');
var rules = {
    "X,X div": "direction:ltr;font-family:'Open Sans', verdana, arial, sans-serif;margin:0;padding:0;",
    "X input,X button": "font-family:'Open Sans', verdana, arial, sans-serif;",
    "X input:focus,X button:focus": "outline:none;",
    "X a": "text-decoration:none;",
    "X a:hover": "text-decoration:none;",
    "X .crisp": "shape-rendering:crispEdges;",
    "X .user-select-none": "-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;",
    "X svg": "overflow:hidden;",
    "X svg a": "fill:#447adb;",
    "X svg a:hover": "fill:#3c6dc5;",
    "X .main-svg": "position:absolute;top:0;left:0;pointer-events:none;",
    "X .main-svg .draglayer": "pointer-events:all;",
    "X .cursor-default": "cursor:default;",
    "X .cursor-pointer": "cursor:pointer;",
    "X .cursor-crosshair": "cursor:crosshair;",
    "X .cursor-move": "cursor:move;",
    "X .cursor-col-resize": "cursor:col-resize;",
    "X .cursor-row-resize": "cursor:row-resize;",
    "X .cursor-ns-resize": "cursor:ns-resize;",
    "X .cursor-ew-resize": "cursor:ew-resize;",
    "X .cursor-sw-resize": "cursor:sw-resize;",
    "X .cursor-s-resize": "cursor:s-resize;",
    "X .cursor-se-resize": "cursor:se-resize;",
    "X .cursor-w-resize": "cursor:w-resize;",
    "X .cursor-e-resize": "cursor:e-resize;",
    "X .cursor-nw-resize": "cursor:nw-resize;",
    "X .cursor-n-resize": "cursor:n-resize;",
    "X .cursor-ne-resize": "cursor:ne-resize;",
    "X .cursor-grab": "cursor:-webkit-grab;cursor:grab;",
    "X .modebar": "position:absolute;top:2px;right:2px;z-index:1001;",
    "X .ease-bg": "-webkit-transition:background-color 0.3s ease 0s;-moz-transition:background-color 0.3s ease 0s;-ms-transition:background-color 0.3s ease 0s;-o-transition:background-color 0.3s ease 0s;transition:background-color 0.3s ease 0s;",
    "X .modebar--hover>:not(.watermark)": "opacity:0;-webkit-transition:opacity 0.3s ease 0s;-moz-transition:opacity 0.3s ease 0s;-ms-transition:opacity 0.3s ease 0s;-o-transition:opacity 0.3s ease 0s;transition:opacity 0.3s ease 0s;",
    "X:hover .modebar--hover .modebar-group": "opacity:1;",
    "X .modebar-group": "float:left;display:inline-block;box-sizing:border-box;margin-left:8px;position:relative;vertical-align:middle;white-space:nowrap;",
    "X .modebar-btn": "position:relative;font-size:16px;padding:3px 4px;height:22px;cursor:pointer;line-height:normal;box-sizing:border-box;",
    "X .modebar-btn svg": "position:relative;top:2px;",
    "X .modebar.vertical": "display:flex;flex-direction:column;flex-wrap:wrap;align-content:flex-end;max-height:100%;",
    "X .modebar.vertical svg": "top:-1px;",
    "X .modebar.vertical .modebar-group": "display:block;float:none;margin-left:0px;margin-bottom:8px;",
    "X .modebar.vertical .modebar-group .modebar-btn": "display:block;text-align:center;",
    "X [data-title]:before,X [data-title]:after": "position:absolute;-webkit-transform:translate3d(0, 0, 0);-moz-transform:translate3d(0, 0, 0);-ms-transform:translate3d(0, 0, 0);-o-transform:translate3d(0, 0, 0);transform:translate3d(0, 0, 0);display:none;opacity:0;z-index:1001;pointer-events:none;top:110%;right:50%;",
    "X [data-title]:hover:before,X [data-title]:hover:after": "display:block;opacity:1;",
    "X [data-title]:before": "content:'';position:absolute;background:transparent;border:6px solid transparent;z-index:1002;margin-top:-12px;border-bottom-color:#69738a;margin-right:-6px;",
    "X [data-title]:after": "content:attr(data-title);background:#69738a;color:white;padding:8px 10px;font-size:12px;line-height:12px;white-space:nowrap;margin-right:-18px;border-radius:2px;",
    "X .vertical [data-title]:before,X .vertical [data-title]:after": "top:0%;right:200%;",
    "X .vertical [data-title]:before": "border:6px solid transparent;border-left-color:#69738a;margin-top:8px;margin-right:-30px;",
    "X .select-outline": "fill:none;stroke-width:1;shape-rendering:crispEdges;",
    "X .select-outline-1": "stroke:white;",
    "X .select-outline-2": "stroke:black;stroke-dasharray:2px 2px;",
    Y: "font-family:'Open Sans';position:fixed;top:50px;right:20px;z-index:10000;font-size:10pt;max-width:180px;",
    "Y p": "margin:0;",
    "Y .notifier-note": "min-width:180px;max-width:250px;border:1px solid #fff;z-index:3000;margin:0;background-color:#8c97af;background-color:rgba(140,151,175,0.9);color:#fff;padding:10px;overflow-wrap:break-word;word-wrap:break-word;-ms-hyphens:auto;-webkit-hyphens:auto;hyphens:auto;",
    "Y .notifier-close": "color:#fff;opacity:0.8;float:right;padding:0 5px;background:none;border:none;font-size:20px;font-weight:bold;line-height:20px;",
    "Y .notifier-close:hover": "color:#444;text-decoration:none;cursor:pointer;"
};

for(var selector in rules) {
    var fullSelector = selector.replace(/^,/,' ,')
        .replace(/X/g, '.js-plotly-plot .plotly')
        .replace(/Y/g, '.plotly-notifier');
    Lib.addStyleRule(fullSelector, rules[selector]);
}

},{"../src/lib":694}],2:[function(_dereq_,module,exports){
'use strict';

module.exports = {
    'undo': {
        'width': 857.1,
        'height': 1000,
        'path': 'm857 350q0-87-34-166t-91-137-137-92-166-34q-96 0-183 41t-147 114q-4 6-4 13t5 11l76 77q6 5 14 5 9-1 13-7 41-53 100-82t126-29q58 0 110 23t92 61 61 91 22 111-22 111-61 91-92 61-110 23q-55 0-105-20t-90-57l77-77q17-16 8-38-10-23-33-23h-250q-15 0-25 11t-11 25v250q0 24 22 33 22 10 39-8l72-72q60 57 137 88t159 31q87 0 166-34t137-92 91-137 34-166z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'home': {
        'width': 928.6,
        'height': 1000,
        'path': 'm786 296v-267q0-15-11-26t-25-10h-214v214h-143v-214h-214q-15 0-25 10t-11 26v267q0 1 0 2t0 2l321 264 321-264q1-1 1-4z m124 39l-34-41q-5-5-12-6h-2q-7 0-12 3l-386 322-386-322q-7-4-13-4-7 2-12 7l-35 41q-4 5-3 13t6 12l401 334q18 15 42 15t43-15l136-114v109q0 8 5 13t13 5h107q8 0 13-5t5-13v-227l122-102q5-5 6-12t-4-13z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'camera-retro': {
        'width': 1000,
        'height': 1000,
        'path': 'm518 386q0 8-5 13t-13 5q-37 0-63-27t-26-63q0-8 5-13t13-5 12 5 5 13q0 23 16 38t38 16q8 0 13 5t5 13z m125-73q0-59-42-101t-101-42-101 42-42 101 42 101 101 42 101-42 42-101z m-572-320h858v71h-858v-71z m643 320q0 89-62 152t-152 62-151-62-63-152 63-151 151-63 152 63 62 151z m-571 358h214v72h-214v-72z m-72-107h858v143h-462l-36-71h-360v-72z m929 143v-714q0-30-21-51t-50-21h-858q-29 0-50 21t-21 51v714q0 30 21 51t50 21h858q29 0 50-21t21-51z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'zoombox': {
        'width': 1000,
        'height': 1000,
        'path': 'm1000-25l-250 251c40 63 63 138 63 218 0 224-182 406-407 406-224 0-406-182-406-406s183-406 407-406c80 0 155 22 218 62l250-250 125 125z m-812 250l0 438 437 0 0-438-437 0z m62 375l313 0 0-312-313 0 0 312z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'pan': {
        'width': 1000,
        'height': 1000,
        'path': 'm1000 350l-187 188 0-125-250 0 0 250 125 0-188 187-187-187 125 0 0-250-250 0 0 125-188-188 186-187 0 125 252 0 0-250-125 0 187-188 188 188-125 0 0 250 250 0 0-126 187 188z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'zoom_plus': {
        'width': 875,
        'height': 1000,
        'path': 'm1 787l0-875 875 0 0 875-875 0z m687-500l-187 0 0-187-125 0 0 187-188 0 0 125 188 0 0 187 125 0 0-187 187 0 0-125z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'zoom_minus': {
        'width': 875,
        'height': 1000,
        'path': 'm0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'autoscale': {
        'width': 1000,
        'height': 1000,
        'path': 'm250 850l-187 0-63 0 0-62 0-188 63 0 0 188 187 0 0 62z m688 0l-188 0 0-62 188 0 0-188 62 0 0 188 0 62-62 0z m-875-938l0 188-63 0 0-188 0-62 63 0 187 0 0 62-187 0z m875 188l0-188-188 0 0-62 188 0 62 0 0 62 0 188-62 0z m-125 188l-1 0-93-94-156 156 156 156 92-93 2 0 0 250-250 0 0-2 93-92-156-156-156 156 94 92 0 2-250 0 0-250 0 0 93 93 157-156-157-156-93 94 0 0 0-250 250 0 0 0-94 93 156 157 156-157-93-93 0 0 250 0 0 250z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'tooltip_basic': {
        'width': 1500,
        'height': 1000,
        'path': 'm375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'tooltip_compare': {
        'width': 1125,
        'height': 1000,
        'path': 'm187 786l0 2-187-188 188-187 0 0 937 0 0 373-938 0z m0-499l0 1-187-188 188-188 0 0 937 0 0 376-938-1z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'plotlylogo': {
        'width': 1542,
        'height': 1000,
        'path': 'm0-10h182v-140h-182v140z m228 146h183v-286h-183v286z m225 714h182v-1000h-182v1000z m225-285h182v-715h-182v715z m225 142h183v-857h-183v857z m231-428h182v-429h-182v429z m225-291h183v-138h-183v138z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'z-axis': {
        'width': 1000,
        'height': 1000,
        'path': 'm833 5l-17 108v41l-130-65 130-66c0 0 0 38 0 39 0-1 36-14 39-25 4-15-6-22-16-30-15-12-39-16-56-20-90-22-187-23-279-23-261 0-341 34-353 59 3 60 228 110 228 110-140-8-351-35-351-116 0-120 293-142 474-142 155 0 477 22 477 142 0 50-74 79-163 96z m-374 94c-58-5-99-21-99-40 0-24 65-43 144-43 79 0 143 19 143 43 0 19-42 34-98 40v216h87l-132 135-133-135h88v-216z m167 515h-136v1c16 16 31 34 46 52l84 109v54h-230v-71h124v-1c-16-17-28-32-44-51l-89-114v-51h245v72z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    '3d_rotate': {
        'width': 1000,
        'height': 1000,
        'path': 'm922 660c-5 4-9 7-14 11-359 263-580-31-580-31l-102 28 58-400c0 1 1 1 2 2 118 108 351 249 351 249s-62 27-100 42c88 83 222 183 347 122 16-8 30-17 44-27-2 1-4 2-6 4z m36-329c0 0 64 229-88 296-62 27-124 14-175-11 157-78 225-208 249-266 8-19 11-31 11-31 2 5 6 15 11 32-5-13-8-20-8-20z m-775-239c70-31 117-50 198-32-121 80-199 346-199 346l-96-15-58-12c0 0 55-226 155-287z m603 133l-317-139c0 0 4-4 19-14 7-5 24-15 24-15s-177-147-389 4c235-287 536-112 536-112l31-22 100 299-4-1z m-298-153c6-4 14-9 24-15 0 0-17 10-24 15z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'camera': {
        'width': 1000,
        'height': 1000,
        'path': 'm500 450c-83 0-150-67-150-150 0-83 67-150 150-150 83 0 150 67 150 150 0 83-67 150-150 150z m400 150h-120c-16 0-34 13-39 29l-31 93c-6 15-23 28-40 28h-340c-16 0-34-13-39-28l-31-94c-6-15-23-28-40-28h-120c-55 0-100-45-100-100v-450c0-55 45-100 100-100h800c55 0 100 45 100 100v450c0 55-45 100-100 100z m-400-550c-138 0-250 112-250 250 0 138 112 250 250 250 138 0 250-112 250-250 0-138-112-250-250-250z m365 380c-19 0-35 16-35 35 0 19 16 35 35 35 19 0 35-16 35-35 0-19-16-35-35-35z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'movie': {
        'width': 1000,
        'height': 1000,
        'path': 'm938 413l-188-125c0 37-17 71-44 94 64 38 107 107 107 187 0 121-98 219-219 219-121 0-219-98-219-219 0-61 25-117 66-156h-115c30 33 49 76 49 125 0 103-84 187-187 187s-188-84-188-187c0-57 26-107 65-141-38-22-65-62-65-109v-250c0-70 56-126 125-126h500c69 0 125 56 125 126l188-126c34 0 62 28 62 63v375c0 35-28 63-62 63z m-750 0c-69 0-125 56-125 125s56 125 125 125 125-56 125-125-56-125-125-125z m406-1c-87 0-157 70-157 157 0 86 70 156 157 156s156-70 156-156-70-157-156-157z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'question': {
        'width': 857.1,
        'height': 1000,
        'path': 'm500 82v107q0 8-5 13t-13 5h-107q-8 0-13-5t-5-13v-107q0-8 5-13t13-5h107q8 0 13 5t5 13z m143 375q0 49-31 91t-77 65-95 23q-136 0-207-119-9-14 4-24l74-55q4-4 10-4 9 0 14 7 30 38 48 51 19 14 48 14 27 0 48-15t21-33q0-21-11-34t-38-25q-35-16-65-48t-29-70v-20q0-8 5-13t13-5h107q8 0 13 5t5 13q0 10 12 27t30 28q18 10 28 16t25 19 25 27 16 34 7 45z m214-107q0-117-57-215t-156-156-215-58-216 58-155 156-58 215 58 215 155 156 216 58 215-58 156-156 57-215z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'disk': {
        'width': 857.1,
        'height': 1000,
        'path': 'm214-7h429v214h-429v-214z m500 0h72v500q0 8-6 21t-11 20l-157 156q-5 6-19 12t-22 5v-232q0-22-15-38t-38-16h-322q-22 0-37 16t-16 38v232h-72v-714h72v232q0 22 16 38t37 16h465q22 0 38-16t15-38v-232z m-214 518v178q0 8-5 13t-13 5h-107q-7 0-13-5t-5-13v-178q0-8 5-13t13-5h107q7 0 13 5t5 13z m357-18v-518q0-22-15-38t-38-16h-750q-23 0-38 16t-16 38v750q0 22 16 38t38 16h517q23 0 50-12t42-26l156-157q16-15 27-42t11-49z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'lasso': {
        'width': 1031,
        'height': 1000,
        'path': 'm1018 538c-36 207-290 336-568 286-277-48-473-256-436-463 10-57 36-108 76-151-13-66 11-137 68-183 34-28 75-41 114-42l-55-70 0 0c-2-1-3-2-4-3-10-14-8-34 5-45 14-11 34-8 45 4 1 1 2 3 2 5l0 0 113 140c16 11 31 24 45 40 4 3 6 7 8 11 48-3 100 0 151 9 278 48 473 255 436 462z m-624-379c-80 14-149 48-197 96 42 42 109 47 156 9 33-26 47-66 41-105z m-187-74c-19 16-33 37-39 60 50-32 109-55 174-68-42-25-95-24-135 8z m360 75c-34-7-69-9-102-8 8 62-16 128-68 170-73 59-175 54-244-5-9 20-16 40-20 61-28 159 121 317 333 354s407-60 434-217c28-159-121-318-333-355z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'selectbox': {
        'width': 1000,
        'height': 1000,
        'path': 'm0 850l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-285l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z',
        'transform': 'matrix(1 0 0 -1 0 850)'
    },
    'spikeline': {
        'width': 1000,
        'height': 1000,
        'path': 'M512 409c0-57-46-104-103-104-57 0-104 47-104 104 0 57 47 103 104 103 57 0 103-46 103-103z m-327-39l92 0 0 92-92 0z m-185 0l92 0 0 92-92 0z m370-186l92 0 0 93-92 0z m0-184l92 0 0 92-92 0z',
        'transform': 'matrix(1.5 0 0 -1.5 0 850)'
    },
    'newplotlylogo': {
        'name': 'newplotlylogo',
        'svg': '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 132 132\'><defs><style>.cls-1 {fill: #119dff;} .cls-2 {fill: #25fefd;} .cls-3 {fill: #fff;}</style></defs><title>plotly-logomark</title><g id=\'symbol\'><rect class=\'cls-1\' width=\'132\' height=\'132\' rx=\'6\' ry=\'6\'/><circle class=\'cls-2\' cx=\'78\' cy=\'54\' r=\'6\'/><circle class=\'cls-2\' cx=\'102\' cy=\'30\' r=\'6\'/><circle class=\'cls-2\' cx=\'78\' cy=\'30\' r=\'6\'/><circle class=\'cls-2\' cx=\'54\' cy=\'30\' r=\'6\'/><circle class=\'cls-2\' cx=\'30\' cy=\'30\' r=\'6\'/><circle class=\'cls-2\' cx=\'30\' cy=\'54\' r=\'6\'/><path class=\'cls-3\' d=\'M30,72a6,6,0,0,0-6,6v24a6,6,0,0,0,12,0V78A6,6,0,0,0,30,72Z\'/><path class=\'cls-3\' d=\'M78,72a6,6,0,0,0-6,6v24a6,6,0,0,0,12,0V78A6,6,0,0,0,78,72Z\'/><path class=\'cls-3\' d=\'M54,48a6,6,0,0,0-6,6v48a6,6,0,0,0,12,0V54A6,6,0,0,0,54,48Z\'/><path class=\'cls-3\' d=\'M102,48a6,6,0,0,0-6,6v48a6,6,0,0,0,12,0V54A6,6,0,0,0,102,48Z\'/></g></svg>'
    }
};

},{}],3:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/transforms/aggregate');

},{"../src/transforms/aggregate":1159}],4:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/bar');

},{"../src/traces/bar":842}],5:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/barpolar');

},{"../src/traces/barpolar":854}],6:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/box');

},{"../src/traces/box":864}],7:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/components/calendars');

},{"../src/components/calendars":569}],8:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/candlestick');

},{"../src/traces/candlestick":873}],9:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/carpet');

},{"../src/traces/carpet":892}],10:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/choropleth');

},{"../src/traces/choropleth":906}],11:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/cone');

},{"../src/traces/cone":914}],12:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/contour');

},{"../src/traces/contour":929}],13:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/contourcarpet');

},{"../src/traces/contourcarpet":940}],14:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/core');

},{"../src/core":673}],15:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/transforms/filter');

},{"../src/transforms/filter":1160}],16:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/transforms/groupby');

},{"../src/transforms/groupby":1161}],17:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/heatmap');

},{"../src/traces/heatmap":952}],18:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/heatmapgl');

},{"../src/traces/heatmapgl":961}],19:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/histogram');

},{"../src/traces/histogram":973}],20:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/histogram2d');

},{"../src/traces/histogram2d":980}],21:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/histogram2dcontour');

},{"../src/traces/histogram2dcontour":984}],22:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Plotly = _dereq_('./core');

// traces
Plotly.register([
    _dereq_('./bar'),
    _dereq_('./box'),
    _dereq_('./heatmap'),
    _dereq_('./histogram'),
    _dereq_('./histogram2d'),
    _dereq_('./histogram2dcontour'),
    _dereq_('./pie'),
    _dereq_('./contour'),
    _dereq_('./scatterternary'),
    _dereq_('./violin'),

    _dereq_('./scatter3d'),
    _dereq_('./surface'),
    _dereq_('./isosurface'),
    _dereq_('./mesh3d'),
    _dereq_('./cone'),
    _dereq_('./streamtube'),

    _dereq_('./scattergeo'),
    _dereq_('./choropleth'),

    _dereq_('./scattergl'),
    _dereq_('./splom'),

    _dereq_('./pointcloud'),
    _dereq_('./heatmapgl'),
    _dereq_('./parcoords'),
    _dereq_('./parcats'),
    _dereq_('./scattermapbox'),

    _dereq_('./sankey'),

    _dereq_('./table'),

    _dereq_('./carpet'),
    _dereq_('./scattercarpet'),
    _dereq_('./contourcarpet'),

    _dereq_('./ohlc'),
    _dereq_('./candlestick'),

    _dereq_('./scatterpolar'),
    _dereq_('./scatterpolargl'),
    _dereq_('./barpolar')
]);

// transforms
//
// Please note that all *transform* methods are executed before
// all *calcTransform* methods - which could possibly lead to
// unexpected results when applying multiple transforms of different types
// to a given trace.
//
// For more info, see:
// https://github.com/plotly/plotly.js/pull/978#pullrequestreview-2403353
//
Plotly.register([
    _dereq_('./aggregate'),
    _dereq_('./filter'),
    _dereq_('./groupby'),
    _dereq_('./sort')
]);

// components
Plotly.register([
    _dereq_('./calendars')
]);

module.exports = Plotly;

},{"./aggregate":3,"./bar":4,"./barpolar":5,"./box":6,"./calendars":7,"./candlestick":8,"./carpet":9,"./choropleth":10,"./cone":11,"./contour":12,"./contourcarpet":13,"./core":14,"./filter":15,"./groupby":16,"./heatmap":17,"./heatmapgl":18,"./histogram":19,"./histogram2d":20,"./histogram2dcontour":21,"./isosurface":23,"./mesh3d":24,"./ohlc":25,"./parcats":26,"./parcoords":27,"./pie":28,"./pointcloud":29,"./sankey":30,"./scatter3d":31,"./scattercarpet":32,"./scattergeo":33,"./scattergl":34,"./scattermapbox":35,"./scatterpolar":36,"./scatterpolargl":37,"./scatterternary":38,"./sort":39,"./splom":40,"./streamtube":41,"./surface":42,"./table":43,"./violin":44}],23:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/isosurface');

},{"../src/traces/isosurface":989}],24:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/mesh3d');

},{"../src/traces/mesh3d":994}],25:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/ohlc');

},{"../src/traces/ohlc":999}],26:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/parcats');

},{"../src/traces/parcats":1008}],27:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/parcoords');

},{"../src/traces/parcoords":1017}],28:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/pie');

},{"../src/traces/pie":1028}],29:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/pointcloud');

},{"../src/traces/pointcloud":1037}],30:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/sankey');

},{"../src/traces/sankey":1043}],31:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/scatter3d');

},{"../src/traces/scatter3d":1079}],32:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/scattercarpet');

},{"../src/traces/scattercarpet":1085}],33:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/scattergeo');

},{"../src/traces/scattergeo":1092}],34:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/scattergl');

},{"../src/traces/scattergl":1100}],35:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/scattermapbox');

},{"../src/traces/scattermapbox":1106}],36:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/scatterpolar');

},{"../src/traces/scatterpolar":1113}],37:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/scatterpolargl');

},{"../src/traces/scatterpolargl":1117}],38:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/scatterternary');

},{"../src/traces/scatterternary":1123}],39:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/transforms/sort');

},{"../src/transforms/sort":1163}],40:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/splom');

},{"../src/traces/splom":1128}],41:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/streamtube');

},{"../src/traces/streamtube":1133}],42:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/surface');

},{"../src/traces/surface":1138}],43:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/table');

},{"../src/traces/table":1146}],44:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = _dereq_('../src/traces/violin');

},{"../src/traces/violin":1154}],45:[function(_dereq_,module,exports){
'use strict'

module.exports = createCamera

var now         = _dereq_('right-now')
var createView  = _dereq_('3d-view')
var mouseChange = _dereq_('mouse-change')
var mouseWheel  = _dereq_('mouse-wheel')
var mouseOffset = _dereq_('mouse-event-offset')
var hasPassive  = _dereq_('has-passive-events')

function createCamera(element, options) {
  element = element || document.body
  options = options || {}

  var limits  = [ 0.01, Infinity ]
  if('distanceLimits' in options) {
    limits[0] = options.distanceLimits[0]
    limits[1] = options.distanceLimits[1]
  }
  if('zoomMin' in options) {
    limits[0] = options.zoomMin
  }
  if('zoomMax' in options) {
    limits[1] = options.zoomMax
  }

  var view = createView({
    center: options.center || [0,0,0],
    up:     options.up     || [0,1,0],
    eye:    options.eye    || [0,0,10],
    mode:   options.mode   || 'orbit',
    distanceLimits: limits
  })

  var pmatrix = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
  var distance = 0.0
  var width   = element.clientWidth
  var height  = element.clientHeight

  var camera = {
    view:               view,
    element:            element,
    delay:              options.delay          || 16,
    rotateSpeed:        options.rotateSpeed    || 1,
    zoomSpeed:          options.zoomSpeed      || 1,
    translateSpeed:     options.translateSpeed || 1,
    flipX:              !!options.flipX,
    flipY:              !!options.flipY,
    modes:              view.modes,
    tick: function() {
      var t = now()
      var delay = this.delay
      view.idle(t-delay)
      view.flush(t-(100+delay*2))
      var ctime = t - 2 * delay
      view.recalcMatrix(ctime)
      var allEqual = true
      var matrix = view.computedMatrix
      for(var i=0; i<16; ++i) {
        allEqual = allEqual && (pmatrix[i] === matrix[i])
        pmatrix[i] = matrix[i]
      }
      var sizeChanged =
          element.clientWidth === width &&
          element.clientHeight === height
      width  = element.clientWidth
      height = element.clientHeight
      if(allEqual) {
        return !sizeChanged
      }
      distance = Math.exp(view.computedRadius[0])
      return true
    },
    lookAt: function(center, eye, up) {
      view.lookAt(view.lastT(), center, eye, up)
    },
    rotate: function(pitch, yaw, roll) {
      view.rotate(view.lastT(), pitch, yaw, roll)
    },
    pan: function(dx, dy, dz) {
      view.pan(view.lastT(), dx, dy, dz)
    },
    translate: function(dx, dy, dz) {
      view.translate(view.lastT(), dx, dy, dz)
    }
  }

  Object.defineProperties(camera, {
    matrix: {
      get: function() {
        return view.computedMatrix
      },
      set: function(mat) {
        view.setMatrix(view.lastT(), mat)
        return view.computedMatrix
      },
      enumerable: true
    },
    mode: {
      get: function() {
        return view.getMode()
      },
      set: function(mode) {
        view.setMode(mode)
        return view.getMode()
      },
      enumerable: true
    },
    center: {
      get: function() {
        return view.computedCenter
      },
      set: function(ncenter) {
        view.lookAt(view.lastT(), ncenter)
        return view.computedCenter
      },
      enumerable: true
    },
    eye: {
      get: function() {
        return view.computedEye
      },
      set: function(neye) {
        view.lookAt(view.lastT(), null, neye)
        return view.computedEye
      },
      enumerable: true
    },
    up: {
      get: function() {
        return view.computedUp
      },
      set: function(nup) {
        view.lookAt(view.lastT(), null, null, nup)
        return view.computedUp
      },
      enumerable: true
    },
    distance: {
      get: function() {
        return distance
      },
      set: function(d) {
        view.setDistance(view.lastT(), d)
        return d
      },
      enumerable: true
    },
    distanceLimits: {
      get: function() {
        return view.getDistanceLimits(limits)
      },
      set: function(v) {
        view.setDistanceLimits(v)
        return v
      },
      enumerable: true
    }
  })

  element.addEventListener('contextmenu', function(ev) {
    ev.preventDefault()
    return false
  })

  var lastX = 0, lastY = 0, lastMods = {shift: false, control: false, alt: false, meta: false}
  mouseChange(element, handleInteraction)

  //enable simple touch interactions
  element.addEventListener('touchstart', function (ev) {
    var xy = mouseOffset(ev.changedTouches[0], element)
    handleInteraction(0, xy[0], xy[1], lastMods)
    handleInteraction(1, xy[0], xy[1], lastMods)

    ev.preventDefault()
  }, hasPassive ? {passive: false} : false)

  element.addEventListener('touchmove', function (ev) {
    var xy = mouseOffset(ev.changedTouches[0], element)
    handleInteraction(1, xy[0], xy[1], lastMods)

    ev.preventDefault()
  }, hasPassive ? {passive: false} : false)

  element.addEventListener('touchend', function (ev) {
    var xy = mouseOffset(ev.changedTouches[0], element)
    handleInteraction(0, lastX, lastY, lastMods)

    ev.preventDefault()
  }, hasPassive ? {passive: false} : false)

  function handleInteraction (buttons, x, y, mods) {
    var scale = 1.0 / element.clientHeight
    var dx    = scale * (x - lastX)
    var dy    = scale * (y - lastY)

    var flipX = camera.flipX ? 1 : -1
    var flipY = camera.flipY ? 1 : -1

    var drot  = Math.PI * camera.rotateSpeed

    var t = now()

    if(buttons & 1) {
      if(mods.shift) {
        view.rotate(t, 0, 0, -dx * drot)
      } else {
        view.rotate(t, flipX * drot * dx, -flipY * drot * dy, 0)
      }
    } else if(buttons & 2) {
      view.pan(t, -camera.translateSpeed * dx * distance, camera.translateSpeed * dy * distance, 0)
    } else if(buttons & 4) {
      var kzoom = camera.zoomSpeed * dy / window.innerHeight * (t - view.lastT()) * 50.0
      view.pan(t, 0, 0, distance * (Math.exp(kzoom) - 1))
    }

    lastX = x
    lastY = y
    lastMods = mods
  }

  mouseWheel(element, function(dx, dy, dz) {
    var flipX = camera.flipX ? 1 : -1
    var flipY = camera.flipY ? 1 : -1
    var t = now()
    if(Math.abs(dx) > Math.abs(dy)) {
      view.rotate(t, 0, 0, -dx * flipX * Math.PI * camera.rotateSpeed / window.innerWidth)
    } else {
      var kzoom = camera.zoomSpeed * flipY * dy / window.innerHeight * (t - view.lastT()) / 100.0
      view.pan(t, 0, 0, distance * (Math.exp(kzoom) - 1))
    }
  }, true)

  return camera
}

},{"3d-view":46,"has-passive-events":397,"mouse-change":421,"mouse-event-offset":422,"mouse-wheel":424,"right-now":482}],46:[function(_dereq_,module,exports){
'use strict'

module.exports = createViewController

var createTurntable = _dereq_('turntable-camera-controller')
var createOrbit     = _dereq_('orbit-camera-controller')
var createMatrix    = _dereq_('matrix-camera-controller')

function ViewController(controllers, mode) {
  this._controllerNames = Object.keys(controllers)
  this._controllerList = this._controllerNames.map(function(n) {
    return controllers[n]
  })
  this._mode   = mode
  this._active = controllers[mode]
  if(!this._active) {
    this._mode   = 'turntable'
    this._active = controllers.turntable
  }
  this.modes = this._controllerNames
  this.computedMatrix = this._active.computedMatrix
  this.computedEye    = this._active.computedEye
  this.computedUp     = this._active.computedUp
  this.computedCenter = this._active.computedCenter
  this.computedRadius = this._active.computedRadius
}

var proto = ViewController.prototype

var COMMON_METHODS = [
  ['flush', 1],
  ['idle', 1],
  ['lookAt', 4],
  ['rotate', 4],
  ['pan', 4],
  ['translate', 4],
  ['setMatrix', 2],
  ['setDistanceLimits', 2],
  ['setDistance', 2]
]

COMMON_METHODS.forEach(function(method) {
  var name = method[0]
  var argNames = []
  for(var i=0; i<method[1]; ++i) {
    argNames.push('a'+i)
  }
  var code = 'var cc=this._controllerList;for(var i=0;i<cc.length;++i){cc[i].'+method[0]+'('+argNames.join()+')}'
  proto[name] = Function.apply(null, argNames.concat(code))
})

proto.recalcMatrix = function(t) {
  this._active.recalcMatrix(t)
}

proto.getDistance = function(t) {
  return this._active.getDistance(t)
}
proto.getDistanceLimits = function(out) {
  return this._active.getDistanceLimits(out)
}

proto.lastT = function() {
  return this._active.lastT()
}

proto.setMode = function(mode) {
  if(mode === this._mode) {
    return
  }
  var idx = this._controllerNames.indexOf(mode)
  if(idx < 0) {
    return
  }
  var prev  = this._active
  var next  = this._controllerList[idx]
  var lastT = Math.max(prev.lastT(), next.lastT())

  prev.recalcMatrix(lastT)
  next.setMatrix(lastT, prev.computedMatrix)
  
  this._active = next
  this._mode   = mode

  //Update matrix properties
  this.computedMatrix = this._active.computedMatrix
  this.computedEye    = this._active.computedEye
  this.computedUp     = this._active.computedUp
  this.computedCenter = this._active.computedCenter
  this.computedRadius = this._active.computedRadius
}

proto.getMode = function() {
  return this._mode
}

function createViewController(options) {
  options = options || {}

  var eye       = options.eye    || [0,0,1]
  var center    = options.center || [0,0,0]
  var up        = options.up     || [0,1,0]
  var limits    = options.distanceLimits || [0, Infinity]
  var mode      = options.mode   || 'turntable'

  var turntable = createTurntable()
  var orbit     = createOrbit()
  var matrix    = createMatrix()

  turntable.setDistanceLimits(limits[0], limits[1])
  turntable.lookAt(0, eye, center, up)
  orbit.setDistanceLimits(limits[0], limits[1])
  orbit.lookAt(0, eye, center, up)
  matrix.setDistanceLimits(limits[0], limits[1])
  matrix.lookAt(0, eye, center, up)

  return new ViewController({
    turntable: turntable,
    orbit: orbit,
    matrix: matrix
  }, mode)
}
},{"matrix-camera-controller":419,"orbit-camera-controller":442,"turntable-camera-controller":520}],47:[function(_dereq_,module,exports){
// https://github.com/d3/d3-sankey Version 0.5.1. Copyright 2018 Mike Bostock.
(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, _dereq_('d3-array'), _dereq_('d3-collection'), _dereq_('d3-interpolate')) :
	typeof define === 'function' && define.amd ? define(['exports', 'd3-array', 'd3-collection', 'd3-interpolate'], factory) :
	(factory((global.d3 = global.d3 || {}),global.d3,global.d3,global.d3));
}(this, (function (exports,d3Array,d3Collection,d3Interpolate) { 'use strict';

var sankey = function() {
  var sankey = {},
      nodeWidth = 24,
      nodePadding = 8,
      size = [1, 1],
      nodes = [],
      links = [],
      maxPaddedSpace = 2 / 3; // Defined as a fraction of the total available space

  sankey.nodeWidth = function(_) {
    if (!arguments.length) return nodeWidth;
    nodeWidth = +_;
    return sankey;
  };

  sankey.nodePadding = function(_) {
    if (!arguments.length) return nodePadding;
    nodePadding = +_;
    return sankey;
  };

  sankey.nodes = function(_) {
    if (!arguments.length) return nodes;
    nodes = _;
    return sankey;
  };

  sankey.links = function(_) {
    if (!arguments.length) return links;
    links = _;
    return sankey;
  };

  sankey.size = function(_) {
    if (!arguments.length) return size;
    size = _;
    return sankey;
  };

  sankey.layout = function(iterations) {
    computeNodeLinks();
    computeNodeValues();
    computeNodeBreadths();
    computeNodeDepths(iterations);
    computeLinkDepths();
    return sankey;
  };

  sankey.relayout = function() {
    computeLinkDepths();
    return sankey;
  };

  sankey.link = function() {
    var curvature = .5;

    function link(d) {
      var x0 = d.source.x + d.source.dx,
          x1 = d.target.x,
          xi = d3Interpolate.interpolateNumber(x0, x1),
          x2 = xi(curvature),
          x3 = xi(1 - curvature),
          y0a = d.source.y + d.sy,
          y0b = y0a + d.dy,
          y1a = d.target.y + d.ty,
          y1b = y1a + d.dy;
      return "M" + x0 + "," + y0a
           + "C" + x2 + "," + y0a
           + " " + x3 + "," + y1a
           + " " + x1 + "," + y1a
           + "L" + x1 + "," + y1b
           + "C" + x3 + "," + y1b
           + " " + x2 + "," + y0b
           + " " + x0 + "," + y0b
           + "Z";
    }

    link.curvature = function(_) {
      if (!arguments.length) return curvature;
      curvature = +_;
      return link;
    };

    return link;
  };

  // Populate the sourceLinks and targetLinks for each node.
  // Also, if the source and target are not objects, assume they are indices.
  function computeNodeLinks() {
    nodes.forEach(function(node) {
      node.sourceLinks = [];
      node.targetLinks = [];
    });
    links.forEach(function(link, i) {
      var source = link.source,
          target = link.target;
      if (typeof source === "number") source = link.source = nodes[link.source];
      if (typeof target === "number") target = link.target = nodes[link.target];
      link.originalIndex = i;
      source.sourceLinks.push(link);
      target.targetLinks.push(link);
    });
  }

  // Compute the value (size) of each node by summing the associated links.
  function computeNodeValues() {
    nodes.forEach(function(node) {
      node.value = Math.max(
        d3Array.sum(node.sourceLinks, value),
        d3Array.sum(node.targetLinks, value)
      );
    });
  }

  // Iteratively assign the breadth (x-position) for each node.
  // Nodes are assigned the maximum breadth of incoming neighbors plus one;
  // nodes with no incoming links are assigned breadth zero, while
  // nodes with no outgoing links are assigned the maximum breadth.
  function computeNodeBreadths() {
    var remainingNodes = nodes,
        nextNodes,
        x = 0;

    while (remainingNodes.length) {
      nextNodes = [];
      remainingNodes.forEach(function(node) {
        node.x = x;
        node.dx = nodeWidth;
        node.sourceLinks.forEach(function(link) {
          if (nextNodes.indexOf(link.target) < 0) {
            nextNodes.push(link.target);
          }
        });
      });
      remainingNodes = nextNodes;
      ++x;
    }

    //
    moveSinksRight(x);
    scaleNodeBreadths((size[0] - nodeWidth) / (x - 1));
  }

  // function moveSourcesRight() {
  //   nodes.forEach(function(node) {
  //     if (!node.targetLinks.length) {
  //       node.x = min(node.sourceLinks, function(d) { return d.target.x; }) - 1;
  //     }
  //   });
  // }

  function moveSinksRight(x) {
    nodes.forEach(function(node) {
      if (!node.sourceLinks.length) {
        node.x = x - 1;
      }
    });
  }

  function scaleNodeBreadths(kx) {
    nodes.forEach(function(node) {
      node.x *= kx;
    });
  }

  function computeNodeDepths(iterations) {
    var nodesByBreadth = d3Collection.nest()
        .key(function(d) { return d.x; })
        .sortKeys(d3Array.ascending)
        .entries(nodes)
        .map(function(d) { return d.values; });

    //
    initializeNodeDepth();
    resolveCollisions();
    for (var alpha = 1; iterations > 0; --iterations) {
      relaxRightToLeft(alpha *= .99);
      resolveCollisions();
      relaxLeftToRight(alpha);
      resolveCollisions();
    }

    function initializeNodeDepth() {
      var L = d3Array.max(nodesByBreadth, function(nodes) {
        return nodes.length;
      });
      var maxNodePadding = maxPaddedSpace * size[1] / (L - 1);
      if(nodePadding > maxNodePadding) nodePadding = maxNodePadding;
      var ky = d3Array.min(nodesByBreadth, function(nodes) {
        return (size[1] - (nodes.length - 1) * nodePadding) / d3Array.sum(nodes, value);
      });

      nodesByBreadth.forEach(function(nodes) {
        nodes.forEach(function(node, i) {
          node.y = i;
          node.dy = node.value * ky;
        });
      });

      links.forEach(function(link) {
        link.dy = link.value * ky;
      });
    }

    function relaxLeftToRight(alpha) {
      nodesByBreadth.forEach(function(nodes) {
        nodes.forEach(function(node) {
          if (node.targetLinks.length) {
            var y = d3Array.sum(node.targetLinks, weightedSource) / d3Array.sum(node.targetLinks, value);
            node.y += (y - center(node)) * alpha;
          }
        });
      });

      function weightedSource(link) {
        return center(link.source) * link.value;
      }
    }

    function relaxRightToLeft(alpha) {
      nodesByBreadth.slice().reverse().forEach(function(nodes) {
        nodes.forEach(function(node) {
          if (node.sourceLinks.length) {
            var y = d3Array.sum(node.sourceLinks, weightedTarget) / d3Array.sum(node.sourceLinks, value);
            node.y += (y - center(node)) * alpha;
          }
        });
      });

      function weightedTarget(link) {
        return center(link.target) * link.value;
      }
    }

    function resolveCollisions() {
      nodesByBreadth.forEach(function(nodes) {
        var node,
            dy,
            y0 = 0,
            n = nodes.length,
            i;

        // Push any overlapping nodes down.
        nodes.sort(ascendingDepth);
        for (i = 0; i < n; ++i) {
          node = nodes[i];
          dy = y0 - node.y;
          if (dy > 0) node.y += dy;
          y0 = node.y + node.dy + nodePadding;
        }

        // If the bottommost node goes outside the bounds, push it back up.
        dy = y0 - nodePadding - size[1];
        if (dy > 0) {
          y0 = node.y -= dy;

          // Push any overlapping nodes back up.
          for (i = n - 2; i >= 0; --i) {
            node = nodes[i];
            dy = node.y + node.dy + nodePadding - y0;
            if (dy > 0) node.y -= dy;
            y0 = node.y;
          }
        }
      });
    }

    function ascendingDepth(a, b) {
      return a.y - b.y;
    }
  }

  function computeLinkDepths() {
    nodes.forEach(function(node) {
      node.sourceLinks.sort(ascendingTargetDepth);
      node.targetLinks.sort(ascendingSourceDepth);
    });
    nodes.forEach(function(node) {
      var sy = 0, ty = 0;
      node.sourceLinks.forEach(function(link) {
        link.sy = sy;
        sy += link.dy;
      });
      node.targetLinks.forEach(function(link) {
        link.ty = ty;
        ty += link.dy;
      });
    });

    function ascendingSourceDepth(a, b) {
      return (a.source.y - b.source.y) || (a.originalIndex - b.originalIndex);
    }

    function ascendingTargetDepth(a, b) {
      return (a.target.y - b.target.y) || (a.originalIndex - b.originalIndex);
    }
  }

  function center(node) {
    return node.y + node.dy / 2;
  }

  function value(link) {
    return link.value;
  }

  return sankey;
};

exports.sankey = sankey;

Object.defineProperty(exports, '__esModule', { value: true });

})));

},{"d3-array":141,"d3-collection":142,"d3-interpolate":146}],48:[function(_dereq_,module,exports){
'use strict'

var weakMap      = typeof WeakMap === 'undefined' ? _dereq_('weak-map') : WeakMap
var createBuffer = _dereq_('gl-buffer')
var createVAO    = _dereq_('gl-vao')

var TriangleCache = new weakMap()

function createABigTriangle(gl) {

  var triangleVAO = TriangleCache.get(gl)
  var handle = triangleVAO && (triangleVAO._triangleBuffer.handle || triangleVAO._triangleBuffer.buffer)
  if(!handle || !gl.isBuffer(handle)) {
    var buf = createBuffer(gl, new Float32Array([-1, -1, -1, 4, 4, -1]))
    triangleVAO = createVAO(gl, [
      { buffer: buf,
        type: gl.FLOAT,
        size: 2
      }
    ])
    triangleVAO._triangleBuffer = buf
    TriangleCache.set(gl, triangleVAO)
  }
  triangleVAO.bind()
  gl.drawArrays(gl.TRIANGLES, 0, 3)
  triangleVAO.unbind()
}

module.exports = createABigTriangle

},{"gl-buffer":231,"gl-vao":313,"weak-map":530}],49:[function(_dereq_,module,exports){

module.exports = absolutize

/**
 * redefine `path` with absolute coordinates
 *
 * @param {Array} path
 * @return {Array}
 */

function absolutize(path){
	var startX = 0
	var startY = 0
	var x = 0
	var y = 0

	return path.map(function(seg){
		seg = seg.slice()
		var type = seg[0]
		var command = type.toUpperCase()

		// is relative
		if (type != command) {
			seg[0] = command
			switch (type) {
				case 'a':
					seg[6] += x
					seg[7] += y
					break
				case 'v':
					seg[1] += y
					break
				case 'h':
					seg[1] += x
					break
				default:
					for (var i = 1; i < seg.length;) {
						seg[i++] += x
						seg[i++] += y
					}
			}
		}

		// update cursor state
		switch (command) {
			case 'Z':
				x = startX
				y = startY
				break
			case 'H':
				x = seg[1]
				break
			case 'V':
				y = seg[1]
				break
			case 'M':
				x = startX = seg[1]
				y = startY = seg[2]
				break
			default:
				x = seg[seg.length - 2]
				y = seg[seg.length - 1]
		}

		return seg
	})
}

},{}],50:[function(_dereq_,module,exports){
var padLeft = _dereq_('pad-left')

module.exports = addLineNumbers
function addLineNumbers (string, start, delim) {
  start = typeof start === 'number' ? start : 1
  delim = delim || ': '

  var lines = string.split(/\r?\n/)
  var totalDigits = String(lines.length + start - 1).length
  return lines.map(function (line, i) {
    var c = i + start
    var digits = String(c).length
    var prefix = padLeft(c, totalDigits - digits)
    return prefix + delim + line
  }).join('\n')
}

},{"pad-left":443}],51:[function(_dereq_,module,exports){
'use strict'

module.exports = affineHull

var orient = _dereq_('robust-orientation')

function linearlyIndependent(points, d) {
  var nhull = new Array(d+1)
  for(var i=0; i<points.length; ++i) {
    nhull[i] = points[i]
  }
  for(var i=0; i<=points.length; ++i) {
    for(var j=points.length; j<=d; ++j) {
      var x = new Array(d)
      for(var k=0; k<d; ++k) {
        x[k] = Math.pow(j+1-i, k)
      }
      nhull[j] = x
    }
    var o = orient.apply(void 0, nhull)
    if(o) {
      return true
    }
  }
  return false
}

function affineHull(points) {
  var n = points.length
  if(n === 0) {
    return []
  }
  if(n === 1) {
    return [0]
  }
  var d = points[0].length
  var frame = [ points[0] ]
  var index = [ 0 ]
  for(var i=1; i<n; ++i) {
    frame.push(points[i])
    if(!linearlyIndependent(frame, d)) {
      frame.pop()
      continue
    }
    index.push(i)
    if(index.length === d+1) {
      return index
    }
  }
  return index
}
},{"robust-orientation":488}],52:[function(_dereq_,module,exports){
'use strict'

module.exports = alphaComplex

var delaunay = _dereq_('delaunay-triangulate')
var circumradius = _dereq_('circumradius')

function alphaComplex(alpha, points) {
  return delaunay(points).filter(function(cell) {
    var simplex = new Array(cell.length)
    for(var i=0; i<cell.length; ++i) {
      simplex[i] = points[cell[i]]
    }
    return circumradius(simplex) * alpha < 1
  })
}
},{"circumradius":103,"delaunay-triangulate":151}],53:[function(_dereq_,module,exports){
module.exports = alphaShape

var ac = _dereq_('alpha-complex')
var bnd = _dereq_('simplicial-complex-boundary')

function alphaShape(alpha, points) {
  return bnd(ac(alpha, points))
}
},{"alpha-complex":52,"simplicial-complex-boundary":495}],54:[function(_dereq_,module,exports){
'use strict'

module.exports = normalize;

function normalize (arr, dim) {
	if (!arr || arr.length == null) throw Error('Argument should be an array')

	if (dim == null) dim = 1
	else dim = Math.floor(dim)

	var bounds = Array(dim * 2)

	for (var offset = 0; offset < dim; offset++) {
		var max = -Infinity, min = Infinity, i = offset, l = arr.length;

		for (; i < l; i+=dim) {
			if (arr[i] > max) max = arr[i];
			if (arr[i] < min) min = arr[i];
		}

		bounds[offset] = min
		bounds[dim + offset] = max
	}

	return bounds;
}

},{}],55:[function(_dereq_,module,exports){
'use strict'

var getBounds = _dereq_('array-bounds')

module.exports = normalize;

function normalize (arr, dim, bounds) {
	if (!arr || arr.length == null) throw Error('Argument should be an array')

	if (dim == null) dim = 1
	if (bounds == null) bounds = getBounds(arr, dim)

	for (var offset = 0; offset < dim; offset++) {
		var max = bounds[dim + offset], min = bounds[offset], i = offset, l = arr.length;

		if (max === Infinity && min === -Infinity) {
			for (i = offset; i < l; i+=dim) {
				arr[i] = arr[i] === max ? 1 : arr[i] === min ? 0 : .5
			}
		}
		else if (max === Infinity) {
			for (i = offset; i < l; i+=dim) {
				arr[i] = arr[i] === max ? 1 : 0
			}
		}
		else if (min === -Infinity) {
			for (i = offset; i < l; i+=dim) {
				arr[i] = arr[i] === min ? 0 : 1
			}
		}
		else {
			var range = max - min
			for (i = offset; i < l; i+=dim) {
				arr[i] = range === 0 ? .5 : (arr[i] - min) / range
			}
		}
	}

	return arr;
}

},{"array-bounds":54}],56:[function(_dereq_,module,exports){

module.exports = function newArray(start, end) {
    var n0 = typeof start === 'number',
        n1 = typeof end === 'number'

    if (n0 && !n1) {
        end = start
        start = 0
    } else if (!n0 && !n1) {
        start = 0
        end = 0
    }

    start = start|0
    end = end|0
    var len = end-start
    if (len<0)
        throw new Error('array length must be positive')
    
    var a = new Array(len)
    for (var i=0, c=start; i<len; i++, c++)
        a[i] = c
    return a
}
},{}],57:[function(_dereq_,module,exports){
(function (global){
'use strict';

// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
// original notice:

/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
 * @license  MIT
 */
function compare(a, b) {
  if (a === b) {
    return 0;
  }

  var x = a.length;
  var y = b.length;

  for (var i = 0, len = Math.min(x, y); i < len; ++i) {
    if (a[i] !== b[i]) {
      x = a[i];
      y = b[i];
      break;
    }
  }

  if (x < y) {
    return -1;
  }
  if (y < x) {
    return 1;
  }
  return 0;
}
function isBuffer(b) {
  if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
    return global.Buffer.isBuffer(b);
  }
  return !!(b != null && b._isBuffer);
}

// based on node assert, original notice:

// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
//
// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
//
// Originally from narwhal.js (http://narwhaljs.org)
// Copyright (c) 2009 Thomas Robinson <280north.com>
//
// 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 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.

var util = _dereq_('util/');
var hasOwn = Object.prototype.hasOwnProperty;
var pSlice = Array.prototype.slice;
var functionsHaveNames = (function () {
  return function foo() {}.name === 'foo';
}());
function pToString (obj) {
  return Object.prototype.toString.call(obj);
}
function isView(arrbuf) {
  if (isBuffer(arrbuf)) {
    return false;
  }
  if (typeof global.ArrayBuffer !== 'function') {
    return false;
  }
  if (typeof ArrayBuffer.isView === 'function') {
    return ArrayBuffer.isView(arrbuf);
  }
  if (!arrbuf) {
    return false;
  }
  if (arrbuf instanceof DataView) {
    return true;
  }
  if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
    return true;
  }
  return false;
}
// 1. The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.

var assert = module.exports = ok;

// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
//                             actual: actual,
//                             expected: expected })

var regex = /\s*function\s+([^\(\s]*)\s*/;
// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
function getName(func) {
  if (!util.isFunction(func)) {
    return;
  }
  if (functionsHaveNames) {
    return func.name;
  }
  var str = func.toString();
  var match = str.match(regex);
  return match && match[1];
}
assert.AssertionError = function AssertionError(options) {
  this.name = 'AssertionError';
  this.actual = options.actual;
  this.expected = options.expected;
  this.operator = options.operator;
  if (options.message) {
    this.message = options.message;
    this.generatedMessage = false;
  } else {
    this.message = getMessage(this);
    this.generatedMessage = true;
  }
  var stackStartFunction = options.stackStartFunction || fail;
  if (Error.captureStackTrace) {
    Error.captureStackTrace(this, stackStartFunction);
  } else {
    // non v8 browsers so we can have a stacktrace
    var err = new Error();
    if (err.stack) {
      var out = err.stack;

      // try to strip useless frames
      var fn_name = getName(stackStartFunction);
      var idx = out.indexOf('\n' + fn_name);
      if (idx >= 0) {
        // once we have located the function frame
        // we need to strip out everything before it (and its line)
        var next_line = out.indexOf('\n', idx + 1);
        out = out.substring(next_line + 1);
      }

      this.stack = out;
    }
  }
};

// assert.AssertionError instanceof Error
util.inherits(assert.AssertionError, Error);

function truncate(s, n) {
  if (typeof s === 'string') {
    return s.length < n ? s : s.slice(0, n);
  } else {
    return s;
  }
}
function inspect(something) {
  if (functionsHaveNames || !util.isFunction(something)) {
    return util.inspect(something);
  }
  var rawname = getName(something);
  var name = rawname ? ': ' + rawname : '';
  return '[Function' +  name + ']';
}
function getMessage(self) {
  return truncate(inspect(self.actual), 128) + ' ' +
         self.operator + ' ' +
         truncate(inspect(self.expected), 128);
}

// At present only the three keys mentioned above are used and
// understood by the spec. Implementations or sub modules can pass
// other keys to the AssertionError's constructor - they will be
// ignored.

// 3. All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided.  All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.

function fail(actual, expected, message, operator, stackStartFunction) {
  throw new assert.AssertionError({
    message: message,
    actual: actual,
    expected: expected,
    operator: operator,
    stackStartFunction: stackStartFunction
  });
}

// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;

// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.

function ok(value, message) {
  if (!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;

// 5. The equality assertion tests shallow, coercive equality with
// ==.
// assert.equal(actual, expected, message_opt);

assert.equal = function equal(actual, expected, message) {
  if (actual != expected) fail(actual, expected, message, '==', assert.equal);
};

// 6. The non-equality assertion tests for whether two objects are not equal
// with != assert.notEqual(actual, expected, message_opt);

assert.notEqual = function notEqual(actual, expected, message) {
  if (actual == expected) {
    fail(actual, expected, message, '!=', assert.notEqual);
  }
};

// 7. The equivalence assertion tests a deep equality relation.
// assert.deepEqual(actual, expected, message_opt);

assert.deepEqual = function deepEqual(actual, expected, message) {
  if (!_deepEqual(actual, expected, false)) {
    fail(actual, expected, message, 'deepEqual', assert.deepEqual);
  }
};

assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
  if (!_deepEqual(actual, expected, true)) {
    fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
  }
};

function _deepEqual(actual, expected, strict, memos) {
  // 7.1. All identical values are equivalent, as determined by ===.
  if (actual === expected) {
    return true;
  } else if (isBuffer(actual) && isBuffer(expected)) {
    return compare(actual, expected) === 0;

  // 7.2. If the expected value is a Date object, the actual value is
  // equivalent if it is also a Date object that refers to the same time.
  } else if (util.isDate(actual) && util.isDate(expected)) {
    return actual.getTime() === expected.getTime();

  // 7.3 If the expected value is a RegExp object, the actual value is
  // equivalent if it is also a RegExp object with the same source and
  // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
  } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
    return actual.source === expected.source &&
           actual.global === expected.global &&
           actual.multiline === expected.multiline &&
           actual.lastIndex === expected.lastIndex &&
           actual.ignoreCase === expected.ignoreCase;

  // 7.4. Other pairs that do not both pass typeof value == 'object',
  // equivalence is determined by ==.
  } else if ((actual === null || typeof actual !== 'object') &&
             (expected === null || typeof expected !== 'object')) {
    return strict ? actual === expected : actual == expected;

  // If both values are instances of typed arrays, wrap their underlying
  // ArrayBuffers in a Buffer each to increase performance
  // This optimization requires the arrays to have the same type as checked by
  // Object.prototype.toString (aka pToString). Never perform binary
  // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
  // bit patterns are not identical.
  } else if (isView(actual) && isView(expected) &&
             pToString(actual) === pToString(expected) &&
             !(actual instanceof Float32Array ||
               actual instanceof Float64Array)) {
    return compare(new Uint8Array(actual.buffer),
                   new Uint8Array(expected.buffer)) === 0;

  // 7.5 For all other Object pairs, including Array objects, equivalence is
  // determined by having the same number of owned properties (as verified
  // with Object.prototype.hasOwnProperty.call), the same set of keys
  // (although not necessarily the same order), equivalent values for every
  // corresponding key, and an identical 'prototype' property. Note: this
  // accounts for both named and indexed properties on Arrays.
  } else if (isBuffer(actual) !== isBuffer(expected)) {
    return false;
  } else {
    memos = memos || {actual: [], expected: []};

    var actualIndex = memos.actual.indexOf(actual);
    if (actualIndex !== -1) {
      if (actualIndex === memos.expected.indexOf(expected)) {
        return true;
      }
    }

    memos.actual.push(actual);
    memos.expected.push(expected);

    return objEquiv(actual, expected, strict, memos);
  }
}

function isArguments(object) {
  return Object.prototype.toString.call(object) == '[object Arguments]';
}

function objEquiv(a, b, strict, actualVisitedObjects) {
  if (a === null || a === undefined || b === null || b === undefined)
    return false;
  // if one is a primitive, the other must be same
  if (util.isPrimitive(a) || util.isPrimitive(b))
    return a === b;
  if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
    return false;
  var aIsArgs = isArguments(a);
  var bIsArgs = isArguments(b);
  if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
    return false;
  if (aIsArgs) {
    a = pSlice.call(a);
    b = pSlice.call(b);
    return _deepEqual(a, b, strict);
  }
  var ka = objectKeys(a);
  var kb = objectKeys(b);
  var key, i;
  // having the same number of owned properties (keys incorporates
  // hasOwnProperty)
  if (ka.length !== kb.length)
    return false;
  //the same set of keys (although not necessarily the same order),
  ka.sort();
  kb.sort();
  //~~~cheap key test
  for (i = ka.length - 1; i >= 0; i--) {
    if (ka[i] !== kb[i])
      return false;
  }
  //equivalent values for every corresponding key, and
  //~~~possibly expensive deep test
  for (i = ka.length - 1; i >= 0; i--) {
    key = ka[i];
    if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
      return false;
  }
  return true;
}

// 8. The non-equivalence assertion tests for any deep inequality.
// assert.notDeepEqual(actual, expected, message_opt);

assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
  if (_deepEqual(actual, expected, false)) {
    fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
  }
};

assert.notDeepStrictEqual = notDeepStrictEqual;
function notDeepStrictEqual(actual, expected, message) {
  if (_deepEqual(actual, expected, true)) {
    fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
  }
}


// 9. The strict equality assertion tests strict equality, as determined by ===.
// assert.strictEqual(actual, expected, message_opt);

assert.strictEqual = function strictEqual(actual, expected, message) {
  if (actual !== expected) {
    fail(actual, expected, message, '===', assert.strictEqual);
  }
};

// 10. The strict non-equality assertion tests for strict inequality, as
// determined by !==.  assert.notStrictEqual(actual, expected, message_opt);

assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (actual === expected) {
    fail(actual, expected, message, '!==', assert.notStrictEqual);
  }
};

function expectedException(actual, expected) {
  if (!actual || !expected) {
    return false;
  }

  if (Object.prototype.toString.call(expected) == '[object RegExp]') {
    return expected.test(actual);
  }

  try {
    if (actual instanceof expected) {
      return true;
    }
  } catch (e) {
    // Ignore.  The instanceof check doesn't work for arrow functions.
  }

  if (Error.isPrototypeOf(expected)) {
    return false;
  }

  return expected.call({}, actual) === true;
}

function _tryBlock(block) {
  var error;
  try {
    block();
  } catch (e) {
    error = e;
  }
  return error;
}

function _throws(shouldThrow, block, expected, message) {
  var actual;

  if (typeof block !== 'function') {
    throw new TypeError('"block" argument must be a function');
  }

  if (typeof expected === 'string') {
    message = expected;
    expected = null;
  }

  actual = _tryBlock(block);

  message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
            (message ? ' ' + message : '.');

  if (shouldThrow && !actual) {
    fail(actual, expected, 'Missing expected exception' + message);
  }

  var userProvidedMessage = typeof message === 'string';
  var isUnwantedException = !shouldThrow && util.isError(actual);
  var isUnexpectedException = !shouldThrow && actual && !expected;

  if ((isUnwantedException &&
      userProvidedMessage &&
      expectedException(actual, expected)) ||
      isUnexpectedException) {
    fail(actual, expected, 'Got unwanted exception' + message);
  }

  if ((shouldThrow && actual && expected &&
      !expectedException(actual, expected)) || (!shouldThrow && actual)) {
    throw actual;
  }
}

// 11. Expected to throw an error:
// assert.throws(block, Error_opt, message_opt);

assert.throws = function(block, /*optional*/error, /*optional*/message) {
  _throws(true, block, error, message);
};

// EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
  _throws(false, block, error, message);
};

assert.ifError = function(err) { if (err) throw err; };

var objectKeys = Object.keys || function (obj) {
  var keys = [];
  for (var key in obj) {
    if (hasOwn.call(obj, key)) keys.push(key);
  }
  return keys;
};

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"util/":60}],58:[function(_dereq_,module,exports){
if (typeof Object.create === 'function') {
  // implementation from standard node.js 'util' module
  module.exports = function inherits(ctor, superCtor) {
    ctor.super_ = superCtor
    ctor.prototype = Object.create(superCtor.prototype, {
      constructor: {
        value: ctor,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
  };
} else {
  // old school shim for old browsers
  module.exports = function inherits(ctor, superCtor) {
    ctor.super_ = superCtor
    var TempCtor = function () {}
    TempCtor.prototype = superCtor.prototype
    ctor.prototype = new TempCtor()
    ctor.prototype.constructor = ctor
  }
}

},{}],59:[function(_dereq_,module,exports){
module.exports = function isBuffer(arg) {
  return arg && typeof arg === 'object'
    && typeof arg.copy === 'function'
    && typeof arg.fill === 'function'
    && typeof arg.readUInt8 === 'function';
}
},{}],60:[function(_dereq_,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.

var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
  if (!isString(f)) {
    var objects = [];
    for (var i = 0; i < arguments.length; i++) {
      objects.push(inspect(arguments[i]));
    }
    return objects.join(' ');
  }

  var i = 1;
  var args = arguments;
  var len = args.length;
  var str = String(f).replace(formatRegExp, function(x) {
    if (x === '%%') return '%';
    if (i >= len) return x;
    switch (x) {
      case '%s': return String(args[i++]);
      case '%d': return Number(args[i++]);
      case '%j':
        try {
          return JSON.stringify(args[i++]);
        } catch (_) {
          return '[Circular]';
        }
      default:
        return x;
    }
  });
  for (var x = args[i]; i < len; x = args[++i]) {
    if (isNull(x) || !isObject(x)) {
      str += ' ' + x;
    } else {
      str += ' ' + inspect(x);
    }
  }
  return str;
};


// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
  // Allow for deprecating things in the process of starting up.
  if (isUndefined(global.process)) {
    return function() {
      return exports.deprecate(fn, msg).apply(this, arguments);
    };
  }

  if (process.noDeprecation === true) {
    return fn;
  }

  var warned = false;
  function deprecated() {
    if (!warned) {
      if (process.throwDeprecation) {
        throw new Error(msg);
      } else if (process.traceDeprecation) {
        console.trace(msg);
      } else {
        console.error(msg);
      }
      warned = true;
    }
    return fn.apply(this, arguments);
  }

  return deprecated;
};


var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
  if (isUndefined(debugEnviron))
    debugEnviron = process.env.NODE_DEBUG || '';
  set = set.toUpperCase();
  if (!debugs[set]) {
    if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
      var pid = process.pid;
      debugs[set] = function() {
        var msg = exports.format.apply(exports, arguments);
        console.error('%s %d: %s', set, pid, msg);
      };
    } else {
      debugs[set] = function() {};
    }
  }
  return debugs[set];
};


/**
 * Echos the value of a value. Trys to print the value out
 * in the best way possible given the different types.
 *
 * @param {Object} obj The object to print out.
 * @param {Object} opts Optional options object that alters the output.
 */
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
  // default options
  var ctx = {
    seen: [],
    stylize: stylizeNoColor
  };
  // legacy...
  if (arguments.length >= 3) ctx.depth = arguments[2];
  if (arguments.length >= 4) ctx.colors = arguments[3];
  if (isBoolean(opts)) {
    // legacy...
    ctx.showHidden = opts;
  } else if (opts) {
    // got an "options" object
    exports._extend(ctx, opts);
  }
  // set default options
  if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  if (isUndefined(ctx.depth)) ctx.depth = 2;
  if (isUndefined(ctx.colors)) ctx.colors = false;
  if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  if (ctx.colors) ctx.stylize = stylizeWithColor;
  return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;


// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
  'bold' : [1, 22],
  'italic' : [3, 23],
  'underline' : [4, 24],
  'inverse' : [7, 27],
  'white' : [37, 39],
  'grey' : [90, 39],
  'black' : [30, 39],
  'blue' : [34, 39],
  'cyan' : [36, 39],
  'green' : [32, 39],
  'magenta' : [35, 39],
  'red' : [31, 39],
  'yellow' : [33, 39]
};

// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
  'special': 'cyan',
  'number': 'yellow',
  'boolean': 'yellow',
  'undefined': 'grey',
  'null': 'bold',
  'string': 'green',
  'date': 'magenta',
  // "name": intentionally not styling
  'regexp': 'red'
};


function stylizeWithColor(str, styleType) {
  var style = inspect.styles[styleType];

  if (style) {
    return '\u001b[' + inspect.colors[style][0] + 'm' + str +
           '\u001b[' + inspect.colors[style][1] + 'm';
  } else {
    return str;
  }
}


function stylizeNoColor(str, styleType) {
  return str;
}


function arrayToHash(array) {
  var hash = {};

  array.forEach(function(val, idx) {
    hash[val] = true;
  });

  return hash;
}


function formatValue(ctx, value, recurseTimes) {
  // Provide a hook for user-specified inspect functions.
  // Check that value is an object with an inspect function on it
  if (ctx.customInspect &&
      value &&
      isFunction(value.inspect) &&
      // Filter out the util module, it's inspect function is special
      value.inspect !== exports.inspect &&
      // Also filter out any prototype objects using the circular check.
      !(value.constructor && value.constructor.prototype === value)) {
    var ret = value.inspect(recurseTimes, ctx);
    if (!isString(ret)) {
      ret = formatValue(ctx, ret, recurseTimes);
    }
    return ret;
  }

  // Primitive types cannot have properties
  var primitive = formatPrimitive(ctx, value);
  if (primitive) {
    return primitive;
  }

  // Look up the keys of the object.
  var keys = Object.keys(value);
  var visibleKeys = arrayToHash(keys);

  if (ctx.showHidden) {
    keys = Object.getOwnPropertyNames(value);
  }

  // IE doesn't make error fields non-enumerable
  // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  if (isError(value)
      && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
    return formatError(value);
  }

  // Some type of object without properties can be shortcutted.
  if (keys.length === 0) {
    if (isFunction(value)) {
      var name = value.name ? ': ' + value.name : '';
      return ctx.stylize('[Function' + name + ']', 'special');
    }
    if (isRegExp(value)) {
      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
    }
    if (isDate(value)) {
      return ctx.stylize(Date.prototype.toString.call(value), 'date');
    }
    if (isError(value)) {
      return formatError(value);
    }
  }

  var base = '', array = false, braces = ['{', '}'];

  // Make Array say that they are Array
  if (isArray(value)) {
    array = true;
    braces = ['[', ']'];
  }

  // Make functions say that they are functions
  if (isFunction(value)) {
    var n = value.name ? ': ' + value.name : '';
    base = ' [Function' + n + ']';
  }

  // Make RegExps say that they are RegExps
  if (isRegExp(value)) {
    base = ' ' + RegExp.prototype.toString.call(value);
  }

  // Make dates with properties first say the date
  if (isDate(value)) {
    base = ' ' + Date.prototype.toUTCString.call(value);
  }

  // Make error with message first say the error
  if (isError(value)) {
    base = ' ' + formatError(value);
  }

  if (keys.length === 0 && (!array || value.length == 0)) {
    return braces[0] + base + braces[1];
  }

  if (recurseTimes < 0) {
    if (isRegExp(value)) {
      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
    } else {
      return ctx.stylize('[Object]', 'special');
    }
  }

  ctx.seen.push(value);

  var output;
  if (array) {
    output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  } else {
    output = keys.map(function(key) {
      return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
    });
  }

  ctx.seen.pop();

  return reduceToSingleString(output, base, braces);
}


function formatPrimitive(ctx, value) {
  if (isUndefined(value))
    return ctx.stylize('undefined', 'undefined');
  if (isString(value)) {
    var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
                                             .replace(/'/g, "\\'")
                                             .replace(/\\"/g, '"') + '\'';
    return ctx.stylize(simple, 'string');
  }
  if (isNumber(value))
    return ctx.stylize('' + value, 'number');
  if (isBoolean(value))
    return ctx.stylize('' + value, 'boolean');
  // For some reason typeof null is "object", so special case here.
  if (isNull(value))
    return ctx.stylize('null', 'null');
}


function formatError(value) {
  return '[' + Error.prototype.toString.call(value) + ']';
}


function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  var output = [];
  for (var i = 0, l = value.length; i < l; ++i) {
    if (hasOwnProperty(value, String(i))) {
      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
          String(i), true));
    } else {
      output.push('');
    }
  }
  keys.forEach(function(key) {
    if (!key.match(/^\d+$/)) {
      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
          key, true));
    }
  });
  return output;
}


function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  var name, str, desc;
  desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  if (desc.get) {
    if (desc.set) {
      str = ctx.stylize('[Getter/Setter]', 'special');
    } else {
      str = ctx.stylize('[Getter]', 'special');
    }
  } else {
    if (desc.set) {
      str = ctx.stylize('[Setter]', 'special');
    }
  }
  if (!hasOwnProperty(visibleKeys, key)) {
    name = '[' + key + ']';
  }
  if (!str) {
    if (ctx.seen.indexOf(desc.value) < 0) {
      if (isNull(recurseTimes)) {
        str = formatValue(ctx, desc.value, null);
      } else {
        str = formatValue(ctx, desc.value, recurseTimes - 1);
      }
      if (str.indexOf('\n') > -1) {
        if (array) {
          str = str.split('\n').map(function(line) {
            return '  ' + line;
          }).join('\n').substr(2);
        } else {
          str = '\n' + str.split('\n').map(function(line) {
            return '   ' + line;
          }).join('\n');
        }
      }
    } else {
      str = ctx.stylize('[Circular]', 'special');
    }
  }
  if (isUndefined(name)) {
    if (array && key.match(/^\d+$/)) {
      return str;
    }
    name = JSON.stringify('' + key);
    if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
      name = name.substr(1, name.length - 2);
      name = ctx.stylize(name, 'name');
    } else {
      name = name.replace(/'/g, "\\'")
                 .replace(/\\"/g, '"')
                 .replace(/(^"|"$)/g, "'");
      name = ctx.stylize(name, 'string');
    }
  }

  return name + ': ' + str;
}


function reduceToSingleString(output, base, braces) {
  var numLinesEst = 0;
  var length = output.reduce(function(prev, cur) {
    numLinesEst++;
    if (cur.indexOf('\n') >= 0) numLinesEst++;
    return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  }, 0);

  if (length > 60) {
    return braces[0] +
           (base === '' ? '' : base + '\n ') +
           ' ' +
           output.join(',\n  ') +
           ' ' +
           braces[1];
  }

  return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}


// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
  return Array.isArray(ar);
}
exports.isArray = isArray;

function isBoolean(arg) {
  return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;

function isNull(arg) {
  return arg === null;
}
exports.isNull = isNull;

function isNullOrUndefined(arg) {
  return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;

function isNumber(arg) {
  return typeof arg === 'number';
}
exports.isNumber = isNumber;

function isString(arg) {
  return typeof arg === 'string';
}
exports.isString = isString;

function isSymbol(arg) {
  return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;

function isUndefined(arg) {
  return arg === void 0;
}
exports.isUndefined = isUndefined;

function isRegExp(re) {
  return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;

function isObject(arg) {
  return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;

function isDate(d) {
  return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;

function isError(e) {
  return isObject(e) &&
      (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;

function isFunction(arg) {
  return typeof arg === 'function';
}
exports.isFunction = isFunction;

function isPrimitive(arg) {
  return arg === null ||
         typeof arg === 'boolean' ||
         typeof arg === 'number' ||
         typeof arg === 'string' ||
         typeof arg === 'symbol' ||  // ES6 symbol
         typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;

exports.isBuffer = _dereq_('./support/isBuffer');

function objectToString(o) {
  return Object.prototype.toString.call(o);
}


function pad(n) {
  return n < 10 ? '0' + n.toString(10) : n.toString(10);
}


var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
              'Oct', 'Nov', 'Dec'];

// 26 Feb 16:19:34
function timestamp() {
  var d = new Date();
  var time = [pad(d.getHours()),
              pad(d.getMinutes()),
              pad(d.getSeconds())].join(':');
  return [d.getDate(), months[d.getMonth()], time].join(' ');
}


// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
  console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};


/**
 * Inherit the prototype methods from one constructor into another.
 *
 * The Function.prototype.inherits from lang.js rewritten as a standalone
 * function (not on Function.prototype). NOTE: If this file is to be loaded
 * during bootstrapping this function needs to be rewritten using some native
 * functions as prototype setup using normal JavaScript does not work as
 * expected during bootstrapping (see mirror.js in r114903).
 *
 * @param {function} ctor Constructor function which needs to inherit the
 *     prototype.
 * @param {function} superCtor Constructor function to inherit prototype from.
 */
exports.inherits = _dereq_('inherits');

exports._extend = function(origin, add) {
  // Don't do anything if add isn't an object
  if (!add || !isObject(add)) return origin;

  var keys = Object.keys(add);
  var i = keys.length;
  while (i--) {
    origin[keys[i]] = add[keys[i]];
  }
  return origin;
};

function hasOwnProperty(obj, prop) {
  return Object.prototype.hasOwnProperty.call(obj, prop);
}

}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":59,"_process":468,"inherits":58}],61:[function(_dereq_,module,exports){
module.exports = function _atob(str) {
  return atob(str)
}

},{}],62:[function(_dereq_,module,exports){
'use strict'

module.exports = barycentric

var solve = _dereq_('robust-linear-solve')

function reduce(x) {
  var r = 0
  for(var i=0; i<x.length; ++i) {
    r += x[i]
  }
  return r
}

function barycentric(simplex, point) {
  var d = point.length
  var A = new Array(d+1)
  for(var i=0; i<d; ++i) {
    var row = new Array(d+1)
    for(var j=0; j<=d; ++j) {
      row[j] = simplex[j][i]
    }
    A[i] = row
  }
  A[d] = new Array(d+1)
  for(var i=0; i<=d; ++i) {
    A[d][i] = 1
  }

  var b = new Array(d+1)
  for(var i=0; i<d; ++i) {
    b[i] = point[i]
  }
  b[d] = 1.0

  var x = solve(A, b)
  var w = reduce(x[d+1])
  
  if(w === 0) {
    w = 1.0
  }
  var y = new Array(d+1)
  for(var i=0; i<=d; ++i) {
    y[i] = reduce(x[i]) / w
  }
  return y
}
},{"robust-linear-solve":487}],63:[function(_dereq_,module,exports){
'use strict'

exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray

var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array

var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
  lookup[i] = code[i]
  revLookup[code.charCodeAt(i)] = i
}

// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63

function getLens (b64) {
  var len = b64.length

  if (len % 4 > 0) {
    throw new Error('Invalid string. Length must be a multiple of 4')
  }

  // Trim off extra bytes after placeholder bytes are found
  // See: https://github.com/beatgammit/base64-js/issues/42
  var validLen = b64.indexOf('=')
  if (validLen === -1) validLen = len

  var placeHoldersLen = validLen === len
    ? 0
    : 4 - (validLen % 4)

  return [validLen, placeHoldersLen]
}

// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function _byteLength (b64, validLen, placeHoldersLen) {
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function toByteArray (b64) {
  var tmp
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]

  var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))

  var curByte = 0

  // if there are placeholders, only get up to the last complete 4 chars
  var len = placeHoldersLen > 0
    ? validLen - 4
    : validLen

  for (var i = 0; i < len; i += 4) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 18) |
      (revLookup[b64.charCodeAt(i + 1)] << 12) |
      (revLookup[b64.charCodeAt(i + 2)] << 6) |
      revLookup[b64.charCodeAt(i + 3)]
    arr[curByte++] = (tmp >> 16) & 0xFF
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 2) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 2) |
      (revLookup[b64.charCodeAt(i + 1)] >> 4)
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 1) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 10) |
      (revLookup[b64.charCodeAt(i + 1)] << 4) |
      (revLookup[b64.charCodeAt(i + 2)] >> 2)
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  return arr
}

function tripletToBase64 (num) {
  return lookup[num >> 18 & 0x3F] +
    lookup[num >> 12 & 0x3F] +
    lookup[num >> 6 & 0x3F] +
    lookup[num & 0x3F]
}

function encodeChunk (uint8, start, end) {
  var tmp
  var output = []
  for (var i = start; i < end; i += 3) {
    tmp =
      ((uint8[i] << 16) & 0xFF0000) +
      ((uint8[i + 1] << 8) & 0xFF00) +
      (uint8[i + 2] & 0xFF)
    output.push(tripletToBase64(tmp))
  }
  return output.join('')
}

function fromByteArray (uint8) {
  var tmp
  var len = uint8.length
  var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  var parts = []
  var maxChunkLength = 16383 // must be multiple of 3

  // go through the array every three bytes, we'll deal with trailing stuff later
  for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
    parts.push(encodeChunk(
      uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
    ))
  }

  // pad the end with zeros, but make sure to not forget the extra bytes
  if (extraBytes === 1) {
    tmp = uint8[len - 1]
    parts.push(
      lookup[tmp >> 2] +
      lookup[(tmp << 4) & 0x3F] +
      '=='
    )
  } else if (extraBytes === 2) {
    tmp = (uint8[len - 2] << 8) + uint8[len - 1]
    parts.push(
      lookup[tmp >> 10] +
      lookup[(tmp >> 4) & 0x3F] +
      lookup[(tmp << 2) & 0x3F] +
      '='
    )
  }

  return parts.join('')
}

},{}],64:[function(_dereq_,module,exports){
'use strict'

var rationalize = _dereq_('./lib/rationalize')

module.exports = add

function add(a, b) {
  return rationalize(
    a[0].mul(b[1]).add(b[0].mul(a[1])),
    a[1].mul(b[1]))
}

},{"./lib/rationalize":74}],65:[function(_dereq_,module,exports){
'use strict'

module.exports = cmp

function cmp(a, b) {
    return a[0].mul(b[1]).cmp(b[0].mul(a[1]))
}

},{}],66:[function(_dereq_,module,exports){
'use strict'

var rationalize = _dereq_('./lib/rationalize')

module.exports = div

function div(a, b) {
  return rationalize(a[0].mul(b[1]), a[1].mul(b[0]))
}

},{"./lib/rationalize":74}],67:[function(_dereq_,module,exports){
'use strict'

var isRat = _dereq_('./is-rat')
var isBN = _dereq_('./lib/is-bn')
var num2bn = _dereq_('./lib/num-to-bn')
var str2bn = _dereq_('./lib/str-to-bn')
var rationalize = _dereq_('./lib/rationalize')
var div = _dereq_('./div')

module.exports = makeRational

function makeRational(numer, denom) {
  if(isRat(numer)) {
    if(denom) {
      return div(numer, makeRational(denom))
    }
    return [numer[0].clone(), numer[1].clone()]
  }
  var shift = 0
  var a, b
  if(isBN(numer)) {
    a = numer.clone()
  } else if(typeof numer === 'string') {
    a = str2bn(numer)
  } else if(numer === 0) {
    return [num2bn(0), num2bn(1)]
  } else if(numer === Math.floor(numer)) {
    a = num2bn(numer)
  } else {
    while(numer !== Math.floor(numer)) {
      numer = numer * Math.pow(2, 256)
      shift -= 256
    }
    a = num2bn(numer)
  }
  if(isRat(denom)) {
    a.mul(denom[1])
    b = denom[0].clone()
  } else if(isBN(denom)) {
    b = denom.clone()
  } else if(typeof denom === 'string') {
    b = str2bn(denom)
  } else if(!denom) {
    b = num2bn(1)
  } else if(denom === Math.floor(denom)) {
    b = num2bn(denom)
  } else {
    while(denom !== Math.floor(denom)) {
      denom = denom * Math.pow(2, 256)
      shift += 256
    }
    b = num2bn(denom)
  }
  if(shift > 0) {
    a = a.ushln(shift)
  } else if(shift < 0) {
    b = b.ushln(-shift)
  }
  return rationalize(a, b)
}

},{"./div":66,"./is-rat":68,"./lib/is-bn":72,"./lib/num-to-bn":73,"./lib/rationalize":74,"./lib/str-to-bn":75}],68:[function(_dereq_,module,exports){
'use strict'

var isBN = _dereq_('./lib/is-bn')

module.exports = isRat

function isRat(x) {
  return Array.isArray(x) && x.length === 2 && isBN(x[0]) && isBN(x[1])
}

},{"./lib/is-bn":72}],69:[function(_dereq_,module,exports){
'use strict'

var BN = _dereq_('bn.js')

module.exports = sign

function sign (x) {
  return x.cmp(new BN(0))
}

},{"bn.js":83}],70:[function(_dereq_,module,exports){
'use strict'

var sign = _dereq_('./bn-sign')

module.exports = bn2num

//TODO: Make this better
function bn2num(b) {
  var l = b.length
  var words = b.words
  var out = 0
  if (l === 1) {
    out = words[0]
  } else if (l === 2) {
    out = words[0] + (words[1] * 0x4000000)
  } else {
    for (var i = 0; i < l; i++) {
      var w = words[i]
      out += w * Math.pow(0x4000000, i)
    }
  }
  return sign(b) * out
}

},{"./bn-sign":69}],71:[function(_dereq_,module,exports){
'use strict'

var db = _dereq_('double-bits')
var ctz = _dereq_('bit-twiddle').countTrailingZeros

module.exports = ctzNumber

//Counts the number of trailing zeros
function ctzNumber(x) {
  var l = ctz(db.lo(x))
  if(l < 32) {
    return l
  }
  var h = ctz(db.hi(x))
  if(h > 20) {
    return 52
  }
  return h + 32
}

},{"bit-twiddle":81,"double-bits":153}],72:[function(_dereq_,module,exports){
'use strict'

var BN = _dereq_('bn.js')

module.exports = isBN

//Test if x is a bignumber
//FIXME: obviously this is the wrong way to do it
function isBN(x) {
  return x && typeof x === 'object' && Boolean(x.words)
}

},{"bn.js":83}],73:[function(_dereq_,module,exports){
'use strict'

var BN = _dereq_('bn.js')
var db = _dereq_('double-bits')

module.exports = num2bn

function num2bn(x) {
  var e = db.exponent(x)
  if(e < 52) {
    return new BN(x)
  } else {
    return (new BN(x * Math.pow(2, 52-e))).ushln(e-52)
  }
}

},{"bn.js":83,"double-bits":153}],74:[function(_dereq_,module,exports){
'use strict'

var num2bn = _dereq_('./num-to-bn')
var sign = _dereq_('./bn-sign')

module.exports = rationalize

function rationalize(numer, denom) {
  var snumer = sign(numer)
  var sdenom = sign(denom)
  if(snumer === 0) {
    return [num2bn(0), num2bn(1)]
  }
  if(sdenom === 0) {
    return [num2bn(0), num2bn(0)]
  }
  if(sdenom < 0) {
    numer = numer.neg()
    denom = denom.neg()
  }
  var d = numer.gcd(denom)
  if(d.cmpn(1)) {
    return [ numer.div(d), denom.div(d) ]
  }
  return [ numer, denom ]
}

},{"./bn-sign":69,"./num-to-bn":73}],75:[function(_dereq_,module,exports){
'use strict'

var BN = _dereq_('bn.js')

module.exports = str2BN

function str2BN(x) {
  return new BN(x)
}

},{"bn.js":83}],76:[function(_dereq_,module,exports){
'use strict'

var rationalize = _dereq_('./lib/rationalize')

module.exports = mul

function mul(a, b) {
  return rationalize(a[0].mul(b[0]), a[1].mul(b[1]))
}

},{"./lib/rationalize":74}],77:[function(_dereq_,module,exports){
'use strict'

var bnsign = _dereq_('./lib/bn-sign')

module.exports = sign

function sign(x) {
  return bnsign(x[0]) * bnsign(x[1])
}

},{"./lib/bn-sign":69}],78:[function(_dereq_,module,exports){
'use strict'

var rationalize = _dereq_('./lib/rationalize')

module.exports = sub

function sub(a, b) {
  return rationalize(a[0].mul(b[1]).sub(a[1].mul(b[0])), a[1].mul(b[1]))
}

},{"./lib/rationalize":74}],79:[function(_dereq_,module,exports){
'use strict'

var bn2num = _dereq_('./lib/bn-to-num')
var ctz = _dereq_('./lib/ctz')

module.exports = roundRat

// Round a rational to the closest float
function roundRat (f) {
  var a = f[0]
  var b = f[1]
  if (a.cmpn(0) === 0) {
    return 0
  }
  var h = a.abs().divmod(b.abs())
  var iv = h.div
  var x = bn2num(iv)
  var ir = h.mod
  var sgn = (a.negative !== b.negative) ? -1 : 1
  if (ir.cmpn(0) === 0) {
    return sgn * x
  }
  if (x) {
    var s = ctz(x) + 4
    var y = bn2num(ir.ushln(s).divRound(b))
    return sgn * (x + y * Math.pow(2, -s))
  } else {
    var ybits = b.bitLength() - ir.bitLength() + 53
    var y = bn2num(ir.ushln(ybits).divRound(b))
    if (ybits < 1023) {
      return sgn * y * Math.pow(2, -ybits)
    }
    y *= Math.pow(2, -1023)
    return sgn * y * Math.pow(2, 1023 - ybits)
  }
}

},{"./lib/bn-to-num":70,"./lib/ctz":71}],80:[function(_dereq_,module,exports){
"use strict"

function compileSearch(funcName, predicate, reversed, extraArgs, useNdarray, earlyOut) {
  var code = [
    "function ", funcName, "(a,l,h,", extraArgs.join(","),  "){",
earlyOut ? "" : "var i=", (reversed ? "l-1" : "h+1"),
";while(l<=h){\
var m=(l+h)>>>1,x=a", useNdarray ? ".get(m)" : "[m]"]
  if(earlyOut) {
    if(predicate.indexOf("c") < 0) {
      code.push(";if(x===y){return m}else if(x<=y){")
    } else {
      code.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){")
    }
  } else {
    code.push(";if(", predicate, "){i=m;")
  }
  if(reversed) {
    code.push("l=m+1}else{h=m-1}")
  } else {
    code.push("h=m-1}else{l=m+1}")
  }
  code.push("}")
  if(earlyOut) {
    code.push("return -1};")
  } else {
    code.push("return i};")
  }
  return code.join("")
}

function compileBoundsSearch(predicate, reversed, suffix, earlyOut) {
  var result = new Function([
  compileSearch("A", "x" + predicate + "y", reversed, ["y"], false, earlyOut),
  compileSearch("B", "x" + predicate + "y", reversed, ["y"], true, earlyOut),
  compileSearch("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], false, earlyOut),
  compileSearch("Q", "c(x,y)" + predicate + "0", reversed, ["y", "c"], true, earlyOut),
"function dispatchBsearch", suffix, "(a,y,c,l,h){\
if(a.shape){\
if(typeof(c)==='function'){\
return Q(a,(l===undefined)?0:l|0,(h===undefined)?a.shape[0]-1:h|0,y,c)\
}else{\
return B(a,(c===undefined)?0:c|0,(l===undefined)?a.shape[0]-1:l|0,y)\
}}else{\
if(typeof(c)==='function'){\
return P(a,(l===undefined)?0:l|0,(h===undefined)?a.length-1:h|0,y,c)\
}else{\
return A(a,(c===undefined)?0:c|0,(l===undefined)?a.length-1:l|0,y)\
}}}\
return dispatchBsearch", suffix].join(""))
  return result()
}

module.exports = {
  ge: compileBoundsSearch(">=", false, "GE"),
  gt: compileBoundsSearch(">", false, "GT"),
  lt: compileBoundsSearch("<", true, "LT"),
  le: compileBoundsSearch("<=", true, "LE"),
  eq: compileBoundsSearch("-", true, "EQ", true)
}

},{}],81:[function(_dereq_,module,exports){
/**
 * Bit twiddling hacks for JavaScript.
 *
 * Author: Mikola Lysenko
 *
 * Ported from Stanford bit twiddling hack library:
 *    http://graphics.stanford.edu/~seander/bithacks.html
 */

"use strict"; "use restrict";

//Number of bits in an integer
var INT_BITS = 32;

//Constants
exports.INT_BITS  = INT_BITS;
exports.INT_MAX   =  0x7fffffff;
exports.INT_MIN   = -1<<(INT_BITS-1);

//Returns -1, 0, +1 depending on sign of x
exports.sign = function(v) {
  return (v > 0) - (v < 0);
}

//Computes absolute value of integer
exports.abs = function(v) {
  var mask = v >> (INT_BITS-1);
  return (v ^ mask) - mask;
}

//Computes minimum of integers x and y
exports.min = function(x, y) {
  return y ^ ((x ^ y) & -(x < y));
}

//Computes maximum of integers x and y
exports.max = function(x, y) {
  return x ^ ((x ^ y) & -(x < y));
}

//Checks if a number is a power of two
exports.isPow2 = function(v) {
  return !(v & (v-1)) && (!!v);
}

//Computes log base 2 of v
exports.log2 = function(v) {
  var r, shift;
  r =     (v > 0xFFFF) << 4; v >>>= r;
  shift = (v > 0xFF  ) << 3; v >>>= shift; r |= shift;
  shift = (v > 0xF   ) << 2; v >>>= shift; r |= shift;
  shift = (v > 0x3   ) << 1; v >>>= shift; r |= shift;
  return r | (v >> 1);
}

//Computes log base 10 of v
exports.log10 = function(v) {
  return  (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 :
          (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 :
          (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0;
}

//Counts number of bits
exports.popCount = function(v) {
  v = v - ((v >>> 1) & 0x55555555);
  v = (v & 0x33333333) + ((v >>> 2) & 0x33333333);
  return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24;
}

//Counts number of trailing zeros
function countTrailingZeros(v) {
  var c = 32;
  v &= -v;
  if (v) c--;
  if (v & 0x0000FFFF) c -= 16;
  if (v & 0x00FF00FF) c -= 8;
  if (v & 0x0F0F0F0F) c -= 4;
  if (v & 0x33333333) c -= 2;
  if (v & 0x55555555) c -= 1;
  return c;
}
exports.countTrailingZeros = countTrailingZeros;

//Rounds to next power of 2
exports.nextPow2 = function(v) {
  v += v === 0;
  --v;
  v |= v >>> 1;
  v |= v >>> 2;
  v |= v >>> 4;
  v |= v >>> 8;
  v |= v >>> 16;
  return v + 1;
}

//Rounds down to previous power of 2
exports.prevPow2 = function(v) {
  v |= v >>> 1;
  v |= v >>> 2;
  v |= v >>> 4;
  v |= v >>> 8;
  v |= v >>> 16;
  return v - (v>>>1);
}

//Computes parity of word
exports.parity = function(v) {
  v ^= v >>> 16;
  v ^= v >>> 8;
  v ^= v >>> 4;
  v &= 0xf;
  return (0x6996 >>> v) & 1;
}

var REVERSE_TABLE = new Array(256);

(function(tab) {
  for(var i=0; i<256; ++i) {
    var v = i, r = i, s = 7;
    for (v >>>= 1; v; v >>>= 1) {
      r <<= 1;
      r |= v & 1;
      --s;
    }
    tab[i] = (r << s) & 0xff;
  }
})(REVERSE_TABLE);

//Reverse bits in a 32 bit word
exports.reverse = function(v) {
  return  (REVERSE_TABLE[ v         & 0xff] << 24) |
          (REVERSE_TABLE[(v >>> 8)  & 0xff] << 16) |
          (REVERSE_TABLE[(v >>> 16) & 0xff] << 8)  |
           REVERSE_TABLE[(v >>> 24) & 0xff];
}

//Interleave bits of 2 coordinates with 16 bits.  Useful for fast quadtree codes
exports.interleave2 = function(x, y) {
  x &= 0xFFFF;
  x = (x | (x << 8)) & 0x00FF00FF;
  x = (x | (x << 4)) & 0x0F0F0F0F;
  x = (x | (x << 2)) & 0x33333333;
  x = (x | (x << 1)) & 0x55555555;

  y &= 0xFFFF;
  y = (y | (y << 8)) & 0x00FF00FF;
  y = (y | (y << 4)) & 0x0F0F0F0F;
  y = (y | (y << 2)) & 0x33333333;
  y = (y | (y << 1)) & 0x55555555;

  return x | (y << 1);
}

//Extracts the nth interleaved component
exports.deinterleave2 = function(v, n) {
  v = (v >>> n) & 0x55555555;
  v = (v | (v >>> 1))  & 0x33333333;
  v = (v | (v >>> 2))  & 0x0F0F0F0F;
  v = (v | (v >>> 4))  & 0x00FF00FF;
  v = (v | (v >>> 16)) & 0x000FFFF;
  return (v << 16) >> 16;
}


//Interleave bits of 3 coordinates, each with 10 bits.  Useful for fast octree codes
exports.interleave3 = function(x, y, z) {
  x &= 0x3FF;
  x  = (x | (x<<16)) & 4278190335;
  x  = (x | (x<<8))  & 251719695;
  x  = (x | (x<<4))  & 3272356035;
  x  = (x | (x<<2))  & 1227133513;

  y &= 0x3FF;
  y  = (y | (y<<16)) & 4278190335;
  y  = (y | (y<<8))  & 251719695;
  y  = (y | (y<<4))  & 3272356035;
  y  = (y | (y<<2))  & 1227133513;
  x |= (y << 1);
  
  z &= 0x3FF;
  z  = (z | (z<<16)) & 4278190335;
  z  = (z | (z<<8))  & 251719695;
  z  = (z | (z<<4))  & 3272356035;
  z  = (z | (z<<2))  & 1227133513;
  
  return x | (z << 2);
}

//Extracts nth interleaved component of a 3-tuple
exports.deinterleave3 = function(v, n) {
  v = (v >>> n)       & 1227133513;
  v = (v | (v>>>2))   & 3272356035;
  v = (v | (v>>>4))   & 251719695;
  v = (v | (v>>>8))   & 4278190335;
  v = (v | (v>>>16))  & 0x3FF;
  return (v<<22)>>22;
}

//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page)
exports.nextCombination = function(v) {
  var t = v | (v - 1);
  return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1));
}


},{}],82:[function(_dereq_,module,exports){
'use strict'

var clamp = _dereq_('clamp')

module.exports = calcSDF

var INF = 1e20;

function calcSDF(src, options) {
    if (!options) options = {}

    var cutoff = options.cutoff == null ? 0.25 : options.cutoff
    var radius = options.radius == null ? 8 : options.radius
    var channel = options.channel || 0
    var w, h, size, data, intData, stride, ctx, canvas, imgData, i, l

    // handle image container
    if (ArrayBuffer.isView(src) || Array.isArray(src)) {
        if (!options.width || !options.height) throw Error('For raw data width and height should be provided by options')
        w = options.width, h = options.height
        data = src

        if (!options.stride) stride = Math.floor(src.length / w / h)
        else stride = options.stride
    }
    else {
        if (window.HTMLCanvasElement && src instanceof window.HTMLCanvasElement) {
            canvas = src
            ctx = canvas.getContext('2d')
            w = canvas.width, h = canvas.height
            imgData = ctx.getImageData(0, 0, w, h)
            data = imgData.data
            stride = 4
        }
        else if (window.CanvasRenderingContext2D && src instanceof window.CanvasRenderingContext2D) {
            canvas = src.canvas
            ctx = src
            w = canvas.width, h = canvas.height
            imgData = ctx.getImageData(0, 0, w, h)
            data = imgData.data
            stride = 4
        }
        else if (window.ImageData && src instanceof window.ImageData) {
            imgData = src
            w = src.width, h = src.height
            data = imgData.data
            stride = 4
        }
    }

    size = Math.max(w, h)

    //convert int data to floats
    if ((window.Uint8ClampedArray && data instanceof window.Uint8ClampedArray) || (window.Uint8Array && data instanceof window.Uint8Array)) {
        intData = data
        data = Array(w*h)

        for (i = 0, l = intData.length; i < l; i++) {
            data[i] = intData[i*stride + channel] / 255
        }
    }
    else {
        if (stride !== 1) throw Error('Raw data can have only 1 value per pixel')
    }

    // temporary arrays for the distance transform
    var gridOuter = Array(w * h)
    var gridInner = Array(w * h)
    var f = Array(size)
    var d = Array(size)
    var z = Array(size + 1)
    var v = Array(size)

    for (i = 0, l = w * h; i < l; i++) {
        var a = data[i]
        gridOuter[i] = a === 1 ? 0 : a === 0 ? INF : Math.pow(Math.max(0, 0.5 - a), 2)
        gridInner[i] = a === 1 ? INF : a === 0 ? 0 : Math.pow(Math.max(0, a - 0.5), 2)
    }

    edt(gridOuter, w, h, f, d, v, z)
    edt(gridInner, w, h, f, d, v, z)

    var dist = window.Float32Array ? new Float32Array(w * h) : new Array(w * h)

    for (i = 0, l = w*h; i < l; i++) {
        dist[i] = clamp(1 - ( (gridOuter[i] - gridInner[i]) / radius + cutoff), 0, 1)
    }

    return dist
}

// 2D Euclidean distance transform by Felzenszwalb & Huttenlocher https://cs.brown.edu/~pff/dt/
function edt(data, width, height, f, d, v, z) {
    for (var x = 0; x < width; x++) {
        for (var y = 0; y < height; y++) {
            f[y] = data[y * width + x]
        }
        edt1d(f, d, v, z, height)
        for (y = 0; y < height; y++) {
            data[y * width + x] = d[y]
        }
    }
    for (y = 0; y < height; y++) {
        for (x = 0; x < width; x++) {
            f[x] = data[y * width + x]
        }
        edt1d(f, d, v, z, width)
        for (x = 0; x < width; x++) {
            data[y * width + x] = Math.sqrt(d[x])
        }
    }
}

// 1D squared distance transform
function edt1d(f, d, v, z, n) {
    v[0] = 0;
    z[0] = -INF
    z[1] = +INF

    for (var q = 1, k = 0; q < n; q++) {
        var s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k])
        while (s <= z[k]) {
            k--
            s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k])
        }
        k++
        v[k] = q
        z[k] = s
        z[k + 1] = +INF
    }

    for (q = 0, k = 0; q < n; q++) {
        while (z[k + 1] < q) k++
        d[q] = (q - v[k]) * (q - v[k]) + f[v[k]]
    }
}

},{"clamp":104}],83:[function(_dereq_,module,exports){
(function (module, exports) {
  'use strict';

  // Utils
  function assert (val, msg) {
    if (!val) throw new Error(msg || 'Assertion failed');
  }

  // Could use `inherits` module, but don't want to move from single file
  // architecture yet.
  function inherits (ctor, superCtor) {
    ctor.super_ = superCtor;
    var TempCtor = function () {};
    TempCtor.prototype = superCtor.prototype;
    ctor.prototype = new TempCtor();
    ctor.prototype.constructor = ctor;
  }

  // BN

  function BN (number, base, endian) {
    if (BN.isBN(number)) {
      return number;
    }

    this.negative = 0;
    this.words = null;
    this.length = 0;

    // Reduction context
    this.red = null;

    if (number !== null) {
      if (base === 'le' || base === 'be') {
        endian = base;
        base = 10;
      }

      this._init(number || 0, base || 10, endian || 'be');
    }
  }
  if (typeof module === 'object') {
    module.exports = BN;
  } else {
    exports.BN = BN;
  }

  BN.BN = BN;
  BN.wordSize = 26;

  var Buffer;
  try {
    Buffer = _dereq_('buffer').Buffer;
  } catch (e) {
  }

  BN.isBN = function isBN (num) {
    if (num instanceof BN) {
      return true;
    }

    return num !== null && typeof num === 'object' &&
      num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
  };

  BN.max = function max (left, right) {
    if (left.cmp(right) > 0) return left;
    return right;
  };

  BN.min = function min (left, right) {
    if (left.cmp(right) < 0) return left;
    return right;
  };

  BN.prototype._init = function init (number, base, endian) {
    if (typeof number === 'number') {
      return this._initNumber(number, base, endian);
    }

    if (typeof number === 'object') {
      return this._initArray(number, base, endian);
    }

    if (base === 'hex') {
      base = 16;
    }
    assert(base === (base | 0) && base >= 2 && base <= 36);

    number = number.toString().replace(/\s+/g, '');
    var start = 0;
    if (number[0] === '-') {
      start++;
    }

    if (base === 16) {
      this._parseHex(number, start);
    } else {
      this._parseBase(number, base, start);
    }

    if (number[0] === '-') {
      this.negative = 1;
    }

    this.strip();

    if (endian !== 'le') return;

    this._initArray(this.toArray(), base, endian);
  };

  BN.prototype._initNumber = function _initNumber (number, base, endian) {
    if (number < 0) {
      this.negative = 1;
      number = -number;
    }
    if (number < 0x4000000) {
      this.words = [ number & 0x3ffffff ];
      this.length = 1;
    } else if (number < 0x10000000000000) {
      this.words = [
        number & 0x3ffffff,
        (number / 0x4000000) & 0x3ffffff
      ];
      this.length = 2;
    } else {
      assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
      this.words = [
        number & 0x3ffffff,
        (number / 0x4000000) & 0x3ffffff,
        1
      ];
      this.length = 3;
    }

    if (endian !== 'le') return;

    // Reverse the bytes
    this._initArray(this.toArray(), base, endian);
  };

  BN.prototype._initArray = function _initArray (number, base, endian) {
    // Perhaps a Uint8Array
    assert(typeof number.length === 'number');
    if (number.length <= 0) {
      this.words = [ 0 ];
      this.length = 1;
      return this;
    }

    this.length = Math.ceil(number.length / 3);
    this.words = new Array(this.length);
    for (var i = 0; i < this.length; i++) {
      this.words[i] = 0;
    }

    var j, w;
    var off = 0;
    if (endian === 'be') {
      for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
        w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
        this.words[j] |= (w << off) & 0x3ffffff;
        this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
        off += 24;
        if (off >= 26) {
          off -= 26;
          j++;
        }
      }
    } else if (endian === 'le') {
      for (i = 0, j = 0; i < number.length; i += 3) {
        w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
        this.words[j] |= (w << off) & 0x3ffffff;
        this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
        off += 24;
        if (off >= 26) {
          off -= 26;
          j++;
        }
      }
    }
    return this.strip();
  };

  function parseHex (str, start, end) {
    var r = 0;
    var len = Math.min(str.length, end);
    for (var i = start; i < len; i++) {
      var c = str.charCodeAt(i) - 48;

      r <<= 4;

      // 'a' - 'f'
      if (c >= 49 && c <= 54) {
        r |= c - 49 + 0xa;

      // 'A' - 'F'
      } else if (c >= 17 && c <= 22) {
        r |= c - 17 + 0xa;

      // '0' - '9'
      } else {
        r |= c & 0xf;
      }
    }
    return r;
  }

  BN.prototype._parseHex = function _parseHex (number, start) {
    // Create possibly bigger array to ensure that it fits the number
    this.length = Math.ceil((number.length - start) / 6);
    this.words = new Array(this.length);
    for (var i = 0; i < this.length; i++) {
      this.words[i] = 0;
    }

    var j, w;
    // Scan 24-bit chunks and add them to the number
    var off = 0;
    for (i = number.length - 6, j = 0; i >= start; i -= 6) {
      w = parseHex(number, i, i + 6);
      this.words[j] |= (w << off) & 0x3ffffff;
      // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
      this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
      off += 24;
      if (off >= 26) {
        off -= 26;
        j++;
      }
    }
    if (i + 6 !== start) {
      w = parseHex(number, start, i + 6);
      this.words[j] |= (w << off) & 0x3ffffff;
      this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
    }
    this.strip();
  };

  function parseBase (str, start, end, mul) {
    var r = 0;
    var len = Math.min(str.length, end);
    for (var i = start; i < len; i++) {
      var c = str.charCodeAt(i) - 48;

      r *= mul;

      // 'a'
      if (c >= 49) {
        r += c - 49 + 0xa;

      // 'A'
      } else if (c >= 17) {
        r += c - 17 + 0xa;

      // '0' - '9'
      } else {
        r += c;
      }
    }
    return r;
  }

  BN.prototype._parseBase = function _parseBase (number, base, start) {
    // Initialize as zero
    this.words = [ 0 ];
    this.length = 1;

    // Find length of limb in base
    for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
      limbLen++;
    }
    limbLen--;
    limbPow = (limbPow / base) | 0;

    var total = number.length - start;
    var mod = total % limbLen;
    var end = Math.min(total, total - mod) + start;

    var word = 0;
    for (var i = start; i < end; i += limbLen) {
      word = parseBase(number, i, i + limbLen, base);

      this.imuln(limbPow);
      if (this.words[0] + word < 0x4000000) {
        this.words[0] += word;
      } else {
        this._iaddn(word);
      }
    }

    if (mod !== 0) {
      var pow = 1;
      word = parseBase(number, i, number.length, base);

      for (i = 0; i < mod; i++) {
        pow *= base;
      }

      this.imuln(pow);
      if (this.words[0] + word < 0x4000000) {
        this.words[0] += word;
      } else {
        this._iaddn(word);
      }
    }
  };

  BN.prototype.copy = function copy (dest) {
    dest.words = new Array(this.length);
    for (var i = 0; i < this.length; i++) {
      dest.words[i] = this.words[i];
    }
    dest.length = this.length;
    dest.negative = this.negative;
    dest.red = this.red;
  };

  BN.prototype.clone = function clone () {
    var r = new BN(null);
    this.copy(r);
    return r;
  };

  BN.prototype._expand = function _expand (size) {
    while (this.length < size) {
      this.words[this.length++] = 0;
    }
    return this;
  };

  // Remove leading `0` from `this`
  BN.prototype.strip = function strip () {
    while (this.length > 1 && this.words[this.length - 1] === 0) {
      this.length--;
    }
    return this._normSign();
  };

  BN.prototype._normSign = function _normSign () {
    // -0 = 0
    if (this.length === 1 && this.words[0] === 0) {
      this.negative = 0;
    }
    return this;
  };

  BN.prototype.inspect = function inspect () {
    return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
  };

  /*

  var zeros = [];
  var groupSizes = [];
  var groupBases = [];

  var s = '';
  var i = -1;
  while (++i < BN.wordSize) {
    zeros[i] = s;
    s += '0';
  }
  groupSizes[0] = 0;
  groupSizes[1] = 0;
  groupBases[0] = 0;
  groupBases[1] = 0;
  var base = 2 - 1;
  while (++base < 36 + 1) {
    var groupSize = 0;
    var groupBase = 1;
    while (groupBase < (1 << BN.wordSize) / base) {
      groupBase *= base;
      groupSize += 1;
    }
    groupSizes[base] = groupSize;
    groupBases[base] = groupBase;
  }

  */

  var zeros = [
    '',
    '0',
    '00',
    '000',
    '0000',
    '00000',
    '000000',
    '0000000',
    '00000000',
    '000000000',
    '0000000000',
    '00000000000',
    '000000000000',
    '0000000000000',
    '00000000000000',
    '000000000000000',
    '0000000000000000',
    '00000000000000000',
    '000000000000000000',
    '0000000000000000000',
    '00000000000000000000',
    '000000000000000000000',
    '0000000000000000000000',
    '00000000000000000000000',
    '000000000000000000000000',
    '0000000000000000000000000'
  ];

  var groupSizes = [
    0, 0,
    25, 16, 12, 11, 10, 9, 8,
    8, 7, 7, 7, 7, 6, 6,
    6, 6, 6, 6, 6, 5, 5,
    5, 5, 5, 5, 5, 5, 5,
    5, 5, 5, 5, 5, 5, 5
  ];

  var groupBases = [
    0, 0,
    33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
    43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
    16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
    6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
    24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
  ];

  BN.prototype.toString = function toString (base, padding) {
    base = base || 10;
    padding = padding | 0 || 1;

    var out;
    if (base === 16 || base === 'hex') {
      out = '';
      var off = 0;
      var carry = 0;
      for (var i = 0; i < this.length; i++) {
        var w = this.words[i];
        var word = (((w << off) | carry) & 0xffffff).toString(16);
        carry = (w >>> (24 - off)) & 0xffffff;
        if (carry !== 0 || i !== this.length - 1) {
          out = zeros[6 - word.length] + word + out;
        } else {
          out = word + out;
        }
        off += 2;
        if (off >= 26) {
          off -= 26;
          i--;
        }
      }
      if (carry !== 0) {
        out = carry.toString(16) + out;
      }
      while (out.length % padding !== 0) {
        out = '0' + out;
      }
      if (this.negative !== 0) {
        out = '-' + out;
      }
      return out;
    }

    if (base === (base | 0) && base >= 2 && base <= 36) {
      // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
      var groupSize = groupSizes[base];
      // var groupBase = Math.pow(base, groupSize);
      var groupBase = groupBases[base];
      out = '';
      var c = this.clone();
      c.negative = 0;
      while (!c.isZero()) {
        var r = c.modn(groupBase).toString(base);
        c = c.idivn(groupBase);

        if (!c.isZero()) {
          out = zeros[groupSize - r.length] + r + out;
        } else {
          out = r + out;
        }
      }
      if (this.isZero()) {
        out = '0' + out;
      }
      while (out.length % padding !== 0) {
        out = '0' + out;
      }
      if (this.negative !== 0) {
        out = '-' + out;
      }
      return out;
    }

    assert(false, 'Base should be between 2 and 36');
  };

  BN.prototype.toNumber = function toNumber () {
    var ret = this.words[0];
    if (this.length === 2) {
      ret += this.words[1] * 0x4000000;
    } else if (this.length === 3 && this.words[2] === 0x01) {
      // NOTE: at this stage it is known that the top bit is set
      ret += 0x10000000000000 + (this.words[1] * 0x4000000);
    } else if (this.length > 2) {
      assert(false, 'Number can only safely store up to 53 bits');
    }
    return (this.negative !== 0) ? -ret : ret;
  };

  BN.prototype.toJSON = function toJSON () {
    return this.toString(16);
  };

  BN.prototype.toBuffer = function toBuffer (endian, length) {
    assert(typeof Buffer !== 'undefined');
    return this.toArrayLike(Buffer, endian, length);
  };

  BN.prototype.toArray = function toArray (endian, length) {
    return this.toArrayLike(Array, endian, length);
  };

  BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
    var byteLength = this.byteLength();
    var reqLength = length || Math.max(1, byteLength);
    assert(byteLength <= reqLength, 'byte array longer than desired length');
    assert(reqLength > 0, 'Requested array length <= 0');

    this.strip();
    var littleEndian = endian === 'le';
    var res = new ArrayType(reqLength);

    var b, i;
    var q = this.clone();
    if (!littleEndian) {
      // Assume big-endian
      for (i = 0; i < reqLength - byteLength; i++) {
        res[i] = 0;
      }

      for (i = 0; !q.isZero(); i++) {
        b = q.andln(0xff);
        q.iushrn(8);

        res[reqLength - i - 1] = b;
      }
    } else {
      for (i = 0; !q.isZero(); i++) {
        b = q.andln(0xff);
        q.iushrn(8);

        res[i] = b;
      }

      for (; i < reqLength; i++) {
        res[i] = 0;
      }
    }

    return res;
  };

  if (Math.clz32) {
    BN.prototype._countBits = function _countBits (w) {
      return 32 - Math.clz32(w);
    };
  } else {
    BN.prototype._countBits = function _countBits (w) {
      var t = w;
      var r = 0;
      if (t >= 0x1000) {
        r += 13;
        t >>>= 13;
      }
      if (t >= 0x40) {
        r += 7;
        t >>>= 7;
      }
      if (t >= 0x8) {
        r += 4;
        t >>>= 4;
      }
      if (t >= 0x02) {
        r += 2;
        t >>>= 2;
      }
      return r + t;
    };
  }

  BN.prototype._zeroBits = function _zeroBits (w) {
    // Short-cut
    if (w === 0) return 26;

    var t = w;
    var r = 0;
    if ((t & 0x1fff) === 0) {
      r += 13;
      t >>>= 13;
    }
    if ((t & 0x7f) === 0) {
      r += 7;
      t >>>= 7;
    }
    if ((t & 0xf) === 0) {
      r += 4;
      t >>>= 4;
    }
    if ((t & 0x3) === 0) {
      r += 2;
      t >>>= 2;
    }
    if ((t & 0x1) === 0) {
      r++;
    }
    return r;
  };

  // Return number of used bits in a BN
  BN.prototype.bitLength = function bitLength () {
    var w = this.words[this.length - 1];
    var hi = this._countBits(w);
    return (this.length - 1) * 26 + hi;
  };

  function toBitArray (num) {
    var w = new Array(num.bitLength());

    for (var bit = 0; bit < w.length; bit++) {
      var off = (bit / 26) | 0;
      var wbit = bit % 26;

      w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
    }

    return w;
  }

  // Number of trailing zero bits
  BN.prototype.zeroBits = function zeroBits () {
    if (this.isZero()) return 0;

    var r = 0;
    for (var i = 0; i < this.length; i++) {
      var b = this._zeroBits(this.words[i]);
      r += b;
      if (b !== 26) break;
    }
    return r;
  };

  BN.prototype.byteLength = function byteLength () {
    return Math.ceil(this.bitLength() / 8);
  };

  BN.prototype.toTwos = function toTwos (width) {
    if (this.negative !== 0) {
      return this.abs().inotn(width).iaddn(1);
    }
    return this.clone();
  };

  BN.prototype.fromTwos = function fromTwos (width) {
    if (this.testn(width - 1)) {
      return this.notn(width).iaddn(1).ineg();
    }
    return this.clone();
  };

  BN.prototype.isNeg = function isNeg () {
    return this.negative !== 0;
  };

  // Return negative clone of `this`
  BN.prototype.neg = function neg () {
    return this.clone().ineg();
  };

  BN.prototype.ineg = function ineg () {
    if (!this.isZero()) {
      this.negative ^= 1;
    }

    return this;
  };

  // Or `num` with `this` in-place
  BN.prototype.iuor = function iuor (num) {
    while (this.length < num.length) {
      this.words[this.length++] = 0;
    }

    for (var i = 0; i < num.length; i++) {
      this.words[i] = this.words[i] | num.words[i];
    }

    return this.strip();
  };

  BN.prototype.ior = function ior (num) {
    assert((this.negative | num.negative) === 0);
    return this.iuor(num);
  };

  // Or `num` with `this`
  BN.prototype.or = function or (num) {
    if (this.length > num.length) return this.clone().ior(num);
    return num.clone().ior(this);
  };

  BN.prototype.uor = function uor (num) {
    if (this.length > num.length) return this.clone().iuor(num);
    return num.clone().iuor(this);
  };

  // And `num` with `this` in-place
  BN.prototype.iuand = function iuand (num) {
    // b = min-length(num, this)
    var b;
    if (this.length > num.length) {
      b = num;
    } else {
      b = this;
    }

    for (var i = 0; i < b.length; i++) {
      this.words[i] = this.words[i] & num.words[i];
    }

    this.length = b.length;

    return this.strip();
  };

  BN.prototype.iand = function iand (num) {
    assert((this.negative | num.negative) === 0);
    return this.iuand(num);
  };

  // And `num` with `this`
  BN.prototype.and = function and (num) {
    if (this.length > num.length) return this.clone().iand(num);
    return num.clone().iand(this);
  };

  BN.prototype.uand = function uand (num) {
    if (this.length > num.length) return this.clone().iuand(num);
    return num.clone().iuand(this);
  };

  // Xor `num` with `this` in-place
  BN.prototype.iuxor = function iuxor (num) {
    // a.length > b.length
    var a;
    var b;
    if (this.length > num.length) {
      a = this;
      b = num;
    } else {
      a = num;
      b = this;
    }

    for (var i = 0; i < b.length; i++) {
      this.words[i] = a.words[i] ^ b.words[i];
    }

    if (this !== a) {
      for (; i < a.length; i++) {
        this.words[i] = a.words[i];
      }
    }

    this.length = a.length;

    return this.strip();
  };

  BN.prototype.ixor = function ixor (num) {
    assert((this.negative | num.negative) === 0);
    return this.iuxor(num);
  };

  // Xor `num` with `this`
  BN.prototype.xor = function xor (num) {
    if (this.length > num.length) return this.clone().ixor(num);
    return num.clone().ixor(this);
  };

  BN.prototype.uxor = function uxor (num) {
    if (this.length > num.length) return this.clone().iuxor(num);
    return num.clone().iuxor(this);
  };

  // Not ``this`` with ``width`` bitwidth
  BN.prototype.inotn = function inotn (width) {
    assert(typeof width === 'number' && width >= 0);

    var bytesNeeded = Math.ceil(width / 26) | 0;
    var bitsLeft = width % 26;

    // Extend the buffer with leading zeroes
    this._expand(bytesNeeded);

    if (bitsLeft > 0) {
      bytesNeeded--;
    }

    // Handle complete words
    for (var i = 0; i < bytesNeeded; i++) {
      this.words[i] = ~this.words[i] & 0x3ffffff;
    }

    // Handle the residue
    if (bitsLeft > 0) {
      this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
    }

    // And remove leading zeroes
    return this.strip();
  };

  BN.prototype.notn = function notn (width) {
    return this.clone().inotn(width);
  };

  // Set `bit` of `this`
  BN.prototype.setn = function setn (bit, val) {
    assert(typeof bit === 'number' && bit >= 0);

    var off = (bit / 26) | 0;
    var wbit = bit % 26;

    this._expand(off + 1);

    if (val) {
      this.words[off] = this.words[off] | (1 << wbit);
    } else {
      this.words[off] = this.words[off] & ~(1 << wbit);
    }

    return this.strip();
  };

  // Add `num` to `this` in-place
  BN.prototype.iadd = function iadd (num) {
    var r;

    // negative + positive
    if (this.negative !== 0 && num.negative === 0) {
      this.negative = 0;
      r = this.isub(num);
      this.negative ^= 1;
      return this._normSign();

    // positive + negative
    } else if (this.negative === 0 && num.negative !== 0) {
      num.negative = 0;
      r = this.isub(num);
      num.negative = 1;
      return r._normSign();
    }

    // a.length > b.length
    var a, b;
    if (this.length > num.length) {
      a = this;
      b = num;
    } else {
      a = num;
      b = this;
    }

    var carry = 0;
    for (var i = 0; i < b.length; i++) {
      r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
      this.words[i] = r & 0x3ffffff;
      carry = r >>> 26;
    }
    for (; carry !== 0 && i < a.length; i++) {
      r = (a.words[i] | 0) + carry;
      this.words[i] = r & 0x3ffffff;
      carry = r >>> 26;
    }

    this.length = a.length;
    if (carry !== 0) {
      this.words[this.length] = carry;
      this.length++;
    // Copy the rest of the words
    } else if (a !== this) {
      for (; i < a.length; i++) {
        this.words[i] = a.words[i];
      }
    }

    return this;
  };

  // Add `num` to `this`
  BN.prototype.add = function add (num) {
    var res;
    if (num.negative !== 0 && this.negative === 0) {
      num.negative = 0;
      res = this.sub(num);
      num.negative ^= 1;
      return res;
    } else if (num.negative === 0 && this.negative !== 0) {
      this.negative = 0;
      res = num.sub(this);
      this.negative = 1;
      return res;
    }

    if (this.length > num.length) return this.clone().iadd(num);

    return num.clone().iadd(this);
  };

  // Subtract `num` from `this` in-place
  BN.prototype.isub = function isub (num) {
    // this - (-num) = this + num
    if (num.negative !== 0) {
      num.negative = 0;
      var r = this.iadd(num);
      num.negative = 1;
      return r._normSign();

    // -this - num = -(this + num)
    } else if (this.negative !== 0) {
      this.negative = 0;
      this.iadd(num);
      this.negative = 1;
      return this._normSign();
    }

    // At this point both numbers are positive
    var cmp = this.cmp(num);

    // Optimization - zeroify
    if (cmp === 0) {
      this.negative = 0;
      this.length = 1;
      this.words[0] = 0;
      return this;
    }

    // a > b
    var a, b;
    if (cmp > 0) {
      a = this;
      b = num;
    } else {
      a = num;
      b = this;
    }

    var carry = 0;
    for (var i = 0; i < b.length; i++) {
      r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
      carry = r >> 26;
      this.words[i] = r & 0x3ffffff;
    }
    for (; carry !== 0 && i < a.length; i++) {
      r = (a.words[i] | 0) + carry;
      carry = r >> 26;
      this.words[i] = r & 0x3ffffff;
    }

    // Copy rest of the words
    if (carry === 0 && i < a.length && a !== this) {
      for (; i < a.length; i++) {
        this.words[i] = a.words[i];
      }
    }

    this.length = Math.max(this.length, i);

    if (a !== this) {
      this.negative = 1;
    }

    return this.strip();
  };

  // Subtract `num` from `this`
  BN.prototype.sub = function sub (num) {
    return this.clone().isub(num);
  };

  function smallMulTo (self, num, out) {
    out.negative = num.negative ^ self.negative;
    var len = (self.length + num.length) | 0;
    out.length = len;
    len = (len - 1) | 0;

    // Peel one iteration (compiler can't do it, because of code complexity)
    var a = self.words[0] | 0;
    var b = num.words[0] | 0;
    var r = a * b;

    var lo = r & 0x3ffffff;
    var carry = (r / 0x4000000) | 0;
    out.words[0] = lo;

    for (var k = 1; k < len; k++) {
      // Sum all words with the same `i + j = k` and accumulate `ncarry`,
      // note that ncarry could be >= 0x3ffffff
      var ncarry = carry >>> 26;
      var rword = carry & 0x3ffffff;
      var maxJ = Math.min(k, num.length - 1);
      for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
        var i = (k - j) | 0;
        a = self.words[i] | 0;
        b = num.words[j] | 0;
        r = a * b + rword;
        ncarry += (r / 0x4000000) | 0;
        rword = r & 0x3ffffff;
      }
      out.words[k] = rword | 0;
      carry = ncarry | 0;
    }
    if (carry !== 0) {
      out.words[k] = carry | 0;
    } else {
      out.length--;
    }

    return out.strip();
  }

  // TODO(indutny): it may be reasonable to omit it for users who don't need
  // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
  // multiplication (like elliptic secp256k1).
  var comb10MulTo = function comb10MulTo (self, num, out) {
    var a = self.words;
    var b = num.words;
    var o = out.words;
    var c = 0;
    var lo;
    var mid;
    var hi;
    var a0 = a[0] | 0;
    var al0 = a0 & 0x1fff;
    var ah0 = a0 >>> 13;
    var a1 = a[1] | 0;
    var al1 = a1 & 0x1fff;
    var ah1 = a1 >>> 13;
    var a2 = a[2] | 0;
    var al2 = a2 & 0x1fff;
    var ah2 = a2 >>> 13;
    var a3 = a[3] | 0;
    var al3 = a3 & 0x1fff;
    var ah3 = a3 >>> 13;
    var a4 = a[4] | 0;
    var al4 = a4 & 0x1fff;
    var ah4 = a4 >>> 13;
    var a5 = a[5] | 0;
    var al5 = a5 & 0x1fff;
    var ah5 = a5 >>> 13;
    var a6 = a[6] | 0;
    var al6 = a6 & 0x1fff;
    var ah6 = a6 >>> 13;
    var a7 = a[7] | 0;
    var al7 = a7 & 0x1fff;
    var ah7 = a7 >>> 13;
    var a8 = a[8] | 0;
    var al8 = a8 & 0x1fff;
    var ah8 = a8 >>> 13;
    var a9 = a[9] | 0;
    var al9 = a9 & 0x1fff;
    var ah9 = a9 >>> 13;
    var b0 = b[0] | 0;
    var bl0 = b0 & 0x1fff;
    var bh0 = b0 >>> 13;
    var b1 = b[1] | 0;
    var bl1 = b1 & 0x1fff;
    var bh1 = b1 >>> 13;
    var b2 = b[2] | 0;
    var bl2 = b2 & 0x1fff;
    var bh2 = b2 >>> 13;
    var b3 = b[3] | 0;
    var bl3 = b3 & 0x1fff;
    var bh3 = b3 >>> 13;
    var b4 = b[4] | 0;
    var bl4 = b4 & 0x1fff;
    var bh4 = b4 >>> 13;
    var b5 = b[5] | 0;
    var bl5 = b5 & 0x1fff;
    var bh5 = b5 >>> 13;
    var b6 = b[6] | 0;
    var bl6 = b6 & 0x1fff;
    var bh6 = b6 >>> 13;
    var b7 = b[7] | 0;
    var bl7 = b7 & 0x1fff;
    var bh7 = b7 >>> 13;
    var b8 = b[8] | 0;
    var bl8 = b8 & 0x1fff;
    var bh8 = b8 >>> 13;
    var b9 = b[9] | 0;
    var bl9 = b9 & 0x1fff;
    var bh9 = b9 >>> 13;

    out.negative = self.negative ^ num.negative;
    out.length = 19;
    /* k = 0 */
    lo = Math.imul(al0, bl0);
    mid = Math.imul(al0, bh0);
    mid = (mid + Math.imul(ah0, bl0)) | 0;
    hi = Math.imul(ah0, bh0);
    var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
    w0 &= 0x3ffffff;
    /* k = 1 */
    lo = Math.imul(al1, bl0);
    mid = Math.imul(al1, bh0);
    mid = (mid + Math.imul(ah1, bl0)) | 0;
    hi = Math.imul(ah1, bh0);
    lo = (lo + Math.imul(al0, bl1)) | 0;
    mid = (mid + Math.imul(al0, bh1)) | 0;
    mid = (mid + Math.imul(ah0, bl1)) | 0;
    hi = (hi + Math.imul(ah0, bh1)) | 0;
    var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
    w1 &= 0x3ffffff;
    /* k = 2 */
    lo = Math.imul(al2, bl0);
    mid = Math.imul(al2, bh0);
    mid = (mid + Math.imul(ah2, bl0)) | 0;
    hi = Math.imul(ah2, bh0);
    lo = (lo + Math.imul(al1, bl1)) | 0;
    mid = (mid + Math.imul(al1, bh1)) | 0;
    mid = (mid + Math.imul(ah1, bl1)) | 0;
    hi = (hi + Math.imul(ah1, bh1)) | 0;
    lo = (lo + Math.imul(al0, bl2)) | 0;
    mid = (mid + Math.imul(al0, bh2)) | 0;
    mid = (mid + Math.imul(ah0, bl2)) | 0;
    hi = (hi + Math.imul(ah0, bh2)) | 0;
    var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
    w2 &= 0x3ffffff;
    /* k = 3 */
    lo = Math.imul(al3, bl0);
    mid = Math.imul(al3, bh0);
    mid = (mid + Math.imul(ah3, bl0)) | 0;
    hi = Math.imul(ah3, bh0);
    lo = (lo + Math.imul(al2, bl1)) | 0;
    mid = (mid + Math.imul(al2, bh1)) | 0;
    mid = (mid + Math.imul(ah2, bl1)) | 0;
    hi = (hi + Math.imul(ah2, bh1)) | 0;
    lo = (lo + Math.imul(al1, bl2)) | 0;
    mid = (mid + Math.imul(al1, bh2)) | 0;
    mid = (mid + Math.imul(ah1, bl2)) | 0;
    hi = (hi + Math.imul(ah1, bh2)) | 0;
    lo = (lo + Math.imul(al0, bl3)) | 0;
    mid = (mid + Math.imul(al0, bh3)) | 0;
    mid = (mid + Math.imul(ah0, bl3)) | 0;
    hi = (hi + Math.imul(ah0, bh3)) | 0;
    var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
    w3 &= 0x3ffffff;
    /* k = 4 */
    lo = Math.imul(al4, bl0);
    mid = Math.imul(al4, bh0);
    mid = (mid + Math.imul(ah4, bl0)) | 0;
    hi = Math.imul(ah4, bh0);
    lo = (lo + Math.imul(al3, bl1)) | 0;
    mid = (mid + Math.imul(al3, bh1)) | 0;
    mid = (mid + Math.imul(ah3, bl1)) | 0;
    hi = (hi + Math.imul(ah3, bh1)) | 0;
    lo = (lo + Math.imul(al2, bl2)) | 0;
    mid = (mid + Math.imul(al2, bh2)) | 0;
    mid = (mid + Math.imul(ah2, bl2)) | 0;
    hi = (hi + Math.imul(ah2, bh2)) | 0;
    lo = (lo + Math.imul(al1, bl3)) | 0;
    mid = (mid + Math.imul(al1, bh3)) | 0;
    mid = (mid + Math.imul(ah1, bl3)) | 0;
    hi = (hi + Math.imul(ah1, bh3)) | 0;
    lo = (lo + Math.imul(al0, bl4)) | 0;
    mid = (mid + Math.imul(al0, bh4)) | 0;
    mid = (mid + Math.imul(ah0, bl4)) | 0;
    hi = (hi + Math.imul(ah0, bh4)) | 0;
    var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
    w4 &= 0x3ffffff;
    /* k = 5 */
    lo = Math.imul(al5, bl0);
    mid = Math.imul(al5, bh0);
    mid = (mid + Math.imul(ah5, bl0)) | 0;
    hi = Math.imul(ah5, bh0);
    lo = (lo + Math.imul(al4, bl1)) | 0;
    mid = (mid + Math.imul(al4, bh1)) | 0;
    mid = (mid + Math.imul(ah4, bl1)) | 0;
    hi = (hi + Math.imul(ah4, bh1)) | 0;
    lo = (lo + Math.imul(al3, bl2)) | 0;
    mid = (mid + Math.imul(al3, bh2)) | 0;
    mid = (mid + Math.imul(ah3, bl2)) | 0;
    hi = (hi + Math.imul(ah3, bh2)) | 0;
    lo = (lo + Math.imul(al2, bl3)) | 0;
    mid = (mid + Math.imul(al2, bh3)) | 0;
    mid = (mid + Math.imul(ah2, bl3)) | 0;
    hi = (hi + Math.imul(ah2, bh3)) | 0;
    lo = (lo + Math.imul(al1, bl4)) | 0;
    mid = (mid + Math.imul(al1, bh4)) | 0;
    mid = (mid + Math.imul(ah1, bl4)) | 0;
    hi = (hi + Math.imul(ah1, bh4)) | 0;
    lo = (lo + Math.imul(al0, bl5)) | 0;
    mid = (mid + Math.imul(al0, bh5)) | 0;
    mid = (mid + Math.imul(ah0, bl5)) | 0;
    hi = (hi + Math.imul(ah0, bh5)) | 0;
    var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
    w5 &= 0x3ffffff;
    /* k = 6 */
    lo = Math.imul(al6, bl0);
    mid = Math.imul(al6, bh0);
    mid = (mid + Math.imul(ah6, bl0)) | 0;
    hi = Math.imul(ah6, bh0);
    lo = (lo + Math.imul(al5, bl1)) | 0;
    mid = (mid + Math.imul(al5, bh1)) | 0;
    mid = (mid + Math.imul(ah5, bl1)) | 0;
    hi = (hi + Math.imul(ah5, bh1)) | 0;
    lo = (lo + Math.imul(al4, bl2)) | 0;
    mid = (mid + Math.imul(al4, bh2)) | 0;
    mid = (mid + Math.imul(ah4, bl2)) | 0;
    hi = (hi + Math.imul(ah4, bh2)) | 0;
    lo = (lo + Math.imul(al3, bl3)) | 0;
    mid = (mid + Math.imul(al3, bh3)) | 0;
    mid = (mid + Math.imul(ah3, bl3)) | 0;
    hi = (hi + Math.imul(ah3, bh3)) | 0;
    lo = (lo + Math.imul(al2, bl4)) | 0;
    mid = (mid + Math.imul(al2, bh4)) | 0;
    mid = (mid + Math.imul(ah2, bl4)) | 0;
    hi = (hi + Math.imul(ah2, bh4)) | 0;
    lo = (lo + Math.imul(al1, bl5)) | 0;
    mid = (mid + Math.imul(al1, bh5)) | 0;
    mid = (mid + Math.imul(ah1, bl5)) | 0;
    hi = (hi + Math.imul(ah1, bh5)) | 0;
    lo = (lo + Math.imul(al0, bl6)) | 0;
    mid = (mid + Math.imul(al0, bh6)) | 0;
    mid = (mid + Math.imul(ah0, bl6)) | 0;
    hi = (hi + Math.imul(ah0, bh6)) | 0;
    var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
    w6 &= 0x3ffffff;
    /* k = 7 */
    lo = Math.imul(al7, bl0);
    mid = Math.imul(al7, bh0);
    mid = (mid + Math.imul(ah7, bl0)) | 0;
    hi = Math.imul(ah7, bh0);
    lo = (lo + Math.imul(al6, bl1)) | 0;
    mid = (mid + Math.imul(al6, bh1)) | 0;
    mid = (mid + Math.imul(ah6, bl1)) | 0;
    hi = (hi + Math.imul(ah6, bh1)) | 0;
    lo = (lo + Math.imul(al5, bl2)) | 0;
    mid = (mid + Math.imul(al5, bh2)) | 0;
    mid = (mid + Math.imul(ah5, bl2)) | 0;
    hi = (hi + Math.imul(ah5, bh2)) | 0;
    lo = (lo + Math.imul(al4, bl3)) | 0;
    mid = (mid + Math.imul(al4, bh3)) | 0;
    mid = (mid + Math.imul(ah4, bl3)) | 0;
    hi = (hi + Math.imul(ah4, bh3)) | 0;
    lo = (lo + Math.imul(al3, bl4)) | 0;
    mid = (mid + Math.imul(al3, bh4)) | 0;
    mid = (mid + Math.imul(ah3, bl4)) | 0;
    hi = (hi + Math.imul(ah3, bh4)) | 0;
    lo = (lo + Math.imul(al2, bl5)) | 0;
    mid = (mid + Math.imul(al2, bh5)) | 0;
    mid = (mid + Math.imul(ah2, bl5)) | 0;
    hi = (hi + Math.imul(ah2, bh5)) | 0;
    lo = (lo + Math.imul(al1, bl6)) | 0;
    mid = (mid + Math.imul(al1, bh6)) | 0;
    mid = (mid + Math.imul(ah1, bl6)) | 0;
    hi = (hi + Math.imul(ah1, bh6)) | 0;
    lo = (lo + Math.imul(al0, bl7)) | 0;
    mid = (mid + Math.imul(al0, bh7)) | 0;
    mid = (mid + Math.imul(ah0, bl7)) | 0;
    hi = (hi + Math.imul(ah0, bh7)) | 0;
    var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
    w7 &= 0x3ffffff;
    /* k = 8 */
    lo = Math.imul(al8, bl0);
    mid = Math.imul(al8, bh0);
    mid = (mid + Math.imul(ah8, bl0)) | 0;
    hi = Math.imul(ah8, bh0);
    lo = (lo + Math.imul(al7, bl1)) | 0;
    mid = (mid + Math.imul(al7, bh1)) | 0;
    mid = (mid + Math.imul(ah7, bl1)) | 0;
    hi = (hi + Math.imul(ah7, bh1)) | 0;
    lo = (lo + Math.imul(al6, bl2)) | 0;
    mid = (mid + Math.imul(al6, bh2)) | 0;
    mid = (mid + Math.imul(ah6, bl2)) | 0;
    hi = (hi + Math.imul(ah6, bh2)) | 0;
    lo = (lo + Math.imul(al5, bl3)) | 0;
    mid = (mid + Math.imul(al5, bh3)) | 0;
    mid = (mid + Math.imul(ah5, bl3)) | 0;
    hi = (hi + Math.imul(ah5, bh3)) | 0;
    lo = (lo + Math.imul(al4, bl4)) | 0;
    mid = (mid + Math.imul(al4, bh4)) | 0;
    mid = (mid + Math.imul(ah4, bl4)) | 0;
    hi = (hi + Math.imul(ah4, bh4)) | 0;
    lo = (lo + Math.imul(al3, bl5)) | 0;
    mid = (mid + Math.imul(al3, bh5)) | 0;
    mid = (mid + Math.imul(ah3, bl5)) | 0;
    hi = (hi + Math.imul(ah3, bh5)) | 0;
    lo = (lo + Math.imul(al2, bl6)) | 0;
    mid = (mid + Math.imul(al2, bh6)) | 0;
    mid = (mid + Math.imul(ah2, bl6)) | 0;
    hi = (hi + Math.imul(ah2, bh6)) | 0;
    lo = (lo + Math.imul(al1, bl7)) | 0;
    mid = (mid + Math.imul(al1, bh7)) | 0;
    mid = (mid + Math.imul(ah1, bl7)) | 0;
    hi = (hi + Math.imul(ah1, bh7)) | 0;
    lo = (lo + Math.imul(al0, bl8)) | 0;
    mid = (mid + Math.imul(al0, bh8)) | 0;
    mid = (mid + Math.imul(ah0, bl8)) | 0;
    hi = (hi + Math.imul(ah0, bh8)) | 0;
    var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
    w8 &= 0x3ffffff;
    /* k = 9 */
    lo = Math.imul(al9, bl0);
    mid = Math.imul(al9, bh0);
    mid = (mid + Math.imul(ah9, bl0)) | 0;
    hi = Math.imul(ah9, bh0);
    lo = (lo + Math.imul(al8, bl1)) | 0;
    mid = (mid + Math.imul(al8, bh1)) | 0;
    mid = (mid + Math.imul(ah8, bl1)) | 0;
    hi = (hi + Math.imul(ah8, bh1)) | 0;
    lo = (lo + Math.imul(al7, bl2)) | 0;
    mid = (mid + Math.imul(al7, bh2)) | 0;
    mid = (mid + Math.imul(ah7, bl2)) | 0;
    hi = (hi + Math.imul(ah7, bh2)) | 0;
    lo = (lo + Math.imul(al6, bl3)) | 0;
    mid = (mid + Math.imul(al6, bh3)) | 0;
    mid = (mid + Math.imul(ah6, bl3)) | 0;
    hi = (hi + Math.imul(ah6, bh3)) | 0;
    lo = (lo + Math.imul(al5, bl4)) | 0;
    mid = (mid + Math.imul(al5, bh4)) | 0;
    mid = (mid + Math.imul(ah5, bl4)) | 0;
    hi = (hi + Math.imul(ah5, bh4)) | 0;
    lo = (lo + Math.imul(al4, bl5)) | 0;
    mid = (mid + Math.imul(al4, bh5)) | 0;
    mid = (mid + Math.imul(ah4, bl5)) | 0;
    hi = (hi + Math.imul(ah4, bh5)) | 0;
    lo = (lo + Math.imul(al3, bl6)) | 0;
    mid = (mid + Math.imul(al3, bh6)) | 0;
    mid = (mid + Math.imul(ah3, bl6)) | 0;
    hi = (hi + Math.imul(ah3, bh6)) | 0;
    lo = (lo + Math.imul(al2, bl7)) | 0;
    mid = (mid + Math.imul(al2, bh7)) | 0;
    mid = (mid + Math.imul(ah2, bl7)) | 0;
    hi = (hi + Math.imul(ah2, bh7)) | 0;
    lo = (lo + Math.imul(al1, bl8)) | 0;
    mid = (mid + Math.imul(al1, bh8)) | 0;
    mid = (mid + Math.imul(ah1, bl8)) | 0;
    hi = (hi + Math.imul(ah1, bh8)) | 0;
    lo = (lo + Math.imul(al0, bl9)) | 0;
    mid = (mid + Math.imul(al0, bh9)) | 0;
    mid = (mid + Math.imul(ah0, bl9)) | 0;
    hi = (hi + Math.imul(ah0, bh9)) | 0;
    var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
    w9 &= 0x3ffffff;
    /* k = 10 */
    lo = Math.imul(al9, bl1);
    mid = Math.imul(al9, bh1);
    mid = (mid + Math.imul(ah9, bl1)) | 0;
    hi = Math.imul(ah9, bh1);
    lo = (lo + Math.imul(al8, bl2)) | 0;
    mid = (mid + Math.imul(al8, bh2)) | 0;
    mid = (mid + Math.imul(ah8, bl2)) | 0;
    hi = (hi + Math.imul(ah8, bh2)) | 0;
    lo = (lo + Math.imul(al7, bl3)) | 0;
    mid = (mid + Math.imul(al7, bh3)) | 0;
    mid = (mid + Math.imul(ah7, bl3)) | 0;
    hi = (hi + Math.imul(ah7, bh3)) | 0;
    lo = (lo + Math.imul(al6, bl4)) | 0;
    mid = (mid + Math.imul(al6, bh4)) | 0;
    mid = (mid + Math.imul(ah6, bl4)) | 0;
    hi = (hi + Math.imul(ah6, bh4)) | 0;
    lo = (lo + Math.imul(al5, bl5)) | 0;
    mid = (mid + Math.imul(al5, bh5)) | 0;
    mid = (mid + Math.imul(ah5, bl5)) | 0;
    hi = (hi + Math.imul(ah5, bh5)) | 0;
    lo = (lo + Math.imul(al4, bl6)) | 0;
    mid = (mid + Math.imul(al4, bh6)) | 0;
    mid = (mid + Math.imul(ah4, bl6)) | 0;
    hi = (hi + Math.imul(ah4, bh6)) | 0;
    lo = (lo + Math.imul(al3, bl7)) | 0;
    mid = (mid + Math.imul(al3, bh7)) | 0;
    mid = (mid + Math.imul(ah3, bl7)) | 0;
    hi = (hi + Math.imul(ah3, bh7)) | 0;
    lo = (lo + Math.imul(al2, bl8)) | 0;
    mid = (mid + Math.imul(al2, bh8)) | 0;
    mid = (mid + Math.imul(ah2, bl8)) | 0;
    hi = (hi + Math.imul(ah2, bh8)) | 0;
    lo = (lo + Math.imul(al1, bl9)) | 0;
    mid = (mid + Math.imul(al1, bh9)) | 0;
    mid = (mid + Math.imul(ah1, bl9)) | 0;
    hi = (hi + Math.imul(ah1, bh9)) | 0;
    var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
    w10 &= 0x3ffffff;
    /* k = 11 */
    lo = Math.imul(al9, bl2);
    mid = Math.imul(al9, bh2);
    mid = (mid + Math.imul(ah9, bl2)) | 0;
    hi = Math.imul(ah9, bh2);
    lo = (lo + Math.imul(al8, bl3)) | 0;
    mid = (mid + Math.imul(al8, bh3)) | 0;
    mid = (mid + Math.imul(ah8, bl3)) | 0;
    hi = (hi + Math.imul(ah8, bh3)) | 0;
    lo = (lo + Math.imul(al7, bl4)) | 0;
    mid = (mid + Math.imul(al7, bh4)) | 0;
    mid = (mid + Math.imul(ah7, bl4)) | 0;
    hi = (hi + Math.imul(ah7, bh4)) | 0;
    lo = (lo + Math.imul(al6, bl5)) | 0;
    mid = (mid + Math.imul(al6, bh5)) | 0;
    mid = (mid + Math.imul(ah6, bl5)) | 0;
    hi = (hi + Math.imul(ah6, bh5)) | 0;
    lo = (lo + Math.imul(al5, bl6)) | 0;
    mid = (mid + Math.imul(al5, bh6)) | 0;
    mid = (mid + Math.imul(ah5, bl6)) | 0;
    hi = (hi + Math.imul(ah5, bh6)) | 0;
    lo = (lo + Math.imul(al4, bl7)) | 0;
    mid = (mid + Math.imul(al4, bh7)) | 0;
    mid = (mid + Math.imul(ah4, bl7)) | 0;
    hi = (hi + Math.imul(ah4, bh7)) | 0;
    lo = (lo + Math.imul(al3, bl8)) | 0;
    mid = (mid + Math.imul(al3, bh8)) | 0;
    mid = (mid + Math.imul(ah3, bl8)) | 0;
    hi = (hi + Math.imul(ah3, bh8)) | 0;
    lo = (lo + Math.imul(al2, bl9)) | 0;
    mid = (mid + Math.imul(al2, bh9)) | 0;
    mid = (mid + Math.imul(ah2, bl9)) | 0;
    hi = (hi + Math.imul(ah2, bh9)) | 0;
    var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
    w11 &= 0x3ffffff;
    /* k = 12 */
    lo = Math.imul(al9, bl3);
    mid = Math.imul(al9, bh3);
    mid = (mid + Math.imul(ah9, bl3)) | 0;
    hi = Math.imul(ah9, bh3);
    lo = (lo + Math.imul(al8, bl4)) | 0;
    mid = (mid + Math.imul(al8, bh4)) | 0;
    mid = (mid + Math.imul(ah8, bl4)) | 0;
    hi = (hi + Math.imul(ah8, bh4)) | 0;
    lo = (lo + Math.imul(al7, bl5)) | 0;
    mid = (mid + Math.imul(al7, bh5)) | 0;
    mid = (mid + Math.imul(ah7, bl5)) | 0;
    hi = (hi + Math.imul(ah7, bh5)) | 0;
    lo = (lo + Math.imul(al6, bl6)) | 0;
    mid = (mid + Math.imul(al6, bh6)) | 0;
    mid = (mid + Math.imul(ah6, bl6)) | 0;
    hi = (hi + Math.imul(ah6, bh6)) | 0;
    lo = (lo + Math.imul(al5, bl7)) | 0;
    mid = (mid + Math.imul(al5, bh7)) | 0;
    mid = (mid + Math.imul(ah5, bl7)) | 0;
    hi = (hi + Math.imul(ah5, bh7)) | 0;
    lo = (lo + Math.imul(al4, bl8)) | 0;
    mid = (mid + Math.imul(al4, bh8)) | 0;
    mid = (mid + Math.imul(ah4, bl8)) | 0;
    hi = (hi + Math.imul(ah4, bh8)) | 0;
    lo = (lo + Math.imul(al3, bl9)) | 0;
    mid = (mid + Math.imul(al3, bh9)) | 0;
    mid = (mid + Math.imul(ah3, bl9)) | 0;
    hi = (hi + Math.imul(ah3, bh9)) | 0;
    var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
    w12 &= 0x3ffffff;
    /* k = 13 */
    lo = Math.imul(al9, bl4);
    mid = Math.imul(al9, bh4);
    mid = (mid + Math.imul(ah9, bl4)) | 0;
    hi = Math.imul(ah9, bh4);
    lo = (lo + Math.imul(al8, bl5)) | 0;
    mid = (mid + Math.imul(al8, bh5)) | 0;
    mid = (mid + Math.imul(ah8, bl5)) | 0;
    hi = (hi + Math.imul(ah8, bh5)) | 0;
    lo = (lo + Math.imul(al7, bl6)) | 0;
    mid = (mid + Math.imul(al7, bh6)) | 0;
    mid = (mid + Math.imul(ah7, bl6)) | 0;
    hi = (hi + Math.imul(ah7, bh6)) | 0;
    lo = (lo + Math.imul(al6, bl7)) | 0;
    mid = (mid + Math.imul(al6, bh7)) | 0;
    mid = (mid + Math.imul(ah6, bl7)) | 0;
    hi = (hi + Math.imul(ah6, bh7)) | 0;
    lo = (lo + Math.imul(al5, bl8)) | 0;
    mid = (mid + Math.imul(al5, bh8)) | 0;
    mid = (mid + Math.imul(ah5, bl8)) | 0;
    hi = (hi + Math.imul(ah5, bh8)) | 0;
    lo = (lo + Math.imul(al4, bl9)) | 0;
    mid = (mid + Math.imul(al4, bh9)) | 0;
    mid = (mid + Math.imul(ah4, bl9)) | 0;
    hi = (hi + Math.imul(ah4, bh9)) | 0;
    var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
    w13 &= 0x3ffffff;
    /* k = 14 */
    lo = Math.imul(al9, bl5);
    mid = Math.imul(al9, bh5);
    mid = (mid + Math.imul(ah9, bl5)) | 0;
    hi = Math.imul(ah9, bh5);
    lo = (lo + Math.imul(al8, bl6)) | 0;
    mid = (mid + Math.imul(al8, bh6)) | 0;
    mid = (mid + Math.imul(ah8, bl6)) | 0;
    hi = (hi + Math.imul(ah8, bh6)) | 0;
    lo = (lo + Math.imul(al7, bl7)) | 0;
    mid = (mid + Math.imul(al7, bh7)) | 0;
    mid = (mid + Math.imul(ah7, bl7)) | 0;
    hi = (hi + Math.imul(ah7, bh7)) | 0;
    lo = (lo + Math.imul(al6, bl8)) | 0;
    mid = (mid + Math.imul(al6, bh8)) | 0;
    mid = (mid + Math.imul(ah6, bl8)) | 0;
    hi = (hi + Math.imul(ah6, bh8)) | 0;
    lo = (lo + Math.imul(al5, bl9)) | 0;
    mid = (mid + Math.imul(al5, bh9)) | 0;
    mid = (mid + Math.imul(ah5, bl9)) | 0;
    hi = (hi + Math.imul(ah5, bh9)) | 0;
    var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
    w14 &= 0x3ffffff;
    /* k = 15 */
    lo = Math.imul(al9, bl6);
    mid = Math.imul(al9, bh6);
    mid = (mid + Math.imul(ah9, bl6)) | 0;
    hi = Math.imul(ah9, bh6);
    lo = (lo + Math.imul(al8, bl7)) | 0;
    mid = (mid + Math.imul(al8, bh7)) | 0;
    mid = (mid + Math.imul(ah8, bl7)) | 0;
    hi = (hi + Math.imul(ah8, bh7)) | 0;
    lo = (lo + Math.imul(al7, bl8)) | 0;
    mid = (mid + Math.imul(al7, bh8)) | 0;
    mid = (mid + Math.imul(ah7, bl8)) | 0;
    hi = (hi + Math.imul(ah7, bh8)) | 0;
    lo = (lo + Math.imul(al6, bl9)) | 0;
    mid = (mid + Math.imul(al6, bh9)) | 0;
    mid = (mid + Math.imul(ah6, bl9)) | 0;
    hi = (hi + Math.imul(ah6, bh9)) | 0;
    var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
    w15 &= 0x3ffffff;
    /* k = 16 */
    lo = Math.imul(al9, bl7);
    mid = Math.imul(al9, bh7);
    mid = (mid + Math.imul(ah9, bl7)) | 0;
    hi = Math.imul(ah9, bh7);
    lo = (lo + Math.imul(al8, bl8)) | 0;
    mid = (mid + Math.imul(al8, bh8)) | 0;
    mid = (mid + Math.imul(ah8, bl8)) | 0;
    hi = (hi + Math.imul(ah8, bh8)) | 0;
    lo = (lo + Math.imul(al7, bl9)) | 0;
    mid = (mid + Math.imul(al7, bh9)) | 0;
    mid = (mid + Math.imul(ah7, bl9)) | 0;
    hi = (hi + Math.imul(ah7, bh9)) | 0;
    var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
    w16 &= 0x3ffffff;
    /* k = 17 */
    lo = Math.imul(al9, bl8);
    mid = Math.imul(al9, bh8);
    mid = (mid + Math.imul(ah9, bl8)) | 0;
    hi = Math.imul(ah9, bh8);
    lo = (lo + Math.imul(al8, bl9)) | 0;
    mid = (mid + Math.imul(al8, bh9)) | 0;
    mid = (mid + Math.imul(ah8, bl9)) | 0;
    hi = (hi + Math.imul(ah8, bh9)) | 0;
    var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
    w17 &= 0x3ffffff;
    /* k = 18 */
    lo = Math.imul(al9, bl9);
    mid = Math.imul(al9, bh9);
    mid = (mid + Math.imul(ah9, bl9)) | 0;
    hi = Math.imul(ah9, bh9);
    var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
    w18 &= 0x3ffffff;
    o[0] = w0;
    o[1] = w1;
    o[2] = w2;
    o[3] = w3;
    o[4] = w4;
    o[5] = w5;
    o[6] = w6;
    o[7] = w7;
    o[8] = w8;
    o[9] = w9;
    o[10] = w10;
    o[11] = w11;
    o[12] = w12;
    o[13] = w13;
    o[14] = w14;
    o[15] = w15;
    o[16] = w16;
    o[17] = w17;
    o[18] = w18;
    if (c !== 0) {
      o[19] = c;
      out.length++;
    }
    return out;
  };

  // Polyfill comb
  if (!Math.imul) {
    comb10MulTo = smallMulTo;
  }

  function bigMulTo (self, num, out) {
    out.negative = num.negative ^ self.negative;
    out.length = self.length + num.length;

    var carry = 0;
    var hncarry = 0;
    for (var k = 0; k < out.length - 1; k++) {
      // Sum all words with the same `i + j = k` and accumulate `ncarry`,
      // note that ncarry could be >= 0x3ffffff
      var ncarry = hncarry;
      hncarry = 0;
      var rword = carry & 0x3ffffff;
      var maxJ = Math.min(k, num.length - 1);
      for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
        var i = k - j;
        var a = self.words[i] | 0;
        var b = num.words[j] | 0;
        var r = a * b;

        var lo = r & 0x3ffffff;
        ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
        lo = (lo + rword) | 0;
        rword = lo & 0x3ffffff;
        ncarry = (ncarry + (lo >>> 26)) | 0;

        hncarry += ncarry >>> 26;
        ncarry &= 0x3ffffff;
      }
      out.words[k] = rword;
      carry = ncarry;
      ncarry = hncarry;
    }
    if (carry !== 0) {
      out.words[k] = carry;
    } else {
      out.length--;
    }

    return out.strip();
  }

  function jumboMulTo (self, num, out) {
    var fftm = new FFTM();
    return fftm.mulp(self, num, out);
  }

  BN.prototype.mulTo = function mulTo (num, out) {
    var res;
    var len = this.length + num.length;
    if (this.length === 10 && num.length === 10) {
      res = comb10MulTo(this, num, out);
    } else if (len < 63) {
      res = smallMulTo(this, num, out);
    } else if (len < 1024) {
      res = bigMulTo(this, num, out);
    } else {
      res = jumboMulTo(this, num, out);
    }

    return res;
  };

  // Cooley-Tukey algorithm for FFT
  // slightly revisited to rely on looping instead of recursion

  function FFTM (x, y) {
    this.x = x;
    this.y = y;
  }

  FFTM.prototype.makeRBT = function makeRBT (N) {
    var t = new Array(N);
    var l = BN.prototype._countBits(N) - 1;
    for (var i = 0; i < N; i++) {
      t[i] = this.revBin(i, l, N);
    }

    return t;
  };

  // Returns binary-reversed representation of `x`
  FFTM.prototype.revBin = function revBin (x, l, N) {
    if (x === 0 || x === N - 1) return x;

    var rb = 0;
    for (var i = 0; i < l; i++) {
      rb |= (x & 1) << (l - i - 1);
      x >>= 1;
    }

    return rb;
  };

  // Performs "tweedling" phase, therefore 'emulating'
  // behaviour of the recursive algorithm
  FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
    for (var i = 0; i < N; i++) {
      rtws[i] = rws[rbt[i]];
      itws[i] = iws[rbt[i]];
    }
  };

  FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
    this.permute(rbt, rws, iws, rtws, itws, N);

    for (var s = 1; s < N; s <<= 1) {
      var l = s << 1;

      var rtwdf = Math.cos(2 * Math.PI / l);
      var itwdf = Math.sin(2 * Math.PI / l);

      for (var p = 0; p < N; p += l) {
        var rtwdf_ = rtwdf;
        var itwdf_ = itwdf;

        for (var j = 0; j < s; j++) {
          var re = rtws[p + j];
          var ie = itws[p + j];

          var ro = rtws[p + j + s];
          var io = itws[p + j + s];

          var rx = rtwdf_ * ro - itwdf_ * io;

          io = rtwdf_ * io + itwdf_ * ro;
          ro = rx;

          rtws[p + j] = re + ro;
          itws[p + j] = ie + io;

          rtws[p + j + s] = re - ro;
          itws[p + j + s] = ie - io;

          /* jshint maxdepth : false */
          if (j !== l) {
            rx = rtwdf * rtwdf_ - itwdf * itwdf_;

            itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
            rtwdf_ = rx;
          }
        }
      }
    }
  };

  FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
    var N = Math.max(m, n) | 1;
    var odd = N & 1;
    var i = 0;
    for (N = N / 2 | 0; N; N = N >>> 1) {
      i++;
    }

    return 1 << i + 1 + odd;
  };

  FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
    if (N <= 1) return;

    for (var i = 0; i < N / 2; i++) {
      var t = rws[i];

      rws[i] = rws[N - i - 1];
      rws[N - i - 1] = t;

      t = iws[i];

      iws[i] = -iws[N - i - 1];
      iws[N - i - 1] = -t;
    }
  };

  FFTM.prototype.normalize13b = function normalize13b (ws, N) {
    var carry = 0;
    for (var i = 0; i < N / 2; i++) {
      var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
        Math.round(ws[2 * i] / N) +
        carry;

      ws[i] = w & 0x3ffffff;

      if (w < 0x4000000) {
        carry = 0;
      } else {
        carry = w / 0x4000000 | 0;
      }
    }

    return ws;
  };

  FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
    var carry = 0;
    for (var i = 0; i < len; i++) {
      carry = carry + (ws[i] | 0);

      rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
      rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
    }

    // Pad with zeroes
    for (i = 2 * len; i < N; ++i) {
      rws[i] = 0;
    }

    assert(carry === 0);
    assert((carry & ~0x1fff) === 0);
  };

  FFTM.prototype.stub = function stub (N) {
    var ph = new Array(N);
    for (var i = 0; i < N; i++) {
      ph[i] = 0;
    }

    return ph;
  };

  FFTM.prototype.mulp = function mulp (x, y, out) {
    var N = 2 * this.guessLen13b(x.length, y.length);

    var rbt = this.makeRBT(N);

    var _ = this.stub(N);

    var rws = new Array(N);
    var rwst = new Array(N);
    var iwst = new Array(N);

    var nrws = new Array(N);
    var nrwst = new Array(N);
    var niwst = new Array(N);

    var rmws = out.words;
    rmws.length = N;

    this.convert13b(x.words, x.length, rws, N);
    this.convert13b(y.words, y.length, nrws, N);

    this.transform(rws, _, rwst, iwst, N, rbt);
    this.transform(nrws, _, nrwst, niwst, N, rbt);

    for (var i = 0; i < N; i++) {
      var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
      iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
      rwst[i] = rx;
    }

    this.conjugate(rwst, iwst, N);
    this.transform(rwst, iwst, rmws, _, N, rbt);
    this.conjugate(rmws, _, N);
    this.normalize13b(rmws, N);

    out.negative = x.negative ^ y.negative;
    out.length = x.length + y.length;
    return out.strip();
  };

  // Multiply `this` by `num`
  BN.prototype.mul = function mul (num) {
    var out = new BN(null);
    out.words = new Array(this.length + num.length);
    return this.mulTo(num, out);
  };

  // Multiply employing FFT
  BN.prototype.mulf = function mulf (num) {
    var out = new BN(null);
    out.words = new Array(this.length + num.length);
    return jumboMulTo(this, num, out);
  };

  // In-place Multiplication
  BN.prototype.imul = function imul (num) {
    return this.clone().mulTo(num, this);
  };

  BN.prototype.imuln = function imuln (num) {
    assert(typeof num === 'number');
    assert(num < 0x4000000);

    // Carry
    var carry = 0;
    for (var i = 0; i < this.length; i++) {
      var w = (this.words[i] | 0) * num;
      var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
      carry >>= 26;
      carry += (w / 0x4000000) | 0;
      // NOTE: lo is 27bit maximum
      carry += lo >>> 26;
      this.words[i] = lo & 0x3ffffff;
    }

    if (carry !== 0) {
      this.words[i] = carry;
      this.length++;
    }

    return this;
  };

  BN.prototype.muln = function muln (num) {
    return this.clone().imuln(num);
  };

  // `this` * `this`
  BN.prototype.sqr = function sqr () {
    return this.mul(this);
  };

  // `this` * `this` in-place
  BN.prototype.isqr = function isqr () {
    return this.imul(this.clone());
  };

  // Math.pow(`this`, `num`)
  BN.prototype.pow = function pow (num) {
    var w = toBitArray(num);
    if (w.length === 0) return new BN(1);

    // Skip leading zeroes
    var res = this;
    for (var i = 0; i < w.length; i++, res = res.sqr()) {
      if (w[i] !== 0) break;
    }

    if (++i < w.length) {
      for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
        if (w[i] === 0) continue;

        res = res.mul(q);
      }
    }

    return res;
  };

  // Shift-left in-place
  BN.prototype.iushln = function iushln (bits) {
    assert(typeof bits === 'number' && bits >= 0);
    var r = bits % 26;
    var s = (bits - r) / 26;
    var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
    var i;

    if (r !== 0) {
      var carry = 0;

      for (i = 0; i < this.length; i++) {
        var newCarry = this.words[i] & carryMask;
        var c = ((this.words[i] | 0) - newCarry) << r;
        this.words[i] = c | carry;
        carry = newCarry >>> (26 - r);
      }

      if (carry) {
        this.words[i] = carry;
        this.length++;
      }
    }

    if (s !== 0) {
      for (i = this.length - 1; i >= 0; i--) {
        this.words[i + s] = this.words[i];
      }

      for (i = 0; i < s; i++) {
        this.words[i] = 0;
      }

      this.length += s;
    }

    return this.strip();
  };

  BN.prototype.ishln = function ishln (bits) {
    // TODO(indutny): implement me
    assert(this.negative === 0);
    return this.iushln(bits);
  };

  // Shift-right in-place
  // NOTE: `hint` is a lowest bit before trailing zeroes
  // NOTE: if `extended` is present - it will be filled with destroyed bits
  BN.prototype.iushrn = function iushrn (bits, hint, extended) {
    assert(typeof bits === 'number' && bits >= 0);
    var h;
    if (hint) {
      h = (hint - (hint % 26)) / 26;
    } else {
      h = 0;
    }

    var r = bits % 26;
    var s = Math.min((bits - r) / 26, this.length);
    var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
    var maskedWords = extended;

    h -= s;
    h = Math.max(0, h);

    // Extended mode, copy masked part
    if (maskedWords) {
      for (var i = 0; i < s; i++) {
        maskedWords.words[i] = this.words[i];
      }
      maskedWords.length = s;
    }

    if (s === 0) {
      // No-op, we should not move anything at all
    } else if (this.length > s) {
      this.length -= s;
      for (i = 0; i < this.length; i++) {
        this.words[i] = this.words[i + s];
      }
    } else {
      this.words[0] = 0;
      this.length = 1;
    }

    var carry = 0;
    for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
      var word = this.words[i] | 0;
      this.words[i] = (carry << (26 - r)) | (word >>> r);
      carry = word & mask;
    }

    // Push carried bits as a mask
    if (maskedWords && carry !== 0) {
      maskedWords.words[maskedWords.length++] = carry;
    }

    if (this.length === 0) {
      this.words[0] = 0;
      this.length = 1;
    }

    return this.strip();
  };

  BN.prototype.ishrn = function ishrn (bits, hint, extended) {
    // TODO(indutny): implement me
    assert(this.negative === 0);
    return this.iushrn(bits, hint, extended);
  };

  // Shift-left
  BN.prototype.shln = function shln (bits) {
    return this.clone().ishln(bits);
  };

  BN.prototype.ushln = function ushln (bits) {
    return this.clone().iushln(bits);
  };

  // Shift-right
  BN.prototype.shrn = function shrn (bits) {
    return this.clone().ishrn(bits);
  };

  BN.prototype.ushrn = function ushrn (bits) {
    return this.clone().iushrn(bits);
  };

  // Test if n bit is set
  BN.prototype.testn = function testn (bit) {
    assert(typeof bit === 'number' && bit >= 0);
    var r = bit % 26;
    var s = (bit - r) / 26;
    var q = 1 << r;

    // Fast case: bit is much higher than all existing words
    if (this.length <= s) return false;

    // Check bit and return
    var w = this.words[s];

    return !!(w & q);
  };

  // Return only lowers bits of number (in-place)
  BN.prototype.imaskn = function imaskn (bits) {
    assert(typeof bits === 'number' && bits >= 0);
    var r = bits % 26;
    var s = (bits - r) / 26;

    assert(this.negative === 0, 'imaskn works only with positive numbers');

    if (this.length <= s) {
      return this;
    }

    if (r !== 0) {
      s++;
    }
    this.length = Math.min(s, this.length);

    if (r !== 0) {
      var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
      this.words[this.length - 1] &= mask;
    }

    return this.strip();
  };

  // Return only lowers bits of number
  BN.prototype.maskn = function maskn (bits) {
    return this.clone().imaskn(bits);
  };

  // Add plain number `num` to `this`
  BN.prototype.iaddn = function iaddn (num) {
    assert(typeof num === 'number');
    assert(num < 0x4000000);
    if (num < 0) return this.isubn(-num);

    // Possible sign change
    if (this.negative !== 0) {
      if (this.length === 1 && (this.words[0] | 0) < num) {
        this.words[0] = num - (this.words[0] | 0);
        this.negative = 0;
        return this;
      }

      this.negative = 0;
      this.isubn(num);
      this.negative = 1;
      return this;
    }

    // Add without checks
    return this._iaddn(num);
  };

  BN.prototype._iaddn = function _iaddn (num) {
    this.words[0] += num;

    // Carry
    for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
      this.words[i] -= 0x4000000;
      if (i === this.length - 1) {
        this.words[i + 1] = 1;
      } else {
        this.words[i + 1]++;
      }
    }
    this.length = Math.max(this.length, i + 1);

    return this;
  };

  // Subtract plain number `num` from `this`
  BN.prototype.isubn = function isubn (num) {
    assert(typeof num === 'number');
    assert(num < 0x4000000);
    if (num < 0) return this.iaddn(-num);

    if (this.negative !== 0) {
      this.negative = 0;
      this.iaddn(num);
      this.negative = 1;
      return this;
    }

    this.words[0] -= num;

    if (this.length === 1 && this.words[0] < 0) {
      this.words[0] = -this.words[0];
      this.negative = 1;
    } else {
      // Carry
      for (var i = 0; i < this.length && this.words[i] < 0; i++) {
        this.words[i] += 0x4000000;
        this.words[i + 1] -= 1;
      }
    }

    return this.strip();
  };

  BN.prototype.addn = function addn (num) {
    return this.clone().iaddn(num);
  };

  BN.prototype.subn = function subn (num) {
    return this.clone().isubn(num);
  };

  BN.prototype.iabs = function iabs () {
    this.negative = 0;

    return this;
  };

  BN.prototype.abs = function abs () {
    return this.clone().iabs();
  };

  BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
    var len = num.length + shift;
    var i;

    this._expand(len);

    var w;
    var carry = 0;
    for (i = 0; i < num.length; i++) {
      w = (this.words[i + shift] | 0) + carry;
      var right = (num.words[i] | 0) * mul;
      w -= right & 0x3ffffff;
      carry = (w >> 26) - ((right / 0x4000000) | 0);
      this.words[i + shift] = w & 0x3ffffff;
    }
    for (; i < this.length - shift; i++) {
      w = (this.words[i + shift] | 0) + carry;
      carry = w >> 26;
      this.words[i + shift] = w & 0x3ffffff;
    }

    if (carry === 0) return this.strip();

    // Subtraction overflow
    assert(carry === -1);
    carry = 0;
    for (i = 0; i < this.length; i++) {
      w = -(this.words[i] | 0) + carry;
      carry = w >> 26;
      this.words[i] = w & 0x3ffffff;
    }
    this.negative = 1;

    return this.strip();
  };

  BN.prototype._wordDiv = function _wordDiv (num, mode) {
    var shift = this.length - num.length;

    var a = this.clone();
    var b = num;

    // Normalize
    var bhi = b.words[b.length - 1] | 0;
    var bhiBits = this._countBits(bhi);
    shift = 26 - bhiBits;
    if (shift !== 0) {
      b = b.ushln(shift);
      a.iushln(shift);
      bhi = b.words[b.length - 1] | 0;
    }

    // Initialize quotient
    var m = a.length - b.length;
    var q;

    if (mode !== 'mod') {
      q = new BN(null);
      q.length = m + 1;
      q.words = new Array(q.length);
      for (var i = 0; i < q.length; i++) {
        q.words[i] = 0;
      }
    }

    var diff = a.clone()._ishlnsubmul(b, 1, m);
    if (diff.negative === 0) {
      a = diff;
      if (q) {
        q.words[m] = 1;
      }
    }

    for (var j = m - 1; j >= 0; j--) {
      var qj = (a.words[b.length + j] | 0) * 0x4000000 +
        (a.words[b.length + j - 1] | 0);

      // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
      // (0x7ffffff)
      qj = Math.min((qj / bhi) | 0, 0x3ffffff);

      a._ishlnsubmul(b, qj, j);
      while (a.negative !== 0) {
        qj--;
        a.negative = 0;
        a._ishlnsubmul(b, 1, j);
        if (!a.isZero()) {
          a.negative ^= 1;
        }
      }
      if (q) {
        q.words[j] = qj;
      }
    }
    if (q) {
      q.strip();
    }
    a.strip();

    // Denormalize
    if (mode !== 'div' && shift !== 0) {
      a.iushrn(shift);
    }

    return {
      div: q || null,
      mod: a
    };
  };

  // NOTE: 1) `mode` can be set to `mod` to request mod only,
  //       to `div` to request div only, or be absent to
  //       request both div & mod
  //       2) `positive` is true if unsigned mod is requested
  BN.prototype.divmod = function divmod (num, mode, positive) {
    assert(!num.isZero());

    if (this.isZero()) {
      return {
        div: new BN(0),
        mod: new BN(0)
      };
    }

    var div, mod, res;
    if (this.negative !== 0 && num.negative === 0) {
      res = this.neg().divmod(num, mode);

      if (mode !== 'mod') {
        div = res.div.neg();
      }

      if (mode !== 'div') {
        mod = res.mod.neg();
        if (positive && mod.negative !== 0) {
          mod.iadd(num);
        }
      }

      return {
        div: div,
        mod: mod
      };
    }

    if (this.negative === 0 && num.negative !== 0) {
      res = this.divmod(num.neg(), mode);

      if (mode !== 'mod') {
        div = res.div.neg();
      }

      return {
        div: div,
        mod: res.mod
      };
    }

    if ((this.negative & num.negative) !== 0) {
      res = this.neg().divmod(num.neg(), mode);

      if (mode !== 'div') {
        mod = res.mod.neg();
        if (positive && mod.negative !== 0) {
          mod.isub(num);
        }
      }

      return {
        div: res.div,
        mod: mod
      };
    }

    // Both numbers are positive at this point

    // Strip both numbers to approximate shift value
    if (num.length > this.length || this.cmp(num) < 0) {
      return {
        div: new BN(0),
        mod: this
      };
    }

    // Very short reduction
    if (num.length === 1) {
      if (mode === 'div') {
        return {
          div: this.divn(num.words[0]),
          mod: null
        };
      }

      if (mode === 'mod') {
        return {
          div: null,
          mod: new BN(this.modn(num.words[0]))
        };
      }

      return {
        div: this.divn(num.words[0]),
        mod: new BN(this.modn(num.words[0]))
      };
    }

    return this._wordDiv(num, mode);
  };

  // Find `this` / `num`
  BN.prototype.div = function div (num) {
    return this.divmod(num, 'div', false).div;
  };

  // Find `this` % `num`
  BN.prototype.mod = function mod (num) {
    return this.divmod(num, 'mod', false).mod;
  };

  BN.prototype.umod = function umod (num) {
    return this.divmod(num, 'mod', true).mod;
  };

  // Find Round(`this` / `num`)
  BN.prototype.divRound = function divRound (num) {
    var dm = this.divmod(num);

    // Fast case - exact division
    if (dm.mod.isZero()) return dm.div;

    var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;

    var half = num.ushrn(1);
    var r2 = num.andln(1);
    var cmp = mod.cmp(half);

    // Round down
    if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;

    // Round up
    return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
  };

  BN.prototype.modn = function modn (num) {
    assert(num <= 0x3ffffff);
    var p = (1 << 26) % num;

    var acc = 0;
    for (var i = this.length - 1; i >= 0; i--) {
      acc = (p * acc + (this.words[i] | 0)) % num;
    }

    return acc;
  };

  // In-place division by number
  BN.prototype.idivn = function idivn (num) {
    assert(num <= 0x3ffffff);

    var carry = 0;
    for (var i = this.length - 1; i >= 0; i--) {
      var w = (this.words[i] | 0) + carry * 0x4000000;
      this.words[i] = (w / num) | 0;
      carry = w % num;
    }

    return this.strip();
  };

  BN.prototype.divn = function divn (num) {
    return this.clone().idivn(num);
  };

  BN.prototype.egcd = function egcd (p) {
    assert(p.negative === 0);
    assert(!p.isZero());

    var x = this;
    var y = p.clone();

    if (x.negative !== 0) {
      x = x.umod(p);
    } else {
      x = x.clone();
    }

    // A * x + B * y = x
    var A = new BN(1);
    var B = new BN(0);

    // C * x + D * y = y
    var C = new BN(0);
    var D = new BN(1);

    var g = 0;

    while (x.isEven() && y.isEven()) {
      x.iushrn(1);
      y.iushrn(1);
      ++g;
    }

    var yp = y.clone();
    var xp = x.clone();

    while (!x.isZero()) {
      for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
      if (i > 0) {
        x.iushrn(i);
        while (i-- > 0) {
          if (A.isOdd() || B.isOdd()) {
            A.iadd(yp);
            B.isub(xp);
          }

          A.iushrn(1);
          B.iushrn(1);
        }
      }

      for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
      if (j > 0) {
        y.iushrn(j);
        while (j-- > 0) {
          if (C.isOdd() || D.isOdd()) {
            C.iadd(yp);
            D.isub(xp);
          }

          C.iushrn(1);
          D.iushrn(1);
        }
      }

      if (x.cmp(y) >= 0) {
        x.isub(y);
        A.isub(C);
        B.isub(D);
      } else {
        y.isub(x);
        C.isub(A);
        D.isub(B);
      }
    }

    return {
      a: C,
      b: D,
      gcd: y.iushln(g)
    };
  };

  // This is reduced incarnation of the binary EEA
  // above, designated to invert members of the
  // _prime_ fields F(p) at a maximal speed
  BN.prototype._invmp = function _invmp (p) {
    assert(p.negative === 0);
    assert(!p.isZero());

    var a = this;
    var b = p.clone();

    if (a.negative !== 0) {
      a = a.umod(p);
    } else {
      a = a.clone();
    }

    var x1 = new BN(1);
    var x2 = new BN(0);

    var delta = b.clone();

    while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
      for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
      if (i > 0) {
        a.iushrn(i);
        while (i-- > 0) {
          if (x1.isOdd()) {
            x1.iadd(delta);
          }

          x1.iushrn(1);
        }
      }

      for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
      if (j > 0) {
        b.iushrn(j);
        while (j-- > 0) {
          if (x2.isOdd()) {
            x2.iadd(delta);
          }

          x2.iushrn(1);
        }
      }

      if (a.cmp(b) >= 0) {
        a.isub(b);
        x1.isub(x2);
      } else {
        b.isub(a);
        x2.isub(x1);
      }
    }

    var res;
    if (a.cmpn(1) === 0) {
      res = x1;
    } else {
      res = x2;
    }

    if (res.cmpn(0) < 0) {
      res.iadd(p);
    }

    return res;
  };

  BN.prototype.gcd = function gcd (num) {
    if (this.isZero()) return num.abs();
    if (num.isZero()) return this.abs();

    var a = this.clone();
    var b = num.clone();
    a.negative = 0;
    b.negative = 0;

    // Remove common factor of two
    for (var shift = 0; a.isEven() && b.isEven(); shift++) {
      a.iushrn(1);
      b.iushrn(1);
    }

    do {
      while (a.isEven()) {
        a.iushrn(1);
      }
      while (b.isEven()) {
        b.iushrn(1);
      }

      var r = a.cmp(b);
      if (r < 0) {
        // Swap `a` and `b` to make `a` always bigger than `b`
        var t = a;
        a = b;
        b = t;
      } else if (r === 0 || b.cmpn(1) === 0) {
        break;
      }

      a.isub(b);
    } while (true);

    return b.iushln(shift);
  };

  // Invert number in the field F(num)
  BN.prototype.invm = function invm (num) {
    return this.egcd(num).a.umod(num);
  };

  BN.prototype.isEven = function isEven () {
    return (this.words[0] & 1) === 0;
  };

  BN.prototype.isOdd = function isOdd () {
    return (this.words[0] & 1) === 1;
  };

  // And first word and num
  BN.prototype.andln = function andln (num) {
    return this.words[0] & num;
  };

  // Increment at the bit position in-line
  BN.prototype.bincn = function bincn (bit) {
    assert(typeof bit === 'number');
    var r = bit % 26;
    var s = (bit - r) / 26;
    var q = 1 << r;

    // Fast case: bit is much higher than all existing words
    if (this.length <= s) {
      this._expand(s + 1);
      this.words[s] |= q;
      return this;
    }

    // Add bit and propagate, if needed
    var carry = q;
    for (var i = s; carry !== 0 && i < this.length; i++) {
      var w = this.words[i] | 0;
      w += carry;
      carry = w >>> 26;
      w &= 0x3ffffff;
      this.words[i] = w;
    }
    if (carry !== 0) {
      this.words[i] = carry;
      this.length++;
    }
    return this;
  };

  BN.prototype.isZero = function isZero () {
    return this.length === 1 && this.words[0] === 0;
  };

  BN.prototype.cmpn = function cmpn (num) {
    var negative = num < 0;

    if (this.negative !== 0 && !negative) return -1;
    if (this.negative === 0 && negative) return 1;

    this.strip();

    var res;
    if (this.length > 1) {
      res = 1;
    } else {
      if (negative) {
        num = -num;
      }

      assert(num <= 0x3ffffff, 'Number is too big');

      var w = this.words[0] | 0;
      res = w === num ? 0 : w < num ? -1 : 1;
    }
    if (this.negative !== 0) return -res | 0;
    return res;
  };

  // Compare two numbers and return:
  // 1 - if `this` > `num`
  // 0 - if `this` == `num`
  // -1 - if `this` < `num`
  BN.prototype.cmp = function cmp (num) {
    if (this.negative !== 0 && num.negative === 0) return -1;
    if (this.negative === 0 && num.negative !== 0) return 1;

    var res = this.ucmp(num);
    if (this.negative !== 0) return -res | 0;
    return res;
  };

  // Unsigned comparison
  BN.prototype.ucmp = function ucmp (num) {
    // At this point both numbers have the same sign
    if (this.length > num.length) return 1;
    if (this.length < num.length) return -1;

    var res = 0;
    for (var i = this.length - 1; i >= 0; i--) {
      var a = this.words[i] | 0;
      var b = num.words[i] | 0;

      if (a === b) continue;
      if (a < b) {
        res = -1;
      } else if (a > b) {
        res = 1;
      }
      break;
    }
    return res;
  };

  BN.prototype.gtn = function gtn (num) {
    return this.cmpn(num) === 1;
  };

  BN.prototype.gt = function gt (num) {
    return this.cmp(num) === 1;
  };

  BN.prototype.gten = function gten (num) {
    return this.cmpn(num) >= 0;
  };

  BN.prototype.gte = function gte (num) {
    return this.cmp(num) >= 0;
  };

  BN.prototype.ltn = function ltn (num) {
    return this.cmpn(num) === -1;
  };

  BN.prototype.lt = function lt (num) {
    return this.cmp(num) === -1;
  };

  BN.prototype.lten = function lten (num) {
    return this.cmpn(num) <= 0;
  };

  BN.prototype.lte = function lte (num) {
    return this.cmp(num) <= 0;
  };

  BN.prototype.eqn = function eqn (num) {
    return this.cmpn(num) === 0;
  };

  BN.prototype.eq = function eq (num) {
    return this.cmp(num) === 0;
  };

  //
  // A reduce context, could be using montgomery or something better, depending
  // on the `m` itself.
  //
  BN.red = function red (num) {
    return new Red(num);
  };

  BN.prototype.toRed = function toRed (ctx) {
    assert(!this.red, 'Already a number in reduction context');
    assert(this.negative === 0, 'red works only with positives');
    return ctx.convertTo(this)._forceRed(ctx);
  };

  BN.prototype.fromRed = function fromRed () {
    assert(this.red, 'fromRed works only with numbers in reduction context');
    return this.red.convertFrom(this);
  };

  BN.prototype._forceRed = function _forceRed (ctx) {
    this.red = ctx;
    return this;
  };

  BN.prototype.forceRed = function forceRed (ctx) {
    assert(!this.red, 'Already a number in reduction context');
    return this._forceRed(ctx);
  };

  BN.prototype.redAdd = function redAdd (num) {
    assert(this.red, 'redAdd works only with red numbers');
    return this.red.add(this, num);
  };

  BN.prototype.redIAdd = function redIAdd (num) {
    assert(this.red, 'redIAdd works only with red numbers');
    return this.red.iadd(this, num);
  };

  BN.prototype.redSub = function redSub (num) {
    assert(this.red, 'redSub works only with red numbers');
    return this.red.sub(this, num);
  };

  BN.prototype.redISub = function redISub (num) {
    assert(this.red, 'redISub works only with red numbers');
    return this.red.isub(this, num);
  };

  BN.prototype.redShl = function redShl (num) {
    assert(this.red, 'redShl works only with red numbers');
    return this.red.shl(this, num);
  };

  BN.prototype.redMul = function redMul (num) {
    assert(this.red, 'redMul works only with red numbers');
    this.red._verify2(this, num);
    return this.red.mul(this, num);
  };

  BN.prototype.redIMul = function redIMul (num) {
    assert(this.red, 'redMul works only with red numbers');
    this.red._verify2(this, num);
    return this.red.imul(this, num);
  };

  BN.prototype.redSqr = function redSqr () {
    assert(this.red, 'redSqr works only with red numbers');
    this.red._verify1(this);
    return this.red.sqr(this);
  };

  BN.prototype.redISqr = function redISqr () {
    assert(this.red, 'redISqr works only with red numbers');
    this.red._verify1(this);
    return this.red.isqr(this);
  };

  // Square root over p
  BN.prototype.redSqrt = function redSqrt () {
    assert(this.red, 'redSqrt works only with red numbers');
    this.red._verify1(this);
    return this.red.sqrt(this);
  };

  BN.prototype.redInvm = function redInvm () {
    assert(this.red, 'redInvm works only with red numbers');
    this.red._verify1(this);
    return this.red.invm(this);
  };

  // Return negative clone of `this` % `red modulo`
  BN.prototype.redNeg = function redNeg () {
    assert(this.red, 'redNeg works only with red numbers');
    this.red._verify1(this);
    return this.red.neg(this);
  };

  BN.prototype.redPow = function redPow (num) {
    assert(this.red && !num.red, 'redPow(normalNum)');
    this.red._verify1(this);
    return this.red.pow(this, num);
  };

  // Prime numbers with efficient reduction
  var primes = {
    k256: null,
    p224: null,
    p192: null,
    p25519: null
  };

  // Pseudo-Mersenne prime
  function MPrime (name, p) {
    // P = 2 ^ N - K
    this.name = name;
    this.p = new BN(p, 16);
    this.n = this.p.bitLength();
    this.k = new BN(1).iushln(this.n).isub(this.p);

    this.tmp = this._tmp();
  }

  MPrime.prototype._tmp = function _tmp () {
    var tmp = new BN(null);
    tmp.words = new Array(Math.ceil(this.n / 13));
    return tmp;
  };

  MPrime.prototype.ireduce = function ireduce (num) {
    // Assumes that `num` is less than `P^2`
    // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
    var r = num;
    var rlen;

    do {
      this.split(r, this.tmp);
      r = this.imulK(r);
      r = r.iadd(this.tmp);
      rlen = r.bitLength();
    } while (rlen > this.n);

    var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
    if (cmp === 0) {
      r.words[0] = 0;
      r.length = 1;
    } else if (cmp > 0) {
      r.isub(this.p);
    } else {
      r.strip();
    }

    return r;
  };

  MPrime.prototype.split = function split (input, out) {
    input.iushrn(this.n, 0, out);
  };

  MPrime.prototype.imulK = function imulK (num) {
    return num.imul(this.k);
  };

  function K256 () {
    MPrime.call(
      this,
      'k256',
      'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
  }
  inherits(K256, MPrime);

  K256.prototype.split = function split (input, output) {
    // 256 = 9 * 26 + 22
    var mask = 0x3fffff;

    var outLen = Math.min(input.length, 9);
    for (var i = 0; i < outLen; i++) {
      output.words[i] = input.words[i];
    }
    output.length = outLen;

    if (input.length <= 9) {
      input.words[0] = 0;
      input.length = 1;
      return;
    }

    // Shift by 9 limbs
    var prev = input.words[9];
    output.words[output.length++] = prev & mask;

    for (i = 10; i < input.length; i++) {
      var next = input.words[i] | 0;
      input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
      prev = next;
    }
    prev >>>= 22;
    input.words[i - 10] = prev;
    if (prev === 0 && input.length > 10) {
      input.length -= 10;
    } else {
      input.length -= 9;
    }
  };

  K256.prototype.imulK = function imulK (num) {
    // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
    num.words[num.length] = 0;
    num.words[num.length + 1] = 0;
    num.length += 2;

    // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
    var lo = 0;
    for (var i = 0; i < num.length; i++) {
      var w = num.words[i] | 0;
      lo += w * 0x3d1;
      num.words[i] = lo & 0x3ffffff;
      lo = w * 0x40 + ((lo / 0x4000000) | 0);
    }

    // Fast length reduction
    if (num.words[num.length - 1] === 0) {
      num.length--;
      if (num.words[num.length - 1] === 0) {
        num.length--;
      }
    }
    return num;
  };

  function P224 () {
    MPrime.call(
      this,
      'p224',
      'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
  }
  inherits(P224, MPrime);

  function P192 () {
    MPrime.call(
      this,
      'p192',
      'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
  }
  inherits(P192, MPrime);

  function P25519 () {
    // 2 ^ 255 - 19
    MPrime.call(
      this,
      '25519',
      '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
  }
  inherits(P25519, MPrime);

  P25519.prototype.imulK = function imulK (num) {
    // K = 0x13
    var carry = 0;
    for (var i = 0; i < num.length; i++) {
      var hi = (num.words[i] | 0) * 0x13 + carry;
      var lo = hi & 0x3ffffff;
      hi >>>= 26;

      num.words[i] = lo;
      carry = hi;
    }
    if (carry !== 0) {
      num.words[num.length++] = carry;
    }
    return num;
  };

  // Exported mostly for testing purposes, use plain name instead
  BN._prime = function prime (name) {
    // Cached version of prime
    if (primes[name]) return primes[name];

    var prime;
    if (name === 'k256') {
      prime = new K256();
    } else if (name === 'p224') {
      prime = new P224();
    } else if (name === 'p192') {
      prime = new P192();
    } else if (name === 'p25519') {
      prime = new P25519();
    } else {
      throw new Error('Unknown prime ' + name);
    }
    primes[name] = prime;

    return prime;
  };

  //
  // Base reduction engine
  //
  function Red (m) {
    if (typeof m === 'string') {
      var prime = BN._prime(m);
      this.m = prime.p;
      this.prime = prime;
    } else {
      assert(m.gtn(1), 'modulus must be greater than 1');
      this.m = m;
      this.prime = null;
    }
  }

  Red.prototype._verify1 = function _verify1 (a) {
    assert(a.negative === 0, 'red works only with positives');
    assert(a.red, 'red works only with red numbers');
  };

  Red.prototype._verify2 = function _verify2 (a, b) {
    assert((a.negative | b.negative) === 0, 'red works only with positives');
    assert(a.red && a.red === b.red,
      'red works only with red numbers');
  };

  Red.prototype.imod = function imod (a) {
    if (this.prime) return this.prime.ireduce(a)._forceRed(this);
    return a.umod(this.m)._forceRed(this);
  };

  Red.prototype.neg = function neg (a) {
    if (a.isZero()) {
      return a.clone();
    }

    return this.m.sub(a)._forceRed(this);
  };

  Red.prototype.add = function add (a, b) {
    this._verify2(a, b);

    var res = a.add(b);
    if (res.cmp(this.m) >= 0) {
      res.isub(this.m);
    }
    return res._forceRed(this);
  };

  Red.prototype.iadd = function iadd (a, b) {
    this._verify2(a, b);

    var res = a.iadd(b);
    if (res.cmp(this.m) >= 0) {
      res.isub(this.m);
    }
    return res;
  };

  Red.prototype.sub = function sub (a, b) {
    this._verify2(a, b);

    var res = a.sub(b);
    if (res.cmpn(0) < 0) {
      res.iadd(this.m);
    }
    return res._forceRed(this);
  };

  Red.prototype.isub = function isub (a, b) {
    this._verify2(a, b);

    var res = a.isub(b);
    if (res.cmpn(0) < 0) {
      res.iadd(this.m);
    }
    return res;
  };

  Red.prototype.shl = function shl (a, num) {
    this._verify1(a);
    return this.imod(a.ushln(num));
  };

  Red.prototype.imul = function imul (a, b) {
    this._verify2(a, b);
    return this.imod(a.imul(b));
  };

  Red.prototype.mul = function mul (a, b) {
    this._verify2(a, b);
    return this.imod(a.mul(b));
  };

  Red.prototype.isqr = function isqr (a) {
    return this.imul(a, a.clone());
  };

  Red.prototype.sqr = function sqr (a) {
    return this.mul(a, a);
  };

  Red.prototype.sqrt = function sqrt (a) {
    if (a.isZero()) return a.clone();

    var mod3 = this.m.andln(3);
    assert(mod3 % 2 === 1);

    // Fast case
    if (mod3 === 3) {
      var pow = this.m.add(new BN(1)).iushrn(2);
      return this.pow(a, pow);
    }

    // Tonelli-Shanks algorithm (Totally unoptimized and slow)
    //
    // Find Q and S, that Q * 2 ^ S = (P - 1)
    var q = this.m.subn(1);
    var s = 0;
    while (!q.isZero() && q.andln(1) === 0) {
      s++;
      q.iushrn(1);
    }
    assert(!q.isZero());

    var one = new BN(1).toRed(this);
    var nOne = one.redNeg();

    // Find quadratic non-residue
    // NOTE: Max is such because of generalized Riemann hypothesis.
    var lpow = this.m.subn(1).iushrn(1);
    var z = this.m.bitLength();
    z = new BN(2 * z * z).toRed(this);

    while (this.pow(z, lpow).cmp(nOne) !== 0) {
      z.redIAdd(nOne);
    }

    var c = this.pow(z, q);
    var r = this.pow(a, q.addn(1).iushrn(1));
    var t = this.pow(a, q);
    var m = s;
    while (t.cmp(one) !== 0) {
      var tmp = t;
      for (var i = 0; tmp.cmp(one) !== 0; i++) {
        tmp = tmp.redSqr();
      }
      assert(i < m);
      var b = this.pow(c, new BN(1).iushln(m - i - 1));

      r = r.redMul(b);
      c = b.redSqr();
      t = t.redMul(c);
      m = i;
    }

    return r;
  };

  Red.prototype.invm = function invm (a) {
    var inv = a._invmp(this.m);
    if (inv.negative !== 0) {
      inv.negative = 0;
      return this.imod(inv).redNeg();
    } else {
      return this.imod(inv);
    }
  };

  Red.prototype.pow = function pow (a, num) {
    if (num.isZero()) return new BN(1).toRed(this);
    if (num.cmpn(1) === 0) return a.clone();

    var windowSize = 4;
    var wnd = new Array(1 << windowSize);
    wnd[0] = new BN(1).toRed(this);
    wnd[1] = a;
    for (var i = 2; i < wnd.length; i++) {
      wnd[i] = this.mul(wnd[i - 1], a);
    }

    var res = wnd[0];
    var current = 0;
    var currentLen = 0;
    var start = num.bitLength() % 26;
    if (start === 0) {
      start = 26;
    }

    for (i = num.length - 1; i >= 0; i--) {
      var word = num.words[i];
      for (var j = start - 1; j >= 0; j--) {
        var bit = (word >> j) & 1;
        if (res !== wnd[0]) {
          res = this.sqr(res);
        }

        if (bit === 0 && current === 0) {
          currentLen = 0;
          continue;
        }

        current <<= 1;
        current |= bit;
        currentLen++;
        if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;

        res = this.mul(res, wnd[current]);
        currentLen = 0;
        current = 0;
      }
      start = 26;
    }

    return res;
  };

  Red.prototype.convertTo = function convertTo (num) {
    var r = num.umod(this.m);

    return r === num ? r.clone() : r;
  };

  Red.prototype.convertFrom = function convertFrom (num) {
    var res = num.clone();
    res.red = null;
    return res;
  };

  //
  // Montgomery method engine
  //

  BN.mont = function mont (num) {
    return new Mont(num);
  };

  function Mont (m) {
    Red.call(this, m);

    this.shift = this.m.bitLength();
    if (this.shift % 26 !== 0) {
      this.shift += 26 - (this.shift % 26);
    }

    this.r = new BN(1).iushln(this.shift);
    this.r2 = this.imod(this.r.sqr());
    this.rinv = this.r._invmp(this.m);

    this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
    this.minv = this.minv.umod(this.r);
    this.minv = this.r.sub(this.minv);
  }
  inherits(Mont, Red);

  Mont.prototype.convertTo = function convertTo (num) {
    return this.imod(num.ushln(this.shift));
  };

  Mont.prototype.convertFrom = function convertFrom (num) {
    var r = this.imod(num.mul(this.rinv));
    r.red = null;
    return r;
  };

  Mont.prototype.imul = function imul (a, b) {
    if (a.isZero() || b.isZero()) {
      a.words[0] = 0;
      a.length = 1;
      return a;
    }

    var t = a.imul(b);
    var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
    var u = t.isub(c).iushrn(this.shift);
    var res = u;

    if (u.cmp(this.m) >= 0) {
      res = u.isub(this.m);
    } else if (u.cmpn(0) < 0) {
      res = u.iadd(this.m);
    }

    return res._forceRed(this);
  };

  Mont.prototype.mul = function mul (a, b) {
    if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);

    var t = a.mul(b);
    var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
    var u = t.isub(c).iushrn(this.shift);
    var res = u;
    if (u.cmp(this.m) >= 0) {
      res = u.isub(this.m);
    } else if (u.cmpn(0) < 0) {
      res = u.iadd(this.m);
    }

    return res._forceRed(this);
  };

  Mont.prototype.invm = function invm (a) {
    // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
    var res = this.imod(a._invmp(this.m).mul(this.r2));
    return res._forceRed(this);
  };
})(typeof module === 'undefined' || module, this);

},{"buffer":92}],84:[function(_dereq_,module,exports){
'use strict'

module.exports = boundary

function boundary (cells) {
  var i, j, k
  var n = cells.length
  var sz = 0
  for (i = 0; i < n; ++i) {
    sz += cells[i].length
  }
  var result = new Array(sz)
  var ptr = 0
  for (i = 0; i < n; ++i) {
    var c = cells[i]
    var d = c.length
    for (j = 0; j < d; ++j) {
      var b = result[ptr++] = new Array(d - 1)
      var p = 0
      for (k = 0; k < d; ++k) {
        if (k === j) {
          continue
        }
        b[p++] = c[k]
      }
      if (j & 1) {
        var tmp = b[1]
        b[1] = b[0]
        b[0] = tmp
      }
    }
  }
  return result
}

},{}],85:[function(_dereq_,module,exports){
'use strict'

module.exports = boxIntersectWrapper

var pool = _dereq_('typedarray-pool')
var sweep = _dereq_('./lib/sweep')
var boxIntersectIter = _dereq_('./lib/intersect')

function boxEmpty(d, box) {
  for(var j=0; j<d; ++j) {
    if(!(box[j] <= box[j+d])) {
      return true
    }
  }
  return false
}

//Unpack boxes into a flat typed array, remove empty boxes
function convertBoxes(boxes, d, data, ids) {
  var ptr = 0
  var count = 0
  for(var i=0, n=boxes.length; i<n; ++i) {
    var b = boxes[i]
    if(boxEmpty(d, b)) {
      continue
    }
    for(var j=0; j<2*d; ++j) {
      data[ptr++] = b[j]
    }
    ids[count++] = i
  }
  return count
}

//Perform type conversions, check bounds
function boxIntersect(red, blue, visit, full) {
  var n = red.length
  var m = blue.length

  //If either array is empty, then we can skip this whole thing
  if(n <= 0 || m <= 0) {
    return
  }

  //Compute dimension, if it is 0 then we skip
  var d = (red[0].length)>>>1
  if(d <= 0) {
    return
  }

  var retval

  //Convert red boxes
  var redList  = pool.mallocDouble(2*d*n)
  var redIds   = pool.mallocInt32(n)
  n = convertBoxes(red, d, redList, redIds)

  if(n > 0) {
    if(d === 1 && full) {
      //Special case: 1d complete
      sweep.init(n)
      retval = sweep.sweepComplete(
        d, visit, 
        0, n, redList, redIds,
        0, n, redList, redIds)
    } else {

      //Convert blue boxes
      var blueList = pool.mallocDouble(2*d*m)
      var blueIds  = pool.mallocInt32(m)
      m = convertBoxes(blue, d, blueList, blueIds)

      if(m > 0) {
        sweep.init(n+m)

        if(d === 1) {
          //Special case: 1d bipartite
          retval = sweep.sweepBipartite(
            d, visit, 
            0, n, redList,  redIds,
            0, m, blueList, blueIds)
        } else {
          //General case:  d>1
          retval = boxIntersectIter(
            d, visit,    full,
            n, redList,  redIds,
            m, blueList, blueIds)
        }

        pool.free(blueList)
        pool.free(blueIds)
      }
    }

    pool.free(redList)
    pool.free(redIds)
  }

  return retval
}


var RESULT

function appendItem(i,j) {
  RESULT.push([i,j])
}

function intersectFullArray(x) {
  RESULT = []
  boxIntersect(x, x, appendItem, true)
  return RESULT
}

function intersectBipartiteArray(x, y) {
  RESULT = []
  boxIntersect(x, y, appendItem, false)
  return RESULT
}

//User-friendly wrapper, handle full input and no-visitor cases
function boxIntersectWrapper(arg0, arg1, arg2) {
  var result
  switch(arguments.length) {
    case 1:
      return intersectFullArray(arg0)
    case 2:
      if(typeof arg1 === 'function') {
        return boxIntersect(arg0, arg0, arg1, true)
      } else {
        return intersectBipartiteArray(arg0, arg1)
      }
    case 3:
      return boxIntersect(arg0, arg1, arg2, false)
    default:
      throw new Error('box-intersect: Invalid arguments')
  }
}
},{"./lib/intersect":87,"./lib/sweep":91,"typedarray-pool":523}],86:[function(_dereq_,module,exports){
'use strict'

var DIMENSION   = 'd'
var AXIS        = 'ax'
var VISIT       = 'vv'
var FLIP        = 'fp'

var ELEM_SIZE   = 'es'

var RED_START   = 'rs'
var RED_END     = 're'
var RED_BOXES   = 'rb'
var RED_INDEX   = 'ri'
var RED_PTR     = 'rp'

var BLUE_START  = 'bs'
var BLUE_END    = 'be'
var BLUE_BOXES  = 'bb'
var BLUE_INDEX  = 'bi'
var BLUE_PTR    = 'bp'

var RETVAL      = 'rv'

var INNER_LABEL = 'Q'

var ARGS = [
  DIMENSION,
  AXIS,
  VISIT,
  RED_START,
  RED_END,
  RED_BOXES,
  RED_INDEX,
  BLUE_START,
  BLUE_END,
  BLUE_BOXES,
  BLUE_INDEX
]

function generateBruteForce(redMajor, flip, full) {
  var funcName = 'bruteForce' + 
    (redMajor ? 'Red' : 'Blue') + 
    (flip ? 'Flip' : '') +
    (full ? 'Full' : '')

  var code = ['function ', funcName, '(', ARGS.join(), '){',
    'var ', ELEM_SIZE, '=2*', DIMENSION, ';']

  var redLoop = 
    'for(var i=' + RED_START + ',' + RED_PTR + '=' + ELEM_SIZE + '*' + RED_START + ';' +
        'i<' + RED_END +';' +
        '++i,' + RED_PTR + '+=' + ELEM_SIZE + '){' +
        'var x0=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '],' +
            'x1=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '+' + DIMENSION + '],' +
            'xi=' + RED_INDEX + '[i];'

  var blueLoop = 
    'for(var j=' + BLUE_START + ',' + BLUE_PTR + '=' + ELEM_SIZE + '*' + BLUE_START + ';' +
        'j<' + BLUE_END + ';' +
        '++j,' + BLUE_PTR + '+=' + ELEM_SIZE + '){' +
        'var y0=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '],' +
            (full ? 'y1=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '+' + DIMENSION + '],' : '') +
            'yi=' + BLUE_INDEX + '[j];'

  if(redMajor) {
    code.push(redLoop, INNER_LABEL, ':', blueLoop)
  } else {
    code.push(blueLoop, INNER_LABEL, ':', redLoop)
  }

  if(full) {
    code.push('if(y1<x0||x1<y0)continue;')
  } else if(flip) {
    code.push('if(y0<=x0||x1<y0)continue;')
  } else {
    code.push('if(y0<x0||x1<y0)continue;')
  }

  code.push('for(var k='+AXIS+'+1;k<'+DIMENSION+';++k){'+
    'var r0='+RED_BOXES+'[k+'+RED_PTR+'],'+
        'r1='+RED_BOXES+'[k+'+DIMENSION+'+'+RED_PTR+'],'+
        'b0='+BLUE_BOXES+'[k+'+BLUE_PTR+'],'+
        'b1='+BLUE_BOXES+'[k+'+DIMENSION+'+'+BLUE_PTR+'];'+
      'if(r1<b0||b1<r0)continue ' + INNER_LABEL + ';}' +
      'var ' + RETVAL + '=' + VISIT + '(')

  if(flip) {
    code.push('yi,xi')
  } else {
    code.push('xi,yi')
  }

  code.push(');if(' + RETVAL + '!==void 0)return ' + RETVAL + ';}}}')

  return {
    name: funcName, 
    code: code.join('')
  }
}

function bruteForcePlanner(full) {
  var funcName = 'bruteForce' + (full ? 'Full' : 'Partial')
  var prefix = []
  var fargs = ARGS.slice()
  if(!full) {
    fargs.splice(3, 0, FLIP)
  }

  var code = ['function ' + funcName + '(' + fargs.join() + '){']

  function invoke(redMajor, flip) {
    var res = generateBruteForce(redMajor, flip, full)
    prefix.push(res.code)
    code.push('return ' + res.name + '(' + ARGS.join() + ');')
  }

  code.push('if(' + RED_END + '-' + RED_START + '>' +
                    BLUE_END + '-' + BLUE_START + '){')

  if(full) {
    invoke(true, false)
    code.push('}else{')
    invoke(false, false)
  } else {
    code.push('if(' + FLIP + '){')
    invoke(true, true)
    code.push('}else{')
    invoke(true, false)
    code.push('}}else{if(' + FLIP + '){')
    invoke(false, true)
    code.push('}else{')
    invoke(false, false)
    code.push('}')
  }
  code.push('}}return ' + funcName)

  var codeStr = prefix.join('') + code.join('')
  var proc = new Function(codeStr)
  return proc()
}


exports.partial = bruteForcePlanner(false)
exports.full    = bruteForcePlanner(true)
},{}],87:[function(_dereq_,module,exports){
'use strict'

module.exports = boxIntersectIter

var pool = _dereq_('typedarray-pool')
var bits = _dereq_('bit-twiddle')
var bruteForce = _dereq_('./brute')
var bruteForcePartial = bruteForce.partial
var bruteForceFull = bruteForce.full
var sweep = _dereq_('./sweep')
var findMedian = _dereq_('./median')
var genPartition = _dereq_('./partition')

//Twiddle parameters
var BRUTE_FORCE_CUTOFF    = 128       //Cut off for brute force search
var SCAN_CUTOFF           = (1<<22)   //Cut off for two way scan
var SCAN_COMPLETE_CUTOFF  = (1<<22)  

//Partition functions
var partitionInteriorContainsInterval = genPartition(
  '!(lo>=p0)&&!(p1>=hi)', 
  ['p0', 'p1'])

var partitionStartEqual = genPartition(
  'lo===p0',
  ['p0'])

var partitionStartLessThan = genPartition(
  'lo<p0',
  ['p0'])

var partitionEndLessThanEqual = genPartition(
  'hi<=p0',
  ['p0'])

var partitionContainsPoint = genPartition(
  'lo<=p0&&p0<=hi',
  ['p0'])

var partitionContainsPointProper = genPartition(
  'lo<p0&&p0<=hi',
  ['p0'])

//Frame size for iterative loop
var IFRAME_SIZE = 6
var DFRAME_SIZE = 2

//Data for box statck
var INIT_CAPACITY = 1024
var BOX_ISTACK  = pool.mallocInt32(INIT_CAPACITY)
var BOX_DSTACK  = pool.mallocDouble(INIT_CAPACITY)

//Initialize iterative loop queue
function iterInit(d, count) {
  var levels = (8 * bits.log2(count+1) * (d+1))|0
  var maxInts = bits.nextPow2(IFRAME_SIZE*levels)
  if(BOX_ISTACK.length < maxInts) {
    pool.free(BOX_ISTACK)
    BOX_ISTACK = pool.mallocInt32(maxInts)
  }
  var maxDoubles = bits.nextPow2(DFRAME_SIZE*levels)
  if(BOX_DSTACK < maxDoubles) {
    pool.free(BOX_DSTACK)
    BOX_DSTACK = pool.mallocDouble(maxDoubles)
  }
}

//Append item to queue
function iterPush(ptr,
  axis, 
  redStart, redEnd, 
  blueStart, blueEnd, 
  state, 
  lo, hi) {

  var iptr = IFRAME_SIZE * ptr
  BOX_ISTACK[iptr]   = axis
  BOX_ISTACK[iptr+1] = redStart
  BOX_ISTACK[iptr+2] = redEnd
  BOX_ISTACK[iptr+3] = blueStart
  BOX_ISTACK[iptr+4] = blueEnd
  BOX_ISTACK[iptr+5] = state

  var dptr = DFRAME_SIZE * ptr
  BOX_DSTACK[dptr]   = lo
  BOX_DSTACK[dptr+1] = hi
}

//Special case:  Intersect single point with list of intervals
function onePointPartial(
  d, axis, visit, flip,
  redStart, redEnd, red, redIndex,
  blueOffset, blue, blueId) {

  var elemSize = 2 * d
  var bluePtr  = blueOffset * elemSize
  var blueX    = blue[bluePtr + axis]

red_loop:
  for(var i=redStart, redPtr=redStart*elemSize; i<redEnd; ++i, redPtr+=elemSize) {
    var r0 = red[redPtr+axis]
    var r1 = red[redPtr+axis+d]
    if(blueX < r0 || r1 < blueX) {
      continue
    }
    if(flip && blueX === r0) {
      continue
    }
    var redId = redIndex[i]
    for(var j=axis+1; j<d; ++j) {
      var r0 = red[redPtr+j]
      var r1 = red[redPtr+j+d]
      var b0 = blue[bluePtr+j]
      var b1 = blue[bluePtr+j+d]
      if(r1 < b0 || b1 < r0) {
        continue red_loop
      }
    }
    var retval
    if(flip) {
      retval = visit(blueId, redId)
    } else {
      retval = visit(redId, blueId)
    }
    if(retval !== void 0) {
      return retval
    }
  }
}

//Special case:  Intersect one point with list of intervals
function onePointFull(
  d, axis, visit,
  redStart, redEnd, red, redIndex,
  blueOffset, blue, blueId) {

  var elemSize = 2 * d
  var bluePtr  = blueOffset * elemSize
  var blueX    = blue[bluePtr + axis]

red_loop:
  for(var i=redStart, redPtr=redStart*elemSize; i<redEnd; ++i, redPtr+=elemSize) {
    var redId = redIndex[i]
    if(redId === blueId) {
      continue
    }
    var r0 = red[redPtr+axis]
    var r1 = red[redPtr+axis+d]
    if(blueX < r0 || r1 < blueX) {
      continue
    }
    for(var j=axis+1; j<d; ++j) {
      var r0 = red[redPtr+j]
      var r1 = red[redPtr+j+d]
      var b0 = blue[bluePtr+j]
      var b1 = blue[bluePtr+j+d]
      if(r1 < b0 || b1 < r0) {
        continue red_loop
      }
    }
    var retval = visit(redId, blueId)
    if(retval !== void 0) {
      return retval
    }
  }
}

//The main box intersection routine
function boxIntersectIter(
  d, visit, initFull,
  xSize, xBoxes, xIndex,
  ySize, yBoxes, yIndex) {

  //Reserve memory for stack
  iterInit(d, xSize + ySize)

  var top  = 0
  var elemSize = 2 * d
  var retval

  iterPush(top++,
      0,
      0, xSize,
      0, ySize,
      initFull ? 16 : 0, 
      -Infinity, Infinity)
  if(!initFull) {
    iterPush(top++,
      0,
      0, ySize,
      0, xSize,
      1, 
      -Infinity, Infinity)
  }

  while(top > 0) {
    top  -= 1

    var iptr = top * IFRAME_SIZE
    var axis      = BOX_ISTACK[iptr]
    var redStart  = BOX_ISTACK[iptr+1]
    var redEnd    = BOX_ISTACK[iptr+2]
    var blueStart = BOX_ISTACK[iptr+3]
    var blueEnd   = BOX_ISTACK[iptr+4]
    var state     = BOX_ISTACK[iptr+5]

    var dptr = top * DFRAME_SIZE
    var lo        = BOX_DSTACK[dptr]
    var hi        = BOX_DSTACK[dptr+1]

    //Unpack state info
    var flip      = (state & 1)
    var full      = !!(state & 16)

    //Unpack indices
    var red       = xBoxes
    var redIndex  = xIndex
    var blue      = yBoxes
    var blueIndex = yIndex
    if(flip) {
      red         = yBoxes
      redIndex    = yIndex
      blue        = xBoxes
      blueIndex   = xIndex
    }

    if(state & 2) {
      redEnd = partitionStartLessThan(
        d, axis,
        redStart, redEnd, red, redIndex,
        hi)
      if(redStart >= redEnd) {
        continue
      }
    }
    if(state & 4) {
      redStart = partitionEndLessThanEqual(
        d, axis,
        redStart, redEnd, red, redIndex,
        lo)
      if(redStart >= redEnd) {
        continue
      }
    }
    
    var redCount  = redEnd  - redStart
    var blueCount = blueEnd - blueStart

    if(full) {
      if(d * redCount * (redCount + blueCount) < SCAN_COMPLETE_CUTOFF) {
        retval = sweep.scanComplete(
          d, axis, visit, 
          redStart, redEnd, red, redIndex,
          blueStart, blueEnd, blue, blueIndex)
        if(retval !== void 0) {
          return retval
        }
        continue
      }
    } else {
      if(d * Math.min(redCount, blueCount) < BRUTE_FORCE_CUTOFF) {
        //If input small, then use brute force
        retval = bruteForcePartial(
            d, axis, visit, flip,
            redStart,  redEnd,  red,  redIndex,
            blueStart, blueEnd, blue, blueIndex)
        if(retval !== void 0) {
          return retval
        }
        continue
      } else if(d * redCount * blueCount < SCAN_CUTOFF) {
        //If input medium sized, then use sweep and prune
        retval = sweep.scanBipartite(
          d, axis, visit, flip, 
          redStart, redEnd, red, redIndex,
          blueStart, blueEnd, blue, blueIndex)
        if(retval !== void 0) {
          return retval
        }
        continue
      }
    }
    
    //First, find all red intervals whose interior contains (lo,hi)
    var red0 = partitionInteriorContainsInterval(
      d, axis, 
      redStart, redEnd, red, redIndex,
      lo, hi)

    //Lower dimensional case
    if(redStart < red0) {

      if(d * (red0 - redStart) < BRUTE_FORCE_CUTOFF) {
        //Special case for small inputs: use brute force
        retval = bruteForceFull(
          d, axis+1, visit,
          redStart, red0, red, redIndex,
          blueStart, blueEnd, blue, blueIndex)
        if(retval !== void 0) {
          return retval
        }
      } else if(axis === d-2) {
        if(flip) {
          retval = sweep.sweepBipartite(
            d, visit,
            blueStart, blueEnd, blue, blueIndex,
            redStart, red0, red, redIndex)
        } else {
          retval = sweep.sweepBipartite(
            d, visit,
            redStart, red0, red, redIndex,
            blueStart, blueEnd, blue, blueIndex)
        }
        if(retval !== void 0) {
          return retval
        }
      } else {
        iterPush(top++,
          axis+1,
          redStart, red0,
          blueStart, blueEnd,
          flip,
          -Infinity, Infinity)
        iterPush(top++,
          axis+1,
          blueStart, blueEnd,
          redStart, red0,
          flip^1,
          -Infinity, Infinity)
      }
    }

    //Divide and conquer phase
    if(red0 < redEnd) {

      //Cut blue into 3 parts:
      //
      //  Points < mid point
      //  Points = mid point
      //  Points > mid point
      //
      var blue0 = findMedian(
        d, axis, 
        blueStart, blueEnd, blue, blueIndex)
      var mid = blue[elemSize * blue0 + axis]
      var blue1 = partitionStartEqual(
        d, axis,
        blue0, blueEnd, blue, blueIndex,
        mid)

      //Right case
      if(blue1 < blueEnd) {
        iterPush(top++,
          axis,
          red0, redEnd,
          blue1, blueEnd,
          (flip|4) + (full ? 16 : 0),
          mid, hi)
      }

      //Left case
      if(blueStart < blue0) {
        iterPush(top++,
          axis,
          red0, redEnd,
          blueStart, blue0,
          (flip|2) + (full ? 16 : 0),
          lo, mid)
      }

      //Center case (the hard part)
      if(blue0 + 1 === blue1) {
        //Optimization: Range with exactly 1 point, use a brute force scan
        if(full) {
          retval = onePointFull(
            d, axis, visit,
            red0, redEnd, red, redIndex,
            blue0, blue, blueIndex[blue0])
        } else {
          retval = onePointPartial(
            d, axis, visit, flip,
            red0, redEnd, red, redIndex,
            blue0, blue, blueIndex[blue0])
        }
        if(retval !== void 0) {
          return retval
        }
      } else if(blue0 < blue1) {
        var red1
        if(full) {
          //If full intersection, need to handle special case
          red1 = partitionContainsPoint(
            d, axis,
            red0, redEnd, red, redIndex,
            mid)
          if(red0 < red1) {
            var redX = partitionStartEqual(
              d, axis,
              red0, red1, red, redIndex,
              mid)
            if(axis === d-2) {
              //Degenerate sweep intersection:
              //  [red0, redX] with [blue0, blue1]
              if(red0 < redX) {
                retval = sweep.sweepComplete(
                  d, visit,
                  red0, redX, red, redIndex,
                  blue0, blue1, blue, blueIndex)
                if(retval !== void 0) {
                  return retval
                }
              }

              //Normal sweep intersection:
              //  [redX, red1] with [blue0, blue1]
              if(redX < red1) {
                retval = sweep.sweepBipartite(
                  d, visit,
                  redX, red1, red, redIndex,
                  blue0, blue1, blue, blueIndex)
                if(retval !== void 0) {
                  return retval
                }
              }
            } else {
              if(red0 < redX) {
                iterPush(top++,
                  axis+1,
                  red0, redX,
                  blue0, blue1,
                  16,
                  -Infinity, Infinity)
              }
              if(redX < red1) {
                iterPush(top++,
                  axis+1,
                  redX, red1,
                  blue0, blue1,
                  0,
                  -Infinity, Infinity)
                iterPush(top++,
                  axis+1,
                  blue0, blue1,
                  redX, red1,
                  1,
                  -Infinity, Infinity)
              }
            }
          }
        } else {
          if(flip) {
            red1 = partitionContainsPointProper(
              d, axis,
              red0, redEnd, red, redIndex,
              mid)
          } else {
            red1 = partitionContainsPoint(
              d, axis,
              red0, redEnd, red, redIndex,
              mid)
          }
          if(red0 < red1) {
            if(axis === d-2) {
              if(flip) {
                retval = sweep.sweepBipartite(
                  d, visit,
                  blue0, blue1, blue, blueIndex,
                  red0, red1, red, redIndex)
              } else {
                retval = sweep.sweepBipartite(
                  d, visit,
                  red0, red1, red, redIndex,
                  blue0, blue1, blue, blueIndex)
              }
            } else {
              iterPush(top++,
                axis+1,
                red0, red1,
                blue0, blue1,
                flip,
                -Infinity, Infinity)
              iterPush(top++,
                axis+1,
                blue0, blue1,
                red0, red1,
                flip^1,
                -Infinity, Infinity)
            }
          }
        }
      }
    }
  }
}
},{"./brute":86,"./median":88,"./partition":89,"./sweep":91,"bit-twiddle":81,"typedarray-pool":523}],88:[function(_dereq_,module,exports){
'use strict'

module.exports = findMedian

var genPartition = _dereq_('./partition')

var partitionStartLessThan = genPartition('lo<p0', ['p0'])

var PARTITION_THRESHOLD = 8   //Cut off for using insertion sort in findMedian

//Base case for median finding:  Use insertion sort
function insertionSort(d, axis, start, end, boxes, ids) {
  var elemSize = 2 * d
  var boxPtr = elemSize * (start+1) + axis
  for(var i=start+1; i<end; ++i, boxPtr+=elemSize) {
    var x = boxes[boxPtr]
    for(var j=i, ptr=elemSize*(i-1); 
        j>start && boxes[ptr+axis] > x; 
        --j, ptr-=elemSize) {
      //Swap
      var aPtr = ptr
      var bPtr = ptr+elemSize
      for(var k=0; k<elemSize; ++k, ++aPtr, ++bPtr) {
        var y = boxes[aPtr]
        boxes[aPtr] = boxes[bPtr]
        boxes[bPtr] = y
      }
      var tmp = ids[j]
      ids[j] = ids[j-1]
      ids[j-1] = tmp
    }
  }
}

//Find median using quick select algorithm
//  takes O(n) time with high probability
function findMedian(d, axis, start, end, boxes, ids) {
  if(end <= start+1) {
    return start
  }

  var lo       = start
  var hi       = end
  var mid      = ((end + start) >>> 1)
  var elemSize = 2*d
  var pivot    = mid
  var value    = boxes[elemSize*mid+axis]
  
  while(lo < hi) {
    if(hi - lo < PARTITION_THRESHOLD) {
      insertionSort(d, axis, lo, hi, boxes, ids)
      value = boxes[elemSize*mid+axis]
      break
    }
    
    //Select pivot using median-of-3
    var count  = hi - lo
    var pivot0 = (Math.random()*count+lo)|0
    var value0 = boxes[elemSize*pivot0 + axis]
    var pivot1 = (Math.random()*count+lo)|0
    var value1 = boxes[elemSize*pivot1 + axis]
    var pivot2 = (Math.random()*count+lo)|0
    var value2 = boxes[elemSize*pivot2 + axis]
    if(value0 <= value1) {
      if(value2 >= value1) {
        pivot = pivot1
        value = value1
      } else if(value0 >= value2) {
        pivot = pivot0
        value = value0
      } else {
        pivot = pivot2
        value = value2
      }
    } else {
      if(value1 >= value2) {
        pivot = pivot1
        value = value1
      } else if(value2 >= value0) {
        pivot = pivot0
        value = value0
      } else {
        pivot = pivot2
        value = value2
      }
    }

    //Swap pivot to end of array
    var aPtr = elemSize * (hi-1)
    var bPtr = elemSize * pivot
    for(var i=0; i<elemSize; ++i, ++aPtr, ++bPtr) {
      var x = boxes[aPtr]
      boxes[aPtr] = boxes[bPtr]
      boxes[bPtr] = x
    }
    var y = ids[hi-1]
    ids[hi-1] = ids[pivot]
    ids[pivot] = y

    //Partition using pivot
    pivot = partitionStartLessThan(
      d, axis, 
      lo, hi-1, boxes, ids,
      value)

    //Swap pivot back
    var aPtr = elemSize * (hi-1)
    var bPtr = elemSize * pivot
    for(var i=0; i<elemSize; ++i, ++aPtr, ++bPtr) {
      var x = boxes[aPtr]
      boxes[aPtr] = boxes[bPtr]
      boxes[bPtr] = x
    }
    var y = ids[hi-1]
    ids[hi-1] = ids[pivot]
    ids[pivot] = y

    //Swap pivot to last pivot
    if(mid < pivot) {
      hi = pivot-1
      while(lo < hi && 
        boxes[elemSize*(hi-1)+axis] === value) {
        hi -= 1
      }
      hi += 1
    } else if(pivot < mid) {
      lo = pivot + 1
      while(lo < hi &&
        boxes[elemSize*lo+axis] === value) {
        lo += 1
      }
    } else {
      break
    }
  }

  //Make sure pivot is at start
  return partitionStartLessThan(
    d, axis, 
    start, mid, boxes, ids,
    boxes[elemSize*mid+axis])
}
},{"./partition":89}],89:[function(_dereq_,module,exports){
'use strict'

module.exports = genPartition

var code = 'for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m'

function genPartition(predicate, args) {
  var fargs ='abcdef'.split('').concat(args)
  var reads = []
  if(predicate.indexOf('lo') >= 0) {
    reads.push('lo=e[k+n]')
  }
  if(predicate.indexOf('hi') >= 0) {
    reads.push('hi=e[k+o]')
  }
  fargs.push(
    code.replace('_', reads.join())
        .replace('$', predicate))
  return Function.apply(void 0, fargs)
}
},{}],90:[function(_dereq_,module,exports){
'use strict';

//This code is extracted from ndarray-sort
//It is inlined here as a temporary workaround

module.exports = wrapper;

var INSERT_SORT_CUTOFF = 32

function wrapper(data, n0) {
  if (n0 <= 4*INSERT_SORT_CUTOFF) {
    insertionSort(0, n0 - 1, data);
  } else {
    quickSort(0, n0 - 1, data);
  }
}

function insertionSort(left, right, data) {
  var ptr = 2*(left+1)
  for(var i=left+1; i<=right; ++i) {
    var a = data[ptr++]
    var b = data[ptr++]
    var j = i
    var jptr = ptr-2
    while(j-- > left) {
      var x = data[jptr-2]
      var y = data[jptr-1]
      if(x < a) {
        break
      } else if(x === a && y < b) {
        break
      }
      data[jptr]   = x
      data[jptr+1] = y
      jptr -= 2
    }
    data[jptr]   = a
    data[jptr+1] = b
  }
}

function swap(i, j, data) {
  i *= 2
  j *= 2
  var x = data[i]
  var y = data[i+1]
  data[i] = data[j]
  data[i+1] = data[j+1]
  data[j] = x
  data[j+1] = y
}

function move(i, j, data) {
  i *= 2
  j *= 2
  data[i] = data[j]
  data[i+1] = data[j+1]
}

function rotate(i, j, k, data) {
  i *= 2
  j *= 2
  k *= 2
  var x = data[i]
  var y = data[i+1]
  data[i] = data[j]
  data[i+1] = data[j+1]
  data[j] = data[k]
  data[j+1] = data[k+1]
  data[k] = x
  data[k+1] = y
}

function shufflePivot(i, j, px, py, data) {
  i *= 2
  j *= 2
  data[i] = data[j]
  data[j] = px
  data[i+1] = data[j+1]
  data[j+1] = py
}

function compare(i, j, data) {
  i *= 2
  j *= 2
  var x = data[i],
      y = data[j]
  if(x < y) {
    return false
  } else if(x === y) {
    return data[i+1] > data[j+1]
  }
  return true
}

function comparePivot(i, y, b, data) {
  i *= 2
  var x = data[i]
  if(x < y) {
    return true
  } else if(x === y) {
    return data[i+1] < b
  }
  return false
}

function quickSort(left, right, data) {
  var sixth = (right - left + 1) / 6 | 0, 
      index1 = left + sixth, 
      index5 = right - sixth, 
      index3 = left + right >> 1, 
      index2 = index3 - sixth, 
      index4 = index3 + sixth, 
      el1 = index1, 
      el2 = index2, 
      el3 = index3, 
      el4 = index4, 
      el5 = index5, 
      less = left + 1, 
      great = right - 1, 
      tmp = 0
  if(compare(el1, el2, data)) {
    tmp = el1
    el1 = el2
    el2 = tmp
  }
  if(compare(el4, el5, data)) {
    tmp = el4
    el4 = el5
    el5 = tmp
  }
  if(compare(el1, el3, data)) {
    tmp = el1
    el1 = el3
    el3 = tmp
  }
  if(compare(el2, el3, data)) {
    tmp = el2
    el2 = el3
    el3 = tmp
  }
  if(compare(el1, el4, data)) {
    tmp = el1
    el1 = el4
    el4 = tmp
  }
  if(compare(el3, el4, data)) {
    tmp = el3
    el3 = el4
    el4 = tmp
  }
  if(compare(el2, el5, data)) {
    tmp = el2
    el2 = el5
    el5 = tmp
  }
  if(compare(el2, el3, data)) {
    tmp = el2
    el2 = el3
    el3 = tmp
  }
  if(compare(el4, el5, data)) {
    tmp = el4
    el4 = el5
    el5 = tmp
  }

  var pivot1X = data[2*el2]
  var pivot1Y = data[2*el2+1]
  var pivot2X = data[2*el4]
  var pivot2Y = data[2*el4+1]

  var ptr0 = 2 * el1;
  var ptr2 = 2 * el3;
  var ptr4 = 2 * el5;
  var ptr5 = 2 * index1;
  var ptr6 = 2 * index3;
  var ptr7 = 2 * index5;
  for (var i1 = 0; i1 < 2; ++i1) {
    var x = data[ptr0+i1];
    var y = data[ptr2+i1];
    var z = data[ptr4+i1];
    data[ptr5+i1] = x;
    data[ptr6+i1] = y;
    data[ptr7+i1] = z;
  }

  move(index2, left, data)
  move(index4, right, data)
  for (var k = less; k <= great; ++k) {
    if (comparePivot(k, pivot1X, pivot1Y, data)) {
      if (k !== less) {
        swap(k, less, data)
      }
      ++less;
    } else {
      if (!comparePivot(k, pivot2X, pivot2Y, data)) {
        while (true) {
          if (!comparePivot(great, pivot2X, pivot2Y, data)) {
            if (--great < k) {
              break;
            }
            continue;
          } else {
            if (comparePivot(great, pivot1X, pivot1Y, data)) {
              rotate(k, less, great, data)
              ++less;
              --great;
            } else {
              swap(k, great, data)
              --great;
            }
            break;
          }
        }
      }
    }
  }
  shufflePivot(left, less-1, pivot1X, pivot1Y, data)
  shufflePivot(right, great+1, pivot2X, pivot2Y, data)
  if (less - 2 - left <= INSERT_SORT_CUTOFF) {
    insertionSort(left, less - 2, data);
  } else {
    quickSort(left, less - 2, data);
  }
  if (right - (great + 2) <= INSERT_SORT_CUTOFF) {
    insertionSort(great + 2, right, data);
  } else {
    quickSort(great + 2, right, data);
  }
  if (great - less <= INSERT_SORT_CUTOFF) {
    insertionSort(less, great, data);
  } else {
    quickSort(less, great, data);
  }
}
},{}],91:[function(_dereq_,module,exports){
'use strict'

module.exports = {
  init:           sqInit,
  sweepBipartite: sweepBipartite,
  sweepComplete:  sweepComplete,
  scanBipartite:  scanBipartite,
  scanComplete:   scanComplete
}

var pool  = _dereq_('typedarray-pool')
var bits  = _dereq_('bit-twiddle')
var isort = _dereq_('./sort')

//Flag for blue
var BLUE_FLAG = (1<<28)

//1D sweep event queue stuff (use pool to save space)
var INIT_CAPACITY      = 1024
var RED_SWEEP_QUEUE    = pool.mallocInt32(INIT_CAPACITY)
var RED_SWEEP_INDEX    = pool.mallocInt32(INIT_CAPACITY)
var BLUE_SWEEP_QUEUE   = pool.mallocInt32(INIT_CAPACITY)
var BLUE_SWEEP_INDEX   = pool.mallocInt32(INIT_CAPACITY)
var COMMON_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY)
var COMMON_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY)
var SWEEP_EVENTS       = pool.mallocDouble(INIT_CAPACITY * 8)

//Reserves memory for the 1D sweep data structures
function sqInit(count) {
  var rcount = bits.nextPow2(count)
  if(RED_SWEEP_QUEUE.length < rcount) {
    pool.free(RED_SWEEP_QUEUE)
    RED_SWEEP_QUEUE = pool.mallocInt32(rcount)
  }
  if(RED_SWEEP_INDEX.length < rcount) {
    pool.free(RED_SWEEP_INDEX)
    RED_SWEEP_INDEX = pool.mallocInt32(rcount)
  }
  if(BLUE_SWEEP_QUEUE.length < rcount) {
    pool.free(BLUE_SWEEP_QUEUE)
    BLUE_SWEEP_QUEUE = pool.mallocInt32(rcount)
  }
  if(BLUE_SWEEP_INDEX.length < rcount) {
    pool.free(BLUE_SWEEP_INDEX)
    BLUE_SWEEP_INDEX = pool.mallocInt32(rcount)
  }
  if(COMMON_SWEEP_QUEUE.length < rcount) {
    pool.free(COMMON_SWEEP_QUEUE)
    COMMON_SWEEP_QUEUE = pool.mallocInt32(rcount)
  }
  if(COMMON_SWEEP_INDEX.length < rcount) {
    pool.free(COMMON_SWEEP_INDEX)
    COMMON_SWEEP_INDEX = pool.mallocInt32(rcount)
  }
  var eventLength = 8 * rcount
  if(SWEEP_EVENTS.length < eventLength) {
    pool.free(SWEEP_EVENTS)
    SWEEP_EVENTS = pool.mallocDouble(eventLength)
  }
}

//Remove an item from the active queue in O(1)
function sqPop(queue, index, count, item) {
  var idx = index[item]
  var top = queue[count-1]
  queue[idx] = top
  index[top] = idx
}

//Insert an item into the active queue in O(1)
function sqPush(queue, index, count, item) {
  queue[count] = item
  index[item]  = count
}

//Recursion base case: use 1D sweep algorithm
function sweepBipartite(
    d, visit,
    redStart,  redEnd, red, redIndex,
    blueStart, blueEnd, blue, blueIndex) {

  //store events as pairs [coordinate, idx]
  //
  //  red create:  -(idx+1)
  //  red destroy: idx
  //  blue create: -(idx+BLUE_FLAG)
  //  blue destroy: idx+BLUE_FLAG
  //
  var ptr      = 0
  var elemSize = 2*d
  var istart   = d-1
  var iend     = elemSize-1

  for(var i=redStart; i<redEnd; ++i) {
    var idx = redIndex[i]
    var redOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = red[redOffset+istart]
    SWEEP_EVENTS[ptr++] = -(idx+1)
    SWEEP_EVENTS[ptr++] = red[redOffset+iend]
    SWEEP_EVENTS[ptr++] = idx
  }

  for(var i=blueStart; i<blueEnd; ++i) {
    var idx = blueIndex[i]+BLUE_FLAG
    var blueOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = blue[blueOffset+istart]
    SWEEP_EVENTS[ptr++] = -idx
    SWEEP_EVENTS[ptr++] = blue[blueOffset+iend]
    SWEEP_EVENTS[ptr++] = idx
  }

  //process events from left->right
  var n = ptr >>> 1
  isort(SWEEP_EVENTS, n)
  
  var redActive  = 0
  var blueActive = 0
  for(var i=0; i<n; ++i) {
    var e = SWEEP_EVENTS[2*i+1]|0
    if(e >= BLUE_FLAG) {
      //blue destroy event
      e = (e-BLUE_FLAG)|0
      sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, e)
    } else if(e >= 0) {
      //red destroy event
      sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e)
    } else if(e <= -BLUE_FLAG) {
      //blue create event
      e = (-e-BLUE_FLAG)|0
      for(var j=0; j<redActive; ++j) {
        var retval = visit(RED_SWEEP_QUEUE[j], e)
        if(retval !== void 0) {
          return retval
        }
      }
      sqPush(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive++, e)
    } else {
      //red create event
      e = (-e-1)|0
      for(var j=0; j<blueActive; ++j) {
        var retval = visit(e, BLUE_SWEEP_QUEUE[j])
        if(retval !== void 0) {
          return retval
        }
      }
      sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, e)
    }
  }
}

//Complete sweep
function sweepComplete(d, visit, 
  redStart, redEnd, red, redIndex,
  blueStart, blueEnd, blue, blueIndex) {

  var ptr      = 0
  var elemSize = 2*d
  var istart   = d-1
  var iend     = elemSize-1

  for(var i=redStart; i<redEnd; ++i) {
    var idx = (redIndex[i]+1)<<1
    var redOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = red[redOffset+istart]
    SWEEP_EVENTS[ptr++] = -idx
    SWEEP_EVENTS[ptr++] = red[redOffset+iend]
    SWEEP_EVENTS[ptr++] = idx
  }

  for(var i=blueStart; i<blueEnd; ++i) {
    var idx = (blueIndex[i]+1)<<1
    var blueOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = blue[blueOffset+istart]
    SWEEP_EVENTS[ptr++] = (-idx)|1
    SWEEP_EVENTS[ptr++] = blue[blueOffset+iend]
    SWEEP_EVENTS[ptr++] = idx|1
  }

  //process events from left->right
  var n = ptr >>> 1
  isort(SWEEP_EVENTS, n)
  
  var redActive    = 0
  var blueActive   = 0
  var commonActive = 0
  for(var i=0; i<n; ++i) {
    var e     = SWEEP_EVENTS[2*i+1]|0
    var color = e&1
    if(i < n-1 && (e>>1) === (SWEEP_EVENTS[2*i+3]>>1)) {
      color = 2
      i += 1
    }
    
    if(e < 0) {
      //Create event
      var id = -(e>>1) - 1

      //Intersect with common
      for(var j=0; j<commonActive; ++j) {
        var retval = visit(COMMON_SWEEP_QUEUE[j], id)
        if(retval !== void 0) {
          return retval
        }
      }

      if(color !== 0) {
        //Intersect with red
        for(var j=0; j<redActive; ++j) {
          var retval = visit(RED_SWEEP_QUEUE[j], id)
          if(retval !== void 0) {
            return retval
          }
        }
      }

      if(color !== 1) {
        //Intersect with blue
        for(var j=0; j<blueActive; ++j) {
          var retval = visit(BLUE_SWEEP_QUEUE[j], id)
          if(retval !== void 0) {
            return retval
          }
        }
      }

      if(color === 0) {
        //Red
        sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, id)
      } else if(color === 1) {
        //Blue
        sqPush(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive++, id)
      } else if(color === 2) {
        //Both
        sqPush(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive++, id)
      }
    } else {
      //Destroy event
      var id = (e>>1) - 1
      if(color === 0) {
        //Red
        sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, id)
      } else if(color === 1) {
        //Blue
        sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, id)
      } else if(color === 2) {
        //Both
        sqPop(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive--, id)
      }
    }
  }
}

//Sweep and prune/scanline algorithm:
//  Scan along axis, detect intersections
//  Brute force all boxes along axis
function scanBipartite(
  d, axis, visit, flip,
  redStart,  redEnd, red, redIndex,
  blueStart, blueEnd, blue, blueIndex) {
  
  var ptr      = 0
  var elemSize = 2*d
  var istart   = axis
  var iend     = axis+d

  var redShift  = 1
  var blueShift = 1
  if(flip) {
    blueShift = BLUE_FLAG
  } else {
    redShift  = BLUE_FLAG
  }

  for(var i=redStart; i<redEnd; ++i) {
    var idx = i + redShift
    var redOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = red[redOffset+istart]
    SWEEP_EVENTS[ptr++] = -idx
    SWEEP_EVENTS[ptr++] = red[redOffset+iend]
    SWEEP_EVENTS[ptr++] = idx
  }
  for(var i=blueStart; i<blueEnd; ++i) {
    var idx = i + blueShift
    var blueOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = blue[blueOffset+istart]
    SWEEP_EVENTS[ptr++] = -idx
  }

  //process events from left->right
  var n = ptr >>> 1
  isort(SWEEP_EVENTS, n)
  
  var redActive    = 0
  for(var i=0; i<n; ++i) {
    var e = SWEEP_EVENTS[2*i+1]|0
    if(e < 0) {
      var idx   = -e
      var isRed = false
      if(idx >= BLUE_FLAG) {
        isRed = !flip
        idx -= BLUE_FLAG 
      } else {
        isRed = !!flip
        idx -= 1
      }
      if(isRed) {
        sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, idx)
      } else {
        var blueId  = blueIndex[idx]
        var bluePtr = elemSize * idx
        
        var b0 = blue[bluePtr+axis+1]
        var b1 = blue[bluePtr+axis+1+d]

red_loop:
        for(var j=0; j<redActive; ++j) {
          var oidx   = RED_SWEEP_QUEUE[j]
          var redPtr = elemSize * oidx

          if(b1 < red[redPtr+axis+1] || 
             red[redPtr+axis+1+d] < b0) {
            continue
          }

          for(var k=axis+2; k<d; ++k) {
            if(blue[bluePtr + k + d] < red[redPtr + k] || 
               red[redPtr + k + d] < blue[bluePtr + k]) {
              continue red_loop
            }
          }

          var redId  = redIndex[oidx]
          var retval
          if(flip) {
            retval = visit(blueId, redId)
          } else {
            retval = visit(redId, blueId)
          }
          if(retval !== void 0) {
            return retval 
          }
        }
      }
    } else {
      sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e - redShift)
    }
  }
}

function scanComplete(
  d, axis, visit,
  redStart,  redEnd, red, redIndex,
  blueStart, blueEnd, blue, blueIndex) {

  var ptr      = 0
  var elemSize = 2*d
  var istart   = axis
  var iend     = axis+d

  for(var i=redStart; i<redEnd; ++i) {
    var idx = i + BLUE_FLAG
    var redOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = red[redOffset+istart]
    SWEEP_EVENTS[ptr++] = -idx
    SWEEP_EVENTS[ptr++] = red[redOffset+iend]
    SWEEP_EVENTS[ptr++] = idx
  }
  for(var i=blueStart; i<blueEnd; ++i) {
    var idx = i + 1
    var blueOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = blue[blueOffset+istart]
    SWEEP_EVENTS[ptr++] = -idx
  }

  //process events from left->right
  var n = ptr >>> 1
  isort(SWEEP_EVENTS, n)
  
  var redActive    = 0
  for(var i=0; i<n; ++i) {
    var e = SWEEP_EVENTS[2*i+1]|0
    if(e < 0) {
      var idx   = -e
      if(idx >= BLUE_FLAG) {
        RED_SWEEP_QUEUE[redActive++] = idx - BLUE_FLAG
      } else {
        idx -= 1
        var blueId  = blueIndex[idx]
        var bluePtr = elemSize * idx

        var b0 = blue[bluePtr+axis+1]
        var b1 = blue[bluePtr+axis+1+d]

red_loop:
        for(var j=0; j<redActive; ++j) {
          var oidx   = RED_SWEEP_QUEUE[j]
          var redId  = redIndex[oidx]

          if(redId === blueId) {
            break
          }

          var redPtr = elemSize * oidx
          if(b1 < red[redPtr+axis+1] || 
            red[redPtr+axis+1+d] < b0) {
            continue
          }
          for(var k=axis+2; k<d; ++k) {
            if(blue[bluePtr + k + d] < red[redPtr + k] || 
               red[redPtr + k + d]   < blue[bluePtr + k]) {
              continue red_loop
            }
          }

          var retval = visit(redId, blueId)
          if(retval !== void 0) {
            return retval 
          }
        }
      }
    } else {
      var idx = e - BLUE_FLAG
      for(var j=redActive-1; j>=0; --j) {
        if(RED_SWEEP_QUEUE[j] === idx) {
          for(var k=j+1; k<redActive; ++k) {
            RED_SWEEP_QUEUE[k-1] = RED_SWEEP_QUEUE[k]
          }
          break
        }
      }
      --redActive
    }
  }
}
},{"./sort":90,"bit-twiddle":81,"typedarray-pool":523}],92:[function(_dereq_,module,exports){

},{}],93:[function(_dereq_,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.

var objectCreate = Object.create || objectCreatePolyfill
var objectKeys = Object.keys || objectKeysPolyfill
var bind = Function.prototype.bind || functionBindPolyfill

function EventEmitter() {
  if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
    this._events = objectCreate(null);
    this._eventsCount = 0;
  }

  this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;

// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;

EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;

// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
var defaultMaxListeners = 10;

var hasDefineProperty;
try {
  var o = {};
  if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
  hasDefineProperty = o.x === 0;
} catch (err) { hasDefineProperty = false }
if (hasDefineProperty) {
  Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
    enumerable: true,
    get: function() {
      return defaultMaxListeners;
    },
    set: function(arg) {
      // check whether the input is a positive number (whose value is zero or
      // greater and not a NaN).
      if (typeof arg !== 'number' || arg < 0 || arg !== arg)
        throw new TypeError('"defaultMaxListeners" must be a positive number');
      defaultMaxListeners = arg;
    }
  });
} else {
  EventEmitter.defaultMaxListeners = defaultMaxListeners;
}

// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  if (typeof n !== 'number' || n < 0 || isNaN(n))
    throw new TypeError('"n" argument must be a positive number');
  this._maxListeners = n;
  return this;
};

function $getMaxListeners(that) {
  if (that._maxListeners === undefined)
    return EventEmitter.defaultMaxListeners;
  return that._maxListeners;
}

EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  return $getMaxListeners(this);
};

// These standalone emit* functions are used to optimize calling of event
// handlers for fast cases because emit() itself often has a variable number of
// arguments and can be deoptimized because of that. These functions always have
// the same number of arguments and thus do not get deoptimized, so the code
// inside them can execute faster.
function emitNone(handler, isFn, self) {
  if (isFn)
    handler.call(self);
  else {
    var len = handler.length;
    var listeners = arrayClone(handler, len);
    for (var i = 0; i < len; ++i)
      listeners[i].call(self);
  }
}
function emitOne(handler, isFn, self, arg1) {
  if (isFn)
    handler.call(self, arg1);
  else {
    var len = handler.length;
    var listeners = arrayClone(handler, len);
    for (var i = 0; i < len; ++i)
      listeners[i].call(self, arg1);
  }
}
function emitTwo(handler, isFn, self, arg1, arg2) {
  if (isFn)
    handler.call(self, arg1, arg2);
  else {
    var len = handler.length;
    var listeners = arrayClone(handler, len);
    for (var i = 0; i < len; ++i)
      listeners[i].call(self, arg1, arg2);
  }
}
function emitThree(handler, isFn, self, arg1, arg2, arg3) {
  if (isFn)
    handler.call(self, arg1, arg2, arg3);
  else {
    var len = handler.length;
    var listeners = arrayClone(handler, len);
    for (var i = 0; i < len; ++i)
      listeners[i].call(self, arg1, arg2, arg3);
  }
}

function emitMany(handler, isFn, self, args) {
  if (isFn)
    handler.apply(self, args);
  else {
    var len = handler.length;
    var listeners = arrayClone(handler, len);
    for (var i = 0; i < len; ++i)
      listeners[i].apply(self, args);
  }
}

EventEmitter.prototype.emit = function emit(type) {
  var er, handler, len, args, i, events;
  var doError = (type === 'error');

  events = this._events;
  if (events)
    doError = (doError && events.error == null);
  else if (!doError)
    return false;

  // If there is no 'error' event listener then throw.
  if (doError) {
    if (arguments.length > 1)
      er = arguments[1];
    if (er instanceof Error) {
      throw er; // Unhandled 'error' event
    } else {
      // At least give some kind of context to the user
      var err = new Error('Unhandled "error" event. (' + er + ')');
      err.context = er;
      throw err;
    }
    return false;
  }

  handler = events[type];

  if (!handler)
    return false;

  var isFn = typeof handler === 'function';
  len = arguments.length;
  switch (len) {
      // fast cases
    case 1:
      emitNone(handler, isFn, this);
      break;
    case 2:
      emitOne(handler, isFn, this, arguments[1]);
      break;
    case 3:
      emitTwo(handler, isFn, this, arguments[1], arguments[2]);
      break;
    case 4:
      emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
      break;
      // slower
    default:
      args = new Array(len - 1);
      for (i = 1; i < len; i++)
        args[i - 1] = arguments[i];
      emitMany(handler, isFn, this, args);
  }

  return true;
};

function _addListener(target, type, listener, prepend) {
  var m;
  var events;
  var existing;

  if (typeof listener !== 'function')
    throw new TypeError('"listener" argument must be a function');

  events = target._events;
  if (!events) {
    events = target._events = objectCreate(null);
    target._eventsCount = 0;
  } else {
    // To avoid recursion in the case that type === "newListener"! Before
    // adding it to the listeners, first emit "newListener".
    if (events.newListener) {
      target.emit('newListener', type,
          listener.listener ? listener.listener : listener);

      // Re-assign `events` because a newListener handler could have caused the
      // this._events to be assigned to a new object
      events = target._events;
    }
    existing = events[type];
  }

  if (!existing) {
    // Optimize the case of one listener. Don't need the extra array object.
    existing = events[type] = listener;
    ++target._eventsCount;
  } else {
    if (typeof existing === 'function') {
      // Adding the second element, need to change to array.
      existing = events[type] =
          prepend ? [listener, existing] : [existing, listener];
    } else {
      // If we've already got an array, just append.
      if (prepend) {
        existing.unshift(listener);
      } else {
        existing.push(listener);
      }
    }

    // Check for listener leak
    if (!existing.warned) {
      m = $getMaxListeners(target);
      if (m && m > 0 && existing.length > m) {
        existing.warned = true;
        var w = new Error('Possible EventEmitter memory leak detected. ' +
            existing.length + ' "' + String(type) + '" listeners ' +
            'added. Use emitter.setMaxListeners() to ' +
            'increase limit.');
        w.name = 'MaxListenersExceededWarning';
        w.emitter = target;
        w.type = type;
        w.count = existing.length;
        if (typeof console === 'object' && console.warn) {
          console.warn('%s: %s', w.name, w.message);
        }
      }
    }
  }

  return target;
}

EventEmitter.prototype.addListener = function addListener(type, listener) {
  return _addListener(this, type, listener, false);
};

EventEmitter.prototype.on = EventEmitter.prototype.addListener;

EventEmitter.prototype.prependListener =
    function prependListener(type, listener) {
      return _addListener(this, type, listener, true);
    };

function onceWrapper() {
  if (!this.fired) {
    this.target.removeListener(this.type, this.wrapFn);
    this.fired = true;
    switch (arguments.length) {
      case 0:
        return this.listener.call(this.target);
      case 1:
        return this.listener.call(this.target, arguments[0]);
      case 2:
        return this.listener.call(this.target, arguments[0], arguments[1]);
      case 3:
        return this.listener.call(this.target, arguments[0], arguments[1],
            arguments[2]);
      default:
        var args = new Array(arguments.length);
        for (var i = 0; i < args.length; ++i)
          args[i] = arguments[i];
        this.listener.apply(this.target, args);
    }
  }
}

function _onceWrap(target, type, listener) {
  var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  var wrapped = bind.call(onceWrapper, state);
  wrapped.listener = listener;
  state.wrapFn = wrapped;
  return wrapped;
}

EventEmitter.prototype.once = function once(type, listener) {
  if (typeof listener !== 'function')
    throw new TypeError('"listener" argument must be a function');
  this.on(type, _onceWrap(this, type, listener));
  return this;
};

EventEmitter.prototype.prependOnceListener =
    function prependOnceListener(type, listener) {
      if (typeof listener !== 'function')
        throw new TypeError('"listener" argument must be a function');
      this.prependListener(type, _onceWrap(this, type, listener));
      return this;
    };

// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
    function removeListener(type, listener) {
      var list, events, position, i, originalListener;

      if (typeof listener !== 'function')
        throw new TypeError('"listener" argument must be a function');

      events = this._events;
      if (!events)
        return this;

      list = events[type];
      if (!list)
        return this;

      if (list === listener || list.listener === listener) {
        if (--this._eventsCount === 0)
          this._events = objectCreate(null);
        else {
          delete events[type];
          if (events.removeListener)
            this.emit('removeListener', type, list.listener || listener);
        }
      } else if (typeof list !== 'function') {
        position = -1;

        for (i = list.length - 1; i >= 0; i--) {
          if (list[i] === listener || list[i].listener === listener) {
            originalListener = list[i].listener;
            position = i;
            break;
          }
        }

        if (position < 0)
          return this;

        if (position === 0)
          list.shift();
        else
          spliceOne(list, position);

        if (list.length === 1)
          events[type] = list[0];

        if (events.removeListener)
          this.emit('removeListener', type, originalListener || listener);
      }

      return this;
    };

EventEmitter.prototype.removeAllListeners =
    function removeAllListeners(type) {
      var listeners, events, i;

      events = this._events;
      if (!events)
        return this;

      // not listening for removeListener, no need to emit
      if (!events.removeListener) {
        if (arguments.length === 0) {
          this._events = objectCreate(null);
          this._eventsCount = 0;
        } else if (events[type]) {
          if (--this._eventsCount === 0)
            this._events = objectCreate(null);
          else
            delete events[type];
        }
        return this;
      }

      // emit removeListener for all listeners on all events
      if (arguments.length === 0) {
        var keys = objectKeys(events);
        var key;
        for (i = 0; i < keys.length; ++i) {
          key = keys[i];
          if (key === 'removeListener') continue;
          this.removeAllListeners(key);
        }
        this.removeAllListeners('removeListener');
        this._events = objectCreate(null);
        this._eventsCount = 0;
        return this;
      }

      listeners = events[type];

      if (typeof listeners === 'function') {
        this.removeListener(type, listeners);
      } else if (listeners) {
        // LIFO order
        for (i = listeners.length - 1; i >= 0; i--) {
          this.removeListener(type, listeners[i]);
        }
      }

      return this;
    };

function _listeners(target, type, unwrap) {
  var events = target._events;

  if (!events)
    return [];

  var evlistener = events[type];
  if (!evlistener)
    return [];

  if (typeof evlistener === 'function')
    return unwrap ? [evlistener.listener || evlistener] : [evlistener];

  return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}

EventEmitter.prototype.listeners = function listeners(type) {
  return _listeners(this, type, true);
};

EventEmitter.prototype.rawListeners = function rawListeners(type) {
  return _listeners(this, type, false);
};

EventEmitter.listenerCount = function(emitter, type) {
  if (typeof emitter.listenerCount === 'function') {
    return emitter.listenerCount(type);
  } else {
    return listenerCount.call(emitter, type);
  }
};

EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
  var events = this._events;

  if (events) {
    var evlistener = events[type];

    if (typeof evlistener === 'function') {
      return 1;
    } else if (evlistener) {
      return evlistener.length;
    }
  }

  return 0;
}

EventEmitter.prototype.eventNames = function eventNames() {
  return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
};

// About 1.5x faster than the two-arg version of Array#splice().
function spliceOne(list, index) {
  for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
    list[i] = list[k];
  list.pop();
}

function arrayClone(arr, n) {
  var copy = new Array(n);
  for (var i = 0; i < n; ++i)
    copy[i] = arr[i];
  return copy;
}

function unwrapListeners(arr) {
  var ret = new Array(arr.length);
  for (var i = 0; i < ret.length; ++i) {
    ret[i] = arr[i].listener || arr[i];
  }
  return ret;
}

function objectCreatePolyfill(proto) {
  var F = function() {};
  F.prototype = proto;
  return new F;
}
function objectKeysPolyfill(obj) {
  var keys = [];
  for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
    keys.push(k);
  }
  return k;
}
function functionBindPolyfill(context) {
  var fn = this;
  return function () {
    return fn.apply(context, arguments);
  };
}

},{}],94:[function(_dereq_,module,exports){
/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <https://feross.org>
 * @license  MIT
 */
/* eslint-disable no-proto */

'use strict'

var base64 = _dereq_('base64-js')
var ieee754 = _dereq_('ieee754')

exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50

var K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH

/**
 * If `Buffer.TYPED_ARRAY_SUPPORT`:
 *   === true    Use Uint8Array implementation (fastest)
 *   === false   Print warning and recommend using `buffer` v4.x which has an Object
 *               implementation (most compatible, even IE6)
 *
 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
 * Opera 11.6+, iOS 4.2+.
 *
 * We report that the browser does not support typed arrays if the are not subclassable
 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
 * for __proto__ and has a buggy typed array implementation.
 */
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()

if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
    typeof console.error === 'function') {
  console.error(
    'This browser lacks typed array (Uint8Array) support which is required by ' +
    '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  )
}

function typedArraySupport () {
  // Can typed array instances can be augmented?
  try {
    var arr = new Uint8Array(1)
    arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
    return arr.foo() === 42
  } catch (e) {
    return false
  }
}

Object.defineProperty(Buffer.prototype, 'parent', {
  enumerable: true,
  get: function () {
    if (!Buffer.isBuffer(this)) return undefined
    return this.buffer
  }
})

Object.defineProperty(Buffer.prototype, 'offset', {
  enumerable: true,
  get: function () {
    if (!Buffer.isBuffer(this)) return undefined
    return this.byteOffset
  }
})

function createBuffer (length) {
  if (length > K_MAX_LENGTH) {
    throw new RangeError('The value "' + length + '" is invalid for option "size"')
  }
  // Return an augmented `Uint8Array` instance
  var buf = new Uint8Array(length)
  buf.__proto__ = Buffer.prototype
  return buf
}

/**
 * The Buffer constructor returns instances of `Uint8Array` that have their
 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
 * returns a single octet.
 *
 * The `Uint8Array` prototype remains unmodified.
 */

function Buffer (arg, encodingOrOffset, length) {
  // Common case.
  if (typeof arg === 'number') {
    if (typeof encodingOrOffset === 'string') {
      throw new TypeError(
        'The "string" argument must be of type string. Received type number'
      )
    }
    return allocUnsafe(arg)
  }
  return from(arg, encodingOrOffset, length)
}

// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (typeof Symbol !== 'undefined' && Symbol.species != null &&
    Buffer[Symbol.species] === Buffer) {
  Object.defineProperty(Buffer, Symbol.species, {
    value: null,
    configurable: true,
    enumerable: false,
    writable: false
  })
}

Buffer.poolSize = 8192 // not used by this implementation

function from (value, encodingOrOffset, length) {
  if (typeof value === 'string') {
    return fromString(value, encodingOrOffset)
  }

  if (ArrayBuffer.isView(value)) {
    return fromArrayLike(value)
  }

  if (value == null) {
    throw TypeError(
      'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
      'or Array-like Object. Received type ' + (typeof value)
    )
  }

  if (isInstance(value, ArrayBuffer) ||
      (value && isInstance(value.buffer, ArrayBuffer))) {
    return fromArrayBuffer(value, encodingOrOffset, length)
  }

  if (typeof value === 'number') {
    throw new TypeError(
      'The "value" argument must not be of type number. Received type number'
    )
  }

  var valueOf = value.valueOf && value.valueOf()
  if (valueOf != null && valueOf !== value) {
    return Buffer.from(valueOf, encodingOrOffset, length)
  }

  var b = fromObject(value)
  if (b) return b

  if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
      typeof value[Symbol.toPrimitive] === 'function') {
    return Buffer.from(
      value[Symbol.toPrimitive]('string'), encodingOrOffset, length
    )
  }

  throw new TypeError(
    'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
    'or Array-like Object. Received type ' + (typeof value)
  )
}

/**
 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
 * if value is a number.
 * Buffer.from(str[, encoding])
 * Buffer.from(array)
 * Buffer.from(buffer)
 * Buffer.from(arrayBuffer[, byteOffset[, length]])
 **/
Buffer.from = function (value, encodingOrOffset, length) {
  return from(value, encodingOrOffset, length)
}

// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array

function assertSize (size) {
  if (typeof size !== 'number') {
    throw new TypeError('"size" argument must be of type number')
  } else if (size < 0) {
    throw new RangeError('The value "' + size + '" is invalid for option "size"')
  }
}

function alloc (size, fill, encoding) {
  assertSize(size)
  if (size <= 0) {
    return createBuffer(size)
  }
  if (fill !== undefined) {
    // Only pay attention to encoding if it's a string. This
    // prevents accidentally sending in a number that would
    // be interpretted as a start offset.
    return typeof encoding === 'string'
      ? createBuffer(size).fill(fill, encoding)
      : createBuffer(size).fill(fill)
  }
  return createBuffer(size)
}

/**
 * Creates a new filled Buffer instance.
 * alloc(size[, fill[, encoding]])
 **/
Buffer.alloc = function (size, fill, encoding) {
  return alloc(size, fill, encoding)
}

function allocUnsafe (size) {
  assertSize(size)
  return createBuffer(size < 0 ? 0 : checked(size) | 0)
}

/**
 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
 * */
Buffer.allocUnsafe = function (size) {
  return allocUnsafe(size)
}
/**
 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
 */
Buffer.allocUnsafeSlow = function (size) {
  return allocUnsafe(size)
}

function fromString (string, encoding) {
  if (typeof encoding !== 'string' || encoding === '') {
    encoding = 'utf8'
  }

  if (!Buffer.isEncoding(encoding)) {
    throw new TypeError('Unknown encoding: ' + encoding)
  }

  var length = byteLength(string, encoding) | 0
  var buf = createBuffer(length)

  var actual = buf.write(string, encoding)

  if (actual !== length) {
    // Writing a hex string, for example, that contains invalid characters will
    // cause everything after the first invalid character to be ignored. (e.g.
    // 'abxxcd' will be treated as 'ab')
    buf = buf.slice(0, actual)
  }

  return buf
}

function fromArrayLike (array) {
  var length = array.length < 0 ? 0 : checked(array.length) | 0
  var buf = createBuffer(length)
  for (var i = 0; i < length; i += 1) {
    buf[i] = array[i] & 255
  }
  return buf
}

function fromArrayBuffer (array, byteOffset, length) {
  if (byteOffset < 0 || array.byteLength < byteOffset) {
    throw new RangeError('"offset" is outside of buffer bounds')
  }

  if (array.byteLength < byteOffset + (length || 0)) {
    throw new RangeError('"length" is outside of buffer bounds')
  }

  var buf
  if (byteOffset === undefined && length === undefined) {
    buf = new Uint8Array(array)
  } else if (length === undefined) {
    buf = new Uint8Array(array, byteOffset)
  } else {
    buf = new Uint8Array(array, byteOffset, length)
  }

  // Return an augmented `Uint8Array` instance
  buf.__proto__ = Buffer.prototype
  return buf
}

function fromObject (obj) {
  if (Buffer.isBuffer(obj)) {
    var len = checked(obj.length) | 0
    var buf = createBuffer(len)

    if (buf.length === 0) {
      return buf
    }

    obj.copy(buf, 0, 0, len)
    return buf
  }

  if (obj.length !== undefined) {
    if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
      return createBuffer(0)
    }
    return fromArrayLike(obj)
  }

  if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
    return fromArrayLike(obj.data)
  }
}

function checked (length) {
  // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  // length is NaN (which is otherwise coerced to zero.)
  if (length >= K_MAX_LENGTH) {
    throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
                         'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  }
  return length | 0
}

function SlowBuffer (length) {
  if (+length != length) { // eslint-disable-line eqeqeq
    length = 0
  }
  return Buffer.alloc(+length)
}

Buffer.isBuffer = function isBuffer (b) {
  return b != null && b._isBuffer === true &&
    b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
}

Buffer.compare = function compare (a, b) {
  if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
  if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
  if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
    throw new TypeError(
      'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
    )
  }

  if (a === b) return 0

  var x = a.length
  var y = b.length

  for (var i = 0, len = Math.min(x, y); i < len; ++i) {
    if (a[i] !== b[i]) {
      x = a[i]
      y = b[i]
      break
    }
  }

  if (x < y) return -1
  if (y < x) return 1
  return 0
}

Buffer.isEncoding = function isEncoding (encoding) {
  switch (String(encoding).toLowerCase()) {
    case 'hex':
    case 'utf8':
    case 'utf-8':
    case 'ascii':
    case 'latin1':
    case 'binary':
    case 'base64':
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return true
    default:
      return false
  }
}

Buffer.concat = function concat (list, length) {
  if (!Array.isArray(list)) {
    throw new TypeError('"list" argument must be an Array of Buffers')
  }

  if (list.length === 0) {
    return Buffer.alloc(0)
  }

  var i
  if (length === undefined) {
    length = 0
    for (i = 0; i < list.length; ++i) {
      length += list[i].length
    }
  }

  var buffer = Buffer.allocUnsafe(length)
  var pos = 0
  for (i = 0; i < list.length; ++i) {
    var buf = list[i]
    if (isInstance(buf, Uint8Array)) {
      buf = Buffer.from(buf)
    }
    if (!Buffer.isBuffer(buf)) {
      throw new TypeError('"list" argument must be an Array of Buffers')
    }
    buf.copy(buffer, pos)
    pos += buf.length
  }
  return buffer
}

function byteLength (string, encoding) {
  if (Buffer.isBuffer(string)) {
    return string.length
  }
  if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
    return string.byteLength
  }
  if (typeof string !== 'string') {
    throw new TypeError(
      'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
      'Received type ' + typeof string
    )
  }

  var len = string.length
  var mustMatch = (arguments.length > 2 && arguments[2] === true)
  if (!mustMatch && len === 0) return 0

  // Use a for loop to avoid recursion
  var loweredCase = false
  for (;;) {
    switch (encoding) {
      case 'ascii':
      case 'latin1':
      case 'binary':
        return len
      case 'utf8':
      case 'utf-8':
        return utf8ToBytes(string).length
      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return len * 2
      case 'hex':
        return len >>> 1
      case 'base64':
        return base64ToBytes(string).length
      default:
        if (loweredCase) {
          return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
        }
        encoding = ('' + encoding).toLowerCase()
        loweredCase = true
    }
  }
}
Buffer.byteLength = byteLength

function slowToString (encoding, start, end) {
  var loweredCase = false

  // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  // property of a typed array.

  // This behaves neither like String nor Uint8Array in that we set start/end
  // to their upper/lower bounds if the value passed is out of range.
  // undefined is handled specially as per ECMA-262 6th Edition,
  // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  if (start === undefined || start < 0) {
    start = 0
  }
  // Return early if start > this.length. Done here to prevent potential uint32
  // coercion fail below.
  if (start > this.length) {
    return ''
  }

  if (end === undefined || end > this.length) {
    end = this.length
  }

  if (end <= 0) {
    return ''
  }

  // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  end >>>= 0
  start >>>= 0

  if (end <= start) {
    return ''
  }

  if (!encoding) encoding = 'utf8'

  while (true) {
    switch (encoding) {
      case 'hex':
        return hexSlice(this, start, end)

      case 'utf8':
      case 'utf-8':
        return utf8Slice(this, start, end)

      case 'ascii':
        return asciiSlice(this, start, end)

      case 'latin1':
      case 'binary':
        return latin1Slice(this, start, end)

      case 'base64':
        return base64Slice(this, start, end)

      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return utf16leSlice(this, start, end)

      default:
        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
        encoding = (encoding + '').toLowerCase()
        loweredCase = true
    }
  }
}

// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true

function swap (b, n, m) {
  var i = b[n]
  b[n] = b[m]
  b[m] = i
}

Buffer.prototype.swap16 = function swap16 () {
  var len = this.length
  if (len % 2 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 16-bits')
  }
  for (var i = 0; i < len; i += 2) {
    swap(this, i, i + 1)
  }
  return this
}

Buffer.prototype.swap32 = function swap32 () {
  var len = this.length
  if (len % 4 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 32-bits')
  }
  for (var i = 0; i < len; i += 4) {
    swap(this, i, i + 3)
    swap(this, i + 1, i + 2)
  }
  return this
}

Buffer.prototype.swap64 = function swap64 () {
  var len = this.length
  if (len % 8 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 64-bits')
  }
  for (var i = 0; i < len; i += 8) {
    swap(this, i, i + 7)
    swap(this, i + 1, i + 6)
    swap(this, i + 2, i + 5)
    swap(this, i + 3, i + 4)
  }
  return this
}

Buffer.prototype.toString = function toString () {
  var length = this.length
  if (length === 0) return ''
  if (arguments.length === 0) return utf8Slice(this, 0, length)
  return slowToString.apply(this, arguments)
}

Buffer.prototype.toLocaleString = Buffer.prototype.toString

Buffer.prototype.equals = function equals (b) {
  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  if (this === b) return true
  return Buffer.compare(this, b) === 0
}

Buffer.prototype.inspect = function inspect () {
  var str = ''
  var max = exports.INSPECT_MAX_BYTES
  str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
  if (this.length > max) str += ' ... '
  return '<Buffer ' + str + '>'
}

Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  if (isInstance(target, Uint8Array)) {
    target = Buffer.from(target, target.offset, target.byteLength)
  }
  if (!Buffer.isBuffer(target)) {
    throw new TypeError(
      'The "target" argument must be one of type Buffer or Uint8Array. ' +
      'Received type ' + (typeof target)
    )
  }

  if (start === undefined) {
    start = 0
  }
  if (end === undefined) {
    end = target ? target.length : 0
  }
  if (thisStart === undefined) {
    thisStart = 0
  }
  if (thisEnd === undefined) {
    thisEnd = this.length
  }

  if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
    throw new RangeError('out of range index')
  }

  if (thisStart >= thisEnd && start >= end) {
    return 0
  }
  if (thisStart >= thisEnd) {
    return -1
  }
  if (start >= end) {
    return 1
  }

  start >>>= 0
  end >>>= 0
  thisStart >>>= 0
  thisEnd >>>= 0

  if (this === target) return 0

  var x = thisEnd - thisStart
  var y = end - start
  var len = Math.min(x, y)

  var thisCopy = this.slice(thisStart, thisEnd)
  var targetCopy = target.slice(start, end)

  for (var i = 0; i < len; ++i) {
    if (thisCopy[i] !== targetCopy[i]) {
      x = thisCopy[i]
      y = targetCopy[i]
      break
    }
  }

  if (x < y) return -1
  if (y < x) return 1
  return 0
}

// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  // Empty buffer means no match
  if (buffer.length === 0) return -1

  // Normalize byteOffset
  if (typeof byteOffset === 'string') {
    encoding = byteOffset
    byteOffset = 0
  } else if (byteOffset > 0x7fffffff) {
    byteOffset = 0x7fffffff
  } else if (byteOffset < -0x80000000) {
    byteOffset = -0x80000000
  }
  byteOffset = +byteOffset // Coerce to Number.
  if (numberIsNaN(byteOffset)) {
    // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
    byteOffset = dir ? 0 : (buffer.length - 1)
  }

  // Normalize byteOffset: negative offsets start from the end of the buffer
  if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  if (byteOffset >= buffer.length) {
    if (dir) return -1
    else byteOffset = buffer.length - 1
  } else if (byteOffset < 0) {
    if (dir) byteOffset = 0
    else return -1
  }

  // Normalize val
  if (typeof val === 'string') {
    val = Buffer.from(val, encoding)
  }

  // Finally, search either indexOf (if dir is true) or lastIndexOf
  if (Buffer.isBuffer(val)) {
    // Special case: looking for empty string/buffer always fails
    if (val.length === 0) {
      return -1
    }
    return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  } else if (typeof val === 'number') {
    val = val & 0xFF // Search for a byte value [0-255]
    if (typeof Uint8Array.prototype.indexOf === 'function') {
      if (dir) {
        return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
      } else {
        return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
      }
    }
    return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  }

  throw new TypeError('val must be string, number or Buffer')
}

function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  var indexSize = 1
  var arrLength = arr.length
  var valLength = val.length

  if (encoding !== undefined) {
    encoding = String(encoding).toLowerCase()
    if (encoding === 'ucs2' || encoding === 'ucs-2' ||
        encoding === 'utf16le' || encoding === 'utf-16le') {
      if (arr.length < 2 || val.length < 2) {
        return -1
      }
      indexSize = 2
      arrLength /= 2
      valLength /= 2
      byteOffset /= 2
    }
  }

  function read (buf, i) {
    if (indexSize === 1) {
      return buf[i]
    } else {
      return buf.readUInt16BE(i * indexSize)
    }
  }

  var i
  if (dir) {
    var foundIndex = -1
    for (i = byteOffset; i < arrLength; i++) {
      if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
        if (foundIndex === -1) foundIndex = i
        if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
      } else {
        if (foundIndex !== -1) i -= i - foundIndex
        foundIndex = -1
      }
    }
  } else {
    if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
    for (i = byteOffset; i >= 0; i--) {
      var found = true
      for (var j = 0; j < valLength; j++) {
        if (read(arr, i + j) !== read(val, j)) {
          found = false
          break
        }
      }
      if (found) return i
    }
  }

  return -1
}

Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  return this.indexOf(val, byteOffset, encoding) !== -1
}

Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}

Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}

function hexWrite (buf, string, offset, length) {
  offset = Number(offset) || 0
  var remaining = buf.length - offset
  if (!length) {
    length = remaining
  } else {
    length = Number(length)
    if (length > remaining) {
      length = remaining
    }
  }

  var strLen = string.length

  if (length > strLen / 2) {
    length = strLen / 2
  }
  for (var i = 0; i < length; ++i) {
    var parsed = parseInt(string.substr(i * 2, 2), 16)
    if (numberIsNaN(parsed)) return i
    buf[offset + i] = parsed
  }
  return i
}

function utf8Write (buf, string, offset, length) {
  return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}

function asciiWrite (buf, string, offset, length) {
  return blitBuffer(asciiToBytes(string), buf, offset, length)
}

function latin1Write (buf, string, offset, length) {
  return asciiWrite(buf, string, offset, length)
}

function base64Write (buf, string, offset, length) {
  return blitBuffer(base64ToBytes(string), buf, offset, length)
}

function ucs2Write (buf, string, offset, length) {
  return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}

Buffer.prototype.write = function write (string, offset, length, encoding) {
  // Buffer#write(string)
  if (offset === undefined) {
    encoding = 'utf8'
    length = this.length
    offset = 0
  // Buffer#write(string, encoding)
  } else if (length === undefined && typeof offset === 'string') {
    encoding = offset
    length = this.length
    offset = 0
  // Buffer#write(string, offset[, length][, encoding])
  } else if (isFinite(offset)) {
    offset = offset >>> 0
    if (isFinite(length)) {
      length = length >>> 0
      if (encoding === undefined) encoding = 'utf8'
    } else {
      encoding = length
      length = undefined
    }
  } else {
    throw new Error(
      'Buffer.write(string, encoding, offset[, length]) is no longer supported'
    )
  }

  var remaining = this.length - offset
  if (length === undefined || length > remaining) length = remaining

  if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
    throw new RangeError('Attempt to write outside buffer bounds')
  }

  if (!encoding) encoding = 'utf8'

  var loweredCase = false
  for (;;) {
    switch (encoding) {
      case 'hex':
        return hexWrite(this, string, offset, length)

      case 'utf8':
      case 'utf-8':
        return utf8Write(this, string, offset, length)

      case 'ascii':
        return asciiWrite(this, string, offset, length)

      case 'latin1':
      case 'binary':
        return latin1Write(this, string, offset, length)

      case 'base64':
        // Warning: maxLength not taken into account in base64Write
        return base64Write(this, string, offset, length)

      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return ucs2Write(this, string, offset, length)

      default:
        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
        encoding = ('' + encoding).toLowerCase()
        loweredCase = true
    }
  }
}

Buffer.prototype.toJSON = function toJSON () {
  return {
    type: 'Buffer',
    data: Array.prototype.slice.call(this._arr || this, 0)
  }
}

function base64Slice (buf, start, end) {
  if (start === 0 && end === buf.length) {
    return base64.fromByteArray(buf)
  } else {
    return base64.fromByteArray(buf.slice(start, end))
  }
}

function utf8Slice (buf, start, end) {
  end = Math.min(buf.length, end)
  var res = []

  var i = start
  while (i < end) {
    var firstByte = buf[i]
    var codePoint = null
    var bytesPerSequence = (firstByte > 0xEF) ? 4
      : (firstByte > 0xDF) ? 3
        : (firstByte > 0xBF) ? 2
          : 1

    if (i + bytesPerSequence <= end) {
      var secondByte, thirdByte, fourthByte, tempCodePoint

      switch (bytesPerSequence) {
        case 1:
          if (firstByte < 0x80) {
            codePoint = firstByte
          }
          break
        case 2:
          secondByte = buf[i + 1]
          if ((secondByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
            if (tempCodePoint > 0x7F) {
              codePoint = tempCodePoint
            }
          }
          break
        case 3:
          secondByte = buf[i + 1]
          thirdByte = buf[i + 2]
          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
            if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
              codePoint = tempCodePoint
            }
          }
          break
        case 4:
          secondByte = buf[i + 1]
          thirdByte = buf[i + 2]
          fourthByte = buf[i + 3]
          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
            if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
              codePoint = tempCodePoint
            }
          }
      }
    }

    if (codePoint === null) {
      // we did not generate a valid codePoint so insert a
      // replacement char (U+FFFD) and advance only 1 byte
      codePoint = 0xFFFD
      bytesPerSequence = 1
    } else if (codePoint > 0xFFFF) {
      // encode to utf16 (surrogate pair dance)
      codePoint -= 0x10000
      res.push(codePoint >>> 10 & 0x3FF | 0xD800)
      codePoint = 0xDC00 | codePoint & 0x3FF
    }

    res.push(codePoint)
    i += bytesPerSequence
  }

  return decodeCodePointsArray(res)
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000

function decodeCodePointsArray (codePoints) {
  var len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }

  // Decode in chunks to avoid "call stack size exceeded".
  var res = ''
  var i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}

function asciiSlice (buf, start, end) {
  var ret = ''
  end = Math.min(buf.length, end)

  for (var i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i] & 0x7F)
  }
  return ret
}

function latin1Slice (buf, start, end) {
  var ret = ''
  end = Math.min(buf.length, end)

  for (var i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i])
  }
  return ret
}

function hexSlice (buf, start, end) {
  var len = buf.length

  if (!start || start < 0) start = 0
  if (!end || end < 0 || end > len) end = len

  var out = ''
  for (var i = start; i < end; ++i) {
    out += toHex(buf[i])
  }
  return out
}

function utf16leSlice (buf, start, end) {
  var bytes = buf.slice(start, end)
  var res = ''
  for (var i = 0; i < bytes.length; i += 2) {
    res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  }
  return res
}

Buffer.prototype.slice = function slice (start, end) {
  var len = this.length
  start = ~~start
  end = end === undefined ? len : ~~end

  if (start < 0) {
    start += len
    if (start < 0) start = 0
  } else if (start > len) {
    start = len
  }

  if (end < 0) {
    end += len
    if (end < 0) end = 0
  } else if (end > len) {
    end = len
  }

  if (end < start) end = start

  var newBuf = this.subarray(start, end)
  // Return an augmented `Uint8Array` instance
  newBuf.__proto__ = Buffer.prototype
  return newBuf
}

/*
 * Need to make sure that buffer isn't trying to write out of bounds.
 */
function checkOffset (offset, ext, length) {
  if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}

Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  var val = this[offset]
  var mul = 1
  var i = 0
  while (++i < byteLength && (mul *= 0x100)) {
    val += this[offset + i] * mul
  }

  return val
}

Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) {
    checkOffset(offset, byteLength, this.length)
  }

  var val = this[offset + --byteLength]
  var mul = 1
  while (byteLength > 0 && (mul *= 0x100)) {
    val += this[offset + --byteLength] * mul
  }

  return val
}

Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 1, this.length)
  return this[offset]
}

Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  return this[offset] | (this[offset + 1] << 8)
}

Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  return (this[offset] << 8) | this[offset + 1]
}

Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return ((this[offset]) |
      (this[offset + 1] << 8) |
      (this[offset + 2] << 16)) +
      (this[offset + 3] * 0x1000000)
}

Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset] * 0x1000000) +
    ((this[offset + 1] << 16) |
    (this[offset + 2] << 8) |
    this[offset + 3])
}

Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  var val = this[offset]
  var mul = 1
  var i = 0
  while (++i < byteLength && (mul *= 0x100)) {
    val += this[offset + i] * mul
  }
  mul *= 0x80

  if (val >= mul) val -= Math.pow(2, 8 * byteLength)

  return val
}

Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  var i = byteLength
  var mul = 1
  var val = this[offset + --i]
  while (i > 0 && (mul *= 0x100)) {
    val += this[offset + --i] * mul
  }
  mul *= 0x80

  if (val >= mul) val -= Math.pow(2, 8 * byteLength)

  return val
}

Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 1, this.length)
  if (!(this[offset] & 0x80)) return (this[offset])
  return ((0xff - this[offset] + 1) * -1)
}

Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  var val = this[offset] | (this[offset + 1] << 8)
  return (val & 0x8000) ? val | 0xFFFF0000 : val
}

Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  var val = this[offset + 1] | (this[offset] << 8)
  return (val & 0x8000) ? val | 0xFFFF0000 : val
}

Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset]) |
    (this[offset + 1] << 8) |
    (this[offset + 2] << 16) |
    (this[offset + 3] << 24)
}

Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset] << 24) |
    (this[offset + 1] << 16) |
    (this[offset + 2] << 8) |
    (this[offset + 3])
}

Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)
  return ieee754.read(this, offset, true, 23, 4)
}

Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)
  return ieee754.read(this, offset, false, 23, 4)
}

Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 8, this.length)
  return ieee754.read(this, offset, true, 52, 8)
}

Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 8, this.length)
  return ieee754.read(this, offset, false, 52, 8)
}

function checkInt (buf, value, offset, ext, max, min) {
  if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  if (offset + ext > buf.length) throw new RangeError('Index out of range')
}

Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) {
    var maxBytes = Math.pow(2, 8 * byteLength) - 1
    checkInt(this, value, offset, byteLength, maxBytes, 0)
  }

  var mul = 1
  var i = 0
  this[offset] = value & 0xFF
  while (++i < byteLength && (mul *= 0x100)) {
    this[offset + i] = (value / mul) & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) {
    var maxBytes = Math.pow(2, 8 * byteLength) - 1
    checkInt(this, value, offset, byteLength, maxBytes, 0)
  }

  var i = byteLength - 1
  var mul = 1
  this[offset + i] = value & 0xFF
  while (--i >= 0 && (mul *= 0x100)) {
    this[offset + i] = (value / mul) & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  this[offset] = (value & 0xff)
  return offset + 1
}

Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  this[offset] = (value & 0xff)
  this[offset + 1] = (value >>> 8)
  return offset + 2
}

Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  this[offset] = (value >>> 8)
  this[offset + 1] = (value & 0xff)
  return offset + 2
}

Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  this[offset + 3] = (value >>> 24)
  this[offset + 2] = (value >>> 16)
  this[offset + 1] = (value >>> 8)
  this[offset] = (value & 0xff)
  return offset + 4
}

Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  this[offset] = (value >>> 24)
  this[offset + 1] = (value >>> 16)
  this[offset + 2] = (value >>> 8)
  this[offset + 3] = (value & 0xff)
  return offset + 4
}

Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    var limit = Math.pow(2, (8 * byteLength) - 1)

    checkInt(this, value, offset, byteLength, limit - 1, -limit)
  }

  var i = 0
  var mul = 1
  var sub = 0
  this[offset] = value & 0xFF
  while (++i < byteLength && (mul *= 0x100)) {
    if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
      sub = 1
    }
    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    var limit = Math.pow(2, (8 * byteLength) - 1)

    checkInt(this, value, offset, byteLength, limit - 1, -limit)
  }

  var i = byteLength - 1
  var mul = 1
  var sub = 0
  this[offset + i] = value & 0xFF
  while (--i >= 0 && (mul *= 0x100)) {
    if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
      sub = 1
    }
    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  if (value < 0) value = 0xff + value + 1
  this[offset] = (value & 0xff)
  return offset + 1
}

Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  this[offset] = (value & 0xff)
  this[offset + 1] = (value >>> 8)
  return offset + 2
}

Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  this[offset] = (value >>> 8)
  this[offset + 1] = (value & 0xff)
  return offset + 2
}

Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  this[offset] = (value & 0xff)
  this[offset + 1] = (value >>> 8)
  this[offset + 2] = (value >>> 16)
  this[offset + 3] = (value >>> 24)
  return offset + 4
}

Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  if (value < 0) value = 0xffffffff + value + 1
  this[offset] = (value >>> 24)
  this[offset + 1] = (value >>> 16)
  this[offset + 2] = (value >>> 8)
  this[offset + 3] = (value & 0xff)
  return offset + 4
}

function checkIEEE754 (buf, value, offset, ext, max, min) {
  if (offset + ext > buf.length) throw new RangeError('Index out of range')
  if (offset < 0) throw new RangeError('Index out of range')
}

function writeFloat (buf, value, offset, littleEndian, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  }
  ieee754.write(buf, value, offset, littleEndian, 23, 4)
  return offset + 4
}

Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  return writeFloat(this, value, offset, true, noAssert)
}

Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  return writeFloat(this, value, offset, false, noAssert)
}

function writeDouble (buf, value, offset, littleEndian, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  }
  ieee754.write(buf, value, offset, littleEndian, 52, 8)
  return offset + 8
}

Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  return writeDouble(this, value, offset, true, noAssert)
}

Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  return writeDouble(this, value, offset, false, noAssert)
}

// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  if (!start) start = 0
  if (!end && end !== 0) end = this.length
  if (targetStart >= target.length) targetStart = target.length
  if (!targetStart) targetStart = 0
  if (end > 0 && end < start) end = start

  // Copy 0 bytes; we're done
  if (end === start) return 0
  if (target.length === 0 || this.length === 0) return 0

  // Fatal error conditions
  if (targetStart < 0) {
    throw new RangeError('targetStart out of bounds')
  }
  if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  if (end < 0) throw new RangeError('sourceEnd out of bounds')

  // Are we oob?
  if (end > this.length) end = this.length
  if (target.length - targetStart < end - start) {
    end = target.length - targetStart + start
  }

  var len = end - start

  if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
    // Use built-in when available, missing from IE11
    this.copyWithin(targetStart, start, end)
  } else if (this === target && start < targetStart && targetStart < end) {
    // descending copy from end
    for (var i = len - 1; i >= 0; --i) {
      target[i + targetStart] = this[i + start]
    }
  } else {
    Uint8Array.prototype.set.call(
      target,
      this.subarray(start, end),
      targetStart
    )
  }

  return len
}

// Usage:
//    buffer.fill(number[, offset[, end]])
//    buffer.fill(buffer[, offset[, end]])
//    buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
  // Handle string cases:
  if (typeof val === 'string') {
    if (typeof start === 'string') {
      encoding = start
      start = 0
      end = this.length
    } else if (typeof end === 'string') {
      encoding = end
      end = this.length
    }
    if (encoding !== undefined && typeof encoding !== 'string') {
      throw new TypeError('encoding must be a string')
    }
    if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
      throw new TypeError('Unknown encoding: ' + encoding)
    }
    if (val.length === 1) {
      var code = val.charCodeAt(0)
      if ((encoding === 'utf8' && code < 128) ||
          encoding === 'latin1') {
        // Fast path: If `val` fits into a single byte, use that numeric value.
        val = code
      }
    }
  } else if (typeof val === 'number') {
    val = val & 255
  }

  // Invalid ranges are not set to a default, so can range check early.
  if (start < 0 || this.length < start || this.length < end) {
    throw new RangeError('Out of range index')
  }

  if (end <= start) {
    return this
  }

  start = start >>> 0
  end = end === undefined ? this.length : end >>> 0

  if (!val) val = 0

  var i
  if (typeof val === 'number') {
    for (i = start; i < end; ++i) {
      this[i] = val
    }
  } else {
    var bytes = Buffer.isBuffer(val)
      ? val
      : Buffer.from(val, encoding)
    var len = bytes.length
    if (len === 0) {
      throw new TypeError('The value "' + val +
        '" is invalid for argument "value"')
    }
    for (i = 0; i < end - start; ++i) {
      this[i + start] = bytes[i % len]
    }
  }

  return this
}

// HELPER FUNCTIONS
// ================

var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g

function base64clean (str) {
  // Node takes equal signs as end of the Base64 encoding
  str = str.split('=')[0]
  // Node strips out invalid characters like \n and \t from the string, base64-js does not
  str = str.trim().replace(INVALID_BASE64_RE, '')
  // Node converts strings with length < 2 to ''
  if (str.length < 2) return ''
  // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  while (str.length % 4 !== 0) {
    str = str + '='
  }
  return str
}

function toHex (n) {
  if (n < 16) return '0' + n.toString(16)
  return n.toString(16)
}

function utf8ToBytes (string, units) {
  units = units || Infinity
  var codePoint
  var length = string.length
  var leadSurrogate = null
  var bytes = []

  for (var i = 0; i < length; ++i) {
    codePoint = string.charCodeAt(i)

    // is surrogate component
    if (codePoint > 0xD7FF && codePoint < 0xE000) {
      // last char was a lead
      if (!leadSurrogate) {
        // no lead yet
        if (codePoint > 0xDBFF) {
          // unexpected trail
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
          continue
        } else if (i + 1 === length) {
          // unpaired lead
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
          continue
        }

        // valid lead
        leadSurrogate = codePoint

        continue
      }

      // 2 leads in a row
      if (codePoint < 0xDC00) {
        if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
        leadSurrogate = codePoint
        continue
      }

      // valid surrogate pair
      codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
    } else if (leadSurrogate) {
      // valid bmp char, but last char was a lead
      if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
    }

    leadSurrogate = null

    // encode utf8
    if (codePoint < 0x80) {
      if ((units -= 1) < 0) break
      bytes.push(codePoint)
    } else if (codePoint < 0x800) {
      if ((units -= 2) < 0) break
      bytes.push(
        codePoint >> 0x6 | 0xC0,
        codePoint & 0x3F | 0x80
      )
    } else if (codePoint < 0x10000) {
      if ((units -= 3) < 0) break
      bytes.push(
        codePoint >> 0xC | 0xE0,
        codePoint >> 0x6 & 0x3F | 0x80,
        codePoint & 0x3F | 0x80
      )
    } else if (codePoint < 0x110000) {
      if ((units -= 4) < 0) break
      bytes.push(
        codePoint >> 0x12 | 0xF0,
        codePoint >> 0xC & 0x3F | 0x80,
        codePoint >> 0x6 & 0x3F | 0x80,
        codePoint & 0x3F | 0x80
      )
    } else {
      throw new Error('Invalid code point')
    }
  }

  return bytes
}

function asciiToBytes (str) {
  var byteArray = []
  for (var i = 0; i < str.length; ++i) {
    // Node's code seems to be doing this and not & 0x7F..
    byteArray.push(str.charCodeAt(i) & 0xFF)
  }
  return byteArray
}

function utf16leToBytes (str, units) {
  var c, hi, lo
  var byteArray = []
  for (var i = 0; i < str.length; ++i) {
    if ((units -= 2) < 0) break

    c = str.charCodeAt(i)
    hi = c >> 8
    lo = c % 256
    byteArray.push(lo)
    byteArray.push(hi)
  }

  return byteArray
}

function base64ToBytes (str) {
  return base64.toByteArray(base64clean(str))
}

function blitBuffer (src, dst, offset, length) {
  for (var i = 0; i < length; ++i) {
    if ((i + offset >= dst.length) || (i >= src.length)) break
    dst[i + offset] = src[i]
  }
  return i
}

// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
// the `instanceof` check but they should be treated as of that type.
// See: https://github.com/feross/buffer/issues/166
function isInstance (obj, type) {
  return obj instanceof type ||
    (obj != null && obj.constructor != null && obj.constructor.name != null &&
      obj.constructor.name === type.name)
}
function numberIsNaN (obj) {
  // For IE11 support
  return obj !== obj // eslint-disable-line no-self-compare
}

},{"base64-js":63,"ieee754":398}],95:[function(_dereq_,module,exports){
'use strict'

var monotoneTriangulate = _dereq_('./lib/monotone')
var makeIndex = _dereq_('./lib/triangulation')
var delaunayFlip = _dereq_('./lib/delaunay')
var filterTriangulation = _dereq_('./lib/filter')

module.exports = cdt2d

function canonicalizeEdge(e) {
  return [Math.min(e[0], e[1]), Math.max(e[0], e[1])]
}

function compareEdge(a, b) {
  return a[0]-b[0] || a[1]-b[1]
}

function canonicalizeEdges(edges) {
  return edges.map(canonicalizeEdge).sort(compareEdge)
}

function getDefault(options, property, dflt) {
  if(property in options) {
    return options[property]
  }
  return dflt
}

function cdt2d(points, edges, options) {

  if(!Array.isArray(edges)) {
    options = edges || {}
    edges = []
  } else {
    options = options || {}
    edges = edges || []
  }

  //Parse out options
  var delaunay = !!getDefault(options, 'delaunay', true)
  var interior = !!getDefault(options, 'interior', true)
  var exterior = !!getDefault(options, 'exterior', true)
  var infinity = !!getDefault(options, 'infinity', false)

  //Handle trivial case
  if((!interior && !exterior) || points.length === 0) {
    return []
  }

  //Construct initial triangulation
  var cells = monotoneTriangulate(points, edges)

  //If delaunay refinement needed, then improve quality by edge flipping
  if(delaunay || interior !== exterior || infinity) {

    //Index all of the cells to support fast neighborhood queries
    var triangulation = makeIndex(points.length, canonicalizeEdges(edges))
    for(var i=0; i<cells.length; ++i) {
      var f = cells[i]
      triangulation.addTriangle(f[0], f[1], f[2])
    }

    //Run edge flipping
    if(delaunay) {
      delaunayFlip(points, triangulation)
    }

    //Filter points
    if(!exterior) {
      return filterTriangulation(triangulation, -1)
    } else if(!interior) {
      return filterTriangulation(triangulation,  1, infinity)
    } else if(infinity) {
      return filterTriangulation(triangulation, 0, infinity)
    } else {
      return triangulation.cells()
    }
    
  } else {
    return cells
  }
}

},{"./lib/delaunay":96,"./lib/filter":97,"./lib/monotone":98,"./lib/triangulation":99}],96:[function(_dereq_,module,exports){
'use strict'

var inCircle = _dereq_('robust-in-sphere')[4]
var bsearch = _dereq_('binary-search-bounds')

module.exports = delaunayRefine

function testFlip(points, triangulation, stack, a, b, x) {
  var y = triangulation.opposite(a, b)

  //Test boundary edge
  if(y < 0) {
    return
  }

  //Swap edge if order flipped
  if(b < a) {
    var tmp = a
    a = b
    b = tmp
    tmp = x
    x = y
    y = tmp
  }

  //Test if edge is constrained
  if(triangulation.isConstraint(a, b)) {
    return
  }

  //Test if edge is delaunay
  if(inCircle(points[a], points[b], points[x], points[y]) < 0) {
    stack.push(a, b)
  }
}

//Assume edges are sorted lexicographically
function delaunayRefine(points, triangulation) {
  var stack = []

  var numPoints = points.length
  var stars = triangulation.stars
  for(var a=0; a<numPoints; ++a) {
    var star = stars[a]
    for(var j=1; j<star.length; j+=2) {
      var b = star[j]

      //If order is not consistent, then skip edge
      if(b < a) {
        continue
      }

      //Check if edge is constrained
      if(triangulation.isConstraint(a, b)) {
        continue
      }

      //Find opposite edge
      var x = star[j-1], y = -1
      for(var k=1; k<star.length; k+=2) {
        if(star[k-1] === b) {
          y = star[k]
          break
        }
      }

      //If this is a boundary edge, don't flip it
      if(y < 0) {
        continue
      }

      //If edge is in circle, flip it
      if(inCircle(points[a], points[b], points[x], points[y]) < 0) {
        stack.push(a, b)
      }
    }
  }

  while(stack.length > 0) {
    var b = stack.pop()
    var a = stack.pop()

    //Find opposite pairs
    var x = -1, y = -1
    var star = stars[a]
    for(var i=1; i<star.length; i+=2) {
      var s = star[i-1]
      var t = star[i]
      if(s === b) {
        y = t
      } else if(t === b) {
        x = s
      }
    }

    //If x/y are both valid then skip edge
    if(x < 0 || y < 0) {
      continue
    }

    //If edge is now delaunay, then don't flip it
    if(inCircle(points[a], points[b], points[x], points[y]) >= 0) {
      continue
    }

    //Flip the edge
    triangulation.flip(a, b)

    //Test flipping neighboring edges
    testFlip(points, triangulation, stack, x, a, y)
    testFlip(points, triangulation, stack, a, y, x)
    testFlip(points, triangulation, stack, y, b, x)
    testFlip(points, triangulation, stack, b, x, y)
  }
}

},{"binary-search-bounds":100,"robust-in-sphere":486}],97:[function(_dereq_,module,exports){
'use strict'

var bsearch = _dereq_('binary-search-bounds')

module.exports = classifyFaces

function FaceIndex(cells, neighbor, constraint, flags, active, next, boundary) {
  this.cells       = cells
  this.neighbor    = neighbor
  this.flags       = flags
  this.constraint  = constraint
  this.active      = active
  this.next        = next
  this.boundary    = boundary
}

var proto = FaceIndex.prototype

function compareCell(a, b) {
  return a[0] - b[0] ||
         a[1] - b[1] ||
         a[2] - b[2]
}

proto.locate = (function() {
  var key = [0,0,0]
  return function(a, b, c) {
    var x = a, y = b, z = c
    if(b < c) {
      if(b < a) {
        x = b
        y = c
        z = a
      }
    } else if(c < a) {
      x = c
      y = a
      z = b
    }
    if(x < 0) {
      return -1
    }
    key[0] = x
    key[1] = y
    key[2] = z
    return bsearch.eq(this.cells, key, compareCell)
  }
})()

function indexCells(triangulation, infinity) {
  //First get cells and canonicalize
  var cells = triangulation.cells()
  var nc = cells.length
  for(var i=0; i<nc; ++i) {
    var c = cells[i]
    var x = c[0], y = c[1], z = c[2]
    if(y < z) {
      if(y < x) {
        c[0] = y
        c[1] = z
        c[2] = x
      }
    } else if(z < x) {
      c[0] = z
      c[1] = x
      c[2] = y
    }
  }
  cells.sort(compareCell)

  //Initialize flag array
  var flags = new Array(nc)
  for(var i=0; i<flags.length; ++i) {
    flags[i] = 0
  }

  //Build neighbor index, initialize queues
  var active = []
  var next   = []
  var neighbor = new Array(3*nc)
  var constraint = new Array(3*nc)
  var boundary = null
  if(infinity) {
    boundary = []
  }
  var index = new FaceIndex(
    cells,
    neighbor,
    constraint,
    flags,
    active,
    next,
    boundary)
  for(var i=0; i<nc; ++i) {
    var c = cells[i]
    for(var j=0; j<3; ++j) {
      var x = c[j], y = c[(j+1)%3]
      var a = neighbor[3*i+j] = index.locate(y, x, triangulation.opposite(y, x))
      var b = constraint[3*i+j] = triangulation.isConstraint(x, y)
      if(a < 0) {
        if(b) {
          next.push(i)
        } else {
          active.push(i)
          flags[i] = 1
        }
        if(infinity) {
          boundary.push([y, x, -1])
        }
      }
    }
  }
  return index
}

function filterCells(cells, flags, target) {
  var ptr = 0
  for(var i=0; i<cells.length; ++i) {
    if(flags[i] === target) {
      cells[ptr++] = cells[i]
    }
  }
  cells.length = ptr
  return cells
}

function classifyFaces(triangulation, target, infinity) {
  var index = indexCells(triangulation, infinity)

  if(target === 0) {
    if(infinity) {
      return index.cells.concat(index.boundary)
    } else {
      return index.cells
    }
  }

  var side = 1
  var active = index.active
  var next = index.next
  var flags = index.flags
  var cells = index.cells
  var constraint = index.constraint
  var neighbor = index.neighbor

  while(active.length > 0 || next.length > 0) {
    while(active.length > 0) {
      var t = active.pop()
      if(flags[t] === -side) {
        continue
      }
      flags[t] = side
      var c = cells[t]
      for(var j=0; j<3; ++j) {
        var f = neighbor[3*t+j]
        if(f >= 0 && flags[f] === 0) {
          if(constraint[3*t+j]) {
            next.push(f)
          } else {
            active.push(f)
            flags[f] = side
          }
        }
      }
    }

    //Swap arrays and loop
    var tmp = next
    next = active
    active = tmp
    next.length = 0
    side = -side
  }

  var result = filterCells(cells, flags, target)
  if(infinity) {
    return result.concat(index.boundary)
  }
  return result
}

},{"binary-search-bounds":100}],98:[function(_dereq_,module,exports){
'use strict'

var bsearch = _dereq_('binary-search-bounds')
var orient = _dereq_('robust-orientation')[3]

var EVENT_POINT = 0
var EVENT_END   = 1
var EVENT_START = 2

module.exports = monotoneTriangulate

//A partial convex hull fragment, made of two unimonotone polygons
function PartialHull(a, b, idx, lowerIds, upperIds) {
  this.a = a
  this.b = b
  this.idx = idx
  this.lowerIds = lowerIds
  this.upperIds = upperIds
}

//An event in the sweep line procedure
function Event(a, b, type, idx) {
  this.a    = a
  this.b    = b
  this.type = type
  this.idx  = idx
}

//This is used to compare events for the sweep line procedure
// Points are:
//  1. sorted lexicographically
//  2. sorted by type  (point < end < start)
//  3. segments sorted by winding order
//  4. sorted by index
function compareEvent(a, b) {
  var d =
    (a.a[0] - b.a[0]) ||
    (a.a[1] - b.a[1]) ||
    (a.type - b.type)
  if(d) { return d }
  if(a.type !== EVENT_POINT) {
    d = orient(a.a, a.b, b.b)
    if(d) { return d }
  }
  return a.idx - b.idx
}

function testPoint(hull, p) {
  return orient(hull.a, hull.b, p)
}

function addPoint(cells, hulls, points, p, idx) {
  var lo = bsearch.lt(hulls, p, testPoint)
  var hi = bsearch.gt(hulls, p, testPoint)
  for(var i=lo; i<hi; ++i) {
    var hull = hulls[i]

    //Insert p into lower hull
    var lowerIds = hull.lowerIds
    var m = lowerIds.length
    while(m > 1 && orient(
        points[lowerIds[m-2]],
        points[lowerIds[m-1]],
        p) > 0) {
      cells.push(
        [lowerIds[m-1],
         lowerIds[m-2],
         idx])
      m -= 1
    }
    lowerIds.length = m
    lowerIds.push(idx)

    //Insert p into upper hull
    var upperIds = hull.upperIds
    var m = upperIds.length
    while(m > 1 && orient(
        points[upperIds[m-2]],
        points[upperIds[m-1]],
        p) < 0) {
      cells.push(
        [upperIds[m-2],
         upperIds[m-1],
         idx])
      m -= 1
    }
    upperIds.length = m
    upperIds.push(idx)
  }
}

function findSplit(hull, edge) {
  var d
  if(hull.a[0] < edge.a[0]) {
    d = orient(hull.a, hull.b, edge.a)
  } else {
    d = orient(edge.b, edge.a, hull.a)
  }
  if(d) { return d }
  if(edge.b[0] < hull.b[0]) {
    d = orient(hull.a, hull.b, edge.b)
  } else {
    d = orient(edge.b, edge.a, hull.b)
  }
  return d || hull.idx - edge.idx
}

function splitHulls(hulls, points, event) {
  var splitIdx = bsearch.le(hulls, event, findSplit)
  var hull = hulls[splitIdx]
  var upperIds = hull.upperIds
  var x = upperIds[upperIds.length-1]
  hull.upperIds = [x]
  hulls.splice(splitIdx+1, 0,
    new PartialHull(event.a, event.b, event.idx, [x], upperIds))
}


function mergeHulls(hulls, points, event) {
  //Swap pointers for merge search
  var tmp = event.a
  event.a = event.b
  event.b = tmp
  var mergeIdx = bsearch.eq(hulls, event, findSplit)
  var upper = hulls[mergeIdx]
  var lower = hulls[mergeIdx-1]
  lower.upperIds = upper.upperIds
  hulls.splice(mergeIdx, 1)
}


function monotoneTriangulate(points, edges) {

  var numPoints = points.length
  var numEdges = edges.length

  var events = []

  //Create point events
  for(var i=0; i<numPoints; ++i) {
    events.push(new Event(
      points[i],
      null,
      EVENT_POINT,
      i))
  }

  //Create edge events
  for(var i=0; i<numEdges; ++i) {
    var e = edges[i]
    var a = points[e[0]]
    var b = points[e[1]]
    if(a[0] < b[0]) {
      events.push(
        new Event(a, b, EVENT_START, i),
        new Event(b, a, EVENT_END, i))
    } else if(a[0] > b[0]) {
      events.push(
        new Event(b, a, EVENT_START, i),
        new Event(a, b, EVENT_END, i))
    }
  }

  //Sort events
  events.sort(compareEvent)

  //Initialize hull
  var minX = events[0].a[0] - (1 + Math.abs(events[0].a[0])) * Math.pow(2, -52)
  var hull = [ new PartialHull([minX, 1], [minX, 0], -1, [], [], [], []) ]

  //Process events in order
  var cells = []
  for(var i=0, numEvents=events.length; i<numEvents; ++i) {
    var event = events[i]
    var type = event.type
    if(type === EVENT_POINT) {
      addPoint(cells, hull, points, event.a, event.idx)
    } else if(type === EVENT_START) {
      splitHulls(hull, points, event)
    } else {
      mergeHulls(hull, points, event)
    }
  }

  //Return triangulation
  return cells
}

},{"binary-search-bounds":100,"robust-orientation":488}],99:[function(_dereq_,module,exports){
'use strict'

var bsearch = _dereq_('binary-search-bounds')

module.exports = createTriangulation

function Triangulation(stars, edges) {
  this.stars = stars
  this.edges = edges
}

var proto = Triangulation.prototype

function removePair(list, j, k) {
  for(var i=1, n=list.length; i<n; i+=2) {
    if(list[i-1] === j && list[i] === k) {
      list[i-1] = list[n-2]
      list[i] = list[n-1]
      list.length = n - 2
      return
    }
  }
}

proto.isConstraint = (function() {
  var e = [0,0]
  function compareLex(a, b) {
    return a[0] - b[0] || a[1] - b[1]
  }
  return function(i, j) {
    e[0] = Math.min(i,j)
    e[1] = Math.max(i,j)
    return bsearch.eq(this.edges, e, compareLex) >= 0
  }
})()

proto.removeTriangle = function(i, j, k) {
  var stars = this.stars
  removePair(stars[i], j, k)
  removePair(stars[j], k, i)
  removePair(stars[k], i, j)
}

proto.addTriangle = function(i, j, k) {
  var stars = this.stars
  stars[i].push(j, k)
  stars[j].push(k, i)
  stars[k].push(i, j)
}

proto.opposite = function(j, i) {
  var list = this.stars[i]
  for(var k=1, n=list.length; k<n; k+=2) {
    if(list[k] === j) {
      return list[k-1]
    }
  }
  return -1
}

proto.flip = function(i, j) {
  var a = this.opposite(i, j)
  var b = this.opposite(j, i)
  this.removeTriangle(i, j, a)
  this.removeTriangle(j, i, b)
  this.addTriangle(i, b, a)
  this.addTriangle(j, a, b)
}

proto.edges = function() {
  var stars = this.stars
  var result = []
  for(var i=0, n=stars.length; i<n; ++i) {
    var list = stars[i]
    for(var j=0, m=list.length; j<m; j+=2) {
      result.push([list[j], list[j+1]])
    }
  }
  return result
}

proto.cells = function() {
  var stars = this.stars
  var result = []
  for(var i=0, n=stars.length; i<n; ++i) {
    var list = stars[i]
    for(var j=0, m=list.length; j<m; j+=2) {
      var s = list[j]
      var t = list[j+1]
      if(i < Math.min(s, t)) {
        result.push([i, s, t])
      }
    }
  }
  return result
}

function createTriangulation(numVerts, edges) {
  var stars = new Array(numVerts)
  for(var i=0; i<numVerts; ++i) {
    stars[i] = []
  }
  return new Triangulation(stars, edges)
}

},{"binary-search-bounds":100}],100:[function(_dereq_,module,exports){
"use strict"

function compileSearch(funcName, predicate, reversed, extraArgs, earlyOut) {
  var code = [
    "function ", funcName, "(a,l,h,", extraArgs.join(","),  "){",
    earlyOut ? "" : "var i=", (reversed ? "l-1" : "h+1"),
    ";while(l<=h){var m=(l+h)>>>1,x=a[m]"]
  if(earlyOut) {
    if(predicate.indexOf("c") < 0) {
      code.push(";if(x===y){return m}else if(x<=y){")
    } else {
      code.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){")
    }
  } else {
    code.push(";if(", predicate, "){i=m;")
  }
  if(reversed) {
    code.push("l=m+1}else{h=m-1}")
  } else {
    code.push("h=m-1}else{l=m+1}")
  }
  code.push("}")
  if(earlyOut) {
    code.push("return -1};")
  } else {
    code.push("return i};")
  }
  return code.join("")
}

function compileBoundsSearch(predicate, reversed, suffix, earlyOut) {
  var result = new Function([
  compileSearch("A", "x" + predicate + "y", reversed, ["y"], earlyOut),
  compileSearch("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut),
"function dispatchBsearch", suffix, "(a,y,c,l,h){\
if(typeof(c)==='function'){\
return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\
}else{\
return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\
}}\
return dispatchBsearch", suffix].join(""))
  return result()
}

module.exports = {
  ge: compileBoundsSearch(">=", false,  "GE"),
  gt: compileBoundsSearch(">",  false,  "GT"),
  lt: compileBoundsSearch("<",  true,   "LT"),
  le: compileBoundsSearch("<=", true,   "LE"),
  eq: compileBoundsSearch("-",  true,   "EQ", true)
}

},{}],101:[function(_dereq_,module,exports){
'use strict'

module.exports = orientation

function orientation(s) {
  var p = 1
  for(var i=1; i<s.length; ++i) {
    for(var j=0; j<i; ++j) {
      if(s[i] < s[j]) {
        p = -p
      } else if(s[j] === s[i]) {
        return 0
      }
    }
  }
  return p
}

},{}],102:[function(_dereq_,module,exports){
"use strict"

var dup = _dereq_("dup")
var solve = _dereq_("robust-linear-solve")

function dot(a, b) {
  var s = 0.0
  var d = a.length
  for(var i=0; i<d; ++i) {
    s += a[i] * b[i]
  }
  return s
}

function barycentricCircumcenter(points) {
  var N = points.length
  if(N === 0) {
    return []
  }
  
  var D = points[0].length
  var A = dup([points.length+1, points.length+1], 1.0)
  var b = dup([points.length+1], 1.0)
  A[N][N] = 0.0
  for(var i=0; i<N; ++i) {
    for(var j=0; j<=i; ++j) {
      A[j][i] = A[i][j] = 2.0 * dot(points[i], points[j])
    }
    b[i] = dot(points[i], points[i])
  }
  var x = solve(A, b)

  var denom = 0.0
  var h = x[N+1]
  for(var i=0; i<h.length; ++i) {
    denom += h[i]
  }

  var y = new Array(N)
  for(var i=0; i<N; ++i) {
    var h = x[i]
    var numer = 0.0
    for(var j=0; j<h.length; ++j) {
      numer += h[j]
    }
    y[i] =  numer / denom
  }

  return y
}

function circumcenter(points) {
  if(points.length === 0) {
    return []
  }
  var D = points[0].length
  var result = dup([D])
  var weights = barycentricCircumcenter(points)
  for(var i=0; i<points.length; ++i) {
    for(var j=0; j<D; ++j) {
      result[j] += points[i][j] * weights[i]
    }
  }
  return result
}

circumcenter.barycenetric = barycentricCircumcenter
module.exports = circumcenter
},{"dup":156,"robust-linear-solve":487}],103:[function(_dereq_,module,exports){
module.exports = circumradius

var circumcenter = _dereq_('circumcenter')

function circumradius(points) {
  var center = circumcenter(points)
  var avgDist = 0.0
  for(var i=0; i<points.length; ++i) {
    var p = points[i]
    for(var j=0; j<center.length; ++j) {
      avgDist += Math.pow(p[j] - center[j], 2)
    }
  }
  return Math.sqrt(avgDist / points.length)
}
},{"circumcenter":102}],104:[function(_dereq_,module,exports){
module.exports = clamp

function clamp(value, min, max) {
  return min < max
    ? (value < min ? min : value > max ? max : value)
    : (value < max ? max : value > min ? min : value)
}

},{}],105:[function(_dereq_,module,exports){
'use strict'

module.exports = cleanPSLG

var UnionFind = _dereq_('union-find')
var boxIntersect = _dereq_('box-intersect')
var segseg = _dereq_('robust-segment-intersect')
var rat = _dereq_('big-rat')
var ratCmp = _dereq_('big-rat/cmp')
var ratToFloat = _dereq_('big-rat/to-float')
var ratVec = _dereq_('rat-vec')
var nextafter = _dereq_('nextafter')

var solveIntersection = _dereq_('./lib/rat-seg-intersect')

// Bounds on a rational number when rounded to a float
function boundRat (r) {
  var f = ratToFloat(r)
  return [
    nextafter(f, -Infinity),
    nextafter(f, Infinity)
  ]
}

// Convert a list of edges in a pslg to bounding boxes
function boundEdges (points, edges) {
  var bounds = new Array(edges.length)
  for (var i = 0; i < edges.length; ++i) {
    var e = edges[i]
    var a = points[e[0]]
    var b = points[e[1]]
    bounds[i] = [
      nextafter(Math.min(a[0], b[0]), -Infinity),
      nextafter(Math.min(a[1], b[1]), -Infinity),
      nextafter(Math.max(a[0], b[0]), Infinity),
      nextafter(Math.max(a[1], b[1]), Infinity)
    ]
  }
  return bounds
}

// Convert a list of points into bounding boxes by duplicating coords
function boundPoints (points) {
  var bounds = new Array(points.length)
  for (var i = 0; i < points.length; ++i) {
    var p = points[i]
    bounds[i] = [
      nextafter(p[0], -Infinity),
      nextafter(p[1], -Infinity),
      nextafter(p[0], Infinity),
      nextafter(p[1], Infinity)
    ]
  }
  return bounds
}

// Find all pairs of crossing edges in a pslg (given edge bounds)
function getCrossings (points, edges, edgeBounds) {
  var result = []
  boxIntersect(edgeBounds, function (i, j) {
    var e = edges[i]
    var f = edges[j]
    if (e[0] === f[0] || e[0] === f[1] ||
      e[1] === f[0] || e[1] === f[1]) {
      return
    }
    var a = points[e[0]]
    var b = points[e[1]]
    var c = points[f[0]]
    var d = points[f[1]]
    if (segseg(a, b, c, d)) {
      result.push([i, j])
    }
  })
  return result
}

// Find all pairs of crossing vertices in a pslg (given edge/vert bounds)
function getTJunctions (points, edges, edgeBounds, vertBounds) {
  var result = []
  boxIntersect(edgeBounds, vertBounds, function (i, v) {
    var e = edges[i]
    if (e[0] === v || e[1] === v) {
      return
    }
    var p = points[v]
    var a = points[e[0]]
    var b = points[e[1]]
    if (segseg(a, b, p, p)) {
      result.push([i, v])
    }
  })
  return result
}

// Cut edges along crossings/tjunctions
function cutEdges (floatPoints, edges, crossings, junctions, useColor) {
  var i, e

  // Convert crossings into tjunctions by constructing rational points
  var ratPoints = floatPoints.map(function(p) {
      return [
          rat(p[0]),
          rat(p[1])
      ]
  })
  for (i = 0; i < crossings.length; ++i) {
    var crossing = crossings[i]
    e = crossing[0]
    var f = crossing[1]
    var ee = edges[e]
    var ef = edges[f]
    var x = solveIntersection(
      ratVec(floatPoints[ee[0]]),
      ratVec(floatPoints[ee[1]]),
      ratVec(floatPoints[ef[0]]),
      ratVec(floatPoints[ef[1]]))
    if (!x) {
      // Segments are parallel, should already be handled by t-junctions
      continue
    }
    var idx = floatPoints.length
    floatPoints.push([ratToFloat(x[0]), ratToFloat(x[1])])
    ratPoints.push(x)
    junctions.push([e, idx], [f, idx])
  }

  // Sort tjunctions
  junctions.sort(function (a, b) {
    if (a[0] !== b[0]) {
      return a[0] - b[0]
    }
    var u = ratPoints[a[1]]
    var v = ratPoints[b[1]]
    return ratCmp(u[0], v[0]) || ratCmp(u[1], v[1])
  })

  // Split edges along junctions
  for (i = junctions.length - 1; i >= 0; --i) {
    var junction = junctions[i]
    e = junction[0]

    var edge = edges[e]
    var s = edge[0]
    var t = edge[1]

    // Check if edge is not lexicographically sorted
    var a = floatPoints[s]
    var b = floatPoints[t]
    if (((a[0] - b[0]) || (a[1] - b[1])) < 0) {
      var tmp = s
      s = t
      t = tmp
    }

    // Split leading edge
    edge[0] = s
    var last = edge[1] = junction[1]

    // If we are grouping edges by color, remember to track data
    var color
    if (useColor) {
      color = edge[2]
    }

    // Split other edges
    while (i > 0 && junctions[i - 1][0] === e) {
      var junction = junctions[--i]
      var next = junction[1]
      if (useColor) {
        edges.push([last, next, color])
      } else {
        edges.push([last, next])
      }
      last = next
    }

    // Add final edge
    if (useColor) {
      edges.push([last, t, color])
    } else {
      edges.push([last, t])
    }
  }

  // Return constructed rational points
  return ratPoints
}

// Merge overlapping points
function dedupPoints (floatPoints, ratPoints, floatBounds) {
  var numPoints = ratPoints.length
  var uf = new UnionFind(numPoints)

  // Compute rational bounds
  var bounds = []
  for (var i = 0; i < ratPoints.length; ++i) {
    var p = ratPoints[i]
    var xb = boundRat(p[0])
    var yb = boundRat(p[1])
    bounds.push([
      nextafter(xb[0], -Infinity),
      nextafter(yb[0], -Infinity),
      nextafter(xb[1], Infinity),
      nextafter(yb[1], Infinity)
    ])
  }

  // Link all points with over lapping boxes
  boxIntersect(bounds, function (i, j) {
    uf.link(i, j)
  })

  // Do 1 pass over points to combine points in label sets
  var noDupes = true
  var labels = new Array(numPoints)
  for (var i = 0; i < numPoints; ++i) {
    var j = uf.find(i)
    if (j !== i) {
      // Clear no-dupes flag, zero out label
      noDupes = false
      // Make each point the top-left point from its cell
      floatPoints[j] = [
        Math.min(floatPoints[i][0], floatPoints[j][0]),
        Math.min(floatPoints[i][1], floatPoints[j][1])
      ]
    }
  }

  // If no duplicates, return null to signal termination
  if (noDupes) {
    return null
  }

  var ptr = 0
  for (var i = 0; i < numPoints; ++i) {
    var j = uf.find(i)
    if (j === i) {
      labels[i] = ptr
      floatPoints[ptr++] = floatPoints[i]
    } else {
      labels[i] = -1
    }
  }

  floatPoints.length = ptr

  // Do a second pass to fix up missing labels
  for (var i = 0; i < numPoints; ++i) {
    if (labels[i] < 0) {
      labels[i] = labels[uf.find(i)]
    }
  }

  // Return resulting union-find data structure
  return labels
}

function compareLex2 (a, b) { return (a[0] - b[0]) || (a[1] - b[1]) }
function compareLex3 (a, b) {
  var d = (a[0] - b[0]) || (a[1] - b[1])
  if (d) {
    return d
  }
  if (a[2] < b[2]) {
    return -1
  } else if (a[2] > b[2]) {
    return 1
  }
  return 0
}

// Remove duplicate edge labels
function dedupEdges (edges, labels, useColor) {
  if (edges.length === 0) {
    return
  }
  if (labels) {
    for (var i = 0; i < edges.length; ++i) {
      var e = edges[i]
      var a = labels[e[0]]
      var b = labels[e[1]]
      e[0] = Math.min(a, b)
      e[1] = Math.max(a, b)
    }
  } else {
    for (var i = 0; i < edges.length; ++i) {
      var e = edges[i]
      var a = e[0]
      var b = e[1]
      e[0] = Math.min(a, b)
      e[1] = Math.max(a, b)
    }
  }
  if (useColor) {
    edges.sort(compareLex3)
  } else {
    edges.sort(compareLex2)
  }
  var ptr = 1
  for (var i = 1; i < edges.length; ++i) {
    var prev = edges[i - 1]
    var next = edges[i]
    if (next[0] === prev[0] && next[1] === prev[1] &&
      (!useColor || next[2] === prev[2])) {
      continue
    }
    edges[ptr++] = next
  }
  edges.length = ptr
}

function preRound (points, edges, useColor) {
  var labels = dedupPoints(points, [], boundPoints(points))
  dedupEdges(edges, labels, useColor)
  return !!labels
}

// Repeat until convergence
function snapRound (points, edges, useColor) {
  // 1. find edge crossings
  var edgeBounds = boundEdges(points, edges)
  var crossings = getCrossings(points, edges, edgeBounds)

  // 2. find t-junctions
  var vertBounds = boundPoints(points)
  var tjunctions = getTJunctions(points, edges, edgeBounds, vertBounds)

  // 3. cut edges, construct rational points
  var ratPoints = cutEdges(points, edges, crossings, tjunctions, useColor)

  // 4. dedupe verts
  var labels = dedupPoints(points, ratPoints, vertBounds)

  // 5. dedupe edges
  dedupEdges(edges, labels, useColor)

  // 6. check termination
  if (!labels) {
    return (crossings.length > 0 || tjunctions.length > 0)
  }

  // More iterations necessary
  return true
}

// Main loop, runs PSLG clean up until completion
function cleanPSLG (points, edges, colors) {
  // If using colors, augment edges with color data
  var prevEdges
  if (colors) {
    prevEdges = edges
    var augEdges = new Array(edges.length)
    for (var i = 0; i < edges.length; ++i) {
      var e = edges[i]
      augEdges[i] = [e[0], e[1], colors[i]]
    }
    edges = augEdges
  }

  // First round: remove duplicate edges and points
  var modified = preRound(points, edges, !!colors)

  // Run snap rounding until convergence
  while (snapRound(points, edges, !!colors)) {
    modified = true
  }

  // Strip color tags
  if (!!colors && modified) {
    prevEdges.length = 0
    colors.length = 0
    for (var i = 0; i < edges.length; ++i) {
      var e = edges[i]
      prevEdges.push([e[0], e[1]])
      colors.push(e[2])
    }
  }

  return modified
}

},{"./lib/rat-seg-intersect":106,"big-rat":67,"big-rat/cmp":65,"big-rat/to-float":79,"box-intersect":85,"nextafter":437,"rat-vec":472,"robust-segment-intersect":491,"union-find":524}],106:[function(_dereq_,module,exports){
'use strict'

module.exports = solveIntersection

var ratMul = _dereq_('big-rat/mul')
var ratDiv = _dereq_('big-rat/div')
var ratSub = _dereq_('big-rat/sub')
var ratSign = _dereq_('big-rat/sign')
var rvSub = _dereq_('rat-vec/sub')
var rvAdd = _dereq_('rat-vec/add')
var rvMuls = _dereq_('rat-vec/muls')

function ratPerp (a, b) {
  return ratSub(ratMul(a[0], b[1]), ratMul(a[1], b[0]))
}

// Solve for intersection
//  x = a + t (b-a)
//  (x - c) ^ (d-c) = 0
//  (t * (b-a) + (a-c) ) ^ (d-c) = 0
//  t * (b-a)^(d-c) = (d-c)^(a-c)
//  t = (d-c)^(a-c) / (b-a)^(d-c)

function solveIntersection (a, b, c, d) {
  var ba = rvSub(b, a)
  var dc = rvSub(d, c)

  var baXdc = ratPerp(ba, dc)

  if (ratSign(baXdc) === 0) {
    return null
  }

  var ac = rvSub(a, c)
  var dcXac = ratPerp(dc, ac)

  var t = ratDiv(dcXac, baXdc)
  var s = rvMuls(ba, t)
  var r = rvAdd(a, s)

  return r
}

},{"big-rat/div":66,"big-rat/mul":76,"big-rat/sign":77,"big-rat/sub":78,"rat-vec/add":471,"rat-vec/muls":473,"rat-vec/sub":474}],107:[function(_dereq_,module,exports){
/** @module  color-id */

'use strict'

var clamp = _dereq_('clamp')

module.exports = toNumber
module.exports.to = toNumber
module.exports.from = fromNumber

function toNumber (rgba, normalized) {
	if(normalized == null) normalized = true

	var r = rgba[0], g = rgba[1], b = rgba[2], a = rgba[3]

	if (a == null) a = normalized ? 1 : 255

	if (normalized) {
		r *= 255
		g *= 255
		b *= 255
		a *= 255
	}

	r = clamp(r, 0, 255) & 0xFF
	g = clamp(g, 0, 255) & 0xFF
	b = clamp(b, 0, 255) & 0xFF
	a = clamp(a, 0, 255) & 0xFF

	//hi-order shift converts to -1, so we can't use <<24
	var n = (r * 0x01000000) + (g << 16) + (b << 8) + (a)

	return n
}

function fromNumber (n, normalized) {
	n = +n

	var r = n >>> 24
	var g = (n & 0x00ff0000) >>> 16
	var b = (n & 0x0000ff00) >>> 8
	var a = n & 0x000000ff

	if (normalized === false) return [r, g, b, a]

	return [r/255, g/255, b/255, a/255]
}

},{"clamp":104}],108:[function(_dereq_,module,exports){
'use strict'

module.exports = {
	"aliceblue": [240, 248, 255],
	"antiquewhite": [250, 235, 215],
	"aqua": [0, 255, 255],
	"aquamarine": [127, 255, 212],
	"azure": [240, 255, 255],
	"beige": [245, 245, 220],
	"bisque": [255, 228, 196],
	"black": [0, 0, 0],
	"blanchedalmond": [255, 235, 205],
	"blue": [0, 0, 255],
	"blueviolet": [138, 43, 226],
	"brown": [165, 42, 42],
	"burlywood": [222, 184, 135],
	"cadetblue": [95, 158, 160],
	"chartreuse": [127, 255, 0],
	"chocolate": [210, 105, 30],
	"coral": [255, 127, 80],
	"cornflowerblue": [100, 149, 237],
	"cornsilk": [255, 248, 220],
	"crimson": [220, 20, 60],
	"cyan": [0, 255, 255],
	"darkblue": [0, 0, 139],
	"darkcyan": [0, 139, 139],
	"darkgoldenrod": [184, 134, 11],
	"darkgray": [169, 169, 169],
	"darkgreen": [0, 100, 0],
	"darkgrey": [169, 169, 169],
	"darkkhaki": [189, 183, 107],
	"darkmagenta": [139, 0, 139],
	"darkolivegreen": [85, 107, 47],
	"darkorange": [255, 140, 0],
	"darkorchid": [153, 50, 204],
	"darkred": [139, 0, 0],
	"darksalmon": [233, 150, 122],
	"darkseagreen": [143, 188, 143],
	"darkslateblue": [72, 61, 139],
	"darkslategray": [47, 79, 79],
	"darkslategrey": [47, 79, 79],
	"darkturquoise": [0, 206, 209],
	"darkviolet": [148, 0, 211],
	"deeppink": [255, 20, 147],
	"deepskyblue": [0, 191, 255],
	"dimgray": [105, 105, 105],
	"dimgrey": [105, 105, 105],
	"dodgerblue": [30, 144, 255],
	"firebrick": [178, 34, 34],
	"floralwhite": [255, 250, 240],
	"forestgreen": [34, 139, 34],
	"fuchsia": [255, 0, 255],
	"gainsboro": [220, 220, 220],
	"ghostwhite": [248, 248, 255],
	"gold": [255, 215, 0],
	"goldenrod": [218, 165, 32],
	"gray": [128, 128, 128],
	"green": [0, 128, 0],
	"greenyellow": [173, 255, 47],
	"grey": [128, 128, 128],
	"honeydew": [240, 255, 240],
	"hotpink": [255, 105, 180],
	"indianred": [205, 92, 92],
	"indigo": [75, 0, 130],
	"ivory": [255, 255, 240],
	"khaki": [240, 230, 140],
	"lavender": [230, 230, 250],
	"lavenderblush": [255, 240, 245],
	"lawngreen": [124, 252, 0],
	"lemonchiffon": [255, 250, 205],
	"lightblue": [173, 216, 230],
	"lightcoral": [240, 128, 128],
	"lightcyan": [224, 255, 255],
	"lightgoldenrodyellow": [250, 250, 210],
	"lightgray": [211, 211, 211],
	"lightgreen": [144, 238, 144],
	"lightgrey": [211, 211, 211],
	"lightpink": [255, 182, 193],
	"lightsalmon": [255, 160, 122],
	"lightseagreen": [32, 178, 170],
	"lightskyblue": [135, 206, 250],
	"lightslategray": [119, 136, 153],
	"lightslategrey": [119, 136, 153],
	"lightsteelblue": [176, 196, 222],
	"lightyellow": [255, 255, 224],
	"lime": [0, 255, 0],
	"limegreen": [50, 205, 50],
	"linen": [250, 240, 230],
	"magenta": [255, 0, 255],
	"maroon": [128, 0, 0],
	"mediumaquamarine": [102, 205, 170],
	"mediumblue": [0, 0, 205],
	"mediumorchid": [186, 85, 211],
	"mediumpurple": [147, 112, 219],
	"mediumseagreen": [60, 179, 113],
	"mediumslateblue": [123, 104, 238],
	"mediumspringgreen": [0, 250, 154],
	"mediumturquoise": [72, 209, 204],
	"mediumvioletred": [199, 21, 133],
	"midnightblue": [25, 25, 112],
	"mintcream": [245, 255, 250],
	"mistyrose": [255, 228, 225],
	"moccasin": [255, 228, 181],
	"navajowhite": [255, 222, 173],
	"navy": [0, 0, 128],
	"oldlace": [253, 245, 230],
	"olive": [128, 128, 0],
	"olivedrab": [107, 142, 35],
	"orange": [255, 165, 0],
	"orangered": [255, 69, 0],
	"orchid": [218, 112, 214],
	"palegoldenrod": [238, 232, 170],
	"palegreen": [152, 251, 152],
	"paleturquoise": [175, 238, 238],
	"palevioletred": [219, 112, 147],
	"papayawhip": [255, 239, 213],
	"peachpuff": [255, 218, 185],
	"peru": [205, 133, 63],
	"pink": [255, 192, 203],
	"plum": [221, 160, 221],
	"powderblue": [176, 224, 230],
	"purple": [128, 0, 128],
	"rebeccapurple": [102, 51, 153],
	"red": [255, 0, 0],
	"rosybrown": [188, 143, 143],
	"royalblue": [65, 105, 225],
	"saddlebrown": [139, 69, 19],
	"salmon": [250, 128, 114],
	"sandybrown": [244, 164, 96],
	"seagreen": [46, 139, 87],
	"seashell": [255, 245, 238],
	"sienna": [160, 82, 45],
	"silver": [192, 192, 192],
	"skyblue": [135, 206, 235],
	"slateblue": [106, 90, 205],
	"slategray": [112, 128, 144],
	"slategrey": [112, 128, 144],
	"snow": [255, 250, 250],
	"springgreen": [0, 255, 127],
	"steelblue": [70, 130, 180],
	"tan": [210, 180, 140],
	"teal": [0, 128, 128],
	"thistle": [216, 191, 216],
	"tomato": [255, 99, 71],
	"turquoise": [64, 224, 208],
	"violet": [238, 130, 238],
	"wheat": [245, 222, 179],
	"white": [255, 255, 255],
	"whitesmoke": [245, 245, 245],
	"yellow": [255, 255, 0],
	"yellowgreen": [154, 205, 50]
};

},{}],109:[function(_dereq_,module,exports){
/** @module  color-normalize */

'use strict'

var rgba = _dereq_('color-rgba')
var clamp = _dereq_('clamp')
var dtype = _dereq_('dtype')

module.exports = function normalize (color, type) {
	if (type === 'float' || !type) type = 'array'
	if (type === 'uint') type = 'uint8'
	if (type === 'uint_clamped') type = 'uint8_clamped'
	var Ctor = dtype(type)
	var output = new Ctor(4)

	var normalize = type !== 'uint8' && type !== 'uint8_clamped'

	// attempt to parse non-array arguments
	if (!color.length || typeof color === 'string') {
		color = rgba(color)
		color[0] /= 255
		color[1] /= 255
		color[2] /= 255
	}

	// 0, 1 are possible contradictory values for Arrays:
	// [1,1,1] input gives [1,1,1] output instead of [1/255,1/255,1/255], which may be collision if input is meant to be uint.
	// converting [1,1,1] to [1/255,1/255,1/255] in case of float input gives larger mistake since [1,1,1] float is frequent edge value, whereas [0,1,1], [1,1,1] etc. uint inputs are relatively rare
	if (isInt(color)) {
		output[0] = color[0]
		output[1] = color[1]
		output[2] = color[2]
		output[3] = color[3] != null ? color[3] : 255

		if (normalize) {
			output[0] /= 255
			output[1] /= 255
			output[2] /= 255
			output[3] /= 255
		}

		return output
	}

	if (!normalize) {
		output[0] = clamp(Math.floor(color[0] * 255), 0, 255)
		output[1] = clamp(Math.floor(color[1] * 255), 0, 255)
		output[2] = clamp(Math.floor(color[2] * 255), 0, 255)
		output[3] = color[3] == null ? 255 : clamp(Math.floor(color[3] * 255), 0, 255)
	} else {
		output[0] = color[0]
		output[1] = color[1]
		output[2] = color[2]
		output[3] = color[3] != null ? color[3] : 1
	}

	return output
}

function isInt(color) {
	if (color instanceof Uint8Array || color instanceof Uint8ClampedArray) return true

	if (Array.isArray(color) &&
		(color[0] > 1 || color[0] === 0) &&
		(color[1] > 1 || color[1] === 0) &&
		(color[2] > 1 || color[2] === 0) &&
		(!color[3] || color[3] > 1)
	) return true

	return false
}

},{"clamp":104,"color-rgba":111,"dtype":155}],110:[function(_dereq_,module,exports){
(function (global){
/**
 * @module color-parse
 */

'use strict'

var names = _dereq_('color-name')
var isObject = _dereq_('is-plain-obj')
var defined = _dereq_('defined')

module.exports = parse

/**
 * Base hues
 * http://dev.w3.org/csswg/css-color/#typedef-named-hue
 */
//FIXME: use external hue detector
var baseHues = {
	red: 0,
	orange: 60,
	yellow: 120,
	green: 180,
	blue: 240,
	purple: 300
}

/**
 * Parse color from the string passed
 *
 * @return {Object} A space indicator `space`, an array `values` and `alpha`
 */
function parse (cstr) {
	var m, parts = [], alpha = 1, space

	if (typeof cstr === 'string') {
		//keyword
		if (names[cstr]) {
			parts = names[cstr].slice()
			space = 'rgb'
		}

		//reserved words
		else if (cstr === 'transparent') {
			alpha = 0
			space = 'rgb'
			parts = [0,0,0]
		}

		//hex
		else if (/^#[A-Fa-f0-9]+$/.test(cstr)) {
			var base = cstr.slice(1)
			var size = base.length
			var isShort = size <= 4
			alpha = 1

			if (isShort) {
				parts = [
					parseInt(base[0] + base[0], 16),
					parseInt(base[1] + base[1], 16),
					parseInt(base[2] + base[2], 16)
				]
				if (size === 4) {
					alpha = parseInt(base[3] + base[3], 16) / 255
				}
			}
			else {
				parts = [
					parseInt(base[0] + base[1], 16),
					parseInt(base[2] + base[3], 16),
					parseInt(base[4] + base[5], 16)
				]
				if (size === 8) {
					alpha = parseInt(base[6] + base[7], 16) / 255
				}
			}

			if (!parts[0]) parts[0] = 0
			if (!parts[1]) parts[1] = 0
			if (!parts[2]) parts[2] = 0

			space = 'rgb'
		}

		//color space
		else if (m = /^((?:rgb|hs[lvb]|hwb|cmyk?|xy[zy]|gray|lab|lchu?v?|[ly]uv|lms)a?)\s*\(([^\)]*)\)/.exec(cstr)) {
			var name = m[1]
			var base = name.replace(/a$/, '')
			space = base
			var size = base === 'cmyk' ? 4 : base === 'gray' ? 1 : 3
			parts = m[2].trim()
				.split(/\s*,\s*/)
				.map(function (x, i) {
					//<percentage>
					if (/%$/.test(x)) {
						//alpha
						if (i === size)	return parseFloat(x) / 100
						//rgb
						if (base === 'rgb') return parseFloat(x) * 255 / 100
						return parseFloat(x)
					}
					//hue
					else if (base[i] === 'h') {
						//<deg>
						if (/deg$/.test(x)) {
							return parseFloat(x)
						}
						//<base-hue>
						else if (baseHues[x] !== undefined) {
							return baseHues[x]
						}
					}
					return parseFloat(x)
				})

			if (name === base) parts.push(1)
			alpha = parts[size] === undefined ? 1 : parts[size]
			parts = parts.slice(0, size)
		}

		//named channels case
		else if (cstr.length > 10 && /[0-9](?:\s|\/)/.test(cstr)) {
			parts = cstr.match(/([0-9]+)/g).map(function (value) {
				return parseFloat(value)
			})

			space = cstr.match(/([a-z])/ig).join('').toLowerCase()
		}
	}

	//numeric case
	else if (!isNaN(cstr)) {
		space = 'rgb'
		parts = [cstr >>> 16, (cstr & 0x00ff00) >>> 8, cstr & 0x0000ff]
	}

	//object case - detects css cases of rgb and hsl
	else if (isObject(cstr)) {
		var r = defined(cstr.r, cstr.red, cstr.R, null)

		if (r !== null) {
			space = 'rgb'
			parts = [
				r,
				defined(cstr.g, cstr.green, cstr.G),
				defined(cstr.b, cstr.blue, cstr.B)
			]
		}
		else {
			space = 'hsl'
			parts = [
				defined(cstr.h, cstr.hue, cstr.H),
				defined(cstr.s, cstr.saturation, cstr.S),
				defined(cstr.l, cstr.lightness, cstr.L, cstr.b, cstr.brightness)
			]
		}

		alpha = defined(cstr.a, cstr.alpha, cstr.opacity, 1)

		if (cstr.opacity != null) alpha /= 100
	}

	//array
	else if (Array.isArray(cstr) || global.ArrayBuffer && ArrayBuffer.isView && ArrayBuffer.isView(cstr)) {
		parts = [cstr[0], cstr[1], cstr[2]]
		space = 'rgb'
		alpha = cstr.length === 4 ? cstr[3] : 1
	}

	return {
		space: space,
		values: parts,
		alpha: alpha
	}
}

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"color-name":108,"defined":150,"is-plain-obj":408}],111:[function(_dereq_,module,exports){
/** @module  color-rgba */

'use strict'

var parse = _dereq_('color-parse')
var hsl = _dereq_('color-space/hsl')
var clamp = _dereq_('clamp')

module.exports = function rgba (color) {
	var values, i, l

	//attempt to parse non-array arguments
	var parsed = parse(color)

	if (!parsed.space) return []

	values = Array(3)
	values[0] = clamp(parsed.values[0], 0, 255)
	values[1] = clamp(parsed.values[1], 0, 255)
	values[2] = clamp(parsed.values[2], 0, 255)

	if (parsed.space[0] === 'h') {
		values = hsl.rgb(values)
	}

	values.push(clamp(parsed.alpha, 0, 1))

	return values
}

},{"clamp":104,"color-parse":110,"color-space/hsl":112}],112:[function(_dereq_,module,exports){
/**
 * @module color-space/hsl
 */
'use strict'

var rgb = _dereq_('./rgb');

module.exports = {
	name: 'hsl',
	min: [0,0,0],
	max: [360,100,100],
	channel: ['hue', 'saturation', 'lightness'],
	alias: ['HSL'],

	rgb: function(hsl) {
		var h = hsl[0] / 360,
				s = hsl[1] / 100,
				l = hsl[2] / 100,
				t1, t2, t3, rgb, val;

		if (s === 0) {
			val = l * 255;
			return [val, val, val];
		}

		if (l < 0.5) {
			t2 = l * (1 + s);
		}
		else {
			t2 = l + s - l * s;
		}
		t1 = 2 * l - t2;

		rgb = [0, 0, 0];
		for (var i = 0; i < 3; i++) {
			t3 = h + 1 / 3 * - (i - 1);
			if (t3 < 0) {
				t3++;
			}
			else if (t3 > 1) {
				t3--;
			}

			if (6 * t3 < 1) {
				val = t1 + (t2 - t1) * 6 * t3;
			}
			else if (2 * t3 < 1) {
				val = t2;
			}
			else if (3 * t3 < 2) {
				val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
			}
			else {
				val = t1;
			}

			rgb[i] = val * 255;
		}

		return rgb;
	}
};


//extend rgb
rgb.hsl = function(rgb) {
	var r = rgb[0]/255,
			g = rgb[1]/255,
			b = rgb[2]/255,
			min = Math.min(r, g, b),
			max = Math.max(r, g, b),
			delta = max - min,
			h, s, l;

	if (max === min) {
		h = 0;
	}
	else if (r === max) {
		h = (g - b) / delta;
	}
	else if (g === max) {
		h = 2 + (b - r) / delta;
	}
	else if (b === max) {
		h = 4 + (r - g)/ delta;
	}

	h = Math.min(h * 60, 360);

	if (h < 0) {
		h += 360;
	}

	l = (min + max) / 2;

	if (max === min) {
		s = 0;
	}
	else if (l <= 0.5) {
		s = delta / (max + min);
	}
	else {
		s = delta / (2 - max - min);
	}

	return [h, s * 100, l * 100];
};

},{"./rgb":113}],113:[function(_dereq_,module,exports){
/**
 * RGB space.
 *
 * @module  color-space/rgb
 */
'use strict'

module.exports = {
	name: 'rgb',
	min: [0,0,0],
	max: [255,255,255],
	channel: ['red', 'green', 'blue'],
	alias: ['RGB']
};

},{}],114:[function(_dereq_,module,exports){
module.exports={
	"jet":[{"index":0,"rgb":[0,0,131]},{"index":0.125,"rgb":[0,60,170]},{"index":0.375,"rgb":[5,255,255]},{"index":0.625,"rgb":[255,255,0]},{"index":0.875,"rgb":[250,0,0]},{"index":1,"rgb":[128,0,0]}],

	"hsv":[{"index":0,"rgb":[255,0,0]},{"index":0.169,"rgb":[253,255,2]},{"index":0.173,"rgb":[247,255,2]},{"index":0.337,"rgb":[0,252,4]},{"index":0.341,"rgb":[0,252,10]},{"index":0.506,"rgb":[1,249,255]},{"index":0.671,"rgb":[2,0,253]},{"index":0.675,"rgb":[8,0,253]},{"index":0.839,"rgb":[255,0,251]},{"index":0.843,"rgb":[255,0,245]},{"index":1,"rgb":[255,0,6]}],

	"hot":[{"index":0,"rgb":[0,0,0]},{"index":0.3,"rgb":[230,0,0]},{"index":0.6,"rgb":[255,210,0]},{"index":1,"rgb":[255,255,255]}],

	"cool":[{"index":0,"rgb":[0,255,255]},{"index":1,"rgb":[255,0,255]}],

	"spring":[{"index":0,"rgb":[255,0,255]},{"index":1,"rgb":[255,255,0]}],

	"summer":[{"index":0,"rgb":[0,128,102]},{"index":1,"rgb":[255,255,102]}],

	"autumn":[{"index":0,"rgb":[255,0,0]},{"index":1,"rgb":[255,255,0]}],

	"winter":[{"index":0,"rgb":[0,0,255]},{"index":1,"rgb":[0,255,128]}],

	"bone":[{"index":0,"rgb":[0,0,0]},{"index":0.376,"rgb":[84,84,116]},{"index":0.753,"rgb":[169,200,200]},{"index":1,"rgb":[255,255,255]}],

	"copper":[{"index":0,"rgb":[0,0,0]},{"index":0.804,"rgb":[255,160,102]},{"index":1,"rgb":[255,199,127]}],

	"greys":[{"index":0,"rgb":[0,0,0]},{"index":1,"rgb":[255,255,255]}],

	"yignbu":[{"index":0,"rgb":[8,29,88]},{"index":0.125,"rgb":[37,52,148]},{"index":0.25,"rgb":[34,94,168]},{"index":0.375,"rgb":[29,145,192]},{"index":0.5,"rgb":[65,182,196]},{"index":0.625,"rgb":[127,205,187]},{"index":0.75,"rgb":[199,233,180]},{"index":0.875,"rgb":[237,248,217]},{"index":1,"rgb":[255,255,217]}],

	"greens":[{"index":0,"rgb":[0,68,27]},{"index":0.125,"rgb":[0,109,44]},{"index":0.25,"rgb":[35,139,69]},{"index":0.375,"rgb":[65,171,93]},{"index":0.5,"rgb":[116,196,118]},{"index":0.625,"rgb":[161,217,155]},{"index":0.75,"rgb":[199,233,192]},{"index":0.875,"rgb":[229,245,224]},{"index":1,"rgb":[247,252,245]}],

	"yiorrd":[{"index":0,"rgb":[128,0,38]},{"index":0.125,"rgb":[189,0,38]},{"index":0.25,"rgb":[227,26,28]},{"index":0.375,"rgb":[252,78,42]},{"index":0.5,"rgb":[253,141,60]},{"index":0.625,"rgb":[254,178,76]},{"index":0.75,"rgb":[254,217,118]},{"index":0.875,"rgb":[255,237,160]},{"index":1,"rgb":[255,255,204]}],

	"bluered":[{"index":0,"rgb":[0,0,255]},{"index":1,"rgb":[255,0,0]}],

	"rdbu":[{"index":0,"rgb":[5,10,172]},{"index":0.35,"rgb":[106,137,247]},{"index":0.5,"rgb":[190,190,190]},{"index":0.6,"rgb":[220,170,132]},{"index":0.7,"rgb":[230,145,90]},{"index":1,"rgb":[178,10,28]}],

	"picnic":[{"index":0,"rgb":[0,0,255]},{"index":0.1,"rgb":[51,153,255]},{"index":0.2,"rgb":[102,204,255]},{"index":0.3,"rgb":[153,204,255]},{"index":0.4,"rgb":[204,204,255]},{"index":0.5,"rgb":[255,255,255]},{"index":0.6,"rgb":[255,204,255]},{"index":0.7,"rgb":[255,153,255]},{"index":0.8,"rgb":[255,102,204]},{"index":0.9,"rgb":[255,102,102]},{"index":1,"rgb":[255,0,0]}],

	"rainbow":[{"index":0,"rgb":[150,0,90]},{"index":0.125,"rgb":[0,0,200]},{"index":0.25,"rgb":[0,25,255]},{"index":0.375,"rgb":[0,152,255]},{"index":0.5,"rgb":[44,255,150]},{"index":0.625,"rgb":[151,255,0]},{"index":0.75,"rgb":[255,234,0]},{"index":0.875,"rgb":[255,111,0]},{"index":1,"rgb":[255,0,0]}],

	"portland":[{"index":0,"rgb":[12,51,131]},{"index":0.25,"rgb":[10,136,186]},{"index":0.5,"rgb":[242,211,56]},{"index":0.75,"rgb":[242,143,56]},{"index":1,"rgb":[217,30,30]}],

	"blackbody":[{"index":0,"rgb":[0,0,0]},{"index":0.2,"rgb":[230,0,0]},{"index":0.4,"rgb":[230,210,0]},{"index":0.7,"rgb":[255,255,255]},{"index":1,"rgb":[160,200,255]}],

	"earth":[{"index":0,"rgb":[0,0,130]},{"index":0.1,"rgb":[0,180,180]},{"index":0.2,"rgb":[40,210,40]},{"index":0.4,"rgb":[230,230,50]},{"index":0.6,"rgb":[120,70,20]},{"index":1,"rgb":[255,255,255]}],

	"electric":[{"index":0,"rgb":[0,0,0]},{"index":0.15,"rgb":[30,0,100]},{"index":0.4,"rgb":[120,0,100]},{"index":0.6,"rgb":[160,90,0]},{"index":0.8,"rgb":[230,200,0]},{"index":1,"rgb":[255,250,220]}],

	"alpha": [{"index":0, "rgb": [255,255,255,0]},{"index":1, "rgb": [255,255,255,1]}],

	"viridis": [{"index":0,"rgb":[68,1,84]},{"index":0.13,"rgb":[71,44,122]},{"index":0.25,"rgb":[59,81,139]},{"index":0.38,"rgb":[44,113,142]},{"index":0.5,"rgb":[33,144,141]},{"index":0.63,"rgb":[39,173,129]},{"index":0.75,"rgb":[92,200,99]},{"index":0.88,"rgb":[170,220,50]},{"index":1,"rgb":[253,231,37]}],

	"inferno": [{"index":0,"rgb":[0,0,4]},{"index":0.13,"rgb":[31,12,72]},{"index":0.25,"rgb":[85,15,109]},{"index":0.38,"rgb":[136,34,106]},{"index":0.5,"rgb":[186,54,85]},{"index":0.63,"rgb":[227,89,51]},{"index":0.75,"rgb":[249,140,10]},{"index":0.88,"rgb":[249,201,50]},{"index":1,"rgb":[252,255,164]}],

	"magma": [{"index":0,"rgb":[0,0,4]},{"index":0.13,"rgb":[28,16,68]},{"index":0.25,"rgb":[79,18,123]},{"index":0.38,"rgb":[129,37,129]},{"index":0.5,"rgb":[181,54,122]},{"index":0.63,"rgb":[229,80,100]},{"index":0.75,"rgb":[251,135,97]},{"index":0.88,"rgb":[254,194,135]},{"index":1,"rgb":[252,253,191]}],

	"plasma": [{"index":0,"rgb":[13,8,135]},{"index":0.13,"rgb":[75,3,161]},{"index":0.25,"rgb":[125,3,168]},{"index":0.38,"rgb":[168,34,150]},{"index":0.5,"rgb":[203,70,121]},{"index":0.63,"rgb":[229,107,93]},{"index":0.75,"rgb":[248,148,65]},{"index":0.88,"rgb":[253,195,40]},{"index":1,"rgb":[240,249,33]}],

	"warm": [{"index":0,"rgb":[125,0,179]},{"index":0.13,"rgb":[172,0,187]},{"index":0.25,"rgb":[219,0,170]},{"index":0.38,"rgb":[255,0,130]},{"index":0.5,"rgb":[255,63,74]},{"index":0.63,"rgb":[255,123,0]},{"index":0.75,"rgb":[234,176,0]},{"index":0.88,"rgb":[190,228,0]},{"index":1,"rgb":[147,255,0]}],

	"cool": [{"index":0,"rgb":[125,0,179]},{"index":0.13,"rgb":[116,0,218]},{"index":0.25,"rgb":[98,74,237]},{"index":0.38,"rgb":[68,146,231]},{"index":0.5,"rgb":[0,204,197]},{"index":0.63,"rgb":[0,247,146]},{"index":0.75,"rgb":[0,255,88]},{"index":0.88,"rgb":[40,255,8]},{"index":1,"rgb":[147,255,0]}],

	"rainbow-soft": [{"index":0,"rgb":[125,0,179]},{"index":0.1,"rgb":[199,0,180]},{"index":0.2,"rgb":[255,0,121]},{"index":0.3,"rgb":[255,108,0]},{"index":0.4,"rgb":[222,194,0]},{"index":0.5,"rgb":[150,255,0]},{"index":0.6,"rgb":[0,255,55]},{"index":0.7,"rgb":[0,246,150]},{"index":0.8,"rgb":[50,167,222]},{"index":0.9,"rgb":[103,51,235]},{"index":1,"rgb":[124,0,186]}],

	"bathymetry": [{"index":0,"rgb":[40,26,44]},{"index":0.13,"rgb":[59,49,90]},{"index":0.25,"rgb":[64,76,139]},{"index":0.38,"rgb":[63,110,151]},{"index":0.5,"rgb":[72,142,158]},{"index":0.63,"rgb":[85,174,163]},{"index":0.75,"rgb":[120,206,163]},{"index":0.88,"rgb":[187,230,172]},{"index":1,"rgb":[253,254,204]}],

	"cdom": [{"index":0,"rgb":[47,15,62]},{"index":0.13,"rgb":[87,23,86]},{"index":0.25,"rgb":[130,28,99]},{"index":0.38,"rgb":[171,41,96]},{"index":0.5,"rgb":[206,67,86]},{"index":0.63,"rgb":[230,106,84]},{"index":0.75,"rgb":[242,149,103]},{"index":0.88,"rgb":[249,193,135]},{"index":1,"rgb":[254,237,176]}],

	"chlorophyll": [{"index":0,"rgb":[18,36,20]},{"index":0.13,"rgb":[25,63,41]},{"index":0.25,"rgb":[24,91,59]},{"index":0.38,"rgb":[13,119,72]},{"index":0.5,"rgb":[18,148,80]},{"index":0.63,"rgb":[80,173,89]},{"index":0.75,"rgb":[132,196,122]},{"index":0.88,"rgb":[175,221,162]},{"index":1,"rgb":[215,249,208]}],

	"density": [{"index":0,"rgb":[54,14,36]},{"index":0.13,"rgb":[89,23,80]},{"index":0.25,"rgb":[110,45,132]},{"index":0.38,"rgb":[120,77,178]},{"index":0.5,"rgb":[120,113,213]},{"index":0.63,"rgb":[115,151,228]},{"index":0.75,"rgb":[134,185,227]},{"index":0.88,"rgb":[177,214,227]},{"index":1,"rgb":[230,241,241]}],

	"freesurface-blue": [{"index":0,"rgb":[30,4,110]},{"index":0.13,"rgb":[47,14,176]},{"index":0.25,"rgb":[41,45,236]},{"index":0.38,"rgb":[25,99,212]},{"index":0.5,"rgb":[68,131,200]},{"index":0.63,"rgb":[114,156,197]},{"index":0.75,"rgb":[157,181,203]},{"index":0.88,"rgb":[200,208,216]},{"index":1,"rgb":[241,237,236]}],

	"freesurface-red": [{"index":0,"rgb":[60,9,18]},{"index":0.13,"rgb":[100,17,27]},{"index":0.25,"rgb":[142,20,29]},{"index":0.38,"rgb":[177,43,27]},{"index":0.5,"rgb":[192,87,63]},{"index":0.63,"rgb":[205,125,105]},{"index":0.75,"rgb":[216,162,148]},{"index":0.88,"rgb":[227,199,193]},{"index":1,"rgb":[241,237,236]}],

	"oxygen": [{"index":0,"rgb":[64,5,5]},{"index":0.13,"rgb":[106,6,15]},{"index":0.25,"rgb":[144,26,7]},{"index":0.38,"rgb":[168,64,3]},{"index":0.5,"rgb":[188,100,4]},{"index":0.63,"rgb":[206,136,11]},{"index":0.75,"rgb":[220,174,25]},{"index":0.88,"rgb":[231,215,44]},{"index":1,"rgb":[248,254,105]}],

	"par": [{"index":0,"rgb":[51,20,24]},{"index":0.13,"rgb":[90,32,35]},{"index":0.25,"rgb":[129,44,34]},{"index":0.38,"rgb":[159,68,25]},{"index":0.5,"rgb":[182,99,19]},{"index":0.63,"rgb":[199,134,22]},{"index":0.75,"rgb":[212,171,35]},{"index":0.88,"rgb":[221,210,54]},{"index":1,"rgb":[225,253,75]}],

	"phase": [{"index":0,"rgb":[145,105,18]},{"index":0.13,"rgb":[184,71,38]},{"index":0.25,"rgb":[186,58,115]},{"index":0.38,"rgb":[160,71,185]},{"index":0.5,"rgb":[110,97,218]},{"index":0.63,"rgb":[50,123,164]},{"index":0.75,"rgb":[31,131,110]},{"index":0.88,"rgb":[77,129,34]},{"index":1,"rgb":[145,105,18]}],

	"salinity": [{"index":0,"rgb":[42,24,108]},{"index":0.13,"rgb":[33,50,162]},{"index":0.25,"rgb":[15,90,145]},{"index":0.38,"rgb":[40,118,137]},{"index":0.5,"rgb":[59,146,135]},{"index":0.63,"rgb":[79,175,126]},{"index":0.75,"rgb":[120,203,104]},{"index":0.88,"rgb":[193,221,100]},{"index":1,"rgb":[253,239,154]}],

	"temperature": [{"index":0,"rgb":[4,35,51]},{"index":0.13,"rgb":[23,51,122]},{"index":0.25,"rgb":[85,59,157]},{"index":0.38,"rgb":[129,79,143]},{"index":0.5,"rgb":[175,95,130]},{"index":0.63,"rgb":[222,112,101]},{"index":0.75,"rgb":[249,146,66]},{"index":0.88,"rgb":[249,196,65]},{"index":1,"rgb":[232,250,91]}],

	"turbidity": [{"index":0,"rgb":[34,31,27]},{"index":0.13,"rgb":[65,50,41]},{"index":0.25,"rgb":[98,69,52]},{"index":0.38,"rgb":[131,89,57]},{"index":0.5,"rgb":[161,112,59]},{"index":0.63,"rgb":[185,140,66]},{"index":0.75,"rgb":[202,174,88]},{"index":0.88,"rgb":[216,209,126]},{"index":1,"rgb":[233,246,171]}],

	"velocity-blue": [{"index":0,"rgb":[17,32,64]},{"index":0.13,"rgb":[35,52,116]},{"index":0.25,"rgb":[29,81,156]},{"index":0.38,"rgb":[31,113,162]},{"index":0.5,"rgb":[50,144,169]},{"index":0.63,"rgb":[87,173,176]},{"index":0.75,"rgb":[149,196,189]},{"index":0.88,"rgb":[203,221,211]},{"index":1,"rgb":[254,251,230]}],

	"velocity-green": [{"index":0,"rgb":[23,35,19]},{"index":0.13,"rgb":[24,64,38]},{"index":0.25,"rgb":[11,95,45]},{"index":0.38,"rgb":[39,123,35]},{"index":0.5,"rgb":[95,146,12]},{"index":0.63,"rgb":[152,165,18]},{"index":0.75,"rgb":[201,186,69]},{"index":0.88,"rgb":[233,216,137]},{"index":1,"rgb":[255,253,205]}],

	"cubehelix": [{"index":0,"rgb":[0,0,0]},{"index":0.07,"rgb":[22,5,59]},{"index":0.13,"rgb":[60,4,105]},{"index":0.2,"rgb":[109,1,135]},{"index":0.27,"rgb":[161,0,147]},{"index":0.33,"rgb":[210,2,142]},{"index":0.4,"rgb":[251,11,123]},{"index":0.47,"rgb":[255,29,97]},{"index":0.53,"rgb":[255,54,69]},{"index":0.6,"rgb":[255,85,46]},{"index":0.67,"rgb":[255,120,34]},{"index":0.73,"rgb":[255,157,37]},{"index":0.8,"rgb":[241,191,57]},{"index":0.87,"rgb":[224,220,93]},{"index":0.93,"rgb":[218,241,142]},{"index":1,"rgb":[227,253,198]}]
};

},{}],115:[function(_dereq_,module,exports){
/*
 * Ben Postlethwaite
 * January 2013
 * License MIT
 */
'use strict';

var colorScale = _dereq_('./colorScale');
var lerp = _dereq_('lerp')

module.exports = createColormap;

function createColormap (spec) {
    /*
     * Default Options
     */
    var indicies, rgba, fromrgba, torgba,
        nsteps, cmap, colormap, format,
        nshades, colors, alpha, index, i,
        r = [],
        g = [],
        b = [],
        a = [];

    if ( !spec ) spec = {};

    nshades = (spec.nshades || 72) - 1;
    format = spec.format || 'hex';

    colormap = spec.colormap;
    if (!colormap) colormap = 'jet';

    if (typeof colormap === 'string') {
        colormap = colormap.toLowerCase();

        if (!colorScale[colormap]) {
            throw Error(colormap + ' not a supported colorscale');
        }

        cmap = colorScale[colormap];

    } else if (Array.isArray(colormap)) {
        cmap = colormap.slice();

    } else {
        throw Error('unsupported colormap option', colormap);
    }

    if (cmap.length > nshades) {
        throw new Error(
            colormap+' map requires nshades to be at least size '+cmap.length
        );
    }

    if (!Array.isArray(spec.alpha)) {

        if (typeof spec.alpha === 'number') {
            alpha = [spec.alpha, spec.alpha];

        } else {
            alpha = [1, 1];
        }

    } else if (spec.alpha.length !== 2) {
        alpha = [1, 1];

    } else {
        alpha = spec.alpha.slice();
    }

    // map index points from 0..1 to 0..n-1
    indicies = cmap.map(function(c) {
        return Math.round(c.index * nshades);
    });

    // Add alpha channel to the map
    alpha[0] = Math.min(Math.max(alpha[0], 0), 1);
    alpha[1] = Math.min(Math.max(alpha[1], 0), 1);

    var steps = cmap.map(function(c, i) {
        var index = cmap[i].index

        var rgba = cmap[i].rgb.slice();

        // if user supplies their own map use it
        if (rgba.length === 4 && rgba[3] >= 0 && rgba[3] <= 1) {
            return rgba
        }
        rgba[3] = alpha[0] + (alpha[1] - alpha[0])*index;

        return rgba
    })


    /*
     * map increasing linear values between indicies to
     * linear steps in colorvalues
     */
    var colors = []
    for (i = 0; i < indicies.length-1; ++i) {
        nsteps = indicies[i+1] - indicies[i];
        fromrgba = steps[i];
        torgba = steps[i+1];

        for (var j = 0; j < nsteps; j++) {
            var amt = j / nsteps
            colors.push([
                Math.round(lerp(fromrgba[0], torgba[0], amt)),
                Math.round(lerp(fromrgba[1], torgba[1], amt)),
                Math.round(lerp(fromrgba[2], torgba[2], amt)),
                lerp(fromrgba[3], torgba[3], amt)
            ])
        }
    }

    //add 1 step as last value
    colors.push(cmap[cmap.length - 1].rgb.concat(alpha[1]))

    if (format === 'hex') colors = colors.map( rgb2hex );
    else if (format === 'rgbaString') colors = colors.map( rgbaStr );
    else if (format === 'float') colors = colors.map( rgb2float );

    return colors;
};

function rgb2float (rgba) {
    return [
        rgba[0] / 255,
        rgba[1] / 255,
        rgba[2] / 255,
        rgba[3]
    ]
}

function rgb2hex (rgba) {
    var dig, hex = '#';
    for (var i = 0; i < 3; ++i) {
        dig = rgba[i];
        dig = dig.toString(16);
        hex += ('00' + dig).substr( dig.length );
    }
    return hex;
}

function rgbaStr (rgba) {
    return 'rgba(' + rgba.join(',') + ')';
}

},{"./colorScale":114,"lerp":411}],116:[function(_dereq_,module,exports){
"use strict"

module.exports = compareAngle

var orient = _dereq_("robust-orientation")
var sgn = _dereq_("signum")
var twoSum = _dereq_("two-sum")
var robustProduct = _dereq_("robust-product")
var robustSum = _dereq_("robust-sum")

function testInterior(a, b, c) {
  var x0 = twoSum(a[0], -b[0])
  var y0 = twoSum(a[1], -b[1])
  var x1 = twoSum(c[0], -b[0])
  var y1 = twoSum(c[1], -b[1])

  var d = robustSum(
    robustProduct(x0, x1),
    robustProduct(y0, y1))

  return d[d.length-1] >= 0
}

function compareAngle(a, b, c, d) {
  var bcd = orient(b, c, d)
  if(bcd === 0) {
    //Handle degenerate cases
    var sabc = sgn(orient(a, b, c))
    var sabd = sgn(orient(a, b, d))
    if(sabc === sabd) {
      if(sabc === 0) {
        var ic = testInterior(a, b, c)
        var id = testInterior(a, b, d)
        if(ic === id) {
          return 0
        } else if(ic) {
          return 1
        } else {
          return -1
        }
      }
      return 0
    } else if(sabd === 0) {
      if(sabc > 0) {
        return -1
      } else if(testInterior(a, b, d)) {
        return -1
      } else {
        return 1
      }
    } else if(sabc === 0) {
      if(sabd > 0) {
        return 1
      } else if(testInterior(a, b, c)) {
        return 1
      } else {
        return -1
      }
    }
    return sgn(sabd - sabc)
  }
  var abc = orient(a, b, c)
  if(abc > 0) {
    if(bcd > 0 && orient(a, b, d) > 0) {
      return 1
    }
    return -1
  } else if(abc < 0) {
    if(bcd > 0 || orient(a, b, d) > 0) {
      return 1
    }
    return -1
  } else {
    var abd = orient(a, b, d)
    if(abd > 0) {
      return 1
    } else {
      if(testInterior(a, b, c)) {
        return 1
      } else {
        return -1
      }
    }
  }
}
},{"robust-orientation":488,"robust-product":489,"robust-sum":493,"signum":494,"two-sum":522}],117:[function(_dereq_,module,exports){
module.exports = compareCells

var min = Math.min

function compareInt(a, b) {
  return a - b
}

function compareCells(a, b) {
  var n = a.length
    , t = a.length - b.length
  if(t) {
    return t
  }
  switch(n) {
    case 0:
      return 0
    case 1:
      return a[0] - b[0]
    case 2:
      return (a[0]+a[1]-b[0]-b[1]) ||
             min(a[0],a[1]) - min(b[0],b[1])
    case 3:
      var l1 = a[0]+a[1]
        , m1 = b[0]+b[1]
      t = l1+a[2] - (m1+b[2])
      if(t) {
        return t
      }
      var l0 = min(a[0], a[1])
        , m0 = min(b[0], b[1])
      return min(l0, a[2]) - min(m0, b[2]) ||
             min(l0+a[2], l1) - min(m0+b[2], m1)
    case 4:
      var aw=a[0], ax=a[1], ay=a[2], az=a[3]
        , bw=b[0], bx=b[1], by=b[2], bz=b[3]
      return (aw+ax+ay+az)-(bw+bx+by+bz) ||
             min(aw,ax,ay,az)-min(bw,bx,by,bz,bw) ||
             min(aw+ax,aw+ay,aw+az,ax+ay,ax+az,ay+az) -
               min(bw+bx,bw+by,bw+bz,bx+by,bx+bz,by+bz) ||
             min(aw+ax+ay,aw+ax+az,aw+ay+az,ax+ay+az) -
               min(bw+bx+by,bw+bx+bz,bw+by+bz,bx+by+bz)
    default:
      var as = a.slice().sort(compareInt)
      var bs = b.slice().sort(compareInt)
      for(var i=0; i<n; ++i) {
        t = as[i] - bs[i]
        if(t) {
          return t
        }
      }
      return 0
  }
}

},{}],118:[function(_dereq_,module,exports){
'use strict'

var compareCells = _dereq_('compare-cell')
var parity = _dereq_('cell-orientation')

module.exports = compareOrientedCells

function compareOrientedCells(a, b) {
  return compareCells(a, b) || parity(a) - parity(b)
}

},{"cell-orientation":101,"compare-cell":117}],119:[function(_dereq_,module,exports){
"use strict"

var convexHull1d = _dereq_('./lib/ch1d')
var convexHull2d = _dereq_('./lib/ch2d')
var convexHullnd = _dereq_('./lib/chnd')

module.exports = convexHull

function convexHull(points) {
  var n = points.length
  if(n === 0) {
    return []
  } else if(n === 1) {
    return [[0]]
  }
  var d = points[0].length
  if(d === 0) {
    return []
  } else if(d === 1) {
    return convexHull1d(points)
  } else if(d === 2) {
    return convexHull2d(points)
  }
  return convexHullnd(points, d)
}
},{"./lib/ch1d":120,"./lib/ch2d":121,"./lib/chnd":122}],120:[function(_dereq_,module,exports){
"use strict"

module.exports = convexHull1d

function convexHull1d(points) {
  var lo = 0
  var hi = 0
  for(var i=1; i<points.length; ++i) {
    if(points[i][0] < points[lo][0]) {
      lo = i
    }
    if(points[i][0] > points[hi][0]) {
      hi = i
    }
  }
  if(lo < hi) {
    return [[lo], [hi]]
  } else if(lo > hi) {
    return [[hi], [lo]]
  } else {
    return [[lo]]
  }
}
},{}],121:[function(_dereq_,module,exports){
'use strict'

module.exports = convexHull2D

var monotoneHull = _dereq_('monotone-convex-hull-2d')

function convexHull2D(points) {
  var hull = monotoneHull(points)
  var h = hull.length
  if(h <= 2) {
    return []
  }
  var edges = new Array(h)
  var a = hull[h-1]
  for(var i=0; i<h; ++i) {
    var b = hull[i]
    edges[i] = [a,b]
    a = b
  }
  return edges
}

},{"monotone-convex-hull-2d":420}],122:[function(_dereq_,module,exports){
'use strict'

module.exports = convexHullnD

var ich = _dereq_('incremental-convex-hull')
var aff = _dereq_('affine-hull')

function permute(points, front) {
  var n = points.length
  var npoints = new Array(n)
  for(var i=0; i<front.length; ++i) {
    npoints[i] = points[front[i]]
  }
  var ptr = front.length
  for(var i=0; i<n; ++i) {
    if(front.indexOf(i) < 0) {
      npoints[ptr++] = points[i]
    }
  }
  return npoints
}

function invPermute(cells, front) {
  var nc = cells.length
  var nf = front.length
  for(var i=0; i<nc; ++i) {
    var c = cells[i]
    for(var j=0; j<c.length; ++j) {
      var x = c[j]
      if(x < nf) {
        c[j] = front[x]
      } else {
        x = x - nf
        for(var k=0; k<nf; ++k) {
          if(x >= front[k]) {
            x += 1
          }
        }
        c[j] = x
      }
    }
  }
  return cells
}

function convexHullnD(points, d) {
  try {
    return ich(points, true)
  } catch(e) {
    //If point set is degenerate, try to find a basis and rerun it
    var ah = aff(points)
    if(ah.length <= d) {
      //No basis, no try
      return []
    }
    var npoints = permute(points, ah)
    var nhull   = ich(npoints, true)
    return invPermute(nhull, ah)
  }
}
},{"affine-hull":51,"incremental-convex-hull":399}],123:[function(_dereq_,module,exports){
module.exports = {
  AFG: 'afghan',
  ALA: '\\b\\wland',
  ALB: 'albania',
  DZA: 'algeria',
  ASM: '^(?=.*americ).*samoa',
  AND: 'andorra',
  AGO: 'angola',
  AIA: 'anguill?a',
  ATA: 'antarctica',
  ATG: 'antigua',
  ARG: 'argentin',
  ARM: 'armenia',
  ABW: '^(?!.*bonaire).*\\baruba',
  AUS: 'australia',
  AUT: '^(?!.*hungary).*austria|\\baustri.*\\bemp',
  AZE: 'azerbaijan',
  BHS: 'bahamas',
  BHR: 'bahrain',
  BGD: 'bangladesh|^(?=.*east).*paki?stan',
  BRB: 'barbados',
  BLR: 'belarus|byelo',
  BEL: '^(?!.*luxem).*belgium',
  BLZ: 'belize|^(?=.*british).*honduras',
  BEN: 'benin|dahome',
  BMU: 'bermuda',
  BTN: 'bhutan',
  BOL: 'bolivia',
  BES: '^(?=.*bonaire).*eustatius|^(?=.*carib).*netherlands|\\bbes.?islands',
  BIH: 'herzegovina|bosnia',
  BWA: 'botswana|bechuana',
  BVT: 'bouvet',
  BRA: 'brazil',
  IOT: 'british.?indian.?ocean',
  BRN: 'brunei',
  BGR: 'bulgaria',
  BFA: 'burkina|\\bfaso|upper.?volta',
  BDI: 'burundi',
  CPV: 'verde',
  KHM: 'cambodia|kampuchea|khmer',
  CMR: 'cameroon',
  CAN: 'canada',
  CYM: 'cayman',
  CAF: '\\bcentral.african.republic',
  TCD: '\\bchad',
  CHL: '\\bchile',
  CHN: '^(?!.*\\bmac)(?!.*\\bhong)(?!.*\\btai)(?!.*\\brep).*china|^(?=.*peo)(?=.*rep).*china',
  CXR: 'christmas',
  CCK: '\\bcocos|keeling',
  COL: 'colombia',
  COM: 'comoro',
  COG: '^(?!.*\\bdem)(?!.*\\bd[\\.]?r)(?!.*kinshasa)(?!.*zaire)(?!.*belg)(?!.*l.opoldville)(?!.*free).*\\bcongo',
  COK: '\\bcook',
  CRI: 'costa.?rica',
  CIV: 'ivoire|ivory',
  HRV: 'croatia',
  CUB: '\\bcuba',
  CUW: '^(?!.*bonaire).*\\bcura(c|ç)ao',
  CYP: 'cyprus',
  CSK: 'czechoslovakia',
  CZE: '^(?=.*rep).*czech|czechia|bohemia',
  COD: '\\bdem.*congo|congo.*\\bdem|congo.*\\bd[\\.]?r|\\bd[\\.]?r.*congo|belgian.?congo|congo.?free.?state|kinshasa|zaire|l.opoldville|drc|droc|rdc',
  DNK: 'denmark',
  DJI: 'djibouti',
  DMA: 'dominica(?!n)',
  DOM: 'dominican.rep',
  ECU: 'ecuador',
  EGY: 'egypt',
  SLV: 'el.?salvador',
  GNQ: 'guine.*eq|eq.*guine|^(?=.*span).*guinea',
  ERI: 'eritrea',
  EST: 'estonia',
  ETH: 'ethiopia|abyssinia',
  FLK: 'falkland|malvinas',
  FRO: 'faroe|faeroe',
  FJI: 'fiji',
  FIN: 'finland',
  FRA: '^(?!.*\\bdep)(?!.*martinique).*france|french.?republic|\\bgaul',
  GUF: '^(?=.*french).*guiana',
  PYF: 'french.?polynesia|tahiti',
  ATF: 'french.?southern',
  GAB: 'gabon',
  GMB: 'gambia',
  GEO: '^(?!.*south).*georgia',
  DDR: 'german.?democratic.?republic|democratic.?republic.*germany|east.germany',
  DEU: '^(?!.*east).*germany|^(?=.*\\bfed.*\\brep).*german',
  GHA: 'ghana|gold.?coast',
  GIB: 'gibraltar',
  GRC: 'greece|hellenic|hellas',
  GRL: 'greenland',
  GRD: 'grenada',
  GLP: 'guadeloupe',
  GUM: '\\bguam',
  GTM: 'guatemala',
  GGY: 'guernsey',
  GIN: '^(?!.*eq)(?!.*span)(?!.*bissau)(?!.*portu)(?!.*new).*guinea',
  GNB: 'bissau|^(?=.*portu).*guinea',
  GUY: 'guyana|british.?guiana',
  HTI: 'haiti',
  HMD: 'heard.*mcdonald',
  VAT: 'holy.?see|vatican|papal.?st',
  HND: '^(?!.*brit).*honduras',
  HKG: 'hong.?kong',
  HUN: '^(?!.*austr).*hungary',
  ISL: 'iceland',
  IND: 'india(?!.*ocea)',
  IDN: 'indonesia',
  IRN: '\\biran|persia',
  IRQ: '\\biraq|mesopotamia',
  IRL: '(^ireland)|(^republic.*ireland)',
  IMN: '^(?=.*isle).*\\bman',
  ISR: 'israel',
  ITA: 'italy',
  JAM: 'jamaica',
  JPN: 'japan',
  JEY: 'jersey',
  JOR: 'jordan',
  KAZ: 'kazak',
  KEN: 'kenya|british.?east.?africa|east.?africa.?prot',
  KIR: 'kiribati',
  PRK: '^(?=.*democrat|people|north|d.*p.*.r).*\\bkorea|dprk|korea.*(d.*p.*r)',
  KWT: 'kuwait',
  KGZ: 'kyrgyz|kirghiz',
  LAO: '\\blaos?\\b',
  LVA: 'latvia',
  LBN: 'lebanon',
  LSO: 'lesotho|basuto',
  LBR: 'liberia',
  LBY: 'libya',
  LIE: 'liechtenstein',
  LTU: 'lithuania',
  LUX: '^(?!.*belg).*luxem',
  MAC: 'maca(o|u)',
  MDG: 'madagascar|malagasy',
  MWI: 'malawi|nyasa',
  MYS: 'malaysia',
  MDV: 'maldive',
  MLI: '\\bmali\\b',
  MLT: '\\bmalta',
  MHL: 'marshall',
  MTQ: 'martinique',
  MRT: 'mauritania',
  MUS: 'mauritius',
  MYT: '\\bmayotte',
  MEX: '\\bmexic',
  FSM: 'fed.*micronesia|micronesia.*fed',
  MCO: 'monaco',
  MNG: 'mongolia',
  MNE: '^(?!.*serbia).*montenegro',
  MSR: 'montserrat',
  MAR: 'morocco|\\bmaroc',
  MOZ: 'mozambique',
  MMR: 'myanmar|burma',
  NAM: 'namibia',
  NRU: 'nauru',
  NPL: 'nepal',
  NLD: '^(?!.*\\bant)(?!.*\\bcarib).*netherlands',
  ANT: '^(?=.*\\bant).*(nether|dutch)',
  NCL: 'new.?caledonia',
  NZL: 'new.?zealand',
  NIC: 'nicaragua',
  NER: '\\bniger(?!ia)',
  NGA: 'nigeria',
  NIU: 'niue',
  NFK: 'norfolk',
  MNP: 'mariana',
  NOR: 'norway',
  OMN: '\\boman|trucial',
  PAK: '^(?!.*east).*paki?stan',
  PLW: 'palau',
  PSE: 'palestin|\\bgaza|west.?bank',
  PAN: 'panama',
  PNG: 'papua|new.?guinea',
  PRY: 'paraguay',
  PER: 'peru',
  PHL: 'philippines',
  PCN: 'pitcairn',
  POL: 'poland',
  PRT: 'portugal',
  PRI: 'puerto.?rico',
  QAT: 'qatar',
  KOR: '^(?!.*d.*p.*r)(?!.*democrat)(?!.*people)(?!.*north).*\\bkorea(?!.*d.*p.*r)',
  MDA: 'moldov|b(a|e)ssarabia',
  REU: 'r(e|é)union',
  ROU: 'r(o|u|ou)mania',
  RUS: '\\brussia|soviet.?union|u\\.?s\\.?s\\.?r|socialist.?republics',
  RWA: 'rwanda',
  BLM: 'barth(e|é)lemy',
  SHN: 'helena',
  KNA: 'kitts|\\bnevis',
  LCA: '\\blucia',
  MAF: '^(?=.*collectivity).*martin|^(?=.*france).*martin(?!ique)|^(?=.*french).*martin(?!ique)',
  SPM: 'miquelon',
  VCT: 'vincent',
  WSM: '^(?!.*amer).*samoa',
  SMR: 'san.?marino',
  STP: '\\bs(a|ã)o.?tom(e|é)',
  SAU: '\\bsa\\w*.?arabia',
  SEN: 'senegal',
  SRB: '^(?!.*monte).*serbia',
  SYC: 'seychell',
  SLE: 'sierra',
  SGP: 'singapore',
  SXM: '^(?!.*martin)(?!.*saba).*maarten',
  SVK: '^(?!.*cze).*slovak',
  SVN: 'slovenia',
  SLB: 'solomon',
  SOM: 'somali',
  ZAF: 'south.africa|s\\\\..?africa',
  SGS: 'south.?georgia|sandwich',
  SSD: '\\bs\\w*.?sudan',
  ESP: 'spain',
  LKA: 'sri.?lanka|ceylon',
  SDN: '^(?!.*\\bs(?!u)).*sudan',
  SUR: 'surinam|dutch.?guiana',
  SJM: 'svalbard',
  SWZ: 'swaziland',
  SWE: 'sweden',
  CHE: 'switz|swiss',
  SYR: 'syria',
  TWN: 'taiwan|taipei|formosa|^(?!.*peo)(?=.*rep).*china',
  TJK: 'tajik',
  THA: 'thailand|\\bsiam',
  MKD: 'macedonia|fyrom',
  TLS: '^(?=.*leste).*timor|^(?=.*east).*timor',
  TGO: 'togo',
  TKL: 'tokelau',
  TON: 'tonga',
  TTO: 'trinidad|tobago',
  TUN: 'tunisia',
  TUR: 'turkey',
  TKM: 'turkmen',
  TCA: 'turks',
  TUV: 'tuvalu',
  UGA: 'uganda',
  UKR: 'ukrain',
  ARE: 'emirates|^u\\.?a\\.?e\\.?$|united.?arab.?em',
  GBR: 'united.?kingdom|britain|^u\\.?k\\.?$',
  TZA: 'tanzania',
  USA: 'united.?states\\b(?!.*islands)|\\bu\\.?s\\.?a\\.?\\b|^\\s*u\\.?s\\.?\\b(?!.*islands)',
  UMI: 'minor.?outlying.?is',
  URY: 'uruguay',
  UZB: 'uzbek',
  VUT: 'vanuatu|new.?hebrides',
  VEN: 'venezuela',
  VNM: '^(?!.*republic).*viet.?nam|^(?=.*socialist).*viet.?nam',
  VGB: '^(?=.*\\bu\\.?\\s?k).*virgin|^(?=.*brit).*virgin|^(?=.*kingdom).*virgin',
  VIR: '^(?=.*\\bu\\.?\\s?s).*virgin|^(?=.*states).*virgin',
  WLF: 'futuna|wallis',
  ESH: 'western.sahara',
  YEM: '^(?!.*arab)(?!.*north)(?!.*sana)(?!.*peo)(?!.*dem)(?!.*south)(?!.*aden)(?!.*\\bp\\.?d\\.?r).*yemen',
  YMD: '^(?=.*peo).*yemen|^(?!.*rep)(?=.*dem).*yemen|^(?=.*south).*yemen|^(?=.*aden).*yemen|^(?=.*\\bp\\.?d\\.?r).*yemen',
  YUG: 'yugoslavia',
  ZMB: 'zambia|northern.?rhodesia',
  EAZ: 'zanzibar',
  ZWE: 'zimbabwe|^(?!.*northern).*rhodesia'
}

},{}],124:[function(_dereq_,module,exports){
module.exports=[
	"xx-small",
	"x-small",
	"small",
	"medium",
	"large",
	"x-large",
	"xx-large",
	"larger",
	"smaller"
]

},{}],125:[function(_dereq_,module,exports){
module.exports=[
	"normal",
	"condensed",
	"semi-condensed",
	"extra-condensed",
	"ultra-condensed",
	"expanded",
	"semi-expanded",
	"extra-expanded",
	"ultra-expanded"
]

},{}],126:[function(_dereq_,module,exports){
module.exports=[
	"normal",
	"italic",
	"oblique"
]

},{}],127:[function(_dereq_,module,exports){
module.exports=[
	"normal",
	"bold",
	"bolder",
	"lighter",
	"100",
	"200",
	"300",
	"400",
	"500",
	"600",
	"700",
	"800",
	"900"
]

},{}],128:[function(_dereq_,module,exports){
'use strict'

module.exports = {
	parse: _dereq_('./parse'),
	stringify: _dereq_('./stringify')
}

},{"./parse":130,"./stringify":131}],129:[function(_dereq_,module,exports){
'use strict'

var sizes = _dereq_('css-font-size-keywords')

module.exports = {
	isSize: function isSize(value) {
		return /^[\d\.]/.test(value)
			|| value.indexOf('/') !== -1
			|| sizes.indexOf(value) !== -1
	}
}

},{"css-font-size-keywords":124}],130:[function(_dereq_,module,exports){
'use strict'

var unquote = _dereq_('unquote')
var globalKeywords = _dereq_('css-global-keywords')
var systemFontKeywords = _dereq_('css-system-font-keywords')
var fontWeightKeywords = _dereq_('css-font-weight-keywords')
var fontStyleKeywords = _dereq_('css-font-style-keywords')
var fontStretchKeywords = _dereq_('css-font-stretch-keywords')
var splitBy = _dereq_('string-split-by')
var isSize = _dereq_('./lib/util').isSize


module.exports = parseFont


var cache = parseFont.cache = {}


function parseFont (value) {
	if (typeof value !== 'string') throw new Error('Font argument must be a string.')

	if (cache[value]) return cache[value]

	if (value === '') {
		throw new Error('Cannot parse an empty string.')
	}

	if (systemFontKeywords.indexOf(value) !== -1) {
		return cache[value] = {system: value}
	}

	var font = {
		style: 'normal',
		variant: 'normal',
		weight: 'normal',
		stretch: 'normal',
		lineHeight: 'normal',
		size: '1rem',
		family: ['serif']
	}

	var tokens = splitBy(value, /\s+/)
	var token

	while (token = tokens.shift()) {
		if (globalKeywords.indexOf(token) !== -1) {
			['style', 'variant', 'weight', 'stretch'].forEach(function(prop) {
				font[prop] = token
			})

			return cache[value] = font
		}

		if (fontStyleKeywords.indexOf(token) !== -1) {
			font.style = token
			continue
		}

		if (token === 'normal' || token === 'small-caps') {
			font.variant = token
			continue
		}

		if (fontStretchKeywords.indexOf(token) !== -1) {
			font.stretch = token
			continue
		}

		if (fontWeightKeywords.indexOf(token) !== -1) {
			font.weight = token
			continue
		}


		if (isSize(token)) {
			var parts = splitBy(token, '/')
			font.size = parts[0]
			if (parts[1] != null) {
				font.lineHeight = parseLineHeight(parts[1])
			}
			else if (tokens[0] === '/') {
				tokens.shift()
				font.lineHeight = parseLineHeight(tokens.shift())
 			}

			if (!tokens.length) {
				throw new Error('Missing required font-family.')
			}
			font.family = splitBy(tokens.join(' '), /\s*,\s*/).map(unquote)

			return cache[value] = font
		}

		throw new Error('Unknown or unsupported font token: ' + token)
	}

	throw new Error('Missing required font-size.')
}


function parseLineHeight(value) {
	var parsed = parseFloat(value)
	if (parsed.toString() === value) {
		return parsed
	}
	return value
}

},{"./lib/util":129,"css-font-stretch-keywords":125,"css-font-style-keywords":126,"css-font-weight-keywords":127,"css-global-keywords":132,"css-system-font-keywords":133,"string-split-by":507,"unquote":526}],131:[function(_dereq_,module,exports){
'use strict'

var pick = _dereq_('pick-by-alias')
var isSize = _dereq_('./lib/util').isSize

var globals = a2o(_dereq_('css-global-keywords'))
var systems = a2o(_dereq_('css-system-font-keywords'))
var weights = a2o(_dereq_('css-font-weight-keywords'))
var styles = a2o(_dereq_('css-font-style-keywords'))
var stretches = a2o(_dereq_('css-font-stretch-keywords'))

var variants = {'normal': 1, 'small-caps': 1}
var fams = {
	'serif': 1,
	'sans-serif': 1,
	'monospace': 1,
	'cursive': 1,
	'fantasy': 1,
	'system-ui': 1
}

var defaults = {
	style: 'normal',
	variant: 'normal',
	weight: 'normal',
	stretch: 'normal',
	size: '1rem',
	lineHeight: 'normal',
	family: 'serif'
}

module.exports = function stringifyFont (o) {
	o = pick(o, {
		style: 'style fontstyle fontStyle font-style slope distinction',
		variant: 'variant font-variant fontVariant fontvariant var capitalization',
		weight: 'weight w font-weight fontWeight fontweight',
		stretch: 'stretch font-stretch fontStretch fontstretch width',
		size: 'size s font-size fontSize fontsize height em emSize',
		lineHeight: 'lh line-height lineHeight lineheight leading',
		family: 'font family fontFamily font-family fontfamily type typeface face',
		system: 'system reserved default global',
	})

	if (o.system) {
		if (o.system) verify(o.system, systems)
		return o.system
	}

	verify(o.style, styles)
	verify(o.variant, variants)
	verify(o.weight, weights)
	verify(o.stretch, stretches)

	// default root value is medium, but by default it's inherited
	if (o.size == null) o.size = defaults.size
	if (typeof o.size === 'number') o.size += 'px'

	if (!isSize) throw Error('Bad size value `' + o.size + '`')

	// many user-agents use serif, we don't detect that for consistency
	if (!o.family) o.family = defaults.family
	if (Array.isArray(o.family)) {
		if (!o.family.length) o.family = [defaults.family]
		o.family = o.family.map(function (f) {
			return fams[f] ? f : '"' + f + '"'
		}).join(', ')
	}

	// [ [ <'font-style'> || <font-variant-css21> || <'font-weight'> || <'font-stretch'> ]? <'font-size'> [ / <'line-height'> ]? <'font-family'> ]
	var result = []

	result.push(o.style)
	if (o.variant !== o.style) result.push(o.variant)

	if (o.weight !== o.variant &&
		o.weight !== o.style) result.push(o.weight)

	if (o.stretch !== o.weight &&
		o.stretch !== o.variant &&
		o.stretch !== o.style) result.push(o.stretch)

	result.push(o.size + (o.lineHeight == null || o.lineHeight === 'normal' || (o.lineHeight + '' === '1')  ? '' : ('/' + o.lineHeight)))
	result.push(o.family)

	return result.filter(Boolean).join(' ')
}

function verify (value, values) {
	if (value && !values[value] && !globals[value]) throw Error('Unknown keyword `' + value +'`')

	return value
}


// ['a', 'b'] -> {a: true, b: true}
function a2o (a) {
	var o = {}
	for (var i = 0; i < a.length; i++) {
		o[a[i]] = 1
	}
	return o
}

},{"./lib/util":129,"css-font-stretch-keywords":125,"css-font-style-keywords":126,"css-font-weight-keywords":127,"css-global-keywords":132,"css-system-font-keywords":133,"pick-by-alias":451}],132:[function(_dereq_,module,exports){
module.exports=[
	"inherit",
	"initial",
	"unset"
]

},{}],133:[function(_dereq_,module,exports){
module.exports=[
	"caption",
	"icon",
	"menu",
	"message-box",
	"small-caption",
	"status-bar"
]

},{}],134:[function(_dereq_,module,exports){
"use strict"

function dcubicHermite(p0, v0, p1, v1, t, f) {
  var dh00 = 6*t*t-6*t,
      dh10 = 3*t*t-4*t + 1,
      dh01 = -6*t*t+6*t,
      dh11 = 3*t*t-2*t
  if(p0.length) {
    if(!f) {
      f = new Array(p0.length)
    }
    for(var i=p0.length-1; i>=0; --i) {
      f[i] = dh00*p0[i] + dh10*v0[i] + dh01*p1[i] + dh11*v1[i]
    }
    return f
  }
  return dh00*p0 + dh10*v0 + dh01*p1[i] + dh11*v1
}

function cubicHermite(p0, v0, p1, v1, t, f) {
  var ti  = (t-1), t2 = t*t, ti2 = ti*ti,
      h00 = (1+2*t)*ti2,
      h10 = t*ti2,
      h01 = t2*(3-2*t),
      h11 = t2*ti
  if(p0.length) {
    if(!f) {
      f = new Array(p0.length)
    }
    for(var i=p0.length-1; i>=0; --i) {
      f[i] = h00*p0[i] + h10*v0[i] + h01*p1[i] + h11*v1[i]
    }
    return f
  }
  return h00*p0 + h10*v0 + h01*p1 + h11*v1
}

module.exports = cubicHermite
module.exports.derivative = dcubicHermite
},{}],135:[function(_dereq_,module,exports){
"use strict"

var createThunk = _dereq_("./lib/thunk.js")

function Procedure() {
  this.argTypes = []
  this.shimArgs = []
  this.arrayArgs = []
  this.arrayBlockIndices = []
  this.scalarArgs = []
  this.offsetArgs = []
  this.offsetArgIndex = []
  this.indexArgs = []
  this.shapeArgs = []
  this.funcName = ""
  this.pre = null
  this.body = null
  this.post = null
  this.debug = false
}

function compileCwise(user_args) {
  //Create procedure
  var proc = new Procedure()
  
  //Parse blocks
  proc.pre    = user_args.pre
  proc.body   = user_args.body
  proc.post   = user_args.post

  //Parse arguments
  var proc_args = user_args.args.slice(0)
  proc.argTypes = proc_args
  for(var i=0; i<proc_args.length; ++i) {
    var arg_type = proc_args[i]
    if(arg_type === "array" || (typeof arg_type === "object" && arg_type.blockIndices)) {
      proc.argTypes[i] = "array"
      proc.arrayArgs.push(i)
      proc.arrayBlockIndices.push(arg_type.blockIndices ? arg_type.blockIndices : 0)
      proc.shimArgs.push("array" + i)
      if(i < proc.pre.args.length && proc.pre.args[i].count>0) {
        throw new Error("cwise: pre() block may not reference array args")
      }
      if(i < proc.post.args.length && proc.post.args[i].count>0) {
        throw new Error("cwise: post() block may not reference array args")
      }
    } else if(arg_type === "scalar") {
      proc.scalarArgs.push(i)
      proc.shimArgs.push("scalar" + i)
    } else if(arg_type === "index") {
      proc.indexArgs.push(i)
      if(i < proc.pre.args.length && proc.pre.args[i].count > 0) {
        throw new Error("cwise: pre() block may not reference array index")
      }
      if(i < proc.body.args.length && proc.body.args[i].lvalue) {
        throw new Error("cwise: body() block may not write to array index")
      }
      if(i < proc.post.args.length && proc.post.args[i].count > 0) {
        throw new Error("cwise: post() block may not reference array index")
      }
    } else if(arg_type === "shape") {
      proc.shapeArgs.push(i)
      if(i < proc.pre.args.length && proc.pre.args[i].lvalue) {
        throw new Error("cwise: pre() block may not write to array shape")
      }
      if(i < proc.body.args.length && proc.body.args[i].lvalue) {
        throw new Error("cwise: body() block may not write to array shape")
      }
      if(i < proc.post.args.length && proc.post.args[i].lvalue) {
        throw new Error("cwise: post() block may not write to array shape")
      }
    } else if(typeof arg_type === "object" && arg_type.offset) {
      proc.argTypes[i] = "offset"
      proc.offsetArgs.push({ array: arg_type.array, offset:arg_type.offset })
      proc.offsetArgIndex.push(i)
    } else {
      throw new Error("cwise: Unknown argument type " + proc_args[i])
    }
  }
  
  //Make sure at least one array argument was specified
  if(proc.arrayArgs.length <= 0) {
    throw new Error("cwise: No array arguments specified")
  }
  
  //Make sure arguments are correct
  if(proc.pre.args.length > proc_args.length) {
    throw new Error("cwise: Too many arguments in pre() block")
  }
  if(proc.body.args.length > proc_args.length) {
    throw new Error("cwise: Too many arguments in body() block")
  }
  if(proc.post.args.length > proc_args.length) {
    throw new Error("cwise: Too many arguments in post() block")
  }

  //Check debug flag
  proc.debug = !!user_args.printCode || !!user_args.debug
  
  //Retrieve name
  proc.funcName = user_args.funcName || "cwise"
  
  //Read in block size
  proc.blockSize = user_args.blockSize || 64

  return createThunk(proc)
}

module.exports = compileCwise

},{"./lib/thunk.js":137}],136:[function(_dereq_,module,exports){
"use strict"

var uniq = _dereq_("uniq")

// This function generates very simple loops analogous to how you typically traverse arrays (the outermost loop corresponds to the slowest changing index, the innermost loop to the fastest changing index)
// TODO: If two arrays have the same strides (and offsets) there is potential for decreasing the number of "pointers" and related variables. The drawback is that the type signature would become more specific and that there would thus be less potential for caching, but it might still be worth it, especially when dealing with large numbers of arguments.
function innerFill(order, proc, body) {
  var dimension = order.length
    , nargs = proc.arrayArgs.length
    , has_index = proc.indexArgs.length>0
    , code = []
    , vars = []
    , idx=0, pidx=0, i, j
  for(i=0; i<dimension; ++i) { // Iteration variables
    vars.push(["i",i,"=0"].join(""))
  }
  //Compute scan deltas
  for(j=0; j<nargs; ++j) {
    for(i=0; i<dimension; ++i) {
      pidx = idx
      idx = order[i]
      if(i === 0) { // The innermost/fastest dimension's delta is simply its stride
        vars.push(["d",j,"s",i,"=t",j,"p",idx].join(""))
      } else { // For other dimensions the delta is basically the stride minus something which essentially "rewinds" the previous (more inner) dimension
        vars.push(["d",j,"s",i,"=(t",j,"p",idx,"-s",pidx,"*t",j,"p",pidx,")"].join(""))
      }
    }
  }
  if (vars.length > 0) {
    code.push("var " + vars.join(","))
  }  
  //Scan loop
  for(i=dimension-1; i>=0; --i) { // Start at largest stride and work your way inwards
    idx = order[i]
    code.push(["for(i",i,"=0;i",i,"<s",idx,";++i",i,"){"].join(""))
  }
  //Push body of inner loop
  code.push(body)
  //Advance scan pointers
  for(i=0; i<dimension; ++i) {
    pidx = idx
    idx = order[i]
    for(j=0; j<nargs; ++j) {
      code.push(["p",j,"+=d",j,"s",i].join(""))
    }
    if(has_index) {
      if(i > 0) {
        code.push(["index[",pidx,"]-=s",pidx].join(""))
      }
      code.push(["++index[",idx,"]"].join(""))
    }
    code.push("}")
  }
  return code.join("\n")
}

// Generate "outer" loops that loop over blocks of data, applying "inner" loops to the blocks by manipulating the local variables in such a way that the inner loop only "sees" the current block.
// TODO: If this is used, then the previous declaration (done by generateCwiseOp) of s* is essentially unnecessary.
//       I believe the s* are not used elsewhere (in particular, I don't think they're used in the pre/post parts and "shape" is defined independently), so it would be possible to make defining the s* dependent on what loop method is being used.
function outerFill(matched, order, proc, body) {
  var dimension = order.length
    , nargs = proc.arrayArgs.length
    , blockSize = proc.blockSize
    , has_index = proc.indexArgs.length > 0
    , code = []
  for(var i=0; i<nargs; ++i) {
    code.push(["var offset",i,"=p",i].join(""))
  }
  //Generate loops for unmatched dimensions
  // The order in which these dimensions are traversed is fairly arbitrary (from small stride to large stride, for the first argument)
  // TODO: It would be nice if the order in which these loops are placed would also be somehow "optimal" (at the very least we should check that it really doesn't hurt us if they're not).
  for(var i=matched; i<dimension; ++i) {
    code.push(["for(var j"+i+"=SS[", order[i], "]|0;j", i, ">0;){"].join("")) // Iterate back to front
    code.push(["if(j",i,"<",blockSize,"){"].join("")) // Either decrease j by blockSize (s = blockSize), or set it to zero (after setting s = j).
    code.push(["s",order[i],"=j",i].join(""))
    code.push(["j",i,"=0"].join(""))
    code.push(["}else{s",order[i],"=",blockSize].join(""))
    code.push(["j",i,"-=",blockSize,"}"].join(""))
    if(has_index) {
      code.push(["index[",order[i],"]=j",i].join(""))
    }
  }
  for(var i=0; i<nargs; ++i) {
    var indexStr = ["offset"+i]
    for(var j=matched; j<dimension; ++j) {
      indexStr.push(["j",j,"*t",i,"p",order[j]].join(""))
    }
    code.push(["p",i,"=(",indexStr.join("+"),")"].join(""))
  }
  code.push(innerFill(order, proc, body))
  for(var i=matched; i<dimension; ++i) {
    code.push("}")
  }
  return code.join("\n")
}

//Count the number of compatible inner orders
// This is the length of the longest common prefix of the arrays in orders.
// Each array in orders lists the dimensions of the correspond ndarray in order of increasing stride.
// This is thus the maximum number of dimensions that can be efficiently traversed by simple nested loops for all arrays.
function countMatches(orders) {
  var matched = 0, dimension = orders[0].length
  while(matched < dimension) {
    for(var j=1; j<orders.length; ++j) {
      if(orders[j][matched] !== orders[0][matched]) {
        return matched
      }
    }
    ++matched
  }
  return matched
}

//Processes a block according to the given data types
// Replaces variable names by different ones, either "local" ones (that are then ferried in and out of the given array) or ones matching the arguments that the function performing the ultimate loop will accept.
function processBlock(block, proc, dtypes) {
  var code = block.body
  var pre = []
  var post = []
  for(var i=0; i<block.args.length; ++i) {
    var carg = block.args[i]
    if(carg.count <= 0) {
      continue
    }
    var re = new RegExp(carg.name, "g")
    var ptrStr = ""
    var arrNum = proc.arrayArgs.indexOf(i)
    switch(proc.argTypes[i]) {
      case "offset":
        var offArgIndex = proc.offsetArgIndex.indexOf(i)
        var offArg = proc.offsetArgs[offArgIndex]
        arrNum = offArg.array
        ptrStr = "+q" + offArgIndex // Adds offset to the "pointer" in the array
      case "array":
        ptrStr = "p" + arrNum + ptrStr
        var localStr = "l" + i
        var arrStr = "a" + arrNum
        if (proc.arrayBlockIndices[arrNum] === 0) { // Argument to body is just a single value from this array
          if(carg.count === 1) { // Argument/array used only once(?)
            if(dtypes[arrNum] === "generic") {
              if(carg.lvalue) {
                pre.push(["var ", localStr, "=", arrStr, ".get(", ptrStr, ")"].join("")) // Is this necessary if the argument is ONLY used as an lvalue? (keep in mind that we can have a += something, so we would actually need to check carg.rvalue)
                code = code.replace(re, localStr)
                post.push([arrStr, ".set(", ptrStr, ",", localStr,")"].join(""))
              } else {
                code = code.replace(re, [arrStr, ".get(", ptrStr, ")"].join(""))
              }
            } else {
              code = code.replace(re, [arrStr, "[", ptrStr, "]"].join(""))
            }
          } else if(dtypes[arrNum] === "generic") {
            pre.push(["var ", localStr, "=", arrStr, ".get(", ptrStr, ")"].join("")) // TODO: Could we optimize by checking for carg.rvalue?
            code = code.replace(re, localStr)
            if(carg.lvalue) {
              post.push([arrStr, ".set(", ptrStr, ",", localStr,")"].join(""))
            }
          } else {
            pre.push(["var ", localStr, "=", arrStr, "[", ptrStr, "]"].join("")) // TODO: Could we optimize by checking for carg.rvalue?
            code = code.replace(re, localStr)
            if(carg.lvalue) {
              post.push([arrStr, "[", ptrStr, "]=", localStr].join(""))
            }
          }
        } else { // Argument to body is a "block"
          var reStrArr = [carg.name], ptrStrArr = [ptrStr]
          for(var j=0; j<Math.abs(proc.arrayBlockIndices[arrNum]); j++) {
            reStrArr.push("\\s*\\[([^\\]]+)\\]")
            ptrStrArr.push("$" + (j+1) + "*t" + arrNum + "b" + j) // Matched index times stride
          }
          re = new RegExp(reStrArr.join(""), "g")
          ptrStr = ptrStrArr.join("+")
          if(dtypes[arrNum] === "generic") {
            /*if(carg.lvalue) {
              pre.push(["var ", localStr, "=", arrStr, ".get(", ptrStr, ")"].join("")) // Is this necessary if the argument is ONLY used as an lvalue? (keep in mind that we can have a += something, so we would actually need to check carg.rvalue)
              code = code.replace(re, localStr)
              post.push([arrStr, ".set(", ptrStr, ",", localStr,")"].join(""))
            } else {
              code = code.replace(re, [arrStr, ".get(", ptrStr, ")"].join(""))
            }*/
            throw new Error("cwise: Generic arrays not supported in combination with blocks!")
          } else {
            // This does not produce any local variables, even if variables are used multiple times. It would be possible to do so, but it would complicate things quite a bit.
            code = code.replace(re, [arrStr, "[", ptrStr, "]"].join(""))
          }
        }
      break
      case "scalar":
        code = code.replace(re, "Y" + proc.scalarArgs.indexOf(i))
      break
      case "index":
        code = code.replace(re, "index")
      break
      case "shape":
        code = code.replace(re, "shape")
      break
    }
  }
  return [pre.join("\n"), code, post.join("\n")].join("\n").trim()
}

function typeSummary(dtypes) {
  var summary = new Array(dtypes.length)
  var allEqual = true
  for(var i=0; i<dtypes.length; ++i) {
    var t = dtypes[i]
    var digits = t.match(/\d+/)
    if(!digits) {
      digits = ""
    } else {
      digits = digits[0]
    }
    if(t.charAt(0) === 0) {
      summary[i] = "u" + t.charAt(1) + digits
    } else {
      summary[i] = t.charAt(0) + digits
    }
    if(i > 0) {
      allEqual = allEqual && summary[i] === summary[i-1]
    }
  }
  if(allEqual) {
    return summary[0]
  }
  return summary.join("")
}

//Generates a cwise operator
function generateCWiseOp(proc, typesig) {

  //Compute dimension
  // Arrays get put first in typesig, and there are two entries per array (dtype and order), so this gets the number of dimensions in the first array arg.
  var dimension = (typesig[1].length - Math.abs(proc.arrayBlockIndices[0]))|0
  var orders = new Array(proc.arrayArgs.length)
  var dtypes = new Array(proc.arrayArgs.length)
  for(var i=0; i<proc.arrayArgs.length; ++i) {
    dtypes[i] = typesig[2*i]
    orders[i] = typesig[2*i+1]
  }
  
  //Determine where block and loop indices start and end
  var blockBegin = [], blockEnd = [] // These indices are exposed as blocks
  var loopBegin = [], loopEnd = [] // These indices are iterated over
  var loopOrders = [] // orders restricted to the loop indices
  for(var i=0; i<proc.arrayArgs.length; ++i) {
    if (proc.arrayBlockIndices[i]<0) {
      loopBegin.push(0)
      loopEnd.push(dimension)
      blockBegin.push(dimension)
      blockEnd.push(dimension+proc.arrayBlockIndices[i])
    } else {
      loopBegin.push(proc.arrayBlockIndices[i]) // Non-negative
      loopEnd.push(proc.arrayBlockIndices[i]+dimension)
      blockBegin.push(0)
      blockEnd.push(proc.arrayBlockIndices[i])
    }
    var newOrder = []
    for(var j=0; j<orders[i].length; j++) {
      if (loopBegin[i]<=orders[i][j] && orders[i][j]<loopEnd[i]) {
        newOrder.push(orders[i][j]-loopBegin[i]) // If this is a loop index, put it in newOrder, subtracting loopBegin, to make sure that all loopOrders are using a common set of indices.
      }
    }
    loopOrders.push(newOrder)
  }

  //First create arguments for procedure
  var arglist = ["SS"] // SS is the overall shape over which we iterate
  var code = ["'use strict'"]
  var vars = []
  
  for(var j=0; j<dimension; ++j) {
    vars.push(["s", j, "=SS[", j, "]"].join("")) // The limits for each dimension.
  }
  for(var i=0; i<proc.arrayArgs.length; ++i) {
    arglist.push("a"+i) // Actual data array
    arglist.push("t"+i) // Strides
    arglist.push("p"+i) // Offset in the array at which the data starts (also used for iterating over the data)
    
    for(var j=0; j<dimension; ++j) { // Unpack the strides into vars for looping
      vars.push(["t",i,"p",j,"=t",i,"[",loopBegin[i]+j,"]"].join(""))
    }
    
    for(var j=0; j<Math.abs(proc.arrayBlockIndices[i]); ++j) { // Unpack the strides into vars for block iteration
      vars.push(["t",i,"b",j,"=t",i,"[",blockBegin[i]+j,"]"].join(""))
    }
  }
  for(var i=0; i<proc.scalarArgs.length; ++i) {
    arglist.push("Y" + i)
  }
  if(proc.shapeArgs.length > 0) {
    vars.push("shape=SS.slice(0)") // Makes the shape over which we iterate available to the user defined functions (so you can use width/height for example)
  }
  if(proc.indexArgs.length > 0) {
    // Prepare an array to keep track of the (logical) indices, initialized to dimension zeroes.
    var zeros = new Array(dimension)
    for(var i=0; i<dimension; ++i) {
      zeros[i] = "0"
    }
    vars.push(["index=[", zeros.join(","), "]"].join(""))
  }
  for(var i=0; i<proc.offsetArgs.length; ++i) { // Offset arguments used for stencil operations
    var off_arg = proc.offsetArgs[i]
    var init_string = []
    for(var j=0; j<off_arg.offset.length; ++j) {
      if(off_arg.offset[j] === 0) {
        continue
      } else if(off_arg.offset[j] === 1) {
        init_string.push(["t", off_arg.array, "p", j].join(""))      
      } else {
        init_string.push([off_arg.offset[j], "*t", off_arg.array, "p", j].join(""))
      }
    }
    if(init_string.length === 0) {
      vars.push("q" + i + "=0")
    } else {
      vars.push(["q", i, "=", init_string.join("+")].join(""))
    }
  }

  //Prepare this variables
  var thisVars = uniq([].concat(proc.pre.thisVars)
                      .concat(proc.body.thisVars)
                      .concat(proc.post.thisVars))
  vars = vars.concat(thisVars)
  if (vars.length > 0) {
    code.push("var " + vars.join(","))
  }
  for(var i=0; i<proc.arrayArgs.length; ++i) {
    code.push("p"+i+"|=0")
  }
  
  //Inline prelude
  if(proc.pre.body.length > 3) {
    code.push(processBlock(proc.pre, proc, dtypes))
  }

  //Process body
  var body = processBlock(proc.body, proc, dtypes)
  var matched = countMatches(loopOrders)
  if(matched < dimension) {
    code.push(outerFill(matched, loopOrders[0], proc, body)) // TODO: Rather than passing loopOrders[0], it might be interesting to look at passing an order that represents the majority of the arguments for example.
  } else {
    code.push(innerFill(loopOrders[0], proc, body))
  }

  //Inline epilog
  if(proc.post.body.length > 3) {
    code.push(processBlock(proc.post, proc, dtypes))
  }
  
  if(proc.debug) {
    console.log("-----Generated cwise routine for ", typesig, ":\n" + code.join("\n") + "\n----------")
  }
  
  var loopName = [(proc.funcName||"unnamed"), "_cwise_loop_", orders[0].join("s"),"m",matched,typeSummary(dtypes)].join("")
  var f = new Function(["function ",loopName,"(", arglist.join(","),"){", code.join("\n"),"} return ", loopName].join(""))
  return f()
}
module.exports = generateCWiseOp

},{"uniq":525}],137:[function(_dereq_,module,exports){
"use strict"

// The function below is called when constructing a cwise function object, and does the following:
// A function object is constructed which accepts as argument a compilation function and returns another function.
// It is this other function that is eventually returned by createThunk, and this function is the one that actually
// checks whether a certain pattern of arguments has already been used before and compiles new loops as needed.
// The compilation passed to the first function object is used for compiling new functions.
// Once this function object is created, it is called with compile as argument, where the first argument of compile
// is bound to "proc" (essentially containing a preprocessed version of the user arguments to cwise).
// So createThunk roughly works like this:
// function createThunk(proc) {
//   var thunk = function(compileBound) {
//     var CACHED = {}
//     return function(arrays and scalars) {
//       if (dtype and order of arrays in CACHED) {
//         var func = CACHED[dtype and order of arrays]
//       } else {
//         var func = CACHED[dtype and order of arrays] = compileBound(dtype and order of arrays)
//       }
//       return func(arrays and scalars)
//     }
//   }
//   return thunk(compile.bind1(proc))
// }

var compile = _dereq_("./compile.js")

function createThunk(proc) {
  var code = ["'use strict'", "var CACHED={}"]
  var vars = []
  var thunkName = proc.funcName + "_cwise_thunk"
  
  //Build thunk
  code.push(["return function ", thunkName, "(", proc.shimArgs.join(","), "){"].join(""))
  var typesig = []
  var string_typesig = []
  var proc_args = [["array",proc.arrayArgs[0],".shape.slice(", // Slice shape so that we only retain the shape over which we iterate (which gets passed to the cwise operator as SS).
                    Math.max(0,proc.arrayBlockIndices[0]),proc.arrayBlockIndices[0]<0?(","+proc.arrayBlockIndices[0]+")"):")"].join("")]
  var shapeLengthConditions = [], shapeConditions = []
  // Process array arguments
  for(var i=0; i<proc.arrayArgs.length; ++i) {
    var j = proc.arrayArgs[i]
    vars.push(["t", j, "=array", j, ".dtype,",
               "r", j, "=array", j, ".order"].join(""))
    typesig.push("t" + j)
    typesig.push("r" + j)
    string_typesig.push("t"+j)
    string_typesig.push("r"+j+".join()")
    proc_args.push("array" + j + ".data")
    proc_args.push("array" + j + ".stride")
    proc_args.push("array" + j + ".offset|0")
    if (i>0) { // Gather conditions to check for shape equality (ignoring block indices)
      shapeLengthConditions.push("array" + proc.arrayArgs[0] + ".shape.length===array" + j + ".shape.length+" + (Math.abs(proc.arrayBlockIndices[0])-Math.abs(proc.arrayBlockIndices[i])))
      shapeConditions.push("array" + proc.arrayArgs[0] + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[0]) + "]===array" + j + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[i]) + "]")
    }
  }
  // Check for shape equality
  if (proc.arrayArgs.length > 1) {
    code.push("if (!(" + shapeLengthConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same dimensionality!')")
    code.push("for(var shapeIndex=array" + proc.arrayArgs[0] + ".shape.length-" + Math.abs(proc.arrayBlockIndices[0]) + "; shapeIndex-->0;) {")
    code.push("if (!(" + shapeConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same shape!')")
    code.push("}")
  }
  // Process scalar arguments
  for(var i=0; i<proc.scalarArgs.length; ++i) {
    proc_args.push("scalar" + proc.scalarArgs[i])
  }
  // Check for cached function (and if not present, generate it)
  vars.push(["type=[", string_typesig.join(","), "].join()"].join(""))
  vars.push("proc=CACHED[type]")
  code.push("var " + vars.join(","))
  
  code.push(["if(!proc){",
             "CACHED[type]=proc=compile([", typesig.join(","), "])}",
             "return proc(", proc_args.join(","), ")}"].join(""))

  if(proc.debug) {
    console.log("-----Generated thunk:\n" + code.join("\n") + "\n----------")
  }
  
  //Compile thunk
  var thunk = new Function("compile", code.join("\n"))
  return thunk(compile.bind(undefined, proc))
}

module.exports = createThunk

},{"./compile.js":136}],138:[function(_dereq_,module,exports){
module.exports = _dereq_("cwise-compiler")
},{"cwise-compiler":135}],139:[function(_dereq_,module,exports){
'use strict';

var copy             = _dereq_('es5-ext/object/copy')
  , normalizeOptions = _dereq_('es5-ext/object/normalize-options')
  , ensureCallable   = _dereq_('es5-ext/object/valid-callable')
  , map              = _dereq_('es5-ext/object/map')
  , callable         = _dereq_('es5-ext/object/valid-callable')
  , validValue       = _dereq_('es5-ext/object/valid-value')

  , bind = Function.prototype.bind, defineProperty = Object.defineProperty
  , hasOwnProperty = Object.prototype.hasOwnProperty
  , define;

define = function (name, desc, options) {
	var value = validValue(desc) && callable(desc.value), dgs;
	dgs = copy(desc);
	delete dgs.writable;
	delete dgs.value;
	dgs.get = function () {
		if (!options.overwriteDefinition && hasOwnProperty.call(this, name)) return value;
		desc.value = bind.call(value, options.resolveContext ? options.resolveContext(this) : this);
		defineProperty(this, name, desc);
		return this[name];
	};
	return dgs;
};

module.exports = function (props/*, options*/) {
	var options = normalizeOptions(arguments[1]);
	if (options.resolveContext != null) ensureCallable(options.resolveContext);
	return map(props, function (desc, name) { return define(name, desc, options); });
};

},{"es5-ext/object/copy":175,"es5-ext/object/map":184,"es5-ext/object/normalize-options":185,"es5-ext/object/valid-callable":189,"es5-ext/object/valid-value":191}],140:[function(_dereq_,module,exports){
'use strict';

var assign        = _dereq_('es5-ext/object/assign')
  , normalizeOpts = _dereq_('es5-ext/object/normalize-options')
  , isCallable    = _dereq_('es5-ext/object/is-callable')
  , contains      = _dereq_('es5-ext/string/#/contains')

  , d;

d = module.exports = function (dscr, value/*, options*/) {
	var c, e, w, options, desc;
	if ((arguments.length < 2) || (typeof dscr !== 'string')) {
		options = value;
		value = dscr;
		dscr = null;
	} else {
		options = arguments[2];
	}
	if (dscr == null) {
		c = w = true;
		e = false;
	} else {
		c = contains.call(dscr, 'c');
		e = contains.call(dscr, 'e');
		w = contains.call(dscr, 'w');
	}

	desc = { value: value, configurable: c, enumerable: e, writable: w };
	return !options ? desc : assign(normalizeOpts(options), desc);
};

d.gs = function (dscr, get, set/*, options*/) {
	var c, e, options, desc;
	if (typeof dscr !== 'string') {
		options = set;
		set = get;
		get = dscr;
		dscr = null;
	} else {
		options = arguments[3];
	}
	if (get == null) {
		get = undefined;
	} else if (!isCallable(get)) {
		options = get;
		get = set = undefined;
	} else if (set == null) {
		set = undefined;
	} else if (!isCallable(set)) {
		options = set;
		set = undefined;
	}
	if (dscr == null) {
		c = true;
		e = false;
	} else {
		c = contains.call(dscr, 'c');
		e = contains.call(dscr, 'e');
	}

	desc = { get: get, set: set, configurable: c, enumerable: e };
	return !options ? desc : assign(normalizeOpts(options), desc);
};

},{"es5-ext/object/assign":172,"es5-ext/object/is-callable":178,"es5-ext/object/normalize-options":185,"es5-ext/string/#/contains":192}],141:[function(_dereq_,module,exports){
// https://d3js.org/d3-array/ v1.2.4 Copyright 2018 Mike Bostock
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.d3 = global.d3 || {})));
}(this, (function (exports) { 'use strict';

function ascending(a, b) {
  return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}

function bisector(compare) {
  if (compare.length === 1) compare = ascendingComparator(compare);
  return {
    left: function(a, x, lo, hi) {
      if (lo == null) lo = 0;
      if (hi == null) hi = a.length;
      while (lo < hi) {
        var mid = lo + hi >>> 1;
        if (compare(a[mid], x) < 0) lo = mid + 1;
        else hi = mid;
      }
      return lo;
    },
    right: function(a, x, lo, hi) {
      if (lo == null) lo = 0;
      if (hi == null) hi = a.length;
      while (lo < hi) {
        var mid = lo + hi >>> 1;
        if (compare(a[mid], x) > 0) hi = mid;
        else lo = mid + 1;
      }
      return lo;
    }
  };
}

function ascendingComparator(f) {
  return function(d, x) {
    return ascending(f(d), x);
  };
}

var ascendingBisect = bisector(ascending);
var bisectRight = ascendingBisect.right;
var bisectLeft = ascendingBisect.left;

function pairs(array, f) {
  if (f == null) f = pair;
  var i = 0, n = array.length - 1, p = array[0], pairs = new Array(n < 0 ? 0 : n);
  while (i < n) pairs[i] = f(p, p = array[++i]);
  return pairs;
}

function pair(a, b) {
  return [a, b];
}

function cross(values0, values1, reduce) {
  var n0 = values0.length,
      n1 = values1.length,
      values = new Array(n0 * n1),
      i0,
      i1,
      i,
      value0;

  if (reduce == null) reduce = pair;

  for (i0 = i = 0; i0 < n0; ++i0) {
    for (value0 = values0[i0], i1 = 0; i1 < n1; ++i1, ++i) {
      values[i] = reduce(value0, values1[i1]);
    }
  }

  return values;
}

function descending(a, b) {
  return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
}

function number(x) {
  return x === null ? NaN : +x;
}

function variance(values, valueof) {
  var n = values.length,
      m = 0,
      i = -1,
      mean = 0,
      value,
      delta,
      sum = 0;

  if (valueof == null) {
    while (++i < n) {
      if (!isNaN(value = number(values[i]))) {
        delta = value - mean;
        mean += delta / ++m;
        sum += delta * (value - mean);
      }
    }
  }

  else {
    while (++i < n) {
      if (!isNaN(value = number(valueof(values[i], i, values)))) {
        delta = value - mean;
        mean += delta / ++m;
        sum += delta * (value - mean);
      }
    }
  }

  if (m > 1) return sum / (m - 1);
}

function deviation(array, f) {
  var v = variance(array, f);
  return v ? Math.sqrt(v) : v;
}

function extent(values, valueof) {
  var n = values.length,
      i = -1,
      value,
      min,
      max;

  if (valueof == null) {
    while (++i < n) { // Find the first comparable value.
      if ((value = values[i]) != null && value >= value) {
        min = max = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = values[i]) != null) {
            if (min > value) min = value;
            if (max < value) max = value;
          }
        }
      }
    }
  }

  else {
    while (++i < n) { // Find the first comparable value.
      if ((value = valueof(values[i], i, values)) != null && value >= value) {
        min = max = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = valueof(values[i], i, values)) != null) {
            if (min > value) min = value;
            if (max < value) max = value;
          }
        }
      }
    }
  }

  return [min, max];
}

var array = Array.prototype;

var slice = array.slice;
var map = array.map;

function constant(x) {
  return function() {
    return x;
  };
}

function identity(x) {
  return x;
}

function range(start, stop, step) {
  start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;

  var i = -1,
      n = Math.max(0, Math.ceil((stop - start) / step)) | 0,
      range = new Array(n);

  while (++i < n) {
    range[i] = start + i * step;
  }

  return range;
}

var e10 = Math.sqrt(50),
    e5 = Math.sqrt(10),
    e2 = Math.sqrt(2);

function ticks(start, stop, count) {
  var reverse,
      i = -1,
      n,
      ticks,
      step;

  stop = +stop, start = +start, count = +count;
  if (start === stop && count > 0) return [start];
  if (reverse = stop < start) n = start, start = stop, stop = n;
  if ((step = tickIncrement(start, stop, count)) === 0 || !isFinite(step)) return [];

  if (step > 0) {
    start = Math.ceil(start / step);
    stop = Math.floor(stop / step);
    ticks = new Array(n = Math.ceil(stop - start + 1));
    while (++i < n) ticks[i] = (start + i) * step;
  } else {
    start = Math.floor(start * step);
    stop = Math.ceil(stop * step);
    ticks = new Array(n = Math.ceil(start - stop + 1));
    while (++i < n) ticks[i] = (start - i) / step;
  }

  if (reverse) ticks.reverse();

  return ticks;
}

function tickIncrement(start, stop, count) {
  var step = (stop - start) / Math.max(0, count),
      power = Math.floor(Math.log(step) / Math.LN10),
      error = step / Math.pow(10, power);
  return power >= 0
      ? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power)
      : -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1);
}

function tickStep(start, stop, count) {
  var step0 = Math.abs(stop - start) / Math.max(0, count),
      step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)),
      error = step0 / step1;
  if (error >= e10) step1 *= 10;
  else if (error >= e5) step1 *= 5;
  else if (error >= e2) step1 *= 2;
  return stop < start ? -step1 : step1;
}

function sturges(values) {
  return Math.ceil(Math.log(values.length) / Math.LN2) + 1;
}

function histogram() {
  var value = identity,
      domain = extent,
      threshold = sturges;

  function histogram(data) {
    var i,
        n = data.length,
        x,
        values = new Array(n);

    for (i = 0; i < n; ++i) {
      values[i] = value(data[i], i, data);
    }

    var xz = domain(values),
        x0 = xz[0],
        x1 = xz[1],
        tz = threshold(values, x0, x1);

    // Convert number of thresholds into uniform thresholds.
    if (!Array.isArray(tz)) {
      tz = tickStep(x0, x1, tz);
      tz = range(Math.ceil(x0 / tz) * tz, x1, tz); // exclusive
    }

    // Remove any thresholds outside the domain.
    var m = tz.length;
    while (tz[0] <= x0) tz.shift(), --m;
    while (tz[m - 1] > x1) tz.pop(), --m;

    var bins = new Array(m + 1),
        bin;

    // Initialize bins.
    for (i = 0; i <= m; ++i) {
      bin = bins[i] = [];
      bin.x0 = i > 0 ? tz[i - 1] : x0;
      bin.x1 = i < m ? tz[i] : x1;
    }

    // Assign data to bins by value, ignoring any outside the domain.
    for (i = 0; i < n; ++i) {
      x = values[i];
      if (x0 <= x && x <= x1) {
        bins[bisectRight(tz, x, 0, m)].push(data[i]);
      }
    }

    return bins;
  }

  histogram.value = function(_) {
    return arguments.length ? (value = typeof _ === "function" ? _ : constant(_), histogram) : value;
  };

  histogram.domain = function(_) {
    return arguments.length ? (domain = typeof _ === "function" ? _ : constant([_[0], _[1]]), histogram) : domain;
  };

  histogram.thresholds = function(_) {
    return arguments.length ? (threshold = typeof _ === "function" ? _ : Array.isArray(_) ? constant(slice.call(_)) : constant(_), histogram) : threshold;
  };

  return histogram;
}

function quantile(values, p, valueof) {
  if (valueof == null) valueof = number;
  if (!(n = values.length)) return;
  if ((p = +p) <= 0 || n < 2) return +valueof(values[0], 0, values);
  if (p >= 1) return +valueof(values[n - 1], n - 1, values);
  var n,
      i = (n - 1) * p,
      i0 = Math.floor(i),
      value0 = +valueof(values[i0], i0, values),
      value1 = +valueof(values[i0 + 1], i0 + 1, values);
  return value0 + (value1 - value0) * (i - i0);
}

function freedmanDiaconis(values, min, max) {
  values = map.call(values, number).sort(ascending);
  return Math.ceil((max - min) / (2 * (quantile(values, 0.75) - quantile(values, 0.25)) * Math.pow(values.length, -1 / 3)));
}

function scott(values, min, max) {
  return Math.ceil((max - min) / (3.5 * deviation(values) * Math.pow(values.length, -1 / 3)));
}

function max(values, valueof) {
  var n = values.length,
      i = -1,
      value,
      max;

  if (valueof == null) {
    while (++i < n) { // Find the first comparable value.
      if ((value = values[i]) != null && value >= value) {
        max = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = values[i]) != null && value > max) {
            max = value;
          }
        }
      }
    }
  }

  else {
    while (++i < n) { // Find the first comparable value.
      if ((value = valueof(values[i], i, values)) != null && value >= value) {
        max = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = valueof(values[i], i, values)) != null && value > max) {
            max = value;
          }
        }
      }
    }
  }

  return max;
}

function mean(values, valueof) {
  var n = values.length,
      m = n,
      i = -1,
      value,
      sum = 0;

  if (valueof == null) {
    while (++i < n) {
      if (!isNaN(value = number(values[i]))) sum += value;
      else --m;
    }
  }

  else {
    while (++i < n) {
      if (!isNaN(value = number(valueof(values[i], i, values)))) sum += value;
      else --m;
    }
  }

  if (m) return sum / m;
}

function median(values, valueof) {
  var n = values.length,
      i = -1,
      value,
      numbers = [];

  if (valueof == null) {
    while (++i < n) {
      if (!isNaN(value = number(values[i]))) {
        numbers.push(value);
      }
    }
  }

  else {
    while (++i < n) {
      if (!isNaN(value = number(valueof(values[i], i, values)))) {
        numbers.push(value);
      }
    }
  }

  return quantile(numbers.sort(ascending), 0.5);
}

function merge(arrays) {
  var n = arrays.length,
      m,
      i = -1,
      j = 0,
      merged,
      array;

  while (++i < n) j += arrays[i].length;
  merged = new Array(j);

  while (--n >= 0) {
    array = arrays[n];
    m = array.length;
    while (--m >= 0) {
      merged[--j] = array[m];
    }
  }

  return merged;
}

function min(values, valueof) {
  var n = values.length,
      i = -1,
      value,
      min;

  if (valueof == null) {
    while (++i < n) { // Find the first comparable value.
      if ((value = values[i]) != null && value >= value) {
        min = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = values[i]) != null && min > value) {
            min = value;
          }
        }
      }
    }
  }

  else {
    while (++i < n) { // Find the first comparable value.
      if ((value = valueof(values[i], i, values)) != null && value >= value) {
        min = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = valueof(values[i], i, values)) != null && min > value) {
            min = value;
          }
        }
      }
    }
  }

  return min;
}

function permute(array, indexes) {
  var i = indexes.length, permutes = new Array(i);
  while (i--) permutes[i] = array[indexes[i]];
  return permutes;
}

function scan(values, compare) {
  if (!(n = values.length)) return;
  var n,
      i = 0,
      j = 0,
      xi,
      xj = values[j];

  if (compare == null) compare = ascending;

  while (++i < n) {
    if (compare(xi = values[i], xj) < 0 || compare(xj, xj) !== 0) {
      xj = xi, j = i;
    }
  }

  if (compare(xj, xj) === 0) return j;
}

function shuffle(array, i0, i1) {
  var m = (i1 == null ? array.length : i1) - (i0 = i0 == null ? 0 : +i0),
      t,
      i;

  while (m) {
    i = Math.random() * m-- | 0;
    t = array[m + i0];
    array[m + i0] = array[i + i0];
    array[i + i0] = t;
  }

  return array;
}

function sum(values, valueof) {
  var n = values.length,
      i = -1,
      value,
      sum = 0;

  if (valueof == null) {
    while (++i < n) {
      if (value = +values[i]) sum += value; // Note: zero and null are equivalent.
    }
  }

  else {
    while (++i < n) {
      if (value = +valueof(values[i], i, values)) sum += value;
    }
  }

  return sum;
}

function transpose(matrix) {
  if (!(n = matrix.length)) return [];
  for (var i = -1, m = min(matrix, length), transpose = new Array(m); ++i < m;) {
    for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n;) {
      row[j] = matrix[j][i];
    }
  }
  return transpose;
}

function length(d) {
  return d.length;
}

function zip() {
  return transpose(arguments);
}

exports.bisect = bisectRight;
exports.bisectRight = bisectRight;
exports.bisectLeft = bisectLeft;
exports.ascending = ascending;
exports.bisector = bisector;
exports.cross = cross;
exports.descending = descending;
exports.deviation = deviation;
exports.extent = extent;
exports.histogram = histogram;
exports.thresholdFreedmanDiaconis = freedmanDiaconis;
exports.thresholdScott = scott;
exports.thresholdSturges = sturges;
exports.max = max;
exports.mean = mean;
exports.median = median;
exports.merge = merge;
exports.min = min;
exports.pairs = pairs;
exports.permute = permute;
exports.quantile = quantile;
exports.range = range;
exports.scan = scan;
exports.shuffle = shuffle;
exports.sum = sum;
exports.ticks = ticks;
exports.tickIncrement = tickIncrement;
exports.tickStep = tickStep;
exports.transpose = transpose;
exports.variance = variance;
exports.zip = zip;

Object.defineProperty(exports, '__esModule', { value: true });

})));

},{}],142:[function(_dereq_,module,exports){
// https://d3js.org/d3-collection/ Version 1.0.4. Copyright 2017 Mike Bostock.
(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
	typeof define === 'function' && define.amd ? define(['exports'], factory) :
	(factory((global.d3 = global.d3 || {})));
}(this, (function (exports) { 'use strict';

var prefix = "$";

function Map() {}

Map.prototype = map.prototype = {
  constructor: Map,
  has: function(key) {
    return (prefix + key) in this;
  },
  get: function(key) {
    return this[prefix + key];
  },
  set: function(key, value) {
    this[prefix + key] = value;
    return this;
  },
  remove: function(key) {
    var property = prefix + key;
    return property in this && delete this[property];
  },
  clear: function() {
    for (var property in this) if (property[0] === prefix) delete this[property];
  },
  keys: function() {
    var keys = [];
    for (var property in this) if (property[0] === prefix) keys.push(property.slice(1));
    return keys;
  },
  values: function() {
    var values = [];
    for (var property in this) if (property[0] === prefix) values.push(this[property]);
    return values;
  },
  entries: function() {
    var entries = [];
    for (var property in this) if (property[0] === prefix) entries.push({key: property.slice(1), value: this[property]});
    return entries;
  },
  size: function() {
    var size = 0;
    for (var property in this) if (property[0] === prefix) ++size;
    return size;
  },
  empty: function() {
    for (var property in this) if (property[0] === prefix) return false;
    return true;
  },
  each: function(f) {
    for (var property in this) if (property[0] === prefix) f(this[property], property.slice(1), this);
  }
};

function map(object, f) {
  var map = new Map;

  // Copy constructor.
  if (object instanceof Map) object.each(function(value, key) { map.set(key, value); });

  // Index array by numeric index or specified key function.
  else if (Array.isArray(object)) {
    var i = -1,
        n = object.length,
        o;

    if (f == null) while (++i < n) map.set(i, object[i]);
    else while (++i < n) map.set(f(o = object[i], i, object), o);
  }

  // Convert object to map.
  else if (object) for (var key in object) map.set(key, object[key]);

  return map;
}

var nest = function() {
  var keys = [],
      sortKeys = [],
      sortValues,
      rollup,
      nest;

  function apply(array, depth, createResult, setResult) {
    if (depth >= keys.length) {
      if (sortValues != null) array.sort(sortValues);
      return rollup != null ? rollup(array) : array;
    }

    var i = -1,
        n = array.length,
        key = keys[depth++],
        keyValue,
        value,
        valuesByKey = map(),
        values,
        result = createResult();

    while (++i < n) {
      if (values = valuesByKey.get(keyValue = key(value = array[i]) + "")) {
        values.push(value);
      } else {
        valuesByKey.set(keyValue, [value]);
      }
    }

    valuesByKey.each(function(values, key) {
      setResult(result, key, apply(values, depth, createResult, setResult));
    });

    return result;
  }

  function entries(map$$1, depth) {
    if (++depth > keys.length) return map$$1;
    var array, sortKey = sortKeys[depth - 1];
    if (rollup != null && depth >= keys.length) array = map$$1.entries();
    else array = [], map$$1.each(function(v, k) { array.push({key: k, values: entries(v, depth)}); });
    return sortKey != null ? array.sort(function(a, b) { return sortKey(a.key, b.key); }) : array;
  }

  return nest = {
    object: function(array) { return apply(array, 0, createObject, setObject); },
    map: function(array) { return apply(array, 0, createMap, setMap); },
    entries: function(array) { return entries(apply(array, 0, createMap, setMap), 0); },
    key: function(d) { keys.push(d); return nest; },
    sortKeys: function(order) { sortKeys[keys.length - 1] = order; return nest; },
    sortValues: function(order) { sortValues = order; return nest; },
    rollup: function(f) { rollup = f; return nest; }
  };
};

function createObject() {
  return {};
}

function setObject(object, key, value) {
  object[key] = value;
}

function createMap() {
  return map();
}

function setMap(map$$1, key, value) {
  map$$1.set(key, value);
}

function Set() {}

var proto = map.prototype;

Set.prototype = set.prototype = {
  constructor: Set,
  has: proto.has,
  add: function(value) {
    value += "";
    this[prefix + value] = value;
    return this;
  },
  remove: proto.remove,
  clear: proto.clear,
  values: proto.keys,
  size: proto.size,
  empty: proto.empty,
  each: proto.each
};

function set(object, f) {
  var set = new Set;

  // Copy constructor.
  if (object instanceof Set) object.each(function(value) { set.add(value); });

  // Otherwise, assume it’s an array.
  else if (object) {
    var i = -1, n = object.length;
    if (f == null) while (++i < n) set.add(object[i]);
    else while (++i < n) set.add(f(object[i], i, object));
  }

  return set;
}

var keys = function(map) {
  var keys = [];
  for (var key in map) keys.push(key);
  return keys;
};

var values = function(map) {
  var values = [];
  for (var key in map) values.push(map[key]);
  return values;
};

var entries = function(map) {
  var entries = [];
  for (var key in map) entries.push({key: key, value: map[key]});
  return entries;
};

exports.nest = nest;
exports.set = set;
exports.map = map;
exports.keys = keys;
exports.values = values;
exports.entries = entries;

Object.defineProperty(exports, '__esModule', { value: true });

})));

},{}],143:[function(_dereq_,module,exports){
// https://d3js.org/d3-color/ v1.2.3 Copyright 2018 Mike Bostock
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.d3 = global.d3 || {})));
}(this, (function (exports) { 'use strict';

function define(constructor, factory, prototype) {
  constructor.prototype = factory.prototype = prototype;
  prototype.constructor = constructor;
}

function extend(parent, definition) {
  var prototype = Object.create(parent.prototype);
  for (var key in definition) prototype[key] = definition[key];
  return prototype;
}

function Color() {}

var darker = 0.7;
var brighter = 1 / darker;

var reI = "\\s*([+-]?\\d+)\\s*",
    reN = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",
    reP = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",
    reHex3 = /^#([0-9a-f]{3})$/,
    reHex6 = /^#([0-9a-f]{6})$/,
    reRgbInteger = new RegExp("^rgb\\(" + [reI, reI, reI] + "\\)$"),
    reRgbPercent = new RegExp("^rgb\\(" + [reP, reP, reP] + "\\)$"),
    reRgbaInteger = new RegExp("^rgba\\(" + [reI, reI, reI, reN] + "\\)$"),
    reRgbaPercent = new RegExp("^rgba\\(" + [reP, reP, reP, reN] + "\\)$"),
    reHslPercent = new RegExp("^hsl\\(" + [reN, reP, reP] + "\\)$"),
    reHslaPercent = new RegExp("^hsla\\(" + [reN, reP, reP, reN] + "\\)$");

var named = {
  aliceblue: 0xf0f8ff,
  antiquewhite: 0xfaebd7,
  aqua: 0x00ffff,
  aquamarine: 0x7fffd4,
  azure: 0xf0ffff,
  beige: 0xf5f5dc,
  bisque: 0xffe4c4,
  black: 0x000000,
  blanchedalmond: 0xffebcd,
  blue: 0x0000ff,
  blueviolet: 0x8a2be2,
  brown: 0xa52a2a,
  burlywood: 0xdeb887,
  cadetblue: 0x5f9ea0,
  chartreuse: 0x7fff00,
  chocolate: 0xd2691e,
  coral: 0xff7f50,
  cornflowerblue: 0x6495ed,
  cornsilk: 0xfff8dc,
  crimson: 0xdc143c,
  cyan: 0x00ffff,
  darkblue: 0x00008b,
  darkcyan: 0x008b8b,
  darkgoldenrod: 0xb8860b,
  darkgray: 0xa9a9a9,
  darkgreen: 0x006400,
  darkgrey: 0xa9a9a9,
  darkkhaki: 0xbdb76b,
  darkmagenta: 0x8b008b,
  darkolivegreen: 0x556b2f,
  darkorange: 0xff8c00,
  darkorchid: 0x9932cc,
  darkred: 0x8b0000,
  darksalmon: 0xe9967a,
  darkseagreen: 0x8fbc8f,
  darkslateblue: 0x483d8b,
  darkslategray: 0x2f4f4f,
  darkslategrey: 0x2f4f4f,
  darkturquoise: 0x00ced1,
  darkviolet: 0x9400d3,
  deeppink: 0xff1493,
  deepskyblue: 0x00bfff,
  dimgray: 0x696969,
  dimgrey: 0x696969,
  dodgerblue: 0x1e90ff,
  firebrick: 0xb22222,
  floralwhite: 0xfffaf0,
  forestgreen: 0x228b22,
  fuchsia: 0xff00ff,
  gainsboro: 0xdcdcdc,
  ghostwhite: 0xf8f8ff,
  gold: 0xffd700,
  goldenrod: 0xdaa520,
  gray: 0x808080,
  green: 0x008000,
  greenyellow: 0xadff2f,
  grey: 0x808080,
  honeydew: 0xf0fff0,
  hotpink: 0xff69b4,
  indianred: 0xcd5c5c,
  indigo: 0x4b0082,
  ivory: 0xfffff0,
  khaki: 0xf0e68c,
  lavender: 0xe6e6fa,
  lavenderblush: 0xfff0f5,
  lawngreen: 0x7cfc00,
  lemonchiffon: 0xfffacd,
  lightblue: 0xadd8e6,
  lightcoral: 0xf08080,
  lightcyan: 0xe0ffff,
  lightgoldenrodyellow: 0xfafad2,
  lightgray: 0xd3d3d3,
  lightgreen: 0x90ee90,
  lightgrey: 0xd3d3d3,
  lightpink: 0xffb6c1,
  lightsalmon: 0xffa07a,
  lightseagreen: 0x20b2aa,
  lightskyblue: 0x87cefa,
  lightslategray: 0x778899,
  lightslategrey: 0x778899,
  lightsteelblue: 0xb0c4de,
  lightyellow: 0xffffe0,
  lime: 0x00ff00,
  limegreen: 0x32cd32,
  linen: 0xfaf0e6,
  magenta: 0xff00ff,
  maroon: 0x800000,
  mediumaquamarine: 0x66cdaa,
  mediumblue: 0x0000cd,
  mediumorchid: 0xba55d3,
  mediumpurple: 0x9370db,
  mediumseagreen: 0x3cb371,
  mediumslateblue: 0x7b68ee,
  mediumspringgreen: 0x00fa9a,
  mediumturquoise: 0x48d1cc,
  mediumvioletred: 0xc71585,
  midnightblue: 0x191970,
  mintcream: 0xf5fffa,
  mistyrose: 0xffe4e1,
  moccasin: 0xffe4b5,
  navajowhite: 0xffdead,
  navy: 0x000080,
  oldlace: 0xfdf5e6,
  olive: 0x808000,
  olivedrab: 0x6b8e23,
  orange: 0xffa500,
  orangered: 0xff4500,
  orchid: 0xda70d6,
  palegoldenrod: 0xeee8aa,
  palegreen: 0x98fb98,
  paleturquoise: 0xafeeee,
  palevioletred: 0xdb7093,
  papayawhip: 0xffefd5,
  peachpuff: 0xffdab9,
  peru: 0xcd853f,
  pink: 0xffc0cb,
  plum: 0xdda0dd,
  powderblue: 0xb0e0e6,
  purple: 0x800080,
  rebeccapurple: 0x663399,
  red: 0xff0000,
  rosybrown: 0xbc8f8f,
  royalblue: 0x4169e1,
  saddlebrown: 0x8b4513,
  salmon: 0xfa8072,
  sandybrown: 0xf4a460,
  seagreen: 0x2e8b57,
  seashell: 0xfff5ee,
  sienna: 0xa0522d,
  silver: 0xc0c0c0,
  skyblue: 0x87ceeb,
  slateblue: 0x6a5acd,
  slategray: 0x708090,
  slategrey: 0x708090,
  snow: 0xfffafa,
  springgreen: 0x00ff7f,
  steelblue: 0x4682b4,
  tan: 0xd2b48c,
  teal: 0x008080,
  thistle: 0xd8bfd8,
  tomato: 0xff6347,
  turquoise: 0x40e0d0,
  violet: 0xee82ee,
  wheat: 0xf5deb3,
  white: 0xffffff,
  whitesmoke: 0xf5f5f5,
  yellow: 0xffff00,
  yellowgreen: 0x9acd32
};

define(Color, color, {
  displayable: function() {
    return this.rgb().displayable();
  },
  hex: function() {
    return this.rgb().hex();
  },
  toString: function() {
    return this.rgb() + "";
  }
});

function color(format) {
  var m;
  format = (format + "").trim().toLowerCase();
  return (m = reHex3.exec(format)) ? (m = parseInt(m[1], 16), new Rgb((m >> 8 & 0xf) | (m >> 4 & 0x0f0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1)) // #f00
      : (m = reHex6.exec(format)) ? rgbn(parseInt(m[1], 16)) // #ff0000
      : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)
      : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)
      : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)
      : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)
      : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)
      : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)
      : named.hasOwnProperty(format) ? rgbn(named[format])
      : format === "transparent" ? new Rgb(NaN, NaN, NaN, 0)
      : null;
}

function rgbn(n) {
  return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);
}

function rgba(r, g, b, a) {
  if (a <= 0) r = g = b = NaN;
  return new Rgb(r, g, b, a);
}

function rgbConvert(o) {
  if (!(o instanceof Color)) o = color(o);
  if (!o) return new Rgb;
  o = o.rgb();
  return new Rgb(o.r, o.g, o.b, o.opacity);
}

function rgb(r, g, b, opacity) {
  return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);
}

function Rgb(r, g, b, opacity) {
  this.r = +r;
  this.g = +g;
  this.b = +b;
  this.opacity = +opacity;
}

define(Rgb, rgb, extend(Color, {
  brighter: function(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  darker: function(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  rgb: function() {
    return this;
  },
  displayable: function() {
    return (0 <= this.r && this.r <= 255)
        && (0 <= this.g && this.g <= 255)
        && (0 <= this.b && this.b <= 255)
        && (0 <= this.opacity && this.opacity <= 1);
  },
  hex: function() {
    return "#" + hex(this.r) + hex(this.g) + hex(this.b);
  },
  toString: function() {
    var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
    return (a === 1 ? "rgb(" : "rgba(")
        + Math.max(0, Math.min(255, Math.round(this.r) || 0)) + ", "
        + Math.max(0, Math.min(255, Math.round(this.g) || 0)) + ", "
        + Math.max(0, Math.min(255, Math.round(this.b) || 0))
        + (a === 1 ? ")" : ", " + a + ")");
  }
}));

function hex(value) {
  value = Math.max(0, Math.min(255, Math.round(value) || 0));
  return (value < 16 ? "0" : "") + value.toString(16);
}

function hsla(h, s, l, a) {
  if (a <= 0) h = s = l = NaN;
  else if (l <= 0 || l >= 1) h = s = NaN;
  else if (s <= 0) h = NaN;
  return new Hsl(h, s, l, a);
}

function hslConvert(o) {
  if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);
  if (!(o instanceof Color)) o = color(o);
  if (!o) return new Hsl;
  if (o instanceof Hsl) return o;
  o = o.rgb();
  var r = o.r / 255,
      g = o.g / 255,
      b = o.b / 255,
      min = Math.min(r, g, b),
      max = Math.max(r, g, b),
      h = NaN,
      s = max - min,
      l = (max + min) / 2;
  if (s) {
    if (r === max) h = (g - b) / s + (g < b) * 6;
    else if (g === max) h = (b - r) / s + 2;
    else h = (r - g) / s + 4;
    s /= l < 0.5 ? max + min : 2 - max - min;
    h *= 60;
  } else {
    s = l > 0 && l < 1 ? 0 : h;
  }
  return new Hsl(h, s, l, o.opacity);
}

function hsl(h, s, l, opacity) {
  return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);
}

function Hsl(h, s, l, opacity) {
  this.h = +h;
  this.s = +s;
  this.l = +l;
  this.opacity = +opacity;
}

define(Hsl, hsl, extend(Color, {
  brighter: function(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  darker: function(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  rgb: function() {
    var h = this.h % 360 + (this.h < 0) * 360,
        s = isNaN(h) || isNaN(this.s) ? 0 : this.s,
        l = this.l,
        m2 = l + (l < 0.5 ? l : 1 - l) * s,
        m1 = 2 * l - m2;
    return new Rgb(
      hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),
      hsl2rgb(h, m1, m2),
      hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),
      this.opacity
    );
  },
  displayable: function() {
    return (0 <= this.s && this.s <= 1 || isNaN(this.s))
        && (0 <= this.l && this.l <= 1)
        && (0 <= this.opacity && this.opacity <= 1);
  }
}));

/* From FvD 13.37, CSS Color Module Level 3 */
function hsl2rgb(h, m1, m2) {
  return (h < 60 ? m1 + (m2 - m1) * h / 60
      : h < 180 ? m2
      : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60
      : m1) * 255;
}

var deg2rad = Math.PI / 180;
var rad2deg = 180 / Math.PI;

// https://beta.observablehq.com/@mbostock/lab-and-rgb
var K = 18,
    Xn = 0.96422,
    Yn = 1,
    Zn = 0.82521,
    t0 = 4 / 29,
    t1 = 6 / 29,
    t2 = 3 * t1 * t1,
    t3 = t1 * t1 * t1;

function labConvert(o) {
  if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity);
  if (o instanceof Hcl) {
    if (isNaN(o.h)) return new Lab(o.l, 0, 0, o.opacity);
    var h = o.h * deg2rad;
    return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity);
  }
  if (!(o instanceof Rgb)) o = rgbConvert(o);
  var r = rgb2lrgb(o.r),
      g = rgb2lrgb(o.g),
      b = rgb2lrgb(o.b),
      y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn), x, z;
  if (r === g && g === b) x = z = y; else {
    x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn);
    z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn);
  }
  return new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity);
}

function gray(l, opacity) {
  return new Lab(l, 0, 0, opacity == null ? 1 : opacity);
}

function lab(l, a, b, opacity) {
  return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity);
}

function Lab(l, a, b, opacity) {
  this.l = +l;
  this.a = +a;
  this.b = +b;
  this.opacity = +opacity;
}

define(Lab, lab, extend(Color, {
  brighter: function(k) {
    return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity);
  },
  darker: function(k) {
    return new Lab(this.l - K * (k == null ? 1 : k), this.a, this.b, this.opacity);
  },
  rgb: function() {
    var y = (this.l + 16) / 116,
        x = isNaN(this.a) ? y : y + this.a / 500,
        z = isNaN(this.b) ? y : y - this.b / 200;
    x = Xn * lab2xyz(x);
    y = Yn * lab2xyz(y);
    z = Zn * lab2xyz(z);
    return new Rgb(
      lrgb2rgb( 3.1338561 * x - 1.6168667 * y - 0.4906146 * z),
      lrgb2rgb(-0.9787684 * x + 1.9161415 * y + 0.0334540 * z),
      lrgb2rgb( 0.0719453 * x - 0.2289914 * y + 1.4052427 * z),
      this.opacity
    );
  }
}));

function xyz2lab(t) {
  return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;
}

function lab2xyz(t) {
  return t > t1 ? t * t * t : t2 * (t - t0);
}

function lrgb2rgb(x) {
  return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);
}

function rgb2lrgb(x) {
  return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
}

function hclConvert(o) {
  if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity);
  if (!(o instanceof Lab)) o = labConvert(o);
  if (o.a === 0 && o.b === 0) return new Hcl(NaN, 0, o.l, o.opacity);
  var h = Math.atan2(o.b, o.a) * rad2deg;
  return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity);
}

function lch(l, c, h, opacity) {
  return arguments.length === 1 ? hclConvert(l) : new Hcl(h, c, l, opacity == null ? 1 : opacity);
}

function hcl(h, c, l, opacity) {
  return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity);
}

function Hcl(h, c, l, opacity) {
  this.h = +h;
  this.c = +c;
  this.l = +l;
  this.opacity = +opacity;
}

define(Hcl, hcl, extend(Color, {
  brighter: function(k) {
    return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity);
  },
  darker: function(k) {
    return new Hcl(this.h, this.c, this.l - K * (k == null ? 1 : k), this.opacity);
  },
  rgb: function() {
    return labConvert(this).rgb();
  }
}));

var A = -0.14861,
    B = +1.78277,
    C = -0.29227,
    D = -0.90649,
    E = +1.97294,
    ED = E * D,
    EB = E * B,
    BC_DA = B * C - D * A;

function cubehelixConvert(o) {
  if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity);
  if (!(o instanceof Rgb)) o = rgbConvert(o);
  var r = o.r / 255,
      g = o.g / 255,
      b = o.b / 255,
      l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB),
      bl = b - l,
      k = (E * (g - l) - C * bl) / D,
      s = Math.sqrt(k * k + bl * bl) / (E * l * (1 - l)), // NaN if l=0 or l=1
      h = s ? Math.atan2(k, bl) * rad2deg - 120 : NaN;
  return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity);
}

function cubehelix(h, s, l, opacity) {
  return arguments.length === 1 ? cubehelixConvert(h) : new Cubehelix(h, s, l, opacity == null ? 1 : opacity);
}

function Cubehelix(h, s, l, opacity) {
  this.h = +h;
  this.s = +s;
  this.l = +l;
  this.opacity = +opacity;
}

define(Cubehelix, cubehelix, extend(Color, {
  brighter: function(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
  },
  darker: function(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
  },
  rgb: function() {
    var h = isNaN(this.h) ? 0 : (this.h + 120) * deg2rad,
        l = +this.l,
        a = isNaN(this.s) ? 0 : this.s * l * (1 - l),
        cosh = Math.cos(h),
        sinh = Math.sin(h);
    return new Rgb(
      255 * (l + a * (A * cosh + B * sinh)),
      255 * (l + a * (C * cosh + D * sinh)),
      255 * (l + a * (E * cosh)),
      this.opacity
    );
  }
}));

exports.color = color;
exports.rgb = rgb;
exports.hsl = hsl;
exports.lab = lab;
exports.hcl = hcl;
exports.lch = lch;
exports.gray = gray;
exports.cubehelix = cubehelix;

Object.defineProperty(exports, '__esModule', { value: true });

})));

},{}],144:[function(_dereq_,module,exports){
// https://d3js.org/d3-dispatch/ Version 1.0.3. Copyright 2017 Mike Bostock.
(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
	typeof define === 'function' && define.amd ? define(['exports'], factory) :
	(factory((global.d3 = global.d3 || {})));
}(this, (function (exports) { 'use strict';

var noop = {value: function() {}};

function dispatch() {
  for (var i = 0, n = arguments.length, _ = {}, t; i < n; ++i) {
    if (!(t = arguments[i] + "") || (t in _)) throw new Error("illegal type: " + t);
    _[t] = [];
  }
  return new Dispatch(_);
}

function Dispatch(_) {
  this._ = _;
}

function parseTypenames(typenames, types) {
  return typenames.trim().split(/^|\s+/).map(function(t) {
    var name = "", i = t.indexOf(".");
    if (i >= 0) name = t.slice(i + 1), t = t.slice(0, i);
    if (t && !types.hasOwnProperty(t)) throw new Error("unknown type: " + t);
    return {type: t, name: name};
  });
}

Dispatch.prototype = dispatch.prototype = {
  constructor: Dispatch,
  on: function(typename, callback) {
    var _ = this._,
        T = parseTypenames(typename + "", _),
        t,
        i = -1,
        n = T.length;

    // If no callback was specified, return the callback of the given type and name.
    if (arguments.length < 2) {
      while (++i < n) if ((t = (typename = T[i]).type) && (t = get(_[t], typename.name))) return t;
      return;
    }

    // If a type was specified, set the callback for the given type and name.
    // Otherwise, if a null callback was specified, remove callbacks of the given name.
    if (callback != null && typeof callback !== "function") throw new Error("invalid callback: " + callback);
    while (++i < n) {
      if (t = (typename = T[i]).type) _[t] = set(_[t], typename.name, callback);
      else if (callback == null) for (t in _) _[t] = set(_[t], typename.name, null);
    }

    return this;
  },
  copy: function() {
    var copy = {}, _ = this._;
    for (var t in _) copy[t] = _[t].slice();
    return new Dispatch(copy);
  },
  call: function(type, that) {
    if ((n = arguments.length - 2) > 0) for (var args = new Array(n), i = 0, n, t; i < n; ++i) args[i] = arguments[i + 2];
    if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type);
    for (t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args);
  },
  apply: function(type, that, args) {
    if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type);
    for (var t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args);
  }
};

function get(type, name) {
  for (var i = 0, n = type.length, c; i < n; ++i) {
    if ((c = type[i]).name === name) {
      return c.value;
    }
  }
}

function set(type, name, callback) {
  for (var i = 0, n = type.length; i < n; ++i) {
    if (type[i].name === name) {
      type[i] = noop, type = type.slice(0, i).concat(type.slice(i + 1));
      break;
    }
  }
  if (callback != null) type.push({name: name, value: callback});
  return type;
}

exports.dispatch = dispatch;

Object.defineProperty(exports, '__esModule', { value: true });

})));

},{}],145:[function(_dereq_,module,exports){
// https://d3js.org/d3-force/ Version 1.1.0. Copyright 2017 Mike Bostock.
(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, _dereq_('d3-quadtree'), _dereq_('d3-collection'), _dereq_('d3-dispatch'), _dereq_('d3-timer')) :
	typeof define === 'function' && define.amd ? define(['exports', 'd3-quadtree', 'd3-collection', 'd3-dispatch', 'd3-timer'], factory) :
	(factory((global.d3 = global.d3 || {}),global.d3,global.d3,global.d3,global.d3));
}(this, (function (exports,d3Quadtree,d3Collection,d3Dispatch,d3Timer) { 'use strict';

var center = function(x, y) {
  var nodes;

  if (x == null) x = 0;
  if (y == null) y = 0;

  function force() {
    var i,
        n = nodes.length,
        node,
        sx = 0,
        sy = 0;

    for (i = 0; i < n; ++i) {
      node = nodes[i], sx += node.x, sy += node.y;
    }

    for (sx = sx / n - x, sy = sy / n - y, i = 0; i < n; ++i) {
      node = nodes[i], node.x -= sx, node.y -= sy;
    }
  }

  force.initialize = function(_) {
    nodes = _;
  };

  force.x = function(_) {
    return arguments.length ? (x = +_, force) : x;
  };

  force.y = function(_) {
    return arguments.length ? (y = +_, force) : y;
  };

  return force;
};

var constant = function(x) {
  return function() {
    return x;
  };
};

var jiggle = function() {
  return (Math.random() - 0.5) * 1e-6;
};

function x(d) {
  return d.x + d.vx;
}

function y(d) {
  return d.y + d.vy;
}

var collide = function(radius) {
  var nodes,
      radii,
      strength = 1,
      iterations = 1;

  if (typeof radius !== "function") radius = constant(radius == null ? 1 : +radius);

  function force() {
    var i, n = nodes.length,
        tree,
        node,
        xi,
        yi,
        ri,
        ri2;

    for (var k = 0; k < iterations; ++k) {
      tree = d3Quadtree.quadtree(nodes, x, y).visitAfter(prepare);
      for (i = 0; i < n; ++i) {
        node = nodes[i];
        ri = radii[node.index], ri2 = ri * ri;
        xi = node.x + node.vx;
        yi = node.y + node.vy;
        tree.visit(apply);
      }
    }

    function apply(quad, x0, y0, x1, y1) {
      var data = quad.data, rj = quad.r, r = ri + rj;
      if (data) {
        if (data.index > node.index) {
          var x = xi - data.x - data.vx,
              y = yi - data.y - data.vy,
              l = x * x + y * y;
          if (l < r * r) {
            if (x === 0) x = jiggle(), l += x * x;
            if (y === 0) y = jiggle(), l += y * y;
            l = (r - (l = Math.sqrt(l))) / l * strength;
            node.vx += (x *= l) * (r = (rj *= rj) / (ri2 + rj));
            node.vy += (y *= l) * r;
            data.vx -= x * (r = 1 - r);
            data.vy -= y * r;
          }
        }
        return;
      }
      return x0 > xi + r || x1 < xi - r || y0 > yi + r || y1 < yi - r;
    }
  }

  function prepare(quad) {
    if (quad.data) return quad.r = radii[quad.data.index];
    for (var i = quad.r = 0; i < 4; ++i) {
      if (quad[i] && quad[i].r > quad.r) {
        quad.r = quad[i].r;
      }
    }
  }

  function initialize() {
    if (!nodes) return;
    var i, n = nodes.length, node;
    radii = new Array(n);
    for (i = 0; i < n; ++i) node = nodes[i], radii[node.index] = +radius(node, i, nodes);
  }

  force.initialize = function(_) {
    nodes = _;
    initialize();
  };

  force.iterations = function(_) {
    return arguments.length ? (iterations = +_, force) : iterations;
  };

  force.strength = function(_) {
    return arguments.length ? (strength = +_, force) : strength;
  };

  force.radius = function(_) {
    return arguments.length ? (radius = typeof _ === "function" ? _ : constant(+_), initialize(), force) : radius;
  };

  return force;
};

function index(d) {
  return d.index;
}

function find(nodeById, nodeId) {
  var node = nodeById.get(nodeId);
  if (!node) throw new Error("missing: " + nodeId);
  return node;
}

var link = function(links) {
  var id = index,
      strength = defaultStrength,
      strengths,
      distance = constant(30),
      distances,
      nodes,
      count,
      bias,
      iterations = 1;

  if (links == null) links = [];

  function defaultStrength(link) {
    return 1 / Math.min(count[link.source.index], count[link.target.index]);
  }

  function force(alpha) {
    for (var k = 0, n = links.length; k < iterations; ++k) {
      for (var i = 0, link, source, target, x, y, l, b; i < n; ++i) {
        link = links[i], source = link.source, target = link.target;
        x = target.x + target.vx - source.x - source.vx || jiggle();
        y = target.y + target.vy - source.y - source.vy || jiggle();
        l = Math.sqrt(x * x + y * y);
        l = (l - distances[i]) / l * alpha * strengths[i];
        x *= l, y *= l;
        target.vx -= x * (b = bias[i]);
        target.vy -= y * b;
        source.vx += x * (b = 1 - b);
        source.vy += y * b;
      }
    }
  }

  function initialize() {
    if (!nodes) return;

    var i,
        n = nodes.length,
        m = links.length,
        nodeById = d3Collection.map(nodes, id),
        link;

    for (i = 0, count = new Array(n); i < m; ++i) {
      link = links[i], link.index = i;
      if (typeof link.source !== "object") link.source = find(nodeById, link.source);
      if (typeof link.target !== "object") link.target = find(nodeById, link.target);
      count[link.source.index] = (count[link.source.index] || 0) + 1;
      count[link.target.index] = (count[link.target.index] || 0) + 1;
    }

    for (i = 0, bias = new Array(m); i < m; ++i) {
      link = links[i], bias[i] = count[link.source.index] / (count[link.source.index] + count[link.target.index]);
    }

    strengths = new Array(m), initializeStrength();
    distances = new Array(m), initializeDistance();
  }

  function initializeStrength() {
    if (!nodes) return;

    for (var i = 0, n = links.length; i < n; ++i) {
      strengths[i] = +strength(links[i], i, links);
    }
  }

  function initializeDistance() {
    if (!nodes) return;

    for (var i = 0, n = links.length; i < n; ++i) {
      distances[i] = +distance(links[i], i, links);
    }
  }

  force.initialize = function(_) {
    nodes = _;
    initialize();
  };

  force.links = function(_) {
    return arguments.length ? (links = _, initialize(), force) : links;
  };

  force.id = function(_) {
    return arguments.length ? (id = _, force) : id;
  };

  force.iterations = function(_) {
    return arguments.length ? (iterations = +_, force) : iterations;
  };

  force.strength = function(_) {
    return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initializeStrength(), force) : strength;
  };

  force.distance = function(_) {
    return arguments.length ? (distance = typeof _ === "function" ? _ : constant(+_), initializeDistance(), force) : distance;
  };

  return force;
};

function x$1(d) {
  return d.x;
}

function y$1(d) {
  return d.y;
}

var initialRadius = 10;
var initialAngle = Math.PI * (3 - Math.sqrt(5));

var simulation = function(nodes) {
  var simulation,
      alpha = 1,
      alphaMin = 0.001,
      alphaDecay = 1 - Math.pow(alphaMin, 1 / 300),
      alphaTarget = 0,
      velocityDecay = 0.6,
      forces = d3Collection.map(),
      stepper = d3Timer.timer(step),
      event = d3Dispatch.dispatch("tick", "end");

  if (nodes == null) nodes = [];

  function step() {
    tick();
    event.call("tick", simulation);
    if (alpha < alphaMin) {
      stepper.stop();
      event.call("end", simulation);
    }
  }

  function tick() {
    var i, n = nodes.length, node;

    alpha += (alphaTarget - alpha) * alphaDecay;

    forces.each(function(force) {
      force(alpha);
    });

    for (i = 0; i < n; ++i) {
      node = nodes[i];
      if (node.fx == null) node.x += node.vx *= velocityDecay;
      else node.x = node.fx, node.vx = 0;
      if (node.fy == null) node.y += node.vy *= velocityDecay;
      else node.y = node.fy, node.vy = 0;
    }
  }

  function initializeNodes() {
    for (var i = 0, n = nodes.length, node; i < n; ++i) {
      node = nodes[i], node.index = i;
      if (isNaN(node.x) || isNaN(node.y)) {
        var radius = initialRadius * Math.sqrt(i), angle = i * initialAngle;
        node.x = radius * Math.cos(angle);
        node.y = radius * Math.sin(angle);
      }
      if (isNaN(node.vx) || isNaN(node.vy)) {
        node.vx = node.vy = 0;
      }
    }
  }

  function initializeForce(force) {
    if (force.initialize) force.initialize(nodes);
    return force;
  }

  initializeNodes();

  return simulation = {
    tick: tick,

    restart: function() {
      return stepper.restart(step), simulation;
    },

    stop: function() {
      return stepper.stop(), simulation;
    },

    nodes: function(_) {
      return arguments.length ? (nodes = _, initializeNodes(), forces.each(initializeForce), simulation) : nodes;
    },

    alpha: function(_) {
      return arguments.length ? (alpha = +_, simulation) : alpha;
    },

    alphaMin: function(_) {
      return arguments.length ? (alphaMin = +_, simulation) : alphaMin;
    },

    alphaDecay: function(_) {
      return arguments.length ? (alphaDecay = +_, simulation) : +alphaDecay;
    },

    alphaTarget: function(_) {
      return arguments.length ? (alphaTarget = +_, simulation) : alphaTarget;
    },

    velocityDecay: function(_) {
      return arguments.length ? (velocityDecay = 1 - _, simulation) : 1 - velocityDecay;
    },

    force: function(name, _) {
      return arguments.length > 1 ? ((_ == null ? forces.remove(name) : forces.set(name, initializeForce(_))), simulation) : forces.get(name);
    },

    find: function(x, y, radius) {
      var i = 0,
          n = nodes.length,
          dx,
          dy,
          d2,
          node,
          closest;

      if (radius == null) radius = Infinity;
      else radius *= radius;

      for (i = 0; i < n; ++i) {
        node = nodes[i];
        dx = x - node.x;
        dy = y - node.y;
        d2 = dx * dx + dy * dy;
        if (d2 < radius) closest = node, radius = d2;
      }

      return closest;
    },

    on: function(name, _) {
      return arguments.length > 1 ? (event.on(name, _), simulation) : event.on(name);
    }
  };
};

var manyBody = function() {
  var nodes,
      node,
      alpha,
      strength = constant(-30),
      strengths,
      distanceMin2 = 1,
      distanceMax2 = Infinity,
      theta2 = 0.81;

  function force(_) {
    var i, n = nodes.length, tree = d3Quadtree.quadtree(nodes, x$1, y$1).visitAfter(accumulate);
    for (alpha = _, i = 0; i < n; ++i) node = nodes[i], tree.visit(apply);
  }

  function initialize() {
    if (!nodes) return;
    var i, n = nodes.length, node;
    strengths = new Array(n);
    for (i = 0; i < n; ++i) node = nodes[i], strengths[node.index] = +strength(node, i, nodes);
  }

  function accumulate(quad) {
    var strength = 0, q, c, weight = 0, x, y, i;

    // For internal nodes, accumulate forces from child quadrants.
    if (quad.length) {
      for (x = y = i = 0; i < 4; ++i) {
        if ((q = quad[i]) && (c = Math.abs(q.value))) {
          strength += q.value, weight += c, x += c * q.x, y += c * q.y;
        }
      }
      quad.x = x / weight;
      quad.y = y / weight;
    }

    // For leaf nodes, accumulate forces from coincident quadrants.
    else {
      q = quad;
      q.x = q.data.x;
      q.y = q.data.y;
      do strength += strengths[q.data.index];
      while (q = q.next);
    }

    quad.value = strength;
  }

  function apply(quad, x1, _, x2) {
    if (!quad.value) return true;

    var x = quad.x - node.x,
        y = quad.y - node.y,
        w = x2 - x1,
        l = x * x + y * y;

    // Apply the Barnes-Hut approximation if possible.
    // Limit forces for very close nodes; randomize direction if coincident.
    if (w * w / theta2 < l) {
      if (l < distanceMax2) {
        if (x === 0) x = jiggle(), l += x * x;
        if (y === 0) y = jiggle(), l += y * y;
        if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l);
        node.vx += x * quad.value * alpha / l;
        node.vy += y * quad.value * alpha / l;
      }
      return true;
    }

    // Otherwise, process points directly.
    else if (quad.length || l >= distanceMax2) return;

    // Limit forces for very close nodes; randomize direction if coincident.
    if (quad.data !== node || quad.next) {
      if (x === 0) x = jiggle(), l += x * x;
      if (y === 0) y = jiggle(), l += y * y;
      if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l);
    }

    do if (quad.data !== node) {
      w = strengths[quad.data.index] * alpha / l;
      node.vx += x * w;
      node.vy += y * w;
    } while (quad = quad.next);
  }

  force.initialize = function(_) {
    nodes = _;
    initialize();
  };

  force.strength = function(_) {
    return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength;
  };

  force.distanceMin = function(_) {
    return arguments.length ? (distanceMin2 = _ * _, force) : Math.sqrt(distanceMin2);
  };

  force.distanceMax = function(_) {
    return arguments.length ? (distanceMax2 = _ * _, force) : Math.sqrt(distanceMax2);
  };

  force.theta = function(_) {
    return arguments.length ? (theta2 = _ * _, force) : Math.sqrt(theta2);
  };

  return force;
};

var radial = function(radius, x, y) {
  var nodes,
      strength = constant(0.1),
      strengths,
      radiuses;

  if (typeof radius !== "function") radius = constant(+radius);
  if (x == null) x = 0;
  if (y == null) y = 0;

  function force(alpha) {
    for (var i = 0, n = nodes.length; i < n; ++i) {
      var node = nodes[i],
          dx = node.x - x || 1e-6,
          dy = node.y - y || 1e-6,
          r = Math.sqrt(dx * dx + dy * dy),
          k = (radiuses[i] - r) * strengths[i] * alpha / r;
      node.vx += dx * k;
      node.vy += dy * k;
    }
  }

  function initialize() {
    if (!nodes) return;
    var i, n = nodes.length;
    strengths = new Array(n);
    radiuses = new Array(n);
    for (i = 0; i < n; ++i) {
      radiuses[i] = +radius(nodes[i], i, nodes);
      strengths[i] = isNaN(radiuses[i]) ? 0 : +strength(nodes[i], i, nodes);
    }
  }

  force.initialize = function(_) {
    nodes = _, initialize();
  };

  force.strength = function(_) {
    return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength;
  };

  force.radius = function(_) {
    return arguments.length ? (radius = typeof _ === "function" ? _ : constant(+_), initialize(), force) : radius;
  };

  force.x = function(_) {
    return arguments.length ? (x = +_, force) : x;
  };

  force.y = function(_) {
    return arguments.length ? (y = +_, force) : y;
  };

  return force;
};

var x$2 = function(x) {
  var strength = constant(0.1),
      nodes,
      strengths,
      xz;

  if (typeof x !== "function") x = constant(x == null ? 0 : +x);

  function force(alpha) {
    for (var i = 0, n = nodes.length, node; i < n; ++i) {
      node = nodes[i], node.vx += (xz[i] - node.x) * strengths[i] * alpha;
    }
  }

  function initialize() {
    if (!nodes) return;
    var i, n = nodes.length;
    strengths = new Array(n);
    xz = new Array(n);
    for (i = 0; i < n; ++i) {
      strengths[i] = isNaN(xz[i] = +x(nodes[i], i, nodes)) ? 0 : +strength(nodes[i], i, nodes);
    }
  }

  force.initialize = function(_) {
    nodes = _;
    initialize();
  };

  force.strength = function(_) {
    return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength;
  };

  force.x = function(_) {
    return arguments.length ? (x = typeof _ === "function" ? _ : constant(+_), initialize(), force) : x;
  };

  return force;
};

var y$2 = function(y) {
  var strength = constant(0.1),
      nodes,
      strengths,
      yz;

  if (typeof y !== "function") y = constant(y == null ? 0 : +y);

  function force(alpha) {
    for (var i = 0, n = nodes.length, node; i < n; ++i) {
      node = nodes[i], node.vy += (yz[i] - node.y) * strengths[i] * alpha;
    }
  }

  function initialize() {
    if (!nodes) return;
    var i, n = nodes.length;
    strengths = new Array(n);
    yz = new Array(n);
    for (i = 0; i < n; ++i) {
      strengths[i] = isNaN(yz[i] = +y(nodes[i], i, nodes)) ? 0 : +strength(nodes[i], i, nodes);
    }
  }

  force.initialize = function(_) {
    nodes = _;
    initialize();
  };

  force.strength = function(_) {
    return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength;
  };

  force.y = function(_) {
    return arguments.length ? (y = typeof _ === "function" ? _ : constant(+_), initialize(), force) : y;
  };

  return force;
};

exports.forceCenter = center;
exports.forceCollide = collide;
exports.forceLink = link;
exports.forceManyBody = manyBody;
exports.forceRadial = radial;
exports.forceSimulation = simulation;
exports.forceX = x$2;
exports.forceY = y$2;

Object.defineProperty(exports, '__esModule', { value: true });

})));

},{"d3-collection":142,"d3-dispatch":144,"d3-quadtree":147,"d3-timer":148}],146:[function(_dereq_,module,exports){
// https://d3js.org/d3-interpolate/ v1.3.2 Copyright 2018 Mike Bostock
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, _dereq_('d3-color')) :
typeof define === 'function' && define.amd ? define(['exports', 'd3-color'], factory) :
(factory((global.d3 = global.d3 || {}),global.d3));
}(this, (function (exports,d3Color) { 'use strict';

function basis(t1, v0, v1, v2, v3) {
  var t2 = t1 * t1, t3 = t2 * t1;
  return ((1 - 3 * t1 + 3 * t2 - t3) * v0
      + (4 - 6 * t2 + 3 * t3) * v1
      + (1 + 3 * t1 + 3 * t2 - 3 * t3) * v2
      + t3 * v3) / 6;
}

function basis$1(values) {
  var n = values.length - 1;
  return function(t) {
    var i = t <= 0 ? (t = 0) : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n),
        v1 = values[i],
        v2 = values[i + 1],
        v0 = i > 0 ? values[i - 1] : 2 * v1 - v2,
        v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1;
    return basis((t - i / n) * n, v0, v1, v2, v3);
  };
}

function basisClosed(values) {
  var n = values.length;
  return function(t) {
    var i = Math.floor(((t %= 1) < 0 ? ++t : t) * n),
        v0 = values[(i + n - 1) % n],
        v1 = values[i % n],
        v2 = values[(i + 1) % n],
        v3 = values[(i + 2) % n];
    return basis((t - i / n) * n, v0, v1, v2, v3);
  };
}

function constant(x) {
  return function() {
    return x;
  };
}

function linear(a, d) {
  return function(t) {
    return a + t * d;
  };
}

function exponential(a, b, y) {
  return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) {
    return Math.pow(a + t * b, y);
  };
}

function hue(a, b) {
  var d = b - a;
  return d ? linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : constant(isNaN(a) ? b : a);
}

function gamma(y) {
  return (y = +y) === 1 ? nogamma : function(a, b) {
    return b - a ? exponential(a, b, y) : constant(isNaN(a) ? b : a);
  };
}

function nogamma(a, b) {
  var d = b - a;
  return d ? linear(a, d) : constant(isNaN(a) ? b : a);
}

var rgb = (function rgbGamma(y) {
  var color = gamma(y);

  function rgb(start, end) {
    var r = color((start = d3Color.rgb(start)).r, (end = d3Color.rgb(end)).r),
        g = color(start.g, end.g),
        b = color(start.b, end.b),
        opacity = nogamma(start.opacity, end.opacity);
    return function(t) {
      start.r = r(t);
      start.g = g(t);
      start.b = b(t);
      start.opacity = opacity(t);
      return start + "";
    };
  }

  rgb.gamma = rgbGamma;

  return rgb;
})(1);

function rgbSpline(spline) {
  return function(colors) {
    var n = colors.length,
        r = new Array(n),
        g = new Array(n),
        b = new Array(n),
        i, color;
    for (i = 0; i < n; ++i) {
      color = d3Color.rgb(colors[i]);
      r[i] = color.r || 0;
      g[i] = color.g || 0;
      b[i] = color.b || 0;
    }
    r = spline(r);
    g = spline(g);
    b = spline(b);
    color.opacity = 1;
    return function(t) {
      color.r = r(t);
      color.g = g(t);
      color.b = b(t);
      return color + "";
    };
  };
}

var rgbBasis = rgbSpline(basis$1);
var rgbBasisClosed = rgbSpline(basisClosed);

function array(a, b) {
  var nb = b ? b.length : 0,
      na = a ? Math.min(nb, a.length) : 0,
      x = new Array(na),
      c = new Array(nb),
      i;

  for (i = 0; i < na; ++i) x[i] = value(a[i], b[i]);
  for (; i < nb; ++i) c[i] = b[i];

  return function(t) {
    for (i = 0; i < na; ++i) c[i] = x[i](t);
    return c;
  };
}

function date(a, b) {
  var d = new Date;
  return a = +a, b -= a, function(t) {
    return d.setTime(a + b * t), d;
  };
}

function number(a, b) {
  return a = +a, b -= a, function(t) {
    return a + b * t;
  };
}

function object(a, b) {
  var i = {},
      c = {},
      k;

  if (a === null || typeof a !== "object") a = {};
  if (b === null || typeof b !== "object") b = {};

  for (k in b) {
    if (k in a) {
      i[k] = value(a[k], b[k]);
    } else {
      c[k] = b[k];
    }
  }

  return function(t) {
    for (k in i) c[k] = i[k](t);
    return c;
  };
}

var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,
    reB = new RegExp(reA.source, "g");

function zero(b) {
  return function() {
    return b;
  };
}

function one(b) {
  return function(t) {
    return b(t) + "";
  };
}

function string(a, b) {
  var bi = reA.lastIndex = reB.lastIndex = 0, // scan index for next number in b
      am, // current match in a
      bm, // current match in b
      bs, // string preceding current number in b, if any
      i = -1, // index in s
      s = [], // string constants and placeholders
      q = []; // number interpolators

  // Coerce inputs to strings.
  a = a + "", b = b + "";

  // Interpolate pairs of numbers in a & b.
  while ((am = reA.exec(a))
      && (bm = reB.exec(b))) {
    if ((bs = bm.index) > bi) { // a string precedes the next number in b
      bs = b.slice(bi, bs);
      if (s[i]) s[i] += bs; // coalesce with previous string
      else s[++i] = bs;
    }
    if ((am = am[0]) === (bm = bm[0])) { // numbers in a & b match
      if (s[i]) s[i] += bm; // coalesce with previous string
      else s[++i] = bm;
    } else { // interpolate non-matching numbers
      s[++i] = null;
      q.push({i: i, x: number(am, bm)});
    }
    bi = reB.lastIndex;
  }

  // Add remains of b.
  if (bi < b.length) {
    bs = b.slice(bi);
    if (s[i]) s[i] += bs; // coalesce with previous string
    else s[++i] = bs;
  }

  // Special optimization for only a single match.
  // Otherwise, interpolate each of the numbers and rejoin the string.
  return s.length < 2 ? (q[0]
      ? one(q[0].x)
      : zero(b))
      : (b = q.length, function(t) {
          for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);
          return s.join("");
        });
}

function value(a, b) {
  var t = typeof b, c;
  return b == null || t === "boolean" ? constant(b)
      : (t === "number" ? number
      : t === "string" ? ((c = d3Color.color(b)) ? (b = c, rgb) : string)
      : b instanceof d3Color.color ? rgb
      : b instanceof Date ? date
      : Array.isArray(b) ? array
      : typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? object
      : number)(a, b);
}

function discrete(range) {
  var n = range.length;
  return function(t) {
    return range[Math.max(0, Math.min(n - 1, Math.floor(t * n)))];
  };
}

function hue$1(a, b) {
  var i = hue(+a, +b);
  return function(t) {
    var x = i(t);
    return x - 360 * Math.floor(x / 360);
  };
}

function round(a, b) {
  return a = +a, b -= a, function(t) {
    return Math.round(a + b * t);
  };
}

var degrees = 180 / Math.PI;

var identity = {
  translateX: 0,
  translateY: 0,
  rotate: 0,
  skewX: 0,
  scaleX: 1,
  scaleY: 1
};

function decompose(a, b, c, d, e, f) {
  var scaleX, scaleY, skewX;
  if (scaleX = Math.sqrt(a * a + b * b)) a /= scaleX, b /= scaleX;
  if (skewX = a * c + b * d) c -= a * skewX, d -= b * skewX;
  if (scaleY = Math.sqrt(c * c + d * d)) c /= scaleY, d /= scaleY, skewX /= scaleY;
  if (a * d < b * c) a = -a, b = -b, skewX = -skewX, scaleX = -scaleX;
  return {
    translateX: e,
    translateY: f,
    rotate: Math.atan2(b, a) * degrees,
    skewX: Math.atan(skewX) * degrees,
    scaleX: scaleX,
    scaleY: scaleY
  };
}

var cssNode,
    cssRoot,
    cssView,
    svgNode;

function parseCss(value) {
  if (value === "none") return identity;
  if (!cssNode) cssNode = document.createElement("DIV"), cssRoot = document.documentElement, cssView = document.defaultView;
  cssNode.style.transform = value;
  value = cssView.getComputedStyle(cssRoot.appendChild(cssNode), null).getPropertyValue("transform");
  cssRoot.removeChild(cssNode);
  value = value.slice(7, -1).split(",");
  return decompose(+value[0], +value[1], +value[2], +value[3], +value[4], +value[5]);
}

function parseSvg(value) {
  if (value == null) return identity;
  if (!svgNode) svgNode = document.createElementNS("http://www.w3.org/2000/svg", "g");
  svgNode.setAttribute("transform", value);
  if (!(value = svgNode.transform.baseVal.consolidate())) return identity;
  value = value.matrix;
  return decompose(value.a, value.b, value.c, value.d, value.e, value.f);
}

function interpolateTransform(parse, pxComma, pxParen, degParen) {

  function pop(s) {
    return s.length ? s.pop() + " " : "";
  }

  function translate(xa, ya, xb, yb, s, q) {
    if (xa !== xb || ya !== yb) {
      var i = s.push("translate(", null, pxComma, null, pxParen);
      q.push({i: i - 4, x: number(xa, xb)}, {i: i - 2, x: number(ya, yb)});
    } else if (xb || yb) {
      s.push("translate(" + xb + pxComma + yb + pxParen);
    }
  }

  function rotate(a, b, s, q) {
    if (a !== b) {
      if (a - b > 180) b += 360; else if (b - a > 180) a += 360; // shortest path
      q.push({i: s.push(pop(s) + "rotate(", null, degParen) - 2, x: number(a, b)});
    } else if (b) {
      s.push(pop(s) + "rotate(" + b + degParen);
    }
  }

  function skewX(a, b, s, q) {
    if (a !== b) {
      q.push({i: s.push(pop(s) + "skewX(", null, degParen) - 2, x: number(a, b)});
    } else if (b) {
      s.push(pop(s) + "skewX(" + b + degParen);
    }
  }

  function scale(xa, ya, xb, yb, s, q) {
    if (xa !== xb || ya !== yb) {
      var i = s.push(pop(s) + "scale(", null, ",", null, ")");
      q.push({i: i - 4, x: number(xa, xb)}, {i: i - 2, x: number(ya, yb)});
    } else if (xb !== 1 || yb !== 1) {
      s.push(pop(s) + "scale(" + xb + "," + yb + ")");
    }
  }

  return function(a, b) {
    var s = [], // string constants and placeholders
        q = []; // number interpolators
    a = parse(a), b = parse(b);
    translate(a.translateX, a.translateY, b.translateX, b.translateY, s, q);
    rotate(a.rotate, b.rotate, s, q);
    skewX(a.skewX, b.skewX, s, q);
    scale(a.scaleX, a.scaleY, b.scaleX, b.scaleY, s, q);
    a = b = null; // gc
    return function(t) {
      var i = -1, n = q.length, o;
      while (++i < n) s[(o = q[i]).i] = o.x(t);
      return s.join("");
    };
  };
}

var interpolateTransformCss = interpolateTransform(parseCss, "px, ", "px)", "deg)");
var interpolateTransformSvg = interpolateTransform(parseSvg, ", ", ")", ")");

var rho = Math.SQRT2,
    rho2 = 2,
    rho4 = 4,
    epsilon2 = 1e-12;

function cosh(x) {
  return ((x = Math.exp(x)) + 1 / x) / 2;
}

function sinh(x) {
  return ((x = Math.exp(x)) - 1 / x) / 2;
}

function tanh(x) {
  return ((x = Math.exp(2 * x)) - 1) / (x + 1);
}

// p0 = [ux0, uy0, w0]
// p1 = [ux1, uy1, w1]
function zoom(p0, p1) {
  var ux0 = p0[0], uy0 = p0[1], w0 = p0[2],
      ux1 = p1[0], uy1 = p1[1], w1 = p1[2],
      dx = ux1 - ux0,
      dy = uy1 - uy0,
      d2 = dx * dx + dy * dy,
      i,
      S;

  // Special case for u0 ≅ u1.
  if (d2 < epsilon2) {
    S = Math.log(w1 / w0) / rho;
    i = function(t) {
      return [
        ux0 + t * dx,
        uy0 + t * dy,
        w0 * Math.exp(rho * t * S)
      ];
    };
  }

  // General case.
  else {
    var d1 = Math.sqrt(d2),
        b0 = (w1 * w1 - w0 * w0 + rho4 * d2) / (2 * w0 * rho2 * d1),
        b1 = (w1 * w1 - w0 * w0 - rho4 * d2) / (2 * w1 * rho2 * d1),
        r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0),
        r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);
    S = (r1 - r0) / rho;
    i = function(t) {
      var s = t * S,
          coshr0 = cosh(r0),
          u = w0 / (rho2 * d1) * (coshr0 * tanh(rho * s + r0) - sinh(r0));
      return [
        ux0 + u * dx,
        uy0 + u * dy,
        w0 * coshr0 / cosh(rho * s + r0)
      ];
    };
  }

  i.duration = S * 1000;

  return i;
}

function hsl(hue$$1) {
  return function(start, end) {
    var h = hue$$1((start = d3Color.hsl(start)).h, (end = d3Color.hsl(end)).h),
        s = nogamma(start.s, end.s),
        l = nogamma(start.l, end.l),
        opacity = nogamma(start.opacity, end.opacity);
    return function(t) {
      start.h = h(t);
      start.s = s(t);
      start.l = l(t);
      start.opacity = opacity(t);
      return start + "";
    };
  }
}

var hsl$1 = hsl(hue);
var hslLong = hsl(nogamma);

function lab(start, end) {
  var l = nogamma((start = d3Color.lab(start)).l, (end = d3Color.lab(end)).l),
      a = nogamma(start.a, end.a),
      b = nogamma(start.b, end.b),
      opacity = nogamma(start.opacity, end.opacity);
  return function(t) {
    start.l = l(t);
    start.a = a(t);
    start.b = b(t);
    start.opacity = opacity(t);
    return start + "";
  };
}

function hcl(hue$$1) {
  return function(start, end) {
    var h = hue$$1((start = d3Color.hcl(start)).h, (end = d3Color.hcl(end)).h),
        c = nogamma(start.c, end.c),
        l = nogamma(start.l, end.l),
        opacity = nogamma(start.opacity, end.opacity);
    return function(t) {
      start.h = h(t);
      start.c = c(t);
      start.l = l(t);
      start.opacity = opacity(t);
      return start + "";
    };
  }
}

var hcl$1 = hcl(hue);
var hclLong = hcl(nogamma);

function cubehelix(hue$$1) {
  return (function cubehelixGamma(y) {
    y = +y;

    function cubehelix(start, end) {
      var h = hue$$1((start = d3Color.cubehelix(start)).h, (end = d3Color.cubehelix(end)).h),
          s = nogamma(start.s, end.s),
          l = nogamma(start.l, end.l),
          opacity = nogamma(start.opacity, end.opacity);
      return function(t) {
        start.h = h(t);
        start.s = s(t);
        start.l = l(Math.pow(t, y));
        start.opacity = opacity(t);
        return start + "";
      };
    }

    cubehelix.gamma = cubehelixGamma;

    return cubehelix;
  })(1);
}

var cubehelix$1 = cubehelix(hue);
var cubehelixLong = cubehelix(nogamma);

function piecewise(interpolate, values) {
  var i = 0, n = values.length - 1, v = values[0], I = new Array(n < 0 ? 0 : n);
  while (i < n) I[i] = interpolate(v, v = values[++i]);
  return function(t) {
    var i = Math.max(0, Math.min(n - 1, Math.floor(t *= n)));
    return I[i](t - i);
  };
}

function quantize(interpolator, n) {
  var samples = new Array(n);
  for (var i = 0; i < n; ++i) samples[i] = interpolator(i / (n - 1));
  return samples;
}

exports.interpolate = value;
exports.interpolateArray = array;
exports.interpolateBasis = basis$1;
exports.interpolateBasisClosed = basisClosed;
exports.interpolateDate = date;
exports.interpolateDiscrete = discrete;
exports.interpolateHue = hue$1;
exports.interpolateNumber = number;
exports.interpolateObject = object;
exports.interpolateRound = round;
exports.interpolateString = string;
exports.interpolateTransformCss = interpolateTransformCss;
exports.interpolateTransformSvg = interpolateTransformSvg;
exports.interpolateZoom = zoom;
exports.interpolateRgb = rgb;
exports.interpolateRgbBasis = rgbBasis;
exports.interpolateRgbBasisClosed = rgbBasisClosed;
exports.interpolateHsl = hsl$1;
exports.interpolateHslLong = hslLong;
exports.interpolateLab = lab;
exports.interpolateHcl = hcl$1;
exports.interpolateHclLong = hclLong;
exports.interpolateCubehelix = cubehelix$1;
exports.interpolateCubehelixLong = cubehelixLong;
exports.piecewise = piecewise;
exports.quantize = quantize;

Object.defineProperty(exports, '__esModule', { value: true });

})));

},{"d3-color":143}],147:[function(_dereq_,module,exports){
// https://d3js.org/d3-quadtree/ Version 1.0.3. Copyright 2017 Mike Bostock.
(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
	typeof define === 'function' && define.amd ? define(['exports'], factory) :
	(factory((global.d3 = global.d3 || {})));
}(this, (function (exports) { 'use strict';

var tree_add = function(d) {
  var x = +this._x.call(null, d),
      y = +this._y.call(null, d);
  return add(this.cover(x, y), x, y, d);
};

function add(tree, x, y, d) {
  if (isNaN(x) || isNaN(y)) return tree; // ignore invalid points

  var parent,
      node = tree._root,
      leaf = {data: d},
      x0 = tree._x0,
      y0 = tree._y0,
      x1 = tree._x1,
      y1 = tree._y1,
      xm,
      ym,
      xp,
      yp,
      right,
      bottom,
      i,
      j;

  // If the tree is empty, initialize the root as a leaf.
  if (!node) return tree._root = leaf, tree;

  // Find the existing leaf for the new point, or add it.
  while (node.length) {
    if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
    if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;
    if (parent = node, !(node = node[i = bottom << 1 | right])) return parent[i] = leaf, tree;
  }

  // Is the new point is exactly coincident with the existing point?
  xp = +tree._x.call(null, node.data);
  yp = +tree._y.call(null, node.data);
  if (x === xp && y === yp) return leaf.next = node, parent ? parent[i] = leaf : tree._root = leaf, tree;

  // Otherwise, split the leaf node until the old and new point are separated.
  do {
    parent = parent ? parent[i] = new Array(4) : tree._root = new Array(4);
    if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
    if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;
  } while ((i = bottom << 1 | right) === (j = (yp >= ym) << 1 | (xp >= xm)));
  return parent[j] = node, parent[i] = leaf, tree;
}

function addAll(data) {
  var d, i, n = data.length,
      x,
      y,
      xz = new Array(n),
      yz = new Array(n),
      x0 = Infinity,
      y0 = Infinity,
      x1 = -Infinity,
      y1 = -Infinity;

  // Compute the points and their extent.
  for (i = 0; i < n; ++i) {
    if (isNaN(x = +this._x.call(null, d = data[i])) || isNaN(y = +this._y.call(null, d))) continue;
    xz[i] = x;
    yz[i] = y;
    if (x < x0) x0 = x;
    if (x > x1) x1 = x;
    if (y < y0) y0 = y;
    if (y > y1) y1 = y;
  }

  // If there were no (valid) points, inherit the existing extent.
  if (x1 < x0) x0 = this._x0, x1 = this._x1;
  if (y1 < y0) y0 = this._y0, y1 = this._y1;

  // Expand the tree to cover the new points.
  this.cover(x0, y0).cover(x1, y1);

  // Add the new points.
  for (i = 0; i < n; ++i) {
    add(this, xz[i], yz[i], data[i]);
  }

  return this;
}

var tree_cover = function(x, y) {
  if (isNaN(x = +x) || isNaN(y = +y)) return this; // ignore invalid points

  var x0 = this._x0,
      y0 = this._y0,
      x1 = this._x1,
      y1 = this._y1;

  // If the quadtree has no extent, initialize them.
  // Integer extent are necessary so that if we later double the extent,
  // the existing quadrant boundaries don’t change due to floating point error!
  if (isNaN(x0)) {
    x1 = (x0 = Math.floor(x)) + 1;
    y1 = (y0 = Math.floor(y)) + 1;
  }

  // Otherwise, double repeatedly to cover.
  else if (x0 > x || x > x1 || y0 > y || y > y1) {
    var z = x1 - x0,
        node = this._root,
        parent,
        i;

    switch (i = (y < (y0 + y1) / 2) << 1 | (x < (x0 + x1) / 2)) {
      case 0: {
        do parent = new Array(4), parent[i] = node, node = parent;
        while (z *= 2, x1 = x0 + z, y1 = y0 + z, x > x1 || y > y1);
        break;
      }
      case 1: {
        do parent = new Array(4), parent[i] = node, node = parent;
        while (z *= 2, x0 = x1 - z, y1 = y0 + z, x0 > x || y > y1);
        break;
      }
      case 2: {
        do parent = new Array(4), parent[i] = node, node = parent;
        while (z *= 2, x1 = x0 + z, y0 = y1 - z, x > x1 || y0 > y);
        break;
      }
      case 3: {
        do parent = new Array(4), parent[i] = node, node = parent;
        while (z *= 2, x0 = x1 - z, y0 = y1 - z, x0 > x || y0 > y);
        break;
      }
    }

    if (this._root && this._root.length) this._root = node;
  }

  // If the quadtree covers the point already, just return.
  else return this;

  this._x0 = x0;
  this._y0 = y0;
  this._x1 = x1;
  this._y1 = y1;
  return this;
};

var tree_data = function() {
  var data = [];
  this.visit(function(node) {
    if (!node.length) do data.push(node.data); while (node = node.next)
  });
  return data;
};

var tree_extent = function(_) {
  return arguments.length
      ? this.cover(+_[0][0], +_[0][1]).cover(+_[1][0], +_[1][1])
      : isNaN(this._x0) ? undefined : [[this._x0, this._y0], [this._x1, this._y1]];
};

var Quad = function(node, x0, y0, x1, y1) {
  this.node = node;
  this.x0 = x0;
  this.y0 = y0;
  this.x1 = x1;
  this.y1 = y1;
};

var tree_find = function(x, y, radius) {
  var data,
      x0 = this._x0,
      y0 = this._y0,
      x1,
      y1,
      x2,
      y2,
      x3 = this._x1,
      y3 = this._y1,
      quads = [],
      node = this._root,
      q,
      i;

  if (node) quads.push(new Quad(node, x0, y0, x3, y3));
  if (radius == null) radius = Infinity;
  else {
    x0 = x - radius, y0 = y - radius;
    x3 = x + radius, y3 = y + radius;
    radius *= radius;
  }

  while (q = quads.pop()) {

    // Stop searching if this quadrant can’t contain a closer node.
    if (!(node = q.node)
        || (x1 = q.x0) > x3
        || (y1 = q.y0) > y3
        || (x2 = q.x1) < x0
        || (y2 = q.y1) < y0) continue;

    // Bisect the current quadrant.
    if (node.length) {
      var xm = (x1 + x2) / 2,
          ym = (y1 + y2) / 2;

      quads.push(
        new Quad(node[3], xm, ym, x2, y2),
        new Quad(node[2], x1, ym, xm, y2),
        new Quad(node[1], xm, y1, x2, ym),
        new Quad(node[0], x1, y1, xm, ym)
      );

      // Visit the closest quadrant first.
      if (i = (y >= ym) << 1 | (x >= xm)) {
        q = quads[quads.length - 1];
        quads[quads.length - 1] = quads[quads.length - 1 - i];
        quads[quads.length - 1 - i] = q;
      }
    }

    // Visit this point. (Visiting coincident points isn’t necessary!)
    else {
      var dx = x - +this._x.call(null, node.data),
          dy = y - +this._y.call(null, node.data),
          d2 = dx * dx + dy * dy;
      if (d2 < radius) {
        var d = Math.sqrt(radius = d2);
        x0 = x - d, y0 = y - d;
        x3 = x + d, y3 = y + d;
        data = node.data;
      }
    }
  }

  return data;
};

var tree_remove = function(d) {
  if (isNaN(x = +this._x.call(null, d)) || isNaN(y = +this._y.call(null, d))) return this; // ignore invalid points

  var parent,
      node = this._root,
      retainer,
      previous,
      next,
      x0 = this._x0,
      y0 = this._y0,
      x1 = this._x1,
      y1 = this._y1,
      x,
      y,
      xm,
      ym,
      right,
      bottom,
      i,
      j;

  // If the tree is empty, initialize the root as a leaf.
  if (!node) return this;

  // Find the leaf node for the point.
  // While descending, also retain the deepest parent with a non-removed sibling.
  if (node.length) while (true) {
    if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
    if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;
    if (!(parent = node, node = node[i = bottom << 1 | right])) return this;
    if (!node.length) break;
    if (parent[(i + 1) & 3] || parent[(i + 2) & 3] || parent[(i + 3) & 3]) retainer = parent, j = i;
  }

  // Find the point to remove.
  while (node.data !== d) if (!(previous = node, node = node.next)) return this;
  if (next = node.next) delete node.next;

  // If there are multiple coincident points, remove just the point.
  if (previous) return (next ? previous.next = next : delete previous.next), this;

  // If this is the root point, remove it.
  if (!parent) return this._root = next, this;

  // Remove this leaf.
  next ? parent[i] = next : delete parent[i];

  // If the parent now contains exactly one leaf, collapse superfluous parents.
  if ((node = parent[0] || parent[1] || parent[2] || parent[3])
      && node === (parent[3] || parent[2] || parent[1] || parent[0])
      && !node.length) {
    if (retainer) retainer[j] = node;
    else this._root = node;
  }

  return this;
};

function removeAll(data) {
  for (var i = 0, n = data.length; i < n; ++i) this.remove(data[i]);
  return this;
}

var tree_root = function() {
  return this._root;
};

var tree_size = function() {
  var size = 0;
  this.visit(function(node) {
    if (!node.length) do ++size; while (node = node.next)
  });
  return size;
};

var tree_visit = function(callback) {
  var quads = [], q, node = this._root, child, x0, y0, x1, y1;
  if (node) quads.push(new Quad(node, this._x0, this._y0, this._x1, this._y1));
  while (q = quads.pop()) {
    if (!callback(node = q.node, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1) && node.length) {
      var xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
      if (child = node[3]) quads.push(new Quad(child, xm, ym, x1, y1));
      if (child = node[2]) quads.push(new Quad(child, x0, ym, xm, y1));
      if (child = node[1]) quads.push(new Quad(child, xm, y0, x1, ym));
      if (child = node[0]) quads.push(new Quad(child, x0, y0, xm, ym));
    }
  }
  return this;
};

var tree_visitAfter = function(callback) {
  var quads = [], next = [], q;
  if (this._root) quads.push(new Quad(this._root, this._x0, this._y0, this._x1, this._y1));
  while (q = quads.pop()) {
    var node = q.node;
    if (node.length) {
      var child, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1, xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
      if (child = node[0]) quads.push(new Quad(child, x0, y0, xm, ym));
      if (child = node[1]) quads.push(new Quad(child, xm, y0, x1, ym));
      if (child = node[2]) quads.push(new Quad(child, x0, ym, xm, y1));
      if (child = node[3]) quads.push(new Quad(child, xm, ym, x1, y1));
    }
    next.push(q);
  }
  while (q = next.pop()) {
    callback(q.node, q.x0, q.y0, q.x1, q.y1);
  }
  return this;
};

function defaultX(d) {
  return d[0];
}

var tree_x = function(_) {
  return arguments.length ? (this._x = _, this) : this._x;
};

function defaultY(d) {
  return d[1];
}

var tree_y = function(_) {
  return arguments.length ? (this._y = _, this) : this._y;
};

function quadtree(nodes, x, y) {
  var tree = new Quadtree(x == null ? defaultX : x, y == null ? defaultY : y, NaN, NaN, NaN, NaN);
  return nodes == null ? tree : tree.addAll(nodes);
}

function Quadtree(x, y, x0, y0, x1, y1) {
  this._x = x;
  this._y = y;
  this._x0 = x0;
  this._y0 = y0;
  this._x1 = x1;
  this._y1 = y1;
  this._root = undefined;
}

function leaf_copy(leaf) {
  var copy = {data: leaf.data}, next = copy;
  while (leaf = leaf.next) next = next.next = {data: leaf.data};
  return copy;
}

var treeProto = quadtree.prototype = Quadtree.prototype;

treeProto.copy = function() {
  var copy = new Quadtree(this._x, this._y, this._x0, this._y0, this._x1, this._y1),
      node = this._root,
      nodes,
      child;

  if (!node) return copy;

  if (!node.length) return copy._root = leaf_copy(node), copy;

  nodes = [{source: node, target: copy._root = new Array(4)}];
  while (node = nodes.pop()) {
    for (var i = 0; i < 4; ++i) {
      if (child = node.source[i]) {
        if (child.length) nodes.push({source: child, target: node.target[i] = new Array(4)});
        else node.target[i] = leaf_copy(child);
      }
    }
  }

  return copy;
};

treeProto.add = tree_add;
treeProto.addAll = addAll;
treeProto.cover = tree_cover;
treeProto.data = tree_data;
treeProto.extent = tree_extent;
treeProto.find = tree_find;
treeProto.remove = tree_remove;
treeProto.removeAll = removeAll;
treeProto.root = tree_root;
treeProto.size = tree_size;
treeProto.visit = tree_visit;
treeProto.visitAfter = tree_visitAfter;
treeProto.x = tree_x;
treeProto.y = tree_y;

exports.quadtree = quadtree;

Object.defineProperty(exports, '__esModule', { value: true });

})));

},{}],148:[function(_dereq_,module,exports){
// https://d3js.org/d3-timer/ Version 1.0.7. Copyright 2017 Mike Bostock.
(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
	typeof define === 'function' && define.amd ? define(['exports'], factory) :
	(factory((global.d3 = global.d3 || {})));
}(this, (function (exports) { 'use strict';

var frame = 0;
var timeout = 0;
var interval = 0;
var pokeDelay = 1000;
var taskHead;
var taskTail;
var clockLast = 0;
var clockNow = 0;
var clockSkew = 0;
var clock = typeof performance === "object" && performance.now ? performance : Date;
var setFrame = typeof window === "object" && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : function(f) { setTimeout(f, 17); };

function now() {
  return clockNow || (setFrame(clearNow), clockNow = clock.now() + clockSkew);
}

function clearNow() {
  clockNow = 0;
}

function Timer() {
  this._call =
  this._time =
  this._next = null;
}

Timer.prototype = timer.prototype = {
  constructor: Timer,
  restart: function(callback, delay, time) {
    if (typeof callback !== "function") throw new TypeError("callback is not a function");
    time = (time == null ? now() : +time) + (delay == null ? 0 : +delay);
    if (!this._next && taskTail !== this) {
      if (taskTail) taskTail._next = this;
      else taskHead = this;
      taskTail = this;
    }
    this._call = callback;
    this._time = time;
    sleep();
  },
  stop: function() {
    if (this._call) {
      this._call = null;
      this._time = Infinity;
      sleep();
    }
  }
};

function timer(callback, delay, time) {
  var t = new Timer;
  t.restart(callback, delay, time);
  return t;
}

function timerFlush() {
  now(); // Get the current time, if not already set.
  ++frame; // Pretend we’ve set an alarm, if we haven’t already.
  var t = taskHead, e;
  while (t) {
    if ((e = clockNow - t._time) >= 0) t._call.call(null, e);
    t = t._next;
  }
  --frame;
}

function wake() {
  clockNow = (clockLast = clock.now()) + clockSkew;
  frame = timeout = 0;
  try {
    timerFlush();
  } finally {
    frame = 0;
    nap();
    clockNow = 0;
  }
}

function poke() {
  var now = clock.now(), delay = now - clockLast;
  if (delay > pokeDelay) clockSkew -= delay, clockLast = now;
}

function nap() {
  var t0, t1 = taskHead, t2, time = Infinity;
  while (t1) {
    if (t1._call) {
      if (time > t1._time) time = t1._time;
      t0 = t1, t1 = t1._next;
    } else {
      t2 = t1._next, t1._next = null;
      t1 = t0 ? t0._next = t2 : taskHead = t2;
    }
  }
  taskTail = t0;
  sleep(time);
}

function sleep(time) {
  if (frame) return; // Soonest alarm already set, or will be.
  if (timeout) timeout = clearTimeout(timeout);
  var delay = time - clockNow; // Strictly less than if we recomputed clockNow.
  if (delay > 24) {
    if (time < Infinity) timeout = setTimeout(wake, time - clock.now() - clockSkew);
    if (interval) interval = clearInterval(interval);
  } else {
    if (!interval) clockLast = clock.now(), interval = setInterval(poke, pokeDelay);
    frame = 1, setFrame(wake);
  }
}

var timeout$1 = function(callback, delay, time) {
  var t = new Timer;
  delay = delay == null ? 0 : +delay;
  t.restart(function(elapsed) {
    t.stop();
    callback(elapsed + delay);
  }, delay, time);
  return t;
};

var interval$1 = function(callback, delay, time) {
  var t = new Timer, total = delay;
  if (delay == null) return t.restart(callback, delay, time), t;
  delay = +delay, time = time == null ? now() : +time;
  t.restart(function tick(elapsed) {
    elapsed += total;
    t.restart(tick, total += delay, time);
    callback(elapsed);
  }, delay, time);
  return t;
};

exports.now = now;
exports.timer = timer;
exports.timerFlush = timerFlush;
exports.timeout = timeout$1;
exports.interval = interval$1;

Object.defineProperty(exports, '__esModule', { value: true });

})));

},{}],149:[function(_dereq_,module,exports){
!function() {
  var d3 = {
    version: "3.5.17"
  };
  var d3_arraySlice = [].slice, d3_array = function(list) {
    return d3_arraySlice.call(list);
  };
  var d3_document = this.document;
  function d3_documentElement(node) {
    return node && (node.ownerDocument || node.document || node).documentElement;
  }
  function d3_window(node) {
    return node && (node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView);
  }
  if (d3_document) {
    try {
      d3_array(d3_document.documentElement.childNodes)[0].nodeType;
    } catch (e) {
      d3_array = function(list) {
        var i = list.length, array = new Array(i);
        while (i--) array[i] = list[i];
        return array;
      };
    }
  }
  if (!Date.now) Date.now = function() {
    return +new Date();
  };
  if (d3_document) {
    try {
      d3_document.createElement("DIV").style.setProperty("opacity", 0, "");
    } catch (error) {
      var d3_element_prototype = this.Element.prototype, d3_element_setAttribute = d3_element_prototype.setAttribute, d3_element_setAttributeNS = d3_element_prototype.setAttributeNS, d3_style_prototype = this.CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty;
      d3_element_prototype.setAttribute = function(name, value) {
        d3_element_setAttribute.call(this, name, value + "");
      };
      d3_element_prototype.setAttributeNS = function(space, local, value) {
        d3_element_setAttributeNS.call(this, space, local, value + "");
      };
      d3_style_prototype.setProperty = function(name, value, priority) {
        d3_style_setProperty.call(this, name, value + "", priority);
      };
    }
  }
  d3.ascending = d3_ascending;
  function d3_ascending(a, b) {
    return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
  }
  d3.descending = function(a, b) {
    return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
  };
  d3.min = function(array, f) {
    var i = -1, n = array.length, a, b;
    if (arguments.length === 1) {
      while (++i < n) if ((b = array[i]) != null && b >= b) {
        a = b;
        break;
      }
      while (++i < n) if ((b = array[i]) != null && a > b) a = b;
    } else {
      while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
        a = b;
        break;
      }
      while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b;
    }
    return a;
  };
  d3.max = function(array, f) {
    var i = -1, n = array.length, a, b;
    if (arguments.length === 1) {
      while (++i < n) if ((b = array[i]) != null && b >= b) {
        a = b;
        break;
      }
      while (++i < n) if ((b = array[i]) != null && b > a) a = b;
    } else {
      while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
        a = b;
        break;
      }
      while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b;
    }
    return a;
  };
  d3.extent = function(array, f) {
    var i = -1, n = array.length, a, b, c;
    if (arguments.length === 1) {
      while (++i < n) if ((b = array[i]) != null && b >= b) {
        a = c = b;
        break;
      }
      while (++i < n) if ((b = array[i]) != null) {
        if (a > b) a = b;
        if (c < b) c = b;
      }
    } else {
      while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
        a = c = b;
        break;
      }
      while (++i < n) if ((b = f.call(array, array[i], i)) != null) {
        if (a > b) a = b;
        if (c < b) c = b;
      }
    }
    return [ a, c ];
  };
  function d3_number(x) {
    return x === null ? NaN : +x;
  }
  function d3_numeric(x) {
    return !isNaN(x);
  }
  d3.sum = function(array, f) {
    var s = 0, n = array.length, a, i = -1;
    if (arguments.length === 1) {
      while (++i < n) if (d3_numeric(a = +array[i])) s += a;
    } else {
      while (++i < n) if (d3_numeric(a = +f.call(array, array[i], i))) s += a;
    }
    return s;
  };
  d3.mean = function(array, f) {
    var s = 0, n = array.length, a, i = -1, j = n;
    if (arguments.length === 1) {
      while (++i < n) if (d3_numeric(a = d3_number(array[i]))) s += a; else --j;
    } else {
      while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) s += a; else --j;
    }
    if (j) return s / j;
  };
  d3.quantile = function(values, p) {
    var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h;
    return e ? v + e * (values[h] - v) : v;
  };
  d3.median = function(array, f) {
    var numbers = [], n = array.length, a, i = -1;
    if (arguments.length === 1) {
      while (++i < n) if (d3_numeric(a = d3_number(array[i]))) numbers.push(a);
    } else {
      while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) numbers.push(a);
    }
    if (numbers.length) return d3.quantile(numbers.sort(d3_ascending), .5);
  };
  d3.variance = function(array, f) {
    var n = array.length, m = 0, a, d, s = 0, i = -1, j = 0;
    if (arguments.length === 1) {
      while (++i < n) {
        if (d3_numeric(a = d3_number(array[i]))) {
          d = a - m;
          m += d / ++j;
          s += d * (a - m);
        }
      }
    } else {
      while (++i < n) {
        if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) {
          d = a - m;
          m += d / ++j;
          s += d * (a - m);
        }
      }
    }
    if (j > 1) return s / (j - 1);
  };
  d3.deviation = function() {
    var v = d3.variance.apply(this, arguments);
    return v ? Math.sqrt(v) : v;
  };
  function d3_bisector(compare) {
    return {
      left: function(a, x, lo, hi) {
        if (arguments.length < 3) lo = 0;
        if (arguments.length < 4) hi = a.length;
        while (lo < hi) {
          var mid = lo + hi >>> 1;
          if (compare(a[mid], x) < 0) lo = mid + 1; else hi = mid;
        }
        return lo;
      },
      right: function(a, x, lo, hi) {
        if (arguments.length < 3) lo = 0;
        if (arguments.length < 4) hi = a.length;
        while (lo < hi) {
          var mid = lo + hi >>> 1;
          if (compare(a[mid], x) > 0) hi = mid; else lo = mid + 1;
        }
        return lo;
      }
    };
  }
  var d3_bisect = d3_bisector(d3_ascending);
  d3.bisectLeft = d3_bisect.left;
  d3.bisect = d3.bisectRight = d3_bisect.right;
  d3.bisector = function(f) {
    return d3_bisector(f.length === 1 ? function(d, x) {
      return d3_ascending(f(d), x);
    } : f);
  };
  d3.shuffle = function(array, i0, i1) {
    if ((m = arguments.length) < 3) {
      i1 = array.length;
      if (m < 2) i0 = 0;
    }
    var m = i1 - i0, t, i;
    while (m) {
      i = Math.random() * m-- | 0;
      t = array[m + i0], array[m + i0] = array[i + i0], array[i + i0] = t;
    }
    return array;
  };
  d3.permute = function(array, indexes) {
    var i = indexes.length, permutes = new Array(i);
    while (i--) permutes[i] = array[indexes[i]];
    return permutes;
  };
  d3.pairs = function(array) {
    var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n);
    while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ];
    return pairs;
  };
  d3.transpose = function(matrix) {
    if (!(n = matrix.length)) return [];
    for (var i = -1, m = d3.min(matrix, d3_transposeLength), transpose = new Array(m); ++i < m; ) {
      for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n; ) {
        row[j] = matrix[j][i];
      }
    }
    return transpose;
  };
  function d3_transposeLength(d) {
    return d.length;
  }
  d3.zip = function() {
    return d3.transpose(arguments);
  };
  d3.keys = function(map) {
    var keys = [];
    for (var key in map) keys.push(key);
    return keys;
  };
  d3.values = function(map) {
    var values = [];
    for (var key in map) values.push(map[key]);
    return values;
  };
  d3.entries = function(map) {
    var entries = [];
    for (var key in map) entries.push({
      key: key,
      value: map[key]
    });
    return entries;
  };
  d3.merge = function(arrays) {
    var n = arrays.length, m, i = -1, j = 0, merged, array;
    while (++i < n) j += arrays[i].length;
    merged = new Array(j);
    while (--n >= 0) {
      array = arrays[n];
      m = array.length;
      while (--m >= 0) {
        merged[--j] = array[m];
      }
    }
    return merged;
  };
  var abs = Math.abs;
  d3.range = function(start, stop, step) {
    if (arguments.length < 3) {
      step = 1;
      if (arguments.length < 2) {
        stop = start;
        start = 0;
      }
    }
    if ((stop - start) / step === Infinity) throw new Error("infinite range");
    var range = [], k = d3_range_integerScale(abs(step)), i = -1, j;
    start *= k, stop *= k, step *= k;
    if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k);
    return range;
  };
  function d3_range_integerScale(x) {
    var k = 1;
    while (x * k % 1) k *= 10;
    return k;
  }
  function d3_class(ctor, properties) {
    for (var key in properties) {
      Object.defineProperty(ctor.prototype, key, {
        value: properties[key],
        enumerable: false
      });
    }
  }
  d3.map = function(object, f) {
    var map = new d3_Map();
    if (object instanceof d3_Map) {
      object.forEach(function(key, value) {
        map.set(key, value);
      });
    } else if (Array.isArray(object)) {
      var i = -1, n = object.length, o;
      if (arguments.length === 1) while (++i < n) map.set(i, object[i]); else while (++i < n) map.set(f.call(object, o = object[i], i), o);
    } else {
      for (var key in object) map.set(key, object[key]);
    }
    return map;
  };
  function d3_Map() {
    this._ = Object.create(null);
  }
  var d3_map_proto = "__proto__", d3_map_zero = "\x00";
  d3_class(d3_Map, {
    has: d3_map_has,
    get: function(key) {
      return this._[d3_map_escape(key)];
    },
    set: function(key, value) {
      return this._[d3_map_escape(key)] = value;
    },
    remove: d3_map_remove,
    keys: d3_map_keys,
    values: function() {
      var values = [];
      for (var key in this._) values.push(this._[key]);
      return values;
    },
    entries: function() {
      var entries = [];
      for (var key in this._) entries.push({
        key: d3_map_unescape(key),
        value: this._[key]
      });
      return entries;
    },
    size: d3_map_size,
    empty: d3_map_empty,
    forEach: function(f) {
      for (var key in this._) f.call(this, d3_map_unescape(key), this._[key]);
    }
  });
  function d3_map_escape(key) {
    return (key += "") === d3_map_proto || key[0] === d3_map_zero ? d3_map_zero + key : key;
  }
  function d3_map_unescape(key) {
    return (key += "")[0] === d3_map_zero ? key.slice(1) : key;
  }
  function d3_map_has(key) {
    return d3_map_escape(key) in this._;
  }
  function d3_map_remove(key) {
    return (key = d3_map_escape(key)) in this._ && delete this._[key];
  }
  function d3_map_keys() {
    var keys = [];
    for (var key in this._) keys.push(d3_map_unescape(key));
    return keys;
  }
  function d3_map_size() {
    var size = 0;
    for (var key in this._) ++size;
    return size;
  }
  function d3_map_empty() {
    for (var key in this._) return false;
    return true;
  }
  d3.nest = function() {
    var nest = {}, keys = [], sortKeys = [], sortValues, rollup;
    function map(mapType, array, depth) {
      if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array;
      var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values;
      while (++i < n) {
        if (values = valuesByKey.get(keyValue = key(object = array[i]))) {
          values.push(object);
        } else {
          valuesByKey.set(keyValue, [ object ]);
        }
      }
      if (mapType) {
        object = mapType();
        setter = function(keyValue, values) {
          object.set(keyValue, map(mapType, values, depth));
        };
      } else {
        object = {};
        setter = function(keyValue, values) {
          object[keyValue] = map(mapType, values, depth);
        };
      }
      valuesByKey.forEach(setter);
      return object;
    }
    function entries(map, depth) {
      if (depth >= keys.length) return map;
      var array = [], sortKey = sortKeys[depth++];
      map.forEach(function(key, keyMap) {
        array.push({
          key: key,
          values: entries(keyMap, depth)
        });
      });
      return sortKey ? array.sort(function(a, b) {
        return sortKey(a.key, b.key);
      }) : array;
    }
    nest.map = function(array, mapType) {
      return map(mapType, array, 0);
    };
    nest.entries = function(array) {
      return entries(map(d3.map, array, 0), 0);
    };
    nest.key = function(d) {
      keys.push(d);
      return nest;
    };
    nest.sortKeys = function(order) {
      sortKeys[keys.length - 1] = order;
      return nest;
    };
    nest.sortValues = function(order) {
      sortValues = order;
      return nest;
    };
    nest.rollup = function(f) {
      rollup = f;
      return nest;
    };
    return nest;
  };
  d3.set = function(array) {
    var set = new d3_Set();
    if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]);
    return set;
  };
  function d3_Set() {
    this._ = Object.create(null);
  }
  d3_class(d3_Set, {
    has: d3_map_has,
    add: function(key) {
      this._[d3_map_escape(key += "")] = true;
      return key;
    },
    remove: d3_map_remove,
    values: d3_map_keys,
    size: d3_map_size,
    empty: d3_map_empty,
    forEach: function(f) {
      for (var key in this._) f.call(this, d3_map_unescape(key));
    }
  });
  d3.behavior = {};
  function d3_identity(d) {
    return d;
  }
  d3.rebind = function(target, source) {
    var i = 1, n = arguments.length, method;
    while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]);
    return target;
  };
  function d3_rebind(target, source, method) {
    return function() {
      var value = method.apply(source, arguments);
      return value === source ? target : value;
    };
  }
  function d3_vendorSymbol(object, name) {
    if (name in object) return name;
    name = name.charAt(0).toUpperCase() + name.slice(1);
    for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) {
      var prefixName = d3_vendorPrefixes[i] + name;
      if (prefixName in object) return prefixName;
    }
  }
  var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ];
  function d3_noop() {}
  d3.dispatch = function() {
    var dispatch = new d3_dispatch(), i = -1, n = arguments.length;
    while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch);
    return dispatch;
  };
  function d3_dispatch() {}
  d3_dispatch.prototype.on = function(type, listener) {
    var i = type.indexOf("."), name = "";
    if (i >= 0) {
      name = type.slice(i + 1);
      type = type.slice(0, i);
    }
    if (type) return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener);
    if (arguments.length === 2) {
      if (listener == null) for (type in this) {
        if (this.hasOwnProperty(type)) this[type].on(name, null);
      }
      return this;
    }
  };
  function d3_dispatch_event(dispatch) {
    var listeners = [], listenerByName = new d3_Map();
    function event() {
      var z = listeners, i = -1, n = z.length, l;
      while (++i < n) if (l = z[i].on) l.apply(this, arguments);
      return dispatch;
    }
    event.on = function(name, listener) {
      var l = listenerByName.get(name), i;
      if (arguments.length < 2) return l && l.on;
      if (l) {
        l.on = null;
        listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1));
        listenerByName.remove(name);
      }
      if (listener) listeners.push(listenerByName.set(name, {
        on: listener
      }));
      return dispatch;
    };
    return event;
  }
  d3.event = null;
  function d3_eventPreventDefault() {
    d3.event.preventDefault();
  }
  function d3_eventSource() {
    var e = d3.event, s;
    while (s = e.sourceEvent) e = s;
    return e;
  }
  function d3_eventDispatch(target) {
    var dispatch = new d3_dispatch(), i = 0, n = arguments.length;
    while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch);
    dispatch.of = function(thiz, argumentz) {
      return function(e1) {
        try {
          var e0 = e1.sourceEvent = d3.event;
          e1.target = target;
          d3.event = e1;
          dispatch[e1.type].apply(thiz, argumentz);
        } finally {
          d3.event = e0;
        }
      };
    };
    return dispatch;
  }
  d3.requote = function(s) {
    return s.replace(d3_requote_re, "\\$&");
  };
  var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;
  var d3_subclass = {}.__proto__ ? function(object, prototype) {
    object.__proto__ = prototype;
  } : function(object, prototype) {
    for (var property in prototype) object[property] = prototype[property];
  };
  function d3_selection(groups) {
    d3_subclass(groups, d3_selectionPrototype);
    return groups;
  }
  var d3_select = function(s, n) {
    return n.querySelector(s);
  }, d3_selectAll = function(s, n) {
    return n.querySelectorAll(s);
  }, d3_selectMatches = function(n, s) {
    var d3_selectMatcher = n.matches || n[d3_vendorSymbol(n, "matchesSelector")];
    d3_selectMatches = function(n, s) {
      return d3_selectMatcher.call(n, s);
    };
    return d3_selectMatches(n, s);
  };
  if (typeof Sizzle === "function") {
    d3_select = function(s, n) {
      return Sizzle(s, n)[0] || null;
    };
    d3_selectAll = Sizzle;
    d3_selectMatches = Sizzle.matchesSelector;
  }
  d3.selection = function() {
    return d3.select(d3_document.documentElement);
  };
  var d3_selectionPrototype = d3.selection.prototype = [];
  d3_selectionPrototype.select = function(selector) {
    var subgroups = [], subgroup, subnode, group, node;
    selector = d3_selection_selector(selector);
    for (var j = -1, m = this.length; ++j < m; ) {
      subgroups.push(subgroup = []);
      subgroup.parentNode = (group = this[j]).parentNode;
      for (var i = -1, n = group.length; ++i < n; ) {
        if (node = group[i]) {
          subgroup.push(subnode = selector.call(node, node.__data__, i, j));
          if (subnode && "__data__" in node) subnode.__data__ = node.__data__;
        } else {
          subgroup.push(null);
        }
      }
    }
    return d3_selection(subgroups);
  };
  function d3_selection_selector(selector) {
    return typeof selector === "function" ? selector : function() {
      return d3_select(selector, this);
    };
  }
  d3_selectionPrototype.selectAll = function(selector) {
    var subgroups = [], subgroup, node;
    selector = d3_selection_selectorAll(selector);
    for (var j = -1, m = this.length; ++j < m; ) {
      for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
        if (node = group[i]) {
          subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j)));
          subgroup.parentNode = node;
        }
      }
    }
    return d3_selection(subgroups);
  };
  function d3_selection_selectorAll(selector) {
    return typeof selector === "function" ? selector : function() {
      return d3_selectAll(selector, this);
    };
  }
  var d3_nsXhtml = "http://www.w3.org/1999/xhtml";
  var d3_nsPrefix = {
    svg: "http://www.w3.org/2000/svg",
    xhtml: d3_nsXhtml,
    xlink: "http://www.w3.org/1999/xlink",
    xml: "http://www.w3.org/XML/1998/namespace",
    xmlns: "http://www.w3.org/2000/xmlns/"
  };
  d3.ns = {
    prefix: d3_nsPrefix,
    qualify: function(name) {
      var i = name.indexOf(":"), prefix = name;
      if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1);
      return d3_nsPrefix.hasOwnProperty(prefix) ? {
        space: d3_nsPrefix[prefix],
        local: name
      } : name;
    }
  };
  d3_selectionPrototype.attr = function(name, value) {
    if (arguments.length < 2) {
      if (typeof name === "string") {
        var node = this.node();
        name = d3.ns.qualify(name);
        return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name);
      }
      for (value in name) this.each(d3_selection_attr(value, name[value]));
      return this;
    }
    return this.each(d3_selection_attr(name, value));
  };
  function d3_selection_attr(name, value) {
    name = d3.ns.qualify(name);
    function attrNull() {
      this.removeAttribute(name);
    }
    function attrNullNS() {
      this.removeAttributeNS(name.space, name.local);
    }
    function attrConstant() {
      this.setAttribute(name, value);
    }
    function attrConstantNS() {
      this.setAttributeNS(name.space, name.local, value);
    }
    function attrFunction() {
      var x = value.apply(this, arguments);
      if (x == null) this.removeAttribute(name); else this.setAttribute(name, x);
    }
    function attrFunctionNS() {
      var x = value.apply(this, arguments);
      if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x);
    }
    return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant;
  }
  function d3_collapse(s) {
    return s.trim().replace(/\s+/g, " ");
  }
  d3_selectionPrototype.classed = function(name, value) {
    if (arguments.length < 2) {
      if (typeof name === "string") {
        var node = this.node(), n = (name = d3_selection_classes(name)).length, i = -1;
        if (value = node.classList) {
          while (++i < n) if (!value.contains(name[i])) return false;
        } else {
          value = node.getAttribute("class");
          while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false;
        }
        return true;
      }
      for (value in name) this.each(d3_selection_classed(value, name[value]));
      return this;
    }
    return this.each(d3_selection_classed(name, value));
  };
  function d3_selection_classedRe(name) {
    return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g");
  }
  function d3_selection_classes(name) {
    return (name + "").trim().split(/^|\s+/);
  }
  function d3_selection_classed(name, value) {
    name = d3_selection_classes(name).map(d3_selection_classedName);
    var n = name.length;
    function classedConstant() {
      var i = -1;
      while (++i < n) name[i](this, value);
    }
    function classedFunction() {
      var i = -1, x = value.apply(this, arguments);
      while (++i < n) name[i](this, x);
    }
    return typeof value === "function" ? classedFunction : classedConstant;
  }
  function d3_selection_classedName(name) {
    var re = d3_selection_classedRe(name);
    return function(node, value) {
      if (c = node.classList) return value ? c.add(name) : c.remove(name);
      var c = node.getAttribute("class") || "";
      if (value) {
        re.lastIndex = 0;
        if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name));
      } else {
        node.setAttribute("class", d3_collapse(c.replace(re, " ")));
      }
    };
  }
  d3_selectionPrototype.style = function(name, value, priority) {
    var n = arguments.length;
    if (n < 3) {
      if (typeof name !== "string") {
        if (n < 2) value = "";
        for (priority in name) this.each(d3_selection_style(priority, name[priority], value));
        return this;
      }
      if (n < 2) {
        var node = this.node();
        return d3_window(node).getComputedStyle(node, null).getPropertyValue(name);
      }
      priority = "";
    }
    return this.each(d3_selection_style(name, value, priority));
  };
  function d3_selection_style(name, value, priority) {
    function styleNull() {
      this.style.removeProperty(name);
    }
    function styleConstant() {
      this.style.setProperty(name, value, priority);
    }
    function styleFunction() {
      var x = value.apply(this, arguments);
      if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority);
    }
    return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant;
  }
  d3_selectionPrototype.property = function(name, value) {
    if (arguments.length < 2) {
      if (typeof name === "string") return this.node()[name];
      for (value in name) this.each(d3_selection_property(value, name[value]));
      return this;
    }
    return this.each(d3_selection_property(name, value));
  };
  function d3_selection_property(name, value) {
    function propertyNull() {
      delete this[name];
    }
    function propertyConstant() {
      this[name] = value;
    }
    function propertyFunction() {
      var x = value.apply(this, arguments);
      if (x == null) delete this[name]; else this[name] = x;
    }
    return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant;
  }
  d3_selectionPrototype.text = function(value) {
    return arguments.length ? this.each(typeof value === "function" ? function() {
      var v = value.apply(this, arguments);
      this.textContent = v == null ? "" : v;
    } : value == null ? function() {
      this.textContent = "";
    } : function() {
      this.textContent = value;
    }) : this.node().textContent;
  };
  d3_selectionPrototype.html = function(value) {
    return arguments.length ? this.each(typeof value === "function" ? function() {
      var v = value.apply(this, arguments);
      this.innerHTML = v == null ? "" : v;
    } : value == null ? function() {
      this.innerHTML = "";
    } : function() {
      this.innerHTML = value;
    }) : this.node().innerHTML;
  };
  d3_selectionPrototype.append = function(name) {
    name = d3_selection_creator(name);
    return this.select(function() {
      return this.appendChild(name.apply(this, arguments));
    });
  };
  function d3_selection_creator(name) {
    function create() {
      var document = this.ownerDocument, namespace = this.namespaceURI;
      return namespace === d3_nsXhtml && document.documentElement.namespaceURI === d3_nsXhtml ? document.createElement(name) : document.createElementNS(namespace, name);
    }
    function createNS() {
      return this.ownerDocument.createElementNS(name.space, name.local);
    }
    return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? createNS : create;
  }
  d3_selectionPrototype.insert = function(name, before) {
    name = d3_selection_creator(name);
    before = d3_selection_selector(before);
    return this.select(function() {
      return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null);
    });
  };
  d3_selectionPrototype.remove = function() {
    return this.each(d3_selectionRemove);
  };
  function d3_selectionRemove() {
    var parent = this.parentNode;
    if (parent) parent.removeChild(this);
  }
  d3_selectionPrototype.data = function(value, key) {
    var i = -1, n = this.length, group, node;
    if (!arguments.length) {
      value = new Array(n = (group = this[0]).length);
      while (++i < n) {
        if (node = group[i]) {
          value[i] = node.__data__;
        }
      }
      return value;
    }
    function bind(group, groupData) {
      var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData;
      if (key) {
        var nodeByKeyValue = new d3_Map(), keyValues = new Array(n), keyValue;
        for (i = -1; ++i < n; ) {
          if (node = group[i]) {
            if (nodeByKeyValue.has(keyValue = key.call(node, node.__data__, i))) {
              exitNodes[i] = node;
            } else {
              nodeByKeyValue.set(keyValue, node);
            }
            keyValues[i] = keyValue;
          }
        }
        for (i = -1; ++i < m; ) {
          if (!(node = nodeByKeyValue.get(keyValue = key.call(groupData, nodeData = groupData[i], i)))) {
            enterNodes[i] = d3_selection_dataNode(nodeData);
          } else if (node !== true) {
            updateNodes[i] = node;
            node.__data__ = nodeData;
          }
          nodeByKeyValue.set(keyValue, true);
        }
        for (i = -1; ++i < n; ) {
          if (i in keyValues && nodeByKeyValue.get(keyValues[i]) !== true) {
            exitNodes[i] = group[i];
          }
        }
      } else {
        for (i = -1; ++i < n0; ) {
          node = group[i];
          nodeData = groupData[i];
          if (node) {
            node.__data__ = nodeData;
            updateNodes[i] = node;
          } else {
            enterNodes[i] = d3_selection_dataNode(nodeData);
          }
        }
        for (;i < m; ++i) {
          enterNodes[i] = d3_selection_dataNode(groupData[i]);
        }
        for (;i < n; ++i) {
          exitNodes[i] = group[i];
        }
      }
      enterNodes.update = updateNodes;
      enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode;
      enter.push(enterNodes);
      update.push(updateNodes);
      exit.push(exitNodes);
    }
    var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]);
    if (typeof value === "function") {
      while (++i < n) {
        bind(group = this[i], value.call(group, group.parentNode.__data__, i));
      }
    } else {
      while (++i < n) {
        bind(group = this[i], value);
      }
    }
    update.enter = function() {
      return enter;
    };
    update.exit = function() {
      return exit;
    };
    return update;
  };
  function d3_selection_dataNode(data) {
    return {
      __data__: data
    };
  }
  d3_selectionPrototype.datum = function(value) {
    return arguments.length ? this.property("__data__", value) : this.property("__data__");
  };
  d3_selectionPrototype.filter = function(filter) {
    var subgroups = [], subgroup, group, node;
    if (typeof filter !== "function") filter = d3_selection_filter(filter);
    for (var j = 0, m = this.length; j < m; j++) {
      subgroups.push(subgroup = []);
      subgroup.parentNode = (group = this[j]).parentNode;
      for (var i = 0, n = group.length; i < n; i++) {
        if ((node = group[i]) && filter.call(node, node.__data__, i, j)) {
          subgroup.push(node);
        }
      }
    }
    return d3_selection(subgroups);
  };
  function d3_selection_filter(selector) {
    return function() {
      return d3_selectMatches(this, selector);
    };
  }
  d3_selectionPrototype.order = function() {
    for (var j = -1, m = this.length; ++j < m; ) {
      for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) {
        if (node = group[i]) {
          if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next);
          next = node;
        }
      }
    }
    return this;
  };
  d3_selectionPrototype.sort = function(comparator) {
    comparator = d3_selection_sortComparator.apply(this, arguments);
    for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator);
    return this.order();
  };
  function d3_selection_sortComparator(comparator) {
    if (!arguments.length) comparator = d3_ascending;
    return function(a, b) {
      return a && b ? comparator(a.__data__, b.__data__) : !a - !b;
    };
  }
  d3_selectionPrototype.each = function(callback) {
    return d3_selection_each(this, function(node, i, j) {
      callback.call(node, node.__data__, i, j);
    });
  };
  function d3_selection_each(groups, callback) {
    for (var j = 0, m = groups.length; j < m; j++) {
      for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) {
        if (node = group[i]) callback(node, i, j);
      }
    }
    return groups;
  }
  d3_selectionPrototype.call = function(callback) {
    var args = d3_array(arguments);
    callback.apply(args[0] = this, args);
    return this;
  };
  d3_selectionPrototype.empty = function() {
    return !this.node();
  };
  d3_selectionPrototype.node = function() {
    for (var j = 0, m = this.length; j < m; j++) {
      for (var group = this[j], i = 0, n = group.length; i < n; i++) {
        var node = group[i];
        if (node) return node;
      }
    }
    return null;
  };
  d3_selectionPrototype.size = function() {
    var n = 0;
    d3_selection_each(this, function() {
      ++n;
    });
    return n;
  };
  function d3_selection_enter(selection) {
    d3_subclass(selection, d3_selection_enterPrototype);
    return selection;
  }
  var d3_selection_enterPrototype = [];
  d3.selection.enter = d3_selection_enter;
  d3.selection.enter.prototype = d3_selection_enterPrototype;
  d3_selection_enterPrototype.append = d3_selectionPrototype.append;
  d3_selection_enterPrototype.empty = d3_selectionPrototype.empty;
  d3_selection_enterPrototype.node = d3_selectionPrototype.node;
  d3_selection_enterPrototype.call = d3_selectionPrototype.call;
  d3_selection_enterPrototype.size = d3_selectionPrototype.size;
  d3_selection_enterPrototype.select = function(selector) {
    var subgroups = [], subgroup, subnode, upgroup, group, node;
    for (var j = -1, m = this.length; ++j < m; ) {
      upgroup = (group = this[j]).update;
      subgroups.push(subgroup = []);
      subgroup.parentNode = group.parentNode;
      for (var i = -1, n = group.length; ++i < n; ) {
        if (node = group[i]) {
          subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j));
          subnode.__data__ = node.__data__;
        } else {
          subgroup.push(null);
        }
      }
    }
    return d3_selection(subgroups);
  };
  d3_selection_enterPrototype.insert = function(name, before) {
    if (arguments.length < 2) before = d3_selection_enterInsertBefore(this);
    return d3_selectionPrototype.insert.call(this, name, before);
  };
  function d3_selection_enterInsertBefore(enter) {
    var i0, j0;
    return function(d, i, j) {
      var group = enter[j].update, n = group.length, node;
      if (j != j0) j0 = j, i0 = 0;
      if (i >= i0) i0 = i + 1;
      while (!(node = group[i0]) && ++i0 < n) ;
      return node;
    };
  }
  d3.select = function(node) {
    var group;
    if (typeof node === "string") {
      group = [ d3_select(node, d3_document) ];
      group.parentNode = d3_document.documentElement;
    } else {
      group = [ node ];
      group.parentNode = d3_documentElement(node);
    }
    return d3_selection([ group ]);
  };
  d3.selectAll = function(nodes) {
    var group;
    if (typeof nodes === "string") {
      group = d3_array(d3_selectAll(nodes, d3_document));
      group.parentNode = d3_document.documentElement;
    } else {
      group = d3_array(nodes);
      group.parentNode = null;
    }
    return d3_selection([ group ]);
  };
  d3_selectionPrototype.on = function(type, listener, capture) {
    var n = arguments.length;
    if (n < 3) {
      if (typeof type !== "string") {
        if (n < 2) listener = false;
        for (capture in type) this.each(d3_selection_on(capture, type[capture], listener));
        return this;
      }
      if (n < 2) return (n = this.node()["__on" + type]) && n._;
      capture = false;
    }
    return this.each(d3_selection_on(type, listener, capture));
  };
  function d3_selection_on(type, listener, capture) {
    var name = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener;
    if (i > 0) type = type.slice(0, i);
    var filter = d3_selection_onFilters.get(type);
    if (filter) type = filter, wrap = d3_selection_onFilter;
    function onRemove() {
      var l = this[name];
      if (l) {
        this.removeEventListener(type, l, l.$);
        delete this[name];
      }
    }
    function onAdd() {
      var l = wrap(listener, d3_array(arguments));
      onRemove.call(this);
      this.addEventListener(type, this[name] = l, l.$ = capture);
      l._ = listener;
    }
    function removeAll() {
      var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match;
      for (var name in this) {
        if (match = name.match(re)) {
          var l = this[name];
          this.removeEventListener(match[1], l, l.$);
          delete this[name];
        }
      }
    }
    return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll;
  }
  var d3_selection_onFilters = d3.map({
    mouseenter: "mouseover",
    mouseleave: "mouseout"
  });
  if (d3_document) {
    d3_selection_onFilters.forEach(function(k) {
      if ("on" + k in d3_document) d3_selection_onFilters.remove(k);
    });
  }
  function d3_selection_onListener(listener, argumentz) {
    return function(e) {
      var o = d3.event;
      d3.event = e;
      argumentz[0] = this.__data__;
      try {
        listener.apply(this, argumentz);
      } finally {
        d3.event = o;
      }
    };
  }
  function d3_selection_onFilter(listener, argumentz) {
    var l = d3_selection_onListener(listener, argumentz);
    return function(e) {
      var target = this, related = e.relatedTarget;
      if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) {
        l.call(target, e);
      }
    };
  }
  var d3_event_dragSelect, d3_event_dragId = 0;
  function d3_event_dragSuppress(node) {
    var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window(node)).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault);
    if (d3_event_dragSelect == null) {
      d3_event_dragSelect = "onselectstart" in node ? false : d3_vendorSymbol(node.style, "userSelect");
    }
    if (d3_event_dragSelect) {
      var style = d3_documentElement(node).style, select = style[d3_event_dragSelect];
      style[d3_event_dragSelect] = "none";
    }
    return function(suppressClick) {
      w.on(name, null);
      if (d3_event_dragSelect) style[d3_event_dragSelect] = select;
      if (suppressClick) {
        var off = function() {
          w.on(click, null);
        };
        w.on(click, function() {
          d3_eventPreventDefault();
          off();
        }, true);
        setTimeout(off, 0);
      }
    };
  }
  d3.mouse = function(container) {
    return d3_mousePoint(container, d3_eventSource());
  };
  var d3_mouse_bug44083 = this.navigator && /WebKit/.test(this.navigator.userAgent) ? -1 : 0;
  function d3_mousePoint(container, e) {
    if (e.changedTouches) e = e.changedTouches[0];
    var svg = container.ownerSVGElement || container;
    if (svg.createSVGPoint) {
      var point = svg.createSVGPoint();
      if (d3_mouse_bug44083 < 0) {
        var window = d3_window(container);
        if (window.scrollX || window.scrollY) {
          svg = d3.select("body").append("svg").style({
            position: "absolute",
            top: 0,
            left: 0,
            margin: 0,
            padding: 0,
            border: "none"
          }, "important");
          var ctm = svg[0][0].getScreenCTM();
          d3_mouse_bug44083 = !(ctm.f || ctm.e);
          svg.remove();
        }
      }
      if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; else point.x = e.clientX, 
      point.y = e.clientY;
      point = point.matrixTransform(container.getScreenCTM().inverse());
      return [ point.x, point.y ];
    }
    var rect = container.getBoundingClientRect();
    return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ];
  }
  d3.touch = function(container, touches, identifier) {
    if (arguments.length < 3) identifier = touches, touches = d3_eventSource().changedTouches;
    if (touches) for (var i = 0, n = touches.length, touch; i < n; ++i) {
      if ((touch = touches[i]).identifier === identifier) {
        return d3_mousePoint(container, touch);
      }
    }
  };
  d3.behavior.drag = function() {
    var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, d3_window, "mousemove", "mouseup"), touchstart = dragstart(d3_behavior_dragTouchId, d3.touch, d3_identity, "touchmove", "touchend");
    function drag() {
      this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart);
    }
    function dragstart(id, position, subject, move, end) {
      return function() {
        var that = this, target = d3.event.target.correspondingElement || d3.event.target, parent = that.parentNode, dispatch = event.of(that, arguments), dragged = 0, dragId = id(), dragName = ".drag" + (dragId == null ? "" : "-" + dragId), dragOffset, dragSubject = d3.select(subject(target)).on(move + dragName, moved).on(end + dragName, ended), dragRestore = d3_event_dragSuppress(target), position0 = position(parent, dragId);
        if (origin) {
          dragOffset = origin.apply(that, arguments);
          dragOffset = [ dragOffset.x - position0[0], dragOffset.y - position0[1] ];
        } else {
          dragOffset = [ 0, 0 ];
        }
        dispatch({
          type: "dragstart"
        });
        function moved() {
          var position1 = position(parent, dragId), dx, dy;
          if (!position1) return;
          dx = position1[0] - position0[0];
          dy = position1[1] - position0[1];
          dragged |= dx | dy;
          position0 = position1;
          dispatch({
            type: "drag",
            x: position1[0] + dragOffset[0],
            y: position1[1] + dragOffset[1],
            dx: dx,
            dy: dy
          });
        }
        function ended() {
          if (!position(parent, dragId)) return;
          dragSubject.on(move + dragName, null).on(end + dragName, null);
          dragRestore(dragged);
          dispatch({
            type: "dragend"
          });
        }
      };
    }
    drag.origin = function(x) {
      if (!arguments.length) return origin;
      origin = x;
      return drag;
    };
    return d3.rebind(drag, event, "on");
  };
  function d3_behavior_dragTouchId() {
    return d3.event.changedTouches[0].identifier;
  }
  d3.touches = function(container, touches) {
    if (arguments.length < 2) touches = d3_eventSource().touches;
    return touches ? d3_array(touches).map(function(touch) {
      var point = d3_mousePoint(container, touch);
      point.identifier = touch.identifier;
      return point;
    }) : [];
  };
  var ε = 1e-6, ε2 = ε * ε, π = Math.PI, τ = 2 * π, τε = τ - ε, halfπ = π / 2, d3_radians = π / 180, d3_degrees = 180 / π;
  function d3_sgn(x) {
    return x > 0 ? 1 : x < 0 ? -1 : 0;
  }
  function d3_cross2d(a, b, c) {
    return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
  }
  function d3_acos(x) {
    return x > 1 ? 0 : x < -1 ? π : Math.acos(x);
  }
  function d3_asin(x) {
    return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x);
  }
  function d3_sinh(x) {
    return ((x = Math.exp(x)) - 1 / x) / 2;
  }
  function d3_cosh(x) {
    return ((x = Math.exp(x)) + 1 / x) / 2;
  }
  function d3_tanh(x) {
    return ((x = Math.exp(2 * x)) - 1) / (x + 1);
  }
  function d3_haversin(x) {
    return (x = Math.sin(x / 2)) * x;
  }
  var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4;
  d3.interpolateZoom = function(p0, p1) {
    var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S;
    if (d2 < ε2) {
      S = Math.log(w1 / w0) / ρ;
      i = function(t) {
        return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * t * S) ];
      };
    } else {
      var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);
      S = (r1 - r0) / ρ;
      i = function(t) {
        var s = t * S, coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0));
        return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0) ];
      };
    }
    i.duration = S * 1e3;
    return i;
  };
  d3.behavior.zoom = function() {
    var view = {
      x: 0,
      y: 0,
      k: 1
    }, translate0, center0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, duration = 250, zooming = 0, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1;
    if (!d3_behavior_zoomWheel) {
      d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() {
        return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1);
      }, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() {
        return d3.event.wheelDelta;
      }, "mousewheel") : (d3_behavior_zoomDelta = function() {
        return -d3.event.detail;
      }, "MozMousePixelScroll");
    }
    function zoom(g) {
      g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted);
    }
    zoom.event = function(g) {
      g.each(function() {
        var dispatch = event.of(this, arguments), view1 = view;
        if (d3_transitionInheritId) {
          d3.select(this).transition().each("start.zoom", function() {
            view = this.__chart__ || {
              x: 0,
              y: 0,
              k: 1
            };
            zoomstarted(dispatch);
          }).tween("zoom:zoom", function() {
            var dx = size[0], dy = size[1], cx = center0 ? center0[0] : dx / 2, cy = center0 ? center0[1] : dy / 2, i = d3.interpolateZoom([ (cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k ], [ (cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k ]);
            return function(t) {
              var l = i(t), k = dx / l[2];
              this.__chart__ = view = {
                x: cx - l[0] * k,
                y: cy - l[1] * k,
                k: k
              };
              zoomed(dispatch);
            };
          }).each("interrupt.zoom", function() {
            zoomended(dispatch);
          }).each("end.zoom", function() {
            zoomended(dispatch);
          });
        } else {
          this.__chart__ = view;
          zoomstarted(dispatch);
          zoomed(dispatch);
          zoomended(dispatch);
        }
      });
    };
    zoom.translate = function(_) {
      if (!arguments.length) return [ view.x, view.y ];
      view = {
        x: +_[0],
        y: +_[1],
        k: view.k
      };
      rescale();
      return zoom;
    };
    zoom.scale = function(_) {
      if (!arguments.length) return view.k;
      view = {
        x: view.x,
        y: view.y,
        k: null
      };
      scaleTo(+_);
      rescale();
      return zoom;
    };
    zoom.scaleExtent = function(_) {
      if (!arguments.length) return scaleExtent;
      scaleExtent = _ == null ? d3_behavior_zoomInfinity : [ +_[0], +_[1] ];
      return zoom;
    };
    zoom.center = function(_) {
      if (!arguments.length) return center;
      center = _ && [ +_[0], +_[1] ];
      return zoom;
    };
    zoom.size = function(_) {
      if (!arguments.length) return size;
      size = _ && [ +_[0], +_[1] ];
      return zoom;
    };
    zoom.duration = function(_) {
      if (!arguments.length) return duration;
      duration = +_;
      return zoom;
    };
    zoom.x = function(z) {
      if (!arguments.length) return x1;
      x1 = z;
      x0 = z.copy();
      view = {
        x: 0,
        y: 0,
        k: 1
      };
      return zoom;
    };
    zoom.y = function(z) {
      if (!arguments.length) return y1;
      y1 = z;
      y0 = z.copy();
      view = {
        x: 0,
        y: 0,
        k: 1
      };
      return zoom;
    };
    function location(p) {
      return [ (p[0] - view.x) / view.k, (p[1] - view.y) / view.k ];
    }
    function point(l) {
      return [ l[0] * view.k + view.x, l[1] * view.k + view.y ];
    }
    function scaleTo(s) {
      view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s));
    }
    function translateTo(p, l) {
      l = point(l);
      view.x += p[0] - l[0];
      view.y += p[1] - l[1];
    }
    function zoomTo(that, p, l, k) {
      that.__chart__ = {
        x: view.x,
        y: view.y,
        k: view.k
      };
      scaleTo(Math.pow(2, k));
      translateTo(center0 = p, l);
      that = d3.select(that);
      if (duration > 0) that = that.transition().duration(duration);
      that.call(zoom.event);
    }
    function rescale() {
      if (x1) x1.domain(x0.range().map(function(x) {
        return (x - view.x) / view.k;
      }).map(x0.invert));
      if (y1) y1.domain(y0.range().map(function(y) {
        return (y - view.y) / view.k;
      }).map(y0.invert));
    }
    function zoomstarted(dispatch) {
      if (!zooming++) dispatch({
        type: "zoomstart"
      });
    }
    function zoomed(dispatch) {
      rescale();
      dispatch({
        type: "zoom",
        scale: view.k,
        translate: [ view.x, view.y ]
      });
    }
    function zoomended(dispatch) {
      if (!--zooming) dispatch({
        type: "zoomend"
      }), center0 = null;
    }
    function mousedowned() {
      var that = this, dispatch = event.of(that, arguments), dragged = 0, subject = d3.select(d3_window(that)).on(mousemove, moved).on(mouseup, ended), location0 = location(d3.mouse(that)), dragRestore = d3_event_dragSuppress(that);
      d3_selection_interrupt.call(that);
      zoomstarted(dispatch);
      function moved() {
        dragged = 1;
        translateTo(d3.mouse(that), location0);
        zoomed(dispatch);
      }
      function ended() {
        subject.on(mousemove, null).on(mouseup, null);
        dragRestore(dragged);
        zoomended(dispatch);
      }
    }
    function touchstarted() {
      var that = this, dispatch = event.of(that, arguments), locations0 = {}, distance0 = 0, scale0, zoomName = ".zoom-" + d3.event.changedTouches[0].identifier, touchmove = "touchmove" + zoomName, touchend = "touchend" + zoomName, targets = [], subject = d3.select(that), dragRestore = d3_event_dragSuppress(that);
      started();
      zoomstarted(dispatch);
      subject.on(mousedown, null).on(touchstart, started);
      function relocate() {
        var touches = d3.touches(that);
        scale0 = view.k;
        touches.forEach(function(t) {
          if (t.identifier in locations0) locations0[t.identifier] = location(t);
        });
        return touches;
      }
      function started() {
        var target = d3.event.target;
        d3.select(target).on(touchmove, moved).on(touchend, ended);
        targets.push(target);
        var changed = d3.event.changedTouches;
        for (var i = 0, n = changed.length; i < n; ++i) {
          locations0[changed[i].identifier] = null;
        }
        var touches = relocate(), now = Date.now();
        if (touches.length === 1) {
          if (now - touchtime < 500) {
            var p = touches[0];
            zoomTo(that, p, locations0[p.identifier], Math.floor(Math.log(view.k) / Math.LN2) + 1);
            d3_eventPreventDefault();
          }
          touchtime = now;
        } else if (touches.length > 1) {
          var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1];
          distance0 = dx * dx + dy * dy;
        }
      }
      function moved() {
        var touches = d3.touches(that), p0, l0, p1, l1;
        d3_selection_interrupt.call(that);
        for (var i = 0, n = touches.length; i < n; ++i, l1 = null) {
          p1 = touches[i];
          if (l1 = locations0[p1.identifier]) {
            if (l0) break;
            p0 = p1, l0 = l1;
          }
        }
        if (l1) {
          var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0);
          p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ];
          l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ];
          scaleTo(scale1 * scale0);
        }
        touchtime = null;
        translateTo(p0, l0);
        zoomed(dispatch);
      }
      function ended() {
        if (d3.event.touches.length) {
          var changed = d3.event.changedTouches;
          for (var i = 0, n = changed.length; i < n; ++i) {
            delete locations0[changed[i].identifier];
          }
          for (var identifier in locations0) {
            return void relocate();
          }
        }
        d3.selectAll(targets).on(zoomName, null);
        subject.on(mousedown, mousedowned).on(touchstart, touchstarted);
        dragRestore();
        zoomended(dispatch);
      }
    }
    function mousewheeled() {
      var dispatch = event.of(this, arguments);
      if (mousewheelTimer) clearTimeout(mousewheelTimer); else d3_selection_interrupt.call(this), 
      translate0 = location(center0 = center || d3.mouse(this)), zoomstarted(dispatch);
      mousewheelTimer = setTimeout(function() {
        mousewheelTimer = null;
        zoomended(dispatch);
      }, 50);
      d3_eventPreventDefault();
      scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k);
      translateTo(center0, translate0);
      zoomed(dispatch);
    }
    function dblclicked() {
      var p = d3.mouse(this), k = Math.log(view.k) / Math.LN2;
      zoomTo(this, p, location(p), d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1);
    }
    return d3.rebind(zoom, event, "on");
  };
  var d3_behavior_zoomInfinity = [ 0, Infinity ], d3_behavior_zoomDelta, d3_behavior_zoomWheel;
  d3.color = d3_color;
  function d3_color() {}
  d3_color.prototype.toString = function() {
    return this.rgb() + "";
  };
  d3.hsl = d3_hsl;
  function d3_hsl(h, s, l) {
    return this instanceof d3_hsl ? void (this.h = +h, this.s = +s, this.l = +l) : arguments.length < 2 ? h instanceof d3_hsl ? new d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : new d3_hsl(h, s, l);
  }
  var d3_hslPrototype = d3_hsl.prototype = new d3_color();
  d3_hslPrototype.brighter = function(k) {
    k = Math.pow(.7, arguments.length ? k : 1);
    return new d3_hsl(this.h, this.s, this.l / k);
  };
  d3_hslPrototype.darker = function(k) {
    k = Math.pow(.7, arguments.length ? k : 1);
    return new d3_hsl(this.h, this.s, k * this.l);
  };
  d3_hslPrototype.rgb = function() {
    return d3_hsl_rgb(this.h, this.s, this.l);
  };
  function d3_hsl_rgb(h, s, l) {
    var m1, m2;
    h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h;
    s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s;
    l = l < 0 ? 0 : l > 1 ? 1 : l;
    m2 = l <= .5 ? l * (1 + s) : l + s - l * s;
    m1 = 2 * l - m2;
    function v(h) {
      if (h > 360) h -= 360; else if (h < 0) h += 360;
      if (h < 60) return m1 + (m2 - m1) * h / 60;
      if (h < 180) return m2;
      if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60;
      return m1;
    }
    function vv(h) {
      return Math.round(v(h) * 255);
    }
    return new d3_rgb(vv(h + 120), vv(h), vv(h - 120));
  }
  d3.hcl = d3_hcl;
  function d3_hcl(h, c, l) {
    return this instanceof d3_hcl ? void (this.h = +h, this.c = +c, this.l = +l) : arguments.length < 2 ? h instanceof d3_hcl ? new d3_hcl(h.h, h.c, h.l) : h instanceof d3_lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : new d3_hcl(h, c, l);
  }
  var d3_hclPrototype = d3_hcl.prototype = new d3_color();
  d3_hclPrototype.brighter = function(k) {
    return new d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)));
  };
  d3_hclPrototype.darker = function(k) {
    return new d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)));
  };
  d3_hclPrototype.rgb = function() {
    return d3_hcl_lab(this.h, this.c, this.l).rgb();
  };
  function d3_hcl_lab(h, c, l) {
    if (isNaN(h)) h = 0;
    if (isNaN(c)) c = 0;
    return new d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c);
  }
  d3.lab = d3_lab;
  function d3_lab(l, a, b) {
    return this instanceof d3_lab ? void (this.l = +l, this.a = +a, this.b = +b) : arguments.length < 2 ? l instanceof d3_lab ? new d3_lab(l.l, l.a, l.b) : l instanceof d3_hcl ? d3_hcl_lab(l.h, l.c, l.l) : d3_rgb_lab((l = d3_rgb(l)).r, l.g, l.b) : new d3_lab(l, a, b);
  }
  var d3_lab_K = 18;
  var d3_lab_X = .95047, d3_lab_Y = 1, d3_lab_Z = 1.08883;
  var d3_labPrototype = d3_lab.prototype = new d3_color();
  d3_labPrototype.brighter = function(k) {
    return new d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b);
  };
  d3_labPrototype.darker = function(k) {
    return new d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b);
  };
  d3_labPrototype.rgb = function() {
    return d3_lab_rgb(this.l, this.a, this.b);
  };
  function d3_lab_rgb(l, a, b) {
    var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200;
    x = d3_lab_xyz(x) * d3_lab_X;
    y = d3_lab_xyz(y) * d3_lab_Y;
    z = d3_lab_xyz(z) * d3_lab_Z;
    return new d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z), d3_xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z), d3_xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z));
  }
  function d3_lab_hcl(l, a, b) {
    return l > 0 ? new d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : new d3_hcl(NaN, NaN, l);
  }
  function d3_lab_xyz(x) {
    return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037;
  }
  function d3_xyz_lab(x) {
    return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29;
  }
  function d3_xyz_rgb(r) {
    return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055));
  }
  d3.rgb = d3_rgb;
  function d3_rgb(r, g, b) {
    return this instanceof d3_rgb ? void (this.r = ~~r, this.g = ~~g, this.b = ~~b) : arguments.length < 2 ? r instanceof d3_rgb ? new d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : new d3_rgb(r, g, b);
  }
  function d3_rgbNumber(value) {
    return new d3_rgb(value >> 16, value >> 8 & 255, value & 255);
  }
  function d3_rgbString(value) {
    return d3_rgbNumber(value) + "";
  }
  var d3_rgbPrototype = d3_rgb.prototype = new d3_color();
  d3_rgbPrototype.brighter = function(k) {
    k = Math.pow(.7, arguments.length ? k : 1);
    var r = this.r, g = this.g, b = this.b, i = 30;
    if (!r && !g && !b) return new d3_rgb(i, i, i);
    if (r && r < i) r = i;
    if (g && g < i) g = i;
    if (b && b < i) b = i;
    return new d3_rgb(Math.min(255, r / k), Math.min(255, g / k), Math.min(255, b / k));
  };
  d3_rgbPrototype.darker = function(k) {
    k = Math.pow(.7, arguments.length ? k : 1);
    return new d3_rgb(k * this.r, k * this.g, k * this.b);
  };
  d3_rgbPrototype.hsl = function() {
    return d3_rgb_hsl(this.r, this.g, this.b);
  };
  d3_rgbPrototype.toString = function() {
    return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b);
  };
  function d3_rgb_hex(v) {
    return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16);
  }
  function d3_rgb_parse(format, rgb, hsl) {
    var r = 0, g = 0, b = 0, m1, m2, color;
    m1 = /([a-z]+)\((.*)\)/.exec(format = format.toLowerCase());
    if (m1) {
      m2 = m1[2].split(",");
      switch (m1[1]) {
       case "hsl":
        {
          return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100);
        }

       case "rgb":
        {
          return rgb(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2]));
        }
      }
    }
    if (color = d3_rgb_names.get(format)) {
      return rgb(color.r, color.g, color.b);
    }
    if (format != null && format.charAt(0) === "#" && !isNaN(color = parseInt(format.slice(1), 16))) {
      if (format.length === 4) {
        r = (color & 3840) >> 4;
        r = r >> 4 | r;
        g = color & 240;
        g = g >> 4 | g;
        b = color & 15;
        b = b << 4 | b;
      } else if (format.length === 7) {
        r = (color & 16711680) >> 16;
        g = (color & 65280) >> 8;
        b = color & 255;
      }
    }
    return rgb(r, g, b);
  }
  function d3_rgb_hsl(r, g, b) {
    var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2;
    if (d) {
      s = l < .5 ? d / (max + min) : d / (2 - max - min);
      if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4;
      h *= 60;
    } else {
      h = NaN;
      s = l > 0 && l < 1 ? 0 : h;
    }
    return new d3_hsl(h, s, l);
  }
  function d3_rgb_lab(r, g, b) {
    r = d3_rgb_xyz(r);
    g = d3_rgb_xyz(g);
    b = d3_rgb_xyz(b);
    var x = d3_xyz_lab((.4124564 * r + .3575761 * g + .1804375 * b) / d3_lab_X), y = d3_xyz_lab((.2126729 * r + .7151522 * g + .072175 * b) / d3_lab_Y), z = d3_xyz_lab((.0193339 * r + .119192 * g + .9503041 * b) / d3_lab_Z);
    return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z));
  }
  function d3_rgb_xyz(r) {
    return (r /= 255) <= .04045 ? r / 12.92 : Math.pow((r + .055) / 1.055, 2.4);
  }
  function d3_rgb_parseNumber(c) {
    var f = parseFloat(c);
    return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f;
  }
  var d3_rgb_names = d3.map({
    aliceblue: 15792383,
    antiquewhite: 16444375,
    aqua: 65535,
    aquamarine: 8388564,
    azure: 15794175,
    beige: 16119260,
    bisque: 16770244,
    black: 0,
    blanchedalmond: 16772045,
    blue: 255,
    blueviolet: 9055202,
    brown: 10824234,
    burlywood: 14596231,
    cadetblue: 6266528,
    chartreuse: 8388352,
    chocolate: 13789470,
    coral: 16744272,
    cornflowerblue: 6591981,
    cornsilk: 16775388,
    crimson: 14423100,
    cyan: 65535,
    darkblue: 139,
    darkcyan: 35723,
    darkgoldenrod: 12092939,
    darkgray: 11119017,
    darkgreen: 25600,
    darkgrey: 11119017,
    darkkhaki: 12433259,
    darkmagenta: 9109643,
    darkolivegreen: 5597999,
    darkorange: 16747520,
    darkorchid: 10040012,
    darkred: 9109504,
    darksalmon: 15308410,
    darkseagreen: 9419919,
    darkslateblue: 4734347,
    darkslategray: 3100495,
    darkslategrey: 3100495,
    darkturquoise: 52945,
    darkviolet: 9699539,
    deeppink: 16716947,
    deepskyblue: 49151,
    dimgray: 6908265,
    dimgrey: 6908265,
    dodgerblue: 2003199,
    firebrick: 11674146,
    floralwhite: 16775920,
    forestgreen: 2263842,
    fuchsia: 16711935,
    gainsboro: 14474460,
    ghostwhite: 16316671,
    gold: 16766720,
    goldenrod: 14329120,
    gray: 8421504,
    green: 32768,
    greenyellow: 11403055,
    grey: 8421504,
    honeydew: 15794160,
    hotpink: 16738740,
    indianred: 13458524,
    indigo: 4915330,
    ivory: 16777200,
    khaki: 15787660,
    lavender: 15132410,
    lavenderblush: 16773365,
    lawngreen: 8190976,
    lemonchiffon: 16775885,
    lightblue: 11393254,
    lightcoral: 15761536,
    lightcyan: 14745599,
    lightgoldenrodyellow: 16448210,
    lightgray: 13882323,
    lightgreen: 9498256,
    lightgrey: 13882323,
    lightpink: 16758465,
    lightsalmon: 16752762,
    lightseagreen: 2142890,
    lightskyblue: 8900346,
    lightslategray: 7833753,
    lightslategrey: 7833753,
    lightsteelblue: 11584734,
    lightyellow: 16777184,
    lime: 65280,
    limegreen: 3329330,
    linen: 16445670,
    magenta: 16711935,
    maroon: 8388608,
    mediumaquamarine: 6737322,
    mediumblue: 205,
    mediumorchid: 12211667,
    mediumpurple: 9662683,
    mediumseagreen: 3978097,
    mediumslateblue: 8087790,
    mediumspringgreen: 64154,
    mediumturquoise: 4772300,
    mediumvioletred: 13047173,
    midnightblue: 1644912,
    mintcream: 16121850,
    mistyrose: 16770273,
    moccasin: 16770229,
    navajowhite: 16768685,
    navy: 128,
    oldlace: 16643558,
    olive: 8421376,
    olivedrab: 7048739,
    orange: 16753920,
    orangered: 16729344,
    orchid: 14315734,
    palegoldenrod: 15657130,
    palegreen: 10025880,
    paleturquoise: 11529966,
    palevioletred: 14381203,
    papayawhip: 16773077,
    peachpuff: 16767673,
    peru: 13468991,
    pink: 16761035,
    plum: 14524637,
    powderblue: 11591910,
    purple: 8388736,
    rebeccapurple: 6697881,
    red: 16711680,
    rosybrown: 12357519,
    royalblue: 4286945,
    saddlebrown: 9127187,
    salmon: 16416882,
    sandybrown: 16032864,
    seagreen: 3050327,
    seashell: 16774638,
    sienna: 10506797,
    silver: 12632256,
    skyblue: 8900331,
    slateblue: 6970061,
    slategray: 7372944,
    slategrey: 7372944,
    snow: 16775930,
    springgreen: 65407,
    steelblue: 4620980,
    tan: 13808780,
    teal: 32896,
    thistle: 14204888,
    tomato: 16737095,
    turquoise: 4251856,
    violet: 15631086,
    wheat: 16113331,
    white: 16777215,
    whitesmoke: 16119285,
    yellow: 16776960,
    yellowgreen: 10145074
  });
  d3_rgb_names.forEach(function(key, value) {
    d3_rgb_names.set(key, d3_rgbNumber(value));
  });
  function d3_functor(v) {
    return typeof v === "function" ? v : function() {
      return v;
    };
  }
  d3.functor = d3_functor;
  d3.xhr = d3_xhrType(d3_identity);
  function d3_xhrType(response) {
    return function(url, mimeType, callback) {
      if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType, 
      mimeType = null;
      return d3_xhr(url, mimeType, response, callback);
    };
  }
  function d3_xhr(url, mimeType, response, callback) {
    var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null;
    if (this.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest();
    "onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() {
      request.readyState > 3 && respond();
    };
    function respond() {
      var status = request.status, result;
      if (!status && d3_xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) {
        try {
          result = response.call(xhr, request);
        } catch (e) {
          dispatch.error.call(xhr, e);
          return;
        }
        dispatch.load.call(xhr, result);
      } else {
        dispatch.error.call(xhr, request);
      }
    }
    request.onprogress = function(event) {
      var o = d3.event;
      d3.event = event;
      try {
        dispatch.progress.call(xhr, request);
      } finally {
        d3.event = o;
      }
    };
    xhr.header = function(name, value) {
      name = (name + "").toLowerCase();
      if (arguments.length < 2) return headers[name];
      if (value == null) delete headers[name]; else headers[name] = value + "";
      return xhr;
    };
    xhr.mimeType = function(value) {
      if (!arguments.length) return mimeType;
      mimeType = value == null ? null : value + "";
      return xhr;
    };
    xhr.responseType = function(value) {
      if (!arguments.length) return responseType;
      responseType = value;
      return xhr;
    };
    xhr.response = function(value) {
      response = value;
      return xhr;
    };
    [ "get", "post" ].forEach(function(method) {
      xhr[method] = function() {
        return xhr.send.apply(xhr, [ method ].concat(d3_array(arguments)));
      };
    });
    xhr.send = function(method, data, callback) {
      if (arguments.length === 2 && typeof data === "function") callback = data, data = null;
      request.open(method, url, true);
      if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*";
      if (request.setRequestHeader) for (var name in headers) request.setRequestHeader(name, headers[name]);
      if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType);
      if (responseType != null) request.responseType = responseType;
      if (callback != null) xhr.on("error", callback).on("load", function(request) {
        callback(null, request);
      });
      dispatch.beforesend.call(xhr, request);
      request.send(data == null ? null : data);
      return xhr;
    };
    xhr.abort = function() {
      request.abort();
      return xhr;
    };
    d3.rebind(xhr, dispatch, "on");
    return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback));
  }
  function d3_xhr_fixCallback(callback) {
    return callback.length === 1 ? function(error, request) {
      callback(error == null ? request : null);
    } : callback;
  }
  function d3_xhrHasResponse(request) {
    var type = request.responseType;
    return type && type !== "text" ? request.response : request.responseText;
  }
  d3.dsv = function(delimiter, mimeType) {
    var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0);
    function dsv(url, row, callback) {
      if (arguments.length < 3) callback = row, row = null;
      var xhr = d3_xhr(url, mimeType, row == null ? response : typedResponse(row), callback);
      xhr.row = function(_) {
        return arguments.length ? xhr.response((row = _) == null ? response : typedResponse(_)) : row;
      };
      return xhr;
    }
    function response(request) {
      return dsv.parse(request.responseText);
    }
    function typedResponse(f) {
      return function(request) {
        return dsv.parse(request.responseText, f);
      };
    }
    dsv.parse = function(text, f) {
      var o;
      return dsv.parseRows(text, function(row, i) {
        if (o) return o(row, i - 1);
        var a = new Function("d", "return {" + row.map(function(name, i) {
          return JSON.stringify(name) + ": d[" + i + "]";
        }).join(",") + "}");
        o = f ? function(row, i) {
          return f(a(row), i);
        } : a;
      });
    };
    dsv.parseRows = function(text, f) {
      var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol;
      function token() {
        if (I >= N) return EOF;
        if (eol) return eol = false, EOL;
        var j = I;
        if (text.charCodeAt(j) === 34) {
          var i = j;
          while (i++ < N) {
            if (text.charCodeAt(i) === 34) {
              if (text.charCodeAt(i + 1) !== 34) break;
              ++i;
            }
          }
          I = i + 2;
          var c = text.charCodeAt(i + 1);
          if (c === 13) {
            eol = true;
            if (text.charCodeAt(i + 2) === 10) ++I;
          } else if (c === 10) {
            eol = true;
          }
          return text.slice(j + 1, i).replace(/""/g, '"');
        }
        while (I < N) {
          var c = text.charCodeAt(I++), k = 1;
          if (c === 10) eol = true; else if (c === 13) {
            eol = true;
            if (text.charCodeAt(I) === 10) ++I, ++k;
          } else if (c !== delimiterCode) continue;
          return text.slice(j, I - k);
        }
        return text.slice(j);
      }
      while ((t = token()) !== EOF) {
        var a = [];
        while (t !== EOL && t !== EOF) {
          a.push(t);
          t = token();
        }
        if (f && (a = f(a, n++)) == null) continue;
        rows.push(a);
      }
      return rows;
    };
    dsv.format = function(rows) {
      if (Array.isArray(rows[0])) return dsv.formatRows(rows);
      var fieldSet = new d3_Set(), fields = [];
      rows.forEach(function(row) {
        for (var field in row) {
          if (!fieldSet.has(field)) {
            fields.push(fieldSet.add(field));
          }
        }
      });
      return [ fields.map(formatValue).join(delimiter) ].concat(rows.map(function(row) {
        return fields.map(function(field) {
          return formatValue(row[field]);
        }).join(delimiter);
      })).join("\n");
    };
    dsv.formatRows = function(rows) {
      return rows.map(formatRow).join("\n");
    };
    function formatRow(row) {
      return row.map(formatValue).join(delimiter);
    }
    function formatValue(text) {
      return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text;
    }
    return dsv;
  };
  d3.csv = d3.dsv(",", "text/csv");
  d3.tsv = d3.dsv("	", "text/tab-separated-values");
  var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_frame = this[d3_vendorSymbol(this, "requestAnimationFrame")] || function(callback) {
    setTimeout(callback, 17);
  };
  d3.timer = function() {
    d3_timer.apply(this, arguments);
  };
  function d3_timer(callback, delay, then) {
    var n = arguments.length;
    if (n < 2) delay = 0;
    if (n < 3) then = Date.now();
    var time = then + delay, timer = {
      c: callback,
      t: time,
      n: null
    };
    if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer;
    d3_timer_queueTail = timer;
    if (!d3_timer_interval) {
      d3_timer_timeout = clearTimeout(d3_timer_timeout);
      d3_timer_interval = 1;
      d3_timer_frame(d3_timer_step);
    }
    return timer;
  }
  function d3_timer_step() {
    var now = d3_timer_mark(), delay = d3_timer_sweep() - now;
    if (delay > 24) {
      if (isFinite(delay)) {
        clearTimeout(d3_timer_timeout);
        d3_timer_timeout = setTimeout(d3_timer_step, delay);
      }
      d3_timer_interval = 0;
    } else {
      d3_timer_interval = 1;
      d3_timer_frame(d3_timer_step);
    }
  }
  d3.timer.flush = function() {
    d3_timer_mark();
    d3_timer_sweep();
  };
  function d3_timer_mark() {
    var now = Date.now(), timer = d3_timer_queueHead;
    while (timer) {
      if (now >= timer.t && timer.c(now - timer.t)) timer.c = null;
      timer = timer.n;
    }
    return now;
  }
  function d3_timer_sweep() {
    var t0, t1 = d3_timer_queueHead, time = Infinity;
    while (t1) {
      if (t1.c) {
        if (t1.t < time) time = t1.t;
        t1 = (t0 = t1).n;
      } else {
        t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n;
      }
    }
    d3_timer_queueTail = t0;
    return time;
  }
  function d3_format_precision(x, p) {
    return p - (x ? Math.ceil(Math.log(x) / Math.LN10) : 1);
  }
  d3.round = function(x, n) {
    return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x);
  };
  var d3_formatPrefixes = [ "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" ].map(d3_formatPrefix);
  d3.formatPrefix = function(value, precision) {
    var i = 0;
    if (value = +value) {
      if (value < 0) value *= -1;
      if (precision) value = d3.round(value, d3_format_precision(value, precision));
      i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10);
      i = Math.max(-24, Math.min(24, Math.floor((i - 1) / 3) * 3));
    }
    return d3_formatPrefixes[8 + i / 3];
  };
  function d3_formatPrefix(d, i) {
    var k = Math.pow(10, abs(8 - i) * 3);
    return {
      scale: i > 8 ? function(d) {
        return d / k;
      } : function(d) {
        return d * k;
      },
      symbol: d
    };
  }
  function d3_locale_numberFormat(locale) {
    var locale_decimal = locale.decimal, locale_thousands = locale.thousands, locale_grouping = locale.grouping, locale_currency = locale.currency, formatGroup = locale_grouping && locale_thousands ? function(value, width) {
      var i = value.length, t = [], j = 0, g = locale_grouping[0], length = 0;
      while (i > 0 && g > 0) {
        if (length + g + 1 > width) g = Math.max(1, width - length);
        t.push(value.substring(i -= g, i + g));
        if ((length += g + 1) > width) break;
        g = locale_grouping[j = (j + 1) % locale_grouping.length];
      }
      return t.reverse().join(locale_thousands);
    } : d3_identity;
    return function(specifier) {
      var match = d3_format_re.exec(specifier), fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "-", symbol = match[4] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, prefix = "", suffix = "", integer = false, exponent = true;
      if (precision) precision = +precision.substring(1);
      if (zfill || fill === "0" && align === "=") {
        zfill = fill = "0";
        align = "=";
      }
      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();

       case "c":
        exponent = false;

       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 (type == "r" && !precision) type = "g";
      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));
      }
      type = d3_format_types.get(type) || d3_format_typeDefault;
      var zcomma = zfill && comma;
      return function(value) {
        var fullSuffix = suffix;
        if (integer && value % 1) return "";
        var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, "-") : sign === "-" ? "" : sign;
        if (scale < 0) {
          var unit = d3.formatPrefix(value, precision);
          value = unit.scale(value);
          fullSuffix = unit.symbol + suffix;
        } else {
          value *= scale;
        }
        value = type(value, precision);
        var i = value.lastIndexOf("."), before, after;
        if (i < 0) {
          var j = exponent ? value.lastIndexOf("e") : -1;
          if (j < 0) before = value, after = ""; else before = value.substring(0, j), after = value.substring(j);
        } else {
          before = value.substring(0, i);
          after = locale_decimal + value.substring(i + 1);
        }
        if (!zfill && comma) before = formatGroup(before, Infinity);
        var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length), padding = length < width ? new Array(length = width - length + 1).join(fill) : "";
        if (zcomma) before = formatGroup(padding + before, padding.length ? width - after.length : Infinity);
        negative += prefix;
        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;
      };
    };
  }
  var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i;
  var d3_format_types = d3.map({
    b: function(x) {
      return x.toString(2);
    },
    c: function(x) {
      return String.fromCharCode(x);
    },
    o: function(x) {
      return x.toString(8);
    },
    x: function(x) {
      return x.toString(16);
    },
    X: function(x) {
      return x.toString(16).toUpperCase();
    },
    g: function(x, p) {
      return x.toPrecision(p);
    },
    e: function(x, p) {
      return x.toExponential(p);
    },
    f: function(x, p) {
      return x.toFixed(p);
    },
    r: function(x, p) {
      return (x = d3.round(x, d3_format_precision(x, p))).toFixed(Math.max(0, Math.min(20, d3_format_precision(x * (1 + 1e-15), p))));
    }
  });
  function d3_format_typeDefault(x) {
    return x + "";
  }
  var d3_time = d3.time = {}, d3_date = Date;
  function d3_date_utc() {
    this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]);
  }
  d3_date_utc.prototype = {
    getDate: function() {
      return this._.getUTCDate();
    },
    getDay: function() {
      return this._.getUTCDay();
    },
    getFullYear: function() {
      return this._.getUTCFullYear();
    },
    getHours: function() {
      return this._.getUTCHours();
    },
    getMilliseconds: function() {
      return this._.getUTCMilliseconds();
    },
    getMinutes: function() {
      return this._.getUTCMinutes();
    },
    getMonth: function() {
      return this._.getUTCMonth();
    },
    getSeconds: function() {
      return this._.getUTCSeconds();
    },
    getTime: function() {
      return this._.getTime();
    },
    getTimezoneOffset: function() {
      return 0;
    },
    valueOf: function() {
      return this._.valueOf();
    },
    setDate: function() {
      d3_time_prototype.setUTCDate.apply(this._, arguments);
    },
    setDay: function() {
      d3_time_prototype.setUTCDay.apply(this._, arguments);
    },
    setFullYear: function() {
      d3_time_prototype.setUTCFullYear.apply(this._, arguments);
    },
    setHours: function() {
      d3_time_prototype.setUTCHours.apply(this._, arguments);
    },
    setMilliseconds: function() {
      d3_time_prototype.setUTCMilliseconds.apply(this._, arguments);
    },
    setMinutes: function() {
      d3_time_prototype.setUTCMinutes.apply(this._, arguments);
    },
    setMonth: function() {
      d3_time_prototype.setUTCMonth.apply(this._, arguments);
    },
    setSeconds: function() {
      d3_time_prototype.setUTCSeconds.apply(this._, arguments);
    },
    setTime: function() {
      d3_time_prototype.setTime.apply(this._, arguments);
    }
  };
  var d3_time_prototype = Date.prototype;
  function d3_time_interval(local, step, number) {
    function round(date) {
      var d0 = local(date), d1 = offset(d0, 1);
      return date - d0 < d1 - date ? d0 : d1;
    }
    function ceil(date) {
      step(date = local(new d3_date(date - 1)), 1);
      return date;
    }
    function offset(date, k) {
      step(date = new d3_date(+date), k);
      return date;
    }
    function range(t0, t1, dt) {
      var time = ceil(t0), times = [];
      if (dt > 1) {
        while (time < t1) {
          if (!(number(time) % dt)) times.push(new Date(+time));
          step(time, 1);
        }
      } else {
        while (time < t1) times.push(new Date(+time)), step(time, 1);
      }
      return times;
    }
    function range_utc(t0, t1, dt) {
      try {
        d3_date = d3_date_utc;
        var utc = new d3_date_utc();
        utc._ = t0;
        return range(utc, t1, dt);
      } finally {
        d3_date = Date;
      }
    }
    local.floor = local;
    local.round = round;
    local.ceil = ceil;
    local.offset = offset;
    local.range = range;
    var utc = local.utc = d3_time_interval_utc(local);
    utc.floor = utc;
    utc.round = d3_time_interval_utc(round);
    utc.ceil = d3_time_interval_utc(ceil);
    utc.offset = d3_time_interval_utc(offset);
    utc.range = range_utc;
    return local;
  }
  function d3_time_interval_utc(method) {
    return function(date, k) {
      try {
        d3_date = d3_date_utc;
        var utc = new d3_date_utc();
        utc._ = date;
        return method(utc, k)._;
      } finally {
        d3_date = Date;
      }
    };
  }
  d3_time.year = d3_time_interval(function(date) {
    date = d3_time.day(date);
    date.setMonth(0, 1);
    return date;
  }, function(date, offset) {
    date.setFullYear(date.getFullYear() + offset);
  }, function(date) {
    return date.getFullYear();
  });
  d3_time.years = d3_time.year.range;
  d3_time.years.utc = d3_time.year.utc.range;
  d3_time.day = d3_time_interval(function(date) {
    var day = new d3_date(2e3, 0);
    day.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());
    return day;
  }, function(date, offset) {
    date.setDate(date.getDate() + offset);
  }, function(date) {
    return date.getDate() - 1;
  });
  d3_time.days = d3_time.day.range;
  d3_time.days.utc = d3_time.day.utc.range;
  d3_time.dayOfYear = function(date) {
    var year = d3_time.year(date);
    return Math.floor((date - year - (date.getTimezoneOffset() - year.getTimezoneOffset()) * 6e4) / 864e5);
  };
  [ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ].forEach(function(day, i) {
    i = 7 - i;
    var interval = d3_time[day] = d3_time_interval(function(date) {
      (date = d3_time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7);
      return date;
    }, function(date, offset) {
      date.setDate(date.getDate() + Math.floor(offset) * 7);
    }, function(date) {
      var day = d3_time.year(date).getDay();
      return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i);
    });
    d3_time[day + "s"] = interval.range;
    d3_time[day + "s"].utc = interval.utc.range;
    d3_time[day + "OfYear"] = function(date) {
      var day = d3_time.year(date).getDay();
      return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7);
    };
  });
  d3_time.week = d3_time.sunday;
  d3_time.weeks = d3_time.sunday.range;
  d3_time.weeks.utc = d3_time.sunday.utc.range;
  d3_time.weekOfYear = d3_time.sundayOfYear;
  function d3_locale_timeFormat(locale) {
    var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_days = locale.days, locale_shortDays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths;
    function d3_time_format(template) {
      var n = template.length;
      function format(date) {
        var string = [], i = -1, j = 0, c, p, f;
        while (++i < n) {
          if (template.charCodeAt(i) === 37) {
            string.push(template.slice(j, i));
            if ((p = d3_time_formatPads[c = template.charAt(++i)]) != null) c = template.charAt(++i);
            if (f = d3_time_formats[c]) c = f(date, p == null ? c === "e" ? " " : "0" : p);
            string.push(c);
            j = i + 1;
          }
        }
        string.push(template.slice(j, i));
        return string.join("");
      }
      format.parse = function(string) {
        var d = {
          y: 1900,
          m: 0,
          d: 1,
          H: 0,
          M: 0,
          S: 0,
          L: 0,
          Z: null
        }, i = d3_time_parse(d, template, string, 0);
        if (i != string.length) return null;
        if ("p" in d) d.H = d.H % 12 + d.p * 12;
        var localZ = d.Z != null && d3_date !== d3_date_utc, date = new (localZ ? d3_date_utc : d3_date)();
        if ("j" in d) date.setFullYear(d.y, 0, d.j); else if ("W" in d || "U" in d) {
          if (!("w" in d)) d.w = "W" in d ? 1 : 0;
          date.setFullYear(d.y, 0, 1);
          date.setFullYear(d.y, 0, "W" in d ? (d.w + 6) % 7 + d.W * 7 - (date.getDay() + 5) % 7 : d.w + d.U * 7 - (date.getDay() + 6) % 7);
        } else date.setFullYear(d.y, d.m, d.d);
        date.setHours(d.H + (d.Z / 100 | 0), d.M + d.Z % 100, d.S, d.L);
        return localZ ? date._ : date;
      };
      format.toString = function() {
        return template;
      };
      return format;
    }
    function d3_time_parse(date, template, string, j) {
      var c, p, t, i = 0, n = template.length, m = string.length;
      while (i < n) {
        if (j >= m) return -1;
        c = template.charCodeAt(i++);
        if (c === 37) {
          t = template.charAt(i++);
          p = d3_time_parsers[t in d3_time_formatPads ? template.charAt(i++) : t];
          if (!p || (j = p(date, string, j)) < 0) return -1;
        } else if (c != string.charCodeAt(j++)) {
          return -1;
        }
      }
      return j;
    }
    d3_time_format.utc = function(template) {
      var local = d3_time_format(template);
      function format(date) {
        try {
          d3_date = d3_date_utc;
          var utc = new d3_date();
          utc._ = date;
          return local(utc);
        } finally {
          d3_date = Date;
        }
      }
      format.parse = function(string) {
        try {
          d3_date = d3_date_utc;
          var date = local.parse(string);
          return date && date._;
        } finally {
          d3_date = Date;
        }
      };
      format.toString = local.toString;
      return format;
    };
    d3_time_format.multi = d3_time_format.utc.multi = d3_time_formatMulti;
    var d3_time_periodLookup = d3.map(), d3_time_dayRe = d3_time_formatRe(locale_days), d3_time_dayLookup = d3_time_formatLookup(locale_days), d3_time_dayAbbrevRe = d3_time_formatRe(locale_shortDays), d3_time_dayAbbrevLookup = d3_time_formatLookup(locale_shortDays), d3_time_monthRe = d3_time_formatRe(locale_months), d3_time_monthLookup = d3_time_formatLookup(locale_months), d3_time_monthAbbrevRe = d3_time_formatRe(locale_shortMonths), d3_time_monthAbbrevLookup = d3_time_formatLookup(locale_shortMonths);
    locale_periods.forEach(function(p, i) {
      d3_time_periodLookup.set(p.toLowerCase(), i);
    });
    var d3_time_formats = {
      a: function(d) {
        return locale_shortDays[d.getDay()];
      },
      A: function(d) {
        return locale_days[d.getDay()];
      },
      b: function(d) {
        return locale_shortMonths[d.getMonth()];
      },
      B: function(d) {
        return locale_months[d.getMonth()];
      },
      c: d3_time_format(locale_dateTime),
      d: function(d, p) {
        return d3_time_formatPad(d.getDate(), p, 2);
      },
      e: function(d, p) {
        return d3_time_formatPad(d.getDate(), p, 2);
      },
      H: function(d, p) {
        return d3_time_formatPad(d.getHours(), p, 2);
      },
      I: function(d, p) {
        return d3_time_formatPad(d.getHours() % 12 || 12, p, 2);
      },
      j: function(d, p) {
        return d3_time_formatPad(1 + d3_time.dayOfYear(d), p, 3);
      },
      L: function(d, p) {
        return d3_time_formatPad(d.getMilliseconds(), p, 3);
      },
      m: function(d, p) {
        return d3_time_formatPad(d.getMonth() + 1, p, 2);
      },
      M: function(d, p) {
        return d3_time_formatPad(d.getMinutes(), p, 2);
      },
      p: function(d) {
        return locale_periods[+(d.getHours() >= 12)];
      },
      S: function(d, p) {
        return d3_time_formatPad(d.getSeconds(), p, 2);
      },
      U: function(d, p) {
        return d3_time_formatPad(d3_time.sundayOfYear(d), p, 2);
      },
      w: function(d) {
        return d.getDay();
      },
      W: function(d, p) {
        return d3_time_formatPad(d3_time.mondayOfYear(d), p, 2);
      },
      x: d3_time_format(locale_date),
      X: d3_time_format(locale_time),
      y: function(d, p) {
        return d3_time_formatPad(d.getFullYear() % 100, p, 2);
      },
      Y: function(d, p) {
        return d3_time_formatPad(d.getFullYear() % 1e4, p, 4);
      },
      Z: d3_time_zone,
      "%": function() {
        return "%";
      }
    };
    var d3_time_parsers = {
      a: d3_time_parseWeekdayAbbrev,
      A: d3_time_parseWeekday,
      b: d3_time_parseMonthAbbrev,
      B: d3_time_parseMonth,
      c: d3_time_parseLocaleFull,
      d: d3_time_parseDay,
      e: d3_time_parseDay,
      H: d3_time_parseHour24,
      I: d3_time_parseHour24,
      j: d3_time_parseDayOfYear,
      L: d3_time_parseMilliseconds,
      m: d3_time_parseMonthNumber,
      M: d3_time_parseMinutes,
      p: d3_time_parseAmPm,
      S: d3_time_parseSeconds,
      U: d3_time_parseWeekNumberSunday,
      w: d3_time_parseWeekdayNumber,
      W: d3_time_parseWeekNumberMonday,
      x: d3_time_parseLocaleDate,
      X: d3_time_parseLocaleTime,
      y: d3_time_parseYear,
      Y: d3_time_parseFullYear,
      Z: d3_time_parseZone,
      "%": d3_time_parseLiteralPercent
    };
    function d3_time_parseWeekdayAbbrev(date, string, i) {
      d3_time_dayAbbrevRe.lastIndex = 0;
      var n = d3_time_dayAbbrevRe.exec(string.slice(i));
      return n ? (date.w = d3_time_dayAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
    }
    function d3_time_parseWeekday(date, string, i) {
      d3_time_dayRe.lastIndex = 0;
      var n = d3_time_dayRe.exec(string.slice(i));
      return n ? (date.w = d3_time_dayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
    }
    function d3_time_parseMonthAbbrev(date, string, i) {
      d3_time_monthAbbrevRe.lastIndex = 0;
      var n = d3_time_monthAbbrevRe.exec(string.slice(i));
      return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
    }
    function d3_time_parseMonth(date, string, i) {
      d3_time_monthRe.lastIndex = 0;
      var n = d3_time_monthRe.exec(string.slice(i));
      return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
    }
    function d3_time_parseLocaleFull(date, string, i) {
      return d3_time_parse(date, d3_time_formats.c.toString(), string, i);
    }
    function d3_time_parseLocaleDate(date, string, i) {
      return d3_time_parse(date, d3_time_formats.x.toString(), string, i);
    }
    function d3_time_parseLocaleTime(date, string, i) {
      return d3_time_parse(date, d3_time_formats.X.toString(), string, i);
    }
    function d3_time_parseAmPm(date, string, i) {
      var n = d3_time_periodLookup.get(string.slice(i, i += 2).toLowerCase());
      return n == null ? -1 : (date.p = n, i);
    }
    return d3_time_format;
  }
  var d3_time_formatPads = {
    "-": "",
    _: " ",
    "0": "0"
  }, d3_time_numberRe = /^\s*\d+/, d3_time_percentRe = /^%/;
  function d3_time_formatPad(value, fill, width) {
    var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length;
    return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string);
  }
  function d3_time_formatRe(names) {
    return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i");
  }
  function d3_time_formatLookup(names) {
    var map = new d3_Map(), i = -1, n = names.length;
    while (++i < n) map.set(names[i].toLowerCase(), i);
    return map;
  }
  function d3_time_parseWeekdayNumber(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 1));
    return n ? (date.w = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseWeekNumberSunday(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i));
    return n ? (date.U = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseWeekNumberMonday(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i));
    return n ? (date.W = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseFullYear(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 4));
    return n ? (date.y = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseYear(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.y = d3_time_expandYear(+n[0]), i + n[0].length) : -1;
  }
  function d3_time_parseZone(date, string, i) {
    return /^[+-]\d{4}$/.test(string = string.slice(i, i + 5)) ? (date.Z = -string, 
    i + 5) : -1;
  }
  function d3_time_expandYear(d) {
    return d + (d > 68 ? 1900 : 2e3);
  }
  function d3_time_parseMonthNumber(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.m = n[0] - 1, i + n[0].length) : -1;
  }
  function d3_time_parseDay(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.d = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseDayOfYear(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 3));
    return n ? (date.j = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseHour24(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.H = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseMinutes(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.M = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseSeconds(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.S = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseMilliseconds(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 3));
    return n ? (date.L = +n[0], i + n[0].length) : -1;
  }
  function d3_time_zone(d) {
    var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = abs(z) / 60 | 0, zm = abs(z) % 60;
    return zs + d3_time_formatPad(zh, "0", 2) + d3_time_formatPad(zm, "0", 2);
  }
  function d3_time_parseLiteralPercent(date, string, i) {
    d3_time_percentRe.lastIndex = 0;
    var n = d3_time_percentRe.exec(string.slice(i, i + 1));
    return n ? i + n[0].length : -1;
  }
  function d3_time_formatMulti(formats) {
    var n = formats.length, i = -1;
    while (++i < n) formats[i][0] = this(formats[i][0]);
    return function(date) {
      var i = 0, f = formats[i];
      while (!f[1](date)) f = formats[++i];
      return f[0](date);
    };
  }
  d3.locale = function(locale) {
    return {
      numberFormat: d3_locale_numberFormat(locale),
      timeFormat: d3_locale_timeFormat(locale)
    };
  };
  var d3_locale_enUS = d3.locale({
    decimal: ".",
    thousands: ",",
    grouping: [ 3 ],
    currency: [ "$", "" ],
    dateTime: "%a %b %e %X %Y",
    date: "%m/%d/%Y",
    time: "%H:%M:%S",
    periods: [ "AM", "PM" ],
    days: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ],
    shortDays: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ],
    months: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ],
    shortMonths: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]
  });
  d3.format = d3_locale_enUS.numberFormat;
  d3.geo = {};
  function d3_adder() {}
  d3_adder.prototype = {
    s: 0,
    t: 0,
    add: function(y) {
      d3_adderSum(y, this.t, d3_adderTemp);
      d3_adderSum(d3_adderTemp.s, this.s, this);
      if (this.s) this.t += d3_adderTemp.t; else this.s = d3_adderTemp.t;
    },
    reset: function() {
      this.s = this.t = 0;
    },
    valueOf: function() {
      return this.s;
    }
  };
  var d3_adderTemp = new d3_adder();
  function d3_adderSum(a, b, o) {
    var x = o.s = a + b, bv = x - a, av = x - bv;
    o.t = a - av + (b - bv);
  }
  d3.geo.stream = function(object, listener) {
    if (object && d3_geo_streamObjectType.hasOwnProperty(object.type)) {
      d3_geo_streamObjectType[object.type](object, listener);
    } else {
      d3_geo_streamGeometry(object, listener);
    }
  };
  function d3_geo_streamGeometry(geometry, listener) {
    if (geometry && d3_geo_streamGeometryType.hasOwnProperty(geometry.type)) {
      d3_geo_streamGeometryType[geometry.type](geometry, listener);
    }
  }
  var d3_geo_streamObjectType = {
    Feature: function(feature, listener) {
      d3_geo_streamGeometry(feature.geometry, listener);
    },
    FeatureCollection: function(object, listener) {
      var features = object.features, i = -1, n = features.length;
      while (++i < n) d3_geo_streamGeometry(features[i].geometry, listener);
    }
  };
  var d3_geo_streamGeometryType = {
    Sphere: function(object, listener) {
      listener.sphere();
    },
    Point: function(object, listener) {
      object = object.coordinates;
      listener.point(object[0], object[1], object[2]);
    },
    MultiPoint: function(object, listener) {
      var coordinates = object.coordinates, i = -1, n = coordinates.length;
      while (++i < n) object = coordinates[i], listener.point(object[0], object[1], object[2]);
    },
    LineString: function(object, listener) {
      d3_geo_streamLine(object.coordinates, listener, 0);
    },
    MultiLineString: function(object, listener) {
      var coordinates = object.coordinates, i = -1, n = coordinates.length;
      while (++i < n) d3_geo_streamLine(coordinates[i], listener, 0);
    },
    Polygon: function(object, listener) {
      d3_geo_streamPolygon(object.coordinates, listener);
    },
    MultiPolygon: function(object, listener) {
      var coordinates = object.coordinates, i = -1, n = coordinates.length;
      while (++i < n) d3_geo_streamPolygon(coordinates[i], listener);
    },
    GeometryCollection: function(object, listener) {
      var geometries = object.geometries, i = -1, n = geometries.length;
      while (++i < n) d3_geo_streamGeometry(geometries[i], listener);
    }
  };
  function d3_geo_streamLine(coordinates, listener, closed) {
    var i = -1, n = coordinates.length - closed, coordinate;
    listener.lineStart();
    while (++i < n) coordinate = coordinates[i], listener.point(coordinate[0], coordinate[1], coordinate[2]);
    listener.lineEnd();
  }
  function d3_geo_streamPolygon(coordinates, listener) {
    var i = -1, n = coordinates.length;
    listener.polygonStart();
    while (++i < n) d3_geo_streamLine(coordinates[i], listener, 1);
    listener.polygonEnd();
  }
  d3.geo.area = function(object) {
    d3_geo_areaSum = 0;
    d3.geo.stream(object, d3_geo_area);
    return d3_geo_areaSum;
  };
  var d3_geo_areaSum, d3_geo_areaRingSum = new d3_adder();
  var d3_geo_area = {
    sphere: function() {
      d3_geo_areaSum += 4 * π;
    },
    point: d3_noop,
    lineStart: d3_noop,
    lineEnd: d3_noop,
    polygonStart: function() {
      d3_geo_areaRingSum.reset();
      d3_geo_area.lineStart = d3_geo_areaRingStart;
    },
    polygonEnd: function() {
      var area = 2 * d3_geo_areaRingSum;
      d3_geo_areaSum += area < 0 ? 4 * π + area : area;
      d3_geo_area.lineStart = d3_geo_area.lineEnd = d3_geo_area.point = d3_noop;
    }
  };
  function d3_geo_areaRingStart() {
    var λ00, φ00, λ0, cosφ0, sinφ0;
    d3_geo_area.point = function(λ, φ) {
      d3_geo_area.point = nextPoint;
      λ0 = (λ00 = λ) * d3_radians, cosφ0 = Math.cos(φ = (φ00 = φ) * d3_radians / 2 + π / 4), 
      sinφ0 = Math.sin(φ);
    };
    function nextPoint(λ, φ) {
      λ *= d3_radians;
      φ = φ * d3_radians / 2 + π / 4;
      var dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, cosφ = Math.cos(φ), sinφ = Math.sin(φ), k = sinφ0 * sinφ, u = cosφ0 * cosφ + k * Math.cos(adλ), v = k * sdλ * Math.sin(adλ);
      d3_geo_areaRingSum.add(Math.atan2(v, u));
      λ0 = λ, cosφ0 = cosφ, sinφ0 = sinφ;
    }
    d3_geo_area.lineEnd = function() {
      nextPoint(λ00, φ00);
    };
  }
  function d3_geo_cartesian(spherical) {
    var λ = spherical[0], φ = spherical[1], cosφ = Math.cos(φ);
    return [ cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ) ];
  }
  function d3_geo_cartesianDot(a, b) {
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  }
  function d3_geo_cartesianCross(a, b) {
    return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ];
  }
  function d3_geo_cartesianAdd(a, b) {
    a[0] += b[0];
    a[1] += b[1];
    a[2] += b[2];
  }
  function d3_geo_cartesianScale(vector, k) {
    return [ vector[0] * k, vector[1] * k, vector[2] * k ];
  }
  function d3_geo_cartesianNormalize(d) {
    var l = Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
    d[0] /= l;
    d[1] /= l;
    d[2] /= l;
  }
  function d3_geo_spherical(cartesian) {
    return [ Math.atan2(cartesian[1], cartesian[0]), d3_asin(cartesian[2]) ];
  }
  function d3_geo_sphericalEqual(a, b) {
    return abs(a[0] - b[0]) < ε && abs(a[1] - b[1]) < ε;
  }
  d3.geo.bounds = function() {
    var λ0, φ0, λ1, φ1, λ_, λ__, φ__, p0, dλSum, ranges, range;
    var bound = {
      point: point,
      lineStart: lineStart,
      lineEnd: lineEnd,
      polygonStart: function() {
        bound.point = ringPoint;
        bound.lineStart = ringStart;
        bound.lineEnd = ringEnd;
        dλSum = 0;
        d3_geo_area.polygonStart();
      },
      polygonEnd: function() {
        d3_geo_area.polygonEnd();
        bound.point = point;
        bound.lineStart = lineStart;
        bound.lineEnd = lineEnd;
        if (d3_geo_areaRingSum < 0) λ0 = -(λ1 = 180), φ0 = -(φ1 = 90); else if (dλSum > ε) φ1 = 90; else if (dλSum < -ε) φ0 = -90;
        range[0] = λ0, range[1] = λ1;
      }
    };
    function point(λ, φ) {
      ranges.push(range = [ λ0 = λ, λ1 = λ ]);
      if (φ < φ0) φ0 = φ;
      if (φ > φ1) φ1 = φ;
    }
    function linePoint(λ, φ) {
      var p = d3_geo_cartesian([ λ * d3_radians, φ * d3_radians ]);
      if (p0) {
        var normal = d3_geo_cartesianCross(p0, p), equatorial = [ normal[1], -normal[0], 0 ], inflection = d3_geo_cartesianCross(equatorial, normal);
        d3_geo_cartesianNormalize(inflection);
        inflection = d3_geo_spherical(inflection);
        var dλ = λ - λ_, s = dλ > 0 ? 1 : -1, λi = inflection[0] * d3_degrees * s, antimeridian = abs(dλ) > 180;
        if (antimeridian ^ (s * λ_ < λi && λi < s * λ)) {
          var φi = inflection[1] * d3_degrees;
          if (φi > φ1) φ1 = φi;
        } else if (λi = (λi + 360) % 360 - 180, antimeridian ^ (s * λ_ < λi && λi < s * λ)) {
          var φi = -inflection[1] * d3_degrees;
          if (φi < φ0) φ0 = φi;
        } else {
          if (φ < φ0) φ0 = φ;
          if (φ > φ1) φ1 = φ;
        }
        if (antimeridian) {
          if (λ < λ_) {
            if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ;
          } else {
            if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ;
          }
        } else {
          if (λ1 >= λ0) {
            if (λ < λ0) λ0 = λ;
            if (λ > λ1) λ1 = λ;
          } else {
            if (λ > λ_) {
              if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ;
            } else {
              if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ;
            }
          }
        }
      } else {
        point(λ, φ);
      }
      p0 = p, λ_ = λ;
    }
    function lineStart() {
      bound.point = linePoint;
    }
    function lineEnd() {
      range[0] = λ0, range[1] = λ1;
      bound.point = point;
      p0 = null;
    }
    function ringPoint(λ, φ) {
      if (p0) {
        var dλ = λ - λ_;
        dλSum += abs(dλ) > 180 ? dλ + (dλ > 0 ? 360 : -360) : dλ;
      } else λ__ = λ, φ__ = φ;
      d3_geo_area.point(λ, φ);
      linePoint(λ, φ);
    }
    function ringStart() {
      d3_geo_area.lineStart();
    }
    function ringEnd() {
      ringPoint(λ__, φ__);
      d3_geo_area.lineEnd();
      if (abs(dλSum) > ε) λ0 = -(λ1 = 180);
      range[0] = λ0, range[1] = λ1;
      p0 = null;
    }
    function angle(λ0, λ1) {
      return (λ1 -= λ0) < 0 ? λ1 + 360 : λ1;
    }
    function compareRanges(a, b) {
      return a[0] - b[0];
    }
    function withinRange(x, range) {
      return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x;
    }
    return function(feature) {
      φ1 = λ1 = -(λ0 = φ0 = Infinity);
      ranges = [];
      d3.geo.stream(feature, bound);
      var n = ranges.length;
      if (n) {
        ranges.sort(compareRanges);
        for (var i = 1, a = ranges[0], b, merged = [ a ]; i < n; ++i) {
          b = ranges[i];
          if (withinRange(b[0], a) || withinRange(b[1], a)) {
            if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1];
            if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0];
          } else {
            merged.push(a = b);
          }
        }
        var best = -Infinity, dλ;
        for (var n = merged.length - 1, i = 0, a = merged[n], b; i <= n; a = b, ++i) {
          b = merged[i];
          if ((dλ = angle(a[1], b[0])) > best) best = dλ, λ0 = b[0], λ1 = a[1];
        }
      }
      ranges = range = null;
      return λ0 === Infinity || φ0 === Infinity ? [ [ NaN, NaN ], [ NaN, NaN ] ] : [ [ λ0, φ0 ], [ λ1, φ1 ] ];
    };
  }();
  d3.geo.centroid = function(object) {
    d3_geo_centroidW0 = d3_geo_centroidW1 = d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0;
    d3.geo.stream(object, d3_geo_centroid);
    var x = d3_geo_centroidX2, y = d3_geo_centroidY2, z = d3_geo_centroidZ2, m = x * x + y * y + z * z;
    if (m < ε2) {
      x = d3_geo_centroidX1, y = d3_geo_centroidY1, z = d3_geo_centroidZ1;
      if (d3_geo_centroidW1 < ε) x = d3_geo_centroidX0, y = d3_geo_centroidY0, z = d3_geo_centroidZ0;
      m = x * x + y * y + z * z;
      if (m < ε2) return [ NaN, NaN ];
    }
    return [ Math.atan2(y, x) * d3_degrees, d3_asin(z / Math.sqrt(m)) * d3_degrees ];
  };
  var d3_geo_centroidW0, d3_geo_centroidW1, d3_geo_centroidX0, d3_geo_centroidY0, d3_geo_centroidZ0, d3_geo_centroidX1, d3_geo_centroidY1, d3_geo_centroidZ1, d3_geo_centroidX2, d3_geo_centroidY2, d3_geo_centroidZ2;
  var d3_geo_centroid = {
    sphere: d3_noop,
    point: d3_geo_centroidPoint,
    lineStart: d3_geo_centroidLineStart,
    lineEnd: d3_geo_centroidLineEnd,
    polygonStart: function() {
      d3_geo_centroid.lineStart = d3_geo_centroidRingStart;
    },
    polygonEnd: function() {
      d3_geo_centroid.lineStart = d3_geo_centroidLineStart;
    }
  };
  function d3_geo_centroidPoint(λ, φ) {
    λ *= d3_radians;
    var cosφ = Math.cos(φ *= d3_radians);
    d3_geo_centroidPointXYZ(cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ));
  }
  function d3_geo_centroidPointXYZ(x, y, z) {
    ++d3_geo_centroidW0;
    d3_geo_centroidX0 += (x - d3_geo_centroidX0) / d3_geo_centroidW0;
    d3_geo_centroidY0 += (y - d3_geo_centroidY0) / d3_geo_centroidW0;
    d3_geo_centroidZ0 += (z - d3_geo_centroidZ0) / d3_geo_centroidW0;
  }
  function d3_geo_centroidLineStart() {
    var x0, y0, z0;
    d3_geo_centroid.point = function(λ, φ) {
      λ *= d3_radians;
      var cosφ = Math.cos(φ *= d3_radians);
      x0 = cosφ * Math.cos(λ);
      y0 = cosφ * Math.sin(λ);
      z0 = Math.sin(φ);
      d3_geo_centroid.point = nextPoint;
      d3_geo_centroidPointXYZ(x0, y0, z0);
    };
    function nextPoint(λ, φ) {
      λ *= d3_radians;
      var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), w = Math.atan2(Math.sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z);
      d3_geo_centroidW1 += w;
      d3_geo_centroidX1 += w * (x0 + (x0 = x));
      d3_geo_centroidY1 += w * (y0 + (y0 = y));
      d3_geo_centroidZ1 += w * (z0 + (z0 = z));
      d3_geo_centroidPointXYZ(x0, y0, z0);
    }
  }
  function d3_geo_centroidLineEnd() {
    d3_geo_centroid.point = d3_geo_centroidPoint;
  }
  function d3_geo_centroidRingStart() {
    var λ00, φ00, x0, y0, z0;
    d3_geo_centroid.point = function(λ, φ) {
      λ00 = λ, φ00 = φ;
      d3_geo_centroid.point = nextPoint;
      λ *= d3_radians;
      var cosφ = Math.cos(φ *= d3_radians);
      x0 = cosφ * Math.cos(λ);
      y0 = cosφ * Math.sin(λ);
      z0 = Math.sin(φ);
      d3_geo_centroidPointXYZ(x0, y0, z0);
    };
    d3_geo_centroid.lineEnd = function() {
      nextPoint(λ00, φ00);
      d3_geo_centroid.lineEnd = d3_geo_centroidLineEnd;
      d3_geo_centroid.point = d3_geo_centroidPoint;
    };
    function nextPoint(λ, φ) {
      λ *= d3_radians;
      var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = Math.sqrt(cx * cx + cy * cy + cz * cz), u = x0 * x + y0 * y + z0 * z, v = m && -d3_acos(u) / m, w = Math.atan2(m, u);
      d3_geo_centroidX2 += v * cx;
      d3_geo_centroidY2 += v * cy;
      d3_geo_centroidZ2 += v * cz;
      d3_geo_centroidW1 += w;
      d3_geo_centroidX1 += w * (x0 + (x0 = x));
      d3_geo_centroidY1 += w * (y0 + (y0 = y));
      d3_geo_centroidZ1 += w * (z0 + (z0 = z));
      d3_geo_centroidPointXYZ(x0, y0, z0);
    }
  }
  function d3_geo_compose(a, b) {
    function compose(x, y) {
      return x = a(x, y), b(x[0], x[1]);
    }
    if (a.invert && b.invert) compose.invert = function(x, y) {
      return x = b.invert(x, y), x && a.invert(x[0], x[1]);
    };
    return compose;
  }
  function d3_true() {
    return true;
  }
  function d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener) {
    var subject = [], clip = [];
    segments.forEach(function(segment) {
      if ((n = segment.length - 1) <= 0) return;
      var n, p0 = segment[0], p1 = segment[n];
      if (d3_geo_sphericalEqual(p0, p1)) {
        listener.lineStart();
        for (var i = 0; i < n; ++i) listener.point((p0 = segment[i])[0], p0[1]);
        listener.lineEnd();
        return;
      }
      var a = new d3_geo_clipPolygonIntersection(p0, segment, null, true), b = new d3_geo_clipPolygonIntersection(p0, null, a, false);
      a.o = b;
      subject.push(a);
      clip.push(b);
      a = new d3_geo_clipPolygonIntersection(p1, segment, null, false);
      b = new d3_geo_clipPolygonIntersection(p1, null, a, true);
      a.o = b;
      subject.push(a);
      clip.push(b);
    });
    clip.sort(compare);
    d3_geo_clipPolygonLinkCircular(subject);
    d3_geo_clipPolygonLinkCircular(clip);
    if (!subject.length) return;
    for (var i = 0, entry = clipStartInside, n = clip.length; i < n; ++i) {
      clip[i].e = entry = !entry;
    }
    var start = subject[0], points, point;
    while (1) {
      var current = start, isSubject = true;
      while (current.v) if ((current = current.n) === start) return;
      points = current.z;
      listener.lineStart();
      do {
        current.v = current.o.v = true;
        if (current.e) {
          if (isSubject) {
            for (var i = 0, n = points.length; i < n; ++i) listener.point((point = points[i])[0], point[1]);
          } else {
            interpolate(current.x, current.n.x, 1, listener);
          }
          current = current.n;
        } else {
          if (isSubject) {
            points = current.p.z;
            for (var i = points.length - 1; i >= 0; --i) listener.point((point = points[i])[0], point[1]);
          } else {
            interpolate(current.x, current.p.x, -1, listener);
          }
          current = current.p;
        }
        current = current.o;
        points = current.z;
        isSubject = !isSubject;
      } while (!current.v);
      listener.lineEnd();
    }
  }
  function d3_geo_clipPolygonLinkCircular(array) {
    if (!(n = array.length)) return;
    var n, i = 0, a = array[0], b;
    while (++i < n) {
      a.n = b = array[i];
      b.p = a;
      a = b;
    }
    a.n = b = array[0];
    b.p = a;
  }
  function d3_geo_clipPolygonIntersection(point, points, other, entry) {
    this.x = point;
    this.z = points;
    this.o = other;
    this.e = entry;
    this.v = false;
    this.n = this.p = null;
  }
  function d3_geo_clip(pointVisible, clipLine, interpolate, clipStart) {
    return function(rotate, listener) {
      var line = clipLine(listener), rotatedClipStart = rotate.invert(clipStart[0], clipStart[1]);
      var clip = {
        point: point,
        lineStart: lineStart,
        lineEnd: lineEnd,
        polygonStart: function() {
          clip.point = pointRing;
          clip.lineStart = ringStart;
          clip.lineEnd = ringEnd;
          segments = [];
          polygon = [];
        },
        polygonEnd: function() {
          clip.point = point;
          clip.lineStart = lineStart;
          clip.lineEnd = lineEnd;
          segments = d3.merge(segments);
          var clipStartInside = d3_geo_pointInPolygon(rotatedClipStart, polygon);
          if (segments.length) {
            if (!polygonStarted) listener.polygonStart(), polygonStarted = true;
            d3_geo_clipPolygon(segments, d3_geo_clipSort, clipStartInside, interpolate, listener);
          } else if (clipStartInside) {
            if (!polygonStarted) listener.polygonStart(), polygonStarted = true;
            listener.lineStart();
            interpolate(null, null, 1, listener);
            listener.lineEnd();
          }
          if (polygonStarted) listener.polygonEnd(), polygonStarted = false;
          segments = polygon = null;
        },
        sphere: function() {
          listener.polygonStart();
          listener.lineStart();
          interpolate(null, null, 1, listener);
          listener.lineEnd();
          listener.polygonEnd();
        }
      };
      function point(λ, φ) {
        var point = rotate(λ, φ);
        if (pointVisible(λ = point[0], φ = point[1])) listener.point(λ, φ);
      }
      function pointLine(λ, φ) {
        var point = rotate(λ, φ);
        line.point(point[0], point[1]);
      }
      function lineStart() {
        clip.point = pointLine;
        line.lineStart();
      }
      function lineEnd() {
        clip.point = point;
        line.lineEnd();
      }
      var segments;
      var buffer = d3_geo_clipBufferListener(), ringListener = clipLine(buffer), polygonStarted = false, polygon, ring;
      function pointRing(λ, φ) {
        ring.push([ λ, φ ]);
        var point = rotate(λ, φ);
        ringListener.point(point[0], point[1]);
      }
      function ringStart() {
        ringListener.lineStart();
        ring = [];
      }
      function ringEnd() {
        pointRing(ring[0][0], ring[0][1]);
        ringListener.lineEnd();
        var clean = ringListener.clean(), ringSegments = buffer.buffer(), segment, n = ringSegments.length;
        ring.pop();
        polygon.push(ring);
        ring = null;
        if (!n) return;
        if (clean & 1) {
          segment = ringSegments[0];
          var n = segment.length - 1, i = -1, point;
          if (n > 0) {
            if (!polygonStarted) listener.polygonStart(), polygonStarted = true;
            listener.lineStart();
            while (++i < n) listener.point((point = segment[i])[0], point[1]);
            listener.lineEnd();
          }
          return;
        }
        if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift()));
        segments.push(ringSegments.filter(d3_geo_clipSegmentLength1));
      }
      return clip;
    };
  }
  function d3_geo_clipSegmentLength1(segment) {
    return segment.length > 1;
  }
  function d3_geo_clipBufferListener() {
    var lines = [], line;
    return {
      lineStart: function() {
        lines.push(line = []);
      },
      point: function(λ, φ) {
        line.push([ λ, φ ]);
      },
      lineEnd: d3_noop,
      buffer: function() {
        var buffer = lines;
        lines = [];
        line = null;
        return buffer;
      },
      rejoin: function() {
        if (lines.length > 1) lines.push(lines.pop().concat(lines.shift()));
      }
    };
  }
  function d3_geo_clipSort(a, b) {
    return ((a = a.x)[0] < 0 ? a[1] - halfπ - ε : halfπ - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfπ - ε : halfπ - b[1]);
  }
  var d3_geo_clipAntimeridian = d3_geo_clip(d3_true, d3_geo_clipAntimeridianLine, d3_geo_clipAntimeridianInterpolate, [ -π, -π / 2 ]);
  function d3_geo_clipAntimeridianLine(listener) {
    var λ0 = NaN, φ0 = NaN, sλ0 = NaN, clean;
    return {
      lineStart: function() {
        listener.lineStart();
        clean = 1;
      },
      point: function(λ1, φ1) {
        var sλ1 = λ1 > 0 ? π : -π, dλ = abs(λ1 - λ0);
        if (abs(dλ - π) < ε) {
          listener.point(λ0, φ0 = (φ0 + φ1) / 2 > 0 ? halfπ : -halfπ);
          listener.point(sλ0, φ0);
          listener.lineEnd();
          listener.lineStart();
          listener.point(sλ1, φ0);
          listener.point(λ1, φ0);
          clean = 0;
        } else if (sλ0 !== sλ1 && dλ >= π) {
          if (abs(λ0 - sλ0) < ε) λ0 -= sλ0 * ε;
          if (abs(λ1 - sλ1) < ε) λ1 -= sλ1 * ε;
          φ0 = d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1);
          listener.point(sλ0, φ0);
          listener.lineEnd();
          listener.lineStart();
          listener.point(sλ1, φ0);
          clean = 0;
        }
        listener.point(λ0 = λ1, φ0 = φ1);
        sλ0 = sλ1;
      },
      lineEnd: function() {
        listener.lineEnd();
        λ0 = φ0 = NaN;
      },
      clean: function() {
        return 2 - clean;
      }
    };
  }
  function d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1) {
    var cosφ0, cosφ1, sinλ0_λ1 = Math.sin(λ0 - λ1);
    return abs(sinλ0_λ1) > ε ? Math.atan((Math.sin(φ0) * (cosφ1 = Math.cos(φ1)) * Math.sin(λ1) - Math.sin(φ1) * (cosφ0 = Math.cos(φ0)) * Math.sin(λ0)) / (cosφ0 * cosφ1 * sinλ0_λ1)) : (φ0 + φ1) / 2;
  }
  function d3_geo_clipAntimeridianInterpolate(from, to, direction, listener) {
    var φ;
    if (from == null) {
      φ = direction * halfπ;
      listener.point(-π, φ);
      listener.point(0, φ);
      listener.point(π, φ);
      listener.point(π, 0);
      listener.point(π, -φ);
      listener.point(0, -φ);
      listener.point(-π, -φ);
      listener.point(-π, 0);
      listener.point(-π, φ);
    } else if (abs(from[0] - to[0]) > ε) {
      var s = from[0] < to[0] ? π : -π;
      φ = direction * s / 2;
      listener.point(-s, φ);
      listener.point(0, φ);
      listener.point(s, φ);
    } else {
      listener.point(to[0], to[1]);
    }
  }
  function d3_geo_pointInPolygon(point, polygon) {
    var meridian = point[0], parallel = point[1], meridianNormal = [ Math.sin(meridian), -Math.cos(meridian), 0 ], polarAngle = 0, winding = 0;
    d3_geo_areaRingSum.reset();
    for (var i = 0, n = polygon.length; i < n; ++i) {
      var ring = polygon[i], m = ring.length;
      if (!m) continue;
      var point0 = ring[0], λ0 = point0[0], φ0 = point0[1] / 2 + π / 4, sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), j = 1;
      while (true) {
        if (j === m) j = 0;
        point = ring[j];
        var λ = point[0], φ = point[1] / 2 + π / 4, sinφ = Math.sin(φ), cosφ = Math.cos(φ), dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, antimeridian = adλ > π, k = sinφ0 * sinφ;
        d3_geo_areaRingSum.add(Math.atan2(k * sdλ * Math.sin(adλ), cosφ0 * cosφ + k * Math.cos(adλ)));
        polarAngle += antimeridian ? dλ + sdλ * τ : dλ;
        if (antimeridian ^ λ0 >= meridian ^ λ >= meridian) {
          var arc = d3_geo_cartesianCross(d3_geo_cartesian(point0), d3_geo_cartesian(point));
          d3_geo_cartesianNormalize(arc);
          var intersection = d3_geo_cartesianCross(meridianNormal, arc);
          d3_geo_cartesianNormalize(intersection);
          var φarc = (antimeridian ^ dλ >= 0 ? -1 : 1) * d3_asin(intersection[2]);
          if (parallel > φarc || parallel === φarc && (arc[0] || arc[1])) {
            winding += antimeridian ^ dλ >= 0 ? 1 : -1;
          }
        }
        if (!j++) break;
        λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ, point0 = point;
      }
    }
    return (polarAngle < -ε || polarAngle < ε && d3_geo_areaRingSum < -ε) ^ winding & 1;
  }
  function d3_geo_clipCircle(radius) {
    var cr = Math.cos(radius), smallRadius = cr > 0, notHemisphere = abs(cr) > ε, interpolate = d3_geo_circleInterpolate(radius, 6 * d3_radians);
    return d3_geo_clip(visible, clipLine, interpolate, smallRadius ? [ 0, -radius ] : [ -π, radius - π ]);
    function visible(λ, φ) {
      return Math.cos(λ) * Math.cos(φ) > cr;
    }
    function clipLine(listener) {
      var point0, c0, v0, v00, clean;
      return {
        lineStart: function() {
          v00 = v0 = false;
          clean = 1;
        },
        point: function(λ, φ) {
          var point1 = [ λ, φ ], point2, v = visible(λ, φ), c = smallRadius ? v ? 0 : code(λ, φ) : v ? code(λ + (λ < 0 ? π : -π), φ) : 0;
          if (!point0 && (v00 = v0 = v)) listener.lineStart();
          if (v !== v0) {
            point2 = intersect(point0, point1);
            if (d3_geo_sphericalEqual(point0, point2) || d3_geo_sphericalEqual(point1, point2)) {
              point1[0] += ε;
              point1[1] += ε;
              v = visible(point1[0], point1[1]);
            }
          }
          if (v !== v0) {
            clean = 0;
            if (v) {
              listener.lineStart();
              point2 = intersect(point1, point0);
              listener.point(point2[0], point2[1]);
            } else {
              point2 = intersect(point0, point1);
              listener.point(point2[0], point2[1]);
              listener.lineEnd();
            }
            point0 = point2;
          } else if (notHemisphere && point0 && smallRadius ^ v) {
            var t;
            if (!(c & c0) && (t = intersect(point1, point0, true))) {
              clean = 0;
              if (smallRadius) {
                listener.lineStart();
                listener.point(t[0][0], t[0][1]);
                listener.point(t[1][0], t[1][1]);
                listener.lineEnd();
              } else {
                listener.point(t[1][0], t[1][1]);
                listener.lineEnd();
                listener.lineStart();
                listener.point(t[0][0], t[0][1]);
              }
            }
          }
          if (v && (!point0 || !d3_geo_sphericalEqual(point0, point1))) {
            listener.point(point1[0], point1[1]);
          }
          point0 = point1, v0 = v, c0 = c;
        },
        lineEnd: function() {
          if (v0) listener.lineEnd();
          point0 = null;
        },
        clean: function() {
          return clean | (v00 && v0) << 1;
        }
      };
    }
    function intersect(a, b, two) {
      var pa = d3_geo_cartesian(a), pb = d3_geo_cartesian(b);
      var n1 = [ 1, 0, 0 ], n2 = d3_geo_cartesianCross(pa, pb), n2n2 = d3_geo_cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2;
      if (!determinant) return !two && a;
      var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = d3_geo_cartesianCross(n1, n2), A = d3_geo_cartesianScale(n1, c1), B = d3_geo_cartesianScale(n2, c2);
      d3_geo_cartesianAdd(A, B);
      var u = n1xn2, w = d3_geo_cartesianDot(A, u), uu = d3_geo_cartesianDot(u, u), t2 = w * w - uu * (d3_geo_cartesianDot(A, A) - 1);
      if (t2 < 0) return;
      var t = Math.sqrt(t2), q = d3_geo_cartesianScale(u, (-w - t) / uu);
      d3_geo_cartesianAdd(q, A);
      q = d3_geo_spherical(q);
      if (!two) return q;
      var λ0 = a[0], λ1 = b[0], φ0 = a[1], φ1 = b[1], z;
      if (λ1 < λ0) z = λ0, λ0 = λ1, λ1 = z;
      var δλ = λ1 - λ0, polar = abs(δλ - π) < ε, meridian = polar || δλ < ε;
      if (!polar && φ1 < φ0) z = φ0, φ0 = φ1, φ1 = z;
      if (meridian ? polar ? φ0 + φ1 > 0 ^ q[1] < (abs(q[0] - λ0) < ε ? φ0 : φ1) : φ0 <= q[1] && q[1] <= φ1 : δλ > π ^ (λ0 <= q[0] && q[0] <= λ1)) {
        var q1 = d3_geo_cartesianScale(u, (-w + t) / uu);
        d3_geo_cartesianAdd(q1, A);
        return [ q, d3_geo_spherical(q1) ];
      }
    }
    function code(λ, φ) {
      var r = smallRadius ? radius : π - radius, code = 0;
      if (λ < -r) code |= 1; else if (λ > r) code |= 2;
      if (φ < -r) code |= 4; else if (φ > r) code |= 8;
      return code;
    }
  }
  function d3_geom_clipLine(x0, y0, x1, y1) {
    return function(line) {
      var a = line.a, b = line.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay, r;
      r = x0 - ax;
      if (!dx && r > 0) return;
      r /= dx;
      if (dx < 0) {
        if (r < t0) return;
        if (r < t1) t1 = r;
      } else if (dx > 0) {
        if (r > t1) return;
        if (r > t0) t0 = r;
      }
      r = x1 - ax;
      if (!dx && r < 0) return;
      r /= dx;
      if (dx < 0) {
        if (r > t1) return;
        if (r > t0) t0 = r;
      } else if (dx > 0) {
        if (r < t0) return;
        if (r < t1) t1 = r;
      }
      r = y0 - ay;
      if (!dy && r > 0) return;
      r /= dy;
      if (dy < 0) {
        if (r < t0) return;
        if (r < t1) t1 = r;
      } else if (dy > 0) {
        if (r > t1) return;
        if (r > t0) t0 = r;
      }
      r = y1 - ay;
      if (!dy && r < 0) return;
      r /= dy;
      if (dy < 0) {
        if (r > t1) return;
        if (r > t0) t0 = r;
      } else if (dy > 0) {
        if (r < t0) return;
        if (r < t1) t1 = r;
      }
      if (t0 > 0) line.a = {
        x: ax + t0 * dx,
        y: ay + t0 * dy
      };
      if (t1 < 1) line.b = {
        x: ax + t1 * dx,
        y: ay + t1 * dy
      };
      return line;
    };
  }
  var d3_geo_clipExtentMAX = 1e9;
  d3.geo.clipExtent = function() {
    var x0, y0, x1, y1, stream, clip, clipExtent = {
      stream: function(output) {
        if (stream) stream.valid = false;
        stream = clip(output);
        stream.valid = true;
        return stream;
      },
      extent: function(_) {
        if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ];
        clip = d3_geo_clipExtent(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]);
        if (stream) stream.valid = false, stream = null;
        return clipExtent;
      }
    };
    return clipExtent.extent([ [ 0, 0 ], [ 960, 500 ] ]);
  };
  function d3_geo_clipExtent(x0, y0, x1, y1) {
    return function(listener) {
      var listener_ = listener, bufferListener = d3_geo_clipBufferListener(), clipLine = d3_geom_clipLine(x0, y0, x1, y1), segments, polygon, ring;
      var clip = {
        point: point,
        lineStart: lineStart,
        lineEnd: lineEnd,
        polygonStart: function() {
          listener = bufferListener;
          segments = [];
          polygon = [];
          clean = true;
        },
        polygonEnd: function() {
          listener = listener_;
          segments = d3.merge(segments);
          var clipStartInside = insidePolygon([ x0, y1 ]), inside = clean && clipStartInside, visible = segments.length;
          if (inside || visible) {
            listener.polygonStart();
            if (inside) {
              listener.lineStart();
              interpolate(null, null, 1, listener);
              listener.lineEnd();
            }
            if (visible) {
              d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener);
            }
            listener.polygonEnd();
          }
          segments = polygon = ring = null;
        }
      };
      function insidePolygon(p) {
        var wn = 0, n = polygon.length, y = p[1];
        for (var i = 0; i < n; ++i) {
          for (var j = 1, v = polygon[i], m = v.length, a = v[0], b; j < m; ++j) {
            b = v[j];
            if (a[1] <= y) {
              if (b[1] > y && d3_cross2d(a, b, p) > 0) ++wn;
            } else {
              if (b[1] <= y && d3_cross2d(a, b, p) < 0) --wn;
            }
            a = b;
          }
        }
        return wn !== 0;
      }
      function interpolate(from, to, direction, listener) {
        var a = 0, a1 = 0;
        if (from == null || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoints(from, to) < 0 ^ direction > 0) {
          do {
            listener.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0);
          } while ((a = (a + direction + 4) % 4) !== a1);
        } else {
          listener.point(to[0], to[1]);
        }
      }
      function pointVisible(x, y) {
        return x0 <= x && x <= x1 && y0 <= y && y <= y1;
      }
      function point(x, y) {
        if (pointVisible(x, y)) listener.point(x, y);
      }
      var x__, y__, v__, x_, y_, v_, first, clean;
      function lineStart() {
        clip.point = linePoint;
        if (polygon) polygon.push(ring = []);
        first = true;
        v_ = false;
        x_ = y_ = NaN;
      }
      function lineEnd() {
        if (segments) {
          linePoint(x__, y__);
          if (v__ && v_) bufferListener.rejoin();
          segments.push(bufferListener.buffer());
        }
        clip.point = point;
        if (v_) listener.lineEnd();
      }
      function linePoint(x, y) {
        x = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, x));
        y = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, y));
        var v = pointVisible(x, y);
        if (polygon) ring.push([ x, y ]);
        if (first) {
          x__ = x, y__ = y, v__ = v;
          first = false;
          if (v) {
            listener.lineStart();
            listener.point(x, y);
          }
        } else {
          if (v && v_) listener.point(x, y); else {
            var l = {
              a: {
                x: x_,
                y: y_
              },
              b: {
                x: x,
                y: y
              }
            };
            if (clipLine(l)) {
              if (!v_) {
                listener.lineStart();
                listener.point(l.a.x, l.a.y);
              }
              listener.point(l.b.x, l.b.y);
              if (!v) listener.lineEnd();
              clean = false;
            } else if (v) {
              listener.lineStart();
              listener.point(x, y);
              clean = false;
            }
          }
        }
        x_ = x, y_ = y, v_ = v;
      }
      return clip;
    };
    function corner(p, direction) {
      return abs(p[0] - x0) < ε ? direction > 0 ? 0 : 3 : abs(p[0] - x1) < ε ? direction > 0 ? 2 : 1 : abs(p[1] - y0) < ε ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2;
    }
    function compare(a, b) {
      return comparePoints(a.x, b.x);
    }
    function comparePoints(a, b) {
      var ca = corner(a, 1), cb = corner(b, 1);
      return ca !== cb ? ca - cb : ca === 0 ? b[1] - a[1] : ca === 1 ? a[0] - b[0] : ca === 2 ? a[1] - b[1] : b[0] - a[0];
    }
  }
  function d3_geo_conic(projectAt) {
    var φ0 = 0, φ1 = π / 3, m = d3_geo_projectionMutator(projectAt), p = m(φ0, φ1);
    p.parallels = function(_) {
      if (!arguments.length) return [ φ0 / π * 180, φ1 / π * 180 ];
      return m(φ0 = _[0] * π / 180, φ1 = _[1] * π / 180);
    };
    return p;
  }
  function d3_geo_conicEqualArea(φ0, φ1) {
    var sinφ0 = Math.sin(φ0), n = (sinφ0 + Math.sin(φ1)) / 2, C = 1 + sinφ0 * (2 * n - sinφ0), ρ0 = Math.sqrt(C) / n;
    function forward(λ, φ) {
      var ρ = Math.sqrt(C - 2 * n * Math.sin(φ)) / n;
      return [ ρ * Math.sin(λ *= n), ρ0 - ρ * Math.cos(λ) ];
    }
    forward.invert = function(x, y) {
      var ρ0_y = ρ0 - y;
      return [ Math.atan2(x, ρ0_y) / n, d3_asin((C - (x * x + ρ0_y * ρ0_y) * n * n) / (2 * n)) ];
    };
    return forward;
  }
  (d3.geo.conicEqualArea = function() {
    return d3_geo_conic(d3_geo_conicEqualArea);
  }).raw = d3_geo_conicEqualArea;
  d3.geo.albers = function() {
    return d3.geo.conicEqualArea().rotate([ 96, 0 ]).center([ -.6, 38.7 ]).parallels([ 29.5, 45.5 ]).scale(1070);
  };
  d3.geo.albersUsa = function() {
    var lower48 = d3.geo.albers();
    var alaska = d3.geo.conicEqualArea().rotate([ 154, 0 ]).center([ -2, 58.5 ]).parallels([ 55, 65 ]);
    var hawaii = d3.geo.conicEqualArea().rotate([ 157, 0 ]).center([ -3, 19.9 ]).parallels([ 8, 18 ]);
    var point, pointStream = {
      point: function(x, y) {
        point = [ x, y ];
      }
    }, lower48Point, alaskaPoint, hawaiiPoint;
    function albersUsa(coordinates) {
      var x = coordinates[0], y = coordinates[1];
      point = null;
      (lower48Point(x, y), point) || (alaskaPoint(x, y), point) || hawaiiPoint(x, y);
      return point;
    }
    albersUsa.invert = function(coordinates) {
      var k = lower48.scale(), t = lower48.translate(), x = (coordinates[0] - t[0]) / k, y = (coordinates[1] - t[1]) / k;
      return (y >= .12 && y < .234 && x >= -.425 && x < -.214 ? alaska : y >= .166 && y < .234 && x >= -.214 && x < -.115 ? hawaii : lower48).invert(coordinates);
    };
    albersUsa.stream = function(stream) {
      var lower48Stream = lower48.stream(stream), alaskaStream = alaska.stream(stream), hawaiiStream = hawaii.stream(stream);
      return {
        point: function(x, y) {
          lower48Stream.point(x, y);
          alaskaStream.point(x, y);
          hawaiiStream.point(x, y);
        },
        sphere: function() {
          lower48Stream.sphere();
          alaskaStream.sphere();
          hawaiiStream.sphere();
        },
        lineStart: function() {
          lower48Stream.lineStart();
          alaskaStream.lineStart();
          hawaiiStream.lineStart();
        },
        lineEnd: function() {
          lower48Stream.lineEnd();
          alaskaStream.lineEnd();
          hawaiiStream.lineEnd();
        },
        polygonStart: function() {
          lower48Stream.polygonStart();
          alaskaStream.polygonStart();
          hawaiiStream.polygonStart();
        },
        polygonEnd: function() {
          lower48Stream.polygonEnd();
          alaskaStream.polygonEnd();
          hawaiiStream.polygonEnd();
        }
      };
    };
    albersUsa.precision = function(_) {
      if (!arguments.length) return lower48.precision();
      lower48.precision(_);
      alaska.precision(_);
      hawaii.precision(_);
      return albersUsa;
    };
    albersUsa.scale = function(_) {
      if (!arguments.length) return lower48.scale();
      lower48.scale(_);
      alaska.scale(_ * .35);
      hawaii.scale(_);
      return albersUsa.translate(lower48.translate());
    };
    albersUsa.translate = function(_) {
      if (!arguments.length) return lower48.translate();
      var k = lower48.scale(), x = +_[0], y = +_[1];
      lower48Point = lower48.translate(_).clipExtent([ [ x - .455 * k, y - .238 * k ], [ x + .455 * k, y + .238 * k ] ]).stream(pointStream).point;
      alaskaPoint = alaska.translate([ x - .307 * k, y + .201 * k ]).clipExtent([ [ x - .425 * k + ε, y + .12 * k + ε ], [ x - .214 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point;
      hawaiiPoint = hawaii.translate([ x - .205 * k, y + .212 * k ]).clipExtent([ [ x - .214 * k + ε, y + .166 * k + ε ], [ x - .115 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point;
      return albersUsa;
    };
    return albersUsa.scale(1070);
  };
  var d3_geo_pathAreaSum, d3_geo_pathAreaPolygon, d3_geo_pathArea = {
    point: d3_noop,
    lineStart: d3_noop,
    lineEnd: d3_noop,
    polygonStart: function() {
      d3_geo_pathAreaPolygon = 0;
      d3_geo_pathArea.lineStart = d3_geo_pathAreaRingStart;
    },
    polygonEnd: function() {
      d3_geo_pathArea.lineStart = d3_geo_pathArea.lineEnd = d3_geo_pathArea.point = d3_noop;
      d3_geo_pathAreaSum += abs(d3_geo_pathAreaPolygon / 2);
    }
  };
  function d3_geo_pathAreaRingStart() {
    var x00, y00, x0, y0;
    d3_geo_pathArea.point = function(x, y) {
      d3_geo_pathArea.point = nextPoint;
      x00 = x0 = x, y00 = y0 = y;
    };
    function nextPoint(x, y) {
      d3_geo_pathAreaPolygon += y0 * x - x0 * y;
      x0 = x, y0 = y;
    }
    d3_geo_pathArea.lineEnd = function() {
      nextPoint(x00, y00);
    };
  }
  var d3_geo_pathBoundsX0, d3_geo_pathBoundsY0, d3_geo_pathBoundsX1, d3_geo_pathBoundsY1;
  var d3_geo_pathBounds = {
    point: d3_geo_pathBoundsPoint,
    lineStart: d3_noop,
    lineEnd: d3_noop,
    polygonStart: d3_noop,
    polygonEnd: d3_noop
  };
  function d3_geo_pathBoundsPoint(x, y) {
    if (x < d3_geo_pathBoundsX0) d3_geo_pathBoundsX0 = x;
    if (x > d3_geo_pathBoundsX1) d3_geo_pathBoundsX1 = x;
    if (y < d3_geo_pathBoundsY0) d3_geo_pathBoundsY0 = y;
    if (y > d3_geo_pathBoundsY1) d3_geo_pathBoundsY1 = y;
  }
  function d3_geo_pathBuffer() {
    var pointCircle = d3_geo_pathBufferCircle(4.5), buffer = [];
    var stream = {
      point: point,
      lineStart: function() {
        stream.point = pointLineStart;
      },
      lineEnd: lineEnd,
      polygonStart: function() {
        stream.lineEnd = lineEndPolygon;
      },
      polygonEnd: function() {
        stream.lineEnd = lineEnd;
        stream.point = point;
      },
      pointRadius: function(_) {
        pointCircle = d3_geo_pathBufferCircle(_);
        return stream;
      },
      result: function() {
        if (buffer.length) {
          var result = buffer.join("");
          buffer = [];
          return result;
        }
      }
    };
    function point(x, y) {
      buffer.push("M", x, ",", y, pointCircle);
    }
    function pointLineStart(x, y) {
      buffer.push("M", x, ",", y);
      stream.point = pointLine;
    }
    function pointLine(x, y) {
      buffer.push("L", x, ",", y);
    }
    function lineEnd() {
      stream.point = point;
    }
    function lineEndPolygon() {
      buffer.push("Z");
    }
    return stream;
  }
  function d3_geo_pathBufferCircle(radius) {
    return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius + "z";
  }
  var d3_geo_pathCentroid = {
    point: d3_geo_pathCentroidPoint,
    lineStart: d3_geo_pathCentroidLineStart,
    lineEnd: d3_geo_pathCentroidLineEnd,
    polygonStart: function() {
      d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidRingStart;
    },
    polygonEnd: function() {
      d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint;
      d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidLineStart;
      d3_geo_pathCentroid.lineEnd = d3_geo_pathCentroidLineEnd;
    }
  };
  function d3_geo_pathCentroidPoint(x, y) {
    d3_geo_centroidX0 += x;
    d3_geo_centroidY0 += y;
    ++d3_geo_centroidZ0;
  }
  function d3_geo_pathCentroidLineStart() {
    var x0, y0;
    d3_geo_pathCentroid.point = function(x, y) {
      d3_geo_pathCentroid.point = nextPoint;
      d3_geo_pathCentroidPoint(x0 = x, y0 = y);
    };
    function nextPoint(x, y) {
      var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy);
      d3_geo_centroidX1 += z * (x0 + x) / 2;
      d3_geo_centroidY1 += z * (y0 + y) / 2;
      d3_geo_centroidZ1 += z;
      d3_geo_pathCentroidPoint(x0 = x, y0 = y);
    }
  }
  function d3_geo_pathCentroidLineEnd() {
    d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint;
  }
  function d3_geo_pathCentroidRingStart() {
    var x00, y00, x0, y0;
    d3_geo_pathCentroid.point = function(x, y) {
      d3_geo_pathCentroid.point = nextPoint;
      d3_geo_pathCentroidPoint(x00 = x0 = x, y00 = y0 = y);
    };
    function nextPoint(x, y) {
      var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy);
      d3_geo_centroidX1 += z * (x0 + x) / 2;
      d3_geo_centroidY1 += z * (y0 + y) / 2;
      d3_geo_centroidZ1 += z;
      z = y0 * x - x0 * y;
      d3_geo_centroidX2 += z * (x0 + x);
      d3_geo_centroidY2 += z * (y0 + y);
      d3_geo_centroidZ2 += z * 3;
      d3_geo_pathCentroidPoint(x0 = x, y0 = y);
    }
    d3_geo_pathCentroid.lineEnd = function() {
      nextPoint(x00, y00);
    };
  }
  function d3_geo_pathContext(context) {
    var pointRadius = 4.5;
    var stream = {
      point: point,
      lineStart: function() {
        stream.point = pointLineStart;
      },
      lineEnd: lineEnd,
      polygonStart: function() {
        stream.lineEnd = lineEndPolygon;
      },
      polygonEnd: function() {
        stream.lineEnd = lineEnd;
        stream.point = point;
      },
      pointRadius: function(_) {
        pointRadius = _;
        return stream;
      },
      result: d3_noop
    };
    function point(x, y) {
      context.moveTo(x + pointRadius, y);
      context.arc(x, y, pointRadius, 0, τ);
    }
    function pointLineStart(x, y) {
      context.moveTo(x, y);
      stream.point = pointLine;
    }
    function pointLine(x, y) {
      context.lineTo(x, y);
    }
    function lineEnd() {
      stream.point = point;
    }
    function lineEndPolygon() {
      context.closePath();
    }
    return stream;
  }
  function d3_geo_resample(project) {
    var δ2 = .5, cosMinDistance = Math.cos(30 * d3_radians), maxDepth = 16;
    function resample(stream) {
      return (maxDepth ? resampleRecursive : resampleNone)(stream);
    }
    function resampleNone(stream) {
      return d3_geo_transformPoint(stream, function(x, y) {
        x = project(x, y);
        stream.point(x[0], x[1]);
      });
    }
    function resampleRecursive(stream) {
      var λ00, φ00, x00, y00, a00, b00, c00, λ0, x0, y0, a0, b0, c0;
      var resample = {
        point: point,
        lineStart: lineStart,
        lineEnd: lineEnd,
        polygonStart: function() {
          stream.polygonStart();
          resample.lineStart = ringStart;
        },
        polygonEnd: function() {
          stream.polygonEnd();
          resample.lineStart = lineStart;
        }
      };
      function point(x, y) {
        x = project(x, y);
        stream.point(x[0], x[1]);
      }
      function lineStart() {
        x0 = NaN;
        resample.point = linePoint;
        stream.lineStart();
      }
      function linePoint(λ, φ) {
        var c = d3_geo_cartesian([ λ, φ ]), p = project(λ, φ);
        resampleLineTo(x0, y0, λ0, a0, b0, c0, x0 = p[0], y0 = p[1], λ0 = λ, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream);
        stream.point(x0, y0);
      }
      function lineEnd() {
        resample.point = point;
        stream.lineEnd();
      }
      function ringStart() {
        lineStart();
        resample.point = ringPoint;
        resample.lineEnd = ringEnd;
      }
      function ringPoint(λ, φ) {
        linePoint(λ00 = λ, φ00 = φ), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0;
        resample.point = linePoint;
      }
      function ringEnd() {
        resampleLineTo(x0, y0, λ0, a0, b0, c0, x00, y00, λ00, a00, b00, c00, maxDepth, stream);
        resample.lineEnd = lineEnd;
        lineEnd();
      }
      return resample;
    }
    function resampleLineTo(x0, y0, λ0, a0, b0, c0, x1, y1, λ1, a1, b1, c1, depth, stream) {
      var dx = x1 - x0, dy = y1 - y0, d2 = dx * dx + dy * dy;
      if (d2 > 4 * δ2 && depth--) {
        var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = Math.sqrt(a * a + b * b + c * c), φ2 = Math.asin(c /= m), λ2 = abs(abs(c) - 1) < ε || abs(λ0 - λ1) < ε ? (λ0 + λ1) / 2 : Math.atan2(b, a), p = project(λ2, φ2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2;
        if (dz * dz / d2 > δ2 || abs((dx * dx2 + dy * dy2) / d2 - .5) > .3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) {
          resampleLineTo(x0, y0, λ0, a0, b0, c0, x2, y2, λ2, a /= m, b /= m, c, depth, stream);
          stream.point(x2, y2);
          resampleLineTo(x2, y2, λ2, a, b, c, x1, y1, λ1, a1, b1, c1, depth, stream);
        }
      }
    }
    resample.precision = function(_) {
      if (!arguments.length) return Math.sqrt(δ2);
      maxDepth = (δ2 = _ * _) > 0 && 16;
      return resample;
    };
    return resample;
  }
  d3.geo.path = function() {
    var pointRadius = 4.5, projection, context, projectStream, contextStream, cacheStream;
    function path(object) {
      if (object) {
        if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments));
        if (!cacheStream || !cacheStream.valid) cacheStream = projectStream(contextStream);
        d3.geo.stream(object, cacheStream);
      }
      return contextStream.result();
    }
    path.area = function(object) {
      d3_geo_pathAreaSum = 0;
      d3.geo.stream(object, projectStream(d3_geo_pathArea));
      return d3_geo_pathAreaSum;
    };
    path.centroid = function(object) {
      d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0;
      d3.geo.stream(object, projectStream(d3_geo_pathCentroid));
      return d3_geo_centroidZ2 ? [ d3_geo_centroidX2 / d3_geo_centroidZ2, d3_geo_centroidY2 / d3_geo_centroidZ2 ] : d3_geo_centroidZ1 ? [ d3_geo_centroidX1 / d3_geo_centroidZ1, d3_geo_centroidY1 / d3_geo_centroidZ1 ] : d3_geo_centroidZ0 ? [ d3_geo_centroidX0 / d3_geo_centroidZ0, d3_geo_centroidY0 / d3_geo_centroidZ0 ] : [ NaN, NaN ];
    };
    path.bounds = function(object) {
      d3_geo_pathBoundsX1 = d3_geo_pathBoundsY1 = -(d3_geo_pathBoundsX0 = d3_geo_pathBoundsY0 = Infinity);
      d3.geo.stream(object, projectStream(d3_geo_pathBounds));
      return [ [ d3_geo_pathBoundsX0, d3_geo_pathBoundsY0 ], [ d3_geo_pathBoundsX1, d3_geo_pathBoundsY1 ] ];
    };
    path.projection = function(_) {
      if (!arguments.length) return projection;
      projectStream = (projection = _) ? _.stream || d3_geo_pathProjectStream(_) : d3_identity;
      return reset();
    };
    path.context = function(_) {
      if (!arguments.length) return context;
      contextStream = (context = _) == null ? new d3_geo_pathBuffer() : new d3_geo_pathContext(_);
      if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius);
      return reset();
    };
    path.pointRadius = function(_) {
      if (!arguments.length) return pointRadius;
      pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_);
      return path;
    };
    function reset() {
      cacheStream = null;
      return path;
    }
    return path.projection(d3.geo.albersUsa()).context(null);
  };
  function d3_geo_pathProjectStream(project) {
    var resample = d3_geo_resample(function(x, y) {
      return project([ x * d3_degrees, y * d3_degrees ]);
    });
    return function(stream) {
      return d3_geo_projectionRadians(resample(stream));
    };
  }
  d3.geo.transform = function(methods) {
    return {
      stream: function(stream) {
        var transform = new d3_geo_transform(stream);
        for (var k in methods) transform[k] = methods[k];
        return transform;
      }
    };
  };
  function d3_geo_transform(stream) {
    this.stream = stream;
  }
  d3_geo_transform.prototype = {
    point: function(x, y) {
      this.stream.point(x, y);
    },
    sphere: function() {
      this.stream.sphere();
    },
    lineStart: function() {
      this.stream.lineStart();
    },
    lineEnd: function() {
      this.stream.lineEnd();
    },
    polygonStart: function() {
      this.stream.polygonStart();
    },
    polygonEnd: function() {
      this.stream.polygonEnd();
    }
  };
  function d3_geo_transformPoint(stream, point) {
    return {
      point: point,
      sphere: function() {
        stream.sphere();
      },
      lineStart: function() {
        stream.lineStart();
      },
      lineEnd: function() {
        stream.lineEnd();
      },
      polygonStart: function() {
        stream.polygonStart();
      },
      polygonEnd: function() {
        stream.polygonEnd();
      }
    };
  }
  d3.geo.projection = d3_geo_projection;
  d3.geo.projectionMutator = d3_geo_projectionMutator;
  function d3_geo_projection(project) {
    return d3_geo_projectionMutator(function() {
      return project;
    })();
  }
  function d3_geo_projectionMutator(projectAt) {
    var project, rotate, projectRotate, projectResample = d3_geo_resample(function(x, y) {
      x = project(x, y);
      return [ x[0] * k + δx, δy - x[1] * k ];
    }), k = 150, x = 480, y = 250, λ = 0, φ = 0, δλ = 0, δφ = 0, δγ = 0, δx, δy, preclip = d3_geo_clipAntimeridian, postclip = d3_identity, clipAngle = null, clipExtent = null, stream;
    function projection(point) {
      point = projectRotate(point[0] * d3_radians, point[1] * d3_radians);
      return [ point[0] * k + δx, δy - point[1] * k ];
    }
    function invert(point) {
      point = projectRotate.invert((point[0] - δx) / k, (δy - point[1]) / k);
      return point && [ point[0] * d3_degrees, point[1] * d3_degrees ];
    }
    projection.stream = function(output) {
      if (stream) stream.valid = false;
      stream = d3_geo_projectionRadians(preclip(rotate, projectResample(postclip(output))));
      stream.valid = true;
      return stream;
    };
    projection.clipAngle = function(_) {
      if (!arguments.length) return clipAngle;
      preclip = _ == null ? (clipAngle = _, d3_geo_clipAntimeridian) : d3_geo_clipCircle((clipAngle = +_) * d3_radians);
      return invalidate();
    };
    projection.clipExtent = function(_) {
      if (!arguments.length) return clipExtent;
      clipExtent = _;
      postclip = _ ? d3_geo_clipExtent(_[0][0], _[0][1], _[1][0], _[1][1]) : d3_identity;
      return invalidate();
    };
    projection.scale = function(_) {
      if (!arguments.length) return k;
      k = +_;
      return reset();
    };
    projection.translate = function(_) {
      if (!arguments.length) return [ x, y ];
      x = +_[0];
      y = +_[1];
      return reset();
    };
    projection.center = function(_) {
      if (!arguments.length) return [ λ * d3_degrees, φ * d3_degrees ];
      λ = _[0] % 360 * d3_radians;
      φ = _[1] % 360 * d3_radians;
      return reset();
    };
    projection.rotate = function(_) {
      if (!arguments.length) return [ δλ * d3_degrees, δφ * d3_degrees, δγ * d3_degrees ];
      δλ = _[0] % 360 * d3_radians;
      δφ = _[1] % 360 * d3_radians;
      δγ = _.length > 2 ? _[2] % 360 * d3_radians : 0;
      return reset();
    };
    d3.rebind(projection, projectResample, "precision");
    function reset() {
      projectRotate = d3_geo_compose(rotate = d3_geo_rotation(δλ, δφ, δγ), project);
      var center = project(λ, φ);
      δx = x - center[0] * k;
      δy = y + center[1] * k;
      return invalidate();
    }
    function invalidate() {
      if (stream) stream.valid = false, stream = null;
      return projection;
    }
    return function() {
      project = projectAt.apply(this, arguments);
      projection.invert = project.invert && invert;
      return reset();
    };
  }
  function d3_geo_projectionRadians(stream) {
    return d3_geo_transformPoint(stream, function(x, y) {
      stream.point(x * d3_radians, y * d3_radians);
    });
  }
  function d3_geo_equirectangular(λ, φ) {
    return [ λ, φ ];
  }
  (d3.geo.equirectangular = function() {
    return d3_geo_projection(d3_geo_equirectangular);
  }).raw = d3_geo_equirectangular.invert = d3_geo_equirectangular;
  d3.geo.rotation = function(rotate) {
    rotate = d3_geo_rotation(rotate[0] % 360 * d3_radians, rotate[1] * d3_radians, rotate.length > 2 ? rotate[2] * d3_radians : 0);
    function forward(coordinates) {
      coordinates = rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians);
      return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates;
    }
    forward.invert = function(coordinates) {
      coordinates = rotate.invert(coordinates[0] * d3_radians, coordinates[1] * d3_radians);
      return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates;
    };
    return forward;
  };
  function d3_geo_identityRotation(λ, φ) {
    return [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ];
  }
  d3_geo_identityRotation.invert = d3_geo_equirectangular;
  function d3_geo_rotation(δλ, δφ, δγ) {
    return δλ ? δφ || δγ ? d3_geo_compose(d3_geo_rotationλ(δλ), d3_geo_rotationφγ(δφ, δγ)) : d3_geo_rotationλ(δλ) : δφ || δγ ? d3_geo_rotationφγ(δφ, δγ) : d3_geo_identityRotation;
  }
  function d3_geo_forwardRotationλ(δλ) {
    return function(λ, φ) {
      return λ += δλ, [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ];
    };
  }
  function d3_geo_rotationλ(δλ) {
    var rotation = d3_geo_forwardRotationλ(δλ);
    rotation.invert = d3_geo_forwardRotationλ(-δλ);
    return rotation;
  }
  function d3_geo_rotationφγ(δφ, δγ) {
    var cosδφ = Math.cos(δφ), sinδφ = Math.sin(δφ), cosδγ = Math.cos(δγ), sinδγ = Math.sin(δγ);
    function rotation(λ, φ) {
      var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδφ + x * sinδφ;
      return [ Math.atan2(y * cosδγ - k * sinδγ, x * cosδφ - z * sinδφ), d3_asin(k * cosδγ + y * sinδγ) ];
    }
    rotation.invert = function(λ, φ) {
      var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδγ - y * sinδγ;
      return [ Math.atan2(y * cosδγ + z * sinδγ, x * cosδφ + k * sinδφ), d3_asin(k * cosδφ - x * sinδφ) ];
    };
    return rotation;
  }
  d3.geo.circle = function() {
    var origin = [ 0, 0 ], angle, precision = 6, interpolate;
    function circle() {
      var center = typeof origin === "function" ? origin.apply(this, arguments) : origin, rotate = d3_geo_rotation(-center[0] * d3_radians, -center[1] * d3_radians, 0).invert, ring = [];
      interpolate(null, null, 1, {
        point: function(x, y) {
          ring.push(x = rotate(x, y));
          x[0] *= d3_degrees, x[1] *= d3_degrees;
        }
      });
      return {
        type: "Polygon",
        coordinates: [ ring ]
      };
    }
    circle.origin = function(x) {
      if (!arguments.length) return origin;
      origin = x;
      return circle;
    };
    circle.angle = function(x) {
      if (!arguments.length) return angle;
      interpolate = d3_geo_circleInterpolate((angle = +x) * d3_radians, precision * d3_radians);
      return circle;
    };
    circle.precision = function(_) {
      if (!arguments.length) return precision;
      interpolate = d3_geo_circleInterpolate(angle * d3_radians, (precision = +_) * d3_radians);
      return circle;
    };
    return circle.angle(90);
  };
  function d3_geo_circleInterpolate(radius, precision) {
    var cr = Math.cos(radius), sr = Math.sin(radius);
    return function(from, to, direction, listener) {
      var step = direction * precision;
      if (from != null) {
        from = d3_geo_circleAngle(cr, from);
        to = d3_geo_circleAngle(cr, to);
        if (direction > 0 ? from < to : from > to) from += direction * τ;
      } else {
        from = radius + direction * τ;
        to = radius - .5 * step;
      }
      for (var point, t = from; direction > 0 ? t > to : t < to; t -= step) {
        listener.point((point = d3_geo_spherical([ cr, -sr * Math.cos(t), -sr * Math.sin(t) ]))[0], point[1]);
      }
    };
  }
  function d3_geo_circleAngle(cr, point) {
    var a = d3_geo_cartesian(point);
    a[0] -= cr;
    d3_geo_cartesianNormalize(a);
    var angle = d3_acos(-a[1]);
    return ((-a[2] < 0 ? -angle : angle) + 2 * Math.PI - ε) % (2 * Math.PI);
  }
  d3.geo.distance = function(a, b) {
    var Δλ = (b[0] - a[0]) * d3_radians, φ0 = a[1] * d3_radians, φ1 = b[1] * d3_radians, sinΔλ = Math.sin(Δλ), cosΔλ = Math.cos(Δλ), sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), sinφ1 = Math.sin(φ1), cosφ1 = Math.cos(φ1), t;
    return Math.atan2(Math.sqrt((t = cosφ1 * sinΔλ) * t + (t = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * t), sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ);
  };
  d3.geo.graticule = function() {
    var x1, x0, X1, X0, y1, y0, Y1, Y0, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5;
    function graticule() {
      return {
        type: "MultiLineString",
        coordinates: lines()
      };
    }
    function lines() {
      return d3.range(Math.ceil(X0 / DX) * DX, X1, DX).map(X).concat(d3.range(Math.ceil(Y0 / DY) * DY, Y1, DY).map(Y)).concat(d3.range(Math.ceil(x0 / dx) * dx, x1, dx).filter(function(x) {
        return abs(x % DX) > ε;
      }).map(x)).concat(d3.range(Math.ceil(y0 / dy) * dy, y1, dy).filter(function(y) {
        return abs(y % DY) > ε;
      }).map(y));
    }
    graticule.lines = function() {
      return lines().map(function(coordinates) {
        return {
          type: "LineString",
          coordinates: coordinates
        };
      });
    };
    graticule.outline = function() {
      return {
        type: "Polygon",
        coordinates: [ X(X0).concat(Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1)) ]
      };
    };
    graticule.extent = function(_) {
      if (!arguments.length) return graticule.minorExtent();
      return graticule.majorExtent(_).minorExtent(_);
    };
    graticule.majorExtent = function(_) {
      if (!arguments.length) return [ [ X0, Y0 ], [ X1, Y1 ] ];
      X0 = +_[0][0], X1 = +_[1][0];
      Y0 = +_[0][1], Y1 = +_[1][1];
      if (X0 > X1) _ = X0, X0 = X1, X1 = _;
      if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _;
      return graticule.precision(precision);
    };
    graticule.minorExtent = function(_) {
      if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ];
      x0 = +_[0][0], x1 = +_[1][0];
      y0 = +_[0][1], y1 = +_[1][1];
      if (x0 > x1) _ = x0, x0 = x1, x1 = _;
      if (y0 > y1) _ = y0, y0 = y1, y1 = _;
      return graticule.precision(precision);
    };
    graticule.step = function(_) {
      if (!arguments.length) return graticule.minorStep();
      return graticule.majorStep(_).minorStep(_);
    };
    graticule.majorStep = function(_) {
      if (!arguments.length) return [ DX, DY ];
      DX = +_[0], DY = +_[1];
      return graticule;
    };
    graticule.minorStep = function(_) {
      if (!arguments.length) return [ dx, dy ];
      dx = +_[0], dy = +_[1];
      return graticule;
    };
    graticule.precision = function(_) {
      if (!arguments.length) return precision;
      precision = +_;
      x = d3_geo_graticuleX(y0, y1, 90);
      y = d3_geo_graticuleY(x0, x1, precision);
      X = d3_geo_graticuleX(Y0, Y1, 90);
      Y = d3_geo_graticuleY(X0, X1, precision);
      return graticule;
    };
    return graticule.majorExtent([ [ -180, -90 + ε ], [ 180, 90 - ε ] ]).minorExtent([ [ -180, -80 - ε ], [ 180, 80 + ε ] ]);
  };
  function d3_geo_graticuleX(y0, y1, dy) {
    var y = d3.range(y0, y1 - ε, dy).concat(y1);
    return function(x) {
      return y.map(function(y) {
        return [ x, y ];
      });
    };
  }
  function d3_geo_graticuleY(x0, x1, dx) {
    var x = d3.range(x0, x1 - ε, dx).concat(x1);
    return function(y) {
      return x.map(function(x) {
        return [ x, y ];
      });
    };
  }
  function d3_source(d) {
    return d.source;
  }
  function d3_target(d) {
    return d.target;
  }
  d3.geo.greatArc = function() {
    var source = d3_source, source_, target = d3_target, target_;
    function greatArc() {
      return {
        type: "LineString",
        coordinates: [ source_ || source.apply(this, arguments), target_ || target.apply(this, arguments) ]
      };
    }
    greatArc.distance = function() {
      return d3.geo.distance(source_ || source.apply(this, arguments), target_ || target.apply(this, arguments));
    };
    greatArc.source = function(_) {
      if (!arguments.length) return source;
      source = _, source_ = typeof _ === "function" ? null : _;
      return greatArc;
    };
    greatArc.target = function(_) {
      if (!arguments.length) return target;
      target = _, target_ = typeof _ === "function" ? null : _;
      return greatArc;
    };
    greatArc.precision = function() {
      return arguments.length ? greatArc : 0;
    };
    return greatArc;
  };
  d3.geo.interpolate = function(source, target) {
    return d3_geo_interpolate(source[0] * d3_radians, source[1] * d3_radians, target[0] * d3_radians, target[1] * d3_radians);
  };
  function d3_geo_interpolate(x0, y0, x1, y1) {
    var cy0 = Math.cos(y0), sy0 = Math.sin(y0), cy1 = Math.cos(y1), sy1 = Math.sin(y1), kx0 = cy0 * Math.cos(x0), ky0 = cy0 * Math.sin(x0), kx1 = cy1 * Math.cos(x1), ky1 = cy1 * Math.sin(x1), d = 2 * Math.asin(Math.sqrt(d3_haversin(y1 - y0) + cy0 * cy1 * d3_haversin(x1 - x0))), k = 1 / Math.sin(d);
    var interpolate = d ? function(t) {
      var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1;
      return [ Math.atan2(y, x) * d3_degrees, Math.atan2(z, Math.sqrt(x * x + y * y)) * d3_degrees ];
    } : function() {
      return [ x0 * d3_degrees, y0 * d3_degrees ];
    };
    interpolate.distance = d;
    return interpolate;
  }
  d3.geo.length = function(object) {
    d3_geo_lengthSum = 0;
    d3.geo.stream(object, d3_geo_length);
    return d3_geo_lengthSum;
  };
  var d3_geo_lengthSum;
  var d3_geo_length = {
    sphere: d3_noop,
    point: d3_noop,
    lineStart: d3_geo_lengthLineStart,
    lineEnd: d3_noop,
    polygonStart: d3_noop,
    polygonEnd: d3_noop
  };
  function d3_geo_lengthLineStart() {
    var λ0, sinφ0, cosφ0;
    d3_geo_length.point = function(λ, φ) {
      λ0 = λ * d3_radians, sinφ0 = Math.sin(φ *= d3_radians), cosφ0 = Math.cos(φ);
      d3_geo_length.point = nextPoint;
    };
    d3_geo_length.lineEnd = function() {
      d3_geo_length.point = d3_geo_length.lineEnd = d3_noop;
    };
    function nextPoint(λ, φ) {
      var sinφ = Math.sin(φ *= d3_radians), cosφ = Math.cos(φ), t = abs((λ *= d3_radians) - λ0), cosΔλ = Math.cos(t);
      d3_geo_lengthSum += Math.atan2(Math.sqrt((t = cosφ * Math.sin(t)) * t + (t = cosφ0 * sinφ - sinφ0 * cosφ * cosΔλ) * t), sinφ0 * sinφ + cosφ0 * cosφ * cosΔλ);
      λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ;
    }
  }
  function d3_geo_azimuthal(scale, angle) {
    function azimuthal(λ, φ) {
      var cosλ = Math.cos(λ), cosφ = Math.cos(φ), k = scale(cosλ * cosφ);
      return [ k * cosφ * Math.sin(λ), k * Math.sin(φ) ];
    }
    azimuthal.invert = function(x, y) {
      var ρ = Math.sqrt(x * x + y * y), c = angle(ρ), sinc = Math.sin(c), cosc = Math.cos(c);
      return [ Math.atan2(x * sinc, ρ * cosc), Math.asin(ρ && y * sinc / ρ) ];
    };
    return azimuthal;
  }
  var d3_geo_azimuthalEqualArea = d3_geo_azimuthal(function(cosλcosφ) {
    return Math.sqrt(2 / (1 + cosλcosφ));
  }, function(ρ) {
    return 2 * Math.asin(ρ / 2);
  });
  (d3.geo.azimuthalEqualArea = function() {
    return d3_geo_projection(d3_geo_azimuthalEqualArea);
  }).raw = d3_geo_azimuthalEqualArea;
  var d3_geo_azimuthalEquidistant = d3_geo_azimuthal(function(cosλcosφ) {
    var c = Math.acos(cosλcosφ);
    return c && c / Math.sin(c);
  }, d3_identity);
  (d3.geo.azimuthalEquidistant = function() {
    return d3_geo_projection(d3_geo_azimuthalEquidistant);
  }).raw = d3_geo_azimuthalEquidistant;
  function d3_geo_conicConformal(φ0, φ1) {
    var cosφ0 = Math.cos(φ0), t = function(φ) {
      return Math.tan(π / 4 + φ / 2);
    }, n = φ0 === φ1 ? Math.sin(φ0) : Math.log(cosφ0 / Math.cos(φ1)) / Math.log(t(φ1) / t(φ0)), F = cosφ0 * Math.pow(t(φ0), n) / n;
    if (!n) return d3_geo_mercator;
    function forward(λ, φ) {
      if (F > 0) {
        if (φ < -halfπ + ε) φ = -halfπ + ε;
      } else {
        if (φ > halfπ - ε) φ = halfπ - ε;
      }
      var ρ = F / Math.pow(t(φ), n);
      return [ ρ * Math.sin(n * λ), F - ρ * Math.cos(n * λ) ];
    }
    forward.invert = function(x, y) {
      var ρ0_y = F - y, ρ = d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y);
      return [ Math.atan2(x, ρ0_y) / n, 2 * Math.atan(Math.pow(F / ρ, 1 / n)) - halfπ ];
    };
    return forward;
  }
  (d3.geo.conicConformal = function() {
    return d3_geo_conic(d3_geo_conicConformal);
  }).raw = d3_geo_conicConformal;
  function d3_geo_conicEquidistant(φ0, φ1) {
    var cosφ0 = Math.cos(φ0), n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0), G = cosφ0 / n + φ0;
    if (abs(n) < ε) return d3_geo_equirectangular;
    function forward(λ, φ) {
      var ρ = G - φ;
      return [ ρ * Math.sin(n * λ), G - ρ * Math.cos(n * λ) ];
    }
    forward.invert = function(x, y) {
      var ρ0_y = G - y;
      return [ Math.atan2(x, ρ0_y) / n, G - d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y) ];
    };
    return forward;
  }
  (d3.geo.conicEquidistant = function() {
    return d3_geo_conic(d3_geo_conicEquidistant);
  }).raw = d3_geo_conicEquidistant;
  var d3_geo_gnomonic = d3_geo_azimuthal(function(cosλcosφ) {
    return 1 / cosλcosφ;
  }, Math.atan);
  (d3.geo.gnomonic = function() {
    return d3_geo_projection(d3_geo_gnomonic);
  }).raw = d3_geo_gnomonic;
  function d3_geo_mercator(λ, φ) {
    return [ λ, Math.log(Math.tan(π / 4 + φ / 2)) ];
  }
  d3_geo_mercator.invert = function(x, y) {
    return [ x, 2 * Math.atan(Math.exp(y)) - halfπ ];
  };
  function d3_geo_mercatorProjection(project) {
    var m = d3_geo_projection(project), scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, clipAuto;
    m.scale = function() {
      var v = scale.apply(m, arguments);
      return v === m ? clipAuto ? m.clipExtent(null) : m : v;
    };
    m.translate = function() {
      var v = translate.apply(m, arguments);
      return v === m ? clipAuto ? m.clipExtent(null) : m : v;
    };
    m.clipExtent = function(_) {
      var v = clipExtent.apply(m, arguments);
      if (v === m) {
        if (clipAuto = _ == null) {
          var k = π * scale(), t = translate();
          clipExtent([ [ t[0] - k, t[1] - k ], [ t[0] + k, t[1] + k ] ]);
        }
      } else if (clipAuto) {
        v = null;
      }
      return v;
    };
    return m.clipExtent(null);
  }
  (d3.geo.mercator = function() {
    return d3_geo_mercatorProjection(d3_geo_mercator);
  }).raw = d3_geo_mercator;
  var d3_geo_orthographic = d3_geo_azimuthal(function() {
    return 1;
  }, Math.asin);
  (d3.geo.orthographic = function() {
    return d3_geo_projection(d3_geo_orthographic);
  }).raw = d3_geo_orthographic;
  var d3_geo_stereographic = d3_geo_azimuthal(function(cosλcosφ) {
    return 1 / (1 + cosλcosφ);
  }, function(ρ) {
    return 2 * Math.atan(ρ);
  });
  (d3.geo.stereographic = function() {
    return d3_geo_projection(d3_geo_stereographic);
  }).raw = d3_geo_stereographic;
  function d3_geo_transverseMercator(λ, φ) {
    return [ Math.log(Math.tan(π / 4 + φ / 2)), -λ ];
  }
  d3_geo_transverseMercator.invert = function(x, y) {
    return [ -y, 2 * Math.atan(Math.exp(x)) - halfπ ];
  };
  (d3.geo.transverseMercator = function() {
    var projection = d3_geo_mercatorProjection(d3_geo_transverseMercator), center = projection.center, rotate = projection.rotate;
    projection.center = function(_) {
      return _ ? center([ -_[1], _[0] ]) : (_ = center(), [ _[1], -_[0] ]);
    };
    projection.rotate = function(_) {
      return _ ? rotate([ _[0], _[1], _.length > 2 ? _[2] + 90 : 90 ]) : (_ = rotate(), 
      [ _[0], _[1], _[2] - 90 ]);
    };
    return rotate([ 0, 0, 90 ]);
  }).raw = d3_geo_transverseMercator;
  d3.geom = {};
  function d3_geom_pointX(d) {
    return d[0];
  }
  function d3_geom_pointY(d) {
    return d[1];
  }
  d3.geom.hull = function(vertices) {
    var x = d3_geom_pointX, y = d3_geom_pointY;
    if (arguments.length) return hull(vertices);
    function hull(data) {
      if (data.length < 3) return [];
      var fx = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = [];
      for (i = 0; i < n; i++) {
        points.push([ +fx.call(this, data[i], i), +fy.call(this, data[i], i), i ]);
      }
      points.sort(d3_geom_hullOrder);
      for (i = 0; i < n; i++) flippedPoints.push([ points[i][0], -points[i][1] ]);
      var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints);
      var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon = [];
      for (i = upper.length - 1; i >= 0; --i) polygon.push(data[points[upper[i]][2]]);
      for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon.push(data[points[lower[i]][2]]);
      return polygon;
    }
    hull.x = function(_) {
      return arguments.length ? (x = _, hull) : x;
    };
    hull.y = function(_) {
      return arguments.length ? (y = _, hull) : y;
    };
    return hull;
  };
  function d3_geom_hullUpper(points) {
    var n = points.length, hull = [ 0, 1 ], hs = 2;
    for (var i = 2; i < n; i++) {
      while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs;
      hull[hs++] = i;
    }
    return hull.slice(0, hs);
  }
  function d3_geom_hullOrder(a, b) {
    return a[0] - b[0] || a[1] - b[1];
  }
  d3.geom.polygon = function(coordinates) {
    d3_subclass(coordinates, d3_geom_polygonPrototype);
    return coordinates;
  };
  var d3_geom_polygonPrototype = d3.geom.polygon.prototype = [];
  d3_geom_polygonPrototype.area = function() {
    var i = -1, n = this.length, a, b = this[n - 1], area = 0;
    while (++i < n) {
      a = b;
      b = this[i];
      area += a[1] * b[0] - a[0] * b[1];
    }
    return area * .5;
  };
  d3_geom_polygonPrototype.centroid = function(k) {
    var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c;
    if (!arguments.length) k = -1 / (6 * this.area());
    while (++i < n) {
      a = b;
      b = this[i];
      c = a[0] * b[1] - b[0] * a[1];
      x += (a[0] + b[0]) * c;
      y += (a[1] + b[1]) * c;
    }
    return [ x * k, y * k ];
  };
  d3_geom_polygonPrototype.clip = function(subject) {
    var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d;
    while (++i < n) {
      input = subject.slice();
      subject.length = 0;
      b = this[i];
      c = input[(m = input.length - closed) - 1];
      j = -1;
      while (++j < m) {
        d = input[j];
        if (d3_geom_polygonInside(d, a, b)) {
          if (!d3_geom_polygonInside(c, a, b)) {
            subject.push(d3_geom_polygonIntersect(c, d, a, b));
          }
          subject.push(d);
        } else if (d3_geom_polygonInside(c, a, b)) {
          subject.push(d3_geom_polygonIntersect(c, d, a, b));
        }
        c = d;
      }
      if (closed) subject.push(subject[0]);
      a = b;
    }
    return subject;
  };
  function d3_geom_polygonInside(p, a, b) {
    return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]);
  }
  function d3_geom_polygonIntersect(c, d, a, b) {
    var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21);
    return [ x1 + ua * x21, y1 + ua * y21 ];
  }
  function d3_geom_polygonClosed(coordinates) {
    var a = coordinates[0], b = coordinates[coordinates.length - 1];
    return !(a[0] - b[0] || a[1] - b[1]);
  }
  var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = [];
  function d3_geom_voronoiBeach() {
    d3_geom_voronoiRedBlackNode(this);
    this.edge = this.site = this.circle = null;
  }
  function d3_geom_voronoiCreateBeach(site) {
    var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach();
    beach.site = site;
    return beach;
  }
  function d3_geom_voronoiDetachBeach(beach) {
    d3_geom_voronoiDetachCircle(beach);
    d3_geom_voronoiBeaches.remove(beach);
    d3_geom_voronoiBeachPool.push(beach);
    d3_geom_voronoiRedBlackNode(beach);
  }
  function d3_geom_voronoiRemoveBeach(beach) {
    var circle = beach.circle, x = circle.x, y = circle.cy, vertex = {
      x: x,
      y: y
    }, previous = beach.P, next = beach.N, disappearing = [ beach ];
    d3_geom_voronoiDetachBeach(beach);
    var lArc = previous;
    while (lArc.circle && abs(x - lArc.circle.x) < ε && abs(y - lArc.circle.cy) < ε) {
      previous = lArc.P;
      disappearing.unshift(lArc);
      d3_geom_voronoiDetachBeach(lArc);
      lArc = previous;
    }
    disappearing.unshift(lArc);
    d3_geom_voronoiDetachCircle(lArc);
    var rArc = next;
    while (rArc.circle && abs(x - rArc.circle.x) < ε && abs(y - rArc.circle.cy) < ε) {
      next = rArc.N;
      disappearing.push(rArc);
      d3_geom_voronoiDetachBeach(rArc);
      rArc = next;
    }
    disappearing.push(rArc);
    d3_geom_voronoiDetachCircle(rArc);
    var nArcs = disappearing.length, iArc;
    for (iArc = 1; iArc < nArcs; ++iArc) {
      rArc = disappearing[iArc];
      lArc = disappearing[iArc - 1];
      d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex);
    }
    lArc = disappearing[0];
    rArc = disappearing[nArcs - 1];
    rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex);
    d3_geom_voronoiAttachCircle(lArc);
    d3_geom_voronoiAttachCircle(rArc);
  }
  function d3_geom_voronoiAddBeach(site) {
    var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._;
    while (node) {
      dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x;
      if (dxl > ε) node = node.L; else {
        dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix);
        if (dxr > ε) {
          if (!node.R) {
            lArc = node;
            break;
          }
          node = node.R;
        } else {
          if (dxl > -ε) {
            lArc = node.P;
            rArc = node;
          } else if (dxr > -ε) {
            lArc = node;
            rArc = node.N;
          } else {
            lArc = rArc = node;
          }
          break;
        }
      }
    }
    var newArc = d3_geom_voronoiCreateBeach(site);
    d3_geom_voronoiBeaches.insert(lArc, newArc);
    if (!lArc && !rArc) return;
    if (lArc === rArc) {
      d3_geom_voronoiDetachCircle(lArc);
      rArc = d3_geom_voronoiCreateBeach(lArc.site);
      d3_geom_voronoiBeaches.insert(newArc, rArc);
      newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site);
      d3_geom_voronoiAttachCircle(lArc);
      d3_geom_voronoiAttachCircle(rArc);
      return;
    }
    if (!rArc) {
      newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site);
      return;
    }
    d3_geom_voronoiDetachCircle(lArc);
    d3_geom_voronoiDetachCircle(rArc);
    var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = {
      x: (cy * hb - by * hc) / d + ax,
      y: (bx * hc - cx * hb) / d + ay
    };
    d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex);
    newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex);
    rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex);
    d3_geom_voronoiAttachCircle(lArc);
    d3_geom_voronoiAttachCircle(rArc);
  }
  function d3_geom_voronoiLeftBreakPoint(arc, directrix) {
    var site = arc.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix;
    if (!pby2) return rfocx;
    var lArc = arc.P;
    if (!lArc) return -Infinity;
    site = lArc.site;
    var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix;
    if (!plby2) return lfocx;
    var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2;
    if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx;
    return (rfocx + lfocx) / 2;
  }
  function d3_geom_voronoiRightBreakPoint(arc, directrix) {
    var rArc = arc.N;
    if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix);
    var site = arc.site;
    return site.y === directrix ? site.x : Infinity;
  }
  function d3_geom_voronoiCell(site) {
    this.site = site;
    this.edges = [];
  }
  d3_geom_voronoiCell.prototype.prepare = function() {
    var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge;
    while (iHalfEdge--) {
      edge = halfEdges[iHalfEdge].edge;
      if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1);
    }
    halfEdges.sort(d3_geom_voronoiHalfEdgeOrder);
    return halfEdges.length;
  };
  function d3_geom_voronoiCloseCells(extent) {
    var x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end;
    while (iCell--) {
      cell = cells[iCell];
      if (!cell || !cell.prepare()) continue;
      halfEdges = cell.edges;
      nHalfEdges = halfEdges.length;
      iHalfEdge = 0;
      while (iHalfEdge < nHalfEdges) {
        end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y;
        start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y;
        if (abs(x3 - x2) > ε || abs(y3 - y2) > ε) {
          halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < ε && y1 - y3 > ε ? {
            x: x0,
            y: abs(x2 - x0) < ε ? y2 : y1
          } : abs(y3 - y1) < ε && x1 - x3 > ε ? {
            x: abs(y2 - y1) < ε ? x2 : x1,
            y: y1
          } : abs(x3 - x1) < ε && y3 - y0 > ε ? {
            x: x1,
            y: abs(x2 - x1) < ε ? y2 : y0
          } : abs(y3 - y0) < ε && x3 - x0 > ε ? {
            x: abs(y2 - y0) < ε ? x2 : x0,
            y: y0
          } : null), cell.site, null));
          ++nHalfEdges;
        }
      }
    }
  }
  function d3_geom_voronoiHalfEdgeOrder(a, b) {
    return b.angle - a.angle;
  }
  function d3_geom_voronoiCircle() {
    d3_geom_voronoiRedBlackNode(this);
    this.x = this.y = this.arc = this.site = this.cy = null;
  }
  function d3_geom_voronoiAttachCircle(arc) {
    var lArc = arc.P, rArc = arc.N;
    if (!lArc || !rArc) return;
    var lSite = lArc.site, cSite = arc.site, rSite = rArc.site;
    if (lSite === rSite) return;
    var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by;
    var d = 2 * (ax * cy - ay * cx);
    if (d >= -ε2) return;
    var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by;
    var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle();
    circle.arc = arc;
    circle.site = cSite;
    circle.x = x + bx;
    circle.y = cy + Math.sqrt(x * x + y * y);
    circle.cy = cy;
    arc.circle = circle;
    var before = null, node = d3_geom_voronoiCircles._;
    while (node) {
      if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) {
        if (node.L) node = node.L; else {
          before = node.P;
          break;
        }
      } else {
        if (node.R) node = node.R; else {
          before = node;
          break;
        }
      }
    }
    d3_geom_voronoiCircles.insert(before, circle);
    if (!before) d3_geom_voronoiFirstCircle = circle;
  }
  function d3_geom_voronoiDetachCircle(arc) {
    var circle = arc.circle;
    if (circle) {
      if (!circle.P) d3_geom_voronoiFirstCircle = circle.N;
      d3_geom_voronoiCircles.remove(circle);
      d3_geom_voronoiCirclePool.push(circle);
      d3_geom_voronoiRedBlackNode(circle);
      arc.circle = null;
    }
  }
  function d3_geom_voronoiClipEdges(extent) {
    var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e;
    while (i--) {
      e = edges[i];
      if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < ε && abs(e.a.y - e.b.y) < ε) {
        e.a = e.b = null;
        edges.splice(i, 1);
      }
    }
  }
  function d3_geom_voronoiConnectEdge(edge, extent) {
    var vb = edge.b;
    if (vb) return true;
    var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb;
    if (ry === ly) {
      if (fx < x0 || fx >= x1) return;
      if (lx > rx) {
        if (!va) va = {
          x: fx,
          y: y0
        }; else if (va.y >= y1) return;
        vb = {
          x: fx,
          y: y1
        };
      } else {
        if (!va) va = {
          x: fx,
          y: y1
        }; else if (va.y < y0) return;
        vb = {
          x: fx,
          y: y0
        };
      }
    } else {
      fm = (lx - rx) / (ry - ly);
      fb = fy - fm * fx;
      if (fm < -1 || fm > 1) {
        if (lx > rx) {
          if (!va) va = {
            x: (y0 - fb) / fm,
            y: y0
          }; else if (va.y >= y1) return;
          vb = {
            x: (y1 - fb) / fm,
            y: y1
          };
        } else {
          if (!va) va = {
            x: (y1 - fb) / fm,
            y: y1
          }; else if (va.y < y0) return;
          vb = {
            x: (y0 - fb) / fm,
            y: y0
          };
        }
      } else {
        if (ly < ry) {
          if (!va) va = {
            x: x0,
            y: fm * x0 + fb
          }; else if (va.x >= x1) return;
          vb = {
            x: x1,
            y: fm * x1 + fb
          };
        } else {
          if (!va) va = {
            x: x1,
            y: fm * x1 + fb
          }; else if (va.x < x0) return;
          vb = {
            x: x0,
            y: fm * x0 + fb
          };
        }
      }
    }
    edge.a = va;
    edge.b = vb;
    return true;
  }
  function d3_geom_voronoiEdge(lSite, rSite) {
    this.l = lSite;
    this.r = rSite;
    this.a = this.b = null;
  }
  function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) {
    var edge = new d3_geom_voronoiEdge(lSite, rSite);
    d3_geom_voronoiEdges.push(edge);
    if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va);
    if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb);
    d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite));
    d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite));
    return edge;
  }
  function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) {
    var edge = new d3_geom_voronoiEdge(lSite, null);
    edge.a = va;
    edge.b = vb;
    d3_geom_voronoiEdges.push(edge);
    return edge;
  }
  function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) {
    if (!edge.a && !edge.b) {
      edge.a = vertex;
      edge.l = lSite;
      edge.r = rSite;
    } else if (edge.l === rSite) {
      edge.b = vertex;
    } else {
      edge.a = vertex;
    }
  }
  function d3_geom_voronoiHalfEdge(edge, lSite, rSite) {
    var va = edge.a, vb = edge.b;
    this.edge = edge;
    this.site = lSite;
    this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y);
  }
  d3_geom_voronoiHalfEdge.prototype = {
    start: function() {
      return this.edge.l === this.site ? this.edge.a : this.edge.b;
    },
    end: function() {
      return this.edge.l === this.site ? this.edge.b : this.edge.a;
    }
  };
  function d3_geom_voronoiRedBlackTree() {
    this._ = null;
  }
  function d3_geom_voronoiRedBlackNode(node) {
    node.U = node.C = node.L = node.R = node.P = node.N = null;
  }
  d3_geom_voronoiRedBlackTree.prototype = {
    insert: function(after, node) {
      var parent, grandpa, uncle;
      if (after) {
        node.P = after;
        node.N = after.N;
        if (after.N) after.N.P = node;
        after.N = node;
        if (after.R) {
          after = after.R;
          while (after.L) after = after.L;
          after.L = node;
        } else {
          after.R = node;
        }
        parent = after;
      } else if (this._) {
        after = d3_geom_voronoiRedBlackFirst(this._);
        node.P = null;
        node.N = after;
        after.P = after.L = node;
        parent = after;
      } else {
        node.P = node.N = null;
        this._ = node;
        parent = null;
      }
      node.L = node.R = null;
      node.U = parent;
      node.C = true;
      after = node;
      while (parent && parent.C) {
        grandpa = parent.U;
        if (parent === grandpa.L) {
          uncle = grandpa.R;
          if (uncle && uncle.C) {
            parent.C = uncle.C = false;
            grandpa.C = true;
            after = grandpa;
          } else {
            if (after === parent.R) {
              d3_geom_voronoiRedBlackRotateLeft(this, parent);
              after = parent;
              parent = after.U;
            }
            parent.C = false;
            grandpa.C = true;
            d3_geom_voronoiRedBlackRotateRight(this, grandpa);
          }
        } else {
          uncle = grandpa.L;
          if (uncle && uncle.C) {
            parent.C = uncle.C = false;
            grandpa.C = true;
            after = grandpa;
          } else {
            if (after === parent.L) {
              d3_geom_voronoiRedBlackRotateRight(this, parent);
              after = parent;
              parent = after.U;
            }
            parent.C = false;
            grandpa.C = true;
            d3_geom_voronoiRedBlackRotateLeft(this, grandpa);
          }
        }
        parent = after.U;
      }
      this._.C = false;
    },
    remove: function(node) {
      if (node.N) node.N.P = node.P;
      if (node.P) node.P.N = node.N;
      node.N = node.P = null;
      var parent = node.U, sibling, left = node.L, right = node.R, next, red;
      if (!left) next = right; else if (!right) next = left; else next = d3_geom_voronoiRedBlackFirst(right);
      if (parent) {
        if (parent.L === node) parent.L = next; else parent.R = next;
      } else {
        this._ = next;
      }
      if (left && right) {
        red = next.C;
        next.C = node.C;
        next.L = left;
        left.U = next;
        if (next !== right) {
          parent = next.U;
          next.U = node.U;
          node = next.R;
          parent.L = node;
          next.R = right;
          right.U = next;
        } else {
          next.U = parent;
          parent = next;
          node = next.R;
        }
      } else {
        red = node.C;
        node = next;
      }
      if (node) node.U = parent;
      if (red) return;
      if (node && node.C) {
        node.C = false;
        return;
      }
      do {
        if (node === this._) break;
        if (node === parent.L) {
          sibling = parent.R;
          if (sibling.C) {
            sibling.C = false;
            parent.C = true;
            d3_geom_voronoiRedBlackRotateLeft(this, parent);
            sibling = parent.R;
          }
          if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) {
            if (!sibling.R || !sibling.R.C) {
              sibling.L.C = false;
              sibling.C = true;
              d3_geom_voronoiRedBlackRotateRight(this, sibling);
              sibling = parent.R;
            }
            sibling.C = parent.C;
            parent.C = sibling.R.C = false;
            d3_geom_voronoiRedBlackRotateLeft(this, parent);
            node = this._;
            break;
          }
        } else {
          sibling = parent.L;
          if (sibling.C) {
            sibling.C = false;
            parent.C = true;
            d3_geom_voronoiRedBlackRotateRight(this, parent);
            sibling = parent.L;
          }
          if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) {
            if (!sibling.L || !sibling.L.C) {
              sibling.R.C = false;
              sibling.C = true;
              d3_geom_voronoiRedBlackRotateLeft(this, sibling);
              sibling = parent.L;
            }
            sibling.C = parent.C;
            parent.C = sibling.L.C = false;
            d3_geom_voronoiRedBlackRotateRight(this, parent);
            node = this._;
            break;
          }
        }
        sibling.C = true;
        node = parent;
        parent = parent.U;
      } while (!node.C);
      if (node) node.C = false;
    }
  };
  function d3_geom_voronoiRedBlackRotateLeft(tree, node) {
    var p = node, q = node.R, parent = p.U;
    if (parent) {
      if (parent.L === p) parent.L = q; else parent.R = q;
    } else {
      tree._ = q;
    }
    q.U = parent;
    p.U = q;
    p.R = q.L;
    if (p.R) p.R.U = p;
    q.L = p;
  }
  function d3_geom_voronoiRedBlackRotateRight(tree, node) {
    var p = node, q = node.L, parent = p.U;
    if (parent) {
      if (parent.L === p) parent.L = q; else parent.R = q;
    } else {
      tree._ = q;
    }
    q.U = parent;
    p.U = q;
    p.L = q.R;
    if (p.L) p.L.U = p;
    q.R = p;
  }
  function d3_geom_voronoiRedBlackFirst(node) {
    while (node.L) node = node.L;
    return node;
  }
  function d3_geom_voronoi(sites, bbox) {
    var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle;
    d3_geom_voronoiEdges = [];
    d3_geom_voronoiCells = new Array(sites.length);
    d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree();
    d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree();
    while (true) {
      circle = d3_geom_voronoiFirstCircle;
      if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) {
        if (site.x !== x0 || site.y !== y0) {
          d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site);
          d3_geom_voronoiAddBeach(site);
          x0 = site.x, y0 = site.y;
        }
        site = sites.pop();
      } else if (circle) {
        d3_geom_voronoiRemoveBeach(circle.arc);
      } else {
        break;
      }
    }
    if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox);
    var diagram = {
      cells: d3_geom_voronoiCells,
      edges: d3_geom_voronoiEdges
    };
    d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null;
    return diagram;
  }
  function d3_geom_voronoiVertexOrder(a, b) {
    return b.y - a.y || b.x - a.x;
  }
  d3.geom.voronoi = function(points) {
    var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent;
    if (points) return voronoi(points);
    function voronoi(data) {
      var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1];
      d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) {
        var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) {
          var s = e.start();
          return [ s.x, s.y ];
        }) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [ [ x0, y1 ], [ x1, y1 ], [ x1, y0 ], [ x0, y0 ] ] : [];
        polygon.point = data[i];
      });
      return polygons;
    }
    function sites(data) {
      return data.map(function(d, i) {
        return {
          x: Math.round(fx(d, i) / ε) * ε,
          y: Math.round(fy(d, i) / ε) * ε,
          i: i
        };
      });
    }
    voronoi.links = function(data) {
      return d3_geom_voronoi(sites(data)).edges.filter(function(edge) {
        return edge.l && edge.r;
      }).map(function(edge) {
        return {
          source: data[edge.l.i],
          target: data[edge.r.i]
        };
      });
    };
    voronoi.triangles = function(data) {
      var triangles = [];
      d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) {
        var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l;
        while (++j < m) {
          e0 = e1;
          s0 = s1;
          e1 = edges[j].edge;
          s1 = e1.l === site ? e1.r : e1.l;
          if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) {
            triangles.push([ data[i], data[s0.i], data[s1.i] ]);
          }
        }
      });
      return triangles;
    };
    voronoi.x = function(_) {
      return arguments.length ? (fx = d3_functor(x = _), voronoi) : x;
    };
    voronoi.y = function(_) {
      return arguments.length ? (fy = d3_functor(y = _), voronoi) : y;
    };
    voronoi.clipExtent = function(_) {
      if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent;
      clipExtent = _ == null ? d3_geom_voronoiClipExtent : _;
      return voronoi;
    };
    voronoi.size = function(_) {
      if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1];
      return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]);
    };
    return voronoi;
  };
  var d3_geom_voronoiClipExtent = [ [ -1e6, -1e6 ], [ 1e6, 1e6 ] ];
  function d3_geom_voronoiTriangleArea(a, b, c) {
    return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y);
  }
  d3.geom.delaunay = function(vertices) {
    return d3.geom.voronoi().triangles(vertices);
  };
  d3.geom.quadtree = function(points, x1, y1, x2, y2) {
    var x = d3_geom_pointX, y = d3_geom_pointY, compat;
    if (compat = arguments.length) {
      x = d3_geom_quadtreeCompatX;
      y = d3_geom_quadtreeCompatY;
      if (compat === 3) {
        y2 = y1;
        x2 = x1;
        y1 = x1 = 0;
      }
      return quadtree(points);
    }
    function quadtree(data) {
      var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_;
      if (x1 != null) {
        x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2;
      } else {
        x2_ = y2_ = -(x1_ = y1_ = Infinity);
        xs = [], ys = [];
        n = data.length;
        if (compat) for (i = 0; i < n; ++i) {
          d = data[i];
          if (d.x < x1_) x1_ = d.x;
          if (d.y < y1_) y1_ = d.y;
          if (d.x > x2_) x2_ = d.x;
          if (d.y > y2_) y2_ = d.y;
          xs.push(d.x);
          ys.push(d.y);
        } else for (i = 0; i < n; ++i) {
          var x_ = +fx(d = data[i], i), y_ = +fy(d, i);
          if (x_ < x1_) x1_ = x_;
          if (y_ < y1_) y1_ = y_;
          if (x_ > x2_) x2_ = x_;
          if (y_ > y2_) y2_ = y_;
          xs.push(x_);
          ys.push(y_);
        }
      }
      var dx = x2_ - x1_, dy = y2_ - y1_;
      if (dx > dy) y2_ = y1_ + dx; else x2_ = x1_ + dy;
      function insert(n, d, x, y, x1, y1, x2, y2) {
        if (isNaN(x) || isNaN(y)) return;
        if (n.leaf) {
          var nx = n.x, ny = n.y;
          if (nx != null) {
            if (abs(nx - x) + abs(ny - y) < .01) {
              insertChild(n, d, x, y, x1, y1, x2, y2);
            } else {
              var nPoint = n.point;
              n.x = n.y = n.point = null;
              insertChild(n, nPoint, nx, ny, x1, y1, x2, y2);
              insertChild(n, d, x, y, x1, y1, x2, y2);
            }
          } else {
            n.x = x, n.y = y, n.point = d;
          }
        } else {
          insertChild(n, d, x, y, x1, y1, x2, y2);
        }
      }
      function insertChild(n, d, x, y, x1, y1, x2, y2) {
        var xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym, i = below << 1 | right;
        n.leaf = false;
        n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode());
        if (right) x1 = xm; else x2 = xm;
        if (below) y1 = ym; else y2 = ym;
        insert(n, d, x, y, x1, y1, x2, y2);
      }
      var root = d3_geom_quadtreeNode();
      root.add = function(d) {
        insert(root, d, +fx(d, ++i), +fy(d, i), x1_, y1_, x2_, y2_);
      };
      root.visit = function(f) {
        d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_);
      };
      root.find = function(point) {
        return d3_geom_quadtreeFind(root, point[0], point[1], x1_, y1_, x2_, y2_);
      };
      i = -1;
      if (x1 == null) {
        while (++i < n) {
          insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_);
        }
        --i;
      } else data.forEach(root.add);
      xs = ys = data = d = null;
      return root;
    }
    quadtree.x = function(_) {
      return arguments.length ? (x = _, quadtree) : x;
    };
    quadtree.y = function(_) {
      return arguments.length ? (y = _, quadtree) : y;
    };
    quadtree.extent = function(_) {
      if (!arguments.length) return x1 == null ? null : [ [ x1, y1 ], [ x2, y2 ] ];
      if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0], 
      y2 = +_[1][1];
      return quadtree;
    };
    quadtree.size = function(_) {
      if (!arguments.length) return x1 == null ? null : [ x2 - x1, y2 - y1 ];
      if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = y1 = 0, x2 = +_[0], y2 = +_[1];
      return quadtree;
    };
    return quadtree;
  };
  function d3_geom_quadtreeCompatX(d) {
    return d.x;
  }
  function d3_geom_quadtreeCompatY(d) {
    return d.y;
  }
  function d3_geom_quadtreeNode() {
    return {
      leaf: true,
      nodes: [],
      point: null,
      x: null,
      y: null
    };
  }
  function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) {
    if (!f(node, x1, y1, x2, y2)) {
      var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes;
      if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy);
      if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy);
      if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2);
      if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2);
    }
  }
  function d3_geom_quadtreeFind(root, x, y, x0, y0, x3, y3) {
    var minDistance2 = Infinity, closestPoint;
    (function find(node, x1, y1, x2, y2) {
      if (x1 > x3 || y1 > y3 || x2 < x0 || y2 < y0) return;
      if (point = node.point) {
        var point, dx = x - node.x, dy = y - node.y, distance2 = dx * dx + dy * dy;
        if (distance2 < minDistance2) {
          var distance = Math.sqrt(minDistance2 = distance2);
          x0 = x - distance, y0 = y - distance;
          x3 = x + distance, y3 = y + distance;
          closestPoint = point;
        }
      }
      var children = node.nodes, xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym;
      for (var i = below << 1 | right, j = i + 4; i < j; ++i) {
        if (node = children[i & 3]) switch (i & 3) {
         case 0:
          find(node, x1, y1, xm, ym);
          break;

         case 1:
          find(node, xm, y1, x2, ym);
          break;

         case 2:
          find(node, x1, ym, xm, y2);
          break;

         case 3:
          find(node, xm, ym, x2, y2);
          break;
        }
      }
    })(root, x0, y0, x3, y3);
    return closestPoint;
  }
  d3.interpolateRgb = d3_interpolateRgb;
  function d3_interpolateRgb(a, b) {
    a = d3.rgb(a);
    b = d3.rgb(b);
    var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab;
    return function(t) {
      return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t));
    };
  }
  d3.interpolateObject = d3_interpolateObject;
  function d3_interpolateObject(a, b) {
    var i = {}, c = {}, k;
    for (k in a) {
      if (k in b) {
        i[k] = d3_interpolate(a[k], b[k]);
      } else {
        c[k] = a[k];
      }
    }
    for (k in b) {
      if (!(k in a)) {
        c[k] = b[k];
      }
    }
    return function(t) {
      for (k in i) c[k] = i[k](t);
      return c;
    };
  }
  d3.interpolateNumber = d3_interpolateNumber;
  function d3_interpolateNumber(a, b) {
    a = +a, b = +b;
    return function(t) {
      return a * (1 - t) + b * t;
    };
  }
  d3.interpolateString = d3_interpolateString;
  function d3_interpolateString(a, b) {
    var bi = d3_interpolate_numberA.lastIndex = d3_interpolate_numberB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = [];
    a = a + "", b = b + "";
    while ((am = d3_interpolate_numberA.exec(a)) && (bm = d3_interpolate_numberB.exec(b))) {
      if ((bs = bm.index) > bi) {
        bs = b.slice(bi, bs);
        if (s[i]) s[i] += bs; else s[++i] = bs;
      }
      if ((am = am[0]) === (bm = bm[0])) {
        if (s[i]) s[i] += bm; else s[++i] = bm;
      } else {
        s[++i] = null;
        q.push({
          i: i,
          x: d3_interpolateNumber(am, bm)
        });
      }
      bi = d3_interpolate_numberB.lastIndex;
    }
    if (bi < b.length) {
      bs = b.slice(bi);
      if (s[i]) s[i] += bs; else s[++i] = bs;
    }
    return s.length < 2 ? q[0] ? (b = q[0].x, function(t) {
      return b(t) + "";
    }) : function() {
      return b;
    } : (b = q.length, function(t) {
      for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);
      return s.join("");
    });
  }
  var d3_interpolate_numberA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, d3_interpolate_numberB = new RegExp(d3_interpolate_numberA.source, "g");
  d3.interpolate = d3_interpolate;
  function d3_interpolate(a, b) {
    var i = d3.interpolators.length, f;
    while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ;
    return f;
  }
  d3.interpolators = [ function(a, b) {
    var t = typeof b;
    return (t === "string" ? d3_rgb_names.has(b.toLowerCase()) || /^(#|rgb\(|hsl\()/i.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_color ? d3_interpolateRgb : Array.isArray(b) ? d3_interpolateArray : t === "object" && isNaN(b) ? d3_interpolateObject : d3_interpolateNumber)(a, b);
  } ];
  d3.interpolateArray = d3_interpolateArray;
  function d3_interpolateArray(a, b) {
    var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i;
    for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i]));
    for (;i < na; ++i) c[i] = a[i];
    for (;i < nb; ++i) c[i] = b[i];
    return function(t) {
      for (i = 0; i < n0; ++i) c[i] = x[i](t);
      return c;
    };
  }
  var d3_ease_default = function() {
    return d3_identity;
  };
  var d3_ease = d3.map({
    linear: d3_ease_default,
    poly: d3_ease_poly,
    quad: function() {
      return d3_ease_quad;
    },
    cubic: function() {
      return d3_ease_cubic;
    },
    sin: function() {
      return d3_ease_sin;
    },
    exp: function() {
      return d3_ease_exp;
    },
    circle: function() {
      return d3_ease_circle;
    },
    elastic: d3_ease_elastic,
    back: d3_ease_back,
    bounce: function() {
      return d3_ease_bounce;
    }
  });
  var d3_ease_mode = d3.map({
    "in": d3_identity,
    out: d3_ease_reverse,
    "in-out": d3_ease_reflect,
    "out-in": function(f) {
      return d3_ease_reflect(d3_ease_reverse(f));
    }
  });
  d3.ease = function(name) {
    var i = name.indexOf("-"), t = i >= 0 ? name.slice(0, i) : name, m = i >= 0 ? name.slice(i + 1) : "in";
    t = d3_ease.get(t) || d3_ease_default;
    m = d3_ease_mode.get(m) || d3_identity;
    return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1))));
  };
  function d3_ease_clamp(f) {
    return function(t) {
      return t <= 0 ? 0 : t >= 1 ? 1 : f(t);
    };
  }
  function d3_ease_reverse(f) {
    return function(t) {
      return 1 - f(1 - t);
    };
  }
  function d3_ease_reflect(f) {
    return function(t) {
      return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t));
    };
  }
  function d3_ease_quad(t) {
    return t * t;
  }
  function d3_ease_cubic(t) {
    return t * t * t;
  }
  function d3_ease_cubicInOut(t) {
    if (t <= 0) return 0;
    if (t >= 1) return 1;
    var t2 = t * t, t3 = t2 * t;
    return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75);
  }
  function d3_ease_poly(e) {
    return function(t) {
      return Math.pow(t, e);
    };
  }
  function d3_ease_sin(t) {
    return 1 - Math.cos(t * halfπ);
  }
  function d3_ease_exp(t) {
    return Math.pow(2, 10 * (t - 1));
  }
  function d3_ease_circle(t) {
    return 1 - Math.sqrt(1 - t * t);
  }
  function d3_ease_elastic(a, p) {
    var s;
    if (arguments.length < 2) p = .45;
    if (arguments.length) s = p / τ * Math.asin(1 / a); else a = 1, s = p / 4;
    return function(t) {
      return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * τ / p);
    };
  }
  function d3_ease_back(s) {
    if (!s) s = 1.70158;
    return function(t) {
      return t * t * ((s + 1) * t - s);
    };
  }
  function d3_ease_bounce(t) {
    return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375;
  }
  d3.interpolateHcl = d3_interpolateHcl;
  function d3_interpolateHcl(a, b) {
    a = d3.hcl(a);
    b = d3.hcl(b);
    var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al;
    if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac;
    if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360;
    return function(t) {
      return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + "";
    };
  }
  d3.interpolateHsl = d3_interpolateHsl;
  function d3_interpolateHsl(a, b) {
    a = d3.hsl(a);
    b = d3.hsl(b);
    var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al;
    if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as;
    if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360;
    return function(t) {
      return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + "";
    };
  }
  d3.interpolateLab = d3_interpolateLab;
  function d3_interpolateLab(a, b) {
    a = d3.lab(a);
    b = d3.lab(b);
    var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab;
    return function(t) {
      return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + "";
    };
  }
  d3.interpolateRound = d3_interpolateRound;
  function d3_interpolateRound(a, b) {
    b -= a;
    return function(t) {
      return Math.round(a + b * t);
    };
  }
  d3.transform = function(string) {
    var g = d3_document.createElementNS(d3.ns.prefix.svg, "g");
    return (d3.transform = function(string) {
      if (string != null) {
        g.setAttribute("transform", string);
        var t = g.transform.baseVal.consolidate();
      }
      return new d3_transform(t ? t.matrix : d3_transformIdentity);
    })(string);
  };
  function d3_transform(m) {
    var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0;
    if (r0[0] * r1[1] < r1[0] * r0[1]) {
      r0[0] *= -1;
      r0[1] *= -1;
      kx *= -1;
      kz *= -1;
    }
    this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees;
    this.translate = [ m.e, m.f ];
    this.scale = [ kx, ky ];
    this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0;
  }
  d3_transform.prototype.toString = function() {
    return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")";
  };
  function d3_transformDot(a, b) {
    return a[0] * b[0] + a[1] * b[1];
  }
  function d3_transformNormalize(a) {
    var k = Math.sqrt(d3_transformDot(a, a));
    if (k) {
      a[0] /= k;
      a[1] /= k;
    }
    return k;
  }
  function d3_transformCombine(a, b, k) {
    a[0] += k * b[0];
    a[1] += k * b[1];
    return a;
  }
  var d3_transformIdentity = {
    a: 1,
    b: 0,
    c: 0,
    d: 1,
    e: 0,
    f: 0
  };
  d3.interpolateTransform = d3_interpolateTransform;
  function d3_interpolateTransformPop(s) {
    return s.length ? s.pop() + "," : "";
  }
  function d3_interpolateTranslate(ta, tb, s, q) {
    if (ta[0] !== tb[0] || ta[1] !== tb[1]) {
      var i = s.push("translate(", null, ",", null, ")");
      q.push({
        i: i - 4,
        x: d3_interpolateNumber(ta[0], tb[0])
      }, {
        i: i - 2,
        x: d3_interpolateNumber(ta[1], tb[1])
      });
    } else if (tb[0] || tb[1]) {
      s.push("translate(" + tb + ")");
    }
  }
  function d3_interpolateRotate(ra, rb, s, q) {
    if (ra !== rb) {
      if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360;
      q.push({
        i: s.push(d3_interpolateTransformPop(s) + "rotate(", null, ")") - 2,
        x: d3_interpolateNumber(ra, rb)
      });
    } else if (rb) {
      s.push(d3_interpolateTransformPop(s) + "rotate(" + rb + ")");
    }
  }
  function d3_interpolateSkew(wa, wb, s, q) {
    if (wa !== wb) {
      q.push({
        i: s.push(d3_interpolateTransformPop(s) + "skewX(", null, ")") - 2,
        x: d3_interpolateNumber(wa, wb)
      });
    } else if (wb) {
      s.push(d3_interpolateTransformPop(s) + "skewX(" + wb + ")");
    }
  }
  function d3_interpolateScale(ka, kb, s, q) {
    if (ka[0] !== kb[0] || ka[1] !== kb[1]) {
      var i = s.push(d3_interpolateTransformPop(s) + "scale(", null, ",", null, ")");
      q.push({
        i: i - 4,
        x: d3_interpolateNumber(ka[0], kb[0])
      }, {
        i: i - 2,
        x: d3_interpolateNumber(ka[1], kb[1])
      });
    } else if (kb[0] !== 1 || kb[1] !== 1) {
      s.push(d3_interpolateTransformPop(s) + "scale(" + kb + ")");
    }
  }
  function d3_interpolateTransform(a, b) {
    var s = [], q = [];
    a = d3.transform(a), b = d3.transform(b);
    d3_interpolateTranslate(a.translate, b.translate, s, q);
    d3_interpolateRotate(a.rotate, b.rotate, s, q);
    d3_interpolateSkew(a.skew, b.skew, s, q);
    d3_interpolateScale(a.scale, b.scale, s, q);
    a = b = null;
    return function(t) {
      var i = -1, n = q.length, o;
      while (++i < n) s[(o = q[i]).i] = o.x(t);
      return s.join("");
    };
  }
  function d3_uninterpolateNumber(a, b) {
    b = (b -= a = +a) || 1 / b;
    return function(x) {
      return (x - a) / b;
    };
  }
  function d3_uninterpolateClamp(a, b) {
    b = (b -= a = +a) || 1 / b;
    return function(x) {
      return Math.max(0, Math.min(1, (x - a) / b));
    };
  }
  d3.layout = {};
  d3.layout.bundle = function() {
    return function(links) {
      var paths = [], i = -1, n = links.length;
      while (++i < n) paths.push(d3_layout_bundlePath(links[i]));
      return paths;
    };
  };
  function d3_layout_bundlePath(link) {
    var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ];
    while (start !== lca) {
      start = start.parent;
      points.push(start);
    }
    var k = points.length;
    while (end !== lca) {
      points.splice(k, 0, end);
      end = end.parent;
    }
    return points;
  }
  function d3_layout_bundleAncestors(node) {
    var ancestors = [], parent = node.parent;
    while (parent != null) {
      ancestors.push(node);
      node = parent;
      parent = parent.parent;
    }
    ancestors.push(node);
    return ancestors;
  }
  function d3_layout_bundleLeastCommonAncestor(a, b) {
    if (a === b) return a;
    var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null;
    while (aNode === bNode) {
      sharedNode = aNode;
      aNode = aNodes.pop();
      bNode = bNodes.pop();
    }
    return sharedNode;
  }
  d3.layout.chord = function() {
    var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords;
    function relayout() {
      var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j;
      chords = [];
      groups = [];
      k = 0, i = -1;
      while (++i < n) {
        x = 0, j = -1;
        while (++j < n) {
          x += matrix[i][j];
        }
        groupSums.push(x);
        subgroupIndex.push(d3.range(n));
        k += x;
      }
      if (sortGroups) {
        groupIndex.sort(function(a, b) {
          return sortGroups(groupSums[a], groupSums[b]);
        });
      }
      if (sortSubgroups) {
        subgroupIndex.forEach(function(d, i) {
          d.sort(function(a, b) {
            return sortSubgroups(matrix[i][a], matrix[i][b]);
          });
        });
      }
      k = (τ - padding * n) / k;
      x = 0, i = -1;
      while (++i < n) {
        x0 = x, j = -1;
        while (++j < n) {
          var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k;
          subgroups[di + "-" + dj] = {
            index: di,
            subindex: dj,
            startAngle: a0,
            endAngle: a1,
            value: v
          };
        }
        groups[di] = {
          index: di,
          startAngle: x0,
          endAngle: x,
          value: groupSums[di]
        };
        x += padding;
      }
      i = -1;
      while (++i < n) {
        j = i - 1;
        while (++j < n) {
          var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i];
          if (source.value || target.value) {
            chords.push(source.value < target.value ? {
              source: target,
              target: source
            } : {
              source: source,
              target: target
            });
          }
        }
      }
      if (sortChords) resort();
    }
    function resort() {
      chords.sort(function(a, b) {
        return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2);
      });
    }
    chord.matrix = function(x) {
      if (!arguments.length) return matrix;
      n = (matrix = x) && matrix.length;
      chords = groups = null;
      return chord;
    };
    chord.padding = function(x) {
      if (!arguments.length) return padding;
      padding = x;
      chords = groups = null;
      return chord;
    };
    chord.sortGroups = function(x) {
      if (!arguments.length) return sortGroups;
      sortGroups = x;
      chords = groups = null;
      return chord;
    };
    chord.sortSubgroups = function(x) {
      if (!arguments.length) return sortSubgroups;
      sortSubgroups = x;
      chords = null;
      return chord;
    };
    chord.sortChords = function(x) {
      if (!arguments.length) return sortChords;
      sortChords = x;
      if (chords) resort();
      return chord;
    };
    chord.chords = function() {
      if (!chords) relayout();
      return chords;
    };
    chord.groups = function() {
      if (!groups) relayout();
      return groups;
    };
    return chord;
  };
  d3.layout.force = function() {
    var force = {}, event = d3.dispatch("start", "tick", "end"), timer, size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, chargeDistance2 = d3_layout_forceChargeDistance2, gravity = .1, theta2 = .64, nodes = [], links = [], distances, strengths, charges;
    function repulse(node) {
      return function(quad, x1, _, x2) {
        if (quad.point !== node) {
          var dx = quad.cx - node.x, dy = quad.cy - node.y, dw = x2 - x1, dn = dx * dx + dy * dy;
          if (dw * dw / theta2 < dn) {
            if (dn < chargeDistance2) {
              var k = quad.charge / dn;
              node.px -= dx * k;
              node.py -= dy * k;
            }
            return true;
          }
          if (quad.point && dn && dn < chargeDistance2) {
            var k = quad.pointCharge / dn;
            node.px -= dx * k;
            node.py -= dy * k;
          }
        }
        return !quad.charge;
      };
    }
    force.tick = function() {
      if ((alpha *= .99) < .005) {
        timer = null;
        event.end({
          type: "end",
          alpha: alpha = 0
        });
        return true;
      }
      var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y;
      for (i = 0; i < m; ++i) {
        o = links[i];
        s = o.source;
        t = o.target;
        x = t.x - s.x;
        y = t.y - s.y;
        if (l = x * x + y * y) {
          l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l;
          x *= l;
          y *= l;
          t.x -= x * (k = s.weight + t.weight ? s.weight / (s.weight + t.weight) : .5);
          t.y -= y * k;
          s.x += x * (k = 1 - k);
          s.y += y * k;
        }
      }
      if (k = alpha * gravity) {
        x = size[0] / 2;
        y = size[1] / 2;
        i = -1;
        if (k) while (++i < n) {
          o = nodes[i];
          o.x += (x - o.x) * k;
          o.y += (y - o.y) * k;
        }
      }
      if (charge) {
        d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges);
        i = -1;
        while (++i < n) {
          if (!(o = nodes[i]).fixed) {
            q.visit(repulse(o));
          }
        }
      }
      i = -1;
      while (++i < n) {
        o = nodes[i];
        if (o.fixed) {
          o.x = o.px;
          o.y = o.py;
        } else {
          o.x -= (o.px - (o.px = o.x)) * friction;
          o.y -= (o.py - (o.py = o.y)) * friction;
        }
      }
      event.tick({
        type: "tick",
        alpha: alpha
      });
    };
    force.nodes = function(x) {
      if (!arguments.length) return nodes;
      nodes = x;
      return force;
    };
    force.links = function(x) {
      if (!arguments.length) return links;
      links = x;
      return force;
    };
    force.size = function(x) {
      if (!arguments.length) return size;
      size = x;
      return force;
    };
    force.linkDistance = function(x) {
      if (!arguments.length) return linkDistance;
      linkDistance = typeof x === "function" ? x : +x;
      return force;
    };
    force.distance = force.linkDistance;
    force.linkStrength = function(x) {
      if (!arguments.length) return linkStrength;
      linkStrength = typeof x === "function" ? x : +x;
      return force;
    };
    force.friction = function(x) {
      if (!arguments.length) return friction;
      friction = +x;
      return force;
    };
    force.charge = function(x) {
      if (!arguments.length) return charge;
      charge = typeof x === "function" ? x : +x;
      return force;
    };
    force.chargeDistance = function(x) {
      if (!arguments.length) return Math.sqrt(chargeDistance2);
      chargeDistance2 = x * x;
      return force;
    };
    force.gravity = function(x) {
      if (!arguments.length) return gravity;
      gravity = +x;
      return force;
    };
    force.theta = function(x) {
      if (!arguments.length) return Math.sqrt(theta2);
      theta2 = x * x;
      return force;
    };
    force.alpha = function(x) {
      if (!arguments.length) return alpha;
      x = +x;
      if (alpha) {
        if (x > 0) {
          alpha = x;
        } else {
          timer.c = null, timer.t = NaN, timer = null;
          event.end({
            type: "end",
            alpha: alpha = 0
          });
        }
      } else if (x > 0) {
        event.start({
          type: "start",
          alpha: alpha = x
        });
        timer = d3_timer(force.tick);
      }
      return force;
    };
    force.start = function() {
      var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o;
      for (i = 0; i < n; ++i) {
        (o = nodes[i]).index = i;
        o.weight = 0;
      }
      for (i = 0; i < m; ++i) {
        o = links[i];
        if (typeof o.source == "number") o.source = nodes[o.source];
        if (typeof o.target == "number") o.target = nodes[o.target];
        ++o.source.weight;
        ++o.target.weight;
      }
      for (i = 0; i < n; ++i) {
        o = nodes[i];
        if (isNaN(o.x)) o.x = position("x", w);
        if (isNaN(o.y)) o.y = position("y", h);
        if (isNaN(o.px)) o.px = o.x;
        if (isNaN(o.py)) o.py = o.y;
      }
      distances = [];
      if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance;
      strengths = [];
      if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength;
      charges = [];
      if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge;
      function position(dimension, size) {
        if (!neighbors) {
          neighbors = new Array(n);
          for (j = 0; j < n; ++j) {
            neighbors[j] = [];
          }
          for (j = 0; j < m; ++j) {
            var o = links[j];
            neighbors[o.source.index].push(o.target);
            neighbors[o.target.index].push(o.source);
          }
        }
        var candidates = neighbors[i], j = -1, l = candidates.length, x;
        while (++j < l) if (!isNaN(x = candidates[j][dimension])) return x;
        return Math.random() * size;
      }
      return force.resume();
    };
    force.resume = function() {
      return force.alpha(.1);
    };
    force.stop = function() {
      return force.alpha(0);
    };
    force.drag = function() {
      if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend);
      if (!arguments.length) return drag;
      this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag);
    };
    function dragmove(d) {
      d.px = d3.event.x, d.py = d3.event.y;
      force.resume();
    }
    return d3.rebind(force, event, "on");
  };
  function d3_layout_forceDragstart(d) {
    d.fixed |= 2;
  }
  function d3_layout_forceDragend(d) {
    d.fixed &= ~6;
  }
  function d3_layout_forceMouseover(d) {
    d.fixed |= 4;
    d.px = d.x, d.py = d.y;
  }
  function d3_layout_forceMouseout(d) {
    d.fixed &= ~4;
  }
  function d3_layout_forceAccumulate(quad, alpha, charges) {
    var cx = 0, cy = 0;
    quad.charge = 0;
    if (!quad.leaf) {
      var nodes = quad.nodes, n = nodes.length, i = -1, c;
      while (++i < n) {
        c = nodes[i];
        if (c == null) continue;
        d3_layout_forceAccumulate(c, alpha, charges);
        quad.charge += c.charge;
        cx += c.charge * c.cx;
        cy += c.charge * c.cy;
      }
    }
    if (quad.point) {
      if (!quad.leaf) {
        quad.point.x += Math.random() - .5;
        quad.point.y += Math.random() - .5;
      }
      var k = alpha * charges[quad.point.index];
      quad.charge += quad.pointCharge = k;
      cx += k * quad.point.x;
      cy += k * quad.point.y;
    }
    quad.cx = cx / quad.charge;
    quad.cy = cy / quad.charge;
  }
  var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1, d3_layout_forceChargeDistance2 = Infinity;
  d3.layout.hierarchy = function() {
    var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue;
    function hierarchy(root) {
      var stack = [ root ], nodes = [], node;
      root.depth = 0;
      while ((node = stack.pop()) != null) {
        nodes.push(node);
        if ((childs = children.call(hierarchy, node, node.depth)) && (n = childs.length)) {
          var n, childs, child;
          while (--n >= 0) {
            stack.push(child = childs[n]);
            child.parent = node;
            child.depth = node.depth + 1;
          }
          if (value) node.value = 0;
          node.children = childs;
        } else {
          if (value) node.value = +value.call(hierarchy, node, node.depth) || 0;
          delete node.children;
        }
      }
      d3_layout_hierarchyVisitAfter(root, function(node) {
        var childs, parent;
        if (sort && (childs = node.children)) childs.sort(sort);
        if (value && (parent = node.parent)) parent.value += node.value;
      });
      return nodes;
    }
    hierarchy.sort = function(x) {
      if (!arguments.length) return sort;
      sort = x;
      return hierarchy;
    };
    hierarchy.children = function(x) {
      if (!arguments.length) return children;
      children = x;
      return hierarchy;
    };
    hierarchy.value = function(x) {
      if (!arguments.length) return value;
      value = x;
      return hierarchy;
    };
    hierarchy.revalue = function(root) {
      if (value) {
        d3_layout_hierarchyVisitBefore(root, function(node) {
          if (node.children) node.value = 0;
        });
        d3_layout_hierarchyVisitAfter(root, function(node) {
          var parent;
          if (!node.children) node.value = +value.call(hierarchy, node, node.depth) || 0;
          if (parent = node.parent) parent.value += node.value;
        });
      }
      return root;
    };
    return hierarchy;
  };
  function d3_layout_hierarchyRebind(object, hierarchy) {
    d3.rebind(object, hierarchy, "sort", "children", "value");
    object.nodes = object;
    object.links = d3_layout_hierarchyLinks;
    return object;
  }
  function d3_layout_hierarchyVisitBefore(node, callback) {
    var nodes = [ node ];
    while ((node = nodes.pop()) != null) {
      callback(node);
      if ((children = node.children) && (n = children.length)) {
        var n, children;
        while (--n >= 0) nodes.push(children[n]);
      }
    }
  }
  function d3_layout_hierarchyVisitAfter(node, callback) {
    var nodes = [ node ], nodes2 = [];
    while ((node = nodes.pop()) != null) {
      nodes2.push(node);
      if ((children = node.children) && (n = children.length)) {
        var i = -1, n, children;
        while (++i < n) nodes.push(children[i]);
      }
    }
    while ((node = nodes2.pop()) != null) {
      callback(node);
    }
  }
  function d3_layout_hierarchyChildren(d) {
    return d.children;
  }
  function d3_layout_hierarchyValue(d) {
    return d.value;
  }
  function d3_layout_hierarchySort(a, b) {
    return b.value - a.value;
  }
  function d3_layout_hierarchyLinks(nodes) {
    return d3.merge(nodes.map(function(parent) {
      return (parent.children || []).map(function(child) {
        return {
          source: parent,
          target: child
        };
      });
    }));
  }
  d3.layout.partition = function() {
    var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ];
    function position(node, x, dx, dy) {
      var children = node.children;
      node.x = x;
      node.y = node.depth * dy;
      node.dx = dx;
      node.dy = dy;
      if (children && (n = children.length)) {
        var i = -1, n, c, d;
        dx = node.value ? dx / node.value : 0;
        while (++i < n) {
          position(c = children[i], x, d = c.value * dx, dy);
          x += d;
        }
      }
    }
    function depth(node) {
      var children = node.children, d = 0;
      if (children && (n = children.length)) {
        var i = -1, n;
        while (++i < n) d = Math.max(d, depth(children[i]));
      }
      return 1 + d;
    }
    function partition(d, i) {
      var nodes = hierarchy.call(this, d, i);
      position(nodes[0], 0, size[0], size[1] / depth(nodes[0]));
      return nodes;
    }
    partition.size = function(x) {
      if (!arguments.length) return size;
      size = x;
      return partition;
    };
    return d3_layout_hierarchyRebind(partition, hierarchy);
  };
  d3.layout.pie = function() {
    var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ, padAngle = 0;
    function pie(data) {
      var n = data.length, values = data.map(function(d, i) {
        return +value.call(pie, d, i);
      }), a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle), da = (typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a, p = Math.min(Math.abs(da) / n, +(typeof padAngle === "function" ? padAngle.apply(this, arguments) : padAngle)), pa = p * (da < 0 ? -1 : 1), sum = d3.sum(values), k = sum ? (da - n * pa) / sum : 0, index = d3.range(n), arcs = [], v;
      if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) {
        return values[j] - values[i];
      } : function(i, j) {
        return sort(data[i], data[j]);
      });
      index.forEach(function(i) {
        arcs[i] = {
          data: data[i],
          value: v = values[i],
          startAngle: a,
          endAngle: a += v * k + pa,
          padAngle: p
        };
      });
      return arcs;
    }
    pie.value = function(_) {
      if (!arguments.length) return value;
      value = _;
      return pie;
    };
    pie.sort = function(_) {
      if (!arguments.length) return sort;
      sort = _;
      return pie;
    };
    pie.startAngle = function(_) {
      if (!arguments.length) return startAngle;
      startAngle = _;
      return pie;
    };
    pie.endAngle = function(_) {
      if (!arguments.length) return endAngle;
      endAngle = _;
      return pie;
    };
    pie.padAngle = function(_) {
      if (!arguments.length) return padAngle;
      padAngle = _;
      return pie;
    };
    return pie;
  };
  var d3_layout_pieSortByValue = {};
  d3.layout.stack = function() {
    var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY;
    function stack(data, index) {
      if (!(n = data.length)) return data;
      var series = data.map(function(d, i) {
        return values.call(stack, d, i);
      });
      var points = series.map(function(d) {
        return d.map(function(v, i) {
          return [ x.call(stack, v, i), y.call(stack, v, i) ];
        });
      });
      var orders = order.call(stack, points, index);
      series = d3.permute(series, orders);
      points = d3.permute(points, orders);
      var offsets = offset.call(stack, points, index);
      var m = series[0].length, n, i, j, o;
      for (j = 0; j < m; ++j) {
        out.call(stack, series[0][j], o = offsets[j], points[0][j][1]);
        for (i = 1; i < n; ++i) {
          out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]);
        }
      }
      return data;
    }
    stack.values = function(x) {
      if (!arguments.length) return values;
      values = x;
      return stack;
    };
    stack.order = function(x) {
      if (!arguments.length) return order;
      order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault;
      return stack;
    };
    stack.offset = function(x) {
      if (!arguments.length) return offset;
      offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero;
      return stack;
    };
    stack.x = function(z) {
      if (!arguments.length) return x;
      x = z;
      return stack;
    };
    stack.y = function(z) {
      if (!arguments.length) return y;
      y = z;
      return stack;
    };
    stack.out = function(z) {
      if (!arguments.length) return out;
      out = z;
      return stack;
    };
    return stack;
  };
  function d3_layout_stackX(d) {
    return d.x;
  }
  function d3_layout_stackY(d) {
    return d.y;
  }
  function d3_layout_stackOut(d, y0, y) {
    d.y0 = y0;
    d.y = y;
  }
  var d3_layout_stackOrders = d3.map({
    "inside-out": function(data) {
      var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) {
        return max[a] - max[b];
      }), top = 0, bottom = 0, tops = [], bottoms = [];
      for (i = 0; i < n; ++i) {
        j = index[i];
        if (top < bottom) {
          top += sums[j];
          tops.push(j);
        } else {
          bottom += sums[j];
          bottoms.push(j);
        }
      }
      return bottoms.reverse().concat(tops);
    },
    reverse: function(data) {
      return d3.range(data.length).reverse();
    },
    "default": d3_layout_stackOrderDefault
  });
  var d3_layout_stackOffsets = d3.map({
    silhouette: function(data) {
      var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = [];
      for (j = 0; j < m; ++j) {
        for (i = 0, o = 0; i < n; i++) o += data[i][j][1];
        if (o > max) max = o;
        sums.push(o);
      }
      for (j = 0; j < m; ++j) {
        y0[j] = (max - sums[j]) / 2;
      }
      return y0;
    },
    wiggle: function(data) {
      var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = [];
      y0[0] = o = o0 = 0;
      for (j = 1; j < m; ++j) {
        for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1];
        for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) {
          for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) {
            s3 += (data[k][j][1] - data[k][j - 1][1]) / dx;
          }
          s2 += s3 * data[i][j][1];
        }
        y0[j] = o -= s1 ? s2 / s1 * dx : 0;
        if (o < o0) o0 = o;
      }
      for (j = 0; j < m; ++j) y0[j] -= o0;
      return y0;
    },
    expand: function(data) {
      var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = [];
      for (j = 0; j < m; ++j) {
        for (i = 0, o = 0; i < n; i++) o += data[i][j][1];
        if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k;
      }
      for (j = 0; j < m; ++j) y0[j] = 0;
      return y0;
    },
    zero: d3_layout_stackOffsetZero
  });
  function d3_layout_stackOrderDefault(data) {
    return d3.range(data.length);
  }
  function d3_layout_stackOffsetZero(data) {
    var j = -1, m = data[0].length, y0 = [];
    while (++j < m) y0[j] = 0;
    return y0;
  }
  function d3_layout_stackMaxIndex(array) {
    var i = 1, j = 0, v = array[0][1], k, n = array.length;
    for (;i < n; ++i) {
      if ((k = array[i][1]) > v) {
        j = i;
        v = k;
      }
    }
    return j;
  }
  function d3_layout_stackReduceSum(d) {
    return d.reduce(d3_layout_stackSum, 0);
  }
  function d3_layout_stackSum(p, d) {
    return p + d[1];
  }
  d3.layout.histogram = function() {
    var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges;
    function histogram(data, i) {
      var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x;
      while (++i < m) {
        bin = bins[i] = [];
        bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]);
        bin.y = 0;
      }
      if (m > 0) {
        i = -1;
        while (++i < n) {
          x = values[i];
          if (x >= range[0] && x <= range[1]) {
            bin = bins[d3.bisect(thresholds, x, 1, m) - 1];
            bin.y += k;
            bin.push(data[i]);
          }
        }
      }
      return bins;
    }
    histogram.value = function(x) {
      if (!arguments.length) return valuer;
      valuer = x;
      return histogram;
    };
    histogram.range = function(x) {
      if (!arguments.length) return ranger;
      ranger = d3_functor(x);
      return histogram;
    };
    histogram.bins = function(x) {
      if (!arguments.length) return binner;
      binner = typeof x === "number" ? function(range) {
        return d3_layout_histogramBinFixed(range, x);
      } : d3_functor(x);
      return histogram;
    };
    histogram.frequency = function(x) {
      if (!arguments.length) return frequency;
      frequency = !!x;
      return histogram;
    };
    return histogram;
  };
  function d3_layout_histogramBinSturges(range, values) {
    return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1));
  }
  function d3_layout_histogramBinFixed(range, n) {
    var x = -1, b = +range[0], m = (range[1] - b) / n, f = [];
    while (++x <= n) f[x] = m * x + b;
    return f;
  }
  function d3_layout_histogramRange(values) {
    return [ d3.min(values), d3.max(values) ];
  }
  d3.layout.pack = function() {
    var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ], radius;
    function pack(d, i) {
      var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() {
        return radius;
      };
      root.x = root.y = 0;
      d3_layout_hierarchyVisitAfter(root, function(d) {
        d.r = +r(d.value);
      });
      d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings);
      if (padding) {
        var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2;
        d3_layout_hierarchyVisitAfter(root, function(d) {
          d.r += dr;
        });
        d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings);
        d3_layout_hierarchyVisitAfter(root, function(d) {
          d.r -= dr;
        });
      }
      d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h));
      return nodes;
    }
    pack.size = function(_) {
      if (!arguments.length) return size;
      size = _;
      return pack;
    };
    pack.radius = function(_) {
      if (!arguments.length) return radius;
      radius = _ == null || typeof _ === "function" ? _ : +_;
      return pack;
    };
    pack.padding = function(_) {
      if (!arguments.length) return padding;
      padding = +_;
      return pack;
    };
    return d3_layout_hierarchyRebind(pack, hierarchy);
  };
  function d3_layout_packSort(a, b) {
    return a.value - b.value;
  }
  function d3_layout_packInsert(a, b) {
    var c = a._pack_next;
    a._pack_next = b;
    b._pack_prev = a;
    b._pack_next = c;
    c._pack_prev = b;
  }
  function d3_layout_packSplice(a, b) {
    a._pack_next = b;
    b._pack_prev = a;
  }
  function d3_layout_packIntersects(a, b) {
    var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r;
    return .999 * dr * dr > dx * dx + dy * dy;
  }
  function d3_layout_packSiblings(node) {
    if (!(nodes = node.children) || !(n = nodes.length)) return;
    var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n;
    function bound(node) {
      xMin = Math.min(node.x - node.r, xMin);
      xMax = Math.max(node.x + node.r, xMax);
      yMin = Math.min(node.y - node.r, yMin);
      yMax = Math.max(node.y + node.r, yMax);
    }
    nodes.forEach(d3_layout_packLink);
    a = nodes[0];
    a.x = -a.r;
    a.y = 0;
    bound(a);
    if (n > 1) {
      b = nodes[1];
      b.x = b.r;
      b.y = 0;
      bound(b);
      if (n > 2) {
        c = nodes[2];
        d3_layout_packPlace(a, b, c);
        bound(c);
        d3_layout_packInsert(a, c);
        a._pack_prev = c;
        d3_layout_packInsert(c, b);
        b = a._pack_next;
        for (i = 3; i < n; i++) {
          d3_layout_packPlace(a, b, c = nodes[i]);
          var isect = 0, s1 = 1, s2 = 1;
          for (j = b._pack_next; j !== b; j = j._pack_next, s1++) {
            if (d3_layout_packIntersects(j, c)) {
              isect = 1;
              break;
            }
          }
          if (isect == 1) {
            for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) {
              if (d3_layout_packIntersects(k, c)) {
                break;
              }
            }
          }
          if (isect) {
            if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b);
            i--;
          } else {
            d3_layout_packInsert(a, c);
            b = c;
            bound(c);
          }
        }
      }
    }
    var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0;
    for (i = 0; i < n; i++) {
      c = nodes[i];
      c.x -= cx;
      c.y -= cy;
      cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y));
    }
    node.r = cr;
    nodes.forEach(d3_layout_packUnlink);
  }
  function d3_layout_packLink(node) {
    node._pack_next = node._pack_prev = node;
  }
  function d3_layout_packUnlink(node) {
    delete node._pack_next;
    delete node._pack_prev;
  }
  function d3_layout_packTransform(node, x, y, k) {
    var children = node.children;
    node.x = x += k * node.x;
    node.y = y += k * node.y;
    node.r *= k;
    if (children) {
      var i = -1, n = children.length;
      while (++i < n) d3_layout_packTransform(children[i], x, y, k);
    }
  }
  function d3_layout_packPlace(a, b, c) {
    var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y;
    if (db && (dx || dy)) {
      var da = b.r + c.r, dc = dx * dx + dy * dy;
      da *= da;
      db *= db;
      var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc);
      c.x = a.x + x * dx + y * dy;
      c.y = a.y + x * dy - y * dx;
    } else {
      c.x = a.x + db;
      c.y = a.y;
    }
  }
  d3.layout.tree = function() {
    var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = null;
    function tree(d, i) {
      var nodes = hierarchy.call(this, d, i), root0 = nodes[0], root1 = wrapTree(root0);
      d3_layout_hierarchyVisitAfter(root1, firstWalk), root1.parent.m = -root1.z;
      d3_layout_hierarchyVisitBefore(root1, secondWalk);
      if (nodeSize) d3_layout_hierarchyVisitBefore(root0, sizeNode); else {
        var left = root0, right = root0, bottom = root0;
        d3_layout_hierarchyVisitBefore(root0, function(node) {
          if (node.x < left.x) left = node;
          if (node.x > right.x) right = node;
          if (node.depth > bottom.depth) bottom = node;
        });
        var tx = separation(left, right) / 2 - left.x, kx = size[0] / (right.x + separation(right, left) / 2 + tx), ky = size[1] / (bottom.depth || 1);
        d3_layout_hierarchyVisitBefore(root0, function(node) {
          node.x = (node.x + tx) * kx;
          node.y = node.depth * ky;
        });
      }
      return nodes;
    }
    function wrapTree(root0) {
      var root1 = {
        A: null,
        children: [ root0 ]
      }, queue = [ root1 ], node1;
      while ((node1 = queue.pop()) != null) {
        for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) {
          queue.push((children[i] = child = {
            _: children[i],
            parent: node1,
            children: (child = children[i].children) && child.slice() || [],
            A: null,
            a: null,
            z: 0,
            m: 0,
            c: 0,
            s: 0,
            t: null,
            i: i
          }).a = child);
        }
      }
      return root1.children[0];
    }
    function firstWalk(v) {
      var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null;
      if (children.length) {
        d3_layout_treeShift(v);
        var midpoint = (children[0].z + children[children.length - 1].z) / 2;
        if (w) {
          v.z = w.z + separation(v._, w._);
          v.m = v.z - midpoint;
        } else {
          v.z = midpoint;
        }
      } else if (w) {
        v.z = w.z + separation(v._, w._);
      }
      v.parent.A = apportion(v, w, v.parent.A || siblings[0]);
    }
    function secondWalk(v) {
      v._.x = v.z + v.parent.m;
      v.m += v.parent.m;
    }
    function apportion(v, w, ancestor) {
      if (w) {
        var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift;
        while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) {
          vom = d3_layout_treeLeft(vom);
          vop = d3_layout_treeRight(vop);
          vop.a = v;
          shift = vim.z + sim - vip.z - sip + separation(vim._, vip._);
          if (shift > 0) {
            d3_layout_treeMove(d3_layout_treeAncestor(vim, v, ancestor), v, shift);
            sip += shift;
            sop += shift;
          }
          sim += vim.m;
          sip += vip.m;
          som += vom.m;
          sop += vop.m;
        }
        if (vim && !d3_layout_treeRight(vop)) {
          vop.t = vim;
          vop.m += sim - sop;
        }
        if (vip && !d3_layout_treeLeft(vom)) {
          vom.t = vip;
          vom.m += sip - som;
          ancestor = v;
        }
      }
      return ancestor;
    }
    function sizeNode(node) {
      node.x *= size[0];
      node.y = node.depth * size[1];
    }
    tree.separation = function(x) {
      if (!arguments.length) return separation;
      separation = x;
      return tree;
    };
    tree.size = function(x) {
      if (!arguments.length) return nodeSize ? null : size;
      nodeSize = (size = x) == null ? sizeNode : null;
      return tree;
    };
    tree.nodeSize = function(x) {
      if (!arguments.length) return nodeSize ? size : null;
      nodeSize = (size = x) == null ? null : sizeNode;
      return tree;
    };
    return d3_layout_hierarchyRebind(tree, hierarchy);
  };
  function d3_layout_treeSeparation(a, b) {
    return a.parent == b.parent ? 1 : 2;
  }
  function d3_layout_treeLeft(v) {
    var children = v.children;
    return children.length ? children[0] : v.t;
  }
  function d3_layout_treeRight(v) {
    var children = v.children, n;
    return (n = children.length) ? children[n - 1] : v.t;
  }
  function d3_layout_treeMove(wm, wp, shift) {
    var change = shift / (wp.i - wm.i);
    wp.c -= change;
    wp.s += shift;
    wm.c += change;
    wp.z += shift;
    wp.m += shift;
  }
  function d3_layout_treeShift(v) {
    var shift = 0, change = 0, children = v.children, i = children.length, w;
    while (--i >= 0) {
      w = children[i];
      w.z += shift;
      w.m += shift;
      shift += w.s + (change += w.c);
    }
  }
  function d3_layout_treeAncestor(vim, v, ancestor) {
    return vim.a.parent === v.parent ? vim.a : ancestor;
  }
  d3.layout.cluster = function() {
    var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false;
    function cluster(d, i) {
      var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0;
      d3_layout_hierarchyVisitAfter(root, function(node) {
        var children = node.children;
        if (children && children.length) {
          node.x = d3_layout_clusterX(children);
          node.y = d3_layout_clusterY(children);
        } else {
          node.x = previousNode ? x += separation(node, previousNode) : 0;
          node.y = 0;
          previousNode = node;
        }
      });
      var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2;
      d3_layout_hierarchyVisitAfter(root, nodeSize ? function(node) {
        node.x = (node.x - root.x) * size[0];
        node.y = (root.y - node.y) * size[1];
      } : function(node) {
        node.x = (node.x - x0) / (x1 - x0) * size[0];
        node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1];
      });
      return nodes;
    }
    cluster.separation = function(x) {
      if (!arguments.length) return separation;
      separation = x;
      return cluster;
    };
    cluster.size = function(x) {
      if (!arguments.length) return nodeSize ? null : size;
      nodeSize = (size = x) == null;
      return cluster;
    };
    cluster.nodeSize = function(x) {
      if (!arguments.length) return nodeSize ? size : null;
      nodeSize = (size = x) != null;
      return cluster;
    };
    return d3_layout_hierarchyRebind(cluster, hierarchy);
  };
  function d3_layout_clusterY(children) {
    return 1 + d3.max(children, function(child) {
      return child.y;
    });
  }
  function d3_layout_clusterX(children) {
    return children.reduce(function(x, child) {
      return x + child.x;
    }, 0) / children.length;
  }
  function d3_layout_clusterLeft(node) {
    var children = node.children;
    return children && children.length ? d3_layout_clusterLeft(children[0]) : node;
  }
  function d3_layout_clusterRight(node) {
    var children = node.children, n;
    return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node;
  }
  d3.layout.treemap = function() {
    var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [ 1, 1 ], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = .5 * (1 + Math.sqrt(5));
    function scale(children, k) {
      var i = -1, n = children.length, child, area;
      while (++i < n) {
        area = (child = children[i]).value * (k < 0 ? 0 : k);
        child.area = isNaN(area) || area <= 0 ? 0 : area;
      }
    }
    function squarify(node) {
      var children = node.children;
      if (children && children.length) {
        var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = mode === "slice" ? rect.dx : mode === "dice" ? rect.dy : mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx : Math.min(rect.dx, rect.dy), n;
        scale(remaining, rect.dx * rect.dy / node.value);
        row.area = 0;
        while ((n = remaining.length) > 0) {
          row.push(child = remaining[n - 1]);
          row.area += child.area;
          if (mode !== "squarify" || (score = worst(row, u)) <= best) {
            remaining.pop();
            best = score;
          } else {
            row.area -= row.pop().area;
            position(row, u, rect, false);
            u = Math.min(rect.dx, rect.dy);
            row.length = row.area = 0;
            best = Infinity;
          }
        }
        if (row.length) {
          position(row, u, rect, true);
          row.length = row.area = 0;
        }
        children.forEach(squarify);
      }
    }
    function stickify(node) {
      var children = node.children;
      if (children && children.length) {
        var rect = pad(node), remaining = children.slice(), child, row = [];
        scale(remaining, rect.dx * rect.dy / node.value);
        row.area = 0;
        while (child = remaining.pop()) {
          row.push(child);
          row.area += child.area;
          if (child.z != null) {
            position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length);
            row.length = row.area = 0;
          }
        }
        children.forEach(stickify);
      }
    }
    function worst(row, u) {
      var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length;
      while (++i < n) {
        if (!(r = row[i].area)) continue;
        if (r < rmin) rmin = r;
        if (r > rmax) rmax = r;
      }
      s *= s;
      u *= u;
      return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity;
    }
    function position(row, u, rect, flush) {
      var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o;
      if (u == rect.dx) {
        if (flush || v > rect.dy) v = rect.dy;
        while (++i < n) {
          o = row[i];
          o.x = x;
          o.y = y;
          o.dy = v;
          x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0);
        }
        o.z = true;
        o.dx += rect.x + rect.dx - x;
        rect.y += v;
        rect.dy -= v;
      } else {
        if (flush || v > rect.dx) v = rect.dx;
        while (++i < n) {
          o = row[i];
          o.x = x;
          o.y = y;
          o.dx = v;
          y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0);
        }
        o.z = false;
        o.dy += rect.y + rect.dy - y;
        rect.x += v;
        rect.dx -= v;
      }
    }
    function treemap(d) {
      var nodes = stickies || hierarchy(d), root = nodes[0];
      root.x = root.y = 0;
      if (root.value) root.dx = size[0], root.dy = size[1]; else root.dx = root.dy = 0;
      if (stickies) hierarchy.revalue(root);
      scale([ root ], root.dx * root.dy / root.value);
      (stickies ? stickify : squarify)(root);
      if (sticky) stickies = nodes;
      return nodes;
    }
    treemap.size = function(x) {
      if (!arguments.length) return size;
      size = x;
      return treemap;
    };
    treemap.padding = function(x) {
      if (!arguments.length) return padding;
      function padFunction(node) {
        var p = x.call(treemap, node, node.depth);
        return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p);
      }
      function padConstant(node) {
        return d3_layout_treemapPad(node, x);
      }
      var type;
      pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ], 
      padConstant) : padConstant;
      return treemap;
    };
    treemap.round = function(x) {
      if (!arguments.length) return round != Number;
      round = x ? Math.round : Number;
      return treemap;
    };
    treemap.sticky = function(x) {
      if (!arguments.length) return sticky;
      sticky = x;
      stickies = null;
      return treemap;
    };
    treemap.ratio = function(x) {
      if (!arguments.length) return ratio;
      ratio = x;
      return treemap;
    };
    treemap.mode = function(x) {
      if (!arguments.length) return mode;
      mode = x + "";
      return treemap;
    };
    return d3_layout_hierarchyRebind(treemap, hierarchy);
  };
  function d3_layout_treemapPadNull(node) {
    return {
      x: node.x,
      y: node.y,
      dx: node.dx,
      dy: node.dy
    };
  }
  function d3_layout_treemapPad(node, padding) {
    var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2];
    if (dx < 0) {
      x += dx / 2;
      dx = 0;
    }
    if (dy < 0) {
      y += dy / 2;
      dy = 0;
    }
    return {
      x: x,
      y: y,
      dx: dx,
      dy: dy
    };
  }
  d3.random = {
    normal: function(µ, σ) {
      var n = arguments.length;
      if (n < 2) σ = 1;
      if (n < 1) µ = 0;
      return function() {
        var x, y, r;
        do {
          x = Math.random() * 2 - 1;
          y = Math.random() * 2 - 1;
          r = x * x + y * y;
        } while (!r || r > 1);
        return µ + σ * x * Math.sqrt(-2 * Math.log(r) / r);
      };
    },
    logNormal: function() {
      var random = d3.random.normal.apply(d3, arguments);
      return function() {
        return Math.exp(random());
      };
    },
    bates: function(m) {
      var random = d3.random.irwinHall(m);
      return function() {
        return random() / m;
      };
    },
    irwinHall: function(m) {
      return function() {
        for (var s = 0, j = 0; j < m; j++) s += Math.random();
        return s;
      };
    }
  };
  d3.scale = {};
  function d3_scaleExtent(domain) {
    var start = domain[0], stop = domain[domain.length - 1];
    return start < stop ? [ start, stop ] : [ stop, start ];
  }
  function d3_scaleRange(scale) {
    return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range());
  }
  function d3_scale_bilinear(domain, range, uninterpolate, interpolate) {
    var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]);
    return function(x) {
      return i(u(x));
    };
  }
  function d3_scale_nice(domain, nice) {
    var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx;
    if (x1 < x0) {
      dx = i0, i0 = i1, i1 = dx;
      dx = x0, x0 = x1, x1 = dx;
    }
    domain[i0] = nice.floor(x0);
    domain[i1] = nice.ceil(x1);
    return domain;
  }
  function d3_scale_niceStep(step) {
    return step ? {
      floor: function(x) {
        return Math.floor(x / step) * step;
      },
      ceil: function(x) {
        return Math.ceil(x / step) * step;
      }
    } : d3_scale_niceIdentity;
  }
  var d3_scale_niceIdentity = {
    floor: d3_identity,
    ceil: d3_identity
  };
  function d3_scale_polylinear(domain, range, uninterpolate, interpolate) {
    var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1;
    if (domain[k] < domain[0]) {
      domain = domain.slice().reverse();
      range = range.slice().reverse();
    }
    while (++j <= k) {
      u.push(uninterpolate(domain[j - 1], domain[j]));
      i.push(interpolate(range[j - 1], range[j]));
    }
    return function(x) {
      var j = d3.bisect(domain, x, 1, k) - 1;
      return i[j](u[j](x));
    };
  }
  d3.scale.linear = function() {
    return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3_interpolate, false);
  };
  function d3_scale_linear(domain, range, interpolate, clamp) {
    var output, input;
    function rescale() {
      var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber;
      output = linear(domain, range, uninterpolate, interpolate);
      input = linear(range, domain, uninterpolate, d3_interpolate);
      return scale;
    }
    function scale(x) {
      return output(x);
    }
    scale.invert = function(y) {
      return input(y);
    };
    scale.domain = function(x) {
      if (!arguments.length) return domain;
      domain = x.map(Number);
      return rescale();
    };
    scale.range = function(x) {
      if (!arguments.length) return range;
      range = x;
      return rescale();
    };
    scale.rangeRound = function(x) {
      return scale.range(x).interpolate(d3_interpolateRound);
    };
    scale.clamp = function(x) {
      if (!arguments.length) return clamp;
      clamp = x;
      return rescale();
    };
    scale.interpolate = function(x) {
      if (!arguments.length) return interpolate;
      interpolate = x;
      return rescale();
    };
    scale.ticks = function(m) {
      return d3_scale_linearTicks(domain, m);
    };
    scale.tickFormat = function(m, format) {
      return d3_scale_linearTickFormat(domain, m, format);
    };
    scale.nice = function(m) {
      d3_scale_linearNice(domain, m);
      return rescale();
    };
    scale.copy = function() {
      return d3_scale_linear(domain, range, interpolate, clamp);
    };
    return rescale();
  }
  function d3_scale_linearRebind(scale, linear) {
    return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp");
  }
  function d3_scale_linearNice(domain, m) {
    d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2]));
    d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2]));
    return domain;
  }
  function d3_scale_linearTickRange(domain, m) {
    if (m == null) m = 10;
    var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step;
    if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2;
    extent[0] = Math.ceil(extent[0] / step) * step;
    extent[1] = Math.floor(extent[1] / step) * step + step * .5;
    extent[2] = step;
    return extent;
  }
  function d3_scale_linearTicks(domain, m) {
    return d3.range.apply(d3, d3_scale_linearTickRange(domain, m));
  }
  function d3_scale_linearTickFormat(domain, m, format) {
    var range = d3_scale_linearTickRange(domain, m);
    if (format) {
      var match = d3_format_re.exec(format);
      match.shift();
      if (match[8] === "s") {
        var prefix = d3.formatPrefix(Math.max(abs(range[0]), abs(range[1])));
        if (!match[7]) match[7] = "." + d3_scale_linearPrecision(prefix.scale(range[2]));
        match[8] = "f";
        format = d3.format(match.join(""));
        return function(d) {
          return format(prefix.scale(d)) + prefix.symbol;
        };
      }
      if (!match[7]) match[7] = "." + d3_scale_linearFormatPrecision(match[8], range);
      format = match.join("");
    } else {
      format = ",." + d3_scale_linearPrecision(range[2]) + "f";
    }
    return d3.format(format);
  }
  var d3_scale_linearFormatSignificant = {
    s: 1,
    g: 1,
    p: 1,
    r: 1,
    e: 1
  };
  function d3_scale_linearPrecision(value) {
    return -Math.floor(Math.log(value) / Math.LN10 + .01);
  }
  function d3_scale_linearFormatPrecision(type, range) {
    var p = d3_scale_linearPrecision(range[2]);
    return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(abs(range[0]), abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2;
  }
  d3.scale.log = function() {
    return d3_scale_log(d3.scale.linear().domain([ 0, 1 ]), 10, true, [ 1, 10 ]);
  };
  function d3_scale_log(linear, base, positive, domain) {
    function log(x) {
      return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base);
    }
    function pow(x) {
      return positive ? Math.pow(base, x) : -Math.pow(base, -x);
    }
    function scale(x) {
      return linear(log(x));
    }
    scale.invert = function(x) {
      return pow(linear.invert(x));
    };
    scale.domain = function(x) {
      if (!arguments.length) return domain;
      positive = x[0] >= 0;
      linear.domain((domain = x.map(Number)).map(log));
      return scale;
    };
    scale.base = function(_) {
      if (!arguments.length) return base;
      base = +_;
      linear.domain(domain.map(log));
      return scale;
    };
    scale.nice = function() {
      var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative);
      linear.domain(niced);
      domain = niced.map(pow);
      return scale;
    };
    scale.ticks = function() {
      var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base;
      if (isFinite(j - i)) {
        if (positive) {
          for (;i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k);
          ticks.push(pow(i));
        } else {
          ticks.push(pow(i));
          for (;i++ < j; ) for (var k = n - 1; k > 0; k--) ticks.push(pow(i) * k);
        }
        for (i = 0; ticks[i] < u; i++) {}
        for (j = ticks.length; ticks[j - 1] > v; j--) {}
        ticks = ticks.slice(i, j);
      }
      return ticks;
    };
    scale.tickFormat = function(n, format) {
      if (!arguments.length) return d3_scale_logFormat;
      if (arguments.length < 2) format = d3_scale_logFormat; else if (typeof format !== "function") format = d3.format(format);
      var k = Math.max(1, base * n / scale.ticks().length);
      return function(d) {
        var i = d / pow(Math.round(log(d)));
        if (i * base < base - .5) i *= base;
        return i <= k ? format(d) : "";
      };
    };
    scale.copy = function() {
      return d3_scale_log(linear.copy(), base, positive, domain);
    };
    return d3_scale_linearRebind(scale, linear);
  }
  var d3_scale_logFormat = d3.format(".0e"), d3_scale_logNiceNegative = {
    floor: function(x) {
      return -Math.ceil(-x);
    },
    ceil: function(x) {
      return -Math.floor(-x);
    }
  };
  d3.scale.pow = function() {
    return d3_scale_pow(d3.scale.linear(), 1, [ 0, 1 ]);
  };
  function d3_scale_pow(linear, exponent, domain) {
    var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent);
    function scale(x) {
      return linear(powp(x));
    }
    scale.invert = function(x) {
      return powb(linear.invert(x));
    };
    scale.domain = function(x) {
      if (!arguments.length) return domain;
      linear.domain((domain = x.map(Number)).map(powp));
      return scale;
    };
    scale.ticks = function(m) {
      return d3_scale_linearTicks(domain, m);
    };
    scale.tickFormat = function(m, format) {
      return d3_scale_linearTickFormat(domain, m, format);
    };
    scale.nice = function(m) {
      return scale.domain(d3_scale_linearNice(domain, m));
    };
    scale.exponent = function(x) {
      if (!arguments.length) return exponent;
      powp = d3_scale_powPow(exponent = x);
      powb = d3_scale_powPow(1 / exponent);
      linear.domain(domain.map(powp));
      return scale;
    };
    scale.copy = function() {
      return d3_scale_pow(linear.copy(), exponent, domain);
    };
    return d3_scale_linearRebind(scale, linear);
  }
  function d3_scale_powPow(e) {
    return function(x) {
      return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e);
    };
  }
  d3.scale.sqrt = function() {
    return d3.scale.pow().exponent(.5);
  };
  d3.scale.ordinal = function() {
    return d3_scale_ordinal([], {
      t: "range",
      a: [ [] ]
    });
  };
  function d3_scale_ordinal(domain, ranger) {
    var index, range, rangeBand;
    function scale(x) {
      return range[((index.get(x) || (ranger.t === "range" ? index.set(x, domain.push(x)) : NaN)) - 1) % range.length];
    }
    function steps(start, step) {
      return d3.range(domain.length).map(function(i) {
        return start + step * i;
      });
    }
    scale.domain = function(x) {
      if (!arguments.length) return domain;
      domain = [];
      index = new d3_Map();
      var i = -1, n = x.length, xi;
      while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi));
      return scale[ranger.t].apply(scale, ranger.a);
    };
    scale.range = function(x) {
      if (!arguments.length) return range;
      range = x;
      rangeBand = 0;
      ranger = {
        t: "range",
        a: arguments
      };
      return scale;
    };
    scale.rangePoints = function(x, padding) {
      if (arguments.length < 2) padding = 0;
      var start = x[0], stop = x[1], step = domain.length < 2 ? (start = (start + stop) / 2, 
      0) : (stop - start) / (domain.length - 1 + padding);
      range = steps(start + step * padding / 2, step);
      rangeBand = 0;
      ranger = {
        t: "rangePoints",
        a: arguments
      };
      return scale;
    };
    scale.rangeRoundPoints = function(x, padding) {
      if (arguments.length < 2) padding = 0;
      var start = x[0], stop = x[1], step = domain.length < 2 ? (start = stop = Math.round((start + stop) / 2), 
      0) : (stop - start) / (domain.length - 1 + padding) | 0;
      range = steps(start + Math.round(step * padding / 2 + (stop - start - (domain.length - 1 + padding) * step) / 2), step);
      rangeBand = 0;
      ranger = {
        t: "rangeRoundPoints",
        a: arguments
      };
      return scale;
    };
    scale.rangeBands = function(x, padding, outerPadding) {
      if (arguments.length < 2) padding = 0;
      if (arguments.length < 3) outerPadding = padding;
      var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding);
      range = steps(start + step * outerPadding, step);
      if (reverse) range.reverse();
      rangeBand = step * (1 - padding);
      ranger = {
        t: "rangeBands",
        a: arguments
      };
      return scale;
    };
    scale.rangeRoundBands = function(x, padding, outerPadding) {
      if (arguments.length < 2) padding = 0;
      if (arguments.length < 3) outerPadding = padding;
      var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding));
      range = steps(start + Math.round((stop - start - (domain.length - padding) * step) / 2), step);
      if (reverse) range.reverse();
      rangeBand = Math.round(step * (1 - padding));
      ranger = {
        t: "rangeRoundBands",
        a: arguments
      };
      return scale;
    };
    scale.rangeBand = function() {
      return rangeBand;
    };
    scale.rangeExtent = function() {
      return d3_scaleExtent(ranger.a[0]);
    };
    scale.copy = function() {
      return d3_scale_ordinal(domain, ranger);
    };
    return scale.domain(domain);
  }
  d3.scale.category10 = function() {
    return d3.scale.ordinal().range(d3_category10);
  };
  d3.scale.category20 = function() {
    return d3.scale.ordinal().range(d3_category20);
  };
  d3.scale.category20b = function() {
    return d3.scale.ordinal().range(d3_category20b);
  };
  d3.scale.category20c = function() {
    return d3.scale.ordinal().range(d3_category20c);
  };
  var d3_category10 = [ 2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175 ].map(d3_rgbString);
  var d3_category20 = [ 2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725 ].map(d3_rgbString);
  var d3_category20b = [ 3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654 ].map(d3_rgbString);
  var d3_category20c = [ 3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081 ].map(d3_rgbString);
  d3.scale.quantile = function() {
    return d3_scale_quantile([], []);
  };
  function d3_scale_quantile(domain, range) {
    var thresholds;
    function rescale() {
      var k = 0, q = range.length;
      thresholds = [];
      while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q);
      return scale;
    }
    function scale(x) {
      if (!isNaN(x = +x)) return range[d3.bisect(thresholds, x)];
    }
    scale.domain = function(x) {
      if (!arguments.length) return domain;
      domain = x.map(d3_number).filter(d3_numeric).sort(d3_ascending);
      return rescale();
    };
    scale.range = function(x) {
      if (!arguments.length) return range;
      range = x;
      return rescale();
    };
    scale.quantiles = function() {
      return thresholds;
    };
    scale.invertExtent = function(y) {
      y = range.indexOf(y);
      return y < 0 ? [ NaN, NaN ] : [ y > 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1] ];
    };
    scale.copy = function() {
      return d3_scale_quantile(domain, range);
    };
    return rescale();
  }
  d3.scale.quantize = function() {
    return d3_scale_quantize(0, 1, [ 0, 1 ]);
  };
  function d3_scale_quantize(x0, x1, range) {
    var kx, i;
    function scale(x) {
      return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))];
    }
    function rescale() {
      kx = range.length / (x1 - x0);
      i = range.length - 1;
      return scale;
    }
    scale.domain = function(x) {
      if (!arguments.length) return [ x0, x1 ];
      x0 = +x[0];
      x1 = +x[x.length - 1];
      return rescale();
    };
    scale.range = function(x) {
      if (!arguments.length) return range;
      range = x;
      return rescale();
    };
    scale.invertExtent = function(y) {
      y = range.indexOf(y);
      y = y < 0 ? NaN : y / kx + x0;
      return [ y, y + 1 / kx ];
    };
    scale.copy = function() {
      return d3_scale_quantize(x0, x1, range);
    };
    return rescale();
  }
  d3.scale.threshold = function() {
    return d3_scale_threshold([ .5 ], [ 0, 1 ]);
  };
  function d3_scale_threshold(domain, range) {
    function scale(x) {
      if (x <= x) return range[d3.bisect(domain, x)];
    }
    scale.domain = function(_) {
      if (!arguments.length) return domain;
      domain = _;
      return scale;
    };
    scale.range = function(_) {
      if (!arguments.length) return range;
      range = _;
      return scale;
    };
    scale.invertExtent = function(y) {
      y = range.indexOf(y);
      return [ domain[y - 1], domain[y] ];
    };
    scale.copy = function() {
      return d3_scale_threshold(domain, range);
    };
    return scale;
  }
  d3.scale.identity = function() {
    return d3_scale_identity([ 0, 1 ]);
  };
  function d3_scale_identity(domain) {
    function identity(x) {
      return +x;
    }
    identity.invert = identity;
    identity.domain = identity.range = function(x) {
      if (!arguments.length) return domain;
      domain = x.map(identity);
      return identity;
    };
    identity.ticks = function(m) {
      return d3_scale_linearTicks(domain, m);
    };
    identity.tickFormat = function(m, format) {
      return d3_scale_linearTickFormat(domain, m, format);
    };
    identity.copy = function() {
      return d3_scale_identity(domain);
    };
    return identity;
  }
  d3.svg = {};
  function d3_zero() {
    return 0;
  }
  d3.svg.arc = function() {
    var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, cornerRadius = d3_zero, padRadius = d3_svg_arcAuto, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle, padAngle = d3_svg_arcPadAngle;
    function arc() {
      var r0 = Math.max(0, +innerRadius.apply(this, arguments)), r1 = Math.max(0, +outerRadius.apply(this, arguments)), a0 = startAngle.apply(this, arguments) - halfπ, a1 = endAngle.apply(this, arguments) - halfπ, da = Math.abs(a1 - a0), cw = a0 > a1 ? 0 : 1;
      if (r1 < r0) rc = r1, r1 = r0, r0 = rc;
      if (da >= τε) return circleSegment(r1, cw) + (r0 ? circleSegment(r0, 1 - cw) : "") + "Z";
      var rc, cr, rp, ap, p0 = 0, p1 = 0, x0, y0, x1, y1, x2, y2, x3, y3, path = [];
      if (ap = (+padAngle.apply(this, arguments) || 0) / 2) {
        rp = padRadius === d3_svg_arcAuto ? Math.sqrt(r0 * r0 + r1 * r1) : +padRadius.apply(this, arguments);
        if (!cw) p1 *= -1;
        if (r1) p1 = d3_asin(rp / r1 * Math.sin(ap));
        if (r0) p0 = d3_asin(rp / r0 * Math.sin(ap));
      }
      if (r1) {
        x0 = r1 * Math.cos(a0 + p1);
        y0 = r1 * Math.sin(a0 + p1);
        x1 = r1 * Math.cos(a1 - p1);
        y1 = r1 * Math.sin(a1 - p1);
        var l1 = Math.abs(a1 - a0 - 2 * p1) <= π ? 0 : 1;
        if (p1 && d3_svg_arcSweep(x0, y0, x1, y1) === cw ^ l1) {
          var h1 = (a0 + a1) / 2;
          x0 = r1 * Math.cos(h1);
          y0 = r1 * Math.sin(h1);
          x1 = y1 = null;
        }
      } else {
        x0 = y0 = 0;
      }
      if (r0) {
        x2 = r0 * Math.cos(a1 - p0);
        y2 = r0 * Math.sin(a1 - p0);
        x3 = r0 * Math.cos(a0 + p0);
        y3 = r0 * Math.sin(a0 + p0);
        var l0 = Math.abs(a0 - a1 + 2 * p0) <= π ? 0 : 1;
        if (p0 && d3_svg_arcSweep(x2, y2, x3, y3) === 1 - cw ^ l0) {
          var h0 = (a0 + a1) / 2;
          x2 = r0 * Math.cos(h0);
          y2 = r0 * Math.sin(h0);
          x3 = y3 = null;
        }
      } else {
        x2 = y2 = 0;
      }
      if (da > ε && (rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > .001) {
        cr = r0 < r1 ^ cw ? 0 : 1;
        var rc1 = rc, rc0 = rc;
        if (da < π) {
          var oc = x3 == null ? [ x2, y2 ] : x1 == null ? [ x0, y0 ] : d3_geom_polygonIntersect([ x0, y0 ], [ x3, y3 ], [ x1, y1 ], [ x2, y2 ]), ax = x0 - oc[0], ay = y0 - oc[1], bx = x1 - oc[0], by = y1 - oc[1], kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2), lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]);
          rc0 = Math.min(rc, (r0 - lc) / (kc - 1));
          rc1 = Math.min(rc, (r1 - lc) / (kc + 1));
        }
        if (x1 != null) {
          var t30 = d3_svg_arcCornerTangents(x3 == null ? [ x2, y2 ] : [ x3, y3 ], [ x0, y0 ], r1, rc1, cw), t12 = d3_svg_arcCornerTangents([ x1, y1 ], [ x2, y2 ], r1, rc1, cw);
          if (rc === rc1) {
            path.push("M", t30[0], "A", rc1, ",", rc1, " 0 0,", cr, " ", t30[1], "A", r1, ",", r1, " 0 ", 1 - cw ^ d3_svg_arcSweep(t30[1][0], t30[1][1], t12[1][0], t12[1][1]), ",", cw, " ", t12[1], "A", rc1, ",", rc1, " 0 0,", cr, " ", t12[0]);
          } else {
            path.push("M", t30[0], "A", rc1, ",", rc1, " 0 1,", cr, " ", t12[0]);
          }
        } else {
          path.push("M", x0, ",", y0);
        }
        if (x3 != null) {
          var t03 = d3_svg_arcCornerTangents([ x0, y0 ], [ x3, y3 ], r0, -rc0, cw), t21 = d3_svg_arcCornerTangents([ x2, y2 ], x1 == null ? [ x0, y0 ] : [ x1, y1 ], r0, -rc0, cw);
          if (rc === rc0) {
            path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t21[1], "A", r0, ",", r0, " 0 ", cw ^ d3_svg_arcSweep(t21[1][0], t21[1][1], t03[1][0], t03[1][1]), ",", 1 - cw, " ", t03[1], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]);
          } else {
            path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]);
          }
        } else {
          path.push("L", x2, ",", y2);
        }
      } else {
        path.push("M", x0, ",", y0);
        if (x1 != null) path.push("A", r1, ",", r1, " 0 ", l1, ",", cw, " ", x1, ",", y1);
        path.push("L", x2, ",", y2);
        if (x3 != null) path.push("A", r0, ",", r0, " 0 ", l0, ",", 1 - cw, " ", x3, ",", y3);
      }
      path.push("Z");
      return path.join("");
    }
    function circleSegment(r1, cw) {
      return "M0," + r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + -r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + r1;
    }
    arc.innerRadius = function(v) {
      if (!arguments.length) return innerRadius;
      innerRadius = d3_functor(v);
      return arc;
    };
    arc.outerRadius = function(v) {
      if (!arguments.length) return outerRadius;
      outerRadius = d3_functor(v);
      return arc;
    };
    arc.cornerRadius = function(v) {
      if (!arguments.length) return cornerRadius;
      cornerRadius = d3_functor(v);
      return arc;
    };
    arc.padRadius = function(v) {
      if (!arguments.length) return padRadius;
      padRadius = v == d3_svg_arcAuto ? d3_svg_arcAuto : d3_functor(v);
      return arc;
    };
    arc.startAngle = function(v) {
      if (!arguments.length) return startAngle;
      startAngle = d3_functor(v);
      return arc;
    };
    arc.endAngle = function(v) {
      if (!arguments.length) return endAngle;
      endAngle = d3_functor(v);
      return arc;
    };
    arc.padAngle = function(v) {
      if (!arguments.length) return padAngle;
      padAngle = d3_functor(v);
      return arc;
    };
    arc.centroid = function() {
      var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - halfπ;
      return [ Math.cos(a) * r, Math.sin(a) * r ];
    };
    return arc;
  };
  var d3_svg_arcAuto = "auto";
  function d3_svg_arcInnerRadius(d) {
    return d.innerRadius;
  }
  function d3_svg_arcOuterRadius(d) {
    return d.outerRadius;
  }
  function d3_svg_arcStartAngle(d) {
    return d.startAngle;
  }
  function d3_svg_arcEndAngle(d) {
    return d.endAngle;
  }
  function d3_svg_arcPadAngle(d) {
    return d && d.padAngle;
  }
  function d3_svg_arcSweep(x0, y0, x1, y1) {
    return (x0 - x1) * y0 - (y0 - y1) * x0 > 0 ? 0 : 1;
  }
  function d3_svg_arcCornerTangents(p0, p1, r1, rc, cw) {
    var x01 = p0[0] - p1[0], y01 = p0[1] - p1[1], lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x1 = p0[0] + ox, y1 = p0[1] + oy, x2 = p1[0] + ox, y2 = p1[1] + oy, x3 = (x1 + x2) / 2, y3 = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, d2 = dx * dx + dy * dy, r = r1 - rc, D = x1 * y2 - x2 * y1, d = (dy < 0 ? -1 : 1) * Math.sqrt(Math.max(0, r * r * d2 - D * D)), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x3, dy0 = cy0 - y3, dx1 = cx1 - x3, dy1 = cy1 - y3;
    if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1;
    return [ [ cx0 - ox, cy0 - oy ], [ cx0 * r1 / r, cy0 * r1 / r ] ];
  }
  function d3_svg_line(projection) {
    var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7;
    function line(data) {
      var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y);
      function segment() {
        segments.push("M", interpolate(projection(points), tension));
      }
      while (++i < n) {
        if (defined.call(this, d = data[i], i)) {
          points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]);
        } else if (points.length) {
          segment();
          points = [];
        }
      }
      if (points.length) segment();
      return segments.length ? segments.join("") : null;
    }
    line.x = function(_) {
      if (!arguments.length) return x;
      x = _;
      return line;
    };
    line.y = function(_) {
      if (!arguments.length) return y;
      y = _;
      return line;
    };
    line.defined = function(_) {
      if (!arguments.length) return defined;
      defined = _;
      return line;
    };
    line.interpolate = function(_) {
      if (!arguments.length) return interpolateKey;
      if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key;
      return line;
    };
    line.tension = function(_) {
      if (!arguments.length) return tension;
      tension = _;
      return line;
    };
    return line;
  }
  d3.svg.line = function() {
    return d3_svg_line(d3_identity);
  };
  var d3_svg_lineInterpolators = d3.map({
    linear: d3_svg_lineLinear,
    "linear-closed": d3_svg_lineLinearClosed,
    step: d3_svg_lineStep,
    "step-before": d3_svg_lineStepBefore,
    "step-after": d3_svg_lineStepAfter,
    basis: d3_svg_lineBasis,
    "basis-open": d3_svg_lineBasisOpen,
    "basis-closed": d3_svg_lineBasisClosed,
    bundle: d3_svg_lineBundle,
    cardinal: d3_svg_lineCardinal,
    "cardinal-open": d3_svg_lineCardinalOpen,
    "cardinal-closed": d3_svg_lineCardinalClosed,
    monotone: d3_svg_lineMonotone
  });
  d3_svg_lineInterpolators.forEach(function(key, value) {
    value.key = key;
    value.closed = /-closed$/.test(key);
  });
  function d3_svg_lineLinear(points) {
    return points.length > 1 ? points.join("L") : points + "Z";
  }
  function d3_svg_lineLinearClosed(points) {
    return points.join("L") + "Z";
  }
  function d3_svg_lineStep(points) {
    var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
    while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]);
    if (n > 1) path.push("H", p[0]);
    return path.join("");
  }
  function d3_svg_lineStepBefore(points) {
    var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
    while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]);
    return path.join("");
  }
  function d3_svg_lineStepAfter(points) {
    var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
    while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]);
    return path.join("");
  }
  function d3_svg_lineCardinalOpen(points, tension) {
    return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, -1), d3_svg_lineCardinalTangents(points, tension));
  }
  function d3_svg_lineCardinalClosed(points, tension) {
    return points.length < 3 ? d3_svg_lineLinearClosed(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), 
    points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension));
  }
  function d3_svg_lineCardinal(points, tension) {
    return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension));
  }
  function d3_svg_lineHermite(points, tangents) {
    if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) {
      return d3_svg_lineLinear(points);
    }
    var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1;
    if (quad) {
      path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1];
      p0 = points[1];
      pi = 2;
    }
    if (tangents.length > 1) {
      t = tangents[1];
      p = points[pi];
      pi++;
      path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
      for (var i = 2; i < tangents.length; i++, pi++) {
        p = points[pi];
        t = tangents[i];
        path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
      }
    }
    if (quad) {
      var lp = points[pi];
      path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1];
    }
    return path;
  }
  function d3_svg_lineCardinalTangents(points, tension) {
    var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length;
    while (++i < n) {
      p0 = p1;
      p1 = p2;
      p2 = points[i];
      tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]);
    }
    return tangents;
  }
  function d3_svg_lineBasis(points) {
    if (points.length < 3) return d3_svg_lineLinear(points);
    var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ];
    points.push(points[n - 1]);
    while (++i <= n) {
      pi = points[i];
      px.shift();
      px.push(pi[0]);
      py.shift();
      py.push(pi[1]);
      d3_svg_lineBasisBezier(path, px, py);
    }
    points.pop();
    path.push("L", pi);
    return path.join("");
  }
  function d3_svg_lineBasisOpen(points) {
    if (points.length < 4) return d3_svg_lineLinear(points);
    var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ];
    while (++i < 3) {
      pi = points[i];
      px.push(pi[0]);
      py.push(pi[1]);
    }
    path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py));
    --i;
    while (++i < n) {
      pi = points[i];
      px.shift();
      px.push(pi[0]);
      py.shift();
      py.push(pi[1]);
      d3_svg_lineBasisBezier(path, px, py);
    }
    return path.join("");
  }
  function d3_svg_lineBasisClosed(points) {
    var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = [];
    while (++i < 4) {
      pi = points[i % n];
      px.push(pi[0]);
      py.push(pi[1]);
    }
    path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ];
    --i;
    while (++i < m) {
      pi = points[i % n];
      px.shift();
      px.push(pi[0]);
      py.shift();
      py.push(pi[1]);
      d3_svg_lineBasisBezier(path, px, py);
    }
    return path.join("");
  }
  function d3_svg_lineBundle(points, tension) {
    var n = points.length - 1;
    if (n) {
      var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t;
      while (++i <= n) {
        p = points[i];
        t = i / n;
        p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx);
        p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy);
      }
    }
    return d3_svg_lineBasis(points);
  }
  function d3_svg_lineDot4(a, b) {
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
  }
  var d3_svg_lineBasisBezier1 = [ 0, 2 / 3, 1 / 3, 0 ], d3_svg_lineBasisBezier2 = [ 0, 1 / 3, 2 / 3, 0 ], d3_svg_lineBasisBezier3 = [ 0, 1 / 6, 2 / 3, 1 / 6 ];
  function d3_svg_lineBasisBezier(path, x, y) {
    path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y));
  }
  function d3_svg_lineSlope(p0, p1) {
    return (p1[1] - p0[1]) / (p1[0] - p0[0]);
  }
  function d3_svg_lineFiniteDifferences(points) {
    var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1);
    while (++i < j) {
      m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2;
    }
    m[i] = d;
    return m;
  }
  function d3_svg_lineMonotoneTangents(points) {
    var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1;
    while (++i < j) {
      d = d3_svg_lineSlope(points[i], points[i + 1]);
      if (abs(d) < ε) {
        m[i] = m[i + 1] = 0;
      } else {
        a = m[i] / d;
        b = m[i + 1] / d;
        s = a * a + b * b;
        if (s > 9) {
          s = d * 3 / Math.sqrt(s);
          m[i] = s * a;
          m[i + 1] = s * b;
        }
      }
    }
    i = -1;
    while (++i <= j) {
      s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i]));
      tangents.push([ s || 0, m[i] * s || 0 ]);
    }
    return tangents;
  }
  function d3_svg_lineMonotone(points) {
    return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points));
  }
  d3.svg.line.radial = function() {
    var line = d3_svg_line(d3_svg_lineRadial);
    line.radius = line.x, delete line.x;
    line.angle = line.y, delete line.y;
    return line;
  };
  function d3_svg_lineRadial(points) {
    var point, i = -1, n = points.length, r, a;
    while (++i < n) {
      point = points[i];
      r = point[0];
      a = point[1] - halfπ;
      point[0] = r * Math.cos(a);
      point[1] = r * Math.sin(a);
    }
    return points;
  }
  function d3_svg_area(projection) {
    var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7;
    function area(data) {
      var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() {
        return x;
      } : d3_functor(x1), fy1 = y0 === y1 ? function() {
        return y;
      } : d3_functor(y1), x, y;
      function segment() {
        segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z");
      }
      while (++i < n) {
        if (defined.call(this, d = data[i], i)) {
          points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]);
          points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]);
        } else if (points0.length) {
          segment();
          points0 = [];
          points1 = [];
        }
      }
      if (points0.length) segment();
      return segments.length ? segments.join("") : null;
    }
    area.x = function(_) {
      if (!arguments.length) return x1;
      x0 = x1 = _;
      return area;
    };
    area.x0 = function(_) {
      if (!arguments.length) return x0;
      x0 = _;
      return area;
    };
    area.x1 = function(_) {
      if (!arguments.length) return x1;
      x1 = _;
      return area;
    };
    area.y = function(_) {
      if (!arguments.length) return y1;
      y0 = y1 = _;
      return area;
    };
    area.y0 = function(_) {
      if (!arguments.length) return y0;
      y0 = _;
      return area;
    };
    area.y1 = function(_) {
      if (!arguments.length) return y1;
      y1 = _;
      return area;
    };
    area.defined = function(_) {
      if (!arguments.length) return defined;
      defined = _;
      return area;
    };
    area.interpolate = function(_) {
      if (!arguments.length) return interpolateKey;
      if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key;
      interpolateReverse = interpolate.reverse || interpolate;
      L = interpolate.closed ? "M" : "L";
      return area;
    };
    area.tension = function(_) {
      if (!arguments.length) return tension;
      tension = _;
      return area;
    };
    return area;
  }
  d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter;
  d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore;
  d3.svg.area = function() {
    return d3_svg_area(d3_identity);
  };
  d3.svg.area.radial = function() {
    var area = d3_svg_area(d3_svg_lineRadial);
    area.radius = area.x, delete area.x;
    area.innerRadius = area.x0, delete area.x0;
    area.outerRadius = area.x1, delete area.x1;
    area.angle = area.y, delete area.y;
    area.startAngle = area.y0, delete area.y0;
    area.endAngle = area.y1, delete area.y1;
    return area;
  };
  d3.svg.chord = function() {
    var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle;
    function chord(d, i) {
      var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i);
      return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z";
    }
    function subgroup(self, f, d, i) {
      var subgroup = f.call(self, d, i), r = radius.call(self, subgroup, i), a0 = startAngle.call(self, subgroup, i) - halfπ, a1 = endAngle.call(self, subgroup, i) - halfπ;
      return {
        r: r,
        a0: a0,
        a1: a1,
        p0: [ r * Math.cos(a0), r * Math.sin(a0) ],
        p1: [ r * Math.cos(a1), r * Math.sin(a1) ]
      };
    }
    function equals(a, b) {
      return a.a0 == b.a0 && a.a1 == b.a1;
    }
    function arc(r, p, a) {
      return "A" + r + "," + r + " 0 " + +(a > π) + ",1 " + p;
    }
    function curve(r0, p0, r1, p1) {
      return "Q 0,0 " + p1;
    }
    chord.radius = function(v) {
      if (!arguments.length) return radius;
      radius = d3_functor(v);
      return chord;
    };
    chord.source = function(v) {
      if (!arguments.length) return source;
      source = d3_functor(v);
      return chord;
    };
    chord.target = function(v) {
      if (!arguments.length) return target;
      target = d3_functor(v);
      return chord;
    };
    chord.startAngle = function(v) {
      if (!arguments.length) return startAngle;
      startAngle = d3_functor(v);
      return chord;
    };
    chord.endAngle = function(v) {
      if (!arguments.length) return endAngle;
      endAngle = d3_functor(v);
      return chord;
    };
    return chord;
  };
  function d3_svg_chordRadius(d) {
    return d.radius;
  }
  d3.svg.diagonal = function() {
    var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection;
    function diagonal(d, i) {
      var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, {
        x: p0.x,
        y: m
      }, {
        x: p3.x,
        y: m
      }, p3 ];
      p = p.map(projection);
      return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3];
    }
    diagonal.source = function(x) {
      if (!arguments.length) return source;
      source = d3_functor(x);
      return diagonal;
    };
    diagonal.target = function(x) {
      if (!arguments.length) return target;
      target = d3_functor(x);
      return diagonal;
    };
    diagonal.projection = function(x) {
      if (!arguments.length) return projection;
      projection = x;
      return diagonal;
    };
    return diagonal;
  };
  function d3_svg_diagonalProjection(d) {
    return [ d.x, d.y ];
  }
  d3.svg.diagonal.radial = function() {
    var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection;
    diagonal.projection = function(x) {
      return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection;
    };
    return diagonal;
  };
  function d3_svg_diagonalRadialProjection(projection) {
    return function() {
      var d = projection.apply(this, arguments), r = d[0], a = d[1] - halfπ;
      return [ r * Math.cos(a), r * Math.sin(a) ];
    };
  }
  d3.svg.symbol = function() {
    var type = d3_svg_symbolType, size = d3_svg_symbolSize;
    function symbol(d, i) {
      return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i));
    }
    symbol.type = function(x) {
      if (!arguments.length) return type;
      type = d3_functor(x);
      return symbol;
    };
    symbol.size = function(x) {
      if (!arguments.length) return size;
      size = d3_functor(x);
      return symbol;
    };
    return symbol;
  };
  function d3_svg_symbolSize() {
    return 64;
  }
  function d3_svg_symbolType() {
    return "circle";
  }
  function d3_svg_symbolCircle(size) {
    var r = Math.sqrt(size / π);
    return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z";
  }
  var d3_svg_symbols = d3.map({
    circle: d3_svg_symbolCircle,
    cross: function(size) {
      var r = Math.sqrt(size / 5) / 2;
      return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z";
    },
    diamond: function(size) {
      var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30;
      return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z";
    },
    square: function(size) {
      var r = Math.sqrt(size) / 2;
      return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z";
    },
    "triangle-down": function(size) {
      var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2;
      return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z";
    },
    "triangle-up": function(size) {
      var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2;
      return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z";
    }
  });
  d3.svg.symbolTypes = d3_svg_symbols.keys();
  var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians);
  d3_selectionPrototype.transition = function(name) {
    var id = d3_transitionInheritId || ++d3_transitionId, ns = d3_transitionNamespace(name), subgroups = [], subgroup, node, transition = d3_transitionInherit || {
      time: Date.now(),
      ease: d3_ease_cubicInOut,
      delay: 0,
      duration: 250
    };
    for (var j = -1, m = this.length; ++j < m; ) {
      subgroups.push(subgroup = []);
      for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
        if (node = group[i]) d3_transitionNode(node, i, ns, id, transition);
        subgroup.push(node);
      }
    }
    return d3_transition(subgroups, ns, id);
  };
  d3_selectionPrototype.interrupt = function(name) {
    return this.each(name == null ? d3_selection_interrupt : d3_selection_interruptNS(d3_transitionNamespace(name)));
  };
  var d3_selection_interrupt = d3_selection_interruptNS(d3_transitionNamespace());
  function d3_selection_interruptNS(ns) {
    return function() {
      var lock, activeId, active;
      if ((lock = this[ns]) && (active = lock[activeId = lock.active])) {
        active.timer.c = null;
        active.timer.t = NaN;
        if (--lock.count) delete lock[activeId]; else delete this[ns];
        lock.active += .5;
        active.event && active.event.interrupt.call(this, this.__data__, active.index);
      }
    };
  }
  function d3_transition(groups, ns, id) {
    d3_subclass(groups, d3_transitionPrototype);
    groups.namespace = ns;
    groups.id = id;
    return groups;
  }
  var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit;
  d3_transitionPrototype.call = d3_selectionPrototype.call;
  d3_transitionPrototype.empty = d3_selectionPrototype.empty;
  d3_transitionPrototype.node = d3_selectionPrototype.node;
  d3_transitionPrototype.size = d3_selectionPrototype.size;
  d3.transition = function(selection, name) {
    return selection && selection.transition ? d3_transitionInheritId ? selection.transition(name) : selection : d3.selection().transition(selection);
  };
  d3.transition.prototype = d3_transitionPrototype;
  d3_transitionPrototype.select = function(selector) {
    var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnode, node;
    selector = d3_selection_selector(selector);
    for (var j = -1, m = this.length; ++j < m; ) {
      subgroups.push(subgroup = []);
      for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
        if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) {
          if ("__data__" in node) subnode.__data__ = node.__data__;
          d3_transitionNode(subnode, i, ns, id, node[ns][id]);
          subgroup.push(subnode);
        } else {
          subgroup.push(null);
        }
      }
    }
    return d3_transition(subgroups, ns, id);
  };
  d3_transitionPrototype.selectAll = function(selector) {
    var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnodes, node, subnode, transition;
    selector = d3_selection_selectorAll(selector);
    for (var j = -1, m = this.length; ++j < m; ) {
      for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
        if (node = group[i]) {
          transition = node[ns][id];
          subnodes = selector.call(node, node.__data__, i, j);
          subgroups.push(subgroup = []);
          for (var k = -1, o = subnodes.length; ++k < o; ) {
            if (subnode = subnodes[k]) d3_transitionNode(subnode, k, ns, id, transition);
            subgroup.push(subnode);
          }
        }
      }
    }
    return d3_transition(subgroups, ns, id);
  };
  d3_transitionPrototype.filter = function(filter) {
    var subgroups = [], subgroup, group, node;
    if (typeof filter !== "function") filter = d3_selection_filter(filter);
    for (var j = 0, m = this.length; j < m; j++) {
      subgroups.push(subgroup = []);
      for (var group = this[j], i = 0, n = group.length; i < n; i++) {
        if ((node = group[i]) && filter.call(node, node.__data__, i, j)) {
          subgroup.push(node);
        }
      }
    }
    return d3_transition(subgroups, this.namespace, this.id);
  };
  d3_transitionPrototype.tween = function(name, tween) {
    var id = this.id, ns = this.namespace;
    if (arguments.length < 2) return this.node()[ns][id].tween.get(name);
    return d3_selection_each(this, tween == null ? function(node) {
      node[ns][id].tween.remove(name);
    } : function(node) {
      node[ns][id].tween.set(name, tween);
    });
  };
  function d3_transition_tween(groups, name, value, tween) {
    var id = groups.id, ns = groups.namespace;
    return d3_selection_each(groups, typeof value === "function" ? function(node, i, j) {
      node[ns][id].tween.set(name, tween(value.call(node, node.__data__, i, j)));
    } : (value = tween(value), function(node) {
      node[ns][id].tween.set(name, value);
    }));
  }
  d3_transitionPrototype.attr = function(nameNS, value) {
    if (arguments.length < 2) {
      for (value in nameNS) this.attr(value, nameNS[value]);
      return this;
    }
    var interpolate = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name = d3.ns.qualify(nameNS);
    function attrNull() {
      this.removeAttribute(name);
    }
    function attrNullNS() {
      this.removeAttributeNS(name.space, name.local);
    }
    function attrTween(b) {
      return b == null ? attrNull : (b += "", function() {
        var a = this.getAttribute(name), i;
        return a !== b && (i = interpolate(a, b), function(t) {
          this.setAttribute(name, i(t));
        });
      });
    }
    function attrTweenNS(b) {
      return b == null ? attrNullNS : (b += "", function() {
        var a = this.getAttributeNS(name.space, name.local), i;
        return a !== b && (i = interpolate(a, b), function(t) {
          this.setAttributeNS(name.space, name.local, i(t));
        });
      });
    }
    return d3_transition_tween(this, "attr." + nameNS, value, name.local ? attrTweenNS : attrTween);
  };
  d3_transitionPrototype.attrTween = function(nameNS, tween) {
    var name = d3.ns.qualify(nameNS);
    function attrTween(d, i) {
      var f = tween.call(this, d, i, this.getAttribute(name));
      return f && function(t) {
        this.setAttribute(name, f(t));
      };
    }
    function attrTweenNS(d, i) {
      var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local));
      return f && function(t) {
        this.setAttributeNS(name.space, name.local, f(t));
      };
    }
    return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween);
  };
  d3_transitionPrototype.style = function(name, value, priority) {
    var n = arguments.length;
    if (n < 3) {
      if (typeof name !== "string") {
        if (n < 2) value = "";
        for (priority in name) this.style(priority, name[priority], value);
        return this;
      }
      priority = "";
    }
    function styleNull() {
      this.style.removeProperty(name);
    }
    function styleString(b) {
      return b == null ? styleNull : (b += "", function() {
        var a = d3_window(this).getComputedStyle(this, null).getPropertyValue(name), i;
        return a !== b && (i = d3_interpolate(a, b), function(t) {
          this.style.setProperty(name, i(t), priority);
        });
      });
    }
    return d3_transition_tween(this, "style." + name, value, styleString);
  };
  d3_transitionPrototype.styleTween = function(name, tween, priority) {
    if (arguments.length < 3) priority = "";
    function styleTween(d, i) {
      var f = tween.call(this, d, i, d3_window(this).getComputedStyle(this, null).getPropertyValue(name));
      return f && function(t) {
        this.style.setProperty(name, f(t), priority);
      };
    }
    return this.tween("style." + name, styleTween);
  };
  d3_transitionPrototype.text = function(value) {
    return d3_transition_tween(this, "text", value, d3_transition_text);
  };
  function d3_transition_text(b) {
    if (b == null) b = "";
    return function() {
      this.textContent = b;
    };
  }
  d3_transitionPrototype.remove = function() {
    var ns = this.namespace;
    return this.each("end.transition", function() {
      var p;
      if (this[ns].count < 2 && (p = this.parentNode)) p.removeChild(this);
    });
  };
  d3_transitionPrototype.ease = function(value) {
    var id = this.id, ns = this.namespace;
    if (arguments.length < 1) return this.node()[ns][id].ease;
    if (typeof value !== "function") value = d3.ease.apply(d3, arguments);
    return d3_selection_each(this, function(node) {
      node[ns][id].ease = value;
    });
  };
  d3_transitionPrototype.delay = function(value) {
    var id = this.id, ns = this.namespace;
    if (arguments.length < 1) return this.node()[ns][id].delay;
    return d3_selection_each(this, typeof value === "function" ? function(node, i, j) {
      node[ns][id].delay = +value.call(node, node.__data__, i, j);
    } : (value = +value, function(node) {
      node[ns][id].delay = value;
    }));
  };
  d3_transitionPrototype.duration = function(value) {
    var id = this.id, ns = this.namespace;
    if (arguments.length < 1) return this.node()[ns][id].duration;
    return d3_selection_each(this, typeof value === "function" ? function(node, i, j) {
      node[ns][id].duration = Math.max(1, value.call(node, node.__data__, i, j));
    } : (value = Math.max(1, value), function(node) {
      node[ns][id].duration = value;
    }));
  };
  d3_transitionPrototype.each = function(type, listener) {
    var id = this.id, ns = this.namespace;
    if (arguments.length < 2) {
      var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId;
      try {
        d3_transitionInheritId = id;
        d3_selection_each(this, function(node, i, j) {
          d3_transitionInherit = node[ns][id];
          type.call(node, node.__data__, i, j);
        });
      } finally {
        d3_transitionInherit = inherit;
        d3_transitionInheritId = inheritId;
      }
    } else {
      d3_selection_each(this, function(node) {
        var transition = node[ns][id];
        (transition.event || (transition.event = d3.dispatch("start", "end", "interrupt"))).on(type, listener);
      });
    }
    return this;
  };
  d3_transitionPrototype.transition = function() {
    var id0 = this.id, id1 = ++d3_transitionId, ns = this.namespace, subgroups = [], subgroup, group, node, transition;
    for (var j = 0, m = this.length; j < m; j++) {
      subgroups.push(subgroup = []);
      for (var group = this[j], i = 0, n = group.length; i < n; i++) {
        if (node = group[i]) {
          transition = node[ns][id0];
          d3_transitionNode(node, i, ns, id1, {
            time: transition.time,
            ease: transition.ease,
            delay: transition.delay + transition.duration,
            duration: transition.duration
          });
        }
        subgroup.push(node);
      }
    }
    return d3_transition(subgroups, ns, id1);
  };
  function d3_transitionNamespace(name) {
    return name == null ? "__transition__" : "__transition_" + name + "__";
  }
  function d3_transitionNode(node, i, ns, id, inherit) {
    var lock = node[ns] || (node[ns] = {
      active: 0,
      count: 0
    }), transition = lock[id], time, timer, duration, ease, tweens;
    function schedule(elapsed) {
      var delay = transition.delay;
      timer.t = delay + time;
      if (delay <= elapsed) return start(elapsed - delay);
      timer.c = start;
    }
    function start(elapsed) {
      var activeId = lock.active, active = lock[activeId];
      if (active) {
        active.timer.c = null;
        active.timer.t = NaN;
        --lock.count;
        delete lock[activeId];
        active.event && active.event.interrupt.call(node, node.__data__, active.index);
      }
      for (var cancelId in lock) {
        if (+cancelId < id) {
          var cancel = lock[cancelId];
          cancel.timer.c = null;
          cancel.timer.t = NaN;
          --lock.count;
          delete lock[cancelId];
        }
      }
      timer.c = tick;
      d3_timer(function() {
        if (timer.c && tick(elapsed || 1)) {
          timer.c = null;
          timer.t = NaN;
        }
        return 1;
      }, 0, time);
      lock.active = id;
      transition.event && transition.event.start.call(node, node.__data__, i);
      tweens = [];
      transition.tween.forEach(function(key, value) {
        if (value = value.call(node, node.__data__, i)) {
          tweens.push(value);
        }
      });
      ease = transition.ease;
      duration = transition.duration;
    }
    function tick(elapsed) {
      var t = elapsed / duration, e = ease(t), n = tweens.length;
      while (n > 0) {
        tweens[--n].call(node, e);
      }
      if (t >= 1) {
        transition.event && transition.event.end.call(node, node.__data__, i);
        if (--lock.count) delete lock[id]; else delete node[ns];
        return 1;
      }
    }
    if (!transition) {
      time = inherit.time;
      timer = d3_timer(schedule, 0, time);
      transition = lock[id] = {
        tween: new d3_Map(),
        time: time,
        timer: timer,
        delay: inherit.delay,
        duration: inherit.duration,
        ease: inherit.ease,
        index: i
      };
      inherit = null;
      ++lock.count;
    }
  }
  d3.svg.axis = function() {
    var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_;
    function axis(g) {
      g.each(function() {
        var g = d3.select(this);
        var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy();
        var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d3.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d3.transition(tick.order()).style("opacity", 1), tickSpacing = Math.max(innerTickSize, 0) + tickPadding, tickTransform;
        var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"), 
        d3.transition(path));
        tickEnter.append("line");
        tickEnter.append("text");
        var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"), sign = orient === "top" || orient === "left" ? -1 : 1, x1, x2, y1, y2;
        if (orient === "bottom" || orient === "top") {
          tickTransform = d3_svg_axisX, x1 = "x", y1 = "y", x2 = "x2", y2 = "y2";
          text.attr("dy", sign < 0 ? "0em" : ".71em").style("text-anchor", "middle");
          pathUpdate.attr("d", "M" + range[0] + "," + sign * outerTickSize + "V0H" + range[1] + "V" + sign * outerTickSize);
        } else {
          tickTransform = d3_svg_axisY, x1 = "y", y1 = "x", x2 = "y2", y2 = "x2";
          text.attr("dy", ".32em").style("text-anchor", sign < 0 ? "end" : "start");
          pathUpdate.attr("d", "M" + sign * outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + sign * outerTickSize);
        }
        lineEnter.attr(y2, sign * innerTickSize);
        textEnter.attr(y1, sign * tickSpacing);
        lineUpdate.attr(x2, 0).attr(y2, sign * innerTickSize);
        textUpdate.attr(x1, 0).attr(y1, sign * tickSpacing);
        if (scale1.rangeBand) {
          var x = scale1, dx = x.rangeBand() / 2;
          scale0 = scale1 = function(d) {
            return x(d) + dx;
          };
        } else if (scale0.rangeBand) {
          scale0 = scale1;
        } else {
          tickExit.call(tickTransform, scale1, scale0);
        }
        tickEnter.call(tickTransform, scale0, scale1);
        tickUpdate.call(tickTransform, scale1, scale1);
      });
    }
    axis.scale = function(x) {
      if (!arguments.length) return scale;
      scale = x;
      return axis;
    };
    axis.orient = function(x) {
      if (!arguments.length) return orient;
      orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient;
      return axis;
    };
    axis.ticks = function() {
      if (!arguments.length) return tickArguments_;
      tickArguments_ = d3_array(arguments);
      return axis;
    };
    axis.tickValues = function(x) {
      if (!arguments.length) return tickValues;
      tickValues = x;
      return axis;
    };
    axis.tickFormat = function(x) {
      if (!arguments.length) return tickFormat_;
      tickFormat_ = x;
      return axis;
    };
    axis.tickSize = function(x) {
      var n = arguments.length;
      if (!n) return innerTickSize;
      innerTickSize = +x;
      outerTickSize = +arguments[n - 1];
      return axis;
    };
    axis.innerTickSize = function(x) {
      if (!arguments.length) return innerTickSize;
      innerTickSize = +x;
      return axis;
    };
    axis.outerTickSize = function(x) {
      if (!arguments.length) return outerTickSize;
      outerTickSize = +x;
      return axis;
    };
    axis.tickPadding = function(x) {
      if (!arguments.length) return tickPadding;
      tickPadding = +x;
      return axis;
    };
    axis.tickSubdivide = function() {
      return arguments.length && axis;
    };
    return axis;
  };
  var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = {
    top: 1,
    right: 1,
    bottom: 1,
    left: 1
  };
  function d3_svg_axisX(selection, x0, x1) {
    selection.attr("transform", function(d) {
      var v0 = x0(d);
      return "translate(" + (isFinite(v0) ? v0 : x1(d)) + ",0)";
    });
  }
  function d3_svg_axisY(selection, y0, y1) {
    selection.attr("transform", function(d) {
      var v0 = y0(d);
      return "translate(0," + (isFinite(v0) ? v0 : y1(d)) + ")";
    });
  }
  d3.svg.brush = function() {
    var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [ 0, 0 ], yExtent = [ 0, 0 ], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0];
    function brush(g) {
      g.each(function() {
        var g = d3.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart);
        var background = g.selectAll(".background").data([ 0 ]);
        background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair");
        g.selectAll(".extent").data([ 0 ]).enter().append("rect").attr("class", "extent").style("cursor", "move");
        var resize = g.selectAll(".resize").data(resizes, d3_identity);
        resize.exit().remove();
        resize.enter().append("g").attr("class", function(d) {
          return "resize " + d;
        }).style("cursor", function(d) {
          return d3_svg_brushCursor[d];
        }).append("rect").attr("x", function(d) {
          return /[ew]$/.test(d) ? -3 : null;
        }).attr("y", function(d) {
          return /^[ns]/.test(d) ? -3 : null;
        }).attr("width", 6).attr("height", 6).style("visibility", "hidden");
        resize.style("display", brush.empty() ? "none" : null);
        var gUpdate = d3.transition(g), backgroundUpdate = d3.transition(background), range;
        if (x) {
          range = d3_scaleRange(x);
          backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]);
          redrawX(gUpdate);
        }
        if (y) {
          range = d3_scaleRange(y);
          backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]);
          redrawY(gUpdate);
        }
        redraw(gUpdate);
      });
    }
    brush.event = function(g) {
      g.each(function() {
        var event_ = event.of(this, arguments), extent1 = {
          x: xExtent,
          y: yExtent,
          i: xExtentDomain,
          j: yExtentDomain
        }, extent0 = this.__chart__ || extent1;
        this.__chart__ = extent1;
        if (d3_transitionInheritId) {
          d3.select(this).transition().each("start.brush", function() {
            xExtentDomain = extent0.i;
            yExtentDomain = extent0.j;
            xExtent = extent0.x;
            yExtent = extent0.y;
            event_({
              type: "brushstart"
            });
          }).tween("brush:brush", function() {
            var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y);
            xExtentDomain = yExtentDomain = null;
            return function(t) {
              xExtent = extent1.x = xi(t);
              yExtent = extent1.y = yi(t);
              event_({
                type: "brush",
                mode: "resize"
              });
            };
          }).each("end.brush", function() {
            xExtentDomain = extent1.i;
            yExtentDomain = extent1.j;
            event_({
              type: "brush",
              mode: "resize"
            });
            event_({
              type: "brushend"
            });
          });
        } else {
          event_({
            type: "brushstart"
          });
          event_({
            type: "brush",
            mode: "resize"
          });
          event_({
            type: "brushend"
          });
        }
      });
    };
    function redraw(g) {
      g.selectAll(".resize").attr("transform", function(d) {
        return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")";
      });
    }
    function redrawX(g) {
      g.select(".extent").attr("x", xExtent[0]);
      g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]);
    }
    function redrawY(g) {
      g.select(".extent").attr("y", yExtent[0]);
      g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]);
    }
    function brushstart() {
      var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(target), center, origin = d3.mouse(target), offset;
      var w = d3.select(d3_window(target)).on("keydown.brush", keydown).on("keyup.brush", keyup);
      if (d3.event.changedTouches) {
        w.on("touchmove.brush", brushmove).on("touchend.brush", brushend);
      } else {
        w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend);
      }
      g.interrupt().selectAll("*").interrupt();
      if (dragging) {
        origin[0] = xExtent[0] - origin[0];
        origin[1] = yExtent[0] - origin[1];
      } else if (resizing) {
        var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing);
        offset = [ xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1] ];
        origin[0] = xExtent[ex];
        origin[1] = yExtent[ey];
      } else if (d3.event.altKey) center = origin.slice();
      g.style("pointer-events", "none").selectAll(".resize").style("display", null);
      d3.select("body").style("cursor", eventTarget.style("cursor"));
      event_({
        type: "brushstart"
      });
      brushmove();
      function keydown() {
        if (d3.event.keyCode == 32) {
          if (!dragging) {
            center = null;
            origin[0] -= xExtent[1];
            origin[1] -= yExtent[1];
            dragging = 2;
          }
          d3_eventPreventDefault();
        }
      }
      function keyup() {
        if (d3.event.keyCode == 32 && dragging == 2) {
          origin[0] += xExtent[1];
          origin[1] += yExtent[1];
          dragging = 0;
          d3_eventPreventDefault();
        }
      }
      function brushmove() {
        var point = d3.mouse(target), moved = false;
        if (offset) {
          point[0] += offset[0];
          point[1] += offset[1];
        }
        if (!dragging) {
          if (d3.event.altKey) {
            if (!center) center = [ (xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2 ];
            origin[0] = xExtent[+(point[0] < center[0])];
            origin[1] = yExtent[+(point[1] < center[1])];
          } else center = null;
        }
        if (resizingX && move1(point, x, 0)) {
          redrawX(g);
          moved = true;
        }
        if (resizingY && move1(point, y, 1)) {
          redrawY(g);
          moved = true;
        }
        if (moved) {
          redraw(g);
          event_({
            type: "brush",
            mode: dragging ? "move" : "resize"
          });
        }
      }
      function move1(point, scale, i) {
        var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], extent = i ? yExtent : xExtent, size = extent[1] - extent[0], min, max;
        if (dragging) {
          r0 -= position;
          r1 -= size + position;
        }
        min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i];
        if (dragging) {
          max = (min += position) + size;
        } else {
          if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min));
          if (position < min) {
            max = min;
            min = position;
          } else {
            max = position;
          }
        }
        if (extent[0] != min || extent[1] != max) {
          if (i) yExtentDomain = null; else xExtentDomain = null;
          extent[0] = min;
          extent[1] = max;
          return true;
        }
      }
      function brushend() {
        brushmove();
        g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null);
        d3.select("body").style("cursor", null);
        w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null);
        dragRestore();
        event_({
          type: "brushend"
        });
      }
    }
    brush.x = function(z) {
      if (!arguments.length) return x;
      x = z;
      resizes = d3_svg_brushResizes[!x << 1 | !y];
      return brush;
    };
    brush.y = function(z) {
      if (!arguments.length) return y;
      y = z;
      resizes = d3_svg_brushResizes[!x << 1 | !y];
      return brush;
    };
    brush.clamp = function(z) {
      if (!arguments.length) return x && y ? [ xClamp, yClamp ] : x ? xClamp : y ? yClamp : null;
      if (x && y) xClamp = !!z[0], yClamp = !!z[1]; else if (x) xClamp = !!z; else if (y) yClamp = !!z;
      return brush;
    };
    brush.extent = function(z) {
      var x0, x1, y0, y1, t;
      if (!arguments.length) {
        if (x) {
          if (xExtentDomain) {
            x0 = xExtentDomain[0], x1 = xExtentDomain[1];
          } else {
            x0 = xExtent[0], x1 = xExtent[1];
            if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1);
            if (x1 < x0) t = x0, x0 = x1, x1 = t;
          }
        }
        if (y) {
          if (yExtentDomain) {
            y0 = yExtentDomain[0], y1 = yExtentDomain[1];
          } else {
            y0 = yExtent[0], y1 = yExtent[1];
            if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1);
            if (y1 < y0) t = y0, y0 = y1, y1 = t;
          }
        }
        return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ];
      }
      if (x) {
        x0 = z[0], x1 = z[1];
        if (y) x0 = x0[0], x1 = x1[0];
        xExtentDomain = [ x0, x1 ];
        if (x.invert) x0 = x(x0), x1 = x(x1);
        if (x1 < x0) t = x0, x0 = x1, x1 = t;
        if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [ x0, x1 ];
      }
      if (y) {
        y0 = z[0], y1 = z[1];
        if (x) y0 = y0[1], y1 = y1[1];
        yExtentDomain = [ y0, y1 ];
        if (y.invert) y0 = y(y0), y1 = y(y1);
        if (y1 < y0) t = y0, y0 = y1, y1 = t;
        if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [ y0, y1 ];
      }
      return brush;
    };
    brush.clear = function() {
      if (!brush.empty()) {
        xExtent = [ 0, 0 ], yExtent = [ 0, 0 ];
        xExtentDomain = yExtentDomain = null;
      }
      return brush;
    };
    brush.empty = function() {
      return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1];
    };
    return d3.rebind(brush, event, "on");
  };
  var d3_svg_brushCursor = {
    n: "ns-resize",
    e: "ew-resize",
    s: "ns-resize",
    w: "ew-resize",
    nw: "nwse-resize",
    ne: "nesw-resize",
    se: "nwse-resize",
    sw: "nesw-resize"
  };
  var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ];
  var d3_time_format = d3_time.format = d3_locale_enUS.timeFormat;
  var d3_time_formatUtc = d3_time_format.utc;
  var d3_time_formatIso = d3_time_formatUtc("%Y-%m-%dT%H:%M:%S.%LZ");
  d3_time_format.iso = Date.prototype.toISOString && +new Date("2000-01-01T00:00:00.000Z") ? d3_time_formatIsoNative : d3_time_formatIso;
  function d3_time_formatIsoNative(date) {
    return date.toISOString();
  }
  d3_time_formatIsoNative.parse = function(string) {
    var date = new Date(string);
    return isNaN(date) ? null : date;
  };
  d3_time_formatIsoNative.toString = d3_time_formatIso.toString;
  d3_time.second = d3_time_interval(function(date) {
    return new d3_date(Math.floor(date / 1e3) * 1e3);
  }, function(date, offset) {
    date.setTime(date.getTime() + Math.floor(offset) * 1e3);
  }, function(date) {
    return date.getSeconds();
  });
  d3_time.seconds = d3_time.second.range;
  d3_time.seconds.utc = d3_time.second.utc.range;
  d3_time.minute = d3_time_interval(function(date) {
    return new d3_date(Math.floor(date / 6e4) * 6e4);
  }, function(date, offset) {
    date.setTime(date.getTime() + Math.floor(offset) * 6e4);
  }, function(date) {
    return date.getMinutes();
  });
  d3_time.minutes = d3_time.minute.range;
  d3_time.minutes.utc = d3_time.minute.utc.range;
  d3_time.hour = d3_time_interval(function(date) {
    var timezone = date.getTimezoneOffset() / 60;
    return new d3_date((Math.floor(date / 36e5 - timezone) + timezone) * 36e5);
  }, function(date, offset) {
    date.setTime(date.getTime() + Math.floor(offset) * 36e5);
  }, function(date) {
    return date.getHours();
  });
  d3_time.hours = d3_time.hour.range;
  d3_time.hours.utc = d3_time.hour.utc.range;
  d3_time.month = d3_time_interval(function(date) {
    date = d3_time.day(date);
    date.setDate(1);
    return date;
  }, function(date, offset) {
    date.setMonth(date.getMonth() + offset);
  }, function(date) {
    return date.getMonth();
  });
  d3_time.months = d3_time.month.range;
  d3_time.months.utc = d3_time.month.utc.range;
  function d3_time_scale(linear, methods, format) {
    function scale(x) {
      return linear(x);
    }
    scale.invert = function(x) {
      return d3_time_scaleDate(linear.invert(x));
    };
    scale.domain = function(x) {
      if (!arguments.length) return linear.domain().map(d3_time_scaleDate);
      linear.domain(x);
      return scale;
    };
    function tickMethod(extent, count) {
      var span = extent[1] - extent[0], target = span / count, i = d3.bisect(d3_time_scaleSteps, target);
      return i == d3_time_scaleSteps.length ? [ methods.year, d3_scale_linearTickRange(extent.map(function(d) {
        return d / 31536e6;
      }), count)[2] ] : !i ? [ d3_time_scaleMilliseconds, d3_scale_linearTickRange(extent, count)[2] ] : methods[target / d3_time_scaleSteps[i - 1] < d3_time_scaleSteps[i] / target ? i - 1 : i];
    }
    scale.nice = function(interval, skip) {
      var domain = scale.domain(), extent = d3_scaleExtent(domain), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" && tickMethod(extent, interval);
      if (method) interval = method[0], skip = method[1];
      function skipped(date) {
        return !isNaN(date) && !interval.range(date, d3_time_scaleDate(+date + 1), skip).length;
      }
      return scale.domain(d3_scale_nice(domain, skip > 1 ? {
        floor: function(date) {
          while (skipped(date = interval.floor(date))) date = d3_time_scaleDate(date - 1);
          return date;
        },
        ceil: function(date) {
          while (skipped(date = interval.ceil(date))) date = d3_time_scaleDate(+date + 1);
          return date;
        }
      } : interval));
    };
    scale.ticks = function(interval, skip) {
      var extent = d3_scaleExtent(scale.domain()), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" ? tickMethod(extent, interval) : !interval.range && [ {
        range: interval
      }, skip ];
      if (method) interval = method[0], skip = method[1];
      return interval.range(extent[0], d3_time_scaleDate(+extent[1] + 1), skip < 1 ? 1 : skip);
    };
    scale.tickFormat = function() {
      return format;
    };
    scale.copy = function() {
      return d3_time_scale(linear.copy(), methods, format);
    };
    return d3_scale_linearRebind(scale, linear);
  }
  function d3_time_scaleDate(t) {
    return new Date(t);
  }
  var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ];
  var d3_time_scaleLocalMethods = [ [ d3_time.second, 1 ], [ d3_time.second, 5 ], [ d3_time.second, 15 ], [ d3_time.second, 30 ], [ d3_time.minute, 1 ], [ d3_time.minute, 5 ], [ d3_time.minute, 15 ], [ d3_time.minute, 30 ], [ d3_time.hour, 1 ], [ d3_time.hour, 3 ], [ d3_time.hour, 6 ], [ d3_time.hour, 12 ], [ d3_time.day, 1 ], [ d3_time.day, 2 ], [ d3_time.week, 1 ], [ d3_time.month, 1 ], [ d3_time.month, 3 ], [ d3_time.year, 1 ] ];
  var d3_time_scaleLocalFormat = d3_time_format.multi([ [ ".%L", function(d) {
    return d.getMilliseconds();
  } ], [ ":%S", function(d) {
    return d.getSeconds();
  } ], [ "%I:%M", function(d) {
    return d.getMinutes();
  } ], [ "%I %p", function(d) {
    return d.getHours();
  } ], [ "%a %d", function(d) {
    return d.getDay() && d.getDate() != 1;
  } ], [ "%b %d", function(d) {
    return d.getDate() != 1;
  } ], [ "%B", function(d) {
    return d.getMonth();
  } ], [ "%Y", d3_true ] ]);
  var d3_time_scaleMilliseconds = {
    range: function(start, stop, step) {
      return d3.range(Math.ceil(start / step) * step, +stop, step).map(d3_time_scaleDate);
    },
    floor: d3_identity,
    ceil: d3_identity
  };
  d3_time_scaleLocalMethods.year = d3_time.year;
  d3_time.scale = function() {
    return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat);
  };
  var d3_time_scaleUtcMethods = d3_time_scaleLocalMethods.map(function(m) {
    return [ m[0].utc, m[1] ];
  });
  var d3_time_scaleUtcFormat = d3_time_formatUtc.multi([ [ ".%L", function(d) {
    return d.getUTCMilliseconds();
  } ], [ ":%S", function(d) {
    return d.getUTCSeconds();
  } ], [ "%I:%M", function(d) {
    return d.getUTCMinutes();
  } ], [ "%I %p", function(d) {
    return d.getUTCHours();
  } ], [ "%a %d", function(d) {
    return d.getUTCDay() && d.getUTCDate() != 1;
  } ], [ "%b %d", function(d) {
    return d.getUTCDate() != 1;
  } ], [ "%B", function(d) {
    return d.getUTCMonth();
  } ], [ "%Y", d3_true ] ]);
  d3_time_scaleUtcMethods.year = d3_time.year.utc;
  d3_time.scale.utc = function() {
    return d3_time_scale(d3.scale.linear(), d3_time_scaleUtcMethods, d3_time_scaleUtcFormat);
  };
  d3.text = d3_xhrType(function(request) {
    return request.responseText;
  });
  d3.json = function(url, callback) {
    return d3_xhr(url, "application/json", d3_json, callback);
  };
  function d3_json(request) {
    return JSON.parse(request.responseText);
  }
  d3.html = function(url, callback) {
    return d3_xhr(url, "text/html", d3_html, callback);
  };
  function d3_html(request) {
    var range = d3_document.createRange();
    range.selectNode(d3_document.body);
    return range.createContextualFragment(request.responseText);
  }
  d3.xml = d3_xhrType(function(request) {
    return request.responseXML;
  });
  if (typeof define === "function" && define.amd) this.d3 = d3, define(d3); else if (typeof module === "object" && module.exports) module.exports = d3; else this.d3 = d3;
}();
},{}],150:[function(_dereq_,module,exports){
module.exports = function () {
    for (var i = 0; i < arguments.length; i++) {
        if (arguments[i] !== undefined) return arguments[i];
    }
};

},{}],151:[function(_dereq_,module,exports){
"use strict"

var ch = _dereq_("incremental-convex-hull")
var uniq = _dereq_("uniq")

module.exports = triangulate

function LiftedPoint(p, i) {
  this.point = p
  this.index = i
}

function compareLifted(a, b) {
  var ap = a.point
  var bp = b.point
  var d = ap.length
  for(var i=0; i<d; ++i) {
    var s = bp[i] - ap[i]
    if(s) {
      return s
    }
  }
  return 0
}

function triangulate1D(n, points, includePointAtInfinity) {
  if(n === 1) {
    if(includePointAtInfinity) {
      return [ [-1, 0] ]
    } else {
      return []
    }
  }
  var lifted = points.map(function(p, i) {
    return [ p[0], i ]
  })
  lifted.sort(function(a,b) {
    return a[0] - b[0]
  })
  var cells = new Array(n - 1)
  for(var i=1; i<n; ++i) {
    var a = lifted[i-1]
    var b = lifted[i]
    cells[i-1] = [ a[1], b[1] ]
  }
  if(includePointAtInfinity) {
    cells.push(
      [ -1, cells[0][1], ],
      [ cells[n-1][1], -1 ])
  }
  return cells
}

function triangulate(points, includePointAtInfinity) {
  var n = points.length
  if(n === 0) {
    return []
  }
  
  var d = points[0].length
  if(d < 1) {
    return []
  }

  //Special case:  For 1D we can just sort the points
  if(d === 1) {
    return triangulate1D(n, points, includePointAtInfinity)
  }
  
  //Lift points, sort
  var lifted = new Array(n)
  var upper = 1.0
  for(var i=0; i<n; ++i) {
    var p = points[i]
    var x = new Array(d+1)
    var l = 0.0
    for(var j=0; j<d; ++j) {
      var v = p[j]
      x[j] = v
      l += v * v
    }
    x[d] = l
    lifted[i] = new LiftedPoint(x, i)
    upper = Math.max(l, upper)
  }
  uniq(lifted, compareLifted)
  
  //Double points
  n = lifted.length

  //Create new list of points
  var dpoints = new Array(n + d + 1)
  var dindex = new Array(n + d + 1)

  //Add steiner points at top
  var u = (d+1) * (d+1) * upper
  var y = new Array(d+1)
  for(var i=0; i<=d; ++i) {
    y[i] = 0.0
  }
  y[d] = u

  dpoints[0] = y.slice()
  dindex[0] = -1

  for(var i=0; i<=d; ++i) {
    var x = y.slice()
    x[i] = 1
    dpoints[i+1] = x
    dindex[i+1] = -1
  }

  //Copy rest of the points over
  for(var i=0; i<n; ++i) {
    var h = lifted[i]
    dpoints[i + d + 1] = h.point
    dindex[i + d + 1] =  h.index
  }

  //Construct convex hull
  var hull = ch(dpoints, false)
  if(includePointAtInfinity) {
    hull = hull.filter(function(cell) {
      var count = 0
      for(var j=0; j<=d; ++j) {
        var v = dindex[cell[j]]
        if(v < 0) {
          if(++count >= 2) {
            return false
          }
        }
        cell[j] = v
      }
      return true
    })
  } else {
    hull = hull.filter(function(cell) {
      for(var i=0; i<=d; ++i) {
        var v = dindex[cell[i]]
        if(v < 0) {
          return false
        }
        cell[i] = v
      }
      return true
    })
  }

  if(d & 1) {
    for(var i=0; i<hull.length; ++i) {
      var h = hull[i]
      var x = h[0]
      h[0] = h[1]
      h[1] = x
    }
  }

  return hull
}
},{"incremental-convex-hull":399,"uniq":525}],152:[function(_dereq_,module,exports){
'use strict'


module.exports = kerning


var canvas = kerning.canvas = document.createElement('canvas')
var ctx = canvas.getContext('2d')
var asciiPairs = createPairs([32, 126])

kerning.createPairs = createPairs
kerning.ascii = asciiPairs


function kerning (family, o) {
	if (Array.isArray(family)) family = family.join(', ')

	var table = {}, pairs, fs = 16, threshold = .05

	if (o) {
		if (o.length === 2 && typeof o[0] === 'number') {
			pairs = createPairs(o)
		}
		else if (Array.isArray(o)) {
			pairs = o
		}
		else {
			if (o.o) pairs = createPairs(o.o)
			else if (o.pairs) pairs = o.pairs

			if (o.fontSize) fs = o.fontSize
			if (o.threshold != null) threshold = o.threshold
		}
	}

	if (!pairs) pairs = asciiPairs

	ctx.font = fs + 'px ' + family

	for (var i = 0; i < pairs.length; i++) {
		var pair = pairs[i]
		var width = ctx.measureText(pair[0]).width + ctx.measureText(pair[1]).width
		var kerningWidth = ctx.measureText(pair).width
		if (Math.abs(width - kerningWidth) > fs * threshold) {
			var emWidth = (kerningWidth - width) / fs
			table[pair] = emWidth * 1000
		}
	}

	return table
}


function createPairs (range) {
	var pairs = []

    for (var i = range[0]; i <= range[1]; i++) {
		var leftChar = String.fromCharCode(i)
		for (var j = range[0]; j < range[1]; j++) {
			var rightChar = String.fromCharCode(j)
			var pair = leftChar + rightChar

			pairs.push(pair)
		}
	}

	return pairs
}

},{}],153:[function(_dereq_,module,exports){
(function (Buffer){
var hasTypedArrays = false
if(typeof Float64Array !== "undefined") {
  var DOUBLE_VIEW = new Float64Array(1)
    , UINT_VIEW   = new Uint32Array(DOUBLE_VIEW.buffer)
  DOUBLE_VIEW[0] = 1.0
  hasTypedArrays = true
  if(UINT_VIEW[1] === 0x3ff00000) {
    //Use little endian
    module.exports = function doubleBitsLE(n) {
      DOUBLE_VIEW[0] = n
      return [ UINT_VIEW[0], UINT_VIEW[1] ]
    }
    function toDoubleLE(lo, hi) {
      UINT_VIEW[0] = lo
      UINT_VIEW[1] = hi
      return DOUBLE_VIEW[0]
    }
    module.exports.pack = toDoubleLE
    function lowUintLE(n) {
      DOUBLE_VIEW[0] = n
      return UINT_VIEW[0]
    }
    module.exports.lo = lowUintLE
    function highUintLE(n) {
      DOUBLE_VIEW[0] = n
      return UINT_VIEW[1]
    }
    module.exports.hi = highUintLE
  } else if(UINT_VIEW[0] === 0x3ff00000) {
    //Use big endian
    module.exports = function doubleBitsBE(n) {
      DOUBLE_VIEW[0] = n
      return [ UINT_VIEW[1], UINT_VIEW[0] ]
    }
    function toDoubleBE(lo, hi) {
      UINT_VIEW[1] = lo
      UINT_VIEW[0] = hi
      return DOUBLE_VIEW[0]
    }
    module.exports.pack = toDoubleBE
    function lowUintBE(n) {
      DOUBLE_VIEW[0] = n
      return UINT_VIEW[1]
    }
    module.exports.lo = lowUintBE
    function highUintBE(n) {
      DOUBLE_VIEW[0] = n
      return UINT_VIEW[0]
    }
    module.exports.hi = highUintBE
  } else {
    hasTypedArrays = false
  }
}
if(!hasTypedArrays) {
  var buffer = new Buffer(8)
  module.exports = function doubleBits(n) {
    buffer.writeDoubleLE(n, 0, true)
    return [ buffer.readUInt32LE(0, true), buffer.readUInt32LE(4, true) ]
  }
  function toDouble(lo, hi) {
    buffer.writeUInt32LE(lo, 0, true)
    buffer.writeUInt32LE(hi, 4, true)
    return buffer.readDoubleLE(0, true)
  }
  module.exports.pack = toDouble  
  function lowUint(n) {
    buffer.writeDoubleLE(n, 0, true)
    return buffer.readUInt32LE(0, true)
  }
  module.exports.lo = lowUint
  function highUint(n) {
    buffer.writeDoubleLE(n, 0, true)
    return buffer.readUInt32LE(4, true)
  }
  module.exports.hi = highUint
}

module.exports.sign = function(n) {
  return module.exports.hi(n) >>> 31
}

module.exports.exponent = function(n) {
  var b = module.exports.hi(n)
  return ((b<<1) >>> 21) - 1023
}

module.exports.fraction = function(n) {
  var lo = module.exports.lo(n)
  var hi = module.exports.hi(n)
  var b = hi & ((1<<20) - 1)
  if(hi & 0x7ff00000) {
    b += (1<<20)
  }
  return [lo, b]
}

module.exports.denormalized = function(n) {
  var hi = module.exports.hi(n)
  return !(hi & 0x7ff00000)
}
}).call(this,_dereq_("buffer").Buffer)
},{"buffer":94}],154:[function(_dereq_,module,exports){
var abs = _dereq_('abs-svg-path')
var normalize = _dereq_('normalize-svg-path')

var methods = {
  'M': 'moveTo',
  'C': 'bezierCurveTo'
}

module.exports = function(context, segments) {
  context.beginPath()

  // Make path easy to reproduce.
  normalize(abs(segments)).forEach(
    function(segment) {
      var command = segment[0]
      var args = segment.slice(1)

      // Convert the path command to a context method.
      context[methods[command]].apply(context, args)
    }
  )

  context.closePath()
}

},{"abs-svg-path":49,"normalize-svg-path":438}],155:[function(_dereq_,module,exports){
module.exports = function(dtype) {
  switch (dtype) {
    case 'int8':
      return Int8Array
    case 'int16':
      return Int16Array
    case 'int32':
      return Int32Array
    case 'uint8':
      return Uint8Array
    case 'uint16':
      return Uint16Array
    case 'uint32':
      return Uint32Array
    case 'float32':
      return Float32Array
    case 'float64':
      return Float64Array
    case 'array':
      return Array
    case 'uint8_clamped':
      return Uint8ClampedArray
  }
}

},{}],156:[function(_dereq_,module,exports){
"use strict"

function dupe_array(count, value, i) {
  var c = count[i]|0
  if(c <= 0) {
    return []
  }
  var result = new Array(c), j
  if(i === count.length-1) {
    for(j=0; j<c; ++j) {
      result[j] = value
    }
  } else {
    for(j=0; j<c; ++j) {
      result[j] = dupe_array(count, value, i+1)
    }
  }
  return result
}

function dupe_number(count, value) {
  var result, i
  result = new Array(count)
  for(i=0; i<count; ++i) {
    result[i] = value
  }
  return result
}

function dupe(count, value) {
  if(typeof value === "undefined") {
    value = 0
  }
  switch(typeof count) {
    case "number":
      if(count > 0) {
        return dupe_number(count|0, value)
      }
    break
    case "object":
      if(typeof (count.length) === "number") {
        return dupe_array(count, value, 0)
      }
    break
  }
  return []
}

module.exports = dupe
},{}],157:[function(_dereq_,module,exports){
'use strict';

module.exports = earcut;
module.exports.default = earcut;

function earcut(data, holeIndices, dim) {

    dim = dim || 2;

    var hasHoles = holeIndices && holeIndices.length,
        outerLen = hasHoles ? holeIndices[0] * dim : data.length,
        outerNode = linkedList(data, 0, outerLen, dim, true),
        triangles = [];

    if (!outerNode) return triangles;

    var minX, minY, maxX, maxY, x, y, invSize;

    if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);

    // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
    if (data.length > 80 * dim) {
        minX = maxX = data[0];
        minY = maxY = data[1];

        for (var i = dim; i < outerLen; i += dim) {
            x = data[i];
            y = data[i + 1];
            if (x < minX) minX = x;
            if (y < minY) minY = y;
            if (x > maxX) maxX = x;
            if (y > maxY) maxY = y;
        }

        // minX, minY and invSize are later used to transform coords into integers for z-order calculation
        invSize = Math.max(maxX - minX, maxY - minY);
        invSize = invSize !== 0 ? 1 / invSize : 0;
    }

    earcutLinked(outerNode, triangles, dim, minX, minY, invSize);

    return triangles;
}

// create a circular doubly linked list from polygon points in the specified winding order
function linkedList(data, start, end, dim, clockwise) {
    var i, last;

    if (clockwise === (signedArea(data, start, end, dim) > 0)) {
        for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
    } else {
        for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
    }

    if (last && equals(last, last.next)) {
        removeNode(last);
        last = last.next;
    }

    return last;
}

// eliminate colinear or duplicate points
function filterPoints(start, end) {
    if (!start) return start;
    if (!end) end = start;

    var p = start,
        again;
    do {
        again = false;

        if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
            removeNode(p);
            p = end = p.prev;
            if (p === p.next) break;
            again = true;

        } else {
            p = p.next;
        }
    } while (again || p !== end);

    return end;
}

// main ear slicing loop which triangulates a polygon (given as a linked list)
function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
    if (!ear) return;

    // interlink polygon nodes in z-order
    if (!pass && invSize) indexCurve(ear, minX, minY, invSize);

    var stop = ear,
        prev, next;

    // iterate through ears, slicing them one by one
    while (ear.prev !== ear.next) {
        prev = ear.prev;
        next = ear.next;

        if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
            // cut off the triangle
            triangles.push(prev.i / dim);
            triangles.push(ear.i / dim);
            triangles.push(next.i / dim);

            removeNode(ear);

            // skipping the next vertice leads to less sliver triangles
            ear = next.next;
            stop = next.next;

            continue;
        }

        ear = next;

        // if we looped through the whole remaining polygon and can't find any more ears
        if (ear === stop) {
            // try filtering points and slicing again
            if (!pass) {
                earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);

            // if this didn't work, try curing all small self-intersections locally
            } else if (pass === 1) {
                ear = cureLocalIntersections(ear, triangles, dim);
                earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);

            // as a last resort, try splitting the remaining polygon into two
            } else if (pass === 2) {
                splitEarcut(ear, triangles, dim, minX, minY, invSize);
            }

            break;
        }
    }
}

// check whether a polygon node forms a valid ear with adjacent nodes
function isEar(ear) {
    var a = ear.prev,
        b = ear,
        c = ear.next;

    if (area(a, b, c) >= 0) return false; // reflex, can't be an ear

    // now make sure we don't have other points inside the potential ear
    var p = ear.next.next;

    while (p !== ear.prev) {
        if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
            area(p.prev, p, p.next) >= 0) return false;
        p = p.next;
    }

    return true;
}

function isEarHashed(ear, minX, minY, invSize) {
    var a = ear.prev,
        b = ear,
        c = ear.next;

    if (area(a, b, c) >= 0) return false; // reflex, can't be an ear

    // triangle bbox; min & max are calculated like this for speed
    var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
        minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
        maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
        maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);

    // z-order range for the current triangle bbox;
    var minZ = zOrder(minTX, minTY, minX, minY, invSize),
        maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);

    var p = ear.prevZ,
        n = ear.nextZ;

    // look for points inside the triangle in both directions
    while (p && p.z >= minZ && n && n.z <= maxZ) {
        if (p !== ear.prev && p !== ear.next &&
            pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
            area(p.prev, p, p.next) >= 0) return false;
        p = p.prevZ;

        if (n !== ear.prev && n !== ear.next &&
            pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) &&
            area(n.prev, n, n.next) >= 0) return false;
        n = n.nextZ;
    }

    // look for remaining points in decreasing z-order
    while (p && p.z >= minZ) {
        if (p !== ear.prev && p !== ear.next &&
            pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
            area(p.prev, p, p.next) >= 0) return false;
        p = p.prevZ;
    }

    // look for remaining points in increasing z-order
    while (n && n.z <= maxZ) {
        if (n !== ear.prev && n !== ear.next &&
            pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) &&
            area(n.prev, n, n.next) >= 0) return false;
        n = n.nextZ;
    }

    return true;
}

// go through all polygon nodes and cure small local self-intersections
function cureLocalIntersections(start, triangles, dim) {
    var p = start;
    do {
        var a = p.prev,
            b = p.next.next;

        if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {

            triangles.push(a.i / dim);
            triangles.push(p.i / dim);
            triangles.push(b.i / dim);

            // remove two nodes involved
            removeNode(p);
            removeNode(p.next);

            p = start = b;
        }
        p = p.next;
    } while (p !== start);

    return p;
}

// try splitting polygon into two and triangulate them independently
function splitEarcut(start, triangles, dim, minX, minY, invSize) {
    // look for a valid diagonal that divides the polygon into two
    var a = start;
    do {
        var b = a.next.next;
        while (b !== a.prev) {
            if (a.i !== b.i && isValidDiagonal(a, b)) {
                // split the polygon in two by the diagonal
                var c = splitPolygon(a, b);

                // filter colinear points around the cuts
                a = filterPoints(a, a.next);
                c = filterPoints(c, c.next);

                // run earcut on each half
                earcutLinked(a, triangles, dim, minX, minY, invSize);
                earcutLinked(c, triangles, dim, minX, minY, invSize);
                return;
            }
            b = b.next;
        }
        a = a.next;
    } while (a !== start);
}

// link every hole into the outer loop, producing a single-ring polygon without holes
function eliminateHoles(data, holeIndices, outerNode, dim) {
    var queue = [],
        i, len, start, end, list;

    for (i = 0, len = holeIndices.length; i < len; i++) {
        start = holeIndices[i] * dim;
        end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
        list = linkedList(data, start, end, dim, false);
        if (list === list.next) list.steiner = true;
        queue.push(getLeftmost(list));
    }

    queue.sort(compareX);

    // process holes from left to right
    for (i = 0; i < queue.length; i++) {
        eliminateHole(queue[i], outerNode);
        outerNode = filterPoints(outerNode, outerNode.next);
    }

    return outerNode;
}

function compareX(a, b) {
    return a.x - b.x;
}

// find a bridge between vertices that connects hole with an outer ring and and link it
function eliminateHole(hole, outerNode) {
    outerNode = findHoleBridge(hole, outerNode);
    if (outerNode) {
        var b = splitPolygon(outerNode, hole);
        filterPoints(b, b.next);
    }
}

// David Eberly's algorithm for finding a bridge between hole and outer polygon
function findHoleBridge(hole, outerNode) {
    var p = outerNode,
        hx = hole.x,
        hy = hole.y,
        qx = -Infinity,
        m;

    // find a segment intersected by a ray from the hole's leftmost point to the left;
    // segment's endpoint with lesser x will be potential connection point
    do {
        if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
            var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
            if (x <= hx && x > qx) {
                qx = x;
                if (x === hx) {
                    if (hy === p.y) return p;
                    if (hy === p.next.y) return p.next;
                }
                m = p.x < p.next.x ? p : p.next;
            }
        }
        p = p.next;
    } while (p !== outerNode);

    if (!m) return null;

    if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint

    // look for points inside the triangle of hole point, segment intersection and endpoint;
    // if there are no points found, we have a valid connection;
    // otherwise choose the point of the minimum angle with the ray as connection point

    var stop = m,
        mx = m.x,
        my = m.y,
        tanMin = Infinity,
        tan;

    p = m.next;

    while (p !== stop) {
        if (hx >= p.x && p.x >= mx && hx !== p.x &&
                pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {

            tan = Math.abs(hy - p.y) / (hx - p.x); // tangential

            if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
                m = p;
                tanMin = tan;
            }
        }

        p = p.next;
    }

    return m;
}

// interlink polygon nodes in z-order
function indexCurve(start, minX, minY, invSize) {
    var p = start;
    do {
        if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
        p.prevZ = p.prev;
        p.nextZ = p.next;
        p = p.next;
    } while (p !== start);

    p.prevZ.nextZ = null;
    p.prevZ = null;

    sortLinked(p);
}

// Simon Tatham's linked list merge sort algorithm
// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
function sortLinked(list) {
    var i, p, q, e, tail, numMerges, pSize, qSize,
        inSize = 1;

    do {
        p = list;
        list = null;
        tail = null;
        numMerges = 0;

        while (p) {
            numMerges++;
            q = p;
            pSize = 0;
            for (i = 0; i < inSize; i++) {
                pSize++;
                q = q.nextZ;
                if (!q) break;
            }
            qSize = inSize;

            while (pSize > 0 || (qSize > 0 && q)) {

                if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
                    e = p;
                    p = p.nextZ;
                    pSize--;
                } else {
                    e = q;
                    q = q.nextZ;
                    qSize--;
                }

                if (tail) tail.nextZ = e;
                else list = e;

                e.prevZ = tail;
                tail = e;
            }

            p = q;
        }

        tail.nextZ = null;
        inSize *= 2;

    } while (numMerges > 1);

    return list;
}

// z-order of a point given coords and inverse of the longer side of data bbox
function zOrder(x, y, minX, minY, invSize) {
    // coords are transformed into non-negative 15-bit integer range
    x = 32767 * (x - minX) * invSize;
    y = 32767 * (y - minY) * invSize;

    x = (x | (x << 8)) & 0x00FF00FF;
    x = (x | (x << 4)) & 0x0F0F0F0F;
    x = (x | (x << 2)) & 0x33333333;
    x = (x | (x << 1)) & 0x55555555;

    y = (y | (y << 8)) & 0x00FF00FF;
    y = (y | (y << 4)) & 0x0F0F0F0F;
    y = (y | (y << 2)) & 0x33333333;
    y = (y | (y << 1)) & 0x55555555;

    return x | (y << 1);
}

// find the leftmost node of a polygon ring
function getLeftmost(start) {
    var p = start,
        leftmost = start;
    do {
        if (p.x < leftmost.x) leftmost = p;
        p = p.next;
    } while (p !== start);

    return leftmost;
}

// check if a point lies within a convex triangle
function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
    return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
           (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
           (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
}

// check if a diagonal between two polygon nodes is valid (lies in polygon interior)
function isValidDiagonal(a, b) {
    return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) &&
           locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
}

// signed area of a triangle
function area(p, q, r) {
    return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
}

// check if two points are equal
function equals(p1, p2) {
    return p1.x === p2.x && p1.y === p2.y;
}

// check if two segments intersect
function intersects(p1, q1, p2, q2) {
    if ((equals(p1, q1) && equals(p2, q2)) ||
        (equals(p1, q2) && equals(p2, q1))) return true;
    return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
           area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
}

// check if a polygon diagonal intersects any polygon segments
function intersectsPolygon(a, b) {
    var p = a;
    do {
        if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
                intersects(p, p.next, a, b)) return true;
        p = p.next;
    } while (p !== a);

    return false;
}

// check if a polygon diagonal is locally inside the polygon
function locallyInside(a, b) {
    return area(a.prev, a, a.next) < 0 ?
        area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
        area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
}

// check if the middle point of a polygon diagonal is inside the polygon
function middleInside(a, b) {
    var p = a,
        inside = false,
        px = (a.x + b.x) / 2,
        py = (a.y + b.y) / 2;
    do {
        if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
                (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
            inside = !inside;
        p = p.next;
    } while (p !== a);

    return inside;
}

// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
// if one belongs to the outer ring and another to a hole, it merges it into a single ring
function splitPolygon(a, b) {
    var a2 = new Node(a.i, a.x, a.y),
        b2 = new Node(b.i, b.x, b.y),
        an = a.next,
        bp = b.prev;

    a.next = b;
    b.prev = a;

    a2.next = an;
    an.prev = a2;

    b2.next = a2;
    a2.prev = b2;

    bp.next = b2;
    b2.prev = bp;

    return b2;
}

// create a node and optionally link it with previous one (in a circular doubly linked list)
function insertNode(i, x, y, last) {
    var p = new Node(i, x, y);

    if (!last) {
        p.prev = p;
        p.next = p;

    } else {
        p.next = last.next;
        p.prev = last;
        last.next.prev = p;
        last.next = p;
    }
    return p;
}

function removeNode(p) {
    p.next.prev = p.prev;
    p.prev.next = p.next;

    if (p.prevZ) p.prevZ.nextZ = p.nextZ;
    if (p.nextZ) p.nextZ.prevZ = p.prevZ;
}

function Node(i, x, y) {
    // vertice index in coordinates array
    this.i = i;

    // vertex coordinates
    this.x = x;
    this.y = y;

    // previous and next vertice nodes in a polygon ring
    this.prev = null;
    this.next = null;

    // z-order curve value
    this.z = null;

    // previous and next nodes in z-order
    this.prevZ = null;
    this.nextZ = null;

    // indicates whether this is a steiner point
    this.steiner = false;
}

// return a percentage difference between the polygon area and its triangulation area;
// used to verify correctness of triangulation
earcut.deviation = function (data, holeIndices, dim, triangles) {
    var hasHoles = holeIndices && holeIndices.length;
    var outerLen = hasHoles ? holeIndices[0] * dim : data.length;

    var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
    if (hasHoles) {
        for (var i = 0, len = holeIndices.length; i < len; i++) {
            var start = holeIndices[i] * dim;
            var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
            polygonArea -= Math.abs(signedArea(data, start, end, dim));
        }
    }

    var trianglesArea = 0;
    for (i = 0; i < triangles.length; i += 3) {
        var a = triangles[i] * dim;
        var b = triangles[i + 1] * dim;
        var c = triangles[i + 2] * dim;
        trianglesArea += Math.abs(
            (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
            (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
    }

    return polygonArea === 0 && trianglesArea === 0 ? 0 :
        Math.abs((trianglesArea - polygonArea) / polygonArea);
};

function signedArea(data, start, end, dim) {
    var sum = 0;
    for (var i = start, j = end - dim; i < end; i += dim) {
        sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
        j = i;
    }
    return sum;
}

// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
earcut.flatten = function (data) {
    var dim = data[0][0].length,
        result = {vertices: [], holes: [], dimensions: dim},
        holeIndex = 0;

    for (var i = 0; i < data.length; i++) {
        for (var j = 0; j < data[i].length; j++) {
            for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
        }
        if (i > 0) {
            holeIndex += data[i - 1].length;
            result.holes.push(holeIndex);
        }
    }
    return result;
};

},{}],158:[function(_dereq_,module,exports){
"use strict"

module.exports = edgeToAdjacency

var uniq = _dereq_("uniq")

function edgeToAdjacency(edges, numVertices) {
  var numEdges = edges.length
  if(typeof numVertices !== "number") {
    numVertices = 0
    for(var i=0; i<numEdges; ++i) {
      var e = edges[i]
      numVertices = Math.max(numVertices, e[0], e[1])
    }
    numVertices = (numVertices|0) + 1
  }
  numVertices = numVertices|0
  var adj = new Array(numVertices)
  for(var i=0; i<numVertices; ++i) {
    adj[i] = []
  }
  for(var i=0; i<numEdges; ++i) {
    var e = edges[i]
    adj[e[0]].push(e[1])
    adj[e[1]].push(e[0])
  }
  for(var j=0; j<numVertices; ++j) {
    uniq(adj[j], function(a, b) {
      return a - b
    })
  }
  return adj
}
},{"uniq":525}],159:[function(_dereq_,module,exports){
// Inspired by Google Closure:
// http://closure-library.googlecode.com/svn/docs/
// closure_goog_array_array.js.html#goog.array.clear

"use strict";

var value = _dereq_("../../object/valid-value");

module.exports = function () {
	value(this).length = 0;
	return this;
};

},{"../../object/valid-value":191}],160:[function(_dereq_,module,exports){
"use strict";

module.exports = _dereq_("./is-implemented")()
	? Array.from
	: _dereq_("./shim");

},{"./is-implemented":161,"./shim":162}],161:[function(_dereq_,module,exports){
"use strict";

module.exports = function () {
	var from = Array.from, arr, result;
	if (typeof from !== "function") return false;
	arr = ["raz", "dwa"];
	result = from(arr);
	return Boolean(result && (result !== arr) && (result[1] === "dwa"));
};

},{}],162:[function(_dereq_,module,exports){
"use strict";

var iteratorSymbol = _dereq_("es6-symbol").iterator
  , isArguments    = _dereq_("../../function/is-arguments")
  , isFunction     = _dereq_("../../function/is-function")
  , toPosInt       = _dereq_("../../number/to-pos-integer")
  , callable       = _dereq_("../../object/valid-callable")
  , validValue     = _dereq_("../../object/valid-value")
  , isValue        = _dereq_("../../object/is-value")
  , isString       = _dereq_("../../string/is-string")
  , isArray        = Array.isArray
  , call           = Function.prototype.call
  , desc           = { configurable: true, enumerable: true, writable: true, value: null }
  , defineProperty = Object.defineProperty;

// eslint-disable-next-line complexity
module.exports = function (arrayLike /*, mapFn, thisArg*/) {
	var mapFn = arguments[1]
	  , thisArg = arguments[2]
	  , Context
	  , i
	  , j
	  , arr
	  , length
	  , code
	  , iterator
	  , result
	  , getIterator
	  , value;

	arrayLike = Object(validValue(arrayLike));

	if (isValue(mapFn)) callable(mapFn);
	if (!this || this === Array || !isFunction(this)) {
		// Result: Plain array
		if (!mapFn) {
			if (isArguments(arrayLike)) {
				// Source: Arguments
				length = arrayLike.length;
				if (length !== 1) return Array.apply(null, arrayLike);
				arr = new Array(1);
				arr[0] = arrayLike[0];
				return arr;
			}
			if (isArray(arrayLike)) {
				// Source: Array
				arr = new Array(length = arrayLike.length);
				for (i = 0; i < length; ++i) arr[i] = arrayLike[i];
				return arr;
			}
		}
		arr = [];
	} else {
		// Result: Non plain array
		Context = this;
	}

	if (!isArray(arrayLike)) {
		if ((getIterator = arrayLike[iteratorSymbol]) !== undefined) {
			// Source: Iterator
			iterator = callable(getIterator).call(arrayLike);
			if (Context) arr = new Context();
			result = iterator.next();
			i = 0;
			while (!result.done) {
				value = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value;
				if (Context) {
					desc.value = value;
					defineProperty(arr, i, desc);
				} else {
					arr[i] = value;
				}
				result = iterator.next();
				++i;
			}
			length = i;
		} else if (isString(arrayLike)) {
			// Source: String
			length = arrayLike.length;
			if (Context) arr = new Context();
			for (i = 0, j = 0; i < length; ++i) {
				value = arrayLike[i];
				if (i + 1 < length) {
					code = value.charCodeAt(0);
					// eslint-disable-next-line max-depth
					if (code >= 0xd800 && code <= 0xdbff) value += arrayLike[++i];
				}
				value = mapFn ? call.call(mapFn, thisArg, value, j) : value;
				if (Context) {
					desc.value = value;
					defineProperty(arr, j, desc);
				} else {
					arr[j] = value;
				}
				++j;
			}
			length = j;
		}
	}
	if (length === undefined) {
		// Source: array or array-like
		length = toPosInt(arrayLike.length);
		if (Context) arr = new Context(length);
		for (i = 0; i < length; ++i) {
			value = mapFn ? call.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[i];
			if (Context) {
				desc.value = value;
				defineProperty(arr, i, desc);
			} else {
				arr[i] = value;
			}
		}
	}
	if (Context) {
		desc.value = null;
		arr.length = length;
	}
	return arr;
};

},{"../../function/is-arguments":163,"../../function/is-function":164,"../../number/to-pos-integer":170,"../../object/is-value":180,"../../object/valid-callable":189,"../../object/valid-value":191,"../../string/is-string":195,"es6-symbol":205}],163:[function(_dereq_,module,exports){
"use strict";

var objToString = Object.prototype.toString
  , id = objToString.call(
	(function () {
		return arguments;
	})()
);

module.exports = function (value) {
	return objToString.call(value) === id;
};

},{}],164:[function(_dereq_,module,exports){
"use strict";

var objToString = Object.prototype.toString, id = objToString.call(_dereq_("./noop"));

module.exports = function (value) {
	return typeof value === "function" && objToString.call(value) === id;
};

},{"./noop":165}],165:[function(_dereq_,module,exports){
"use strict";

// eslint-disable-next-line no-empty-function
module.exports = function () {};

},{}],166:[function(_dereq_,module,exports){
"use strict";

module.exports = _dereq_("./is-implemented")()
	? Math.sign
	: _dereq_("./shim");

},{"./is-implemented":167,"./shim":168}],167:[function(_dereq_,module,exports){
"use strict";

module.exports = function () {
	var sign = Math.sign;
	if (typeof sign !== "function") return false;
	return (sign(10) === 1) && (sign(-20) === -1);
};

},{}],168:[function(_dereq_,module,exports){
"use strict";

module.exports = function (value) {
	value = Number(value);
	if (isNaN(value) || (value === 0)) return value;
	return value > 0 ? 1 : -1;
};

},{}],169:[function(_dereq_,module,exports){
"use strict";

var sign = _dereq_("../math/sign")

  , abs = Math.abs, floor = Math.floor;

module.exports = function (value) {
	if (isNaN(value)) return 0;
	value = Number(value);
	if ((value === 0) || !isFinite(value)) return value;
	return sign(value) * floor(abs(value));
};

},{"../math/sign":166}],170:[function(_dereq_,module,exports){
"use strict";

var toInteger = _dereq_("./to-integer")

  , max = Math.max;

module.exports = function (value) {
 return max(0, toInteger(value));
};

},{"./to-integer":169}],171:[function(_dereq_,module,exports){
// Internal method, used by iteration functions.
// Calls a function for each key-value pair found in object
// Optionally takes compareFn to iterate object in specific order

"use strict";

var callable                = _dereq_("./valid-callable")
  , value                   = _dereq_("./valid-value")
  , bind                    = Function.prototype.bind
  , call                    = Function.prototype.call
  , keys                    = Object.keys
  , objPropertyIsEnumerable = Object.prototype.propertyIsEnumerable;

module.exports = function (method, defVal) {
	return function (obj, cb /*, thisArg, compareFn*/) {
		var list, thisArg = arguments[2], compareFn = arguments[3];
		obj = Object(value(obj));
		callable(cb);

		list = keys(obj);
		if (compareFn) {
			list.sort(typeof compareFn === "function" ? bind.call(compareFn, obj) : undefined);
		}
		if (typeof method !== "function") method = list[method];
		return call.call(method, list, function (key, index) {
			if (!objPropertyIsEnumerable.call(obj, key)) return defVal;
			return call.call(cb, thisArg, obj[key], key, obj, index);
		});
	};
};

},{"./valid-callable":189,"./valid-value":191}],172:[function(_dereq_,module,exports){
"use strict";

module.exports = _dereq_("./is-implemented")()
	? Object.assign
	: _dereq_("./shim");

},{"./is-implemented":173,"./shim":174}],173:[function(_dereq_,module,exports){
"use strict";

module.exports = function () {
	var assign = Object.assign, obj;
	if (typeof assign !== "function") return false;
	obj = { foo: "raz" };
	assign(obj, { bar: "dwa" }, { trzy: "trzy" });
	return (obj.foo + obj.bar + obj.trzy) === "razdwatrzy";
};

},{}],174:[function(_dereq_,module,exports){
"use strict";

var keys  = _dereq_("../keys")
  , value = _dereq_("../valid-value")
  , max   = Math.max;

module.exports = function (dest, src /*, …srcn*/) {
	var error, i, length = max(arguments.length, 2), assign;
	dest = Object(value(dest));
	assign = function (key) {
		try {
			dest[key] = src[key];
		} catch (e) {
			if (!error) error = e;
		}
	};
	for (i = 1; i < length; ++i) {
		src = arguments[i];
		keys(src).forEach(assign);
	}
	if (error !== undefined) throw error;
	return dest;
};

},{"../keys":181,"../valid-value":191}],175:[function(_dereq_,module,exports){
"use strict";

var aFrom  = _dereq_("../array/from")
  , assign = _dereq_("./assign")
  , value  = _dereq_("./valid-value");

module.exports = function (obj/*, propertyNames, options*/) {
	var copy = Object(value(obj)), propertyNames = arguments[1], options = Object(arguments[2]);
	if (copy !== obj && !propertyNames) return copy;
	var result = {};
	if (propertyNames) {
		aFrom(propertyNames, function (propertyName) {
			if (options.ensure || propertyName in obj) result[propertyName] = obj[propertyName];
		});
	} else {
		assign(result, obj);
	}
	return result;
};

},{"../array/from":160,"./assign":172,"./valid-value":191}],176:[function(_dereq_,module,exports){
// Workaround for http://code.google.com/p/v8/issues/detail?id=2804

"use strict";

var create = Object.create, shim;

if (!_dereq_("./set-prototype-of/is-implemented")()) {
	shim = _dereq_("./set-prototype-of/shim");
}

module.exports = (function () {
	var nullObject, polyProps, desc;
	if (!shim) return create;
	if (shim.level !== 1) return create;

	nullObject = {};
	polyProps = {};
	desc = {
		configurable: false,
		enumerable: false,
		writable: true,
		value: undefined
	};
	Object.getOwnPropertyNames(Object.prototype).forEach(function (name) {
		if (name === "__proto__") {
			polyProps[name] = {
				configurable: true,
				enumerable: false,
				writable: true,
				value: undefined
			};
			return;
		}
		polyProps[name] = desc;
	});
	Object.defineProperties(nullObject, polyProps);

	Object.defineProperty(shim, "nullPolyfill", {
		configurable: false,
		enumerable: false,
		writable: false,
		value: nullObject
	});

	return function (prototype, props) {
		return create(prototype === null ? nullObject : prototype, props);
	};
}());

},{"./set-prototype-of/is-implemented":187,"./set-prototype-of/shim":188}],177:[function(_dereq_,module,exports){
"use strict";

module.exports = _dereq_("./_iterate")("forEach");

},{"./_iterate":171}],178:[function(_dereq_,module,exports){
// Deprecated

"use strict";

module.exports = function (obj) {
 return typeof obj === "function";
};

},{}],179:[function(_dereq_,module,exports){
"use strict";

var isValue = _dereq_("./is-value");

var map = { function: true, object: true };

module.exports = function (value) {
	return (isValue(value) && map[typeof value]) || false;
};

},{"./is-value":180}],180:[function(_dereq_,module,exports){
"use strict";

var _undefined = _dereq_("../function/noop")(); // Support ES3 engines

module.exports = function (val) {
 return (val !== _undefined) && (val !== null);
};

},{"../function/noop":165}],181:[function(_dereq_,module,exports){
"use strict";

module.exports = _dereq_("./is-implemented")() ? Object.keys : _dereq_("./shim");

},{"./is-implemented":182,"./shim":183}],182:[function(_dereq_,module,exports){
"use strict";

module.exports = function () {
	try {
		Object.keys("primitive");
		return true;
	} catch (e) {
		return false;
	}
};

},{}],183:[function(_dereq_,module,exports){
"use strict";

var isValue = _dereq_("../is-value");

var keys = Object.keys;

module.exports = function (object) { return keys(isValue(object) ? Object(object) : object); };

},{"../is-value":180}],184:[function(_dereq_,module,exports){
"use strict";

var callable = _dereq_("./valid-callable")
  , forEach  = _dereq_("./for-each")
  , call     = Function.prototype.call;

module.exports = function (obj, cb /*, thisArg*/) {
	var result = {}, thisArg = arguments[2];
	callable(cb);
	forEach(obj, function (value, key, targetObj, index) {
		result[key] = call.call(cb, thisArg, value, key, targetObj, index);
	});
	return result;
};

},{"./for-each":177,"./valid-callable":189}],185:[function(_dereq_,module,exports){
"use strict";

var isValue = _dereq_("./is-value");

var forEach = Array.prototype.forEach, create = Object.create;

var process = function (src, obj) {
	var key;
	for (key in src) obj[key] = src[key];
};

// eslint-disable-next-line no-unused-vars
module.exports = function (opts1 /*, …options*/) {
	var result = create(null);
	forEach.call(arguments, function (options) {
		if (!isValue(options)) return;
		process(Object(options), result);
	});
	return result;
};

},{"./is-value":180}],186:[function(_dereq_,module,exports){
"use strict";

module.exports = _dereq_("./is-implemented")()
	? Object.setPrototypeOf
	: _dereq_("./shim");

},{"./is-implemented":187,"./shim":188}],187:[function(_dereq_,module,exports){
"use strict";

var create = Object.create, getPrototypeOf = Object.getPrototypeOf, plainObject = {};

module.exports = function (/* CustomCreate*/) {
	var setPrototypeOf = Object.setPrototypeOf, customCreate = arguments[0] || create;
	if (typeof setPrototypeOf !== "function") return false;
	return getPrototypeOf(setPrototypeOf(customCreate(null), plainObject)) === plainObject;
};

},{}],188:[function(_dereq_,module,exports){
/* eslint no-proto: "off" */

// Big thanks to @WebReflection for sorting this out
// https://gist.github.com/WebReflection/5593554

"use strict";

var isObject        = _dereq_("../is-object")
  , value           = _dereq_("../valid-value")
  , objIsPrototypeOf = Object.prototype.isPrototypeOf
  , defineProperty  = Object.defineProperty
  , nullDesc        = {
	configurable: true,
	enumerable: false,
	writable: true,
	value: undefined
}
  , validate;

validate = function (obj, prototype) {
	value(obj);
	if (prototype === null || isObject(prototype)) return obj;
	throw new TypeError("Prototype must be null or an object");
};

module.exports = (function (status) {
	var fn, set;
	if (!status) return null;
	if (status.level === 2) {
		if (status.set) {
			set = status.set;
			fn = function (obj, prototype) {
				set.call(validate(obj, prototype), prototype);
				return obj;
			};
		} else {
			fn = function (obj, prototype) {
				validate(obj, prototype).__proto__ = prototype;
				return obj;
			};
		}
	} else {
		fn = function self(obj, prototype) {
			var isNullBase;
			validate(obj, prototype);
			isNullBase = objIsPrototypeOf.call(self.nullPolyfill, obj);
			if (isNullBase) delete self.nullPolyfill.__proto__;
			if (prototype === null) prototype = self.nullPolyfill;
			obj.__proto__ = prototype;
			if (isNullBase) defineProperty(self.nullPolyfill, "__proto__", nullDesc);
			return obj;
		};
	}
	return Object.defineProperty(fn, "level", {
		configurable: false,
		enumerable: false,
		writable: false,
		value: status.level
	});
}(
	(function () {
		var tmpObj1 = Object.create(null)
		  , tmpObj2 = {}
		  , set
		  , desc = Object.getOwnPropertyDescriptor(Object.prototype, "__proto__");

		if (desc) {
			try {
				set = desc.set; // Opera crashes at this point
				set.call(tmpObj1, tmpObj2);
			} catch (ignore) {}
			if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { set: set, level: 2 };
		}

		tmpObj1.__proto__ = tmpObj2;
		if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 2 };

		tmpObj1 = {};
		tmpObj1.__proto__ = tmpObj2;
		if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 1 };

		return false;
	})()
));

_dereq_("../create");

},{"../create":176,"../is-object":179,"../valid-value":191}],189:[function(_dereq_,module,exports){
"use strict";

module.exports = function (fn) {
	if (typeof fn !== "function") throw new TypeError(fn + " is not a function");
	return fn;
};

},{}],190:[function(_dereq_,module,exports){
"use strict";

var isObject = _dereq_("./is-object");

module.exports = function (value) {
	if (!isObject(value)) throw new TypeError(value + " is not an Object");
	return value;
};

},{"./is-object":179}],191:[function(_dereq_,module,exports){
"use strict";

var isValue = _dereq_("./is-value");

module.exports = function (value) {
	if (!isValue(value)) throw new TypeError("Cannot use null or undefined");
	return value;
};

},{"./is-value":180}],192:[function(_dereq_,module,exports){
"use strict";

module.exports = _dereq_("./is-implemented")()
	? String.prototype.contains
	: _dereq_("./shim");

},{"./is-implemented":193,"./shim":194}],193:[function(_dereq_,module,exports){
"use strict";

var str = "razdwatrzy";

module.exports = function () {
	if (typeof str.contains !== "function") return false;
	return (str.contains("dwa") === true) && (str.contains("foo") === false);
};

},{}],194:[function(_dereq_,module,exports){
"use strict";

var indexOf = String.prototype.indexOf;

module.exports = function (searchString/*, position*/) {
	return indexOf.call(this, searchString, arguments[1]) > -1;
};

},{}],195:[function(_dereq_,module,exports){
"use strict";

var objToString = Object.prototype.toString, id = objToString.call("");

module.exports = function (value) {
	return (
		typeof value === "string" ||
		(value &&
			typeof value === "object" &&
			(value instanceof String || objToString.call(value) === id)) ||
		false
	);
};

},{}],196:[function(_dereq_,module,exports){
"use strict";

var generated = Object.create(null), random = Math.random;

module.exports = function () {
	var str;
	do {
		str = random()
			.toString(36)
			.slice(2);
	} while (generated[str]);
	return str;
};

},{}],197:[function(_dereq_,module,exports){
"use strict";

var setPrototypeOf = _dereq_("es5-ext/object/set-prototype-of")
  , contains       = _dereq_("es5-ext/string/#/contains")
  , d              = _dereq_("d")
  , Symbol         = _dereq_("es6-symbol")
  , Iterator       = _dereq_("./");

var defineProperty = Object.defineProperty, ArrayIterator;

ArrayIterator = module.exports = function (arr, kind) {
	if (!(this instanceof ArrayIterator)) throw new TypeError("Constructor requires 'new'");
	Iterator.call(this, arr);
	if (!kind) kind = "value";
	else if (contains.call(kind, "key+value")) kind = "key+value";
	else if (contains.call(kind, "key")) kind = "key";
	else kind = "value";
	defineProperty(this, "__kind__", d("", kind));
};
if (setPrototypeOf) setPrototypeOf(ArrayIterator, Iterator);

// Internal %ArrayIteratorPrototype% doesn't expose its constructor
delete ArrayIterator.prototype.constructor;

ArrayIterator.prototype = Object.create(Iterator.prototype, {
	_resolve: d(function (i) {
		if (this.__kind__ === "value") return this.__list__[i];
		if (this.__kind__ === "key+value") return [i, this.__list__[i]];
		return i;
	})
});
defineProperty(ArrayIterator.prototype, Symbol.toStringTag, d("c", "Array Iterator"));

},{"./":200,"d":140,"es5-ext/object/set-prototype-of":186,"es5-ext/string/#/contains":192,"es6-symbol":205}],198:[function(_dereq_,module,exports){
"use strict";

var isArguments = _dereq_("es5-ext/function/is-arguments")
  , callable    = _dereq_("es5-ext/object/valid-callable")
  , isString    = _dereq_("es5-ext/string/is-string")
  , get         = _dereq_("./get");

var isArray = Array.isArray, call = Function.prototype.call, some = Array.prototype.some;

module.exports = function (iterable, cb /*, thisArg*/) {
	var mode, thisArg = arguments[2], result, doBreak, broken, i, length, char, code;
	if (isArray(iterable) || isArguments(iterable)) mode = "array";
	else if (isString(iterable)) mode = "string";
	else iterable = get(iterable);

	callable(cb);
	doBreak = function () {
		broken = true;
	};
	if (mode === "array") {
		some.call(iterable, function (value) {
			call.call(cb, thisArg, value, doBreak);
			return broken;
		});
		return;
	}
	if (mode === "string") {
		length = iterable.length;
		for (i = 0; i < length; ++i) {
			char = iterable[i];
			if (i + 1 < length) {
				code = char.charCodeAt(0);
				if (code >= 0xd800 && code <= 0xdbff) char += iterable[++i];
			}
			call.call(cb, thisArg, char, doBreak);
			if (broken) break;
		}
		return;
	}
	result = iterable.next();

	while (!result.done) {
		call.call(cb, thisArg, result.value, doBreak);
		if (broken) return;
		result = iterable.next();
	}
};

},{"./get":199,"es5-ext/function/is-arguments":163,"es5-ext/object/valid-callable":189,"es5-ext/string/is-string":195}],199:[function(_dereq_,module,exports){
"use strict";

var isArguments    = _dereq_("es5-ext/function/is-arguments")
  , isString       = _dereq_("es5-ext/string/is-string")
  , ArrayIterator  = _dereq_("./array")
  , StringIterator = _dereq_("./string")
  , iterable       = _dereq_("./valid-iterable")
  , iteratorSymbol = _dereq_("es6-symbol").iterator;

module.exports = function (obj) {
	if (typeof iterable(obj)[iteratorSymbol] === "function") return obj[iteratorSymbol]();
	if (isArguments(obj)) return new ArrayIterator(obj);
	if (isString(obj)) return new StringIterator(obj);
	return new ArrayIterator(obj);
};

},{"./array":197,"./string":202,"./valid-iterable":203,"es5-ext/function/is-arguments":163,"es5-ext/string/is-string":195,"es6-symbol":205}],200:[function(_dereq_,module,exports){
"use strict";

var clear    = _dereq_("es5-ext/array/#/clear")
  , assign   = _dereq_("es5-ext/object/assign")
  , callable = _dereq_("es5-ext/object/valid-callable")
  , value    = _dereq_("es5-ext/object/valid-value")
  , d        = _dereq_("d")
  , autoBind = _dereq_("d/auto-bind")
  , Symbol   = _dereq_("es6-symbol");

var defineProperty = Object.defineProperty, defineProperties = Object.defineProperties, Iterator;

module.exports = Iterator = function (list, context) {
	if (!(this instanceof Iterator)) throw new TypeError("Constructor requires 'new'");
	defineProperties(this, {
		__list__: d("w", value(list)),
		__context__: d("w", context),
		__nextIndex__: d("w", 0)
	});
	if (!context) return;
	callable(context.on);
	context.on("_add", this._onAdd);
	context.on("_delete", this._onDelete);
	context.on("_clear", this._onClear);
};

// Internal %IteratorPrototype% doesn't expose its constructor
delete Iterator.prototype.constructor;

defineProperties(
	Iterator.prototype,
	assign(
		{
			_next: d(function () {
				var i;
				if (!this.__list__) return undefined;
				if (this.__redo__) {
					i = this.__redo__.shift();
					if (i !== undefined) return i;
				}
				if (this.__nextIndex__ < this.__list__.length) return this.__nextIndex__++;
				this._unBind();
				return undefined;
			}),
			next: d(function () {
				return this._createResult(this._next());
			}),
			_createResult: d(function (i) {
				if (i === undefined) return { done: true, value: undefined };
				return { done: false, value: this._resolve(i) };
			}),
			_resolve: d(function (i) {
				return this.__list__[i];
			}),
			_unBind: d(function () {
				this.__list__ = null;
				delete this.__redo__;
				if (!this.__context__) return;
				this.__context__.off("_add", this._onAdd);
				this.__context__.off("_delete", this._onDelete);
				this.__context__.off("_clear", this._onClear);
				this.__context__ = null;
			}),
			toString: d(function () {
				return "[object " + (this[Symbol.toStringTag] || "Object") + "]";
			})
		},
		autoBind({
			_onAdd: d(function (index) {
				if (index >= this.__nextIndex__) return;
				++this.__nextIndex__;
				if (!this.__redo__) {
					defineProperty(this, "__redo__", d("c", [index]));
					return;
				}
				this.__redo__.forEach(function (redo, i) {
					if (redo >= index) this.__redo__[i] = ++redo;
				}, this);
				this.__redo__.push(index);
			}),
			_onDelete: d(function (index) {
				var i;
				if (index >= this.__nextIndex__) return;
				--this.__nextIndex__;
				if (!this.__redo__) return;
				i = this.__redo__.indexOf(index);
				if (i !== -1) this.__redo__.splice(i, 1);
				this.__redo__.forEach(function (redo, j) {
					if (redo > index) this.__redo__[j] = --redo;
				}, this);
			}),
			_onClear: d(function () {
				if (this.__redo__) clear.call(this.__redo__);
				this.__nextIndex__ = 0;
			})
		})
	)
);

defineProperty(
	Iterator.prototype,
	Symbol.iterator,
	d(function () {
		return this;
	})
);

},{"d":140,"d/auto-bind":139,"es5-ext/array/#/clear":159,"es5-ext/object/assign":172,"es5-ext/object/valid-callable":189,"es5-ext/object/valid-value":191,"es6-symbol":205}],201:[function(_dereq_,module,exports){
"use strict";

var isArguments = _dereq_("es5-ext/function/is-arguments")
  , isValue     = _dereq_("es5-ext/object/is-value")
  , isString    = _dereq_("es5-ext/string/is-string");

var iteratorSymbol = _dereq_("es6-symbol").iterator
  , isArray        = Array.isArray;

module.exports = function (value) {
	if (!isValue(value)) return false;
	if (isArray(value)) return true;
	if (isString(value)) return true;
	if (isArguments(value)) return true;
	return typeof value[iteratorSymbol] === "function";
};

},{"es5-ext/function/is-arguments":163,"es5-ext/object/is-value":180,"es5-ext/string/is-string":195,"es6-symbol":205}],202:[function(_dereq_,module,exports){
// Thanks @mathiasbynens
// http://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols

"use strict";

var setPrototypeOf = _dereq_("es5-ext/object/set-prototype-of")
  , d              = _dereq_("d")
  , Symbol         = _dereq_("es6-symbol")
  , Iterator       = _dereq_("./");

var defineProperty = Object.defineProperty, StringIterator;

StringIterator = module.exports = function (str) {
	if (!(this instanceof StringIterator)) throw new TypeError("Constructor requires 'new'");
	str = String(str);
	Iterator.call(this, str);
	defineProperty(this, "__length__", d("", str.length));
};
if (setPrototypeOf) setPrototypeOf(StringIterator, Iterator);

// Internal %ArrayIteratorPrototype% doesn't expose its constructor
delete StringIterator.prototype.constructor;

StringIterator.prototype = Object.create(Iterator.prototype, {
	_next: d(function () {
		if (!this.__list__) return undefined;
		if (this.__nextIndex__ < this.__length__) return this.__nextIndex__++;
		this._unBind();
		return undefined;
	}),
	_resolve: d(function (i) {
		var char = this.__list__[i], code;
		if (this.__nextIndex__ === this.__length__) return char;
		code = char.charCodeAt(0);
		if (code >= 0xd800 && code <= 0xdbff) return char + this.__list__[this.__nextIndex__++];
		return char;
	})
});
defineProperty(StringIterator.prototype, Symbol.toStringTag, d("c", "String Iterator"));

},{"./":200,"d":140,"es5-ext/object/set-prototype-of":186,"es6-symbol":205}],203:[function(_dereq_,module,exports){
"use strict";

var isIterable = _dereq_("./is-iterable");

module.exports = function (value) {
	if (!isIterable(value)) throw new TypeError(value + " is not iterable");
	return value;
};

},{"./is-iterable":201}],204:[function(_dereq_,module,exports){
(function (process,global){
/*!
 * @overview es6-promise - a tiny implementation of Promises/A+.
 * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
 * @license   Licensed under MIT license
 *            See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
 * @version   3.3.1
 */

(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
    typeof define === 'function' && define.amd ? define(factory) :
    (global.ES6Promise = factory());
}(this, (function () { 'use strict';

function objectOrFunction(x) {
  return typeof x === 'function' || typeof x === 'object' && x !== null;
}

function isFunction(x) {
  return typeof x === 'function';
}

var _isArray = undefined;
if (!Array.isArray) {
  _isArray = function (x) {
    return Object.prototype.toString.call(x) === '[object Array]';
  };
} else {
  _isArray = Array.isArray;
}

var isArray = _isArray;

var len = 0;
var vertxNext = undefined;
var customSchedulerFn = undefined;

var asap = function asap(callback, arg) {
  queue[len] = callback;
  queue[len + 1] = arg;
  len += 2;
  if (len === 2) {
    // If len is 2, that means that we need to schedule an async flush.
    // If additional callbacks are queued before the queue is flushed, they
    // will be processed by this flush that we are scheduling.
    if (customSchedulerFn) {
      customSchedulerFn(flush);
    } else {
      scheduleFlush();
    }
  }
};

function setScheduler(scheduleFn) {
  customSchedulerFn = scheduleFn;
}

function setAsap(asapFn) {
  asap = asapFn;
}

var browserWindow = typeof window !== 'undefined' ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';

// test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';

// node
function useNextTick() {
  // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  // see https://github.com/cujojs/when/issues/410 for details
  return function () {
    return process.nextTick(flush);
  };
}

// vertx
function useVertxTimer() {
  return function () {
    vertxNext(flush);
  };
}

function useMutationObserver() {
  var iterations = 0;
  var observer = new BrowserMutationObserver(flush);
  var node = document.createTextNode('');
  observer.observe(node, { characterData: true });

  return function () {
    node.data = iterations = ++iterations % 2;
  };
}

// web worker
function useMessageChannel() {
  var channel = new MessageChannel();
  channel.port1.onmessage = flush;
  return function () {
    return channel.port2.postMessage(0);
  };
}

function useSetTimeout() {
  // Store setTimeout reference so es6-promise will be unaffected by
  // other code modifying setTimeout (like sinon.useFakeTimers())
  var globalSetTimeout = setTimeout;
  return function () {
    return globalSetTimeout(flush, 1);
  };
}

var queue = new Array(1000);
function flush() {
  for (var i = 0; i < len; i += 2) {
    var callback = queue[i];
    var arg = queue[i + 1];

    callback(arg);

    queue[i] = undefined;
    queue[i + 1] = undefined;
  }

  len = 0;
}

function attemptVertx() {
  try {
    var r = _dereq_;
    var vertx = r('vertx');
    vertxNext = vertx.runOnLoop || vertx.runOnContext;
    return useVertxTimer();
  } catch (e) {
    return useSetTimeout();
  }
}

var scheduleFlush = undefined;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
  scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
  scheduleFlush = useMutationObserver();
} else if (isWorker) {
  scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && typeof _dereq_ === 'function') {
  scheduleFlush = attemptVertx();
} else {
  scheduleFlush = useSetTimeout();
}

function then(onFulfillment, onRejection) {
  var _arguments = arguments;

  var parent = this;

  var child = new this.constructor(noop);

  if (child[PROMISE_ID] === undefined) {
    makePromise(child);
  }

  var _state = parent._state;

  if (_state) {
    (function () {
      var callback = _arguments[_state - 1];
      asap(function () {
        return invokeCallback(_state, child, callback, parent._result);
      });
    })();
  } else {
    subscribe(parent, child, onFulfillment, onRejection);
  }

  return child;
}

/**
  `Promise.resolve` returns a promise that will become resolved with the
  passed `value`. It is shorthand for the following:

  ```javascript
  let promise = new Promise(function(resolve, reject){
    resolve(1);
  });

  promise.then(function(value){
    // value === 1
  });
  ```

  Instead of writing the above, your code now simply becomes the following:

  ```javascript
  let promise = Promise.resolve(1);

  promise.then(function(value){
    // value === 1
  });
  ```

  @method resolve
  @static
  @param {Any} value value that the returned promise will be resolved with
  Useful for tooling.
  @return {Promise} a promise that will become fulfilled with the given
  `value`
*/
function resolve(object) {
  /*jshint validthis:true */
  var Constructor = this;

  if (object && typeof object === 'object' && object.constructor === Constructor) {
    return object;
  }

  var promise = new Constructor(noop);
  _resolve(promise, object);
  return promise;
}

var PROMISE_ID = Math.random().toString(36).substring(16);

function noop() {}

var PENDING = void 0;
var FULFILLED = 1;
var REJECTED = 2;

var GET_THEN_ERROR = new ErrorObject();

function selfFulfillment() {
  return new TypeError("You cannot resolve a promise with itself");
}

function cannotReturnOwn() {
  return new TypeError('A promises callback cannot return that same promise.');
}

function getThen(promise) {
  try {
    return promise.then;
  } catch (error) {
    GET_THEN_ERROR.error = error;
    return GET_THEN_ERROR;
  }
}

function tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  try {
    then.call(value, fulfillmentHandler, rejectionHandler);
  } catch (e) {
    return e;
  }
}

function handleForeignThenable(promise, thenable, then) {
  asap(function (promise) {
    var sealed = false;
    var error = tryThen(then, thenable, function (value) {
      if (sealed) {
        return;
      }
      sealed = true;
      if (thenable !== value) {
        _resolve(promise, value);
      } else {
        fulfill(promise, value);
      }
    }, function (reason) {
      if (sealed) {
        return;
      }
      sealed = true;

      _reject(promise, reason);
    }, 'Settle: ' + (promise._label || ' unknown promise'));

    if (!sealed && error) {
      sealed = true;
      _reject(promise, error);
    }
  }, promise);
}

function handleOwnThenable(promise, thenable) {
  if (thenable._state === FULFILLED) {
    fulfill(promise, thenable._result);
  } else if (thenable._state === REJECTED) {
    _reject(promise, thenable._result);
  } else {
    subscribe(thenable, undefined, function (value) {
      return _resolve(promise, value);
    }, function (reason) {
      return _reject(promise, reason);
    });
  }
}

function handleMaybeThenable(promise, maybeThenable, then$$) {
  if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) {
    handleOwnThenable(promise, maybeThenable);
  } else {
    if (then$$ === GET_THEN_ERROR) {
      _reject(promise, GET_THEN_ERROR.error);
    } else if (then$$ === undefined) {
      fulfill(promise, maybeThenable);
    } else if (isFunction(then$$)) {
      handleForeignThenable(promise, maybeThenable, then$$);
    } else {
      fulfill(promise, maybeThenable);
    }
  }
}

function _resolve(promise, value) {
  if (promise === value) {
    _reject(promise, selfFulfillment());
  } else if (objectOrFunction(value)) {
    handleMaybeThenable(promise, value, getThen(value));
  } else {
    fulfill(promise, value);
  }
}

function publishRejection(promise) {
  if (promise._onerror) {
    promise._onerror(promise._result);
  }

  publish(promise);
}

function fulfill(promise, value) {
  if (promise._state !== PENDING) {
    return;
  }

  promise._result = value;
  promise._state = FULFILLED;

  if (promise._subscribers.length !== 0) {
    asap(publish, promise);
  }
}

function _reject(promise, reason) {
  if (promise._state !== PENDING) {
    return;
  }
  promise._state = REJECTED;
  promise._result = reason;

  asap(publishRejection, promise);
}

function subscribe(parent, child, onFulfillment, onRejection) {
  var _subscribers = parent._subscribers;
  var length = _subscribers.length;

  parent._onerror = null;

  _subscribers[length] = child;
  _subscribers[length + FULFILLED] = onFulfillment;
  _subscribers[length + REJECTED] = onRejection;

  if (length === 0 && parent._state) {
    asap(publish, parent);
  }
}

function publish(promise) {
  var subscribers = promise._subscribers;
  var settled = promise._state;

  if (subscribers.length === 0) {
    return;
  }

  var child = undefined,
      callback = undefined,
      detail = promise._result;

  for (var i = 0; i < subscribers.length; i += 3) {
    child = subscribers[i];
    callback = subscribers[i + settled];

    if (child) {
      invokeCallback(settled, child, callback, detail);
    } else {
      callback(detail);
    }
  }

  promise._subscribers.length = 0;
}

function ErrorObject() {
  this.error = null;
}

var TRY_CATCH_ERROR = new ErrorObject();

function tryCatch(callback, detail) {
  try {
    return callback(detail);
  } catch (e) {
    TRY_CATCH_ERROR.error = e;
    return TRY_CATCH_ERROR;
  }
}

function invokeCallback(settled, promise, callback, detail) {
  var hasCallback = isFunction(callback),
      value = undefined,
      error = undefined,
      succeeded = undefined,
      failed = undefined;

  if (hasCallback) {
    value = tryCatch(callback, detail);

    if (value === TRY_CATCH_ERROR) {
      failed = true;
      error = value.error;
      value = null;
    } else {
      succeeded = true;
    }

    if (promise === value) {
      _reject(promise, cannotReturnOwn());
      return;
    }
  } else {
    value = detail;
    succeeded = true;
  }

  if (promise._state !== PENDING) {
    // noop
  } else if (hasCallback && succeeded) {
      _resolve(promise, value);
    } else if (failed) {
      _reject(promise, error);
    } else if (settled === FULFILLED) {
      fulfill(promise, value);
    } else if (settled === REJECTED) {
      _reject(promise, value);
    }
}

function initializePromise(promise, resolver) {
  try {
    resolver(function resolvePromise(value) {
      _resolve(promise, value);
    }, function rejectPromise(reason) {
      _reject(promise, reason);
    });
  } catch (e) {
    _reject(promise, e);
  }
}

var id = 0;
function nextId() {
  return id++;
}

function makePromise(promise) {
  promise[PROMISE_ID] = id++;
  promise._state = undefined;
  promise._result = undefined;
  promise._subscribers = [];
}

function Enumerator(Constructor, input) {
  this._instanceConstructor = Constructor;
  this.promise = new Constructor(noop);

  if (!this.promise[PROMISE_ID]) {
    makePromise(this.promise);
  }

  if (isArray(input)) {
    this._input = input;
    this.length = input.length;
    this._remaining = input.length;

    this._result = new Array(this.length);

    if (this.length === 0) {
      fulfill(this.promise, this._result);
    } else {
      this.length = this.length || 0;
      this._enumerate();
      if (this._remaining === 0) {
        fulfill(this.promise, this._result);
      }
    }
  } else {
    _reject(this.promise, validationError());
  }
}

function validationError() {
  return new Error('Array Methods must be provided an Array');
};

Enumerator.prototype._enumerate = function () {
  var length = this.length;
  var _input = this._input;

  for (var i = 0; this._state === PENDING && i < length; i++) {
    this._eachEntry(_input[i], i);
  }
};

Enumerator.prototype._eachEntry = function (entry, i) {
  var c = this._instanceConstructor;
  var resolve$$ = c.resolve;

  if (resolve$$ === resolve) {
    var _then = getThen(entry);

    if (_then === then && entry._state !== PENDING) {
      this._settledAt(entry._state, i, entry._result);
    } else if (typeof _then !== 'function') {
      this._remaining--;
      this._result[i] = entry;
    } else if (c === Promise) {
      var promise = new c(noop);
      handleMaybeThenable(promise, entry, _then);
      this._willSettleAt(promise, i);
    } else {
      this._willSettleAt(new c(function (resolve$$) {
        return resolve$$(entry);
      }), i);
    }
  } else {
    this._willSettleAt(resolve$$(entry), i);
  }
};

Enumerator.prototype._settledAt = function (state, i, value) {
  var promise = this.promise;

  if (promise._state === PENDING) {
    this._remaining--;

    if (state === REJECTED) {
      _reject(promise, value);
    } else {
      this._result[i] = value;
    }
  }

  if (this._remaining === 0) {
    fulfill(promise, this._result);
  }
};

Enumerator.prototype._willSettleAt = function (promise, i) {
  var enumerator = this;

  subscribe(promise, undefined, function (value) {
    return enumerator._settledAt(FULFILLED, i, value);
  }, function (reason) {
    return enumerator._settledAt(REJECTED, i, reason);
  });
};

/**
  `Promise.all` accepts an array of promises, and returns a new promise which
  is fulfilled with an array of fulfillment values for the passed promises, or
  rejected with the reason of the first passed promise to be rejected. It casts all
  elements of the passed iterable to promises as it runs this algorithm.

  Example:

  ```javascript
  let promise1 = resolve(1);
  let promise2 = resolve(2);
  let promise3 = resolve(3);
  let promises = [ promise1, promise2, promise3 ];

  Promise.all(promises).then(function(array){
    // The array here would be [ 1, 2, 3 ];
  });
  ```

  If any of the `promises` given to `all` are rejected, the first promise
  that is rejected will be given as an argument to the returned promises's
  rejection handler. For example:

  Example:

  ```javascript
  let promise1 = resolve(1);
  let promise2 = reject(new Error("2"));
  let promise3 = reject(new Error("3"));
  let promises = [ promise1, promise2, promise3 ];

  Promise.all(promises).then(function(array){
    // Code here never runs because there are rejected promises!
  }, function(error) {
    // error.message === "2"
  });
  ```

  @method all
  @static
  @param {Array} entries array of promises
  @param {String} label optional string for labeling the promise.
  Useful for tooling.
  @return {Promise} promise that is fulfilled when all `promises` have been
  fulfilled, or rejected if any of them become rejected.
  @static
*/
function all(entries) {
  return new Enumerator(this, entries).promise;
}

/**
  `Promise.race` returns a new promise which is settled in the same way as the
  first passed promise to settle.

  Example:

  ```javascript
  let promise1 = new Promise(function(resolve, reject){
    setTimeout(function(){
      resolve('promise 1');
    }, 200);
  });

  let promise2 = new Promise(function(resolve, reject){
    setTimeout(function(){
      resolve('promise 2');
    }, 100);
  });

  Promise.race([promise1, promise2]).then(function(result){
    // result === 'promise 2' because it was resolved before promise1
    // was resolved.
  });
  ```

  `Promise.race` is deterministic in that only the state of the first
  settled promise matters. For example, even if other promises given to the
  `promises` array argument are resolved, but the first settled promise has
  become rejected before the other promises became fulfilled, the returned
  promise will become rejected:

  ```javascript
  let promise1 = new Promise(function(resolve, reject){
    setTimeout(function(){
      resolve('promise 1');
    }, 200);
  });

  let promise2 = new Promise(function(resolve, reject){
    setTimeout(function(){
      reject(new Error('promise 2'));
    }, 100);
  });

  Promise.race([promise1, promise2]).then(function(result){
    // Code here never runs
  }, function(reason){
    // reason.message === 'promise 2' because promise 2 became rejected before
    // promise 1 became fulfilled
  });
  ```

  An example real-world use case is implementing timeouts:

  ```javascript
  Promise.race([ajax('foo.json'), timeout(5000)])
  ```

  @method race
  @static
  @param {Array} promises array of promises to observe
  Useful for tooling.
  @return {Promise} a promise which settles in the same way as the first passed
  promise to settle.
*/
function race(entries) {
  /*jshint validthis:true */
  var Constructor = this;

  if (!isArray(entries)) {
    return new Constructor(function (_, reject) {
      return reject(new TypeError('You must pass an array to race.'));
    });
  } else {
    return new Constructor(function (resolve, reject) {
      var length = entries.length;
      for (var i = 0; i < length; i++) {
        Constructor.resolve(entries[i]).then(resolve, reject);
      }
    });
  }
}

/**
  `Promise.reject` returns a promise rejected with the passed `reason`.
  It is shorthand for the following:

  ```javascript
  let promise = new Promise(function(resolve, reject){
    reject(new Error('WHOOPS'));
  });

  promise.then(function(value){
    // Code here doesn't run because the promise is rejected!
  }, function(reason){
    // reason.message === 'WHOOPS'
  });
  ```

  Instead of writing the above, your code now simply becomes the following:

  ```javascript
  let promise = Promise.reject(new Error('WHOOPS'));

  promise.then(function(value){
    // Code here doesn't run because the promise is rejected!
  }, function(reason){
    // reason.message === 'WHOOPS'
  });
  ```

  @method reject
  @static
  @param {Any} reason value that the returned promise will be rejected with.
  Useful for tooling.
  @return {Promise} a promise rejected with the given `reason`.
*/
function reject(reason) {
  /*jshint validthis:true */
  var Constructor = this;
  var promise = new Constructor(noop);
  _reject(promise, reason);
  return promise;
}

function needsResolver() {
  throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}

function needsNew() {
  throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}

/**
  Promise objects represent the eventual result of an asynchronous operation. The
  primary way of interacting with a promise is through its `then` method, which
  registers callbacks to receive either a promise's eventual value or the reason
  why the promise cannot be fulfilled.

  Terminology
  -----------

  - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  - `thenable` is an object or function that defines a `then` method.
  - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  - `exception` is a value that is thrown using the throw statement.
  - `reason` is a value that indicates why a promise was rejected.
  - `settled` the final resting state of a promise, fulfilled or rejected.

  A promise can be in one of three states: pending, fulfilled, or rejected.

  Promises that are fulfilled have a fulfillment value and are in the fulfilled
  state.  Promises that are rejected have a rejection reason and are in the
  rejected state.  A fulfillment value is never a thenable.

  Promises can also be said to *resolve* a value.  If this value is also a
  promise, then the original promise's settled state will match the value's
  settled state.  So a promise that *resolves* a promise that rejects will
  itself reject, and a promise that *resolves* a promise that fulfills will
  itself fulfill.


  Basic Usage:
  ------------

  ```js
  let promise = new Promise(function(resolve, reject) {
    // on success
    resolve(value);

    // on failure
    reject(reason);
  });

  promise.then(function(value) {
    // on fulfillment
  }, function(reason) {
    // on rejection
  });
  ```

  Advanced Usage:
  ---------------

  Promises shine when abstracting away asynchronous interactions such as
  `XMLHttpRequest`s.

  ```js
  function getJSON(url) {
    return new Promise(function(resolve, reject){
      let xhr = new XMLHttpRequest();

      xhr.open('GET', url);
      xhr.onreadystatechange = handler;
      xhr.responseType = 'json';
      xhr.setRequestHeader('Accept', 'application/json');
      xhr.send();

      function handler() {
        if (this.readyState === this.DONE) {
          if (this.status === 200) {
            resolve(this.response);
          } else {
            reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
          }
        }
      };
    });
  }

  getJSON('/posts.json').then(function(json) {
    // on fulfillment
  }, function(reason) {
    // on rejection
  });
  ```

  Unlike callbacks, promises are great composable primitives.

  ```js
  Promise.all([
    getJSON('/posts'),
    getJSON('/comments')
  ]).then(function(values){
    values[0] // => postsJSON
    values[1] // => commentsJSON

    return values;
  });
  ```

  @class Promise
  @param {function} resolver
  Useful for tooling.
  @constructor
*/
function Promise(resolver) {
  this[PROMISE_ID] = nextId();
  this._result = this._state = undefined;
  this._subscribers = [];

  if (noop !== resolver) {
    typeof resolver !== 'function' && needsResolver();
    this instanceof Promise ? initializePromise(this, resolver) : needsNew();
  }
}

Promise.all = all;
Promise.race = race;
Promise.resolve = resolve;
Promise.reject = reject;
Promise._setScheduler = setScheduler;
Promise._setAsap = setAsap;
Promise._asap = asap;

Promise.prototype = {
  constructor: Promise,

  /**
    The primary way of interacting with a promise is through its `then` method,
    which registers callbacks to receive either a promise's eventual value or the
    reason why the promise cannot be fulfilled.
  
    ```js
    findUser().then(function(user){
      // user is available
    }, function(reason){
      // user is unavailable, and you are given the reason why
    });
    ```
  
    Chaining
    --------
  
    The return value of `then` is itself a promise.  This second, 'downstream'
    promise is resolved with the return value of the first promise's fulfillment
    or rejection handler, or rejected if the handler throws an exception.
  
    ```js
    findUser().then(function (user) {
      return user.name;
    }, function (reason) {
      return 'default name';
    }).then(function (userName) {
      // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
      // will be `'default name'`
    });
  
    findUser().then(function (user) {
      throw new Error('Found user, but still unhappy');
    }, function (reason) {
      throw new Error('`findUser` rejected and we're unhappy');
    }).then(function (value) {
      // never reached
    }, function (reason) {
      // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
      // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
    });
    ```
    If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  
    ```js
    findUser().then(function (user) {
      throw new PedagogicalException('Upstream error');
    }).then(function (value) {
      // never reached
    }).then(function (value) {
      // never reached
    }, function (reason) {
      // The `PedgagocialException` is propagated all the way down to here
    });
    ```
  
    Assimilation
    ------------
  
    Sometimes the value you want to propagate to a downstream promise can only be
    retrieved asynchronously. This can be achieved by returning a promise in the
    fulfillment or rejection handler. The downstream promise will then be pending
    until the returned promise is settled. This is called *assimilation*.
  
    ```js
    findUser().then(function (user) {
      return findCommentsByAuthor(user);
    }).then(function (comments) {
      // The user's comments are now available
    });
    ```
  
    If the assimliated promise rejects, then the downstream promise will also reject.
  
    ```js
    findUser().then(function (user) {
      return findCommentsByAuthor(user);
    }).then(function (comments) {
      // If `findCommentsByAuthor` fulfills, we'll have the value here
    }, function (reason) {
      // If `findCommentsByAuthor` rejects, we'll have the reason here
    });
    ```
  
    Simple Example
    --------------
  
    Synchronous Example
  
    ```javascript
    let result;
  
    try {
      result = findResult();
      // success
    } catch(reason) {
      // failure
    }
    ```
  
    Errback Example
  
    ```js
    findResult(function(result, err){
      if (err) {
        // failure
      } else {
        // success
      }
    });
    ```
  
    Promise Example;
  
    ```javascript
    findResult().then(function(result){
      // success
    }, function(reason){
      // failure
    });
    ```
  
    Advanced Example
    --------------
  
    Synchronous Example
  
    ```javascript
    let author, books;
  
    try {
      author = findAuthor();
      books  = findBooksByAuthor(author);
      // success
    } catch(reason) {
      // failure
    }
    ```
  
    Errback Example
  
    ```js
  
    function foundBooks(books) {
  
    }
  
    function failure(reason) {
  
    }
  
    findAuthor(function(author, err){
      if (err) {
        failure(err);
        // failure
      } else {
        try {
          findBoooksByAuthor(author, function(books, err) {
            if (err) {
              failure(err);
            } else {
              try {
                foundBooks(books);
              } catch(reason) {
                failure(reason);
              }
            }
          });
        } catch(error) {
          failure(err);
        }
        // success
      }
    });
    ```
  
    Promise Example;
  
    ```javascript
    findAuthor().
      then(findBooksByAuthor).
      then(function(books){
        // found books
    }).catch(function(reason){
      // something went wrong
    });
    ```
  
    @method then
    @param {Function} onFulfilled
    @param {Function} onRejected
    Useful for tooling.
    @return {Promise}
  */
  then: then,

  /**
    `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
    as the catch block of a try/catch statement.
  
    ```js
    function findAuthor(){
      throw new Error('couldn't find that author');
    }
  
    // synchronous
    try {
      findAuthor();
    } catch(reason) {
      // something went wrong
    }
  
    // async with promises
    findAuthor().catch(function(reason){
      // something went wrong
    });
    ```
  
    @method catch
    @param {Function} onRejection
    Useful for tooling.
    @return {Promise}
  */
  'catch': function _catch(onRejection) {
    return this.then(null, onRejection);
  }
};

function polyfill() {
    var local = undefined;

    if (typeof global !== 'undefined') {
        local = global;
    } else if (typeof self !== 'undefined') {
        local = self;
    } else {
        try {
            local = Function('return this')();
        } catch (e) {
            throw new Error('polyfill failed because global object is unavailable in this environment');
        }
    }

    var P = local.Promise;

    if (P) {
        var promiseToString = null;
        try {
            promiseToString = Object.prototype.toString.call(P.resolve());
        } catch (e) {
            // silently ignored
        }

        if (promiseToString === '[object Promise]' && !P.cast) {
            return;
        }
    }

    local.Promise = Promise;
}

polyfill();
// Strange compat..
Promise.polyfill = polyfill;
Promise.Promise = Promise;

return Promise;

})));

}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":468}],205:[function(_dereq_,module,exports){
'use strict';

module.exports = _dereq_('./is-implemented')() ? Symbol : _dereq_('./polyfill');

},{"./is-implemented":206,"./polyfill":208}],206:[function(_dereq_,module,exports){
'use strict';

var validTypes = { object: true, symbol: true };

module.exports = function () {
	var symbol;
	if (typeof Symbol !== 'function') return false;
	symbol = Symbol('test symbol');
	try { String(symbol); } catch (e) { return false; }

	// Return 'true' also for polyfills
	if (!validTypes[typeof Symbol.iterator]) return false;
	if (!validTypes[typeof Symbol.toPrimitive]) return false;
	if (!validTypes[typeof Symbol.toStringTag]) return false;

	return true;
};

},{}],207:[function(_dereq_,module,exports){
'use strict';

module.exports = function (x) {
	if (!x) return false;
	if (typeof x === 'symbol') return true;
	if (!x.constructor) return false;
	if (x.constructor.name !== 'Symbol') return false;
	return (x[x.constructor.toStringTag] === 'Symbol');
};

},{}],208:[function(_dereq_,module,exports){
// ES2015 Symbol polyfill for environments that do not (or partially) support it

'use strict';

var d              = _dereq_('d')
  , validateSymbol = _dereq_('./validate-symbol')

  , create = Object.create, defineProperties = Object.defineProperties
  , defineProperty = Object.defineProperty, objPrototype = Object.prototype
  , NativeSymbol, SymbolPolyfill, HiddenSymbol, globalSymbols = create(null)
  , isNativeSafe;

if (typeof Symbol === 'function') {
	NativeSymbol = Symbol;
	try {
		String(NativeSymbol());
		isNativeSafe = true;
	} catch (ignore) {}
}

var generateName = (function () {
	var created = create(null);
	return function (desc) {
		var postfix = 0, name, ie11BugWorkaround;
		while (created[desc + (postfix || '')]) ++postfix;
		desc += (postfix || '');
		created[desc] = true;
		name = '@@' + desc;
		defineProperty(objPrototype, name, d.gs(null, function (value) {
			// For IE11 issue see:
			// https://connect.microsoft.com/IE/feedbackdetail/view/1928508/
			//    ie11-broken-getters-on-dom-objects
			// https://github.com/medikoo/es6-symbol/issues/12
			if (ie11BugWorkaround) return;
			ie11BugWorkaround = true;
			defineProperty(this, name, d(value));
			ie11BugWorkaround = false;
		}));
		return name;
	};
}());

// Internal constructor (not one exposed) for creating Symbol instances.
// This one is used to ensure that `someSymbol instanceof Symbol` always return false
HiddenSymbol = function Symbol(description) {
	if (this instanceof HiddenSymbol) throw new TypeError('Symbol is not a constructor');
	return SymbolPolyfill(description);
};

// Exposed `Symbol` constructor
// (returns instances of HiddenSymbol)
module.exports = SymbolPolyfill = function Symbol(description) {
	var symbol;
	if (this instanceof Symbol) throw new TypeError('Symbol is not a constructor');
	if (isNativeSafe) return NativeSymbol(description);
	symbol = create(HiddenSymbol.prototype);
	description = (description === undefined ? '' : String(description));
	return defineProperties(symbol, {
		__description__: d('', description),
		__name__: d('', generateName(description))
	});
};
defineProperties(SymbolPolyfill, {
	for: d(function (key) {
		if (globalSymbols[key]) return globalSymbols[key];
		return (globalSymbols[key] = SymbolPolyfill(String(key)));
	}),
	keyFor: d(function (s) {
		var key;
		validateSymbol(s);
		for (key in globalSymbols) if (globalSymbols[key] === s) return key;
	}),

	// To ensure proper interoperability with other native functions (e.g. Array.from)
	// fallback to eventual native implementation of given symbol
	hasInstance: d('', (NativeSymbol && NativeSymbol.hasInstance) || SymbolPolyfill('hasInstance')),
	isConcatSpreadable: d('', (NativeSymbol && NativeSymbol.isConcatSpreadable) ||
		SymbolPolyfill('isConcatSpreadable')),
	iterator: d('', (NativeSymbol && NativeSymbol.iterator) || SymbolPolyfill('iterator')),
	match: d('', (NativeSymbol && NativeSymbol.match) || SymbolPolyfill('match')),
	replace: d('', (NativeSymbol && NativeSymbol.replace) || SymbolPolyfill('replace')),
	search: d('', (NativeSymbol && NativeSymbol.search) || SymbolPolyfill('search')),
	species: d('', (NativeSymbol && NativeSymbol.species) || SymbolPolyfill('species')),
	split: d('', (NativeSymbol && NativeSymbol.split) || SymbolPolyfill('split')),
	toPrimitive: d('', (NativeSymbol && NativeSymbol.toPrimitive) || SymbolPolyfill('toPrimitive')),
	toStringTag: d('', (NativeSymbol && NativeSymbol.toStringTag) || SymbolPolyfill('toStringTag')),
	unscopables: d('', (NativeSymbol && NativeSymbol.unscopables) || SymbolPolyfill('unscopables'))
});

// Internal tweaks for real symbol producer
defineProperties(HiddenSymbol.prototype, {
	constructor: d(SymbolPolyfill),
	toString: d('', function () { return this.__name__; })
});

// Proper implementation of methods exposed on Symbol.prototype
// They won't be accessible on produced symbol instances as they derive from HiddenSymbol.prototype
defineProperties(SymbolPolyfill.prototype, {
	toString: d(function () { return 'Symbol (' + validateSymbol(this).__description__ + ')'; }),
	valueOf: d(function () { return validateSymbol(this); })
});
defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toPrimitive, d('', function () {
	var symbol = validateSymbol(this);
	if (typeof symbol === 'symbol') return symbol;
	return symbol.toString();
}));
defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, d('c', 'Symbol'));

// Proper implementaton of toPrimitive and toStringTag for returned symbol instances
defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toStringTag,
	d('c', SymbolPolyfill.prototype[SymbolPolyfill.toStringTag]));

// Note: It's important to define `toPrimitive` as last one, as some implementations
// implement `toPrimitive` natively without implementing `toStringTag` (or other specified symbols)
// And that may invoke error in definition flow:
// See: https://github.com/medikoo/es6-symbol/issues/13#issuecomment-164146149
defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toPrimitive,
	d('c', SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive]));

},{"./validate-symbol":209,"d":140}],209:[function(_dereq_,module,exports){
'use strict';

var isSymbol = _dereq_('./is-symbol');

module.exports = function (value) {
	if (!isSymbol(value)) throw new TypeError(value + " is not a symbol");
	return value;
};

},{"./is-symbol":207}],210:[function(_dereq_,module,exports){
'use strict';

module.exports = _dereq_('./is-implemented')() ? WeakMap : _dereq_('./polyfill');

},{"./is-implemented":211,"./polyfill":213}],211:[function(_dereq_,module,exports){
'use strict';

module.exports = function () {
	var weakMap, x;
	if (typeof WeakMap !== 'function') return false;
	try {
		// WebKit doesn't support arguments and crashes
		weakMap = new WeakMap([[x = {}, 'one'], [{}, 'two'], [{}, 'three']]);
	} catch (e) {
		return false;
	}
	if (String(weakMap) !== '[object WeakMap]') return false;
	if (typeof weakMap.set !== 'function') return false;
	if (weakMap.set({}, 1) !== weakMap) return false;
	if (typeof weakMap.delete !== 'function') return false;
	if (typeof weakMap.has !== 'function') return false;
	if (weakMap.get(x) !== 'one') return false;

	return true;
};

},{}],212:[function(_dereq_,module,exports){
// Exports true if environment provides native `WeakMap` implementation, whatever that is.

'use strict';

module.exports = (function () {
	if (typeof WeakMap !== 'function') return false;
	return (Object.prototype.toString.call(new WeakMap()) === '[object WeakMap]');
}());

},{}],213:[function(_dereq_,module,exports){
'use strict';

var setPrototypeOf    = _dereq_('es5-ext/object/set-prototype-of')
  , object            = _dereq_('es5-ext/object/valid-object')
  , value             = _dereq_('es5-ext/object/valid-value')
  , randomUniq        = _dereq_('es5-ext/string/random-uniq')
  , d                 = _dereq_('d')
  , getIterator       = _dereq_('es6-iterator/get')
  , forOf             = _dereq_('es6-iterator/for-of')
  , toStringTagSymbol = _dereq_('es6-symbol').toStringTag
  , isNative          = _dereq_('./is-native-implemented')

  , isArray = Array.isArray, defineProperty = Object.defineProperty
  , hasOwnProperty = Object.prototype.hasOwnProperty, getPrototypeOf = Object.getPrototypeOf
  , WeakMapPoly;

module.exports = WeakMapPoly = function (/*iterable*/) {
	var iterable = arguments[0], self;
	if (!(this instanceof WeakMapPoly)) throw new TypeError('Constructor requires \'new\'');
	if (isNative && setPrototypeOf && (WeakMap !== WeakMapPoly)) {
		self = setPrototypeOf(new WeakMap(), getPrototypeOf(this));
	} else {
		self = this;
	}
	if (iterable != null) {
		if (!isArray(iterable)) iterable = getIterator(iterable);
	}
	defineProperty(self, '__weakMapData__', d('c', '$weakMap$' + randomUniq()));
	if (!iterable) return self;
	forOf(iterable, function (val) {
		value(val);
		self.set(val[0], val[1]);
	});
	return self;
};

if (isNative) {
	if (setPrototypeOf) setPrototypeOf(WeakMapPoly, WeakMap);
	WeakMapPoly.prototype = Object.create(WeakMap.prototype, {
		constructor: d(WeakMapPoly)
	});
}

Object.defineProperties(WeakMapPoly.prototype, {
	delete: d(function (key) {
		if (hasOwnProperty.call(object(key), this.__weakMapData__)) {
			delete key[this.__weakMapData__];
			return true;
		}
		return false;
	}),
	get: d(function (key) {
		if (hasOwnProperty.call(object(key), this.__weakMapData__)) {
			return key[this.__weakMapData__];
		}
	}),
	has: d(function (key) {
		return hasOwnProperty.call(object(key), this.__weakMapData__);
	}),
	set: d(function (key, value) {
		defineProperty(object(key), this.__weakMapData__, d('c', value));
		return this;
	}),
	toString: d(function () { return '[object WeakMap]'; })
});
defineProperty(WeakMapPoly.prototype, toStringTagSymbol, d('c', 'WeakMap'));

},{"./is-native-implemented":212,"d":140,"es5-ext/object/set-prototype-of":186,"es5-ext/object/valid-object":190,"es5-ext/object/valid-value":191,"es5-ext/string/random-uniq":196,"es6-iterator/for-of":198,"es6-iterator/get":199,"es6-symbol":205}],214:[function(_dereq_,module,exports){
"use strict"

module.exports = extractPlanes

function extractPlanes(M, zNear, zFar) {
  var z  = zNear || 0.0
  var zf = zFar || 1.0
  return [
    [ M[12] + M[0], M[13] + M[1], M[14] + M[2], M[15] + M[3] ],
    [ M[12] - M[0], M[13] - M[1], M[14] - M[2], M[15] - M[3] ],
    [ M[12] + M[4], M[13] + M[5], M[14] + M[6], M[15] + M[7] ],
    [ M[12] - M[4], M[13] - M[5], M[14] - M[6], M[15] - M[7] ],
    [ z*M[12] + M[8], z*M[13] + M[9], z*M[14] + M[10], z*M[15] + M[11] ],
    [ zf*M[12] - M[8], zf*M[13] - M[9], zf*M[14] - M[10], zf*M[15] - M[11] ]
  ]
}
},{}],215:[function(_dereq_,module,exports){
/**
 * inspired by is-number <https://github.com/jonschlinkert/is-number>
 * but significantly simplified and sped up by ignoring number and string constructors
 * ie these return false:
 *   new Number(1)
 *   new String('1')
 */

'use strict';

var allBlankCharCodes = _dereq_('is-string-blank');

module.exports = function(n) {
    var type = typeof n;
    if(type === 'string') {
        var original = n;
        n = +n;
        // whitespace strings cast to zero - filter them out
        if(n===0 && allBlankCharCodes(original)) return false;
    }
    else if(type !== 'number') return false;

    return n - n < 1;
};

},{"is-string-blank":409}],216:[function(_dereq_,module,exports){
'use strict'

module.exports = createFilteredVector

var cubicHermite = _dereq_('cubic-hermite')
var bsearch = _dereq_('binary-search-bounds')

function clamp(lo, hi, x) {
  return Math.min(hi, Math.max(lo, x))
}

function FilteredVector(state0, velocity0, t0) {
  this.dimension  = state0.length
  this.bounds     = [ new Array(this.dimension), new Array(this.dimension) ]
  for(var i=0; i<this.dimension; ++i) {
    this.bounds[0][i] = -Infinity
    this.bounds[1][i] = Infinity
  }
  this._state     = state0.slice().reverse()
  this._velocity  = velocity0.slice().reverse()
  this._time      = [ t0 ]
  this._scratch   = [ state0.slice(), state0.slice(), state0.slice(), state0.slice(), state0.slice() ]
}

var proto = FilteredVector.prototype

proto.flush = function(t) {
  var idx = bsearch.gt(this._time, t) - 1
  if(idx <= 0) {
    return
  }
  this._time.splice(0, idx)
  this._state.splice(0, idx * this.dimension)
  this._velocity.splice(0, idx * this.dimension)
}

proto.curve = function(t) {
  var time      = this._time
  var n         = time.length
  var idx       = bsearch.le(time, t)
  var result    = this._scratch[0]
  var state     = this._state
  var velocity  = this._velocity
  var d         = this.dimension
  var bounds    = this.bounds
  if(idx < 0) {
    var ptr = d-1
    for(var i=0; i<d; ++i, --ptr) {
      result[i] = state[ptr]
    }
  } else if(idx >= n-1) {
    var ptr = state.length-1
    var tf = t - time[n-1]
    for(var i=0; i<d; ++i, --ptr) {
      result[i] = state[ptr] + tf * velocity[ptr]
    }
  } else {
    var ptr = d * (idx+1) - 1
    var t0  = time[idx]
    var t1  = time[idx+1]
    var dt  = (t1 - t0) || 1.0
    var x0  = this._scratch[1]
    var x1  = this._scratch[2]
    var v0  = this._scratch[3]
    var v1  = this._scratch[4]
    var steady = true
    for(var i=0; i<d; ++i, --ptr) {
      x0[i] = state[ptr]
      v0[i] = velocity[ptr] * dt
      x1[i] = state[ptr+d]
      v1[i] = velocity[ptr+d] * dt
      steady = steady && (x0[i] === x1[i] && v0[i] === v1[i] && v0[i] === 0.0)
    }
    if(steady) {
      for(var i=0; i<d; ++i) {
        result[i] = x0[i]
      }
    } else {
      cubicHermite(x0, v0, x1, v1, (t-t0)/dt, result)
    }
  }
  var lo = bounds[0]
  var hi = bounds[1]
  for(var i=0; i<d; ++i) {
    result[i] = clamp(lo[i], hi[i], result[i])
  }
  return result
}

proto.dcurve = function(t) {
  var time     = this._time
  var n        = time.length
  var idx      = bsearch.le(time, t)
  var result   = this._scratch[0]
  var state    = this._state
  var velocity = this._velocity
  var d        = this.dimension
  if(idx >= n-1) {
    var ptr = state.length-1
    var tf = t - time[n-1]
    for(var i=0; i<d; ++i, --ptr) {
      result[i] = velocity[ptr]
    }
  } else {
    var ptr = d * (idx+1) - 1
    var t0 = time[idx]
    var t1 = time[idx+1]
    var dt = (t1 - t0) || 1.0
    var x0 = this._scratch[1]
    var x1 = this._scratch[2]
    var v0 = this._scratch[3]
    var v1 = this._scratch[4]
    var steady = true
    for(var i=0; i<d; ++i, --ptr) {
      x0[i] = state[ptr]
      v0[i] = velocity[ptr] * dt
      x1[i] = state[ptr+d]
      v1[i] = velocity[ptr+d] * dt
      steady = steady && (x0[i] === x1[i] && v0[i] === v1[i] && v0[i] === 0.0)
    }
    if(steady) {
      for(var i=0; i<d; ++i) {
        result[i] = 0.0
      }
    } else {
      cubicHermite.derivative(x0, v0, x1, v1, (t-t0)/dt, result)
      for(var i=0; i<d; ++i) {
        result[i] /= dt
      }
    }
  }
  return result
}

proto.lastT = function() {
  var time = this._time
  return time[time.length-1]
}

proto.stable = function() {
  var velocity = this._velocity
  var ptr = velocity.length
  for(var i=this.dimension-1; i>=0; --i) {
    if(velocity[--ptr]) {
      return false
    }
  }
  return true
}

proto.jump = function(t) {
  var t0 = this.lastT()
  var d  = this.dimension
  if(t < t0 || arguments.length !== d+1) {
    return
  }
  var state     = this._state
  var velocity  = this._velocity
  var ptr       = state.length-this.dimension
  var bounds    = this.bounds
  var lo        = bounds[0]
  var hi        = bounds[1]
  this._time.push(t0, t)
  for(var j=0; j<2; ++j) {
    for(var i=0; i<d; ++i) {
      state.push(state[ptr++])
      velocity.push(0)
    }
  }
  this._time.push(t)
  for(var i=d; i>0; --i) {
    state.push(clamp(lo[i-1], hi[i-1], arguments[i]))
    velocity.push(0)
  }
}

proto.push = function(t) {
  var t0 = this.lastT()
  var d  = this.dimension
  if(t < t0 || arguments.length !== d+1) {
    return
  }
  var state     = this._state
  var velocity  = this._velocity
  var ptr       = state.length-this.dimension
  var dt        = t - t0
  var bounds    = this.bounds
  var lo        = bounds[0]
  var hi        = bounds[1]
  var sf        = (dt > 1e-6) ? 1/dt : 0
  this._time.push(t)
  for(var i=d; i>0; --i) {
    var xc = clamp(lo[i-1], hi[i-1], arguments[i])
    state.push(xc)
    velocity.push((xc - state[ptr++]) * sf)
  }
}

proto.set = function(t) {
  var d = this.dimension
  if(t < this.lastT() || arguments.length !== d+1) {
    return
  }
  var state     = this._state
  var velocity  = this._velocity
  var bounds    = this.bounds
  var lo        = bounds[0]
  var hi        = bounds[1]
  this._time.push(t)
  for(var i=d; i>0; --i) {
    state.push(clamp(lo[i-1], hi[i-1], arguments[i]))
    velocity.push(0)
  }
}

proto.move = function(t) {
  var t0 = this.lastT()
  var d  = this.dimension
  if(t <= t0 || arguments.length !== d+1) {
    return
  }
  var state    = this._state
  var velocity = this._velocity
  var statePtr = state.length - this.dimension
  var bounds   = this.bounds
  var lo       = bounds[0]
  var hi       = bounds[1]
  var dt       = t - t0
  var sf       = (dt > 1e-6) ? 1/dt : 0.0
  this._time.push(t)
  for(var i=d; i>0; --i) {
    var dx = arguments[i]
    state.push(clamp(lo[i-1], hi[i-1], state[statePtr++] + dx))
    velocity.push(dx * sf)
  }
}

proto.idle = function(t) {
  var t0 = this.lastT()
  if(t < t0) {
    return
  }
  var d        = this.dimension
  var state    = this._state
  var velocity = this._velocity
  var statePtr = state.length-d
  var bounds   = this.bounds
  var lo       = bounds[0]
  var hi       = bounds[1]
  var dt       = t - t0
  this._time.push(t)
  for(var i=d-1; i>=0; --i) {
    state.push(clamp(lo[i], hi[i], state[statePtr] + dt * velocity[statePtr]))
    velocity.push(0)
    statePtr += 1
  }
}

function getZero(d) {
  var result = new Array(d)
  for(var i=0; i<d; ++i) {
    result[i] = 0.0
  }
  return result
}

function createFilteredVector(initState, initVelocity, initTime) {
  switch(arguments.length) {
    case 0:
      return new FilteredVector([0], [0], 0)
    case 1:
      if(typeof initState === 'number') {
        var zero = getZero(initState)
        return new FilteredVector(zero, zero, 0)
      } else {
        return new FilteredVector(initState, getZero(initState.length), 0)
      }
    case 2:
      if(typeof initVelocity === 'number') {
        var zero = getZero(initState.length)
        return new FilteredVector(initState, zero, +initVelocity)
      } else {
        initTime = 0
      }
    case 3:
      if(initState.length !== initVelocity.length) {
        throw new Error('state and velocity lengths must match')
      }
      return new FilteredVector(initState, initVelocity, initTime)
  }
}

},{"binary-search-bounds":80,"cubic-hermite":134}],217:[function(_dereq_,module,exports){
/*eslint new-cap:0*/
var dtype = _dereq_('dtype')

module.exports = flattenVertexData

function flattenVertexData (data, output, offset) {
  if (!data) throw new TypeError('must specify data as first parameter')
  offset = +(offset || 0) | 0

  if (Array.isArray(data) && (data[0] && typeof data[0][0] === 'number')) {
    var dim = data[0].length
    var length = data.length * dim
    var i, j, k, l

    // no output specified, create a new typed array
    if (!output || typeof output === 'string') {
      output = new (dtype(output || 'float32'))(length + offset)
    }

    var dstLength = output.length - offset
    if (length !== dstLength) {
      throw new Error('source length ' + length + ' (' + dim + 'x' + data.length + ')' +
        ' does not match destination length ' + dstLength)
    }

    for (i = 0, k = offset; i < data.length; i++) {
      for (j = 0; j < dim; j++) {
        output[k++] = data[i][j] === null ? NaN : data[i][j]
      }
    }
  } else {
    if (!output || typeof output === 'string') {
      // no output, create a new one
      var Ctor = dtype(output || 'float32')

      // handle arrays separately due to possible nulls
      if (Array.isArray(data) || output === 'array') {
        output = new Ctor(data.length + offset)
        for (i = 0, k = offset, l = output.length; k < l; k++, i++) {
          output[k] = data[i] === null ? NaN : data[i]
        }
      } else {
        if (offset === 0) {
          output = new Ctor(data)
        } else {
          output = new Ctor(data.length + offset)

          output.set(data, offset)
        }
      }
    } else {
      // store output in existing array
      output.set(data, offset)
    }
  }

  return output
}

},{"dtype":155}],218:[function(_dereq_,module,exports){
'use strict'

var stringifyFont = _dereq_('css-font/stringify')
var defaultChars = [32, 126]

module.exports = atlas

function atlas(options) {
  options = options || {}

  var shape  = options.shape ? options.shape : options.canvas ? [options.canvas.width, options.canvas.height] : [512, 512]
  var canvas = options.canvas || document.createElement('canvas')
  var font   = options.font
  var step   = typeof options.step === 'number' ? [options.step, options.step] : options.step || [32, 32]
  var chars  = options.chars || defaultChars

  if (font && typeof font !== 'string') font = stringifyFont(font)

  if (!Array.isArray(chars)) {
    chars = String(chars).split('')
  } else
  if (chars.length === 2
    && typeof chars[0] === 'number'
    && typeof chars[1] === 'number'
  ) {
    var newchars = []

    for (var i = chars[0], j = 0; i <= chars[1]; i++) {
      newchars[j++] = String.fromCharCode(i)
    }

    chars = newchars
  }

  shape = shape.slice()
  canvas.width  = shape[0]
  canvas.height = shape[1]

  var ctx = canvas.getContext('2d')

  ctx.fillStyle = '#000'
  ctx.fillRect(0, 0, canvas.width, canvas.height)

  ctx.font = font
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'
  ctx.fillStyle = '#fff'

  var x = step[0] / 2
  var y = step[1] / 2
  for (var i = 0; i < chars.length; i++) {
    ctx.fillText(chars[i], x, y)
    if ((x += step[0]) > shape[0] - step[0]/2) (x = step[0]/2), (y += step[1])
  }

  return canvas
}

},{"css-font/stringify":131}],219:[function(_dereq_,module,exports){
'use strict'

module.exports = measure

measure.canvas = document.createElement('canvas')
measure.cache = {}

function measure (font, o) {
	if (!o) o = {}

	if (typeof font === 'string' || Array.isArray(font)) {
		o.family = font
	}

	var family = Array.isArray(o.family) ? o.family.join(', ') : o.family
	if (!family) throw Error('`family` must be defined')

	var fs = o.size || o.fontSize || o.em || 48
	var weight = o.weight || o.fontWeight || ''
	var style = o.style || o.fontStyle || ''
	var font = [style, weight, fs].join(' ') + 'px ' + family
	var origin = o.origin || 'top'

	if (measure.cache[family]) {
		// return more precise values if cache has them
		if (fs <= measure.cache[family].em) {
			return applyOrigin(measure.cache[family], origin)
		}
	}

	var canvas = o.canvas || measure.canvas
	var ctx = canvas.getContext('2d')
	var chars = {
		upper: o.upper !== undefined ? o.upper : 'H',
		lower: o.lower !== undefined ? o.lower : 'x',
		descent: o.descent !== undefined ? o.descent : 'p',
		ascent: o.ascent !== undefined ? o.ascent : 'h',
		tittle: o.tittle !== undefined ? o.tittle : 'i',
		overshoot: o.overshoot !== undefined ? o.overshoot : 'O'
	}
	var l = Math.ceil(fs * 1.5)
	canvas.height = l
	canvas.width = l * .5
	ctx.font = font

	var char = 'H'
	var result = {
		top: 0
	}

	// measure line-height
	ctx.clearRect(0, 0, l, l)
	ctx.textBaseline = 'top'
	ctx.fillStyle = 'black'
	ctx.fillText(char, 0, 0)
	var topPx = firstTop(ctx.getImageData(0, 0, l, l))
	ctx.clearRect(0, 0, l, l)
	ctx.textBaseline = 'bottom'
	ctx.fillText(char, 0, l)
	var bottomPx = firstTop(ctx.getImageData(0, 0, l, l))
	result.lineHeight =
	result.bottom = l - bottomPx + topPx

	// measure baseline
	ctx.clearRect(0, 0, l, l)
	ctx.textBaseline = 'alphabetic'
	ctx.fillText(char, 0, l)
	var baselinePx = firstTop(ctx.getImageData(0, 0, l, l))
	var baseline = l - baselinePx - 1 + topPx
	result.baseline =
	result.alphabetic = baseline

	// measure median
	ctx.clearRect(0, 0, l, l)
	ctx.textBaseline = 'middle'
	ctx.fillText(char, 0, l * .5)
	var medianPx = firstTop(ctx.getImageData(0, 0, l, l))
	result.median =
	result.middle = l - medianPx - 1 + topPx - l * .5

	// measure hanging
	ctx.clearRect(0, 0, l, l)
	ctx.textBaseline = 'hanging'
	ctx.fillText(char, 0, l * .5)
	var hangingPx = firstTop(ctx.getImageData(0, 0, l, l))
	result.hanging = l - hangingPx - 1 + topPx - l * .5

	// measure ideographic
	ctx.clearRect(0, 0, l, l)
	ctx.textBaseline = 'ideographic'
	ctx.fillText(char, 0, l)
	var ideographicPx = firstTop(ctx.getImageData(0, 0, l, l))
	result.ideographic = l - ideographicPx - 1 + topPx

	// measure cap
	if (chars.upper) {
		ctx.clearRect(0, 0, l, l)
		ctx.textBaseline = 'top'
		ctx.fillText(chars.upper, 0, 0)
		result.upper = firstTop(ctx.getImageData(0, 0, l, l))
		result.capHeight = (result.baseline - result.upper)
	}

	// measure x
	if (chars.lower) {
		ctx.clearRect(0, 0, l, l)
		ctx.textBaseline = 'top'
		ctx.fillText(chars.lower, 0, 0)
		result.lower = firstTop(ctx.getImageData(0, 0, l, l))
		result.xHeight = (result.baseline - result.lower)
	}

	// measure tittle
	if (chars.tittle) {
		ctx.clearRect(0, 0, l, l)
		ctx.textBaseline = 'top'
		ctx.fillText(chars.tittle, 0, 0)
		result.tittle = firstTop(ctx.getImageData(0, 0, l, l))
	}

	// measure ascent
	if (chars.ascent) {
		ctx.clearRect(0, 0, l, l)
		ctx.textBaseline = 'top'
		ctx.fillText(chars.ascent, 0, 0)
		result.ascent = firstTop(ctx.getImageData(0, 0, l, l))
	}

	// measure descent
	if (chars.descent) {
		ctx.clearRect(0, 0, l, l)
		ctx.textBaseline = 'top'
		ctx.fillText(chars.descent, 0, 0)
		result.descent = firstBottom(ctx.getImageData(0, 0, l, l))
	}

	// measure overshoot
	if (chars.overshoot) {
		ctx.clearRect(0, 0, l, l)
		ctx.textBaseline = 'top'
		ctx.fillText(chars.overshoot, 0, 0)
		var overshootPx = firstBottom(ctx.getImageData(0, 0, l, l))
		result.overshoot = overshootPx - baseline
	}

	// normalize result
	for (var name in result) {
		result[name] /= fs
	}

	result.em = fs
	measure.cache[family] = result

	return applyOrigin(result, origin)
}

function applyOrigin(obj, origin) {
	var res = {}
	if (typeof origin === 'string') origin = obj[origin]
	for (var name in obj) {
		if (name === 'em') continue
		res[name] = obj[name] - origin
	}
	return res
}

function firstTop(iData) {
	var l = iData.height
	var data = iData.data
	for (var i = 3; i < data.length; i+=4) {
		if (data[i] !== 0) {
			return Math.floor((i - 3) *.25 / l)
		}
	}
}

function firstBottom(iData) {
	var l = iData.height
	var data = iData.data
	for (var i = data.length - 1; i > 0; i -= 4) {
		if (data[i] !== 0) {
			return Math.floor((i - 3) *.25 / l)
		}
	}
}

},{}],220:[function(_dereq_,module,exports){
"use strict"

module.exports = createRBTree

var RED   = 0
var BLACK = 1

function RBNode(color, key, value, left, right, count) {
  this._color = color
  this.key = key
  this.value = value
  this.left = left
  this.right = right
  this._count = count
}

function cloneNode(node) {
  return new RBNode(node._color, node.key, node.value, node.left, node.right, node._count)
}

function repaint(color, node) {
  return new RBNode(color, node.key, node.value, node.left, node.right, node._count)
}

function recount(node) {
  node._count = 1 + (node.left ? node.left._count : 0) + (node.right ? node.right._count : 0)
}

function RedBlackTree(compare, root) {
  this._compare = compare
  this.root = root
}

var proto = RedBlackTree.prototype

Object.defineProperty(proto, "keys", {
  get: function() {
    var result = []
    this.forEach(function(k,v) {
      result.push(k)
    })
    return result
  }
})

Object.defineProperty(proto, "values", {
  get: function() {
    var result = []
    this.forEach(function(k,v) {
      result.push(v)
    })
    return result
  }
})

//Returns the number of nodes in the tree
Object.defineProperty(proto, "length", {
  get: function() {
    if(this.root) {
      return this.root._count
    }
    return 0
  }
})

//Insert a new item into the tree
proto.insert = function(key, value) {
  var cmp = this._compare
  //Find point to insert new node at
  var n = this.root
  var n_stack = []
  var d_stack = []
  while(n) {
    var d = cmp(key, n.key)
    n_stack.push(n)
    d_stack.push(d)
    if(d <= 0) {
      n = n.left
    } else {
      n = n.right
    }
  }
  //Rebuild path to leaf node
  n_stack.push(new RBNode(RED, key, value, null, null, 1))
  for(var s=n_stack.length-2; s>=0; --s) {
    var n = n_stack[s]
    if(d_stack[s] <= 0) {
      n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s+1], n.right, n._count+1)
    } else {
      n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s+1], n._count+1)
    }
  }
  //Rebalance tree using rotations
  //console.log("start insert", key, d_stack)
  for(var s=n_stack.length-1; s>1; --s) {
    var p = n_stack[s-1]
    var n = n_stack[s]
    if(p._color === BLACK || n._color === BLACK) {
      break
    }
    var pp = n_stack[s-2]
    if(pp.left === p) {
      if(p.left === n) {
        var y = pp.right
        if(y && y._color === RED) {
          //console.log("LLr")
          p._color = BLACK
          pp.right = repaint(BLACK, y)
          pp._color = RED
          s -= 1
        } else {
          //console.log("LLb")
          pp._color = RED
          pp.left = p.right
          p._color = BLACK
          p.right = pp
          n_stack[s-2] = p
          n_stack[s-1] = n
          recount(pp)
          recount(p)
          if(s >= 3) {
            var ppp = n_stack[s-3]
            if(ppp.left === pp) {
              ppp.left = p
            } else {
              ppp.right = p
            }
          }
          break
        }
      } else {
        var y = pp.right
        if(y && y._color === RED) {
          //console.log("LRr")
          p._color = BLACK
          pp.right = repaint(BLACK, y)
          pp._color = RED
          s -= 1
        } else {
          //console.log("LRb")
          p.right = n.left
          pp._color = RED
          pp.left = n.right
          n._color = BLACK
          n.left = p
          n.right = pp
          n_stack[s-2] = n
          n_stack[s-1] = p
          recount(pp)
          recount(p)
          recount(n)
          if(s >= 3) {
            var ppp = n_stack[s-3]
            if(ppp.left === pp) {
              ppp.left = n
            } else {
              ppp.right = n
            }
          }
          break
        }
      }
    } else {
      if(p.right === n) {
        var y = pp.left
        if(y && y._color === RED) {
          //console.log("RRr", y.key)
          p._color = BLACK
          pp.left = repaint(BLACK, y)
          pp._color = RED
          s -= 1
        } else {
          //console.log("RRb")
          pp._color = RED
          pp.right = p.left
          p._color = BLACK
          p.left = pp
          n_stack[s-2] = p
          n_stack[s-1] = n
          recount(pp)
          recount(p)
          if(s >= 3) {
            var ppp = n_stack[s-3]
            if(ppp.right === pp) {
              ppp.right = p
            } else {
              ppp.left = p
            }
          }
          break
        }
      } else {
        var y = pp.left
        if(y && y._color === RED) {
          //console.log("RLr")
          p._color = BLACK
          pp.left = repaint(BLACK, y)
          pp._color = RED
          s -= 1
        } else {
          //console.log("RLb")
          p.left = n.right
          pp._color = RED
          pp.right = n.left
          n._color = BLACK
          n.right = p
          n.left = pp
          n_stack[s-2] = n
          n_stack[s-1] = p
          recount(pp)
          recount(p)
          recount(n)
          if(s >= 3) {
            var ppp = n_stack[s-3]
            if(ppp.right === pp) {
              ppp.right = n
            } else {
              ppp.left = n
            }
          }
          break
        }
      }
    }
  }
  //Return new tree
  n_stack[0]._color = BLACK
  return new RedBlackTree(cmp, n_stack[0])
}


//Visit all nodes inorder
function doVisitFull(visit, node) {
  if(node.left) {
    var v = doVisitFull(visit, node.left)
    if(v) { return v }
  }
  var v = visit(node.key, node.value)
  if(v) { return v }
  if(node.right) {
    return doVisitFull(visit, node.right)
  }
}

//Visit half nodes in order
function doVisitHalf(lo, compare, visit, node) {
  var l = compare(lo, node.key)
  if(l <= 0) {
    if(node.left) {
      var v = doVisitHalf(lo, compare, visit, node.left)
      if(v) { return v }
    }
    var v = visit(node.key, node.value)
    if(v) { return v }
  }
  if(node.right) {
    return doVisitHalf(lo, compare, visit, node.right)
  }
}

//Visit all nodes within a range
function doVisit(lo, hi, compare, visit, node) {
  var l = compare(lo, node.key)
  var h = compare(hi, node.key)
  var v
  if(l <= 0) {
    if(node.left) {
      v = doVisit(lo, hi, compare, visit, node.left)
      if(v) { return v }
    }
    if(h > 0) {
      v = visit(node.key, node.value)
      if(v) { return v }
    }
  }
  if(h > 0 && node.right) {
    return doVisit(lo, hi, compare, visit, node.right)
  }
}


proto.forEach = function rbTreeForEach(visit, lo, hi) {
  if(!this.root) {
    return
  }
  switch(arguments.length) {
    case 1:
      return doVisitFull(visit, this.root)
    break

    case 2:
      return doVisitHalf(lo, this._compare, visit, this.root)
    break

    case 3:
      if(this._compare(lo, hi) >= 0) {
        return
      }
      return doVisit(lo, hi, this._compare, visit, this.root)
    break
  }
}

//First item in list
Object.defineProperty(proto, "begin", {
  get: function() {
    var stack = []
    var n = this.root
    while(n) {
      stack.push(n)
      n = n.left
    }
    return new RedBlackTreeIterator(this, stack)
  }
})

//Last item in list
Object.defineProperty(proto, "end", {
  get: function() {
    var stack = []
    var n = this.root
    while(n) {
      stack.push(n)
      n = n.right
    }
    return new RedBlackTreeIterator(this, stack)
  }
})

//Find the ith item in the tree
proto.at = function(idx) {
  if(idx < 0) {
    return new RedBlackTreeIterator(this, [])
  }
  var n = this.root
  var stack = []
  while(true) {
    stack.push(n)
    if(n.left) {
      if(idx < n.left._count) {
        n = n.left
        continue
      }
      idx -= n.left._count
    }
    if(!idx) {
      return new RedBlackTreeIterator(this, stack)
    }
    idx -= 1
    if(n.right) {
      if(idx >= n.right._count) {
        break
      }
      n = n.right
    } else {
      break
    }
  }
  return new RedBlackTreeIterator(this, [])
}

proto.ge = function(key) {
  var cmp = this._compare
  var n = this.root
  var stack = []
  var last_ptr = 0
  while(n) {
    var d = cmp(key, n.key)
    stack.push(n)
    if(d <= 0) {
      last_ptr = stack.length
    }
    if(d <= 0) {
      n = n.left
    } else {
      n = n.right
    }
  }
  stack.length = last_ptr
  return new RedBlackTreeIterator(this, stack)
}

proto.gt = function(key) {
  var cmp = this._compare
  var n = this.root
  var stack = []
  var last_ptr = 0
  while(n) {
    var d = cmp(key, n.key)
    stack.push(n)
    if(d < 0) {
      last_ptr = stack.length
    }
    if(d < 0) {
      n = n.left
    } else {
      n = n.right
    }
  }
  stack.length = last_ptr
  return new RedBlackTreeIterator(this, stack)
}

proto.lt = function(key) {
  var cmp = this._compare
  var n = this.root
  var stack = []
  var last_ptr = 0
  while(n) {
    var d = cmp(key, n.key)
    stack.push(n)
    if(d > 0) {
      last_ptr = stack.length
    }
    if(d <= 0) {
      n = n.left
    } else {
      n = n.right
    }
  }
  stack.length = last_ptr
  return new RedBlackTreeIterator(this, stack)
}

proto.le = function(key) {
  var cmp = this._compare
  var n = this.root
  var stack = []
  var last_ptr = 0
  while(n) {
    var d = cmp(key, n.key)
    stack.push(n)
    if(d >= 0) {
      last_ptr = stack.length
    }
    if(d < 0) {
      n = n.left
    } else {
      n = n.right
    }
  }
  stack.length = last_ptr
  return new RedBlackTreeIterator(this, stack)
}

//Finds the item with key if it exists
proto.find = function(key) {
  var cmp = this._compare
  var n = this.root
  var stack = []
  while(n) {
    var d = cmp(key, n.key)
    stack.push(n)
    if(d === 0) {
      return new RedBlackTreeIterator(this, stack)
    }
    if(d <= 0) {
      n = n.left
    } else {
      n = n.right
    }
  }
  return new RedBlackTreeIterator(this, [])
}

//Removes item with key from tree
proto.remove = function(key) {
  var iter = this.find(key)
  if(iter) {
    return iter.remove()
  }
  return this
}

//Returns the item at `key`
proto.get = function(key) {
  var cmp = this._compare
  var n = this.root
  while(n) {
    var d = cmp(key, n.key)
    if(d === 0) {
      return n.value
    }
    if(d <= 0) {
      n = n.left
    } else {
      n = n.right
    }
  }
  return
}

//Iterator for red black tree
function RedBlackTreeIterator(tree, stack) {
  this.tree = tree
  this._stack = stack
}

var iproto = RedBlackTreeIterator.prototype

//Test if iterator is valid
Object.defineProperty(iproto, "valid", {
  get: function() {
    return this._stack.length > 0
  }
})

//Node of the iterator
Object.defineProperty(iproto, "node", {
  get: function() {
    if(this._stack.length > 0) {
      return this._stack[this._stack.length-1]
    }
    return null
  },
  enumerable: true
})

//Makes a copy of an iterator
iproto.clone = function() {
  return new RedBlackTreeIterator(this.tree, this._stack.slice())
}

//Swaps two nodes
function swapNode(n, v) {
  n.key = v.key
  n.value = v.value
  n.left = v.left
  n.right = v.right
  n._color = v._color
  n._count = v._count
}

//Fix up a double black node in a tree
function fixDoubleBlack(stack) {
  var n, p, s, z
  for(var i=stack.length-1; i>=0; --i) {
    n = stack[i]
    if(i === 0) {
      n._color = BLACK
      return
    }
    //console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key)
    p = stack[i-1]
    if(p.left === n) {
      //console.log("left child")
      s = p.right
      if(s.right && s.right._color === RED) {
        //console.log("case 1: right sibling child red")
        s = p.right = cloneNode(s)
        z = s.right = cloneNode(s.right)
        p.right = s.left
        s.left = p
        s.right = z
        s._color = p._color
        n._color = BLACK
        p._color = BLACK
        z._color = BLACK
        recount(p)
        recount(s)
        if(i > 1) {
          var pp = stack[i-2]
          if(pp.left === p) {
            pp.left = s
          } else {
            pp.right = s
          }
        }
        stack[i-1] = s
        return
      } else if(s.left && s.left._color === RED) {
        //console.log("case 1: left sibling child red")
        s = p.right = cloneNode(s)
        z = s.left = cloneNode(s.left)
        p.right = z.left
        s.left = z.right
        z.left = p
        z.right = s
        z._color = p._color
        p._color = BLACK
        s._color = BLACK
        n._color = BLACK
        recount(p)
        recount(s)
        recount(z)
        if(i > 1) {
          var pp = stack[i-2]
          if(pp.left === p) {
            pp.left = z
          } else {
            pp.right = z
          }
        }
        stack[i-1] = z
        return
      }
      if(s._color === BLACK) {
        if(p._color === RED) {
          //console.log("case 2: black sibling, red parent", p.right.value)
          p._color = BLACK
          p.right = repaint(RED, s)
          return
        } else {
          //console.log("case 2: black sibling, black parent", p.right.value)
          p.right = repaint(RED, s)
          continue  
        }
      } else {
        //console.log("case 3: red sibling")
        s = cloneNode(s)
        p.right = s.left
        s.left = p
        s._color = p._color
        p._color = RED
        recount(p)
        recount(s)
        if(i > 1) {
          var pp = stack[i-2]
          if(pp.left === p) {
            pp.left = s
          } else {
            pp.right = s
          }
        }
        stack[i-1] = s
        stack[i] = p
        if(i+1 < stack.length) {
          stack[i+1] = n
        } else {
          stack.push(n)
        }
        i = i+2
      }
    } else {
      //console.log("right child")
      s = p.left
      if(s.left && s.left._color === RED) {
        //console.log("case 1: left sibling child red", p.value, p._color)
        s = p.left = cloneNode(s)
        z = s.left = cloneNode(s.left)
        p.left = s.right
        s.right = p
        s.left = z
        s._color = p._color
        n._color = BLACK
        p._color = BLACK
        z._color = BLACK
        recount(p)
        recount(s)
        if(i > 1) {
          var pp = stack[i-2]
          if(pp.right === p) {
            pp.right = s
          } else {
            pp.left = s
          }
        }
        stack[i-1] = s
        return
      } else if(s.right && s.right._color === RED) {
        //console.log("case 1: right sibling child red")
        s = p.left = cloneNode(s)
        z = s.right = cloneNode(s.right)
        p.left = z.right
        s.right = z.left
        z.right = p
        z.left = s
        z._color = p._color
        p._color = BLACK
        s._color = BLACK
        n._color = BLACK
        recount(p)
        recount(s)
        recount(z)
        if(i > 1) {
          var pp = stack[i-2]
          if(pp.right === p) {
            pp.right = z
          } else {
            pp.left = z
          }
        }
        stack[i-1] = z
        return
      }
      if(s._color === BLACK) {
        if(p._color === RED) {
          //console.log("case 2: black sibling, red parent")
          p._color = BLACK
          p.left = repaint(RED, s)
          return
        } else {
          //console.log("case 2: black sibling, black parent")
          p.left = repaint(RED, s)
          continue  
        }
      } else {
        //console.log("case 3: red sibling")
        s = cloneNode(s)
        p.left = s.right
        s.right = p
        s._color = p._color
        p._color = RED
        recount(p)
        recount(s)
        if(i > 1) {
          var pp = stack[i-2]
          if(pp.right === p) {
            pp.right = s
          } else {
            pp.left = s
          }
        }
        stack[i-1] = s
        stack[i] = p
        if(i+1 < stack.length) {
          stack[i+1] = n
        } else {
          stack.push(n)
        }
        i = i+2
      }
    }
  }
}

//Removes item at iterator from tree
iproto.remove = function() {
  var stack = this._stack
  if(stack.length === 0) {
    return this.tree
  }
  //First copy path to node
  var cstack = new Array(stack.length)
  var n = stack[stack.length-1]
  cstack[cstack.length-1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count)
  for(var i=stack.length-2; i>=0; --i) {
    var n = stack[i]
    if(n.left === stack[i+1]) {
      cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count)
    } else {
      cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
    }
  }

  //Get node
  n = cstack[cstack.length-1]
  //console.log("start remove: ", n.value)

  //If not leaf, then swap with previous node
  if(n.left && n.right) {
    //console.log("moving to leaf")

    //First walk to previous leaf
    var split = cstack.length
    n = n.left
    while(n.right) {
      cstack.push(n)
      n = n.right
    }
    //Copy path to leaf
    var v = cstack[split-1]
    cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count))
    cstack[split-1].key = n.key
    cstack[split-1].value = n.value

    //Fix up stack
    for(var i=cstack.length-2; i>=split; --i) {
      n = cstack[i]
      cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
    }
    cstack[split-1].left = cstack[split]
  }
  //console.log("stack=", cstack.map(function(v) { return v.value }))

  //Remove leaf node
  n = cstack[cstack.length-1]
  if(n._color === RED) {
    //Easy case: removing red leaf
    //console.log("RED leaf")
    var p = cstack[cstack.length-2]
    if(p.left === n) {
      p.left = null
    } else if(p.right === n) {
      p.right = null
    }
    cstack.pop()
    for(var i=0; i<cstack.length; ++i) {
      cstack[i]._count--
    }
    return new RedBlackTree(this.tree._compare, cstack[0])
  } else {
    if(n.left || n.right) {
      //Second easy case:  Single child black parent
      //console.log("BLACK single child")
      if(n.left) {
        swapNode(n, n.left)
      } else if(n.right) {
        swapNode(n, n.right)
      }
      //Child must be red, so repaint it black to balance color
      n._color = BLACK
      for(var i=0; i<cstack.length-1; ++i) {
        cstack[i]._count--
      }
      return new RedBlackTree(this.tree._compare, cstack[0])
    } else if(cstack.length === 1) {
      //Third easy case: root
      //console.log("ROOT")
      return new RedBlackTree(this.tree._compare, null)
    } else {
      //Hard case: Repaint n, and then do some nasty stuff
      //console.log("BLACK leaf no children")
      for(var i=0; i<cstack.length; ++i) {
        cstack[i]._count--
      }
      var parent = cstack[cstack.length-2]
      fixDoubleBlack(cstack)
      //Fix up links
      if(parent.left === n) {
        parent.left = null
      } else {
        parent.right = null
      }
    }
  }
  return new RedBlackTree(this.tree._compare, cstack[0])
}

//Returns key
Object.defineProperty(iproto, "key", {
  get: function() {
    if(this._stack.length > 0) {
      return this._stack[this._stack.length-1].key
    }
    return
  },
  enumerable: true
})

//Returns value
Object.defineProperty(iproto, "value", {
  get: function() {
    if(this._stack.length > 0) {
      return this._stack[this._stack.length-1].value
    }
    return
  },
  enumerable: true
})


//Returns the position of this iterator in the sorted list
Object.defineProperty(iproto, "index", {
  get: function() {
    var idx = 0
    var stack = this._stack
    if(stack.length === 0) {
      var r = this.tree.root
      if(r) {
        return r._count
      }
      return 0
    } else if(stack[stack.length-1].left) {
      idx = stack[stack.length-1].left._count
    }
    for(var s=stack.length-2; s>=0; --s) {
      if(stack[s+1] === stack[s].right) {
        ++idx
        if(stack[s].left) {
          idx += stack[s].left._count
        }
      }
    }
    return idx
  },
  enumerable: true
})

//Advances iterator to next element in list
iproto.next = function() {
  var stack = this._stack
  if(stack.length === 0) {
    return
  }
  var n = stack[stack.length-1]
  if(n.right) {
    n = n.right
    while(n) {
      stack.push(n)
      n = n.left
    }
  } else {
    stack.pop()
    while(stack.length > 0 && stack[stack.length-1].right === n) {
      n = stack[stack.length-1]
      stack.pop()
    }
  }
}

//Checks if iterator is at end of tree
Object.defineProperty(iproto, "hasNext", {
  get: function() {
    var stack = this._stack
    if(stack.length === 0) {
      return false
    }
    if(stack[stack.length-1].right) {
      return true
    }
    for(var s=stack.length-1; s>0; --s) {
      if(stack[s-1].left === stack[s]) {
        return true
      }
    }
    return false
  }
})

//Update value
iproto.update = function(value) {
  var stack = this._stack
  if(stack.length === 0) {
    throw new Error("Can't update empty node!")
  }
  var cstack = new Array(stack.length)
  var n = stack[stack.length-1]
  cstack[cstack.length-1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count)
  for(var i=stack.length-2; i>=0; --i) {
    n = stack[i]
    if(n.left === stack[i+1]) {
      cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count)
    } else {
      cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
    }
  }
  return new RedBlackTree(this.tree._compare, cstack[0])
}

//Moves iterator backward one element
iproto.prev = function() {
  var stack = this._stack
  if(stack.length === 0) {
    return
  }
  var n = stack[stack.length-1]
  if(n.left) {
    n = n.left
    while(n) {
      stack.push(n)
      n = n.right
    }
  } else {
    stack.pop()
    while(stack.length > 0 && stack[stack.length-1].left === n) {
      n = stack[stack.length-1]
      stack.pop()
    }
  }
}

//Checks if iterator is at start of tree
Object.defineProperty(iproto, "hasPrev", {
  get: function() {
    var stack = this._stack
    if(stack.length === 0) {
      return false
    }
    if(stack[stack.length-1].left) {
      return true
    }
    for(var s=stack.length-1; s>0; --s) {
      if(stack[s-1].right === stack[s]) {
        return true
      }
    }
    return false
  }
})

//Default comparison function
function defaultCompare(a, b) {
  if(a < b) {
    return -1
  }
  if(a > b) {
    return 1
  }
  return 0
}

//Build a tree
function createRBTree(compare) {
  return new RedBlackTree(compare || defaultCompare, null)
}
},{}],221:[function(_dereq_,module,exports){
// transliterated from the python snippet here:
// http://en.wikipedia.org/wiki/Lanczos_approximation

var g = 7;
var p = [
    0.99999999999980993,
    676.5203681218851,
    -1259.1392167224028,
    771.32342877765313,
    -176.61502916214059,
    12.507343278686905,
    -0.13857109526572012,
    9.9843695780195716e-6,
    1.5056327351493116e-7
];

var g_ln = 607/128;
var p_ln = [
    0.99999999999999709182,
    57.156235665862923517,
    -59.597960355475491248,
    14.136097974741747174,
    -0.49191381609762019978,
    0.33994649984811888699e-4,
    0.46523628927048575665e-4,
    -0.98374475304879564677e-4,
    0.15808870322491248884e-3,
    -0.21026444172410488319e-3,
    0.21743961811521264320e-3,
    -0.16431810653676389022e-3,
    0.84418223983852743293e-4,
    -0.26190838401581408670e-4,
    0.36899182659531622704e-5
];

// Spouge approximation (suitable for large arguments)
function lngamma(z) {

    if(z < 0) return Number('0/0');
    var x = p_ln[0];
    for(var i = p_ln.length - 1; i > 0; --i) x += p_ln[i] / (z + i);
    var t = z + g_ln + 0.5;
    return .5*Math.log(2*Math.PI)+(z+.5)*Math.log(t)-t+Math.log(x)-Math.log(z);
}

module.exports = function gamma (z) {
    if (z < 0.5) {
        return Math.PI / (Math.sin(Math.PI * z) * gamma(1 - z));
    }
    else if(z > 100) return Math.exp(lngamma(z));
    else {
        z -= 1;
        var x = p[0];
        for (var i = 1; i < g + 2; i++) {
            x += p[i] / (z + i);
        }
        var t = z + g + 0.5;

        return Math.sqrt(2 * Math.PI)
            * Math.pow(t, z + 0.5)
            * Math.exp(-t)
            * x
        ;
    }
};

module.exports.log = lngamma;

},{}],222:[function(_dereq_,module,exports){
module.exports = getCanvasContext
function getCanvasContext (type, opts) {
  if (typeof type !== 'string') {
    throw new TypeError('must specify type string')
  }

  opts = opts || {}

  if (typeof document === 'undefined' && !opts.canvas) {
    return null // check for Node
  }

  var canvas = opts.canvas || document.createElement('canvas')
  if (typeof opts.width === 'number') {
    canvas.width = opts.width
  }
  if (typeof opts.height === 'number') {
    canvas.height = opts.height
  }

  var attribs = opts
  var gl
  try {
    var names = [ type ]
    // prefix GL contexts
    if (type.indexOf('webgl') === 0) {
      names.push('experimental-' + type)
    }

    for (var i = 0; i < names.length; i++) {
      gl = canvas.getContext(names[i], attribs)
      if (gl) return gl
    }
  } catch (e) {
    gl = null
  }
  return (gl || null) // ensure null on fail
}

},{}],223:[function(_dereq_,module,exports){
'use strict'

module.exports = createAxes

var createText        = _dereq_('./lib/text.js')
var createLines       = _dereq_('./lib/lines.js')
var createBackground  = _dereq_('./lib/background.js')
var getCubeProperties = _dereq_('./lib/cube.js')
var Ticks             = _dereq_('./lib/ticks.js')

var identity = new Float32Array([
  1, 0, 0, 0,
  0, 1, 0, 0,
  0, 0, 1, 0,
  0, 0, 0, 1])

function copyVec3(a, b) {
  a[0] = b[0]
  a[1] = b[1]
  a[2] = b[2]
  return a
}

function Axes(gl) {
  this.gl             = gl

  this.pixelRatio     = 1

  this.bounds         = [ [-10, -10, -10],
                          [ 10,  10,  10] ]
  this.ticks          = [ [], [], [] ]
  this.autoTicks      = true
  this.tickSpacing    = [ 1, 1, 1 ]

  this.tickEnable     = [ true, true, true ]
  this.tickFont       = [ 'sans-serif', 'sans-serif', 'sans-serif' ]
  this.tickSize       = [ 12, 12, 12 ]
  this.tickAngle      = [ 0, 0, 0 ]
  this._tickAlign      = [ 'auto', 'auto', 'auto' ]
  this.tickColor      = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ]
  this.tickPad        = [ 10, 10, 10 ]

  this.lastCubeProps  = {
    cubeEdges: [0,0,0],
    axis:      [0,0,0]
  }

  this.labels         = [ 'x', 'y', 'z' ]
  this.labelEnable    = [ true, true, true ]
  this.labelFont      = 'sans-serif'
  this.labelSize      = [ 20, 20, 20 ]
  this.labelAngle     = [ 0, 0, 0 ]
  this.labelAlign     = [ 'auto', 'auto', 'auto' ]
  this.labelColor     = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ]
  this.labelPad       = [ 10, 10, 10 ]

  this.lineEnable     = [ true, true, true ]
  this.lineMirror     = [ false, false, false ]
  this.lineWidth      = [ 1, 1, 1 ]
  this.lineColor      = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ]

  this.lineTickEnable = [ true, true, true ]
  this.lineTickMirror = [ false, false, false ]
  this.lineTickLength = [ 0, 0, 0 ]
  this.lineTickWidth  = [ 1, 1, 1 ]
  this.lineTickColor  = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ]

  this.gridEnable     = [ true, true, true ]
  this.gridWidth      = [ 1, 1, 1 ]
  this.gridColor      = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ]

  this.zeroEnable     = [ true, true, true ]
  this.zeroLineColor  = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ]
  this.zeroLineWidth  = [ 2, 2, 2 ]

  this.backgroundEnable = [ false, false, false ]
  this.backgroundColor  = [ [0.8, 0.8, 0.8, 0.5],
                            [0.8, 0.8, 0.8, 0.5],
                            [0.8, 0.8, 0.8, 0.5] ]

  this._firstInit = true
  this._text  = null
  this._lines = null
  this._background = createBackground(gl)
}

var proto = Axes.prototype

proto.update = function(options) {
  options = options || {}

  //Option parsing helper functions
  function parseOption(nest, cons, name) {
    if(name in options) {
      var opt = options[name]
      var prev = this[name]
      var next
      if(nest ? (Array.isArray(opt) && Array.isArray(opt[0])) :
                 Array.isArray(opt) ) {
        this[name] = next = [ cons(opt[0]), cons(opt[1]), cons(opt[2]) ]
      } else {
        this[name] = next = [ cons(opt), cons(opt), cons(opt) ]
      }
      for(var i=0; i<3; ++i) {
        if(next[i] !== prev[i]) {
          return true
        }
      }
    }
    return false
  }

  var NUMBER  = parseOption.bind(this, false, Number)
  var BOOLEAN = parseOption.bind(this, false, Boolean)
  var STRING  = parseOption.bind(this, false, String)
  var COLOR   = parseOption.bind(this, true, function(v) {
    if(Array.isArray(v)) {
      if(v.length === 3) {
        return [ +v[0], +v[1], +v[2], 1.0 ]
      } else if(v.length === 4) {
        return [ +v[0], +v[1], +v[2], +v[3] ]
      }
    }
    return [ 0, 0, 0, 1 ]
  })

  //Tick marks and bounds
  var nextTicks
  var ticksUpdate   = false
  var boundsChanged = false
  if('bounds' in options) {
    var bounds = options.bounds
i_loop:
    for(var i=0; i<2; ++i) {
      for(var j=0; j<3; ++j) {
        if(bounds[i][j] !== this.bounds[i][j]) {
          boundsChanged = true
        }
        this.bounds[i][j] = bounds[i][j]
      }
    }
  }
  if('ticks' in options) {
    nextTicks      = options.ticks
    ticksUpdate    = true
    this.autoTicks = false
    for(var i=0; i<3; ++i) {
      this.tickSpacing[i] = 0.0
    }
  } else if(NUMBER('tickSpacing')) {
    this.autoTicks  = true
    boundsChanged   = true
  }

  if(this._firstInit) {
    if(!('ticks' in options || 'tickSpacing' in options)) {
      this.autoTicks = true
    }

    //Force tick recomputation on first update
    boundsChanged   = true
    ticksUpdate     = true
    this._firstInit = false
  }

  if(boundsChanged && this.autoTicks) {
    nextTicks = Ticks.create(this.bounds, this.tickSpacing)
    ticksUpdate = true
  }

  //Compare next ticks to previous ticks, only update if needed
  if(ticksUpdate) {
    for(var i=0; i<3; ++i) {
      nextTicks[i].sort(function(a,b) {
        return a.x-b.x
      })
    }
    if(Ticks.equal(nextTicks, this.ticks)) {
      ticksUpdate = false
    } else {
      this.ticks = nextTicks
    }
  }

  //Parse tick properties
  BOOLEAN('tickEnable')
  if(STRING('tickFont')) {
    ticksUpdate = true  //If font changes, must rebuild vbo
  }
  NUMBER('tickSize')
  NUMBER('tickAngle')
  NUMBER('tickPad')
  COLOR('tickColor')

  //Axis labels
  var labelUpdate = STRING('labels')
  if(STRING('labelFont')) {
    labelUpdate = true
  }
  BOOLEAN('labelEnable')
  NUMBER('labelSize')
  NUMBER('labelPad')
  COLOR('labelColor')

  //Axis lines
  BOOLEAN('lineEnable')
  BOOLEAN('lineMirror')
  NUMBER('lineWidth')
  COLOR('lineColor')

  //Axis line ticks
  BOOLEAN('lineTickEnable')
  BOOLEAN('lineTickMirror')
  NUMBER('lineTickLength')
  NUMBER('lineTickWidth')
  COLOR('lineTickColor')

  //Grid lines
  BOOLEAN('gridEnable')
  NUMBER('gridWidth')
  COLOR('gridColor')

  //Zero line
  BOOLEAN('zeroEnable')
  COLOR('zeroLineColor')
  NUMBER('zeroLineWidth')

  //Background
  BOOLEAN('backgroundEnable')
  COLOR('backgroundColor')

  //Update text if necessary
  if(!this._text) {
    this._text = createText(
      this.gl,
      this.bounds,
      this.labels,
      this.labelFont,
      this.ticks,
      this.tickFont)
  } else if(this._text && (labelUpdate || ticksUpdate)) {
    this._text.update(
      this.bounds,
      this.labels,
      this.labelFont,
      this.ticks,
      this.tickFont)
  }

  //Update lines if necessary
  if(this._lines && ticksUpdate) {
    this._lines.dispose()
    this._lines = null
  }
  if(!this._lines) {
    this._lines = createLines(this.gl, this.bounds, this.ticks)
  }
}

function OffsetInfo() {
  this.primalOffset = [0,0,0]
  this.primalMinor  = [0,0,0]
  this.mirrorOffset = [0,0,0]
  this.mirrorMinor  = [0,0,0]
}

var LINE_OFFSET = [ new OffsetInfo(), new OffsetInfo(), new OffsetInfo() ]

function computeLineOffset(result, i, bounds, cubeEdges, cubeAxis) {
  var primalOffset = result.primalOffset
  var primalMinor  = result.primalMinor
  var dualOffset   = result.mirrorOffset
  var dualMinor    = result.mirrorMinor
  var e = cubeEdges[i]

  //Calculate offsets
  for(var j=0; j<3; ++j) {
    if(i === j) {
      continue
    }
    var a = primalOffset,
        b = dualOffset,
        c = primalMinor,
        d = dualMinor
    if(e & (1<<j)) {
      a = dualOffset
      b = primalOffset
      c = dualMinor
      d = primalMinor
    }
    a[j] = bounds[0][j]
    b[j] = bounds[1][j]
    if(cubeAxis[j] > 0) {
      c[j] = -1
      d[j] = 0
    } else {
      c[j] = 0
      d[j] = +1
    }
  }
}

var CUBE_ENABLE = [0,0,0]
var DEFAULT_PARAMS = {
  model:      identity,
  view:       identity,
  projection: identity
}

proto.isOpaque = function() {
  return true
}

proto.isTransparent = function() {
  return false
}

proto.drawTransparent = function(params) {}

var ALIGN_OPTION_AUTO = 0 // i.e. as defined in the shader the text would rotate to stay upwards range: [-90,90]

var PRIMAL_MINOR  = [0,0,0]
var MIRROR_MINOR  = [0,0,0]
var PRIMAL_OFFSET = [0,0,0]

proto.draw = function(params) {
  params = params || DEFAULT_PARAMS

  var gl = this.gl

  //Geometry for camera and axes
  var model       = params.model || identity
  var view        = params.view || identity
  var projection  = params.projection || identity
  var bounds      = this.bounds

  //Unpack axis info
  var cubeParams  = getCubeProperties(model, view, projection, bounds)
  var cubeEdges   = cubeParams.cubeEdges
  var cubeAxis    = cubeParams.axis

  var cx = view[12]
  var cy = view[13]
  var cz = view[14]
  var cw = view[15]

  var pixelScaleF = this.pixelRatio * (projection[3]*cx + projection[7]*cy + projection[11]*cz + projection[15]*cw) / gl.drawingBufferHeight

  for(var i=0; i<3; ++i) {
    this.lastCubeProps.cubeEdges[i] = cubeEdges[i]
    this.lastCubeProps.axis[i] = cubeAxis[i]
  }

  //Compute axis info
  var lineOffset  = LINE_OFFSET
  for(var i=0; i<3; ++i) {
    computeLineOffset(
      LINE_OFFSET[i],
      i,
      this.bounds,
      cubeEdges,
      cubeAxis)
  }

  //Set up state parameters
  var gl = this.gl

  //Draw background first
  var cubeEnable = CUBE_ENABLE
  for(var i=0; i<3; ++i) {
    if(this.backgroundEnable[i]) {
      cubeEnable[i] = cubeAxis[i]
    } else {
      cubeEnable[i] = 0
    }
  }

  this._background.draw(
    model,
    view,
    projection,
    bounds,
    cubeEnable,
    this.backgroundColor)

  //Draw lines
  this._lines.bind(
    model,
    view,
    projection,
    this)

  //First draw grid lines and zero lines
  for(var i=0; i<3; ++i) {
    var x = [0,0,0]
    if(cubeAxis[i] > 0) {
      x[i] = bounds[1][i]
    } else {
      x[i] = bounds[0][i]
    }

    //Draw grid lines
    for(var j=0; j<2; ++j) {
      var u = (i + 1 + j) % 3
      var v = (i + 1 + (j^1)) % 3
      if(this.gridEnable[u]) {
        this._lines.drawGrid(u, v, this.bounds, x, this.gridColor[u], this.gridWidth[u]*this.pixelRatio)
      }
    }

    //Draw zero lines (need to do this AFTER all grid lines are drawn)
    for(var j=0; j<2; ++j) {
      var u = (i + 1 + j) % 3
      var v = (i + 1 + (j^1)) % 3
      if(this.zeroEnable[v]) {
        //Check if zero line in bounds
        if(Math.min(bounds[0][v], bounds[1][v]) <= 0 && Math.max(bounds[0][v], bounds[1][v]) >= 0) {
          this._lines.drawZero(u, v, this.bounds, x, this.zeroLineColor[v], this.zeroLineWidth[v]*this.pixelRatio)
        }
      }
    }
  }

  //Then draw axis lines and tick marks
  for(var i=0; i<3; ++i) {

    //Draw axis lines
    if(this.lineEnable[i]) {
      this._lines.drawAxisLine(i, this.bounds, lineOffset[i].primalOffset, this.lineColor[i], this.lineWidth[i]*this.pixelRatio)
    }
    if(this.lineMirror[i]) {
      this._lines.drawAxisLine(i, this.bounds, lineOffset[i].mirrorOffset, this.lineColor[i], this.lineWidth[i]*this.pixelRatio)
    }

    //Compute minor axes
    var primalMinor = copyVec3(PRIMAL_MINOR, lineOffset[i].primalMinor)
    var mirrorMinor = copyVec3(MIRROR_MINOR, lineOffset[i].mirrorMinor)
    var tickLength  = this.lineTickLength
    var op = 0
    for(var j=0; j<3; ++j) {
      var scaleFactor = pixelScaleF / model[5*j]
      primalMinor[j] *= tickLength[j] * scaleFactor
      mirrorMinor[j] *= tickLength[j] * scaleFactor
    }

    //Draw axis line ticks
    if(this.lineTickEnable[i]) {
      this._lines.drawAxisTicks(i, lineOffset[i].primalOffset, primalMinor, this.lineTickColor[i], this.lineTickWidth[i]*this.pixelRatio)
    }
    if(this.lineTickMirror[i]) {
      this._lines.drawAxisTicks(i, lineOffset[i].mirrorOffset, mirrorMinor, this.lineTickColor[i], this.lineTickWidth[i]*this.pixelRatio)
    }
  }
  this._lines.unbind()

  //Draw text sprites
  this._text.bind(
    model,
    view,
    projection,
    this.pixelRatio)

  var alignOpt // options in shader are from this list {-1, 0, 1, 2, 3, ..., n}
  // -1: backward compatible
  //  0: raw data
  //  1: auto align, free angles
  //  2: auto align, horizontal or vertical
  //3-n: auto align, round to n directions e.g. 12 -> round to angles with 30-degree steps

  var hv_ratio = 0.5 // can have an effect on the ratio between horizontals and verticals when using option 2

  var enableAlign
  var alignDir

  function alignTo(i) {
    alignDir = [0,0,0]
    alignDir[i] = 1
  }

  function solveTickAlignments(i, minor, major) {

    var i1 = (i + 1) % 3
    var i2 = (i + 2) % 3

    var A = minor[i1]
    var B = minor[i2]
    var C = major[i1]
    var D = major[i2]

         if ((A > 0) && (D > 0)) { alignTo(i1); return; }
    else if ((A > 0) && (D < 0)) { alignTo(i1); return; }
    else if ((A < 0) && (D > 0)) { alignTo(i1); return; }
    else if ((A < 0) && (D < 0)) { alignTo(i1); return; }
    else if ((B > 0) && (C > 0)) { alignTo(i2); return; }
    else if ((B > 0) && (C < 0)) { alignTo(i2); return; }
    else if ((B < 0) && (C > 0)) { alignTo(i2); return; }
    else if ((B < 0) && (C < 0)) { alignTo(i2); return; }
  }

  for(var i=0; i<3; ++i) {

    var minor      = lineOffset[i].primalMinor
    var major      = lineOffset[i].mirrorMinor

    var offset     = copyVec3(PRIMAL_OFFSET, lineOffset[i].primalOffset)

    for(var j=0; j<3; ++j) {
      if(this.lineTickEnable[i]) {
        offset[j] += pixelScaleF * minor[j] * Math.max(this.lineTickLength[j], 0)  / model[5*j]
      }
    }

    var axis = [0,0,0]
    axis[i] = 1

    //Draw tick text
    if(this.tickEnable[i]) {

      if(this.tickAngle[i] === -3600) {
        this.tickAngle[i] = 0
        this._tickAlign[i] = 'auto'
      } else {
        this._tickAlign[i] = -1
      }

      enableAlign = 1;

      alignOpt = [this._tickAlign[i], hv_ratio, enableAlign]
      if(alignOpt[0] === 'auto') alignOpt[0] = ALIGN_OPTION_AUTO
      else alignOpt[0] = parseInt('' + alignOpt[0])

      alignDir = [0,0,0]
      solveTickAlignments(i, minor, major)

      //Add tick padding
      for(var j=0; j<3; ++j) {
        offset[j] += pixelScaleF * minor[j] * this.tickPad[j] / model[5*j]
      }

      //Draw axis
      this._text.drawTicks(
        i,
        this.tickSize[i],
        this.tickAngle[i],
        offset,
        this.tickColor[i],
        axis,
        alignDir,
        alignOpt)
    }

    //Draw labels
    if(this.labelEnable[i]) {

      enableAlign = 0
      alignDir = [0,0,0]
      if(this.labels[i].length > 4) { // for large label axis enable alignDir to axis
        alignTo(i)
        enableAlign = 1
      }

      alignOpt = [this.labelAlign[i], hv_ratio, enableAlign]
      if(alignOpt[0] === 'auto') alignOpt[0] = ALIGN_OPTION_AUTO
      else alignOpt[0] = parseInt('' + alignOpt[0])

      //Add label padding
      for(var j=0; j<3; ++j) {
        offset[j] += pixelScaleF * minor[j] * this.labelPad[j] / model[5*j]
      }
      offset[i] += 0.5 * (bounds[0][i] + bounds[1][i])

      //Draw axis
      this._text.drawLabel(
        i,
        this.labelSize[i],
        this.labelAngle[i],
        offset,
        this.labelColor[i],
        [0,0,0],
        alignDir,
        alignOpt)
    }
  }

  this._text.unbind()
}

proto.dispose = function() {
  this._text.dispose()
  this._lines.dispose()
  this._background.dispose()
  this._lines = null
  this._text = null
  this._background = null
  this.gl = null
}

function createAxes(gl, options) {
  var axes = new Axes(gl)
  axes.update(options)
  return axes
}

},{"./lib/background.js":224,"./lib/cube.js":225,"./lib/lines.js":226,"./lib/text.js":228,"./lib/ticks.js":229}],224:[function(_dereq_,module,exports){
'use strict'

module.exports = createBackgroundCube

var createBuffer = _dereq_('gl-buffer')
var createVAO    = _dereq_('gl-vao')
var createShader = _dereq_('./shaders').bg

function BackgroundCube(gl, buffer, vao, shader) {
  this.gl = gl
  this.buffer = buffer
  this.vao = vao
  this.shader = shader
}

var proto = BackgroundCube.prototype

proto.draw = function(model, view, projection, bounds, enable, colors) {
  var needsBG = false
  for(var i=0; i<3; ++i) {
    needsBG = needsBG || enable[i]
  }
  if(!needsBG) {
    return
  }

  var gl = this.gl

  gl.enable(gl.POLYGON_OFFSET_FILL)
  gl.polygonOffset(1, 2)

  this.shader.bind()
  this.shader.uniforms = {
    model: model,
    view: view,
    projection: projection,
    bounds: bounds,
    enable: enable,
    colors: colors
  }
  this.vao.bind()
  this.vao.draw(this.gl.TRIANGLES, 36)
  this.vao.unbind()

  gl.disable(gl.POLYGON_OFFSET_FILL)
}

proto.dispose = function() {
  this.vao.dispose()
  this.buffer.dispose()
  this.shader.dispose()
}

function createBackgroundCube(gl) {
  //Create cube vertices
  var vertices = []
  var indices  = []
  var ptr = 0
  for(var d=0; d<3; ++d) {
    var u = (d+1) % 3
    var v = (d+2) % 3
    var x = [0,0,0]
    var c = [0,0,0]
    for(var s=-1; s<=1; s+=2) {
      indices.push(ptr,   ptr+2, ptr+1,
                   ptr+1, ptr+2, ptr+3)
      x[d] = s
      c[d] = s
      for(var i=-1; i<=1; i+=2) {
        x[u] = i
        for(var j=-1; j<=1; j+=2) {
          x[v] = j
          vertices.push(x[0], x[1], x[2],
                        c[0], c[1], c[2])
          ptr += 1
        }
      }
      //Swap u and v
      var tt = u
      u = v
      v = tt
    }
  }

  //Allocate buffer and vertex array
  var buffer = createBuffer(gl, new Float32Array(vertices))
  var elements = createBuffer(gl, new Uint16Array(indices), gl.ELEMENT_ARRAY_BUFFER)
  var vao = createVAO(gl, [
      {
        buffer: buffer,
        type: gl.FLOAT,
        size: 3,
        offset: 0,
        stride: 24
      },
      {
        buffer: buffer,
        type: gl.FLOAT,
        size: 3,
        offset: 12,
        stride: 24
      }
    ], elements)

  //Create shader object
  var shader = createShader(gl)
  shader.attributes.position.location = 0
  shader.attributes.normal.location = 1

  return new BackgroundCube(gl, buffer, vao, shader)
}

},{"./shaders":227,"gl-buffer":231,"gl-vao":313}],225:[function(_dereq_,module,exports){
"use strict"

module.exports = getCubeEdges

var bits      = _dereq_('bit-twiddle')
var multiply  = _dereq_('gl-mat4/multiply')
var splitPoly = _dereq_('split-polygon')
var orient    = _dereq_('robust-orientation')

var mvp        = new Array(16)
var pCubeVerts = new Array(8)
var cubeVerts  = new Array(8)
var x          = new Array(3)
var zero3      = [0,0,0]

;(function() {
  for(var i=0; i<8; ++i) {
    pCubeVerts[i] =[1,1,1,1]
    cubeVerts[i] = [1,1,1]
  }
})()


function transformHg(result, x, mat) {
  for(var i=0; i<4; ++i) {
    result[i] = mat[12+i]
    for(var j=0; j<3; ++j) {
      result[i] += x[j]*mat[4*j+i]
    }
  }
}

var FRUSTUM_PLANES = [
  [ 0, 0, 1, 0, 0],
  [ 0, 0,-1, 1, 0],
  [ 0,-1, 0, 1, 0],
  [ 0, 1, 0, 1, 0],
  [-1, 0, 0, 1, 0],
  [ 1, 0, 0, 1, 0]
]

function polygonArea(p) {
  for(var i=0; i<FRUSTUM_PLANES.length; ++i) {
    p = splitPoly.positive(p, FRUSTUM_PLANES[i])
    if(p.length < 3) {
      return 0
    }
  }

  var base = p[0]
  var ax = base[0] / base[3]
  var ay = base[1] / base[3]
  var area = 0.0
  for(var i=1; i+1<p.length; ++i) {
    var b = p[i]
    var c = p[i+1]

    var bx = b[0]/b[3]
    var by = b[1]/b[3]
    var cx = c[0]/c[3]
    var cy = c[1]/c[3]

    var ux = bx - ax
    var uy = by - ay

    var vx = cx - ax
    var vy = cy - ay

    area += Math.abs(ux * vy - uy * vx)
  }

  return area
}

var CUBE_EDGES = [1,1,1]
var CUBE_AXIS  = [0,0,0]
var CUBE_RESULT = {
  cubeEdges: CUBE_EDGES,
  axis: CUBE_AXIS
}

function getCubeEdges(model, view, projection, bounds) {

  //Concatenate matrices
  multiply(mvp, view, model)
  multiply(mvp, projection, mvp)

  //First project cube vertices
  var ptr = 0
  for(var i=0; i<2; ++i) {
    x[2] = bounds[i][2]
    for(var j=0; j<2; ++j) {
      x[1] = bounds[j][1]
      for(var k=0; k<2; ++k) {
        x[0] = bounds[k][0]
        transformHg(pCubeVerts[ptr], x, mvp)
        ptr += 1
      }
    }
  }

  //Classify camera against cube faces
  var closest = -1

  for(var i=0; i<8; ++i) {
    var w = pCubeVerts[i][3]
    for(var l=0; l<3; ++l) {
      cubeVerts[i][l] = pCubeVerts[i][l] / w
    }
    if(w < 0) {
      if(closest < 0) {
        closest = i
      } else if(cubeVerts[i][2] < cubeVerts[closest][2]) {
        closest = i
      }
    }
  }

  if(closest < 0) {
    closest = 0
    for(var d=0; d<3; ++d) {
      var u = (d+2) % 3
      var v = (d+1) % 3
      var o0 = -1
      var o1 = -1
      for(var s=0; s<2; ++s) {
        var f0 = (s<<d)
        var f1 = f0 + (s << u) + ((1-s) << v)
        var f2 = f0 + ((1-s) << u) + (s << v)
        if(orient(cubeVerts[f0], cubeVerts[f1], cubeVerts[f2], zero3) < 0) {
          continue
        }
        if(s) {
          o0 = 1
        } else {
          o1 = 1
        }
      }
      if(o0 < 0 || o1 < 0) {
        if(o1 > o0) {
          closest |= 1<<d
        }
        continue
      }
      for(var s=0; s<2; ++s) {
        var f0 = (s<<d)
        var f1 = f0 + (s << u) + ((1-s) << v)
        var f2 = f0 + ((1-s) << u) + (s << v)
        var o = polygonArea([
            pCubeVerts[f0],
            pCubeVerts[f1],
            pCubeVerts[f2],
            pCubeVerts[f0+(1<<u)+(1<<v)]])
        if(s) {
          o0 = o
        } else {
          o1 = o
        }
      }
      if(o1 > o0) {
        closest |= 1<<d
        continue
      }
    }
  }

  var farthest = 7^closest

  //Find lowest vertex which is not closest closest
  var bottom = -1
  for(var i=0; i<8; ++i) {
    if(i === closest || i === farthest) {
      continue
    }
    if(bottom < 0) {
      bottom = i
    } else if(cubeVerts[bottom][1] > cubeVerts[i][1]) {
      bottom = i
    }
  }

  //Find left/right neighbors of bottom vertex
  var left = -1
  for(var i=0; i<3; ++i) {
    var idx = bottom ^ (1<<i)
    if(idx === closest || idx === farthest) {
      continue
    }
    if(left < 0) {
      left = idx
    }
    var v = cubeVerts[idx]
    if(v[0] < cubeVerts[left][0]) {
      left = idx
    }
  }
  var right = -1
  for(var i=0; i<3; ++i) {
    var idx = bottom ^ (1<<i)
    if(idx === closest || idx === farthest || idx === left) {
      continue
    }
    if(right < 0) {
      right = idx
    }
    var v = cubeVerts[idx]
    if(v[0] > cubeVerts[right][0]) {
      right = idx
    }
  }

  //Determine edge axis coordinates
  var cubeEdges = CUBE_EDGES
  cubeEdges[0] = cubeEdges[1] = cubeEdges[2] = 0
  cubeEdges[bits.log2(left^bottom)] = bottom&left
  cubeEdges[bits.log2(bottom^right)] = bottom&right
  var top = right ^ 7
  if(top === closest || top === farthest) {
    top = left ^ 7
    cubeEdges[bits.log2(right^top)] = top&right
  } else {
    cubeEdges[bits.log2(left^top)] = top&left
  }

  //Determine visible faces
  var axis = CUBE_AXIS
  var cutCorner = closest
  for(var d=0; d<3; ++d) {
    if(cutCorner & (1<<d)) {
      axis[d] = -1
    } else {
      axis[d] = 1
    }
  }

  //Return result
  return CUBE_RESULT
}
},{"bit-twiddle":81,"gl-mat4/multiply":258,"robust-orientation":488,"split-polygon":505}],226:[function(_dereq_,module,exports){
'use strict'

module.exports    = createLines

var createBuffer  = _dereq_('gl-buffer')
var createVAO     = _dereq_('gl-vao')
var createShader  = _dereq_('./shaders').line

var MAJOR_AXIS = [0,0,0]
var MINOR_AXIS = [0,0,0]
var SCREEN_AXIS = [0,0,0]
var OFFSET_VEC = [0,0,0]
var SHAPE = [1,1]

function zeroVec(a) {
  a[0] = a[1] = a[2] = 0
  return a
}

function copyVec(a,b) {
  a[0] = b[0]
  a[1] = b[1]
  a[2] = b[2]
  return a
}

function Lines(gl, vertBuffer, vao, shader, tickCount, tickOffset, gridCount, gridOffset) {
  this.gl         = gl
  this.vertBuffer = vertBuffer
  this.vao        = vao
  this.shader     = shader
  this.tickCount  = tickCount
  this.tickOffset = tickOffset
  this.gridCount  = gridCount
  this.gridOffset = gridOffset
}

var proto = Lines.prototype

proto.bind = function(model, view, projection) {
  this.shader.bind()
  this.shader.uniforms.model = model
  this.shader.uniforms.view = view
  this.shader.uniforms.projection = projection

  SHAPE[0] = this.gl.drawingBufferWidth
  SHAPE[1] = this.gl.drawingBufferHeight

  this.shader.uniforms.screenShape = SHAPE
  this.vao.bind()
}

proto.unbind = function() {
  this.vao.unbind()
}

proto.drawAxisLine = function(j, bounds, offset, color, lineWidth) {
  var minorAxis = zeroVec(MINOR_AXIS)
  this.shader.uniforms.majorAxis = MINOR_AXIS

  minorAxis[j] = bounds[1][j] - bounds[0][j]
  this.shader.uniforms.minorAxis = minorAxis

  var noffset = copyVec(OFFSET_VEC, offset)
  noffset[j] += bounds[0][j]
  this.shader.uniforms.offset = noffset

  this.shader.uniforms.lineWidth = lineWidth

  this.shader.uniforms.color = color

  var screenAxis = zeroVec(SCREEN_AXIS)
  screenAxis[(j+2)%3] = 1
  this.shader.uniforms.screenAxis = screenAxis
  this.vao.draw(this.gl.TRIANGLES, 6)

  var screenAxis = zeroVec(SCREEN_AXIS)
  screenAxis[(j+1)%3] = 1
  this.shader.uniforms.screenAxis = screenAxis
  this.vao.draw(this.gl.TRIANGLES, 6)
}

proto.drawAxisTicks = function(j, offset, minorAxis, color, lineWidth) {
  if(!this.tickCount[j]) {
    return
  }

  var majorAxis = zeroVec(MAJOR_AXIS)
  majorAxis[j]  = 1
  this.shader.uniforms.majorAxis = majorAxis
  this.shader.uniforms.offset    = offset
  this.shader.uniforms.minorAxis = minorAxis
  this.shader.uniforms.color     = color
  this.shader.uniforms.lineWidth = lineWidth

  var screenAxis = zeroVec(SCREEN_AXIS)
  screenAxis[j] = 1
  this.shader.uniforms.screenAxis = screenAxis
  this.vao.draw(this.gl.TRIANGLES, this.tickCount[j], this.tickOffset[j])
}


proto.drawGrid = function(i, j, bounds, offset, color, lineWidth) {
  if(!this.gridCount[i]) {
    return
  }

  var minorAxis = zeroVec(MINOR_AXIS)
  minorAxis[j]  = bounds[1][j] - bounds[0][j]
  this.shader.uniforms.minorAxis = minorAxis

  var noffset = copyVec(OFFSET_VEC, offset)
  noffset[j] += bounds[0][j]
  this.shader.uniforms.offset = noffset

  var majorAxis = zeroVec(MAJOR_AXIS)
  majorAxis[i]  = 1
  this.shader.uniforms.majorAxis = majorAxis

  var screenAxis = zeroVec(SCREEN_AXIS)
  screenAxis[i] = 1
  this.shader.uniforms.screenAxis = screenAxis
  this.shader.uniforms.lineWidth = lineWidth

  this.shader.uniforms.color = color
  this.vao.draw(this.gl.TRIANGLES, this.gridCount[i], this.gridOffset[i])
}

proto.drawZero = function(j, i, bounds, offset, color, lineWidth) {
  var minorAxis = zeroVec(MINOR_AXIS)
  this.shader.uniforms.majorAxis = minorAxis

  minorAxis[j] = bounds[1][j] - bounds[0][j]
  this.shader.uniforms.minorAxis = minorAxis

  var noffset = copyVec(OFFSET_VEC, offset)
  noffset[j] += bounds[0][j]
  this.shader.uniforms.offset = noffset

  var screenAxis = zeroVec(SCREEN_AXIS)
  screenAxis[i] = 1
  this.shader.uniforms.screenAxis = screenAxis
  this.shader.uniforms.lineWidth = lineWidth

  this.shader.uniforms.color = color
  this.vao.draw(this.gl.TRIANGLES, 6)
}

proto.dispose = function() {
  this.vao.dispose()
  this.vertBuffer.dispose()
  this.shader.dispose()
}

function createLines(gl, bounds, ticks) {
  var vertices    = []
  var tickOffset  = [0,0,0]
  var tickCount   = [0,0,0]

  //Create grid lines for each axis/direction
  var gridOffset = [0,0,0]
  var gridCount  = [0,0,0]

  //Add zero line
  vertices.push(
    0,0,1,   0,1,1,   0,0,-1,
    0,0,-1,  0,1,1,   0,1,-1)

  for(var i=0; i<3; ++i) {
    //Axis tick marks
    var start = ((vertices.length / 3)|0)
    for(var j=0; j<ticks[i].length; ++j) {
      var x = +ticks[i][j].x
      vertices.push(
        x,0,1,   x,1,1,   x,0,-1,
        x,0,-1,  x,1,1,   x,1,-1)
    }
    var end = ((vertices.length / 3)|0)
    tickOffset[i] = start
    tickCount[i]  = end - start

    //Grid lines
    var start = ((vertices.length / 3)|0)
    for(var k=0; k<ticks[i].length; ++k) {
      var x = +ticks[i][k].x
      vertices.push(
        x,0,1,   x,1,1,   x,0,-1,
        x,0,-1,  x,1,1,   x,1,-1)
    }
    var end = ((vertices.length / 3)|0)
    gridOffset[i] = start
    gridCount[i]  = end - start
  }

  //Create cube VAO
  var vertBuf = createBuffer(gl, new Float32Array(vertices))
  var vao = createVAO(gl, [
    { "buffer": vertBuf,
      "type": gl.FLOAT,
      "size": 3,
      "stride": 0,
      "offset": 0
    }
  ])
  var shader = createShader(gl)
  shader.attributes.position.location = 0
  return new Lines(gl, vertBuf, vao, shader, tickCount, tickOffset, gridCount, gridOffset)
}

},{"./shaders":227,"gl-buffer":231,"gl-vao":313}],227:[function(_dereq_,module,exports){
'use strict'

var glslify = _dereq_('glslify')
var createShader = _dereq_('gl-shader')

var lineVert = glslify(["#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, majorAxis, minorAxis, screenAxis;\nuniform float lineWidth;\nuniform vec2 screenShape;\n\nvec3 project(vec3 p) {\n  vec4 pp = projection * view * model * vec4(p, 1.0);\n  return pp.xyz / max(pp.w, 0.0001);\n}\n\nvoid main() {\n  vec3 major = position.x * majorAxis;\n  vec3 minor = position.y * minorAxis;\n\n  vec3 vPosition = major + minor + offset;\n  vec3 pPosition = project(vPosition);\n  vec3 offset = project(vPosition + screenAxis * position.z);\n\n  vec2 screen = normalize((offset - pPosition).xy * screenShape) / screenShape;\n\n  gl_Position = vec4(pPosition + vec3(0.5 * screen * lineWidth, 0), 1.0);\n}\n"])
var lineFrag = glslify(["precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n  gl_FragColor = color;\n}"])
exports.line = function(gl) {
  return createShader(gl, lineVert, lineFrag, null, [
    {name: 'position', type: 'vec3'}
  ])
}

var textVert = glslify(["#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, axis, alignDir, alignOpt;\nuniform float scale, angle, pixelScale;\nuniform vec2 resolution;\n\nvec3 project(vec3 p) {\n  vec4 pp = projection * view * model * vec4(p, 1.0);\n  return pp.xyz / max(pp.w, 0.0001);\n}\n\nfloat computeViewAngle(vec3 a, vec3 b) {\n  vec3 A = project(a);\n  vec3 B = project(b);\n\n  return atan(\n    (B.y - A.y) * resolution.y,\n    (B.x - A.x) * resolution.x\n  );\n}\n\nconst float PI = 3.141592;\nconst float TWO_PI = 2.0 * PI;\nconst float HALF_PI = 0.5 * PI;\nconst float ONE_AND_HALF_PI = 1.5 * PI;\n\nint option = int(floor(alignOpt.x + 0.001));\nfloat hv_ratio =       alignOpt.y;\nbool enableAlign =    (alignOpt.z != 0.0);\n\nfloat mod_angle(float a) {\n  return mod(a, PI);\n}\n\nfloat positive_angle(float a) {\n  return mod_angle((a < 0.0) ?\n    a + TWO_PI :\n    a\n  );\n}\n\nfloat look_upwards(float a) {\n  float b = positive_angle(a);\n  return ((b > HALF_PI) && (b <= ONE_AND_HALF_PI)) ?\n    b - PI :\n    b;\n}\n\nfloat look_horizontal_or_vertical(float a, float ratio) {\n  // ratio controls the ratio between being horizontal to (vertical + horizontal)\n  // if ratio is set to 0.5 then it is 50%, 50%.\n  // when using a higher ratio e.g. 0.75 the result would\n  // likely be more horizontal than vertical.\n\n  float b = positive_angle(a);\n\n  return\n    (b < (      ratio) * HALF_PI) ? 0.0 :\n    (b < (2.0 - ratio) * HALF_PI) ? -HALF_PI :\n    (b < (2.0 + ratio) * HALF_PI) ? 0.0 :\n    (b < (4.0 - ratio) * HALF_PI) ? HALF_PI :\n                                    0.0;\n}\n\nfloat roundTo(float a, float b) {\n  return float(b * floor((a + 0.5 * b) / b));\n}\n\nfloat look_round_n_directions(float a, int n) {\n  float b = positive_angle(a);\n  float div = TWO_PI / float(n);\n  float c = roundTo(b, div);\n  return look_upwards(c);\n}\n\nfloat applyAlignOption(float rawAngle, float delta) {\n  return\n    (option >  2) ? look_round_n_directions(rawAngle + delta, option) :       // option 3-n: round to n directions\n    (option == 2) ? look_horizontal_or_vertical(rawAngle + delta, hv_ratio) : // horizontal or vertical\n    (option == 1) ? rawAngle + delta :       // use free angle, and flip to align with one direction of the axis\n    (option == 0) ? look_upwards(rawAngle) : // use free angle, and stay upwards\n    (option ==-1) ? 0.0 :                    // useful for backward compatibility, all texts remains horizontal\n                    rawAngle;                // otherwise return back raw input angle\n}\n\nbool isAxisTitle = (axis.x == 0.0) &&\n                   (axis.y == 0.0) &&\n                   (axis.z == 0.0);\n\nvoid main() {\n  //Compute world offset\n  float axisDistance = position.z;\n  vec3 dataPosition = axisDistance * axis + offset;\n\n  float beta = angle; // i.e. user defined attributes for each tick\n\n  float axisAngle;\n  float clipAngle;\n  float flip;\n\n  if (enableAlign) {\n    axisAngle = (isAxisTitle) ? HALF_PI :\n                      computeViewAngle(dataPosition, dataPosition + axis);\n    clipAngle = computeViewAngle(dataPosition, dataPosition + alignDir);\n\n    axisAngle += (sin(axisAngle) < 0.0) ? PI : 0.0;\n    clipAngle += (sin(clipAngle) < 0.0) ? PI : 0.0;\n\n    flip = (dot(vec2(cos(axisAngle), sin(axisAngle)),\n                vec2(sin(clipAngle),-cos(clipAngle))) > 0.0) ? 1.0 : 0.0;\n\n    beta += applyAlignOption(clipAngle, flip * PI);\n  }\n\n  //Compute plane offset\n  vec2 planeCoord = position.xy * pixelScale;\n\n  mat2 planeXform = scale * mat2(\n     cos(beta), sin(beta),\n    -sin(beta), cos(beta)\n  );\n\n  vec2 viewOffset = 2.0 * planeXform * planeCoord / resolution;\n\n  //Compute clip position\n  vec3 clipPosition = project(dataPosition);\n\n  //Apply text offset in clip coordinates\n  clipPosition += vec3(viewOffset, 0.0);\n\n  //Done\n  gl_Position = vec4(clipPosition, 1.0);\n}"])
var textFrag = glslify(["precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n  gl_FragColor = color;\n}"])
exports.text = function(gl) {
  return createShader(gl, textVert, textFrag, null, [
    {name: 'position', type: 'vec3'}
  ])
}

var bgVert = glslify(["#define GLSLIFY 1\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection;\nuniform vec3 enable;\nuniform vec3 bounds[2];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n\n  vec3 signAxis = sign(bounds[1] - bounds[0]);\n\n  vec3 realNormal = signAxis * normal;\n\n  if(dot(realNormal, enable) > 0.0) {\n    vec3 minRange = min(bounds[0], bounds[1]);\n    vec3 maxRange = max(bounds[0], bounds[1]);\n    vec3 nPosition = mix(minRange, maxRange, 0.5 * (position + 1.0));\n    gl_Position = projection * view * model * vec4(nPosition, 1.0);\n  } else {\n    gl_Position = vec4(0,0,0,0);\n  }\n\n  colorChannel = abs(realNormal);\n}"])
var bgFrag = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 colors[3];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n  gl_FragColor = colorChannel.x * colors[0] +\n                 colorChannel.y * colors[1] +\n                 colorChannel.z * colors[2];\n}"])
exports.bg = function(gl) {
  return createShader(gl, bgVert, bgFrag, null, [
    {name: 'position', type: 'vec3'},
    {name: 'normal', type: 'vec3'}
  ])
}

},{"gl-shader":290,"glslify":395}],228:[function(_dereq_,module,exports){
(function (process){
"use strict"

module.exports = createTextSprites

var createBuffer  = _dereq_('gl-buffer')
var createVAO     = _dereq_('gl-vao')
var vectorizeText = _dereq_('vectorize-text')
var createShader  = _dereq_('./shaders').text

var globals = window || process.global || {}
var __TEXT_CACHE  = globals.__TEXT_CACHE || {}
globals.__TEXT_CACHE = {}

//Vertex buffer format for text is:
//
/// [x,y,z] = Spatial coordinate
//

var VERTEX_SIZE = 3

function TextSprites(
  gl,
  shader,
  buffer,
  vao) {
  this.gl           = gl
  this.shader       = shader
  this.buffer       = buffer
  this.vao          = vao
  this.tickOffset   =
  this.tickCount    =
  this.labelOffset  =
  this.labelCount   = null
}

var proto = TextSprites.prototype

//Bind textures for rendering
var SHAPE = [0,0]
proto.bind = function(model, view, projection, pixelScale) {
  this.vao.bind()
  this.shader.bind()
  var uniforms = this.shader.uniforms
  uniforms.model = model
  uniforms.view = view
  uniforms.projection = projection
  uniforms.pixelScale = pixelScale
  SHAPE[0] = this.gl.drawingBufferWidth
  SHAPE[1] = this.gl.drawingBufferHeight
  this.shader.uniforms.resolution = SHAPE
}

proto.unbind = function() {
  this.vao.unbind()
}

proto.update = function(bounds, labels, labelFont, ticks, tickFont) {
  var data = []

  function addItem(t, text, font, size, lineSpacing, styletags) {
    var fontcache = __TEXT_CACHE[font]
    if(!fontcache) {
      fontcache = __TEXT_CACHE[font] = {}
    }
    var mesh = fontcache[text]
    if(!mesh) {
      mesh = fontcache[text] = tryVectorizeText(text, {
        triangles: true,
        font: font,
        textAlign: 'center',
        textBaseline: 'middle',
        lineSpacing: lineSpacing,
        styletags: styletags
      })
    }
    var scale = (size || 12) / 12
    var positions = mesh.positions
    var cells = mesh.cells
    for(var i=0, nc=cells.length; i<nc; ++i) {
      var c = cells[i]
      for(var j=2; j>=0; --j) {
        var p = positions[c[j]]
        data.push(scale*p[0], -scale*p[1], t)
      }
    }
  }

  //Generate sprites for all 3 axes, store data in texture atlases
  var tickOffset  = [0,0,0]
  var tickCount   = [0,0,0]
  var labelOffset = [0,0,0]
  var labelCount  = [0,0,0]
  var lineSpacing = 1.25
  var styletags = {
    breaklines:true,
    bolds: true,
    italics: true,
    subscripts:true,
    superscripts:true
  }
  for(var d=0; d<3; ++d) {

    //Generate label
    labelOffset[d] = (data.length/VERTEX_SIZE)|0
    addItem(
      0.5*(bounds[0][d]+bounds[1][d]),
      labels[d],
      labelFont[d],
      12, // labelFontSize
      lineSpacing,
      styletags
    )
    labelCount[d] = ((data.length/VERTEX_SIZE)|0) - labelOffset[d]

    //Generate sprites for tick marks
    tickOffset[d] = (data.length/VERTEX_SIZE)|0
    for(var i=0; i<ticks[d].length; ++i) {
      if(!ticks[d][i].text) {
        continue
      }
      addItem(
        ticks[d][i].x,
        ticks[d][i].text,
        ticks[d][i].font || tickFont,
        ticks[d][i].fontSize || 12,
        lineSpacing,
        styletags
      )
    }
    tickCount[d] = ((data.length/VERTEX_SIZE)|0) - tickOffset[d]
  }

  this.buffer.update(data)
  this.tickOffset = tickOffset
  this.tickCount = tickCount
  this.labelOffset = labelOffset
  this.labelCount = labelCount
}

//Draws the tick marks for an axis
proto.drawTicks = function(d, scale, angle, offset, color, axis, alignDir, alignOpt) {
  if(!this.tickCount[d]) {
    return
  }

  this.shader.uniforms.axis = axis
  this.shader.uniforms.color = color
  this.shader.uniforms.angle = angle
  this.shader.uniforms.scale = scale
  this.shader.uniforms.offset = offset
  this.shader.uniforms.alignDir = alignDir
  this.shader.uniforms.alignOpt = alignOpt
  this.vao.draw(this.gl.TRIANGLES, this.tickCount[d], this.tickOffset[d])
}

//Draws the text label for an axis
proto.drawLabel = function(d, scale, angle, offset, color, axis, alignDir, alignOpt) {
  if(!this.labelCount[d]) {
    return
  }

  this.shader.uniforms.axis = axis
  this.shader.uniforms.color = color
  this.shader.uniforms.angle = angle
  this.shader.uniforms.scale = scale
  this.shader.uniforms.offset = offset
  this.shader.uniforms.alignDir = alignDir
  this.shader.uniforms.alignOpt = alignOpt
  this.vao.draw(this.gl.TRIANGLES, this.labelCount[d], this.labelOffset[d])
}

//Releases all resources attached to this object
proto.dispose = function() {
  this.shader.dispose()
  this.vao.dispose()
  this.buffer.dispose()
}

function tryVectorizeText(text, options) {
  try {
    return vectorizeText(text, options)
  } catch(e) {
    console.warn('error vectorizing text:"' + text + '" error:', e)
    return {
      cells: [],
      positions: []
    }
  }
}

function createTextSprites(
    gl,
    bounds,
    labels,
    labelFont,
    ticks,
    tickFont) {

  var buffer = createBuffer(gl)
  var vao = createVAO(gl, [
    { "buffer": buffer,
      "size": 3
    }
  ])

  var shader = createShader(gl)
  shader.attributes.position.location = 0

  var result = new TextSprites(
    gl,
    shader,
    buffer,
    vao)

  result.update(bounds, labels, labelFont, ticks, tickFont)

  return result
}

}).call(this,_dereq_('_process'))
},{"./shaders":227,"_process":468,"gl-buffer":231,"gl-vao":313,"vectorize-text":528}],229:[function(_dereq_,module,exports){
'use strict'

exports.create   = defaultTicks
exports.equal    = ticksEqual

function prettyPrint(spacing, i) {
  var stepStr = spacing + ""
  var u = stepStr.indexOf(".")
  var sigFigs = 0
  if(u >= 0) {
    sigFigs = stepStr.length - u - 1
  }
  var shift = Math.pow(10, sigFigs)
  var x = Math.round(spacing * i * shift)
  var xstr = x + ""
  if(xstr.indexOf("e") >= 0) {
    return xstr
  }
  var xi = x / shift, xf = x % shift
  if(x < 0) {
    xi = -Math.ceil(xi)|0
    xf = (-xf)|0
  } else {
    xi = Math.floor(xi)|0
    xf = xf|0
  }
  var xis = "" + xi 
  if(x < 0) {
    xis = "-" + xis
  }
  if(sigFigs) {
    var xs = "" + xf
    while(xs.length < sigFigs) {
      xs = "0" + xs
    }
    return xis + "." + xs
  } else {
    return xis
  }
}

function defaultTicks(bounds, tickSpacing) {
  var array = []
  for(var d=0; d<3; ++d) {
    var ticks = []
    var m = 0.5*(bounds[0][d]+bounds[1][d])
    for(var t=0; t*tickSpacing[d]<=bounds[1][d]; ++t) {
      ticks.push({x: t*tickSpacing[d], text: prettyPrint(tickSpacing[d], t)})
    }
    for(var t=-1; t*tickSpacing[d]>=bounds[0][d]; --t) {
      ticks.push({x: t*tickSpacing[d], text: prettyPrint(tickSpacing[d], t)})
    }
    array.push(ticks)
  }
  return array
}

function ticksEqual(ticksA, ticksB) {
  for(var i=0; i<3; ++i) {
    if(ticksA[i].length !== ticksB[i].length) {
      return false
    }
    for(var j=0; j<ticksA[i].length; ++j) {
      var a = ticksA[i][j]
      var b = ticksB[i][j]
      if(
        a.x !== b.x ||
        a.text !== b.text ||
        a.font !== b.font ||
        a.fontColor !== b.fontColor ||
        a.fontSize !== b.fontSize ||
        a.dx !== b.dx ||
        a.dy !== b.dy
      ) {
        return false
      }
    }
  }
  return true
}
},{}],230:[function(_dereq_,module,exports){
"use strict"

module.exports = axesProperties

var getPlanes   = _dereq_("extract-frustum-planes")
var splitPoly   = _dereq_("split-polygon")
var cubeParams  = _dereq_("./lib/cube.js")
var m4mul       = _dereq_("gl-mat4/multiply")
var m4transpose = _dereq_("gl-mat4/transpose")
var v4transformMat4 = _dereq_("gl-vec4/transformMat4")

var identity    = new Float32Array([
    1, 0, 0, 0,
    0, 1, 0, 0,
    0, 0, 1, 0,
    0, 0, 0, 1
  ])

var mvp         = new Float32Array(16)

function AxesRange3D(lo, hi, pixelsPerDataUnit) {
  this.lo = lo
  this.hi = hi
  this.pixelsPerDataUnit = pixelsPerDataUnit
}

var SCRATCH_P = [0,0,0,1]
var SCRATCH_Q = [0,0,0,1]

function gradient(result, M, v, width, height) {
  for(var i=0; i<3; ++i) {
    var p = SCRATCH_P
    var q = SCRATCH_Q
    for(var j=0; j<3; ++j) {
      q[j] = p[j] = v[j]
    }
    q[3] = p[3] = 1

    q[i] += 1
    v4transformMat4(q, q, M)
    if(q[3] < 0) {
      result[i] = Infinity
    }

    p[i] -= 1
    v4transformMat4(p, p, M)
    if(p[3] < 0) {
      result[i] = Infinity
    }

    var dx = (p[0]/p[3] - q[0]/q[3]) * width
    var dy = (p[1]/p[3] - q[1]/q[3]) * height

    result[i] = 0.25 * Math.sqrt(dx*dx + dy*dy)
  }
  return result
}

var RANGES = [
  new AxesRange3D(Infinity, -Infinity, Infinity),
  new AxesRange3D(Infinity, -Infinity, Infinity),
  new AxesRange3D(Infinity, -Infinity, Infinity)
]

var SCRATCH_X = [0,0,0]

function axesProperties(axes, camera, width, height, params) {
  var model       = camera.model || identity
  var view        = camera.view || identity
  var projection  = camera.projection || identity
  var bounds      = axes.bounds
  var params      = params || cubeParams(model, view, projection, bounds)
  var axis        = params.axis
  var edges       = params.edges

  m4mul(mvp, view, model)
  m4mul(mvp, projection, mvp)

  //Calculate the following properties for each axis:
  //
  // * lo - start of visible range for each axis in tick coordinates
  // * hi - end of visible range for each axis in tick coordinates
  // * ticksPerPixel - pixel density of tick marks for the axis
  //
  var ranges = RANGES
  for(var i=0; i<3; ++i) {
    ranges[i].lo = Infinity
    ranges[i].hi = -Infinity
    ranges[i].pixelsPerDataUnit = Infinity
  }

  //Compute frustum planes, intersect with box
  var frustum = getPlanes(m4transpose(mvp, mvp))
  m4transpose(mvp, mvp)

  //Loop over vertices of viewable box
  for(var d=0; d<3; ++d) {
    var u = (d+1)%3
    var v = (d+2)%3
    var x = SCRATCH_X
i_loop:
    for(var i=0; i<2; ++i) {
      var poly = []

      if((axis[d] < 0) === !!i) {
        continue
      }

      x[d] = bounds[i][d]
      for(var j=0; j<2; ++j) {
        x[u] = bounds[j^i][u]
        for(var k=0; k<2; ++k) {
          x[v] = bounds[k^j^i][v]
          poly.push(x.slice())
        }
      }
      for(var j=4; j===4; ++j) { // Note: using only near plane here.
        if(poly.length === 0) {
          continue i_loop
        }
        poly = splitPoly.positive(poly, frustum[j])
      }

      //Loop over vertices of polygon to find extremal points
      for(var j=0; j<poly.length; ++j) {
        var v = poly[j]
        var grad = gradient(SCRATCH_X, mvp, v, width, height)
        for(var k=0; k<3; ++k) {
          ranges[k].lo = Math.min(ranges[k].lo, v[k])
          ranges[k].hi = Math.max(ranges[k].hi, v[k])
          if(k !== d) {
            ranges[k].pixelsPerDataUnit = Math.min(ranges[k].pixelsPerDataUnit, Math.abs(grad[k]))
          }
        }
      }
    }
  }

  return ranges
}

},{"./lib/cube.js":225,"extract-frustum-planes":214,"gl-mat4/multiply":258,"gl-mat4/transpose":266,"gl-vec4/transformMat4":384,"split-polygon":505}],231:[function(_dereq_,module,exports){
"use strict"

var pool = _dereq_("typedarray-pool")
var ops = _dereq_("ndarray-ops")
var ndarray = _dereq_("ndarray")

var SUPPORTED_TYPES = [
  "uint8",
  "uint8_clamped",
  "uint16",
  "uint32",
  "int8",
  "int16",
  "int32",
  "float32" ]

function GLBuffer(gl, type, handle, length, usage) {
  this.gl = gl
  this.type = type
  this.handle = handle
  this.length = length
  this.usage = usage
}

var proto = GLBuffer.prototype

proto.bind = function() {
  this.gl.bindBuffer(this.type, this.handle)
}

proto.unbind = function() {
  this.gl.bindBuffer(this.type, null)
}

proto.dispose = function() {
  this.gl.deleteBuffer(this.handle)
}

function updateTypeArray(gl, type, len, usage, data, offset) {
  var dataLen = data.length * data.BYTES_PER_ELEMENT
  if(offset < 0) {
    gl.bufferData(type, data, usage)
    return dataLen
  }
  if(dataLen + offset > len) {
    throw new Error("gl-buffer: If resizing buffer, must not specify offset")
  }
  gl.bufferSubData(type, offset, data)
  return len
}

function makeScratchTypeArray(array, dtype) {
  var res = pool.malloc(array.length, dtype)
  var n = array.length
  for(var i=0; i<n; ++i) {
    res[i] = array[i]
  }
  return res
}

function isPacked(shape, stride) {
  var n = 1
  for(var i=stride.length-1; i>=0; --i) {
    if(stride[i] !== n) {
      return false
    }
    n *= shape[i]
  }
  return true
}

proto.update = function(array, offset) {
  if(typeof offset !== "number") {
    offset = -1
  }
  this.bind()
  if(typeof array === "object" && typeof array.shape !== "undefined") { //ndarray
    var dtype = array.dtype
    if(SUPPORTED_TYPES.indexOf(dtype) < 0) {
      dtype = "float32"
    }
    if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) {
      var ext = gl.getExtension('OES_element_index_uint')
      if(ext && dtype !== "uint16") {
        dtype = "uint32"
      } else {
        dtype = "uint16"
      }
    }
    if(dtype === array.dtype && isPacked(array.shape, array.stride)) {
      if(array.offset === 0 && array.data.length === array.shape[0]) {
        this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data, offset)
      } else {
        this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data.subarray(array.offset, array.shape[0]), offset)
      }
    } else {
      var tmp = pool.malloc(array.size, dtype)
      var ndt = ndarray(tmp, array.shape)
      ops.assign(ndt, array)
      if(offset < 0) {
        this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp, offset)
      } else {
        this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp.subarray(0, array.size), offset)
      }
      pool.free(tmp)
    }
  } else if(Array.isArray(array)) { //Vanilla array
    var t
    if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) {
      t = makeScratchTypeArray(array, "uint16")
    } else {
      t = makeScratchTypeArray(array, "float32")
    }
    if(offset < 0) {
      this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t, offset)
    } else {
      this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t.subarray(0, array.length), offset)
    }
    pool.free(t)
  } else if(typeof array === "object" && typeof array.length === "number") { //Typed array
    this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array, offset)
  } else if(typeof array === "number" || array === undefined) { //Number/default
    if(offset >= 0) {
      throw new Error("gl-buffer: Cannot specify offset when resizing buffer")
    }
    array = array | 0
    if(array <= 0) {
      array = 1
    }
    this.gl.bufferData(this.type, array|0, this.usage)
    this.length = array
  } else { //Error, case should not happen
    throw new Error("gl-buffer: Invalid data type")
  }
}

function createBuffer(gl, data, type, usage) {
  type = type || gl.ARRAY_BUFFER
  usage = usage || gl.DYNAMIC_DRAW
  if(type !== gl.ARRAY_BUFFER && type !== gl.ELEMENT_ARRAY_BUFFER) {
    throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER")
  }
  if(usage !== gl.DYNAMIC_DRAW && usage !== gl.STATIC_DRAW && usage !== gl.STREAM_DRAW) {
    throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW")
  }
  var handle = gl.createBuffer()
  var result = new GLBuffer(gl, type, handle, 0, usage)
  result.update(data)
  return result
}

module.exports = createBuffer

},{"ndarray":436,"ndarray-ops":430,"typedarray-pool":523}],232:[function(_dereq_,module,exports){
"use strict";

var V = _dereq_('gl-vec3');
var V4 = _dereq_('gl-vec4');

var vec3 = function(x, y, z) {
	var v = V.create();
	if (x !== undefined) {
		V.set(v, x, y, z);
	}
	return v;
}

var createPositionsForMeshgrid = function(meshgrid) {
	var xs = meshgrid[0], ys = meshgrid[1], zs = meshgrid[2];
	var positions = [];
	for (var z=0; z<zs.length; z++) {
		for (var y=0; y<ys.length; y++) {
			for (var x=0; x<xs.length; x++) {
				positions.push([zs[z], ys[y], xs[x]]);
			}
		}
	}
	return positions;
};

var findLastSmallerIndex = function(points, v) {
	for (var i=0; i<points.length; i++) {
		if (points[i] >= v) {
			return i-1;
		}
	}
	return i;
};

var tmp = V.create();
var tmp2 = V.create();

var clamp = function(v, min, max) {
	return v < min ? min : (v > max ? max : v);
};

var sampleMeshgrid = function(point, array, meshgrid, clampOverflow) {
	var x = point[0];
	var y = point[1];
	var z = point[2];

	var w = meshgrid[0].length;
	var h = meshgrid[1].length;
	var d = meshgrid[2].length;

	// Find the index of the nearest smaller value in the meshgrid for each coordinate of (x,y,z).
	// The nearest smaller value index for x is the index x0 such that
	// meshgrid[0][x0] < x and for all x1 > x0, meshgrid[0][x1] >= x.
	var x0 = findLastSmallerIndex(meshgrid[0], x);
	var y0 = findLastSmallerIndex(meshgrid[1], y);
	var z0 = findLastSmallerIndex(meshgrid[2], z);

	// Get the nearest larger meshgrid value indices.
	// From the above "nearest smaller value", we know that
	//   meshgrid[0][x0] < x
	//   meshgrid[0][x0+1] >= x
	var x1 = x0 + 1;
	var y1 = y0 + 1;
	var z1 = z0 + 1;

	if (clampOverflow) {
		x0 = clamp(x0, 0, w-1);
		x1 = clamp(x1, 0, w-1);
		y0 = clamp(y0, 0, h-1);
		y1 = clamp(y1, 0, h-1);
		z0 = clamp(z0, 0, d-1);
		z1 = clamp(z1, 0, d-1);
	}

	// Reject points outside the meshgrid, return a zero vector.
	if (x0 < 0 || y0 < 0 || z0 < 0 || x1 >= w || y1 >= h || z1 >= d) {
		return V.create();
	}

	// Normalize point coordinates to 0..1 scaling factor between x0 and x1.
	var xf = (x - meshgrid[0][x0]) / (meshgrid[0][x1] - meshgrid[0][x0]);
	var yf = (y - meshgrid[1][y0]) / (meshgrid[1][y1] - meshgrid[1][y0]);
	var zf = (z - meshgrid[2][z0]) / (meshgrid[2][z1] - meshgrid[2][z0]);

	if (xf < 0 || xf > 1 || isNaN(xf)) xf = 0;
	if (yf < 0 || yf > 1 || isNaN(yf)) yf = 0;
	if (zf < 0 || zf > 1 || isNaN(zf)) zf = 0;

	var z0off = z0*w*h;
	var z1off = z1*w*h;

	var y0off = y0*w;
	var y1off = y1*w;

	var x0off = x0;
	var x1off = x1;

	// Sample data array around the (x,y,z) point.
	//  vZYX = array[zZoff + yYoff + xXoff]
	var v000 = array[y0off + z0off + x0off];
	var v001 = array[y0off + z0off + x1off];
	var v010 = array[y1off + z0off + x0off];
	var v011 = array[y1off + z0off + x1off];
	var v100 = array[y0off + z1off + x0off];
	var v101 = array[y0off + z1off + x1off];
	var v110 = array[y1off + z1off + x0off];
	var v111 = array[y1off + z1off + x1off];

	var result = V.create();

	// Average samples according to distance to point.
	V.lerp(result, v000, v001, xf);
	V.lerp(tmp, v010, v011, xf);
	V.lerp(result, result, tmp, yf);
	V.lerp(tmp, v100, v101, xf);
	V.lerp(tmp2, v110, v111, xf);
	V.lerp(tmp, tmp, tmp2, yf);
	V.lerp(result, result, tmp, zf);

	return result;
};

var getOrthogonalVector = function(dst, v) {
	// Return up-vector for only-z vector.
	if (v[0] === 0 && v[1] === 0) {
		V.set(dst, 0, 1, 0);
	} else {
		// Return ax + by + cz = 0, a point that lies on the plane that has v as a normal and that isn't (0,0,0).
		// From the above if-statement we have ||a|| > 0  U  ||b|| > 0.
		// Assign z = 0, x = -b, y = a:
		// a*-b + b*a + c*0 = -ba + ba + 0 = 0
		V.set(dst, -v[1], v[0], 0);
	}
	return dst;
};

module.exports = function(vectorfield, bounds) {
	var positions;
	if (vectorfield.positions) {
		positions = vectorfield.positions;
	} else {
		positions = createPositionsForMeshgrid(vectorfield.meshgrid);
	}
	var meshgrid = vectorfield.meshgrid;
	var vectors = vectorfield.vectors;
	var geo = {
		positions: [],
		vertexIntensity: [],
		vertexIntensityBounds: vectorfield.vertexIntensityBounds,
		vertexNormals: [],
		vectors: [],
		cells: [],
		coneOffset: vectorfield.coneOffset,
		colormap: vectorfield.colormap
	};

	if (vectorfield.positions.length === 0) {
		if (bounds) {
			bounds[0] = [0,0,0];
			bounds[1] = [0,0,0];
		}
		return geo;
	}

	// Compute bounding box for the dataset.
	// Compute maximum velocity for the dataset to use for scaling the cones.
	var maxNorm = 0;
	var minX = 1/0, maxX = -1/0;
	var minY = 1/0, maxY = -1/0;
	var minZ = 1/0, maxZ = -1/0;
	var p2 = null;
	var u2 = null;
	var positionVectors = [];
	var vectorScale = 1/0;
	for (var i = 0; i < positions.length; i++) {
		var p = positions[i];
		minX = Math.min(p[0], minX);
		maxX = Math.max(p[0], maxX);
		minY = Math.min(p[1], minY);
		maxY = Math.max(p[1], maxY);
		minZ = Math.min(p[2], minZ);
		maxZ = Math.max(p[2], maxZ);
		var u;
		if (meshgrid) {
			u = sampleMeshgrid(p, vectors, meshgrid, true);
		} else {
			u = vectors[i];
		}
		if (V.length(u) > maxNorm) {
			maxNorm = V.length(u);
		}
		if (i) {
			// Find vector scale [w/ units of time] using "successive" positions
			// (not "adjacent" with would be O(n^2)),
			//
			// The vector scale corresponds to the minimum "time" to travel across two
			// two adjacent positions at the average velocity of those two adjacent positions
			vectorScale = Math.min(vectorScale,
				2 * V.distance(p2, p) / (V.length(u2) + V.length(u))
			);
		}
		p2 = p;
		u2 = u;
		positionVectors.push(u);
	}
	var minV = [minX, minY, minZ];
	var maxV = [maxX, maxY, maxZ];
	if (bounds) {
		bounds[0] = minV;
		bounds[1] = maxV;
	}
	if (maxNorm === 0) {
		maxNorm = 1;
	}

	// Inverted max norm would map vector with norm maxNorm to 1 coord space units in length
	var invertedMaxNorm = 1 / maxNorm;

	if (!isFinite(vectorScale) || isNaN(vectorScale)) {
		vectorScale = 1.0;
	}
	geo.vectorScale = vectorScale;

	var nml = vec3(0,1,0);

	var coneScale = vectorfield.coneSize || 0.5;

	if (vectorfield.absoluteConeSize) {
		coneScale = vectorfield.absoluteConeSize * invertedMaxNorm;
	}

	geo.coneScale = coneScale;

	// Build the cone model.
	for (var i = 0, j = 0; i < positions.length; i++) {
		var p = positions[i];
		var x = p[0], y = p[1], z = p[2];
		var d = positionVectors[i];
		var intensity = V.length(d) * invertedMaxNorm;
		for (var k = 0, l = 8; k < l; k++) {
			geo.positions.push([x, y, z, j++]);
			geo.positions.push([x, y, z, j++]);
			geo.positions.push([x, y, z, j++]);
			geo.positions.push([x, y, z, j++]);
			geo.positions.push([x, y, z, j++]);
			geo.positions.push([x, y, z, j++]);

			geo.vectors.push(d);
			geo.vectors.push(d);
			geo.vectors.push(d);
			geo.vectors.push(d);
			geo.vectors.push(d);
			geo.vectors.push(d);

			geo.vertexIntensity.push(intensity, intensity, intensity);
			geo.vertexIntensity.push(intensity, intensity, intensity);

			geo.vertexNormals.push(nml, nml, nml);
			geo.vertexNormals.push(nml, nml, nml);

			var m = geo.positions.length;
			geo.cells.push([m-6, m-5, m-4], [m-3, m-2, m-1]);
		}
	}

	return geo;
};

module.exports.createConeMesh = _dereq_('./lib/conemesh');

},{"./lib/conemesh":234,"gl-vec3":332,"gl-vec4":368}],233:[function(_dereq_,module,exports){
'use strict'

var barycentric            = _dereq_('barycentric')
var closestPointToTriangle = _dereq_('polytope-closest-point/lib/closest_point_2d.js')

module.exports = closestPointToPickLocation

function xformMatrix(m, v) {
  var out = [0,0,0,0]
  for(var i=0; i<4; ++i) {
    for(var j=0; j<4; ++j) {
      out[j] += m[4*i + j] * v[i]
    }
  }
  return out
}

function projectVertex(v, model, view, projection, resolution) {
  var p = xformMatrix(projection,
            xformMatrix(view,
              xformMatrix(model, [v[0], v[1], v[2], 1])))
  for(var i=0; i<3; ++i) {
    p[i] /= p[3]
  }
  return [ 0.5 * resolution[0] * (1.0+p[0]), 0.5 * resolution[1] * (1.0-p[1]) ]
}

function barycentricCoord(simplex, point) {
  if(simplex.length === 2) {
    var d0 = 0.0
    var d1 = 0.0
    for(var i=0; i<2; ++i) {
      d0 += Math.pow(point[i] - simplex[0][i], 2)
      d1 += Math.pow(point[i] - simplex[1][i], 2)
    }
    d0 = Math.sqrt(d0)
    d1 = Math.sqrt(d1)
    if(d0+d1 < 1e-6) {
      return [1,0]
    }
    return [d1/(d0+d1),d0/(d1+d0)]
  } else if(simplex.length === 3) {
    var closestPoint = [0,0]
    closestPointToTriangle(simplex[0], simplex[1], simplex[2], point, closestPoint)
    return barycentric(simplex, closestPoint)
  }
  return []
}

function interpolate(simplex, weights) {
  var result = [0,0,0]
  for(var i=0; i<simplex.length; ++i) {
    var p = simplex[i]
    var w = weights[i]
    for(var j=0; j<3; ++j) {
      result[j] += w * p[j]
    }
  }
  return result
}

function closestPointToPickLocation(simplex, pixelCoord, model, view, projection, resolution) {
  if(simplex.length === 1) {
    return [0, simplex[0].slice()]
  }
  var simplex2D = new Array(simplex.length)
  for(var i=0; i<simplex.length; ++i) {
    simplex2D[i] = projectVertex(simplex[i], model, view, projection, resolution);
  }

  var closestIndex = 0
  var closestDist  = Infinity
  for(var i=0; i<simplex2D.length; ++i) {
    var d2 = 0.0
    for(var j=0; j<2; ++j) {
      d2 += Math.pow(simplex2D[i][j] - pixelCoord[j], 2)
    }
    if(d2 < closestDist) {
      closestDist  = d2
      closestIndex = i
    }
  }

  var weights = barycentricCoord(simplex2D, pixelCoord)
  var s = 0.0
  for(var i=0; i<3; ++i) {
    if(weights[i] < -0.001 ||
       weights[i] > 1.0001) {
      return null
    }
    s += weights[i]
  }
  if(Math.abs(s - 1.0) > 0.001) {
    return null
  }
  return [closestIndex, interpolate(simplex, weights), weights]
}
},{"barycentric":62,"polytope-closest-point/lib/closest_point_2d.js":467}],234:[function(_dereq_,module,exports){
'use strict'

var DEFAULT_VERTEX_NORMALS_EPSILON = 1e-6; // may be too large if triangles are very small
var DEFAULT_FACE_NORMALS_EPSILON = 1e-6;

var createShader  = _dereq_('gl-shader')
var createBuffer  = _dereq_('gl-buffer')
var createVAO     = _dereq_('gl-vao')
var createTexture = _dereq_('gl-texture2d')
var normals       = _dereq_('normals')
var multiply      = _dereq_('gl-mat4/multiply')
var invert        = _dereq_('gl-mat4/invert')
var ndarray       = _dereq_('ndarray')
var colormap      = _dereq_('colormap')
var getContour    = _dereq_('simplicial-complex-contour')
var pool          = _dereq_('typedarray-pool')
var shaders       = _dereq_('./shaders')
var closestPoint  = _dereq_('./closest-point')

var meshShader    = shaders.meshShader
var pickShader    = shaders.pickShader

var identityMatrix = [
  1,0,0,0,
  0,1,0,0,
  0,0,1,0,
  0,0,0,1]

function SimplicialMesh(gl
  , texture
  , triShader
  , lineShader
  , pointShader
  , pickShader
  , pointPickShader
  , contourShader
  , trianglePositions
  , triangleVectors
  , triangleIds
  , triangleColors
  , triangleUVs
  , triangleNormals
  , triangleVAO
  , edgePositions
  , edgeIds
  , edgeColors
  , edgeUVs
  , edgeVAO
  , pointPositions
  , pointIds
  , pointColors
  , pointUVs
  , pointSizes
  , pointVAO
  , contourPositions
  , contourVAO) {

  this.gl                = gl
  this.cells             = []
  this.positions         = []
  this.intensity         = []
  this.texture           = texture
  this.dirty             = true

  this.triShader         = triShader
  this.lineShader        = lineShader
  this.pointShader       = pointShader
  this.pickShader        = pickShader
  this.pointPickShader   = pointPickShader
  this.contourShader     = contourShader

  this.trianglePositions = trianglePositions
  this.triangleVectors   = triangleVectors
  this.triangleColors    = triangleColors
  this.triangleNormals   = triangleNormals
  this.triangleUVs       = triangleUVs
  this.triangleIds       = triangleIds
  this.triangleVAO       = triangleVAO
  this.triangleCount     = 0

  this.lineWidth         = 1
  this.edgePositions     = edgePositions
  this.edgeColors        = edgeColors
  this.edgeUVs           = edgeUVs
  this.edgeIds           = edgeIds
  this.edgeVAO           = edgeVAO
  this.edgeCount         = 0

  this.pointPositions    = pointPositions
  this.pointColors       = pointColors
  this.pointUVs          = pointUVs
  this.pointSizes        = pointSizes
  this.pointIds          = pointIds
  this.pointVAO          = pointVAO
  this.pointCount        = 0

  this.contourLineWidth  = 1
  this.contourPositions  = contourPositions
  this.contourVAO        = contourVAO
  this.contourCount      = 0
  this.contourColor      = [0,0,0]
  this.contourEnable     = true

  this.pickId            = 1
  this.bounds            = [
    [ Infinity, Infinity, Infinity],
    [-Infinity,-Infinity,-Infinity] ]
  this.clipBounds        = [
    [-Infinity,-Infinity,-Infinity],
    [ Infinity, Infinity, Infinity] ]

  this.lightPosition = [1e5, 1e5, 0]
  this.ambientLight  = 0.8
  this.diffuseLight  = 0.8
  this.specularLight = 2.0
  this.roughness     = 0.5
  this.fresnel       = 1.5

  this.opacity       = 1.0

  this.coneScale     = 2.0
  this.vectorScale   = 1.0
  this.coneOffset    = 1.0 / 4.0;

  this._model       = identityMatrix
  this._view        = identityMatrix
  this._projection  = identityMatrix
  this._resolution  = [1,1]
}

var proto = SimplicialMesh.prototype

proto.isOpaque = function() {
  return this.opacity >= 1
}

proto.isTransparent = function() {
  return this.opacity < 1
}

proto.pickSlots = 1

proto.setPickBase = function(id) {
  this.pickId = id
}

function genColormap(param) {
  var colors = colormap({
      colormap: param
    , nshades:  256
    , format:  'rgba'
  })

  var result = new Uint8Array(256*4)
  for(var i=0; i<256; ++i) {
    var c = colors[i]
    for(var j=0; j<3; ++j) {
      result[4*i+j] = c[j]
    }
    result[4*i+3] = c[3]*255
  }

  return ndarray(result, [256,256,4], [4,0,1])
}

function unpackIntensity(cells, numVerts, cellIntensity) {
  var result = new Array(numVerts)
  for(var i=0; i<numVerts; ++i) {
    result[i] = 0
  }
  var numCells = cells.length
  for(var i=0; i<numCells; ++i) {
    var c = cells[i]
    for(var j=0; j<c.length; ++j) {
      result[c[j]] = cellIntensity[i]
    }
  }
  return result
}

function takeZComponent(array) {
  var n = array.length
  var result = new Array(n)
  for(var i=0; i<n; ++i) {
    result[i] = array[i][2]
  }
  return result
}

proto.highlight = function(selection) {
  if(!selection || !this.contourEnable) {
    this.contourCount = 0
    return
  }
  var level = getContour(this.cells, this.intensity, selection.intensity)
  var cells         = level.cells
  var vertexIds     = level.vertexIds
  var vertexWeights = level.vertexWeights
  var numCells = cells.length
  var result = pool.mallocFloat32(2 * 3 * numCells)
  var ptr = 0
  for(var i=0; i<numCells; ++i) {
    var c = cells[i]
    for(var j=0; j<2; ++j) {
      var v = c[0]
      if(c.length === 2) {
        v = c[j]
      }
      var a = vertexIds[v][0]
      var b = vertexIds[v][1]
      var w = vertexWeights[v]
      var wi = 1.0 - w
      var pa = this.positions[a]
      var pb = this.positions[b]
      for(var k=0; k<3; ++k) {
        result[ptr++] = w * pa[k] + wi * pb[k]
      }
    }
  }
  this.contourCount = (ptr / 3)|0
  this.contourPositions.update(result.subarray(0, ptr))
  pool.free(result)
}

proto.update = function(params) {
  params = params || {}
  var gl = this.gl

  this.dirty = true

  if('contourEnable' in params) {
    this.contourEnable = params.contourEnable
  }
  if('contourColor' in params) {
    this.contourColor = params.contourColor
  }
  if('lineWidth' in params) {
    this.lineWidth = params.lineWidth
  }
  if('lightPosition' in params) {
    this.lightPosition = params.lightPosition
  }
  if('opacity' in params) {
    this.opacity = params.opacity
  }
  if('ambient' in params) {
    this.ambientLight  = params.ambient
  }
  if('diffuse' in params) {
    this.diffuseLight = params.diffuse
  }
  if('specular' in params) {
    this.specularLight = params.specular
  }
  if('roughness' in params) {
    this.roughness = params.roughness
  }
  if('fresnel' in params) {
    this.fresnel = params.fresnel
  }

  if (params.vectorScale !== undefined) {
    this.vectorScale = params.vectorScale;
  }
  if (params.coneScale !== undefined) {
    this.coneScale = params.coneScale;
  }
  if (params.coneOffset !== undefined) {
    this.coneOffset = params.coneOffset;
  }

  if(params.texture) {
    this.texture.dispose()
    this.texture = createTexture(gl, params.texture)
  } else if (params.colormap) {
    this.texture.shape = [256,256]
    this.texture.minFilter = gl.LINEAR_MIPMAP_LINEAR
    this.texture.magFilter = gl.LINEAR
    this.texture.setPixels(genColormap(params.colormap))
    this.texture.generateMipmap()
  }

  var cells = params.cells
  var positions = params.positions
  var vectors = params.vectors

  if(!positions || !cells || !vectors) {
    return
  }

  var tPos = []
  var tVec = []
  var tCol = []
  var tNor = []
  var tUVs = []
  var tIds = []

  var ePos = []
  var eCol = []
  var eUVs = []
  var eIds = []

  var pPos = []
  var pCol = []
  var pUVs = []
  var pSiz = []
  var pIds = []

  //Save geometry data for picking calculations
  this.cells     = cells
  this.positions = positions

  //Compute normals
  var vertexNormals = params.vertexNormals
  var cellNormals   = params.cellNormals
  var vertexNormalsEpsilon = params.vertexNormalsEpsilon === void(0) ? DEFAULT_VERTEX_NORMALS_EPSILON : params.vertexNormalsEpsilon
  var faceNormalsEpsilon = params.faceNormalsEpsilon === void(0) ? DEFAULT_FACE_NORMALS_EPSILON : params.faceNormalsEpsilon
  if(params.useFacetNormals && !cellNormals) {
    cellNormals = normals.faceNormals(cells, positions, faceNormalsEpsilon)
  }
  if(!cellNormals && !vertexNormals) {
    vertexNormals = normals.vertexNormals(cells, positions, vertexNormalsEpsilon)
  }

  //Compute colors
  var vertexColors    = params.vertexColors
  var cellColors      = params.cellColors
  var meshColor       = params.meshColor || [1,1,1,1]

  //UVs
  var vertexUVs       = params.vertexUVs
  var vertexIntensity = params.vertexIntensity
  var cellUVs         = params.cellUVs
  var cellIntensity   = params.cellIntensity

  var intensityLo     = Infinity
  var intensityHi     = -Infinity
  if(!vertexUVs && !cellUVs) {
    if(vertexIntensity) {
      if(params.vertexIntensityBounds) {
        intensityLo = +params.vertexIntensityBounds[0]
        intensityHi = +params.vertexIntensityBounds[1]
      } else {
        for(var i=0; i<vertexIntensity.length; ++i) {
          var f = vertexIntensity[i]
          intensityLo = Math.min(intensityLo, f)
          intensityHi = Math.max(intensityHi, f)
        }
      }
    } else if(cellIntensity) {
      for(var i=0; i<cellIntensity.length; ++i) {
        var f = cellIntensity[i]
        intensityLo = Math.min(intensityLo, f)
        intensityHi = Math.max(intensityHi, f)
      }
    } else {
      for(var i=0; i<positions.length; ++i) {
        var f = positions[i][2]
        intensityLo = Math.min(intensityLo, f)
        intensityHi = Math.max(intensityHi, f)
      }
    }
  }

  if(vertexIntensity) {
    this.intensity = vertexIntensity
  } else if(cellIntensity) {
    this.intensity = unpackIntensity(cells, positions.length, cellIntensity)
  } else {
    this.intensity = takeZComponent(positions)
  }

  //Point size
  var pointSizes      = params.pointSizes
  var meshPointSize   = params.pointSize || 1.0

  //Update bounds
  this.bounds       = [[Infinity,Infinity,Infinity], [-Infinity,-Infinity,-Infinity]]
  for(var i=0; i<positions.length; ++i) {
    var p = positions[i]
    for(var j=0; j<3; ++j) {
      if(isNaN(p[j]) || !isFinite(p[j])) {
        continue
      }
      this.bounds[0][j] = Math.min(this.bounds[0][j], p[j])
      this.bounds[1][j] = Math.max(this.bounds[1][j], p[j])
    }
  }

  //Pack cells into buffers
  var triangleCount = 0
  var edgeCount = 0
  var pointCount = 0

fill_loop:
  for(var i=0; i<cells.length; ++i) {
    var cell = cells[i]
    switch(cell.length) {
      case 1:

        var v = cell[0]
        var p = positions[v]

        //Check NaNs
        for(var j=0; j<3; ++j) {
          if(isNaN(p[j]) || !isFinite(p[j])) {
            continue fill_loop
          }
        }

        pPos.push(p[0], p[1], p[2], p[3])

        var c
        if(vertexColors) {
          c = vertexColors[v]
        } else if(cellColors) {
          c = cellColors[i]
        } else {
          c = meshColor
        }
        if(c.length === 3) {
          pCol.push(c[0], c[1], c[2], 1)
        } else {
          pCol.push(c[0], c[1], c[2], c[3])
        }

        var uv
        if(vertexUVs) {
          uv = vertexUVs[v]
        } else if(vertexIntensity) {
          uv = [
            (vertexIntensity[v] - intensityLo) /
            (intensityHi - intensityLo), 0]
        } else if(cellUVs) {
          uv = cellUVs[i]
        } else if(cellIntensity) {
          uv = [
            (cellIntensity[i] - intensityLo) /
            (intensityHi - intensityLo), 0]
        } else {
          uv = [
            (p[2] - intensityLo) /
            (intensityHi - intensityLo), 0]
        }
        pUVs.push(uv[0], uv[1])

        if(pointSizes) {
          pSiz.push(pointSizes[v])
        } else {
          pSiz.push(meshPointSize)
        }

        pIds.push(i)

        pointCount += 1
      break

      case 2:

        //Check NaNs
        for(var j=0; j<2; ++j) {
          var v = cell[j]
          var p = positions[v]
          for(var k=0; k<3; ++k) {
            if(isNaN(p[k]) || !isFinite(p[k])) {
              continue fill_loop
            }
          }
        }

        for(var j=0; j<2; ++j) {
          var v = cell[j]
          var p = positions[v]

          ePos.push(p[0], p[1], p[2])

          var c
          if(vertexColors) {
            c = vertexColors[v]
          } else if(cellColors) {
            c = cellColors[i]
          } else {
            c = meshColor
          }
          if(c.length === 3) {
            eCol.push(c[0], c[1], c[2], 1)
          } else {
            eCol.push(c[0], c[1], c[2], c[3])
          }

          var uv
          if(vertexUVs) {
            uv = vertexUVs[v]
          } else if(vertexIntensity) {
            uv = [
              (vertexIntensity[v] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else if(cellUVs) {
            uv = cellUVs[i]
          } else if(cellIntensity) {
            uv = [
              (cellIntensity[i] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else {
            uv = [
              (p[2] - intensityLo) /
              (intensityHi - intensityLo), 0]
          }
          eUVs.push(uv[0], uv[1])

          eIds.push(i)
        }
        edgeCount += 1
      break

      case 3:
        //Check NaNs
        for(var j=0; j<3; ++j) {
          var v = cell[j]
          var p = positions[v]
          for(var k=0; k<3; ++k) {
            if(isNaN(p[k]) || !isFinite(p[k])) {
              continue fill_loop
            }
          }
        }

        for(var j=0; j<3; ++j) {
          var v = cell[j]

          var p = positions[v]
          tPos.push(p[0], p[1], p[2], p[3])

          var w = vectors[v]
          tVec.push(w[0], w[1], w[2]);

          var c
          if(vertexColors) {
            c = vertexColors[v]
          } else if(cellColors) {
            c = cellColors[i]
          } else {
            c = meshColor
          }
          if(c.length === 3) {
            tCol.push(c[0], c[1], c[2], 1)
          } else {
            tCol.push(c[0], c[1], c[2], c[3])
          }

          var uv
          if(vertexUVs) {
            uv = vertexUVs[v]
          } else if(vertexIntensity) {
            uv = [
              (vertexIntensity[v] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else if(cellUVs) {
            uv = cellUVs[i]
          } else if(cellIntensity) {
            uv = [
              (cellIntensity[i] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else {
            uv = [
              (p[2] - intensityLo) /
              (intensityHi - intensityLo), 0]
          }
          tUVs.push(uv[0], uv[1])

          var q
          if(vertexNormals) {
            q = vertexNormals[v]
          } else {
            q = cellNormals[i]
          }
          tNor.push(q[0], q[1], q[2])

          tIds.push(i)
        }
        triangleCount += 1
      break

      default:
      break
    }
  }

  this.pointCount     = pointCount
  this.edgeCount      = edgeCount
  this.triangleCount  = triangleCount

  this.pointPositions.update(pPos)
  this.pointColors.update(pCol)
  this.pointUVs.update(pUVs)
  this.pointSizes.update(pSiz)
  this.pointIds.update(new Uint32Array(pIds))

  this.edgePositions.update(ePos)
  this.edgeColors.update(eCol)
  this.edgeUVs.update(eUVs)
  this.edgeIds.update(new Uint32Array(eIds))

  this.trianglePositions.update(tPos)
  this.triangleVectors.update(tVec)
  this.triangleColors.update(tCol)
  this.triangleUVs.update(tUVs)
  this.triangleNormals.update(tNor)
  this.triangleIds.update(new Uint32Array(tIds))
}

proto.drawTransparent = proto.draw = function(params) {
  params = params || {}
  var gl          = this.gl
  var model       = params.model      || identityMatrix
  var view        = params.view       || identityMatrix
  var projection  = params.projection || identityMatrix

  var clipBounds = [[-1e6,-1e6,-1e6],[1e6,1e6,1e6]]
  for(var i=0; i<3; ++i) {
    clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i])
    clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i])
  }

  var uniforms = {
    model:      model,
    view:       view,
    projection: projection,

    clipBounds: clipBounds,

    kambient:   this.ambientLight,
    kdiffuse:   this.diffuseLight,
    kspecular:  this.specularLight,
    roughness:  this.roughness,
    fresnel:    this.fresnel,

    eyePosition:   [0,0,0],
    lightPosition: [0,0,0],

    opacity:  this.opacity,

    vectorScale: this.vectorScale,
    coneScale: this.coneScale,
    coneOffset: this.coneOffset,

    contourColor: this.contourColor,

    texture:    0
  }

  this.texture.bind(0)

  var invCameraMatrix = new Array(16)
  multiply(invCameraMatrix, uniforms.view, uniforms.model)
  multiply(invCameraMatrix, uniforms.projection, invCameraMatrix)
  invert(invCameraMatrix, invCameraMatrix)

  for(var i=0; i<3; ++i) {
    uniforms.eyePosition[i] = invCameraMatrix[12+i] / invCameraMatrix[15]
  }

  var w = invCameraMatrix[15]
  for(var i=0; i<3; ++i) {
    w += this.lightPosition[i] * invCameraMatrix[4*i+3]
  }
  for(var i=0; i<3; ++i) {
    var s = invCameraMatrix[12+i]
    for(var j=0; j<3; ++j) {
      s += invCameraMatrix[4*j+i] * this.lightPosition[j]
    }
    uniforms.lightPosition[i] = s / w
  }

  if(this.triangleCount > 0) {
    var shader = this.triShader
    shader.bind()
    shader.uniforms = uniforms

    this.triangleVAO.bind()
    gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3)
    this.triangleVAO.unbind()
  }

  if(this.edgeCount > 0 && this.lineWidth > 0) {
    var shader = this.lineShader
    shader.bind()
    shader.uniforms = uniforms

    this.edgeVAO.bind()
    gl.lineWidth(this.lineWidth)
    gl.drawArrays(gl.LINES, 0, this.edgeCount*2)
    this.edgeVAO.unbind()
  }

  if(this.pointCount > 0) {
    var shader = this.pointShader
    shader.bind()
    shader.uniforms = uniforms

    this.pointVAO.bind()
    gl.drawArrays(gl.POINTS, 0, this.pointCount)
    this.pointVAO.unbind()
  }

  if(this.contourEnable && this.contourCount > 0 && this.contourLineWidth > 0) {
    var shader = this.contourShader
    shader.bind()
    shader.uniforms = uniforms

    this.contourVAO.bind()
    gl.drawArrays(gl.LINES, 0, this.contourCount)
    this.contourVAO.unbind()
  }
}

proto.drawPick = function(params) {
  params = params || {}

  var gl         = this.gl

  var model      = params.model      || identityMatrix
  var view       = params.view       || identityMatrix
  var projection = params.projection || identityMatrix

  var clipBounds = [[-1e6,-1e6,-1e6],[1e6,1e6,1e6]]
  for(var i=0; i<3; ++i) {
    clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i])
    clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i])
  }

  //Save camera parameters
  this._model      = [].slice.call(model)
  this._view       = [].slice.call(view)
  this._projection = [].slice.call(projection)
  this._resolution = [gl.drawingBufferWidth, gl.drawingBufferHeight]

  var uniforms = {
    model:      model,
    view:       view,
    projection: projection,
    clipBounds: clipBounds,

    vectorScale: this.vectorScale,
    coneScale: this.coneScale,
    coneOffset: this.coneOffset,

    pickId:     this.pickId / 255.0,
  }

  var shader = this.pickShader
  shader.bind()
  shader.uniforms = uniforms

  if(this.triangleCount > 0) {
    this.triangleVAO.bind()
    gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3)
    this.triangleVAO.unbind()
  }

  if(this.edgeCount > 0) {
    this.edgeVAO.bind()
    gl.lineWidth(this.lineWidth)
    gl.drawArrays(gl.LINES, 0, this.edgeCount*2)
    this.edgeVAO.unbind()
  }

  if(this.pointCount > 0) {
    var shader = this.pointPickShader
    shader.bind()
    shader.uniforms = uniforms

    this.pointVAO.bind()
    gl.drawArrays(gl.POINTS, 0, this.pointCount)
    this.pointVAO.unbind()
  }
}


proto.pick = function(pickData) {
  if(!pickData) {
    return null
  }
  if(pickData.id !== this.pickId) {
    return null
  }

  var cellId    = pickData.value[0] + 256*pickData.value[1] + 65536*pickData.value[2]
  var cell      = this.cells[cellId]
  var pos =     this.positions[cell[1]].slice(0, 3)

  return {
    // corresponding to input indices
    index: Math.floor(cell[1] / 48),
    position: pos,
    dataCoordinate: pos
  }
}


proto.dispose = function() {
  this.texture.dispose()

  this.triShader.dispose()
  // this.lineShader.dispose()
  // this.pointShader.dispose()
  this.pickShader.dispose()
  // this.pointPickShader.dispose()

  this.triangleVAO.dispose()
  this.trianglePositions.dispose()
  this.triangleVectors.dispose()
  this.triangleColors.dispose()
  this.triangleUVs.dispose()
  this.triangleNormals.dispose()
  this.triangleIds.dispose()

  this.edgeVAO.dispose()
  this.edgePositions.dispose()
  this.edgeColors.dispose()
  this.edgeUVs.dispose()
  this.edgeIds.dispose()

  this.pointVAO.dispose()
  this.pointPositions.dispose()
  this.pointColors.dispose()
  this.pointUVs.dispose()
  this.pointSizes.dispose()
  this.pointIds.dispose()

  this.contourVAO.dispose()
  this.contourPositions.dispose()
  // this.contourShader.dispose()
}

function createMeshShader(gl) {
  // need to pass meshShader attributes manually,
  // to make this work on etpinard's Ubuntu Thinkpad
  var shader = createShader(gl, meshShader.vertex, meshShader.fragment, null, meshShader.attributes)
  shader.attributes.position.location = 0
  shader.attributes.color.location    = 2
  shader.attributes.uv.location       = 3
  shader.attributes.vector.location   = 5
  return shader
}

function createWireShader(gl) {
  var shader = createShader(gl, wireShader.vertex, wireShader.fragment)
  shader.attributes.position.location = 0
  shader.attributes.color.location    = 2
  shader.attributes.uv.location       = 3
  return shader
}

function createPointShader(gl) {
  var shader = createShader(gl, pointShader.vertex, pointShader.fragment)
  shader.attributes.position.location  = 0
  shader.attributes.color.location     = 2
  shader.attributes.uv.location        = 3
  shader.attributes.pointSize.location = 4
  return shader
}

function createPickShader(gl) {
  var shader = createShader(gl, pickShader.vertex, pickShader.fragment, null, pickShader.attributes)
  shader.attributes.position.location = 0
  shader.attributes.id.location       = 1
  shader.attributes.vector.location   = 5
  return shader
}

function createPointPickShader(gl) {
  var shader = createShader(gl, pointPickShader.vertex, pointPickShader.fragment)
  shader.attributes.position.location  = 0
  shader.attributes.id.location        = 1
  shader.attributes.pointSize.location = 4
  return shader
}

function createContourShader(gl) {
  var shader = createShader(gl, contourShader.vertex, contourShader.fragment)
  shader.attributes.position.location = 0
  return shader
}

function createSimplicialMesh(gl, params) {
  if (arguments.length === 1) {
    params = gl;
    gl = params.gl;
  }

  var triShader       = params.triShader || createMeshShader(gl)
  var lineShader      = null; //createWireShader(gl)
  var pointShader     = null; //createPointShader(gl)
  var pickShader      = createPickShader(gl)
  var pointPickShader = null; //createPointPickShader(gl)
  var contourShader   = null; //createContourShader(gl)

  var meshTexture       = createTexture(gl,
    ndarray(new Uint8Array([255,255,255,255]), [1,1,4]))
  meshTexture.generateMipmap()
  meshTexture.minFilter = gl.LINEAR_MIPMAP_LINEAR
  meshTexture.magFilter = gl.LINEAR

  var trianglePositions = createBuffer(gl)
  var triangleVectors   = createBuffer(gl)
  var triangleColors    = createBuffer(gl)
  var triangleUVs       = createBuffer(gl)
  var triangleNormals   = createBuffer(gl)
  var triangleIds       = createBuffer(gl)
  var triangleVAO       = createVAO(gl, [
    { buffer: trianglePositions,
      type: gl.FLOAT,
      size: 4
    },
    { buffer: triangleIds,
      type: gl.UNSIGNED_BYTE,
      size: 4,
      normalized: true
    },
    { buffer: triangleColors,
      type: gl.FLOAT,
      size: 4
    },
    { buffer: triangleUVs,
      type: gl.FLOAT,
      size: 2
    },
    { buffer: triangleNormals,
      type: gl.FLOAT,
      size: 3
    },
    { buffer: triangleVectors,
      type: gl.FLOAT,
      size: 3
    }
  ])

  var edgePositions = createBuffer(gl)
  var edgeColors    = createBuffer(gl)
  var edgeUVs       = createBuffer(gl)
  var edgeIds       = createBuffer(gl)
  var edgeVAO       = createVAO(gl, [
    { buffer: edgePositions,
      type: gl.FLOAT,
      size: 3
    },
    { buffer: edgeIds,
      type: gl.UNSIGNED_BYTE,
      size: 4,
      normalized: true
    },
    { buffer: edgeColors,
      type: gl.FLOAT,
      size: 4
    },
    { buffer: edgeUVs,
      type: gl.FLOAT,
      size: 2
    }
  ])

  var pointPositions  = createBuffer(gl)
  var pointColors     = createBuffer(gl)
  var pointUVs        = createBuffer(gl)
  var pointSizes      = createBuffer(gl)
  var pointIds        = createBuffer(gl)
  var pointVAO        = createVAO(gl, [
    { buffer: pointPositions,
      type: gl.FLOAT,
      size: 3
    },
    { buffer: pointIds,
      type: gl.UNSIGNED_BYTE,
      size: 4,
      normalized: true
    },
    { buffer: pointColors,
      type: gl.FLOAT,
      size: 4
    },
    { buffer: pointUVs,
      type: gl.FLOAT,
      size: 2
    },
    { buffer: pointSizes,
      type: gl.FLOAT,
      size: 1
    }
  ])

  var contourPositions = createBuffer(gl)
  var contourVAO       = createVAO(gl, [
    { buffer: contourPositions,
      type:   gl.FLOAT,
      size:   3
    }])

  var mesh = new SimplicialMesh(gl
    , meshTexture
    , triShader
    , lineShader
    , pointShader
    , pickShader
    , pointPickShader
    , contourShader
    , trianglePositions
    , triangleVectors
    , triangleIds
    , triangleColors
    , triangleUVs
    , triangleNormals
    , triangleVAO
    , edgePositions
    , edgeIds
    , edgeColors
    , edgeUVs
    , edgeVAO
    , pointPositions
    , pointIds
    , pointColors
    , pointUVs
    , pointSizes
    , pointVAO
    , contourPositions
    , contourVAO)

  mesh.update(params)

  return mesh
}

module.exports = createSimplicialMesh

},{"./closest-point":233,"./shaders":235,"colormap":115,"gl-buffer":231,"gl-mat4/invert":256,"gl-mat4/multiply":258,"gl-shader":290,"gl-texture2d":308,"gl-vao":313,"ndarray":436,"normals":439,"simplicial-complex-contour":496,"typedarray-pool":523}],235:[function(_dereq_,module,exports){
var glslify       = _dereq_('glslify')

var triVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nfloat inverse(float m) {\n  return 1.0 / m;\n}\n\nmat2 inverse(mat2 m) {\n  return mat2(m[1][1],-m[0][1],\n             -m[1][0], m[0][0]) / (m[0][0]*m[1][1] - m[0][1]*m[1][0]);\n}\n\nmat3 inverse(mat3 m) {\n  float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];\n  float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];\n  float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];\n\n  float b01 = a22 * a11 - a12 * a21;\n  float b11 = -a22 * a10 + a12 * a20;\n  float b21 = a21 * a10 - a11 * a20;\n\n  float det = a00 * b01 + a01 * b11 + a02 * b21;\n\n  return mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),\n              b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),\n              b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;\n}\n\nmat4 inverse(mat4 m) {\n  float\n      a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3],\n      a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3],\n      a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3],\n      a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3],\n\n      b00 = a00 * a11 - a01 * a10,\n      b01 = a00 * a12 - a02 * a10,\n      b02 = a00 * a13 - a03 * a10,\n      b03 = a01 * a12 - a02 * a11,\n      b04 = a01 * a13 - a03 * a11,\n      b05 = a02 * a13 - a03 * a12,\n      b06 = a20 * a31 - a21 * a30,\n      b07 = a20 * a32 - a22 * a30,\n      b08 = a20 * a33 - a23 * a30,\n      b09 = a21 * a32 - a22 * a31,\n      b10 = a21 * a33 - a23 * a31,\n      b11 = a22 * a33 - a23 * a32,\n\n      det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n  return mat4(\n      a11 * b11 - a12 * b10 + a13 * b09,\n      a02 * b10 - a01 * b11 - a03 * b09,\n      a31 * b05 - a32 * b04 + a33 * b03,\n      a22 * b04 - a21 * b05 - a23 * b03,\n      a12 * b08 - a10 * b11 - a13 * b07,\n      a00 * b11 - a02 * b08 + a03 * b07,\n      a32 * b02 - a30 * b05 - a33 * b01,\n      a20 * b05 - a22 * b02 + a23 * b01,\n      a10 * b10 - a11 * b08 + a13 * b06,\n      a01 * b08 - a00 * b10 - a03 * b06,\n      a30 * b04 - a31 * b02 + a33 * b00,\n      a21 * b02 - a20 * b04 - a23 * b00,\n      a11 * b07 - a10 * b09 - a12 * b06,\n      a00 * b09 - a01 * b07 + a02 * b06,\n      a31 * b01 - a30 * b03 - a32 * b00,\n      a20 * b03 - a21 * b01 + a22 * b00) / det;\n}\n\nvec3 getOrthogonalVector(vec3 v) {\n  // Return up-vector for only-z vector.\n  // Return ax + by + cz = 0, a point that lies on the plane that has v as a normal and that isn't (0,0,0).\n  // From the above if-statement we have ||a|| > 0  U  ||b|| > 0.\n  // Assign z = 0, x = -b, y = a:\n  // a*-b + b*a + c*0 = -ba + ba + 0 = 0\n  if (v.x*v.x > v.z*v.z || v.y*v.y > v.z*v.z) {\n    return normalize(vec3(-v.y, v.x, 0.0));\n  } else {\n    return normalize(vec3(0.0, v.z, -v.y));\n  }\n}\n\n// Calculate the cone vertex and normal at the given index.\n//\n// The returned vertex is for a cone with its top at origin and height of 1.0,\n// pointing in the direction of the vector attribute.\n//\n// Each cone is made up of a top vertex, a center base vertex and base perimeter vertices.\n// These vertices are used to make up the triangles of the cone by the following:\n//   segment + 0 top vertex\n//   segment + 1 perimeter vertex a+1\n//   segment + 2 perimeter vertex a\n//   segment + 3 center base vertex\n//   segment + 4 perimeter vertex a\n//   segment + 5 perimeter vertex a+1\n// Where segment is the number of the radial segment * 6 and a is the angle at that radial segment.\n// To go from index to segment, floor(index / 6)\n// To go from segment to angle, 2*pi * (segment/segmentCount)\n// To go from index to segment index, index - (segment*6)\n//\nvec3 getConePosition(vec3 d, float index, float coneOffset, out vec3 normal) {\n\n  const float segmentCount = 8.0;\n\n  index = mod(index, segmentCount * 6.0);\n\n  float segment = floor(index/6.0);\n  float segmentIndex = index - (segment*6.0);\n\n  normal = -normalize(d);\n\n  if (segmentIndex == 3.0) {\n    return mix(vec3(0.0), -d, coneOffset);\n  }\n\n  // angle = 2pi * ((segment + ((segmentIndex == 1.0 || segmentIndex == 5.0) ? 1.0 : 0.0)) / segmentCount)\n  float nextAngle = float(segmentIndex == 1.0 || segmentIndex == 5.0);\n  float angle = 2.0 * 3.14159 * ((segment + nextAngle) / segmentCount);\n\n  vec3 v1 = mix(d, vec3(0.0), coneOffset);\n  vec3 v2 = v1 - d;\n\n  vec3 u = getOrthogonalVector(d);\n  vec3 v = normalize(cross(u, d));\n\n  vec3 x = u * cos(angle) * length(d)*0.25;\n  vec3 y = v * sin(angle) * length(d)*0.25;\n  vec3 v3 = v2 + x + y;\n  if (segmentIndex <= 2.0) {\n    vec3 tx = u * sin(angle);\n    vec3 ty = v * -cos(angle);\n    vec3 tangent = tx + ty;\n    normal = normalize(cross(v3 - v1, tangent));\n  }\n\n  if (segmentIndex == 0.0) {\n    return mix(d, vec3(0.0), coneOffset);\n  }\n  return v3;\n}\n\nattribute vec3 vector;\nattribute vec4 color, position;\nattribute vec2 uv;\nuniform float vectorScale;\nuniform float coneScale;\n\nuniform float coneOffset;\n\nuniform mat4 model\n           , view\n           , projection;\nuniform vec3 eyePosition\n           , lightPosition;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data\n           , f_position;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  // Scale the vector magnitude to stay constant with\n  // model & view changes.\n  vec3 normal;\n  vec3 XYZ = getConePosition(mat3(model) * ((vectorScale * coneScale) * vector), position.w, coneOffset, normal);\n  vec4 conePosition = model * vec4(position.xyz, 1.0) + vec4(XYZ, 0.0);\n  normal = normalize(normal * inverse(mat3(model)));\n\n  // vec4 m_position  = model * vec4(conePosition, 1.0);\n  vec4 t_position  = view * conePosition;\n  gl_Position      = projection * t_position;\n  f_color          = color; //vec4(position.w, color.r, 0, 0);\n  f_normal         = normal;\n  f_data           = conePosition.xyz;\n  f_position       = position.xyz;\n  f_eyeDirection   = eyePosition   - conePosition.xyz;\n  f_lightDirection = lightPosition - conePosition.xyz;\n  f_uv             = uv;\n}\n"])
var triFragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution(float x, float roughness) {\n  float NdotH = max(x, 0.0001);\n  float cos2Alpha = NdotH * NdotH;\n  float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n  float roughness2 = roughness * roughness;\n  float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n  return exp(tan2Alpha / roughness2) / denom;\n}\n\nfloat cookTorranceSpecular(\n  vec3 lightDirection,\n  vec3 viewDirection,\n  vec3 surfaceNormal,\n  float roughness,\n  float fresnel) {\n\n  float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n  float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n  //Half angle vector\n  vec3 H = normalize(lightDirection + viewDirection);\n\n  //Geometric term\n  float NdotH = max(dot(surfaceNormal, H), 0.0);\n  float VdotH = max(dot(viewDirection, H), 0.000001);\n  float LdotH = max(dot(lightDirection, H), 0.000001);\n  float G1 = (2.0 * NdotH * VdotN) / VdotH;\n  float G2 = (2.0 * NdotH * LdotN) / LdotH;\n  float G = min(1.0, min(G1, G2));\n  \n  //Distribution term\n  float D = beckmannDistribution(NdotH, roughness);\n\n  //Fresnel term\n  float F = pow(1.0 - VdotN, fresnel);\n\n  //Multiply terms and done\n  return  G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n            , fresnel\n            , kambient\n            , kdiffuse\n            , kspecular\n            , opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data\n           , f_position;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n\n  if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n\n  vec3 N = normalize(f_normal);\n  vec3 L = normalize(f_lightDirection);\n  vec3 V = normalize(f_eyeDirection);\n\n  if(!gl_FrontFacing) {\n    N = -N;\n  }\n\n  float specular = cookTorranceSpecular(L, V, N, roughness, fresnel);\n  float diffuse  = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n  vec4 surfaceColor =  texture2D(texture, f_uv);\n  vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular,  1.0);\n\n  gl_FragColor = litColor * opacity;\n}"])
var pickVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nvec3 getOrthogonalVector(vec3 v) {\n  // Return up-vector for only-z vector.\n  // Return ax + by + cz = 0, a point that lies on the plane that has v as a normal and that isn't (0,0,0).\n  // From the above if-statement we have ||a|| > 0  U  ||b|| > 0.\n  // Assign z = 0, x = -b, y = a:\n  // a*-b + b*a + c*0 = -ba + ba + 0 = 0\n  if (v.x*v.x > v.z*v.z || v.y*v.y > v.z*v.z) {\n    return normalize(vec3(-v.y, v.x, 0.0));\n  } else {\n    return normalize(vec3(0.0, v.z, -v.y));\n  }\n}\n\n// Calculate the cone vertex and normal at the given index.\n//\n// The returned vertex is for a cone with its top at origin and height of 1.0,\n// pointing in the direction of the vector attribute.\n//\n// Each cone is made up of a top vertex, a center base vertex and base perimeter vertices.\n// These vertices are used to make up the triangles of the cone by the following:\n//   segment + 0 top vertex\n//   segment + 1 perimeter vertex a+1\n//   segment + 2 perimeter vertex a\n//   segment + 3 center base vertex\n//   segment + 4 perimeter vertex a\n//   segment + 5 perimeter vertex a+1\n// Where segment is the number of the radial segment * 6 and a is the angle at that radial segment.\n// To go from index to segment, floor(index / 6)\n// To go from segment to angle, 2*pi * (segment/segmentCount)\n// To go from index to segment index, index - (segment*6)\n//\nvec3 getConePosition(vec3 d, float index, float coneOffset, out vec3 normal) {\n\n  const float segmentCount = 8.0;\n\n  index = mod(index, segmentCount * 6.0);\n\n  float segment = floor(index/6.0);\n  float segmentIndex = index - (segment*6.0);\n\n  normal = -normalize(d);\n\n  if (segmentIndex == 3.0) {\n    return mix(vec3(0.0), -d, coneOffset);\n  }\n\n  // angle = 2pi * ((segment + ((segmentIndex == 1.0 || segmentIndex == 5.0) ? 1.0 : 0.0)) / segmentCount)\n  float nextAngle = float(segmentIndex == 1.0 || segmentIndex == 5.0);\n  float angle = 2.0 * 3.14159 * ((segment + nextAngle) / segmentCount);\n\n  vec3 v1 = mix(d, vec3(0.0), coneOffset);\n  vec3 v2 = v1 - d;\n\n  vec3 u = getOrthogonalVector(d);\n  vec3 v = normalize(cross(u, d));\n\n  vec3 x = u * cos(angle) * length(d)*0.25;\n  vec3 y = v * sin(angle) * length(d)*0.25;\n  vec3 v3 = v2 + x + y;\n  if (segmentIndex <= 2.0) {\n    vec3 tx = u * sin(angle);\n    vec3 ty = v * -cos(angle);\n    vec3 tangent = tx + ty;\n    normal = normalize(cross(v3 - v1, tangent));\n  }\n\n  if (segmentIndex == 0.0) {\n    return mix(d, vec3(0.0), coneOffset);\n  }\n  return v3;\n}\n\nattribute vec3 vector;\nattribute vec4 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\n\nuniform float vectorScale;\nuniform float coneScale;\nuniform float coneOffset;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  vec3 normal;\n  vec3 XYZ = getConePosition(mat3(model) * ((vectorScale * coneScale) * vector), position.w, coneOffset, normal);\n  vec4 conePosition = model * vec4(position.xyz, 1.0) + vec4(XYZ, 0.0);\n  gl_Position = projection * view * conePosition;\n  f_id        = id;\n  f_position  = position.xyz;\n}\n"])
var pickFragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3  clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n\n  gl_FragColor = vec4(pickId, f_id.xyz);\n}"])

exports.meshShader = {
  vertex:   triVertSrc,
  fragment: triFragSrc,
  attributes: [
    {name: 'position', type: 'vec4'},
    {name: 'normal', type: 'vec3'},
    {name: 'color', type: 'vec4'},
    {name: 'uv', type: 'vec2'},
    {name: 'vector', type: 'vec3'}
  ]
}
exports.pickShader = {
  vertex:   pickVertSrc,
  fragment: pickFragSrc,
  attributes: [
    {name: 'position', type: 'vec4'},
    {name: 'id', type: 'vec4'},
    {name: 'vector', type: 'vec3'}
  ]
}

},{"glslify":395}],236:[function(_dereq_,module,exports){
module.exports = {
  0: 'NONE',
  1: 'ONE',
  2: 'LINE_LOOP',
  3: 'LINE_STRIP',
  4: 'TRIANGLES',
  5: 'TRIANGLE_STRIP',
  6: 'TRIANGLE_FAN',
  256: 'DEPTH_BUFFER_BIT',
  512: 'NEVER',
  513: 'LESS',
  514: 'EQUAL',
  515: 'LEQUAL',
  516: 'GREATER',
  517: 'NOTEQUAL',
  518: 'GEQUAL',
  519: 'ALWAYS',
  768: 'SRC_COLOR',
  769: 'ONE_MINUS_SRC_COLOR',
  770: 'SRC_ALPHA',
  771: 'ONE_MINUS_SRC_ALPHA',
  772: 'DST_ALPHA',
  773: 'ONE_MINUS_DST_ALPHA',
  774: 'DST_COLOR',
  775: 'ONE_MINUS_DST_COLOR',
  776: 'SRC_ALPHA_SATURATE',
  1024: 'STENCIL_BUFFER_BIT',
  1028: 'FRONT',
  1029: 'BACK',
  1032: 'FRONT_AND_BACK',
  1280: 'INVALID_ENUM',
  1281: 'INVALID_VALUE',
  1282: 'INVALID_OPERATION',
  1285: 'OUT_OF_MEMORY',
  1286: 'INVALID_FRAMEBUFFER_OPERATION',
  2304: 'CW',
  2305: 'CCW',
  2849: 'LINE_WIDTH',
  2884: 'CULL_FACE',
  2885: 'CULL_FACE_MODE',
  2886: 'FRONT_FACE',
  2928: 'DEPTH_RANGE',
  2929: 'DEPTH_TEST',
  2930: 'DEPTH_WRITEMASK',
  2931: 'DEPTH_CLEAR_VALUE',
  2932: 'DEPTH_FUNC',
  2960: 'STENCIL_TEST',
  2961: 'STENCIL_CLEAR_VALUE',
  2962: 'STENCIL_FUNC',
  2963: 'STENCIL_VALUE_MASK',
  2964: 'STENCIL_FAIL',
  2965: 'STENCIL_PASS_DEPTH_FAIL',
  2966: 'STENCIL_PASS_DEPTH_PASS',
  2967: 'STENCIL_REF',
  2968: 'STENCIL_WRITEMASK',
  2978: 'VIEWPORT',
  3024: 'DITHER',
  3042: 'BLEND',
  3088: 'SCISSOR_BOX',
  3089: 'SCISSOR_TEST',
  3106: 'COLOR_CLEAR_VALUE',
  3107: 'COLOR_WRITEMASK',
  3317: 'UNPACK_ALIGNMENT',
  3333: 'PACK_ALIGNMENT',
  3379: 'MAX_TEXTURE_SIZE',
  3386: 'MAX_VIEWPORT_DIMS',
  3408: 'SUBPIXEL_BITS',
  3410: 'RED_BITS',
  3411: 'GREEN_BITS',
  3412: 'BLUE_BITS',
  3413: 'ALPHA_BITS',
  3414: 'DEPTH_BITS',
  3415: 'STENCIL_BITS',
  3553: 'TEXTURE_2D',
  4352: 'DONT_CARE',
  4353: 'FASTEST',
  4354: 'NICEST',
  5120: 'BYTE',
  5121: 'UNSIGNED_BYTE',
  5122: 'SHORT',
  5123: 'UNSIGNED_SHORT',
  5124: 'INT',
  5125: 'UNSIGNED_INT',
  5126: 'FLOAT',
  5386: 'INVERT',
  5890: 'TEXTURE',
  6401: 'STENCIL_INDEX',
  6402: 'DEPTH_COMPONENT',
  6406: 'ALPHA',
  6407: 'RGB',
  6408: 'RGBA',
  6409: 'LUMINANCE',
  6410: 'LUMINANCE_ALPHA',
  7680: 'KEEP',
  7681: 'REPLACE',
  7682: 'INCR',
  7683: 'DECR',
  7936: 'VENDOR',
  7937: 'RENDERER',
  7938: 'VERSION',
  9728: 'NEAREST',
  9729: 'LINEAR',
  9984: 'NEAREST_MIPMAP_NEAREST',
  9985: 'LINEAR_MIPMAP_NEAREST',
  9986: 'NEAREST_MIPMAP_LINEAR',
  9987: 'LINEAR_MIPMAP_LINEAR',
  10240: 'TEXTURE_MAG_FILTER',
  10241: 'TEXTURE_MIN_FILTER',
  10242: 'TEXTURE_WRAP_S',
  10243: 'TEXTURE_WRAP_T',
  10497: 'REPEAT',
  10752: 'POLYGON_OFFSET_UNITS',
  16384: 'COLOR_BUFFER_BIT',
  32769: 'CONSTANT_COLOR',
  32770: 'ONE_MINUS_CONSTANT_COLOR',
  32771: 'CONSTANT_ALPHA',
  32772: 'ONE_MINUS_CONSTANT_ALPHA',
  32773: 'BLEND_COLOR',
  32774: 'FUNC_ADD',
  32777: 'BLEND_EQUATION_RGB',
  32778: 'FUNC_SUBTRACT',
  32779: 'FUNC_REVERSE_SUBTRACT',
  32819: 'UNSIGNED_SHORT_4_4_4_4',
  32820: 'UNSIGNED_SHORT_5_5_5_1',
  32823: 'POLYGON_OFFSET_FILL',
  32824: 'POLYGON_OFFSET_FACTOR',
  32854: 'RGBA4',
  32855: 'RGB5_A1',
  32873: 'TEXTURE_BINDING_2D',
  32926: 'SAMPLE_ALPHA_TO_COVERAGE',
  32928: 'SAMPLE_COVERAGE',
  32936: 'SAMPLE_BUFFERS',
  32937: 'SAMPLES',
  32938: 'SAMPLE_COVERAGE_VALUE',
  32939: 'SAMPLE_COVERAGE_INVERT',
  32968: 'BLEND_DST_RGB',
  32969: 'BLEND_SRC_RGB',
  32970: 'BLEND_DST_ALPHA',
  32971: 'BLEND_SRC_ALPHA',
  33071: 'CLAMP_TO_EDGE',
  33170: 'GENERATE_MIPMAP_HINT',
  33189: 'DEPTH_COMPONENT16',
  33306: 'DEPTH_STENCIL_ATTACHMENT',
  33635: 'UNSIGNED_SHORT_5_6_5',
  33648: 'MIRRORED_REPEAT',
  33901: 'ALIASED_POINT_SIZE_RANGE',
  33902: 'ALIASED_LINE_WIDTH_RANGE',
  33984: 'TEXTURE0',
  33985: 'TEXTURE1',
  33986: 'TEXTURE2',
  33987: 'TEXTURE3',
  33988: 'TEXTURE4',
  33989: 'TEXTURE5',
  33990: 'TEXTURE6',
  33991: 'TEXTURE7',
  33992: 'TEXTURE8',
  33993: 'TEXTURE9',
  33994: 'TEXTURE10',
  33995: 'TEXTURE11',
  33996: 'TEXTURE12',
  33997: 'TEXTURE13',
  33998: 'TEXTURE14',
  33999: 'TEXTURE15',
  34000: 'TEXTURE16',
  34001: 'TEXTURE17',
  34002: 'TEXTURE18',
  34003: 'TEXTURE19',
  34004: 'TEXTURE20',
  34005: 'TEXTURE21',
  34006: 'TEXTURE22',
  34007: 'TEXTURE23',
  34008: 'TEXTURE24',
  34009: 'TEXTURE25',
  34010: 'TEXTURE26',
  34011: 'TEXTURE27',
  34012: 'TEXTURE28',
  34013: 'TEXTURE29',
  34014: 'TEXTURE30',
  34015: 'TEXTURE31',
  34016: 'ACTIVE_TEXTURE',
  34024: 'MAX_RENDERBUFFER_SIZE',
  34041: 'DEPTH_STENCIL',
  34055: 'INCR_WRAP',
  34056: 'DECR_WRAP',
  34067: 'TEXTURE_CUBE_MAP',
  34068: 'TEXTURE_BINDING_CUBE_MAP',
  34069: 'TEXTURE_CUBE_MAP_POSITIVE_X',
  34070: 'TEXTURE_CUBE_MAP_NEGATIVE_X',
  34071: 'TEXTURE_CUBE_MAP_POSITIVE_Y',
  34072: 'TEXTURE_CUBE_MAP_NEGATIVE_Y',
  34073: 'TEXTURE_CUBE_MAP_POSITIVE_Z',
  34074: 'TEXTURE_CUBE_MAP_NEGATIVE_Z',
  34076: 'MAX_CUBE_MAP_TEXTURE_SIZE',
  34338: 'VERTEX_ATTRIB_ARRAY_ENABLED',
  34339: 'VERTEX_ATTRIB_ARRAY_SIZE',
  34340: 'VERTEX_ATTRIB_ARRAY_STRIDE',
  34341: 'VERTEX_ATTRIB_ARRAY_TYPE',
  34342: 'CURRENT_VERTEX_ATTRIB',
  34373: 'VERTEX_ATTRIB_ARRAY_POINTER',
  34466: 'NUM_COMPRESSED_TEXTURE_FORMATS',
  34467: 'COMPRESSED_TEXTURE_FORMATS',
  34660: 'BUFFER_SIZE',
  34661: 'BUFFER_USAGE',
  34816: 'STENCIL_BACK_FUNC',
  34817: 'STENCIL_BACK_FAIL',
  34818: 'STENCIL_BACK_PASS_DEPTH_FAIL',
  34819: 'STENCIL_BACK_PASS_DEPTH_PASS',
  34877: 'BLEND_EQUATION_ALPHA',
  34921: 'MAX_VERTEX_ATTRIBS',
  34922: 'VERTEX_ATTRIB_ARRAY_NORMALIZED',
  34930: 'MAX_TEXTURE_IMAGE_UNITS',
  34962: 'ARRAY_BUFFER',
  34963: 'ELEMENT_ARRAY_BUFFER',
  34964: 'ARRAY_BUFFER_BINDING',
  34965: 'ELEMENT_ARRAY_BUFFER_BINDING',
  34975: 'VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
  35040: 'STREAM_DRAW',
  35044: 'STATIC_DRAW',
  35048: 'DYNAMIC_DRAW',
  35632: 'FRAGMENT_SHADER',
  35633: 'VERTEX_SHADER',
  35660: 'MAX_VERTEX_TEXTURE_IMAGE_UNITS',
  35661: 'MAX_COMBINED_TEXTURE_IMAGE_UNITS',
  35663: 'SHADER_TYPE',
  35664: 'FLOAT_VEC2',
  35665: 'FLOAT_VEC3',
  35666: 'FLOAT_VEC4',
  35667: 'INT_VEC2',
  35668: 'INT_VEC3',
  35669: 'INT_VEC4',
  35670: 'BOOL',
  35671: 'BOOL_VEC2',
  35672: 'BOOL_VEC3',
  35673: 'BOOL_VEC4',
  35674: 'FLOAT_MAT2',
  35675: 'FLOAT_MAT3',
  35676: 'FLOAT_MAT4',
  35678: 'SAMPLER_2D',
  35680: 'SAMPLER_CUBE',
  35712: 'DELETE_STATUS',
  35713: 'COMPILE_STATUS',
  35714: 'LINK_STATUS',
  35715: 'VALIDATE_STATUS',
  35716: 'INFO_LOG_LENGTH',
  35717: 'ATTACHED_SHADERS',
  35718: 'ACTIVE_UNIFORMS',
  35719: 'ACTIVE_UNIFORM_MAX_LENGTH',
  35720: 'SHADER_SOURCE_LENGTH',
  35721: 'ACTIVE_ATTRIBUTES',
  35722: 'ACTIVE_ATTRIBUTE_MAX_LENGTH',
  35724: 'SHADING_LANGUAGE_VERSION',
  35725: 'CURRENT_PROGRAM',
  36003: 'STENCIL_BACK_REF',
  36004: 'STENCIL_BACK_VALUE_MASK',
  36005: 'STENCIL_BACK_WRITEMASK',
  36006: 'FRAMEBUFFER_BINDING',
  36007: 'RENDERBUFFER_BINDING',
  36048: 'FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
  36049: 'FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
  36050: 'FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
  36051: 'FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
  36053: 'FRAMEBUFFER_COMPLETE',
  36054: 'FRAMEBUFFER_INCOMPLETE_ATTACHMENT',
  36055: 'FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT',
  36057: 'FRAMEBUFFER_INCOMPLETE_DIMENSIONS',
  36061: 'FRAMEBUFFER_UNSUPPORTED',
  36064: 'COLOR_ATTACHMENT0',
  36096: 'DEPTH_ATTACHMENT',
  36128: 'STENCIL_ATTACHMENT',
  36160: 'FRAMEBUFFER',
  36161: 'RENDERBUFFER',
  36162: 'RENDERBUFFER_WIDTH',
  36163: 'RENDERBUFFER_HEIGHT',
  36164: 'RENDERBUFFER_INTERNAL_FORMAT',
  36168: 'STENCIL_INDEX8',
  36176: 'RENDERBUFFER_RED_SIZE',
  36177: 'RENDERBUFFER_GREEN_SIZE',
  36178: 'RENDERBUFFER_BLUE_SIZE',
  36179: 'RENDERBUFFER_ALPHA_SIZE',
  36180: 'RENDERBUFFER_DEPTH_SIZE',
  36181: 'RENDERBUFFER_STENCIL_SIZE',
  36194: 'RGB565',
  36336: 'LOW_FLOAT',
  36337: 'MEDIUM_FLOAT',
  36338: 'HIGH_FLOAT',
  36339: 'LOW_INT',
  36340: 'MEDIUM_INT',
  36341: 'HIGH_INT',
  36346: 'SHADER_COMPILER',
  36347: 'MAX_VERTEX_UNIFORM_VECTORS',
  36348: 'MAX_VARYING_VECTORS',
  36349: 'MAX_FRAGMENT_UNIFORM_VECTORS',
  37440: 'UNPACK_FLIP_Y_WEBGL',
  37441: 'UNPACK_PREMULTIPLY_ALPHA_WEBGL',
  37442: 'CONTEXT_LOST_WEBGL',
  37443: 'UNPACK_COLORSPACE_CONVERSION_WEBGL',
  37444: 'BROWSER_DEFAULT_WEBGL'
}

},{}],237:[function(_dereq_,module,exports){
var gl10 = _dereq_('./1.0/numbers')

module.exports = function lookupConstant (number) {
  return gl10[number]
}

},{"./1.0/numbers":236}],238:[function(_dereq_,module,exports){
'use strict'

module.exports = createErrorBars

var createBuffer  = _dereq_('gl-buffer')
var createVAO     = _dereq_('gl-vao')
var createShader  = _dereq_('./shaders/index')

var IDENTITY = [1,0,0,0,
                0,1,0,0,
                0,0,1,0,
                0,0,0,1]

function ErrorBars(gl, buffer, vao, shader) {
  this.gl           = gl
  this.shader       = shader
  this.buffer       = buffer
  this.vao          = vao
  this.pixelRatio   = 1
  this.bounds       = [[ Infinity, Infinity, Infinity], [-Infinity,-Infinity,-Infinity]]
  this.clipBounds   = [[-Infinity,-Infinity,-Infinity], [ Infinity, Infinity, Infinity]]
  this.lineWidth    = [1,1,1]
  this.capSize      = [10,10,10]
  this.lineCount    = [0,0,0]
  this.lineOffset   = [0,0,0]
  this.opacity      = 1
  this.hasAlpha     = false
}

var proto = ErrorBars.prototype

proto.isOpaque = function() {
  return !this.hasAlpha
}

proto.isTransparent = function() {
  return this.hasAlpha
}

proto.drawTransparent = proto.draw = function(cameraParams) {
  var gl = this.gl
  var uniforms        = this.shader.uniforms

  this.shader.bind()
  var view       = uniforms.view       = cameraParams.view       || IDENTITY
  var projection = uniforms.projection = cameraParams.projection || IDENTITY
  uniforms.model      = cameraParams.model      || IDENTITY
  uniforms.clipBounds = this.clipBounds
  uniforms.opacity    = this.opacity


  var cx = view[12]
  var cy = view[13]
  var cz = view[14]
  var cw = view[15]
  var pixelScaleF = this.pixelRatio * (projection[3]*cx + projection[7]*cy + projection[11]*cz + projection[15]*cw) / gl.drawingBufferHeight

  this.vao.bind()
  for(var i=0; i<3; ++i) {
    gl.lineWidth(this.lineWidth[i])
    uniforms.capSize = this.capSize[i] * pixelScaleF
    if (this.lineCount[i]) {
      gl.drawArrays(gl.LINES, this.lineOffset[i], this.lineCount[i])
    }
  }
  this.vao.unbind()
}

function updateBounds(bounds, point) {
  for(var i=0; i<3; ++i) {
    bounds[0][i] = Math.min(bounds[0][i], point[i])
    bounds[1][i] = Math.max(bounds[1][i], point[i])
  }
}

var FACE_TABLE = (function(){
  var table = new Array(3)
  for(var d=0; d<3; ++d) {
    var row = []
    for(var j=1; j<=2; ++j) {
      for(var s=-1; s<=1; s+=2) {
        var u = (j+d) % 3
        var y = [0,0,0]
        y[u] = s
        row.push(y)
      }
    }
    table[d] = row
  }
  return table
})()


function emitFace(verts, x, c, d) {
  var offsets = FACE_TABLE[d]
  for(var i=0; i<offsets.length; ++i) {
    var o = offsets[i]
    verts.push(x[0], x[1], x[2],
               c[0], c[1], c[2], c[3],
               o[0], o[1], o[2])
  }
  return offsets.length
}

proto.update = function(options) {
  options = options || {}

  if('lineWidth' in options) {
    this.lineWidth = options.lineWidth
    if(!Array.isArray(this.lineWidth)) {
      this.lineWidth = [this.lineWidth, this.lineWidth, this.lineWidth]
    }
  }
  if('capSize' in options) {
    this.capSize = options.capSize
    if(!Array.isArray(this.capSize)) {
      this.capSize = [this.capSize, this.capSize, this.capSize]
    }
  }

  this.hasAlpha = false // default to no transparent draw
  if('opacity' in options) {
    this.opacity = +options.opacity
    if(this.opacity < 1) {
      this.hasAlpha = true;
    }
  }

  var color    = options.color || [[0,0,0],[0,0,0],[0,0,0]]
  var position = options.position
  var error    = options.error
  if(!Array.isArray(color[0])) {
    color = [color,color,color]
  }

  if(position && error) {

    var verts       = []
    var n           = position.length
    var vertexCount = 0
    this.bounds     = [[ Infinity, Infinity, Infinity],
                       [-Infinity,-Infinity,-Infinity]]
    this.lineCount  = [0,0,0]

    //Build geometry for lines
    for(var j=0; j<3; ++j) {
      this.lineOffset[j] = vertexCount

i_loop:
      for(var i=0; i<n; ++i) {
        var p = position[i]

        for(var k=0; k<3; ++k) {
          if(isNaN(p[k]) || !isFinite(p[k])) {
            continue i_loop
          }
        }

        var e = error[i]
        var c = color[j]
        if(Array.isArray(c[0])) {
          c = color[i]
        }
        if(c.length === 3) {
          c = [c[0], c[1], c[2], 1]
        } else if(c.length === 4) {
          c = [c[0], c[1], c[2], c[3]]
          if(!this.hasAlpha && c[3] < 1) this.hasAlpha = true
        }

        if(isNaN(e[0][j]) || isNaN(e[1][j])) {
          continue
        }
        if(e[0][j] < 0) {
          var x = p.slice()
          x[j] += e[0][j]
          verts.push(p[0], p[1], p[2],
                     c[0], c[1], c[2], c[3],
                        0,    0,    0,
                     x[0], x[1], x[2],
                     c[0], c[1], c[2], c[3],
                        0,    0,    0)
          updateBounds(this.bounds, x)
          vertexCount += 2 + emitFace(verts, x, c, j)
        }
        if(e[1][j] > 0) {
          var x = p.slice()
          x[j] += e[1][j]
          verts.push(p[0], p[1], p[2],
                     c[0], c[1], c[2], c[3],
                        0,    0,    0,
                     x[0], x[1], x[2],
                     c[0], c[1], c[2], c[3],
                        0,    0,    0)
          updateBounds(this.bounds, x)
          vertexCount += 2 + emitFace(verts, x, c, j)
        }
      }
      this.lineCount[j] = vertexCount - this.lineOffset[j]
    }
    this.buffer.update(verts)
  }
}

proto.dispose = function() {
  this.shader.dispose()
  this.buffer.dispose()
  this.vao.dispose()
}

function createErrorBars(options) {
  var gl = options.gl
  var buffer = createBuffer(gl)
  var vao = createVAO(gl, [
      {
        buffer: buffer,
        type:   gl.FLOAT,
        size:   3,
        offset: 0,
        stride: 40
      },
      {
        buffer: buffer,
        type:   gl.FLOAT,
        size:   4,
        offset: 12,
        stride: 40
      },
      {
        buffer: buffer,
        type:   gl.FLOAT,
        size:   3,
        offset: 28,
        stride: 40
      }
    ])

  var shader = createShader(gl)
  shader.attributes.position.location = 0
  shader.attributes.color.location    = 1
  shader.attributes.offset.location   = 2

  var result = new ErrorBars(gl, buffer, vao, shader)
  result.update(options)
  return result
}

},{"./shaders/index":239,"gl-buffer":231,"gl-vao":313}],239:[function(_dereq_,module,exports){
'use strict'

var glslify = _dereq_('glslify')
var createShader = _dereq_('gl-shader')

var vertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, offset;\nattribute vec4 color;\nuniform mat4 model, view, projection;\nuniform float capSize;\nvarying vec4 fragColor;\nvarying vec3 fragPosition;\n\nvoid main() {\n  vec4 worldPosition  = model * vec4(position, 1.0);\n  worldPosition       = (worldPosition / worldPosition.w) + vec4(capSize * offset, 0.0);\n  gl_Position         = projection * view * worldPosition;\n  fragColor           = color;\n  fragPosition        = position;\n}"])
var fragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform float opacity;\nvarying vec3 fragPosition;\nvarying vec4 fragColor;\n\nvoid main() {\n  if (\n    outOfRange(clipBounds[0], clipBounds[1], fragPosition) ||\n    fragColor.a * opacity == 0.\n  ) discard;\n\n  gl_FragColor = opacity * fragColor;\n}"])

module.exports = function(gl) {
  return createShader(gl, vertSrc, fragSrc, null, [
    {name: 'position', type: 'vec3'},
    {name: 'color', type: 'vec4'},
    {name: 'offset', type: 'vec3'}
  ])
}

},{"gl-shader":290,"glslify":395}],240:[function(_dereq_,module,exports){
'use strict'

var createTexture = _dereq_('gl-texture2d')

module.exports = createFBO

var colorAttachmentArrays = null
var FRAMEBUFFER_UNSUPPORTED
var FRAMEBUFFER_INCOMPLETE_ATTACHMENT
var FRAMEBUFFER_INCOMPLETE_DIMENSIONS
var FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT

function saveFBOState(gl) {
  var fbo = gl.getParameter(gl.FRAMEBUFFER_BINDING)
  var rbo = gl.getParameter(gl.RENDERBUFFER_BINDING)
  var tex = gl.getParameter(gl.TEXTURE_BINDING_2D)
  return [fbo, rbo, tex]
}

function restoreFBOState(gl, data) {
  gl.bindFramebuffer(gl.FRAMEBUFFER, data[0])
  gl.bindRenderbuffer(gl.RENDERBUFFER, data[1])
  gl.bindTexture(gl.TEXTURE_2D, data[2])
}

function lazyInitColorAttachments(gl, ext) {
  var maxColorAttachments = gl.getParameter(ext.MAX_COLOR_ATTACHMENTS_WEBGL)
  colorAttachmentArrays = new Array(maxColorAttachments + 1)
  for(var i=0; i<=maxColorAttachments; ++i) {
    var x = new Array(maxColorAttachments)
    for(var j=0; j<i; ++j) {
      x[j] = gl.COLOR_ATTACHMENT0 + j
    }
    for(var j=i; j<maxColorAttachments; ++j) {
      x[j] = gl.NONE
    }
    colorAttachmentArrays[i] = x
  }
}

//Throw an appropriate error
function throwFBOError(status) {
  switch(status){
    case FRAMEBUFFER_UNSUPPORTED:
      throw new Error('gl-fbo: Framebuffer unsupported')
    case FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
      throw new Error('gl-fbo: Framebuffer incomplete attachment')
    case FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
      throw new Error('gl-fbo: Framebuffer incomplete dimensions')
    case FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
      throw new Error('gl-fbo: Framebuffer incomplete missing attachment')
    default:
      throw new Error('gl-fbo: Framebuffer failed for unspecified reason')
  }
}

//Initialize a texture object
function initTexture(gl, width, height, type, format, attachment) {
  if(!type) {
    return null
  }
  var result = createTexture(gl, width, height, format, type)
  result.magFilter = gl.NEAREST
  result.minFilter = gl.NEAREST
  result.mipSamples = 1
  result.bind()
  gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, result.handle, 0)
  return result
}

//Initialize a render buffer object
function initRenderBuffer(gl, width, height, component, attachment) {
  var result = gl.createRenderbuffer()
  gl.bindRenderbuffer(gl.RENDERBUFFER, result)
  gl.renderbufferStorage(gl.RENDERBUFFER, component, width, height)
  gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, result)
  return result
}

//Rebuild the frame buffer
function rebuildFBO(fbo) {

  //Save FBO state
  var state = saveFBOState(fbo.gl)

  var gl = fbo.gl
  var handle = fbo.handle = gl.createFramebuffer()
  var width = fbo._shape[0]
  var height = fbo._shape[1]
  var numColors = fbo.color.length
  var ext = fbo._ext
  var useStencil = fbo._useStencil
  var useDepth = fbo._useDepth
  var colorType = fbo._colorType

  //Bind the fbo
  gl.bindFramebuffer(gl.FRAMEBUFFER, handle)

  //Allocate color buffers
  for(var i=0; i<numColors; ++i) {
    fbo.color[i] = initTexture(gl, width, height, colorType, gl.RGBA, gl.COLOR_ATTACHMENT0 + i)
  }
  if(numColors === 0) {
    fbo._color_rb = initRenderBuffer(gl, width, height, gl.RGBA4, gl.COLOR_ATTACHMENT0)
    if(ext) {
      ext.drawBuffersWEBGL(colorAttachmentArrays[0])
    }
  } else if(numColors > 1) {
    ext.drawBuffersWEBGL(colorAttachmentArrays[numColors])
  }

  //Allocate depth/stencil buffers
  var WEBGL_depth_texture = gl.getExtension('WEBGL_depth_texture')
  if(WEBGL_depth_texture) {
    if(useStencil) {
      fbo.depth = initTexture(gl, width, height,
                          WEBGL_depth_texture.UNSIGNED_INT_24_8_WEBGL,
                          gl.DEPTH_STENCIL,
                          gl.DEPTH_STENCIL_ATTACHMENT)
    } else if(useDepth) {
      fbo.depth = initTexture(gl, width, height,
                          gl.UNSIGNED_SHORT,
                          gl.DEPTH_COMPONENT,
                          gl.DEPTH_ATTACHMENT)
    }
  } else {
    if(useDepth && useStencil) {
      fbo._depth_rb = initRenderBuffer(gl, width, height, gl.DEPTH_STENCIL, gl.DEPTH_STENCIL_ATTACHMENT)
    } else if(useDepth) {
      fbo._depth_rb = initRenderBuffer(gl, width, height, gl.DEPTH_COMPONENT16, gl.DEPTH_ATTACHMENT)
    } else if(useStencil) {
      fbo._depth_rb = initRenderBuffer(gl, width, height, gl.STENCIL_INDEX, gl.STENCIL_ATTACHMENT)
    }
  }

  //Check frame buffer state
  var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER)
  if(status !== gl.FRAMEBUFFER_COMPLETE) {

    //Release all partially allocated resources
    fbo._destroyed = true

    //Release all resources
    gl.bindFramebuffer(gl.FRAMEBUFFER, null)
    gl.deleteFramebuffer(fbo.handle)
    fbo.handle = null
    if(fbo.depth) {
      fbo.depth.dispose()
      fbo.depth = null
    }
    if(fbo._depth_rb) {
      gl.deleteRenderbuffer(fbo._depth_rb)
      fbo._depth_rb = null
    }
    for(var i=0; i<fbo.color.length; ++i) {
      fbo.color[i].dispose()
      fbo.color[i] = null
    }
    if(fbo._color_rb) {
      gl.deleteRenderbuffer(fbo._color_rb)
      fbo._color_rb = null
    }

    restoreFBOState(gl, state)

    //Throw the frame buffer error
    throwFBOError(status)
  }

  //Everything ok, let's get on with life
  restoreFBOState(gl, state)
}

function Framebuffer(gl, width, height, colorType, numColors, useDepth, useStencil, ext) {

  //Handle and set properties
  this.gl = gl
  this._shape = [width|0, height|0]
  this._destroyed = false
  this._ext = ext

  //Allocate buffers
  this.color = new Array(numColors)
  for(var i=0; i<numColors; ++i) {
    this.color[i] = null
  }
  this._color_rb = null
  this.depth = null
  this._depth_rb = null

  //Save depth and stencil flags
  this._colorType = colorType
  this._useDepth = useDepth
  this._useStencil = useStencil

  //Shape vector for resizing
  var parent = this
  var shapeVector = [width|0, height|0]
  Object.defineProperties(shapeVector, {
    0: {
      get: function() {
        return parent._shape[0]
      },
      set: function(w) {
        return parent.width = w
      }
    },
    1: {
      get: function() {
        return parent._shape[1]
      },
      set: function(h) {
        return parent.height = h
      }
    }
  })
  this._shapeVector = shapeVector

  //Initialize all attachments
  rebuildFBO(this)
}

var proto = Framebuffer.prototype

function reshapeFBO(fbo, w, h) {
  //If fbo is invalid, just skip this
  if(fbo._destroyed) {
    throw new Error('gl-fbo: Can\'t resize destroyed FBO')
  }

  //Don't resize if no change in shape
  if( (fbo._shape[0] === w) &&
      (fbo._shape[1] === h) ) {
    return
  }

  var gl = fbo.gl

  //Check parameter ranges
  var maxFBOSize = gl.getParameter(gl.MAX_RENDERBUFFER_SIZE)
  if( w < 0 || w > maxFBOSize ||
      h < 0 || h > maxFBOSize) {
    throw new Error('gl-fbo: Can\'t resize FBO, invalid dimensions')
  }

  //Update shape
  fbo._shape[0] = w
  fbo._shape[1] = h

  //Save framebuffer state
  var state = saveFBOState(gl)

  //Resize framebuffer attachments
  for(var i=0; i<fbo.color.length; ++i) {
    fbo.color[i].shape = fbo._shape
  }
  if(fbo._color_rb) {
    gl.bindRenderbuffer(gl.RENDERBUFFER, fbo._color_rb)
    gl.renderbufferStorage(gl.RENDERBUFFER, gl.RGBA4, fbo._shape[0], fbo._shape[1])
  }
  if(fbo.depth) {
    fbo.depth.shape = fbo._shape
  }
  if(fbo._depth_rb) {
    gl.bindRenderbuffer(gl.RENDERBUFFER, fbo._depth_rb)
    if(fbo._useDepth && fbo._useStencil) {
      gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, fbo._shape[0], fbo._shape[1])
    } else if(fbo._useDepth) {
      gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, fbo._shape[0], fbo._shape[1])
    } else if(fbo._useStencil) {
      gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX, fbo._shape[0], fbo._shape[1])
    }
  }

  //Check FBO status after resize, if something broke then die in a fire
  gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.handle)
  var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER)
  if(status !== gl.FRAMEBUFFER_COMPLETE) {
    fbo.dispose()
    restoreFBOState(gl, state)
    throwFBOError(status)
  }

  //Restore framebuffer state
  restoreFBOState(gl, state)
}

Object.defineProperties(proto, {
  'shape': {
    get: function() {
      if(this._destroyed) {
        return [0,0]
      }
      return this._shapeVector
    },
    set: function(x) {
      if(!Array.isArray(x)) {
        x = [x|0, x|0]
      }
      if(x.length !== 2) {
        throw new Error('gl-fbo: Shape vector must be length 2')
      }

      var w = x[0]|0
      var h = x[1]|0
      reshapeFBO(this, w, h)

      return [w, h]
    },
    enumerable: false
  },
  'width': {
    get: function() {
      if(this._destroyed) {
        return 0
      }
      return this._shape[0]
    },
    set: function(w) {
      w = w|0
      reshapeFBO(this, w, this._shape[1])
      return w
    },
    enumerable: false
  },
  'height': {
    get: function() {
      if(this._destroyed) {
        return 0
      }
      return this._shape[1]
    },
    set: function(h) {
      h = h|0
      reshapeFBO(this, this._shape[0], h)
      return h
    },
    enumerable: false
  }
})

proto.bind = function() {
  if(this._destroyed) {
    return
  }
  var gl = this.gl
  gl.bindFramebuffer(gl.FRAMEBUFFER, this.handle)
  gl.viewport(0, 0, this._shape[0], this._shape[1])
}

proto.dispose = function() {
  if(this._destroyed) {
    return
  }
  this._destroyed = true
  var gl = this.gl
  gl.deleteFramebuffer(this.handle)
  this.handle = null
  if(this.depth) {
    this.depth.dispose()
    this.depth = null
  }
  if(this._depth_rb) {
    gl.deleteRenderbuffer(this._depth_rb)
    this._depth_rb = null
  }
  for(var i=0; i<this.color.length; ++i) {
    this.color[i].dispose()
    this.color[i] = null
  }
  if(this._color_rb) {
    gl.deleteRenderbuffer(this._color_rb)
    this._color_rb = null
  }
}

function createFBO(gl, width, height, options) {

  //Update frame buffer error code values
  if(!FRAMEBUFFER_UNSUPPORTED) {
    FRAMEBUFFER_UNSUPPORTED = gl.FRAMEBUFFER_UNSUPPORTED
    FRAMEBUFFER_INCOMPLETE_ATTACHMENT = gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT
    FRAMEBUFFER_INCOMPLETE_DIMENSIONS = gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS
    FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT
  }

  //Lazily initialize color attachment arrays
  var WEBGL_draw_buffers = gl.getExtension('WEBGL_draw_buffers')
  if(!colorAttachmentArrays && WEBGL_draw_buffers) {
    lazyInitColorAttachments(gl, WEBGL_draw_buffers)
  }

  //Special case: Can accept an array as argument
  if(Array.isArray(width)) {
    options = height
    height = width[1]|0
    width = width[0]|0
  }

  if(typeof width !== 'number') {
    throw new Error('gl-fbo: Missing shape parameter')
  }

  //Validate width/height properties
  var maxFBOSize = gl.getParameter(gl.MAX_RENDERBUFFER_SIZE)
  if(width < 0 || width > maxFBOSize || height < 0 || height > maxFBOSize) {
    throw new Error('gl-fbo: Parameters are too large for FBO')
  }

  //Handle each option type
  options = options || {}

  //Figure out number of color buffers to use
  var numColors = 1
  if('color' in options) {
    numColors = Math.max(options.color|0, 0)
    if(numColors < 0) {
      throw new Error('gl-fbo: Must specify a nonnegative number of colors')
    }
    if(numColors > 1) {
      //Check if multiple render targets supported
      if(!WEBGL_draw_buffers) {
        throw new Error('gl-fbo: Multiple draw buffer extension not supported')
      } else if(numColors > gl.getParameter(WEBGL_draw_buffers.MAX_COLOR_ATTACHMENTS_WEBGL)) {
        throw new Error('gl-fbo: Context does not support ' + numColors + ' draw buffers')
      }
    }
  }

  //Determine whether to use floating point textures
  var colorType = gl.UNSIGNED_BYTE
  var OES_texture_float = gl.getExtension('OES_texture_float')
  if(options.float && numColors > 0) {
    if(!OES_texture_float) {
      throw new Error('gl-fbo: Context does not support floating point textures')
    }
    colorType = gl.FLOAT
  } else if(options.preferFloat && numColors > 0) {
    if(OES_texture_float) {
      colorType = gl.FLOAT
    }
  }

  //Check if we should use depth buffer
  var useDepth = true
  if('depth' in options) {
    useDepth = !!options.depth
  }

  //Check if we should use a stencil buffer
  var useStencil = false
  if('stencil' in options) {
    useStencil = !!options.stencil
  }

  return new Framebuffer(
    gl,
    width,
    height,
    colorType,
    numColors,
    useDepth,
    useStencil,
    WEBGL_draw_buffers)
}

},{"gl-texture2d":308}],241:[function(_dereq_,module,exports){

var sprintf = _dereq_('sprintf-js').sprintf;
var glConstants = _dereq_('gl-constants/lookup');
var shaderName = _dereq_('glsl-shader-name');
var addLineNumbers = _dereq_('add-line-numbers');

module.exports = formatCompilerError;

function formatCompilerError(errLog, src, type) {
    "use strict";

    var name = shaderName(src) || 'of unknown name (see npm glsl-shader-name)';

    var typeName = 'unknown type';
    if (type !== undefined) {
        typeName = type === glConstants.FRAGMENT_SHADER ? 'fragment' : 'vertex'
    }

    var longForm = sprintf('Error compiling %s shader %s:\n', typeName, name);
    var shortForm = sprintf("%s%s", longForm, errLog);

    var errorStrings = errLog.split('\n');
    var errors = {};

    for (var i = 0; i < errorStrings.length; i++) {
        var errorString = errorStrings[i];
        if (errorString === '' || errorString === "\0") continue;
        var lineNo = parseInt(errorString.split(':')[2]);
        if (isNaN(lineNo)) {
            throw new Error(sprintf('Could not parse error: %s', errorString));
        }
        errors[lineNo] = errorString;
    }

    var lines = addLineNumbers(src).split('\n');

    for (var i = 0; i < lines.length; i++) {
        if (!errors[i+3] && !errors[i+2] && !errors[i+1]) continue;
        var line = lines[i];
        longForm += line + '\n';
        if (errors[i+1]) {
            var e = errors[i+1];
            e = e.substr(e.split(':', 3).join(':').length + 1).trim();
            longForm += sprintf('^^^ %s\n\n', e);
        }
    }

    return {
        long: longForm.trim(),
        short: shortForm.trim()
    };
}


},{"add-line-numbers":50,"gl-constants/lookup":237,"glsl-shader-name":387,"sprintf-js":506}],242:[function(_dereq_,module,exports){
'use strict'

module.exports = createHeatmap2D

var bsearch = _dereq_('binary-search-bounds')
var iota = _dereq_('iota-array')
var pool = _dereq_('typedarray-pool')
var createShader = _dereq_('gl-shader')
var createBuffer = _dereq_('gl-buffer')

var shaders = _dereq_('./lib/shaders')

function GLHeatmap2D (
  plot,
  shader,
  pickShader,
  positionBuffer,
  weightBuffer,
  colorBuffer,
  idBuffer) {
  this.plot = plot
  this.shader = shader
  this.pickShader = pickShader
  this.positionBuffer = positionBuffer
  this.weightBuffer = weightBuffer
  this.colorBuffer = colorBuffer
  this.idBuffer = idBuffer
  this.xData = []
  this.yData = []
  this.shape = [0, 0]
  this.bounds = [Infinity, Infinity, -Infinity, -Infinity]
  this.pickOffset = 0
}

var proto = GLHeatmap2D.prototype

var WEIGHTS = [
  0, 0,
  1, 0,
  0, 1,
  1, 0,
  1, 1,
  0, 1
]

proto.draw = (function () {
  var MATRIX = [
    1, 0, 0,
    0, 1, 0,
    0, 0, 1
  ]

  return function () {
    var plot = this.plot
    var shader = this.shader
    var bounds = this.bounds
    var numVertices = this.numVertices

    if (numVertices <= 0) {
      return
    }

    var gl = plot.gl
    var dataBox = plot.dataBox

    var boundX = bounds[2] - bounds[0]
    var boundY = bounds[3] - bounds[1]
    var dataX = dataBox[2] - dataBox[0]
    var dataY = dataBox[3] - dataBox[1]

    MATRIX[0] = 2.0 * boundX / dataX
    MATRIX[4] = 2.0 * boundY / dataY
    MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0
    MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0

    shader.bind()

    var uniforms = shader.uniforms
    uniforms.viewTransform = MATRIX

    uniforms.shape = this.shape

    var attributes = shader.attributes
    this.positionBuffer.bind()
    attributes.position.pointer()

    this.weightBuffer.bind()
    attributes.weight.pointer(gl.UNSIGNED_BYTE, false)

    this.colorBuffer.bind()
    attributes.color.pointer(gl.UNSIGNED_BYTE, true)

    gl.drawArrays(gl.TRIANGLES, 0, numVertices)
  }
})()

proto.drawPick = (function () {
  var MATRIX = [
    1, 0, 0,
    0, 1, 0,
    0, 0, 1
  ]

  var PICK_VECTOR = [0, 0, 0, 0]

  return function (pickOffset) {
    var plot = this.plot
    var shader = this.pickShader
    var bounds = this.bounds
    var numVertices = this.numVertices

    if (numVertices <= 0) {
      return
    }

    var gl = plot.gl
    var dataBox = plot.dataBox

    var boundX = bounds[2] - bounds[0]
    var boundY = bounds[3] - bounds[1]
    var dataX = dataBox[2] - dataBox[0]
    var dataY = dataBox[3] - dataBox[1]

    MATRIX[0] = 2.0 * boundX / dataX
    MATRIX[4] = 2.0 * boundY / dataY
    MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0
    MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0

    for (var i = 0; i < 4; ++i) {
      PICK_VECTOR[i] = (pickOffset >> (i * 8)) & 0xff
    }

    this.pickOffset = pickOffset

    shader.bind()

    var uniforms = shader.uniforms
    uniforms.viewTransform = MATRIX
    uniforms.pickOffset = PICK_VECTOR
    uniforms.shape = this.shape

    var attributes = shader.attributes
    this.positionBuffer.bind()
    attributes.position.pointer()

    this.weightBuffer.bind()
    attributes.weight.pointer(gl.UNSIGNED_BYTE, false)

    this.idBuffer.bind()
    attributes.pickId.pointer(gl.UNSIGNED_BYTE, false)

    gl.drawArrays(gl.TRIANGLES, 0, numVertices)

    return pickOffset + this.shape[0] * this.shape[1]
  }
})()

proto.pick = function (x, y, value) {
  var pickOffset = this.pickOffset
  var pointCount = this.shape[0] * this.shape[1]
  if (value < pickOffset || value >= pickOffset + pointCount) {
    return null
  }
  var pointId = value - pickOffset
  var xData = this.xData
  var yData = this.yData
  return {
    object: this,
    pointId: pointId,
    dataCoord: [
      xData[pointId % this.shape[0]],
      yData[(pointId / this.shape[0]) | 0]]
  }
}

proto.update = function (options) {
  options = options || {}

  var shape = options.shape || [0, 0]

  var x = options.x || iota(shape[0])
  var y = options.y || iota(shape[1])
  var z = options.z || new Float32Array(shape[0] * shape[1])

  this.xData = x
  this.yData = y

  var colorLevels = options.colorLevels || [0]
  var colorValues = options.colorValues || [0, 0, 0, 1]
  var colorCount = colorLevels.length

  var bounds = this.bounds
  var lox = bounds[0] = x[0]
  var loy = bounds[1] = y[0]
  var hix = bounds[2] = x[x.length - 1]
  var hiy = bounds[3] = y[y.length - 1]

  var xs = 1.0 / (hix - lox)
  var ys = 1.0 / (hiy - loy)

  var numX = shape[0]
  var numY = shape[1]

  this.shape = [numX, numY]

  var numVerts = (numX - 1) * (numY - 1) * (WEIGHTS.length >>> 1)

  this.numVertices = numVerts

  var colors = pool.mallocUint8(numVerts * 4)
  var positions = pool.mallocFloat32(numVerts * 2)
  var weights   = pool.mallocUint8 (numVerts * 2)
  var ids = pool.mallocUint32(numVerts)

  var ptr = 0

  for (var j = 0; j < numY - 1; ++j) {
    var yc0 = ys * (y[j] - loy)
    var yc1 = ys * (y[j + 1] - loy)
    for (var i = 0; i < numX - 1; ++i) {
      var xc0 = xs * (x[i] - lox)
      var xc1 = xs * (x[i + 1] - lox)

      for (var dd = 0; dd < WEIGHTS.length; dd += 2) {
        var dx = WEIGHTS[dd]
        var dy = WEIGHTS[dd + 1]
        var offset = (j + dy) * numX + (i + dx)
        var zc = z[offset]
        var colorIdx = bsearch.le(colorLevels, zc)
        var r, g, b, a
        if (colorIdx < 0) {
          r = colorValues[0]
          g = colorValues[1]
          b = colorValues[2]
          a = colorValues[3]
        } else if (colorIdx === colorCount - 1) {
          r = colorValues[4 * colorCount - 4]
          g = colorValues[4 * colorCount - 3]
          b = colorValues[4 * colorCount - 2]
          a = colorValues[4 * colorCount - 1]
        } else {
          var t = (zc - colorLevels[colorIdx]) /
            (colorLevels[colorIdx + 1] - colorLevels[colorIdx])
          var ti = 1.0 - t
          var i0 = 4 * colorIdx
          var i1 = 4 * (colorIdx + 1)
          r = ti * colorValues[i0] + t * colorValues[i1]
          g = ti * colorValues[i0 + 1] + t * colorValues[i1 + 1]
          b = ti * colorValues[i0 + 2] + t * colorValues[i1 + 2]
          a = ti * colorValues[i0 + 3] + t * colorValues[i1 + 3]
        }

        colors[4 * ptr] = 255 * r
        colors[4 * ptr + 1] = 255 * g
        colors[4 * ptr + 2] = 255 * b
        colors[4 * ptr + 3] = 255 * a

        positions[2*ptr] = xc0*.5 + xc1*.5;
        positions[2*ptr+1] = yc0*.5 + yc1*.5;

        weights[2*ptr] = dx;
        weights[2*ptr+1] = dy;

        ids[ptr] = j * numX + i

        ptr += 1
      }
    }
  }

  this.positionBuffer.update(positions)
  this.weightBuffer.update(weights)
  this.colorBuffer.update(colors)
  this.idBuffer.update(ids)

  pool.free(positions)
  pool.free(colors)
  pool.free(weights)
  pool.free(ids)
}

proto.dispose = function () {
  this.shader.dispose()
  this.pickShader.dispose()
  this.positionBuffer.dispose()
  this.weightBuffer.dispose()
  this.colorBuffer.dispose()
  this.idBuffer.dispose()
  this.plot.removeObject(this)
}

function createHeatmap2D (plot, options) {
  var gl = plot.gl

  var shader = createShader(gl, shaders.vertex, shaders.fragment)
  var pickShader = createShader(gl, shaders.pickVertex, shaders.pickFragment)

  var positionBuffer = createBuffer(gl)
  var weightBuffer   = createBuffer(gl)
  var colorBuffer = createBuffer(gl)
  var idBuffer = createBuffer(gl)

  var heatmap = new GLHeatmap2D(
    plot,
    shader,
    pickShader,
    positionBuffer,
    weightBuffer,
    colorBuffer,
    idBuffer)

  heatmap.update(options)
  plot.addObject(heatmap)

  return heatmap
}

},{"./lib/shaders":243,"binary-search-bounds":244,"gl-buffer":231,"gl-shader":290,"iota-array":402,"typedarray-pool":523}],243:[function(_dereq_,module,exports){
'use strict'

var glslify = _dereq_('glslify')

module.exports = {
  fragment:     glslify(["precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n  gl_FragColor = vec4(fragColor.rgb * fragColor.a, fragColor.a);\n}\n"]),
  vertex:       glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 color;\nattribute vec2 weight;\n\nuniform vec2 shape;\nuniform mat3 viewTransform;\n\nvarying vec4 fragColor;\n\nvoid main() {\n  vec3 vPosition = viewTransform * vec3( position + (weight-.5)/(shape-1.) , 1.0);\n  fragColor = color;\n  gl_Position = vec4(vPosition.xy, 0, vPosition.z);\n}\n"]),
  pickFragment: glslify(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragId;\nvarying vec2 vWeight;\n\nuniform vec2 shape;\nuniform vec4 pickOffset;\n\nvoid main() {\n  vec2 d = step(.5, vWeight);\n  vec4 id = fragId + pickOffset;\n  id.x += d.x + d.y*shape.x;\n\n  id.y += floor(id.x / 256.0);\n  id.x -= floor(id.x / 256.0) * 256.0;\n\n  id.z += floor(id.y / 256.0);\n  id.y -= floor(id.y / 256.0) * 256.0;\n\n  id.w += floor(id.z / 256.0);\n  id.z -= floor(id.z / 256.0) * 256.0;\n\n  gl_FragColor = id/255.;\n}\n"]),
  pickVertex:   glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 pickId;\nattribute vec2 weight;\n\nuniform vec2 shape;\nuniform mat3 viewTransform;\n\nvarying vec4 fragId;\nvarying vec2 vWeight;\n\nvoid main() {\n  vWeight = weight;\n\n  fragId = pickId;\n\n  vec3 vPosition = viewTransform * vec3( position + (weight-.5)/(shape-1.) , 1.0);\n  gl_Position = vec4(vPosition.xy, 0, vPosition.z);\n}\n"])
}

},{"glslify":395}],244:[function(_dereq_,module,exports){
arguments[4][100][0].apply(exports,arguments)
},{"dup":100}],245:[function(_dereq_,module,exports){
var glslify       = _dereq_('glslify')
var createShader  = _dereq_('gl-shader')

var vertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, nextPosition;\nattribute float arcLength, lineWidth;\nattribute vec4 color;\n\nuniform vec2 screenShape;\nuniform float pixelRatio;\nuniform mat4 model, view, projection;\n\nvarying vec4 fragColor;\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\n\nvec4 project(vec3 p) {\n  return projection * view * model * vec4(p, 1.0);\n}\n\nvoid main() {\n  vec4 startPoint = project(position);\n  vec4 endPoint   = project(nextPosition);\n\n  vec2 A = startPoint.xy / startPoint.w;\n  vec2 B =   endPoint.xy /   endPoint.w;\n\n  float clipAngle = atan(\n    (B.y - A.y) * screenShape.y,\n    (B.x - A.x) * screenShape.x\n  );\n\n  vec2 offset = 0.5 * pixelRatio * lineWidth * vec2(\n    sin(clipAngle),\n    -cos(clipAngle)\n  ) / screenShape;\n\n  gl_Position = vec4(startPoint.xy + startPoint.w * offset, startPoint.zw);\n\n  worldPosition = position;\n  pixelArcLength = arcLength;\n  fragColor = color;\n}\n"])
var forwardFrag = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3      clipBounds[2];\nuniform sampler2D dashTexture;\nuniform float     dashScale;\nuniform float     opacity;\n\nvarying vec3    worldPosition;\nvarying float   pixelArcLength;\nvarying vec4    fragColor;\n\nvoid main() {\n  if (\n    outOfRange(clipBounds[0], clipBounds[1], worldPosition) ||\n    fragColor.a * opacity == 0.\n  ) discard;\n\n  float dashWeight = texture2D(dashTexture, vec2(dashScale * pixelArcLength, 0)).r;\n  if(dashWeight < 0.5) {\n    discard;\n  }\n  gl_FragColor = fragColor * opacity;\n}\n"])
var pickFrag = glslify(["precision mediump float;\n#define GLSLIFY 1\n\n#define FLOAT_MAX  1.70141184e38\n#define FLOAT_MIN  1.17549435e-38\n\nlowp vec4 encode_float_1540259130(highp float v) {\n  highp float av = abs(v);\n\n  //Handle special cases\n  if(av < FLOAT_MIN) {\n    return vec4(0.0, 0.0, 0.0, 0.0);\n  } else if(v > FLOAT_MAX) {\n    return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n  } else if(v < -FLOAT_MAX) {\n    return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n  }\n\n  highp vec4 c = vec4(0,0,0,0);\n\n  //Compute exponent and mantissa\n  highp float e = floor(log2(av));\n  highp float m = av * pow(2.0, -e) - 1.0;\n  \n  //Unpack mantissa\n  c[1] = floor(128.0 * m);\n  m -= c[1] / 128.0;\n  c[2] = floor(32768.0 * m);\n  m -= c[2] / 32768.0;\n  c[3] = floor(8388608.0 * m);\n  \n  //Unpack exponent\n  highp float ebias = e + 127.0;\n  c[0] = floor(ebias / 2.0);\n  ebias -= c[0] * 2.0;\n  c[1] += floor(ebias) * 128.0; \n\n  //Unpack sign bit\n  c[0] += 128.0 * step(0.0, -v);\n\n  //Scale back to range\n  return c / 255.0;\n}\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], worldPosition)) discard;\n\n  gl_FragColor = vec4(pickId/255.0, encode_float_1540259130(pixelArcLength).xyz);\n}"])

var ATTRIBUTES = [
  {name: 'position', type: 'vec3'},
  {name: 'nextPosition', type: 'vec3'},
  {name: 'arcLength', type: 'float'},
  {name: 'lineWidth', type: 'float'},
  {name: 'color', type: 'vec4'}
]

exports.createShader = function(gl) {
  return createShader(gl, vertSrc, forwardFrag, null, ATTRIBUTES)
}

exports.createPickShader = function(gl) {
  return createShader(gl, vertSrc, pickFrag, null, ATTRIBUTES)
}

},{"gl-shader":290,"glslify":395}],246:[function(_dereq_,module,exports){
'use strict'

module.exports = createLinePlot

var createBuffer = _dereq_('gl-buffer')
var createVAO = _dereq_('gl-vao')
var createTexture = _dereq_('gl-texture2d')
var unpackFloat = _dereq_('glsl-read-float')
var bsearch = _dereq_('binary-search-bounds')
var ndarray = _dereq_('ndarray')
var shaders = _dereq_('./lib/shaders')

var createShader = shaders.createShader
var createPickShader = shaders.createPickShader

var identity = [1, 0, 0, 0,
  0, 1, 0, 0,
  0, 0, 1, 0,
  0, 0, 0, 1]

function distance (a, b) {
  var s = 0.0
  for (var i = 0; i < 3; ++i) {
    var d = a[i] - b[i]
    s += d * d
  }
  return Math.sqrt(s)
}

function filterClipBounds (bounds) {
  var result = [[-1e6, -1e6, -1e6], [1e6, 1e6, 1e6]]
  for (var i = 0; i < 3; ++i) {
    result[0][i] = Math.max(bounds[0][i], result[0][i])
    result[1][i] = Math.min(bounds[1][i], result[1][i])
  }
  return result
}

function PickResult (tau, position, index, dataCoordinate) {
  this.arcLength = tau
  this.position = position
  this.index = index
  this.dataCoordinate = dataCoordinate
}

function LinePlot (gl, shader, pickShader, buffer, vao, texture) {
  this.gl = gl
  this.shader = shader
  this.pickShader = pickShader
  this.buffer = buffer
  this.vao = vao
  this.clipBounds = [
    [ -Infinity, -Infinity, -Infinity ],
    [ Infinity, Infinity, Infinity ]]
  this.points = []
  this.arcLength = []
  this.vertexCount = 0
  this.bounds = [[0, 0, 0], [0, 0, 0]]
  this.pickId = 0
  this.lineWidth = 1
  this.texture = texture
  this.dashScale = 1
  this.opacity = 1
  this.hasAlpha = false
  this.dirty = true
  this.pixelRatio = 1
}

var proto = LinePlot.prototype

proto.isTransparent = function () {
  return this.hasAlpha
}

proto.isOpaque = function () {
  return !this.hasAlpha
}

proto.pickSlots = 1

proto.setPickBase = function (id) {
  this.pickId = id
}

proto.drawTransparent = proto.draw = function (camera) {
  if (!this.vertexCount) return
  var gl = this.gl
  var shader = this.shader
  var vao = this.vao
  shader.bind()
  shader.uniforms = {
    model: camera.model || identity,
    view: camera.view || identity,
    projection: camera.projection || identity,
    clipBounds: filterClipBounds(this.clipBounds),
    dashTexture: this.texture.bind(),
    dashScale: this.dashScale / this.arcLength[this.arcLength.length - 1],
    opacity: this.opacity,
    screenShape: [gl.drawingBufferWidth, gl.drawingBufferHeight],
    pixelRatio: this.pixelRatio
  }
  vao.bind()
  vao.draw(gl.TRIANGLE_STRIP, this.vertexCount)
  vao.unbind()
}

proto.drawPick = function (camera) {
  if (!this.vertexCount) return
  var gl = this.gl
  var shader = this.pickShader
  var vao = this.vao
  shader.bind()
  shader.uniforms = {
    model: camera.model || identity,
    view: camera.view || identity,
    projection: camera.projection || identity,
    pickId: this.pickId,
    clipBounds: filterClipBounds(this.clipBounds),
    screenShape: [gl.drawingBufferWidth, gl.drawingBufferHeight],
    pixelRatio: this.pixelRatio
  }
  vao.bind()
  vao.draw(gl.TRIANGLE_STRIP, this.vertexCount)
  vao.unbind()
}

proto.update = function (options) {
  var i, j

  this.dirty = true

  var connectGaps = !!options.connectGaps

  if ('dashScale' in options) {
    this.dashScale = options.dashScale
  }

  this.hasAlpha = false // default to no transparent draw
  if ('opacity' in options) {
    this.opacity = +options.opacity
    if(this.opacity < 1) {
      this.hasAlpha = true;
    }
  }

  // Recalculate buffer data
  var buffer = []
  var arcLengthArray = []
  var pointArray = []
  var arcLength = 0.0
  var vertexCount = 0
  var bounds = [
    [ Infinity, Infinity, Infinity ],
    [ -Infinity, -Infinity, -Infinity ]]

  var positions = options.position || options.positions
  if (positions) {

    // Default color
    var colors = options.color || options.colors || [0, 0, 0, 1]

    var lineWidth = options.lineWidth || 1

    var hadGap = false

    fill_loop:
    for (i = 1; i < positions.length; ++i) {
      var a = positions[i - 1]
      var b = positions[i]

      arcLengthArray.push(arcLength)
      pointArray.push(a.slice())

      for (j = 0; j < 3; ++j) {
        if (isNaN(a[j]) || isNaN(b[j]) ||
          !isFinite(a[j]) || !isFinite(b[j])) {

          if (!connectGaps && buffer.length > 0) {
            for (var k = 0; k < 24; ++k) {
              buffer.push(buffer[buffer.length - 12])
            }
            vertexCount += 2
            hadGap = true
          }

          continue fill_loop
        }
        bounds[0][j] = Math.min(bounds[0][j], a[j], b[j])
        bounds[1][j] = Math.max(bounds[1][j], a[j], b[j])
      }

      var acolor, bcolor
      if (Array.isArray(colors[0])) {
        acolor = (colors.length > i - 1) ? colors[i - 1] :             // using index value
                 (colors.length > 0)     ? colors[colors.length - 1] : // using last item
                                           [0, 0, 0, 1];               // using black

        bcolor = (colors.length > i) ? colors[i] :                 // using index value
                 (colors.length > 0) ? colors[colors.length - 1] : // using last item
                                       [0, 0, 0, 1];               // using black
      } else {
        acolor = bcolor = colors
      }

      if (acolor.length === 3) {
        acolor = [acolor[0], acolor[1], acolor[2], 1]
      }
      if (bcolor.length === 3) {
        bcolor = [bcolor[0], bcolor[1], bcolor[2], 1]
      }

      if(!this.hasAlpha && acolor[3] < 1) this.hasAlpha = true

      var w0
      if (Array.isArray(lineWidth)) {
        w0 = (lineWidth.length > i - 1) ? lineWidth[i - 1] :                // using index value
             (lineWidth.length > 0)     ? lineWidth[lineWidth.length - 1] : // using last item
                                          [0, 0, 0, 1];                     // using black
      } else {
        w0 = lineWidth
      }

      var t0 = arcLength
      arcLength += distance(a, b)

      if (hadGap) {
        for (j = 0; j < 2; ++j) {
          buffer.push(
            a[0], a[1], a[2], b[0], b[1], b[2], t0, w0, acolor[0], acolor[1], acolor[2], acolor[3])
        }
        vertexCount += 2
        hadGap = false
      }

      buffer.push(
        a[0], a[1], a[2], b[0], b[1], b[2], t0, w0, acolor[0], acolor[1], acolor[2], acolor[3],
        a[0], a[1], a[2], b[0], b[1], b[2], t0, -w0, acolor[0], acolor[1], acolor[2], acolor[3],
        b[0], b[1], b[2], a[0], a[1], a[2], arcLength, -w0, bcolor[0], bcolor[1], bcolor[2], bcolor[3],
        b[0], b[1], b[2], a[0], a[1], a[2], arcLength, w0, bcolor[0], bcolor[1], bcolor[2], bcolor[3])

      vertexCount += 4
    }
  }
  this.buffer.update(buffer)

  arcLengthArray.push(arcLength)
  pointArray.push(positions[positions.length - 1].slice())

  this.bounds = bounds

  this.vertexCount = vertexCount

  this.points = pointArray
  this.arcLength = arcLengthArray

  if ('dashes' in options) {
    var dashArray = options.dashes

    // Calculate prefix sum
    var prefixSum = dashArray.slice()
    prefixSum.unshift(0)
    for (i = 1; i < prefixSum.length; ++i) {
      prefixSum[i] = prefixSum[i - 1] + prefixSum[i]
    }

    var dashTexture = ndarray(new Array(256 * 4), [256, 1, 4])
    for (i = 0; i < 256; ++i) {
      for (j = 0; j < 4; ++j) {
        dashTexture.set(i, 0, j, 0)
      }
      if (bsearch.le(prefixSum, prefixSum[prefixSum.length - 1] * i / 255.0) & 1) {
        dashTexture.set(i, 0, 0, 0)
      } else {
        dashTexture.set(i, 0, 0, 255)
      }
    }

    this.texture.setPixels(dashTexture)
  }
}

proto.dispose = function () {
  this.shader.dispose()
  this.vao.dispose()
  this.buffer.dispose()
}

proto.pick = function (selection) {
  if (!selection) {
    return null
  }
  if (selection.id !== this.pickId) {
    return null
  }
  var tau = unpackFloat(
    selection.value[0],
    selection.value[1],
    selection.value[2],
    0)
  var index = bsearch.le(this.arcLength, tau)
  if (index < 0) {
    return null
  }
  if (index === this.arcLength.length - 1) {
    return new PickResult(
      this.arcLength[this.arcLength.length - 1],
      this.points[this.points.length - 1].slice(),
      index)
  }
  var a = this.points[index]
  var b = this.points[Math.min(index + 1, this.points.length - 1)]
  var t = (tau - this.arcLength[index]) / (this.arcLength[index + 1] - this.arcLength[index])
  var ti = 1.0 - t
  var x = [0, 0, 0]
  for (var i = 0; i < 3; ++i) {
    x[i] = ti * a[i] + t * b[i]
  }
  var dataIndex = Math.min((t < 0.5) ? index : (index + 1), this.points.length - 1)
  return new PickResult(
    tau,
    x,
    dataIndex,
    this.points[dataIndex])
}

function createLinePlot (options) {
  var gl = options.gl || (options.scene && options.scene.gl)

  var shader = createShader(gl)
  shader.attributes.position.location = 0
  shader.attributes.nextPosition.location = 1
  shader.attributes.arcLength.location = 2
  shader.attributes.lineWidth.location = 3
  shader.attributes.color.location = 4

  var pickShader = createPickShader(gl)
  pickShader.attributes.position.location = 0
  pickShader.attributes.nextPosition.location = 1
  pickShader.attributes.arcLength.location = 2
  pickShader.attributes.lineWidth.location = 3
  pickShader.attributes.color.location = 4

  var buffer = createBuffer(gl)
  var vao = createVAO(gl, [
    {
      'buffer': buffer,
      'size': 3,
      'offset': 0,
      'stride': 48
    },
    {
      'buffer': buffer,
      'size': 3,
      'offset': 12,
      'stride': 48
    },
    {
      'buffer': buffer,
      'size': 1,
      'offset': 24,
      'stride': 48
    },
    {
      'buffer': buffer,
      'size': 1,
      'offset': 28,
      'stride': 48
    },
    {
      'buffer': buffer,
      'size': 4,
      'offset': 32,
      'stride': 48
    }
  ])

  // Create texture for dash pattern
  var defaultTexture = ndarray(new Array(256 * 4), [256, 1, 4])
  for (var i = 0; i < 256 * 4; ++i) {
    defaultTexture.data[i] = 255
  }
  var texture = createTexture(gl, defaultTexture)
  texture.wrap = gl.REPEAT

  var linePlot = new LinePlot(gl, shader, pickShader, buffer, vao, texture)
  linePlot.update(options)
  return linePlot
}

},{"./lib/shaders":245,"binary-search-bounds":247,"gl-buffer":231,"gl-texture2d":308,"gl-vao":313,"glsl-read-float":386,"ndarray":436}],247:[function(_dereq_,module,exports){
arguments[4][100][0].apply(exports,arguments)
},{"dup":100}],248:[function(_dereq_,module,exports){
module.exports = invert

/**
 * Inverts a mat2
 *
 * @alias mat2.invert
 * @param {mat2} out the receiving matrix
 * @param {mat2} a the source matrix
 * @returns {mat2} out
 */
function invert(out, a) {
  var a0 = a[0]
  var a1 = a[1]
  var a2 = a[2]
  var a3 = a[3]
  var det = a0 * a3 - a2 * a1

  if (!det) return null
  det = 1.0 / det

  out[0] =  a3 * det
  out[1] = -a1 * det
  out[2] = -a2 * det
  out[3] =  a0 * det

  return out
}

},{}],249:[function(_dereq_,module,exports){
module.exports = invert

/**
 * Inverts a mat3
 *
 * @alias mat3.invert
 * @param {mat3} out the receiving matrix
 * @param {mat3} a the source matrix
 * @returns {mat3} out
 */
function invert(out, a) {
  var a00 = a[0], a01 = a[1], a02 = a[2]
  var a10 = a[3], a11 = a[4], a12 = a[5]
  var a20 = a[6], a21 = a[7], a22 = a[8]

  var b01 = a22 * a11 - a12 * a21
  var b11 = -a22 * a10 + a12 * a20
  var b21 = a21 * a10 - a11 * a20

  // Calculate the determinant
  var det = a00 * b01 + a01 * b11 + a02 * b21

  if (!det) return null
  det = 1.0 / det

  out[0] = b01 * det
  out[1] = (-a22 * a01 + a02 * a21) * det
  out[2] = (a12 * a01 - a02 * a11) * det
  out[3] = b11 * det
  out[4] = (a22 * a00 - a02 * a20) * det
  out[5] = (-a12 * a00 + a02 * a10) * det
  out[6] = b21 * det
  out[7] = (-a21 * a00 + a01 * a20) * det
  out[8] = (a11 * a00 - a01 * a10) * det

  return out
}

},{}],250:[function(_dereq_,module,exports){
module.exports = clone;

/**
 * Creates a new mat4 initialized with values from an existing matrix
 *
 * @param {mat4} a matrix to clone
 * @returns {mat4} a new 4x4 matrix
 */
function clone(a) {
    var out = new Float32Array(16);
    out[0] = a[0];
    out[1] = a[1];
    out[2] = a[2];
    out[3] = a[3];
    out[4] = a[4];
    out[5] = a[5];
    out[6] = a[6];
    out[7] = a[7];
    out[8] = a[8];
    out[9] = a[9];
    out[10] = a[10];
    out[11] = a[11];
    out[12] = a[12];
    out[13] = a[13];
    out[14] = a[14];
    out[15] = a[15];
    return out;
};
},{}],251:[function(_dereq_,module,exports){
module.exports = create;

/**
 * Creates a new identity mat4
 *
 * @returns {mat4} a new 4x4 matrix
 */
function create() {
    var out = new Float32Array(16);
    out[0] = 1;
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = 0;
    out[5] = 1;
    out[6] = 0;
    out[7] = 0;
    out[8] = 0;
    out[9] = 0;
    out[10] = 1;
    out[11] = 0;
    out[12] = 0;
    out[13] = 0;
    out[14] = 0;
    out[15] = 1;
    return out;
};
},{}],252:[function(_dereq_,module,exports){
module.exports = determinant;

/**
 * Calculates the determinant of a mat4
 *
 * @param {mat4} a the source matrix
 * @returns {Number} determinant of a
 */
function determinant(a) {
    var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
        a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
        a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
        a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15],

        b00 = a00 * a11 - a01 * a10,
        b01 = a00 * a12 - a02 * a10,
        b02 = a00 * a13 - a03 * a10,
        b03 = a01 * a12 - a02 * a11,
        b04 = a01 * a13 - a03 * a11,
        b05 = a02 * a13 - a03 * a12,
        b06 = a20 * a31 - a21 * a30,
        b07 = a20 * a32 - a22 * a30,
        b08 = a20 * a33 - a23 * a30,
        b09 = a21 * a32 - a22 * a31,
        b10 = a21 * a33 - a23 * a31,
        b11 = a22 * a33 - a23 * a32;

    // Calculate the determinant
    return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
};
},{}],253:[function(_dereq_,module,exports){
module.exports = fromQuat;

/**
 * Creates a matrix from a quaternion rotation.
 *
 * @param {mat4} out mat4 receiving operation result
 * @param {quat4} q Rotation quaternion
 * @returns {mat4} out
 */
function fromQuat(out, q) {
    var x = q[0], y = q[1], z = q[2], w = q[3],
        x2 = x + x,
        y2 = y + y,
        z2 = z + z,

        xx = x * x2,
        yx = y * x2,
        yy = y * y2,
        zx = z * x2,
        zy = z * y2,
        zz = z * z2,
        wx = w * x2,
        wy = w * y2,
        wz = w * z2;

    out[0] = 1 - yy - zz;
    out[1] = yx + wz;
    out[2] = zx - wy;
    out[3] = 0;

    out[4] = yx - wz;
    out[5] = 1 - xx - zz;
    out[6] = zy + wx;
    out[7] = 0;

    out[8] = zx + wy;
    out[9] = zy - wx;
    out[10] = 1 - xx - yy;
    out[11] = 0;

    out[12] = 0;
    out[13] = 0;
    out[14] = 0;
    out[15] = 1;

    return out;
};
},{}],254:[function(_dereq_,module,exports){
module.exports = fromRotationTranslation;

/**
 * Creates a matrix from a quaternion rotation and vector translation
 * This is equivalent to (but much faster than):
 *
 *     mat4.identity(dest);
 *     mat4.translate(dest, vec);
 *     var quatMat = mat4.create();
 *     quat4.toMat4(quat, quatMat);
 *     mat4.multiply(dest, quatMat);
 *
 * @param {mat4} out mat4 receiving operation result
 * @param {quat4} q Rotation quaternion
 * @param {vec3} v Translation vector
 * @returns {mat4} out
 */
function fromRotationTranslation(out, q, v) {
    // Quaternion math
    var x = q[0], y = q[1], z = q[2], w = q[3],
        x2 = x + x,
        y2 = y + y,
        z2 = z + z,

        xx = x * x2,
        xy = x * y2,
        xz = x * z2,
        yy = y * y2,
        yz = y * z2,
        zz = z * z2,
        wx = w * x2,
        wy = w * y2,
        wz = w * z2;

    out[0] = 1 - (yy + zz);
    out[1] = xy + wz;
    out[2] = xz - wy;
    out[3] = 0;
    out[4] = xy - wz;
    out[5] = 1 - (xx + zz);
    out[6] = yz + wx;
    out[7] = 0;
    out[8] = xz + wy;
    out[9] = yz - wx;
    out[10] = 1 - (xx + yy);
    out[11] = 0;
    out[12] = v[0];
    out[13] = v[1];
    out[14] = v[2];
    out[15] = 1;
    
    return out;
};
},{}],255:[function(_dereq_,module,exports){
module.exports = identity;

/**
 * Set a mat4 to the identity matrix
 *
 * @param {mat4} out the receiving matrix
 * @returns {mat4} out
 */
function identity(out) {
    out[0] = 1;
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = 0;
    out[5] = 1;
    out[6] = 0;
    out[7] = 0;
    out[8] = 0;
    out[9] = 0;
    out[10] = 1;
    out[11] = 0;
    out[12] = 0;
    out[13] = 0;
    out[14] = 0;
    out[15] = 1;
    return out;
};
},{}],256:[function(_dereq_,module,exports){
module.exports = invert;

/**
 * Inverts a mat4
 *
 * @param {mat4} out the receiving matrix
 * @param {mat4} a the source matrix
 * @returns {mat4} out
 */
function invert(out, a) {
    var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
        a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
        a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
        a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15],

        b00 = a00 * a11 - a01 * a10,
        b01 = a00 * a12 - a02 * a10,
        b02 = a00 * a13 - a03 * a10,
        b03 = a01 * a12 - a02 * a11,
        b04 = a01 * a13 - a03 * a11,
        b05 = a02 * a13 - a03 * a12,
        b06 = a20 * a31 - a21 * a30,
        b07 = a20 * a32 - a22 * a30,
        b08 = a20 * a33 - a23 * a30,
        b09 = a21 * a32 - a22 * a31,
        b10 = a21 * a33 - a23 * a31,
        b11 = a22 * a33 - a23 * a32,

        // Calculate the determinant
        det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;

    if (!det) { 
        return null; 
    }
    det = 1.0 / det;

    out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
    out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
    out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
    out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
    out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
    out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
    out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
    out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
    out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
    out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
    out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
    out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
    out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
    out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
    out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
    out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;

    return out;
};
},{}],257:[function(_dereq_,module,exports){
var identity = _dereq_('./identity');

module.exports = lookAt;

/**
 * Generates a look-at matrix with the given eye position, focal point, and up axis
 *
 * @param {mat4} out mat4 frustum matrix will be written into
 * @param {vec3} eye Position of the viewer
 * @param {vec3} center Point the viewer is looking at
 * @param {vec3} up vec3 pointing up
 * @returns {mat4} out
 */
function lookAt(out, eye, center, up) {
    var x0, x1, x2, y0, y1, y2, z0, z1, z2, len,
        eyex = eye[0],
        eyey = eye[1],
        eyez = eye[2],
        upx = up[0],
        upy = up[1],
        upz = up[2],
        centerx = center[0],
        centery = center[1],
        centerz = center[2];

    if (Math.abs(eyex - centerx) < 0.000001 &&
        Math.abs(eyey - centery) < 0.000001 &&
        Math.abs(eyez - centerz) < 0.000001) {
        return identity(out);
    }

    z0 = eyex - centerx;
    z1 = eyey - centery;
    z2 = eyez - centerz;

    len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);
    z0 *= len;
    z1 *= len;
    z2 *= len;

    x0 = upy * z2 - upz * z1;
    x1 = upz * z0 - upx * z2;
    x2 = upx * z1 - upy * z0;
    len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);
    if (!len) {
        x0 = 0;
        x1 = 0;
        x2 = 0;
    } else {
        len = 1 / len;
        x0 *= len;
        x1 *= len;
        x2 *= len;
    }

    y0 = z1 * x2 - z2 * x1;
    y1 = z2 * x0 - z0 * x2;
    y2 = z0 * x1 - z1 * x0;

    len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2);
    if (!len) {
        y0 = 0;
        y1 = 0;
        y2 = 0;
    } else {
        len = 1 / len;
        y0 *= len;
        y1 *= len;
        y2 *= len;
    }

    out[0] = x0;
    out[1] = y0;
    out[2] = z0;
    out[3] = 0;
    out[4] = x1;
    out[5] = y1;
    out[6] = z1;
    out[7] = 0;
    out[8] = x2;
    out[9] = y2;
    out[10] = z2;
    out[11] = 0;
    out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
    out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
    out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
    out[15] = 1;

    return out;
};
},{"./identity":255}],258:[function(_dereq_,module,exports){
module.exports = multiply;

/**
 * Multiplies two mat4's
 *
 * @param {mat4} out the receiving matrix
 * @param {mat4} a the first operand
 * @param {mat4} b the second operand
 * @returns {mat4} out
 */
function multiply(out, a, b) {
    var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
        a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
        a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
        a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];

    // Cache only the current line of the second matrix
    var b0  = b[0], b1 = b[1], b2 = b[2], b3 = b[3];  
    out[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
    out[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
    out[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
    out[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33;

    b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7];
    out[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
    out[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
    out[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
    out[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33;

    b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11];
    out[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
    out[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
    out[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
    out[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33;

    b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15];
    out[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
    out[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
    out[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
    out[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
    return out;
};
},{}],259:[function(_dereq_,module,exports){
module.exports = perspective;

/**
 * Generates a perspective projection matrix with the given bounds
 *
 * @param {mat4} out mat4 frustum matrix will be written into
 * @param {number} fovy Vertical field of view in radians
 * @param {number} aspect Aspect ratio. typically viewport width/height
 * @param {number} near Near bound of the frustum
 * @param {number} far Far bound of the frustum
 * @returns {mat4} out
 */
function perspective(out, fovy, aspect, near, far) {
    var f = 1.0 / Math.tan(fovy / 2),
        nf = 1 / (near - far);
    out[0] = f / aspect;
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = 0;
    out[5] = f;
    out[6] = 0;
    out[7] = 0;
    out[8] = 0;
    out[9] = 0;
    out[10] = (far + near) * nf;
    out[11] = -1;
    out[12] = 0;
    out[13] = 0;
    out[14] = (2 * far * near) * nf;
    out[15] = 0;
    return out;
};
},{}],260:[function(_dereq_,module,exports){
module.exports = rotate;

/**
 * Rotates a mat4 by the given angle
 *
 * @param {mat4} out the receiving matrix
 * @param {mat4} a the matrix to rotate
 * @param {Number} rad the angle to rotate the matrix by
 * @param {vec3} axis the axis to rotate around
 * @returns {mat4} out
 */
function rotate(out, a, rad, axis) {
    var x = axis[0], y = axis[1], z = axis[2],
        len = Math.sqrt(x * x + y * y + z * z),
        s, c, t,
        a00, a01, a02, a03,
        a10, a11, a12, a13,
        a20, a21, a22, a23,
        b00, b01, b02,
        b10, b11, b12,
        b20, b21, b22;

    if (Math.abs(len) < 0.000001) { return null; }
    
    len = 1 / len;
    x *= len;
    y *= len;
    z *= len;

    s = Math.sin(rad);
    c = Math.cos(rad);
    t = 1 - c;

    a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3];
    a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7];
    a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11];

    // Construct the elements of the rotation matrix
    b00 = x * x * t + c; b01 = y * x * t + z * s; b02 = z * x * t - y * s;
    b10 = x * y * t - z * s; b11 = y * y * t + c; b12 = z * y * t + x * s;
    b20 = x * z * t + y * s; b21 = y * z * t - x * s; b22 = z * z * t + c;

    // Perform rotation-specific matrix multiplication
    out[0] = a00 * b00 + a10 * b01 + a20 * b02;
    out[1] = a01 * b00 + a11 * b01 + a21 * b02;
    out[2] = a02 * b00 + a12 * b01 + a22 * b02;
    out[3] = a03 * b00 + a13 * b01 + a23 * b02;
    out[4] = a00 * b10 + a10 * b11 + a20 * b12;
    out[5] = a01 * b10 + a11 * b11 + a21 * b12;
    out[6] = a02 * b10 + a12 * b11 + a22 * b12;
    out[7] = a03 * b10 + a13 * b11 + a23 * b12;
    out[8] = a00 * b20 + a10 * b21 + a20 * b22;
    out[9] = a01 * b20 + a11 * b21 + a21 * b22;
    out[10] = a02 * b20 + a12 * b21 + a22 * b22;
    out[11] = a03 * b20 + a13 * b21 + a23 * b22;

    if (a !== out) { // If the source and destination differ, copy the unchanged last row
        out[12] = a[12];
        out[13] = a[13];
        out[14] = a[14];
        out[15] = a[15];
    }
    return out;
};
},{}],261:[function(_dereq_,module,exports){
module.exports = rotateX;

/**
 * Rotates a matrix by the given angle around the X axis
 *
 * @param {mat4} out the receiving matrix
 * @param {mat4} a the matrix to rotate
 * @param {Number} rad the angle to rotate the matrix by
 * @returns {mat4} out
 */
function rotateX(out, a, rad) {
    var s = Math.sin(rad),
        c = Math.cos(rad),
        a10 = a[4],
        a11 = a[5],
        a12 = a[6],
        a13 = a[7],
        a20 = a[8],
        a21 = a[9],
        a22 = a[10],
        a23 = a[11];

    if (a !== out) { // If the source and destination differ, copy the unchanged rows
        out[0]  = a[0];
        out[1]  = a[1];
        out[2]  = a[2];
        out[3]  = a[3];
        out[12] = a[12];
        out[13] = a[13];
        out[14] = a[14];
        out[15] = a[15];
    }

    // Perform axis-specific matrix multiplication
    out[4] = a10 * c + a20 * s;
    out[5] = a11 * c + a21 * s;
    out[6] = a12 * c + a22 * s;
    out[7] = a13 * c + a23 * s;
    out[8] = a20 * c - a10 * s;
    out[9] = a21 * c - a11 * s;
    out[10] = a22 * c - a12 * s;
    out[11] = a23 * c - a13 * s;
    return out;
};
},{}],262:[function(_dereq_,module,exports){
module.exports = rotateY;

/**
 * Rotates a matrix by the given angle around the Y axis
 *
 * @param {mat4} out the receiving matrix
 * @param {mat4} a the matrix to rotate
 * @param {Number} rad the angle to rotate the matrix by
 * @returns {mat4} out
 */
function rotateY(out, a, rad) {
    var s = Math.sin(rad),
        c = Math.cos(rad),
        a00 = a[0],
        a01 = a[1],
        a02 = a[2],
        a03 = a[3],
        a20 = a[8],
        a21 = a[9],
        a22 = a[10],
        a23 = a[11];

    if (a !== out) { // If the source and destination differ, copy the unchanged rows
        out[4]  = a[4];
        out[5]  = a[5];
        out[6]  = a[6];
        out[7]  = a[7];
        out[12] = a[12];
        out[13] = a[13];
        out[14] = a[14];
        out[15] = a[15];
    }

    // Perform axis-specific matrix multiplication
    out[0] = a00 * c - a20 * s;
    out[1] = a01 * c - a21 * s;
    out[2] = a02 * c - a22 * s;
    out[3] = a03 * c - a23 * s;
    out[8] = a00 * s + a20 * c;
    out[9] = a01 * s + a21 * c;
    out[10] = a02 * s + a22 * c;
    out[11] = a03 * s + a23 * c;
    return out;
};
},{}],263:[function(_dereq_,module,exports){
module.exports = rotateZ;

/**
 * Rotates a matrix by the given angle around the Z axis
 *
 * @param {mat4} out the receiving matrix
 * @param {mat4} a the matrix to rotate
 * @param {Number} rad the angle to rotate the matrix by
 * @returns {mat4} out
 */
function rotateZ(out, a, rad) {
    var s = Math.sin(rad),
        c = Math.cos(rad),
        a00 = a[0],
        a01 = a[1],
        a02 = a[2],
        a03 = a[3],
        a10 = a[4],
        a11 = a[5],
        a12 = a[6],
        a13 = a[7];

    if (a !== out) { // If the source and destination differ, copy the unchanged last row
        out[8]  = a[8];
        out[9]  = a[9];
        out[10] = a[10];
        out[11] = a[11];
        out[12] = a[12];
        out[13] = a[13];
        out[14] = a[14];
        out[15] = a[15];
    }

    // Perform axis-specific matrix multiplication
    out[0] = a00 * c + a10 * s;
    out[1] = a01 * c + a11 * s;
    out[2] = a02 * c + a12 * s;
    out[3] = a03 * c + a13 * s;
    out[4] = a10 * c - a00 * s;
    out[5] = a11 * c - a01 * s;
    out[6] = a12 * c - a02 * s;
    out[7] = a13 * c - a03 * s;
    return out;
};
},{}],264:[function(_dereq_,module,exports){
module.exports = scale;

/**
 * Scales the mat4 by the dimensions in the given vec3
 *
 * @param {mat4} out the receiving matrix
 * @param {mat4} a the matrix to scale
 * @param {vec3} v the vec3 to scale the matrix by
 * @returns {mat4} out
 **/
function scale(out, a, v) {
    var x = v[0], y = v[1], z = v[2];

    out[0] = a[0] * x;
    out[1] = a[1] * x;
    out[2] = a[2] * x;
    out[3] = a[3] * x;
    out[4] = a[4] * y;
    out[5] = a[5] * y;
    out[6] = a[6] * y;
    out[7] = a[7] * y;
    out[8] = a[8] * z;
    out[9] = a[9] * z;
    out[10] = a[10] * z;
    out[11] = a[11] * z;
    out[12] = a[12];
    out[13] = a[13];
    out[14] = a[14];
    out[15] = a[15];
    return out;
};
},{}],265:[function(_dereq_,module,exports){
module.exports = translate;

/**
 * Translate a mat4 by the given vector
 *
 * @param {mat4} out the receiving matrix
 * @param {mat4} a the matrix to translate
 * @param {vec3} v vector to translate by
 * @returns {mat4} out
 */
function translate(out, a, v) {
    var x = v[0], y = v[1], z = v[2],
        a00, a01, a02, a03,
        a10, a11, a12, a13,
        a20, a21, a22, a23;

    if (a === out) {
        out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
        out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
        out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
        out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
    } else {
        a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3];
        a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7];
        a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11];

        out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a03;
        out[4] = a10; out[5] = a11; out[6] = a12; out[7] = a13;
        out[8] = a20; out[9] = a21; out[10] = a22; out[11] = a23;

        out[12] = a00 * x + a10 * y + a20 * z + a[12];
        out[13] = a01 * x + a11 * y + a21 * z + a[13];
        out[14] = a02 * x + a12 * y + a22 * z + a[14];
        out[15] = a03 * x + a13 * y + a23 * z + a[15];
    }

    return out;
};
},{}],266:[function(_dereq_,module,exports){
module.exports = transpose;

/**
 * Transpose the values of a mat4
 *
 * @param {mat4} out the receiving matrix
 * @param {mat4} a the source matrix
 * @returns {mat4} out
 */
function transpose(out, a) {
    // If we are transposing ourselves we can skip a few steps but have to cache some values
    if (out === a) {
        var a01 = a[1], a02 = a[2], a03 = a[3],
            a12 = a[6], a13 = a[7],
            a23 = a[11];

        out[1] = a[4];
        out[2] = a[8];
        out[3] = a[12];
        out[4] = a01;
        out[6] = a[9];
        out[7] = a[13];
        out[8] = a02;
        out[9] = a12;
        out[11] = a[14];
        out[12] = a03;
        out[13] = a13;
        out[14] = a23;
    } else {
        out[0] = a[0];
        out[1] = a[4];
        out[2] = a[8];
        out[3] = a[12];
        out[4] = a[1];
        out[5] = a[5];
        out[6] = a[9];
        out[7] = a[13];
        out[8] = a[2];
        out[9] = a[6];
        out[10] = a[10];
        out[11] = a[14];
        out[12] = a[3];
        out[13] = a[7];
        out[14] = a[11];
        out[15] = a[15];
    }
    
    return out;
};
},{}],267:[function(_dereq_,module,exports){
'use strict'

module.exports = invert

var invert2 = _dereq_('gl-mat2/invert')
var invert3 = _dereq_('gl-mat3/invert')
var invert4 = _dereq_('gl-mat4/invert')

function invert(out, M) {
  switch(M.length) {
    case 0:
    break
    case 1:
      out[0] = 1.0 / M[0]
    break
    case 4:
      invert2(out, M)
    break
    case 9:
      invert3(out, M)
    break
    case 16:
      invert4(out, M)
    break
    default:
      throw new Error('currently supports matrices up to 4x4')
    break
  }
  return out
}
},{"gl-mat2/invert":248,"gl-mat3/invert":249,"gl-mat4/invert":256}],268:[function(_dereq_,module,exports){
arguments[4][233][0].apply(exports,arguments)
},{"barycentric":62,"dup":233,"polytope-closest-point/lib/closest_point_2d.js":467}],269:[function(_dereq_,module,exports){
var glslify       = _dereq_('glslify')

var triVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, normal;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model\n           , view\n           , projection\n           , inverseModel;\nuniform vec3 eyePosition\n           , lightPosition;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvec4 project(vec3 p) {\n  return projection * view * model * vec4(p, 1.0);\n}\n\nvoid main() {\n  gl_Position      = project(position);\n\n  //Lighting geometry parameters\n  vec4 cameraCoordinate = view * vec4(position , 1.0);\n  cameraCoordinate.xyz /= cameraCoordinate.w;\n  f_lightDirection = lightPosition - cameraCoordinate.xyz;\n  f_eyeDirection   = eyePosition - cameraCoordinate.xyz;\n  f_normal  = normalize((vec4(normal,0) * inverseModel).xyz);\n\n  f_color          = color;\n  f_data           = position;\n  f_uv             = uv;\n}\n"])
var triFragSrc = glslify(["#extension GL_OES_standard_derivatives : enable\n\nprecision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution(float x, float roughness) {\n  float NdotH = max(x, 0.0001);\n  float cos2Alpha = NdotH * NdotH;\n  float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n  float roughness2 = roughness * roughness;\n  float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n  return exp(tan2Alpha / roughness2) / denom;\n}\n\nfloat cookTorranceSpecular(\n  vec3 lightDirection,\n  vec3 viewDirection,\n  vec3 surfaceNormal,\n  float roughness,\n  float fresnel) {\n\n  float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n  float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n  //Half angle vector\n  vec3 H = normalize(lightDirection + viewDirection);\n\n  //Geometric term\n  float NdotH = max(dot(surfaceNormal, H), 0.0);\n  float VdotH = max(dot(viewDirection, H), 0.000001);\n  float LdotH = max(dot(lightDirection, H), 0.000001);\n  float G1 = (2.0 * NdotH * VdotN) / VdotH;\n  float G2 = (2.0 * NdotH * LdotN) / LdotH;\n  float G = min(1.0, min(G1, G2));\n  \n  //Distribution term\n  float D = beckmannDistribution(NdotH, roughness);\n\n  //Fresnel term\n  float F = pow(1.0 - VdotN, fresnel);\n\n  //Multiply terms and done\n  return  G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\n//#pragma glslify: beckmann = require(glsl-specular-beckmann) // used in gl-surface3d\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n            , fresnel\n            , kambient\n            , kdiffuse\n            , kspecular\n            , opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_data)) discard;\n\n  vec3 N = normalize(f_normal);\n  vec3 L = normalize(f_lightDirection);\n  vec3 V = normalize(f_eyeDirection);\n\n  if(gl_FrontFacing) {\n    N = -N;\n  }\n\n  float specular = min(1.0, max(0.0, cookTorranceSpecular(L, V, N, roughness, fresnel)));\n  //float specular = max(0.0, beckmann(L, V, N, roughness)); // used in gl-surface3d\n\n  float diffuse  = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n  vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n  vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular,  1.0);\n\n  gl_FragColor = litColor * opacity;\n}\n"])
var edgeVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model, view, projection;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n  gl_Position = projection * view * model * vec4(position, 1.0);\n  f_color = color;\n  f_data  = position;\n  f_uv    = uv;\n}"])
var edgeFragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_data)) discard;\n\n  gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}"])
var pointVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\nattribute float pointSize;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    gl_Position = projection * view * model * vec4(position, 1.0);\n  }\n  gl_PointSize = pointSize;\n  f_color = color;\n  f_uv = uv;\n}"])
var pointFragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  vec2 pointR = gl_PointCoord.xy - vec2(0.5,0.5);\n  if(dot(pointR, pointR) > 0.25) {\n    discard;\n  }\n  gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}"])
var pickVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  gl_Position = projection * view * model * vec4(position, 1.0);\n  f_id        = id;\n  f_position  = position;\n}"])
var pickFragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3  clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n\n  gl_FragColor = vec4(pickId, f_id.xyz);\n}"])
var pickPointVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3  position;\nattribute float pointSize;\nattribute vec4  id;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    gl_Position  = projection * view * model * vec4(position, 1.0);\n    gl_PointSize = pointSize;\n  }\n  f_id         = id;\n  f_position   = position;\n}"])
var contourVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\n\nvoid main() {\n  gl_Position = projection * view * model * vec4(position, 1.0);\n}"])
var contourFragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n  gl_FragColor = vec4(contourColor,1);\n}\n"])

exports.meshShader = {
  vertex:   triVertSrc,
  fragment: triFragSrc,
  attributes: [
    {name: 'position', type: 'vec3'},
    {name: 'normal', type: 'vec3'},
    {name: 'color', type: 'vec4'},
    {name: 'uv', type: 'vec2'}
  ]
}
exports.wireShader = {
  vertex:   edgeVertSrc,
  fragment: edgeFragSrc,
  attributes: [
    {name: 'position', type: 'vec3'},
    {name: 'color', type: 'vec4'},
    {name: 'uv', type: 'vec2'}
  ]
}
exports.pointShader = {
  vertex:   pointVertSrc,
  fragment: pointFragSrc,
  attributes: [
    {name: 'position', type: 'vec3'},
    {name: 'color', type: 'vec4'},
    {name: 'uv', type: 'vec2'},
    {name: 'pointSize', type: 'float'}
  ]
}
exports.pickShader = {
  vertex:   pickVertSrc,
  fragment: pickFragSrc,
  attributes: [
    {name: 'position', type: 'vec3'},
    {name: 'id', type: 'vec4'}
  ]
}
exports.pointPickShader = {
  vertex:   pickPointVertSrc,
  fragment: pickFragSrc,
  attributes: [
    {name: 'position', type: 'vec3'},
    {name: 'pointSize', type: 'float'},
    {name: 'id', type: 'vec4'}
  ]
}
exports.contourShader = {
  vertex:   contourVertSrc,
  fragment: contourFragSrc,
  attributes: [
    {name: 'position', type: 'vec3'}
  ]
}

},{"glslify":395}],270:[function(_dereq_,module,exports){
'use strict'

var DEFAULT_VERTEX_NORMALS_EPSILON = 1e-6; // may be too large if triangles are very small
var DEFAULT_FACE_NORMALS_EPSILON = 1e-6;

var createShader  = _dereq_('gl-shader')
var createBuffer  = _dereq_('gl-buffer')
var createVAO     = _dereq_('gl-vao')
var createTexture = _dereq_('gl-texture2d')
var normals       = _dereq_('normals')
var multiply      = _dereq_('gl-mat4/multiply')
var invert        = _dereq_('gl-mat4/invert')
var ndarray       = _dereq_('ndarray')
var colormap      = _dereq_('colormap')
var getContour    = _dereq_('simplicial-complex-contour')
var pool          = _dereq_('typedarray-pool')
var shaders       = _dereq_('./lib/shaders')
var closestPoint  = _dereq_('./lib/closest-point')

var meshShader    = shaders.meshShader
var wireShader    = shaders.wireShader
var pointShader   = shaders.pointShader
var pickShader    = shaders.pickShader
var pointPickShader = shaders.pointPickShader
var contourShader = shaders.contourShader

var IDENTITY = [
  1,0,0,0,
  0,1,0,0,
  0,0,1,0,
  0,0,0,1]


function SimplicialMesh(gl
  , texture
  , triShader
  , lineShader
  , pointShader
  , pickShader
  , pointPickShader
  , contourShader
  , trianglePositions
  , triangleIds
  , triangleColors
  , triangleUVs
  , triangleNormals
  , triangleVAO
  , edgePositions
  , edgeIds
  , edgeColors
  , edgeUVs
  , edgeVAO
  , pointPositions
  , pointIds
  , pointColors
  , pointUVs
  , pointSizes
  , pointVAO
  , contourPositions
  , contourVAO) {

  this.gl                = gl
  this.cells             = []
  this.positions         = []
  this.intensity         = []
  this.texture           = texture
  this.dirty             = true

  this.triShader         = triShader
  this.lineShader        = lineShader
  this.pointShader       = pointShader
  this.pickShader        = pickShader
  this.pointPickShader   = pointPickShader
  this.contourShader     = contourShader

  this.trianglePositions = trianglePositions
  this.triangleColors    = triangleColors
  this.triangleNormals   = triangleNormals
  this.triangleUVs       = triangleUVs
  this.triangleIds       = triangleIds
  this.triangleVAO       = triangleVAO
  this.triangleCount     = 0

  this.lineWidth         = 1
  this.edgePositions     = edgePositions
  this.edgeColors        = edgeColors
  this.edgeUVs           = edgeUVs
  this.edgeIds           = edgeIds
  this.edgeVAO           = edgeVAO
  this.edgeCount         = 0

  this.pointPositions    = pointPositions
  this.pointColors       = pointColors
  this.pointUVs          = pointUVs
  this.pointSizes        = pointSizes
  this.pointIds          = pointIds
  this.pointVAO          = pointVAO
  this.pointCount        = 0

  this.contourLineWidth  = 1
  this.contourPositions  = contourPositions
  this.contourVAO        = contourVAO
  this.contourCount      = 0
  this.contourColor      = [0,0,0]
  this.contourEnable     = true

  this.pickId            = 1
  this.bounds            = [
    [ Infinity, Infinity, Infinity],
    [-Infinity,-Infinity,-Infinity] ]
  this.clipBounds        = [
    [-Infinity,-Infinity,-Infinity],
    [ Infinity, Infinity, Infinity] ]

  this.lightPosition = [1e5, 1e5, 0]
  this.ambientLight  = 0.8
  this.diffuseLight  = 0.8
  this.specularLight = 2.0
  this.roughness     = 0.5
  this.fresnel       = 1.5

  this.opacity       = 1.0

  this._model       = IDENTITY
  this._view        = IDENTITY
  this._projection  = IDENTITY
  this._resolution  = [1,1]
}

var proto = SimplicialMesh.prototype

proto.isOpaque = function() {
  return this.opacity >= 1
}

proto.isTransparent = function() {
  return this.opacity < 1
}

proto.pickSlots = 1

proto.setPickBase = function(id) {
  this.pickId = id
}

function genColormap(param) {
  var colors = colormap({
      colormap: param
    , nshades:  256
    , format:  'rgba'
  })

  var result = new Uint8Array(256*4)
  for(var i=0; i<256; ++i) {
    var c = colors[i]
    for(var j=0; j<3; ++j) {
      result[4*i+j] = c[j]
    }
    result[4*i+3] = c[3]*255
  }

  return ndarray(result, [256,256,4], [4,0,1])
}

function unpackIntensity(cells, numVerts, cellIntensity) {
  var result = new Array(numVerts)
  for(var i=0; i<numVerts; ++i) {
    result[i] = 0
  }
  var numCells = cells.length
  for(var i=0; i<numCells; ++i) {
    var c = cells[i]
    for(var j=0; j<c.length; ++j) {
      result[c[j]] = cellIntensity[i]
    }
  }
  return result
}

function takeZComponent(array) {
  var n = array.length
  var result = new Array(n)
  for(var i=0; i<n; ++i) {
    result[i] = array[i][2]
  }
  return result
}

proto.highlight = function(selection) {
  if(!selection || !this.contourEnable) {
    this.contourCount = 0
    return
  }
  var level = getContour(this.cells, this.intensity, selection.intensity)
  var cells         = level.cells
  var vertexIds     = level.vertexIds
  var vertexWeights = level.vertexWeights
  var numCells = cells.length
  var result = pool.mallocFloat32(2 * 3 * numCells)
  var ptr = 0
  for(var i=0; i<numCells; ++i) {
    var c = cells[i]
    for(var j=0; j<2; ++j) {
      var v = c[0]
      if(c.length === 2) {
        v = c[j]
      }
      var a = vertexIds[v][0]
      var b = vertexIds[v][1]
      var w = vertexWeights[v]
      var wi = 1.0 - w
      var pa = this.positions[a]
      var pb = this.positions[b]
      for(var k=0; k<3; ++k) {
        result[ptr++] = w * pa[k] + wi * pb[k]
      }
    }
  }
  this.contourCount = (ptr / 3)|0
  this.contourPositions.update(result.subarray(0, ptr))
  pool.free(result)
}

proto.update = function(params) {
  params = params || {}
  var gl = this.gl

  this.dirty = true

  if('contourEnable' in params) {
    this.contourEnable = params.contourEnable
  }
  if('contourColor' in params) {
    this.contourColor = params.contourColor
  }
  if('lineWidth' in params) {
    this.lineWidth = params.lineWidth
  }
  if('lightPosition' in params) {
    this.lightPosition = params.lightPosition
  }
  if('opacity' in params) {
    this.opacity = params.opacity
  }
  if('ambient' in params) {
    this.ambientLight  = params.ambient
  }
  if('diffuse' in params) {
    this.diffuseLight = params.diffuse
  }
  if('specular' in params) {
    this.specularLight = params.specular
  }
  if('roughness' in params) {
    this.roughness = params.roughness
  }
  if('fresnel' in params) {
    this.fresnel = params.fresnel
  }

  if(params.texture) {
    this.texture.dispose()
    this.texture = createTexture(gl, params.texture)
  } else if (params.colormap) {
    this.texture.shape = [256,256]
    this.texture.minFilter = gl.LINEAR_MIPMAP_LINEAR
    this.texture.magFilter = gl.LINEAR
    this.texture.setPixels(genColormap(params.colormap))
    this.texture.generateMipmap()
  }

  var cells = params.cells
  var positions = params.positions

  if(!positions || !cells) {
    return
  }

  var tPos = []
  var tCol = []
  var tNor = []
  var tUVs = []
  var tIds = []

  var ePos = []
  var eCol = []
  var eUVs = []
  var eIds = []

  var pPos = []
  var pCol = []
  var pUVs = []
  var pSiz = []
  var pIds = []

  //Save geometry data for picking calculations
  this.cells     = cells
  this.positions = positions

  //Compute normals
  var vertexNormals = params.vertexNormals
  var cellNormals   = params.cellNormals
  var vertexNormalsEpsilon = params.vertexNormalsEpsilon === void(0) ? DEFAULT_VERTEX_NORMALS_EPSILON : params.vertexNormalsEpsilon
  var faceNormalsEpsilon = params.faceNormalsEpsilon === void(0) ? DEFAULT_FACE_NORMALS_EPSILON : params.faceNormalsEpsilon
  if(params.useFacetNormals && !cellNormals) {
    cellNormals = normals.faceNormals(cells, positions, faceNormalsEpsilon)
  }
  if(!cellNormals && !vertexNormals) {
    vertexNormals = normals.vertexNormals(cells, positions, vertexNormalsEpsilon)
  }

  //Compute colors
  var vertexColors    = params.vertexColors
  var cellColors      = params.cellColors
  var meshColor       = params.meshColor || [1,1,1,1]

  //UVs
  var vertexUVs       = params.vertexUVs
  var vertexIntensity = params.vertexIntensity
  var cellUVs         = params.cellUVs
  var cellIntensity   = params.cellIntensity

  var intensityLo     = Infinity
  var intensityHi     = -Infinity
  if(!vertexUVs && !cellUVs) {
    if(vertexIntensity) {
      if(params.vertexIntensityBounds) {
        intensityLo = +params.vertexIntensityBounds[0]
        intensityHi = +params.vertexIntensityBounds[1]
      } else {
        for(var i=0; i<vertexIntensity.length; ++i) {
          var f = vertexIntensity[i]
          intensityLo = Math.min(intensityLo, f)
          intensityHi = Math.max(intensityHi, f)
        }
      }
    } else if(cellIntensity) {
      for(var i=0; i<cellIntensity.length; ++i) {
        var f = cellIntensity[i]
        intensityLo = Math.min(intensityLo, f)
        intensityHi = Math.max(intensityHi, f)
      }
    } else {
      for(var i=0; i<positions.length; ++i) {
        var f = positions[i][2]
        intensityLo = Math.min(intensityLo, f)
        intensityHi = Math.max(intensityHi, f)
      }
    }
  }

  if(vertexIntensity) {
    this.intensity = vertexIntensity
  } else if(cellIntensity) {
    this.intensity = unpackIntensity(cells, positions.length, cellIntensity)
  } else {
    this.intensity = takeZComponent(positions)
  }

  //Point size
  var pointSizes      = params.pointSizes
  var meshPointSize   = params.pointSize || 1.0

  //Update bounds
  this.bounds       = [[Infinity,Infinity,Infinity], [-Infinity,-Infinity,-Infinity]]
  for(var i=0; i<positions.length; ++i) {
    var p = positions[i]
    for(var j=0; j<3; ++j) {
      if(isNaN(p[j]) || !isFinite(p[j])) {
        continue
      }
      this.bounds[0][j] = Math.min(this.bounds[0][j], p[j])
      this.bounds[1][j] = Math.max(this.bounds[1][j], p[j])
    }
  }

  //Pack cells into buffers
  var triangleCount = 0
  var edgeCount = 0
  var pointCount = 0

fill_loop:
  for(var i=0; i<cells.length; ++i) {
    var cell = cells[i]
    switch(cell.length) {
      case 1:

        var v = cell[0]
        var p = positions[v]

        //Check NaNs
        for(var j=0; j<3; ++j) {
          if(isNaN(p[j]) || !isFinite(p[j])) {
            continue fill_loop
          }
        }

        pPos.push(p[0], p[1], p[2])

        var c
        if(vertexColors) {
          c = vertexColors[v]
        } else if(cellColors) {
          c = cellColors[i]
        } else {
          c = meshColor
        }
        if(c.length === 3) {
          pCol.push(c[0], c[1], c[2], 1)
        } else {
          pCol.push(c[0], c[1], c[2], c[3])
        }

        var uv
        if(vertexUVs) {
          uv = vertexUVs[v]
        } else if(vertexIntensity) {
          uv = [
            (vertexIntensity[v] - intensityLo) /
            (intensityHi - intensityLo), 0]
        } else if(cellUVs) {
          uv = cellUVs[i]
        } else if(cellIntensity) {
          uv = [
            (cellIntensity[i] - intensityLo) /
            (intensityHi - intensityLo), 0]
        } else {
          uv = [
            (p[2] - intensityLo) /
            (intensityHi - intensityLo), 0]
        }
        pUVs.push(uv[0], uv[1])

        if(pointSizes) {
          pSiz.push(pointSizes[v])
        } else {
          pSiz.push(meshPointSize)
        }

        pIds.push(i)

        pointCount += 1
      break

      case 2:

        //Check NaNs
        for(var j=0; j<2; ++j) {
          var v = cell[j]
          var p = positions[v]
          for(var k=0; k<3; ++k) {
            if(isNaN(p[k]) || !isFinite(p[k])) {
              continue fill_loop
            }
          }
        }

        for(var j=0; j<2; ++j) {
          var v = cell[j]
          var p = positions[v]

          ePos.push(p[0], p[1], p[2])

          var c
          if(vertexColors) {
            c = vertexColors[v]
          } else if(cellColors) {
            c = cellColors[i]
          } else {
            c = meshColor
          }
          if(c.length === 3) {
            eCol.push(c[0], c[1], c[2], 1)
          } else {
            eCol.push(c[0], c[1], c[2], c[3])
          }

          var uv
          if(vertexUVs) {
            uv = vertexUVs[v]
          } else if(vertexIntensity) {
            uv = [
              (vertexIntensity[v] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else if(cellUVs) {
            uv = cellUVs[i]
          } else if(cellIntensity) {
            uv = [
              (cellIntensity[i] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else {
            uv = [
              (p[2] - intensityLo) /
              (intensityHi - intensityLo), 0]
          }
          eUVs.push(uv[0], uv[1])

          eIds.push(i)
        }
        edgeCount += 1
      break

      case 3:
        //Check NaNs
        for(var j=0; j<3; ++j) {
          var v = cell[j]
          var p = positions[v]
          for(var k=0; k<3; ++k) {
            if(isNaN(p[k]) || !isFinite(p[k])) {
              continue fill_loop
            }
          }
        }

        for(var j=0; j<3; ++j) {
          var v = cell[2 - j]

          var p = positions[v]
          tPos.push(p[0], p[1], p[2])

          var c
          if(vertexColors) {
            c = vertexColors[v]
          } else if(cellColors) {
            c = cellColors[i]
          } else {
            c = meshColor
          }
          if(c.length === 3) {
            tCol.push(c[0], c[1], c[2], 1)
          } else {
            tCol.push(c[0], c[1], c[2], c[3])
          }

          var uv
          if(vertexUVs) {
            uv = vertexUVs[v]
          } else if(vertexIntensity) {
            uv = [
              (vertexIntensity[v] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else if(cellUVs) {
            uv = cellUVs[i]
          } else if(cellIntensity) {
            uv = [
              (cellIntensity[i] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else {
            uv = [
              (p[2] - intensityLo) /
              (intensityHi - intensityLo), 0]
          }
          tUVs.push(uv[0], uv[1])

          var q
          if(vertexNormals) {
            q = vertexNormals[v]
          } else {
            q = cellNormals[i]
          }
          tNor.push(q[0], q[1], q[2])

          tIds.push(i)
        }
        triangleCount += 1
      break

      default:
      break
    }
  }

  this.pointCount     = pointCount
  this.edgeCount      = edgeCount
  this.triangleCount  = triangleCount

  this.pointPositions.update(pPos)
  this.pointColors.update(pCol)
  this.pointUVs.update(pUVs)
  this.pointSizes.update(pSiz)
  this.pointIds.update(new Uint32Array(pIds))

  this.edgePositions.update(ePos)
  this.edgeColors.update(eCol)
  this.edgeUVs.update(eUVs)
  this.edgeIds.update(new Uint32Array(eIds))

  this.trianglePositions.update(tPos)
  this.triangleColors.update(tCol)
  this.triangleUVs.update(tUVs)
  this.triangleNormals.update(tNor)
  this.triangleIds.update(new Uint32Array(tIds))
}

proto.drawTransparent = proto.draw = function(params) {
  params = params || {}
  var gl          = this.gl
  var model       = params.model      || IDENTITY
  var view        = params.view       || IDENTITY
  var projection  = params.projection || IDENTITY

  var clipBounds = [[-1e6,-1e6,-1e6],[1e6,1e6,1e6]]
  for(var i=0; i<3; ++i) {
    clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i])
    clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i])
  }

  var uniforms = {
    model:      model,
    view:       view,
    projection: projection,
    inverseModel: IDENTITY.slice(),

    clipBounds: clipBounds,

    kambient:   this.ambientLight,
    kdiffuse:   this.diffuseLight,
    kspecular:  this.specularLight,
    roughness:  this.roughness,
    fresnel:    this.fresnel,

    eyePosition:   [0,0,0],
    lightPosition: [0,0,0],

    opacity:  this.opacity,

    contourColor: this.contourColor,

    texture:    0
  }

  uniforms.inverseModel = invert(uniforms.inverseModel, uniforms.model)

  gl.disable(gl.CULL_FACE)

  this.texture.bind(0)

  var invCameraMatrix = new Array(16)
  multiply(invCameraMatrix, uniforms.view, uniforms.model)
  multiply(invCameraMatrix, uniforms.projection, invCameraMatrix)
  invert(invCameraMatrix, invCameraMatrix)

  for(var i=0; i<3; ++i) {
    uniforms.eyePosition[i] = invCameraMatrix[12+i] / invCameraMatrix[15]
  }

  var w = invCameraMatrix[15]
  for(var i=0; i<3; ++i) {
    w += this.lightPosition[i] * invCameraMatrix[4*i+3]
  }
  for(var i=0; i<3; ++i) {
    var s = invCameraMatrix[12+i]
    for(var j=0; j<3; ++j) {
      s += invCameraMatrix[4*j+i] * this.lightPosition[j]
    }
    uniforms.lightPosition[i] = s / w
  }

  if(this.triangleCount > 0) {
    var shader = this.triShader
    shader.bind()
    shader.uniforms = uniforms

    this.triangleVAO.bind()
    gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3)
    this.triangleVAO.unbind()
  }

  if(this.edgeCount > 0 && this.lineWidth > 0) {
    var shader = this.lineShader
    shader.bind()
    shader.uniforms = uniforms

    this.edgeVAO.bind()
    gl.lineWidth(this.lineWidth)
    gl.drawArrays(gl.LINES, 0, this.edgeCount*2)
    this.edgeVAO.unbind()
  }

  if(this.pointCount > 0) {
    var shader = this.pointShader
    shader.bind()
    shader.uniforms = uniforms

    this.pointVAO.bind()
    gl.drawArrays(gl.POINTS, 0, this.pointCount)
    this.pointVAO.unbind()
  }

  if(this.contourEnable && this.contourCount > 0 && this.contourLineWidth > 0) {
    var shader = this.contourShader
    shader.bind()
    shader.uniforms = uniforms

    this.contourVAO.bind()
    gl.drawArrays(gl.LINES, 0, this.contourCount)
    this.contourVAO.unbind()
  }
}

proto.drawPick = function(params) {
  params = params || {}

  var gl         = this.gl

  var model      = params.model      || IDENTITY
  var view       = params.view       || IDENTITY
  var projection = params.projection || IDENTITY

  var clipBounds = [[-1e6,-1e6,-1e6],[1e6,1e6,1e6]]
  for(var i=0; i<3; ++i) {
    clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i])
    clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i])
  }

  //Save camera parameters
  this._model      = [].slice.call(model)
  this._view       = [].slice.call(view)
  this._projection = [].slice.call(projection)
  this._resolution = [gl.drawingBufferWidth, gl.drawingBufferHeight]

  var uniforms = {
    model:      model,
    view:       view,
    projection: projection,
    clipBounds: clipBounds,
    pickId:     this.pickId / 255.0,
  }

  var shader = this.pickShader
  shader.bind()
  shader.uniforms = uniforms

  if(this.triangleCount > 0) {
    this.triangleVAO.bind()
    gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3)
    this.triangleVAO.unbind()
  }

  if(this.edgeCount > 0) {
    this.edgeVAO.bind()
    gl.lineWidth(this.lineWidth)
    gl.drawArrays(gl.LINES, 0, this.edgeCount*2)
    this.edgeVAO.unbind()
  }

  if(this.pointCount > 0) {
    var shader = this.pointPickShader
    shader.bind()
    shader.uniforms = uniforms

    this.pointVAO.bind()
    gl.drawArrays(gl.POINTS, 0, this.pointCount)
    this.pointVAO.unbind()
  }
}


proto.pick = function(pickData) {
  if(!pickData) {
    return null
  }
  if(pickData.id !== this.pickId) {
    return null
  }

  var cellId    = pickData.value[0] + 256*pickData.value[1] + 65536*pickData.value[2]
  var cell      = this.cells[cellId]
  var positions = this.positions

  var simplex   = new Array(cell.length)
  for(var i=0; i<cell.length; ++i) {
    simplex[i] = positions[cell[i]]
  }

  var data = closestPoint(
    simplex,
    [pickData.coord[0], this._resolution[1]-pickData.coord[1]],
    this._model,
    this._view,
    this._projection,
    this._resolution)

  if(!data) {
    return null
  }

  var weights = data[2]
  var interpIntensity = 0.0
  for(var i=0; i<cell.length; ++i) {
    interpIntensity += weights[i] * this.intensity[cell[i]]
  }

  return {
    position: data[1],
    index:    cell[data[0]],
    cell:     cell,
    cellId:   cellId,
    intensity:  interpIntensity,
    dataCoordinate: this.positions[cell[data[0]]]
  }
}


proto.dispose = function() {
  this.texture.dispose()

  this.triShader.dispose()
  this.lineShader.dispose()
  this.pointShader.dispose()
  this.pickShader.dispose()
  this.pointPickShader.dispose()

  this.triangleVAO.dispose()
  this.trianglePositions.dispose()
  this.triangleColors.dispose()
  this.triangleUVs.dispose()
  this.triangleNormals.dispose()
  this.triangleIds.dispose()

  this.edgeVAO.dispose()
  this.edgePositions.dispose()
  this.edgeColors.dispose()
  this.edgeUVs.dispose()
  this.edgeIds.dispose()

  this.pointVAO.dispose()
  this.pointPositions.dispose()
  this.pointColors.dispose()
  this.pointUVs.dispose()
  this.pointSizes.dispose()
  this.pointIds.dispose()

  this.contourVAO.dispose()
  this.contourPositions.dispose()
  this.contourShader.dispose()
}

function createMeshShader(gl) {
  var shader = createShader(gl, meshShader.vertex, meshShader.fragment)
  shader.attributes.position.location = 0
  shader.attributes.color.location    = 2
  shader.attributes.uv.location       = 3
  shader.attributes.normal.location   = 4
  return shader
}

function createWireShader(gl) {
  var shader = createShader(gl, wireShader.vertex, wireShader.fragment)
  shader.attributes.position.location = 0
  shader.attributes.color.location    = 2
  shader.attributes.uv.location       = 3
  return shader
}

function createPointShader(gl) {
  var shader = createShader(gl, pointShader.vertex, pointShader.fragment)
  shader.attributes.position.location  = 0
  shader.attributes.color.location     = 2
  shader.attributes.uv.location        = 3
  shader.attributes.pointSize.location = 4
  return shader
}

function createPickShader(gl) {
  var shader = createShader(gl, pickShader.vertex, pickShader.fragment)
  shader.attributes.position.location = 0
  shader.attributes.id.location       = 1
  return shader
}

function createPointPickShader(gl) {
  var shader = createShader(gl, pointPickShader.vertex, pointPickShader.fragment)
  shader.attributes.position.location  = 0
  shader.attributes.id.location        = 1
  shader.attributes.pointSize.location = 4
  return shader
}

function createContourShader(gl) {
  var shader = createShader(gl, contourShader.vertex, contourShader.fragment)
  shader.attributes.position.location = 0
  return shader
}

function createSimplicialMesh(gl, params) {
  if (arguments.length === 1) {
    params = gl;
    gl = params.gl;
  }

  //enable derivatives for face normals
  var ext = gl.getExtension('OES_standard_derivatives') || gl.getExtension('MOZ_OES_standard_derivatives') || gl.getExtension('WEBKIT_OES_standard_derivatives')
  if (!ext)
    throw new Error('derivatives not supported')

  var triShader       = createMeshShader(gl)
  var lineShader      = createWireShader(gl)
  var pointShader     = createPointShader(gl)
  var pickShader      = createPickShader(gl)
  var pointPickShader = createPointPickShader(gl)
  var contourShader   = createContourShader(gl)

  var meshTexture       = createTexture(gl,
    ndarray(new Uint8Array([255,255,255,255]), [1,1,4]))
  meshTexture.generateMipmap()
  meshTexture.minFilter = gl.LINEAR_MIPMAP_LINEAR
  meshTexture.magFilter = gl.LINEAR

  var trianglePositions = createBuffer(gl)
  var triangleColors    = createBuffer(gl)
  var triangleUVs       = createBuffer(gl)
  var triangleNormals   = createBuffer(gl)
  var triangleIds       = createBuffer(gl)
  var triangleVAO       = createVAO(gl, [
    { buffer: trianglePositions,
      type: gl.FLOAT,
      size: 3
    },
    { buffer: triangleIds,
      type: gl.UNSIGNED_BYTE,
      size: 4,
      normalized: true
    },
    { buffer: triangleColors,
      type: gl.FLOAT,
      size: 4
    },
    { buffer: triangleUVs,
      type: gl.FLOAT,
      size: 2
    },
    { buffer: triangleNormals,
      type: gl.FLOAT,
      size: 3
    }
  ])

  var edgePositions = createBuffer(gl)
  var edgeColors    = createBuffer(gl)
  var edgeUVs       = createBuffer(gl)
  var edgeIds       = createBuffer(gl)
  var edgeVAO       = createVAO(gl, [
    { buffer: edgePositions,
      type: gl.FLOAT,
      size: 3
    },
    { buffer: edgeIds,
      type: gl.UNSIGNED_BYTE,
      size: 4,
      normalized: true
    },
    { buffer: edgeColors,
      type: gl.FLOAT,
      size: 4
    },
    { buffer: edgeUVs,
      type: gl.FLOAT,
      size: 2
    }
  ])

  var pointPositions  = createBuffer(gl)
  var pointColors     = createBuffer(gl)
  var pointUVs        = createBuffer(gl)
  var pointSizes      = createBuffer(gl)
  var pointIds        = createBuffer(gl)
  var pointVAO        = createVAO(gl, [
    { buffer: pointPositions,
      type: gl.FLOAT,
      size: 3
    },
    { buffer: pointIds,
      type: gl.UNSIGNED_BYTE,
      size: 4,
      normalized: true
    },
    { buffer: pointColors,
      type: gl.FLOAT,
      size: 4
    },
    { buffer: pointUVs,
      type: gl.FLOAT,
      size: 2
    },
    { buffer: pointSizes,
      type: gl.FLOAT,
      size: 1
    }
  ])

  var contourPositions = createBuffer(gl)
  var contourVAO       = createVAO(gl, [
    { buffer: contourPositions,
      type:   gl.FLOAT,
      size:   3
    }])

  var mesh = new SimplicialMesh(gl
    , meshTexture
    , triShader
    , lineShader
    , pointShader
    , pickShader
    , pointPickShader
    , contourShader
    , trianglePositions
    , triangleIds
    , triangleColors
    , triangleUVs
    , triangleNormals
    , triangleVAO
    , edgePositions
    , edgeIds
    , edgeColors
    , edgeUVs
    , edgeVAO
    , pointPositions
    , pointIds
    , pointColors
    , pointUVs
    , pointSizes
    , pointVAO
    , contourPositions
    , contourVAO)

  mesh.update(params)

  return mesh
}

module.exports = createSimplicialMesh

},{"./lib/closest-point":268,"./lib/shaders":269,"colormap":115,"gl-buffer":231,"gl-mat4/invert":256,"gl-mat4/multiply":258,"gl-shader":290,"gl-texture2d":308,"gl-vao":313,"ndarray":436,"normals":439,"simplicial-complex-contour":496,"typedarray-pool":523}],271:[function(_dereq_,module,exports){
'use strict'

module.exports = createBoxes

var createBuffer = _dereq_('gl-buffer')
var createShader = _dereq_('gl-shader')

var shaders = _dereq_('./shaders')

function Boxes(plot, vbo, shader) {
  this.plot   = plot
  this.vbo    = vbo
  this.shader = shader
}

var proto = Boxes.prototype

proto.bind = function() {
  var shader = this.shader
  this.vbo.bind()
  this.shader.bind()
  shader.attributes.coord.pointer()
  shader.uniforms.screenBox = this.plot.screenBox
}

proto.drawBox = (function() {
  var lo = [0,0]
  var hi = [0,0]
  return function(loX, loY, hiX, hiY, color) {
    var plot       = this.plot
    var shader     = this.shader
    var gl         = plot.gl

    lo[0] = loX
    lo[1] = loY
    hi[0] = hiX
    hi[1] = hiY

    shader.uniforms.lo     = lo
    shader.uniforms.hi     = hi
    shader.uniforms.color  = color

    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
  }
}())

proto.dispose = function() {
  this.vbo.dispose()
  this.shader.dispose()
}

function createBoxes(plot) {
  var gl  = plot.gl
  var vbo = createBuffer(gl, [
    0,0,
    0,1,
    1,0,
    1,1])
  var shader  = createShader(gl, shaders.boxVert, shaders.lineFrag)
  return new Boxes(plot, vbo, shader)
}

},{"./shaders":274,"gl-buffer":231,"gl-shader":290}],272:[function(_dereq_,module,exports){
'use strict'

module.exports = createGrid

var createBuffer  = _dereq_('gl-buffer')
var createShader  = _dereq_('gl-shader')
var bsearch       = _dereq_('binary-search-bounds')
var shaders       = _dereq_('./shaders')

function Grid(plot, vbo, shader, tickShader) {
  this.plot   = plot
  this.vbo    = vbo
  this.shader = shader
  this.tickShader = tickShader
  this.ticks  = [[], []]
}

function compareTickNum(a, b) {
  return a - b
}

var proto = Grid.prototype

proto.draw = (function() {

  var DATA_SHIFT = [0,0]
  var DATA_SCALE = [0,0]
  var DATA_AXIS  = [0,0]

  return function() {
    var plot       = this.plot
    var vbo        = this.vbo
    var shader     = this.shader
    var ticks      = this.ticks
    var gl         = plot.gl
    var bounds     = plot._tickBounds
    var dataBox    = plot.dataBox
    var viewPixels = plot.viewBox
    var lineWidth  = plot.gridLineWidth
    var gridColor  = plot.gridLineColor
    var gridEnable = plot.gridLineEnable
    var pixelRatio = plot.pixelRatio

    for(var i=0; i<2; ++i) {
      var lo = bounds[i]
      var hi = bounds[i+2]
      var boundScale = hi - lo
      var dataCenter  = 0.5 * (dataBox[i+2] + dataBox[i])
      var dataWidth   = dataBox[i+2] - dataBox[i]
      DATA_SCALE[i] = 2.0 * boundScale / dataWidth
      DATA_SHIFT[i] = 2.0 * (lo - dataCenter) / dataWidth
    }

    shader.bind()
    vbo.bind()
    shader.attributes.dataCoord.pointer()
    shader.uniforms.dataShift = DATA_SHIFT
    shader.uniforms.dataScale = DATA_SCALE

    var offset = 0
    for(var i=0; i<2; ++i) {
      DATA_AXIS[0] = DATA_AXIS[1] = 0
      DATA_AXIS[i] = 1
      shader.uniforms.dataAxis  = DATA_AXIS
      shader.uniforms.lineWidth = lineWidth[i] / (viewPixels[i+2] - viewPixels[i]) * pixelRatio
      shader.uniforms.color     = gridColor[i]

      var size = ticks[i].length * 6
      if(gridEnable[i] && size) {
        gl.drawArrays(gl.TRIANGLES, offset, size)
      }
      offset += size
    }
  }
})()

proto.drawTickMarks = (function() {
  var DATA_SHIFT = [0,0]
  var DATA_SCALE = [0,0]
  var X_AXIS     = [1,0]
  var Y_AXIS     = [0,1]
  var SCR_OFFSET = [0,0]
  var TICK_SCALE = [0,0]

  return function() {
    var plot       = this.plot
    var vbo        = this.vbo
    var shader     = this.tickShader
    var ticks      = this.ticks
    var gl         = plot.gl
    var bounds     = plot._tickBounds
    var dataBox    = plot.dataBox
    var viewBox    = plot.viewBox
    var pixelRatio = plot.pixelRatio
    var screenBox  = plot.screenBox

    var screenWidth  = screenBox[2] - screenBox[0]
    var screenHeight = screenBox[3] - screenBox[1]
    var viewWidth    = viewBox[2]   - viewBox[0]
    var viewHeight   = viewBox[3]   - viewBox[1]

    for(var i=0; i<2; ++i) {
      var lo = bounds[i]
      var hi = bounds[i+2]
      var boundScale = hi - lo
      var dataCenter  = 0.5 * (dataBox[i+2] + dataBox[i])
      var dataWidth   = (dataBox[i+2] - dataBox[i])
      DATA_SCALE[i] = 2.0 * boundScale / dataWidth
      DATA_SHIFT[i] = 2.0 * (lo - dataCenter) / dataWidth
    }

    DATA_SCALE[0] *= viewWidth / screenWidth
    DATA_SHIFT[0] *= viewWidth / screenWidth

    DATA_SCALE[1] *= viewHeight / screenHeight
    DATA_SHIFT[1] *= viewHeight / screenHeight

    shader.bind()
    vbo.bind()

    shader.attributes.dataCoord.pointer()

    var uniforms = shader.uniforms
    uniforms.dataShift = DATA_SHIFT
    uniforms.dataScale = DATA_SCALE

    var tickMarkLength = plot.tickMarkLength
    var tickMarkWidth  = plot.tickMarkWidth
    var tickMarkColor  = plot.tickMarkColor

    var xTicksOffset = 0
    var yTicksOffset = ticks[0].length * 6

    var xStart = Math.min(bsearch.ge(ticks[0], (dataBox[0] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length)
    var xEnd   = Math.min(bsearch.gt(ticks[0], (dataBox[2] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length)
    var xOffset = xTicksOffset + 6 * xStart
    var xCount  = 6 * Math.max(0, xEnd - xStart)

    var yStart = Math.min(bsearch.ge(ticks[1], (dataBox[1] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length)
    var yEnd   = Math.min(bsearch.gt(ticks[1], (dataBox[3] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length)
    var yOffset = yTicksOffset + 6 * yStart
    var yCount  = 6 * Math.max(0, yEnd - yStart)

    SCR_OFFSET[0]         = 2.0 * (viewBox[0] - tickMarkLength[1]) / screenWidth - 1.0
    SCR_OFFSET[1]         = (viewBox[3] + viewBox[1]) / screenHeight - 1.0
    TICK_SCALE[0]         = tickMarkLength[1] * pixelRatio / screenWidth
    TICK_SCALE[1]         = tickMarkWidth[1]  * pixelRatio / screenHeight

    if(yCount) {
      uniforms.color        = tickMarkColor[1]
      uniforms.tickScale    = TICK_SCALE
      uniforms.dataAxis     = Y_AXIS
      uniforms.screenOffset = SCR_OFFSET
      gl.drawArrays(gl.TRIANGLES, yOffset, yCount)
    }

    SCR_OFFSET[0]         = (viewBox[2] + viewBox[0]) / screenWidth - 1.0
    SCR_OFFSET[1]         = 2.0 * (viewBox[1] - tickMarkLength[0]) / screenHeight - 1.0
    TICK_SCALE[0]         = tickMarkWidth[0]  * pixelRatio / screenWidth
    TICK_SCALE[1]         = tickMarkLength[0] * pixelRatio / screenHeight

    if(xCount) {
      uniforms.color        = tickMarkColor[0]
      uniforms.tickScale    = TICK_SCALE
      uniforms.dataAxis     = X_AXIS
      uniforms.screenOffset = SCR_OFFSET
      gl.drawArrays(gl.TRIANGLES, xOffset, xCount)
    }

    SCR_OFFSET[0]         = 2.0 * (viewBox[2] + tickMarkLength[3]) / screenWidth - 1.0
    SCR_OFFSET[1]         = (viewBox[3] + viewBox[1]) / screenHeight - 1.0
    TICK_SCALE[0]         = tickMarkLength[3] * pixelRatio / screenWidth
    TICK_SCALE[1]         = tickMarkWidth[3]  * pixelRatio / screenHeight

    if(yCount) {
      uniforms.color        = tickMarkColor[3]
      uniforms.tickScale    = TICK_SCALE
      uniforms.dataAxis     = Y_AXIS
      uniforms.screenOffset = SCR_OFFSET
      gl.drawArrays(gl.TRIANGLES, yOffset, yCount)
    }

    SCR_OFFSET[0]         = (viewBox[2] + viewBox[0]) / screenWidth - 1.0
    SCR_OFFSET[1]         = 2.0 * (viewBox[3] + tickMarkLength[2]) / screenHeight - 1.0
    TICK_SCALE[0]         = tickMarkWidth[2]  * pixelRatio / screenWidth
    TICK_SCALE[1]         = tickMarkLength[2] * pixelRatio / screenHeight

    if(xCount) {
      uniforms.color        = tickMarkColor[2]
      uniforms.tickScale    = TICK_SCALE
      uniforms.dataAxis     = X_AXIS
      uniforms.screenOffset = SCR_OFFSET
      gl.drawArrays(gl.TRIANGLES, xOffset, xCount)
    }
  }
})()

proto.update = (function() {
  var OFFSET_X = [1,  1, -1, -1,  1, -1]
  var OFFSET_Y = [1, -1,  1,  1, -1, -1]

  return function(options) {
    var ticks  = options.ticks
    var bounds = options.bounds
    var data   = new Float32Array(6 * 3 * (ticks[0].length + ticks[1].length))

    var zeroLineEnable = this.plot.zeroLineEnable

    var ptr    = 0
    var gridTicks = [[], []]
    for(var dim=0; dim<2; ++dim) {
      var localTicks = gridTicks[dim]
      var axisTicks = ticks[dim]
      var lo = bounds[dim]
      var hi = bounds[dim+2]
      for(var i=0; i<axisTicks.length; ++i) {
        var x = (axisTicks[i].x - lo) / (hi - lo)
        localTicks.push(x)
        for(var j=0; j<6; ++j) {
          data[ptr++] = x
          data[ptr++] = OFFSET_X[j]
          data[ptr++] = OFFSET_Y[j]
        }
      }
    }

    this.ticks = gridTicks
    this.vbo.update(data)
  }
})()

proto.dispose = function() {
  this.vbo.dispose()
  this.shader.dispose()
  this.tickShader.dispose()
}

function createGrid(plot) {
  var gl     = plot.gl
  var vbo    = createBuffer(gl)
  var shader = createShader(gl, shaders.gridVert, shaders.gridFrag)
  var tickShader = createShader(gl, shaders.tickVert, shaders.gridFrag)
  var grid   = new Grid(plot, vbo, shader, tickShader)
  return grid
}

},{"./shaders":274,"binary-search-bounds":276,"gl-buffer":231,"gl-shader":290}],273:[function(_dereq_,module,exports){
'use strict'

module.exports = createLines

var createBuffer = _dereq_('gl-buffer')
var createShader = _dereq_('gl-shader')

var shaders = _dereq_('./shaders')

function Lines(plot, vbo, shader) {
  this.plot   = plot
  this.vbo    = vbo
  this.shader = shader
}

var proto = Lines.prototype

proto.bind = function() {
  var shader = this.shader
  this.vbo.bind()
  this.shader.bind()
  shader.attributes.coord.pointer()
  shader.uniforms.screenBox = this.plot.screenBox
}

proto.drawLine = (function() {
  var start = [0,0]
  var end   = [0,0]
  return function(startX, startY, endX, endY, width, color) {
    var plot       = this.plot
    var shader     = this.shader
    var gl         = plot.gl

    start[0] = startX
    start[1] = startY
    end[0]   = endX
    end[1]   = endY

    shader.uniforms.start  = start
    shader.uniforms.end    = end
    shader.uniforms.width  = width * plot.pixelRatio
    shader.uniforms.color  = color

    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
  }
}())

proto.dispose = function() {
  this.vbo.dispose()
  this.shader.dispose()
}

function createLines(plot) {
  var gl  = plot.gl
  var vbo = createBuffer(gl, [
    -1,-1,
    -1,1,
    1,-1,
    1,1])
  var shader  = createShader(gl, shaders.lineVert, shaders.lineFrag)
  var lines   = new Lines(plot, vbo, shader)
  return lines
}

},{"./shaders":274,"gl-buffer":231,"gl-shader":290}],274:[function(_dereq_,module,exports){
'use strict'

var glslify = _dereq_('glslify')

var FRAGMENT = glslify(["precision lowp float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n  gl_FragColor = vec4(color.xyz * color.w, color.w);\n}\n"])

module.exports = {
  lineVert: glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 start, end;\nuniform float width;\n\nvec2 perp(vec2 v) {\n  return vec2(v.y, -v.x);\n}\n\nvec2 screen(vec2 v) {\n  return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n  vec2 delta = normalize(perp(start - end));\n  vec2 offset = mix(start, end, 0.5 * (coord.y+1.0));\n  gl_Position = vec4(screen(offset + 0.5 * width * delta * coord.x), 0, 1);\n}\n"]),
  lineFrag: FRAGMENT,
  textVert: glslify(["#define GLSLIFY 1\nattribute vec3 textCoordinate;\n\nuniform vec2 dataScale, dataShift, dataAxis, screenOffset, textScale;\nuniform float angle;\n\nvoid main() {\n  float dataOffset  = textCoordinate.z;\n  vec2 glyphOffset  = textCoordinate.xy;\n  mat2 glyphMatrix = mat2(cos(angle), sin(angle), -sin(angle), cos(angle));\n  vec2 screenCoordinate = dataAxis * (dataScale * dataOffset + dataShift) +\n    glyphMatrix * glyphOffset * textScale + screenOffset;\n  gl_Position = vec4(screenCoordinate, 0, 1);\n}\n"]),
  textFrag: FRAGMENT,
  gridVert: glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale;\nuniform float lineWidth;\n\nvoid main() {\n  vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n  pos += 10.0 * dataCoord.y * vec2(dataAxis.y, -dataAxis.x) + dataCoord.z * lineWidth;\n  gl_Position = vec4(pos, 0, 1);\n}\n"]),
  gridFrag: FRAGMENT,
  boxVert:  glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 lo, hi;\n\nvec2 screen(vec2 v) {\n  return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n  gl_Position = vec4(screen(mix(lo, hi, coord)), 0, 1);\n}\n"]),
  tickVert: glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale, screenOffset, tickScale;\n\nvoid main() {\n  vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n  gl_Position = vec4(pos + tickScale*dataCoord.yz + screenOffset, 0, 1);\n}\n"])
}

},{"glslify":395}],275:[function(_dereq_,module,exports){
'use strict'

module.exports = createTextElements

var createBuffer = _dereq_('gl-buffer')
var createShader = _dereq_('gl-shader')
var getText      = _dereq_('text-cache')
var bsearch      = _dereq_('binary-search-bounds')
var shaders      = _dereq_('./shaders')

function TextElements(plot, vbo, shader) {
  this.plot         = plot
  this.vbo          = vbo
  this.shader       = shader
  this.tickOffset   = [[],[]]
  this.tickX        = [[],[]]
  this.labelOffset  = [0,0]
  this.labelCount   = [0,0]
}

var proto = TextElements.prototype

proto.drawTicks = (function() {
  var DATA_AXIS = [0,0]
  var SCREEN_OFFSET = [0,0]
  var ZERO_2 = [0,0]

  return function(axis) {
    var plot        = this.plot
    var shader      = this.shader
    var tickX       = this.tickX[axis]
    var tickOffset  = this.tickOffset[axis]
    var gl          = plot.gl
    var viewBox     = plot.viewBox
    var dataBox     = plot.dataBox
    var screenBox   = plot.screenBox
    var pixelRatio  = plot.pixelRatio
    var tickEnable  = plot.tickEnable
    var tickPad     = plot.tickPad
    var textColor   = plot.tickColor
    var textAngle   = plot.tickAngle
    // todo check if this should be used (now unused)
    // var tickLength  = plot.tickMarkLength

    var labelEnable = plot.labelEnable
    var labelPad    = plot.labelPad
    var labelColor  = plot.labelColor
    var labelAngle  = plot.labelAngle
    var labelOffset = this.labelOffset[axis]
    var labelCount  = this.labelCount[axis]

    var start = bsearch.lt(tickX, dataBox[axis])
    var end   = bsearch.le(tickX, dataBox[axis+2])

    DATA_AXIS[0]    = DATA_AXIS[1] = 0
    DATA_AXIS[axis] = 1

    SCREEN_OFFSET[axis] = (viewBox[2+axis] + viewBox[axis]) / (screenBox[2+axis] - screenBox[axis]) - 1.0

    var screenScale = 2.0 / screenBox[2+(axis^1)] - screenBox[axis^1]

    SCREEN_OFFSET[axis^1] = screenScale * viewBox[axis^1] - 1.0
    if(tickEnable[axis]) {
      SCREEN_OFFSET[axis^1] -= screenScale * pixelRatio * tickPad[axis]
      if(start < end && tickOffset[end] > tickOffset[start]) {
        shader.uniforms.dataAxis     = DATA_AXIS
        shader.uniforms.screenOffset = SCREEN_OFFSET
        shader.uniforms.color        = textColor[axis]
        shader.uniforms.angle        = textAngle[axis]
        gl.drawArrays(
          gl.TRIANGLES,
          tickOffset[start],
          tickOffset[end] - tickOffset[start])
      }
    }
    if(labelEnable[axis] && labelCount) {
      SCREEN_OFFSET[axis^1] -= screenScale * pixelRatio * labelPad[axis]
      shader.uniforms.dataAxis     = ZERO_2
      shader.uniforms.screenOffset = SCREEN_OFFSET
      shader.uniforms.color        = labelColor[axis]
      shader.uniforms.angle        = labelAngle[axis]
      gl.drawArrays(
        gl.TRIANGLES,
        labelOffset,
        labelCount)
    }

    SCREEN_OFFSET[axis^1] = screenScale * viewBox[2+(axis^1)] - 1.0
    if(tickEnable[axis+2]) {
      SCREEN_OFFSET[axis^1] += screenScale * pixelRatio * tickPad[axis+2]
      if(start < end && tickOffset[end] > tickOffset[start]) {
        shader.uniforms.dataAxis     = DATA_AXIS
        shader.uniforms.screenOffset = SCREEN_OFFSET
        shader.uniforms.color        = textColor[axis+2]
        shader.uniforms.angle        = textAngle[axis+2]
        gl.drawArrays(
          gl.TRIANGLES,
          tickOffset[start],
          tickOffset[end] - tickOffset[start])
      }
    }
    if(labelEnable[axis+2] && labelCount) {
      SCREEN_OFFSET[axis^1] += screenScale * pixelRatio * labelPad[axis+2]
      shader.uniforms.dataAxis     = ZERO_2
      shader.uniforms.screenOffset = SCREEN_OFFSET
      shader.uniforms.color        = labelColor[axis+2]
      shader.uniforms.angle        = labelAngle[axis+2]
      gl.drawArrays(
        gl.TRIANGLES,
        labelOffset,
        labelCount)
    }

  }
})()

proto.drawTitle = (function() {
  var DATA_AXIS = [0,0]
  var SCREEN_OFFSET = [0,0]

  return function() {
    var plot        = this.plot
    var shader      = this.shader
    var gl          = plot.gl
    var screenBox   = plot.screenBox
    var titleCenter = plot.titleCenter
    var titleAngle  = plot.titleAngle
    var titleColor  = plot.titleColor
    var pixelRatio  = plot.pixelRatio

    if(!this.titleCount) {
      return
    }

    for(var i=0; i<2; ++i) {
      SCREEN_OFFSET[i] = 2.0 * (titleCenter[i]*pixelRatio - screenBox[i]) /
        (screenBox[2+i] - screenBox[i]) - 1
    }

    shader.bind()
    shader.uniforms.dataAxis      = DATA_AXIS
    shader.uniforms.screenOffset  = SCREEN_OFFSET
    shader.uniforms.angle         = titleAngle
    shader.uniforms.color         = titleColor

    gl.drawArrays(gl.TRIANGLES, this.titleOffset, this.titleCount)
  }
})()

proto.bind = (function() {
  var DATA_SHIFT = [0,0]
  var DATA_SCALE = [0,0]
  var TEXT_SCALE = [0,0]

  return function() {
    var plot      = this.plot
    var shader    = this.shader
    var bounds    = plot._tickBounds
    var dataBox   = plot.dataBox
    var screenBox = plot.screenBox
    var viewBox   = plot.viewBox

    shader.bind()

    //Set up coordinate scaling uniforms
    for(var i=0; i<2; ++i) {

      var lo = bounds[i]
      var hi = bounds[i+2]
      var boundScale = hi - lo
      var dataCenter  = 0.5 * (dataBox[i+2] + dataBox[i])
      var dataWidth   = (dataBox[i+2] - dataBox[i])

      var viewLo = viewBox[i]
      var viewHi = viewBox[i+2]
      var viewScale = viewHi - viewLo
      var screenLo = screenBox[i]
      var screenHi = screenBox[i+2]
      var screenScale = screenHi - screenLo

      DATA_SCALE[i] = 2.0 * boundScale / dataWidth * viewScale / screenScale
      DATA_SHIFT[i] = 2.0 * (lo - dataCenter) / dataWidth * viewScale / screenScale
    }

    TEXT_SCALE[1] = 2.0 * plot.pixelRatio / (screenBox[3] - screenBox[1])
    TEXT_SCALE[0] = TEXT_SCALE[1] * (screenBox[3] - screenBox[1]) / (screenBox[2] - screenBox[0])

    shader.uniforms.dataScale = DATA_SCALE
    shader.uniforms.dataShift = DATA_SHIFT
    shader.uniforms.textScale = TEXT_SCALE

    //Set attributes
    this.vbo.bind()
    shader.attributes.textCoordinate.pointer()
  }
})()

proto.update = function(options) {
  var vertices  = []
  var axesTicks = options.ticks
  var bounds    = options.bounds
  var i, j, k, data, scale, dimension

  for(dimension=0; dimension<2; ++dimension) {
    var offsets = [Math.floor(vertices.length/3)], tickX = [-Infinity]

    //Copy vertices over to buffer
    var ticks = axesTicks[dimension]
    for(i=0; i<ticks.length; ++i) {
      var tick  = ticks[i]
      var x     = tick.x
      var text  = tick.text
      var font  = tick.font || 'sans-serif'
      scale = (tick.fontSize || 12)

      var coordScale = 1.0 / (bounds[dimension+2] - bounds[dimension])
      var coordShift = bounds[dimension]

      var rows = text.split('\n')
      for(var r = 0; r < rows.length; r++) {
        data = getText(font, rows[r]).data
        for (j = 0; j < data.length; j += 2) {
          vertices.push(
              data[j] * scale,
              -data[j + 1] * scale - r * scale * 1.2,
              (x - coordShift) * coordScale)
        }
      }

      offsets.push(Math.floor(vertices.length/3))
      tickX.push(x)
    }

    this.tickOffset[dimension] = offsets
    this.tickX[dimension] = tickX
  }

  //Add labels
  for(dimension=0; dimension<2; ++dimension) {
    this.labelOffset[dimension] = Math.floor(vertices.length/3)

    data  = getText(options.labelFont[dimension], options.labels[dimension], { textAlign: 'center' }).data
    scale = options.labelSize[dimension]
    for(i=0; i<data.length; i+=2) {
      vertices.push(data[i]*scale, -data[i+1]*scale, 0)
    }

    this.labelCount[dimension] =
      Math.floor(vertices.length/3) - this.labelOffset[dimension]
  }

  //Add title
  this.titleOffset = Math.floor(vertices.length/3)
  data = getText(options.titleFont, options.title).data
  scale = options.titleSize
  for(i=0; i<data.length; i+=2) {
    vertices.push(data[i]*scale, -data[i+1]*scale, 0)
  }
  this.titleCount = Math.floor(vertices.length/3) - this.titleOffset

  //Upload new vertices
  this.vbo.update(vertices)
}

proto.dispose = function() {
  this.vbo.dispose()
  this.shader.dispose()
}

function createTextElements(plot) {
  var gl = plot.gl
  var vbo = createBuffer(gl)
  var shader = createShader(gl, shaders.textVert, shaders.textFrag)
  var text = new TextElements(plot, vbo, shader)
  return text
}

},{"./shaders":274,"binary-search-bounds":276,"gl-buffer":231,"gl-shader":290,"text-cache":514}],276:[function(_dereq_,module,exports){
arguments[4][100][0].apply(exports,arguments)
},{"dup":100}],277:[function(_dereq_,module,exports){
'use strict'

module.exports = createGLPlot2D

var createPick = _dereq_('gl-select-static')

var createGrid = _dereq_('./lib/grid')
var createText = _dereq_('./lib/text')
var createLine = _dereq_('./lib/line')
var createBox  = _dereq_('./lib/box')

function GLPlot2D(gl, pickBuffer) {
  this.gl               = gl
  this.pickBuffer       = pickBuffer

  this.screenBox        = [0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight]
  this.viewBox          = [0, 0, 0, 0]
  this.dataBox          = [-10, -10, 10, 10]

  this.gridLineEnable   = [true,true]
  this.gridLineWidth    = [1,1]
  this.gridLineColor    = [[0,0,0,1],
                           [0,0,0,1]]

  this.pixelRatio       = 1

  this.tickMarkLength   = [0,0,0,0]
  this.tickMarkWidth    = [0,0,0,0]
  this.tickMarkColor    = [[0,0,0,1],
                           [0,0,0,1],
                           [0,0,0,1],
                           [0,0,0,1]]

  this.tickPad          = [15,15,15,15]
  this.tickAngle        = [0,0,0,0]
  this.tickEnable       = [true,true,true,true]
  this.tickColor        = [[0,0,0,1],
                           [0,0,0,1],
                           [0,0,0,1],
                           [0,0,0,1]]

  this.labelPad         = [15,15,15,15]
  this.labelAngle       = [0,Math.PI/2,0,3.0*Math.PI/2]
  this.labelEnable      = [true,true,true,true]
  this.labelColor       = [[0,0,0,1],
                           [0,0,0,1],
                           [0,0,0,1],
                           [0,0,0,1]]

  this.titleCenter      = [0,0]
  this.titleEnable      = true
  this.titleAngle       = 0
  this.titleColor       = [0,0,0,1]

  this.borderColor      = [0,0,0,0]
  this.backgroundColor  = [0,0,0,0]

  this.zeroLineEnable   = [true, true]
  this.zeroLineWidth    = [4, 4]
  this.zeroLineColor    = [[0, 0, 0, 1],[0, 0, 0, 1]]

  this.borderLineEnable = [true,true,true,true]
  this.borderLineWidth  = [2,2,2,2]
  this.borderLineColor  = [[0,0,0,1],
                           [0,0,0,1],
                           [0,0,0,1],
                           [0,0,0,1]]

  //Drawing parameters
  this.grid             = null
  this.text             = null
  this.line             = null
  this.box              = null
  this.objects          = []
  this.overlays         = []

  this._tickBounds      = [Infinity, Infinity, -Infinity, -Infinity]

  this.static = false

  this.dirty        = false
  this.pickDirty    = false
  this.pickDelay    = 120
  this.pickRadius   = 10
  this._pickTimeout = null
  this._drawPick    = this.drawPick.bind(this)

  this._depthCounter = 0
}

var proto = GLPlot2D.prototype

proto.setDirty = function() {
  this.dirty = this.pickDirty = true
}

proto.setOverlayDirty = function() {
  this.dirty = true
}

proto.nextDepthValue = function() {
  return (this._depthCounter++) / 65536.0
}

function lerp(a, b, t) {
  var s = 0.5 * (t + 1.0)
  return Math.floor((1.0-s)*a + s*b)|0
}

proto.draw = (function() {
var TICK_MARK_BOX = [0,0,0,0]
return function() {
  var gl         = this.gl
  var screenBox  = this.screenBox
  var viewPixels = this.viewBox
  var dataBox    = this.dataBox
  var pixelRatio = this.pixelRatio
  var grid       = this.grid
  var line       = this.line
  var text       = this.text
  var objects    = this.objects

  this._depthCounter = 0

  if(this.pickDirty) {
    if(this._pickTimeout) {
      clearTimeout(this._pickTimeout)
    }
    this.pickDirty = false
    this._pickTimeout = setTimeout(this._drawPick, this.pickDelay)
  }

  if(!this.dirty) {
    return
  }
  this.dirty = false

  gl.bindFramebuffer(gl.FRAMEBUFFER, null)

  //Turn on scissor
  gl.enable(gl.SCISSOR_TEST)

  //Turn off depth buffer
  gl.disable(gl.DEPTH_TEST)
  gl.depthFunc(gl.LESS)
  gl.depthMask(false)

  //Configure premultiplied alpha blending
  gl.enable(gl.BLEND)
  gl.blendEquation(gl.FUNC_ADD, gl.FUNC_ADD);
  gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);

  //Draw border
  if (this.borderColor) {
    gl.scissor(
      screenBox[0],
      screenBox[1],
      screenBox[2]-screenBox[0],
      screenBox[3]-screenBox[1])
    var borderColor = this.borderColor
    gl.clearColor(
      borderColor[0]*borderColor[3],
      borderColor[1]*borderColor[3],
      borderColor[2]*borderColor[3],
      borderColor[3])
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
  }

  //Draw center pane
  gl.scissor(
    viewPixels[0],
    viewPixels[1],
    viewPixels[2]-viewPixels[0],
    viewPixels[3]-viewPixels[1])
  gl.viewport(
    viewPixels[0],
    viewPixels[1],
    viewPixels[2]-viewPixels[0],
    viewPixels[3]-viewPixels[1])
  var backgroundColor = this.backgroundColor
  gl.clearColor(
    backgroundColor[0]*backgroundColor[3],
    backgroundColor[1]*backgroundColor[3],
    backgroundColor[2]*backgroundColor[3],
    backgroundColor[3])
  gl.clear(gl.COLOR_BUFFER_BIT)

  //Draw grid
  grid.draw()

  //Draw zero lines separately
  var zeroLineEnable = this.zeroLineEnable
  var zeroLineColor  = this.zeroLineColor
  var zeroLineWidth  = this.zeroLineWidth
  if(zeroLineEnable[0] || zeroLineEnable[1]) {
    line.bind()
    for(var i=0; i<2; ++i) {
      if(!zeroLineEnable[i] ||
        !(dataBox[i] <= 0 && dataBox[i+2] >= 0)) {
        continue
      }

      var zeroIntercept = screenBox[i] -
        dataBox[i] * (screenBox[i+2] - screenBox[i]) / (dataBox[i+2] - dataBox[i])

      if(i === 0) {
        line.drawLine(
          zeroIntercept, screenBox[1], zeroIntercept, screenBox[3],
          zeroLineWidth[i],
          zeroLineColor[i])
      } else {
        line.drawLine(
          screenBox[0], zeroIntercept, screenBox[2], zeroIntercept,
          zeroLineWidth[i],
          zeroLineColor[i])
      }
    }
  }

  //Draw traces
  for(var i=0; i<objects.length; ++i) {
    objects[i].draw()
  }

  //Return viewport to default
  gl.viewport(
    screenBox[0],
    screenBox[1],
    screenBox[2]-screenBox[0],
    screenBox[3]-screenBox[1])
  gl.scissor(
    screenBox[0],
    screenBox[1],
    screenBox[2]-screenBox[0],
    screenBox[3]-screenBox[1])

  //Draw tick marks
  this.grid.drawTickMarks()

  //Draw line elements
  line.bind()

  //Draw border lines
  var borderLineEnable = this.borderLineEnable
  var borderLineWidth  = this.borderLineWidth
  var borderLineColor  = this.borderLineColor
  if(borderLineEnable[1]) {
    line.drawLine(
      viewPixels[0], viewPixels[1] - 0.5*borderLineWidth[1]*pixelRatio,
      viewPixels[0], viewPixels[3] + 0.5*borderLineWidth[3]*pixelRatio,
      borderLineWidth[1], borderLineColor[1])
  }
  if(borderLineEnable[0]) {
    line.drawLine(
      viewPixels[0] - 0.5*borderLineWidth[0]*pixelRatio, viewPixels[1],
      viewPixels[2] + 0.5*borderLineWidth[2]*pixelRatio, viewPixels[1],
      borderLineWidth[0], borderLineColor[0])
  }
  if(borderLineEnable[3]) {
    line.drawLine(
      viewPixels[2], viewPixels[1] - 0.5*borderLineWidth[1]*pixelRatio,
      viewPixels[2], viewPixels[3] + 0.5*borderLineWidth[3]*pixelRatio,
      borderLineWidth[3], borderLineColor[3])
  }
  if(borderLineEnable[2]) {
    line.drawLine(
      viewPixels[0] - 0.5*borderLineWidth[0]*pixelRatio, viewPixels[3],
      viewPixels[2] + 0.5*borderLineWidth[2]*pixelRatio, viewPixels[3],
      borderLineWidth[2], borderLineColor[2])
  }

  //Draw text elements
  text.bind()
  for(var i=0; i<2; ++i) {
    text.drawTicks(i)
  }
  if(this.titleEnable) {
    text.drawTitle()
  }

  //Draw other overlay elements (select boxes, etc.)
  var overlays = this.overlays
  for(var i=0; i<overlays.length; ++i) {
    overlays[i].draw()
  }

  //Turn off scissor test
  gl.disable(gl.SCISSOR_TEST)
  gl.disable(gl.BLEND)
  gl.depthMask(true)
}
})()

proto.drawPick = (function() {

return function() {
  if (this.static) return;

  var pickBuffer = this.pickBuffer
  var gl = this.gl

  this._pickTimeout = null
  pickBuffer.begin()

  var pickOffset = 1
  var objects = this.objects
  for(var i=0; i<objects.length; ++i) {
    pickOffset = objects[i].drawPick(pickOffset)
  }

  pickBuffer.end()
}
})()

proto.pick = (function() {
return function(x, y) {
  if (this.static) return;

  var pixelRatio     = this.pixelRatio
  var pickPixelRatio = this.pickPixelRatio
  var viewBox        = this.viewBox

  var scrX = Math.round((x - viewBox[0] / pixelRatio) * pickPixelRatio)|0
  var scrY = Math.round((y - viewBox[1] / pixelRatio) * pickPixelRatio)|0

  var pickResult = this.pickBuffer.query(scrX, scrY, this.pickRadius)
  if(!pickResult) {
    return null
  }

  var pickValue = pickResult.id +
    (pickResult.value[0]<<8)  +
    (pickResult.value[1]<<16) +
    (pickResult.value[2]<<24)

  var objects = this.objects
  for(var i=0; i<objects.length; ++i) {
    var result = objects[i].pick(scrX, scrY, pickValue)
    if(result) {
      return result
    }
  }

  return null
}
})()

function deepClone(array) {
  var result = array.slice()
  for(var i=0; i<result.length; ++i) {
    result[i] = result[i].slice()
  }
  return result
}

function compareTicks(a, b) {
  return a.x - b.x
}

proto.setScreenBox = function(nbox) {
  var screenBox = this.screenBox
  var pixelRatio = this.pixelRatio

  screenBox[0] = Math.round(nbox[0] * pixelRatio) | 0
  screenBox[1] = Math.round(nbox[1] * pixelRatio) | 0
  screenBox[2] = Math.round(nbox[2] * pixelRatio) | 0
  screenBox[3] = Math.round(nbox[3] * pixelRatio) | 0

  this.setDirty()
}

proto.setDataBox = function(nbox) {
  var dataBox = this.dataBox

  var different =
    dataBox[0] !== nbox[0] ||
    dataBox[1] !== nbox[1] ||
    dataBox[2] !== nbox[2] ||
    dataBox[3] !== nbox[3]

  if(different) {
    dataBox[0] = nbox[0]
    dataBox[1] = nbox[1]
    dataBox[2] = nbox[2]
    dataBox[3] = nbox[3]

    this.setDirty()
  }
}

proto.setViewBox = function(nbox) {
  var pixelRatio = this.pixelRatio
  var viewBox = this.viewBox

  viewBox[0] = Math.round(nbox[0] * pixelRatio)|0
  viewBox[1] = Math.round(nbox[1] * pixelRatio)|0
  viewBox[2] = Math.round(nbox[2] * pixelRatio)|0
  viewBox[3] = Math.round(nbox[3] * pixelRatio)|0

  var pickPixelRatio = this.pickPixelRatio
  this.pickBuffer.shape = [
    Math.round((nbox[2] - nbox[0]) * pickPixelRatio)|0,
    Math.round((nbox[3] - nbox[1]) * pickPixelRatio)|0 ]

  this.setDirty()
}

proto.update = function(options) {
  options = options || {}

  var gl = this.gl

  this.pixelRatio      = options.pixelRatio || 1

  var pixelRatio       = this.pixelRatio
  this.pickPixelRatio  = Math.max(pixelRatio, 1)

  this.setScreenBox(options.screenBox ||
    [0, 0, gl.drawingBufferWidth/pixelRatio, gl.drawingBufferHeight/pixelRatio])

  var screenBox = this.screenBox
  this.setViewBox(options.viewBox ||
    [0.125*(this.screenBox[2]-this.screenBox[0])/pixelRatio,
     0.125*(this.screenBox[3]-this.screenBox[1])/pixelRatio,
     0.875*(this.screenBox[2]-this.screenBox[0])/pixelRatio,
     0.875*(this.screenBox[3]-this.screenBox[1])/pixelRatio])

  var viewBox = this.viewBox
  var aspectRatio = (viewBox[2] - viewBox[0]) / (viewBox[3] - viewBox[1])
  this.setDataBox(options.dataBox || [-10, -10/aspectRatio, 10, 10/aspectRatio])

  this.borderColor     = options.borderColor !== false ? (options.borderColor || [0,0,0,0]).slice() : false
  this.backgroundColor = (options.backgroundColor || [0,0,0,0]).slice()

  this.gridLineEnable  = (options.gridLineEnable || [true,true]).slice()
  this.gridLineWidth   = (options.gridLineWidth || [1,1]).slice()
  this.gridLineColor   = deepClone(options.gridLineColor ||
    [[0.5,0.5,0.5,1],[0.5,0.5,0.5,1]])

  this.zeroLineEnable   = (options.zeroLineEnable || [true, true]).slice()
  this.zeroLineWidth    = (options.zeroLineWidth || [4, 4]).slice()
  this.zeroLineColor    = deepClone(options.zeroLineColor ||
    [[0, 0, 0, 1],[0, 0, 0, 1]])

  this.tickMarkLength   = (options.tickMarkLength || [0,0,0,0]).slice()
  this.tickMarkWidth    = (options.tickMarkWidth || [0,0,0,0]).slice()
  this.tickMarkColor    = deepClone(options.tickMarkColor ||
    [[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]])

  this.titleCenter      = (options.titleCenter || [
    0.5*(viewBox[0]+viewBox[2])/pixelRatio,(viewBox[3]+120)/pixelRatio]).slice()
  this.titleEnable      = !('titleEnable' in options) || !!options.titleEnable
  this.titleAngle       = options.titleAngle || 0
  this.titleColor       = (options.titleColor || [0,0,0,1]).slice()

  this.labelPad         = (options.labelPad || [15,15,15,15]).slice()
  this.labelAngle       = (options.labelAngle ||
    [0,Math.PI/2,0,3.0*Math.PI/2]).slice()
  this.labelEnable      = (options.labelEnable || [true,true,true,true]).slice()
  this.labelColor       = deepClone(options.labelColor ||
    [[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]])

  this.tickPad         = (options.tickPad || [15,15,15,15]).slice()
  this.tickAngle       = (options.tickAngle || [0,0,0,0]).slice()
  this.tickEnable      = (options.tickEnable || [true,true,true,true]).slice()
  this.tickColor       = deepClone(options.tickColor ||
    [[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]])

  this.borderLineEnable = (options.borderLineEnable ||
                            [true,true,true,true]).slice()
  this.borderLineWidth  = (options.borderLineWidth || [2,2,2,2]).slice()
  this.borderLineColor  = deepClone(options.borderLineColor ||
                          [[0,0,0,1],
                           [0,0,0,1],
                           [0,0,0,1],
                           [0,0,0,1]])

  var ticks = options.ticks || [ [], [] ]

  //Compute bounds on ticks
  var bounds = this._tickBounds
  bounds[0] = bounds[1] =  Infinity
  bounds[2] = bounds[3] = -Infinity
  for(var i=0; i<2; ++i) {
    var axisTicks = ticks[i].slice(0)
    if(axisTicks.length === 0) {
      continue
    }
    axisTicks.sort(compareTicks)
    bounds[i]   = Math.min(bounds[i], axisTicks[0].x)
    bounds[i+2] = Math.max(bounds[i+2], axisTicks[axisTicks.length-1].x)
  }

  //Update grid
  this.grid.update({
    bounds: bounds,
    ticks:  ticks
  })

  //Update text
  this.text.update({
    bounds:     bounds,
    ticks:      ticks,
    labels:     options.labels    || ['x', 'y'],
    labelSize:  options.labelSize || [12,12],
    labelFont:  options.labelFont || ['sans-serif', 'sans-serif'],
    title:      options.title     || '',
    titleSize:  options.titleSize || 18,
    titleFont:  options.titleFont || 'sans-serif'
  })

  this.static = !!options.static;

  this.setDirty()
}

proto.dispose = function() {
  this.box.dispose()
  this.grid.dispose()
  this.text.dispose()
  this.line.dispose()
  for(var i=this.objects.length-1; i>=0; --i) {
    this.objects[i].dispose()
  }
  this.objects.length = 0
  for(var i=this.overlays.length-1; i>=0; --i) {
    this.overlays[i].dispose()
  }
  this.overlays.length = 0

  this.gl = null
}

proto.addObject = function(object) {
  if(this.objects.indexOf(object) < 0) {
    this.objects.push(object)
    this.setDirty()
  }
}

proto.removeObject = function(object) {
  var objects = this.objects
  for(var i=0; i<objects.length; ++i) {
    if(objects[i] === object) {
      objects.splice(i,1)
      this.setDirty()
      break
    }
  }
}

proto.addOverlay = function(object) {
  if(this.overlays.indexOf(object) < 0) {
    this.overlays.push(object)
    this.setOverlayDirty()
  }
}

proto.removeOverlay = function(object) {
  var objects = this.overlays
  for(var i=0; i<objects.length; ++i) {
    if(objects[i] === object) {
      objects.splice(i,1)
      this.setOverlayDirty()
      break
    }
  }
}

function createGLPlot2D(options) {
  var gl = options.gl
  var pickBuffer = createPick(gl, [
    gl.drawingBufferWidth, gl.drawingBufferHeight])
  var plot = new GLPlot2D(gl, pickBuffer)
  plot.grid = createGrid(plot)
  plot.text = createText(plot)
  plot.line = createLine(plot)
  plot.box  = createBox(plot)
  plot.update(options)
  return plot
}

},{"./lib/box":271,"./lib/grid":272,"./lib/line":273,"./lib/text":275,"gl-select-static":289}],278:[function(_dereq_,module,exports){
var glslify      = _dereq_('glslify')
var createShader = _dereq_('gl-shader')

var vertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\nattribute vec2 position;\nvarying vec2 uv;\nvoid main() {\n  uv = position;\n  gl_Position = vec4(position, 0, 1);\n}"])
var fragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nuniform sampler2D accumBuffer;\nvarying vec2 uv;\n\nvoid main() {\n  vec4 accum = texture2D(accumBuffer, 0.5 * (uv + 1.0));\n  gl_FragColor = min(vec4(1,1,1,1), accum);\n}"])

module.exports = function(gl) {
  return createShader(gl, vertSrc, fragSrc, null, [ { name: 'position', type: 'vec2'}])
}

},{"gl-shader":290,"glslify":395}],279:[function(_dereq_,module,exports){
'use strict'

module.exports = createScene

var createCamera = _dereq_('3d-view-controls')
var createAxes   = _dereq_('gl-axes3d')
var axesRanges   = _dereq_('gl-axes3d/properties')
var createSpikes = _dereq_('gl-spikes3d')
var createSelect = _dereq_('gl-select-static')
var createFBO    = _dereq_('gl-fbo')
var drawTriangle = _dereq_('a-big-triangle')
var mouseChange  = _dereq_('mouse-change')
var perspective  = _dereq_('gl-mat4/perspective')
var createShader = _dereq_('./lib/shader')
var isMobile = _dereq_('is-mobile')({ tablet: true })

function MouseSelect() {
  this.mouse          = [-1,-1]
  this.screen         = null
  this.distance       = Infinity
  this.index          = null
  this.dataCoordinate = null
  this.dataPosition   = null
  this.object         = null
  this.data           = null
}

function getContext(canvas, options) {
  var gl = null
  try {
    gl = canvas.getContext('webgl', options)
    if(!gl) {
      gl = canvas.getContext('experimental-webgl', options)
    }
  } catch(e) {
    return null
  }
  return gl
}

function roundUpPow10(x) {
  var y = Math.round(Math.log(Math.abs(x)) / Math.log(10))
  if(y < 0) {
    var base = Math.round(Math.pow(10, -y))
    return Math.ceil(x*base) / base
  } else if(y > 0) {
    var base = Math.round(Math.pow(10, y))
    return Math.ceil(x/base) * base
  }
  return Math.ceil(x)
}

function defaultBool(x) {
  if(typeof x === 'boolean') {
    return x
  }
  return true
}

function createScene(options) {
  options = options || {}

  var stopped = false

  var pixelRatio = options.pixelRatio || parseFloat(window.devicePixelRatio)

  var canvas = options.canvas
  if(!canvas) {
    canvas = document.createElement('canvas')
    if(options.container) {
      var container = options.container
      container.appendChild(canvas)
    } else {
      document.body.appendChild(canvas)
    }
  }

  var gl = options.gl
  if(!gl) {
    gl = getContext(canvas,
      options.glOptions || {
        premultipliedAlpha: true,
        antialias: true,
        preserveDrawingBuffer: isMobile
      })
  }
  if(!gl) {
    throw new Error('webgl not supported')
  }

  //Initial bounds
  var bounds = options.bounds || [[-10,-10,-10], [10,10,10]]

  //Create selection
  var selection = new MouseSelect()

  //Accumulation buffer
  var accumBuffer = createFBO(gl,
    [gl.drawingBufferWidth, gl.drawingBufferHeight], {
      preferFloat: !isMobile
    })

  var accumShader = createShader(gl)

  //Create a camera
  var cameraOptions = options.camera || {
    eye:    [2,0,0],
    center: [0,0,0],
    up:     [0,1,0],
    zoomMin: 0.1,
    zoomMax: 100,
    mode:    'turntable'
  }

  //Create axes
  var axesOptions = options.axes || {}
  var axes = createAxes(gl, axesOptions)
  axes.enable = !axesOptions.disable

  //Create spikes
  var spikeOptions = options.spikes || {}
  var spikes = createSpikes(gl, spikeOptions)

  //Object list is empty initially
  var objects         = []
  var pickBufferIds   = []
  var pickBufferCount = []
  var pickBuffers     = []

  //Dirty flag, skip redraw if scene static
  var dirty       = true
  var pickDirty   = true

  var projection     = new Array(16)
  var model          = new Array(16)

  var cameraParams = {
    view:         null,
    projection:   projection,
    model:        model
  }

  var pickDirty = true

  var viewShape = [ gl.drawingBufferWidth, gl.drawingBufferHeight ]

  //Create scene object
  var scene = {
    gl:           gl,
    contextLost:  false,
    pixelRatio:   options.pixelRatio || parseFloat(window.devicePixelRatio),
    canvas:       canvas,
    selection:    selection,
    camera:       createCamera(canvas, cameraOptions),
    axes:         axes,
    axesPixels:   null,
    spikes:       spikes,
    bounds:       bounds,
    objects:      objects,
    shape:        viewShape,
    aspect:       options.aspectRatio || [1,1,1],
    pickRadius:   options.pickRadius || 10,
    zNear:        options.zNear || 0.01,
    zFar:         options.zFar  || 1000,
    fovy:         options.fovy  || Math.PI/4,
    clearColor:   options.clearColor || [0,0,0,0],
    autoResize:   defaultBool(options.autoResize),
    autoBounds:   defaultBool(options.autoBounds),
    autoScale:    !!options.autoScale,
    autoCenter:   defaultBool(options.autoCenter),
    clipToBounds: defaultBool(options.clipToBounds),
    snapToData:   !!options.snapToData,
    onselect:     options.onselect || null,
    onrender:     options.onrender || null,
    onclick:      options.onclick  || null,
    cameraParams: cameraParams,
    oncontextloss: null,
    mouseListener: null
  }

  var pickShape = [ (gl.drawingBufferWidth/scene.pixelRatio)|0, (gl.drawingBufferHeight/scene.pixelRatio)|0 ]

  function resizeListener() {
    if(stopped) {
      return
    }
    if(!scene.autoResize) {
      return
    }
    var parent = canvas.parentNode
    var width  = 1
    var height = 1
    if(parent && parent !== document.body) {
      width  = parent.clientWidth
      height = parent.clientHeight
    } else {
      width  = window.innerWidth
      height = window.innerHeight
    }
    var nextWidth  = Math.ceil(width  * scene.pixelRatio)|0
    var nextHeight = Math.ceil(height * scene.pixelRatio)|0
    if(nextWidth !== canvas.width || nextHeight !== canvas.height) {
      canvas.width   = nextWidth
      canvas.height  = nextHeight
      var style = canvas.style
      style.position = style.position || 'absolute'
      style.left     = '0px'
      style.top      = '0px'
      style.width    = width  + 'px'
      style.height   = height + 'px'
      dirty = true
    }
  }
  if(scene.autoResize) {
    resizeListener()
  }
  window.addEventListener('resize', resizeListener)

  function reallocPickIds() {
    var numObjs = objects.length
    var numPick = pickBuffers.length
    for(var i=0; i<numPick; ++i) {
      pickBufferCount[i] = 0
    }
    obj_loop:
    for(var i=0; i<numObjs; ++i) {
      var obj = objects[i]
      var pickCount = obj.pickSlots
      if(!pickCount) {
        pickBufferIds[i] = -1
        continue
      }
      for(var j=0; j<numPick; ++j) {
        if(pickBufferCount[j] + pickCount < 255) {
          pickBufferIds[i] = j
          obj.setPickBase(pickBufferCount[j]+1)
          pickBufferCount[j] += pickCount
          continue obj_loop
        }
      }
      //Create new pick buffer
      var nbuffer = createSelect(gl, viewShape)
      pickBufferIds[i] = numPick
      pickBuffers.push(nbuffer)
      pickBufferCount.push(pickCount)
      obj.setPickBase(1)
      numPick += 1
    }
    while(numPick > 0 && pickBufferCount[numPick-1] === 0) {
      pickBufferCount.pop()
      pickBuffers.pop().dispose()
    }
  }

  scene.update = function(options) {
    if(stopped) {
      return
    }
    options = options || {}
    dirty = true
    pickDirty = true
  }

  scene.add = function(obj) {
    if(stopped) {
      return
    }
    obj.axes = axes
    objects.push(obj)
    pickBufferIds.push(-1)
    dirty = true
    pickDirty = true
    reallocPickIds()
  }

  scene.remove = function(obj) {
    if(stopped) {
      return
    }
    var idx = objects.indexOf(obj)
    if(idx < 0) {
      return
    }
    objects.splice(idx, 1)
    pickBufferIds.pop()
    dirty = true
    pickDirty = true
    reallocPickIds()
  }

  scene.dispose = function() {
    if(stopped) {
      return
    }

    stopped = true

    window.removeEventListener('resize', resizeListener)
    canvas.removeEventListener('webglcontextlost', checkContextLoss)
    scene.mouseListener.enabled = false

    if(scene.contextLost) {
      return
    }

    //Destroy objects
    axes.dispose()
    spikes.dispose()
    for(var i=0; i<objects.length; ++i) {
      objects[i].dispose()
    }

    //Clean up buffers
    accumBuffer.dispose()
    for(var i=0; i<pickBuffers.length; ++i) {
      pickBuffers[i].dispose()
    }

    //Clean up shaders
    accumShader.dispose()

    //Release all references
    gl = null
    axes = null
    spikes = null
    objects = []
  }

  //Update mouse position
  var mouseRotating = false

  var prevButtons = 0

  scene.mouseListener = mouseChange(canvas, function(buttons, x, y) {
    if(stopped) {
      return
    }

    var numPick = pickBuffers.length
    var numObjs = objects.length
    var prevObj = selection.object

    selection.distance = Infinity
    selection.mouse[0] = x
    selection.mouse[1] = y
    selection.object = null
    selection.screen = null
    selection.dataCoordinate = selection.dataPosition = null

    var change = false

    if(buttons && prevButtons) {
      mouseRotating = true
    } else {
      if(mouseRotating) {
        pickDirty = true
      }
      mouseRotating = false

      for(var i=0; i<numPick; ++i) {
        var result = pickBuffers[i].query(x, pickShape[1] - y - 1, scene.pickRadius)
        if(result) {
          if(result.distance > selection.distance) {
            continue
          }
          for(var j=0; j<numObjs; ++j) {
            var obj = objects[j]
            if(pickBufferIds[j] !== i) {
              continue
            }
            var objPick = obj.pick(result)
            if(objPick) {
              selection.buttons        = buttons
              selection.screen         = result.coord
              selection.distance       = result.distance
              selection.object         = obj
              selection.index          = objPick.distance
              selection.dataPosition   = objPick.position
              selection.dataCoordinate = objPick.dataCoordinate
              selection.data           = objPick
              change = true
            }
          }
        }
      }
    }

    if(prevObj && prevObj !== selection.object) {
      if(prevObj.highlight) {
        prevObj.highlight(null)
      }
      dirty = true
    }
    if(selection.object) {
      if(selection.object.highlight) {
        selection.object.highlight(selection.data)
      }
      dirty = true
    }

    change = change || (selection.object !== prevObj)
    if(change && scene.onselect) {
      scene.onselect(selection)
    }

    if((buttons & 1) && !(prevButtons & 1) && scene.onclick) {
      scene.onclick(selection)
    }
    prevButtons = buttons
  })

  function checkContextLoss() {
    if(scene.contextLost) {
      return true
    }
    if(gl.isContextLost()) {
      scene.contextLost = true
      scene.mouseListener.enabled = false
      scene.selection.object = null
      if(scene.oncontextloss) {
        scene.oncontextloss()
      }
    }
  }

  canvas.addEventListener('webglcontextlost', checkContextLoss)

  //Render the scene for mouse picking
  function renderPick() {
    if(checkContextLoss()) {
      return
    }

    gl.colorMask(true, true, true, true)
    gl.depthMask(true)
    gl.disable(gl.BLEND)
    gl.enable(gl.DEPTH_TEST)

    var numObjs = objects.length
    var numPick = pickBuffers.length
    for(var j=0; j<numPick; ++j) {
      var buf = pickBuffers[j]
      buf.shape = pickShape
      buf.begin()
      for(var i=0; i<numObjs; ++i) {
        if(pickBufferIds[i] !== j) {
          continue
        }
        var obj = objects[i]
        if(obj.drawPick) {
          obj.pixelRatio = 1
          obj.drawPick(cameraParams)
        }
      }
      buf.end()
    }
  }

  var nBounds = [
    [ Infinity, Infinity, Infinity],
    [-Infinity,-Infinity,-Infinity]]

  var prevBounds = [nBounds[0].slice(), nBounds[1].slice()]

  function redraw() {
    if(checkContextLoss()) {
      return
    }

    resizeListener()

    //Tick camera
    var cameraMoved = scene.camera.tick()
    cameraParams.view = scene.camera.matrix
    dirty     = dirty || cameraMoved
    pickDirty = pickDirty || cameraMoved

      //Set pixel ratio
    axes.pixelRatio   = scene.pixelRatio
    spikes.pixelRatio = scene.pixelRatio

    //Check if any objects changed, recalculate bounds
    var numObjs = objects.length
    var lo = nBounds[0]
    var hi = nBounds[1]
    lo[0] = lo[1] = lo[2] =  Infinity
    hi[0] = hi[1] = hi[2] = -Infinity
    for(var i=0; i<numObjs; ++i) {
      var obj = objects[i]

      //Set the axes properties for each object
      obj.pixelRatio = scene.pixelRatio
      obj.axes = scene.axes

      dirty = dirty || !!obj.dirty
      pickDirty = pickDirty || !!obj.dirty
      var obb = obj.bounds
      if(obb) {
        var olo = obb[0]
        var ohi = obb[1]
        for(var j=0; j<3; ++j) {
          lo[j] = Math.min(lo[j], olo[j])
          hi[j] = Math.max(hi[j], ohi[j])
        }
      }
    }

    //Recalculate bounds
    var bounds = scene.bounds
    if(scene.autoBounds) {
      for(var j=0; j<3; ++j) {
        if(hi[j] < lo[j]) {
          lo[j] = -1
          hi[j] = 1
        } else {
          if(lo[j] === hi[j]) {
            lo[j] -= 1
            hi[j] += 1
          }
          var padding = 0.05 * (hi[j] - lo[j])
          lo[j] = lo[j] - padding
          hi[j] = hi[j] + padding
        }
        bounds[0][j] = lo[j]
        bounds[1][j] = hi[j]
      }
    }

    var boundsChanged = false
    for(var j=0; j<3; ++j) {
        boundsChanged = boundsChanged ||
            (prevBounds[0][j] !== bounds[0][j])  ||
            (prevBounds[1][j] !== bounds[1][j])
        prevBounds[0][j] = bounds[0][j]
        prevBounds[1][j] = bounds[1][j]
    }

    //Recalculate bounds
    pickDirty = pickDirty || boundsChanged
    dirty = dirty || boundsChanged

    if(!dirty) {
      return
    }

    if(boundsChanged) {
      var tickSpacing = [0,0,0]
      for(var i=0; i<3; ++i) {
        tickSpacing[i] = roundUpPow10((bounds[1][i]-bounds[0][i]) / 10.0)
      }
      if(axes.autoTicks) {
        axes.update({
          bounds: bounds,
          tickSpacing: tickSpacing
        })
      } else {
        axes.update({
          bounds: bounds
        })
      }
    }

    //Get scene
    var width  = gl.drawingBufferWidth
    var height = gl.drawingBufferHeight
    viewShape[0] = width
    viewShape[1] = height
    pickShape[0] = Math.max(width/scene.pixelRatio, 1)|0
    pickShape[1] = Math.max(height/scene.pixelRatio, 1)|0

    //Compute camera parameters
    perspective(projection,
      scene.fovy,
      width/height,
      scene.zNear,
      scene.zFar)

    //Compute model matrix
    for(var i=0; i<16; ++i) {
      model[i] = 0
    }
    model[15] = 1

    var maxS = 0
    for(var i=0; i<3; ++i) {
      maxS = Math.max(maxS, bounds[1][i] - bounds[0][i])
    }

    for(var i=0; i<3; ++i) {
      if(scene.autoScale) {
        model[5*i] = scene.aspect[i] / (bounds[1][i] - bounds[0][i])
      } else {
        model[5*i] = 1  / maxS
      }
      if(scene.autoCenter) {
        model[12+i] = -model[5*i] * 0.5 * (bounds[0][i] + bounds[1][i])
      }
    }

    //Apply axes/clip bounds
    for(var i=0; i<numObjs; ++i) {
      var obj = objects[i]

      //Set axes bounds
      obj.axesBounds = bounds

      //Set clip bounds
      if(scene.clipToBounds) {
        obj.clipBounds = bounds
      }
    }
    //Set spike parameters
    if(selection.object) {
      if(scene.snapToData) {
        spikes.position = selection.dataCoordinate
      } else {
        spikes.position = selection.dataPosition
      }
      spikes.bounds = bounds
    }

    //If state changed, then redraw pick buffers
    if(pickDirty) {
      pickDirty = false
      renderPick()
    }

    //Recalculate pixel data
    scene.axesPixels = axesRanges(scene.axes, cameraParams, width, height)

    //Call render callback
    if(scene.onrender) {
      scene.onrender()
    }

    //Read value
    gl.bindFramebuffer(gl.FRAMEBUFFER, null)
    gl.viewport(0, 0, width, height)

    //General strategy: 3 steps
    //  1. render non-transparent objects
    //  2. accumulate transparent objects into separate fbo
    //  3. composite final scene

    //Clear FBO
    var clearColor = scene.clearColor
    gl.clearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3])
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
    gl.depthMask(true)
    gl.colorMask(true, true, true, true)
    gl.enable(gl.DEPTH_TEST)
    gl.depthFunc(gl.LEQUAL)
    gl.disable(gl.BLEND)
    gl.disable(gl.CULL_FACE)  //most visualization surfaces are 2 sided

    //Render opaque pass
    var hasTransparent = false
    if(axes.enable) {
      hasTransparent = hasTransparent || axes.isTransparent()
      axes.draw(cameraParams)
    }
    spikes.axes = axes
    if(selection.object) {
      spikes.draw(cameraParams)
    }

    gl.disable(gl.CULL_FACE)  //most visualization surfaces are 2 sided

    for(var i=0; i<numObjs; ++i) {
      var obj = objects[i]
      obj.axes = axes
      obj.pixelRatio = scene.pixelRatio
      if(obj.isOpaque && obj.isOpaque()) {
        obj.draw(cameraParams)
      }
      if(obj.isTransparent && obj.isTransparent()) {
        hasTransparent = true
      }
    }

    if(hasTransparent) {
      //Render transparent pass
      accumBuffer.shape = viewShape
      accumBuffer.bind()
      gl.clear(gl.DEPTH_BUFFER_BIT)
      gl.colorMask(false, false, false, false)
      gl.depthMask(true)
      gl.depthFunc(gl.LESS)

      //Render forward facing objects
      if(axes.enable && axes.isTransparent()) {
        axes.drawTransparent(cameraParams)
      }
      for(var i=0; i<numObjs; ++i) {
        var obj = objects[i]
        if(obj.isOpaque && obj.isOpaque()) {
          obj.draw(cameraParams)
        }
      }

      //Render transparent pass
      gl.enable(gl.BLEND)
      gl.blendEquation(gl.FUNC_ADD)
      gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
      gl.colorMask(true, true, true, true)
      gl.depthMask(false)
      gl.clearColor(0,0,0,0)
      gl.clear(gl.COLOR_BUFFER_BIT)

      if(axes.isTransparent()) {
        axes.drawTransparent(cameraParams)
      }

      for(var i=0; i<numObjs; ++i) {
        var obj = objects[i]
        if(obj.isTransparent && obj.isTransparent()) {
          obj.drawTransparent(cameraParams)
        }
      }

      //Unbind framebuffer
      gl.bindFramebuffer(gl.FRAMEBUFFER, null)

      //Draw composite pass
      gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
      gl.disable(gl.DEPTH_TEST)
      accumShader.bind()
      accumBuffer.color[0].bind(0)
      accumShader.uniforms.accumBuffer = 0
      drawTriangle(gl)

      //Turn off blending
      gl.disable(gl.BLEND)
    }

    //Clear dirty flags
    dirty = false
    for(var i=0; i<numObjs; ++i) {
      objects[i].dirty = false
    }
  }


  //Draw the whole scene
  function render() {
    if(stopped || scene.contextLost) {
      return
    }
    // this order is important: ios safari sometimes has sync raf
    redraw()
    requestAnimationFrame(render)
  }
  render()

  //Force redraw of whole scene
  scene.redraw = function() {
    if(stopped) {
      return
    }
    dirty = true
    redraw()
  }

  return scene
}

},{"./lib/shader":278,"3d-view-controls":45,"a-big-triangle":48,"gl-axes3d":223,"gl-axes3d/properties":230,"gl-fbo":240,"gl-mat4/perspective":259,"gl-select-static":289,"gl-spikes3d":299,"is-mobile":406,"mouse-change":421}],280:[function(_dereq_,module,exports){
var glslify = _dereq_('glslify')

exports.pointVertex       = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform float pointCloud;\n\nhighp float rand(vec2 co) {\n  highp float a = 12.9898;\n  highp float b = 78.233;\n  highp float c = 43758.5453;\n  highp float d = dot(co.xy, vec2(a, b));\n  highp float e = mod(d, 3.14);\n  return fract(sin(e) * c);\n}\n\nvoid main() {\n  vec3 hgPosition = matrix * vec3(position, 1);\n  gl_Position  = vec4(hgPosition.xy, 0, hgPosition.z);\n    // if we don't jitter the point size a bit, overall point cloud\n    // saturation 'jumps' on zooming, which is disturbing and confusing\n  gl_PointSize = pointSize * ((19.5 + rand(position)) / 20.0);\n  if(pointCloud != 0.0) { // pointCloud is truthy\n    // get the same square surface as circle would be\n    gl_PointSize *= 0.886;\n  }\n}"])
exports.pointFragment     = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color, borderColor;\nuniform float centerFraction;\nuniform float pointCloud;\n\nvoid main() {\n  float radius;\n  vec4 baseColor;\n  if(pointCloud != 0.0) { // pointCloud is truthy\n    if(centerFraction == 1.0) {\n      gl_FragColor = color;\n    } else {\n      gl_FragColor = mix(borderColor, color, centerFraction);\n    }\n  } else {\n    radius = length(2.0 * gl_PointCoord.xy - 1.0);\n    if(radius > 1.0) {\n      discard;\n    }\n    baseColor = mix(borderColor, color, step(radius, centerFraction));\n    gl_FragColor = vec4(baseColor.rgb * baseColor.a, baseColor.a);\n  }\n}\n"])
exports.pickVertex        = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 pickId;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform vec4 pickOffset;\n\nvarying vec4 fragId;\n\nvoid main() {\n  vec3 hgPosition = matrix * vec3(position, 1);\n  gl_Position  = vec4(hgPosition.xy, 0, hgPosition.z);\n  gl_PointSize = pointSize;\n\n  vec4 id = pickId + pickOffset;\n  id.y += floor(id.x / 256.0);\n  id.x -= floor(id.x / 256.0) * 256.0;\n\n  id.z += floor(id.y / 256.0);\n  id.y -= floor(id.y / 256.0) * 256.0;\n\n  id.w += floor(id.z / 256.0);\n  id.z -= floor(id.z / 256.0) * 256.0;\n\n  fragId = id;\n}\n"])
exports.pickFragment      = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragId;\n\nvoid main() {\n  float radius = length(2.0 * gl_PointCoord.xy - 1.0);\n  if(radius > 1.0) {\n    discard;\n  }\n  gl_FragColor = fragId / 255.0;\n}\n"])

},{"glslify":395}],281:[function(_dereq_,module,exports){
'use strict'

var createShader = _dereq_('gl-shader')
var createBuffer = _dereq_('gl-buffer')

var pool = _dereq_('typedarray-pool')

var SHADERS = _dereq_('./lib/shader')

module.exports = createPointcloud2D

function Pointcloud2D(plot, offsetBuffer, pickBuffer, shader, pickShader) {
  this.plot           = plot
  this.offsetBuffer   = offsetBuffer
  this.pickBuffer     = pickBuffer
  this.shader         = shader
  this.pickShader     = pickShader
  this.sizeMin        = 0.5
  this.sizeMinCap     = 2
  this.sizeMax        = 20
  this.areaRatio      = 1.0
  this.pointCount     = 0
  this.color          = [1, 0, 0, 1]
  this.borderColor    = [0, 0, 0, 1]
  this.blend          = false
  this.pickOffset     = 0
  this.points         = null
}

var proto = Pointcloud2D.prototype

proto.dispose = function() {
  this.shader.dispose()
  this.pickShader.dispose()
  this.offsetBuffer.dispose()
  this.pickBuffer.dispose()
  this.plot.removeObject(this)
}

proto.update = function(options) {

  var i

  options = options || {}

  function dflt(opt, value) {
    if(opt in options) {
      return options[opt]
    }
    return value
  }

  this.sizeMin      = dflt('sizeMin', 0.5)
  // this.sizeMinCap      = dflt('sizeMinCap', 2)
  this.sizeMax      = dflt('sizeMax', 20)
  this.color        = dflt('color', [1, 0, 0, 1]).slice()
  this.areaRatio    = dflt('areaRatio', 1)
  this.borderColor  = dflt('borderColor', [0, 0, 0, 1]).slice()
  this.blend        = dflt('blend', false)

  //Update point data

  // Attempt straight-through processing (STP) to avoid allocation and copy
  // TODO eventually abstract out STP logic, maybe into `pool` or a layer above
  var pointCount = options.positions.length >>> 1
  var dataStraightThrough = options.positions instanceof Float32Array
  var idStraightThrough = options.idToIndex instanceof Int32Array && options.idToIndex.length >= pointCount // permit larger to help reuse

  var data          = options.positions
  var packed        = dataStraightThrough ? data : pool.mallocFloat32(data.length)
  var packedId      = idStraightThrough ? options.idToIndex : pool.mallocInt32(pointCount)

  if(!dataStraightThrough) {
    packed.set(data)
  }

  if(!idStraightThrough) {
    packed.set(data)
    for(i = 0; i < pointCount; i++) {
      packedId[i] = i
    }
  }

  this.points       = data

  this.offsetBuffer.update(packed)
  this.pickBuffer.update(packedId)

  if(!dataStraightThrough) {
    pool.free(packed)
  }

  if(!idStraightThrough) {
    pool.free(packedId)
  }

  this.pointCount = pointCount
  this.pickOffset = 0
}

function count(points, dataBox) {
  var visiblePointCountEstimate = 0
  var length = points.length >>> 1
  var i
  for(i = 0; i < length; i++) {
    var x = points[i * 2]
    var y = points[i * 2 + 1]
    if(x >= dataBox[0] && x <= dataBox[2] && y >= dataBox[1] && y <= dataBox[3])
      visiblePointCountEstimate++
  }
  return visiblePointCountEstimate
}

proto.unifiedDraw = (function() {
  var MATRIX = [1, 0, 0,
                0, 1, 0,
                0, 0, 1]
  var PICK_VEC4 = [0, 0, 0, 0]
return function(pickOffset) {
  var pick = pickOffset !== void(0)

  var shader        = pick ? this.pickShader : this.shader
  var gl            = this.plot.gl
  var dataBox       = this.plot.dataBox

  if(this.pointCount === 0) {
    return pickOffset
  }

  var dataX   = dataBox[2] - dataBox[0]
  var dataY   = dataBox[3] - dataBox[1]

  var visiblePointCountEstimate = count(this.points, dataBox)
  var basicPointSize =  this.plot.pickPixelRatio * Math.max(Math.min(this.sizeMinCap, this.sizeMin), Math.min(this.sizeMax, this.sizeMax / Math.pow(visiblePointCountEstimate, 0.33333)))

  MATRIX[0] = 2.0 / dataX
  MATRIX[4] = 2.0 / dataY
  MATRIX[6] = -2.0 * dataBox[0] / dataX - 1.0
  MATRIX[7] = -2.0 * dataBox[1] / dataY - 1.0

  this.offsetBuffer.bind()

  shader.bind()
  shader.attributes.position.pointer()
  shader.uniforms.matrix      = MATRIX
  shader.uniforms.color       = this.color
  shader.uniforms.borderColor = this.borderColor
  shader.uniforms.pointCloud = basicPointSize < 5
  shader.uniforms.pointSize = basicPointSize
  shader.uniforms.centerFraction = Math.min(1, Math.max(0, Math.sqrt(1 - this.areaRatio)))

  if(pick) {

    PICK_VEC4[0] = ( pickOffset        & 0xff)
    PICK_VEC4[1] = ((pickOffset >> 8)  & 0xff)
    PICK_VEC4[2] = ((pickOffset >> 16) & 0xff)
    PICK_VEC4[3] = ((pickOffset >> 24) & 0xff)

    this.pickBuffer.bind()
    shader.attributes.pickId.pointer(gl.UNSIGNED_BYTE)
    shader.uniforms.pickOffset = PICK_VEC4
    this.pickOffset = pickOffset
  }

  // Worth switching these off, but we can't make assumptions about other
  // renderers, so let's restore it after each draw
  var blend = gl.getParameter(gl.BLEND)
  var dither = gl.getParameter(gl.DITHER)

  if(blend && !this.blend)
    gl.disable(gl.BLEND)
  if(dither)
    gl.disable(gl.DITHER)

  gl.drawArrays(gl.POINTS, 0, this.pointCount)

  if(blend && !this.blend)
    gl.enable(gl.BLEND)
  if(dither)
    gl.enable(gl.DITHER)

  return pickOffset + this.pointCount
}
})()

proto.draw = proto.unifiedDraw
proto.drawPick = proto.unifiedDraw

proto.pick = function(x, y, value) {
  var pickOffset = this.pickOffset
  var pointCount = this.pointCount
  if(value < pickOffset || value >= pickOffset + pointCount) {
    return null
  }
  var pointId = value - pickOffset
  var points = this.points
  return {
    object: this,
    pointId: pointId,
    dataCoord: [points[2 * pointId], points[2 * pointId + 1] ]
  }
}

function createPointcloud2D(plot, options) {
  var gl = plot.gl
  var buffer = createBuffer(gl)
  var pickBuffer = createBuffer(gl)
  var shader = createShader(gl, SHADERS.pointVertex, SHADERS.pointFragment)
  var pickShader = createShader(gl, SHADERS.pickVertex, SHADERS.pickFragment)

  var result = new Pointcloud2D(plot, buffer, pickBuffer, shader, pickShader)
  result.update(options)

  //Register with plot
  plot.addObject(result)

  return result
}

},{"./lib/shader":280,"gl-buffer":231,"gl-shader":290,"typedarray-pool":523}],282:[function(_dereq_,module,exports){
module.exports = slerp

/**
 * Performs a spherical linear interpolation between two quat
 *
 * @param {quat} out the receiving quaternion
 * @param {quat} a the first operand
 * @param {quat} b the second operand
 * @param {Number} t interpolation amount between the two inputs
 * @returns {quat} out
 */
function slerp (out, a, b, t) {
  // benchmarks:
  //    http://jsperf.com/quaternion-slerp-implementations

  var ax = a[0], ay = a[1], az = a[2], aw = a[3],
    bx = b[0], by = b[1], bz = b[2], bw = b[3]

  var omega, cosom, sinom, scale0, scale1

  // calc cosine
  cosom = ax * bx + ay * by + az * bz + aw * bw
  // adjust signs (if necessary)
  if (cosom < 0.0) {
    cosom = -cosom
    bx = -bx
    by = -by
    bz = -bz
    bw = -bw
  }
  // calculate coefficients
  if ((1.0 - cosom) > 0.000001) {
    // standard case (slerp)
    omega = Math.acos(cosom)
    sinom = Math.sin(omega)
    scale0 = Math.sin((1.0 - t) * omega) / sinom
    scale1 = Math.sin(t * omega) / sinom
  } else {
    // "from" and "to" quaternions are very close
    //  ... so we can do a linear interpolation
    scale0 = 1.0 - t
    scale1 = t
  }
  // calculate final values
  out[0] = scale0 * ax + scale1 * bx
  out[1] = scale0 * ay + scale1 * by
  out[2] = scale0 * az + scale1 * bz
  out[3] = scale0 * aw + scale1 * bw

  return out
}

},{}],283:[function(_dereq_,module,exports){
'use strict';

module.exports = function(a){
  return (!a && a !== 0) ? '' : a.toString();
}

},{}],284:[function(_dereq_,module,exports){
"use strict"

var vectorizeText = _dereq_("vectorize-text")

module.exports = getGlyph

var GLYPH_CACHE = {}

function getGlyph(symbol, font) {
  var fontCache = GLYPH_CACHE[font]
  if(!fontCache) {
    fontCache = GLYPH_CACHE[font] = {}
  }
  if(symbol in fontCache) {
    return fontCache[symbol]
  }

  var config = {
    textAlign: "center",
    textBaseline: "middle",
    lineHeight: 1.0,
    font: font,
    lineSpacing: 1.25,
    styletags: {
      breaklines:true,
      bolds: true,
      italics: true,
      subscripts:true,
      superscripts:true
    }
  }

  //Get line and triangle meshes for glyph
  config.triangles = true;
  var triSymbol = vectorizeText(symbol, config)
  config.triangles = false;
  var lineSymbol = vectorizeText(symbol, config)

  //Calculate bounding box
  var bounds = [[Infinity,Infinity], [-Infinity,-Infinity]]
  var n = lineSymbol.positions.length
  for(var i = 0; i < n; ++i) {
    var p = lineSymbol.positions[i]
    for(var j=0; j<2; ++j) {
      bounds[0][j] = Math.min(bounds[0][j], p[j])
      bounds[1][j] = Math.max(bounds[1][j], p[j])
    }
  }

  //Save cached symbol
  return fontCache[symbol] = [triSymbol, lineSymbol, bounds]
}
},{"vectorize-text":528}],285:[function(_dereq_,module,exports){
var createShaderWrapper = _dereq_('gl-shader')
var glslify = _dereq_('glslify')

var perspectiveVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform vec4 highlightId;\nuniform float highlightScale;\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    float scale = 1.0;\n    if(distance(highlightId, id) < 0.0001) {\n      scale = highlightScale;\n    }\n\n    vec4 worldPosition = model * vec4(position, 1);\n    vec4 viewPosition = view * worldPosition;\n    viewPosition = viewPosition / viewPosition.w;\n    vec4 clipPosition = projection * (viewPosition + scale * vec4(glyph.x, -glyph.y, 0, 0));\n\n    gl_Position = clipPosition;\n    interpColor = color;\n    pickId = id;\n    dataCoordinate = position;\n  }\n}"])
var orthographicVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float highlightScale, pixelRatio;\nuniform vec4 highlightId;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    float scale = pixelRatio;\n    if(distance(highlightId.bgr, id.bgr) < 0.001) {\n      scale *= highlightScale;\n    }\n\n    vec4 worldPosition = model * vec4(position, 1.0);\n    vec4 viewPosition = view * worldPosition;\n    vec4 clipPosition = projection * viewPosition;\n    clipPosition /= clipPosition.w;\n\n    gl_Position = clipPosition + vec4(screenSize * scale * vec2(glyph.x, -glyph.y), 0.0, 0.0);\n    interpColor = color;\n    pickId = id;\n    dataCoordinate = position;\n  }\n}"])
var projectionVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform float highlightScale;\nuniform vec4 highlightId;\nuniform vec3 axes[2];\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float scale, pixelRatio;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    float lscale = pixelRatio * scale;\n    if(distance(highlightId, id) < 0.0001) {\n      lscale *= highlightScale;\n    }\n\n    vec4 clipCenter   = projection * view * model * vec4(position, 1);\n    vec3 dataPosition = position + 0.5*lscale*(axes[0] * glyph.x + axes[1] * glyph.y) * clipCenter.w * screenSize.y;\n    vec4 clipPosition = projection * view * model * vec4(dataPosition, 1);\n\n    gl_Position = clipPosition;\n    interpColor = color;\n    pickId = id;\n    dataCoordinate = dataPosition;\n  }\n}\n"])
var drawFragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 fragClipBounds[2];\nuniform float opacity;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if (\n    outOfRange(fragClipBounds[0], fragClipBounds[1], dataCoordinate) ||\n    interpColor.a * opacity == 0.\n  ) discard;\n  gl_FragColor = interpColor * opacity;\n}\n"])
var pickFragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 fragClipBounds[2];\nuniform float pickGroup;\n\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if (outOfRange(fragClipBounds[0], fragClipBounds[1], dataCoordinate)) discard;\n\n  gl_FragColor = vec4(pickGroup, pickId.bgr);\n}"])

var ATTRIBUTES = [
  {name: 'position', type: 'vec3'},
  {name: 'color', type: 'vec4'},
  {name: 'glyph', type: 'vec2'},
  {name: 'id', type: 'vec4'}
]

var perspective = {
    vertex: perspectiveVertSrc,
    fragment: drawFragSrc,
    attributes: ATTRIBUTES
  },
  ortho = {
    vertex: orthographicVertSrc,
    fragment: drawFragSrc,
    attributes: ATTRIBUTES
  },
  project = {
    vertex: projectionVertSrc,
    fragment: drawFragSrc,
    attributes: ATTRIBUTES
  },
  pickPerspective = {
    vertex: perspectiveVertSrc,
    fragment: pickFragSrc,
    attributes: ATTRIBUTES
  },
  pickOrtho = {
    vertex: orthographicVertSrc,
    fragment: pickFragSrc,
    attributes: ATTRIBUTES
  },
  pickProject = {
    vertex: projectionVertSrc,
    fragment: pickFragSrc,
    attributes: ATTRIBUTES
  }

function createShader(gl, src) {
  var shader = createShaderWrapper(gl, src)
  var attr = shader.attributes
  attr.position.location = 0
  attr.color.location = 1
  attr.glyph.location = 2
  attr.id.location = 3
  return shader
}

exports.createPerspective = function(gl) {
  return createShader(gl, perspective)
}
exports.createOrtho = function(gl) {
  return createShader(gl, ortho)
}
exports.createProject = function(gl) {
  return createShader(gl, project)
}
exports.createPickPerspective = function(gl) {
  return createShader(gl, pickPerspective)
}
exports.createPickOrtho = function(gl) {
  return createShader(gl, pickOrtho)
}
exports.createPickProject = function(gl) {
  return createShader(gl, pickProject)
}

},{"gl-shader":290,"glslify":395}],286:[function(_dereq_,module,exports){
'use strict'

var isAllBlank      = _dereq_('is-string-blank')
var createBuffer    = _dereq_('gl-buffer')
var createVAO       = _dereq_('gl-vao')
var pool            = _dereq_('typedarray-pool')
var mat4mult        = _dereq_('gl-mat4/multiply')
var shaders         = _dereq_('./lib/shaders')
var getGlyph        = _dereq_('./lib/glyphs')
var getSimpleString = _dereq_('./lib/get-simple-string')

var IDENTITY = [1,0,0,0,
                0,1,0,0,
                0,0,1,0,
                0,0,0,1]

module.exports = createPointCloud

function transformMat4(x, m) {
  var x0 = x[0]
  var x1 = x[1]
  var x2 = x[2]
  var x3 = x[3]
  x[0] = m[0] * x0 + m[4] * x1 + m[8]  * x2 + m[12] * x3
  x[1] = m[1] * x0 + m[5] * x1 + m[9]  * x2 + m[13] * x3
  x[2] = m[2] * x0 + m[6] * x1 + m[10] * x2 + m[14] * x3
  x[3] = m[3] * x0 + m[7] * x1 + m[11] * x2 + m[15] * x3
  return x
}

function project(p, v, m, x) {
  transformMat4(x, x, m)
  transformMat4(x, x, v)
  return transformMat4(x, x, p)
}

function ScatterPlotPickResult(index, position) {
  this.index = index
  this.dataCoordinate = this.position = position
}

function fixOpacity(a) {
  if(a === true) return 1
  if(a > 1) return 1
  return a
}

function PointCloud(
  gl,
  shader,
  orthoShader,
  projectShader,
  pointBuffer,
  colorBuffer,
  glyphBuffer,
  idBuffer,
  vao,
  pickPerspectiveShader,
  pickOrthoShader,
  pickProjectShader) {

  this.gl              = gl

  this.pixelRatio      = 1

  this.shader          = shader
  this.orthoShader     = orthoShader
  this.projectShader   = projectShader

  this.pointBuffer     = pointBuffer
  this.colorBuffer     = colorBuffer
  this.glyphBuffer     = glyphBuffer
  this.idBuffer        = idBuffer
  this.vao             = vao
  this.vertexCount     = 0
  this.lineVertexCount = 0

  this.opacity         = 1
  this.hasAlpha        = false

  this.lineWidth       = 0
  this.projectScale    = [2.0/3.0, 2.0/3.0, 2.0/3.0]
  this.projectOpacity  = [1, 1, 1]
  this.projectHasAlpha  = false

  this.pickId                = 0
  this.pickPerspectiveShader = pickPerspectiveShader
  this.pickOrthoShader       = pickOrthoShader
  this.pickProjectShader     = pickProjectShader
  this.points                = []

  this._selectResult = new ScatterPlotPickResult(0, [0,0,0])

  this.useOrtho = true
  this.bounds   = [[ Infinity,Infinity,Infinity],
                   [-Infinity,-Infinity,-Infinity]]

  //Axes projections
  this.axesProject = [ true, true, true ]
  this.axesBounds = [[-Infinity,-Infinity,-Infinity],
                     [ Infinity, Infinity, Infinity]]

  this.highlightId    = [1,1,1,1]
  this.highlightScale = 2

  this.clipBounds = [[-Infinity,-Infinity,-Infinity],
                     [ Infinity, Infinity, Infinity]]

  this.dirty = true
}

var proto = PointCloud.prototype

proto.pickSlots = 1

proto.setPickBase = function(pickBase) {
  this.pickId = pickBase
}

proto.isTransparent = function() {
  if(this.hasAlpha)  {
    return true
  }
  for(var i=0; i<3; ++i) {
    if(this.axesProject[i] && this.projectHasAlpha) {
      return true
    }
  }
  return false
}

proto.isOpaque = function() {
  if(!this.hasAlpha)  {
    return true
  }
  for(var i=0; i<3; ++i) {
    if(this.axesProject[i] && !this.projectHasAlpha) {
      return true
    }
  }
  return false
}

var VIEW_SHAPE = [0,0]
var U_VEC = [0,0,0]
var V_VEC = [0,0,0]
var MU_VEC = [0,0,0,1]
var MV_VEC = [0,0,0,1]
var SCRATCH_MATRIX = IDENTITY.slice()
var SCRATCH_VEC = [0,0,0]
var CLIP_BOUNDS = [[0,0,0], [0,0,0]]

function zeroVec(a) {
  a[0] = a[1] = a[2] = 0
  return a
}

function augment(hg, af) {
  hg[0] = af[0]
  hg[1] = af[1]
  hg[2] = af[2]
  hg[3] = 1
  return hg
}

function setComponent(out, v, i, x) {
  out[0] = v[0]
  out[1] = v[1]
  out[2] = v[2]
  out[i] = x
  return out
}

function getClipBounds(bounds) {
  var result = CLIP_BOUNDS
  for(var i=0; i<2; ++i) {
    for(var j=0; j<3; ++j) {
      result[i][j] = Math.max(Math.min(bounds[i][j], 1e8), -1e8)
    }
  }
  return result
}

function drawProject(shader, points, camera) {
  var axesProject = points.axesProject

  var gl         = points.gl
  var uniforms   = shader.uniforms
  var model      = camera.model      || IDENTITY
  var view       = camera.view       || IDENTITY
  var projection = camera.projection || IDENTITY
  var bounds     = points.axesBounds
  var clipBounds = getClipBounds(points.clipBounds)

  var cubeAxis
  if(points.axes && points.axes.lastCubeProps) {
    cubeAxis = points.axes.lastCubeProps.axis
  } else {
    cubeAxis = [1,1,1]
  }

  VIEW_SHAPE[0] = 2.0/gl.drawingBufferWidth
  VIEW_SHAPE[1] = 2.0/gl.drawingBufferHeight

  shader.bind()
  uniforms.view           = view
  uniforms.projection     = projection
  uniforms.screenSize     = VIEW_SHAPE
  uniforms.highlightId    = points.highlightId
  uniforms.highlightScale = points.highlightScale
  uniforms.clipBounds     = clipBounds
  uniforms.pickGroup      = points.pickId / 255.0
  uniforms.pixelRatio     = points.pixelRatio

  for(var i=0; i<3; ++i) {
    if(!axesProject[i]) {
      continue
    }

    uniforms.scale          = points.projectScale[i]
    uniforms.opacity        = points.projectOpacity[i]

    //Project model matrix
    var pmodel = SCRATCH_MATRIX
    for(var j=0; j<16; ++j) {
      pmodel[j] = 0
    }
    for(var j=0; j<4; ++j) {
      pmodel[5*j] = 1
    }
    pmodel[5*i] = 0
    if(cubeAxis[i] < 0) {
      pmodel[12+i] = bounds[0][i]
    } else {
      pmodel[12+i] = bounds[1][i]
    }
    mat4mult(pmodel, model, pmodel)
    uniforms.model = pmodel

    //Compute initial axes
    var u = (i+1)%3
    var v = (i+2)%3
    var du = zeroVec(U_VEC)
    var dv = zeroVec(V_VEC)
    du[u] = 1
    dv[v] = 1

    //Align orientation relative to viewer
    var mdu = project(projection, view, model, augment(MU_VEC, du))
    var mdv = project(projection, view, model, augment(MV_VEC, dv))
    if(Math.abs(mdu[1]) > Math.abs(mdv[1])) {
      var tmp = mdu
      mdu = mdv
      mdv = tmp
      tmp = du
      du = dv
      dv = tmp
      var t = u
      u = v
      v = t
    }
    if(mdu[0] < 0) {
      du[u] = -1
    }
    if(mdv[1] > 0) {
      dv[v] = -1
    }
    var su = 0.0
    var sv = 0.0
    for(var j=0; j<4; ++j) {
      su += Math.pow(model[4*u+j], 2)
      sv += Math.pow(model[4*v+j], 2)
    }
    du[u] /= Math.sqrt(su)
    dv[v] /= Math.sqrt(sv)
    uniforms.axes[0] = du
    uniforms.axes[1] = dv

    //Update fragment clip bounds
    uniforms.fragClipBounds[0] = setComponent(SCRATCH_VEC, clipBounds[0], i, -1e8)
    uniforms.fragClipBounds[1] = setComponent(SCRATCH_VEC, clipBounds[1], i, 1e8)

    points.vao.bind()

    //Draw interior
    points.vao.draw(gl.TRIANGLES, points.vertexCount)

    //Draw edges
    if(points.lineWidth > 0) {
      gl.lineWidth(points.lineWidth)
      points.vao.draw(gl.LINES, points.lineVertexCount, points.vertexCount)
    }

    points.vao.unbind()
  }
}


var NEG_INFINITY3 = [-1e8, -1e8, -1e8]
var POS_INFINITY3 = [1e8, 1e8, 1e8]
var CLIP_GROUP    = [NEG_INFINITY3, POS_INFINITY3]

function drawFull(shader, pshader, points, camera, transparent, forceDraw) {
  var gl = points.gl

  if(transparent === points.projectHasAlpha || forceDraw) {
    drawProject(pshader, points, camera)
  }

  if(transparent === points.hasAlpha || forceDraw) {

    shader.bind()
    var uniforms = shader.uniforms

    uniforms.model      = camera.model      || IDENTITY
    uniforms.view       = camera.view       || IDENTITY
    uniforms.projection = camera.projection || IDENTITY

    VIEW_SHAPE[0]       = 2.0/gl.drawingBufferWidth
    VIEW_SHAPE[1]       = 2.0/gl.drawingBufferHeight
    uniforms.screenSize = VIEW_SHAPE

    uniforms.highlightId    = points.highlightId
    uniforms.highlightScale = points.highlightScale

    uniforms.fragClipBounds = CLIP_GROUP
    uniforms.clipBounds     = points.axes.bounds

    uniforms.opacity    = points.opacity
    uniforms.pickGroup  = points.pickId / 255.0

    uniforms.pixelRatio = points.pixelRatio

    points.vao.bind()

    //Draw interior
    points.vao.draw(gl.TRIANGLES, points.vertexCount)

    //Draw edges
    if(points.lineWidth > 0) {
      gl.lineWidth(points.lineWidth)
      points.vao.draw(gl.LINES, points.lineVertexCount, points.vertexCount)
    }

    points.vao.unbind()
  }


}

proto.draw = function(camera) {
  var shader = this.useOrtho ? this.orthoShader : this.shader
  drawFull(shader, this.projectShader, this, camera, false, false)
}

proto.drawTransparent = function(camera) {
  var shader = this.useOrtho ? this.orthoShader : this.shader
  drawFull(shader, this.projectShader, this, camera, true, false)
}

proto.drawPick = function(camera) {
  var shader = this.useOrtho ? this.pickOrthoShader : this.pickPerspectiveShader
  drawFull(shader, this.pickProjectShader, this, camera, true, true)
}

proto.pick = function(selected) {
  if(!selected) {
    return null
  }
  if(selected.id !== this.pickId) {
    return null
  }
  var x = selected.value[2] + (selected.value[1]<<8) + (selected.value[0]<<16)
  if(x >= this.pointCount || x < 0) {
    return null
  }

  //Unpack result
  var coord = this.points[x]
  var result = this._selectResult
  result.index = x
  for(var i=0; i<3; ++i) {
    result.position[i] = result.dataCoordinate[i] = coord[i]
  }
  return result
}

proto.highlight = function(selection) {
  if(!selection) {
    this.highlightId = [1,1,1,1]
  } else {
    var pointId = selection.index
    var a0 =  pointId     &0xff
    var a1 = (pointId>>8) &0xff
    var a2 = (pointId>>16)&0xff
    this.highlightId = [a0/255.0, a1/255.0, a2/255.0, 0]
  }
}

function get_glyphData(glyphs, index, font) {
  var str

  // use the data if presented in an array
  if(Array.isArray(glyphs)) {
    if(index < glyphs.length) {
      str = glyphs[index]
    } else {
      str = undefined
    }
  } else {
    str = glyphs
  }

  str = getSimpleString(str) // this would handle undefined cases

  var visible = true
  if(isAllBlank(str)) {
    str = '▼' // Note: this special character may have minimum number of surfaces
    visible = false
  }

  var glyph = getGlyph(str, font)

  return { mesh:glyph[0],
          lines:glyph[1],
         bounds:glyph[2],
        visible:visible };
}



proto.update = function(options) {

  options = options || {}

  if('perspective' in options) {
    this.useOrtho = !options.perspective
  }
  if('orthographic' in options) {
    this.useOrtho = !!options.orthographic
  }
  if('lineWidth' in options) {
    this.lineWidth = options.lineWidth
  }
  if('project' in options) {
    if(Array.isArray(options.project)) {
      this.axesProject = options.project
    } else {
      var v = !!options.project
      this.axesProject = [v,v,v]
    }
  }
  if('projectScale' in options) {
    if(Array.isArray(options.projectScale)) {
      this.projectScale = options.projectScale.slice()
    } else {
      var s = +options.projectScale
      this.projectScale = [s,s,s]
    }
  }

  this.projectHasAlpha = false // default to no transparent draw
  if('projectOpacity' in options) {
    if(Array.isArray(options.projectOpacity)) {
      this.projectOpacity = options.projectOpacity.slice()
    } else {
      var s = +options.projectOpacity
      this.projectOpacity = [s,s,s]
    }
    for(var i=0; i<3; ++i) {
      this.projectOpacity[i] = fixOpacity(this.projectOpacity[i]);
      if(this.projectOpacity[i] < 1) {
        this.projectHasAlpha = true;
      }
    }
  }

  this.hasAlpha = false // default to no transparent draw
  if('opacity' in options) {
    this.opacity = fixOpacity(options.opacity)
    if(this.opacity < 1) {
      this.hasAlpha = true;
    }
  }

  //Set dirty flag
  this.dirty = true

  //Create new buffers
  var points = options.position

  //Text font
  var font      = options.font      || 'normal'
  var alignment = options.alignment || [0,0]

  var alignmentX;
  var alignmentY;
  if (alignment.length === 2) {
    alignmentX = alignment[0]
    alignmentY = alignment[1]
  } else {
    alignmentX = []
    alignmentY = []
    for (var i = 0; i < alignment.length; ++i) {
      alignmentX[i] = alignment[i][0]
      alignmentY[i] = alignment[i][1]
    }
  }

  //Bounds
  var lowerBound = [ Infinity, Infinity, Infinity]
  var upperBound = [-Infinity,-Infinity,-Infinity]

  //Unpack options
  var glyphs     = options.glyph
  var colors     = options.color
  var sizes      = options.size
  var angles     = options.angle
  var lineColors = options.lineColor

  //Picking geometry
  var pickCounter = -1

  //First do pass to compute buffer sizes
  var triVertexCount  = 0
  var lineVertexCount = 0

  var numPoints = 0;

  if(points.length) {

    //Count number of points and buffer size
    numPoints = points.length

  count_loop:
    for(var i=0; i<numPoints; ++i) {
      var x = points[i]
      for(var j=0; j<3; ++j) {
        if(isNaN(x[j]) || !isFinite(x[j])) {
          continue count_loop
        }
      }

      var glyphData = get_glyphData(glyphs, i, font)

      var glyphMesh   = glyphData.mesh
      var glyphLines  = glyphData.lines
      var glyphBounds = glyphData.bounds

      triVertexCount  += glyphMesh.cells.length * 3
      lineVertexCount += glyphLines.edges.length * 2
    }
  }

  var vertexCount   = triVertexCount + lineVertexCount

  //Preallocate data
  var positionArray = pool.mallocFloat(3*vertexCount)
  var colorArray    = pool.mallocFloat(4*vertexCount)
  var glyphArray    = pool.mallocFloat(2*vertexCount)
  var idArray       = pool.mallocUint32(vertexCount)

  if(vertexCount > 0) {
    var triOffset  = 0
    var lineOffset = triVertexCount
    var color      = [0,0,0,1]
    var lineColor  = [0,0,0,1]

    var isColorArray      = Array.isArray(colors)     && Array.isArray(colors[0])
    var isLineColorArray  = Array.isArray(lineColors) && Array.isArray(lineColors[0])

  fill_loop:
    for(var i=0; i<numPoints; ++i) {
      //Increment pickCounter
      pickCounter += 1

      var x = points[i]
      for(var j=0; j<3; ++j) {
        if(isNaN(x[j]) || !isFinite(x[j])) {
          continue fill_loop
        }

        upperBound[j] = Math.max(upperBound[j], x[j])
        lowerBound[j] = Math.min(lowerBound[j], x[j])
      }

      var glyphData = get_glyphData(glyphs, i, font)

      var glyphMesh   = glyphData.mesh
      var glyphLines  = glyphData.lines
      var glyphBounds = glyphData.bounds
      var glyphVisible = glyphData.visible

      //Get color
      if(!glyphVisible) color = [1,1,1,0]
      else if(Array.isArray(colors)) {
        var c
        if(isColorArray) {
          if(i < colors.length) {
            c = colors[i]
          } else {
            c = [0,0,0,0]
          }
        } else {
          c = colors
        }

        if(c.length === 3) {
          for(var j=0; j<3; ++j) {
            color[j] = c[j]
          }
          color[3] = 1
        } else if(c.length === 4) {
          for(var j=0; j<4; ++j) {
            color[j] = c[j]
          }
          if(!this.hasAlpha && c[3] < 1) this.hasAlpha = true
        }
      } else {
        color[0] = color[1] = color[2] = 0
        color[3] = 1
      }


      //Get lineColor
      if(!glyphVisible) lineColor = [1,1,1,0]
      else if(Array.isArray(lineColors)) {
        var c
        if(isLineColorArray) {
          if(i < lineColors.length) {
            c = lineColors[i]
          } else {
            c = [0,0,0,0]
          }
        } else {
          c = lineColors
        }

        if(c.length === 3) {
          for(var j=0; j<3; ++j) {
            lineColor[j] = c[j]
          }
          lineColor[j] = 1
        } else if(c.length === 4) {
          for(var j=0; j<4; ++j) {
            lineColor[j] = c[j]
          }
          if(!this.hasAlpha && c[3] < 1) this.hasAlpha = true
        }
      } else {
        lineColor[0] = lineColor[1] = lineColor[2] = 0
        lineColor[3] = 1
      }


      var size = 0.5
      if(!glyphVisible) size = 0.0
      else if(Array.isArray(sizes)) {
        if(i < sizes.length) {
          size = +sizes[i]
        } else {
          size = 12
        }
      } else if(sizes) {
        size = +sizes
      } else if(this.useOrtho) {
        size = 12
      }


      var angle = 0
      if(Array.isArray(angles)) {
        if(i < angles.length) {
          angle = +angles[i]
        } else {
          angle = 0
        }
      } else if(angles) {
        angle = +angles
      }

      //Loop through markers and append to buffers
      var cos = Math.cos(angle)
      var sin = Math.sin(angle)

      var x = points[i]
      for(var j=0; j<3; ++j) {
        upperBound[j] = Math.max(upperBound[j], x[j])
        lowerBound[j] = Math.min(lowerBound[j], x[j])
      }

      //Calculate text offset
      var textOffsetX = alignmentX
      var textOffsetY = alignmentY

      var textOffsetX = 0
      if(Array.isArray(alignmentX)) {
        if(i < alignmentX.length) {
          textOffsetX = alignmentX[i]
        } else {
          textOffsetX = 0
        }
      } else if(alignmentX) {
        textOffsetX = alignmentX
      }

      var textOffsetY = 0
      if(Array.isArray(alignmentY)) {
        if(i < alignmentY.length) {
          textOffsetY = alignmentY[i]
        } else {
          textOffsetY = 0
        }
      } else if(alignmentY) {
        textOffsetY = alignmentY
      }

      textOffsetX *= (textOffsetX > 0) ? (1 - glyphBounds[0][0]) :
                     (textOffsetX < 0) ? (1 + glyphBounds[1][0]) : 1;

      textOffsetY *= (textOffsetY > 0) ? (1 - glyphBounds[0][1]) :
                     (textOffsetY < 0) ? (1 + glyphBounds[1][1]) : 1;

      var textOffset = [textOffsetX, textOffsetY]

      //Write out inner marker
      var cells = glyphMesh.cells || []
      var verts = glyphMesh.positions || []

      for(var j=0; j<cells.length; ++j) {
        var cell = cells[j]
        for(var k=0; k<3; ++k) {
          for(var l=0; l<3; ++l) {
            positionArray[3*triOffset+l] = x[l]
          }
          for(var l=0; l<4; ++l) {
            colorArray[4*triOffset+l] = color[l]
          }
          idArray[triOffset] = pickCounter
          var p = verts[cell[k]]
          glyphArray[2*triOffset]   = size * (cos*p[0] - sin*p[1] + textOffset[0])
          glyphArray[2*triOffset+1] = size * (sin*p[0] + cos*p[1] + textOffset[1])
          triOffset += 1
        }
      }

      var cells = glyphLines.edges
      var verts = glyphLines.positions

      for(var j=0; j<cells.length; ++j) {
        var cell = cells[j]
        for(var k=0; k<2; ++k) {
          for(var l=0; l<3; ++l) {
            positionArray[3*lineOffset+l] = x[l]
          }
          for(var l=0; l<4; ++l) {
            colorArray[4*lineOffset+l] = lineColor[l]
          }
          idArray[lineOffset] = pickCounter
          var p = verts[cell[k]]
          glyphArray[2*lineOffset]   = size * (cos*p[0] - sin*p[1] + textOffset[0])
          glyphArray[2*lineOffset+1] = size * (sin*p[0] + cos*p[1] + textOffset[1])
          lineOffset += 1
        }
      }

    }



  }

  //Update bounds
  this.bounds = [lowerBound, upperBound]

  //Save points
  this.points = points

  //Save number of points
  this.pointCount = points.length

  //Update vertex counts
  this.vertexCount      = triVertexCount
  this.lineVertexCount  = lineVertexCount

  this.pointBuffer.update(positionArray)
  this.colorBuffer.update(colorArray)
  this.glyphBuffer.update(glyphArray)
  //this.idBuffer.update(new Uint32Array(idArray))
  this.idBuffer.update(idArray)

  pool.free(positionArray)
  pool.free(colorArray)
  pool.free(glyphArray)
  pool.free(idArray)
}

proto.dispose = function() {
  //Shaders
  this.shader.dispose()
  this.orthoShader.dispose()
  this.pickPerspectiveShader.dispose()
  this.pickOrthoShader.dispose()

  //Vertex array
  this.vao.dispose()

  //Buffers
  this.pointBuffer.dispose()
  this.colorBuffer.dispose()
  this.glyphBuffer.dispose()
  this.idBuffer.dispose()
}

function createPointCloud(options) {
  var gl = options.gl

  var shader                = shaders.createPerspective(gl)
  var orthoShader           = shaders.createOrtho(gl)
  var projectShader         = shaders.createProject(gl)
  var pickPerspectiveShader = shaders.createPickPerspective(gl)
  var pickOrthoShader       = shaders.createPickOrtho(gl)
  var pickProjectShader     = shaders.createPickProject(gl)

  var pointBuffer = createBuffer(gl)
  var colorBuffer = createBuffer(gl)
  var glyphBuffer = createBuffer(gl)
  var idBuffer    = createBuffer(gl)
  var vao = createVAO(gl, [
    {
      buffer: pointBuffer,
      size: 3,
      type: gl.FLOAT
    },
    {
      buffer: colorBuffer,
      size: 4,
      type: gl.FLOAT
    },
    {
      buffer: glyphBuffer,
      size: 2,
      type: gl.FLOAT
    },
    {
      buffer: idBuffer,
      size: 4,
      type: gl.UNSIGNED_BYTE,
      normalized: true
    }
  ])

  var pointCloud = new PointCloud(
    gl,
    shader,
    orthoShader,
    projectShader,
    pointBuffer,
    colorBuffer,
    glyphBuffer,
    idBuffer,
    vao,
    pickPerspectiveShader,
    pickOrthoShader,
    pickProjectShader)

  pointCloud.update(options)

  return pointCloud
}

},{"./lib/get-simple-string":283,"./lib/glyphs":284,"./lib/shaders":285,"gl-buffer":231,"gl-mat4/multiply":258,"gl-vao":313,"is-string-blank":409,"typedarray-pool":523}],287:[function(_dereq_,module,exports){
'use strict'

var glslify = _dereq_('glslify')

exports.boxVertex = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 vertex;\n\nuniform vec2 cornerA, cornerB;\n\nvoid main() {\n  gl_Position = vec4(mix(cornerA, cornerB, vertex), 0, 1);\n}\n"])
exports.boxFragment = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n  gl_FragColor = color;\n}\n"])

},{"glslify":395}],288:[function(_dereq_,module,exports){
'use strict'

var createShader = _dereq_('gl-shader')
var createBuffer = _dereq_('gl-buffer')

var SHADERS = _dereq_('./lib/shaders')

module.exports = createSelectBox

function SelectBox(plot, boxBuffer, boxShader) {
  this.plot = plot
  this.boxBuffer = boxBuffer
  this.boxShader = boxShader

  this.enabled = true

  this.selectBox = [Infinity,Infinity,-Infinity,-Infinity]

  this.borderColor = [0,0,0,1]
  this.innerFill   = false
  this.innerColor  = [0,0,0,0.25]
  this.outerFill   = true
  this.outerColor  = [0,0,0,0.5]
  this.borderWidth = 10
}

var proto = SelectBox.prototype

proto.draw = function() {
  if(!this.enabled) {
    return
  }

  var plot         = this.plot
  var selectBox    = this.selectBox
  var lineWidth    = this.borderWidth

  var innerFill    = this.innerFill
  var innerColor   = this.innerColor
  var outerFill    = this.outerFill
  var outerColor   = this.outerColor
  var borderColor  = this.borderColor

  var boxes        = plot.box
  var screenBox    = plot.screenBox
  var dataBox      = plot.dataBox
  var viewBox      = plot.viewBox
  var pixelRatio   = plot.pixelRatio

  //Map select box into pixel coordinates
  var loX = (selectBox[0]-dataBox[0])*(viewBox[2]-viewBox[0])/(dataBox[2]-dataBox[0])+viewBox[0]
  var loY = (selectBox[1]-dataBox[1])*(viewBox[3]-viewBox[1])/(dataBox[3]-dataBox[1])+viewBox[1]
  var hiX = (selectBox[2]-dataBox[0])*(viewBox[2]-viewBox[0])/(dataBox[2]-dataBox[0])+viewBox[0]
  var hiY = (selectBox[3]-dataBox[1])*(viewBox[3]-viewBox[1])/(dataBox[3]-dataBox[1])+viewBox[1]

  loX = Math.max(loX, viewBox[0])
  loY = Math.max(loY, viewBox[1])
  hiX = Math.min(hiX, viewBox[2])
  hiY = Math.min(hiY, viewBox[3])

  if(hiX < loX || hiY < loY) {
    return
  }

  boxes.bind()

  //Draw box
  var screenWidth  = screenBox[2] - screenBox[0]
  var screenHeight = screenBox[3] - screenBox[1]

  if(this.outerFill) {
    boxes.drawBox(0, 0, screenWidth, loY, outerColor)
    boxes.drawBox(0, loY, loX, hiY, outerColor)
    boxes.drawBox(0, hiY, screenWidth, screenHeight, outerColor)
    boxes.drawBox(hiX, loY, screenWidth, hiY, outerColor)
  }

  if(this.innerFill) {
    boxes.drawBox(loX, loY, hiX, hiY, innerColor)
  }

  //Draw border
  if(lineWidth > 0) {

    //Draw border
    var w = lineWidth * pixelRatio
    boxes.drawBox(loX-w, loY-w, hiX+w, loY+w, borderColor)
    boxes.drawBox(loX-w, hiY-w, hiX+w, hiY+w, borderColor)
    boxes.drawBox(loX-w, loY-w, loX+w, hiY+w, borderColor)
    boxes.drawBox(hiX-w, loY-w, hiX+w, hiY+w, borderColor)
  }
}

proto.update = function(options) {
  options = options || {}

  this.innerFill    = !!options.innerFill
  this.outerFill    = !!options.outerFill
  this.innerColor   = (options.innerColor   || [0,0,0,0.5]).slice()
  this.outerColor   = (options.outerColor   || [0,0,0,0.5]).slice()
  this.borderColor  = (options.borderColor || [0,0,0,1]).slice()
  this.borderWidth  = options.borderWidth || 0
  this.selectBox    = (options.selectBox || this.selectBox).slice()
}

proto.dispose = function() {
  this.boxBuffer.dispose()
  this.boxShader.dispose()
  this.plot.removeOverlay(this)
}

function createSelectBox(plot, options) {
  var gl = plot.gl
  var buffer = createBuffer(gl, [
    0, 0,
    0, 1,
    1, 0,
    1, 1 ])
  var shader = createShader(gl, SHADERS.boxVertex, SHADERS.boxFragment)
  var selectBox = new SelectBox(plot, buffer, shader)
  selectBox.update(options)
  plot.addOverlay(selectBox)
  return selectBox
}

},{"./lib/shaders":287,"gl-buffer":231,"gl-shader":290}],289:[function(_dereq_,module,exports){
'use strict'

module.exports = createSelectBuffer

var createFBO = _dereq_('gl-fbo')
var pool      = _dereq_('typedarray-pool')
var ndarray   = _dereq_('ndarray')

var nextPow2  = _dereq_('bit-twiddle').nextPow2

var selectRange = _dereq_('cwise/lib/wrapper')({"args":["array",{"offset":[0,0,1],"array":0},{"offset":[0,0,2],"array":0},{"offset":[0,0,3],"array":0},"scalar","scalar","index"],"pre":{"body":"{this_closestD2=1e8,this_closestX=-1,this_closestY=-1}","args":[],"thisVars":["this_closestD2","this_closestX","this_closestY"],"localVars":[]},"body":{"body":"{if(_inline_16_arg0_<255||_inline_16_arg1_<255||_inline_16_arg2_<255||_inline_16_arg3_<255){var _inline_16_l=_inline_16_arg4_-_inline_16_arg6_[0],_inline_16_a=_inline_16_arg5_-_inline_16_arg6_[1],_inline_16_f=_inline_16_l*_inline_16_l+_inline_16_a*_inline_16_a;_inline_16_f<this_closestD2&&(this_closestD2=_inline_16_f,this_closestX=_inline_16_arg6_[0],this_closestY=_inline_16_arg6_[1])}}","args":[{"name":"_inline_16_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_16_arg1_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_16_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_16_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_16_arg4_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_16_arg5_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_16_arg6_","lvalue":false,"rvalue":true,"count":4}],"thisVars":["this_closestD2","this_closestX","this_closestY"],"localVars":["_inline_16_a","_inline_16_f","_inline_16_l"]},"post":{"body":"{return[this_closestX,this_closestY,this_closestD2]}","args":[],"thisVars":["this_closestD2","this_closestX","this_closestY"],"localVars":[]},"debug":false,"funcName":"cwise","blockSize":64})

function SelectResult(x, y, id, value, distance) {
  this.coord = [x, y]
  this.id = id
  this.value = value
  this.distance = distance
}

function SelectBuffer(gl, fbo, buffer) {
  this.gl     = gl
  this.fbo    = fbo
  this.buffer = buffer
  this._readTimeout = null
  var self = this

  this._readCallback = function() {
    if(!self.gl) {
      return
    }
    fbo.bind()
    gl.readPixels(0,0,fbo.shape[0],fbo.shape[1],gl.RGBA,gl.UNSIGNED_BYTE,self.buffer)
    self._readTimeout = null
  }
}

var proto = SelectBuffer.prototype

Object.defineProperty(proto, 'shape', {
  get: function() {
    if(!this.gl) {
      return [0,0]
    }
    return this.fbo.shape.slice()
  },
  set: function(v) {
    if(!this.gl) {
      return
    }
    this.fbo.shape = v
    var c = this.fbo.shape[0]
    var r = this.fbo.shape[1]
    if(r*c*4 > this.buffer.length) {
      pool.free(this.buffer)
      var buffer = this.buffer = pool.mallocUint8(nextPow2(r*c*4))
      for(var i=0; i<r*c*4; ++i) {
        buffer[i] = 0xff
      }
    }
    return v
  }
})

proto.begin = function() {
  var gl = this.gl
  var shape = this.shape
  if(!gl) {
    return
  }

  this.fbo.bind()
  gl.clearColor(1,1,1,1)
  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
}

proto.end = function() {
  var gl = this.gl
  if(!gl) {
    return
  }
  gl.bindFramebuffer(gl.FRAMEBUFFER, null)
  if(!this._readTimeout) {
    clearTimeout(this._readTimeout)
  }
  this._readTimeout = setTimeout(this._readCallback, 1)
}

proto.query = function(x, y, radius) {
  if(!this.gl) {
    return null
  }

  var shape = this.fbo.shape.slice()

  x = x|0
  y = y|0
  if(typeof radius !== 'number') {
    radius = 1.0
  }

  var x0 = Math.min(Math.max(x - radius, 0), shape[0])|0
  var x1 = Math.min(Math.max(x + radius, 0), shape[0])|0
  var y0 = Math.min(Math.max(y - radius, 0), shape[1])|0
  var y1 = Math.min(Math.max(y + radius, 0), shape[1])|0

  if(x1 <= x0 || y1 <= y0) {
    return null
  }

  var dims   = [x1-x0,y1-y0]
  var region = ndarray(
    this.buffer,
    [dims[0], dims[1], 4],
    [4, shape[0]*4, 1],
    4*(x0 + shape[0]*y0));

  var closest = selectRange(region.hi(dims[0],dims[1],1), radius, radius)
  var dx = closest[0]
  var dy = closest[1]
  if(dx < 0 || Math.pow(this.radius, 2) < closest[2]) {
    return null
  }

  var c0 = region.get(dx, dy, 0)
  var c1 = region.get(dx, dy, 1)
  var c2 = region.get(dx, dy, 2)
  var c3 = region.get(dx, dy, 3)

  return new SelectResult(
     (dx + x0)|0,
     (dy + y0)|0,
     c0,
     [c1, c2, c3],
     Math.sqrt(closest[2]))
}

proto.dispose = function() {
  if(!this.gl) {
    return
  }
  this.fbo.dispose()
  pool.free(this.buffer)
  this.gl = null
  if(this._readTimeout) {
    clearTimeout(this._readTimeout)
  }
}

function createSelectBuffer(gl, shape) {
  var fbo = createFBO(gl, shape)
  var buffer = pool.mallocUint8(shape[0]*shape[1]*4)
  return new SelectBuffer(gl, fbo, buffer)
}

},{"bit-twiddle":81,"cwise/lib/wrapper":138,"gl-fbo":240,"ndarray":436,"typedarray-pool":523}],290:[function(_dereq_,module,exports){
'use strict'

var createUniformWrapper   = _dereq_('./lib/create-uniforms')
var createAttributeWrapper = _dereq_('./lib/create-attributes')
var makeReflect            = _dereq_('./lib/reflect')
var shaderCache            = _dereq_('./lib/shader-cache')
var runtime                = _dereq_('./lib/runtime-reflect')
var GLError                = _dereq_("./lib/GLError")

//Shader object
function Shader(gl) {
  this.gl         = gl
  this.gl.lastAttribCount = 0  // fixme where else should we store info, safe but not nice on the gl object

  //Default initialize these to null
  this._vref      =
  this._fref      =
  this._relink    =
  this.vertShader =
  this.fragShader =
  this.program    =
  this.attributes =
  this.uniforms   =
  this.types      = null
}

var proto = Shader.prototype

proto.bind = function() {
  if(!this.program) {
    this._relink()
  }

  // ensuring that we have the right number of enabled vertex attributes
  var i
  var newAttribCount = this.gl.getProgramParameter(this.program, this.gl.ACTIVE_ATTRIBUTES) // more robust approach
  //var newAttribCount = Object.keys(this.attributes).length // avoids the probably immaterial introspection slowdown
  var oldAttribCount = this.gl.lastAttribCount
  if(newAttribCount > oldAttribCount) {
    for(i = oldAttribCount; i < newAttribCount; i++) {
      this.gl.enableVertexAttribArray(i)
    }
  } else if(oldAttribCount > newAttribCount) {
    for(i = newAttribCount; i < oldAttribCount; i++) {
      this.gl.disableVertexAttribArray(i)
    }
  }

  this.gl.lastAttribCount = newAttribCount

  this.gl.useProgram(this.program)
}

proto.dispose = function() {

  // disabling vertex attributes so new shader starts with zero
  // and it's also useful if all shaders are disposed but the
  // gl context is reused for subsequent replotting
  var oldAttribCount = this.gl.lastAttribCount
  for (var i = 0; i < oldAttribCount; i++) {
    this.gl.disableVertexAttribArray(i)
  }
  this.gl.lastAttribCount = 0

  if(this._fref) {
    this._fref.dispose()
  }
  if(this._vref) {
    this._vref.dispose()
  }
  this.attributes =
  this.types      =
  this.vertShader =
  this.fragShader =
  this.program    =
  this._relink    =
  this._fref      =
  this._vref      = null
}

function compareAttributes(a, b) {
  if(a.name < b.name) {
    return -1
  }
  return 1
}

//Update export hook for glslify-live
proto.update = function(
    vertSource
  , fragSource
  , uniforms
  , attributes) {

  //If only one object passed, assume glslify style output
  if(!fragSource || arguments.length === 1) {
    var obj = vertSource
    vertSource = obj.vertex
    fragSource = obj.fragment
    uniforms   = obj.uniforms
    attributes = obj.attributes
  }

  var wrapper = this
  var gl      = wrapper.gl

  //Compile vertex and fragment shaders
  var pvref = wrapper._vref
  wrapper._vref = shaderCache.shader(gl, gl.VERTEX_SHADER, vertSource)
  if(pvref) {
    pvref.dispose()
  }
  wrapper.vertShader = wrapper._vref.shader
  var pfref = this._fref
  wrapper._fref = shaderCache.shader(gl, gl.FRAGMENT_SHADER, fragSource)
  if(pfref) {
    pfref.dispose()
  }
  wrapper.fragShader = wrapper._fref.shader

  //If uniforms/attributes is not specified, use RT reflection
  if(!uniforms || !attributes) {

    //Create initial test program
    var testProgram = gl.createProgram()
    gl.attachShader(testProgram, wrapper.fragShader)
    gl.attachShader(testProgram, wrapper.vertShader)
    gl.linkProgram(testProgram)
    if(!gl.getProgramParameter(testProgram, gl.LINK_STATUS)) {
      var errLog = gl.getProgramInfoLog(testProgram)
      throw new GLError(errLog, 'Error linking program:' + errLog)
    }

    //Load data from runtime
    uniforms   = uniforms   || runtime.uniforms(gl, testProgram)
    attributes = attributes || runtime.attributes(gl, testProgram)

    //Release test program
    gl.deleteProgram(testProgram)
  }

  //Sort attributes lexicographically
  // overrides undefined WebGL behavior for attribute locations
  attributes = attributes.slice()
  attributes.sort(compareAttributes)

  //Convert attribute types, read out locations
  var attributeUnpacked  = []
  var attributeNames     = []
  var attributeLocations = []
  var i
  for(i=0; i<attributes.length; ++i) {
    var attr = attributes[i]
    if(attr.type.indexOf('mat') >= 0) {
      var size = attr.type.charAt(attr.type.length-1)|0
      var locVector = new Array(size)
      for(var j=0; j<size; ++j) {
        locVector[j] = attributeLocations.length
        attributeNames.push(attr.name + '[' + j + ']')
        if(typeof attr.location === 'number') {
          attributeLocations.push(attr.location + j)
        } else if(Array.isArray(attr.location) &&
                  attr.location.length === size &&
                  typeof attr.location[j] === 'number') {
          attributeLocations.push(attr.location[j]|0)
        } else {
          attributeLocations.push(-1)
        }
      }
      attributeUnpacked.push({
        name: attr.name,
        type: attr.type,
        locations: locVector
      })
    } else {
      attributeUnpacked.push({
        name: attr.name,
        type: attr.type,
        locations: [ attributeLocations.length ]
      })
      attributeNames.push(attr.name)
      if(typeof attr.location === 'number') {
        attributeLocations.push(attr.location|0)
      } else {
        attributeLocations.push(-1)
      }
    }
  }

  //For all unspecified attributes, assign them lexicographically min attribute
  var curLocation = 0
  for(i=0; i<attributeLocations.length; ++i) {
    if(attributeLocations[i] < 0) {
      while(attributeLocations.indexOf(curLocation) >= 0) {
        curLocation += 1
      }
      attributeLocations[i] = curLocation
    }
  }

  //Rebuild program and recompute all uniform locations
  var uniformLocations = new Array(uniforms.length)
  function relink() {
    wrapper.program = shaderCache.program(
        gl
      , wrapper._vref
      , wrapper._fref
      , attributeNames
      , attributeLocations)

    for(var i=0; i<uniforms.length; ++i) {
      uniformLocations[i] = gl.getUniformLocation(
          wrapper.program
        , uniforms[i].name)
    }
  }

  //Perform initial linking, reuse program used for reflection
  relink()

  //Save relinking procedure, defer until runtime
  wrapper._relink = relink

  //Generate type info
  wrapper.types = {
    uniforms:   makeReflect(uniforms),
    attributes: makeReflect(attributes)
  }

  //Generate attribute wrappers
  wrapper.attributes = createAttributeWrapper(
      gl
    , wrapper
    , attributeUnpacked
    , attributeLocations)

  //Generate uniform wrappers
  Object.defineProperty(wrapper, 'uniforms', createUniformWrapper(
      gl
    , wrapper
    , uniforms
    , uniformLocations))
}

//Compiles and links a shader program with the given attribute and vertex list
function createShader(
    gl
  , vertSource
  , fragSource
  , uniforms
  , attributes) {

  var shader = new Shader(gl)

  shader.update(
      vertSource
    , fragSource
    , uniforms
    , attributes)

  return shader
}

module.exports = createShader

},{"./lib/GLError":291,"./lib/create-attributes":292,"./lib/create-uniforms":293,"./lib/reflect":294,"./lib/runtime-reflect":295,"./lib/shader-cache":296}],291:[function(_dereq_,module,exports){
function GLError (rawError, shortMessage, longMessage) {
    this.shortMessage = shortMessage || ''
    this.longMessage = longMessage || ''
    this.rawError = rawError || ''
    this.message =
      'gl-shader: ' + (shortMessage || rawError || '') +
      (longMessage ? '\n'+longMessage : '')
    this.stack = (new Error()).stack
}
GLError.prototype = new Error
GLError.prototype.name = 'GLError'
GLError.prototype.constructor = GLError
module.exports = GLError

},{}],292:[function(_dereq_,module,exports){
'use strict'

module.exports = createAttributeWrapper

var GLError = _dereq_("./GLError")

function ShaderAttribute(
    gl
  , wrapper
  , index
  , locations
  , dimension
  , constFunc) {
  this._gl        = gl
  this._wrapper   = wrapper
  this._index     = index
  this._locations = locations
  this._dimension = dimension
  this._constFunc = constFunc
}

var proto = ShaderAttribute.prototype

proto.pointer = function setAttribPointer(
    type
  , normalized
  , stride
  , offset) {

  var self      = this
  var gl        = self._gl
  var location  = self._locations[self._index]

  gl.vertexAttribPointer(
      location
    , self._dimension
    , type || gl.FLOAT
    , !!normalized
    , stride || 0
    , offset || 0)
  gl.enableVertexAttribArray(location)
}

proto.set = function(x0, x1, x2, x3) {
  return this._constFunc(this._locations[this._index], x0, x1, x2, x3)
}

Object.defineProperty(proto, 'location', {
  get: function() {
    return this._locations[this._index]
  }
  , set: function(v) {
    if(v !== this._locations[this._index]) {
      this._locations[this._index] = v|0
      this._wrapper.program = null
    }
    return v|0
  }
})

//Adds a vector attribute to obj
function addVectorAttribute(
    gl
  , wrapper
  , index
  , locations
  , dimension
  , obj
  , name) {

  //Construct constant function
  var constFuncArgs = [ 'gl', 'v' ]
  var varNames = []
  for(var i=0; i<dimension; ++i) {
    constFuncArgs.push('x'+i)
    varNames.push('x'+i)
  }
  constFuncArgs.push(
    'if(x0.length===void 0){return gl.vertexAttrib' +
    dimension + 'f(v,' +
    varNames.join() +
    ')}else{return gl.vertexAttrib' +
    dimension +
    'fv(v,x0)}')
  var constFunc = Function.apply(null, constFuncArgs)

  //Create attribute wrapper
  var attr = new ShaderAttribute(
      gl
    , wrapper
    , index
    , locations
    , dimension
    , constFunc)

  //Create accessor
  Object.defineProperty(obj, name, {
    set: function(x) {
      gl.disableVertexAttribArray(locations[index])
      constFunc(gl, locations[index], x)
      return x
    }
    , get: function() {
      return attr
    }
    , enumerable: true
  })
}

function addMatrixAttribute(
    gl
  , wrapper
  , index
  , locations
  , dimension
  , obj
  , name) {

  var parts = new Array(dimension)
  var attrs = new Array(dimension)
  for(var i=0; i<dimension; ++i) {
    addVectorAttribute(
        gl
      , wrapper
      , index[i]
      , locations
      , dimension
      , parts
      , i)
    attrs[i] = parts[i]
  }

  Object.defineProperty(parts, 'location', {
    set: function(v) {
      if(Array.isArray(v)) {
        for(var i=0; i<dimension; ++i) {
          attrs[i].location = v[i]
        }
      } else {
        for(var i=0; i<dimension; ++i) {
          attrs[i].location = v + i
        }
      }
      return v
    }
    , get: function() {
      var result = new Array(dimension)
      for(var i=0; i<dimension; ++i) {
        result[i] = locations[index[i]]
      }
      return result
    }
    , enumerable: true
  })

  parts.pointer = function(type, normalized, stride, offset) {
    type       = type || gl.FLOAT
    normalized = !!normalized
    stride     = stride || (dimension * dimension)
    offset     = offset || 0
    for(var i=0; i<dimension; ++i) {
      var location = locations[index[i]]
      gl.vertexAttribPointer(
            location
          , dimension
          , type
          , normalized
          , stride
          , offset + i * dimension)
      gl.enableVertexAttribArray(location)
    }
  }

  var scratch = new Array(dimension)
  var vertexAttrib = gl['vertexAttrib' + dimension + 'fv']

  Object.defineProperty(obj, name, {
    set: function(x) {
      for(var i=0; i<dimension; ++i) {
        var loc = locations[index[i]]
        gl.disableVertexAttribArray(loc)
        if(Array.isArray(x[0])) {
          vertexAttrib.call(gl, loc, x[i])
        } else {
          for(var j=0; j<dimension; ++j) {
            scratch[j] = x[dimension*i + j]
          }
          vertexAttrib.call(gl, loc, scratch)
        }
      }
      return x
    }
    , get: function() {
      return parts
    }
    , enumerable: true
  })
}

//Create shims for attributes
function createAttributeWrapper(
    gl
  , wrapper
  , attributes
  , locations) {

  var obj = {}
  for(var i=0, n=attributes.length; i<n; ++i) {

    var a = attributes[i]
    var name = a.name
    var type = a.type
    var locs = a.locations

    switch(type) {
      case 'bool':
      case 'int':
      case 'float':
        addVectorAttribute(
            gl
          , wrapper
          , locs[0]
          , locations
          , 1
          , obj
          , name)
      break

      default:
        if(type.indexOf('vec') >= 0) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new GLError('', 'Invalid data type for attribute ' + name + ': ' + type)
          }
          addVectorAttribute(
              gl
            , wrapper
            , locs[0]
            , locations
            , d
            , obj
            , name)
        } else if(type.indexOf('mat') >= 0) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new GLError('', 'Invalid data type for attribute ' + name + ': ' + type)
          }
          addMatrixAttribute(
              gl
            , wrapper
            , locs
            , locations
            , d
            , obj
            , name)
        } else {
          throw new GLError('', 'Unknown data type for attribute ' + name + ': ' + type)
        }
      break
    }
  }
  return obj
}

},{"./GLError":291}],293:[function(_dereq_,module,exports){
'use strict'

var coallesceUniforms = _dereq_('./reflect')
var GLError = _dereq_("./GLError")

module.exports = createUniformWrapper

//Binds a function and returns a value
function identity(x) {
  var c = new Function('y', 'return function(){return y}')
  return c(x)
}

function makeVector(length, fill) {
  var result = new Array(length)
  for(var i=0; i<length; ++i) {
    result[i] = fill
  }
  return result
}

//Create shims for uniforms
function createUniformWrapper(gl, wrapper, uniforms, locations) {

  function makeGetter(index) {
    var proc = new Function(
        'gl'
      , 'wrapper'
      , 'locations'
      , 'return function(){return gl.getUniform(wrapper.program,locations[' + index + '])}')
    return proc(gl, wrapper, locations)
  }

  function makePropSetter(path, index, type) {
    switch(type) {
      case 'bool':
      case 'int':
      case 'sampler2D':
      case 'samplerCube':
        return 'gl.uniform1i(locations[' + index + '],obj' + path + ')'
      case 'float':
        return 'gl.uniform1f(locations[' + index + '],obj' + path + ')'
      default:
        var vidx = type.indexOf('vec')
        if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new GLError('', 'Invalid data type')
          }
          switch(type.charAt(0)) {
            case 'b':
            case 'i':
              return 'gl.uniform' + d + 'iv(locations[' + index + '],obj' + path + ')'
            case 'v':
              return 'gl.uniform' + d + 'fv(locations[' + index + '],obj' + path + ')'
            default:
              throw new GLError('', 'Unrecognized data type for vector ' + name + ': ' + type)
          }
        } else if(type.indexOf('mat') === 0 && type.length === 4) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new GLError('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type)
          }
          return 'gl.uniformMatrix' + d + 'fv(locations[' + index + '],false,obj' + path + ')'
        } else {
          throw new GLError('', 'Unknown uniform data type for ' + name + ': ' + type)
        }
      break
    }
  }

  function enumerateIndices(prefix, type) {
    if(typeof type !== 'object') {
      return [ [prefix, type] ]
    }
    var indices = []
    for(var id in type) {
      var prop = type[id]
      var tprefix = prefix
      if(parseInt(id) + '' === id) {
        tprefix += '[' + id + ']'
      } else {
        tprefix += '.' + id
      }
      if(typeof prop === 'object') {
        indices.push.apply(indices, enumerateIndices(tprefix, prop))
      } else {
        indices.push([tprefix, prop])
      }
    }
    return indices
  }

  function makeSetter(type) {
    var code = [ 'return function updateProperty(obj){' ]
    var indices = enumerateIndices('', type)
    for(var i=0; i<indices.length; ++i) {
      var item = indices[i]
      var path = item[0]
      var idx  = item[1]
      if(locations[idx]) {
        code.push(makePropSetter(path, idx, uniforms[idx].type))
      }
    }
    code.push('return obj}')
    var proc = new Function('gl', 'locations', code.join('\n'))
    return proc(gl, locations)
  }

  function defaultValue(type) {
    switch(type) {
      case 'bool':
        return false
      case 'int':
      case 'sampler2D':
      case 'samplerCube':
        return 0
      case 'float':
        return 0.0
      default:
        var vidx = type.indexOf('vec')
        if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new GLError('', 'Invalid data type')
          }
          if(type.charAt(0) === 'b') {
            return makeVector(d, false)
          }
          return makeVector(d, 0)
        } else if(type.indexOf('mat') === 0 && type.length === 4) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new GLError('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type)
          }
          return makeVector(d*d, 0)
        } else {
          throw new GLError('', 'Unknown uniform data type for ' + name + ': ' + type)
        }
      break
    }
  }

  function storeProperty(obj, prop, type) {
    if(typeof type === 'object') {
      var child = processObject(type)
      Object.defineProperty(obj, prop, {
        get: identity(child),
        set: makeSetter(type),
        enumerable: true,
        configurable: false
      })
    } else {
      if(locations[type]) {
        Object.defineProperty(obj, prop, {
          get: makeGetter(type),
          set: makeSetter(type),
          enumerable: true,
          configurable: false
        })
      } else {
        obj[prop] = defaultValue(uniforms[type].type)
      }
    }
  }

  function processObject(obj) {
    var result
    if(Array.isArray(obj)) {
      result = new Array(obj.length)
      for(var i=0; i<obj.length; ++i) {
        storeProperty(result, i, obj[i])
      }
    } else {
      result = {}
      for(var id in obj) {
        storeProperty(result, id, obj[id])
      }
    }
    return result
  }

  //Return data
  var coallesced = coallesceUniforms(uniforms, true)
  return {
    get: identity(processObject(coallesced)),
    set: makeSetter(coallesced),
    enumerable: true,
    configurable: true
  }
}

},{"./GLError":291,"./reflect":294}],294:[function(_dereq_,module,exports){
'use strict'

module.exports = makeReflectTypes

//Construct type info for reflection.
//
// This iterates over the flattened list of uniform type values and smashes them into a JSON object.
//
// The leaves of the resulting object are either indices or type strings representing primitive glslify types
function makeReflectTypes(uniforms, useIndex) {
  var obj = {}
  for(var i=0; i<uniforms.length; ++i) {
    var n = uniforms[i].name
    var parts = n.split(".")
    var o = obj
    for(var j=0; j<parts.length; ++j) {
      var x = parts[j].split("[")
      if(x.length > 1) {
        if(!(x[0] in o)) {
          o[x[0]] = []
        }
        o = o[x[0]]
        for(var k=1; k<x.length; ++k) {
          var y = parseInt(x[k])
          if(k<x.length-1 || j<parts.length-1) {
            if(!(y in o)) {
              if(k < x.length-1) {
                o[y] = []
              } else {
                o[y] = {}
              }
            }
            o = o[y]
          } else {
            if(useIndex) {
              o[y] = i
            } else {
              o[y] = uniforms[i].type
            }
          }
        }
      } else if(j < parts.length-1) {
        if(!(x[0] in o)) {
          o[x[0]] = {}
        }
        o = o[x[0]]
      } else {
        if(useIndex) {
          o[x[0]] = i
        } else {
          o[x[0]] = uniforms[i].type
        }
      }
    }
  }
  return obj
}
},{}],295:[function(_dereq_,module,exports){
'use strict'

exports.uniforms    = runtimeUniforms
exports.attributes  = runtimeAttributes

var GL_TO_GLSL_TYPES = {
  'FLOAT':       'float',
  'FLOAT_VEC2':  'vec2',
  'FLOAT_VEC3':  'vec3',
  'FLOAT_VEC4':  'vec4',
  'INT':         'int',
  'INT_VEC2':    'ivec2',
  'INT_VEC3':    'ivec3',
  'INT_VEC4':    'ivec4',
  'BOOL':        'bool',
  'BOOL_VEC2':   'bvec2',
  'BOOL_VEC3':   'bvec3',
  'BOOL_VEC4':   'bvec4',
  'FLOAT_MAT2':  'mat2',
  'FLOAT_MAT3':  'mat3',
  'FLOAT_MAT4':  'mat4',
  'SAMPLER_2D':  'sampler2D',
  'SAMPLER_CUBE':'samplerCube'
}

var GL_TABLE = null

function getType(gl, type) {
  if(!GL_TABLE) {
    var typeNames = Object.keys(GL_TO_GLSL_TYPES)
    GL_TABLE = {}
    for(var i=0; i<typeNames.length; ++i) {
      var tn = typeNames[i]
      GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]
    }
  }
  return GL_TABLE[type]
}

function runtimeUniforms(gl, program) {
  var numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS)
  var result = []
  for(var i=0; i<numUniforms; ++i) {
    var info = gl.getActiveUniform(program, i)
    if(info) {
      var type = getType(gl, info.type)
      if(info.size > 1) {
        for(var j=0; j<info.size; ++j) {
          result.push({
            name: info.name.replace('[0]', '[' + j + ']'),
            type: type
          })
        }
      } else {
        result.push({
          name: info.name,
          type: type
        })
      }
    }
  }
  return result
}

function runtimeAttributes(gl, program) {
  var numAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES)
  var result = []
  for(var i=0; i<numAttributes; ++i) {
    var info = gl.getActiveAttrib(program, i)
    if(info) {
      result.push({
        name: info.name,
        type: getType(gl, info.type)
      })
    }
  }
  return result
}

},{}],296:[function(_dereq_,module,exports){
'use strict'

exports.shader   = getShaderReference
exports.program  = createProgram

var GLError = _dereq_("./GLError")
var formatCompilerError = _dereq_('gl-format-compiler-error');

var weakMap = typeof WeakMap === 'undefined' ? _dereq_('weakmap-shim') : WeakMap
var CACHE = new weakMap()

var SHADER_COUNTER = 0

function ShaderReference(id, src, type, shader, programs, count, cache) {
  this.id       = id
  this.src      = src
  this.type     = type
  this.shader   = shader
  this.count    = count
  this.programs = []
  this.cache    = cache
}

ShaderReference.prototype.dispose = function() {
  if(--this.count === 0) {
    var cache    = this.cache
    var gl       = cache.gl

    //Remove program references
    var programs = this.programs
    for(var i=0, n=programs.length; i<n; ++i) {
      var p = cache.programs[programs[i]]
      if(p) {
        delete cache.programs[i]
        gl.deleteProgram(p)
      }
    }

    //Remove shader reference
    gl.deleteShader(this.shader)
    delete cache.shaders[(this.type === gl.FRAGMENT_SHADER)|0][this.src]
  }
}

function ContextCache(gl) {
  this.gl       = gl
  this.shaders  = [{}, {}]
  this.programs = {}
}

var proto = ContextCache.prototype

function compileShader(gl, type, src) {
  var shader = gl.createShader(type)
  gl.shaderSource(shader, src)
  gl.compileShader(shader)
  if(!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
    var errLog = gl.getShaderInfoLog(shader)
    try {
        var fmt = formatCompilerError(errLog, src, type);
    } catch (e){
        console.warn('Failed to format compiler error: ' + e);
        throw new GLError(errLog, 'Error compiling shader:\n' + errLog)
    }
    throw new GLError(errLog, fmt.short, fmt.long)
  }
  return shader
}

proto.getShaderReference = function(type, src) {
  var gl      = this.gl
  var shaders = this.shaders[(type === gl.FRAGMENT_SHADER)|0]
  var shader  = shaders[src]
  if(!shader || !gl.isShader(shader.shader)) {
    var shaderObj = compileShader(gl, type, src)
    shader = shaders[src] = new ShaderReference(
      SHADER_COUNTER++,
      src,
      type,
      shaderObj,
      [],
      1,
      this)
  } else {
    shader.count += 1
  }
  return shader
}

function linkProgram(gl, vshader, fshader, attribs, locations) {
  var program = gl.createProgram()
  gl.attachShader(program, vshader)
  gl.attachShader(program, fshader)
  for(var i=0; i<attribs.length; ++i) {
    gl.bindAttribLocation(program, locations[i], attribs[i])
  }
  gl.linkProgram(program)
  if(!gl.getProgramParameter(program, gl.LINK_STATUS)) {
    var errLog = gl.getProgramInfoLog(program)
    throw new GLError(errLog, 'Error linking program: ' + errLog)
  }
  return program
}

proto.getProgram = function(vref, fref, attribs, locations) {
  var token = [vref.id, fref.id, attribs.join(':'), locations.join(':')].join('@')
  var prog  = this.programs[token]
  if(!prog || !this.gl.isProgram(prog)) {
    this.programs[token] = prog = linkProgram(
      this.gl,
      vref.shader,
      fref.shader,
      attribs,
      locations)
    vref.programs.push(token)
    fref.programs.push(token)
  }
  return prog
}

function getCache(gl) {
  var ctxCache = CACHE.get(gl)
  if(!ctxCache) {
    ctxCache = new ContextCache(gl)
    CACHE.set(gl, ctxCache)
  }
  return ctxCache
}

function getShaderReference(gl, type, src) {
  return getCache(gl).getShaderReference(type, src)
}

function createProgram(gl, vref, fref, attribs, locations) {
  return getCache(gl).getProgram(vref, fref, attribs, locations)
}

},{"./GLError":291,"gl-format-compiler-error":241,"weakmap-shim":533}],297:[function(_dereq_,module,exports){
'use strict'

module.exports = createSpikes2D

function GLSpikes2D(plot) {
  this.plot = plot
  this.enable = [true, true, false, false]
  this.width  = [1, 1, 1, 1]
  this.color  = [[0,0,0,1],
                 [0,0,0,1],
                 [0,0,0,1],
                 [0,0,0,1]]
  this.center = [Infinity, Infinity]
}

var proto = GLSpikes2D.prototype

proto.update = function(options) {
  options = options || {}
  this.enable = (options.enable || [true,true,false,false]).slice()
  this.width  = (options.width || [1,1,1,1]).slice()
  this.color  = (options.color || [
                  [0,0,0,1],
                  [0,0,0,1],
                  [0,0,0,1],
                  [0,0,0,1]]).map(function(x) { return x.slice() })
  this.center = (options.center || [Infinity,Infinity]).slice()
  this.plot.setOverlayDirty()
}

proto.draw = function() {
  var spikeEnable = this.enable
  var spikeWidth  = this.width
  var spikeColor  = this.color
  var spikeCenter = this.center
  var plot        = this.plot
  var line        = plot.line

  var dataBox     = plot.dataBox
  var viewPixels  = plot.viewBox

  line.bind()

  if(dataBox[0] <= spikeCenter[0] && spikeCenter[0] <= dataBox[2] &&
     dataBox[1] <= spikeCenter[1] && spikeCenter[1] <= dataBox[3]) {

    var centerX = viewPixels[0] + (spikeCenter[0] - dataBox[0]) / (dataBox[2] - dataBox[0]) * (viewPixels[2] - viewPixels[0])
    var centerY = viewPixels[1] + (spikeCenter[1] - dataBox[1]) / (dataBox[3] - dataBox[1]) * (viewPixels[3] - viewPixels[1])

    if(spikeEnable[0]) {
     line.drawLine(
       centerX, centerY,
       viewPixels[0], centerY,
       spikeWidth[0], spikeColor[0])
    }
    if(spikeEnable[1]) {
     line.drawLine(
       centerX, centerY,
       centerX, viewPixels[1],
       spikeWidth[1], spikeColor[1])
    }
    if(spikeEnable[2]) {
      line.drawLine(
        centerX, centerY,
        viewPixels[2], centerY,
        spikeWidth[2], spikeColor[2])
    }
    if(spikeEnable[3]) {
      line.drawLine(
        centerX, centerY,
        centerX, viewPixels[3],
        spikeWidth[3], spikeColor[3])
    }
  }
}

proto.dispose = function() {
  this.plot.removeOverlay(this)
}

function createSpikes2D(plot, options) {
  var spikes = new GLSpikes2D(plot)
  spikes.update(options)
  plot.addOverlay(spikes)
  return spikes
}

},{}],298:[function(_dereq_,module,exports){
'use strict'

var glslify      = _dereq_('glslify')
var createShader = _dereq_('gl-shader')

var vertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, color;\nattribute float weight;\n\nuniform mat4 model, view, projection;\nuniform vec3 coordinates[3];\nuniform vec4 colors[3];\nuniform vec2 screenShape;\nuniform float lineWidth;\n\nvarying vec4 fragColor;\n\nvoid main() {\n  vec3 vertexPosition = mix(coordinates[0],\n    mix(coordinates[2], coordinates[1], 0.5 * (position + 1.0)), abs(position));\n\n  vec4 clipPos = projection * view * model * vec4(vertexPosition, 1.0);\n  vec2 clipOffset = (projection * view * model * vec4(color, 0.0)).xy;\n  vec2 delta = weight * clipOffset * screenShape;\n  vec2 lineOffset = normalize(vec2(delta.y, -delta.x)) / screenShape;\n\n  gl_Position   = vec4(clipPos.xy + clipPos.w * 0.5 * lineWidth * lineOffset, clipPos.z, clipPos.w);\n  fragColor     = color.x * colors[0] + color.y * colors[1] + color.z * colors[2];\n}\n"])
var fragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n  gl_FragColor = fragColor;\n}"])

module.exports = function(gl) {
  return createShader(gl, vertSrc, fragSrc, null, [
    {name: 'position', type: 'vec3'},
    {name: 'color', type: 'vec3'},
    {name: 'weight', type: 'float'}
  ])
}

},{"gl-shader":290,"glslify":395}],299:[function(_dereq_,module,exports){
'use strict'

var createBuffer = _dereq_('gl-buffer')
var createVAO = _dereq_('gl-vao')
var createShader = _dereq_('./shaders/index')

module.exports = createSpikes

var identity = [1,0,0,0,
                0,1,0,0,
                0,0,1,0,
                0,0,0,1]

function AxisSpikes(gl, buffer, vao, shader) {
  this.gl         = gl
  this.buffer     = buffer
  this.vao        = vao
  this.shader     = shader
  this.pixelRatio = 1
  this.bounds     = [[-1000,-1000,-1000], [1000,1000,1000]]
  this.position   = [0,0,0]
  this.lineWidth  = [2,2,2]
  this.colors     = [[0,0,0,1], [0,0,0,1], [0,0,0,1]]
  this.enabled    = [true,true,true]
  this.drawSides  = [true,true,true]
  this.axes       = null
}

var proto = AxisSpikes.prototype

var OUTER_FACE = [0,0,0]
var INNER_FACE = [0,0,0]

var SHAPE = [0,0]

proto.isTransparent = function() {
  return false
}

proto.drawTransparent = function(camera) {}

proto.draw = function(camera) {
  var gl = this.gl
  var vao = this.vao
  var shader = this.shader

  vao.bind()
  shader.bind()

  var model      = camera.model || identity
  var view       = camera.view || identity
  var projection = camera.projection || identity

  var axis
  if(this.axes) {
    axis = this.axes.lastCubeProps.axis
  }

  var outerFace = OUTER_FACE
  var innerFace = INNER_FACE
  for(var i=0; i<3; ++i) {
    if(axis && axis[i] < 0) {
      outerFace[i] = this.bounds[0][i]
      innerFace[i] = this.bounds[1][i]
    } else {
      outerFace[i] = this.bounds[1][i]
      innerFace[i] = this.bounds[0][i]
    }
  }

  SHAPE[0] = gl.drawingBufferWidth
  SHAPE[1] = gl.drawingBufferHeight

  shader.uniforms.model       = model
  shader.uniforms.view        = view
  shader.uniforms.projection  = projection
  shader.uniforms.coordinates = [this.position, outerFace, innerFace]
  shader.uniforms.colors      = this.colors
  shader.uniforms.screenShape = SHAPE

  for(var i=0; i<3; ++i) {
    shader.uniforms.lineWidth = this.lineWidth[i] * this.pixelRatio
    if(this.enabled[i]) {
      vao.draw(gl.TRIANGLES, 6, 6*i)
      if(this.drawSides[i]) {
        vao.draw(gl.TRIANGLES, 12, 18+12*i)
      }
    }
  }

  vao.unbind()
}

proto.update = function(options) {
  if(!options) {
    return
  }
  if("bounds" in options) {
    this.bounds = options.bounds
  }
  if("position" in options) {
    this.position = options.position
  }
  if("lineWidth" in options) {
    this.lineWidth = options.lineWidth
  }
  if("colors" in options) {
    this.colors = options.colors
  }
  if("enabled" in options) {
    this.enabled = options.enabled
  }
  if("drawSides" in options) {
    this.drawSides = options.drawSides
  }
}

proto.dispose = function() {
  this.vao.dispose()
  this.buffer.dispose()
  this.shader.dispose()
}



function createSpikes(gl, options) {
  //Create buffers
  var data = [ ]

  function line(x,y,z,i,l,h) {
    var row = [x,y,z,  0,0,0,  1]
    row[i+3] = 1
    row[i] = l
    data.push.apply(data, row)
    row[6] = -1
    data.push.apply(data, row)
    row[i] = h
    data.push.apply(data, row)
    data.push.apply(data, row)
    row[6] = 1
    data.push.apply(data, row)
    row[i] = l
    data.push.apply(data, row)
  }

  line(0,0,0, 0, 0, 1)
  line(0,0,0, 1, 0, 1)
  line(0,0,0, 2, 0, 1)

  line(1,0,0,  1,  -1,1)
  line(1,0,0,  2,  -1,1)

  line(0,1,0,  0,  -1,1)
  line(0,1,0,  2,  -1,1)

  line(0,0,1,  0,  -1,1)
  line(0,0,1,  1,  -1,1)

  var buffer = createBuffer(gl, data)
  var vao = createVAO(gl, [{
    type: gl.FLOAT,
    buffer: buffer,
    size: 3,
    offset: 0,
    stride: 28
  }, {
    type: gl.FLOAT,
    buffer: buffer,
    size: 3,
    offset: 12,
    stride: 28
  }, {
    type: gl.FLOAT,
    buffer: buffer,
    size: 1,
    offset: 24,
    stride: 28
  }])

  //Create shader
  var shader = createShader(gl)
  shader.attributes.position.location = 0
  shader.attributes.color.location = 1
  shader.attributes.weight.location = 2

  //Create spike object
  var spikes = new AxisSpikes(gl, buffer, vao, shader)

  //Set parameters
  spikes.update(options)

  //Return resulting object
  return spikes
}

},{"./shaders/index":298,"gl-buffer":231,"gl-vao":313}],300:[function(_dereq_,module,exports){
arguments[4][233][0].apply(exports,arguments)
},{"barycentric":62,"dup":233,"polytope-closest-point/lib/closest_point_2d.js":467}],301:[function(_dereq_,module,exports){
var glslify       = _dereq_('glslify')

var triVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nfloat inverse(float m) {\n  return 1.0 / m;\n}\n\nmat2 inverse(mat2 m) {\n  return mat2(m[1][1],-m[0][1],\n             -m[1][0], m[0][0]) / (m[0][0]*m[1][1] - m[0][1]*m[1][0]);\n}\n\nmat3 inverse(mat3 m) {\n  float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];\n  float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];\n  float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];\n\n  float b01 = a22 * a11 - a12 * a21;\n  float b11 = -a22 * a10 + a12 * a20;\n  float b21 = a21 * a10 - a11 * a20;\n\n  float det = a00 * b01 + a01 * b11 + a02 * b21;\n\n  return mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),\n              b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),\n              b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;\n}\n\nmat4 inverse(mat4 m) {\n  float\n      a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3],\n      a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3],\n      a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3],\n      a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3],\n\n      b00 = a00 * a11 - a01 * a10,\n      b01 = a00 * a12 - a02 * a10,\n      b02 = a00 * a13 - a03 * a10,\n      b03 = a01 * a12 - a02 * a11,\n      b04 = a01 * a13 - a03 * a11,\n      b05 = a02 * a13 - a03 * a12,\n      b06 = a20 * a31 - a21 * a30,\n      b07 = a20 * a32 - a22 * a30,\n      b08 = a20 * a33 - a23 * a30,\n      b09 = a21 * a32 - a22 * a31,\n      b10 = a21 * a33 - a23 * a31,\n      b11 = a22 * a33 - a23 * a32,\n\n      det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n  return mat4(\n      a11 * b11 - a12 * b10 + a13 * b09,\n      a02 * b10 - a01 * b11 - a03 * b09,\n      a31 * b05 - a32 * b04 + a33 * b03,\n      a22 * b04 - a21 * b05 - a23 * b03,\n      a12 * b08 - a10 * b11 - a13 * b07,\n      a00 * b11 - a02 * b08 + a03 * b07,\n      a32 * b02 - a30 * b05 - a33 * b01,\n      a20 * b05 - a22 * b02 + a23 * b01,\n      a10 * b10 - a11 * b08 + a13 * b06,\n      a01 * b08 - a00 * b10 - a03 * b06,\n      a30 * b04 - a31 * b02 + a33 * b00,\n      a21 * b02 - a20 * b04 - a23 * b00,\n      a11 * b07 - a10 * b09 - a12 * b06,\n      a00 * b09 - a01 * b07 + a02 * b06,\n      a31 * b01 - a30 * b03 - a32 * b00,\n      a20 * b03 - a21 * b01 + a22 * b00) / det;\n}\n\nvec3 getOrthogonalVector(vec3 v) {\n  // Return up-vector for only-z vector.\n  // Return ax + by + cz = 0, a point that lies on the plane that has v as a normal and that isn't (0,0,0).\n  // From the above if-statement we have ||a|| > 0  U  ||b|| > 0.\n  // Assign z = 0, x = -b, y = a:\n  // a*-b + b*a + c*0 = -ba + ba + 0 = 0\n  if (v.x*v.x > v.z*v.z || v.y*v.y > v.z*v.z) {\n    return normalize(vec3(-v.y, v.x, 0.0));\n  } else {\n    return normalize(vec3(0.0, v.z, -v.y));\n  }\n}\n\n// Calculate the tube vertex and normal at the given index.\n//\n// The returned vertex is for a tube ring with its center at origin, radius of length(d), pointing in the direction of d.\n//\n// Each tube segment is made up of a ring of vertices.\n// These vertices are used to make up the triangles of the tube by connecting them together in the vertex array.\n// The indexes of tube segments run from 0 to 8.\n//\nvec3 getTubePosition(vec3 d, float index, out vec3 normal) {\n  float segmentCount = 8.0;\n\n  float angle = 2.0 * 3.14159 * (index / segmentCount);\n\n  vec3 u = getOrthogonalVector(d);\n  vec3 v = normalize(cross(u, d));\n\n  vec3 x = u * cos(angle) * length(d);\n  vec3 y = v * sin(angle) * length(d);\n  vec3 v3 = x + y;\n\n  normal = normalize(v3);\n\n  return v3;\n}\n\nattribute vec4 vector;\nattribute vec4 color, position;\nattribute vec2 uv;\nuniform float tubeScale;\n\nuniform mat4 model\n           , view\n           , projection;\nuniform vec3 eyePosition\n           , lightPosition;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data\n           , f_position;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  // Scale the vector magnitude to stay constant with\n  // model & view changes.\n  vec3 normal;\n  vec3 XYZ = getTubePosition(mat3(model) * (tubeScale * vector.w * normalize(vector.xyz)), position.w, normal);\n  vec4 tubePosition = model * vec4(position.xyz, 1.0) + vec4(XYZ, 0.0);\n  normal = normalize(normal * inverse(mat3(model)));\n\n  gl_Position      = projection * view * tubePosition;\n  f_color          = color;\n  f_normal         = normal;\n  f_data           = tubePosition.xyz;\n  f_position       = position.xyz;\n  f_eyeDirection   = eyePosition   - tubePosition.xyz;\n  f_lightDirection = lightPosition - tubePosition.xyz;\n  f_uv             = uv;\n}\n"])
var triFragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution(float x, float roughness) {\n  float NdotH = max(x, 0.0001);\n  float cos2Alpha = NdotH * NdotH;\n  float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n  float roughness2 = roughness * roughness;\n  float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n  return exp(tan2Alpha / roughness2) / denom;\n}\n\nfloat cookTorranceSpecular(\n  vec3 lightDirection,\n  vec3 viewDirection,\n  vec3 surfaceNormal,\n  float roughness,\n  float fresnel) {\n\n  float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n  float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n  //Half angle vector\n  vec3 H = normalize(lightDirection + viewDirection);\n\n  //Geometric term\n  float NdotH = max(dot(surfaceNormal, H), 0.0);\n  float VdotH = max(dot(viewDirection, H), 0.000001);\n  float LdotH = max(dot(lightDirection, H), 0.000001);\n  float G1 = (2.0 * NdotH * VdotN) / VdotH;\n  float G2 = (2.0 * NdotH * LdotN) / LdotH;\n  float G = min(1.0, min(G1, G2));\n  \n  //Distribution term\n  float D = beckmannDistribution(NdotH, roughness);\n\n  //Fresnel term\n  float F = pow(1.0 - VdotN, fresnel);\n\n  //Multiply terms and done\n  return  G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n            , fresnel\n            , kambient\n            , kdiffuse\n            , kspecular\n            , opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data\n           , f_position;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n\n  if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n\n  vec3 N = normalize(f_normal);\n  vec3 L = normalize(f_lightDirection);\n  vec3 V = normalize(f_eyeDirection);\n\n  if(!gl_FrontFacing) {\n    N = -N;\n  }\n\n  float specular = cookTorranceSpecular(L, V, N, roughness, fresnel);\n  float diffuse  = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n  vec4 surfaceColor =  texture2D(texture, f_uv);\n  vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular,  1.0);\n\n  gl_FragColor = litColor * opacity;\n}"])
var pickVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nvec3 getOrthogonalVector(vec3 v) {\n  // Return up-vector for only-z vector.\n  // Return ax + by + cz = 0, a point that lies on the plane that has v as a normal and that isn't (0,0,0).\n  // From the above if-statement we have ||a|| > 0  U  ||b|| > 0.\n  // Assign z = 0, x = -b, y = a:\n  // a*-b + b*a + c*0 = -ba + ba + 0 = 0\n  if (v.x*v.x > v.z*v.z || v.y*v.y > v.z*v.z) {\n    return normalize(vec3(-v.y, v.x, 0.0));\n  } else {\n    return normalize(vec3(0.0, v.z, -v.y));\n  }\n}\n\n// Calculate the tube vertex and normal at the given index.\n//\n// The returned vertex is for a tube ring with its center at origin, radius of length(d), pointing in the direction of d.\n//\n// Each tube segment is made up of a ring of vertices.\n// These vertices are used to make up the triangles of the tube by connecting them together in the vertex array.\n// The indexes of tube segments run from 0 to 8.\n//\nvec3 getTubePosition(vec3 d, float index, out vec3 normal) {\n  float segmentCount = 8.0;\n\n  float angle = 2.0 * 3.14159 * (index / segmentCount);\n\n  vec3 u = getOrthogonalVector(d);\n  vec3 v = normalize(cross(u, d));\n\n  vec3 x = u * cos(angle) * length(d);\n  vec3 y = v * sin(angle) * length(d);\n  vec3 v3 = x + y;\n\n  normal = normalize(v3);\n\n  return v3;\n}\n\nattribute vec4 vector;\nattribute vec4 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform float tubeScale;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  vec3 normal;\n  vec3 XYZ = getTubePosition(mat3(model) * (tubeScale * vector.w * normalize(vector.xyz)), position.w, normal);\n  vec4 tubePosition = model * vec4(position.xyz, 1.0) + vec4(XYZ, 0.0);\n\n  gl_Position = projection * view * tubePosition;\n  f_id        = id;\n  f_position  = position.xyz;\n}\n"])
var pickFragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3  clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n\n  gl_FragColor = vec4(pickId, f_id.xyz);\n}"])

exports.meshShader = {
  vertex:   triVertSrc,
  fragment: triFragSrc,
  attributes: [
    {name: 'position', type: 'vec4'},
    {name: 'normal', type: 'vec3'},
    {name: 'color', type: 'vec4'},
    {name: 'uv', type: 'vec2'},
    {name: 'vector', type: 'vec4'}
  ]
}
exports.pickShader = {
  vertex:   pickVertSrc,
  fragment: pickFragSrc,
  attributes: [
    {name: 'position', type: 'vec4'},
    {name: 'id', type: 'vec4'},
    {name: 'vector', type: 'vec4'}
  ]
}

},{"glslify":395}],302:[function(_dereq_,module,exports){
'use strict'

var DEFAULT_VERTEX_NORMALS_EPSILON = 1e-6; // may be too large if triangles are very small
var DEFAULT_FACE_NORMALS_EPSILON = 1e-6;

var createShader  = _dereq_('gl-shader')
var createBuffer  = _dereq_('gl-buffer')
var createVAO     = _dereq_('gl-vao')
var createTexture = _dereq_('gl-texture2d')
var normals       = _dereq_('normals')
var multiply      = _dereq_('gl-mat4/multiply')
var invert        = _dereq_('gl-mat4/invert')
var ndarray       = _dereq_('ndarray')
var colormap      = _dereq_('colormap')
var getContour    = _dereq_('simplicial-complex-contour')
var pool          = _dereq_('typedarray-pool')
var shaders       = _dereq_('./shaders')
var closestPoint  = _dereq_('./closest-point')

var meshShader    = shaders.meshShader
var pickShader    = shaders.pickShader

var identityMatrix = [
  1,0,0,0,
  0,1,0,0,
  0,0,1,0,
  0,0,0,1]

function SimplicialMesh(gl
  , texture
  , triShader
  , lineShader
  , pointShader
  , pickShader
  , pointPickShader
  , contourShader
  , trianglePositions
  , triangleVectors
  , triangleIds
  , triangleColors
  , triangleUVs
  , triangleNormals
  , triangleVAO
  , edgePositions
  , edgeIds
  , edgeColors
  , edgeUVs
  , edgeVAO
  , pointPositions
  , pointIds
  , pointColors
  , pointUVs
  , pointSizes
  , pointVAO
  , contourPositions
  , contourVAO) {

  this.gl                = gl
  this.cells             = []
  this.positions         = []
  this.intensity         = []
  this.texture           = texture
  this.dirty             = true

  this.triShader         = triShader
  this.lineShader        = lineShader
  this.pointShader       = pointShader
  this.pickShader        = pickShader
  this.pointPickShader   = pointPickShader
  this.contourShader     = contourShader

  this.trianglePositions = trianglePositions
  this.triangleVectors   = triangleVectors
  this.triangleColors    = triangleColors
  this.triangleNormals   = triangleNormals
  this.triangleUVs       = triangleUVs
  this.triangleIds       = triangleIds
  this.triangleVAO       = triangleVAO
  this.triangleCount     = 0

  this.lineWidth         = 1
  this.edgePositions     = edgePositions
  this.edgeColors        = edgeColors
  this.edgeUVs           = edgeUVs
  this.edgeIds           = edgeIds
  this.edgeVAO           = edgeVAO
  this.edgeCount         = 0

  this.pointPositions    = pointPositions
  this.pointColors       = pointColors
  this.pointUVs          = pointUVs
  this.pointSizes        = pointSizes
  this.pointIds          = pointIds
  this.pointVAO          = pointVAO
  this.pointCount        = 0

  this.contourLineWidth  = 1
  this.contourPositions  = contourPositions
  this.contourVAO        = contourVAO
  this.contourCount      = 0
  this.contourColor      = [0,0,0]
  this.contourEnable     = false

  this.pickId            = 1
  this.bounds            = [
    [ Infinity, Infinity, Infinity],
    [-Infinity,-Infinity,-Infinity] ]
  this.clipBounds        = [
    [-Infinity,-Infinity,-Infinity],
    [ Infinity, Infinity, Infinity] ]

  this.lightPosition = [1e5, 1e5, 0]
  this.ambientLight  = 0.8
  this.diffuseLight  = 0.8
  this.specularLight = 2.0
  this.roughness     = 0.5
  this.fresnel       = 1.5

  this.opacity       = 1.0

  this.tubeScale     = 1.0

  this._model       = identityMatrix
  this._view        = identityMatrix
  this._projection  = identityMatrix
  this._resolution  = [1,1]
}

var proto = SimplicialMesh.prototype

proto.isOpaque = function() {
  return this.opacity >= 1
}

proto.isTransparent = function() {
  return this.opacity < 1
}

proto.pickSlots = 1

proto.setPickBase = function(id) {
  this.pickId = id
}

function genColormap(param) {
  var colors = colormap({
      colormap: param
    , nshades:  256
    , format:  'rgba'
  })

  var result = new Uint8Array(256*4)
  for(var i=0; i<256; ++i) {
    var c = colors[i]
    for(var j=0; j<3; ++j) {
      result[4*i+j] = c[j]
    }
    result[4*i+3] = c[3]*255
  }

  return ndarray(result, [256,256,4], [4,0,1])
}

function unpackIntensity(cells, numVerts, cellIntensity) {
  var result = new Array(numVerts)
  for(var i=0; i<numVerts; ++i) {
    result[i] = 0
  }
  var numCells = cells.length
  for(var i=0; i<numCells; ++i) {
    var c = cells[i]
    for(var j=0; j<c.length; ++j) {
      result[c[j]] = cellIntensity[i]
    }
  }
  return result
}

function takeZComponent(array) {
  var n = array.length
  var result = new Array(n)
  for(var i=0; i<n; ++i) {
    result[i] = array[i][2]
  }
  return result
}

proto.highlight = function(selection) {
  if(!selection || !this.contourEnable) {
    this.contourCount = 0
    return
  }
  var level = getContour(this.cells, this.intensity, selection.intensity)
  var cells         = level.cells
  var vertexIds     = level.vertexIds
  var vertexWeights = level.vertexWeights
  var numCells = cells.length
  var result = pool.mallocFloat32(2 * 3 * numCells)
  var ptr = 0
  for(var i=0; i<numCells; ++i) {
    var c = cells[i]
    for(var j=0; j<2; ++j) {
      var v = c[0]
      if(c.length === 2) {
        v = c[j]
      }
      var a = vertexIds[v][0]
      var b = vertexIds[v][1]
      var w = vertexWeights[v]
      var wi = 1.0 - w
      var pa = this.positions[a]
      var pb = this.positions[b]
      for(var k=0; k<3; ++k) {
        result[ptr++] = w * pa[k] + wi * pb[k]
      }
    }
  }
  this.contourCount = (ptr / 3)|0
  this.contourPositions.update(result.subarray(0, ptr))
  pool.free(result)
}

proto.update = function(params) {
  params = params || {}
  var gl = this.gl

  this.dirty = true

  if('contourEnable' in params) {
    this.contourEnable = params.contourEnable
  }
  if('contourColor' in params) {
    this.contourColor = params.contourColor
  }
  if('lineWidth' in params) {
    this.lineWidth = params.lineWidth
  }
  if('lightPosition' in params) {
    this.lightPosition = params.lightPosition
  }
  if('opacity' in params) {
    this.opacity = params.opacity
  }
  if('ambient' in params) {
    this.ambientLight  = params.ambient
  }
  if('diffuse' in params) {
    this.diffuseLight = params.diffuse
  }
  if('specular' in params) {
    this.specularLight = params.specular
  }
  if('roughness' in params) {
    this.roughness = params.roughness
  }
  if('fresnel' in params) {
    this.fresnel = params.fresnel
  }

  if(params.texture) {
    this.texture.dispose()
    this.texture = createTexture(gl, params.texture)
  } else if (params.colormap) {
    this.texture.shape = [256,256]
    this.texture.minFilter = gl.LINEAR_MIPMAP_LINEAR
    this.texture.magFilter = gl.LINEAR
    this.texture.setPixels(genColormap(params.colormap))
    this.texture.generateMipmap()
  }

  var cells = params.cells
  var positions = params.positions
  var vectors = params.vectors

  if(!positions || !cells || !vectors) {
    return
  }

  if (params.tubeScale !== undefined) {
    this.tubeScale = params.tubeScale;
  }

  var tPos = []
  var tVec = []
  var tCol = []
  var tNor = []
  var tUVs = []
  var tIds = []

  var ePos = []
  var eCol = []
  var eUVs = []
  var eIds = []

  var pPos = []
  var pCol = []
  var pUVs = []
  var pSiz = []
  var pIds = []

  //Save geometry data for picking calculations
  this.cells     = cells
  this.positions = positions
  this.vectors   = vectors

  //Compute normals
  var vertexNormals = params.vertexNormals
  var cellNormals   = params.cellNormals
  var vertexNormalsEpsilon = params.vertexNormalsEpsilon === void(0) ? DEFAULT_VERTEX_NORMALS_EPSILON : params.vertexNormalsEpsilon
  var faceNormalsEpsilon = params.faceNormalsEpsilon === void(0) ? DEFAULT_FACE_NORMALS_EPSILON : params.faceNormalsEpsilon
  if(params.useFacetNormals && !cellNormals) {
    cellNormals = normals.faceNormals(cells, positions, faceNormalsEpsilon)
  }
  if(!cellNormals && !vertexNormals) {
    vertexNormals = normals.vertexNormals(cells, positions, vertexNormalsEpsilon)
  }

  //Compute colors
  var vertexColors    = params.vertexColors
  var cellColors      = params.cellColors
  var meshColor       = params.meshColor || [1,1,1,1]

  //UVs
  var vertexUVs       = params.vertexUVs
  var vertexIntensity = params.vertexIntensity
  var cellUVs         = params.cellUVs
  var cellIntensity   = params.cellIntensity

  var intensityLo     = Infinity
  var intensityHi     = -Infinity
  if(!vertexUVs && !cellUVs) {
    if(vertexIntensity) {
      if(params.vertexIntensityBounds) {
        intensityLo = +params.vertexIntensityBounds[0]
        intensityHi = +params.vertexIntensityBounds[1]
      } else {
        for(var i=0; i<vertexIntensity.length; ++i) {
          var f = vertexIntensity[i]
          intensityLo = Math.min(intensityLo, f)
          intensityHi = Math.max(intensityHi, f)
        }
      }
    } else if(cellIntensity) {
      for(var i=0; i<cellIntensity.length; ++i) {
        var f = cellIntensity[i]
        intensityLo = Math.min(intensityLo, f)
        intensityHi = Math.max(intensityHi, f)
      }
    } else {
      for(var i=0; i<positions.length; ++i) {
        var f = positions[i][2]
        intensityLo = Math.min(intensityLo, f)
        intensityHi = Math.max(intensityHi, f)
      }
    }
  }

  if(vertexIntensity) {
    this.intensity = vertexIntensity
  } else if(cellIntensity) {
    this.intensity = unpackIntensity(cells, positions.length, cellIntensity)
  } else {
    this.intensity = takeZComponent(positions)
  }

  //Point size
  var pointSizes      = params.pointSizes
  var meshPointSize   = params.pointSize || 1.0

  //Update bounds
  this.bounds       = [[Infinity,Infinity,Infinity], [-Infinity,-Infinity,-Infinity]]
  for(var i=0; i<positions.length; ++i) {
    var p = positions[i]
    for(var j=0; j<3; ++j) {
      if(isNaN(p[j]) || !isFinite(p[j])) {
        continue
      }
      this.bounds[0][j] = Math.min(this.bounds[0][j], p[j])
      this.bounds[1][j] = Math.max(this.bounds[1][j], p[j])
    }
  }

  //Pack cells into buffers
  var triangleCount = 0
  var edgeCount = 0
  var pointCount = 0

fill_loop:
  for(var i=0; i<cells.length; ++i) {
    var cell = cells[i]
    switch(cell.length) {
      case 1:

        var v = cell[0]
        var p = positions[v]

        //Check NaNs
        for(var j=0; j<3; ++j) {
          if(isNaN(p[j]) || !isFinite(p[j])) {
            continue fill_loop
          }
        }

        pPos.push(p[0], p[1], p[2], p[3])

        var c
        if(vertexColors) {
          c = vertexColors[v]
        } else if(cellColors) {
          c = cellColors[i]
        } else {
          c = meshColor
        }
        if(c.length === 3) {
          pCol.push(c[0], c[1], c[2], 1)
        } else {
          pCol.push(c[0], c[1], c[2], c[3])
        }

        var uv
        if(vertexUVs) {
          uv = vertexUVs[v]
        } else if(vertexIntensity) {
          uv = [
            (vertexIntensity[v] - intensityLo) /
            (intensityHi - intensityLo), 0]
        } else if(cellUVs) {
          uv = cellUVs[i]
        } else if(cellIntensity) {
          uv = [
            (cellIntensity[i] - intensityLo) /
            (intensityHi - intensityLo), 0]
        } else {
          uv = [
            (p[2] - intensityLo) /
            (intensityHi - intensityLo), 0]
        }
        pUVs.push(uv[0], uv[1])

        if(pointSizes) {
          pSiz.push(pointSizes[v])
        } else {
          pSiz.push(meshPointSize)
        }

        pIds.push(i)

        pointCount += 1
      break

      case 2:

        //Check NaNs
        for(var j=0; j<2; ++j) {
          var v = cell[j]
          var p = positions[v]
          for(var k=0; k<3; ++k) {
            if(isNaN(p[k]) || !isFinite(p[k])) {
              continue fill_loop
            }
          }
        }

        for(var j=0; j<2; ++j) {
          var v = cell[j]
          var p = positions[v]

          ePos.push(p[0], p[1], p[2])

          var c
          if(vertexColors) {
            c = vertexColors[v]
          } else if(cellColors) {
            c = cellColors[i]
          } else {
            c = meshColor
          }
          if(c.length === 3) {
            eCol.push(c[0], c[1], c[2], 1)
          } else {
            eCol.push(c[0], c[1], c[2], c[3])
          }

          var uv
          if(vertexUVs) {
            uv = vertexUVs[v]
          } else if(vertexIntensity) {
            uv = [
              (vertexIntensity[v] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else if(cellUVs) {
            uv = cellUVs[i]
          } else if(cellIntensity) {
            uv = [
              (cellIntensity[i] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else {
            uv = [
              (p[2] - intensityLo) /
              (intensityHi - intensityLo), 0]
          }
          eUVs.push(uv[0], uv[1])

          eIds.push(i)
        }
        edgeCount += 1
      break

      case 3:
        //Check NaNs
        for(var j=0; j<3; ++j) {
          var v = cell[j]
          var p = positions[v]
          for(var k=0; k<3; ++k) {
            if(isNaN(p[k]) || !isFinite(p[k])) {
              continue fill_loop
            }
          }
        }

        for(var j=0; j<3; ++j) {
          var v = cell[j]

          var p = positions[v]
          tPos.push(p[0], p[1], p[2], p[3])

          var w = vectors[v]
          tVec.push(w[0], w[1], w[2], w[3]);

          var c
          if(vertexColors) {
            c = vertexColors[v]
          } else if(cellColors) {
            c = cellColors[i]
          } else {
            c = meshColor
          }
          if(c.length === 3) {
            tCol.push(c[0], c[1], c[2], 1)
          } else {
            tCol.push(c[0], c[1], c[2], c[3])
          }

          var uv
          if(vertexUVs) {
            uv = vertexUVs[v]
          } else if(vertexIntensity) {
            uv = [
              (vertexIntensity[v] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else if(cellUVs) {
            uv = cellUVs[i]
          } else if(cellIntensity) {
            uv = [
              (cellIntensity[i] - intensityLo) /
              (intensityHi - intensityLo), 0]
          } else {
            uv = [
              (p[2] - intensityLo) /
              (intensityHi - intensityLo), 0]
          }
          tUVs.push(uv[0], uv[1])

          var q
          if(vertexNormals) {
            q = vertexNormals[v]
          } else {
            q = cellNormals[i]
          }
          tNor.push(q[0], q[1], q[2])

          tIds.push(i)
        }
        triangleCount += 1
      break

      default:
      break
    }
  }

  this.pointCount     = pointCount
  this.edgeCount      = edgeCount
  this.triangleCount  = triangleCount

  this.pointPositions.update(pPos)
  this.pointColors.update(pCol)
  this.pointUVs.update(pUVs)
  this.pointSizes.update(pSiz)
  this.pointIds.update(new Uint32Array(pIds))

  this.edgePositions.update(ePos)
  this.edgeColors.update(eCol)
  this.edgeUVs.update(eUVs)
  this.edgeIds.update(new Uint32Array(eIds))

  this.trianglePositions.update(tPos)
  this.triangleVectors.update(tVec)
  this.triangleColors.update(tCol)
  this.triangleUVs.update(tUVs)
  this.triangleNormals.update(tNor)
  this.triangleIds.update(new Uint32Array(tIds))
}

proto.drawTransparent = proto.draw = function(params) {
  params = params || {}
  var gl          = this.gl
  var model       = params.model      || identityMatrix
  var view        = params.view       || identityMatrix
  var projection  = params.projection || identityMatrix

  var clipBounds = [[-1e6,-1e6,-1e6],[1e6,1e6,1e6]]
  for(var i=0; i<3; ++i) {
    clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i])
    clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i])
  }

  var uniforms = {
    model:      model,
    view:       view,
    projection: projection,

    clipBounds: clipBounds,

    kambient:   this.ambientLight,
    kdiffuse:   this.diffuseLight,
    kspecular:  this.specularLight,
    roughness:  this.roughness,
    fresnel:    this.fresnel,

    eyePosition:   [0,0,0],
    lightPosition: [0,0,0],

    opacity:  this.opacity,

    tubeScale: this.tubeScale,

    contourColor: this.contourColor,

    texture:    0
  }

  this.texture.bind(0)

  var invCameraMatrix = new Array(16)
  multiply(invCameraMatrix, uniforms.view, uniforms.model)
  multiply(invCameraMatrix, uniforms.projection, invCameraMatrix)
  invert(invCameraMatrix, invCameraMatrix)

  for(var i=0; i<3; ++i) {
    uniforms.eyePosition[i] = invCameraMatrix[12+i] / invCameraMatrix[15]
  }

  var w = invCameraMatrix[15]
  for(var i=0; i<3; ++i) {
    w += this.lightPosition[i] * invCameraMatrix[4*i+3]
  }
  for(var i=0; i<3; ++i) {
    var s = invCameraMatrix[12+i]
    for(var j=0; j<3; ++j) {
      s += invCameraMatrix[4*j+i] * this.lightPosition[j]
    }
    uniforms.lightPosition[i] = s / w
  }

  if(this.triangleCount > 0) {
    var shader = this.triShader
    shader.bind()
    shader.uniforms = uniforms

    this.triangleVAO.bind()
    gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3)
    this.triangleVAO.unbind()
  }

  if(this.edgeCount > 0 && this.lineWidth > 0) {
    var shader = this.lineShader
    shader.bind()
    shader.uniforms = uniforms

    this.edgeVAO.bind()
    gl.lineWidth(this.lineWidth)
    gl.drawArrays(gl.LINES, 0, this.edgeCount*2)
    this.edgeVAO.unbind()
  }

  if(this.pointCount > 0) {
    var shader = this.pointShader
    shader.bind()
    shader.uniforms = uniforms

    this.pointVAO.bind()
    gl.drawArrays(gl.POINTS, 0, this.pointCount)
    this.pointVAO.unbind()
  }

  if(this.contourEnable && this.contourCount > 0 && this.contourLineWidth > 0) {
    var shader = this.contourShader
    shader.bind()
    shader.uniforms = uniforms

    this.contourVAO.bind()
    gl.drawArrays(gl.LINES, 0, this.contourCount)
    this.contourVAO.unbind()
  }
}

proto.drawPick = function(params) {
  params = params || {}

  var gl         = this.gl

  var model      = params.model      || identityMatrix
  var view       = params.view       || identityMatrix
  var projection = params.projection || identityMatrix

  var clipBounds = [[-1e6,-1e6,-1e6],[1e6,1e6,1e6]]
  for(var i=0; i<3; ++i) {
    clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i])
    clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i])
  }

  //Save camera parameters
  this._model      = [].slice.call(model)
  this._view       = [].slice.call(view)
  this._projection = [].slice.call(projection)
  this._resolution = [gl.drawingBufferWidth, gl.drawingBufferHeight]

  var uniforms = {
    model:      model,
    view:       view,
    projection: projection,
    clipBounds: clipBounds,

    tubeScale: this.tubeScale,

    pickId:     this.pickId / 255.0,
  }

  var shader = this.pickShader
  shader.bind()
  shader.uniforms = uniforms

  if(this.triangleCount > 0) {
    this.triangleVAO.bind()
    gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3)
    this.triangleVAO.unbind()
  }

  if(this.edgeCount > 0) {
    this.edgeVAO.bind()
    gl.lineWidth(this.lineWidth)
    gl.drawArrays(gl.LINES, 0, this.edgeCount*2)
    this.edgeVAO.unbind()
  }

  if(this.pointCount > 0) {
    var shader = this.pointPickShader
    shader.bind()
    shader.uniforms = uniforms

    this.pointVAO.bind()
    gl.drawArrays(gl.POINTS, 0, this.pointCount)
    this.pointVAO.unbind()
  }
}


proto.pick = function(pickData) {
  if(!pickData) {
    return null
  }
  if(pickData.id !== this.pickId) {
    return null
  }

  var cellId = pickData.value[0] + 256*pickData.value[1] + 65536*pickData.value[2]
  var cell = this.cells[cellId]

  var pos = this.positions[cell[1]].slice(0, 3)
  var intensity = this.intensity[cell[1]]
  var velocity = this.vectors[cell[1]].slice(0, 3)
  var divergence = this.vectors[cell[1]][3]

  return {
    index: cellId,
    position: pos,
    intensity: intensity,
    velocity: velocity,
    divergence: divergence,
    dataCoordinate: pos
  }
}


proto.dispose = function() {
  this.texture.dispose()

  this.triShader.dispose()
  // this.lineShader.dispose()
  // this.pointShader.dispose()
  this.pickShader.dispose()
  // this.pointPickShader.dispose()

  this.triangleVAO.dispose()
  this.trianglePositions.dispose()
  this.triangleVectors.dispose()
  this.triangleColors.dispose()
  this.triangleUVs.dispose()
  this.triangleNormals.dispose()
  this.triangleIds.dispose()

  this.edgeVAO.dispose()
  this.edgePositions.dispose()
  this.edgeColors.dispose()
  this.edgeUVs.dispose()
  this.edgeIds.dispose()

  this.pointVAO.dispose()
  this.pointPositions.dispose()
  this.pointColors.dispose()
  this.pointUVs.dispose()
  this.pointSizes.dispose()
  this.pointIds.dispose()

  this.contourVAO.dispose()
  this.contourPositions.dispose()
  // this.contourShader.dispose()
}

function createMeshShader(gl) {
  var shader = createShader(gl, meshShader.vertex, meshShader.fragment, null, meshShader.attributes)
  shader.attributes.position.location = 0
  shader.attributes.color.location    = 2
  shader.attributes.uv.location       = 3
  shader.attributes.vector.location   = 5
  return shader
}

function createWireShader(gl) {
  var shader = createShader(gl, wireShader.vertex, wireShader.fragment)
  shader.attributes.position.location = 0
  shader.attributes.color.location    = 2
  shader.attributes.uv.location       = 3
  return shader
}

function createPointShader(gl) {
  var shader = createShader(gl, pointShader.vertex, pointShader.fragment)
  shader.attributes.position.location  = 0
  shader.attributes.color.location     = 2
  shader.attributes.uv.location        = 3
  shader.attributes.pointSize.location = 4
  return shader
}

function createPickShader(gl) {
  var shader = createShader(gl, pickShader.vertex, pickShader.fragment, null, pickShader.attributes)
  shader.attributes.position.location = 0
  shader.attributes.id.location       = 1
  shader.attributes.vector.location   = 5
  return shader
}

function createPointPickShader(gl) {
  var shader = createShader(gl, pointPickShader.vertex, pointPickShader.fragment)
  shader.attributes.position.location  = 0
  shader.attributes.id.location        = 1
  shader.attributes.pointSize.location = 4
  return shader
}

function createContourShader(gl) {
  var shader = createShader(gl, contourShader.vertex, contourShader.fragment)
  shader.attributes.position.location = 0
  return shader
}

function createSimplicialMesh(gl, params) {
  if (arguments.length === 1) {
    params = gl;
    gl = params.gl;
  }

  var triShader       = params.triShader || createMeshShader(gl)
  var lineShader      = null; //createWireShader(gl)
  var pointShader     = null; //createPointShader(gl)
  var pickShader      = createPickShader(gl)
  var pointPickShader = null; //createPointPickShader(gl)
  var contourShader   = null; //createContourShader(gl)

  var meshTexture       = createTexture(gl,
    ndarray(new Uint8Array([255,255,255,255]), [1,1,4]))
  meshTexture.generateMipmap()
  meshTexture.minFilter = gl.LINEAR_MIPMAP_LINEAR
  meshTexture.magFilter = gl.LINEAR

  var trianglePositions = createBuffer(gl)
  var triangleVectors   = createBuffer(gl)
  var triangleColors    = createBuffer(gl)
  var triangleUVs       = createBuffer(gl)
  var triangleNormals   = createBuffer(gl)
  var triangleIds       = createBuffer(gl)
  var triangleVAO       = createVAO(gl, [
    { buffer: trianglePositions,
      type: gl.FLOAT,
      size: 4
    },
    { buffer: triangleIds,
      type: gl.UNSIGNED_BYTE,
      size: 4,
      normalized: true
    },
    { buffer: triangleColors,
      type: gl.FLOAT,
      size: 4
    },
    { buffer: triangleUVs,
      type: gl.FLOAT,
      size: 2
    },
    { buffer: triangleNormals,
      type: gl.FLOAT,
      size: 3
    },
    { buffer: triangleVectors,
      type: gl.FLOAT,
      size: 4
    }
  ])

  var edgePositions = createBuffer(gl)
  var edgeColors    = createBuffer(gl)
  var edgeUVs       = createBuffer(gl)
  var edgeIds       = createBuffer(gl)
  var edgeVAO       = createVAO(gl, [
    { buffer: edgePositions,
      type: gl.FLOAT,
      size: 3
    },
    { buffer: edgeIds,
      type: gl.UNSIGNED_BYTE,
      size: 4,
      normalized: true
    },
    { buffer: edgeColors,
      type: gl.FLOAT,
      size: 4
    },
    { buffer: edgeUVs,
      type: gl.FLOAT,
      size: 2
    }
  ])

  var pointPositions  = createBuffer(gl)
  var pointColors     = createBuffer(gl)
  var pointUVs        = createBuffer(gl)
  var pointSizes      = createBuffer(gl)
  var pointIds        = createBuffer(gl)
  var pointVAO        = createVAO(gl, [
    { buffer: pointPositions,
      type: gl.FLOAT,
      size: 3
    },
    { buffer: pointIds,
      type: gl.UNSIGNED_BYTE,
      size: 4,
      normalized: true
    },
    { buffer: pointColors,
      type: gl.FLOAT,
      size: 4
    },
    { buffer: pointUVs,
      type: gl.FLOAT,
      size: 2
    },
    { buffer: pointSizes,
      type: gl.FLOAT,
      size: 1
    }
  ])

  var contourPositions = createBuffer(gl)
  var contourVAO       = createVAO(gl, [
    { buffer: contourPositions,
      type:   gl.FLOAT,
      size:   3
    }])

  var mesh = new SimplicialMesh(gl
    , meshTexture
    , triShader
    , lineShader
    , pointShader
    , pickShader
    , pointPickShader
    , contourShader
    , trianglePositions
    , triangleVectors
    , triangleIds
    , triangleColors
    , triangleUVs
    , triangleNormals
    , triangleVAO
    , edgePositions
    , edgeIds
    , edgeColors
    , edgeUVs
    , edgeVAO
    , pointPositions
    , pointIds
    , pointColors
    , pointUVs
    , pointSizes
    , pointVAO
    , contourPositions
    , contourVAO)

  mesh.update(params)

  return mesh
}

module.exports = createSimplicialMesh

},{"./closest-point":300,"./shaders":301,"colormap":115,"gl-buffer":231,"gl-mat4/invert":256,"gl-mat4/multiply":258,"gl-shader":290,"gl-texture2d":308,"gl-vao":313,"ndarray":436,"normals":439,"simplicial-complex-contour":496,"typedarray-pool":523}],303:[function(_dereq_,module,exports){
"use strict";

var vec3 = _dereq_('gl-vec3');
var vec4 = _dereq_('gl-vec4');

var streamToTube = function(stream, maxDivergence, minDistance, maxNorm) {
	var points = stream.points;
	var velocities = stream.velocities;
	var divergences = stream.divergences;

	var p, fwd, r, u, v, up;
	up = vec3.set(vec3.create(), 0, 1, 0);
	u = vec3.create();
	v = vec3.create();
	var p2 = vec3.create();

	var verts = [];
	var faces = [];
	var vectors = [];
	var previousVerts = [];
	var currentVerts = [];
	var intensities = [];
	var previousIntensity = 0;
	var currentIntensity = 0;
	var currentVector = vec4.create();
	var previousVector = vec4.create();

	var facets = 8;

	for (var i = 0; i < points.length; i++) {
		p = points[i];
		fwd = velocities[i];
		r = divergences[i];
		if (maxDivergence === 0) {
			r = minDistance * 0.05;
		}
		currentIntensity = vec3.length(fwd) / maxNorm;
		currentVector = vec4.create();
		vec3.copy(currentVector, fwd);
		currentVector[3] = r;
		
		for (var a = 0; a < facets; a++) {
			currentVerts[a] = [p[0], p[1], p[2], a];
		}
		if (previousVerts.length > 0) {
			for (var a = 0; a < facets; a++) {
				var a1 = (a+1) % facets;
				verts.push(
					previousVerts[a],
					currentVerts[a],
					currentVerts[a1],

					currentVerts[a1],
					previousVerts[a1],
					previousVerts[a]
				);
				vectors.push(
					previousVector,
					currentVector,
					currentVector,

					currentVector,
					previousVector,
					previousVector
				);
				intensities.push(
					previousIntensity,
					currentIntensity,
					currentIntensity,

					currentIntensity,
					previousIntensity,
					previousIntensity
				);
				faces.push(
					[verts.length-6, verts.length-5, verts.length-4],
					[verts.length-3, verts.length-2, verts.length-1]
				);
			}
		}
		var tmp = previousVerts;
		previousVerts = currentVerts;
		currentVerts = tmp;
		tmp = previousVector;
		previousVector = currentVector;
		currentVector = tmp;
		tmp = previousIntensity;
		previousIntensity = currentIntensity;
		currentIntensity = tmp;
	}
	return {
		positions: verts,
		cells: faces,
		vectors: vectors,
		vertexIntensity: intensities
	};

};

var createTubes = function(streams, colormap, maxDivergence, minDistance) {

	var maxNorm = 0;
	for (var i=0; i<streams.length; i++) {
		var velocities = streams[i].velocities;
		for (var j=0; j<velocities.length; j++) {
			var norm = vec3.length(velocities[j]);
			if (norm > maxNorm) {
				maxNorm = norm;
			}
		}
	}

	var tubes = streams.map(function(s) {
		return streamToTube(s, maxDivergence, minDistance, maxNorm);
	});

	var positions = [];
	var cells = [];
	var vectors = [];
	var vertexIntensity = [];
	for (var i=0; i < tubes.length; i++) {
		var tube = tubes[i];
		var offset = positions.length;
		positions = positions.concat(tube.positions);
		vectors = vectors.concat(tube.vectors);
		vertexIntensity = vertexIntensity.concat(tube.vertexIntensity);
		for (var j=0; j<tube.cells.length; j++) {
			var cell = tube.cells[j];
			var newCell = [];
			cells.push(newCell);
			for (var k=0; k<cell.length; k++) {
				newCell.push(cell[k] + offset);
			}
		}
	}
	return {
		positions: positions,
		cells: cells,
		vectors: vectors,
		vertexIntensity: vertexIntensity,
		colormap: colormap
	};
};

var defaultGetDivergence = function(p, v0) {
	var dp = vec3.create();
	var e = 1/10000;

	vec3.add(dp, p, [e, 0, 0]);
	var vx = this.getVelocity(dp);
	vec3.subtract(vx, vx, v0);
	vec3.scale(vx, vx, 1/e);

	vec3.add(dp, p, [0, e, 0]);
	var vy = this.getVelocity(dp);
	vec3.subtract(vy, vy, v0);
	vec3.scale(vy, vy, 1/e);

	vec3.add(dp, p, [0, 0, e]);
	var vz = this.getVelocity(dp);
	vec3.subtract(vz, vz, v0);
	vec3.scale(vz, vz, 1/e);

	vec3.add(dp, vx, vy);
	vec3.add(dp, dp, vz);
	return dp;
};

var defaultGetVelocity = function(p) {
    var u = sampleMeshgrid(p, this.vectors, this.meshgrid, this.clampBorders);
    return u;
};


var findLastSmallerIndex = function(points, v) {
  for (var i=0; i<points.length; i++) {
  	var p = points[i];
  	if (p === v) return i;
    if (p > v) return i-1;
  }
  return i;
};

var tmp = vec3.create();
var tmp2 = vec3.create();

var clamp = function(v, min, max) {
	return v < min ? min : (v > max ? max : v);
};

var sampleMeshgrid = function(point, array, meshgrid, clampOverflow) {
	var x = point[0];
	var y = point[1];
	var z = point[2];

	var w = meshgrid[0].length;
	var h = meshgrid[1].length;
	var d = meshgrid[2].length;

	// Find the index of the nearest smaller value in the meshgrid for each coordinate of (x,y,z).
	// The nearest smaller value index for x is the index x0 such that
	// meshgrid[0][x0] < x and for all x1 > x0, meshgrid[0][x1] >= x.
	var x0 = findLastSmallerIndex(meshgrid[0], x);
	var y0 = findLastSmallerIndex(meshgrid[1], y);
	var z0 = findLastSmallerIndex(meshgrid[2], z);

	// Get the nearest larger meshgrid value indices.
	// From the above "nearest smaller value", we know that
	//   meshgrid[0][x0] < x
	//   meshgrid[0][x0+1] >= x
	var x1 = x0 + 1;
	var y1 = y0 + 1;
	var z1 = z0 + 1;

	if (meshgrid[0][x0] === x) x1 = x0;
	if (meshgrid[1][y0] === y) y1 = y0;
	if (meshgrid[2][z0] === z) z1 = z0;

	if (clampOverflow) {
		x0 = clamp(x0, 0, w-1);
		x1 = clamp(x1, 0, w-1);
		y0 = clamp(y0, 0, h-1);
		y1 = clamp(y1, 0, h-1);
		z0 = clamp(z0, 0, d-1);
		z1 = clamp(z1, 0, d-1);
	}

	// Reject points outside the meshgrid, return a zero vector.
	if (x0 < 0 || y0 < 0 || z0 < 0 || x1 >= w || y1 >= h || z1 >= d) {
		return vec3.create();
	}

	// Normalize point coordinates to 0..1 scaling factor between x0 and x1.
	var xf = (x - meshgrid[0][x0]) / (meshgrid[0][x1] - meshgrid[0][x0]);
	var yf = (y - meshgrid[1][y0]) / (meshgrid[1][y1] - meshgrid[1][y0]);
	var zf = (z - meshgrid[2][z0]) / (meshgrid[2][z1] - meshgrid[2][z0]);

	if (xf < 0 || xf > 1 || isNaN(xf)) xf = 0;
	if (yf < 0 || yf > 1 || isNaN(yf)) yf = 0;
	if (zf < 0 || zf > 1 || isNaN(zf)) zf = 0;

	var z0off = z0*w*h;
	var z1off = z1*w*h;

	var y0off = y0*w;
	var y1off = y1*w;

	var x0off = x0;
	var x1off = x1;

	// Sample data array around the (x,y,z) point.
	//  vZYX = array[zZoff + yYoff + xXoff]
	var v000 = array[y0off + z0off + x0off];
	var v001 = array[y0off + z0off + x1off];
	var v010 = array[y1off + z0off + x0off];
	var v011 = array[y1off + z0off + x1off];
	var v100 = array[y0off + z1off + x0off];
	var v101 = array[y0off + z1off + x1off];
	var v110 = array[y1off + z1off + x0off];
	var v111 = array[y1off + z1off + x1off];

	var result = vec3.create();

	// Average samples according to distance to point.
	vec3.lerp(result, v000, v001, xf);
	vec3.lerp(tmp, v010, v011, xf);
	vec3.lerp(result, result, tmp, yf);
	vec3.lerp(tmp, v100, v101, xf);
	vec3.lerp(tmp2, v110, v111, xf);
	vec3.lerp(tmp, tmp, tmp2, yf);
	vec3.lerp(result, result, tmp, zf);

	return result;
};


var vabs = function(dst, v) {
	var x = v[0];
	var y = v[1];
	var z = v[2];
	dst[0] = x >= 0 ? x : -x;
	dst[1] = y >= 0 ? y : -y;
	dst[2] = z >= 0 ? z : -z;
	return dst;
};

var findMinSeparation = function(xs) {
	var minSeparation = 1/0;
	xs.sort(function(a, b) { return a - b; });
	for (var i=1; i<xs.length; i++) {
		var d = Math.abs(xs[i] - xs[i-1]);
		if (d < minSeparation) {
			minSeparation = d;
		}
	}
	return minSeparation;
};

// Finds the minimum per-component distance in positions.
// 
var calculateMinPositionDistance = function(positions) {
	var xs = [], ys = [], zs = [];
	var xi = {}, yi = {}, zi = {};
	for (var i=0; i<positions.length; i++) {
		var p = positions[i];
		var x = p[0], y = p[1], z = p[2];

		// Split the positions array into arrays of unique component values.
		//
		// Why go through the trouble of using a uniqueness hash table vs
		// sort and uniq: 
		//
		// Suppose you've got a million positions in a 100x100x100 grid.
		//
		// Using a uniqueness hash table, you're doing 1M array reads, 
		// 3M hash table lookups from 100-element hashes, 300 hash table inserts, then
		// sorting three 100-element arrays and iterating over them.
		// Roughly, 1M + 3M * ln(100) + 300 * ln(100/2) + 3 * 100 * ln(100) + 3 * 100 = 
		//          1M + 13.8M + 0.0012M +  0.0014M + 0.0003M 
		//          =~ 15M
		//
		// Sort and uniq solution would do 1M array reads, 3M array inserts,
		// sort three 1M-element arrays and iterate over them.
		// Roughly, 1M + 3M + 3 * 1M * ln(1M) + 3 * 1M = 
		//          1M + 3M + 41.4M + 3M 
		//          =~ 48.4M
		//
		// Guessing that a hard-coded sort & uniq would be faster due to not having
		// to run a hashing function on everything. More memory usage though 
		// (bunch of small hash tables vs. duplicating the input array.)
		//
		// In JS-land, who knows. Maybe xi[x] casts x to string and destroys perf, 
		// maybe numeric keys get special-cased, maybe the object lookups run at near O(1)-speeds.
		// Maybe the sorting comparison function is expensive to call, maybe it gets inlined or special-cased.
		//
		// ... You're probably not going to call this with more than 10k positions anyhow, so this is very academic.
		//
		if (!xi[x]) {
			xs.push(x);
			xi[x] = true;
		}
		if (!yi[y]) {
			ys.push(y);
			yi[y] = true;
		}
		if (!zi[z]) {
			zs.push(z);
			zi[z] = true;
		}
	}
	var xSep = findMinSeparation(xs);
	var ySep = findMinSeparation(ys);
	var zSep = findMinSeparation(zs);
	var minSeparation = Math.min(xSep, ySep, zSep);
	if (!isFinite(minSeparation)) {
		return 1;
	}
	return minSeparation;
};

module.exports = function(vectorField, bounds) {
	var positions = vectorField.startingPositions;
	var maxLength = vectorField.maxLength || 1000;
	var tubeSize = vectorField.tubeSize || 1;
	var absoluteTubeSize = vectorField.absoluteTubeSize;

	if (!vectorField.getDivergence) {
		vectorField.getDivergence = defaultGetDivergence;
	}

	if (!vectorField.getVelocity) {
		vectorField.getVelocity = defaultGetVelocity;
	}

	if (vectorField.clampBorders === undefined) {
		vectorField.clampBorders = true;
	}

	var streams = [];

	var minX = bounds[0][0], minY = bounds[0][1], minZ = bounds[0][2];
	var maxX = bounds[1][0], maxY = bounds[1][1], maxZ = bounds[1][2];

	var inBounds = function(bounds, p) {
		var x = p[0];
		var y = p[1];
		var z = p[2];
		return (
			x >= minX && x <= maxX &&
			y >= minY && y <= maxY &&
			z >= minZ && z <= maxZ
		);
	};

	var boundsSize = vec3.distance(bounds[0], bounds[1]);
	var maxStepSize = 10 * boundsSize / maxLength;
	var maxStepSizeSq = maxStepSize * maxStepSize;

	var minDistance = 1;
	var maxDivergence = 0; // For component-wise divergence vec3.create();
	var tmp = vec3.create();

	if (positions.length >= 2) {
		minDistance = calculateMinPositionDistance(positions);
	}

	for (var i = 0; i < positions.length; i++) {
		var p = vec3.create();
		vec3.copy(p, positions[i]);

		var stream = [p];
		var velocities = [];
		var v = vectorField.getVelocity(p);
		var op = p;
		velocities.push(v);

		var divergences = [];

		var dv = vectorField.getDivergence(p, v);
		var dvLength = vec3.length(dv);
		if (dvLength > maxDivergence && !isNaN(dvLength) && isFinite(dvLength)) {
			maxDivergence = dvLength;
		}
		// In case we need to do component-wise divergence visualization
		// vec3.max(maxDivergence, maxDivergence, vabs(tmp, dv));
		divergences.push(dvLength);

		streams.push({points: stream, velocities: velocities, divergences: divergences});

		var j = 0;

		while (j < maxLength * 100 && stream.length < maxLength && inBounds(bounds, p)) {
			j++;
			var np = vec3.clone(v);
			var sqLen = vec3.squaredLength(np);
			if (sqLen === 0) {
				break;
			} else if (sqLen > maxStepSizeSq) {
				vec3.scale(np, np, maxStepSize / Math.sqrt(sqLen));
			}
			vec3.add(np, np, p);

			v = vectorField.getVelocity(np);

			if (vec3.squaredDistance(op, np) - maxStepSizeSq > -0.0001 * maxStepSizeSq) {
				stream.push(np);
				op = np;
				velocities.push(v);
				var dv = vectorField.getDivergence(np, v);
				var dvLength = vec3.length(dv);
				if (dvLength > maxDivergence && !isNaN(dvLength) && isFinite(dvLength)) {
					maxDivergence = dvLength;
				}
				// In case we need to do component-wise divergence visualization
				//vec3.max(maxDivergence, maxDivergence, vabs(tmp, dv));
				divergences.push(dvLength);
			}

			p = np;
		}
	}

	// Replace NaNs and Infinities with non-NaN, finite maxDivergence
	for (var i=0; i<divergences.length; i++) {
		var dvLength = divergences[i];
		if (isNaN(dvLength) || !isFinite(dvLength)) {
			divergences[i] = maxDivergence;
		}
	}

	var tubes = createTubes(streams, vectorField.colormap, maxDivergence, minDistance);

	if (absoluteTubeSize) {
		tubes.tubeScale = absoluteTubeSize;
	} else {
		// Avoid division by zero.
		if (maxDivergence === 0) {
			maxDivergence = 1;
		}
		tubes.tubeScale = tubeSize * 0.5 * minDistance / maxDivergence;
	}

	return tubes;
};

module.exports.createTubeMesh = _dereq_('./lib/tubemesh');

},{"./lib/tubemesh":302,"gl-vec3":332,"gl-vec4":368}],304:[function(_dereq_,module,exports){
var createShader = _dereq_('gl-shader')
var glslify = _dereq_('glslify')

var vertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute vec3 f;\nattribute vec3 normal;\n\nuniform vec3 objectOffset;\nuniform mat4 model, view, projection, inverseModel;\nuniform vec3 lightPosition, eyePosition;\nuniform sampler2D colormap;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\nvarying vec4 vColor;\n\nvoid main() {\n  vec3 localCoordinate = vec3(uv.zw, f.x);\n  worldCoordinate = objectOffset + localCoordinate;\n  vec4 worldPosition = model * vec4(worldCoordinate, 1.0);\n  vec4 clipPosition = projection * view * worldPosition;\n  gl_Position = clipPosition;\n  kill = f.y;\n  value = f.z;\n  planeCoordinate = uv.xy;\n\n  vColor = texture2D(colormap, vec2(value, value));\n\n  //Lighting geometry parameters\n  vec4 cameraCoordinate = view * worldPosition;\n  cameraCoordinate.xyz /= cameraCoordinate.w;\n  lightDirection = lightPosition - cameraCoordinate.xyz;\n  eyeDirection   = eyePosition - cameraCoordinate.xyz;\n  surfaceNormal  = normalize((vec4(normal,0) * inverseModel).xyz);\n}\n"])
var fragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution(float x, float roughness) {\n  float NdotH = max(x, 0.0001);\n  float cos2Alpha = NdotH * NdotH;\n  float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n  float roughness2 = roughness * roughness;\n  float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n  return exp(tan2Alpha / roughness2) / denom;\n}\n\nfloat beckmannSpecular(\n  vec3 lightDirection,\n  vec3 viewDirection,\n  vec3 surfaceNormal,\n  float roughness) {\n  return beckmannDistribution(dot(surfaceNormal, normalize(lightDirection + viewDirection)), roughness);\n}\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 lowerBound, upperBound;\nuniform float contourTint;\nuniform vec4 contourColor;\nuniform sampler2D colormap;\nuniform vec3 clipBounds[2];\nuniform float roughness, fresnel, kambient, kdiffuse, kspecular, opacity;\nuniform float vertexColor;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\nvarying vec4 vColor;\n\nvoid main() {\n  if ((kill > 0.0) ||\n      (outOfRange(clipBounds[0], clipBounds[1], worldCoordinate))) discard;\n\n  vec3 N = normalize(surfaceNormal);\n  vec3 V = normalize(eyeDirection);\n  vec3 L = normalize(lightDirection);\n\n  if(gl_FrontFacing) {\n    N = -N;\n  }\n\n  float specular = max(beckmannSpecular(L, V, N, roughness), 0.);\n  float diffuse  = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n  //decide how to interpolate color — in vertex or in fragment\n  vec4 surfaceColor =\n    step(vertexColor, .5) * texture2D(colormap, vec2(value, value)) +\n    step(.5, vertexColor) * vColor;\n\n  vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular,  1.0);\n\n  gl_FragColor = mix(litColor, contourColor, contourTint) * opacity;\n}\n"])
var contourVertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute float f;\n\nuniform vec3 objectOffset;\nuniform mat3 permutation;\nuniform mat4 model, view, projection;\nuniform float height, zOffset;\nuniform sampler2D colormap;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\nvarying vec4 vColor;\n\nvoid main() {\n  vec3 dataCoordinate = permutation * vec3(uv.xy, height);\n  worldCoordinate = objectOffset + dataCoordinate;\n  vec4 worldPosition = model * vec4(worldCoordinate, 1.0);\n\n  vec4 clipPosition = projection * view * worldPosition;\n  clipPosition.z += zOffset;\n\n  gl_Position = clipPosition;\n  value = f + objectOffset.z;\n  kill = -1.0;\n  planeCoordinate = uv.zw;\n\n  vColor = texture2D(colormap, vec2(value, value));\n\n  //Don't do lighting for contours\n  surfaceNormal   = vec3(1,0,0);\n  eyeDirection    = vec3(0,1,0);\n  lightDirection  = vec3(0,0,1);\n}\n"])
var pickSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec2 shape;\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 surfaceNormal;\n\nvec2 splitFloat(float v) {\n  float vh = 255.0 * v;\n  float upper = floor(vh);\n  float lower = fract(vh);\n  return vec2(upper / 255.0, floor(lower * 16.0) / 16.0);\n}\n\nvoid main() {\n  if ((kill > 0.0) ||\n      (outOfRange(clipBounds[0], clipBounds[1], worldCoordinate))) discard;\n\n  vec2 ux = splitFloat(planeCoordinate.x / shape.x);\n  vec2 uy = splitFloat(planeCoordinate.y / shape.y);\n  gl_FragColor = vec4(pickId, ux.x, uy.x, ux.y + (uy.y/16.0));\n}\n"])

exports.createShader = function (gl) {
  var shader = createShader(gl, vertSrc, fragSrc, null, [
    {name: 'uv', type: 'vec4'},
    {name: 'f', type: 'vec3'},
    {name: 'normal', type: 'vec3'}
  ])
  shader.attributes.uv.location = 0
  shader.attributes.f.location = 1
  shader.attributes.normal.location = 2
  return shader
}
exports.createPickShader = function (gl) {
  var shader = createShader(gl, vertSrc, pickSrc, null, [
    {name: 'uv', type: 'vec4'},
    {name: 'f', type: 'vec3'},
    {name: 'normal', type: 'vec3'}
  ])
  shader.attributes.uv.location = 0
  shader.attributes.f.location = 1
  shader.attributes.normal.location = 2
  return shader
}
exports.createContourShader = function (gl) {
  var shader = createShader(gl, contourVertSrc, fragSrc, null, [
    {name: 'uv', type: 'vec4'},
    {name: 'f', type: 'float'}
  ])
  shader.attributes.uv.location = 0
  shader.attributes.f.location = 1
  return shader
}
exports.createPickContourShader = function (gl) {
  var shader = createShader(gl, contourVertSrc, pickSrc, null, [
    {name: 'uv', type: 'vec4'},
    {name: 'f', type: 'float'}
  ])
  shader.attributes.uv.location = 0
  shader.attributes.f.location = 1
  return shader
}

},{"gl-shader":290,"glslify":395}],305:[function(_dereq_,module,exports){
arguments[4][100][0].apply(exports,arguments)
},{"dup":100}],306:[function(_dereq_,module,exports){
'use strict'

module.exports = createSurfacePlot

var bits = _dereq_('bit-twiddle')
var createBuffer = _dereq_('gl-buffer')
var createVAO = _dereq_('gl-vao')
var createTexture = _dereq_('gl-texture2d')
var pool = _dereq_('typedarray-pool')
var colormap = _dereq_('colormap')
var ops = _dereq_('ndarray-ops')
var pack = _dereq_('ndarray-pack')
var ndarray = _dereq_('ndarray')
var surfaceNets = _dereq_('surface-nets')
var multiply = _dereq_('gl-mat4/multiply')
var invert = _dereq_('gl-mat4/invert')
var bsearch = _dereq_('binary-search-bounds')
var gradient = _dereq_('ndarray-gradient')
var shaders = _dereq_('./lib/shaders')

var createShader = shaders.createShader
var createContourShader = shaders.createContourShader
var createPickShader = shaders.createPickShader
var createPickContourShader = shaders.createPickContourShader

var SURFACE_VERTEX_SIZE = 4 * (4 + 3 + 3)

var IDENTITY = [
  1, 0, 0, 0,
  0, 1, 0, 0,
  0, 0, 1, 0,
  0, 0, 0, 1 ]

var QUAD = [
  [0, 0],
  [0, 1],
  [1, 0],
  [1, 1],
  [1, 0],
  [0, 1]
]

var PERMUTATIONS = [
  [0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0]
]

;(function () {
  for (var i = 0; i < 3; ++i) {
    var p = PERMUTATIONS[i]
    var u = (i + 1) % 3
    var v = (i + 2) % 3
    p[u + 0] = 1
    p[v + 3] = 1
    p[i + 6] = 1
  }
})()

function SurfacePickResult (position, index, uv, level, dataCoordinate) {
  this.position = position
  this.index = index
  this.uv = uv
  this.level = level
  this.dataCoordinate = dataCoordinate
}

var N_COLORS = 256

function genColormap (name) {
  var x = pack([colormap({
    colormap: name,
    nshades: N_COLORS,
    format: 'rgba'
  }).map(function (c) {
    return [c[0], c[1], c[2], 255 * c[3]]
  })])
  ops.divseq(x, 255.0)
  return x
}

function SurfacePlot (
  gl,
  shape,
  bounds,
  shader,
  pickShader,
  coordinates,
  vao,
  colorMap,
  contourShader,
  contourPickShader,
  contourBuffer,
  contourVAO,
  dynamicBuffer,
  dynamicVAO,
  objectOffset) {
  this.gl = gl
  this.shape = shape
  this.bounds = bounds
  this.objectOffset = objectOffset
  this.intensityBounds = []

  this._shader = shader
  this._pickShader = pickShader
  this._coordinateBuffer = coordinates
  this._vao = vao
  this._colorMap = colorMap

  this._contourShader = contourShader
  this._contourPickShader = contourPickShader
  this._contourBuffer = contourBuffer
  this._contourVAO = contourVAO
  this._contourOffsets = [[], [], []]
  this._contourCounts = [[], [], []]
  this._vertexCount = 0

  this._pickResult = new SurfacePickResult([0, 0, 0], [0, 0], [0, 0], [0, 0, 0], [0, 0, 0])

  this._dynamicBuffer = dynamicBuffer
  this._dynamicVAO = dynamicVAO
  this._dynamicOffsets = [0, 0, 0]
  this._dynamicCounts = [0, 0, 0]

  this.contourWidth = [ 1, 1, 1 ]
  this.contourLevels = [[1], [1], [1]]
  this.contourTint = [0, 0, 0]
  this.contourColor = [[0.5, 0.5, 0.5, 1], [0.5, 0.5, 0.5, 1], [0.5, 0.5, 0.5, 1]]

  this.showContour = true
  this.showSurface = true

  this.enableHighlight = [true, true, true]
  this.highlightColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]]
  this.highlightTint = [ 1, 1, 1 ]
  this.highlightLevel = [-1, -1, -1]

  // Dynamic contour options
  this.enableDynamic = [ true, true, true ]
  this.dynamicLevel = [ NaN, NaN, NaN ]
  this.dynamicColor = [ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1] ]
  this.dynamicTint = [ 1, 1, 1 ]
  this.dynamicWidth = [ 1, 1, 1 ]

  this.axesBounds = [[Infinity, Infinity, Infinity], [-Infinity, -Infinity, -Infinity]]
  this.surfaceProject = [ false, false, false ]
  this.contourProject = [[ false, false, false ],
    [ false, false, false ],
    [ false, false, false ]]

  this.colorBounds = [ false, false ]

  // Store xyz fields, need this for picking
  this._field = [
    ndarray(pool.mallocFloat(1024), [0, 0]),
    ndarray(pool.mallocFloat(1024), [0, 0]),
    ndarray(pool.mallocFloat(1024), [0, 0]) ]

  this.pickId = 1
  this.clipBounds = [[-Infinity, -Infinity, -Infinity], [Infinity, Infinity, Infinity]]

  this.snapToData = false

  this.opacity = 1.0

  this.lightPosition = [10, 10000, 0]
  this.ambientLight = 0.8
  this.diffuseLight = 0.8
  this.specularLight = 2.0
  this.roughness = 0.5
  this.fresnel = 1.5
  this.vertexColor = 0

  this.dirty = true
}

var proto = SurfacePlot.prototype

proto.isTransparent = function () {
  return this.opacity < 1
}

proto.isOpaque = function () {
  if (this.opacity >= 1) {
    return true
  }
  for (var i = 0; i < 3; ++i) {
    if (this._contourCounts[i].length > 0 || this._dynamicCounts[i] > 0) {
      return true
    }
  }
  return false
}

proto.pickSlots = 1

proto.setPickBase = function (id) {
  this.pickId = id
}

var ZERO_VEC = [0, 0, 0]

var PROJECT_DATA = {
  showSurface: false,
  showContour: false,
  projections: [IDENTITY.slice(), IDENTITY.slice(), IDENTITY.slice()],
  clipBounds: [
    [[0, 0, 0], [0, 0, 0]],
    [[0, 0, 0], [0, 0, 0]],
    [[0, 0, 0], [0, 0, 0]]]
}

function computeProjectionData (camera, obj) {
  var i, j, k

  // Compute cube properties
  var cubeAxis = (obj.axes && obj.axes.lastCubeProps.axis) || ZERO_VEC

  var showSurface = obj.showSurface
  var showContour = obj.showContour

  for (i = 0; i < 3; ++i) {
    showSurface = showSurface || obj.surfaceProject[i]
    for (j = 0; j < 3; ++j) {
      showContour = showContour || obj.contourProject[i][j]
    }
  }

  for (i = 0; i < 3; ++i) {
    // Construct projection onto axis
    var axisSquish = PROJECT_DATA.projections[i]
    for (j = 0; j < 16; ++j) {
      axisSquish[j] = 0
    }
    for (j = 0; j < 4; ++j) {
      axisSquish[5 * j] = 1
    }
    axisSquish[5 * i] = 0
    axisSquish[12 + i] = obj.axesBounds[+(cubeAxis[i] > 0)][i]
    multiply(axisSquish, camera.model, axisSquish)

    var nclipBounds = PROJECT_DATA.clipBounds[i]
    for (k = 0; k < 2; ++k) {
      for (j = 0; j < 3; ++j) {
        nclipBounds[k][j] = camera.clipBounds[k][j]
      }
    }
    nclipBounds[0][i] = -1e8
    nclipBounds[1][i] = 1e8
  }

  PROJECT_DATA.showSurface = showSurface
  PROJECT_DATA.showContour = showContour

  return PROJECT_DATA
}

var UNIFORMS = {
  model: IDENTITY,
  view: IDENTITY,
  projection: IDENTITY,
  inverseModel: IDENTITY.slice(),
  lowerBound: [0, 0, 0],
  upperBound: [0, 0, 0],
  colorMap: 0,
  clipBounds: [[0, 0, 0], [0, 0, 0]],
  height: 0.0,
  contourTint: 0,
  contourColor: [0, 0, 0, 1],
  permutation: [1, 0, 0, 0, 1, 0, 0, 0, 1],
  zOffset: -1e-4,
  objectOffset: [0, 0, 0],
  kambient: 1,
  kdiffuse: 1,
  kspecular: 1,
  lightPosition: [1000, 1000, 1000],
  eyePosition: [0, 0, 0],
  roughness: 1,
  fresnel: 1,
  opacity: 1,
  vertexColor: 0
}

var MATRIX_INVERSE = IDENTITY.slice()
var DEFAULT_PERM = [1, 0, 0, 0, 1, 0, 0, 0, 1]

function drawCore (params, transparent) {
  params = params || {}
  var gl = this.gl

  gl.disable(gl.CULL_FACE)

  this._colorMap.bind(0)

  var uniforms = UNIFORMS
  uniforms.model = params.model || IDENTITY
  uniforms.view = params.view || IDENTITY
  uniforms.projection = params.projection || IDENTITY
  uniforms.lowerBound = [this.bounds[0][0], this.bounds[0][1], this.colorBounds[0] || this.bounds[0][2]]
  uniforms.upperBound = [this.bounds[1][0], this.bounds[1][1], this.colorBounds[1] || this.bounds[1][2]]
  uniforms.objectOffset = this.objectOffset
  uniforms.contourColor = this.contourColor[0]

  uniforms.inverseModel = invert(uniforms.inverseModel, uniforms.model)

  for (var i = 0; i < 2; ++i) {
    var clipClamped = uniforms.clipBounds[i]
    for (var j = 0; j < 3; ++j) {
      clipClamped[j] = Math.min(Math.max(this.clipBounds[i][j], -1e8), 1e8)
    }
  }

  uniforms.kambient = this.ambientLight
  uniforms.kdiffuse = this.diffuseLight
  uniforms.kspecular = this.specularLight

  uniforms.roughness = this.roughness
  uniforms.fresnel = this.fresnel
  uniforms.opacity = this.opacity

  uniforms.height = 0.0
  uniforms.permutation = DEFAULT_PERM

  uniforms.vertexColor = this.vertexColor

  // Compute camera matrix inverse
  var invCameraMatrix = MATRIX_INVERSE
  multiply(invCameraMatrix, uniforms.view, uniforms.model)
  multiply(invCameraMatrix, uniforms.projection, invCameraMatrix)
  invert(invCameraMatrix, invCameraMatrix)

  for (i = 0; i < 3; ++i) {
    uniforms.eyePosition[i] = invCameraMatrix[12 + i] / invCameraMatrix[15]
  }

  var w = invCameraMatrix[15]
  for (i = 0; i < 3; ++i) {
    w += this.lightPosition[i] * invCameraMatrix[4 * i + 3]
  }
  for (i = 0; i < 3; ++i) {
    var s = invCameraMatrix[12 + i]
    for (j = 0; j < 3; ++j) {
      s += invCameraMatrix[4 * j + i] * this.lightPosition[j]
    }
    uniforms.lightPosition[i] = s / w
  }

  var projectData = computeProjectionData(uniforms, this)

  if (projectData.showSurface && (transparent === (this.opacity < 1))) {
    // Set up uniforms
    this._shader.bind()
    this._shader.uniforms = uniforms

    // Draw it
    this._vao.bind()

    if (this.showSurface && this._vertexCount) {
      this._vao.draw(gl.TRIANGLES, this._vertexCount)
    }

    // Draw projections of surface
    for (i = 0; i < 3; ++i) {
      if (!this.surfaceProject[i] || !this.vertexCount) {
        continue
      }
      this._shader.uniforms.model = projectData.projections[i]
      this._shader.uniforms.clipBounds = projectData.clipBounds[i]
      this._vao.draw(gl.TRIANGLES, this._vertexCount)
    }

    this._vao.unbind()
  }

  if (projectData.showContour && !transparent) {
    var shader = this._contourShader

    // Don't apply lighting to contours
    uniforms.kambient = 1.0
    uniforms.kdiffuse = 0.0
    uniforms.kspecular = 0.0
    uniforms.opacity = 1.0

    shader.bind()
    shader.uniforms = uniforms

    // Draw contour lines
    var vao = this._contourVAO
    vao.bind()

    // Draw contour levels
    for (i = 0; i < 3; ++i) {
      shader.uniforms.permutation = PERMUTATIONS[i]
      gl.lineWidth(this.contourWidth[i])

      for (j = 0; j < this.contourLevels[i].length; ++j) {
        if (j === this.highlightLevel[i]) {
          shader.uniforms.contourColor = this.highlightColor[i]
          shader.uniforms.contourTint = this.highlightTint[i]
        } else if (j === 0 || (j - 1) === this.highlightLevel[i]) {
          shader.uniforms.contourColor = this.contourColor[i]
          shader.uniforms.contourTint = this.contourTint[i]
        }
        if (!this._contourCounts[i][j]) {
          continue
        }

        shader.uniforms.height = this.contourLevels[i][j]

        vao.draw(gl.LINES, this._contourCounts[i][j], this._contourOffsets[i][j])
      }
    }

    // Draw projections of surface
    for (i = 0; i < 3; ++i) {
      shader.uniforms.model = projectData.projections[i]
      shader.uniforms.clipBounds = projectData.clipBounds[i]
      for (j = 0; j < 3; ++j) {
        if (!this.contourProject[i][j]) {
          continue
        }
        shader.uniforms.permutation = PERMUTATIONS[j]
        gl.lineWidth(this.contourWidth[j])
        for (var k = 0; k < this.contourLevels[j].length; ++k) {
          if (k === this.highlightLevel[j]) {
            shader.uniforms.contourColor = this.highlightColor[j]
            shader.uniforms.contourTint = this.highlightTint[j]
          } else if (k === 0 || (k - 1) === this.highlightLevel[j]) {
            shader.uniforms.contourColor = this.contourColor[j]
            shader.uniforms.contourTint = this.contourTint[j]
          }
          shader.uniforms.height = this.contourLevels[j][k]
          vao.draw(gl.LINES, this._contourCounts[j][k], this._contourOffsets[j][k])
        }
      }
    }

    vao.unbind()

    // Draw dynamic contours
    vao = this._dynamicVAO
    vao.bind()

    // Draw contour levels
    for (i = 0; i < 3; ++i) {
      if (this._dynamicCounts[i] === 0) {
        continue
      }

      shader.uniforms.model = uniforms.model
      shader.uniforms.clipBounds = uniforms.clipBounds
      shader.uniforms.permutation = PERMUTATIONS[i]
      gl.lineWidth(this.dynamicWidth[i])

      shader.uniforms.contourColor = this.dynamicColor[i]
      shader.uniforms.contourTint = this.dynamicTint[i]
      shader.uniforms.height = this.dynamicLevel[i]
      vao.draw(gl.LINES, this._dynamicCounts[i], this._dynamicOffsets[i])

      for (j = 0; j < 3; ++j) {
        if (!this.contourProject[j][i]) {
          continue
        }

        shader.uniforms.model = projectData.projections[j]
        shader.uniforms.clipBounds = projectData.clipBounds[j]
        vao.draw(gl.LINES, this._dynamicCounts[i], this._dynamicOffsets[i])
      }
    }

    vao.unbind()
  }
}

proto.draw = function (params) {
  return drawCore.call(this, params, false)
}

proto.drawTransparent = function (params) {
  return drawCore.call(this, params, true)
}

var PICK_UNIFORMS = {
  model: IDENTITY,
  view: IDENTITY,
  projection: IDENTITY,
  inverseModel: IDENTITY,
  clipBounds: [[0, 0, 0], [0, 0, 0]],
  height: 0.0,
  shape: [0, 0],
  pickId: 0,
  lowerBound: [0, 0, 0],
  upperBound: [0, 0, 0],
  zOffset: 0.0,
  objectOffset: [0, 0, 0],
  permutation: [1, 0, 0, 0, 1, 0, 0, 0, 1],
  lightPosition: [0, 0, 0],
  eyePosition: [0, 0, 0]
}

proto.drawPick = function (params) {
  params = params || {}
  var gl = this.gl
  gl.disable(gl.CULL_FACE)

  var uniforms = PICK_UNIFORMS
  uniforms.model = params.model || IDENTITY
  uniforms.view = params.view || IDENTITY
  uniforms.projection = params.projection || IDENTITY
  uniforms.shape = this._field[2].shape
  uniforms.pickId = this.pickId / 255.0
  uniforms.lowerBound = this.bounds[0]
  uniforms.upperBound = this.bounds[1]
  uniforms.objectOffset = this.objectOffset
  uniforms.permutation = DEFAULT_PERM

  for (var i = 0; i < 2; ++i) {
    var clipClamped = uniforms.clipBounds[i]
    for (var j = 0; j < 3; ++j) {
      clipClamped[j] = Math.min(Math.max(this.clipBounds[i][j], -1e8), 1e8)
    }
  }

  var projectData = computeProjectionData(uniforms, this)

  if (projectData.showSurface) {
    // Set up uniforms
    this._pickShader.bind()
    this._pickShader.uniforms = uniforms

    // Draw it
    this._vao.bind()
    this._vao.draw(gl.TRIANGLES, this._vertexCount)

    // Draw projections of surface
    for (i = 0; i < 3; ++i) {
      if (!this.surfaceProject[i]) {
        continue
      }
      this._pickShader.uniforms.model = projectData.projections[i]
      this._pickShader.uniforms.clipBounds = projectData.clipBounds[i]
      this._vao.draw(gl.TRIANGLES, this._vertexCount)
    }

    this._vao.unbind()
  }

  if (projectData.showContour) {
    var shader = this._contourPickShader

    shader.bind()
    shader.uniforms = uniforms

    var vao = this._contourVAO
    vao.bind()

    for (j = 0; j < 3; ++j) {
      gl.lineWidth(this.contourWidth[j])
      shader.uniforms.permutation = PERMUTATIONS[j]
      for (i = 0; i < this.contourLevels[j].length; ++i) {
        if (this._contourCounts[j][i]) {
          shader.uniforms.height = this.contourLevels[j][i]
          vao.draw(gl.LINES, this._contourCounts[j][i], this._contourOffsets[j][i])
        }
      }
    }

    // Draw projections of surface
    for (i = 0; i < 3; ++i) {
      shader.uniforms.model = projectData.projections[i]
      shader.uniforms.clipBounds = projectData.clipBounds[i]

      for (j = 0; j < 3; ++j) {
        if (!this.contourProject[i][j]) {
          continue
        }

        shader.uniforms.permutation = PERMUTATIONS[j]
        gl.lineWidth(this.contourWidth[j])
        for (var k = 0; k < this.contourLevels[j].length; ++k) {
          if (this._contourCounts[j][k]) {
            shader.uniforms.height = this.contourLevels[j][k]
            vao.draw(gl.LINES, this._contourCounts[j][k], this._contourOffsets[j][k])
          }
        }
      }
    }

    vao.unbind()
  }
}

proto.pick = function (selection) {
  if (!selection) {
    return null
  }

  if (selection.id !== this.pickId) {
    return null
  }

  var shape = this._field[2].shape

  var result = this._pickResult

  // Compute uv coordinate
  var x = shape[0] * (selection.value[0] + (selection.value[2] >> 4) / 16.0) / 255.0
  var ix = Math.floor(x)
  var fx = x - ix

  var y = shape[1] * (selection.value[1] + (selection.value[2] & 15) / 16.0) / 255.0
  var iy = Math.floor(y)
  var fy = y - iy

  ix += 1
  iy += 1

  // Compute xyz coordinate
  var pos = result.position
  pos[0] = pos[1] = pos[2] = 0
  for (var dx = 0; dx < 2; ++dx) {
    var s = dx ? fx : 1.0 - fx
    for (var dy = 0; dy < 2; ++dy) {
      var t = dy ? fy : 1.0 - fy

      var r = ix + dx
      var c = iy + dy
      var w = s * t

      for (var i = 0; i < 3; ++i) {
        pos[i] += this._field[i].get(r, c) * w
      }
    }
  }

  // Find closest level
  var levelIndex = this._pickResult.level
  for (var j = 0; j < 3; ++j) {
    levelIndex[j] = bsearch.le(this.contourLevels[j], pos[j])
    if (levelIndex[j] < 0) {
      if (this.contourLevels[j].length > 0) {
        levelIndex[j] = 0
      }
    } else if (levelIndex[j] < this.contourLevels[j].length - 1) {
      var a = this.contourLevels[j][levelIndex[j]]
      var b = this.contourLevels[j][levelIndex[j] + 1]
      if (Math.abs(a - pos[j]) > Math.abs(b - pos[j])) {
        levelIndex[j] += 1
      }
    }
  }

  result.index[0] = fx < 0.5 ? ix : (ix + 1)
  result.index[1] = fy < 0.5 ? iy : (iy + 1)

  result.uv[0] = x / shape[0]
  result.uv[1] = y / shape[1]

  for (i = 0; i < 3; ++i) {
    result.dataCoordinate[i] = this._field[i].get(result.index[0], result.index[1])
  }

  return result
}

proto.padField = function(dstField, srcField) {
  var srcShape = srcField.shape.slice()
  var dstShape = dstField.shape.slice()

  // Center
  ops.assign(dstField.lo(1, 1).hi(srcShape[0], srcShape[1]), srcField)

  // Edges
  ops.assign(dstField.lo(1).hi(srcShape[0], 1),
    srcField.hi(srcShape[0], 1))
  ops.assign(dstField.lo(1, dstShape[1] - 1).hi(srcShape[0], 1),
    srcField.lo(0, srcShape[1] - 1).hi(srcShape[0], 1))
  ops.assign(dstField.lo(0, 1).hi(1, srcShape[1]),
    srcField.hi(1))
  ops.assign(dstField.lo(dstShape[0] - 1, 1).hi(1, srcShape[1]),
    srcField.lo(srcShape[0] - 1))
  // Corners
  dstField.set(0, 0, srcField.get(0, 0))
  dstField.set(0, dstShape[1] - 1, srcField.get(0, srcShape[1] - 1))
  dstField.set(dstShape[0] - 1, 0, srcField.get(srcShape[0] - 1, 0))
  dstField.set(dstShape[0] - 1, dstShape[1] - 1, srcField.get(srcShape[0] - 1, srcShape[1] - 1))
}

function handleArray (param, ctor) {
  if (Array.isArray(param)) {
    return [ ctor(param[0]), ctor(param[1]), ctor(param[2]) ]
  }
  return [ ctor(param), ctor(param), ctor(param) ]
}

function toColor (x) {
  if (Array.isArray(x)) {
    if (x.length === 3) {
      return [x[0], x[1], x[2], 1]
    }
    return [x[0], x[1], x[2], x[3]]
  }
  return [0, 0, 0, 1]
}

function handleColor (param) {
  if (Array.isArray(param)) {
    if (Array.isArray(param)) {
      return [
        toColor(param[0]),
        toColor(param[1]),
        toColor(param[2]) ]
    } else {
      var c = toColor(param)
      return [
        c.slice(),
        c.slice(),
        c.slice() ]
    }
  }
}

proto.update = function (params) {
  params = params || {}

  this.objectOffset = params.objectOffset || this.objectOffset

  this.dirty = true

  if ('contourWidth' in params) {
    this.contourWidth = handleArray(params.contourWidth, Number)
  }
  if ('showContour' in params) {
    this.showContour = handleArray(params.showContour, Boolean)
  }
  if ('showSurface' in params) {
    this.showSurface = !!params.showSurface
  }
  if ('contourTint' in params) {
    this.contourTint = handleArray(params.contourTint, Boolean)
  }
  if ('contourColor' in params) {
    this.contourColor = handleColor(params.contourColor)
  }
  if ('contourProject' in params) {
    this.contourProject = handleArray(params.contourProject, function (x) {
      return handleArray(x, Boolean)
    })
  }
  if ('surfaceProject' in params) {
    this.surfaceProject = params.surfaceProject
  }
  if ('dynamicColor' in params) {
    this.dynamicColor = handleColor(params.dynamicColor)
  }
  if ('dynamicTint' in params) {
    this.dynamicTint = handleArray(params.dynamicTint, Number)
  }
  if ('dynamicWidth' in params) {
    this.dynamicWidth = handleArray(params.dynamicWidth, Number)
  }
  if ('opacity' in params) {
    this.opacity = params.opacity
  }
  if ('colorBounds' in params) {
    this.colorBounds = params.colorBounds
  }
  if ('vertexColor' in params) {
    this.vertexColor = params.vertexColor ? 1 : 0;
  }

  var field = params.field || (params.coords && params.coords[2]) || null
  var levelsChanged = false

  if (!field) {
    if (this._field[2].shape[0] || this._field[2].shape[2]) {
      field = this._field[2].lo(1, 1).hi(this._field[2].shape[0] - 2, this._field[2].shape[1] - 2)
    } else {
      field = this._field[2].hi(0, 0)
    }
  }

  // Update field
  if ('field' in params || 'coords' in params) {
    var fsize = (field.shape[0] + 2) * (field.shape[1] + 2)

    // Resize if necessary
    if (fsize > this._field[2].data.length) {
      pool.freeFloat(this._field[2].data)
      this._field[2].data = pool.mallocFloat(bits.nextPow2(fsize))
    }

    // Pad field
    this._field[2] = ndarray(this._field[2].data, [field.shape[0] + 2, field.shape[1] + 2])
    this.padField(this._field[2], field)

    // Save shape of field
    this.shape = field.shape.slice()
    var shape = this.shape

    // Resize coordinate fields if necessary
    for (var i = 0; i < 2; ++i) {
      if (this._field[2].size > this._field[i].data.length) {
        pool.freeFloat(this._field[i].data)
        this._field[i].data = pool.mallocFloat(this._field[2].size)
      }
      this._field[i] = ndarray(this._field[i].data, [shape[0] + 2, shape[1] + 2])
    }

    // Generate x/y coordinates
    if (params.coords) {
      var coords = params.coords
      if (!Array.isArray(coords) || coords.length !== 3) {
        throw new Error('gl-surface: invalid coordinates for x/y')
      }
      for (i = 0; i < 2; ++i) {
        var coord = coords[i]
        for (j = 0; j < 2; ++j) {
          if (coord.shape[j] !== shape[j]) {
            throw new Error('gl-surface: coords have incorrect shape')
          }
        }
        this.padField(this._field[i], coord)
      }
    } else if (params.ticks) {
      var ticks = params.ticks
      if (!Array.isArray(ticks) || ticks.length !== 2) {
        throw new Error('gl-surface: invalid ticks')
      }
      for (i = 0; i < 2; ++i) {
        var tick = ticks[i]
        if (Array.isArray(tick) || tick.length) {
          tick = ndarray(tick)
        }
        if (tick.shape[0] !== shape[i]) {
          throw new Error('gl-surface: invalid tick length')
        }
        // Make a copy view of the tick array
        var tick2 = ndarray(tick.data, shape)
        tick2.stride[i] = tick.stride[0]
        tick2.stride[i ^ 1] = 0

        // Fill in field array
        this.padField(this._field[i], tick2)
      }
    } else {
      for (i = 0; i < 2; ++i) {
        var offset = [0, 0]
        offset[i] = 1
        this._field[i] = ndarray(this._field[i].data, [shape[0] + 2, shape[1] + 2], offset, 0)
      }
      this._field[0].set(0, 0, 0)
      for (var j = 0; j < shape[0]; ++j) {
        this._field[0].set(j + 1, 0, j)
      }
      this._field[0].set(shape[0] + 1, 0, shape[0] - 1)
      this._field[1].set(0, 0, 0)
      for (j = 0; j < shape[1]; ++j) {
        this._field[1].set(0, j + 1, j)
      }
      this._field[1].set(0, shape[1] + 1, shape[1] - 1)
    }

    // Save shape
    var fields = this._field

    // Compute surface normals
    var dfields = ndarray(pool.mallocFloat(fields[2].size * 3 * 2), [3, shape[0] + 2, shape[1] + 2, 2])
    for (i = 0; i < 3; ++i) {
      gradient(dfields.pick(i), fields[i], 'mirror')
    }
    var normals = ndarray(pool.mallocFloat(fields[2].size * 3), [shape[0] + 2, shape[1] + 2, 3])
    for (i = 0; i < shape[0] + 2; ++i) {
      for (j = 0; j < shape[1] + 2; ++j) {
        var dxdu = dfields.get(0, i, j, 0)
        var dxdv = dfields.get(0, i, j, 1)
        var dydu = dfields.get(1, i, j, 0)
        var dydv = dfields.get(1, i, j, 1)
        var dzdu = dfields.get(2, i, j, 0)
        var dzdv = dfields.get(2, i, j, 1)

        var nx = dydu * dzdv - dydv * dzdu
        var ny = dzdu * dxdv - dzdv * dxdu
        var nz = dxdu * dydv - dxdv * dydu

        var nl = Math.sqrt(nx * nx + ny * ny + nz * nz)
        if (nl < 1e-8) {
          nl = Math.max(Math.abs(nx), Math.abs(ny), Math.abs(nz))
          if (nl < 1e-8) {
            nz = 1.0
            ny = nx = 0.0
            nl = 1.0
          } else {
            nl = 1.0 / nl
          }
        } else {
          nl = 1.0 / Math.sqrt(nl)
        }

        normals.set(i, j, 0, nx * nl)
        normals.set(i, j, 1, ny * nl)
        normals.set(i, j, 2, nz * nl)
      }
    }
    pool.free(dfields.data)

    // Initialize surface
    var lo = [ Infinity, Infinity, Infinity ]
    var hi = [ -Infinity, -Infinity, -Infinity ]
    var lo_intensity = Infinity
    var hi_intensity = -Infinity
    var count = (shape[0] - 1) * (shape[1] - 1) * 6
    var tverts = pool.mallocFloat(bits.nextPow2(10 * count))
    var tptr = 0
    var vertexCount = 0
    for (i = 0; i < shape[0] - 1; ++i) {
      j_loop:
      for (j = 0; j < shape[1] - 1; ++j) {
        // Test for NaNs
        for (var dx = 0; dx < 2; ++dx) {
          for (var dy = 0; dy < 2; ++dy) {
            for (var k = 0; k < 3; ++k) {
              var f = this._field[k].get(1 + i + dx, 1 + j + dy)
              if (isNaN(f) || !isFinite(f)) {
                continue j_loop
              }
            }
          }
        }
        for (k = 0; k < 6; ++k) {
          var r = i + QUAD[k][0]
          var c = j + QUAD[k][1]

          var tx = this._field[0].get(r + 1, c + 1)
          var ty = this._field[1].get(r + 1, c + 1)
          f =      this._field[2].get(r + 1, c + 1)

          nx = normals.get(r + 1, c + 1, 0)
          ny = normals.get(r + 1, c + 1, 1)
          nz = normals.get(r + 1, c + 1, 2)

          if (params.intensity) {
            vf = params.intensity.get(r, c)
          }

          var vf = (params.intensity) ?
            params.intensity.get(r, c) :
            f + this.objectOffset[2];

          tverts[tptr++] = r
          tverts[tptr++] = c
          tverts[tptr++] = tx
          tverts[tptr++] = ty
          tverts[tptr++] = f
          tverts[tptr++] = 0
          tverts[tptr++] = vf
          tverts[tptr++] = nx
          tverts[tptr++] = ny
          tverts[tptr++] = nz

          lo[0] = Math.min(lo[0], tx + this.objectOffset[0])
          lo[1] = Math.min(lo[1], ty + this.objectOffset[1])
          lo[2] = Math.min(lo[2], f  + this.objectOffset[2])
          lo_intensity = Math.min(lo_intensity, vf)

          hi[0] = Math.max(hi[0], tx + this.objectOffset[0])
          hi[1] = Math.max(hi[1], ty + this.objectOffset[1])
          hi[2] = Math.max(hi[2], f  + this.objectOffset[2])
          hi_intensity = Math.max(hi_intensity, vf)

          vertexCount += 1
        }
      }
    }

    if (params.intensityBounds) {
      lo_intensity = +params.intensityBounds[0]
      hi_intensity = +params.intensityBounds[1]
    }

    // Scale all vertex intensities
    for (i = 6; i < tptr; i += 10) {
      tverts[i] = (tverts[i] - lo_intensity) / (hi_intensity - lo_intensity)
    }

    this._vertexCount = vertexCount
    this._coordinateBuffer.update(tverts.subarray(0, tptr))
    pool.freeFloat(tverts)
    pool.free(normals.data)

    // Update bounds
    this.bounds = [lo, hi]

    // Save intensity
    this.intensity = params.intensity || this._field[2]

    if(this.intensityBounds[0] !== lo_intensity || this.intensityBounds[1] !== hi_intensity) {
        levelsChanged = true
    }

    // Save intensity bound
    this.intensityBounds = [lo_intensity, hi_intensity]
  }

  // Update level crossings
  if ('levels' in params) {
    var levels = params.levels
    if (!Array.isArray(levels[0])) {
      levels = [ [], [], levels ]
    } else {
      levels = levels.slice()
    }
    for (i = 0; i < 3; ++i) {
      levels[i] = levels[i].slice()
      levels.sort(function (a, b) {
        return a - b
      })
    }
    for (i = 0; i < 3; ++i) {
      for (j = 0; j < levels[i].length; ++j) {
        levels[i][j] -= this.objectOffset[i]
      }
    }
    change_test:
    for (i = 0; i < 3; ++i) {
      if (levels[i].length !== this.contourLevels[i].length) {
        levelsChanged = true
        break
      }
      for (j = 0; j < levels[i].length; ++j) {
        if (levels[i][j] !== this.contourLevels[i][j]) {
          levelsChanged = true
          break change_test
        }
      }
    }
    this.contourLevels = levels
  }

  if (levelsChanged) {
    fields = this._field
    shape = this.shape

    // Update contour lines
    var contourVerts = []

    for (var dim = 0; dim < 3; ++dim) {
      levels = this.contourLevels[dim]
      var levelOffsets = []
      var levelCounts = []

      var parts = [0, 0, 0]

      for (i = 0; i < levels.length; ++i) {
        var graph = surfaceNets(this._field[dim], levels[i])

        levelOffsets.push((contourVerts.length / 5) | 0)
        vertexCount = 0

        edge_loop:
        for (j = 0; j < graph.cells.length; ++j) {
          var e = graph.cells[j]
          for (k = 0; k < 2; ++k) {
            var p = graph.positions[e[k]]

            var x = p[0]
            var ix = Math.floor(x) | 0
            var fx = x - ix

            var y = p[1]
            var iy = Math.floor(y) | 0
            var fy = y - iy

            var hole = false
            axis_loop:
            for (var axis = 0; axis < 3; ++axis) {
              parts[axis] = 0.0
              var iu = (dim + axis + 1) % 3
              for (dx = 0; dx < 2; ++dx) {
                var s = dx ? fx : 1.0 - fx
                r = Math.min(Math.max(ix + dx, 0), shape[0]) | 0
                for (dy = 0; dy < 2; ++dy) {
                  var t = dy ? fy : 1.0 - fy
                  c = Math.min(Math.max(iy + dy, 0), shape[1]) | 0

                  if (axis < 2) {
                    f = this._field[iu].get(r, c)
                  } else {
                    f = (this.intensity.get(r, c) - this.intensityBounds[0]) / (this.intensityBounds[1] - this.intensityBounds[0])
                  }
                  if (!isFinite(f) || isNaN(f)) {
                    hole = true
                    break axis_loop
                  }

                  var w = s * t
                  parts[axis] += w * f
                }
              }
            }

            if (!hole) {
              contourVerts.push(
                parts[0],
                parts[1],
                p[0],
                p[1],
                parts[2]
              )
              vertexCount += 1
            } else {
              if (k > 0) {
                // If we already added first edge, pop off verts
                for (var l = 0; l < 5; ++l) {
                  contourVerts.pop()
                }
                vertexCount -= 1
              }
              continue edge_loop
            }
          }
        }
        levelCounts.push(vertexCount)
      }

      // Store results
      this._contourOffsets[dim] = levelOffsets
      this._contourCounts[dim] = levelCounts

    }

    var floatBuffer = pool.mallocFloat(contourVerts.length)
    for (i = 0; i < contourVerts.length; ++i) {
      floatBuffer[i] = contourVerts[i]
    }
    this._contourBuffer.update(floatBuffer)
    pool.freeFloat(floatBuffer)
  }

  if (params.colormap) {
    this._colorMap.setPixels(genColormap(params.colormap))
  }
}

proto.dispose = function () {
  this._shader.dispose()
  this._vao.dispose()
  this._coordinateBuffer.dispose()
  this._colorMap.dispose()
  this._contourBuffer.dispose()
  this._contourVAO.dispose()
  this._contourShader.dispose()
  this._contourPickShader.dispose()
  this._dynamicBuffer.dispose()
  this._dynamicVAO.dispose()
  for (var i = 0; i < 3; ++i) {
    pool.freeFloat(this._field[i].data)
  }
}

proto.highlight = function (selection) {
  var i

  if (!selection) {
    this._dynamicCounts = [0, 0, 0]
    this.dyanamicLevel = [NaN, NaN, NaN]
    this.highlightLevel = [-1, -1, -1]
    return
  }

  for (i = 0; i < 3; ++i) {
    if (this.enableHighlight[i]) {
      this.highlightLevel[i] = selection.level[i]
    } else {
      this.highlightLevel[i] = -1
    }
  }

  var levels
  if (this.snapToData) {
    levels = selection.dataCoordinate
  } else {
    levels = selection.position
  }
  for (i = 0; i < 3; ++i) {
    levels[i] -= this.objectOffset[i]
  }
  if ((!this.enableDynamic[0] || levels[0] === this.dynamicLevel[0]) &&
    (!this.enableDynamic[1] || levels[1] === this.dynamicLevel[1]) &&
    (!this.enableDynamic[2] || levels[2] === this.dynamicLevel[2])) {
    return
  }

  var vertexCount = 0
  var shape = this.shape
  var scratchBuffer = pool.mallocFloat(12 * shape[0] * shape[1])

  for (var d = 0; d < 3; ++d) {
    if (!this.enableDynamic[d]) {
      this.dynamicLevel[d] = NaN
      this._dynamicCounts[d] = 0
      continue
    }

    this.dynamicLevel[d] = levels[d]

    var u = (d + 1) % 3
    var v = (d + 2) % 3

    var f = this._field[d]
    var g = this._field[u]
    var h = this._field[v]

    var graph = surfaceNets(f, levels[d])
    var edges = graph.cells
    var positions = graph.positions

    this._dynamicOffsets[d] = vertexCount

    for (i = 0; i < edges.length; ++i) {
      var e = edges[i]
      for (var j = 0; j < 2; ++j) {
        var p = positions[e[j]]

        var x = +p[0]
        var ix = x | 0
        var jx = Math.min(ix + 1, shape[0]) | 0
        var fx = x - ix
        var hx = 1.0 - fx

        var y = +p[1]
        var iy = y | 0
        var jy = Math.min(iy + 1, shape[1]) | 0
        var fy = y - iy
        var hy = 1.0 - fy

        var w00 = hx * hy
        var w01 = hx * fy
        var w10 = fx * hy
        var w11 = fx * fy

        var cu = w00 * g.get(ix, iy) +
          w01 * g.get(ix, jy) +
          w10 * g.get(jx, iy) +
          w11 * g.get(jx, jy)

        var cv = w00 * h.get(ix, iy) +
          w01 * h.get(ix, jy) +
          w10 * h.get(jx, iy) +
          w11 * h.get(jx, jy)

        if (isNaN(cu) || isNaN(cv)) {
          if (j) {
            vertexCount -= 1
          }
          break
        }

        scratchBuffer[2 * vertexCount + 0] = cu
        scratchBuffer[2 * vertexCount + 1] = cv

        vertexCount += 1
      }
    }

    this._dynamicCounts[d] = vertexCount - this._dynamicOffsets[d]
  }

  this._dynamicBuffer.update(scratchBuffer.subarray(0, 2 * vertexCount))
  pool.freeFloat(scratchBuffer)
}

function createSurfacePlot (params) {
  var gl = params.gl
  var shader = createShader(gl)
  var pickShader = createPickShader(gl)
  var contourShader = createContourShader(gl)
  var contourPickShader = createPickContourShader(gl)

  var coordinateBuffer = createBuffer(gl)
  var vao = createVAO(gl, [
    { buffer: coordinateBuffer,
      size: 4,
      stride: SURFACE_VERTEX_SIZE,
      offset: 0
    },
    { buffer: coordinateBuffer,
      size: 3,
      stride: SURFACE_VERTEX_SIZE,
      offset: 16
    },
    {
      buffer: coordinateBuffer,
      size: 3,
      stride: SURFACE_VERTEX_SIZE,
      offset: 28
    }
  ])

  var contourBuffer = createBuffer(gl)
  var contourVAO = createVAO(gl, [
    {
      buffer: contourBuffer,
      size: 4,
      stride: 20,
      offset: 0
    },
    {
      buffer: contourBuffer,
      size: 1,
      stride: 20,
      offset: 16
    }
  ])

  var dynamicBuffer = createBuffer(gl)
  var dynamicVAO = createVAO(gl, [
    {
      buffer: dynamicBuffer,
      size: 2,
      type: gl.FLOAT
    }])

  var cmap = createTexture(gl, 1, N_COLORS, gl.RGBA, gl.UNSIGNED_BYTE)
  cmap.minFilter = gl.LINEAR
  cmap.magFilter = gl.LINEAR

  var surface = new SurfacePlot(
    gl,
    [0, 0], // shape
    [[0, 0, 0], [0, 0, 0]], // bounds
    shader,
    pickShader,
    coordinateBuffer,
    vao,
    cmap,
    contourShader,
    contourPickShader,
    contourBuffer,
    contourVAO,
    dynamicBuffer,
    dynamicVAO,
    [0, 0, 0] // objectOffset
  )

  var nparams = {
    levels: [[], [], []]
  }
  for (var id in params) {
    nparams[id] = params[id]
  }
  nparams.colormap = nparams.colormap || 'jet'

  surface.update(nparams)

  return surface
}

},{"./lib/shaders":304,"binary-search-bounds":305,"bit-twiddle":81,"colormap":115,"gl-buffer":231,"gl-mat4/invert":256,"gl-mat4/multiply":258,"gl-texture2d":308,"gl-vao":313,"ndarray":436,"ndarray-gradient":427,"ndarray-ops":430,"ndarray-pack":431,"surface-nets":509,"typedarray-pool":523}],307:[function(_dereq_,module,exports){
'use strict'

var Font = _dereq_('css-font')
var pick = _dereq_('pick-by-alias')
var createRegl = _dereq_('regl')
var createGl = _dereq_('gl-util/context')
var WeakMap = _dereq_('es6-weak-map')
var rgba = _dereq_('color-normalize')
var fontAtlas = _dereq_('font-atlas')
var pool = _dereq_('typedarray-pool')
var parseRect = _dereq_('parse-rect')
var isObj = _dereq_('is-plain-obj')
var parseUnit = _dereq_('parse-unit')
var px = _dereq_('to-px')
var kerning = _dereq_('detect-kerning')
var extend = _dereq_('object-assign')
var metrics = _dereq_('font-measure')
var flatten = _dereq_('flatten-vertex-data')
var ref = _dereq_('bit-twiddle');
var nextPow2 = ref.nextPow2;

var shaderCache = new WeakMap


// Safari does not support font-stretch
var isStretchSupported = false
if (document.body) {
    var el = document.body.appendChild(document.createElement('div'))
    el.style.font = 'italic small-caps bold condensed 16px/2 cursive'
    if (getComputedStyle(el).fontStretch) {
        isStretchSupported = true
    }
    document.body.removeChild(el)
}

var GlText = function GlText (o) {
	if (isRegl(o)) {
		o = {regl: o}
		this.gl = o.regl._gl
	}
	else {
		this.gl = createGl(o)
	}

	this.shader = shaderCache.get(this.gl)

	if (!this.shader) {
		this.regl = o.regl || createRegl({ gl: this.gl })
	}
	else {
		this.regl = this.shader.regl
	}

	this.charBuffer = this.regl.buffer({ type: 'uint8', usage: 'stream' })
	this.sizeBuffer = this.regl.buffer({ type: 'float', usage: 'stream' })

	if (!this.shader) {
		this.shader = this.createShader()
		shaderCache.set(this.gl, this.shader)
	}

	this.batch = []

	// multiple options initial state
	this.fontSize = []
	this.font = []
	this.fontAtlas = []

	this.draw = this.shader.draw.bind(this)
	this.render = function () {
		// FIXME: add Safari regl report here:
		// charBuffer and width just do not trigger
		this.regl._refresh()
		this.draw(this.batch)
	}
	this.canvas = this.gl.canvas

	this.update(isObj(o) ? o : {})
};

GlText.prototype.createShader = function createShader () {
	var regl = this.regl

	// FIXME: store 2 shader versions: with normal viewport and without
	// draw texture method
	var draw = regl({
		blend: {
			enable: true,
			color: [0,0,0,1],

			func: {
				srcRGB: 'src alpha',
				dstRGB: 'one minus src alpha',
				srcAlpha: 'one minus dst alpha',
				dstAlpha: 'one'
			}
		},
		stencil: {enable: false},
		depth: {enable: false},

		count: regl.prop('count'),
		offset: regl.prop('offset'),
		attributes: {
			charOffset: {
				offset: 4,
				stride: 8,
				buffer: regl.this('sizeBuffer')
			},
			width: {
				offset: 0,
				stride: 8,
				buffer: regl.this('sizeBuffer')
			},
			char: regl.this('charBuffer'),
			position: regl.this('position')
		},
		uniforms: {
			atlasSize: function (c, p) { return [p.atlas.width, p.atlas.height]; },
			atlasDim: function (c, p) { return [p.atlas.cols, p.atlas.rows]; },
			atlas: function (c, p) { return p.atlas.texture; },
			charStep: function (c, p) { return p.atlas.step; },
			em: function (c, p) { return p.atlas.em; },
			color: regl.prop('color'),
			opacity: regl.prop('opacity'),
			viewport: regl.this('viewportArray'),
			scale: regl.this('scale'),
			align: regl.prop('align'),
			baseline: regl.prop('baseline'),
			translate: regl.this('translate'),
			positionOffset: regl.prop('positionOffset')
		},
		primitive: 'points',
		viewport: regl.this('viewport'),

		vert: ("\n\t\t\tprecision highp float;\n\t\t\tattribute float width, charOffset, char;\n\t\t\tattribute vec2 position;\n\t\t\tuniform float fontSize, charStep, em, align, baseline;\n\t\t\tuniform vec4 viewport;\n\t\t\tuniform vec4 color;\n\t\t\tuniform vec2 atlasSize, atlasDim, scale, translate, positionOffset;\n\t\t\tvarying vec2 charCoord, charId;\n\t\t\tvarying float charWidth;\n\t\t\tvarying vec4 fontColor;\n\t\t\tvoid main () {\n\t\t\t\t" + (!GlText.normalViewport ? 'vec2 positionOffset = vec2(positionOffset.x,- positionOffset.y);' : '') + "\n\n\t\t\t\tvec2 offset = floor(em * (vec2(align + charOffset, baseline)\n\t\t\t\t\t+ positionOffset))\n\t\t\t\t\t/ (viewport.zw * scale.xy);\n\n\t\t\t\tvec2 position = (position + translate) * scale;\n\t\t\t\tposition += offset * scale;\n\n\t\t\t\t" + (GlText.normalViewport ? 'position.y = 1. - position.y;' : '') + "\n\n\t\t\t\tcharCoord = position * viewport.zw + viewport.xy;\n\n\t\t\t\tgl_Position = vec4(position * 2. - 1., 0, 1);\n\n\t\t\t\tgl_PointSize = charStep;\n\n\t\t\t\tcharId.x = mod(char, atlasDim.x);\n\t\t\t\tcharId.y = floor(char / atlasDim.x);\n\n\t\t\t\tcharWidth = width * em;\n\n\t\t\t\tfontColor = color / 255.;\n\t\t\t}"),

		frag: "\n\t\t\tprecision highp float;\n\t\t\tuniform sampler2D atlas;\n\t\t\tuniform float fontSize, charStep, opacity;\n\t\t\tuniform vec2 atlasSize;\n\t\t\tuniform vec4 viewport;\n\t\t\tvarying vec4 fontColor;\n\t\t\tvarying vec2 charCoord, charId;\n\t\t\tvarying float charWidth;\n\n\t\t\tfloat lightness(vec4 color) {\n\t\t\t\treturn color.r * 0.299 + color.g * 0.587 + color.b * 0.114;\n\t\t\t}\n\n\t\t\tvoid main () {\n\t\t\t\tvec2 uv = gl_FragCoord.xy - charCoord + charStep * .5;\n\t\t\t\tfloat halfCharStep = floor(charStep * .5 + .5);\n\n\t\t\t\t// invert y and shift by 1px (FF expecially needs that)\n\t\t\t\tuv.y = charStep - uv.y;\n\n\t\t\t\t// ignore points outside of character bounding box\n\t\t\t\tfloat halfCharWidth = ceil(charWidth * .5);\n\t\t\t\tif (floor(uv.x) > halfCharStep + halfCharWidth ||\n\t\t\t\t\tfloor(uv.x) < halfCharStep - halfCharWidth) return;\n\n\t\t\t\tuv += charId * charStep;\n\t\t\t\tuv = uv / atlasSize;\n\n\t\t\t\tvec4 color = fontColor;\n\t\t\t\tvec4 mask = texture2D(atlas, uv);\n\n\t\t\t\tfloat maskY = lightness(mask);\n\t\t\t\t// float colorY = lightness(color);\n\t\t\t\tcolor.a *= maskY;\n\t\t\t\tcolor.a *= opacity;\n\n\t\t\t\t// color.a += .1;\n\n\t\t\t\t// antialiasing, see yiq color space y-channel formula\n\t\t\t\t// color.rgb += (1. - color.rgb) * (1. - mask.rgb);\n\n\t\t\t\tgl_FragColor = color;\n\t\t\t}"
	})

	// per font-size atlas
	var atlas = {}

	return { regl: regl, draw: draw, atlas: atlas }
};

GlText.prototype.update = function update (o) {
		var this$1 = this;

	if (typeof o === 'string') { o = { text: o } }
	else if (!o) { return }

	// FIXME: make this a static transform or more general approact
	o = pick(o, {
		position: 'position positions coord coords coordinates',
		font: 'font fontFace fontface typeface cssFont css-font family fontFamily',
		fontSize: 'fontSize fontsize size font-size',
		text: 'text texts chars characters value values symbols',
		align: 'align alignment textAlign textbaseline',
		baseline: 'baseline textBaseline textbaseline',
		direction: 'dir direction textDirection',
		color: 'color colour fill fill-color fillColor textColor textcolor',
		kerning: 'kerning kern',
		range: 'range dataBox',
		viewport: 'vp viewport viewBox viewbox viewPort',
		opacity: 'opacity alpha transparency visible visibility opaque',
		offset: 'offset positionOffset padding shift indent indentation'
	}, true)


	if (o.opacity != null) {
		if (Array.isArray(o.opacity)) {
			this.opacity = o.opacity.map(function (o) { return parseFloat(o); })
		}
		else {
			this.opacity = parseFloat(o.opacity)
		}
	}

	if (o.viewport != null) {
		this.viewport = parseRect(o.viewport)

		if (GlText.normalViewport) {
			this.viewport.y = this.canvas.height - this.viewport.y - this.viewport.height
		}

		this.viewportArray = [this.viewport.x, this.viewport.y, this.viewport.width, this.viewport.height]

	}
	if (this.viewport == null) {
		this.viewport = {
			x: 0, y: 0,
			width: this.gl.drawingBufferWidth,
			height: this.gl.drawingBufferHeight
		}
		this.viewportArray = [this.viewport.x, this.viewport.y, this.viewport.width, this.viewport.height]
	}

	if (o.kerning != null) { this.kerning = o.kerning }

	if (o.offset != null) {
		if (typeof o.offset === 'number') { o.offset = [o.offset, 0] }

		this.positionOffset = flatten(o.offset)
	}

	if (o.direction) { this.direction = o.direction }

	if (o.range) {
		this.range = o.range
		this.scale = [1 / (o.range[2] - o.range[0]), 1 / (o.range[3] - o.range[1])]
		this.translate = [-o.range[0], -o.range[1]]
	}
	if (o.scale) { this.scale = o.scale }
	if (o.translate) { this.translate = o.translate }

	// default scale corresponds to viewport
	if (!this.scale) { this.scale = [1 / this.viewport.width, 1 / this.viewport.height] }

	if (!this.translate) { this.translate = [0, 0] }

	if (!this.font.length && !o.font) { o.font = GlText.baseFontSize + 'px sans-serif' }

	// normalize font caching string
	var newFont = false, newFontSize = false

	// obtain new font data
	if (o.font) {
		(Array.isArray(o.font) ? o.font : [o.font]).forEach(function (font, i) {
			// normalize font
			if (typeof font === 'string') {
				try {
					font = Font.parse(font)
				} catch (e) {
					font = Font.parse(GlText.baseFontSize + 'px ' + font)
				}
			}
			else { font = Font.parse(Font.stringify(font)) }

			var baseString = Font.stringify({
				size: GlText.baseFontSize,
				family: font.family,
				stretch: isStretchSupported ? font.stretch : undefined,
				variant: font.variant,
				weight: font.weight,
				style: font.style
			})

			var unit = parseUnit(font.size)
			var fs = Math.round(unit[0] * px(unit[1]))
			if (fs !== this$1.fontSize[i]) {
				newFontSize = true
				this$1.fontSize[i] = fs
			}

			// calc new font metrics/atlas
			if (!this$1.font[i] || baseString != this$1.font[i].baseString) {
				newFont = true

				// obtain font cache or create one
				this$1.font[i] = GlText.fonts[baseString]
				if (!this$1.font[i]) {
					var family = font.family.join(', ')
					var style = [font.style]
					if (font.style != font.variant) { style.push(font.variant) }
					if (font.variant != font.weight) { style.push(font.weight) }
					if (isStretchSupported && font.weight != font.stretch) { style.push(font.stretch) }

					this$1.font[i] = {
						baseString: baseString,

						// typeface
						family: family,
						weight: font.weight,
						stretch: font.stretch,
						style: font.style,
						variant: font.variant,

						// widths of characters
						width: {},

						// kernin pairs offsets
						kerning: {},

						metrics: metrics(family, {
							origin: 'top',
							fontSize: GlText.baseFontSize,
							fontStyle: style.join(' ')
						})
					}

					GlText.fonts[baseString] = this$1.font[i]
				}
			}
		})
	}

	// FIXME: make independend font-size
	// if (o.fontSize) {
	// let unit = parseUnit(o.fontSize)
	// let fs = Math.round(unit[0] * px(unit[1]))

	// if (fs != this.fontSize) {
	// 	newFontSize = true
	// 	this.fontSize = fs
	// }
	// }

	if (newFont || newFontSize) {
		this.font.forEach(function (font, i) {
			var fontString = Font.stringify({
				size: this$1.fontSize[i],
				family: font.family,
				stretch: isStretchSupported ? font.stretch : undefined,
				variant: font.variant,
				weight: font.weight,
				style: font.style
			})

			// calc new font size atlas
			this$1.fontAtlas[i] = this$1.shader.atlas[fontString]

			if (!this$1.fontAtlas[i]) {
				var metrics = font.metrics

				this$1.shader.atlas[fontString] =
				this$1.fontAtlas[i] = {
					fontString: fontString,
					// even step is better for rendered characters
					step: Math.ceil(this$1.fontSize[i] * metrics.bottom * .5) * 2,
					em: this$1.fontSize[i],
					cols: 0,
					rows: 0,
					height: 0,
					width: 0,
					chars: [],
					ids: {},
					texture: this$1.regl.texture()
				}
			}

			// bump atlas characters
			if (o.text == null) { o.text = this$1.text }
		})
	}

	// if multiple positions - duplicate text arguments
	// FIXME: this possibly can be done better to avoid array spawn
	if (typeof o.text === 'string' && o.position && o.position.length > 2) {
		var textArray = Array(o.position.length * .5)
		for (var i = 0; i < textArray.length; i++) {
			textArray[i] = o.text
		}
		o.text = textArray
	}

	// calculate offsets for the new font/text
	var newAtlasChars
	if (o.text != null || newFont) {
		// FIXME: ignore spaces
		// text offsets within the text buffer
		this.textOffsets = [0]

		if (Array.isArray(o.text)) {
			this.count = o.text[0].length
			this.counts = [this.count]
			for (var i$1 = 1; i$1 < o.text.length; i$1++) {
				this$1.textOffsets[i$1] = this$1.textOffsets[i$1 - 1] + o.text[i$1 - 1].length
				this$1.count += o.text[i$1].length
				this$1.counts.push(o.text[i$1].length)
			}
			this.text = o.text.join('')
		}
		else {
			this.text = o.text
			this.count = this.text.length
			this.counts = [this.count]
		}

		newAtlasChars = []

		// detect & measure new characters
		this.font.forEach(function (font, idx) {
			GlText.atlasContext.font = font.baseString

			var atlas = this$1.fontAtlas[idx]

			for (var i = 0; i < this$1.text.length; i++) {
				var char = this$1.text.charAt(i)

				if (atlas.ids[char] == null) {
					atlas.ids[char] = atlas.chars.length
					atlas.chars.push(char)
					newAtlasChars.push(char)
				}

				if (font.width[char] == null) {
					font.width[char] = GlText.atlasContext.measureText(char).width / GlText.baseFontSize

					// measure kerning pairs for the new character
					if (this$1.kerning) {
						var pairs = []
						for (var baseChar in font.width) {
							pairs.push(baseChar + char, char + baseChar)
						}
						extend(font.kerning, kerning(font.family, {
							pairs: pairs
						}))
					}
				}
			}
		})
	}

	// create single position buffer (faster than batch or multiple separate instances)
	if (o.position) {
		if (o.position.length > 2) {
			var flat = !o.position[0].length
			var positionData = pool.mallocFloat(this.count * 2)
			for (var i$2 = 0, ptr = 0; i$2 < this.counts.length; i$2++) {
				var count = this$1.counts[i$2]
				if (flat) {
					for (var j = 0; j < count; j++) {
						positionData[ptr++] = o.position[i$2 * 2]
						positionData[ptr++] = o.position[i$2 * 2 + 1]
					}
				}
				else {
					for (var j$1 = 0; j$1 < count; j$1++) {
						positionData[ptr++] = o.position[i$2][0]
						positionData[ptr++] = o.position[i$2][1]
					}
				}
			}
			if (this.position.call) {
				this.position({
					type: 'float',
					data: positionData
				})
			} else {
				this.position = this.regl.buffer({
					type: 'float',
					data: positionData
				})
			}
			pool.freeFloat(positionData)
		}
		else {
			if (this.position.destroy) { this.position.destroy() }
			this.position = {
				constant: o.position
			}
		}
	}

	// populate text/offset buffers if font/text has changed
	// as [charWidth, offset, charWidth, offset...]
	// that is in em units since font-size can change often
	if (o.text || newFont) {
		var charIds = pool.mallocUint8(this.count)
		var sizeData = pool.mallocFloat(this.count * 2)
		this.textWidth = []

		for (var i$3 = 0, ptr$1 = 0; i$3 < this.counts.length; i$3++) {
			var count$1 = this$1.counts[i$3]
			var font = this$1.font[i$3] || this$1.font[0]
			var atlas = this$1.fontAtlas[i$3] || this$1.fontAtlas[0]

			for (var j$2 = 0; j$2 < count$1; j$2++) {
				var char = this$1.text.charAt(ptr$1)
				var prevChar = this$1.text.charAt(ptr$1 - 1)

				charIds[ptr$1] = atlas.ids[char]
				sizeData[ptr$1 * 2] = font.width[char]

				if (j$2) {
					var prevWidth = sizeData[ptr$1 * 2 - 2]
					var currWidth = sizeData[ptr$1 * 2]
					var prevOffset = sizeData[ptr$1 * 2 - 1]
					var offset = prevOffset + prevWidth * .5 + currWidth * .5;

					if (this$1.kerning) {
						var kerning$1 = font.kerning[prevChar + char]
						if (kerning$1) {
							offset += kerning$1 * 1e-3
						}
					}

					sizeData[ptr$1 * 2 + 1] = offset
				}
				else {
					sizeData[ptr$1 * 2 + 1] = sizeData[ptr$1 * 2] * .5
				}

				ptr$1++
			}
			this$1.textWidth.push(
				!sizeData.length ? 0 :
				// last offset + half last width
				sizeData[ptr$1 * 2 - 2] * .5 + sizeData[ptr$1 * 2 - 1]
			)
		}


		// bump recalc align offset
		if (!o.align) { o.align = this.align }
		this.charBuffer({data: charIds, type: 'uint8', usage: 'stream'})
		this.sizeBuffer({data: sizeData, type: 'float', usage: 'stream'})
		pool.freeUint8(charIds)
		pool.freeFloat(sizeData)

		// udpate font atlas and texture
		if (newAtlasChars.length) {
			this.font.forEach(function (font, i) {
				var atlas = this$1.fontAtlas[i]

				// FIXME: insert metrics-based ratio here
				var step = atlas.step

				var maxCols = Math.floor(GlText.maxAtlasSize / step)
				var cols = Math.min(maxCols, atlas.chars.length)
				var rows = Math.ceil(atlas.chars.length / cols)

				var atlasWidth = nextPow2( cols * step )
				// let atlasHeight = Math.min(rows * step + step * .5, GlText.maxAtlasSize);
				var atlasHeight = nextPow2( rows * step );

				atlas.width = atlasWidth
				atlas.height = atlasHeight;
				atlas.rows = rows
				atlas.cols = cols

				if (!atlas.em) { return }

				atlas.texture({
					data: fontAtlas({
						canvas: GlText.atlasCanvas,
						font: atlas.fontString,
						chars: atlas.chars,
						shape: [atlasWidth, atlasHeight],
						step: [step, step]
					})
				})

			})
		}
	}

	if (o.align) {
		this.align = o.align
		this.alignOffset = this.textWidth.map(function (textWidth, i) {
			var align = !Array.isArray(this$1.align) ? this$1.align : this$1.align.length > 1 ? this$1.align[i] : this$1.align[0]

			if (typeof align === 'number') { return align }
			switch (align) {
				case 'right':
				case 'end':
					return -textWidth
				case 'center':
				case 'centre':
				case 'middle':
					return -textWidth * .5
			}

			return 0
		})
	}

	if (this.baseline == null && o.baseline == null) {
		o.baseline = 0
	}
	if (o.baseline != null) {
		this.baseline = o.baseline
		if (!Array.isArray(this.baseline)) { this.baseline = [this.baseline] }
		this.baselineOffset = this.baseline.map(function (baseline, i) {
			var m = (this$1.font[i] || this$1.font[0]).metrics
			var base = 0

			base += m.bottom * .5

			if (typeof baseline === 'number') {
				base += (baseline - m.baseline)
			}
			else {
				base += -m[baseline]
			}

			if (!GlText.normalViewport) { base *= -1 }
			return base
		})
	}

	// flatten colors to a single uint8 array
	if (o.color != null) {
		if (!o.color) { o.color = 'transparent' }

		// single color
		if (typeof o.color === 'string' || !isNaN(o.color)) {
			this.color = rgba(o.color, 'uint8')
		}
		// array
		else {
			var colorData

			// flat array
			if (typeof o.color[0] === 'number' && o.color.length > this.counts.length) {
				var l = o.color.length
				colorData = pool.mallocUint8(l)
				var sub = (o.color.subarray || o.color.slice).bind(o.color)
				for (var i$4 = 0; i$4 < l; i$4 += 4) {
					colorData.set(rgba(sub(i$4, i$4 + 4), 'uint8'), i$4)
				}
			}
			// nested array
			else {
				var l$1 = o.color.length
				colorData = pool.mallocUint8(l$1 * 4)
				for (var i$5 = 0; i$5 < l$1; i$5++) {
					colorData.set(rgba(o.color[i$5] || 0, 'uint8'), i$5 * 4)
				}
			}

			this.color = colorData
		}
	}

	// update render batch
	if (o.position || o.text || o.color || o.baseline || o.align || o.font || o.offset || o.opacity) {
		var isBatch = (this.color.length > 4)
			|| (this.baselineOffset.length > 1)
			|| (this.align && this.align.length > 1)
			|| (this.fontAtlas.length > 1)
			|| (this.positionOffset.length > 2)
		if (isBatch) {
			var length = Math.max(
				this.position.length * .5 || 0,
				this.color.length * .25 || 0,
				this.baselineOffset.length || 0,
				this.alignOffset.length || 0,
				this.font.length || 0,
				this.opacity.length || 0,
				this.positionOffset.length * .5 || 0
			)
			this.batch = Array(length)
			for (var i$6 = 0; i$6 < this.batch.length; i$6++) {
				this$1.batch[i$6] = {
					count: this$1.counts.length > 1 ? this$1.counts[i$6] : this$1.counts[0],
					offset: this$1.textOffsets.length > 1 ? this$1.textOffsets[i$6] : this$1.textOffsets[0],
					color: !this$1.color ? [0,0,0,255] : this$1.color.length <= 4 ? this$1.color : this$1.color.subarray(i$6 * 4, i$6 * 4 + 4),
					opacity: Array.isArray(this$1.opacity) ? this$1.opacity[i$6] : this$1.opacity,
					baseline: this$1.baselineOffset[i$6] != null ? this$1.baselineOffset[i$6] : this$1.baselineOffset[0],
					align: !this$1.align ? 0 : this$1.alignOffset[i$6] != null ? this$1.alignOffset[i$6] : this$1.alignOffset[0],
					atlas: this$1.fontAtlas[i$6] || this$1.fontAtlas[0],
					positionOffset: this$1.positionOffset.length > 2 ? this$1.positionOffset.subarray(i$6 * 2, i$6 * 2 + 2) : this$1.positionOffset
				}
			}
		}
		// single-color, single-baseline, single-align batch is faster to render
		else {
			if (this.count) {
				this.batch = [{
					count: this.count,
					offset: 0,
					color: this.color || [0,0,0,255],
					opacity: Array.isArray(this.opacity) ? this.opacity[0] : this.opacity,
					baseline: this.baselineOffset[0],
					align: this.alignOffset ? this.alignOffset[0] : 0,
					atlas: this.fontAtlas[0],
					positionOffset: this.positionOffset
				}]
			}
			else {
				this.batch = []
			}
		}
	}
};

GlText.prototype.destroy = function destroy () {
	// TODO: count instances of atlases and destroy all on null
};


// defaults
GlText.prototype.kerning = true
GlText.prototype.position = { constant: new Float32Array(2) }
GlText.prototype.translate = null
GlText.prototype.scale = null
GlText.prototype.font = null
GlText.prototype.text = ''
GlText.prototype.positionOffset = [0, 0]
GlText.prototype.opacity = 1
GlText.prototype.color = new Uint8Array([0, 0, 0, 255])
GlText.prototype.alignOffset = [0, 0]


// whether viewport should be top↓bottom 2d one (true) or webgl one (false)
GlText.normalViewport = false

// size of an atlas
GlText.maxAtlasSize = 1024

// font atlas canvas is singleton
GlText.atlasCanvas = document.createElement('canvas')
GlText.atlasContext = GlText.atlasCanvas.getContext('2d', {alpha: false})

// font-size used for metrics, atlas step calculation
GlText.baseFontSize = 64

// fonts storage
GlText.fonts = {}

// max number of different font atlases/textures cached
// FIXME: enable atlas size limitation via LRU
// GlText.atlasCacheSize = 64

function isRegl (o) {
	return typeof o === 'function' &&
	o._gl &&
	o.prop &&
	o.texture &&
	o.buffer
}


module.exports = GlText


},{"bit-twiddle":81,"color-normalize":109,"css-font":128,"detect-kerning":152,"es6-weak-map":210,"flatten-vertex-data":217,"font-atlas":218,"font-measure":219,"gl-util/context":309,"is-plain-obj":408,"object-assign":440,"parse-rect":445,"parse-unit":447,"pick-by-alias":451,"regl":480,"to-px":517,"typedarray-pool":523}],308:[function(_dereq_,module,exports){
'use strict'

var ndarray = _dereq_('ndarray')
var ops     = _dereq_('ndarray-ops')
var pool    = _dereq_('typedarray-pool')

module.exports = createTexture2D

var linearTypes = null
var filterTypes = null
var wrapTypes   = null

function lazyInitLinearTypes(gl) {
  linearTypes = [
    gl.LINEAR,
    gl.NEAREST_MIPMAP_LINEAR,
    gl.LINEAR_MIPMAP_NEAREST,
    gl.LINEAR_MIPMAP_NEAREST
  ]
  filterTypes = [
    gl.NEAREST,
    gl.LINEAR,
    gl.NEAREST_MIPMAP_NEAREST,
    gl.NEAREST_MIPMAP_LINEAR,
    gl.LINEAR_MIPMAP_NEAREST,
    gl.LINEAR_MIPMAP_LINEAR
  ]
  wrapTypes = [
    gl.REPEAT,
    gl.CLAMP_TO_EDGE,
    gl.MIRRORED_REPEAT
  ]
}

function acceptTextureDOM (obj) {
  return (
    ('undefined' != typeof HTMLCanvasElement && obj instanceof HTMLCanvasElement) ||
    ('undefined' != typeof HTMLImageElement && obj instanceof HTMLImageElement) ||
    ('undefined' != typeof HTMLVideoElement && obj instanceof HTMLVideoElement) ||
    ('undefined' != typeof ImageData && obj instanceof ImageData))
}

var convertFloatToUint8 = function(out, inp) {
  ops.muls(out, inp, 255.0)
}

function reshapeTexture(tex, w, h) {
  var gl = tex.gl
  var maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE)
  if(w < 0 || w > maxSize || h < 0 || h > maxSize) {
    throw new Error('gl-texture2d: Invalid texture size')
  }
  tex._shape = [w, h]
  tex.bind()
  gl.texImage2D(gl.TEXTURE_2D, 0, tex.format, w, h, 0, tex.format, tex.type, null)
  tex._mipLevels = [0]
  return tex
}

function Texture2D(gl, handle, width, height, format, type) {
  this.gl = gl
  this.handle = handle
  this.format = format
  this.type = type
  this._shape = [width, height]
  this._mipLevels = [0]
  this._magFilter = gl.NEAREST
  this._minFilter = gl.NEAREST
  this._wrapS = gl.CLAMP_TO_EDGE
  this._wrapT = gl.CLAMP_TO_EDGE
  this._anisoSamples = 1

  var parent = this
  var wrapVector = [this._wrapS, this._wrapT]
  Object.defineProperties(wrapVector, [
    {
      get: function() {
        return parent._wrapS
      },
      set: function(v) {
        return parent.wrapS = v
      }
    },
    {
      get: function() {
        return parent._wrapT
      },
      set: function(v) {
        return parent.wrapT = v
      }
    }
  ])
  this._wrapVector = wrapVector

  var shapeVector = [this._shape[0], this._shape[1]]
  Object.defineProperties(shapeVector, [
    {
      get: function() {
        return parent._shape[0]
      },
      set: function(v) {
        return parent.width = v
      }
    },
    {
      get: function() {
        return parent._shape[1]
      },
      set: function(v) {
        return parent.height = v
      }
    }
  ])
  this._shapeVector = shapeVector
}

var proto = Texture2D.prototype

Object.defineProperties(proto, {
  minFilter: {
    get: function() {
      return this._minFilter
    },
    set: function(v) {
      this.bind()
      var gl = this.gl
      if(this.type === gl.FLOAT && linearTypes.indexOf(v) >= 0) {
        if(!gl.getExtension('OES_texture_float_linear')) {
          v = gl.NEAREST
        }
      }
      if(filterTypes.indexOf(v) < 0) {
        throw new Error('gl-texture2d: Unknown filter mode ' + v)
      }
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, v)
      return this._minFilter = v
    }
  },
  magFilter: {
    get: function() {
      return this._magFilter
    },
    set: function(v) {
      this.bind()
      var gl = this.gl
      if(this.type === gl.FLOAT && linearTypes.indexOf(v) >= 0) {
        if(!gl.getExtension('OES_texture_float_linear')) {
          v = gl.NEAREST
        }
      }
      if(filterTypes.indexOf(v) < 0) {
        throw new Error('gl-texture2d: Unknown filter mode ' + v)
      }
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, v)
      return this._magFilter = v
    }
  },
  mipSamples: {
    get: function() {
      return this._anisoSamples
    },
    set: function(i) {
      var psamples = this._anisoSamples
      this._anisoSamples = Math.max(i, 1)|0
      if(psamples !== this._anisoSamples) {
        var ext = this.gl.getExtension('EXT_texture_filter_anisotropic')
        if(ext) {
          this.gl.texParameterf(this.gl.TEXTURE_2D, ext.TEXTURE_MAX_ANISOTROPY_EXT, this._anisoSamples)
        }
      }
      return this._anisoSamples
    }
  },
  wrapS: {
    get: function() {
      return this._wrapS
    },
    set: function(v) {
      this.bind()
      if(wrapTypes.indexOf(v) < 0) {
        throw new Error('gl-texture2d: Unknown wrap mode ' + v)
      }
      this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, v)
      return this._wrapS = v
    }
  },
  wrapT: {
    get: function() {
      return this._wrapT
    },
    set: function(v) {
      this.bind()
      if(wrapTypes.indexOf(v) < 0) {
        throw new Error('gl-texture2d: Unknown wrap mode ' + v)
      }
      this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, v)
      return this._wrapT = v
    }
  },
  wrap: {
    get: function() {
      return this._wrapVector
    },
    set: function(v) {
      if(!Array.isArray(v)) {
        v = [v,v]
      }
      if(v.length !== 2) {
        throw new Error('gl-texture2d: Must specify wrap mode for rows and columns')
      }
      for(var i=0; i<2; ++i) {
        if(wrapTypes.indexOf(v[i]) < 0) {
          throw new Error('gl-texture2d: Unknown wrap mode ' + v)
        }
      }
      this._wrapS = v[0]
      this._wrapT = v[1]

      var gl = this.gl
      this.bind()
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this._wrapS)
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this._wrapT)

      return v
    }
  },
  shape: {
    get: function() {
      return this._shapeVector
    },
    set: function(x) {
      if(!Array.isArray(x)) {
        x = [x|0,x|0]
      } else {
        if(x.length !== 2) {
          throw new Error('gl-texture2d: Invalid texture shape')
        }
      }
      reshapeTexture(this, x[0]|0, x[1]|0)
      return [x[0]|0, x[1]|0]
    }
  },
  width: {
    get: function() {
      return this._shape[0]
    },
    set: function(w) {
      w = w|0
      reshapeTexture(this, w, this._shape[1])
      return w
    }
  },
  height: {
    get: function() {
      return this._shape[1]
    },
    set: function(h) {
      h = h|0
      reshapeTexture(this, this._shape[0], h)
      return h
    }
  }
})

proto.bind = function(unit) {
  var gl = this.gl
  if(unit !== undefined) {
    gl.activeTexture(gl.TEXTURE0 + (unit|0))
  }
  gl.bindTexture(gl.TEXTURE_2D, this.handle)
  if(unit !== undefined) {
    return (unit|0)
  }
  return gl.getParameter(gl.ACTIVE_TEXTURE) - gl.TEXTURE0
}

proto.dispose = function() {
  this.gl.deleteTexture(this.handle)
}

proto.generateMipmap = function() {
  this.bind()
  this.gl.generateMipmap(this.gl.TEXTURE_2D)

  //Update mip levels
  var l = Math.min(this._shape[0], this._shape[1])
  for(var i=0; l>0; ++i, l>>>=1) {
    if(this._mipLevels.indexOf(i) < 0) {
      this._mipLevels.push(i)
    }
  }
}

proto.setPixels = function(data, x_off, y_off, mip_level) {
  var gl = this.gl
  this.bind()
  if(Array.isArray(x_off)) {
    mip_level = y_off
    y_off = x_off[1]|0
    x_off = x_off[0]|0
  } else {
    x_off = x_off || 0
    y_off = y_off || 0
  }
  mip_level = mip_level || 0
  var directData = acceptTextureDOM(data) ? data : data.raw
  if(directData) {
    var needsMip = this._mipLevels.indexOf(mip_level) < 0
    if(needsMip) {
      gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, directData)
      this._mipLevels.push(mip_level)
    } else {
      gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, this.format, this.type, directData)
    }
  } else if(data.shape && data.stride && data.data) {
    if(data.shape.length < 2 ||
       x_off + data.shape[1] > this._shape[1]>>>mip_level ||
       y_off + data.shape[0] > this._shape[0]>>>mip_level ||
       x_off < 0 ||
       y_off < 0) {
      throw new Error('gl-texture2d: Texture dimensions are out of bounds')
    }
    texSubImageArray(gl, x_off, y_off, mip_level, this.format, this.type, this._mipLevels, data)
  } else {
    throw new Error('gl-texture2d: Unsupported data type')
  }
}


function isPacked(shape, stride) {
  if(shape.length === 3) {
    return  (stride[2] === 1) &&
            (stride[1] === shape[0]*shape[2]) &&
            (stride[0] === shape[2])
  }
  return  (stride[0] === 1) &&
          (stride[1] === shape[0])
}

function texSubImageArray(gl, x_off, y_off, mip_level, cformat, ctype, mipLevels, array) {
  var dtype = array.dtype
  var shape = array.shape.slice()
  if(shape.length < 2 || shape.length > 3) {
    throw new Error('gl-texture2d: Invalid ndarray, must be 2d or 3d')
  }
  var type = 0, format = 0
  var packed = isPacked(shape, array.stride.slice())
  if(dtype === 'float32') {
    type = gl.FLOAT
  } else if(dtype === 'float64') {
    type = gl.FLOAT
    packed = false
    dtype = 'float32'
  } else if(dtype === 'uint8') {
    type = gl.UNSIGNED_BYTE
  } else {
    type = gl.UNSIGNED_BYTE
    packed = false
    dtype = 'uint8'
  }
  var channels = 1
  if(shape.length === 2) {
    format = gl.LUMINANCE
    shape = [shape[0], shape[1], 1]
    array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset)
  } else if(shape.length === 3) {
    if(shape[2] === 1) {
      format = gl.ALPHA
    } else if(shape[2] === 2) {
      format = gl.LUMINANCE_ALPHA
    } else if(shape[2] === 3) {
      format = gl.RGB
    } else if(shape[2] === 4) {
      format = gl.RGBA
    } else {
      throw new Error('gl-texture2d: Invalid shape for pixel coords')
    }
    channels = shape[2]
  } else {
    throw new Error('gl-texture2d: Invalid shape for texture')
  }
  //For 1-channel textures allow conversion between formats
  if((format  === gl.LUMINANCE || format  === gl.ALPHA) &&
     (cformat === gl.LUMINANCE || cformat === gl.ALPHA)) {
    format = cformat
  }
  if(format !== cformat) {
    throw new Error('gl-texture2d: Incompatible texture format for setPixels')
  }
  var size = array.size
  var needsMip = mipLevels.indexOf(mip_level) < 0
  if(needsMip) {
    mipLevels.push(mip_level)
  }
  if(type === ctype && packed) {
    //Array data types are compatible, can directly copy into texture
    if(array.offset === 0 && array.data.length === size) {
      if(needsMip) {
        gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, array.data)
      } else {
        gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, array.data)
      }
    } else {
      if(needsMip) {
        gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, array.data.subarray(array.offset, array.offset+size))
      } else {
        gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, array.data.subarray(array.offset, array.offset+size))
      }
    }
  } else {
    //Need to do type conversion to pack data into buffer
    var pack_buffer
    if(ctype === gl.FLOAT) {
      pack_buffer = pool.mallocFloat32(size)
    } else {
      pack_buffer = pool.mallocUint8(size)
    }
    var pack_view = ndarray(pack_buffer, shape, [shape[2], shape[2]*shape[0], 1])
    if(type === gl.FLOAT && ctype === gl.UNSIGNED_BYTE) {
      convertFloatToUint8(pack_view, array)
    } else {
      ops.assign(pack_view, array)
    }
    if(needsMip) {
      gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, pack_buffer.subarray(0, size))
    } else {
      gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, pack_buffer.subarray(0, size))
    }
    if(ctype === gl.FLOAT) {
      pool.freeFloat32(pack_buffer)
    } else {
      pool.freeUint8(pack_buffer)
    }
  }
}

function initTexture(gl) {
  var tex = gl.createTexture()
  gl.bindTexture(gl.TEXTURE_2D, tex)
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
  return tex
}

function createTextureShape(gl, width, height, format, type) {
  var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE)
  if(width < 0 || width > maxTextureSize || height < 0 || height  > maxTextureSize) {
    throw new Error('gl-texture2d: Invalid texture shape')
  }
  if(type === gl.FLOAT && !gl.getExtension('OES_texture_float')) {
    throw new Error('gl-texture2d: Floating point textures not supported on this platform')
  }
  var tex = initTexture(gl)
  gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, 0, format, type, null)
  return new Texture2D(gl, tex, width, height, format, type)
}

function createTextureDOM(gl, directData, width, height, format, type) {
  var tex = initTexture(gl)
  gl.texImage2D(gl.TEXTURE_2D, 0, format, format, type, directData)
  return new Texture2D(gl, tex, width, height, format, type)
}

//Creates a texture from an ndarray
function createTextureArray(gl, array) {
  var dtype = array.dtype
  var shape = array.shape.slice()
  var maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE)
  if(shape[0] < 0 || shape[0] > maxSize || shape[1] < 0 || shape[1] > maxSize) {
    throw new Error('gl-texture2d: Invalid texture size')
  }
  var packed = isPacked(shape, array.stride.slice())
  var type = 0
  if(dtype === 'float32') {
    type = gl.FLOAT
  } else if(dtype === 'float64') {
    type = gl.FLOAT
    packed = false
    dtype = 'float32'
  } else if(dtype === 'uint8') {
    type = gl.UNSIGNED_BYTE
  } else {
    type = gl.UNSIGNED_BYTE
    packed = false
    dtype = 'uint8'
  }
  var format = 0
  if(shape.length === 2) {
    format = gl.LUMINANCE
    shape = [shape[0], shape[1], 1]
    array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset)
  } else if(shape.length === 3) {
    if(shape[2] === 1) {
      format = gl.ALPHA
    } else if(shape[2] === 2) {
      format = gl.LUMINANCE_ALPHA
    } else if(shape[2] === 3) {
      format = gl.RGB
    } else if(shape[2] === 4) {
      format = gl.RGBA
    } else {
      throw new Error('gl-texture2d: Invalid shape for pixel coords')
    }
  } else {
    throw new Error('gl-texture2d: Invalid shape for texture')
  }
  if(type === gl.FLOAT && !gl.getExtension('OES_texture_float')) {
    type = gl.UNSIGNED_BYTE
    packed = false
  }
  var buffer, buf_store
  var size = array.size
  if(!packed) {
    var stride = [shape[2], shape[2]*shape[0], 1]
    buf_store = pool.malloc(size, dtype)
    var buf_array = ndarray(buf_store, shape, stride, 0)
    if((dtype === 'float32' || dtype === 'float64') && type === gl.UNSIGNED_BYTE) {
      convertFloatToUint8(buf_array, array)
    } else {
      ops.assign(buf_array, array)
    }
    buffer = buf_store.subarray(0, size)
  } else if (array.offset === 0 && array.data.length === size) {
    buffer = array.data
  } else {
    buffer = array.data.subarray(array.offset, array.offset + size)
  }
  var tex = initTexture(gl)
  gl.texImage2D(gl.TEXTURE_2D, 0, format, shape[0], shape[1], 0, format, type, buffer)
  if(!packed) {
    pool.free(buf_store)
  }
  return new Texture2D(gl, tex, shape[0], shape[1], format, type)
}

function createTexture2D(gl) {
  if(arguments.length <= 1) {
    throw new Error('gl-texture2d: Missing arguments for texture2d constructor')
  }
  if(!linearTypes) {
    lazyInitLinearTypes(gl)
  }
  if(typeof arguments[1] === 'number') {
    return createTextureShape(gl, arguments[1], arguments[2], arguments[3]||gl.RGBA, arguments[4]||gl.UNSIGNED_BYTE)
  }
  if(Array.isArray(arguments[1])) {
    return createTextureShape(gl, arguments[1][0]|0, arguments[1][1]|0, arguments[2]||gl.RGBA, arguments[3]||gl.UNSIGNED_BYTE)
  }
  if(typeof arguments[1] === 'object') {
    var obj = arguments[1]
    var directData = acceptTextureDOM(obj) ? obj : obj.raw
    if (directData) {
      return createTextureDOM(gl, directData, obj.width|0, obj.height|0, arguments[2]||gl.RGBA, arguments[3]||gl.UNSIGNED_BYTE)
    } else if(obj.shape && obj.data && obj.stride) {
      return createTextureArray(gl, obj)
    }
  }
  throw new Error('gl-texture2d: Invalid arguments for texture2d constructor')
}

},{"ndarray":436,"ndarray-ops":430,"typedarray-pool":523}],309:[function(_dereq_,module,exports){
/** @module  gl-util/context */
'use strict'

var pick = _dereq_('pick-by-alias')

module.exports = function setContext (o) {
	if (!o) o = {}
	else if (typeof o === 'string') o = {container: o}

	// HTMLCanvasElement
	if (isCanvas(o)) {
		o = {container: o}
	}
	// HTMLElement
	else if (isElement(o)) {
		o = {container: o}
	}
	// WebGLContext
	else if (isContext(o)) {
		o = {gl: o}
	}
	// options object
	else {
		o = pick(o, {
			container: 'container target element el canvas holder parent parentNode wrapper use ref root node',
			gl: 'gl context webgl glContext',
			attrs: 'attributes attrs contextAttributes',
			pixelRatio: 'pixelRatio pxRatio px ratio pxratio pixelratio'
		}, true)
	}

	if (!o.pixelRatio) o.pixelRatio = window.pixelRatio || 1

	// make sure there is container and canvas
	if (o.gl) {
		return o.gl
	}
	if (o.canvas) {
		o.container = o.canvas.parentNode
	}
	if (o.container) {
		if (typeof o.container === 'string') {
			var c = document.querySelector(o.container)
			if (!c) throw Error('Element ' + o.container + ' is not found')
			o.container = c
		}
		if (isCanvas(o.container)) {
			o.canvas = o.container
			o.container = o.canvas.parentNode
		}
		else if (!o.canvas) {
			o.canvas = document.createElement('canvas')
			o.container.appendChild(o.canvas)
			resize(o)
		}
	}
	// blank new canvas
	else if (!o.canvas) {
		o.container = document.body || document.documentElement
		o.canvas = document.createElement('canvas')
		o.canvas.style.position = 'absolute'
		o.canvas.style.top = 0
		o.canvas.style.left = 0
		o.container.appendChild(o.canvas)
		resize(o)
	}

	// make sure there is context
	if (!o.gl) {
		try {
			o.gl = o.canvas.getContext('webgl', o.attrs)
		} catch (e) {
			try {
				o.gl = o.canvas.getContext('experimental-webgl', o.attrs)
			}
			catch (e) {
				o.gl = o.canvas.getContext('webgl-experimental', o.attrs)
			}
		}
	}

	return o.gl
}


function resize (o) {
	if (o.container) {
		if (o.container == document.body) {
			if (!document.body.style.width) o.canvas.width = o.width || (o.pixelRatio * window.innerWidth)
			if (!document.body.style.height) o.canvas.height = o.height || (o.pixelRatio * window.innerHeight)
		}
		else {
			var bounds = o.container.getBoundingClientRect()
			o.canvas.width = o.width || (bounds.right - bounds.left)
			o.canvas.height = o.height || (bounds.bottom - bounds.top)
		}
	}
}

function isCanvas (e) {
	return typeof e.getContext === 'function'
		&& 'width' in e
		&& 'height' in e
}

function isElement (e) {
	return typeof e.nodeName === 'string' &&
		typeof e.appendChild === 'function' &&
		typeof e.getBoundingClientRect === 'function'
}

function isContext (e) {
	return typeof e.drawArrays === 'function' ||
		typeof e.drawElements === 'function'
}

},{"pick-by-alias":451}],310:[function(_dereq_,module,exports){
"use strict"

function doBind(gl, elements, attributes) {
  if(elements) {
    elements.bind()
  } else {
    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null)
  }
  var nattribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS)|0
  if(attributes) {
    if(attributes.length > nattribs) {
      throw new Error("gl-vao: Too many vertex attributes")
    }
    for(var i=0; i<attributes.length; ++i) {
      var attrib = attributes[i]
      if(attrib.buffer) {
        var buffer = attrib.buffer
        var size = attrib.size || 4
        var type = attrib.type || gl.FLOAT
        var normalized = !!attrib.normalized
        var stride = attrib.stride || 0
        var offset = attrib.offset || 0
        buffer.bind()
        gl.enableVertexAttribArray(i)
        gl.vertexAttribPointer(i, size, type, normalized, stride, offset)
      } else {
        if(typeof attrib === "number") {
          gl.vertexAttrib1f(i, attrib)
        } else if(attrib.length === 1) {
          gl.vertexAttrib1f(i, attrib[0])
        } else if(attrib.length === 2) {
          gl.vertexAttrib2f(i, attrib[0], attrib[1])
        } else if(attrib.length === 3) {
          gl.vertexAttrib3f(i, attrib[0], attrib[1], attrib[2])
        } else if(attrib.length === 4) {
          gl.vertexAttrib4f(i, attrib[0], attrib[1], attrib[2], attrib[3])
        } else {
          throw new Error("gl-vao: Invalid vertex attribute")
        }
        gl.disableVertexAttribArray(i)
      }
    }
    for(; i<nattribs; ++i) {
      gl.disableVertexAttribArray(i)
    }
  } else {
    gl.bindBuffer(gl.ARRAY_BUFFER, null)
    for(var i=0; i<nattribs; ++i) {
      gl.disableVertexAttribArray(i)
    }
  }
}

module.exports = doBind
},{}],311:[function(_dereq_,module,exports){
"use strict"

var bindAttribs = _dereq_("./do-bind.js")

function VAOEmulated(gl) {
  this.gl = gl
  this._elements = null
  this._attributes = null
  this._elementsType = gl.UNSIGNED_SHORT
}

VAOEmulated.prototype.bind = function() {
  bindAttribs(this.gl, this._elements, this._attributes)
}

VAOEmulated.prototype.update = function(attributes, elements, elementsType) {
  this._elements = elements
  this._attributes = attributes
  this._elementsType = elementsType || this.gl.UNSIGNED_SHORT
}

VAOEmulated.prototype.dispose = function() { }
VAOEmulated.prototype.unbind = function() { }

VAOEmulated.prototype.draw = function(mode, count, offset) {
  offset = offset || 0
  var gl = this.gl
  if(this._elements) {
    gl.drawElements(mode, count, this._elementsType, offset)
  } else {
    gl.drawArrays(mode, offset, count)
  }
}

function createVAOEmulated(gl) {
  return new VAOEmulated(gl)
}

module.exports = createVAOEmulated
},{"./do-bind.js":310}],312:[function(_dereq_,module,exports){
"use strict"

var bindAttribs = _dereq_("./do-bind.js")

function VertexAttribute(location, dimension, a, b, c, d) {
  this.location = location
  this.dimension = dimension
  this.a = a
  this.b = b
  this.c = c
  this.d = d
}

VertexAttribute.prototype.bind = function(gl) {
  switch(this.dimension) {
    case 1:
      gl.vertexAttrib1f(this.location, this.a)
    break
    case 2:
      gl.vertexAttrib2f(this.location, this.a, this.b)
    break
    case 3:
      gl.vertexAttrib3f(this.location, this.a, this.b, this.c)
    break
    case 4:
      gl.vertexAttrib4f(this.location, this.a, this.b, this.c, this.d)
    break
  }
}

function VAONative(gl, ext, handle) {
  this.gl = gl
  this._ext = ext
  this.handle = handle
  this._attribs = []
  this._useElements = false
  this._elementsType = gl.UNSIGNED_SHORT
}

VAONative.prototype.bind = function() {
  this._ext.bindVertexArrayOES(this.handle)
  for(var i=0; i<this._attribs.length; ++i) {
    this._attribs[i].bind(this.gl)
  }
}

VAONative.prototype.unbind = function() {
  this._ext.bindVertexArrayOES(null)
}

VAONative.prototype.dispose = function() {
  this._ext.deleteVertexArrayOES(this.handle)
}

VAONative.prototype.update = function(attributes, elements, elementsType) {
  this.bind()
  bindAttribs(this.gl, elements, attributes)
  this.unbind()
  this._attribs.length = 0
  if(attributes)
  for(var i=0; i<attributes.length; ++i) {
    var a = attributes[i]
    if(typeof a === "number") {
      this._attribs.push(new VertexAttribute(i, 1, a))
    } else if(Array.isArray(a)) {
      this._attribs.push(new VertexAttribute(i, a.length, a[0], a[1], a[2], a[3]))
    }
  }
  this._useElements = !!elements
  this._elementsType = elementsType || this.gl.UNSIGNED_SHORT
}

VAONative.prototype.draw = function(mode, count, offset) {
  offset = offset || 0
  var gl = this.gl
  if(this._useElements) {
    gl.drawElements(mode, count, this._elementsType, offset)
  } else {
    gl.drawArrays(mode, offset, count)
  }
}

function createVAONative(gl, ext) {
  return new VAONative(gl, ext, ext.createVertexArrayOES())
}

module.exports = createVAONative
},{"./do-bind.js":310}],313:[function(_dereq_,module,exports){
"use strict"

var createVAONative = _dereq_("./lib/vao-native.js")
var createVAOEmulated = _dereq_("./lib/vao-emulated.js")

function ExtensionShim (gl) {
  this.bindVertexArrayOES = gl.bindVertexArray.bind(gl)
  this.createVertexArrayOES = gl.createVertexArray.bind(gl)
  this.deleteVertexArrayOES = gl.deleteVertexArray.bind(gl)
}

function createVAO(gl, attributes, elements, elementsType) {
  var ext = gl.createVertexArray
    ? new ExtensionShim(gl)
    : gl.getExtension('OES_vertex_array_object')
  var vao

  if(ext) {
    vao = createVAONative(gl, ext)
  } else {
    vao = createVAOEmulated(gl)
  }
  vao.update(attributes, elements, elementsType)
  return vao
}

module.exports = createVAO

},{"./lib/vao-emulated.js":311,"./lib/vao-native.js":312}],314:[function(_dereq_,module,exports){
module.exports = add;

/**
 * Adds two vec3's
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @returns {vec3} out
 */
function add(out, a, b) {
    out[0] = a[0] + b[0]
    out[1] = a[1] + b[1]
    out[2] = a[2] + b[2]
    return out
}
},{}],315:[function(_dereq_,module,exports){
module.exports = angle

var fromValues = _dereq_('./fromValues')
var normalize = _dereq_('./normalize')
var dot = _dereq_('./dot')

/**
 * Get the angle between two 3D vectors
 * @param {vec3} a The first operand
 * @param {vec3} b The second operand
 * @returns {Number} The angle in radians
 */
function angle(a, b) {
    var tempA = fromValues(a[0], a[1], a[2])
    var tempB = fromValues(b[0], b[1], b[2])
 
    normalize(tempA, tempA)
    normalize(tempB, tempB)
 
    var cosine = dot(tempA, tempB)

    if(cosine > 1.0){
        return 0
    } else {
        return Math.acos(cosine)
    }     
}

},{"./dot":325,"./fromValues":331,"./normalize":342}],316:[function(_dereq_,module,exports){
module.exports = ceil

/**
 * Math.ceil the components of a vec3
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a vector to ceil
 * @returns {vec3} out
 */
function ceil(out, a) {
  out[0] = Math.ceil(a[0])
  out[1] = Math.ceil(a[1])
  out[2] = Math.ceil(a[2])
  return out
}

},{}],317:[function(_dereq_,module,exports){
module.exports = clone;

/**
 * Creates a new vec3 initialized with values from an existing vector
 *
 * @param {vec3} a vector to clone
 * @returns {vec3} a new 3D vector
 */
function clone(a) {
    var out = new Float32Array(3)
    out[0] = a[0]
    out[1] = a[1]
    out[2] = a[2]
    return out
}
},{}],318:[function(_dereq_,module,exports){
module.exports = copy;

/**
 * Copy the values from one vec3 to another
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the source vector
 * @returns {vec3} out
 */
function copy(out, a) {
    out[0] = a[0]
    out[1] = a[1]
    out[2] = a[2]
    return out
}
},{}],319:[function(_dereq_,module,exports){
module.exports = create;

/**
 * Creates a new, empty vec3
 *
 * @returns {vec3} a new 3D vector
 */
function create() {
    var out = new Float32Array(3)
    out[0] = 0
    out[1] = 0
    out[2] = 0
    return out
}
},{}],320:[function(_dereq_,module,exports){
module.exports = cross;

/**
 * Computes the cross product of two vec3's
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @returns {vec3} out
 */
function cross(out, a, b) {
    var ax = a[0], ay = a[1], az = a[2],
        bx = b[0], by = b[1], bz = b[2]

    out[0] = ay * bz - az * by
    out[1] = az * bx - ax * bz
    out[2] = ax * by - ay * bx
    return out
}
},{}],321:[function(_dereq_,module,exports){
module.exports = _dereq_('./distance')

},{"./distance":322}],322:[function(_dereq_,module,exports){
module.exports = distance;

/**
 * Calculates the euclidian distance between two vec3's
 *
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @returns {Number} distance between a and b
 */
function distance(a, b) {
    var x = b[0] - a[0],
        y = b[1] - a[1],
        z = b[2] - a[2]
    return Math.sqrt(x*x + y*y + z*z)
}
},{}],323:[function(_dereq_,module,exports){
module.exports = _dereq_('./divide')

},{"./divide":324}],324:[function(_dereq_,module,exports){
module.exports = divide;

/**
 * Divides two vec3's
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @returns {vec3} out
 */
function divide(out, a, b) {
    out[0] = a[0] / b[0]
    out[1] = a[1] / b[1]
    out[2] = a[2] / b[2]
    return out
}
},{}],325:[function(_dereq_,module,exports){
module.exports = dot;

/**
 * Calculates the dot product of two vec3's
 *
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @returns {Number} dot product of a and b
 */
function dot(a, b) {
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
},{}],326:[function(_dereq_,module,exports){
module.exports = 0.000001

},{}],327:[function(_dereq_,module,exports){
module.exports = equals

var EPSILON = _dereq_('./epsilon')

/**
 * Returns whether or not the vectors have approximately the same elements in the same position.
 *
 * @param {vec3} a The first vector.
 * @param {vec3} b The second vector.
 * @returns {Boolean} True if the vectors are equal, false otherwise.
 */
function equals(a, b) {
  var a0 = a[0]
  var a1 = a[1]
  var a2 = a[2]
  var b0 = b[0]
  var b1 = b[1]
  var b2 = b[2]
  return (Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) &&
          Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) &&
          Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)))
}

},{"./epsilon":326}],328:[function(_dereq_,module,exports){
module.exports = exactEquals

/**
 * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===)
 *
 * @param {vec3} a The first vector.
 * @param {vec3} b The second vector.
 * @returns {Boolean} True if the vectors are equal, false otherwise.
 */
function exactEquals(a, b) {
  return a[0] === b[0] && a[1] === b[1] && a[2] === b[2]
}

},{}],329:[function(_dereq_,module,exports){
module.exports = floor

/**
 * Math.floor the components of a vec3
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a vector to floor
 * @returns {vec3} out
 */
function floor(out, a) {
  out[0] = Math.floor(a[0])
  out[1] = Math.floor(a[1])
  out[2] = Math.floor(a[2])
  return out
}

},{}],330:[function(_dereq_,module,exports){
module.exports = forEach;

var vec = _dereq_('./create')()

/**
 * Perform some operation over an array of vec3s.
 *
 * @param {Array} a the array of vectors to iterate over
 * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
 * @param {Number} offset Number of elements to skip at the beginning of the array
 * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
 * @param {Function} fn Function to call for each vector in the array
 * @param {Object} [arg] additional argument to pass to fn
 * @returns {Array} a
 * @function
 */
function forEach(a, stride, offset, count, fn, arg) {
        var i, l
        if(!stride) {
            stride = 3
        }

        if(!offset) {
            offset = 0
        }
        
        if(count) {
            l = Math.min((count * stride) + offset, a.length)
        } else {
            l = a.length
        }

        for(i = offset; i < l; i += stride) {
            vec[0] = a[i] 
            vec[1] = a[i+1] 
            vec[2] = a[i+2]
            fn(vec, vec, arg)
            a[i] = vec[0] 
            a[i+1] = vec[1] 
            a[i+2] = vec[2]
        }
        
        return a
}
},{"./create":319}],331:[function(_dereq_,module,exports){
module.exports = fromValues;

/**
 * Creates a new vec3 initialized with the given values
 *
 * @param {Number} x X component
 * @param {Number} y Y component
 * @param {Number} z Z component
 * @returns {vec3} a new 3D vector
 */
function fromValues(x, y, z) {
    var out = new Float32Array(3)
    out[0] = x
    out[1] = y
    out[2] = z
    return out
}
},{}],332:[function(_dereq_,module,exports){
module.exports = {
  EPSILON: _dereq_('./epsilon')
  , create: _dereq_('./create')
  , clone: _dereq_('./clone')
  , angle: _dereq_('./angle')
  , fromValues: _dereq_('./fromValues')
  , copy: _dereq_('./copy')
  , set: _dereq_('./set')
  , equals: _dereq_('./equals')
  , exactEquals: _dereq_('./exactEquals')
  , add: _dereq_('./add')
  , subtract: _dereq_('./subtract')
  , sub: _dereq_('./sub')
  , multiply: _dereq_('./multiply')
  , mul: _dereq_('./mul')
  , divide: _dereq_('./divide')
  , div: _dereq_('./div')
  , min: _dereq_('./min')
  , max: _dereq_('./max')
  , floor: _dereq_('./floor')
  , ceil: _dereq_('./ceil')
  , round: _dereq_('./round')
  , scale: _dereq_('./scale')
  , scaleAndAdd: _dereq_('./scaleAndAdd')
  , distance: _dereq_('./distance')
  , dist: _dereq_('./dist')
  , squaredDistance: _dereq_('./squaredDistance')
  , sqrDist: _dereq_('./sqrDist')
  , length: _dereq_('./length')
  , len: _dereq_('./len')
  , squaredLength: _dereq_('./squaredLength')
  , sqrLen: _dereq_('./sqrLen')
  , negate: _dereq_('./negate')
  , inverse: _dereq_('./inverse')
  , normalize: _dereq_('./normalize')
  , dot: _dereq_('./dot')
  , cross: _dereq_('./cross')
  , lerp: _dereq_('./lerp')
  , random: _dereq_('./random')
  , transformMat4: _dereq_('./transformMat4')
  , transformMat3: _dereq_('./transformMat3')
  , transformQuat: _dereq_('./transformQuat')
  , rotateX: _dereq_('./rotateX')
  , rotateY: _dereq_('./rotateY')
  , rotateZ: _dereq_('./rotateZ')
  , forEach: _dereq_('./forEach')
}

},{"./add":314,"./angle":315,"./ceil":316,"./clone":317,"./copy":318,"./create":319,"./cross":320,"./dist":321,"./distance":322,"./div":323,"./divide":324,"./dot":325,"./epsilon":326,"./equals":327,"./exactEquals":328,"./floor":329,"./forEach":330,"./fromValues":331,"./inverse":333,"./len":334,"./length":335,"./lerp":336,"./max":337,"./min":338,"./mul":339,"./multiply":340,"./negate":341,"./normalize":342,"./random":343,"./rotateX":344,"./rotateY":345,"./rotateZ":346,"./round":347,"./scale":348,"./scaleAndAdd":349,"./set":350,"./sqrDist":351,"./sqrLen":352,"./squaredDistance":353,"./squaredLength":354,"./sub":355,"./subtract":356,"./transformMat3":357,"./transformMat4":358,"./transformQuat":359}],333:[function(_dereq_,module,exports){
module.exports = inverse;

/**
 * Returns the inverse of the components of a vec3
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a vector to invert
 * @returns {vec3} out
 */
function inverse(out, a) {
  out[0] = 1.0 / a[0]
  out[1] = 1.0 / a[1]
  out[2] = 1.0 / a[2]
  return out
}
},{}],334:[function(_dereq_,module,exports){
module.exports = _dereq_('./length')

},{"./length":335}],335:[function(_dereq_,module,exports){
module.exports = length;

/**
 * Calculates the length of a vec3
 *
 * @param {vec3} a vector to calculate length of
 * @returns {Number} length of a
 */
function length(a) {
    var x = a[0],
        y = a[1],
        z = a[2]
    return Math.sqrt(x*x + y*y + z*z)
}
},{}],336:[function(_dereq_,module,exports){
module.exports = lerp;

/**
 * Performs a linear interpolation between two vec3's
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @param {Number} t interpolation amount between the two inputs
 * @returns {vec3} out
 */
function lerp(out, a, b, t) {
    var ax = a[0],
        ay = a[1],
        az = a[2]
    out[0] = ax + t * (b[0] - ax)
    out[1] = ay + t * (b[1] - ay)
    out[2] = az + t * (b[2] - az)
    return out
}
},{}],337:[function(_dereq_,module,exports){
module.exports = max;

/**
 * Returns the maximum of two vec3's
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @returns {vec3} out
 */
function max(out, a, b) {
    out[0] = Math.max(a[0], b[0])
    out[1] = Math.max(a[1], b[1])
    out[2] = Math.max(a[2], b[2])
    return out
}
},{}],338:[function(_dereq_,module,exports){
module.exports = min;

/**
 * Returns the minimum of two vec3's
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @returns {vec3} out
 */
function min(out, a, b) {
    out[0] = Math.min(a[0], b[0])
    out[1] = Math.min(a[1], b[1])
    out[2] = Math.min(a[2], b[2])
    return out
}
},{}],339:[function(_dereq_,module,exports){
module.exports = _dereq_('./multiply')

},{"./multiply":340}],340:[function(_dereq_,module,exports){
module.exports = multiply;

/**
 * Multiplies two vec3's
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @returns {vec3} out
 */
function multiply(out, a, b) {
    out[0] = a[0] * b[0]
    out[1] = a[1] * b[1]
    out[2] = a[2] * b[2]
    return out
}
},{}],341:[function(_dereq_,module,exports){
module.exports = negate;

/**
 * Negates the components of a vec3
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a vector to negate
 * @returns {vec3} out
 */
function negate(out, a) {
    out[0] = -a[0]
    out[1] = -a[1]
    out[2] = -a[2]
    return out
}
},{}],342:[function(_dereq_,module,exports){
module.exports = normalize;

/**
 * Normalize a vec3
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a vector to normalize
 * @returns {vec3} out
 */
function normalize(out, a) {
    var x = a[0],
        y = a[1],
        z = a[2]
    var len = x*x + y*y + z*z
    if (len > 0) {
        //TODO: evaluate use of glm_invsqrt here?
        len = 1 / Math.sqrt(len)
        out[0] = a[0] * len
        out[1] = a[1] * len
        out[2] = a[2] * len
    }
    return out
}
},{}],343:[function(_dereq_,module,exports){
module.exports = random;

/**
 * Generates a random vector with the given scale
 *
 * @param {vec3} out the receiving vector
 * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned
 * @returns {vec3} out
 */
function random(out, scale) {
    scale = scale || 1.0

    var r = Math.random() * 2.0 * Math.PI
    var z = (Math.random() * 2.0) - 1.0
    var zScale = Math.sqrt(1.0-z*z) * scale

    out[0] = Math.cos(r) * zScale
    out[1] = Math.sin(r) * zScale
    out[2] = z * scale
    return out
}
},{}],344:[function(_dereq_,module,exports){
module.exports = rotateX;

/**
 * Rotate a 3D vector around the x-axis
 * @param {vec3} out The receiving vec3
 * @param {vec3} a The vec3 point to rotate
 * @param {vec3} b The origin of the rotation
 * @param {Number} c The angle of rotation
 * @returns {vec3} out
 */
function rotateX(out, a, b, c){
    var by = b[1]
    var bz = b[2]

    // Translate point to the origin
    var py = a[1] - by
    var pz = a[2] - bz

    var sc = Math.sin(c)
    var cc = Math.cos(c)

    // perform rotation and translate to correct position
    out[0] = a[0]
    out[1] = by + py * cc - pz * sc
    out[2] = bz + py * sc + pz * cc

    return out
}

},{}],345:[function(_dereq_,module,exports){
module.exports = rotateY;

/**
 * Rotate a 3D vector around the y-axis
 * @param {vec3} out The receiving vec3
 * @param {vec3} a The vec3 point to rotate
 * @param {vec3} b The origin of the rotation
 * @param {Number} c The angle of rotation
 * @returns {vec3} out
 */
function rotateY(out, a, b, c){
    var bx = b[0]
    var bz = b[2]

    // translate point to the origin
    var px = a[0] - bx
    var pz = a[2] - bz
    
    var sc = Math.sin(c)
    var cc = Math.cos(c)
  
    // perform rotation and translate to correct position
    out[0] = bx + pz * sc + px * cc
    out[1] = a[1]
    out[2] = bz + pz * cc - px * sc
  
    return out
}

},{}],346:[function(_dereq_,module,exports){
module.exports = rotateZ;

/**
 * Rotate a 3D vector around the z-axis
 * @param {vec3} out The receiving vec3
 * @param {vec3} a The vec3 point to rotate
 * @param {vec3} b The origin of the rotation
 * @param {Number} c The angle of rotation
 * @returns {vec3} out
 */
function rotateZ(out, a, b, c){
    var bx = b[0]
    var by = b[1]

    //Translate point to the origin
    var px = a[0] - bx
    var py = a[1] - by
  
    var sc = Math.sin(c)
    var cc = Math.cos(c)

    // perform rotation and translate to correct position
    out[0] = bx + px * cc - py * sc
    out[1] = by + px * sc + py * cc
    out[2] = a[2]
  
    return out
}

},{}],347:[function(_dereq_,module,exports){
module.exports = round

/**
 * Math.round the components of a vec3
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a vector to round
 * @returns {vec3} out
 */
function round(out, a) {
  out[0] = Math.round(a[0])
  out[1] = Math.round(a[1])
  out[2] = Math.round(a[2])
  return out
}

},{}],348:[function(_dereq_,module,exports){
module.exports = scale;

/**
 * Scales a vec3 by a scalar number
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the vector to scale
 * @param {Number} b amount to scale the vector by
 * @returns {vec3} out
 */
function scale(out, a, b) {
    out[0] = a[0] * b
    out[1] = a[1] * b
    out[2] = a[2] * b
    return out
}
},{}],349:[function(_dereq_,module,exports){
module.exports = scaleAndAdd;

/**
 * Adds two vec3's after scaling the second operand by a scalar value
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @param {Number} scale the amount to scale b by before adding
 * @returns {vec3} out
 */
function scaleAndAdd(out, a, b, scale) {
    out[0] = a[0] + (b[0] * scale)
    out[1] = a[1] + (b[1] * scale)
    out[2] = a[2] + (b[2] * scale)
    return out
}
},{}],350:[function(_dereq_,module,exports){
module.exports = set;

/**
 * Set the components of a vec3 to the given values
 *
 * @param {vec3} out the receiving vector
 * @param {Number} x X component
 * @param {Number} y Y component
 * @param {Number} z Z component
 * @returns {vec3} out
 */
function set(out, x, y, z) {
    out[0] = x
    out[1] = y
    out[2] = z
    return out
}
},{}],351:[function(_dereq_,module,exports){
module.exports = _dereq_('./squaredDistance')

},{"./squaredDistance":353}],352:[function(_dereq_,module,exports){
module.exports = _dereq_('./squaredLength')

},{"./squaredLength":354}],353:[function(_dereq_,module,exports){
module.exports = squaredDistance;

/**
 * Calculates the squared euclidian distance between two vec3's
 *
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @returns {Number} squared distance between a and b
 */
function squaredDistance(a, b) {
    var x = b[0] - a[0],
        y = b[1] - a[1],
        z = b[2] - a[2]
    return x*x + y*y + z*z
}
},{}],354:[function(_dereq_,module,exports){
module.exports = squaredLength;

/**
 * Calculates the squared length of a vec3
 *
 * @param {vec3} a vector to calculate squared length of
 * @returns {Number} squared length of a
 */
function squaredLength(a) {
    var x = a[0],
        y = a[1],
        z = a[2]
    return x*x + y*y + z*z
}
},{}],355:[function(_dereq_,module,exports){
module.exports = _dereq_('./subtract')

},{"./subtract":356}],356:[function(_dereq_,module,exports){
module.exports = subtract;

/**
 * Subtracts vector b from vector a
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the first operand
 * @param {vec3} b the second operand
 * @returns {vec3} out
 */
function subtract(out, a, b) {
    out[0] = a[0] - b[0]
    out[1] = a[1] - b[1]
    out[2] = a[2] - b[2]
    return out
}
},{}],357:[function(_dereq_,module,exports){
module.exports = transformMat3;

/**
 * Transforms the vec3 with a mat3.
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the vector to transform
 * @param {mat4} m the 3x3 matrix to transform with
 * @returns {vec3} out
 */
function transformMat3(out, a, m) {
    var x = a[0], y = a[1], z = a[2]
    out[0] = x * m[0] + y * m[3] + z * m[6]
    out[1] = x * m[1] + y * m[4] + z * m[7]
    out[2] = x * m[2] + y * m[5] + z * m[8]
    return out
}
},{}],358:[function(_dereq_,module,exports){
module.exports = transformMat4;

/**
 * Transforms the vec3 with a mat4.
 * 4th vector component is implicitly '1'
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the vector to transform
 * @param {mat4} m matrix to transform with
 * @returns {vec3} out
 */
function transformMat4(out, a, m) {
    var x = a[0], y = a[1], z = a[2],
        w = m[3] * x + m[7] * y + m[11] * z + m[15]
    w = w || 1.0
    out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w
    out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w
    out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w
    return out
}
},{}],359:[function(_dereq_,module,exports){
module.exports = transformQuat;

/**
 * Transforms the vec3 with a quat
 *
 * @param {vec3} out the receiving vector
 * @param {vec3} a the vector to transform
 * @param {quat} q quaternion to transform with
 * @returns {vec3} out
 */
function transformQuat(out, a, q) {
    // benchmarks: http://jsperf.com/quaternion-transform-vec3-implementations

    var x = a[0], y = a[1], z = a[2],
        qx = q[0], qy = q[1], qz = q[2], qw = q[3],

        // calculate quat * vec
        ix = qw * x + qy * z - qz * y,
        iy = qw * y + qz * x - qx * z,
        iz = qw * z + qx * y - qy * x,
        iw = -qx * x - qy * y - qz * z

    // calculate result * inverse quat
    out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy
    out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz
    out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx
    return out
}
},{}],360:[function(_dereq_,module,exports){
module.exports = add

/**
 * Adds two vec4's
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the first operand
 * @param {vec4} b the second operand
 * @returns {vec4} out
 */
function add (out, a, b) {
  out[0] = a[0] + b[0]
  out[1] = a[1] + b[1]
  out[2] = a[2] + b[2]
  out[3] = a[3] + b[3]
  return out
}

},{}],361:[function(_dereq_,module,exports){
module.exports = clone

/**
 * Creates a new vec4 initialized with values from an existing vector
 *
 * @param {vec4} a vector to clone
 * @returns {vec4} a new 4D vector
 */
function clone (a) {
  var out = new Float32Array(4)
  out[0] = a[0]
  out[1] = a[1]
  out[2] = a[2]
  out[3] = a[3]
  return out
}

},{}],362:[function(_dereq_,module,exports){
module.exports = copy

/**
 * Copy the values from one vec4 to another
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the source vector
 * @returns {vec4} out
 */
function copy (out, a) {
  out[0] = a[0]
  out[1] = a[1]
  out[2] = a[2]
  out[3] = a[3]
  return out
}

},{}],363:[function(_dereq_,module,exports){
module.exports = create

/**
 * Creates a new, empty vec4
 *
 * @returns {vec4} a new 4D vector
 */
function create () {
  var out = new Float32Array(4)
  out[0] = 0
  out[1] = 0
  out[2] = 0
  out[3] = 0
  return out
}

},{}],364:[function(_dereq_,module,exports){
module.exports = distance

/**
 * Calculates the euclidian distance between two vec4's
 *
 * @param {vec4} a the first operand
 * @param {vec4} b the second operand
 * @returns {Number} distance between a and b
 */
function distance (a, b) {
  var x = b[0] - a[0],
    y = b[1] - a[1],
    z = b[2] - a[2],
    w = b[3] - a[3]
  return Math.sqrt(x * x + y * y + z * z + w * w)
}

},{}],365:[function(_dereq_,module,exports){
module.exports = divide

/**
 * Divides two vec4's
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the first operand
 * @param {vec4} b the second operand
 * @returns {vec4} out
 */
function divide (out, a, b) {
  out[0] = a[0] / b[0]
  out[1] = a[1] / b[1]
  out[2] = a[2] / b[2]
  out[3] = a[3] / b[3]
  return out
}

},{}],366:[function(_dereq_,module,exports){
module.exports = dot

/**
 * Calculates the dot product of two vec4's
 *
 * @param {vec4} a the first operand
 * @param {vec4} b the second operand
 * @returns {Number} dot product of a and b
 */
function dot (a, b) {
  return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]
}

},{}],367:[function(_dereq_,module,exports){
module.exports = fromValues

/**
 * Creates a new vec4 initialized with the given values
 *
 * @param {Number} x X component
 * @param {Number} y Y component
 * @param {Number} z Z component
 * @param {Number} w W component
 * @returns {vec4} a new 4D vector
 */
function fromValues (x, y, z, w) {
  var out = new Float32Array(4)
  out[0] = x
  out[1] = y
  out[2] = z
  out[3] = w
  return out
}

},{}],368:[function(_dereq_,module,exports){
module.exports = {
  create: _dereq_('./create'),
  clone: _dereq_('./clone'),
  fromValues: _dereq_('./fromValues'),
  copy: _dereq_('./copy'),
  set: _dereq_('./set'),
  add: _dereq_('./add'),
  subtract: _dereq_('./subtract'),
  multiply: _dereq_('./multiply'),
  divide: _dereq_('./divide'),
  min: _dereq_('./min'),
  max: _dereq_('./max'),
  scale: _dereq_('./scale'),
  scaleAndAdd: _dereq_('./scaleAndAdd'),
  distance: _dereq_('./distance'),
  squaredDistance: _dereq_('./squaredDistance'),
  length: _dereq_('./length'),
  squaredLength: _dereq_('./squaredLength'),
  negate: _dereq_('./negate'),
  inverse: _dereq_('./inverse'),
  normalize: _dereq_('./normalize'),
  dot: _dereq_('./dot'),
  lerp: _dereq_('./lerp'),
  random: _dereq_('./random'),
  transformMat4: _dereq_('./transformMat4'),
  transformQuat: _dereq_('./transformQuat')
}

},{"./add":360,"./clone":361,"./copy":362,"./create":363,"./distance":364,"./divide":365,"./dot":366,"./fromValues":367,"./inverse":369,"./length":370,"./lerp":371,"./max":372,"./min":373,"./multiply":374,"./negate":375,"./normalize":376,"./random":377,"./scale":378,"./scaleAndAdd":379,"./set":380,"./squaredDistance":381,"./squaredLength":382,"./subtract":383,"./transformMat4":384,"./transformQuat":385}],369:[function(_dereq_,module,exports){
module.exports = inverse

/**
 * Returns the inverse of the components of a vec4
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a vector to invert
 * @returns {vec4} out
 */
function inverse (out, a) {
  out[0] = 1.0 / a[0]
  out[1] = 1.0 / a[1]
  out[2] = 1.0 / a[2]
  out[3] = 1.0 / a[3]
  return out
}

},{}],370:[function(_dereq_,module,exports){
module.exports = length

/**
 * Calculates the length of a vec4
 *
 * @param {vec4} a vector to calculate length of
 * @returns {Number} length of a
 */
function length (a) {
  var x = a[0],
    y = a[1],
    z = a[2],
    w = a[3]
  return Math.sqrt(x * x + y * y + z * z + w * w)
}

},{}],371:[function(_dereq_,module,exports){
module.exports = lerp

/**
 * Performs a linear interpolation between two vec4's
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the first operand
 * @param {vec4} b the second operand
 * @param {Number} t interpolation amount between the two inputs
 * @returns {vec4} out
 */
function lerp (out, a, b, t) {
  var ax = a[0],
    ay = a[1],
    az = a[2],
    aw = a[3]
  out[0] = ax + t * (b[0] - ax)
  out[1] = ay + t * (b[1] - ay)
  out[2] = az + t * (b[2] - az)
  out[3] = aw + t * (b[3] - aw)
  return out
}

},{}],372:[function(_dereq_,module,exports){
module.exports = max

/**
 * Returns the maximum of two vec4's
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the first operand
 * @param {vec4} b the second operand
 * @returns {vec4} out
 */
function max (out, a, b) {
  out[0] = Math.max(a[0], b[0])
  out[1] = Math.max(a[1], b[1])
  out[2] = Math.max(a[2], b[2])
  out[3] = Math.max(a[3], b[3])
  return out
}

},{}],373:[function(_dereq_,module,exports){
module.exports = min

/**
 * Returns the minimum of two vec4's
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the first operand
 * @param {vec4} b the second operand
 * @returns {vec4} out
 */
function min (out, a, b) {
  out[0] = Math.min(a[0], b[0])
  out[1] = Math.min(a[1], b[1])
  out[2] = Math.min(a[2], b[2])
  out[3] = Math.min(a[3], b[3])
  return out
}

},{}],374:[function(_dereq_,module,exports){
module.exports = multiply

/**
 * Multiplies two vec4's
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the first operand
 * @param {vec4} b the second operand
 * @returns {vec4} out
 */
function multiply (out, a, b) {
  out[0] = a[0] * b[0]
  out[1] = a[1] * b[1]
  out[2] = a[2] * b[2]
  out[3] = a[3] * b[3]
  return out
}

},{}],375:[function(_dereq_,module,exports){
module.exports = negate

/**
 * Negates the components of a vec4
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a vector to negate
 * @returns {vec4} out
 */
function negate (out, a) {
  out[0] = -a[0]
  out[1] = -a[1]
  out[2] = -a[2]
  out[3] = -a[3]
  return out
}

},{}],376:[function(_dereq_,module,exports){
module.exports = normalize

/**
 * Normalize a vec4
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a vector to normalize
 * @returns {vec4} out
 */
function normalize (out, a) {
  var x = a[0],
    y = a[1],
    z = a[2],
    w = a[3]
  var len = x * x + y * y + z * z + w * w
  if (len > 0) {
    len = 1 / Math.sqrt(len)
    out[0] = x * len
    out[1] = y * len
    out[2] = z * len
    out[3] = w * len
  }
  return out
}

},{}],377:[function(_dereq_,module,exports){
var vecNormalize = _dereq_('./normalize')
var vecScale = _dereq_('./scale')

module.exports = random

/**
 * Generates a random vector with the given scale
 *
 * @param {vec4} out the receiving vector
 * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned
 * @returns {vec4} out
 */
function random (out, scale) {
  scale = scale || 1.0

  // TODO: This is a pretty awful way of doing this. Find something better.
  out[0] = Math.random()
  out[1] = Math.random()
  out[2] = Math.random()
  out[3] = Math.random()
  vecNormalize(out, out)
  vecScale(out, out, scale)
  return out
}

},{"./normalize":376,"./scale":378}],378:[function(_dereq_,module,exports){
module.exports = scale

/**
 * Scales a vec4 by a scalar number
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the vector to scale
 * @param {Number} b amount to scale the vector by
 * @returns {vec4} out
 */
function scale (out, a, b) {
  out[0] = a[0] * b
  out[1] = a[1] * b
  out[2] = a[2] * b
  out[3] = a[3] * b
  return out
}

},{}],379:[function(_dereq_,module,exports){
module.exports = scaleAndAdd

/**
 * Adds two vec4's after scaling the second operand by a scalar value
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the first operand
 * @param {vec4} b the second operand
 * @param {Number} scale the amount to scale b by before adding
 * @returns {vec4} out
 */
function scaleAndAdd (out, a, b, scale) {
  out[0] = a[0] + (b[0] * scale)
  out[1] = a[1] + (b[1] * scale)
  out[2] = a[2] + (b[2] * scale)
  out[3] = a[3] + (b[3] * scale)
  return out
}

},{}],380:[function(_dereq_,module,exports){
module.exports = set

/**
 * Set the components of a vec4 to the given values
 *
 * @param {vec4} out the receiving vector
 * @param {Number} x X component
 * @param {Number} y Y component
 * @param {Number} z Z component
 * @param {Number} w W component
 * @returns {vec4} out
 */
function set (out, x, y, z, w) {
  out[0] = x
  out[1] = y
  out[2] = z
  out[3] = w
  return out
}

},{}],381:[function(_dereq_,module,exports){
module.exports = squaredDistance

/**
 * Calculates the squared euclidian distance between two vec4's
 *
 * @param {vec4} a the first operand
 * @param {vec4} b the second operand
 * @returns {Number} squared distance between a and b
 */
function squaredDistance (a, b) {
  var x = b[0] - a[0],
    y = b[1] - a[1],
    z = b[2] - a[2],
    w = b[3] - a[3]
  return x * x + y * y + z * z + w * w
}

},{}],382:[function(_dereq_,module,exports){
module.exports = squaredLength

/**
 * Calculates the squared length of a vec4
 *
 * @param {vec4} a vector to calculate squared length of
 * @returns {Number} squared length of a
 */
function squaredLength (a) {
  var x = a[0],
    y = a[1],
    z = a[2],
    w = a[3]
  return x * x + y * y + z * z + w * w
}

},{}],383:[function(_dereq_,module,exports){
module.exports = subtract

/**
 * Subtracts vector b from vector a
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the first operand
 * @param {vec4} b the second operand
 * @returns {vec4} out
 */
function subtract (out, a, b) {
  out[0] = a[0] - b[0]
  out[1] = a[1] - b[1]
  out[2] = a[2] - b[2]
  out[3] = a[3] - b[3]
  return out
}

},{}],384:[function(_dereq_,module,exports){
module.exports = transformMat4

/**
 * Transforms the vec4 with a mat4.
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the vector to transform
 * @param {mat4} m matrix to transform with
 * @returns {vec4} out
 */
function transformMat4 (out, a, m) {
  var x = a[0], y = a[1], z = a[2], w = a[3]
  out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w
  out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w
  out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w
  out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w
  return out
}

},{}],385:[function(_dereq_,module,exports){
module.exports = transformQuat

/**
 * Transforms the vec4 with a quat
 *
 * @param {vec4} out the receiving vector
 * @param {vec4} a the vector to transform
 * @param {quat} q quaternion to transform with
 * @returns {vec4} out
 */
function transformQuat (out, a, q) {
  var x = a[0], y = a[1], z = a[2],
    qx = q[0], qy = q[1], qz = q[2], qw = q[3],

    // calculate quat * vec
    ix = qw * x + qy * z - qz * y,
    iy = qw * y + qz * x - qx * z,
    iz = qw * z + qx * y - qy * x,
    iw = -qx * x - qy * y - qz * z

  // calculate result * inverse quat
  out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy
  out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz
  out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx
  out[3] = a[3]
  return out
}

},{}],386:[function(_dereq_,module,exports){
module.exports = decodeFloat

var UINT8_VIEW = new Uint8Array(4)
var FLOAT_VIEW = new Float32Array(UINT8_VIEW.buffer)

function decodeFloat(x, y, z, w) {
  UINT8_VIEW[0] = w
  UINT8_VIEW[1] = z
  UINT8_VIEW[2] = y
  UINT8_VIEW[3] = x
  return FLOAT_VIEW[0]
}

},{}],387:[function(_dereq_,module,exports){
var tokenize = _dereq_('glsl-tokenizer')
var atob     = _dereq_('atob-lite')

module.exports = getName

function getName(src) {
  var tokens = Array.isArray(src)
    ? src
    : tokenize(src)

  for (var i = 0; i < tokens.length; i++) {
    var token = tokens[i]
    if (token.type !== 'preprocessor') continue
    var match = token.data.match(/\#define\s+SHADER_NAME(_B64)?\s+(.+)$/)
    if (!match) continue
    if (!match[2]) continue

    var b64  = match[1]
    var name = match[2]

    return (b64 ? atob(name) : name).trim()
  }
}

},{"atob-lite":61,"glsl-tokenizer":394}],388:[function(_dereq_,module,exports){
module.exports = tokenize

var literals100 = _dereq_('./lib/literals')
  , operators = _dereq_('./lib/operators')
  , builtins100 = _dereq_('./lib/builtins')
  , literals300es = _dereq_('./lib/literals-300es')
  , builtins300es = _dereq_('./lib/builtins-300es')

var NORMAL = 999          // <-- never emitted
  , TOKEN = 9999          // <-- never emitted
  , BLOCK_COMMENT = 0
  , LINE_COMMENT = 1
  , PREPROCESSOR = 2
  , OPERATOR = 3
  , INTEGER = 4
  , FLOAT = 5
  , IDENT = 6
  , BUILTIN = 7
  , KEYWORD = 8
  , WHITESPACE = 9
  , EOF = 10
  , HEX = 11

var map = [
    'block-comment'
  , 'line-comment'
  , 'preprocessor'
  , 'operator'
  , 'integer'
  , 'float'
  , 'ident'
  , 'builtin'
  , 'keyword'
  , 'whitespace'
  , 'eof'
  , 'integer'
]

function tokenize(opt) {
  var i = 0
    , total = 0
    , mode = NORMAL
    , c
    , last
    , content = []
    , tokens = []
    , token_idx = 0
    , token_offs = 0
    , line = 1
    , col = 0
    , start = 0
    , isnum = false
    , isoperator = false
    , input = ''
    , len

  opt = opt || {}
  var allBuiltins = builtins100
  var allLiterals = literals100
  if (opt.version === '300 es') {
    allBuiltins = builtins300es
    allLiterals = literals300es
  }

  return function(data) {
    tokens = []
    if (data !== null) return write(data.replace ? data.replace(/\r\n/g, '\n') : data)
    return end()
  }

  function token(data) {
    if (data.length) {
      tokens.push({
        type: map[mode]
      , data: data
      , position: start
      , line: line
      , column: col
      })
    }
  }

  function write(chunk) {
    i = 0
    input += chunk
    len = input.length

    var last

    while(c = input[i], i < len) {
      last = i

      switch(mode) {
        case BLOCK_COMMENT: i = block_comment(); break
        case LINE_COMMENT: i = line_comment(); break
        case PREPROCESSOR: i = preprocessor(); break
        case OPERATOR: i = operator(); break
        case INTEGER: i = integer(); break
        case HEX: i = hex(); break
        case FLOAT: i = decimal(); break
        case TOKEN: i = readtoken(); break
        case WHITESPACE: i = whitespace(); break
        case NORMAL: i = normal(); break
      }

      if(last !== i) {
        switch(input[last]) {
          case '\n': col = 0; ++line; break
          default: ++col; break
        }
      }
    }

    total += i
    input = input.slice(i)
    return tokens
  }

  function end(chunk) {
    if(content.length) {
      token(content.join(''))
    }

    mode = EOF
    token('(eof)')
    return tokens
  }

  function normal() {
    content = content.length ? [] : content

    if(last === '/' && c === '*') {
      start = total + i - 1
      mode = BLOCK_COMMENT
      last = c
      return i + 1
    }

    if(last === '/' && c === '/') {
      start = total + i - 1
      mode = LINE_COMMENT
      last = c
      return i + 1
    }

    if(c === '#') {
      mode = PREPROCESSOR
      start = total + i
      return i
    }

    if(/\s/.test(c)) {
      mode = WHITESPACE
      start = total + i
      return i
    }

    isnum = /\d/.test(c)
    isoperator = /[^\w_]/.test(c)

    start = total + i
    mode = isnum ? INTEGER : isoperator ? OPERATOR : TOKEN
    return i
  }

  function whitespace() {
    if(/[^\s]/g.test(c)) {
      token(content.join(''))
      mode = NORMAL
      return i
    }
    content.push(c)
    last = c
    return i + 1
  }

  function preprocessor() {
    if((c === '\r' || c === '\n') && last !== '\\') {
      token(content.join(''))
      mode = NORMAL
      return i
    }
    content.push(c)
    last = c
    return i + 1
  }

  function line_comment() {
    return preprocessor()
  }

  function block_comment() {
    if(c === '/' && last === '*') {
      content.push(c)
      token(content.join(''))
      mode = NORMAL
      return i + 1
    }

    content.push(c)
    last = c
    return i + 1
  }

  function operator() {
    if(last === '.' && /\d/.test(c)) {
      mode = FLOAT
      return i
    }

    if(last === '/' && c === '*') {
      mode = BLOCK_COMMENT
      return i
    }

    if(last === '/' && c === '/') {
      mode = LINE_COMMENT
      return i
    }

    if(c === '.' && content.length) {
      while(determine_operator(content));

      mode = FLOAT
      return i
    }

    if(c === ';' || c === ')' || c === '(') {
      if(content.length) while(determine_operator(content));
      token(c)
      mode = NORMAL
      return i + 1
    }

    var is_composite_operator = content.length === 2 && c !== '='
    if(/[\w_\d\s]/.test(c) || is_composite_operator) {
      while(determine_operator(content));
      mode = NORMAL
      return i
    }

    content.push(c)
    last = c
    return i + 1
  }

  function determine_operator(buf) {
    var j = 0
      , idx
      , res

    do {
      idx = operators.indexOf(buf.slice(0, buf.length + j).join(''))
      res = operators[idx]

      if(idx === -1) {
        if(j-- + buf.length > 0) continue
        res = buf.slice(0, 1).join('')
      }

      token(res)

      start += res.length
      content = content.slice(res.length)
      return content.length
    } while(1)
  }

  function hex() {
    if(/[^a-fA-F0-9]/.test(c)) {
      token(content.join(''))
      mode = NORMAL
      return i
    }

    content.push(c)
    last = c
    return i + 1
  }

  function integer() {
    if(c === '.') {
      content.push(c)
      mode = FLOAT
      last = c
      return i + 1
    }

    if(/[eE]/.test(c)) {
      content.push(c)
      mode = FLOAT
      last = c
      return i + 1
    }

    if(c === 'x' && content.length === 1 && content[0] === '0') {
      mode = HEX
      content.push(c)
      last = c
      return i + 1
    }

    if(/[^\d]/.test(c)) {
      token(content.join(''))
      mode = NORMAL
      return i
    }

    content.push(c)
    last = c
    return i + 1
  }

  function decimal() {
    if(c === 'f') {
      content.push(c)
      last = c
      i += 1
    }

    if(/[eE]/.test(c)) {
      content.push(c)
      last = c
      return i + 1
    }

    if (c === '-' && /[eE]/.test(last)) {
      content.push(c)
      last = c
      return i + 1
    }

    if(/[^\d]/.test(c)) {
      token(content.join(''))
      mode = NORMAL
      return i
    }

    content.push(c)
    last = c
    return i + 1
  }

  function readtoken() {
    if(/[^\d\w_]/.test(c)) {
      var contentstr = content.join('')
      if(allLiterals.indexOf(contentstr) > -1) {
        mode = KEYWORD
      } else if(allBuiltins.indexOf(contentstr) > -1) {
        mode = BUILTIN
      } else {
        mode = IDENT
      }
      token(content.join(''))
      mode = NORMAL
      return i
    }
    content.push(c)
    last = c
    return i + 1
  }
}

},{"./lib/builtins":390,"./lib/builtins-300es":389,"./lib/literals":392,"./lib/literals-300es":391,"./lib/operators":393}],389:[function(_dereq_,module,exports){
// 300es builtins/reserved words that were previously valid in v100
var v100 = _dereq_('./builtins')

// The texture2D|Cube functions have been removed
// And the gl_ features are updated
v100 = v100.slice().filter(function (b) {
  return !/^(gl\_|texture)/.test(b)
})

module.exports = v100.concat([
  // the updated gl_ constants
    'gl_VertexID'
  , 'gl_InstanceID'
  , 'gl_Position'
  , 'gl_PointSize'
  , 'gl_FragCoord'
  , 'gl_FrontFacing'
  , 'gl_FragDepth'
  , 'gl_PointCoord'
  , 'gl_MaxVertexAttribs'
  , 'gl_MaxVertexUniformVectors'
  , 'gl_MaxVertexOutputVectors'
  , 'gl_MaxFragmentInputVectors'
  , 'gl_MaxVertexTextureImageUnits'
  , 'gl_MaxCombinedTextureImageUnits'
  , 'gl_MaxTextureImageUnits'
  , 'gl_MaxFragmentUniformVectors'
  , 'gl_MaxDrawBuffers'
  , 'gl_MinProgramTexelOffset'
  , 'gl_MaxProgramTexelOffset'
  , 'gl_DepthRangeParameters'
  , 'gl_DepthRange'

  // other builtins
  , 'trunc'
  , 'round'
  , 'roundEven'
  , 'isnan'
  , 'isinf'
  , 'floatBitsToInt'
  , 'floatBitsToUint'
  , 'intBitsToFloat'
  , 'uintBitsToFloat'
  , 'packSnorm2x16'
  , 'unpackSnorm2x16'
  , 'packUnorm2x16'
  , 'unpackUnorm2x16'
  , 'packHalf2x16'
  , 'unpackHalf2x16'
  , 'outerProduct'
  , 'transpose'
  , 'determinant'
  , 'inverse'
  , 'texture'
  , 'textureSize'
  , 'textureProj'
  , 'textureLod'
  , 'textureOffset'
  , 'texelFetch'
  , 'texelFetchOffset'
  , 'textureProjOffset'
  , 'textureLodOffset'
  , 'textureProjLod'
  , 'textureProjLodOffset'
  , 'textureGrad'
  , 'textureGradOffset'
  , 'textureProjGrad'
  , 'textureProjGradOffset'
])

},{"./builtins":390}],390:[function(_dereq_,module,exports){
module.exports = [
  // Keep this list sorted
  'abs'
  , 'acos'
  , 'all'
  , 'any'
  , 'asin'
  , 'atan'
  , 'ceil'
  , 'clamp'
  , 'cos'
  , 'cross'
  , 'dFdx'
  , 'dFdy'
  , 'degrees'
  , 'distance'
  , 'dot'
  , 'equal'
  , 'exp'
  , 'exp2'
  , 'faceforward'
  , 'floor'
  , 'fract'
  , 'gl_BackColor'
  , 'gl_BackLightModelProduct'
  , 'gl_BackLightProduct'
  , 'gl_BackMaterial'
  , 'gl_BackSecondaryColor'
  , 'gl_ClipPlane'
  , 'gl_ClipVertex'
  , 'gl_Color'
  , 'gl_DepthRange'
  , 'gl_DepthRangeParameters'
  , 'gl_EyePlaneQ'
  , 'gl_EyePlaneR'
  , 'gl_EyePlaneS'
  , 'gl_EyePlaneT'
  , 'gl_Fog'
  , 'gl_FogCoord'
  , 'gl_FogFragCoord'
  , 'gl_FogParameters'
  , 'gl_FragColor'
  , 'gl_FragCoord'
  , 'gl_FragData'
  , 'gl_FragDepth'
  , 'gl_FragDepthEXT'
  , 'gl_FrontColor'
  , 'gl_FrontFacing'
  , 'gl_FrontLightModelProduct'
  , 'gl_FrontLightProduct'
  , 'gl_FrontMaterial'
  , 'gl_FrontSecondaryColor'
  , 'gl_LightModel'
  , 'gl_LightModelParameters'
  , 'gl_LightModelProducts'
  , 'gl_LightProducts'
  , 'gl_LightSource'
  , 'gl_LightSourceParameters'
  , 'gl_MaterialParameters'
  , 'gl_MaxClipPlanes'
  , 'gl_MaxCombinedTextureImageUnits'
  , 'gl_MaxDrawBuffers'
  , 'gl_MaxFragmentUniformComponents'
  , 'gl_MaxLights'
  , 'gl_MaxTextureCoords'
  , 'gl_MaxTextureImageUnits'
  , 'gl_MaxTextureUnits'
  , 'gl_MaxVaryingFloats'
  , 'gl_MaxVertexAttribs'
  , 'gl_MaxVertexTextureImageUnits'
  , 'gl_MaxVertexUniformComponents'
  , 'gl_ModelViewMatrix'
  , 'gl_ModelViewMatrixInverse'
  , 'gl_ModelViewMatrixInverseTranspose'
  , 'gl_ModelViewMatrixTranspose'
  , 'gl_ModelViewProjectionMatrix'
  , 'gl_ModelViewProjectionMatrixInverse'
  , 'gl_ModelViewProjectionMatrixInverseTranspose'
  , 'gl_ModelViewProjectionMatrixTranspose'
  , 'gl_MultiTexCoord0'
  , 'gl_MultiTexCoord1'
  , 'gl_MultiTexCoord2'
  , 'gl_MultiTexCoord3'
  , 'gl_MultiTexCoord4'
  , 'gl_MultiTexCoord5'
  , 'gl_MultiTexCoord6'
  , 'gl_MultiTexCoord7'
  , 'gl_Normal'
  , 'gl_NormalMatrix'
  , 'gl_NormalScale'
  , 'gl_ObjectPlaneQ'
  , 'gl_ObjectPlaneR'
  , 'gl_ObjectPlaneS'
  , 'gl_ObjectPlaneT'
  , 'gl_Point'
  , 'gl_PointCoord'
  , 'gl_PointParameters'
  , 'gl_PointSize'
  , 'gl_Position'
  , 'gl_ProjectionMatrix'
  , 'gl_ProjectionMatrixInverse'
  , 'gl_ProjectionMatrixInverseTranspose'
  , 'gl_ProjectionMatrixTranspose'
  , 'gl_SecondaryColor'
  , 'gl_TexCoord'
  , 'gl_TextureEnvColor'
  , 'gl_TextureMatrix'
  , 'gl_TextureMatrixInverse'
  , 'gl_TextureMatrixInverseTranspose'
  , 'gl_TextureMatrixTranspose'
  , 'gl_Vertex'
  , 'greaterThan'
  , 'greaterThanEqual'
  , 'inversesqrt'
  , 'length'
  , 'lessThan'
  , 'lessThanEqual'
  , 'log'
  , 'log2'
  , 'matrixCompMult'
  , 'max'
  , 'min'
  , 'mix'
  , 'mod'
  , 'normalize'
  , 'not'
  , 'notEqual'
  , 'pow'
  , 'radians'
  , 'reflect'
  , 'refract'
  , 'sign'
  , 'sin'
  , 'smoothstep'
  , 'sqrt'
  , 'step'
  , 'tan'
  , 'texture2D'
  , 'texture2DLod'
  , 'texture2DProj'
  , 'texture2DProjLod'
  , 'textureCube'
  , 'textureCubeLod'
  , 'texture2DLodEXT'
  , 'texture2DProjLodEXT'
  , 'textureCubeLodEXT'
  , 'texture2DGradEXT'
  , 'texture2DProjGradEXT'
  , 'textureCubeGradEXT'
]

},{}],391:[function(_dereq_,module,exports){
var v100 = _dereq_('./literals')

module.exports = v100.slice().concat([
   'layout'
  , 'centroid'
  , 'smooth'
  , 'case'
  , 'mat2x2'
  , 'mat2x3'
  , 'mat2x4'
  , 'mat3x2'
  , 'mat3x3'
  , 'mat3x4'
  , 'mat4x2'
  , 'mat4x3'
  , 'mat4x4'
  , 'uint'
  , 'uvec2'
  , 'uvec3'
  , 'uvec4'
  , 'samplerCubeShadow'
  , 'sampler2DArray'
  , 'sampler2DArrayShadow'
  , 'isampler2D'
  , 'isampler3D'
  , 'isamplerCube'
  , 'isampler2DArray'
  , 'usampler2D'
  , 'usampler3D'
  , 'usamplerCube'
  , 'usampler2DArray'
  , 'coherent'
  , 'restrict'
  , 'readonly'
  , 'writeonly'
  , 'resource'
  , 'atomic_uint'
  , 'noperspective'
  , 'patch'
  , 'sample'
  , 'subroutine'
  , 'common'
  , 'partition'
  , 'active'
  , 'filter'
  , 'image1D'
  , 'image2D'
  , 'image3D'
  , 'imageCube'
  , 'iimage1D'
  , 'iimage2D'
  , 'iimage3D'
  , 'iimageCube'
  , 'uimage1D'
  , 'uimage2D'
  , 'uimage3D'
  , 'uimageCube'
  , 'image1DArray'
  , 'image2DArray'
  , 'iimage1DArray'
  , 'iimage2DArray'
  , 'uimage1DArray'
  , 'uimage2DArray'
  , 'image1DShadow'
  , 'image2DShadow'
  , 'image1DArrayShadow'
  , 'image2DArrayShadow'
  , 'imageBuffer'
  , 'iimageBuffer'
  , 'uimageBuffer'
  , 'sampler1DArray'
  , 'sampler1DArrayShadow'
  , 'isampler1D'
  , 'isampler1DArray'
  , 'usampler1D'
  , 'usampler1DArray'
  , 'isampler2DRect'
  , 'usampler2DRect'
  , 'samplerBuffer'
  , 'isamplerBuffer'
  , 'usamplerBuffer'
  , 'sampler2DMS'
  , 'isampler2DMS'
  , 'usampler2DMS'
  , 'sampler2DMSArray'
  , 'isampler2DMSArray'
  , 'usampler2DMSArray'
])

},{"./literals":392}],392:[function(_dereq_,module,exports){
module.exports = [
  // current
    'precision'
  , 'highp'
  , 'mediump'
  , 'lowp'
  , 'attribute'
  , 'const'
  , 'uniform'
  , 'varying'
  , 'break'
  , 'continue'
  , 'do'
  , 'for'
  , 'while'
  , 'if'
  , 'else'
  , 'in'
  , 'out'
  , 'inout'
  , 'float'
  , 'int'
  , 'void'
  , 'bool'
  , 'true'
  , 'false'
  , 'discard'
  , 'return'
  , 'mat2'
  , 'mat3'
  , 'mat4'
  , 'vec2'
  , 'vec3'
  , 'vec4'
  , 'ivec2'
  , 'ivec3'
  , 'ivec4'
  , 'bvec2'
  , 'bvec3'
  , 'bvec4'
  , 'sampler1D'
  , 'sampler2D'
  , 'sampler3D'
  , 'samplerCube'
  , 'sampler1DShadow'
  , 'sampler2DShadow'
  , 'struct'

  // future
  , 'asm'
  , 'class'
  , 'union'
  , 'enum'
  , 'typedef'
  , 'template'
  , 'this'
  , 'packed'
  , 'goto'
  , 'switch'
  , 'default'
  , 'inline'
  , 'noinline'
  , 'volatile'
  , 'public'
  , 'static'
  , 'extern'
  , 'external'
  , 'interface'
  , 'long'
  , 'short'
  , 'double'
  , 'half'
  , 'fixed'
  , 'unsigned'
  , 'input'
  , 'output'
  , 'hvec2'
  , 'hvec3'
  , 'hvec4'
  , 'dvec2'
  , 'dvec3'
  , 'dvec4'
  , 'fvec2'
  , 'fvec3'
  , 'fvec4'
  , 'sampler2DRect'
  , 'sampler3DRect'
  , 'sampler2DRectShadow'
  , 'sizeof'
  , 'cast'
  , 'namespace'
  , 'using'
]

},{}],393:[function(_dereq_,module,exports){
module.exports = [
    '<<='
  , '>>='
  , '++'
  , '--'
  , '<<'
  , '>>'
  , '<='
  , '>='
  , '=='
  , '!='
  , '&&'
  , '||'
  , '+='
  , '-='
  , '*='
  , '/='
  , '%='
  , '&='
  , '^^'
  , '^='
  , '|='
  , '('
  , ')'
  , '['
  , ']'
  , '.'
  , '!'
  , '~'
  , '*'
  , '/'
  , '%'
  , '+'
  , '-'
  , '<'
  , '>'
  , '&'
  , '^'
  , '|'
  , '?'
  , ':'
  , '='
  , ','
  , ';'
  , '{'
  , '}'
]

},{}],394:[function(_dereq_,module,exports){
var tokenize = _dereq_('./index')

module.exports = tokenizeString

function tokenizeString(str, opt) {
  var generator = tokenize(opt)
  var tokens = []

  tokens = tokens.concat(generator(str))
  tokens = tokens.concat(generator(null))

  return tokens
}

},{"./index":388}],395:[function(_dereq_,module,exports){
module.exports = function(strings) {
  if (typeof strings === 'string') strings = [strings]
  var exprs = [].slice.call(arguments,1)
  var parts = []
  for (var i = 0; i < strings.length-1; i++) {
    parts.push(strings[i], exprs[i] || '')
  }
  parts.push(strings[i])
  return parts.join('')
}

},{}],396:[function(_dereq_,module,exports){
(function (global){
'use strict'

var isBrowser = _dereq_('is-browser')
var hasHover

if (typeof global.matchMedia === 'function') {
	hasHover = !global.matchMedia('(hover: none)').matches
}
else {
	hasHover = isBrowser
}

module.exports = hasHover

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"is-browser":403}],397:[function(_dereq_,module,exports){
'use strict'

var isBrowser = _dereq_('is-browser')

function detect() {
	var supported = false

	try {
		var opts = Object.defineProperty({}, 'passive', {
			get: function() {
				supported = true
			}
		})

		window.addEventListener('test', null, opts)
		window.removeEventListener('test', null, opts)
	} catch(e) {
		supported = false
	}

	return supported
}

module.exports = isBrowser && detect()

},{"is-browser":403}],398:[function(_dereq_,module,exports){
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  var e, m
  var eLen = (nBytes * 8) - mLen - 1
  var eMax = (1 << eLen) - 1
  var eBias = eMax >> 1
  var nBits = -7
  var i = isLE ? (nBytes - 1) : 0
  var d = isLE ? -1 : 1
  var s = buffer[offset + i]

  i += d

  e = s & ((1 << (-nBits)) - 1)
  s >>= (-nBits)
  nBits += eLen
  for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  m = e & ((1 << (-nBits)) - 1)
  e >>= (-nBits)
  nBits += mLen
  for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  if (e === 0) {
    e = 1 - eBias
  } else if (e === eMax) {
    return m ? NaN : ((s ? -1 : 1) * Infinity)
  } else {
    m = m + Math.pow(2, mLen)
    e = e - eBias
  }
  return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}

exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  var e, m, c
  var eLen = (nBytes * 8) - mLen - 1
  var eMax = (1 << eLen) - 1
  var eBias = eMax >> 1
  var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  var i = isLE ? 0 : (nBytes - 1)
  var d = isLE ? 1 : -1
  var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0

  value = Math.abs(value)

  if (isNaN(value) || value === Infinity) {
    m = isNaN(value) ? 1 : 0
    e = eMax
  } else {
    e = Math.floor(Math.log(value) / Math.LN2)
    if (value * (c = Math.pow(2, -e)) < 1) {
      e--
      c *= 2
    }
    if (e + eBias >= 1) {
      value += rt / c
    } else {
      value += rt * Math.pow(2, 1 - eBias)
    }
    if (value * c >= 2) {
      e++
      c /= 2
    }

    if (e + eBias >= eMax) {
      m = 0
      e = eMax
    } else if (e + eBias >= 1) {
      m = ((value * c) - 1) * Math.pow(2, mLen)
      e = e + eBias
    } else {
      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
      e = 0
    }
  }

  for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}

  e = (e << mLen) | m
  eLen += mLen
  for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}

  buffer[offset + i - d] |= s * 128
}

},{}],399:[function(_dereq_,module,exports){
"use strict"

//High level idea:
// 1. Use Clarkson's incremental construction to find convex hull
// 2. Point location in triangulation by jump and walk

module.exports = incrementalConvexHull

var orient = _dereq_("robust-orientation")
var compareCell = _dereq_("simplicial-complex").compareCells

function compareInt(a, b) {
  return a - b
}

function Simplex(vertices, adjacent, boundary) {
  this.vertices = vertices
  this.adjacent = adjacent
  this.boundary = boundary
  this.lastVisited = -1
}

Simplex.prototype.flip = function() {
  var t = this.vertices[0]
  this.vertices[0] = this.vertices[1]
  this.vertices[1] = t
  var u = this.adjacent[0]
  this.adjacent[0] = this.adjacent[1]
  this.adjacent[1] = u
}

function GlueFacet(vertices, cell, index) {
  this.vertices = vertices
  this.cell = cell
  this.index = index
}

function compareGlue(a, b) {
  return compareCell(a.vertices, b.vertices)
}

function bakeOrient(d) {
  var code = ["function orient(){var tuple=this.tuple;return test("]
  for(var i=0; i<=d; ++i) {
    if(i > 0) {
      code.push(",")
    }
    code.push("tuple[", i, "]")
  }
  code.push(")}return orient")
  var proc = new Function("test", code.join(""))
  var test = orient[d+1]
  if(!test) {
    test = orient
  }
  return proc(test)
}

var BAKED = []

function Triangulation(dimension, vertices, simplices) {
  this.dimension = dimension
  this.vertices = vertices
  this.simplices = simplices
  this.interior = simplices.filter(function(c) {
    return !c.boundary
  })

  this.tuple = new Array(dimension+1)
  for(var i=0; i<=dimension; ++i) {
    this.tuple[i] = this.vertices[i]
  }

  var o = BAKED[dimension]
  if(!o) {
    o = BAKED[dimension] = bakeOrient(dimension)
  }
  this.orient = o
}

var proto = Triangulation.prototype

//Degenerate situation where we are on boundary, but coplanar to face
proto.handleBoundaryDegeneracy = function(cell, point) {
  var d = this.dimension
  var n = this.vertices.length - 1
  var tuple = this.tuple
  var verts = this.vertices

  //Dumb solution: Just do dfs from boundary cell until we find any peak, or terminate
  var toVisit = [ cell ]
  cell.lastVisited = -n
  while(toVisit.length > 0) {
    cell = toVisit.pop()
    var cellVerts = cell.vertices
    var cellAdj = cell.adjacent
    for(var i=0; i<=d; ++i) {
      var neighbor = cellAdj[i]
      if(!neighbor.boundary || neighbor.lastVisited <= -n) {
        continue
      }
      var nv = neighbor.vertices
      for(var j=0; j<=d; ++j) {
        var vv = nv[j]
        if(vv < 0) {
          tuple[j] = point
        } else {
          tuple[j] = verts[vv]
        }
      }
      var o = this.orient()
      if(o > 0) {
        return neighbor
      }
      neighbor.lastVisited = -n
      if(o === 0) {
        toVisit.push(neighbor)
      }
    }
  }
  return null
}

proto.walk = function(point, random) {
  //Alias local properties
  var n = this.vertices.length - 1
  var d = this.dimension
  var verts = this.vertices
  var tuple = this.tuple

  //Compute initial jump cell
  var initIndex = random ? (this.interior.length * Math.random())|0 : (this.interior.length-1)
  var cell = this.interior[ initIndex ]

  //Start walking
outerLoop:
  while(!cell.boundary) {
    var cellVerts = cell.vertices
    var cellAdj = cell.adjacent

    for(var i=0; i<=d; ++i) {
      tuple[i] = verts[cellVerts[i]]
    }
    cell.lastVisited = n

    //Find farthest adjacent cell
    for(var i=0; i<=d; ++i) {
      var neighbor = cellAdj[i]
      if(neighbor.lastVisited >= n) {
        continue
      }
      var prev = tuple[i]
      tuple[i] = point
      var o = this.orient()
      tuple[i] = prev
      if(o < 0) {
        cell = neighbor
        continue outerLoop
      } else {
        if(!neighbor.boundary) {
          neighbor.lastVisited = n
        } else {
          neighbor.lastVisited = -n
        }
      }
    }
    return
  }

  return cell
}

proto.addPeaks = function(point, cell) {
  var n = this.vertices.length - 1
  var d = this.dimension
  var verts = this.vertices
  var tuple = this.tuple
  var interior = this.interior
  var simplices = this.simplices

  //Walking finished at boundary, time to add peaks
  var tovisit = [ cell ]

  //Stretch initial boundary cell into a peak
  cell.lastVisited = n
  cell.vertices[cell.vertices.indexOf(-1)] = n
  cell.boundary = false
  interior.push(cell)

  //Record a list of all new boundaries created by added peaks so we can glue them together when we are all done
  var glueFacets = []

  //Do a traversal of the boundary walking outward from starting peak
  while(tovisit.length > 0) {
    //Pop off peak and walk over adjacent cells
    var cell = tovisit.pop()
    var cellVerts = cell.vertices
    var cellAdj = cell.adjacent
    var indexOfN = cellVerts.indexOf(n)
    if(indexOfN < 0) {
      continue
    }

    for(var i=0; i<=d; ++i) {
      if(i === indexOfN) {
        continue
      }

      //For each boundary neighbor of the cell
      var neighbor = cellAdj[i]
      if(!neighbor.boundary || neighbor.lastVisited >= n) {
        continue
      }

      var nv = neighbor.vertices

      //Test if neighbor is a peak
      if(neighbor.lastVisited !== -n) {      
        //Compute orientation of p relative to each boundary peak
        var indexOfNeg1 = 0
        for(var j=0; j<=d; ++j) {
          if(nv[j] < 0) {
            indexOfNeg1 = j
            tuple[j] = point
          } else {
            tuple[j] = verts[nv[j]]
          }
        }
        var o = this.orient()

        //Test if neighbor cell is also a peak
        if(o > 0) {
          nv[indexOfNeg1] = n
          neighbor.boundary = false
          interior.push(neighbor)
          tovisit.push(neighbor)
          neighbor.lastVisited = n
          continue
        } else {
          neighbor.lastVisited = -n
        }
      }

      var na = neighbor.adjacent

      //Otherwise, replace neighbor with new face
      var vverts = cellVerts.slice()
      var vadj = cellAdj.slice()
      var ncell = new Simplex(vverts, vadj, true)
      simplices.push(ncell)

      //Connect to neighbor
      var opposite = na.indexOf(cell)
      if(opposite < 0) {
        continue
      }
      na[opposite] = ncell
      vadj[indexOfN] = neighbor

      //Connect to cell
      vverts[i] = -1
      vadj[i] = cell
      cellAdj[i] = ncell

      //Flip facet
      ncell.flip()

      //Add to glue list
      for(var j=0; j<=d; ++j) {
        var uu = vverts[j]
        if(uu < 0 || uu === n) {
          continue
        }
        var nface = new Array(d-1)
        var nptr = 0
        for(var k=0; k<=d; ++k) {
          var vv = vverts[k]
          if(vv < 0 || k === j) {
            continue
          }
          nface[nptr++] = vv
        }
        glueFacets.push(new GlueFacet(nface, ncell, j))
      }
    }
  }

  //Glue boundary facets together
  glueFacets.sort(compareGlue)

  for(var i=0; i+1<glueFacets.length; i+=2) {
    var a = glueFacets[i]
    var b = glueFacets[i+1]
    var ai = a.index
    var bi = b.index
    if(ai < 0 || bi < 0) {
      continue
    }
    a.cell.adjacent[a.index] = b.cell
    b.cell.adjacent[b.index] = a.cell
  }
}

proto.insert = function(point, random) {
  //Add point
  var verts = this.vertices
  verts.push(point)

  var cell = this.walk(point, random)
  if(!cell) {
    return
  }

  //Alias local properties
  var d = this.dimension
  var tuple = this.tuple

  //Degenerate case: If point is coplanar to cell, then walk until we find a non-degenerate boundary
  for(var i=0; i<=d; ++i) {
    var vv = cell.vertices[i]
    if(vv < 0) {
      tuple[i] = point
    } else {
      tuple[i] = verts[vv]
    }
  }
  var o = this.orient(tuple)
  if(o < 0) {
    return
  } else if(o === 0) {
    cell = this.handleBoundaryDegeneracy(cell, point)
    if(!cell) {
      return
    }
  }

  //Add peaks
  this.addPeaks(point, cell)
}

//Extract all boundary cells
proto.boundary = function() {
  var d = this.dimension
  var boundary = []
  var cells = this.simplices
  var nc = cells.length
  for(var i=0; i<nc; ++i) {
    var c = cells[i]
    if(c.boundary) {
      var bcell = new Array(d)
      var cv = c.vertices
      var ptr = 0
      var parity = 0
      for(var j=0; j<=d; ++j) {
        if(cv[j] >= 0) {
          bcell[ptr++] = cv[j]
        } else {
          parity = j&1
        }
      }
      if(parity === (d&1)) {
        var t = bcell[0]
        bcell[0] = bcell[1]
        bcell[1] = t
      }
      boundary.push(bcell)
    }
  }
  return boundary
}

function incrementalConvexHull(points, randomSearch) {
  var n = points.length
  if(n === 0) {
    throw new Error("Must have at least d+1 points")
  }
  var d = points[0].length
  if(n <= d) {
    throw new Error("Must input at least d+1 points")
  }

  //FIXME: This could be degenerate, but need to select d+1 non-coplanar points to bootstrap process
  var initialSimplex = points.slice(0, d+1)

  //Make sure initial simplex is positively oriented
  var o = orient.apply(void 0, initialSimplex)
  if(o === 0) {
    throw new Error("Input not in general position")
  }
  var initialCoords = new Array(d+1)
  for(var i=0; i<=d; ++i) {
    initialCoords[i] = i
  }
  if(o < 0) {
    initialCoords[0] = 1
    initialCoords[1] = 0
  }

  //Create initial topological index, glue pointers together (kind of messy)
  var initialCell = new Simplex(initialCoords, new Array(d+1), false)
  var boundary = initialCell.adjacent
  var list = new Array(d+2)
  for(var i=0; i<=d; ++i) {
    var verts = initialCoords.slice()
    for(var j=0; j<=d; ++j) {
      if(j === i) {
        verts[j] = -1
      }
    }
    var t = verts[0]
    verts[0] = verts[1]
    verts[1] = t
    var cell = new Simplex(verts, new Array(d+1), true)
    boundary[i] = cell
    list[i] = cell
  }
  list[d+1] = initialCell
  for(var i=0; i<=d; ++i) {
    var verts = boundary[i].vertices
    var adj = boundary[i].adjacent
    for(var j=0; j<=d; ++j) {
      var v = verts[j]
      if(v < 0) {
        adj[j] = initialCell
        continue
      }
      for(var k=0; k<=d; ++k) {
        if(boundary[k].vertices.indexOf(v) < 0) {
          adj[j] = boundary[k]
        }
      }
    }
  }

  //Initialize triangles
  var triangles = new Triangulation(d, initialSimplex, list)

  //Insert remaining points
  var useRandom = !!randomSearch
  for(var i=d+1; i<n; ++i) {
    triangles.insert(points[i], useRandom)
  }
  
  //Extract boundary cells
  return triangles.boundary()
}
},{"robust-orientation":488,"simplicial-complex":498}],400:[function(_dereq_,module,exports){
"use strict"

var bounds = _dereq_("binary-search-bounds")

var NOT_FOUND = 0
var SUCCESS = 1
var EMPTY = 2

module.exports = createWrapper

function IntervalTreeNode(mid, left, right, leftPoints, rightPoints) {
  this.mid = mid
  this.left = left
  this.right = right
  this.leftPoints = leftPoints
  this.rightPoints = rightPoints
  this.count = (left ? left.count : 0) + (right ? right.count : 0) + leftPoints.length
}

var proto = IntervalTreeNode.prototype

function copy(a, b) {
  a.mid = b.mid
  a.left = b.left
  a.right = b.right
  a.leftPoints = b.leftPoints
  a.rightPoints = b.rightPoints
  a.count = b.count
}

function rebuild(node, intervals) {
  var ntree = createIntervalTree(intervals)
  node.mid = ntree.mid
  node.left = ntree.left
  node.right = ntree.right
  node.leftPoints = ntree.leftPoints
  node.rightPoints = ntree.rightPoints
  node.count = ntree.count
}

function rebuildWithInterval(node, interval) {
  var intervals = node.intervals([])
  intervals.push(interval)
  rebuild(node, intervals)    
}

function rebuildWithoutInterval(node, interval) {
  var intervals = node.intervals([])
  var idx = intervals.indexOf(interval)
  if(idx < 0) {
    return NOT_FOUND
  }
  intervals.splice(idx, 1)
  rebuild(node, intervals)
  return SUCCESS
}

proto.intervals = function(result) {
  result.push.apply(result, this.leftPoints)
  if(this.left) {
    this.left.intervals(result)
  }
  if(this.right) {
    this.right.intervals(result)
  }
  return result
}

proto.insert = function(interval) {
  var weight = this.count - this.leftPoints.length
  this.count += 1
  if(interval[1] < this.mid) {
    if(this.left) {
      if(4*(this.left.count+1) > 3*(weight+1)) {
        rebuildWithInterval(this, interval)
      } else {
        this.left.insert(interval)
      }
    } else {
      this.left = createIntervalTree([interval])
    }
  } else if(interval[0] > this.mid) {
    if(this.right) {
      if(4*(this.right.count+1) > 3*(weight+1)) {
        rebuildWithInterval(this, interval)
      } else {
        this.right.insert(interval)
      }
    } else {
      this.right = createIntervalTree([interval])
    }
  } else {
    var l = bounds.ge(this.leftPoints, interval, compareBegin)
    var r = bounds.ge(this.rightPoints, interval, compareEnd)
    this.leftPoints.splice(l, 0, interval)
    this.rightPoints.splice(r, 0, interval)
  }
}

proto.remove = function(interval) {
  var weight = this.count - this.leftPoints
  if(interval[1] < this.mid) {
    if(!this.left) {
      return NOT_FOUND
    }
    var rw = this.right ? this.right.count : 0
    if(4 * rw > 3 * (weight-1)) {
      return rebuildWithoutInterval(this, interval)
    }
    var r = this.left.remove(interval)
    if(r === EMPTY) {
      this.left = null
      this.count -= 1
      return SUCCESS
    } else if(r === SUCCESS) {
      this.count -= 1
    }
    return r
  } else if(interval[0] > this.mid) {
    if(!this.right) {
      return NOT_FOUND
    }
    var lw = this.left ? this.left.count : 0
    if(4 * lw > 3 * (weight-1)) {
      return rebuildWithoutInterval(this, interval)
    }
    var r = this.right.remove(interval)
    if(r === EMPTY) {
      this.right = null
      this.count -= 1
      return SUCCESS
    } else if(r === SUCCESS) {
      this.count -= 1
    }
    return r
  } else {
    if(this.count === 1) {
      if(this.leftPoints[0] === interval) {
        return EMPTY
      } else {
        return NOT_FOUND
      }
    }
    if(this.leftPoints.length === 1 && this.leftPoints[0] === interval) {
      if(this.left && this.right) {
        var p = this
        var n = this.left
        while(n.right) {
          p = n
          n = n.right
        }
        if(p === this) {
          n.right = this.right
        } else {
          var l = this.left
          var r = this.right
          p.count -= n.count
          p.right = n.left
          n.left = l
          n.right = r
        }
        copy(this, n)
        this.count = (this.left?this.left.count:0) + (this.right?this.right.count:0) + this.leftPoints.length
      } else if(this.left) {
        copy(this, this.left)
      } else {
        copy(this, this.right)
      }
      return SUCCESS
    }
    for(var l = bounds.ge(this.leftPoints, interval, compareBegin); l<this.leftPoints.length; ++l) {
      if(this.leftPoints[l][0] !== interval[0]) {
        break
      }
      if(this.leftPoints[l] === interval) {
        this.count -= 1
        this.leftPoints.splice(l, 1)
        for(var r = bounds.ge(this.rightPoints, interval, compareEnd); r<this.rightPoints.length; ++r) {
          if(this.rightPoints[r][1] !== interval[1]) {
            break
          } else if(this.rightPoints[r] === interval) {
            this.rightPoints.splice(r, 1)
            return SUCCESS
          }
        }
      }
    }
    return NOT_FOUND
  }
}

function reportLeftRange(arr, hi, cb) {
  for(var i=0; i<arr.length && arr[i][0] <= hi; ++i) {
    var r = cb(arr[i])
    if(r) { return r }
  }
}

function reportRightRange(arr, lo, cb) {
  for(var i=arr.length-1; i>=0 && arr[i][1] >= lo; --i) {
    var r = cb(arr[i])
    if(r) { return r }
  }
}

function reportRange(arr, cb) {
  for(var i=0; i<arr.length; ++i) {
    var r = cb(arr[i])
    if(r) { return r }
  }
}

proto.queryPoint = function(x, cb) {
  if(x < this.mid) {
    if(this.left) {
      var r = this.left.queryPoint(x, cb)
      if(r) { return r }
    }
    return reportLeftRange(this.leftPoints, x, cb)
  } else if(x > this.mid) {
    if(this.right) {
      var r = this.right.queryPoint(x, cb)
      if(r) { return r }
    }
    return reportRightRange(this.rightPoints, x, cb)
  } else {
    return reportRange(this.leftPoints, cb)
  }
}

proto.queryInterval = function(lo, hi, cb) {
  if(lo < this.mid && this.left) {
    var r = this.left.queryInterval(lo, hi, cb)
    if(r) { return r }
  }
  if(hi > this.mid && this.right) {
    var r = this.right.queryInterval(lo, hi, cb)
    if(r) { return r }
  }
  if(hi < this.mid) {
    return reportLeftRange(this.leftPoints, hi, cb)
  } else if(lo > this.mid) {
    return reportRightRange(this.rightPoints, lo, cb)
  } else {
    return reportRange(this.leftPoints, cb)
  }
}

function compareNumbers(a, b) {
  return a - b
}

function compareBegin(a, b) {
  var d = a[0] - b[0]
  if(d) { return d }
  return a[1] - b[1]
}

function compareEnd(a, b) {
  var d = a[1] - b[1]
  if(d) { return d }
  return a[0] - b[0]
}

function createIntervalTree(intervals) {
  if(intervals.length === 0) {
    return null
  }
  var pts = []
  for(var i=0; i<intervals.length; ++i) {
    pts.push(intervals[i][0], intervals[i][1])
  }
  pts.sort(compareNumbers)

  var mid = pts[pts.length>>1]

  var leftIntervals = []
  var rightIntervals = []
  var centerIntervals = []
  for(var i=0; i<intervals.length; ++i) {
    var s = intervals[i]
    if(s[1] < mid) {
      leftIntervals.push(s)
    } else if(mid < s[0]) {
      rightIntervals.push(s)
    } else {
      centerIntervals.push(s)
    }
  }

  //Split center intervals
  var leftPoints = centerIntervals
  var rightPoints = centerIntervals.slice()
  leftPoints.sort(compareBegin)
  rightPoints.sort(compareEnd)

  return new IntervalTreeNode(mid, 
    createIntervalTree(leftIntervals),
    createIntervalTree(rightIntervals),
    leftPoints,
    rightPoints)
}

//User friendly wrapper that makes it possible to support empty trees
function IntervalTree(root) {
  this.root = root
}

var tproto = IntervalTree.prototype

tproto.insert = function(interval) {
  if(this.root) {
    this.root.insert(interval)
  } else {
    this.root = new IntervalTreeNode(interval[0], null, null, [interval], [interval])
  }
}

tproto.remove = function(interval) {
  if(this.root) {
    var r = this.root.remove(interval)
    if(r === EMPTY) {
      this.root = null
    }
    return r !== NOT_FOUND
  }
  return false
}

tproto.queryPoint = function(p, cb) {
  if(this.root) {
    return this.root.queryPoint(p, cb)
  }
}

tproto.queryInterval = function(lo, hi, cb) {
  if(lo <= hi && this.root) {
    return this.root.queryInterval(lo, hi, cb)
  }
}

Object.defineProperty(tproto, "count", {
  get: function() {
    if(this.root) {
      return this.root.count
    }
    return 0
  }
})

Object.defineProperty(tproto, "intervals", {
  get: function() {
    if(this.root) {
      return this.root.intervals([])
    }
    return []
  }
})

function createWrapper(intervals) {
  if(!intervals || intervals.length === 0) {
    return new IntervalTree(null)
  }
  return new IntervalTree(createIntervalTree(intervals))
}

},{"binary-search-bounds":80}],401:[function(_dereq_,module,exports){
"use strict"

function invertPermutation(pi, result) {
  result = result || new Array(pi.length)
  for(var i=0; i<pi.length; ++i) {
    result[pi[i]] = i
  }
  return result
}

module.exports = invertPermutation
},{}],402:[function(_dereq_,module,exports){
"use strict"

function iota(n) {
  var result = new Array(n)
  for(var i=0; i<n; ++i) {
    result[i] = i
  }
  return result
}

module.exports = iota
},{}],403:[function(_dereq_,module,exports){
module.exports = true;
},{}],404:[function(_dereq_,module,exports){
/*!
 * Determine if an object is a Buffer
 *
 * @author   Feross Aboukhadijeh <https://feross.org>
 * @license  MIT
 */

// The _isBuffer check is for Safari 5-7 support, because it's missing
// Object.prototype.constructor. Remove this eventually
module.exports = function (obj) {
  return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
}

function isBuffer (obj) {
  return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
}

// For Node v0.10 support. Remove this eventually.
function isSlowBuffer (obj) {
  return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
}

},{}],405:[function(_dereq_,module,exports){
'use strict';
module.exports = typeof navigator !== 'undefined' &&
	(/MSIE/.test(navigator.userAgent) || /Trident\//.test(navigator.appVersion));

},{}],406:[function(_dereq_,module,exports){
'use strict'

module.exports = isMobile;
module.exports.isMobile = isMobile;

var mobileRE = /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i;

var tabletRE = /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino|android|ipad|playbook|silk/i;

function isMobile (opts) {
  if (!opts) opts = {}
  var ua = opts.ua
  if (!ua && typeof navigator !== 'undefined') ua = navigator.userAgent;
  if (ua && ua.headers && typeof ua.headers['user-agent'] === 'string') {
    ua = ua.headers['user-agent'];
  }
  if (typeof ua !== 'string') return false;

  return opts.tablet
    ? tabletRE.test(ua)
    : mobileRE.test(ua);
}

},{}],407:[function(_dereq_,module,exports){
'use strict';
module.exports = function (x) {
	var type = typeof x;
	return x !== null && (type === 'object' || type === 'function');
};

},{}],408:[function(_dereq_,module,exports){
'use strict';
var toString = Object.prototype.toString;

module.exports = function (x) {
	var prototype;
	return toString.call(x) === '[object Object]' && (prototype = Object.getPrototypeOf(x), prototype === null || prototype === Object.getPrototypeOf({}));
};

},{}],409:[function(_dereq_,module,exports){
'use strict';

/**
 * Is this string all whitespace?
 * This solution kind of makes my brain hurt, but it's significantly faster
 * than !str.trim() or any other solution I could find.
 *
 * whitespace codes from: http://en.wikipedia.org/wiki/Whitespace_character
 * and verified with:
 *
 *  for(var i = 0; i < 65536; i++) {
 *      var s = String.fromCharCode(i);
 *      if(+s===0 && !s.trim()) console.log(i, s);
 *  }
 *
 * which counts a couple of these as *not* whitespace, but finds nothing else
 * that *is* whitespace. Note that charCodeAt stops at 16 bits, but it appears
 * that there are no whitespace characters above this, and code points above
 * this do not map onto white space characters.
 */

module.exports = function(str){
    var l = str.length,
        a;
    for(var i = 0; i < l; i++) {
        a = str.charCodeAt(i);
        if((a < 9 || a > 13) && (a !== 32) && (a !== 133) && (a !== 160) &&
            (a !== 5760) && (a !== 6158) && (a < 8192 || a > 8205) &&
            (a !== 8232) && (a !== 8233) && (a !== 8239) && (a !== 8287) &&
            (a !== 8288) && (a !== 12288) && (a !== 65279)) {
                return false;
        }
    }
    return true;
}

},{}],410:[function(_dereq_,module,exports){
'use strict'

module.exports = function isPath(str) {
	if (typeof str !== 'string') return false

	str = str.trim()

	// https://www.w3.org/TR/SVG/paths.html#PathDataBNF
	if (/^[mzlhvcsqta]\s*[-+.0-9][^mlhvzcsqta]+/i.test(str) && /[\dz]$/i.test(str) && str.length > 4) return true

	return false
}

},{}],411:[function(_dereq_,module,exports){
function lerp(v0, v1, t) {
    return v0*(1-t)+v1*t
}
module.exports = lerp
},{}],412:[function(_dereq_,module,exports){
(function (global){
(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
	typeof define === 'function' && define.amd ? define(factory) :
	(global.mapboxgl = factory());
}(this, (function () { 'use strict';

/* eslint-disable */

var shared, worker, mapboxgl;
// define gets called three times: one for each chunk. we rely on the order
// they're imported to know which is which
function define(_, chunk) {
if (!shared) {
    shared = chunk;
} else if (!worker) {
    worker = chunk;
} else {
    var workerBundleString = 'var sharedChunk = {}; (' + shared + ')(sharedChunk); (' + worker + ')(sharedChunk);'

    var sharedChunk = {};
    shared(sharedChunk);
    mapboxgl = chunk(sharedChunk);
    mapboxgl.workerUrl = window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' }));
}
}


define(["exports"],function(t){"use strict";var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function r(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function n(t,e){return t(e={exports:{}},e.exports),e.exports}var i=o;function o(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=n,this.p2x=r,this.p2y=n;}o.prototype.sampleCurveX=function(t){return((this.ax*t+this.bx)*t+this.cx)*t},o.prototype.sampleCurveY=function(t){return((this.ay*t+this.by)*t+this.cy)*t},o.prototype.sampleCurveDerivativeX=function(t){return(3*this.ax*t+2*this.bx)*t+this.cx},o.prototype.solveCurveX=function(t,e){var r,n,i,o,a;for(void 0===e&&(e=1e-6),i=t,a=0;a<8;a++){if(o=this.sampleCurveX(i)-t,Math.abs(o)<e)return i;var s=this.sampleCurveDerivativeX(i);if(Math.abs(s)<1e-6)break;i-=o/s;}if((i=t)<(r=0))return r;if(i>(n=1))return n;for(;r<n;){if(o=this.sampleCurveX(i),Math.abs(o-t)<e)return i;t>o?r=i:n=i,i=.5*(n-r)+r;}return i},o.prototype.solve=function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))};var a=function(t,e,r){this.column=t,this.row=e,this.zoom=r;};a.prototype.clone=function(){return new a(this.column,this.row,this.zoom)},a.prototype.zoomTo=function(t){return this.clone()._zoomTo(t)},a.prototype.sub=function(t){return this.clone()._sub(t)},a.prototype._zoomTo=function(t){var e=Math.pow(2,t-this.zoom);return this.column*=e,this.row*=e,this.zoom=t,this},a.prototype._sub=function(t){return t=t.zoomTo(this.zoom),this.column-=t.column,this.row-=t.row,this};var s=u;function u(t,e){this.x=t,this.y=e;}function l(t,e,r,n){var o=new i(t,e,r,n);return function(t){return o.solve(t)}}u.prototype={clone:function(){return new u(this.x,this.y)},add:function(t){return this.clone()._add(t)},sub:function(t){return this.clone()._sub(t)},multByPoint:function(t){return this.clone()._multByPoint(t)},divByPoint:function(t){return this.clone()._divByPoint(t)},mult:function(t){return this.clone()._mult(t)},div:function(t){return this.clone()._div(t)},rotate:function(t){return this.clone()._rotate(t)},rotateAround:function(t,e){return this.clone()._rotateAround(t,e)},matMult:function(t){return this.clone()._matMult(t)},unit:function(){return this.clone()._unit()},perp:function(){return this.clone()._perp()},round:function(){return this.clone()._round()},mag:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals:function(t){return this.x===t.x&&this.y===t.y},dist:function(t){return Math.sqrt(this.distSqr(t))},distSqr:function(t){var e=t.x-this.x,r=t.y-this.y;return e*e+r*r},angle:function(){return Math.atan2(this.y,this.x)},angleTo:function(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith:function(t){return this.angleWithSep(t.x,t.y)},angleWithSep:function(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult:function(t){var e=t[0]*this.x+t[1]*this.y,r=t[2]*this.x+t[3]*this.y;return this.x=e,this.y=r,this},_add:function(t){return this.x+=t.x,this.y+=t.y,this},_sub:function(t){return this.x-=t.x,this.y-=t.y,this},_mult:function(t){return this.x*=t,this.y*=t,this},_div:function(t){return this.x/=t,this.y/=t,this},_multByPoint:function(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint:function(t){return this.x/=t.x,this.y/=t.y,this},_unit:function(){return this._div(this.mag()),this},_perp:function(){var t=this.y;return this.y=this.x,this.x=-t,this},_rotate:function(t){var e=Math.cos(t),r=Math.sin(t),n=e*this.x-r*this.y,i=r*this.x+e*this.y;return this.x=n,this.y=i,this},_rotateAround:function(t,e){var r=Math.cos(t),n=Math.sin(t),i=e.x+r*(this.x-e.x)-n*(this.y-e.y),o=e.y+n*(this.x-e.x)+r*(this.y-e.y);return this.x=i,this.y=o,this},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}},u.convert=function(t){return t instanceof u?t:Array.isArray(t)?new u(t[0],t[1]):t};var p=l(.25,.1,.25,1);function c(t,e,r){return Math.min(r,Math.max(e,t))}function h(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];for(var n=0,i=e;n<i.length;n+=1){var o=i[n];for(var a in o)t[a]=o[a];}return t}var f=1;function y(t,e){t.forEach(function(t){e[t]&&(e[t]=e[t].bind(e));});}function d(t,e){return-1!==t.indexOf(e,t.length-e.length)}function v(t,e,r){var n={};for(var i in t)n[i]=e.call(r||this,t[i],i,t);return n}function m(t,e,r){var n={};for(var i in t)e.call(r||this,t[i],i,t)&&(n[i]=t[i]);return n}function g(t){return Array.isArray(t)?t.map(g):"object"==typeof t&&t?v(t,g):t}var x={};function b(t){x[t]||("undefined"!=typeof console&&console.warn(t),x[t]=!0);}function w(t,e,r){return(r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)}function _(t){for(var e=0,r=0,n=t.length,i=n-1,o=void 0,a=void 0;r<n;i=r++)o=t[r],e+=((a=t[i]).x-o.x)*(o.y+a.y);return e}var A={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Image:"Image"};"function"==typeof Object.freeze&&Object.freeze(A);var k=function(t){function e(e,r,n){t.call(this,e),this.status=r,this.url=n,this.name=this.constructor.name,this.message=e;}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.toString=function(){return this.name+": "+this.message+" ("+this.status+"): "+this.url},e}(Error);function z(t){var e=new self.XMLHttpRequest;for(var r in e.open("GET",t.url,!0),t.headers)e.setRequestHeader(r,t.headers[r]);return e.withCredentials="include"===t.credentials,e}var S=function(t,e){var r=z(t);return r.responseType="arraybuffer",r.onerror=function(){e(new Error(r.statusText));},r.onload=function(){var n=r.response;if(0===n.byteLength&&200===r.status)return e(new Error("http status 200 returned without content."));r.status>=200&&r.status<300&&r.response?e(null,{data:n,cacheControl:r.getResponseHeader("Cache-Control"),expires:r.getResponseHeader("Expires")}):e(new k(r.statusText,r.status,t.url));},r.send(),r};function M(t,e,r){r[t]=r[t]||[],r[t].push(e);}function V(t,e,r){if(r&&r[t]){var n=r[t].indexOf(e);-1!==n&&r[t].splice(n,1);}}var B=function(t,e){void 0===e&&(e={}),h(this,e),this.type=t;},C=function(t){function e(e,r){void 0===r&&(r={}),t.call(this,"error",h({error:e},r));}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(B),I=function(){};I.prototype.on=function(t,e){return this._listeners=this._listeners||{},M(t,e,this._listeners),this},I.prototype.off=function(t,e){return V(t,e,this._listeners),V(t,e,this._oneTimeListeners),this},I.prototype.once=function(t,e){return this._oneTimeListeners=this._oneTimeListeners||{},M(t,e,this._oneTimeListeners),this},I.prototype.fire=function(t){"string"==typeof t&&(t=new B(t,arguments[1]||{}));var e=t.type;if(this.listens(e)){t.target=this;for(var r=0,n=this._listeners&&this._listeners[e]?this._listeners[e].slice():[];r<n.length;r+=1){n[r].call(this,t);}for(var i=0,o=this._oneTimeListeners&&this._oneTimeListeners[e]?this._oneTimeListeners[e].slice():[];i<o.length;i+=1){var a=o[i];V(e,a,this._oneTimeListeners),a.call(this,t);}var s=this._eventedParent;s&&(h(t,"function"==typeof this._eventedParentData?this._eventedParentData():this._eventedParentData),s.fire(t));}else d(e,"error")?console.error(t&&t.error||t||"Empty error event"):d(e,"warning")&&console.warn(t&&t.warning||t||"Empty warning event");return this},I.prototype.listens=function(t){return this._listeners&&this._listeners[t]&&this._listeners[t].length>0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)},I.prototype.setEventedParent=function(t,e){return this._eventedParent=t,this._eventedParentData=e,this};var E={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},light:{type:"light"},sources:{required:!0,type:"sources"},sprite:{type:"string"},glyphs:{type:"string"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:!0,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.0511,180,85.0511]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},"*":{type:"*"}},source_raster:{type:{required:!0,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.0511,180,85.0511]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},"*":{type:"*"}},source_raster_dem:{type:{required:!0,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.0511,180,85.0511]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{}},default:"mapbox"},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:{geojson:{}}},data:{type:"*"},maxzoom:{type:"number",default:18},buffer:{type:"number",default:128,maximum:512,minimum:0},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},lineMetrics:{type:"boolean",default:!1}},source_video:{type:{required:!0,type:"enum",values:{video:{}}},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:{image:{}}},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},background:{}},required:!0},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},layout_fill:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},layout_circle:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},layout_line:{"line-cap":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{butt:{},round:{},square:{}},default:"butt"},"line-join":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:{bevel:{},round:{},miter:{}},default:"miter"},"line-miter-limit":{type:"number",default:2,function:"interpolated","zoom-function":!0,requires:[{"line-join":"miter"}]},"line-round-limit":{type:"number",default:1.05,function:"interpolated","zoom-function":!0,requires:[{"line-join":"round"}]},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},layout_symbol:{"symbol-placement":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{point:{},line:{}},default:"point"},"symbol-spacing":{type:"number",default:250,minimum:1,function:"interpolated","zoom-function":!0,units:"pixels",requires:[{"symbol-placement":"line"}]},"symbol-avoid-edges":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1},"icon-allow-overlap":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1,requires:["icon-image"]},"icon-ignore-placement":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1,requires:["icon-image"]},"icon-optional":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1,requires:["icon-image","text-field"]},"icon-rotation-alignment":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"]},"icon-size":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,units:"factor of the original icon size",requires:["icon-image"]},"icon-text-fit":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"]},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",function:"interpolated","zoom-function":!0,requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}]},"icon-image":{type:"string",function:"piecewise-constant","zoom-function":!0,"property-function":!0,tokens:!0},"icon-rotate":{type:"number",default:0,period:360,function:"interpolated","zoom-function":!0,"property-function":!0,units:"degrees",requires:["icon-image"]},"icon-padding":{type:"number",default:2,minimum:0,function:"interpolated","zoom-function":!0,units:"pixels",requires:["icon-image"]},"icon-keep-upright":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":"line"}]},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,"property-function":!0,requires:["icon-image"]},"icon-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"]},"icon-pitch-alignment":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"]},"text-pitch-alignment":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"]},"text-rotation-alignment":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"]},"text-field":{type:"string",function:"piecewise-constant","zoom-function":!0,"property-function":!0,default:"",tokens:!0},"text-font":{type:"array",value:"string",function:"piecewise-constant","zoom-function":!0,"property-function":!0,default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"]},"text-size":{type:"number",default:16,minimum:0,units:"pixels",function:"interpolated","zoom-function":!0,"property-function":!0,requires:["text-field"]},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",function:"interpolated","zoom-function":!0,"property-function":!0,requires:["text-field"]},"text-line-height":{type:"number",default:1.2,units:"ems",function:"interpolated","zoom-function":!0,requires:["text-field"]},"text-letter-spacing":{type:"number",default:0,units:"ems",function:"interpolated","zoom-function":!0,"property-function":!0,requires:["text-field"]},"text-justify":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:{left:{},center:{},right:{}},default:"center",requires:["text-field"]},"text-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field"]},"text-max-angle":{type:"number",default:45,units:"degrees",function:"interpolated","zoom-function":!0,requires:["text-field",{"symbol-placement":"line"}]},"text-rotate":{type:"number",default:0,period:360,units:"degrees",function:"interpolated","zoom-function":!0,"property-function":!0,requires:["text-field"]},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",function:"interpolated","zoom-function":!0,requires:["text-field"]},"text-keep-upright":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":"line"}]},"text-transform":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"]},"text-offset":{type:"array",value:"number",units:"ems",function:"interpolated","zoom-function":!0,"property-function":!0,length:2,default:[0,0],requires:["text-field"]},"text-allow-overlap":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1,requires:["text-field"]},"text-ignore-placement":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1,requires:["text-field"]},"text-optional":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1,requires:["text-field","icon-image"]},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},filter:{type:"array",value:"*"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function_stop:{type:"array",minimum:0,maximum:22,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},expression_name:{type:"enum",values:{let:{group:"Variable binding"},var:{group:"Variable binding"},literal:{group:"Types"},array:{group:"Types"},at:{group:"Lookup"},case:{group:"Decision"},match:{group:"Decision"},coalesce:{group:"Decision"},step:{group:"Ramps, scales, curves"},interpolate:{group:"Ramps, scales, curves"},ln2:{group:"Math"},pi:{group:"Math"},e:{group:"Math"},typeof:{group:"Types"},string:{group:"Types"},number:{group:"Types"},boolean:{group:"Types"},object:{group:"Types"},collator:{group:"Types"},"to-string":{group:"Types"},"to-number":{group:"Types"},"to-boolean":{group:"Types"},"to-rgba":{group:"Color"},"to-color":{group:"Types"},rgb:{group:"Color"},rgba:{group:"Color"},get:{group:"Lookup"},has:{group:"Lookup"},length:{group:"Lookup"},properties:{group:"Feature data"},"geometry-type":{group:"Feature data"},id:{group:"Feature data"},zoom:{group:"Zoom"},"heatmap-density":{group:"Heatmap"},"line-progress":{group:"Heatmap"},"+":{group:"Math"},"*":{group:"Math"},"-":{group:"Math"},"/":{group:"Math"},"%":{group:"Math"},"^":{group:"Math"},sqrt:{group:"Math"},log10:{group:"Math"},ln:{group:"Math"},log2:{group:"Math"},sin:{group:"Math"},cos:{group:"Math"},tan:{group:"Math"},asin:{group:"Math"},acos:{group:"Math"},atan:{group:"Math"},min:{group:"Math"},max:{group:"Math"},round:{group:"Math"},abs:{group:"Math"},ceil:{group:"Math"},floor:{group:"Math"},"==":{group:"Decision"},"!=":{group:"Decision"},">":{group:"Decision"},"<":{group:"Decision"},">=":{group:"Decision"},"<=":{group:"Decision"},all:{group:"Decision"},any:{group:"Decision"},"!":{group:"Decision"},"is-supported-script":{group:"String"},upcase:{group:"String"},downcase:{group:"String"},concat:{group:"String"},"resolved-locale":{group:"String"}}},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},transition:!1,"zoom-function":!0,"property-function":!1,function:"piecewise-constant"},position:{type:"array",default:[1.15,210,30],length:3,value:"number",transition:!0,function:"interpolated","zoom-function":!0,"property-function":!1},color:{type:"color",default:"#ffffff",function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0},intensity:{type:"number",default:.5,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!0},"fill-opacity":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:1,minimum:0,maximum:1,transition:!0},"fill-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"fill-pattern"}]},"fill-outline-color":{type:"color",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}]},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"fill-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["fill-translate"]},"fill-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0}},paint_line:{"line-opacity":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:1,minimum:0,maximum:1,transition:!0},"line-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"line-pattern"}]},"line-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"line-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["line-translate"]},"line-width":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-gap-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-offset":{type:"number",default:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-dasharray":{type:"array",value:"number",function:"piecewise-constant","zoom-function":!0,minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}]},"line-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0},"line-gradient":{type:"color",function:"interpolated","zoom-function":!1,"property-function":!1,transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}]}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"circle-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-blur":{type:"number",default:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"circle-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["circle-translate"]},"circle-pitch-scale":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map"},"circle-pitch-alignment":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"viewport"},"circle-stroke-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"circle-stroke-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"heatmap-weight":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!1},"heatmap-intensity":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],function:"interpolated","zoom-function":!1,"property-function":!1,transition:!1},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-halo-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-halo-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"]},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-halo-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-halo-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"]}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-hue-rotate":{type:"number",default:0,period:360,function:"interpolated","zoom-function":!0,transition:!0,units:"degrees"},"raster-brightness-min":{type:"number",function:"interpolated","zoom-function":!0,default:0,minimum:0,maximum:1,transition:!0},"raster-brightness-max":{type:"number",function:"interpolated","zoom-function":!0,default:1,minimum:0,maximum:1,transition:!0},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-fade-duration":{type:"number",default:300,minimum:0,function:"interpolated","zoom-function":!0,transition:!1,units:"milliseconds"}},paint_hillshade:{"hillshade-illumination-direction":{type:"number",default:335,minimum:0,maximum:359,function:"interpolated","zoom-function":!0,transition:!1},"hillshade-illumination-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"viewport"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"hillshade-shadow-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,transition:!0},"hillshade-highlight-color":{type:"color",default:"#FFFFFF",function:"interpolated","zoom-function":!0,transition:!0},"hillshade-accent-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,transition:!0}},paint_background:{"background-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,transition:!0,requires:[{"!":"background-pattern"}]},"background-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,transition:!0}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!1,default:1,minimum:0,maximum:1,transition:!0},"fill-extrusion-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"fill-extrusion-pattern"}]},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"fill-extrusion-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"]},"fill-extrusion-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0},"fill-extrusion-height":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:0,minimum:0,units:"meters",transition:!0},"fill-extrusion-base":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"]}}},F=function(t,e,r,n){this.message=(t?t+": ":"")+r,n&&(this.identifier=n),null!=e&&e.__line__&&(this.line=e.__line__);};function P(t){var e=t.key,r=t.value;return r?[new F(e,r,"constants have been deprecated as of v8")]:[]}function T(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];for(var n=0,i=e;n<i.length;n+=1){var o=i[n];for(var a in o)t[a]=o[a];}return t}function O(t){return t instanceof Number||t instanceof String||t instanceof Boolean?t.valueOf():t}function L(t){return Array.isArray(t)?t.map(L):O(t)}var j=function(t){function e(e,r){t.call(this,r),this.message=r,this.key=e;}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(Error),q=function(t,e){void 0===e&&(e=[]),this.parent=t,this.bindings={};for(var r=0,n=e;r<n.length;r+=1){var i=n[r],o=i[0],a=i[1];this.bindings[o]=a;}};q.prototype.concat=function(t){return new q(this,t)},q.prototype.get=function(t){if(this.bindings[t])return this.bindings[t];if(this.parent)return this.parent.get(t);throw new Error(t+" not found in scope.")},q.prototype.has=function(t){return!!this.bindings[t]||!!this.parent&&this.parent.has(t)};var R={kind:"null"},U={kind:"number"},D={kind:"string"},N={kind:"boolean"},Z={kind:"color"},K={kind:"object"},J={kind:"value"},$={kind:"collator"};function H(t,e){return{kind:"array",itemType:t,N:e}}function X(t){if("array"===t.kind){var e=X(t.itemType);return"number"==typeof t.N?"array<"+e+", "+t.N+">":"value"===t.itemType.kind?"array":"array<"+e+">"}return t.kind}var G=[R,U,D,N,Z,K,H(J)];function Y(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&!Y(t.itemType,e.itemType)&&("number"!=typeof t.N||t.N===e.N))return null}else{if(t.kind===e.kind)return null;if("value"===t.kind)for(var r=0,n=G;r<n.length;r+=1){if(!Y(n[r],e))return null}}return"Expected "+X(t)+" but found "+X(e)+" instead."}var W=n(function(t,e){var r={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],rebeccapurple:[102,51,153,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function n(t){return(t=Math.round(t))<0?0:t>255?255:t}function i(t){return t<0?0:t>1?1:t}function o(t){return"%"===t[t.length-1]?n(parseFloat(t)/100*255):n(parseInt(t))}function a(t){return"%"===t[t.length-1]?i(parseFloat(t)/100):i(parseFloat(t))}function s(t,e,r){return r<0?r+=1:r>1&&(r-=1),6*r<1?t+(e-t)*r*6:2*r<1?e:3*r<2?t+(e-t)*(2/3-r)*6:t}try{e.parseCSSColor=function(t){var e,i=t.replace(/ /g,"").toLowerCase();if(i in r)return r[i].slice();if("#"===i[0])return 4===i.length?(e=parseInt(i.substr(1),16))>=0&&e<=4095?[(3840&e)>>4|(3840&e)>>8,240&e|(240&e)>>4,15&e|(15&e)<<4,1]:null:7===i.length&&(e=parseInt(i.substr(1),16))>=0&&e<=16777215?[(16711680&e)>>16,(65280&e)>>8,255&e,1]:null;var u=i.indexOf("("),l=i.indexOf(")");if(-1!==u&&l+1===i.length){var p=i.substr(0,u),c=i.substr(u+1,l-(u+1)).split(","),h=1;switch(p){case"rgba":if(4!==c.length)return null;h=a(c.pop());case"rgb":return 3!==c.length?null:[o(c[0]),o(c[1]),o(c[2]),h];case"hsla":if(4!==c.length)return null;h=a(c.pop());case"hsl":if(3!==c.length)return null;var f=(parseFloat(c[0])%360+360)%360/360,y=a(c[1]),d=a(c[2]),v=d<=.5?d*(y+1):d+y-d*y,m=2*d-v;return[n(255*s(m,v,f+1/3)),n(255*s(m,v,f)),n(255*s(m,v,f-1/3)),h];default:return null}}return null};}catch(t){}}).parseCSSColor,Q=function(t,e,r,n){void 0===n&&(n=1),this.r=t,this.g=e,this.b=r,this.a=n;};Q.parse=function(t){if(t){if(t instanceof Q)return t;if("string"==typeof t){var e=W(t);if(e)return new Q(e[0]/255*e[3],e[1]/255*e[3],e[2]/255*e[3],e[3])}}},Q.prototype.toString=function(){var t=this.toArray(),e=t[0],r=t[1],n=t[2],i=t[3];return"rgba("+Math.round(e)+","+Math.round(r)+","+Math.round(n)+","+i+")"},Q.prototype.toArray=function(){var t=this.r,e=this.g,r=this.b,n=this.a;return 0===n?[0,0,0,0]:[255*t/n,255*e/n,255*r/n,n]},Q.black=new Q(0,0,0,1),Q.white=new Q(1,1,1,1),Q.transparent=new Q(0,0,0,0);var tt=function(t,e,r){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=r,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"});};tt.prototype.compare=function(t,e){return this.collator.compare(t,e)},tt.prototype.resolvedLocale=function(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale};var et=function(t,e,r){this.type=$,this.locale=r,this.caseSensitive=t,this.diacriticSensitive=e;};function rt(t,e,r,n){return"number"==typeof t&&t>=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:"Invalid rgba value ["+[t,e,r,n].join(", ")+"]: 'a' must be between 0 and 1.":"Invalid rgba value ["+("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")+"]: 'r', 'g', and 'b' must be between 0 and 255."}function nt(t){if(null===t)return R;if("string"==typeof t)return D;if("boolean"==typeof t)return N;if("number"==typeof t)return U;if(t instanceof Q)return Z;if(t instanceof tt)return $;if(Array.isArray(t)){for(var e,r=t.length,n=0,i=t;n<i.length;n+=1){var o=nt(i[n]);if(e){if(e===o)continue;e=J;break}e=o;}return H(e||J,r)}return K}et.parse=function(t,e){if(2!==t.length)return e.error("Expected one argument.");var r=t[1];if("object"!=typeof r||Array.isArray(r))return e.error("Collator options argument must be an object.");var n=e.parse(void 0!==r["case-sensitive"]&&r["case-sensitive"],1,N);if(!n)return null;var i=e.parse(void 0!==r["diacritic-sensitive"]&&r["diacritic-sensitive"],1,N);if(!i)return null;var o=null;return r.locale&&!(o=e.parse(r.locale,1,D))?null:new et(n,i,o)},et.prototype.evaluate=function(t){return new tt(this.caseSensitive.evaluate(t),this.diacriticSensitive.evaluate(t),this.locale?this.locale.evaluate(t):null)},et.prototype.eachChild=function(t){t(this.caseSensitive),t(this.diacriticSensitive),this.locale&&t(this.locale);},et.prototype.possibleOutputs=function(){return[void 0]},et.prototype.serialize=function(){var t={};return t["case-sensitive"]=this.caseSensitive.serialize(),t["diacritic-sensitive"]=this.diacriticSensitive.serialize(),this.locale&&(t.locale=this.locale.serialize()),["collator",t]};var it=function(t,e){this.type=t,this.value=e;};it.parse=function(t,e){if(2!==t.length)return e.error("'literal' expression requires exactly one argument, but found "+(t.length-1)+" instead.");if(!function t(e){if(null===e)return!0;if("string"==typeof e)return!0;if("boolean"==typeof e)return!0;if("number"==typeof e)return!0;if(e instanceof Q)return!0;if(e instanceof tt)return!0;if(Array.isArray(e)){for(var r=0,n=e;r<n.length;r+=1)if(!t(n[r]))return!1;return!0}if("object"==typeof e){for(var i in e)if(!t(e[i]))return!1;return!0}return!1}(t[1]))return e.error("invalid value");var r=t[1],n=nt(r),i=e.expectedType;return"array"!==n.kind||0!==n.N||!i||"array"!==i.kind||"number"==typeof i.N&&0!==i.N||(n=i),new it(n,r)},it.prototype.evaluate=function(){return this.value},it.prototype.eachChild=function(){},it.prototype.possibleOutputs=function(){return[this.value]},it.prototype.serialize=function(){return"array"===this.type.kind||"object"===this.type.kind?["literal",this.value]:this.value instanceof Q?["rgba"].concat(this.value.toArray()):this.value};var ot=function(t){this.name="ExpressionEvaluationError",this.message=t;};ot.prototype.toJSON=function(){return this.message};var at={string:D,number:U,boolean:N,object:K},st=function(t,e){this.type=t,this.args=e;};st.parse=function(t,e){if(t.length<2)return e.error("Expected at least one argument.");for(var r=t[0],n=at[r],i=[],o=1;o<t.length;o++){var a=e.parse(t[o],o,J);if(!a)return null;i.push(a);}return new st(n,i)},st.prototype.evaluate=function(t){for(var e=0;e<this.args.length;e++){var r=this.args[e].evaluate(t);if(!Y(this.type,nt(r)))return r;if(e===this.args.length-1)throw new ot("Expected value to be of type "+X(this.type)+", but found "+X(nt(r))+" instead.")}return null},st.prototype.eachChild=function(t){this.args.forEach(t);},st.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.args.map(function(t){return t.possibleOutputs()}));var t;},st.prototype.serialize=function(){return[this.type.kind].concat(this.args.map(function(t){return t.serialize()}))};var ut={string:D,number:U,boolean:N},lt=function(t,e){this.type=t,this.input=e;};lt.parse=function(t,e){if(t.length<2||t.length>4)return e.error("Expected 1, 2, or 3 arguments, but found "+(t.length-1)+" instead.");var r,n;if(t.length>2){var i=t[1];if("string"!=typeof i||!(i in ut))return e.error('The item type argument of "array" must be one of string, number, boolean',1);r=ut[i];}else r=J;if(t.length>3){if("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2]))return e.error('The length argument to "array" must be a positive integer literal',2);n=t[2];}var o=H(r,n),a=e.parse(t[t.length-1],t.length-1,J);return a?new lt(o,a):null},lt.prototype.evaluate=function(t){var e=this.input.evaluate(t);if(Y(this.type,nt(e)))throw new ot("Expected value to be of type "+X(this.type)+", but found "+X(nt(e))+" instead.");return e},lt.prototype.eachChild=function(t){t(this.input);},lt.prototype.possibleOutputs=function(){return this.input.possibleOutputs()},lt.prototype.serialize=function(){var t=["array"],e=this.type.itemType;if("string"===e.kind||"number"===e.kind||"boolean"===e.kind){t.push(e.kind);var r=this.type.N;"number"==typeof r&&t.push(r);}return t.push(this.input.serialize()),t};var pt={"to-number":U,"to-color":Z},ct=function(t,e){this.type=t,this.args=e;};ct.parse=function(t,e){if(t.length<2)return e.error("Expected at least one argument.");for(var r=t[0],n=pt[r],i=[],o=1;o<t.length;o++){var a=e.parse(t[o],o,J);if(!a)return null;i.push(a);}return new ct(n,i)},ct.prototype.evaluate=function(t){if("color"===this.type.kind){for(var e,r,n=0,i=this.args;n<i.length;n+=1){if(r=null,"string"==typeof(e=i[n].evaluate(t))){var o=t.parseColor(e);if(o)return o}else if(Array.isArray(e)&&!(r=e.length<3||e.length>4?"Invalid rbga value "+JSON.stringify(e)+": expected an array containing either three or four numeric values.":rt(e[0],e[1],e[2],e[3])))return new Q(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new ot(r||"Could not parse color from value '"+("string"==typeof e?e:JSON.stringify(e))+"'")}for(var a=null,s=0,u=this.args;s<u.length;s+=1){if(null!==(a=u[s].evaluate(t))){var l=Number(a);if(!isNaN(l))return l}}throw new ot("Could not convert "+JSON.stringify(a)+" to number.")},ct.prototype.eachChild=function(t){this.args.forEach(t);},ct.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.args.map(function(t){return t.possibleOutputs()}));var t;},ct.prototype.serialize=function(){var t=["to-"+this.type.kind];return this.eachChild(function(e){t.push(e.serialize());}),t};var ht=["Unknown","Point","LineString","Polygon"],ft=function(){this._parseColorCache={};};ft.prototype.id=function(){return this.feature&&"id"in this.feature?this.feature.id:null},ft.prototype.geometryType=function(){return this.feature?"number"==typeof this.feature.type?ht[this.feature.type]:this.feature.type:null},ft.prototype.properties=function(){return this.feature&&this.feature.properties||{}},ft.prototype.parseColor=function(t){var e=this._parseColorCache[t];return e||(e=this._parseColorCache[t]=Q.parse(t)),e};var yt=function(t,e,r,n){this.name=t,this.type=e,this._evaluate=r,this.args=n;};function dt(t){if(t instanceof yt){if("get"===t.name&&1===t.args.length)return!1;if("has"===t.name&&1===t.args.length)return!1;if("properties"===t.name||"geometry-type"===t.name||"id"===t.name)return!1;if(/^filter-/.test(t.name))return!1}var e=!0;return t.eachChild(function(t){e&&!dt(t)&&(e=!1);}),e}function vt(t,e){if(t instanceof yt&&e.indexOf(t.name)>=0)return!1;var r=!0;return t.eachChild(function(t){r&&!vt(t,e)&&(r=!1);}),r}yt.prototype.evaluate=function(t){return this._evaluate(t,this.args)},yt.prototype.eachChild=function(t){this.args.forEach(t);},yt.prototype.possibleOutputs=function(){return[void 0]},yt.prototype.serialize=function(){return[this.name].concat(this.args.map(function(t){return t.serialize()}))},yt.parse=function(t,e){var r=t[0],n=yt.definitions[r];if(!n)return e.error('Unknown expression "'+r+'". If you wanted a literal array, use ["literal", [...]].',0);for(var i=Array.isArray(n)?n[0]:n.type,o=Array.isArray(n)?[[n[1],n[2]]]:n.overloads,a=o.filter(function(e){var r=e[0];return!Array.isArray(r)||r.length===t.length-1}),s=[],u=1;u<t.length;u++){var l=t[u],p=void 0;if(1===a.length){var c=a[0][0];p=Array.isArray(c)?c[u-1]:c.type;}var h=e.parse(l,1+s.length,p);if(!h)return null;s.push(h);}for(var f=null,y=0,d=a;y<d.length;y+=1){var v=d[y],m=v[0],g=v[1];if(f=new gt(e.registry,e.path,null,e.scope),Array.isArray(m)&&m.length!==s.length)f.error("Expected "+m.length+" arguments, but found "+s.length+" instead.");else{for(var x=0;x<s.length;x++){var b=Array.isArray(m)?m[x]:m.type,w=s[x];f.concat(x+1).checkSubtype(b,w.type);}if(0===f.errors.length)return new yt(r,i,g,s)}}if(1===a.length)e.errors.push.apply(e.errors,f.errors);else{var _=(a.length?a:o).map(function(t){var e,r=t[0];return e=r,Array.isArray(e)?"("+e.map(X).join(", ")+")":"("+X(e.type)+"...)"}).join(" | "),A=s.map(function(t){return X(t.type)}).join(", ");e.error("Expected arguments of type "+_+", but found ("+A+") instead.");}return null},yt.register=function(t,e){for(var r in yt.definitions=e,e)t[r]=yt;};var mt=function(t,e){this.type=e.type,this.name=t,this.boundExpression=e;};mt.parse=function(t,e){if(2!==t.length||"string"!=typeof t[1])return e.error("'var' expression requires exactly one string literal argument.");var r=t[1];return e.scope.has(r)?new mt(r,e.scope.get(r)):e.error('Unknown variable "'+r+'". Make sure "'+r+'" has been bound in an enclosing "let" expression before using it.',1)},mt.prototype.evaluate=function(t){return this.boundExpression.evaluate(t)},mt.prototype.eachChild=function(){},mt.prototype.possibleOutputs=function(){return[void 0]},mt.prototype.serialize=function(){return["var",this.name]};var gt=function(t,e,r,n,i){void 0===e&&(e=[]),void 0===n&&(n=new q),void 0===i&&(i=[]),this.registry=t,this.path=e,this.key=e.map(function(t){return"["+t+"]"}).join(""),this.scope=n,this.errors=i,this.expectedType=r;};function xt(t,e){for(var r,n,i=0,o=t.length-1,a=0;i<=o;){if(r=t[a=Math.floor((i+o)/2)],n=t[a+1],e===r||e>r&&e<n)return a;if(r<e)i=a+1;else{if(!(r>e))throw new ot("Input is not a number.");o=a-1;}}return Math.max(a-1,0)}gt.prototype.parse=function(t,e,r,n,i){return void 0===i&&(i={}),e?this.concat(e,r,n)._parse(t,i):this._parse(t,i)},gt.prototype._parse=function(t,e){if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');var r=t[0];if("string"!=typeof r)return this.error("Expression name must be a string, but found "+typeof r+' instead. If you wanted a literal array, use ["literal", [...]].',0),null;var n=this.registry[r];if(n){var i=n.parse(t,this);if(!i)return null;if(this.expectedType){var o=this.expectedType,a=i.type;if("string"!==o.kind&&"number"!==o.kind&&"boolean"!==o.kind&&"object"!==o.kind||"value"!==a.kind)if("array"===o.kind&&"value"===a.kind)e.omitTypeAnnotations||(i=new lt(o,i));else if("color"!==o.kind||"value"!==a.kind&&"string"!==a.kind){if(this.checkSubtype(this.expectedType,i.type))return null}else e.omitTypeAnnotations||(i=new ct(o,[i]));else e.omitTypeAnnotations||(i=new st(o,[i]));}if(!(i instanceof it)&&function t(e){if(e instanceof mt)return t(e.boundExpression);if(e instanceof yt&&"error"===e.name)return!1;if(e instanceof et)return!1;var r=e instanceof ct||e instanceof st||e instanceof lt;var n=!0;e.eachChild(function(e){n=r?n&&t(e):n&&e instanceof it;});if(!n)return!1;return dt(e)&&vt(e,["zoom","heatmap-density","line-progress","is-supported-script"])}(i)){var s=new ft;try{i=new it(i.type,i.evaluate(s));}catch(t){return this.error(t.message),null}}return i}return this.error('Unknown expression "'+r+'". If you wanted a literal array, use ["literal", [...]].',0)}return void 0===t?this.error("'undefined' value invalid. Use null instead."):"object"==typeof t?this.error('Bare objects invalid. Use ["literal", {...}] instead.'):this.error("Expected an array, but found "+typeof t+" instead.")},gt.prototype.concat=function(t,e,r){var n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new gt(this.registry,n,e||null,i,this.errors)},gt.prototype.error=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];var n=""+this.key+e.map(function(t){return"["+t+"]"}).join("");this.errors.push(new j(n,t));},gt.prototype.checkSubtype=function(t,e){var r=Y(t,e);return r&&this.error(r),r};var bt=function(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(var n=0,i=r;n<i.length;n+=1){var o=i[n],a=o[0],s=o[1];this.labels.push(a),this.outputs.push(s);}};function wt(t,e,r){return t*(1-r)+e*r}bt.parse=function(t,e){var r=t[1],n=t.slice(2);if(t.length-1<4)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(!(r=e.parse(r,1,U)))return null;var i=[],o=null;e.expectedType&&"value"!==e.expectedType.kind&&(o=e.expectedType),n.unshift(-1/0);for(var a=0;a<n.length;a+=2){var s=n[a],u=n[a+1],l=a+1,p=a+2;if("number"!=typeof s)return e.error('Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values.',l);if(i.length&&i[i.length-1][0]>=s)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',l);var c=e.parse(u,p,o);if(!c)return null;o=o||c.type,i.push([s,c]);}return new bt(o,r,i)},bt.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var i=e.length;return n>=e[i-1]?r[i-1].evaluate(t):r[xt(e,n)].evaluate(t)},bt.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;e<r.length;e+=1){t(r[e]);}},bt.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.outputs.map(function(t){return t.possibleOutputs()}));var t;},bt.prototype.serialize=function(){for(var t=["step",this.input.serialize()],e=0;e<this.labels.length;e++)e>0&&t.push(this.labels[e]),t.push(this.outputs[e].serialize());return t};var _t=Object.freeze({number:wt,color:function(t,e,r){return new Q(wt(t.r,e.r,r),wt(t.g,e.g,r),wt(t.b,e.b,r),wt(t.a,e.a,r))},array:function(t,e,r){return t.map(function(t,n){return wt(t,e[n],r)})}}),At=function(t,e,r,n){this.type=t,this.interpolation=e,this.input=r,this.labels=[],this.outputs=[];for(var i=0,o=n;i<o.length;i+=1){var a=o[i],s=a[0],u=a[1];this.labels.push(s),this.outputs.push(u);}};function kt(t,e,r,n){var i=n-r,o=t-r;return 0===i?0:1===e?o/i:(Math.pow(e,o)-1)/(Math.pow(e,i)-1)}At.interpolationFactor=function(t,e,r,n){var o=0;if("exponential"===t.name)o=kt(e,t.base,r,n);else if("linear"===t.name)o=kt(e,1,r,n);else if("cubic-bezier"===t.name){var a=t.controlPoints;o=new i(a[0],a[1],a[2],a[3]).solve(kt(e,1,r,n));}return o},At.parse=function(t,e){var r=t[1],n=t[2],i=t.slice(3);if(!Array.isArray(r)||0===r.length)return e.error("Expected an interpolation type expression.",1);if("linear"===r[0])r={name:"linear"};else if("exponential"===r[0]){var o=r[1];if("number"!=typeof o)return e.error("Exponential interpolation requires a numeric base.",1,1);r={name:"exponential",base:o};}else{if("cubic-bezier"!==r[0])return e.error("Unknown interpolation type "+String(r[0]),1,0);var a=r.slice(1);if(4!==a.length||a.some(function(t){return"number"!=typeof t||t<0||t>1}))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);r={name:"cubic-bezier",controlPoints:a};}if(t.length-1<4)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(!(n=e.parse(n,2,U)))return null;var s=[],u=null;e.expectedType&&"value"!==e.expectedType.kind&&(u=e.expectedType);for(var l=0;l<i.length;l+=2){var p=i[l],c=i[l+1],h=l+3,f=l+4;if("number"!=typeof p)return e.error('Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.',h);if(s.length&&s[s.length-1][0]>=p)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',h);var y=e.parse(c,f,u);if(!y)return null;u=u||y.type,s.push([p,y]);}return"number"===u.kind||"color"===u.kind||"array"===u.kind&&"number"===u.itemType.kind&&"number"==typeof u.N?new At(u,r,n,s):e.error("Type "+X(u)+" is not interpolatable.")},At.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);var o=xt(e,n),a=e[o],s=e[o+1],u=At.interpolationFactor(this.interpolation,n,a,s),l=r[o].evaluate(t),p=r[o+1].evaluate(t);return _t[this.type.kind.toLowerCase()](l,p,u)},At.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;e<r.length;e+=1){t(r[e]);}},At.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.outputs.map(function(t){return t.possibleOutputs()}));var t;},At.prototype.serialize=function(){for(var t=["interpolate","linear"===this.interpolation.name?["linear"]:"exponential"===this.interpolation.name?1===this.interpolation.base?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier"].concat(this.interpolation.controlPoints),this.input.serialize()],e=0;e<this.labels.length;e++)t.push(this.labels[e],this.outputs[e].serialize());return t};var zt=function(t,e){this.type=t,this.args=e;};zt.parse=function(t,e){if(t.length<2)return e.error("Expectected at least one argument.");var r=null,n=e.expectedType;n&&"value"!==n.kind&&(r=n);for(var i=[],o=0,a=t.slice(1);o<a.length;o+=1){var s=a[o],u=e.parse(s,1+i.length,r,void 0,{omitTypeAnnotations:!0});if(!u)return null;r=r||u.type,i.push(u);}var l=n&&i.some(function(t){return Y(n,t.type)});return new zt(l?J:r,i)},zt.prototype.evaluate=function(t){for(var e=null,r=0,n=this.args;r<n.length;r+=1){if(null!==(e=n[r].evaluate(t)))break}return e},zt.prototype.eachChild=function(t){this.args.forEach(t);},zt.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.args.map(function(t){return t.possibleOutputs()}));var t;},zt.prototype.serialize=function(){var t=["coalesce"];return this.eachChild(function(e){t.push(e.serialize());}),t};var St=function(t,e){this.type=e.type,this.bindings=[].concat(t),this.result=e;};St.prototype.evaluate=function(t){return this.result.evaluate(t)},St.prototype.eachChild=function(t){for(var e=0,r=this.bindings;e<r.length;e+=1){t(r[e][1]);}t(this.result);},St.parse=function(t,e){if(t.length<4)return e.error("Expected at least 3 arguments, but found "+(t.length-1)+" instead.");for(var r=[],n=1;n<t.length-1;n+=2){var i=t[n];if("string"!=typeof i)return e.error("Expected string, but found "+typeof i+" instead.",n);if(/[^a-zA-Z0-9_]/.test(i))return e.error("Variable names must contain only alphanumeric characters or '_'.",n);var o=e.parse(t[n+1],n+1);if(!o)return null;r.push([i,o]);}var a=e.parse(t[t.length-1],t.length-1,void 0,r);return a?new St(r,a):null},St.prototype.possibleOutputs=function(){return this.result.possibleOutputs()},St.prototype.serialize=function(){for(var t=["let"],e=0,r=this.bindings;e<r.length;e+=1){var n=r[e],i=n[0],o=n[1];t.push(i,o.serialize());}return t.push(this.result.serialize()),t};var Mt=function(t,e,r){this.type=t,this.index=e,this.input=r;};Mt.parse=function(t,e){if(3!==t.length)return e.error("Expected 2 arguments, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1,U),n=e.parse(t[2],2,H(e.expectedType||J));if(!r||!n)return null;var i=n.type;return new Mt(i.itemType,r,n)},Mt.prototype.evaluate=function(t){var e=this.index.evaluate(t),r=this.input.evaluate(t);if(e<0)throw new ot("Array index out of bounds: "+e+" < 0.");if(e>=r.length)throw new ot("Array index out of bounds: "+e+" > "+(r.length-1)+".");if(e!==Math.floor(e))throw new ot("Array index must be an integer, but found "+e+" instead.");return r[e]},Mt.prototype.eachChild=function(t){t(this.index),t(this.input);},Mt.prototype.possibleOutputs=function(){return[void 0]},Mt.prototype.serialize=function(){return["at",this.index.serialize(),this.input.serialize()]};var Vt=function(t,e,r,n,i,o){this.inputType=t,this.type=e,this.input=r,this.cases=n,this.outputs=i,this.otherwise=o;};Vt.parse=function(t,e){if(t.length<5)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if(t.length%2!=1)return e.error("Expected an even number of arguments.");var r,n;e.expectedType&&"value"!==e.expectedType.kind&&(n=e.expectedType);for(var i={},o=[],a=2;a<t.length-1;a+=2){var s=t[a],u=t[a+1];Array.isArray(s)||(s=[s]);var l=e.concat(a);if(0===s.length)return l.error("Expected at least one branch label.");for(var p=0,c=s;p<c.length;p+=1){var h=c[p];if("number"!=typeof h&&"string"!=typeof h)return l.error("Branch labels must be numbers or strings.");if("number"==typeof h&&Math.abs(h)>Number.MAX_SAFE_INTEGER)return l.error("Branch labels must be integers no larger than "+Number.MAX_SAFE_INTEGER+".");if("number"==typeof h&&Math.floor(h)!==h)return l.error("Numeric branch labels must be integer values.");if(r){if(l.checkSubtype(r,nt(h)))return null}else r=nt(h);if(void 0!==i[String(h)])return l.error("Branch labels must be unique.");i[String(h)]=o.length;}var f=e.parse(u,a,n);if(!f)return null;n=n||f.type,o.push(f);}var y=e.parse(t[1],1,r);if(!y)return null;var d=e.parse(t[t.length-1],t.length-1,n);return d?new Vt(r,n,y,i,o,d):null},Vt.prototype.evaluate=function(t){var e=this.input.evaluate(t);return(this.outputs[this.cases[e]]||this.otherwise).evaluate(t)},Vt.prototype.eachChild=function(t){t(this.input),this.outputs.forEach(t),t(this.otherwise);},Vt.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.outputs.map(function(t){return t.possibleOutputs()})).concat(this.otherwise.possibleOutputs());var t;},Vt.prototype.serialize=function(){for(var t=this,e=["match",this.input.serialize()],r=[],n={},i=0,o=Object.keys(this.cases).sort();i<o.length;i+=1){var a=o[i],s=n[t.cases[a]];void 0===s?(n[t.cases[a]]=r.length,r.push([t.cases[a],[a]])):r[s][1].push(a);}for(var u=function(e){return"number"===t.input.type.kind?Number(e):e},l=0,p=r;l<p.length;l+=1){var c=p[l],h=c[0],f=c[1];1===f.length?e.push(u(f[0])):e.push(f.map(u)),e.push(t.outputs[h].serialize());}return e.push(this.otherwise.serialize()),e};var Bt=function(t,e,r){this.type=t,this.branches=e,this.otherwise=r;};function Ct(t){return"string"===t.kind||"number"===t.kind||"boolean"===t.kind||"null"===t.kind}function It(t,e){return function(){function r(t,e,r){this.type=N,this.lhs=t,this.rhs=e,this.collator=r;}return r.parse=function(t,e){if(3!==t.length&&4!==t.length)return e.error("Expected two or three arguments.");var n=e.parse(t[1],1,J);if(!n)return null;var i=e.parse(t[2],2,J);if(!i)return null;if(!Ct(n.type)&&!Ct(i.type))return e.error("Expected at least one argument to be a string, number, boolean, or null, but found ("+X(n.type)+", "+X(i.type)+") instead.");if(n.type.kind!==i.type.kind&&"value"!==n.type.kind&&"value"!==i.type.kind)return e.error("Cannot compare "+X(n.type)+" and "+X(i.type)+".");var o=null;if(4===t.length){if("string"!==n.type.kind&&"string"!==i.type.kind)return e.error("Cannot use collator to compare non-string types.");if(!(o=e.parse(t[3],3,$)))return null}return new r(n,i,o)},r.prototype.evaluate=function(t){var r=this.collator?0===this.collator.evaluate(t).compare(this.lhs.evaluate(t),this.rhs.evaluate(t)):this.lhs.evaluate(t)===this.rhs.evaluate(t);return e?!r:r},r.prototype.eachChild=function(t){t(this.lhs),t(this.rhs),this.collator&&t(this.collator);},r.prototype.possibleOutputs=function(){return[!0,!1]},r.prototype.serialize=function(){var e=[t];return this.eachChild(function(t){e.push(t.serialize());}),e},r}()}Bt.parse=function(t,e){if(t.length<4)return e.error("Expected at least 3 arguments, but found only "+(t.length-1)+".");if(t.length%2!=0)return e.error("Expected an odd number of arguments.");var r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);for(var n=[],i=1;i<t.length-1;i+=2){var o=e.parse(t[i],i,N);if(!o)return null;var a=e.parse(t[i+1],i+1,r);if(!a)return null;n.push([o,a]),r=r||a.type;}var s=e.parse(t[t.length-1],t.length-1,r);return s?new Bt(r,n,s):null},Bt.prototype.evaluate=function(t){for(var e=0,r=this.branches;e<r.length;e+=1){var n=r[e],i=n[0],o=n[1];if(i.evaluate(t))return o.evaluate(t)}return this.otherwise.evaluate(t)},Bt.prototype.eachChild=function(t){for(var e=0,r=this.branches;e<r.length;e+=1){var n=r[e],i=n[0],o=n[1];t(i),t(o);}t(this.otherwise);},Bt.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.branches.map(function(t){t[0];return t[1].possibleOutputs()})).concat(this.otherwise.possibleOutputs());var t;},Bt.prototype.serialize=function(){var t=["case"];return this.eachChild(function(e){t.push(e.serialize());}),t};var Et=It("==",!1),Ft=It("!=",!0),Pt=function(t){this.type=U,this.input=t;};Pt.parse=function(t,e){if(2!==t.length)return e.error("Expected 1 argument, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1);return r?"array"!==r.type.kind&&"string"!==r.type.kind&&"value"!==r.type.kind?e.error("Expected argument of type string or array, but found "+X(r.type)+" instead."):new Pt(r):null},Pt.prototype.evaluate=function(t){var e=this.input.evaluate(t);if("string"==typeof e)return e.length;if(Array.isArray(e))return e.length;throw new ot("Expected value to be of type string or array, but found "+X(nt(e))+" instead.")},Pt.prototype.eachChild=function(t){t(this.input);},Pt.prototype.possibleOutputs=function(){return[void 0]},Pt.prototype.serialize=function(){var t=["length"];return this.eachChild(function(e){t.push(e.serialize());}),t};var Tt={"==":Et,"!=":Ft,array:lt,at:Mt,boolean:st,case:Bt,coalesce:zt,collator:et,interpolate:At,length:Pt,let:St,literal:it,match:Vt,number:st,object:st,step:bt,string:st,"to-color":ct,"to-number":ct,var:mt};function Ot(t,e){var r=e[0],n=e[1],i=e[2],o=e[3];r=r.evaluate(t),n=n.evaluate(t),i=i.evaluate(t);var a=o?o.evaluate(t):1,s=rt(r,n,i,a);if(s)throw new ot(s);return new Q(r/255*a,n/255*a,i/255*a,a)}function Lt(t,e){return t in e}function jt(t,e){var r=e[t];return void 0===r?null:r}function qt(t,e){var r=e[0],n=e[1];return r.evaluate(t)<n.evaluate(t)}function Rt(t,e){var r=e[0],n=e[1];return r.evaluate(t)>n.evaluate(t)}function Ut(t,e){var r=e[0],n=e[1];return r.evaluate(t)<=n.evaluate(t)}function Dt(t,e){var r=e[0],n=e[1];return r.evaluate(t)>=n.evaluate(t)}function Nt(t){return{type:t}}function Zt(t){return{result:"success",value:t}}function Kt(t){return{result:"error",value:t}}yt.register(Tt,{error:[{kind:"error"},[D],function(t,e){var r=e[0];throw new ot(r.evaluate(t))}],typeof:[D,[J],function(t,e){return X(nt(e[0].evaluate(t)))}],"to-string":[D,[J],function(t,e){var r=e[0],n=typeof(r=r.evaluate(t));return null===r?"":"string"===n||"number"===n||"boolean"===n?String(r):r instanceof Q?r.toString():JSON.stringify(r)}],"to-boolean":[N,[J],function(t,e){var r=e[0];return Boolean(r.evaluate(t))}],"to-rgba":[H(U,4),[Z],function(t,e){return e[0].evaluate(t).toArray()}],rgb:[Z,[U,U,U],Ot],rgba:[Z,[U,U,U,U],Ot],has:{type:N,overloads:[[[D],function(t,e){return Lt(e[0].evaluate(t),t.properties())}],[[D,K],function(t,e){var r=e[0],n=e[1];return Lt(r.evaluate(t),n.evaluate(t))}]]},get:{type:J,overloads:[[[D],function(t,e){return jt(e[0].evaluate(t),t.properties())}],[[D,K],function(t,e){var r=e[0],n=e[1];return jt(r.evaluate(t),n.evaluate(t))}]]},properties:[K,[],function(t){return t.properties()}],"geometry-type":[D,[],function(t){return t.geometryType()}],id:[J,[],function(t){return t.id()}],zoom:[U,[],function(t){return t.globals.zoom}],"heatmap-density":[U,[],function(t){return t.globals.heatmapDensity||0}],"line-progress":[U,[],function(t){return t.globals.lineProgress||0}],"+":[U,Nt(U),function(t,e){for(var r=0,n=0,i=e;n<i.length;n+=1){r+=i[n].evaluate(t);}return r}],"*":[U,Nt(U),function(t,e){for(var r=1,n=0,i=e;n<i.length;n+=1){r*=i[n].evaluate(t);}return r}],"-":{type:U,overloads:[[[U,U],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)-n.evaluate(t)}],[[U],function(t,e){return-e[0].evaluate(t)}]]},"/":[U,[U,U],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)/n.evaluate(t)}],"%":[U,[U,U],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)%n.evaluate(t)}],ln2:[U,[],function(){return Math.LN2}],pi:[U,[],function(){return Math.PI}],e:[U,[],function(){return Math.E}],"^":[U,[U,U],function(t,e){var r=e[0],n=e[1];return Math.pow(r.evaluate(t),n.evaluate(t))}],sqrt:[U,[U],function(t,e){var r=e[0];return Math.sqrt(r.evaluate(t))}],log10:[U,[U],function(t,e){var r=e[0];return Math.log10(r.evaluate(t))}],ln:[U,[U],function(t,e){var r=e[0];return Math.log(r.evaluate(t))}],log2:[U,[U],function(t,e){var r=e[0];return Math.log2(r.evaluate(t))}],sin:[U,[U],function(t,e){var r=e[0];return Math.sin(r.evaluate(t))}],cos:[U,[U],function(t,e){var r=e[0];return Math.cos(r.evaluate(t))}],tan:[U,[U],function(t,e){var r=e[0];return Math.tan(r.evaluate(t))}],asin:[U,[U],function(t,e){var r=e[0];return Math.asin(r.evaluate(t))}],acos:[U,[U],function(t,e){var r=e[0];return Math.acos(r.evaluate(t))}],atan:[U,[U],function(t,e){var r=e[0];return Math.atan(r.evaluate(t))}],min:[U,Nt(U),function(t,e){return Math.min.apply(Math,e.map(function(e){return e.evaluate(t)}))}],max:[U,Nt(U),function(t,e){return Math.max.apply(Math,e.map(function(e){return e.evaluate(t)}))}],abs:[U,[U],function(t,e){var r=e[0];return Math.abs(r.evaluate(t))}],round:[U,[U],function(t,e){var r=e[0].evaluate(t);return r<0?-Math.round(-r):Math.round(r)}],floor:[U,[U],function(t,e){var r=e[0];return Math.floor(r.evaluate(t))}],ceil:[U,[U],function(t,e){var r=e[0];return Math.ceil(r.evaluate(t))}],"filter-==":[N,[D,J],function(t,e){var r=e[0],n=e[1];return t.properties()[r.value]===n.value}],"filter-id-==":[N,[J],function(t,e){var r=e[0];return t.id()===r.value}],"filter-type-==":[N,[D],function(t,e){var r=e[0];return t.geometryType()===r.value}],"filter-<":[N,[D,J],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],o=n.value;return typeof i==typeof o&&i<o}],"filter-id-<":[N,[J],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n<i}],"filter->":[N,[D,J],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],o=n.value;return typeof i==typeof o&&i>o}],"filter-id->":[N,[J],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>i}],"filter-<=":[N,[D,J],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],o=n.value;return typeof i==typeof o&&i<=o}],"filter-id-<=":[N,[J],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n<=i}],"filter->=":[N,[D,J],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],o=n.value;return typeof i==typeof o&&i>=o}],"filter-id->=":[N,[J],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>=i}],"filter-has":[N,[J],function(t,e){return e[0].value in t.properties()}],"filter-has-id":[N,[],function(t){return null!==t.id()}],"filter-type-in":[N,[H(D)],function(t,e){return e[0].value.indexOf(t.geometryType())>=0}],"filter-id-in":[N,[H(J)],function(t,e){return e[0].value.indexOf(t.id())>=0}],"filter-in-small":[N,[D,H(J)],function(t,e){var r=e[0];return e[1].value.indexOf(t.properties()[r.value])>=0}],"filter-in-large":[N,[D,H(J)],function(t,e){var r=e[0],n=e[1];return function(t,e,r,n){for(;r<=n;){var i=r+n>>1;if(e[i]===t)return!0;e[i]>t?n=i-1:r=i+1;}return!1}(t.properties()[r.value],n.value,0,n.value.length-1)}],">":{type:N,overloads:[[[U,U],Rt],[[D,D],Rt],[[D,D,$],function(t,e){var r=e[0],n=e[1];return e[2].evaluate(t).compare(r.evaluate(t),n.evaluate(t))>0}]]},"<":{type:N,overloads:[[[U,U],qt],[[D,D],qt],[[D,D,$],function(t,e){var r=e[0],n=e[1];return e[2].evaluate(t).compare(r.evaluate(t),n.evaluate(t))<0}]]},">=":{type:N,overloads:[[[U,U],Dt],[[D,D],Dt],[[D,D,$],function(t,e){var r=e[0],n=e[1];return e[2].evaluate(t).compare(r.evaluate(t),n.evaluate(t))>=0}]]},"<=":{type:N,overloads:[[[U,U],Ut],[[D,D],Ut],[[D,D,$],function(t,e){var r=e[0],n=e[1];return e[2].evaluate(t).compare(r.evaluate(t),n.evaluate(t))<=0}]]},all:{type:N,overloads:[[[N,N],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)&&n.evaluate(t)}],[Nt(N),function(t,e){for(var r=0,n=e;r<n.length;r+=1){if(!n[r].evaluate(t))return!1}return!0}]]},any:{type:N,overloads:[[[N,N],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)||n.evaluate(t)}],[Nt(N),function(t,e){for(var r=0,n=e;r<n.length;r+=1){if(n[r].evaluate(t))return!0}return!1}]]},"!":[N,[N],function(t,e){return!e[0].evaluate(t)}],"is-supported-script":[N,[D],function(t,e){var r=e[0],n=t.globals&&t.globals.isSupportedScript;return!n||n(r.evaluate(t))}],upcase:[D,[D],function(t,e){return e[0].evaluate(t).toUpperCase()}],downcase:[D,[D],function(t,e){return e[0].evaluate(t).toLowerCase()}],concat:[D,Nt(D),function(t,e){return e.map(function(e){return e.evaluate(t)}).join("")}],"resolved-locale":[D,[$],function(t,e){return e[0].evaluate(t).resolvedLocale()}]});var Jt=.95047,$t=1,Ht=1.08883,Xt=4/29,Gt=6/29,Yt=3*Gt*Gt,Wt=Gt*Gt*Gt,Qt=Math.PI/180,te=180/Math.PI;function ee(t){return t>Wt?Math.pow(t,1/3):t/Yt+Xt}function re(t){return t>Gt?t*t*t:Yt*(t-Xt)}function ne(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function ie(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function oe(t){var e=ie(t.r),r=ie(t.g),n=ie(t.b),i=ee((.4124564*e+.3575761*r+.1804375*n)/Jt),o=ee((.2126729*e+.7151522*r+.072175*n)/$t);return{l:116*o-16,a:500*(i-o),b:200*(o-ee((.0193339*e+.119192*r+.9503041*n)/Ht)),alpha:t.a}}function ae(t){var e=(t.l+16)/116,r=isNaN(t.a)?e:e+t.a/500,n=isNaN(t.b)?e:e-t.b/200;return e=$t*re(e),r=Jt*re(r),n=Ht*re(n),new Q(ne(3.2404542*r-1.5371385*e-.4985314*n),ne(-.969266*r+1.8760108*e+.041556*n),ne(.0556434*r-.2040259*e+1.0572252*n),t.alpha)}var se={forward:oe,reverse:ae,interpolate:function(t,e,r){return{l:wt(t.l,e.l,r),a:wt(t.a,e.a,r),b:wt(t.b,e.b,r),alpha:wt(t.alpha,e.alpha,r)}}},ue={forward:function(t){var e=oe(t),r=e.l,n=e.a,i=e.b,o=Math.atan2(i,n)*te;return{h:o<0?o+360:o,c:Math.sqrt(n*n+i*i),l:r,alpha:t.a}},reverse:function(t){var e=t.h*Qt,r=t.c;return ae({l:t.l,a:Math.cos(e)*r,b:Math.sin(e)*r,alpha:t.alpha})},interpolate:function(t,e,r){return{h:function(t,e,r){var n=e-t;return t+r*(n>180||n<-180?n-360*Math.round(n/360):n)}(t.h,e.h,r),c:wt(t.c,e.c,r),l:wt(t.l,e.l,r),alpha:wt(t.alpha,e.alpha,r)}}},le=Object.freeze({lab:se,hcl:ue});function pe(t){return t instanceof Number?"number":t instanceof String?"string":t instanceof Boolean?"boolean":Array.isArray(t)?"array":null===t?"null":typeof t}function ce(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function he(t){return t}function fe(t,e,r){return void 0!==t?t:void 0!==e?e:void 0!==r?r:void 0}function ye(t,e,r,n,i){return fe(typeof r===i?n[r]:void 0,t.default,e.default)}function de(t,e,r){if("number"!==pe(r))return fe(t.default,e.default);var n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];var i=ge(t.stops,r);return t.stops[i][1]}function ve(t,e,r){var n=void 0!==t.base?t.base:1;if("number"!==pe(r))return fe(t.default,e.default);var i=t.stops.length;if(1===i)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[i-1][0])return t.stops[i-1][1];var o=ge(t.stops,r),a=function(t,e,r,n){var i=n-r,o=t-r;return 0===i?0:1===e?o/i:(Math.pow(e,o)-1)/(Math.pow(e,i)-1)}(r,n,t.stops[o][0],t.stops[o+1][0]),s=t.stops[o][1],u=t.stops[o+1][1],l=_t[e.type]||he;if(t.colorSpace&&"rgb"!==t.colorSpace){var p=le[t.colorSpace];l=function(t,e){return p.reverse(p.interpolate(p.forward(t),p.forward(e),a))};}return"function"==typeof s.evaluate?{evaluate:function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];var r=s.evaluate.apply(void 0,t),n=u.evaluate.apply(void 0,t);if(void 0!==r&&void 0!==n)return l(r,n,a)}}:l(s,u,a)}function me(t,e,r){return"color"===e.type?r=Q.parse(r):pe(r)===e.type||"enum"===e.type&&e.values[r]||(r=void 0),fe(r,t.default,e.default)}function ge(t,e){for(var r,n,i=0,o=t.length-1,a=0;i<=o;){if(r=t[a=Math.floor((i+o)/2)][0],n=t[a+1][0],e===r||e>r&&e<n)return a;r<e?i=a+1:r>e&&(o=a-1);}return Math.max(a-1,0)}var xe=function(t,e){var r;this.expression=t,this._warningHistory={},this._defaultValue="color"===(r=e).type&&ce(r.default)?new Q(0,0,0,0):"color"===r.type?Q.parse(r.default)||null:void 0===r.default?null:r.default,"enum"===e.type&&(this._enumValues=e.values);};function be(t){return Array.isArray(t)&&t.length>0&&"string"==typeof t[0]&&t[0]in Tt}function we(t,e){var r=new gt(Tt,[],function(t){var e={color:Z,string:D,number:U,enum:D,boolean:N};if("array"===t.type)return H(e[t.value]||J,t.length);return e[t.type]||null}(e)),n=r.parse(t);return n?Zt(new xe(n,e)):Kt(r.errors)}xe.prototype.evaluateWithoutErrorHandling=function(t,e){return this._evaluator||(this._evaluator=new ft),this._evaluator.globals=t,this._evaluator.feature=e,this.expression.evaluate(this._evaluator)},xe.prototype.evaluate=function(t,e){this._evaluator||(this._evaluator=new ft),this._evaluator.globals=t,this._evaluator.feature=e;try{var r=this.expression.evaluate(this._evaluator);if(null==r)return this._defaultValue;if(this._enumValues&&!(r in this._enumValues))throw new ot("Expected value to be one of "+Object.keys(this._enumValues).map(function(t){return JSON.stringify(t)}).join(", ")+", but found "+JSON.stringify(r)+" instead.");return r}catch(t){return this._warningHistory[t.message]||(this._warningHistory[t.message]=!0,"undefined"!=typeof console&&console.warn(t.message)),this._defaultValue}};var _e=function(t,e){this.kind=t,this._styleExpression=e;};_e.prototype.evaluateWithoutErrorHandling=function(t,e){return this._styleExpression.evaluateWithoutErrorHandling(t,e)},_e.prototype.evaluate=function(t,e){return this._styleExpression.evaluate(t,e)};var Ae=function(t,e,r){this.kind=t,this.zoomStops=r.labels,this._styleExpression=e,r instanceof At&&(this._interpolationType=r.interpolation);};function ke(t,e){if("error"===(t=we(t,e)).result)return t;var r=t.value.expression,n=dt(r);if(!n&&!e["property-function"])return Kt([new j("","property expressions not supported")]);var i=vt(r,["zoom"]);if(!i&&!1===e["zoom-function"])return Kt([new j("","zoom expressions not supported")]);var o=function t(e){var r=null;if(e instanceof St)r=t(e.result);else if(e instanceof zt)for(var n=0,i=e.args;n<i.length;n+=1){var o=i[n];if(r=t(o))break}else(e instanceof bt||e instanceof At)&&e.input instanceof yt&&"zoom"===e.input.name&&(r=e);if(r instanceof j)return r;e.eachChild(function(e){var n=t(e);n instanceof j?r=n:!r&&n?r=new j("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):r&&n&&r!==n&&(r=new j("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'));});return r}(r);return o||i?o instanceof j?Kt([o]):o instanceof At&&"piecewise-constant"===e.function?Kt([new j("",'"interpolate" expressions cannot be used with this property')]):Zt(o?new Ae(n?"camera":"composite",t.value,o):new _e(n?"constant":"source",t.value)):Kt([new j("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}Ae.prototype.evaluateWithoutErrorHandling=function(t,e){return this._styleExpression.evaluateWithoutErrorHandling(t,e)},Ae.prototype.evaluate=function(t,e){return this._styleExpression.evaluate(t,e)},Ae.prototype.interpolationFactor=function(t,e,r){return this._interpolationType?At.interpolationFactor(this._interpolationType,t,e,r):0};var ze=function(t,e){this._parameters=t,this._specification=e,T(this,function t(e,r){var n,i,o,a="color"===r.type,s=e.stops&&"object"==typeof e.stops[0][0],u=s||void 0!==e.property,l=s||!u,p=e.type||("interpolated"===r.function?"exponential":"interval");if(a&&((e=T({},e)).stops&&(e.stops=e.stops.map(function(t){return[t[0],Q.parse(t[1])]})),e.default?e.default=Q.parse(e.default):e.default=Q.parse(r.default)),e.colorSpace&&"rgb"!==e.colorSpace&&!le[e.colorSpace])throw new Error("Unknown color space: "+e.colorSpace);if("exponential"===p)n=ve;else if("interval"===p)n=de;else if("categorical"===p){n=ye,i=Object.create(null);for(var c=0,h=e.stops;c<h.length;c+=1){var f=h[c];i[f[0]]=f[1];}o=typeof e.stops[0][0];}else{if("identity"!==p)throw new Error('Unknown function type "'+p+'"');n=me;}if(s){for(var y={},d=[],v=0;v<e.stops.length;v++){var m=e.stops[v],g=m[0].zoom;void 0===y[g]&&(y[g]={zoom:g,type:e.type,property:e.property,default:e.default,stops:[]},d.push(g)),y[g].stops.push([m[0].value,m[1]]);}for(var x=[],b=0,w=d;b<w.length;b+=1){var _=w[b];x.push([y[_].zoom,t(y[_],r)]);}return{kind:"composite",interpolationFactor:At.interpolationFactor.bind(void 0,{name:"linear"}),zoomStops:x.map(function(t){return t[0]}),evaluate:function(t,n){var i=t.zoom;return ve({stops:x,base:e.base},r,i).evaluate(i,n)}}}return l?{kind:"camera",interpolationFactor:"exponential"===p?At.interpolationFactor.bind(void 0,{name:"exponential",base:void 0!==e.base?e.base:1}):function(){return 0},zoomStops:e.stops.map(function(t){return t[0]}),evaluate:function(t){var a=t.zoom;return n(e,r,a,i,o)}}:{kind:"source",evaluate:function(t,a){var s=a&&a.properties?a.properties[e.property]:void 0;return void 0===s?fe(e.default,r.default):n(e,r,s,i,o)}}}(this._parameters,this._specification));};function Se(t,e){if(ce(t))return new ze(t,e);if(be(t)){var r=ke(t,e);if("error"===r.result)throw new Error(r.value.map(function(t){return t.key+": "+t.message}).join(", "));return r.value}var n=t;return"string"==typeof t&&"color"===e.type&&(n=Q.parse(t)),{kind:"constant",evaluate:function(){return n}}}function Me(t){var e=t.key,r=t.value,n=t.valueSpec||{},i=t.objectElementValidators||{},o=t.style,a=t.styleSpec,s=[],u=pe(r);if("object"!==u)return[new F(e,r,"object expected, "+u+" found")];for(var l in r){var p=l.split(".")[0],c=n[p]||n["*"],h=void 0;if(i[p])h=i[p];else if(n[p])h=Ye;else if(i["*"])h=i["*"];else{if(!n["*"]){s.push(new F(e,r[l],'unknown property "'+l+'"'));continue}h=Ye;}s=s.concat(h({key:(e?e+".":e)+l,value:r[l],valueSpec:c,style:o,styleSpec:a,object:r,objectKey:l},r));}for(var f in n)i[f]||n[f].required&&void 0===n[f].default&&void 0===r[f]&&s.push(new F(e,r,'missing required property "'+f+'"'));return s}function Ve(t){var e=t.value,r=t.valueSpec,n=t.style,i=t.styleSpec,o=t.key,a=t.arrayElementValidator||Ye;if("array"!==pe(e))return[new F(o,e,"array expected, "+pe(e)+" found")];if(r.length&&e.length!==r.length)return[new F(o,e,"array length "+r.length+" expected, length "+e.length+" found")];if(r["min-length"]&&e.length<r["min-length"])return[new F(o,e,"array length at least "+r["min-length"]+" expected, length "+e.length+" found")];var s={type:r.value};i.$version<7&&(s.function=r.function),"object"===pe(r.value)&&(s=r.value);for(var u=[],l=0;l<e.length;l++)u=u.concat(a({array:e,arrayIndex:l,value:e[l],valueSpec:s,style:n,styleSpec:i,key:o+"["+l+"]"}));return u}function Be(t){var e=t.key,r=t.value,n=t.valueSpec,i=pe(r);return"number"!==i?[new F(e,r,"number expected, "+i+" found")]:"minimum"in n&&r<n.minimum?[new F(e,r,r+" is less than the minimum value "+n.minimum)]:"maximum"in n&&r>n.maximum?[new F(e,r,r+" is greater than the maximum value "+n.maximum)]:[]}function Ce(t){var e,r,n,i=t.valueSpec,o=O(t.value.type),a={},s="categorical"!==o&&void 0===t.value.property,u=!s,l="array"===pe(t.value.stops)&&"array"===pe(t.value.stops[0])&&"object"===pe(t.value.stops[0][0]),p=Me({key:t.key,value:t.value,valueSpec:t.styleSpec.function,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{stops:function(t){if("identity"===o)return[new F(t.key,t.value,'identity function may not have a "stops" property')];var e=[],r=t.value;e=e.concat(Ve({key:t.key,value:r,valueSpec:t.valueSpec,style:t.style,styleSpec:t.styleSpec,arrayElementValidator:c})),"array"===pe(r)&&0===r.length&&e.push(new F(t.key,r,"array must have at least one stop"));return e},default:function(t){return Ye({key:t.key,value:t.value,valueSpec:i,style:t.style,styleSpec:t.styleSpec})}}});return"identity"===o&&s&&p.push(new F(t.key,t.value,'missing required property "property"')),"identity"===o||t.value.stops||p.push(new F(t.key,t.value,'missing required property "stops"')),"exponential"===o&&"piecewise-constant"===t.valueSpec.function&&p.push(new F(t.key,t.value,"exponential functions not supported")),t.styleSpec.$version>=8&&(u&&!t.valueSpec["property-function"]?p.push(new F(t.key,t.value,"property functions not supported")):s&&!t.valueSpec["zoom-function"]&&"heatmap-color"!==t.objectKey&&"line-gradient"!==t.objectKey&&p.push(new F(t.key,t.value,"zoom functions not supported"))),"categorical"!==o&&!l||void 0!==t.value.property||p.push(new F(t.key,t.value,'"property" property is required')),p;function c(t){var e=[],o=t.value,s=t.key;if("array"!==pe(o))return[new F(s,o,"array expected, "+pe(o)+" found")];if(2!==o.length)return[new F(s,o,"array length 2 expected, length "+o.length+" found")];if(l){if("object"!==pe(o[0]))return[new F(s,o,"object expected, "+pe(o[0])+" found")];if(void 0===o[0].zoom)return[new F(s,o,"object stop key must have zoom")];if(void 0===o[0].value)return[new F(s,o,"object stop key must have value")];if(n&&n>O(o[0].zoom))return[new F(s,o[0].zoom,"stop zoom values must appear in ascending order")];O(o[0].zoom)!==n&&(n=O(o[0].zoom),r=void 0,a={}),e=e.concat(Me({key:s+"[0]",value:o[0],valueSpec:{zoom:{}},style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:Be,value:h}}));}else e=e.concat(h({key:s+"[0]",value:o[0],valueSpec:{},style:t.style,styleSpec:t.styleSpec},o));return e.concat(Ye({key:s+"[1]",value:o[1],valueSpec:i,style:t.style,styleSpec:t.styleSpec}))}function h(t,n){var s=pe(t.value),u=O(t.value),l=null!==t.value?t.value:n;if(e){if(s!==e)return[new F(t.key,l,s+" stop domain type must match previous stop domain type "+e)]}else e=s;if("number"!==s&&"string"!==s&&"boolean"!==s)return[new F(t.key,l,"stop domain value must be a number, string, or boolean")];if("number"!==s&&"categorical"!==o){var p="number expected, "+s+" found";return i["property-function"]&&void 0===o&&(p+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new F(t.key,l,p)]}return"categorical"!==o||"number"!==s||isFinite(u)&&Math.floor(u)===u?"categorical"!==o&&"number"===s&&void 0!==r&&u<r?[new F(t.key,l,"stop domain values must appear in ascending order")]:(r=u,"categorical"===o&&u in a?[new F(t.key,l,"stop domain values must be unique")]:(a[u]=!0,[])):[new F(t.key,l,"integer expected, found "+u)]}}function Ie(t){var e=("property"===t.expressionContext?ke:we)(L(t.value),t.valueSpec);return"error"===e.result?e.value.map(function(e){return new F(""+t.key+e.key,t.value,e.message)}):"property"===t.expressionContext&&"text-font"===t.propertyKey&&-1!==e.value._styleExpression.expression.possibleOutputs().indexOf(void 0)?[new F(t.key,t.value,'Invalid data expression for "text-font". Output values must be contained as literals within the expression.')]:[]}function Ee(t){var e=t.key,r=t.value,n=t.valueSpec,i=[];return Array.isArray(n.values)?-1===n.values.indexOf(O(r))&&i.push(new F(e,r,"expected one of ["+n.values.join(", ")+"], "+JSON.stringify(r)+" found")):-1===Object.keys(n.values).indexOf(O(r))&&i.push(new F(e,r,"expected one of ["+Object.keys(n.values).join(", ")+"], "+JSON.stringify(r)+" found")),i}function Fe(t){if(!Array.isArray(t)||0===t.length)return!1;switch(t[0]){case"has":return t.length>=2&&"$id"!==t[1]&&"$type"!==t[1];case"in":case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return 3===t.length&&(Array.isArray(t[1])||Array.isArray(t[2]));case"any":case"all":for(var e=0,r=t.slice(1);e<r.length;e+=1){var n=r[e];if(!Fe(n)&&"boolean"!=typeof n)return!1}return!0;default:return!0}}ze.deserialize=function(t){return new ze(t._parameters,t._specification)},ze.serialize=function(t){return{_parameters:t._parameters,_specification:t._specification}};var Pe={type:"boolean",default:!1,function:!0,"property-function":!0,"zoom-function":!0};function Te(t){if(!t)return function(){return!0};Fe(t)||(t=Le(t));var e=we(t,Pe);if("error"===e.result)throw new Error(e.value.map(function(t){return t.key+": "+t.message}).join(", "));return function(t,r){return e.value.evaluate(t,r)}}function Oe(t,e){return t<e?-1:t>e?1:0}function Le(t){if(!t)return!0;var e,r=t[0];return t.length<=1?"any"!==r:"=="===r?je(t[1],t[2],"=="):"!="===r?Ue(je(t[1],t[2],"==")):"<"===r||">"===r||"<="===r||">="===r?je(t[1],t[2],r):"any"===r?(e=t.slice(1),["any"].concat(e.map(Le))):"all"===r?["all"].concat(t.slice(1).map(Le)):"none"===r?["all"].concat(t.slice(1).map(Le).map(Ue)):"in"===r?qe(t[1],t.slice(2)):"!in"===r?Ue(qe(t[1],t.slice(2))):"has"===r?Re(t[1]):"!has"!==r||Ue(Re(t[1]))}function je(t,e,r){switch(t){case"$type":return["filter-type-"+r,e];case"$id":return["filter-id-"+r,e];default:return["filter-"+r,t,e]}}function qe(t,e){if(0===e.length)return!1;switch(t){case"$type":return["filter-type-in",["literal",e]];case"$id":return["filter-id-in",["literal",e]];default:return e.length>200&&!e.some(function(t){return typeof t!=typeof e[0]})?["filter-in-large",t,["literal",e.sort(Oe)]]:["filter-in-small",t,["literal",e]]}}function Re(t){switch(t){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",t]}}function Ue(t){return["!",t]}function De(t){return Fe(L(t.value))?Ie(T({},t,{expressionContext:"filter",valueSpec:{value:"boolean"}})):function t(e){var r=e.value;var n=e.key;if("array"!==pe(r))return[new F(n,r,"array expected, "+pe(r)+" found")];var i=e.styleSpec;var o;var a=[];if(r.length<1)return[new F(n,r,"filter array must have at least 1 element")];a=a.concat(Ee({key:n+"[0]",value:r[0],valueSpec:i.filter_operator,style:e.style,styleSpec:e.styleSpec}));switch(O(r[0])){case"<":case"<=":case">":case">=":r.length>=2&&"$type"===O(r[1])&&a.push(new F(n,r,'"$type" cannot be use with operator "'+r[0]+'"'));case"==":case"!=":3!==r.length&&a.push(new F(n,r,'filter array for operator "'+r[0]+'" must have 3 elements'));case"in":case"!in":r.length>=2&&"string"!==(o=pe(r[1]))&&a.push(new F(n+"[1]",r[1],"string expected, "+o+" found"));for(var s=2;s<r.length;s++)o=pe(r[s]),"$type"===O(r[1])?a=a.concat(Ee({key:n+"["+s+"]",value:r[s],valueSpec:i.geometry_type,style:e.style,styleSpec:e.styleSpec})):"string"!==o&&"number"!==o&&"boolean"!==o&&a.push(new F(n+"["+s+"]",r[s],"string, number, or boolean expected, "+o+" found"));break;case"any":case"all":case"none":for(var u=1;u<r.length;u++)a=a.concat(t({key:n+"["+u+"]",value:r[u],style:e.style,styleSpec:e.styleSpec}));break;case"has":case"!has":o=pe(r[1]),2!==r.length?a.push(new F(n,r,'filter array for "'+r[0]+'" operator must have 2 elements')):"string"!==o&&a.push(new F(n+"[1]",r[1],"string expected, "+o+" found"));}return a}(t)}function Ne(t,e){var r=t.key,n=t.style,i=t.styleSpec,o=t.value,a=t.objectKey,s=i[e+"_"+t.layerType];if(!s)return[];var u=a.match(/^(.*)-transition$/);if("paint"===e&&u&&s[u[1]]&&s[u[1]].transition)return Ye({key:r,value:o,valueSpec:i.transition,style:n,styleSpec:i});var l,p=t.valueSpec||s[a];if(!p)return[new F(r,o,'unknown property "'+a+'"')];if("string"===pe(o)&&p["property-function"]&&!p.tokens&&(l=/^{([^}]+)}$/.exec(o)))return[new F(r,o,'"'+a+'" does not support interpolation syntax\nUse an identity property function instead: `{ "type": "identity", "property": '+JSON.stringify(l[1])+" }`.")];var c=[];return"symbol"===t.layerType&&("text-field"===a&&n&&!n.glyphs&&c.push(new F(r,o,'use of "text-field" requires a style "glyphs" property')),"text-font"===a&&ce(L(o))&&"identity"===O(o.type)&&c.push(new F(r,o,'"text-font" does not support identity functions'))),c.concat(Ye({key:t.key,value:o,valueSpec:p,style:n,styleSpec:i,expressionContext:"property",propertyKey:a}))}function Ze(t){return Ne(t,"paint")}function Ke(t){return Ne(t,"layout")}function Je(t){var e=[],r=t.value,n=t.key,i=t.style,o=t.styleSpec;r.type||r.ref||e.push(new F(n,r,'either "type" or "ref" is required'));var a,s=O(r.type),u=O(r.ref);if(r.id)for(var l=O(r.id),p=0;p<t.arrayIndex;p++){var c=i.layers[p];O(c.id)===l&&e.push(new F(n,r.id,'duplicate layer id "'+r.id+'", previously used at line '+c.id.__line__));}if("ref"in r)["type","source","source-layer","filter","layout"].forEach(function(t){t in r&&e.push(new F(n,r[t],'"'+t+'" is prohibited for ref layers'));}),i.layers.forEach(function(t){O(t.id)===u&&(a=t);}),a?a.ref?e.push(new F(n,r.ref,"ref cannot reference another ref layer")):s=O(a.type):e.push(new F(n,r.ref,'ref layer "'+u+'" not found'));else if("background"!==s)if(r.source){var h=i.sources&&i.sources[r.source],f=h&&O(h.type);h?"vector"===f&&"raster"===s?e.push(new F(n,r.source,'layer "'+r.id+'" requires a raster source')):"raster"===f&&"raster"!==s?e.push(new F(n,r.source,'layer "'+r.id+'" requires a vector source')):"vector"!==f||r["source-layer"]?"raster-dem"===f&&"hillshade"!==s?e.push(new F(n,r.source,"raster-dem source can only be used with layer type 'hillshade'.")):"line"!==s||!r.paint||!r.paint["line-gradient"]||"geojson"===f&&h.lineMetrics||e.push(new F(n,r,'layer "'+r.id+'" specifies a line-gradient, which requires a GeoJSON source with `lineMetrics` enabled.')):e.push(new F(n,r,'layer "'+r.id+'" must specify a "source-layer"')):e.push(new F(n,r.source,'source "'+r.source+'" not found'));}else e.push(new F(n,r,'missing required property "source"'));return e=e.concat(Me({key:n,value:r,valueSpec:o.layer,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{"*":function(){return[]},type:function(){return Ye({key:n+".type",value:r.type,valueSpec:o.layer.type,style:t.style,styleSpec:t.styleSpec,object:r,objectKey:"type"})},filter:De,layout:function(t){return Me({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{"*":function(t){return Ke(T({layerType:s},t))}}})},paint:function(t){return Me({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{"*":function(t){return Ze(T({layerType:s},t))}}})}}}))}function $e(t){var e=t.value,r=t.key,n=t.styleSpec,i=t.style;if(!e.type)return[new F(r,e,'"type" is required')];var o=O(e.type),a=[];switch(o){case"vector":case"raster":case"raster-dem":if(a=a.concat(Me({key:r,value:e,valueSpec:n["source_"+o.replace("-","_")],style:t.style,styleSpec:n})),"url"in e)for(var s in e)["type","url","tileSize"].indexOf(s)<0&&a.push(new F(r+"."+s,e[s],'a source with a "url" property may not include a "'+s+'" property'));return a;case"geojson":return Me({key:r,value:e,valueSpec:n.source_geojson,style:i,styleSpec:n});case"video":return Me({key:r,value:e,valueSpec:n.source_video,style:i,styleSpec:n});case"image":return Me({key:r,value:e,valueSpec:n.source_image,style:i,styleSpec:n});case"canvas":return a.push(new F(r,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")),a;default:return Ee({key:r+".type",value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]},style:i,styleSpec:n})}}function He(t){var e=t.value,r=t.styleSpec,n=r.light,i=t.style,o=[],a=pe(e);if(void 0===e)return o;if("object"!==a)return o=o.concat([new F("light",e,"object expected, "+a+" found")]);for(var s in e){var u=s.match(/^(.*)-transition$/);o=u&&n[u[1]]&&n[u[1]].transition?o.concat(Ye({key:s,value:e[s],valueSpec:r.transition,style:i,styleSpec:r})):n[s]?o.concat(Ye({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r})):o.concat([new F(s,e[s],'unknown property "'+s+'"')]);}return o}function Xe(t){var e=t.value,r=t.key,n=pe(e);return"string"!==n?[new F(r,e,"string expected, "+n+" found")]:[]}var Ge={"*":function(){return[]},array:Ve,boolean:function(t){var e=t.value,r=t.key,n=pe(e);return"boolean"!==n?[new F(r,e,"boolean expected, "+n+" found")]:[]},number:Be,color:function(t){var e=t.key,r=t.value,n=pe(r);return"string"!==n?[new F(e,r,"color expected, "+n+" found")]:null===W(r)?[new F(e,r,'color expected, "'+r+'" found')]:[]},constants:P,enum:Ee,filter:De,function:Ce,layer:Je,object:Me,source:$e,light:He,string:Xe};function Ye(t){var e=t.value,r=t.valueSpec,n=t.styleSpec;return r.function&&ce(O(e))?Ce(t):r.function&&be(L(e))?Ie(t):r.type&&Ge[r.type]?Ge[r.type](t):Me(T({},t,{valueSpec:r.type?n[r.type]:r}))}function We(t){var e=t.value,r=t.key,n=Xe(t);return n.length?n:(-1===e.indexOf("{fontstack}")&&n.push(new F(r,e,'"glyphs" url must include a "{fontstack}" token')),-1===e.indexOf("{range}")&&n.push(new F(r,e,'"glyphs" url must include a "{range}" token')),n)}function Qe(t,e){e=e||E;var r=[];return r=r.concat(Ye({key:"",value:t,valueSpec:e.$root,styleSpec:e,style:t,objectElementValidators:{glyphs:We,"*":function(){return[]}}})),t.constants&&(r=r.concat(P({key:"constants",value:t.constants,style:t,styleSpec:e}))),tr(r)}function tr(t){return[].concat(t).sort(function(t,e){return t.line-e.line})}function er(t){return function(){return tr(t.apply(this,arguments))}}Qe.source=er($e),Qe.light=er(He),Qe.layer=er(Je),Qe.filter=er(De),Qe.paintProperty=er(Ze),Qe.layoutProperty=er(Ke);var rr=Qe,nr=Qe.light,ir=Qe.paintProperty,or=Qe.layoutProperty;function ar(t,e){var r=!1;if(e&&e.length)for(var n=0,i=e;n<i.length;n+=1){var o=i[n];t.fire(new C(new Error(o.message))),r=!0;}return r}var sr=lr,ur=3;function lr(t,e,r){var n=this.cells=[];if(t instanceof ArrayBuffer){this.arrayBuffer=t;var i=new Int32Array(this.arrayBuffer);t=i[0],e=i[1],r=i[2],this.d=e+2*r;for(var o=0;o<this.d*this.d;o++){var a=i[ur+o],s=i[ur+o+1];n.push(a===s?null:i.subarray(a,s));}var u=i[ur+n.length],l=i[ur+n.length+1];this.keys=i.subarray(u,l),this.bboxes=i.subarray(l),this.insert=this._insertReadonly;}else{this.d=e+2*r;for(var p=0;p<this.d*this.d;p++)n.push([]);this.keys=[],this.bboxes=[];}this.n=e,this.extent=t,this.padding=r,this.scale=e/t,this.uid=0;var c=r/e*t;this.min=-c,this.max=t+c;}lr.prototype.insert=function(t,e,r,n,i){this._forEachCell(e,r,n,i,this._insertCell,this.uid++),this.keys.push(t),this.bboxes.push(e),this.bboxes.push(r),this.bboxes.push(n),this.bboxes.push(i);},lr.prototype._insertReadonly=function(){throw"Cannot insert into a GridIndex created from an ArrayBuffer."},lr.prototype._insertCell=function(t,e,r,n,i,o){this.cells[i].push(o);},lr.prototype.query=function(t,e,r,n){var i=this.min,o=this.max;if(t<=i&&e<=i&&o<=r&&o<=n)return Array.prototype.slice.call(this.keys);var a=[];return this._forEachCell(t,e,r,n,this._queryCell,a,{}),a},lr.prototype._queryCell=function(t,e,r,n,i,o,a){var s=this.cells[i];if(null!==s)for(var u=this.keys,l=this.bboxes,p=0;p<s.length;p++){var c=s[p];if(void 0===a[c]){var h=4*c;t<=l[h+2]&&e<=l[h+3]&&r>=l[h+0]&&n>=l[h+1]?(a[c]=!0,o.push(u[c])):a[c]=!1;}}},lr.prototype._forEachCell=function(t,e,r,n,i,o,a){for(var s=this._convertToCellCoord(t),u=this._convertToCellCoord(e),l=this._convertToCellCoord(r),p=this._convertToCellCoord(n),c=s;c<=l;c++)for(var h=u;h<=p;h++){var f=this.d*h+c;if(i.call(this,t,e,r,n,f,o,a))return}},lr.prototype._convertToCellCoord=function(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))},lr.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var t=this.cells,e=ur+this.cells.length+1+1,r=0,n=0;n<this.cells.length;n++)r+=this.cells[n].length;var i=new Int32Array(e+r+this.keys.length+this.bboxes.length);i[0]=this.extent,i[1]=this.n,i[2]=this.padding;for(var o=e,a=0;a<t.length;a++){var s=t[a];i[ur+a]=o,i.set(s,o),o+=s.length;}return i[ur+t.length]=o,i.set(this.keys,o),o+=this.keys.length,i[ur+t.length+1]=o,i.set(this.bboxes,o),o+=this.bboxes.length,i.buffer};var pr=self.ImageData,cr={};function hr(t,e,r){void 0===r&&(r={}),Object.defineProperty(e,"_classRegistryKey",{value:t,writeable:!1}),cr[t]={klass:e,omit:r.omit||[],shallow:r.shallow||[]};}for(var fr in hr("Object",Object),sr.serialize=function(t,e){var r=t.toArrayBuffer();return e&&e.push(r),r},sr.deserialize=function(t){return new sr(t)},hr("Grid",sr),hr("Color",Q),hr("Error",Error),hr("StylePropertyFunction",ze),hr("StyleExpression",xe,{omit:["_evaluator"]}),hr("ZoomDependentExpression",Ae),hr("ZoomConstantExpression",_e),hr("CompoundExpression",yt,{omit:["_evaluate"]}),Tt)Tt[fr]._classRegistryKey||hr("Expression_"+fr,Tt[fr]);function yr(t,e){if(null==t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||t instanceof Boolean||t instanceof Number||t instanceof String||t instanceof Date||t instanceof RegExp)return t;if(t instanceof ArrayBuffer)return e&&e.push(t),t;if(ArrayBuffer.isView(t)){var r=t;return e&&e.push(r.buffer),r}if(t instanceof pr)return e&&e.push(t.data.buffer),t;if(Array.isArray(t)){for(var n=[],i=0,o=t;i<o.length;i+=1){var a=o[i];n.push(yr(a,e));}return n}if("object"==typeof t){var s=t.constructor,u=s._classRegistryKey;if(!u)throw new Error("can't serialize object of unregistered class");var l={};if(s.serialize)l._serialized=s.serialize(t,e);else{for(var p in t)if(t.hasOwnProperty(p)&&!(cr[u].omit.indexOf(p)>=0)){var c=t[p];l[p]=cr[u].shallow.indexOf(p)>=0?c:yr(c,e);}t instanceof Error&&(l.message=t.message);}return{name:u,properties:l}}throw new Error("can't serialize object of type "+typeof t)}function dr(t){if(null==t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||t instanceof Boolean||t instanceof Number||t instanceof String||t instanceof Date||t instanceof RegExp||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||t instanceof pr)return t;if(Array.isArray(t))return t.map(function(t){return dr(t)});if("object"==typeof t){var e=t,r=e.name,n=e.properties;if(!r)throw new Error("can't deserialize object of anonymous class");var i=cr[r].klass;if(!i)throw new Error("can't deserialize unregistered class "+r);if(i.deserialize)return i.deserialize(n._serialized);for(var o=Object.create(i.prototype),a=0,s=Object.keys(n);a<s.length;a+=1){var u=s[a];o[u]=cr[r].shallow.indexOf(u)>=0?n[u]:dr(n[u]);}return o}throw new Error("can't deserialize object of type "+typeof t)}var vr=function(){this.first=!0;};vr.prototype.update=function(t,e){var r=Math.floor(t);return this.first?(this.first=!1,this.lastIntegerZoom=r,this.lastIntegerZoomTime=0,this.lastZoom=t,this.lastFloorZoom=r,!0):(this.lastFloorZoom>r?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoom<r&&(this.lastIntegerZoom=r,this.lastIntegerZoomTime=e),t!==this.lastZoom&&(this.lastZoom=t,this.lastFloorZoom=r,!0))};var mr={"Latin-1 Supplement":function(t){return t>=128&&t<=255},Arabic:function(t){return t>=1536&&t<=1791},"Arabic Supplement":function(t){return t>=1872&&t<=1919},"Arabic Extended-A":function(t){return t>=2208&&t<=2303},"Hangul Jamo":function(t){return t>=4352&&t<=4607},"Unified Canadian Aboriginal Syllabics":function(t){return t>=5120&&t<=5759},Khmer:function(t){return t>=6016&&t<=6143},"Unified Canadian Aboriginal Syllabics Extended":function(t){return t>=6320&&t<=6399},"General Punctuation":function(t){return t>=8192&&t<=8303},"Letterlike Symbols":function(t){return t>=8448&&t<=8527},"Number Forms":function(t){return t>=8528&&t<=8591},"Miscellaneous Technical":function(t){return t>=8960&&t<=9215},"Control Pictures":function(t){return t>=9216&&t<=9279},"Optical Character Recognition":function(t){return t>=9280&&t<=9311},"Enclosed Alphanumerics":function(t){return t>=9312&&t<=9471},"Geometric Shapes":function(t){return t>=9632&&t<=9727},"Miscellaneous Symbols":function(t){return t>=9728&&t<=9983},"Miscellaneous Symbols and Arrows":function(t){return t>=11008&&t<=11263},"CJK Radicals Supplement":function(t){return t>=11904&&t<=12031},"Kangxi Radicals":function(t){return t>=12032&&t<=12255},"Ideographic Description Characters":function(t){return t>=12272&&t<=12287},"CJK Symbols and Punctuation":function(t){return t>=12288&&t<=12351},Hiragana:function(t){return t>=12352&&t<=12447},Katakana:function(t){return t>=12448&&t<=12543},Bopomofo:function(t){return t>=12544&&t<=12591},"Hangul Compatibility Jamo":function(t){return t>=12592&&t<=12687},Kanbun:function(t){return t>=12688&&t<=12703},"Bopomofo Extended":function(t){return t>=12704&&t<=12735},"CJK Strokes":function(t){return t>=12736&&t<=12783},"Katakana Phonetic Extensions":function(t){return t>=12784&&t<=12799},"Enclosed CJK Letters and Months":function(t){return t>=12800&&t<=13055},"CJK Compatibility":function(t){return t>=13056&&t<=13311},"CJK Unified Ideographs Extension A":function(t){return t>=13312&&t<=19903},"Yijing Hexagram Symbols":function(t){return t>=19904&&t<=19967},"CJK Unified Ideographs":function(t){return t>=19968&&t<=40959},"Yi Syllables":function(t){return t>=40960&&t<=42127},"Yi Radicals":function(t){return t>=42128&&t<=42191},"Hangul Jamo Extended-A":function(t){return t>=43360&&t<=43391},"Hangul Syllables":function(t){return t>=44032&&t<=55215},"Hangul Jamo Extended-B":function(t){return t>=55216&&t<=55295},"Private Use Area":function(t){return t>=57344&&t<=63743},"CJK Compatibility Ideographs":function(t){return t>=63744&&t<=64255},"Arabic Presentation Forms-A":function(t){return t>=64336&&t<=65023},"Vertical Forms":function(t){return t>=65040&&t<=65055},"CJK Compatibility Forms":function(t){return t>=65072&&t<=65103},"Small Form Variants":function(t){return t>=65104&&t<=65135},"Arabic Presentation Forms-B":function(t){return t>=65136&&t<=65279},"Halfwidth and Fullwidth Forms":function(t){return t>=65280&&t<=65519}};function gr(t){for(var e=0,r=t;e<r.length;e+=1){if(br(r[e].charCodeAt(0)))return!0}return!1}function xr(t){return!mr.Arabic(t)&&(!mr["Arabic Supplement"](t)&&(!mr["Arabic Extended-A"](t)&&(!mr["Arabic Presentation Forms-A"](t)&&!mr["Arabic Presentation Forms-B"](t))))}function br(t){return 746===t||747===t||!(t<4352)&&(!!mr["Bopomofo Extended"](t)||(!!mr.Bopomofo(t)||(!(!mr["CJK Compatibility Forms"](t)||t>=65097&&t<=65103)||(!!mr["CJK Compatibility Ideographs"](t)||(!!mr["CJK Compatibility"](t)||(!!mr["CJK Radicals Supplement"](t)||(!!mr["CJK Strokes"](t)||(!(!mr["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||(!!mr["CJK Unified Ideographs Extension A"](t)||(!!mr["CJK Unified Ideographs"](t)||(!!mr["Enclosed CJK Letters and Months"](t)||(!!mr["Hangul Compatibility Jamo"](t)||(!!mr["Hangul Jamo Extended-A"](t)||(!!mr["Hangul Jamo Extended-B"](t)||(!!mr["Hangul Jamo"](t)||(!!mr["Hangul Syllables"](t)||(!!mr.Hiragana(t)||(!!mr["Ideographic Description Characters"](t)||(!!mr.Kanbun(t)||(!!mr["Kangxi Radicals"](t)||(!!mr["Katakana Phonetic Extensions"](t)||(!(!mr.Katakana(t)||12540===t)||(!(!mr["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||(!(!mr["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||(!!mr["Unified Canadian Aboriginal Syllabics"](t)||(!!mr["Unified Canadian Aboriginal Syllabics Extended"](t)||(!!mr["Vertical Forms"](t)||(!!mr["Yijing Hexagram Symbols"](t)||(!!mr["Yi Syllables"](t)||!!mr["Yi Radicals"](t))))))))))))))))))))))))))))))}function wr(t){return!(br(t)||function(t){return!!(mr["Latin-1 Supplement"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||mr["General Punctuation"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||mr["Letterlike Symbols"](t)||mr["Number Forms"](t)||mr["Miscellaneous Technical"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||mr["Control Pictures"](t)&&9251!==t||mr["Optical Character Recognition"](t)||mr["Enclosed Alphanumerics"](t)||mr["Geometric Shapes"](t)||mr["Miscellaneous Symbols"](t)&&!(t>=9754&&t<=9759)||mr["Miscellaneous Symbols and Arrows"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||mr["CJK Symbols and Punctuation"](t)||mr.Katakana(t)||mr["Private Use Area"](t)||mr["CJK Compatibility Forms"](t)||mr["Small Form Variants"](t)||mr["Halfwidth and Fullwidth Forms"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)}(t))}function _r(t,e){return!(!e&&(t>=1424&&t<=2303||mr["Arabic Presentation Forms-A"](t)||mr["Arabic Presentation Forms-B"](t)))&&!(t>=2304&&t<=3583||t>=3840&&t<=4255||mr.Khmer(t))}var Ar,kr=!1,zr=null,Sr=!1,Mr=new I,Vr={applyArabicShaping:null,processBidirectionalText:null,isLoaded:function(){return Sr||null!=Vr.applyArabicShaping}},Br=function(t,e){this.zoom=t,e?(this.now=e.now,this.fadeDuration=e.fadeDuration,this.zoomHistory=e.zoomHistory,this.transition=e.transition):(this.now=0,this.fadeDuration=0,this.zoomHistory=new vr,this.transition={});};Br.prototype.isSupportedScript=function(t){return function(t,e){for(var r=0,n=t;r<n.length;r+=1)if(!_r(n[r].charCodeAt(0),e))return!1;return!0}(t,Vr.isLoaded())},Br.prototype.crossFadingFactor=function(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)};var Cr=function(t,e){this.property=t,this.value=e,this.expression=Se(void 0===e?t.specification.default:e,t.specification);};Cr.prototype.isDataDriven=function(){return"source"===this.expression.kind||"composite"===this.expression.kind},Cr.prototype.possiblyEvaluate=function(t){return this.property.possiblyEvaluate(this,t)};var Ir=function(t){this.property=t,this.value=new Cr(t,void 0);};Ir.prototype.transitioned=function(t,e){return new Fr(this.property,this.value,e,h({},t.transition,this.transition),t.now)},Ir.prototype.untransitioned=function(){return new Fr(this.property,this.value,null,{},0)};var Er=function(t){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues);};Er.prototype.getValue=function(t){return g(this._values[t].value.value)},Er.prototype.setValue=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new Ir(this._values[t].property)),this._values[t].value=new Cr(this._values[t].property,null===e?void 0:g(e));},Er.prototype.getTransition=function(t){return g(this._values[t].transition)},Er.prototype.setTransition=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new Ir(this._values[t].property)),this._values[t].transition=g(e)||void 0;},Er.prototype.serialize=function(){for(var t={},e=0,r=Object.keys(this._values);e<r.length;e+=1){var n=r[e],i=this.getValue(n);void 0!==i&&(t[n]=i);var o=this.getTransition(n);void 0!==o&&(t[n+"-transition"]=o);}return t},Er.prototype.transitioned=function(t,e){for(var r=new Pr(this._properties),n=0,i=Object.keys(this._values);n<i.length;n+=1){var o=i[n];r._values[o]=this._values[o].transitioned(t,e._values[o]);}return r},Er.prototype.untransitioned=function(){for(var t=new Pr(this._properties),e=0,r=Object.keys(this._values);e<r.length;e+=1){var n=r[e];t._values[n]=this._values[n].untransitioned();}return t};var Fr=function(t,e,r,n,i){this.property=t,this.value=e,this.begin=i+n.delay||0,this.end=this.begin+n.duration||0,t.specification.transition&&(n.delay||n.duration)&&(this.prior=r);};Fr.prototype.possiblyEvaluate=function(t){var e=t.now||0,r=this.value.possiblyEvaluate(t),n=this.prior;if(n){if(e>this.end)return this.prior=null,r;if(this.value.isDataDriven())return this.prior=null,r;if(e<this.begin)return n.possiblyEvaluate(t);var i=(e-this.begin)/(this.end-this.begin);return this.property.interpolate(n.possiblyEvaluate(t),r,function(t){if(t<=0)return 0;if(t>=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}(i))}return r};var Pr=function(t){this._properties=t,this._values=Object.create(t.defaultTransitioningPropertyValues);};Pr.prototype.possiblyEvaluate=function(t){for(var e=new Lr(this._properties),r=0,n=Object.keys(this._values);r<n.length;r+=1){var i=n[r];e._values[i]=this._values[i].possiblyEvaluate(t);}return e},Pr.prototype.hasTransition=function(){for(var t=0,e=Object.keys(this._values);t<e.length;t+=1){var r=e[t];if(this._values[r].prior)return!0}return!1};var Tr=function(t){this._properties=t,this._values=Object.create(t.defaultPropertyValues);};Tr.prototype.getValue=function(t){return g(this._values[t].value)},Tr.prototype.setValue=function(t,e){this._values[t]=new Cr(this._values[t].property,null===e?void 0:g(e));},Tr.prototype.serialize=function(){for(var t={},e=0,r=Object.keys(this._values);e<r.length;e+=1){var n=r[e],i=this.getValue(n);void 0!==i&&(t[n]=i);}return t},Tr.prototype.possiblyEvaluate=function(t){for(var e=new Lr(this._properties),r=0,n=Object.keys(this._values);r<n.length;r+=1){var i=n[r];e._values[i]=this._values[i].possiblyEvaluate(t);}return e};var Or=function(t,e,r){this.property=t,this.value=e,this.globals=r;};Or.prototype.isConstant=function(){return"constant"===this.value.kind},Or.prototype.constantOr=function(t){return"constant"===this.value.kind?this.value.value:t},Or.prototype.evaluate=function(t){return this.property.evaluate(this.value,this.globals,t)};var Lr=function(t){this._properties=t,this._values=Object.create(t.defaultPossiblyEvaluatedValues);};Lr.prototype.get=function(t){return this._values[t]};var jr=function(t){this.specification=t;};jr.prototype.possiblyEvaluate=function(t,e){return t.expression.evaluate(e)},jr.prototype.interpolate=function(t,e,r){var n=_t[this.specification.type];return n?n(t,e,r):t};var qr=function(t){this.specification=t;};qr.prototype.possiblyEvaluate=function(t,e){return"constant"===t.expression.kind||"camera"===t.expression.kind?new Or(this,{kind:"constant",value:t.expression.evaluate(e)},e):new Or(this,t.expression,e)},qr.prototype.interpolate=function(t,e,r){if("constant"!==t.value.kind||"constant"!==e.value.kind)return t;if(void 0===t.value.value||void 0===e.value.value)return new Or(this,{kind:"constant",value:void 0},t.globals);var n=_t[this.specification.type];return n?new Or(this,{kind:"constant",value:n(t.value.value,e.value.value,r)},t.globals):t},qr.prototype.evaluate=function(t,e,r){return"constant"===t.kind?t.value:t.evaluate(e,r)};var Rr=function(t){this.specification=t;};Rr.prototype.possiblyEvaluate=function(t,e){if(void 0!==t.value){if("constant"===t.expression.kind){var r=t.expression.evaluate(e);return this._calculate(r,r,r,e)}return this._calculate(t.expression.evaluate(new Br(Math.floor(e.zoom-1),e)),t.expression.evaluate(new Br(Math.floor(e.zoom),e)),t.expression.evaluate(new Br(Math.floor(e.zoom+1),e)),e)}},Rr.prototype._calculate=function(t,e,r,n){var i=n.zoom,o=i-Math.floor(i),a=n.crossFadingFactor();return i>n.zoomHistory.lastIntegerZoom?{from:t,to:e,fromScale:2,toScale:1,t:o+(1-o)*a}:{from:r,to:e,fromScale:.5,toScale:1,t:1-(1-a)*o}},Rr.prototype.interpolate=function(t){return t};var Ur=function(t){this.specification=t;};Ur.prototype.possiblyEvaluate=function(t,e){return!!t.expression.evaluate(e)},Ur.prototype.interpolate=function(){return!1};var Dr=function(t){for(var e in this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},t){var r=t[e],n=this.defaultPropertyValues[e]=new Cr(r,void 0),i=this.defaultTransitionablePropertyValues[e]=new Ir(r);this.defaultTransitioningPropertyValues[e]=i.untransitioned(),this.defaultPossiblyEvaluatedValues[e]=n.possiblyEvaluate({});}};hr("DataDrivenProperty",qr),hr("DataConstantProperty",jr),hr("CrossFadedProperty",Rr),hr("ColorRampProperty",Ur);var Nr=function(t){function e(e,r){for(var n in t.call(this),this.id=e.id,this.metadata=e.metadata,this.type=e.type,this.minzoom=e.minzoom,this.maxzoom=e.maxzoom,this.visibility="visible","background"!==e.type&&(this.source=e.source,this.sourceLayer=e["source-layer"],this.filter=e.filter),this._featureFilter=function(){return!0},r.layout&&(this._unevaluatedLayout=new Tr(r.layout)),this._transitionablePaint=new Er(r.paint),e.paint)this.setPaintProperty(n,e.paint[n],{validate:!1});for(var i in e.layout)this.setLayoutProperty(i,e.layout[i],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned();}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getLayoutProperty=function(t){return"visibility"===t?this.visibility:this._unevaluatedLayout.getValue(t)},e.prototype.setLayoutProperty=function(t,e,r){if(null!=e){var n="layers."+this.id+".layout."+t;if(this._validate(or,n,t,e,r))return}"visibility"!==t?this._unevaluatedLayout.setValue(t,e):this.visibility="none"===e?e:"visible";},e.prototype.getPaintProperty=function(t){return d(t,"-transition")?this._transitionablePaint.getTransition(t.slice(0,-"-transition".length)):this._transitionablePaint.getValue(t)},e.prototype.setPaintProperty=function(t,e,r){if(null!=e){var n="layers."+this.id+".paint."+t;if(this._validate(ir,n,t,e,r))return}d(t,"-transition")?this._transitionablePaint.setTransition(t.slice(0,-"-transition".length),e||void 0):this._transitionablePaint.setValue(t,e);},e.prototype.isHidden=function(t){return!!(this.minzoom&&t<this.minzoom)||(!!(this.maxzoom&&t>=this.maxzoom)||"none"===this.visibility)},e.prototype.updateTransitions=function(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint);},e.prototype.hasTransition=function(){return this._transitioningPaint.hasTransition()},e.prototype.recalculate=function(t){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t)),this.paint=this._transitioningPaint.possiblyEvaluate(t);},e.prototype.serialize=function(){var t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return"none"===this.visibility&&(t.layout=t.layout||{},t.layout.visibility="none"),m(t,function(t,e){return!(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)})},e.prototype._validate=function(t,e,r,n,i){return(!i||!1!==i.validate)&&ar(this,t.call(rr,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:E,style:{glyphs:!0,sprite:!0}}))},e.prototype.hasOffscreenPass=function(){return!1},e.prototype.resize=function(){},e}(I),Zr={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array},Kr=function(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8;},Jr=function(){this.isTransferred=!1,this.capacity=-1,this.resize(0);};function $r(t,e){void 0===e&&(e=1);var r=0,n=0;return{members:t.map(function(t){var i,o=(i=t.type,Zr[i].BYTES_PER_ELEMENT),a=r=Hr(r,Math.max(e,o)),s=t.components||1;return n=Math.max(n,o),r+=o*s,{name:t.name,type:t.type,components:s,offset:a}}),size:Hr(r,Math.max(n,e)),alignment:e}}function Hr(t,e){return Math.ceil(t/e)*e}Jr.serialize=function(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}},Jr.deserialize=function(t){var e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e},Jr.prototype._trim=function(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews());},Jr.prototype.clear=function(){this.length=0;},Jr.prototype.resize=function(t){this.reserve(t),this.length=t;},Jr.prototype.reserve=function(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);var e=this.uint8;this._refreshViews(),e&&this.uint8.set(e);}},Jr.prototype._refreshViews=function(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")};var Xr=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e){var r=this.length;this.resize(r+1);var n=2*r;return this.int16[n+0]=t,this.int16[n+1]=e,r},e}(Jr);Xr.prototype.bytesPerElement=4,hr("StructArrayLayout2i4",Xr);var Gr=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n){var i=this.length;this.resize(i+1);var o=4*i;return this.int16[o+0]=t,this.int16[o+1]=e,this.int16[o+2]=r,this.int16[o+3]=n,i},e}(Jr);Gr.prototype.bytesPerElement=8,hr("StructArrayLayout4i8",Gr);var Yr=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,o){var a=this.length;this.resize(a+1);var s=6*a;return this.int16[s+0]=t,this.int16[s+1]=e,this.int16[s+2]=r,this.int16[s+3]=n,this.int16[s+4]=i,this.int16[s+5]=o,a},e}(Jr);Yr.prototype.bytesPerElement=12,hr("StructArrayLayout2i4i12",Yr);var Wr=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,o,a,s){var u=this.length;this.resize(u+1);var l=6*u,p=12*u;return this.int16[l+0]=t,this.int16[l+1]=e,this.int16[l+2]=r,this.int16[l+3]=n,this.uint8[p+8]=i,this.uint8[p+9]=o,this.uint8[p+10]=a,this.uint8[p+11]=s,u},e}(Jr);Wr.prototype.bytesPerElement=12,hr("StructArrayLayout4i4ub12",Wr);var Qr=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,o,a,s){var u=this.length;this.resize(u+1);var l=8*u;return this.int16[l+0]=t,this.int16[l+1]=e,this.int16[l+2]=r,this.int16[l+3]=n,this.uint16[l+4]=i,this.uint16[l+5]=o,this.uint16[l+6]=a,this.uint16[l+7]=s,u},e}(Jr);Qr.prototype.bytesPerElement=16,hr("StructArrayLayout4i4ui16",Qr);var tn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;this.resize(n+1);var i=3*n;return this.float32[i+0]=t,this.float32[i+1]=e,this.float32[i+2]=r,n},e}(Jr);tn.prototype.bytesPerElement=12,hr("StructArrayLayout3f12",tn);var en=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t){var e=this.length;this.resize(e+1);var r=1*e;return this.uint32[r+0]=t,e},e}(Jr);en.prototype.bytesPerElement=4,hr("StructArrayLayout1ul4",en);var rn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,o,a,s,u,l,p){var c=this.length;this.resize(c+1);var h=12*c,f=6*c;return this.int16[h+0]=t,this.int16[h+1]=e,this.int16[h+2]=r,this.int16[h+3]=n,this.int16[h+4]=i,this.int16[h+5]=o,this.uint32[f+3]=a,this.uint16[h+8]=s,this.uint16[h+9]=u,this.int16[h+10]=l,this.int16[h+11]=p,c},e}(Jr);rn.prototype.bytesPerElement=24,hr("StructArrayLayout6i1ul2ui2i24",rn);var nn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,o){var a=this.length;this.resize(a+1);var s=6*a;return this.int16[s+0]=t,this.int16[s+1]=e,this.int16[s+2]=r,this.int16[s+3]=n,this.int16[s+4]=i,this.int16[s+5]=o,a},e}(Jr);nn.prototype.bytesPerElement=12,hr("StructArrayLayout2i2i2i12",nn);var on=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e){var r=this.length;this.resize(r+1);var n=4*r;return this.uint8[n+0]=t,this.uint8[n+1]=e,r},e}(Jr);on.prototype.bytesPerElement=4,hr("StructArrayLayout2ub4",on);var an=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,o,a,s,u,l,p,c,h,f){var y=this.length;this.resize(y+1);var d=20*y,v=10*y,m=40*y;return this.int16[d+0]=t,this.int16[d+1]=e,this.uint16[d+2]=r,this.uint16[d+3]=n,this.uint32[v+2]=i,this.uint32[v+3]=o,this.uint32[v+4]=a,this.uint16[d+10]=s,this.uint16[d+11]=u,this.uint16[d+12]=l,this.float32[v+7]=p,this.float32[v+8]=c,this.uint8[m+36]=h,this.uint8[m+37]=f,y},e}(Jr);an.prototype.bytesPerElement=40,hr("StructArrayLayout2i2ui3ul3ui2f2ub40",an);var sn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t){var e=this.length;this.resize(e+1);var r=1*e;return this.float32[r+0]=t,e},e}(Jr);sn.prototype.bytesPerElement=4,hr("StructArrayLayout1f4",sn);var un=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;this.resize(n+1);var i=3*n;return this.int16[i+0]=t,this.int16[i+1]=e,this.int16[i+2]=r,n},e}(Jr);un.prototype.bytesPerElement=6,hr("StructArrayLayout3i6",un);var ln=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;this.resize(n+1);var i=2*n,o=4*n;return this.uint32[i+0]=t,this.uint16[o+2]=e,this.uint16[o+3]=r,n},e}(Jr);ln.prototype.bytesPerElement=8,hr("StructArrayLayout1ul2ui8",ln);var pn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;this.resize(n+1);var i=3*n;return this.uint16[i+0]=t,this.uint16[i+1]=e,this.uint16[i+2]=r,n},e}(Jr);pn.prototype.bytesPerElement=6,hr("StructArrayLayout3ui6",pn);var cn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e){var r=this.length;this.resize(r+1);var n=2*r;return this.uint16[n+0]=t,this.uint16[n+1]=e,r},e}(Jr);cn.prototype.bytesPerElement=4,hr("StructArrayLayout2ui4",cn);var hn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e){var r=this.length;this.resize(r+1);var n=2*r;return this.float32[n+0]=t,this.float32[n+1]=e,r},e}(Jr);hn.prototype.bytesPerElement=8,hr("StructArrayLayout2f8",hn);var fn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n){var i=this.length;this.resize(i+1);var o=4*i;return this.float32[o+0]=t,this.float32[o+1]=e,this.float32[o+2]=r,this.float32[o+3]=n,i},e}(Jr);fn.prototype.bytesPerElement=16,hr("StructArrayLayout4f16",fn);var yn=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={anchorPointX:{configurable:!0},anchorPointY:{configurable:!0},x1:{configurable:!0},y1:{configurable:!0},x2:{configurable:!0},y2:{configurable:!0},featureIndex:{configurable:!0},sourceLayerIndex:{configurable:!0},bucketIndex:{configurable:!0},radius:{configurable:!0},signedDistanceFromAnchor:{configurable:!0},anchorPoint:{configurable:!0}};return r.anchorPointX.get=function(){return this._structArray.int16[this._pos2+0]},r.anchorPointX.set=function(t){this._structArray.int16[this._pos2+0]=t;},r.anchorPointY.get=function(){return this._structArray.int16[this._pos2+1]},r.anchorPointY.set=function(t){this._structArray.int16[this._pos2+1]=t;},r.x1.get=function(){return this._structArray.int16[this._pos2+2]},r.x1.set=function(t){this._structArray.int16[this._pos2+2]=t;},r.y1.get=function(){return this._structArray.int16[this._pos2+3]},r.y1.set=function(t){this._structArray.int16[this._pos2+3]=t;},r.x2.get=function(){return this._structArray.int16[this._pos2+4]},r.x2.set=function(t){this._structArray.int16[this._pos2+4]=t;},r.y2.get=function(){return this._structArray.int16[this._pos2+5]},r.y2.set=function(t){this._structArray.int16[this._pos2+5]=t;},r.featureIndex.get=function(){return this._structArray.uint32[this._pos4+3]},r.featureIndex.set=function(t){this._structArray.uint32[this._pos4+3]=t;},r.sourceLayerIndex.get=function(){return this._structArray.uint16[this._pos2+8]},r.sourceLayerIndex.set=function(t){this._structArray.uint16[this._pos2+8]=t;},r.bucketIndex.get=function(){return this._structArray.uint16[this._pos2+9]},r.bucketIndex.set=function(t){this._structArray.uint16[this._pos2+9]=t;},r.radius.get=function(){return this._structArray.int16[this._pos2+10]},r.radius.set=function(t){this._structArray.int16[this._pos2+10]=t;},r.signedDistanceFromAnchor.get=function(){return this._structArray.int16[this._pos2+11]},r.signedDistanceFromAnchor.set=function(t){this._structArray.int16[this._pos2+11]=t;},r.anchorPoint.get=function(){return new s(this.anchorPointX,this.anchorPointY)},Object.defineProperties(e.prototype,r),e}(Kr);yn.prototype.size=24;var dn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.get=function(t){return new yn(this,t)},e}(rn);hr("CollisionBoxArray",dn);var vn=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={anchorX:{configurable:!0},anchorY:{configurable:!0},glyphStartIndex:{configurable:!0},numGlyphs:{configurable:!0},vertexStartIndex:{configurable:!0},lineStartIndex:{configurable:!0},lineLength:{configurable:!0},segment:{configurable:!0},lowerSize:{configurable:!0},upperSize:{configurable:!0},lineOffsetX:{configurable:!0},lineOffsetY:{configurable:!0},writingMode:{configurable:!0},hidden:{configurable:!0}};return r.anchorX.get=function(){return this._structArray.int16[this._pos2+0]},r.anchorX.set=function(t){this._structArray.int16[this._pos2+0]=t;},r.anchorY.get=function(){return this._structArray.int16[this._pos2+1]},r.anchorY.set=function(t){this._structArray.int16[this._pos2+1]=t;},r.glyphStartIndex.get=function(){return this._structArray.uint16[this._pos2+2]},r.glyphStartIndex.set=function(t){this._structArray.uint16[this._pos2+2]=t;},r.numGlyphs.get=function(){return this._structArray.uint16[this._pos2+3]},r.numGlyphs.set=function(t){this._structArray.uint16[this._pos2+3]=t;},r.vertexStartIndex.get=function(){return this._structArray.uint32[this._pos4+2]},r.vertexStartIndex.set=function(t){this._structArray.uint32[this._pos4+2]=t;},r.lineStartIndex.get=function(){return this._structArray.uint32[this._pos4+3]},r.lineStartIndex.set=function(t){this._structArray.uint32[this._pos4+3]=t;},r.lineLength.get=function(){return this._structArray.uint32[this._pos4+4]},r.lineLength.set=function(t){this._structArray.uint32[this._pos4+4]=t;},r.segment.get=function(){return this._structArray.uint16[this._pos2+10]},r.segment.set=function(t){this._structArray.uint16[this._pos2+10]=t;},r.lowerSize.get=function(){return this._structArray.uint16[this._pos2+11]},r.lowerSize.set=function(t){this._structArray.uint16[this._pos2+11]=t;},r.upperSize.get=function(){return this._structArray.uint16[this._pos2+12]},r.upperSize.set=function(t){this._structArray.uint16[this._pos2+12]=t;},r.lineOffsetX.get=function(){return this._structArray.float32[this._pos4+7]},r.lineOffsetX.set=function(t){this._structArray.float32[this._pos4+7]=t;},r.lineOffsetY.get=function(){return this._structArray.float32[this._pos4+8]},r.lineOffsetY.set=function(t){this._structArray.float32[this._pos4+8]=t;},r.writingMode.get=function(){return this._structArray.uint8[this._pos1+36]},r.writingMode.set=function(t){this._structArray.uint8[this._pos1+36]=t;},r.hidden.get=function(){return this._structArray.uint8[this._pos1+37]},r.hidden.set=function(t){this._structArray.uint8[this._pos1+37]=t;},Object.defineProperties(e.prototype,r),e}(Kr);vn.prototype.size=40;var mn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.get=function(t){return new vn(this,t)},e}(an);hr("PlacedSymbolArray",mn);var gn=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={offsetX:{configurable:!0}};return r.offsetX.get=function(){return this._structArray.float32[this._pos4+0]},r.offsetX.set=function(t){this._structArray.float32[this._pos4+0]=t;},Object.defineProperties(e.prototype,r),e}(Kr);gn.prototype.size=4;var xn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getoffsetX=function(t){return this.float32[1*t+0]},e.prototype.get=function(t){return new gn(this,t)},e}(sn);hr("GlyphOffsetArray",xn);var bn=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={x:{configurable:!0},y:{configurable:!0},tileUnitDistanceFromAnchor:{configurable:!0}};return r.x.get=function(){return this._structArray.int16[this._pos2+0]},r.x.set=function(t){this._structArray.int16[this._pos2+0]=t;},r.y.get=function(){return this._structArray.int16[this._pos2+1]},r.y.set=function(t){this._structArray.int16[this._pos2+1]=t;},r.tileUnitDistanceFromAnchor.get=function(){return this._structArray.int16[this._pos2+2]},r.tileUnitDistanceFromAnchor.set=function(t){this._structArray.int16[this._pos2+2]=t;},Object.defineProperties(e.prototype,r),e}(Kr);bn.prototype.size=6;var wn=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getx=function(t){return this.int16[3*t+0]},e.prototype.gety=function(t){return this.int16[3*t+1]},e.prototype.gettileUnitDistanceFromAnchor=function(t){return this.int16[3*t+2]},e.prototype.get=function(t){return new bn(this,t)},e}(un);hr("SymbolLineVertexArray",wn);var _n=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={featureIndex:{configurable:!0},sourceLayerIndex:{configurable:!0},bucketIndex:{configurable:!0}};return r.featureIndex.get=function(){return this._structArray.uint32[this._pos4+0]},r.featureIndex.set=function(t){this._structArray.uint32[this._pos4+0]=t;},r.sourceLayerIndex.get=function(){return this._structArray.uint16[this._pos2+2]},r.sourceLayerIndex.set=function(t){this._structArray.uint16[this._pos2+2]=t;},r.bucketIndex.get=function(){return this._structArray.uint16[this._pos2+3]},r.bucketIndex.set=function(t){this._structArray.uint16[this._pos2+3]=t;},Object.defineProperties(e.prototype,r),e}(Kr);_n.prototype.size=8;var An=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.get=function(t){return new _n(this,t)},e}(ln);hr("FeatureIndexArray",An);var kn=$r([{name:"a_pos",components:2,type:"Int16"}],4).members,zn=function(t){void 0===t&&(t=[]),this.segments=t;};zn.prototype.prepareSegment=function(t,e,r){var n=this.segments[this.segments.length-1];return t>zn.MAX_VERTEX_ARRAY_LENGTH&&b("Max vertices per segment is "+zn.MAX_VERTEX_ARRAY_LENGTH+": bucket requested "+t),(!n||n.vertexLength+t>zn.MAX_VERTEX_ARRAY_LENGTH)&&(n={vertexOffset:e.length,primitiveOffset:r.length,vertexLength:0,primitiveLength:0},this.segments.push(n)),n},zn.prototype.get=function(){return this.segments},zn.prototype.destroy=function(){for(var t=0,e=this.segments;t<e.length;t+=1){var r=e[t];for(var n in r.vaos)r.vaos[n].destroy();}},zn.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,hr("SegmentVector",zn);var Sn=function(t,e){return 256*(t=c(Math.floor(t),0,255))+(e=c(Math.floor(e),0,255))};function Mn(t){return[Sn(255*t.r,255*t.g),Sn(255*t.b,255*t.a)]}var Vn=function(t,e,r){this.value=t,this.name=e,this.type=r,this.statistics={max:-1/0};};Vn.prototype.defines=function(){return["#define HAS_UNIFORM_u_"+this.name]},Vn.prototype.populatePaintArray=function(){},Vn.prototype.upload=function(){},Vn.prototype.destroy=function(){},Vn.prototype.setUniforms=function(t,e,r,n){var i=n.constantOr(this.value),o=t.gl;"color"===this.type?o.uniform4f(e.uniforms["u_"+this.name],i.r,i.g,i.b,i.a):o.uniform1f(e.uniforms["u_"+this.name],i);};var Bn=function(t,e,r){this.expression=t,this.name=e,this.type=r,this.statistics={max:-1/0};var n="color"===r?hn:sn;this.paintVertexAttributes=[{name:"a_"+e,type:"Float32",components:"color"===r?2:1,offset:0}],this.paintVertexArray=new n;};Bn.prototype.defines=function(){return[]},Bn.prototype.populatePaintArray=function(t,e){var r=this.paintVertexArray,n=r.length;r.reserve(t);var i=this.expression.evaluate(new Br(0),e);if("color"===this.type)for(var o=Mn(i),a=n;a<t;a++)r.emplaceBack(o[0],o[1]);else{for(var s=n;s<t;s++)r.emplaceBack(i);this.statistics.max=Math.max(this.statistics.max,i);}},Bn.prototype.upload=function(t){this.paintVertexArray&&(this.paintVertexBuffer=t.createVertexBuffer(this.paintVertexArray,this.paintVertexAttributes));},Bn.prototype.destroy=function(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy();},Bn.prototype.setUniforms=function(t,e){t.gl.uniform1f(e.uniforms["a_"+this.name+"_t"],0);};var Cn=function(t,e,r,n,i){this.expression=t,this.name=e,this.type=r,this.useIntegerZoom=n,this.zoom=i,this.statistics={max:-1/0};var o="color"===r?fn:hn;this.paintVertexAttributes=[{name:"a_"+e,type:"Float32",components:"color"===r?4:2,offset:0}],this.paintVertexArray=new o;};Cn.prototype.defines=function(){return[]},Cn.prototype.populatePaintArray=function(t,e){var r=this.paintVertexArray,n=r.length;r.reserve(t);var i=this.expression.evaluate(new Br(this.zoom),e),o=this.expression.evaluate(new Br(this.zoom+1),e);if("color"===this.type)for(var a=Mn(i),s=Mn(o),u=n;u<t;u++)r.emplaceBack(a[0],a[1],s[0],s[1]);else{for(var l=n;l<t;l++)r.emplaceBack(i,o);this.statistics.max=Math.max(this.statistics.max,i,o);}},Cn.prototype.upload=function(t){this.paintVertexArray&&(this.paintVertexBuffer=t.createVertexBuffer(this.paintVertexArray,this.paintVertexAttributes));},Cn.prototype.destroy=function(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy();},Cn.prototype.interpolationFactor=function(t){return this.useIntegerZoom?this.expression.interpolationFactor(Math.floor(t),this.zoom,this.zoom+1):this.expression.interpolationFactor(t,this.zoom,this.zoom+1)},Cn.prototype.setUniforms=function(t,e,r){t.gl.uniform1f(e.uniforms["a_"+this.name+"_t"],this.interpolationFactor(r.zoom));};var In=function(){this.binders={},this.cacheKey="",this._buffers=[];};In.createDynamic=function(t,e,r){var n=new In,i=[];for(var o in t.paint._values)if(r(o)){var a=t.paint.get(o);if(a instanceof Or&&a.property.specification["property-function"]){var s=Fn(o,t.type),u=a.property.specification.type,l=a.property.useIntegerZoom;"constant"===a.value.kind?(n.binders[o]=new Vn(a.value,s,u),i.push("/u_"+s)):"source"===a.value.kind?(n.binders[o]=new Bn(a.value,s,u),i.push("/a_"+s)):(n.binders[o]=new Cn(a.value,s,u,l,e),i.push("/z_"+s));}}return n.cacheKey=i.sort().join(""),n},In.prototype.populatePaintArrays=function(t,e){for(var r in this.binders)this.binders[r].populatePaintArray(t,e);},In.prototype.defines=function(){var t=[];for(var e in this.binders)t.push.apply(t,this.binders[e].defines());return t},In.prototype.setUniforms=function(t,e,r,n){for(var i in this.binders){this.binders[i].setUniforms(t,e,n,r.get(i));}},In.prototype.getPaintVertexBuffers=function(){return this._buffers},In.prototype.upload=function(t){for(var e in this.binders)this.binders[e].upload(t);var r=[];for(var n in this.binders){var i=this.binders[n];(i instanceof Bn||i instanceof Cn)&&i.paintVertexBuffer&&r.push(i.paintVertexBuffer);}this._buffers=r;},In.prototype.destroy=function(){for(var t in this.binders)this.binders[t].destroy();};var En=function(t,e,r,n){void 0===n&&(n=function(){return!0}),this.programConfigurations={};for(var i=0,o=e;i<o.length;i+=1){var a=o[i];this.programConfigurations[a.id]=In.createDynamic(a,r,n),this.programConfigurations[a.id].layoutAttributes=t;}};function Fn(t,e){return{"text-opacity":"opacity","icon-opacity":"opacity","text-color":"fill_color","icon-color":"fill_color","text-halo-color":"halo_color","icon-halo-color":"halo_color","text-halo-blur":"halo_blur","icon-halo-blur":"halo_blur","text-halo-width":"halo_width","icon-halo-width":"halo_width","line-gap-width":"gapwidth"}[t]||t.replace(e+"-","").replace(/-/g,"_")}En.prototype.populatePaintArrays=function(t,e){for(var r in this.programConfigurations)this.programConfigurations[r].populatePaintArrays(t,e);},En.prototype.get=function(t){return this.programConfigurations[t]},En.prototype.upload=function(t){for(var e in this.programConfigurations)this.programConfigurations[e].upload(t);},En.prototype.destroy=function(){for(var t in this.programConfigurations)this.programConfigurations[t].destroy();},hr("ConstantBinder",Vn),hr("SourceExpressionBinder",Bn),hr("CompositeExpressionBinder",Cn),hr("ProgramConfiguration",In,{omit:["_buffers"]}),hr("ProgramConfigurationSet",En);var Pn=8192;var Tn,On=(Tn=16,{min:-1*Math.pow(2,Tn-1),max:Math.pow(2,Tn-1)-1});function Ln(t){for(var e=Pn/t.extent,r=t.loadGeometry(),n=0;n<r.length;n++)for(var i=r[n],o=0;o<i.length;o++){var a=i[o];a.x=Math.round(a.x*e),a.y=Math.round(a.y*e),(a.x<On.min||a.x>On.max||a.y<On.min||a.y>On.max)&&b("Geometry exceeds allowed extent, reduce your vector tile buffer size");}return r}function jn(t,e,r,n,i){t.emplaceBack(2*e+(n+1)/2,2*r+(i+1)/2);}var qn=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new Xr,this.indexArray=new pn,this.segments=new zn,this.programConfigurations=new En(kn,t.layers,t.zoom);};function Rn(t,e,r){for(var n=0;n<t.length;n++){var i=t[n];if(Xn(i,e))return!0;if(Jn(e,i,r))return!0}return!1}function Un(t,e){if(1===t.length&&1===t[0].length)return Hn(e,t[0][0]);for(var r=0;r<e.length;r++)for(var n=e[r],i=0;i<n.length;i++)if(Hn(t,n[i]))return!0;for(var o=0;o<t.length;o++){for(var a=t[o],s=0;s<a.length;s++)if(Hn(e,a[s]))return!0;for(var u=0;u<e.length;u++)if(Zn(a,e[u]))return!0}return!1}function Dn(t,e,r){for(var n=0;n<e.length;n++)for(var i=e[n],o=0;o<t.length;o++){var a=t[o];if(a.length>=3)for(var s=0;s<i.length;s++)if(Xn(a,i[s]))return!0;if(Nn(a,i,r))return!0}return!1}function Nn(t,e,r){if(t.length>1){if(Zn(t,e))return!0;for(var n=0;n<e.length;n++)if(Jn(e[n],t,r))return!0}for(var i=0;i<t.length;i++)if(Jn(t[i],e,r))return!0;return!1}function Zn(t,e){if(0===t.length||0===e.length)return!1;for(var r=0;r<t.length-1;r++)for(var n=t[r],i=t[r+1],o=0;o<e.length-1;o++){if(Kn(n,i,e[o],e[o+1]))return!0}return!1}function Kn(t,e,r,n){return w(t,r,n)!==w(e,r,n)&&w(t,e,r)!==w(t,e,n)}function Jn(t,e,r){var n=r*r;if(1===e.length)return t.distSqr(e[0])<n;for(var i=1;i<e.length;i++){if($n(t,e[i-1],e[i])<n)return!0}return!1}function $n(t,e,r){var n=e.distSqr(r);if(0===n)return t.distSqr(e);var i=((t.x-e.x)*(r.x-e.x)+(t.y-e.y)*(r.y-e.y))/n;return i<0?t.distSqr(e):i>1?t.distSqr(r):t.distSqr(r.sub(e)._mult(i)._add(e))}function Hn(t,e){for(var r,n,i,o=!1,a=0;a<t.length;a++)for(var s=0,u=(r=t[a]).length-1;s<r.length;u=s++)n=r[s],i=r[u],n.y>e.y!=i.y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(o=!o);return o}function Xn(t,e){for(var r=!1,n=0,i=t.length-1;n<t.length;i=n++){var o=t[n],a=t[i];o.y>e.y!=a.y>e.y&&e.x<(a.x-o.x)*(e.y-o.y)/(a.y-o.y)+o.x&&(r=!r);}return r}function Gn(t,e,r){var n=e.paint.get(t).value;return"constant"===n.kind?n.value:r.programConfigurations.get(e.id).binders[t].statistics.max}function Yn(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])}function Wn(t,e,r,n,i){if(!e[0]&&!e[1])return t;var o=s.convert(e);"viewport"===r&&o._rotate(-n);for(var a=[],u=0;u<t.length;u++){for(var l=t[u],p=[],c=0;c<l.length;c++)p.push(l[c].sub(o._mult(i)));a.push(p);}return a}qn.prototype.populate=function(t,e){for(var r=0,n=t;r<n.length;r+=1){var i=n[r],o=i.feature,a=i.index,s=i.sourceLayerIndex;if(this.layers[0]._featureFilter(new Br(this.zoom),o)){var u=Ln(o);this.addFeature(o,u),e.featureIndex.insert(o,u,a,s,this.index);}}},qn.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},qn.prototype.upload=function(t){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,kn),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.programConfigurations.upload(t);},qn.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());},qn.prototype.addFeature=function(t,e){for(var r=0,n=e;r<n.length;r+=1)for(var i=0,o=n[r];i<o.length;i+=1){var a=o[i],s=a.x,u=a.y;if(!(s<0||s>=Pn||u<0||u>=Pn)){var l=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray),p=l.vertexLength;jn(this.layoutVertexArray,s,u,-1,-1),jn(this.layoutVertexArray,s,u,1,-1),jn(this.layoutVertexArray,s,u,1,1),jn(this.layoutVertexArray,s,u,-1,1),this.indexArray.emplaceBack(p,p+1,p+2),this.indexArray.emplaceBack(p,p+3,p+2),l.vertexLength+=4,l.primitiveLength+=2;}}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t);},hr("CircleBucket",qn,{omit:["layers"]});var Qn={paint:new Dr({"circle-radius":new qr(E.paint_circle["circle-radius"]),"circle-color":new qr(E.paint_circle["circle-color"]),"circle-blur":new qr(E.paint_circle["circle-blur"]),"circle-opacity":new qr(E.paint_circle["circle-opacity"]),"circle-translate":new jr(E.paint_circle["circle-translate"]),"circle-translate-anchor":new jr(E.paint_circle["circle-translate-anchor"]),"circle-pitch-scale":new jr(E.paint_circle["circle-pitch-scale"]),"circle-pitch-alignment":new jr(E.paint_circle["circle-pitch-alignment"]),"circle-stroke-width":new qr(E.paint_circle["circle-stroke-width"]),"circle-stroke-color":new qr(E.paint_circle["circle-stroke-color"]),"circle-stroke-opacity":new qr(E.paint_circle["circle-stroke-opacity"])})},ti=n(function(t,e){var r;t.exports=((r=new Float32Array(3))[0]=0,r[1]=0,r[2]=0,function(){var t=new Float32Array(4);t[0]=0,t[1]=0,t[2]=0,t[3]=0;}(),{vec3:{transformMat3:function(t,e,r){var n=e[0],i=e[1],o=e[2];return t[0]=n*r[0]+i*r[3]+o*r[6],t[1]=n*r[1]+i*r[4]+o*r[7],t[2]=n*r[2]+i*r[5]+o*r[8],t}},vec4:{transformMat4:function(t,e,r){var n=e[0],i=e[1],o=e[2],a=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*o+r[12]*a,t[1]=r[1]*n+r[5]*i+r[9]*o+r[13]*a,t[2]=r[2]*n+r[6]*i+r[10]*o+r[14]*a,t[3]=r[3]*n+r[7]*i+r[11]*o+r[15]*a,t}},mat2:{create:function(){var t=new Float32Array(4);return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t},rotate:function(t,e,r){var n=e[0],i=e[1],o=e[2],a=e[3],s=Math.sin(r),u=Math.cos(r);return t[0]=n*u+o*s,t[1]=i*u+a*s,t[2]=n*-s+o*u,t[3]=i*-s+a*u,t},scale:function(t,e,r){var n=e[0],i=e[1],o=e[2],a=e[3],s=r[0],u=r[1];return t[0]=n*s,t[1]=i*s,t[2]=o*u,t[3]=a*u,t}},mat3:{create:function(){var t=new Float32Array(9);return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t},fromRotation:function(t,e){var r=Math.sin(e),n=Math.cos(e);return t[0]=n,t[1]=r,t[2]=0,t[3]=-r,t[4]=n,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t}},mat4:{create:function(){var t=new Float32Array(16);return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},identity:function(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},translate:function(t,e,r){var n,i,o,a,s,u,l,p,c,h,f,y,d=r[0],v=r[1],m=r[2];return e===t?(t[12]=e[0]*d+e[4]*v+e[8]*m+e[12],t[13]=e[1]*d+e[5]*v+e[9]*m+e[13],t[14]=e[2]*d+e[6]*v+e[10]*m+e[14],t[15]=e[3]*d+e[7]*v+e[11]*m+e[15]):(n=e[0],i=e[1],o=e[2],a=e[3],s=e[4],u=e[5],l=e[6],p=e[7],c=e[8],h=e[9],f=e[10],y=e[11],t[0]=n,t[1]=i,t[2]=o,t[3]=a,t[4]=s,t[5]=u,t[6]=l,t[7]=p,t[8]=c,t[9]=h,t[10]=f,t[11]=y,t[12]=n*d+s*v+c*m+e[12],t[13]=i*d+u*v+h*m+e[13],t[14]=o*d+l*v+f*m+e[14],t[15]=a*d+p*v+y*m+e[15]),t},scale:function(t,e,r){var n=r[0],i=r[1],o=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*o,t[9]=e[9]*o,t[10]=e[10]*o,t[11]=e[11]*o,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},multiply:function(t,e,r){var n=e[0],i=e[1],o=e[2],a=e[3],s=e[4],u=e[5],l=e[6],p=e[7],c=e[8],h=e[9],f=e[10],y=e[11],d=e[12],v=e[13],m=e[14],g=e[15],x=r[0],b=r[1],w=r[2],_=r[3];return t[0]=x*n+b*s+w*c+_*d,t[1]=x*i+b*u+w*h+_*v,t[2]=x*o+b*l+w*f+_*m,t[3]=x*a+b*p+w*y+_*g,x=r[4],b=r[5],w=r[6],_=r[7],t[4]=x*n+b*s+w*c+_*d,t[5]=x*i+b*u+w*h+_*v,t[6]=x*o+b*l+w*f+_*m,t[7]=x*a+b*p+w*y+_*g,x=r[8],b=r[9],w=r[10],_=r[11],t[8]=x*n+b*s+w*c+_*d,t[9]=x*i+b*u+w*h+_*v,t[10]=x*o+b*l+w*f+_*m,t[11]=x*a+b*p+w*y+_*g,x=r[12],b=r[13],w=r[14],_=r[15],t[12]=x*n+b*s+w*c+_*d,t[13]=x*i+b*u+w*h+_*v,t[14]=x*o+b*l+w*f+_*m,t[15]=x*a+b*p+w*y+_*g,t},perspective:function(t,e,r,n,i){var o=1/Math.tan(e/2),a=1/(n-i);return t[0]=o/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=o,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=(i+n)*a,t[11]=-1,t[12]=0,t[13]=0,t[14]=2*i*n*a,t[15]=0,t},rotateX:function(t,e,r){var n=Math.sin(r),i=Math.cos(r),o=e[4],a=e[5],s=e[6],u=e[7],l=e[8],p=e[9],c=e[10],h=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=o*i+l*n,t[5]=a*i+p*n,t[6]=s*i+c*n,t[7]=u*i+h*n,t[8]=l*i-o*n,t[9]=p*i-a*n,t[10]=c*i-s*n,t[11]=h*i-u*n,t},rotateZ:function(t,e,r){var n=Math.sin(r),i=Math.cos(r),o=e[0],a=e[1],s=e[2],u=e[3],l=e[4],p=e[5],c=e[6],h=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=o*i+l*n,t[1]=a*i+p*n,t[2]=s*i+c*n,t[3]=u*i+h*n,t[4]=l*i-o*n,t[5]=p*i-a*n,t[6]=c*i-s*n,t[7]=h*i-u*n,t},invert:function(t,e){var r=e[0],n=e[1],i=e[2],o=e[3],a=e[4],s=e[5],u=e[6],l=e[7],p=e[8],c=e[9],h=e[10],f=e[11],y=e[12],d=e[13],v=e[14],m=e[15],g=r*s-n*a,x=r*u-i*a,b=r*l-o*a,w=n*u-i*s,_=n*l-o*s,A=i*l-o*u,k=p*d-c*y,z=p*v-h*y,S=p*m-f*y,M=c*v-h*d,V=c*m-f*d,B=h*m-f*v,C=g*B-x*V+b*M+w*S-_*z+A*k;return C?(C=1/C,t[0]=(s*B-u*V+l*M)*C,t[1]=(i*V-n*B-o*M)*C,t[2]=(d*A-v*_+m*w)*C,t[3]=(h*_-c*A-f*w)*C,t[4]=(u*S-a*B-l*z)*C,t[5]=(r*B-i*S+o*z)*C,t[6]=(v*b-y*A-m*x)*C,t[7]=(p*A-h*b+f*x)*C,t[8]=(a*V-s*S+l*k)*C,t[9]=(n*S-r*V-o*k)*C,t[10]=(y*_-d*b+m*g)*C,t[11]=(c*b-p*_-f*g)*C,t[12]=(s*z-a*M-u*k)*C,t[13]=(r*M-n*z+i*k)*C,t[14]=(d*x-y*w-v*g)*C,t[15]=(p*w-c*x+h*g)*C,t):null},ortho:function(t,e,r,n,i,o,a){var s=1/(e-r),u=1/(n-i),l=1/(o-a);return t[0]=-2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*u,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*l,t[11]=0,t[12]=(e+r)*s,t[13]=(i+n)*u,t[14]=(a+o)*l,t[15]=1,t}}});}),ei=(ti.vec3,ti.vec4),ri=(ti.mat2,ti.mat3,ti.mat4),ni=function(t){function e(e){t.call(this,e,Qn);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new qn(t)},e.prototype.queryRadius=function(t){var e=t;return Gn("circle-radius",this,e)+Gn("circle-stroke-width",this,e)+Yn(this.paint.get("circle-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,o,a){for(var s=Wn(t,this.paint.get("circle-translate"),this.paint.get("circle-translate-anchor"),i.angle,o),u=this.paint.get("circle-radius").evaluate(e)+this.paint.get("circle-stroke-width").evaluate(e),l="map"===this.paint.get("circle-pitch-alignment"),p=l?s:function(t,e,r){return t.map(function(t){return t.map(function(t){return ii(t,e,r)})})}(s,a,i),c=l?u*o:u,h=0,f=r;h<f.length;h+=1)for(var y=0,d=f[h];y<d.length;y+=1){var v=d[y],m=l?v:ii(v,a,i),g=c,x=ei.transformMat4([],[v.x,v.y,0,1],a);if("viewport"===this.paint.get("circle-pitch-scale")&&"map"===this.paint.get("circle-pitch-alignment")?g*=x[3]/i.cameraToCenterDistance:"map"===this.paint.get("circle-pitch-scale")&&"viewport"===this.paint.get("circle-pitch-alignment")&&(g*=i.cameraToCenterDistance/x[3]),Rn(p,m,g))return!0}return!1},e}(Nr);function ii(t,e,r){var n=ei.transformMat4([],[t.x,t.y,0,1],e);return new s((n[0]/n[3]+1)*r.width*.5,(n[1]/n[3]+1)*r.height*.5)}var oi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(qn);function ai(t,e,r,n){var i=e.width,o=e.height;if(n){if(n.length!==i*o*r)throw new RangeError("mismatched image size")}else n=new Uint8Array(i*o*r);return t.width=i,t.height=o,t.data=n,t}function si(t,e,r){var n=e.width,i=e.height;if(n!==t.width||i!==t.height){var o=ai({},{width:n,height:i},r);ui(t,o,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,n),height:Math.min(t.height,i)},r),t.width=n,t.height=i,t.data=o.data;}}function ui(t,e,r,n,i,o){if(0===i.width||0===i.height)return e;if(i.width>t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");for(var a=t.data,s=e.data,u=0;u<i.height;u++)for(var l=((r.y+u)*t.width+r.x)*o,p=((n.y+u)*e.width+n.x)*o,c=0;c<i.width*o;c++)s[p+c]=a[l+c];return e}hr("HeatmapBucket",oi,{omit:["layers"]});var li=function(t,e){ai(this,t,1,e);};li.prototype.resize=function(t){si(this,t,1);},li.prototype.clone=function(){return new li({width:this.width,height:this.height},new Uint8Array(this.data))},li.copy=function(t,e,r,n,i){ui(t,e,r,n,i,1);};var pi=function(t,e){ai(this,t,4,e);};pi.prototype.resize=function(t){si(this,t,4);},pi.prototype.clone=function(){return new pi({width:this.width,height:this.height},new Uint8Array(this.data))},pi.copy=function(t,e,r,n,i){ui(t,e,r,n,i,4);},hr("AlphaImage",li),hr("RGBAImage",pi);var ci={paint:new Dr({"heatmap-radius":new qr(E.paint_heatmap["heatmap-radius"]),"heatmap-weight":new qr(E.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new jr(E.paint_heatmap["heatmap-intensity"]),"heatmap-color":new Ur(E.paint_heatmap["heatmap-color"]),"heatmap-opacity":new jr(E.paint_heatmap["heatmap-opacity"])})};function hi(t,e){for(var r=new Uint8Array(1024),n={},i=0,o=0;i<256;i++,o+=4){n[e]=i/255;var a=t.evaluate(n);r[o+0]=Math.floor(255*a.r/a.a),r[o+1]=Math.floor(255*a.g/a.a),r[o+2]=Math.floor(255*a.b/a.a),r[o+3]=Math.floor(255*a.a);}return new pi({width:256,height:1},r)}var fi=function(t){function e(e){t.call(this,e,ci),this._updateColorRamp();}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new oi(t)},e.prototype.setPaintProperty=function(e,r,n){t.prototype.setPaintProperty.call(this,e,r,n),"heatmap-color"===e&&this._updateColorRamp();},e.prototype._updateColorRamp=function(){var t=this._transitionablePaint._values["heatmap-color"].value.expression;this.colorRamp=hi(t,"heatmapDensity"),this.colorRampTexture=null;},e.prototype.resize=function(){this.heatmapFbo&&(this.heatmapFbo.destroy(),this.heatmapFbo=null);},e.prototype.queryRadius=function(){return 0},e.prototype.queryIntersectsFeature=function(){return!1},e.prototype.hasOffscreenPass=function(){return 0!==this.paint.get("heatmap-opacity")&&"none"!==this.visibility},e}(Nr),yi={paint:new Dr({"hillshade-illumination-direction":new jr(E.paint_hillshade["hillshade-illumination-direction"]),"hillshade-illumination-anchor":new jr(E.paint_hillshade["hillshade-illumination-anchor"]),"hillshade-exaggeration":new jr(E.paint_hillshade["hillshade-exaggeration"]),"hillshade-shadow-color":new jr(E.paint_hillshade["hillshade-shadow-color"]),"hillshade-highlight-color":new jr(E.paint_hillshade["hillshade-highlight-color"]),"hillshade-accent-color":new jr(E.paint_hillshade["hillshade-accent-color"])})},di=function(t){function e(e){t.call(this,e,yi);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.hasOffscreenPass=function(){return 0!==this.paint.get("hillshade-exaggeration")&&"none"!==this.visibility},e}(Nr),vi=$r([{name:"a_pos",components:2,type:"Int16"}],4).members,mi=xi,gi=xi;function xi(t,e,r){r=r||2;var n,i,o,a,s,u,l,p=e&&e.length,c=p?e[0]*r:t.length,h=bi(t,0,c,r,!0),f=[];if(!h)return f;if(p&&(h=function(t,e,r,n){var i,o,a,s,u,l=[];for(i=0,o=e.length;i<o;i++)a=e[i]*n,s=i<o-1?e[i+1]*n:t.length,(u=bi(t,a,s,n,!1))===u.next&&(u.steiner=!0),l.push(Ci(u));for(l.sort(Mi),i=0;i<l.length;i++)Vi(l[i],r),r=wi(r,r.next);return r}(t,e,h,r)),t.length>80*r){n=o=t[0],i=a=t[1];for(var y=r;y<c;y+=r)(s=t[y])<n&&(n=s),(u=t[y+1])<i&&(i=u),s>o&&(o=s),u>a&&(a=u);l=0!==(l=Math.max(o-n,a-i))?1/l:0;}return _i(h,f,r,n,i,l),f}function bi(t,e,r,n,i){var o,a;if(i===Ui(t,e,r,n)>0)for(o=e;o<r;o+=n)a=ji(o,t[o],t[o+1],a);else for(o=r-n;o>=e;o-=n)a=ji(o,t[o],t[o+1],a);return a&&Pi(a,a.next)&&(qi(a),a=a.next),a}function wi(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!Pi(n,n.next)&&0!==Fi(n.prev,n,n.next))n=n.next;else{if(qi(n),(n=e=n.prev)===n.next)break;r=!0;}}while(r||n!==e);return e}function _i(t,e,r,n,i,o,a){if(t){!a&&o&&function(t,e,r,n){var i=t;do{null===i.z&&(i.z=Bi(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,r,n,i,o,a,s,u,l=1;do{for(r=t,t=null,o=null,a=0;r;){for(a++,n=r,s=0,e=0;e<l&&(s++,n=n.nextZ);e++);for(u=l;s>0||u>0&&n;)0!==s&&(0===u||!n||r.z<=n.z)?(i=r,r=r.nextZ,s--):(i=n,n=n.nextZ,u--),o?o.nextZ=i:t=i,i.prevZ=o,o=i;r=n;}o.nextZ=null,l*=2;}while(a>1)}(i);}(t,n,i,o);for(var s,u,l=t;t.prev!==t.next;)if(s=t.prev,u=t.next,o?ki(t,n,i,o):Ai(t))e.push(s.i/r),e.push(t.i/r),e.push(u.i/r),qi(t),t=u.next,l=u.next;else if((t=u)===l){a?1===a?_i(t=zi(t,e,r),e,r,n,i,o,2):2===a&&Si(t,e,r,n,i,o):_i(wi(t),e,r,n,i,o,1);break}}}function Ai(t){var e=t.prev,r=t,n=t.next;if(Fi(e,r,n)>=0)return!1;for(var i=t.next.next;i!==t.prev;){if(Ii(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&Fi(i.prev,i,i.next)>=0)return!1;i=i.next;}return!0}function ki(t,e,r,n){var i=t.prev,o=t,a=t.next;if(Fi(i,o,a)>=0)return!1;for(var s=i.x<o.x?i.x<a.x?i.x:a.x:o.x<a.x?o.x:a.x,u=i.y<o.y?i.y<a.y?i.y:a.y:o.y<a.y?o.y:a.y,l=i.x>o.x?i.x>a.x?i.x:a.x:o.x>a.x?o.x:a.x,p=i.y>o.y?i.y>a.y?i.y:a.y:o.y>a.y?o.y:a.y,c=Bi(s,u,e,r,n),h=Bi(l,p,e,r,n),f=t.prevZ,y=t.nextZ;f&&f.z>=c&&y&&y.z<=h;){if(f!==t.prev&&f!==t.next&&Ii(i.x,i.y,o.x,o.y,a.x,a.y,f.x,f.y)&&Fi(f.prev,f,f.next)>=0)return!1;if(f=f.prevZ,y!==t.prev&&y!==t.next&&Ii(i.x,i.y,o.x,o.y,a.x,a.y,y.x,y.y)&&Fi(y.prev,y,y.next)>=0)return!1;y=y.nextZ;}for(;f&&f.z>=c;){if(f!==t.prev&&f!==t.next&&Ii(i.x,i.y,o.x,o.y,a.x,a.y,f.x,f.y)&&Fi(f.prev,f,f.next)>=0)return!1;f=f.prevZ;}for(;y&&y.z<=h;){if(y!==t.prev&&y!==t.next&&Ii(i.x,i.y,o.x,o.y,a.x,a.y,y.x,y.y)&&Fi(y.prev,y,y.next)>=0)return!1;y=y.nextZ;}return!0}function zi(t,e,r){var n=t;do{var i=n.prev,o=n.next.next;!Pi(i,o)&&Ti(i,n,n.next,o)&&Oi(i,o)&&Oi(o,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(o.i/r),qi(n),qi(n.next),n=t=o),n=n.next;}while(n!==t);return n}function Si(t,e,r,n,i,o){var a=t;do{for(var s=a.next.next;s!==a.prev;){if(a.i!==s.i&&Ei(a,s)){var u=Li(a,s);return a=wi(a,a.next),u=wi(u,u.next),_i(a,e,r,n,i,o),void _i(u,e,r,n,i,o)}s=s.next;}a=a.next;}while(a!==t)}function Mi(t,e){return t.x-e.x}function Vi(t,e){if(e=function(t,e){var r,n=e,i=t.x,o=t.y,a=-1/0;do{if(o<=n.y&&o>=n.next.y&&n.next.y!==n.y){var s=n.x+(o-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(s<=i&&s>a){if(a=s,s===i){if(o===n.y)return n;if(o===n.next.y)return n.next}r=n.x<n.next.x?n:n.next;}}n=n.next;}while(n!==e);if(!r)return null;if(i===a)return r.prev;var u,l=r,p=r.x,c=r.y,h=1/0;n=r.next;for(;n!==l;)i>=n.x&&n.x>=p&&i!==n.x&&Ii(o<c?i:a,o,p,c,o<c?a:i,o,n.x,n.y)&&((u=Math.abs(o-n.y)/(i-n.x))<h||u===h&&n.x>r.x)&&Oi(n,t)&&(r=n,h=u),n=n.next;return r}(t,e)){var r=Li(e,t);wi(r,r.next);}}function Bi(t,e,r,n,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*i)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*i)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function Ci(t){var e=t,r=t;do{e.x<r.x&&(r=e),e=e.next;}while(e!==t);return r}function Ii(t,e,r,n,i,o,a,s){return(i-a)*(e-s)-(t-a)*(o-s)>=0&&(t-a)*(n-s)-(r-a)*(e-s)>=0&&(r-a)*(o-s)-(i-a)*(n-s)>=0}function Ei(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&Ti(r,r.next,t,e))return!0;r=r.next;}while(r!==t);return!1}(t,e)&&Oi(t,e)&&Oi(e,t)&&function(t,e){var r=t,n=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;do{r.y>o!=r.next.y>o&&r.next.y!==r.y&&i<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;}while(r!==t);return n}(t,e)}function Fi(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function Pi(t,e){return t.x===e.x&&t.y===e.y}function Ti(t,e,r,n){return!!(Pi(t,e)&&Pi(r,n)||Pi(t,n)&&Pi(r,e))||Fi(t,e,r)>0!=Fi(t,e,n)>0&&Fi(r,n,t)>0!=Fi(r,n,e)>0}function Oi(t,e){return Fi(t.prev,t,t.next)<0?Fi(t,e,t.next)>=0&&Fi(t,t.prev,e)>=0:Fi(t,e,t.prev)<0||Fi(t,t.next,e)<0}function Li(t,e){var r=new Ri(t.i,t.x,t.y),n=new Ri(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,o.next=n,n.prev=o,n}function ji(t,e,r,n){var i=new Ri(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function qi(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ);}function Ri(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1;}function Ui(t,e,r,n){for(var i=0,o=e,a=r-n;o<r;o+=n)i+=(t[a]-t[o])*(t[o+1]+t[a+1]),a=o;return i}xi.deviation=function(t,e,r,n){var i=e&&e.length,o=i?e[0]*r:t.length,a=Math.abs(Ui(t,0,o,r));if(i)for(var s=0,u=e.length;s<u;s++){var l=e[s]*r,p=s<u-1?e[s+1]*r:t.length;a-=Math.abs(Ui(t,l,p,r));}var c=0;for(s=0;s<n.length;s+=3){var h=n[s]*r,f=n[s+1]*r,y=n[s+2]*r;c+=Math.abs((t[h]-t[y])*(t[f+1]-t[h+1])-(t[h]-t[f])*(t[y+1]-t[h+1]));}return 0===a&&0===c?0:Math.abs((c-a)/a)},xi.flatten=function(t){for(var e=t[0][0].length,r={vertices:[],holes:[],dimensions:e},n=0,i=0;i<t.length;i++){for(var o=0;o<t[i].length;o++)for(var a=0;a<e;a++)r.vertices.push(t[i][o][a]);i>0&&(n+=t[i-1].length,r.holes.push(n));}return r},mi.default=gi;var Di=Zi,Ni=Zi;function Zi(t,e,r,n,i){!function t(e,r,n,i,o){for(;i>n;){if(i-n>600){var a=i-n+1,s=r-n+1,u=Math.log(a),l=.5*Math.exp(2*u/3),p=.5*Math.sqrt(u*l*(a-l)/a)*(s-a/2<0?-1:1),c=Math.max(n,Math.floor(r-s*l/a+p)),h=Math.min(i,Math.floor(r+(a-s)*l/a+p));t(e,r,c,h,o);}var f=e[r],y=n,d=i;for(Ki(e,n,r),o(e[i],f)>0&&Ki(e,n,i);y<d;){for(Ki(e,y,d),y++,d--;o(e[y],f)<0;)y++;for(;o(e[d],f)>0;)d--;}0===o(e[n],f)?Ki(e,n,d):Ki(e,++d,i),d<=r&&(n=d+1),r<=d&&(i=d-1);}}(t,e,r||0,n||t.length-1,i||Ji);}function Ki(t,e,r){var n=t[e];t[e]=t[r],t[r]=n;}function Ji(t,e){return t<e?-1:t>e?1:0}function $i(t,e){var r=t.length;if(r<=1)return[t];for(var n,i,o=[],a=0;a<r;a++){var s=_(t[a]);0!==s&&(t[a].area=Math.abs(s),void 0===i&&(i=s<0),i===s<0?(n&&o.push(n),n=[t[a]]):n.push(t[a]));}if(n&&o.push(n),e>1)for(var u=0;u<o.length;u++)o[u].length<=e||(Di(o[u],e,1,o[u].length-1,Hi),o[u]=o[u].slice(0,e));return o}function Hi(t,e){return e.area-t.area}Di.default=Ni;var Xi=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new Xr,this.indexArray=new pn,this.indexArray2=new cn,this.programConfigurations=new En(vi,t.layers,t.zoom),this.segments=new zn,this.segments2=new zn;};Xi.prototype.populate=function(t,e){for(var r=0,n=t;r<n.length;r+=1){var i=n[r],o=i.feature,a=i.index,s=i.sourceLayerIndex;if(this.layers[0]._featureFilter(new Br(this.zoom),o)){var u=Ln(o);this.addFeature(o,u),e.featureIndex.insert(o,u,a,s,this.index);}}},Xi.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},Xi.prototype.upload=function(t){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,vi),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.indexBuffer2=t.createIndexBuffer(this.indexArray2),this.programConfigurations.upload(t);},Xi.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy());},Xi.prototype.addFeature=function(t,e){for(var r=0,n=$i(e,500);r<n.length;r+=1){for(var i=n[r],o=0,a=0,s=i;a<s.length;a+=1){o+=s[a].length;}for(var u=this.segments.prepareSegment(o,this.layoutVertexArray,this.indexArray),l=u.vertexLength,p=[],c=[],h=0,f=i;h<f.length;h+=1){var y=f[h];if(0!==y.length){y!==i[0]&&c.push(p.length/2);var d=this.segments2.prepareSegment(y.length,this.layoutVertexArray,this.indexArray2),v=d.vertexLength;this.layoutVertexArray.emplaceBack(y[0].x,y[0].y),this.indexArray2.emplaceBack(v+y.length-1,v),p.push(y[0].x),p.push(y[0].y);for(var m=1;m<y.length;m++)this.layoutVertexArray.emplaceBack(y[m].x,y[m].y),this.indexArray2.emplaceBack(v+m-1,v+m),p.push(y[m].x),p.push(y[m].y);d.vertexLength+=y.length,d.primitiveLength+=y.length;}}for(var g=mi(p,c),x=0;x<g.length;x+=3)this.indexArray.emplaceBack(l+g[x],l+g[x+1],l+g[x+2]);u.vertexLength+=o,u.primitiveLength+=g.length/3;}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t);},hr("FillBucket",Xi,{omit:["layers"]});var Gi={paint:new Dr({"fill-antialias":new jr(E.paint_fill["fill-antialias"]),"fill-opacity":new qr(E.paint_fill["fill-opacity"]),"fill-color":new qr(E.paint_fill["fill-color"]),"fill-outline-color":new qr(E.paint_fill["fill-outline-color"]),"fill-translate":new jr(E.paint_fill["fill-translate"]),"fill-translate-anchor":new jr(E.paint_fill["fill-translate-anchor"]),"fill-pattern":new Rr(E.paint_fill["fill-pattern"])})},Yi=function(t){function e(e){t.call(this,e,Gi);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.recalculate=function(t){this.paint=this._transitioningPaint.possiblyEvaluate(t);var e=this.paint._values["fill-outline-color"];"constant"===e.value.kind&&void 0===e.value.value&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"]);},e.prototype.createBucket=function(t){return new Xi(t)},e.prototype.queryRadius=function(){return Yn(this.paint.get("fill-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,o){return Un(Wn(t,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),i.angle,o),r)},e}(Nr),Wi=$r([{name:"a_pos",components:2,type:"Int16"},{name:"a_normal_ed",components:4,type:"Int16"}],4).members,Qi=Math.pow(2,13);function to(t,e,r,n,i,o,a,s){t.emplaceBack(e,r,2*Math.floor(n*Qi)+a,i*Qi*2,o*Qi*2,Math.round(s));}var eo=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new Yr,this.indexArray=new pn,this.programConfigurations=new En(Wi,t.layers,t.zoom),this.segments=new zn;};function ro(t,e){return t.x===e.x&&(t.x<0||t.x>Pn)||t.y===e.y&&(t.y<0||t.y>Pn)}function no(t){return t.every(function(t){return t.x<0})||t.every(function(t){return t.x>Pn})||t.every(function(t){return t.y<0})||t.every(function(t){return t.y>Pn})}eo.prototype.populate=function(t,e){for(var r=0,n=t;r<n.length;r+=1){var i=n[r],o=i.feature,a=i.index,s=i.sourceLayerIndex;if(this.layers[0]._featureFilter(new Br(this.zoom),o)){var u=Ln(o);this.addFeature(o,u),e.featureIndex.insert(o,u,a,s,this.index);}}},eo.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},eo.prototype.upload=function(t){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Wi),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.programConfigurations.upload(t);},eo.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());},eo.prototype.addFeature=function(t,e){for(var r=0,n=$i(e,500);r<n.length;r+=1){for(var i=n[r],o=0,a=0,s=i;a<s.length;a+=1){o+=s[a].length;}for(var u=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray),l=0,p=i;l<p.length;l+=1){var c=p[l];if(0!==c.length&&!no(c))for(var h=0,f=0;f<c.length;f++){var y=c[f];if(f>=1){var d=c[f-1];if(!ro(y,d)){u.vertexLength+4>zn.MAX_VERTEX_ARRAY_LENGTH&&(u=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));var v=y.sub(d)._perp()._unit(),m=d.dist(y);h+m>32768&&(h=0),to(this.layoutVertexArray,y.x,y.y,v.x,v.y,0,0,h),to(this.layoutVertexArray,y.x,y.y,v.x,v.y,0,1,h),h+=m,to(this.layoutVertexArray,d.x,d.y,v.x,v.y,0,0,h),to(this.layoutVertexArray,d.x,d.y,v.x,v.y,0,1,h);var g=u.vertexLength;this.indexArray.emplaceBack(g,g+1,g+2),this.indexArray.emplaceBack(g+1,g+2,g+3),u.vertexLength+=4,u.primitiveLength+=2;}}}}u.vertexLength+o>zn.MAX_VERTEX_ARRAY_LENGTH&&(u=this.segments.prepareSegment(o,this.layoutVertexArray,this.indexArray));for(var x=[],b=[],w=u.vertexLength,_=0,A=i;_<A.length;_+=1){var k=A[_];if(0!==k.length){k!==i[0]&&b.push(x.length/2);for(var z=0;z<k.length;z++){var S=k[z];to(this.layoutVertexArray,S.x,S.y,0,0,1,1,0),x.push(S.x),x.push(S.y);}}}for(var M=mi(x,b),V=0;V<M.length;V+=3)this.indexArray.emplaceBack(w+M[V],w+M[V+1],w+M[V+2]);u.primitiveLength+=M.length/3,u.vertexLength+=o;}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t);},hr("FillExtrusionBucket",eo,{omit:["layers"]});var io={paint:new Dr({"fill-extrusion-opacity":new jr(E["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new qr(E["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new jr(E["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new jr(E["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new Rr(E["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new qr(E["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new qr(E["paint_fill-extrusion"]["fill-extrusion-base"])})},oo=function(t){function e(e){t.call(this,e,io);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new eo(t)},e.prototype.queryRadius=function(){return Yn(this.paint.get("fill-extrusion-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,o){return Un(Wn(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),i.angle,o),r)},e.prototype.hasOffscreenPass=function(){return 0!==this.paint.get("fill-extrusion-opacity")&&"none"!==this.visibility},e.prototype.resize=function(){this.viewportFrame&&(this.viewportFrame.destroy(),this.viewportFrame=null);},e}(Nr),ao=$r([{name:"a_pos_normal",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint8"}],4).members,so=uo;function uo(t,e,r,n,i){this.properties={},this.extent=r,this.type=0,this._pbf=t,this._geometry=-1,this._keys=n,this._values=i,t.readFields(lo,this,e);}function lo(t,e,r){1==t?e.id=r.readVarint():2==t?function(t,e){var r=t.readVarint()+t.pos;for(;t.pos<r;){var n=e._keys[t.readVarint()],i=e._values[t.readVarint()];e.properties[n]=i;}}(r,e):3==t?e.type=r.readVarint():4==t&&(e._geometry=r.pos);}function po(t){for(var e,r,n=0,i=0,o=t.length,a=o-1;i<o;a=i++)e=t[i],n+=((r=t[a]).x-e.x)*(e.y+r.y);return n}uo.types=["Unknown","Point","LineString","Polygon"],uo.prototype.loadGeometry=function(){var t=this._pbf;t.pos=this._geometry;for(var e,r=t.readVarint()+t.pos,n=1,i=0,o=0,a=0,u=[];t.pos<r;){if(i<=0){var l=t.readVarint();n=7&l,i=l>>3;}if(i--,1===n||2===n)o+=t.readSVarint(),a+=t.readSVarint(),1===n&&(e&&u.push(e),e=[]),e.push(new s(o,a));else{if(7!==n)throw new Error("unknown command "+n);e&&e.push(e[0].clone());}}return e&&u.push(e),u},uo.prototype.bbox=function(){var t=this._pbf;t.pos=this._geometry;for(var e=t.readVarint()+t.pos,r=1,n=0,i=0,o=0,a=1/0,s=-1/0,u=1/0,l=-1/0;t.pos<e;){if(n<=0){var p=t.readVarint();r=7&p,n=p>>3;}if(n--,1===r||2===r)(i+=t.readSVarint())<a&&(a=i),i>s&&(s=i),(o+=t.readSVarint())<u&&(u=o),o>l&&(l=o);else if(7!==r)throw new Error("unknown command "+r)}return[a,u,s,l]},uo.prototype.toGeoJSON=function(t,e,r){var n,i,o=this.extent*Math.pow(2,r),a=this.extent*t,s=this.extent*e,u=this.loadGeometry(),l=uo.types[this.type];function p(t){for(var e=0;e<t.length;e++){var r=t[e],n=180-360*(r.y+s)/o;t[e]=[360*(r.x+a)/o-180,360/Math.PI*Math.atan(Math.exp(n*Math.PI/180))-90];}}switch(this.type){case 1:var c=[];for(n=0;n<u.length;n++)c[n]=u[n][0];p(u=c);break;case 2:for(n=0;n<u.length;n++)p(u[n]);break;case 3:for(u=function(t){var e=t.length;if(e<=1)return[t];for(var r,n,i=[],o=0;o<e;o++){var a=po(t[o]);0!==a&&(void 0===n&&(n=a<0),n===a<0?(r&&i.push(r),r=[t[o]]):r.push(t[o]));}r&&i.push(r);return i}(u),n=0;n<u.length;n++)for(i=0;i<u[n].length;i++)p(u[n][i]);}1===u.length?u=u[0]:l="Multi"+l;var h={type:"Feature",geometry:{type:l,coordinates:u},properties:this.properties};return"id"in this&&(h.id=this.id),h};var co=ho;function ho(t,e){this.version=1,this.name=null,this.extent=4096,this.length=0,this._pbf=t,this._keys=[],this._values=[],this._features=[],t.readFields(fo,this,e),this.length=this._features.length;}function fo(t,e,r){15===t?e.version=r.readVarint():1===t?e.name=r.readString():5===t?e.extent=r.readVarint():2===t?e._features.push(r.pos):3===t?e._keys.push(r.readString()):4===t&&e._values.push(function(t){var e=null,r=t.readVarint()+t.pos;for(;t.pos<r;){var n=t.readVarint()>>3;e=1===n?t.readString():2===n?t.readFloat():3===n?t.readDouble():4===n?t.readVarint64():5===n?t.readVarint():6===n?t.readSVarint():7===n?t.readBoolean():null;}return e}(r));}function yo(t,e,r){if(3===t){var n=new co(r,r.readVarint()+r.pos);n.length&&(e[n.name]=n);}}ho.prototype.feature=function(t){if(t<0||t>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];var e=this._pbf.readVarint()+this._pbf.pos;return new so(this._pbf,e,this.extent,this._keys,this._values)};var vo={VectorTile:function(t,e){this.layers=t.readFields(yo,{},e);},VectorTileFeature:so,VectorTileLayer:co},mo=vo.VectorTileFeature.types,go=63,xo=Math.cos(Math.PI/180*37.5),bo=.5,wo=Math.pow(2,14)/bo;function _o(t,e,r,n,i,o,a){t.emplaceBack(e.x,e.y,n?1:0,i?1:-1,Math.round(go*r.x)+128,Math.round(go*r.y)+128,1+(0===o?0:o<0?-1:1)|(a*bo&63)<<2,a*bo>>6);}var Ao=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new Wr,this.indexArray=new pn,this.programConfigurations=new En(ao,t.layers,t.zoom),this.segments=new zn;};function ko(t,e){return(t/e.tileTotal*(e.end-e.start)+e.start)*(wo-1)}Ao.prototype.populate=function(t,e){for(var r=0,n=t;r<n.length;r+=1){var i=n[r],o=i.feature,a=i.index,s=i.sourceLayerIndex;if(this.layers[0]._featureFilter(new Br(this.zoom),o)){var u=Ln(o);this.addFeature(o,u),e.featureIndex.insert(o,u,a,s,this.index);}}},Ao.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},Ao.prototype.upload=function(t){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,ao),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.programConfigurations.upload(t);},Ao.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());},Ao.prototype.addFeature=function(t,e){for(var r=this.layers[0].layout,n=r.get("line-join").evaluate(t),i=r.get("line-cap"),o=r.get("line-miter-limit"),a=r.get("line-round-limit"),s=0,u=e;s<u.length;s+=1){var l=u[s];this.addLine(l,t,n,i,o,a);}},Ao.prototype.addLine=function(t,e,r,n,i,o){var a=null;e.properties&&e.properties.hasOwnProperty("mapbox_clip_start")&&e.properties.hasOwnProperty("mapbox_clip_end")&&(a={start:e.properties.mapbox_clip_start,end:e.properties.mapbox_clip_end,tileTotal:void 0});for(var s="Polygon"===mo[e.type],u=t.length;u>=2&&t[u-1].equals(t[u-2]);)u--;for(var l=0;l<u-1&&t[l].equals(t[l+1]);)l++;if(!(u<(s?3:2))){a&&(a.tileTotal=function(t,e,r){for(var n,i,o=0,a=e;a<r-1;a++)n=t[a],i=t[a+1],o+=n.dist(i);return o}(t,l,u)),"bevel"===r&&(i=1.05);var p=Pn/(512*this.overscaling)*15,c=t[l],h=this.segments.prepareSegment(10*u,this.layoutVertexArray,this.indexArray);this.distance=0;var f,y,d,v=n,m=s?"butt":n,g=!0,x=void 0,b=void 0,w=void 0,_=void 0;this.e1=this.e2=this.e3=-1,s&&(f=t[u-2],_=c.sub(f)._unit()._perp());for(var A=l;A<u;A++)if(!(b=s&&A===u-1?t[l+1]:t[A+1])||!t[A].equals(b)){_&&(w=_),f&&(x=f),f=t[A],_=b?b.sub(f)._unit()._perp():w;var k=(w=w||_).add(_);0===k.x&&0===k.y||k._unit();var z=k.x*_.x+k.y*_.y,S=0!==z?1/z:1/0,M=z<xo&&x&&b;if(M&&A>l){var V=f.dist(x);if(V>2*p){var B=f.sub(f.sub(x)._mult(p/V)._round());this.distance+=B.dist(x),this.addCurrentVertex(B,this.distance,w.mult(1),0,0,!1,h,a),x=B;}}var C=x&&b,I=C?r:b?v:m;if(C&&"round"===I&&(S<o?I="miter":S<=2&&(I="fakeround")),"miter"===I&&S>i&&(I="bevel"),"bevel"===I&&(S>2&&(I="flipbevel"),S<i&&(I="miter")),x&&(this.distance+=f.dist(x)),"miter"===I)k._mult(S),this.addCurrentVertex(f,this.distance,k,0,0,!1,h,a);else if("flipbevel"===I){if(S>100)k=_.clone().mult(-1);else{var E=w.x*_.y-w.y*_.x>0?-1:1,F=S*w.add(_).mag()/w.sub(_).mag();k._perp()._mult(F*E);}this.addCurrentVertex(f,this.distance,k,0,0,!1,h,a),this.addCurrentVertex(f,this.distance,k.mult(-1),0,0,!1,h,a);}else if("bevel"===I||"fakeround"===I){var P=w.x*_.y-w.y*_.x>0,T=-Math.sqrt(S*S-1);if(P?(d=0,y=T):(y=0,d=T),g||this.addCurrentVertex(f,this.distance,w,y,d,!1,h,a),"fakeround"===I){for(var O=Math.floor(8*(.5-(z-.5))),L=void 0,j=0;j<O;j++)L=_.mult((j+1)/(O+1))._add(w)._unit(),this.addPieSliceVertex(f,this.distance,L,P,h,a);this.addPieSliceVertex(f,this.distance,k,P,h,a);for(var q=O-1;q>=0;q--)L=w.mult((q+1)/(O+1))._add(_)._unit(),this.addPieSliceVertex(f,this.distance,L,P,h,a);}b&&this.addCurrentVertex(f,this.distance,_,-y,-d,!1,h,a);}else"butt"===I?(g||this.addCurrentVertex(f,this.distance,w,0,0,!1,h,a),b&&this.addCurrentVertex(f,this.distance,_,0,0,!1,h,a)):"square"===I?(g||(this.addCurrentVertex(f,this.distance,w,1,1,!1,h,a),this.e1=this.e2=-1),b&&this.addCurrentVertex(f,this.distance,_,-1,-1,!1,h,a)):"round"===I&&(g||(this.addCurrentVertex(f,this.distance,w,0,0,!1,h,a),this.addCurrentVertex(f,this.distance,w,1,1,!0,h,a),this.e1=this.e2=-1),b&&(this.addCurrentVertex(f,this.distance,_,-1,-1,!0,h,a),this.addCurrentVertex(f,this.distance,_,0,0,!1,h,a)));if(M&&A<u-1){var R=f.dist(b);if(R>2*p){var U=f.add(b.sub(f)._mult(p/R)._round());this.distance+=U.dist(f),this.addCurrentVertex(U,this.distance,_.mult(1),0,0,!1,h,a),f=U;}}g=!1;}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,e);}},Ao.prototype.addCurrentVertex=function(t,e,r,n,i,o,a,s){var u,l=this.layoutVertexArray,p=this.indexArray;s&&(e=ko(e,s)),u=r.clone(),n&&u._sub(r.perp()._mult(n)),_o(l,t,u,o,!1,n,e),this.e3=a.vertexLength++,this.e1>=0&&this.e2>=0&&(p.emplaceBack(this.e1,this.e2,this.e3),a.primitiveLength++),this.e1=this.e2,this.e2=this.e3,u=r.mult(-1),i&&u._sub(r.perp()._mult(i)),_o(l,t,u,o,!0,-i,e),this.e3=a.vertexLength++,this.e1>=0&&this.e2>=0&&(p.emplaceBack(this.e1,this.e2,this.e3),a.primitiveLength++),this.e1=this.e2,this.e2=this.e3,e>wo/2&&!s&&(this.distance=0,this.addCurrentVertex(t,this.distance,r,n,i,o,a));},Ao.prototype.addPieSliceVertex=function(t,e,r,n,i,o){r=r.mult(n?-1:1);var a=this.layoutVertexArray,s=this.indexArray;o&&(e=ko(e,o)),_o(a,t,r,!1,n,0,e),this.e3=i.vertexLength++,this.e1>=0&&this.e2>=0&&(s.emplaceBack(this.e1,this.e2,this.e3),i.primitiveLength++),n?this.e2=this.e3:this.e1=this.e3;},hr("LineBucket",Ao,{omit:["layers"]});var zo=new Dr({"line-cap":new jr(E.layout_line["line-cap"]),"line-join":new qr(E.layout_line["line-join"]),"line-miter-limit":new jr(E.layout_line["line-miter-limit"]),"line-round-limit":new jr(E.layout_line["line-round-limit"])}),So={paint:new Dr({"line-opacity":new qr(E.paint_line["line-opacity"]),"line-color":new qr(E.paint_line["line-color"]),"line-translate":new jr(E.paint_line["line-translate"]),"line-translate-anchor":new jr(E.paint_line["line-translate-anchor"]),"line-width":new qr(E.paint_line["line-width"]),"line-gap-width":new qr(E.paint_line["line-gap-width"]),"line-offset":new qr(E.paint_line["line-offset"]),"line-blur":new qr(E.paint_line["line-blur"]),"line-dasharray":new Rr(E.paint_line["line-dasharray"]),"line-pattern":new Rr(E.paint_line["line-pattern"]),"line-gradient":new Ur(E.paint_line["line-gradient"])}),layout:zo},Mo=new(function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.possiblyEvaluate=function(e,r){return r=new Br(Math.floor(r.zoom),{now:r.now,fadeDuration:r.fadeDuration,zoomHistory:r.zoomHistory,transition:r.transition}),t.prototype.possiblyEvaluate.call(this,e,r)},e.prototype.evaluate=function(e,r,n){return r=h({},r,{zoom:Math.floor(r.zoom)}),t.prototype.evaluate.call(this,e,r,n)},e}(qr))(So.paint.properties["line-width"].specification);Mo.useIntegerZoom=!0;var Vo=function(t){function e(e){t.call(this,e,So);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.setPaintProperty=function(e,r,n){t.prototype.setPaintProperty.call(this,e,r,n),"line-gradient"===e&&this._updateGradient();},e.prototype._updateGradient=function(){var t=this._transitionablePaint._values["line-gradient"].value.expression;this.gradient=hi(t,"lineProgress"),this.gradientTexture=null;},e.prototype.recalculate=function(e){t.prototype.recalculate.call(this,e),this.paint._values["line-floorwidth"]=Mo.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,e);},e.prototype.createBucket=function(t){return new Ao(t)},e.prototype.queryRadius=function(t){var e=t,r=Bo(Gn("line-width",this,e),Gn("line-gap-width",this,e)),n=Gn("line-offset",this,e);return r/2+Math.abs(n)+Yn(this.paint.get("line-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,o){var a=Wn(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),i.angle,o),u=o/2*Bo(this.paint.get("line-width").evaluate(e),this.paint.get("line-gap-width").evaluate(e)),l=this.paint.get("line-offset").evaluate(e);return l&&(r=function(t,e){for(var r=[],n=new s(0,0),i=0;i<t.length;i++){for(var o=t[i],a=[],u=0;u<o.length;u++){var l=o[u-1],p=o[u],c=o[u+1],h=0===u?n:p.sub(l)._unit()._perp(),f=u===o.length-1?n:c.sub(p)._unit()._perp(),y=h._add(f)._unit(),d=y.x*f.x+y.y*f.y;y._mult(1/d),a.push(y._mult(e)._add(p));}r.push(a);}return r}(r,l*o)),Dn(a,r,u)},e}(Nr);function Bo(t,e){return e>0?e+2*t:t}var Co=$r([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"}]),Io=$r([{name:"a_projected_pos",components:3,type:"Float32"}],4),Eo=($r([{name:"a_fade_opacity",components:1,type:"Uint32"}],4),$r([{name:"a_placed",components:2,type:"Uint8"}],4)),Fo=($r([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"},{type:"Int16",name:"radius"},{type:"Int16",name:"signedDistanceFromAnchor"}]),$r([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4)),Po=$r([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4);$r([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"hidden"}]),$r([{type:"Float32",name:"offsetX"}]),$r([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]);function To(t,e,r){var n=e.layout.get("text-transform").evaluate(r);return"uppercase"===n?t=t.toLocaleUpperCase():"lowercase"===n&&(t=t.toLocaleLowerCase()),Vr.applyArabicShaping&&(t=Vr.applyArabicShaping(t)),t}var Oo={"!":"︕","#":"＃",$:"＄","%":"％","&":"＆","(":"︵",")":"︶","*":"＊","+":"＋",",":"︐","-":"︲",".":"・","/":"／",":":"︓",";":"︔","<":"︿","=":"＝",">":"﹀","?":"︖","@":"＠","[":"﹇","\\":"＼","]":"﹈","^":"＾",_:"︳","`":"｀","{":"︷","|":"―","}":"︸","~":"～","¢":"￠","£":"￡","¥":"￥","¦":"￤","¬":"￢","¯":"￣","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"￦","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","！":"︕","（":"︵","）":"︶","，":"︐","－":"︲","．":"・","：":"︓","；":"︔","＜":"︿","＞":"﹀","？":"︖","［":"﹇","］":"﹈","＿":"︳","｛":"︷","｜":"―","｝":"︸","｟":"︵","｠":"︶","｡":"︒","｢":"﹁","｣":"﹂"};var Lo=function(t){function e(e,r,n,i){t.call(this,e,r),this.angle=n,void 0!==i&&(this.segment=i);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.clone=function(){return new e(this.x,this.y,this.angle,this.segment)},e}(s);function jo(t,e){var r=e.expression;if("constant"===r.kind)return{functionType:"constant",layoutSize:r.evaluate(new Br(t+1))};if("source"===r.kind)return{functionType:"source"};for(var n=r.zoomStops,i=0;i<n.length&&n[i]<=t;)i++;for(var o=i=Math.max(0,i-1);o<n.length&&n[o]<t+1;)o++;o=Math.min(n.length-1,o);var a={min:n[i],max:n[o]};return"composite"===r.kind?{functionType:"composite",zoomRange:a,propertyValue:e.value}:{functionType:"camera",layoutSize:r.evaluate(new Br(t+1)),zoomRange:a,sizeRange:{min:r.evaluate(new Br(a.min)),max:r.evaluate(new Br(a.max))},propertyValue:e.value}}hr("Anchor",Lo);var qo=vo.VectorTileFeature.types,Ro=[{name:"a_fade_opacity",components:1,type:"Uint8",offset:0}];function Uo(t,e,r,n,i,o,a,s){t.emplaceBack(e,r,Math.round(32*n),Math.round(32*i),o,a,s?s[0]:0,s?s[1]:0);}function Do(t,e,r){t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r);}var No=function(t){this.layoutVertexArray=new Qr,this.indexArray=new pn,this.programConfigurations=t,this.segments=new zn,this.dynamicLayoutVertexArray=new tn,this.opacityVertexArray=new en,this.placedSymbolArray=new mn;};No.prototype.upload=function(t,e){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Co.members),this.indexBuffer=t.createIndexBuffer(this.indexArray,e),this.programConfigurations.upload(t),this.dynamicLayoutVertexBuffer=t.createVertexBuffer(this.dynamicLayoutVertexArray,Io.members,!0),this.opacityVertexBuffer=t.createVertexBuffer(this.opacityVertexArray,Ro,!0),this.opacityVertexBuffer.itemSize=1;},No.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.dynamicLayoutVertexBuffer.destroy(),this.opacityVertexBuffer.destroy());},hr("SymbolBuffers",No);var Zo=function(t,e,r){this.layoutVertexArray=new t,this.layoutAttributes=e,this.indexArray=new r,this.segments=new zn,this.collisionVertexArray=new on;};Zo.prototype.upload=function(t){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=t.createVertexBuffer(this.collisionVertexArray,Eo.members,!0);},Zo.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy());},hr("CollisionBuffers",Zo);var Ko=function(t){this.collisionBoxArray=t.collisionBoxArray,this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.pixelRatio=t.pixelRatio,this.sourceLayerIndex=t.sourceLayerIndex;var e=this.layers[0]._unevaluatedLayout._values;this.textSizeData=jo(this.zoom,e["text-size"]),this.iconSizeData=jo(this.zoom,e["icon-size"]);var r=this.layers[0].layout;this.sortFeaturesByY=r.get("text-allow-overlap")||r.get("icon-allow-overlap")||r.get("text-ignore-placement")||r.get("icon-ignore-placement");};Ko.prototype.createArrays=function(){this.text=new No(new En(Co.members,this.layers,this.zoom,function(t){return/^text/.test(t)})),this.icon=new No(new En(Co.members,this.layers,this.zoom,function(t){return/^icon/.test(t)})),this.collisionBox=new Zo(nn,Fo.members,cn),this.collisionCircle=new Zo(nn,Po.members,pn),this.glyphOffsetArray=new xn,this.lineVertexArray=new wn;},Ko.prototype.populate=function(t,e){var r=this.layers[0],n=r.layout,i=n.get("text-font"),o=n.get("text-field"),a=n.get("icon-image"),s=("constant"!==o.value.kind||o.value.value.length>0)&&("constant"!==i.value.kind||i.value.value.length>0),u="constant"!==a.value.kind||a.value.value&&a.value.value.length>0;if(this.features=[],s||u){for(var l=e.iconDependencies,p=e.glyphDependencies,c=new Br(this.zoom),h=0,f=t;h<f.length;h+=1){var y=f[h],d=y.feature,v=y.index,m=y.sourceLayerIndex;if(r._featureFilter(c,d)){var g=void 0;s&&(g=To(g=r.getValueAndResolveTokens("text-field",d),r,d));var x=void 0;if(u&&(x=r.getValueAndResolveTokens("icon-image",d)),g||x){var b={text:g,icon:x,index:v,sourceLayerIndex:m,geometry:Ln(d),properties:d.properties,type:qo[d.type]};if(void 0!==d.id&&(b.id=d.id),this.features.push(b),x&&(l[x]=!0),g)for(var w=i.evaluate(d).join(","),_=p[w]=p[w]||{},A="map"===n.get("text-rotation-alignment")&&"line"===n.get("symbol-placement"),k=gr(g),z=0;z<g.length;z++)if(_[g.charCodeAt(z)]=!0,A&&k){var S=Oo[g.charAt(z)];S&&(_[S.charCodeAt(0)]=!0);}}}}"line"===n.get("symbol-placement")&&(this.features=function(t){var e={},r={},n=[],i=0;function o(e){n.push(t[e]),i++;}function a(t,e,i){var o=r[t];return delete r[t],r[e]=o,n[o].geometry[0].pop(),n[o].geometry[0]=n[o].geometry[0].concat(i[0]),o}function s(t,r,i){var o=e[r];return delete e[r],e[t]=o,n[o].geometry[0].shift(),n[o].geometry[0]=i[0].concat(n[o].geometry[0]),o}function u(t,e,r){var n=r?e[0][e[0].length-1]:e[0][0];return t+":"+n.x+":"+n.y}for(var l=0;l<t.length;l++){var p=t[l],c=p.geometry,h=p.text;if(h){var f=u(h,c),y=u(h,c,!0);if(f in r&&y in e&&r[f]!==e[y]){var d=s(f,y,c),v=a(f,y,n[d].geometry);delete e[f],delete r[y],r[u(h,n[v].geometry,!0)]=v,n[d].geometry=null;}else f in r?a(f,y,c):y in e?s(f,y,c):(o(l),e[f]=i-1,r[y]=i-1);}else o(l);}return n.filter(function(t){return t.geometry})}(this.features));}},Ko.prototype.isEmpty=function(){return 0===this.symbolInstances.length},Ko.prototype.upload=function(t){this.text.upload(t,this.sortFeaturesByY),this.icon.upload(t,this.sortFeaturesByY),this.collisionBox.upload(t),this.collisionCircle.upload(t);},Ko.prototype.destroy=function(){this.text.destroy(),this.icon.destroy(),this.collisionBox.destroy(),this.collisionCircle.destroy();},Ko.prototype.addToLineVertexArray=function(t,e){var r=this.lineVertexArray.length;if(void 0!==t.segment){for(var n=t.dist(e[t.segment+1]),i=t.dist(e[t.segment]),o={},a=t.segment+1;a<e.length;a++)o[a]={x:e[a].x,y:e[a].y,tileUnitDistanceFromAnchor:n},a<e.length-1&&(n+=e[a+1].dist(e[a]));for(var s=t.segment||0;s>=0;s--)o[s]={x:e[s].x,y:e[s].y,tileUnitDistanceFromAnchor:i},s>0&&(i+=e[s-1].dist(e[s]));for(var u=0;u<e.length;u++){var l=o[u];this.lineVertexArray.emplaceBack(l.x,l.y,l.tileUnitDistanceFromAnchor);}}return{lineStartIndex:r,lineLength:this.lineVertexArray.length-r}},Ko.prototype.addSymbols=function(t,e,r,n,i,o,a,s,u,l){for(var p=t.indexArray,c=t.layoutVertexArray,h=t.dynamicLayoutVertexArray,f=t.segments.prepareSegment(4*e.length,t.layoutVertexArray,t.indexArray),y=this.glyphOffsetArray.length,d=f.vertexLength,v=0,m=e;v<m.length;v+=1){var g=m[v],x=g.tl,b=g.tr,w=g.bl,_=g.br,A=g.tex,k=f.vertexLength,z=g.glyphOffset[1];Uo(c,s.x,s.y,x.x,z+x.y,A.x,A.y,r),Uo(c,s.x,s.y,b.x,z+b.y,A.x+A.w,A.y,r),Uo(c,s.x,s.y,w.x,z+w.y,A.x,A.y+A.h,r),Uo(c,s.x,s.y,_.x,z+_.y,A.x+A.w,A.y+A.h,r),Do(h,s,0),p.emplaceBack(k,k+1,k+2),p.emplaceBack(k+1,k+2,k+3),f.vertexLength+=4,f.primitiveLength+=2,this.glyphOffsetArray.emplaceBack(g.glyphOffset[0]);}t.placedSymbolArray.emplaceBack(s.x,s.y,y,this.glyphOffsetArray.length-y,d,u,l,s.segment,r?r[0]:0,r?r[1]:0,n[0],n[1],a,!1),t.programConfigurations.populatePaintArrays(t.layoutVertexArray.length,o);},Ko.prototype._addCollisionDebugVertex=function(t,e,r,n,i){return e.emplaceBack(0,0),t.emplaceBack(r.x,r.y,n.x,n.y,Math.round(i.x),Math.round(i.y))},Ko.prototype.addCollisionDebugVertices=function(t,e,r,n,i,o,a,u){var l=i.segments.prepareSegment(4,i.layoutVertexArray,i.indexArray),p=l.vertexLength,c=i.layoutVertexArray,h=i.collisionVertexArray;if(this._addCollisionDebugVertex(c,h,o,a.anchor,new s(t,e)),this._addCollisionDebugVertex(c,h,o,a.anchor,new s(r,e)),this._addCollisionDebugVertex(c,h,o,a.anchor,new s(r,n)),this._addCollisionDebugVertex(c,h,o,a.anchor,new s(t,n)),l.vertexLength+=4,u){var f=i.indexArray;f.emplaceBack(p,p+1,p+2),f.emplaceBack(p,p+2,p+3),l.primitiveLength+=2;}else{var y=i.indexArray;y.emplaceBack(p,p+1),y.emplaceBack(p+1,p+2),y.emplaceBack(p+2,p+3),y.emplaceBack(p+3,p),l.primitiveLength+=4;}},Ko.prototype.generateCollisionDebugBuffers=function(){for(var t=0,e=this.symbolInstances;t<e.length;t+=1){var r=e[t];r.textCollisionFeature={boxStartIndex:r.textBoxStartIndex,boxEndIndex:r.textBoxEndIndex},r.iconCollisionFeature={boxStartIndex:r.iconBoxStartIndex,boxEndIndex:r.iconBoxEndIndex};for(var n=0;n<2;n++){var i=r[0===n?"textCollisionFeature":"iconCollisionFeature"];if(i)for(var o=i.boxStartIndex;o<i.boxEndIndex;o++){var a=this.collisionBoxArray.get(o),s=a.x1,u=a.y1,l=a.x2,p=a.y2,c=a.radius>0;this.addCollisionDebugVertices(s,u,l,p,c?this.collisionCircle:this.collisionBox,a.anchorPoint,r,c);}}}},Ko.prototype.deserializeCollisionBoxes=function(t,e,r,n,i){for(var o={},a=e;a<r;a++){var s=t.get(a);if(0===s.radius){o.textBox={x1:s.x1,y1:s.y1,x2:s.x2,y2:s.y2,anchorPointX:s.anchorPointX,anchorPointY:s.anchorPointY},o.textFeatureIndex=s.featureIndex;break}o.textCircles||(o.textCircles=[],o.textFeatureIndex=s.featureIndex);o.textCircles.push(s.anchorPointX,s.anchorPointY,s.radius,s.signedDistanceFromAnchor,1);}for(var u=n;u<i;u++){var l=t.get(u);if(0===l.radius){o.iconBox={x1:l.x1,y1:l.y1,x2:l.x2,y2:l.y2,anchorPointX:l.anchorPointX,anchorPointY:l.anchorPointY},o.iconFeatureIndex=l.featureIndex;break}}return o},Ko.prototype.hasTextData=function(){return this.text.segments.get().length>0},Ko.prototype.hasIconData=function(){return this.icon.segments.get().length>0},Ko.prototype.hasCollisionBoxData=function(){return this.collisionBox.segments.get().length>0},Ko.prototype.hasCollisionCircleData=function(){return this.collisionCircle.segments.get().length>0},Ko.prototype.sortFeatures=function(t){var e=this;if(this.sortFeaturesByY&&this.sortedAngle!==t&&(this.sortedAngle=t,!(this.text.segments.get().length>1||this.icon.segments.get().length>1))){for(var r=[],n=0;n<this.symbolInstances.length;n++)r.push(n);var i=Math.sin(t),o=Math.cos(t);r.sort(function(t,r){var n=e.symbolInstances[t],a=e.symbolInstances[r];return(i*n.anchor.x+o*n.anchor.y|0)-(i*a.anchor.x+o*a.anchor.y|0)||a.featureIndex-n.featureIndex}),this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(var a=0,s=r;a<s.length;a+=1){var u=s[a],l=e.symbolInstances[u];e.featureSortOrder.push(l.featureIndex);for(var p=0,c=l.placedTextSymbolIndices;p<c.length;p+=1)for(var h=c[p],f=e.text.placedSymbolArray.get(h),y=f.vertexStartIndex+4*f.numGlyphs,d=f.vertexStartIndex;d<y;d+=4)e.text.indexArray.emplaceBack(d,d+1,d+2),e.text.indexArray.emplaceBack(d+1,d+2,d+3);var v=e.icon.placedSymbolArray.get(u);if(v.numGlyphs){var m=v.vertexStartIndex;e.icon.indexArray.emplaceBack(m,m+1,m+2),e.icon.indexArray.emplaceBack(m+1,m+2,m+3);}}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray);}},hr("SymbolBucket",Ko,{omit:["layers","collisionBoxArray","features","compareText"],shallow:["symbolInstances"]}),Ko.MAX_GLYPHS=65535,Ko.addDynamicAttributes=Do;var Jo=new Dr({"symbol-placement":new jr(E.layout_symbol["symbol-placement"]),"symbol-spacing":new jr(E.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new jr(E.layout_symbol["symbol-avoid-edges"]),"icon-allow-overlap":new jr(E.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new jr(E.layout_symbol["icon-ignore-placement"]),"icon-optional":new jr(E.layout_symbol["icon-optional"]),"icon-rotation-alignment":new jr(E.layout_symbol["icon-rotation-alignment"]),"icon-size":new qr(E.layout_symbol["icon-size"]),"icon-text-fit":new jr(E.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new jr(E.layout_symbol["icon-text-fit-padding"]),"icon-image":new qr(E.layout_symbol["icon-image"]),"icon-rotate":new qr(E.layout_symbol["icon-rotate"]),"icon-padding":new jr(E.layout_symbol["icon-padding"]),"icon-keep-upright":new jr(E.layout_symbol["icon-keep-upright"]),"icon-offset":new qr(E.layout_symbol["icon-offset"]),"icon-anchor":new qr(E.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new jr(E.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new jr(E.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new jr(E.layout_symbol["text-rotation-alignment"]),"text-field":new qr(E.layout_symbol["text-field"]),"text-font":new qr(E.layout_symbol["text-font"]),"text-size":new qr(E.layout_symbol["text-size"]),"text-max-width":new qr(E.layout_symbol["text-max-width"]),"text-line-height":new jr(E.layout_symbol["text-line-height"]),"text-letter-spacing":new qr(E.layout_symbol["text-letter-spacing"]),"text-justify":new qr(E.layout_symbol["text-justify"]),"text-anchor":new qr(E.layout_symbol["text-anchor"]),"text-max-angle":new jr(E.layout_symbol["text-max-angle"]),"text-rotate":new qr(E.layout_symbol["text-rotate"]),"text-padding":new jr(E.layout_symbol["text-padding"]),"text-keep-upright":new jr(E.layout_symbol["text-keep-upright"]),"text-transform":new qr(E.layout_symbol["text-transform"]),"text-offset":new qr(E.layout_symbol["text-offset"]),"text-allow-overlap":new jr(E.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new jr(E.layout_symbol["text-ignore-placement"]),"text-optional":new jr(E.layout_symbol["text-optional"])}),$o={paint:new Dr({"icon-opacity":new qr(E.paint_symbol["icon-opacity"]),"icon-color":new qr(E.paint_symbol["icon-color"]),"icon-halo-color":new qr(E.paint_symbol["icon-halo-color"]),"icon-halo-width":new qr(E.paint_symbol["icon-halo-width"]),"icon-halo-blur":new qr(E.paint_symbol["icon-halo-blur"]),"icon-translate":new jr(E.paint_symbol["icon-translate"]),"icon-translate-anchor":new jr(E.paint_symbol["icon-translate-anchor"]),"text-opacity":new qr(E.paint_symbol["text-opacity"]),"text-color":new qr(E.paint_symbol["text-color"]),"text-halo-color":new qr(E.paint_symbol["text-halo-color"]),"text-halo-width":new qr(E.paint_symbol["text-halo-width"]),"text-halo-blur":new qr(E.paint_symbol["text-halo-blur"]),"text-translate":new jr(E.paint_symbol["text-translate"]),"text-translate-anchor":new jr(E.paint_symbol["text-translate-anchor"])}),layout:Jo},Ho=function(t){function e(e){t.call(this,e,$o);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.recalculate=function(e){t.prototype.recalculate.call(this,e),"auto"===this.layout.get("icon-rotation-alignment")&&("line"===this.layout.get("symbol-placement")?this.layout._values["icon-rotation-alignment"]="map":this.layout._values["icon-rotation-alignment"]="viewport"),"auto"===this.layout.get("text-rotation-alignment")&&("line"===this.layout.get("symbol-placement")?this.layout._values["text-rotation-alignment"]="map":this.layout._values["text-rotation-alignment"]="viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]=this.layout.get("text-rotation-alignment")),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment"));},e.prototype.getValueAndResolveTokens=function(t,e){var r,n=this.layout.get(t).evaluate(e),i=this._unevaluatedLayout._values[t];return i.isDataDriven()||be(i.value)?n:(r=e.properties,n.replace(/{([^{}]+)}/g,function(t,e){return e in r?String(r[e]):""}))},e.prototype.createBucket=function(t){return new Ko(t)},e.prototype.queryRadius=function(){return 0},e.prototype.queryIntersectsFeature=function(){return!1},e}(Nr),Xo={paint:new Dr({"background-color":new jr(E.paint_background["background-color"]),"background-pattern":new Rr(E.paint_background["background-pattern"]),"background-opacity":new jr(E.paint_background["background-opacity"])})},Go=function(t){function e(e){t.call(this,e,Xo);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(Nr),Yo={paint:new Dr({"raster-opacity":new jr(E.paint_raster["raster-opacity"]),"raster-hue-rotate":new jr(E.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new jr(E.paint_raster["raster-brightness-min"]),"raster-brightness-max":new jr(E.paint_raster["raster-brightness-max"]),"raster-saturation":new jr(E.paint_raster["raster-saturation"]),"raster-contrast":new jr(E.paint_raster["raster-contrast"]),"raster-fade-duration":new jr(E.paint_raster["raster-fade-duration"])})},Wo={circle:ni,heatmap:fi,hillshade:di,fill:Yi,"fill-extrusion":oo,line:Vo,symbol:Ho,background:Go,raster:function(t){function e(e){t.call(this,e,Yo);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(Nr)};var Qo=n(function(t,e){t.exports=function(){function t(t,e,r){r=r||{},this.w=t||64,this.h=e||64,this.autoResize=!!r.autoResize,this.shelves=[],this.freebins=[],this.stats={},this.bins={},this.maxId=0;}function e(t,e,r){this.x=0,this.y=t,this.w=this.free=e,this.h=r;}return t.prototype.pack=function(t,e){t=[].concat(t),e=e||{};for(var r,n,i,o,a=[],s=0;s<t.length;s++)if(r=t[s].w||t[s].width,n=t[s].h||t[s].height,i=t[s].id,r&&n){if(!(o=this.packOne(r,n,i)))continue;e.inPlace&&(t[s].x=o.x,t[s].y=o.y,t[s].id=o.id),a.push(o);}return this.shrink(),a},t.prototype.packOne=function(t,r,n){var i,o,a,s,u,l,p,c,h={freebin:-1,shelf:-1,waste:1/0},f=0;if("string"==typeof n||"number"==typeof n){if(i=this.getBin(n))return this.ref(i),i;"number"==typeof n&&(this.maxId=Math.max(n,this.maxId));}else n=++this.maxId;for(s=0;s<this.freebins.length;s++){if(r===(i=this.freebins[s]).maxh&&t===i.maxw)return this.allocFreebin(s,t,r,n);r>i.maxh||t>i.maxw||r<=i.maxh&&t<=i.maxw&&(a=i.maxw*i.maxh-t*r)<h.waste&&(h.waste=a,h.freebin=s);}for(s=0;s<this.shelves.length;s++)if(f+=(o=this.shelves[s]).h,!(t>o.free)){if(r===o.h)return this.allocShelf(s,t,r,n);r>o.h||r<o.h&&(a=(o.h-r)*t)<h.waste&&(h.freebin=-1,h.waste=a,h.shelf=s);}return-1!==h.freebin?this.allocFreebin(h.freebin,t,r,n):-1!==h.shelf?this.allocShelf(h.shelf,t,r,n):r<=this.h-f&&t<=this.w?(o=new e(f,this.w,r),this.allocShelf(this.shelves.push(o)-1,t,r,n)):this.autoResize?(u=l=this.h,((p=c=this.w)<=u||t>p)&&(c=2*Math.max(t,p)),(u<p||r>u)&&(l=2*Math.max(r,u)),this.resize(c,l),this.packOne(t,r,n)):null},t.prototype.allocFreebin=function(t,e,r,n){var i=this.freebins.splice(t,1)[0];return i.id=n,i.w=e,i.h=r,i.refcount=0,this.bins[n]=i,this.ref(i),i},t.prototype.allocShelf=function(t,e,r,n){var i=this.shelves[t].alloc(e,r,n);return this.bins[n]=i,this.ref(i),i},t.prototype.shrink=function(){if(this.shelves.length>0){for(var t=0,e=0,r=0;r<this.shelves.length;r++){var n=this.shelves[r];e+=n.h,t=Math.max(n.w-n.free,t);}this.resize(t,e);}},t.prototype.getBin=function(t){return this.bins[t]},t.prototype.ref=function(t){if(1==++t.refcount){var e=t.h;this.stats[e]=1+(0|this.stats[e]);}return t.refcount},t.prototype.unref=function(t){return 0===t.refcount?0:(0==--t.refcount&&(this.stats[t.h]--,delete this.bins[t.id],this.freebins.push(t)),t.refcount)},t.prototype.clear=function(){this.shelves=[],this.freebins=[],this.stats={},this.bins={},this.maxId=0;},t.prototype.resize=function(t,e){this.w=t,this.h=e;for(var r=0;r<this.shelves.length;r++)this.shelves[r].resize(t);return!0},e.prototype.alloc=function(t,e,r){if(t>this.free||e>this.h)return null;var n=this.x;return this.x+=t,this.free-=t,new function(t,e,r,n,i,o,a){this.id=t,this.x=e,this.y=r,this.w=n,this.h=i,this.maxw=o||n,this.maxh=a||i,this.refcount=0;}(r,n,this.y,t,e,t,this.h)},e.prototype.resize=function(t){return this.free+=t-this.w,this.w=t,!0},t}();}),ta=function(t,e){var r=e.pixelRatio;this.paddedRect=t,this.pixelRatio=r;},ea={tl:{configurable:!0},br:{configurable:!0},displaySize:{configurable:!0}};ea.tl.get=function(){return[this.paddedRect.x+1,this.paddedRect.y+1]},ea.br.get=function(){return[this.paddedRect.x+this.paddedRect.w-1,this.paddedRect.y+this.paddedRect.h-1]},ea.displaySize.get=function(){return[(this.paddedRect.w-2)/this.pixelRatio,(this.paddedRect.h-2)/this.pixelRatio]},Object.defineProperties(ta.prototype,ea);var ra=function(t){var e=new pi({width:0,height:0}),r={},n=new Qo(0,0,{autoResize:!0});for(var i in t){var o=t[i],a=n.packOne(o.data.width+2,o.data.height+2);e.resize({width:n.w,height:n.h}),pi.copy(o.data,e,{x:0,y:0},{x:a.x+1,y:a.y+1},o.data),r[i]=new ta(a,o);}n.shrink(),e.resize({width:n.w,height:n.h}),this.image=e,this.positions=r;};hr("ImagePosition",ta),hr("ImageAtlas",ra);var na=function(t,e,r,n,i){var o,a,s=8*i-n-1,u=(1<<s)-1,l=u>>1,p=-7,c=r?i-1:0,h=r?-1:1,f=t[e+c];for(c+=h,o=f&(1<<-p)-1,f>>=-p,p+=s;p>0;o=256*o+t[e+c],c+=h,p-=8);for(a=o&(1<<-p)-1,o>>=-p,p+=n;p>0;a=256*a+t[e+c],c+=h,p-=8);if(0===o)o=1-l;else{if(o===u)return a?NaN:1/0*(f?-1:1);a+=Math.pow(2,n),o-=l;}return(f?-1:1)*a*Math.pow(2,o-n)},ia=function(t,e,r,n,i,o){var a,s,u,l=8*o-i-1,p=(1<<l)-1,c=p>>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:o-1,y=n?1:-1,d=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,a=p):(a=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-a))<1&&(a--,u*=2),(e+=a+c>=1?h/u:h*Math.pow(2,1-c))*u>=2&&(a++,u/=2),a+c>=p?(s=0,a=p):a+c>=1?(s=(e*u-1)*Math.pow(2,i),a+=c):(s=e*Math.pow(2,c-1)*Math.pow(2,i),a=0));i>=8;t[r+f]=255&s,f+=y,s/=256,i-=8);for(a=a<<i|s,l+=i;l>0;t[r+f]=255&a,f+=y,a/=256,l-=8);t[r+f-y]|=128*d;},oa=aa;function aa(t){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(t)?t:new Uint8Array(t||0),this.pos=0,this.type=0,this.length=this.buf.length;}aa.Varint=0,aa.Fixed64=1,aa.Bytes=2,aa.Fixed32=5;function sa(t){return t.type===aa.Bytes?t.readVarint()+t.pos:t.pos+1}function ua(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function la(t,e,r){var n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.ceil(Math.log(e)/(7*Math.LN2));r.realloc(n);for(var i=r.pos-1;i>=t;i--)r.buf[i+n]=r.buf[i];}function pa(t,e){for(var r=0;r<t.length;r++)e.writeVarint(t[r]);}function ca(t,e){for(var r=0;r<t.length;r++)e.writeSVarint(t[r]);}function ha(t,e){for(var r=0;r<t.length;r++)e.writeFloat(t[r]);}function fa(t,e){for(var r=0;r<t.length;r++)e.writeDouble(t[r]);}function ya(t,e){for(var r=0;r<t.length;r++)e.writeBoolean(t[r]);}function da(t,e){for(var r=0;r<t.length;r++)e.writeFixed32(t[r]);}function va(t,e){for(var r=0;r<t.length;r++)e.writeSFixed32(t[r]);}function ma(t,e){for(var r=0;r<t.length;r++)e.writeFixed64(t[r]);}function ga(t,e){for(var r=0;r<t.length;r++)e.writeSFixed64(t[r]);}function xa(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16)+16777216*t[e+3]}function ba(t,e,r){t[r]=e,t[r+1]=e>>>8,t[r+2]=e>>>16,t[r+3]=e>>>24;}function wa(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16)+(t[e+3]<<24)}aa.prototype={destroy:function(){this.buf=null;},readFields:function(t,e,r){for(r=r||this.length;this.pos<r;){var n=this.readVarint(),i=n>>3,o=this.pos;this.type=7&n,t(i,e,this),this.pos===o&&this.skip(n);}return e},readMessage:function(t,e){return this.readFields(t,e,this.readVarint()+this.pos)},readFixed32:function(){var t=xa(this.buf,this.pos);return this.pos+=4,t},readSFixed32:function(){var t=wa(this.buf,this.pos);return this.pos+=4,t},readFixed64:function(){var t=xa(this.buf,this.pos)+4294967296*xa(this.buf,this.pos+4);return this.pos+=8,t},readSFixed64:function(){var t=xa(this.buf,this.pos)+4294967296*wa(this.buf,this.pos+4);return this.pos+=8,t},readFloat:function(){var t=na(this.buf,this.pos,!0,23,4);return this.pos+=4,t},readDouble:function(){var t=na(this.buf,this.pos,!0,52,8);return this.pos+=8,t},readVarint:function(t){var e,r,n=this.buf;return e=127&(r=n[this.pos++]),r<128?e:(e|=(127&(r=n[this.pos++]))<<7,r<128?e:(e|=(127&(r=n[this.pos++]))<<14,r<128?e:(e|=(127&(r=n[this.pos++]))<<21,r<128?e:function(t,e,r){var n,i,o=r.buf;if(i=o[r.pos++],n=(112&i)>>4,i<128)return ua(t,n,e);if(i=o[r.pos++],n|=(127&i)<<3,i<128)return ua(t,n,e);if(i=o[r.pos++],n|=(127&i)<<10,i<128)return ua(t,n,e);if(i=o[r.pos++],n|=(127&i)<<17,i<128)return ua(t,n,e);if(i=o[r.pos++],n|=(127&i)<<24,i<128)return ua(t,n,e);if(i=o[r.pos++],n|=(1&i)<<31,i<128)return ua(t,n,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(r=n[this.pos]))<<28,t,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var t=this.readVarint();return t%2==1?(t+1)/-2:t/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var t=this.readVarint()+this.pos,e=function(t,e,r){var n="",i=e;for(;i<r;){var o,a,s,u=t[i],l=null,p=u>239?4:u>223?3:u>191?2:1;if(i+p>r)break;1===p?u<128&&(l=u):2===p?128==(192&(o=t[i+1]))&&(l=(31&u)<<6|63&o)<=127&&(l=null):3===p?(o=t[i+1],a=t[i+2],128==(192&o)&&128==(192&a)&&((l=(15&u)<<12|(63&o)<<6|63&a)<=2047||l>=55296&&l<=57343)&&(l=null)):4===p&&(o=t[i+1],a=t[i+2],s=t[i+3],128==(192&o)&&128==(192&a)&&128==(192&s)&&((l=(15&u)<<18|(63&o)<<12|(63&a)<<6|63&s)<=65535||l>=1114112)&&(l=null)),null===l?(l=65533,p=1):l>65535&&(l-=65536,n+=String.fromCharCode(l>>>10&1023|55296),l=56320|1023&l),n+=String.fromCharCode(l),i+=p;}return n}(this.buf,this.pos,t);return this.pos=t,e},readBytes:function(){var t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e},readPackedVarint:function(t,e){var r=sa(this);for(t=t||[];this.pos<r;)t.push(this.readVarint(e));return t},readPackedSVarint:function(t){var e=sa(this);for(t=t||[];this.pos<e;)t.push(this.readSVarint());return t},readPackedBoolean:function(t){var e=sa(this);for(t=t||[];this.pos<e;)t.push(this.readBoolean());return t},readPackedFloat:function(t){var e=sa(this);for(t=t||[];this.pos<e;)t.push(this.readFloat());return t},readPackedDouble:function(t){var e=sa(this);for(t=t||[];this.pos<e;)t.push(this.readDouble());return t},readPackedFixed32:function(t){var e=sa(this);for(t=t||[];this.pos<e;)t.push(this.readFixed32());return t},readPackedSFixed32:function(t){var e=sa(this);for(t=t||[];this.pos<e;)t.push(this.readSFixed32());return t},readPackedFixed64:function(t){var e=sa(this);for(t=t||[];this.pos<e;)t.push(this.readFixed64());return t},readPackedSFixed64:function(t){var e=sa(this);for(t=t||[];this.pos<e;)t.push(this.readSFixed64());return t},skip:function(t){var e=7&t;if(e===aa.Varint)for(;this.buf[this.pos++]>127;);else if(e===aa.Bytes)this.pos=this.readVarint()+this.pos;else if(e===aa.Fixed32)this.pos+=4;else{if(e!==aa.Fixed64)throw new Error("Unimplemented type: "+e);this.pos+=8;}},writeTag:function(t,e){this.writeVarint(t<<3|e);},realloc:function(t){for(var e=this.length||16;e<this.pos+t;)e*=2;if(e!==this.length){var r=new Uint8Array(e);r.set(this.buf),this.buf=r,this.length=e;}},finish:function(){return this.length=this.pos,this.pos=0,this.buf.subarray(0,this.length)},writeFixed32:function(t){this.realloc(4),ba(this.buf,t,this.pos),this.pos+=4;},writeSFixed32:function(t){this.realloc(4),ba(this.buf,t,this.pos),this.pos+=4;},writeFixed64:function(t){this.realloc(8),ba(this.buf,-1&t,this.pos),ba(this.buf,Math.floor(t*(1/4294967296)),this.pos+4),this.pos+=8;},writeSFixed64:function(t){this.realloc(8),ba(this.buf,-1&t,this.pos),ba(this.buf,Math.floor(t*(1/4294967296)),this.pos+4),this.pos+=8;},writeVarint:function(t){(t=+t||0)>268435455||t<0?function(t,e){var r,n;t>=0?(r=t%4294967296|0,n=t/4294967296|0):(n=~(-t/4294967296),4294967295^(r=~(-t%4294967296))?r=r+1|0:(r=0,n=n+1|0));if(t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos]=127&t;}(r,0,e),function(t,e){var r=(7&t)<<4;if(e.buf[e.pos++]|=r|((t>>>=3)?128:0),!t)return;if(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),!t)return;if(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),!t)return;if(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),!t)return;if(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),!t)return;e.buf[e.pos++]=127&t;}(n,e);}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))));},writeSVarint:function(t){this.writeVarint(t<0?2*-t-1:2*t);},writeBoolean:function(t){this.writeVarint(Boolean(t));},writeString:function(t){t=String(t),this.realloc(4*t.length),this.pos++;var e=this.pos;this.pos=function(t,e,r){for(var n,i,o=0;o<e.length;o++){if((n=e.charCodeAt(o))>55295&&n<57344){if(!i){n>56319||o+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null;}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128);}return r}(this.buf,t,this.pos);var r=this.pos-e;r>=128&&la(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r;},writeFloat:function(t){this.realloc(4),ia(this.buf,t,this.pos,!0,23,4),this.pos+=4;},writeDouble:function(t){this.realloc(8),ia(this.buf,t,this.pos,!0,52,8),this.pos+=8;},writeBytes:function(t){var e=t.length;this.writeVarint(e),this.realloc(e);for(var r=0;r<e;r++)this.buf[this.pos++]=t[r];},writeRawMessage:function(t,e){this.pos++;var r=this.pos;t(e,this);var n=this.pos-r;n>=128&&la(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n;},writeMessage:function(t,e,r){this.writeTag(t,aa.Bytes),this.writeRawMessage(e,r);},writePackedVarint:function(t,e){this.writeMessage(t,pa,e);},writePackedSVarint:function(t,e){this.writeMessage(t,ca,e);},writePackedBoolean:function(t,e){this.writeMessage(t,ya,e);},writePackedFloat:function(t,e){this.writeMessage(t,ha,e);},writePackedDouble:function(t,e){this.writeMessage(t,fa,e);},writePackedFixed32:function(t,e){this.writeMessage(t,da,e);},writePackedSFixed32:function(t,e){this.writeMessage(t,va,e);},writePackedFixed64:function(t,e){this.writeMessage(t,ma,e);},writePackedSFixed64:function(t,e){this.writeMessage(t,ga,e);},writeBytesField:function(t,e){this.writeTag(t,aa.Bytes),this.writeBytes(e);},writeFixed32Field:function(t,e){this.writeTag(t,aa.Fixed32),this.writeFixed32(e);},writeSFixed32Field:function(t,e){this.writeTag(t,aa.Fixed32),this.writeSFixed32(e);},writeFixed64Field:function(t,e){this.writeTag(t,aa.Fixed64),this.writeFixed64(e);},writeSFixed64Field:function(t,e){this.writeTag(t,aa.Fixed64),this.writeSFixed64(e);},writeVarintField:function(t,e){this.writeTag(t,aa.Varint),this.writeVarint(e);},writeSVarintField:function(t,e){this.writeTag(t,aa.Varint),this.writeSVarint(e);},writeStringField:function(t,e){this.writeTag(t,aa.Bytes),this.writeString(e);},writeFloatField:function(t,e){this.writeTag(t,aa.Fixed32),this.writeFloat(e);},writeDoubleField:function(t,e){this.writeTag(t,aa.Fixed64),this.writeDouble(e);},writeBooleanField:function(t,e){this.writeVarintField(t,Boolean(e));}};var _a=3;function Aa(t,e,r){1===t&&r.readMessage(ka,e);}function ka(t,e,r){if(3===t){var n=r.readMessage(za,{}),i=n.id,o=n.bitmap,a=n.width,s=n.height,u=n.left,l=n.top,p=n.advance;e.push({id:i,bitmap:new li({width:a+2*_a,height:s+2*_a},o),metrics:{width:a,height:s,left:u,top:l,advance:p}});}}function za(t,e,r){1===t?e.id=r.readVarint():2===t?e.bitmap=r.readBytes():3===t?e.width=r.readVarint():4===t?e.height=r.readVarint():5===t?e.left=r.readSVarint():6===t?e.top=r.readSVarint():7===t&&(e.advance=r.readVarint());}var Sa=_a,Ma=function(t,e,r){this.target=t,this.parent=e,this.mapId=r,this.callbacks={},this.callbackID=0,y(["receive"],this),this.target.addEventListener("message",this.receive,!1);};Ma.prototype.send=function(t,e,r,n){var i=r?this.mapId+":"+this.callbackID++:null;r&&(this.callbacks[i]=r);var o=[];this.target.postMessage({targetMapId:n,sourceMapId:this.mapId,type:t,id:String(i),data:yr(e,o)},o);},Ma.prototype.receive=function(t){var e,r=this,n=t.data,i=n.id;if(!n.targetMapId||this.mapId===n.targetMapId){var o=function(t,e){var n=[];r.target.postMessage({sourceMapId:r.mapId,type:"<response>",id:String(i),error:t?yr(t):null,data:yr(e,n)},n);};if("<response>"===n.type)e=this.callbacks[n.id],delete this.callbacks[n.id],e&&n.error?e(dr(n.error)):e&&e(null,dr(n.data));else if(void 0!==n.id&&this.parent[n.type])this.parent[n.type](n.sourceMapId,dr(n.data),o);else if(void 0!==n.id&&this.parent.getWorkerSource){var a=n.type.split(".");this.parent.getWorkerSource(n.sourceMapId,a[0],a[1])[a[2]](dr(n.data),o);}else this.parent[n.type](dr(n.data));}},Ma.prototype.remove=function(){this.target.removeEventListener("message",this.receive,!1);};var Va=r(n(function(t,e){!function(t){function e(t,e,n){e=Math.pow(2,n)-e-1;var i=r(256*t,256*e,n),o=r(256*(t+1),256*(e+1),n);return i[0]+","+i[1]+","+o[0]+","+o[1]}function r(t,e,r){var n=2*Math.PI*6378137/256/Math.pow(2,r),i=t*n-2*Math.PI*6378137/2,o=e*n-2*Math.PI*6378137/2;return[i,o]}t.getURL=function(t,r,n,i,o,a){return a=a||{},t+"?"+["bbox="+e(n,i,o),"format="+(a.format||"image/png"),"service="+(a.service||"WMS"),"version="+(a.version||"1.1.1"),"request="+(a.request||"GetMap"),"srs="+(a.srs||"EPSG:3857"),"width="+(a.width||256),"height="+(a.height||256),"layers="+r].join("&")},t.getTileBBox=e,t.getMercCoords=r,Object.defineProperty(t,"__esModule",{value:!0});}(e);})),Ba=function(t,e,r){this.z=t,this.x=e,this.y=r,this.key=Ea(0,t,e,r);};Ba.prototype.equals=function(t){return this.z===t.z&&this.x===t.x&&this.y===t.y},Ba.prototype.url=function(t,e){var r=Va.getTileBBox(this.x,this.y,this.z),n=function(t,e,r){for(var n,i="",o=t;o>0;o--)i+=(e&(n=1<<o-1)?1:0)+(r&n?2:0);return i}(this.z,this.x,this.y);return t[(this.x+this.y)%t.length].replace("{prefix}",(this.x%16).toString(16)+(this.y%16).toString(16)).replace("{z}",String(this.z)).replace("{x}",String(this.x)).replace("{y}",String("tms"===e?Math.pow(2,this.z)-this.y-1:this.y)).replace("{quadkey}",n).replace("{bbox-epsg-3857}",r)};var Ca=function(t,e){this.wrap=t,this.canonical=e,this.key=Ea(t,e.z,e.x,e.y);},Ia=function(t,e,r,n,i){this.overscaledZ=t,this.wrap=e,this.canonical=new Ba(r,+n,+i),this.key=Ea(e,t,n,i);};function Ea(t,e,r,n){(t*=2)<0&&(t=-1*t-1);var i=1<<e;return 32*(i*i*t+i*n+r)+e}Ia.prototype.equals=function(t){return this.overscaledZ===t.overscaledZ&&this.wrap===t.wrap&&this.canonical.equals(t.canonical)},Ia.prototype.scaledTo=function(t){var e=this.canonical.z-t;return t>this.canonical.z?new Ia(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new Ia(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)},Ia.prototype.isChildOf=function(t){var e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ<this.overscaledZ&&t.canonical.x===this.canonical.x>>e&&t.canonical.y===this.canonical.y>>e},Ia.prototype.children=function(t){if(this.overscaledZ>=t)return[new Ia(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];var e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return[new Ia(e,this.wrap,e,r,n),new Ia(e,this.wrap,e,r+1,n),new Ia(e,this.wrap,e,r,n+1),new Ia(e,this.wrap,e,r+1,n+1)]},Ia.prototype.isLessThan=function(t){return this.wrap<t.wrap||!(this.wrap>t.wrap)&&(this.overscaledZ<t.overscaledZ||!(this.overscaledZ>t.overscaledZ)&&(this.canonical.x<t.canonical.x||!(this.canonical.x>t.canonical.x)&&this.canonical.y<t.canonical.y))},Ia.prototype.wrapped=function(){return new Ia(this.overscaledZ,0,this.canonical.z,this.canonical.x,this.canonical.y)},Ia.prototype.unwrapTo=function(t){return new Ia(this.overscaledZ,t,this.canonical.z,this.canonical.x,this.canonical.y)},Ia.prototype.overscaleFactor=function(){return Math.pow(2,this.overscaledZ-this.canonical.z)},Ia.prototype.toUnwrapped=function(){return new Ca(this.wrap,this.canonical)},Ia.prototype.toString=function(){return this.overscaledZ+"/"+this.canonical.x+"/"+this.canonical.y},Ia.prototype.toCoordinate=function(){return new a(this.canonical.x+Math.pow(2,this.wrap),this.canonical.y,this.canonical.z)},hr("CanonicalTileID",Ba),hr("OverscaledTileID",Ia,{omit:["posMatrix"]});var Fa=function(t,e,r){if(t<=0)throw new RangeError("Level must have positive dimension");this.dim=t,this.border=e,this.stride=this.dim+2*this.border,this.data=r||new Int32Array((this.dim+2*this.border)*(this.dim+2*this.border));};Fa.prototype.set=function(t,e,r){this.data[this._idx(t,e)]=r+65536;},Fa.prototype.get=function(t,e){return this.data[this._idx(t,e)]-65536},Fa.prototype._idx=function(t,e){if(t<-this.border||t>=this.dim+this.border||e<-this.border||e>=this.dim+this.border)throw new RangeError("out of range source coordinates for DEM data");return(e+this.border)*this.stride+(t+this.border)},hr("Level",Fa);var Pa=function(t,e,r){this.uid=t,this.scale=e||1,this.level=r||new Fa(256,512),this.loaded=!!r;};Pa.prototype.loadFromImage=function(t,e){if(t.height!==t.width)throw new RangeError("DEM tiles must be square");if(e&&"mapbox"!==e&&"terrarium"!==e)return b('"'+e+'" is not a valid encoding type. Valid types include "mapbox" and "terrarium".');var r=this.level=new Fa(t.width,t.width/2),n=t.data;this._unpackData(r,n,e||"mapbox");for(var i=0;i<r.dim;i++)r.set(-1,i,r.get(0,i)),r.set(r.dim,i,r.get(r.dim-1,i)),r.set(i,-1,r.get(i,0)),r.set(i,r.dim,r.get(i,r.dim-1));r.set(-1,-1,r.get(0,0)),r.set(r.dim,-1,r.get(r.dim-1,0)),r.set(-1,r.dim,r.get(0,r.dim-1)),r.set(r.dim,r.dim,r.get(r.dim-1,r.dim-1)),this.loaded=!0;},Pa.prototype._unpackMapbox=function(t,e,r){return(256*t*256+256*e+r)/10-1e4},Pa.prototype._unpackTerrarium=function(t,e,r){return 256*t+e+r/256-32768},Pa.prototype._unpackData=function(t,e,r){for(var n={mapbox:this._unpackMapbox,terrarium:this._unpackTerrarium}[r],i=0;i<t.dim;i++)for(var o=0;o<t.dim;o++){var a=4*(i*t.dim+o);t.set(o,i,this.scale*n(e[a],e[a+1],e[a+2]));}},Pa.prototype.getPixels=function(){return new pi({width:this.level.dim+2*this.level.border,height:this.level.dim+2*this.level.border},new Uint8Array(this.level.data.buffer))},Pa.prototype.backfillBorder=function(t,e,r){var n=this.level,i=t.level;if(n.dim!==i.dim)throw new Error("level mismatch (dem dimension)");var o=e*n.dim,a=e*n.dim+n.dim,s=r*n.dim,u=r*n.dim+n.dim;switch(e){case-1:o=a-1;break;case 1:a=o+1;}switch(r){case-1:s=u-1;break;case 1:u=s+1;}for(var l=c(o,-n.border,n.dim+n.border),p=c(a,-n.border,n.dim+n.border),h=c(s,-n.border,n.dim+n.border),f=c(u,-n.border,n.dim+n.border),y=-e*n.dim,d=-r*n.dim,v=h;v<f;v++)for(var m=l;m<p;m++)n.set(m,v,i.get(m+y,v+d));},hr("DEMData",Pa);var Ta=function(t){this._stringToNumber={},this._numberToString=[];for(var e=0;e<t.length;e++){var r=t[e];this._stringToNumber[r]=e,this._numberToString[e]=r;}};Ta.prototype.encode=function(t){return this._stringToNumber[t]},Ta.prototype.decode=function(t){return this._numberToString[t]};var Oa=function(t,e,r,n){this.type="Feature",this._vectorTileFeature=t,t._z=e,t._x=r,t._y=n,this.properties=t.properties,null!=t.id&&(this.id=t.id);},La={geometry:{configurable:!0}};La.geometry.get=function(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry},La.geometry.set=function(t){this._geometry=t;},Oa.prototype.toJSON=function(){var t={geometry:this.geometry};for(var e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&(t[e]=this[e]);return t},Object.defineProperties(Oa.prototype,La);var ja=function(t,e,r){this.tileID=t,this.x=t.canonical.x,this.y=t.canonical.y,this.z=t.canonical.z,this.grid=e||new sr(Pn,16,0),this.featureIndexArray=r||new An;};function qa(t,e){return e-t}ja.prototype.insert=function(t,e,r,n,i){var o=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(r,n,i);for(var a=0;a<e.length;a++){for(var s=e[a],u=[1/0,1/0,-1/0,-1/0],l=0;l<s.length;l++){var p=s[l];u[0]=Math.min(u[0],p.x),u[1]=Math.min(u[1],p.y),u[2]=Math.max(u[2],p.x),u[3]=Math.max(u[3],p.y);}u[0]<Pn&&u[1]<Pn&&u[2]>=0&&u[3]>=0&&this.grid.insert(o,u[0],u[1],u[2],u[3]);}},ja.prototype.loadVTLayers=function(){return this.vtLayers||(this.vtLayers=new vo.VectorTile(new oa(this.rawTileData)).layers,this.sourceLayerCoder=new Ta(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])),this.vtLayers},ja.prototype.query=function(t,e){var r=this;this.loadVTLayers();for(var n=t.params||{},i=Pn/t.tileSize/t.scale,o=Te(n.filter),a=t.queryGeometry,s=t.queryPadding*i,u=1/0,l=1/0,p=-1/0,c=-1/0,h=0;h<a.length;h++)for(var f=a[h],y=0;y<f.length;y++){var d=f[y];u=Math.min(u,d.x),l=Math.min(l,d.y),p=Math.max(p,d.x),c=Math.max(c,d.y);}var v=this.grid.query(u-s,l-s,p+s,c+s);v.sort(qa);for(var m,g={},x=function(s){var u=v[s];if(u!==m){m=u;var l=r.featureIndexArray.get(u),p=null;r.loadMatchingFeature(g,l.bucketIndex,l.sourceLayerIndex,l.featureIndex,o,n.layers,e,function(e,n){return p||(p=Ln(e)),n.queryIntersectsFeature(a,e,p,r.z,t.transform,i,t.posMatrix)});}},b=0;b<v.length;b++)x(b);return g},ja.prototype.loadMatchingFeature=function(t,e,r,n,i,o,a,s){var u=this.bucketLayerIDs[e];if(!o||function(t,e){for(var r=0;r<t.length;r++)if(e.indexOf(t[r])>=0)return!0;return!1}(o,u)){var l=this.sourceLayerCoder.decode(r),p=this.vtLayers[l].feature(n);if(i(new Br(this.tileID.overscaledZ),p))for(var c=0;c<u.length;c++){var h=u[c];if(!(o&&o.indexOf(h)<0)){var f=a[h];if(f&&(!s||s(p,f))){var y=new Oa(p,this.z,this.x,this.y);y.layer=f.serialize();var d=t[h];void 0===d&&(d=t[h]=[]),d.push({featureIndex:n,feature:y});}}}}},ja.prototype.lookupSymbolFeatures=function(t,e,r,n,i,o){var a={};this.loadVTLayers();for(var s=Te(n),u=0,l=t;u<l.length;u+=1){var p=l[u];this.loadMatchingFeature(a,e,r,p,s,i,o);}return a},ja.prototype.hasLayer=function(t){for(var e=0,r=this.bucketLayerIDs;e<r.length;e+=1)for(var n=0,i=r[e];n<i.length;n+=1){if(t===i[n])return!0}return!1},hr("FeatureIndex",ja,{omit:["rawTileData","sourceLayerCoder"]});var Ra={horizontal:1,vertical:2,horizontalOnly:3};var Ua={9:!0,10:!0,11:!0,12:!0,13:!0,32:!0},Da={};function Na(t,e,r,n){var i=Math.pow(t-e,2);return n?t<e?i/2:2*i:i+Math.abs(r)*r}function Za(t,e){var r=0;return 10===t&&(r-=1e4),40!==t&&65288!==t||(r+=50),41!==e&&65289!==e||(r+=50),r}function Ka(t,e,r,n,i,o){for(var a=null,s=Na(e,r,i,o),u=0,l=n;u<l.length;u+=1){var p=l[u],c=Na(e-p.x,r,i,o)+p.badness;c<=s&&(a=p,s=c);}return{index:t,x:e,priorBreak:a,badness:s}}function Ja(t,e,r,n){if(!r)return[];if(!t)return[];for(var i,o=[],a=function(t,e,r,n){for(var i=0,o=0;o<t.length;o++){var a=n[t.charCodeAt(o)];a&&(i+=a.metrics.advance+e);}return i/Math.max(1,Math.ceil(i/r))}(t,e,r,n),s=0,u=0;u<t.length;u++){var l=t.charCodeAt(u),p=n[l];p&&!Ua[l]&&(s+=p.metrics.advance+e),u<t.length-1&&(Da[l]||!((i=l)<11904)&&(mr["Bopomofo Extended"](i)||mr.Bopomofo(i)||mr["CJK Compatibility Forms"](i)||mr["CJK Compatibility Ideographs"](i)||mr["CJK Compatibility"](i)||mr["CJK Radicals Supplement"](i)||mr["CJK Strokes"](i)||mr["CJK Symbols and Punctuation"](i)||mr["CJK Unified Ideographs Extension A"](i)||mr["CJK Unified Ideographs"](i)||mr["Enclosed CJK Letters and Months"](i)||mr["Halfwidth and Fullwidth Forms"](i)||mr.Hiragana(i)||mr["Ideographic Description Characters"](i)||mr["Kangxi Radicals"](i)||mr["Katakana Phonetic Extensions"](i)||mr.Katakana(i)||mr["Vertical Forms"](i)||mr["Yi Radicals"](i)||mr["Yi Syllables"](i)))&&o.push(Ka(u+1,s,a,o,Za(l,t.charCodeAt(u+1)),!1));}return function t(e){return e?t(e.priorBreak).concat(e.index):[]}(Ka(t.length,s,a,o,0,!0))}function $a(t){var e=.5,r=.5;switch(t){case"right":case"top-right":case"bottom-right":e=1;break;case"left":case"top-left":case"bottom-left":e=0;}switch(t){case"bottom":case"bottom-right":case"bottom-left":r=1;break;case"top":case"top-right":case"top-left":r=0;}return{horizontalAlign:e,verticalAlign:r}}function Ha(t,e,r,n,i){if(i){var o=e[t[n].glyph];if(o)for(var a=o.metrics.advance,s=(t[n].x+a)*i,u=r;u<=n;u++)t[u].x-=s;}}Da[10]=!0,Da[32]=!0,Da[38]=!0,Da[40]=!0,Da[41]=!0,Da[43]=!0,Da[45]=!0,Da[47]=!0,Da[173]=!0,Da[183]=!0,Da[8203]=!0,Da[8208]=!0,Da[8211]=!0,Da[8231]=!0,t.commonjsGlobal=e,t.unwrapExports=r,t.createCommonjsModule=n,t.default=self,t.default$1=s,t.getJSON=function(t,e){var r=z(t);return r.setRequestHeader("Accept","application/json"),r.onerror=function(){e(new Error(r.statusText));},r.onload=function(){if(r.status>=200&&r.status<300&&r.response){var n;try{n=JSON.parse(r.response);}catch(t){return e(t)}e(null,n);}else 401===r.status&&t.url.match(/mapbox.com/)?e(new k(r.statusText+": you may have provided an invalid Mapbox access token. See https://www.mapbox.com/api-documentation/#access-tokens",r.status,t.url)):e(new k(r.statusText,r.status,t.url));},r.send(),r},t.getImage=function(t,e){return S(t,function(t,r){if(t)e(t);else if(r){var n=new self.Image,i=self.URL||self.webkitURL;n.onload=function(){e(null,n),i.revokeObjectURL(n.src);};var o=new self.Blob([new Uint8Array(r.data)],{type:"image/png"});n.cacheControl=r.cacheControl,n.expires=r.expires,n.src=r.data.byteLength?i.createObjectURL(o):"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";}})},t.ResourceType=A,t.RGBAImage=pi,t.default$2=Qo,t.ImagePosition=ta,t.getArrayBuffer=S,t.default$3=function(t){return new oa(t).readFields(Aa,[])},t.default$4=mr,t.asyncAll=function(t,e,r){if(!t.length)return r(null,[]);var n=t.length,i=new Array(t.length),o=null;t.forEach(function(t,a){e(t,function(t,e){t&&(o=t),i[a]=e,0==--n&&r(o,i);});});},t.AlphaImage=li,t.default$5=E,t.endsWith=d,t.extend=h,t.sphericalToCartesian=function(t){var e=t[0],r=t[1],n=t[2];return r+=90,r*=Math.PI/180,n*=Math.PI/180,{x:e*Math.cos(r)*Math.sin(n),y:e*Math.sin(r)*Math.sin(n),z:e*Math.cos(n)}},t.Evented=I,t.validateStyle=rr,t.validateLight=nr,t.emitValidationErrors=ar,t.default$6=Q,t.number=wt,t.Properties=Dr,t.Transitionable=Er,t.Transitioning=Pr,t.PossiblyEvaluated=Lr,t.DataConstantProperty=jr,t.warnOnce=b,t.uniqueId=function(){return f++},t.default$7=Ma,t.pick=function(t,e){for(var r={},n=0;n<e.length;n++){var i=e[n];i in t&&(r[i]=t[i]);}return r},t.wrap=function(t,e,r){var n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i},t.clamp=c,t.Event=B,t.ErrorEvent=C,t.OverscaledTileID=Ia,t.default$8=Pn,t.createLayout=$r,t.getCoordinatesCenter=function(t){for(var e=1/0,r=1/0,n=-1/0,i=-1/0,o=0;o<t.length;o++)e=Math.min(e,t[o].column),r=Math.min(r,t[o].row),n=Math.max(n,t[o].column),i=Math.max(i,t[o].row);var s=n-e,u=i-r,l=Math.max(s,u),p=Math.max(0,Math.floor(-Math.log(l)/Math.LN2));return new a((e+n)/2,(r+i)/2,0).zoomTo(p)},t.CanonicalTileID=Ba,t.RasterBoundsArray=Gr,t.getVideo=function(t,e){var r,n,i=self.document.createElement("video");i.onloadstart=function(){e(null,i);};for(var o=0;o<t.length;o++){var a=self.document.createElement("source");r=t[o],n=void 0,(n=self.document.createElement("a")).href=r,(n.protocol!==self.document.location.protocol||n.host!==self.document.location.host)&&(i.crossOrigin="Anonymous"),a.src=t[o],i.appendChild(a);}return i},t.default$9=F,t.bindAll=y,t.default$10=function t(e,r){if(Array.isArray(e)){if(!Array.isArray(r)||e.length!==r.length)return!1;for(var n=0;n<e.length;n++)if(!t(e[n],r[n]))return!1;return!0}if("object"==typeof e&&null!==e&&null!==r){if("object"!=typeof r)return!1;if(Object.keys(e).length!==Object.keys(r).length)return!1;for(var i in e)if(!t(e[i],r[i]))return!1;return!0}return e===r},t.parseCacheControl=function(t){var e={};if(t.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,function(t,r,n,i){var o=n||i;return e[r]=!o||o.toLowerCase(),""}),e["max-age"]){var r=parseInt(e["max-age"],10);isNaN(r)?delete e["max-age"]:e["max-age"]=r;}return e},t.default$11=ja,t.default$12=Oa,t.default$13=Te,t.default$14=Ko,t.CollisionBoxArray=dn,t.default$15=zn,t.TriangleIndexArray=pn,t.default$16=Br,t.default$17=a,t.keysDifference=function(t,e){var r=[];for(var n in t)n in e||r.push(n);return r},t.default$18=["type","source","source-layer","minzoom","maxzoom","filter","layout"],t.mat4=ri,t.vec4=ei,t.getSizeData=jo,t.evaluateSizeForFeature=function(t,e,r){var n=e;return"source"===t.functionType?r.lowerSize/10:"composite"===t.functionType?wt(r.lowerSize/10,r.upperSize/10,n.uSizeT):n.uSize},t.evaluateSizeForZoom=function(t,e,r){if("constant"===t.functionType)return{uSizeT:0,uSize:t.layoutSize};if("source"===t.functionType)return{uSizeT:0,uSize:0};if("camera"===t.functionType){var n=t.propertyValue,i=t.zoomRange,o=t.sizeRange,a=c(Se(n,r.specification).interpolationFactor(e,i.min,i.max),0,1);return{uSizeT:0,uSize:o.min+a*(o.max-o.min)}}var s=t.propertyValue,u=t.zoomRange;return{uSizeT:c(Se(s,r.specification).interpolationFactor(e,u.min,u.max),0,1),uSize:0}},t.addDynamicAttributes=Do,t.default$19=$o,t.WritingMode=Ra,t.multiPolygonIntersectsBufferedPoint=Rn,t.multiPolygonIntersectsMultiPolygon=Un,t.multiPolygonIntersectsBufferedMultiLine=Dn,t.polygonIntersectsPolygon=function(t,e){for(var r=0;r<t.length;r++)if(Xn(e,t[r]))return!0;for(var n=0;n<e.length;n++)if(Xn(t,e[n]))return!0;return!!Zn(t,e)},t.distToSegmentSquared=$n,t.default$20=ti,t.default$21=Nr,t.default$22=function(t){return new Wo[t.type](t)},t.clone=g,t.filterObject=m,t.mapObject=v,t.registerForPluginAvailability=function(t){return zr?t({pluginURL:zr,completionCallback:Ar}):Mr.once("pluginAvailable",t),t},t.evented=Mr,t.default$23=vr,t.default$24=In,t.PosArray=Xr,t.UnwrappedTileID=Ca,t.ease=p,t.bezier=l,t.setRTLTextPlugin=function(t,e){if(kr)throw new Error("setRTLTextPlugin cannot be called multiple times.");kr=!0,zr=t,Ar=function(t){t?(kr=!1,zr=null,e&&e(t)):Sr=!0;},Mr.fire(new B("pluginAvailable",{pluginURL:zr,completionCallback:Ar}));},t.values=function(t){var e=[];for(var r in t)e.push(t[r]);return e},t.default$25=Lo,t.register=hr,t.GLYPH_PBF_BORDER=Sa,t.shapeText=function(t,e,r,n,i,o,a,s,u,l){var p=t.trim();l===Ra.vertical&&(p=function(t){for(var e="",r=0;r<t.length;r++){var n=t.charCodeAt(r+1)||null,i=t.charCodeAt(r-1)||null;n&&wr(n)&&!Oo[t[r+1]]||i&&wr(i)&&!Oo[t[r-1]]||!Oo[t[r]]?e+=t[r]:e+=Oo[t[r]];}return e}(p));var c=[],h={positionedGlyphs:c,text:p,top:s[1],bottom:s[1],left:s[0],right:s[0],writingMode:l},f=Vr.processBidirectionalText;return function(t,e,r,n,i,o,a,s,u){for(var l=0,p=-17,c=0,h=t.positionedGlyphs,f="right"===o?1:"left"===o?0:.5,y=0,d=r;y<d.length;y+=1){var v=d[y];if((v=v.trim()).length){for(var m=h.length,g=0;g<v.length;g++){var x=v.charCodeAt(g),b=e[x];b&&(br(x)&&a!==Ra.horizontal?(h.push({glyph:x,x:l,y:0,vertical:!0}),l+=u+s):(h.push({glyph:x,x:l,y:p,vertical:!1}),l+=b.metrics.advance+s));}if(h.length!==m){var w=l-s;c=Math.max(w,c),Ha(h,e,m,h.length-1,f);}l=0,p+=n;}else p+=n;}var _=$a(i),A=_.horizontalAlign,k=_.verticalAlign;!function(t,e,r,n,i,o,a){for(var s=(e-r)*i,u=(-n*a+.5)*o,l=0;l<t.length;l++)t[l].x+=s,t[l].y+=u;}(h,f,A,k,c,n,r.length);var z=r.length*n;t.top+=-k*z,t.bottom=t.top+z,t.left+=-A*c,t.right=t.left+c;}(h,e,f?f(p,Ja(p,a,r,e)):function(t,e){for(var r=[],n=0,i=0,o=e;i<o.length;i+=1){var a=o[i];r.push(t.substring(n,a)),n=a;}return n<t.length&&r.push(t.substring(n,t.length)),r}(p,Ja(p,a,r,e)),n,i,o,l,a,u),!!c.length&&h},t.shapeIcon=function(t,e,r){var n=$a(r),i=n.horizontalAlign,o=n.verticalAlign,a=e[0],s=e[1],u=a-t.displaySize[0]*i,l=u+t.displaySize[0],p=s-t.displaySize[1]*o;return{image:t,top:p,bottom:p+t.displaySize[1],left:u,right:l}},t.allowsVerticalWritingMode=gr,t.allowsLetterSpacing=function(t){for(var e=0,r=t;e<r.length;e+=1)if(!xr(r[e].charCodeAt(0)))return!1;return!0},t.default$26=$i,t.default$27=Ta,t.default$28=ra,t.default$29=vo,t.default$30=oa,t.default$31=Pa,t.__moduleExports=vo,t.default$32=s,t.__moduleExports$1=oa,t.plugin=Vr;});

define(["./chunk1.js"],function(e){"use strict";function t(e){var i=typeof e;if("number"===i||"boolean"===i||"string"===i||null==e)return JSON.stringify(e);if(Array.isArray(e)){for(var r="[",n=0,o=e;n<o.length;n+=1){r+=t(o[n])+",";}return r+"]"}for(var a=Object.keys(e).sort(),s="{",l=0;l<a.length;l++)s+=JSON.stringify(a[l])+":"+t(e[a[l]])+",";return s+"}"}function i(i){for(var r="",n=0,o=e.default$18;n<o.length;n+=1){r+="/"+t(i[o[n]]);}return r}var r=function(e){e&&this.replace(e);};function n(e,t,i,r,n){if(void 0===t.segment)return!0;for(var o=t,a=t.segment+1,s=0;s>-i/2;){if(--a<0)return!1;s-=e[a].dist(o),o=e[a];}s+=e[a].dist(e[a+1]),a++;for(var l=[],u=0;s<i/2;){var h=e[a-1],c=e[a],f=e[a+1];if(!f)return!1;var p=h.angleTo(c)-c.angleTo(f);for(p=Math.abs((p+3*Math.PI)%(2*Math.PI)-Math.PI),l.push({distance:s,angleDelta:p}),u+=p;s-l[0].distance>r;)u-=l.shift().angleDelta;if(u>n)return!1;a++,s+=c.dist(f);}return!0}function o(t,i,r,o,a,s,l,u,h){var c=o?.6*s*l:0,f=Math.max(o?o.right-o.left:0,a?a.right-a.left:0),p=0===t[0].x||t[0].x===h||0===t[0].y||t[0].y===h;return i-f*l<i/4&&(i=f*l+i/4),function t(i,r,o,a,s,l,u,h,c){var f=l/2;var p=0;for(var d=0;d<i.length-1;d++)p+=i[d].dist(i[d+1]);var g=0,v=r-o;var y=[];for(var m=0;m<i.length-1;m++){for(var x=i[m],w=i[m+1],S=x.dist(w),M=w.angleTo(x);v+o<g+S;){var b=((v+=o)-g)/S,_=e.number(x.x,w.x,b),I=e.number(x.y,w.y,b);if(_>=0&&_<c&&I>=0&&I<c&&v-f>=0&&v+f<=p){var z=new e.default$25(_,I,M,m);z._round(),a&&!n(i,z,l,a,s)||y.push(z);}}g+=S;}h||y.length||u||(y=t(i,g/2,o,a,s,l,u,!0,c));return y}(t,p?i/2*u%i:(f/2+2*s)*l*u%i,i,c,r,f*l,p,!1,h)}r.prototype.replace=function(e){this._layerConfigs={},this._layers={},this.update(e,[]);},r.prototype.update=function(t,r){for(var n=this,o=0,a=t;o<a.length;o+=1){var s=a[o];n._layerConfigs[s.id]=s;var l=n._layers[s.id]=e.default$22(s);l._featureFilter=e.default$13(l.filter);}for(var u=0,h=r;u<h.length;u+=1){var c=h[u];delete n._layerConfigs[c],delete n._layers[c];}this.familiesBySource={};for(var f=0,p=function(e){for(var t={},r=0;r<e.length;r++){var n=i(e[r]),o=t[n];o||(o=t[n]=[]),o.push(e[r]);}var a=[];for(var s in t)a.push(t[s]);return a}(e.values(this._layerConfigs));f<p.length;f+=1){var d=p[f].map(function(e){return n._layers[e.id]}),g=d[0];if("none"!==g.visibility){var v=g.source||"",y=n.familiesBySource[v];y||(y=n.familiesBySource[v]={});var m=g.sourceLayer||"_geojsonTileLayer",x=y[m];x||(x=y[m]=[]),x.push(d);}}};var a=function(){this.opacity=0,this.targetOpacity=0,this.time=0;};a.prototype.clone=function(){var e=new a;return e.opacity=this.opacity,e.targetOpacity=this.targetOpacity,e.time=this.time,e},e.register("OpacityState",a);var s=function(e,t,i,r,n,o,a,s,l,u,h){var c=a.top*s-l,f=a.bottom*s+l,p=a.left*s-l,d=a.right*s+l;if(this.boxStartIndex=e.length,u){var g=f-c,v=d-p;g>0&&(g=Math.max(10*s,g),this._addLineCollisionCircles(e,t,i,i.segment,v,g,r,n,o,h));}else e.emplaceBack(i.x,i.y,p,c,d,f,r,n,o,0,0);this.boxEndIndex=e.length;};s.prototype._addLineCollisionCircles=function(e,t,i,r,n,o,a,s,l,u){var h=o/2,c=Math.floor(n/h),f=1+.4*Math.log(u)/Math.LN2,p=Math.floor(c*f/2),d=-o/2,g=i,v=r+1,y=d,m=-n/2,x=m-n/4;do{if(--v<0){if(y>m)return;v=0;break}y-=t[v].dist(g),g=t[v];}while(y>x);for(var w=t[v].dist(t[v+1]),S=-p;S<c+p;S++){var M=S*h,b=m+M;if(M<0&&(b+=M),M>n&&(b+=M-n),!(b<y)){for(;y+w<b;){if(y+=w,++v+1>=t.length)return;w=t[v].dist(t[v+1]);}var _=b-y,I=t[v],z=t[v+1].sub(I)._unit()._mult(_)._add(I)._round(),T=Math.abs(b-d)<h?0:.8*(b-d);e.emplaceBack(z.x,z.y,-o/2,-o/2,o/2,o/2,a,s,l,o/2,T);}}};var l=h,u=h;function h(e,t){if(!(this instanceof h))return new h(e,t);if(this.data=e||[],this.length=this.data.length,this.compare=t||c,this.length>0)for(var i=(this.length>>1)-1;i>=0;i--)this._down(i);}function c(e,t){return e<t?-1:e>t?1:0}function f(t,i,r){void 0===i&&(i=1),void 0===r&&(r=!1);for(var n=1/0,o=1/0,a=-1/0,s=-1/0,u=t[0],h=0;h<u.length;h++){var c=u[h];(!h||c.x<n)&&(n=c.x),(!h||c.y<o)&&(o=c.y),(!h||c.x>a)&&(a=c.x),(!h||c.y>s)&&(s=c.y);}var f=a-n,g=s-o,v=Math.min(f,g),y=v/2,m=new l(null,p);if(0===v)return new e.default$1(n,o);for(var x=n;x<a;x+=v)for(var w=o;w<s;w+=v)m.push(new d(x+y,w+y,y,t));for(var S=function(e){for(var t=0,i=0,r=0,n=e[0],o=0,a=n.length,s=a-1;o<a;s=o++){var l=n[o],u=n[s],h=l.x*u.y-u.x*l.y;i+=(l.x+u.x)*h,r+=(l.y+u.y)*h,t+=3*h;}return new d(i/t,r/t,0,e)}(t),M=m.length;m.length;){var b=m.pop();(b.d>S.d||!S.d)&&(S=b,r&&console.log("found best %d after %d probes",Math.round(1e4*b.d)/1e4,M)),b.max-S.d<=i||(y=b.h/2,m.push(new d(b.p.x-y,b.p.y-y,y,t)),m.push(new d(b.p.x+y,b.p.y-y,y,t)),m.push(new d(b.p.x-y,b.p.y+y,y,t)),m.push(new d(b.p.x+y,b.p.y+y,y,t)),M+=4);}return r&&(console.log("num probes: "+M),console.log("best distance: "+S.d)),S.p}function p(e,t){return t.max-e.max}function d(t,i,r,n){this.p=new e.default$1(t,i),this.h=r,this.d=function(t,i){for(var r=!1,n=1/0,o=0;o<i.length;o++)for(var a=i[o],s=0,l=a.length,u=l-1;s<l;u=s++){var h=a[s],c=a[u];h.y>t.y!=c.y>t.y&&t.x<(c.x-h.x)*(t.y-h.y)/(c.y-h.y)+h.x&&(r=!r),n=Math.min(n,e.distToSegmentSquared(t,h,c));}return(r?1:-1)*Math.sqrt(n)}(this.p,n),this.max=this.d+this.h*Math.SQRT2;}function g(t,i,r,n,o,a){t.createArrays(),t.symbolInstances=[];var s=512*t.overscaling;t.tilePixelRatio=e.default$8/s,t.compareText={},t.iconsNeedLinear=!1;var l=t.layers[0].layout,u=t.layers[0]._unevaluatedLayout._values,h={};if("composite"===t.textSizeData.functionType){var c=t.textSizeData.zoomRange,f=c.min,p=c.max;h.compositeTextSizes=[u["text-size"].possiblyEvaluate(new e.default$16(f)),u["text-size"].possiblyEvaluate(new e.default$16(p))];}if("composite"===t.iconSizeData.functionType){var d=t.iconSizeData.zoomRange,g=d.min,y=d.max;h.compositeIconSizes=[u["icon-size"].possiblyEvaluate(new e.default$16(g)),u["icon-size"].possiblyEvaluate(new e.default$16(y))];}h.layoutTextSize=u["text-size"].possiblyEvaluate(new e.default$16(t.zoom+1)),h.layoutIconSize=u["icon-size"].possiblyEvaluate(new e.default$16(t.zoom+1)),h.textMaxSize=u["text-size"].possiblyEvaluate(new e.default$16(18));for(var m=24*l.get("text-line-height"),x="map"===l.get("text-rotation-alignment")&&"line"===l.get("symbol-placement"),w=l.get("text-keep-upright"),S=0,M=t.features;S<M.length;S+=1){var b=M[S],_=l.get("text-font").evaluate(b).join(","),I=i[_]||{},z=r[_]||{},T={},P=b.text;if(P){var k=l.get("text-offset").evaluate(b).map(function(e){return 24*e}),L=24*l.get("text-letter-spacing").evaluate(b),$=e.allowsLetterSpacing(P)?L:0,D=l.get("text-anchor").evaluate(b),O=l.get("text-justify").evaluate(b),C="line"!==l.get("symbol-placement")?24*l.get("text-max-width").evaluate(b):0;T.horizontal=e.shapeText(P,I,C,m,D,O,$,k,24,e.WritingMode.horizontal),e.allowsVerticalWritingMode(P)&&x&&w&&(T.vertical=e.shapeText(P,I,C,m,D,O,$,k,24,e.WritingMode.vertical));}var A=void 0;if(b.icon){var E=n[b.icon];E&&(A=e.shapeIcon(o[b.icon],l.get("icon-offset").evaluate(b),l.get("icon-anchor").evaluate(b)),void 0===t.sdfIcons?t.sdfIcons=E.sdf:t.sdfIcons!==E.sdf&&e.warnOnce("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"),E.pixelRatio!==t.pixelRatio?t.iconsNeedLinear=!0:0!==l.get("icon-rotate").constantOr(1)&&(t.iconsNeedLinear=!0));}(T.horizontal||A)&&v(t,b,T,A,z,h);}a&&t.generateCollisionDebugBuffers();}function v(t,i,r,n,l,u){var h=u.layoutTextSize.evaluate(i),c=u.layoutIconSize.evaluate(i),p=u.textMaxSize.evaluate(i);void 0===p&&(p=h);var d=t.layers[0].layout,g=d.get("text-offset").evaluate(i),v=d.get("icon-offset").evaluate(i),x=h/24,w=t.tilePixelRatio*x,S=t.tilePixelRatio*p/24,M=t.tilePixelRatio*c,b=t.tilePixelRatio*d.get("symbol-spacing"),_=d.get("text-padding")*t.tilePixelRatio,I=d.get("icon-padding")*t.tilePixelRatio,z=d.get("text-max-angle")/180*Math.PI,T="map"===d.get("text-rotation-alignment")&&"line"===d.get("symbol-placement"),P="map"===d.get("icon-rotation-alignment")&&"line"===d.get("symbol-placement"),k=b/2,L=function(o,h){h.x<0||h.x>=e.default$8||h.y<0||h.y>=e.default$8||t.symbolInstances.push(function(t,i,r,n,o,l,u,h,c,f,p,d,g,v,m,x,w,S,M,b,_){var I,z,T=t.addToLineVertexArray(i,r),P=0,k=0,L=0,$=n.horizontal?n.horizontal.text:"",D=[];n.horizontal&&(I=new s(u,r,i,h,c,f,n.horizontal,p,d,g,t.overscaling),k+=y(t,i,n.horizontal,l,g,M,v,T,n.vertical?e.WritingMode.horizontal:e.WritingMode.horizontalOnly,D,b,_),n.vertical&&(L+=y(t,i,n.vertical,l,g,M,v,T,e.WritingMode.vertical,D,b,_)));var O=I?I.boxStartIndex:t.collisionBoxArray.length,C=I?I.boxEndIndex:t.collisionBoxArray.length;if(o){var A=function(t,i,r,n,o,a){var s,l,u,h,c=i.image,f=r.layout,p=i.top-1/c.pixelRatio,d=i.left-1/c.pixelRatio,g=i.bottom+1/c.pixelRatio,v=i.right+1/c.pixelRatio;if("none"!==f.get("icon-text-fit")&&o){var y=v-d,m=g-p,x=f.get("text-size").evaluate(a)/24,w=o.left*x,S=o.right*x,M=o.top*x,b=S-w,_=o.bottom*x-M,I=f.get("icon-text-fit-padding")[0],z=f.get("icon-text-fit-padding")[1],T=f.get("icon-text-fit-padding")[2],P=f.get("icon-text-fit-padding")[3],k="width"===f.get("icon-text-fit")?.5*(_-m):0,L="height"===f.get("icon-text-fit")?.5*(b-y):0,$="width"===f.get("icon-text-fit")||"both"===f.get("icon-text-fit")?b:y,D="height"===f.get("icon-text-fit")||"both"===f.get("icon-text-fit")?_:m;s=new e.default$1(w+L-P,M+k-I),l=new e.default$1(w+L+z+$,M+k-I),u=new e.default$1(w+L+z+$,M+k+T+D),h=new e.default$1(w+L-P,M+k+T+D);}else s=new e.default$1(d,p),l=new e.default$1(v,p),u=new e.default$1(v,g),h=new e.default$1(d,g);var O=r.layout.get("icon-rotate").evaluate(a)*Math.PI/180;if(O){var C=Math.sin(O),A=Math.cos(O),E=[A,-C,C,A];s._matMult(E),l._matMult(E),h._matMult(E),u._matMult(E);}return[{tl:s,tr:l,bl:h,br:u,tex:c.paddedRect,writingMode:void 0,glyphOffset:[0,0]}]}(0,o,l,0,n.horizontal,M);z=new s(u,r,i,h,c,f,o,m,x,!1,t.overscaling),P=4*A.length;var E=t.iconSizeData,N=null;"source"===E.functionType?N=[10*l.layout.get("icon-size").evaluate(M)]:"composite"===E.functionType&&(N=[10*_.compositeIconSizes[0].evaluate(M),10*_.compositeIconSizes[1].evaluate(M)]),t.addSymbols(t.icon,A,N,S,w,M,!1,i,T.lineStartIndex,T.lineLength);}var R=z?z.boxStartIndex:t.collisionBoxArray.length,B=z?z.boxEndIndex:t.collisionBoxArray.length;t.glyphOffsetArray.length>=e.default$14.MAX_GLYPHS&&e.warnOnce("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907");var F=new a,G=new a;return{key:$,textBoxStartIndex:O,textBoxEndIndex:C,iconBoxStartIndex:R,iconBoxEndIndex:B,textOffset:v,iconOffset:S,anchor:i,line:r,featureIndex:h,feature:M,numGlyphVertices:k,numVerticalGlyphVertices:L,numIconVertices:P,textOpacityState:F,iconOpacityState:G,isDuplicate:!1,placedTextSymbolIndices:D,crossTileID:0}}(t,h,o,r,n,t.layers[0],t.collisionBoxArray,i.index,i.sourceLayerIndex,t.index,w,_,T,g,M,I,P,v,i,l,u));};if("line"===d.get("symbol-placement"))for(var $=0,D=function(t,i,r,n,o){for(var a=[],s=0;s<t.length;s++)for(var l=t[s],u=void 0,h=0;h<l.length-1;h++){var c=l[h],f=l[h+1];c.x<i&&f.x<i||(c.x<i?c=new e.default$1(i,c.y+(f.y-c.y)*((i-c.x)/(f.x-c.x)))._round():f.x<i&&(f=new e.default$1(i,c.y+(f.y-c.y)*((i-c.x)/(f.x-c.x)))._round()),c.y<r&&f.y<r||(c.y<r?c=new e.default$1(c.x+(f.x-c.x)*((r-c.y)/(f.y-c.y)),r)._round():f.y<r&&(f=new e.default$1(c.x+(f.x-c.x)*((r-c.y)/(f.y-c.y)),r)._round()),c.x>=n&&f.x>=n||(c.x>=n?c=new e.default$1(n,c.y+(f.y-c.y)*((n-c.x)/(f.x-c.x)))._round():f.x>=n&&(f=new e.default$1(n,c.y+(f.y-c.y)*((n-c.x)/(f.x-c.x)))._round()),c.y>=o&&f.y>=o||(c.y>=o?c=new e.default$1(c.x+(f.x-c.x)*((o-c.y)/(f.y-c.y)),o)._round():f.y>=o&&(f=new e.default$1(c.x+(f.x-c.x)*((o-c.y)/(f.y-c.y)),o)._round()),u&&c.equals(u[u.length-1])||(u=[c],a.push(u)),u.push(f)))));}return a}(i.geometry,0,0,e.default$8,e.default$8);$<D.length;$+=1)for(var O=D[$],C=0,A=o(O,b,z,r.vertical||r.horizontal,n,24,S,t.overscaling,e.default$8);C<A.length;C+=1){var E=A[C],N=r.horizontal;N&&m(t,N.text,k,E)||L(O,E);}else if("Polygon"===i.type)for(var R=0,B=e.default$26(i.geometry,0);R<B.length;R+=1){var F=B[R],G=f(F,16);L(F[0],new e.default$25(G.x,G.y,0));}else if("LineString"===i.type)for(var V=0,J=i.geometry;V<J.length;V+=1){var W=J[V];L(W,new e.default$25(W[0].x,W[0].y,0));}else if("Point"===i.type)for(var Y=0,Z=i.geometry;Y<Z.length;Y+=1)for(var j=0,X=Z[Y];j<X.length;j+=1){var q=X[j];L([q],new e.default$25(q.x,q.y,0));}}function y(t,i,r,n,o,a,s,l,u,h,c,f){var p=function(t,i,r,n,o,a){for(var s=r.layout.get("text-rotate").evaluate(o)*Math.PI/180,l=r.layout.get("text-offset").evaluate(o).map(function(e){return 24*e}),u=i.positionedGlyphs,h=[],c=0;c<u.length;c++){var f=u[c],p=a[f.glyph];if(p){var d=p.rect;if(d){var g=e.GLYPH_PBF_BORDER+1,v=p.metrics.advance/2,y=n?[f.x+v,f.y]:[0,0],m=n?[0,0]:[f.x+v+l[0],f.y+l[1]],x=p.metrics.left-g-v+m[0],w=-p.metrics.top-g+m[1],S=x+d.w,M=w+d.h,b=new e.default$1(x,w),_=new e.default$1(S,w),I=new e.default$1(x,M),z=new e.default$1(S,M);if(n&&f.vertical){var T=new e.default$1(-v,v),P=-Math.PI/2,k=new e.default$1(5,0);b._rotateAround(P,T)._add(k),_._rotateAround(P,T)._add(k),I._rotateAround(P,T)._add(k),z._rotateAround(P,T)._add(k);}if(s){var L=Math.sin(s),$=Math.cos(s),D=[$,-L,L,$];b._matMult(D),_._matMult(D),I._matMult(D),z._matMult(D);}h.push({tl:b,tr:_,bl:I,br:z,tex:d,writingMode:i.writingMode,glyphOffset:y});}}}return h}(0,r,n,o,a,c),d=t.textSizeData,g=null;return"source"===d.functionType?g=[10*n.layout.get("text-size").evaluate(a)]:"composite"===d.functionType&&(g=[10*f.compositeTextSizes[0].evaluate(a),10*f.compositeTextSizes[1].evaluate(a)]),t.addSymbols(t.text,p,g,s,o,a,u,i,l.lineStartIndex,l.lineLength),h.push(t.text.placedSymbolArray.length-1),4*p.length}function m(e,t,i,r){var n=e.compareText;if(t in n){for(var o=n[t],a=o.length-1;a>=0;a--)if(r.dist(o[a])<i)return!0}else n[t]=[];return n[t].push(r),!1}h.prototype={push:function(e){this.data.push(e),this.length++,this._up(this.length-1);},pop:function(){if(0!==this.length){var e=this.data[0];return this.length--,this.length>0&&(this.data[0]=this.data[this.length],this._down(0)),this.data.pop(),e}},peek:function(){return this.data[0]},_up:function(e){for(var t=this.data,i=this.compare,r=t[e];e>0;){var n=e-1>>1,o=t[n];if(i(r,o)>=0)break;t[e]=o,e=n;}t[e]=r;},_down:function(e){for(var t=this.data,i=this.compare,r=this.length>>1,n=t[e];e<r;){var o=1+(e<<1),a=o+1,s=t[o];if(a<this.length&&i(t[a],s)<0&&(o=a,s=t[a]),i(s,n)>=0)break;t[e]=s,e=o;}t[e]=n;}},l.default=u;var x=function(t){var i=new e.AlphaImage({width:0,height:0}),r={},n=new e.default$2(0,0,{autoResize:!0});for(var o in t){var a=t[o],s=r[o]={};for(var l in a){var u=a[+l];if(u&&0!==u.bitmap.width&&0!==u.bitmap.height){var h=n.packOne(u.bitmap.width+2,u.bitmap.height+2);i.resize({width:n.w,height:n.h}),e.AlphaImage.copy(u.bitmap,i,{x:0,y:0},{x:h.x+1,y:h.y+1},u.bitmap),s[l]={rect:h,metrics:u.metrics};}}}n.shrink(),i.resize({width:n.w,height:n.h}),this.image=i,this.positions=r;};e.register("GlyphAtlas",x);var w=function(t){this.tileID=new e.OverscaledTileID(t.tileID.overscaledZ,t.tileID.wrap,t.tileID.canonical.z,t.tileID.canonical.x,t.tileID.canonical.y),this.uid=t.uid,this.zoom=t.zoom,this.pixelRatio=t.pixelRatio,this.tileSize=t.tileSize,this.source=t.source,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=t.showCollisionBoxes,this.collectResourceTiming=!!t.collectResourceTiming;};function S(t,i){for(var r=new e.default$16(i),n=0,o=t;n<o.length;n+=1){o[n].recalculate(r);}}w.prototype.parse=function(t,i,r,n){var o=this;this.status="parsing",this.data=t,this.collisionBoxArray=new e.CollisionBoxArray;var a=new e.default$27(Object.keys(t.layers).sort()),s=new e.default$11(this.tileID);s.bucketLayerIDs=[];var l,u,h,c={},f={featureIndex:s,iconDependencies:{},glyphDependencies:{}},p=i.familiesBySource[this.source];for(var d in p){var v=t.layers[d];if(v){1===v.version&&e.warnOnce('Vector tile source "'+o.source+'" layer "'+d+'" does not use vector tile spec v2 and therefore may have some rendering errors.');for(var y=a.encode(d),m=[],w=0;w<v.length;w++){var M=v.feature(w);m.push({feature:M,index:w,sourceLayerIndex:y});}for(var b=0,_=p[d];b<_.length;b+=1){var I=_[b],z=I[0];if(!(z.minzoom&&o.zoom<Math.floor(z.minzoom)))if(!(z.maxzoom&&o.zoom>=z.maxzoom))if("none"!==z.visibility)S(I,o.zoom),(c[z.id]=z.createBucket({index:s.bucketLayerIDs.length,layers:I,zoom:o.zoom,pixelRatio:o.pixelRatio,overscaling:o.overscaling,collisionBoxArray:o.collisionBoxArray,sourceLayerIndex:y})).populate(m,f),s.bucketLayerIDs.push(I.map(function(e){return e.id}));}}}var T=e.mapObject(f.glyphDependencies,function(e){return Object.keys(e).map(Number)});Object.keys(T).length?r.send("getGlyphs",{uid:this.uid,stacks:T},function(e,t){l||(l=e,u=t,k.call(o));}):u={};var P=Object.keys(f.iconDependencies);function k(){if(l)return n(l);if(u&&h){var t=new x(u),i=new e.default$28(h);for(var r in c){var o=c[r];o instanceof e.default$14&&(S(o.layers,this.zoom),g(o,u,t.positions,h,i.positions,this.showCollisionBoxes));}this.status="done",n(null,{buckets:e.values(c).filter(function(e){return!e.isEmpty()}),featureIndex:s,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:t.image,iconAtlasImage:i.image});}}P.length?r.send("getImages",{icons:P},function(e,t){l||(l=e,h=t,k.call(o));}):h={},k.call(this);};var M=function(e){return!(!performance||!performance.getEntriesByName)&&performance.getEntriesByName(e)};function b(t,i){var r=e.getArrayBuffer(t.request,function(t,r){t?i(t):r&&i(null,{vectorTile:new e.default$29.VectorTile(new e.default$30(r.data)),rawData:r.data,cacheControl:r.cacheControl,expires:r.expires});});return function(){r.abort(),i();}}var _=function(e,t,i){this.actor=e,this.layerIndex=t,this.loadVectorData=i||b,this.loading={},this.loaded={};};_.prototype.loadTile=function(t,i){var r=this,n=t.uid;this.loading||(this.loading={});var o=this.loading[n]=new w(t);o.abort=this.loadVectorData(t,function(a,s){if(delete r.loading[n],a||!s)return i(a);var l=s.rawData,u={};s.expires&&(u.expires=s.expires),s.cacheControl&&(u.cacheControl=s.cacheControl);var h={};if(t.request&&t.request.collectResourceTiming){var c=M(t.request.url);c&&(h.resourceTiming=JSON.parse(JSON.stringify(c)));}o.vectorTile=s.vectorTile,o.parse(s.vectorTile,r.layerIndex,r.actor,function(t,r){if(t||!r)return i(t);i(null,e.extend({rawTileData:l.slice(0)},r,u,h));}),r.loaded=r.loaded||{},r.loaded[n]=o;});},_.prototype.reloadTile=function(e,t){var i=this.loaded,r=e.uid,n=this;if(i&&i[r]){var o=i[r];o.showCollisionBoxes=e.showCollisionBoxes;var a=function(e,i){var r=o.reloadCallback;r&&(delete o.reloadCallback,o.parse(o.vectorTile,n.layerIndex,n.actor,r)),t(e,i);};"parsing"===o.status?o.reloadCallback=a:"done"===o.status&&o.parse(o.vectorTile,this.layerIndex,this.actor,a);}},_.prototype.abortTile=function(e,t){var i=this.loading,r=e.uid;i&&i[r]&&i[r].abort&&(i[r].abort(),delete i[r]),t();},_.prototype.removeTile=function(e,t){var i=this.loaded,r=e.uid;i&&i[r]&&delete i[r],t();};var I=function(){this.loading={},this.loaded={};};I.prototype.loadTile=function(t,i){var r=t.uid,n=t.encoding,o=new e.default$31(r);this.loading[r]=o,o.loadFromImage(t.rawImageData,n),delete this.loading[r],this.loaded=this.loaded||{},this.loaded[r]=o,i(null,o);},I.prototype.removeTile=function(e){var t=this.loaded,i=e.uid;t&&t[i]&&delete t[i];};var z={RADIUS:6378137,FLATTENING:1/298.257223563,POLAR_RADIUS:6356752.3142};function T(e){var t=0;if(e&&e.length>0){t+=Math.abs(P(e[0]));for(var i=1;i<e.length;i++)t-=Math.abs(P(e[i]));}return t}function P(e){var t,i,r,n,o,a,s=0,l=e.length;if(l>2){for(a=0;a<l;a++)a===l-2?(r=l-2,n=l-1,o=0):a===l-1?(r=l-1,n=0,o=1):(r=a,n=a+1,o=a+2),t=e[r],i=e[n],s+=(k(e[o][0])-k(t[0]))*Math.sin(k(i[1]));s=s*z.RADIUS*z.RADIUS/2;}return s}function k(e){return e*Math.PI/180}var L={geometry:function e(t){var i,r=0;switch(t.type){case"Polygon":return T(t.coordinates);case"MultiPolygon":for(i=0;i<t.coordinates.length;i++)r+=T(t.coordinates[i]);return r;case"Point":case"MultiPoint":case"LineString":case"MultiLineString":return 0;case"GeometryCollection":for(i=0;i<t.geometries.length;i++)r+=e(t.geometries[i]);return r}},ring:P},$=function e(t,i){switch(t&&t.type||null){case"FeatureCollection":return t.features=t.features.map(D(e,i)),t;case"Feature":return t.geometry=e(t.geometry,i),t;case"Polygon":case"MultiPolygon":return function(e,t){"Polygon"===e.type?e.coordinates=O(e.coordinates,t):"MultiPolygon"===e.type&&(e.coordinates=e.coordinates.map(D(O,t)));return e}(t,i);default:return t}};function D(e,t){return function(i){return e(i,t)}}function O(e,t){t=!!t,e[0]=C(e[0],t);for(var i=1;i<e.length;i++)e[i]=C(e[i],!t);return e}function C(e,t){return function(e){return L.ring(e)>=0}(e)===t?e:e.reverse()}var A=e.default$29.VectorTileFeature.prototype.toGeoJSON,E=function(t){this._feature=t,this.extent=e.default$8,this.type=t.type,this.properties=t.tags,"id"in t&&!isNaN(t.id)&&(this.id=parseInt(t.id,10));};E.prototype.loadGeometry=function(){if(1===this._feature.type){for(var t=[],i=0,r=this._feature.geometry;i<r.length;i+=1){var n=r[i];t.push([new e.default$1(n[0],n[1])]);}return t}for(var o=[],a=0,s=this._feature.geometry;a<s.length;a+=1){for(var l=[],u=0,h=s[a];u<h.length;u+=1){var c=h[u];l.push(new e.default$1(c[0],c[1]));}o.push(l);}return o},E.prototype.toGeoJSON=function(e,t,i){return A.call(this,e,t,i)};var N=function(t){this.layers={_geojsonTileLayer:this},this.name="_geojsonTileLayer",this.extent=e.default$8,this.length=t.length,this._features=t;};N.prototype.feature=function(e){return new E(this._features[e])};var R=e.__moduleExports.VectorTileFeature,B=F;function F(e,t){this.options=t||{},this.features=e,this.length=e.length;}function G(e,t){this.id="number"==typeof e.id?e.id:void 0,this.type=e.type,this.rawGeometry=1===e.type?[e.geometry]:e.geometry,this.properties=e.tags,this.extent=t||4096;}F.prototype.feature=function(e){return new G(this.features[e],this.options.extent)},G.prototype.loadGeometry=function(){var t=this.rawGeometry;this.geometry=[];for(var i=0;i<t.length;i++){for(var r=t[i],n=[],o=0;o<r.length;o++)n.push(new e.default$32(r[o][0],r[o][1]));this.geometry.push(n);}return this.geometry},G.prototype.bbox=function(){this.geometry||this.loadGeometry();for(var e=this.geometry,t=1/0,i=-1/0,r=1/0,n=-1/0,o=0;o<e.length;o++)for(var a=e[o],s=0;s<a.length;s++){var l=a[s];t=Math.min(t,l.x),i=Math.max(i,l.x),r=Math.min(r,l.y),n=Math.max(n,l.y);}return[t,r,i,n]},G.prototype.toGeoJSON=R.prototype.toGeoJSON;var V=Z,J=Z,W=function(e,t){t=t||{};var i={};for(var r in e)i[r]=new B(e[r].features,t),i[r].name=r,i[r].version=t.version,i[r].extent=t.extent;return Z({layers:i})},Y=B;function Z(t){var i=new e.__moduleExports$1;return function(e,t){for(var i in e.layers)t.writeMessage(3,j,e.layers[i]);}(t,i),i.finish()}function j(e,t){var i;t.writeVarintField(15,e.version||1),t.writeStringField(1,e.name||""),t.writeVarintField(5,e.extent||4096);var r={keys:[],values:[],keycache:{},valuecache:{}};for(i=0;i<e.length;i++)r.feature=e.feature(i),t.writeMessage(2,X,r);var n=r.keys;for(i=0;i<n.length;i++)t.writeStringField(3,n[i]);var o=r.values;for(i=0;i<o.length;i++)t.writeMessage(4,K,o[i]);}function X(e,t){var i=e.feature;void 0!==i.id&&t.writeVarintField(1,i.id),t.writeMessage(2,q,e),t.writeVarintField(3,i.type),t.writeMessage(4,Q,i);}function q(e,t){var i=e.feature,r=e.keys,n=e.values,o=e.keycache,a=e.valuecache;for(var s in i.properties){var l=o[s];void 0===l&&(r.push(s),l=r.length-1,o[s]=l),t.writeVarint(l);var u=i.properties[s],h=typeof u;"string"!==h&&"boolean"!==h&&"number"!==h&&(u=JSON.stringify(u));var c=h+":"+u,f=a[c];void 0===f&&(n.push(u),f=n.length-1,a[c]=f),t.writeVarint(f);}}function U(e,t){return(t<<3)+(7&e)}function H(e){return e<<1^e>>31}function Q(e,t){for(var i=e.loadGeometry(),r=e.type,n=0,o=0,a=i.length,s=0;s<a;s++){var l=i[s],u=1;1===r&&(u=l.length),t.writeVarint(U(1,u));for(var h=3===r?l.length-1:l.length,c=0;c<h;c++){1===c&&1!==r&&t.writeVarint(U(2,h-1));var f=l[c].x-n,p=l[c].y-o;t.writeVarint(H(f)),t.writeVarint(H(p)),n+=f,o+=p;}3===r&&t.writeVarint(U(7,0));}}function K(e,t){var i=typeof e;"string"===i?t.writeStringField(1,e):"boolean"===i?t.writeBooleanField(7,e):"number"===i&&(e%1!=0?t.writeDoubleField(3,e):e<0?t.writeSVarintField(6,e):t.writeVarintField(5,e));}V.fromVectorTileJs=J,V.fromGeojsonVt=W,V.GeoJSONWrapper=Y;var ee=function e(t,i,r,n,o,a){if(o-n<=r)return;var s=Math.floor((n+o)/2);!function e(t,i,r,n,o,a){for(;o>n;){if(o-n>600){var s=o-n+1,l=r-n+1,u=Math.log(s),h=.5*Math.exp(2*u/3),c=.5*Math.sqrt(u*h*(s-h)/s)*(l-s/2<0?-1:1),f=Math.max(n,Math.floor(r-l*h/s+c)),p=Math.min(o,Math.floor(r+(s-l)*h/s+c));e(t,i,r,f,p,a);}var d=i[2*r+a],g=n,v=o;for(te(t,i,n,r),i[2*o+a]>d&&te(t,i,n,o);g<v;){for(te(t,i,g,v),g++,v--;i[2*g+a]<d;)g++;for(;i[2*v+a]>d;)v--;}i[2*n+a]===d?te(t,i,n,v):te(t,i,++v,o),v<=r&&(n=v+1),r<=v&&(o=v-1);}}(t,i,s,n,o,a%2);e(t,i,r,n,s-1,a+1);e(t,i,r,s+1,o,a+1);};function te(e,t,i,r){ie(e,i,r),ie(t,2*i,2*r),ie(t,2*i+1,2*r+1);}function ie(e,t,i){var r=e[t];e[t]=e[i],e[i]=r;}var re=function(e,t,i,r,n,o,a){var s,l,u=[0,e.length-1,0],h=[];for(;u.length;){var c=u.pop(),f=u.pop(),p=u.pop();if(f-p<=a)for(var d=p;d<=f;d++)s=t[2*d],l=t[2*d+1],s>=i&&s<=n&&l>=r&&l<=o&&h.push(e[d]);else{var g=Math.floor((p+f)/2);s=t[2*g],l=t[2*g+1],s>=i&&s<=n&&l>=r&&l<=o&&h.push(e[g]);var v=(c+1)%2;(0===c?i<=s:r<=l)&&(u.push(p),u.push(g-1),u.push(v)),(0===c?n>=s:o>=l)&&(u.push(g+1),u.push(f),u.push(v));}}return h};var ne=function(e,t,i,r,n,o){var a=[0,e.length-1,0],s=[],l=n*n;for(;a.length;){var u=a.pop(),h=a.pop(),c=a.pop();if(h-c<=o)for(var f=c;f<=h;f++)oe(t[2*f],t[2*f+1],i,r)<=l&&s.push(e[f]);else{var p=Math.floor((c+h)/2),d=t[2*p],g=t[2*p+1];oe(d,g,i,r)<=l&&s.push(e[p]);var v=(u+1)%2;(0===u?i-n<=d:r-n<=g)&&(a.push(c),a.push(p-1),a.push(v)),(0===u?i+n>=d:r+n>=g)&&(a.push(p+1),a.push(h),a.push(v));}}return s};function oe(e,t,i,r){var n=e-i,o=t-r;return n*n+o*o}var ae=function(e,t,i,r,n){return new se(e,t,i,r,n)};function se(e,t,i,r,n){t=t||le,i=i||ue,n=n||Array,this.nodeSize=r||64,this.points=e,this.ids=new n(e.length),this.coords=new n(2*e.length);for(var o=0;o<e.length;o++)this.ids[o]=o,this.coords[2*o]=t(e[o]),this.coords[2*o+1]=i(e[o]);ee(this.ids,this.coords,this.nodeSize,0,this.ids.length-1,0);}function le(e){return e[0]}function ue(e){return e[1]}se.prototype={range:function(e,t,i,r){return re(this.ids,this.coords,e,t,i,r,this.nodeSize)},within:function(e,t,i){return ne(this.ids,this.coords,e,t,i,this.nodeSize)}};var he=function(e){return new ce(e)};function ce(e){this.options=me(Object.create(this.options),e),this.trees=new Array(this.options.maxZoom+1);}function fe(e,t,i,r,n){return{x:e,y:t,zoom:1/0,id:r,properties:n,parentId:-1,numPoints:i}}function pe(e,t){var i=e.geometry.coordinates;return{x:ve(i[0]),y:ye(i[1]),zoom:1/0,id:t,parentId:-1}}function de(e){return{type:"Feature",properties:ge(e),geometry:{type:"Point",coordinates:[(r=e.x,360*(r-.5)),(t=e.y,i=(180-360*t)*Math.PI/180,360*Math.atan(Math.exp(i))/Math.PI-90)]}};var t,i,r;}function ge(e){var t=e.numPoints,i=t>=1e4?Math.round(t/1e3)+"k":t>=1e3?Math.round(t/100)/10+"k":t;return me(me({},e.properties),{cluster:!0,cluster_id:e.id,point_count:t,point_count_abbreviated:i})}function ve(e){return e/360+.5}function ye(e){var t=Math.sin(e*Math.PI/180),i=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return i<0?0:i>1?1:i}function me(e,t){for(var i in t)e[i]=t[i];return e}function xe(e){return e.x}function we(e){return e.y}function Se(e,t,i,r,n,o){var a=n-i,s=o-r;if(0!==a||0!==s){var l=((e-i)*a+(t-r)*s)/(a*a+s*s);l>1?(i=n,r=o):l>0&&(i+=a*l,r+=s*l);}return(a=e-i)*a+(s=t-r)*s}function Me(e,t,i,r){var n={id:e||null,type:t,geometry:i,tags:r,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};return function(e){var t=e.geometry,i=e.type;if("Point"===i||"MultiPoint"===i||"LineString"===i)be(e,t);else if("Polygon"===i||"MultiLineString"===i)for(var r=0;r<t.length;r++)be(e,t[r]);else if("MultiPolygon"===i)for(r=0;r<t.length;r++)for(var n=0;n<t[r].length;n++)be(e,t[r][n]);}(n),n}function be(e,t){for(var i=0;i<t.length;i+=3)e.minX=Math.min(e.minX,t[i]),e.minY=Math.min(e.minY,t[i+1]),e.maxX=Math.max(e.maxX,t[i]),e.maxY=Math.max(e.maxY,t[i+1]);}function _e(e,t,i){if(t.geometry){var r=t.geometry.coordinates,n=t.geometry.type,o=Math.pow(i.tolerance/((1<<i.maxZoom)*i.extent),2),a=[];if("Point"===n)Ie(r,a);else if("MultiPoint"===n)for(var s=0;s<r.length;s++)Ie(r[s],a);else if("LineString"===n)ze(r,a,o,!1);else if("MultiLineString"===n)if(i.lineMetrics)for(s=0;s<r.length;s++)return a=[],ze(r[s],a,o,!1),void e.push(Me(t.id,"LineString",a,t.properties));else Te(r,a,o,!1);else if("Polygon"===n)Te(r,a,o,!0);else{if("MultiPolygon"!==n){if("GeometryCollection"===n){for(s=0;s<t.geometry.geometries.length;s++)_e(e,{id:t.id,geometry:t.geometry.geometries[s],properties:t.properties},i);return}throw new Error("Input data is not a valid GeoJSON object.")}for(s=0;s<r.length;s++){var l=[];Te(r[s],l,o,!0),a.push(l);}}e.push(Me(t.id,n,a,t.properties));}}function Ie(e,t){t.push(Pe(e[0])),t.push(ke(e[1])),t.push(0);}function ze(e,t,i,r){for(var n,o,a=0,s=0;s<e.length;s++){var l=Pe(e[s][0]),u=ke(e[s][1]);t.push(l),t.push(u),t.push(0),s>0&&(a+=r?(n*u-l*o)/2:Math.sqrt(Math.pow(l-n,2)+Math.pow(u-o,2))),n=l,o=u;}var h=t.length-3;t[2]=1,function e(t,i,r,n){for(var o,a=n,s=t[i],l=t[i+1],u=t[r],h=t[r+1],c=i+3;c<r;c+=3){var f=Se(t[c],t[c+1],s,l,u,h);f>a&&(o=c,a=f);}a>n&&(o-i>3&&e(t,i,o,n),t[o+2]=a,r-o>3&&e(t,o,r,n));}(t,0,h,i),t[h+2]=1,t.size=Math.abs(a),t.start=0,t.end=t.size;}function Te(e,t,i,r){for(var n=0;n<e.length;n++){var o=[];ze(e[n],o,i,r),t.push(o);}}function Pe(e){return e/360+.5}function ke(e){var t=Math.sin(e*Math.PI/180),i=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return i<0?0:i>1?1:i}function Le(e,t,i,r,n,o,a,s){if(r/=t,o>=(i/=t)&&a<=r)return e;if(o>r||a<i)return null;for(var l=[],u=0;u<e.length;u++){var h=e[u],c=h.geometry,f=h.type,p=0===n?h.minX:h.minY,d=0===n?h.maxX:h.maxY;if(p>=i&&d<=r)l.push(h);else if(!(p>r||d<i)){var g=[];if("Point"===f||"MultiPoint"===f)$e(c,g,i,r,n);else if("LineString"===f)De(c,g,i,r,n,!1,s.lineMetrics);else if("MultiLineString"===f)Ce(c,g,i,r,n,!1);else if("Polygon"===f)Ce(c,g,i,r,n,!0);else if("MultiPolygon"===f)for(var v=0;v<c.length;v++){var y=[];Ce(c[v],y,i,r,n,!0),y.length&&g.push(y);}if(g.length){if(s.lineMetrics&&"LineString"===f){for(v=0;v<g.length;v++)l.push(Me(h.id,f,g[v],h.tags));continue}"LineString"!==f&&"MultiLineString"!==f||(1===g.length?(f="LineString",g=g[0]):f="MultiLineString"),"Point"!==f&&"MultiPoint"!==f||(f=3===g.length?"Point":"MultiPoint"),l.push(Me(h.id,f,g,h.tags));}}}return l.length?l:null}function $e(e,t,i,r,n){for(var o=0;o<e.length;o+=3){var a=e[o+n];a>=i&&a<=r&&(t.push(e[o]),t.push(e[o+1]),t.push(e[o+2]));}}function De(e,t,i,r,n,o,a){for(var s,l,u=Oe(e),h=0===n?Ee:Ne,c=e.start,f=0;f<e.length-3;f+=3){var p=e[f],d=e[f+1],g=e[f+2],v=e[f+3],y=e[f+4],m=0===n?p:d,x=0===n?v:y,w=!1;a&&(s=Math.sqrt(Math.pow(p-v,2)+Math.pow(d-y,2))),m<i?x>=i&&(l=h(u,p,d,v,y,i),a&&(u.start=c+s*l)):m>r?x<=r&&(l=h(u,p,d,v,y,r),a&&(u.start=c+s*l)):Ae(u,p,d,g),x<i&&m>=i&&(l=h(u,p,d,v,y,i),w=!0),x>r&&m<=r&&(l=h(u,p,d,v,y,r),w=!0),!o&&w&&(a&&(u.end=c+s*l),t.push(u),u=Oe(e)),a&&(c+=s);}var S=e.length-3;p=e[S],d=e[S+1],g=e[S+2],(m=0===n?p:d)>=i&&m<=r&&Ae(u,p,d,g),S=u.length-3,o&&S>=3&&(u[S]!==u[0]||u[S+1]!==u[1])&&Ae(u,u[0],u[1],u[2]),u.length&&t.push(u);}function Oe(e){var t=[];return t.size=e.size,t.start=e.start,t.end=e.end,t}function Ce(e,t,i,r,n,o){for(var a=0;a<e.length;a++)De(e[a],t,i,r,n,o,!1);}function Ae(e,t,i,r){e.push(t),e.push(i),e.push(r);}function Ee(e,t,i,r,n,o){var a=(o-t)/(r-t);return e.push(o),e.push(i+(n-i)*a),e.push(1),a}function Ne(e,t,i,r,n,o){var a=(o-i)/(n-i);return e.push(t+(r-t)*a),e.push(o),e.push(1),a}function Re(e,t){for(var i=[],r=0;r<e.length;r++){var n,o=e[r],a=o.type;if("Point"===a||"MultiPoint"===a||"LineString"===a)n=Be(o.geometry,t);else if("MultiLineString"===a||"Polygon"===a){n=[];for(var s=0;s<o.geometry.length;s++)n.push(Be(o.geometry[s],t));}else if("MultiPolygon"===a)for(n=[],s=0;s<o.geometry.length;s++){for(var l=[],u=0;u<o.geometry[s].length;u++)l.push(Be(o.geometry[s][u],t));n.push(l);}i.push(Me(o.id,a,n,o.tags));}return i}function Be(e,t){var i=[];i.size=e.size,void 0!==e.start&&(i.start=e.start,i.end=e.end);for(var r=0;r<e.length;r+=3)i.push(e[r]+t,e[r+1],e[r+2]);return i}function Fe(e,t){if(e.transformed)return e;var i,r,n,o=1<<e.z,a=e.x,s=e.y;for(i=0;i<e.features.length;i++){var l=e.features[i],u=l.geometry,h=l.type;if(l.geometry=[],1===h)for(r=0;r<u.length;r+=2)l.geometry.push(Ge(u[r],u[r+1],t,o,a,s));else for(r=0;r<u.length;r++){var c=[];for(n=0;n<u[r].length;n+=2)c.push(Ge(u[r][n],u[r][n+1],t,o,a,s));l.geometry.push(c);}}return e.transformed=!0,e}function Ge(e,t,i,r,n,o){return[Math.round(i*(e*r-n)),Math.round(i*(t*r-o))]}function Ve(e,t,i,r,n){for(var o=t===n.maxZoom?0:n.tolerance/((1<<t)*n.extent),a={features:[],numPoints:0,numSimplified:0,numFeatures:0,source:null,x:i,y:r,z:t,transformed:!1,minX:2,minY:1,maxX:-1,maxY:0},s=0;s<e.length;s++){a.numFeatures++,Je(a,e[s],o,n);var l=e[s].minX,u=e[s].minY,h=e[s].maxX,c=e[s].maxY;l<a.minX&&(a.minX=l),u<a.minY&&(a.minY=u),h>a.maxX&&(a.maxX=h),c>a.maxY&&(a.maxY=c);}return a}function Je(e,t,i,r){var n=t.geometry,o=t.type,a=[];if("Point"===o||"MultiPoint"===o)for(var s=0;s<n.length;s+=3)a.push(n[s]),a.push(n[s+1]),e.numPoints++,e.numSimplified++;else if("LineString"===o)We(a,n,e,i,!1,!1);else if("MultiLineString"===o||"Polygon"===o)for(s=0;s<n.length;s++)We(a,n[s],e,i,"Polygon"===o,0===s);else if("MultiPolygon"===o)for(var l=0;l<n.length;l++){var u=n[l];for(s=0;s<u.length;s++)We(a,u[s],e,i,!0,0===s);}if(a.length){var h=t.tags||null;if("LineString"===o&&r.lineMetrics){for(var c in h={},t.tags)h[c]=t.tags[c];h.mapbox_clip_start=n.start/n.size,h.mapbox_clip_end=n.end/n.size;}var f={geometry:a,type:"Polygon"===o||"MultiPolygon"===o?3:"LineString"===o||"MultiLineString"===o?2:1,tags:h};null!==t.id&&(f.id=t.id),e.features.push(f);}}function We(e,t,i,r,n,o){var a=r*r;if(r>0&&t.size<(n?a:r))i.numPoints+=t.length/3;else{for(var s=[],l=0;l<t.length;l+=3)(0===r||t[l+2]>a)&&(i.numSimplified++,s.push(t[l]),s.push(t[l+1])),i.numPoints++;n&&function(e,t){for(var i=0,r=0,n=e.length,o=n-2;r<n;o=r,r+=2)i+=(e[r]-e[o])*(e[r+1]+e[o+1]);if(i>0===t)for(r=0,n=e.length;r<n/2;r+=2){var a=e[r],s=e[r+1];e[r]=e[n-2-r],e[r+1]=e[n-1-r],e[n-2-r]=a,e[n-1-r]=s;}}(s,o),e.push(s);}}function Ye(e,t){var i=(t=this.options=function(e,t){for(var i in t)e[i]=t[i];return e}(Object.create(this.options),t)).debug;if(i&&console.time("preprocess data"),t.maxZoom<0||t.maxZoom>24)throw new Error("maxZoom should be in the 0-24 range");var r=function(e,t){var i=[];if("FeatureCollection"===e.type)for(var r=0;r<e.features.length;r++)_e(i,e.features[r],t);else"Feature"===e.type?_e(i,e,t):_e(i,{geometry:e},t);return i}(e,t);this.tiles={},this.tileCoords=[],i&&(console.timeEnd("preprocess data"),console.log("index: maxZoom: %d, maxPoints: %d",t.indexMaxZoom,t.indexMaxPoints),console.time("generate tiles"),this.stats={},this.total=0),(r=function(e,t){var i=t.buffer/t.extent,r=e,n=Le(e,1,-1-i,i,0,-1,2,t),o=Le(e,1,1-i,2+i,0,-1,2,t);return(n||o)&&(r=Le(e,1,-i,1+i,0,-1,2,t)||[],n&&(r=Re(n,1).concat(r)),o&&(r=r.concat(Re(o,-1)))),r}(r,t)).length&&this.splitTile(r,0,0,0),i&&(r.length&&console.log("features: %d, points: %d",this.tiles[0].numFeatures,this.tiles[0].numPoints),console.timeEnd("generate tiles"),console.log("tiles generated:",this.total,JSON.stringify(this.stats)));}function Ze(e,t,i){return 32*((1<<e)*i+t)+e}function je(e,t){var i=e.tileID.canonical;if(!this._geoJSONIndex)return t(null,null);var r=this._geoJSONIndex.getTile(i.z,i.x,i.y);if(!r)return t(null,null);var n=new N(r.features),o=V(n);0===o.byteOffset&&o.byteLength===o.buffer.byteLength||(o=new Uint8Array(o)),t(null,{vectorTile:n,rawData:o.buffer});}ce.prototype={options:{minZoom:0,maxZoom:16,radius:40,extent:512,nodeSize:64,log:!1,reduce:null,initial:function(){return{}},map:function(e){return e}},load:function(e){var t=this.options.log;t&&console.time("total time");var i="prepare "+e.length+" points";t&&console.time(i),this.points=e;var r=e.map(pe);t&&console.timeEnd(i);for(var n=this.options.maxZoom;n>=this.options.minZoom;n--){var o=+Date.now();this.trees[n+1]=ae(r,xe,we,this.options.nodeSize,Float32Array),r=this._cluster(r,n),t&&console.log("z%d: %d clusters in %dms",n,r.length,+Date.now()-o);}return this.trees[this.options.minZoom]=ae(r,xe,we,this.options.nodeSize,Float32Array),t&&console.timeEnd("total time"),this},getClusters:function(e,t){for(var i=this.trees[this._limitZoom(t)],r=i.range(ve(e[0]),ye(e[3]),ve(e[2]),ye(e[1])),n=[],o=0;o<r.length;o++){var a=i.points[r[o]];n.push(a.numPoints?de(a):this.points[a.id]);}return n},getChildren:function(e,t){for(var i=this.trees[t+1].points[e],r=this.options.radius/(this.options.extent*Math.pow(2,t)),n=this.trees[t+1].within(i.x,i.y,r),o=[],a=0;a<n.length;a++){var s=this.trees[t+1].points[n[a]];s.parentId===e&&o.push(s.numPoints?de(s):this.points[s.id]);}return o},getLeaves:function(e,t,i,r){i=i||10,r=r||0;var n=[];return this._appendLeaves(n,e,t,i,r,0),n},getTile:function(e,t,i){var r=this.trees[this._limitZoom(e)],n=Math.pow(2,e),o=this.options.extent,a=this.options.radius/o,s=(i-a)/n,l=(i+1+a)/n,u={features:[]};return this._addTileFeatures(r.range((t-a)/n,s,(t+1+a)/n,l),r.points,t,i,n,u),0===t&&this._addTileFeatures(r.range(1-a/n,s,1,l),r.points,n,i,n,u),t===n-1&&this._addTileFeatures(r.range(0,s,a/n,l),r.points,-1,i,n,u),u.features.length?u:null},getClusterExpansionZoom:function(e,t){for(;t<this.options.maxZoom;){var i=this.getChildren(e,t);if(t++,1!==i.length)break;e=i[0].properties.cluster_id;}return t},_appendLeaves:function(e,t,i,r,n,o){for(var a=this.getChildren(t,i),s=0;s<a.length;s++){var l=a[s].properties;if(l.cluster?o+l.point_count<=n?o+=l.point_count:o=this._appendLeaves(e,l.cluster_id,i+1,r,n,o):o<n?o++:e.push(a[s]),e.length===r)break}return o},_addTileFeatures:function(e,t,i,r,n,o){for(var a=0;a<e.length;a++){var s=t[e[a]];o.features.push({type:1,geometry:[[Math.round(this.options.extent*(s.x*n-i)),Math.round(this.options.extent*(s.y*n-r))]],tags:s.numPoints?ge(s):this.points[s.id].properties});}},_limitZoom:function(e){return Math.max(this.options.minZoom,Math.min(e,this.options.maxZoom+1))},_cluster:function(e,t){for(var i=[],r=this.options.radius/(this.options.extent*Math.pow(2,t)),n=0;n<e.length;n++){var o=e[n];if(!(o.zoom<=t)){o.zoom=t;var a=this.trees[t+1],s=a.within(o.x,o.y,r),l=o.numPoints||1,u=o.x*l,h=o.y*l,c=null;this.options.reduce&&(c=this.options.initial(),this._accumulate(c,o));for(var f=0;f<s.length;f++){var p=a.points[s[f]];if(t<p.zoom){var d=p.numPoints||1;p.zoom=t,u+=p.x*d,h+=p.y*d,l+=d,p.parentId=n,this.options.reduce&&this._accumulate(c,p);}}1===l?i.push(o):(o.parentId=n,i.push(fe(u/l,h/l,l,n,c)));}}return i},_accumulate:function(e,t){var i=t.numPoints?t.properties:this.options.map(this.points[t.id].properties);this.options.reduce(e,i);}},Ye.prototype.options={maxZoom:14,indexMaxZoom:5,indexMaxPoints:1e5,tolerance:3,extent:4096,buffer:64,lineMetrics:!1,debug:0},Ye.prototype.splitTile=function(e,t,i,r,n,o,a){for(var s=[e,t,i,r],l=this.options,u=l.debug;s.length;){r=s.pop(),i=s.pop(),t=s.pop(),e=s.pop();var h=1<<t,c=Ze(t,i,r),f=this.tiles[c];if(!f&&(u>1&&console.time("creation"),f=this.tiles[c]=Ve(e,t,i,r,l),this.tileCoords.push({z:t,x:i,y:r}),u)){u>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",t,i,r,f.numFeatures,f.numPoints,f.numSimplified),console.timeEnd("creation"));var p="z"+t;this.stats[p]=(this.stats[p]||0)+1,this.total++;}if(f.source=e,n){if(t===l.maxZoom||t===n)continue;var d=1<<n-t;if(i!==Math.floor(o/d)||r!==Math.floor(a/d))continue}else if(t===l.indexMaxZoom||f.numPoints<=l.indexMaxPoints)continue;if(f.source=null,0!==e.length){u>1&&console.time("clipping");var g,v,y,m,x,w,S=.5*l.buffer/l.extent,M=.5-S,b=.5+S,_=1+S;g=v=y=m=null,x=Le(e,h,i-S,i+b,0,f.minX,f.maxX,l),w=Le(e,h,i+M,i+_,0,f.minX,f.maxX,l),e=null,x&&(g=Le(x,h,r-S,r+b,1,f.minY,f.maxY,l),v=Le(x,h,r+M,r+_,1,f.minY,f.maxY,l),x=null),w&&(y=Le(w,h,r-S,r+b,1,f.minY,f.maxY,l),m=Le(w,h,r+M,r+_,1,f.minY,f.maxY,l),w=null),u>1&&console.timeEnd("clipping"),s.push(g||[],t+1,2*i,2*r),s.push(v||[],t+1,2*i,2*r+1),s.push(y||[],t+1,2*i+1,2*r),s.push(m||[],t+1,2*i+1,2*r+1);}}},Ye.prototype.getTile=function(e,t,i){var r=this.options,n=r.extent,o=r.debug;if(e<0||e>24)return null;var a=1<<e,s=Ze(e,t=(t%a+a)%a,i);if(this.tiles[s])return Fe(this.tiles[s],n);o>1&&console.log("drilling down to z%d-%d-%d",e,t,i);for(var l,u=e,h=t,c=i;!l&&u>0;)u--,h=Math.floor(h/2),c=Math.floor(c/2),l=this.tiles[Ze(u,h,c)];return l&&l.source?(o>1&&console.log("found parent tile z%d-%d-%d",u,h,c),o>1&&console.time("drilling down"),this.splitTile(l.source,u,h,c,e,t,i),o>1&&console.timeEnd("drilling down"),this.tiles[s]?Fe(this.tiles[s],n):null):null};var Xe=function(t){function i(e,i,r){t.call(this,e,i,je),r&&(this.loadGeoJSON=r);}return t&&(i.__proto__=t),i.prototype=Object.create(t&&t.prototype),i.prototype.constructor=i,i.prototype.loadData=function(e,t){this._pendingCallback&&this._pendingCallback(null,{abandoned:!0}),this._pendingCallback=t,this._pendingLoadDataParams=e,this._state&&"Idle"!==this._state?this._state="NeedsLoadData":(this._state="Coalescing",this._loadData());},i.prototype._loadData=function(){var e=this;if(this._pendingCallback&&this._pendingLoadDataParams){var t=this._pendingCallback,i=this._pendingLoadDataParams;delete this._pendingCallback,delete this._pendingLoadDataParams,this.loadGeoJSON(i,function(r,n){if(r||!n)return t(r);if("object"!=typeof n)return t(new Error("Input data is not a valid GeoJSON object."));$(n,!0);try{e._geoJSONIndex=i.cluster?he(i.superclusterOptions).load(n.features):function(e,t){return new Ye(e,t)}(n,i.geojsonVtOptions);}catch(r){return t(r)}e.loaded={};var o={};if(i.request&&i.request.collectResourceTiming){var a=M(i.request.url);a&&(o.resourceTiming={},o.resourceTiming[i.source]=JSON.parse(JSON.stringify(a)));}t(null,o);});}},i.prototype.coalesce=function(){"Coalescing"===this._state?this._state="Idle":"NeedsLoadData"===this._state&&(this._state="Coalescing",this._loadData());},i.prototype.reloadTile=function(e,i){var r=this.loaded,n=e.uid;return r&&r[n]?t.prototype.reloadTile.call(this,e,i):this.loadTile(e,i)},i.prototype.loadGeoJSON=function(t,i){if(t.request)e.getJSON(t.request,i);else{if("string"!=typeof t.data)return i(new Error("Input data is not a valid GeoJSON object."));try{return i(null,JSON.parse(t.data))}catch(e){return i(new Error("Input data is not a valid GeoJSON object."))}}},i.prototype.removeSource=function(e,t){this._pendingCallback&&this._pendingCallback(null,{abandoned:!0}),t();},i}(_),qe=function(t){var i=this;this.self=t,this.actor=new e.default$7(t,this),this.layerIndexes={},this.workerSourceTypes={vector:_,geojson:Xe},this.workerSources={},this.demWorkerSources={},this.self.registerWorkerSource=function(e,t){if(i.workerSourceTypes[e])throw new Error('Worker source with name "'+e+'" already registered.');i.workerSourceTypes[e]=t;},this.self.registerRTLTextPlugin=function(t){if(e.plugin.isLoaded())throw new Error("RTL text plugin already registered.");e.plugin.applyArabicShaping=t.applyArabicShaping,e.plugin.processBidirectionalText=t.processBidirectionalText;};};return qe.prototype.setLayers=function(e,t,i){this.getLayerIndex(e).replace(t),i();},qe.prototype.updateLayers=function(e,t,i){this.getLayerIndex(e).update(t.layers,t.removedIds),i();},qe.prototype.loadTile=function(e,t,i){this.getWorkerSource(e,t.type,t.source).loadTile(t,i);},qe.prototype.loadDEMTile=function(e,t,i){this.getDEMWorkerSource(e,t.source).loadTile(t,i);},qe.prototype.reloadTile=function(e,t,i){this.getWorkerSource(e,t.type,t.source).reloadTile(t,i);},qe.prototype.abortTile=function(e,t,i){this.getWorkerSource(e,t.type,t.source).abortTile(t,i);},qe.prototype.removeTile=function(e,t,i){this.getWorkerSource(e,t.type,t.source).removeTile(t,i);},qe.prototype.removeDEMTile=function(e,t){this.getDEMWorkerSource(e,t.source).removeTile(t);},qe.prototype.removeSource=function(e,t,i){if(this.workerSources[e]&&this.workerSources[e][t.type]&&this.workerSources[e][t.type][t.source]){var r=this.workerSources[e][t.type][t.source];delete this.workerSources[e][t.type][t.source],void 0!==r.removeSource?r.removeSource(t,i):i();}},qe.prototype.loadWorkerSource=function(e,t,i){try{this.self.importScripts(t.url),i();}catch(e){i(e.toString());}},qe.prototype.loadRTLTextPlugin=function(t,i,r){try{e.plugin.isLoaded()||(this.self.importScripts(i),r(e.plugin.isLoaded()?null:new Error("RTL Text Plugin failed to import scripts from "+i)));}catch(e){r(e.toString());}},qe.prototype.getLayerIndex=function(e){var t=this.layerIndexes[e];return t||(t=this.layerIndexes[e]=new r),t},qe.prototype.getWorkerSource=function(e,t,i){var r=this;if(this.workerSources[e]||(this.workerSources[e]={}),this.workerSources[e][t]||(this.workerSources[e][t]={}),!this.workerSources[e][t][i]){var n={send:function(t,i,n){r.actor.send(t,i,n,e);}};this.workerSources[e][t][i]=new this.workerSourceTypes[t](n,this.getLayerIndex(e));}return this.workerSources[e][t][i]},qe.prototype.getDEMWorkerSource=function(e,t){return this.demWorkerSources[e]||(this.demWorkerSources[e]={}),this.demWorkerSources[e][t]||(this.demWorkerSources[e][t]=new I),this.demWorkerSources[e][t]},"undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof self&&self instanceof WorkerGlobalScope&&new qe(self),qe});

define(["./chunk1.js"],function(t){"use strict";var e=t.createCommonjsModule(function(t){function e(t){return!!("undefined"!=typeof window&&"undefined"!=typeof document&&Array.prototype&&Array.prototype.every&&Array.prototype.filter&&Array.prototype.forEach&&Array.prototype.indexOf&&Array.prototype.lastIndexOf&&Array.prototype.map&&Array.prototype.some&&Array.prototype.reduce&&Array.prototype.reduceRight&&Array.isArray&&Function.prototype&&Function.prototype.bind&&Object.keys&&Object.create&&Object.getPrototypeOf&&Object.getOwnPropertyNames&&Object.isSealed&&Object.isFrozen&&Object.isExtensible&&Object.getOwnPropertyDescriptor&&Object.defineProperty&&Object.defineProperties&&Object.seal&&Object.freeze&&Object.preventExtensions&&"JSON"in window&&"parse"in JSON&&"stringify"in JSON&&function(){if(!("Worker"in window&&"Blob"in window&&"URL"in window))return!1;var t,e,i=new Blob([""],{type:"text/javascript"}),n=URL.createObjectURL(i);try{e=new Worker(n),t=!0;}catch(e){t=!1;}e&&e.terminate();return URL.revokeObjectURL(n),t}()&&"Uint8ClampedArray"in window&&function(t){void 0===i[t]&&(i[t]=function(t){var i=document.createElement("canvas"),n=Object.create(e.webGLContextAttributes);return n.failIfMajorPerformanceCaveat=t,i.probablySupportsContext?i.probablySupportsContext("webgl",n)||i.probablySupportsContext("experimental-webgl",n):i.supportsContext?i.supportsContext("webgl",n)||i.supportsContext("experimental-webgl",n):i.getContext("webgl",n)||i.getContext("experimental-webgl",n)}(t));return i[t]}(t&&t.failIfMajorPerformanceCaveat))}t.exports?t.exports=e:window&&(window.mapboxgl=window.mapboxgl||{},window.mapboxgl.supported=e);var i={};e.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0};}),i=t.default.performance&&t.default.performance.now?t.default.performance.now.bind(t.default.performance):Date.now.bind(Date),n=t.default.requestAnimationFrame||t.default.mozRequestAnimationFrame||t.default.webkitRequestAnimationFrame||t.default.msRequestAnimationFrame,o=t.default.cancelAnimationFrame||t.default.mozCancelAnimationFrame||t.default.webkitCancelAnimationFrame||t.default.msCancelAnimationFrame,r={now:i,frame:function(t){return n(t)},cancelFrame:function(t){return o(t)},getImageData:function(e){var i=t.default.document.createElement("canvas"),n=i.getContext("2d");if(!n)throw new Error("failed to create canvas 2d context");return i.width=e.width,i.height=e.height,n.drawImage(e,0,0,e.width,e.height),n.getImageData(0,0,e.width,e.height)},hardwareConcurrency:t.default.navigator.hardwareConcurrency||4,get devicePixelRatio(){return t.default.devicePixelRatio},supportsWebp:!1};if(t.default.document){var a=t.default.document.createElement("img");a.onload=function(){r.supportsWebp=!0;},a.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=";}var s={create:function(e,i,n){var o=t.default.document.createElement(e);return i&&(o.className=i),n&&n.appendChild(o),o},createNS:function(e,i){return t.default.document.createElementNS(e,i)}},l=t.default.document?t.default.document.documentElement.style:null;function c(t){if(!l)return null;for(var e=0;e<t.length;e++)if(t[e]in l)return t[e];return t[0]}var u,h=c(["userSelect","MozUserSelect","WebkitUserSelect","msUserSelect"]);s.disableDrag=function(){l&&h&&(u=l[h],l[h]="none");},s.enableDrag=function(){l&&h&&(l[h]=u);};var p=c(["transform","WebkitTransform"]);s.setTransform=function(t,e){t.style[p]=e;};var d=!1;try{var f=Object.defineProperty({},"passive",{get:function(){d=!0;}});t.default.addEventListener("test",f,f),t.default.removeEventListener("test",f,f);}catch(t){d=!1;}s.addEventListener=function(t,e,i,n){void 0===n&&(n={}),"passive"in n&&d?t.addEventListener(e,i,n):t.addEventListener(e,i,n.capture);},s.removeEventListener=function(t,e,i,n){void 0===n&&(n={}),"passive"in n&&d?t.removeEventListener(e,i,n):t.removeEventListener(e,i,n.capture);};var m=function(e){e.preventDefault(),e.stopPropagation(),t.default.removeEventListener("click",m,!0);};s.suppressClick=function(){t.default.addEventListener("click",m,!0),t.default.setTimeout(function(){t.default.removeEventListener("click",m,!0);},0);},s.mousePos=function(e,i){var n=e.getBoundingClientRect();return i=i.touches?i.touches[0]:i,new t.default$1(i.clientX-n.left-e.clientLeft,i.clientY-n.top-e.clientTop)},s.touchPos=function(e,i){for(var n=e.getBoundingClientRect(),o=[],r="touchend"===i.type?i.changedTouches:i.touches,a=0;a<r.length;a++)o.push(new t.default$1(r[a].clientX-n.left-e.clientLeft,r[a].clientY-n.top-e.clientTop));return o},s.mouseButton=function(e){return void 0!==t.default.InstallTrigger&&2===e.button&&e.ctrlKey&&t.default.navigator.platform.toUpperCase().indexOf("MAC")>=0?0:e.button},s.remove=function(t){t.parentNode&&t.parentNode.removeChild(t);};var _={API_URL:"https://api.mapbox.com",REQUIRE_ACCESS_TOKEN:!0,ACCESS_TOKEN:null},g="See https://www.mapbox.com/api-documentation/#access-tokens";function v(t,e){var i=C(_.API_URL);if(t.protocol=i.protocol,t.authority=i.authority,"/"!==i.path&&(t.path=""+i.path+t.path),!_.REQUIRE_ACCESS_TOKEN)return S(t);if(!(e=e||_.ACCESS_TOKEN))throw new Error("An API access token is required to use Mapbox GL. "+g);if("s"===e[0])throw new Error("Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). "+g);return t.params.push("access_token="+e),S(t)}function y(t){return 0===t.indexOf("mapbox:")}var x=function(t,e){if(!y(t))return t;var i=C(t);return i.path="/fonts/v1"+i.path,v(i,e)},b=function(t,e){if(!y(t))return t;var i=C(t);return i.path="/v4/"+i.authority+".json",i.params.push("secure"),v(i,e)},w=function(t,e,i,n){var o=C(t);return y(t)?(o.path="/styles/v1"+o.path+"/sprite"+e+i,v(o,n)):(o.path+=""+e+i,S(o))},E=/(\.(png|jpg)\d*)(?=$)/,T=function(t,e,i){if(!e||!y(e))return t;var n=C(t),o=r.devicePixelRatio>=2||512===i?"@2x":"",a=r.supportsWebp?".webp":"$1";return n.path=n.path.replace(E,""+o+a),function(t){for(var e=0;e<t.length;e++)0===t[e].indexOf("access_token=tk.")&&(t[e]="access_token="+(_.ACCESS_TOKEN||""));}(n.params),S(n)};var I=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function C(t){var e=t.match(I);if(!e)throw new Error("Unable to parse URL object");return{protocol:e[1],authority:e[2],path:e[3]||"/",params:e[4]?e[4].split("&"):[]}}function S(t){var e=t.params.length?"?"+t.params.join("&"):"";return t.protocol+"://"+t.authority+t.path+e}var z=t.default.HTMLImageElement,A=t.default.HTMLCanvasElement,R=t.default.HTMLVideoElement,D=t.default.ImageData,M=function(t,e,i,n){this.context=t,this.format=i,this.texture=t.gl.createTexture(),this.update(e,n);};M.prototype.update=function(t,e){var i=t.width,n=t.height,o=!this.size||this.size[0]!==i||this.size[1]!==n,r=this.context,a=r.gl;this.useMipmap=Boolean(e&&e.useMipmap),a.bindTexture(a.TEXTURE_2D,this.texture),o?(this.size=[i,n],r.pixelStoreUnpack.set(1),this.format!==a.RGBA||e&&!1===e.premultiply||r.pixelStoreUnpackPremultiplyAlpha.set(!0),t instanceof z||t instanceof A||t instanceof R||t instanceof D?a.texImage2D(a.TEXTURE_2D,0,this.format,this.format,a.UNSIGNED_BYTE,t):a.texImage2D(a.TEXTURE_2D,0,this.format,i,n,0,this.format,a.UNSIGNED_BYTE,t.data)):t instanceof z||t instanceof A||t instanceof R||t instanceof D?a.texSubImage2D(a.TEXTURE_2D,0,0,0,a.RGBA,a.UNSIGNED_BYTE,t):a.texSubImage2D(a.TEXTURE_2D,0,0,0,i,n,a.RGBA,a.UNSIGNED_BYTE,t.data),this.useMipmap&&this.isSizePowerOfTwo()&&a.generateMipmap(a.TEXTURE_2D);},M.prototype.bind=function(t,e,i){var n=this.context.gl;n.bindTexture(n.TEXTURE_2D,this.texture),i!==n.LINEAR_MIPMAP_NEAREST||this.isSizePowerOfTwo()||(i=n.LINEAR),t!==this.filter&&(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,t),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,i||t),this.filter=t),e!==this.wrap&&(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,e),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,e),this.wrap=e);},M.prototype.isSizePowerOfTwo=function(){return this.size[0]===this.size[1]&&Math.log(this.size[0])/Math.LN2%1==0},M.prototype.destroy=function(){this.context.gl.deleteTexture(this.texture),this.texture=null;};var L=function(){this.images={},this.loaded=!1,this.requestors=[],this.shelfPack=new t.default$2(64,64,{autoResize:!0}),this.patterns={},this.atlasImage=new t.RGBAImage({width:64,height:64}),this.dirty=!0;};L.prototype.isLoaded=function(){return this.loaded},L.prototype.setLoaded=function(t){if(this.loaded!==t&&(this.loaded=t,t)){for(var e=0,i=this.requestors;e<i.length;e+=1){var n=i[e],o=n.ids,r=n.callback;this._notify(o,r);}this.requestors=[];}},L.prototype.getImage=function(t){return this.images[t]},L.prototype.addImage=function(t,e){this.images[t]=e;},L.prototype.removeImage=function(t){delete this.images[t];var e=this.patterns[t];e&&(this.shelfPack.unref(e.bin),delete this.patterns[t]);},L.prototype.getImages=function(t,e){var i=!0;if(!this.isLoaded())for(var n=0,o=t;n<o.length;n+=1){var r=o[n];this.images[r]||(i=!1);}this.isLoaded()||i?this._notify(t,e):this.requestors.push({ids:t,callback:e});},L.prototype._notify=function(t,e){for(var i={},n=0,o=t;n<o.length;n+=1){var r=o[n],a=this.images[r];a&&(i[r]={data:a.data.clone(),pixelRatio:a.pixelRatio,sdf:a.sdf});}e(null,i);},L.prototype.getPixelSize=function(){return{width:this.shelfPack.w,height:this.shelfPack.h}},L.prototype.getPattern=function(e){var i=this.patterns[e];if(i)return i.position;var n=this.getImage(e);if(!n)return null;var o=n.data.width+2,r=n.data.height+2,a=this.shelfPack.packOne(o,r);if(!a)return null;this.atlasImage.resize(this.getPixelSize());var s=n.data,l=this.atlasImage,c=a.x+1,u=a.y+1,h=s.width,p=s.height;t.RGBAImage.copy(s,l,{x:0,y:0},{x:c,y:u},{width:h,height:p}),t.RGBAImage.copy(s,l,{x:0,y:p-1},{x:c,y:u-1},{width:h,height:1}),t.RGBAImage.copy(s,l,{x:0,y:0},{x:c,y:u+p},{width:h,height:1}),t.RGBAImage.copy(s,l,{x:h-1,y:0},{x:c-1,y:u},{width:1,height:p}),t.RGBAImage.copy(s,l,{x:0,y:0},{x:c+h,y:u},{width:1,height:p}),this.dirty=!0;var d=new t.ImagePosition(a,n);return this.patterns[e]={bin:a,position:d},d},L.prototype.bind=function(t){var e=t.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=!1):this.atlasTexture=new M(t,this.atlasImage,e.RGBA),this.atlasTexture.bind(e.LINEAR,e.CLAMP_TO_EDGE);};var P=B,k=1e20;function B(t,e,i,n,o,r){this.fontSize=t||24,this.buffer=void 0===e?3:e,this.cutoff=n||.25,this.fontFamily=o||"sans-serif",this.fontWeight=r||"normal",this.radius=i||8;var a=this.size=this.fontSize+2*this.buffer;this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=a,this.ctx=this.canvas.getContext("2d"),this.ctx.font=this.fontWeight+" "+this.fontSize+"px "+this.fontFamily,this.ctx.textBaseline="middle",this.ctx.fillStyle="black",this.gridOuter=new Float64Array(a*a),this.gridInner=new Float64Array(a*a),this.f=new Float64Array(a),this.d=new Float64Array(a),this.z=new Float64Array(a+1),this.v=new Int16Array(a),this.middle=Math.round(a/2*(navigator.userAgent.indexOf("Gecko/")>=0?1.2:1));}function O(t,e,i,n,o,r,a){for(var s=0;s<e;s++){for(var l=0;l<i;l++)n[l]=t[l*e+s];for(F(n,o,r,a,i),l=0;l<i;l++)t[l*e+s]=o[l];}for(l=0;l<i;l++){for(s=0;s<e;s++)n[s]=t[l*e+s];for(F(n,o,r,a,e),s=0;s<e;s++)t[l*e+s]=Math.sqrt(o[s]);}}function F(t,e,i,n,o){i[0]=0,n[0]=-k,n[1]=+k;for(var r=1,a=0;r<o;r++){for(var s=(t[r]+r*r-(t[i[a]]+i[a]*i[a]))/(2*r-2*i[a]);s<=n[a];)a--,s=(t[r]+r*r-(t[i[a]]+i[a]*i[a]))/(2*r-2*i[a]);i[++a]=r,n[a]=s,n[a+1]=+k;}for(r=0,a=0;r<o;r++){for(;n[a+1]<r;)a++;e[r]=(r-i[a])*(r-i[a])+t[i[a]];}}B.prototype.draw=function(t){this.ctx.clearRect(0,0,this.size,this.size),this.ctx.fillText(t,this.buffer,this.middle);for(var e=this.ctx.getImageData(0,0,this.size,this.size),i=new Uint8ClampedArray(this.size*this.size),n=0;n<this.size*this.size;n++){var o=e.data[4*n+3]/255;this.gridOuter[n]=1===o?0:0===o?k:Math.pow(Math.max(0,.5-o),2),this.gridInner[n]=1===o?k:0===o?0:Math.pow(Math.max(0,o-.5),2);}for(O(this.gridOuter,this.size,this.size,this.f,this.d,this.v,this.z),O(this.gridInner,this.size,this.size,this.f,this.d,this.v,this.z),n=0;n<this.size*this.size;n++){var r=this.gridOuter[n]-this.gridInner[n];i[n]=Math.max(0,Math.min(255,Math.round(255-255*(r/this.radius+this.cutoff))));}return i};var N=function(t,e){this.requestTransform=t,this.localIdeographFontFamily=e,this.entries={};};N.prototype.setURL=function(t){this.url=t;},N.prototype.getGlyphs=function(e,i){var n=this,o=[];for(var r in e)for(var a=0,s=e[r];a<s.length;a+=1){var l=s[a];o.push({stack:r,id:l});}t.asyncAll(o,function(t,e){var i=t.stack,o=t.id,r=n.entries[i];r||(r=n.entries[i]={glyphs:{},requests:{}});var a=r.glyphs[o];if(void 0===a)if(a=n._tinySDF(r,i,o))e(null,{stack:i,id:o,glyph:a});else{var s=Math.floor(o/256);if(256*s>65535)e(new Error("glyphs > 65535 not supported"));else{var l=r.requests[s];l||(l=r.requests[s]=[],N.loadGlyphRange(i,s,n.url,n.requestTransform,function(t,e){if(e)for(var i in e)r.glyphs[+i]=e[+i];for(var n=0,o=l;n<o.length;n+=1){(0,o[n])(t,e);}delete r.requests[s];})),l.push(function(t,n){t?e(t):n&&e(null,{stack:i,id:o,glyph:n[o]||null});});}}else e(null,{stack:i,id:o,glyph:a});},function(t,e){if(t)i(t);else if(e){for(var n={},o=0,r=e;o<r.length;o+=1){var a=r[o],s=a.stack,l=a.id,c=a.glyph;(n[s]||(n[s]={}))[l]=c&&{id:c.id,bitmap:c.bitmap.clone(),metrics:c.metrics};}i(null,n);}});},N.prototype._tinySDF=function(e,i,n){var o=this.localIdeographFontFamily;if(o&&(t.default$4["CJK Unified Ideographs"](n)||t.default$4["Hangul Syllables"](n))){var r=e.tinySDF;if(!r){var a="400";/bold/i.test(i)?a="900":/medium/i.test(i)?a="500":/light/i.test(i)&&(a="200"),r=e.tinySDF=new N.TinySDF(24,3,8,.25,o,a);}return{id:n,bitmap:new t.AlphaImage({width:30,height:30},r.draw(String.fromCharCode(n))),metrics:{width:24,height:24,left:0,top:-8,advance:24}}}},N.loadGlyphRange=function(e,i,n,o,r){var a=256*i,s=a+255,l=o(x(n).replace("{fontstack}",e).replace("{range}",a+"-"+s),t.ResourceType.Glyphs);t.getArrayBuffer(l,function(e,i){if(e)r(e);else if(i){for(var n={},o=0,a=t.default$3(i.data);o<a.length;o+=1){var s=a[o];n[s.id]=s;}r(null,n);}});},N.TinySDF=P;var U=function(){this.specification=t.default$5.light.position;};U.prototype.possiblyEvaluate=function(e,i){return t.sphericalToCartesian(e.expression.evaluate(i))},U.prototype.interpolate=function(e,i,n){return{x:t.number(e.x,i.x,n),y:t.number(e.y,i.y,n),z:t.number(e.z,i.z,n)}};var Z=new t.Properties({anchor:new t.DataConstantProperty(t.default$5.light.anchor),position:new U,color:new t.DataConstantProperty(t.default$5.light.color),intensity:new t.DataConstantProperty(t.default$5.light.intensity)}),V=function(e){function i(i){e.call(this),this._transitionable=new t.Transitionable(Z),this.setLight(i),this._transitioning=this._transitionable.untransitioned();}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.getLight=function(){return this._transitionable.serialize()},i.prototype.setLight=function(e){if(!this._validate(t.validateLight,e))for(var i in e){var n=e[i];t.endsWith(i,"-transition")?this._transitionable.setTransition(i.slice(0,-"-transition".length),n):this._transitionable.setValue(i,n);}},i.prototype.updateTransitions=function(t){this._transitioning=this._transitionable.transitioned(t,this._transitioning);},i.prototype.hasTransition=function(){return this._transitioning.hasTransition()},i.prototype.recalculate=function(t){this.properties=this._transitioning.possiblyEvaluate(t);},i.prototype._validate=function(e,i){return t.emitValidationErrors(this,e.call(t.validateStyle,t.extend({value:i,style:{glyphs:!0,sprite:!0},styleSpec:t.default$5})))},i}(t.Evented),j=function(t,e){this.width=t,this.height=e,this.nextRow=0,this.bytes=4,this.data=new Uint8Array(this.width*this.height*this.bytes),this.positions={};};j.prototype.getDash=function(t,e){var i=t.join(",")+String(e);return this.positions[i]||(this.positions[i]=this.addDash(t,e)),this.positions[i]},j.prototype.addDash=function(e,i){var n=i?7:0,o=2*n+1;if(this.nextRow+o>this.height)return t.warnOnce("LineAtlas out of space"),null;for(var r=0,a=0;a<e.length;a++)r+=e[a];for(var s=this.width/r,l=s/2,c=e.length%2==1,u=-n;u<=n;u++)for(var h=this.nextRow+n+u,p=this.width*h,d=c?-e[e.length-1]:0,f=e[0],m=1,_=0;_<this.width;_++){for(;f<_/s;)d=f,f+=e[m],c&&m===e.length-1&&(f+=e[0]),m++;var g=Math.abs(_-d*s),v=Math.abs(_-f*s),y=Math.min(g,v),x=m%2==1,b=void 0;if(i){var w=n?u/n*(l+1):0;if(x){var E=l-Math.abs(w);b=Math.sqrt(y*y+E*E);}else b=l-Math.sqrt(y*y+w*w);}else b=(x?1:-1)*y;this.data[3+4*(p+_)]=Math.max(0,Math.min(255,b+128));}var T={y:(this.nextRow+n+.5)/this.height,height:2*n/this.height,width:r};return this.nextRow+=o,this.dirty=!0,T},j.prototype.bind=function(t){var e=t.gl;this.texture?(e.bindTexture(e.TEXTURE_2D,this.texture),this.dirty&&(this.dirty=!1,e.texSubImage2D(e.TEXTURE_2D,0,0,0,this.width,this.height,e.RGBA,e.UNSIGNED_BYTE,this.data))):(this.texture=e.createTexture(),e.bindTexture(e.TEXTURE_2D,this.texture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,this.width,this.height,0,e.RGBA,e.UNSIGNED_BYTE,this.data));};var $=function e(i,n){this.workerPool=i,this.actors=[],this.currentActor=0,this.id=t.uniqueId();for(var o=this.workerPool.acquire(this.id),r=0;r<o.length;r++){var a=o[r],s=new e.Actor(a,n,this.id);s.name="Worker "+r,this.actors.push(s);}};function G(e,i,n){var o=function(e,i){if(e)return n(e);if(i){var o=t.pick(i,["tiles","minzoom","maxzoom","attribution","mapbox_logo","bounds"]);i.vector_layers&&(o.vectorLayers=i.vector_layers,o.vectorLayerIds=o.vectorLayers.map(function(t){return t.id})),n(null,o);}};e.url?t.getJSON(i(b(e.url),t.ResourceType.Source),o):r.frame(function(){return o(null,e)});}$.prototype.broadcast=function(e,i,n){n=n||function(){},t.asyncAll(this.actors,function(t,n){t.send(e,i,n);},n);},$.prototype.send=function(t,e,i,n){return("number"!=typeof n||isNaN(n))&&(n=this.currentActor=(this.currentActor+1)%this.actors.length),this.actors[n].send(t,e,i),n},$.prototype.remove=function(){this.actors.forEach(function(t){t.remove();}),this.actors=[],this.workerPool.release(this.id);},$.Actor=t.default$7;var W=function(t,e){if(isNaN(t)||isNaN(e))throw new Error("Invalid LngLat object: ("+t+", "+e+")");if(this.lng=+t,this.lat=+e,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")};W.prototype.wrap=function(){return new W(t.wrap(this.lng,-180,180),this.lat)},W.prototype.toArray=function(){return[this.lng,this.lat]},W.prototype.toString=function(){return"LngLat("+this.lng+", "+this.lat+")"},W.prototype.toBounds=function(t){var e=360*t/40075017,i=e/Math.cos(Math.PI/180*this.lat);return new q(new W(this.lng-i,this.lat-e),new W(this.lng+i,this.lat+e))},W.convert=function(t){if(t instanceof W)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new W(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new W(Number(t.lng),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: <lng>, lat: <lat>}, or an array of [<lng>, <lat>]")};var q=function(t,e){t&&(e?this.setSouthWest(t).setNorthEast(e):4===t.length?this.setSouthWest([t[0],t[1]]).setNorthEast([t[2],t[3]]):this.setSouthWest(t[0]).setNorthEast(t[1]));};q.prototype.setNorthEast=function(t){return this._ne=t instanceof W?new W(t.lng,t.lat):W.convert(t),this},q.prototype.setSouthWest=function(t){return this._sw=t instanceof W?new W(t.lng,t.lat):W.convert(t),this},q.prototype.extend=function(t){var e,i,n=this._sw,o=this._ne;if(t instanceof W)e=t,i=t;else{if(!(t instanceof q))return Array.isArray(t)?t.every(Array.isArray)?this.extend(q.convert(t)):this.extend(W.convert(t)):this;if(e=t._sw,i=t._ne,!e||!i)return this}return n||o?(n.lng=Math.min(e.lng,n.lng),n.lat=Math.min(e.lat,n.lat),o.lng=Math.max(i.lng,o.lng),o.lat=Math.max(i.lat,o.lat)):(this._sw=new W(e.lng,e.lat),this._ne=new W(i.lng,i.lat)),this},q.prototype.getCenter=function(){return new W((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)},q.prototype.getSouthWest=function(){return this._sw},q.prototype.getNorthEast=function(){return this._ne},q.prototype.getNorthWest=function(){return new W(this.getWest(),this.getNorth())},q.prototype.getSouthEast=function(){return new W(this.getEast(),this.getSouth())},q.prototype.getWest=function(){return this._sw.lng},q.prototype.getSouth=function(){return this._sw.lat},q.prototype.getEast=function(){return this._ne.lng},q.prototype.getNorth=function(){return this._ne.lat},q.prototype.toArray=function(){return[this._sw.toArray(),this._ne.toArray()]},q.prototype.toString=function(){return"LngLatBounds("+this._sw.toString()+", "+this._ne.toString()+")"},q.prototype.isEmpty=function(){return!(this._sw&&this._ne)},q.convert=function(t){return!t||t instanceof q?t:new q(t)};var X=function(t,e,i){this.bounds=q.convert(this.validateBounds(t)),this.minzoom=e||0,this.maxzoom=i||24;};X.prototype.validateBounds=function(t){return Array.isArray(t)&&4===t.length?[Math.max(-180,t[0]),Math.max(-90,t[1]),Math.min(180,t[2]),Math.min(90,t[3])]:[-180,-90,180,90]},X.prototype.contains=function(t){var e=Math.floor(this.lngX(this.bounds.getWest(),t.z)),i=Math.floor(this.latY(this.bounds.getNorth(),t.z)),n=Math.ceil(this.lngX(this.bounds.getEast(),t.z)),o=Math.ceil(this.latY(this.bounds.getSouth(),t.z));return t.x>=e&&t.x<n&&t.y>=i&&t.y<o},X.prototype.lngX=function(t,e){return(t+180)*(Math.pow(2,e)/360)},X.prototype.latY=function(e,i){var n=t.clamp(Math.sin(Math.PI/180*e),-.9999,.9999),o=Math.pow(2,i)/(2*Math.PI);return Math.pow(2,i-1)+.5*Math.log((1+n)/(1-n))*-o};var H=function(e){function i(i,n,o,r){if(e.call(this),this.id=i,this.dispatcher=o,this.type="vector",this.minzoom=0,this.maxzoom=22,this.scheme="xyz",this.tileSize=512,this.reparseOverscaled=!0,this.isTileClipped=!0,t.extend(this,t.pick(n,["url","scheme","tileSize"])),this._options=t.extend({type:"vector"},n),this._collectResourceTiming=n.collectResourceTiming,512!==this.tileSize)throw new Error("vector tile sources must have a tileSize of 512");this.setEventedParent(r);}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.load=function(){var e=this;this.fire(new t.Event("dataloading",{dataType:"source"})),G(this._options,this.map._transformRequest,function(i,n){i?e.fire(new t.ErrorEvent(i)):n&&(t.extend(e,n),n.bounds&&(e.tileBounds=new X(n.bounds,e.minzoom,e.maxzoom)),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"content"})));});},i.prototype.hasTile=function(t){return!this.tileBounds||this.tileBounds.contains(t.canonical)},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.serialize=function(){return t.extend({},this._options)},i.prototype.loadTile=function(e,i){var n=T(e.tileID.canonical.url(this.tiles,this.scheme),this.url),o={request:this.map._transformRequest(n,t.ResourceType.Tile),uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,tileSize:this.tileSize*e.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:r.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes};function a(t,n){return e.aborted?i(null):t?i(t):(n&&n.resourceTiming&&(e.resourceTiming=n.resourceTiming),this.map._refreshExpiredTiles&&e.setExpiryData(n),e.loadVectorData(n,this.map.painter),i(null),void(e.reloadCallback&&(this.loadTile(e,e.reloadCallback),e.reloadCallback=null)))}o.request.collectResourceTiming=this._collectResourceTiming,void 0===e.workerID||"expired"===e.state?e.workerID=this.dispatcher.send("loadTile",o,a.bind(this)):"loading"===e.state?e.reloadCallback=i:this.dispatcher.send("reloadTile",o,a.bind(this),e.workerID);},i.prototype.abortTile=function(t){this.dispatcher.send("abortTile",{uid:t.uid,type:this.type,source:this.id},void 0,t.workerID);},i.prototype.unloadTile=function(t){t.unloadVectorData(),this.dispatcher.send("removeTile",{uid:t.uid,type:this.type,source:this.id},void 0,t.workerID);},i.prototype.hasTransition=function(){return!1},i}(t.Evented),K=function(e){function i(i,n,o,r){e.call(this),this.id=i,this.dispatcher=o,this.setEventedParent(r),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=t.extend({},n),t.extend(this,t.pick(n,["url","scheme","tileSize"]));}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.load=function(){var e=this;this.fire(new t.Event("dataloading",{dataType:"source"})),G(this._options,this.map._transformRequest,function(i,n){i?e.fire(new t.ErrorEvent(i)):n&&(t.extend(e,n),n.bounds&&(e.tileBounds=new X(n.bounds,e.minzoom,e.maxzoom)),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"content"})));});},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.serialize=function(){return t.extend({},this._options)},i.prototype.hasTile=function(t){return!this.tileBounds||this.tileBounds.contains(t.canonical)},i.prototype.loadTile=function(e,i){var n=this,o=T(e.tileID.canonical.url(this.tiles,this.scheme),this.url,this.tileSize);e.request=t.getImage(this.map._transformRequest(o,t.ResourceType.Tile),function(t,o){if(delete e.request,e.aborted)e.state="unloaded",i(null);else if(t)e.state="errored",i(t);else if(o){n.map._refreshExpiredTiles&&e.setExpiryData(o),delete o.cacheControl,delete o.expires;var r=n.map.painter.context,a=r.gl;e.texture=n.map.painter.getTileTexture(o.width),e.texture?e.texture.update(o,{useMipmap:!0}):(e.texture=new M(r,o,a.RGBA,{useMipmap:!0}),e.texture.bind(a.LINEAR,a.CLAMP_TO_EDGE,a.LINEAR_MIPMAP_NEAREST),r.extTextureFilterAnisotropic&&a.texParameterf(a.TEXTURE_2D,r.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,r.extTextureFilterAnisotropicMax)),e.state="loaded",i(null);}});},i.prototype.abortTile=function(t,e){t.request&&(t.request.abort(),delete t.request),e();},i.prototype.unloadTile=function(t,e){t.texture&&this.map.painter.saveTileTexture(t.texture),e();},i.prototype.hasTransition=function(){return!1},i}(t.Evented),Y=function(e){function i(i,n,o,r){e.call(this,i,n,o,r),this.type="raster-dem",this.maxzoom=22,this._options=t.extend({},n),this.encoding=n.encoding||"mapbox";}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.serialize=function(){return{type:"raster-dem",url:this.url,tileSize:this.tileSize,tiles:this.tiles,bounds:this.bounds,encoding:this.encoding}},i.prototype.loadTile=function(e,i){var n=T(e.tileID.canonical.url(this.tiles,this.scheme),this.url,this.tileSize);e.request=t.getImage(this.map._transformRequest(n,t.ResourceType.Tile),function(t,n){if(delete e.request,e.aborted)e.state="unloaded",i(null);else if(t)e.state="errored",i(t);else if(n){this.map._refreshExpiredTiles&&e.setExpiryData(n),delete n.cacheControl,delete n.expires;var o=r.getImageData(n),a={uid:e.uid,coord:e.tileID,source:this.id,rawImageData:o,encoding:this.encoding};e.workerID&&"expired"!==e.state||(e.workerID=this.dispatcher.send("loadDEMTile",a,function(t,n){t&&(e.state="errored",i(t));n&&(e.dem=n,e.needsHillshadePrepare=!0,e.state="loaded",i(null));}.bind(this)));}}.bind(this)),e.neighboringTiles=this._getNeighboringTiles(e.tileID);},i.prototype._getNeighboringTiles=function(e){var i=e.canonical,n=Math.pow(2,i.z),o=(i.x-1+n)%n,r=0===i.x?e.wrap-1:e.wrap,a=(i.x+1+n)%n,s=i.x+1===n?e.wrap+1:e.wrap,l={};return l[new t.OverscaledTileID(e.overscaledZ,r,i.z,o,i.y).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,s,i.z,a,i.y).key]={backfilled:!1},i.y>0&&(l[new t.OverscaledTileID(e.overscaledZ,r,i.z,o,i.y-1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,e.wrap,i.z,i.x,i.y-1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,s,i.z,a,i.y-1).key]={backfilled:!1}),i.y+1<n&&(l[new t.OverscaledTileID(e.overscaledZ,r,i.z,o,i.y+1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,e.wrap,i.z,i.x,i.y+1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,s,i.z,a,i.y+1).key]={backfilled:!1}),l},i.prototype.unloadTile=function(t){t.demTexture&&this.map.painter.saveTileTexture(t.demTexture),t.fbo&&(t.fbo.destroy(),delete t.fbo),t.dem&&delete t.dem,delete t.neighboringTiles,t.state="unloaded",this.dispatcher.send("removeDEMTile",{uid:t.uid,source:this.id},void 0,t.workerID);},i}(K),J=function(e){function i(i,n,o,r){e.call(this),this.id=i,this.type="geojson",this.minzoom=0,this.maxzoom=18,this.tileSize=512,this.isTileClipped=!0,this.reparseOverscaled=!0,this._removed=!1,this.dispatcher=o,this.setEventedParent(r),this._data=n.data,this._options=t.extend({},n),this._collectResourceTiming=n.collectResourceTiming,this._resourceTiming=[],void 0!==n.maxzoom&&(this.maxzoom=n.maxzoom),n.type&&(this.type=n.type);var a=t.default$8/this.tileSize;this.workerOptions=t.extend({source:this.id,cluster:n.cluster||!1,geojsonVtOptions:{buffer:(void 0!==n.buffer?n.buffer:128)*a,tolerance:(void 0!==n.tolerance?n.tolerance:.375)*a,extent:t.default$8,maxZoom:this.maxzoom,lineMetrics:n.lineMetrics||!1},superclusterOptions:{maxZoom:void 0!==n.clusterMaxZoom?Math.min(n.clusterMaxZoom,this.maxzoom-1):this.maxzoom-1,extent:t.default$8,radius:(n.clusterRadius||50)*a,log:!1}},n.workerOptions);}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.load=function(){var e=this;this.fire(new t.Event("dataloading",{dataType:"source"})),this._updateWorkerData(function(i){if(i)e.fire(new t.ErrorEvent(i));else{var n={dataType:"source",sourceDataType:"metadata"};e._collectResourceTiming&&e._resourceTiming&&e._resourceTiming.length>0&&(n.resourceTiming=e._resourceTiming,e._resourceTiming=[]),e.fire(new t.Event("data",n));}});},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.setData=function(e){var i=this;return this._data=e,this.fire(new t.Event("dataloading",{dataType:"source"})),this._updateWorkerData(function(e){if(e)return i.fire(new t.ErrorEvent(e));var n={dataType:"source",sourceDataType:"content"};i._collectResourceTiming&&i._resourceTiming&&i._resourceTiming.length>0&&(n.resourceTiming=i._resourceTiming,i._resourceTiming=[]),i.fire(new t.Event("data",n));}),this},i.prototype._updateWorkerData=function(e){var i,n,o=this,r=t.extend({},this.workerOptions),a=this._data;"string"==typeof a?(r.request=this.map._transformRequest((i=a,(n=t.default.document.createElement("a")).href=i,n.href),t.ResourceType.Source),r.request.collectResourceTiming=this._collectResourceTiming):r.data=JSON.stringify(a),this.workerID=this.dispatcher.send(this.type+"."+r.source+".loadData",r,function(t,i){o._removed||i&&i.abandoned||(o._loaded=!0,i&&i.resourceTiming&&i.resourceTiming[o.id]&&(o._resourceTiming=i.resourceTiming[o.id].slice(0)),o.dispatcher.send(o.type+"."+r.source+".coalesce",null,null,o.workerID),e(t));},this.workerID);},i.prototype.loadTile=function(t,e){var i=this,n=void 0===t.workerID?"loadTile":"reloadTile",o={type:this.type,uid:t.uid,tileID:t.tileID,zoom:t.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:r.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes};t.workerID=this.dispatcher.send(n,o,function(o,r){return t.unloadVectorData(),t.aborted?e(null):o?e(o):(t.loadVectorData(r,i.map.painter,"reloadTile"===n),e(null))},this.workerID);},i.prototype.abortTile=function(t){t.aborted=!0;},i.prototype.unloadTile=function(t){t.unloadVectorData(),this.dispatcher.send("removeTile",{uid:t.uid,type:this.type,source:this.id},null,t.workerID);},i.prototype.onRemove=function(){this._removed=!0,this.dispatcher.send("removeSource",{type:this.type,source:this.id},null,this.workerID);},i.prototype.serialize=function(){return t.extend({},this._options,{type:this.type,data:this._data})},i.prototype.hasTransition=function(){return!1},i}(t.Evented);var Q=t.createLayout([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]),tt=function(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null;};tt.prototype.bind=function(t,e,i,n,o,r,a,s){this.context=t;for(var l=this.boundPaintVertexBuffers.length!==n.length,c=0;!l&&c<n.length;c++)this.boundPaintVertexBuffers[c]!==n[c]&&(l=!0);var u=!this.vao||this.boundProgram!==e||this.boundLayoutVertexBuffer!==i||l||this.boundIndexBuffer!==o||this.boundVertexOffset!==r||this.boundDynamicVertexBuffer!==a||this.boundDynamicVertexBuffer2!==s;!t.extVertexArrayObject||u?this.freshBind(e,i,n,o,r,a,s):(t.bindVertexArrayOES.set(this.vao),a&&a.bind(),o&&o.dynamicDraw&&o.bind(),s&&s.bind());},tt.prototype.freshBind=function(t,e,i,n,o,r,a){var s,l=t.numAttributes,c=this.context,u=c.gl;if(c.extVertexArrayObject)this.vao&&this.destroy(),this.vao=c.extVertexArrayObject.createVertexArrayOES(),c.bindVertexArrayOES.set(this.vao),s=0,this.boundProgram=t,this.boundLayoutVertexBuffer=e,this.boundPaintVertexBuffers=i,this.boundIndexBuffer=n,this.boundVertexOffset=o,this.boundDynamicVertexBuffer=r,this.boundDynamicVertexBuffer2=a;else{s=c.currentNumAttributes||0;for(var h=l;h<s;h++)u.disableVertexAttribArray(h);}e.enableAttributes(u,t);for(var p=0,d=i;p<d.length;p+=1){d[p].enableAttributes(u,t);}r&&r.enableAttributes(u,t),a&&a.enableAttributes(u,t),e.bind(),e.setVertexAttribPointers(u,t,o);for(var f=0,m=i;f<m.length;f+=1){var _=m[f];_.bind(),_.setVertexAttribPointers(u,t,o);}r&&(r.bind(),r.setVertexAttribPointers(u,t,o)),n&&n.bind(),a&&(a.bind(),a.setVertexAttribPointers(u,t,o)),c.currentNumAttributes=l;},tt.prototype.destroy=function(){this.vao&&(this.context.extVertexArrayObject.deleteVertexArrayOES(this.vao),this.vao=null);};var et=function(e){function i(t,i,n,o){e.call(this),this.id=t,this.dispatcher=n,this.coordinates=i.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this.setEventedParent(o),this.options=i;}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.load=function(){var e=this;this.fire(new t.Event("dataloading",{dataType:"source"})),this.url=this.options.url,t.getImage(this.map._transformRequest(this.url,t.ResourceType.Image),function(i,n){i?e.fire(new t.ErrorEvent(i)):n&&(e.image=r.getImageData(n),e._finishLoading());});},i.prototype._finishLoading=function(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})));},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.setCoordinates=function(e){this.coordinates=e;var i=this.map,n=e.map(function(t){return i.transform.locationCoordinate(W.convert(t)).zoomTo(0)}),o=this.centerCoord=t.getCoordinatesCenter(n);o.column=Math.floor(o.column),o.row=Math.floor(o.row),this.tileID=new t.CanonicalTileID(o.zoom,o.column,o.row),this.minzoom=this.maxzoom=o.zoom;var r=n.map(function(e){var i=e.zoomTo(o.zoom);return new t.default$1(Math.round((i.column-o.column)*t.default$8),Math.round((i.row-o.row)*t.default$8))});return this._boundsArray=new t.RasterBoundsArray,this._boundsArray.emplaceBack(r[0].x,r[0].y,0,0),this._boundsArray.emplaceBack(r[1].x,r[1].y,t.default$8,0),this._boundsArray.emplaceBack(r[3].x,r[3].y,0,t.default$8),this._boundsArray.emplaceBack(r[2].x,r[2].y,t.default$8,t.default$8),this.boundsBuffer&&(this.boundsBuffer.destroy(),delete this.boundsBuffer),this.fire(new t.Event("data",{dataType:"source",sourceDataType:"content"})),this},i.prototype.prepare=function(){if(0!==Object.keys(this.tiles).length&&this.image){var t=this.map.painter.context,e=t.gl;for(var i in this.boundsBuffer||(this.boundsBuffer=t.createVertexBuffer(this._boundsArray,Q.members)),this.boundsVAO||(this.boundsVAO=new tt),this.texture||(this.texture=new M(t,this.image,e.RGBA),this.texture.bind(e.LINEAR,e.CLAMP_TO_EDGE)),this.tiles){var n=this.tiles[i];"loaded"!==n.state&&(n.state="loaded",n.texture=this.texture);}}},i.prototype.loadTile=function(t,e){this.tileID&&this.tileID.equals(t.tileID.canonical)?(this.tiles[String(t.tileID.wrap)]=t,t.buckets={},e(null)):(t.state="errored",e(null));},i.prototype.serialize=function(){return{type:"image",url:this.options.url,coordinates:this.coordinates}},i.prototype.hasTransition=function(){return!1},i}(t.Evented),it=function(e){function i(t,i,n,o){e.call(this,t,i,n,o),this.roundZoom=!0,this.type="video",this.options=i;}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.load=function(){var e=this,i=this.options;this.urls=[];for(var n=0,o=i.urls;n<o.length;n+=1){var r=o[n];e.urls.push(e.map._transformRequest(r,t.ResourceType.Source).url);}t.getVideo(this.urls,function(i,n){i?e.fire(new t.ErrorEvent(i)):n&&(e.video=n,e.video.loop=!0,e.video.addEventListener("playing",function(){e.map._rerender();}),e.map&&e.video.play(),e._finishLoading());});},i.prototype.getVideo=function(){return this.video},i.prototype.onAdd=function(t){this.map||(this.map=t,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)));},i.prototype.prepare=function(){if(!(0===Object.keys(this.tiles).length||this.video.readyState<2)){var t=this.map.painter.context,e=t.gl;for(var i in this.boundsBuffer||(this.boundsBuffer=t.createVertexBuffer(this._boundsArray,Q.members)),this.boundsVAO||(this.boundsVAO=new tt),this.texture?this.video.paused||(this.texture.bind(e.LINEAR,e.CLAMP_TO_EDGE),e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,this.video)):(this.texture=new M(t,this.video,e.RGBA),this.texture.bind(e.LINEAR,e.CLAMP_TO_EDGE)),this.tiles){var n=this.tiles[i];"loaded"!==n.state&&(n.state="loaded",n.texture=this.texture);}}},i.prototype.serialize=function(){return{type:"video",urls:this.urls,coordinates:this.coordinates}},i.prototype.hasTransition=function(){return this.video&&!this.video.paused},i}(et),nt=function(e){function i(i,n,o,r){e.call(this,i,n,o,r),n.coordinates?Array.isArray(n.coordinates)&&4===n.coordinates.length&&!n.coordinates.some(function(t){return!Array.isArray(t)||2!==t.length||t.some(function(t){return"number"!=typeof t})})||this.fire(new t.ErrorEvent(new t.default$9("sources."+i,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new t.ErrorEvent(new t.default$9("sources."+i,null,'missing required property "coordinates"'))),n.animate&&"boolean"!=typeof n.animate&&this.fire(new t.ErrorEvent(new t.default$9("sources."+i,null,'optional "animate" property must be a boolean value'))),n.canvas?"string"==typeof n.canvas||n.canvas instanceof t.default.HTMLCanvasElement||this.fire(new t.ErrorEvent(new t.default$9("sources."+i,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new t.ErrorEvent(new t.default$9("sources."+i,null,'missing required property "canvas"'))),this.options=n,this.animate=void 0===n.animate||n.animate;}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.load=function(){this.canvas||(this.canvas=this.options.canvas instanceof t.default.HTMLCanvasElement?this.options.canvas:t.default.document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new t.ErrorEvent(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map._rerender();},this.pause=function(){this._playing=!1;},this._finishLoading());},i.prototype.getCanvas=function(){return this.canvas},i.prototype.onAdd=function(t){this.map=t,this.load(),this.canvas&&this.animate&&this.play();},i.prototype.onRemove=function(){this.pause();},i.prototype.prepare=function(){var t=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,t=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,t=!0),!this._hasInvalidDimensions()&&0!==Object.keys(this.tiles).length){var e=this.map.painter.context,i=e.gl;for(var n in this.boundsBuffer||(this.boundsBuffer=e.createVertexBuffer(this._boundsArray,Q.members)),this.boundsVAO||(this.boundsVAO=new tt),this.texture?t?this.texture.update(this.canvas):this._playing&&(this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE),i.texSubImage2D(i.TEXTURE_2D,0,0,0,i.RGBA,i.UNSIGNED_BYTE,this.canvas)):(this.texture=new M(e,this.canvas,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE)),this.tiles){var o=this.tiles[n];"loaded"!==o.state&&(o.state="loaded",o.texture=this.texture);}}},i.prototype.serialize=function(){return{type:"canvas",coordinates:this.coordinates}},i.prototype.hasTransition=function(){return this._playing},i.prototype._hasInvalidDimensions=function(){for(var t=0,e=[this.canvas.width,this.canvas.height];t<e.length;t+=1){var i=e[t];if(isNaN(i)||i<=0)return!0}return!1},i}(et),ot={vector:H,raster:K,"raster-dem":Y,geojson:J,video:it,image:et,canvas:nt},rt=function(e,i,n,o){var r=new ot[i.type](e,i,n,o);if(r.id!==e)throw new Error("Expected Source id to be "+e+" instead of "+r.id);return t.bindAll(["load","abort","unload","serialize","prepare"],r),r};function at(t,e,i,n,o){var r=o.maxPitchScaleFactor(),a=t.tilesIn(i,r);a.sort(st);for(var s=[],l=0,c=a;l<c.length;l+=1){var u=c[l];s.push({wrappedTileID:u.tileID.wrapped().key,queryResults:u.tile.queryRenderedFeatures(e,u.queryGeometry,u.scale,n,o,r,t.transform.calculatePosMatrix(u.tileID.toUnwrapped()))});}return function(t){for(var e={},i={},n=0,o=t;n<o.length;n+=1){var r=o[n],a=r.queryResults,s=r.wrappedTileID,l=i[s]=i[s]||{};for(var c in a)for(var u=a[c],h=l[c]=l[c]||{},p=e[c]=e[c]||[],d=0,f=u;d<f.length;d+=1){var m=f[d];h[m.featureIndex]||(h[m.featureIndex]=!0,p.push(m.feature));}}return e}(s)}function st(t,e){var i=t.tileID,n=e.tileID;return i.overscaledZ-n.overscaledZ||i.canonical.y-n.canonical.y||i.wrap-n.wrap||i.canonical.x-n.canonical.x}var lt=function(e,i){this.tileID=e,this.uid=t.uniqueId(),this.uses=0,this.tileSize=i,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.expiredRequestCount=0,this.state="loading";};lt.prototype.registerFadeDuration=function(t){var e=t+this.timeAdded;e<r.now()||this.fadeEndTime&&e<this.fadeEndTime||(this.fadeEndTime=e);},lt.prototype.wasRequested=function(){return"errored"===this.state||"loaded"===this.state||"reloading"===this.state},lt.prototype.loadVectorData=function(e,i,n){if(this.hasData()&&this.unloadVectorData(),this.state="loaded",e){if(e.featureIndex&&(this.latestFeatureIndex=e.featureIndex,e.rawTileData?(this.latestRawTileData=e.rawTileData,this.latestFeatureIndex.rawTileData=e.rawTileData):this.latestRawTileData&&(this.latestFeatureIndex.rawTileData=this.latestRawTileData)),this.collisionBoxArray=e.collisionBoxArray,this.buckets=function(t,e){var i={};if(!e)return i;for(var n=0,o=t;n<o.length;n+=1){var r=o[n],a=r.layerIds.map(function(t){return e.getLayer(t)}).filter(Boolean);if(0!==a.length){r.layers=a;for(var s=0,l=a;s<l.length;s+=1)i[l[s].id]=r;}}return i}(e.buckets,i.style),n)for(var o in this.buckets){var r=this.buckets[o];r instanceof t.default$14&&(r.justReloaded=!0);}for(var a in this.queryPadding=0,this.buckets){var s=this.buckets[a];this.queryPadding=Math.max(this.queryPadding,i.style.getLayer(s.layerIds[0]).queryRadius(s));}e.iconAtlasImage&&(this.iconAtlasImage=e.iconAtlasImage),e.glyphAtlasImage&&(this.glyphAtlasImage=e.glyphAtlasImage);}else this.collisionBoxArray=new t.CollisionBoxArray;},lt.prototype.unloadVectorData=function(){for(var t in this.buckets)this.buckets[t].destroy();this.buckets={},this.iconAtlasTexture&&this.iconAtlasTexture.destroy(),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.latestFeatureIndex=null,this.state="unloaded";},lt.prototype.unloadDEMData=function(){this.dem=null,this.neighboringTiles=null,this.state="unloaded";},lt.prototype.getBucket=function(t){return this.buckets[t.id]},lt.prototype.upload=function(t){for(var e in this.buckets){var i=this.buckets[e];i.uploaded||(i.upload(t),i.uploaded=!0);}var n=t.gl;this.iconAtlasImage&&(this.iconAtlasTexture=new M(t,this.iconAtlasImage,n.RGBA),this.iconAtlasImage=null),this.glyphAtlasImage&&(this.glyphAtlasTexture=new M(t,this.glyphAtlasImage,n.ALPHA),this.glyphAtlasImage=null);},lt.prototype.queryRenderedFeatures=function(t,e,i,n,o,r,a){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({queryGeometry:e,scale:i,tileSize:this.tileSize,posMatrix:a,transform:o,params:n,queryPadding:this.queryPadding*r},t):{}},lt.prototype.querySourceFeatures=function(e,i){if(this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData){var n=this.latestFeatureIndex.loadVTLayers(),o=i?i.sourceLayer:"",r=n._geojsonTileLayer||n[o];if(r)for(var a=t.default$13(i&&i.filter),s={z:this.tileID.overscaledZ,x:this.tileID.canonical.x,y:this.tileID.canonical.y},l=0;l<r.length;l++){var c=r.feature(l);if(a(new t.default$16(this.tileID.overscaledZ),c)){var u=new t.default$12(c,s.z,s.x,s.y);u.tile=s,e.push(u);}}}},lt.prototype.clearMask=function(){this.segments&&(this.segments.destroy(),delete this.segments),this.maskedBoundsBuffer&&(this.maskedBoundsBuffer.destroy(),delete this.maskedBoundsBuffer),this.maskedIndexBuffer&&(this.maskedIndexBuffer.destroy(),delete this.maskedIndexBuffer);},lt.prototype.setMask=function(e,i){if(!t.default$10(this.mask,e)&&(this.mask=e,this.clearMask(),!t.default$10(e,{0:!0}))){var n=new t.RasterBoundsArray,o=new t.TriangleIndexArray;this.segments=new t.default$15,this.segments.prepareSegment(0,n,o);for(var r=Object.keys(e),a=0;a<r.length;a++){var s=e[r[a]],l=t.default$8>>s.z,c=new t.default$1(s.x*l,s.y*l),u=new t.default$1(c.x+l,c.y+l),h=this.segments.prepareSegment(4,n,o);n.emplaceBack(c.x,c.y,c.x,c.y),n.emplaceBack(u.x,c.y,u.x,c.y),n.emplaceBack(c.x,u.y,c.x,u.y),n.emplaceBack(u.x,u.y,u.x,u.y);var p=h.vertexLength;o.emplaceBack(p,p+1,p+2),o.emplaceBack(p+1,p+2,p+3),h.vertexLength+=4,h.primitiveLength+=2;}this.maskedBoundsBuffer=i.createVertexBuffer(n,Q.members),this.maskedIndexBuffer=i.createIndexBuffer(o);}},lt.prototype.hasData=function(){return"loaded"===this.state||"reloading"===this.state||"expired"===this.state},lt.prototype.setExpiryData=function(e){var i=this.expirationTime;if(e.cacheControl){var n=t.parseCacheControl(e.cacheControl);n["max-age"]&&(this.expirationTime=Date.now()+1e3*n["max-age"]);}else e.expires&&(this.expirationTime=new Date(e.expires).getTime());if(this.expirationTime){var o=Date.now(),r=!1;if(this.expirationTime>o)r=!1;else if(i)if(this.expirationTime<i)r=!0;else{var a=this.expirationTime-i;a?this.expirationTime=o+Math.max(a,3e4):r=!0;}else r=!0;r?(this.expiredRequestCount++,this.state="expired"):this.expiredRequestCount=0;}},lt.prototype.getExpiryTimeout=function(){if(this.expirationTime)return this.expiredRequestCount?1e3*(1<<Math.min(this.expiredRequestCount-1,31)):Math.min(this.expirationTime-(new Date).getTime(),Math.pow(2,31)-1)};var ct=function(t,e){this.max=t,this.onRemove=e,this.reset();};ct.prototype.reset=function(){for(var t in this.data)for(var e=0,i=this.data[t];e<i.length;e+=1){var n=i[e];n.timeout&&clearTimeout(n.timeout),this.onRemove(n.value);}return this.data={},this.order=[],this},ct.prototype.add=function(t,e,i){var n=this,o=t.wrapped().key;void 0===this.data[o]&&(this.data[o]=[]);var r={value:e,timeout:void 0};if(void 0!==i&&(r.timeout=setTimeout(function(){n.remove(t,r);},i)),this.data[o].push(r),this.order.push(o),this.order.length>this.max){var a=this._getAndRemoveByKey(this.order[0]);a&&this.onRemove(a);}return this},ct.prototype.has=function(t){return t.wrapped().key in this.data},ct.prototype.getAndRemove=function(t){return this.has(t)?this._getAndRemoveByKey(t.wrapped().key):null},ct.prototype._getAndRemoveByKey=function(t){var e=this.data[t].shift();return e.timeout&&clearTimeout(e.timeout),0===this.data[t].length&&delete this.data[t],this.order.splice(this.order.indexOf(t),1),e.value},ct.prototype.get=function(t){return this.has(t)?this.data[t.wrapped().key][0].value:null},ct.prototype.remove=function(t,e){if(!this.has(t))return this;var i=t.wrapped().key,n=void 0===e?0:this.data[i].indexOf(e),o=this.data[i][n];return this.data[i].splice(n,1),o.timeout&&clearTimeout(o.timeout),0===this.data[i].length&&delete this.data[i],this.onRemove(o.value),this.order.splice(this.order.indexOf(i),1),this},ct.prototype.setMaxSize=function(t){for(this.max=t;this.order.length>this.max;){var e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this};var ut=function(t,e,i){this.context=t;var n=t.gl;this.buffer=n.createBuffer(),this.dynamicDraw=Boolean(i),this.unbindVAO(),t.bindElementBuffer.set(this.buffer),n.bufferData(n.ELEMENT_ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?n.DYNAMIC_DRAW:n.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer;};ut.prototype.unbindVAO=function(){this.context.extVertexArrayObject&&this.context.bindVertexArrayOES.set(null);},ut.prototype.bind=function(){this.context.bindElementBuffer.set(this.buffer);},ut.prototype.updateData=function(t){var e=this.context.gl;this.unbindVAO(),this.bind(),e.bufferSubData(e.ELEMENT_ARRAY_BUFFER,0,t.arrayBuffer);},ut.prototype.destroy=function(){var t=this.context.gl;this.buffer&&(t.deleteBuffer(this.buffer),delete this.buffer);};var ht={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"},pt=function(t,e,i,n){this.length=e.length,this.attributes=i,this.itemSize=e.bytesPerElement,this.dynamicDraw=n,this.context=t;var o=t.gl;this.buffer=o.createBuffer(),t.bindVertexBuffer.set(this.buffer),o.bufferData(o.ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?o.DYNAMIC_DRAW:o.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer;};pt.prototype.bind=function(){this.context.bindVertexBuffer.set(this.buffer);},pt.prototype.updateData=function(t){var e=this.context.gl;this.bind(),e.bufferSubData(e.ARRAY_BUFFER,0,t.arrayBuffer);},pt.prototype.enableAttributes=function(t,e){for(var i=0;i<this.attributes.length;i++){var n=this.attributes[i],o=e.attributes[n.name];void 0!==o&&t.enableVertexAttribArray(o);}},pt.prototype.setVertexAttribPointers=function(t,e,i){for(var n=0;n<this.attributes.length;n++){var o=this.attributes[n],r=e.attributes[o.name];void 0!==r&&t.vertexAttribPointer(r,o.components,t[ht[o.type]],!1,this.itemSize,o.offset+this.itemSize*(i||0));}},pt.prototype.destroy=function(){var t=this.context.gl;this.buffer&&(t.deleteBuffer(this.buffer),delete this.buffer);};var dt=function(e){this.context=e,this.current=t.default$6.transparent;};dt.prototype.get=function(){return this.current},dt.prototype.set=function(t){var e=this.current;t.r===e.r&&t.g===e.g&&t.b===e.b&&t.a===e.a||(this.context.gl.clearColor(t.r,t.g,t.b,t.a),this.current=t);};var ft=function(t){this.context=t,this.current=1;};ft.prototype.get=function(){return this.current},ft.prototype.set=function(t){this.current!==t&&(this.context.gl.clearDepth(t),this.current=t);};var mt=function(t){this.context=t,this.current=0;};mt.prototype.get=function(){return this.current},mt.prototype.set=function(t){this.current!==t&&(this.context.gl.clearStencil(t),this.current=t);};var _t=function(t){this.context=t,this.current=[!0,!0,!0,!0];};_t.prototype.get=function(){return this.current},_t.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(this.context.gl.colorMask(t[0],t[1],t[2],t[3]),this.current=t);};var gt=function(t){this.context=t,this.current=!0;};gt.prototype.get=function(){return this.current},gt.prototype.set=function(t){this.current!==t&&(this.context.gl.depthMask(t),this.current=t);};var vt=function(t){this.context=t,this.current=255;};vt.prototype.get=function(){return this.current},vt.prototype.set=function(t){this.current!==t&&(this.context.gl.stencilMask(t),this.current=t);};var yt=function(t){this.context=t,this.current={func:t.gl.ALWAYS,ref:0,mask:255};};yt.prototype.get=function(){return this.current},yt.prototype.set=function(t){var e=this.current;t.func===e.func&&t.ref===e.ref&&t.mask===e.mask||(this.context.gl.stencilFunc(t.func,t.ref,t.mask),this.current=t);};var xt=function(t){this.context=t;var e=this.context.gl;this.current=[e.KEEP,e.KEEP,e.KEEP];};xt.prototype.get=function(){return this.current},xt.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]||(this.context.gl.stencilOp(t[0],t[1],t[2]),this.current=t);};var bt=function(t){this.context=t,this.current=!1;};bt.prototype.get=function(){return this.current},bt.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;t?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this.current=t;}};var wt=function(t){this.context=t,this.current=[0,1];};wt.prototype.get=function(){return this.current},wt.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]||(this.context.gl.depthRange(t[0],t[1]),this.current=t);};var Et=function(t){this.context=t,this.current=!1;};Et.prototype.get=function(){return this.current},Et.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;t?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this.current=t;}};var Tt=function(t){this.context=t,this.current=t.gl.LESS;};Tt.prototype.get=function(){return this.current},Tt.prototype.set=function(t){this.current!==t&&(this.context.gl.depthFunc(t),this.current=t);};var It=function(t){this.context=t,this.current=!1;};It.prototype.get=function(){return this.current},It.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;t?e.enable(e.BLEND):e.disable(e.BLEND),this.current=t;}};var Ct=function(t){this.context=t;var e=this.context.gl;this.current=[e.ONE,e.ZERO];};Ct.prototype.get=function(){return this.current},Ct.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]||(this.context.gl.blendFunc(t[0],t[1]),this.current=t);};var St=function(e){this.context=e,this.current=t.default$6.transparent;};St.prototype.get=function(){return this.current},St.prototype.set=function(t){var e=this.current;t.r===e.r&&t.g===e.g&&t.b===e.b&&t.a===e.a||(this.context.gl.blendColor(t.r,t.g,t.b,t.a),this.current=t);};var zt=function(t){this.context=t,this.current=null;};zt.prototype.get=function(){return this.current},zt.prototype.set=function(t){this.current!==t&&(this.context.gl.useProgram(t),this.current=t);};var At=function(t){this.context=t,this.current=1;};At.prototype.get=function(){return this.current},At.prototype.set=function(e){var i=this.context.lineWidthRange,n=t.clamp(e,i[0],i[1]);this.current!==n&&(this.context.gl.lineWidth(n),this.current=e);};var Rt=function(t){this.context=t,this.current=t.gl.TEXTURE0;};Rt.prototype.get=function(){return this.current},Rt.prototype.set=function(t){this.current!==t&&(this.context.gl.activeTexture(t),this.current=t);};var Dt=function(t){this.context=t;var e=this.context.gl;this.current=[0,0,e.drawingBufferWidth,e.drawingBufferHeight];};Dt.prototype.get=function(){return this.current},Dt.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(this.context.gl.viewport(t[0],t[1],t[2],t[3]),this.current=t);};var Mt=function(t){this.context=t,this.current=null;};Mt.prototype.get=function(){return this.current},Mt.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindFramebuffer(e.FRAMEBUFFER,t),this.current=t;}};var Lt=function(t){this.context=t,this.current=null;};Lt.prototype.get=function(){return this.current},Lt.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindRenderbuffer(e.RENDERBUFFER,t),this.current=t;}};var Pt=function(t){this.context=t,this.current=null;};Pt.prototype.get=function(){return this.current},Pt.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindTexture(e.TEXTURE_2D,t),this.current=t;}};var kt=function(t){this.context=t,this.current=null;};kt.prototype.get=function(){return this.current},kt.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindBuffer(e.ARRAY_BUFFER,t),this.current=t;}};var Bt=function(t){this.context=t,this.current=null;};Bt.prototype.get=function(){return this.current},Bt.prototype.set=function(t){var e=this.context.gl;e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t),this.current=t;};var Ot=function(t){this.context=t,this.current=null;};Ot.prototype.get=function(){return this.current},Ot.prototype.set=function(t){this.current!==t&&this.context.extVertexArrayObject&&(this.context.extVertexArrayObject.bindVertexArrayOES(t),this.current=t);};var Ft=function(t){this.context=t,this.current=4;};Ft.prototype.get=function(){return this.current},Ft.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.pixelStorei(e.UNPACK_ALIGNMENT,t),this.current=t;}};var Nt=function(t){this.context=t,this.current=!1;};Nt.prototype.get=function(){return this.current},Nt.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t),this.current=t;}};var Ut=function(t,e){this.context=t,this.current=null,this.parent=e;};Ut.prototype.get=function(){return this.current};var Zt=function(t){function e(e,i){t.call(this,e,i),this.dirty=!1;}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.set=function(t){if(this.dirty||this.current!==t){var e=this.context.gl;this.context.bindFramebuffer.set(this.parent),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.current=t,this.dirty=!1;}},e.prototype.setDirty=function(){this.dirty=!0;},e}(Ut),Vt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;this.context.bindFramebuffer.set(this.parent),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,t),this.current=t;}},e}(Ut),jt=function(t,e,i){this.context=t,this.width=e,this.height=i;var n=t.gl,o=this.framebuffer=n.createFramebuffer();this.colorAttachment=new Zt(t,o),this.depthAttachment=new Vt(t,o);};jt.prototype.destroy=function(){var t=this.context.gl,e=this.colorAttachment.get();e&&t.deleteTexture(e);var i=this.depthAttachment.get();i&&t.deleteRenderbuffer(i),t.deleteFramebuffer(this.framebuffer);};var $t=function(t,e,i){this.func=t,this.mask=e,this.range=i;};$t.ReadOnly=!1,$t.ReadWrite=!0,$t.disabled=new $t(519,$t.ReadOnly,[0,1]);var Gt=function(t,e,i,n,o,r){this.test=t,this.ref=e,this.mask=i,this.fail=n,this.depthFail=o,this.pass=r;};Gt.disabled=new Gt({func:519,mask:0},0,0,7680,7680,7680);var Wt=function(t,e,i){this.blendFunction=t,this.blendColor=e,this.mask=i;};Wt.Replace=[1,0],Wt.disabled=new Wt(Wt.Replace,t.default$6.transparent,[!1,!1,!1,!1]),Wt.unblended=new Wt(Wt.Replace,t.default$6.transparent,[!0,!0,!0,!0]),Wt.alphaBlended=new Wt([1,771],t.default$6.transparent,[!0,!0,!0,!0]);var qt=function(t){this.gl=t,this.extVertexArrayObject=this.gl.getExtension("OES_vertex_array_object"),this.lineWidthRange=t.getParameter(t.ALIASED_LINE_WIDTH_RANGE),this.clearColor=new dt(this),this.clearDepth=new ft(this),this.clearStencil=new mt(this),this.colorMask=new _t(this),this.depthMask=new gt(this),this.stencilMask=new vt(this),this.stencilFunc=new yt(this),this.stencilOp=new xt(this),this.stencilTest=new bt(this),this.depthRange=new wt(this),this.depthTest=new Et(this),this.depthFunc=new Tt(this),this.blend=new It(this),this.blendFunc=new Ct(this),this.blendColor=new St(this),this.program=new zt(this),this.lineWidth=new At(this),this.activeTexture=new Rt(this),this.viewport=new Dt(this),this.bindFramebuffer=new Mt(this),this.bindRenderbuffer=new Lt(this),this.bindTexture=new Pt(this),this.bindVertexBuffer=new kt(this),this.bindElementBuffer=new Bt(this),this.bindVertexArrayOES=this.extVertexArrayObject&&new Ot(this),this.pixelStoreUnpack=new Ft(this),this.pixelStoreUnpackPremultiplyAlpha=new Nt(this),this.extTextureFilterAnisotropic=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=t.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT)),this.extTextureHalfFloat=t.getExtension("OES_texture_half_float"),this.extTextureHalfFloat&&t.getExtension("OES_texture_half_float_linear");};qt.prototype.createIndexBuffer=function(t,e){return new ut(this,t,e)},qt.prototype.createVertexBuffer=function(t,e,i){return new pt(this,t,e,i)},qt.prototype.createRenderbuffer=function(t,e,i){var n=this.gl,o=n.createRenderbuffer();return this.bindRenderbuffer.set(o),n.renderbufferStorage(n.RENDERBUFFER,t,e,i),this.bindRenderbuffer.set(null),o},qt.prototype.createFramebuffer=function(t,e){return new jt(this,t,e)},qt.prototype.clear=function(t){var e=t.color,i=t.depth,n=this.gl,o=0;e&&(o|=n.COLOR_BUFFER_BIT,this.clearColor.set(e),this.colorMask.set([!0,!0,!0,!0])),void 0!==i&&(o|=n.DEPTH_BUFFER_BIT,this.clearDepth.set(i),this.depthMask.set(!0)),n.clear(o);},qt.prototype.setDepthMode=function(t){t.func!==this.gl.ALWAYS||t.mask?(this.depthTest.set(!0),this.depthFunc.set(t.func),this.depthMask.set(t.mask),this.depthRange.set(t.range)):this.depthTest.set(!1);},qt.prototype.setStencilMode=function(t){t.test.func!==this.gl.ALWAYS||t.mask?(this.stencilTest.set(!0),this.stencilMask.set(t.mask),this.stencilOp.set([t.fail,t.depthFail,t.pass]),this.stencilFunc.set({func:t.test.func,ref:t.ref,mask:t.test.mask})):this.stencilTest.set(!1);},qt.prototype.setColorMode=function(e){t.default$10(e.blendFunction,Wt.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(e.blendFunction),this.blendColor.set(e.blendColor)),this.colorMask.set(e.mask);};var Xt=function(e){function i(t,i,n){var o=this;e.call(this),this.id=t,this.dispatcher=n,this.on("data",function(t){"source"===t.dataType&&"metadata"===t.sourceDataType&&(o._sourceLoaded=!0),o._sourceLoaded&&!o._paused&&"source"===t.dataType&&"content"===t.sourceDataType&&(o.reload(),o.transform&&o.update(o.transform));}),this.on("error",function(){o._sourceErrored=!0;}),this._source=rt(t,i,n,this),this._tiles={},this._cache=new ct(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._maxTileCacheSize=null,this._isIdRenderable=this._isIdRenderable.bind(this),this._coveredTiles={};}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.onAdd=function(t){this.map=t,this._maxTileCacheSize=t?t._maxTileCacheSize:null,this._source&&this._source.onAdd&&this._source.onAdd(t);},i.prototype.onRemove=function(t){this._source&&this._source.onRemove&&this._source.onRemove(t);},i.prototype.loaded=function(){if(this._sourceErrored)return!0;if(!this._sourceLoaded)return!1;for(var t in this._tiles){var e=this._tiles[t];if("loaded"!==e.state&&"errored"!==e.state)return!1}return!0},i.prototype.getSource=function(){return this._source},i.prototype.pause=function(){this._paused=!0;},i.prototype.resume=function(){if(this._paused){var t=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,t&&this.reload(),this.transform&&this.update(this.transform);}},i.prototype._loadTile=function(t,e){return this._source.loadTile(t,e)},i.prototype._unloadTile=function(t){if(this._source.unloadTile)return this._source.unloadTile(t,function(){})},i.prototype._abortTile=function(t){if(this._source.abortTile)return this._source.abortTile(t,function(){})},i.prototype.serialize=function(){return this._source.serialize()},i.prototype.prepare=function(t){for(var e in this._source.prepare&&this._source.prepare(),this._tiles)this._tiles[e].upload(t);},i.prototype.getIds=function(){var e=this;return Object.keys(this._tiles).map(Number).sort(function(i,n){var o=e._tiles[i].tileID,r=e._tiles[n].tileID,a=new t.default$1(o.canonical.x,o.canonical.y).rotate(e.transform.angle),s=new t.default$1(r.canonical.x,r.canonical.y).rotate(e.transform.angle);return o.overscaledZ-r.overscaledZ||s.y-a.y||s.x-a.x})},i.prototype.getRenderableIds=function(){return this.getIds().filter(this._isIdRenderable)},i.prototype.hasRenderableParent=function(t){var e=this.findLoadedParent(t,0,{});return!!e&&this._isIdRenderable(e.tileID.key)},i.prototype._isIdRenderable=function(t){return this._tiles[t]&&this._tiles[t].hasData()&&!this._coveredTiles[t]},i.prototype.reload=function(){if(this._paused)this._shouldReloadOnResume=!0;else for(var t in this._cache.reset(),this._tiles)this._reloadTile(t,"reloading");},i.prototype._reloadTile=function(t,e){var i=this._tiles[t];i&&("loading"!==i.state&&(i.state=e),this._loadTile(i,this._tileLoaded.bind(this,i,t,e)));},i.prototype._tileLoaded=function(e,i,n,o){if(o)return e.state="errored",void(404!==o.status?this._source.fire(new t.ErrorEvent(o,{tile:e})):this.update(this.transform));e.timeAdded=r.now(),"expired"===n&&(e.refreshedUponExpiration=!0),this._setTileReloadTimer(i,e),"raster-dem"===this.getSource().type&&e.dem&&this._backfillDEM(e),this._source.fire(new t.Event("data",{dataType:"source",tile:e,coord:e.tileID})),this.map&&(this.map.painter.tileExtentVAO.vao=null);},i.prototype._backfillDEM=function(t){for(var e=this.getRenderableIds(),i=0;i<e.length;i++){var n=e[i];if(t.neighboringTiles&&t.neighboringTiles[n]){var o=this.getTileByID(n);r(t,o),r(o,t);}}function r(t,e){t.needsHillshadePrepare=!0;var i=e.tileID.canonical.x-t.tileID.canonical.x,n=e.tileID.canonical.y-t.tileID.canonical.y,o=Math.pow(2,t.tileID.canonical.z),r=e.tileID.key;0===i&&0===n||Math.abs(n)>1||(Math.abs(i)>1&&(1===Math.abs(i+o)?i+=o:1===Math.abs(i-o)&&(i-=o)),e.dem&&t.dem&&(t.dem.backfillBorder(e.dem,i,n),t.neighboringTiles&&t.neighboringTiles[r]&&(t.neighboringTiles[r].backfilled=!0)));}},i.prototype.getTile=function(t){return this.getTileByID(t.key)},i.prototype.getTileByID=function(t){return this._tiles[t]},i.prototype.getZoom=function(t){return t.zoom+t.scaleZoom(t.tileSize/this._source.tileSize)},i.prototype._findLoadedChildren=function(t,e,i){var n=!1;for(var o in this._tiles){var r=this._tiles[o];if(!(i[o]||!r.hasData()||r.tileID.overscaledZ<=t.overscaledZ||r.tileID.overscaledZ>e)){var a=Math.pow(2,r.tileID.canonical.z-t.canonical.z);if(Math.floor(r.tileID.canonical.x/a)===t.canonical.x&&Math.floor(r.tileID.canonical.y/a)===t.canonical.y)for(i[o]=r.tileID,n=!0;r&&r.tileID.overscaledZ-1>t.overscaledZ;){var s=r.tileID.scaledTo(r.tileID.overscaledZ-1);if(!s)break;(r=this._tiles[s.key])&&r.hasData()&&(delete i[o],i[s.key]=s);}}}return n},i.prototype.findLoadedParent=function(t,e,i){for(var n=t.overscaledZ-1;n>=e;n--){var o=t.scaledTo(n);if(!o)return;var r=String(o.key),a=this._tiles[r];if(a&&a.hasData())return i[r]=o,a;if(this._cache.has(o))return i[r]=o,this._cache.get(o)}},i.prototype.updateCacheSize=function(t){var e=(Math.ceil(t.width/this._source.tileSize)+1)*(Math.ceil(t.height/this._source.tileSize)+1),i=Math.floor(5*e),n="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,i):i;this._cache.setMaxSize(n);},i.prototype.handleWrapJump=function(t){var e=(t-(void 0===this._prevLng?t:this._prevLng))/360,i=Math.round(e);if(this._prevLng=t,i){var n={};for(var o in this._tiles){var r=this._tiles[o];r.tileID=r.tileID.unwrapTo(r.tileID.wrap+i),n[r.tileID.key]=r;}for(var a in this._tiles=n,this._timers)clearTimeout(this._timers[a]),delete this._timers[a];for(var s in this._tiles){var l=this._tiles[s];this._setTileReloadTimer(s,l);}}},i.prototype.update=function(e){var n=this;if(this.transform=e,this._sourceLoaded&&!this._paused){var o;this.updateCacheSize(e),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used?this._source.tileID?o=e.getVisibleUnwrappedCoordinates(this._source.tileID).map(function(e){return new t.OverscaledTileID(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y)}):(o=e.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}),this._source.hasTile&&(o=o.filter(function(t){return n._source.hasTile(t)}))):o=[];var a,s=(this._source.roundZoom?Math.round:Math.floor)(this.getZoom(e)),l=Math.max(s-i.maxOverzooming,this._source.minzoom),c=Math.max(s+i.maxUnderzooming,this._source.minzoom),u=this._updateRetainedTiles(o,s),h={};if(Kt(this._source.type))for(var p=Object.keys(u),d=0;d<p.length;d++){var f=p[d],m=u[f],_=n._tiles[f];if(_&&(void 0===_.fadeEndTime||_.fadeEndTime>=r.now())){n._findLoadedChildren(m,c,u)&&(u[f]=m);var g=n.findLoadedParent(m,l,h);g&&n._addTile(g.tileID);}}for(a in h)u[a]||(n._coveredTiles[a]=!0);for(a in h)u[a]=h[a];for(var v=t.keysDifference(this._tiles,u),y=0;y<v.length;y++)n._removeTile(v[y]);}},i.prototype._updateRetainedTiles=function(t,e){for(var n={},o={},r=Math.max(e-i.maxOverzooming,this._source.minzoom),a=Math.max(e+i.maxUnderzooming,this._source.minzoom),s=0;s<t.length;s++){var l=t[s],c=this._addTile(l),u=!1;if(c.hasData())n[l.key]=l;else{u=c.wasRequested(),n[l.key]=l;var h=!0;if(e+1>this._source.maxzoom){var p=l.children(this._source.maxzoom)[0],d=this.getTile(p);d&&d.hasData()?n[p.key]=p:h=!1;}else{this._findLoadedChildren(l,a,n);for(var f=l.children(this._source.maxzoom),m=0;m<f.length;m++)if(!n[f[m].key]){h=!1;break}}if(!h)for(var _=l.overscaledZ-1;_>=r;--_){var g=l.scaledTo(_);if(o[g.key])break;if(o[g.key]=!0,!(c=this.getTile(g))&&u&&(c=this._addTile(g)),c&&(n[g.key]=g,u=c.wasRequested(),c.hasData()))break}}}return n},i.prototype._addTile=function(e){var i=this._tiles[e.key];if(i)return i;(i=this._cache.getAndRemove(e))&&(this._setTileReloadTimer(e.key,i),i.tileID=e);var n=Boolean(i);return n||(i=new lt(e,this._source.tileSize*e.overscaleFactor()),this._loadTile(i,this._tileLoaded.bind(this,i,e.key,i.state))),i?(i.uses++,this._tiles[e.key]=i,n||this._source.fire(new t.Event("dataloading",{tile:i,coord:i.tileID,dataType:"source"})),i):null},i.prototype._setTileReloadTimer=function(t,e){var i=this;t in this._timers&&(clearTimeout(this._timers[t]),delete this._timers[t]);var n=e.getExpiryTimeout();n&&(this._timers[t]=setTimeout(function(){i._reloadTile(t,"expired"),delete i._timers[t];},n));},i.prototype._removeTile=function(t){var e=this._tiles[t];e&&(e.uses--,delete this._tiles[t],this._timers[t]&&(clearTimeout(this._timers[t]),delete this._timers[t]),e.uses>0||(e.hasData()?this._cache.add(e.tileID,e,e.getExpiryTimeout()):(e.aborted=!0,this._abortTile(e),this._unloadTile(e))));},i.prototype.clearTiles=function(){for(var t in this._shouldReloadOnResume=!1,this._paused=!1,this._tiles)this._removeTile(t);this._cache.reset();},i.prototype.tilesIn=function(e,i){for(var n=[],o=this.getIds(),r=1/0,a=1/0,s=-1/0,l=-1/0,c=e[0].zoom,u=0;u<e.length;u++){var h=e[u];r=Math.min(r,h.column),a=Math.min(a,h.row),s=Math.max(s,h.column),l=Math.max(l,h.row);}for(var p=0;p<o.length;p++){var d=this._tiles[o[p]],f=d.tileID,m=Math.pow(2,this.transform.zoom-d.tileID.overscaledZ),_=i*d.queryPadding*t.default$8/d.tileSize/m,g=[Ht(f,new t.default$17(r,a,c)),Ht(f,new t.default$17(s,l,c))];if(g[0].x-_<t.default$8&&g[0].y-_<t.default$8&&g[1].x+_>=0&&g[1].y+_>=0){for(var v=[],y=0;y<e.length;y++)v.push(Ht(f,e[y]));n.push({tile:d,tileID:f,queryGeometry:[v],scale:m});}}return n},i.prototype.getVisibleCoordinates=function(){for(var t=this,e=this.getRenderableIds().map(function(e){return t._tiles[e].tileID}),i=0,n=e;i<n.length;i+=1){var o=n[i];o.posMatrix=t.transform.calculatePosMatrix(o.toUnwrapped());}return e},i.prototype.hasTransition=function(){if(this._source.hasTransition())return!0;if(Kt(this._source.type))for(var t in this._tiles){var e=this._tiles[t];if(void 0!==e.fadeEndTime&&e.fadeEndTime>=r.now())return!0}return!1},i}(t.Evented);function Ht(e,i){var n=i.zoomTo(e.canonical.z);return new t.default$1((n.column-(e.canonical.x+e.wrap*Math.pow(2,e.canonical.z)))*t.default$8,(n.row-e.canonical.y)*t.default$8)}function Kt(t){return"raster"===t||"image"===t||"video"===t}function Yt(){return new t.default.Worker(Rn.workerUrl)}Xt.maxOverzooming=10,Xt.maxUnderzooming=3;var Jt,Qt=function(){this.active={};};function te(e,i){var n={};for(var o in e)"ref"!==o&&(n[o]=e[o]);return t.default$18.forEach(function(t){t in i&&(n[t]=i[t]);}),n}function ee(t){t=t.slice();for(var e=Object.create(null),i=0;i<t.length;i++)e[t[i].id]=t[i];for(var n=0;n<t.length;n++)"ref"in t[n]&&(t[n]=te(t[n],e[t[n].ref]));return t}Qt.prototype.acquire=function(t){if(!this.workers){var e=Rn.workerCount;for(this.workers=[];this.workers.length<e;)this.workers.push(new Yt);}return this.active[t]=!0,this.workers.slice()},Qt.prototype.release=function(t){delete this.active[t],0===Object.keys(this.active).length&&(this.workers.forEach(function(t){t.terminate();}),this.workers=null);};var ie={setStyle:"setStyle",addLayer:"addLayer",removeLayer:"removeLayer",setPaintProperty:"setPaintProperty",setLayoutProperty:"setLayoutProperty",setFilter:"setFilter",addSource:"addSource",removeSource:"removeSource",setGeoJSONSourceData:"setGeoJSONSourceData",setLayerZoomRange:"setLayerZoomRange",setLayerProperty:"setLayerProperty",setCenter:"setCenter",setZoom:"setZoom",setBearing:"setBearing",setPitch:"setPitch",setSprite:"setSprite",setGlyphs:"setGlyphs",setTransition:"setTransition",setLight:"setLight"};function ne(t,e,i){i.push({command:ie.addSource,args:[t,e[t]]});}function oe(t,e,i){e.push({command:ie.removeSource,args:[t]}),i[t]=!0;}function re(t,e,i,n){oe(t,i,n),ne(t,e,i);}function ae(e,i,n){var o;for(o in e[n])if(e[n].hasOwnProperty(o)&&"data"!==o&&!t.default$10(e[n][o],i[n][o]))return!1;for(o in i[n])if(i[n].hasOwnProperty(o)&&"data"!==o&&!t.default$10(e[n][o],i[n][o]))return!1;return!0}function se(e,i,n,o,r,a){var s;for(s in i=i||{},e=e||{})e.hasOwnProperty(s)&&(t.default$10(e[s],i[s])||n.push({command:a,args:[o,s,i[s],r]}));for(s in i)i.hasOwnProperty(s)&&!e.hasOwnProperty(s)&&(t.default$10(e[s],i[s])||n.push({command:a,args:[o,s,i[s],r]}));}function le(t){return t.id}function ce(t,e){return t[e.id]=e,t}function ue(e,i){if(!e)return[{command:ie.setStyle,args:[i]}];var n=[];try{if(!t.default$10(e.version,i.version))return[{command:ie.setStyle,args:[i]}];t.default$10(e.center,i.center)||n.push({command:ie.setCenter,args:[i.center]}),t.default$10(e.zoom,i.zoom)||n.push({command:ie.setZoom,args:[i.zoom]}),t.default$10(e.bearing,i.bearing)||n.push({command:ie.setBearing,args:[i.bearing]}),t.default$10(e.pitch,i.pitch)||n.push({command:ie.setPitch,args:[i.pitch]}),t.default$10(e.sprite,i.sprite)||n.push({command:ie.setSprite,args:[i.sprite]}),t.default$10(e.glyphs,i.glyphs)||n.push({command:ie.setGlyphs,args:[i.glyphs]}),t.default$10(e.transition,i.transition)||n.push({command:ie.setTransition,args:[i.transition]}),t.default$10(e.light,i.light)||n.push({command:ie.setLight,args:[i.light]});var o={},r=[];!function(e,i,n,o){var r;for(r in i=i||{},e=e||{})e.hasOwnProperty(r)&&(i.hasOwnProperty(r)||oe(r,n,o));for(r in i)i.hasOwnProperty(r)&&(e.hasOwnProperty(r)?t.default$10(e[r],i[r])||("geojson"===e[r].type&&"geojson"===i[r].type&&ae(e,i,r)?n.push({command:ie.setGeoJSONSourceData,args:[r,i[r].data]}):re(r,i,n,o)):ne(r,i,n));}(e.sources,i.sources,r,o);var a=[];e.layers&&e.layers.forEach(function(t){o[t.source]?n.push({command:ie.removeLayer,args:[t.id]}):a.push(t);}),n=n.concat(r),function(e,i,n){i=i||[];var o,r,a,s,l,c,u,h=(e=e||[]).map(le),p=i.map(le),d=e.reduce(ce,{}),f=i.reduce(ce,{}),m=h.slice(),_=Object.create(null);for(o=0,r=0;o<h.length;o++)a=h[o],f.hasOwnProperty(a)?r++:(n.push({command:ie.removeLayer,args:[a]}),m.splice(m.indexOf(a,r),1));for(o=0,r=0;o<p.length;o++)a=p[p.length-1-o],m[m.length-1-o]!==a&&(d.hasOwnProperty(a)?(n.push({command:ie.removeLayer,args:[a]}),m.splice(m.lastIndexOf(a,m.length-r),1)):r++,c=m[m.length-o],n.push({command:ie.addLayer,args:[f[a],c]}),m.splice(m.length-o,0,a),_[a]=!0);for(o=0;o<p.length;o++)if(s=d[a=p[o]],l=f[a],!_[a]&&!t.default$10(s,l))if(t.default$10(s.source,l.source)&&t.default$10(s["source-layer"],l["source-layer"])&&t.default$10(s.type,l.type)){for(u in se(s.layout,l.layout,n,a,null,ie.setLayoutProperty),se(s.paint,l.paint,n,a,null,ie.setPaintProperty),t.default$10(s.filter,l.filter)||n.push({command:ie.setFilter,args:[a,l.filter]}),t.default$10(s.minzoom,l.minzoom)&&t.default$10(s.maxzoom,l.maxzoom)||n.push({command:ie.setLayerZoomRange,args:[a,l.minzoom,l.maxzoom]}),s)s.hasOwnProperty(u)&&"layout"!==u&&"paint"!==u&&"filter"!==u&&"metadata"!==u&&"minzoom"!==u&&"maxzoom"!==u&&(0===u.indexOf("paint.")?se(s[u],l[u],n,a,u.slice(6),ie.setPaintProperty):t.default$10(s[u],l[u])||n.push({command:ie.setLayerProperty,args:[a,u,l[u]]}));for(u in l)l.hasOwnProperty(u)&&!s.hasOwnProperty(u)&&"layout"!==u&&"paint"!==u&&"filter"!==u&&"metadata"!==u&&"minzoom"!==u&&"maxzoom"!==u&&(0===u.indexOf("paint.")?se(s[u],l[u],n,a,u.slice(6),ie.setPaintProperty):t.default$10(s[u],l[u])||n.push({command:ie.setLayerProperty,args:[a,u,l[u]]}));}else n.push({command:ie.removeLayer,args:[a]}),c=m[m.lastIndexOf(a)+1],n.push({command:ie.addLayer,args:[l,c]});}(a,i.layers,n);}catch(t){console.warn("Unable to compute style diff:",t),n=[{command:ie.setStyle,args:[i]}];}return n}var he=function(t,e,i){var n=this.boxCells=[],o=this.circleCells=[];this.xCellCount=Math.ceil(t/i),this.yCellCount=Math.ceil(e/i);for(var r=0;r<this.xCellCount*this.yCellCount;r++)n.push([]),o.push([]);this.circleKeys=[],this.boxKeys=[],this.bboxes=[],this.circles=[],this.width=t,this.height=e,this.xScale=this.xCellCount/t,this.yScale=this.yCellCount/e,this.boxUid=0,this.circleUid=0;};he.prototype.keysLength=function(){return this.boxKeys.length+this.circleKeys.length},he.prototype.insert=function(t,e,i,n,o){this._forEachCell(e,i,n,o,this._insertBoxCell,this.boxUid++),this.boxKeys.push(t),this.bboxes.push(e),this.bboxes.push(i),this.bboxes.push(n),this.bboxes.push(o);},he.prototype.insertCircle=function(t,e,i,n){this._forEachCell(e-n,i-n,e+n,i+n,this._insertCircleCell,this.circleUid++),this.circleKeys.push(t),this.circles.push(e),this.circles.push(i),this.circles.push(n);},he.prototype._insertBoxCell=function(t,e,i,n,o,r){this.boxCells[o].push(r);},he.prototype._insertCircleCell=function(t,e,i,n,o,r){this.circleCells[o].push(r);},he.prototype._query=function(t,e,i,n,o){if(i<0||t>this.width||n<0||e>this.height)return!o&&[];var r=[];if(t<=0&&e<=0&&this.width<=i&&this.height<=n){if(o)return!0;for(var a=0;a<this.boxKeys.length;a++)r.push({key:this.boxKeys[a],x1:this.bboxes[4*a],y1:this.bboxes[4*a+1],x2:this.bboxes[4*a+2],y2:this.bboxes[4*a+3]});for(var s=0;s<this.circleKeys.length;s++){var l=this.circles[3*s],c=this.circles[3*s+1],u=this.circles[3*s+2];r.push({key:this.circleKeys[s],x1:l-u,y1:c-u,x2:l+u,y2:c+u});}}else{var h={hitTest:o,seenUids:{box:{},circle:{}}};this._forEachCell(t,e,i,n,this._queryCell,r,h);}return o?r.length>0:r},he.prototype._queryCircle=function(t,e,i,n){var o=t-i,r=t+i,a=e-i,s=e+i;if(r<0||o>this.width||s<0||a>this.height)return!n&&[];var l=[],c={hitTest:n,circle:{x:t,y:e,radius:i},seenUids:{box:{},circle:{}}};return this._forEachCell(o,a,r,s,this._queryCellCircle,l,c),n?l.length>0:l},he.prototype.query=function(t,e,i,n){return this._query(t,e,i,n,!1)},he.prototype.hitTest=function(t,e,i,n){return this._query(t,e,i,n,!0)},he.prototype.hitTestCircle=function(t,e,i){return this._queryCircle(t,e,i,!0)},he.prototype._queryCell=function(t,e,i,n,o,r,a){var s=a.seenUids,l=this.boxCells[o];if(null!==l)for(var c=this.bboxes,u=0,h=l;u<h.length;u+=1){var p=h[u];if(!s.box[p]){s.box[p]=!0;var d=4*p;if(t<=c[d+2]&&e<=c[d+3]&&i>=c[d+0]&&n>=c[d+1]){if(a.hitTest)return r.push(!0),!0;r.push({key:this.boxKeys[p],x1:c[d],y1:c[d+1],x2:c[d+2],y2:c[d+3]});}}}var f=this.circleCells[o];if(null!==f)for(var m=this.circles,_=0,g=f;_<g.length;_+=1){var v=g[_];if(!s.circle[v]){s.circle[v]=!0;var y=3*v;if(this._circleAndRectCollide(m[y],m[y+1],m[y+2],t,e,i,n)){if(a.hitTest)return r.push(!0),!0;var x=m[y],b=m[y+1],w=m[y+2];r.push({key:this.circleKeys[v],x1:x-w,y1:b-w,x2:x+w,y2:b+w});}}}},he.prototype._queryCellCircle=function(t,e,i,n,o,r,a){var s=a.circle,l=a.seenUids,c=this.boxCells[o];if(null!==c)for(var u=this.bboxes,h=0,p=c;h<p.length;h+=1){var d=p[h];if(!l.box[d]){l.box[d]=!0;var f=4*d;if(this._circleAndRectCollide(s.x,s.y,s.radius,u[f+0],u[f+1],u[f+2],u[f+3]))return r.push(!0),!0}}var m=this.circleCells[o];if(null!==m)for(var _=this.circles,g=0,v=m;g<v.length;g+=1){var y=v[g];if(!l.circle[y]){l.circle[y]=!0;var x=3*y;if(this._circlesCollide(_[x],_[x+1],_[x+2],s.x,s.y,s.radius))return r.push(!0),!0}}},he.prototype._forEachCell=function(t,e,i,n,o,r,a){for(var s=this._convertToXCellCoord(t),l=this._convertToYCellCoord(e),c=this._convertToXCellCoord(i),u=this._convertToYCellCoord(n),h=s;h<=c;h++)for(var p=l;p<=u;p++){var d=this.xCellCount*p+h;if(o.call(this,t,e,i,n,d,r,a))return}},he.prototype._convertToXCellCoord=function(t){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(t*this.xScale)))},he.prototype._convertToYCellCoord=function(t){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(t*this.yScale)))},he.prototype._circlesCollide=function(t,e,i,n,o,r){var a=n-t,s=o-e,l=i+r;return l*l>a*a+s*s},he.prototype._circleAndRectCollide=function(t,e,i,n,o,r,a){var s=(r-n)/2,l=Math.abs(t-(n+s));if(l>s+i)return!1;var c=(a-o)/2,u=Math.abs(e-(o+c));if(u>c+i)return!1;if(l<=s||u<=c)return!0;var h=l-s,p=u-c;return h*h+p*p<=i*i};var pe=t.default$19.layout;function de(e,i,n,o,r){var a=t.mat4.identity(new Float32Array(16));return i?(t.mat4.identity(a),t.mat4.scale(a,a,[1/r,1/r,1]),n||t.mat4.rotateZ(a,a,o.angle)):(t.mat4.scale(a,a,[o.width/2,-o.height/2,1]),t.mat4.translate(a,a,[1,-1,0]),t.mat4.multiply(a,a,e)),a}function fe(e,i,n,o,r){var a=t.mat4.identity(new Float32Array(16));return i?(t.mat4.multiply(a,a,e),t.mat4.scale(a,a,[r,r,1]),n||t.mat4.rotateZ(a,a,-o.angle)):(t.mat4.scale(a,a,[1,-1,1]),t.mat4.translate(a,a,[-1,-1,0]),t.mat4.scale(a,a,[2/o.width,2/o.height,1])),a}function me(e,i){var n=[e.x,e.y,0,1];Ie(n,n,i);var o=n[3];return{point:new t.default$1(n[0]/o,n[1]/o),signedDistanceFromCamera:o}}function _e(t,e){var i=t[0]/t[3],n=t[1]/t[3];return i>=-e[0]&&i<=e[0]&&n>=-e[1]&&n<=e[1]}function ge(e,i,n,o,r,a,s,l){var c=o?e.textSizeData:e.iconSizeData,u=t.evaluateSizeForZoom(c,n.transform.zoom,pe.properties[o?"text-size":"icon-size"]),h=[256/n.width*2+1,256/n.height*2+1],p=o?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;p.clear();for(var d=e.lineVertexArray,f=o?e.text.placedSymbolArray:e.icon.placedSymbolArray,m=n.transform.width/n.transform.height,_=!1,g=0;g<f.length;g++){var v=f.get(g);if(v.hidden||v.writingMode===t.WritingMode.vertical&&!_)Te(v.numGlyphs,p);else{_=!1;var y=[v.anchorX,v.anchorY,0,1];if(t.vec4.transformMat4(y,y,i),_e(y,h)){var x=.5+y[3]/n.transform.cameraToCenterDistance*.5,b=t.evaluateSizeForFeature(c,u,v),w=s?b*x:b/x,E=new t.default$1(v.anchorX,v.anchorY),T=me(E,r).point,I={},C=xe(v,w,!1,l,i,r,a,e.glyphOffsetArray,d,p,T,E,I,m);_=C.useVertical,(C.notEnoughRoom||_||C.needsFlipping&&xe(v,w,!0,l,i,r,a,e.glyphOffsetArray,d,p,T,E,I,m).notEnoughRoom)&&Te(v.numGlyphs,p);}else Te(v.numGlyphs,p);}}o?e.text.dynamicLayoutVertexBuffer.updateData(p):e.icon.dynamicLayoutVertexBuffer.updateData(p);}function ve(t,e,i,n,o,r,a,s,l,c,u,h){var p=s.glyphStartIndex+s.numGlyphs,d=s.lineStartIndex,f=s.lineStartIndex+s.lineLength,m=e.getoffsetX(s.glyphStartIndex),_=e.getoffsetX(p-1),g=we(t*m,i,n,o,r,a,s.segment,d,f,l,c,u,h);if(!g)return null;var v=we(t*_,i,n,o,r,a,s.segment,d,f,l,c,u,h);return v?{first:g,last:v}:null}function ye(e,i,n,o){if(e===t.WritingMode.horizontal&&Math.abs(n.y-i.y)>Math.abs(n.x-i.x)*o)return{useVertical:!0};return(e===t.WritingMode.vertical?i.y<n.y:i.x>n.x)?{needsFlipping:!0}:null}function xe(e,i,n,o,r,a,s,l,c,u,h,p,d,f){var m,_=i/24,g=e.lineOffsetX*i,v=e.lineOffsetY*i;if(e.numGlyphs>1){var y=e.glyphStartIndex+e.numGlyphs,x=e.lineStartIndex,b=e.lineStartIndex+e.lineLength,w=ve(_,l,g,v,n,h,p,e,c,a,d,!1);if(!w)return{notEnoughRoom:!0};var E=me(w.first.point,s).point,T=me(w.last.point,s).point;if(o&&!n){var I=ye(e.writingMode,E,T,f);if(I)return I}m=[w.first];for(var C=e.glyphStartIndex+1;C<y-1;C++)m.push(we(_*l.getoffsetX(C),g,v,n,h,p,e.segment,x,b,c,a,d,!1));m.push(w.last);}else{if(o&&!n){var S=me(p,r).point,z=e.lineStartIndex+e.segment+1,A=new t.default$1(c.getx(z),c.gety(z)),R=me(A,r),D=R.signedDistanceFromCamera>0?R.point:be(p,A,S,1,r),M=ye(e.writingMode,S,D,f);if(M)return M}var L=we(_*l.getoffsetX(e.glyphStartIndex),g,v,n,h,p,e.segment,e.lineStartIndex,e.lineStartIndex+e.lineLength,c,a,d,!1);if(!L)return{notEnoughRoom:!0};m=[L];}for(var P=0,k=m;P<k.length;P+=1){var B=k[P];t.addDynamicAttributes(u,B.point,B.angle);}return{}}function be(t,e,i,n,o){var r=me(t.add(t.sub(e)._unit()),o).point,a=i.sub(r);return i.add(a._mult(n/a.mag()))}function we(e,i,n,o,r,a,s,l,c,u,h,p,d){var f=o?e-i:e+i,m=f>0?1:-1,_=0;o&&(m*=-1,_=Math.PI),m<0&&(_+=Math.PI);for(var g=m>0?l+s:l+s+1,v=g,y=r,x=r,b=0,w=0,E=Math.abs(f);b+w<=E;){if((g+=m)<l||g>=c)return null;if(x=y,void 0===(y=p[g])){var T=new t.default$1(u.getx(g),u.gety(g)),I=me(T,h);if(I.signedDistanceFromCamera>0)y=p[g]=I.point;else{var C=g-m;y=be(0===b?a:new t.default$1(u.getx(C),u.gety(C)),T,x,E-b+1,h);}}b+=w,w=x.dist(y);}var S=(E-b)/w,z=y.sub(x),A=z.mult(S)._add(x);return A._add(z._unit()._perp()._mult(n*m)),{point:A,angle:_+Math.atan2(y.y-x.y,y.x-x.x),tileDistance:d?{prevTileDistance:g-m===v?0:u.gettileUnitDistanceFromAnchor(g-m),lastSegmentViewportDistance:E-b}:null}}var Ee=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function Te(t,e){for(var i=0;i<t;i++){var n=e.length;e.resize(n+4),e.float32.set(Ee,3*n);}}function Ie(t,e,i){var n=e[0],o=e[1];return t[0]=i[0]*n+i[4]*o+i[12],t[1]=i[1]*n+i[5]*o+i[13],t[3]=i[3]*n+i[7]*o+i[15],t}t.default$20.mat4;var Ce=function(t,e,i){void 0===e&&(e=new he(t.width+200,t.height+200,25)),void 0===i&&(i=new he(t.width+200,t.height+200,25)),this.transform=t,this.grid=e,this.ignoredGrid=i,this.pitchfactor=Math.cos(t._pitch)*t.cameraToCenterDistance,this.screenRightBoundary=t.width+100,this.screenBottomBoundary=t.height+100;};function Se(t,e,i){t[e+4]=i?1:0;}function ze(e,i,n){return i*(t.default$8/(e.tileSize*Math.pow(2,n-e.tileID.overscaledZ)))}Ce.prototype.placeCollisionBox=function(t,e,i,n){var o=this.projectAndGetPerspectiveRatio(n,t.anchorPointX,t.anchorPointY),r=i*o.perspectiveRatio,a=t.x1*r+o.point.x,s=t.y1*r+o.point.y,l=t.x2*r+o.point.x,c=t.y2*r+o.point.y;return!e&&this.grid.hitTest(a,s,l,c)?{box:[],offscreen:!1}:{box:[a,s,l,c],offscreen:this.isOffscreen(a,s,l,c)}},Ce.prototype.approximateTileDistance=function(t,e,i,n,o){var r=o?1:n/this.pitchfactor,a=t.lastSegmentViewportDistance*i;return t.prevTileDistance+a+(r-1)*a*Math.abs(Math.sin(e))},Ce.prototype.placeCollisionCircles=function(e,i,n,o,r,a,s,l,c,u,h,p,d){var f=[],m=this.projectAnchor(u,a.anchorX,a.anchorY),_=c/24,g=a.lineOffsetX*c,v=a.lineOffsetY*c,y=new t.default$1(a.anchorX,a.anchorY),x=ve(_,l,g,v,!1,me(y,h).point,y,a,s,h,{},!0),b=!1,w=!0,E=m.perspectiveRatio*o,T=1/(o*n),I=0,C=0;x&&(I=this.approximateTileDistance(x.first.tileDistance,x.first.angle,T,m.cameraDistance,d),C=this.approximateTileDistance(x.last.tileDistance,x.last.angle,T,m.cameraDistance,d));for(var S=0;S<e.length;S+=5){var z=e[S],A=e[S+1],R=e[S+2],D=e[S+3];if(!x||D<-I||D>C)Se(e,S,!1);else{var M=this.projectPoint(u,z,A),L=R*E;if(f.length>0){var P=M.x-f[f.length-4],k=M.y-f[f.length-3];if(L*L*2>P*P+k*k)if(S+8<e.length){var B=e[S+8];if(B>-I&&B<C){Se(e,S,!1);continue}}}var O=S/5;if(f.push(M.x,M.y,L,O),Se(e,S,!0),w=w&&this.isOffscreen(M.x-L,M.y-L,M.x+L,M.y+L),!i&&this.grid.hitTestCircle(M.x,M.y,L)){if(!p)return{circles:[],offscreen:!1};b=!0;}}}return{circles:b?[]:f,offscreen:w}},Ce.prototype.queryRenderedSymbols=function(e){if(0===e.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return{};for(var i=[],n=1/0,o=1/0,r=-1/0,a=-1/0,s=0,l=e;s<l.length;s+=1){var c=l[s],u=new t.default$1(c.x+100,c.y+100);n=Math.min(n,u.x),o=Math.min(o,u.y),r=Math.max(r,u.x),a=Math.max(a,u.y),i.push(u);}for(var h={},p={},d=0,f=this.grid.query(n,o,r,a).concat(this.ignoredGrid.query(n,o,r,a));d<f.length;d+=1){var m=f[d],_=m.key;if(void 0===h[_.bucketInstanceId]&&(h[_.bucketInstanceId]={}),!h[_.bucketInstanceId][_.featureIndex]){var g=[new t.default$1(m.x1,m.y1),new t.default$1(m.x2,m.y1),new t.default$1(m.x2,m.y2),new t.default$1(m.x1,m.y2)];t.polygonIntersectsPolygon(i,g)&&(h[_.bucketInstanceId][_.featureIndex]=!0,void 0===p[_.bucketInstanceId]&&(p[_.bucketInstanceId]=[]),p[_.bucketInstanceId].push(_.featureIndex));}}return p},Ce.prototype.insertCollisionBox=function(t,e,i,n){var o={bucketInstanceId:i,featureIndex:n};(e?this.ignoredGrid:this.grid).insert(o,t[0],t[1],t[2],t[3]);},Ce.prototype.insertCollisionCircles=function(t,e,i,n){for(var o=e?this.ignoredGrid:this.grid,r={bucketInstanceId:i,featureIndex:n},a=0;a<t.length;a+=4)o.insertCircle(r,t[a],t[a+1],t[a+2]);},Ce.prototype.projectAnchor=function(t,e,i){var n=[e,i,0,1];return Ie(n,n,t),{perspectiveRatio:.5+this.transform.cameraToCenterDistance/n[3]*.5,cameraDistance:n[3]}},Ce.prototype.projectPoint=function(e,i,n){var o=[i,n,0,1];return Ie(o,o,e),new t.default$1((o[0]/o[3]+1)/2*this.transform.width+100,(-o[1]/o[3]+1)/2*this.transform.height+100)},Ce.prototype.projectAndGetPerspectiveRatio=function(e,i,n){var o=[i,n,0,1];return Ie(o,o,e),{point:new t.default$1((o[0]/o[3]+1)/2*this.transform.width+100,(-o[1]/o[3]+1)/2*this.transform.height+100),perspectiveRatio:.5+this.transform.cameraToCenterDistance/o[3]*.5}},Ce.prototype.isOffscreen=function(t,e,i,n){return i<100||t>=this.screenRightBoundary||n<100||e>this.screenBottomBoundary};var Ae=t.default$19.layout,Re=function(t,e,i,n){this.opacity=t?Math.max(0,Math.min(1,t.opacity+(t.placed?e:-e))):n&&i?1:0,this.placed=i;};Re.prototype.isHidden=function(){return 0===this.opacity&&!this.placed};var De=function(t,e,i,n,o){this.text=new Re(t?t.text:null,e,i,o),this.icon=new Re(t?t.icon:null,e,n,o);};De.prototype.isHidden=function(){return this.text.isHidden()&&this.icon.isHidden()};var Me=function(t,e,i){this.text=t,this.icon=e,this.skipFade=i;},Le=function(t,e){this.transform=t.clone(),this.collisionIndex=new Ce(this.transform),this.placements={},this.opacities={},this.stale=!1,this.fadeDuration=e,this.retainedQueryData={};};function Pe(t,e,i){t.emplaceBack(e?1:0,i?1:0),t.emplaceBack(e?1:0,i?1:0),t.emplaceBack(e?1:0,i?1:0),t.emplaceBack(e?1:0,i?1:0);}Le.prototype.placeLayerTile=function(e,i,n,o){var r=i.getBucket(e),a=i.latestFeatureIndex;if(r&&a&&e.id===r.layerIds[0]){var s=i.collisionBoxArray,l=r.layers[0].layout,c=Math.pow(2,this.transform.zoom-i.tileID.overscaledZ),u=i.tileSize/t.default$8,h=this.transform.calculatePosMatrix(i.tileID.toUnwrapped()),p=de(h,"map"===l.get("text-pitch-alignment"),"map"===l.get("text-rotation-alignment"),this.transform,ze(i,1,this.transform.zoom)),d=de(h,"map"===l.get("icon-pitch-alignment"),"map"===l.get("icon-rotation-alignment"),this.transform,ze(i,1,this.transform.zoom));this.retainedQueryData[r.bucketInstanceId]=new function(t,e,i,n,o){this.bucketInstanceId=t,this.featureIndex=e,this.sourceLayerIndex=i,this.bucketIndex=n,this.tileID=o;}(r.bucketInstanceId,a,r.sourceLayerIndex,r.index,i.tileID),this.placeLayerBucket(r,h,p,d,c,u,n,o,s);}},Le.prototype.placeLayerBucket=function(e,i,n,o,r,a,s,l,c){for(var u=e.layers[0].layout,h=t.evaluateSizeForZoom(e.textSizeData,this.transform.zoom,Ae.properties["text-size"]),p=!e.hasTextData()||u.get("text-optional"),d=!e.hasIconData()||u.get("icon-optional"),f=0,m=e.symbolInstances;f<m.length;f+=1){var _=m[f];if(!l[_.crossTileID]){var g=void 0!==_.feature.text,v=void 0!==_.feature.icon,y=!0,x=null,b=null,w=null,E=0,T=0;_.collisionArrays||(_.collisionArrays=e.deserializeCollisionBoxes(c,_.textBoxStartIndex,_.textBoxEndIndex,_.iconBoxStartIndex,_.iconBoxEndIndex)),_.collisionArrays.textFeatureIndex&&(E=_.collisionArrays.textFeatureIndex),_.collisionArrays.textBox&&(g=(x=this.collisionIndex.placeCollisionBox(_.collisionArrays.textBox,u.get("text-allow-overlap"),a,i)).box.length>0,y=y&&x.offscreen);var I=_.collisionArrays.textCircles;if(I){var C=e.text.placedSymbolArray.get(_.placedTextSymbolIndices[0]),S=t.evaluateSizeForFeature(e.textSizeData,h,C);b=this.collisionIndex.placeCollisionCircles(I,u.get("text-allow-overlap"),r,a,_.key,C,e.lineVertexArray,e.glyphOffsetArray,S,i,n,s,"map"===u.get("text-pitch-alignment")),g=u.get("text-allow-overlap")||b.circles.length>0,y=y&&b.offscreen;}_.collisionArrays.iconFeatureIndex&&(T=_.collisionArrays.iconFeatureIndex),_.collisionArrays.iconBox&&(v=(w=this.collisionIndex.placeCollisionBox(_.collisionArrays.iconBox,u.get("icon-allow-overlap"),a,i)).box.length>0,y=y&&w.offscreen),p||d?d?p||(v=v&&g):g=v&&g:v=g=v&&g,g&&x&&this.collisionIndex.insertCollisionBox(x.box,u.get("text-ignore-placement"),e.bucketInstanceId,E),v&&w&&this.collisionIndex.insertCollisionBox(w.box,u.get("icon-ignore-placement"),e.bucketInstanceId,T),g&&b&&this.collisionIndex.insertCollisionCircles(b.circles,u.get("text-ignore-placement"),e.bucketInstanceId,E),this.placements[_.crossTileID]=new Me(g,v,y||e.justReloaded),l[_.crossTileID]=!0;}}e.justReloaded=!1;},Le.prototype.commit=function(t,e){this.commitTime=e;var i=!1,n=t&&0!==this.fadeDuration?(this.commitTime-t.commitTime)/this.fadeDuration:1,o=t?t.opacities:{};for(var r in this.placements){var a=this.placements[r],s=o[r];s?(this.opacities[r]=new De(s,n,a.text,a.icon),i=i||a.text!==s.text.placed||a.icon!==s.icon.placed):(this.opacities[r]=new De(null,n,a.text,a.icon,a.skipFade),i=i||a.text||a.icon);}for(var l in o){var c=o[l];if(!this.opacities[l]){var u=new De(c,n,!1,!1);u.isHidden()||(this.opacities[l]=u,i=i||c.text.placed||c.icon.placed);}}i?this.lastPlacementChangeTime=e:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=t?t.lastPlacementChangeTime:e);},Le.prototype.updateLayerOpacities=function(t,e){for(var i={},n=0,o=e;n<o.length;n+=1){var r=o[n],a=r.getBucket(t);a&&r.latestFeatureIndex&&t.id===a.layerIds[0]&&this.updateBucketOpacities(a,i,r.collisionBoxArray);}},Le.prototype.updateBucketOpacities=function(t,e,i){t.hasTextData()&&t.text.opacityVertexArray.clear(),t.hasIconData()&&t.icon.opacityVertexArray.clear(),t.hasCollisionBoxData()&&t.collisionBox.collisionVertexArray.clear(),t.hasCollisionCircleData()&&t.collisionCircle.collisionVertexArray.clear();for(var n=t.layers[0].layout,o=new De(null,0,!1,!1,!0),r=new De(null,0,n.get("text-allow-overlap"),n.get("icon-allow-overlap"),!0),a=0;a<t.symbolInstances.length;a++){var s=t.symbolInstances[a],l=e[s.crossTileID],c=this.opacities[s.crossTileID];l?c=o:c||(c=r,this.opacities[s.crossTileID]=c),e[s.crossTileID]=!0;var u=s.numGlyphVertices>0||s.numVerticalGlyphVertices>0,h=s.numIconVertices>0;if(u){for(var p=Ve(c.text),d=(s.numGlyphVertices+s.numVerticalGlyphVertices)/4,f=0;f<d;f++)t.text.opacityVertexArray.emplaceBack(p);for(var m=0,_=s.placedTextSymbolIndices;m<_.length;m+=1){var g=_[m];t.text.placedSymbolArray.get(g).hidden=c.text.isHidden();}}if(h){for(var v=Ve(c.icon),y=0;y<s.numIconVertices/4;y++)t.icon.opacityVertexArray.emplaceBack(v);t.icon.placedSymbolArray.get(a).hidden=c.icon.isHidden();}s.collisionArrays||(s.collisionArrays=t.deserializeCollisionBoxes(i,s.textBoxStartIndex,s.textBoxEndIndex,s.iconBoxStartIndex,s.iconBoxEndIndex));var x=s.collisionArrays;if(x){x.textBox&&t.hasCollisionBoxData()&&Pe(t.collisionBox.collisionVertexArray,c.text.placed,!1),x.iconBox&&t.hasCollisionBoxData()&&Pe(t.collisionBox.collisionVertexArray,c.icon.placed,!1);var b=x.textCircles;if(b&&t.hasCollisionCircleData())for(var w=0;w<b.length;w+=5){var E=l||0===b[w+4];Pe(t.collisionCircle.collisionVertexArray,c.text.placed,E);}}}t.sortFeatures(this.transform.angle),this.retainedQueryData[t.bucketInstanceId]&&(this.retainedQueryData[t.bucketInstanceId].featureSortOrder=t.featureSortOrder),t.hasTextData()&&t.text.opacityVertexBuffer&&t.text.opacityVertexBuffer.updateData(t.text.opacityVertexArray),t.hasIconData()&&t.icon.opacityVertexBuffer&&t.icon.opacityVertexBuffer.updateData(t.icon.opacityVertexArray),t.hasCollisionBoxData()&&t.collisionBox.collisionVertexBuffer&&t.collisionBox.collisionVertexBuffer.updateData(t.collisionBox.collisionVertexArray),t.hasCollisionCircleData()&&t.collisionCircle.collisionVertexBuffer&&t.collisionCircle.collisionVertexBuffer.updateData(t.collisionCircle.collisionVertexArray);},Le.prototype.symbolFadeChange=function(t){return 0===this.fadeDuration?1:(t-this.commitTime)/this.fadeDuration},Le.prototype.hasTransitions=function(t){return this.stale||t-this.lastPlacementChangeTime<this.fadeDuration},Le.prototype.stillRecent=function(t){return"undefined"!==this.commitTime&&this.commitTime+this.fadeDuration>t},Le.prototype.setStale=function(){this.stale=!0;};var ke=Math.pow(2,25),Be=Math.pow(2,24),Oe=Math.pow(2,17),Fe=Math.pow(2,16),Ne=Math.pow(2,9),Ue=Math.pow(2,8),Ze=Math.pow(2,1);function Ve(t){if(0===t.opacity&&!t.placed)return 0;if(1===t.opacity&&t.placed)return 4294967295;var e=t.placed?1:0,i=Math.floor(127*t.opacity);return i*ke+e*Be+i*Oe+e*Fe+i*Ne+e*Ue+i*Ze+e}var je=function(){this._currentTileIndex=0,this._seenCrossTileIDs={};};je.prototype.continuePlacement=function(t,e,i,n,o){for(;this._currentTileIndex<t.length;){var r=t[this._currentTileIndex];if(e.placeLayerTile(n,r,i,this._seenCrossTileIDs),this._currentTileIndex++,o())return!0}};var $e=function(t,e,i,n,o){this.placement=new Le(t,o),this._currentPlacementIndex=e.length-1,this._forceFullPlacement=i,this._showCollisionBoxes=n,this._done=!1;};$e.prototype.isDone=function(){return this._done},$e.prototype.continuePlacement=function(t,e,i){for(var n=this,o=r.now(),a=function(){var t=r.now()-o;return!n._forceFullPlacement&&t>2};this._currentPlacementIndex>=0;){var s=e[t[n._currentPlacementIndex]],l=n.placement.collisionIndex.transform.zoom;if("symbol"===s.type&&(!s.minzoom||s.minzoom<=l)&&(!s.maxzoom||s.maxzoom>l)){if(n._inProgressLayer||(n._inProgressLayer=new je),n._inProgressLayer.continuePlacement(i[s.source],n.placement,n._showCollisionBoxes,s,a))return;delete n._inProgressLayer;}n._currentPlacementIndex--;}this._done=!0;},$e.prototype.commit=function(t,e){return this.placement.commit(t,e),this.placement};var Ge=512/t.default$8/2,We=function(t,e,i){this.tileID=t,this.indexedSymbolInstances={},this.bucketInstanceId=i;for(var n=0,o=e;n<o.length;n+=1){var r=o[n],a=r.key;this.indexedSymbolInstances[a]||(this.indexedSymbolInstances[a]=[]),this.indexedSymbolInstances[a].push({crossTileID:r.crossTileID,coord:this.getScaledCoordinates(r,t)});}};We.prototype.getScaledCoordinates=function(e,i){var n=i.canonical.z-this.tileID.canonical.z,o=Ge/Math.pow(2,n),r=e.anchor;return{x:Math.floor((i.canonical.x*t.default$8+r.x)*o),y:Math.floor((i.canonical.y*t.default$8+r.y)*o)}},We.prototype.findMatches=function(t,e,i){for(var n=this.tileID.canonical.z<e.canonical.z?1:Math.pow(2,this.tileID.canonical.z-e.canonical.z),o=0,r=t;o<r.length;o+=1){var a=r[o];if(!a.crossTileID){var s=this.indexedSymbolInstances[a.key];if(s)for(var l=this.getScaledCoordinates(a,e),c=0,u=s;c<u.length;c+=1){var h=u[c];if(Math.abs(h.coord.x-l.x)<=n&&Math.abs(h.coord.y-l.y)<=n&&!i[h.crossTileID]){i[h.crossTileID]=!0,a.crossTileID=h.crossTileID;break}}}}};var qe=function(){this.maxCrossTileID=0;};qe.prototype.generate=function(){return++this.maxCrossTileID};var Xe=function(){this.indexes={},this.usedCrossTileIDs={},this.lng=0;};Xe.prototype.handleWrapJump=function(t){var e=Math.round((t-this.lng)/360);if(0!==e)for(var i in this.indexes){var n=this.indexes[i],o={};for(var r in n){var a=n[r];a.tileID=a.tileID.unwrapTo(a.tileID.wrap+e),o[a.tileID.key]=a;}this.indexes[i]=o;}this.lng=t;},Xe.prototype.addBucket=function(t,e,i){if(this.indexes[t.overscaledZ]&&this.indexes[t.overscaledZ][t.key]){if(this.indexes[t.overscaledZ][t.key].bucketInstanceId===e.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(t.overscaledZ,this.indexes[t.overscaledZ][t.key]);}for(var n=0,o=e.symbolInstances;n<o.length;n+=1){o[n].crossTileID=0;}this.usedCrossTileIDs[t.overscaledZ]||(this.usedCrossTileIDs[t.overscaledZ]={});var r=this.usedCrossTileIDs[t.overscaledZ];for(var a in this.indexes){var s=this.indexes[a];if(Number(a)>t.overscaledZ)for(var l in s){var c=s[l];c.tileID.isChildOf(t)&&c.findMatches(e.symbolInstances,t,r);}else{var u=s[t.scaledTo(Number(a)).key];u&&u.findMatches(e.symbolInstances,t,r);}}for(var h=0,p=e.symbolInstances;h<p.length;h+=1){var d=p[h];d.crossTileID||(d.crossTileID=i.generate(),r[d.crossTileID]=!0);}return void 0===this.indexes[t.overscaledZ]&&(this.indexes[t.overscaledZ]={}),this.indexes[t.overscaledZ][t.key]=new We(t,e.symbolInstances,e.bucketInstanceId),!0},Xe.prototype.removeBucketCrossTileIDs=function(t,e){for(var i in e.indexedSymbolInstances)for(var n=0,o=e.indexedSymbolInstances[i];n<o.length;n+=1){var r=o[n];delete this.usedCrossTileIDs[t][r.crossTileID];}},Xe.prototype.removeStaleBuckets=function(t){var e=!1;for(var i in this.indexes){var n=this.indexes[i];for(var o in n)t[n[o].bucketInstanceId]||(this.removeBucketCrossTileIDs(i,n[o]),delete n[o],e=!0);}return e};var He=function(){this.layerIndexes={},this.crossTileIDs=new qe,this.maxBucketInstanceId=0,this.bucketsInCurrentPlacement={};};He.prototype.addLayer=function(t,e,i){var n=this.layerIndexes[t.id];void 0===n&&(n=this.layerIndexes[t.id]=new Xe);var o=!1,r={};n.handleWrapJump(i);for(var a=0,s=e;a<s.length;a+=1){var l=s[a],c=l.getBucket(t);c&&t.id===c.layerIds[0]&&(c.bucketInstanceId||(c.bucketInstanceId=++this.maxBucketInstanceId),n.addBucket(l.tileID,c,this.crossTileIDs)&&(o=!0),r[c.bucketInstanceId]=!0);}return n.removeStaleBuckets(r)&&(o=!0),o},He.prototype.pruneUnusedLayers=function(t){var e={};for(var i in t.forEach(function(t){e[t]=!0;}),this.layerIndexes)e[i]||delete this.layerIndexes[i];};var Ke=function(e,i){return t.emitValidationErrors(e,i&&i.filter(function(t){return"source.canvas"!==t.identifier}))},Ye=t.pick(ie,["addLayer","removeLayer","setPaintProperty","setLayoutProperty","setFilter","addSource","removeSource","setLayerZoomRange","setLight","setTransition","setGeoJSONSourceData"]),Je=t.pick(ie,["setCenter","setZoom","setBearing","setPitch"]),Qe=function(e){function i(n,o){var r=this;void 0===o&&(o={}),e.call(this),this.map=n,this.dispatcher=new $((Jt||(Jt=new Qt),Jt),this),this.imageManager=new L,this.glyphManager=new N(n._transformRequest,o.localIdeographFontFamily),this.lineAtlas=new j(256,512),this.crossTileSymbolIndex=new He,this._layers={},this._order=[],this.sourceCaches={},this.zoomHistory=new t.default$23,this._loaded=!1,this._resetUpdates();var a=this;this._rtlTextPluginCallback=i.registerForPluginAvailability(function(t){for(var e in a.dispatcher.broadcast("loadRTLTextPlugin",t.pluginURL,t.completionCallback),a.sourceCaches)a.sourceCaches[e].reload();}),this.on("data",function(t){if("source"===t.dataType&&"metadata"===t.sourceDataType){var e=r.sourceCaches[t.sourceId];if(e){var i=e.getSource();if(i&&i.vectorLayerIds)for(var n in r._layers){var o=r._layers[n];o.source===i.id&&r._validateLayer(o);}}}});}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.loadURL=function(e,i){var n=this;void 0===i&&(i={}),this.fire(new t.Event("dataloading",{dataType:"style"}));var o="boolean"==typeof i.validate?i.validate:!y(e);e=function(t,e){if(!y(t))return t;var i=C(t);return i.path="/styles/v1"+i.path,v(i,e)}(e,i.accessToken);var r=this.map._transformRequest(e,t.ResourceType.Style);t.getJSON(r,function(e,i){e?n.fire(new t.ErrorEvent(e)):i&&n._load(i,o);});},i.prototype.loadJSON=function(e,i){var n=this;void 0===i&&(i={}),this.fire(new t.Event("dataloading",{dataType:"style"})),r.frame(function(){n._load(e,!1!==i.validate);});},i.prototype._load=function(e,i){var n=this;if(!i||!Ke(this,t.validateStyle(e))){for(var o in this._loaded=!0,this.stylesheet=e,e.sources)n.addSource(o,e.sources[o],{validate:!1});e.sprite?function(e,i,n){var o,a,s,l=r.devicePixelRatio>1?"@2x":"";function c(){if(s)n(s);else if(o&&a){var e=r.getImageData(a),i={};for(var l in o){var c=o[l],u=c.width,h=c.height,p=c.x,d=c.y,f=c.sdf,m=c.pixelRatio,_=new t.RGBAImage({width:u,height:h});t.RGBAImage.copy(e,_,{x:p,y:d},{x:0,y:0},{width:u,height:h}),i[l]={data:_,pixelRatio:m,sdf:f};}n(null,i);}}t.getJSON(i(w(e,l,".json"),t.ResourceType.SpriteJSON),function(t,e){s||(s=t,o=e,c());}),t.getImage(i(w(e,l,".png"),t.ResourceType.SpriteImage),function(t,e){s||(s=t,a=e,c());});}(e.sprite,this.map._transformRequest,function(e,i){if(e)n.fire(new t.ErrorEvent(e));else if(i)for(var o in i)n.imageManager.addImage(o,i[o]);n.imageManager.setLoaded(!0),n.fire(new t.Event("data",{dataType:"style"}));}):this.imageManager.setLoaded(!0),this.glyphManager.setURL(e.glyphs);var a=ee(this.stylesheet.layers);this._order=a.map(function(t){return t.id}),this._layers={};for(var s=0,l=a;s<l.length;s+=1){var c=l[s];(c=t.default$22(c)).setEventedParent(n,{layer:{id:c.id}}),n._layers[c.id]=c;}this.dispatcher.broadcast("setLayers",this._serializeLayers(this._order)),this.light=new V(this.stylesheet.light),this.fire(new t.Event("data",{dataType:"style"})),this.fire(new t.Event("style.load"));}},i.prototype._validateLayer=function(e){var i=this.sourceCaches[e.source];if(i){var n=e.sourceLayer;if(n){var o=i.getSource();("geojson"===o.type||o.vectorLayerIds&&-1===o.vectorLayerIds.indexOf(n))&&this.fire(new t.ErrorEvent(new Error('Source layer "'+n+'" does not exist on source "'+o.id+'" as specified by style layer "'+e.id+'"')));}}},i.prototype.loaded=function(){if(!this._loaded)return!1;if(Object.keys(this._updatedSources).length)return!1;for(var t in this.sourceCaches)if(!this.sourceCaches[t].loaded())return!1;return!!this.imageManager.isLoaded()},i.prototype._serializeLayers=function(t){var e=this;return t.map(function(t){return e._layers[t].serialize()})},i.prototype.hasTransitions=function(){if(this.light&&this.light.hasTransition())return!0;for(var t in this.sourceCaches)if(this.sourceCaches[t].hasTransition())return!0;for(var e in this._layers)if(this._layers[e].hasTransition())return!0;return!1},i.prototype._checkLoaded=function(){if(!this._loaded)throw new Error("Style is not done loading")},i.prototype.update=function(e){if(this._loaded){if(this._changed){var i=Object.keys(this._updatedLayers),n=Object.keys(this._removedLayers);for(var o in(i.length||n.length)&&this._updateWorkerLayers(i,n),this._updatedSources){var r=this._updatedSources[o];"reload"===r?this._reloadSource(o):"clear"===r&&this._clearSource(o);}for(var a in this._updatedPaintProps)this._layers[a].updateTransitions(e);this.light.updateTransitions(e),this._resetUpdates(),this.fire(new t.Event("data",{dataType:"style"}));}for(var s in this.sourceCaches)this.sourceCaches[s].used=!1;for(var l=0,c=this._order;l<c.length;l+=1){var u=c[l],h=this._layers[u];h.recalculate(e),!h.isHidden(e.zoom)&&h.source&&(this.sourceCaches[h.source].used=!0);}this.light.recalculate(e),this.z=e.zoom;}},i.prototype._updateWorkerLayers=function(t,e){this.dispatcher.broadcast("updateLayers",{layers:this._serializeLayers(t),removedIds:e});},i.prototype._resetUpdates=function(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={};},i.prototype.setState=function(e){var i=this;if(this._checkLoaded(),Ke(this,t.validateStyle(e)))return!1;(e=t.clone(e)).layers=ee(e.layers);var n=ue(this.serialize(),e).filter(function(t){return!(t.command in Je)});if(0===n.length)return!1;var o=n.filter(function(t){return!(t.command in Ye)});if(o.length>0)throw new Error("Unimplemented: "+o.map(function(t){return t.command}).join(", ")+".");return n.forEach(function(t){"setTransition"!==t.command&&i[t.command].apply(i,t.args);}),this.stylesheet=e,!0},i.prototype.addImage=function(e,i){if(this.getImage(e))return this.fire(new t.ErrorEvent(new Error("An image with this name already exists.")));this.imageManager.addImage(e,i),this.fire(new t.Event("data",{dataType:"style"}));},i.prototype.getImage=function(t){return this.imageManager.getImage(t)},i.prototype.removeImage=function(e){if(!this.getImage(e))return this.fire(new t.ErrorEvent(new Error("No image with this name exists.")));this.imageManager.removeImage(e),this.fire(new t.Event("data",{dataType:"style"}));},i.prototype.addSource=function(e,i,n){var o=this;if(this._checkLoaded(),void 0!==this.sourceCaches[e])throw new Error("There is already a source with this ID");if(!i.type)throw new Error("The type property must be defined, but the only the following properties were given: "+Object.keys(i).join(", ")+".");if(!(["vector","raster","geojson","video","image"].indexOf(i.type)>=0)||!this._validate(t.validateStyle.source,"sources."+e,i,null,n)){this.map&&this.map._collectResourceTiming&&(i.collectResourceTiming=!0);var r=this.sourceCaches[e]=new Xt(e,i,this.dispatcher);r.style=this,r.setEventedParent(this,function(){return{isSourceLoaded:o.loaded(),source:r.serialize(),sourceId:e}}),r.onAdd(this.map),this._changed=!0;}},i.prototype.removeSource=function(e){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error("There is no source with this ID");for(var i in this._layers)if(this._layers[i].source===e)return this.fire(new t.ErrorEvent(new Error('Source "'+e+'" cannot be removed while layer "'+i+'" is using it.')));var n=this.sourceCaches[e];delete this.sourceCaches[e],delete this._updatedSources[e],n.fire(new t.Event("data",{sourceDataType:"metadata",dataType:"source",sourceId:e})),n.setEventedParent(null),n.clearTiles(),n.onRemove&&n.onRemove(this.map),this._changed=!0;},i.prototype.setGeoJSONSourceData=function(t,e){this._checkLoaded(),this.sourceCaches[t].getSource().setData(e),this._changed=!0;},i.prototype.getSource=function(t){return this.sourceCaches[t]&&this.sourceCaches[t].getSource()},i.prototype.addLayer=function(e,i,n){this._checkLoaded();var o=e.id;if(this.getLayer(o))this.fire(new t.ErrorEvent(new Error('Layer with id "'+o+'" already exists on this map')));else if("object"==typeof e.source&&(this.addSource(o,e.source),e=t.clone(e),e=t.extend(e,{source:o})),!this._validate(t.validateStyle.layer,"layers."+o,e,{arrayIndex:-1},n)){var r=t.default$22(e);this._validateLayer(r),r.setEventedParent(this,{layer:{id:o}});var a=i?this._order.indexOf(i):this._order.length;if(i&&-1===a)this.fire(new t.ErrorEvent(new Error('Layer with id "'+i+'" does not exist on this map.')));else{if(this._order.splice(a,0,o),this._layerOrderChanged=!0,this._layers[o]=r,this._removedLayers[o]&&r.source){var s=this._removedLayers[o];delete this._removedLayers[o],s.type!==r.type?this._updatedSources[r.source]="clear":(this._updatedSources[r.source]="reload",this.sourceCaches[r.source].pause());}this._updateLayer(r);}}},i.prototype.moveLayer=function(e,i){if(this._checkLoaded(),this._changed=!0,this._layers[e]){if(e!==i){var n=this._order.indexOf(e);this._order.splice(n,1);var o=i?this._order.indexOf(i):this._order.length;i&&-1===o?this.fire(new t.ErrorEvent(new Error('Layer with id "'+i+'" does not exist on this map.'))):(this._order.splice(o,0,e),this._layerOrderChanged=!0);}}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be moved.")));},i.prototype.removeLayer=function(e){this._checkLoaded();var i=this._layers[e];if(i){i.setEventedParent(null);var n=this._order.indexOf(e);this._order.splice(n,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[e]=i,delete this._layers[e],delete this._updatedLayers[e],delete this._updatedPaintProps[e];}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be removed.")));},i.prototype.getLayer=function(t){return this._layers[t]},i.prototype.setLayerZoomRange=function(e,i,n){this._checkLoaded();var o=this.getLayer(e);o?o.minzoom===i&&o.maxzoom===n||(null!=i&&(o.minzoom=i),null!=n&&(o.maxzoom=n),this._updateLayer(o)):this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot have zoom extent.")));},i.prototype.setFilter=function(e,i){this._checkLoaded();var n=this.getLayer(e);if(n){if(!t.default$10(n.filter,i))return null==i?(n.filter=void 0,void this._updateLayer(n)):void(this._validate(t.validateStyle.filter,"layers."+n.id+".filter",i)||(n.filter=t.clone(i),this._updateLayer(n)))}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be filtered.")));},i.prototype.getFilter=function(e){return t.clone(this.getLayer(e).filter)},i.prototype.setLayoutProperty=function(e,i,n){this._checkLoaded();var o=this.getLayer(e);o?t.default$10(o.getLayoutProperty(i),n)||(o.setLayoutProperty(i,n),this._updateLayer(o)):this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be styled.")));},i.prototype.getLayoutProperty=function(t,e){return this.getLayer(t).getLayoutProperty(e)},i.prototype.setPaintProperty=function(e,i,n){this._checkLoaded();var o=this.getLayer(e);if(o){if(!t.default$10(o.getPaintProperty(i),n)){var r=o._transitionablePaint._values[i].value.isDataDriven();o.setPaintProperty(i,n),(o._transitionablePaint._values[i].value.isDataDriven()||r)&&this._updateLayer(o),this._changed=!0,this._updatedPaintProps[e]=!0;}}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be styled.")));},i.prototype.getPaintProperty=function(t,e){return this.getLayer(t).getPaintProperty(e)},i.prototype.getTransition=function(){return t.extend({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)},i.prototype.serialize=function(){var e=this;return t.filterObject({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,light:this.stylesheet.light,center:this.stylesheet.center,zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,sources:t.mapObject(this.sourceCaches,function(t){return t.serialize()}),layers:this._order.map(function(t){return e._layers[t].serialize()})},function(t){return void 0!==t})},i.prototype._updateLayer=function(t){this._updatedLayers[t.id]=!0,t.source&&!this._updatedSources[t.source]&&(this._updatedSources[t.source]="reload",this.sourceCaches[t.source].pause()),this._changed=!0;},i.prototype._flattenRenderedFeatures=function(t){for(var e=[],i=this._order.length-1;i>=0;i--)for(var n=this._order[i],o=0,r=t;o<r.length;o+=1){var a=r[o][n];if(a)for(var s=0,l=a;s<l.length;s+=1){var c=l[s];e.push(c);}}return e},i.prototype.queryRenderedFeatures=function(e,i,n){i&&i.filter&&this._validate(t.validateStyle.filter,"queryRenderedFeatures.filter",i.filter);var o={};if(i&&i.layers){if(!Array.isArray(i.layers))return this.fire(new t.ErrorEvent(new Error("parameters.layers must be an Array."))),[];for(var r=0,a=i.layers;r<a.length;r+=1){var s=a[r],l=this._layers[s];if(!l)return this.fire(new t.ErrorEvent(new Error("The layer '"+s+"' does not exist in the map's style and cannot be queried for features."))),[];o[l.source]=!0;}}var c=[];for(var u in this.sourceCaches)i.layers&&!o[u]||c.push(at(this.sourceCaches[u],this._layers,e.worldCoordinate,i,n));return this.placement&&c.push(function(t,e,i,n,o){for(var r={},a=n.queryRenderedSymbols(e),s=[],l=0,c=Object.keys(a).map(Number);l<c.length;l+=1){var u=c[l];s.push(o[u]);}s.sort(st);for(var h=function(){var e=d[p],n=e.featureIndex.lookupSymbolFeatures(a[e.bucketInstanceId],e.bucketIndex,e.sourceLayerIndex,i.filter,i.layers,t);for(var o in n){var s=r[o]=r[o]||[],l=n[o];l.sort(function(t,i){var n=e.featureSortOrder;if(n){var o=n.indexOf(t.featureIndex);return n.indexOf(i.featureIndex)-o}return i.featureIndex-t.featureIndex});for(var c=0,u=l;c<u.length;c+=1){var h=u[c];s.push(h.feature);}}},p=0,d=s;p<d.length;p+=1)h();return r}(this._layers,e.viewport,i,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenRenderedFeatures(c)},i.prototype.querySourceFeatures=function(e,i){i&&i.filter&&this._validate(t.validateStyle.filter,"querySourceFeatures.filter",i.filter);var n=this.sourceCaches[e];return n?function(t,e){for(var i=t.getRenderableIds().map(function(e){return t.getTileByID(e)}),n=[],o={},r=0;r<i.length;r++){var a=i[r],s=a.tileID.canonical.key;o[s]||(o[s]=!0,a.querySourceFeatures(n,e));}return n}(n,i):[]},i.prototype.addSourceType=function(t,e,n){return i.getSourceType(t)?n(new Error('A source type called "'+t+'" already exists.')):(i.setSourceType(t,e),e.workerSourceURL?void this.dispatcher.broadcast("loadWorkerSource",{name:t,url:e.workerSourceURL},n):n(null,null))},i.prototype.getLight=function(){return this.light.getLight()},i.prototype.setLight=function(e){this._checkLoaded();var i=this.light.getLight(),n=!1;for(var o in e)if(!t.default$10(e[o],i[o])){n=!0;break}if(n){var a={now:r.now(),transition:t.extend({duration:300,delay:0},this.stylesheet.transition)};this.light.setLight(e),this.light.updateTransitions(a);}},i.prototype._validate=function(e,i,n,o,r){return(!r||!1!==r.validate)&&Ke(this,e.call(t.validateStyle,t.extend({key:i,style:this.serialize(),value:n,styleSpec:t.default$5},o)))},i.prototype._remove=function(){for(var e in t.evented.off("pluginAvailable",this._rtlTextPluginCallback),this.sourceCaches)this.sourceCaches[e].clearTiles();this.dispatcher.remove();},i.prototype._clearSource=function(t){this.sourceCaches[t].clearTiles();},i.prototype._reloadSource=function(t){this.sourceCaches[t].resume(),this.sourceCaches[t].reload();},i.prototype._updateSources=function(t){for(var e in this.sourceCaches)this.sourceCaches[e].update(t);},i.prototype._generateCollisionBoxes=function(){for(var t in this.sourceCaches)this._reloadSource(t);},i.prototype._updatePlacement=function(t,e,i){for(var n=!1,o=!1,a={},s=0,l=this._order;s<l.length;s+=1){var c=l[s],u=this._layers[c];if("symbol"===u.type){if(!a[u.source]){var h=this.sourceCaches[u.source];a[u.source]=h.getRenderableIds().map(function(t){return h.getTileByID(t)}).sort(function(t,e){return e.tileID.overscaledZ-t.tileID.overscaledZ||(t.tileID.isLessThan(e.tileID)?-1:1)});}var p=this.crossTileSymbolIndex.addLayer(u,a[u.source],t.center.lng);n=n||p;}}this.crossTileSymbolIndex.pruneUnusedLayers(this._order);var d=this._layerOrderChanged;if((d||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(r.now()))&&(this.pauseablePlacement=new $e(t,this._order,d,e,i),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,a),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(this.placement,r.now()),o=!0),n&&this.pauseablePlacement.placement.setStale()),o||n)for(var f=0,m=this._order;f<m.length;f+=1){var _=m[f],g=this._layers[_];"symbol"===g.type&&this.placement.updateLayerOpacities(g,a[g.source]);}return!this.pauseablePlacement.isDone()||this.placement.hasTransitions(r.now())},i.prototype.getImages=function(t,e,i){this.imageManager.getImages(e.icons,i);},i.prototype.getGlyphs=function(t,e,i){this.glyphManager.getGlyphs(e.stacks,i);},i}(t.Evented);Qe.getSourceType=function(t){return ot[t]},Qe.setSourceType=function(t,e){ot[t]=e;},Qe.registerForPluginAvailability=t.registerForPluginAvailability;var ti=t.createLayout([{name:"a_pos",type:"Int16",components:2}]),ei={prelude:{fragmentSource:"#ifdef GL_ES\nprecision mediump float;\n#else\n\n#if !defined(lowp)\n#define lowp\n#endif\n\n#if !defined(mediump)\n#define mediump\n#endif\n\n#if !defined(highp)\n#define highp\n#endif\n\n#endif\n",vertexSource:"#ifdef GL_ES\nprecision highp float;\n#else\n\n#if !defined(lowp)\n#define lowp\n#endif\n\n#if !defined(mediump)\n#define mediump\n#endif\n\n#if !defined(highp)\n#define highp\n#endif\n\n#endif\n\n// Unpack a pair of values that have been packed into a single float.\n// The packed values are assumed to be 8-bit unsigned integers, and are\n// packed like so:\n// packedValue = floor(input[0]) * 256 + input[1],\nvec2 unpack_float(const float packedValue) {\n    int packedIntValue = int(packedValue);\n    int v0 = packedIntValue / 256;\n    return vec2(v0, packedIntValue - v0 * 256);\n}\n\nvec2 unpack_opacity(const float packedOpacity) {\n    int intOpacity = int(packedOpacity) / 2;\n    return vec2(float(intOpacity) / 127.0, mod(packedOpacity, 2.0));\n}\n\n// To minimize the number of attributes needed, we encode a 4-component\n// color into a pair of floats (i.e. a vec2) as follows:\n// [ floor(color.r * 255) * 256 + color.g * 255,\n//   floor(color.b * 255) * 256 + color.g * 255 ]\nvec4 decode_color(const vec2 encodedColor) {\n    return vec4(\n        unpack_float(encodedColor[0]) / 255.0,\n        unpack_float(encodedColor[1]) / 255.0\n    );\n}\n\n// Unpack a pair of paint values and interpolate between them.\nfloat unpack_mix_vec2(const vec2 packedValue, const float t) {\n    return mix(packedValue[0], packedValue[1], t);\n}\n\n// Unpack a pair of paint values and interpolate between them.\nvec4 unpack_mix_vec4(const vec4 packedColors, const float t) {\n    vec4 minColor = decode_color(vec2(packedColors[0], packedColors[1]));\n    vec4 maxColor = decode_color(vec2(packedColors[2], packedColors[3]));\n    return mix(minColor, maxColor, t);\n}\n\n// The offset depends on how many pixels are between the world origin and the edge of the tile:\n// vec2 offset = mod(pixel_coord, size)\n//\n// At high zoom levels there are a ton of pixels between the world origin and the edge of the tile.\n// The glsl spec only guarantees 16 bits of precision for highp floats. We need more than that.\n//\n// The pixel_coord is passed in as two 16 bit values:\n// pixel_coord_upper = floor(pixel_coord / 2^16)\n// pixel_coord_lower = mod(pixel_coord, 2^16)\n//\n// The offset is calculated in a series of steps that should preserve this precision:\nvec2 get_pattern_pos(const vec2 pixel_coord_upper, const vec2 pixel_coord_lower,\n    const vec2 pattern_size, const float tile_units_to_pixels, const vec2 pos) {\n\n    vec2 offset = mod(mod(mod(pixel_coord_upper, pattern_size) * 256.0, pattern_size) * 256.0 + pixel_coord_lower, pattern_size);\n    return (tile_units_to_pixels * pos + offset) / pattern_size;\n}\n"},background:{fragmentSource:"uniform vec4 u_color;\nuniform float u_opacity;\n\nvoid main() {\n    gl_FragColor = u_color * u_opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n"},backgroundPattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\nuniform float u_opacity;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\nvoid main() {\n    vec2 imagecoord = mod(v_pos_a, 1.0);\n    vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n    vec4 color1 = texture2D(u_image, pos);\n\n    vec2 imagecoord_b = mod(v_pos_b, 1.0);\n    vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n    vec4 color2 = texture2D(u_image, pos2);\n\n    gl_FragColor = mix(color1, color2, u_mix) * u_opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n\n    v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, a_pos);\n    v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, a_pos);\n}\n"},circle:{fragmentSource:"#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\n\nvarying vec3 v_data;\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize mediump float radius\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize highp vec4 stroke_color\n    #pragma mapbox: initialize mediump float stroke_width\n    #pragma mapbox: initialize lowp float stroke_opacity\n\n    vec2 extrude = v_data.xy;\n    float extrude_length = length(extrude);\n\n    lowp float antialiasblur = v_data.z;\n    float antialiased_blur = -max(blur, antialiasblur);\n\n    float opacity_t = smoothstep(0.0, antialiased_blur, extrude_length - 1.0);\n\n    float color_t = stroke_width < 0.01 ? 0.0 : smoothstep(\n        antialiased_blur,\n        0.0,\n        extrude_length - radius / (radius + stroke_width)\n    );\n\n    gl_FragColor = opacity_t * mix(color * opacity, stroke_color * stroke_opacity, color_t);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform bool u_scale_with_map;\nuniform bool u_pitch_with_map;\nuniform vec2 u_extrude_scale;\nuniform highp float u_camera_to_center_distance;\n\nattribute vec2 a_pos;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\n\nvarying vec3 v_data;\n\nvoid main(void) {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize mediump float radius\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize highp vec4 stroke_color\n    #pragma mapbox: initialize mediump float stroke_width\n    #pragma mapbox: initialize lowp float stroke_opacity\n\n    // unencode the extrusion vector that we snuck into the a_pos vector\n    vec2 extrude = vec2(mod(a_pos, 2.0) * 2.0 - 1.0);\n\n    // multiply a_pos by 0.5, since we had it * 2 in order to sneak\n    // in extrusion data\n    vec2 circle_center = floor(a_pos * 0.5);\n    if (u_pitch_with_map) {\n        vec2 corner_position = circle_center;\n        if (u_scale_with_map) {\n            corner_position += extrude * (radius + stroke_width) * u_extrude_scale;\n        } else {\n            // Pitching the circle with the map effectively scales it with the map\n            // To counteract the effect for pitch-scale: viewport, we rescale the\n            // whole circle based on the pitch scaling effect at its central point\n            vec4 projected_center = u_matrix * vec4(circle_center, 0, 1);\n            corner_position += extrude * (radius + stroke_width) * u_extrude_scale * (projected_center.w / u_camera_to_center_distance);\n        }\n\n        gl_Position = u_matrix * vec4(corner_position, 0, 1);\n    } else {\n        gl_Position = u_matrix * vec4(circle_center, 0, 1);\n\n        if (u_scale_with_map) {\n            gl_Position.xy += extrude * (radius + stroke_width) * u_extrude_scale * u_camera_to_center_distance;\n        } else {\n            gl_Position.xy += extrude * (radius + stroke_width) * u_extrude_scale * gl_Position.w;\n        }\n    }\n\n    // This is a minimum blur distance that serves as a faux-antialiasing for\n    // the circle. since blur is a ratio of the circle's size and the intent is\n    // to keep the blur at roughly 1px, the two are inversely related.\n    lowp float antialiasblur = 1.0 / DEVICE_PIXEL_RATIO / (radius + stroke_width);\n\n    v_data = vec3(extrude.x, extrude.y, antialiasblur);\n}\n"},clippingMask:{fragmentSource:"void main() {\n    gl_FragColor = vec4(1.0);\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n"},heatmap:{fragmentSource:"#pragma mapbox: define highp float weight\n\nuniform highp float u_intensity;\nvarying vec2 v_extrude;\n\n// Gaussian kernel coefficient: 1 / sqrt(2 * PI)\n#define GAUSS_COEF 0.3989422804014327\n\nvoid main() {\n    #pragma mapbox: initialize highp float weight\n\n    // Kernel density estimation with a Gaussian kernel of size 5x5\n    float d = -0.5 * 3.0 * 3.0 * dot(v_extrude, v_extrude);\n    float val = weight * u_intensity * GAUSS_COEF * exp(d);\n\n    gl_FragColor = vec4(val, 1.0, 1.0, 1.0);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\n\nuniform mat4 u_matrix;\nuniform float u_extrude_scale;\nuniform float u_opacity;\nuniform float u_intensity;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_extrude;\n\n// Effective \"0\" in the kernel density texture to adjust the kernel size to;\n// this empirically chosen number minimizes artifacts on overlapping kernels\n// for typical heatmap cases (assuming clustered source)\nconst highp float ZERO = 1.0 / 255.0 / 16.0;\n\n// Gaussian kernel coefficient: 1 / sqrt(2 * PI)\n#define GAUSS_COEF 0.3989422804014327\n\nvoid main(void) {\n    #pragma mapbox: initialize highp float weight\n    #pragma mapbox: initialize mediump float radius\n\n    // unencode the extrusion vector that we snuck into the a_pos vector\n    vec2 unscaled_extrude = vec2(mod(a_pos, 2.0) * 2.0 - 1.0);\n\n    // This 'extrude' comes in ranging from [-1, -1], to [1, 1].  We'll use\n    // it to produce the vertices of a square mesh framing the point feature\n    // we're adding to the kernel density texture.  We'll also pass it as\n    // a varying, so that the fragment shader can determine the distance of\n    // each fragment from the point feature.\n    // Before we do so, we need to scale it up sufficiently so that the\n    // kernel falls effectively to zero at the edge of the mesh.\n    // That is, we want to know S such that\n    // weight * u_intensity * GAUSS_COEF * exp(-0.5 * 3.0^2 * S^2) == ZERO\n    // Which solves to:\n    // S = sqrt(-2.0 * log(ZERO / (weight * u_intensity * GAUSS_COEF))) / 3.0\n    float S = sqrt(-2.0 * log(ZERO / weight / u_intensity / GAUSS_COEF)) / 3.0;\n\n    // Pass the varying in units of radius\n    v_extrude = S * unscaled_extrude;\n\n    // Scale by radius and the zoom-based scale factor to produce actual\n    // mesh position\n    vec2 extrude = v_extrude * radius * u_extrude_scale;\n\n    // multiply a_pos by 0.5, since we had it * 2 in order to sneak\n    // in extrusion data\n    vec4 pos = vec4(floor(a_pos * 0.5) + extrude, 0, 1);\n\n    gl_Position = u_matrix * pos;\n}\n"},heatmapTexture:{fragmentSource:"uniform sampler2D u_image;\nuniform sampler2D u_color_ramp;\nuniform float u_opacity;\nvarying vec2 v_pos;\n\nvoid main() {\n    float t = texture2D(u_image, v_pos).r;\n    vec4 color = texture2D(u_color_ramp, vec2(t, 0.5));\n    gl_FragColor = color * u_opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(0.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_world;\nattribute vec2 a_pos;\nvarying vec2 v_pos;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos * u_world, 0, 1);\n\n    v_pos.x = a_pos.x;\n    v_pos.y = 1.0 - a_pos.y;\n}\n"},collisionBox:{fragmentSource:"\nvarying float v_placed;\nvarying float v_notUsed;\n\nvoid main() {\n\n    float alpha = 0.5;\n\n    // Red = collision, hide label\n    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0) * alpha;\n\n    // Blue = no collision, label is showing\n    if (v_placed > 0.5) {\n        gl_FragColor = vec4(0.0, 0.0, 1.0, 0.5) * alpha;\n    }\n\n    if (v_notUsed > 0.5) {\n        // This box not used, fade it out\n        gl_FragColor *= .1;\n    }\n}",vertexSource:"attribute vec2 a_pos;\nattribute vec2 a_anchor_pos;\nattribute vec2 a_extrude;\nattribute vec2 a_placed;\n\nuniform mat4 u_matrix;\nuniform vec2 u_extrude_scale;\nuniform float u_camera_to_center_distance;\n\nvarying float v_placed;\nvarying float v_notUsed;\n\nvoid main() {\n    vec4 projectedPoint = u_matrix * vec4(a_anchor_pos, 0, 1);\n    highp float camera_to_anchor_distance = projectedPoint.w;\n    highp float collision_perspective_ratio = clamp(\n        0.5 + 0.5 * (u_camera_to_center_distance / camera_to_anchor_distance),\n        0.0, // Prevents oversized near-field boxes in pitched/overzoomed tiles\n        4.0);\n\n    gl_Position = u_matrix * vec4(a_pos, 0.0, 1.0);\n    gl_Position.xy += a_extrude * u_extrude_scale * gl_Position.w * collision_perspective_ratio;\n\n    v_placed = a_placed.x;\n    v_notUsed = a_placed.y;\n}\n"},collisionCircle:{fragmentSource:"uniform float u_overscale_factor;\n\nvarying float v_placed;\nvarying float v_notUsed;\nvarying float v_radius;\nvarying vec2 v_extrude;\nvarying vec2 v_extrude_scale;\n\nvoid main() {\n    float alpha = 0.5;\n\n    // Red = collision, hide label\n    vec4 color = vec4(1.0, 0.0, 0.0, 1.0) * alpha;\n\n    // Blue = no collision, label is showing\n    if (v_placed > 0.5) {\n        color = vec4(0.0, 0.0, 1.0, 0.5) * alpha;\n    }\n\n    if (v_notUsed > 0.5) {\n        // This box not used, fade it out\n        color *= .2;\n    }\n\n    float extrude_scale_length = length(v_extrude_scale);\n    float extrude_length = length(v_extrude) * extrude_scale_length;\n    float stroke_width = 15.0 * extrude_scale_length / u_overscale_factor;\n    float radius = v_radius * extrude_scale_length;\n\n    float distance_to_edge = abs(extrude_length - radius);\n    float opacity_t = smoothstep(-stroke_width, 0.0, -distance_to_edge);\n\n    gl_FragColor = opacity_t * color;\n}\n",vertexSource:"attribute vec2 a_pos;\nattribute vec2 a_anchor_pos;\nattribute vec2 a_extrude;\nattribute vec2 a_placed;\n\nuniform mat4 u_matrix;\nuniform vec2 u_extrude_scale;\nuniform float u_camera_to_center_distance;\n\nvarying float v_placed;\nvarying float v_notUsed;\nvarying float v_radius;\n\nvarying vec2 v_extrude;\nvarying vec2 v_extrude_scale;\n\nvoid main() {\n    vec4 projectedPoint = u_matrix * vec4(a_anchor_pos, 0, 1);\n    highp float camera_to_anchor_distance = projectedPoint.w;\n    highp float collision_perspective_ratio = clamp(\n        0.5 + 0.5 * (u_camera_to_center_distance / camera_to_anchor_distance),\n        0.0, // Prevents oversized near-field circles in pitched/overzoomed tiles\n        4.0);\n\n    gl_Position = u_matrix * vec4(a_pos, 0.0, 1.0);\n\n    highp float padding_factor = 1.2; // Pad the vertices slightly to make room for anti-alias blur\n    gl_Position.xy += a_extrude * u_extrude_scale * padding_factor * gl_Position.w * collision_perspective_ratio;\n\n    v_placed = a_placed.x;\n    v_notUsed = a_placed.y;\n    v_radius = abs(a_extrude.y); // We don't pitch the circles, so both units of the extrusion vector are equal in magnitude to the radius\n\n    v_extrude = a_extrude * padding_factor;\n    v_extrude_scale = u_extrude_scale * u_camera_to_center_distance * collision_perspective_ratio;\n}\n"},debug:{fragmentSource:"uniform highp vec4 u_color;\n\nvoid main() {\n    gl_FragColor = u_color;\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n"},fill:{fragmentSource:"#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float opacity\n\n    gl_FragColor = color * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float opacity\n\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n"},fillOutline:{fragmentSource:"#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_pos;\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 outline_color\n    #pragma mapbox: initialize lowp float opacity\n\n    float dist = length(v_pos - gl_FragCoord.xy);\n    float alpha = 1.0 - smoothstep(0.0, 1.0, dist);\n    gl_FragColor = outline_color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\nuniform vec2 u_world;\n\nvarying vec2 v_pos;\n\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 outline_color\n    #pragma mapbox: initialize lowp float opacity\n\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n    v_pos = (gl_Position.xy / gl_Position.w + 1.0) / 2.0 * u_world;\n}\n"},fillOutlinePattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec2 v_pos;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    vec2 imagecoord = mod(v_pos_a, 1.0);\n    vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n    vec4 color1 = texture2D(u_image, pos);\n\n    vec2 imagecoord_b = mod(v_pos_b, 1.0);\n    vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n    vec4 color2 = texture2D(u_image, pos2);\n\n    // find distance to outline for alpha interpolation\n\n    float dist = length(v_pos - gl_FragCoord.xy);\n    float alpha = 1.0 - smoothstep(0.0, 1.0, dist);\n\n\n    gl_FragColor = mix(color1, color2, u_mix) * alpha * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_world;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec2 v_pos;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n\n    v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, a_pos);\n    v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, a_pos);\n\n    v_pos = (gl_Position.xy / gl_Position.w + 1.0) / 2.0 * u_world;\n}\n"},fillPattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    vec2 imagecoord = mod(v_pos_a, 1.0);\n    vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n    vec4 color1 = texture2D(u_image, pos);\n\n    vec2 imagecoord_b = mod(v_pos_b, 1.0);\n    vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n    vec4 color2 = texture2D(u_image, pos2);\n\n    gl_FragColor = mix(color1, color2, u_mix) * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n\n    v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, a_pos);\n    v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, a_pos);\n}\n"},fillExtrusion:{fragmentSource:"varying vec4 v_color;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define highp vec4 color\n\nvoid main() {\n    #pragma mapbox: initialize lowp float base\n    #pragma mapbox: initialize lowp float height\n    #pragma mapbox: initialize highp vec4 color\n\n    gl_FragColor = v_color;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec3 u_lightcolor;\nuniform lowp vec3 u_lightpos;\nuniform lowp float u_lightintensity;\n\nattribute vec2 a_pos;\nattribute vec4 a_normal_ed;\n\nvarying vec4 v_color;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\n#pragma mapbox: define highp vec4 color\n\nvoid main() {\n    #pragma mapbox: initialize lowp float base\n    #pragma mapbox: initialize lowp float height\n    #pragma mapbox: initialize highp vec4 color\n\n    vec3 normal = a_normal_ed.xyz;\n\n    base = max(0.0, base);\n    height = max(0.0, height);\n\n    float t = mod(normal.x, 2.0);\n\n    gl_Position = u_matrix * vec4(a_pos, t > 0.0 ? height : base, 1);\n\n    // Relative luminance (how dark/bright is the surface color?)\n    float colorvalue = color.r * 0.2126 + color.g * 0.7152 + color.b * 0.0722;\n\n    v_color = vec4(0.0, 0.0, 0.0, 1.0);\n\n    // Add slight ambient lighting so no extrusions are totally black\n    vec4 ambientlight = vec4(0.03, 0.03, 0.03, 1.0);\n    color += ambientlight;\n\n    // Calculate cos(theta), where theta is the angle between surface normal and diffuse light ray\n    float directional = clamp(dot(normal / 16384.0, u_lightpos), 0.0, 1.0);\n\n    // Adjust directional so that\n    // the range of values for highlight/shading is narrower\n    // with lower light intensity\n    // and with lighter/brighter surface colors\n    directional = mix((1.0 - u_lightintensity), max((1.0 - colorvalue + u_lightintensity), 1.0), directional);\n\n    // Add gradient along z axis of side surfaces\n    if (normal.y != 0.0) {\n        directional *= clamp((t + base) * pow(height / 150.0, 0.5), mix(0.7, 0.98, 1.0 - u_lightintensity), 1.0);\n    }\n\n    // Assign final color based on surface + ambient light color, diffuse light directional, and light color\n    // with lower bounds adjusted to hue of light\n    // so that shading is tinted with the complementary (opposite) color to the light color\n    v_color.r += clamp(color.r * directional * u_lightcolor.r, mix(0.0, 0.3, 1.0 - u_lightcolor.r), 1.0);\n    v_color.g += clamp(color.g * directional * u_lightcolor.g, mix(0.0, 0.3, 1.0 - u_lightcolor.g), 1.0);\n    v_color.b += clamp(color.b * directional * u_lightcolor.b, mix(0.0, 0.3, 1.0 - u_lightcolor.b), 1.0);\n}\n"},fillExtrusionPattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec4 v_lighting;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\nvoid main() {\n    #pragma mapbox: initialize lowp float base\n    #pragma mapbox: initialize lowp float height\n\n    vec2 imagecoord = mod(v_pos_a, 1.0);\n    vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n    vec4 color1 = texture2D(u_image, pos);\n\n    vec2 imagecoord_b = mod(v_pos_b, 1.0);\n    vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n    vec4 color2 = texture2D(u_image, pos2);\n\n    vec4 mixedColor = mix(color1, color2, u_mix);\n\n    gl_FragColor = mixedColor * v_lighting;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\nuniform float u_height_factor;\n\nuniform vec3 u_lightcolor;\nuniform lowp vec3 u_lightpos;\nuniform lowp float u_lightintensity;\n\nattribute vec2 a_pos;\nattribute vec4 a_normal_ed;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec4 v_lighting;\nvarying float v_directional;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\nvoid main() {\n    #pragma mapbox: initialize lowp float base\n    #pragma mapbox: initialize lowp float height\n\n    vec3 normal = a_normal_ed.xyz;\n    float edgedistance = a_normal_ed.w;\n\n    base = max(0.0, base);\n    height = max(0.0, height);\n\n    float t = mod(normal.x, 2.0);\n    float z = t > 0.0 ? height : base;\n\n    gl_Position = u_matrix * vec4(a_pos, z, 1);\n\n    vec2 pos = normal.x == 1.0 && normal.y == 0.0 && normal.z == 16384.0\n        ? a_pos // extrusion top\n        : vec2(edgedistance, z * u_height_factor); // extrusion side\n\n    v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, pos);\n    v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, pos);\n\n    v_lighting = vec4(0.0, 0.0, 0.0, 1.0);\n    float directional = clamp(dot(normal / 16383.0, u_lightpos), 0.0, 1.0);\n    directional = mix((1.0 - u_lightintensity), max((0.5 + u_lightintensity), 1.0), directional);\n\n    if (normal.y != 0.0) {\n        directional *= clamp((t + base) * pow(height / 150.0, 0.5), mix(0.7, 0.98, 1.0 - u_lightintensity), 1.0);\n    }\n\n    v_lighting.rgb += clamp(directional * u_lightcolor, mix(vec3(0.0), vec3(0.3), 1.0 - u_lightcolor), vec3(1.0));\n}\n"},extrusionTexture:{fragmentSource:"uniform sampler2D u_image;\nuniform float u_opacity;\nvarying vec2 v_pos;\n\nvoid main() {\n    gl_FragColor = texture2D(u_image, v_pos) * u_opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(0.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_world;\nattribute vec2 a_pos;\nvarying vec2 v_pos;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos * u_world, 0, 1);\n\n    v_pos.x = a_pos.x;\n    v_pos.y = 1.0 - a_pos.y;\n}\n"},hillshadePrepare:{fragmentSource:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D u_image;\nvarying vec2 v_pos;\nuniform vec2 u_dimension;\nuniform float u_zoom;\nuniform float u_maxzoom;\n\nfloat getElevation(vec2 coord, float bias) {\n    // Convert encoded elevation value to meters\n    vec4 data = texture2D(u_image, coord) * 255.0;\n    return (data.r + data.g * 256.0 + data.b * 256.0 * 256.0) / 4.0;\n}\n\nvoid main() {\n    vec2 epsilon = 1.0 / u_dimension;\n\n    // queried pixels:\n    // +-----------+\n    // |   |   |   |\n    // | a | b | c |\n    // |   |   |   |\n    // +-----------+\n    // |   |   |   |\n    // | d | e | f |\n    // |   |   |   |\n    // +-----------+\n    // |   |   |   |\n    // | g | h | i |\n    // |   |   |   |\n    // +-----------+\n\n    float a = getElevation(v_pos + vec2(-epsilon.x, -epsilon.y), 0.0);\n    float b = getElevation(v_pos + vec2(0, -epsilon.y), 0.0);\n    float c = getElevation(v_pos + vec2(epsilon.x, -epsilon.y), 0.0);\n    float d = getElevation(v_pos + vec2(-epsilon.x, 0), 0.0);\n    float e = getElevation(v_pos, 0.0);\n    float f = getElevation(v_pos + vec2(epsilon.x, 0), 0.0);\n    float g = getElevation(v_pos + vec2(-epsilon.x, epsilon.y), 0.0);\n    float h = getElevation(v_pos + vec2(0, epsilon.y), 0.0);\n    float i = getElevation(v_pos + vec2(epsilon.x, epsilon.y), 0.0);\n\n    // here we divide the x and y slopes by 8 * pixel size\n    // where pixel size (aka meters/pixel) is:\n    // circumference of the world / (pixels per tile * number of tiles)\n    // which is equivalent to: 8 * 40075016.6855785 / (512 * pow(2, u_zoom))\n    // which can be reduced to: pow(2, 19.25619978527 - u_zoom)\n    // we want to vertically exaggerate the hillshading though, because otherwise\n    // it is barely noticeable at low zooms. to do this, we multiply this by some\n    // scale factor pow(2, (u_zoom - u_maxzoom) * a) where a is an arbitrary value\n    // Here we use a=0.3 which works out to the expression below. see \n    // nickidlugash's awesome breakdown for more info\n    // https://github.com/mapbox/mapbox-gl-js/pull/5286#discussion_r148419556\n    float exaggeration = u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;\n\n    vec2 deriv = vec2(\n        (c + f + f + i) - (a + d + d + g),\n        (g + h + h + i) - (a + b + b + c)\n    ) /  pow(2.0, (u_zoom - u_maxzoom) * exaggeration + 19.2562 - u_zoom);\n\n    gl_FragColor = clamp(vec4(\n        deriv.x / 2.0 + 0.5,\n        deriv.y / 2.0 + 0.5,\n        1.0,\n        1.0), 0.0, 1.0);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n    v_pos = (a_texture_pos / 8192.0) / 2.0 + 0.25;\n}\n"},hillshade:{fragmentSource:"uniform sampler2D u_image;\nvarying vec2 v_pos;\n\nuniform vec2 u_latrange;\nuniform vec2 u_light;\nuniform vec4 u_shadow;\nuniform vec4 u_highlight;\nuniform vec4 u_accent;\n\n#define PI 3.141592653589793\n\nvoid main() {\n    vec4 pixel = texture2D(u_image, v_pos);\n\n    vec2 deriv = ((pixel.rg * 2.0) - 1.0);\n\n    // We divide the slope by a scale factor based on the cosin of the pixel's approximate latitude\n    // to account for mercator projection distortion. see #4807 for details\n    float scaleFactor = cos(radians((u_latrange[0] - u_latrange[1]) * (1.0 - v_pos.y) + u_latrange[1]));\n    // We also multiply the slope by an arbitrary z-factor of 1.25\n    float slope = atan(1.25 * length(deriv) / scaleFactor);\n    float aspect = deriv.x != 0.0 ? atan(deriv.y, -deriv.x) : PI / 2.0 * (deriv.y > 0.0 ? 1.0 : -1.0);\n\n    float intensity = u_light.x;\n    // We add PI to make this property match the global light object, which adds PI/2 to the light's azimuthal\n    // position property to account for 0deg corresponding to north/the top of the viewport in the style spec\n    // and the original shader was written to accept (-illuminationDirection - 90) as the azimuthal.\n    float azimuth = u_light.y + PI;\n\n    // We scale the slope exponentially based on intensity, using a calculation similar to\n    // the exponential interpolation function in the style spec:\n    // https://github.com/mapbox/mapbox-gl-js/blob/master/src/style-spec/expression/definitions/interpolate.js#L217-L228\n    // so that higher intensity values create more opaque hillshading.\n    float base = 1.875 - intensity * 1.75;\n    float maxValue = 0.5 * PI;\n    float scaledSlope = intensity != 0.5 ? ((pow(base, slope) - 1.0) / (pow(base, maxValue) - 1.0)) * maxValue : slope;\n\n    // The accent color is calculated with the cosine of the slope while the shade color is calculated with the sine\n    // so that the accent color's rate of change eases in while the shade color's eases out.\n    float accent = cos(scaledSlope);\n    // We multiply both the accent and shade color by a clamped intensity value\n    // so that intensities >= 0.5 do not additionally affect the color values\n    // while intensity values < 0.5 make the overall color more transparent.\n    vec4 accent_color = (1.0 - accent) * u_accent * clamp(intensity * 2.0, 0.0, 1.0);\n    float shade = abs(mod((aspect + azimuth) / PI + 0.5, 2.0) - 1.0);\n    vec4 shade_color = mix(u_shadow, u_highlight, shade) * sin(scaledSlope) * clamp(intensity * 2.0, 0.0, 1.0);\n    gl_FragColor = accent_color * (1.0 - shade_color.a) + shade_color;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n    v_pos = a_texture_pos / 8192.0;\n}\n"},line:{fragmentSource:"#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_width2;\nvarying vec2 v_normal;\nvarying float v_gamma_scale;\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n\n    // Calculate the distance of the pixel from the line in pixels.\n    float dist = length(v_normal) * v_width2.s;\n\n    // Calculate the antialiasing fade factor. This is either when fading in\n    // the line in case of an offset line (v_width2.t) or when fading out\n    // (v_width2.s)\n    float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n    float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n    gl_FragColor = color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\n// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_gamma_scale;\nvarying highp float v_linesofar;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize mediump float gapwidth\n    #pragma mapbox: initialize lowp float offset\n    #pragma mapbox: initialize mediump float width\n\n    vec2 a_extrude = a_data.xy - 128.0;\n    float a_direction = mod(a_data.z, 4.0) - 1.0;\n\n    v_linesofar = (floor(a_data.z / 4.0) + a_data.w * 64.0) * 2.0;\n\n    vec2 pos = a_pos_normal.xy;\n\n    // x is 1 if it's a round cap, 0 otherwise\n    // y is 1 if the normal points up, and -1 if it points down\n    mediump vec2 normal = a_pos_normal.zw;\n    v_normal = normal;\n\n    // these transformations used to be applied in the JS and native code bases.\n    // moved them into the shader for clarity and simplicity.\n    gapwidth = gapwidth / 2.0;\n    float halfwidth = width / 2.0;\n    offset = -1.0 * offset;\n\n    float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n    float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n    // Scale the extrusion vector down to a normal and then up by the line width\n    // of this vertex.\n    mediump vec2 dist = outset * a_extrude * scale;\n\n    // Calculate the offset when drawing a line that is to the side of the actual line.\n    // We do this by creating a vector that points towards the extrude, but rotate\n    // it when we're drawing round end points (a_direction = -1 or 1) since their\n    // extrude vector points in another direction.\n    mediump float u = 0.5 * a_direction;\n    mediump float t = 1.0 - abs(u);\n    mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n    vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n    gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n    // calculate how much the perspective view squishes or stretches the extrude\n    float extrude_length_without_perspective = length(dist);\n    float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n    v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n    v_width2 = vec2(outset, inset);\n}\n"},lineGradient:{fragmentSource:"\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n\nuniform sampler2D u_image;\n\nvarying vec2 v_width2;\nvarying vec2 v_normal;\nvarying float v_gamma_scale;\nvarying highp float v_lineprogress;\n\nvoid main() {\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n\n    // Calculate the distance of the pixel from the line in pixels.\n    float dist = length(v_normal) * v_width2.s;\n\n    // Calculate the antialiasing fade factor. This is either when fading in\n    // the line in case of an offset line (v_width2.t) or when fading out\n    // (v_width2.s)\n    float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n    float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n    // For gradient lines, v_lineprogress is the ratio along the entire line,\n    // scaled to [0, 2^15), and the gradient ramp is stored in a texture.\n    vec4 color = texture2D(u_image, vec2(v_lineprogress, 0.5));\n\n    gl_FragColor = color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"\n// the attribute conveying progress along a line is scaled to [0, 2^15)\n#define MAX_LINE_DISTANCE 32767.0\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\n// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_gamma_scale;\nvarying highp float v_lineprogress;\n\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n\nvoid main() {\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize mediump float gapwidth\n    #pragma mapbox: initialize lowp float offset\n    #pragma mapbox: initialize mediump float width\n\n    vec2 a_extrude = a_data.xy - 128.0;\n    float a_direction = mod(a_data.z, 4.0) - 1.0;\n\n    v_lineprogress = (floor(a_data.z / 4.0) + a_data.w * 64.0) * 2.0 / MAX_LINE_DISTANCE;\n\n    vec2 pos = a_pos_normal.xy;\n\n    // x is 1 if it's a round cap, 0 otherwise\n    // y is 1 if the normal points up, and -1 if it points down\n    mediump vec2 normal = a_pos_normal.zw;\n    v_normal = normal;\n\n    // these transformations used to be applied in the JS and native code bases.\n    // moved them into the shader for clarity and simplicity.\n    gapwidth = gapwidth / 2.0;\n    float halfwidth = width / 2.0;\n    offset = -1.0 * offset;\n\n    float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n    float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n    // Scale the extrusion vector down to a normal and then up by the line width\n    // of this vertex.\n    mediump vec2 dist = outset * a_extrude * scale;\n\n    // Calculate the offset when drawing a line that is to the side of the actual line.\n    // We do this by creating a vector that points towards the extrude, but rotate\n    // it when we're drawing round end points (a_direction = -1 or 1) since their\n    // extrude vector points in another direction.\n    mediump float u = 0.5 * a_direction;\n    mediump float t = 1.0 - abs(u);\n    mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n    vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n    gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n    // calculate how much the perspective view squishes or stretches the extrude\n    float extrude_length_without_perspective = length(dist);\n    float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n    v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n    v_width2 = vec2(outset, inset);\n}\n"},linePattern:{fragmentSource:"uniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_fade;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_linesofar;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n\n    // Calculate the distance of the pixel from the line in pixels.\n    float dist = length(v_normal) * v_width2.s;\n\n    // Calculate the antialiasing fade factor. This is either when fading in\n    // the line in case of an offset line (v_width2.t) or when fading out\n    // (v_width2.s)\n    float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n    float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n    float x_a = mod(v_linesofar / u_pattern_size_a.x, 1.0);\n    float x_b = mod(v_linesofar / u_pattern_size_b.x, 1.0);\n\n    // v_normal.y is 0 at the midpoint of the line, -1 at the lower edge, 1 at the upper edge\n    // we clamp the line width outset to be between 0 and half the pattern height plus padding (2.0)\n    // to ensure we don't sample outside the designated symbol on the sprite sheet.\n    // 0.5 is added to shift the component to be bounded between 0 and 1 for interpolation of\n    // the texture coordinate\n    float y_a = 0.5 + (v_normal.y * clamp(v_width2.s, 0.0, (u_pattern_size_a.y + 2.0) / 2.0) / u_pattern_size_a.y);\n    float y_b = 0.5 + (v_normal.y * clamp(v_width2.s, 0.0, (u_pattern_size_b.y + 2.0) / 2.0) / u_pattern_size_b.y);\n    vec2 pos_a = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, vec2(x_a, y_a));\n    vec2 pos_b = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, vec2(x_b, y_b));\n\n    vec4 color = mix(texture2D(u_image, pos_a), texture2D(u_image, pos_b), u_fade);\n\n    gl_FragColor = color * alpha * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\n// We scale the distance before adding it to the buffers so that we can store\n// long distances for long segments. Use this value to unscale the distance.\n#define LINE_DISTANCE_SCALE 2.0\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_linesofar;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n\nvoid main() {\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize lowp float offset\n    #pragma mapbox: initialize mediump float gapwidth\n    #pragma mapbox: initialize mediump float width\n\n    vec2 a_extrude = a_data.xy - 128.0;\n    float a_direction = mod(a_data.z, 4.0) - 1.0;\n    float a_linesofar = (floor(a_data.z / 4.0) + a_data.w * 64.0) * LINE_DISTANCE_SCALE;\n\n    vec2 pos = a_pos_normal.xy;\n\n    // x is 1 if it's a round cap, 0 otherwise\n    // y is 1 if the normal points up, and -1 if it points down\n    mediump vec2 normal = a_pos_normal.zw;\n    v_normal = normal;\n\n    // these transformations used to be applied in the JS and native code bases.\n    // moved them into the shader for clarity and simplicity.\n    gapwidth = gapwidth / 2.0;\n    float halfwidth = width / 2.0;\n    offset = -1.0 * offset;\n\n    float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n    float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n    // Scale the extrusion vector down to a normal and then up by the line width\n    // of this vertex.\n    mediump vec2 dist = outset * a_extrude * scale;\n\n    // Calculate the offset when drawing a line that is to the side of the actual line.\n    // We do this by creating a vector that points towards the extrude, but rotate\n    // it when we're drawing round end points (a_direction = -1 or 1) since their\n    // extrude vector points in another direction.\n    mediump float u = 0.5 * a_direction;\n    mediump float t = 1.0 - abs(u);\n    mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n    vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n    gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n    // calculate how much the perspective view squishes or stretches the extrude\n    float extrude_length_without_perspective = length(dist);\n    float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n    v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n    v_linesofar = a_linesofar;\n    v_width2 = vec2(outset, inset);\n}\n"},lineSDF:{fragmentSource:"\nuniform sampler2D u_image;\nuniform float u_sdfgamma;\nuniform float u_mix;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying vec2 v_tex_a;\nvarying vec2 v_tex_b;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize mediump float width\n    #pragma mapbox: initialize lowp float floorwidth\n\n    // Calculate the distance of the pixel from the line in pixels.\n    float dist = length(v_normal) * v_width2.s;\n\n    // Calculate the antialiasing fade factor. This is either when fading in\n    // the line in case of an offset line (v_width2.t) or when fading out\n    // (v_width2.s)\n    float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n    float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n    float sdfdist_a = texture2D(u_image, v_tex_a).a;\n    float sdfdist_b = texture2D(u_image, v_tex_b).a;\n    float sdfdist = mix(sdfdist_a, sdfdist_b, u_mix);\n    alpha *= smoothstep(0.5 - u_sdfgamma / floorwidth, 0.5 + u_sdfgamma / floorwidth, sdfdist);\n\n    gl_FragColor = color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\n// We scale the distance before adding it to the buffers so that we can store\n// long distances for long segments. Use this value to unscale the distance.\n#define LINE_DISTANCE_SCALE 2.0\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_patternscale_a;\nuniform float u_tex_y_a;\nuniform vec2 u_patternscale_b;\nuniform float u_tex_y_b;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying vec2 v_tex_a;\nvarying vec2 v_tex_b;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize mediump float gapwidth\n    #pragma mapbox: initialize lowp float offset\n    #pragma mapbox: initialize mediump float width\n    #pragma mapbox: initialize lowp float floorwidth\n\n    vec2 a_extrude = a_data.xy - 128.0;\n    float a_direction = mod(a_data.z, 4.0) - 1.0;\n    float a_linesofar = (floor(a_data.z / 4.0) + a_data.w * 64.0) * LINE_DISTANCE_SCALE;\n\n    vec2 pos = a_pos_normal.xy;\n\n    // x is 1 if it's a round cap, 0 otherwise\n    // y is 1 if the normal points up, and -1 if it points down\n    mediump vec2 normal = a_pos_normal.zw;\n    v_normal = normal;\n\n    // these transformations used to be applied in the JS and native code bases.\n    // moved them into the shader for clarity and simplicity.\n    gapwidth = gapwidth / 2.0;\n    float halfwidth = width / 2.0;\n    offset = -1.0 * offset;\n\n    float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n    float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n    // Scale the extrusion vector down to a normal and then up by the line width\n    // of this vertex.\n    mediump vec2 dist =outset * a_extrude * scale;\n\n    // Calculate the offset when drawing a line that is to the side of the actual line.\n    // We do this by creating a vector that points towards the extrude, but rotate\n    // it when we're drawing round end points (a_direction = -1 or 1) since their\n    // extrude vector points in another direction.\n    mediump float u = 0.5 * a_direction;\n    mediump float t = 1.0 - abs(u);\n    mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n    vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n    gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n    // calculate how much the perspective view squishes or stretches the extrude\n    float extrude_length_without_perspective = length(dist);\n    float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n    v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n    v_tex_a = vec2(a_linesofar * u_patternscale_a.x / floorwidth, normal.y * u_patternscale_a.y + u_tex_y_a);\n    v_tex_b = vec2(a_linesofar * u_patternscale_b.x / floorwidth, normal.y * u_patternscale_b.y + u_tex_y_b);\n\n    v_width2 = vec2(outset, inset);\n}\n"},raster:{fragmentSource:"uniform float u_fade_t;\nuniform float u_opacity;\nuniform sampler2D u_image0;\nuniform sampler2D u_image1;\nvarying vec2 v_pos0;\nvarying vec2 v_pos1;\n\nuniform float u_brightness_low;\nuniform float u_brightness_high;\n\nuniform float u_saturation_factor;\nuniform float u_contrast_factor;\nuniform vec3 u_spin_weights;\n\nvoid main() {\n\n    // read and cross-fade colors from the main and parent tiles\n    vec4 color0 = texture2D(u_image0, v_pos0);\n    vec4 color1 = texture2D(u_image1, v_pos1);\n    if (color0.a > 0.0) {\n        color0.rgb = color0.rgb / color0.a;\n    }\n    if (color1.a > 0.0) {\n        color1.rgb = color1.rgb / color1.a;\n    }\n    vec4 color = mix(color0, color1, u_fade_t);\n    color.a *= u_opacity;\n    vec3 rgb = color.rgb;\n\n    // spin\n    rgb = vec3(\n        dot(rgb, u_spin_weights.xyz),\n        dot(rgb, u_spin_weights.zxy),\n        dot(rgb, u_spin_weights.yzx));\n\n    // saturation\n    float average = (color.r + color.g + color.b) / 3.0;\n    rgb += (average - rgb) * u_saturation_factor;\n\n    // contrast\n    rgb = (rgb - 0.5) * u_contrast_factor + 0.5;\n\n    // brightness\n    vec3 u_high_vec = vec3(u_brightness_low, u_brightness_low, u_brightness_low);\n    vec3 u_low_vec = vec3(u_brightness_high, u_brightness_high, u_brightness_high);\n\n    gl_FragColor = vec4(mix(u_high_vec, u_low_vec, rgb) * color.a, color.a);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_tl_parent;\nuniform float u_scale_parent;\nuniform float u_buffer_scale;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos0;\nvarying vec2 v_pos1;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n    // We are using Int16 for texture position coordinates to give us enough precision for\n    // fractional coordinates. We use 8192 to scale the texture coordinates in the buffer\n    // as an arbitrarily high number to preserve adequate precision when rendering.\n    // This is also the same value as the EXTENT we are using for our tile buffer pos coordinates,\n    // so math for modifying either is consistent.\n    v_pos0 = (((a_texture_pos / 8192.0) - 0.5) / u_buffer_scale ) + 0.5;\n    v_pos1 = (v_pos0 * u_scale_parent) + u_tl_parent;\n}\n"},symbolIcon:{fragmentSource:"uniform sampler2D u_texture;\n\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_tex;\nvarying float v_fade_opacity;\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    lowp float alpha = opacity * v_fade_opacity;\n    gl_FragColor = texture2D(u_texture, v_tex) * alpha;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"const float PI = 3.141592653589793;\n\nattribute vec4 a_pos_offset;\nattribute vec4 a_data;\nattribute vec3 a_projected_pos;\nattribute float a_fade_opacity;\n\nuniform bool u_is_size_zoom_constant;\nuniform bool u_is_size_feature_constant;\nuniform highp float u_size_t; // used to interpolate between zoom stops when size is a composite function\nuniform highp float u_size; // used when size is both zoom and feature constant\nuniform highp float u_camera_to_center_distance;\nuniform highp float u_pitch;\nuniform bool u_rotate_symbol;\nuniform highp float u_aspect_ratio;\nuniform float u_fade_change;\n\n#pragma mapbox: define lowp float opacity\n\nuniform mat4 u_matrix;\nuniform mat4 u_label_plane_matrix;\nuniform mat4 u_gl_coord_matrix;\n\nuniform bool u_is_text;\nuniform bool u_pitch_with_map;\n\nuniform vec2 u_texsize;\n\nvarying vec2 v_tex;\nvarying float v_fade_opacity;\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    vec2 a_pos = a_pos_offset.xy;\n    vec2 a_offset = a_pos_offset.zw;\n\n    vec2 a_tex = a_data.xy;\n    vec2 a_size = a_data.zw;\n\n    highp float segment_angle = -a_projected_pos[2];\n\n    float size;\n    if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {\n        size = mix(a_size[0], a_size[1], u_size_t) / 10.0;\n    } else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {\n        size = a_size[0] / 10.0;\n    } else if (!u_is_size_zoom_constant && u_is_size_feature_constant) {\n        size = u_size;\n    } else {\n        size = u_size;\n    }\n\n    vec4 projectedPoint = u_matrix * vec4(a_pos, 0, 1);\n    highp float camera_to_anchor_distance = projectedPoint.w;\n    // See comments in symbol_sdf.vertex\n    highp float distance_ratio = u_pitch_with_map ?\n        camera_to_anchor_distance / u_camera_to_center_distance :\n        u_camera_to_center_distance / camera_to_anchor_distance;\n    highp float perspective_ratio = clamp(\n            0.5 + 0.5 * distance_ratio,\n            0.0, // Prevents oversized near-field symbols in pitched/overzoomed tiles\n            4.0);\n\n    size *= perspective_ratio;\n\n    float fontScale = u_is_text ? size / 24.0 : size;\n\n    highp float symbol_rotation = 0.0;\n    if (u_rotate_symbol) {\n        // See comments in symbol_sdf.vertex\n        vec4 offsetProjectedPoint = u_matrix * vec4(a_pos + vec2(1, 0), 0, 1);\n\n        vec2 a = projectedPoint.xy / projectedPoint.w;\n        vec2 b = offsetProjectedPoint.xy / offsetProjectedPoint.w;\n\n        symbol_rotation = atan((b.y - a.y) / u_aspect_ratio, b.x - a.x);\n    }\n\n    highp float angle_sin = sin(segment_angle + symbol_rotation);\n    highp float angle_cos = cos(segment_angle + symbol_rotation);\n    mat2 rotation_matrix = mat2(angle_cos, -1.0 * angle_sin, angle_sin, angle_cos);\n\n    vec4 projected_pos = u_label_plane_matrix * vec4(a_projected_pos.xy, 0.0, 1.0);\n    gl_Position = u_gl_coord_matrix * vec4(projected_pos.xy / projected_pos.w + rotation_matrix * (a_offset / 32.0 * fontScale), 0.0, 1.0);\n\n    v_tex = a_tex / u_texsize;\n    vec2 fade_opacity = unpack_opacity(a_fade_opacity);\n    float fade_change = fade_opacity[1] > 0.5 ? u_fade_change : -u_fade_change;\n    v_fade_opacity = max(0.0, min(1.0, fade_opacity[0] + fade_change));\n}\n"},symbolSDF:{fragmentSource:"#define SDF_PX 8.0\n#define EDGE_GAMMA 0.105/DEVICE_PIXEL_RATIO\n\nuniform bool u_is_halo;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\n\nuniform sampler2D u_texture;\nuniform highp float u_gamma_scale;\nuniform bool u_is_text;\n\nvarying vec2 v_data0;\nvarying vec3 v_data1;\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 fill_color\n    #pragma mapbox: initialize highp vec4 halo_color\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize lowp float halo_width\n    #pragma mapbox: initialize lowp float halo_blur\n\n    vec2 tex = v_data0.xy;\n    float gamma_scale = v_data1.x;\n    float size = v_data1.y;\n    float fade_opacity = v_data1[2];\n\n    float fontScale = u_is_text ? size / 24.0 : size;\n\n    lowp vec4 color = fill_color;\n    highp float gamma = EDGE_GAMMA / (fontScale * u_gamma_scale);\n    lowp float buff = (256.0 - 64.0) / 256.0;\n    if (u_is_halo) {\n        color = halo_color;\n        gamma = (halo_blur * 1.19 / SDF_PX + EDGE_GAMMA) / (fontScale * u_gamma_scale);\n        buff = (6.0 - halo_width / fontScale) / SDF_PX;\n    }\n\n    lowp float dist = texture2D(u_texture, tex).a;\n    highp float gamma_scaled = gamma * gamma_scale;\n    highp float alpha = smoothstep(buff - gamma_scaled, buff + gamma_scaled, dist);\n\n    gl_FragColor = color * (alpha * opacity * fade_opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"const float PI = 3.141592653589793;\n\nattribute vec4 a_pos_offset;\nattribute vec4 a_data;\nattribute vec3 a_projected_pos;\nattribute float a_fade_opacity;\n\n// contents of a_size vary based on the type of property value\n// used for {text,icon}-size.\n// For constants, a_size is disabled.\n// For source functions, we bind only one value per vertex: the value of {text,icon}-size evaluated for the current feature.\n// For composite functions:\n// [ text-size(lowerZoomStop, feature),\n//   text-size(upperZoomStop, feature) ]\nuniform bool u_is_size_zoom_constant;\nuniform bool u_is_size_feature_constant;\nuniform highp float u_size_t; // used to interpolate between zoom stops when size is a composite function\nuniform highp float u_size; // used when size is both zoom and feature constant\n\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\n\nuniform mat4 u_matrix;\nuniform mat4 u_label_plane_matrix;\nuniform mat4 u_gl_coord_matrix;\n\nuniform bool u_is_text;\nuniform bool u_pitch_with_map;\nuniform highp float u_pitch;\nuniform bool u_rotate_symbol;\nuniform highp float u_aspect_ratio;\nuniform highp float u_camera_to_center_distance;\nuniform float u_fade_change;\n\nuniform vec2 u_texsize;\n\nvarying vec2 v_data0;\nvarying vec3 v_data1;\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 fill_color\n    #pragma mapbox: initialize highp vec4 halo_color\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize lowp float halo_width\n    #pragma mapbox: initialize lowp float halo_blur\n\n    vec2 a_pos = a_pos_offset.xy;\n    vec2 a_offset = a_pos_offset.zw;\n\n    vec2 a_tex = a_data.xy;\n    vec2 a_size = a_data.zw;\n\n    highp float segment_angle = -a_projected_pos[2];\n    float size;\n\n    if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {\n        size = mix(a_size[0], a_size[1], u_size_t) / 10.0;\n    } else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {\n        size = a_size[0] / 10.0;\n    } else if (!u_is_size_zoom_constant && u_is_size_feature_constant) {\n        size = u_size;\n    } else {\n        size = u_size;\n    }\n\n    vec4 projectedPoint = u_matrix * vec4(a_pos, 0, 1);\n    highp float camera_to_anchor_distance = projectedPoint.w;\n    // If the label is pitched with the map, layout is done in pitched space,\n    // which makes labels in the distance smaller relative to viewport space.\n    // We counteract part of that effect by multiplying by the perspective ratio.\n    // If the label isn't pitched with the map, we do layout in viewport space,\n    // which makes labels in the distance larger relative to the features around\n    // them. We counteract part of that effect by dividing by the perspective ratio.\n    highp float distance_ratio = u_pitch_with_map ?\n        camera_to_anchor_distance / u_camera_to_center_distance :\n        u_camera_to_center_distance / camera_to_anchor_distance;\n    highp float perspective_ratio = clamp(\n        0.5 + 0.5 * distance_ratio,\n        0.0, // Prevents oversized near-field symbols in pitched/overzoomed tiles\n        4.0);\n\n    size *= perspective_ratio;\n\n    float fontScale = u_is_text ? size / 24.0 : size;\n\n    highp float symbol_rotation = 0.0;\n    if (u_rotate_symbol) {\n        // Point labels with 'rotation-alignment: map' are horizontal with respect to tile units\n        // To figure out that angle in projected space, we draw a short horizontal line in tile\n        // space, project it, and measure its angle in projected space.\n        vec4 offsetProjectedPoint = u_matrix * vec4(a_pos + vec2(1, 0), 0, 1);\n\n        vec2 a = projectedPoint.xy / projectedPoint.w;\n        vec2 b = offsetProjectedPoint.xy / offsetProjectedPoint.w;\n\n        symbol_rotation = atan((b.y - a.y) / u_aspect_ratio, b.x - a.x);\n    }\n\n    highp float angle_sin = sin(segment_angle + symbol_rotation);\n    highp float angle_cos = cos(segment_angle + symbol_rotation);\n    mat2 rotation_matrix = mat2(angle_cos, -1.0 * angle_sin, angle_sin, angle_cos);\n\n    vec4 projected_pos = u_label_plane_matrix * vec4(a_projected_pos.xy, 0.0, 1.0);\n    gl_Position = u_gl_coord_matrix * vec4(projected_pos.xy / projected_pos.w + rotation_matrix * (a_offset / 32.0 * fontScale), 0.0, 1.0);\n    float gamma_scale = gl_Position.w;\n\n    vec2 tex = a_tex / u_texsize;\n    vec2 fade_opacity = unpack_opacity(a_fade_opacity);\n    float fade_change = fade_opacity[1] > 0.5 ? u_fade_change : -u_fade_change;\n    float interpolated_fade_opacity = max(0.0, min(1.0, fade_opacity[0] + fade_change));\n\n    v_data0 = vec2(tex.x, tex.y);\n    v_data1 = vec3(gamma_scale, size, interpolated_fade_opacity);\n}\n"}},ii=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,ni=function(t){var e=ei[t],i={};e.fragmentSource=e.fragmentSource.replace(ii,function(t,e,n,o,r){return i[r]=!0,"define"===e?"\n#ifndef HAS_UNIFORM_u_"+r+"\nvarying "+n+" "+o+" "+r+";\n#else\nuniform "+n+" "+o+" u_"+r+";\n#endif\n":"\n#ifdef HAS_UNIFORM_u_"+r+"\n    "+n+" "+o+" "+r+" = u_"+r+";\n#endif\n"}),e.vertexSource=e.vertexSource.replace(ii,function(t,e,n,o,r){var a="float"===o?"vec2":"vec4";return i[r]?"define"===e?"\n#ifndef HAS_UNIFORM_u_"+r+"\nuniform lowp float a_"+r+"_t;\nattribute "+n+" "+a+" a_"+r+";\nvarying "+n+" "+o+" "+r+";\n#else\nuniform "+n+" "+o+" u_"+r+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+r+"\n    "+r+" = unpack_mix_"+a+"(a_"+r+", a_"+r+"_t);\n#else\n    "+n+" "+o+" "+r+" = u_"+r+";\n#endif\n":"define"===e?"\n#ifndef HAS_UNIFORM_u_"+r+"\nuniform lowp float a_"+r+"_t;\nattribute "+n+" "+a+" a_"+r+";\n#else\nuniform "+n+" "+o+" u_"+r+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+r+"\n    "+n+" "+o+" "+r+" = unpack_mix_"+a+"(a_"+r+", a_"+r+"_t);\n#else\n    "+n+" "+o+" "+r+" = u_"+r+";\n#endif\n"});};for(var oi in ei)ni(oi);var ri=ei,ai=function(t,e,i,n){var o=t.gl;this.program=o.createProgram();var a=i.defines().concat("#define DEVICE_PIXEL_RATIO "+r.devicePixelRatio.toFixed(1));n&&a.push("#define OVERDRAW_INSPECTOR;");var s=a.concat(ri.prelude.fragmentSource,e.fragmentSource).join("\n"),l=a.concat(ri.prelude.vertexSource,e.vertexSource).join("\n"),c=o.createShader(o.FRAGMENT_SHADER);o.shaderSource(c,s),o.compileShader(c),o.attachShader(this.program,c);var u=o.createShader(o.VERTEX_SHADER);o.shaderSource(u,l),o.compileShader(u),o.attachShader(this.program,u);for(var h=i.layoutAttributes||[],p=0;p<h.length;p++)o.bindAttribLocation(this.program,p,h[p].name);o.linkProgram(this.program),this.numAttributes=o.getProgramParameter(this.program,o.ACTIVE_ATTRIBUTES),this.attributes={},this.uniforms={};for(var d=0;d<this.numAttributes;d++){var f=o.getActiveAttrib(this.program,d);f&&(this.attributes[f.name]=o.getAttribLocation(this.program,f.name));}for(var m=o.getProgramParameter(this.program,o.ACTIVE_UNIFORMS),_=0;_<m;_++){var g=o.getActiveUniform(this.program,_);g&&(this.uniforms[g.name]=o.getUniformLocation(this.program,g.name));}};function si(e,i,n,o,r){for(var a=0;a<n.length;a++){var s=n[a];if(o.isLessThan(s.tileID))break;if(i.key===s.tileID.key)return;if(s.tileID.isChildOf(i)){for(var l=i.children(1/0),c=0;c<l.length;c++){si(e,l[c],n.slice(a),o,r);}return}}var u=i.overscaledZ-e.overscaledZ,h=new t.CanonicalTileID(u,i.canonical.x-(e.canonical.x<<u),i.canonical.y-(e.canonical.y<<u));r[h.key]=r[h.key]||h;}function li(t,e,i,n,o){var r=t.context,a=r.gl,s=o?t.useProgram("collisionCircle"):t.useProgram("collisionBox");r.setDepthMode($t.disabled),r.setStencilMode(Gt.disabled),r.setColorMode(t.colorModeForRenderPass());for(var l=0;l<n.length;l++){var c=n[l],u=e.getTile(c),h=u.getBucket(i);if(h){var p=o?h.collisionCircle:h.collisionBox;if(p){a.uniformMatrix4fv(s.uniforms.u_matrix,!1,c.posMatrix),o||r.lineWidth.set(1),a.uniform1f(s.uniforms.u_camera_to_center_distance,t.transform.cameraToCenterDistance);var d=ze(u,1,t.transform.zoom),f=Math.pow(2,t.transform.zoom-u.tileID.overscaledZ);a.uniform1f(s.uniforms.u_pixels_to_tile_units,d),a.uniform2f(s.uniforms.u_extrude_scale,t.transform.pixelsToGLUnits[0]/(d*f),t.transform.pixelsToGLUnits[1]/(d*f)),a.uniform1f(s.uniforms.u_overscale_factor,u.tileID.overscaleFactor()),s.draw(r,o?a.TRIANGLES:a.LINES,i.id,p.layoutVertexBuffer,p.indexBuffer,p.segments,null,p.collisionVertexBuffer,null);}}}}ai.prototype.draw=function(t,e,i,n,o,r,a,s,l){for(var c,u=t.gl,h=(c={},c[u.LINES]=2,c[u.TRIANGLES]=3,c)[e],p=0,d=r.get();p<d.length;p+=1){var f=d[p],m=f.vaos||(f.vaos={});(m[i]||(m[i]=new tt)).bind(t,this,n,a?a.getPaintVertexBuffers():[],o,f.vertexOffset,s,l),u.drawElements(e,f.primitiveLength*h,u.UNSIGNED_SHORT,f.primitiveOffset*h*2);}};var ci=t.mat4.identity(new Float32Array(16)),ui=t.default$19.layout;function hi(t,e,i,n,o,r,a,s,l,c){var u,h=t.context,p=h.gl,d=t.transform,f="map"===s,m="map"===l,_=f&&"line"===i.layout.get("symbol-placement"),g=f&&!m&&!_,v=m;h.setDepthMode(v?t.depthModeForSublayer(0,$t.ReadOnly):$t.disabled);for(var y=0,x=n;y<x.length;y+=1){var b=x[y],w=e.getTile(b),E=w.getBucket(i);if(E){var T=o?E.text:E.icon;if(T&&T.segments.get().length){var I=T.programConfigurations.get(i.id),C=o||E.sdfIcons,S=o?E.textSizeData:E.iconSizeData;if(u||(u=t.useProgram(C?"symbolSDF":"symbolIcon",I),I.setUniforms(t.context,u,i.paint,{zoom:t.transform.zoom}),pi(u,t,i,o,g,m,S)),h.activeTexture.set(p.TEXTURE0),p.uniform1i(u.uniforms.u_texture,0),o)w.glyphAtlasTexture.bind(p.LINEAR,p.CLAMP_TO_EDGE),p.uniform2fv(u.uniforms.u_texsize,w.glyphAtlasTexture.size);else{var z=1!==i.layout.get("icon-size").constantOr(0)||E.iconsNeedLinear,A=m||0!==d.pitch;w.iconAtlasTexture.bind(C||t.options.rotating||t.options.zooming||z||A?p.LINEAR:p.NEAREST,p.CLAMP_TO_EDGE),p.uniform2fv(u.uniforms.u_texsize,w.iconAtlasTexture.size);}p.uniformMatrix4fv(u.uniforms.u_matrix,!1,t.translatePosMatrix(b.posMatrix,w,r,a));var R=ze(w,1,t.transform.zoom),D=de(b.posMatrix,m,f,t.transform,R),M=fe(b.posMatrix,m,f,t.transform,R);p.uniformMatrix4fv(u.uniforms.u_gl_coord_matrix,!1,t.translatePosMatrix(M,w,r,a,!0)),_?(p.uniformMatrix4fv(u.uniforms.u_label_plane_matrix,!1,ci),ge(E,b.posMatrix,t,o,D,M,m,c)):p.uniformMatrix4fv(u.uniforms.u_label_plane_matrix,!1,D),p.uniform1f(u.uniforms.u_fade_change,t.options.fadeDuration?t.symbolFadeChange:1),di(u,I,t,i,w,T,o,C,m);}}}}function pi(e,i,n,o,r,a,s){var l=i.context.gl,c=i.transform;l.uniform1i(e.uniforms.u_pitch_with_map,a?1:0),l.uniform1f(e.uniforms.u_is_text,o?1:0),l.uniform1f(e.uniforms.u_pitch,c.pitch/360*2*Math.PI);var u="constant"===s.functionType||"source"===s.functionType,h="constant"===s.functionType||"camera"===s.functionType;l.uniform1i(e.uniforms.u_is_size_zoom_constant,u?1:0),l.uniform1i(e.uniforms.u_is_size_feature_constant,h?1:0),l.uniform1f(e.uniforms.u_camera_to_center_distance,c.cameraToCenterDistance);var p=t.evaluateSizeForZoom(s,c.zoom,ui.properties[o?"text-size":"icon-size"]);void 0!==p.uSizeT&&l.uniform1f(e.uniforms.u_size_t,p.uSizeT),void 0!==p.uSize&&l.uniform1f(e.uniforms.u_size,p.uSize),l.uniform1f(e.uniforms.u_aspect_ratio,c.width/c.height),l.uniform1i(e.uniforms.u_rotate_symbol,r?1:0);}function di(t,e,i,n,o,r,a,s,l){var c=i.context,u=c.gl,h=i.transform;if(s){var p=0!==n.paint.get(a?"text-halo-width":"icon-halo-width").constantOr(1),d=l?Math.cos(h._pitch)*h.cameraToCenterDistance:1;u.uniform1f(t.uniforms.u_gamma_scale,d),p&&(u.uniform1f(t.uniforms.u_is_halo,1),fi(r,n,c,t)),u.uniform1f(t.uniforms.u_is_halo,0);}fi(r,n,c,t);}function fi(t,e,i,n){n.draw(i,i.gl.TRIANGLES,e.id,t.layoutVertexBuffer,t.indexBuffer,t.segments,t.programConfigurations.get(e.id),t.dynamicLayoutVertexBuffer,t.opacityVertexBuffer);}function mi(t,e,i,n,o,a,s,l,c){var u,h,p,d,f=e.context,m=f.gl,_=o.paint.get("line-dasharray"),g=o.paint.get("line-pattern");if(l||c){var v=1/ze(i,1,e.transform.tileZoom);if(_){u=e.lineAtlas.getDash(_.from,"round"===o.layout.get("line-cap")),h=e.lineAtlas.getDash(_.to,"round"===o.layout.get("line-cap"));var y=u.width*_.fromScale,x=h.width*_.toScale;m.uniform2f(t.uniforms.u_patternscale_a,v/y,-u.height/2),m.uniform2f(t.uniforms.u_patternscale_b,v/x,-h.height/2),m.uniform1f(t.uniforms.u_sdfgamma,e.lineAtlas.width/(256*Math.min(y,x)*r.devicePixelRatio)/2);}else if(g){if(p=e.imageManager.getPattern(g.from),d=e.imageManager.getPattern(g.to),!p||!d)return;m.uniform2f(t.uniforms.u_pattern_size_a,p.displaySize[0]*g.fromScale/v,p.displaySize[1]),m.uniform2f(t.uniforms.u_pattern_size_b,d.displaySize[0]*g.toScale/v,d.displaySize[1]);var b=e.imageManager.getPixelSize(),w=b.width,E=b.height;m.uniform2fv(t.uniforms.u_texsize,[w,E]);}m.uniform2f(t.uniforms.u_gl_units_to_pixels,1/e.transform.pixelsToGLUnits[0],1/e.transform.pixelsToGLUnits[1]);}l&&(_?(m.uniform1i(t.uniforms.u_image,0),f.activeTexture.set(m.TEXTURE0),e.lineAtlas.bind(f),m.uniform1f(t.uniforms.u_tex_y_a,u.y),m.uniform1f(t.uniforms.u_tex_y_b,h.y),m.uniform1f(t.uniforms.u_mix,_.t)):g&&(m.uniform1i(t.uniforms.u_image,0),f.activeTexture.set(m.TEXTURE0),e.imageManager.bind(f),m.uniform2fv(t.uniforms.u_pattern_tl_a,p.tl),m.uniform2fv(t.uniforms.u_pattern_br_a,p.br),m.uniform2fv(t.uniforms.u_pattern_tl_b,d.tl),m.uniform2fv(t.uniforms.u_pattern_br_b,d.br),m.uniform1f(t.uniforms.u_fade,g.t))),f.setStencilMode(e.stencilModeForClipping(a));var T=e.translatePosMatrix(a.posMatrix,i,o.paint.get("line-translate"),o.paint.get("line-translate-anchor"));if(m.uniformMatrix4fv(t.uniforms.u_matrix,!1,T),m.uniform1f(t.uniforms.u_ratio,1/ze(i,1,e.transform.zoom)),o.paint.get("line-gradient")){f.activeTexture.set(m.TEXTURE0);var I=o.gradientTexture;if(!o.gradient)return;I||(I=o.gradientTexture=new M(f,o.gradient,m.RGBA)),I.bind(m.LINEAR,m.CLAMP_TO_EDGE),m.uniform1i(t.uniforms.u_image,0);}t.draw(f,m.TRIANGLES,o.id,n.layoutVertexBuffer,n.indexBuffer,n.segments,s);}var _i=function(t,e){if(!t)return!1;var i=e.imageManager.getPattern(t.from),n=e.imageManager.getPattern(t.to);return!i||!n},gi=function(t,e,i){var n=e.context,o=n.gl,r=e.imageManager.getPattern(t.from),a=e.imageManager.getPattern(t.to);o.uniform1i(i.uniforms.u_image,0),o.uniform2fv(i.uniforms.u_pattern_tl_a,r.tl),o.uniform2fv(i.uniforms.u_pattern_br_a,r.br),o.uniform2fv(i.uniforms.u_pattern_tl_b,a.tl),o.uniform2fv(i.uniforms.u_pattern_br_b,a.br);var s=e.imageManager.getPixelSize(),l=s.width,c=s.height;o.uniform2fv(i.uniforms.u_texsize,[l,c]),o.uniform1f(i.uniforms.u_mix,t.t),o.uniform2fv(i.uniforms.u_pattern_size_a,r.displaySize),o.uniform2fv(i.uniforms.u_pattern_size_b,a.displaySize),o.uniform1f(i.uniforms.u_scale_a,t.fromScale),o.uniform1f(i.uniforms.u_scale_b,t.toScale),n.activeTexture.set(o.TEXTURE0),e.imageManager.bind(e.context);},vi=function(t,e,i){var n=e.context.gl;n.uniform1f(i.uniforms.u_tile_units_to_pixels,1/ze(t,1,e.transform.tileZoom));var o=Math.pow(2,t.tileID.overscaledZ),r=t.tileSize*Math.pow(2,e.transform.tileZoom)/o,a=r*(t.tileID.canonical.x+t.tileID.wrap*o),s=r*t.tileID.canonical.y;n.uniform2f(i.uniforms.u_pixel_coord_upper,a>>16,s>>16),n.uniform2f(i.uniforms.u_pixel_coord_lower,65535&a,65535&s);};function yi(t,e,i,n,o){if(!_i(i.paint.get("fill-pattern"),t))for(var r=!0,a=0,s=n;a<s.length;a+=1){var l=s[a],c=e.getTile(l),u=c.getBucket(i);u&&(t.context.setStencilMode(t.stencilModeForClipping(l)),o(t,e,i,c,l,u,r),r=!1);}}function xi(t,e,i,n,o,r,a){var s=t.context.gl,l=r.programConfigurations.get(i.id);wi("fill",i.paint.get("fill-pattern"),t,l,i,n,o,a).draw(t.context,s.TRIANGLES,i.id,r.layoutVertexBuffer,r.indexBuffer,r.segments,l);}function bi(t,e,i,n,o,r,a){var s=t.context.gl,l=r.programConfigurations.get(i.id),c=wi("fillOutline",i.getPaintProperty("fill-outline-color")?null:i.paint.get("fill-pattern"),t,l,i,n,o,a);s.uniform2f(c.uniforms.u_world,s.drawingBufferWidth,s.drawingBufferHeight),c.draw(t.context,s.LINES,i.id,r.layoutVertexBuffer,r.indexBuffer2,r.segments2,l);}function wi(t,e,i,n,o,r,a,s){var l,c=i.context.program.get();return e?(l=i.useProgram(t+"Pattern",n),(s||l.program!==c)&&(n.setUniforms(i.context,l,o.paint,{zoom:i.transform.zoom}),gi(e,i,l)),vi(r,i,l)):(l=i.useProgram(t,n),(s||l.program!==c)&&n.setUniforms(i.context,l,o.paint,{zoom:i.transform.zoom})),i.context.gl.uniformMatrix4fv(l.uniforms.u_matrix,!1,i.translatePosMatrix(a.posMatrix,r,o.paint.get("fill-translate"),o.paint.get("fill-translate-anchor"))),l}var Ei=t.default$20.mat3,Ti=t.default$20.mat4,Ii=t.default$20.vec3;function Ci(t,e,i,n,o,r,a){var s=t.context,l=s.gl,c=i.paint.get("fill-extrusion-pattern"),u=t.context.program.get(),h=r.programConfigurations.get(i.id),p=t.useProgram(c?"fillExtrusionPattern":"fillExtrusion",h);if((a||p.program!==u)&&h.setUniforms(s,p,i.paint,{zoom:t.transform.zoom}),c){if(_i(c,t))return;gi(c,t,p),vi(n,t,p),l.uniform1f(p.uniforms.u_height_factor,-Math.pow(2,o.overscaledZ)/n.tileSize/8);}t.context.gl.uniformMatrix4fv(p.uniforms.u_matrix,!1,t.translatePosMatrix(o.posMatrix,n,i.paint.get("fill-extrusion-translate"),i.paint.get("fill-extrusion-translate-anchor"))),function(t,e){var i=e.context.gl,n=e.style.light,o=n.properties.get("position"),r=[o.x,o.y,o.z],a=Ei.create();"viewport"===n.properties.get("anchor")&&Ei.fromRotation(a,-e.transform.angle);Ii.transformMat3(r,r,a);var s=n.properties.get("color");i.uniform3fv(t.uniforms.u_lightpos,r),i.uniform1f(t.uniforms.u_lightintensity,n.properties.get("intensity")),i.uniform3f(t.uniforms.u_lightcolor,s.r,s.g,s.b);}(p,t),p.draw(s,l.TRIANGLES,i.id,r.layoutVertexBuffer,r.indexBuffer,r.segments,h);}function Si(e,i,n){var o=e.context,r=o.gl,a=i.fbo;if(a){var s=e.useProgram("hillshade"),l=e.transform.calculatePosMatrix(i.tileID.toUnwrapped(),!0);!function(t,e,i){var n=i.paint.get("hillshade-illumination-direction")*(Math.PI/180);"viewport"===i.paint.get("hillshade-illumination-anchor")&&(n-=e.transform.angle),e.context.gl.uniform2f(t.uniforms.u_light,i.paint.get("hillshade-exaggeration"),n);}(s,e,n);var c=function(e,i){var n=i.toCoordinate(),o=new t.default$17(n.column,n.row+1,n.zoom);return[e.transform.coordinateLocation(n).lat,e.transform.coordinateLocation(o).lat]}(e,i.tileID);o.activeTexture.set(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,a.colorAttachment.get()),r.uniformMatrix4fv(s.uniforms.u_matrix,!1,l),r.uniform2fv(s.uniforms.u_latrange,c),r.uniform1i(s.uniforms.u_image,0);var u=n.paint.get("hillshade-shadow-color");r.uniform4f(s.uniforms.u_shadow,u.r,u.g,u.b,u.a);var h=n.paint.get("hillshade-highlight-color");r.uniform4f(s.uniforms.u_highlight,h.r,h.g,h.b,h.a);var p=n.paint.get("hillshade-accent-color");if(r.uniform4f(s.uniforms.u_accent,p.r,p.g,p.b,p.a),i.maskedBoundsBuffer&&i.maskedIndexBuffer&&i.segments)s.draw(o,r.TRIANGLES,n.id,i.maskedBoundsBuffer,i.maskedIndexBuffer,i.segments);else{var d=e.rasterBoundsBuffer;e.rasterBoundsVAO.bind(o,s,d,[]),r.drawArrays(r.TRIANGLE_STRIP,0,d.length);}}}function zi(e,i,n){var o=e.context,r=o.gl;if(i.dem&&i.dem.level){var a=i.dem.level.dim,s=i.dem.getPixels();if(o.activeTexture.set(r.TEXTURE1),o.pixelStoreUnpackPremultiplyAlpha.set(!1),i.demTexture=i.demTexture||e.getTileTexture(i.tileSize),i.demTexture){var l=i.demTexture;l.update(s,{premultiply:!1}),l.bind(r.NEAREST,r.CLAMP_TO_EDGE);}else i.demTexture=new M(o,s,r.RGBA,{premultiply:!1}),i.demTexture.bind(r.NEAREST,r.CLAMP_TO_EDGE);o.activeTexture.set(r.TEXTURE0);var c=i.fbo;if(!c){var u=new M(o,{width:a,height:a,data:null},r.RGBA);u.bind(r.LINEAR,r.CLAMP_TO_EDGE),(c=i.fbo=o.createFramebuffer(a,a)).colorAttachment.set(u.texture);}o.bindFramebuffer.set(c.framebuffer),o.viewport.set([0,0,a,a]);var h=t.mat4.create();t.mat4.ortho(h,0,t.default$8,-t.default$8,0,0,1),t.mat4.translate(h,h,[0,-t.default$8,0]);var p=e.useProgram("hillshadePrepare");r.uniformMatrix4fv(p.uniforms.u_matrix,!1,h),r.uniform1f(p.uniforms.u_zoom,i.tileID.overscaledZ),r.uniform2fv(p.uniforms.u_dimension,[2*a,2*a]),r.uniform1i(p.uniforms.u_image,1),r.uniform1f(p.uniforms.u_maxzoom,n);var d=e.rasterBoundsBuffer;e.rasterBoundsVAO.bind(o,p,d,[]),r.drawArrays(r.TRIANGLE_STRIP,0,d.length),i.needsHillshadePrepare=!1;}}function Ai(e,i,n,o,a){var s=o.paint.get("raster-fade-duration");if(s>0){var l=r.now(),c=(l-e.timeAdded)/s,u=i?(l-i.timeAdded)/s:-1,h=n.getSource(),p=a.coveringZoomLevel({tileSize:h.tileSize,roundZoom:h.roundZoom}),d=!i||Math.abs(i.tileID.overscaledZ-p)>Math.abs(e.tileID.overscaledZ-p),f=d&&e.refreshedUponExpiration?1:t.clamp(d?c:1-u,0,1);return e.refreshedUponExpiration&&c>=1&&(e.refreshedUponExpiration=!1),i?{opacity:1,mix:1-f}:{opacity:f,mix:0}}return{opacity:1,mix:0}}function Ri(e,i,n){var o=e.context,a=o.gl;o.lineWidth.set(1*r.devicePixelRatio);var s=n.posMatrix,l=e.useProgram("debug");o.setDepthMode($t.disabled),o.setStencilMode(Gt.disabled),o.setColorMode(e.colorModeForRenderPass()),a.uniformMatrix4fv(l.uniforms.u_matrix,!1,s),a.uniform4f(l.uniforms.u_color,1,0,0,1),e.debugVAO.bind(o,l,e.debugBuffer,[]),a.drawArrays(a.LINE_STRIP,0,e.debugBuffer.length);for(var c=function(t,e,i,n){n=n||1;var o,r,a,s,l,c,u,h,p=[];for(o=0,r=t.length;o<r;o++)if(l=Di[t[o]]){for(h=null,a=0,s=l[1].length;a<s;a+=2)-1===l[1][a]&&-1===l[1][a+1]?h=null:(c=e+l[1][a]*n,u=i-l[1][a+1]*n,h&&p.push(h.x,h.y,c,u),h={x:c,y:u});e+=l[0]*n;}return p}(n.toString(),50,200,5),u=new t.PosArray,h=0;h<c.length;h+=2)u.emplaceBack(c[h],c[h+1]);var p=o.createVertexBuffer(u,ti.members);(new tt).bind(o,l,p,[]),a.uniform4f(l.uniforms.u_color,1,1,1,1);for(var d=i.getTile(n).tileSize,f=t.default$8/(Math.pow(2,e.transform.zoom-n.overscaledZ)*d),m=[[-1,-1],[-1,1],[1,-1],[1,1]],_=0;_<m.length;_++){var g=m[_];a.uniformMatrix4fv(l.uniforms.u_matrix,!1,t.mat4.translate([],s,[f*g[0],f*g[1],0])),a.drawArrays(a.LINES,0,p.length);}a.uniform4f(l.uniforms.u_color,0,0,0,1),a.uniformMatrix4fv(l.uniforms.u_matrix,!1,s),a.drawArrays(a.LINES,0,p.length);}var Di={" ":[16,[]],"!":[10,[5,21,5,7,-1,-1,5,2,4,1,5,0,6,1,5,2]],'"':[16,[4,21,4,14,-1,-1,12,21,12,14]],"#":[21,[11,25,4,-7,-1,-1,17,25,10,-7,-1,-1,4,12,18,12,-1,-1,3,6,17,6]],$:[20,[8,25,8,-4,-1,-1,12,25,12,-4,-1,-1,17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3]],"%":[24,[21,21,3,0,-1,-1,8,21,10,19,10,17,9,15,7,14,5,14,3,16,3,18,4,20,6,21,8,21,10,20,13,19,16,19,19,20,21,21,-1,-1,17,7,15,6,14,4,14,2,16,0,18,0,20,1,21,3,21,5,19,7,17,7]],"&":[26,[23,12,23,13,22,14,21,14,20,13,19,11,17,6,15,3,13,1,11,0,7,0,5,1,4,2,3,4,3,6,4,8,5,9,12,13,13,14,14,16,14,18,13,20,11,21,9,20,8,18,8,16,9,13,11,10,16,3,18,1,20,0,22,0,23,1,23,2]],"'":[10,[5,19,4,20,5,21,6,20,6,18,5,16,4,15]],"(":[14,[11,25,9,23,7,20,5,16,4,11,4,7,5,2,7,-2,9,-5,11,-7]],")":[14,[3,25,5,23,7,20,9,16,10,11,10,7,9,2,7,-2,5,-5,3,-7]],"*":[16,[8,21,8,9,-1,-1,3,18,13,12,-1,-1,13,18,3,12]],"+":[26,[13,18,13,0,-1,-1,4,9,22,9]],",":[10,[6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4]],"-":[26,[4,9,22,9]],".":[10,[5,2,4,1,5,0,6,1,5,2]],"/":[22,[20,25,2,-7]],0:[20,[9,21,6,20,4,17,3,12,3,9,4,4,6,1,9,0,11,0,14,1,16,4,17,9,17,12,16,17,14,20,11,21,9,21]],1:[20,[6,17,8,18,11,21,11,0]],2:[20,[4,16,4,17,5,19,6,20,8,21,12,21,14,20,15,19,16,17,16,15,15,13,13,10,3,0,17,0]],3:[20,[5,21,16,21,10,13,13,13,15,12,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4]],4:[20,[13,21,3,7,18,7,-1,-1,13,21,13,0]],5:[20,[15,21,5,21,4,12,5,13,8,14,11,14,14,13,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4]],6:[20,[16,18,15,20,12,21,10,21,7,20,5,17,4,12,4,7,5,3,7,1,10,0,11,0,14,1,16,3,17,6,17,7,16,10,14,12,11,13,10,13,7,12,5,10,4,7]],7:[20,[17,21,7,0,-1,-1,3,21,17,21]],8:[20,[8,21,5,20,4,18,4,16,5,14,7,13,11,12,14,11,16,9,17,7,17,4,16,2,15,1,12,0,8,0,5,1,4,2,3,4,3,7,4,9,6,11,9,12,13,13,15,14,16,16,16,18,15,20,12,21,8,21]],9:[20,[16,14,15,11,13,9,10,8,9,8,6,9,4,11,3,14,3,15,4,18,6,20,9,21,10,21,13,20,15,18,16,14,16,9,15,4,13,1,10,0,8,0,5,1,4,3]],":":[10,[5,14,4,13,5,12,6,13,5,14,-1,-1,5,2,4,1,5,0,6,1,5,2]],";":[10,[5,14,4,13,5,12,6,13,5,14,-1,-1,6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4]],"<":[24,[20,18,4,9,20,0]],"=":[26,[4,12,22,12,-1,-1,4,6,22,6]],">":[24,[4,18,20,9,4,0]],"?":[18,[3,16,3,17,4,19,5,20,7,21,11,21,13,20,14,19,15,17,15,15,14,13,13,12,9,10,9,7,-1,-1,9,2,8,1,9,0,10,1,9,2]],"@":[27,[18,13,17,15,15,16,12,16,10,15,9,14,8,11,8,8,9,6,11,5,14,5,16,6,17,8,-1,-1,12,16,10,14,9,11,9,8,10,6,11,5,-1,-1,18,16,17,8,17,6,19,5,21,5,23,7,24,10,24,12,23,15,22,17,20,19,18,20,15,21,12,21,9,20,7,19,5,17,4,15,3,12,3,9,4,6,5,4,7,2,9,1,12,0,15,0,18,1,20,2,21,3,-1,-1,19,16,18,8,18,6,19,5]],A:[18,[9,21,1,0,-1,-1,9,21,17,0,-1,-1,4,7,14,7]],B:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,-1,-1,4,11,13,11,16,10,17,9,18,7,18,4,17,2,16,1,13,0,4,0]],C:[21,[18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5]],D:[21,[4,21,4,0,-1,-1,4,21,11,21,14,20,16,18,17,16,18,13,18,8,17,5,16,3,14,1,11,0,4,0]],E:[19,[4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11,-1,-1,4,0,17,0]],F:[18,[4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11]],G:[21,[18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,18,8,-1,-1,13,8,18,8]],H:[22,[4,21,4,0,-1,-1,18,21,18,0,-1,-1,4,11,18,11]],I:[8,[4,21,4,0]],J:[16,[12,21,12,5,11,2,10,1,8,0,6,0,4,1,3,2,2,5,2,7]],K:[21,[4,21,4,0,-1,-1,18,21,4,7,-1,-1,9,12,18,0]],L:[17,[4,21,4,0,-1,-1,4,0,16,0]],M:[24,[4,21,4,0,-1,-1,4,21,12,0,-1,-1,20,21,12,0,-1,-1,20,21,20,0]],N:[22,[4,21,4,0,-1,-1,4,21,18,0,-1,-1,18,21,18,0]],O:[22,[9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21]],P:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,14,17,12,16,11,13,10,4,10]],Q:[22,[9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,-1,-1,12,4,18,-2]],R:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,4,11,-1,-1,11,11,18,0]],S:[20,[17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3]],T:[16,[8,21,8,0,-1,-1,1,21,15,21]],U:[22,[4,21,4,6,5,3,7,1,10,0,12,0,15,1,17,3,18,6,18,21]],V:[18,[1,21,9,0,-1,-1,17,21,9,0]],W:[24,[2,21,7,0,-1,-1,12,21,7,0,-1,-1,12,21,17,0,-1,-1,22,21,17,0]],X:[20,[3,21,17,0,-1,-1,17,21,3,0]],Y:[18,[1,21,9,11,9,0,-1,-1,17,21,9,11]],Z:[20,[17,21,3,0,-1,-1,3,21,17,21,-1,-1,3,0,17,0]],"[":[14,[4,25,4,-7,-1,-1,5,25,5,-7,-1,-1,4,25,11,25,-1,-1,4,-7,11,-7]],"\\":[14,[0,21,14,-3]],"]":[14,[9,25,9,-7,-1,-1,10,25,10,-7,-1,-1,3,25,10,25,-1,-1,3,-7,10,-7]],"^":[16,[6,15,8,18,10,15,-1,-1,3,12,8,17,13,12,-1,-1,8,17,8,0]],_:[16,[0,-2,16,-2]],"`":[10,[6,21,5,20,4,18,4,16,5,15,6,16,5,17]],a:[19,[15,14,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],b:[19,[4,21,4,0,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3]],c:[18,[15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],d:[19,[15,21,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],e:[18,[3,8,15,8,15,10,14,12,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],f:[12,[10,21,8,21,6,20,5,17,5,0,-1,-1,2,14,9,14]],g:[19,[15,14,15,-2,14,-5,13,-6,11,-7,8,-7,6,-6,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],h:[19,[4,21,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0]],i:[8,[3,21,4,20,5,21,4,22,3,21,-1,-1,4,14,4,0]],j:[10,[5,21,6,20,7,21,6,22,5,21,-1,-1,6,14,6,-3,5,-6,3,-7,1,-7]],k:[17,[4,21,4,0,-1,-1,14,14,4,4,-1,-1,8,8,15,0]],l:[8,[4,21,4,0]],m:[30,[4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,15,10,18,13,20,14,23,14,25,13,26,10,26,0]],n:[19,[4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0]],o:[19,[8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,16,6,16,8,15,11,13,13,11,14,8,14]],p:[19,[4,14,4,-7,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3]],q:[19,[15,14,15,-7,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],r:[13,[4,14,4,0,-1,-1,4,8,5,11,7,13,9,14,12,14]],s:[17,[14,11,13,13,10,14,7,14,4,13,3,11,4,9,6,8,11,7,13,6,14,4,14,3,13,1,10,0,7,0,4,1,3,3]],t:[12,[5,21,5,4,6,1,8,0,10,0,-1,-1,2,14,9,14]],u:[19,[4,14,4,4,5,1,7,0,10,0,12,1,15,4,-1,-1,15,14,15,0]],v:[16,[2,14,8,0,-1,-1,14,14,8,0]],w:[22,[3,14,7,0,-1,-1,11,14,7,0,-1,-1,11,14,15,0,-1,-1,19,14,15,0]],x:[17,[3,14,14,0,-1,-1,14,14,3,0]],y:[16,[2,14,8,0,-1,-1,14,14,8,0,6,-4,4,-6,2,-7,1,-7]],z:[17,[14,14,3,0,-1,-1,3,14,14,14,-1,-1,3,0,14,0]],"{":[14,[9,25,7,24,6,23,5,21,5,19,6,17,7,16,8,14,8,12,6,10,-1,-1,7,24,6,22,6,20,7,18,8,17,9,15,9,13,8,11,4,9,8,7,9,5,9,3,8,1,7,0,6,-2,6,-4,7,-6,-1,-1,6,8,8,6,8,4,7,2,6,1,5,-1,5,-3,6,-5,7,-6,9,-7]],"|":[8,[4,25,4,-7]],"}":[14,[5,25,7,24,8,23,9,21,9,19,8,17,7,16,6,14,6,12,8,10,-1,-1,7,24,8,22,8,20,7,18,6,17,5,15,5,13,6,11,10,9,6,7,5,5,5,3,6,1,7,0,8,-2,8,-4,7,-6,-1,-1,8,8,6,6,6,4,7,2,8,1,9,-1,9,-3,8,-5,7,-6,5,-7]],"~":[24,[3,6,3,8,4,11,6,12,8,12,10,11,14,8,16,7,18,7,20,8,21,10,-1,-1,3,8,4,10,6,11,8,11,10,10,14,7,16,6,18,6,20,7,21,10,21,12]]};var Mi={symbol:function(t,e,i,n){if("translucent"===t.renderPass){var o=t.context;o.setStencilMode(Gt.disabled),o.setColorMode(t.colorModeForRenderPass()),0!==i.paint.get("icon-opacity").constantOr(1)&&hi(t,e,i,n,!1,i.paint.get("icon-translate"),i.paint.get("icon-translate-anchor"),i.layout.get("icon-rotation-alignment"),i.layout.get("icon-pitch-alignment"),i.layout.get("icon-keep-upright")),0!==i.paint.get("text-opacity").constantOr(1)&&hi(t,e,i,n,!0,i.paint.get("text-translate"),i.paint.get("text-translate-anchor"),i.layout.get("text-rotation-alignment"),i.layout.get("text-pitch-alignment"),i.layout.get("text-keep-upright")),e.map.showCollisionBoxes&&function(t,e,i,n){li(t,e,i,n,!1),li(t,e,i,n,!0);}(t,e,i,n);}},circle:function(t,e,i,n){if("translucent"===t.renderPass){var o=i.paint.get("circle-opacity"),r=i.paint.get("circle-stroke-width"),a=i.paint.get("circle-stroke-opacity");if(0!==o.constantOr(1)||0!==r.constantOr(1)&&0!==a.constantOr(1)){var s=t.context,l=s.gl;s.setDepthMode(t.depthModeForSublayer(0,$t.ReadOnly)),s.setStencilMode(Gt.disabled),s.setColorMode(t.colorModeForRenderPass());for(var c=!0,u=0;u<n.length;u++){var h=n[u],p=e.getTile(h),d=p.getBucket(i);if(d){var f=t.context.program.get(),m=d.programConfigurations.get(i.id),_=t.useProgram("circle",m);if((c||_.program!==f)&&(m.setUniforms(s,_,i.paint,{zoom:t.transform.zoom}),c=!1),l.uniform1f(_.uniforms.u_camera_to_center_distance,t.transform.cameraToCenterDistance),l.uniform1i(_.uniforms.u_scale_with_map,"map"===i.paint.get("circle-pitch-scale")?1:0),"map"===i.paint.get("circle-pitch-alignment")){l.uniform1i(_.uniforms.u_pitch_with_map,1);var g=ze(p,1,t.transform.zoom);l.uniform2f(_.uniforms.u_extrude_scale,g,g);}else l.uniform1i(_.uniforms.u_pitch_with_map,0),l.uniform2fv(_.uniforms.u_extrude_scale,t.transform.pixelsToGLUnits);l.uniformMatrix4fv(_.uniforms.u_matrix,!1,t.translatePosMatrix(h.posMatrix,p,i.paint.get("circle-translate"),i.paint.get("circle-translate-anchor"))),_.draw(s,l.TRIANGLES,i.id,d.layoutVertexBuffer,d.indexBuffer,d.segments,m);}}}}},heatmap:function(e,i,n,o){if(0!==n.paint.get("heatmap-opacity"))if("offscreen"===e.renderPass){var r=e.context,a=r.gl;r.setDepthMode(e.depthModeForSublayer(0,$t.ReadOnly)),r.setStencilMode(Gt.disabled),function(t,e,i){var n=t.gl;t.activeTexture.set(n.TEXTURE1),t.viewport.set([0,0,e.width/4,e.height/4]);var o=i.heatmapFbo;if(o)n.bindTexture(n.TEXTURE_2D,o.colorAttachment.get()),t.bindFramebuffer.set(o.framebuffer);else{var r=n.createTexture();n.bindTexture(n.TEXTURE_2D,r),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),o=i.heatmapFbo=t.createFramebuffer(e.width/4,e.height/4),function t(e,i,n,o){var r=e.gl;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,i.width/4,i.height/4,0,r.RGBA,e.extTextureHalfFloat?e.extTextureHalfFloat.HALF_FLOAT_OES:r.UNSIGNED_BYTE,null),o.colorAttachment.set(n),e.extTextureHalfFloat&&r.checkFramebufferStatus(r.FRAMEBUFFER)!==r.FRAMEBUFFER_COMPLETE&&(e.extTextureHalfFloat=null,o.colorAttachment.setDirty(),t(e,i,n,o));}(t,e,r,o);}}(r,e,n),r.clear({color:t.default$6.transparent}),r.setColorMode(new Wt([a.ONE,a.ONE],t.default$6.transparent,[!0,!0,!0,!0]));for(var s=!0,l=0;l<o.length;l++){var c=o[l];if(!i.hasRenderableParent(c)){var u=i.getTile(c),h=u.getBucket(n);if(h){var p=e.context.program.get(),d=h.programConfigurations.get(n.id),f=e.useProgram("heatmap",d),m=e.transform.zoom;(s||f.program!==p)&&(d.setUniforms(e.context,f,n.paint,{zoom:m}),s=!1),a.uniform1f(f.uniforms.u_extrude_scale,ze(u,1,m)),a.uniform1f(f.uniforms.u_intensity,n.paint.get("heatmap-intensity")),a.uniformMatrix4fv(f.uniforms.u_matrix,!1,c.posMatrix),f.draw(r,a.TRIANGLES,n.id,h.layoutVertexBuffer,h.indexBuffer,h.segments,d);}}}r.viewport.set([0,0,e.width,e.height]);}else"translucent"===e.renderPass&&(e.context.setColorMode(e.colorModeForRenderPass()),function(e,i){var n=e.context,o=n.gl,r=i.heatmapFbo;if(r){n.activeTexture.set(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,r.colorAttachment.get()),n.activeTexture.set(o.TEXTURE1);var a=i.colorRampTexture;a||(a=i.colorRampTexture=new M(n,i.colorRamp,o.RGBA)),a.bind(o.LINEAR,o.CLAMP_TO_EDGE),n.setDepthMode($t.disabled);var s=e.useProgram("heatmapTexture"),l=i.paint.get("heatmap-opacity");o.uniform1f(s.uniforms.u_opacity,l),o.uniform1i(s.uniforms.u_image,0),o.uniform1i(s.uniforms.u_color_ramp,1);var c=t.mat4.create();t.mat4.ortho(c,0,e.width,e.height,0,0,1),o.uniformMatrix4fv(s.uniforms.u_matrix,!1,c),o.uniform2f(s.uniforms.u_world,o.drawingBufferWidth,o.drawingBufferHeight),e.viewportVAO.bind(e.context,s,e.viewportBuffer,[]),o.drawArrays(o.TRIANGLE_STRIP,0,4);}}(e,n));},line:function(t,e,i,n){if("translucent"===t.renderPass&&0!==i.paint.get("line-opacity").constantOr(1)){var o=t.context;o.setDepthMode(t.depthModeForSublayer(0,$t.ReadOnly)),o.setColorMode(t.colorModeForRenderPass());for(var r,a=i.paint.get("line-dasharray")?"lineSDF":i.paint.get("line-pattern")?"linePattern":i.paint.get("line-gradient")?"lineGradient":"line",s=!0,l=0,c=n;l<c.length;l+=1){var u=c[l],h=e.getTile(u),p=h.getBucket(i);if(p){var d=p.programConfigurations.get(i.id),f=t.context.program.get(),m=t.useProgram(a,d),_=s||m.program!==f,g=r!==h.tileID.overscaledZ;_&&d.setUniforms(t.context,m,i.paint,{zoom:t.transform.zoom}),mi(m,t,h,p,i,u,d,_,g),r=h.tileID.overscaledZ,s=!1;}}}},fill:function(e,i,n,o){var r=n.paint.get("fill-color"),a=n.paint.get("fill-opacity");if(0!==a.constantOr(1)){var s=e.context;s.setColorMode(e.colorModeForRenderPass());var l=n.paint.get("fill-pattern")||1!==r.constantOr(t.default$6.transparent).a||1!==a.constantOr(0)?"translucent":"opaque";e.renderPass===l&&(s.setDepthMode(e.depthModeForSublayer(1,"opaque"===e.renderPass?$t.ReadWrite:$t.ReadOnly)),yi(e,i,n,o,xi)),"translucent"===e.renderPass&&n.paint.get("fill-antialias")&&(s.lineWidth.set(2),s.setDepthMode(e.depthModeForSublayer(n.getPaintProperty("fill-outline-color")?2:0,$t.ReadOnly)),yi(e,i,n,o,bi));}},"fill-extrusion":function(e,i,n,o){if(0!==n.paint.get("fill-extrusion-opacity"))if("offscreen"===e.renderPass){!function(e,i){var n=e.context,o=n.gl,r=i.viewportFrame;if(e.depthRboNeedsClear&&e.setupOffscreenDepthRenderbuffer(),!r){var a=new M(n,{width:e.width,height:e.height,data:null},o.RGBA);a.bind(o.LINEAR,o.CLAMP_TO_EDGE),(r=i.viewportFrame=n.createFramebuffer(e.width,e.height)).colorAttachment.set(a.texture);}n.bindFramebuffer.set(r.framebuffer),r.depthAttachment.set(e.depthRbo),e.depthRboNeedsClear&&(n.clear({depth:1}),e.depthRboNeedsClear=!1),n.clear({color:t.default$6.transparent}),n.setStencilMode(Gt.disabled),n.setDepthMode(new $t(o.LEQUAL,$t.ReadWrite,[0,1])),n.setColorMode(e.colorModeForRenderPass());}(e,n);for(var r=!0,a=0,s=o;a<s.length;a+=1){var l=s[a],c=i.getTile(l),u=c.getBucket(n);u&&(Ci(e,0,n,c,l,u,r),r=!1);}}else"translucent"===e.renderPass&&function(t,e){var i=e.viewportFrame;if(i){var n=t.context,o=n.gl,r=t.useProgram("extrusionTexture");n.setStencilMode(Gt.disabled),n.setDepthMode($t.disabled),n.setColorMode(t.colorModeForRenderPass()),n.activeTexture.set(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,i.colorAttachment.get()),o.uniform1f(r.uniforms.u_opacity,e.paint.get("fill-extrusion-opacity")),o.uniform1i(r.uniforms.u_image,0);var a=Ti.create();Ti.ortho(a,0,t.width,t.height,0,0,1),o.uniformMatrix4fv(r.uniforms.u_matrix,!1,a),o.uniform2f(r.uniforms.u_world,o.drawingBufferWidth,o.drawingBufferHeight),t.viewportVAO.bind(n,r,t.viewportBuffer,[]),o.drawArrays(o.TRIANGLE_STRIP,0,4);}}(e,n);},hillshade:function(t,e,i,n){if("offscreen"===t.renderPass||"translucent"===t.renderPass){var o=t.context,r=e.getSource().maxzoom;o.setDepthMode(t.depthModeForSublayer(0,$t.ReadOnly)),o.setStencilMode(Gt.disabled),o.setColorMode(t.colorModeForRenderPass());for(var a=0,s=n;a<s.length;a+=1){var l=s[a],c=e.getTile(l);c.needsHillshadePrepare&&"offscreen"===t.renderPass?zi(t,c,r):"translucent"===t.renderPass&&Si(t,c,i);}o.viewport.set([0,0,t.width,t.height]);}},raster:function(t,e,i,n){if("translucent"===t.renderPass&&0!==i.paint.get("raster-opacity")){var o,r,a=t.context,s=a.gl,l=e.getSource(),c=t.useProgram("raster");a.setStencilMode(Gt.disabled),a.setColorMode(t.colorModeForRenderPass()),s.uniform1f(c.uniforms.u_brightness_low,i.paint.get("raster-brightness-min")),s.uniform1f(c.uniforms.u_brightness_high,i.paint.get("raster-brightness-max")),s.uniform1f(c.uniforms.u_saturation_factor,(o=i.paint.get("raster-saturation"))>0?1-1/(1.001-o):-o),s.uniform1f(c.uniforms.u_contrast_factor,(r=i.paint.get("raster-contrast"))>0?1/(1-r):1+r),s.uniform3fv(c.uniforms.u_spin_weights,function(t){t*=Math.PI/180;var e=Math.sin(t),i=Math.cos(t);return[(2*i+1)/3,(-Math.sqrt(3)*e-i+1)/3,(Math.sqrt(3)*e-i+1)/3]}(i.paint.get("raster-hue-rotate"))),s.uniform1f(c.uniforms.u_buffer_scale,1),s.uniform1i(c.uniforms.u_image0,0),s.uniform1i(c.uniforms.u_image1,1);for(var u=n.length&&n[0].overscaledZ,h=0,p=n;h<p.length;h+=1){var d=p[h];a.setDepthMode(t.depthModeForSublayer(d.overscaledZ-u,1===i.paint.get("raster-opacity")?$t.ReadWrite:$t.ReadOnly,s.LESS));var f=e.getTile(d),m=t.transform.calculatePosMatrix(d.toUnwrapped(),!0);f.registerFadeDuration(i.paint.get("raster-fade-duration")),s.uniformMatrix4fv(c.uniforms.u_matrix,!1,m);var _=e.findLoadedParent(d,0,{}),g=Ai(f,_,e,i,t.transform),v=void 0,y=void 0;if(a.activeTexture.set(s.TEXTURE0),f.texture.bind(s.LINEAR,s.CLAMP_TO_EDGE,s.LINEAR_MIPMAP_NEAREST),a.activeTexture.set(s.TEXTURE1),_?(_.texture.bind(s.LINEAR,s.CLAMP_TO_EDGE,s.LINEAR_MIPMAP_NEAREST),v=Math.pow(2,_.tileID.overscaledZ-f.tileID.overscaledZ),y=[f.tileID.canonical.x*v%1,f.tileID.canonical.y*v%1]):f.texture.bind(s.LINEAR,s.CLAMP_TO_EDGE,s.LINEAR_MIPMAP_NEAREST),s.uniform2fv(c.uniforms.u_tl_parent,y||[0,0]),s.uniform1f(c.uniforms.u_scale_parent,v||1),s.uniform1f(c.uniforms.u_fade_t,g.mix),s.uniform1f(c.uniforms.u_opacity,g.opacity*i.paint.get("raster-opacity")),l instanceof et){var x=l.boundsBuffer;l.boundsVAO.bind(a,c,x,[]),s.drawArrays(s.TRIANGLE_STRIP,0,x.length);}else if(f.maskedBoundsBuffer&&f.maskedIndexBuffer&&f.segments)c.draw(a,s.TRIANGLES,i.id,f.maskedBoundsBuffer,f.maskedIndexBuffer,f.segments);else{var b=t.rasterBoundsBuffer;t.rasterBoundsVAO.bind(a,c,b,[]),s.drawArrays(s.TRIANGLE_STRIP,0,b.length);}}}},background:function(t,e,i){var n=i.paint.get("background-color"),o=i.paint.get("background-opacity");if(0!==o){var r=t.context,a=r.gl,s=t.transform,l=s.tileSize,c=i.paint.get("background-pattern"),u=c||1!==n.a||1!==o?"translucent":"opaque";if(t.renderPass===u){var h;if(r.setStencilMode(Gt.disabled),r.setDepthMode(t.depthModeForSublayer(0,"opaque"===u?$t.ReadWrite:$t.ReadOnly)),r.setColorMode(t.colorModeForRenderPass()),c){if(_i(c,t))return;h=t.useProgram("backgroundPattern"),gi(c,t,h),t.tileExtentPatternVAO.bind(r,h,t.tileExtentBuffer,[]);}else h=t.useProgram("background"),a.uniform4fv(h.uniforms.u_color,[n.r,n.g,n.b,n.a]),t.tileExtentVAO.bind(r,h,t.tileExtentBuffer,[]);a.uniform1f(h.uniforms.u_opacity,o);for(var p=0,d=s.coveringTiles({tileSize:l});p<d.length;p+=1){var f=d[p];c&&vi({tileID:f,tileSize:l},t,h),a.uniformMatrix4fv(h.uniforms.u_matrix,!1,t.transform.calculatePosMatrix(f.toUnwrapped())),a.drawArrays(a.TRIANGLE_STRIP,0,t.tileExtentBuffer.length);}}}},debug:function(t,e,i){for(var n=0;n<i.length;n++)Ri(t,e,i[n]);}},Li=function(e,i){this.context=new qt(e),this.transform=i,this._tileTextures={},this.setup(),this.numSublayers=Xt.maxUnderzooming+Xt.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.depthRboNeedsClear=!0,this.emptyProgramConfiguration=new t.default$24,this.crossTileSymbolIndex=new He;};function Pi(t,e){if(t.row>e.row){var i=t;t=e,e=i;}return{x0:t.column,y0:t.row,x1:e.column,y1:e.row,dx:e.column-t.column,dy:e.row-t.row}}function ki(t,e,i,n,o){var r=Math.max(i,Math.floor(e.y0)),a=Math.min(n,Math.ceil(e.y1));if(t.x0===e.x0&&t.y0===e.y0?t.x0+e.dy/t.dy*t.dx<e.x1:t.x1-e.dy/t.dy*t.dx<e.x0){var s=t;t=e,e=s;}for(var l=t.dx/t.dy,c=e.dx/e.dy,u=t.dx>0,h=e.dx<0,p=r;p<a;p++){var d=l*Math.max(0,Math.min(t.dy,p+u-t.y0))+t.x0,f=c*Math.max(0,Math.min(e.dy,p+h-e.y0))+e.x0;o(Math.floor(f),Math.ceil(d),p);}}function Bi(t,e,i,n,o,r){var a,s=Pi(t,e),l=Pi(e,i),c=Pi(i,t);s.dy>l.dy&&(a=s,s=l,l=a),s.dy>c.dy&&(a=s,s=c,c=a),l.dy>c.dy&&(a=l,l=c,c=a),s.dy&&ki(c,s,n,o,r),l.dy&&ki(c,l,n,o,r);}Li.prototype.resize=function(t,e){var i=this.context.gl;if(this.width=t*r.devicePixelRatio,this.height=e*r.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(var n=0,o=this.style._order;n<o.length;n+=1){var a=o[n];this.style._layers[a].resize();}this.depthRbo&&(i.deleteRenderbuffer(this.depthRbo),this.depthRbo=null);},Li.prototype.setup=function(){var e=this.context,i=new t.PosArray;i.emplaceBack(0,0),i.emplaceBack(t.default$8,0),i.emplaceBack(0,t.default$8),i.emplaceBack(t.default$8,t.default$8),this.tileExtentBuffer=e.createVertexBuffer(i,ti.members),this.tileExtentVAO=new tt,this.tileExtentPatternVAO=new tt;var n=new t.PosArray;n.emplaceBack(0,0),n.emplaceBack(t.default$8,0),n.emplaceBack(t.default$8,t.default$8),n.emplaceBack(0,t.default$8),n.emplaceBack(0,0),this.debugBuffer=e.createVertexBuffer(n,ti.members),this.debugVAO=new tt;var o=new t.RasterBoundsArray;o.emplaceBack(0,0,0,0),o.emplaceBack(t.default$8,0,t.default$8,0),o.emplaceBack(0,t.default$8,0,t.default$8),o.emplaceBack(t.default$8,t.default$8,t.default$8,t.default$8),this.rasterBoundsBuffer=e.createVertexBuffer(o,Q.members),this.rasterBoundsVAO=new tt;var r=new t.PosArray;r.emplaceBack(0,0),r.emplaceBack(1,0),r.emplaceBack(0,1),r.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(r,ti.members),this.viewportVAO=new tt;},Li.prototype.clearStencil=function(){var e=this.context,i=e.gl;e.setColorMode(Wt.disabled),e.setDepthMode($t.disabled),e.setStencilMode(new Gt({func:i.ALWAYS,mask:0},0,255,i.ZERO,i.ZERO,i.ZERO));var n=t.mat4.create();t.mat4.ortho(n,0,this.width,this.height,0,0,1),t.mat4.scale(n,n,[i.drawingBufferWidth,i.drawingBufferHeight,0]);var o=this.useProgram("clippingMask");i.uniformMatrix4fv(o.uniforms.u_matrix,!1,n),this.viewportVAO.bind(e,o,this.viewportBuffer,[]),i.drawArrays(i.TRIANGLE_STRIP,0,4);},Li.prototype._renderTileClippingMasks=function(t){var e=this.context,i=e.gl;e.setColorMode(Wt.disabled),e.setDepthMode($t.disabled);var n=1;this._tileClippingMaskIDs={};for(var o=0,r=t;o<r.length;o+=1){var a=r[o],s=this._tileClippingMaskIDs[a.key]=n++;e.setStencilMode(new Gt({func:i.ALWAYS,mask:0},s,255,i.KEEP,i.KEEP,i.REPLACE));var l=this.useProgram("clippingMask");i.uniformMatrix4fv(l.uniforms.u_matrix,!1,a.posMatrix),this.tileExtentVAO.bind(this.context,l,this.tileExtentBuffer,[]),i.drawArrays(i.TRIANGLE_STRIP,0,this.tileExtentBuffer.length);}},Li.prototype.stencilModeForClipping=function(t){var e=this.context.gl;return new Gt({func:e.EQUAL,mask:255},this._tileClippingMaskIDs[t.key],0,e.KEEP,e.KEEP,e.REPLACE)},Li.prototype.colorModeForRenderPass=function(){var e=this.context.gl;if(this._showOverdrawInspector){return new Wt([e.CONSTANT_COLOR,e.ONE],new t.default$6(1/8,1/8,1/8,0),[!0,!0,!0,!0])}return"opaque"===this.renderPass?Wt.unblended:Wt.alphaBlended},Li.prototype.depthModeForSublayer=function(t,e,i){var n=1-((1+this.currentLayer)*this.numSublayers+t)*this.depthEpsilon,o=n-1+this.depthRange;return new $t(i||this.context.gl.LEQUAL,e,[o,n])},Li.prototype.render=function(e,i){var n=this;for(var o in this.style=e,this.options=i,this.lineAtlas=e.lineAtlas,this.imageManager=e.imageManager,this.glyphManager=e.glyphManager,this.symbolFadeChange=e.placement.symbolFadeChange(r.now()),e.sourceCaches){var a=n.style.sourceCaches[o];a.used&&a.prepare(n.context);}var s=this.style._order,l=t.filterObject(this.style.sourceCaches,function(t){return"raster"===t.getSource().type||"raster-dem"===t.getSource().type}),c=function(e){var i=l[e];!function(e,i){for(var n=e.sort(function(t,e){return t.tileID.isLessThan(e.tileID)?-1:e.tileID.isLessThan(t.tileID)?1:0}),o=0;o<n.length;o++){var r={},a=n[o],s=n.slice(o+1);si(a.tileID.wrapped(),a.tileID,s,new t.OverscaledTileID(0,a.tileID.wrap+1,0,0,0),r),a.setMask(r,i);}}(i.getVisibleCoordinates().map(function(t){return i.getTile(t)}),n.context);};for(var u in l)c(u);this.renderPass="offscreen";var h,p=[];this.depthRboNeedsClear=!0;for(var d=0;d<s.length;d++){var f=n.style._layers[s[d]];f.hasOffscreenPass()&&!f.isHidden(n.transform.zoom)&&(f.source!==(h&&h.id)&&(p=[],(h=n.style.sourceCaches[f.source])&&(p=h.getVisibleCoordinates()).reverse()),p.length&&n.renderLayer(n,h,f,p));}this.context.bindFramebuffer.set(null),this.context.clear({color:i.showOverdrawInspector?t.default$6.black:t.default$6.transparent,depth:1}),this._showOverdrawInspector=i.showOverdrawInspector,this.depthRange=(e._order.length+2)*this.numSublayers*this.depthEpsilon,this.renderPass="opaque";var m,_=[];for(this.currentLayer=s.length-1,this.currentLayer;this.currentLayer>=0;this.currentLayer--){var g=n.style._layers[s[n.currentLayer]];g.source!==(m&&m.id)&&(_=[],(m=n.style.sourceCaches[g.source])&&(n.clearStencil(),_=m.getVisibleCoordinates(),m.getSource().isTileClipped&&n._renderTileClippingMasks(_))),n.renderLayer(n,m,g,_);}this.renderPass="translucent";var v,y=[];for(this.currentLayer=0,this.currentLayer;this.currentLayer<s.length;this.currentLayer++){var x=n.style._layers[s[n.currentLayer]];x.source!==(v&&v.id)&&(y=[],(v=n.style.sourceCaches[x.source])&&(n.clearStencil(),y=v.getVisibleCoordinates(),v.getSource().isTileClipped&&n._renderTileClippingMasks(y)),y.reverse()),n.renderLayer(n,v,x,y);}if(this.options.showTileBoundaries){var b=this.style.sourceCaches[Object.keys(this.style.sourceCaches)[0]];b&&Mi.debug(this,b,b.getVisibleCoordinates());}},Li.prototype.setupOffscreenDepthRenderbuffer=function(){var t=this.context;this.depthRbo||(this.depthRbo=t.createRenderbuffer(t.gl.DEPTH_COMPONENT16,this.width,this.height));},Li.prototype.renderLayer=function(t,e,i,n){i.isHidden(this.transform.zoom)||("background"===i.type||n.length)&&(this.id=i.id,Mi[i.type](t,e,i,n));},Li.prototype.translatePosMatrix=function(e,i,n,o,r){if(!n[0]&&!n[1])return e;var a=r?"map"===o?this.transform.angle:0:"viewport"===o?-this.transform.angle:0;if(a){var s=Math.sin(a),l=Math.cos(a);n=[n[0]*l-n[1]*s,n[0]*s+n[1]*l];}var c=[r?n[0]:ze(i,n[0],this.transform.zoom),r?n[1]:ze(i,n[1],this.transform.zoom),0],u=new Float32Array(16);return t.mat4.translate(u,e,c),u},Li.prototype.saveTileTexture=function(t){var e=this._tileTextures[t.size[0]];e?e.push(t):this._tileTextures[t.size[0]]=[t];},Li.prototype.getTileTexture=function(t){var e=this._tileTextures[t];return e&&e.length>0?e.pop():null},Li.prototype._createProgramCached=function(t,e){this.cache=this.cache||{};var i=""+t+(e.cacheKey||"")+(this._showOverdrawInspector?"/overdraw":"");return this.cache[i]||(this.cache[i]=new ai(this.context,ri[t],e,this._showOverdrawInspector)),this.cache[i]},Li.prototype.useProgram=function(t,e){var i=this._createProgramCached(t,e||this.emptyProgramConfiguration);return this.context.program.set(i.program),i};var Oi=t.default$20.vec4,Fi=t.default$20.mat4,Ni=t.default$20.mat2,Ui=function(t,e,i){this.tileSize=512,this._renderWorldCopies=void 0===i||i,this._minZoom=t||0,this._maxZoom=e||22,this.latRange=[-85.05113,85.05113],this.width=0,this.height=0,this._center=new W(0,0),this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._unmodified=!0,this._posMatrixCache={},this._alignedPosMatrixCache={};},Zi={minZoom:{configurable:!0},maxZoom:{configurable:!0},renderWorldCopies:{configurable:!0},worldSize:{configurable:!0},centerPoint:{configurable:!0},size:{configurable:!0},bearing:{configurable:!0},pitch:{configurable:!0},fov:{configurable:!0},zoom:{configurable:!0},center:{configurable:!0},unmodified:{configurable:!0},x:{configurable:!0},y:{configurable:!0},point:{configurable:!0}};Ui.prototype.clone=function(){var t=new Ui(this._minZoom,this._maxZoom,this._renderWorldCopies);return t.tileSize=this.tileSize,t.latRange=this.latRange,t.width=this.width,t.height=this.height,t._center=this._center,t.zoom=this.zoom,t.angle=this.angle,t._fov=this._fov,t._pitch=this._pitch,t._unmodified=this._unmodified,t._calcMatrices(),t},Zi.minZoom.get=function(){return this._minZoom},Zi.minZoom.set=function(t){this._minZoom!==t&&(this._minZoom=t,this.zoom=Math.max(this.zoom,t));},Zi.maxZoom.get=function(){return this._maxZoom},Zi.maxZoom.set=function(t){this._maxZoom!==t&&(this._maxZoom=t,this.zoom=Math.min(this.zoom,t));},Zi.renderWorldCopies.get=function(){return this._renderWorldCopies},Zi.renderWorldCopies.set=function(t){void 0===t?t=!0:null===t&&(t=!1),this._renderWorldCopies=t;},Zi.worldSize.get=function(){return this.tileSize*this.scale},Zi.centerPoint.get=function(){return this.size._div(2)},Zi.size.get=function(){return new t.default$1(this.width,this.height)},Zi.bearing.get=function(){return-this.angle/Math.PI*180},Zi.bearing.set=function(e){var i=-t.wrap(e,-180,180)*Math.PI/180;this.angle!==i&&(this._unmodified=!1,this.angle=i,this._calcMatrices(),this.rotationMatrix=Ni.create(),Ni.rotate(this.rotationMatrix,this.rotationMatrix,this.angle));},Zi.pitch.get=function(){return this._pitch/Math.PI*180},Zi.pitch.set=function(e){var i=t.clamp(e,0,60)/180*Math.PI;this._pitch!==i&&(this._unmodified=!1,this._pitch=i,this._calcMatrices());},Zi.fov.get=function(){return this._fov/Math.PI*180},Zi.fov.set=function(t){t=Math.max(.01,Math.min(60,t)),this._fov!==t&&(this._unmodified=!1,this._fov=t/180*Math.PI,this._calcMatrices());},Zi.zoom.get=function(){return this._zoom},Zi.zoom.set=function(t){var e=Math.min(Math.max(t,this.minZoom),this.maxZoom);this._zoom!==e&&(this._unmodified=!1,this._zoom=e,this.scale=this.zoomScale(e),this.tileZoom=Math.floor(e),this.zoomFraction=e-this.tileZoom,this._constrain(),this._calcMatrices());},Zi.center.get=function(){return this._center},Zi.center.set=function(t){t.lat===this._center.lat&&t.lng===this._center.lng||(this._unmodified=!1,this._center=t,this._constrain(),this._calcMatrices());},Ui.prototype.coveringZoomLevel=function(t){return(t.roundZoom?Math.round:Math.floor)(this.zoom+this.scaleZoom(this.tileSize/t.tileSize))},Ui.prototype.getVisibleUnwrappedCoordinates=function(e){var i=this.pointCoordinate(new t.default$1(0,0),0),n=this.pointCoordinate(new t.default$1(this.width,0),0),o=Math.floor(i.column),r=Math.floor(n.column),a=[new t.UnwrappedTileID(0,e)];if(this._renderWorldCopies)for(var s=o;s<=r;s++)0!==s&&a.push(new t.UnwrappedTileID(s,e));return a},Ui.prototype.coveringTiles=function(e){var i=this.coveringZoomLevel(e),n=i;if(void 0!==e.minzoom&&i<e.minzoom)return[];void 0!==e.maxzoom&&i>e.maxzoom&&(i=e.maxzoom);var o=this.pointCoordinate(this.centerPoint,i),r=new t.default$1(o.column-.5,o.row-.5);return function(e,i,n,o){void 0===o&&(o=!0);var r=1<<e,a={};function s(i,s,l){var c,u,h,p;if(l>=0&&l<=r)for(c=i;c<s;c++)u=Math.floor(c/r),h=(c%r+r)%r,0!==u&&!0!==o||(p=new t.OverscaledTileID(n,u,e,h,l),a[p.key]=p);}return Bi(i[0],i[1],i[2],0,r,s),Bi(i[2],i[3],i[0],0,r,s),Object.keys(a).map(function(t){return a[t]})}(i,[this.pointCoordinate(new t.default$1(0,0),i),this.pointCoordinate(new t.default$1(this.width,0),i),this.pointCoordinate(new t.default$1(this.width,this.height),i),this.pointCoordinate(new t.default$1(0,this.height),i)],e.reparseOverscaled?n:i,this._renderWorldCopies).sort(function(t,e){return r.dist(t.canonical)-r.dist(e.canonical)})},Ui.prototype.resize=function(t,e){this.width=t,this.height=e,this.pixelsToGLUnits=[2/t,-2/e],this._constrain(),this._calcMatrices();},Zi.unmodified.get=function(){return this._unmodified},Ui.prototype.zoomScale=function(t){return Math.pow(2,t)},Ui.prototype.scaleZoom=function(t){return Math.log(t)/Math.LN2},Ui.prototype.project=function(e){return new t.default$1(this.lngX(e.lng),this.latY(e.lat))},Ui.prototype.unproject=function(t){return new W(this.xLng(t.x),this.yLat(t.y))},Zi.x.get=function(){return this.lngX(this.center.lng)},Zi.y.get=function(){return this.latY(this.center.lat)},Zi.point.get=function(){return new t.default$1(this.x,this.y)},Ui.prototype.lngX=function(t){return(180+t)*this.worldSize/360},Ui.prototype.latY=function(t){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))*this.worldSize/360},Ui.prototype.xLng=function(t){return 360*t/this.worldSize-180},Ui.prototype.yLat=function(t){var e=180-360*t/this.worldSize;return 360/Math.PI*Math.atan(Math.exp(e*Math.PI/180))-90},Ui.prototype.setLocationAtPoint=function(t,e){var i=this.pointCoordinate(e)._sub(this.pointCoordinate(this.centerPoint));this.center=this.coordinateLocation(this.locationCoordinate(t)._sub(i)),this._renderWorldCopies&&(this.center=this.center.wrap());},Ui.prototype.locationPoint=function(t){return this.coordinatePoint(this.locationCoordinate(t))},Ui.prototype.pointLocation=function(t){return this.coordinateLocation(this.pointCoordinate(t))},Ui.prototype.locationCoordinate=function(e){return new t.default$17(this.lngX(e.lng)/this.tileSize,this.latY(e.lat)/this.tileSize,this.zoom).zoomTo(this.tileZoom)},Ui.prototype.coordinateLocation=function(t){var e=t.zoomTo(this.zoom);return new W(this.xLng(e.column*this.tileSize),this.yLat(e.row*this.tileSize))},Ui.prototype.pointCoordinate=function(e,i){void 0===i&&(i=this.tileZoom);var n=[e.x,e.y,0,1],o=[e.x,e.y,1,1];Oi.transformMat4(n,n,this.pixelMatrixInverse),Oi.transformMat4(o,o,this.pixelMatrixInverse);var r=n[3],a=o[3],s=n[0]/r,l=o[0]/a,c=n[1]/r,u=o[1]/a,h=n[2]/r,p=o[2]/a,d=h===p?0:(0-h)/(p-h);return new t.default$17(t.number(s,l,d)/this.tileSize,t.number(c,u,d)/this.tileSize,this.zoom)._zoomTo(i)},Ui.prototype.coordinatePoint=function(e){var i=e.zoomTo(this.zoom),n=[i.column*this.tileSize,i.row*this.tileSize,0,1];return Oi.transformMat4(n,n,this.pixelMatrix),new t.default$1(n[0]/n[3],n[1]/n[3])},Ui.prototype.calculatePosMatrix=function(e,i){void 0===i&&(i=!1);var n=e.key,o=i?this._alignedPosMatrixCache:this._posMatrixCache;if(o[n])return o[n];var r=e.canonical,a=this.worldSize/this.zoomScale(r.z),s=r.x+Math.pow(2,r.z)*e.wrap,l=Fi.identity(new Float64Array(16));return Fi.translate(l,l,[s*a,r.y*a,0]),Fi.scale(l,l,[a/t.default$8,a/t.default$8,1]),Fi.multiply(l,i?this.alignedProjMatrix:this.projMatrix,l),o[n]=new Float32Array(l),o[n]},Ui.prototype._constrain=function(){if(this.center&&this.width&&this.height&&!this._constraining){this._constraining=!0;var e,i,n,o,r=-90,a=90,s=-180,l=180,c=this.size,u=this._unmodified;if(this.latRange){var h=this.latRange;r=this.latY(h[1]),e=(a=this.latY(h[0]))-r<c.y?c.y/(a-r):0;}if(this.lngRange){var p=this.lngRange;s=this.lngX(p[0]),i=(l=this.lngX(p[1]))-s<c.x?c.x/(l-s):0;}var d=Math.max(i||0,e||0);if(d)return this.center=this.unproject(new t.default$1(i?(l+s)/2:this.x,e?(a+r)/2:this.y)),this.zoom+=this.scaleZoom(d),this._unmodified=u,void(this._constraining=!1);if(this.latRange){var f=this.y,m=c.y/2;f-m<r&&(o=r+m),f+m>a&&(o=a-m);}if(this.lngRange){var _=this.x,g=c.x/2;_-g<s&&(n=s+g),_+g>l&&(n=l-g);}void 0===n&&void 0===o||(this.center=this.unproject(new t.default$1(void 0!==n?n:this.x,void 0!==o?o:this.y))),this._unmodified=u,this._constraining=!1;}},Ui.prototype._calcMatrices=function(){if(this.height){this.cameraToCenterDistance=.5/Math.tan(this._fov/2)*this.height;var t=this._fov/2,e=Math.PI/2+this._pitch,i=Math.sin(t)*this.cameraToCenterDistance/Math.sin(Math.PI-e-t),n=this.x,o=this.y,r=1.01*(Math.cos(Math.PI/2-this._pitch)*i+this.cameraToCenterDistance),a=new Float64Array(16);Fi.perspective(a,this._fov,this.width/this.height,1,r),Fi.scale(a,a,[1,-1,1]),Fi.translate(a,a,[0,0,-this.cameraToCenterDistance]),Fi.rotateX(a,a,this._pitch),Fi.rotateZ(a,a,this.angle),Fi.translate(a,a,[-n,-o,0]);var s=this.worldSize/(2*Math.PI*6378137*Math.abs(Math.cos(this.center.lat*(Math.PI/180))));Fi.scale(a,a,[1,1,s,1]),this.projMatrix=a;var l=this.width%2/2,c=this.height%2/2,u=Math.cos(this.angle),h=Math.sin(this.angle),p=n-Math.round(n)+u*l+h*c,d=o-Math.round(o)+u*c+h*l,f=new Float64Array(a);if(Fi.translate(f,f,[p>.5?p-1:p,d>.5?d-1:d,0]),this.alignedProjMatrix=f,a=Fi.create(),Fi.scale(a,a,[this.width/2,-this.height/2,1]),Fi.translate(a,a,[1,-1,0]),this.pixelMatrix=Fi.multiply(new Float64Array(16),a,this.projMatrix),!(a=Fi.invert(new Float64Array(16),this.pixelMatrix)))throw new Error("failed to invert matrix");this.pixelMatrixInverse=a,this._posMatrixCache={},this._alignedPosMatrixCache={};}},Ui.prototype.maxPitchScaleFactor=function(){if(!this.pixelMatrixInverse)return 1;var e=this.pointCoordinate(new t.default$1(0,0)).zoomTo(this.zoom),i=[e.column*this.tileSize,e.row*this.tileSize,0,1];return Oi.transformMat4(i,i,this.pixelMatrix)[3]/this.cameraToCenterDistance},Object.defineProperties(Ui.prototype,Zi);var Vi=function(){var e,i,n,o,r;t.bindAll(["_onHashChange","_updateHash"],this),this._updateHash=(e=this._updateHashUnthrottled.bind(this),i=300,n=!1,o=0,r=function(){o=0,n&&(e(),o=setTimeout(r,i),n=!1);},function(){return n=!0,o||r(),o});};Vi.prototype.addTo=function(e){return this._map=e,t.default.addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this},Vi.prototype.remove=function(){return t.default.removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),delete this._map,this},Vi.prototype.getHashString=function(t){var e=this._map.getCenter(),i=Math.round(100*this._map.getZoom())/100,n=Math.ceil((i*Math.LN2+Math.log(512/360/.5))/Math.LN10),o=Math.pow(10,n),r=Math.round(e.lng*o)/o,a=Math.round(e.lat*o)/o,s=this._map.getBearing(),l=this._map.getPitch(),c="";return c+=t?"#/"+r+"/"+a+"/"+i:"#"+i+"/"+a+"/"+r,(s||l)&&(c+="/"+Math.round(10*s)/10),l&&(c+="/"+Math.round(l)),c},Vi.prototype._onHashChange=function(){var e=t.default.location.hash.replace("#","").split("/");return e.length>=3&&(this._map.jumpTo({center:[+e[2],+e[1]],zoom:+e[0],bearing:+(e[3]||0),pitch:+(e[4]||0)}),!0)},Vi.prototype._updateHashUnthrottled=function(){var e=this.getHashString();t.default.history.replaceState(t.default.history.state,"",e);};var ji=function(e){function i(i,n,o,r){void 0===r&&(r={});var a=s.mousePos(n.getCanvasContainer(),o),l=n.unproject(a);e.call(this,i,t.extend({point:a,lngLat:l,originalEvent:o},r)),this._defaultPrevented=!1,this.target=n;}e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i;var n={defaultPrevented:{configurable:!0}};return i.prototype.preventDefault=function(){this._defaultPrevented=!0;},n.defaultPrevented.get=function(){return this._defaultPrevented},Object.defineProperties(i.prototype,n),i}(t.Event),$i=function(e){function i(i,n,o){var r=s.touchPos(n.getCanvasContainer(),o),a=r.map(function(t){return n.unproject(t)}),l=r.reduce(function(t,e,i,n){return t.add(e.div(n.length))},new t.default$1(0,0)),c=n.unproject(l);e.call(this,i,{points:r,point:l,lngLats:a,lngLat:c,originalEvent:o}),this._defaultPrevented=!1;}e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i;var n={defaultPrevented:{configurable:!0}};return i.prototype.preventDefault=function(){this._defaultPrevented=!0;},n.defaultPrevented.get=function(){return this._defaultPrevented},Object.defineProperties(i.prototype,n),i}(t.Event),Gi=function(t){function e(e,i,n){t.call(this,e,{originalEvent:n}),this._defaultPrevented=!1;}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var i={defaultPrevented:{configurable:!0}};return e.prototype.preventDefault=function(){this._defaultPrevented=!0;},i.defaultPrevented.get=function(){return this._defaultPrevented},Object.defineProperties(e.prototype,i),e}(t.Event),Wi=function(e){this._map=e,this._el=e.getCanvasContainer(),this._delta=0,t.bindAll(["_onWheel","_onTimeout","_onScrollFrame","_onScrollFinished"],this);};Wi.prototype.isEnabled=function(){return!!this._enabled},Wi.prototype.isActive=function(){return!!this._active},Wi.prototype.enable=function(t){this.isEnabled()||(this._enabled=!0,this._aroundCenter=t&&"center"===t.around);},Wi.prototype.disable=function(){this.isEnabled()&&(this._enabled=!1);},Wi.prototype.onWheel=function(e){if(this.isEnabled()){var i=e.deltaMode===t.default.WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY,n=r.now(),o=n-(this._lastWheelEventTime||0);this._lastWheelEventTime=n,0!==i&&i%4.000244140625==0?this._type="wheel":0!==i&&Math.abs(i)<4?this._type="trackpad":o>400?(this._type=null,this._lastValue=i,this._timeout=setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(o*i)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,i+=this._lastValue)),e.shiftKey&&i&&(i/=4),this._type&&(this._lastWheelEvent=e,this._delta-=i,this.isActive()||this._start(e)),e.preventDefault();}},Wi.prototype._onTimeout=function(t){this._type="wheel",this._delta-=this._lastValue,this.isActive()||this._start(t);},Wi.prototype._start=function(e){if(this._delta){this._frameId&&(this._map._cancelRenderFrame(this._frameId),this._frameId=null),this._active=!0,this._map.fire(new t.Event("movestart",{originalEvent:e})),this._map.fire(new t.Event("zoomstart",{originalEvent:e})),this._finishTimeout&&clearTimeout(this._finishTimeout);var i=s.mousePos(this._el,e);this._around=W.convert(this._aroundCenter?this._map.getCenter():this._map.unproject(i)),this._aroundPoint=this._map.transform.locationPoint(this._around),this._frameId||(this._frameId=this._map._requestRenderFrame(this._onScrollFrame));}},Wi.prototype._onScrollFrame=function(){var e=this;if(this._frameId=null,this.isActive()){var i=this._map.transform;if(0!==this._delta){var n="wheel"===this._type&&Math.abs(this._delta)>4.000244140625?1/450:.01,o=2/(1+Math.exp(-Math.abs(this._delta*n)));this._delta<0&&0!==o&&(o=1/o);var a="number"==typeof this._targetZoom?i.zoomScale(this._targetZoom):i.scale;this._targetZoom=Math.min(i.maxZoom,Math.max(i.minZoom,i.scaleZoom(a*o))),"wheel"===this._type&&(this._startZoom=i.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0;}var s=!1;if("wheel"===this._type){var l=Math.min((r.now()-this._lastWheelEventTime)/200,1),c=this._easing(l);i.zoom=t.number(this._startZoom,this._targetZoom,c),l<1?this._frameId||(this._frameId=this._map._requestRenderFrame(this._onScrollFrame)):s=!0;}else i.zoom=this._targetZoom,s=!0;i.setLocationAtPoint(this._around,this._aroundPoint),this._map.fire(new t.Event("move",{originalEvent:this._lastWheelEvent})),this._map.fire(new t.Event("zoom",{originalEvent:this._lastWheelEvent})),s&&(this._active=!1,this._finishTimeout=setTimeout(function(){e._map.fire(new t.Event("zoomend",{originalEvent:e._lastWheelEvent})),e._map.fire(new t.Event("moveend",{originalEvent:e._lastWheelEvent})),delete e._targetZoom;},200));}},Wi.prototype._smoothOutEasing=function(e){var i=t.ease;if(this._prevEase){var n=this._prevEase,o=(r.now()-n.start)/n.duration,a=n.easing(o+.01)-n.easing(o),s=.27/Math.sqrt(a*a+1e-4)*.01,l=Math.sqrt(.0729-s*s);i=t.bezier(s,l,.25,1);}return this._prevEase={start:r.now(),duration:e,easing:i},i};var qi=function(e){this._map=e,this._el=e.getCanvasContainer(),this._container=e.getContainer(),t.bindAll(["_onMouseMove","_onMouseUp","_onKeyDown"],this);};qi.prototype.isEnabled=function(){return!!this._enabled},qi.prototype.isActive=function(){return!!this._active},qi.prototype.enable=function(){this.isEnabled()||(this._enabled=!0);},qi.prototype.disable=function(){this.isEnabled()&&(this._enabled=!1);},qi.prototype.onMouseDown=function(e){this.isEnabled()&&e.shiftKey&&0===e.button&&(t.default.document.addEventListener("mousemove",this._onMouseMove,!1),t.default.document.addEventListener("keydown",this._onKeyDown,!1),t.default.document.addEventListener("mouseup",this._onMouseUp,!1),s.disableDrag(),this._startPos=s.mousePos(this._el,e),this._active=!0);},qi.prototype._onMouseMove=function(t){var e=this._startPos,i=s.mousePos(this._el,t);this._box||(this._box=s.create("div","mapboxgl-boxzoom",this._container),this._container.classList.add("mapboxgl-crosshair"),this._fireEvent("boxzoomstart",t));var n=Math.min(e.x,i.x),o=Math.max(e.x,i.x),r=Math.min(e.y,i.y),a=Math.max(e.y,i.y);s.setTransform(this._box,"translate("+n+"px,"+r+"px)"),this._box.style.width=o-n+"px",this._box.style.height=a-r+"px";},qi.prototype._onMouseUp=function(e){if(0===e.button){var i=this._startPos,n=s.mousePos(this._el,e),o=(new q).extend(this._map.unproject(i)).extend(this._map.unproject(n));this._finish(),s.suppressClick(),i.x===n.x&&i.y===n.y?this._fireEvent("boxzoomcancel",e):this._map.fitBounds(o,{linear:!0}).fire(new t.Event("boxzoomend",{originalEvent:e,boxZoomBounds:o}));}},qi.prototype._onKeyDown=function(t){27===t.keyCode&&(this._finish(),this._fireEvent("boxzoomcancel",t));},qi.prototype._finish=function(){this._active=!1,t.default.document.removeEventListener("mousemove",this._onMouseMove,!1),t.default.document.removeEventListener("keydown",this._onKeyDown,!1),t.default.document.removeEventListener("mouseup",this._onMouseUp,!1),this._container.classList.remove("mapboxgl-crosshair"),this._box&&(s.remove(this._box),this._box=null),s.enableDrag();},qi.prototype._fireEvent=function(e,i){return this._map.fire(new t.Event(e,{originalEvent:i}))};var Xi=t.bezier(0,0,.25,1),Hi=function(e,i){this._map=e,this._el=i.element||e.getCanvasContainer(),this._state="disabled",this._button=i.button||"right",this._bearingSnap=i.bearingSnap||0,this._pitchWithRotate=!1!==i.pitchWithRotate,t.bindAll(["_onMouseMove","_onMouseUp","_onBlur","_onDragFrame"],this);};Hi.prototype.isEnabled=function(){return"disabled"!==this._state},Hi.prototype.isActive=function(){return"active"===this._state},Hi.prototype.enable=function(){this.isEnabled()||(this._state="enabled");},Hi.prototype.disable=function(){if(this.isEnabled())switch(this._state){case"active":this._state="disabled",this._unbind(),this._deactivate(),this._fireEvent("rotateend"),this._pitchWithRotate&&this._fireEvent("pitchend"),this._fireEvent("moveend");break;case"pending":this._state="disabled",this._unbind();break;default:this._state="disabled";}},Hi.prototype.onMouseDown=function(e){if("enabled"===this._state){if("right"===this._button){if(this._eventButton=s.mouseButton(e),this._eventButton!==(e.ctrlKey?0:2))return}else{if(e.ctrlKey||0!==s.mouseButton(e))return;this._eventButton=0;}s.disableDrag(),t.default.document.addEventListener("mousemove",this._onMouseMove,{capture:!0}),t.default.document.addEventListener("mouseup",this._onMouseUp),t.default.addEventListener("blur",this._onBlur),this._state="pending",this._inertia=[[r.now(),this._map.getBearing()]],this._previousPos=s.mousePos(this._el,e),this._center=this._map.transform.centerPoint,e.preventDefault();}},Hi.prototype._onMouseMove=function(t){this._lastMoveEvent=t,this._pos=s.mousePos(this._el,t),"pending"===this._state&&(this._state="active",this._fireEvent("rotatestart",t),this._fireEvent("movestart",t),this._pitchWithRotate&&this._fireEvent("pitchstart",t)),this._frameId||(this._frameId=this._map._requestRenderFrame(this._onDragFrame));},Hi.prototype._onDragFrame=function(){this._frameId=null;var t=this._lastMoveEvent;if(t){var e=this._map.transform,i=this._previousPos,n=this._pos,o=.8*(i.x-n.x),a=-.5*(i.y-n.y),s=e.bearing-o,l=e.pitch-a,c=this._inertia,u=c[c.length-1];this._drainInertiaBuffer(),c.push([r.now(),this._map._normalizeBearing(s,u[1])]),e.bearing=s,this._pitchWithRotate&&(this._fireEvent("pitch",t),e.pitch=l),this._fireEvent("rotate",t),this._fireEvent("move",t),delete this._lastMoveEvent,this._previousPos=this._pos;}},Hi.prototype._onMouseUp=function(t){if(s.mouseButton(t)===this._eventButton)switch(this._state){case"active":this._state="enabled",s.suppressClick(),this._unbind(),this._deactivate(),this._inertialRotate(t);break;case"pending":this._state="enabled",this._unbind();}},Hi.prototype._onBlur=function(t){switch(this._state){case"active":this._state="enabled",this._unbind(),this._deactivate(),this._fireEvent("rotateend",t),this._pitchWithRotate&&this._fireEvent("pitchend",t),this._fireEvent("moveend",t);break;case"pending":this._state="enabled",this._unbind();}},Hi.prototype._unbind=function(){t.default.document.removeEventListener("mousemove",this._onMouseMove,{capture:!0}),t.default.document.removeEventListener("mouseup",this._onMouseUp),t.default.removeEventListener("blur",this._onBlur),s.enableDrag();},Hi.prototype._deactivate=function(){this._frameId&&(this._map._cancelRenderFrame(this._frameId),this._frameId=null),delete this._lastMoveEvent,delete this._previousPos;},Hi.prototype._inertialRotate=function(t){var e=this;this._fireEvent("rotateend",t),this._drainInertiaBuffer();var i=this._map,n=i.getBearing(),o=this._inertia,r=function(){Math.abs(n)<e._bearingSnap?i.resetNorth({noMoveStart:!0},{originalEvent:t}):e._fireEvent("moveend",t),e._pitchWithRotate&&e._fireEvent("pitchend",t);};if(o.length<2)r();else{var a=o[0],s=o[o.length-1],l=o[o.length-2],c=i._normalizeBearing(n,l[1]),u=s[1]-a[1],h=u<0?-1:1,p=(s[0]-a[0])/1e3;if(0!==u&&0!==p){var d=Math.abs(u*(.25/p));d>180&&(d=180);var f=d/180;c+=h*d*(f/2),Math.abs(i._normalizeBearing(c,0))<this._bearingSnap&&(c=i._normalizeBearing(0,c)),i.rotateTo(c,{duration:1e3*f,easing:Xi,noMoveStart:!0},{originalEvent:t});}else r();}},Hi.prototype._fireEvent=function(e,i){return this._map.fire(new t.Event(e,i?{originalEvent:i}:{}))},Hi.prototype._drainInertiaBuffer=function(){for(var t=this._inertia,e=r.now();t.length>0&&e-t[0][0]>160;)t.shift();};var Ki=t.bezier(0,0,.3,1),Yi=function(e){this._map=e,this._el=e.getCanvasContainer(),this._state="disabled",t.bindAll(["_onMove","_onMouseUp","_onTouchEnd","_onBlur","_onDragFrame"],this);};Yi.prototype.isEnabled=function(){return"disabled"!==this._state},Yi.prototype.isActive=function(){return"active"===this._state},Yi.prototype.enable=function(){this.isEnabled()||(this._el.classList.add("mapboxgl-touch-drag-pan"),this._state="enabled");},Yi.prototype.disable=function(){if(this.isEnabled())switch(this._el.classList.remove("mapboxgl-touch-drag-pan"),this._state){case"active":this._state="disabled",this._unbind(),this._deactivate(),this._fireEvent("dragend"),this._fireEvent("moveend");break;case"pending":this._state="disabled",this._unbind();break;default:this._state="disabled";}},Yi.prototype.onMouseDown=function(e){"enabled"===this._state&&(e.ctrlKey||0!==s.mouseButton(e)||(s.addEventListener(t.default.document,"mousemove",this._onMove,{capture:!0}),s.addEventListener(t.default.document,"mouseup",this._onMouseUp),this._start(e)));},Yi.prototype.onTouchStart=function(e){"enabled"===this._state&&(e.touches.length>1||(s.addEventListener(t.default.document,"touchmove",this._onMove,{capture:!0,passive:!1}),s.addEventListener(t.default.document,"touchend",this._onTouchEnd),this._start(e)));},Yi.prototype._start=function(e){t.default.addEventListener("blur",this._onBlur),this._state="pending",this._previousPos=s.mousePos(this._el,e),this._inertia=[[r.now(),this._previousPos]];},Yi.prototype._onMove=function(t){this._lastMoveEvent=t,t.preventDefault(),this._pos=s.mousePos(this._el,t),this._drainInertiaBuffer(),this._inertia.push([r.now(),this._pos]),"pending"===this._state&&(this._state="active",this._fireEvent("dragstart",t),this._fireEvent("movestart",t)),this._frameId||(this._frameId=this._map._requestRenderFrame(this._onDragFrame));},Yi.prototype._onDragFrame=function(){this._frameId=null;var t=this._lastMoveEvent;if(t){var e=this._map.transform;e.setLocationAtPoint(e.pointLocation(this._previousPos),this._pos),this._fireEvent("drag",t),this._fireEvent("move",t),this._previousPos=this._pos,delete this._lastMoveEvent;}},Yi.prototype._onMouseUp=function(t){if(0===s.mouseButton(t))switch(this._state){case"active":this._state="enabled",s.suppressClick(),this._unbind(),this._deactivate(),this._inertialPan(t);break;case"pending":this._state="enabled",this._unbind();}},Yi.prototype._onTouchEnd=function(t){switch(this._state){case"active":this._state="enabled",this._unbind(),this._deactivate(),this._inertialPan(t);break;case"pending":this._state="enabled",this._unbind();}},Yi.prototype._onBlur=function(t){switch(this._state){case"active":this._state="enabled",this._unbind(),this._deactivate(),this._fireEvent("dragend",t),this._fireEvent("moveend",t);break;case"pending":this._state="enabled",this._unbind();}},Yi.prototype._unbind=function(){s.removeEventListener(t.default.document,"touchmove",this._onMove,{capture:!0,passive:!1}),s.removeEventListener(t.default.document,"touchend",this._onTouchEnd),s.removeEventListener(t.default.document,"mousemove",this._onMove,{capture:!0}),s.removeEventListener(t.default.document,"mouseup",this._onMouseUp),s.removeEventListener(t.default,"blur",this._onBlur);},Yi.prototype._deactivate=function(){this._frameId&&(this._map._cancelRenderFrame(this._frameId),this._frameId=null),delete this._lastMoveEvent,delete this._previousPos,delete this._pos;},Yi.prototype._inertialPan=function(t){this._fireEvent("dragend",t),this._drainInertiaBuffer();var e=this._inertia;if(e.length<2)this._fireEvent("moveend",t);else{var i=e[e.length-1],n=e[0],o=i[1].sub(n[1]),r=(i[0]-n[0])/1e3;if(0===r||i[1].equals(n[1]))this._fireEvent("moveend",t);else{var a=o.mult(.3/r),s=a.mag();s>1400&&(s=1400,a._unit()._mult(s));var l=s/750,c=a.mult(-l/2);this._map.panBy(c,{duration:1e3*l,easing:Ki,noMoveStart:!0},{originalEvent:t});}}},Yi.prototype._fireEvent=function(e,i){return this._map.fire(new t.Event(e,i?{originalEvent:i}:{}))},Yi.prototype._drainInertiaBuffer=function(){for(var t=this._inertia,e=r.now();t.length>0&&e-t[0][0]>160;)t.shift();};var Ji=function(e){this._map=e,this._el=e.getCanvasContainer(),t.bindAll(["_onKeyDown"],this);};function Qi(t){return t*(2-t)}Ji.prototype.isEnabled=function(){return!!this._enabled},Ji.prototype.enable=function(){this.isEnabled()||(this._el.addEventListener("keydown",this._onKeyDown,!1),this._enabled=!0);},Ji.prototype.disable=function(){this.isEnabled()&&(this._el.removeEventListener("keydown",this._onKeyDown),this._enabled=!1);},Ji.prototype._onKeyDown=function(t){if(!(t.altKey||t.ctrlKey||t.metaKey)){var e=0,i=0,n=0,o=0,r=0;switch(t.keyCode){case 61:case 107:case 171:case 187:e=1;break;case 189:case 109:case 173:e=-1;break;case 37:t.shiftKey?i=-1:(t.preventDefault(),o=-1);break;case 39:t.shiftKey?i=1:(t.preventDefault(),o=1);break;case 38:t.shiftKey?n=1:(t.preventDefault(),r=-1);break;case 40:t.shiftKey?n=-1:(r=1,t.preventDefault());break;default:return}var a=this._map,s=a.getZoom(),l={duration:300,delayEndEvents:500,easing:Qi,zoom:e?Math.round(s)+e*(t.shiftKey?2:1):s,bearing:a.getBearing()+15*i,pitch:a.getPitch()+10*n,offset:[100*-o,100*-r],center:a.getCenter()};a.easeTo(l,{originalEvent:t});}};var tn=function(e){this._map=e,t.bindAll(["_onDblClick","_onZoomEnd"],this);};tn.prototype.isEnabled=function(){return!!this._enabled},tn.prototype.isActive=function(){return!!this._active},tn.prototype.enable=function(){this.isEnabled()||(this._enabled=!0);},tn.prototype.disable=function(){this.isEnabled()&&(this._enabled=!1);},tn.prototype.onTouchStart=function(t){var e=this;this.isEnabled()&&(t.points.length>1||(this._tapped?(clearTimeout(this._tapped),this._tapped=null,this._zoom(t)):this._tapped=setTimeout(function(){e._tapped=null;},300)));},tn.prototype.onDblClick=function(t){this.isEnabled()&&(t.originalEvent.preventDefault(),this._zoom(t));},tn.prototype._zoom=function(t){this._active=!0,this._map.on("zoomend",this._onZoomEnd),this._map.zoomTo(this._map.getZoom()+(t.originalEvent.shiftKey?-1:1),{around:t.lngLat},t);},tn.prototype._onZoomEnd=function(){this._active=!1,this._map.off("zoomend",this._onZoomEnd);};var en=t.bezier(0,0,.15,1),nn=function(e){this._map=e,this._el=e.getCanvasContainer(),t.bindAll(["_onMove","_onEnd","_onTouchFrame"],this);};nn.prototype.isEnabled=function(){return!!this._enabled},nn.prototype.enable=function(t){this.isEnabled()||(this._el.classList.add("mapboxgl-touch-zoom-rotate"),this._enabled=!0,this._aroundCenter=!!t&&"center"===t.around);},nn.prototype.disable=function(){this.isEnabled()&&(this._el.classList.remove("mapboxgl-touch-zoom-rotate"),this._enabled=!1);},nn.prototype.disableRotation=function(){this._rotationDisabled=!0;},nn.prototype.enableRotation=function(){this._rotationDisabled=!1;},nn.prototype.onStart=function(e){if(this.isEnabled()&&2===e.touches.length){var i=s.mousePos(this._el,e.touches[0]),n=s.mousePos(this._el,e.touches[1]);this._startVec=i.sub(n),this._gestureIntent=void 0,this._inertia=[],s.addEventListener(t.default.document,"touchmove",this._onMove,{passive:!1}),s.addEventListener(t.default.document,"touchend",this._onEnd);}},nn.prototype._getTouchEventData=function(t){var e=s.mousePos(this._el,t.touches[0]),i=s.mousePos(this._el,t.touches[1]),n=e.sub(i);return{vec:n,center:e.add(i).div(2),scale:n.mag()/this._startVec.mag(),bearing:this._rotationDisabled?0:180*n.angleWith(this._startVec)/Math.PI}},nn.prototype._onMove=function(e){if(2===e.touches.length){var i=this._getTouchEventData(e),n=i.vec,o=i.scale,r=i.bearing;if(!this._gestureIntent){var a=Math.abs(1-o)>.15;Math.abs(r)>10?this._gestureIntent="rotate":a&&(this._gestureIntent="zoom"),this._gestureIntent&&(this._map.fire(new t.Event(this._gestureIntent+"start",{originalEvent:e})),this._map.fire(new t.Event("movestart",{originalEvent:e})),this._startVec=n);}this._lastTouchEvent=e,this._frameId||(this._frameId=this._map._requestRenderFrame(this._onTouchFrame)),e.preventDefault();}},nn.prototype._onTouchFrame=function(){this._frameId=null;var e=this._gestureIntent;if(e){var i=this._map.transform;this._startScale||(this._startScale=i.scale,this._startBearing=i.bearing);var n=this._getTouchEventData(this._lastTouchEvent),o=n.center,a=n.bearing,s=n.scale,l=i.pointLocation(o),c=i.locationPoint(l);"rotate"===e&&(i.bearing=this._startBearing+a),i.zoom=i.scaleZoom(this._startScale*s),i.setLocationAtPoint(l,c),this._map.fire(new t.Event(e,{originalEvent:this._lastTouchEvent})),this._map.fire(new t.Event("move",{originalEvent:this._lastTouchEvent})),this._drainInertiaBuffer(),this._inertia.push([r.now(),s,o]);}},nn.prototype._onEnd=function(e){s.removeEventListener(t.default.document,"touchmove",this._onMove,{passive:!1}),s.removeEventListener(t.default.document,"touchend",this._onEnd);var i=this._gestureIntent,n=this._startScale;if(this._frameId&&(this._map._cancelRenderFrame(this._frameId),this._frameId=null),delete this._gestureIntent,delete this._startScale,delete this._startBearing,delete this._lastTouchEvent,i){this._map.fire(new t.Event(i+"end",{originalEvent:e})),this._drainInertiaBuffer();var o=this._inertia,r=this._map;if(o.length<2)r.snapToNorth({},{originalEvent:e});else{var a=o[o.length-1],l=o[0],c=r.transform.scaleZoom(n*a[1]),u=r.transform.scaleZoom(n*l[1]),h=c-u,p=(a[0]-l[0])/1e3,d=a[2];if(0!==p&&c!==u){var f=.15*h/p;Math.abs(f)>2.5&&(f=f>0?2.5:-2.5);var m=1e3*Math.abs(f/(12*.15)),_=c+f*m/2e3;_<0&&(_=0),r.easeTo({zoom:_,duration:m,easing:en,around:this._aroundCenter?r.getCenter():r.unproject(d),noMoveStart:!0},{originalEvent:e});}else r.snapToNorth({},{originalEvent:e});}}},nn.prototype._drainInertiaBuffer=function(){for(var t=this._inertia,e=r.now();t.length>2&&e-t[0][0]>160;)t.shift();};var on={scrollZoom:Wi,boxZoom:qi,dragRotate:Hi,dragPan:Yi,keyboard:Ji,doubleClickZoom:tn,touchZoomRotate:nn};var rn=function(e){function i(i,n){e.call(this),this._moving=!1,this._zooming=!1,this.transform=i,this._bearingSnap=n.bearingSnap,t.bindAll(["_renderFrameCallback"],this);}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.getCenter=function(){return this.transform.center},i.prototype.setCenter=function(t,e){return this.jumpTo({center:t},e)},i.prototype.panBy=function(e,i,n){return e=t.default$1.convert(e).mult(-1),this.panTo(this.transform.center,t.extend({offset:e},i),n)},i.prototype.panTo=function(e,i,n){return this.easeTo(t.extend({center:e},i),n)},i.prototype.getZoom=function(){return this.transform.zoom},i.prototype.setZoom=function(t,e){return this.jumpTo({zoom:t},e),this},i.prototype.zoomTo=function(e,i,n){return this.easeTo(t.extend({zoom:e},i),n)},i.prototype.zoomIn=function(t,e){return this.zoomTo(this.getZoom()+1,t,e),this},i.prototype.zoomOut=function(t,e){return this.zoomTo(this.getZoom()-1,t,e),this},i.prototype.getBearing=function(){return this.transform.bearing},i.prototype.setBearing=function(t,e){return this.jumpTo({bearing:t},e),this},i.prototype.rotateTo=function(e,i,n){return this.easeTo(t.extend({bearing:e},i),n)},i.prototype.resetNorth=function(e,i){return this.rotateTo(0,t.extend({duration:1e3},e),i),this},i.prototype.snapToNorth=function(t,e){return Math.abs(this.getBearing())<this._bearingSnap?this.resetNorth(t,e):this},i.prototype.getPitch=function(){return this.transform.pitch},i.prototype.setPitch=function(t,e){return this.jumpTo({pitch:t},e),this},i.prototype.fitBounds=function(e,i,n){if("number"==typeof(i=t.extend({padding:{top:0,bottom:0,right:0,left:0},offset:[0,0],maxZoom:this.transform.maxZoom},i)).padding){var o=i.padding;i.padding={top:o,bottom:o,right:o,left:o};}if(!t.default$10(Object.keys(i.padding).sort(function(t,e){return t<e?-1:t>e?1:0}),["bottom","left","right","top"]))return t.warnOnce("options.padding must be a positive number, or an Object with keys 'bottom', 'left', 'right', 'top'"),this;e=q.convert(e);var r=[(i.padding.left-i.padding.right)/2,(i.padding.top-i.padding.bottom)/2],a=Math.min(i.padding.right,i.padding.left),s=Math.min(i.padding.top,i.padding.bottom);i.offset=[i.offset[0]+r[0],i.offset[1]+r[1]];var l=t.default$1.convert(i.offset),c=this.transform,u=c.project(e.getNorthWest()),h=c.project(e.getSouthEast()),p=h.sub(u),d=(c.width-2*a-2*Math.abs(l.x))/p.x,f=(c.height-2*s-2*Math.abs(l.y))/p.y;return f<0||d<0?(t.warnOnce("Map cannot fit within canvas with the given bounds, padding, and/or offset."),this):(i.center=c.unproject(u.add(h).div(2)),i.zoom=Math.min(c.scaleZoom(c.scale*Math.min(d,f)),i.maxZoom),i.bearing=0,i.linear?this.easeTo(i,n):this.flyTo(i,n))},i.prototype.jumpTo=function(e,i){this.stop();var n=this.transform,o=!1,r=!1,a=!1;return"zoom"in e&&n.zoom!==+e.zoom&&(o=!0,n.zoom=+e.zoom),void 0!==e.center&&(n.center=W.convert(e.center)),"bearing"in e&&n.bearing!==+e.bearing&&(r=!0,n.bearing=+e.bearing),"pitch"in e&&n.pitch!==+e.pitch&&(a=!0,n.pitch=+e.pitch),this.fire(new t.Event("movestart",i)).fire(new t.Event("move",i)),o&&this.fire(new t.Event("zoomstart",i)).fire(new t.Event("zoom",i)).fire(new t.Event("zoomend",i)),r&&this.fire(new t.Event("rotatestart",i)).fire(new t.Event("rotate",i)).fire(new t.Event("rotateend",i)),a&&this.fire(new t.Event("pitchstart",i)).fire(new t.Event("pitch",i)).fire(new t.Event("pitchend",i)),this.fire(new t.Event("moveend",i))},i.prototype.easeTo=function(e,i){var n=this;this.stop(),!1===(e=t.extend({offset:[0,0],duration:500,easing:t.ease},e)).animate&&(e.duration=0);var o=this.transform,r=this.getZoom(),a=this.getBearing(),s=this.getPitch(),l="zoom"in e?+e.zoom:r,c="bearing"in e?this._normalizeBearing(e.bearing,a):a,u="pitch"in e?+e.pitch:s,h=o.centerPoint.add(t.default$1.convert(e.offset)),p=o.pointLocation(h),d=W.convert(e.center||p);this._normalizeCenter(d);var f,m,_=o.project(p),g=o.project(d).sub(_),v=o.zoomScale(l-r);return e.around&&(f=W.convert(e.around),m=o.locationPoint(f)),this._zooming=l!==r,this._rotating=a!==c,this._pitching=u!==s,this._prepareEase(i,e.noMoveStart),clearTimeout(this._easeEndTimeoutID),this._ease(function(e){if(n._zooming&&(o.zoom=t.number(r,l,e)),n._rotating&&(o.bearing=t.number(a,c,e)),n._pitching&&(o.pitch=t.number(s,u,e)),f)o.setLocationAtPoint(f,m);else{var p=o.zoomScale(o.zoom-r),d=l>r?Math.min(2,v):Math.max(.5,v),y=Math.pow(d,1-e),x=o.unproject(_.add(g.mult(e*y)).mult(p));o.setLocationAtPoint(o.renderWorldCopies?x.wrap():x,h);}n._fireMoveEvents(i);},function(){e.delayEndEvents?n._easeEndTimeoutID=setTimeout(function(){return n._afterEase(i)},e.delayEndEvents):n._afterEase(i);},e),this},i.prototype._prepareEase=function(e,i){this._moving=!0,i||this.fire(new t.Event("movestart",e)),this._zooming&&this.fire(new t.Event("zoomstart",e)),this._rotating&&this.fire(new t.Event("rotatestart",e)),this._pitching&&this.fire(new t.Event("pitchstart",e));},i.prototype._fireMoveEvents=function(e){this.fire(new t.Event("move",e)),this._zooming&&this.fire(new t.Event("zoom",e)),this._rotating&&this.fire(new t.Event("rotate",e)),this._pitching&&this.fire(new t.Event("pitch",e));},i.prototype._afterEase=function(e){var i=this._zooming,n=this._rotating,o=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,i&&this.fire(new t.Event("zoomend",e)),n&&this.fire(new t.Event("rotateend",e)),o&&this.fire(new t.Event("pitchend",e)),this.fire(new t.Event("moveend",e));},i.prototype.flyTo=function(e,i){var n=this;this.stop(),e=t.extend({offset:[0,0],speed:1.2,curve:1.42,easing:t.ease},e);var o=this.transform,r=this.getZoom(),a=this.getBearing(),s=this.getPitch(),l="zoom"in e?t.clamp(+e.zoom,o.minZoom,o.maxZoom):r,c="bearing"in e?this._normalizeBearing(e.bearing,a):a,u="pitch"in e?+e.pitch:s,h=o.zoomScale(l-r),p=o.centerPoint.add(t.default$1.convert(e.offset)),d=o.pointLocation(p),f=W.convert(e.center||d);this._normalizeCenter(f);var m=o.project(d),_=o.project(f).sub(m),g=e.curve,v=Math.max(o.width,o.height),y=v/h,x=_.mag();if("minZoom"in e){var b=t.clamp(Math.min(e.minZoom,r,l),o.minZoom,o.maxZoom),w=v/o.zoomScale(b-r);g=Math.sqrt(w/x*2);}var E=g*g;function T(t){var e=(y*y-v*v+(t?-1:1)*E*E*x*x)/(2*(t?y:v)*E*x);return Math.log(Math.sqrt(e*e+1)-e)}function I(t){return(Math.exp(t)-Math.exp(-t))/2}function C(t){return(Math.exp(t)+Math.exp(-t))/2}var S=T(0),z=function(t){return C(S)/C(S+g*t)},A=function(t){return v*((C(S)*(I(e=S+g*t)/C(e))-I(S))/E)/x;var e;},R=(T(1)-S)/g;if(Math.abs(x)<1e-6||!isFinite(R)){if(Math.abs(v-y)<1e-6)return this.easeTo(e,i);var D=y<v?-1:1;R=Math.abs(Math.log(y/v))/g,A=function(){return 0},z=function(t){return Math.exp(D*g*t)};}if("duration"in e)e.duration=+e.duration;else{var M="screenSpeed"in e?+e.screenSpeed/g:+e.speed;e.duration=1e3*R/M;}return e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0),this._zooming=!0,this._rotating=a!==c,this._pitching=u!==s,this._prepareEase(i,!1),this._ease(function(e){var l=e*R,h=1/z(l);o.zoom=r+o.scaleZoom(h),n._rotating&&(o.bearing=t.number(a,c,e)),n._pitching&&(o.pitch=t.number(s,u,e));var d=o.unproject(m.add(_.mult(A(l))).mult(h));o.setLocationAtPoint(o.renderWorldCopies?d.wrap():d,p),n._fireMoveEvents(i);},function(){return n._afterEase(i)},e),this},i.prototype.isEasing=function(){return!!this._easeFrameId},i.prototype.stop=function(){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){var t=this._onEaseEnd;delete this._onEaseEnd,t.call(this);}return this},i.prototype._ease=function(t,e,i){!1===i.animate||0===i.duration?(t(1),e()):(this._easeStart=r.now(),this._easeOptions=i,this._onEaseFrame=t,this._onEaseEnd=e,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback));},i.prototype._renderFrameCallback=function(){var t=Math.min((r.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(t)),t<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop();},i.prototype._normalizeBearing=function(e,i){e=t.wrap(e,-180,180);var n=Math.abs(e-i);return Math.abs(e-360-i)<n&&(e-=360),Math.abs(e+360-i)<n&&(e+=360),e},i.prototype._normalizeCenter=function(t){var e=this.transform;if(e.renderWorldCopies&&!e.lngRange){var i=t.lng-e.center.lng;t.lng+=i>180?-360:i<-180?360:0;}},i}(t.Evented),an=function(e){void 0===e&&(e={}),this.options=e,t.bindAll(["_updateEditLink","_updateData","_updateCompact"],this);};an.prototype.getDefaultPosition=function(){return"bottom-right"},an.prototype.onAdd=function(t){var e=this.options&&this.options.compact;return this._map=t,this._container=s.create("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),e&&this._container.classList.add("mapboxgl-compact"),this._updateAttributions(),this._updateEditLink(),this._map.on("sourcedata",this._updateData),this._map.on("moveend",this._updateEditLink),void 0===e&&(this._map.on("resize",this._updateCompact),this._updateCompact()),this._container},an.prototype.onRemove=function(){s.remove(this._container),this._map.off("sourcedata",this._updateData),this._map.off("moveend",this._updateEditLink),this._map.off("resize",this._updateCompact),this._map=void 0;},an.prototype._updateEditLink=function(){var t=this._editLink;t||(t=this._editLink=this._container.querySelector(".mapbox-improve-map"));var e=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:_.ACCESS_TOKEN}];if(t){var i=e.reduce(function(t,i,n){return i.value&&(t+=i.key+"="+i.value+(n<e.length-1?"&":"")),t},"?");t.href="https://www.mapbox.com/feedback/"+i+(this._map._hash?this._map._hash.getHashString(!0):"");}},an.prototype._updateData=function(t){t&&"metadata"===t.sourceDataType&&(this._updateAttributions(),this._updateEditLink());},an.prototype._updateAttributions=function(){if(this._map.style){var t=[];if(this._map.style.stylesheet){var e=this._map.style.stylesheet;this.styleOwner=e.owner,this.styleId=e.id;}var i=this._map.style.sourceCaches;for(var n in i){var o=i[n].getSource();o.attribution&&t.indexOf(o.attribution)<0&&t.push(o.attribution);}t.sort(function(t,e){return t.length-e.length}),(t=t.filter(function(e,i){for(var n=i+1;n<t.length;n++)if(t[n].indexOf(e)>=0)return!1;return!0})).length?(this._container.innerHTML=t.join(" | "),this._container.classList.remove("mapboxgl-attrib-empty")):this._container.classList.add("mapboxgl-attrib-empty"),this._editLink=null;}},an.prototype._updateCompact=function(){this._map.getCanvasContainer().offsetWidth<=640?this._container.classList.add("mapboxgl-compact"):this._container.classList.remove("mapboxgl-compact");};var sn=function(){t.bindAll(["_updateLogo"],this);};sn.prototype.onAdd=function(t){this._map=t,this._container=s.create("div","mapboxgl-ctrl");var e=s.create("a","mapboxgl-ctrl-logo");return e.target="_blank",e.href="https://www.mapbox.com/",e.setAttribute("aria-label","Mapbox logo"),this._container.appendChild(e),this._container.style.display="none",this._map.on("sourcedata",this._updateLogo),this._updateLogo(),this._container},sn.prototype.onRemove=function(){s.remove(this._container),this._map.off("sourcedata",this._updateLogo);},sn.prototype.getDefaultPosition=function(){return"bottom-left"},sn.prototype._updateLogo=function(t){t&&"metadata"!==t.sourceDataType||(this._container.style.display=this._logoRequired()?"block":"none");},sn.prototype._logoRequired=function(){if(this._map.style){var t=this._map.style.sourceCaches;for(var e in t){if(t[e].getSource().mapbox_logo)return!0}return!1}};var ln=function(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1;};ln.prototype.add=function(t){var e=++this._id;return this._queue.push({callback:t,id:e,cancelled:!1}),e},ln.prototype.remove=function(t){for(var e=this._currentlyRunning,i=0,n=e?this._queue.concat(e):this._queue;i<n.length;i+=1){var o=n[i];if(o.id===t)return void(o.cancelled=!0)}},ln.prototype.run=function(){var t=this._currentlyRunning=this._queue;this._queue=[];for(var e=0,i=t;e<i.length;e+=1){var n=i[e];if(!n.cancelled&&(n.callback(),this._cleared))break}this._cleared=!1,this._currentlyRunning=!1;},ln.prototype.clear=function(){this._currentlyRunning&&(this._cleared=!0),this._queue=[];};var cn=t.default.HTMLImageElement,un=t.default.HTMLElement,hn={center:[0,0],zoom:0,bearing:0,pitch:0,minZoom:0,maxZoom:22,interactive:!0,scrollZoom:!0,boxZoom:!0,dragRotate:!0,dragPan:!0,keyboard:!0,doubleClickZoom:!0,touchZoomRotate:!0,bearingSnap:7,hash:!1,attributionControl:!0,failIfMajorPerformanceCaveat:!1,preserveDrawingBuffer:!1,trackResize:!0,renderWorldCopies:!0,refreshExpiredTiles:!0,maxTileCacheSize:null,transformRequest:null,fadeDuration:300},pn=function(i){function n(e){if(null!=(e=t.extend({},hn,e)).minZoom&&null!=e.maxZoom&&e.minZoom>e.maxZoom)throw new Error("maxZoom must be greater than minZoom");var n=new Ui(e.minZoom,e.maxZoom,e.renderWorldCopies);i.call(this,n,e),this._interactive=e.interactive,this._maxTileCacheSize=e.maxTileCacheSize,this._failIfMajorPerformanceCaveat=e.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=e.preserveDrawingBuffer,this._trackResize=e.trackResize,this._bearingSnap=e.bearingSnap,this._refreshExpiredTiles=e.refreshExpiredTiles,this._fadeDuration=e.fadeDuration,this._crossFadingFactor=1,this._collectResourceTiming=e.collectResourceTiming,this._renderTaskQueue=new ln;var o=e.transformRequest;if(this._transformRequest=o?function(t,e){return o(t,e)||{url:t}}:function(t){return{url:t}},"string"==typeof e.container){var r=t.default.document.getElementById(e.container);if(!r)throw new Error("Container '"+e.container+"' not found.");this._container=r;}else{if(!(e.container instanceof un))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=e.container;}e.maxBounds&&this.setMaxBounds(e.maxBounds),t.bindAll(["_onWindowOnline","_onWindowResize","_contextLost","_contextRestored","_update","_render","_onData","_onDataLoading"],this),this._setupContainer(),this._setupPainter(),this.on("move",this._update.bind(this,!1)),this.on("zoom",this._update.bind(this,!0)),void 0!==t.default&&(t.default.addEventListener("online",this._onWindowOnline,!1),t.default.addEventListener("resize",this._onWindowResize,!1)),function(t,e){var i=t.getCanvasContainer(),n=null,o=!1;for(var r in on)t[r]=new on[r](t,e),e.interactive&&e[r]&&t[r].enable(e[r]);s.addEventListener(i,"mouseout",function(e){t.fire(new ji("mouseout",t,e));}),s.addEventListener(i,"mousedown",function(i){o=!0;var n=new ji("mousedown",t,i);t.fire(n),n.defaultPrevented||(e.interactive&&!t.doubleClickZoom.isActive()&&t.stop(),t.boxZoom.onMouseDown(i),t.boxZoom.isActive()||t.dragPan.isActive()||t.dragRotate.onMouseDown(i),t.boxZoom.isActive()||t.dragRotate.isActive()||t.dragPan.onMouseDown(i));}),s.addEventListener(i,"mouseup",function(e){var i=t.dragRotate.isActive();n&&!i&&t.fire(new ji("contextmenu",t,n)),n=null,o=!1,t.fire(new ji("mouseup",t,e));}),s.addEventListener(i,"mousemove",function(e){if(!t.dragPan.isActive()&&!t.dragRotate.isActive()){for(var n=e.toElement||e.target;n&&n!==i;)n=n.parentNode;n===i&&t.fire(new ji("mousemove",t,e));}}),s.addEventListener(i,"mouseover",function(e){for(var n=e.toElement||e.target;n&&n!==i;)n=n.parentNode;n===i&&t.fire(new ji("mouseover",t,e));}),s.addEventListener(i,"touchstart",function(i){var n=new $i("touchstart",t,i);t.fire(n),n.defaultPrevented||(e.interactive&&t.stop(),t.boxZoom.isActive()||t.dragRotate.isActive()||t.dragPan.onTouchStart(i),t.touchZoomRotate.onStart(i),t.doubleClickZoom.onTouchStart(n));},{passive:!1}),s.addEventListener(i,"touchmove",function(e){t.fire(new $i("touchmove",t,e));},{passive:!1}),s.addEventListener(i,"touchend",function(e){t.fire(new $i("touchend",t,e));}),s.addEventListener(i,"touchcancel",function(e){t.fire(new $i("touchcancel",t,e));}),s.addEventListener(i,"click",function(e){t.fire(new ji("click",t,e));}),s.addEventListener(i,"dblclick",function(e){var i=new ji("dblclick",t,e);t.fire(i),i.defaultPrevented||t.doubleClickZoom.onDblClick(i);}),s.addEventListener(i,"contextmenu",function(e){var i=t.dragRotate.isActive();o||i?o&&(n=e):t.fire(new ji("contextmenu",t,e)),e.preventDefault();}),s.addEventListener(i,"wheel",function(e){var i=new Gi("wheel",t,e);t.fire(i),i.defaultPrevented||t.scrollZoom.onWheel(e);},{passive:!1});}(this,e),this._hash=e.hash&&(new Vi).addTo(this),this._hash&&this._hash._onHashChange()||this.jumpTo({center:e.center,zoom:e.zoom,bearing:e.bearing,pitch:e.pitch}),this.resize(),e.style&&this.setStyle(e.style,{localIdeographFontFamily:e.localIdeographFontFamily}),e.attributionControl&&this.addControl(new an),this.addControl(new sn,e.logoPosition),this.on("style.load",function(){this.transform.unmodified&&this.jumpTo(this.style.stylesheet);}),this.on("data",this._onData),this.on("dataloading",this._onDataLoading);}i&&(n.__proto__=i),n.prototype=Object.create(i&&i.prototype),n.prototype.constructor=n;var o={showTileBoundaries:{configurable:!0},showCollisionBoxes:{configurable:!0},showOverdrawInspector:{configurable:!0},repaint:{configurable:!0},vertices:{configurable:!0}};return n.prototype.addControl=function(t,e){void 0===e&&t.getDefaultPosition&&(e=t.getDefaultPosition()),void 0===e&&(e="top-right");var i=t.onAdd(this),n=this._controlPositions[e];return-1!==e.indexOf("bottom")?n.insertBefore(i,n.firstChild):n.appendChild(i),this},n.prototype.removeControl=function(t){return t.onRemove(this),this},n.prototype.resize=function(e){var i=this._containerDimensions(),n=i[0],o=i[1];return this._resizeCanvas(n,o),this.transform.resize(n,o),this.painter.resize(n,o),this.fire(new t.Event("movestart",e)).fire(new t.Event("move",e)).fire(new t.Event("resize",e)).fire(new t.Event("moveend",e))},n.prototype.getBounds=function(){var e=new q(this.transform.pointLocation(new t.default$1(0,this.transform.height)),this.transform.pointLocation(new t.default$1(this.transform.width,0)));return(this.transform.angle||this.transform.pitch)&&(e.extend(this.transform.pointLocation(new t.default$1(this.transform.size.x,0))),e.extend(this.transform.pointLocation(new t.default$1(0,this.transform.size.y)))),e},n.prototype.getMaxBounds=function(){return this.transform.latRange&&2===this.transform.latRange.length&&this.transform.lngRange&&2===this.transform.lngRange.length?new q([this.transform.lngRange[0],this.transform.latRange[0]],[this.transform.lngRange[1],this.transform.latRange[1]]):null},n.prototype.setMaxBounds=function(t){if(t){var e=q.convert(t);this.transform.lngRange=[e.getWest(),e.getEast()],this.transform.latRange=[e.getSouth(),e.getNorth()],this.transform._constrain(),this._update();}else null==t&&(this.transform.lngRange=null,this.transform.latRange=null,this._update());return this},n.prototype.setMinZoom=function(t){if((t=null==t?0:t)>=0&&t<=this.transform.maxZoom)return this.transform.minZoom=t,this._update(),this.getZoom()<t&&this.setZoom(t),this;throw new Error("minZoom must be between 0 and the current maxZoom, inclusive")},n.prototype.getMinZoom=function(){return this.transform.minZoom},n.prototype.setMaxZoom=function(t){if((t=null==t?22:t)>=this.transform.minZoom)return this.transform.maxZoom=t,this._update(),this.getZoom()>t&&this.setZoom(t),this;throw new Error("maxZoom must be greater than the current minZoom")},n.prototype.getRenderWorldCopies=function(){return this.transform.renderWorldCopies},n.prototype.setRenderWorldCopies=function(t){return this.transform.renderWorldCopies=t,this._update(),this},n.prototype.getMaxZoom=function(){return this.transform.maxZoom},n.prototype.project=function(t){return this.transform.locationPoint(W.convert(t))},n.prototype.unproject=function(e){return this.transform.pointLocation(t.default$1.convert(e))},n.prototype.isMoving=function(){return this._moving||this.dragPan.isActive()||this.dragRotate.isActive()||this.scrollZoom.isActive()},n.prototype.isZooming=function(){return this._zooming||this.scrollZoom.isActive()},n.prototype.isRotating=function(){return this._rotating||this.dragRotate.isActive()},n.prototype.on=function(t,e,n){var o,r=this;if(void 0===n)return i.prototype.on.call(this,t,e);var a=function(){if("mouseenter"===t||"mouseover"===t){var i=!1;return{layer:e,listener:n,delegates:{mousemove:function(o){var a=r.getLayer(e)?r.queryRenderedFeatures(o.point,{layers:[e]}):[];a.length?i||(i=!0,n.call(r,new ji(t,r,o.originalEvent,{features:a}))):i=!1;},mouseout:function(){i=!1;}}}}if("mouseleave"===t||"mouseout"===t){var a=!1;return{layer:e,listener:n,delegates:{mousemove:function(i){(r.getLayer(e)?r.queryRenderedFeatures(i.point,{layers:[e]}):[]).length?a=!0:a&&(a=!1,n.call(r,new ji(t,r,i.originalEvent)));},mouseout:function(e){a&&(a=!1,n.call(r,new ji(t,r,e.originalEvent)));}}}}return{layer:e,listener:n,delegates:(o={},o[t]=function(t){var i=r.getLayer(e)?r.queryRenderedFeatures(t.point,{layers:[e]}):[];i.length&&(t.features=i,n.call(r,t),delete t.features);},o)}}();for(var s in this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[t]=this._delegatedListeners[t]||[],this._delegatedListeners[t].push(a),a.delegates)r.on(s,a.delegates[s]);return this},n.prototype.off=function(t,e,n){if(void 0===n)return i.prototype.off.call(this,t,e);if(this._delegatedListeners&&this._delegatedListeners[t])for(var o=this._delegatedListeners[t],r=0;r<o.length;r++){var a=o[r];if(a.layer===e&&a.listener===n){for(var s in a.delegates)this.off(s,a.delegates[s]);return o.splice(r,1),this}}return this},n.prototype.queryRenderedFeatures=function(e,i){var n;return 2===arguments.length?(e=arguments[0],i=arguments[1]):1===arguments.length&&((n=arguments[0])instanceof t.default$1||Array.isArray(n))?(e=arguments[0],i={}):1===arguments.length?(e=void 0,i=arguments[0]):(e=void 0,i={}),this.style?this.style.queryRenderedFeatures(this._makeQueryGeometry(e),i,this.transform):[]},n.prototype._makeQueryGeometry=function(e){var i,n=this;if(void 0===e&&(e=[t.default$1.convert([0,0]),t.default$1.convert([this.transform.width,this.transform.height])]),e instanceof t.default$1||"number"==typeof e[0]){i=[t.default$1.convert(e)];}else{var o=[t.default$1.convert(e[0]),t.default$1.convert(e[1])];i=[o[0],new t.default$1(o[1].x,o[0].y),o[1],new t.default$1(o[0].x,o[1].y),o[0]];}return{viewport:i,worldCoordinate:i.map(function(t){return n.transform.pointCoordinate(t)})}},n.prototype.querySourceFeatures=function(t,e){return this.style.querySourceFeatures(t,e)},n.prototype.setStyle=function(e,i){if((!i||!1!==i.diff&&!i.localIdeographFontFamily)&&this.style&&e&&"object"==typeof e)try{return this.style.setState(e)&&this._update(!0),this}catch(e){t.warnOnce("Unable to perform style diff: "+(e.message||e.error||e)+".  Rebuilding the style from scratch.");}return this.style&&(this.style.setEventedParent(null),this.style._remove()),e?(this.style=new Qe(this,i||{}),this.style.setEventedParent(this,{style:this.style}),"string"==typeof e?this.style.loadURL(e):this.style.loadJSON(e),this):(delete this.style,this)},n.prototype.getStyle=function(){if(this.style)return this.style.serialize()},n.prototype.isStyleLoaded=function(){return this.style?this.style.loaded():t.warnOnce("There is no style added to the map.")},n.prototype.addSource=function(t,e){return this.style.addSource(t,e),this._update(!0),this},n.prototype.isSourceLoaded=function(e){var i=this.style&&this.style.sourceCaches[e];if(void 0!==i)return i.loaded();this.fire(new t.ErrorEvent(new Error("There is no source with ID '"+e+"'")));},n.prototype.areTilesLoaded=function(){var t=this.style&&this.style.sourceCaches;for(var e in t){var i=t[e]._tiles;for(var n in i){var o=i[n];if("loaded"!==o.state&&"errored"!==o.state)return!1}}return!0},n.prototype.addSourceType=function(t,e,i){return this.style.addSourceType(t,e,i)},n.prototype.removeSource=function(t){return this.style.removeSource(t),this._update(!0),this},n.prototype.getSource=function(t){return this.style.getSource(t)},n.prototype.addImage=function(e,i,n){void 0===n&&(n={});var o=n.pixelRatio;void 0===o&&(o=1);var a=n.sdf;if(void 0===a&&(a=!1),i instanceof cn){var s=r.getImageData(i),l=s.width,c=s.height,u=s.data;this.style.addImage(e,{data:new t.RGBAImage({width:l,height:c},u),pixelRatio:o,sdf:a});}else{if(void 0===i.width||void 0===i.height)return this.fire(new t.ErrorEvent(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));var h=i.width,p=i.height,d=i.data;this.style.addImage(e,{data:new t.RGBAImage({width:h,height:p},d.slice(0)),pixelRatio:o,sdf:a});}},n.prototype.hasImage=function(e){return e?!!this.style.getImage(e):(this.fire(new t.ErrorEvent(new Error("Missing required image id"))),!1)},n.prototype.removeImage=function(t){this.style.removeImage(t);},n.prototype.loadImage=function(e,i){t.getImage(this._transformRequest(e,t.ResourceType.Image),i);},n.prototype.addLayer=function(t,e){return this.style.addLayer(t,e),this._update(!0),this},n.prototype.moveLayer=function(t,e){return this.style.moveLayer(t,e),this._update(!0),this},n.prototype.removeLayer=function(t){return this.style.removeLayer(t),this._update(!0),this},n.prototype.getLayer=function(t){return this.style.getLayer(t)},n.prototype.setFilter=function(t,e){return this.style.setFilter(t,e),this._update(!0),this},n.prototype.setLayerZoomRange=function(t,e,i){return this.style.setLayerZoomRange(t,e,i),this._update(!0),this},n.prototype.getFilter=function(t){return this.style.getFilter(t)},n.prototype.setPaintProperty=function(t,e,i){return this.style.setPaintProperty(t,e,i),this._update(!0),this},n.prototype.getPaintProperty=function(t,e){return this.style.getPaintProperty(t,e)},n.prototype.setLayoutProperty=function(t,e,i){return this.style.setLayoutProperty(t,e,i),this._update(!0),this},n.prototype.getLayoutProperty=function(t,e){return this.style.getLayoutProperty(t,e)},n.prototype.setLight=function(t){return this.style.setLight(t),this._update(!0),this},n.prototype.getLight=function(){return this.style.getLight()},n.prototype.getContainer=function(){return this._container},n.prototype.getCanvasContainer=function(){return this._canvasContainer},n.prototype.getCanvas=function(){return this._canvas},n.prototype._containerDimensions=function(){var t=0,e=0;return this._container&&(t=this._container.offsetWidth||400,e=this._container.offsetHeight||300),[t,e]},n.prototype._setupContainer=function(){var t=this._container;t.classList.add("mapboxgl-map"),(this._missingCSSContainer=s.create("div","mapboxgl-missing-css",t)).innerHTML="Missing Mapbox GL JS CSS";var e=this._canvasContainer=s.create("div","mapboxgl-canvas-container",t);this._interactive&&e.classList.add("mapboxgl-interactive"),this._canvas=s.create("canvas","mapboxgl-canvas",e),this._canvas.style.position="absolute",this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("tabindex","0"),this._canvas.setAttribute("aria-label","Map");var i=this._containerDimensions();this._resizeCanvas(i[0],i[1]);var n=this._controlContainer=s.create("div","mapboxgl-control-container",t),o=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach(function(t){o[t]=s.create("div","mapboxgl-ctrl-"+t,n);});},n.prototype._resizeCanvas=function(e,i){var n=t.default.devicePixelRatio||1;this._canvas.width=n*e,this._canvas.height=n*i,this._canvas.style.width=e+"px",this._canvas.style.height=i+"px";},n.prototype._setupPainter=function(){var i=t.extend({failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer},e.webGLContextAttributes),n=this._canvas.getContext("webgl",i)||this._canvas.getContext("experimental-webgl",i);n?this.painter=new Li(n,this.transform):this.fire(new t.ErrorEvent(new Error("Failed to initialize WebGL")));},n.prototype._contextLost=function(e){e.preventDefault(),this._frameId&&(r.cancelFrame(this._frameId),this._frameId=null),this.fire(new t.Event("webglcontextlost",{originalEvent:e}));},n.prototype._contextRestored=function(e){this._setupPainter(),this.resize(),this._update(),this.fire(new t.Event("webglcontextrestored",{originalEvent:e}));},n.prototype.loaded=function(){return!this._styleDirty&&!this._sourcesDirty&&!(!this.style||!this.style.loaded())},n.prototype._update=function(t){this.style&&(this._styleDirty=this._styleDirty||t,this._sourcesDirty=!0,this._rerender());},n.prototype._requestRenderFrame=function(t){return this._update(),this._renderTaskQueue.add(t)},n.prototype._cancelRenderFrame=function(t){this._renderTaskQueue.remove(t);},n.prototype._render=function(){this._renderTaskQueue.run();var e=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;var i=this.transform.zoom,n=r.now();this.style.zoomHistory.update(i,n);var o=new t.default$16(i,{now:n,fadeDuration:this._fadeDuration,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),a=o.crossFadingFactor();1===a&&a===this._crossFadingFactor||(e=!0,this._crossFadingFactor=a),this.style.update(o);}return this.style&&this._sourcesDirty&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this._placementDirty=this.style&&this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,this._fadeDuration),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),fadeDuration:this._fadeDuration}),this.fire(new t.Event("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,this.fire(new t.Event("load"))),this.style&&(this.style.hasTransitions()||e)&&(this._styleDirty=!0),(this._sourcesDirty||this._repaint||this._styleDirty||this._placementDirty)&&this._rerender(),this},n.prototype.remove=function(){this._hash&&this._hash.remove(),r.cancelFrame(this._frameId),this._renderTaskQueue.clear(),this._frameId=null,this.setStyle(null),void 0!==t.default&&(t.default.removeEventListener("resize",this._onWindowResize,!1),t.default.removeEventListener("online",this._onWindowOnline,!1));var e=this.painter.context.gl.getExtension("WEBGL_lose_context");e&&e.loseContext(),dn(this._canvasContainer),dn(this._controlContainer),dn(this._missingCSSContainer),this._container.classList.remove("mapboxgl-map"),this.fire(new t.Event("remove"));},n.prototype._rerender=function(){var t=this;this.style&&!this._frameId&&(this._frameId=r.frame(function(){t._frameId=null,t._render();}));},n.prototype._onWindowOnline=function(){this._update();},n.prototype._onWindowResize=function(){this._trackResize&&this.stop().resize()._update();},o.showTileBoundaries.get=function(){return!!this._showTileBoundaries},o.showTileBoundaries.set=function(t){this._showTileBoundaries!==t&&(this._showTileBoundaries=t,this._update());},o.showCollisionBoxes.get=function(){return!!this._showCollisionBoxes},o.showCollisionBoxes.set=function(t){this._showCollisionBoxes!==t&&(this._showCollisionBoxes=t,t?this.style._generateCollisionBoxes():this._update());},o.showOverdrawInspector.get=function(){return!!this._showOverdrawInspector},o.showOverdrawInspector.set=function(t){this._showOverdrawInspector!==t&&(this._showOverdrawInspector=t,this._update());},o.repaint.get=function(){return!!this._repaint},o.repaint.set=function(t){this._repaint=t,this._update();},o.vertices.get=function(){return!!this._vertices},o.vertices.set=function(t){this._vertices=t,this._update();},n.prototype._onData=function(e){this._update("style"===e.dataType),this.fire(new t.Event(e.dataType+"data",e));},n.prototype._onDataLoading=function(e){this.fire(new t.Event(e.dataType+"dataloading",e));},Object.defineProperties(n.prototype,o),n}(rn);function dn(t){t.parentNode&&t.parentNode.removeChild(t);}var fn={showCompass:!0,showZoom:!0},mn=function(e){var i=this;this.options=t.extend({},fn,e),this._container=s.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",function(t){return t.preventDefault()}),this.options.showZoom&&(this._zoomInButton=this._createButton("mapboxgl-ctrl-icon mapboxgl-ctrl-zoom-in","Zoom In",function(){return i._map.zoomIn()}),this._zoomOutButton=this._createButton("mapboxgl-ctrl-icon mapboxgl-ctrl-zoom-out","Zoom Out",function(){return i._map.zoomOut()})),this.options.showCompass&&(t.bindAll(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-icon mapboxgl-ctrl-compass","Reset North",function(){return i._map.resetNorth()}),this._compassArrow=s.create("span","mapboxgl-ctrl-compass-arrow",this._compass));};function _n(t,e,i){if(t=new W(t.lng,t.lat),e){var n=new W(t.lng-360,t.lat),o=new W(t.lng+360,t.lat),r=i.locationPoint(t).distSqr(e);i.locationPoint(n).distSqr(e)<r?t=n:i.locationPoint(o).distSqr(e)<r&&(t=o);}for(;Math.abs(t.lng-i.center.lng)>180;){var a=i.locationPoint(t);if(a.x>=0&&a.y>=0&&a.x<=i.width&&a.y<=i.height)break;t.lng>i.center.lng?t.lng-=360:t.lng+=360;}return t}mn.prototype._rotateCompassArrow=function(){var t="rotate("+this._map.transform.angle*(180/Math.PI)+"deg)";this._compassArrow.style.transform=t;},mn.prototype.onAdd=function(t){return this._map=t,this.options.showCompass&&(this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new Hi(t,{button:"left",element:this._compass}),this._handler.enable()),this._container},mn.prototype.onRemove=function(){s.remove(this._container),this.options.showCompass&&(this._map.off("rotate",this._rotateCompassArrow),this._handler.disable(),delete this._handler),delete this._map;},mn.prototype._createButton=function(t,e,i){var n=s.create("button",t,this._container);return n.type="button",n.setAttribute("aria-label",e),n.addEventListener("click",i),n};var gn={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function vn(t,e,i){var n=t.classList;for(var o in gn)n.remove("mapboxgl-"+i+"-anchor-"+o);n.add("mapboxgl-"+i+"-anchor-"+e);}var yn=function(e){if((arguments[0]instanceof t.default.HTMLElement||2===arguments.length)&&(e=t.extend({element:e},arguments[1])),t.bindAll(["_update","_onMapClick"],this),this._anchor=e&&e.anchor||"center",this._color=e&&e.color||"#3FB1CE",e&&e.element)this._element=e.element,this._offset=t.default$1.convert(e&&e.offset||[0,0]);else{this._defaultMarker=!0,this._element=s.create("div");var i=s.createNS("http://www.w3.org/2000/svg","svg");i.setAttributeNS(null,"height","41px"),i.setAttributeNS(null,"width","27px"),i.setAttributeNS(null,"viewBox","0 0 27 41");var n=s.createNS("http://www.w3.org/2000/svg","g");n.setAttributeNS(null,"stroke","none"),n.setAttributeNS(null,"stroke-width","1"),n.setAttributeNS(null,"fill","none"),n.setAttributeNS(null,"fill-rule","evenodd");var o=s.createNS("http://www.w3.org/2000/svg","g");o.setAttributeNS(null,"fill-rule","nonzero");var r=s.createNS("http://www.w3.org/2000/svg","g");r.setAttributeNS(null,"transform","translate(3.0, 29.0)"),r.setAttributeNS(null,"fill","#000000");for(var a=0,l=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];a<l.length;a+=1){var c=l[a],u=s.createNS("http://www.w3.org/2000/svg","ellipse");u.setAttributeNS(null,"opacity","0.04"),u.setAttributeNS(null,"cx","10.5"),u.setAttributeNS(null,"cy","5.80029008"),u.setAttributeNS(null,"rx",c.rx),u.setAttributeNS(null,"ry",c.ry),r.appendChild(u);}var h=s.createNS("http://www.w3.org/2000/svg","g");h.setAttributeNS(null,"fill",this._color);var p=s.createNS("http://www.w3.org/2000/svg","path");p.setAttributeNS(null,"d","M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z"),h.appendChild(p);var d=s.createNS("http://www.w3.org/2000/svg","g");d.setAttributeNS(null,"opacity","0.25"),d.setAttributeNS(null,"fill","#000000");var f=s.createNS("http://www.w3.org/2000/svg","path");f.setAttributeNS(null,"d","M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z"),d.appendChild(f);var m=s.createNS("http://www.w3.org/2000/svg","g");m.setAttributeNS(null,"transform","translate(6.0, 7.0)"),m.setAttributeNS(null,"fill","#FFFFFF");var _=s.createNS("http://www.w3.org/2000/svg","g");_.setAttributeNS(null,"transform","translate(8.0, 8.0)");var g=s.createNS("http://www.w3.org/2000/svg","circle");g.setAttributeNS(null,"fill","#000000"),g.setAttributeNS(null,"opacity","0.25"),g.setAttributeNS(null,"cx","5.5"),g.setAttributeNS(null,"cy","5.5"),g.setAttributeNS(null,"r","5.4999962");var v=s.createNS("http://www.w3.org/2000/svg","circle");v.setAttributeNS(null,"fill","#FFFFFF"),v.setAttributeNS(null,"cx","5.5"),v.setAttributeNS(null,"cy","5.5"),v.setAttributeNS(null,"r","5.4999962"),_.appendChild(g),_.appendChild(v),o.appendChild(r),o.appendChild(h),o.appendChild(d),o.appendChild(m),o.appendChild(_),i.appendChild(o),this._element.appendChild(i),this._offset=t.default$1.convert(e&&e.offset||[0,-14]);}this._element.classList.add("mapboxgl-marker"),this._popup=null;};yn.prototype.addTo=function(t){return this.remove(),this._map=t,t.getCanvasContainer().appendChild(this._element),t.on("move",this._update),t.on("moveend",this._update),this._update(),this._map.on("click",this._onMapClick),this},yn.prototype.remove=function(){return this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),delete this._map),s.remove(this._element),this._popup&&this._popup.remove(),this},yn.prototype.getLngLat=function(){return this._lngLat},yn.prototype.setLngLat=function(t){return this._lngLat=W.convert(t),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this},yn.prototype.getElement=function(){return this._element},yn.prototype.setPopup=function(t){if(this._popup&&(this._popup.remove(),this._popup=null),t){if(!("offset"in t.options)){var e=Math.sqrt(Math.pow(13.5,2)/2);t.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[e,-1*(24.6+e)],"bottom-right":[-e,-1*(24.6+e)],left:[13.5,-24.6],right:[-13.5,-24.6]}:this._offset;}this._popup=t,this._lngLat&&this._popup.setLngLat(this._lngLat);}return this},yn.prototype._onMapClick=function(t){var e=t.originalEvent.target,i=this._element;this._popup&&(e===i||i.contains(e))&&this.togglePopup();},yn.prototype.getPopup=function(){return this._popup},yn.prototype.togglePopup=function(){var t=this._popup;return t?(t.isOpen()?t.remove():t.addTo(this._map),this):this},yn.prototype._update=function(t){this._map&&(this._map.transform.renderWorldCopies&&(this._lngLat=_n(this._lngLat,this._pos,this._map.transform)),this._pos=this._map.project(this._lngLat)._add(this._offset),t&&"moveend"!==t.type||(this._pos=this._pos.round()),s.setTransform(this._element,gn[this._anchor]+" translate("+this._pos.x+"px, "+this._pos.y+"px)"),vn(this._element,this._anchor,"marker"));},yn.prototype.getOffset=function(){return this._offset},yn.prototype.setOffset=function(e){return this._offset=t.default$1.convert(e),this._update(),this};var xn,bn={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showUserLocation:!0};var wn=function(e){function i(i){e.call(this),this.options=t.extend({},bn,i),t.bindAll(["_onSuccess","_onError","_finish","_setupUI","_updateCamera","_updateMarker"],this);}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.onAdd=function(e){var i;return this._map=e,this._container=s.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),i=this._setupUI,void 0!==xn?i(xn):void 0!==t.default.navigator.permissions?t.default.navigator.permissions.query({name:"geolocation"}).then(function(t){xn="denied"!==t.state,i(xn);}):(xn=!!t.default.navigator.geolocation,i(xn)),this._container},i.prototype.onRemove=function(){void 0!==this._geolocationWatchID&&(t.default.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker.remove(),s.remove(this._container),this._map=void 0;},i.prototype._onSuccess=function(e){if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove("mapboxgl-user-location-dot-stale"),this.fire(new t.Event("geolocate",e)),this._finish();},i.prototype._updateCamera=function(t){var e=new W(t.coords.longitude,t.coords.latitude),i=t.coords.accuracy;this._map.fitBounds(e.toBounds(i),this.options.fitBoundsOptions,{geolocateSource:!0});},i.prototype._updateMarker=function(t){t?this._userLocationDotMarker.setLngLat([t.coords.longitude,t.coords.latitude]).addTo(this._map):this._userLocationDotMarker.remove();},i.prototype._onError=function(e){if(this.options.trackUserLocation)if(1===e.code)this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),void 0!==this._geolocationWatchID&&this._clearWatch();else switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("mapboxgl-user-location-dot-stale"),this.fire(new t.Event("error",e)),this._finish();},i.prototype._finish=function(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0;},i.prototype._setupUI=function(e){var i=this;!1!==e&&(this._container.addEventListener("contextmenu",function(t){return t.preventDefault()}),this._geolocateButton=s.create("button","mapboxgl-ctrl-icon mapboxgl-ctrl-geolocate",this._container),this._geolocateButton.type="button",this._geolocateButton.setAttribute("aria-label","Geolocate"),this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=s.create("div","mapboxgl-user-location-dot"),this._userLocationDotMarker=new yn(this._dotElement),this.options.trackUserLocation&&(this._watchState="OFF")),this._geolocateButton.addEventListener("click",this.trigger.bind(this)),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",function(e){e.geolocateSource||"ACTIVE_LOCK"!==i._watchState||(i._watchState="BACKGROUND",i._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),i._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),i.fire(new t.Event("trackuserlocationend")));}));},i.prototype.trigger=function(){if(!this._setup)return t.warnOnce("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new t.Event("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this.fire(new t.Event("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new t.Event("trackuserlocationstart"));}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"BACKGROUND":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");break;case"BACKGROUND_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error");}"OFF"===this._watchState&&void 0!==this._geolocationWatchID?this._clearWatch():void 0===this._geolocationWatchID&&(this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),this._geolocationWatchID=t.default.navigator.geolocation.watchPosition(this._onSuccess,this._onError,this.options.positionOptions));}else t.default.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return!0},i.prototype._clearWatch=function(){t.default.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null);},i}(t.Evented),En={maxWidth:100,unit:"metric"},Tn=function(e){this.options=t.extend({},En,e),t.bindAll(["_onMove","setUnit"],this);};function In(t,e,i){var n,o,r,a,s,l,c=i&&i.maxWidth||100,u=t._container.clientHeight/2,h=(n=t.unproject([0,u]),o=t.unproject([c,u]),r=Math.PI/180,a=n.lat*r,s=o.lat*r,l=Math.sin(a)*Math.sin(s)+Math.cos(a)*Math.cos(s)*Math.cos((o.lng-n.lng)*r),6371e3*Math.acos(Math.min(l,1)));if(i&&"imperial"===i.unit){var p=3.2808*h;if(p>5280)Cn(e,c,p/5280,"mi");else Cn(e,c,p,"ft");}else if(i&&"nautical"===i.unit){Cn(e,c,h/1852,"nm");}else Cn(e,c,h,"m");}function Cn(t,e,i,n){var o,r,a,s=(o=i,(r=Math.pow(10,(""+Math.floor(o)).length-1))*(a=(a=o/r)>=10?10:a>=5?5:a>=3?3:a>=2?2:1)),l=s/i;"m"===n&&s>=1e3&&(s/=1e3,n="km"),t.style.width=e*l+"px",t.innerHTML=s+n;}Tn.prototype.getDefaultPosition=function(){return"bottom-left"},Tn.prototype._onMove=function(){In(this._map,this._container,this.options);},Tn.prototype.onAdd=function(t){return this._map=t,this._container=s.create("div","mapboxgl-ctrl mapboxgl-ctrl-scale",t.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container},Tn.prototype.onRemove=function(){s.remove(this._container),this._map.off("move",this._onMove),this._map=void 0;},Tn.prototype.setUnit=function(t){this.options.unit=t,In(this._map,this._container,this.options);};var Sn=function(){this._fullscreen=!1,t.bindAll(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in t.default.document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in t.default.document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in t.default.document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in t.default.document&&(this._fullscreenchange="MSFullscreenChange"),this._className="mapboxgl-ctrl";};Sn.prototype.onAdd=function(e){return this._map=e,this._mapContainer=this._map.getContainer(),this._container=s.create("div",this._className+" mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._container.style.display="none",t.warnOnce("This device does not support fullscreen mode.")),this._container},Sn.prototype.onRemove=function(){s.remove(this._container),this._map=null,t.default.document.removeEventListener(this._fullscreenchange,this._changeIcon);},Sn.prototype._checkFullscreenSupport=function(){return!!(t.default.document.fullscreenEnabled||t.default.document.mozFullScreenEnabled||t.default.document.msFullscreenEnabled||t.default.document.webkitFullscreenEnabled)},Sn.prototype._setupUI=function(){var e=this._fullscreenButton=s.create("button",this._className+"-icon "+this._className+"-fullscreen",this._container);e.setAttribute("aria-label","Toggle fullscreen"),e.type="button",this._fullscreenButton.addEventListener("click",this._onClickFullscreen),t.default.document.addEventListener(this._fullscreenchange,this._changeIcon);},Sn.prototype._isFullscreen=function(){return this._fullscreen},Sn.prototype._changeIcon=function(){(t.default.document.fullscreenElement||t.default.document.mozFullScreenElement||t.default.document.webkitFullscreenElement||t.default.document.msFullscreenElement)===this._mapContainer!==this._fullscreen&&(this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle(this._className+"-shrink"),this._fullscreenButton.classList.toggle(this._className+"-fullscreen"));},Sn.prototype._onClickFullscreen=function(){this._isFullscreen()?t.default.document.exitFullscreen?t.default.document.exitFullscreen():t.default.document.mozCancelFullScreen?t.default.document.mozCancelFullScreen():t.default.document.msExitFullscreen?t.default.document.msExitFullscreen():t.default.document.webkitCancelFullScreen&&t.default.document.webkitCancelFullScreen():this._mapContainer.requestFullscreen?this._mapContainer.requestFullscreen():this._mapContainer.mozRequestFullScreen?this._mapContainer.mozRequestFullScreen():this._mapContainer.msRequestFullscreen?this._mapContainer.msRequestFullscreen():this._mapContainer.webkitRequestFullscreen&&this._mapContainer.webkitRequestFullscreen();};var zn={closeButton:!0,closeOnClick:!0},An=function(e){function i(i){e.call(this),this.options=t.extend(Object.create(zn),i),t.bindAll(["_update","_onClickClose"],this);}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.addTo=function(e){return this._map=e,this._map.on("move",this._update),this.options.closeOnClick&&this._map.on("click",this._onClickClose),this._update(),this.fire(new t.Event("open")),this},i.prototype.isOpen=function(){return!!this._map},i.prototype.remove=function(){return this._content&&s.remove(this._content),this._container&&(s.remove(this._container),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("click",this._onClickClose),delete this._map),this.fire(new t.Event("close")),this},i.prototype.getLngLat=function(){return this._lngLat},i.prototype.setLngLat=function(t){return this._lngLat=W.convert(t),this._pos=null,this._update(),this},i.prototype.setText=function(e){return this.setDOMContent(t.default.document.createTextNode(e))},i.prototype.setHTML=function(e){var i,n=t.default.document.createDocumentFragment(),o=t.default.document.createElement("body");for(o.innerHTML=e;i=o.firstChild;)n.appendChild(i);return this.setDOMContent(n)},i.prototype.setDOMContent=function(t){return this._createContent(),this._content.appendChild(t),this._update(),this},i.prototype._createContent=function(){this._content&&s.remove(this._content),this._content=s.create("div","mapboxgl-popup-content",this._container),this.options.closeButton&&(this._closeButton=s.create("button","mapboxgl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.setAttribute("aria-label","Close popup"),this._closeButton.innerHTML="&#215;",this._closeButton.addEventListener("click",this._onClickClose));},i.prototype._update=function(){if(this._map&&this._lngLat&&this._content){this._container||(this._container=s.create("div","mapboxgl-popup",this._map.getContainer()),this._tip=s.create("div","mapboxgl-popup-tip",this._container),this._container.appendChild(this._content)),this._map.transform.renderWorldCopies&&(this._lngLat=_n(this._lngLat,this._pos,this._map.transform));var e=this._pos=this._map.project(this._lngLat),i=this.options.anchor,n=function e(i){if(i){if("number"==typeof i){var n=Math.round(Math.sqrt(.5*Math.pow(i,2)));return{center:new t.default$1(0,0),top:new t.default$1(0,i),"top-left":new t.default$1(n,n),"top-right":new t.default$1(-n,n),bottom:new t.default$1(0,-i),"bottom-left":new t.default$1(n,-n),"bottom-right":new t.default$1(-n,-n),left:new t.default$1(i,0),right:new t.default$1(-i,0)}}if(i instanceof t.default$1||Array.isArray(i)){var o=t.default$1.convert(i);return{center:o,top:o,"top-left":o,"top-right":o,bottom:o,"bottom-left":o,"bottom-right":o,left:o,right:o}}return{center:t.default$1.convert(i.center||[0,0]),top:t.default$1.convert(i.top||[0,0]),"top-left":t.default$1.convert(i["top-left"]||[0,0]),"top-right":t.default$1.convert(i["top-right"]||[0,0]),bottom:t.default$1.convert(i.bottom||[0,0]),"bottom-left":t.default$1.convert(i["bottom-left"]||[0,0]),"bottom-right":t.default$1.convert(i["bottom-right"]||[0,0]),left:t.default$1.convert(i.left||[0,0]),right:t.default$1.convert(i.right||[0,0])}}return e(new t.default$1(0,0))}(this.options.offset);if(!i){var o,r=this._container.offsetWidth,a=this._container.offsetHeight;o=e.y+n.bottom.y<a?["top"]:e.y>this._map.transform.height-a?["bottom"]:[],e.x<r/2?o.push("left"):e.x>this._map.transform.width-r/2&&o.push("right"),i=0===o.length?"bottom":o.join("-");}var l=e.add(n[i]).round();s.setTransform(this._container,gn[i]+" translate("+l.x+"px,"+l.y+"px)"),vn(this._container,i,"popup");}},i.prototype._onClickClose=function(){this.remove();},i}(t.Evented);var Rn={version:"0.45.0",supported:e,workerCount:Math.max(Math.floor(r.hardwareConcurrency/2),1),setRTLTextPlugin:t.setRTLTextPlugin,Map:pn,NavigationControl:mn,GeolocateControl:wn,AttributionControl:an,ScaleControl:Tn,FullscreenControl:Sn,Popup:An,Marker:yn,Style:Qe,LngLat:W,LngLatBounds:q,Point:t.default$1,Evented:t.Evented,config:_,get accessToken(){return _.ACCESS_TOKEN},set accessToken(t){_.ACCESS_TOKEN=t;},workerUrl:""};return Rn});

//

return mapboxgl;

})));


}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],413:[function(_dereq_,module,exports){
'use strict'

module.exports = createTable

var chull = _dereq_('convex-hull')

function constructVertex(d, a, b) {
  var x = new Array(d)
  for(var i=0; i<d; ++i) {
    x[i] = 0.0
    if(i === a) {
      x[i] += 0.5
    }
    if(i === b) {
      x[i] += 0.5
    }
  }
  return x
}

function constructCell(dimension, mask) {
  if(mask === 0 || mask === (1<<(dimension+1))-1) {
    return []
  }
  var points = []
  var index  = []
  for(var i=0; i<=dimension; ++i) {
    if(mask & (1<<i)) {
      points.push(constructVertex(dimension, i-1, i-1))
      index.push(null)
      for(var j=0; j<=dimension; ++j) {
        if(~mask & (1<<j)) {
          points.push(constructVertex(dimension, i-1, j-1))
          index.push([i,j])
        }
      }
    }
  }
  
  //Preprocess points so first d+1 points are linearly independent
  var hull = chull(points)
  var faces = []
i_loop:
  for(var i=0; i<hull.length; ++i) {
    var face = hull[i]
    var nface = []
    for(var j=0; j<face.length; ++j) {
      if(!index[face[j]]) {
        continue i_loop
      }
      nface.push(index[face[j]].slice())
    }
    faces.push(nface)
  }
  return faces
}

function createTable(dimension) {
  var numCells = 1<<(dimension+1)
  var result = new Array(numCells)
  for(var i=0; i<numCells; ++i) {
    result[i] = constructCell(dimension, i)
  }
  return result
}
},{"convex-hull":119}],414:[function(_dereq_,module,exports){
/*jshint unused:true*/
/*
Input:  matrix      ; a 4x4 matrix
Output: translation ; a 3 component vector
        scale       ; a 3 component vector
        skew        ; skew factors XY,XZ,YZ represented as a 3 component vector
        perspective ; a 4 component vector
        quaternion  ; a 4 component vector
Returns false if the matrix cannot be decomposed, true if it can


References:
https://github.com/kamicane/matrix3d/blob/master/lib/Matrix3d.js
https://github.com/ChromiumWebApps/chromium/blob/master/ui/gfx/transform_util.cc
http://www.w3.org/TR/css3-transforms/#decomposing-a-3d-matrix
*/

var normalize = _dereq_('./normalize')

var create = _dereq_('gl-mat4/create')
var clone = _dereq_('gl-mat4/clone')
var determinant = _dereq_('gl-mat4/determinant')
var invert = _dereq_('gl-mat4/invert')
var transpose = _dereq_('gl-mat4/transpose')
var vec3 = {
    length: _dereq_('gl-vec3/length'),
    normalize: _dereq_('gl-vec3/normalize'),
    dot: _dereq_('gl-vec3/dot'),
    cross: _dereq_('gl-vec3/cross')
}

var tmp = create()
var perspectiveMatrix = create()
var tmpVec4 = [0, 0, 0, 0]
var row = [ [0,0,0], [0,0,0], [0,0,0] ]
var pdum3 = [0,0,0]

module.exports = function decomposeMat4(matrix, translation, scale, skew, perspective, quaternion) {
    if (!translation) translation = [0,0,0]
    if (!scale) scale = [0,0,0]
    if (!skew) skew = [0,0,0]
    if (!perspective) perspective = [0,0,0,1]
    if (!quaternion) quaternion = [0,0,0,1]

    //normalize, if not possible then bail out early
    if (!normalize(tmp, matrix))
        return false

    // perspectiveMatrix is used to solve for perspective, but it also provides
    // an easy way to test for singularity of the upper 3x3 component.
    clone(perspectiveMatrix, tmp)

    perspectiveMatrix[3] = 0
    perspectiveMatrix[7] = 0
    perspectiveMatrix[11] = 0
    perspectiveMatrix[15] = 1

    // If the perspectiveMatrix is not invertible, we are also unable to
    // decompose, so we'll bail early. Constant taken from SkMatrix44::invert.
    if (Math.abs(determinant(perspectiveMatrix) < 1e-8))
        return false

    var a03 = tmp[3], a13 = tmp[7], a23 = tmp[11],
            a30 = tmp[12], a31 = tmp[13], a32 = tmp[14], a33 = tmp[15]

    // First, isolate perspective.
    if (a03 !== 0 || a13 !== 0 || a23 !== 0) {
        tmpVec4[0] = a03
        tmpVec4[1] = a13
        tmpVec4[2] = a23
        tmpVec4[3] = a33

        // Solve the equation by inverting perspectiveMatrix and multiplying
        // rightHandSide by the inverse.
        // resuing the perspectiveMatrix here since it's no longer needed
        var ret = invert(perspectiveMatrix, perspectiveMatrix)
        if (!ret) return false
        transpose(perspectiveMatrix, perspectiveMatrix)

        //multiply by transposed inverse perspective matrix, into perspective vec4
        vec4multMat4(perspective, tmpVec4, perspectiveMatrix)
    } else { 
        //no perspective
        perspective[0] = perspective[1] = perspective[2] = 0
        perspective[3] = 1
    }

    // Next take care of translation
    translation[0] = a30
    translation[1] = a31
    translation[2] = a32

    // Now get scale and shear. 'row' is a 3 element array of 3 component vectors
    mat3from4(row, tmp)

    // Compute X scale factor and normalize first row.
    scale[0] = vec3.length(row[0])
    vec3.normalize(row[0], row[0])

    // Compute XY shear factor and make 2nd row orthogonal to 1st.
    skew[0] = vec3.dot(row[0], row[1])
    combine(row[1], row[1], row[0], 1.0, -skew[0])

    // Now, compute Y scale and normalize 2nd row.
    scale[1] = vec3.length(row[1])
    vec3.normalize(row[1], row[1])
    skew[0] /= scale[1]

    // Compute XZ and YZ shears, orthogonalize 3rd row
    skew[1] = vec3.dot(row[0], row[2])
    combine(row[2], row[2], row[0], 1.0, -skew[1])
    skew[2] = vec3.dot(row[1], row[2])
    combine(row[2], row[2], row[1], 1.0, -skew[2])

    // Next, get Z scale and normalize 3rd row.
    scale[2] = vec3.length(row[2])
    vec3.normalize(row[2], row[2])
    skew[1] /= scale[2]
    skew[2] /= scale[2]


    // At this point, the matrix (in rows) is orthonormal.
    // Check for a coordinate system flip.  If the determinant
    // is -1, then negate the matrix and the scaling factors.
    vec3.cross(pdum3, row[1], row[2])
    if (vec3.dot(row[0], pdum3) < 0) {
        for (var i = 0; i < 3; i++) {
            scale[i] *= -1;
            row[i][0] *= -1
            row[i][1] *= -1
            row[i][2] *= -1
        }
    }

    // Now, get the rotations out
    quaternion[0] = 0.5 * Math.sqrt(Math.max(1 + row[0][0] - row[1][1] - row[2][2], 0))
    quaternion[1] = 0.5 * Math.sqrt(Math.max(1 - row[0][0] + row[1][1] - row[2][2], 0))
    quaternion[2] = 0.5 * Math.sqrt(Math.max(1 - row[0][0] - row[1][1] + row[2][2], 0))
    quaternion[3] = 0.5 * Math.sqrt(Math.max(1 + row[0][0] + row[1][1] + row[2][2], 0))

    if (row[2][1] > row[1][2])
        quaternion[0] = -quaternion[0]
    if (row[0][2] > row[2][0])
        quaternion[1] = -quaternion[1]
    if (row[1][0] > row[0][1])
        quaternion[2] = -quaternion[2]
    return true
}

//will be replaced by gl-vec4 eventually
function vec4multMat4(out, a, m) {
    var x = a[0], y = a[1], z = a[2], w = a[3];
    out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
    out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
    out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
    out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
    return out;
}

//gets upper-left of a 4x4 matrix into a 3x3 of vectors
function mat3from4(out, mat4x4) {
    out[0][0] = mat4x4[0]
    out[0][1] = mat4x4[1]
    out[0][2] = mat4x4[2]
    
    out[1][0] = mat4x4[4]
    out[1][1] = mat4x4[5]
    out[1][2] = mat4x4[6]

    out[2][0] = mat4x4[8]
    out[2][1] = mat4x4[9]
    out[2][2] = mat4x4[10]
}

function combine(out, a, b, scale1, scale2) {
    out[0] = a[0] * scale1 + b[0] * scale2
    out[1] = a[1] * scale1 + b[1] * scale2
    out[2] = a[2] * scale1 + b[2] * scale2
}
},{"./normalize":415,"gl-mat4/clone":250,"gl-mat4/create":251,"gl-mat4/determinant":252,"gl-mat4/invert":256,"gl-mat4/transpose":266,"gl-vec3/cross":320,"gl-vec3/dot":325,"gl-vec3/length":335,"gl-vec3/normalize":342}],415:[function(_dereq_,module,exports){
module.exports = function normalize(out, mat) {
    var m44 = mat[15]
    // Cannot normalize.
    if (m44 === 0) 
        return false
    var scale = 1 / m44
    for (var i=0; i<16; i++)
        out[i] = mat[i] * scale
    return true
}
},{}],416:[function(_dereq_,module,exports){
var lerp = _dereq_('gl-vec3/lerp')

var recompose = _dereq_('mat4-recompose')
var decompose = _dereq_('mat4-decompose')
var determinant = _dereq_('gl-mat4/determinant')
var slerp = _dereq_('quat-slerp')

var state0 = state()
var state1 = state()
var tmp = state()

module.exports = interpolate
function interpolate(out, start, end, alpha) {
    if (determinant(start) === 0 || determinant(end) === 0)
        return false

    //decompose the start and end matrices into individual components
    var r0 = decompose(start, state0.translate, state0.scale, state0.skew, state0.perspective, state0.quaternion)
    var r1 = decompose(end, state1.translate, state1.scale, state1.skew, state1.perspective, state1.quaternion)
    if (!r0 || !r1)
        return false    


    //now lerp/slerp the start and end components into a temporary     lerp(tmptranslate, state0.translate, state1.translate, alpha)
    lerp(tmp.translate, state0.translate, state1.translate, alpha)
    lerp(tmp.skew, state0.skew, state1.skew, alpha)
    lerp(tmp.scale, state0.scale, state1.scale, alpha)
    lerp(tmp.perspective, state0.perspective, state1.perspective, alpha)
    slerp(tmp.quaternion, state0.quaternion, state1.quaternion, alpha)

    //and recompose into our 'out' matrix
    recompose(out, tmp.translate, tmp.scale, tmp.skew, tmp.perspective, tmp.quaternion)
    return true
}

function state() {
    return {
        translate: vec3(),
        scale: vec3(1),
        skew: vec3(),
        perspective: vec4(),
        quaternion: vec4()
    }
}

function vec3(n) {
    return [n||0,n||0,n||0]
}

function vec4() {
    return [0,0,0,1]
}
},{"gl-mat4/determinant":252,"gl-vec3/lerp":336,"mat4-decompose":414,"mat4-recompose":417,"quat-slerp":469}],417:[function(_dereq_,module,exports){
/*
Input:  translation ; a 3 component vector
        scale       ; a 3 component vector
        skew        ; skew factors XY,XZ,YZ represented as a 3 component vector
        perspective ; a 4 component vector
        quaternion  ; a 4 component vector
Output: matrix      ; a 4x4 matrix

From: http://www.w3.org/TR/css3-transforms/#recomposing-to-a-3d-matrix
*/

var mat4 = {
    identity: _dereq_('gl-mat4/identity'),
    translate: _dereq_('gl-mat4/translate'),
    multiply: _dereq_('gl-mat4/multiply'),
    create: _dereq_('gl-mat4/create'),
    scale: _dereq_('gl-mat4/scale'),
    fromRotationTranslation: _dereq_('gl-mat4/fromRotationTranslation')
}

var rotationMatrix = mat4.create()
var temp = mat4.create()

module.exports = function recomposeMat4(matrix, translation, scale, skew, perspective, quaternion) {
    mat4.identity(matrix)

    //apply translation & rotation
    mat4.fromRotationTranslation(matrix, quaternion, translation)

    //apply perspective
    matrix[3] = perspective[0]
    matrix[7] = perspective[1]
    matrix[11] = perspective[2]
    matrix[15] = perspective[3]
        
    // apply skew
    // temp is a identity 4x4 matrix initially
    mat4.identity(temp)

    if (skew[2] !== 0) {
        temp[9] = skew[2]
        mat4.multiply(matrix, matrix, temp)
    }

    if (skew[1] !== 0) {
        temp[9] = 0
        temp[8] = skew[1]
        mat4.multiply(matrix, matrix, temp)
    }

    if (skew[0] !== 0) {
        temp[8] = 0
        temp[4] = skew[0]
        mat4.multiply(matrix, matrix, temp)
    }

    //apply scale
    mat4.scale(matrix, matrix, scale)
    return matrix
}
},{"gl-mat4/create":251,"gl-mat4/fromRotationTranslation":254,"gl-mat4/identity":255,"gl-mat4/multiply":258,"gl-mat4/scale":264,"gl-mat4/translate":265}],418:[function(_dereq_,module,exports){
'use strict';
module.exports = Math.log2 || function (x) {
	return Math.log(x) * Math.LOG2E;
};

},{}],419:[function(_dereq_,module,exports){
'use strict'

var bsearch   = _dereq_('binary-search-bounds')
var m4interp  = _dereq_('mat4-interpolate')
var invert44  = _dereq_('gl-mat4/invert')
var rotateX   = _dereq_('gl-mat4/rotateX')
var rotateY   = _dereq_('gl-mat4/rotateY')
var rotateZ   = _dereq_('gl-mat4/rotateZ')
var lookAt    = _dereq_('gl-mat4/lookAt')
var translate = _dereq_('gl-mat4/translate')
var scale     = _dereq_('gl-mat4/scale')
var normalize = _dereq_('gl-vec3/normalize')

var DEFAULT_CENTER = [0,0,0]

module.exports = createMatrixCameraController

function MatrixCameraController(initialMatrix) {
  this._components    = initialMatrix.slice()
  this._time          = [0]
  this.prevMatrix     = initialMatrix.slice()
  this.nextMatrix     = initialMatrix.slice()
  this.computedMatrix = initialMatrix.slice()
  this.computedInverse = initialMatrix.slice()
  this.computedEye    = [0,0,0]
  this.computedUp     = [0,0,0]
  this.computedCenter = [0,0,0]
  this.computedRadius = [0]
  this._limits        = [-Infinity, Infinity]
}

var proto = MatrixCameraController.prototype

proto.recalcMatrix = function(t) {
  var time = this._time
  var tidx = bsearch.le(time, t)
  var mat = this.computedMatrix
  if(tidx < 0) {
    return
  }
  var comps = this._components
  if(tidx === time.length-1) {
    var ptr = 16*tidx
    for(var i=0; i<16; ++i) {
      mat[i] = comps[ptr++]
    }
  } else {
    var dt = (time[tidx+1] - time[tidx])
    var ptr = 16*tidx
    var prev = this.prevMatrix
    var allEqual = true
    for(var i=0; i<16; ++i) {
      prev[i] = comps[ptr++]
    }
    var next = this.nextMatrix
    for(var i=0; i<16; ++i) {
      next[i] = comps[ptr++]
      allEqual = allEqual && (prev[i] === next[i])
    }
    if(dt < 1e-6 || allEqual) {
      for(var i=0; i<16; ++i) {
        mat[i] = prev[i]
      }
    } else {
      m4interp(mat, prev, next, (t - time[tidx])/dt)
    }
  }

  var up = this.computedUp
  up[0] = mat[1]
  up[1] = mat[5]
  up[2] = mat[9]
  normalize(up, up)

  var imat = this.computedInverse
  invert44(imat, mat)
  var eye = this.computedEye
  var w = imat[15]
  eye[0] = imat[12]/w
  eye[1] = imat[13]/w
  eye[2] = imat[14]/w

  var center = this.computedCenter
  var radius = Math.exp(this.computedRadius[0])
  for(var i=0; i<3; ++i) {
    center[i] = eye[i] - mat[2+4*i] * radius
  }
}

proto.idle = function(t) {
  if(t < this.lastT()) {
    return
  }
  var mc = this._components
  var ptr = mc.length-16
  for(var i=0; i<16; ++i) {
    mc.push(mc[ptr++])
  }
  this._time.push(t)
}

proto.flush = function(t) {
  var idx = bsearch.gt(this._time, t) - 2
  if(idx < 0) {
    return
  }
  this._time.splice(0, idx)
  this._components.splice(0, 16*idx)
}

proto.lastT = function() {
  return this._time[this._time.length-1]
}

proto.lookAt = function(t, eye, center, up) {
  this.recalcMatrix(t)
  eye    = eye || this.computedEye
  center = center || DEFAULT_CENTER
  up     = up || this.computedUp
  this.setMatrix(t, lookAt(this.computedMatrix, eye, center, up))
  var d2 = 0.0
  for(var i=0; i<3; ++i) {
    d2 += Math.pow(center[i] - eye[i], 2)
  }
  d2 = Math.log(Math.sqrt(d2))
  this.computedRadius[0] = d2
}

proto.rotate = function(t, yaw, pitch, roll) {
  this.recalcMatrix(t)
  var mat = this.computedInverse
  if(yaw)   rotateY(mat, mat, yaw)
  if(pitch) rotateX(mat, mat, pitch)
  if(roll)  rotateZ(mat, mat, roll)
  this.setMatrix(t, invert44(this.computedMatrix, mat))
}

var tvec = [0,0,0]

proto.pan = function(t, dx, dy, dz) {
  tvec[0] = -(dx || 0.0)
  tvec[1] = -(dy || 0.0)
  tvec[2] = -(dz || 0.0)
  this.recalcMatrix(t)
  var mat = this.computedInverse
  translate(mat, mat, tvec)
  this.setMatrix(t, invert44(mat, mat))
}

proto.translate = function(t, dx, dy, dz) {
  tvec[0] = dx || 0.0
  tvec[1] = dy || 0.0
  tvec[2] = dz || 0.0
  this.recalcMatrix(t)
  var mat = this.computedMatrix
  translate(mat, mat, tvec)
  this.setMatrix(t, mat)
}

proto.setMatrix = function(t, mat) {
  if(t < this.lastT()) {
    return
  }
  this._time.push(t)
  for(var i=0; i<16; ++i) {
    this._components.push(mat[i])
  }
}

proto.setDistance = function(t, d) {
  this.computedRadius[0] = d
}

proto.setDistanceLimits = function(a,b) {
  var lim = this._limits
  lim[0] = a
  lim[1] = b
}

proto.getDistanceLimits = function(out) {
  var lim = this._limits
  if(out) {
    out[0] = lim[0]
    out[1] = lim[1]
    return out
  }
  return lim
}

function createMatrixCameraController(options) {
  options = options || {}
  var matrix = options.matrix || 
              [1,0,0,0,
               0,1,0,0,
               0,0,1,0,
               0,0,0,1]
  return new MatrixCameraController(matrix)
}

},{"binary-search-bounds":80,"gl-mat4/invert":256,"gl-mat4/lookAt":257,"gl-mat4/rotateX":261,"gl-mat4/rotateY":262,"gl-mat4/rotateZ":263,"gl-mat4/scale":264,"gl-mat4/translate":265,"gl-vec3/normalize":342,"mat4-interpolate":416}],420:[function(_dereq_,module,exports){
'use strict'

module.exports = monotoneConvexHull2D

var orient = _dereq_('robust-orientation')[3]

function monotoneConvexHull2D(points) {
  var n = points.length

  if(n < 3) {
    var result = new Array(n)
    for(var i=0; i<n; ++i) {
      result[i] = i
    }

    if(n === 2 &&
       points[0][0] === points[1][0] &&
       points[0][1] === points[1][1]) {
      return [0]
    }

    return result
  }

  //Sort point indices along x-axis
  var sorted = new Array(n)
  for(var i=0; i<n; ++i) {
    sorted[i] = i
  }
  sorted.sort(function(a,b) {
    var d = points[a][0]-points[b][0]
    if(d) {
      return d
    }
    return points[a][1] - points[b][1]
  })

  //Construct upper and lower hulls
  var lower = [sorted[0], sorted[1]]
  var upper = [sorted[0], sorted[1]]

  for(var i=2; i<n; ++i) {
    var idx = sorted[i]
    var p   = points[idx]

    //Insert into lower list
    var m = lower.length
    while(m > 1 && orient(
        points[lower[m-2]], 
        points[lower[m-1]], 
        p) <= 0) {
      m -= 1
      lower.pop()
    }
    lower.push(idx)

    //Insert into upper list
    m = upper.length
    while(m > 1 && orient(
        points[upper[m-2]], 
        points[upper[m-1]], 
        p) >= 0) {
      m -= 1
      upper.pop()
    }
    upper.push(idx)
  }

  //Merge lists together
  var result = new Array(upper.length + lower.length - 2)
  var ptr    = 0
  for(var i=0, nl=lower.length; i<nl; ++i) {
    result[ptr++] = lower[i]
  }
  for(var j=upper.length-2; j>0; --j) {
    result[ptr++] = upper[j]
  }

  //Return result
  return result
}
},{"robust-orientation":488}],421:[function(_dereq_,module,exports){
'use strict'

module.exports = mouseListen

var mouse = _dereq_('mouse-event')

function mouseListen (element, callback) {
  if (!callback) {
    callback = element
    element = window
  }

  var buttonState = 0
  var x = 0
  var y = 0
  var mods = {
    shift: false,
    alt: false,
    control: false,
    meta: false
  }
  var attached = false

  function updateMods (ev) {
    var changed = false
    if ('altKey' in ev) {
      changed = changed || ev.altKey !== mods.alt
      mods.alt = !!ev.altKey
    }
    if ('shiftKey' in ev) {
      changed = changed || ev.shiftKey !== mods.shift
      mods.shift = !!ev.shiftKey
    }
    if ('ctrlKey' in ev) {
      changed = changed || ev.ctrlKey !== mods.control
      mods.control = !!ev.ctrlKey
    }
    if ('metaKey' in ev) {
      changed = changed || ev.metaKey !== mods.meta
      mods.meta = !!ev.metaKey
    }
    return changed
  }

  function handleEvent (nextButtons, ev) {
    var nextX = mouse.x(ev)
    var nextY = mouse.y(ev)
    if ('buttons' in ev) {
      nextButtons = ev.buttons | 0
    }
    if (nextButtons !== buttonState ||
      nextX !== x ||
      nextY !== y ||
      updateMods(ev)) {
      buttonState = nextButtons | 0
      x = nextX || 0
      y = nextY || 0
      callback && callback(buttonState, x, y, mods)
    }
  }

  function clearState (ev) {
    handleEvent(0, ev)
  }

  function handleBlur () {
    if (buttonState ||
      x ||
      y ||
      mods.shift ||
      mods.alt ||
      mods.meta ||
      mods.control) {
      x = y = 0
      buttonState = 0
      mods.shift = mods.alt = mods.control = mods.meta = false
      callback && callback(0, 0, 0, mods)
    }
  }

  function handleMods (ev) {
    if (updateMods(ev)) {
      callback && callback(buttonState, x, y, mods)
    }
  }

  function handleMouseMove (ev) {
    if (mouse.buttons(ev) === 0) {
      handleEvent(0, ev)
    } else {
      handleEvent(buttonState, ev)
    }
  }

  function handleMouseDown (ev) {
    handleEvent(buttonState | mouse.buttons(ev), ev)
  }

  function handleMouseUp (ev) {
    handleEvent(buttonState & ~mouse.buttons(ev), ev)
  }

  function attachListeners () {
    if (attached) {
      return
    }
    attached = true

    element.addEventListener('mousemove', handleMouseMove)

    element.addEventListener('mousedown', handleMouseDown)

    element.addEventListener('mouseup', handleMouseUp)

    element.addEventListener('mouseleave', clearState)
    element.addEventListener('mouseenter', clearState)
    element.addEventListener('mouseout', clearState)
    element.addEventListener('mouseover', clearState)

    element.addEventListener('blur', handleBlur)

    element.addEventListener('keyup', handleMods)
    element.addEventListener('keydown', handleMods)
    element.addEventListener('keypress', handleMods)

    if (element !== window) {
      window.addEventListener('blur', handleBlur)

      window.addEventListener('keyup', handleMods)
      window.addEventListener('keydown', handleMods)
      window.addEventListener('keypress', handleMods)
    }
  }

  function detachListeners () {
    if (!attached) {
      return
    }
    attached = false

    element.removeEventListener('mousemove', handleMouseMove)

    element.removeEventListener('mousedown', handleMouseDown)

    element.removeEventListener('mouseup', handleMouseUp)

    element.removeEventListener('mouseleave', clearState)
    element.removeEventListener('mouseenter', clearState)
    element.removeEventListener('mouseout', clearState)
    element.removeEventListener('mouseover', clearState)

    element.removeEventListener('blur', handleBlur)

    element.removeEventListener('keyup', handleMods)
    element.removeEventListener('keydown', handleMods)
    element.removeEventListener('keypress', handleMods)

    if (element !== window) {
      window.removeEventListener('blur', handleBlur)

      window.removeEventListener('keyup', handleMods)
      window.removeEventListener('keydown', handleMods)
      window.removeEventListener('keypress', handleMods)
    }
  }

  // Attach listeners
  attachListeners()

  var result = {
    element: element
  }

  Object.defineProperties(result, {
    enabled: {
      get: function () { return attached },
      set: function (f) {
        if (f) {
          attachListeners()
        } else {
          detachListeners()
        }
      },
      enumerable: true
    },
    buttons: {
      get: function () { return buttonState },
      enumerable: true
    },
    x: {
      get: function () { return x },
      enumerable: true
    },
    y: {
      get: function () { return y },
      enumerable: true
    },
    mods: {
      get: function () { return mods },
      enumerable: true
    }
  })

  return result
}

},{"mouse-event":423}],422:[function(_dereq_,module,exports){
var rootPosition = { left: 0, top: 0 }

module.exports = mouseEventOffset
function mouseEventOffset (ev, target, out) {
  target = target || ev.currentTarget || ev.srcElement
  if (!Array.isArray(out)) {
    out = [ 0, 0 ]
  }
  var cx = ev.clientX || 0
  var cy = ev.clientY || 0
  var rect = getBoundingClientOffset(target)
  out[0] = cx - rect.left
  out[1] = cy - rect.top
  return out
}

function getBoundingClientOffset (element) {
  if (element === window ||
      element === document ||
      element === document.body) {
    return rootPosition
  } else {
    return element.getBoundingClientRect()
  }
}

},{}],423:[function(_dereq_,module,exports){
'use strict'

function mouseButtons(ev) {
  if(typeof ev === 'object') {
    if('buttons' in ev) {
      return ev.buttons
    } else if('which' in ev) {
      var b = ev.which
      if(b === 2) {
        return 4
      } else if(b === 3) {
        return 2
      } else if(b > 0) {
        return 1<<(b-1)
      }
    } else if('button' in ev) {
      var b = ev.button
      if(b === 1) {
        return 4
      } else if(b === 2) {
        return 2
      } else if(b >= 0) {
        return 1<<b
      }
    }
  }
  return 0
}
exports.buttons = mouseButtons

function mouseElement(ev) {
  return ev.target || ev.srcElement || window
}
exports.element = mouseElement

function mouseRelativeX(ev) {
  if(typeof ev === 'object') {
    if('offsetX' in ev) {
      return ev.offsetX
    }
    var target = mouseElement(ev)
    var bounds = target.getBoundingClientRect()
    return ev.clientX - bounds.left
  }
  return 0
}
exports.x = mouseRelativeX

function mouseRelativeY(ev) {
  if(typeof ev === 'object') {
    if('offsetY' in ev) {
      return ev.offsetY
    }
    var target = mouseElement(ev)
    var bounds = target.getBoundingClientRect()
    return ev.clientY - bounds.top
  }
  return 0
}
exports.y = mouseRelativeY

},{}],424:[function(_dereq_,module,exports){
'use strict'

var toPX = _dereq_('to-px')

module.exports = mouseWheelListen

function mouseWheelListen(element, callback, noScroll) {
  if(typeof element === 'function') {
    noScroll = !!callback
    callback = element
    element = window
  }
  var lineHeight = toPX('ex', element)
  var listener = function(ev) {
    if(noScroll) {
      ev.preventDefault()
    }
    var dx = ev.deltaX || 0
    var dy = ev.deltaY || 0
    var dz = ev.deltaZ || 0
    var mode = ev.deltaMode
    var scale = 1
    switch(mode) {
      case 1:
        scale = lineHeight
      break
      case 2:
        scale = window.innerHeight
      break
    }
    dx *= scale
    dy *= scale
    dz *= scale
    if(dx || dy || dz) {
      return callback(dx, dy, dz, ev)
    }
  }
  element.addEventListener('wheel', listener)
  return listener
}

},{"to-px":517}],425:[function(_dereq_,module,exports){
"use strict"

var pool = _dereq_("typedarray-pool")

module.exports = createSurfaceExtractor

//Helper macros
function array(i) {
  return "a" + i
}
function data(i) {
  return "d" + i
}
function cube(i,bitmask) {
  return "c" + i + "_" + bitmask
}
function shape(i) {
  return "s" + i
}
function stride(i,j) {
  return "t" + i + "_" + j
}
function offset(i) {
  return "o" + i
}
function scalar(i) {
  return "x" + i
}
function pointer(i) {
  return "p" + i
}
function delta(i,bitmask) {
  return "d" + i + "_" + bitmask
}
function index(i) {
  return "i" + i
}
function step(i,j) {
  return "u" + i + "_" + j
}
function pcube(bitmask) {
  return "b" + bitmask
}
function qcube(bitmask) {
  return "y" + bitmask
}
function pdelta(bitmask) {
  return "e" + bitmask
}
function vert(i) {
  return "v" + i
}
var VERTEX_IDS = "V"
var PHASES = "P"
var VERTEX_COUNT = "N"
var POOL_SIZE = "Q"
var POINTER = "X"
var TEMPORARY = "T"

function permBitmask(dimension, mask, order) {
  var r = 0
  for(var i=0; i<dimension; ++i) {
    if(mask & (1<<i)) {
      r |= (1<<order[i])
    }
  }
  return r
}

//Generates the surface procedure
function compileSurfaceProcedure(vertexFunc, faceFunc, phaseFunc, scalarArgs, order, typesig) {
  var arrayArgs = typesig.length
  var dimension = order.length

  if(dimension < 2) {
    throw new Error("ndarray-extract-contour: Dimension must be at least 2")
  }

  var funcName = "extractContour" + order.join("_")
  var code = []
  var vars = []
  var args = []

  //Assemble arguments
  for(var i=0; i<arrayArgs; ++i) {
    args.push(array(i))  
  }
  for(var i=0; i<scalarArgs; ++i) {
    args.push(scalar(i))
  }

  //Shape
  for(var i=0; i<dimension; ++i) {
    vars.push(shape(i) + "=" + array(0) + ".shape[" + i + "]|0")
  }
  //Data, stride, offset pointers
  for(var i=0; i<arrayArgs; ++i) {
    vars.push(data(i) + "=" + array(i) + ".data",
              offset(i) + "=" + array(i) + ".offset|0")
    for(var j=0; j<dimension; ++j) {
      vars.push(stride(i,j) + "=" + array(i) + ".stride[" + j + "]|0")
    }
  }
  //Pointer, delta and cube variables
  for(var i=0; i<arrayArgs; ++i) {
    vars.push(pointer(i) + "=" + offset(i))
    vars.push(cube(i,0))
    for(var j=1; j<(1<<dimension); ++j) {
      var ptrStr = []
      for(var k=0; k<dimension; ++k) {
        if(j & (1<<k)) {
          ptrStr.push("-" + stride(i,k))
        }
      }
      vars.push(delta(i,j) + "=(" + ptrStr.join("") + ")|0")
      vars.push(cube(i,j) + "=0")
    }
  }
  //Create step variables
  for(var i=0; i<arrayArgs; ++i) {
    for(var j=0; j<dimension; ++j) {
      var stepVal = [ stride(i,order[j]) ]
      if(j > 0) {
        stepVal.push(stride(i, order[j-1]) + "*" + shape(order[j-1]) )
      }
      vars.push(step(i,order[j]) + "=(" + stepVal.join("-") + ")|0")
    }
  }
  //Create index variables
  for(var i=0; i<dimension; ++i) {
    vars.push(index(i) + "=0")
  }
  //Vertex count
  vars.push(VERTEX_COUNT + "=0")
  //Compute pool size, initialize pool step
  var sizeVariable = ["2"]
  for(var i=dimension-2; i>=0; --i) {
    sizeVariable.push(shape(order[i]))
  }
  //Previous phases and vertex_ids
  vars.push(POOL_SIZE + "=(" + sizeVariable.join("*") + ")|0",
            PHASES + "=mallocUint32(" + POOL_SIZE + ")",
            VERTEX_IDS + "=mallocUint32(" + POOL_SIZE + ")",
            POINTER + "=0")
  //Create cube variables for phases
  vars.push(pcube(0) + "=0")
  for(var j=1; j<(1<<dimension); ++j) {
    var cubeDelta = []
    var cubeStep = [ ]
    for(var k=0; k<dimension; ++k) {
      if(j & (1<<k)) {
        if(cubeStep.length === 0) {
          cubeDelta.push("1")
        } else {
          cubeDelta.unshift(cubeStep.join("*"))
        }
      }
      cubeStep.push(shape(order[k]))
    }
    var signFlag = ""
    if(cubeDelta[0].indexOf(shape(order[dimension-2])) < 0) {
      signFlag = "-"
    }
    var jperm = permBitmask(dimension, j, order)
    vars.push(pdelta(jperm) + "=(-" + cubeDelta.join("-") + ")|0",
              qcube(jperm) + "=(" + signFlag + cubeDelta.join("-") + ")|0",
              pcube(jperm) + "=0")
  }
  vars.push(vert(0) + "=0", TEMPORARY + "=0")

  function forLoopBegin(i, start) {
    code.push("for(", index(order[i]), "=", start, ";",
      index(order[i]), "<", shape(order[i]), ";",
      "++", index(order[i]), "){")
  }

  function forLoopEnd(i) {
    for(var j=0; j<arrayArgs; ++j) {
      code.push(pointer(j), "+=", step(j,order[i]), ";")
    }
    code.push("}")
  }

  function fillEmptySlice(k) {
    for(var i=k-1; i>=0; --i) {
      forLoopBegin(i, 0) 
    }
    var phaseFuncArgs = []
    for(var i=0; i<arrayArgs; ++i) {
      if(typesig[i]) {
        phaseFuncArgs.push(data(i) + ".get(" + pointer(i) + ")")
      } else {
        phaseFuncArgs.push(data(i) + "[" + pointer(i) + "]")
      }
    }
    for(var i=0; i<scalarArgs; ++i) {
      phaseFuncArgs.push(scalar(i))
    }
    code.push(PHASES, "[", POINTER, "++]=phase(", phaseFuncArgs.join(), ");")
    for(var i=0; i<k; ++i) {
      forLoopEnd(i)
    }
    for(var j=0; j<arrayArgs; ++j) {
      code.push(pointer(j), "+=", step(j,order[k]), ";")
    }
  }

  function processGridCell(mask) {
    //Read in local data
    for(var i=0; i<arrayArgs; ++i) {
      if(typesig[i]) {
        code.push(cube(i,0), "=", data(i), ".get(", pointer(i), ");")
      } else {
        code.push(cube(i,0), "=", data(i), "[", pointer(i), "];")
      }
    }

    //Read in phase
    var phaseFuncArgs = []
    for(var i=0; i<arrayArgs; ++i) {
      phaseFuncArgs.push(cube(i,0))
    }
    for(var i=0; i<scalarArgs; ++i) {
      phaseFuncArgs.push(scalar(i))
    }
    
    code.push(pcube(0), "=", PHASES, "[", POINTER, "]=phase(", phaseFuncArgs.join(), ");")
    
    //Read in other cube data
    for(var j=1; j<(1<<dimension); ++j) {
      code.push(pcube(j), "=", PHASES, "[", POINTER, "+", pdelta(j), "];")
    }

    //Check for boundary crossing
    var vertexPredicate = []
    for(var j=1; j<(1<<dimension); ++j) {
      vertexPredicate.push("(" + pcube(0) + "!==" + pcube(j) + ")")
    }
    code.push("if(", vertexPredicate.join("||"), "){")

    //Read in boundary data
    var vertexArgs = []
    for(var i=0; i<dimension; ++i) {
      vertexArgs.push(index(i))
    }
    for(var i=0; i<arrayArgs; ++i) {
      vertexArgs.push(cube(i,0))
      for(var j=1; j<(1<<dimension); ++j) {
        if(typesig[i]) {
          code.push(cube(i,j), "=", data(i), ".get(", pointer(i), "+", delta(i,j), ");")
        } else {
          code.push(cube(i,j), "=", data(i), "[", pointer(i), "+", delta(i,j), "];")
        }
        vertexArgs.push(cube(i,j))
      }
    }
    for(var i=0; i<(1<<dimension); ++i) {
      vertexArgs.push(pcube(i))
    }
    for(var i=0; i<scalarArgs; ++i) {
      vertexArgs.push(scalar(i))
    }

    //Generate vertex
    code.push("vertex(", vertexArgs.join(), ");",
      vert(0), "=", VERTEX_IDS, "[", POINTER, "]=", VERTEX_COUNT, "++;")

    //Check for face crossings
    var base = (1<<dimension)-1
    var corner = pcube(base)
    for(var j=0; j<dimension; ++j) {
      if((mask & ~(1<<j))===0) {
        //Check face
        var subset = base^(1<<j)
        var edge = pcube(subset)
        var faceArgs = [ ]
        for(var k=subset; k>0; k=(k-1)&subset) {
          faceArgs.push(VERTEX_IDS + "[" + POINTER + "+" + pdelta(k) + "]")
        }
        faceArgs.push(vert(0))
        for(var k=0; k<arrayArgs; ++k) {
          if(j&1) {
            faceArgs.push(cube(k,base), cube(k,subset))
          } else {
            faceArgs.push(cube(k,subset), cube(k,base))
          }
        }
        if(j&1) {
          faceArgs.push(corner, edge)
        } else {
          faceArgs.push(edge, corner)
        }
        for(var k=0; k<scalarArgs; ++k) {
          faceArgs.push(scalar(k))
        }
        code.push("if(", corner, "!==", edge, "){",
          "face(", faceArgs.join(), ")}")
      }
    }
    
    //Increment pointer, close off if statement
    code.push("}",
      POINTER, "+=1;")
  }

  function flip() {
    for(var j=1; j<(1<<dimension); ++j) {
      code.push(TEMPORARY, "=", pdelta(j), ";",
                pdelta(j), "=", qcube(j), ";",
                qcube(j), "=", TEMPORARY, ";")
    }
  }

  function createLoop(i, mask) {
    if(i < 0) {
      processGridCell(mask)
      return
    }
    fillEmptySlice(i)
    code.push("if(", shape(order[i]), ">0){",
      index(order[i]), "=1;")
    createLoop(i-1, mask|(1<<order[i]))

    for(var j=0; j<arrayArgs; ++j) {
      code.push(pointer(j), "+=", step(j,order[i]), ";")
    }
    if(i === dimension-1) {
      code.push(POINTER, "=0;")
      flip()
    }
    forLoopBegin(i, 2)
    createLoop(i-1, mask)
    if(i === dimension-1) {
      code.push("if(", index(order[dimension-1]), "&1){",
        POINTER, "=0;}")
      flip()
    }
    forLoopEnd(i)
    code.push("}")
  }

  createLoop(dimension-1, 0)

  //Release scratch memory
  code.push("freeUint32(", VERTEX_IDS, ");freeUint32(", PHASES, ");")

  //Compile and link procedure
  var procedureCode = [
    "'use strict';",
    "function ", funcName, "(", args.join(), "){",
      "var ", vars.join(), ";",
      code.join(""),
    "}",
    "return ", funcName ].join("")

  var proc = new Function(
    "vertex", 
    "face", 
    "phase", 
    "mallocUint32", 
    "freeUint32",
    procedureCode)
  return proc(
    vertexFunc, 
    faceFunc, 
    phaseFunc, 
    pool.mallocUint32, 
    pool.freeUint32)
}

function createSurfaceExtractor(args) {
  function error(msg) {
    throw new Error("ndarray-extract-contour: " + msg)
  }
  if(typeof args !== "object") {
    error("Must specify arguments")
  }
  var order = args.order
  if(!Array.isArray(order)) {
    error("Must specify order")
  }
  var arrays = args.arrayArguments||1
  if(arrays < 1) {
    error("Must have at least one array argument")
  }
  var scalars = args.scalarArguments||0
  if(scalars < 0) {
    error("Scalar arg count must be > 0")
  }
  if(typeof args.vertex !== "function") {
    error("Must specify vertex creation function")
  }
  if(typeof args.cell !== "function") {
    error("Must specify cell creation function")
  }
  if(typeof args.phase !== "function") {
    error("Must specify phase function")
  }
  var getters = args.getters || []
  var typesig = new Array(arrays)
  for(var i=0; i<arrays; ++i) {
    if(getters.indexOf(i) >= 0) {
      typesig[i] = true
    } else {
      typesig[i] = false
    }
  }
  return compileSurfaceProcedure(
    args.vertex,
    args.cell,
    args.phase,
    scalars,
    order,
    typesig)
}
},{"typedarray-pool":523}],426:[function(_dereq_,module,exports){
"use strict"



var fill = _dereq_('cwise/lib/wrapper')({"args":["index","array","scalar"],"pre":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"body":{"body":"{_inline_1_arg1_=_inline_1_arg2_.apply(void 0,_inline_1_arg0_)}","args":[{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_1_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_1_arg2_","lvalue":false,"rvalue":true,"count":1}],"thisVars":[],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"cwise","blockSize":64})

module.exports = function(array, f) {
  fill(array, f)
  return array
}

},{"cwise/lib/wrapper":138}],427:[function(_dereq_,module,exports){
'use strict'

module.exports      = gradient

var dup             = _dereq_('dup')
var cwiseCompiler   = _dereq_('cwise-compiler')

var TEMPLATE_CACHE  = {}
var GRADIENT_CACHE  = {}

var EmptyProc = {
  body: "",
  args: [],
  thisVars: [],
  localVars: []
}

var centralDiff = cwiseCompiler({
  args: [ 'array', 'array', 'array' ],
  pre: EmptyProc,
  post: EmptyProc,
  body: {
    args: [ {
      name: 'out', 
      lvalue: true,
      rvalue: false,
      count: 1
    }, {
      name: 'left', 
      lvalue: false,
      rvalue: true,
      count: 1
    }, {
      name: 'right', 
      lvalue: false,
      rvalue: true,
      count: 1
    }],
    body: "out=0.5*(left-right)",
    thisVars: [],
    localVars: []
  },
  funcName: 'cdiff'
})

var zeroOut = cwiseCompiler({
  args: [ 'array' ],
  pre: EmptyProc,
  post: EmptyProc,
  body: {
    args: [ {
      name: 'out', 
      lvalue: true,
      rvalue: false,
      count: 1
    }],
    body: "out=0",
    thisVars: [],
    localVars: []
  },
  funcName: 'zero'
})

function generateTemplate(d) {
  if(d in TEMPLATE_CACHE) {
    return TEMPLATE_CACHE[d]
  }
  var code = []
  for(var i=0; i<d; ++i) {
    code.push('out', i, 's=0.5*(inp', i, 'l-inp', i, 'r);')
  }
  var args = [ 'array' ]
  var names = ['junk']
  for(var i=0; i<d; ++i) {
    args.push('array')
    names.push('out' + i + 's')
    var o = dup(d)
    o[i] = -1
    args.push({
      array: 0,
      offset: o.slice()
    })
    o[i] = 1
    args.push({
      array: 0,
      offset: o.slice()
    })
    names.push('inp' + i + 'l', 'inp' + i + 'r')
  }
  return TEMPLATE_CACHE[d] = cwiseCompiler({
    args: args,
    pre:  EmptyProc,
    post: EmptyProc,
    body: {
      body: code.join(''),
      args: names.map(function(n) {
        return {
          name: n,
          lvalue: n.indexOf('out') === 0,
          rvalue: n.indexOf('inp') === 0,
          count: (n!=='junk')|0
        }
      }),
      thisVars: [],
      localVars: []
    },
    funcName: 'fdTemplate' + d
  })
}

function generateGradient(boundaryConditions) {
  var token = boundaryConditions.join()
  var proc = GRADIENT_CACHE[token]
  if(proc) {
    return proc
  }

  var d = boundaryConditions.length
  var code = ['function gradient(dst,src){var s=src.shape.slice();' ]
  
  function handleBoundary(facet) {
    var cod = d - facet.length

    var loStr = []
    var hiStr = []
    var pickStr = []
    for(var i=0; i<d; ++i) {
      if(facet.indexOf(i+1) >= 0) {
        pickStr.push('0')
      } else if(facet.indexOf(-(i+1)) >= 0) {
        pickStr.push('s['+i+']-1')
      } else {
        pickStr.push('-1')
        loStr.push('1')
        hiStr.push('s['+i+']-2')
      }
    }
    var boundStr = '.lo(' + loStr.join() + ').hi(' + hiStr.join() + ')'
    if(loStr.length === 0) {
      boundStr = ''
    }
        
    if(cod > 0) {
      code.push('if(1') 
      for(var i=0; i<d; ++i) {
        if(facet.indexOf(i+1) >= 0 || facet.indexOf(-(i+1)) >= 0) {
          continue
        }
        code.push('&&s[', i, ']>2')
      }
      code.push('){grad', cod, '(src.pick(', pickStr.join(), ')', boundStr)
      for(var i=0; i<d; ++i) {
        if(facet.indexOf(i+1) >= 0 || facet.indexOf(-(i+1)) >= 0) {
          continue
        }
        code.push(',dst.pick(', pickStr.join(), ',', i, ')', boundStr)
      }
      code.push(');')
    }

    for(var i=0; i<facet.length; ++i) {
      var bnd = Math.abs(facet[i])-1
      var outStr = 'dst.pick(' + pickStr.join() + ',' + bnd + ')' + boundStr
      switch(boundaryConditions[bnd]) {

        case 'clamp':
          var cPickStr = pickStr.slice()
          var dPickStr = pickStr.slice()
          if(facet[i] < 0) {
            cPickStr[bnd] = 's[' + bnd + ']-2'
          } else {
            dPickStr[bnd] = '1'
          }
          if(cod === 0) {
            code.push('if(s[', bnd, ']>1){dst.set(',
              pickStr.join(), ',', bnd, ',0.5*(src.get(',
                cPickStr.join(), ')-src.get(',
                dPickStr.join(), ')))}else{dst.set(',
              pickStr.join(), ',', bnd, ',0)};')
          } else {
            code.push('if(s[', bnd, ']>1){diff(', outStr, 
                ',src.pick(', cPickStr.join(), ')', boundStr, 
                ',src.pick(', dPickStr.join(), ')', boundStr, 
                ');}else{zero(', outStr, ');};')
          }
        break

        case 'mirror':
          if(cod === 0) {
            code.push('dst.set(', pickStr.join(), ',', bnd, ',0);')
          } else {
            code.push('zero(', outStr, ');')
          }
        break

        case 'wrap':
          var aPickStr = pickStr.slice()
          var bPickStr = pickStr.slice()
          if(facet[i] < 0) {
            aPickStr[bnd] = 's[' + bnd + ']-2'
            bPickStr[bnd] = '0'
            
          } else {
            aPickStr[bnd] = 's[' + bnd + ']-1'
            bPickStr[bnd] = '1'
          }
          if(cod === 0) {
            code.push('if(s[', bnd, ']>2){dst.set(',
              pickStr.join(), ',', bnd, ',0.5*(src.get(',
                aPickStr.join(), ')-src.get(',
                bPickStr.join(), ')))}else{dst.set(',
              pickStr.join(), ',', bnd, ',0)};')
          } else {
            code.push('if(s[', bnd, ']>2){diff(', outStr, 
                ',src.pick(', aPickStr.join(), ')', boundStr, 
                ',src.pick(', bPickStr.join(), ')', boundStr, 
                ');}else{zero(', outStr, ');};')
          }
        break

        default:
          throw new Error('ndarray-gradient: Invalid boundary condition')
      }
    }

    if(cod > 0) {
      code.push('};')
    }
  }

  //Enumerate ridges, facets, etc. of hypercube
  for(var i=0; i<(1<<d); ++i) {
    var faces = []
    for(var j=0; j<d; ++j) {
      if(i & (1<<j)) {
        faces.push(j+1)
      }
    }
    for(var k=0; k<(1<<faces.length); ++k) {
      var sfaces = faces.slice()
      for(var j=0; j<faces.length; ++j) {
        if(k & (1<<j)) {
          sfaces[j] = -sfaces[j]
        }
      }
      handleBoundary(sfaces)
    }
  }

  code.push('return dst;};return gradient')

  //Compile and link routine, save cached procedure
  var linkNames = [ 'diff', 'zero' ]
  var linkArgs  = [ centralDiff, zeroOut ]
  for(var i=1; i<=d; ++i) {
    linkNames.push('grad' + i)
    linkArgs.push(generateTemplate(i))
  }
  linkNames.push(code.join(''))

  var link = Function.apply(void 0, linkNames)
  var proc = link.apply(void 0, linkArgs)
  TEMPLATE_CACHE[token] = proc
  return proc
}

function gradient(out, inp, bc) {
  if(Array.isArray(bc)) {
    if(bc.length !== inp.dimension) {
      throw new Error('ndarray-gradient: invalid boundary conditions')
    }
  } else if(typeof bc === 'string') {
    bc = dup(inp.dimension, bc)
  } else {
    bc = dup(inp.dimension, 'clamp')
  }
  if(out.dimension !== inp.dimension + 1) {
    throw new Error('ndarray-gradient: output dimension must be +1 input dimension')
  }
  if(out.shape[inp.dimension] !== inp.dimension) {
    throw new Error('ndarray-gradient: output shape must match input shape')
  }
  for(var i=0; i<inp.dimension; ++i) {
    if(out.shape[i] !== inp.shape[i]) {
      throw new Error('ndarray-gradient: shape mismatch')
    }
  }
  if(inp.size === 0) {
    return out
  }
  if(inp.dimension <= 0) {
    out.set(0)
    return out
  }
  var cached = generateGradient(bc)
  return cached(out, inp)
}
},{"cwise-compiler":135,"dup":156}],428:[function(_dereq_,module,exports){
'use strict'

var warp = _dereq_('ndarray-warp')
var invert = _dereq_('gl-matrix-invert')

module.exports = applyHomography

function applyHomography(dest, src, Xi) {
  var n = src.dimension
  var X = invert([], Xi)
  warp(dest, src, function(out_c, inp_c) {
    for(var i=0; i<n; ++i) {
      out_c[i] = X[(n+1)*n + i]
      for(var j=0; j<n; ++j) {
        out_c[i] += X[(n+1)*j+i] * inp_c[j]
      }
    }
    var w = X[(n+1)*(n+1)-1]
    for(var j=0; j<n; ++j) {
      w += X[(n+1)*j+n] * inp_c[j]
    }
    var wr = 1.0 / w
    for(var i=0; i<n; ++i) {
      out_c[i] *= wr
    }
    return out_c
  })
  return dest
}
},{"gl-matrix-invert":267,"ndarray-warp":435}],429:[function(_dereq_,module,exports){
"use strict"

function interp1d(arr, x) {
  var ix = Math.floor(x)
    , fx = x - ix
    , s0 = 0 <= ix   && ix   < arr.shape[0]
    , s1 = 0 <= ix+1 && ix+1 < arr.shape[0]
    , w0 = s0 ? +arr.get(ix)   : 0.0
    , w1 = s1 ? +arr.get(ix+1) : 0.0
  return (1.0-fx)*w0 + fx*w1
}

function interp2d(arr, x, y) {
  var ix = Math.floor(x)
    , fx = x - ix
    , s0 = 0 <= ix   && ix   < arr.shape[0]
    , s1 = 0 <= ix+1 && ix+1 < arr.shape[0]
    , iy = Math.floor(y)
    , fy = y - iy
    , t0 = 0 <= iy   && iy   < arr.shape[1]
    , t1 = 0 <= iy+1 && iy+1 < arr.shape[1]
    , w00 = s0&&t0 ? arr.get(ix  ,iy  ) : 0.0
    , w01 = s0&&t1 ? arr.get(ix  ,iy+1) : 0.0
    , w10 = s1&&t0 ? arr.get(ix+1,iy  ) : 0.0
    , w11 = s1&&t1 ? arr.get(ix+1,iy+1) : 0.0
  return (1.0-fy) * ((1.0-fx)*w00 + fx*w10) + fy * ((1.0-fx)*w01 + fx*w11)
}

function interp3d(arr, x, y, z) {
  var ix = Math.floor(x)
    , fx = x - ix
    , s0 = 0 <= ix   && ix   < arr.shape[0]
    , s1 = 0 <= ix+1 && ix+1 < arr.shape[0]
    , iy = Math.floor(y)
    , fy = y - iy
    , t0 = 0 <= iy   && iy   < arr.shape[1]
    , t1 = 0 <= iy+1 && iy+1 < arr.shape[1]
    , iz = Math.floor(z)
    , fz = z - iz
    , u0 = 0 <= iz   && iz   < arr.shape[2]
    , u1 = 0 <= iz+1 && iz+1 < arr.shape[2]
    , w000 = s0&&t0&&u0 ? arr.get(ix,iy,iz)       : 0.0
    , w010 = s0&&t1&&u0 ? arr.get(ix,iy+1,iz)     : 0.0
    , w100 = s1&&t0&&u0 ? arr.get(ix+1,iy,iz)     : 0.0
    , w110 = s1&&t1&&u0 ? arr.get(ix+1,iy+1,iz)   : 0.0
    , w001 = s0&&t0&&u1 ? arr.get(ix,iy,iz+1)     : 0.0
    , w011 = s0&&t1&&u1 ? arr.get(ix,iy+1,iz+1)   : 0.0
    , w101 = s1&&t0&&u1 ? arr.get(ix+1,iy,iz+1)   : 0.0
    , w111 = s1&&t1&&u1 ? arr.get(ix+1,iy+1,iz+1) : 0.0
  return (1.0-fz) * ((1.0-fy) * ((1.0-fx)*w000 + fx*w100) + fy * ((1.0-fx)*w010 + fx*w110)) + fz * ((1.0-fy) * ((1.0-fx)*w001 + fx*w101) + fy * ((1.0-fx)*w011 + fx*w111))
}

function interpNd(arr) {
  var d = arr.shape.length|0
    , ix = new Array(d)
    , fx = new Array(d)
    , s0 = new Array(d)
    , s1 = new Array(d)
    , i, t
  for(i=0; i<d; ++i) {
    t = +arguments[i+1]
    ix[i] = Math.floor(t)
    fx[i] = t - ix[i]
    s0[i] = (0 <= ix[i]   && ix[i]   < arr.shape[i])
    s1[i] = (0 <= ix[i]+1 && ix[i]+1 < arr.shape[i])
  }
  var r = 0.0, j, w, idx
i_loop:
  for(i=0; i<(1<<d); ++i) {
    w = 1.0
    idx = arr.offset
    for(j=0; j<d; ++j) {
      if(i & (1<<j)) {
        if(!s1[j]) {
          continue i_loop
        }
        w *= fx[j]
        idx += arr.stride[j] * (ix[j] + 1)
      } else {
        if(!s0[j]) {
          continue i_loop
        }
        w *= 1.0 - fx[j]
        idx += arr.stride[j] * ix[j]
      }
    }
    r += w * arr.data[idx]
  }
  return r
}

function interpolate(arr, x, y, z) {
  switch(arr.shape.length) {
    case 0:
      return 0.0
    case 1:
      return interp1d(arr, x)
    case 2:
      return interp2d(arr, x, y)
    case 3:
      return interp3d(arr, x, y, z)
    default:
      return interpNd.apply(undefined, arguments)
  }
}
module.exports = interpolate
module.exports.d1 = interp1d
module.exports.d2 = interp2d
module.exports.d3 = interp3d

},{}],430:[function(_dereq_,module,exports){
"use strict"

var compile = _dereq_("cwise-compiler")

var EmptyProc = {
  body: "",
  args: [],
  thisVars: [],
  localVars: []
}

function fixup(x) {
  if(!x) {
    return EmptyProc
  }
  for(var i=0; i<x.args.length; ++i) {
    var a = x.args[i]
    if(i === 0) {
      x.args[i] = {name: a, lvalue:true, rvalue: !!x.rvalue, count:x.count||1 }
    } else {
      x.args[i] = {name: a, lvalue:false, rvalue:true, count: 1}
    }
  }
  if(!x.thisVars) {
    x.thisVars = []
  }
  if(!x.localVars) {
    x.localVars = []
  }
  return x
}

function pcompile(user_args) {
  return compile({
    args:     user_args.args,
    pre:      fixup(user_args.pre),
    body:     fixup(user_args.body),
    post:     fixup(user_args.proc),
    funcName: user_args.funcName
  })
}

function makeOp(user_args) {
  var args = []
  for(var i=0; i<user_args.args.length; ++i) {
    args.push("a"+i)
  }
  var wrapper = new Function("P", [
    "return function ", user_args.funcName, "_ndarrayops(", args.join(","), ") {P(", args.join(","), ");return a0}"
  ].join(""))
  return wrapper(pcompile(user_args))
}

var assign_ops = {
  add:  "+",
  sub:  "-",
  mul:  "*",
  div:  "/",
  mod:  "%",
  band: "&",
  bor:  "|",
  bxor: "^",
  lshift: "<<",
  rshift: ">>",
  rrshift: ">>>"
}
;(function(){
  for(var id in assign_ops) {
    var op = assign_ops[id]
    exports[id] = makeOp({
      args: ["array","array","array"],
      body: {args:["a","b","c"],
             body: "a=b"+op+"c"},
      funcName: id
    })
    exports[id+"eq"] = makeOp({
      args: ["array","array"],
      body: {args:["a","b"],
             body:"a"+op+"=b"},
      rvalue: true,
      funcName: id+"eq"
    })
    exports[id+"s"] = makeOp({
      args: ["array", "array", "scalar"],
      body: {args:["a","b","s"],
             body:"a=b"+op+"s"},
      funcName: id+"s"
    })
    exports[id+"seq"] = makeOp({
      args: ["array","scalar"],
      body: {args:["a","s"],
             body:"a"+op+"=s"},
      rvalue: true,
      funcName: id+"seq"
    })
  }
})();

var unary_ops = {
  not: "!",
  bnot: "~",
  neg: "-",
  recip: "1.0/"
}
;(function(){
  for(var id in unary_ops) {
    var op = unary_ops[id]
    exports[id] = makeOp({
      args: ["array", "array"],
      body: {args:["a","b"],
             body:"a="+op+"b"},
      funcName: id
    })
    exports[id+"eq"] = makeOp({
      args: ["array"],
      body: {args:["a"],
             body:"a="+op+"a"},
      rvalue: true,
      count: 2,
      funcName: id+"eq"
    })
  }
})();

var binary_ops = {
  and: "&&",
  or: "||",
  eq: "===",
  neq: "!==",
  lt: "<",
  gt: ">",
  leq: "<=",
  geq: ">="
}
;(function() {
  for(var id in binary_ops) {
    var op = binary_ops[id]
    exports[id] = makeOp({
      args: ["array","array","array"],
      body: {args:["a", "b", "c"],
             body:"a=b"+op+"c"},
      funcName: id
    })
    exports[id+"s"] = makeOp({
      args: ["array","array","scalar"],
      body: {args:["a", "b", "s"],
             body:"a=b"+op+"s"},
      funcName: id+"s"
    })
    exports[id+"eq"] = makeOp({
      args: ["array", "array"],
      body: {args:["a", "b"],
             body:"a=a"+op+"b"},
      rvalue:true,
      count:2,
      funcName: id+"eq"
    })
    exports[id+"seq"] = makeOp({
      args: ["array", "scalar"],
      body: {args:["a","s"],
             body:"a=a"+op+"s"},
      rvalue:true,
      count:2,
      funcName: id+"seq"
    })
  }
})();

var math_unary = [
  "abs",
  "acos",
  "asin",
  "atan",
  "ceil",
  "cos",
  "exp",
  "floor",
  "log",
  "round",
  "sin",
  "sqrt",
  "tan"
]
;(function() {
  for(var i=0; i<math_unary.length; ++i) {
    var f = math_unary[i]
    exports[f] = makeOp({
                    args: ["array", "array"],
                    pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
                    body: {args:["a","b"], body:"a=this_f(b)", thisVars:["this_f"]},
                    funcName: f
                  })
    exports[f+"eq"] = makeOp({
                      args: ["array"],
                      pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
                      body: {args: ["a"], body:"a=this_f(a)", thisVars:["this_f"]},
                      rvalue: true,
                      count: 2,
                      funcName: f+"eq"
                    })
  }
})();

var math_comm = [
  "max",
  "min",
  "atan2",
  "pow"
]
;(function(){
  for(var i=0; i<math_comm.length; ++i) {
    var f= math_comm[i]
    exports[f] = makeOp({
                  args:["array", "array", "array"],
                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
                  body: {args:["a","b","c"], body:"a=this_f(b,c)", thisVars:["this_f"]},
                  funcName: f
                })
    exports[f+"s"] = makeOp({
                  args:["array", "array", "scalar"],
                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
                  body: {args:["a","b","c"], body:"a=this_f(b,c)", thisVars:["this_f"]},
                  funcName: f+"s"
                  })
    exports[f+"eq"] = makeOp({ args:["array", "array"],
                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
                  body: {args:["a","b"], body:"a=this_f(a,b)", thisVars:["this_f"]},
                  rvalue: true,
                  count: 2,
                  funcName: f+"eq"
                  })
    exports[f+"seq"] = makeOp({ args:["array", "scalar"],
                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
                  body: {args:["a","b"], body:"a=this_f(a,b)", thisVars:["this_f"]},
                  rvalue:true,
                  count:2,
                  funcName: f+"seq"
                  })
  }
})();

var math_noncomm = [
  "atan2",
  "pow"
]
;(function(){
  for(var i=0; i<math_noncomm.length; ++i) {
    var f= math_noncomm[i]
    exports[f+"op"] = makeOp({
                  args:["array", "array", "array"],
                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
                  body: {args:["a","b","c"], body:"a=this_f(c,b)", thisVars:["this_f"]},
                  funcName: f+"op"
                })
    exports[f+"ops"] = makeOp({
                  args:["array", "array", "scalar"],
                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
                  body: {args:["a","b","c"], body:"a=this_f(c,b)", thisVars:["this_f"]},
                  funcName: f+"ops"
                  })
    exports[f+"opeq"] = makeOp({ args:["array", "array"],
                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
                  body: {args:["a","b"], body:"a=this_f(b,a)", thisVars:["this_f"]},
                  rvalue: true,
                  count: 2,
                  funcName: f+"opeq"
                  })
    exports[f+"opseq"] = makeOp({ args:["array", "scalar"],
                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
                  body: {args:["a","b"], body:"a=this_f(b,a)", thisVars:["this_f"]},
                  rvalue:true,
                  count:2,
                  funcName: f+"opseq"
                  })
  }
})();

exports.any = compile({
  args:["array"],
  pre: EmptyProc,
  body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "if(a){return true}", localVars: [], thisVars: []},
  post: {args:[], localVars:[], thisVars:[], body:"return false"},
  funcName: "any"
})

exports.all = compile({
  args:["array"],
  pre: EmptyProc,
  body: {args:[{name:"x", lvalue:false, rvalue:true, count:1}], body: "if(!x){return false}", localVars: [], thisVars: []},
  post: {args:[], localVars:[], thisVars:[], body:"return true"},
  funcName: "all"
})

exports.sum = compile({
  args:["array"],
  pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
  body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "this_s+=a", localVars: [], thisVars: ["this_s"]},
  post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
  funcName: "sum"
})

exports.prod = compile({
  args:["array"],
  pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=1"},
  body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "this_s*=a", localVars: [], thisVars: ["this_s"]},
  post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
  funcName: "prod"
})

exports.norm2squared = compile({
  args:["array"],
  pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
  body: {args:[{name:"a", lvalue:false, rvalue:true, count:2}], body: "this_s+=a*a", localVars: [], thisVars: ["this_s"]},
  post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
  funcName: "norm2squared"
})
  
exports.norm2 = compile({
  args:["array"],
  pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
  body: {args:[{name:"a", lvalue:false, rvalue:true, count:2}], body: "this_s+=a*a", localVars: [], thisVars: ["this_s"]},
  post: {args:[], localVars:[], thisVars:["this_s"], body:"return Math.sqrt(this_s)"},
  funcName: "norm2"
})
  

exports.norminf = compile({
  args:["array"],
  pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
  body: {args:[{name:"a", lvalue:false, rvalue:true, count:4}], body:"if(-a>this_s){this_s=-a}else if(a>this_s){this_s=a}", localVars: [], thisVars: ["this_s"]},
  post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
  funcName: "norminf"
})

exports.norm1 = compile({
  args:["array"],
  pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
  body: {args:[{name:"a", lvalue:false, rvalue:true, count:3}], body: "this_s+=a<0?-a:a", localVars: [], thisVars: ["this_s"]},
  post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
  funcName: "norm1"
})

exports.sup = compile({
  args: [ "array" ],
  pre:
   { body: "this_h=-Infinity",
     args: [],
     thisVars: [ "this_h" ],
     localVars: [] },
  body:
   { body: "if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_",
     args: [{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":2} ],
     thisVars: [ "this_h" ],
     localVars: [] },
  post:
   { body: "return this_h",
     args: [],
     thisVars: [ "this_h" ],
     localVars: [] }
 })

exports.inf = compile({
  args: [ "array" ],
  pre:
   { body: "this_h=Infinity",
     args: [],
     thisVars: [ "this_h" ],
     localVars: [] },
  body:
   { body: "if(_inline_1_arg0_<this_h)this_h=_inline_1_arg0_",
     args: [{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":2} ],
     thisVars: [ "this_h" ],
     localVars: [] },
  post:
   { body: "return this_h",
     args: [],
     thisVars: [ "this_h" ],
     localVars: [] }
 })

exports.argmin = compile({
  args:["index","array","shape"],
  pre:{
    body:"{this_v=Infinity;this_i=_inline_0_arg2_.slice(0)}",
    args:[
      {name:"_inline_0_arg0_",lvalue:false,rvalue:false,count:0},
      {name:"_inline_0_arg1_",lvalue:false,rvalue:false,count:0},
      {name:"_inline_0_arg2_",lvalue:false,rvalue:true,count:1}
      ],
    thisVars:["this_i","this_v"],
    localVars:[]},
  body:{
    body:"{if(_inline_1_arg1_<this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",
    args:[
      {name:"_inline_1_arg0_",lvalue:false,rvalue:true,count:2},
      {name:"_inline_1_arg1_",lvalue:false,rvalue:true,count:2}],
    thisVars:["this_i","this_v"],
    localVars:["_inline_1_k"]},
  post:{
    body:"{return this_i}",
    args:[],
    thisVars:["this_i"],
    localVars:[]}
})

exports.argmax = compile({
  args:["index","array","shape"],
  pre:{
    body:"{this_v=-Infinity;this_i=_inline_0_arg2_.slice(0)}",
    args:[
      {name:"_inline_0_arg0_",lvalue:false,rvalue:false,count:0},
      {name:"_inline_0_arg1_",lvalue:false,rvalue:false,count:0},
      {name:"_inline_0_arg2_",lvalue:false,rvalue:true,count:1}
      ],
    thisVars:["this_i","this_v"],
    localVars:[]},
  body:{
    body:"{if(_inline_1_arg1_>this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",
    args:[
      {name:"_inline_1_arg0_",lvalue:false,rvalue:true,count:2},
      {name:"_inline_1_arg1_",lvalue:false,rvalue:true,count:2}],
    thisVars:["this_i","this_v"],
    localVars:["_inline_1_k"]},
  post:{
    body:"{return this_i}",
    args:[],
    thisVars:["this_i"],
    localVars:[]}
})  

exports.random = makeOp({
  args: ["array"],
  pre: {args:[], body:"this_f=Math.random", thisVars:["this_f"]},
  body: {args: ["a"], body:"a=this_f()", thisVars:["this_f"]},
  funcName: "random"
})

exports.assign = makeOp({
  args:["array", "array"],
  body: {args:["a", "b"], body:"a=b"},
  funcName: "assign" })

exports.assigns = makeOp({
  args:["array", "scalar"],
  body: {args:["a", "b"], body:"a=b"},
  funcName: "assigns" })


exports.equals = compile({
  args:["array", "array"],
  pre: EmptyProc,
  body: {args:[{name:"x", lvalue:false, rvalue:true, count:1},
               {name:"y", lvalue:false, rvalue:true, count:1}], 
        body: "if(x!==y){return false}", 
        localVars: [], 
        thisVars: []},
  post: {args:[], localVars:[], thisVars:[], body:"return true"},
  funcName: "equals"
})



},{"cwise-compiler":135}],431:[function(_dereq_,module,exports){
"use strict"

var ndarray = _dereq_("ndarray")
var do_convert = _dereq_("./doConvert.js")

module.exports = function convert(arr, result) {
  var shape = [], c = arr, sz = 1
  while(Array.isArray(c)) {
    shape.push(c.length)
    sz *= c.length
    c = c[0]
  }
  if(shape.length === 0) {
    return ndarray()
  }
  if(!result) {
    result = ndarray(new Float64Array(sz), shape)
  }
  do_convert(result, arr)
  return result
}

},{"./doConvert.js":432,"ndarray":436}],432:[function(_dereq_,module,exports){
module.exports=_dereq_('cwise-compiler')({"args":["array","scalar","index"],"pre":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"body":{"body":"{\nvar _inline_1_v=_inline_1_arg1_,_inline_1_i\nfor(_inline_1_i=0;_inline_1_i<_inline_1_arg2_.length-1;++_inline_1_i) {\n_inline_1_v=_inline_1_v[_inline_1_arg2_[_inline_1_i]]\n}\n_inline_1_arg0_=_inline_1_v[_inline_1_arg2_[_inline_1_arg2_.length-1]]\n}","args":[{"name":"_inline_1_arg0_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_1_arg1_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_1_arg2_","lvalue":false,"rvalue":true,"count":4}],"thisVars":[],"localVars":["_inline_1_i","_inline_1_v"]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"funcName":"convert","blockSize":64})

},{"cwise-compiler":135}],433:[function(_dereq_,module,exports){
"use strict"

var pool = _dereq_("typedarray-pool")

var INSERTION_SORT_THRESHOLD = 32

function getMallocFree(dtype) {
  switch(dtype) {
    case "uint8":
      return [pool.mallocUint8, pool.freeUint8]
    case "uint16":
      return [pool.mallocUint16, pool.freeUint16]
    case "uint32":
      return [pool.mallocUint32, pool.freeUint32]
    case "int8":
      return [pool.mallocInt8, pool.freeInt8]
    case "int16":
      return [pool.mallocInt16, pool.freeInt16]
    case "int32":
      return [pool.mallocInt32, pool.freeInt32]
    case "float32":
      return [pool.mallocFloat, pool.freeFloat]
    case "float64":
      return [pool.mallocDouble, pool.freeDouble]
    default:
      return null
  }
}

function shapeArgs(dimension) {
  var args = []
  for(var i=0; i<dimension; ++i) {
    args.push("s"+i)
  }
  for(var i=0; i<dimension; ++i) {
    args.push("n"+i)
  }
  for(var i=1; i<dimension; ++i) {
    args.push("d"+i)
  }
  for(var i=1; i<dimension; ++i) {
    args.push("e"+i)
  }
  for(var i=1; i<dimension; ++i) {
    args.push("f"+i)
  }
  return args
}

function createInsertionSort(order, dtype) {

  var code = ["'use strict'"]
  var funcName = ["ndarrayInsertionSort", order.join("d"), dtype].join("")
  var funcArgs = ["left", "right", "data", "offset" ].concat(shapeArgs(order.length))
  var allocator = getMallocFree(dtype)
  
  var vars = [ "i,j,cptr,ptr=left*s0+offset" ]
  
  if(order.length > 1) {
    var scratch_shape = []
    for(var i=1; i<order.length; ++i) {
      vars.push("i"+i)
      scratch_shape.push("n"+i)
    }
    if(allocator) {
      vars.push("scratch=malloc(" + scratch_shape.join("*") + ")")
    } else {
      vars.push("scratch=new Array("+scratch_shape.join("*") + ")")
    }
    vars.push("dptr","sptr","a","b")
  } else {
    vars.push("scratch")
  }
  
  function dataRead(ptr) {
    if(dtype === "generic") {
      return ["data.get(", ptr, ")"].join("")
    }
    return ["data[",ptr,"]"].join("")
  }
  
  function dataWrite(ptr, v) {
    if(dtype === "generic") {
      return ["data.set(", ptr, ",", v, ")"].join("")
    }
    return ["data[",ptr,"]=",v].join("")
  }
  
  //Create function header
  code.push(
    ["function ", funcName, "(", funcArgs.join(","), "){var ", vars.join(",")].join(""),
      "for(i=left+1;i<=right;++i){",
        "j=i;ptr+=s0",
        "cptr=ptr")
  
  
  if(order.length > 1) {
  
    //Copy data into scratch
    code.push("dptr=0;sptr=ptr")
    for(var i=order.length-1; i>=0; --i) {
      var j = order[i]
      if(j === 0) {
        continue
      }
      code.push(["for(i",j,"=0;i",j,"<n",j,";++i",j,"){"].join(""))
    }
    code.push("scratch[dptr++]=",dataRead("sptr"))
    for(var i=0; i<order.length; ++i) {
      var j = order[i]
      if(j === 0) {
        continue
      }
      code.push("sptr+=d"+j,"}")
    }

    
    //Compare items in outer loop
    code.push("__g:while(j-->left){",
              "dptr=0",
              "sptr=cptr-s0")
    for(var i=1; i<order.length; ++i) {
      if(i === 1) {
        code.push("__l:")
      }
      code.push(["for(i",i,"=0;i",i,"<n",i,";++i",i,"){"].join(""))
    }
    code.push(["a=", dataRead("sptr"),"\nb=scratch[dptr]\nif(a<b){break __g}\nif(a>b){break __l}"].join(""))
    for(var i=order.length-1; i>=1; --i) {
      code.push(
        "sptr+=e"+i,
        "dptr+=f"+i,
        "}")
    }
    
    //Copy data back
    code.push("dptr=cptr;sptr=cptr-s0")
    for(var i=order.length-1; i>=0; --i) {
      var j = order[i]
      if(j === 0) {
        continue
      }
      code.push(["for(i",j,"=0;i",j,"<n",j,";++i",j,"){"].join(""))
    }
    code.push(dataWrite("dptr", dataRead("sptr")))
    for(var i=0; i<order.length; ++i) {
      var j = order[i]
      if(j === 0) {
        continue
      }
      code.push(["dptr+=d",j,";sptr+=d",j].join(""),"}")
    }
    
    //Close while loop
    code.push("cptr-=s0\n}")

    //Copy scratch into cptr
    code.push("dptr=cptr;sptr=0")
    for(var i=order.length-1; i>=0; --i) {
      var j = order[i]
      if(j === 0) {
        continue
      }
      code.push(["for(i",j,"=0;i",j,"<n",j,";++i",j,"){"].join(""))
    }
    code.push(dataWrite("dptr", "scratch[sptr++]"))
    for(var i=0; i<order.length; ++i) {
      var j = order[i]
      if(j === 0) {
        continue
      }
      code.push("dptr+=d"+j,"}")
    }
  } else {
    code.push("scratch=" + dataRead("ptr"),
              "while((j-->left)&&("+dataRead("cptr-s0")+">scratch)){",
                dataWrite("cptr", dataRead("cptr-s0")),
                "cptr-=s0",
              "}",
              dataWrite("cptr", "scratch"))
  }
  
  //Close outer loop body
  code.push("}")
  if(order.length > 1 && allocator) {
    code.push("free(scratch)")
  }
  code.push("} return " + funcName)
  
  //Compile and link function
  if(allocator) {
    var result = new Function("malloc", "free", code.join("\n"))
    return result(allocator[0], allocator[1])
  } else {
    var result = new Function(code.join("\n"))
    return result()
  }
}

function createQuickSort(order, dtype, insertionSort) {
  var code = [ "'use strict'" ]
  var funcName = ["ndarrayQuickSort", order.join("d"), dtype].join("")
  var funcArgs = ["left", "right", "data", "offset" ].concat(shapeArgs(order.length))
  var allocator = getMallocFree(dtype)
  var labelCounter=0
  
  code.push(["function ", funcName, "(", funcArgs.join(","), "){"].join(""))
  
  var vars = [
    "sixth=((right-left+1)/6)|0",
    "index1=left+sixth",
    "index5=right-sixth",
    "index3=(left+right)>>1",
    "index2=index3-sixth",
    "index4=index3+sixth",
    "el1=index1",
    "el2=index2",
    "el3=index3",
    "el4=index4",
    "el5=index5",
    "less=left+1",
    "great=right-1",
    "pivots_are_equal=true",
    "tmp",
    "tmp0",
    "x",
    "y",
    "z",
    "k",
    "ptr0",
    "ptr1",
    "ptr2",
    "comp_pivot1=0",
    "comp_pivot2=0",
    "comp=0"
  ]
  
  if(order.length > 1) {
    var ele_size = []
    for(var i=1; i<order.length; ++i) {
      ele_size.push("n"+i)
      vars.push("i"+i)
    }
    for(var i=0; i<8; ++i) {
      vars.push("b_ptr"+i)
    }
    vars.push(
      "ptr3",
      "ptr4",
      "ptr5",
      "ptr6",
      "ptr7",
      "pivot_ptr",
      "ptr_shift",
      "elementSize="+ele_size.join("*"))
    if(allocator) {
      vars.push("pivot1=malloc(elementSize)",
                "pivot2=malloc(elementSize)")
    } else {
      vars.push("pivot1=new Array(elementSize),pivot2=new Array(elementSize)")
    }
  } else {
    vars.push("pivot1", "pivot2")
  }
  
  //Initialize local variables
  code.push("var " + vars.join(","))
  
  function toPointer(v) {
    return ["(offset+",v,"*s0)"].join("")
  }
  
  function dataRead(ptr) {
    if(dtype === "generic") {
      return ["data.get(", ptr, ")"].join("")
    }
    return ["data[",ptr,"]"].join("")
  }
  
  function dataWrite(ptr, v) {
    if(dtype === "generic") {
      return ["data.set(", ptr, ",", v, ")"].join("")
    }
    return ["data[",ptr,"]=",v].join("")
  }
  
  function cacheLoop(ptrs, usePivot, body) {
    if(ptrs.length === 1) {
      code.push("ptr0="+toPointer(ptrs[0]))
    } else {
      for(var i=0; i<ptrs.length; ++i) {
        code.push(["b_ptr",i,"=s0*",ptrs[i]].join(""))
      }
    }
    if(usePivot) {
      code.push("pivot_ptr=0")
    }
    code.push("ptr_shift=offset")
    for(var i=order.length-1; i>=0; --i) {
      var j = order[i]
      if(j === 0) {
        continue
      }
      code.push(["for(i",j,"=0;i",j,"<n",j,";++i",j,"){"].join(""))
    }
    if(ptrs.length > 1) {
      for(var i=0; i<ptrs.length; ++i) {
        code.push(["ptr",i,"=b_ptr",i,"+ptr_shift"].join(""))
      }
    }
    code.push(body)
    if(usePivot) {
      code.push("++pivot_ptr")
    }
    for(var i=0; i<order.length; ++i) {
      var j = order[i]
      if(j === 0) {
        continue
      }
      if(ptrs.length>1) {
        code.push("ptr_shift+=d"+j)
      } else {
        code.push("ptr0+=d"+j)
      }
      code.push("}")
    }
  }
  
  function lexicoLoop(label, ptrs, usePivot, body) {
    if(ptrs.length === 1) {
      code.push("ptr0="+toPointer(ptrs[0]))
    } else {
      for(var i=0; i<ptrs.length; ++i) {
        code.push(["b_ptr",i,"=s0*",ptrs[i]].join(""))
      }
      code.push("ptr_shift=offset")
    }
    if(usePivot) {
      code.push("pivot_ptr=0")
    }
    if(label) {
      code.push(label+":")
    }
    for(var i=1; i<order.length; ++i) {
      code.push(["for(i",i,"=0;i",i,"<n",i,";++i",i,"){"].join(""))
    }
    if(ptrs.length > 1) {
      for(var i=0; i<ptrs.length; ++i) {
        code.push(["ptr",i,"=b_ptr",i,"+ptr_shift"].join(""))
      }
    }
    code.push(body)
    for(var i=order.length-1; i>=1; --i) {
      if(usePivot) {
        code.push("pivot_ptr+=f"+i)
      }
      if(ptrs.length > 1) {
        code.push("ptr_shift+=e"+i)
      } else {
        code.push("ptr0+=e"+i)
      }
      code.push("}")
    }
  }
  
  function cleanUp() {
    if(order.length > 1 && allocator) {
      code.push("free(pivot1)", "free(pivot2)")
    }
  }
  
  function compareSwap(a_id, b_id) {
    var a = "el"+a_id
    var b = "el"+b_id
    if(order.length > 1) {
      var lbl = "__l" + (++labelCounter)
      lexicoLoop(lbl, [a, b], false, [
        "comp=",dataRead("ptr0"),"-",dataRead("ptr1"),"\n",
        "if(comp>0){tmp0=", a, ";",a,"=",b,";", b,"=tmp0;break ", lbl,"}\n",
        "if(comp<0){break ", lbl, "}"
      ].join(""))
    } else {
      code.push(["if(", dataRead(toPointer(a)), ">", dataRead(toPointer(b)), "){tmp0=", a, ";",a,"=",b,";", b,"=tmp0}"].join(""))
    }
  }
  
  compareSwap(1, 2)
  compareSwap(4, 5)
  compareSwap(1, 3)
  compareSwap(2, 3)
  compareSwap(1, 4)
  compareSwap(3, 4)
  compareSwap(2, 5)
  compareSwap(2, 3)
  compareSwap(4, 5)
  
  if(order.length > 1) {
    cacheLoop(["el1", "el2", "el3", "el4", "el5", "index1", "index3", "index5"], true, [
      "pivot1[pivot_ptr]=",dataRead("ptr1"),"\n",
      "pivot2[pivot_ptr]=",dataRead("ptr3"),"\n",
      "pivots_are_equal=pivots_are_equal&&(pivot1[pivot_ptr]===pivot2[pivot_ptr])\n",
      "x=",dataRead("ptr0"),"\n",
      "y=",dataRead("ptr2"),"\n",
      "z=",dataRead("ptr4"),"\n",
      dataWrite("ptr5", "x"),"\n",
      dataWrite("ptr6", "y"),"\n",
      dataWrite("ptr7", "z")
    ].join(""))
  } else {
    code.push([
      "pivot1=", dataRead(toPointer("el2")), "\n",
      "pivot2=", dataRead(toPointer("el4")), "\n",
      "pivots_are_equal=pivot1===pivot2\n",
      "x=", dataRead(toPointer("el1")), "\n",
      "y=", dataRead(toPointer("el3")), "\n",
      "z=", dataRead(toPointer("el5")), "\n",
      dataWrite(toPointer("index1"), "x"), "\n",
      dataWrite(toPointer("index3"), "y"), "\n",
      dataWrite(toPointer("index5"), "z")
    ].join(""))
  }
  

  function moveElement(dst, src) {
    if(order.length > 1) {
      cacheLoop([dst, src], false,
        dataWrite("ptr0", dataRead("ptr1"))
      )
    } else {
      code.push(dataWrite(toPointer(dst), dataRead(toPointer(src))))
    }
  }
  
  moveElement("index2", "left")
  moveElement("index4", "right")
  
  function comparePivot(result, ptr, n) {
    if(order.length > 1) {
      var lbl = "__l" + (++labelCounter)
      lexicoLoop(lbl, [ptr], true, [
        result,"=",dataRead("ptr0"),"-pivot",n,"[pivot_ptr]\n",
        "if(",result,"!==0){break ", lbl, "}"
      ].join(""))
    } else {
      code.push([result,"=", dataRead(toPointer(ptr)), "-pivot", n].join(""))
    }
  }
  
  function swapElements(a, b) {
    if(order.length > 1) {
      cacheLoop([a,b],false,[
        "tmp=",dataRead("ptr0"),"\n",
        dataWrite("ptr0", dataRead("ptr1")),"\n",
        dataWrite("ptr1", "tmp")
      ].join(""))
    } else {
      code.push([
        "ptr0=",toPointer(a),"\n",
        "ptr1=",toPointer(b),"\n",
        "tmp=",dataRead("ptr0"),"\n",
        dataWrite("ptr0", dataRead("ptr1")),"\n",
        dataWrite("ptr1", "tmp")
      ].join(""))
    }
  }
  
  function tripleSwap(k, less, great) {
    if(order.length > 1) {
      cacheLoop([k,less,great], false, [
        "tmp=",dataRead("ptr0"),"\n",
        dataWrite("ptr0", dataRead("ptr1")),"\n",
        dataWrite("ptr1", dataRead("ptr2")),"\n",
        dataWrite("ptr2", "tmp")
      ].join(""))
      code.push("++"+less, "--"+great)
    } else {
      code.push([
        "ptr0=",toPointer(k),"\n",
        "ptr1=",toPointer(less),"\n",
        "ptr2=",toPointer(great),"\n",
        "++",less,"\n",
        "--",great,"\n",
        "tmp=", dataRead("ptr0"), "\n",
        dataWrite("ptr0", dataRead("ptr1")), "\n",
        dataWrite("ptr1", dataRead("ptr2")), "\n",
        dataWrite("ptr2", "tmp")
      ].join(""))
    }
  }
  
  function swapAndDecrement(k, great) {
    swapElements(k, great)
    code.push("--"+great)
  }
    
  code.push("if(pivots_are_equal){")
    //Pivots are equal case
    code.push("for(k=less;k<=great;++k){")
      comparePivot("comp", "k", 1)
      code.push("if(comp===0){continue}")
      code.push("if(comp<0){")
        code.push("if(k!==less){")
          swapElements("k", "less")
        code.push("}")
        code.push("++less")
      code.push("}else{")
        code.push("while(true){")
          comparePivot("comp", "great", 1)
          code.push("if(comp>0){")
            code.push("great--")
          code.push("}else if(comp<0){")
            tripleSwap("k", "less", "great")
            code.push("break")
          code.push("}else{")
            swapAndDecrement("k", "great")
            code.push("break")
          code.push("}")
        code.push("}")
      code.push("}")
    code.push("}")
  code.push("}else{")
    //Pivots not equal case
    code.push("for(k=less;k<=great;++k){")
      comparePivot("comp_pivot1", "k", 1)
      code.push("if(comp_pivot1<0){")
        code.push("if(k!==less){")
          swapElements("k", "less")
        code.push("}")
        code.push("++less")
      code.push("}else{")
        comparePivot("comp_pivot2", "k", 2)
        code.push("if(comp_pivot2>0){")
          code.push("while(true){")
            comparePivot("comp", "great", 2)
            code.push("if(comp>0){")
              code.push("if(--great<k){break}")
              code.push("continue")
            code.push("}else{")
              comparePivot("comp", "great", 1)
              code.push("if(comp<0){")
                tripleSwap("k", "less", "great")
              code.push("}else{")
                swapAndDecrement("k", "great")
              code.push("}")
              code.push("break")
            code.push("}")
          code.push("}")
        code.push("}")
      code.push("}")
    code.push("}")
  code.push("}")
  
  //Move pivots to correct place
  function storePivot(mem_dest, pivot_dest, pivot) {
    if(order.length>1) {
      cacheLoop([mem_dest, pivot_dest], true, [
        dataWrite("ptr0", dataRead("ptr1")), "\n",
        dataWrite("ptr1", ["pivot",pivot,"[pivot_ptr]"].join(""))
      ].join(""))
    } else {
      code.push(
          dataWrite(toPointer(mem_dest), dataRead(toPointer(pivot_dest))),
          dataWrite(toPointer(pivot_dest), "pivot"+pivot))
    }
  }
  
  storePivot("left", "(less-1)", 1)
  storePivot("right", "(great+1)", 2)

  //Recursive sort call
  function doSort(left, right) {
    code.push([
      "if((",right,"-",left,")<=",INSERTION_SORT_THRESHOLD,"){\n",
        "insertionSort(", left, ",", right, ",data,offset,", shapeArgs(order.length).join(","), ")\n",
      "}else{\n",
        funcName, "(", left, ",", right, ",data,offset,", shapeArgs(order.length).join(","), ")\n",
      "}"
    ].join(""))
  }
  doSort("left", "(less-2)")
  doSort("(great+2)", "right")
  
  //If pivots are equal, then early out
  code.push("if(pivots_are_equal){")
    cleanUp()
    code.push("return")
  code.push("}")
  
  function walkPointer(ptr, pivot, body) {
    if(order.length > 1) {
      code.push(["__l",++labelCounter,":while(true){"].join(""))
      cacheLoop([ptr], true, [
        "if(", dataRead("ptr0"), "!==pivot", pivot, "[pivot_ptr]){break __l", labelCounter, "}"
      ].join(""))
      code.push(body, "}")
    } else {
      code.push(["while(", dataRead(toPointer(ptr)), "===pivot", pivot, "){", body, "}"].join(""))
    }
  }
  
  //Check bounds
  code.push("if(less<index1&&great>index5){")
  
    walkPointer("less", 1, "++less")
    walkPointer("great", 2, "--great")
  
    code.push("for(k=less;k<=great;++k){")
      comparePivot("comp_pivot1", "k", 1)
      code.push("if(comp_pivot1===0){")
        code.push("if(k!==less){")
          swapElements("k", "less")
        code.push("}")
        code.push("++less")
      code.push("}else{")
        comparePivot("comp_pivot2", "k", 2)
        code.push("if(comp_pivot2===0){")
          code.push("while(true){")
            comparePivot("comp", "great", 2)
            code.push("if(comp===0){")
              code.push("if(--great<k){break}")
              code.push("continue")
            code.push("}else{")
              comparePivot("comp", "great", 1)
              code.push("if(comp<0){")
                tripleSwap("k", "less", "great")
              code.push("}else{")
                swapAndDecrement("k", "great")
              code.push("}")
              code.push("break")
            code.push("}")
          code.push("}")
        code.push("}")
      code.push("}")
    code.push("}")
  code.push("}")
  
  //Clean up and do a final sorting pass
  cleanUp()
  doSort("less", "great")
 
  //Close off main loop
  code.push("}return " + funcName)
  
  //Compile and link
  if(order.length > 1 && allocator) {
    var compiled = new Function("insertionSort", "malloc", "free", code.join("\n"))
    return compiled(insertionSort, allocator[0], allocator[1])
  }
  var compiled = new Function("insertionSort", code.join("\n"))
  return compiled(insertionSort)
}

function compileSort(order, dtype) {
  var code = ["'use strict'"]
  var funcName = ["ndarraySortWrapper", order.join("d"), dtype].join("")
  var funcArgs = [ "array" ]
  
  code.push(["function ", funcName, "(", funcArgs.join(","), "){"].join(""))
  
  //Unpack local variables from array
  var vars = ["data=array.data,offset=array.offset|0,shape=array.shape,stride=array.stride"]
  for(var i=0; i<order.length; ++i) {
    vars.push(["s",i,"=stride[",i,"]|0,n",i,"=shape[",i,"]|0"].join(""))
  }
  
  var scratch_stride = new Array(order.length)
  var nprod = []
  for(var i=0; i<order.length; ++i) {
    var k = order[i]
    if(k === 0) {
      continue
    }
    if(nprod.length === 0) {
      scratch_stride[k] = "1"
    } else {
      scratch_stride[k] = nprod.join("*")
    }
    nprod.push("n"+k)
  }
  
  var p = -1, q = -1
  for(var i=0; i<order.length; ++i) {
    var j = order[i]
    if(j !== 0) {
      if(p > 0) {
        vars.push(["d",j,"=s",j,"-d",p,"*n",p].join(""))
      } else {
        vars.push(["d",j,"=s",j].join(""))
      }
      p = j
    }
    var k = order.length-1-i
    if(k !== 0) {
      if(q > 0) {
        vars.push(["e",k,"=s",k,"-e",q,"*n",q,
                  ",f",k,"=",scratch_stride[k],"-f",q,"*n",q].join(""))
      } else {
        vars.push(["e",k,"=s",k,",f",k,"=",scratch_stride[k]].join(""))
      }
      q = k
    }
  }
  
  //Declare local variables
  code.push("var " + vars.join(","))
  
  //Create arguments for subroutine
  var sortArgs = ["0", "n0-1", "data", "offset"].concat(shapeArgs(order.length))
  
  //Call main sorting routine
  code.push([
    "if(n0<=",INSERTION_SORT_THRESHOLD,"){",
      "insertionSort(", sortArgs.join(","), ")}else{",
      "quickSort(", sortArgs.join(","),
    ")}"
  ].join(""))
  
  //Return
  code.push("}return " + funcName)
  
  //Link everything together
  var result = new Function("insertionSort", "quickSort", code.join("\n"))
  var insertionSort = createInsertionSort(order, dtype)
  var quickSort = createQuickSort(order, dtype, insertionSort)
  return result(insertionSort, quickSort)
}

module.exports = compileSort
},{"typedarray-pool":523}],434:[function(_dereq_,module,exports){
"use strict"

var compile = _dereq_("./lib/compile_sort.js")
var CACHE = {}

function sort(array) {
  var order = array.order
  var dtype = array.dtype
  var typeSig = [order, dtype ]
  var typeName = typeSig.join(":")
  var compiled = CACHE[typeName]
  if(!compiled) {
    CACHE[typeName] = compiled = compile(order, dtype)
  }
  compiled(array)
  return array
}

module.exports = sort
},{"./lib/compile_sort.js":433}],435:[function(_dereq_,module,exports){
'use strict'

var interp  = _dereq_('ndarray-linear-interpolate')


var do_warp = _dereq_('cwise/lib/wrapper')({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=new Array(_inline_3_arg4_)}","args":[{"name":"_inline_3_arg0_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_3_arg1_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_3_arg2_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_3_arg3_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_3_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_4_arg2_(this_warped,_inline_4_arg0_),_inline_4_arg1_=_inline_4_arg3_.apply(void 0,this_warped)}","args":[{"name":"_inline_4_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_4_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_4_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_4_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_4_arg4_","lvalue":false,"rvalue":false,"count":0}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warpND","blockSize":64})

var do_warp_1 = _dereq_('cwise/lib/wrapper')({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=[0]}","args":[],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_7_arg2_(this_warped,_inline_7_arg0_),_inline_7_arg1_=_inline_7_arg3_(_inline_7_arg4_,this_warped[0])}","args":[{"name":"_inline_7_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_7_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_7_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_7_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_7_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warp1D","blockSize":64})

var do_warp_2 = _dereq_('cwise/lib/wrapper')({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=[0,0]}","args":[],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_10_arg2_(this_warped,_inline_10_arg0_),_inline_10_arg1_=_inline_10_arg3_(_inline_10_arg4_,this_warped[0],this_warped[1])}","args":[{"name":"_inline_10_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_10_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_10_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_10_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_10_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warp2D","blockSize":64})

var do_warp_3 = _dereq_('cwise/lib/wrapper')({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=[0,0,0]}","args":[],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_13_arg2_(this_warped,_inline_13_arg0_),_inline_13_arg1_=_inline_13_arg3_(_inline_13_arg4_,this_warped[0],this_warped[1],this_warped[2])}","args":[{"name":"_inline_13_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_13_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_13_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_13_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_13_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warp3D","blockSize":64})

module.exports = function warp(dest, src, func) {
  switch(src.shape.length) {
    case 1:
      do_warp_1(dest, func, interp.d1, src)
      break
    case 2:
      do_warp_2(dest, func, interp.d2, src)
      break
    case 3:
      do_warp_3(dest, func, interp.d3, src)
      break
    default:
      do_warp(dest, func, interp.bind(undefined, src), src.shape.length)
      break
  }
  return dest
}

},{"cwise/lib/wrapper":138,"ndarray-linear-interpolate":429}],436:[function(_dereq_,module,exports){
var iota = _dereq_("iota-array")
var isBuffer = _dereq_("is-buffer")

var hasTypedArrays  = ((typeof Float64Array) !== "undefined")

function compare1st(a, b) {
  return a[0] - b[0]
}

function order() {
  var stride = this.stride
  var terms = new Array(stride.length)
  var i
  for(i=0; i<terms.length; ++i) {
    terms[i] = [Math.abs(stride[i]), i]
  }
  terms.sort(compare1st)
  var result = new Array(terms.length)
  for(i=0; i<result.length; ++i) {
    result[i] = terms[i][1]
  }
  return result
}

function compileConstructor(dtype, dimension) {
  var className = ["View", dimension, "d", dtype].join("")
  if(dimension < 0) {
    className = "View_Nil" + dtype
  }
  var useGetters = (dtype === "generic")

  if(dimension === -1) {
    //Special case for trivial arrays
    var code =
      "function "+className+"(a){this.data=a;};\
var proto="+className+".prototype;\
proto.dtype='"+dtype+"';\
proto.index=function(){return -1};\
proto.size=0;\
proto.dimension=-1;\
proto.shape=proto.stride=proto.order=[];\
proto.lo=proto.hi=proto.transpose=proto.step=\
function(){return new "+className+"(this.data);};\
proto.get=proto.set=function(){};\
proto.pick=function(){return null};\
return function construct_"+className+"(a){return new "+className+"(a);}"
    var procedure = new Function(code)
    return procedure()
  } else if(dimension === 0) {
    //Special case for 0d arrays
    var code =
      "function "+className+"(a,d) {\
this.data = a;\
this.offset = d\
};\
var proto="+className+".prototype;\
proto.dtype='"+dtype+"';\
proto.index=function(){return this.offset};\
proto.dimension=0;\
proto.size=1;\
proto.shape=\
proto.stride=\
proto.order=[];\
proto.lo=\
proto.hi=\
proto.transpose=\
proto.step=function "+className+"_copy() {\
return new "+className+"(this.data,this.offset)\
};\
proto.pick=function "+className+"_pick(){\
return TrivialArray(this.data);\
};\
proto.valueOf=proto.get=function "+className+"_get(){\
return "+(useGetters ? "this.data.get(this.offset)" : "this.data[this.offset]")+
"};\
proto.set=function "+className+"_set(v){\
return "+(useGetters ? "this.data.set(this.offset,v)" : "this.data[this.offset]=v")+"\
};\
return function construct_"+className+"(a,b,c,d){return new "+className+"(a,d)}"
    var procedure = new Function("TrivialArray", code)
    return procedure(CACHED_CONSTRUCTORS[dtype][0])
  }

  var code = ["'use strict'"]

  //Create constructor for view
  var indices = iota(dimension)
  var args = indices.map(function(i) { return "i"+i })
  var index_str = "this.offset+" + indices.map(function(i) {
        return "this.stride[" + i + "]*i" + i
      }).join("+")
  var shapeArg = indices.map(function(i) {
      return "b"+i
    }).join(",")
  var strideArg = indices.map(function(i) {
      return "c"+i
    }).join(",")
  code.push(
    "function "+className+"(a," + shapeArg + "," + strideArg + ",d){this.data=a",
      "this.shape=[" + shapeArg + "]",
      "this.stride=[" + strideArg + "]",
      "this.offset=d|0}",
    "var proto="+className+".prototype",
    "proto.dtype='"+dtype+"'",
    "proto.dimension="+dimension)

  //view.size:
  code.push("Object.defineProperty(proto,'size',{get:function "+className+"_size(){\
return "+indices.map(function(i) { return "this.shape["+i+"]" }).join("*"),
"}})")

  //view.order:
  if(dimension === 1) {
    code.push("proto.order=[0]")
  } else {
    code.push("Object.defineProperty(proto,'order',{get:")
    if(dimension < 4) {
      code.push("function "+className+"_order(){")
      if(dimension === 2) {
        code.push("return (Math.abs(this.stride[0])>Math.abs(this.stride[1]))?[1,0]:[0,1]}})")
      } else if(dimension === 3) {
        code.push(
"var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);\
if(s0>s1){\
if(s1>s2){\
return [2,1,0];\
}else if(s0>s2){\
return [1,2,0];\
}else{\
return [1,0,2];\
}\
}else if(s0>s2){\
return [2,0,1];\
}else if(s2>s1){\
return [0,1,2];\
}else{\
return [0,2,1];\
}}})")
      }
    } else {
      code.push("ORDER})")
    }
  }

  //view.set(i0, ..., v):
  code.push(
"proto.set=function "+className+"_set("+args.join(",")+",v){")
  if(useGetters) {
    code.push("return this.data.set("+index_str+",v)}")
  } else {
    code.push("return this.data["+index_str+"]=v}")
  }

  //view.get(i0, ...):
  code.push("proto.get=function "+className+"_get("+args.join(",")+"){")
  if(useGetters) {
    code.push("return this.data.get("+index_str+")}")
  } else {
    code.push("return this.data["+index_str+"]}")
  }

  //view.index:
  code.push(
    "proto.index=function "+className+"_index(", args.join(), "){return "+index_str+"}")

  //view.hi():
  code.push("proto.hi=function "+className+"_hi("+args.join(",")+"){return new "+className+"(this.data,"+
    indices.map(function(i) {
      return ["(typeof i",i,"!=='number'||i",i,"<0)?this.shape[", i, "]:i", i,"|0"].join("")
    }).join(",")+","+
    indices.map(function(i) {
      return "this.stride["+i + "]"
    }).join(",")+",this.offset)}")

  //view.lo():
  var a_vars = indices.map(function(i) { return "a"+i+"=this.shape["+i+"]" })
  var c_vars = indices.map(function(i) { return "c"+i+"=this.stride["+i+"]" })
  code.push("proto.lo=function "+className+"_lo("+args.join(",")+"){var b=this.offset,d=0,"+a_vars.join(",")+","+c_vars.join(","))
  for(var i=0; i<dimension; ++i) {
    code.push(
"if(typeof i"+i+"==='number'&&i"+i+">=0){\
d=i"+i+"|0;\
b+=c"+i+"*d;\
a"+i+"-=d}")
  }
  code.push("return new "+className+"(this.data,"+
    indices.map(function(i) {
      return "a"+i
    }).join(",")+","+
    indices.map(function(i) {
      return "c"+i
    }).join(",")+",b)}")

  //view.step():
  code.push("proto.step=function "+className+"_step("+args.join(",")+"){var "+
    indices.map(function(i) {
      return "a"+i+"=this.shape["+i+"]"
    }).join(",")+","+
    indices.map(function(i) {
      return "b"+i+"=this.stride["+i+"]"
    }).join(",")+",c=this.offset,d=0,ceil=Math.ceil")
  for(var i=0; i<dimension; ++i) {
    code.push(
"if(typeof i"+i+"==='number'){\
d=i"+i+"|0;\
if(d<0){\
c+=b"+i+"*(a"+i+"-1);\
a"+i+"=ceil(-a"+i+"/d)\
}else{\
a"+i+"=ceil(a"+i+"/d)\
}\
b"+i+"*=d\
}")
  }
  code.push("return new "+className+"(this.data,"+
    indices.map(function(i) {
      return "a" + i
    }).join(",")+","+
    indices.map(function(i) {
      return "b" + i
    }).join(",")+",c)}")

  //view.transpose():
  var tShape = new Array(dimension)
  var tStride = new Array(dimension)
  for(var i=0; i<dimension; ++i) {
    tShape[i] = "a[i"+i+"]"
    tStride[i] = "b[i"+i+"]"
  }
  code.push("proto.transpose=function "+className+"_transpose("+args+"){"+
    args.map(function(n,idx) { return n + "=(" + n + "===undefined?" + idx + ":" + n + "|0)"}).join(";"),
    "var a=this.shape,b=this.stride;return new "+className+"(this.data,"+tShape.join(",")+","+tStride.join(",")+",this.offset)}")

  //view.pick():
  code.push("proto.pick=function "+className+"_pick("+args+"){var a=[],b=[],c=this.offset")
  for(var i=0; i<dimension; ++i) {
    code.push("if(typeof i"+i+"==='number'&&i"+i+">=0){c=(c+this.stride["+i+"]*i"+i+")|0}else{a.push(this.shape["+i+"]);b.push(this.stride["+i+"])}")
  }
  code.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}")

  //Add return statement
  code.push("return function construct_"+className+"(data,shape,stride,offset){return new "+className+"(data,"+
    indices.map(function(i) {
      return "shape["+i+"]"
    }).join(",")+","+
    indices.map(function(i) {
      return "stride["+i+"]"
    }).join(",")+",offset)}")

  //Compile procedure
  var procedure = new Function("CTOR_LIST", "ORDER", code.join("\n"))
  return procedure(CACHED_CONSTRUCTORS[dtype], order)
}

function arrayDType(data) {
  if(isBuffer(data)) {
    return "buffer"
  }
  if(hasTypedArrays) {
    switch(Object.prototype.toString.call(data)) {
      case "[object Float64Array]":
        return "float64"
      case "[object Float32Array]":
        return "float32"
      case "[object Int8Array]":
        return "int8"
      case "[object Int16Array]":
        return "int16"
      case "[object Int32Array]":
        return "int32"
      case "[object Uint8Array]":
        return "uint8"
      case "[object Uint16Array]":
        return "uint16"
      case "[object Uint32Array]":
        return "uint32"
      case "[object Uint8ClampedArray]":
        return "uint8_clamped"
    }
  }
  if(Array.isArray(data)) {
    return "array"
  }
  return "generic"
}

var CACHED_CONSTRUCTORS = {
  "float32":[],
  "float64":[],
  "int8":[],
  "int16":[],
  "int32":[],
  "uint8":[],
  "uint16":[],
  "uint32":[],
  "array":[],
  "uint8_clamped":[],
  "buffer":[],
  "generic":[]
}

;(function() {
  for(var id in CACHED_CONSTRUCTORS) {
    CACHED_CONSTRUCTORS[id].push(compileConstructor(id, -1))
  }
});

function wrappedNDArrayCtor(data, shape, stride, offset) {
  if(data === undefined) {
    var ctor = CACHED_CONSTRUCTORS.array[0]
    return ctor([])
  } else if(typeof data === "number") {
    data = [data]
  }
  if(shape === undefined) {
    shape = [ data.length ]
  }
  var d = shape.length
  if(stride === undefined) {
    stride = new Array(d)
    for(var i=d-1, sz=1; i>=0; --i) {
      stride[i] = sz
      sz *= shape[i]
    }
  }
  if(offset === undefined) {
    offset = 0
    for(var i=0; i<d; ++i) {
      if(stride[i] < 0) {
        offset -= (shape[i]-1)*stride[i]
      }
    }
  }
  var dtype = arrayDType(data)
  var ctor_list = CACHED_CONSTRUCTORS[dtype]
  while(ctor_list.length <= d+1) {
    ctor_list.push(compileConstructor(dtype, ctor_list.length-1))
  }
  var ctor = ctor_list[d+1]
  return ctor(data, shape, stride, offset)
}

module.exports = wrappedNDArrayCtor

},{"iota-array":402,"is-buffer":404}],437:[function(_dereq_,module,exports){
"use strict"

var doubleBits = _dereq_("double-bits")

var SMALLEST_DENORM = Math.pow(2, -1074)
var UINT_MAX = (-1)>>>0

module.exports = nextafter

function nextafter(x, y) {
  if(isNaN(x) || isNaN(y)) {
    return NaN
  }
  if(x === y) {
    return x
  }
  if(x === 0) {
    if(y < 0) {
      return -SMALLEST_DENORM
    } else {
      return SMALLEST_DENORM
    }
  }
  var hi = doubleBits.hi(x)
  var lo = doubleBits.lo(x)
  if((y > x) === (x > 0)) {
    if(lo === UINT_MAX) {
      hi += 1
      lo = 0
    } else {
      lo += 1
    }
  } else {
    if(lo === 0) {
      lo = UINT_MAX
      hi -= 1
    } else {
      lo -= 1
    }
  }
  return doubleBits.pack(lo, hi)
}
},{"double-bits":153}],438:[function(_dereq_,module,exports){

var π = Math.PI
var _120 = radians(120)

module.exports = normalize

/**
 * describe `path` in terms of cubic bézier 
 * curves and move commands
 *
 * @param {Array} path
 * @return {Array}
 */

function normalize(path){
	// init state
	var prev
	var result = []
	var bezierX = 0
	var bezierY = 0
	var startX = 0
	var startY = 0
	var quadX = null
	var quadY = null
	var x = 0
	var y = 0

	for (var i = 0, len = path.length; i < len; i++) {
		var seg = path[i]
		var command = seg[0]
		switch (command) {
			case 'M':
				startX = seg[1]
				startY = seg[2]
				break
			case 'A':
				seg = arc(x, y,seg[1],seg[2],radians(seg[3]),seg[4],seg[5],seg[6],seg[7])
				// split multi part
				seg.unshift('C')
				if (seg.length > 7) {
					result.push(seg.splice(0, 7))
					seg.unshift('C')
				}
				break
			case 'S':
				// default control point
				var cx = x
				var cy = y
				if (prev == 'C' || prev == 'S') {
					cx += cx - bezierX // reflect the previous command's control
					cy += cy - bezierY // point relative to the current point
				}
				seg = ['C', cx, cy, seg[1], seg[2], seg[3], seg[4]]
				break
			case 'T':
				if (prev == 'Q' || prev == 'T') {
					quadX = x * 2 - quadX // as with 'S' reflect previous control point
					quadY = y * 2 - quadY
				} else {
					quadX = x
					quadY = y
				}
				seg = quadratic(x, y, quadX, quadY, seg[1], seg[2])
				break
			case 'Q':
				quadX = seg[1]
				quadY = seg[2]
				seg = quadratic(x, y, seg[1], seg[2], seg[3], seg[4])
				break
			case 'L':
				seg = line(x, y, seg[1], seg[2])
				break
			case 'H':
				seg = line(x, y, seg[1], y)
				break
			case 'V':
				seg = line(x, y, x, seg[1])
				break
			case 'Z':
				seg = line(x, y, startX, startY)
				break
		}

		// update state
		prev = command
		x = seg[seg.length - 2]
		y = seg[seg.length - 1]
		if (seg.length > 4) {
			bezierX = seg[seg.length - 4]
			bezierY = seg[seg.length - 3]
		} else {
			bezierX = x
			bezierY = y
		}
		result.push(seg)
	}

	return result
}

function line(x1, y1, x2, y2){
	return ['C', x1, y1, x2, y2, x2, y2]
}

function quadratic(x1, y1, cx, cy, x2, y2){
	return [
		'C',
		x1/3 + (2/3) * cx,
		y1/3 + (2/3) * cy,
		x2/3 + (2/3) * cx,
		y2/3 + (2/3) * cy,
		x2,
		y2
	]
}

// This function is ripped from 
// github.com/DmitryBaranovskiy/raphael/blob/4d97d4/raphael.js#L2216-L2304 
// which references w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
// TODO: make it human readable

function arc(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) {
	if (!recursive) {
		var xy = rotate(x1, y1, -angle)
		x1 = xy.x
		y1 = xy.y
		xy = rotate(x2, y2, -angle)
		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 = Math.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)
			* Math.sqrt(Math.abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x)))
		if (k == Infinity) k = 1 // neutralize
		var cx = k * rx * y / ry + (x1 + x2) / 2
		var cy = k * -ry * x / rx + (y1 + y2) / 2
		var f1 = Math.asin(((y1 - cy) / ry).toFixed(9))
		var f2 = Math.asin(((y2 - cy) / ry).toFixed(9))

		f1 = x1 < cx ? π - f1 : f1
		f2 = x2 < cx ? π - f2 : f2
		if (f1 < 0) f1 = π * 2 + f1
		if (f2 < 0) f2 = π * 2 + f2
		if (sweep_flag && f1 > f2) f1 = f1 - π * 2
		if (!sweep_flag && f2 > f1) f2 = f2 - π * 2
	} else {
		f1 = recursive[0]
		f2 = recursive[1]
		cx = recursive[2]
		cy = recursive[3]
	}
	// greater than 120 degrees requires multiple segments
	if (Math.abs(f2 - f1) > _120) {
		var f2old = f2
		var x2old = x2
		var y2old = y2
		f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1)
		x2 = cx + rx * Math.cos(f2)
		y2 = cy + ry * Math.sin(f2)
		var res = arc(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy])
	}
	var t = Math.tan((f2 - f1) / 4)
	var hx = 4 / 3 * rx * t
	var hy = 4 / 3 * ry * t
	var curve = [
		2 * x1 - (x1 + hx * Math.sin(f1)),
		2 * y1 - (y1 - hy * Math.cos(f1)),
		x2 + hx * Math.sin(f2),
		y2 - hy * Math.cos(f2),
		x2,
		y2
	]
	if (recursive) return curve
	if (res) curve = curve.concat(res)
	for (var i = 0; i < curve.length;) {
		var rot = rotate(curve[i], curve[i+1], angle)
		curve[i++] = rot.x
		curve[i++] = rot.y
	}
	return curve
}

function rotate(x, y, rad){
	return {
		x: x * Math.cos(rad) - y * Math.sin(rad),
		y: x * Math.sin(rad) + y * Math.cos(rad)
	}
}

function radians(degress){
	return degress * (π / 180)
}

},{}],439:[function(_dereq_,module,exports){
var DEFAULT_NORMALS_EPSILON = 1e-6;
var DEFAULT_FACE_EPSILON = 1e-6;

//Estimate the vertex normals of a mesh
exports.vertexNormals = function(faces, positions, specifiedEpsilon) {

  var N         = positions.length;
  var normals   = new Array(N);
  var epsilon   = specifiedEpsilon === void(0) ? DEFAULT_NORMALS_EPSILON : specifiedEpsilon;

  //Initialize normal array
  for(var i=0; i<N; ++i) {
    normals[i] = [0.0, 0.0, 0.0];
  }

  //Walk over all the faces and add per-vertex contribution to normal weights
  for(var i=0; i<faces.length; ++i) {
    var f = faces[i];
    var p = 0;
    var c = f[f.length-1];
    var n = f[0];
    for(var j=0; j<f.length; ++j) {

      //Shift indices back
      p = c;
      c = n;
      n = f[(j+1) % f.length];

      var v0 = positions[p];
      var v1 = positions[c];
      var v2 = positions[n];

      //Compute infineteismal arcs
      var d01 = new Array(3);
      var m01 = 0.0;
      var d21 = new Array(3);
      var m21 = 0.0;
      for(var k=0; k<3; ++k) {
        d01[k] = v0[k]  - v1[k];
        m01   += d01[k] * d01[k];
        d21[k] = v2[k]  - v1[k];
        m21   += d21[k] * d21[k];
      }

      //Accumulate values in normal
      if(m01 * m21 > epsilon) {
        var norm = normals[c];
        var w = 1.0 / Math.sqrt(m01 * m21);
        for(var k=0; k<3; ++k) {
          var u = (k+1)%3;
          var v = (k+2)%3;
          norm[k] += w * (d21[u] * d01[v] - d21[v] * d01[u]);
        }
      }
    }
  }

  //Scale all normals to unit length
  for(var i=0; i<N; ++i) {
    var norm = normals[i];
    var m = 0.0;
    for(var k=0; k<3; ++k) {
      m += norm[k] * norm[k];
    }
    if(m > epsilon) {
      var w = 1.0 / Math.sqrt(m);
      for(var k=0; k<3; ++k) {
        norm[k] *= w;
      }
    } else {
      for(var k=0; k<3; ++k) {
        norm[k] = 0.0;
      }
    }
  }

  //Return the resulting set of patches
  return normals;
}

//Compute face normals of a mesh
exports.faceNormals = function(faces, positions, specifiedEpsilon) {

  var N         = faces.length;
  var normals   = new Array(N);
  var epsilon   = specifiedEpsilon === void(0) ? DEFAULT_FACE_EPSILON : specifiedEpsilon;

  for(var i=0; i<N; ++i) {
    var f = faces[i];
    var pos = new Array(3);
    for(var j=0; j<3; ++j) {
      pos[j] = positions[f[j]];
    }

    var d01 = new Array(3);
    var d21 = new Array(3);
    for(var j=0; j<3; ++j) {
      d01[j] = pos[1][j] - pos[0][j];
      d21[j] = pos[2][j] - pos[0][j];
    }

    var n = new Array(3);
    var l = 0.0;
    for(var j=0; j<3; ++j) {
      var u = (j+1)%3;
      var v = (j+2)%3;
      n[j] = d01[u] * d21[v] - d01[v] * d21[u];
      l += n[j] * n[j];
    }
    if(l > epsilon) {
      l = 1.0 / Math.sqrt(l);
    } else {
      l = 0.0;
    }
    for(var j=0; j<3; ++j) {
      n[j] *= l;
    }
    normals[i] = n;
  }
  return normals;
}



},{}],440:[function(_dereq_,module,exports){
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/

'use strict';
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;

function toObject(val) {
	if (val === null || val === undefined) {
		throw new TypeError('Object.assign cannot be called with null or undefined');
	}

	return Object(val);
}

function shouldUseNative() {
	try {
		if (!Object.assign) {
			return false;
		}

		// Detect buggy property enumeration order in older V8 versions.

		// https://bugs.chromium.org/p/v8/issues/detail?id=4118
		var test1 = new String('abc');  // eslint-disable-line no-new-wrappers
		test1[5] = 'de';
		if (Object.getOwnPropertyNames(test1)[0] === '5') {
			return false;
		}

		// https://bugs.chromium.org/p/v8/issues/detail?id=3056
		var test2 = {};
		for (var i = 0; i < 10; i++) {
			test2['_' + String.fromCharCode(i)] = i;
		}
		var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
			return test2[n];
		});
		if (order2.join('') !== '0123456789') {
			return false;
		}

		// https://bugs.chromium.org/p/v8/issues/detail?id=3056
		var test3 = {};
		'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
			test3[letter] = letter;
		});
		if (Object.keys(Object.assign({}, test3)).join('') !==
				'abcdefghijklmnopqrst') {
			return false;
		}

		return true;
	} catch (err) {
		// We don't expect any of the above to throw, but better to be safe.
		return false;
	}
}

module.exports = shouldUseNative() ? Object.assign : function (target, source) {
	var from;
	var to = toObject(target);
	var symbols;

	for (var s = 1; s < arguments.length; s++) {
		from = Object(arguments[s]);

		for (var key in from) {
			if (hasOwnProperty.call(from, key)) {
				to[key] = from[key];
			}
		}

		if (getOwnPropertySymbols) {
			symbols = getOwnPropertySymbols(from);
			for (var i = 0; i < symbols.length; i++) {
				if (propIsEnumerable.call(from, symbols[i])) {
					to[symbols[i]] = from[symbols[i]];
				}
			}
		}
	}

	return to;
};

},{}],441:[function(_dereq_,module,exports){
'use strict'

module.exports = quatFromFrame

function quatFromFrame(
  out,
  rx, ry, rz,
  ux, uy, uz,
  fx, fy, fz) {
  var tr = rx + uy + fz
  if(l > 0) {
    var l = Math.sqrt(tr + 1.0)
    out[0] = 0.5 * (uz - fy) / l
    out[1] = 0.5 * (fx - rz) / l
    out[2] = 0.5 * (ry - uy) / l
    out[3] = 0.5 * l
  } else {
    var tf = Math.max(rx, uy, fz)
    var l = Math.sqrt(2 * tf - tr + 1.0)
    if(rx >= tf) {
      //x y z  order
      out[0] = 0.5 * l
      out[1] = 0.5 * (ux + ry) / l
      out[2] = 0.5 * (fx + rz) / l
      out[3] = 0.5 * (uz - fy) / l
    } else if(uy >= tf) {
      //y z x  order
      out[0] = 0.5 * (ry + ux) / l
      out[1] = 0.5 * l
      out[2] = 0.5 * (fy + uz) / l
      out[3] = 0.5 * (fx - rz) / l
    } else {
      //z x y  order
      out[0] = 0.5 * (rz + fx) / l
      out[1] = 0.5 * (uz + fy) / l
      out[2] = 0.5 * l
      out[3] = 0.5 * (ry - ux) / l
    }
  }
  return out
}
},{}],442:[function(_dereq_,module,exports){
'use strict'

module.exports = createOrbitController

var filterVector  = _dereq_('filtered-vector')
var lookAt        = _dereq_('gl-mat4/lookAt')
var mat4FromQuat  = _dereq_('gl-mat4/fromQuat')
var invert44      = _dereq_('gl-mat4/invert')
var quatFromFrame = _dereq_('./lib/quatFromFrame')

function len3(x,y,z) {
  return Math.sqrt(Math.pow(x,2) + Math.pow(y,2) + Math.pow(z,2))
}

function len4(w,x,y,z) {
  return Math.sqrt(Math.pow(w,2) + Math.pow(x,2) + Math.pow(y,2) + Math.pow(z,2))
}

function normalize4(out, a) {
  var ax = a[0]
  var ay = a[1]
  var az = a[2]
  var aw = a[3]
  var al = len4(ax, ay, az, aw)
  if(al > 1e-6) {
    out[0] = ax/al
    out[1] = ay/al
    out[2] = az/al
    out[3] = aw/al
  } else {
    out[0] = out[1] = out[2] = 0.0
    out[3] = 1.0
  }
}

function OrbitCameraController(initQuat, initCenter, initRadius) {
  this.radius    = filterVector([initRadius])
  this.center    = filterVector(initCenter)
  this.rotation  = filterVector(initQuat)

  this.computedRadius   = this.radius.curve(0)
  this.computedCenter   = this.center.curve(0)
  this.computedRotation = this.rotation.curve(0)
  this.computedUp       = [0.1,0,0]
  this.computedEye      = [0.1,0,0]
  this.computedMatrix   = [0.1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

  this.recalcMatrix(0)
}

var proto = OrbitCameraController.prototype

proto.lastT = function() {
  return Math.max(
    this.radius.lastT(),
    this.center.lastT(),
    this.rotation.lastT())
}

proto.recalcMatrix = function(t) {
  this.radius.curve(t)
  this.center.curve(t)
  this.rotation.curve(t)

  var quat = this.computedRotation
  normalize4(quat, quat)

  var mat = this.computedMatrix
  mat4FromQuat(mat, quat)

  var center = this.computedCenter
  var eye    = this.computedEye
  var up     = this.computedUp
  var radius = Math.exp(this.computedRadius[0])

  eye[0] = center[0] + radius * mat[2]
  eye[1] = center[1] + radius * mat[6]
  eye[2] = center[2] + radius * mat[10]
  up[0] = mat[1]
  up[1] = mat[5]
  up[2] = mat[9]

  for(var i=0; i<3; ++i) {
    var rr = 0.0
    for(var j=0; j<3; ++j) {
      rr += mat[i+4*j] * eye[j]
    }
    mat[12+i] = -rr
  }
}

proto.getMatrix = function(t, result) {
  this.recalcMatrix(t)
  var m = this.computedMatrix
  if(result) {
    for(var i=0; i<16; ++i) {
      result[i] = m[i]
    }
    return result
  }
  return m
}

proto.idle = function(t) {
  this.center.idle(t)
  this.radius.idle(t)
  this.rotation.idle(t)
}

proto.flush = function(t) {
  this.center.flush(t)
  this.radius.flush(t)
  this.rotation.flush(t)
}

proto.pan = function(t, dx, dy, dz) {
  dx = dx || 0.0
  dy = dy || 0.0
  dz = dz || 0.0

  this.recalcMatrix(t)
  var mat = this.computedMatrix

  var ux = mat[1]
  var uy = mat[5]
  var uz = mat[9]
  var ul = len3(ux, uy, uz)
  ux /= ul
  uy /= ul
  uz /= ul

  var rx = mat[0]
  var ry = mat[4]
  var rz = mat[8]
  var ru = rx * ux + ry * uy + rz * uz
  rx -= ux * ru
  ry -= uy * ru
  rz -= uz * ru
  var rl = len3(rx, ry, rz)
  rx /= rl
  ry /= rl
  rz /= rl

  var fx = mat[2]
  var fy = mat[6]
  var fz = mat[10]
  var fu = fx * ux + fy * uy + fz * uz
  var fr = fx * rx + fy * ry + fz * rz
  fx -= fu * ux + fr * rx
  fy -= fu * uy + fr * ry
  fz -= fu * uz + fr * rz
  var fl = len3(fx, fy, fz)
  fx /= fl
  fy /= fl
  fz /= fl

  var vx = rx * dx + ux * dy
  var vy = ry * dx + uy * dy
  var vz = rz * dx + uz * dy

  this.center.move(t, vx, vy, vz)

  //Update z-component of radius
  var radius = Math.exp(this.computedRadius[0])
  radius = Math.max(1e-4, radius + dz)
  this.radius.set(t, Math.log(radius))
}

proto.rotate = function(t, dx, dy, dz) {
  this.recalcMatrix(t)

  dx = dx||0.0
  dy = dy||0.0

  var mat = this.computedMatrix

  var rx = mat[0]
  var ry = mat[4]
  var rz = mat[8]

  var ux = mat[1]
  var uy = mat[5]
  var uz = mat[9]

  var fx = mat[2]
  var fy = mat[6]
  var fz = mat[10]

  var qx = dx * rx + dy * ux
  var qy = dx * ry + dy * uy
  var qz = dx * rz + dy * uz

  var bx = -(fy * qz - fz * qy)
  var by = -(fz * qx - fx * qz)
  var bz = -(fx * qy - fy * qx)  
  var bw = Math.sqrt(Math.max(0.0, 1.0 - Math.pow(bx,2) - Math.pow(by,2) - Math.pow(bz,2)))
  var bl = len4(bx, by, bz, bw)
  if(bl > 1e-6) {
    bx /= bl
    by /= bl
    bz /= bl
    bw /= bl
  } else {
    bx = by = bz = 0.0
    bw = 1.0
  }

  var rotation = this.computedRotation
  var ax = rotation[0]
  var ay = rotation[1]
  var az = rotation[2]
  var aw = rotation[3]

  var cx = ax*bw + aw*bx + ay*bz - az*by
  var cy = ay*bw + aw*by + az*bx - ax*bz
  var cz = az*bw + aw*bz + ax*by - ay*bx
  var cw = aw*bw - ax*bx - ay*by - az*bz
  
  //Apply roll
  if(dz) {
    bx = fx
    by = fy
    bz = fz
    var s = Math.sin(dz) / len3(bx, by, bz)
    bx *= s
    by *= s
    bz *= s
    bw = Math.cos(dx)
    cx = cx*bw + cw*bx + cy*bz - cz*by
    cy = cy*bw + cw*by + cz*bx - cx*bz
    cz = cz*bw + cw*bz + cx*by - cy*bx
    cw = cw*bw - cx*bx - cy*by - cz*bz
  }

  var cl = len4(cx, cy, cz, cw)
  if(cl > 1e-6) {
    cx /= cl
    cy /= cl
    cz /= cl
    cw /= cl
  } else {
    cx = cy = cz = 0.0
    cw = 1.0
  }

  this.rotation.set(t, cx, cy, cz, cw)
}

proto.lookAt = function(t, eye, center, up) {
  this.recalcMatrix(t)

  center = center || this.computedCenter
  eye    = eye    || this.computedEye
  up     = up     || this.computedUp

  var mat = this.computedMatrix
  lookAt(mat, eye, center, up)

  var rotation = this.computedRotation
  quatFromFrame(rotation,
    mat[0], mat[1], mat[2],
    mat[4], mat[5], mat[6],
    mat[8], mat[9], mat[10])
  normalize4(rotation, rotation)
  this.rotation.set(t, rotation[0], rotation[1], rotation[2], rotation[3])

  var fl = 0.0
  for(var i=0; i<3; ++i) {
    fl += Math.pow(center[i] - eye[i], 2)
  }
  this.radius.set(t, 0.5 * Math.log(Math.max(fl, 1e-6)))

  this.center.set(t, center[0], center[1], center[2])
}

proto.translate = function(t, dx, dy, dz) {
  this.center.move(t,
    dx||0.0,
    dy||0.0,
    dz||0.0)
}

proto.setMatrix = function(t, matrix) {

  var rotation = this.computedRotation
  quatFromFrame(rotation,
    matrix[0], matrix[1], matrix[2],
    matrix[4], matrix[5], matrix[6],
    matrix[8], matrix[9], matrix[10])
  normalize4(rotation, rotation)
  this.rotation.set(t, rotation[0], rotation[1], rotation[2], rotation[3])

  var mat = this.computedMatrix
  invert44(mat, matrix)
  var w = mat[15]
  if(Math.abs(w) > 1e-6) {
    var cx = mat[12]/w
    var cy = mat[13]/w
    var cz = mat[14]/w

    this.recalcMatrix(t)  
    var r = Math.exp(this.computedRadius[0])
    this.center.set(t, cx-mat[2]*r, cy-mat[6]*r, cz-mat[10]*r)
    this.radius.idle(t)
  } else {
    this.center.idle(t)
    this.radius.idle(t)
  }
}

proto.setDistance = function(t, d) {
  if(d > 0) {
    this.radius.set(t, Math.log(d))
  }
}

proto.setDistanceLimits = function(lo, hi) {
  if(lo > 0) {
    lo = Math.log(lo)
  } else {
    lo = -Infinity    
  }
  if(hi > 0) {
    hi = Math.log(hi)
  } else {
    hi = Infinity
  }
  hi = Math.max(hi, lo)
  this.radius.bounds[0][0] = lo
  this.radius.bounds[1][0] = hi
}

proto.getDistanceLimits = function(out) {
  var bounds = this.radius.bounds
  if(out) {
    out[0] = Math.exp(bounds[0][0])
    out[1] = Math.exp(bounds[1][0])
    return out
  }
  return [ Math.exp(bounds[0][0]), Math.exp(bounds[1][0]) ]
}

proto.toJSON = function() {
  this.recalcMatrix(this.lastT())
  return {
    center:   this.computedCenter.slice(),
    rotation: this.computedRotation.slice(),
    distance: Math.log(this.computedRadius[0]),
    zoomMin:  this.radius.bounds[0][0],
    zoomMax:  this.radius.bounds[1][0]
  }
}

proto.fromJSON = function(options) {
  var t = this.lastT()
  var c = options.center
  if(c) {
    this.center.set(t, c[0], c[1], c[2])
  }
  var r = options.rotation
  if(r) {
    this.rotation.set(t, r[0], r[1], r[2], r[3])
  }
  var d = options.distance
  if(d && d > 0) {
    this.radius.set(t, Math.log(d))
  }
  this.setDistanceLimits(options.zoomMin, options.zoomMax)
}

function createOrbitController(options) {
  options = options || {}
  var center   = options.center   || [0,0,0]
  var rotation = options.rotation || [0,0,0,1]
  var radius   = options.radius   || 1.0

  center = [].slice.call(center, 0, 3)
  rotation = [].slice.call(rotation, 0, 4)
  normalize4(rotation, rotation)

  var result = new OrbitCameraController(
    rotation,
    center,
    Math.log(radius))

  result.setDistanceLimits(options.zoomMin, options.zoomMax)

  if('eye' in options || 'up' in options) {
    result.lookAt(0, options.eye, options.center, options.up)
  }

  return result
}
},{"./lib/quatFromFrame":441,"filtered-vector":216,"gl-mat4/fromQuat":253,"gl-mat4/invert":256,"gl-mat4/lookAt":257}],443:[function(_dereq_,module,exports){
/*!
 * pad-left <https://github.com/jonschlinkert/pad-left>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT license.
 */

'use strict';

var repeat = _dereq_('repeat-string');

module.exports = function padLeft(str, num, ch) {
  ch = typeof ch !== 'undefined' ? (ch + '') : ' ';
  return repeat(ch, num) + str;
};
},{"repeat-string":481}],444:[function(_dereq_,module,exports){
'use strict'

/**
 * @module parenthesis
 */

function parse (str, opts) {
	// pretend non-string parsed per-se
	if (typeof str !== 'string') return [str]

	var res = [str]

	if (typeof opts === 'string' || Array.isArray(opts)) {
		opts = {brackets: opts}
	}
	else if (!opts) opts = {}

	var brackets = opts.brackets ? (Array.isArray(opts.brackets) ? opts.brackets : [opts.brackets]) : ['{}', '[]', '()']

	var escape = opts.escape || '___'

	var flat = !!opts.flat

	brackets.forEach(function (bracket) {
		// create parenthesis regex
		var pRE = new RegExp(['\\', bracket[0], '[^\\', bracket[0], '\\', bracket[1], ']*\\', bracket[1]].join(''))

		var ids = []

		function replaceToken(token, idx, str){
			// save token to res
			var refId = res.push(token.slice(bracket[0].length, -bracket[1].length)) - 1

			ids.push(refId)

			return escape + refId
		}

		res.forEach(function (str, i) {
			var prevStr

			// replace paren tokens till there’s none
			var a = 0
			while (str != prevStr) {
				prevStr = str
				str = str.replace(pRE, replaceToken)
				if (a++ > 10e3) throw Error('References have circular dependency. Please, check them.')
			}

			res[i] = str
		})

		// wrap found refs to brackets
		ids = ids.reverse()
		res = res.map(function (str) {
			ids.forEach(function (id) {
				str = str.replace(new RegExp('(\\' + escape + id + '(?![0-9]))', 'g'), bracket[0] + '$1' + bracket[1])
			})
			return str
		})
	})

	var re = new RegExp('\\' + escape + '([0-9]+)')

	// transform references to tree
	function nest (str, refs, escape) {
		var res = [], match

		var a = 0
		while (match = re.exec(str)) {
			if (a++ > 10e3) throw Error('Circular references in parenthesis')

			res.push(str.slice(0, match.index))

			res.push(nest(refs[match[1]], refs))

			str = str.slice(match.index + match[0].length)
		}

		res.push(str)

		return res
	}

	return flat ? res : nest(res[0], res)
}

function stringify (arg, opts) {
	if (opts && opts.flat) {
		var escape = opts && opts.escape || '___'

		var str = arg[0], prevStr

		// pretend bad string stringified with no parentheses
		if (!str) return ''


		var re = new RegExp('\\' + escape + '([0-9]+)')

		var a = 0
		while (str != prevStr) {
			if (a++ > 10e3) throw Error('Circular references in ' + arg)
			prevStr = str
			str = str.replace(re, replaceRef)
		}

		return str
	}

	return arg.reduce(function f (prev, curr) {
		if (Array.isArray(curr)) {
			curr = curr.reduce(f, '')
		}
		return prev + curr
	}, '')

	function replaceRef(match, idx){
		if (arg[idx] == null) throw Error('Reference ' + idx + 'is undefined')
		return arg[idx]
	}
}

function parenthesis (arg, opts) {
	if (Array.isArray(arg)) {
		return stringify(arg, opts)
	}
	else {
		return parse(arg, opts)
	}
}

parenthesis.parse = parse
parenthesis.stringify = stringify

module.exports = parenthesis

},{}],445:[function(_dereq_,module,exports){
'use strict'

var pick = _dereq_('pick-by-alias')

module.exports = parseRect

function parseRect (arg) {
  var rect

  // direct arguments sequence
  if (arguments.length > 1) {
    arg = arguments
  }

  // svg viewbox
  if (typeof arg === 'string') {
    arg = arg.split(/\s/).map(parseFloat)
  }
  else if (typeof arg === 'number') {
    arg = [arg]
  }

  // 0, 0, 100, 100 - array-like
  if (arg.length && typeof arg[0] === 'number') {
    // [w, w]
    if (arg.length === 1) {
      rect = {
        width: arg[0],
        height: arg[0],
        x: 0, y: 0
      }
    }
    // [w, h]
    else if (arg.length === 2) {
      rect = {
        width: arg[0],
        height: arg[1],
        x: 0, y: 0
      }
    }
    // [l, t, r, b]
    else {
      rect = {
        x: arg[0],
        y: arg[1],
        width: (arg[2] - arg[0]) || 0,
        height: (arg[3] - arg[1]) || 0
      }
    }
  }
  // {x, y, w, h} or {l, t, b, r}
  else if (arg) {
    arg = pick(arg, {
      left: 'x l left Left',
      top: 'y t top Top',
      width: 'w width W Width',
      height: 'h height W Width',
      bottom: 'b bottom Bottom',
      right: 'r right Right'
    })

    rect = {
      x: arg.left || 0,
      y: arg.top || 0
    }

    if (arg.width == null) {
      if (arg.right) rect.width = arg.right - rect.x
      else rect.width = 0
    }
    else {
      rect.width = arg.width
    }

    if (arg.height == null) {
      if (arg.bottom) rect.height = arg.bottom - rect.y
      else rect.height = 0
    }
    else {
      rect.height = arg.height
    }
  }

  return rect
}

},{"pick-by-alias":451}],446:[function(_dereq_,module,exports){

module.exports = parse

/**
 * expected argument lengths
 * @type {Object}
 */

var length = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0}

/**
 * segment pattern
 * @type {RegExp}
 */

var segment = /([astvzqmhlc])([^astvzqmhlc]*)/ig

/**
 * parse an svg path data string. Generates an Array
 * of commands where each command is an Array of the
 * form `[command, arg1, arg2, ...]`
 *
 * @param {String} path
 * @return {Array}
 */

function parse(path) {
	var data = []
	path.replace(segment, function(_, command, args){
		var type = command.toLowerCase()
		args = parseValues(args)

		// overloaded moveTo
		if (type == 'm' && args.length > 2) {
			data.push([command].concat(args.splice(0, 2)))
			type = 'l'
			command = command == 'm' ? 'l' : 'L'
		}

		while (true) {
			if (args.length == length[type]) {
				args.unshift(command)
				return data.push(args)
			}
			if (args.length < length[type]) throw new Error('malformed path data')
			data.push([command].concat(args.splice(0, length[type])))
		}
	})
	return data
}

var number = /-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig

function parseValues(args) {
	var numbers = args.match(number)
	return numbers ? numbers.map(Number) : []
}

},{}],447:[function(_dereq_,module,exports){
module.exports = function parseUnit(str, out) {
    if (!out)
        out = [ 0, '' ]

    str = String(str)
    var num = parseFloat(str, 10)
    out[0] = num
    out[1] = str.match(/[\d.\-\+]*\s*(.*)/)[1] || ''
    return out
}
},{}],448:[function(_dereq_,module,exports){
(function (process){
// Generated by CoffeeScript 1.12.2
(function() {
  var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime;

  if ((typeof performance !== "undefined" && performance !== null) && performance.now) {
    module.exports = function() {
      return performance.now();
    };
  } else if ((typeof process !== "undefined" && process !== null) && process.hrtime) {
    module.exports = function() {
      return (getNanoSeconds() - nodeLoadTime) / 1e6;
    };
    hrtime = process.hrtime;
    getNanoSeconds = function() {
      var hr;
      hr = hrtime();
      return hr[0] * 1e9 + hr[1];
    };
    moduleLoadTime = getNanoSeconds();
    upTime = process.uptime() * 1e9;
    nodeLoadTime = moduleLoadTime - upTime;
  } else if (Date.now) {
    module.exports = function() {
      return Date.now() - loadTime;
    };
    loadTime = Date.now();
  } else {
    module.exports = function() {
      return new Date().getTime() - loadTime;
    };
    loadTime = new Date().getTime();
  }

}).call(this);



}).call(this,_dereq_('_process'))
},{"_process":468}],449:[function(_dereq_,module,exports){
"use strict"

module.exports = permutationSign

var BRUTE_FORCE_CUTOFF = 32

var pool = _dereq_("typedarray-pool")

function permutationSign(p) {
  var n = p.length
  if(n < BRUTE_FORCE_CUTOFF) {
    //Use quadratic algorithm for small n
    var sgn = 1
    for(var i=0; i<n; ++i) {
      for(var j=0; j<i; ++j) {
        if(p[i] < p[j]) {
          sgn = -sgn
        } else if(p[i] === p[j]) {
          return 0
        }
      }
    }
    return sgn
  } else {
    //Otherwise use linear time algorithm
    var visited = pool.mallocUint8(n)
    for(var i=0; i<n; ++i) {
      visited[i] = 0
    }
    var sgn = 1
    for(var i=0; i<n; ++i) {
      if(!visited[i]) {
        var count = 1
        visited[i] = 1
        for(var j=p[i]; j!==i; j=p[j]) {
          if(visited[j]) {
            pool.freeUint8(visited)
            return 0
          }
          count += 1
          visited[j] = 1
        }
        if(!(count & 1)) {
          sgn = -sgn
        }
      }
    }
    pool.freeUint8(visited)
    return sgn
  }
}
},{"typedarray-pool":523}],450:[function(_dereq_,module,exports){
"use strict"

var pool = _dereq_("typedarray-pool")
var inverse = _dereq_("invert-permutation")

function rank(permutation) {
  var n = permutation.length
  switch(n) {
    case 0:
    case 1:
      return 0
    case 2:
      return permutation[1]
    default:
      break
  }
  var p = pool.mallocUint32(n)
  var pinv = pool.mallocUint32(n)
  var r = 0, s, t, i
  inverse(permutation, pinv)
  for(i=0; i<n; ++i) {
    p[i] = permutation[i]
  }
  for(i=n-1; i>0; --i) {
    t = pinv[i]
    s = p[i]
    p[i] = p[t]
    p[t] = s
    pinv[i] = pinv[s]
    pinv[s] = t
    r = (r + s) * i
  }
  pool.freeUint32(pinv)
  pool.freeUint32(p)
  return r
}

function unrank(n, r, p) {
  switch(n) {
    case 0:
      if(p) { return p }
      return []
    case 1:
      if(p) {
        p[0] = 0
        return p
      } else {
        return [0]
      }
    case 2:
      if(p) {
        if(r) {
          p[0] = 0
          p[1] = 1
        } else {
          p[0] = 1
          p[1] = 0
        }
        return p
      } else {
        return r ? [0,1] : [1,0]
      }
    default:
      break
  }
  p = p || new Array(n)
  var s, t, i, nf=1
  p[0] = 0
  for(i=1; i<n; ++i) {
    p[i] = i
    nf = (nf*i)|0
  }
  for(i=n-1; i>0; --i) {
    s = (r / nf)|0
    r = (r - s * nf)|0
    nf = (nf / i)|0
    t = p[i]|0
    p[i] = p[s]|0
    p[s] = t|0
  }
  return p
}

exports.rank = rank
exports.unrank = unrank

},{"invert-permutation":401,"typedarray-pool":523}],451:[function(_dereq_,module,exports){
'use strict'


module.exports = function pick (src, props, keepRest) {
	var result = {}, prop, i

	if (typeof props === 'string') props = toList(props)
	if (Array.isArray(props)) {
		var res = {}
		for (i = 0; i < props.length; i++) {
			res[props[i]] = true
		}
		props = res
	}

	// convert strings to lists
	for (prop in props) {
		props[prop] = toList(props[prop])
	}

	// keep-rest strategy requires unmatched props to be preserved
	var occupied = {}

	for (prop in props) {
		var aliases = props[prop]

		if (Array.isArray(aliases)) {
			for (i = 0; i < aliases.length; i++) {
				var alias = aliases[i]

				if (keepRest) {
					occupied[alias] = true
				}

				if (alias in src) {
					result[prop] = src[alias]

					if (keepRest) {
						for (var j = i; j < aliases.length; j++) {
							occupied[aliases[j]] = true
						}
					}

					break
				}
			}
		}
		else if (prop in src) {
			if (props[prop]) {
				result[prop] = src[prop]
			}

			if (keepRest) {
				occupied[prop] = true
			}
		}
	}

	if (keepRest) {
		for (prop in src) {
			if (occupied[prop]) continue
			result[prop] = src[prop]
		}
	}

	return result
}

var CACHE = {}

function toList(arg) {
	if (CACHE[arg]) return CACHE[arg]
	if (typeof arg === 'string') {
		arg = CACHE[arg] = arg.split(/\s*,\s*|\s+/)
	}
	return arg
}

},{}],452:[function(_dereq_,module,exports){
"use strict"

module.exports = planarDual

var compareAngle = _dereq_("compare-angle")

function planarDual(cells, positions) {

  var numVertices = positions.length|0
  var numEdges = cells.length
  var adj = [new Array(numVertices), new Array(numVertices)]
  for(var i=0; i<numVertices; ++i) {
    adj[0][i] = []
    adj[1][i] = []
  }
  for(var i=0; i<numEdges; ++i) {
    var c = cells[i]
    adj[0][c[0]].push(c)
    adj[1][c[1]].push(c)
  }

  var cycles = []

  //Add isolated vertices as trivial case
  for(var i=0; i<numVertices; ++i) {
    if(adj[0][i].length + adj[1][i].length === 0) {
      cycles.push( [i] )
    }
  }

  //Remove a half edge
  function cut(c, i) {
    var a = adj[i][c[i]]
    a.splice(a.indexOf(c), 1)
  }

  //Find next vertex and cut edge
  function next(a, b, noCut) {
    var nextCell, nextVertex, nextDir
    for(var i=0; i<2; ++i) {
      if(adj[i][b].length > 0) {
        nextCell = adj[i][b][0]
        nextDir = i
        break
      }
    }
    nextVertex = nextCell[nextDir^1]

    for(var dir=0; dir<2; ++dir) {
      var nbhd = adj[dir][b]
      for(var k=0; k<nbhd.length; ++k) {
        var e = nbhd[k]
        var p = e[dir^1]
        var cmp = compareAngle(
            positions[a], 
            positions[b], 
            positions[nextVertex],
            positions[p])
        if(cmp > 0) {
          nextCell = e
          nextVertex = p
          nextDir = dir
        }
      }
    }
    if(noCut) {
      return nextVertex
    }
    if(nextCell) {
      cut(nextCell, nextDir)
    }
    return nextVertex
  }

  function extractCycle(v, dir) {
    var e0 = adj[dir][v][0]
    var cycle = [v]
    cut(e0, dir)
    var u = e0[dir^1]
    var d0 = dir
    while(true) {
      while(u !== v) {
        cycle.push(u)
        u = next(cycle[cycle.length-2], u, false)
      }
      if(adj[0][v].length + adj[1][v].length === 0) {
        break
      }
      var a = cycle[cycle.length-1]
      var b = v
      var c = cycle[1]
      var d = next(a, b, true)
      if(compareAngle(positions[a], positions[b], positions[c], positions[d]) < 0) {
        break
      }
      cycle.push(v)
      u = next(a, b)
    }
    return cycle
  }

  function shouldGlue(pcycle, ncycle) {
    return (ncycle[1] === ncycle[ncycle.length-1])
  }

  for(var i=0; i<numVertices; ++i) {
    for(var j=0; j<2; ++j) {
      var pcycle = []
      while(adj[j][i].length > 0) {
        var ni = adj[0][i].length
        var ncycle = extractCycle(i,j)
        if(shouldGlue(pcycle, ncycle)) {
          //Glue together trivial cycles
          pcycle.push.apply(pcycle, ncycle)
        } else {
          if(pcycle.length > 0) {
            cycles.push(pcycle)
          }
          pcycle = ncycle
        }
      }
      if(pcycle.length > 0) {
        cycles.push(pcycle)
      }
    }
  }

  //Combine paths and loops together
  return cycles
}
},{"compare-angle":116}],453:[function(_dereq_,module,exports){
'use strict'

module.exports = trimLeaves

var e2a = _dereq_('edges-to-adjacency-list')

function trimLeaves(edges, positions) {
  var adj = e2a(edges, positions.length)
  var live = new Array(positions.length)
  var nbhd = new Array(positions.length)

  var dead = []
  for(var i=0; i<positions.length; ++i) {
    var count = adj[i].length
    nbhd[i] = count
    live[i] = true
    if(count <= 1) {
      dead.push(i)
    }
  }

  while(dead.length > 0) {
    var v = dead.pop()
    live[v] = false
    var n = adj[v]
    for(var i=0; i<n.length; ++i) {
      var u = n[i]
      if(--nbhd[u] === 0) {
        dead.push(u)
      }
    }
  }

  var newIndex = new Array(positions.length)
  var npositions = []
  for(var i=0; i<positions.length; ++i) {
    if(live[i]) {
      var v = npositions.length
      newIndex[i] = v
      npositions.push(positions[i])
    } else {
      newIndex[i] = -1
    }
  }

  var nedges = []
  for(var i=0; i<edges.length; ++i) {
    var e = edges[i]
    if(live[e[0]] && live[e[1]]) {
      nedges.push([ newIndex[e[0]], newIndex[e[1]] ])
    }
  }
  
  return [ nedges, npositions ]
}
},{"edges-to-adjacency-list":158}],454:[function(_dereq_,module,exports){
'use strict'

module.exports = planarGraphToPolyline

var e2a = _dereq_('edges-to-adjacency-list')
var planarDual = _dereq_('planar-dual')
var preprocessPolygon = _dereq_('point-in-big-polygon')
var twoProduct = _dereq_('two-product')
var robustSum = _dereq_('robust-sum')
var uniq = _dereq_('uniq')
var trimLeaves = _dereq_('./lib/trim-leaves')

function makeArray(length, fill) {
  var result = new Array(length)
  for(var i=0; i<length; ++i) {
    result[i] = fill
  }
  return result
}

function makeArrayOfArrays(length) {
  var result = new Array(length)
  for(var i=0; i<length; ++i) {
    result[i] = []
  }
  return result
}


function planarGraphToPolyline(edges, positions) {

  //Trim leaves
  var result = trimLeaves(edges, positions)
  edges = result[0]
  positions = result[1]

  var numVertices = positions.length
  var numEdges = edges.length

  //Calculate adjacency list, check manifold
  var adj = e2a(edges, positions.length)
  for(var i=0; i<numVertices; ++i) {
    if(adj[i].length % 2 === 1) {
      throw new Error('planar-graph-to-polyline: graph must be manifold')
    }
  }

  //Get faces
  var faces = planarDual(edges, positions)

  //Check orientation of a polygon using exact arithmetic
  function ccw(c) {
    var n = c.length
    var area = [0]
    for(var j=0; j<n; ++j) {
      var a = positions[c[j]]
      var b = positions[c[(j+1)%n]]
      var t00 = twoProduct(-a[0], a[1])
      var t01 = twoProduct(-a[0], b[1])
      var t10 = twoProduct( b[0], a[1])
      var t11 = twoProduct( b[0], b[1])
      area = robustSum(area, robustSum(robustSum(t00, t01), robustSum(t10, t11)))
    }
    return area[area.length-1] > 0
  }

  //Extract all clockwise faces
  faces = faces.filter(ccw)

  //Detect which loops are contained in one another to handle parent-of relation
  var numFaces = faces.length
  var parent = new Array(numFaces)
  var containment = new Array(numFaces)
  for(var i=0; i<numFaces; ++i) {
    parent[i] = i
    var row = new Array(numFaces)
    var loopVertices = faces[i].map(function(v) {
      return positions[v]
    })
    var pmc = preprocessPolygon([loopVertices])
    var count = 0
    outer:
    for(var j=0; j<numFaces; ++j) {
      row[j] = 0
      if(i === j) {
        continue
      }
      var c = faces[j]
      var n = c.length
      for(var k=0; k<n; ++k) {
        var d = pmc(positions[c[k]])
        if(d !== 0) {
          if(d < 0) {
            row[j] = 1
            count += 1
          }
          continue outer
        }
      }
      row[j] = 1
      count += 1
    }
    containment[i] = [count, i, row]
  }
  containment.sort(function(a,b) {
    return b[0] - a[0]
  })
  for(var i=0; i<numFaces; ++i) {
    var row = containment[i]
    var idx = row[1]
    var children = row[2]
    for(var j=0; j<numFaces; ++j) {
      if(children[j]) {
        parent[j] = idx
      }
    }
  }

  //Initialize face adjacency list
  var fadj = makeArrayOfArrays(numFaces)
  for(var i=0; i<numFaces; ++i) {
    fadj[i].push(parent[i])
    fadj[parent[i]].push(i)
  }

  //Build adjacency matrix for edges
  var edgeAdjacency = {}
  var internalVertices = makeArray(numVertices, false)
  for(var i=0; i<numFaces; ++i) {
    var c = faces[i]
    var n = c.length
    for(var j=0; j<n; ++j) {
      var a = c[j]
      var b = c[(j+1)%n]
      var key = Math.min(a,b) + ":" + Math.max(a,b)
      if(key in edgeAdjacency) {
        var neighbor = edgeAdjacency[key]
        fadj[neighbor].push(i)
        fadj[i].push(neighbor)
        internalVertices[a] = internalVertices[b] = true
      } else {
        edgeAdjacency[key] = i
      }
    }
  }

  function sharedBoundary(c) {
    var n = c.length
    for(var i=0; i<n; ++i) {
      if(!internalVertices[c[i]]) {
        return false
      }
    }
    return true
  }

  var toVisit = []
  var parity = makeArray(numFaces, -1)
  for(var i=0; i<numFaces; ++i) {
    if(parent[i] === i && !sharedBoundary(faces[i])) {
      toVisit.push(i)
      parity[i] = 0
    } else {
      parity[i] = -1
    }
  }

  //Using face adjacency, classify faces as in/out
  var result = []
  while(toVisit.length > 0) {
    var top = toVisit.pop()
    var nbhd = fadj[top]
    uniq(nbhd, function(a,b) {
      return a-b
    })
    var nnbhr = nbhd.length
    var p = parity[top]
    var polyline
    if(p === 0) {
      var c = faces[top]
      polyline = [c]
    }
    for(var i=0; i<nnbhr; ++i) {
      var f = nbhd[i]
      if(parity[f] >= 0) {
        continue
      }
      parity[f] = p^1
      toVisit.push(f)
      if(p === 0) {
        var c = faces[f]
        if(!sharedBoundary(c)) {
          c.reverse()
          polyline.push(c)
        }
      }
    }
    if(p === 0) {
      result.push(polyline)
    }
  }

  return result
}
},{"./lib/trim-leaves":453,"edges-to-adjacency-list":158,"planar-dual":452,"point-in-big-polygon":458,"robust-sum":493,"two-product":521,"uniq":525}],455:[function(_dereq_,module,exports){
'use strict'

module.exports = _dereq_('./quad')
},{"./quad":457}],456:[function(_dereq_,module,exports){
arguments[4][100][0].apply(exports,arguments)
},{"dup":100}],457:[function(_dereq_,module,exports){
/**
 * @module  point-cluster/quad
 *
 * Bucket based quad tree clustering
 */

'use strict'

var search = _dereq_('binary-search-bounds')
var clamp = _dereq_('clamp')
var rect = _dereq_('parse-rect')
var getBounds = _dereq_('array-bounds')
var pick = _dereq_('pick-by-alias')
var defined = _dereq_('defined')
var flatten = _dereq_('flatten-vertex-data')
var isObj = _dereq_('is-obj')
var dtype = _dereq_('dtype')
var log2 = _dereq_('math-log2')


module.exports = function cluster (srcPoints, options) {
	if (!options) { options = {} }

	srcPoints = flatten(srcPoints, 'float64')

	options = pick(options, {
		bounds: 'range bounds dataBox databox',
		maxDepth: 'depth maxDepth maxdepth level maxLevel maxlevel levels',
		dtype: 'type dtype format out dst output destination'
		// sort: 'sortBy sortby sort',
		// pick: 'pick levelPoint',
		// nodeSize: 'node nodeSize minNodeSize minSize size'
	})

	// let nodeSize = defined(options.nodeSize, 1)
	var maxDepth = defined(options.maxDepth, 255)
	var bounds = defined(options.bounds, getBounds(srcPoints, 2))
	if (bounds[0] === bounds[2]) { bounds[2]++ }
	if (bounds[1] === bounds[3]) { bounds[3]++ }

	var points = normalize(srcPoints, bounds)

	// init variables
	var n = srcPoints.length >>> 1
	var ids
	if (!options.dtype) { options.dtype = 'array' }

	if (typeof options.dtype === 'string') {
		ids = new (dtype(options.dtype))(n)
	}
	else if (options.dtype) {
		ids = options.dtype
		if (Array.isArray(ids)) { ids.length = n }
	}
	for (var i = 0; i < n; ++i) {
		ids[i] = i
	}

	// point indexes for levels [0: [a,b,c,d], 1: [a,b,c,d,e,f,...], ...]
	var levels = []

	// starting indexes of subranges in sub levels, levels.length * 4
	var sublevels = []

	// unique group ids, sorted in z-curve fashion within levels
	var groups = []

	// level offsets in `ids`
	var offsets = []


	// sort points
	sort(0, 0, 1, ids, 0, 1)


	// return reordered ids with provided methods
	// save level offsets in output buffer
	var offset = 0
	for (var level = 0; level < levels.length; level++) {
		var levelItems = levels[level]
		if (ids.set) { ids.set(levelItems, offset) }
		else {
			for (var i$1 = 0, l = levelItems.length; i$1 < l; i$1++) {
				ids[i$1 + offset] = levelItems[i$1]
			}
		}
		var nextOffset = offset + levels[level].length
		offsets[level] = [offset, nextOffset]
		offset = nextOffset
	}

	ids.range = range

	return ids



	// FIXME: it is possible to create one typed array heap and reuse that to avoid memory blow
	function sort (x, y, diam, ids, level, group) {
		if (!ids.length) { return null }

		// save first point as level representative
		var levelItems = levels[level] || (levels[level] = [])
		var levelGroups = groups[level] || (groups[level] = [])
		var sublevel = sublevels[level] || (sublevels[level] = [])
		var offset = levelItems.length

		level++

		// max depth reached - put all items into a first group
		if (level > maxDepth) {
			for (var i = 0; i < ids.length; i++) {
				levelItems.push(ids[i])
				levelGroups.push(group)
				sublevel.push(null, null, null, null)
			}

			return offset
		}

		levelItems.push(ids[0])
		levelGroups.push(group)

		if (ids.length <= 1) {
			sublevel.push(null, null, null, null)
			return offset
		}


		var d2 = diam * .5
		var cx = x + d2, cy = y + d2

		// distribute points by 4 buckets
		var lolo = [], lohi = [], hilo = [], hihi = []

		for (var i$1 = 1, l = ids.length; i$1 < l; i$1++) {
			var idx = ids[i$1],
				x$1 = points[idx * 2],
				y$1 = points[idx * 2 + 1]
			x$1 < cx ? (y$1 < cy ? lolo.push(idx) : lohi.push(idx)) : (y$1 < cy ? hilo.push(idx) : hihi.push(idx))
		}

		group <<= 2
		sublevel.push(
			sort(x, y, d2, lolo, level, group),
			sort(x, cy, d2, lohi, level, group + 1),
			sort(cx, y, d2, hilo, level, group + 2),
			sort(cx, cy, d2, hihi, level, group + 3)
		)

		return offset
	}

	// get all points within the passed range
	function range () {
		var args = [], len = arguments.length;
		while ( len-- ) args[ len ] = arguments[ len ];

		var options

		if (isObj(args[args.length - 1])) {
			var arg = args.pop()

			// detect if that was a rect object
			if (!args.length && (arg.x != null || arg.l != null || arg.left != null)) {
				args = [arg]
				options = {}
			}

			options = pick(arg, {
				level: 'level maxLevel',
				d: 'd diam diameter r radius px pxSize pixel pixelSize maxD size minSize',
				lod: 'lod details ranges offsets'
			})
		}
		else {
			options = {}
		}

		if (!args.length) { args = bounds }

		var box = rect.apply( void 0, args )

		var ref = [
			Math.min(box.x, box.x + box.width),
			Math.min(box.y, box.y + box.height),
			Math.max(box.x, box.x + box.width),
			Math.max(box.y, box.y + box.height)
		];
		var minX = ref[0];
		var minY = ref[1];
		var maxX = ref[2];
		var maxY = ref[3];

		var ref$1 = normalize([minX, minY, maxX, maxY], bounds );
		var nminX = ref$1[0];
		var nminY = ref$1[1];
		var nmaxX = ref$1[2];
		var nmaxY = ref$1[3];

		var maxLevel = defined(options.level, levels.length)

		// limit maxLevel by px size
		if (options.d != null) {
			var d
			if (typeof options.d === 'number') { d = [options.d, options.d] }
			else if (options.d.length) { d = options.d }

			maxLevel = Math.min(
				Math.max(
					Math.ceil(-log2(Math.abs(d[0]) / (bounds[2] - bounds[0]))),
					Math.ceil(-log2(Math.abs(d[1]) / (bounds[3] - bounds[1])))
				),
				maxLevel
			)
		}
		maxLevel = Math.min(maxLevel, levels.length)

		// return levels of details
		if (options.lod) {
			return lod(nminX, nminY, nmaxX, nmaxY, maxLevel)
		}



		// do selection ids
		var selection = []

		// FIXME: probably we can do LOD here beforehead
		select( 0, 0, 1, 0, 0, 1)

		function select ( lox, loy, d, level, from, to ) {
			if (from === null || to === null) { return }

			var hix = lox + d
			var hiy = loy + d

			// if box does not intersect level - ignore
			if ( nminX > hix || nminY > hiy || nmaxX < lox || nmaxY < loy ) { return }
			if ( level >= maxLevel ) { return }
			if ( from === to ) { return }

			// if points fall into box range - take it
			var levelItems = levels[level]

			if (to === undefined) { to = levelItems.length }

			for (var i = from; i < to; i++) {
				var id = levelItems[i]

				var px = srcPoints[ id * 2 ]
				var py = srcPoints[ id * 2 + 1 ]

				if ( px >= minX && px <= maxX && py >= minY && py <= maxY ) {selection.push(id)
				}
			}

			// for every subsection do select
			var offsets = sublevels[ level ]
			var off0 = offsets[ from * 4 + 0 ]
			var off1 = offsets[ from * 4 + 1 ]
			var off2 = offsets[ from * 4 + 2 ]
			var off3 = offsets[ from * 4 + 3 ]
			var end = nextOffset(offsets, from + 1)

			var d2 = d * .5
			var nextLevel = level + 1
			select( lox, loy, d2, nextLevel, off0, off1 || off2 || off3 || end)
			select( lox, loy + d2, d2, nextLevel, off1, off2 || off3 || end)
			select( lox + d2, loy, d2, nextLevel, off2, off3 || end)
			select( lox + d2, loy + d2, d2, nextLevel, off3, end)
		}

		function nextOffset(offsets, from) {
			var offset = null, i = 0
			while(offset === null) {
				offset = offsets[ from * 4 + i ]
				i++
				if (i > offsets.length) { return null }
			}
			return offset
		}

		return selection
	}

	// get range offsets within levels to render lods appropriate for zoom level
	// TODO: it is possible to store minSize of a point to optimize neede level calc
	function lod (lox, loy, hix, hiy, maxLevel) {
		var ranges = []

		for (var level = 0; level < maxLevel; level++) {
			var levelGroups = groups[level]
			var from = offsets[level][0]

			var levelGroupStart = group(lox, loy, level)
			var levelGroupEnd = group(hix, hiy, level)

			// FIXME: utilize sublevels to speed up search range here
			var startOffset = search.ge(levelGroups, levelGroupStart)
			var endOffset = search.gt(levelGroups, levelGroupEnd, startOffset, levelGroups.length - 1)

			ranges[level] = [startOffset + from, endOffset + from]
		}

		return ranges
	}

	// get group id closest to the x,y coordinate, corresponding to a level
	function group (x, y, level) {
		var group = 1

		var cx = .5, cy = .5
		var diam = .5

		for (var i = 0; i < level; i++) {
			group <<= 2

			group += x < cx ? (y < cy ? 0 : 1) : (y < cy ? 2 : 3)

			diam *= .5

			cx += x < cx ? -diam : diam
			cy += y < cy ? -diam : diam
		}

		return group
	}
}


// normalize points by bounds
function normalize (pts, bounds) {
	var lox = bounds[0];
	var loy = bounds[1];
	var hix = bounds[2];
	var hiy = bounds[3];
	var scaleX = 1.0 / (hix - lox)
	var scaleY = 1.0 / (hiy - loy)
	var result = new Array(pts.length)

	for (var i = 0, n = pts.length / 2; i < n; i++) {
		result[2*i] = clamp((pts[2*i] - lox) * scaleX, 0, 1)
		result[2*i+1] = clamp((pts[2*i+1] - loy) * scaleY, 0, 1)
	}

	return result
}
},{"array-bounds":54,"binary-search-bounds":456,"clamp":104,"defined":150,"dtype":155,"flatten-vertex-data":217,"is-obj":407,"math-log2":418,"parse-rect":445,"pick-by-alias":451}],458:[function(_dereq_,module,exports){
module.exports = preprocessPolygon

var orient = _dereq_('robust-orientation')[3]
var makeSlabs = _dereq_('slab-decomposition')
var makeIntervalTree = _dereq_('interval-tree-1d')
var bsearch = _dereq_('binary-search-bounds')

function visitInterval() {
  return true
}

function intervalSearch(table) {
  return function(x, y) {
    var tree = table[x]
    if(tree) {
      return !!tree.queryPoint(y, visitInterval)
    }
    return false
  }
}

function buildVerticalIndex(segments) {
  var table = {}
  for(var i=0; i<segments.length; ++i) {
    var s = segments[i]
    var x = s[0][0]
    var y0 = s[0][1]
    var y1 = s[1][1]
    var p = [ Math.min(y0, y1), Math.max(y0, y1) ]
    if(x in table) {
      table[x].push(p)
    } else {
      table[x] = [ p ]
    }
  }
  var intervalTable = {}
  var keys = Object.keys(table)
  for(var i=0; i<keys.length; ++i) {
    var segs = table[keys[i]]
    intervalTable[keys[i]] = makeIntervalTree(segs)
  }
  return intervalSearch(intervalTable)
}

function buildSlabSearch(slabs, coordinates) {
  return function(p) {
    var bucket = bsearch.le(coordinates, p[0])
    if(bucket < 0) {
      return 1
    }
    var root = slabs[bucket]
    if(!root) {
      if(bucket > 0 && coordinates[bucket] === p[0]) {
        root = slabs[bucket-1]
      } else {
        return 1
      }
    }
    var lastOrientation = 1
    while(root) {
      var s = root.key
      var o = orient(p, s[0], s[1])
      if(s[0][0] < s[1][0]) {
        if(o < 0) {
          root = root.left
        } else if(o > 0) {
          lastOrientation = -1
          root = root.right
        } else {
          return 0
        }
      } else {
        if(o > 0) {
          root = root.left
        } else if(o < 0) {
          lastOrientation = 1
          root = root.right
        } else {
          return 0
        }
      }
    }
    return lastOrientation
  }
}

function classifyEmpty(p) {
  return 1
}

function createClassifyVertical(testVertical) {
  return function classify(p) {
    if(testVertical(p[0], p[1])) {
      return 0
    }
    return 1
  }
}

function createClassifyPointDegen(testVertical, testNormal) {
  return function classify(p) {
    if(testVertical(p[0], p[1])) {
      return 0
    }
    return testNormal(p)
  }
}

function preprocessPolygon(loops) {
  //Compute number of loops
  var numLoops = loops.length

  //Unpack segments
  var segments = []
  var vsegments = []
  var ptr = 0
  for(var i=0; i<numLoops; ++i) {
    var loop = loops[i]
    var numVertices = loop.length
    for(var s=numVertices-1,t=0; t<numVertices; s=(t++)) {
      var a = loop[s]
      var b = loop[t]
      if(a[0] === b[0]) {
        vsegments.push([a,b])
      } else {
        segments.push([a,b])
      }
    }
  }

  //Degenerate case: All loops are empty
  if(segments.length === 0) {
    if(vsegments.length === 0) {
      return classifyEmpty
    } else {
      return createClassifyVertical(buildVerticalIndex(vsegments))
    }
  }

  //Build slab decomposition
  var slabs = makeSlabs(segments)
  var testSlab = buildSlabSearch(slabs.slabs, slabs.coordinates)

  if(vsegments.length === 0) {
    return testSlab
  } else {
    return createClassifyPointDegen(
      buildVerticalIndex(vsegments),
      testSlab)
  }
}
},{"binary-search-bounds":80,"interval-tree-1d":400,"robust-orientation":488,"slab-decomposition":504}],459:[function(_dereq_,module,exports){
/*
 * @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc
 * @license MIT
 * @preserve Project Home: https://github.com/voidqk/polybooljs
 */

var BuildLog = _dereq_('./lib/build-log');
var Epsilon = _dereq_('./lib/epsilon');
var Intersecter = _dereq_('./lib/intersecter');
var SegmentChainer = _dereq_('./lib/segment-chainer');
var SegmentSelector = _dereq_('./lib/segment-selector');
var GeoJSON = _dereq_('./lib/geojson');

var buildLog = false;
var epsilon = Epsilon();

var PolyBool;
PolyBool = {
	// getter/setter for buildLog
	buildLog: function(bl){
		if (bl === true)
			buildLog = BuildLog();
		else if (bl === false)
			buildLog = false;
		return buildLog === false ? false : buildLog.list;
	},
	// getter/setter for epsilon
	epsilon: function(v){
		return epsilon.epsilon(v);
	},

	// core API
	segments: function(poly){
		var i = Intersecter(true, epsilon, buildLog);
		poly.regions.forEach(i.addRegion);
		return {
			segments: i.calculate(poly.inverted),
			inverted: poly.inverted
		};
	},
	combine: function(segments1, segments2){
		var i3 = Intersecter(false, epsilon, buildLog);
		return {
			combined: i3.calculate(
				segments1.segments, segments1.inverted,
				segments2.segments, segments2.inverted
			),
			inverted1: segments1.inverted,
			inverted2: segments2.inverted
		};
	},
	selectUnion: function(combined){
		return {
			segments: SegmentSelector.union(combined.combined, buildLog),
			inverted: combined.inverted1 || combined.inverted2
		}
	},
	selectIntersect: function(combined){
		return {
			segments: SegmentSelector.intersect(combined.combined, buildLog),
			inverted: combined.inverted1 && combined.inverted2
		}
	},
	selectDifference: function(combined){
		return {
			segments: SegmentSelector.difference(combined.combined, buildLog),
			inverted: combined.inverted1 && !combined.inverted2
		}
	},
	selectDifferenceRev: function(combined){
		return {
			segments: SegmentSelector.differenceRev(combined.combined, buildLog),
			inverted: !combined.inverted1 && combined.inverted2
		}
	},
	selectXor: function(combined){
		return {
			segments: SegmentSelector.xor(combined.combined, buildLog),
			inverted: combined.inverted1 !== combined.inverted2
		}
	},
	polygon: function(segments){
		return {
			regions: SegmentChainer(segments.segments, epsilon, buildLog),
			inverted: segments.inverted
		};
	},

	// GeoJSON converters
	polygonFromGeoJSON: function(geojson){
		return GeoJSON.toPolygon(PolyBool, geojson);
	},
	polygonToGeoJSON: function(poly){
		return GeoJSON.fromPolygon(PolyBool, epsilon, poly);
	},

	// helper functions for common operations
	union: function(poly1, poly2){
		return operate(poly1, poly2, PolyBool.selectUnion);
	},
	intersect: function(poly1, poly2){
		return operate(poly1, poly2, PolyBool.selectIntersect);
	},
	difference: function(poly1, poly2){
		return operate(poly1, poly2, PolyBool.selectDifference);
	},
	differenceRev: function(poly1, poly2){
		return operate(poly1, poly2, PolyBool.selectDifferenceRev);
	},
	xor: function(poly1, poly2){
		return operate(poly1, poly2, PolyBool.selectXor);
	}
};

function operate(poly1, poly2, selector){
	var seg1 = PolyBool.segments(poly1);
	var seg2 = PolyBool.segments(poly2);
	var comb = PolyBool.combine(seg1, seg2);
	var seg3 = selector(comb);
	return PolyBool.polygon(seg3);
}

if (typeof window === 'object')
	window.PolyBool = PolyBool;

module.exports = PolyBool;

},{"./lib/build-log":460,"./lib/epsilon":461,"./lib/geojson":462,"./lib/intersecter":463,"./lib/segment-chainer":465,"./lib/segment-selector":466}],460:[function(_dereq_,module,exports){
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs

//
// used strictly for logging the processing of the algorithm... only useful if you intend on
// looking under the covers (for pretty UI's or debugging)
//

function BuildLog(){
	var my;
	var nextSegmentId = 0;
	var curVert = false;

	function push(type, data){
		my.list.push({
			type: type,
			data: data ? JSON.parse(JSON.stringify(data)) : void 0
		});
		return my;
	}

	my = {
		list: [],
		segmentId: function(){
			return nextSegmentId++;
		},
		checkIntersection: function(seg1, seg2){
			return push('check', { seg1: seg1, seg2: seg2 });
		},
		segmentChop: function(seg, end){
			push('div_seg', { seg: seg, pt: end });
			return push('chop', { seg: seg, pt: end });
		},
		statusRemove: function(seg){
			return push('pop_seg', { seg: seg });
		},
		segmentUpdate: function(seg){
			return push('seg_update', { seg: seg });
		},
		segmentNew: function(seg, primary){
			return push('new_seg', { seg: seg, primary: primary });
		},
		segmentRemove: function(seg){
			return push('rem_seg', { seg: seg });
		},
		tempStatus: function(seg, above, below){
			return push('temp_status', { seg: seg, above: above, below: below });
		},
		rewind: function(seg){
			return push('rewind', { seg: seg });
		},
		status: function(seg, above, below){
			return push('status', { seg: seg, above: above, below: below });
		},
		vert: function(x){
			if (x === curVert)
				return my;
			curVert = x;
			return push('vert', { x: x });
		},
		log: function(data){
			if (typeof data !== 'string')
				data = JSON.stringify(data, false, '  ');
			return push('log', { txt: data });
		},
		reset: function(){
			return push('reset');
		},
		selected: function(segs){
			return push('selected', { segs: segs });
		},
		chainStart: function(seg){
			return push('chain_start', { seg: seg });
		},
		chainRemoveHead: function(index, pt){
			return push('chain_rem_head', { index: index, pt: pt });
		},
		chainRemoveTail: function(index, pt){
			return push('chain_rem_tail', { index: index, pt: pt });
		},
		chainNew: function(pt1, pt2){
			return push('chain_new', { pt1: pt1, pt2: pt2 });
		},
		chainMatch: function(index){
			return push('chain_match', { index: index });
		},
		chainClose: function(index){
			return push('chain_close', { index: index });
		},
		chainAddHead: function(index, pt){
			return push('chain_add_head', { index: index, pt: pt });
		},
		chainAddTail: function(index, pt){
			return push('chain_add_tail', { index: index, pt: pt, });
		},
		chainConnect: function(index1, index2){
			return push('chain_con', { index1: index1, index2: index2 });
		},
		chainReverse: function(index){
			return push('chain_rev', { index: index });
		},
		chainJoin: function(index1, index2){
			return push('chain_join', { index1: index1, index2: index2 });
		},
		done: function(){
			return push('done');
		}
	};
	return my;
}

module.exports = BuildLog;

},{}],461:[function(_dereq_,module,exports){
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs

//
// provides the raw computation functions that takes epsilon into account
//
// zero is defined to be between (-epsilon, epsilon) exclusive
//

function Epsilon(eps){
	if (typeof eps !== 'number')
		eps = 0.0000000001; // sane default? sure why not
	var my = {
		epsilon: function(v){
			if (typeof v === 'number')
				eps = v;
			return eps;
		},
		pointAboveOrOnLine: function(pt, left, right){
			var Ax = left[0];
			var Ay = left[1];
			var Bx = right[0];
			var By = right[1];
			var Cx = pt[0];
			var Cy = pt[1];
			return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps;
		},
		pointBetween: function(p, left, right){
			// p must be collinear with left->right
			// returns false if p == left, p == right, or left == right
			var d_py_ly = p[1] - left[1];
			var d_rx_lx = right[0] - left[0];
			var d_px_lx = p[0] - left[0];
			var d_ry_ly = right[1] - left[1];

			var dot = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly;
			// if `dot` is 0, then `p` == `left` or `left` == `right` (reject)
			// if `dot` is less than 0, then `p` is to the left of `left` (reject)
			if (dot < eps)
				return false;

			var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly;
			// if `dot` > `sqlen`, then `p` is to the right of `right` (reject)
			// therefore, if `dot - sqlen` is greater than 0, then `p` is to the right of `right` (reject)
			if (dot - sqlen > -eps)
				return false;

			return true;
		},
		pointsSameX: function(p1, p2){
			return Math.abs(p1[0] - p2[0]) < eps;
		},
		pointsSameY: function(p1, p2){
			return Math.abs(p1[1] - p2[1]) < eps;
		},
		pointsSame: function(p1, p2){
			return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2);
		},
		pointsCompare: function(p1, p2){
			// returns -1 if p1 is smaller, 1 if p2 is smaller, 0 if equal
			if (my.pointsSameX(p1, p2))
				return my.pointsSameY(p1, p2) ? 0 : (p1[1] < p2[1] ? -1 : 1);
			return p1[0] < p2[0] ? -1 : 1;
		},
		pointsCollinear: function(pt1, pt2, pt3){
			// does pt1->pt2->pt3 make a straight line?
			// essentially this is just checking to see if the slope(pt1->pt2) === slope(pt2->pt3)
			// if slopes are equal, then they must be collinear, because they share pt2
			var dx1 = pt1[0] - pt2[0];
			var dy1 = pt1[1] - pt2[1];
			var dx2 = pt2[0] - pt3[0];
			var dy2 = pt2[1] - pt3[1];
			return Math.abs(dx1 * dy2 - dx2 * dy1) < eps;
		},
		linesIntersect: function(a0, a1, b0, b1){
			// returns false if the lines are coincident (e.g., parallel or on top of each other)
			//
			// returns an object if the lines intersect:
			//   {
			//     pt: [x, y],    where the intersection point is at
			//     alongA: where intersection point is along A,
			//     alongB: where intersection point is along B
			//   }
			//
			//  alongA and alongB will each be one of: -2, -1, 0, 1, 2
			//
			//  with the following meaning:
			//
			//    -2   intersection point is before segment's first point
			//    -1   intersection point is directly on segment's first point
			//     0   intersection point is between segment's first and second points (exclusive)
			//     1   intersection point is directly on segment's second point
			//     2   intersection point is after segment's second point
			var adx = a1[0] - a0[0];
			var ady = a1[1] - a0[1];
			var bdx = b1[0] - b0[0];
			var bdy = b1[1] - b0[1];

			var axb = adx * bdy - ady * bdx;
			if (Math.abs(axb) < eps)
				return false; // lines are coincident

			var dx = a0[0] - b0[0];
			var dy = a0[1] - b0[1];

			var A = (bdx * dy - bdy * dx) / axb;
			var B = (adx * dy - ady * dx) / axb;

			var ret = {
				alongA: 0,
				alongB: 0,
				pt: [
					a0[0] + A * adx,
					a0[1] + A * ady
				]
			};

			// categorize where intersection point is along A and B

			if (A <= -eps)
				ret.alongA = -2;
			else if (A < eps)
				ret.alongA = -1;
			else if (A - 1 <= -eps)
				ret.alongA = 0;
			else if (A - 1 < eps)
				ret.alongA = 1;
			else
				ret.alongA = 2;

			if (B <= -eps)
				ret.alongB = -2;
			else if (B < eps)
				ret.alongB = -1;
			else if (B - 1 <= -eps)
				ret.alongB = 0;
			else if (B - 1 < eps)
				ret.alongB = 1;
			else
				ret.alongB = 2;

			return ret;
		},
		pointInsideRegion: function(pt, region){
			var x = pt[0];
			var y = pt[1];
			var last_x = region[region.length - 1][0];
			var last_y = region[region.length - 1][1];
			var inside = false;
			for (var i = 0; i < region.length; i++){
				var curr_x = region[i][0];
				var curr_y = region[i][1];

				// if y is between curr_y and last_y, and
				// x is to the right of the boundary created by the line
				if ((curr_y - y > eps) != (last_y - y > eps) &&
					(last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps)
					inside = !inside

				last_x = curr_x;
				last_y = curr_y;
			}
			return inside;
		}
	};
	return my;
}

module.exports = Epsilon;

},{}],462:[function(_dereq_,module,exports){
// (c) Copyright 2017, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs

//
// convert between PolyBool polygon format and GeoJSON formats (Polygon and MultiPolygon)
//

var GeoJSON = {
	// convert a GeoJSON object to a PolyBool polygon
	toPolygon: function(PolyBool, geojson){

		// converts list of LineString's to segments
		function GeoPoly(coords){
			// check for empty coords
			if (coords.length <= 0)
				return PolyBool.segments({ inverted: false, regions: [] });

			// convert LineString to segments
			function LineString(ls){
				// remove tail which should be the same as head
				var reg = ls.slice(0, ls.length - 1);
				return PolyBool.segments({ inverted: false, regions: [reg] });
			}

			// the first LineString is considered the outside
			var out = LineString(coords[0]);

			// the rest of the LineStrings are considered interior holes, so subtract them from the
			// current result
			for (var i = 1; i < coords.length; i++)
				out = PolyBool.selectDifference(PolyBool.combine(out, LineString(coords[i])));

			return out;
		}

		if (geojson.type === 'Polygon'){
			// single polygon, so just convert it and we're done
			return PolyBool.polygon(GeoPoly(geojson.coordinates));
		}
		else if (geojson.type === 'MultiPolygon'){
			// multiple polygons, so union all the polygons together
			var out = PolyBool.segments({ inverted: false, regions: [] });
			for (var i = 0; i < geojson.coordinates.length; i++)
				out = PolyBool.selectUnion(PolyBool.combine(out, GeoPoly(geojson.coordinates[i])));
			return PolyBool.polygon(out);
		}
		throw new Error('PolyBool: Cannot convert GeoJSON object to PolyBool polygon');
	},

	// convert a PolyBool polygon to a GeoJSON object
	fromPolygon: function(PolyBool, eps, poly){
		// make sure out polygon is clean
		poly = PolyBool.polygon(PolyBool.segments(poly));

		// test if r1 is inside r2
		function regionInsideRegion(r1, r2){
			// we're guaranteed no lines intersect (because the polygon is clean), but a vertex
			// could be on the edge -- so we just average pt[0] and pt[1] to produce a point on the
			// edge of the first line, which cannot be on an edge
			return eps.pointInsideRegion([
				(r1[0][0] + r1[1][0]) * 0.5,
				(r1[0][1] + r1[1][1]) * 0.5
			], r2);
		}

		// calculate inside heirarchy
		//
		//  _____________________   _______    roots -> A       -> F
		// |          A          | |   F   |            |          |
		// |  _______   _______  | |  ___  |            +-- B      +-- G
		// | |   B   | |   C   | | | |   | |            |   |
		// | |  ___  | |  ___  | | | |   | |            |   +-- D
		// | | | D | | | | E | | | | | G | |            |
		// | | |___| | | |___| | | | |   | |            +-- C
		// | |_______| |_______| | | |___| |                |
		// |_____________________| |_______|                +-- E

		function newNode(region){
			return {
				region: region,
				children: []
			};
		}

		var roots = newNode(null);

		function addChild(root, region){
			// first check if we're inside any children
			for (var i = 0; i < root.children.length; i++){
				var child = root.children[i];
				if (regionInsideRegion(region, child.region)){
					// we are, so insert inside them instead
					addChild(child, region);
					return;
				}
			}

			// not inside any children, so check to see if any children are inside us
			var node = newNode(region);
			for (var i = 0; i < root.children.length; i++){
				var child = root.children[i];
				if (regionInsideRegion(child.region, region)){
					// oops... move the child beneath us, and remove them from root
					node.children.push(child);
					root.children.splice(i, 1);
					i--;
				}
			}

			// now we can add ourselves
			root.children.push(node);
		}

		// add all regions to the root
		for (var i = 0; i < poly.regions.length; i++){
			var region = poly.regions[i];
			if (region.length < 3) // regions must have at least 3 points (sanity check)
				continue;
			addChild(roots, region);
		}

		// with our heirarchy, we can distinguish between exterior borders, and interior holes
		// the root nodes are exterior, children are interior, children's children are exterior,
		// children's children's children are interior, etc

		// while we're at it, exteriors are counter-clockwise, and interiors are clockwise

		function forceWinding(region, clockwise){
			// first, see if we're clockwise or counter-clockwise
			// https://en.wikipedia.org/wiki/Shoelace_formula
			var winding = 0;
			var last_x = region[region.length - 1][0];
			var last_y = region[region.length - 1][1];
			var copy = [];
			for (var i = 0; i < region.length; i++){
				var curr_x = region[i][0];
				var curr_y = region[i][1];
				copy.push([curr_x, curr_y]); // create a copy while we're at it
				winding += curr_y * last_x - curr_x * last_y;
				last_x = curr_x;
				last_y = curr_y;
			}
			// this assumes Cartesian coordinates (Y is positive going up)
			var isclockwise = winding < 0;
			if (isclockwise !== clockwise)
				copy.reverse();
			// while we're here, the last point must be the first point...
			copy.push([copy[0][0], copy[0][1]]);
			return copy;
		}

		var geopolys = [];

		function addExterior(node){
			var poly = [forceWinding(node.region, false)];
			geopolys.push(poly);
			// children of exteriors are interior
			for (var i = 0; i < node.children.length; i++)
				poly.push(getInterior(node.children[i]));
		}

		function getInterior(node){
			// children of interiors are exterior
			for (var i = 0; i < node.children.length; i++)
				addExterior(node.children[i]);
			// return the clockwise interior
			return forceWinding(node.region, true);
		}

		// root nodes are exterior
		for (var i = 0; i < roots.children.length; i++)
			addExterior(roots.children[i]);

		// lastly, construct the approrpriate GeoJSON object

		if (geopolys.length <= 0) // empty GeoJSON Polygon
			return { type: 'Polygon', coordinates: [] };
		if (geopolys.length == 1) // use a GeoJSON Polygon
			return { type: 'Polygon', coordinates: geopolys[0] };
		return { // otherwise, use a GeoJSON MultiPolygon
			type: 'MultiPolygon',
			coordinates: geopolys
		};
	}
};

module.exports = GeoJSON;

},{}],463:[function(_dereq_,module,exports){
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs

//
// this is the core work-horse
//

var LinkedList = _dereq_('./linked-list');

function Intersecter(selfIntersection, eps, buildLog){
	// selfIntersection is true/false depending on the phase of the overall algorithm

	//
	// segment creation
	//

	function segmentNew(start, end){
		return {
			id: buildLog ? buildLog.segmentId() : -1,
			start: start,
			end: end,
			myFill: {
				above: null, // is there fill above us?
				below: null  // is there fill below us?
			},
			otherFill: null
		};
	}

	function segmentCopy(start, end, seg){
		return {
			id: buildLog ? buildLog.segmentId() : -1,
			start: start,
			end: end,
			myFill: {
				above: seg.myFill.above,
				below: seg.myFill.below
			},
			otherFill: null
		};
	}

	//
	// event logic
	//

	var event_root = LinkedList.create();

	function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2){
		// compare the selected points first
		var comp = eps.pointsCompare(p1_1, p2_1);
		if (comp !== 0)
			return comp;
		// the selected points are the same

		if (eps.pointsSame(p1_2, p2_2)) // if the non-selected points are the same too...
			return 0; // then the segments are equal

		if (p1_isStart !== p2_isStart) // if one is a start and the other isn't...
			return p1_isStart ? 1 : -1; // favor the one that isn't the start

		// otherwise, we'll have to calculate which one is below the other manually
		return eps.pointAboveOrOnLine(p1_2,
			p2_isStart ? p2_1 : p2_2, // order matters
			p2_isStart ? p2_2 : p2_1
		) ? 1 : -1;
	}

	function eventAdd(ev, other_pt){
		event_root.insertBefore(ev, function(here){
			// should ev be inserted before here?
			var comp = eventCompare(
				ev  .isStart, ev  .pt,      other_pt,
				here.isStart, here.pt, here.other.pt
			);
			return comp < 0;
		});
	}

	function eventAddSegmentStart(seg, primary){
		var ev_start = LinkedList.node({
			isStart: true,
			pt: seg.start,
			seg: seg,
			primary: primary,
			other: null,
			status: null
		});
		eventAdd(ev_start, seg.end);
		return ev_start;
	}

	function eventAddSegmentEnd(ev_start, seg, primary){
		var ev_end = LinkedList.node({
			isStart: false,
			pt: seg.end,
			seg: seg,
			primary: primary,
			other: ev_start,
			status: null
		});
		ev_start.other = ev_end;
		eventAdd(ev_end, ev_start.pt);
	}

	function eventAddSegment(seg, primary){
		var ev_start = eventAddSegmentStart(seg, primary);
		eventAddSegmentEnd(ev_start, seg, primary);
		return ev_start;
	}

	function eventUpdateEnd(ev, end){
		// slides an end backwards
		//   (start)------------(end)    to:
		//   (start)---(end)

		if (buildLog)
			buildLog.segmentChop(ev.seg, end);

		ev.other.remove();
		ev.seg.end = end;
		ev.other.pt = end;
		eventAdd(ev.other, ev.pt);
	}

	function eventDivide(ev, pt){
		var ns = segmentCopy(pt, ev.seg.end, ev.seg);
		eventUpdateEnd(ev, pt);
		return eventAddSegment(ns, ev.primary);
	}

	function calculate(primaryPolyInverted, secondaryPolyInverted){
		// if selfIntersection is true then there is no secondary polygon, so that isn't used

		//
		// status logic
		//

		var status_root = LinkedList.create();

		function statusCompare(ev1, ev2){
			var a1 = ev1.seg.start;
			var a2 = ev1.seg.end;
			var b1 = ev2.seg.start;
			var b2 = ev2.seg.end;

			if (eps.pointsCollinear(a1, b1, b2)){
				if (eps.pointsCollinear(a2, b1, b2))
					return 1;//eventCompare(true, a1, a2, true, b1, b2);
				return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1;
			}
			return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1;
		}

		function statusFindSurrounding(ev){
			return status_root.findTransition(function(here){
				var comp = statusCompare(ev, here.ev);
				return comp > 0;
			});
		}

		function checkIntersection(ev1, ev2){
			// returns the segment equal to ev1, or false if nothing equal

			var seg1 = ev1.seg;
			var seg2 = ev2.seg;
			var a1 = seg1.start;
			var a2 = seg1.end;
			var b1 = seg2.start;
			var b2 = seg2.end;

			if (buildLog)
				buildLog.checkIntersection(seg1, seg2);

			var i = eps.linesIntersect(a1, a2, b1, b2);

			if (i === false){
				// segments are parallel or coincident

				// if points aren't collinear, then the segments are parallel, so no intersections
				if (!eps.pointsCollinear(a1, a2, b1))
					return false;
				// otherwise, segments are on top of each other somehow (aka coincident)

				if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1))
					return false; // segments touch at endpoints... no intersection

				var a1_equ_b1 = eps.pointsSame(a1, b1);
				var a2_equ_b2 = eps.pointsSame(a2, b2);

				if (a1_equ_b1 && a2_equ_b2)
					return ev2; // segments are exactly equal

				var a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2);
				var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2);

				// handy for debugging:
				// buildLog.log({
				//	a1_equ_b1: a1_equ_b1,
				//	a2_equ_b2: a2_equ_b2,
				//	a1_between: a1_between,
				//	a2_between: a2_between
				// });

				if (a1_equ_b1){
					if (a2_between){
						//  (a1)---(a2)
						//  (b1)----------(b2)
						eventDivide(ev2, a2);
					}
					else{
						//  (a1)----------(a2)
						//  (b1)---(b2)
						eventDivide(ev1, b2);
					}
					return ev2;
				}
				else if (a1_between){
					if (!a2_equ_b2){
						// make a2 equal to b2
						if (a2_between){
							//         (a1)---(a2)
							//  (b1)-----------------(b2)
							eventDivide(ev2, a2);
						}
						else{
							//         (a1)----------(a2)
							//  (b1)----------(b2)
							eventDivide(ev1, b2);
						}
					}

					//         (a1)---(a2)
					//  (b1)----------(b2)
					eventDivide(ev2, a1);
				}
			}
			else{
				// otherwise, lines intersect at i.pt, which may or may not be between the endpoints

				// is A divided between its endpoints? (exclusive)
				if (i.alongA === 0){
					if (i.alongB === -1) // yes, at exactly b1
						eventDivide(ev1, b1);
					else if (i.alongB === 0) // yes, somewhere between B's endpoints
						eventDivide(ev1, i.pt);
					else if (i.alongB === 1) // yes, at exactly b2
						eventDivide(ev1, b2);
				}

				// is B divided between its endpoints? (exclusive)
				if (i.alongB === 0){
					if (i.alongA === -1) // yes, at exactly a1
						eventDivide(ev2, a1);
					else if (i.alongA === 0) // yes, somewhere between A's endpoints (exclusive)
						eventDivide(ev2, i.pt);
					else if (i.alongA === 1) // yes, at exactly a2
						eventDivide(ev2, a2);
				}
			}
			return false;
		}

		//
		// main event loop
		//
		var segments = [];
		while (!event_root.isEmpty()){
			var ev = event_root.getHead();

			if (buildLog)
				buildLog.vert(ev.pt[0]);

			if (ev.isStart){

				if (buildLog)
					buildLog.segmentNew(ev.seg, ev.primary);

				var surrounding = statusFindSurrounding(ev);
				var above = surrounding.before ? surrounding.before.ev : null;
				var below = surrounding.after ? surrounding.after.ev : null;

				if (buildLog){
					buildLog.tempStatus(
						ev.seg,
						above ? above.seg : false,
						below ? below.seg : false
					);
				}

				function checkBothIntersections(){
					if (above){
						var eve = checkIntersection(ev, above);
						if (eve)
							return eve;
					}
					if (below)
						return checkIntersection(ev, below);
					return false;
				}

				var eve = checkBothIntersections();
				if (eve){
					// ev and eve are equal
					// we'll keep eve and throw away ev

					// merge ev.seg's fill information into eve.seg

					if (selfIntersection){
						var toggle; // are we a toggling edge?
						if (ev.seg.myFill.below === null)
							toggle = true;
						else
							toggle = ev.seg.myFill.above !== ev.seg.myFill.below;

						// merge two segments that belong to the same polygon
						// think of this as sandwiching two segments together, where `eve.seg` is
						// the bottom -- this will cause the above fill flag to toggle
						if (toggle)
							eve.seg.myFill.above = !eve.seg.myFill.above;
					}
					else{
						// merge two segments that belong to different polygons
						// each segment has distinct knowledge, so no special logic is needed
						// note that this can only happen once per segment in this phase, because we
						// are guaranteed that all self-intersections are gone
						eve.seg.otherFill = ev.seg.myFill;
					}

					if (buildLog)
						buildLog.segmentUpdate(eve.seg);

					ev.other.remove();
					ev.remove();
				}

				if (event_root.getHead() !== ev){
					// something was inserted before us in the event queue, so loop back around and
					// process it before continuing
					if (buildLog)
						buildLog.rewind(ev.seg);
					continue;
				}

				//
				// calculate fill flags
				//
				if (selfIntersection){
					var toggle; // are we a toggling edge?
					if (ev.seg.myFill.below === null) // if we are a new segment...
						toggle = true; // then we toggle
					else // we are a segment that has previous knowledge from a division
						toggle = ev.seg.myFill.above !== ev.seg.myFill.below; // calculate toggle

					// next, calculate whether we are filled below us
					if (!below){ // if nothing is below us...
						// we are filled below us if the polygon is inverted
						ev.seg.myFill.below = primaryPolyInverted;
					}
					else{
						// otherwise, we know the answer -- it's the same if whatever is below
						// us is filled above it
						ev.seg.myFill.below = below.seg.myFill.above;
					}

					// since now we know if we're filled below us, we can calculate whether
					// we're filled above us by applying toggle to whatever is below us
					if (toggle)
						ev.seg.myFill.above = !ev.seg.myFill.below;
					else
						ev.seg.myFill.above = ev.seg.myFill.below;
				}
				else{
					// now we fill in any missing transition information, since we are all-knowing
					// at this point

					if (ev.seg.otherFill === null){
						// if we don't have other information, then we need to figure out if we're
						// inside the other polygon
						var inside;
						if (!below){
							// if nothing is below us, then we're inside if the other polygon is
							// inverted
							inside =
								ev.primary ? secondaryPolyInverted : primaryPolyInverted;
						}
						else{ // otherwise, something is below us
							// so copy the below segment's other polygon's above
							if (ev.primary === below.primary)
								inside = below.seg.otherFill.above;
							else
								inside = below.seg.myFill.above;
						}
						ev.seg.otherFill = {
							above: inside,
							below: inside
						};
					}
				}

				if (buildLog){
					buildLog.status(
						ev.seg,
						above ? above.seg : false,
						below ? below.seg : false
					);
				}

				// insert the status and remember it for later removal
				ev.other.status = surrounding.insert(LinkedList.node({ ev: ev }));
			}
			else{
				var st = ev.status;

				if (st === null){
					throw new Error('PolyBool: Zero-length segment detected; your epsilon is ' +
						'probably too small or too large');
				}

				// removing the status will create two new adjacent edges, so we'll need to check
				// for those
				if (status_root.exists(st.prev) && status_root.exists(st.next))
					checkIntersection(st.prev.ev, st.next.ev);

				if (buildLog)
					buildLog.statusRemove(st.ev.seg);

				// remove the status
				st.remove();

				// if we've reached this point, we've calculated everything there is to know, so
				// save the segment for reporting
				if (!ev.primary){
					// make sure `seg.myFill` actually points to the primary polygon though
					var s = ev.seg.myFill;
					ev.seg.myFill = ev.seg.otherFill;
					ev.seg.otherFill = s;
				}
				segments.push(ev.seg);
			}

			// remove the event and continue
			event_root.getHead().remove();
		}

		if (buildLog)
			buildLog.done();

		return segments;
	}

	// return the appropriate API depending on what we're doing
	if (!selfIntersection){
		// performing combination of polygons, so only deal with already-processed segments
		return {
			calculate: function(segments1, inverted1, segments2, inverted2){
				// segmentsX come from the self-intersection API, or this API
				// invertedX is whether we treat that list of segments as an inverted polygon or not
				// returns segments that can be used for further operations
				segments1.forEach(function(seg){
					eventAddSegment(segmentCopy(seg.start, seg.end, seg), true);
				});
				segments2.forEach(function(seg){
					eventAddSegment(segmentCopy(seg.start, seg.end, seg), false);
				});
				return calculate(inverted1, inverted2);
			}
		};
	}

	// otherwise, performing self-intersection, so deal with regions
	return {
		addRegion: function(region){
			// regions are a list of points:
			//  [ [0, 0], [100, 0], [50, 100] ]
			// you can add multiple regions before running calculate
			var pt1;
			var pt2 = region[region.length - 1];
			for (var i = 0; i < region.length; i++){
				pt1 = pt2;
				pt2 = region[i];

				var forward = eps.pointsCompare(pt1, pt2);
				if (forward === 0) // points are equal, so we have a zero-length segment
					continue; // just skip it

				eventAddSegment(
					segmentNew(
						forward < 0 ? pt1 : pt2,
						forward < 0 ? pt2 : pt1
					),
					true
				);
			}
		},
		calculate: function(inverted){
			// is the polygon inverted?
			// returns segments
			return calculate(inverted, false);
		}
	};
}

module.exports = Intersecter;

},{"./linked-list":464}],464:[function(_dereq_,module,exports){
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs

//
// simple linked list implementation that allows you to traverse down nodes and save positions
//

var LinkedList = {
	create: function(){
		var my = {
			root: { root: true, next: null },
			exists: function(node){
				if (node === null || node === my.root)
					return false;
				return true;
			},
			isEmpty: function(){
				return my.root.next === null;
			},
			getHead: function(){
				return my.root.next;
			},
			insertBefore: function(node, check){
				var last = my.root;
				var here = my.root.next;
				while (here !== null){
					if (check(here)){
						node.prev = here.prev;
						node.next = here;
						here.prev.next = node;
						here.prev = node;
						return;
					}
					last = here;
					here = here.next;
				}
				last.next = node;
				node.prev = last;
				node.next = null;
			},
			findTransition: function(check){
				var prev = my.root;
				var here = my.root.next;
				while (here !== null){
					if (check(here))
						break;
					prev = here;
					here = here.next;
				}
				return {
					before: prev === my.root ? null : prev,
					after: here,
					insert: function(node){
						node.prev = prev;
						node.next = here;
						prev.next = node;
						if (here !== null)
							here.prev = node;
						return node;
					}
				};
			}
		};
		return my;
	},
	node: function(data){
		data.prev = null;
		data.next = null;
		data.remove = function(){
			data.prev.next = data.next;
			if (data.next)
				data.next.prev = data.prev;
			data.prev = null;
			data.next = null;
		};
		return data;
	}
};

module.exports = LinkedList;

},{}],465:[function(_dereq_,module,exports){
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs

//
// converts a list of segments into a list of regions, while also removing unnecessary verticies
//

function SegmentChainer(segments, eps, buildLog){
	var chains = [];
	var regions = [];

	segments.forEach(function(seg){
		var pt1 = seg.start;
		var pt2 = seg.end;
		if (eps.pointsSame(pt1, pt2)){
			console.warn('PolyBool: Warning: Zero-length segment detected; your epsilon is ' +
				'probably too small or too large');
			return;
		}

		if (buildLog)
			buildLog.chainStart(seg);

		// search for two chains that this segment matches
		var first_match = {
			index: 0,
			matches_head: false,
			matches_pt1: false
		};
		var second_match = {
			index: 0,
			matches_head: false,
			matches_pt1: false
		};
		var next_match = first_match;
		function setMatch(index, matches_head, matches_pt1){
			// return true if we've matched twice
			next_match.index = index;
			next_match.matches_head = matches_head;
			next_match.matches_pt1 = matches_pt1;
			if (next_match === first_match){
				next_match = second_match;
				return false;
			}
			next_match = null;
			return true; // we've matched twice, we're done here
		}
		for (var i = 0; i < chains.length; i++){
			var chain = chains[i];
			var head  = chain[0];
			var head2 = chain[1];
			var tail  = chain[chain.length - 1];
			var tail2 = chain[chain.length - 2];
			if (eps.pointsSame(head, pt1)){
				if (setMatch(i, true, true))
					break;
			}
			else if (eps.pointsSame(head, pt2)){
				if (setMatch(i, true, false))
					break;
			}
			else if (eps.pointsSame(tail, pt1)){
				if (setMatch(i, false, true))
					break;
			}
			else if (eps.pointsSame(tail, pt2)){
				if (setMatch(i, false, false))
					break;
			}
		}

		if (next_match === first_match){
			// we didn't match anything, so create a new chain
			chains.push([ pt1, pt2 ]);
			if (buildLog)
				buildLog.chainNew(pt1, pt2);
			return;
		}

		if (next_match === second_match){
			// we matched a single chain

			if (buildLog)
				buildLog.chainMatch(first_match.index);

			// add the other point to the apporpriate end, and check to see if we've closed the
			// chain into a loop

			var index = first_match.index;
			var pt = first_match.matches_pt1 ? pt2 : pt1; // if we matched pt1, then we add pt2, etc
			var addToHead = first_match.matches_head; // if we matched at head, then add to the head

			var chain = chains[index];
			var grow  = addToHead ? chain[0] : chain[chain.length - 1];
			var grow2 = addToHead ? chain[1] : chain[chain.length - 2];
			var oppo  = addToHead ? chain[chain.length - 1] : chain[0];
			var oppo2 = addToHead ? chain[chain.length - 2] : chain[1];

			if (eps.pointsCollinear(grow2, grow, pt)){
				// grow isn't needed because it's directly between grow2 and pt:
				// grow2 ---grow---> pt
				if (addToHead){
					if (buildLog)
						buildLog.chainRemoveHead(first_match.index, pt);
					chain.shift();
				}
				else{
					if (buildLog)
						buildLog.chainRemoveTail(first_match.index, pt);
					chain.pop();
				}
				grow = grow2; // old grow is gone... new grow is what grow2 was
			}

			if (eps.pointsSame(oppo, pt)){
				// we're closing the loop, so remove chain from chains
				chains.splice(index, 1);

				if (eps.pointsCollinear(oppo2, oppo, grow)){
					// oppo isn't needed because it's directly between oppo2 and grow:
					// oppo2 ---oppo--->grow
					if (addToHead){
						if (buildLog)
							buildLog.chainRemoveTail(first_match.index, grow);
						chain.pop();
					}
					else{
						if (buildLog)
							buildLog.chainRemoveHead(first_match.index, grow);
						chain.shift();
					}
				}

				if (buildLog)
					buildLog.chainClose(first_match.index);

				// we have a closed chain!
				regions.push(chain);
				return;
			}

			// not closing a loop, so just add it to the apporpriate side
			if (addToHead){
				if (buildLog)
					buildLog.chainAddHead(first_match.index, pt);
				chain.unshift(pt);
			}
			else{
				if (buildLog)
					buildLog.chainAddTail(first_match.index, pt);
				chain.push(pt);
			}
			return;
		}

		// otherwise, we matched two chains, so we need to combine those chains together

		function reverseChain(index){
			if (buildLog)
				buildLog.chainReverse(index);
			chains[index].reverse(); // gee, that's easy
		}

		function appendChain(index1, index2){
			// index1 gets index2 appended to it, and index2 is removed
			var chain1 = chains[index1];
			var chain2 = chains[index2];
			var tail  = chain1[chain1.length - 1];
			var tail2 = chain1[chain1.length - 2];
			var head  = chain2[0];
			var head2 = chain2[1];

			if (eps.pointsCollinear(tail2, tail, head)){
				// tail isn't needed because it's directly between tail2 and head
				// tail2 ---tail---> head
				if (buildLog)
					buildLog.chainRemoveTail(index1, tail);
				chain1.pop();
				tail = tail2; // old tail is gone... new tail is what tail2 was
			}

			if (eps.pointsCollinear(tail, head, head2)){
				// head isn't needed because it's directly between tail and head2
				// tail ---head---> head2
				if (buildLog)
					buildLog.chainRemoveHead(index2, head);
				chain2.shift();
			}

			if (buildLog)
				buildLog.chainJoin(index1, index2);
			chains[index1] = chain1.concat(chain2);
			chains.splice(index2, 1);
		}

		var F = first_match.index;
		var S = second_match.index;

		if (buildLog)
			buildLog.chainConnect(F, S);

		var reverseF = chains[F].length < chains[S].length; // reverse the shorter chain, if needed
		if (first_match.matches_head){
			if (second_match.matches_head){
				if (reverseF){
					// <<<< F <<<< --- >>>> S >>>>
					reverseChain(F);
					// >>>> F >>>> --- >>>> S >>>>
					appendChain(F, S);
				}
				else{
					// <<<< F <<<< --- >>>> S >>>>
					reverseChain(S);
					// <<<< F <<<< --- <<<< S <<<<   logically same as:
					// >>>> S >>>> --- >>>> F >>>>
					appendChain(S, F);
				}
			}
			else{
				// <<<< F <<<< --- <<<< S <<<<   logically same as:
				// >>>> S >>>> --- >>>> F >>>>
				appendChain(S, F);
			}
		}
		else{
			if (second_match.matches_head){
				// >>>> F >>>> --- >>>> S >>>>
				appendChain(F, S);
			}
			else{
				if (reverseF){
					// >>>> F >>>> --- <<<< S <<<<
					reverseChain(F);
					// <<<< F <<<< --- <<<< S <<<<   logically same as:
					// >>>> S >>>> --- >>>> F >>>>
					appendChain(S, F);
				}
				else{
					// >>>> F >>>> --- <<<< S <<<<
					reverseChain(S);
					// >>>> F >>>> --- >>>> S >>>>
					appendChain(F, S);
				}
			}
		}
	});

	return regions;
}

module.exports = SegmentChainer;

},{}],466:[function(_dereq_,module,exports){
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs

//
// filter a list of segments based on boolean operations
//

function select(segments, selection, buildLog){
	var result = [];
	segments.forEach(function(seg){
		var index =
			(seg.myFill.above ? 8 : 0) +
			(seg.myFill.below ? 4 : 0) +
			((seg.otherFill && seg.otherFill.above) ? 2 : 0) +
			((seg.otherFill && seg.otherFill.below) ? 1 : 0);
		if (selection[index] !== 0){
			// copy the segment to the results, while also calculating the fill status
			result.push({
				id: buildLog ? buildLog.segmentId() : -1,
				start: seg.start,
				end: seg.end,
				myFill: {
					above: selection[index] === 1, // 1 if filled above
					below: selection[index] === 2  // 2 if filled below
				},
				otherFill: null
			});
		}
	});

	if (buildLog)
		buildLog.selected(result);

	return result;
}

var SegmentSelector = {
	union: function(segments, buildLog){ // primary | secondary
		// above1 below1 above2 below2    Keep?               Value
		//    0      0      0      0   =>   no                  0
		//    0      0      0      1   =>   yes filled below    2
		//    0      0      1      0   =>   yes filled above    1
		//    0      0      1      1   =>   no                  0
		//    0      1      0      0   =>   yes filled below    2
		//    0      1      0      1   =>   yes filled below    2
		//    0      1      1      0   =>   no                  0
		//    0      1      1      1   =>   no                  0
		//    1      0      0      0   =>   yes filled above    1
		//    1      0      0      1   =>   no                  0
		//    1      0      1      0   =>   yes filled above    1
		//    1      0      1      1   =>   no                  0
		//    1      1      0      0   =>   no                  0
		//    1      1      0      1   =>   no                  0
		//    1      1      1      0   =>   no                  0
		//    1      1      1      1   =>   no                  0
		return select(segments, [
			0, 2, 1, 0,
			2, 2, 0, 0,
			1, 0, 1, 0,
			0, 0, 0, 0
		], buildLog);
	},
	intersect: function(segments, buildLog){ // primary & secondary
		// above1 below1 above2 below2    Keep?               Value
		//    0      0      0      0   =>   no                  0
		//    0      0      0      1   =>   no                  0
		//    0      0      1      0   =>   no                  0
		//    0      0      1      1   =>   no                  0
		//    0      1      0      0   =>   no                  0
		//    0      1      0      1   =>   yes filled below    2
		//    0      1      1      0   =>   no                  0
		//    0      1      1      1   =>   yes filled below    2
		//    1      0      0      0   =>   no                  0
		//    1      0      0      1   =>   no                  0
		//    1      0      1      0   =>   yes filled above    1
		//    1      0      1      1   =>   yes filled above    1
		//    1      1      0      0   =>   no                  0
		//    1      1      0      1   =>   yes filled below    2
		//    1      1      1      0   =>   yes filled above    1
		//    1      1      1      1   =>   no                  0
		return select(segments, [
			0, 0, 0, 0,
			0, 2, 0, 2,
			0, 0, 1, 1,
			0, 2, 1, 0
		], buildLog);
	},
	difference: function(segments, buildLog){ // primary - secondary
		// above1 below1 above2 below2    Keep?               Value
		//    0      0      0      0   =>   no                  0
		//    0      0      0      1   =>   no                  0
		//    0      0      1      0   =>   no                  0
		//    0      0      1      1   =>   no                  0
		//    0      1      0      0   =>   yes filled below    2
		//    0      1      0      1   =>   no                  0
		//    0      1      1      0   =>   yes filled below    2
		//    0      1      1      1   =>   no                  0
		//    1      0      0      0   =>   yes filled above    1
		//    1      0      0      1   =>   yes filled above    1
		//    1      0      1      0   =>   no                  0
		//    1      0      1      1   =>   no                  0
		//    1      1      0      0   =>   no                  0
		//    1      1      0      1   =>   yes filled above    1
		//    1      1      1      0   =>   yes filled below    2
		//    1      1      1      1   =>   no                  0
		return select(segments, [
			0, 0, 0, 0,
			2, 0, 2, 0,
			1, 1, 0, 0,
			0, 1, 2, 0
		], buildLog);
	},
	differenceRev: function(segments, buildLog){ // secondary - primary
		// above1 below1 above2 below2    Keep?               Value
		//    0      0      0      0   =>   no                  0
		//    0      0      0      1   =>   yes filled below    2
		//    0      0      1      0   =>   yes filled above    1
		//    0      0      1      1   =>   no                  0
		//    0      1      0      0   =>   no                  0
		//    0      1      0      1   =>   no                  0
		//    0      1      1      0   =>   yes filled above    1
		//    0      1      1      1   =>   yes filled above    1
		//    1      0      0      0   =>   no                  0
		//    1      0      0      1   =>   yes filled below    2
		//    1      0      1      0   =>   no                  0
		//    1      0      1      1   =>   yes filled below    2
		//    1      1      0      0   =>   no                  0
		//    1      1      0      1   =>   no                  0
		//    1      1      1      0   =>   no                  0
		//    1      1      1      1   =>   no                  0
		return select(segments, [
			0, 2, 1, 0,
			0, 0, 1, 1,
			0, 2, 0, 2,
			0, 0, 0, 0
		], buildLog);
	},
	xor: function(segments, buildLog){ // primary ^ secondary
		// above1 below1 above2 below2    Keep?               Value
		//    0      0      0      0   =>   no                  0
		//    0      0      0      1   =>   yes filled below    2
		//    0      0      1      0   =>   yes filled above    1
		//    0      0      1      1   =>   no                  0
		//    0      1      0      0   =>   yes filled below    2
		//    0      1      0      1   =>   no                  0
		//    0      1      1      0   =>   no                  0
		//    0      1      1      1   =>   yes filled above    1
		//    1      0      0      0   =>   yes filled above    1
		//    1      0      0      1   =>   no                  0
		//    1      0      1      0   =>   no                  0
		//    1      0      1      1   =>   yes filled below    2
		//    1      1      0      0   =>   no                  0
		//    1      1      0      1   =>   yes filled above    1
		//    1      1      1      0   =>   yes filled below    2
		//    1      1      1      1   =>   no                  0
		return select(segments, [
			0, 2, 1, 0,
			2, 0, 0, 1,
			1, 0, 0, 2,
			0, 1, 2, 0
		], buildLog);
	}
};

module.exports = SegmentSelector;

},{}],467:[function(_dereq_,module,exports){
//Optimized version for triangle closest point
// Based on Eberly's WildMagick codes
// http://www.geometrictools.com/LibMathematics/Distance/Distance.html
"use strict";

var diff = new Float64Array(4);
var edge0 = new Float64Array(4);
var edge1 = new Float64Array(4);

function closestPoint2d(V0, V1, V2, point, result) {
  //Reallocate buffers if necessary
  if(diff.length < point.length) {
    diff = new Float64Array(point.length);
    edge0 = new Float64Array(point.length);
    edge1 = new Float64Array(point.length);
  }
  //Compute edges
  for(var i=0; i<point.length; ++i) {
    diff[i]  = V0[i] - point[i];
    edge0[i] = V1[i] - V0[i];
    edge1[i] = V2[i] - V0[i];
  }
  //Compute coefficients for quadratic func
  var a00 = 0.0
    , a01 = 0.0
    , a11 = 0.0
    , b0  = 0.0
    , b1  = 0.0
    , c   = 0.0;
  for(var i=0; i<point.length; ++i) {
    var e0 = edge0[i]
      , e1 = edge1[i]
      , d  = diff[i];
    a00 += e0 * e0;
    a01 += e0 * e1;
    a11 += e1 * e1;
    b0  += d * e0;
    b1  += d * e1;
    c   += d * d;
  }
  //Compute determinant/coeffs
  var det = Math.abs(a00*a11 - a01*a01);
  var s   = a01*b1 - a11*b0;
  var t   = a01*b0 - a00*b1;
  var sqrDistance;
  //Hardcoded Voronoi diagram classification
  if (s + t <= det) {
    if (s < 0) {
      if (t < 0) { // region 4
        if (b0 < 0) {
          t = 0;
          if (-b0 >= a00) {
            s = 1.0;
            sqrDistance = a00 + 2.0*b0 + c;
          } else {
            s = -b0/a00;
            sqrDistance = b0*s + c;
          }
        } else {
          s = 0;
          if (b1 >= 0) {
            t = 0;
            sqrDistance = c;
          } else if (-b1 >= a11) {
            t = 1;
            sqrDistance = a11 + 2.0*b1 + c;
          } else {
            t = -b1/a11;
            sqrDistance = b1*t + c;
          }
        }
      } else {  // region 3
        s = 0;
        if (b1 >= 0) {
          t = 0;
          sqrDistance = c;
        } else if (-b1 >= a11) {
          t = 1;
          sqrDistance = a11 + 2.0*b1 + c;
        } else {
          t = -b1/a11;
          sqrDistance = b1*t + c;
        }
      }
    } else if (t < 0) { // region 5
      t = 0;
      if (b0 >= 0) {
        s = 0;
        sqrDistance = c;
      } else if (-b0 >= a00) {
        s = 1;
        sqrDistance = a00 + 2.0*b0 + c;
      } else {
        s = -b0/a00;
        sqrDistance = b0*s + c;
      }
    } else {  // region 0
      // minimum at interior point
      var invDet = 1.0 / det;
      s *= invDet;
      t *= invDet;
      sqrDistance = s*(a00*s + a01*t + 2.0*b0) + t*(a01*s + a11*t + 2.0*b1) + c;
    }
  } else {
    var tmp0, tmp1, numer, denom;
    
    if (s < 0) {  // region 2
      tmp0 = a01 + b0;
      tmp1 = a11 + b1;
      if (tmp1 > tmp0) {
        numer = tmp1 - tmp0;
        denom = a00 - 2.0*a01 + a11;
        if (numer >= denom) {
          s = 1;
          t = 0;
          sqrDistance = a00 + 2.0*b0 + c;
        } else {
          s = numer/denom;
          t = 1 - s;
          sqrDistance = s*(a00*s + a01*t + 2.0*b0) +
          t*(a01*s + a11*t + 2.0*b1) + c;
        }
      } else {
        s = 0;
        if (tmp1 <= 0) {
          t = 1;
          sqrDistance = a11 + 2.0*b1 + c;
        } else if (b1 >= 0) {
          t = 0;
          sqrDistance = c;
        } else {
          t = -b1/a11;
          sqrDistance = b1*t + c;
        }
      }
    } else if (t < 0) {  // region 6
      tmp0 = a01 + b1;
      tmp1 = a00 + b0;
      if (tmp1 > tmp0) {
        numer = tmp1 - tmp0;
        denom = a00 - 2.0*a01 + a11;
        if (numer >= denom) {
          t = 1;
          s = 0;
          sqrDistance = a11 + 2.0*b1 + c;
        } else {
          t = numer/denom;
          s = 1 - t;
          sqrDistance = s*(a00*s + a01*t + 2.0*b0) +
          t*(a01*s + a11*t + 2.0*b1) + c;
        }
      } else {
        t = 0;
        if (tmp1 <= 0) {
          s = 1;
          sqrDistance = a00 + 2.0*b0 + c;
        } else if (b0 >= 0) {
          s = 0;
          sqrDistance = c;
        } else {
          s = -b0/a00;
          sqrDistance = b0*s + c;
        }
      }
    } else {  // region 1
      numer = a11 + b1 - a01 - b0;
      if (numer <= 0) {
        s = 0;
        t = 1;
        sqrDistance = a11 + 2.0*b1 + c;
      } else {
        denom = a00 - 2.0*a01 + a11;
        if (numer >= denom) {
          s = 1;
          t = 0;
          sqrDistance = a00 + 2.0*b0 + c;
        } else {
          s = numer/denom;
          t = 1 - s;
          sqrDistance = s*(a00*s + a01*t + 2.0*b0) +
          t*(a01*s + a11*t + 2.0*b1) + c;
        }
      }
    }
  }
  var u = 1.0 - s - t;
  for(var i=0; i<point.length; ++i) {
    result[i] = u * V0[i] + s * V1[i] + t * V2[i];
  }
  if(sqrDistance < 0) {
    return 0;
  }
  return sqrDistance;
}

module.exports = closestPoint2d;

},{}],468:[function(_dereq_,module,exports){
// shim for using process in browser
var process = module.exports = {};

// cached from whatever global is present so that test runners that stub it
// don't break things.  But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals.  It's inside a
// function because try/catches deoptimize in certain engines.

var cachedSetTimeout;
var cachedClearTimeout;

function defaultSetTimout() {
    throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
    throw new Error('clearTimeout has not been defined');
}
(function () {
    try {
        if (typeof setTimeout === 'function') {
            cachedSetTimeout = setTimeout;
        } else {
            cachedSetTimeout = defaultSetTimout;
        }
    } catch (e) {
        cachedSetTimeout = defaultSetTimout;
    }
    try {
        if (typeof clearTimeout === 'function') {
            cachedClearTimeout = clearTimeout;
        } else {
            cachedClearTimeout = defaultClearTimeout;
        }
    } catch (e) {
        cachedClearTimeout = defaultClearTimeout;
    }
} ())
function runTimeout(fun) {
    if (cachedSetTimeout === setTimeout) {
        //normal enviroments in sane situations
        return setTimeout(fun, 0);
    }
    // if setTimeout wasn't available but was latter defined
    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
        cachedSetTimeout = setTimeout;
        return setTimeout(fun, 0);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedSetTimeout(fun, 0);
    } catch(e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
            return cachedSetTimeout.call(null, fun, 0);
        } catch(e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
            return cachedSetTimeout.call(this, fun, 0);
        }
    }


}
function runClearTimeout(marker) {
    if (cachedClearTimeout === clearTimeout) {
        //normal enviroments in sane situations
        return clearTimeout(marker);
    }
    // if clearTimeout wasn't available but was latter defined
    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
        cachedClearTimeout = clearTimeout;
        return clearTimeout(marker);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedClearTimeout(marker);
    } catch (e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
            return cachedClearTimeout.call(null, marker);
        } catch (e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
            // Some versions of I.E. have different rules for clearTimeout vs setTimeout
            return cachedClearTimeout.call(this, marker);
        }
    }



}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;

function cleanUpNextTick() {
    if (!draining || !currentQueue) {
        return;
    }
    draining = false;
    if (currentQueue.length) {
        queue = currentQueue.concat(queue);
    } else {
        queueIndex = -1;
    }
    if (queue.length) {
        drainQueue();
    }
}

function drainQueue() {
    if (draining) {
        return;
    }
    var timeout = runTimeout(cleanUpNextTick);
    draining = true;

    var len = queue.length;
    while(len) {
        currentQueue = queue;
        queue = [];
        while (++queueIndex < len) {
            if (currentQueue) {
                currentQueue[queueIndex].run();
            }
        }
        queueIndex = -1;
        len = queue.length;
    }
    currentQueue = null;
    draining = false;
    runClearTimeout(timeout);
}

process.nextTick = function (fun) {
    var args = new Array(arguments.length - 1);
    if (arguments.length > 1) {
        for (var i = 1; i < arguments.length; i++) {
            args[i - 1] = arguments[i];
        }
    }
    queue.push(new Item(fun, args));
    if (queue.length === 1 && !draining) {
        runTimeout(drainQueue);
    }
};

// v8 likes predictible objects
function Item(fun, array) {
    this.fun = fun;
    this.array = array;
}
Item.prototype.run = function () {
    this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};

function noop() {}

process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;

process.listeners = function (name) { return [] }

process.binding = function (name) {
    throw new Error('process.binding is not supported');
};

process.cwd = function () { return '/' };
process.chdir = function (dir) {
    throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };

},{}],469:[function(_dereq_,module,exports){
module.exports = _dereq_('gl-quat/slerp')
},{"gl-quat/slerp":282}],470:[function(_dereq_,module,exports){
(function (global){
var now = _dereq_('performance-now')
  , root = typeof window === 'undefined' ? global : window
  , vendors = ['moz', 'webkit']
  , suffix = 'AnimationFrame'
  , raf = root['request' + suffix]
  , caf = root['cancel' + suffix] || root['cancelRequest' + suffix]

for(var i = 0; !raf && i < vendors.length; i++) {
  raf = root[vendors[i] + 'Request' + suffix]
  caf = root[vendors[i] + 'Cancel' + suffix]
      || root[vendors[i] + 'CancelRequest' + suffix]
}

// Some versions of FF have rAF but not cAF
if(!raf || !caf) {
  var last = 0
    , id = 0
    , queue = []
    , frameDuration = 1000 / 60

  raf = function(callback) {
    if(queue.length === 0) {
      var _now = now()
        , next = Math.max(0, frameDuration - (_now - last))
      last = next + _now
      setTimeout(function() {
        var cp = queue.slice(0)
        // Clear queue here to prevent
        // callbacks from appending listeners
        // to the current frame's queue
        queue.length = 0
        for(var i = 0; i < cp.length; i++) {
          if(!cp[i].cancelled) {
            try{
              cp[i].callback(last)
            } catch(e) {
              setTimeout(function() { throw e }, 0)
            }
          }
        }
      }, Math.round(next))
    }
    queue.push({
      handle: ++id,
      callback: callback,
      cancelled: false
    })
    return id
  }

  caf = function(handle) {
    for(var i = 0; i < queue.length; i++) {
      if(queue[i].handle === handle) {
        queue[i].cancelled = true
      }
    }
  }
}

module.exports = function(fn) {
  // Wrap in a new function to prevent
  // `cancel` potentially being assigned
  // to the native rAF function
  return raf.call(root, fn)
}
module.exports.cancel = function() {
  caf.apply(root, arguments)
}
module.exports.polyfill = function(object) {
  if (!object) {
    object = root;
  }
  object.requestAnimationFrame = raf
  object.cancelAnimationFrame = caf
}

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"performance-now":448}],471:[function(_dereq_,module,exports){
'use strict'

var bnadd = _dereq_('big-rat/add')

module.exports = add

function add (a, b) {
  var n = a.length
  var r = new Array(n)
  for (var i=0; i<n; ++i) {
    r[i] = bnadd(a[i], b[i])
  }
  return r
}

},{"big-rat/add":64}],472:[function(_dereq_,module,exports){
'use strict'

module.exports = float2rat

var rat = _dereq_('big-rat')

function float2rat(v) {
  var result = new Array(v.length)
  for(var i=0; i<v.length; ++i) {
    result[i] = rat(v[i])
  }
  return result
}

},{"big-rat":67}],473:[function(_dereq_,module,exports){
'use strict'

var rat = _dereq_('big-rat')
var mul = _dereq_('big-rat/mul')

module.exports = muls

function muls(a, x) {
  var s = rat(x)
  var n = a.length
  var r = new Array(n)
  for(var i=0; i<n; ++i) {
    r[i] = mul(a[i], s)
  }
  return r
}

},{"big-rat":67,"big-rat/mul":76}],474:[function(_dereq_,module,exports){
'use strict'

var bnsub = _dereq_('big-rat/sub')

module.exports = sub

function sub(a, b) {
  var n = a.length
  var r = new Array(n)
    for(var i=0; i<n; ++i) {
    r[i] = bnsub(a[i], b[i])
  }
  return r
}

},{"big-rat/sub":78}],475:[function(_dereq_,module,exports){
'use strict'

var compareCell = _dereq_('compare-cell')
var compareOrientedCell = _dereq_('compare-oriented-cell')
var orientation = _dereq_('cell-orientation')

module.exports = reduceCellComplex

function reduceCellComplex(cells) {
  cells.sort(compareOrientedCell)
  var n = cells.length
  var ptr = 0
  for(var i=0; i<n; ++i) {
    var c = cells[i]
    var o = orientation(c)
    if(o === 0) {
      continue
    }
    if(ptr > 0) {
      var f = cells[ptr-1]
      if(compareCell(c, f) === 0 &&
         orientation(f)    !== o) {
        ptr -= 1
        continue
      }
    }
    cells[ptr++] = c
  }
  cells.length = ptr
  return cells
}

},{"cell-orientation":101,"compare-cell":117,"compare-oriented-cell":118}],476:[function(_dereq_,module,exports){
'use strict'

var getBounds = _dereq_('array-bounds')
var rgba = _dereq_('color-normalize')
var updateDiff = _dereq_('update-diff')
var pick = _dereq_('pick-by-alias')
var extend = _dereq_('object-assign')
var flatten = _dereq_('flatten-vertex-data')
var ref = _dereq_('to-float32');
var float32 = ref.float32;
var fract32 = ref.fract32;

module.exports = Error2D

var WEIGHTS = [
	//direction, lineWidth shift, capSize shift

	// x-error bar
	[1, 0, 0, 1, 0, 0],
	[1, 0, 0, -1, 0, 0],
	[-1, 0, 0, -1, 0, 0],

	[-1, 0, 0, -1, 0, 0],
	[-1, 0, 0, 1, 0, 0],
	[1, 0, 0, 1, 0, 0],

	// x-error right cap
	[1, 0, -1, 0, 0, 1],
	[1, 0, -1, 0, 0, -1],
	[1, 0, 1, 0, 0, -1],

	[1, 0, 1, 0, 0, -1],
	[1, 0, 1, 0, 0, 1],
	[1, 0, -1, 0, 0, 1],

	// x-error left cap
	[-1, 0, -1, 0, 0, 1],
	[-1, 0, -1, 0, 0, -1],
	[-1, 0, 1, 0, 0, -1],

	[-1, 0, 1, 0, 0, -1],
	[-1, 0, 1, 0, 0, 1],
	[-1, 0, -1, 0, 0, 1],

	// y-error bar
	[0, 1, 1, 0, 0, 0],
	[0, 1, -1, 0, 0, 0],
	[0, -1, -1, 0, 0, 0],

	[0, -1, -1, 0, 0, 0],
	[0, 1, 1, 0, 0, 0],
	[0, -1, 1, 0, 0, 0],

	// y-error top cap
	[0, 1, 0, -1, 1, 0],
	[0, 1, 0, -1, -1, 0],
	[0, 1, 0, 1, -1, 0],

	[0, 1, 0, 1, 1, 0],
	[0, 1, 0, -1, 1, 0],
	[0, 1, 0, 1, -1, 0],

	// y-error bottom cap
	[0, -1, 0, -1, 1, 0],
	[0, -1, 0, -1, -1, 0],
	[0, -1, 0, 1, -1, 0],

	[0, -1, 0, 1, 1, 0],
	[0, -1, 0, -1, 1, 0],
	[0, -1, 0, 1, -1, 0]
]


function Error2D (regl, options) {
	if (typeof regl === 'function') {
		if (!options) { options = {} }
		options.regl = regl
	}
	else {
		options = regl
	}
	if (options.length) { options.positions = options }
	regl = options.regl

	if (!regl.hasExtension('ANGLE_instanced_arrays')) {
		throw Error('regl-error2d: `ANGLE_instanced_arrays` extension should be enabled');
	}

	// persistent variables
	var gl = regl._gl, drawErrors, positionBuffer, positionFractBuffer, colorBuffer, errorBuffer, meshBuffer,
			defaults = {
				color: 'black',
				capSize: 5,
				lineWidth: 1,
				opacity: 1,
				viewport: null,
				range: null,
				offset: 0,
				count: 0,
				bounds: null,
				positions: [],
				errors: []
			}, groups = []

	//color per-point
	colorBuffer = regl.buffer({
		usage: 'dynamic',
		type: 'uint8',
		data: new Uint8Array(0)
	})
	//xy-position per-point
	positionBuffer = regl.buffer({
		usage: 'dynamic',
		type: 'float',
		data: new Uint8Array(0)
	})
	//xy-position float32-fraction
	positionFractBuffer = regl.buffer({
		usage: 'dynamic',
		type: 'float',
		data: new Uint8Array(0)
	})
	//4 errors per-point
	errorBuffer = regl.buffer({
		usage: 'dynamic',
		type: 'float',
		data: new Uint8Array(0)
	})
	//error bar mesh
	meshBuffer = regl.buffer({
		usage: 'static',
		type: 'float',
		data: WEIGHTS
	})

	update(options)

	//drawing method
	drawErrors = regl({
		vert: "\n\t\tprecision highp float;\n\n\t\tattribute vec2 position, positionFract;\n\t\tattribute vec4 error;\n\t\tattribute vec4 color;\n\n\t\tattribute vec2 direction, lineOffset, capOffset;\n\n\t\tuniform vec4 viewport;\n\t\tuniform float lineWidth, capSize;\n\t\tuniform vec2 scale, scaleFract, translate, translateFract;\n\n\t\tvarying vec4 fragColor;\n\n\t\tvoid main() {\n\t\t\tfragColor = color / 255.;\n\n\t\t\tvec2 pixelOffset = lineWidth * lineOffset + (capSize + lineWidth) * capOffset;\n\n\t\t\tvec2 dxy = -step(.5, direction.xy) * error.xz + step(direction.xy, vec2(-.5)) * error.yw;\n\n\t\t\tvec2 position = position + dxy;\n\n\t\t\tvec2 pos = (position + translate) * scale\n\t\t\t\t+ (positionFract + translateFract) * scale\n\t\t\t\t+ (position + translate) * scaleFract\n\t\t\t\t+ (positionFract + translateFract) * scaleFract;\n\n\t\t\tpos += pixelOffset / viewport.zw;\n\n\t\t\tgl_Position = vec4(pos * 2. - 1., 0, 1);\n\t\t}\n\t\t",

		frag: "\n\t\tprecision mediump float;\n\n\t\tvarying vec4 fragColor;\n\n\t\tuniform float opacity;\n\n\t\tvoid main() {\n\t\t\tgl_FragColor = fragColor;\n\t\t\tgl_FragColor.a *= opacity;\n\t\t}\n\t\t",

		uniforms: {
			range: regl.prop('range'),
			lineWidth: regl.prop('lineWidth'),
			capSize: regl.prop('capSize'),
			opacity: regl.prop('opacity'),
			scale: regl.prop('scale'),
			translate: regl.prop('translate'),
			scaleFract: regl.prop('scaleFract'),
			translateFract: regl.prop('translateFract'),
			viewport: function (ctx, prop) { return [prop.viewport.x, prop.viewport.y, ctx.viewportWidth, ctx.viewportHeight]; }
		},

		attributes: {
			//dynamic attributes
			color: {
				buffer: colorBuffer,
				offset: function (ctx, prop) { return prop.offset * 4; },
				divisor: 1,
			},
			position: {
				buffer: positionBuffer,
				offset: function (ctx, prop) { return prop.offset * 8; },
				divisor: 1
			},
			positionFract: {
				buffer: positionFractBuffer,
				offset: function (ctx, prop) { return prop.offset * 8; },
				divisor: 1
			},
			error: {
				buffer: errorBuffer,
				offset: function (ctx, prop) { return prop.offset * 16; },
				divisor: 1
			},

			//static attributes
			direction: {
				buffer: meshBuffer,
				stride: 24,
				offset: 0
			},
			lineOffset: {
				buffer: meshBuffer,
				stride: 24,
				offset: 8
			},
			capOffset: {
				buffer: meshBuffer,
				stride: 24,
				offset: 16
			}
		},

		primitive: 'triangles',

		blend: {
			enable: true,
			color: [0,0,0,0],
			equation: {
				rgb: 'add',
				alpha: 'add'
			},
			func: {
				srcRGB: 'src alpha',
				dstRGB: 'one minus src alpha',
				srcAlpha: 'one minus dst alpha',
				dstAlpha: 'one'
			}
		},

		depth: {
			enable: false
		},

		scissor: {
			enable: true,
			box: regl.prop('viewport')
		},
		viewport: regl.prop('viewport'),
		stencil: false,

		instances: regl.prop('count'),
		count: WEIGHTS.length
	})

	//expose API
	extend(error2d, {
		update: update,
		draw: draw,
		destroy: destroy,
		regl: regl,
		gl: gl,
		canvas: gl.canvas,
		groups: groups
	})

	return error2d

	function error2d (opts) {
		//update
		if (opts) {
			update(opts)
		}

		//destroy
		else if (opts === null) {
			destroy()
		}

		draw()
	}


	//main draw method
	function draw (options) {
		if (typeof options === 'number') { return drawGroup(options) }

		//make options a batch
		if (options && !Array.isArray(options)) { options = [options] }


		regl._refresh()

		//render multiple polylines via regl batch
		groups.forEach(function (s, i) {
			if (!s) { return }

			if (options) {
				if (!options[i]) { s.draw = false }
				else { s.draw = true }
			}

			//ignore draw flag for one pass
			if (!s.draw) {
				s.draw = true;
				return
			}

			drawGroup(i)
		})
	}

	//draw single error group by id
	function drawGroup (s) {
		if (typeof s === 'number') { s = groups[s] }
		if (s == null) { return }

		if (!(s && s.count && s.color && s.opacity && s.positions && s.positions.length > 1)) { return }

		s.scaleRatio = [
			s.scale[0] * s.viewport.width,
			s.scale[1] * s.viewport.height
		]

		drawErrors(s)

		if (s.after) { s.after(s) }
	}

	function update (options) {
		if (!options) { return }

		//direct points argument
		if (options.length != null) {
			if (typeof options[0] === 'number') { options = [{positions: options}] }
		}

		//make options a batch
		else if (!Array.isArray(options)) { options = [options] }

		//global count of points
		var pointCount = 0, errorCount = 0

		error2d.groups = groups = options.map(function (options, i) {
			var group = groups[i]

			if (!options) { return group }
			else if (typeof options === 'function') { options = {after: options} }
			else if (typeof options[0] === 'number') { options = {positions: options} }

			//copy options to avoid mutation & handle aliases
			options = pick(options, {
				color: 'color colors fill',
				capSize: 'capSize cap capsize cap-size',
				lineWidth: 'lineWidth line-width width line thickness',
				opacity: 'opacity alpha',
				range: 'range dataBox',
				viewport: 'viewport viewBox',
				errors: 'errors error',
				positions: 'positions position data points'
			})

			if (!group) {
				groups[i] = group = {
					id: i,
					scale: null,
					translate: null,
					scaleFract: null,
					translateFract: null,
					draw: true
				}
				options = extend({}, defaults, options)
			}

			updateDiff(group, options, [{
				lineWidth: function (v) { return +v * .5; },
				capSize: function (v) { return +v * .5; },
				opacity: parseFloat,
				errors: function (errors) {
					errors = flatten(errors)

					errorCount += errors.length
					return errors
				},
				positions: function (positions, state) {
					positions = flatten(positions, 'float64')
					state.count = Math.floor(positions.length / 2)
					state.bounds = getBounds(positions, 2)
					state.offset = pointCount

					pointCount += state.count

					return positions
				}
			}, {
				color: function (colors, state) {
					var count = state.count

					if (!colors) { colors = 'transparent' }

					// 'black' or [0,0,0,0] case
					if (!Array.isArray(colors) || typeof colors[0] === 'number') {
						var color = colors
						colors = Array(count)
						for (var i = 0; i < count; i++) {
							colors[i] = color
						}
					}

					if (colors.length < count) { throw Error('Not enough colors') }

					var colorData = new Uint8Array(count * 4)

					//convert colors to float arrays
					for (var i$1 = 0; i$1 < count; i$1++) {
						var c = rgba(colors[i$1], 'uint8')
						colorData.set(c, i$1 * 4)
					}

					return colorData
				},

				range: function (range, state, options) {
					var bounds = state.bounds
					if (!range) { range = bounds }

					state.scale = [1 / (range[2] - range[0]), 1 / (range[3] - range[1])]
					state.translate = [-range[0], -range[1]]

					state.scaleFract = fract32(state.scale)
					state.translateFract = fract32(state.translate)

					return range
				},

				viewport: function (vp) {
					var viewport

					if (Array.isArray(vp)) {
						viewport = {
							x: vp[0],
							y: vp[1],
							width: vp[2] - vp[0],
							height: vp[3] - vp[1]
						}
					}
					else if (vp) {
						viewport = {
							x: vp.x || vp.left || 0,
							y: vp.y || vp.top || 0
						}

						if (vp.right) { viewport.width = vp.right - viewport.x }
						else { viewport.width = vp.w || vp.width || 0 }

						if (vp.bottom) { viewport.height = vp.bottom - viewport.y }
						else { viewport.height = vp.h || vp.height || 0 }
					}
					else {
						viewport = {
							x: 0, y: 0,
							width: gl.drawingBufferWidth,
							height: gl.drawingBufferHeight
						}
					}

					return viewport
				}
			}])

			return group
		})

		if (pointCount || errorCount) {
			var len = groups.reduce(function (acc, group, i) {
				return acc + (group ? group.count : 0)
			}, 0)

			var positionData = new Float64Array(len * 2)
			var colorData = new Uint8Array(len * 4)
			var errorData = new Float32Array(len * 4)

			groups.forEach(function (group, i) {
				if (!group) { return }
				var positions = group.positions;
				var count = group.count;
				var offset = group.offset;
				var color = group.color;
				var errors = group.errors;
				if (!count) { return }

				colorData.set(color, offset * 4)
				errorData.set(errors, offset * 4)
				positionData.set(positions, offset * 2)
			})

			positionBuffer(float32(positionData))
			positionFractBuffer(fract32(positionData))
			colorBuffer(colorData)
			errorBuffer(errorData)
		}

	}

	function destroy () {
		positionBuffer.destroy()
		positionFractBuffer.destroy()
		colorBuffer.destroy()
		errorBuffer.destroy()
		meshBuffer.destroy()
	}
}

},{"array-bounds":54,"color-normalize":109,"flatten-vertex-data":217,"object-assign":440,"pick-by-alias":451,"to-float32":516,"update-diff":527}],477:[function(_dereq_,module,exports){
'use strict'


var rgba = _dereq_('color-normalize')
var getBounds = _dereq_('array-bounds')
var extend = _dereq_('object-assign')
var glslify = _dereq_('glslify')
var pick = _dereq_('pick-by-alias')
var flatten = _dereq_('flatten-vertex-data')
var triangulate = _dereq_('earcut')
var normalize = _dereq_('array-normalize')
var ref = _dereq_('to-float32');
var float32 = ref.float32;
var fract32 = ref.fract32;
var WeakMap = _dereq_('es6-weak-map')
var parseRect = _dereq_('parse-rect')


module.exports = Line2D


/** @constructor */
function Line2D (regl, options) {
	if (!(this instanceof Line2D)) { return new Line2D(regl, options) }

	if (typeof regl === 'function') {
		if (!options) { options = {} }
		options.regl = regl
	}
	else {
		options = regl
	}
	if (options.length) { options.positions = options }
	regl = options.regl

	if (!regl.hasExtension('ANGLE_instanced_arrays')) {
		throw Error('regl-error2d: `ANGLE_instanced_arrays` extension should be enabled');
	}

	// persistent variables
	this.gl = regl._gl
	this.regl = regl

	// list of options for lines
	this.passes = []

	// cached shaders instance
	this.shaders = Line2D.shaders.has(regl) ? Line2D.shaders.get(regl) : Line2D.shaders.set(regl, Line2D.createShaders(regl)).get(regl)


	// init defaults
	this.update(options)
}


Line2D.dashMult = 2
Line2D.maxPatternLength = 256
Line2D.precisionThreshold = 3e6
Line2D.maxPoints = 1e4
Line2D.maxLines = 2048


// cache of created draw calls per-regl instance
Line2D.shaders = new WeakMap()


// create static shaders once
Line2D.createShaders = function (regl) {
	var offsetBuffer = regl.buffer({
		usage: 'static',
		type: 'float',
		data: [0,1, 0,0, 1,1, 1,0]
	})

	var shaderOptions = {
		primitive: 'triangle strip',
		instances: regl.prop('count'),
		count: 4,
		offset: 0,

		uniforms: {
			miterMode: function (ctx, prop) { return prop.join === 'round' ? 2 : 1; },
			miterLimit: regl.prop('miterLimit'),
			scale: regl.prop('scale'),
			scaleFract: regl.prop('scaleFract'),
			translateFract: regl.prop('translateFract'),
			translate: regl.prop('translate'),
			thickness: regl.prop('thickness'),
			dashPattern: regl.prop('dashTexture'),
			opacity: regl.prop('opacity'),
			pixelRatio: regl.context('pixelRatio'),
			id: regl.prop('id'),
			dashSize: regl.prop('dashLength'),
			viewport: function (c, p) { return [p.viewport.x, p.viewport.y, c.viewportWidth, c.viewportHeight]; },
			depth: regl.prop('depth')
		},

		blend: {
			enable: true,
			color: [0,0,0,0],
			equation: {
				rgb: 'add',
				alpha: 'add'
			},
			func: {
				srcRGB: 'src alpha',
				dstRGB: 'one minus src alpha',
				srcAlpha: 'one minus dst alpha',
				dstAlpha: 'one'
			}
		},
		depth: {
			enable: function (c, p) {
				return !p.overlay
			}
		},
		stencil: {enable: false},
		scissor: {
			enable: true,
			box: regl.prop('viewport')
		},
		viewport: regl.prop('viewport')
	}


	// simplified rectangular line shader
	var drawRectLine = regl(extend({
		vert: glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, aCoordFract, bCoordFract;\nattribute vec4 color;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float thickness, pixelRatio, id, depth;\nuniform vec4 viewport;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nvec2 project(vec2 position, vec2 positionFract, vec2 scale, vec2 scaleFract, vec2 translate, vec2 translateFract) {\n\t// the order is important\n\treturn position * scale + translate\n       + positionFract * scale + translateFract\n       + position * scaleFract\n       + positionFract * scaleFract;\n}\n\nvoid main() {\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineOffset = lineTop * 2. - 1.;\n\n\tvec2 diff = (bCoord + bCoordFract - aCoord - aCoordFract);\n\ttangent = normalize(diff * scale * viewport.zw);\n\tvec2 normal = vec2(-tangent.y, tangent.x);\n\n\tvec2 position = project(aCoord, aCoordFract, scale, scaleFract, translate, translateFract) * lineStart\n\t\t+ project(bCoord, bCoordFract, scale, scaleFract, translate, translateFract) * lineEnd\n\n\t\t+ thickness * normal * .5 * lineOffset / viewport.zw;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n}\n"]),
		frag: glslify(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\n\nuniform float dashSize, pixelRatio, thickness, opacity, id;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nvoid main() {\n\tfloat alpha = 1.;\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashSize) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t, .5)).r;\n\n\tgl_FragColor = fragColor;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]),

		attributes: {
			// if point is at the end of segment
			lineEnd: {
				buffer: offsetBuffer,
				divisor: 0,
				stride: 8,
				offset: 0
			},
			// if point is at the top of segment
			lineTop: {
				buffer: offsetBuffer,
				divisor: 0,
				stride: 8,
				offset: 4
			},
			// beginning of line coordinate
			aCoord: {
				buffer: regl.prop('positionBuffer'),
				stride: 8,
				offset: 8,
				divisor: 1
			},
			// end of line coordinate
			bCoord: {
				buffer: regl.prop('positionBuffer'),
				stride: 8,
				offset: 16,
				divisor: 1
			},
			aCoordFract: {
				buffer: regl.prop('positionFractBuffer'),
				stride: 8,
				offset: 8,
				divisor: 1
			},
			bCoordFract: {
				buffer: regl.prop('positionFractBuffer'),
				stride: 8,
				offset: 16,
				divisor: 1
			},
			color: {
				buffer: regl.prop('colorBuffer'),
				stride: 4,
				offset: 0,
				divisor: 1
			}
		}
	}, shaderOptions))

	// create regl draw
	var drawMiterLine

	try {
		drawMiterLine = regl(extend({
			// culling removes polygon creasing
			cull: {
				enable: true,
				face: 'back'
			},

			vert: glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, nextCoord, prevCoord;\nattribute vec4 aColor, bColor;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, translate;\nuniform float thickness, pixelRatio, id, depth;\nuniform vec4 viewport;\nuniform float miterLimit, miterMode;\n\nvarying vec4 fragColor;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 tangent;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nconst float REVERSE_THRESHOLD = -.875;\nconst float MIN_DIFF = 1e-6;\n\n// TODO: possible optimizations: avoid overcalculating all for vertices and calc just one instead\n// TODO: precalculate dot products, normalize things beforehead etc.\n// TODO: refactor to rectangular algorithm\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nbool isNaN( float val ){\n  return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true;\n}\n\nvoid main() {\n\tvec2 aCoord = aCoord, bCoord = bCoord, prevCoord = prevCoord, nextCoord = nextCoord;\n\n  vec2 adjustedScale;\n  adjustedScale.x = (abs(scale.x) < MIN_DIFF) ? MIN_DIFF : scale.x;\n  adjustedScale.y = (abs(scale.y) < MIN_DIFF) ? MIN_DIFF : scale.y;\n\n  vec2 scaleRatio = adjustedScale * viewport.zw;\n\tvec2 normalWidth = thickness / scaleRatio;\n\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineBot = 1. - lineTop;\n\n\tfragColor = (lineStart * aColor + lineEnd * bColor) / 255.;\n\n\tif (isNaN(aCoord.x) || isNaN(aCoord.y) || isNaN(bCoord.x) || isNaN(bCoord.y)) return;\n\n\tif (aCoord == prevCoord) prevCoord = aCoord + normalize(bCoord - aCoord);\n\tif (bCoord == nextCoord) nextCoord = bCoord - normalize(bCoord - aCoord);\n\n\tvec2 prevDiff = aCoord - prevCoord;\n\tvec2 currDiff = bCoord - aCoord;\n\tvec2 nextDiff = nextCoord - bCoord;\n\n\tvec2 prevTangent = normalize(prevDiff * scaleRatio);\n\tvec2 currTangent = normalize(currDiff * scaleRatio);\n\tvec2 nextTangent = normalize(nextDiff * scaleRatio);\n\n\tvec2 prevNormal = vec2(-prevTangent.y, prevTangent.x);\n\tvec2 currNormal = vec2(-currTangent.y, currTangent.x);\n\tvec2 nextNormal = vec2(-nextTangent.y, nextTangent.x);\n\n\tvec2 startJoinDirection = normalize(prevTangent - currTangent);\n\tvec2 endJoinDirection = normalize(currTangent - nextTangent);\n\n\t// collapsed/unidirectional segment cases\n\t// FIXME: there should be more elegant solution\n\tvec2 prevTanDiff = abs(prevTangent - currTangent);\n\tvec2 nextTanDiff = abs(nextTangent - currTangent);\n\tif (max(prevTanDiff.x, prevTanDiff.y) < MIN_DIFF) {\n\t\tstartJoinDirection = currNormal;\n\t}\n\tif (max(nextTanDiff.x, nextTanDiff.y) < MIN_DIFF) {\n\t\tendJoinDirection = currNormal;\n\t}\n\tif (aCoord == bCoord) {\n\t\tendJoinDirection = startJoinDirection;\n\t\tcurrNormal = prevNormal;\n\t\tcurrTangent = prevTangent;\n\t}\n\n\ttangent = currTangent;\n\n\t//calculate join shifts relative to normals\n\tfloat startJoinShift = dot(currNormal, startJoinDirection);\n\tfloat endJoinShift = dot(currNormal, endJoinDirection);\n\n\tfloat startMiterRatio = abs(1. / startJoinShift);\n\tfloat endMiterRatio = abs(1. / endJoinShift);\n\n\tvec2 startJoin = startJoinDirection * startMiterRatio;\n\tvec2 endJoin = endJoinDirection * endMiterRatio;\n\n\tvec2 startTopJoin, startBotJoin, endTopJoin, endBotJoin;\n\tstartTopJoin = sign(startJoinShift) * startJoin * .5;\n\tstartBotJoin = -startTopJoin;\n\n\tendTopJoin = sign(endJoinShift) * endJoin * .5;\n\tendBotJoin = -endTopJoin;\n\n\tvec2 aTopCoord = aCoord + normalWidth * startTopJoin;\n\tvec2 bTopCoord = bCoord + normalWidth * endTopJoin;\n\tvec2 aBotCoord = aCoord + normalWidth * startBotJoin;\n\tvec2 bBotCoord = bCoord + normalWidth * endBotJoin;\n\n\t//miter anti-clipping\n\tfloat baClipping = distToLine(bCoord, aCoord, aBotCoord) / dot(normalize(normalWidth * endBotJoin), normalize(normalWidth.yx * vec2(-startBotJoin.y, startBotJoin.x)));\n\tfloat abClipping = distToLine(aCoord, bCoord, bTopCoord) / dot(normalize(normalWidth * startBotJoin), normalize(normalWidth.yx * vec2(-endBotJoin.y, endBotJoin.x)));\n\n\t//prevent close to reverse direction switch\n\tbool prevReverse = dot(currTangent, prevTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, prevNormal)) * min(length(prevDiff), length(currDiff)) <  length(normalWidth * currNormal);\n\tbool nextReverse = dot(currTangent, nextTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, nextNormal)) * min(length(nextDiff), length(currDiff)) <  length(normalWidth * currNormal);\n\n\tif (prevReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * startJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / startMiterRatio, 1.);\n\t\taBotCoord = aCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\taTopCoord = aCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!nextReverse && baClipping > 0. && baClipping < length(normalWidth * endBotJoin)) {\n\t\t//handle miter clipping\n\t\tbTopCoord -= normalWidth * endTopJoin;\n\t\tbTopCoord += normalize(endTopJoin * normalWidth) * baClipping;\n\t}\n\n\tif (nextReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * endJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / endMiterRatio, 1.);\n\t\tbBotCoord = bCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\tbTopCoord = bCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!prevReverse && abClipping > 0. && abClipping < length(normalWidth * startBotJoin)) {\n\t\t//handle miter clipping\n\t\taBotCoord -= normalWidth * startBotJoin;\n\t\taBotCoord += normalize(startBotJoin * normalWidth) * abClipping;\n\t}\n\n\tvec2 aTopPosition = (aTopCoord) * adjustedScale + translate;\n\tvec2 aBotPosition = (aBotCoord) * adjustedScale + translate;\n\n\tvec2 bTopPosition = (bTopCoord) * adjustedScale + translate;\n\tvec2 bBotPosition = (bBotCoord) * adjustedScale + translate;\n\n\t//position is normalized 0..1 coord on the screen\n\tvec2 position = (aTopPosition * lineTop + aBotPosition * lineBot) * lineStart + (bTopPosition * lineTop + bBotPosition * lineBot) * lineEnd;\n\n\tstartCoord = aCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\tendCoord = bCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\n\tgl_Position = vec4(position  * 2.0 - 1.0, depth, 1);\n\n\tenableStartMiter = step(dot(currTangent, prevTangent), .5);\n\tenableEndMiter = step(dot(currTangent, nextTangent), .5);\n\n\t//bevel miter cutoffs\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * miterLimit * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * miterLimit * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x)  / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n\n\t//round miter cutoffs\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * abs(dot(startJoinDirection, currNormal)) * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * abs(dot(endJoinDirection, currNormal)) * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x)  / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n}\n"]),
			frag: glslify(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\nuniform float dashSize, pixelRatio, thickness, opacity, id, miterMode;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nvoid main() {\n\tfloat alpha = 1., distToStart, distToEnd;\n\tfloat cutoff = thickness * .5;\n\n\t//bevel miter\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToStart + 1., 0.), 1.);\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToEnd + 1., 0.), 1.);\n\t\t}\n\t}\n\n\t// round miter\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - startCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - endCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\t}\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashSize) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t, .5)).r;\n\n\tgl_FragColor = fragColor;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]),

			attributes: {
				// is line end
				lineEnd: {
					buffer: offsetBuffer,
					divisor: 0,
					stride: 8,
					offset: 0
				},
				// is line top
				lineTop: {
					buffer: offsetBuffer,
					divisor: 0,
					stride: 8,
					offset: 4
				},
				// left color
				aColor: {
					buffer: regl.prop('colorBuffer'),
					stride: 4,
					offset: 0,
					divisor: 1
				},
				// right color
				bColor: {
					buffer: regl.prop('colorBuffer'),
					stride: 4,
					offset: 4,
					divisor: 1
				},
				prevCoord: {
					buffer: regl.prop('positionBuffer'),
					stride: 8,
					offset: 0,
					divisor: 1
				},
				aCoord: {
					buffer: regl.prop('positionBuffer'),
					stride: 8,
					offset: 8,
					divisor: 1
				},
				bCoord: {
					buffer: regl.prop('positionBuffer'),
					stride: 8,
					offset: 16,
					divisor: 1
				},
				nextCoord: {
					buffer: regl.prop('positionBuffer'),
					stride: 8,
					offset: 24,
					divisor: 1
				}
			}
		}, shaderOptions))
	} catch (e) {
		// IE/bad Webkit fallback
		drawMiterLine = drawRectLine
	}

	// fill shader
	var drawFill = regl({
		primitive: 'triangle',
		elements: function (ctx, prop) { return prop.triangles; },
		offset: 0,

		vert: glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\n\nuniform vec4 color;\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio, id;\nuniform vec4 viewport;\nuniform float opacity;\n\nvarying vec4 fragColor;\n\nconst float MAX_LINES = 256.;\n\nvoid main() {\n\tfloat depth = (MAX_LINES - 4. - id) / (MAX_LINES);\n\n\tvec2 position = position * scale + translate\n       + positionFract * scale + translateFract\n       + position * scaleFract\n       + positionFract * scaleFract;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n\tfragColor.a *= opacity;\n}\n"]),
		frag: glslify(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n\tgl_FragColor = fragColor;\n}\n"]),

		uniforms: {
			scale: regl.prop('scale'),
			color: regl.prop('fill'),
			scaleFract: regl.prop('scaleFract'),
			translateFract: regl.prop('translateFract'),
			translate: regl.prop('translate'),
			opacity: regl.prop('opacity'),
			pixelRatio: regl.context('pixelRatio'),
			id: regl.prop('id'),
			viewport: function (ctx, prop) { return [prop.viewport.x, prop.viewport.y, ctx.viewportWidth, ctx.viewportHeight]; }
		},

		attributes: {
			position: {
				buffer: regl.prop('positionBuffer'),
				stride: 8,
				offset: 8
			},
			positionFract: {
				buffer: regl.prop('positionFractBuffer'),
				stride: 8,
				offset: 8
			}
		},

		blend: shaderOptions.blend,

		depth: { enable: false },
		scissor: shaderOptions.scissor,
		stencil: shaderOptions.stencil,
		viewport: shaderOptions.viewport
	})

	return {
		fill: drawFill, rect: drawRectLine, miter: drawMiterLine
	}
}


// used to for new lines instances
Line2D.defaults = {
	dashes: null,
	join: 'miter',
	miterLimit: 1,
	thickness: 10,
	cap: 'square',
	color: 'black',
	opacity: 1,
	overlay: false,
	viewport: null,
	range: null,
	close: false,
	fill: null
}


Line2D.prototype.render = function () {
	var ref;

	var args = [], len = arguments.length;
	while ( len-- ) args[ len ] = arguments[ len ];
	if (args.length) {
		(ref = this).update.apply(ref, args)
	}

	this.draw()
}


Line2D.prototype.draw = function () {
	var this$1 = this;
	var args = [], len = arguments.length;
	while ( len-- ) args[ len ] = arguments[ len ];

	// render multiple polylines via regl batch
	(args.length ? args : this.passes).forEach(function (s, i) {
		var ref;

		// render array pass as a list of passes
		if (s && Array.isArray(s)) { return (ref = this$1).draw.apply(ref, s) }

		if (typeof s === 'number') { s = this$1.passes[s] }

		if (!(s && s.count > 1 && s.opacity)) { return }

		this$1.regl._refresh()

		if (s.fill && s.triangles && s.triangles.length > 2) {
			this$1.shaders.fill(s)
		}

		if (!s.thickness) { return }

		// high scale is only available for rect mode with precision
		if (s.scale[0] * s.viewport.width > Line2D.precisionThreshold || s.scale[1] * s.viewport.height > Line2D.precisionThreshold) {
			this$1.shaders.rect(s)
		}

		// thin this.passes or too many points are rendered as simplified rect shader
		else if (s.join === 'rect' || (!s.join && (s.thickness <= 2 || s.count >= Line2D.maxPoints))) {
			this$1.shaders.rect(s)
		}
		else {
			this$1.shaders.miter(s)
		}
	})

	return this
}

Line2D.prototype.update = function (options) {
	var this$1 = this;

	if (!options) { return }

	if (options.length != null) {
		if (typeof options[0] === 'number') { options = [{positions: options}] }
	}

	// make options a batch
	else if (!Array.isArray(options)) { options = [options] }

	var ref = this;
	var regl = ref.regl;
	var gl = ref.gl;

	// process per-line settings
	options.forEach(function (o, i) {
		var state = this$1.passes[i]

		if (o === undefined) { return }

		// null-argument removes pass
		if (o === null) {
			this$1.passes[i] = null
			return
		}

		if (typeof o[0] === 'number') { o = {positions: o} }

		// handle aliases
		o = pick(o, {
			positions: 'positions points data coords',
			thickness: 'thickness lineWidth lineWidths line-width linewidth width stroke-width strokewidth strokeWidth',
			join: 'lineJoin linejoin join type mode',
			miterLimit: 'miterlimit miterLimit',
			dashes: 'dash dashes dasharray dash-array dashArray',
			color: 'color colour stroke colors colours stroke-color strokeColor',
			fill: 'fill fill-color fillColor',
			opacity: 'alpha opacity',
			overlay: 'overlay crease overlap intersect',
			close: 'closed close closed-path closePath',
			range: 'range dataBox',
			viewport: 'viewport viewBox',
			hole: 'holes hole hollow'
		})

		// init state
		if (!state) {
			this$1.passes[i] = state = {
				id: i,
				scale: null,
				scaleFract: null,
				translate: null,
				translateFract: null,
				count: 0,
				hole: [],
				depth: 0,

				dashLength: 1,
				dashTexture: regl.texture({
					channels: 1,
					data: new Uint8Array([255]),
					width: 1,
					height: 1,
					mag: 'linear',
					min: 'linear'
				}),

				colorBuffer: regl.buffer({
					usage: 'dynamic',
					type: 'uint8',
					data: new Uint8Array()
				}),
				positionBuffer: regl.buffer({
					usage: 'dynamic',
					type: 'float',
					data: new Uint8Array()
				}),
				positionFractBuffer: regl.buffer({
					usage: 'dynamic',
					type: 'float',
					data: new Uint8Array()
				})
			}

			o = extend({}, Line2D.defaults, o)
		}
		if (o.thickness != null) { state.thickness = parseFloat(o.thickness) }
		if (o.opacity != null) { state.opacity = parseFloat(o.opacity) }
		if (o.miterLimit != null) { state.miterLimit = parseFloat(o.miterLimit) }
		if (o.overlay != null) {
			state.overlay = !!o.overlay
			if (i < Line2D.maxLines) {
				state.depth = 2 * (Line2D.maxLines - 1 - i % Line2D.maxLines) / Line2D.maxLines - 1.;
			}
		}
		if (o.join != null) { state.join = o.join }
		if (o.hole != null) { state.hole = o.hole }
		if (o.fill != null) { state.fill = !o.fill ? null : rgba(o.fill, 'uint8') }
		if (o.viewport != null) { state.viewport = parseRect(o.viewport) }

		if (!state.viewport) {
			state.viewport = parseRect([
				gl.drawingBufferWidth,
				gl.drawingBufferHeight
			])
		}

		if (o.close != null) { state.close = o.close }

		// reset positions
		if (o.positions === null) { o.positions = [] }
		if (o.positions) {
			var positions, count

			// if positions are an object with x/y
			if (o.positions.x && o.positions.y) {
				var xPos = o.positions.x
				var yPos = o.positions.y
				count = state.count = Math.max(
					xPos.length,
					yPos.length
				)
				positions = new Float64Array(count * 2)
				for (var i$1 = 0; i$1 < count; i$1++) {
					positions[i$1 * 2] = xPos[i$1]
					positions[i$1 * 2 + 1] = yPos[i$1]
				}
			}
			else {
				positions = flatten(o.positions, 'float64')
				count = state.count = Math.floor(positions.length / 2)
			}

			var bounds = state.bounds = getBounds(positions, 2)

			// create fill positions
			// FIXME: fill positions can be set only along with positions
			if (state.fill) {
				var pos = []

				// filter bad vertices and remap triangles to ensure shape
				var ids = {}
				var lastId = 0

				for (var i$2 = 0, ptr = 0, l = state.count; i$2 < l; i$2++) {
					var x = positions[i$2*2]
					var y = positions[i$2*2 + 1]
					if (isNaN(x) || isNaN(y) || x == null || y == null) {
						x = positions[lastId*2]
						y = positions[lastId*2 + 1]
						ids[i$2] = lastId
					}
					else {
						lastId = i$2
					}
					pos[ptr++] = x
					pos[ptr++] = y
				}

				var triangles = triangulate(pos, state.hole || [])

				for (var i$3 = 0, l$1 = triangles.length; i$3 < l$1; i$3++) {
					if (ids[triangles[i$3]] != null) { triangles[i$3] = ids[triangles[i$3]] }
				}

				state.triangles = triangles
			}

			// update position buffers
			var npos = new Float64Array(positions)
			normalize(npos, 2, bounds)

			var positionData = new Float64Array(count * 2 + 6)

			// rotate first segment join
			if (state.close) {
				if (positions[0] === positions[count*2 - 2] &&
					positions[1] === positions[count*2 - 1]) {
					positionData[0] = npos[count*2 - 4]
					positionData[1] = npos[count*2 - 3]
				}
				else {
					positionData[0] = npos[count*2 - 2]
					positionData[1] = npos[count*2 - 1]
				}
			}
			else {
				positionData[0] = npos[0]
				positionData[1] = npos[1]
			}

			positionData.set(npos, 2)

			// add last segment
			if (state.close) {
				// ignore coinciding start/end
				if (positions[0] === positions[count*2 - 2] &&
					positions[1] === positions[count*2 - 1]) {
					positionData[count*2 + 2] = npos[2]
					positionData[count*2 + 3] = npos[3]
					state.count -= 1
				}
				else {
					positionData[count*2 + 2] = npos[0]
					positionData[count*2 + 3] = npos[1]
					positionData[count*2 + 4] = npos[2]
					positionData[count*2 + 5] = npos[3]
				}
			}
			// add stub
			else {
				positionData[count*2 + 2] = npos[count*2 - 2]
				positionData[count*2 + 3] = npos[count*2 - 1]
				positionData[count*2 + 4] = npos[count*2 - 2]
				positionData[count*2 + 5] = npos[count*2 - 1]
			}

			state.positionBuffer(float32(positionData))
			state.positionFractBuffer(fract32(positionData))
		}

		if (o.range) {
			state.range = o.range
		} else if (!state.range) {
			state.range = state.bounds
		}

		if ((o.range || o.positions) && state.count) {
			var bounds$1 = state.bounds

			var boundsW = bounds$1[2] - bounds$1[0],
				boundsH = bounds$1[3] - bounds$1[1]

			var rangeW = state.range[2] - state.range[0],
				rangeH = state.range[3] - state.range[1]

			state.scale = [
				boundsW / rangeW,
				boundsH / rangeH
			]
			state.translate = [
				-state.range[0] / rangeW + bounds$1[0] / rangeW || 0,
				-state.range[1] / rangeH + bounds$1[1] / rangeH || 0
			]

			state.scaleFract = fract32(state.scale)
			state.translateFract = fract32(state.translate)
		}

		if (o.dashes) {
			var dashLength = 0., dashData

			if (!o.dashes || o.dashes.length < 2) {
				dashLength = 1.
				dashData = new Uint8Array([255, 255, 255, 255, 255, 255, 255, 255])
			}

			else {
				dashLength = 0.;
				for(var i$4 = 0; i$4 < o.dashes.length; ++i$4) {
					dashLength += o.dashes[i$4]
				}
				dashData = new Uint8Array(dashLength * Line2D.dashMult)
				var ptr$1 = 0
				var fillColor = 255

				// repeat texture two times to provide smooth 0-step
				for (var k = 0; k < 2; k++) {
					for(var i$5 = 0; i$5 < o.dashes.length; ++i$5) {
						for(var j = 0, l$2 = o.dashes[i$5] * Line2D.dashMult * .5; j < l$2; ++j) {
							dashData[ptr$1++] = fillColor
						}
						fillColor ^= 255
					}
				}
			}

			state.dashLength = dashLength
			state.dashTexture({
				channels: 1,
				data: dashData,
				width: dashData.length,
				height: 1,
				mag: 'linear',
				min: 'linear'
			}, 0, 0)
		}

		if (o.color) {
			var count$1 = state.count
			var colors = o.color

			if (!colors) { colors = 'transparent' }

			var colorData = new Uint8Array(count$1 * 4 + 4)

			// convert colors to typed arrays
			if (!Array.isArray(colors) || typeof colors[0] === 'number') {
				var c = rgba(colors, 'uint8')

				for (var i$6 = 0; i$6 < count$1 + 1; i$6++) {
					colorData.set(c, i$6 * 4)
				}
			} else {
				for (var i$7 = 0; i$7 < count$1; i$7++) {
					var c$1 = rgba(colors[i$7], 'uint8')
					colorData.set(c$1, i$7 * 4)
				}
				colorData.set(rgba(colors[0], 'uint8'), count$1 * 4)
			}

			state.colorBuffer({
				usage: 'dynamic',
				type: 'uint8',
				data: colorData
			})
		}
	})

	// remove unmentioned passes
	if (options.length < this.passes.length) {
		for (var i = options.length; i < this.passes.length; i++) {
			var pass = this$1.passes[i]
			if (!pass) { continue }
			pass.colorBuffer.destroy()
			pass.positionBuffer.destroy()
			pass.dashTexture.destroy()
		}
		this.passes.length = options.length
	}

	// remove null items
	var passes = []
	for (var i$1 = 0; i$1 < this.passes.length; i$1++) {
		if (this$1.passes[i$1] !== null) { passes.push(this$1.passes[i$1]) }
	}
	this.passes = passes

	return this
}

Line2D.prototype.destroy = function () {
	this.passes.forEach(function (pass) {
		pass.colorBuffer.destroy()
		pass.positionBuffer.destroy()
		pass.dashTexture.destroy()
	})

	this.passes.length = 0

	return this
}

},{"array-bounds":54,"array-normalize":55,"color-normalize":109,"earcut":157,"es6-weak-map":210,"flatten-vertex-data":217,"glslify":395,"object-assign":440,"parse-rect":445,"pick-by-alias":451,"to-float32":516}],478:[function(_dereq_,module,exports){
'use strict';

function _slicedToArray(arr, i) {
  return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}

function _toConsumableArray(arr) {
  return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}

function _arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) {
    for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];

    return arr2;
  }
}

function _arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}

function _iterableToArray(iter) {
  if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}

function _iterableToArrayLimit(arr, i) {
  var _arr = [];
  var _n = true;
  var _d = false;
  var _e = undefined;

  try {
    for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
      _arr.push(_s.value);

      if (i && _arr.length === i) break;
    }
  } catch (err) {
    _d = true;
    _e = err;
  } finally {
    try {
      if (!_n && _i["return"] != null) _i["return"]();
    } finally {
      if (_d) throw _e;
    }
  }

  return _arr;
}

function _nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance");
}

function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance");
}

var rgba = _dereq_('color-normalize');

var getBounds = _dereq_('array-bounds');

var colorId = _dereq_('color-id');

var cluster = _dereq_('point-cluster');

var extend = _dereq_('object-assign');

var glslify = _dereq_('glslify');

var pick = _dereq_('pick-by-alias');

var updateDiff = _dereq_('update-diff');

var flatten = _dereq_('flatten-vertex-data');

var ie = _dereq_('is-iexplorer');

var f32 = _dereq_('to-float32');

var parseRect = _dereq_('parse-rect');

var scatter = Scatter;

function Scatter(regl, options) {
  var _this = this;

  if (!(this instanceof Scatter)) return new Scatter(regl, options);

  if (typeof regl === 'function') {
    if (!options) options = {};
    options.regl = regl;
  } else {
    options = regl;
    regl = null;
  }

  if (options && options.length) options.positions = options;
  regl = options.regl; // persistent variables

  var gl = regl._gl,
      paletteTexture,
      palette = [],
      paletteIds = {},
      // state
  groups = [],
      // textures for marker keys
  markerTextures = [null],
      markerCache = [null];
  var maxColors = 255,
      maxSize = 100; // direct color buffer mode
  // IE does not support palette anyways

  this.tooManyColors = ie; // texture with color palette

  paletteTexture = regl.texture({
    data: new Uint8Array(maxColors * 4),
    width: maxColors,
    height: 1,
    type: 'uint8',
    format: 'rgba',
    wrapS: 'clamp',
    wrapT: 'clamp',
    mag: 'nearest',
    min: 'nearest'
  });
  extend(this, {
    regl: regl,
    gl: gl,
    groups: groups,
    markerCache: markerCache,
    markerTextures: markerTextures,
    palette: palette,
    paletteIds: paletteIds,
    paletteTexture: paletteTexture,
    maxColors: maxColors,
    maxSize: maxSize,
    canvas: gl.canvas
  });
  this.update(options); // common shader options

  var shaderOptions = {
    uniforms: {
      pixelRatio: regl.context('pixelRatio'),
      palette: paletteTexture,
      paletteSize: function paletteSize(ctx, prop) {
        return [_this.tooManyColors ? 0 : maxColors, paletteTexture.height];
      },
      scale: regl.prop('scale'),
      scaleFract: regl.prop('scaleFract'),
      translate: regl.prop('translate'),
      translateFract: regl.prop('translateFract'),
      opacity: regl.prop('opacity'),
      marker: regl.prop('markerTexture')
    },
    attributes: {
      // FIXME: optimize these parts
      x: function x(ctx, prop) {
        return prop.xAttr || {
          buffer: prop.positionBuffer,
          stride: 8,
          offset: 0
        };
      },
      y: function y(ctx, prop) {
        return prop.yAttr || {
          buffer: prop.positionBuffer,
          stride: 8,
          offset: 4
        };
      },
      xFract: function xFract(ctx, prop) {
        return prop.xAttr ? {
          constant: [0, 0]
        } : {
          buffer: prop.positionFractBuffer,
          stride: 8,
          offset: 0
        };
      },
      yFract: function yFract(ctx, prop) {
        return prop.yAttr ? {
          constant: [0, 0]
        } : {
          buffer: prop.positionFractBuffer,
          stride: 8,
          offset: 4
        };
      },
      size: function size(ctx, prop) {
        return prop.size.length ? {
          buffer: prop.sizeBuffer,
          stride: 2,
          offset: 0
        } : {
          constant: [Math.round(prop.size * 255 / _this.maxSize)]
        };
      },
      borderSize: function borderSize(ctx, prop) {
        return prop.borderSize.length ? {
          buffer: prop.sizeBuffer,
          stride: 2,
          offset: 1
        } : {
          constant: [Math.round(prop.borderSize * 255 / _this.maxSize)]
        };
      },
      colorId: function colorId(ctx, prop) {
        return prop.color.length ? {
          buffer: prop.colorBuffer,
          stride: _this.tooManyColors ? 8 : 4,
          offset: 0
        } : {
          constant: _this.tooManyColors ? palette.slice(prop.color * 4, prop.color * 4 + 4) : [prop.color]
        };
      },
      borderColorId: function borderColorId(ctx, prop) {
        return prop.borderColor.length ? {
          buffer: prop.colorBuffer,
          stride: _this.tooManyColors ? 8 : 4,
          offset: _this.tooManyColors ? 4 : 2
        } : {
          constant: _this.tooManyColors ? palette.slice(prop.borderColor * 4, prop.borderColor * 4 + 4) : [prop.borderColor]
        };
      },
      isActive: function isActive(ctx, prop) {
        return prop.activation === true ? {
          constant: [1]
        } : prop.activation ? prop.activation : {
          constant: [0]
        };
      }
    },
    blend: {
      enable: true,
      color: [0, 0, 0, 1],
      // photoshop blending
      func: {
        srcRGB: 'src alpha',
        dstRGB: 'one minus src alpha',
        srcAlpha: 'one minus dst alpha',
        dstAlpha: 'one'
      }
    },
    scissor: {
      enable: true,
      box: regl.prop('viewport')
    },
    viewport: regl.prop('viewport'),
    stencil: {
      enable: false
    },
    depth: {
      enable: false
    },
    elements: regl.prop('elements'),
    count: regl.prop('count'),
    offset: regl.prop('offset'),
    primitive: 'points' // draw sdf-marker

  };
  var markerOptions = extend({}, shaderOptions);
  markerOptions.frag = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragWidth, fragBorderColorLevel, fragColorLevel;\n\nuniform sampler2D marker;\nuniform float pixelRatio, opacity;\n\nfloat smoothStep(float x, float y) {\n  return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n  float dist = texture2D(marker, gl_PointCoord).r, delta = fragWidth;\n\n  // max-distance alpha\n  if (dist < 0.003) discard;\n\n  // null-border case\n  if (fragBorderColorLevel == fragColorLevel || fragBorderColor.a == 0.) {\n    float colorAmt = smoothstep(.5 - delta, .5 + delta, dist);\n    gl_FragColor = vec4(fragColor.rgb, colorAmt * fragColor.a * opacity);\n  }\n  else {\n    float borderColorAmt = smoothstep(fragBorderColorLevel - delta, fragBorderColorLevel + delta, dist);\n    float colorAmt = smoothstep(fragColorLevel - delta, fragColorLevel + delta, dist);\n\n    vec4 color = fragBorderColor;\n    color.a *= borderColorAmt;\n    color = mix(color, fragColor, colorAmt);\n    color.a *= opacity;\n\n    gl_FragColor = color;\n  }\n\n}\n"]);
  markerOptions.vert = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute float x, y, xFract, yFract;\nattribute float size, borderSize;\nattribute vec4 colorId, borderColorId;\nattribute float isActive;\n\nuniform vec2 scale, scaleFract, translate, translateFract, paletteSize;\nuniform float pixelRatio;\nuniform sampler2D palette;\n\nconst float maxSize = 100.;\nconst float borderLevel = .5;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragPointSize, fragBorderRadius, fragWidth, fragBorderColorLevel, fragColorLevel;\n\nbool isDirect = (paletteSize.x < 1.);\n\nvec4 getColor(vec4 id) {\n  return isDirect ? id / 255. : texture2D(palette,\n    vec2(\n      (id.x + .5) / paletteSize.x,\n      (id.y + .5) / paletteSize.y\n    )\n  );\n}\n\nvoid main() {\n  if (isActive == 0.) return;\n\n  vec2 position = vec2(x, y);\n  vec2 positionFract = vec2(xFract, yFract);\n\n  vec4 color = getColor(colorId);\n  vec4 borderColor = getColor(borderColorId);\n\n  float size = size * maxSize / 255.;\n  float borderSize = borderSize * maxSize / 255.;\n\n  gl_PointSize = 2. * size * pixelRatio;\n  fragPointSize = size * pixelRatio;\n\n  vec2 pos = (position + translate) * scale\n      + (positionFract + translateFract) * scale\n      + (position + translate) * scaleFract\n      + (positionFract + translateFract) * scaleFract;\n\n  gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n  fragColor = color;\n  fragBorderColor = borderColor;\n  fragWidth = 1. / gl_PointSize;\n\n  fragBorderColorLevel = clamp(borderLevel - borderLevel * borderSize / size, 0., 1.);\n  fragColorLevel = clamp(borderLevel + (1. - borderLevel) * borderSize / size, 0., 1.);\n}"]);
  this.drawMarker = regl(markerOptions); // draw circle

  var circleOptions = extend({}, shaderOptions);
  circleOptions.frag = glslify(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\n\nuniform float opacity;\nvarying float fragBorderRadius, fragWidth;\n\nfloat smoothStep(float edge0, float edge1, float x) {\n\tfloat t;\n\tt = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);\n\treturn t * t * (3.0 - 2.0 * t);\n}\n\nvoid main() {\n\tfloat radius, alpha = 1.0, delta = fragWidth;\n\n\tradius = length(2.0 * gl_PointCoord.xy - 1.0);\n\n\tif (radius > 1.0 + delta) {\n\t\tdiscard;\n\t}\n\n\talpha -= smoothstep(1.0 - delta, 1.0 + delta, radius);\n\n\tfloat borderRadius = fragBorderRadius;\n\tfloat ratio = smoothstep(borderRadius - delta, borderRadius + delta, radius);\n\tvec4 color = mix(fragColor, fragBorderColor, ratio);\n\tcolor.a *= alpha * opacity;\n\tgl_FragColor = color;\n}\n"]);
  circleOptions.vert = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute float x, y, xFract, yFract;\nattribute float size, borderSize;\nattribute vec4 colorId, borderColorId;\nattribute float isActive;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio;\nuniform sampler2D palette;\nuniform vec2 paletteSize;\n\nconst float maxSize = 100.;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth;\n\nbool isDirect = (paletteSize.x < 1.);\n\nvec4 getColor(vec4 id) {\n  return isDirect ? id / 255. : texture2D(palette,\n    vec2(\n      (id.x + .5) / paletteSize.x,\n      (id.y + .5) / paletteSize.y\n    )\n  );\n}\n\nvoid main() {\n  // ignore inactive points\n  if (isActive == 0.) return;\n\n  vec2 position = vec2(x, y);\n  vec2 positionFract = vec2(xFract, yFract);\n\n  vec4 color = getColor(colorId);\n  vec4 borderColor = getColor(borderColorId);\n\n  float size = size * maxSize / 255.;\n  float borderSize = borderSize * maxSize / 255.;\n\n  gl_PointSize = (size + borderSize) * pixelRatio;\n\n  vec2 pos = (position + translate) * scale\n      + (positionFract + translateFract) * scale\n      + (position + translate) * scaleFract\n      + (positionFract + translateFract) * scaleFract;\n\n  gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n  fragBorderRadius = 1. - 2. * borderSize / (size + borderSize);\n  fragColor = color;\n  fragBorderColor = borderColor.a == 0. || borderSize == 0. ? vec4(color.rgb, 0.) : borderColor;\n  fragWidth = 1. / gl_PointSize;\n}\n"]); // polyfill IE

  if (ie) {
    circleOptions.frag = circleOptions.frag.replace('smoothstep', 'smoothStep');
    markerOptions.frag = markerOptions.frag.replace('smoothstep', 'smoothStep');
  }

  this.drawCircle = regl(circleOptions);
} // single pass defaults


Scatter.defaults = {
  color: 'black',
  borderColor: 'transparent',
  borderSize: 0,
  size: 12,
  opacity: 1,
  marker: undefined,
  viewport: null,
  range: null,
  pixelSize: null,
  count: 0,
  offset: 0,
  bounds: null,
  positions: [],
  snap: 1e4 // update & redraw

};

Scatter.prototype.render = function () {
  if (arguments.length) {
    this.update.apply(this, arguments);
  }

  this.draw();
  return this;
}; // draw all groups or only indicated ones


Scatter.prototype.draw = function () {
  var _this2 = this;

  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
    args[_key] = arguments[_key];
  }

  var groups = this.groups; // if directly array passed - treat as passes

  if (args.length === 1 && Array.isArray(args[0]) && (args[0][0] === null || Array.isArray(args[0][0]))) {
    args = args[0];
  } // FIXME: remove once https://github.com/regl-project/regl/issues/474 resolved


  this.regl._refresh();

  if (args.length) {
    for (var i = 0; i < args.length; i++) {
      this.drawItem(i, args[i]);
    }
  } // draw all passes
  else {
      groups.forEach(function (group, i) {
        _this2.drawItem(i);
      });
    }

  return this;
}; // draw specific scatter group


Scatter.prototype.drawItem = function (id, els) {
  var groups = this.groups;
  var group = groups[id]; // debug viewport
  // let { viewport } = group
  // gl.enable(gl.SCISSOR_TEST);
  // gl.scissor(viewport.x, viewport.y, viewport.width, viewport.height);
  // gl.clearColor(0, 0, 0, .5);
  // gl.clear(gl.COLOR_BUFFER_BIT);

  if (typeof els === 'number') {
    id = els;
    group = groups[els];
    els = null;
  }

  if (!(group && group.count && group.opacity)) return; // draw circles

  if (group.activation[0]) {
    // TODO: optimize this performance by making groups and regl.this props
    this.drawCircle(this.getMarkerDrawOptions(0, group, els));
  } // draw all other available markers


  var batch = [];

  for (var i = 1; i < group.activation.length; i++) {
    if (!group.activation[i] || group.activation[i] !== true && !group.activation[i].data.length) continue;
    batch.push.apply(batch, _toConsumableArray(this.getMarkerDrawOptions(i, group, els)));
  }

  if (batch.length) {
    this.drawMarker(batch);
  }
}; // get options for the marker ids


Scatter.prototype.getMarkerDrawOptions = function (markerId, group, elements) {
  var range = group.range,
      tree = group.tree,
      viewport = group.viewport,
      activation = group.activation,
      selectionBuffer = group.selectionBuffer,
      count = group.count;
  var regl = this.regl; // direct points

  if (!tree) {
    // if elements array - draw unclustered points
    if (elements) {
      return [extend({}, group, {
        markerTexture: this.markerTextures[markerId],
        activation: activation[markerId],
        count: elements.length,
        elements: elements,
        offset: 0
      })];
    }

    return [extend({}, group, {
      markerTexture: this.markerTextures[markerId],
      activation: activation[markerId],
      offset: 0
    })];
  } // clustered points


  var batch = [];
  var lod = tree.range(range, {
    lod: true,
    px: [(range[2] - range[0]) / viewport.width, (range[3] - range[1]) / viewport.height]
  }); // enable elements by using selection buffer

  if (elements) {
    var markerActivation = activation[markerId];
    var mask = markerActivation.data;
    var data = new Uint8Array(count);

    for (var i = 0; i < elements.length; i++) {
      var id = elements[i];
      data[id] = mask ? mask[id] : 1;
    }

    selectionBuffer.subdata(data);
  }

  for (var l = lod.length; l--;) {
    var _lod$l = _slicedToArray(lod[l], 2),
        from = _lod$l[0],
        to = _lod$l[1];

    batch.push(extend({}, group, {
      markerTexture: this.markerTextures[markerId],
      activation: elements ? selectionBuffer : activation[markerId],
      offset: from,
      count: to - from
    }));
  }

  return batch;
}; // update groups options


Scatter.prototype.update = function () {
  var _this3 = this;

  for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
    args[_key2] = arguments[_key2];
  }

  if (!args.length) return; // passes are as single array

  if (args.length === 1 && Array.isArray(args[0])) args = args[0];
  var groups = this.groups,
      gl = this.gl,
      regl = this.regl,
      maxSize = this.maxSize,
      maxColors = this.maxColors,
      palette = this.palette;
  this.groups = groups = args.map(function (options, i) {
    var group = groups[i];
    if (options === undefined) return group;
    if (options === null) options = {
      positions: null
    };else if (typeof options === 'function') options = {
      ondraw: options
    };else if (typeof options[0] === 'number') options = {
      positions: options // copy options to avoid mutation & handle aliases

    };
    options = pick(options, {
      positions: 'positions data points',
      snap: 'snap cluster lod tree',
      size: 'sizes size radius',
      borderSize: 'borderSizes borderSize border-size bordersize borderWidth borderWidths border-width borderwidth stroke-width strokeWidth strokewidth outline',
      color: 'colors color fill fill-color fillColor',
      borderColor: 'borderColors borderColor stroke stroke-color strokeColor',
      marker: 'markers marker shape',
      range: 'range dataBox databox',
      viewport: 'viewport viewPort viewBox viewbox',
      opacity: 'opacity alpha transparency',
      bounds: 'bound bounds boundaries limits',
      tooManyColors: 'tooManyColors palette paletteMode optimizePalette enablePalette'
    });
    if (options.positions === null) options.positions = [];
    if (options.tooManyColors != null) _this3.tooManyColors = options.tooManyColors;

    if (!group) {
      groups[i] = group = {
        id: i,
        scale: null,
        translate: null,
        scaleFract: null,
        translateFract: null,
        // buffers for active markers
        activation: [],
        // buffer for filtered markers
        selectionBuffer: regl.buffer({
          data: new Uint8Array(0),
          usage: 'stream',
          type: 'uint8'
        }),
        // buffers with data: it is faster to switch them per-pass
        // than provide one congregate buffer
        sizeBuffer: regl.buffer({
          data: new Uint8Array(0),
          usage: 'dynamic',
          type: 'uint8'
        }),
        colorBuffer: regl.buffer({
          data: new Uint8Array(0),
          usage: 'dynamic',
          type: 'uint8'
        }),
        positionBuffer: regl.buffer({
          data: new Uint8Array(0),
          usage: 'dynamic',
          type: 'float'
        }),
        positionFractBuffer: regl.buffer({
          data: new Uint8Array(0),
          usage: 'dynamic',
          type: 'float'
        })
      };
      options = extend({}, Scatter.defaults, options);
    } // force update triggers


    if (options.positions && !('marker' in options)) {
      options.marker = group.marker;
      delete group.marker;
    } // updating markers cause recalculating snapping


    if (options.marker && !('positions' in options)) {
      options.positions = group.positions;
      delete group.positions;
    } // global count of points


    var hasSize = 0,
        hasColor = 0;
    updateDiff(group, options, [{
      snap: true,
      size: function size(s, group) {
        if (s == null) s = Scatter.defaults.size;
        hasSize += s && s.length ? 1 : 0;
        return s;
      },
      borderSize: function borderSize(s, group) {
        if (s == null) s = Scatter.defaults.borderSize;
        hasSize += s && s.length ? 1 : 0;
        return s;
      },
      opacity: parseFloat,
      // add colors to palette, save references
      color: function color(c, group) {
        if (c == null) c = Scatter.defaults.color;
        c = _this3.updateColor(c);
        hasColor++;
        return c;
      },
      borderColor: function borderColor(c, group) {
        if (c == null) c = Scatter.defaults.borderColor;
        c = _this3.updateColor(c);
        hasColor++;
        return c;
      },
      bounds: function bounds(_bounds, group, options) {
        if (!('range' in options)) options.range = null;
        return _bounds;
      },
      positions: function positions(_positions, group, options) {
        var snap = group.snap;
        var positionBuffer = group.positionBuffer,
            positionFractBuffer = group.positionFractBuffer,
            selectionBuffer = group.selectionBuffer; // separate buffers for x/y coordinates

        if (_positions.x || _positions.y) {
          if (_positions.x.length) {
            group.xAttr = {
              buffer: regl.buffer(_positions.x),
              offset: 0,
              stride: 4,
              count: _positions.x.length
            };
          } else {
            group.xAttr = {
              buffer: _positions.x.buffer,
              offset: _positions.x.offset * 4 || 0,
              stride: (_positions.x.stride || 1) * 4,
              count: _positions.x.count
            };
          }

          if (_positions.y.length) {
            group.yAttr = {
              buffer: regl.buffer(_positions.y),
              offset: 0,
              stride: 4,
              count: _positions.y.length
            };
          } else {
            group.yAttr = {
              buffer: _positions.y.buffer,
              offset: _positions.y.offset * 4 || 0,
              stride: (_positions.y.stride || 1) * 4,
              count: _positions.y.count
            };
          }

          group.count = Math.max(group.xAttr.count, group.yAttr.count);
          return _positions;
        }

        _positions = flatten(_positions, 'float64');
        var count = group.count = Math.floor(_positions.length / 2);
        var bounds = group.bounds = count ? getBounds(_positions, 2) : null; // if range is not provided updated - recalc it

        if (!options.range && !group.range) {
          delete group.range;
          options.range = bounds;
        } // reset marker


        if (!options.marker && !group.marker) {
          delete group.marker;
          options.marker = null;
        } // build cluster tree if required


        if (snap && (snap === true || count > snap)) {
          group.tree = cluster(_positions, {
            bounds: bounds
          });
        } // existing tree instance
        else if (snap && snap.length) {
            group.tree = snap;
          }

        if (group.tree) {
          var opts = {
            primitive: 'points',
            usage: 'static',
            data: group.tree,
            type: 'uint32'
          };
          if (group.elements) group.elements(opts);else group.elements = regl.elements(opts);
        } // update position buffers


        positionBuffer({
          data: f32.float(_positions),
          usage: 'dynamic'
        });
        positionFractBuffer({
          data: f32.fract(_positions),
          usage: 'dynamic'
        }); // expand selectionBuffer

        selectionBuffer({
          data: new Uint8Array(count),
          type: 'uint8',
          usage: 'stream'
        });
        return _positions;
      }
    }, {
      // create marker ids corresponding to known marker textures
      marker: function marker(markers, group, options) {
        var activation = group.activation; // reset marker elements

        activation.forEach(function (buffer) {
          return buffer && buffer.destroy && buffer.destroy();
        });
        activation.length = 0; // single sdf marker

        if (!markers || typeof markers[0] === 'number') {
          var id = _this3.addMarker(markers);

          activation[id] = true;
        } // per-point markers use mask buffers to enable markers in vert shader
        else {
            var markerMasks = [];

            for (var _i = 0, l = Math.min(markers.length, group.count); _i < l; _i++) {
              var _id = _this3.addMarker(markers[_i]);

              if (!markerMasks[_id]) markerMasks[_id] = new Uint8Array(group.count); // enable marker by default

              markerMasks[_id][_i] = 1;
            }

            for (var _id2 = 0; _id2 < markerMasks.length; _id2++) {
              if (!markerMasks[_id2]) continue;
              var opts = {
                data: markerMasks[_id2],
                type: 'uint8',
                usage: 'static'
              };

              if (!activation[_id2]) {
                activation[_id2] = regl.buffer(opts);
              } else {
                activation[_id2](opts);
              }

              activation[_id2].data = markerMasks[_id2];
            }
          }

        return markers;
      },
      range: function range(_range, group, options) {
        var bounds = group.bounds; // FIXME: why do we need this?

        if (!bounds) return;
        if (!_range) _range = bounds;
        group.scale = [1 / (_range[2] - _range[0]), 1 / (_range[3] - _range[1])];
        group.translate = [-_range[0], -_range[1]];
        group.scaleFract = f32.fract(group.scale);
        group.translateFract = f32.fract(group.translate);
        return _range;
      },
      viewport: function viewport(vp) {
        var rect = parseRect(vp || [gl.drawingBufferWidth, gl.drawingBufferHeight]); // normalize viewport to the canvas coordinates
        // rect.y = gl.drawingBufferHeight - rect.height - rect.y

        return rect;
      }
    }]); // update size buffer, if needed

    if (hasSize) {
      var _group = group,
          count = _group.count,
          size = _group.size,
          borderSize = _group.borderSize,
          sizeBuffer = _group.sizeBuffer;
      var sizes = new Uint8Array(count * 2);

      if (size.length || borderSize.length) {
        for (var _i2 = 0; _i2 < count; _i2++) {
          // we downscale size to allow for fractions
          sizes[_i2 * 2] = Math.round((size[_i2] == null ? size : size[_i2]) * 255 / maxSize);
          sizes[_i2 * 2 + 1] = Math.round((borderSize[_i2] == null ? borderSize : borderSize[_i2]) * 255 / maxSize);
        }
      }

      sizeBuffer({
        data: sizes,
        usage: 'dynamic'
      });
    } // update color buffer if needed


    if (hasColor) {
      var _group2 = group,
          _count = _group2.count,
          color = _group2.color,
          borderColor = _group2.borderColor,
          colorBuffer = _group2.colorBuffer;
      var colors; // if too many colors - put colors to buffer directly

      if (_this3.tooManyColors) {
        if (color.length || borderColor.length) {
          colors = new Uint8Array(_count * 8);

          for (var _i3 = 0; _i3 < _count; _i3++) {
            var _colorId = color[_i3];
            colors[_i3 * 8] = palette[_colorId * 4];
            colors[_i3 * 8 + 1] = palette[_colorId * 4 + 1];
            colors[_i3 * 8 + 2] = palette[_colorId * 4 + 2];
            colors[_i3 * 8 + 3] = palette[_colorId * 4 + 3];
            var borderColorId = borderColor[_i3];
            colors[_i3 * 8 + 4] = palette[borderColorId * 4];
            colors[_i3 * 8 + 5] = palette[borderColorId * 4 + 1];
            colors[_i3 * 8 + 6] = palette[borderColorId * 4 + 2];
            colors[_i3 * 8 + 7] = palette[borderColorId * 4 + 3];
          }
        }
      } // if limited amount of colors - keep palette color picking
      // that saves significant memory
      else {
          if (color.length || borderColor.length) {
            // we need slight data increase by 2 due to vec4 borderId in shader
            colors = new Uint8Array(_count * 4 + 2);

            for (var _i4 = 0; _i4 < _count; _i4++) {
              // put color coords in palette texture
              if (color[_i4] != null) {
                colors[_i4 * 4] = color[_i4] % maxColors;
                colors[_i4 * 4 + 1] = Math.floor(color[_i4] / maxColors);
              }

              if (borderColor[_i4] != null) {
                colors[_i4 * 4 + 2] = borderColor[_i4] % maxColors;
                colors[_i4 * 4 + 3] = Math.floor(borderColor[_i4] / maxColors);
              }
            }
          }
        }

      colorBuffer({
        data: colors || new Uint8Array(0),
        type: 'uint8',
        usage: 'dynamic'
      });
    }

    return group;
  });
}; // get (and create) marker texture id


Scatter.prototype.addMarker = function (sdf) {
  var markerTextures = this.markerTextures,
      regl = this.regl,
      markerCache = this.markerCache;
  var pos = sdf == null ? 0 : markerCache.indexOf(sdf);
  if (pos >= 0) return pos; // convert sdf to 0..255 range

  var distArr;

  if (sdf instanceof Uint8Array || sdf instanceof Uint8ClampedArray) {
    distArr = sdf;
  } else {
    distArr = new Uint8Array(sdf.length);

    for (var i = 0, l = sdf.length; i < l; i++) {
      distArr[i] = sdf[i] * 255;
    }
  }

  var radius = Math.floor(Math.sqrt(distArr.length));
  pos = markerTextures.length;
  markerCache.push(sdf);
  markerTextures.push(regl.texture({
    channels: 1,
    data: distArr,
    radius: radius,
    mag: 'linear',
    min: 'linear'
  }));
  return pos;
}; // register color to palette, return it's index or list of indexes


Scatter.prototype.updateColor = function (colors) {
  var paletteIds = this.paletteIds,
      palette = this.palette,
      maxColors = this.maxColors;

  if (!Array.isArray(colors)) {
    colors = [colors];
  }

  var idx = []; // if color groups - flatten them

  if (typeof colors[0] === 'number') {
    var grouped = [];

    if (Array.isArray(colors)) {
      for (var i = 0; i < colors.length; i += 4) {
        grouped.push(colors.slice(i, i + 4));
      }
    } else {
      for (var _i5 = 0; _i5 < colors.length; _i5 += 4) {
        grouped.push(colors.subarray(_i5, _i5 + 4));
      }
    }

    colors = grouped;
  }

  for (var _i6 = 0; _i6 < colors.length; _i6++) {
    var color = colors[_i6];
    color = rgba(color, 'uint8');
    var id = colorId(color, false); // if new color - save it

    if (paletteIds[id] == null) {
      var pos = palette.length;
      paletteIds[id] = Math.floor(pos / 4);
      palette[pos] = color[0];
      palette[pos + 1] = color[1];
      palette[pos + 2] = color[2];
      palette[pos + 3] = color[3];
    }

    idx[_i6] = paletteIds[id];
  } // detect if too many colors in palette


  if (!this.tooManyColors && palette.length > maxColors * 4) this.tooManyColors = true; // limit max color

  this.updatePalette(palette); // keep static index for single-color property

  return idx.length === 1 ? idx[0] : idx;
};

Scatter.prototype.updatePalette = function (palette) {
  if (this.tooManyColors) return;
  var maxColors = this.maxColors,
      paletteTexture = this.paletteTexture;
  var requiredHeight = Math.ceil(palette.length * .25 / maxColors); // pad data

  if (requiredHeight > 1) {
    palette = palette.slice();

    for (var i = palette.length * .25 % maxColors; i < requiredHeight * maxColors; i++) {
      palette.push(0, 0, 0, 0);
    }
  } // ensure height


  if (paletteTexture.height < requiredHeight) {
    paletteTexture.resize(maxColors, requiredHeight);
  } // update full data


  paletteTexture.subimage({
    width: Math.min(palette.length * .25, maxColors),
    height: requiredHeight,
    data: palette
  }, 0, 0);
}; // remove unused stuff


Scatter.prototype.destroy = function () {
  this.groups.forEach(function (group) {
    group.sizeBuffer.destroy();
    group.positionBuffer.destroy();
    group.positionFractBuffer.destroy();
    group.colorBuffer.destroy();
    group.activation.forEach(function (b) {
      return b && b.destroy && b.destroy();
    });
    group.selectionBuffer.destroy();
    if (group.elements) group.elements.destroy();
  });
  this.groups.length = 0;
  this.paletteTexture.destroy();
  this.markerTextures.forEach(function (txt) {
    return txt && txt.destroy && txt.destroy();
  });
  return this;
};

var extend$1 = _dereq_('object-assign');

var reglScatter2d = function reglScatter2d(regl, options) {
  var scatter$$1 = new scatter(regl, options);
  var render = scatter$$1.render.bind(scatter$$1); // expose API

  extend$1(render, {
    render: render,
    update: scatter$$1.update.bind(scatter$$1),
    draw: scatter$$1.draw.bind(scatter$$1),
    destroy: scatter$$1.destroy.bind(scatter$$1),
    regl: scatter$$1.regl,
    gl: scatter$$1.gl,
    canvas: scatter$$1.gl.canvas,
    groups: scatter$$1.groups,
    markers: scatter$$1.markerCache,
    palette: scatter$$1.palette
  });
  return render;
};

module.exports = reglScatter2d;

},{"array-bounds":54,"color-id":107,"color-normalize":109,"flatten-vertex-data":217,"glslify":395,"is-iexplorer":405,"object-assign":440,"parse-rect":445,"pick-by-alias":451,"point-cluster":455,"to-float32":516,"update-diff":527}],479:[function(_dereq_,module,exports){
'use strict'


var createScatter = _dereq_('regl-scatter2d')
var pick = _dereq_('pick-by-alias')
var getBounds = _dereq_('array-bounds')
var raf = _dereq_('raf')
var arrRange = _dereq_('array-range')
var rect = _dereq_('parse-rect')
var flatten = _dereq_('flatten-vertex-data')


module.exports = SPLOM


// @constructor
function SPLOM (regl, options) {
	if (!(this instanceof SPLOM)) { return new SPLOM(regl, options) }

	// render passes
	this.traces = []

	// passes for scatter, combined across traces
	this.passes = {}

	this.regl = regl

	// main scatter drawing instance
	this.scatter = createScatter(regl)

	this.canvas = this.scatter.canvas
}


// update & draw passes once per frame
SPLOM.prototype.render = function () {
	var this$1 = this;
	var ref;

	var args = [], len = arguments.length;
	while ( len-- ) args[ len ] = arguments[ len ];
	if (args.length) {
		(ref = this).update.apply(ref, args)
	}

	if (this.regl.attributes.preserveDrawingBuffer) { return this.draw() }

	// make sure draw is not called more often than once a frame
	if (this.dirty) {
		if (this.planned == null) {
			this.planned = raf(function () {
				this$1.draw()
				this$1.dirty = true
				this$1.planned = null
			})
		}
	}
	else {
		this.draw()
		this.dirty = true
		raf(function () {
			this$1.dirty = false
		})
	}

	return this
}


// update passes
SPLOM.prototype.update = function () {
	var this$1 = this;
	var ref;

	var args = [], len = arguments.length;
	while ( len-- ) args[ len ] = arguments[ len ];
	if (!args.length) { return }

	for (var i = 0; i < args.length; i++) {
		this$1.updateItem(i, args[i])
	}

	// remove nulled passes
	this.traces = this.traces.filter(Boolean)

	// FIXME: update passes independently
	var passes = []
	var offset = 0
	for (var i$1 = 0; i$1 < this.traces.length; i$1++) {
		var trace = this$1.traces[i$1]
		var tracePasses = this$1.traces[i$1].passes
		for (var j = 0; j < tracePasses.length; j++) {
			passes.push(this$1.passes[tracePasses[j]])
		}
		// save offset of passes
		trace.passOffset = offset
		offset += trace.passes.length
	}

	(ref = this.scatter).update.apply(ref, passes)

	return this
}


// update trace by index, not supposed to be called directly
SPLOM.prototype.updateItem = function (i, options) {
	var this$1 = this;

	var ref = this;
	var regl = ref.regl;

	// remove pass if null
	if (options === null) {
		this.traces[i] = null
		return this
	}

	if (!options) { return this }

	var o = pick(options, {
		data: 'data items columns rows values dimensions samples x',
		snap: 'snap cluster',
		size: 'sizes size radius',
		color: 'colors color fill fill-color fillColor',
		opacity: 'opacity alpha transparency opaque',
		borderSize: 'borderSizes borderSize border-size bordersize borderWidth borderWidths border-width borderwidth stroke-width strokeWidth strokewidth outline',
		borderColor: 'borderColors borderColor bordercolor stroke stroke-color strokeColor',
		marker: 'markers marker shape',
		range: 'range ranges databox dataBox',
		viewport: 'viewport viewBox viewbox',
		domain: 'domain domains area areas',
		padding: 'pad padding paddings pads margin margins',
		transpose: 'transpose transposed',
		diagonal: 'diagonal diag showDiagonal',
		upper: 'upper up top upperhalf upperHalf showupperhalf showUpper showUpperHalf',
		lower: 'lower low bottom lowerhalf lowerHalf showlowerhalf showLowerHalf showLower'
	})

	// we provide regl buffer per-trace, since trace data can be changed
	var trace = (this.traces[i] || (this.traces[i] = {
		id: i,
		buffer: regl.buffer({
			usage: 'dynamic',
			type: 'float',
			data: new Uint8Array()
		}),
		color: 'black',
		marker: null,
		size: 12,
		borderColor: 'transparent',
		borderSize: 1,
		viewport:  rect([regl._gl.drawingBufferWidth, regl._gl.drawingBufferHeight]),
		padding: [0, 0, 0, 0],
		opacity: 1,
		diagonal: true,
		upper: true,
		lower: true
	}))


	// save styles
	if (o.color != null) {
		trace.color = o.color
	}
	if (o.size != null) {
		trace.size = o.size
	}
	if (o.marker != null) {
		trace.marker = o.marker
	}
	if (o.borderColor != null) {
		trace.borderColor = o.borderColor
	}
	if (o.borderSize != null) {
		trace.borderSize = o.borderSize
	}
	if (o.opacity != null) {
		trace.opacity = o.opacity
	}
	if (o.viewport) {
		trace.viewport = rect(o.viewport)
	}
	if (o.diagonal != null) { trace.diagonal = o.diagonal }
	if (o.upper != null) { trace.upper = o.upper }
	if (o.lower != null) { trace.lower = o.lower }

	// put flattened data into buffer
	if (o.data) {
		trace.buffer(flatten(o.data))
		trace.columns = o.data.length
		trace.count = o.data[0].length

		// detect bounds per-column
		trace.bounds = []

		for (var i$1 = 0; i$1 < trace.columns; i$1++) {
			trace.bounds[i$1] = getBounds(o.data[i$1], 1)
		}
	}

	// add proper range updating markers
	var multirange
	if (o.range) {
		trace.range = o.range
		multirange = trace.range && typeof trace.range[0] !== 'number'
	}

	if (o.domain) {
		trace.domain = o.domain
	}
	var multipadding = false
	if (o.padding != null) {
		// multiple paddings
		if (Array.isArray(o.padding) && o.padding.length === trace.columns && typeof o.padding[o.padding.length - 1] === 'number') {
			trace.padding = o.padding.map(getPad)
			multipadding = true
		}
		// single padding
		else {
			trace.padding = getPad(o.padding)
		}
	}

	// create passes
	var m = trace.columns
	var n = trace.count

	var w = trace.viewport.width
	var h = trace.viewport.height
	var left = trace.viewport.x
	var top = trace.viewport.y
	var iw = w / m
	var ih = h / m

	trace.passes = []

	for (var i$2 = 0; i$2 < m; i$2++) {
		for (var j = 0; j < m; j++) {
			if (!trace.diagonal && j === i$2) { continue }
			if (!trace.upper && i$2 > j) { continue }
			if (!trace.lower && i$2 < j) { continue }

			var key = passId(trace.id, i$2, j)

			var pass = this$1.passes[key] || (this$1.passes[key] = {})

			if (o.data) {
				if (o.transpose) {
					pass.positions = {
						x: {buffer: trace.buffer, offset: j, count: n, stride: m},
						y: {buffer: trace.buffer, offset: i$2, count: n, stride: m}
					}
				}
				else {
					pass.positions = {
						x: {buffer: trace.buffer, offset: j * n, count: n},
						y: {buffer: trace.buffer, offset: i$2 * n, count: n}
					}
				}

				pass.bounds = getBox(trace.bounds, i$2, j)
			}

			if (o.domain || o.viewport || o.data) {
				var pad = multipadding ? getBox(trace.padding, i$2, j) : trace.padding
				if (trace.domain) {
					var ref$1 = getBox(trace.domain, i$2, j);
					var lox = ref$1[0];
					var loy = ref$1[1];
					var hix = ref$1[2];
					var hiy = ref$1[3];

					pass.viewport = [
						left + lox * w + pad[0],
						top + loy * h + pad[1],
						left + hix * w - pad[2],
						top + hiy * h - pad[3]
					]
				}
				// consider auto-domain equipartial
				else {
					pass.viewport = [
						left + j * iw + iw * pad[0],
						top + i$2 * ih + ih * pad[1],
						left + (j + 1) * iw - iw * pad[2],
						top + (i$2 + 1) * ih - ih * pad[3]
					]
				}
			}

			if (o.color) { pass.color = trace.color }
			if (o.size) { pass.size = trace.size }
			if (o.marker) { pass.marker = trace.marker }
			if (o.borderSize) { pass.borderSize = trace.borderSize }
			if (o.borderColor) { pass.borderColor = trace.borderColor }
			if (o.opacity) { pass.opacity = trace.opacity }

			if (o.range) {
				pass.range = multirange ? getBox(trace.range, i$2, j) : trace.range || pass.bounds
			}

			trace.passes.push(key)
		}
	}

	return this
}


// draw all or passed passes
SPLOM.prototype.draw = function () {
	var this$1 = this;
	var ref$2;

	var args = [], len = arguments.length;
	while ( len-- ) args[ len ] = arguments[ len ];
	if (!args.length) {
		this.scatter.draw()
	}
	else {
		var idx = []
		for (var i = 0; i < args.length; i++) {
			// draw(0, 2, 5) - draw traces
			if (typeof args[i] === 'number' ) {
				var ref = this$1.traces[args[i]];
				var passes = ref.passes;
				var passOffset = ref.passOffset;
				idx.push.apply(idx, arrRange(passOffset, passOffset + passes.length))
			}
			// draw([0, 1, 2 ...], [3, 4, 5]) - draw points
			else if (args[i].length) {
				var els = args[i]
				var ref$1 = this$1.traces[i];
				var passes$1 = ref$1.passes;
				var passOffset$1 = ref$1.passOffset;
				passes$1 = passes$1.map(function (passId, i) {
					idx[passOffset$1 + i] = els
				})
			}
		}
		(ref$2 = this.scatter).draw.apply(ref$2, idx)
	}

	return this
}


// dispose resources
SPLOM.prototype.destroy = function () {
	this.traces.forEach(function (trace) {
		if (trace.buffer && trace.buffer.destroy) { trace.buffer.destroy() }
	})
	this.traces = null
	this.passes = null

	this.scatter.destroy()

	return this
}


// return pass corresponding to trace i- j- square
function passId (trace, i, j) {
	var id = (trace.id != null ? trace.id : trace)
	var n = i
	var m = j
	var key = id << 16 | (n & 0xff) << 8 | m & 0xff

	return key
}


// return bounding box corresponding to a pass
function getBox (items, i, j) {
	var ilox, iloy, ihix, ihiy, jlox, jloy, jhix, jhiy
	var iitem = items[i], jitem = items[j]

	if (iitem.length > 2) {
		ilox = iitem[0]
		ihix = iitem[2]
		iloy = iitem[1]
		ihiy = iitem[3]
	}
	else if (iitem.length) {
		ilox = iloy = iitem[0]
		ihix = ihiy = iitem[1]
	}
	else {
		ilox = iitem.x
		iloy = iitem.y
		ihix = iitem.x + iitem.width
		ihiy = iitem.y + iitem.height
	}

	if (jitem.length > 2) {
		jlox = jitem[0]
		jhix = jitem[2]
		jloy = jitem[1]
		jhiy = jitem[3]
	}
	else if (jitem.length) {
		jlox = jloy = jitem[0]
		jhix = jhiy = jitem[1]
	}
	else {
		jlox = jitem.x
		jloy = jitem.y
		jhix = jitem.x + jitem.width
		jhiy = jitem.y + jitem.height
	}

	return [ jlox, iloy, jhix, ihiy ]
}


function getPad (arg) {
	if (typeof arg === 'number') { return [arg, arg, arg, arg] }
	else if (arg.length === 2) { return [arg[0], arg[1], arg[0], arg[1]] }
	else {
		var box = rect(arg)
		return [box.x, box.y, box.x + box.width, box.y + box.height]
	}
}

},{"array-bounds":54,"array-range":56,"flatten-vertex-data":217,"parse-rect":445,"pick-by-alias":451,"raf":470,"regl-scatter2d":478}],480:[function(_dereq_,module,exports){
(function(aa,ia){"object"===typeof exports&&"undefined"!==typeof module?module.exports=ia():"function"===typeof define&&define.amd?define(ia):aa.createREGL=ia()})(this,function(){function aa(a,b){this.id=Ab++;this.type=a;this.data=b}function ia(a){if(0===a.length)return[];var b=a.charAt(0),c=a.charAt(a.length-1);if(1<a.length&&b===c&&('"'===b||"'"===b))return['"'+a.substr(1,a.length-2).replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'];if(b=/\[(false|true|null|\d+|'[^']*'|"[^"]*")\]/.exec(a))return ia(a.substr(0,
b.index)).concat(ia(b[1])).concat(ia(a.substr(b.index+b[0].length)));b=a.split(".");if(1===b.length)return['"'+a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'];a=[];for(c=0;c<b.length;++c)a=a.concat(ia(b[c]));return a}function Za(a){return"["+ia(a).join("][")+"]"}function Bb(){var a={"":0},b=[""];return{id:function(c){var e=a[c];if(e)return e;e=a[c]=b.length;b.push(c);return e},str:function(a){return b[a]}}}function Cb(a,b,c){function e(){var b=window.innerWidth,e=window.innerHeight;a!==document.body&&
(e=a.getBoundingClientRect(),b=e.right-e.left,e=e.bottom-e.top);g.width=c*b;g.height=c*e;E(g.style,{width:b+"px",height:e+"px"})}var g=document.createElement("canvas");E(g.style,{border:0,margin:0,padding:0,top:0,left:0});a.appendChild(g);a===document.body&&(g.style.position="absolute",E(a.style,{margin:0,padding:0}));window.addEventListener("resize",e,!1);e();return{canvas:g,onDestroy:function(){window.removeEventListener("resize",e);a.removeChild(g)}}}function Db(a,b){function c(c){try{return a.getContext(c,
b)}catch(g){return null}}return c("webgl")||c("experimental-webgl")||c("webgl-experimental")}function $a(a){return"string"===typeof a?a.split():a}function ab(a){return"string"===typeof a?document.querySelector(a):a}function Eb(a){var b=a||{},c,e,g,d;a={};var n=[],f=[],r="undefined"===typeof window?1:window.devicePixelRatio,q=!1,t=function(a){},m=function(){};"string"===typeof b?c=document.querySelector(b):"object"===typeof b&&("string"===typeof b.nodeName&&"function"===typeof b.appendChild&&"function"===
typeof b.getBoundingClientRect?c=b:"function"===typeof b.drawArrays||"function"===typeof b.drawElements?(d=b,g=d.canvas):("gl"in b?d=b.gl:"canvas"in b?g=ab(b.canvas):"container"in b&&(e=ab(b.container)),"attributes"in b&&(a=b.attributes),"extensions"in b&&(n=$a(b.extensions)),"optionalExtensions"in b&&(f=$a(b.optionalExtensions)),"onDone"in b&&(t=b.onDone),"profile"in b&&(q=!!b.profile),"pixelRatio"in b&&(r=+b.pixelRatio)));c&&("canvas"===c.nodeName.toLowerCase()?g=c:e=c);if(!d){if(!g){c=Cb(e||document.body,
t,r);if(!c)return null;g=c.canvas;m=c.onDestroy}d=Db(g,a)}return d?{gl:d,canvas:g,container:e,extensions:n,optionalExtensions:f,pixelRatio:r,profile:q,onDone:t,onDestroy:m}:(m(),t("webgl not supported, try upgrading your browser or graphics drivers http://get.webgl.org"),null)}function Fb(a,b){function c(b){b=b.toLowerCase();var c;try{c=e[b]=a.getExtension(b)}catch(g){}return!!c}for(var e={},g=0;g<b.extensions.length;++g){var d=b.extensions[g];if(!c(d))return b.onDestroy(),b.onDone('"'+d+'" extension is not supported by the current WebGL context, try upgrading your system or a different browser'),
null}b.optionalExtensions.forEach(c);return{extensions:e,restore:function(){Object.keys(e).forEach(function(a){if(e[a]&&!c(a))throw Error("(regl): error restoring extension "+a);})}}}function J(a,b){for(var c=Array(a),e=0;e<a;++e)c[e]=b(e);return c}function bb(a){var b,c;b=(65535<a)<<4;a>>>=b;c=(255<a)<<3;a>>>=c;b|=c;c=(15<a)<<2;a>>>=c;b|=c;c=(3<a)<<1;return b|c|a>>>c>>1}function cb(){function a(a){a:{for(var b=16;268435456>=b;b*=16)if(a<=b){a=b;break a}a=0}b=c[bb(a)>>2];return 0<b.length?b.pop():
new ArrayBuffer(a)}function b(a){c[bb(a.byteLength)>>2].push(a)}var c=J(8,function(){return[]});return{alloc:a,free:b,allocType:function(b,c){var d=null;switch(b){case 5120:d=new Int8Array(a(c),0,c);break;case 5121:d=new Uint8Array(a(c),0,c);break;case 5122:d=new Int16Array(a(2*c),0,c);break;case 5123:d=new Uint16Array(a(2*c),0,c);break;case 5124:d=new Int32Array(a(4*c),0,c);break;case 5125:d=new Uint32Array(a(4*c),0,c);break;case 5126:d=new Float32Array(a(4*c),0,c);break;default:return null}return d.length!==
c?d.subarray(0,c):d},freeType:function(a){b(a.buffer)}}}function ma(a){return!!a&&"object"===typeof a&&Array.isArray(a.shape)&&Array.isArray(a.stride)&&"number"===typeof a.offset&&a.shape.length===a.stride.length&&(Array.isArray(a.data)||M(a.data))}function db(a,b,c,e,g,d){for(var n=0;n<b;++n)for(var f=a[n],r=0;r<c;++r)for(var q=f[r],t=0;t<e;++t)g[d++]=q[t]}function eb(a,b,c,e,g){for(var d=1,n=c+1;n<b.length;++n)d*=b[n];var f=b[c];if(4===b.length-c){var r=b[c+1],q=b[c+2];b=b[c+3];for(n=0;n<f;++n)db(a[n],
r,q,b,e,g),g+=d}else for(n=0;n<f;++n)eb(a[n],b,c+1,e,g),g+=d}function Ha(a){return Ia[Object.prototype.toString.call(a)]|0}function fb(a,b){for(var c=0;c<b.length;++c)a[c]=b[c]}function gb(a,b,c,e,g,d,n){for(var f=0,r=0;r<c;++r)for(var q=0;q<e;++q)a[f++]=b[g*r+d*q+n]}function Gb(a,b,c,e){function g(b){this.id=r++;this.buffer=a.createBuffer();this.type=b;this.usage=35044;this.byteLength=0;this.dimension=1;this.dtype=5121;this.persistentData=null;c.profile&&(this.stats={size:0})}function d(b,c,k){b.byteLength=
c.byteLength;a.bufferData(b.type,c,k)}function n(a,b,c,h,l,e){a.usage=c;if(Array.isArray(b)){if(a.dtype=h||5126,0<b.length)if(Array.isArray(b[0])){l=hb(b);for(var v=h=1;v<l.length;++v)h*=l[v];a.dimension=h;b=Qa(b,l,a.dtype);d(a,b,c);e?a.persistentData=b:x.freeType(b)}else"number"===typeof b[0]?(a.dimension=l,l=x.allocType(a.dtype,b.length),fb(l,b),d(a,l,c),e?a.persistentData=l:x.freeType(l)):M(b[0])&&(a.dimension=b[0].length,a.dtype=h||Ha(b[0])||5126,b=Qa(b,[b.length,b[0].length],a.dtype),d(a,b,c),
e?a.persistentData=b:x.freeType(b))}else if(M(b))a.dtype=h||Ha(b),a.dimension=l,d(a,b,c),e&&(a.persistentData=new Uint8Array(new Uint8Array(b.buffer)));else if(ma(b)){l=b.shape;var g=b.stride,v=b.offset,f=0,q=0,r=0,t=0;1===l.length?(f=l[0],q=1,r=g[0],t=0):2===l.length&&(f=l[0],q=l[1],r=g[0],t=g[1]);a.dtype=h||Ha(b.data)||5126;a.dimension=q;l=x.allocType(a.dtype,f*q);gb(l,b.data,f,q,r,t,v);d(a,l,c);e?a.persistentData=l:x.freeType(l)}}function f(c){b.bufferCount--;for(var d=0;d<e.state.length;++d){var k=
e.state[d];k.buffer===c&&(a.disableVertexAttribArray(d),k.buffer=null)}a.deleteBuffer(c.buffer);c.buffer=null;delete q[c.id]}var r=0,q={};g.prototype.bind=function(){a.bindBuffer(this.type,this.buffer)};g.prototype.destroy=function(){f(this)};var t=[];c.profile&&(b.getTotalBufferSize=function(){var a=0;Object.keys(q).forEach(function(b){a+=q[b].stats.size});return a});return{create:function(m,e,d,h){function l(b){var m=35044,e=null,d=0,k=0,g=1;Array.isArray(b)||M(b)||ma(b)?e=b:"number"===typeof b?
d=b|0:b&&("data"in b&&(e=b.data),"usage"in b&&(m=jb[b.usage]),"type"in b&&(k=Ra[b.type]),"dimension"in b&&(g=b.dimension|0),"length"in b&&(d=b.length|0));u.bind();e?n(u,e,m,k,g,h):(d&&a.bufferData(u.type,d,m),u.dtype=k||5121,u.usage=m,u.dimension=g,u.byteLength=d);c.profile&&(u.stats.size=u.byteLength*ja[u.dtype]);return l}b.bufferCount++;var u=new g(e);q[u.id]=u;d||l(m);l._reglType="buffer";l._buffer=u;l.subdata=function(b,c){var m=(c||0)|0,e;u.bind();if(M(b))a.bufferSubData(u.type,m,b);else if(Array.isArray(b)){if(0<
b.length)if("number"===typeof b[0]){var d=x.allocType(u.dtype,b.length);fb(d,b);a.bufferSubData(u.type,m,d);x.freeType(d)}else if(Array.isArray(b[0])||M(b[0]))e=hb(b),d=Qa(b,e,u.dtype),a.bufferSubData(u.type,m,d),x.freeType(d)}else if(ma(b)){e=b.shape;var h=b.stride,k=d=0,g=0,F=0;1===e.length?(d=e[0],k=1,g=h[0],F=0):2===e.length&&(d=e[0],k=e[1],g=h[0],F=h[1]);e=Array.isArray(b.data)?u.dtype:Ha(b.data);e=x.allocType(e,d*k);gb(e,b.data,d,k,g,F,b.offset);a.bufferSubData(u.type,m,e);x.freeType(e)}return l};
c.profile&&(l.stats=u.stats);l.destroy=function(){f(u)};return l},createStream:function(a,b){var c=t.pop();c||(c=new g(a));c.bind();n(c,b,35040,0,1,!1);return c},destroyStream:function(a){t.push(a)},clear:function(){S(q).forEach(f);t.forEach(f)},getBuffer:function(a){return a&&a._buffer instanceof g?a._buffer:null},restore:function(){S(q).forEach(function(b){b.buffer=a.createBuffer();a.bindBuffer(b.type,b.buffer);a.bufferData(b.type,b.persistentData||b.byteLength,b.usage)})},_initBuffer:n}}function Hb(a,
b,c,e){function g(a){this.id=r++;f[this.id]=this;this.buffer=a;this.primType=4;this.type=this.vertCount=0}function d(e,d,g,h,l,u,v){e.buffer.bind();if(d){var f=v;v||M(d)&&(!ma(d)||M(d.data))||(f=b.oes_element_index_uint?5125:5123);c._initBuffer(e.buffer,d,g,f,3)}else a.bufferData(34963,u,g),e.buffer.dtype=f||5121,e.buffer.usage=g,e.buffer.dimension=3,e.buffer.byteLength=u;f=v;if(!v){switch(e.buffer.dtype){case 5121:case 5120:f=5121;break;case 5123:case 5122:f=5123;break;case 5125:case 5124:f=5125}e.buffer.dtype=
f}e.type=f;d=l;0>d&&(d=e.buffer.byteLength,5123===f?d>>=1:5125===f&&(d>>=2));e.vertCount=d;d=h;0>h&&(d=4,h=e.buffer.dimension,1===h&&(d=0),2===h&&(d=1),3===h&&(d=4));e.primType=d}function n(a){e.elementsCount--;delete f[a.id];a.buffer.destroy();a.buffer=null}var f={},r=0,q={uint8:5121,uint16:5123};b.oes_element_index_uint&&(q.uint32=5125);g.prototype.bind=function(){this.buffer.bind()};var t=[];return{create:function(a,b){function k(a){if(a)if("number"===typeof a)h(a),l.primType=4,l.vertCount=a|0,
l.type=5121;else{var b=null,c=35044,e=-1,g=-1,f=0,m=0;if(Array.isArray(a)||M(a)||ma(a))b=a;else if("data"in a&&(b=a.data),"usage"in a&&(c=jb[a.usage]),"primitive"in a&&(e=Sa[a.primitive]),"count"in a&&(g=a.count|0),"type"in a&&(m=q[a.type]),"length"in a)f=a.length|0;else if(f=g,5123===m||5122===m)f*=2;else if(5125===m||5124===m)f*=4;d(l,b,c,e,g,f,m)}else h(),l.primType=4,l.vertCount=0,l.type=5121;return k}var h=c.create(null,34963,!0),l=new g(h._buffer);e.elementsCount++;k(a);k._reglType="elements";
k._elements=l;k.subdata=function(a,b){h.subdata(a,b);return k};k.destroy=function(){n(l)};return k},createStream:function(a){var b=t.pop();b||(b=new g(c.create(null,34963,!0,!1)._buffer));d(b,a,35040,-1,-1,0,0);return b},destroyStream:function(a){t.push(a)},getElements:function(a){return"function"===typeof a&&a._elements instanceof g?a._elements:null},clear:function(){S(f).forEach(n)}}}function kb(a){for(var b=x.allocType(5123,a.length),c=0;c<a.length;++c)if(isNaN(a[c]))b[c]=65535;else if(Infinity===
a[c])b[c]=31744;else if(-Infinity===a[c])b[c]=64512;else{lb[0]=a[c];var e=Ib[0],g=e>>>31<<15,d=(e<<1>>>24)-127,e=e>>13&1023;b[c]=-24>d?g:-14>d?g+(e+1024>>-14-d):15<d?g+31744:g+(d+15<<10)+e}return b}function pa(a){return Array.isArray(a)||M(a)}function Ea(a){return"[object "+a+"]"}function mb(a){return Array.isArray(a)&&(0===a.length||"number"===typeof a[0])}function nb(a){return Array.isArray(a)&&0!==a.length&&pa(a[0])?!0:!1}function na(a){return Object.prototype.toString.call(a)}function Ta(a){if(!a)return!1;
var b=na(a);return 0<=Jb.indexOf(b)?!0:mb(a)||nb(a)||ma(a)}function ob(a,b){36193===a.type?(a.data=kb(b),x.freeType(b)):a.data=b}function Ja(a,b,c,e,g,d){a="undefined"!==typeof y[a]?y[a]:L[a]*qa[b];d&&(a*=6);if(g){for(e=0;1<=c;)e+=a*c*c,c/=2;return e}return a*c*e}function Kb(a,b,c,e,g,d,n){function f(){this.format=this.internalformat=6408;this.type=5121;this.flipY=this.premultiplyAlpha=this.compressed=!1;this.unpackAlignment=1;this.colorSpace=37444;this.channels=this.height=this.width=0}function r(a,
b){a.internalformat=b.internalformat;a.format=b.format;a.type=b.type;a.compressed=b.compressed;a.premultiplyAlpha=b.premultiplyAlpha;a.flipY=b.flipY;a.unpackAlignment=b.unpackAlignment;a.colorSpace=b.colorSpace;a.width=b.width;a.height=b.height;a.channels=b.channels}function q(a,b){if("object"===typeof b&&b){"premultiplyAlpha"in b&&(a.premultiplyAlpha=b.premultiplyAlpha);"flipY"in b&&(a.flipY=b.flipY);"alignment"in b&&(a.unpackAlignment=b.alignment);"colorSpace"in b&&(a.colorSpace=wa[b.colorSpace]);
"type"in b&&(a.type=G[b.type]);var c=a.width,e=a.height,d=a.channels,h=!1;"shape"in b?(c=b.shape[0],e=b.shape[1],3===b.shape.length&&(d=b.shape[2],h=!0)):("radius"in b&&(c=e=b.radius),"width"in b&&(c=b.width),"height"in b&&(e=b.height),"channels"in b&&(d=b.channels,h=!0));a.width=c|0;a.height=e|0;a.channels=d|0;c=!1;"format"in b&&(c=b.format,e=a.internalformat=U[c],a.format=Lb[e],c in G&&!("type"in b)&&(a.type=G[c]),c in W&&(a.compressed=!0),c=!0);!h&&c?a.channels=L[a.format]:h&&!c&&a.channels!==
La[a.format]&&(a.format=a.internalformat=La[a.channels])}}function t(b){a.pixelStorei(37440,b.flipY);a.pixelStorei(37441,b.premultiplyAlpha);a.pixelStorei(37443,b.colorSpace);a.pixelStorei(3317,b.unpackAlignment)}function m(){f.call(this);this.yOffset=this.xOffset=0;this.data=null;this.needsFree=!1;this.element=null;this.needsCopy=!1}function C(a,b){var c=null;Ta(b)?c=b:b&&(q(a,b),"x"in b&&(a.xOffset=b.x|0),"y"in b&&(a.yOffset=b.y|0),Ta(b.data)&&(c=b.data));if(b.copy){var e=g.viewportWidth,d=g.viewportHeight;
a.width=a.width||e-a.xOffset;a.height=a.height||d-a.yOffset;a.needsCopy=!0}else if(!c)a.width=a.width||1,a.height=a.height||1,a.channels=a.channels||4;else if(M(c))a.channels=a.channels||4,a.data=c,"type"in b||5121!==a.type||(a.type=Ia[Object.prototype.toString.call(c)]|0);else if(mb(c)){a.channels=a.channels||4;e=c;d=e.length;switch(a.type){case 5121:case 5123:case 5125:case 5126:d=x.allocType(a.type,d);d.set(e);a.data=d;break;case 36193:a.data=kb(e)}a.alignment=1;a.needsFree=!0}else if(ma(c)){e=
c.data;Array.isArray(e)||5121!==a.type||(a.type=Ia[Object.prototype.toString.call(e)]|0);var d=c.shape,h=c.stride,f,l,p,w;3===d.length?(p=d[2],w=h[2]):w=p=1;f=d[0];l=d[1];d=h[0];h=h[1];a.alignment=1;a.width=f;a.height=l;a.channels=p;a.format=a.internalformat=La[p];a.needsFree=!0;f=w;c=c.offset;p=a.width;w=a.height;l=a.channels;for(var z=x.allocType(36193===a.type?5126:a.type,p*w*l),I=0,fa=0;fa<w;++fa)for(var ga=0;ga<p;++ga)for(var xa=0;xa<l;++xa)z[I++]=e[d*ga+h*fa+f*xa+c];ob(a,z)}else if(na(c)===
Ua||na(c)===pb)na(c)===Ua?a.element=c:a.element=c.canvas,a.width=a.element.width,a.height=a.element.height,a.channels=4;else if(na(c)===qb)a.element=c,a.width=c.width,a.height=c.height,a.channels=4;else if(na(c)===rb)a.element=c,a.width=c.naturalWidth,a.height=c.naturalHeight,a.channels=4;else if(na(c)===sb)a.element=c,a.width=c.videoWidth,a.height=c.videoHeight,a.channels=4;else if(nb(c)){e=a.width||c[0].length;d=a.height||c.length;h=a.channels;h=pa(c[0][0])?h||c[0][0].length:h||1;f=Ma.shape(c);
p=1;for(w=0;w<f.length;++w)p*=f[w];p=x.allocType(36193===a.type?5126:a.type,p);Ma.flatten(c,f,"",p);ob(a,p);a.alignment=1;a.width=e;a.height=d;a.channels=h;a.format=a.internalformat=La[h];a.needsFree=!0}}function k(b,c,d,h,f){var g=b.element,l=b.data,k=b.internalformat,p=b.format,w=b.type,z=b.width,I=b.height;t(b);g?a.texSubImage2D(c,f,d,h,p,w,g):b.compressed?a.compressedTexSubImage2D(c,f,d,h,k,z,I,l):b.needsCopy?(e(),a.copyTexSubImage2D(c,f,d,h,b.xOffset,b.yOffset,z,I)):a.texSubImage2D(c,f,d,h,z,
I,p,w,l)}function h(){return P.pop()||new m}function l(a){a.needsFree&&x.freeType(a.data);m.call(a);P.push(a)}function u(){f.call(this);this.genMipmaps=!1;this.mipmapHint=4352;this.mipmask=0;this.images=Array(16)}function v(a,b,c){var d=a.images[0]=h();a.mipmask=1;d.width=a.width=b;d.height=a.height=c;d.channels=a.channels=4}function N(a,b){var c=null;if(Ta(b))c=a.images[0]=h(),r(c,a),C(c,b),a.mipmask=1;else if(q(a,b),Array.isArray(b.mipmap))for(var d=b.mipmap,e=0;e<d.length;++e)c=a.images[e]=h(),
r(c,a),c.width>>=e,c.height>>=e,C(c,d[e]),a.mipmask|=1<<e;else c=a.images[0]=h(),r(c,a),C(c,b),a.mipmask=1;r(a,a.images[0])}function B(b,c){for(var d=b.images,h=0;h<d.length&&d[h];++h){var f=d[h],g=c,l=h,k=f.element,p=f.data,w=f.internalformat,z=f.format,I=f.type,fa=f.width,ga=f.height,xa=f.channels;t(f);k?a.texImage2D(g,l,z,z,I,k):f.compressed?a.compressedTexImage2D(g,l,w,fa,ga,0,p):f.needsCopy?(e(),a.copyTexImage2D(g,l,z,f.xOffset,f.yOffset,fa,ga,0)):((f=!p)&&(p=x.zero.allocType(I,fa*ga*xa)),a.texImage2D(g,
l,z,fa,ga,0,z,I,p),f&&p&&x.zero.freeType(p))}}function D(){var a=tb.pop()||new u;f.call(a);for(var b=a.mipmask=0;16>b;++b)a.images[b]=null;return a}function ib(a){for(var b=a.images,c=0;c<b.length;++c)b[c]&&l(b[c]),b[c]=null;tb.push(a)}function y(){this.magFilter=this.minFilter=9728;this.wrapT=this.wrapS=33071;this.anisotropic=1;this.genMipmaps=!1;this.mipmapHint=4352}function O(a,b){"min"in b&&(a.minFilter=Va[b.min],0<=Mb.indexOf(a.minFilter)&&!("faces"in b)&&(a.genMipmaps=!0));"mag"in b&&(a.magFilter=
V[b.mag]);var c=a.wrapS,d=a.wrapT;if("wrap"in b){var e=b.wrap;"string"===typeof e?c=d=K[e]:Array.isArray(e)&&(c=K[e[0]],d=K[e[1]])}else"wrapS"in b&&(c=K[b.wrapS]),"wrapT"in b&&(d=K[b.wrapT]);a.wrapS=c;a.wrapT=d;"anisotropic"in b&&(a.anisotropic=b.anisotropic);if("mipmap"in b){c=!1;switch(typeof b.mipmap){case "string":a.mipmapHint=ua[b.mipmap];c=a.genMipmaps=!0;break;case "boolean":c=a.genMipmaps=b.mipmap;break;case "object":a.genMipmaps=!1,c=!0}!c||"min"in b||(a.minFilter=9984)}}function R(c,d){a.texParameteri(d,
10241,c.minFilter);a.texParameteri(d,10240,c.magFilter);a.texParameteri(d,10242,c.wrapS);a.texParameteri(d,10243,c.wrapT);b.ext_texture_filter_anisotropic&&a.texParameteri(d,34046,c.anisotropic);c.genMipmaps&&(a.hint(33170,c.mipmapHint),a.generateMipmap(d))}function F(b){f.call(this);this.mipmask=0;this.internalformat=6408;this.id=ya++;this.refCount=1;this.target=b;this.texture=a.createTexture();this.unit=-1;this.bindCount=0;this.texInfo=new y;n.profile&&(this.stats={size:0})}function T(b){a.activeTexture(33984);
a.bindTexture(b.target,b.texture)}function Aa(){var b=ha[0];b?a.bindTexture(b.target,b.texture):a.bindTexture(3553,null)}function A(b){var c=b.texture,e=b.unit,h=b.target;0<=e&&(a.activeTexture(33984+e),a.bindTexture(h,null),ha[e]=null);a.deleteTexture(c);b.texture=null;b.params=null;b.pixels=null;b.refCount=0;delete X[b.id];d.textureCount--}var ua={"don't care":4352,"dont care":4352,nice:4354,fast:4353},K={repeat:10497,clamp:33071,mirror:33648},V={nearest:9728,linear:9729},Va=E({mipmap:9987,"nearest mipmap nearest":9984,
"linear mipmap nearest":9985,"nearest mipmap linear":9986,"linear mipmap linear":9987},V),wa={none:0,browser:37444},G={uint8:5121,rgba4:32819,rgb565:33635,"rgb5 a1":32820},U={alpha:6406,luminance:6409,"luminance alpha":6410,rgb:6407,rgba:6408,rgba4:32854,"rgb5 a1":32855,rgb565:36194},W={};b.ext_srgb&&(U.srgb=35904,U.srgba=35906);b.oes_texture_float&&(G.float32=G["float"]=5126);b.oes_texture_half_float&&(G.float16=G["half float"]=36193);b.webgl_depth_texture&&(E(U,{depth:6402,"depth stencil":34041}),
E(G,{uint16:5123,uint32:5125,"depth stencil":34042}));b.webgl_compressed_texture_s3tc&&E(W,{"rgb s3tc dxt1":33776,"rgba s3tc dxt1":33777,"rgba s3tc dxt3":33778,"rgba s3tc dxt5":33779});b.webgl_compressed_texture_atc&&E(W,{"rgb atc":35986,"rgba atc explicit alpha":35987,"rgba atc interpolated alpha":34798});b.webgl_compressed_texture_pvrtc&&E(W,{"rgb pvrtc 4bppv1":35840,"rgb pvrtc 2bppv1":35841,"rgba pvrtc 4bppv1":35842,"rgba pvrtc 2bppv1":35843});b.webgl_compressed_texture_etc1&&(W["rgb etc1"]=36196);
var Nb=Array.prototype.slice.call(a.getParameter(34467));Object.keys(W).forEach(function(a){var b=W[a];0<=Nb.indexOf(b)&&(U[a]=b)});var ca=Object.keys(U);c.textureFormats=ca;var J=[];Object.keys(U).forEach(function(a){J[U[a]]=a});var da=[];Object.keys(G).forEach(function(a){da[G[a]]=a});var oa=[];Object.keys(V).forEach(function(a){oa[V[a]]=a});var za=[];Object.keys(Va).forEach(function(a){za[Va[a]]=a});var ka=[];Object.keys(K).forEach(function(a){ka[K[a]]=a});var Lb=ca.reduce(function(a,b){var c=
U[b];6409===c||6406===c||6409===c||6410===c||6402===c||34041===c?a[c]=c:32855===c||0<=b.indexOf("rgba")?a[c]=6408:a[c]=6407;return a},{}),P=[],tb=[],ya=0,X={},ea=c.maxTextureUnits,ha=Array(ea).map(function(){return null});E(F.prototype,{bind:function(){this.bindCount+=1;var b=this.unit;if(0>b){for(var c=0;c<ea;++c){var e=ha[c];if(e){if(0<e.bindCount)continue;e.unit=-1}ha[c]=this;b=c;break}n.profile&&d.maxTextureUnits<b+1&&(d.maxTextureUnits=b+1);this.unit=b;a.activeTexture(33984+b);a.bindTexture(this.target,
this.texture)}return b},unbind:function(){--this.bindCount},decRef:function(){0>=--this.refCount&&A(this)}});n.profile&&(d.getTotalTextureSize=function(){var a=0;Object.keys(X).forEach(function(b){a+=X[b].stats.size});return a});return{create2D:function(b,c){function e(a,b){var c=f.texInfo;y.call(c);var d=D();"number"===typeof a?"number"===typeof b?v(d,a|0,b|0):v(d,a|0,a|0):a?(O(c,a),N(d,a)):v(d,1,1);c.genMipmaps&&(d.mipmask=(d.width<<1)-1);f.mipmask=d.mipmask;r(f,d);f.internalformat=d.internalformat;
e.width=d.width;e.height=d.height;T(f);B(d,3553);R(c,3553);Aa();ib(d);n.profile&&(f.stats.size=Ja(f.internalformat,f.type,d.width,d.height,c.genMipmaps,!1));e.format=J[f.internalformat];e.type=da[f.type];e.mag=oa[c.magFilter];e.min=za[c.minFilter];e.wrapS=ka[c.wrapS];e.wrapT=ka[c.wrapT];return e}var f=new F(3553);X[f.id]=f;d.textureCount++;e(b,c);e.subimage=function(a,b,c,d){b|=0;c|=0;d|=0;var p=h();r(p,f);p.width=0;p.height=0;C(p,a);p.width=p.width||(f.width>>d)-b;p.height=p.height||(f.height>>d)-
c;T(f);k(p,3553,b,c,d);Aa();l(p);return e};e.resize=function(b,c){var d=b|0,h=c|0||d;if(d===f.width&&h===f.height)return e;e.width=f.width=d;e.height=f.height=h;T(f);for(var p,w=f.channels,z=f.type,I=0;f.mipmask>>I;++I){var fa=d>>I,ga=h>>I;if(!fa||!ga)break;p=x.zero.allocType(z,fa*ga*w);a.texImage2D(3553,I,f.format,fa,ga,0,f.format,f.type,p);p&&x.zero.freeType(p)}Aa();n.profile&&(f.stats.size=Ja(f.internalformat,f.type,d,h,!1,!1));return e};e._reglType="texture2d";e._texture=f;n.profile&&(e.stats=
f.stats);e.destroy=function(){f.decRef()};return e},createCube:function(b,c,e,f,g,ua){function A(a,b,c,d,e,f){var H,Y=m.texInfo;y.call(Y);for(H=0;6>H;++H)p[H]=D();if("number"===typeof a||!a)for(a=a|0||1,H=0;6>H;++H)v(p[H],a,a);else if("object"===typeof a)if(b)N(p[0],a),N(p[1],b),N(p[2],c),N(p[3],d),N(p[4],e),N(p[5],f);else if(O(Y,a),q(m,a),"faces"in a)for(a=a.faces,H=0;6>H;++H)r(p[H],m),N(p[H],a[H]);else for(H=0;6>H;++H)N(p[H],a);r(m,p[0]);m.mipmask=Y.genMipmaps?(p[0].width<<1)-1:p[0].mipmask;m.internalformat=
p[0].internalformat;A.width=p[0].width;A.height=p[0].height;T(m);for(H=0;6>H;++H)B(p[H],34069+H);R(Y,34067);Aa();n.profile&&(m.stats.size=Ja(m.internalformat,m.type,A.width,A.height,Y.genMipmaps,!0));A.format=J[m.internalformat];A.type=da[m.type];A.mag=oa[Y.magFilter];A.min=za[Y.minFilter];A.wrapS=ka[Y.wrapS];A.wrapT=ka[Y.wrapT];for(H=0;6>H;++H)ib(p[H]);return A}var m=new F(34067);X[m.id]=m;d.cubeCount++;var p=Array(6);A(b,c,e,f,g,ua);A.subimage=function(a,b,c,p,d){c|=0;p|=0;d|=0;var e=h();r(e,m);
e.width=0;e.height=0;C(e,b);e.width=e.width||(m.width>>d)-c;e.height=e.height||(m.height>>d)-p;T(m);k(e,34069+a,c,p,d);Aa();l(e);return A};A.resize=function(b){b|=0;if(b!==m.width){A.width=m.width=b;A.height=m.height=b;T(m);for(var c=0;6>c;++c)for(var p=0;m.mipmask>>p;++p)a.texImage2D(34069+c,p,m.format,b>>p,b>>p,0,m.format,m.type,null);Aa();n.profile&&(m.stats.size=Ja(m.internalformat,m.type,A.width,A.height,!1,!0));return A}};A._reglType="textureCube";A._texture=m;n.profile&&(A.stats=m.stats);A.destroy=
function(){m.decRef()};return A},clear:function(){for(var b=0;b<ea;++b)a.activeTexture(33984+b),a.bindTexture(3553,null),ha[b]=null;S(X).forEach(A);d.cubeCount=0;d.textureCount=0},getTexture:function(a){return null},restore:function(){for(var b=0;b<ea;++b){var c=ha[b];c&&(c.bindCount=0,c.unit=-1,ha[b]=null)}S(X).forEach(function(b){b.texture=a.createTexture();a.bindTexture(b.target,b.texture);for(var c=0;32>c;++c)if(0!==(b.mipmask&1<<c))if(3553===b.target)a.texImage2D(3553,c,b.internalformat,b.width>>
c,b.height>>c,0,b.internalformat,b.type,null);else for(var d=0;6>d;++d)a.texImage2D(34069+d,c,b.internalformat,b.width>>c,b.height>>c,0,b.internalformat,b.type,null);R(b.texInfo,b.target)})}}}function Ob(a,b,c,e,g,d){function n(a,b,c){this.target=a;this.texture=b;this.renderbuffer=c;var d=a=0;b?(a=b.width,d=b.height):c&&(a=c.width,d=c.height);this.width=a;this.height=d}function f(a){a&&(a.texture&&a.texture._texture.decRef(),a.renderbuffer&&a.renderbuffer._renderbuffer.decRef())}function r(a,b,c){a&&
(a.texture?a.texture._texture.refCount+=1:a.renderbuffer._renderbuffer.refCount+=1)}function q(b,c){c&&(c.texture?a.framebufferTexture2D(36160,b,c.target,c.texture._texture.texture,0):a.framebufferRenderbuffer(36160,b,36161,c.renderbuffer._renderbuffer.renderbuffer))}function t(a){var b=3553,c=null,d=null,e=a;"object"===typeof a&&(e=a.data,"target"in a&&(b=a.target|0));a=e._reglType;"texture2d"===a?c=e:"textureCube"===a?c=e:"renderbuffer"===a&&(d=e,b=36161);return new n(b,c,d)}function m(a,b,c,d,
f){if(c)return a=e.create2D({width:a,height:b,format:d,type:f}),a._texture.refCount=0,new n(3553,a,null);a=g.create({width:a,height:b,format:d});a._renderbuffer.refCount=0;return new n(36161,null,a)}function C(a){return a&&(a.texture||a.renderbuffer)}function k(a,b,c){a&&(a.texture?a.texture.resize(b,c):a.renderbuffer&&a.renderbuffer.resize(b,c),a.width=b,a.height=c)}function h(){this.id=O++;R[this.id]=this;this.framebuffer=a.createFramebuffer();this.height=this.width=0;this.colorAttachments=[];this.depthStencilAttachment=
this.stencilAttachment=this.depthAttachment=null}function l(a){a.colorAttachments.forEach(f);f(a.depthAttachment);f(a.stencilAttachment);f(a.depthStencilAttachment)}function u(b){a.deleteFramebuffer(b.framebuffer);b.framebuffer=null;d.framebufferCount--;delete R[b.id]}function v(b){var d;a.bindFramebuffer(36160,b.framebuffer);var e=b.colorAttachments;for(d=0;d<e.length;++d)q(36064+d,e[d]);for(d=e.length;d<c.maxColorAttachments;++d)a.framebufferTexture2D(36160,36064+d,3553,null,0);a.framebufferTexture2D(36160,
33306,3553,null,0);a.framebufferTexture2D(36160,36096,3553,null,0);a.framebufferTexture2D(36160,36128,3553,null,0);q(36096,b.depthAttachment);q(36128,b.stencilAttachment);q(33306,b.depthStencilAttachment);a.checkFramebufferStatus(36160);a.isContextLost();a.bindFramebuffer(36160,B.next?B.next.framebuffer:null);B.cur=B.next;a.getError()}function N(a,b){function c(a,b){var d,f=0,h=0,g=!0,k=!0;d=null;var q=!0,u="rgba",n="uint8",N=1,da=null,oa=null,B=null,ka=!1;if("number"===typeof a)f=a|0,h=b|0||f;else if(a){"shape"in
a?(h=a.shape,f=h[0],h=h[1]):("radius"in a&&(f=h=a.radius),"width"in a&&(f=a.width),"height"in a&&(h=a.height));if("color"in a||"colors"in a)d=a.color||a.colors,Array.isArray(d);if(!d){"colorCount"in a&&(N=a.colorCount|0);"colorTexture"in a&&(q=!!a.colorTexture,u="rgba4");if("colorType"in a&&(n=a.colorType,!q))if("half float"===n||"float16"===n)u="rgba16f";else if("float"===n||"float32"===n)u="rgba32f";"colorFormat"in a&&(u=a.colorFormat,0<=x.indexOf(u)?q=!0:0<=D.indexOf(u)&&(q=!1))}if("depthTexture"in
a||"depthStencilTexture"in a)ka=!(!a.depthTexture&&!a.depthStencilTexture);"depth"in a&&("boolean"===typeof a.depth?g=a.depth:(da=a.depth,k=!1));"stencil"in a&&("boolean"===typeof a.stencil?k=a.stencil:(oa=a.stencil,g=!1));"depthStencil"in a&&("boolean"===typeof a.depthStencil?g=k=a.depthStencil:(B=a.depthStencil,k=g=!1))}else f=h=1;var F=null,y=null,E=null,T=null;if(Array.isArray(d))F=d.map(t);else if(d)F=[t(d)];else for(F=Array(N),d=0;d<N;++d)F[d]=m(f,h,q,u,n);f=f||F[0].width;h=h||F[0].height;da?
y=t(da):g&&!k&&(y=m(f,h,ka,"depth","uint32"));oa?E=t(oa):k&&!g&&(E=m(f,h,!1,"stencil","uint8"));B?T=t(B):!da&&!oa&&k&&g&&(T=m(f,h,ka,"depth stencil","depth stencil"));g=null;for(d=0;d<F.length;++d)r(F[d],f,h),F[d]&&F[d].texture&&(k=Wa[F[d].texture._texture.format]*Na[F[d].texture._texture.type],null===g&&(g=k));r(y,f,h);r(E,f,h);r(T,f,h);l(e);e.width=f;e.height=h;e.colorAttachments=F;e.depthAttachment=y;e.stencilAttachment=E;e.depthStencilAttachment=T;c.color=F.map(C);c.depth=C(y);c.stencil=C(E);
c.depthStencil=C(T);c.width=e.width;c.height=e.height;v(e);return c}var e=new h;d.framebufferCount++;c(a,b);return E(c,{resize:function(a,b){var d=Math.max(a|0,1),f=Math.max(b|0||d,1);if(d===e.width&&f===e.height)return c;for(var h=e.colorAttachments,g=0;g<h.length;++g)k(h[g],d,f);k(e.depthAttachment,d,f);k(e.stencilAttachment,d,f);k(e.depthStencilAttachment,d,f);e.width=c.width=d;e.height=c.height=f;v(e);return c},_reglType:"framebuffer",_framebuffer:e,destroy:function(){u(e);l(e)},use:function(a){B.setFBO({framebuffer:c},
a)}})}var B={cur:null,next:null,dirty:!1,setFBO:null},x=["rgba"],D=["rgba4","rgb565","rgb5 a1"];b.ext_srgb&&D.push("srgba");b.ext_color_buffer_half_float&&D.push("rgba16f","rgb16f");b.webgl_color_buffer_float&&D.push("rgba32f");var y=["uint8"];b.oes_texture_half_float&&y.push("half float","float16");b.oes_texture_float&&y.push("float","float32");var O=0,R={};return E(B,{getFramebuffer:function(a){return"function"===typeof a&&"framebuffer"===a._reglType&&(a=a._framebuffer,a instanceof h)?a:null},create:N,
createCube:function(a){function b(a){var d,f={color:null},h=0,g=null;d="rgba";var l="uint8",m=1;if("number"===typeof a)h=a|0;else if(a){"shape"in a?h=a.shape[0]:("radius"in a&&(h=a.radius|0),"width"in a?h=a.width|0:"height"in a&&(h=a.height|0));if("color"in a||"colors"in a)g=a.color||a.colors,Array.isArray(g);g||("colorCount"in a&&(m=a.colorCount|0),"colorType"in a&&(l=a.colorType),"colorFormat"in a&&(d=a.colorFormat));"depth"in a&&(f.depth=a.depth);"stencil"in a&&(f.stencil=a.stencil);"depthStencil"in
a&&(f.depthStencil=a.depthStencil)}else h=1;if(g)if(Array.isArray(g))for(a=[],d=0;d<g.length;++d)a[d]=g[d];else a=[g];else for(a=Array(m),g={radius:h,format:d,type:l},d=0;d<m;++d)a[d]=e.createCube(g);f.color=Array(a.length);for(d=0;d<a.length;++d)m=a[d],h=h||m.width,f.color[d]={target:34069,data:a[d]};for(d=0;6>d;++d){for(m=0;m<a.length;++m)f.color[m].target=34069+d;0<d&&(f.depth=c[0].depth,f.stencil=c[0].stencil,f.depthStencil=c[0].depthStencil);if(c[d])c[d](f);else c[d]=N(f)}return E(b,{width:h,
height:h,color:a})}var c=Array(6);b(a);return E(b,{faces:c,resize:function(a){var d=a|0;if(d===b.width)return b;var e=b.color;for(a=0;a<e.length;++a)e[a].resize(d);for(a=0;6>a;++a)c[a].resize(d);b.width=b.height=d;return b},_reglType:"framebufferCube",destroy:function(){c.forEach(function(a){a.destroy()})}})},clear:function(){S(R).forEach(u)},restore:function(){B.cur=null;B.next=null;B.dirty=!0;S(R).forEach(function(b){b.framebuffer=a.createFramebuffer();v(b)})}})}function ub(){this.w=this.z=this.y=
this.x=this.state=0;this.buffer=null;this.size=0;this.normalized=!1;this.type=5126;this.divisor=this.stride=this.offset=0}function Pb(a,b,c,e){a=c.maxAttributes;b=Array(a);for(c=0;c<a;++c)b[c]=new ub;return{Record:ub,scope:{},state:b}}function Qb(a,b,c,e){function g(a,b,c,d){this.name=a;this.id=b;this.location=c;this.info=d}function d(a,b){for(var c=0;c<a.length;++c)if(a[c].id===b.id){a[c].location=b.location;return}a.push(b)}function n(c,d,e){e=35632===c?q:t;var f=e[d];if(!f){var g=b.str(d),f=a.createShader(c);
a.shaderSource(f,g);a.compileShader(f);e[d]=f}return f}function f(a,b){this.id=k++;this.fragId=a;this.vertId=b;this.program=null;this.uniforms=[];this.attributes=[];e.profile&&(this.stats={uniformsCount:0,attributesCount:0})}function r(c,f){var m,k;m=n(35632,c.fragId);k=n(35633,c.vertId);var q=c.program=a.createProgram();a.attachShader(q,m);a.attachShader(q,k);a.linkProgram(q);var r=a.getProgramParameter(q,35718);e.profile&&(c.stats.uniformsCount=r);var t=c.uniforms;for(m=0;m<r;++m)if(k=a.getActiveUniform(q,
m))if(1<k.size)for(var C=0;C<k.size;++C){var y=k.name.replace("[0]","["+C+"]");d(t,new g(y,b.id(y),a.getUniformLocation(q,y),k))}else d(t,new g(k.name,b.id(k.name),a.getUniformLocation(q,k.name),k));r=a.getProgramParameter(q,35721);e.profile&&(c.stats.attributesCount=r);t=c.attributes;for(m=0;m<r;++m)(k=a.getActiveAttrib(q,m))&&d(t,new g(k.name,b.id(k.name),a.getAttribLocation(q,k.name),k))}var q={},t={},m={},C=[],k=0;e.profile&&(c.getMaxUniformsCount=function(){var a=0;C.forEach(function(b){b.stats.uniformsCount>
a&&(a=b.stats.uniformsCount)});return a},c.getMaxAttributesCount=function(){var a=0;C.forEach(function(b){b.stats.attributesCount>a&&(a=b.stats.attributesCount)});return a});return{clear:function(){var b=a.deleteShader.bind(a);S(q).forEach(b);q={};S(t).forEach(b);t={};C.forEach(function(b){a.deleteProgram(b.program)});C.length=0;m={};c.shaderCount=0},program:function(a,b,d){var e=m[b];e||(e=m[b]={});var g=e[a];g||(g=new f(b,a),c.shaderCount++,r(g,d),e[a]=g,C.push(g));return g},restore:function(){q=
{};t={};for(var a=0;a<C.length;++a)r(C[a])},shader:n,frag:-1,vert:-1}}function Rb(a,b,c,e,g,d,n){function f(d){var f;f=null===b.next?5121:b.next.colorAttachments[0].texture._texture.type;var g=0,r=0,k=e.framebufferWidth,h=e.framebufferHeight,l=null;M(d)?l=d:d&&(g=d.x|0,r=d.y|0,k=(d.width||e.framebufferWidth-g)|0,h=(d.height||e.framebufferHeight-r)|0,l=d.data||null);c();d=k*h*4;l||(5121===f?l=new Uint8Array(d):5126===f&&(l=l||new Float32Array(d)));a.pixelStorei(3333,4);a.readPixels(g,r,k,h,6408,f,
l);return l}function r(a){var c;b.setFBO({framebuffer:a.framebuffer},function(){c=f(a)});return c}return function(a){return a&&"framebuffer"in a?r(a):f(a)}}function Ba(a){return Array.prototype.slice.call(a)}function Ca(a){return Ba(a).join("")}function Sb(){function a(){var a=[],b=[];return E(function(){a.push.apply(a,Ba(arguments))},{def:function(){var d="v"+c++;b.push(d);0<arguments.length&&(a.push(d,"="),a.push.apply(a,Ba(arguments)),a.push(";"));return d},toString:function(){return Ca([0<b.length?
"var "+b+";":"",Ca(a)])}})}function b(){function b(a,e){d(a,e,"=",c.def(a,e),";")}var c=a(),d=a(),e=c.toString,g=d.toString;return E(function(){c.apply(c,Ba(arguments))},{def:c.def,entry:c,exit:d,save:b,set:function(a,d,e){b(a,d);c(a,d,"=",e,";")},toString:function(){return e()+g()}})}var c=0,e=[],g=[],d=a(),n={};return{global:d,link:function(a){for(var b=0;b<g.length;++b)if(g[b]===a)return e[b];b="g"+c++;e.push(b);g.push(a);return b},block:a,proc:function(a,c){function d(){var a="a"+e.length;e.push(a);
return a}var e=[];c=c||0;for(var g=0;g<c;++g)d();var g=b(),C=g.toString;return n[a]=E(g,{arg:d,toString:function(){return Ca(["function(",e.join(),"){",C(),"}"])}})},scope:b,cond:function(){var a=Ca(arguments),c=b(),d=b(),e=c.toString,g=d.toString;return E(c,{then:function(){c.apply(c,Ba(arguments));return this},"else":function(){d.apply(d,Ba(arguments));return this},toString:function(){var b=g();b&&(b="else{"+b+"}");return Ca(["if(",a,"){",e(),"}",b])}})},compile:function(){var a=['"use strict";',
d,"return {"];Object.keys(n).forEach(function(b){a.push('"',b,'":',n[b].toString(),",")});a.push("}");var b=Ca(a).replace(/;/g,";\n").replace(/}/g,"}\n").replace(/{/g,"{\n");return Function.apply(null,e.concat(b)).apply(null,g)}}}function Oa(a){return Array.isArray(a)||M(a)||ma(a)}function vb(a){return a.sort(function(a,c){return"viewport"===a?-1:"viewport"===c?1:a<c?-1:1})}function Z(a,b,c,e){this.thisDep=a;this.contextDep=b;this.propDep=c;this.append=e}function va(a){return a&&!(a.thisDep||a.contextDep||
a.propDep)}function D(a){return new Z(!1,!1,!1,a)}function P(a,b){var c=a.type;return 0===c?(c=a.data.length,new Z(!0,1<=c,2<=c,b)):4===c?(c=a.data,new Z(c.thisDep,c.contextDep,c.propDep,b)):new Z(3===c,2===c,1===c,b)}function Tb(a,b,c,e,g,d,n,f,r,q,t,m,C,k,h){function l(a){return a.replace(".","_")}function u(a,b,c){var d=l(a);Ka.push(a);Fa[d]=ra[d]=!!c;sa[d]=b}function v(a,b,c){var d=l(a);Ka.push(a);Array.isArray(c)?(ra[d]=c.slice(),Fa[d]=c.slice()):ra[d]=Fa[d]=c;ta[d]=b}function N(){var a=Sb(),
c=a.link,d=a.global;a.id=qa++;a.batchId="0";var e=c(na),f=a.shared={props:"a0"};Object.keys(na).forEach(function(a){f[a]=d.def(e,".",a)});var g=a.next={},xa=a.current={};Object.keys(ta).forEach(function(a){Array.isArray(ra[a])&&(g[a]=d.def(f.next,".",a),xa[a]=d.def(f.current,".",a))});var H=a.constants={};Object.keys(aa).forEach(function(a){H[a]=d.def(JSON.stringify(aa[a]))});a.invoke=function(b,d){switch(d.type){case 0:var e=["this",f.context,f.props,a.batchId];return b.def(c(d.data),".call(",e.slice(0,
Math.max(d.data.length+1,4)),")");case 1:return b.def(f.props,d.data);case 2:return b.def(f.context,d.data);case 3:return b.def("this",d.data);case 4:return d.data.append(a,b),d.data.ref}};a.attribCache={};var Y={};a.scopeAttrib=function(a){a=b.id(a);if(a in Y)return Y[a];var d=q.scope[a];d||(d=q.scope[a]=new ya);return Y[a]=c(d)};return a}function B(a){var b=a["static"];a=a.dynamic;var c;if("profile"in b){var d=!!b.profile;c=D(function(a,b){return d});c.enable=d}else if("profile"in a){var e=a.profile;
c=P(e,function(a,b){return a.invoke(b,e)})}return c}function y(a,b){var c=a["static"],d=a.dynamic;if("framebuffer"in c){var e=c.framebuffer;return e?(e=f.getFramebuffer(e),D(function(a,b){var c=a.link(e),d=a.shared;b.set(d.framebuffer,".next",c);d=d.context;b.set(d,".framebufferWidth",c+".width");b.set(d,".framebufferHeight",c+".height");return c})):D(function(a,b){var c=a.shared;b.set(c.framebuffer,".next","null");c=c.context;b.set(c,".framebufferWidth",c+".drawingBufferWidth");b.set(c,".framebufferHeight",
c+".drawingBufferHeight");return"null"})}if("framebuffer"in d){var g=d.framebuffer;return P(g,function(a,b){var c=a.invoke(b,g),d=a.shared,e=d.framebuffer,c=b.def(e,".getFramebuffer(",c,")");b.set(e,".next",c);d=d.context;b.set(d,".framebufferWidth",c+"?"+c+".width:"+d+".drawingBufferWidth");b.set(d,".framebufferHeight",c+"?"+c+".height:"+d+".drawingBufferHeight");return c})}return null}function x(a,b,c){function d(a){if(a in e){var c=e[a];a=!0;var p=c.x|0,ba=c.y|0,g,h;"width"in c?g=c.width|0:a=!1;
"height"in c?h=c.height|0:a=!1;return new Z(!a&&b&&b.thisDep,!a&&b&&b.contextDep,!a&&b&&b.propDep,function(a,b){var d=a.shared.context,e=g;"width"in c||(e=b.def(d,".","framebufferWidth","-",p));var f=h;"height"in c||(f=b.def(d,".","framebufferHeight","-",ba));return[p,ba,e,f]})}if(a in f){var z=f[a];a=P(z,function(a,b){var c=a.invoke(b,z),d=a.shared.context,e=b.def(c,".x|0"),p=b.def(c,".y|0"),Y=b.def('"width" in ',c,"?",c,".width|0:","(",d,".","framebufferWidth","-",e,")"),c=b.def('"height" in ',
c,"?",c,".height|0:","(",d,".","framebufferHeight","-",p,")");return[e,p,Y,c]});b&&(a.thisDep=a.thisDep||b.thisDep,a.contextDep=a.contextDep||b.contextDep,a.propDep=a.propDep||b.propDep);return a}return b?new Z(b.thisDep,b.contextDep,b.propDep,function(a,b){var c=a.shared.context;return[0,0,b.def(c,".","framebufferWidth"),b.def(c,".","framebufferHeight")]}):null}var e=a["static"],f=a.dynamic;if(a=d("viewport")){var g=a;a=new Z(a.thisDep,a.contextDep,a.propDep,function(a,b){var c=g.append(a,b),d=a.shared.context;
b.set(d,".viewportWidth",c[2]);b.set(d,".viewportHeight",c[3]);return c})}return{viewport:a,scissor_box:d("scissor.box")}}function E(a){function c(a){if(a in d){var p=b.id(d[a]);a=D(function(){return p});a.id=p;return a}if(a in e){var f=e[a];return P(f,function(a,b){var c=a.invoke(b,f);return b.def(a.shared.strings,".id(",c,")")})}return null}var d=a["static"],e=a.dynamic,f=c("frag"),g=c("vert"),h=null;va(f)&&va(g)?(h=t.program(g.id,f.id),a=D(function(a,b){return a.link(h)})):a=new Z(f&&f.thisDep||
g&&g.thisDep,f&&f.contextDep||g&&g.contextDep,f&&f.propDep||g&&g.propDep,function(a,b){var c=a.shared.shader,d;d=f?f.append(a,b):b.def(c,".","frag");var e;e=g?g.append(a,b):b.def(c,".","vert");return b.def(c+".program("+e+","+d+")")});return{frag:f,vert:g,progVar:a,program:h}}function O(a,b){function c(a,b){if(a in e){var d=e[a]|0;return D(function(a,c){b&&(a.OFFSET=d);return d})}if(a in f){var p=f[a];return P(p,function(a,c){var d=a.invoke(c,p);b&&(a.OFFSET=d);return d})}return b&&g?D(function(a,
b){a.OFFSET="0";return 0}):null}var e=a["static"],f=a.dynamic,g=function(){if("elements"in e){var a=e.elements;Oa(a)?a=d.getElements(d.create(a,!0)):a&&(a=d.getElements(a));var b=D(function(b,c){if(a){var d=b.link(a);return b.ELEMENTS=d}return b.ELEMENTS=null});b.value=a;return b}if("elements"in f){var c=f.elements;return P(c,function(a,b){var d=a.shared,e=d.isBufferArgs,d=d.elements,p=a.invoke(b,c),f=b.def("null"),e=b.def(e,"(",p,")"),p=a.cond(e).then(f,"=",d,".createStream(",p,");")["else"](f,"=",
d,".getElements(",p,");");b.entry(p);b.exit(a.cond(e).then(d,".destroyStream(",f,");"));return a.ELEMENTS=f})}return null}(),h=c("offset",!0);return{elements:g,primitive:function(){if("primitive"in e){var a=e.primitive;return D(function(b,c){return Sa[a]})}if("primitive"in f){var b=f.primitive;return P(b,function(a,c){var d=a.constants.primTypes,e=a.invoke(c,b);return c.def(d,"[",e,"]")})}return g?va(g)?g.value?D(function(a,b){return b.def(a.ELEMENTS,".primType")}):D(function(){return 4}):new Z(g.thisDep,
g.contextDep,g.propDep,function(a,b){var c=a.ELEMENTS;return b.def(c,"?",c,".primType:",4)}):null}(),count:function(){if("count"in e){var a=e.count|0;return D(function(){return a})}if("count"in f){var b=f.count;return P(b,function(a,c){return a.invoke(c,b)})}return g?va(g)?g?h?new Z(h.thisDep,h.contextDep,h.propDep,function(a,b){return b.def(a.ELEMENTS,".vertCount-",a.OFFSET)}):D(function(a,b){return b.def(a.ELEMENTS,".vertCount")}):D(function(){return-1}):new Z(g.thisDep||h.thisDep,g.contextDep||
h.contextDep,g.propDep||h.propDep,function(a,b){var c=a.ELEMENTS;return a.OFFSET?b.def(c,"?",c,".vertCount-",a.OFFSET,":-1"):b.def(c,"?",c,".vertCount:-1")}):null}(),instances:c("instances",!1),offset:h}}function R(a,b){var c=a["static"],d=a.dynamic,e={};Ka.forEach(function(a){function b(f,g){if(a in c){var w=f(c[a]);e[p]=D(function(){return w})}else if(a in d){var h=d[a];e[p]=P(h,function(a,b){return g(a,b,a.invoke(b,h))})}}var p=l(a);switch(a){case "cull.enable":case "blend.enable":case "dither":case "stencil.enable":case "depth.enable":case "scissor.enable":case "polygonOffset.enable":case "sample.alpha":case "sample.enable":case "depth.mask":return b(function(a){return a},
function(a,b,c){return c});case "depth.func":return b(function(a){return Xa[a]},function(a,b,c){return b.def(a.constants.compareFuncs,"[",c,"]")});case "depth.range":return b(function(a){return a},function(a,b,c){a=b.def("+",c,"[0]");b=b.def("+",c,"[1]");return[a,b]});case "blend.func":return b(function(a){return[Ga["srcRGB"in a?a.srcRGB:a.src],Ga["dstRGB"in a?a.dstRGB:a.dst],Ga["srcAlpha"in a?a.srcAlpha:a.src],Ga["dstAlpha"in a?a.dstAlpha:a.dst]]},function(a,b,c){function d(a,e){return b.def('"',
a,e,'" in ',c,"?",c,".",a,e,":",c,".",a)}a=a.constants.blendFuncs;var e=d("src","RGB"),p=d("dst","RGB"),e=b.def(a,"[",e,"]"),f=b.def(a,"[",d("src","Alpha"),"]"),p=b.def(a,"[",p,"]");a=b.def(a,"[",d("dst","Alpha"),"]");return[e,p,f,a]});case "blend.equation":return b(function(a){if("string"===typeof a)return[X[a],X[a]];if("object"===typeof a)return[X[a.rgb],X[a.alpha]]},function(a,b,c){var d=a.constants.blendEquations,e=b.def(),p=b.def();a=a.cond("typeof ",c,'==="string"');a.then(e,"=",p,"=",d,"[",
c,"];");a["else"](e,"=",d,"[",c,".rgb];",p,"=",d,"[",c,".alpha];");b(a);return[e,p]});case "blend.color":return b(function(a){return J(4,function(b){return+a[b]})},function(a,b,c){return J(4,function(a){return b.def("+",c,"[",a,"]")})});case "stencil.mask":return b(function(a){return a|0},function(a,b,c){return b.def(c,"|0")});case "stencil.func":return b(function(a){return[Xa[a.cmp||"keep"],a.ref||0,"mask"in a?a.mask:-1]},function(a,b,c){a=b.def('"cmp" in ',c,"?",a.constants.compareFuncs,"[",c,".cmp]",
":",7680);var d=b.def(c,".ref|0");b=b.def('"mask" in ',c,"?",c,".mask|0:-1");return[a,d,b]});case "stencil.opFront":case "stencil.opBack":return b(function(b){return["stencil.opBack"===a?1029:1028,Pa[b.fail||"keep"],Pa[b.zfail||"keep"],Pa[b.zpass||"keep"]]},function(b,c,d){function e(a){return c.def('"',a,'" in ',d,"?",p,"[",d,".",a,"]:",7680)}var p=b.constants.stencilOps;return["stencil.opBack"===a?1029:1028,e("fail"),e("zfail"),e("zpass")]});case "polygonOffset.offset":return b(function(a){return[a.factor|
0,a.units|0]},function(a,b,c){a=b.def(c,".factor|0");b=b.def(c,".units|0");return[a,b]});case "cull.face":return b(function(a){var b=0;"front"===a?b=1028:"back"===a&&(b=1029);return b},function(a,b,c){return b.def(c,'==="front"?',1028,":",1029)});case "lineWidth":return b(function(a){return a},function(a,b,c){return c});case "frontFace":return b(function(a){return wb[a]},function(a,b,c){return b.def(c+'==="cw"?2304:2305')});case "colorMask":return b(function(a){return a.map(function(a){return!!a})},
function(a,b,c){return J(4,function(a){return"!!"+c+"["+a+"]"})});case "sample.coverage":return b(function(a){return["value"in a?a.value:1,!!a.invert]},function(a,b,c){a=b.def('"value" in ',c,"?+",c,".value:1");b=b.def("!!",c,".invert");return[a,b]})}});return e}function F(a,b){var c=a["static"],d=a.dynamic,e={};Object.keys(c).forEach(function(a){var b=c[a],d;if("number"===typeof b||"boolean"===typeof b)d=D(function(){return b});else if("function"===typeof b){var p=b._reglType;if("texture2d"===p||
"textureCube"===p)d=D(function(a){return a.link(b)});else if("framebuffer"===p||"framebufferCube"===p)d=D(function(a){return a.link(b.color[0])})}else pa(b)&&(d=D(function(a){return a.global.def("[",J(b.length,function(a){return b[a]}),"]")}));d.value=b;e[a]=d});Object.keys(d).forEach(function(a){var b=d[a];e[a]=P(b,function(a,c){return a.invoke(c,b)})});return e}function T(a,c){var d=a["static"],e=a.dynamic,f={};Object.keys(d).forEach(function(a){var c=d[a],e=b.id(a),p=new ya;if(Oa(c))p.state=1,
p.buffer=g.getBuffer(g.create(c,34962,!1,!0)),p.type=0;else{var w=g.getBuffer(c);if(w)p.state=1,p.buffer=w,p.type=0;else if("constant"in c){var h=c.constant;p.buffer="null";p.state=2;"number"===typeof h?p.x=h:Da.forEach(function(a,b){b<h.length&&(p[a]=h[b])})}else{var w=Oa(c.buffer)?g.getBuffer(g.create(c.buffer,34962,!1,!0)):g.getBuffer(c.buffer),k=c.offset|0,m=c.stride|0,I=c.size|0,l=!!c.normalized,n=0;"type"in c&&(n=Ra[c.type]);c=c.divisor|0;p.buffer=w;p.state=1;p.size=I;p.normalized=l;p.type=
n||w.dtype;p.offset=k;p.stride=m;p.divisor=c}}f[a]=D(function(a,b){var c=a.attribCache;if(e in c)return c[e];var d={isStream:!1};Object.keys(p).forEach(function(a){d[a]=p[a]});p.buffer&&(d.buffer=a.link(p.buffer),d.type=d.type||d.buffer+".dtype");return c[e]=d})});Object.keys(e).forEach(function(a){var b=e[a];f[a]=P(b,function(a,c){function d(a){c(w[a],"=",e,".",a,"|0;")}var e=a.invoke(c,b),p=a.shared,f=p.isBufferArgs,g=p.buffer,w={isStream:c.def(!1)},h=new ya;h.state=1;Object.keys(h).forEach(function(a){w[a]=
c.def(""+h[a])});var z=w.buffer,k=w.type;c("if(",f,"(",e,")){",w.isStream,"=true;",z,"=",g,".createStream(",34962,",",e,");",k,"=",z,".dtype;","}else{",z,"=",g,".getBuffer(",e,");","if(",z,"){",k,"=",z,".dtype;",'}else if("constant" in ',e,"){",w.state,"=",2,";","if(typeof "+e+'.constant === "number"){',w[Da[0]],"=",e,".constant;",Da.slice(1).map(function(a){return w[a]}).join("="),"=0;","}else{",Da.map(function(a,b){return w[a]+"="+e+".constant.length>"+b+"?"+e+".constant["+b+"]:0;"}).join(""),"}}else{",
"if(",f,"(",e,".buffer)){",z,"=",g,".createStream(",34962,",",e,".buffer);","}else{",z,"=",g,".getBuffer(",e,".buffer);","}",k,'="type" in ',e,"?",p.glTypes,"[",e,".type]:",z,".dtype;",w.normalized,"=!!",e,".normalized;");d("size");d("offset");d("stride");d("divisor");c("}}");c.exit("if(",w.isStream,"){",g,".destroyStream(",z,");","}");return w})});return f}function M(a){var b=a["static"],c=a.dynamic,d={};Object.keys(b).forEach(function(a){var c=b[a];d[a]=D(function(a,b){return"number"===typeof c||
"boolean"===typeof c?""+c:a.link(c)})});Object.keys(c).forEach(function(a){var b=c[a];d[a]=P(b,function(a,c){return a.invoke(c,b)})});return d}function A(a,b,c,d,e){var f=y(a,e),g=x(a,f,e),h=O(a,e),k=R(a,e),m=E(a,e),ba=g.viewport;ba&&(k.viewport=ba);ba=l("scissor.box");(g=g[ba])&&(k[ba]=g);g=0<Object.keys(k).length;f={framebuffer:f,draw:h,shader:m,state:k,dirty:g};f.profile=B(a,e);f.uniforms=F(c,e);f.attributes=T(b,e);f.context=M(d,e);return f}function ua(a,b,c){var d=a.shared.context,e=a.scope();
Object.keys(c).forEach(function(f){b.save(d,"."+f);e(d,".",f,"=",c[f].append(a,b),";")});b(e)}function K(a,b,c,d){var e=a.shared,f=e.gl,g=e.framebuffer,h;ha&&(h=b.def(e.extensions,".webgl_draw_buffers"));var k=a.constants,e=k.drawBuffer,k=k.backBuffer;a=c?c.append(a,b):b.def(g,".next");d||b("if(",a,"!==",g,".cur){");b("if(",a,"){",f,".bindFramebuffer(",36160,",",a,".framebuffer);");ha&&b(h,".drawBuffersWEBGL(",e,"[",a,".colorAttachments.length]);");b("}else{",f,".bindFramebuffer(",36160,",null);");
ha&&b(h,".drawBuffersWEBGL(",k,");");b("}",g,".cur=",a,";");d||b("}")}function V(a,b,c){var d=a.shared,e=d.gl,f=a.current,g=a.next,h=d.current,k=d.next,m=a.cond(h,".dirty");Ka.forEach(function(b){b=l(b);if(!(b in c.state)){var d,w;if(b in g){d=g[b];w=f[b];var I=J(ra[b].length,function(a){return m.def(d,"[",a,"]")});m(a.cond(I.map(function(a,b){return a+"!=="+w+"["+b+"]"}).join("||")).then(e,".",ta[b],"(",I,");",I.map(function(a,b){return w+"["+b+"]="+a}).join(";"),";"))}else d=m.def(k,".",b),I=a.cond(d,
"!==",h,".",b),m(I),b in sa?I(a.cond(d).then(e,".enable(",sa[b],");")["else"](e,".disable(",sa[b],");"),h,".",b,"=",d,";"):I(e,".",ta[b],"(",d,");",h,".",b,"=",d,";")}});0===Object.keys(c.state).length&&m(h,".dirty=false;");b(m)}function Q(a,b,c,d){var e=a.shared,f=a.current,g=e.current,h=e.gl;vb(Object.keys(c)).forEach(function(e){var k=c[e];if(!d||d(k)){var m=k.append(a,b);if(sa[e]){var l=sa[e];va(k)?m?b(h,".enable(",l,");"):b(h,".disable(",l,");"):b(a.cond(m).then(h,".enable(",l,");")["else"](h,
".disable(",l,");"));b(g,".",e,"=",m,";")}else if(pa(m)){var n=f[e];b(h,".",ta[e],"(",m,");",m.map(function(a,b){return n+"["+b+"]="+a}).join(";"),";")}else b(h,".",ta[e],"(",m,");",g,".",e,"=",m,";")}})}function wa(a,b){ea&&(a.instancing=b.def(a.shared.extensions,".angle_instanced_arrays"))}function G(a,b,c,d,e){function f(){return"undefined"===typeof performance?"Date.now()":"performance.now()"}function g(a){t=b.def();a(t,"=",f(),";");"string"===typeof e?a(ba,".count+=",e,";"):a(ba,".count++;");
k&&(d?(r=b.def(),a(r,"=",q,".getNumPendingQueries();")):a(q,".beginQuery(",ba,");"))}function h(a){a(ba,".cpuTime+=",f(),"-",t,";");k&&(d?a(q,".pushScopeStats(",r,",",q,".getNumPendingQueries(),",ba,");"):a(q,".endQuery();"))}function m(a){var c=b.def(n,".profile");b(n,".profile=",a,";");b.exit(n,".profile=",c,";")}var l=a.shared,ba=a.stats,n=l.current,q=l.timer;c=c.profile;var t,r;if(c){if(va(c)){c.enable?(g(b),h(b.exit),m("true")):m("false");return}c=c.append(a,b);m(c)}else c=b.def(n,".profile");
l=a.block();g(l);b("if(",c,"){",l,"}");a=a.block();h(a);b.exit("if(",c,"){",a,"}")}function U(a,b,c,d,e){function f(a){switch(a){case 35664:case 35667:case 35671:return 2;case 35665:case 35668:case 35672:return 3;case 35666:case 35669:case 35673:return 4;default:return 1}}function g(c,d,e){function f(){b("if(!",z,".buffer){",k,".enableVertexAttribArray(",l,");}");var c=e.type,g;g=e.size?b.def(e.size,"||",d):d;b("if(",z,".type!==",c,"||",z,".size!==",g,"||",q.map(function(a){return z+"."+a+"!=="+e[a]}).join("||"),
"){",k,".bindBuffer(",34962,",",I,".buffer);",k,".vertexAttribPointer(",[l,g,c,e.normalized,e.stride,e.offset],");",z,".type=",c,";",z,".size=",g,";",q.map(function(a){return z+"."+a+"="+e[a]+";"}).join(""),"}");ea&&(c=e.divisor,b("if(",z,".divisor!==",c,"){",a.instancing,".vertexAttribDivisorANGLE(",[l,c],");",z,".divisor=",c,";}"))}function m(){b("if(",z,".buffer){",k,".disableVertexAttribArray(",l,");","}if(",Da.map(function(a,b){return z+"."+a+"!=="+n[b]}).join("||"),"){",k,".vertexAttrib4f(",
l,",",n,");",Da.map(function(a,b){return z+"."+a+"="+n[b]+";"}).join(""),"}")}var k=h.gl,l=b.def(c,".location"),z=b.def(h.attributes,"[",l,"]");c=e.state;var I=e.buffer,n=[e.x,e.y,e.z,e.w],q=["buffer","normalized","offset","stride"];1===c?f():2===c?m():(b("if(",c,"===",1,"){"),f(),b("}else{"),m(),b("}"))}var h=a.shared;d.forEach(function(d){var h=d.name,k=c.attributes[h],m;if(k){if(!e(k))return;m=k.append(a,b)}else{if(!e(xb))return;var l=a.scopeAttrib(h);m={};Object.keys(new ya).forEach(function(a){m[a]=
b.def(l,".",a)})}g(a.link(d),f(d.info.type),m)})}function W(a,c,d,e,f){for(var g=a.shared,h=g.gl,k,m=0;m<e.length;++m){var l=e[m],n=l.name,q=l.info.type,t=d.uniforms[n],l=a.link(l)+".location",r;if(t){if(!f(t))continue;if(va(t)){n=t.value;if(35678===q||35680===q)q=a.link(n._texture||n.color[0]._texture),c(h,".uniform1i(",l,",",q+".bind());"),c.exit(q,".unbind();");else if(35674===q||35675===q||35676===q)n=a.global.def("new Float32Array(["+Array.prototype.slice.call(n)+"])"),t=2,35675===q?t=3:35676===
q&&(t=4),c(h,".uniformMatrix",t,"fv(",l,",false,",n,");");else{switch(q){case 5126:k="1f";break;case 35664:k="2f";break;case 35665:k="3f";break;case 35666:k="4f";break;case 35670:k="1i";break;case 5124:k="1i";break;case 35671:k="2i";break;case 35667:k="2i";break;case 35672:k="3i";break;case 35668:k="3i";break;case 35673:k="4i";break;case 35669:k="4i"}c(h,".uniform",k,"(",l,",",pa(n)?Array.prototype.slice.call(n):n,");")}continue}else r=t.append(a,c)}else{if(!f(xb))continue;r=c.def(g.uniforms,"[",
b.id(n),"]")}35678===q?c("if(",r,"&&",r,'._reglType==="framebuffer"){',r,"=",r,".color[0];","}"):35680===q&&c("if(",r,"&&",r,'._reglType==="framebufferCube"){',r,"=",r,".color[0];","}");n=1;switch(q){case 35678:case 35680:q=c.def(r,"._texture");c(h,".uniform1i(",l,",",q,".bind());");c.exit(q,".unbind();");continue;case 5124:case 35670:k="1i";break;case 35667:case 35671:k="2i";n=2;break;case 35668:case 35672:k="3i";n=3;break;case 35669:case 35673:k="4i";n=4;break;case 5126:k="1f";break;case 35664:k=
"2f";n=2;break;case 35665:k="3f";n=3;break;case 35666:k="4f";n=4;break;case 35674:k="Matrix2fv";break;case 35675:k="Matrix3fv";break;case 35676:k="Matrix4fv"}c(h,".uniform",k,"(",l,",");if("M"===k.charAt(0)){var l=Math.pow(q-35674+2,2),v=a.global.def("new Float32Array(",l,")");c("false,(Array.isArray(",r,")||",r," instanceof Float32Array)?",r,":(",J(l,function(a){return v+"["+a+"]="+r+"["+a+"]"}),",",v,")")}else 1<n?c(J(n,function(a){return r+"["+a+"]"})):c(r);c(");")}}function S(a,b,c,d){function e(f){var g=
l[f];return g?g.contextDep&&d.contextDynamic||g.propDep?g.append(a,c):g.append(a,b):b.def(m,".",f)}function f(){function a(){c(u,".drawElementsInstancedANGLE(",[q,t,C,r+"<<(("+C+"-5121)>>1)",v],");")}function b(){c(u,".drawArraysInstancedANGLE(",[q,r,t,v],");")}n?da?a():(c("if(",n,"){"),a(),c("}else{"),b(),c("}")):b()}function g(){function a(){c(k+".drawElements("+[q,t,C,r+"<<(("+C+"-5121)>>1)"]+");")}function b(){c(k+".drawArrays("+[q,r,t]+");")}n?da?a():(c("if(",n,"){"),a(),c("}else{"),b(),c("}")):
b()}var h=a.shared,k=h.gl,m=h.draw,l=d.draw,n=function(){var e=l.elements,f=b;if(e){if(e.contextDep&&d.contextDynamic||e.propDep)f=c;e=e.append(a,f)}else e=f.def(m,".","elements");e&&f("if("+e+")"+k+".bindBuffer(34963,"+e+".buffer.buffer);");return e}(),q=e("primitive"),r=e("offset"),t=function(){var e=l.count,f=b;if(e){if(e.contextDep&&d.contextDynamic||e.propDep)f=c;e=e.append(a,f)}else e=f.def(m,".","count");return e}();if("number"===typeof t){if(0===t)return}else c("if(",t,"){"),c.exit("}");var v,
u;ea&&(v=e("instances"),u=a.instancing);var C=n+".type",da=l.elements&&va(l.elements);ea&&("number"!==typeof v||0<=v)?"string"===typeof v?(c("if(",v,">0){"),f(),c("}else if(",v,"<0){"),g(),c("}")):f():g()}function ca(a,b,c,d,e){b=N();e=b.proc("body",e);ea&&(b.instancing=e.def(b.shared.extensions,".angle_instanced_arrays"));a(b,e,c,d);return b.compile().body}function L(a,b,c,d){wa(a,b);U(a,b,c,d.attributes,function(){return!0});W(a,b,c,d.uniforms,function(){return!0});S(a,b,b,c)}function da(a,b){var c=
a.proc("draw",1);wa(a,c);ua(a,c,b.context);K(a,c,b.framebuffer);V(a,c,b);Q(a,c,b.state);G(a,c,b,!1,!0);var d=b.shader.progVar.append(a,c);c(a.shared.gl,".useProgram(",d,".program);");if(b.shader.program)L(a,c,b,b.shader.program);else{var e=a.global.def("{}"),f=c.def(d,".id"),g=c.def(e,"[",f,"]");c(a.cond(g).then(g,".call(this,a0);")["else"](g,"=",e,"[",f,"]=",a.link(function(c){return ca(L,a,b,c,1)}),"(",d,");",g,".call(this,a0);"))}0<Object.keys(b.state).length&&c(a.shared.current,".dirty=true;")}
function oa(a,b,c,d){function e(){return!0}a.batchId="a1";wa(a,b);U(a,b,c,d.attributes,e);W(a,b,c,d.uniforms,e);S(a,b,b,c)}function za(a,b,c,d){function e(a){return a.contextDep&&g||a.propDep}function f(a){return!e(a)}wa(a,b);var g=c.contextDep,h=b.def(),k=b.def();a.shared.props=k;a.batchId=h;var m=a.scope(),l=a.scope();b(m.entry,"for(",h,"=0;",h,"<","a1",";++",h,"){",k,"=","a0","[",h,"];",l,"}",m.exit);c.needsContext&&ua(a,l,c.context);c.needsFramebuffer&&K(a,l,c.framebuffer);Q(a,l,c.state,e);c.profile&&
e(c.profile)&&G(a,l,c,!1,!0);d?(U(a,m,c,d.attributes,f),U(a,l,c,d.attributes,e),W(a,m,c,d.uniforms,f),W(a,l,c,d.uniforms,e),S(a,m,l,c)):(b=a.global.def("{}"),d=c.shader.progVar.append(a,l),k=l.def(d,".id"),m=l.def(b,"[",k,"]"),l(a.shared.gl,".useProgram(",d,".program);","if(!",m,"){",m,"=",b,"[",k,"]=",a.link(function(b){return ca(oa,a,c,b,2)}),"(",d,");}",m,".call(this,a0[",h,"],",h,");"))}function ka(a,b){function c(a){return a.contextDep&&e||a.propDep}var d=a.proc("batch",2);a.batchId="0";wa(a,
d);var e=!1,f=!0;Object.keys(b.context).forEach(function(a){e=e||b.context[a].propDep});e||(ua(a,d,b.context),f=!1);var g=b.framebuffer,h=!1;g?(g.propDep?e=h=!0:g.contextDep&&e&&(h=!0),h||K(a,d,g)):K(a,d,null);b.state.viewport&&b.state.viewport.propDep&&(e=!0);V(a,d,b);Q(a,d,b.state,function(a){return!c(a)});b.profile&&c(b.profile)||G(a,d,b,!1,"a1");b.contextDep=e;b.needsContext=f;b.needsFramebuffer=h;f=b.shader.progVar;if(f.contextDep&&e||f.propDep)za(a,d,b,null);else if(f=f.append(a,d),d(a.shared.gl,
".useProgram(",f,".program);"),b.shader.program)za(a,d,b,b.shader.program);else{var g=a.global.def("{}"),h=d.def(f,".id"),k=d.def(g,"[",h,"]");d(a.cond(k).then(k,".call(this,a0,a1);")["else"](k,"=",g,"[",h,"]=",a.link(function(c){return ca(za,a,b,c,2)}),"(",f,");",k,".call(this,a0,a1);"))}0<Object.keys(b.state).length&&d(a.shared.current,".dirty=true;")}function ia(a,c){function d(b){var g=c.shader[b];g&&e.set(f.shader,"."+b,g.append(a,e))}var e=a.proc("scope",3);a.batchId="a2";var f=a.shared,g=f.current;
ua(a,e,c.context);c.framebuffer&&c.framebuffer.append(a,e);vb(Object.keys(c.state)).forEach(function(b){var d=c.state[b].append(a,e);pa(d)?d.forEach(function(c,d){e.set(a.next[b],"["+d+"]",c)}):e.set(f.next,"."+b,d)});G(a,e,c,!0,!0);["elements","offset","count","instances","primitive"].forEach(function(b){var d=c.draw[b];d&&e.set(f.draw,"."+b,""+d.append(a,e))});Object.keys(c.uniforms).forEach(function(d){e.set(f.uniforms,"["+b.id(d)+"]",c.uniforms[d].append(a,e))});Object.keys(c.attributes).forEach(function(b){var d=
c.attributes[b].append(a,e),f=a.scopeAttrib(b);Object.keys(new ya).forEach(function(a){e.set(f,"."+a,d[a])})});d("vert");d("frag");0<Object.keys(c.state).length&&(e(g,".dirty=true;"),e.exit(g,".dirty=true;"));e("a1(",a.shared.context,",a0,",a.batchId,");")}function ma(a){if("object"===typeof a&&!pa(a)){for(var b=Object.keys(a),c=0;c<b.length;++c)if(la.isDynamic(a[b[c]]))return!0;return!1}}function ja(a,b,c){function d(a,b){g.forEach(function(c){var d=e[c];la.isDynamic(d)&&(d=a.invoke(b,d),b(l,".",
c,"=",d,";"))})}var e=b["static"][c];if(e&&ma(e)){var f=a.global,g=Object.keys(e),h=!1,k=!1,m=!1,l=a.global.def("{}");g.forEach(function(b){var c=e[b];if(la.isDynamic(c))"function"===typeof c&&(c=e[b]=la.unbox(c)),b=P(c,null),h=h||b.thisDep,m=m||b.propDep,k=k||b.contextDep;else{f(l,".",b,"=");switch(typeof c){case "number":f(c);break;case "string":f('"',c,'"');break;case "object":Array.isArray(c)&&f("[",c.join(),"]");break;default:f(a.link(c))}f(";")}});b.dynamic[c]=new la.DynamicVariable(4,{thisDep:h,
contextDep:k,propDep:m,ref:l,append:d});delete b["static"][c]}}var ya=q.Record,X={add:32774,subtract:32778,"reverse subtract":32779};c.ext_blend_minmax&&(X.min=32775,X.max=32776);var ea=c.angle_instanced_arrays,ha=c.webgl_draw_buffers,ra={dirty:!0,profile:h.profile},Fa={},Ka=[],sa={},ta={};u("dither",3024);u("blend.enable",3042);v("blend.color","blendColor",[0,0,0,0]);v("blend.equation","blendEquationSeparate",[32774,32774]);v("blend.func","blendFuncSeparate",[1,0,1,0]);u("depth.enable",2929,!0);
v("depth.func","depthFunc",513);v("depth.range","depthRange",[0,1]);v("depth.mask","depthMask",!0);v("colorMask","colorMask",[!0,!0,!0,!0]);u("cull.enable",2884);v("cull.face","cullFace",1029);v("frontFace","frontFace",2305);v("lineWidth","lineWidth",1);u("polygonOffset.enable",32823);v("polygonOffset.offset","polygonOffset",[0,0]);u("sample.alpha",32926);u("sample.enable",32928);v("sample.coverage","sampleCoverage",[1,!1]);u("stencil.enable",2960);v("stencil.mask","stencilMask",-1);v("stencil.func",
"stencilFunc",[519,0,-1]);v("stencil.opFront","stencilOpSeparate",[1028,7680,7680,7680]);v("stencil.opBack","stencilOpSeparate",[1029,7680,7680,7680]);u("scissor.enable",3089);v("scissor.box","scissor",[0,0,a.drawingBufferWidth,a.drawingBufferHeight]);v("viewport","viewport",[0,0,a.drawingBufferWidth,a.drawingBufferHeight]);var na={gl:a,context:C,strings:b,next:Fa,current:ra,draw:m,elements:d,buffer:g,shader:t,attributes:q.state,uniforms:r,framebuffer:f,extensions:c,timer:k,isBufferArgs:Oa},aa={primTypes:Sa,
compareFuncs:Xa,blendFuncs:Ga,blendEquations:X,stencilOps:Pa,glTypes:Ra,orientationType:wb};ha&&(aa.backBuffer=[1029],aa.drawBuffer=J(e.maxDrawbuffers,function(a){return 0===a?[0]:J(a,function(a){return 36064+a})}));var qa=0;return{next:Fa,current:ra,procs:function(){var a=N(),b=a.proc("poll"),c=a.proc("refresh"),d=a.block();b(d);c(d);var f=a.shared,g=f.gl,h=f.next,k=f.current;d(k,".dirty=false;");K(a,b);K(a,c,null,!0);var m;ea&&(m=a.link(ea));for(var l=0;l<e.maxAttributes;++l){var n=c.def(f.attributes,
"[",l,"]"),q=a.cond(n,".buffer");q.then(g,".enableVertexAttribArray(",l,");",g,".bindBuffer(",34962,",",n,".buffer.buffer);",g,".vertexAttribPointer(",l,",",n,".size,",n,".type,",n,".normalized,",n,".stride,",n,".offset);")["else"](g,".disableVertexAttribArray(",l,");",g,".vertexAttrib4f(",l,",",n,".x,",n,".y,",n,".z,",n,".w);",n,".buffer=null;");c(q);ea&&c(m,".vertexAttribDivisorANGLE(",l,",",n,".divisor);")}Object.keys(sa).forEach(function(e){var f=sa[e],m=d.def(h,".",e),l=a.block();l("if(",m,"){",
g,".enable(",f,")}else{",g,".disable(",f,")}",k,".",e,"=",m,";");c(l);b("if(",m,"!==",k,".",e,"){",l,"}")});Object.keys(ta).forEach(function(e){var f=ta[e],m=ra[e],l,n,q=a.block();q(g,".",f,"(");pa(m)?(f=m.length,l=a.global.def(h,".",e),n=a.global.def(k,".",e),q(J(f,function(a){return l+"["+a+"]"}),");",J(f,function(a){return n+"["+a+"]="+l+"["+a+"];"}).join("")),b("if(",J(f,function(a){return l+"["+a+"]!=="+n+"["+a+"]"}).join("||"),"){",q,"}")):(l=d.def(h,".",e),n=d.def(k,".",e),q(l,");",k,".",e,
"=",l,";"),b("if(",l,"!==",n,"){",q,"}"));c(q)});return a.compile()}(),compile:function(a,b,c,d,e){var f=N();f.stats=f.link(e);Object.keys(b["static"]).forEach(function(a){ja(f,b,a)});Ub.forEach(function(b){ja(f,a,b)});c=A(a,b,c,d,f);da(f,c);ia(f,c);ka(f,c);return f.compile()}}}function yb(a,b){for(var c=0;c<a.length;++c)if(a[c]===b)return c;return-1}var E=function(a,b){for(var c=Object.keys(b),e=0;e<c.length;++e)a[c[e]]=b[c[e]];return a},Ab=0,la={DynamicVariable:aa,define:function(a,b){return new aa(a,
Za(b+""))},isDynamic:function(a){return"function"===typeof a&&!a._reglType||a instanceof aa},unbox:function(a,b){return"function"===typeof a?new aa(0,a):a},accessor:Za},Ya={next:"function"===typeof requestAnimationFrame?function(a){return requestAnimationFrame(a)}:function(a){return setTimeout(a,16)},cancel:"function"===typeof cancelAnimationFrame?function(a){return cancelAnimationFrame(a)}:clearTimeout},zb="undefined"!==typeof performance&&performance.now?function(){return performance.now()}:function(){return+new Date},
x=cb();x.zero=cb();var Vb=function(a,b){var c=1;b.ext_texture_filter_anisotropic&&(c=a.getParameter(34047));var e=1,g=1;b.webgl_draw_buffers&&(e=a.getParameter(34852),g=a.getParameter(36063));var d=!!b.oes_texture_float;if(d){d=a.createTexture();a.bindTexture(3553,d);a.texImage2D(3553,0,6408,1,1,0,6408,5126,null);var n=a.createFramebuffer();a.bindFramebuffer(36160,n);a.framebufferTexture2D(36160,36064,3553,d,0);a.bindTexture(3553,null);if(36053!==a.checkFramebufferStatus(36160))d=!1;else{a.viewport(0,
0,1,1);a.clearColor(1,0,0,1);a.clear(16384);var f=x.allocType(5126,4);a.readPixels(0,0,1,1,6408,5126,f);a.getError()?d=!1:(a.deleteFramebuffer(n),a.deleteTexture(d),d=1===f[0]);x.freeType(f)}}f=!0;"undefined"!==typeof navigator&&(/MSIE/.test(navigator.userAgent)||/Trident\//.test(navigator.appVersion)||/Edge/.test(navigator.userAgent))||(f=a.createTexture(),n=x.allocType(5121,36),a.activeTexture(33984),a.bindTexture(34067,f),a.texImage2D(34069,0,6408,3,3,0,6408,5121,n),x.freeType(n),a.bindTexture(34067,
null),a.deleteTexture(f),f=!a.getError());return{colorBits:[a.getParameter(3410),a.getParameter(3411),a.getParameter(3412),a.getParameter(3413)],depthBits:a.getParameter(3414),stencilBits:a.getParameter(3415),subpixelBits:a.getParameter(3408),extensions:Object.keys(b).filter(function(a){return!!b[a]}),maxAnisotropic:c,maxDrawbuffers:e,maxColorAttachments:g,pointSizeDims:a.getParameter(33901),lineWidthDims:a.getParameter(33902),maxViewportDims:a.getParameter(3386),maxCombinedTextureUnits:a.getParameter(35661),
maxCubeMapSize:a.getParameter(34076),maxRenderbufferSize:a.getParameter(34024),maxTextureUnits:a.getParameter(34930),maxTextureSize:a.getParameter(3379),maxAttributes:a.getParameter(34921),maxVertexUniforms:a.getParameter(36347),maxVertexTextureUnits:a.getParameter(35660),maxVaryingVectors:a.getParameter(36348),maxFragmentUniforms:a.getParameter(36349),glsl:a.getParameter(35724),renderer:a.getParameter(7937),vendor:a.getParameter(7936),version:a.getParameter(7938),readFloat:d,npotTextureCube:f}},
M=function(a){return a instanceof Uint8Array||a instanceof Uint16Array||a instanceof Uint32Array||a instanceof Int8Array||a instanceof Int16Array||a instanceof Int32Array||a instanceof Float32Array||a instanceof Float64Array||a instanceof Uint8ClampedArray},S=function(a){return Object.keys(a).map(function(b){return a[b]})},Ma={shape:function(a){for(var b=[];a.length;a=a[0])b.push(a.length);return b},flatten:function(a,b,c,e){var g=1;if(b.length)for(var d=0;d<b.length;++d)g*=b[d];else g=0;c=e||x.allocType(c,
g);switch(b.length){case 0:break;case 1:e=b[0];for(b=0;b<e;++b)c[b]=a[b];break;case 2:e=b[0];b=b[1];for(d=g=0;d<e;++d)for(var n=a[d],f=0;f<b;++f)c[g++]=n[f];break;case 3:db(a,b[0],b[1],b[2],c,0);break;default:eb(a,b,0,c,0)}return c}},Ia={"[object Int8Array]":5120,"[object Int16Array]":5122,"[object Int32Array]":5124,"[object Uint8Array]":5121,"[object Uint8ClampedArray]":5121,"[object Uint16Array]":5123,"[object Uint32Array]":5125,"[object Float32Array]":5126,"[object Float64Array]":5121,"[object ArrayBuffer]":5121},
Ra={int8:5120,int16:5122,int32:5124,uint8:5121,uint16:5123,uint32:5125,"float":5126,float32:5126},jb={dynamic:35048,stream:35040,"static":35044},Qa=Ma.flatten,hb=Ma.shape,ja=[];ja[5120]=1;ja[5122]=2;ja[5124]=4;ja[5121]=1;ja[5123]=2;ja[5125]=4;ja[5126]=4;var Sa={points:0,point:0,lines:1,line:1,triangles:4,triangle:4,"line loop":2,"line strip":3,"triangle strip":5,"triangle fan":6},lb=new Float32Array(1),Ib=new Uint32Array(lb.buffer),Mb=[9984,9986,9985,9987],La=[0,6409,6410,6407,6408],L={};L[6409]=
L[6406]=L[6402]=1;L[34041]=L[6410]=2;L[6407]=L[35904]=3;L[6408]=L[35906]=4;var Ua=Ea("HTMLCanvasElement"),pb=Ea("CanvasRenderingContext2D"),qb=Ea("ImageBitmap"),rb=Ea("HTMLImageElement"),sb=Ea("HTMLVideoElement"),Jb=Object.keys(Ia).concat([Ua,pb,qb,rb,sb]),qa=[];qa[5121]=1;qa[5126]=4;qa[36193]=2;qa[5123]=2;qa[5125]=4;var y=[];y[32854]=2;y[32855]=2;y[36194]=2;y[34041]=4;y[33776]=.5;y[33777]=.5;y[33778]=1;y[33779]=1;y[35986]=.5;y[35987]=1;y[34798]=1;y[35840]=.5;y[35841]=.25;y[35842]=.5;y[35843]=.25;
y[36196]=.5;var Q=[];Q[32854]=2;Q[32855]=2;Q[36194]=2;Q[33189]=2;Q[36168]=1;Q[34041]=4;Q[35907]=4;Q[34836]=16;Q[34842]=8;Q[34843]=6;var Wb=function(a,b,c,e,g){function d(a){this.id=q++;this.refCount=1;this.renderbuffer=a;this.format=32854;this.height=this.width=0;g.profile&&(this.stats={size:0})}function n(b){var c=b.renderbuffer;a.bindRenderbuffer(36161,null);a.deleteRenderbuffer(c);b.renderbuffer=null;b.refCount=0;delete t[b.id];e.renderbufferCount--}var f={rgba4:32854,rgb565:36194,"rgb5 a1":32855,
depth:33189,stencil:36168,"depth stencil":34041};b.ext_srgb&&(f.srgba=35907);b.ext_color_buffer_half_float&&(f.rgba16f=34842,f.rgb16f=34843);b.webgl_color_buffer_float&&(f.rgba32f=34836);var r=[];Object.keys(f).forEach(function(a){r[f[a]]=a});var q=0,t={};d.prototype.decRef=function(){0>=--this.refCount&&n(this)};g.profile&&(e.getTotalRenderbufferSize=function(){var a=0;Object.keys(t).forEach(function(b){a+=t[b].stats.size});return a});return{create:function(b,c){function k(b,c){var d=0,e=0,m=32854;
"object"===typeof b&&b?("shape"in b?(e=b.shape,d=e[0]|0,e=e[1]|0):("radius"in b&&(d=e=b.radius|0),"width"in b&&(d=b.width|0),"height"in b&&(e=b.height|0)),"format"in b&&(m=f[b.format])):"number"===typeof b?(d=b|0,e="number"===typeof c?c|0:d):b||(d=e=1);if(d!==h.width||e!==h.height||m!==h.format)return k.width=h.width=d,k.height=h.height=e,h.format=m,a.bindRenderbuffer(36161,h.renderbuffer),a.renderbufferStorage(36161,m,d,e),g.profile&&(h.stats.size=Q[h.format]*h.width*h.height),k.format=r[h.format],
k}var h=new d(a.createRenderbuffer());t[h.id]=h;e.renderbufferCount++;k(b,c);k.resize=function(b,c){var d=b|0,e=c|0||d;if(d===h.width&&e===h.height)return k;k.width=h.width=d;k.height=h.height=e;a.bindRenderbuffer(36161,h.renderbuffer);a.renderbufferStorage(36161,h.format,d,e);g.profile&&(h.stats.size=Q[h.format]*h.width*h.height);return k};k._reglType="renderbuffer";k._renderbuffer=h;g.profile&&(k.stats=h.stats);k.destroy=function(){h.decRef()};return k},clear:function(){S(t).forEach(n)},restore:function(){S(t).forEach(function(b){b.renderbuffer=
a.createRenderbuffer();a.bindRenderbuffer(36161,b.renderbuffer);a.renderbufferStorage(36161,b.format,b.width,b.height)});a.bindRenderbuffer(36161,null)}}},Wa=[];Wa[6408]=4;Wa[6407]=3;var Na=[];Na[5121]=1;Na[5126]=4;Na[36193]=2;var Da=["x","y","z","w"],Ub="blend.func blend.equation stencil.func stencil.opFront stencil.opBack sample.coverage viewport scissor.box polygonOffset.offset".split(" "),Ga={0:0,1:1,zero:0,one:1,"src color":768,"one minus src color":769,"src alpha":770,"one minus src alpha":771,
"dst color":774,"one minus dst color":775,"dst alpha":772,"one minus dst alpha":773,"constant color":32769,"one minus constant color":32770,"constant alpha":32771,"one minus constant alpha":32772,"src alpha saturate":776},Xa={never:512,less:513,"<":513,equal:514,"=":514,"==":514,"===":514,lequal:515,"<=":515,greater:516,">":516,notequal:517,"!=":517,"!==":517,gequal:518,">=":518,always:519},Pa={0:0,zero:0,keep:7680,replace:7681,increment:7682,decrement:7683,"increment wrap":34055,"decrement wrap":34056,
invert:5386},wb={cw:2304,ccw:2305},xb=new Z(!1,!1,!1,function(){}),Xb=function(a,b){function c(){this.endQueryIndex=this.startQueryIndex=-1;this.sum=0;this.stats=null}function e(a,b,d){var e=n.pop()||new c;e.startQueryIndex=a;e.endQueryIndex=b;e.sum=0;e.stats=d;f.push(e)}if(!b.ext_disjoint_timer_query)return null;var g=[],d=[],n=[],f=[],r=[],q=[];return{beginQuery:function(a){var c=g.pop()||b.ext_disjoint_timer_query.createQueryEXT();b.ext_disjoint_timer_query.beginQueryEXT(35007,c);d.push(c);e(d.length-
1,d.length,a)},endQuery:function(){b.ext_disjoint_timer_query.endQueryEXT(35007)},pushScopeStats:e,update:function(){var a,c;a=d.length;if(0!==a){q.length=Math.max(q.length,a+1);r.length=Math.max(r.length,a+1);r[0]=0;var e=q[0]=0;for(c=a=0;c<d.length;++c){var k=d[c];b.ext_disjoint_timer_query.getQueryObjectEXT(k,34919)?(e+=b.ext_disjoint_timer_query.getQueryObjectEXT(k,34918),g.push(k)):d[a++]=k;r[c+1]=e;q[c+1]=a}d.length=a;for(c=a=0;c<f.length;++c){var e=f[c],h=e.startQueryIndex,k=e.endQueryIndex;
e.sum+=r[k]-r[h];h=q[h];k=q[k];k===h?(e.stats.gpuTime+=e.sum/1E6,n.push(e)):(e.startQueryIndex=h,e.endQueryIndex=k,f[a++]=e)}f.length=a}},getNumPendingQueries:function(){return d.length},clear:function(){g.push.apply(g,d);for(var a=0;a<g.length;a++)b.ext_disjoint_timer_query.deleteQueryEXT(g[a]);d.length=0;g.length=0},restore:function(){d.length=0;g.length=0}}};return function(a){function b(){if(0===G.length)B&&B.update(),ca=null;else{ca=Ya.next(b);t();for(var a=G.length-1;0<=a;--a){var c=G[a];c&&
c(O,null,0)}k.flush();B&&B.update()}}function c(){!ca&&0<G.length&&(ca=Ya.next(b))}function e(){ca&&(Ya.cancel(b),ca=null)}function g(a){a.preventDefault();e();U.forEach(function(a){a()})}function d(a){k.getError();l.restore();Q.restore();F.restore();A.restore();M.restore();K.restore();B&&B.restore();V.procs.refresh();c();W.forEach(function(a){a()})}function n(a){function b(a){var c={},d={};Object.keys(a).forEach(function(b){var e=a[b];la.isDynamic(e)?d[b]=la.unbox(e,b):c[b]=e});return{dynamic:d,
"static":c}}function c(a){for(;m.length<a;)m.push(null);return m}var d=b(a.context||{}),e=b(a.uniforms||{}),f=b(a.attributes||{}),g=b(function(a){function b(a){if(a in c){var d=c[a];delete c[a];Object.keys(d).forEach(function(b){c[a+"."+b]=d[b]})}}var c=E({},a);delete c.uniforms;delete c.attributes;delete c.context;"stencil"in c&&c.stencil.op&&(c.stencil.opBack=c.stencil.opFront=c.stencil.op,delete c.stencil.op);b("blend");b("depth");b("cull");b("stencil");b("polygonOffset");b("scissor");b("sample");
return c}(a));a={gpuTime:0,cpuTime:0,count:0};var d=V.compile(g,f,e,d,a),h=d.draw,k=d.batch,l=d.scope,m=[];return E(function(a,b){var d;if("function"===typeof a)return l.call(this,null,a,0);if("function"===typeof b)if("number"===typeof a)for(d=0;d<a;++d)l.call(this,null,b,d);else if(Array.isArray(a))for(d=0;d<a.length;++d)l.call(this,a[d],b,d);else return l.call(this,a,b,0);else if("number"===typeof a){if(0<a)return k.call(this,c(a|0),a|0)}else if(Array.isArray(a)){if(a.length)return k.call(this,
a,a.length)}else return h.call(this,a)},{stats:a})}function f(a,b){var c=0;V.procs.poll();var d=b.color;d&&(k.clearColor(+d[0]||0,+d[1]||0,+d[2]||0,+d[3]||0),c|=16384);"depth"in b&&(k.clearDepth(+b.depth),c|=256);"stencil"in b&&(k.clearStencil(b.stencil|0),c|=1024);k.clear(c)}function r(a){G.push(a);c();return{cancel:function(){function b(){var a=yb(G,b);G[a]=G[G.length-1];--G.length;0>=G.length&&e()}var c=yb(G,a);G[c]=b}}}function q(){var a=S.viewport,b=S.scissor_box;a[0]=a[1]=b[0]=b[1]=0;O.viewportWidth=
O.framebufferWidth=O.drawingBufferWidth=a[2]=b[2]=k.drawingBufferWidth;O.viewportHeight=O.framebufferHeight=O.drawingBufferHeight=a[3]=b[3]=k.drawingBufferHeight}function t(){O.tick+=1;O.time=y();q();V.procs.poll()}function m(){q();V.procs.refresh();B&&B.update()}function y(){return(zb()-D)/1E3}a=Eb(a);if(!a)return null;var k=a.gl,h=k.getContextAttributes();k.isContextLost();var l=Fb(k,a);if(!l)return null;var u=Bb(),v={bufferCount:0,elementsCount:0,framebufferCount:0,shaderCount:0,textureCount:0,
cubeCount:0,renderbufferCount:0,maxTextureUnits:0},x=l.extensions,B=Xb(k,x),D=zb(),J=k.drawingBufferWidth,P=k.drawingBufferHeight,O={tick:0,time:0,viewportWidth:J,viewportHeight:P,framebufferWidth:J,framebufferHeight:P,drawingBufferWidth:J,drawingBufferHeight:P,pixelRatio:a.pixelRatio},R=Vb(k,x),J=Pb(k,x,R,u),F=Gb(k,v,a,J),T=Hb(k,x,F,v),Q=Qb(k,u,v,a),A=Kb(k,x,R,function(){V.procs.poll()},O,v,a),M=Wb(k,x,R,v,a),K=Ob(k,x,R,A,M,v),V=Tb(k,u,x,R,F,T,A,K,{},J,Q,{elements:null,primitive:4,count:-1,offset:0,
instances:-1},O,B,a),u=Rb(k,K,V.procs.poll,O,h,x,R),S=V.next,L=k.canvas,G=[],U=[],W=[],Z=[a.onDestroy],ca=null;L&&(L.addEventListener("webglcontextlost",g,!1),L.addEventListener("webglcontextrestored",d,!1));var aa=K.setFBO=n({framebuffer:la.define.call(null,1,"framebuffer")});m();h=E(n,{clear:function(a){if("framebuffer"in a)if(a.framebuffer&&"framebufferCube"===a.framebuffer_reglType)for(var b=0;6>b;++b)aa(E({framebuffer:a.framebuffer.faces[b]},a),f);else aa(a,f);else f(null,a)},prop:la.define.bind(null,
1),context:la.define.bind(null,2),"this":la.define.bind(null,3),draw:n({}),buffer:function(a){return F.create(a,34962,!1,!1)},elements:function(a){return T.create(a,!1)},texture:A.create2D,cube:A.createCube,renderbuffer:M.create,framebuffer:K.create,framebufferCube:K.createCube,attributes:h,frame:r,on:function(a,b){var c;switch(a){case "frame":return r(b);case "lost":c=U;break;case "restore":c=W;break;case "destroy":c=Z}c.push(b);return{cancel:function(){for(var a=0;a<c.length;++a)if(c[a]===b){c[a]=
c[c.length-1];c.pop();break}}}},limits:R,hasExtension:function(a){return 0<=R.extensions.indexOf(a.toLowerCase())},read:u,destroy:function(){G.length=0;e();L&&(L.removeEventListener("webglcontextlost",g),L.removeEventListener("webglcontextrestored",d));Q.clear();K.clear();M.clear();A.clear();T.clear();F.clear();B&&B.clear();Z.forEach(function(a){a()})},_gl:k,_refresh:m,poll:function(){t();B&&B.update()},now:y,stats:v});a.onDone(null,h);return h}});

},{}],481:[function(_dereq_,module,exports){
/*!
 * repeat-string <https://github.com/jonschlinkert/repeat-string>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

/**
 * Results cache
 */

var res = '';
var cache;

/**
 * Expose `repeat`
 */

module.exports = repeat;

/**
 * Repeat the given `string` the specified `number`
 * of times.
 *
 * **Example:**
 *
 * ```js
 * var repeat = require('repeat-string');
 * repeat('A', 5);
 * //=> AAAAA
 * ```
 *
 * @param {String} `string` The string to repeat
 * @param {Number} `number` The number of times to repeat the string
 * @return {String} Repeated string
 * @api public
 */

function repeat(str, num) {
  if (typeof str !== 'string') {
    throw new TypeError('expected a string');
  }

  // cover common, quick use cases
  if (num === 1) return str;
  if (num === 2) return str + str;

  var max = str.length * num;
  if (cache !== str || typeof cache === 'undefined') {
    cache = str;
    res = '';
  } else if (res.length >= max) {
    return res.substr(0, max);
  }

  while (max > res.length && num > 1) {
    if (num & 1) {
      res += str;
    }

    num >>= 1;
    str += str;
  }

  res += str;
  res = res.substr(0, max);
  return res;
}

},{}],482:[function(_dereq_,module,exports){
(function (global){
module.exports =
  global.performance &&
  global.performance.now ? function now() {
    return performance.now()
  } : Date.now || function now() {
    return +new Date
  }

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],483:[function(_dereq_,module,exports){
"use strict"

module.exports = compressExpansion

function compressExpansion(e) {
  var m = e.length
  var Q = e[e.length-1]
  var bottom = m
  for(var i=m-2; i>=0; --i) {
    var a = Q
    var b = e[i]
    Q = a + b
    var bv = Q - a
    var q = b - bv
    if(q) {
      e[--bottom] = Q
      Q = q
    }
  }
  var top = 0
  for(var i=bottom; i<m; ++i) {
    var a = e[i]
    var b = Q
    Q = a + b
    var bv = Q - a
    var q = b - bv
    if(q) {
      e[top++] = q
    }
  }
  e[top++] = Q
  e.length = top
  return e
}
},{}],484:[function(_dereq_,module,exports){
"use strict"

var twoProduct = _dereq_("two-product")
var robustSum = _dereq_("robust-sum")
var robustScale = _dereq_("robust-scale")
var compress = _dereq_("robust-compress")

var NUM_EXPANDED = 6

function cofactor(m, c) {
  var result = new Array(m.length-1)
  for(var i=1; i<m.length; ++i) {
    var r = result[i-1] = new Array(m.length-1)
    for(var j=0,k=0; j<m.length; ++j) {
      if(j === c) {
        continue
      }
      r[k++] = m[i][j]
    }
  }
  return result
}

function matrix(n) {
  var result = new Array(n)
  for(var i=0; i<n; ++i) {
    result[i] = new Array(n)
    for(var j=0; j<n; ++j) {
      result[i][j] = ["m[", i, "][", j, "]"].join("")
    }
  }
  return result
}

function sign(n) {
  if(n & 1) {
    return "-"
  }
  return ""
}

function generateSum(expr) {
  if(expr.length === 1) {
    return expr[0]
  } else if(expr.length === 2) {
    return ["sum(", expr[0], ",", expr[1], ")"].join("")
  } else {
    var m = expr.length>>1
    return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("")
  }
}

function determinant(m) {
  if(m.length === 2) {
    return ["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("")
  } else {
    var expr = []
    for(var i=0; i<m.length; ++i) {
      expr.push(["scale(", determinant(cofactor(m, i)), ",", sign(i), m[0][i], ")"].join(""))
    }
    return generateSum(expr)
  }
}

function compileDeterminant(n) {
  var proc = new Function("sum", "scale", "prod", "compress", [
    "function robustDeterminant",n, "(m){return compress(", 
      determinant(matrix(n)),
    ")};return robustDeterminant", n].join(""))
  return proc(robustSum, robustScale, twoProduct, compress)
}

var CACHE = [
  function robustDeterminant0() { return [0] },
  function robustDeterminant1(m) { return [m[0][0]] }
]

function generateDispatch() {
  while(CACHE.length < NUM_EXPANDED) {
    CACHE.push(compileDeterminant(CACHE.length))
  }
  var procArgs = []
  var code = ["function robustDeterminant(m){switch(m.length){"]
  for(var i=0; i<NUM_EXPANDED; ++i) {
    procArgs.push("det" + i)
    code.push("case ", i, ":return det", i, "(m);")
  }
  code.push("}\
var det=CACHE[m.length];\
if(!det)\
det=CACHE[m.length]=gen(m.length);\
return det(m);\
}\
return robustDeterminant")
  procArgs.push("CACHE", "gen", code.join(""))
  var proc = Function.apply(undefined, procArgs)
  module.exports = proc.apply(undefined, CACHE.concat([CACHE, compileDeterminant]))
  for(var i=0; i<CACHE.length; ++i) {
    module.exports[i] = CACHE[i]
  }
}

generateDispatch()
},{"robust-compress":483,"robust-scale":490,"robust-sum":493,"two-product":521}],485:[function(_dereq_,module,exports){
"use strict"

var twoProduct = _dereq_("two-product")
var robustSum = _dereq_("robust-sum")

module.exports = robustDotProduct

function robustDotProduct(a, b) {
  var r = twoProduct(a[0], b[0])
  for(var i=1; i<a.length; ++i) {
    r = robustSum(r, twoProduct(a[i], b[i]))
  }
  return r
}
},{"robust-sum":493,"two-product":521}],486:[function(_dereq_,module,exports){
"use strict"

var twoProduct = _dereq_("two-product")
var robustSum = _dereq_("robust-sum")
var robustDiff = _dereq_("robust-subtract")
var robustScale = _dereq_("robust-scale")

var NUM_EXPAND = 6

function cofactor(m, c) {
  var result = new Array(m.length-1)
  for(var i=1; i<m.length; ++i) {
    var r = result[i-1] = new Array(m.length-1)
    for(var j=0,k=0; j<m.length; ++j) {
      if(j === c) {
        continue
      }
      r[k++] = m[i][j]
    }
  }
  return result
}

function matrix(n) {
  var result = new Array(n)
  for(var i=0; i<n; ++i) {
    result[i] = new Array(n)
    for(var j=0; j<n; ++j) {
      result[i][j] = ["m", j, "[", (n-i-2), "]"].join("")
    }
  }
  return result
}

function generateSum(expr) {
  if(expr.length === 1) {
    return expr[0]
  } else if(expr.length === 2) {
    return ["sum(", expr[0], ",", expr[1], ")"].join("")
  } else {
    var m = expr.length>>1
    return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("")
  }
}

function makeProduct(a, b) {
  if(a.charAt(0) === "m") {
    if(b.charAt(0) === "w") {
      var toks = a.split("[")
      return ["w", b.substr(1), "m", toks[0].substr(1)].join("")
    } else {
      return ["prod(", a, ",", b, ")"].join("")
    }
  } else {
    return makeProduct(b, a)
  }
}

function sign(s) {
  if(s & 1 !== 0) {
    return "-"
  }
  return ""
}

function determinant(m) {
  if(m.length === 2) {
    return [["diff(", makeProduct(m[0][0], m[1][1]), ",", makeProduct(m[1][0], m[0][1]), ")"].join("")]
  } else {
    var expr = []
    for(var i=0; i<m.length; ++i) {
      expr.push(["scale(", generateSum(determinant(cofactor(m, i))), ",", sign(i), m[0][i], ")"].join(""))
    }
    return expr
  }
}

function makeSquare(d, n) {
  var terms = []
  for(var i=0; i<n-2; ++i) {
    terms.push(["prod(m", d, "[", i, "],m", d, "[", i, "])"].join(""))
  }
  return generateSum(terms)
}

function orientation(n) {
  var pos = []
  var neg = []
  var m = matrix(n)
  for(var i=0; i<n; ++i) {
    m[0][i] = "1"
    m[n-1][i] = "w"+i
  } 
  for(var i=0; i<n; ++i) {
    if((i&1)===0) {
      pos.push.apply(pos,determinant(cofactor(m, i)))
    } else {
      neg.push.apply(neg,determinant(cofactor(m, i)))
    }
  }
  var posExpr = generateSum(pos)
  var negExpr = generateSum(neg)
  var funcName = "exactInSphere" + n
  var funcArgs = []
  for(var i=0; i<n; ++i) {
    funcArgs.push("m" + i)
  }
  var code = ["function ", funcName, "(", funcArgs.join(), "){"]
  for(var i=0; i<n; ++i) {
    code.push("var w",i,"=",makeSquare(i,n),";")
    for(var j=0; j<n; ++j) {
      if(j !== i) {
        code.push("var w",i,"m",j,"=scale(w",i,",m",j,"[0]);")
      }
    }
  }
  code.push("var p=", posExpr, ",n=", negExpr, ",d=diff(p,n);return d[d.length-1];}return ", funcName)
  var proc = new Function("sum", "diff", "prod", "scale", code.join(""))
  return proc(robustSum, robustDiff, twoProduct, robustScale)
}

function inSphere0() { return 0 }
function inSphere1() { return 0 }
function inSphere2() { return 0 }

var CACHED = [
  inSphere0,
  inSphere1,
  inSphere2
]

function slowInSphere(args) {
  var proc = CACHED[args.length]
  if(!proc) {
    proc = CACHED[args.length] = orientation(args.length)
  }
  return proc.apply(undefined, args)
}

function generateInSphereTest() {
  while(CACHED.length <= NUM_EXPAND) {
    CACHED.push(orientation(CACHED.length))
  }
  var args = []
  var procArgs = ["slow"]
  for(var i=0; i<=NUM_EXPAND; ++i) {
    args.push("a" + i)
    procArgs.push("o" + i)
  }
  var code = [
    "function testInSphere(", args.join(), "){switch(arguments.length){case 0:case 1:return 0;"
  ]
  for(var i=2; i<=NUM_EXPAND; ++i) {
    code.push("case ", i, ":return o", i, "(", args.slice(0, i).join(), ");")
  }
  code.push("}var s=new Array(arguments.length);for(var i=0;i<arguments.length;++i){s[i]=arguments[i]};return slow(s);}return testInSphere")
  procArgs.push(code.join(""))

  var proc = Function.apply(undefined, procArgs)

  module.exports = proc.apply(undefined, [slowInSphere].concat(CACHED))
  for(var i=0; i<=NUM_EXPAND; ++i) {
    module.exports[i] = CACHED[i]
  }
}

generateInSphereTest()
},{"robust-scale":490,"robust-subtract":492,"robust-sum":493,"two-product":521}],487:[function(_dereq_,module,exports){
"use strict"

var determinant = _dereq_("robust-determinant")

var NUM_EXPAND = 6

function generateSolver(n) {
  var funcName = "robustLinearSolve" + n + "d"
  var code = ["function ", funcName, "(A,b){return ["]
  for(var i=0; i<n; ++i) {
    code.push("det([")
    for(var j=0; j<n; ++j) {
      if(j > 0) {
        code.push(",")
      }
      code.push("[")
      for(var k=0; k<n; ++k) {
        if(k > 0) {
          code.push(",")
        }
        if(k === i) {
          code.push("+b[", j, "]")
        } else {
          code.push("+A[", j, "][", k, "]")
        }
      }
      code.push("]")
    }
    code.push("]),")
  }
  code.push("det(A)]}return ", funcName)
  var proc = new Function("det", code.join(""))
  if(n < 6) {
    return proc(determinant[n])
  }
  return proc(determinant)
}

function robustLinearSolve0d() {
  return [ 0 ]
}

function robustLinearSolve1d(A, b) {
  return [ [ b[0] ], [ A[0][0] ] ]
}

var CACHE = [
  robustLinearSolve0d,
  robustLinearSolve1d
]

function generateDispatch() {
  while(CACHE.length < NUM_EXPAND) {
    CACHE.push(generateSolver(CACHE.length))
  }
  var procArgs = []
  var code = ["function dispatchLinearSolve(A,b){switch(A.length){"]
  for(var i=0; i<NUM_EXPAND; ++i) {
    procArgs.push("s" + i)
    code.push("case ", i, ":return s", i, "(A,b);")
  }
  code.push("}var s=CACHE[A.length];if(!s)s=CACHE[A.length]=g(A.length);return s(A,b)}return dispatchLinearSolve")
  procArgs.push("CACHE", "g", code.join(""))
  var proc = Function.apply(undefined, procArgs)
  module.exports = proc.apply(undefined, CACHE.concat([CACHE, generateSolver]))
  for(var i=0; i<NUM_EXPAND; ++i) {
    module.exports[i] = CACHE[i]
  }
}

generateDispatch()
},{"robust-determinant":484}],488:[function(_dereq_,module,exports){
"use strict"

var twoProduct = _dereq_("two-product")
var robustSum = _dereq_("robust-sum")
var robustScale = _dereq_("robust-scale")
var robustSubtract = _dereq_("robust-subtract")

var NUM_EXPAND = 5

var EPSILON     = 1.1102230246251565e-16
var ERRBOUND3   = (3.0 + 16.0 * EPSILON) * EPSILON
var ERRBOUND4   = (7.0 + 56.0 * EPSILON) * EPSILON

function cofactor(m, c) {
  var result = new Array(m.length-1)
  for(var i=1; i<m.length; ++i) {
    var r = result[i-1] = new Array(m.length-1)
    for(var j=0,k=0; j<m.length; ++j) {
      if(j === c) {
        continue
      }
      r[k++] = m[i][j]
    }
  }
  return result
}

function matrix(n) {
  var result = new Array(n)
  for(var i=0; i<n; ++i) {
    result[i] = new Array(n)
    for(var j=0; j<n; ++j) {
      result[i][j] = ["m", j, "[", (n-i-1), "]"].join("")
    }
  }
  return result
}

function sign(n) {
  if(n & 1) {
    return "-"
  }
  return ""
}

function generateSum(expr) {
  if(expr.length === 1) {
    return expr[0]
  } else if(expr.length === 2) {
    return ["sum(", expr[0], ",", expr[1], ")"].join("")
  } else {
    var m = expr.length>>1
    return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("")
  }
}

function determinant(m) {
  if(m.length === 2) {
    return [["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("")]
  } else {
    var expr = []
    for(var i=0; i<m.length; ++i) {
      expr.push(["scale(", generateSum(determinant(cofactor(m, i))), ",", sign(i), m[0][i], ")"].join(""))
    }
    return expr
  }
}

function orientation(n) {
  var pos = []
  var neg = []
  var m = matrix(n)
  var args = []
  for(var i=0; i<n; ++i) {
    if((i&1)===0) {
      pos.push.apply(pos, determinant(cofactor(m, i)))
    } else {
      neg.push.apply(neg, determinant(cofactor(m, i)))
    }
    args.push("m" + i)
  }
  var posExpr = generateSum(pos)
  var negExpr = generateSum(neg)
  var funcName = "orientation" + n + "Exact"
  var code = ["function ", funcName, "(", args.join(), "){var p=", posExpr, ",n=", negExpr, ",d=sub(p,n);\
return d[d.length-1];};return ", funcName].join("")
  var proc = new Function("sum", "prod", "scale", "sub", code)
  return proc(robustSum, twoProduct, robustScale, robustSubtract)
}

var orientation3Exact = orientation(3)
var orientation4Exact = orientation(4)

var CACHED = [
  function orientation0() { return 0 },
  function orientation1() { return 0 },
  function orientation2(a, b) { 
    return b[0] - a[0]
  },
  function orientation3(a, b, c) {
    var l = (a[1] - c[1]) * (b[0] - c[0])
    var r = (a[0] - c[0]) * (b[1] - c[1])
    var det = l - r
    var s
    if(l > 0) {
      if(r <= 0) {
        return det
      } else {
        s = l + r
      }
    } else if(l < 0) {
      if(r >= 0) {
        return det
      } else {
        s = -(l + r)
      }
    } else {
      return det
    }
    var tol = ERRBOUND3 * s
    if(det >= tol || det <= -tol) {
      return det
    }
    return orientation3Exact(a, b, c)
  },
  function orientation4(a,b,c,d) {
    var adx = a[0] - d[0]
    var bdx = b[0] - d[0]
    var cdx = c[0] - d[0]
    var ady = a[1] - d[1]
    var bdy = b[1] - d[1]
    var cdy = c[1] - d[1]
    var adz = a[2] - d[2]
    var bdz = b[2] - d[2]
    var cdz = c[2] - d[2]
    var bdxcdy = bdx * cdy
    var cdxbdy = cdx * bdy
    var cdxady = cdx * ady
    var adxcdy = adx * cdy
    var adxbdy = adx * bdy
    var bdxady = bdx * ady
    var det = adz * (bdxcdy - cdxbdy) 
            + bdz * (cdxady - adxcdy)
            + cdz * (adxbdy - bdxady)
    var permanent = (Math.abs(bdxcdy) + Math.abs(cdxbdy)) * Math.abs(adz)
                  + (Math.abs(cdxady) + Math.abs(adxcdy)) * Math.abs(bdz)
                  + (Math.abs(adxbdy) + Math.abs(bdxady)) * Math.abs(cdz)
    var tol = ERRBOUND4 * permanent
    if ((det > tol) || (-det > tol)) {
      return det
    }
    return orientation4Exact(a,b,c,d)
  }
]

function slowOrient(args) {
  var proc = CACHED[args.length]
  if(!proc) {
    proc = CACHED[args.length] = orientation(args.length)
  }
  return proc.apply(undefined, args)
}

function generateOrientationProc() {
  while(CACHED.length <= NUM_EXPAND) {
    CACHED.push(orientation(CACHED.length))
  }
  var args = []
  var procArgs = ["slow"]
  for(var i=0; i<=NUM_EXPAND; ++i) {
    args.push("a" + i)
    procArgs.push("o" + i)
  }
  var code = [
    "function getOrientation(", args.join(), "){switch(arguments.length){case 0:case 1:return 0;"
  ]
  for(var i=2; i<=NUM_EXPAND; ++i) {
    code.push("case ", i, ":return o", i, "(", args.slice(0, i).join(), ");")
  }
  code.push("}var s=new Array(arguments.length);for(var i=0;i<arguments.length;++i){s[i]=arguments[i]};return slow(s);}return getOrientation")
  procArgs.push(code.join(""))

  var proc = Function.apply(undefined, procArgs)
  module.exports = proc.apply(undefined, [slowOrient].concat(CACHED))
  for(var i=0; i<=NUM_EXPAND; ++i) {
    module.exports[i] = CACHED[i]
  }
}

generateOrientationProc()
},{"robust-scale":490,"robust-subtract":492,"robust-sum":493,"two-product":521}],489:[function(_dereq_,module,exports){
"use strict"

var robustSum = _dereq_("robust-sum")
var robustScale = _dereq_("robust-scale")

module.exports = robustProduct

function robustProduct(a, b) {
  if(a.length === 1) {
    return robustScale(b, a[0])
  }
  if(b.length === 1) {
    return robustScale(a, b[0])
  }
  if(a.length === 0 || b.length === 0) {
    return [0]
  }
  var r = [0]
  if(a.length < b.length) {
    for(var i=0; i<a.length; ++i) {
      r = robustSum(r, robustScale(b, a[i]))
    }
  } else {
    for(var i=0; i<b.length; ++i) {
      r = robustSum(r, robustScale(a, b[i]))
    }    
  }
  return r
}
},{"robust-scale":490,"robust-sum":493}],490:[function(_dereq_,module,exports){
"use strict"

var twoProduct = _dereq_("two-product")
var twoSum = _dereq_("two-sum")

module.exports = scaleLinearExpansion

function scaleLinearExpansion(e, scale) {
  var n = e.length
  if(n === 1) {
    var ts = twoProduct(e[0], scale)
    if(ts[0]) {
      return ts
    }
    return [ ts[1] ]
  }
  var g = new Array(2 * n)
  var q = [0.1, 0.1]
  var t = [0.1, 0.1]
  var count = 0
  twoProduct(e[0], scale, q)
  if(q[0]) {
    g[count++] = q[0]
  }
  for(var i=1; i<n; ++i) {
    twoProduct(e[i], scale, t)
    var pq = q[1]
    twoSum(pq, t[0], q)
    if(q[0]) {
      g[count++] = q[0]
    }
    var a = t[1]
    var b = q[1]
    var x = a + b
    var bv = x - a
    var y = b - bv
    q[1] = x
    if(y) {
      g[count++] = y
    }
  }
  if(q[1]) {
    g[count++] = q[1]
  }
  if(count === 0) {
    g[count++] = 0.0
  }
  g.length = count
  return g
}
},{"two-product":521,"two-sum":522}],491:[function(_dereq_,module,exports){
"use strict"

module.exports = segmentsIntersect

var orient = _dereq_("robust-orientation")[3]

function checkCollinear(a0, a1, b0, b1) {

  for(var d=0; d<2; ++d) {
    var x0 = a0[d]
    var y0 = a1[d]
    var l0 = Math.min(x0, y0)
    var h0 = Math.max(x0, y0)    

    var x1 = b0[d]
    var y1 = b1[d]
    var l1 = Math.min(x1, y1)
    var h1 = Math.max(x1, y1)    

    if(h1 < l0 || h0 < l1) {
      return false
    }
  }

  return true
}

function segmentsIntersect(a0, a1, b0, b1) {
  var x0 = orient(a0, b0, b1)
  var y0 = orient(a1, b0, b1)
  if((x0 > 0 && y0 > 0) || (x0 < 0 && y0 < 0)) {
    return false
  }

  var x1 = orient(b0, a0, a1)
  var y1 = orient(b1, a0, a1)
  if((x1 > 0 && y1 > 0) || (x1 < 0 && y1 < 0)) {
    return false
  }

  //Check for degenerate collinear case
  if(x0 === 0 && y0 === 0 && x1 === 0 && y1 === 0) {
    return checkCollinear(a0, a1, b0, b1)
  }

  return true
}
},{"robust-orientation":488}],492:[function(_dereq_,module,exports){
"use strict"

module.exports = robustSubtract

//Easy case: Add two scalars
function scalarScalar(a, b) {
  var x = a + b
  var bv = x - a
  var av = x - bv
  var br = b - bv
  var ar = a - av
  var y = ar + br
  if(y) {
    return [y, x]
  }
  return [x]
}

function robustSubtract(e, f) {
  var ne = e.length|0
  var nf = f.length|0
  if(ne === 1 && nf === 1) {
    return scalarScalar(e[0], -f[0])
  }
  var n = ne + nf
  var g = new Array(n)
  var count = 0
  var eptr = 0
  var fptr = 0
  var abs = Math.abs
  var ei = e[eptr]
  var ea = abs(ei)
  var fi = -f[fptr]
  var fa = abs(fi)
  var a, b
  if(ea < fa) {
    b = ei
    eptr += 1
    if(eptr < ne) {
      ei = e[eptr]
      ea = abs(ei)
    }
  } else {
    b = fi
    fptr += 1
    if(fptr < nf) {
      fi = -f[fptr]
      fa = abs(fi)
    }
  }
  if((eptr < ne && ea < fa) || (fptr >= nf)) {
    a = ei
    eptr += 1
    if(eptr < ne) {
      ei = e[eptr]
      ea = abs(ei)
    }
  } else {
    a = fi
    fptr += 1
    if(fptr < nf) {
      fi = -f[fptr]
      fa = abs(fi)
    }
  }
  var x = a + b
  var bv = x - a
  var y = b - bv
  var q0 = y
  var q1 = x
  var _x, _bv, _av, _br, _ar
  while(eptr < ne && fptr < nf) {
    if(ea < fa) {
      a = ei
      eptr += 1
      if(eptr < ne) {
        ei = e[eptr]
        ea = abs(ei)
      }
    } else {
      a = fi
      fptr += 1
      if(fptr < nf) {
        fi = -f[fptr]
        fa = abs(fi)
      }
    }
    b = q0
    x = a + b
    bv = x - a
    y = b - bv
    if(y) {
      g[count++] = y
    }
    _x = q1 + x
    _bv = _x - q1
    _av = _x - _bv
    _br = x - _bv
    _ar = q1 - _av
    q0 = _ar + _br
    q1 = _x
  }
  while(eptr < ne) {
    a = ei
    b = q0
    x = a + b
    bv = x - a
    y = b - bv
    if(y) {
      g[count++] = y
    }
    _x = q1 + x
    _bv = _x - q1
    _av = _x - _bv
    _br = x - _bv
    _ar = q1 - _av
    q0 = _ar + _br
    q1 = _x
    eptr += 1
    if(eptr < ne) {
      ei = e[eptr]
    }
  }
  while(fptr < nf) {
    a = fi
    b = q0
    x = a + b
    bv = x - a
    y = b - bv
    if(y) {
      g[count++] = y
    } 
    _x = q1 + x
    _bv = _x - q1
    _av = _x - _bv
    _br = x - _bv
    _ar = q1 - _av
    q0 = _ar + _br
    q1 = _x
    fptr += 1
    if(fptr < nf) {
      fi = -f[fptr]
    }
  }
  if(q0) {
    g[count++] = q0
  }
  if(q1) {
    g[count++] = q1
  }
  if(!count) {
    g[count++] = 0.0  
  }
  g.length = count
  return g
}
},{}],493:[function(_dereq_,module,exports){
"use strict"

module.exports = linearExpansionSum

//Easy case: Add two scalars
function scalarScalar(a, b) {
  var x = a + b
  var bv = x - a
  var av = x - bv
  var br = b - bv
  var ar = a - av
  var y = ar + br
  if(y) {
    return [y, x]
  }
  return [x]
}

function linearExpansionSum(e, f) {
  var ne = e.length|0
  var nf = f.length|0
  if(ne === 1 && nf === 1) {
    return scalarScalar(e[0], f[0])
  }
  var n = ne + nf
  var g = new Array(n)
  var count = 0
  var eptr = 0
  var fptr = 0
  var abs = Math.abs
  var ei = e[eptr]
  var ea = abs(ei)
  var fi = f[fptr]
  var fa = abs(fi)
  var a, b
  if(ea < fa) {
    b = ei
    eptr += 1
    if(eptr < ne) {
      ei = e[eptr]
      ea = abs(ei)
    }
  } else {
    b = fi
    fptr += 1
    if(fptr < nf) {
      fi = f[fptr]
      fa = abs(fi)
    }
  }
  if((eptr < ne && ea < fa) || (fptr >= nf)) {
    a = ei
    eptr += 1
    if(eptr < ne) {
      ei = e[eptr]
      ea = abs(ei)
    }
  } else {
    a = fi
    fptr += 1
    if(fptr < nf) {
      fi = f[fptr]
      fa = abs(fi)
    }
  }
  var x = a + b
  var bv = x - a
  var y = b - bv
  var q0 = y
  var q1 = x
  var _x, _bv, _av, _br, _ar
  while(eptr < ne && fptr < nf) {
    if(ea < fa) {
      a = ei
      eptr += 1
      if(eptr < ne) {
        ei = e[eptr]
        ea = abs(ei)
      }
    } else {
      a = fi
      fptr += 1
      if(fptr < nf) {
        fi = f[fptr]
        fa = abs(fi)
      }
    }
    b = q0
    x = a + b
    bv = x - a
    y = b - bv
    if(y) {
      g[count++] = y
    }
    _x = q1 + x
    _bv = _x - q1
    _av = _x - _bv
    _br = x - _bv
    _ar = q1 - _av
    q0 = _ar + _br
    q1 = _x
  }
  while(eptr < ne) {
    a = ei
    b = q0
    x = a + b
    bv = x - a
    y = b - bv
    if(y) {
      g[count++] = y
    }
    _x = q1 + x
    _bv = _x - q1
    _av = _x - _bv
    _br = x - _bv
    _ar = q1 - _av
    q0 = _ar + _br
    q1 = _x
    eptr += 1
    if(eptr < ne) {
      ei = e[eptr]
    }
  }
  while(fptr < nf) {
    a = fi
    b = q0
    x = a + b
    bv = x - a
    y = b - bv
    if(y) {
      g[count++] = y
    } 
    _x = q1 + x
    _bv = _x - q1
    _av = _x - _bv
    _br = x - _bv
    _ar = q1 - _av
    q0 = _ar + _br
    q1 = _x
    fptr += 1
    if(fptr < nf) {
      fi = f[fptr]
    }
  }
  if(q0) {
    g[count++] = q0
  }
  if(q1) {
    g[count++] = q1
  }
  if(!count) {
    g[count++] = 0.0  
  }
  g.length = count
  return g
}
},{}],494:[function(_dereq_,module,exports){
"use strict"

module.exports = function signum(x) {
  if(x < 0) { return -1 }
  if(x > 0) { return 1 }
  return 0.0
}
},{}],495:[function(_dereq_,module,exports){
'use strict'

module.exports = boundary

var bnd = _dereq_('boundary-cells')
var reduce = _dereq_('reduce-simplicial-complex')

function boundary(cells) {
  return reduce(bnd(cells))
}

},{"boundary-cells":84,"reduce-simplicial-complex":475}],496:[function(_dereq_,module,exports){
'use strict'

module.exports = extractContour

var ndarray = _dereq_('ndarray')
var pool    = _dereq_('typedarray-pool')
var ndsort  = _dereq_('ndarray-sort')

var contourAlgorithm = _dereq_('./lib/codegen')

function getDimension(cells) {
  var numCells = cells.length
  var d = 0
  for(var i=0; i<numCells; ++i) {
    d = Math.max(d, cells[i].length)|0
  }
  return d-1
}

function getSigns(values, level) {
  var numVerts    = values.length
  var vertexSigns = pool.mallocUint8(numVerts)
  for(var i=0; i<numVerts; ++i) {
    vertexSigns[i] = (values[i] < level)|0
  }
  return vertexSigns
}

function getEdges(cells, d) {
  var numCells = cells.length
  var maxEdges = ((d * (d+1)/2) * numCells)|0
  var edges    = pool.mallocUint32(maxEdges*2)
  var ePtr     = 0
  for(var i=0; i<numCells; ++i) {
    var c = cells[i]
    var d = c.length
    for(var j=0; j<d; ++j) {
      for(var k=0; k<j; ++k) {
        var a = c[k]
        var b = c[j]
        edges[ePtr++] = Math.min(a,b)|0
        edges[ePtr++] = Math.max(a,b)|0
      }
    }
  }
  var nedges = (ePtr/2)|0
  ndsort(ndarray(edges, [nedges,2])) 
  var ptr = 2
  for(var i=2; i<ePtr; i+=2) {
    if(edges[i-2] === edges[i] &&
       edges[i-1] === edges[i+1]) {
      continue
    }
    edges[ptr++] = edges[i]
    edges[ptr++] = edges[i+1]
  }

  return ndarray(edges, [(ptr/2)|0, 2])
}

function getCrossingWeights(edges, values, signs, level) {
  var edata     = edges.data
  var numEdges  = edges.shape[0]
  var weights   = pool.mallocDouble(numEdges)
  var ptr       = 0
  for(var i=0; i<numEdges; ++i) {
    var a  = edata[2*i]
    var b  = edata[2*i+1]
    if(signs[a] === signs[b]) {
      continue
    }
    var va = values[a]
    var vb = values[b]
    edata[2*ptr]     = a
    edata[2*ptr+1]   = b
    weights[ptr++]   = (vb - level) / (vb - va)
  }
  edges.shape[0] = ptr
  return ndarray(weights, [ptr])
}

function getCascade(edges, numVerts) {
  var result   = pool.mallocInt32(numVerts*2)
  var numEdges = edges.shape[0]
  var edata    = edges.data
  result[0]    = 0
  var lastV    = 0
  for(var i=0; i<numEdges; ++i) {
    var a = edata[2*i]
    if(a !== lastV) {
      result[2*lastV+1] = i
      while(++lastV < a) {
        result[2*lastV] = i
        result[2*lastV+1] = i
      }
      result[2*lastV] = i
    }
  }
  result[2*lastV+1] = numEdges
  while(++lastV < numVerts) {
    result[2*lastV] = result[2*lastV+1] = numEdges
  }
  return result
}

function unpackEdges(edges) {
  var ne = edges.shape[0]|0
  var edata = edges.data
  var result = new Array(ne)
  for(var i=0; i<ne; ++i) {
    result[i] = [edata[2*i], edata[2*i+1]]
  }
  return result
}

function extractContour(cells, values, level, d) {
  level = level||0.0

  //If user didn't specify `d`, use brute force scan
  if(typeof d === 'undefined') {
    d = getDimension(cells)
  }

  //Count number of cells
  var numCells = cells.length
  if(numCells === 0 || d < 1) {
    return {
      cells:         [],
      vertexIds:     [],
      vertexWeights: []
    }
  }

  //Read in vertex signs
  var vertexSigns = getSigns(values, +level)

  //First get 1-skeleton, find all crossings
  var edges   = getEdges(cells, d)
  var weights = getCrossingWeights(edges, values, vertexSigns, +level)

  //Build vertex cascade to speed up binary search
  var vcascade = getCascade(edges, values.length|0)

  //Then construct cells
  var faces = contourAlgorithm(d)(cells, edges.data, vcascade, vertexSigns)

  //Unpack data into pretty format
  var uedges   = unpackEdges(edges)
  var uweights = [].slice.call(weights.data, 0, weights.shape[0])

  //Release data
  pool.free(vertexSigns)
  pool.free(edges.data)
  pool.free(weights.data)
  pool.free(vcascade)
  
  return {
    cells:         faces,
    vertexIds:     uedges,
    vertexWeights: uweights
  }
}
},{"./lib/codegen":497,"ndarray":436,"ndarray-sort":434,"typedarray-pool":523}],497:[function(_dereq_,module,exports){
'use strict'

module.exports = getPolygonizer

var pool = _dereq_('typedarray-pool')
var createMSTable = _dereq_('marching-simplex-table')

var CACHE = {}

function createCellPolygonizer(d) {
  var maxCellSize = 0
  var tables = new Array(d+1)
  tables[0] = [ [] ]
  for(var i=1; i<=d; ++i) {
    var tab = tables[i] = createMSTable(i)
    for(var j=0; j<tab.length; ++j) {
      maxCellSize = Math.max(maxCellSize, tab[i].length)
    }
  }

  var code  = [
  'function B(C,E,i,j){',
    'var a=Math.min(i,j)|0,b=Math.max(i,j)|0,l=C[2*a],h=C[2*a+1];',
    'while(l<h){',
      'var m=(l+h)>>1,v=E[2*m+1];',
      'if(v===b){return m}',
      'if(b<v){h=m}else{l=m+1}',
    '}',
    'return l;',
  '};',
  'function getContour', d, 'd(F,E,C,S){',
    'var n=F.length,R=[];',
    'for(var i=0;i<n;++i){var c=F[i],l=c.length;'
  ]

  function generateCase(facets) {
    if(facets.length <= 0) {
      return
    }
    code.push('R.push(')
    for(var i=0; i<facets.length; ++i) {
      var facet = facets[i]
      if(i > 0) {
        code.push(',')
      }
      code.push('[')
      for(var j=0; j<facet.length; ++j) {
        var f = facet[j]
        if(j > 0) {
          code.push(',')
        }
        code.push('B(C,E,c[', f[0], '],c[', f[1], '])')
      }
      code.push(']')
    }
    code.push(');')
  }

  for(var i=d+1; i>1; --i) {
    if(i < d+1) {
      code.push('else ')
    }
    code.push('if(l===', i, '){')

    //Generate mask
    var maskStr = []
    for(var j=0; j<i; ++j) {
      maskStr.push('(S[c['+j+']]<<'+j+')')
    }

    //Perform table look up
    code.push('var M=', maskStr.join('+'), 
      ';if(M===0||M===', (1<<i)-1, 
        '){continue}switch(M){')

    var tab = tables[i-1]
    for(var j=0; j<tab.length; ++j) {
      code.push('case ', j, ':')
      generateCase(tab[j])
      code.push('break;')
    }
    code.push('}}')
  }
  code.push('}return R;};return getContour', d, 'd')

  var proc = new Function('pool', code.join(''))
  return proc(pool)
}

function getPolygonizer(d) {
  var alg = CACHE[d]
  if(!alg) {
    alg = CACHE[d] = createCellPolygonizer(d) 
  }
  return alg
}
},{"marching-simplex-table":413,"typedarray-pool":523}],498:[function(_dereq_,module,exports){
"use strict"; "use restrict";

var bits      = _dereq_("bit-twiddle")
  , UnionFind = _dereq_("union-find")

//Returns the dimension of a cell complex
function dimension(cells) {
  var d = 0
    , max = Math.max
  for(var i=0, il=cells.length; i<il; ++i) {
    d = max(d, cells[i].length)
  }
  return d-1
}
exports.dimension = dimension

//Counts the number of vertices in faces
function countVertices(cells) {
  var vc = -1
    , max = Math.max
  for(var i=0, il=cells.length; i<il; ++i) {
    var c = cells[i]
    for(var j=0, jl=c.length; j<jl; ++j) {
      vc = max(vc, c[j])
    }
  }
  return vc+1
}
exports.countVertices = countVertices

//Returns a deep copy of cells
function cloneCells(cells) {
  var ncells = new Array(cells.length)
  for(var i=0, il=cells.length; i<il; ++i) {
    ncells[i] = cells[i].slice(0)
  }
  return ncells
}
exports.cloneCells = cloneCells

//Ranks a pair of cells up to permutation
function compareCells(a, b) {
  var n = a.length
    , t = a.length - b.length
    , min = Math.min
  if(t) {
    return t
  }
  switch(n) {
    case 0:
      return 0;
    case 1:
      return a[0] - b[0];
    case 2:
      var d = a[0]+a[1]-b[0]-b[1]
      if(d) {
        return d
      }
      return min(a[0],a[1]) - min(b[0],b[1])
    case 3:
      var l1 = a[0]+a[1]
        , m1 = b[0]+b[1]
      d = l1+a[2] - (m1+b[2])
      if(d) {
        return d
      }
      var l0 = min(a[0], a[1])
        , m0 = min(b[0], b[1])
        , d  = min(l0, a[2]) - min(m0, b[2])
      if(d) {
        return d
      }
      return min(l0+a[2], l1) - min(m0+b[2], m1)
    
    //TODO: Maybe optimize n=4 as well?
    
    default:
      var as = a.slice(0)
      as.sort()
      var bs = b.slice(0)
      bs.sort()
      for(var i=0; i<n; ++i) {
        t = as[i] - bs[i]
        if(t) {
          return t
        }
      }
      return 0
  }
}
exports.compareCells = compareCells

function compareZipped(a, b) {
  return compareCells(a[0], b[0])
}

//Puts a cell complex into normal order for the purposes of findCell queries
function normalize(cells, attr) {
  if(attr) {
    var len = cells.length
    var zipped = new Array(len)
    for(var i=0; i<len; ++i) {
      zipped[i] = [cells[i], attr[i]]
    }
    zipped.sort(compareZipped)
    for(var i=0; i<len; ++i) {
      cells[i] = zipped[i][0]
      attr[i] = zipped[i][1]
    }
    return cells
  } else {
    cells.sort(compareCells)
    return cells
  }
}
exports.normalize = normalize

//Removes all duplicate cells in the complex
function unique(cells) {
  if(cells.length === 0) {
    return []
  }
  var ptr = 1
    , len = cells.length
  for(var i=1; i<len; ++i) {
    var a = cells[i]
    if(compareCells(a, cells[i-1])) {
      if(i === ptr) {
        ptr++
        continue
      }
      cells[ptr++] = a
    }
  }
  cells.length = ptr
  return cells
}
exports.unique = unique;

//Finds a cell in a normalized cell complex
function findCell(cells, c) {
  var lo = 0
    , hi = cells.length-1
    , r  = -1
  while (lo <= hi) {
    var mid = (lo + hi) >> 1
      , s   = compareCells(cells[mid], c)
    if(s <= 0) {
      if(s === 0) {
        r = mid
      }
      lo = mid + 1
    } else if(s > 0) {
      hi = mid - 1
    }
  }
  return r
}
exports.findCell = findCell;

//Builds an index for an n-cell.  This is more general than dual, but less efficient
function incidence(from_cells, to_cells) {
  var index = new Array(from_cells.length)
  for(var i=0, il=index.length; i<il; ++i) {
    index[i] = []
  }
  var b = []
  for(var i=0, n=to_cells.length; i<n; ++i) {
    var c = to_cells[i]
    var cl = c.length
    for(var k=1, kn=(1<<cl); k<kn; ++k) {
      b.length = bits.popCount(k)
      var l = 0
      for(var j=0; j<cl; ++j) {
        if(k & (1<<j)) {
          b[l++] = c[j]
        }
      }
      var idx=findCell(from_cells, b)
      if(idx < 0) {
        continue
      }
      while(true) {
        index[idx++].push(i)
        if(idx >= from_cells.length || compareCells(from_cells[idx], b) !== 0) {
          break
        }
      }
    }
  }
  return index
}
exports.incidence = incidence

//Computes the dual of the mesh.  This is basically an optimized version of buildIndex for the situation where from_cells is just the list of vertices
function dual(cells, vertex_count) {
  if(!vertex_count) {
    return incidence(unique(skeleton(cells, 0)), cells, 0)
  }
  var res = new Array(vertex_count)
  for(var i=0; i<vertex_count; ++i) {
    res[i] = []
  }
  for(var i=0, len=cells.length; i<len; ++i) {
    var c = cells[i]
    for(var j=0, cl=c.length; j<cl; ++j) {
      res[c[j]].push(i)
    }
  }
  return res
}
exports.dual = dual

//Enumerates all cells in the complex
function explode(cells) {
  var result = []
  for(var i=0, il=cells.length; i<il; ++i) {
    var c = cells[i]
      , cl = c.length|0
    for(var j=1, jl=(1<<cl); j<jl; ++j) {
      var b = []
      for(var k=0; k<cl; ++k) {
        if((j >>> k) & 1) {
          b.push(c[k])
        }
      }
      result.push(b)
    }
  }
  return normalize(result)
}
exports.explode = explode

//Enumerates all of the n-cells of a cell complex
function skeleton(cells, n) {
  if(n < 0) {
    return []
  }
  var result = []
    , k0     = (1<<(n+1))-1
  for(var i=0; i<cells.length; ++i) {
    var c = cells[i]
    for(var k=k0; k<(1<<c.length); k=bits.nextCombination(k)) {
      var b = new Array(n+1)
        , l = 0
      for(var j=0; j<c.length; ++j) {
        if(k & (1<<j)) {
          b[l++] = c[j]
        }
      }
      result.push(b)
    }
  }
  return normalize(result)
}
exports.skeleton = skeleton;

//Computes the boundary of all cells, does not remove duplicates
function boundary(cells) {
  var res = []
  for(var i=0,il=cells.length; i<il; ++i) {
    var c = cells[i]
    for(var j=0,cl=c.length; j<cl; ++j) {
      var b = new Array(c.length-1)
      for(var k=0, l=0; k<cl; ++k) {
        if(k !== j) {
          b[l++] = c[k]
        }
      }
      res.push(b)
    }
  }
  return normalize(res)
}
exports.boundary = boundary;

//Computes connected components for a dense cell complex
function connectedComponents_dense(cells, vertex_count) {
  var labels = new UnionFind(vertex_count)
  for(var i=0; i<cells.length; ++i) {
    var c = cells[i]
    for(var j=0; j<c.length; ++j) {
      for(var k=j+1; k<c.length; ++k) {
        labels.link(c[j], c[k])
      }
    }
  }
  var components = []
    , component_labels = labels.ranks
  for(var i=0; i<component_labels.length; ++i) {
    component_labels[i] = -1
  }
  for(var i=0; i<cells.length; ++i) {
    var l = labels.find(cells[i][0])
    if(component_labels[l] < 0) {
      component_labels[l] = components.length
      components.push([cells[i].slice(0)])
    } else {
      components[component_labels[l]].push(cells[i].slice(0))
    }
  }
  return components
}

//Computes connected components for a sparse graph
function connectedComponents_sparse(cells) {
  var vertices  = unique(normalize(skeleton(cells, 0)))
    , labels    = new UnionFind(vertices.length)
  for(var i=0; i<cells.length; ++i) {
    var c = cells[i]
    for(var j=0; j<c.length; ++j) {
      var vj = findCell(vertices, [c[j]])
      for(var k=j+1; k<c.length; ++k) {
        labels.link(vj, findCell(vertices, [c[k]]))
      }
    }
  }
  var components        = []
    , component_labels  = labels.ranks
  for(var i=0; i<component_labels.length; ++i) {
    component_labels[i] = -1
  }
  for(var i=0; i<cells.length; ++i) {
    var l = labels.find(findCell(vertices, [cells[i][0]]));
    if(component_labels[l] < 0) {
      component_labels[l] = components.length
      components.push([cells[i].slice(0)])
    } else {
      components[component_labels[l]].push(cells[i].slice(0))
    }
  }
  return components
}

//Computes connected components for a cell complex
function connectedComponents(cells, vertex_count) {
  if(vertex_count) {
    return connectedComponents_dense(cells, vertex_count)
  }
  return connectedComponents_sparse(cells)
}
exports.connectedComponents = connectedComponents

},{"bit-twiddle":81,"union-find":524}],499:[function(_dereq_,module,exports){
arguments[4][81][0].apply(exports,arguments)
},{"dup":81}],500:[function(_dereq_,module,exports){
arguments[4][498][0].apply(exports,arguments)
},{"bit-twiddle":499,"dup":498,"union-find":501}],501:[function(_dereq_,module,exports){
"use strict"; "use restrict";

module.exports = UnionFind;

function UnionFind(count) {
  this.roots = new Array(count);
  this.ranks = new Array(count);
  
  for(var i=0; i<count; ++i) {
    this.roots[i] = i;
    this.ranks[i] = 0;
  }
}

UnionFind.prototype.length = function() {
  return this.roots.length;
}

UnionFind.prototype.makeSet = function() {
  var n = this.roots.length;
  this.roots.push(n);
  this.ranks.push(0);
  return n;
}

UnionFind.prototype.find = function(x) {
  var roots = this.roots;
  while(roots[x] !== x) {
    var y = roots[x];
    roots[x] = roots[y];
    x = y;
  }
  return x;
}

UnionFind.prototype.link = function(x, y) {
  var xr = this.find(x)
    , yr = this.find(y);
  if(xr === yr) {
    return;
  }
  var ranks = this.ranks
    , roots = this.roots
    , xd    = ranks[xr]
    , yd    = ranks[yr];
  if(xd < yd) {
    roots[xr] = yr;
  } else if(yd < xd) {
    roots[yr] = xr;
  } else {
    roots[yr] = xr;
    ++ranks[xr];
  }
}


},{}],502:[function(_dereq_,module,exports){
"use strict"

module.exports = simplifyPolygon

var orient = _dereq_("robust-orientation")
var sc = _dereq_("simplicial-complex")

function errorWeight(base, a, b) {
  var area = Math.abs(orient(base, a, b))
  var perim = Math.sqrt(Math.pow(a[0] - b[0], 2) + Math.pow(a[1]-b[1], 2))
  return area / perim
}

function simplifyPolygon(cells, positions, minArea) {

  var n = positions.length
  var nc = cells.length
  var inv = new Array(n)
  var outv = new Array(n)
  var weights = new Array(n)
  var dead = new Array(n)
  
  //Initialize tables
  for(var i=0; i<n; ++i) {
    inv[i] = outv[i] = -1
    weights[i] = Infinity
    dead[i] = false
  }

  //Compute neighbors
  for(var i=0; i<nc; ++i) {
    var c = cells[i]
    if(c.length !== 2) {
      throw new Error("Input must be a graph")
    }
    var s = c[1]
    var t = c[0]
    if(outv[t] !== -1) {
      outv[t] = -2
    } else {
      outv[t] = s
    }
    if(inv[s] !== -1) {
      inv[s] = -2
    } else {
      inv[s] = t
    }
  }

  //Updates the weight for vertex i
  function computeWeight(i) {
    if(dead[i]) {
      return Infinity
    }
    //TODO: Check that the line segment doesn't cross once simplified
    var s = inv[i]
    var t = outv[i]
    if((s<0) || (t<0)) {
      return Infinity
    } else {
      return errorWeight(positions[i], positions[s], positions[t])
    }
  }

  //Swaps two nodes on the heap (i,j) are the index of the nodes
  function heapSwap(i,j) {
    var a = heap[i]
    var b = heap[j]
    heap[i] = b
    heap[j] = a
    index[a] = j
    index[b] = i
  }

  //Returns the weight of node i on the heap
  function heapWeight(i) {
    return weights[heap[i]]
  }

  function heapParent(i) {
    if(i & 1) {
      return (i - 1) >> 1
    }
    return (i >> 1) - 1
  }

  //Bubble element i down the heap
  function heapDown(i) {
    var w = heapWeight(i)
    while(true) {
      var tw = w
      var left  = 2*i + 1
      var right = 2*(i + 1)
      var next = i
      if(left < heapCount) {
        var lw = heapWeight(left)
        if(lw < tw) {
          next = left
          tw = lw
        }
      }
      if(right < heapCount) {
        var rw = heapWeight(right)
        if(rw < tw) {
          next = right
        }
      }
      if(next === i) {
        return i
      }
      heapSwap(i, next)
      i = next      
    }
  }

  //Bubbles element i up the heap
  function heapUp(i) {
    var w = heapWeight(i)
    while(i > 0) {
      var parent = heapParent(i)
      if(parent >= 0) {
        var pw = heapWeight(parent)
        if(w < pw) {
          heapSwap(i, parent)
          i = parent
          continue
        }
      }
      return i
    }
  }

  //Pop minimum element
  function heapPop() {
    if(heapCount > 0) {
      var head = heap[0]
      heapSwap(0, heapCount-1)
      heapCount -= 1
      heapDown(0)
      return head
    }
    return -1
  }

  //Update heap item i
  function heapUpdate(i, w) {
    var a = heap[i]
    if(weights[a] === w) {
      return i
    }
    weights[a] = -Infinity
    heapUp(i)
    heapPop()
    weights[a] = w
    heapCount += 1
    return heapUp(heapCount-1)
  }

  //Kills a vertex (assume vertex already removed from heap)
  function kill(i) {
    if(dead[i]) {
      return
    }
    //Kill vertex
    dead[i] = true
    //Fixup topology
    var s = inv[i]
    var t = outv[i]
    if(inv[t] >= 0) {
      inv[t] = s
    }
    if(outv[s] >= 0) {
      outv[s] = t
    }

    //Update weights on s and t
    if(index[s] >= 0) {
      heapUpdate(index[s], computeWeight(s))
    }
    if(index[t] >= 0) {
      heapUpdate(index[t], computeWeight(t))
    }
  }

  //Initialize weights and heap
  var heap = []
  var index = new Array(n)
  for(var i=0; i<n; ++i) {
    var w = weights[i] = computeWeight(i)
    if(w < Infinity) {
      index[i] = heap.length
      heap.push(i)
    } else {
      index[i] = -1
    }
  }
  var heapCount = heap.length
  for(var i=heapCount>>1; i>=0; --i) {
    heapDown(i)
  }
  
  //Kill vertices
  while(true) {
    var hmin = heapPop()
    if((hmin < 0) || (weights[hmin] > minArea)) {
      break
    }
    kill(hmin)
  }

  //Build collapsed vertex table
  var npositions = []
  for(var i=0; i<n; ++i) {
    if(!dead[i]) {
      index[i] = npositions.length
      npositions.push(positions[i].slice())
    }
  }
  var nv = npositions.length

  function tortoiseHare(seq, start) {
    if(seq[start] < 0) {
      return start
    }
    var t = start
    var h = start
    do {
      //Walk two steps with h
      var nh = seq[h]
      if(!dead[h] || nh < 0 || nh === h) {
        break
      }
      h = nh
      nh = seq[h]
      if(!dead[h] || nh < 0 || nh === h) {
        break
      }
      h = nh

      //Walk one step with t
      t = seq[t]
    } while(t !== h)
    //Compress cycles
    for(var v=start; v!==h; v = seq[v]) {
      seq[v] = h
    }
    return h
  }

  var ncells = []
  cells.forEach(function(c) {
    var tin = tortoiseHare(inv, c[0])
    var tout = tortoiseHare(outv, c[1])
    if(tin >= 0 && tout >= 0 && tin !== tout) {
      var cin = index[tin]
      var cout = index[tout]
      if(cin !== cout) {
        ncells.push([ cin, cout ])
      }
    }
  })

  //Normalize result
  sc.unique(sc.normalize(ncells))

  //Return final list of cells
  return {
    positions: npositions,
    edges: ncells
  }
}
},{"robust-orientation":488,"simplicial-complex":500}],503:[function(_dereq_,module,exports){
"use strict"

module.exports = orderSegments

var orient = _dereq_("robust-orientation")

function horizontalOrder(a, b) {
  var bl, br
  if(b[0][0] < b[1][0]) {
    bl = b[0]
    br = b[1]
  } else if(b[0][0] > b[1][0]) {
    bl = b[1]
    br = b[0]
  } else {
    var alo = Math.min(a[0][1], a[1][1])
    var ahi = Math.max(a[0][1], a[1][1])
    var blo = Math.min(b[0][1], b[1][1])
    var bhi = Math.max(b[0][1], b[1][1])
    if(ahi < blo) {
      return ahi - blo
    }
    if(alo > bhi) {
      return alo - bhi
    }
    return ahi - bhi
  }
  var al, ar
  if(a[0][1] < a[1][1]) {
    al = a[0]
    ar = a[1]
  } else {
    al = a[1]
    ar = a[0]
  }
  var d = orient(br, bl, al)
  if(d) {
    return d
  }
  d = orient(br, bl, ar)
  if(d) {
    return d
  }
  return ar - br
}

function orderSegments(b, a) {
  var al, ar
  if(a[0][0] < a[1][0]) {
    al = a[0]
    ar = a[1]
  } else if(a[0][0] > a[1][0]) {
    al = a[1]
    ar = a[0]
  } else {
    return horizontalOrder(a, b)
  }
  var bl, br
  if(b[0][0] < b[1][0]) {
    bl = b[0]
    br = b[1]
  } else if(b[0][0] > b[1][0]) {
    bl = b[1]
    br = b[0]
  } else {
    return -horizontalOrder(b, a)
  }
  var d1 = orient(al, ar, br)
  var d2 = orient(al, ar, bl)
  if(d1 < 0) {
    if(d2 <= 0) {
      return d1
    }
  } else if(d1 > 0) {
    if(d2 >= 0) {
      return d1
    }
  } else if(d2) {
    return d2
  }
  d1 = orient(br, bl, ar)
  d2 = orient(br, bl, al)
  if(d1 < 0) {
    if(d2 <= 0) {
      return d1
    }
  } else if(d1 > 0) {
    if(d2 >= 0) {
      return d1
    }
  } else if(d2) {
    return d2
  }
  return ar[0] - br[0]
}
},{"robust-orientation":488}],504:[function(_dereq_,module,exports){
"use strict"

module.exports = createSlabDecomposition

var bounds = _dereq_("binary-search-bounds")
var createRBTree = _dereq_("functional-red-black-tree")
var orient = _dereq_("robust-orientation")
var orderSegments = _dereq_("./lib/order-segments")

function SlabDecomposition(slabs, coordinates, horizontal) {
  this.slabs = slabs
  this.coordinates = coordinates
  this.horizontal = horizontal
}

var proto = SlabDecomposition.prototype

function compareHorizontal(e, y) {
  return e.y - y
}

function searchBucket(root, p) {
  var lastNode = null
  while(root) {
    var seg = root.key
    var l, r
    if(seg[0][0] < seg[1][0]) {
      l = seg[0]
      r = seg[1]
    } else {
      l = seg[1]
      r = seg[0]
    }
    var o = orient(l, r, p)
    if(o < 0) {
      root = root.left
    } else if(o > 0) {
      if(p[0] !== seg[1][0]) {
        lastNode = root
        root = root.right
      } else {
        var val = searchBucket(root.right, p)
        if(val) {
          return val
        }
        root = root.left
      }
    } else {
      if(p[0] !== seg[1][0]) {
        return root
      } else {
        var val = searchBucket(root.right, p)
        if(val) {
          return val
        }
        root = root.left
      }
    }
  }
  return lastNode
}

proto.castUp = function(p) {
  var bucket = bounds.le(this.coordinates, p[0])
  if(bucket < 0) {
    return -1
  }
  var root = this.slabs[bucket]
  var hitNode = searchBucket(this.slabs[bucket], p)
  var lastHit = -1
  if(hitNode) {
    lastHit = hitNode.value
  }
  //Edge case: need to handle horizontal segments (sucks)
  if(this.coordinates[bucket] === p[0]) {
    var lastSegment = null
    if(hitNode) {
      lastSegment = hitNode.key
    }
    if(bucket > 0) {
      var otherHitNode = searchBucket(this.slabs[bucket-1], p)
      if(otherHitNode) {
        if(lastSegment) {
          if(orderSegments(otherHitNode.key, lastSegment) > 0) {
            lastSegment = otherHitNode.key
            lastHit = otherHitNode.value
          }
        } else {
          lastHit = otherHitNode.value
          lastSegment = otherHitNode.key
        }
      }
    }
    var horiz = this.horizontal[bucket]
    if(horiz.length > 0) {
      var hbucket = bounds.ge(horiz, p[1], compareHorizontal)
      if(hbucket < horiz.length) {
        var e = horiz[hbucket]
        if(p[1] === e.y) {
          if(e.closed) {
            return e.index
          } else {
            while(hbucket < horiz.length-1 && horiz[hbucket+1].y === p[1]) {
              hbucket = hbucket+1
              e = horiz[hbucket]
              if(e.closed) {
                return e.index
              }
            }
            if(e.y === p[1] && !e.start) {
              hbucket = hbucket+1
              if(hbucket >= horiz.length) {
                return lastHit
              }
              e = horiz[hbucket]
            }
          }
        }
        //Check if e is above/below last segment
        if(e.start) {
          if(lastSegment) {
            var o = orient(lastSegment[0], lastSegment[1], [p[0], e.y])
            if(lastSegment[0][0] > lastSegment[1][0]) {
              o = -o
            }
            if(o > 0) {
              lastHit = e.index
            }
          } else {
            lastHit = e.index
          }
        } else if(e.y !== p[1]) {
          lastHit = e.index
        }
      }
    }
  }
  return lastHit
}

function IntervalSegment(y, index, start, closed) {
  this.y = y
  this.index = index
  this.start = start
  this.closed = closed
}

function Event(x, segment, create, index) {
  this.x = x
  this.segment = segment
  this.create = create
  this.index = index
}


function createSlabDecomposition(segments) {
  var numSegments = segments.length
  var numEvents = 2 * numSegments
  var events = new Array(numEvents)
  for(var i=0; i<numSegments; ++i) {
    var s = segments[i]
    var f = s[0][0] < s[1][0]
    events[2*i] = new Event(s[0][0], s, f, i)
    events[2*i+1] = new Event(s[1][0], s, !f, i)
  }
  events.sort(function(a,b) {
    var d = a.x - b.x
    if(d) {
      return d
    }
    d = a.create - b.create
    if(d) {
      return d
    }
    return Math.min(a.segment[0][1], a.segment[1][1]) - Math.min(b.segment[0][1], b.segment[1][1])
  })
  var tree = createRBTree(orderSegments)
  var slabs = []
  var lines = []
  var horizontal = []
  var lastX = -Infinity
  for(var i=0; i<numEvents; ) {
    var x = events[i].x
    var horiz = []
    while(i < numEvents) {
      var e = events[i]
      if(e.x !== x) {
        break
      }
      i += 1
      if(e.segment[0][0] === e.x && e.segment[1][0] === e.x) {
        if(e.create) {
          if(e.segment[0][1] < e.segment[1][1]) {
            horiz.push(new IntervalSegment(
                e.segment[0][1],
                e.index,
                true,
                true))
            horiz.push(new IntervalSegment(
                e.segment[1][1],
                e.index,
                false,
                false))
          } else {
            horiz.push(new IntervalSegment(
                e.segment[1][1],
                e.index,
                true,
                false))
            horiz.push(new IntervalSegment(
                e.segment[0][1],
                e.index,
                false,
                true))
          }
        }
      } else {
        if(e.create) {
          tree = tree.insert(e.segment, e.index)
        } else {
          tree = tree.remove(e.segment)
        }
      }
    }
    slabs.push(tree.root)
    lines.push(x)
    horizontal.push(horiz)
  }
  return new SlabDecomposition(slabs, lines, horizontal)
}
},{"./lib/order-segments":503,"binary-search-bounds":80,"functional-red-black-tree":220,"robust-orientation":488}],505:[function(_dereq_,module,exports){
"use strict"

var robustDot = _dereq_("robust-dot-product")
var robustSum = _dereq_("robust-sum")

module.exports = splitPolygon
module.exports.positive = positive
module.exports.negative = negative

function planeT(p, plane) {
  var r = robustSum(robustDot(p, plane), [plane[plane.length-1]])
  return r[r.length-1]
}


//Can't do this exactly and emit a floating point result
function lerpW(a, wa, b, wb) {
  var d = wb - wa
  var t = -wa / d
  if(t < 0.0) {
    t = 0.0
  } else if(t > 1.0) {
    t = 1.0
  }
  var ti = 1.0 - t
  var n = a.length
  var r = new Array(n)
  for(var i=0; i<n; ++i) {
    r[i] = t * a[i] + ti * b[i]
  }
  return r
}

function splitPolygon(points, plane) {
  var pos = []
  var neg = []
  var a = planeT(points[points.length-1], plane)
  for(var s=points[points.length-1], t=points[0], i=0; i<points.length; ++i, s=t) {
    t = points[i]
    var b = planeT(t, plane)
    if((a < 0 && b > 0) || (a > 0 && b < 0)) {
      var p = lerpW(s, b, t, a)
      pos.push(p)
      neg.push(p.slice())
    }
    if(b < 0) {
      neg.push(t.slice())
    } else if(b > 0) {
      pos.push(t.slice())
    } else {
      pos.push(t.slice())
      neg.push(t.slice())
    }
    a = b
  }
  return { positive: pos, negative: neg }
}

function positive(points, plane) {
  var pos = []
  var a = planeT(points[points.length-1], plane)
  for(var s=points[points.length-1], t=points[0], i=0; i<points.length; ++i, s=t) {
    t = points[i]
    var b = planeT(t, plane)
    if((a < 0 && b > 0) || (a > 0 && b < 0)) {
      pos.push(lerpW(s, b, t, a))
    }
    if(b >= 0) {
      pos.push(t.slice())
    }
    a = b
  }
  return pos
}

function negative(points, plane) {
  var neg = []
  var a = planeT(points[points.length-1], plane)
  for(var s=points[points.length-1], t=points[0], i=0; i<points.length; ++i, s=t) {
    t = points[i]
    var b = planeT(t, plane)
    if((a < 0 && b > 0) || (a > 0 && b < 0)) {
      neg.push(lerpW(s, b, t, a))
    }
    if(b <= 0) {
      neg.push(t.slice())
    }
    a = b
  }
  return neg
}
},{"robust-dot-product":485,"robust-sum":493}],506:[function(_dereq_,module,exports){
/* global window, exports, define */

!function() {
    'use strict'

    var re = {
        not_string: /[^s]/,
        not_bool: /[^t]/,
        not_type: /[^T]/,
        not_primitive: /[^v]/,
        number: /[diefg]/,
        numeric_arg: /[bcdiefguxX]/,
        json: /[j]/,
        not_json: /[^j]/,
        text: /^[^\x25]+/,
        modulo: /^\x25{2}/,
        placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
        key: /^([a-z_][a-z_\d]*)/i,
        key_access: /^\.([a-z_][a-z_\d]*)/i,
        index_access: /^\[(\d+)\]/,
        sign: /^[+-]/
    }

    function sprintf(key) {
        // `arguments` is not an array, but should be fine for this call
        return sprintf_format(sprintf_parse(key), arguments)
    }

    function vsprintf(fmt, argv) {
        return sprintf.apply(null, [fmt].concat(argv || []))
    }

    function sprintf_format(parse_tree, argv) {
        var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign
        for (i = 0; i < tree_length; i++) {
            if (typeof parse_tree[i] === 'string') {
                output += parse_tree[i]
            }
            else if (typeof parse_tree[i] === 'object') {
                ph = parse_tree[i] // convenience purposes only
                if (ph.keys) { // keyword argument
                    arg = argv[cursor]
                    for (k = 0; k < ph.keys.length; k++) {
                        if (arg == undefined) {
                            throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k-1]))
                        }
                        arg = arg[ph.keys[k]]
                    }
                }
                else if (ph.param_no) { // positional argument (explicit)
                    arg = argv[ph.param_no]
                }
                else { // positional argument (implicit)
                    arg = argv[cursor++]
                }

                if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
                    arg = arg()
                }

                if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {
                    throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg))
                }

                if (re.number.test(ph.type)) {
                    is_positive = arg >= 0
                }

                switch (ph.type) {
                    case 'b':
                        arg = parseInt(arg, 10).toString(2)
                        break
                    case 'c':
                        arg = String.fromCharCode(parseInt(arg, 10))
                        break
                    case 'd':
                    case 'i':
                        arg = parseInt(arg, 10)
                        break
                    case 'j':
                        arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0)
                        break
                    case 'e':
                        arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential()
                        break
                    case 'f':
                        arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg)
                        break
                    case 'g':
                        arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg)
                        break
                    case 'o':
                        arg = (parseInt(arg, 10) >>> 0).toString(8)
                        break
                    case 's':
                        arg = String(arg)
                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
                        break
                    case 't':
                        arg = String(!!arg)
                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
                        break
                    case 'T':
                        arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase()
                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
                        break
                    case 'u':
                        arg = parseInt(arg, 10) >>> 0
                        break
                    case 'v':
                        arg = arg.valueOf()
                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
                        break
                    case 'x':
                        arg = (parseInt(arg, 10) >>> 0).toString(16)
                        break
                    case 'X':
                        arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase()
                        break
                }
                if (re.json.test(ph.type)) {
                    output += arg
                }
                else {
                    if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
                        sign = is_positive ? '+' : '-'
                        arg = arg.toString().replace(re.sign, '')
                    }
                    else {
                        sign = ''
                    }
                    pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' '
                    pad_length = ph.width - (sign + arg).length
                    pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : ''
                    output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg)
                }
            }
        }
        return output
    }

    var sprintf_cache = Object.create(null)

    function sprintf_parse(fmt) {
        if (sprintf_cache[fmt]) {
            return sprintf_cache[fmt]
        }

        var _fmt = fmt, match, parse_tree = [], arg_names = 0
        while (_fmt) {
            if ((match = re.text.exec(_fmt)) !== null) {
                parse_tree.push(match[0])
            }
            else if ((match = re.modulo.exec(_fmt)) !== null) {
                parse_tree.push('%')
            }
            else if ((match = re.placeholder.exec(_fmt)) !== null) {
                if (match[2]) {
                    arg_names |= 1
                    var field_list = [], replacement_field = match[2], field_match = []
                    if ((field_match = re.key.exec(replacement_field)) !== null) {
                        field_list.push(field_match[1])
                        while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
                            if ((field_match = re.key_access.exec(replacement_field)) !== null) {
                                field_list.push(field_match[1])
                            }
                            else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
                                field_list.push(field_match[1])
                            }
                            else {
                                throw new SyntaxError('[sprintf] failed to parse named argument key')
                            }
                        }
                    }
                    else {
                        throw new SyntaxError('[sprintf] failed to parse named argument key')
                    }
                    match[2] = field_list
                }
                else {
                    arg_names |= 2
                }
                if (arg_names === 3) {
                    throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported')
                }

                parse_tree.push(
                    {
                        placeholder: match[0],
                        param_no:    match[1],
                        keys:        match[2],
                        sign:        match[3],
                        pad_char:    match[4],
                        align:       match[5],
                        width:       match[6],
                        precision:   match[7],
                        type:        match[8]
                    }
                )
            }
            else {
                throw new SyntaxError('[sprintf] unexpected placeholder')
            }
            _fmt = _fmt.substring(match[0].length)
        }
        return sprintf_cache[fmt] = parse_tree
    }

    /**
     * export to either browser or node.js
     */
    /* eslint-disable quote-props */
    if (typeof exports !== 'undefined') {
        exports['sprintf'] = sprintf
        exports['vsprintf'] = vsprintf
    }
    if (typeof window !== 'undefined') {
        window['sprintf'] = sprintf
        window['vsprintf'] = vsprintf

        if (typeof define === 'function' && define['amd']) {
            define(function() {
                return {
                    'sprintf': sprintf,
                    'vsprintf': vsprintf
                }
            })
        }
    }
    /* eslint-enable quote-props */
}(); // eslint-disable-line

},{}],507:[function(_dereq_,module,exports){
'use strict'

var paren = _dereq_('parenthesis')

module.exports = function splitBy (string, separator, o) {
	if (string == null) throw Error('First argument should be a string')
	if (separator == null) throw Error('Separator should be a string or a RegExp')

	if (!o) o = {}
	else if (typeof o === 'string' || Array.isArray(o)) {
		o = {ignore: o}
	}

	if (o.escape == null) o.escape = true
	if (o.ignore == null) o.ignore = ['[]', '()', '{}', '<>', '""', "''", '``', '“”', '«»']
	else {
		if (typeof o.ignore === 'string') {o.ignore = [o.ignore]}

		o.ignore = o.ignore.map(function (pair) {
			// '"' → '""'
			if (pair.length === 1) pair = pair + pair
			return pair
		})
	}

	var tokens = paren.parse(string, {flat: true, brackets: o.ignore})
	var str = tokens[0]

	var parts = str.split(separator)

	// join parts separated by escape
	if (o.escape) {
		var cleanParts = []
		for (var i = 0; i < parts.length; i++) {
			var prev = parts[i]
			var part = parts[i + 1]

			if (prev[prev.length - 1] === '\\' && prev[prev.length - 2] !== '\\') {
				cleanParts.push(prev + separator + part)
				i++
			}
			else {
				cleanParts.push(prev)
			}
		}
		parts = cleanParts
	}

	// open parens pack & apply unquotes, if any
	for (var i = 0; i < parts.length; i++) {
		tokens[0] = parts[i]
		parts[i] = paren.stringify(tokens, {flat: true})
	}

	return parts
}

},{"parenthesis":444}],508:[function(_dereq_,module,exports){
"use strict"

module.exports = stronglyConnectedComponents

function stronglyConnectedComponents(adjList) {
  var numVertices = adjList.length;
  var index = new Array(numVertices)
  var lowValue = new Array(numVertices)
  var active = new Array(numVertices)
  var child = new Array(numVertices)
  var scc = new Array(numVertices)
  var sccLinks = new Array(numVertices)
  
  //Initialize tables
  for(var i=0; i<numVertices; ++i) {
    index[i] = -1
    lowValue[i] = 0
    active[i] = false
    child[i] = 0
    scc[i] = -1
    sccLinks[i] = []
  }

  // The strongConnect function
  var count = 0
  var components = []
  var sccAdjList = []

  function strongConnect(v) {
    // To avoid running out of stack space, this emulates the recursive behaviour of the normal algorithm, effectively using T as the call stack.
    var S = [v], T = [v]
    index[v] = lowValue[v] = count
    active[v] = true
    count += 1
    while(T.length > 0) {
      v = T[T.length-1]
      var e = adjList[v]
      if (child[v] < e.length) { // If we're not done iterating over the children, first try finishing that.
        for(var i=child[v]; i<e.length; ++i) { // Start where we left off.
          var u = e[i]
          if(index[u] < 0) {
            index[u] = lowValue[u] = count
            active[u] = true
            count += 1
            S.push(u)
            T.push(u)
            break // First recurse, then continue here (with the same child!).
            // There is a slight change to Tarjan's algorithm here.
            // Normally, after having recursed, we set lowValue like we do for an active child (although some variants of the algorithm do it slightly differently).
            // Here, we only do so if the child we recursed on is still active.
            // The reasoning is that if it is no longer active, it must have had a lowValue equal to its own index, which means that it is necessarily higher than our lowValue.
          } else if (active[u]) {
            lowValue[v] = Math.min(lowValue[v], lowValue[u])|0
          }
          if (scc[u] >= 0) {
            // Node v is not yet assigned an scc, but once it is that scc can apparently reach scc[u].
            sccLinks[v].push(scc[u])
          }
        }
        child[v] = i // Remember where we left off.
      } else { // If we're done iterating over the children, check whether we have an scc.
        if(lowValue[v] === index[v]) { // TODO: It /might/ be true that T is always a prefix of S (at this point!!!), and if so, this could be used here.
          var component = []
          var links = [], linkCount = 0
          for(var i=S.length-1; i>=0; --i) {
            var w = S[i]
            active[w] = false
            component.push(w)
            links.push(sccLinks[w])
            linkCount += sccLinks[w].length
            scc[w] = components.length
            if(w === v) {
              S.length = i
              break
            }
          }
          components.push(component)
          var allLinks = new Array(linkCount)
          for(var i=0; i<links.length; i++) {
            for(var j=0; j<links[i].length; j++) {
              allLinks[--linkCount] = links[i][j]
            }
          }
          sccAdjList.push(allLinks)
        }
        T.pop() // Now we're finished exploring this particular node (normally corresponds to the return statement)
      }
    }
  }

  //Run strong connect starting from each vertex
  for(var i=0; i<numVertices; ++i) {
    if(index[i] < 0) {
      strongConnect(i)
    }
  }
  
  // Compact sccAdjList
  var newE
  for(var i=0; i<sccAdjList.length; i++) {
    var e = sccAdjList[i]
    if (e.length === 0) continue
    e.sort(function (a,b) { return a-b; })
    newE = [e[0]]
    for(var j=1; j<e.length; j++) {
      if (e[j] !== e[j-1]) {
        newE.push(e[j])
      }
    }
    sccAdjList[i] = newE
  }  

  return {components: components, adjacencyList: sccAdjList}
}

},{}],509:[function(_dereq_,module,exports){
"use strict"

module.exports = surfaceNets

var generateContourExtractor = _dereq_("ndarray-extract-contour")
var triangulateCube = _dereq_("triangulate-hypercube")
var zeroCrossings = _dereq_("zero-crossings")

function buildSurfaceNets(order, dtype) {
  var dimension = order.length
  var code = ["'use strict';"]
  var funcName = "surfaceNets" + order.join("_") + "d" + dtype

  //Contour extraction function
  code.push(
    "var contour=genContour({",
      "order:[", order.join(), "],",
      "scalarArguments: 3,",
      "phase:function phaseFunc(p,a,b,c) { return (p > c)|0 },")
  if(dtype === "generic") {
    code.push("getters:[0],")
  }

  //Generate vertex function
  var cubeArgs = []
  var extraArgs = []
  for(var i=0; i<dimension; ++i) {
    cubeArgs.push("d" + i)
    extraArgs.push("d" + i)
  }
  for(var i=0; i<(1<<dimension); ++i) {
    cubeArgs.push("v" + i)
    extraArgs.push("v" + i)
  }
  for(var i=0; i<(1<<dimension); ++i) {
    cubeArgs.push("p" + i)
    extraArgs.push("p" + i)
  }
  cubeArgs.push("a", "b", "c")
  extraArgs.push("a", "c")
  code.push("vertex:function vertexFunc(", cubeArgs.join(), "){")
  //Mask args together
  var maskStr = []
  for(var i=0; i<(1<<dimension); ++i) {
    maskStr.push("(p" + i + "<<" + i + ")")
  }
  //Generate variables and giganto switch statement
  code.push("var m=(", maskStr.join("+"), ")|0;if(m===0||m===", (1<<(1<<dimension))-1, "){return}")
  var extraFuncs = []
  var currentFunc = []
  if(1<<(1<<dimension) <= 128) {
    code.push("switch(m){")
    currentFunc = code
  } else {
    code.push("switch(m>>>7){")
  }
  for(var i=0; i<1<<(1<<dimension); ++i) {
    if(1<<(1<<dimension) > 128) {
      if((i%128)===0) {
        if(extraFuncs.length > 0) {
          currentFunc.push("}}")
        }
        var efName = "vExtra" + extraFuncs.length
        code.push("case ", (i>>>7), ":", efName, "(m&0x7f,", extraArgs.join(), ");break;")
        currentFunc = [
          "function ", efName, "(m,", extraArgs.join(), "){switch(m){"
        ]
        extraFuncs.push(currentFunc)
      }  
    }
    currentFunc.push("case ", (i&0x7f), ":")
    var crossings = new Array(dimension)
    var denoms = new Array(dimension)
    var crossingCount = new Array(dimension)
    var bias = new Array(dimension)
    var totalCrossings = 0
    for(var j=0; j<dimension; ++j) {
      crossings[j] = []
      denoms[j] = []
      crossingCount[j] = 0
      bias[j] = 0
    }
    for(var j=0; j<(1<<dimension); ++j) {
      for(var k=0; k<dimension; ++k) {
        var u = j ^ (1<<k)
        if(u > j) {
          continue
        }
        if(!(i&(1<<u)) !== !(i&(1<<j))) {
          var sign = 1
          if(i&(1<<u)) {
            denoms[k].push("v" + u + "-v" + j)
          } else {
            denoms[k].push("v" + j + "-v" + u)
            sign = -sign
          }
          if(sign < 0) {
            crossings[k].push("-v" + j + "-v" + u)
            crossingCount[k] += 2
          } else {
            crossings[k].push("v" + j + "+v" + u)
            crossingCount[k] -= 2            
          }
          totalCrossings += 1
          for(var l=0; l<dimension; ++l) {
            if(l === k) {
              continue
            }
            if(u&(1<<l)) {
              bias[l] += 1
            } else {
              bias[l] -= 1
            }
          }
        }
      }
    }
    var vertexStr = []
    for(var k=0; k<dimension; ++k) {
      if(crossings[k].length === 0) {
        vertexStr.push("d" + k + "-0.5")
      } else {
        var cStr = ""
        if(crossingCount[k] < 0) {
          cStr = crossingCount[k] + "*c"
        } else if(crossingCount[k] > 0) {
          cStr = "+" + crossingCount[k] + "*c"
        }
        var weight = 0.5 * (crossings[k].length / totalCrossings)
        var shift = 0.5 + 0.5 * (bias[k] / totalCrossings)
        vertexStr.push("d" + k + "-" + shift + "-" + weight + "*(" + crossings[k].join("+") + cStr + ")/(" + denoms[k].join("+") + ")")
        
      }
    }
    currentFunc.push("a.push([", vertexStr.join(), "]);",
      "break;")
  }
  code.push("}},")
  if(extraFuncs.length > 0) {
    currentFunc.push("}}")
  }

  //Create face function
  var faceArgs = []
  for(var i=0; i<(1<<(dimension-1)); ++i) {
    faceArgs.push("v" + i)
  }
  faceArgs.push("c0", "c1", "p0", "p1", "a", "b", "c")
  code.push("cell:function cellFunc(", faceArgs.join(), "){")

  var facets = triangulateCube(dimension-1)
  code.push("if(p0){b.push(",
    facets.map(function(f) {
      return "[" + f.map(function(v) {
        return "v" + v
      }) + "]"
    }).join(), ")}else{b.push(",
    facets.map(function(f) {
      var e = f.slice()
      e.reverse()
      return "[" + e.map(function(v) {
        return "v" + v
      }) + "]"
    }).join(),
    ")}}});function ", funcName, "(array,level){var verts=[],cells=[];contour(array,verts,cells,level);return {positions:verts,cells:cells};} return ", funcName, ";")

  for(var i=0; i<extraFuncs.length; ++i) {
    code.push(extraFuncs[i].join(""))
  }

  //Compile and link
  var proc = new Function("genContour", code.join(""))
  return proc(generateContourExtractor)
}

//1D case: Need to handle specially
function mesh1D(array, level) {
  var zc = zeroCrossings(array, level)
  var n = zc.length
  var npos = new Array(n)
  var ncel = new Array(n)
  for(var i=0; i<n; ++i) {
    npos[i] = [ zc[i] ]
    ncel[i] = [ i ]
  }
  return {
    positions: npos,
    cells: ncel
  }
}

var CACHE = {}

function surfaceNets(array,level) {
  if(array.dimension <= 0) {
    return { positions: [], cells: [] }
  } else if(array.dimension === 1) {
    return mesh1D(array, level)
  }
  var typesig = array.order.join() + "-" + array.dtype
  var proc = CACHE[typesig]
  var level = (+level) || 0.0
  if(!proc) {
    proc = CACHE[typesig] = buildSurfaceNets(array.order, array.dtype)
  }
  return proc(array,level)
}
},{"ndarray-extract-contour":425,"triangulate-hypercube":519,"zero-crossings":552}],510:[function(_dereq_,module,exports){
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var TAU = Math.PI * 2;

var mapToEllipse = function mapToEllipse(_ref, rx, ry, cosphi, sinphi, centerx, centery) {
  var x = _ref.x,
      y = _ref.y;

  x *= rx;
  y *= ry;

  var xp = cosphi * x - sinphi * y;
  var yp = sinphi * x + cosphi * y;

  return {
    x: xp + centerx,
    y: yp + centery
  };
};

var approxUnitArc = function approxUnitArc(ang1, ang2) {
  // See http://spencermortensen.com/articles/bezier-circle/ for the derivation
  // of this constant.
  var c = 0.551915024494;

  var x1 = Math.cos(ang1);
  var y1 = Math.sin(ang1);
  var x2 = Math.cos(ang1 + ang2);
  var y2 = Math.sin(ang1 + ang2);

  return [{
    x: x1 - y1 * c,
    y: y1 + x1 * c
  }, {
    x: x2 + y2 * c,
    y: y2 - x2 * c
  }, {
    x: x2,
    y: y2
  }];
};

var vectorAngle = function vectorAngle(ux, uy, vx, vy) {
  var sign = ux * vy - uy * vx < 0 ? -1 : 1;
  var umag = Math.sqrt(ux * ux + uy * uy);
  var vmag = Math.sqrt(ux * ux + uy * uy);
  var dot = ux * vx + uy * vy;

  var div = dot / (umag * vmag);

  if (div > 1) {
    div = 1;
  }

  if (div < -1) {
    div = -1;
  }

  return sign * Math.acos(div);
};

var getArcCenter = function getArcCenter(px, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp) {
  var rxsq = Math.pow(rx, 2);
  var rysq = Math.pow(ry, 2);
  var pxpsq = Math.pow(pxp, 2);
  var pypsq = Math.pow(pyp, 2);

  var radicant = rxsq * rysq - rxsq * pypsq - rysq * pxpsq;

  if (radicant < 0) {
    radicant = 0;
  }

  radicant /= rxsq * pypsq + rysq * pxpsq;
  radicant = Math.sqrt(radicant) * (largeArcFlag === sweepFlag ? -1 : 1);

  var centerxp = radicant * rx / ry * pyp;
  var centeryp = radicant * -ry / rx * pxp;

  var centerx = cosphi * centerxp - sinphi * centeryp + (px + cx) / 2;
  var centery = sinphi * centerxp + cosphi * centeryp + (py + cy) / 2;

  var vx1 = (pxp - centerxp) / rx;
  var vy1 = (pyp - centeryp) / ry;
  var vx2 = (-pxp - centerxp) / rx;
  var vy2 = (-pyp - centeryp) / ry;

  var ang1 = vectorAngle(1, 0, vx1, vy1);
  var ang2 = vectorAngle(vx1, vy1, vx2, vy2);

  if (sweepFlag === 0 && ang2 > 0) {
    ang2 -= TAU;
  }

  if (sweepFlag === 1 && ang2 < 0) {
    ang2 += TAU;
  }

  return [centerx, centery, ang1, ang2];
};

var arcToBezier = function arcToBezier(_ref2) {
  var px = _ref2.px,
      py = _ref2.py,
      cx = _ref2.cx,
      cy = _ref2.cy,
      rx = _ref2.rx,
      ry = _ref2.ry,
      _ref2$xAxisRotation = _ref2.xAxisRotation,
      xAxisRotation = _ref2$xAxisRotation === undefined ? 0 : _ref2$xAxisRotation,
      _ref2$largeArcFlag = _ref2.largeArcFlag,
      largeArcFlag = _ref2$largeArcFlag === undefined ? 0 : _ref2$largeArcFlag,
      _ref2$sweepFlag = _ref2.sweepFlag,
      sweepFlag = _ref2$sweepFlag === undefined ? 0 : _ref2$sweepFlag;

  var curves = [];

  if (rx === 0 || ry === 0) {
    return [];
  }

  var sinphi = Math.sin(xAxisRotation * TAU / 360);
  var cosphi = Math.cos(xAxisRotation * TAU / 360);

  var pxp = cosphi * (px - cx) / 2 + sinphi * (py - cy) / 2;
  var pyp = -sinphi * (px - cx) / 2 + cosphi * (py - cy) / 2;

  if (pxp === 0 && pyp === 0) {
    return [];
  }

  rx = Math.abs(rx);
  ry = Math.abs(ry);

  var lambda = Math.pow(pxp, 2) / Math.pow(rx, 2) + Math.pow(pyp, 2) / Math.pow(ry, 2);

  if (lambda > 1) {
    rx *= Math.sqrt(lambda);
    ry *= Math.sqrt(lambda);
  }

  var _getArcCenter = getArcCenter(px, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp),
      _getArcCenter2 = _slicedToArray(_getArcCenter, 4),
      centerx = _getArcCenter2[0],
      centery = _getArcCenter2[1],
      ang1 = _getArcCenter2[2],
      ang2 = _getArcCenter2[3];

  // If 'ang2' == 90.0000000001, then `ratio` will evaluate to
  // 1.0000000001. This causes `segments` to be greater than one, which is an
  // unecessary split, and adds extra points to the bezier curve. To alleviate
  // this issue, we round to 1.0 when the ratio is close to 1.0.


  var ratio = Math.abs(ang2) / (TAU / 4);
  if (Math.abs(1.0 - ratio) < 0.0000001) {
    ratio = 1.0;
  }

  var segments = Math.max(Math.ceil(ratio), 1);

  ang2 /= segments;

  for (var i = 0; i < segments; i++) {
    curves.push(approxUnitArc(ang1, ang2));
    ang1 += ang2;
  }

  return curves.map(function (curve) {
    var _mapToEllipse = mapToEllipse(curve[0], rx, ry, cosphi, sinphi, centerx, centery),
        x1 = _mapToEllipse.x,
        y1 = _mapToEllipse.y;

    var _mapToEllipse2 = mapToEllipse(curve[1], rx, ry, cosphi, sinphi, centerx, centery),
        x2 = _mapToEllipse2.x,
        y2 = _mapToEllipse2.y;

    var _mapToEllipse3 = mapToEllipse(curve[2], rx, ry, cosphi, sinphi, centerx, centery),
        x = _mapToEllipse3.x,
        y = _mapToEllipse3.y;

    return { x1: x1, y1: y1, x2: x2, y2: y2, x: x, y: y };
  });
};

exports.default = arcToBezier;
module.exports = exports.default;
},{}],511:[function(_dereq_,module,exports){
'use strict'

var parse = _dereq_('parse-svg-path')
var abs = _dereq_('abs-svg-path')
var normalize = _dereq_('normalize-svg-path')
var isSvgPath = _dereq_('is-svg-path')
var assert = _dereq_('assert')

module.exports = pathBounds


function pathBounds(path) {
  // ES6 string tpl call
  if (Array.isArray(path) && path.length === 1 && typeof path[0] === 'string') path = path[0]

  // svg path string
  if (typeof path === 'string') {
    assert(isSvgPath(path), 'String is not an SVG path.')
    path = parse(path)
  }

  assert(Array.isArray(path), 'Argument should be a string or an array of path segments.')

  path = abs(path)
  path = normalize(path)

  if (!path.length) return [0, 0, 0, 0]

  var bounds = [Infinity, Infinity, -Infinity, -Infinity]

  for (var i = 0, l = path.length; i < l; i++) {
    var points = path[i].slice(1)

    for (var j = 0; j < points.length; j += 2) {
      if (points[j + 0] < bounds[0]) bounds[0] = points[j + 0]
      if (points[j + 1] < bounds[1]) bounds[1] = points[j + 1]
      if (points[j + 0] > bounds[2]) bounds[2] = points[j + 0]
      if (points[j + 1] > bounds[3]) bounds[3] = points[j + 1]
    }
  }

  return bounds
}

},{"abs-svg-path":49,"assert":57,"is-svg-path":410,"normalize-svg-path":512,"parse-svg-path":446}],512:[function(_dereq_,module,exports){
'use strict'

module.exports = normalize

var arcToCurve = _dereq_('svg-arc-to-cubic-bezier')

function normalize(path){
  // init state
  var prev
  var result = []
  var bezierX = 0
  var bezierY = 0
  var startX = 0
  var startY = 0
  var quadX = null
  var quadY = null
  var x = 0
  var y = 0

  for (var i = 0, len = path.length; i < len; i++) {
    var seg = path[i]
    var command = seg[0]

    switch (command) {
      case 'M':
        startX = seg[1]
        startY = seg[2]
        break
      case 'A':
        var curves = arcToCurve({
          px: x,
          py: y,
          cx: seg[6],
          cy:  seg[7],
          rx: seg[1],
          ry: seg[2],
          xAxisRotation: seg[3],
          largeArcFlag: seg[4],
          sweepFlag: seg[5]
        })

        // null-curves
        if (!curves.length) continue

        for (var j = 0, c; j < curves.length; j++) {
          c = curves[j]
          seg = ['C', c.x1, c.y1, c.x2, c.y2, c.x, c.y]
          if (j < curves.length - 1) result.push(seg)
        }

        break
      case 'S':
        // default control point
        var cx = x
        var cy = y
        if (prev == 'C' || prev == 'S') {
          cx += cx - bezierX // reflect the previous command's control
          cy += cy - bezierY // point relative to the current point
        }
        seg = ['C', cx, cy, seg[1], seg[2], seg[3], seg[4]]
        break
      case 'T':
        if (prev == 'Q' || prev == 'T') {
          quadX = x * 2 - quadX // as with 'S' reflect previous control point
          quadY = y * 2 - quadY
        } else {
          quadX = x
          quadY = y
        }
        seg = quadratic(x, y, quadX, quadY, seg[1], seg[2])
        break
      case 'Q':
        quadX = seg[1]
        quadY = seg[2]
        seg = quadratic(x, y, seg[1], seg[2], seg[3], seg[4])
        break
      case 'L':
        seg = line(x, y, seg[1], seg[2])
        break
      case 'H':
        seg = line(x, y, seg[1], y)
        break
      case 'V':
        seg = line(x, y, x, seg[1])
        break
      case 'Z':
        seg = line(x, y, startX, startY)
        break
    }

    // update state
    prev = command
    x = seg[seg.length - 2]
    y = seg[seg.length - 1]
    if (seg.length > 4) {
      bezierX = seg[seg.length - 4]
      bezierY = seg[seg.length - 3]
    } else {
      bezierX = x
      bezierY = y
    }
    result.push(seg)
  }

  return result
}

function line(x1, y1, x2, y2){
  return ['C', x1, y1, x2, y2, x2, y2]
}

function quadratic(x1, y1, cx, cy, x2, y2){
  return [
    'C',
    x1/3 + (2/3) * cx,
    y1/3 + (2/3) * cy,
    x2/3 + (2/3) * cx,
    y2/3 + (2/3) * cy,
    x2,
    y2
  ]
}

},{"svg-arc-to-cubic-bezier":510}],513:[function(_dereq_,module,exports){
'use strict'

var pathBounds = _dereq_('svg-path-bounds')
var parsePath = _dereq_('parse-svg-path')
var drawPath = _dereq_('draw-svg-path')
var isSvgPath = _dereq_('is-svg-path')
var bitmapSdf = _dereq_('bitmap-sdf')

var canvas = document.createElement('canvas')
var ctx = canvas.getContext('2d')


module.exports = pathSdf


function pathSdf (path, options) {
	if (!isSvgPath(path)) throw Error('Argument should be valid svg path string')

	if (!options) options = {}

	var w, h
	if (options.shape) {
		w = options.shape[0]
		h = options.shape[1]
	}
	else {
		w = canvas.width = options.w || options.width || 200
		h = canvas.height = options.h || options.height || 200
	}
	var size = Math.min(w, h)

	var stroke = options.stroke || 0

	var viewbox = options.viewbox || options.viewBox || pathBounds(path)
	var scale = [w / (viewbox[2] - viewbox[0]), h / (viewbox[3] - viewbox[1])]
	var maxScale = Math.min(scale[0] || 0, scale[1] || 0) / 2

	//clear ctx
	ctx.fillStyle = 'black'
	ctx.fillRect(0, 0, w, h)

	ctx.fillStyle = 'white'

	if (stroke)	{
		if (typeof stroke != 'number') stroke = 1
		if (stroke > 0) {
			ctx.strokeStyle = 'white'
		}
		else {
			ctx.strokeStyle = 'black'
		}

		ctx.lineWidth = Math.abs(stroke)
	}

	ctx.translate(w * .5, h * .5)
	ctx.scale(maxScale, maxScale)

	//if canvas svg paths api is available
	if (isPath2DSupported()) {
		var path2d = new Path2D(path)
		ctx.fill(path2d)
		stroke && ctx.stroke(path2d)
	}
	//fallback to bezier-curves
	else {
		var segments = parsePath(path)
		drawPath(ctx, segments)
		ctx.fill()
		stroke && ctx.stroke()
	}

	ctx.setTransform(1, 0, 0, 1, 0, 0);

	var data = bitmapSdf(ctx, {
		cutoff: options.cutoff != null ? options.cutoff : .5,
		radius: options.radius != null ? options.radius : size * .5
	})

	return data
}

var path2DSupported

function isPath2DSupported () {
	if (path2DSupported != null) return path2DSupported

	var ctx = document.createElement('canvas').getContext('2d')
	ctx.canvas.width = ctx.canvas.height = 1

	if (!window.Path2D) return path2DSupported = false

	var path = new Path2D('M0,0h1v1h-1v-1Z')

	ctx.fillStyle = 'black'
	ctx.fill(path)

	var idata = ctx.getImageData(0,0,1,1)

	return path2DSupported = idata && idata.data && idata.data[3] === 255
}

},{"bitmap-sdf":82,"draw-svg-path":154,"is-svg-path":410,"parse-svg-path":446,"svg-path-bounds":511}],514:[function(_dereq_,module,exports){
(function (process){
'use strict'

module.exports = textGet

var vectorizeText = _dereq_('vectorize-text')

var globals = window || process.global || {}
var __TEXT_CACHE  = globals.__TEXT_CACHE || {}
globals.__TEXT_CACHE = {}

function unwrap(mesh) {
  var cells     = mesh.cells
  var positions = mesh.positions
  var data      = new Float32Array(cells.length * 6)
  var ptr       = 0
  var shapeX    = 0
  for(var i=0; i<cells.length; ++i) {
    var tri = cells[i]
    for(var j=0; j<3; ++j) {
      var point = positions[tri[j]]
      data[ptr++] = point[0]
      data[ptr++] = point[1] + 1.4
      shapeX      = Math.max(point[0], shapeX)
    }
  }
  return {
    data:  data,
    shape: shapeX
  }
}

function textGet(font, text, opts) {
  var opts = opts || {}
  var fontcache = __TEXT_CACHE[font]
  if(!fontcache) {
    fontcache = __TEXT_CACHE[font] = {
      ' ': {
        data:   new Float32Array(0),
        shape: 0.2
      }
    }
  }
  var mesh = fontcache[text]
  if(!mesh) {
    if(text.length <= 1 || !/\d/.test(text)) {
      mesh = fontcache[text] = unwrap(vectorizeText(text, {
        triangles:     true,
        font:          font,
        textAlign:     opts.textAlign || 'left',
        textBaseline:  'alphabetic',
        styletags: {
            breaklines: true,
                 bolds: true,
               italics: true,
            subscripts: true,
          superscripts: true
        }
      }))
    } else {
      var parts = text.split(/(\d|\s)/)
      var buffer = new Array(parts.length)
      var bufferSize = 0
      var shapeX = 0
      for(var i=0; i<parts.length; ++i) {
        buffer[i] = textGet(font, parts[i])
        bufferSize += buffer[i].data.length
        shapeX += buffer[i].shape
        if(i>0) {
          shapeX += 0.02
        }
      }

      var data = new Float32Array(bufferSize)
      var ptr     = 0
      var xOffset = -0.5 * shapeX
      for(var i=0; i<buffer.length; ++i) {
        var bdata = buffer[i].data
        for(var j=0; j<bdata.length; j+=2) {
          data[ptr++] = bdata[j] + xOffset
          data[ptr++] = bdata[j+1]
        }
        xOffset += buffer[i].shape + 0.02
      }

      mesh = fontcache[text] = {
        data:  data,
        shape: shapeX
      }
    }
  }

   return mesh
}

}).call(this,_dereq_('_process'))
},{"_process":468,"vectorize-text":528}],515:[function(_dereq_,module,exports){
// TinyColor v1.4.1
// https://github.com/bgrins/TinyColor
// Brian Grinstead, MIT License

(function(Math) {

var trimLeft = /^\s+/,
    trimRight = /\s+$/,
    tinyCounter = 0,
    mathRound = Math.round,
    mathMin = Math.min,
    mathMax = Math.max,
    mathRandom = Math.random;

function tinycolor (color, opts) {

    color = (color) ? color : '';
    opts = opts || { };

    // If input is already a tinycolor, return itself
    if (color instanceof tinycolor) {
       return color;
    }
    // If we are called as a function, call using new instead
    if (!(this instanceof tinycolor)) {
        return new tinycolor(color, opts);
    }

    var rgb = inputToRGB(color);
    this._originalInput = color,
    this._r = rgb.r,
    this._g = rgb.g,
    this._b = rgb.b,
    this._a = rgb.a,
    this._roundA = mathRound(100*this._a) / 100,
    this._format = opts.format || rgb.format;
    this._gradientType = opts.gradientType;

    // Don't let the range of [0,255] come back in [0,1].
    // Potentially lose a little bit of precision here, but will fix issues where
    // .5 gets interpreted as half of the total, instead of half of 1
    // If it was supposed to be 128, this was already taken care of by `inputToRgb`
    if (this._r < 1) { this._r = mathRound(this._r); }
    if (this._g < 1) { this._g = mathRound(this._g); }
    if (this._b < 1) { this._b = mathRound(this._b); }

    this._ok = rgb.ok;
    this._tc_id = tinyCounter++;
}

tinycolor.prototype = {
    isDark: function() {
        return this.getBrightness() < 128;
    },
    isLight: function() {
        return !this.isDark();
    },
    isValid: function() {
        return this._ok;
    },
    getOriginalInput: function() {
      return this._originalInput;
    },
    getFormat: function() {
        return this._format;
    },
    getAlpha: function() {
        return this._a;
    },
    getBrightness: function() {
        //http://www.w3.org/TR/AERT#color-contrast
        var rgb = this.toRgb();
        return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
    },
    getLuminance: function() {
        //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
        var rgb = this.toRgb();
        var RsRGB, GsRGB, BsRGB, R, G, B;
        RsRGB = rgb.r/255;
        GsRGB = rgb.g/255;
        BsRGB = rgb.b/255;

        if (RsRGB <= 0.03928) {R = RsRGB / 12.92;} else {R = Math.pow(((RsRGB + 0.055) / 1.055), 2.4);}
        if (GsRGB <= 0.03928) {G = GsRGB / 12.92;} else {G = Math.pow(((GsRGB + 0.055) / 1.055), 2.4);}
        if (BsRGB <= 0.03928) {B = BsRGB / 12.92;} else {B = Math.pow(((BsRGB + 0.055) / 1.055), 2.4);}
        return (0.2126 * R) + (0.7152 * G) + (0.0722 * B);
    },
    setAlpha: function(value) {
        this._a = boundAlpha(value);
        this._roundA = mathRound(100*this._a) / 100;
        return this;
    },
    toHsv: function() {
        var hsv = rgbToHsv(this._r, this._g, this._b);
        return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };
    },
    toHsvString: function() {
        var hsv = rgbToHsv(this._r, this._g, this._b);
        var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);
        return (this._a == 1) ?
          "hsv("  + h + ", " + s + "%, " + v + "%)" :
          "hsva(" + h + ", " + s + "%, " + v + "%, "+ this._roundA + ")";
    },
    toHsl: function() {
        var hsl = rgbToHsl(this._r, this._g, this._b);
        return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };
    },
    toHslString: function() {
        var hsl = rgbToHsl(this._r, this._g, this._b);
        var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);
        return (this._a == 1) ?
          "hsl("  + h + ", " + s + "%, " + l + "%)" :
          "hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")";
    },
    toHex: function(allow3Char) {
        return rgbToHex(this._r, this._g, this._b, allow3Char);
    },
    toHexString: function(allow3Char) {
        return '#' + this.toHex(allow3Char);
    },
    toHex8: function(allow4Char) {
        return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char);
    },
    toHex8String: function(allow4Char) {
        return '#' + this.toHex8(allow4Char);
    },
    toRgb: function() {
        return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a };
    },
    toRgbString: function() {
        return (this._a == 1) ?
          "rgb("  + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" :
          "rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")";
    },
    toPercentageRgb: function() {
        return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a };
    },
    toPercentageRgbString: function() {
        return (this._a == 1) ?
          "rgb("  + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" :
          "rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")";
    },
    toName: function() {
        if (this._a === 0) {
            return "transparent";
        }

        if (this._a < 1) {
            return false;
        }

        return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
    },
    toFilter: function(secondColor) {
        var hex8String = '#' + rgbaToArgbHex(this._r, this._g, this._b, this._a);
        var secondHex8String = hex8String;
        var gradientType = this._gradientType ? "GradientType = 1, " : "";

        if (secondColor) {
            var s = tinycolor(secondColor);
            secondHex8String = '#' + rgbaToArgbHex(s._r, s._g, s._b, s._a);
        }

        return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")";
    },
    toString: function(format) {
        var formatSet = !!format;
        format = format || this._format;

        var formattedString = false;
        var hasAlpha = this._a < 1 && this._a >= 0;
        var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name");

        if (needsAlphaFormat) {
            // Special case for "transparent", all other non-alpha formats
            // will return rgba when there is transparency.
            if (format === "name" && this._a === 0) {
                return this.toName();
            }
            return this.toRgbString();
        }
        if (format === "rgb") {
            formattedString = this.toRgbString();
        }
        if (format === "prgb") {
            formattedString = this.toPercentageRgbString();
        }
        if (format === "hex" || format === "hex6") {
            formattedString = this.toHexString();
        }
        if (format === "hex3") {
            formattedString = this.toHexString(true);
        }
        if (format === "hex4") {
            formattedString = this.toHex8String(true);
        }
        if (format === "hex8") {
            formattedString = this.toHex8String();
        }
        if (format === "name") {
            formattedString = this.toName();
        }
        if (format === "hsl") {
            formattedString = this.toHslString();
        }
        if (format === "hsv") {
            formattedString = this.toHsvString();
        }

        return formattedString || this.toHexString();
    },
    clone: function() {
        return tinycolor(this.toString());
    },

    _applyModification: function(fn, args) {
        var color = fn.apply(null, [this].concat([].slice.call(args)));
        this._r = color._r;
        this._g = color._g;
        this._b = color._b;
        this.setAlpha(color._a);
        return this;
    },
    lighten: function() {
        return this._applyModification(lighten, arguments);
    },
    brighten: function() {
        return this._applyModification(brighten, arguments);
    },
    darken: function() {
        return this._applyModification(darken, arguments);
    },
    desaturate: function() {
        return this._applyModification(desaturate, arguments);
    },
    saturate: function() {
        return this._applyModification(saturate, arguments);
    },
    greyscale: function() {
        return this._applyModification(greyscale, arguments);
    },
    spin: function() {
        return this._applyModification(spin, arguments);
    },

    _applyCombination: function(fn, args) {
        return fn.apply(null, [this].concat([].slice.call(args)));
    },
    analogous: function() {
        return this._applyCombination(analogous, arguments);
    },
    complement: function() {
        return this._applyCombination(complement, arguments);
    },
    monochromatic: function() {
        return this._applyCombination(monochromatic, arguments);
    },
    splitcomplement: function() {
        return this._applyCombination(splitcomplement, arguments);
    },
    triad: function() {
        return this._applyCombination(triad, arguments);
    },
    tetrad: function() {
        return this._applyCombination(tetrad, arguments);
    }
};

// If input is an object, force 1 into "1.0" to handle ratios properly
// String input requires "1.0" as input, so 1 will be treated as 1
tinycolor.fromRatio = function(color, opts) {
    if (typeof color == "object") {
        var newColor = {};
        for (var i in color) {
            if (color.hasOwnProperty(i)) {
                if (i === "a") {
                    newColor[i] = color[i];
                }
                else {
                    newColor[i] = convertToPercentage(color[i]);
                }
            }
        }
        color = newColor;
    }

    return tinycolor(color, opts);
};

// Given a string or object, convert that input to RGB
// Possible string inputs:
//
//     "red"
//     "#f00" or "f00"
//     "#ff0000" or "ff0000"
//     "#ff000000" or "ff000000"
//     "rgb 255 0 0" or "rgb (255, 0, 0)"
//     "rgb 1.0 0 0" or "rgb (1, 0, 0)"
//     "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
//     "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
//     "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
//     "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
//     "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
//
function inputToRGB(color) {

    var rgb = { r: 0, g: 0, b: 0 };
    var a = 1;
    var s = null;
    var v = null;
    var l = null;
    var ok = false;
    var format = false;

    if (typeof color == "string") {
        color = stringInputToObject(color);
    }

    if (typeof color == "object") {
        if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) {
            rgb = rgbToRgb(color.r, color.g, color.b);
            ok = true;
            format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
        }
        else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) {
            s = convertToPercentage(color.s);
            v = convertToPercentage(color.v);
            rgb = hsvToRgb(color.h, s, v);
            ok = true;
            format = "hsv";
        }
        else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) {
            s = convertToPercentage(color.s);
            l = convertToPercentage(color.l);
            rgb = hslToRgb(color.h, s, l);
            ok = true;
            format = "hsl";
        }

        if (color.hasOwnProperty("a")) {
            a = color.a;
        }
    }

    a = boundAlpha(a);

    return {
        ok: ok,
        format: color.format || format,
        r: mathMin(255, mathMax(rgb.r, 0)),
        g: mathMin(255, mathMax(rgb.g, 0)),
        b: mathMin(255, mathMax(rgb.b, 0)),
        a: a
    };
}


// Conversion Functions
// --------------------

// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
// <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript>

// `rgbToRgb`
// Handle bounds / percentage checking to conform to CSS color spec
// <http://www.w3.org/TR/css3-color/>
// *Assumes:* r, g, b in [0, 255] or [0, 1]
// *Returns:* { r, g, b } in [0, 255]
function rgbToRgb(r, g, b){
    return {
        r: bound01(r, 255) * 255,
        g: bound01(g, 255) * 255,
        b: bound01(b, 255) * 255
    };
}

// `rgbToHsl`
// Converts an RGB color value to HSL.
// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]
// *Returns:* { h, s, l } in [0,1]
function rgbToHsl(r, g, b) {

    r = bound01(r, 255);
    g = bound01(g, 255);
    b = bound01(b, 255);

    var max = mathMax(r, g, b), min = mathMin(r, g, b);
    var h, s, l = (max + min) / 2;

    if(max == min) {
        h = s = 0; // achromatic
    }
    else {
        var d = max - min;
        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
        switch(max) {
            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
            case g: h = (b - r) / d + 2; break;
            case b: h = (r - g) / d + 4; break;
        }

        h /= 6;
    }

    return { h: h, s: s, l: l };
}

// `hslToRgb`
// Converts an HSL color value to RGB.
// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]
// *Returns:* { r, g, b } in the set [0, 255]
function hslToRgb(h, s, l) {
    var r, g, b;

    h = bound01(h, 360);
    s = bound01(s, 100);
    l = bound01(l, 100);

    function hue2rgb(p, q, t) {
        if(t < 0) t += 1;
        if(t > 1) t -= 1;
        if(t < 1/6) return p + (q - p) * 6 * t;
        if(t < 1/2) return q;
        if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
        return p;
    }

    if(s === 0) {
        r = g = b = l; // achromatic
    }
    else {
        var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
        var p = 2 * l - q;
        r = hue2rgb(p, q, h + 1/3);
        g = hue2rgb(p, q, h);
        b = hue2rgb(p, q, h - 1/3);
    }

    return { r: r * 255, g: g * 255, b: b * 255 };
}

// `rgbToHsv`
// Converts an RGB color value to HSV
// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]
// *Returns:* { h, s, v } in [0,1]
function rgbToHsv(r, g, b) {

    r = bound01(r, 255);
    g = bound01(g, 255);
    b = bound01(b, 255);

    var max = mathMax(r, g, b), min = mathMin(r, g, b);
    var h, s, v = max;

    var d = max - min;
    s = max === 0 ? 0 : d / max;

    if(max == min) {
        h = 0; // achromatic
    }
    else {
        switch(max) {
            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
            case g: h = (b - r) / d + 2; break;
            case b: h = (r - g) / d + 4; break;
        }
        h /= 6;
    }
    return { h: h, s: s, v: v };
}

// `hsvToRgb`
// Converts an HSV color value to RGB.
// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]
// *Returns:* { r, g, b } in the set [0, 255]
 function hsvToRgb(h, s, v) {

    h = bound01(h, 360) * 6;
    s = bound01(s, 100);
    v = bound01(v, 100);

    var i = Math.floor(h),
        f = h - i,
        p = v * (1 - s),
        q = v * (1 - f * s),
        t = v * (1 - (1 - f) * s),
        mod = i % 6,
        r = [v, q, p, p, t, v][mod],
        g = [t, v, v, q, p, p][mod],
        b = [p, p, t, v, v, q][mod];

    return { r: r * 255, g: g * 255, b: b * 255 };
}

// `rgbToHex`
// Converts an RGB color to hex
// Assumes r, g, and b are contained in the set [0, 255]
// Returns a 3 or 6 character hex
function rgbToHex(r, g, b, allow3Char) {

    var hex = [
        pad2(mathRound(r).toString(16)),
        pad2(mathRound(g).toString(16)),
        pad2(mathRound(b).toString(16))
    ];

    // Return a 3 character hex if possible
    if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
        return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
    }

    return hex.join("");
}

// `rgbaToHex`
// Converts an RGBA color plus alpha transparency to hex
// Assumes r, g, b are contained in the set [0, 255] and
// a in [0, 1]. Returns a 4 or 8 character rgba hex
function rgbaToHex(r, g, b, a, allow4Char) {

    var hex = [
        pad2(mathRound(r).toString(16)),
        pad2(mathRound(g).toString(16)),
        pad2(mathRound(b).toString(16)),
        pad2(convertDecimalToHex(a))
    ];

    // Return a 4 character hex if possible
    if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) {
        return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0);
    }

    return hex.join("");
}

// `rgbaToArgbHex`
// Converts an RGBA color to an ARGB Hex8 string
// Rarely used, but required for "toFilter()"
function rgbaToArgbHex(r, g, b, a) {

    var hex = [
        pad2(convertDecimalToHex(a)),
        pad2(mathRound(r).toString(16)),
        pad2(mathRound(g).toString(16)),
        pad2(mathRound(b).toString(16))
    ];

    return hex.join("");
}

// `equals`
// Can be called with any tinycolor input
tinycolor.equals = function (color1, color2) {
    if (!color1 || !color2) { return false; }
    return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
};

tinycolor.random = function() {
    return tinycolor.fromRatio({
        r: mathRandom(),
        g: mathRandom(),
        b: mathRandom()
    });
};


// Modification Functions
// ----------------------
// Thanks to less.js for some of the basics here
// <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js>

function desaturate(color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var hsl = tinycolor(color).toHsl();
    hsl.s -= amount / 100;
    hsl.s = clamp01(hsl.s);
    return tinycolor(hsl);
}

function saturate(color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var hsl = tinycolor(color).toHsl();
    hsl.s += amount / 100;
    hsl.s = clamp01(hsl.s);
    return tinycolor(hsl);
}

function greyscale(color) {
    return tinycolor(color).desaturate(100);
}

function lighten (color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var hsl = tinycolor(color).toHsl();
    hsl.l += amount / 100;
    hsl.l = clamp01(hsl.l);
    return tinycolor(hsl);
}

function brighten(color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var rgb = tinycolor(color).toRgb();
    rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100))));
    rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100))));
    rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100))));
    return tinycolor(rgb);
}

function darken (color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var hsl = tinycolor(color).toHsl();
    hsl.l -= amount / 100;
    hsl.l = clamp01(hsl.l);
    return tinycolor(hsl);
}

// Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.
// Values outside of this range will be wrapped into this range.
function spin(color, amount) {
    var hsl = tinycolor(color).toHsl();
    var hue = (hsl.h + amount) % 360;
    hsl.h = hue < 0 ? 360 + hue : hue;
    return tinycolor(hsl);
}

// Combination Functions
// ---------------------
// Thanks to jQuery xColor for some of the ideas behind these
// <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js>

function complement(color) {
    var hsl = tinycolor(color).toHsl();
    hsl.h = (hsl.h + 180) % 360;
    return tinycolor(hsl);
}

function triad(color) {
    var hsl = tinycolor(color).toHsl();
    var h = hsl.h;
    return [
        tinycolor(color),
        tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),
        tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l })
    ];
}

function tetrad(color) {
    var hsl = tinycolor(color).toHsl();
    var h = hsl.h;
    return [
        tinycolor(color),
        tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),
        tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),
        tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l })
    ];
}

function splitcomplement(color) {
    var hsl = tinycolor(color).toHsl();
    var h = hsl.h;
    return [
        tinycolor(color),
        tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}),
        tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l})
    ];
}

function analogous(color, results, slices) {
    results = results || 6;
    slices = slices || 30;

    var hsl = tinycolor(color).toHsl();
    var part = 360 / slices;
    var ret = [tinycolor(color)];

    for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) {
        hsl.h = (hsl.h + part) % 360;
        ret.push(tinycolor(hsl));
    }
    return ret;
}

function monochromatic(color, results) {
    results = results || 6;
    var hsv = tinycolor(color).toHsv();
    var h = hsv.h, s = hsv.s, v = hsv.v;
    var ret = [];
    var modification = 1 / results;

    while (results--) {
        ret.push(tinycolor({ h: h, s: s, v: v}));
        v = (v + modification) % 1;
    }

    return ret;
}

// Utility Functions
// ---------------------

tinycolor.mix = function(color1, color2, amount) {
    amount = (amount === 0) ? 0 : (amount || 50);

    var rgb1 = tinycolor(color1).toRgb();
    var rgb2 = tinycolor(color2).toRgb();

    var p = amount / 100;

    var rgba = {
        r: ((rgb2.r - rgb1.r) * p) + rgb1.r,
        g: ((rgb2.g - rgb1.g) * p) + rgb1.g,
        b: ((rgb2.b - rgb1.b) * p) + rgb1.b,
        a: ((rgb2.a - rgb1.a) * p) + rgb1.a
    };

    return tinycolor(rgba);
};


// Readability Functions
// ---------------------
// <http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef (WCAG Version 2)

// `contrast`
// Analyze the 2 colors and returns the color contrast defined by (WCAG Version 2)
tinycolor.readability = function(color1, color2) {
    var c1 = tinycolor(color1);
    var c2 = tinycolor(color2);
    return (Math.max(c1.getLuminance(),c2.getLuminance())+0.05) / (Math.min(c1.getLuminance(),c2.getLuminance())+0.05);
};

// `isReadable`
// Ensure that foreground and background color combinations meet WCAG2 guidelines.
// The third argument is an optional Object.
//      the 'level' property states 'AA' or 'AAA' - if missing or invalid, it defaults to 'AA';
//      the 'size' property states 'large' or 'small' - if missing or invalid, it defaults to 'small'.
// If the entire object is absent, isReadable defaults to {level:"AA",size:"small"}.

// *Example*
//    tinycolor.isReadable("#000", "#111") => false
//    tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false
tinycolor.isReadable = function(color1, color2, wcag2) {
    var readability = tinycolor.readability(color1, color2);
    var wcag2Parms, out;

    out = false;

    wcag2Parms = validateWCAG2Parms(wcag2);
    switch (wcag2Parms.level + wcag2Parms.size) {
        case "AAsmall":
        case "AAAlarge":
            out = readability >= 4.5;
            break;
        case "AAlarge":
            out = readability >= 3;
            break;
        case "AAAsmall":
            out = readability >= 7;
            break;
    }
    return out;

};

// `mostReadable`
// Given a base color and a list of possible foreground or background
// colors for that base, returns the most readable color.
// Optionally returns Black or White if the most readable color is unreadable.
// *Example*
//    tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255"
//    tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString();  // "#ffffff"
//    tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3"
//    tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff"
tinycolor.mostReadable = function(baseColor, colorList, args) {
    var bestColor = null;
    var bestScore = 0;
    var readability;
    var includeFallbackColors, level, size ;
    args = args || {};
    includeFallbackColors = args.includeFallbackColors ;
    level = args.level;
    size = args.size;

    for (var i= 0; i < colorList.length ; i++) {
        readability = tinycolor.readability(baseColor, colorList[i]);
        if (readability > bestScore) {
            bestScore = readability;
            bestColor = tinycolor(colorList[i]);
        }
    }

    if (tinycolor.isReadable(baseColor, bestColor, {"level":level,"size":size}) || !includeFallbackColors) {
        return bestColor;
    }
    else {
        args.includeFallbackColors=false;
        return tinycolor.mostReadable(baseColor,["#fff", "#000"],args);
    }
};


// Big List of Colors
// ------------------
// <http://www.w3.org/TR/css3-color/#svg-color>
var names = tinycolor.names = {
    aliceblue: "f0f8ff",
    antiquewhite: "faebd7",
    aqua: "0ff",
    aquamarine: "7fffd4",
    azure: "f0ffff",
    beige: "f5f5dc",
    bisque: "ffe4c4",
    black: "000",
    blanchedalmond: "ffebcd",
    blue: "00f",
    blueviolet: "8a2be2",
    brown: "a52a2a",
    burlywood: "deb887",
    burntsienna: "ea7e5d",
    cadetblue: "5f9ea0",
    chartreuse: "7fff00",
    chocolate: "d2691e",
    coral: "ff7f50",
    cornflowerblue: "6495ed",
    cornsilk: "fff8dc",
    crimson: "dc143c",
    cyan: "0ff",
    darkblue: "00008b",
    darkcyan: "008b8b",
    darkgoldenrod: "b8860b",
    darkgray: "a9a9a9",
    darkgreen: "006400",
    darkgrey: "a9a9a9",
    darkkhaki: "bdb76b",
    darkmagenta: "8b008b",
    darkolivegreen: "556b2f",
    darkorange: "ff8c00",
    darkorchid: "9932cc",
    darkred: "8b0000",
    darksalmon: "e9967a",
    darkseagreen: "8fbc8f",
    darkslateblue: "483d8b",
    darkslategray: "2f4f4f",
    darkslategrey: "2f4f4f",
    darkturquoise: "00ced1",
    darkviolet: "9400d3",
    deeppink: "ff1493",
    deepskyblue: "00bfff",
    dimgray: "696969",
    dimgrey: "696969",
    dodgerblue: "1e90ff",
    firebrick: "b22222",
    floralwhite: "fffaf0",
    forestgreen: "228b22",
    fuchsia: "f0f",
    gainsboro: "dcdcdc",
    ghostwhite: "f8f8ff",
    gold: "ffd700",
    goldenrod: "daa520",
    gray: "808080",
    green: "008000",
    greenyellow: "adff2f",
    grey: "808080",
    honeydew: "f0fff0",
    hotpink: "ff69b4",
    indianred: "cd5c5c",
    indigo: "4b0082",
    ivory: "fffff0",
    khaki: "f0e68c",
    lavender: "e6e6fa",
    lavenderblush: "fff0f5",
    lawngreen: "7cfc00",
    lemonchiffon: "fffacd",
    lightblue: "add8e6",
    lightcoral: "f08080",
    lightcyan: "e0ffff",
    lightgoldenrodyellow: "fafad2",
    lightgray: "d3d3d3",
    lightgreen: "90ee90",
    lightgrey: "d3d3d3",
    lightpink: "ffb6c1",
    lightsalmon: "ffa07a",
    lightseagreen: "20b2aa",
    lightskyblue: "87cefa",
    lightslategray: "789",
    lightslategrey: "789",
    lightsteelblue: "b0c4de",
    lightyellow: "ffffe0",
    lime: "0f0",
    limegreen: "32cd32",
    linen: "faf0e6",
    magenta: "f0f",
    maroon: "800000",
    mediumaquamarine: "66cdaa",
    mediumblue: "0000cd",
    mediumorchid: "ba55d3",
    mediumpurple: "9370db",
    mediumseagreen: "3cb371",
    mediumslateblue: "7b68ee",
    mediumspringgreen: "00fa9a",
    mediumturquoise: "48d1cc",
    mediumvioletred: "c71585",
    midnightblue: "191970",
    mintcream: "f5fffa",
    mistyrose: "ffe4e1",
    moccasin: "ffe4b5",
    navajowhite: "ffdead",
    navy: "000080",
    oldlace: "fdf5e6",
    olive: "808000",
    olivedrab: "6b8e23",
    orange: "ffa500",
    orangered: "ff4500",
    orchid: "da70d6",
    palegoldenrod: "eee8aa",
    palegreen: "98fb98",
    paleturquoise: "afeeee",
    palevioletred: "db7093",
    papayawhip: "ffefd5",
    peachpuff: "ffdab9",
    peru: "cd853f",
    pink: "ffc0cb",
    plum: "dda0dd",
    powderblue: "b0e0e6",
    purple: "800080",
    rebeccapurple: "663399",
    red: "f00",
    rosybrown: "bc8f8f",
    royalblue: "4169e1",
    saddlebrown: "8b4513",
    salmon: "fa8072",
    sandybrown: "f4a460",
    seagreen: "2e8b57",
    seashell: "fff5ee",
    sienna: "a0522d",
    silver: "c0c0c0",
    skyblue: "87ceeb",
    slateblue: "6a5acd",
    slategray: "708090",
    slategrey: "708090",
    snow: "fffafa",
    springgreen: "00ff7f",
    steelblue: "4682b4",
    tan: "d2b48c",
    teal: "008080",
    thistle: "d8bfd8",
    tomato: "ff6347",
    turquoise: "40e0d0",
    violet: "ee82ee",
    wheat: "f5deb3",
    white: "fff",
    whitesmoke: "f5f5f5",
    yellow: "ff0",
    yellowgreen: "9acd32"
};

// Make it easy to access colors via `hexNames[hex]`
var hexNames = tinycolor.hexNames = flip(names);


// Utilities
// ---------

// `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`
function flip(o) {
    var flipped = { };
    for (var i in o) {
        if (o.hasOwnProperty(i)) {
            flipped[o[i]] = i;
        }
    }
    return flipped;
}

// Return a valid alpha value [0,1] with all invalid values being set to 1
function boundAlpha(a) {
    a = parseFloat(a);

    if (isNaN(a) || a < 0 || a > 1) {
        a = 1;
    }

    return a;
}

// Take input from [0, n] and return it as [0, 1]
function bound01(n, max) {
    if (isOnePointZero(n)) { n = "100%"; }

    var processPercent = isPercentage(n);
    n = mathMin(max, mathMax(0, parseFloat(n)));

    // Automatically convert percentage into number
    if (processPercent) {
        n = parseInt(n * max, 10) / 100;
    }

    // Handle floating point rounding errors
    if ((Math.abs(n - max) < 0.000001)) {
        return 1;
    }

    // Convert into [0, 1] range if it isn't already
    return (n % max) / parseFloat(max);
}

// Force a number between 0 and 1
function clamp01(val) {
    return mathMin(1, mathMax(0, val));
}

// Parse a base-16 hex value into a base-10 integer
function parseIntFromHex(val) {
    return parseInt(val, 16);
}

// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
// <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
function isOnePointZero(n) {
    return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1;
}

// Check to see if string passed in is a percentage
function isPercentage(n) {
    return typeof n === "string" && n.indexOf('%') != -1;
}

// Force a hex value to have 2 characters
function pad2(c) {
    return c.length == 1 ? '0' + c : '' + c;
}

// Replace a decimal with it's percentage value
function convertToPercentage(n) {
    if (n <= 1) {
        n = (n * 100) + "%";
    }

    return n;
}

// Converts a decimal to a hex value
function convertDecimalToHex(d) {
    return Math.round(parseFloat(d) * 255).toString(16);
}
// Converts a hex value to a decimal
function convertHexToDecimal(h) {
    return (parseIntFromHex(h) / 255);
}

var matchers = (function() {

    // <http://www.w3.org/TR/css3-values/#integers>
    var CSS_INTEGER = "[-\\+]?\\d+%?";

    // <http://www.w3.org/TR/css3-values/#number-value>
    var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";

    // Allow positive/negative integer/number.  Don't capture the either/or, just the entire outcome.
    var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";

    // Actual matching.
    // Parentheses and commas are optional, but not required.
    // Whitespace can take the place of commas or opening paren
    var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
    var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";

    return {
        CSS_UNIT: new RegExp(CSS_UNIT),
        rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
        rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
        hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
        hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
        hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
        hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
        hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
        hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
        hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
        hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
    };
})();

// `isValidCSSUnit`
// Take in a single string / number and check to see if it looks like a CSS unit
// (see `matchers` above for definition).
function isValidCSSUnit(color) {
    return !!matchers.CSS_UNIT.exec(color);
}

// `stringInputToObject`
// Permissive string parsing.  Take in a number of formats, and output an object
// based on detected format.  Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`
function stringInputToObject(color) {

    color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase();
    var named = false;
    if (names[color]) {
        color = names[color];
        named = true;
    }
    else if (color == 'transparent') {
        return { r: 0, g: 0, b: 0, a: 0, format: "name" };
    }

    // Try to match string input using regular expressions.
    // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]
    // Just return an object and let the conversion functions handle that.
    // This way the result will be the same whether the tinycolor is initialized with string or object.
    var match;
    if ((match = matchers.rgb.exec(color))) {
        return { r: match[1], g: match[2], b: match[3] };
    }
    if ((match = matchers.rgba.exec(color))) {
        return { r: match[1], g: match[2], b: match[3], a: match[4] };
    }
    if ((match = matchers.hsl.exec(color))) {
        return { h: match[1], s: match[2], l: match[3] };
    }
    if ((match = matchers.hsla.exec(color))) {
        return { h: match[1], s: match[2], l: match[3], a: match[4] };
    }
    if ((match = matchers.hsv.exec(color))) {
        return { h: match[1], s: match[2], v: match[3] };
    }
    if ((match = matchers.hsva.exec(color))) {
        return { h: match[1], s: match[2], v: match[3], a: match[4] };
    }
    if ((match = matchers.hex8.exec(color))) {
        return {
            r: parseIntFromHex(match[1]),
            g: parseIntFromHex(match[2]),
            b: parseIntFromHex(match[3]),
            a: convertHexToDecimal(match[4]),
            format: named ? "name" : "hex8"
        };
    }
    if ((match = matchers.hex6.exec(color))) {
        return {
            r: parseIntFromHex(match[1]),
            g: parseIntFromHex(match[2]),
            b: parseIntFromHex(match[3]),
            format: named ? "name" : "hex"
        };
    }
    if ((match = matchers.hex4.exec(color))) {
        return {
            r: parseIntFromHex(match[1] + '' + match[1]),
            g: parseIntFromHex(match[2] + '' + match[2]),
            b: parseIntFromHex(match[3] + '' + match[3]),
            a: convertHexToDecimal(match[4] + '' + match[4]),
            format: named ? "name" : "hex8"
        };
    }
    if ((match = matchers.hex3.exec(color))) {
        return {
            r: parseIntFromHex(match[1] + '' + match[1]),
            g: parseIntFromHex(match[2] + '' + match[2]),
            b: parseIntFromHex(match[3] + '' + match[3]),
            format: named ? "name" : "hex"
        };
    }

    return false;
}

function validateWCAG2Parms(parms) {
    // return valid WCAG2 parms for isReadable.
    // If input parms are invalid, return {"level":"AA", "size":"small"}
    var level, size;
    parms = parms || {"level":"AA", "size":"small"};
    level = (parms.level || "AA").toUpperCase();
    size = (parms.size || "small").toLowerCase();
    if (level !== "AA" && level !== "AAA") {
        level = "AA";
    }
    if (size !== "small" && size !== "large") {
        size = "small";
    }
    return {"level":level, "size":size};
}

// Node: Export function
if (typeof module !== "undefined" && module.exports) {
    module.exports = tinycolor;
}
// AMD/requirejs: Define the module
else if (typeof define === 'function' && define.amd) {
    define(function () {return tinycolor;});
}
// Browser: Expose to window
else {
    window.tinycolor = tinycolor;
}

})(Math);

},{}],516:[function(_dereq_,module,exports){
/* @module to-float32 */

'use strict'

module.exports = float32
module.exports.float32 =
module.exports.float = float32
module.exports.fract32 =
module.exports.fract = fract32

var narr = new Float32Array(1)

// return fractional part of float32 array
function fract32 (arr) {
	if (arr.length) {
		var fract = float32(arr)
		for (var i = 0, l = fract.length; i < l; i++) {
			fract[i] = arr[i] - fract[i]
		}
		return fract
	}

	// number
	return float32(arr - float32(arr))
}

// make sure data is float32 array
function float32 (arr) {
	if (arr.length) {
		if (arr instanceof Float32Array) return arr
		var float = new Float32Array(arr)
		float.set(arr)
		return float
	}

	// number
	narr[0] = arr
	return narr[0]
}

},{}],517:[function(_dereq_,module,exports){
'use strict'

var parseUnit = _dereq_('parse-unit')

module.exports = toPX

var PIXELS_PER_INCH = 96

function getPropertyInPX(element, prop) {
  var parts = parseUnit(getComputedStyle(element).getPropertyValue(prop))
  return parts[0] * toPX(parts[1], element)
}

//This brutal hack is needed
function getSizeBrutal(unit, element) {
  var testDIV = document.createElement('div')
  testDIV.style['font-size'] = '128' + unit
  element.appendChild(testDIV)
  var size = getPropertyInPX(testDIV, 'font-size') / 128
  element.removeChild(testDIV)
  return size
}

function toPX(str, element) {
  element = element || document.body
  str = (str || 'px').trim().toLowerCase()
  if(element === window || element === document) {
    element = document.body 
  }
  switch(str) {
    case '%':  //Ambiguous, not sure if we should use width or height
      return element.clientHeight / 100.0
    case 'ch':
    case 'ex':
      return getSizeBrutal(str, element)
    case 'em':
      return getPropertyInPX(element, 'font-size')
    case 'rem':
      return getPropertyInPX(document.body, 'font-size')
    case 'vw':
      return window.innerWidth/100
    case 'vh':
      return window.innerHeight/100
    case 'vmin':
      return Math.min(window.innerWidth, window.innerHeight) / 100
    case 'vmax':
      return Math.max(window.innerWidth, window.innerHeight) / 100
    case 'in':
      return PIXELS_PER_INCH
    case 'cm':
      return PIXELS_PER_INCH / 2.54
    case 'mm':
      return PIXELS_PER_INCH / 25.4
    case 'pt':
      return PIXELS_PER_INCH / 72
    case 'pc':
      return PIXELS_PER_INCH / 6
  }
  return 1
}
},{"parse-unit":447}],518:[function(_dereq_,module,exports){
// https://github.com/topojson/topojson-client Version 2.1.0. Copyright 2016 Mike Bostock.
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
  (factory((global.topojson = global.topojson || {})));
}(this, (function (exports) { 'use strict';

var identity = function(x) {
  return x;
};

var transform = function(topology) {
  if ((transform = topology.transform) == null) return identity;
  var transform,
      x0,
      y0,
      kx = transform.scale[0],
      ky = transform.scale[1],
      dx = transform.translate[0],
      dy = transform.translate[1];
  return function(point, i) {
    if (!i) x0 = y0 = 0;
    point[0] = (x0 += point[0]) * kx + dx;
    point[1] = (y0 += point[1]) * ky + dy;
    return point;
  };
};

var bbox = function(topology) {
  var bbox = topology.bbox;

  function bboxPoint(p0) {
    p1[0] = p0[0], p1[1] = p0[1], t(p1);
    if (p1[0] < x0) x0 = p1[0];
    if (p1[0] > x1) x1 = p1[0];
    if (p1[1] < y0) y0 = p1[1];
    if (p1[1] > y1) y1 = p1[1];
  }

  function bboxGeometry(o) {
    switch (o.type) {
      case "GeometryCollection": o.geometries.forEach(bboxGeometry); break;
      case "Point": bboxPoint(o.coordinates); break;
      case "MultiPoint": o.coordinates.forEach(bboxPoint); break;
    }
  }

  if (!bbox) {
    var t = transform(topology), p0, p1 = new Array(2), name,
        x0 = Infinity, y0 = x0, x1 = -x0, y1 = -x0;

    topology.arcs.forEach(function(arc) {
      var i = -1, n = arc.length;
      while (++i < n) {
        p0 = arc[i], p1[0] = p0[0], p1[1] = p0[1], t(p1, i);
        if (p1[0] < x0) x0 = p1[0];
        if (p1[0] > x1) x1 = p1[0];
        if (p1[1] < y0) y0 = p1[1];
        if (p1[1] > y1) y1 = p1[1];
      }
    });

    for (name in topology.objects) {
      bboxGeometry(topology.objects[name]);
    }

    bbox = topology.bbox = [x0, y0, x1, y1];
  }

  return bbox;
};

var reverse = function(array, n) {
  var t, j = array.length, i = j - n;
  while (i < --j) t = array[i], array[i++] = array[j], array[j] = t;
};

var feature = function(topology, o) {
  return o.type === "GeometryCollection"
      ? {type: "FeatureCollection", features: o.geometries.map(function(o) { return feature$1(topology, o); })}
      : feature$1(topology, o);
};

function feature$1(topology, o) {
  var id = o.id,
      bbox = o.bbox,
      properties = o.properties == null ? {} : o.properties,
      geometry = object(topology, o);
  return id == null && bbox == null ? {type: "Feature", properties: properties, geometry: geometry}
      : bbox == null ? {type: "Feature", id: id, properties: properties, geometry: geometry}
      : {type: "Feature", id: id, bbox: bbox, properties: properties, geometry: geometry};
}

function object(topology, o) {
  var transformPoint = transform(topology),
      arcs = topology.arcs;

  function arc(i, points) {
    if (points.length) points.pop();
    for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length; k < n; ++k) {
      points.push(transformPoint(a[k].slice(), k));
    }
    if (i < 0) reverse(points, n);
  }

  function point(p) {
    return transformPoint(p.slice());
  }

  function line(arcs) {
    var points = [];
    for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points);
    if (points.length < 2) points.push(points[0].slice());
    return points;
  }

  function ring(arcs) {
    var points = line(arcs);
    while (points.length < 4) points.push(points[0].slice());
    return points;
  }

  function polygon(arcs) {
    return arcs.map(ring);
  }

  function geometry(o) {
    var type = o.type, coordinates;
    switch (type) {
      case "GeometryCollection": return {type: type, geometries: o.geometries.map(geometry)};
      case "Point": coordinates = point(o.coordinates); break;
      case "MultiPoint": coordinates = o.coordinates.map(point); break;
      case "LineString": coordinates = line(o.arcs); break;
      case "MultiLineString": coordinates = o.arcs.map(line); break;
      case "Polygon": coordinates = polygon(o.arcs); break;
      case "MultiPolygon": coordinates = o.arcs.map(polygon); break;
      default: return null;
    }
    return {type: type, coordinates: coordinates};
  }

  return geometry(o);
}

var stitch = function(topology, arcs) {
  var stitchedArcs = {},
      fragmentByStart = {},
      fragmentByEnd = {},
      fragments = [],
      emptyIndex = -1;

  // Stitch empty arcs first, since they may be subsumed by other arcs.
  arcs.forEach(function(i, j) {
    var arc = topology.arcs[i < 0 ? ~i : i], t;
    if (arc.length < 3 && !arc[1][0] && !arc[1][1]) {
      t = arcs[++emptyIndex], arcs[emptyIndex] = i, arcs[j] = t;
    }
  });

  arcs.forEach(function(i) {
    var e = ends(i),
        start = e[0],
        end = e[1],
        f, g;

    if (f = fragmentByEnd[start]) {
      delete fragmentByEnd[f.end];
      f.push(i);
      f.end = end;
      if (g = fragmentByStart[end]) {
        delete fragmentByStart[g.start];
        var fg = g === f ? f : f.concat(g);
        fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg;
      } else {
        fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
      }
    } else if (f = fragmentByStart[end]) {
      delete fragmentByStart[f.start];
      f.unshift(i);
      f.start = start;
      if (g = fragmentByEnd[start]) {
        delete fragmentByEnd[g.end];
        var gf = g === f ? f : g.concat(f);
        fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf;
      } else {
        fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
      }
    } else {
      f = [i];
      fragmentByStart[f.start = start] = fragmentByEnd[f.end = end] = f;
    }
  });

  function ends(i) {
    var arc = topology.arcs[i < 0 ? ~i : i], p0 = arc[0], p1;
    if (topology.transform) p1 = [0, 0], arc.forEach(function(dp) { p1[0] += dp[0], p1[1] += dp[1]; });
    else p1 = arc[arc.length - 1];
    return i < 0 ? [p1, p0] : [p0, p1];
  }

  function flush(fragmentByEnd, fragmentByStart) {
    for (var k in fragmentByEnd) {
      var f = fragmentByEnd[k];
      delete fragmentByStart[f.start];
      delete f.start;
      delete f.end;
      f.forEach(function(i) { stitchedArcs[i < 0 ? ~i : i] = 1; });
      fragments.push(f);
    }
  }

  flush(fragmentByEnd, fragmentByStart);
  flush(fragmentByStart, fragmentByEnd);
  arcs.forEach(function(i) { if (!stitchedArcs[i < 0 ? ~i : i]) fragments.push([i]); });

  return fragments;
};

var mesh = function(topology) {
  return object(topology, meshArcs.apply(this, arguments));
};

function meshArcs(topology, object$$1, filter) {
  var arcs, i, n;
  if (arguments.length > 1) arcs = extractArcs(topology, object$$1, filter);
  else for (i = 0, arcs = new Array(n = topology.arcs.length); i < n; ++i) arcs[i] = i;
  return {type: "MultiLineString", arcs: stitch(topology, arcs)};
}

function extractArcs(topology, object$$1, filter) {
  var arcs = [],
      geomsByArc = [],
      geom;

  function extract0(i) {
    var j = i < 0 ? ~i : i;
    (geomsByArc[j] || (geomsByArc[j] = [])).push({i: i, g: geom});
  }

  function extract1(arcs) {
    arcs.forEach(extract0);
  }

  function extract2(arcs) {
    arcs.forEach(extract1);
  }

  function extract3(arcs) {
    arcs.forEach(extract2);
  }

  function geometry(o) {
    switch (geom = o, o.type) {
      case "GeometryCollection": o.geometries.forEach(geometry); break;
      case "LineString": extract1(o.arcs); break;
      case "MultiLineString": case "Polygon": extract2(o.arcs); break;
      case "MultiPolygon": extract3(o.arcs); break;
    }
  }

  geometry(object$$1);

  geomsByArc.forEach(filter == null
      ? function(geoms) { arcs.push(geoms[0].i); }
      : function(geoms) { if (filter(geoms[0].g, geoms[geoms.length - 1].g)) arcs.push(geoms[0].i); });

  return arcs;
}

function planarRingArea(ring) {
  var i = -1, n = ring.length, a, b = ring[n - 1], area = 0;
  while (++i < n) a = b, b = ring[i], area += a[0] * b[1] - a[1] * b[0];
  return Math.abs(area); // Note: doubled area!
}

var merge = function(topology) {
  return object(topology, mergeArcs.apply(this, arguments));
};

function mergeArcs(topology, objects) {
  var polygonsByArc = {},
      polygons = [],
      groups = [];

  objects.forEach(geometry);

  function geometry(o) {
    switch (o.type) {
      case "GeometryCollection": o.geometries.forEach(geometry); break;
      case "Polygon": extract(o.arcs); break;
      case "MultiPolygon": o.arcs.forEach(extract); break;
    }
  }

  function extract(polygon) {
    polygon.forEach(function(ring) {
      ring.forEach(function(arc) {
        (polygonsByArc[arc = arc < 0 ? ~arc : arc] || (polygonsByArc[arc] = [])).push(polygon);
      });
    });
    polygons.push(polygon);
  }

  function area(ring) {
    return planarRingArea(object(topology, {type: "Polygon", arcs: [ring]}).coordinates[0]);
  }

  polygons.forEach(function(polygon) {
    if (!polygon._) {
      var group = [],
          neighbors = [polygon];
      polygon._ = 1;
      groups.push(group);
      while (polygon = neighbors.pop()) {
        group.push(polygon);
        polygon.forEach(function(ring) {
          ring.forEach(function(arc) {
            polygonsByArc[arc < 0 ? ~arc : arc].forEach(function(polygon) {
              if (!polygon._) {
                polygon._ = 1;
                neighbors.push(polygon);
              }
            });
          });
        });
      }
    }
  });

  polygons.forEach(function(polygon) {
    delete polygon._;
  });

  return {
    type: "MultiPolygon",
    arcs: groups.map(function(polygons) {
      var arcs = [], n;

      // Extract the exterior (unique) arcs.
      polygons.forEach(function(polygon) {
        polygon.forEach(function(ring) {
          ring.forEach(function(arc) {
            if (polygonsByArc[arc < 0 ? ~arc : arc].length < 2) {
              arcs.push(arc);
            }
          });
        });
      });

      // Stitch the arcs into one or more rings.
      arcs = stitch(topology, arcs);

      // If more than one ring is returned,
      // at most one of these rings can be the exterior;
      // choose the one with the greatest absolute area.
      if ((n = arcs.length) > 1) {
        for (var i = 1, k = area(arcs[0]), ki, t; i < n; ++i) {
          if ((ki = area(arcs[i])) > k) {
            t = arcs[0], arcs[0] = arcs[i], arcs[i] = t, k = ki;
          }
        }
      }

      return arcs;
    })
  };
}

var bisect = function(a, x) {
  var lo = 0, hi = a.length;
  while (lo < hi) {
    var mid = lo + hi >>> 1;
    if (a[mid] < x) lo = mid + 1;
    else hi = mid;
  }
  return lo;
};

var neighbors = function(objects) {
  var indexesByArc = {}, // arc index -> array of object indexes
      neighbors = objects.map(function() { return []; });

  function line(arcs, i) {
    arcs.forEach(function(a) {
      if (a < 0) a = ~a;
      var o = indexesByArc[a];
      if (o) o.push(i);
      else indexesByArc[a] = [i];
    });
  }

  function polygon(arcs, i) {
    arcs.forEach(function(arc) { line(arc, i); });
  }

  function geometry(o, i) {
    if (o.type === "GeometryCollection") o.geometries.forEach(function(o) { geometry(o, i); });
    else if (o.type in geometryType) geometryType[o.type](o.arcs, i);
  }

  var geometryType = {
    LineString: line,
    MultiLineString: polygon,
    Polygon: polygon,
    MultiPolygon: function(arcs, i) { arcs.forEach(function(arc) { polygon(arc, i); }); }
  };

  objects.forEach(geometry);

  for (var i in indexesByArc) {
    for (var indexes = indexesByArc[i], m = indexes.length, j = 0; j < m; ++j) {
      for (var k = j + 1; k < m; ++k) {
        var ij = indexes[j], ik = indexes[k], n;
        if ((n = neighbors[ij])[i = bisect(n, ik)] !== ik) n.splice(i, 0, ik);
        if ((n = neighbors[ik])[i = bisect(n, ij)] !== ij) n.splice(i, 0, ij);
      }
    }
  }

  return neighbors;
};

var quantize = function(topology, n) {
  if (!((n = Math.floor(n)) >= 2)) throw new Error("n must be ≥2");
  if (topology.transform) throw new Error("already quantized");
  var bb = bbox(topology), name,
      dx = bb[0], kx = (bb[2] - dx) / (n - 1) || 1,
      dy = bb[1], ky = (bb[3] - dy) / (n - 1) || 1;

  function quantizePoint(p) {
    p[0] = Math.round((p[0] - dx) / kx);
    p[1] = Math.round((p[1] - dy) / ky);
  }

  function quantizeGeometry(o) {
    switch (o.type) {
      case "GeometryCollection": o.geometries.forEach(quantizeGeometry); break;
      case "Point": quantizePoint(o.coordinates); break;
      case "MultiPoint": o.coordinates.forEach(quantizePoint); break;
    }
  }

  topology.arcs.forEach(function(arc) {
    var i = 1,
        j = 1,
        n = arc.length,
        pi = arc[0],
        x0 = pi[0] = Math.round((pi[0] - dx) / kx),
        y0 = pi[1] = Math.round((pi[1] - dy) / ky),
        pj,
        x1,
        y1;

    for (; i < n; ++i) {
      pi = arc[i];
      x1 = Math.round((pi[0] - dx) / kx);
      y1 = Math.round((pi[1] - dy) / ky);
      if (x1 !== x0 || y1 !== y0) {
        pj = arc[j++];
        pj[0] = x1 - x0, x0 = x1;
        pj[1] = y1 - y0, y0 = y1;
      }
    }

    if (j < 2) {
      pj = arc[j++];
      pj[0] = 0;
      pj[1] = 0;
    }

    arc.length = j;
  });

  for (name in topology.objects) {
    quantizeGeometry(topology.objects[name]);
  }

  topology.transform = {
    scale: [kx, ky],
    translate: [dx, dy]
  };

  return topology;
};

var untransform = function(topology) {
  if ((transform = topology.transform) == null) return identity;
  var transform,
      x0,
      y0,
      kx = transform.scale[0],
      ky = transform.scale[1],
      dx = transform.translate[0],
      dy = transform.translate[1];
  return function(point, i) {
    if (!i) x0 = y0 = 0;
    var x1 = Math.round((point[0] - dx) / kx),
        y1 = Math.round((point[1] - dy) / ky);
    point[0] = x1 - x0, x0 = x1;
    point[1] = y1 - y0, y0 = y1;
    return point;
  };
};

exports.bbox = bbox;
exports.feature = feature;
exports.mesh = mesh;
exports.meshArcs = meshArcs;
exports.merge = merge;
exports.mergeArcs = mergeArcs;
exports.neighbors = neighbors;
exports.quantize = quantize;
exports.transform = transform;
exports.untransform = untransform;

Object.defineProperty(exports, '__esModule', { value: true });

})));

},{}],519:[function(_dereq_,module,exports){
"use strict"

module.exports = triangulateCube

var perm = _dereq_("permutation-rank")
var sgn = _dereq_("permutation-parity")
var gamma = _dereq_("gamma")

function triangulateCube(dimension) {
  if(dimension < 0) {
    return [ ]
  }
  if(dimension === 0) {
    return [ [0] ]
  }
  var dfactorial = Math.round(gamma(dimension+1))|0
  var result = []
  for(var i=0; i<dfactorial; ++i) {
    var p = perm.unrank(dimension, i)
    var cell = [ 0 ]
    var v = 0
    for(var j=0; j<p.length; ++j) {
      v += (1<<p[j])
      cell.push(v)
    }
    if(sgn(p) < 1) {
      cell[0] = v
      cell[dimension] = 0
    }
    result.push(cell)
  }
  return result
}
},{"gamma":221,"permutation-parity":449,"permutation-rank":450}],520:[function(_dereq_,module,exports){
'use strict'

module.exports = createTurntableController

var filterVector = _dereq_('filtered-vector')
var invert44     = _dereq_('gl-mat4/invert')
var rotateM      = _dereq_('gl-mat4/rotate')
var cross        = _dereq_('gl-vec3/cross')
var normalize3   = _dereq_('gl-vec3/normalize')
var dot3         = _dereq_('gl-vec3/dot')

function len3(x, y, z) {
  return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2))
}

function clamp1(x) {
  return Math.min(1.0, Math.max(-1.0, x))
}

function findOrthoPair(v) {
  var vx = Math.abs(v[0])
  var vy = Math.abs(v[1])
  var vz = Math.abs(v[2])

  var u = [0,0,0]
  if(vx > Math.max(vy, vz)) {
    u[2] = 1
  } else if(vy > Math.max(vx, vz)) {
    u[0] = 1
  } else {
    u[1] = 1
  }

  var vv = 0
  var uv = 0
  for(var i=0; i<3; ++i ) {
    vv += v[i] * v[i]
    uv += u[i] * v[i]
  }
  for(var i=0; i<3; ++i) {
    u[i] -= (uv / vv) *  v[i]
  }
  normalize3(u, u)
  return u
}

function TurntableController(zoomMin, zoomMax, center, up, right, radius, theta, phi) {
  this.center = filterVector(center)
  this.up     = filterVector(up)
  this.right  = filterVector(right)
  this.radius = filterVector([radius])
  this.angle  = filterVector([theta, phi])
  this.angle.bounds = [[-Infinity,-Math.PI/2], [Infinity,Math.PI/2]]
  this.setDistanceLimits(zoomMin, zoomMax)

  this.computedCenter = this.center.curve(0)
  this.computedUp     = this.up.curve(0)
  this.computedRight  = this.right.curve(0)
  this.computedRadius = this.radius.curve(0)
  this.computedAngle  = this.angle.curve(0)
  this.computedToward = [0,0,0]
  this.computedEye    = [0,0,0]
  this.computedMatrix = new Array(16)
  for(var i=0; i<16; ++i) {
    this.computedMatrix[i] = 0.5
  }

  this.recalcMatrix(0)
}

var proto = TurntableController.prototype

proto.setDistanceLimits = function(minDist, maxDist) {
  if(minDist > 0) {
    minDist = Math.log(minDist)
  } else {
    minDist = -Infinity
  }
  if(maxDist > 0) {
    maxDist = Math.log(maxDist)
  } else {
    maxDist = Infinity
  }
  maxDist = Math.max(maxDist, minDist)
  this.radius.bounds[0][0] = minDist
  this.radius.bounds[1][0] = maxDist
}

proto.getDistanceLimits = function(out) {
  var bounds = this.radius.bounds[0]
  if(out) {
    out[0] = Math.exp(bounds[0][0])
    out[1] = Math.exp(bounds[1][0])
    return out
  }
  return [ Math.exp(bounds[0][0]), Math.exp(bounds[1][0]) ]
}

proto.recalcMatrix = function(t) {
  //Recompute curves
  this.center.curve(t)
  this.up.curve(t)
  this.right.curve(t)
  this.radius.curve(t)
  this.angle.curve(t)

  //Compute frame for camera matrix
  var up     = this.computedUp
  var right  = this.computedRight
  var uu = 0.0
  var ur = 0.0
  for(var i=0; i<3; ++i) {
    ur += up[i] * right[i]
    uu += up[i] * up[i]
  }
  var ul = Math.sqrt(uu)
  var rr = 0.0
  for(var i=0; i<3; ++i) {
    right[i] -= up[i] * ur / uu
    rr       += right[i] * right[i]
    up[i]    /= ul
  }
  var rl = Math.sqrt(rr)
  for(var i=0; i<3; ++i) {
    right[i] /= rl
  }

  //Compute toward vector
  var toward = this.computedToward
  cross(toward, up, right)
  normalize3(toward, toward)

  //Compute angular parameters
  var radius = Math.exp(this.computedRadius[0])
  var theta  = this.computedAngle[0]
  var phi    = this.computedAngle[1]

  var ctheta = Math.cos(theta)
  var stheta = Math.sin(theta)
  var cphi   = Math.cos(phi)
  var sphi   = Math.sin(phi)

  var center = this.computedCenter

  var wx = ctheta * cphi 
  var wy = stheta * cphi
  var wz = sphi

  var sx = -ctheta * sphi
  var sy = -stheta * sphi
  var sz = cphi

  var eye = this.computedEye
  var mat = this.computedMatrix
  for(var i=0; i<3; ++i) {
    var x      = wx * right[i] + wy * toward[i] + wz * up[i]
    mat[4*i+1] = sx * right[i] + sy * toward[i] + sz * up[i]
    mat[4*i+2] = x
    mat[4*i+3] = 0.0
  }

  var ax = mat[1]
  var ay = mat[5]
  var az = mat[9]
  var bx = mat[2]
  var by = mat[6]
  var bz = mat[10]
  var cx = ay * bz - az * by
  var cy = az * bx - ax * bz
  var cz = ax * by - ay * bx
  var cl = len3(cx, cy, cz)
  cx /= cl
  cy /= cl
  cz /= cl
  mat[0] = cx
  mat[4] = cy
  mat[8] = cz

  for(var i=0; i<3; ++i) {
    eye[i] = center[i] + mat[2+4*i]*radius
  }

  for(var i=0; i<3; ++i) {
    var rr = 0.0
    for(var j=0; j<3; ++j) {
      rr += mat[i+4*j] * eye[j]
    }
    mat[12+i] = -rr
  }
  mat[15] = 1.0
}

proto.getMatrix = function(t, result) {
  this.recalcMatrix(t)
  var mat = this.computedMatrix
  if(result) {
    for(var i=0; i<16; ++i) {
      result[i] = mat[i]
    }
    return result
  }
  return mat
}

var zAxis = [0,0,0]
proto.rotate = function(t, dtheta, dphi, droll) {
  this.angle.move(t, dtheta, dphi)
  if(droll) {
    this.recalcMatrix(t)

    var mat = this.computedMatrix
    zAxis[0] = mat[2]
    zAxis[1] = mat[6]
    zAxis[2] = mat[10]

    var up     = this.computedUp
    var right  = this.computedRight
    var toward = this.computedToward

    for(var i=0; i<3; ++i) {
      mat[4*i]   = up[i]
      mat[4*i+1] = right[i]
      mat[4*i+2] = toward[i]
    }
    rotateM(mat, mat, droll, zAxis)
    for(var i=0; i<3; ++i) {
      up[i] =    mat[4*i]
      right[i] = mat[4*i+1]
    }

    this.up.set(t, up[0], up[1], up[2])
    this.right.set(t, right[0], right[1], right[2])
  }
}

proto.pan = function(t, dx, dy, dz) {
  dx = dx || 0.0
  dy = dy || 0.0
  dz = dz || 0.0

  this.recalcMatrix(t)
  var mat = this.computedMatrix

  var dist = Math.exp(this.computedRadius[0])

  var ux = mat[1]
  var uy = mat[5]
  var uz = mat[9]
  var ul = len3(ux, uy, uz)
  ux /= ul
  uy /= ul
  uz /= ul

  var rx = mat[0]
  var ry = mat[4]
  var rz = mat[8]
  var ru = rx * ux + ry * uy + rz * uz
  rx -= ux * ru
  ry -= uy * ru
  rz -= uz * ru
  var rl = len3(rx, ry, rz)
  rx /= rl
  ry /= rl
  rz /= rl

  var vx = rx * dx + ux * dy
  var vy = ry * dx + uy * dy
  var vz = rz * dx + uz * dy
  this.center.move(t, vx, vy, vz)

  //Update z-component of radius
  var radius = Math.exp(this.computedRadius[0])
  radius = Math.max(1e-4, radius + dz)
  this.radius.set(t, Math.log(radius))
}

proto.translate = function(t, dx, dy, dz) {
  this.center.move(t,
    dx||0.0,
    dy||0.0,
    dz||0.0)
}

//Recenters the coordinate axes
proto.setMatrix = function(t, mat, axes, noSnap) {
  
  //Get the axes for tare
  var ushift = 1
  if(typeof axes === 'number') {
    ushift = (axes)|0
  } 
  if(ushift < 0 || ushift > 3) {
    ushift = 1
  }
  var vshift = (ushift + 2) % 3
  var fshift = (ushift + 1) % 3

  //Recompute state for new t value
  if(!mat) { 
    this.recalcMatrix(t)
    mat = this.computedMatrix
  }

  //Get right and up vectors
  var ux = mat[ushift]
  var uy = mat[ushift+4]
  var uz = mat[ushift+8]
  if(!noSnap) {
    var ul = len3(ux, uy, uz)
    ux /= ul
    uy /= ul
    uz /= ul
  } else {
    var ax = Math.abs(ux)
    var ay = Math.abs(uy)
    var az = Math.abs(uz)
    var am = Math.max(ax,ay,az)
    if(ax === am) {
      ux = (ux < 0) ? -1 : 1
      uy = uz = 0
    } else if(az === am) {
      uz = (uz < 0) ? -1 : 1
      ux = uy = 0
    } else {
      uy = (uy < 0) ? -1 : 1
      ux = uz = 0
    }
  }

  var rx = mat[vshift]
  var ry = mat[vshift+4]
  var rz = mat[vshift+8]
  var ru = rx * ux + ry * uy + rz * uz
  rx -= ux * ru
  ry -= uy * ru
  rz -= uz * ru
  var rl = len3(rx, ry, rz)
  rx /= rl
  ry /= rl
  rz /= rl
  
  var fx = uy * rz - uz * ry
  var fy = uz * rx - ux * rz
  var fz = ux * ry - uy * rx
  var fl = len3(fx, fy, fz)
  fx /= fl
  fy /= fl
  fz /= fl

  this.center.jump(t, ex, ey, ez)
  this.radius.idle(t)
  this.up.jump(t, ux, uy, uz)
  this.right.jump(t, rx, ry, rz)

  var phi, theta
  if(ushift === 2) {
    var cx = mat[1]
    var cy = mat[5]
    var cz = mat[9]
    var cr = cx * rx + cy * ry + cz * rz
    var cf = cx * fx + cy * fy + cz * fz
    if(tu < 0) {
      phi = -Math.PI/2
    } else {
      phi = Math.PI/2
    }
    theta = Math.atan2(cf, cr)
  } else {
    var tx = mat[2]
    var ty = mat[6]
    var tz = mat[10]
    var tu = tx * ux + ty * uy + tz * uz
    var tr = tx * rx + ty * ry + tz * rz
    var tf = tx * fx + ty * fy + tz * fz

    phi = Math.asin(clamp1(tu))
    theta = Math.atan2(tf, tr)
  }

  this.angle.jump(t, theta, phi)

  this.recalcMatrix(t)
  var dx = mat[2]
  var dy = mat[6]
  var dz = mat[10]

  var imat = this.computedMatrix
  invert44(imat, mat)
  var w  = imat[15]
  var ex = imat[12] / w
  var ey = imat[13] / w
  var ez = imat[14] / w

  var gs = Math.exp(this.computedRadius[0])
  this.center.jump(t, ex-dx*gs, ey-dy*gs, ez-dz*gs)
}

proto.lastT = function() {
  return Math.max(
    this.center.lastT(),
    this.up.lastT(),
    this.right.lastT(),
    this.radius.lastT(),
    this.angle.lastT())
}

proto.idle = function(t) {
  this.center.idle(t)
  this.up.idle(t)
  this.right.idle(t)
  this.radius.idle(t)
  this.angle.idle(t)
}

proto.flush = function(t) {
  this.center.flush(t)
  this.up.flush(t)
  this.right.flush(t)
  this.radius.flush(t)
  this.angle.flush(t)
}

proto.setDistance = function(t, d) {
  if(d > 0) {
    this.radius.set(t, Math.log(d))
  }
}

proto.lookAt = function(t, eye, center, up) {
  this.recalcMatrix(t)

  eye    = eye    || this.computedEye
  center = center || this.computedCenter
  up     = up     || this.computedUp

  var ux = up[0]
  var uy = up[1]
  var uz = up[2]
  var ul = len3(ux, uy, uz)
  if(ul < 1e-6) {
    return
  }
  ux /= ul
  uy /= ul
  uz /= ul

  var tx = eye[0] - center[0]
  var ty = eye[1] - center[1]
  var tz = eye[2] - center[2]
  var tl = len3(tx, ty, tz)
  if(tl < 1e-6) {
    return
  }
  tx /= tl
  ty /= tl
  tz /= tl

  var right = this.computedRight
  var rx = right[0]
  var ry = right[1]
  var rz = right[2]
  var ru = ux*rx + uy*ry + uz*rz
  rx -= ru * ux
  ry -= ru * uy
  rz -= ru * uz
  var rl = len3(rx, ry, rz)

  if(rl < 0.01) {
    rx = uy * tz - uz * ty
    ry = uz * tx - ux * tz
    rz = ux * ty - uy * tx
    rl = len3(rx, ry, rz)
    if(rl < 1e-6) {
      return
    }
  }
  rx /= rl
  ry /= rl
  rz /= rl

  this.up.set(t, ux, uy, uz)
  this.right.set(t, rx, ry, rz)
  this.center.set(t, center[0], center[1], center[2])
  this.radius.set(t, Math.log(tl))

  var fx = uy * rz - uz * ry
  var fy = uz * rx - ux * rz
  var fz = ux * ry - uy * rx
  var fl = len3(fx, fy, fz)
  fx /= fl
  fy /= fl
  fz /= fl

  var tu = ux*tx + uy*ty + uz*tz
  var tr = rx*tx + ry*ty + rz*tz
  var tf = fx*tx + fy*ty + fz*tz

  var phi   = Math.asin(clamp1(tu))
  var theta = Math.atan2(tf, tr)

  var angleState = this.angle._state
  var lastTheta  = angleState[angleState.length-1]
  var lastPhi    = angleState[angleState.length-2]
  lastTheta      = lastTheta % (2.0 * Math.PI)
  var dp = Math.abs(lastTheta + 2.0 * Math.PI - theta)
  var d0 = Math.abs(lastTheta - theta)
  var dn = Math.abs(lastTheta - 2.0 * Math.PI - theta)
  if(dp < d0) {
    lastTheta += 2.0 * Math.PI
  }
  if(dn < d0) {
    lastTheta -= 2.0 * Math.PI
  }

  this.angle.jump(this.angle.lastT(), lastTheta, lastPhi)
  this.angle.set(t, theta, phi)
}

function createTurntableController(options) {
  options = options || {}

  var center = options.center || [0,0,0]
  var up     = options.up     || [0,1,0]
  var right  = options.right  || findOrthoPair(up)
  var radius = options.radius || 1.0
  var theta  = options.theta  || 0.0
  var phi    = options.phi    || 0.0

  center = [].slice.call(center, 0, 3)

  up = [].slice.call(up, 0, 3)
  normalize3(up, up)

  right = [].slice.call(right, 0, 3)
  normalize3(right, right)

  if('eye' in options) {
    var eye = options.eye
    var toward = [
      eye[0]-center[0],
      eye[1]-center[1],
      eye[2]-center[2]
    ]
    cross(right, toward, up)
    if(len3(right[0], right[1], right[2]) < 1e-6) {
      right = findOrthoPair(up)
    } else {
      normalize3(right, right)
    }

    radius = len3(toward[0], toward[1], toward[2])

    var ut = dot3(up, toward) / radius
    var rt = dot3(right, toward) / radius
    phi    = Math.acos(ut)
    theta  = Math.acos(rt)
  }

  //Use logarithmic coordinates for radius
  radius = Math.log(radius)

  //Return the controller
  return new TurntableController(
    options.zoomMin,
    options.zoomMax,
    center,
    up,
    right,
    radius,
    theta,
    phi)
}
},{"filtered-vector":216,"gl-mat4/invert":256,"gl-mat4/rotate":260,"gl-vec3/cross":320,"gl-vec3/dot":325,"gl-vec3/normalize":342}],521:[function(_dereq_,module,exports){
"use strict"

module.exports = twoProduct

var SPLITTER = +(Math.pow(2, 27) + 1.0)

function twoProduct(a, b, result) {
  var x = a * b

  var c = SPLITTER * a
  var abig = c - a
  var ahi = c - abig
  var alo = a - ahi

  var d = SPLITTER * b
  var bbig = d - b
  var bhi = d - bbig
  var blo = b - bhi

  var err1 = x - (ahi * bhi)
  var err2 = err1 - (alo * bhi)
  var err3 = err2 - (ahi * blo)

  var y = alo * blo - err3

  if(result) {
    result[0] = y
    result[1] = x
    return result
  }

  return [ y, x ]
}
},{}],522:[function(_dereq_,module,exports){
"use strict"

module.exports = fastTwoSum

function fastTwoSum(a, b, result) {
	var x = a + b
	var bv = x - a
	var av = x - bv
	var br = b - bv
	var ar = a - av
	if(result) {
		result[0] = ar + br
		result[1] = x
		return result
	}
	return [ar+br, x]
}
},{}],523:[function(_dereq_,module,exports){
(function (global,Buffer){
'use strict'

var bits = _dereq_('bit-twiddle')
var dup = _dereq_('dup')

//Legacy pool support
if(!global.__TYPEDARRAY_POOL) {
  global.__TYPEDARRAY_POOL = {
      UINT8   : dup([32, 0])
    , UINT16  : dup([32, 0])
    , UINT32  : dup([32, 0])
    , INT8    : dup([32, 0])
    , INT16   : dup([32, 0])
    , INT32   : dup([32, 0])
    , FLOAT   : dup([32, 0])
    , DOUBLE  : dup([32, 0])
    , DATA    : dup([32, 0])
    , UINT8C  : dup([32, 0])
    , BUFFER  : dup([32, 0])
  }
}

var hasUint8C = (typeof Uint8ClampedArray) !== 'undefined'
var POOL = global.__TYPEDARRAY_POOL

//Upgrade pool
if(!POOL.UINT8C) {
  POOL.UINT8C = dup([32, 0])
}
if(!POOL.BUFFER) {
  POOL.BUFFER = dup([32, 0])
}

//New technique: Only allocate from ArrayBufferView and Buffer
var DATA    = POOL.DATA
  , BUFFER  = POOL.BUFFER

exports.free = function free(array) {
  if(Buffer.isBuffer(array)) {
    BUFFER[bits.log2(array.length)].push(array)
  } else {
    if(Object.prototype.toString.call(array) !== '[object ArrayBuffer]') {
      array = array.buffer
    }
    if(!array) {
      return
    }
    var n = array.length || array.byteLength
    var log_n = bits.log2(n)|0
    DATA[log_n].push(array)
  }
}

function freeArrayBuffer(buffer) {
  if(!buffer) {
    return
  }
  var n = buffer.length || buffer.byteLength
  var log_n = bits.log2(n)
  DATA[log_n].push(buffer)
}

function freeTypedArray(array) {
  freeArrayBuffer(array.buffer)
}

exports.freeUint8 =
exports.freeUint16 =
exports.freeUint32 =
exports.freeInt8 =
exports.freeInt16 =
exports.freeInt32 =
exports.freeFloat32 = 
exports.freeFloat =
exports.freeFloat64 = 
exports.freeDouble = 
exports.freeUint8Clamped = 
exports.freeDataView = freeTypedArray

exports.freeArrayBuffer = freeArrayBuffer

exports.freeBuffer = function freeBuffer(array) {
  BUFFER[bits.log2(array.length)].push(array)
}

exports.malloc = function malloc(n, dtype) {
  if(dtype === undefined || dtype === 'arraybuffer') {
    return mallocArrayBuffer(n)
  } else {
    switch(dtype) {
      case 'uint8':
        return mallocUint8(n)
      case 'uint16':
        return mallocUint16(n)
      case 'uint32':
        return mallocUint32(n)
      case 'int8':
        return mallocInt8(n)
      case 'int16':
        return mallocInt16(n)
      case 'int32':
        return mallocInt32(n)
      case 'float':
      case 'float32':
        return mallocFloat(n)
      case 'double':
      case 'float64':
        return mallocDouble(n)
      case 'uint8_clamped':
        return mallocUint8Clamped(n)
      case 'buffer':
        return mallocBuffer(n)
      case 'data':
      case 'dataview':
        return mallocDataView(n)

      default:
        return null
    }
  }
  return null
}

function mallocArrayBuffer(n) {
  var n = bits.nextPow2(n)
  var log_n = bits.log2(n)
  var d = DATA[log_n]
  if(d.length > 0) {
    return d.pop()
  }
  return new ArrayBuffer(n)
}
exports.mallocArrayBuffer = mallocArrayBuffer

function mallocUint8(n) {
  return new Uint8Array(mallocArrayBuffer(n), 0, n)
}
exports.mallocUint8 = mallocUint8

function mallocUint16(n) {
  return new Uint16Array(mallocArrayBuffer(2*n), 0, n)
}
exports.mallocUint16 = mallocUint16

function mallocUint32(n) {
  return new Uint32Array(mallocArrayBuffer(4*n), 0, n)
}
exports.mallocUint32 = mallocUint32

function mallocInt8(n) {
  return new Int8Array(mallocArrayBuffer(n), 0, n)
}
exports.mallocInt8 = mallocInt8

function mallocInt16(n) {
  return new Int16Array(mallocArrayBuffer(2*n), 0, n)
}
exports.mallocInt16 = mallocInt16

function mallocInt32(n) {
  return new Int32Array(mallocArrayBuffer(4*n), 0, n)
}
exports.mallocInt32 = mallocInt32

function mallocFloat(n) {
  return new Float32Array(mallocArrayBuffer(4*n), 0, n)
}
exports.mallocFloat32 = exports.mallocFloat = mallocFloat

function mallocDouble(n) {
  return new Float64Array(mallocArrayBuffer(8*n), 0, n)
}
exports.mallocFloat64 = exports.mallocDouble = mallocDouble

function mallocUint8Clamped(n) {
  if(hasUint8C) {
    return new Uint8ClampedArray(mallocArrayBuffer(n), 0, n)
  } else {
    return mallocUint8(n)
  }
}
exports.mallocUint8Clamped = mallocUint8Clamped

function mallocDataView(n) {
  return new DataView(mallocArrayBuffer(n), 0, n)
}
exports.mallocDataView = mallocDataView

function mallocBuffer(n) {
  n = bits.nextPow2(n)
  var log_n = bits.log2(n)
  var cache = BUFFER[log_n]
  if(cache.length > 0) {
    return cache.pop()
  }
  return new Buffer(n)
}
exports.mallocBuffer = mallocBuffer

exports.clearCache = function clearCache() {
  for(var i=0; i<32; ++i) {
    POOL.UINT8[i].length = 0
    POOL.UINT16[i].length = 0
    POOL.UINT32[i].length = 0
    POOL.INT8[i].length = 0
    POOL.INT16[i].length = 0
    POOL.INT32[i].length = 0
    POOL.FLOAT[i].length = 0
    POOL.DOUBLE[i].length = 0
    POOL.UINT8C[i].length = 0
    DATA[i].length = 0
    BUFFER[i].length = 0
  }
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_("buffer").Buffer)
},{"bit-twiddle":81,"buffer":94,"dup":156}],524:[function(_dereq_,module,exports){
"use strict"; "use restrict";

module.exports = UnionFind;

function UnionFind(count) {
  this.roots = new Array(count);
  this.ranks = new Array(count);
  
  for(var i=0; i<count; ++i) {
    this.roots[i] = i;
    this.ranks[i] = 0;
  }
}

var proto = UnionFind.prototype

Object.defineProperty(proto, "length", {
  "get": function() {
    return this.roots.length
  }
})

proto.makeSet = function() {
  var n = this.roots.length;
  this.roots.push(n);
  this.ranks.push(0);
  return n;
}

proto.find = function(x) {
  var x0 = x
  var roots = this.roots;
  while(roots[x] !== x) {
    x = roots[x]
  }
  while(roots[x0] !== x) {
    var y = roots[x0]
    roots[x0] = x
    x0 = y
  }
  return x;
}

proto.link = function(x, y) {
  var xr = this.find(x)
    , yr = this.find(y);
  if(xr === yr) {
    return;
  }
  var ranks = this.ranks
    , roots = this.roots
    , xd    = ranks[xr]
    , yd    = ranks[yr];
  if(xd < yd) {
    roots[xr] = yr;
  } else if(yd < xd) {
    roots[yr] = xr;
  } else {
    roots[yr] = xr;
    ++ranks[xr];
  }
}
},{}],525:[function(_dereq_,module,exports){
"use strict"

function unique_pred(list, compare) {
  var ptr = 1
    , len = list.length
    , a=list[0], b=list[0]
  for(var i=1; i<len; ++i) {
    b = a
    a = list[i]
    if(compare(a, b)) {
      if(i === ptr) {
        ptr++
        continue
      }
      list[ptr++] = a
    }
  }
  list.length = ptr
  return list
}

function unique_eq(list) {
  var ptr = 1
    , len = list.length
    , a=list[0], b = list[0]
  for(var i=1; i<len; ++i, b=a) {
    b = a
    a = list[i]
    if(a !== b) {
      if(i === ptr) {
        ptr++
        continue
      }
      list[ptr++] = a
    }
  }
  list.length = ptr
  return list
}

function unique(list, compare, sorted) {
  if(list.length === 0) {
    return list
  }
  if(compare) {
    if(!sorted) {
      list.sort(compare)
    }
    return unique_pred(list, compare)
  }
  if(!sorted) {
    list.sort()
  }
  return unique_eq(list)
}

module.exports = unique

},{}],526:[function(_dereq_,module,exports){
var reg = /[\'\"]/

module.exports = function unquote(str) {
  if (!str) {
    return ''
  }
  if (reg.test(str.charAt(0))) {
    str = str.substr(1)
  }
  if (reg.test(str.charAt(str.length - 1))) {
    str = str.substr(0, str.length - 1)
  }
  return str
}

},{}],527:[function(_dereq_,module,exports){
/**
 * @module update-diff
 */

'use strict'

module.exports = function updateDiff (obj, diff, mappers) {
	if (!Array.isArray(mappers)) mappers = [].slice.call(arguments, 2)

	for (var i = 0, l = mappers.length; i < l; i++) {
		var dict = mappers[i]
		for (var prop in dict) {
			if (diff[prop] !== undefined && !Array.isArray(diff[prop]) && obj[prop] === diff[prop]) continue

			if (prop in diff) {
				var result

				if (dict[prop] === true) result = diff[prop]
				else if (dict[prop] === false) continue
				else if (typeof dict[prop] === 'function') {
					result = dict[prop](diff[prop], obj, diff)
					if (result === undefined) continue
				}

				obj[prop] = result
			}
		}
	}

	return obj
}

},{}],528:[function(_dereq_,module,exports){
"use strict"

module.exports = createText

var vectorizeText = _dereq_("./lib/vtext")
var defaultCanvas = null
var defaultContext = null

if(typeof document !== 'undefined') {
  defaultCanvas = document.createElement('canvas')
  defaultCanvas.width = 8192
  defaultCanvas.height = 1024
  defaultContext = defaultCanvas.getContext("2d")
}

function createText(str, options) {
  if((typeof options !== "object") || (options === null)) {
    options = {}
  }
  return vectorizeText(
    str,
    options.canvas || defaultCanvas,
    options.context || defaultContext,
    options)
}

},{"./lib/vtext":529}],529:[function(_dereq_,module,exports){
module.exports = vectorizeText
module.exports.processPixels = processPixels

var surfaceNets = _dereq_('surface-nets')
var ndarray = _dereq_('ndarray')
var simplify = _dereq_('simplify-planar-graph')
var cleanPSLG = _dereq_('clean-pslg')
var cdt2d = _dereq_('cdt2d')
var toPolygonCrappy = _dereq_('planar-graph-to-polyline')

var TAG_bold = "b"
var CHR_bold = 'b|'

var TAG_italic = "i"
var CHR_italic = 'i|'

var TAG_super = "sup"
var CHR_super0 = '+'
var CHR_super = '+1'

var TAG_sub = "sub"
var CHR_sub0 = '-'
var CHR_sub = '-1'

function parseTag(tag, TAG_CHR, str, map) {

  var opnTag =  "<"  + tag + ">"
  var clsTag =  "</" + tag + ">"

  var nOPN = opnTag.length
  var nCLS = clsTag.length

  var isRecursive = (TAG_CHR[0] === CHR_super0) ||
                    (TAG_CHR[0] === CHR_sub0);

  var a = 0
  var b = -nCLS
  while (a > -1) {
    a = str.indexOf(opnTag, a)
    if(a === -1) break

    b = str.indexOf(clsTag, a + nOPN)
    if(b === -1) break

    if(b <= a) break

    for(var i = a; i < b + nCLS; ++i){
      if((i < a + nOPN) || (i >= b)) {
        map[i] = null
        str = str.substr(0, i) + " " + str.substr(i + 1)
      } else {
        if(map[i] !== null) {
          var pos = map[i].indexOf(TAG_CHR[0])
          if(pos === -1) {
            map[i] += TAG_CHR
          } else { // i.e. to handle multiple sub/super-scripts
            if(isRecursive) {
              // i.e to increase the sub/sup number
              map[i] = map[i].substr(0, pos + 1) + (1 + parseInt(map[i][pos + 1])) + map[i].substr(pos + 2)
            }
          }
        }
      }
    }

    var start = a + nOPN
    var remainingStr = str.substr(start, b - start)

    var c = remainingStr.indexOf(opnTag)
    if(c !== -1) a = c
    else a = b + nCLS
  }

  return map
}

function transformPositions(positions, options, size) {
  var align = options.textAlign || "start"
  var baseline = options.textBaseline || "alphabetic"

  var lo = [1<<30, 1<<30]
  var hi = [0,0]
  var n = positions.length
  for(var i=0; i<n; ++i) {
    var p = positions[i]
    for(var j=0; j<2; ++j) {
      lo[j] = Math.min(lo[j], p[j])|0
      hi[j] = Math.max(hi[j], p[j])|0
    }
  }

  var xShift = 0
  switch(align) {
    case "center":
      xShift = -0.5 * (lo[0] + hi[0])
    break

    case "right":
    case "end":
      xShift = -hi[0]
    break

    case "left":
    case "start":
      xShift = -lo[0]
    break

    default:
      throw new Error("vectorize-text: Unrecognized textAlign: '" + align + "'")
  }

  var yShift = 0
  switch(baseline) {
    case "hanging":
    case "top":
      yShift = -lo[1]
    break

    case "middle":
      yShift = -0.5 * (lo[1] + hi[1])
    break

    case "alphabetic":
    case "ideographic":
      yShift = -3 * size
    break

    case "bottom":
      yShift = -hi[1]
    break

    default:
      throw new Error("vectorize-text: Unrecoginized textBaseline: '" + baseline + "'")
  }

  var scale = 1.0 / size
  if("lineHeight" in options) {
    scale *= +options.lineHeight
  } else if("width" in options) {
    scale = options.width / (hi[0] - lo[0])
  } else if("height" in options) {
    scale = options.height / (hi[1] - lo[1])
  }

  return positions.map(function(p) {
    return [ scale * (p[0] + xShift), scale * (p[1] + yShift) ]
  })
}

function getPixels(canvas, context, rawString, fontSize, lineSpacing, styletags) {

  rawString = rawString.replace(/\n/g, '') // don't accept \n in the input

  if(styletags.breaklines === true) {
    rawString = rawString.replace(/\<br\>/g, '\n') // replace <br> tags with \n in the string
  } else {
    rawString = rawString.replace(/\<br\>/g, ' ') // don't accept <br> tags in the input and replace with space in this case
  }

  var activeStyle = ""
  var map = []
  for(j = 0; j < rawString.length; ++j) {
    map[j] = activeStyle
  }

  if(styletags.bolds === true) map = parseTag(TAG_bold, CHR_bold, rawString, map)
  if(styletags.italics === true) map = parseTag(TAG_italic, CHR_italic, rawString, map)
  if(styletags.superscripts === true) map = parseTag(TAG_super, CHR_super, rawString, map)
  if(styletags.subscripts === true) map = parseTag(TAG_sub, CHR_sub, rawString, map)

  var allStyles = []
  var plainText = ""
  for(j = 0; j < rawString.length; ++j) {
    if(map[j] !== null) {
      plainText += rawString[j]
      allStyles.push(map[j])
    }
  }

  var allTexts = plainText.split('\n')

  var numberOfLines = allTexts.length
  var lineHeight = Math.round(lineSpacing * fontSize)
  var offsetX = fontSize
  var offsetY = fontSize * 2
  var maxWidth = 0
  var minHeight = numberOfLines * lineHeight + offsetY

  if(canvas.height < minHeight) {
    canvas.height = minHeight
  }

  context.fillStyle = "#000"
  context.fillRect(0, 0, canvas.width, canvas.height)

  context.fillStyle = "#fff"
  var i, j, xPos, yPos, zPos
  var nDone = 0

  var buffer = ""
  function writeBuffer() {
    if(buffer !== "") {
      var delta = context.measureText(buffer).width

      context.fillText(buffer, offsetX + xPos, offsetY + yPos)
      xPos += delta
    }
  }

  function getTextFontSize() {
    return "" + Math.round(zPos) + "px ";
  }

  function changeStyle(oldStyle, newStyle) {
    var ctxFont = "" + context.font;

    if(styletags.subscripts === true) {
      var oldIndex_Sub = oldStyle.indexOf(CHR_sub0);
      var newIndex_Sub = newStyle.indexOf(CHR_sub0);

      var oldSub = (oldIndex_Sub > -1) ? parseInt(oldStyle[1 + oldIndex_Sub]) : 0;
      var newSub = (newIndex_Sub > -1) ? parseInt(newStyle[1 + newIndex_Sub]) : 0;

      if(oldSub !== newSub) {
        ctxFont = ctxFont.replace(getTextFontSize(), "?px ")
        zPos *= Math.pow(0.75, (newSub - oldSub))
        ctxFont = ctxFont.replace("?px ", getTextFontSize())
      }
      yPos += 0.25 * lineHeight * (newSub - oldSub);
    }

    if(styletags.superscripts === true) {
      var oldIndex_Super = oldStyle.indexOf(CHR_super0);
      var newIndex_Super = newStyle.indexOf(CHR_super0);

      var oldSuper = (oldIndex_Super > -1) ? parseInt(oldStyle[1 + oldIndex_Super]) : 0;
      var newSuper = (newIndex_Super > -1) ? parseInt(newStyle[1 + newIndex_Super]) : 0;

      if(oldSuper !== newSuper) {
        ctxFont = ctxFont.replace(getTextFontSize(), "?px ")
        zPos *= Math.pow(0.75, (newSuper - oldSuper))
        ctxFont = ctxFont.replace("?px ", getTextFontSize())
      }
      yPos -= 0.25 * lineHeight * (newSuper - oldSuper);
    }

    if(styletags.bolds === true) {
      var wasBold = (oldStyle.indexOf(CHR_bold) > -1)
      var is_Bold = (newStyle.indexOf(CHR_bold) > -1)

      if(!wasBold && is_Bold) {
        if(wasItalic) {
          ctxFont = ctxFont.replace("italic ", "italic bold ")
        } else {
          ctxFont = "bold " + ctxFont
        }
      }
      if(wasBold && !is_Bold) {
        ctxFont = ctxFont.replace("bold ", '')
      }
    }

    if(styletags.italics === true) {
      var wasItalic = (oldStyle.indexOf(CHR_italic) > -1)
      var is_Italic = (newStyle.indexOf(CHR_italic) > -1)

      if(!wasItalic && is_Italic) {
        ctxFont = "italic " + ctxFont
      }
      if(wasItalic && !is_Italic) {
        ctxFont = ctxFont.replace("italic ", '')
      }
    }
    context.font = ctxFont
  }

  for(i = 0; i < numberOfLines; ++i) {
    var txt = allTexts[i] + '\n'
    xPos = 0
    yPos = i * lineHeight
    zPos = fontSize

    buffer = ""
    
    for(j = 0; j < txt.length; ++j) {
      var style = (j + nDone < allStyles.length) ? allStyles[j + nDone] : allStyles[allStyles.length - 1]
      if(activeStyle === style) {
        buffer += txt[j]
      } else {
        writeBuffer()
        buffer = txt[j]

        if(style !== undefined) {
          changeStyle(activeStyle, style)
          activeStyle = style
        }
      }
    }
    writeBuffer()

    nDone += txt.length

    var width = Math.round(xPos + 2 * offsetX) | 0
    if(maxWidth < width) maxWidth = width
  }

  //Cut pixels from image
  var xCut = maxWidth
  var yCut = offsetY + lineHeight * numberOfLines
  var pixels = ndarray(context.getImageData(0, 0, xCut, yCut).data, [yCut, xCut, 4])
  return pixels.pick(-1, -1, 0).transpose(1, 0)
}

function getContour(pixels, doSimplify) {
  var contour = surfaceNets(pixels, 128)
  if(doSimplify) {
    return simplify(contour.cells, contour.positions, 0.25)
  }
  return {
    edges: contour.cells,
    positions: contour.positions
  }
}

function processPixelsImpl(pixels, options, size, simplify) {
  //Extract contour
  var contour = getContour(pixels, simplify)

  //Apply warp to positions
  var positions = transformPositions(contour.positions, options, size)
  var edges     = contour.edges
  var flip = "ccw" === options.orientation

  //Clean up the PSLG, resolve self intersections, etc.
  cleanPSLG(positions, edges)

  //If triangulate flag passed, triangulate the result
  if(options.polygons || options.polygon || options.polyline) {
    var result = toPolygonCrappy(edges, positions)
    var nresult = new Array(result.length)
    for(var i=0; i<result.length; ++i) {
      var loops = result[i]
      var nloops = new Array(loops.length)
      for(var j=0; j<loops.length; ++j) {
        var loop = loops[j]
        var nloop = new Array(loop.length)
        for(var k=0; k<loop.length; ++k) {
          nloop[k] = positions[loop[k]].slice()
        }
        if(flip) {
          nloop.reverse()
        }
        nloops[j] = nloop
      }
      nresult[i] = nloops
    }
    return nresult
  } else if(options.triangles || options.triangulate || options.triangle) {
    return {
      cells: cdt2d(positions, edges, {
        delaunay: false,
        exterior: false,
        interior: true
      }),
      positions: positions
    }
  } else {
    return {
      edges:     edges,
      positions: positions
    }
  }
}

function processPixels(pixels, options, size) {
  try {
    return processPixelsImpl(pixels, options, size, true)
  } catch(e) {}
  try {
    return processPixelsImpl(pixels, options, size, false)
  } catch(e) {}
  if(options.polygons || options.polyline || options.polygon) {
    return []
  }
  if(options.triangles || options.triangulate || options.triangle) {
    return {
      cells: [],
      positions: []
    }
  }
  return {
    edges: [],
    positions: []
  }
}

function vectorizeText(str, canvas, context, options) {
  var size = 64
  var lineSpacing = 1.25
  var styletags = {
    breaklines: false,
    bolds: false,
    italics: false,
    subscripts: false,
    superscripts: false
  }

  if(options) {

    if(options.size &&
       options.size > 0) size =
       options.size

    if(options.lineSpacing &&
       options.lineSpacing > 0) lineSpacing =
       options.lineSpacing

    if(options.styletags &&
       options.styletags.breaklines) styletags.breaklines =
       options.styletags.breaklines ? true : false

    if(options.styletags &&
       options.styletags.bolds) styletags.bolds =
       options.styletags.bolds ? true : false

    if(options.styletags &&
       options.styletags.italics) styletags.italics =
       options.styletags.italics ? true : false

    if(options.styletags &&
       options.styletags.subscripts) styletags.subscripts =
       options.styletags.subscripts ? true : false

    if(options.styletags &&
       options.styletags.superscripts) styletags.superscripts =
       options.styletags.superscripts ? true : false
  }

  context.font = [
    options.fontStyle,
    options.fontVariant,
    options.fontWeight,
    size + "px",
    options.font
  ].filter(function(d) {return d}).join(" ")
  context.textAlign = "start"
  context.textBaseline = "alphabetic"
  context.direction = "ltr"

  var pixels = getPixels(canvas, context, str, size, lineSpacing, styletags)

  return processPixels(pixels, options, size)
}

},{"cdt2d":95,"clean-pslg":105,"ndarray":436,"planar-graph-to-polyline":454,"simplify-planar-graph":502,"surface-nets":509}],530:[function(_dereq_,module,exports){
// Copyright (C) 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Install a leaky WeakMap emulation on platforms that
 * don't provide a built-in one.
 *
 * <p>Assumes that an ES5 platform where, if {@code WeakMap} is
 * already present, then it conforms to the anticipated ES6
 * specification. To run this file on an ES5 or almost ES5
 * implementation where the {@code WeakMap} specification does not
 * quite conform, run <code>repairES5.js</code> first.
 *
 * <p>Even though WeakMapModule is not global, the linter thinks it
 * is, which is why it is in the overrides list below.
 *
 * <p>NOTE: Before using this WeakMap emulation in a non-SES
 * environment, see the note below about hiddenRecord.
 *
 * @author Mark S. Miller
 * @requires crypto, ArrayBuffer, Uint8Array, navigator, console
 * @overrides WeakMap, ses, Proxy
 * @overrides WeakMapModule
 */

/**
 * This {@code WeakMap} emulation is observably equivalent to the
 * ES-Harmony WeakMap, but with leakier garbage collection properties.
 *
 * <p>As with true WeakMaps, in this emulation, a key does not
 * retain maps indexed by that key and (crucially) a map does not
 * retain the keys it indexes. A map by itself also does not retain
 * the values associated with that map.
 *
 * <p>However, the values associated with a key in some map are
 * retained so long as that key is retained and those associations are
 * not overridden. For example, when used to support membranes, all
 * values exported from a given membrane will live for the lifetime
 * they would have had in the absence of an interposed membrane. Even
 * when the membrane is revoked, all objects that would have been
 * reachable in the absence of revocation will still be reachable, as
 * far as the GC can tell, even though they will no longer be relevant
 * to ongoing computation.
 *
 * <p>The API implemented here is approximately the API as implemented
 * in FF6.0a1 and agreed to by MarkM, Andreas Gal, and Dave Herman,
 * rather than the offially approved proposal page. TODO(erights):
 * upgrade the ecmascript WeakMap proposal page to explain this API
 * change and present to EcmaScript committee for their approval.
 *
 * <p>The first difference between the emulation here and that in
 * FF6.0a1 is the presence of non enumerable {@code get___, has___,
 * set___, and delete___} methods on WeakMap instances to represent
 * what would be the hidden internal properties of a primitive
 * implementation. Whereas the FF6.0a1 WeakMap.prototype methods
 * require their {@code this} to be a genuine WeakMap instance (i.e.,
 * an object of {@code [[Class]]} "WeakMap}), since there is nothing
 * unforgeable about the pseudo-internal method names used here,
 * nothing prevents these emulated prototype methods from being
 * applied to non-WeakMaps with pseudo-internal methods of the same
 * names.
 *
 * <p>Another difference is that our emulated {@code
 * WeakMap.prototype} is not itself a WeakMap. A problem with the
 * current FF6.0a1 API is that WeakMap.prototype is itself a WeakMap
 * providing ambient mutability and an ambient communications
 * channel. Thus, if a WeakMap is already present and has this
 * problem, repairES5.js wraps it in a safe wrappper in order to
 * prevent access to this channel. (See
 * PATCH_MUTABLE_FROZEN_WEAKMAP_PROTO in repairES5.js).
 */

/**
 * If this is a full <a href=
 * "http://code.google.com/p/es-lab/wiki/SecureableES5"
 * >secureable ES5</a> platform and the ES-Harmony {@code WeakMap} is
 * absent, install an approximate emulation.
 *
 * <p>If WeakMap is present but cannot store some objects, use our approximate
 * emulation as a wrapper.
 *
 * <p>If this is almost a secureable ES5 platform, then WeakMap.js
 * should be run after repairES5.js.
 *
 * <p>See {@code WeakMap} for documentation of the garbage collection
 * properties of this WeakMap emulation.
 */
(function WeakMapModule() {
  "use strict";

  if (typeof ses !== 'undefined' && ses.ok && !ses.ok()) {
    // already too broken, so give up
    return;
  }

  /**
   * In some cases (current Firefox), we must make a choice betweeen a
   * WeakMap which is capable of using all varieties of host objects as
   * keys and one which is capable of safely using proxies as keys. See
   * comments below about HostWeakMap and DoubleWeakMap for details.
   *
   * This function (which is a global, not exposed to guests) marks a
   * WeakMap as permitted to do what is necessary to index all host
   * objects, at the cost of making it unsafe for proxies.
   *
   * Do not apply this function to anything which is not a genuine
   * fresh WeakMap.
   */
  function weakMapPermitHostObjects(map) {
    // identity of function used as a secret -- good enough and cheap
    if (map.permitHostObjects___) {
      map.permitHostObjects___(weakMapPermitHostObjects);
    }
  }
  if (typeof ses !== 'undefined') {
    ses.weakMapPermitHostObjects = weakMapPermitHostObjects;
  }

  // IE 11 has no Proxy but has a broken WeakMap such that we need to patch
  // it using DoubleWeakMap; this flag tells DoubleWeakMap so.
  var doubleWeakMapCheckSilentFailure = false;

  // Check if there is already a good-enough WeakMap implementation, and if so
  // exit without replacing it.
  if (typeof WeakMap === 'function') {
    var HostWeakMap = WeakMap;
    // There is a WeakMap -- is it good enough?
    if (typeof navigator !== 'undefined' &&
        /Firefox/.test(navigator.userAgent)) {
      // We're now *assuming not*, because as of this writing (2013-05-06)
      // Firefox's WeakMaps have a miscellany of objects they won't accept, and
      // we don't want to make an exhaustive list, and testing for just one
      // will be a problem if that one is fixed alone (as they did for Event).

      // If there is a platform that we *can* reliably test on, here's how to
      // do it:
      //  var problematic = ... ;
      //  var testHostMap = new HostWeakMap();
      //  try {
      //    testHostMap.set(problematic, 1);  // Firefox 20 will throw here
      //    if (testHostMap.get(problematic) === 1) {
      //      return;
      //    }
      //  } catch (e) {}

    } else {
      // IE 11 bug: WeakMaps silently fail to store frozen objects.
      var testMap = new HostWeakMap();
      var testObject = Object.freeze({});
      testMap.set(testObject, 1);
      if (testMap.get(testObject) !== 1) {
        doubleWeakMapCheckSilentFailure = true;
        // Fall through to installing our WeakMap.
      } else {
        module.exports = WeakMap;
        return;
      }
    }
  }

  var hop = Object.prototype.hasOwnProperty;
  var gopn = Object.getOwnPropertyNames;
  var defProp = Object.defineProperty;
  var isExtensible = Object.isExtensible;

  /**
   * Security depends on HIDDEN_NAME being both <i>unguessable</i> and
   * <i>undiscoverable</i> by untrusted code.
   *
   * <p>Given the known weaknesses of Math.random() on existing
   * browsers, it does not generate unguessability we can be confident
   * of.
   *
   * <p>It is the monkey patching logic in this file that is intended
   * to ensure undiscoverability. The basic idea is that there are
   * three fundamental means of discovering properties of an object:
   * The for/in loop, Object.keys(), and Object.getOwnPropertyNames(),
   * as well as some proposed ES6 extensions that appear on our
   * whitelist. The first two only discover enumerable properties, and
   * we only use HIDDEN_NAME to name a non-enumerable property, so the
   * only remaining threat should be getOwnPropertyNames and some
   * proposed ES6 extensions that appear on our whitelist. We monkey
   * patch them to remove HIDDEN_NAME from the list of properties they
   * returns.
   *
   * <p>TODO(erights): On a platform with built-in Proxies, proxies
   * could be used to trap and thereby discover the HIDDEN_NAME, so we
   * need to monkey patch Proxy.create, Proxy.createFunction, etc, in
   * order to wrap the provided handler with the real handler which
   * filters out all traps using HIDDEN_NAME.
   *
   * <p>TODO(erights): Revisit Mike Stay's suggestion that we use an
   * encapsulated function at a not-necessarily-secret name, which
   * uses the Stiegler shared-state rights amplification pattern to
   * reveal the associated value only to the WeakMap in which this key
   * is associated with that value. Since only the key retains the
   * function, the function can also remember the key without causing
   * leakage of the key, so this doesn't violate our general gc
   * goals. In addition, because the name need not be a guarded
   * secret, we could efficiently handle cross-frame frozen keys.
   */
  var HIDDEN_NAME_PREFIX = 'weakmap:';
  var HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'ident:' + Math.random() + '___';

  if (typeof crypto !== 'undefined' &&
      typeof crypto.getRandomValues === 'function' &&
      typeof ArrayBuffer === 'function' &&
      typeof Uint8Array === 'function') {
    var ab = new ArrayBuffer(25);
    var u8s = new Uint8Array(ab);
    crypto.getRandomValues(u8s);
    HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'rand:' +
      Array.prototype.map.call(u8s, function(u8) {
        return (u8 % 36).toString(36);
      }).join('') + '___';
  }

  function isNotHiddenName(name) {
    return !(
        name.substr(0, HIDDEN_NAME_PREFIX.length) == HIDDEN_NAME_PREFIX &&
        name.substr(name.length - 3) === '___');
  }

  /**
   * Monkey patch getOwnPropertyNames to avoid revealing the
   * HIDDEN_NAME.
   *
   * <p>The ES5.1 spec requires each name to appear only once, but as
   * of this writing, this requirement is controversial for ES6, so we
   * made this code robust against this case. If the resulting extra
   * search turns out to be expensive, we can probably relax this once
   * ES6 is adequately supported on all major browsers, iff no browser
   * versions we support at that time have relaxed this constraint
   * without providing built-in ES6 WeakMaps.
   */
  defProp(Object, 'getOwnPropertyNames', {
    value: function fakeGetOwnPropertyNames(obj) {
      return gopn(obj).filter(isNotHiddenName);
    }
  });

  /**
   * getPropertyNames is not in ES5 but it is proposed for ES6 and
   * does appear in our whitelist, so we need to clean it too.
   */
  if ('getPropertyNames' in Object) {
    var originalGetPropertyNames = Object.getPropertyNames;
    defProp(Object, 'getPropertyNames', {
      value: function fakeGetPropertyNames(obj) {
        return originalGetPropertyNames(obj).filter(isNotHiddenName);
      }
    });
  }

  /**
   * <p>To treat objects as identity-keys with reasonable efficiency
   * on ES5 by itself (i.e., without any object-keyed collections), we
   * need to add a hidden property to such key objects when we
   * can. This raises several issues:
   * <ul>
   * <li>Arranging to add this property to objects before we lose the
   *     chance, and
   * <li>Hiding the existence of this new property from most
   *     JavaScript code.
   * <li>Preventing <i>certification theft</i>, where one object is
   *     created falsely claiming to be the key of an association
   *     actually keyed by another object.
   * <li>Preventing <i>value theft</i>, where untrusted code with
   *     access to a key object but not a weak map nevertheless
   *     obtains access to the value associated with that key in that
   *     weak map.
   * </ul>
   * We do so by
   * <ul>
   * <li>Making the name of the hidden property unguessable, so "[]"
   *     indexing, which we cannot intercept, cannot be used to access
   *     a property without knowing the name.
   * <li>Making the hidden property non-enumerable, so we need not
   *     worry about for-in loops or {@code Object.keys},
   * <li>monkey patching those reflective methods that would
   *     prevent extensions, to add this hidden property first,
   * <li>monkey patching those methods that would reveal this
   *     hidden property.
   * </ul>
   * Unfortunately, because of same-origin iframes, we cannot reliably
   * add this hidden property before an object becomes
   * non-extensible. Instead, if we encounter a non-extensible object
   * without a hidden record that we can detect (whether or not it has
   * a hidden record stored under a name secret to us), then we just
   * use the key object itself to represent its identity in a brute
   * force leaky map stored in the weak map, losing all the advantages
   * of weakness for these.
   */
  function getHiddenRecord(key) {
    if (key !== Object(key)) {
      throw new TypeError('Not an object: ' + key);
    }
    var hiddenRecord = key[HIDDEN_NAME];
    if (hiddenRecord && hiddenRecord.key === key) { return hiddenRecord; }
    if (!isExtensible(key)) {
      // Weak map must brute force, as explained in doc-comment above.
      return void 0;
    }

    // The hiddenRecord and the key point directly at each other, via
    // the "key" and HIDDEN_NAME properties respectively. The key
    // field is for quickly verifying that this hidden record is an
    // own property, not a hidden record from up the prototype chain.
    //
    // NOTE: Because this WeakMap emulation is meant only for systems like
    // SES where Object.prototype is frozen without any numeric
    // properties, it is ok to use an object literal for the hiddenRecord.
    // This has two advantages:
    // * It is much faster in a performance critical place
    // * It avoids relying on Object.create(null), which had been
    //   problematic on Chrome 28.0.1480.0. See
    //   https://code.google.com/p/google-caja/issues/detail?id=1687
    hiddenRecord = { key: key };

    // When using this WeakMap emulation on platforms where
    // Object.prototype might not be frozen and Object.create(null) is
    // reliable, use the following two commented out lines instead.
    // hiddenRecord = Object.create(null);
    // hiddenRecord.key = key;

    // Please contact us if you need this to work on platforms where
    // Object.prototype might not be frozen and
    // Object.create(null) might not be reliable.

    try {
      defProp(key, HIDDEN_NAME, {
        value: hiddenRecord,
        writable: false,
        enumerable: false,
        configurable: false
      });
      return hiddenRecord;
    } catch (error) {
      // Under some circumstances, isExtensible seems to misreport whether
      // the HIDDEN_NAME can be defined.
      // The circumstances have not been isolated, but at least affect
      // Node.js v0.10.26 on TravisCI / Linux, but not the same version of
      // Node.js on OS X.
      return void 0;
    }
  }

  /**
   * Monkey patch operations that would make their argument
   * non-extensible.
   *
   * <p>The monkey patched versions throw a TypeError if their
   * argument is not an object, so it should only be done to functions
   * that should throw a TypeError anyway if their argument is not an
   * object.
   */
  (function(){
    var oldFreeze = Object.freeze;
    defProp(Object, 'freeze', {
      value: function identifyingFreeze(obj) {
        getHiddenRecord(obj);
        return oldFreeze(obj);
      }
    });
    var oldSeal = Object.seal;
    defProp(Object, 'seal', {
      value: function identifyingSeal(obj) {
        getHiddenRecord(obj);
        return oldSeal(obj);
      }
    });
    var oldPreventExtensions = Object.preventExtensions;
    defProp(Object, 'preventExtensions', {
      value: function identifyingPreventExtensions(obj) {
        getHiddenRecord(obj);
        return oldPreventExtensions(obj);
      }
    });
  })();

  function constFunc(func) {
    func.prototype = null;
    return Object.freeze(func);
  }

  var calledAsFunctionWarningDone = false;
  function calledAsFunctionWarning() {
    // Future ES6 WeakMap is currently (2013-09-10) expected to reject WeakMap()
    // but we used to permit it and do it ourselves, so warn only.
    if (!calledAsFunctionWarningDone && typeof console !== 'undefined') {
      calledAsFunctionWarningDone = true;
      console.warn('WeakMap should be invoked as new WeakMap(), not ' +
          'WeakMap(). This will be an error in the future.');
    }
  }

  var nextId = 0;

  var OurWeakMap = function() {
    if (!(this instanceof OurWeakMap)) {  // approximate test for new ...()
      calledAsFunctionWarning();
    }

    // We are currently (12/25/2012) never encountering any prematurely
    // non-extensible keys.
    var keys = []; // brute force for prematurely non-extensible keys.
    var values = []; // brute force for corresponding values.
    var id = nextId++;

    function get___(key, opt_default) {
      var index;
      var hiddenRecord = getHiddenRecord(key);
      if (hiddenRecord) {
        return id in hiddenRecord ? hiddenRecord[id] : opt_default;
      } else {
        index = keys.indexOf(key);
        return index >= 0 ? values[index] : opt_default;
      }
    }

    function has___(key) {
      var hiddenRecord = getHiddenRecord(key);
      if (hiddenRecord) {
        return id in hiddenRecord;
      } else {
        return keys.indexOf(key) >= 0;
      }
    }

    function set___(key, value) {
      var index;
      var hiddenRecord = getHiddenRecord(key);
      if (hiddenRecord) {
        hiddenRecord[id] = value;
      } else {
        index = keys.indexOf(key);
        if (index >= 0) {
          values[index] = value;
        } else {
          // Since some browsers preemptively terminate slow turns but
          // then continue computing with presumably corrupted heap
          // state, we here defensively get keys.length first and then
          // use it to update both the values and keys arrays, keeping
          // them in sync.
          index = keys.length;
          values[index] = value;
          // If we crash here, values will be one longer than keys.
          keys[index] = key;
        }
      }
      return this;
    }

    function delete___(key) {
      var hiddenRecord = getHiddenRecord(key);
      var index, lastIndex;
      if (hiddenRecord) {
        return id in hiddenRecord && delete hiddenRecord[id];
      } else {
        index = keys.indexOf(key);
        if (index < 0) {
          return false;
        }
        // Since some browsers preemptively terminate slow turns but
        // then continue computing with potentially corrupted heap
        // state, we here defensively get keys.length first and then use
        // it to update both the keys and the values array, keeping
        // them in sync. We update the two with an order of assignments,
        // such that any prefix of these assignments will preserve the
        // key/value correspondence, either before or after the delete.
        // Note that this needs to work correctly when index === lastIndex.
        lastIndex = keys.length - 1;
        keys[index] = void 0;
        // If we crash here, there's a void 0 in the keys array, but
        // no operation will cause a "keys.indexOf(void 0)", since
        // getHiddenRecord(void 0) will always throw an error first.
        values[index] = values[lastIndex];
        // If we crash here, values[index] cannot be found here,
        // because keys[index] is void 0.
        keys[index] = keys[lastIndex];
        // If index === lastIndex and we crash here, then keys[index]
        // is still void 0, since the aliasing killed the previous key.
        keys.length = lastIndex;
        // If we crash here, keys will be one shorter than values.
        values.length = lastIndex;
        return true;
      }
    }

    return Object.create(OurWeakMap.prototype, {
      get___:    { value: constFunc(get___) },
      has___:    { value: constFunc(has___) },
      set___:    { value: constFunc(set___) },
      delete___: { value: constFunc(delete___) }
    });
  };

  OurWeakMap.prototype = Object.create(Object.prototype, {
    get: {
      /**
       * Return the value most recently associated with key, or
       * opt_default if none.
       */
      value: function get(key, opt_default) {
        return this.get___(key, opt_default);
      },
      writable: true,
      configurable: true
    },

    has: {
      /**
       * Is there a value associated with key in this WeakMap?
       */
      value: function has(key) {
        return this.has___(key);
      },
      writable: true,
      configurable: true
    },

    set: {
      /**
       * Associate value with key in this WeakMap, overwriting any
       * previous association if present.
       */
      value: function set(key, value) {
        return this.set___(key, value);
      },
      writable: true,
      configurable: true
    },

    'delete': {
      /**
       * Remove any association for key in this WeakMap, returning
       * whether there was one.
       *
       * <p>Note that the boolean return here does not work like the
       * {@code delete} operator. The {@code delete} operator returns
       * whether the deletion succeeds at bringing about a state in
       * which the deleted property is absent. The {@code delete}
       * operator therefore returns true if the property was already
       * absent, whereas this {@code delete} method returns false if
       * the association was already absent.
       */
      value: function remove(key) {
        return this.delete___(key);
      },
      writable: true,
      configurable: true
    }
  });

  if (typeof HostWeakMap === 'function') {
    (function() {
      // If we got here, then the platform has a WeakMap but we are concerned
      // that it may refuse to store some key types. Therefore, make a map
      // implementation which makes use of both as possible.

      // In this mode we are always using double maps, so we are not proxy-safe.
      // This combination does not occur in any known browser, but we had best
      // be safe.
      if (doubleWeakMapCheckSilentFailure && typeof Proxy !== 'undefined') {
        Proxy = undefined;
      }

      function DoubleWeakMap() {
        if (!(this instanceof OurWeakMap)) {  // approximate test for new ...()
          calledAsFunctionWarning();
        }

        // Preferable, truly weak map.
        var hmap = new HostWeakMap();

        // Our hidden-property-based pseudo-weak-map. Lazily initialized in the
        // 'set' implementation; thus we can avoid performing extra lookups if
        // we know all entries actually stored are entered in 'hmap'.
        var omap = undefined;

        // Hidden-property maps are not compatible with proxies because proxies
        // can observe the hidden name and either accidentally expose it or fail
        // to allow the hidden property to be set. Therefore, we do not allow
        // arbitrary WeakMaps to switch to using hidden properties, but only
        // those which need the ability, and unprivileged code is not allowed
        // to set the flag.
        //
        // (Except in doubleWeakMapCheckSilentFailure mode in which case we
        // disable proxies.)
        var enableSwitching = false;

        function dget(key, opt_default) {
          if (omap) {
            return hmap.has(key) ? hmap.get(key)
                : omap.get___(key, opt_default);
          } else {
            return hmap.get(key, opt_default);
          }
        }

        function dhas(key) {
          return hmap.has(key) || (omap ? omap.has___(key) : false);
        }

        var dset;
        if (doubleWeakMapCheckSilentFailure) {
          dset = function(key, value) {
            hmap.set(key, value);
            if (!hmap.has(key)) {
              if (!omap) { omap = new OurWeakMap(); }
              omap.set(key, value);
            }
            return this;
          };
        } else {
          dset = function(key, value) {
            if (enableSwitching) {
              try {
                hmap.set(key, value);
              } catch (e) {
                if (!omap) { omap = new OurWeakMap(); }
                omap.set___(key, value);
              }
            } else {
              hmap.set(key, value);
            }
            return this;
          };
        }

        function ddelete(key) {
          var result = !!hmap['delete'](key);
          if (omap) { return omap.delete___(key) || result; }
          return result;
        }

        return Object.create(OurWeakMap.prototype, {
          get___:    { value: constFunc(dget) },
          has___:    { value: constFunc(dhas) },
          set___:    { value: constFunc(dset) },
          delete___: { value: constFunc(ddelete) },
          permitHostObjects___: { value: constFunc(function(token) {
            if (token === weakMapPermitHostObjects) {
              enableSwitching = true;
            } else {
              throw new Error('bogus call to permitHostObjects___');
            }
          })}
        });
      }
      DoubleWeakMap.prototype = OurWeakMap.prototype;
      module.exports = DoubleWeakMap;

      // define .constructor to hide OurWeakMap ctor
      Object.defineProperty(WeakMap.prototype, 'constructor', {
        value: WeakMap,
        enumerable: false,  // as default .constructor is
        configurable: true,
        writable: true
      });
    })();
  } else {
    // There is no host WeakMap, so we must use the emulation.

    // Emulated WeakMaps are incompatible with native proxies (because proxies
    // can observe the hidden name), so we must disable Proxy usage (in
    // ArrayLike and Domado, currently).
    if (typeof Proxy !== 'undefined') {
      Proxy = undefined;
    }

    module.exports = OurWeakMap;
  }
})();

},{}],531:[function(_dereq_,module,exports){
var hiddenStore = _dereq_('./hidden-store.js');

module.exports = createStore;

function createStore() {
    var key = {};

    return function (obj) {
        if ((typeof obj !== 'object' || obj === null) &&
            typeof obj !== 'function'
        ) {
            throw new Error('Weakmap-shim: Key must be object')
        }

        var store = obj.valueOf(key);
        return store && store.identity === key ?
            store : hiddenStore(obj, key);
    };
}

},{"./hidden-store.js":532}],532:[function(_dereq_,module,exports){
module.exports = hiddenStore;

function hiddenStore(obj, key) {
    var store = { identity: key };
    var valueOf = obj.valueOf;

    Object.defineProperty(obj, "valueOf", {
        value: function (value) {
            return value !== key ?
                valueOf.apply(this, arguments) : store;
        },
        writable: true
    });

    return store;
}

},{}],533:[function(_dereq_,module,exports){
// Original - @Gozola.
// https://gist.github.com/Gozala/1269991
// This is a reimplemented version (with a few bug fixes).

var createStore = _dereq_('./create-store.js');

module.exports = weakMap;

function weakMap() {
    var privates = createStore();

    return {
        'get': function (key, fallback) {
            var store = privates(key)
            return store.hasOwnProperty('value') ?
                store.value : fallback
        },
        'set': function (key, value) {
            privates(key).value = value;
            return this;
        },
        'has': function(key) {
            return 'value' in privates(key);
        },
        'delete': function (key) {
            return delete privates(key).value;
        }
    }
}

},{"./create-store.js":531}],534:[function(_dereq_,module,exports){
var getContext = _dereq_('get-canvas-context')

module.exports = function getWebGLContext (opt) {
  return getContext('webgl', opt)
}

},{"get-canvas-context":222}],535:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Traditional Chinese calendar for jQuery v2.0.2.
   Written by Nicolas Riesco (enquiries@nicolasriesco.net) December 2016.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


var gregorianCalendar = main.instance();

/** Implementation of the traditional Chinese calendar.
    Source of calendar tables https://github.com/isee15/Lunar-Solar-Calendar-Converter .
    @class ChineseCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function ChineseCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

ChineseCalendar.prototype = new main.baseCalendar;

assign(ChineseCalendar.prototype, {
    /** The calendar name.
        @memberof ChineseCalendar */
    name: 'Chinese',
     /** Julian date of start of Gregorian epoch: 1 January 0001 CE.
        @memberof GregorianCalendar */
    jdEpoch: 1721425.5,
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof ChineseCalendar */
    hasYearZero: false,
    /** The minimum month number.
        This calendar uses month indices to account for intercalary months. 
        @memberof ChineseCalendar */
    minMonth: 0,
    /** The first month in the year.
        This calendar uses month indices to account for intercalary months. 
        @memberof ChineseCalendar */
    firstMonth: 0,
    /** The minimum day number.
        @memberof ChineseCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof ChineseCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Chinese',
            epochs: ['BEC', 'EC'],
            monthNumbers: function(date, padded) {
                if (typeof date === 'string') {
                    var match = date.match(MONTH_NUMBER_REGEXP);
                    return (match) ? match[0] : '';
                }

                var year = this._validateYear(date);
                var monthIndex = date.month();

                var month = '' + this.toChineseMonth(year, monthIndex);

                if (padded && month.length < 2) {
                    month = "0" + month;
                }

                if (this.isIntercalaryMonth(year, monthIndex)) {
                    month += 'i';
                }

                return month;
            },
            monthNames: function(date) {
                if (typeof date === 'string') {
                    var match = date.match(MONTH_NAME_REGEXP);
                    return (match) ? match[0] : '';
                }

                var year = this._validateYear(date);
                var monthIndex = date.month();

                var month = this.toChineseMonth(year, monthIndex);

                var monthName = ['一月','二月','三月','四月','五月','六月',
                    '七月','八月','九月','十月','十一月','十二月'][month - 1];

                if (this.isIntercalaryMonth(year, monthIndex)) {
                    monthName = '闰' + monthName;
                }

                return monthName;
            },
            monthNamesShort: function(date) {
                if (typeof date === 'string') {
                    var match = date.match(MONTH_SHORT_NAME_REGEXP);
                    return (match) ? match[0] : '';
                }

                var year = this._validateYear(date);
                var monthIndex = date.month();

                var month = this.toChineseMonth(year, monthIndex);

                var monthName = ['一','二','三','四','五','六',
                    '七','八','九','十','十一','十二'][month - 1];

                if (this.isIntercalaryMonth(year, monthIndex)) {
                    monthName = '闰' + monthName;
                }

                return monthName;
            },
            parseMonth: function(year, monthString) {
                year = this._validateYear(year);
                var month = parseInt(monthString);
                var isIntercalary;

                if (!isNaN(month)) {
                    var i = monthString[monthString.length - 1];
                    isIntercalary = (i === 'i' || i === 'I');
                } else {
                    if (monthString[0] === '闰') {
                        isIntercalary = true;
                        monthString = monthString.substring(1);
                    }
                    if (monthString[monthString.length - 1] === '月') {
                        monthString = monthString.substring(0, monthString.length - 1);
                    }
                    month = 1 +
                        ['一','二','三','四','五','六',
                        '七','八','九','十','十一','十二'].indexOf(monthString);
                }

                var monthIndex = this.toMonthIndex(year, month, isIntercalary);
                return monthIndex;
            },
            dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
            dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
            dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
            digits: null,
            dateFormat: 'yyyy/mm/dd',
            firstDay: 1,
            isRTL: false
        }
    },

    /** Check that a candidate date is from the same calendar and is valid.
        @memberof BaseCalendar
        @private
        @param year {CDate|number} The date or the year to validate.
        @param error {string} Error message if invalid.
        @return {number} The year.
        @throws Error if year out of range. */
    _validateYear: function(year, error) {
        if (year.year) {
            year = year.year();
        }

        if (typeof year !== 'number' || year < 1888 || year > 2111) {
            throw error.replace(/\{0\}/, this.local.name);
        }

        return year;
    },

    /** Retrieve the month index (i.e. accounting for intercalary months).
        @memberof ChineseCalendar
        @param year {number} The year.
        @param month {number} The month (1 for first month).
        @param [isIntercalary=false] {boolean} If month is intercalary.
        @return {number} The month index (0 for first month).
        @throws Error if an invalid month/year or a different calendar used. */
    toMonthIndex: function(year, month, isIntercalary) {
        // compute intercalary month in the year (0 if none)
        var intercalaryMonth = this.intercalaryMonth(year);

        // validate month
        var invalidIntercalaryMonth = 
            (isIntercalary && month !== intercalaryMonth);
        if (invalidIntercalaryMonth || month < 1 || month > 12) {
            throw main.local.invalidMonth
                .replace(/\{0\}/, this.local.name);
        }

        // compute month index
        var monthIndex;

        if (!intercalaryMonth) {
            monthIndex = month - 1;
        } else if(!isIntercalary && month <= intercalaryMonth) {
            monthIndex = month - 1;
        } else {
            monthIndex = month;
        }

        return monthIndex;
    },

    /** Retrieve the month (i.e. accounting for intercalary months).
        @memberof ChineseCalendar
        @param year {CDate|number} The date or the year to examine.
        @param monthIndex {number} The month index (0 for first month).
        @return {number} The month (1 for first month).
        @throws Error if an invalid month/year or a different calendar used. */
    toChineseMonth: function(year, monthIndex) {
        if (year.year) {
            year = year.year();
            monthIndex = year.month();
        }

        // compute intercalary month in the year (0 if none)
        var intercalaryMonth = this.intercalaryMonth(year);

        // validate month
        var maxMonthIndex = (intercalaryMonth) ? 12 : 11;
        if (monthIndex < 0 || monthIndex > maxMonthIndex) {
            throw main.local.invalidMonth
                .replace(/\{0\}/, this.local.name);
        }

        // compute Chinese month
        var month;

        if (!intercalaryMonth) {
            month = monthIndex + 1;
        } else if(monthIndex < intercalaryMonth) {
            month = monthIndex + 1;
        } else {
            month = monthIndex;
        }

        return month;
    },

    /** Determine the intercalary month of a year (if any).
        @memberof ChineseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The intercalary month number, or 0 if none.
        @throws Error if an invalid year or a different calendar used. */
    intercalaryMonth: function(year) {
        year = this._validateYear(year);

        var monthDaysTable = LUNAR_MONTH_DAYS[year - LUNAR_MONTH_DAYS[0]];
        var intercalaryMonth = monthDaysTable >> 13;

        return intercalaryMonth;
    },

    /** Determine whether this date is an intercalary month.
        @memberof ChineseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [monthIndex] {number} The month index to examine.
        @return {boolean} <code>true</code> if this is an intercalary month, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    isIntercalaryMonth: function(year, monthIndex) {
        if (year.year) {
            year = year.year();
            monthIndex = year.month();
        }

        var intercalaryMonth = this.intercalaryMonth(year);

        return !!intercalaryMonth && intercalaryMonth === monthIndex;
    },

    /** Determine whether this date is in a leap year.
        @memberof ChineseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        return (this.intercalaryMonth(year) !== 0);
    },

    /** Determine the week of the year for a date - ISO 8601.
        @memberof ChineseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [monthIndex] {number} The month index to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, monthIndex, day) {
        // compute Chinese new year
        var validatedYear =
            this._validateYear(year, main.local.invalidyear);
        var packedDate =
            CHINESE_NEW_YEAR[validatedYear - CHINESE_NEW_YEAR[0]];

        var y = (packedDate >> 9) & 0xFFF;
        var m = (packedDate >> 5) & 0x0F;
        var d = packedDate & 0x1F;
        
        // find first Thrusday of the year
        var firstThursday;
        firstThursday = gregorianCalendar.newDate(y, m, d);
        firstThursday.add(4 - (firstThursday.dayOfWeek() || 7), 'd');

        // compute days from first Thursday
        var offset =
            this.toJD(year, monthIndex, day) - firstThursday.toJD();
        return 1 + Math.floor(offset / 7);
    },

    /** Retrieve the number of months in a year.
        @memberof ChineseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of months.
        @throws Error if an invalid year or a different calendar used. */
    monthsInYear: function(year) {
        return (this.leapYear(year)) ? 13 : 12;
    },

    /** Retrieve the number of days in a month.
        @memberof ChineseCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [monthIndex] {number} The month index.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, monthIndex) {
        if (year.year) {
            monthIndex = year.month();
            year = year.year();
        }

        year = this._validateYear(year);

        var monthDaysTable = LUNAR_MONTH_DAYS[year - LUNAR_MONTH_DAYS[0]];

        var intercalaryMonth = monthDaysTable >> 13;
        var maxMonthIndex = (intercalaryMonth) ? 12 : 11;
        if (monthIndex > maxMonthIndex) {
            throw main.local.invalidMonth
                .replace(/\{0\}/, this.local.name);
        }

        var daysInMonth = (monthDaysTable & (1 << (12 - monthIndex))) ?
            30 : 29;

        return daysInMonth;
    },

    /** Determine whether this date is a week day.
        @memberof ChineseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [monthIndex] {number} The month index to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, monthIndex, day) {
        return (this.dayOfWeek(year, monthIndex, day) || 7) < 6;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof ChineseCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [monthIndex] {number} The month index to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, monthIndex, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        year = this._validateYear(date.year());
        monthIndex = date.month();
        day = date.day();

        var isIntercalary = this.isIntercalaryMonth(year, monthIndex);
        var month = this.toChineseMonth(year, monthIndex);

        var solar = toSolar(year, month, day, isIntercalary);

        return gregorianCalendar.toJD(solar.year, solar.month, solar.day);
    },

    /** Create a new date from a Julian date.
        @memberof ChineseCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        var date = gregorianCalendar.fromJD(jd);
        var lunar = toLunar(date.year(), date.month(), date.day());
        var monthIndex = this.toMonthIndex(
            lunar.year, lunar.month, lunar.isIntercalary);
        return this.newDate(lunar.year, monthIndex, lunar.day);
    },

    /** Create a new date from a string.
        @memberof ChineseCalendar
        @param dateString {string} String representing a Chinese date
        @return {CDate} The new date.
        @throws Error if an invalid date. */
    fromString: function(dateString) {
        var match = dateString.match(DATE_REGEXP);

        var year = this._validateYear(+match[1]);

        var month = +match[2];
        var isIntercalary = !!match[3];
        var monthIndex = this.toMonthIndex(year, month, isIntercalary);

        var day = +match[4];

        return this.newDate(year, monthIndex, day);
    },

    /** Add period(s) to a date.
        Cater for no year zero.
        @memberof ChineseCalendar
        @param date {CDate} The starting date.
        @param offset {number} The number of periods to adjust by.
        @param period {string} One of 'y' for year, 'm' for month, 'w' for week, 'd' for day.
        @return {CDate} The updated date.
        @throws Error if a different calendar used. */
    add: function(date, offset, period) {
        var year = date.year();
        var monthIndex = date.month();
        var isIntercalary = this.isIntercalaryMonth(year, monthIndex);
        var month = this.toChineseMonth(year, monthIndex);

        var cdate = Object.getPrototypeOf(ChineseCalendar.prototype)
            .add.call(this, date, offset, period);

        if (period === 'y') {
            // Resync month
            var resultYear = cdate.year();
            var resultMonthIndex = cdate.month();

            // Using the fact the month index of an intercalary month
            // equals its month number:
            var resultCanBeIntercalaryMonth =
                this.isIntercalaryMonth(resultYear, month);

            var correctedMonthIndex =
                (isIntercalary && resultCanBeIntercalaryMonth) ?
                this.toMonthIndex(resultYear, month, true) :
                this.toMonthIndex(resultYear, month, false);

            if (correctedMonthIndex !== resultMonthIndex) {
                cdate.month(correctedMonthIndex);
            }
        }

        return cdate;
    },
});

// Used by ChineseCalendar.prototype.fromString
var DATE_REGEXP = /^\s*(-?\d\d\d\d|\d\d)[-/](\d?\d)([iI]?)[-/](\d?\d)/m;
var MONTH_NUMBER_REGEXP = /^\d?\d[iI]?/m;
var MONTH_NAME_REGEXP = /^闰?十?[一二三四五六七八九]?月/m;
var MONTH_SHORT_NAME_REGEXP = /^闰?十?[一二三四五六七八九]?/m;

// Chinese calendar implementation
main.calendars.chinese = ChineseCalendar;

// Chinese calendar tables from year 1888 to 2111
//
// Source:
// https://github.com/isee15/Lunar-Solar-Calendar-Converter.git

// Table of intercalary months and days per month from year 1888 to 2111
//
// bit (12 - i):        days in the i^th month
//                      (= 0 if i^th lunar month has 29 days)
//                      (= 1 if i^th lunar month has 30 days)
//                      (first month in lunar year is i = 0)
// bits (13,14,15,16):  intercalary month
//                      (= 0 if lunar year has no intercalary month)
var LUNAR_MONTH_DAYS = [1887, 0x1694, 0x16aa, 0x4ad5,
    0xab6, 0xc4b7, 0x4ae, 0xa56, 0xb52a, 0x1d2a, 0xd54, 0x75aa, 0x156a,
    0x1096d, 0x95c, 0x14ae, 0xaa4d, 0x1a4c, 0x1b2a, 0x8d55, 0xad4,
    0x135a, 0x495d, 0x95c, 0xd49b, 0x149a, 0x1a4a, 0xbaa5, 0x16a8,
    0x1ad4, 0x52da, 0x12b6, 0xe937, 0x92e, 0x1496, 0xb64b, 0xd4a,
    0xda8, 0x95b5, 0x56c, 0x12ae, 0x492f, 0x92e, 0xcc96, 0x1a94,
    0x1d4a, 0xada9, 0xb5a, 0x56c, 0x726e, 0x125c, 0xf92d, 0x192a,
    0x1a94, 0xdb4a, 0x16aa, 0xad4, 0x955b, 0x4ba, 0x125a, 0x592b,
    0x152a, 0xf695, 0xd94, 0x16aa, 0xaab5, 0x9b4, 0x14b6, 0x6a57,
    0xa56, 0x1152a, 0x1d2a, 0xd54, 0xd5aa, 0x156a, 0x96c, 0x94ae,
    0x14ae, 0xa4c, 0x7d26, 0x1b2a, 0xeb55, 0xad4, 0x12da, 0xa95d,
    0x95a, 0x149a, 0x9a4d, 0x1a4a, 0x11aa5, 0x16a8, 0x16d4, 0xd2da,
    0x12b6, 0x936, 0x9497, 0x1496, 0x1564b, 0xd4a, 0xda8, 0xd5b4,
    0x156c, 0x12ae, 0xa92f, 0x92e, 0xc96, 0x6d4a, 0x1d4a, 0x10d65,
    0xb58, 0x156c, 0xb26d, 0x125c, 0x192c, 0x9a95, 0x1a94, 0x1b4a,
    0x4b55, 0xad4, 0xf55b, 0x4ba, 0x125a, 0xb92b, 0x152a, 0x1694,
    0x96aa, 0x15aa, 0x12ab5, 0x974, 0x14b6, 0xca57, 0xa56, 0x1526,
    0x8e95, 0xd54, 0x15aa, 0x49b5, 0x96c, 0xd4ae, 0x149c, 0x1a4c,
    0xbd26, 0x1aa6, 0xb54, 0x6d6a, 0x12da, 0x1695d, 0x95a, 0x149a,
    0xda4b, 0x1a4a, 0x1aa4, 0xbb54, 0x16b4, 0xada, 0x495b, 0x936,
    0xf497, 0x1496, 0x154a, 0xb6a5, 0xda4, 0x15b4, 0x6ab6, 0x126e,
    0x1092f, 0x92e, 0xc96, 0xcd4a, 0x1d4a, 0xd64, 0x956c, 0x155c,
    0x125c, 0x792e, 0x192c, 0xfa95, 0x1a94, 0x1b4a, 0xab55, 0xad4,
    0x14da, 0x8a5d, 0xa5a, 0x1152b, 0x152a, 0x1694, 0xd6aa, 0x15aa,
    0xab4, 0x94ba, 0x14b6, 0xa56, 0x7527, 0xd26, 0xee53, 0xd54, 0x15aa,
    0xa9b5, 0x96c, 0x14ae, 0x8a4e, 0x1a4c, 0x11d26, 0x1aa4, 0x1b54,
    0xcd6a, 0xada, 0x95c, 0x949d, 0x149a, 0x1a2a, 0x5b25, 0x1aa4,
    0xfb52, 0x16b4, 0xaba, 0xa95b, 0x936, 0x1496, 0x9a4b, 0x154a,
    0x136a5, 0xda4, 0x15ac];

// Table of Chinese New Years from year 1888 to 2111
// 
// bits (0 to 4):   solar day
// bits (5 to 8):   solar month
// bits (9 to 20):  solar year
var CHINESE_NEW_YEAR = [1887, 0xec04c, 0xec23f, 0xec435, 0xec649,
    0xec83e, 0xeca51, 0xecc46, 0xece3a, 0xed04d, 0xed242, 0xed436,
    0xed64a, 0xed83f, 0xeda53, 0xedc48, 0xede3d, 0xee050, 0xee244,
    0xee439, 0xee64d, 0xee842, 0xeea36, 0xeec4a, 0xeee3e, 0xef052,
    0xef246, 0xef43a, 0xef64e, 0xef843, 0xefa37, 0xefc4b, 0xefe41,
    0xf0054, 0xf0248, 0xf043c, 0xf0650, 0xf0845, 0xf0a38, 0xf0c4d,
    0xf0e42, 0xf1037, 0xf124a, 0xf143e, 0xf1651, 0xf1846, 0xf1a3a,
    0xf1c4e, 0xf1e44, 0xf2038, 0xf224b, 0xf243f, 0xf2653, 0xf2848,
    0xf2a3b, 0xf2c4f, 0xf2e45, 0xf3039, 0xf324d, 0xf3442, 0xf3636,
    0xf384a, 0xf3a3d, 0xf3c51, 0xf3e46, 0xf403b, 0xf424e, 0xf4443,
    0xf4638, 0xf484c, 0xf4a3f, 0xf4c52, 0xf4e48, 0xf503c, 0xf524f,
    0xf5445, 0xf5639, 0xf584d, 0xf5a42, 0xf5c35, 0xf5e49, 0xf603e,
    0xf6251, 0xf6446, 0xf663b, 0xf684f, 0xf6a43, 0xf6c37, 0xf6e4b,
    0xf703f, 0xf7252, 0xf7447, 0xf763c, 0xf7850, 0xf7a45, 0xf7c39,
    0xf7e4d, 0xf8042, 0xf8254, 0xf8449, 0xf863d, 0xf8851, 0xf8a46,
    0xf8c3b, 0xf8e4f, 0xf9044, 0xf9237, 0xf944a, 0xf963f, 0xf9853,
    0xf9a47, 0xf9c3c, 0xf9e50, 0xfa045, 0xfa238, 0xfa44c, 0xfa641,
    0xfa836, 0xfaa49, 0xfac3d, 0xfae52, 0xfb047, 0xfb23a, 0xfb44e,
    0xfb643, 0xfb837, 0xfba4a, 0xfbc3f, 0xfbe53, 0xfc048, 0xfc23c,
    0xfc450, 0xfc645, 0xfc839, 0xfca4c, 0xfcc41, 0xfce36, 0xfd04a,
    0xfd23d, 0xfd451, 0xfd646, 0xfd83a, 0xfda4d, 0xfdc43, 0xfde37,
    0xfe04b, 0xfe23f, 0xfe453, 0xfe648, 0xfe83c, 0xfea4f, 0xfec44,
    0xfee38, 0xff04c, 0xff241, 0xff436, 0xff64a, 0xff83e, 0xffa51,
    0xffc46, 0xffe3a, 0x10004e, 0x100242, 0x100437, 0x10064b, 0x100841,
    0x100a53, 0x100c48, 0x100e3c, 0x10104f, 0x101244, 0x101438,
    0x10164c, 0x101842, 0x101a35, 0x101c49, 0x101e3d, 0x102051,
    0x102245, 0x10243a, 0x10264e, 0x102843, 0x102a37, 0x102c4b,
    0x102e3f, 0x103053, 0x103247, 0x10343b, 0x10364f, 0x103845,
    0x103a38, 0x103c4c, 0x103e42, 0x104036, 0x104249, 0x10443d,
    0x104651, 0x104846, 0x104a3a, 0x104c4e, 0x104e43, 0x105038,
    0x10524a, 0x10543e, 0x105652, 0x105847, 0x105a3b, 0x105c4f,
    0x105e45, 0x106039, 0x10624c, 0x106441, 0x106635, 0x106849,
    0x106a3d, 0x106c51, 0x106e47, 0x10703c, 0x10724f, 0x107444,
    0x107638, 0x10784c, 0x107a3f, 0x107c53, 0x107e48];

function toLunar(yearOrDate, monthOrResult, day, result) {
    var solarDate;
    var lunarDate;

    if(typeof yearOrDate === 'object') {
        solarDate = yearOrDate;
        lunarDate = monthOrResult || {};

    } else {
        var isValidYear = (typeof yearOrDate === 'number') &&
            (yearOrDate >= 1888) && (yearOrDate <= 2111);
        if(!isValidYear)
            throw new Error("Solar year outside range 1888-2111");

        var isValidMonth = (typeof monthOrResult === 'number') &&
            (monthOrResult >= 1) && (monthOrResult <= 12);
        if(!isValidMonth)
            throw new Error("Solar month outside range 1 - 12");

        var isValidDay = (typeof day === 'number') && (day >= 1) && (day <= 31);
        if(!isValidDay)
            throw new Error("Solar day outside range 1 - 31");

        solarDate = {
            year: yearOrDate,
            month: monthOrResult,
            day: day,
        };
        lunarDate = result || {};
    }

    // Compute Chinese new year and lunar year
    var chineseNewYearPackedDate =
        CHINESE_NEW_YEAR[solarDate.year - CHINESE_NEW_YEAR[0]];

    var packedDate = (solarDate.year << 9) | (solarDate.month << 5)
        | solarDate.day;

    lunarDate.year = (packedDate >= chineseNewYearPackedDate) ?
        solarDate.year :
        solarDate.year - 1;

    chineseNewYearPackedDate =
        CHINESE_NEW_YEAR[lunarDate.year - CHINESE_NEW_YEAR[0]];

    var y = (chineseNewYearPackedDate >> 9) & 0xFFF;
    var m = (chineseNewYearPackedDate >> 5) & 0x0F;
    var d = chineseNewYearPackedDate & 0x1F;

    // Compute days from new year
    var daysFromNewYear;

    var chineseNewYearJSDate = new Date(y, m -1, d);
    var jsDate = new Date(solarDate.year, solarDate.month - 1, solarDate.day);

    daysFromNewYear = Math.round(
        (jsDate - chineseNewYearJSDate) / (24 * 3600 * 1000));

    // Compute lunar month and day
    var monthDaysTable = LUNAR_MONTH_DAYS[lunarDate.year - LUNAR_MONTH_DAYS[0]];

    var i;
    for(i = 0; i < 13; i++) {
        var daysInMonth = (monthDaysTable & (1 << (12 - i))) ? 30 : 29;

        if (daysFromNewYear < daysInMonth) {
            break;
        }

        daysFromNewYear -= daysInMonth;
    }

    var intercalaryMonth = monthDaysTable >> 13;
    if (!intercalaryMonth || i < intercalaryMonth) {
        lunarDate.isIntercalary = false;
        lunarDate.month = 1 + i;
    } else if (i === intercalaryMonth) {
        lunarDate.isIntercalary = true;
        lunarDate.month = i;
    } else {
        lunarDate.isIntercalary = false;
        lunarDate.month = i;
    }

    lunarDate.day = 1 + daysFromNewYear;

    return lunarDate;
}

function toSolar(yearOrDate, monthOrResult, day, isIntercalaryOrResult, result) {
    var solarDate;
    var lunarDate;

    if(typeof yearOrDate === 'object') {
        lunarDate = yearOrDate;
        solarDate = monthOrResult || {};

    } else {
        var isValidYear = (typeof yearOrDate === 'number') &&
            (yearOrDate >= 1888) && (yearOrDate <= 2111);
        if(!isValidYear)
            throw new Error("Lunar year outside range 1888-2111");

        var isValidMonth = (typeof monthOrResult === 'number') &&
            (monthOrResult >= 1) && (monthOrResult <= 12);
        if(!isValidMonth)
            throw new Error("Lunar month outside range 1 - 12");

        var isValidDay = (typeof day === 'number') && (day >= 1) && (day <= 30);
        if(!isValidDay)
            throw new Error("Lunar day outside range 1 - 30");

        var isIntercalary;
        if(typeof isIntercalaryOrResult === 'object') {
            isIntercalary = false;
            solarDate = isIntercalaryOrResult;
        } else {
            isIntercalary = !!isIntercalaryOrResult;
            solarDate = result || {};
        }

        lunarDate = {
            year: yearOrDate,
            month: monthOrResult,
            day: day,
            isIntercalary: isIntercalary,
        };
    }

    // Compute days from new year
    var daysFromNewYear;

    daysFromNewYear = lunarDate.day - 1;

    var monthDaysTable = LUNAR_MONTH_DAYS[lunarDate.year - LUNAR_MONTH_DAYS[0]];
    var intercalaryMonth = monthDaysTable >> 13;

    var monthsFromNewYear;
    if (!intercalaryMonth) {
        monthsFromNewYear = lunarDate.month - 1;
    } else if (lunarDate.month > intercalaryMonth) {
        monthsFromNewYear = lunarDate.month;
    } else if (lunarDate.isIntercalary) {
        monthsFromNewYear = lunarDate.month;
    } else {
        monthsFromNewYear = lunarDate.month - 1;
    }

    for(var i = 0; i < monthsFromNewYear; i++) {
        var daysInMonth = (monthDaysTable & (1 << (12 - i))) ? 30 : 29;
        daysFromNewYear += daysInMonth;
    }

    // Compute Chinese new year
    var packedDate = CHINESE_NEW_YEAR[lunarDate.year - CHINESE_NEW_YEAR[0]];

    var y = (packedDate >> 9) & 0xFFF;
    var m = (packedDate >> 5) & 0x0F;
    var d = packedDate & 0x1F;

    // Compute solar date
    var jsDate = new Date(y, m - 1, d + daysFromNewYear);

    solarDate.year = jsDate.getFullYear();
    solarDate.month = 1 + jsDate.getMonth();
    solarDate.day = jsDate.getDate();

    return solarDate;
}


},{"../main":549,"object-assign":440}],536:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Coptic calendar for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) February 2010.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


/** Implementation of the Coptic calendar.
    See <a href="http://en.wikipedia.org/wiki/Coptic_calendar">http://en.wikipedia.org/wiki/Coptic_calendar</a>.
    See also Calendrical Calculations: The Millennium Edition
    (<a href="http://emr.cs.iit.edu/home/reingold/calendar-book/index.shtml">http://emr.cs.iit.edu/home/reingold/calendar-book/index.shtml</a>).
    @class CopticCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function CopticCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

CopticCalendar.prototype = new main.baseCalendar;

assign(CopticCalendar.prototype, {
    /** The calendar name.
        @memberof CopticCalendar */
    name: 'Coptic',
    /** Julian date of start of Coptic epoch: 29 August 284 CE (Gregorian).
        @memberof CopticCalendar */
    jdEpoch: 1825029.5,
    /** Days per month in a common year.
        @memberof CopticCalendar */
    daysPerMonth: [30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 5],
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof CopticCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof CopticCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof CopticCalendar */
    firstMonth: 1,
    /** The minimum day number.
        @memberof CopticCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof CopticCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Coptic',
            epochs: ['BAM', 'AM'],
            monthNames: ['Thout', 'Paopi', 'Hathor', 'Koiak', 'Tobi', 'Meshir',
            'Paremhat', 'Paremoude', 'Pashons', 'Paoni', 'Epip', 'Mesori', 'Pi Kogi Enavot'],
            monthNamesShort: ['Tho', 'Pao', 'Hath', 'Koi', 'Tob', 'Mesh',
            'Pat', 'Pad', 'Pash', 'Pao', 'Epi', 'Meso', 'PiK'],
            dayNames: ['Tkyriaka', 'Pesnau', 'Pshoment', 'Peftoou', 'Ptiou', 'Psoou', 'Psabbaton'],
            dayNamesShort: ['Tky', 'Pes', 'Psh', 'Pef', 'Pti', 'Pso', 'Psa'],
            dayNamesMin: ['Tk', 'Pes', 'Psh', 'Pef', 'Pt', 'Pso', 'Psa'],
            digits: null,
            dateFormat: 'dd/mm/yyyy',
            firstDay: 0,
            isRTL: false
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof CopticCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        var year = date.year() + (date.year() < 0 ? 1 : 0); // No year zero
        return year % 4 === 3 || year % 4 === -1;
    },

    /** Retrieve the number of months in a year.
        @memberof CopticCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of months.
        @throws Error if an invalid year or a different calendar used. */
    monthsInYear: function(year) {
        this._validate(year, this.minMonth, this.minDay,
            main.local.invalidYear || main.regionalOptions[''].invalidYear);
        return 13;
    },

    /** Determine the week of the year for a date.
        @memberof CopticCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number) the month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        // Find Sunday of this week starting on Sunday
        var checkDate = this.newDate(year, month, day);
        checkDate.add(-checkDate.dayOfWeek(), 'd');
        return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
    },

    /** Retrieve the number of days in a month.
        @memberof CopticCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
        return this.daysPerMonth[date.month() - 1] +
            (date.month() === 13 && this.leapYear(date.year()) ? 1 : 0);
    },

    /** Determine whether this date is a week day.
        @memberof CopticCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param month {number} The month to examine.
        @param day {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        return (this.dayOfWeek(year, month, day) || 7) < 6;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof CopticCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number) the month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        year = date.year();
        if (year < 0) { year++; } // No year zero
        return date.day() + (date.month() - 1) * 30 +
            (year - 1) * 365 + Math.floor(year / 4) + this.jdEpoch - 1;
    },

    /** Create a new date from a Julian date.
        @memberof CopticCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        var c = Math.floor(jd) + 0.5 - this.jdEpoch;
        var year = Math.floor((c - Math.floor((c + 366) / 1461)) / 365) + 1;
        if (year <= 0) { year--; } // No year zero
        c = Math.floor(jd) + 0.5 - this.newDate(year, 1, 1).toJD();
        var month = Math.floor(c / 30) + 1;
        var day = c - (month - 1) * 30 + 1;
        return this.newDate(year, month, day);
    }
});

// Coptic calendar implementation
main.calendars.coptic = CopticCalendar;


},{"../main":549,"object-assign":440}],537:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Discworld calendar for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) January 2016.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


/** Implementation of the Discworld calendar - Unseen University version.
    See also <a href="http://wiki.lspace.org/mediawiki/Discworld_calendar">http://wiki.lspace.org/mediawiki/Discworld_calendar</a>
    and <a href="http://discworld.wikia.com/wiki/Discworld_calendar">http://discworld.wikia.com/wiki/Discworld_calendar</a>.
    @class DiscworldCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function DiscworldCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

DiscworldCalendar.prototype = new main.baseCalendar;

assign(DiscworldCalendar.prototype, {
    /** The calendar name.
        @memberof DiscworldCalendar */
    name: 'Discworld',
    /** Julian date of start of Discworld epoch: 1 January 0001 CE.
        @memberof DiscworldCalendar */
    jdEpoch: 1721425.5,
    /** Days per month in a common year.
        @memberof DiscworldCalendar */
    daysPerMonth: [16, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32],
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof DiscworldCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof DiscworldCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof DiscworldCalendar */
    firstMonth: 1,
    /** The minimum day number.
        @memberof DiscworldCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof DiscworldCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Discworld',
            epochs: ['BUC', 'UC'],
            monthNames: ['Ick', 'Offle', 'February', 'March', 'April', 'May', 'June',
            'Grune', 'August', 'Spune', 'Sektober', 'Ember', 'December'],
            monthNamesShort: ['Ick', 'Off', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Gru', 'Aug', 'Spu', 'Sek', 'Emb', 'Dec'],
            dayNames: ['Sunday', 'Octeday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
            dayNamesShort: ['Sun', 'Oct', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
            dayNamesMin: ['Su', 'Oc', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
            digits: null,
            dateFormat: 'yyyy/mm/dd',
            firstDay: 2,
            isRTL: false
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof DiscworldCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        return false;
    },

    /** Retrieve the number of months in a year.
        @memberof DiscworldCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of months.
        @throws Error if an invalid year or a different calendar used. */
    monthsInYear: function(year) {
        this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        return 13;
    },

    /** Retrieve the number of days in a year.
        @memberof DiscworldCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of days.
        @throws Error if an invalid year or a different calendar used. */
    daysInYear: function(year) {
        this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        return 400;
    },

    /** Determine the week of the year for a date.
        @memberof DiscworldCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        // Find Sunday of this week starting on Sunday
        var checkDate = this.newDate(year, month, day);
        checkDate.add(-checkDate.dayOfWeek(), 'd');
        return Math.floor((checkDate.dayOfYear() - 1) / 8) + 1;
    },

    /** Retrieve the number of days in a month.
        @memberof DiscworldCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
        return this.daysPerMonth[date.month() - 1];
    },

    /** Retrieve the number of days in a week.
        @memberof DiscworldCalendar
        @return {number} The number of days. */
    daysInWeek: function() {
        return 8;
    },

    /** Retrieve the day of the week for a date.
        @memberof DiscworldCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The day of the week: 0 to number of days - 1.
        @throws Error if an invalid date or a different calendar used. */
    dayOfWeek: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        return (date.day() + 1) % 8;
    },

    /** Determine whether this date is a week day.
        @memberof DiscworldCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        var dow = this.dayOfWeek(year, month, day);
        return (dow >= 2 && dow <= 6);
    },

    /** Retrieve additional information about a date.
        @memberof DiscworldCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {object} Additional information - contents depends on calendar.
        @throws Error if an invalid date or a different calendar used. */
    extraInfo: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        return {century: centuries[Math.floor((date.year() - 1) / 100) + 1] || ''};
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof DiscworldCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        year = date.year() + (date.year() < 0 ? 1 : 0);
        month = date.month();
        day = date.day();
        return day + (month > 1 ? 16 : 0) + (month > 2 ? (month - 2) * 32 : 0) +
            (year - 1) * 400 + this.jdEpoch - 1;
    },

    /** Create a new date from a Julian date.
        @memberof DiscworldCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        jd = Math.floor(jd + 0.5) - Math.floor(this.jdEpoch) - 1;
        var year = Math.floor(jd / 400) + 1;
        jd -= (year - 1) * 400;
        jd += (jd > 15 ? 16 : 0);
        var month = Math.floor(jd / 32) + 1;
        var day = jd - (month - 1) * 32 + 1;
        return this.newDate(year <= 0 ? year - 1 : year, month, day);
    }
});

// Names of the centuries
var centuries = {
    20: 'Fruitbat',
    21: 'Anchovy'
};

// Discworld calendar implementation
main.calendars.discworld = DiscworldCalendar;


},{"../main":549,"object-assign":440}],538:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Ethiopian calendar for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) February 2010.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


/** Implementation of the Ethiopian calendar.
    See <a href="http://en.wikipedia.org/wiki/Ethiopian_calendar">http://en.wikipedia.org/wiki/Ethiopian_calendar</a>.
    See also Calendrical Calculations: The Millennium Edition
    (<a href="http://emr.cs.iit.edu/home/reingold/calendar-book/index.shtml">http://emr.cs.iit.edu/home/reingold/calendar-book/index.shtml</a>).
    @class EthiopianCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function EthiopianCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

EthiopianCalendar.prototype = new main.baseCalendar;

assign(EthiopianCalendar.prototype, {
    /** The calendar name.
        @memberof EthiopianCalendar */
    name: 'Ethiopian',
    /** Julian date of start of Ethiopian epoch: 27 August 8 CE (Gregorian).
        @memberof EthiopianCalendar */
    jdEpoch: 1724220.5,
    /** Days per month in a common year.
        @memberof EthiopianCalendar */
    daysPerMonth: [30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 5],
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof EthiopianCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof EthiopianCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof EthiopianCalendar */
    firstMonth: 1,
    /** The minimum day number.
        @memberof EthiopianCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof EthiopianCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Ethiopian',
            epochs: ['BEE', 'EE'],
            monthNames: ['Meskerem', 'Tikemet', 'Hidar', 'Tahesas', 'Tir', 'Yekatit',
            'Megabit', 'Miazia', 'Genbot', 'Sene', 'Hamle', 'Nehase', 'Pagume'],
            monthNamesShort: ['Mes', 'Tik', 'Hid', 'Tah', 'Tir', 'Yek',
            'Meg', 'Mia', 'Gen', 'Sen', 'Ham', 'Neh', 'Pag'],
            dayNames: ['Ehud', 'Segno', 'Maksegno', 'Irob', 'Hamus', 'Arb', 'Kidame'],
            dayNamesShort: ['Ehu', 'Seg', 'Mak', 'Iro', 'Ham', 'Arb', 'Kid'],
            dayNamesMin: ['Eh', 'Se', 'Ma', 'Ir', 'Ha', 'Ar', 'Ki'],
            digits: null,
            dateFormat: 'dd/mm/yyyy',
            firstDay: 0,
            isRTL: false
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof EthiopianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        var year = date.year() + (date.year() < 0 ? 1 : 0); // No year zero
        return year % 4 === 3 || year % 4 === -1;
    },

    /** Retrieve the number of months in a year.
        @memberof EthiopianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of months.
        @throws Error if an invalid year or a different calendar used. */
    monthsInYear: function(year) {
        this._validate(year, this.minMonth, this.minDay,
            main.local.invalidYear || main.regionalOptions[''].invalidYear);
        return 13;
    },

    /** Determine the week of the year for a date.
        @memberof EthiopianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        // Find Sunday of this week starting on Sunday
        var checkDate = this.newDate(year, month, day);
        checkDate.add(-checkDate.dayOfWeek(), 'd');
        return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
    },

    /** Retrieve the number of days in a month.
        @memberof EthiopianCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
        return this.daysPerMonth[date.month() - 1] +
            (date.month() === 13 && this.leapYear(date.year()) ? 1 : 0);
    },

    /** Determine whether this date is a week day.
        @memberof EthiopianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        return (this.dayOfWeek(year, month, day) || 7) < 6;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof EthiopianCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        year = date.year();
        if (year < 0) { year++; } // No year zero
        return date.day() + (date.month() - 1) * 30 +
            (year - 1) * 365 + Math.floor(year / 4) + this.jdEpoch - 1;
    },

    /** Create a new date from a Julian date.
        @memberof EthiopianCalendar
        @param jd {number} the Julian date to convert.
        @return {CDate} the equivalent date. */
    fromJD: function(jd) {
        var c = Math.floor(jd) + 0.5 - this.jdEpoch;
        var year = Math.floor((c - Math.floor((c + 366) / 1461)) / 365) + 1;
        if (year <= 0) { year--; } // No year zero
        c = Math.floor(jd) + 0.5 - this.newDate(year, 1, 1).toJD();
        var month = Math.floor(c / 30) + 1;
        var day = c - (month - 1) * 30 + 1;
        return this.newDate(year, month, day);
    }
});

// Ethiopian calendar implementation
main.calendars.ethiopian = EthiopianCalendar;


},{"../main":549,"object-assign":440}],539:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Hebrew calendar for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) August 2009.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


/** Implementation of the Hebrew civil calendar.
    Based on code from <a href="http://www.fourmilab.ch/documents/calendar/">http://www.fourmilab.ch/documents/calendar/</a>.
    See also <a href="http://en.wikipedia.org/wiki/Hebrew_calendar">http://en.wikipedia.org/wiki/Hebrew_calendar</a>.
    @class HebrewCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function HebrewCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

HebrewCalendar.prototype = new main.baseCalendar;

assign(HebrewCalendar.prototype, {
    /** The calendar name.
        @memberof HebrewCalendar */
    name: 'Hebrew',
    /** Julian date of start of Hebrew epoch: 7 October 3761 BCE.
        @memberof HebrewCalendar */
    jdEpoch: 347995.5,
    /** Days per month in a common year.
        @memberof HebrewCalendar */
    daysPerMonth: [30, 29, 30, 29, 30, 29, 30, 29, 30, 29, 30, 29, 29],
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof HebrewCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof HebrewCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof HebrewCalendar */
    firstMonth: 7,
    /** The minimum day number.
        @memberof HebrewCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof HebrewCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Hebrew',
            epochs: ['BAM', 'AM'],
            monthNames: ['Nisan', 'Iyar', 'Sivan', 'Tammuz', 'Av', 'Elul',
            'Tishrei', 'Cheshvan', 'Kislev', 'Tevet', 'Shevat', 'Adar', 'Adar II'],
            monthNamesShort: ['Nis', 'Iya', 'Siv', 'Tam', 'Av', 'Elu', 'Tis', 'Che', 'Kis', 'Tev', 'She', 'Ada', 'Ad2'],
            dayNames: ['Yom Rishon', 'Yom Sheni', 'Yom Shlishi', 'Yom Revi\'i', 'Yom Chamishi', 'Yom Shishi', 'Yom Shabbat'],
            dayNamesShort: ['Ris', 'She', 'Shl', 'Rev', 'Cha', 'Shi', 'Sha'],
            dayNamesMin: ['Ri','She','Shl','Re','Ch','Shi','Sha'],
            digits: null,
            dateFormat: 'dd/mm/yyyy',
            firstDay: 0,
            isRTL: false
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof HebrewCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        return this._leapYear(date.year());
    },

    /** Determine whether this date is in a leap year.
        @memberof HebrewCalendar
        @private
        @param year {number} The year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    _leapYear: function(year) {
        year = (year < 0 ? year + 1 : year);
        return mod(year * 7 + 1, 19) < 7;
    },

    /** Retrieve the number of months in a year.
        @memberof HebrewCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of months.
        @throws Error if an invalid year or a different calendar used. */
    monthsInYear: function(year) {
        this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        return this._leapYear(year.year ? year.year() : year) ? 13 : 12;
    },

    /** Determine the week of the year for a date.
        @memberof HebrewCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        // Find Sunday of this week starting on Sunday
        var checkDate = this.newDate(year, month, day);
        checkDate.add(-checkDate.dayOfWeek(), 'd');
        return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
    },

    /** Retrieve the number of days in a year.
        @memberof HebrewCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of days.
        @throws Error if an invalid year or a different calendar used. */
    daysInYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        year = date.year();
        return this.toJD((year === -1 ? +1 : year + 1), 7, 1) - this.toJD(year, 7, 1);
    },

    /** Retrieve the number of days in a month.
        @memberof HebrewCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        if (year.year) {
            month = year.month();
            year = year.year();
        }
        this._validate(year, month, this.minDay, main.local.invalidMonth);
        return (month === 12 && this.leapYear(year) ? 30 : // Adar I
                (month === 8 && mod(this.daysInYear(year), 10) === 5 ? 30 : // Cheshvan in shlemah year
                (month === 9 && mod(this.daysInYear(year), 10) === 3 ? 29 : // Kislev in chaserah year
                this.daysPerMonth[month - 1])));
    },

    /** Determine whether this date is a week day.
        @memberof HebrewCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        return this.dayOfWeek(year, month, day) !== 6;
    },

    /** Retrieve additional information about a date - year type.
        @memberof HebrewCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {object} Additional information - contents depends on calendar.
        @throws Error if an invalid date or a different calendar used. */
    extraInfo: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        return {yearType: (this.leapYear(date) ? 'embolismic' : 'common') + ' ' +
            ['deficient', 'regular', 'complete'][this.daysInYear(date) % 10 - 3]};
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof HebrewCalendar
        @param year {CDate)|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        year = date.year();
        month = date.month();
        day = date.day();
        var adjYear = (year <= 0 ? year + 1 : year);
        var jd = this.jdEpoch + this._delay1(adjYear) +
            this._delay2(adjYear) + day + 1;
        if (month < 7) {
            for (var m = 7; m <= this.monthsInYear(year); m++) {
                jd += this.daysInMonth(year, m);
            }
            for (var m = 1; m < month; m++) {
                jd += this.daysInMonth(year, m);
            }
        }
        else {
            for (var m = 7; m < month; m++) {
                jd += this.daysInMonth(year, m);
            }
        }
        return jd;
    },

    /** Test for delay of start of new year and to avoid
        Sunday, Wednesday, or Friday as start of the new year.
        @memberof HebrewCalendar
        @private
        @param year {number} The year to examine.
        @return {number} The days to offset by. */
    _delay1: function(year) {
        var months = Math.floor((235 * year - 234) / 19);
        var parts = 12084 + 13753 * months;
        var day = months * 29 + Math.floor(parts / 25920);
        if (mod(3 * (day + 1), 7) < 3) {
            day++;
        }
        return day;
    },

    /** Check for delay in start of new year due to length of adjacent years.
        @memberof HebrewCalendar
        @private
        @param year {number} The year to examine.
        @return {number} The days to offset by. */
    _delay2: function(year) {
        var last = this._delay1(year - 1);
        var present = this._delay1(year);
        var next = this._delay1(year + 1);
        return ((next - present) === 356 ? 2 : ((present - last) === 382 ? 1 : 0));
    },

    /** Create a new date from a Julian date.
        @memberof HebrewCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        jd = Math.floor(jd) + 0.5;
        var year = Math.floor(((jd - this.jdEpoch) * 98496.0) / 35975351.0) - 1;
        while (jd >= this.toJD((year === -1 ? +1 : year + 1), 7, 1)) {
            year++;
        }
        var month = (jd < this.toJD(year, 1, 1)) ? 7 : 1;
        while (jd > this.toJD(year, month, this.daysInMonth(year, month))) {
            month++;
        }
        var day = jd - this.toJD(year, month, 1) + 1;
        return this.newDate(year, month, day);
    }
});

// Modulus function which works for non-integers.
function mod(a, b) {
    return a - (b * Math.floor(a / b));
}

// Hebrew calendar implementation
main.calendars.hebrew = HebrewCalendar;


},{"../main":549,"object-assign":440}],540:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Islamic calendar for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) August 2009.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


/** Implementation of the Islamic or '16 civil' calendar.
    Based on code from <a href="http://www.iranchamber.com/calendar/converter/iranian_calendar_converter.php">http://www.iranchamber.com/calendar/converter/iranian_calendar_converter.php</a>.
    See also <a href="http://en.wikipedia.org/wiki/Islamic_calendar">http://en.wikipedia.org/wiki/Islamic_calendar</a>.
    @class IslamicCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function IslamicCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

IslamicCalendar.prototype = new main.baseCalendar;

assign(IslamicCalendar.prototype, {
    /** The calendar name.
        @memberof IslamicCalendar */
    name: 'Islamic',
    /** Julian date of start of Islamic epoch: 16 July 622 CE.
        @memberof IslamicCalendar */
    jdEpoch: 1948439.5,
    /** Days per month in a common year.
        @memberof IslamicCalendar */
    daysPerMonth: [30, 29, 30, 29, 30, 29, 30, 29, 30, 29, 30, 29],
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof IslamicCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof IslamicCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof IslamicCalendar */
    firstMonth: 1,
    /** The minimum day number.
        @memberof IslamicCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof IslamicCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Islamic',
            epochs: ['BH', 'AH'],
            monthNames: ['Muharram', 'Safar', 'Rabi\' al-awwal', 'Rabi\' al-thani', 'Jumada al-awwal', 'Jumada al-thani',
            'Rajab', 'Sha\'aban', 'Ramadan', 'Shawwal', 'Dhu al-Qi\'dah', 'Dhu al-Hijjah'],
            monthNamesShort: ['Muh', 'Saf', 'Rab1', 'Rab2', 'Jum1', 'Jum2', 'Raj', 'Sha\'', 'Ram', 'Shaw', 'DhuQ', 'DhuH'],
            dayNames: ['Yawm al-ahad', 'Yawm al-ithnayn', 'Yawm ath-thulaathaa\'',
            'Yawm al-arbi\'aa\'', 'Yawm al-khamīs', 'Yawm al-jum\'a', 'Yawm as-sabt'],
            dayNamesShort: ['Aha', 'Ith', 'Thu', 'Arb', 'Kha', 'Jum', 'Sab'],
            dayNamesMin: ['Ah','It','Th','Ar','Kh','Ju','Sa'],
            digits: null,
            dateFormat: 'yyyy/mm/dd',
            firstDay: 6,
            isRTL: false
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof IslamicCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        return (date.year() * 11 + 14) % 30 < 11;
    },

    /** Determine the week of the year for a date.
        @memberof IslamicCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        // Find Sunday of this week starting on Sunday
        var checkDate = this.newDate(year, month, day);
        checkDate.add(-checkDate.dayOfWeek(), 'd');
        return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
    },

    /** Retrieve the number of days in a year.
        @memberof IslamicCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of days.
        @throws Error if an invalid year or a different calendar used. */
    daysInYear: function(year) {
        return (this.leapYear(year) ? 355 : 354);
    },

    /** Retrieve the number of days in a month.
        @memberof IslamicCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
        return this.daysPerMonth[date.month() - 1] +
            (date.month() === 12 && this.leapYear(date.year()) ? 1 : 0);
    },

    /** Determine whether this date is a week day.
        @memberof IslamicCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        return this.dayOfWeek(year, month, day) !== 5;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof IslamicCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        year = date.year();
        month = date.month();
        day = date.day();
        year = (year <= 0 ? year + 1 : year);
        return day + Math.ceil(29.5 * (month - 1)) + (year - 1) * 354 +
            Math.floor((3 + (11 * year)) / 30) + this.jdEpoch - 1;
    },

    /** Create a new date from a Julian date.
        @memberof IslamicCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        jd = Math.floor(jd) + 0.5;
        var year = Math.floor((30 * (jd - this.jdEpoch) + 10646) / 10631);
        year = (year <= 0 ? year - 1 : year);
        var month = Math.min(12, Math.ceil((jd - 29 - this.toJD(year, 1, 1)) / 29.5) + 1);
        var day = jd - this.toJD(year, month, 1) + 1;
        return this.newDate(year, month, day);
    }
});

// Islamic (16 civil) calendar implementation
main.calendars.islamic = IslamicCalendar;


},{"../main":549,"object-assign":440}],541:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Julian calendar for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) August 2009.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


/** Implementation of the Julian calendar.
    Based on code from <a href="http://www.fourmilab.ch/documents/calendar/">http://www.fourmilab.ch/documents/calendar/</a>.
    See also <a href="http://en.wikipedia.org/wiki/Julian_calendar">http://en.wikipedia.org/wiki/Julian_calendar</a>.
    @class JulianCalendar
    @augments BaseCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function JulianCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

JulianCalendar.prototype = new main.baseCalendar;

assign(JulianCalendar.prototype, {
    /** The calendar name.
        @memberof JulianCalendar */
    name: 'Julian',
    /** Julian date of start of Julian epoch: 1 January 0001 AD = 30 December 0001 BCE.
        @memberof JulianCalendar */
    jdEpoch: 1721423.5,
    /** Days per month in a common year.
        @memberof JulianCalendar */
    daysPerMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof JulianCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof JulianCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof JulianCalendar */
    firstMonth: 1,
    /** The minimum day number.
        @memberof JulianCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof JulianCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Julian',
            epochs: ['BC', 'AD'],
            monthNames: ['January', 'February', 'March', 'April', 'May', 'June',
            'July', 'August', 'September', 'October', 'November', 'December'],
            monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
            dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
            dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
            digits: null,
            dateFormat: 'mm/dd/yyyy',
            firstDay: 0,
            isRTL: false
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof JulianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        var year = (date.year() < 0 ? date.year() + 1 : date.year()); // No year zero
        return (year % 4) === 0;
    },

    /** Determine the week of the year for a date - ISO 8601.
        @memberof JulianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        // Find Thursday of this week starting on Monday
        var checkDate = this.newDate(year, month, day);
        checkDate.add(4 - (checkDate.dayOfWeek() || 7), 'd');
        return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
    },

    /** Retrieve the number of days in a month.
        @memberof JulianCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
        return this.daysPerMonth[date.month() - 1] +
            (date.month() === 2 && this.leapYear(date.year()) ? 1 : 0);
    },

    /** Determine whether this date is a week day.
        @memberof JulianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} True if a week day, false if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        return (this.dayOfWeek(year, month, day) || 7) < 6;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof JulianCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        year = date.year();
        month = date.month();
        day = date.day();
        if (year < 0) { year++; } // No year zero
        // Jean Meeus algorithm, "Astronomical Algorithms", 1991
        if (month <= 2) {
            year--;
            month += 12;
        }
        return Math.floor(365.25 * (year + 4716)) +
            Math.floor(30.6001 * (month + 1)) + day - 1524.5;
    },

    /** Create a new date from a Julian date.
        @memberof JulianCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        // Jean Meeus algorithm, "Astronomical Algorithms", 1991
        var a = Math.floor(jd + 0.5);
        var b = a + 1524;
        var c = Math.floor((b - 122.1) / 365.25);
        var d = Math.floor(365.25 * c);
        var e = Math.floor((b - d) / 30.6001);
        var month = e - Math.floor(e < 14 ? 1 : 13);
        var year = c - Math.floor(month > 2 ? 4716 : 4715);
        var day = b - d - Math.floor(30.6001 * e);
        if (year <= 0) { year--; } // No year zero
        return this.newDate(year, month, day);
    }
});

// Julian calendar implementation
main.calendars.julian = JulianCalendar;


},{"../main":549,"object-assign":440}],542:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Mayan calendar for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) August 2009.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


/** Implementation of the Mayan Long Count calendar.
    See also <a href="http://en.wikipedia.org/wiki/Mayan_calendar">http://en.wikipedia.org/wiki/Mayan_calendar</a>.
    @class MayanCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function MayanCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

MayanCalendar.prototype = new main.baseCalendar;

assign(MayanCalendar.prototype, {
    /** The calendar name.
        @memberof MayanCalendar */
    name: 'Mayan',
    /** Julian date of start of Mayan epoch: 11 August 3114 BCE.
        @memberof MayanCalendar */
    jdEpoch: 584282.5,
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof MayanCalendar */
    hasYearZero: true,
    /** The minimum month number.
        @memberof MayanCalendar */
    minMonth: 0,
    /** The first month in the year.
        @memberof MayanCalendar */
    firstMonth: 0,
    /** The minimum day number.
        @memberof MayanCalendar */
    minDay: 0,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof MayanCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left.
        @property haabMonths {string[]} The names of the Haab months.
        @property tzolkinMonths {string[]} The names of the Tzolkin months. */
    regionalOptions: { // Localisations
        '': {
            name: 'Mayan',
            epochs: ['', ''],
            monthNames: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            '10', '11', '12', '13', '14', '15', '16', '17'],
            monthNamesShort: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            '10', '11', '12', '13', '14', '15', '16', '17'],
            dayNames: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            '10', '11', '12', '13', '14', '15', '16', '17', '18', '19'],
            dayNamesShort: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            '10', '11', '12', '13', '14', '15', '16', '17', '18', '19'],
            dayNamesMin: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            '10', '11', '12', '13', '14', '15', '16', '17', '18', '19'],
            digits: null,
            dateFormat: 'YYYY.m.d',
            firstDay: 0,
            isRTL: false,
            haabMonths: ['Pop', 'Uo', 'Zip', 'Zotz', 'Tzec', 'Xul', 'Yaxkin', 'Mol', 'Chen', 'Yax',
            'Zac', 'Ceh', 'Mac', 'Kankin', 'Muan', 'Pax', 'Kayab', 'Cumku', 'Uayeb'],
            tzolkinMonths: ['Imix', 'Ik', 'Akbal', 'Kan', 'Chicchan', 'Cimi', 'Manik', 'Lamat', 'Muluc', 'Oc',
            'Chuen', 'Eb', 'Ben', 'Ix', 'Men', 'Cib', 'Caban', 'Etznab', 'Cauac', 'Ahau']
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof MayanCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        return false;
    },

    /** Format the year, if not a simple sequential number.
        @memberof MayanCalendar
        @param year {CDate|number} The date to format or the year to format.
        @return {string} The formatted year.
        @throws Error if an invalid year or a different calendar used. */
    formatYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        year = date.year();
        var baktun = Math.floor(year / 400);
        year = year % 400;
        year += (year < 0 ? 400 : 0);
        var katun = Math.floor(year / 20);
        return baktun + '.' + katun + '.' + (year % 20);
    },

    /** Convert from the formatted year back to a single number.
        @memberof MayanCalendar
        @param years {string} The year as n.n.n.
        @return {number} The sequential year.
        @throws Error if an invalid value is supplied. */
    forYear: function(years) {
        years = years.split('.');
        if (years.length < 3) {
            throw 'Invalid Mayan year';
        }
        var year = 0;
        for (var i = 0; i < years.length; i++) {
            var y = parseInt(years[i], 10);
            if (Math.abs(y) > 19 || (i > 0 && y < 0)) {
                throw 'Invalid Mayan year';
            }
            year = year * 20 + y;
        }
        return year;
    },

    /** Retrieve the number of months in a year.
        @memberof MayanCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of months.
        @throws Error if an invalid year or a different calendar used. */
    monthsInYear: function(year) {
        this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        return 18;
    },

    /** Determine the week of the year for a date.
        @memberof MayanCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        this._validate(year, month, day, main.local.invalidDate);
        return 0;
    },

    /** Retrieve the number of days in a year.
        @memberof MayanCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of days.
        @throws Error if an invalid year or a different calendar used. */
    daysInYear: function(year) {
        this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        return 360;
    },

    /** Retrieve the number of days in a month.
        @memberof MayanCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        this._validate(year, month, this.minDay, main.local.invalidMonth);
        return 20;
    },

    /** Retrieve the number of days in a week.
        @memberof MayanCalendar
        @return {number} The number of days. */
    daysInWeek: function() {
        return 5; // Just for formatting
    },

    /** Retrieve the day of the week for a date.
        @memberof MayanCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The day of the week: 0 to number of days - 1.
        @throws Error if an invalid date or a different calendar used. */
    dayOfWeek: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        return date.day();
    },

    /** Determine whether this date is a week day.
        @memberof MayanCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        this._validate(year, month, day, main.local.invalidDate);
        return true;
    },

    /** Retrieve additional information about a date - Haab and Tzolkin equivalents.
        @memberof MayanCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {object} Additional information - contents depends on calendar.
        @throws Error if an invalid date or a different calendar used. */
    extraInfo: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        var jd = date.toJD();
        var haab = this._toHaab(jd);
        var tzolkin = this._toTzolkin(jd);
        return {haabMonthName: this.local.haabMonths[haab[0] - 1],
            haabMonth: haab[0], haabDay: haab[1],
            tzolkinDayName: this.local.tzolkinMonths[tzolkin[0] - 1],
            tzolkinDay: tzolkin[0], tzolkinTrecena: tzolkin[1]};
    },

    /** Retrieve Haab date from a Julian date.
        @memberof MayanCalendar
        @private
        @param jd  {number} The Julian date.
        @return {number[]} Corresponding Haab month and day. */
    _toHaab: function(jd) {
        jd -= this.jdEpoch;
        var day = mod(jd + 8 + ((18 - 1) * 20), 365);
        return [Math.floor(day / 20) + 1, mod(day, 20)];
    },

    /** Retrieve Tzolkin date from a Julian date.
        @memberof MayanCalendar
        @private
        @param jd {number} The Julian date.
        @return {number[]} Corresponding Tzolkin day and trecena. */
    _toTzolkin: function(jd) {
        jd -= this.jdEpoch;
        return [amod(jd + 20, 20), amod(jd + 4, 13)];
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof MayanCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        return date.day() + (date.month() * 20) + (date.year() * 360) + this.jdEpoch;
    },

    /** Create a new date from a Julian date.
        @memberof MayanCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        jd = Math.floor(jd) + 0.5 - this.jdEpoch;
        var year = Math.floor(jd / 360);
        jd = jd % 360;
        jd += (jd < 0 ? 360 : 0);
        var month = Math.floor(jd / 20);
        var day = jd % 20;
        return this.newDate(year, month, day);
    }
});

// Modulus function which works for non-integers.
function mod(a, b) {
    return a - (b * Math.floor(a / b));
}

// Modulus function which returns numerator if modulus is zero.
function amod(a, b) {
    return mod(a - 1, b) + 1;
}

// Mayan calendar implementation
main.calendars.mayan = MayanCalendar;


},{"../main":549,"object-assign":440}],543:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

/* http://keith-wood.name/calendars.html
   Nanakshahi calendar for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) January 2016.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


/** Implementation of the Nanakshahi calendar.
    See also <a href="https://en.wikipedia.org/wiki/Nanakshahi_calendar">https://en.wikipedia.org/wiki/Nanakshahi_calendar</a>.
    @class NanakshahiCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function NanakshahiCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

NanakshahiCalendar.prototype = new main.baseCalendar;

var gregorian = main.instance('gregorian');

assign(NanakshahiCalendar.prototype, {
    /** The calendar name.
        @memberof NanakshahiCalendar */
    name: 'Nanakshahi',
    /** Julian date of start of Nanakshahi epoch: 14 March 1469 CE.
        @memberof NanakshahiCalendar */
    jdEpoch: 2257673.5,
    /** Days per month in a common year.
        @memberof NanakshahiCalendar */
    daysPerMonth: [31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30, 30],
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof NanakshahiCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof NanakshahiCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof NanakshahiCalendar */
    firstMonth: 1,
    /** The minimum day number.
        @memberof NanakshahiCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof NanakshahiCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Nanakshahi',
            epochs: ['BN', 'AN'],
            monthNames: ['Chet', 'Vaisakh', 'Jeth', 'Harh', 'Sawan', 'Bhadon',
            'Assu', 'Katak', 'Maghar', 'Poh', 'Magh', 'Phagun'],
            monthNamesShort: ['Che', 'Vai', 'Jet', 'Har', 'Saw', 'Bha', 'Ass', 'Kat', 'Mgr', 'Poh', 'Mgh', 'Pha'],
            dayNames: ['Somvaar', 'Mangalvar', 'Budhvaar', 'Veervaar', 'Shukarvaar', 'Sanicharvaar', 'Etvaar'],
            dayNamesShort: ['Som', 'Mangal', 'Budh', 'Veer', 'Shukar', 'Sanichar', 'Et'],
            dayNamesMin: ['So', 'Ma', 'Bu', 'Ve', 'Sh', 'Sa', 'Et'],
            digits: null,
            dateFormat: 'dd-mm-yyyy',
            firstDay: 0,
            isRTL: false
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof NanakshahiCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay,
            main.local.invalidYear || main.regionalOptions[''].invalidYear);
        return gregorian.leapYear(date.year() + (date.year() < 1 ? 1 : 0) + 1469);
    },

    /** Determine the week of the year for a date.
        @memberof NanakshahiCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        // Find Monday of this week starting on Monday
        var checkDate = this.newDate(year, month, day);
        checkDate.add(1 - (checkDate.dayOfWeek() || 7), 'd');
        return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
    },

    /** Retrieve the number of days in a month.
        @memberof NanakshahiCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
        return this.daysPerMonth[date.month() - 1] +
            (date.month() === 12 && this.leapYear(date.year()) ? 1 : 0);
    },

    /** Determine whether this date is a week day.
        @memberof NanakshahiCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        return (this.dayOfWeek(year, month, day) || 7) < 6;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof NanakshahiCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidMonth);
        var year = date.year();
        if (year < 0) { year++; } // No year zero
        var doy = date.day();
        for (var m = 1; m < date.month(); m++) {
            doy += this.daysPerMonth[m - 1];
        }
        return doy + gregorian.toJD(year + 1468, 3, 13);
    },

    /** Create a new date from a Julian date.
        @memberof NanakshahiCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        jd = Math.floor(jd + 0.5);
        var year = Math.floor((jd - (this.jdEpoch - 1)) / 366);
        while (jd >= this.toJD(year + 1, 1, 1)) {
            year++;
        }
        var day = jd - Math.floor(this.toJD(year, 1, 1) + 0.5) + 1;
        var month = 1;
        while (day > this.daysInMonth(year, month)) {
            day -= this.daysInMonth(year, month);
            month++;
        }
        return this.newDate(year, month, day);
    }
});

// Nanakshahi calendar implementation
main.calendars.nanakshahi = NanakshahiCalendar;


},{"../main":549,"object-assign":440}],544:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Nepali calendar for jQuery v2.0.2.
   Written by Artur Neumann (ict.projects{at}nepal.inf.org) April 2013.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


/** Implementation of the Nepali civil calendar.
    Based on the ideas from 
    <a href="http://codeissue.com/articles/a04e050dea7468f/algorithm-to-convert-english-date-to-nepali-date-using-c-net">http://codeissue.com/articles/a04e050dea7468f/algorithm-to-convert-english-date-to-nepali-date-using-c-net</a>
    and <a href="http://birenj2ee.blogspot.com/2011/04/nepali-calendar-in-java.html">http://birenj2ee.blogspot.com/2011/04/nepali-calendar-in-java.html</a>
    See also <a href="http://en.wikipedia.org/wiki/Nepali_calendar">http://en.wikipedia.org/wiki/Nepali_calendar</a>
    and <a href="https://en.wikipedia.org/wiki/Bikram_Samwat">https://en.wikipedia.org/wiki/Bikram_Samwat</a>.
    @class NepaliCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function NepaliCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

NepaliCalendar.prototype = new main.baseCalendar;

assign(NepaliCalendar.prototype, {
    /** The calendar name.
        @memberof NepaliCalendar */
    name: 'Nepali',
    /** Julian date of start of Nepali epoch: 14 April 57 BCE.
        @memberof NepaliCalendar */
    jdEpoch: 1700709.5,
    /** Days per month in a common year.
        @memberof NepaliCalendar */
    daysPerMonth: [31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof NepaliCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof NepaliCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof NepaliCalendar */
    firstMonth: 1,
    /** The minimum day number.
        @memberof NepaliCalendar */
    minDay: 1, 
    /** The number of days in the year.
        @memberof NepaliCalendar */
    daysPerYear: 365,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof NepaliCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Nepali',
            epochs: ['BBS', 'ABS'],
            monthNames: ['Baisakh', 'Jestha', 'Ashadh', 'Shrawan', 'Bhadra', 'Ashwin',
            'Kartik', 'Mangsir', 'Paush', 'Mangh', 'Falgun', 'Chaitra'],
            monthNamesShort: ['Bai', 'Je', 'As', 'Shra', 'Bha', 'Ash', 'Kar', 'Mang', 'Pau', 'Ma', 'Fal', 'Chai'],
            dayNames: ['Aaitabaar', 'Sombaar', 'Manglbaar', 'Budhabaar', 'Bihibaar', 'Shukrabaar', 'Shanibaar'],
            dayNamesShort: ['Aaita', 'Som', 'Mangl', 'Budha', 'Bihi', 'Shukra', 'Shani'],
            dayNamesMin: ['Aai', 'So', 'Man', 'Bu', 'Bi', 'Shu', 'Sha'],
            digits: null,
            dateFormat: 'dd/mm/yyyy',
            firstDay: 1,
            isRTL: false
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof NepaliCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        return this.daysInYear(year) !== this.daysPerYear;
    },

    /** Determine the week of the year for a date.
        @memberof NepaliCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        // Find Sunday of this week starting on Sunday
        var checkDate = this.newDate(year, month, day);
        checkDate.add(-checkDate.dayOfWeek(), 'd');
        return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
    },

    /** Retrieve the number of days in a year.
        @memberof NepaliCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of days.
        @throws Error if an invalid year or a different calendar used. */
    daysInYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        year = date.year();
        if (typeof this.NEPALI_CALENDAR_DATA[year] === 'undefined') {
            return this.daysPerYear;
        }
        var daysPerYear = 0;
        for (var month_number = this.minMonth; month_number <= 12; month_number++) {
            daysPerYear += this.NEPALI_CALENDAR_DATA[year][month_number];
        }
        return daysPerYear;
    },

    /** Retrieve the number of days in a month.
        @memberof NepaliCalendar
        @param year {CDate|number| The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        if (year.year) {
            month = year.month();
            year = year.year();
        }
        this._validate(year, month, this.minDay, main.local.invalidMonth);
        return (typeof this.NEPALI_CALENDAR_DATA[year] === 'undefined' ?
            this.daysPerMonth[month - 1] : this.NEPALI_CALENDAR_DATA[year][month]);
    },

    /** Determine whether this date is a week day.
        @memberof NepaliCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        return this.dayOfWeek(year, month, day) !== 6;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof NepaliCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(nepaliYear, nepaliMonth, nepaliDay) {
        var date = this._validate(nepaliYear, nepaliMonth, nepaliDay, main.local.invalidDate);
        nepaliYear = date.year();
        nepaliMonth = date.month();
        nepaliDay = date.day();
        var gregorianCalendar = main.instance();
        var gregorianDayOfYear = 0; // We will add all the days that went by since
        // the 1st. January and then we can get the Gregorian Date
        var nepaliMonthToCheck = nepaliMonth;
        var nepaliYearToCheck = nepaliYear;
        this._createMissingCalendarData(nepaliYear);
        // Get the correct year
        var gregorianYear = nepaliYear - (nepaliMonthToCheck > 9 || (nepaliMonthToCheck === 9 &&
            nepaliDay >= this.NEPALI_CALENDAR_DATA[nepaliYearToCheck][0]) ? 56 : 57);
        // First we add the amount of days in the actual Nepali month as the day of year in the
        // Gregorian one because at least this days are gone since the 1st. Jan. 
        if (nepaliMonth !== 9) {
            gregorianDayOfYear = nepaliDay;
            nepaliMonthToCheck--;
        }
        // Now we loop throw all Nepali month and add the amount of days to gregorianDayOfYear 
        // we do this till we reach Paush (9th month). 1st. January always falls in this month  
        while (nepaliMonthToCheck !== 9) {
            if (nepaliMonthToCheck <= 0) {
                nepaliMonthToCheck = 12;
                nepaliYearToCheck--;
            }                
            gregorianDayOfYear += this.NEPALI_CALENDAR_DATA[nepaliYearToCheck][nepaliMonthToCheck];
            nepaliMonthToCheck--;
        }        
        // If the date that has to be converted is in Paush (month no. 9) we have to do some other calculation
        if (nepaliMonth === 9) {
            // Add the days that are passed since the first day of Paush and substract the
            // amount of days that lie between 1st. Jan and 1st Paush
            gregorianDayOfYear += nepaliDay - this.NEPALI_CALENDAR_DATA[nepaliYearToCheck][0];
            // For the first days of Paush we are now in negative values,
            // because in the end of the gregorian year we substract
            // 365 / 366 days (P.S. remember math in school + - gives -)
            if (gregorianDayOfYear < 0) {
                gregorianDayOfYear += gregorianCalendar.daysInYear(gregorianYear);
            }
        }
        else {
            gregorianDayOfYear += this.NEPALI_CALENDAR_DATA[nepaliYearToCheck][9] -
                this.NEPALI_CALENDAR_DATA[nepaliYearToCheck][0];
        }        
        return gregorianCalendar.newDate(gregorianYear, 1 ,1).add(gregorianDayOfYear, 'd').toJD();
    },
    
    /** Create a new date from a Julian date.
        @memberof NepaliCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        var gregorianCalendar =  main.instance();
        var gregorianDate = gregorianCalendar.fromJD(jd);
        var gregorianYear = gregorianDate.year();
        var gregorianDayOfYear = gregorianDate.dayOfYear();
        var nepaliYear = gregorianYear + 56; //this is not final, it could be also +57 but +56 is always true for 1st Jan.
        this._createMissingCalendarData(nepaliYear);
        var nepaliMonth = 9; // Jan 1 always fall in Nepali month Paush which is the 9th month of Nepali calendar.
        // Get the Nepali day in Paush (month 9) of 1st January 
        var dayOfFirstJanInPaush = this.NEPALI_CALENDAR_DATA[nepaliYear][0];
        // Check how many days are left of Paush .
        // Days calculated from 1st Jan till the end of the actual Nepali month, 
        // we use this value to check if the gregorian Date is in the actual Nepali month.
        var daysSinceJanFirstToEndOfNepaliMonth =
            this.NEPALI_CALENDAR_DATA[nepaliYear][nepaliMonth] - dayOfFirstJanInPaush + 1;
        // If the gregorian day-of-year is smaller o equal than the sum of days between the 1st January and 
        // the end of the actual nepali month we found the correct nepali month.
        // Example: 
        // The 4th February 2011 is the gregorianDayOfYear 35 (31 days of January + 4)
        // 1st January 2011 is in the nepali year 2067, where 1st. January is in the 17th day of Paush (9th month)
        // In 2067 Paush has 30days, This means (30-17+1=14) there are 14days between 1st January and end of Paush 
        // (including 17th January)
        // The gregorianDayOfYear (35) is bigger than 14, so we check the next month
        // The next nepali month (Mangh) has 29 days 
        // 29+14=43, this is bigger than gregorianDayOfYear(35) so, we found the correct nepali month
        while (gregorianDayOfYear > daysSinceJanFirstToEndOfNepaliMonth) {
            nepaliMonth++;
            if (nepaliMonth > 12) {
                nepaliMonth = 1;
                nepaliYear++;
            }    
            daysSinceJanFirstToEndOfNepaliMonth += this.NEPALI_CALENDAR_DATA[nepaliYear][nepaliMonth];
        }
        // The last step is to calculate the nepali day-of-month
        // to continue our example from before:
        // we calculated there are 43 days from 1st. January (17 Paush) till end of Mangh (29 days)
        // when we subtract from this 43 days the day-of-year of the the Gregorian date (35),
        // we know how far the searched day is away from the end of the Nepali month.
        // So we simply subtract this number from the amount of days in this month (30) 
        var nepaliDayOfMonth = this.NEPALI_CALENDAR_DATA[nepaliYear][nepaliMonth] -
            (daysSinceJanFirstToEndOfNepaliMonth - gregorianDayOfYear);        
        return this.newDate(nepaliYear, nepaliMonth, nepaliDayOfMonth);
    },
    
    /** Creates missing data in the NEPALI_CALENDAR_DATA table.
        This data will not be correct but just give an estimated result. Mostly -/+ 1 day
        @private
        @param nepaliYear {number} The missing year number. */
    _createMissingCalendarData: function(nepaliYear) {
        var tmp_calendar_data = this.daysPerMonth.slice(0);
        tmp_calendar_data.unshift(17);
        for (var nepaliYearToCreate = (nepaliYear - 1); nepaliYearToCreate < (nepaliYear + 2); nepaliYearToCreate++) {
            if (typeof this.NEPALI_CALENDAR_DATA[nepaliYearToCreate] === 'undefined') {
                this.NEPALI_CALENDAR_DATA[nepaliYearToCreate] = tmp_calendar_data;
            }
        }
    },
    
    NEPALI_CALENDAR_DATA:  {
        // These data are from http://www.ashesh.com.np
        1970: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        1971: [18, 31, 31, 32, 31, 32, 30, 30, 29, 30, 29, 30, 30],
        1972: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 30],
        1973: [19, 30, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        1974: [19, 31, 31, 32, 30, 31, 31, 30, 29, 30, 29, 30, 30],
        1975: [18, 31, 31, 32, 32, 30, 31, 30, 29, 30, 29, 30, 30],
        1976: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        1977: [18, 31, 32, 31, 32, 31, 31, 29, 30, 29, 30, 29, 31],
        1978: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        1979: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        1980: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        1981: [18, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 30, 30],
        1982: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        1983: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        1984: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        1985: [18, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 30, 30],
        1986: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        1987: [18, 31, 32, 31, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        1988: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        1989: [18, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
        1990: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        1991: [18, 31, 32, 31, 32, 31, 30, 30, 29, 30, 29, 30, 30],    
        // These data are from http://nepalicalendar.rat32.com/index.php
        1992: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        1993: [18, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
        1994: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        1995: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 30],
        1996: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        1997: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        1998: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        1999: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2000: [17, 30, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        2001: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2002: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2003: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2004: [17, 30, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        2005: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2006: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2007: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2008: [17, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 29, 31],
        2009: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2010: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2011: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2012: [17, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 30, 30],
        2013: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2014: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2015: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2016: [17, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 30, 30],
        2017: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2018: [18, 31, 32, 31, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2019: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        2020: [17, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
        2021: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2022: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 30],
        2023: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        2024: [17, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
        2025: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2026: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2027: [17, 30, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        2028: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2029: [18, 31, 31, 32, 31, 32, 30, 30, 29, 30, 29, 30, 30],
        2030: [17, 31, 32, 31, 32, 31, 30, 30, 30, 30, 30, 30, 31],
        2031: [17, 31, 32, 31, 32, 31, 31, 31, 31, 31, 31, 31, 31],
        2032: [17, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32],
        2033: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2034: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2035: [17, 30, 32, 31, 32, 31, 31, 29, 30, 30, 29, 29, 31],
        2036: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2037: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2038: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2039: [17, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 30, 30],
        2040: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2041: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2042: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2043: [17, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 30, 30],
        2044: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2045: [18, 31, 32, 31, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2046: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2047: [17, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
        2048: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2049: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 30],
        2050: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        2051: [17, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
        2052: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2053: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 30],
        2054: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        2055: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 30, 29, 30],
        2056: [17, 31, 31, 32, 31, 32, 30, 30, 29, 30, 29, 30, 30],
        2057: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2058: [17, 30, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        2059: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2060: [17, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2061: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2062: [17, 30, 32, 31, 32, 31, 31, 29, 30, 29, 30, 29, 31],
        2063: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2064: [17, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2065: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2066: [17, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 29, 31],
        2067: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2068: [17, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2069: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2070: [17, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 30, 30],
        2071: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2072: [17, 31, 32, 31, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2073: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
        2074: [17, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
        2075: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2076: [16, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 30],
        2077: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
        2078: [17, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
        2079: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
        2080: [16, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 30],
        // These data are from http://www.ashesh.com.np/nepali-calendar/
        2081: [17, 31, 31, 32, 32, 31, 30, 30, 30, 29, 30, 30, 30],
        2082: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 30, 30],
        2083: [17, 31, 31, 32, 31, 31, 30, 30, 30, 29, 30, 30, 30],
        2084: [17, 31, 31, 32, 31, 31, 30, 30, 30, 29, 30, 30, 30],
        2085: [17, 31, 32, 31, 32, 31, 31, 30, 30, 29, 30, 30, 30],
        2086: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 30, 30],
        2087: [16, 31, 31, 32, 31, 31, 31, 30, 30, 29, 30, 30, 30],
        2088: [16, 30, 31, 32, 32, 30, 31, 30, 30, 29, 30, 30, 30],
        2089: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 30, 30],
        2090: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 30, 30],
        2091: [16, 31, 31, 32, 31, 31, 31, 30, 30, 29, 30, 30, 30],
        2092: [16, 31, 31, 32, 32, 31, 30, 30, 30, 29, 30, 30, 30],
        2093: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 30, 30],
        2094: [17, 31, 31, 32, 31, 31, 30, 30, 30, 29, 30, 30, 30],
        2095: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 30, 30, 30],
        2096: [17, 30, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        2097: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 30, 30],
        2098: [17, 31, 31, 32, 31, 31, 31, 29, 30, 29, 30, 30, 31],
        2099: [17, 31, 31, 32, 31, 31, 31, 30, 29, 29, 30, 30, 30],
        2100: [17, 31, 32, 31, 32, 30, 31, 30, 29, 30, 29, 30, 30]    
    }
});    

// Nepali calendar implementation
main.calendars.nepali = NepaliCalendar;


},{"../main":549,"object-assign":440}],545:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Persian calendar for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) August 2009.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


/** Implementation of the Persian or Jalali calendar.
    Based on code from <a href="http://www.iranchamber.com/calendar/converter/iranian_calendar_converter.php">http://www.iranchamber.com/calendar/converter/iranian_calendar_converter.php</a>.
    See also <a href="http://en.wikipedia.org/wiki/Iranian_calendar">http://en.wikipedia.org/wiki/Iranian_calendar</a>.
    @class PersianCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function PersianCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

PersianCalendar.prototype = new main.baseCalendar;

assign(PersianCalendar.prototype, {
    /** The calendar name.
        @memberof PersianCalendar */
    name: 'Persian',
    /** Julian date of start of Persian epoch: 19 March 622 CE.
        @memberof PersianCalendar */
    jdEpoch: 1948320.5,
    /** Days per month in a common year.
        @memberof PersianCalendar */
    daysPerMonth: [31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29],
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof PersianCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof PersianCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof PersianCalendar */
    firstMonth: 1,
    /** The minimum day number.
        @memberof PersianCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof PersianCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Persian',
            epochs: ['BP', 'AP'],
            monthNames: ['Farvardin', 'Ordibehesht', 'Khordad', 'Tir', 'Mordad', 'Shahrivar',
            'Mehr', 'Aban', 'Azar', 'Day', 'Bahman', 'Esfand'],
            monthNamesShort: ['Far', 'Ord', 'Kho', 'Tir', 'Mor', 'Sha', 'Meh', 'Aba', 'Aza', 'Day', 'Bah', 'Esf'],
            dayNames: ['Yekshambe', 'Doshambe', 'Seshambe', 'Chæharshambe', 'Panjshambe', 'Jom\'e', 'Shambe'],
            dayNamesShort: ['Yek', 'Do', 'Se', 'Chæ', 'Panj', 'Jom', 'Sha'],
            dayNamesMin: ['Ye','Do','Se','Ch','Pa','Jo','Sh'],
            digits: null,
            dateFormat: 'yyyy/mm/dd',
            firstDay: 6,
            isRTL: false
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof PersianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        return (((((date.year() - (date.year() > 0 ? 474 : 473)) % 2820) +
            474 + 38) * 682) % 2816) < 682;
    },

    /** Determine the week of the year for a date.
        @memberof PersianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        // Find Saturday of this week starting on Saturday
        var checkDate = this.newDate(year, month, day);
        checkDate.add(-((checkDate.dayOfWeek() + 1) % 7), 'd');
        return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
    },

    /** Retrieve the number of days in a month.
        @memberof PersianCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
        return this.daysPerMonth[date.month() - 1] +
            (date.month() === 12 && this.leapYear(date.year()) ? 1 : 0);
    },

    /** Determine whether this date is a week day.
        @memberof PersianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        return this.dayOfWeek(year, month, day) !== 5;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof PersianCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        year = date.year();
        month = date.month();
        day = date.day();
        var epBase = year - (year >= 0 ? 474 : 473);
        var epYear = 474 + mod(epBase, 2820);
        return day + (month <= 7 ? (month - 1) * 31 : (month - 1) * 30 + 6) +
            Math.floor((epYear * 682 - 110) / 2816) + (epYear - 1) * 365 +
            Math.floor(epBase / 2820) * 1029983 + this.jdEpoch - 1;
    },

    /** Create a new date from a Julian date.
        @memberof PersianCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        jd = Math.floor(jd) + 0.5;
        var depoch = jd - this.toJD(475, 1, 1);
        var cycle = Math.floor(depoch / 1029983);
        var cyear = mod(depoch, 1029983);
        var ycycle = 2820;
        if (cyear !== 1029982) {
            var aux1 = Math.floor(cyear / 366);
            var aux2 = mod(cyear, 366);
            ycycle = Math.floor(((2134 * aux1) + (2816 * aux2) + 2815) / 1028522) + aux1 + 1;
        }
        var year = ycycle + (2820 * cycle) + 474;
        year = (year <= 0 ? year - 1 : year);
        var yday = jd - this.toJD(year, 1, 1) + 1;
        var month = (yday <= 186 ? Math.ceil(yday / 31) : Math.ceil((yday - 6) / 30));
        var day = jd - this.toJD(year, month, 1) + 1;
        return this.newDate(year, month, day);
    }
});

// Modulus function which works for non-integers.
function mod(a, b) {
    return a - (b * Math.floor(a / b));
}

// Persian (Jalali) calendar implementation
main.calendars.persian = PersianCalendar;
main.calendars.jalali = PersianCalendar;


},{"../main":549,"object-assign":440}],546:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Taiwanese (Minguo) calendar for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) February 2010.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


var gregorianCalendar = main.instance();

/** Implementation of the Taiwanese calendar.
    See http://en.wikipedia.org/wiki/Minguo_calendar.
    @class TaiwanCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function TaiwanCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

TaiwanCalendar.prototype = new main.baseCalendar;

assign(TaiwanCalendar.prototype, {
    /** The calendar name.
        @memberof TaiwanCalendar */
    name: 'Taiwan',
    /** Julian date of start of Taiwan epoch: 1 January 1912 CE (Gregorian).
        @memberof TaiwanCalendar */
    jdEpoch: 2419402.5,
    /** Difference in years between Taiwan and Gregorian calendars.
        @memberof TaiwanCalendar */
    yearsOffset: 1911,
    /** Days per month in a common year.
        @memberof TaiwanCalendar */
    daysPerMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof TaiwanCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof TaiwanCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof TaiwanCalendar */
    firstMonth: 1,
    /** The minimum day number.
        @memberof TaiwanCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof TaiwanCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Taiwan',
            epochs: ['BROC', 'ROC'],
            monthNames: ['January', 'February', 'March', 'April', 'May', 'June',
            'July', 'August', 'September', 'October', 'November', 'December'],
            monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
            dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
            dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
            digits: null,
            dateFormat: 'yyyy/mm/dd',
            firstDay: 1,
            isRTL: false
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof TaiwanCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        var year = this._t2gYear(date.year());
        return gregorianCalendar.leapYear(year);
    },

    /** Determine the week of the year for a date - ISO 8601.
        @memberof TaiwanCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        var year = this._t2gYear(date.year());
        return gregorianCalendar.weekOfYear(year, date.month(), date.day());
    },

    /** Retrieve the number of days in a month.
        @memberof TaiwanCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
        return this.daysPerMonth[date.month() - 1] +
            (date.month() === 2 && this.leapYear(date.year()) ? 1 : 0);
    },

    /** Determine whether this date is a week day.
        @memberof TaiwanCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        return (this.dayOfWeek(year, month, day) || 7) < 6;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof TaiwanCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        var year = this._t2gYear(date.year());
        return gregorianCalendar.toJD(year, date.month(), date.day());
    },

    /** Create a new date from a Julian date.
        @memberof TaiwanCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        var date = gregorianCalendar.fromJD(jd);
        var year = this._g2tYear(date.year());
        return this.newDate(year, date.month(), date.day());
    },

    /** Convert Taiwanese to Gregorian year.
        @memberof TaiwanCalendar
        @private
        @param year {number} The Taiwanese year.
        @return {number} The corresponding Gregorian year. */
    _t2gYear: function(year) {
        return year + this.yearsOffset + (year >= -this.yearsOffset && year <= -1 ? 1 : 0);
    },

    /** Convert Gregorian to Taiwanese year.
        @memberof TaiwanCalendar
        @private
        @param year {number} The Gregorian year.
        @return {number} The corresponding Taiwanese year. */
    _g2tYear: function(year) {
        return year - this.yearsOffset - (year >= 1 && year <= this.yearsOffset ? 1 : 0);
    }
});

// Taiwan calendar implementation
main.calendars.taiwan = TaiwanCalendar;


},{"../main":549,"object-assign":440}],547:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Thai calendar for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) February 2010.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


var gregorianCalendar = main.instance();

/** Implementation of the Thai calendar.
    See http://en.wikipedia.org/wiki/Thai_calendar.
    @class ThaiCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function ThaiCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

ThaiCalendar.prototype = new main.baseCalendar;

assign(ThaiCalendar.prototype, {
    /** The calendar name.
        @memberof ThaiCalendar */
    name: 'Thai',
    /** Julian date of start of Thai epoch: 1 January 543 BCE (Gregorian).
        @memberof ThaiCalendar */
    jdEpoch: 1523098.5,
    /** Difference in years between Thai and Gregorian calendars.
        @memberof ThaiCalendar */
    yearsOffset: 543, 
    /** Days per month in a common year.
        @memberof ThaiCalendar */
    daysPerMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof ThaiCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof ThaiCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof ThaiCalendar */
    firstMonth: 1,
    /** The minimum day number.
        @memberof ThaiCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof ThaiCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Thai',
            epochs: ['BBE', 'BE'],
            monthNames: ['January', 'February', 'March', 'April', 'May', 'June',
            'July', 'August', 'September', 'October', 'November', 'December'],
            monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
            dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
            dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
            digits: null,
            dateFormat: 'dd/mm/yyyy',
            firstDay: 0,
            isRTL: false
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof ThaiCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        var year = this._t2gYear(date.year());
        return gregorianCalendar.leapYear(year);
    },

    /** Determine the week of the year for a date - ISO 8601.
        @memberof ThaiCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        var year = this._t2gYear(date.year());
        return gregorianCalendar.weekOfYear(year, date.month(), date.day());
    },

    /** Retrieve the number of days in a month.
        @memberof ThaiCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
        return this.daysPerMonth[date.month() - 1] +
            (date.month() === 2 && this.leapYear(date.year()) ? 1 : 0);
    },

    /** Determine whether this date is a week day.
        @memberof ThaiCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        return (this.dayOfWeek(year, month, day) || 7) < 6;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof ThaiCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        var year = this._t2gYear(date.year());
        return gregorianCalendar.toJD(year, date.month(), date.day());
    },

    /** Create a new date from a Julian date.
        @memberof ThaiCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        var date = gregorianCalendar.fromJD(jd);
        var year = this._g2tYear(date.year());
        return this.newDate(year, date.month(), date.day());
    },

    /** Convert Thai to Gregorian year.
        @memberof ThaiCalendar
        @private
        @param year {number} The Thai year.
        @return {number} The corresponding Gregorian year. */
    _t2gYear: function(year) {
        return year - this.yearsOffset - (year >= 1 && year <= this.yearsOffset ? 1 : 0);
    },

    /** Convert Gregorian to Thai year.
        @memberof ThaiCalendar
        @private
        @param year {number} The Gregorian year.
        @return {number} The corresponding Thai year. */
    _g2tYear: function(year) {
        return year + this.yearsOffset + (year >= -this.yearsOffset && year <= -1 ? 1 : 0);
    }
});

// Thai calendar implementation
main.calendars.thai = ThaiCalendar;


},{"../main":549,"object-assign":440}],548:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   UmmAlQura calendar for jQuery v2.0.2.
   Written by Amro Osama March 2013.
   Modified by Binnooh.com & www.elm.sa - 2014 - Added dates back to 1276 Hijri year.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var main = _dereq_('../main');
var assign = _dereq_('object-assign');


/** Implementation of the UmmAlQura or 'saudi' calendar.
    See also <a href="http://en.wikipedia.org/wiki/Islamic_calendar#Saudi_Arabia.27s_Umm_al-Qura_calendar">http://en.wikipedia.org/wiki/Islamic_calendar#Saudi_Arabia.27s_Umm_al-Qura_calendar</a>.
    <a href="http://www.ummulqura.org.sa/About.aspx">http://www.ummulqura.org.sa/About.aspx</a>
    <a href="http://www.staff.science.uu.nl/~gent0113/islam/ummalqura.htm">http://www.staff.science.uu.nl/~gent0113/islam/ummalqura.htm</a>
    @class UmmAlQuraCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function UmmAlQuraCalendar(language) {
    this.local = this.regionalOptions[language || ''] || this.regionalOptions[''];
}

UmmAlQuraCalendar.prototype = new main.baseCalendar;

assign(UmmAlQuraCalendar.prototype, {
    /** The calendar name.
        @memberof UmmAlQuraCalendar */
    name: 'UmmAlQura',
    //jdEpoch: 1948440, // Julian date of start of UmmAlQura epoch: 14 March 1937 CE
    //daysPerMonth: // Days per month in a common year, replaced by a method.
    /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof UmmAlQuraCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof UmmAlQuraCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof UmmAlQuraCalendar */
    firstMonth: 1,
    /** The minimum day number.
        @memberof UmmAlQuraCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof UmmAlQuraCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Umm al-Qura',
            epochs: ['BH', 'AH'],
            monthNames: ['Al-Muharram', 'Safar', 'Rabi\' al-awwal', 'Rabi\' Al-Thani', 'Jumada Al-Awwal', 'Jumada Al-Thani',
            'Rajab', 'Sha\'aban', 'Ramadan', 'Shawwal', 'Dhu al-Qi\'dah', 'Dhu al-Hijjah'],
            monthNamesShort: ['Muh', 'Saf', 'Rab1', 'Rab2', 'Jum1', 'Jum2', 'Raj', 'Sha\'', 'Ram', 'Shaw', 'DhuQ', 'DhuH'],
            dayNames: ['Yawm al-Ahad', 'Yawm al-Ithnain', 'Yawm al-Thalāthā’', 'Yawm al-Arba‘ā’', 'Yawm al-Khamīs', 'Yawm al-Jum‘a', 'Yawm al-Sabt'],
            dayNamesMin: ['Ah', 'Ith', 'Th', 'Ar', 'Kh', 'Ju', 'Sa'],
            digits: null,
            dateFormat: 'yyyy/mm/dd',
            firstDay: 6,
            isRTL: true
        }
    },

    /** Determine whether this date is in a leap year.
        @memberof UmmAlQuraCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function (year) {
        var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
        return (this.daysInYear(date.year()) === 355);
    },

    /** Determine the week of the year for a date.
        @memberof UmmAlQuraCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function (year, month, day) {
        // Find Sunday of this week starting on Sunday
        var checkDate = this.newDate(year, month, day);
        checkDate.add(-checkDate.dayOfWeek(), 'd');
        return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
    },

    /** Retrieve the number of days in a year.
        @memberof UmmAlQuraCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of days.
        @throws Error if an invalid year or a different calendar used. */
    daysInYear: function (year) {
        var daysCount = 0;
        for (var i = 1; i <= 12; i++) {
            daysCount += this.daysInMonth(year, i);
        }
        return daysCount;
    },

    /** Retrieve the number of days in a month.
        @memberof UmmAlQuraCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function (year, month) {
        var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
        var mcjdn = date.toJD() - 2400000 + 0.5; // Modified Chronological Julian Day Number (MCJDN)
        // the MCJDN's of the start of the lunations in the Umm al-Qura calendar are stored in the 'ummalqura_dat' array
        var index = 0;
        for (var i = 0; i < ummalqura_dat.length; i++) {
            if (ummalqura_dat[i] > mcjdn) {
                return (ummalqura_dat[index] - ummalqura_dat[index - 1]);
            }
            index++;
        }
        return 30; // Unknown outside
    },

    /** Determine whether this date is a week day.
        @memberof UmmAlQuraCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function (year, month, day) {
        return this.dayOfWeek(year, month, day) !== 5;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof UmmAlQuraCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function (year, month, day) {
        var date = this._validate(year, month, day, main.local.invalidDate);
        var index = (12 * (date.year() - 1)) + date.month() - 15292;
        var mcjdn = date.day() + ummalqura_dat[index - 1] - 1;
        return mcjdn + 2400000 - 0.5; // Modified Chronological Julian Day Number (MCJDN)
    },

    /** Create a new date from a Julian date.
        @memberof UmmAlQuraCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function (jd) {
        var mcjdn = jd - 2400000 + 0.5; // Modified Chronological Julian Day Number (MCJDN)
        // the MCJDN's of the start of the lunations in the Umm al-Qura calendar 
        // are stored in the 'ummalqura_dat' array
        var index = 0;
        for (var i = 0; i < ummalqura_dat.length; i++) {
            if (ummalqura_dat[i] > mcjdn) break;
            index++;
        }
        var lunation = index + 15292; //UmmAlQura Lunation Number
        var ii = Math.floor((lunation - 1) / 12);
        var year = ii + 1;
        var month = lunation - 12 * ii;
        var day = mcjdn - ummalqura_dat[index - 1] + 1;
        return this.newDate(year, month, day);
    },

    /** Determine whether a date is valid for this calendar.
        @memberof UmmAlQuraCalendar
        @param year {number} The year to examine.
        @param month {number} The month to examine.
        @param day {number} The day to examine.
        @return {boolean} <code>true</code> if a valid date, <code>false</code> if not. */
    isValid: function(year, month, day) {
        var valid = main.baseCalendar.prototype.isValid.apply(this, arguments);
        if (valid) {
            year = (year.year != null ? year.year : year);
            valid = (year >= 1276 && year <= 1500);
        }
        return valid;
    },

    /** Check that a candidate date is from the same calendar and is valid.
        @memberof UmmAlQuraCalendar
        @private
        @param year {CDate|number} The date to validate or the year to validate.
        @param month {number} The month to validate.
        @param day {number} The day to validate.
        @param error {string} Error message if invalid.
        @throws Error if different calendars used or invalid date. */
    _validate: function(year, month, day, error) {
        var date = main.baseCalendar.prototype._validate.apply(this, arguments);
        if (date.year < 1276 || date.year > 1500) {
            throw error.replace(/\{0\}/, this.local.name);
        }
        return date;
    }
});

// UmmAlQura calendar implementation
main.calendars.ummalqura = UmmAlQuraCalendar;

var ummalqura_dat = [
    20,    50,    79,    109,   138,   168,   197,   227,   256,   286,   315,   345,   374,   404,   433,   463,   492,   522,   551,   581, 
    611,   641,   670,   700,   729,   759,   788,   818,   847,   877,   906,   936,   965,   995,   1024,  1054,  1083,  1113,  1142,  1172,
    1201,  1231,  1260,  1290,  1320,  1350,  1379,  1409,  1438,  1468,  1497,  1527,  1556,  1586,  1615,  1645,  1674,  1704,  1733,  1763,
    1792,  1822,  1851,  1881,  1910,  1940,  1969,  1999,  2028,  2058,  2087,  2117,  2146,  2176,  2205,  2235,  2264,  2294,  2323,  2353,
    2383,  2413,  2442,  2472,  2501,  2531,  2560,  2590,  2619,  2649,  2678,  2708,  2737,  2767,  2796,  2826,  2855,  2885,  2914,  2944,
    2973,  3003,  3032,  3062,  3091,  3121,  3150,  3180,  3209,  3239,  3268,  3298,  3327,  3357,  3386,  3416,  3446,  3476,  3505,  3535,
    3564,  3594,  3623,  3653,  3682,  3712,  3741,  3771,  3800,  3830,  3859,  3889,  3918,  3948,  3977,  4007,  4036,  4066,  4095,  4125,
    4155,  4185,  4214,  4244,  4273,  4303,  4332,  4362,  4391,  4421,  4450,  4480,  4509,  4539,  4568,  4598,  4627,  4657,  4686,  4716,
    4745,  4775,  4804,  4834,  4863,  4893,  4922,  4952,  4981,  5011,  5040,  5070,  5099,  5129,  5158,  5188,  5218,  5248,  5277,  5307,
    5336,  5366,  5395,  5425,  5454,  5484,  5513,  5543,  5572,  5602,  5631,  5661,  5690,  5720,  5749,  5779,  5808,  5838,  5867,  5897,
    5926,  5956,  5985,  6015,  6044,  6074,  6103,  6133,  6162,  6192,  6221,  6251,  6281,  6311,  6340,  6370,  6399,  6429,  6458,  6488,
    6517,  6547,  6576,  6606,  6635,  6665,  6694,  6724,  6753,  6783,  6812,  6842,  6871,  6901,  6930,  6960,  6989,  7019,  7048,  7078,
    7107,  7137,  7166,  7196,  7225,  7255,  7284,  7314,  7344,  7374,  7403,  7433,  7462,  7492,  7521,  7551,  7580,  7610,  7639,  7669,
    7698,  7728,  7757,  7787,  7816,  7846,  7875,  7905,  7934,  7964,  7993,  8023,  8053,  8083,  8112,  8142,  8171,  8201,  8230,  8260,
    8289,  8319,  8348,  8378,  8407,  8437,  8466,  8496,  8525,  8555,  8584,  8614,  8643,  8673,  8702,  8732,  8761,  8791,  8821,  8850,
    8880,  8909,  8938,  8968,  8997,  9027,  9056,  9086,  9115,  9145,  9175,  9205,  9234,  9264,  9293,  9322,  9352,  9381,  9410,  9440,
    9470,  9499,  9529,  9559,  9589,  9618,  9648,  9677,  9706,  9736,  9765,  9794,  9824,  9853,  9883,  9913,  9943,  9972,  10002, 10032,
    10061, 10090, 10120, 10149, 10178, 10208, 10237, 10267, 10297, 10326, 10356, 10386, 10415, 10445, 10474, 10504, 10533, 10562, 10592, 10621,
    10651, 10680, 10710, 10740, 10770, 10799, 10829, 10858, 10888, 10917, 10947, 10976, 11005, 11035, 11064, 11094, 11124, 11153, 11183, 11213,
    11242, 11272, 11301, 11331, 11360, 11389, 11419, 11448, 11478, 11507, 11537, 11567, 11596, 11626, 11655, 11685, 11715, 11744, 11774, 11803,
    11832, 11862, 11891, 11921, 11950, 11980, 12010, 12039, 12069, 12099, 12128, 12158, 12187, 12216, 12246, 12275, 12304, 12334, 12364, 12393,
    12423, 12453, 12483, 12512, 12542, 12571, 12600, 12630, 12659, 12688, 12718, 12747, 12777, 12807, 12837, 12866, 12896, 12926, 12955, 12984,
    13014, 13043, 13072, 13102, 13131, 13161, 13191, 13220, 13250, 13280, 13310, 13339, 13368, 13398, 13427, 13456, 13486, 13515, 13545, 13574,
    13604, 13634, 13664, 13693, 13723, 13752, 13782, 13811, 13840, 13870, 13899, 13929, 13958, 13988, 14018, 14047, 14077, 14107, 14136, 14166,
    14195, 14224, 14254, 14283, 14313, 14342, 14372, 14401, 14431, 14461, 14490, 14520, 14550, 14579, 14609, 14638, 14667, 14697, 14726, 14756,
    14785, 14815, 14844, 14874, 14904, 14933, 14963, 14993, 15021, 15051, 15081, 15110, 15140, 15169, 15199, 15228, 15258, 15287, 15317, 15347,
    15377, 15406, 15436, 15465, 15494, 15524, 15553, 15582, 15612, 15641, 15671, 15701, 15731, 15760, 15790, 15820, 15849, 15878, 15908, 15937,
    15966, 15996, 16025, 16055, 16085, 16114, 16144, 16174, 16204, 16233, 16262, 16292, 16321, 16350, 16380, 16409, 16439, 16468, 16498, 16528,
    16558, 16587, 16617, 16646, 16676, 16705, 16734, 16764, 16793, 16823, 16852, 16882, 16912, 16941, 16971, 17001, 17030, 17060, 17089, 17118,
    17148, 17177, 17207, 17236, 17266, 17295, 17325, 17355, 17384, 17414, 17444, 17473, 17502, 17532, 17561, 17591, 17620, 17650, 17679, 17709,
    17738, 17768, 17798, 17827, 17857, 17886, 17916, 17945, 17975, 18004, 18034, 18063, 18093, 18122, 18152, 18181, 18211, 18241, 18270, 18300,
    18330, 18359, 18388, 18418, 18447, 18476, 18506, 18535, 18565, 18595, 18625, 18654, 18684, 18714, 18743, 18772, 18802, 18831, 18860, 18890,
    18919, 18949, 18979, 19008, 19038, 19068, 19098, 19127, 19156, 19186, 19215, 19244, 19274, 19303, 19333, 19362, 19392, 19422, 19452, 19481,
    19511, 19540, 19570, 19599, 19628, 19658, 19687, 19717, 19746, 19776, 19806, 19836, 19865, 19895, 19924, 19954, 19983, 20012, 20042, 20071,
    20101, 20130, 20160, 20190, 20219, 20249, 20279, 20308, 20338, 20367, 20396, 20426, 20455, 20485, 20514, 20544, 20573, 20603, 20633, 20662,
    20692, 20721, 20751, 20780, 20810, 20839, 20869, 20898, 20928, 20957, 20987, 21016, 21046, 21076, 21105, 21135, 21164, 21194, 21223, 21253,
    21282, 21312, 21341, 21371, 21400, 21430, 21459, 21489, 21519, 21548, 21578, 21607, 21637, 21666, 21696, 21725, 21754, 21784, 21813, 21843,
    21873, 21902, 21932, 21962, 21991, 22021, 22050, 22080, 22109, 22138, 22168, 22197, 22227, 22256, 22286, 22316, 22346, 22375, 22405, 22434,
    22464, 22493, 22522, 22552, 22581, 22611, 22640, 22670, 22700, 22730, 22759, 22789, 22818, 22848, 22877, 22906, 22936, 22965, 22994, 23024,
    23054, 23083, 23113, 23143, 23173, 23202, 23232, 23261, 23290, 23320, 23349, 23379, 23408, 23438, 23467, 23497, 23527, 23556, 23586, 23616,
    23645, 23674, 23704, 23733, 23763, 23792, 23822, 23851, 23881, 23910, 23940, 23970, 23999, 24029, 24058, 24088, 24117, 24147, 24176, 24206,
    24235, 24265, 24294, 24324, 24353, 24383, 24413, 24442, 24472, 24501, 24531, 24560, 24590, 24619, 24648, 24678, 24707, 24737, 24767, 24796,
    24826, 24856, 24885, 24915, 24944, 24974, 25003, 25032, 25062, 25091, 25121, 25150, 25180, 25210, 25240, 25269, 25299, 25328, 25358, 25387,
    25416, 25446, 25475, 25505, 25534, 25564, 25594, 25624, 25653, 25683, 25712, 25742, 25771, 25800, 25830, 25859, 25888, 25918, 25948, 25977,
    26007, 26037, 26067, 26096, 26126, 26155, 26184, 26214, 26243, 26272, 26302, 26332, 26361, 26391, 26421, 26451, 26480, 26510, 26539, 26568,
    26598, 26627, 26656, 26686, 26715, 26745, 26775, 26805, 26834, 26864, 26893, 26923, 26952, 26982, 27011, 27041, 27070, 27099, 27129, 27159,
    27188, 27218, 27248, 27277, 27307, 27336, 27366, 27395, 27425, 27454, 27484, 27513, 27542, 27572, 27602, 27631, 27661, 27691, 27720, 27750,
    27779, 27809, 27838, 27868, 27897, 27926, 27956, 27985, 28015, 28045, 28074, 28104, 28134, 28163, 28193, 28222, 28252, 28281, 28310, 28340,
    28369, 28399, 28428, 28458, 28488, 28517, 28547, 28577,
    // From 1356
    28607, 28636, 28665, 28695, 28724, 28754, 28783, 28813, 28843, 28872, 28901, 28931, 28960, 28990, 29019, 29049, 29078, 29108, 29137, 29167,
    29196, 29226, 29255, 29285, 29315, 29345, 29375, 29404, 29434, 29463, 29492, 29522, 29551, 29580, 29610, 29640, 29669, 29699, 29729, 29759,
    29788, 29818, 29847, 29876, 29906, 29935, 29964, 29994, 30023, 30053, 30082, 30112, 30141, 30171, 30200, 30230, 30259, 30289, 30318, 30348,
    30378, 30408, 30437, 30467, 30496, 30526, 30555, 30585, 30614, 30644, 30673, 30703, 30732, 30762, 30791, 30821, 30850, 30880, 30909, 30939,
    30968, 30998, 31027, 31057, 31086, 31116, 31145, 31175, 31204, 31234, 31263, 31293, 31322, 31352, 31381, 31411, 31441, 31471, 31500, 31530,
    31559, 31589, 31618, 31648, 31676, 31706, 31736, 31766, 31795, 31825, 31854, 31884, 31913, 31943, 31972, 32002, 32031, 32061, 32090, 32120,
    32150, 32180, 32209, 32239, 32268, 32298, 32327, 32357, 32386, 32416, 32445, 32475, 32504, 32534, 32563, 32593, 32622, 32652, 32681, 32711,
    32740, 32770, 32799, 32829, 32858, 32888, 32917, 32947, 32976, 33006, 33035, 33065, 33094, 33124, 33153, 33183, 33213, 33243, 33272, 33302,
    33331, 33361, 33390, 33420, 33450, 33479, 33509, 33539, 33568, 33598, 33627, 33657, 33686, 33716, 33745, 33775, 33804, 33834, 33863, 33893,
    33922, 33952, 33981, 34011, 34040, 34069, 34099, 34128, 34158, 34187, 34217, 34247, 34277, 34306, 34336, 34365, 34395, 34424, 34454, 34483,
    34512, 34542, 34571, 34601, 34631, 34660, 34690, 34719, 34749, 34778, 34808, 34837, 34867, 34896, 34926, 34955, 34985, 35015, 35044, 35074,
    35103, 35133, 35162, 35192, 35222, 35251, 35280, 35310, 35340, 35370, 35399, 35429, 35458, 35488, 35517, 35547, 35576, 35605, 35635, 35665,
    35694, 35723, 35753, 35782, 35811, 35841, 35871, 35901, 35930, 35960, 35989, 36019, 36048, 36078, 36107, 36136, 36166, 36195, 36225, 36254,
    36284, 36314, 36343, 36373, 36403, 36433, 36462, 36492, 36521, 36551, 36580, 36610, 36639, 36669, 36698, 36728, 36757, 36786, 36816, 36845,
    36875, 36904, 36934, 36963, 36993, 37022, 37052, 37081, 37111, 37141, 37170, 37200, 37229, 37259, 37288, 37318, 37347, 37377, 37406, 37436,
    37465, 37495, 37524, 37554, 37584, 37613, 37643, 37672, 37701, 37731, 37760, 37790, 37819, 37849, 37878, 37908, 37938, 37967, 37997, 38027,
    38056, 38085, 38115, 38144, 38174, 38203, 38233, 38262, 38292, 38322, 38351, 38381, 38410, 38440, 38469, 38499, 38528, 38558, 38587, 38617,
    38646, 38676, 38705, 38735, 38764, 38794, 38823, 38853, 38882, 38912, 38941, 38971, 39001, 39030, 39059, 39089, 39118, 39148, 39178, 39208,
    39237, 39267, 39297, 39326, 39355, 39385, 39414, 39444, 39473, 39503, 39532, 39562, 39592, 39621, 39650, 39680, 39709, 39739, 39768, 39798,
    39827, 39857, 39886, 39916, 39946, 39975, 40005, 40035, 40064, 40094, 40123, 40153, 40182, 40212, 40241, 40271, 40300, 40330, 40359, 40389,
    40418, 40448, 40477, 40507, 40536, 40566, 40595, 40625, 40655, 40685, 40714, 40744, 40773, 40803, 40832, 40862, 40892, 40921, 40951, 40980,
    41009, 41039, 41068, 41098, 41127, 41157, 41186, 41216, 41245, 41275, 41304, 41334, 41364, 41393, 41422, 41452, 41481, 41511, 41540, 41570,
    41599, 41629, 41658, 41688, 41718, 41748, 41777, 41807, 41836, 41865, 41894, 41924, 41953, 41983, 42012, 42042, 42072, 42102, 42131, 42161,
    42190, 42220, 42249, 42279, 42308, 42337, 42367, 42397, 42426, 42456, 42485, 42515, 42545, 42574, 42604, 42633, 42662, 42692, 42721, 42751,
    42780, 42810, 42839, 42869, 42899, 42929, 42958, 42988, 43017, 43046, 43076, 43105, 43135, 43164, 43194, 43223, 43253, 43283, 43312, 43342,
    43371, 43401, 43430, 43460, 43489, 43519, 43548, 43578, 43607, 43637, 43666, 43696, 43726, 43755, 43785, 43814, 43844, 43873, 43903, 43932,
    43962, 43991, 44021, 44050, 44080, 44109, 44139, 44169, 44198, 44228, 44258, 44287, 44317, 44346, 44375, 44405, 44434, 44464, 44493, 44523,
    44553, 44582, 44612, 44641, 44671, 44700, 44730, 44759, 44788, 44818, 44847, 44877, 44906, 44936, 44966, 44996, 45025, 45055, 45084, 45114,
    45143, 45172, 45202, 45231, 45261, 45290, 45320, 45350, 45380, 45409, 45439, 45468, 45498, 45527, 45556, 45586, 45615, 45644, 45674, 45704,
    45733, 45763, 45793, 45823, 45852, 45882, 45911, 45940, 45970, 45999, 46028, 46058, 46088, 46117, 46147, 46177, 46206, 46236, 46265, 46295,
    46324, 46354, 46383, 46413, 46442, 46472, 46501, 46531, 46560, 46590, 46620, 46649, 46679, 46708, 46738, 46767, 46797, 46826, 46856, 46885,
    46915, 46944, 46974, 47003, 47033, 47063, 47092, 47122, 47151, 47181, 47210, 47240, 47269, 47298, 47328, 47357, 47387, 47417, 47446, 47476,
    47506, 47535, 47565, 47594, 47624, 47653, 47682, 47712, 47741, 47771, 47800, 47830, 47860, 47890, 47919, 47949, 47978, 48008, 48037, 48066,
    48096, 48125, 48155, 48184, 48214, 48244, 48273, 48303, 48333, 48362, 48392, 48421, 48450, 48480, 48509, 48538, 48568, 48598, 48627, 48657,
    48687, 48717, 48746, 48776, 48805, 48834, 48864, 48893, 48922, 48952, 48982, 49011, 49041, 49071, 49100, 49130, 49160, 49189, 49218, 49248,
    49277, 49306, 49336, 49365, 49395, 49425, 49455, 49484, 49514, 49543, 49573, 49602, 49632, 49661, 49690, 49720, 49749, 49779, 49809, 49838,
    49868, 49898, 49927, 49957, 49986, 50016, 50045, 50075, 50104, 50133, 50163, 50192, 50222, 50252, 50281, 50311, 50340, 50370, 50400, 50429,
    50459, 50488, 50518, 50547, 50576, 50606, 50635, 50665, 50694, 50724, 50754, 50784, 50813, 50843, 50872, 50902, 50931, 50960, 50990, 51019,
    51049, 51078, 51108, 51138, 51167, 51197, 51227, 51256, 51286, 51315, 51345, 51374, 51403, 51433, 51462, 51492, 51522, 51552, 51582, 51611,
    51641, 51670, 51699, 51729, 51758, 51787, 51816, 51846, 51876, 51906, 51936, 51965, 51995, 52025, 52054, 52083, 52113, 52142, 52171, 52200,
    52230, 52260, 52290, 52319, 52349, 52379, 52408, 52438, 52467, 52497, 52526, 52555, 52585, 52614, 52644, 52673, 52703, 52733, 52762, 52792,
    52822, 52851, 52881, 52910, 52939, 52969, 52998, 53028, 53057, 53087, 53116, 53146, 53176, 53205, 53235, 53264, 53294, 53324, 53353, 53383,
    53412, 53441, 53471, 53500, 53530, 53559, 53589, 53619, 53648, 53678, 53708, 53737, 53767, 53796, 53825, 53855, 53884, 53913, 53943, 53973,
    54003, 54032, 54062, 54092, 54121, 54151, 54180, 54209, 54239, 54268, 54297, 54327, 54357, 54387, 54416, 54446, 54476, 54505, 54535, 54564,
    54593, 54623, 54652, 54681, 54711, 54741, 54770, 54800, 54830, 54859, 54889, 54919, 54948, 54977, 55007, 55036, 55066, 55095, 55125, 55154,
    55184, 55213, 55243, 55273, 55302, 55332, 55361, 55391, 55420, 55450, 55479, 55508, 55538, 55567, 55597, 55627, 55657, 55686, 55716, 55745,
    55775, 55804, 55834, 55863, 55892, 55922, 55951, 55981, 56011, 56040, 56070, 56100, 56129, 56159, 56188, 56218, 56247, 56276, 56306, 56335,
    56365, 56394, 56424, 56454, 56483, 56513, 56543, 56572, 56601, 56631, 56660, 56690, 56719, 56749, 56778, 56808, 56837, 56867, 56897, 56926,
    56956, 56985, 57015, 57044, 57074, 57103, 57133, 57162, 57192, 57221, 57251, 57280, 57310, 57340, 57369, 57399, 57429, 57458, 57487, 57517,
    57546, 57576, 57605, 57634, 57664, 57694, 57723, 57753, 57783, 57813, 57842, 57871, 57901, 57930, 57959, 57989, 58018, 58048, 58077, 58107,
    58137, 58167, 58196, 58226, 58255, 58285, 58314, 58343, 58373, 58402, 58432, 58461, 58491, 58521, 58551, 58580, 58610, 58639, 58669, 58698,
    58727, 58757, 58786, 58816, 58845, 58875, 58905, 58934, 58964, 58994, 59023, 59053, 59082, 59111, 59141, 59170, 59200, 59229, 59259, 59288,
    59318, 59348, 59377, 59407, 59436, 59466, 59495, 59525, 59554, 59584, 59613, 59643, 59672, 59702, 59731, 59761, 59791, 59820, 59850, 59879,
    59909, 59939, 59968, 59997, 60027, 60056, 60086, 60115, 60145, 60174, 60204, 60234, 60264, 60293, 60323, 60352, 60381, 60411, 60440, 60469,
    60499, 60528, 60558, 60588, 60618, 60648, 60677, 60707, 60736, 60765, 60795, 60824, 60853, 60883, 60912, 60942, 60972, 61002, 61031, 61061,
    61090, 61120, 61149, 61179, 61208, 61237, 61267, 61296, 61326, 61356, 61385, 61415, 61445, 61474, 61504, 61533, 61563, 61592, 61621, 61651,
    61680, 61710, 61739, 61769, 61799, 61828, 61858, 61888, 61917, 61947, 61976, 62006, 62035, 62064, 62094, 62123, 62153, 62182, 62212, 62242,
    62271, 62301, 62331, 62360, 62390, 62419, 62448, 62478, 62507, 62537, 62566, 62596, 62625, 62655, 62685, 62715, 62744, 62774, 62803, 62832,
    62862, 62891, 62921, 62950, 62980, 63009, 63039, 63069, 63099, 63128, 63157, 63187, 63216, 63246, 63275, 63305, 63334, 63363, 63393, 63423,
    63453, 63482, 63512, 63541, 63571, 63600, 63630, 63659, 63689, 63718, 63747, 63777, 63807, 63836, 63866, 63895, 63925, 63955, 63984, 64014,
    64043, 64073, 64102, 64131, 64161, 64190, 64220, 64249, 64279, 64309, 64339, 64368, 64398, 64427, 64457, 64486, 64515, 64545, 64574, 64603,
    64633, 64663, 64692, 64722, 64752, 64782, 64811, 64841, 64870, 64899, 64929, 64958, 64987, 65017, 65047, 65076, 65106, 65136, 65166, 65195,
    65225, 65254, 65283, 65313, 65342, 65371, 65401, 65431, 65460, 65490, 65520, 65549, 65579, 65608, 65638, 65667, 65697, 65726, 65755, 65785,
    65815, 65844, 65874, 65903, 65933, 65963, 65992, 66022, 66051, 66081, 66110, 66140, 66169, 66199, 66228, 66258, 66287, 66317, 66346, 66376,
    66405, 66435, 66465, 66494, 66524, 66553, 66583, 66612, 66641, 66671, 66700, 66730, 66760, 66789, 66819, 66849, 66878, 66908, 66937, 66967,
    66996, 67025, 67055, 67084, 67114, 67143, 67173, 67203, 67233, 67262, 67292, 67321, 67351, 67380, 67409, 67439, 67468, 67497, 67527, 67557,
    67587, 67617, 67646, 67676, 67705, 67735, 67764, 67793, 67823, 67852, 67882, 67911, 67941, 67971, 68000, 68030, 68060, 68089, 68119, 68148,
    68177, 68207, 68236, 68266, 68295, 68325, 68354, 68384, 68414, 68443, 68473, 68502, 68532, 68561, 68591, 68620, 68650, 68679, 68708, 68738,
    68768, 68797, 68827, 68857, 68886, 68916, 68946, 68975, 69004, 69034, 69063, 69092, 69122, 69152, 69181, 69211, 69240, 69270, 69300, 69330,
    69359, 69388, 69418, 69447, 69476, 69506, 69535, 69565, 69595, 69624, 69654, 69684, 69713, 69743, 69772, 69802, 69831, 69861, 69890, 69919,
    69949, 69978, 70008, 70038, 70067, 70097, 70126, 70156, 70186, 70215, 70245, 70274, 70303, 70333, 70362, 70392, 70421, 70451, 70481, 70510,
    70540, 70570, 70599, 70629, 70658, 70687, 70717, 70746, 70776, 70805, 70835, 70864, 70894, 70924, 70954, 70983, 71013, 71042, 71071, 71101,
    71130, 71159, 71189, 71218, 71248, 71278, 71308, 71337, 71367, 71397, 71426, 71455, 71485, 71514, 71543, 71573, 71602, 71632, 71662, 71691,
    71721, 71751, 71781, 71810, 71839, 71869, 71898, 71927, 71957, 71986, 72016, 72046, 72075, 72105, 72135, 72164, 72194, 72223, 72253, 72282,
    72311, 72341, 72370, 72400, 72429, 72459, 72489, 72518, 72548, 72577, 72607, 72637, 72666, 72695, 72725, 72754, 72784, 72813, 72843, 72872,
    72902, 72931, 72961, 72991, 73020, 73050, 73080, 73109, 73139, 73168, 73197, 73227, 73256, 73286, 73315, 73345, 73375, 73404, 73434, 73464,
    73493, 73523, 73552, 73581, 73611, 73640, 73669, 73699, 73729, 73758, 73788, 73818, 73848, 73877, 73907, 73936, 73965, 73995, 74024, 74053,
    74083, 74113, 74142, 74172, 74202, 74231, 74261, 74291, 74320, 74349, 74379, 74408, 74437, 74467, 74497, 74526, 74556, 74586, 74615, 74645,
    74675, 74704, 74733, 74763, 74792, 74822, 74851, 74881, 74910, 74940, 74969, 74999, 75029, 75058, 75088, 75117, 75147, 75176, 75206, 75235,
    75264, 75294, 75323, 75353, 75383, 75412, 75442, 75472, 75501, 75531, 75560, 75590, 75619, 75648, 75678, 75707, 75737, 75766, 75796, 75826,
    75856, 75885, 75915, 75944, 75974, 76003, 76032, 76062, 76091, 76121, 76150, 76180, 76210, 76239, 76269, 76299, 76328, 76358, 76387, 76416,
    76446, 76475, 76505, 76534, 76564, 76593, 76623, 76653, 76682, 76712, 76741, 76771, 76801, 76830, 76859, 76889, 76918, 76948, 76977, 77007,
    77036, 77066, 77096, 77125, 77155, 77185, 77214, 77243, 77273, 77302, 77332, 77361, 77390, 77420, 77450, 77479, 77509, 77539, 77569, 77598,
    77627, 77657, 77686, 77715, 77745, 77774, 77804, 77833, 77863, 77893, 77923, 77952, 77982, 78011, 78041, 78070, 78099, 78129, 78158, 78188,
    78217, 78247, 78277, 78307, 78336, 78366, 78395, 78425, 78454, 78483, 78513, 78542, 78572, 78601, 78631, 78661, 78690, 78720, 78750, 78779,
    78808, 78838, 78867, 78897, 78926, 78956, 78985, 79015, 79044, 79074, 79104, 79133, 79163, 79192, 79222, 79251, 79281, 79310, 79340, 79369,
    79399, 79428, 79458, 79487, 79517, 79546, 79576, 79606, 79635, 79665, 79695, 79724, 79753, 79783, 79812, 79841, 79871, 79900, 79930, 79960,
    79990];


},{"../main":549,"object-assign":440}],549:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Calendars for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) August 2009.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var assign = _dereq_('object-assign');


function Calendars() {
    this.regionalOptions = [];
    this.regionalOptions[''] = {
        invalidCalendar: 'Calendar {0} not found',
        invalidDate: 'Invalid {0} date',
        invalidMonth: 'Invalid {0} month',
        invalidYear: 'Invalid {0} year',
        differentCalendars: 'Cannot mix {0} and {1} dates'
    };
    this.local = this.regionalOptions[''];
    this.calendars = {};
    this._localCals = {};
}

/** Create the calendars plugin.
    <p>Provides support for various world calendars in a consistent manner.</p>
     @class Calendars
    @example _exports.instance('julian').newDate(2014, 12, 25) */
assign(Calendars.prototype, {

    /** Obtain a calendar implementation and localisation.
        @memberof Calendars
        @param [name='gregorian'] {string} The name of the calendar, e.g. 'gregorian', 'persian', 'islamic'.
        @param [language=''] {string} The language code to use for localisation (default is English).
        @return {Calendar} The calendar and localisation.
        @throws Error if calendar not found. */
    instance: function(name, language) {
        name = (name || 'gregorian').toLowerCase();
        language = language || '';
        var cal = this._localCals[name + '-' + language];
        if (!cal && this.calendars[name]) {
            cal = new this.calendars[name](language);
            this._localCals[name + '-' + language] = cal;
        }
        if (!cal) {
            throw (this.local.invalidCalendar || this.regionalOptions[''].invalidCalendar).
                replace(/\{0\}/, name);
        }
        return cal;
    },

    /** Create a new date - for today if no other parameters given.
        @memberof Calendars
        @param year {CDate|number} The date to copy or the year for the date.
        @param [month] {number} The month for the date.
        @param [day] {number} The day for the date.
        @param [calendar='gregorian'] {BaseCalendar|string} The underlying calendar or the name of the calendar.
        @param [language=''] {string} The language to use for localisation (default English).
        @return {CDate} The new date.
        @throws Error if an invalid date. */
    newDate: function(year, month, day, calendar, language) {
        calendar = (year != null && year.year ? year.calendar() : (typeof calendar === 'string' ?
            this.instance(calendar, language) : calendar)) || this.instance();
        return calendar.newDate(year, month, day);
    },
    
    /** A simple digit substitution function for localising numbers via the Calendar digits option.
        @member Calendars
        @param digits {string[]} The substitute digits, for 0 through 9.
        @return {function} The substitution function. */
    substituteDigits: function(digits) {
        return function(value) {
            return (value + '').replace(/[0-9]/g, function(digit) {
                return digits[digit];
            });
        }
    },
    
    /** Digit substitution function for localising Chinese style numbers via the Calendar digits option.
        @member Calendars
        @param digits {string[]} The substitute digits, for 0 through 9.
        @param powers {string[]} The characters denoting powers of 10, i.e. 1, 10, 100, 1000.
        @return {function} The substitution function. */
    substituteChineseDigits: function(digits, powers) {
        return function(value) {
            var localNumber = '';
            var power = 0;
            while (value > 0) {
                var units = value % 10;
                localNumber = (units === 0 ? '' : digits[units] + powers[power]) + localNumber;
                power++;
                value = Math.floor(value / 10);
            }
            if (localNumber.indexOf(digits[1] + powers[1]) === 0) {
                localNumber = localNumber.substr(1);
            }
            return localNumber || digits[0];
        }
    }
});

/** Generic date, based on a particular calendar.
    @class CDate
    @param calendar {BaseCalendar} The underlying calendar implementation.
    @param year {number} The year for this date.
    @param month {number} The month for this date.
    @param day {number} The day for this date.
    @return {CDate} The date object.
    @throws Error if an invalid date. */
function CDate(calendar, year, month, day) {
    this._calendar = calendar;
    this._year = year;
    this._month = month;
    this._day = day;
    if (this._calendar._validateLevel === 0 &&
            !this._calendar.isValid(this._year, this._month, this._day)) {
        throw (_exports.local.invalidDate || _exports.regionalOptions[''].invalidDate).
            replace(/\{0\}/, this._calendar.local.name);
    }
}

/** Pad a numeric value with leading zeroes.
    @private
    @param value {number} The number to format.
    @param length {number} The minimum length.
    @return {string} The formatted number. */
function pad(value, length) {
    value = '' + value;
    return '000000'.substring(0, length - value.length) + value;
}

assign(CDate.prototype, {

    /** Create a new date.
        @memberof CDate
        @param [year] {CDate|number} The date to copy or the year for the date (default this date).
        @param [month] {number} The month for the date.
        @param [day] {number} The day for the date.
        @return {CDate} The new date.
        @throws Error if an invalid date. */
    newDate: function(year, month, day) {
        return this._calendar.newDate((year == null ? this : year), month, day);
    },

    /** Set or retrieve the year for this date.
        @memberof CDate
        @param [year] {number} The year for the date.
        @return {number|CDate} The date's year (if no parameter) or the updated date.
        @throws Error if an invalid date. */
    year: function(year) {
        return (arguments.length === 0 ? this._year : this.set(year, 'y'));
    },

    /** Set or retrieve the month for this date.
        @memberof CDate
        @param [month] {number} The month for the date.
        @return {number|CDate} The date's month (if no parameter) or the updated date.
        @throws Error if an invalid date. */
    month: function(month) {
        return (arguments.length === 0 ? this._month : this.set(month, 'm'));
    },

    /** Set or retrieve the day for this date.
        @memberof CDate
        @param [day] {number} The day for the date.
        @return {number|CData} The date's day (if no parameter) or the updated date.
        @throws Error if an invalid date. */
    day: function(day) {
        return (arguments.length === 0 ? this._day : this.set(day, 'd'));
    },

    /** Set new values for this date.
        @memberof CDate
        @param year {number} The year for the date.
        @param month {number} The month for the date.
        @param day {number} The day for the date.
        @return {CDate} The updated date.
        @throws Error if an invalid date. */
    date: function(year, month, day) {
        if (!this._calendar.isValid(year, month, day)) {
            throw (_exports.local.invalidDate || _exports.regionalOptions[''].invalidDate).
                replace(/\{0\}/, this._calendar.local.name);
        }
        this._year = year;
        this._month = month;
        this._day = day;
        return this;
    },

    /** Determine whether this date is in a leap year.
        @memberof CDate
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not. */
    leapYear: function() {
        return this._calendar.leapYear(this);
    },

    /** Retrieve the epoch designator for this date, e.g. BCE or CE.
        @memberof CDate
        @return {string} The current epoch. */
    epoch: function() {
        return this._calendar.epoch(this);
    },

    /** Format the year, if not a simple sequential number.
        @memberof CDate
        @return {string} The formatted year. */
    formatYear: function() {
        return this._calendar.formatYear(this);
    },

    /** Retrieve the month of the year for this date,
        i.e. the month's position within a numbered year.
        @memberof CDate
        @return {number} The month of the year: <code>minMonth</code> to months per year. */
    monthOfYear: function() {
        return this._calendar.monthOfYear(this);
    },

    /** Retrieve the week of the year for this date.
        @memberof CDate
        @return {number} The week of the year: 1 to weeks per year. */
    weekOfYear: function() {
        return this._calendar.weekOfYear(this);
    },

    /** Retrieve the number of days in the year for this date.
        @memberof CDate
        @return {number} The number of days in this year. */
    daysInYear: function() {
        return this._calendar.daysInYear(this);
    },

    /** Retrieve the day of the year for this date.
        @memberof CDate
        @return {number} The day of the year: 1 to days per year. */
    dayOfYear: function() {
        return this._calendar.dayOfYear(this);
    },

    /** Retrieve the number of days in the month for this date.
        @memberof CDate
        @return {number} The number of days. */
    daysInMonth: function() {
        return this._calendar.daysInMonth(this);
    },

    /** Retrieve the day of the week for this date.
        @memberof CDate
        @return {number} The day of the week: 0 to number of days - 1. */
    dayOfWeek: function() {
        return this._calendar.dayOfWeek(this);
    },

    /** Determine whether this date is a week day.
        @memberof CDate
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not. */
    weekDay: function() {
        return this._calendar.weekDay(this);
    },

    /** Retrieve additional information about this date.
        @memberof CDate
        @return {object} Additional information - contents depends on calendar. */
    extraInfo: function() {
        return this._calendar.extraInfo(this);
    },

    /** Add period(s) to a date.
        @memberof CDate
        @param offset {number} The number of periods to adjust by.
        @param period {string} One of 'y' for year, 'm' for month, 'w' for week, 'd' for day.
        @return {CDate} The updated date. */
    add: function(offset, period) {
        return this._calendar.add(this, offset, period);
    },

    /** Set a portion of the date.
        @memberof CDate
        @param value {number} The new value for the period.
        @param period {string} One of 'y' for year, 'm' for month, 'd' for day.
        @return {CDate} The updated date.
        @throws Error if not a valid date. */
    set: function(value, period) {
        return this._calendar.set(this, value, period);
    },

    /** Compare this date to another date.
        @memberof CDate
        @param date {CDate} The other date.
        @return {number} -1 if this date is before the other date,
                0 if they are equal, or +1 if this date is after the other date. */
    compareTo: function(date) {
        if (this._calendar.name !== date._calendar.name) {
            throw (_exports.local.differentCalendars || _exports.regionalOptions[''].differentCalendars).
                replace(/\{0\}/, this._calendar.local.name).replace(/\{1\}/, date._calendar.local.name);
        }
        var c = (this._year !== date._year ? this._year - date._year :
            this._month !== date._month ? this.monthOfYear() - date.monthOfYear() :
            this._day - date._day);
        return (c === 0 ? 0 : (c < 0 ? -1 : +1));
    },

    /** Retrieve the calendar backing this date.
        @memberof CDate
        @return {BaseCalendar} The calendar implementation. */
    calendar: function() {
        return this._calendar;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof CDate
        @return {number} The equivalent Julian date. */
    toJD: function() {
        return this._calendar.toJD(this);
    },

    /** Create a new date from a Julian date.
        @memberof CDate
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        return this._calendar.fromJD(jd);
    },

    /** Convert this date to a standard (Gregorian) JavaScript Date.
        @memberof CDate
        @return {Date} The equivalent JavaScript date. */
    toJSDate: function() {
        return this._calendar.toJSDate(this);
    },

    /** Create a new date from a standard (Gregorian) JavaScript Date.
        @memberof CDate
        @param jsd {Date} The JavaScript date to convert.
        @return {CDate} The equivalent date. */
    fromJSDate: function(jsd) {
        return this._calendar.fromJSDate(jsd);
    },

    /** Convert to a string for display.
        @memberof CDate
        @return {string} This date as a string. */
    toString: function() {
        return (this.year() < 0 ? '-' : '') + pad(Math.abs(this.year()), 4) +
            '-' + pad(this.month(), 2) + '-' + pad(this.day(), 2);
    }
});

/** Basic functionality for all calendars.
    Other calendars should extend this:
    <pre>OtherCalendar.prototype = new BaseCalendar;</pre>
    @class BaseCalendar */
function BaseCalendar() {
    this.shortYearCutoff = '+10';
}

assign(BaseCalendar.prototype, {
    _validateLevel: 0, // "Stack" to turn validation on/off

    /** Create a new date within this calendar - today if no parameters given.
        @memberof BaseCalendar
        @param year {CDate|number} The date to duplicate or the year for the date.
        @param [month] {number} The month for the date.
        @param [day] {number} The day for the date.
        @return {CDate} The new date.
        @throws Error if not a valid date or a different calendar used. */
    newDate: function(year, month, day) {
        if (year == null) {
            return this.today();
        }
        if (year.year) {
            this._validate(year, month, day,
                _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate);
            day = year.day();
            month = year.month();
            year = year.year();
        }
        return new CDate(this, year, month, day);
    },

    /** Create a new date for today.
        @memberof BaseCalendar
        @return {CDate} Today's date. */
    today: function() {
        return this.fromJSDate(new Date());
    },

    /** Retrieve the epoch designator for this date.
        @memberof BaseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {string} The current epoch.
        @throws Error if an invalid year or a different calendar used. */
    epoch: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay,
            _exports.local.invalidYear || _exports.regionalOptions[''].invalidYear);
        return (date.year() < 0 ? this.local.epochs[0] : this.local.epochs[1]);
    },

    /** Format the year, if not a simple sequential number
        @memberof BaseCalendar
        @param year {CDate|number} The date to format or the year to format.
        @return {string} The formatted year.
        @throws Error if an invalid year or a different calendar used. */
    formatYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay,
            _exports.local.invalidYear || _exports.regionalOptions[''].invalidYear);
        return (date.year() < 0 ? '-' : '') + pad(Math.abs(date.year()), 4)
    },

    /** Retrieve the number of months in a year.
        @memberof BaseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of months.
        @throws Error if an invalid year or a different calendar used. */
    monthsInYear: function(year) {
        this._validate(year, this.minMonth, this.minDay,
            _exports.local.invalidYear || _exports.regionalOptions[''].invalidYear);
        return 12;
    },

    /** Calculate the month's ordinal position within the year -
        for those calendars that don't start at month 1!
        @memberof BaseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param month {number} The month to examine.
        @return {number} The ordinal position, starting from <code>minMonth</code>.
        @throws Error if an invalid year/month or a different calendar used. */
    monthOfYear: function(year, month) {
        var date = this._validate(year, month, this.minDay,
            _exports.local.invalidMonth || _exports.regionalOptions[''].invalidMonth);
        return (date.month() + this.monthsInYear(date) - this.firstMonth) %
            this.monthsInYear(date) + this.minMonth;
    },

    /** Calculate actual month from ordinal position, starting from minMonth.
        @memberof BaseCalendar
        @param year {number} The year to examine.
        @param ord {number} The month's ordinal position.
        @return {number} The month's number.
        @throws Error if an invalid year/month. */
    fromMonthOfYear: function(year, ord) {
        var m = (ord + this.firstMonth - 2 * this.minMonth) %
            this.monthsInYear(year) + this.minMonth;
        this._validate(year, m, this.minDay,
            _exports.local.invalidMonth || _exports.regionalOptions[''].invalidMonth);
        return m;
    },

    /** Retrieve the number of days in a year.
        @memberof BaseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {number} The number of days.
        @throws Error if an invalid year or a different calendar used. */
    daysInYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay,
            _exports.local.invalidYear || _exports.regionalOptions[''].invalidYear);
        return (this.leapYear(date) ? 366 : 365);
    },

    /** Retrieve the day of the year for a date.
        @memberof BaseCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The day of the year.
        @throws Error if an invalid date or a different calendar used. */
    dayOfYear: function(year, month, day) {
        var date = this._validate(year, month, day,
            _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate);
        return date.toJD() - this.newDate(date.year(),
            this.fromMonthOfYear(date.year(), this.minMonth), this.minDay).toJD() + 1;
    },

    /** Retrieve the number of days in a week.
        @memberof BaseCalendar
        @return {number} The number of days. */
    daysInWeek: function() {
        return 7;
    },

    /** Retrieve the day of the week for a date.
        @memberof BaseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The day of the week: 0 to number of days - 1.
        @throws Error if an invalid date or a different calendar used. */
    dayOfWeek: function(year, month, day) {
        var date = this._validate(year, month, day,
            _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate);
        return (Math.floor(this.toJD(date)) + 2) % this.daysInWeek();
    },

    /** Retrieve additional information about a date.
        @memberof BaseCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {object} Additional information - contents depends on calendar.
        @throws Error if an invalid date or a different calendar used. */
    extraInfo: function(year, month, day) {
        this._validate(year, month, day,
            _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate);
        return {};
    },

    /** Add period(s) to a date.
        Cater for no year zero.
        @memberof BaseCalendar
        @param date {CDate} The starting date.
        @param offset {number} The number of periods to adjust by.
        @param period {string} One of 'y' for year, 'm' for month, 'w' for week, 'd' for day.
        @return {CDate} The updated date.
        @throws Error if a different calendar used. */
    add: function(date, offset, period) {
        this._validate(date, this.minMonth, this.minDay,
            _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate);
        return this._correctAdd(date, this._add(date, offset, period), offset, period);
    },

    /** Add period(s) to a date.
        @memberof BaseCalendar
        @private
        @param date {CDate} The starting date.
        @param offset {number} The number of periods to adjust by.
        @param period {string} One of 'y' for year, 'm' for month, 'w' for week, 'd' for day.
        @return {CDate} The updated date. */
    _add: function(date, offset, period) {
        this._validateLevel++;
        if (period === 'd' || period === 'w') {
            var jd = date.toJD() + offset * (period === 'w' ? this.daysInWeek() : 1);
            var d = date.calendar().fromJD(jd);
            this._validateLevel--;
            return [d.year(), d.month(), d.day()];
        }
        try {
            var y = date.year() + (period === 'y' ? offset : 0);
            var m = date.monthOfYear() + (period === 'm' ? offset : 0);
            var d = date.day();// + (period === 'd' ? offset : 0) +
                //(period === 'w' ? offset * this.daysInWeek() : 0);
            var resyncYearMonth = function(calendar) {
                while (m < calendar.minMonth) {
                    y--;
                    m += calendar.monthsInYear(y);
                }
                var yearMonths = calendar.monthsInYear(y);
                while (m > yearMonths - 1 + calendar.minMonth) {
                    y++;
                    m -= yearMonths;
                    yearMonths = calendar.monthsInYear(y);
                }
            };
            if (period === 'y') {
                if (date.month() !== this.fromMonthOfYear(y, m)) { // Hebrew
                    m = this.newDate(y, date.month(), this.minDay).monthOfYear();
                }
                m = Math.min(m, this.monthsInYear(y));
                d = Math.min(d, this.daysInMonth(y, this.fromMonthOfYear(y, m)));
            }
            else if (period === 'm') {
                resyncYearMonth(this);
                d = Math.min(d, this.daysInMonth(y, this.fromMonthOfYear(y, m)));
            }
            var ymd = [y, this.fromMonthOfYear(y, m), d];
            this._validateLevel--;
            return ymd;
        }
        catch (e) {
            this._validateLevel--;
            throw e;
        }
    },

    /** Correct a candidate date after adding period(s) to a date.
        Handle no year zero if necessary.
        @memberof BaseCalendar
        @private
        @param date {CDate} The starting date.
        @param ymd {number[]} The added date.
        @param offset {number} The number of periods to adjust by.
        @param period {string} One of 'y' for year, 'm' for month, 'w' for week, 'd' for day.
        @return {CDate} The updated date. */
    _correctAdd: function(date, ymd, offset, period) {
        if (!this.hasYearZero && (period === 'y' || period === 'm')) {
            if (ymd[0] === 0 || // In year zero
                    (date.year() > 0) !== (ymd[0] > 0)) { // Crossed year zero
                var adj = {y: [1, 1, 'y'], m: [1, this.monthsInYear(-1), 'm'],
                    w: [this.daysInWeek(), this.daysInYear(-1), 'd'],
                    d: [1, this.daysInYear(-1), 'd']}[period];
                var dir = (offset < 0 ? -1 : +1);
                ymd = this._add(date, offset * adj[0] + dir * adj[1], adj[2]);
            }
        }
        return date.date(ymd[0], ymd[1], ymd[2]);
    },

    /** Set a portion of the date.
        @memberof BaseCalendar
        @param date {CDate} The starting date.
        @param value {number} The new value for the period.
        @param period {string} One of 'y' for year, 'm' for month, 'd' for day.
        @return {CDate} The updated date.
        @throws Error if an invalid date or a different calendar used. */
    set: function(date, value, period) {
        this._validate(date, this.minMonth, this.minDay,
            _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate);
        var y = (period === 'y' ? value : date.year());
        var m = (period === 'm' ? value : date.month());
        var d = (period === 'd' ? value : date.day());
        if (period === 'y' || period === 'm') {
            d = Math.min(d, this.daysInMonth(y, m));
        }
        return date.date(y, m, d);
    },

    /** Determine whether a date is valid for this calendar.
        @memberof BaseCalendar
        @param year {number} The year to examine.
        @param month {number} The month to examine.
        @param day {number} The day to examine.
        @return {boolean} <code>true</code> if a valid date, <code>false</code> if not. */
    isValid: function(year, month, day) {
        this._validateLevel++;
        var valid = (this.hasYearZero || year !== 0);
        if (valid) {
            var date = this.newDate(year, month, this.minDay);
            valid = (month >= this.minMonth && month - this.minMonth < this.monthsInYear(date)) &&
                (day >= this.minDay && day - this.minDay < this.daysInMonth(date));
        }
        this._validateLevel--;
        return valid;
    },

    /** Convert the date to a standard (Gregorian) JavaScript Date.
        @memberof BaseCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {Date} The equivalent JavaScript date.
        @throws Error if an invalid date or a different calendar used. */
    toJSDate: function(year, month, day) {
        var date = this._validate(year, month, day,
            _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate);
        return _exports.instance().fromJD(this.toJD(date)).toJSDate();
    },

    /** Convert the date from a standard (Gregorian) JavaScript Date.
        @memberof BaseCalendar
        @param jsd {Date} The JavaScript date.
        @return {CDate} The equivalent calendar date. */
    fromJSDate: function(jsd) {
        return this.fromJD(_exports.instance().fromJSDate(jsd).toJD());
    },

    /** Check that a candidate date is from the same calendar and is valid.
        @memberof BaseCalendar
        @private
        @param year {CDate|number} The date to validate or the year to validate.
        @param [month] {number} The month to validate.
        @param [day] {number} The day to validate.
        @param error {string} Rrror message if invalid.
        @throws Error if different calendars used or invalid date. */
    _validate: function(year, month, day, error) {
        if (year.year) {
            if (this._validateLevel === 0 && this.name !== year.calendar().name) {
                throw (_exports.local.differentCalendars || _exports.regionalOptions[''].differentCalendars).
                    replace(/\{0\}/, this.local.name).replace(/\{1\}/, year.calendar().local.name);
            }
            return year;
        }
        try {
            this._validateLevel++;
            if (this._validateLevel === 1 && !this.isValid(year, month, day)) {
                throw error.replace(/\{0\}/, this.local.name);
            }
            var date = this.newDate(year, month, day);
            this._validateLevel--;
            return date;
        }
        catch (e) {
            this._validateLevel--;
            throw e;
        }
    }
});

/** Implementation of the Proleptic Gregorian Calendar.
    See <a href=":http://en.wikipedia.org/wiki/Gregorian_calendar">http://en.wikipedia.org/wiki/Gregorian_calendar</a>
    and <a href="http://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar">http://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar</a>.
    @class GregorianCalendar
    @augments BaseCalendar
    @param [language=''] {string} The language code (default English) for localisation. */
function GregorianCalendar(language) {
    this.local = this.regionalOptions[language] || this.regionalOptions[''];
}

GregorianCalendar.prototype = new BaseCalendar;

assign(GregorianCalendar.prototype, {
    /** The calendar name.
        @memberof GregorianCalendar */
    name: 'Gregorian',
     /** Julian date of start of Gregorian epoch: 1 January 0001 CE.
        @memberof GregorianCalendar */
    jdEpoch: 1721425.5,
     /** Days per month in a common year.
        @memberof GregorianCalendar */
    daysPerMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
     /** <code>true</code> if has a year zero, <code>false</code> if not.
        @memberof GregorianCalendar */
    hasYearZero: false,
    /** The minimum month number.
        @memberof GregorianCalendar */
    minMonth: 1,
    /** The first month in the year.
        @memberof GregorianCalendar */
    firstMonth: 1,
     /** The minimum day number.
        @memberof GregorianCalendar */
    minDay: 1,

    /** Localisations for the plugin.
        Entries are objects indexed by the language code ('' being the default US/English).
        Each object has the following attributes.
        @memberof GregorianCalendar
        @property name {string} The calendar name.
        @property epochs {string[]} The epoch names.
        @property monthNames {string[]} The long names of the months of the year.
        @property monthNamesShort {string[]} The short names of the months of the year.
        @property dayNames {string[]} The long names of the days of the week.
        @property dayNamesShort {string[]} The short names of the days of the week.
        @property dayNamesMin {string[]} The minimal names of the days of the week.
        @property dateFormat {string} The date format for this calendar.
                See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
        @property firstDay {number} The number of the first day of the week, starting at 0.
        @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
    regionalOptions: { // Localisations
        '': {
            name: 'Gregorian',
            epochs: ['BCE', 'CE'],
            monthNames: ['January', 'February', 'March', 'April', 'May', 'June',
            'July', 'August', 'September', 'October', 'November', 'December'],
            monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
            dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
            dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
            digits: null,
            dateFormat: 'mm/dd/yyyy',
            firstDay: 0,
            isRTL: false
        }
    },
    
    /** Determine whether this date is in a leap year.
        @memberof GregorianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
        @throws Error if an invalid year or a different calendar used. */
    leapYear: function(year) {
        var date = this._validate(year, this.minMonth, this.minDay,
            _exports.local.invalidYear || _exports.regionalOptions[''].invalidYear);
        var year = date.year() + (date.year() < 0 ? 1 : 0); // No year zero
        return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
    },

    /** Determine the week of the year for a date - ISO 8601.
        @memberof GregorianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {number} The week of the year, starting from 1.
        @throws Error if an invalid date or a different calendar used. */
    weekOfYear: function(year, month, day) {
        // Find Thursday of this week starting on Monday
        var checkDate = this.newDate(year, month, day);
        checkDate.add(4 - (checkDate.dayOfWeek() || 7), 'd');
        return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
    },

    /** Retrieve the number of days in a month.
        @memberof GregorianCalendar
        @param year {CDate|number} The date to examine or the year of the month.
        @param [month] {number} The month.
        @return {number} The number of days in this month.
        @throws Error if an invalid month/year or a different calendar used. */
    daysInMonth: function(year, month) {
        var date = this._validate(year, month, this.minDay,
            _exports.local.invalidMonth || _exports.regionalOptions[''].invalidMonth);
        return this.daysPerMonth[date.month() - 1] +
            (date.month() === 2 && this.leapYear(date.year()) ? 1 : 0);
    },

    /** Determine whether this date is a week day.
        @memberof GregorianCalendar
        @param year {CDate|number} The date to examine or the year to examine.
        @param [month] {number} The month to examine.
        @param [day] {number} The day to examine.
        @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
        @throws Error if an invalid date or a different calendar used. */
    weekDay: function(year, month, day) {
        return (this.dayOfWeek(year, month, day) || 7) < 6;
    },

    /** Retrieve the Julian date equivalent for this date,
        i.e. days since January 1, 4713 BCE Greenwich noon.
        @memberof GregorianCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {number} The equivalent Julian date.
        @throws Error if an invalid date or a different calendar used. */
    toJD: function(year, month, day) {
        var date = this._validate(year, month, day,
            _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate);
        year = date.year();
        month = date.month();
        day = date.day();
        if (year < 0) { year++; } // No year zero
        // Jean Meeus algorithm, "Astronomical Algorithms", 1991
        if (month < 3) {
            month += 12;
            year--;
        }
        var a = Math.floor(year / 100);
        var b = 2 - a + Math.floor(a / 4);
        return Math.floor(365.25 * (year + 4716)) +
            Math.floor(30.6001 * (month + 1)) + day + b - 1524.5;
    },

    /** Create a new date from a Julian date.
        @memberof GregorianCalendar
        @param jd {number} The Julian date to convert.
        @return {CDate} The equivalent date. */
    fromJD: function(jd) {
        // Jean Meeus algorithm, "Astronomical Algorithms", 1991
        var z = Math.floor(jd + 0.5);
        var a = Math.floor((z - 1867216.25) / 36524.25);
        a = z + 1 + a - Math.floor(a / 4);
        var b = a + 1524;
        var c = Math.floor((b - 122.1) / 365.25);
        var d = Math.floor(365.25 * c);
        var e = Math.floor((b - d) / 30.6001);
        var day = b - d - Math.floor(e * 30.6001);
        var month = e - (e > 13.5 ? 13 : 1);
        var year = c - (month > 2.5 ? 4716 : 4715);
        if (year <= 0) { year--; } // No year zero
        return this.newDate(year, month, day);
    },

    /** Convert this date to a standard (Gregorian) JavaScript Date.
        @memberof GregorianCalendar
        @param year {CDate|number} The date to convert or the year to convert.
        @param [month] {number} The month to convert.
        @param [day] {number} The day to convert.
        @return {Date} The equivalent JavaScript date.
        @throws Error if an invalid date or a different calendar used. */
    toJSDate: function(year, month, day) {
        var date = this._validate(year, month, day,
            _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate);
        var jsd = new Date(date.year(), date.month() - 1, date.day());
        jsd.setHours(0);
        jsd.setMinutes(0);
        jsd.setSeconds(0);
        jsd.setMilliseconds(0);
        // Hours may be non-zero on daylight saving cut-over:
        // > 12 when midnight changeover, but then cannot generate
        // midnight datetime, so jump to 1AM, otherwise reset.
        jsd.setHours(jsd.getHours() > 12 ? jsd.getHours() + 2 : 0);
        return jsd;
    },

    /** Create a new date from a standard (Gregorian) JavaScript Date.
        @memberof GregorianCalendar
        @param jsd {Date} The JavaScript date to convert.
        @return {CDate} The equivalent date. */
    fromJSDate: function(jsd) {
        return this.newDate(jsd.getFullYear(), jsd.getMonth() + 1, jsd.getDate());
    }
});

// Singleton manager
var _exports = module.exports = new Calendars();

// Date template
_exports.cdate = CDate;

// Base calendar template
_exports.baseCalendar = BaseCalendar;

// Gregorian calendar implementation
_exports.calendars.gregorian = GregorianCalendar;


},{"object-assign":440}],550:[function(_dereq_,module,exports){
/*
 * World Calendars
 * https://github.com/alexcjohnson/world-calendars
 *
 * Batch-converted from kbwood/calendars
 * Many thanks to Keith Wood and all of the contributors to the original project!
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

﻿/* http://keith-wood.name/calendars.html
   Calendars extras for jQuery v2.0.2.
   Written by Keith Wood (wood.keith{at}optusnet.com.au) August 2009.
   Available under the MIT (http://keith-wood.name/licence.html) license. 
   Please attribute the author if you use it. */

var assign = _dereq_('object-assign');
var main = _dereq_('./main');


assign(main.regionalOptions[''], {
    invalidArguments: 'Invalid arguments',
    invalidFormat: 'Cannot format a date from another calendar',
    missingNumberAt: 'Missing number at position {0}',
    unknownNameAt: 'Unknown name at position {0}',
    unexpectedLiteralAt: 'Unexpected literal at position {0}',
    unexpectedText: 'Additional text found at end'
});
main.local = main.regionalOptions[''];

assign(main.cdate.prototype, {

    /** Format this date.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof CDate
        @param [format] {string} The date format to use (see <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a>).
        @param [settings] {object} Options for the <code>formatDate</code> function.
        @return {string} The formatted date. */
    formatDate: function(format, settings) {
        if (typeof format !== 'string') {
            settings = format;
            format = '';
        }
        return this._calendar.formatDate(format || '', this, settings);
    }
});

assign(main.baseCalendar.prototype, {

    UNIX_EPOCH: main.instance().newDate(1970, 1, 1).toJD(),
    SECS_PER_DAY: 24 * 60 * 60,
    TICKS_EPOCH: main.instance().jdEpoch, // 1 January 0001 CE
    TICKS_PER_DAY: 24 * 60 * 60 * 10000000,

    /** Date form for ATOM (RFC 3339/ISO 8601).
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    ATOM: 'yyyy-mm-dd',
    /** Date form for cookies.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    COOKIE: 'D, dd M yyyy',
    /** Date form for full date.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    FULL: 'DD, MM d, yyyy',
    /** Date form for ISO 8601.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    ISO_8601: 'yyyy-mm-dd',
    /** Date form for Julian date.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    JULIAN: 'J',
    /** Date form for RFC 822.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    RFC_822: 'D, d M yy',
    /** Date form for RFC 850.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    RFC_850: 'DD, dd-M-yy',
    /** Date form for RFC 1036.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    RFC_1036: 'D, d M yy',
    /** Date form for RFC 1123.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    RFC_1123: 'D, d M yyyy',
    /** Date form for RFC 2822.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    RFC_2822: 'D, d M yyyy',
    /** Date form for RSS (RFC 822).
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    RSS: 'D, d M yy',
    /** Date form for Windows ticks.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    TICKS: '!',
    /** Date form for Unix timestamp.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    TIMESTAMP: '@',
    /** Date form for W3c (ISO 8601).
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar */
    W3C: 'yyyy-mm-dd',

    /** Format a date object into a string value.
        The format can be combinations of the following:
        <ul>
        <li>d  - day of month (no leading zero)</li>
        <li>dd - day of month (two digit)</li>
        <li>o  - day of year (no leading zeros)</li>
        <li>oo - day of year (three digit)</li>
        <li>D  - day name short</li>
        <li>DD - day name long</li>
        <li>w  - week of year (no leading zero)</li>
        <li>ww - week of year (two digit)</li>
        <li>m  - month of year (no leading zero)</li>
        <li>mm - month of year (two digit)</li>
        <li>M  - month name short</li>
        <li>MM - month name long</li>
        <li>yy - year (two digit)</li>
        <li>yyyy - year (four digit)</li>
        <li>YYYY - formatted year</li>
        <li>J  - Julian date (days since January 1, 4713 BCE Greenwich noon)</li>
        <li>@  - Unix timestamp (s since 01/01/1970)</li>
        <li>!  - Windows ticks (100ns since 01/01/0001)</li>
        <li>'...' - literal text</li>
        <li>'' - single quote</li>
        </ul>
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar
        @param [format] {string} The desired format of the date (defaults to calendar format).
        @param date {CDate} The date value to format.
        @param [settings] {object} Addition options, whose attributes include:
        @property [dayNamesShort] {string[]} Abbreviated names of the days from Sunday.
        @property [dayNames] {string[]} Names of the days from Sunday.
        @property [monthNamesShort] {string[]} Abbreviated names of the months.
        @property [monthNames] {string[]} Names of the months.
        @property [calculateWeek] {CalendarsPickerCalculateWeek} Function that determines week of the year.
        @property [localNumbers=false] {boolean} <code>true</code> to localise numbers (if available),
                  <code>false</code> to use normal Arabic numerals.
        @return {string} The date in the above format.
        @throws Errors if the date is from a different calendar. */
    formatDate: function(format, date, settings) {
        if (typeof format !== 'string') {
            settings = date;
            date = format;
            format = '';
        }
        if (!date) {
            return '';
        }
        if (date.calendar() !== this) {
            throw main.local.invalidFormat || main.regionalOptions[''].invalidFormat;
        }
        format = format || this.local.dateFormat;
        settings = settings || {};
        var dayNamesShort = settings.dayNamesShort || this.local.dayNamesShort;
        var dayNames = settings.dayNames || this.local.dayNames;
        var monthNumbers = settings.monthNumbers || this.local.monthNumbers;
        var monthNamesShort = settings.monthNamesShort || this.local.monthNamesShort;
        var monthNames = settings.monthNames || this.local.monthNames;
        var calculateWeek = settings.calculateWeek || this.local.calculateWeek;
        // Check whether a format character is doubled
        var doubled = function(match, step) {
            var matches = 1;
            while (iFormat + matches < format.length && format.charAt(iFormat + matches) === match) {
                matches++;
            }
            iFormat += matches - 1;
            return Math.floor(matches / (step || 1)) > 1;
        };
        // Format a number, with leading zeroes if necessary
        var formatNumber = function(match, value, len, step) {
            var num = '' + value;
            if (doubled(match, step)) {
                while (num.length < len) {
                    num = '0' + num;
                }
            }
            return num;
        };
        // Format a name, short or long as requested
        var formatName = function(match, value, shortNames, longNames) {
            return (doubled(match) ? longNames[value] : shortNames[value]);
        };
        // Format month number
        // (e.g. Chinese calendar needs to account for intercalary months)
        var calendar = this;
        var formatMonth = function(date) {
            return (typeof monthNumbers === 'function') ?
                monthNumbers.call(calendar, date, doubled('m')) :
                localiseNumbers(formatNumber('m', date.month(), 2));
        };
        // Format a month name, short or long as requested
        var formatMonthName = function(date, useLongName) {
            if (useLongName) {
                return (typeof monthNames === 'function') ?
                    monthNames.call(calendar, date) :
                    monthNames[date.month() - calendar.minMonth];
            } else {
                return (typeof monthNamesShort === 'function') ?
                    monthNamesShort.call(calendar, date) :
                    monthNamesShort[date.month() - calendar.minMonth];
            }
        };
        // Localise numbers if requested and available
        var digits = this.local.digits;
        var localiseNumbers = function(value) {
            return (settings.localNumbers && digits ? digits(value) : value);
        };
        var output = '';
        var literal = false;
        for (var iFormat = 0; iFormat < format.length; iFormat++) {
            if (literal) {
                if (format.charAt(iFormat) === "'" && !doubled("'")) {
                    literal = false;
                }
                else {
                    output += format.charAt(iFormat);
                }
            }
            else {
                switch (format.charAt(iFormat)) {
                    case 'd': output += localiseNumbers(formatNumber('d', date.day(), 2)); break;
                    case 'D': output += formatName('D', date.dayOfWeek(),
                        dayNamesShort, dayNames); break;
                    case 'o': output += formatNumber('o', date.dayOfYear(), 3); break;
                    case 'w': output += formatNumber('w', date.weekOfYear(), 2); break;
                    case 'm': output += formatMonth(date); break;
                    case 'M': output += formatMonthName(date, doubled('M')); break;
                    case 'y':
                        output += (doubled('y', 2) ? date.year() :
                            (date.year() % 100 < 10 ? '0' : '') + date.year() % 100);
                        break;
                    case 'Y':
                        doubled('Y', 2);
                        output += date.formatYear();
                        break;
                    case 'J': output += date.toJD(); break;
                    case '@': output += (date.toJD() - this.UNIX_EPOCH) * this.SECS_PER_DAY; break;
                    case '!': output += (date.toJD() - this.TICKS_EPOCH) * this.TICKS_PER_DAY; break;
                    case "'":
                        if (doubled("'")) {
                            output += "'";
                        }
                        else {
                            literal = true;
                        }
                        break;
                    default:
                        output += format.charAt(iFormat);
                }
            }
        }
        return output;
    },

    /** Parse a string value into a date object.
        See <a href="#formatDate"><code>formatDate</code></a> for the possible formats, plus:
        <ul>
        <li>* - ignore rest of string</li>
        </ul>
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar
        @param format {string} The expected format of the date ('' for default calendar format).
        @param value {string} The date in the above format.
        @param [settings] {object} Additional options whose attributes include:
        @property [shortYearCutoff] {number} The cutoff year for determining the century.
        @property [dayNamesShort] {string[]} Abbreviated names of the days from Sunday.
        @property [dayNames] {string[]} Names of the days from Sunday.
        @property [monthNamesShort] {string[]} Abbreviated names of the months.
        @property [monthNames] {string[]} Names of the months.
        @return {CDate} The extracted date value or <code>null</code> if value is blank.
        @throws Errors if the format and/or value are missing,
                if the value doesn't match the format, or if the date is invalid. */
    parseDate: function(format, value, settings) {
        if (value == null) {
            throw main.local.invalidArguments || main.regionalOptions[''].invalidArguments;
        }
        value = (typeof value === 'object' ? value.toString() : value + '');
        if (value === '') {
            return null;
        }
        format = format || this.local.dateFormat;
        settings = settings || {};
        var shortYearCutoff = settings.shortYearCutoff || this.shortYearCutoff;
        shortYearCutoff = (typeof shortYearCutoff !== 'string' ? shortYearCutoff :
            this.today().year() % 100 + parseInt(shortYearCutoff, 10));
        var dayNamesShort = settings.dayNamesShort || this.local.dayNamesShort;
        var dayNames = settings.dayNames || this.local.dayNames;
        var parseMonth = settings.parseMonth || this.local.parseMonth;
        var monthNumbers = settings.monthNumbers || this.local.monthNumbers;
        var monthNamesShort = settings.monthNamesShort || this.local.monthNamesShort;
        var monthNames = settings.monthNames || this.local.monthNames;
        var jd = -1;
        var year = -1;
        var month = -1;
        var day = -1;
        var doy = -1;
        var shortYear = false;
        var literal = false;
        // Check whether a format character is doubled
        var doubled = function(match, step) {
            var matches = 1;
            while (iFormat + matches < format.length && format.charAt(iFormat + matches) === match) {
                matches++;
            }
            iFormat += matches - 1;
            return Math.floor(matches / (step || 1)) > 1;
        };
        // Extract a number from the string value
        var getNumber = function(match, step) {
            var isDoubled = doubled(match, step);
            var size = [2, 3, isDoubled ? 4 : 2, isDoubled ? 4 : 2, 10, 11, 20]['oyYJ@!'.indexOf(match) + 1];
            var digits = new RegExp('^-?\\d{1,' + size + '}');
            var num = value.substring(iValue).match(digits);
            if (!num) {
                throw (main.local.missingNumberAt || main.regionalOptions[''].missingNumberAt).
                    replace(/\{0\}/, iValue);
            }
            iValue += num[0].length;
            return parseInt(num[0], 10);
        };
        // Extract a month number from the string value
        var calendar = this;
        var getMonthNumber = function() {
            if (typeof monthNumbers === 'function') {
                doubled('m');  // update iFormat
                var month = monthNumbers.call(calendar, value.substring(iValue));
                iValue += month.length;
                return month;
            }

            return getNumber('m');
        };
        // Extract a name from the string value and convert to an index
        var getName = function(match, shortNames, longNames, step) {
            var names = (doubled(match, step) ? longNames : shortNames);
            for (var i = 0; i < names.length; i++) {
                if (value.substr(iValue, names[i].length).toLowerCase() === names[i].toLowerCase()) {
                    iValue += names[i].length;
                    return i + calendar.minMonth;
                }
            }
            throw (main.local.unknownNameAt || main.regionalOptions[''].unknownNameAt).
                replace(/\{0\}/, iValue);
        };
        // Extract a month number from the string value
        var getMonthName = function() {
            if (typeof monthNames === 'function') {
                var month = doubled('M') ?
                    monthNames.call(calendar, value.substring(iValue)) :
                    monthNamesShort.call(calendar, value.substring(iValue));
                iValue += month.length;
                return month;
            }

            return getName('M', monthNamesShort, monthNames);
        };
        // Confirm that a literal character matches the string value
        var checkLiteral = function() {
            if (value.charAt(iValue) !== format.charAt(iFormat)) {
                throw (main.local.unexpectedLiteralAt ||
                    main.regionalOptions[''].unexpectedLiteralAt).replace(/\{0\}/, iValue);
            }
            iValue++;
        };
        var iValue = 0;
        for (var iFormat = 0; iFormat < format.length; iFormat++) {
            if (literal) {
                if (format.charAt(iFormat) === "'" && !doubled("'")) {
                    literal = false;
                }
                else {
                    checkLiteral();
                }
            }
            else {
                switch (format.charAt(iFormat)) {
                    case 'd': day = getNumber('d'); break;
                    case 'D': getName('D', dayNamesShort, dayNames); break;
                    case 'o': doy = getNumber('o'); break;
                    case 'w': getNumber('w'); break;
                    case 'm': month = getMonthNumber(); break;
                    case 'M': month = getMonthName(); break;
                    case 'y':
                        var iSave = iFormat;
                        shortYear = !doubled('y', 2);
                        iFormat = iSave;
                        year = getNumber('y', 2);
                        break;
                    case 'Y': year = getNumber('Y', 2); break;
                    case 'J':
                        jd = getNumber('J') + 0.5;
                        if (value.charAt(iValue) === '.') {
                            iValue++;
                            getNumber('J');
                        }
                        break;
                    case '@': jd = getNumber('@') / this.SECS_PER_DAY + this.UNIX_EPOCH; break;
                    case '!': jd = getNumber('!') / this.TICKS_PER_DAY + this.TICKS_EPOCH; break;
                    case '*': iValue = value.length; break;
                    case "'":
                        if (doubled("'")) {
                            checkLiteral();
                        }
                        else {
                            literal = true;
                        }
                        break;
                    default: checkLiteral();
                }
            }
        }
        if (iValue < value.length) {
            throw main.local.unexpectedText || main.regionalOptions[''].unexpectedText;
        }
        if (year === -1) {
            year = this.today().year();
        }
        else if (year < 100 && shortYear) {
            year += (shortYearCutoff === -1 ? 1900 : this.today().year() -
                this.today().year() % 100 - (year <= shortYearCutoff ? 0 : 100));
        }
        if (typeof month === 'string') {
            month = parseMonth.call(this, year, month);
        }
        if (doy > -1) {
            month = 1;
            day = doy;
            for (var dim = this.daysInMonth(year, month); day > dim; dim = this.daysInMonth(year, month)) {
                month++;
                day -= dim;
            }
        }
        return (jd > -1 ? this.fromJD(jd) : this.newDate(year, month, day));
    },

    /** A date may be specified as an exact value or a relative one.
        Found in the <code>jquery.calendars.plus.js</code> module.
        @memberof BaseCalendar
        @param dateSpec {CDate|number|string} The date as an object or string in the given format or
                an offset - numeric days from today, or string amounts and periods, e.g. '+1m +2w'.
        @param defaultDate {CDate} The date to use if no other supplied, may be <code>null</code>.
        @param currentDate {CDate} The current date as a possible basis for relative dates,
                if <code>null</code> today is used (optional)
        @param [dateFormat] {string} The expected date format - see <a href="#formatDate"><code>formatDate</code></a>.
        @param [settings] {object} Additional options whose attributes include:
        @property [shortYearCutoff] {number} The cutoff year for determining the century.
        @property [dayNamesShort] {string[]} Abbreviated names of the days from Sunday.
        @property [dayNames] {string[]} Names of the days from Sunday.
        @property [monthNamesShort] {string[]} Abbreviated names of the months.
        @property [monthNames] {string[]} Names of the months.
        @return {CDate} The decoded date. */
    determineDate: function(dateSpec, defaultDate, currentDate, dateFormat, settings) {
        if (currentDate && typeof currentDate !== 'object') {
            settings = dateFormat;
            dateFormat = currentDate;
            currentDate = null;
        }
        if (typeof dateFormat !== 'string') {
            settings = dateFormat;
            dateFormat = '';
        }
        var calendar = this;
        var offsetString = function(offset) {
            try {
                return calendar.parseDate(dateFormat, offset, settings);
            }
            catch (e) {
                // Ignore
            }
            offset = offset.toLowerCase();
            var date = (offset.match(/^c/) && currentDate ?
                currentDate.newDate() : null) || calendar.today();
            var pattern = /([+-]?[0-9]+)\s*(d|w|m|y)?/g;
            var matches = pattern.exec(offset);
            while (matches) {
                date.add(parseInt(matches[1], 10), matches[2] || 'd');
                matches = pattern.exec(offset);
            }
            return date;
        };
        defaultDate = (defaultDate ? defaultDate.newDate() : null);
        dateSpec = (dateSpec == null ? defaultDate :
            (typeof dateSpec === 'string' ? offsetString(dateSpec) : (typeof dateSpec === 'number' ?
            (isNaN(dateSpec) || dateSpec === Infinity || dateSpec === -Infinity ? defaultDate :
            calendar.today().add(dateSpec, 'd')) : calendar.newDate(dateSpec))));
        return dateSpec;
    }
});


},{"./main":549,"object-assign":440}],551:[function(_dereq_,module,exports){
module.exports = _dereq_('cwise-compiler')({
    args: ['array', {
        offset: [1],
        array: 0
    }, 'scalar', 'scalar', 'index'],
    pre: {
        "body": "{}",
        "args": [],
        "thisVars": [],
        "localVars": []
    },
    post: {
        "body": "{}",
        "args": [],
        "thisVars": [],
        "localVars": []
    },
    body: {
        "body": "{\n        var _inline_1_da = _inline_1_arg0_ - _inline_1_arg3_\n        var _inline_1_db = _inline_1_arg1_ - _inline_1_arg3_\n        if((_inline_1_da >= 0) !== (_inline_1_db >= 0)) {\n          _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n        }\n      }",
        "args": [{
            "name": "_inline_1_arg0_",
            "lvalue": false,
            "rvalue": true,
            "count": 1
        }, {
            "name": "_inline_1_arg1_",
            "lvalue": false,
            "rvalue": true,
            "count": 1
        }, {
            "name": "_inline_1_arg2_",
            "lvalue": false,
            "rvalue": true,
            "count": 1
        }, {
            "name": "_inline_1_arg3_",
            "lvalue": false,
            "rvalue": true,
            "count": 2
        }, {
            "name": "_inline_1_arg4_",
            "lvalue": false,
            "rvalue": true,
            "count": 1
        }],
        "thisVars": [],
        "localVars": ["_inline_1_da", "_inline_1_db"]
    },
    funcName: 'zeroCrossings'
})

},{"cwise-compiler":135}],552:[function(_dereq_,module,exports){
"use strict"

module.exports = findZeroCrossings

var core = _dereq_("./lib/zc-core")

function findZeroCrossings(array, level) {
  var cross = []
  level = +level || 0.0
  core(array.hi(array.shape[0]-1), cross, level)
  return cross
}
},{"./lib/zc-core":551}],553:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * All paths are tuned for maximum scalability of the arrowhead,
 * ie throughout arrowwidth=0.3..3 the head is joined smoothly
 * to the line, with the line coming from the left and ending at (0, 0).
 *
 * `backoff` is the distance to move the arrowhead and the end of the line,
 * in order that the arrowhead points to the desired place, either at
 * the tip of the arrow or (in the case of circle or square)
 * the center of the symbol.
 *
 * `noRotate`, if truthy, says that this arrowhead should not rotate with the
 * arrow. That's the case for squares, which should always be straight, and
 * circles, for which it's irrelevant.
 */

module.exports = [
    // no arrow
    {
        path: '',
        backoff: 0
    },
    // wide with flat back
    {
        path: 'M-2.4,-3V3L0.6,0Z',
        backoff: 0.6
    },
    // narrower with flat back
    {
        path: 'M-3.7,-2.5V2.5L1.3,0Z',
        backoff: 1.3
    },
    // barbed
    {
        path: 'M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z',
        backoff: 1.55
    },
    // wide line-drawn
    {
        path: 'M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z',
        backoff: 1.6
    },
    // narrower line-drawn
    {
        path: 'M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z',
        backoff: 2
    },
    // circle
    {
        path: 'M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z',
        backoff: 0,
        noRotate: true
    },
    // square
    {
        path: 'M2,2V-2H-2V2Z',
        backoff: 0,
        noRotate: true
    }
];

},{}],554:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var ARROWPATHS = _dereq_('./arrow_paths');
var fontAttrs = _dereq_('../../plots/font_attributes');
var cartesianConstants = _dereq_('../../plots/cartesian/constants');
var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;


module.exports = templatedArray('annotation', {
    visible: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'calc+arraydraw',
        
    },

    text: {
        valType: 'string',
        
        editType: 'calc+arraydraw',
        
    },
    textangle: {
        valType: 'angle',
        dflt: 0,
        
        editType: 'calc+arraydraw',
        
    },
    font: fontAttrs({
        editType: 'calc+arraydraw',
        colorEditType: 'arraydraw',
        
    }),
    width: {
        valType: 'number',
        min: 1,
        dflt: null,
        
        editType: 'calc+arraydraw',
        
    },
    height: {
        valType: 'number',
        min: 1,
        dflt: null,
        
        editType: 'calc+arraydraw',
        
    },
    opacity: {
        valType: 'number',
        min: 0,
        max: 1,
        dflt: 1,
        
        editType: 'arraydraw',
        
    },
    align: {
        valType: 'enumerated',
        values: ['left', 'center', 'right'],
        dflt: 'center',
        
        editType: 'arraydraw',
        
    },
    valign: {
        valType: 'enumerated',
        values: ['top', 'middle', 'bottom'],
        dflt: 'middle',
        
        editType: 'arraydraw',
        
    },
    bgcolor: {
        valType: 'color',
        dflt: 'rgba(0,0,0,0)',
        
        editType: 'arraydraw',
        
    },
    bordercolor: {
        valType: 'color',
        dflt: 'rgba(0,0,0,0)',
        
        editType: 'arraydraw',
        
    },
    borderpad: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'calc+arraydraw',
        
    },
    borderwidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'calc+arraydraw',
        
    },
    // arrow
    showarrow: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'calc+arraydraw',
        
    },
    arrowcolor: {
        valType: 'color',
        
        editType: 'arraydraw',
        
    },
    arrowhead: {
        valType: 'integer',
        min: 0,
        max: ARROWPATHS.length,
        dflt: 1,
        
        editType: 'arraydraw',
        
    },
    startarrowhead: {
        valType: 'integer',
        min: 0,
        max: ARROWPATHS.length,
        dflt: 1,
        
        editType: 'arraydraw',
        
    },
    arrowside: {
        valType: 'flaglist',
        flags: ['end', 'start'],
        extras: ['none'],
        dflt: 'end',
        
        editType: 'arraydraw',
        
    },
    arrowsize: {
        valType: 'number',
        min: 0.3,
        dflt: 1,
        
        editType: 'calc+arraydraw',
        
    },
    startarrowsize: {
        valType: 'number',
        min: 0.3,
        dflt: 1,
        
        editType: 'calc+arraydraw',
        
    },
    arrowwidth: {
        valType: 'number',
        min: 0.1,
        
        editType: 'calc+arraydraw',
        
    },
    standoff: {
        valType: 'number',
        min: 0,
        dflt: 0,
        
        editType: 'calc+arraydraw',
        
    },
    startstandoff: {
        valType: 'number',
        min: 0,
        dflt: 0,
        
        editType: 'calc+arraydraw',
        
    },
    ax: {
        valType: 'any',
        
        editType: 'calc+arraydraw',
        
    },
    ay: {
        valType: 'any',
        
        editType: 'calc+arraydraw',
        
    },
    axref: {
        valType: 'enumerated',
        dflt: 'pixel',
        values: [
            'pixel',
            cartesianConstants.idRegex.x.toString()
        ],
        
        editType: 'calc',
        
    },
    ayref: {
        valType: 'enumerated',
        dflt: 'pixel',
        values: [
            'pixel',
            cartesianConstants.idRegex.y.toString()
        ],
        
        editType: 'calc',
        
    },
    // positioning
    xref: {
        valType: 'enumerated',
        values: [
            'paper',
            cartesianConstants.idRegex.x.toString()
        ],
        
        editType: 'calc',
        
    },
    x: {
        valType: 'any',
        
        editType: 'calc+arraydraw',
        
    },
    xanchor: {
        valType: 'enumerated',
        values: ['auto', 'left', 'center', 'right'],
        dflt: 'auto',
        
        editType: 'calc+arraydraw',
        
    },
    xshift: {
        valType: 'number',
        dflt: 0,
        
        editType: 'calc+arraydraw',
        
    },
    yref: {
        valType: 'enumerated',
        values: [
            'paper',
            cartesianConstants.idRegex.y.toString()
        ],
        
        editType: 'calc',
        
    },
    y: {
        valType: 'any',
        
        editType: 'calc+arraydraw',
        
    },
    yanchor: {
        valType: 'enumerated',
        values: ['auto', 'top', 'middle', 'bottom'],
        dflt: 'auto',
        
        editType: 'calc+arraydraw',
        
    },
    yshift: {
        valType: 'number',
        dflt: 0,
        
        editType: 'calc+arraydraw',
        
    },
    clicktoshow: {
        valType: 'enumerated',
        values: [false, 'onoff', 'onout'],
        dflt: false,
        
        editType: 'arraydraw',
        
    },
    xclick: {
        valType: 'any',
        
        editType: 'arraydraw',
        
    },
    yclick: {
        valType: 'any',
        
        editType: 'arraydraw',
        
    },
    hovertext: {
        valType: 'string',
        
        editType: 'arraydraw',
        
    },
    hoverlabel: {
        bgcolor: {
            valType: 'color',
            
            editType: 'arraydraw',
            
        },
        bordercolor: {
            valType: 'color',
            
            editType: 'arraydraw',
            
        },
        font: fontAttrs({
            editType: 'arraydraw',
            
        }),
        editType: 'arraydraw'
    },
    captureevents: {
        valType: 'boolean',
        
        editType: 'arraydraw',
        
    },
    editType: 'calc',

    _deprecated: {
        ref: {
            valType: 'string',
            
            editType: 'calc',
            
        }
    }
});

},{"../../plot_api/plot_template":732,"../../plots/cartesian/constants":748,"../../plots/font_attributes":769,"./arrow_paths":553}],555:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');

var draw = _dereq_('./draw').draw;


module.exports = function calcAutorange(gd) {
    var fullLayout = gd._fullLayout;
    var annotationList = Lib.filterVisible(fullLayout.annotations);

    if(annotationList.length && gd._fullData.length) {
        return Lib.syncOrAsync([draw, annAutorange], gd);
    }
};

function annAutorange(gd) {
    var fullLayout = gd._fullLayout;

    // find the bounding boxes for each of these annotations'
    // relative to their anchor points
    // use the arrow and the text bg rectangle,
    // as the whole anno may include hidden text in its bbox
    Lib.filterVisible(fullLayout.annotations).forEach(function(ann) {
        var xa = Axes.getFromId(gd, ann.xref);
        var ya = Axes.getFromId(gd, ann.yref);

        ann._extremes = {};
        if(xa) calcAxisExpansion(ann, xa);
        if(ya) calcAxisExpansion(ann, ya);
    });
}

function calcAxisExpansion(ann, ax) {
    var axId = ax._id;
    var letter = axId.charAt(0);
    var pos = ann[letter];
    var apos = ann['a' + letter];
    var ref = ann[letter + 'ref'];
    var aref = ann['a' + letter + 'ref'];
    var padplus = ann['_' + letter + 'padplus'];
    var padminus = ann['_' + letter + 'padminus'];
    var shift = {x: 1, y: -1}[letter] * ann[letter + 'shift'];
    var headSize = 3 * ann.arrowsize * ann.arrowwidth || 0;
    var headPlus = headSize + shift;
    var headMinus = headSize - shift;
    var startHeadSize = 3 * ann.startarrowsize * ann.arrowwidth || 0;
    var startHeadPlus = startHeadSize + shift;
    var startHeadMinus = startHeadSize - shift;
    var extremes;

    if(aref === ref) {
        // expand for the arrowhead (padded by arrowhead)
        var extremeArrowHead = Axes.findExtremes(ax, [ax.r2c(pos)], {
            ppadplus: headPlus,
            ppadminus: headMinus
        });
        // again for the textbox (padded by textbox)
        var extremeText = Axes.findExtremes(ax, [ax.r2c(apos)], {
            ppadplus: Math.max(padplus, startHeadPlus),
            ppadminus: Math.max(padminus, startHeadMinus)
        });
        extremes = {
            min: [extremeArrowHead.min[0], extremeText.min[0]],
            max: [extremeArrowHead.max[0], extremeText.max[0]]
        };
    } else {
        startHeadPlus = apos ? startHeadPlus + apos : startHeadPlus;
        startHeadMinus = apos ? startHeadMinus - apos : startHeadMinus;
        extremes = Axes.findExtremes(ax, [ax.r2c(pos)], {
            ppadplus: Math.max(padplus, headPlus, startHeadPlus),
            ppadminus: Math.max(padminus, headMinus, startHeadMinus)
        });
    }

    ann._extremes[axId] = extremes;
}

},{"../../lib":694,"../../plots/cartesian/axes":742,"./draw":560}],556:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Registry = _dereq_('../../registry');
var arrayEditor = _dereq_('../../plot_api/plot_template').arrayEditor;

module.exports = {
    hasClickToShow: hasClickToShow,
    onClick: onClick
};

/*
 * hasClickToShow: does the given hoverData have ANY annotations which will
 * turn ON if we click here? (used by hover events to set cursor)
 *
 * gd: graphDiv
 * hoverData: a hoverData array, as included with the *plotly_hover* or
 *     *plotly_click* events in the `points` attribute
 *
 * returns: boolean
 */
function hasClickToShow(gd, hoverData) {
    var sets = getToggleSets(gd, hoverData);
    return sets.on.length > 0 || sets.explicitOff.length > 0;
}

/*
 * onClick: perform the toggling (via Plotly.update) implied by clicking
 * at this hoverData
 *
 * gd: graphDiv
 * hoverData: a hoverData array, as included with the *plotly_hover* or
 *     *plotly_click* events in the `points` attribute
 *
 * returns: Promise that the update is complete
 */
function onClick(gd, hoverData) {
    var toggleSets = getToggleSets(gd, hoverData);
    var onSet = toggleSets.on;
    var offSet = toggleSets.off.concat(toggleSets.explicitOff);
    var update = {};
    var annotationsOut = gd._fullLayout.annotations;
    var i, editHelpers;

    if(!(onSet.length || offSet.length)) return;

    for(i = 0; i < onSet.length; i++) {
        editHelpers = arrayEditor(gd.layout, 'annotations', annotationsOut[onSet[i]]);
        editHelpers.modifyItem('visible', true);
        Lib.extendFlat(update, editHelpers.getUpdateObj());
    }

    for(i = 0; i < offSet.length; i++) {
        editHelpers = arrayEditor(gd.layout, 'annotations', annotationsOut[offSet[i]]);
        editHelpers.modifyItem('visible', false);
        Lib.extendFlat(update, editHelpers.getUpdateObj());
    }

    return Registry.call('update', gd, {}, update);
}

/*
 * getToggleSets: find the annotations which will turn on or off at this
 * hoverData
 *
 * gd: graphDiv
 * hoverData: a hoverData array, as included with the *plotly_hover* or
 *     *plotly_click* events in the `points` attribute
 *
 * returns: {
 *   on: Array (indices of annotations to turn on),
 *   off: Array (indices to turn off because you're not hovering on them),
 *   explicitOff: Array (indices to turn off because you *are* hovering on them)
 * }
 */
function getToggleSets(gd, hoverData) {
    var annotations = gd._fullLayout.annotations;
    var onSet = [];
    var offSet = [];
    var explicitOffSet = [];
    var hoverLen = (hoverData || []).length;

    var i, j, anni, showMode, pointj, xa, ya, toggleType;

    for(i = 0; i < annotations.length; i++) {
        anni = annotations[i];
        showMode = anni.clicktoshow;

        if(showMode) {
            for(j = 0; j < hoverLen; j++) {
                pointj = hoverData[j];
                xa = pointj.xaxis;
                ya = pointj.yaxis;

                if(xa._id === anni.xref &&
                    ya._id === anni.yref &&
                    xa.d2r(pointj.x) === clickData2r(anni._xclick, xa) &&
                    ya.d2r(pointj.y) === clickData2r(anni._yclick, ya)
                ) {
                    // match! toggle this annotation
                    // regardless of its clicktoshow mode
                    // but if it's onout mode, off is implicit
                    if(anni.visible) {
                        if(showMode === 'onout') toggleType = offSet;
                        else toggleType = explicitOffSet;
                    }
                    else {
                        toggleType = onSet;
                    }
                    toggleType.push(i);
                    break;
                }
            }

            if(j === hoverLen) {
                // no match - only turn this annotation OFF, and only if
                // showmode is 'onout'
                if(anni.visible && showMode === 'onout') offSet.push(i);
            }
        }
    }

    return {on: onSet, off: offSet, explicitOff: explicitOffSet};
}

// to handle log axes until v2
function clickData2r(d, ax) {
    return ax.type === 'log' ? ax.l2r(d) : ax.d2r(d);
}

},{"../../lib":694,"../../plot_api/plot_template":732,"../../registry":825}],557:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Color = _dereq_('../color');

// defaults common to 'annotations' and 'annotations3d'
module.exports = function handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce) {
    coerce('opacity');
    var bgColor = coerce('bgcolor');

    var borderColor = coerce('bordercolor');
    var borderOpacity = Color.opacity(borderColor);

    coerce('borderpad');

    var borderWidth = coerce('borderwidth');
    var showArrow = coerce('showarrow');

    coerce('text', showArrow ? ' ' : fullLayout._dfltTitle.annotation);
    coerce('textangle');
    Lib.coerceFont(coerce, 'font', fullLayout.font);

    coerce('width');
    coerce('align');

    var h = coerce('height');
    if(h) coerce('valign');

    if(showArrow) {
        var arrowside = coerce('arrowside');
        var arrowhead;
        var arrowsize;

        if(arrowside.indexOf('end') !== -1) {
            arrowhead = coerce('arrowhead');
            arrowsize = coerce('arrowsize');
        }

        if(arrowside.indexOf('start') !== -1) {
            coerce('startarrowhead', arrowhead);
            coerce('startarrowsize', arrowsize);
        }
        coerce('arrowcolor', borderOpacity ? annOut.bordercolor : Color.defaultLine);
        coerce('arrowwidth', ((borderOpacity && borderWidth) || 1) * 2);
        coerce('standoff');
        coerce('startstandoff');

    }

    var hoverText = coerce('hovertext');
    var globalHoverLabel = fullLayout.hoverlabel || {};

    if(hoverText) {
        var hoverBG = coerce('hoverlabel.bgcolor', globalHoverLabel.bgcolor ||
            (Color.opacity(bgColor) ? Color.rgb(bgColor) : Color.defaultLine)
        );

        var hoverBorder = coerce('hoverlabel.bordercolor', globalHoverLabel.bordercolor ||
            Color.contrast(hoverBG)
        );

        Lib.coerceFont(coerce, 'hoverlabel.font', {
            family: globalHoverLabel.font.family,
            size: globalHoverLabel.font.size,
            color: globalHoverLabel.font.color || hoverBorder
        });
    }

    coerce('captureevents', !!hoverText);
};

},{"../../lib":694,"../color":571}],558:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var toLogRange = _dereq_('../../lib/to_log_range');

/*
 * convertCoords: when converting an axis between log and linear
 * you need to alter any annotations on that axis to keep them
 * pointing at the same data point.
 * In v2.0 this will become obsolete
 *
 * gd: the plot div
 * ax: the axis being changed
 * newType: the type it's getting
 * doExtra: function(attr, val) from inside relayout that sets the attribute.
 *     Use this to make the changes as it's aware if any other changes in the
 *     same relayout call should override this conversion.
 */
module.exports = function convertCoords(gd, ax, newType, doExtra) {
    ax = ax || {};

    var toLog = (newType === 'log') && (ax.type === 'linear');
    var fromLog = (newType === 'linear') && (ax.type === 'log');

    if(!(toLog || fromLog)) return;

    var annotations = gd._fullLayout.annotations;
    var axLetter = ax._id.charAt(0);
    var ann;
    var attrPrefix;

    function convert(attr) {
        var currentVal = ann[attr];
        var newVal = null;

        if(toLog) newVal = toLogRange(currentVal, ax.range);
        else newVal = Math.pow(10, currentVal);

        // if conversion failed, delete the value so it gets a default value
        if(!isNumeric(newVal)) newVal = null;

        doExtra(attrPrefix + attr, newVal);
    }

    for(var i = 0; i < annotations.length; i++) {
        ann = annotations[i];
        attrPrefix = 'annotations[' + i + '].';

        if(ann[axLetter + 'ref'] === ax._id) convert(axLetter);
        if(ann['a' + axLetter + 'ref'] === ax._id) convert('a' + axLetter);
    }
};

},{"../../lib/to_log_range":720,"fast-isnumeric":215}],559:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');
var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');

var handleAnnotationCommonDefaults = _dereq_('./common_defaults');
var attributes = _dereq_('./attributes');


module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
    handleArrayContainerDefaults(layoutIn, layoutOut, {
        name: 'annotations',
        handleItemDefaults: handleAnnotationDefaults
    });
};

function handleAnnotationDefaults(annIn, annOut, fullLayout) {
    function coerce(attr, dflt) {
        return Lib.coerce(annIn, annOut, attributes, attr, dflt);
    }

    var visible = coerce('visible');
    var clickToShow = coerce('clicktoshow');

    if(!(visible || clickToShow)) return;

    handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce);

    var showArrow = annOut.showarrow;

    // positioning
    var axLetters = ['x', 'y'];
    var arrowPosDflt = [-10, -30];
    var gdMock = {_fullLayout: fullLayout};

    for(var i = 0; i < 2; i++) {
        var axLetter = axLetters[i];

        // xref, yref
        var axRef = Axes.coerceRef(annIn, annOut, gdMock, axLetter, '', 'paper');

        if(axRef !== 'paper') {
            var ax = Axes.getFromId(gdMock, axRef);
            ax._annIndices.push(annOut._index);
        }

        // x, y
        Axes.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5);

        if(showArrow) {
            var arrowPosAttr = 'a' + axLetter;
            // axref, ayref
            var aaxRef = Axes.coerceRef(annIn, annOut, gdMock, arrowPosAttr, 'pixel');

            // for now the arrow can only be on the same axis or specified as pixels
            // TODO: sometime it might be interesting to allow it to be on *any* axis
            // but that would require updates to drawing & autorange code and maybe more
            if(aaxRef !== 'pixel' && aaxRef !== axRef) {
                aaxRef = annOut[arrowPosAttr] = 'pixel';
            }

            // ax, ay
            var aDflt = (aaxRef === 'pixel') ? arrowPosDflt[i] : 0.4;
            Axes.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt);
        }

        // xanchor, yanchor
        coerce(axLetter + 'anchor');

        // xshift, yshift
        coerce(axLetter + 'shift');
    }

    // if you have one coordinate you should have both
    Lib.noneOrAll(annIn, annOut, ['x', 'y']);

    // if you have one part of arrow length you should have both
    if(showArrow) {
        Lib.noneOrAll(annIn, annOut, ['ax', 'ay']);
    }

    if(clickToShow) {
        var xClick = coerce('xclick');
        var yClick = coerce('yclick');

        // put the actual click data to bind to into private attributes
        // so we don't have to do this little bit of logic on every hover event
        annOut._xclick = (xClick === undefined) ?
            annOut.x :
            Axes.cleanPosition(xClick, gdMock, annOut.xref);
        annOut._yclick = (yClick === undefined) ?
            annOut.y :
            Axes.cleanPosition(yClick, gdMock, annOut.yref);
    }
}

},{"../../lib":694,"../../plots/array_container_defaults":738,"../../plots/cartesian/axes":742,"./attributes":554,"./common_defaults":557}],560:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Registry = _dereq_('../../registry');
var Plots = _dereq_('../../plots/plots');
var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');
var Color = _dereq_('../color');
var Drawing = _dereq_('../drawing');
var Fx = _dereq_('../fx');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var setCursor = _dereq_('../../lib/setcursor');
var dragElement = _dereq_('../dragelement');
var arrayEditor = _dereq_('../../plot_api/plot_template').arrayEditor;

var drawArrowHead = _dereq_('./draw_arrow_head');

// Annotations are stored in gd.layout.annotations, an array of objects
// index can point to one item in this array,
//  or non-numeric to simply add a new one
//  or -1 to modify all existing
// opt can be the full options object, or one key (to be set to value)
//  or undefined to simply redraw
// if opt is blank, val can be 'add' or a full options object to add a new
//  annotation at that point in the array, or 'remove' to delete this one

module.exports = {
    draw: draw,
    drawOne: drawOne,
    drawRaw: drawRaw
};

/*
 * draw: draw all annotations without any new modifications
 */
function draw(gd) {
    var fullLayout = gd._fullLayout;

    fullLayout._infolayer.selectAll('.annotation').remove();

    for(var i = 0; i < fullLayout.annotations.length; i++) {
        if(fullLayout.annotations[i].visible) {
            drawOne(gd, i);
        }
    }

    return Plots.previousPromises(gd);
}

/*
 * drawOne: draw a single cartesian or paper-ref annotation, potentially with modifications
 *
 * index (int): the annotation to draw
 */
function drawOne(gd, index) {
    var fullLayout = gd._fullLayout;
    var options = fullLayout.annotations[index] || {};
    var xa = Axes.getFromId(gd, options.xref);
    var ya = Axes.getFromId(gd, options.yref);

    if(xa) xa.setScale();
    if(ya) ya.setScale();

    drawRaw(gd, options, index, false, xa, ya);
}

/**
 * drawRaw: draw a single annotation, potentially with modifications
 *
 * @param {DOM element} gd
 * @param {object} options : this annotation's fullLayout options
 * @param {integer} index : index in 'annotations' container of the annotation to draw
 * @param {string} subplotId : id of the annotation's subplot
 *  - use false for 2d (i.e. cartesian or paper-ref) annotations
 * @param {object | undefined} xa : full x-axis object to compute subplot pos-to-px
 * @param {object | undefined} ya : ... y-axis
 */
function drawRaw(gd, options, index, subplotId, xa, ya) {
    var fullLayout = gd._fullLayout;
    var gs = gd._fullLayout._size;
    var edits = gd._context.edits;

    var className, containerStr;

    if(subplotId) {
        className = 'annotation-' + subplotId;
        containerStr = subplotId + '.annotations';
    } else {
        className = 'annotation';
        containerStr = 'annotations';
    }

    var editHelpers = arrayEditor(gd.layout, containerStr, options);
    var modifyBase = editHelpers.modifyBase;
    var modifyItem = editHelpers.modifyItem;
    var getUpdateObj = editHelpers.getUpdateObj;

    // remove the existing annotation if there is one
    fullLayout._infolayer
        .selectAll('.' + className + '[data-index="' + index + '"]')
        .remove();

    var annClipID = 'clip' + fullLayout._uid + '_ann' + index;

    // this annotation is gone - quit now after deleting it
    // TODO: use d3 idioms instead of deleting and redrawing every time
    if(!options._input || options.visible === false) {
        d3.selectAll('#' + annClipID).remove();
        return;
    }

    // calculated pixel positions
    // x & y each will get text, head, and tail as appropriate
    var annPosPx = {x: {}, y: {}};
    var textangle = +options.textangle || 0;

    // create the components
    // made a single group to contain all, so opacity can work right
    // with border/arrow together this could handle a whole bunch of
    // cleanup at this point, but works for now
    var annGroup = fullLayout._infolayer.append('g')
        .classed(className, true)
        .attr('data-index', String(index))
        .style('opacity', options.opacity);

    // another group for text+background so that they can rotate together
    var annTextGroup = annGroup.append('g')
        .classed('annotation-text-g', true);

    var editTextPosition = edits[options.showarrow ? 'annotationTail' : 'annotationPosition'];
    var textEvents = options.captureevents || edits.annotationText || editTextPosition;

    var annTextGroupInner = annTextGroup.append('g')
        .style('pointer-events', textEvents ? 'all' : null)
        .call(setCursor, 'pointer')
        .on('click', function() {
            gd._dragging = false;

            var eventData = {
                index: index,
                annotation: options._input,
                fullAnnotation: options,
                event: d3.event
            };

            if(subplotId) {
                eventData.subplotId = subplotId;
            }

            gd.emit('plotly_clickannotation', eventData);
        });

    if(options.hovertext) {
        annTextGroupInner
        .on('mouseover', function() {
            var hoverOptions = options.hoverlabel;
            var hoverFont = hoverOptions.font;
            var bBox = this.getBoundingClientRect();
            var bBoxRef = gd.getBoundingClientRect();

            Fx.loneHover({
                x0: bBox.left - bBoxRef.left,
                x1: bBox.right - bBoxRef.left,
                y: (bBox.top + bBox.bottom) / 2 - bBoxRef.top,
                text: options.hovertext,
                color: hoverOptions.bgcolor,
                borderColor: hoverOptions.bordercolor,
                fontFamily: hoverFont.family,
                fontSize: hoverFont.size,
                fontColor: hoverFont.color
            }, {
                container: fullLayout._hoverlayer.node(),
                outerContainer: fullLayout._paper.node(),
                gd: gd
            });
        })
        .on('mouseout', function() {
            Fx.loneUnhover(fullLayout._hoverlayer.node());
        });
    }

    var borderwidth = options.borderwidth;
    var borderpad = options.borderpad;
    var borderfull = borderwidth + borderpad;

    var annTextBG = annTextGroupInner.append('rect')
        .attr('class', 'bg')
        .style('stroke-width', borderwidth + 'px')
        .call(Color.stroke, options.bordercolor)
        .call(Color.fill, options.bgcolor);

    var isSizeConstrained = options.width || options.height;

    var annTextClip = fullLayout._topclips
        .selectAll('#' + annClipID)
        .data(isSizeConstrained ? [0] : []);

    annTextClip.enter().append('clipPath')
        .classed('annclip', true)
        .attr('id', annClipID)
      .append('rect');
    annTextClip.exit().remove();

    var font = options.font;

    var text = fullLayout.meta ?
        Lib.templateString(options.text, {meta: fullLayout.meta}) :
        options.text;

    var annText = annTextGroupInner.append('text')
        .classed('annotation-text', true)
        .text(text);

    function textLayout(s) {
        s.call(Drawing.font, font)
        .attr({
            'text-anchor': {
                left: 'start',
                right: 'end'
            }[options.align] || 'middle'
        });

        svgTextUtils.convertToTspans(s, gd, drawGraphicalElements);
        return s;
    }

    function drawGraphicalElements() {
        // if the text has *only* a link, make the whole box into a link
        var anchor3 = annText.selectAll('a');
        if(anchor3.size() === 1 && anchor3.text() === annText.text()) {
            var wholeLink = annTextGroupInner.insert('a', ':first-child').attr({
                'xlink:xlink:href': anchor3.attr('xlink:href'),
                'xlink:xlink:show': anchor3.attr('xlink:show')
            })
            .style({cursor: 'pointer'});

            wholeLink.node().appendChild(annTextBG.node());
        }

        var mathjaxGroup = annTextGroupInner.select('.annotation-text-math-group');
        var hasMathjax = !mathjaxGroup.empty();
        var anntextBB = Drawing.bBox(
                (hasMathjax ? mathjaxGroup : annText).node());
        var textWidth = anntextBB.width;
        var textHeight = anntextBB.height;
        var annWidth = options.width || textWidth;
        var annHeight = options.height || textHeight;
        var outerWidth = Math.round(annWidth + 2 * borderfull);
        var outerHeight = Math.round(annHeight + 2 * borderfull);

        function shiftFraction(v, anchor) {
            if(anchor === 'auto') {
                if(v < 1 / 3) anchor = 'left';
                else if(v > 2 / 3) anchor = 'right';
                else anchor = 'center';
            }
            return {
                center: 0,
                middle: 0,
                left: 0.5,
                bottom: -0.5,
                right: -0.5,
                top: 0.5
            }[anchor];
        }

        var annotationIsOffscreen = false;
        var letters = ['x', 'y'];

        for(var i = 0; i < letters.length; i++) {
            var axLetter = letters[i];
            var axRef = options[axLetter + 'ref'] || axLetter;
            var tailRef = options['a' + axLetter + 'ref'];
            var ax = {x: xa, y: ya}[axLetter];
            var dimAngle = (textangle + (axLetter === 'x' ? 0 : -90)) * Math.PI / 180;
            // note that these two can be either positive or negative
            var annSizeFromWidth = outerWidth * Math.cos(dimAngle);
            var annSizeFromHeight = outerHeight * Math.sin(dimAngle);
            // but this one is the positive total size
            var annSize = Math.abs(annSizeFromWidth) + Math.abs(annSizeFromHeight);
            var anchor = options[axLetter + 'anchor'];
            var overallShift = options[axLetter + 'shift'] * (axLetter === 'x' ? 1 : -1);
            var posPx = annPosPx[axLetter];
            var basePx;
            var textPadShift;
            var alignPosition;
            var autoAlignFraction;
            var textShift;

            /*
             * calculate the *primary* pixel position
             * which is the arrowhead if there is one,
             * otherwise the text anchor point
             */
            if(ax) {
                // check if annotation is off screen, to bypass DOM manipulations
                var posFraction = ax.r2fraction(options[axLetter]);
                if(posFraction < 0 || posFraction > 1) {
                    if(tailRef === axRef) {
                        posFraction = ax.r2fraction(options['a' + axLetter]);
                        if(posFraction < 0 || posFraction > 1) {
                            annotationIsOffscreen = true;
                        }
                    } else {
                        annotationIsOffscreen = true;
                    }
                }
                basePx = ax._offset + ax.r2p(options[axLetter]);
                autoAlignFraction = 0.5;
            }
            else {
                if(axLetter === 'x') {
                    alignPosition = options[axLetter];
                    basePx = gs.l + gs.w * alignPosition;
                }
                else {
                    alignPosition = 1 - options[axLetter];
                    basePx = gs.t + gs.h * alignPosition;
                }
                autoAlignFraction = options.showarrow ? 0.5 : alignPosition;
            }

            // now translate this into pixel positions of head, tail, and text
            // as well as paddings for autorange
            if(options.showarrow) {
                posPx.head = basePx;

                var arrowLength = options['a' + axLetter];

                // with an arrow, the text rotates around the anchor point
                textShift = annSizeFromWidth * shiftFraction(0.5, options.xanchor) -
                    annSizeFromHeight * shiftFraction(0.5, options.yanchor);

                if(tailRef === axRef) {
                    posPx.tail = ax._offset + ax.r2p(arrowLength);
                    // tail is data-referenced: autorange pads the text in px from the tail
                    textPadShift = textShift;
                }
                else {
                    posPx.tail = basePx + arrowLength;
                    // tail is specified in px from head, so autorange also pads vs head
                    textPadShift = textShift + arrowLength;
                }

                posPx.text = posPx.tail + textShift;

                // constrain pixel/paper referenced so the draggers are at least
                // partially visible
                var maxPx = fullLayout[(axLetter === 'x') ? 'width' : 'height'];
                if(axRef === 'paper') {
                    posPx.head = Lib.constrain(posPx.head, 1, maxPx - 1);
                }
                if(tailRef === 'pixel') {
                    var shiftPlus = -Math.max(posPx.tail - 3, posPx.text);
                    var shiftMinus = Math.min(posPx.tail + 3, posPx.text) - maxPx;
                    if(shiftPlus > 0) {
                        posPx.tail += shiftPlus;
                        posPx.text += shiftPlus;
                    }
                    else if(shiftMinus > 0) {
                        posPx.tail -= shiftMinus;
                        posPx.text -= shiftMinus;
                    }
                }

                posPx.tail += overallShift;
                posPx.head += overallShift;
            }
            else {
                // with no arrow, the text rotates and *then* we put the anchor
                // relative to the new bounding box
                textShift = annSize * shiftFraction(autoAlignFraction, anchor);
                textPadShift = textShift;
                posPx.text = basePx + textShift;
            }

            posPx.text += overallShift;
            textShift += overallShift;
            textPadShift += overallShift;

            // padplus/minus are used by autorange
            options['_' + axLetter + 'padplus'] = (annSize / 2) + textPadShift;
            options['_' + axLetter + 'padminus'] = (annSize / 2) - textPadShift;

            // size/shift are used during dragging
            options['_' + axLetter + 'size'] = annSize;
            options['_' + axLetter + 'shift'] = textShift;
        }

        // We have everything we need for calcAutorange at this point,
        // we can safely exit - unless we're currently dragging the plot
        if(!gd._dragging && annotationIsOffscreen) {
            annTextGroupInner.remove();
            return;
        }

        var xShift = 0;
        var yShift = 0;

        if(options.align !== 'left') {
            xShift = (annWidth - textWidth) * (options.align === 'center' ? 0.5 : 1);
        }
        if(options.valign !== 'top') {
            yShift = (annHeight - textHeight) * (options.valign === 'middle' ? 0.5 : 1);
        }

        if(hasMathjax) {
            mathjaxGroup.select('svg').attr({
                x: borderfull + xShift - 1,
                y: borderfull + yShift
            })
            .call(Drawing.setClipUrl, isSizeConstrained ? annClipID : null, gd);
        }
        else {
            var texty = borderfull + yShift - anntextBB.top;
            var textx = borderfull + xShift - anntextBB.left;

            annText.call(svgTextUtils.positionText, textx, texty)
                .call(Drawing.setClipUrl, isSizeConstrained ? annClipID : null, gd);
        }

        annTextClip.select('rect').call(Drawing.setRect, borderfull, borderfull,
            annWidth, annHeight);

        annTextBG.call(Drawing.setRect, borderwidth / 2, borderwidth / 2,
            outerWidth - borderwidth, outerHeight - borderwidth);

        annTextGroupInner.call(Drawing.setTranslate,
            Math.round(annPosPx.x.text - outerWidth / 2),
            Math.round(annPosPx.y.text - outerHeight / 2));

        /*
         * rotate text and background
         * we already calculated the text center position *as rotated*
         * because we needed that for autoranging anyway, so now whether
         * we have an arrow or not, we rotate about the text center.
         */
        annTextGroup.attr({transform: 'rotate(' + textangle + ',' +
                            annPosPx.x.text + ',' + annPosPx.y.text + ')'});

        /*
         * add the arrow
         * uses options[arrowwidth,arrowcolor,arrowhead] for styling
         * dx and dy are normally zero, but when you are dragging the textbox
         * while the head stays put, dx and dy are the pixel offsets
         */
        var drawArrow = function(dx, dy) {
            annGroup
                .selectAll('.annotation-arrow-g')
                .remove();

            var headX = annPosPx.x.head;
            var headY = annPosPx.y.head;
            var tailX = annPosPx.x.tail + dx;
            var tailY = annPosPx.y.tail + dy;
            var textX = annPosPx.x.text + dx;
            var textY = annPosPx.y.text + dy;

            // find the edge of the text box, where we'll start the arrow:
            // create transform matrix to rotate the text box corners
            var transform = Lib.rotationXYMatrix(textangle, textX, textY);
            var applyTransform = Lib.apply2DTransform(transform);
            var applyTransform2 = Lib.apply2DTransform2(transform);

            // calculate and transform bounding box
            var width = +annTextBG.attr('width');
            var height = +annTextBG.attr('height');
            var xLeft = textX - 0.5 * width;
            var xRight = xLeft + width;
            var yTop = textY - 0.5 * height;
            var yBottom = yTop + height;
            var edges = [
                [xLeft, yTop, xLeft, yBottom],
                [xLeft, yBottom, xRight, yBottom],
                [xRight, yBottom, xRight, yTop],
                [xRight, yTop, xLeft, yTop]
            ].map(applyTransform2);

            // Remove the line if it ends inside the box.  Use ray
            // casting for rotated boxes: see which edges intersect a
            // line from the arrowhead to far away and reduce with xor
            // to get the parity of the number of intersections.
            if(edges.reduce(function(a, x) {
                return a ^
                    !!Lib.segmentsIntersect(headX, headY, headX + 1e6, headY + 1e6,
                            x[0], x[1], x[2], x[3]);
            }, false)) {
                // no line or arrow - so quit drawArrow now
                return;
            }

            edges.forEach(function(x) {
                var p = Lib.segmentsIntersect(tailX, tailY, headX, headY,
                            x[0], x[1], x[2], x[3]);
                if(p) {
                    tailX = p.x;
                    tailY = p.y;
                }
            });

            var strokewidth = options.arrowwidth;
            var arrowColor = options.arrowcolor;
            var arrowSide = options.arrowside;

            var arrowGroup = annGroup.append('g')
                .style({opacity: Color.opacity(arrowColor)})
                .classed('annotation-arrow-g', true);

            var arrow = arrowGroup.append('path')
                .attr('d', 'M' + tailX + ',' + tailY + 'L' + headX + ',' + headY)
                .style('stroke-width', strokewidth + 'px')
                .call(Color.stroke, Color.rgb(arrowColor));

            drawArrowHead(arrow, arrowSide, options);

            // the arrow dragger is a small square right at the head, then a line to the tail,
            // all expanded by a stroke width of 6px plus the arrow line width
            if(edits.annotationPosition && arrow.node().parentNode && !subplotId) {
                var arrowDragHeadX = headX;
                var arrowDragHeadY = headY;
                if(options.standoff) {
                    var arrowLength = Math.sqrt(Math.pow(headX - tailX, 2) + Math.pow(headY - tailY, 2));
                    arrowDragHeadX += options.standoff * (tailX - headX) / arrowLength;
                    arrowDragHeadY += options.standoff * (tailY - headY) / arrowLength;
                }
                var arrowDrag = arrowGroup.append('path')
                    .classed('annotation-arrow', true)
                    .classed('anndrag', true)
                    .classed('cursor-move', true)
                    .attr({
                        d: 'M3,3H-3V-3H3ZM0,0L' + (tailX - arrowDragHeadX) + ',' + (tailY - arrowDragHeadY),
                        transform: 'translate(' + arrowDragHeadX + ',' + arrowDragHeadY + ')'
                    })
                    .style('stroke-width', (strokewidth + 6) + 'px')
                    .call(Color.stroke, 'rgba(0,0,0,0)')
                    .call(Color.fill, 'rgba(0,0,0,0)');

                var annx0, anny0;

                // dragger for the arrow & head: translates the whole thing
                // (head/tail/text) all together
                dragElement.init({
                    element: arrowDrag.node(),
                    gd: gd,
                    prepFn: function() {
                        var pos = Drawing.getTranslate(annTextGroupInner);

                        annx0 = pos.x;
                        anny0 = pos.y;
                        if(xa && xa.autorange) {
                            modifyBase(xa._name + '.autorange', true);
                        }
                        if(ya && ya.autorange) {
                            modifyBase(ya._name + '.autorange', true);
                        }
                    },
                    moveFn: function(dx, dy) {
                        var annxy0 = applyTransform(annx0, anny0);
                        var xcenter = annxy0[0] + dx;
                        var ycenter = annxy0[1] + dy;
                        annTextGroupInner.call(Drawing.setTranslate, xcenter, ycenter);

                        modifyItem('x', xa ?
                            xa.p2r(xa.r2p(options.x) + dx) :
                            (options.x + (dx / gs.w)));
                        modifyItem('y', ya ?
                            ya.p2r(ya.r2p(options.y) + dy) :
                            (options.y - (dy / gs.h)));

                        if(options.axref === options.xref) {
                            modifyItem('ax', xa.p2r(xa.r2p(options.ax) + dx));
                        }

                        if(options.ayref === options.yref) {
                            modifyItem('ay', ya.p2r(ya.r2p(options.ay) + dy));
                        }

                        arrowGroup.attr('transform', 'translate(' + dx + ',' + dy + ')');
                        annTextGroup.attr({
                            transform: 'rotate(' + textangle + ',' +
                                   xcenter + ',' + ycenter + ')'
                        });
                    },
                    doneFn: function() {
                        Registry.call('_guiRelayout', gd, getUpdateObj());
                        var notesBox = document.querySelector('.js-notes-box-panel');
                        if(notesBox) notesBox.redraw(notesBox.selectedObj);
                    }
                });
            }
        };

        if(options.showarrow) drawArrow(0, 0);

        // user dragging the annotation (text, not arrow)
        if(editTextPosition) {
            var baseTextTransform;

            // dragger for the textbox: if there's an arrow, just drag the
            // textbox and tail, leave the head untouched
            dragElement.init({
                element: annTextGroupInner.node(),
                gd: gd,
                prepFn: function() {
                    baseTextTransform = annTextGroup.attr('transform');
                },
                moveFn: function(dx, dy) {
                    var csr = 'pointer';
                    if(options.showarrow) {
                        if(options.axref === options.xref) {
                            modifyItem('ax', xa.p2r(xa.r2p(options.ax) + dx));
                        } else {
                            modifyItem('ax', options.ax + dx);
                        }

                        if(options.ayref === options.yref) {
                            modifyItem('ay', ya.p2r(ya.r2p(options.ay) + dy));
                        } else {
                            modifyItem('ay', options.ay + dy);
                        }

                        drawArrow(dx, dy);
                    }
                    else if(!subplotId) {
                        var xUpdate, yUpdate;
                        if(xa) {
                            xUpdate = xa.p2r(xa.r2p(options.x) + dx);

                        } else {
                            var widthFraction = options._xsize / gs.w;
                            var xLeft = options.x + (options._xshift - options.xshift) / gs.w - widthFraction / 2;

                            xUpdate = dragElement.align(xLeft + dx / gs.w,
                                widthFraction, 0, 1, options.xanchor);
                        }

                        if(ya) {
                            yUpdate = ya.p2r(ya.r2p(options.y) + dy);
                        } else {
                            var heightFraction = options._ysize / gs.h;
                            var yBottom = options.y - (options._yshift + options.yshift) / gs.h - heightFraction / 2;

                            yUpdate = dragElement.align(yBottom - dy / gs.h,
                                heightFraction, 0, 1, options.yanchor);
                        }
                        modifyItem('x', xUpdate);
                        modifyItem('y', yUpdate);
                        if(!xa || !ya) {
                            csr = dragElement.getCursor(
                                xa ? 0.5 : xUpdate,
                                ya ? 0.5 : yUpdate,
                                options.xanchor, options.yanchor
                            );
                        }
                    }
                    else return;

                    annTextGroup.attr({
                        transform: 'translate(' + dx + ',' + dy + ')' + baseTextTransform
                    });

                    setCursor(annTextGroupInner, csr);
                },
                doneFn: function() {
                    setCursor(annTextGroupInner);
                    Registry.call('_guiRelayout', gd, getUpdateObj());
                    var notesBox = document.querySelector('.js-notes-box-panel');
                    if(notesBox) notesBox.redraw(notesBox.selectedObj);
                }
            });
        }
    }

    if(edits.annotationText) {
        annText.call(svgTextUtils.makeEditable, {delegate: annTextGroupInner, gd: gd})
            .call(textLayout)
            .on('edit', function(_text) {
                options.text = _text;

                this.call(textLayout);

                modifyItem('text', _text);

                if(xa && xa.autorange) {
                    modifyBase(xa._name + '.autorange', true);
                }
                if(ya && ya.autorange) {
                    modifyBase(ya._name + '.autorange', true);
                }

                Registry.call('_guiRelayout', gd, getUpdateObj());
            });
    }
    else annText.call(textLayout);
}

},{"../../lib":694,"../../lib/setcursor":714,"../../lib/svg_text_utils":718,"../../plot_api/plot_template":732,"../../plots/cartesian/axes":742,"../../plots/plots":806,"../../registry":825,"../color":571,"../dragelement":589,"../drawing":592,"../fx":610,"./draw_arrow_head":561,"d3":149}],561:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

var Color = _dereq_('../color');

var ARROWPATHS = _dereq_('./arrow_paths');

/**
 * Add arrowhead(s) to a path or line element
 *
 * @param {d3.selection} el3: a d3-selected line or path element
 *
 * @param {string} ends: 'none', 'start', 'end', or 'start+end' for which ends get arrowheads
 *
 * @param {object} options: style information. Must have all the following:
 * @param {number} options.arrowhead: end head style - see ./arrow_paths
 * @param {number} options.startarrowhead: start head style - see ./arrow_paths
 * @param {number} options.arrowsize: relative size of the end head vs line width
 * @param {number} options.startarrowsize: relative size of the start head vs line width
 * @param {number} options.standoff: distance in px to move the end arrow point from its target
 * @param {number} options.startstandoff: distance in px to move the start arrow point from its target
 * @param {number} options.arrowwidth: width of the arrow line
 * @param {string} options.arrowcolor: color of the arrow line, for the head to match
 *     Note that the opacity of this color is ignored, as it's assumed the container
 *     of both the line and head has opacity applied to it so there isn't greater opacity
 *     where they overlap.
 */
module.exports = function drawArrowHead(el3, ends, options) {
    var el = el3.node();
    var headStyle = ARROWPATHS[options.arrowhead || 0];
    var startHeadStyle = ARROWPATHS[options.startarrowhead || 0];
    var scale = (options.arrowwidth || 1) * (options.arrowsize || 1);
    var startScale = (options.arrowwidth || 1) * (options.startarrowsize || 1);
    var doStart = ends.indexOf('start') >= 0;
    var doEnd = ends.indexOf('end') >= 0;
    var backOff = headStyle.backoff * scale + options.standoff;
    var startBackOff = startHeadStyle.backoff * startScale + options.startstandoff;

    var start, end, startRot, endRot;

    if(el.nodeName === 'line') {
        start = {x: +el3.attr('x1'), y: +el3.attr('y1')};
        end = {x: +el3.attr('x2'), y: +el3.attr('y2')};

        var dx = start.x - end.x;
        var dy = start.y - end.y;

        startRot = Math.atan2(dy, dx);
        endRot = startRot + Math.PI;
        if(backOff && startBackOff) {
            if(backOff + startBackOff > Math.sqrt(dx * dx + dy * dy)) {
                hideLine();
                return;
            }
        }

        if(backOff) {
            if(backOff * backOff > dx * dx + dy * dy) {
                hideLine();
                return;
            }
            var backOffX = backOff * Math.cos(startRot);
            var backOffY = backOff * Math.sin(startRot);

            end.x += backOffX;
            end.y += backOffY;
            el3.attr({x2: end.x, y2: end.y});

        }

        if(startBackOff) {
            if(startBackOff * startBackOff > dx * dx + dy * dy) {
                hideLine();
                return;
            }
            var startBackOffX = startBackOff * Math.cos(startRot);
            var startbackOffY = startBackOff * Math.sin(startRot);

            start.x -= startBackOffX;
            start.y -= startbackOffY;
            el3.attr({x1: start.x, y1: start.y});

        }
    }
    else if(el.nodeName === 'path') {
        var pathlen = el.getTotalLength();
        // using dash to hide the backOff region of the path.
        // if we ever allow dash for the arrow we'll have to
        // do better than this hack... maybe just manually
        // combine the two
        var dashArray = '';

        if(pathlen < backOff + startBackOff) {
            hideLine();
            return;
        }


        var start0 = el.getPointAtLength(0);
        var dstart = el.getPointAtLength(0.1);

        startRot = Math.atan2(start0.y - dstart.y, start0.x - dstart.x);
        start = el.getPointAtLength(Math.min(startBackOff, pathlen));

        dashArray = '0px,' + startBackOff + 'px,';

        var end0 = el.getPointAtLength(pathlen);
        var dend = el.getPointAtLength(pathlen - 0.1);

        endRot = Math.atan2(end0.y - dend.y, end0.x - dend.x);
        end = el.getPointAtLength(Math.max(0, pathlen - backOff));

        var shortening = dashArray ? startBackOff + backOff : backOff;
        dashArray += (pathlen - shortening) + 'px,' + pathlen + 'px';

        el3.style('stroke-dasharray', dashArray);
    }

    function hideLine() { el3.style('stroke-dasharray', '0px,100px'); }

    function drawhead(arrowHeadStyle, p, rot, arrowScale) {
        if(!arrowHeadStyle.path) return;
        if(arrowHeadStyle.noRotate) rot = 0;

        d3.select(el.parentNode).append('path')
            .attr({
                'class': el3.attr('class'),
                d: arrowHeadStyle.path,
                transform:
                    'translate(' + p.x + ',' + p.y + ')' +
                    (rot ? 'rotate(' + (rot * 180 / Math.PI) + ')' : '') +
                    'scale(' + arrowScale + ')'
            })
            .style({
                fill: Color.rgb(options.arrowcolor),
                'stroke-width': 0
            });
    }

    if(doStart) drawhead(startHeadStyle, start, startRot, startScale);
    if(doEnd) drawhead(headStyle, end, endRot, scale);
};

},{"../color":571,"./arrow_paths":553,"d3":149}],562:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var drawModule = _dereq_('./draw');
var clickModule = _dereq_('./click');

module.exports = {
    moduleType: 'component',
    name: 'annotations',

    layoutAttributes: _dereq_('./attributes'),
    supplyLayoutDefaults: _dereq_('./defaults'),
    includeBasePlot: _dereq_('../../plots/cartesian/include_components')('annotations'),

    calcAutorange: _dereq_('./calc_autorange'),
    draw: drawModule.draw,
    drawOne: drawModule.drawOne,
    drawRaw: drawModule.drawRaw,

    hasClickToShow: clickModule.hasClickToShow,
    onClick: clickModule.onClick,

    convertCoords: _dereq_('./convert_coords')
};

},{"../../plots/cartesian/include_components":753,"./attributes":554,"./calc_autorange":555,"./click":556,"./convert_coords":558,"./defaults":559,"./draw":560}],563:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var annAtts = _dereq_('../annotations/attributes');
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;

module.exports = overrideAll(templatedArray('annotation', {
    visible: annAtts.visible,
    x: {
        valType: 'any',
        
        
    },
    y: {
        valType: 'any',
        
        
    },
    z: {
        valType: 'any',
        
        
    },
    ax: {
        valType: 'number',
        
        
    },
    ay: {
        valType: 'number',
        
        
    },

    xanchor: annAtts.xanchor,
    xshift: annAtts.xshift,
    yanchor: annAtts.yanchor,
    yshift: annAtts.yshift,

    text: annAtts.text,
    textangle: annAtts.textangle,
    font: annAtts.font,
    width: annAtts.width,
    height: annAtts.height,
    opacity: annAtts.opacity,
    align: annAtts.align,
    valign: annAtts.valign,
    bgcolor: annAtts.bgcolor,
    bordercolor: annAtts.bordercolor,
    borderpad: annAtts.borderpad,
    borderwidth: annAtts.borderwidth,
    showarrow: annAtts.showarrow,
    arrowcolor: annAtts.arrowcolor,
    arrowhead: annAtts.arrowhead,
    startarrowhead: annAtts.startarrowhead,
    arrowside: annAtts.arrowside,
    arrowsize: annAtts.arrowsize,
    startarrowsize: annAtts.startarrowsize,
    arrowwidth: annAtts.arrowwidth,
    standoff: annAtts.standoff,
    startstandoff: annAtts.startstandoff,
    hovertext: annAtts.hovertext,
    hoverlabel: annAtts.hoverlabel,
    captureevents: annAtts.captureevents,

    // maybes later?
    // clicktoshow: annAtts.clicktoshow,
    // xclick: annAtts.xclick,
    // yclick: annAtts.yclick,

    // not needed!
    // axref: 'pixel'
    // ayref: 'pixel'
    // xref: 'x'
    // yref: 'y
    // zref: 'z'
}), 'calc', 'from-root');

},{"../../plot_api/edit_types":725,"../../plot_api/plot_template":732,"../annotations/attributes":554}],564:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');

module.exports = function convert(scene) {
    var fullSceneLayout = scene.fullSceneLayout;
    var anns = fullSceneLayout.annotations;

    for(var i = 0; i < anns.length; i++) {
        mockAnnAxes(anns[i], scene);
    }

    scene.fullLayout._infolayer
        .selectAll('.annotation-' + scene.id)
        .remove();
};

function mockAnnAxes(ann, scene) {
    var fullSceneLayout = scene.fullSceneLayout;
    var domain = fullSceneLayout.domain;
    var size = scene.fullLayout._size;

    var base = {
        // this gets fill in on render
        pdata: null,

        // to get setConvert to not execute cleanly
        type: 'linear',

        // don't try to update them on `editable: true`
        autorange: false,

        // set infinite range so that annotation draw routine
        // does not try to remove 'outside-range' annotations,
        // this case is handled in the render loop
        range: [-Infinity, Infinity]
    };

    ann._xa = {};
    Lib.extendFlat(ann._xa, base);
    Axes.setConvert(ann._xa);
    ann._xa._offset = size.l + domain.x[0] * size.w;
    ann._xa.l2p = function() {
        return 0.5 * (1 + ann._pdata[0] / ann._pdata[3]) * size.w * (domain.x[1] - domain.x[0]);
    };

    ann._ya = {};
    Lib.extendFlat(ann._ya, base);
    Axes.setConvert(ann._ya);
    ann._ya._offset = size.t + (1 - domain.y[1]) * size.h;
    ann._ya.l2p = function() {
        return 0.5 * (1 - ann._pdata[1] / ann._pdata[3]) * size.h * (domain.y[1] - domain.y[0]);
    };
}

},{"../../lib":694,"../../plots/cartesian/axes":742}],565:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');
var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');
var handleAnnotationCommonDefaults = _dereq_('../annotations/common_defaults');
var attributes = _dereq_('./attributes');

module.exports = function handleDefaults(sceneLayoutIn, sceneLayoutOut, opts) {
    handleArrayContainerDefaults(sceneLayoutIn, sceneLayoutOut, {
        name: 'annotations',
        handleItemDefaults: handleAnnotationDefaults,
        fullLayout: opts.fullLayout
    });
};

function handleAnnotationDefaults(annIn, annOut, sceneLayout, opts) {
    function coerce(attr, dflt) {
        return Lib.coerce(annIn, annOut, attributes, attr, dflt);
    }

    function coercePosition(axLetter) {
        var axName = axLetter + 'axis';

        // mock in such way that getFromId grabs correct 3D axis
        var gdMock = { _fullLayout: {} };
        gdMock._fullLayout[axName] = sceneLayout[axName];

        return Axes.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5);
    }


    var visible = coerce('visible');
    if(!visible) return;

    handleAnnotationCommonDefaults(annIn, annOut, opts.fullLayout, coerce);

    coercePosition('x');
    coercePosition('y');
    coercePosition('z');

    // if you have one coordinate you should all three
    Lib.noneOrAll(annIn, annOut, ['x', 'y', 'z']);

    // hard-set here for completeness
    annOut.xref = 'x';
    annOut.yref = 'y';
    annOut.zref = 'z';

    coerce('xanchor');
    coerce('yanchor');
    coerce('xshift');
    coerce('yshift');

    if(annOut.showarrow) {
        annOut.axref = 'pixel';
        annOut.ayref = 'pixel';

        // TODO maybe default values should be bigger than the 2D case?
        coerce('ax', -10);
        coerce('ay', -30);

        // if you have one part of arrow length you should have both
        Lib.noneOrAll(annIn, annOut, ['ax', 'ay']);
    }
}

},{"../../lib":694,"../../plots/array_container_defaults":738,"../../plots/cartesian/axes":742,"../annotations/common_defaults":557,"./attributes":563}],566:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var drawRaw = _dereq_('../annotations/draw').drawRaw;
var project = _dereq_('../../plots/gl3d/project');
var axLetters = ['x', 'y', 'z'];

module.exports = function draw(scene) {
    var fullSceneLayout = scene.fullSceneLayout;
    var dataScale = scene.dataScale;
    var anns = fullSceneLayout.annotations;

    for(var i = 0; i < anns.length; i++) {
        var ann = anns[i];
        var annotationIsOffscreen = false;

        for(var j = 0; j < 3; j++) {
            var axLetter = axLetters[j];
            var pos = ann[axLetter];
            var ax = fullSceneLayout[axLetter + 'axis'];
            var posFraction = ax.r2fraction(pos);

            if(posFraction < 0 || posFraction > 1) {
                annotationIsOffscreen = true;
                break;
            }
        }

        if(annotationIsOffscreen) {
            scene.fullLayout._infolayer
                .select('.annotation-' + scene.id + '[data-index="' + i + '"]')
                .remove();
        } else {
            ann._pdata = project(scene.glplot.cameraParams, [
                fullSceneLayout.xaxis.r2l(ann.x) * dataScale[0],
                fullSceneLayout.yaxis.r2l(ann.y) * dataScale[1],
                fullSceneLayout.zaxis.r2l(ann.z) * dataScale[2]
            ]);

            drawRaw(scene.graphDiv, ann, i, scene.id, ann._xa, ann._ya);
        }
    }
};

},{"../../plots/gl3d/project":794,"../annotations/draw":560}],567:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');

module.exports = {
    moduleType: 'component',
    name: 'annotations3d',

    schema: {
        subplots: {
            scene: {annotations: _dereq_('./attributes')}
        }
    },

    layoutAttributes: _dereq_('./attributes'),
    handleDefaults: _dereq_('./defaults'),
    includeBasePlot: includeGL3D,

    convert: _dereq_('./convert'),
    draw: _dereq_('./draw')
};

function includeGL3D(layoutIn, layoutOut) {
    var GL3D = Registry.subplotsRegistry.gl3d;
    if(!GL3D) return;

    var attrRegex = GL3D.attrRegex;

    var keys = Object.keys(layoutIn);
    for(var i = 0; i < keys.length; i++) {
        var k = keys[i];
        if(attrRegex.test(k) && (layoutIn[k].annotations || []).length) {
            Lib.pushUnique(layoutOut._basePlotModules, GL3D);
            Lib.pushUnique(layoutOut._subplots.gl3d, k);
        }
    }
}

},{"../../lib":694,"../../registry":825,"./attributes":563,"./convert":564,"./defaults":565,"./draw":566}],568:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// a trimmed down version of:
// https://github.com/alexcjohnson/world-calendars/blob/master/dist/index.js

module.exports = _dereq_('world-calendars/dist/main');

_dereq_('world-calendars/dist/plus');

_dereq_('world-calendars/dist/calendars/chinese');
_dereq_('world-calendars/dist/calendars/coptic');
_dereq_('world-calendars/dist/calendars/discworld');
_dereq_('world-calendars/dist/calendars/ethiopian');
_dereq_('world-calendars/dist/calendars/hebrew');
_dereq_('world-calendars/dist/calendars/islamic');
_dereq_('world-calendars/dist/calendars/julian');
_dereq_('world-calendars/dist/calendars/mayan');
_dereq_('world-calendars/dist/calendars/nanakshahi');
_dereq_('world-calendars/dist/calendars/nepali');
_dereq_('world-calendars/dist/calendars/persian');
_dereq_('world-calendars/dist/calendars/taiwan');
_dereq_('world-calendars/dist/calendars/thai');
_dereq_('world-calendars/dist/calendars/ummalqura');

},{"world-calendars/dist/calendars/chinese":535,"world-calendars/dist/calendars/coptic":536,"world-calendars/dist/calendars/discworld":537,"world-calendars/dist/calendars/ethiopian":538,"world-calendars/dist/calendars/hebrew":539,"world-calendars/dist/calendars/islamic":540,"world-calendars/dist/calendars/julian":541,"world-calendars/dist/calendars/mayan":542,"world-calendars/dist/calendars/nanakshahi":543,"world-calendars/dist/calendars/nepali":544,"world-calendars/dist/calendars/persian":545,"world-calendars/dist/calendars/taiwan":546,"world-calendars/dist/calendars/thai":547,"world-calendars/dist/calendars/ummalqura":548,"world-calendars/dist/main":549,"world-calendars/dist/plus":550}],569:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var calendars = _dereq_('./calendars');

var Lib = _dereq_('../../lib');
var constants = _dereq_('../../constants/numerical');

var EPOCHJD = constants.EPOCHJD;
var ONEDAY = constants.ONEDAY;

var attributes = {
    valType: 'enumerated',
    values: Object.keys(calendars.calendars),
    
    editType: 'calc',
    dflt: 'gregorian'
};

var handleDefaults = function(contIn, contOut, attr, dflt) {
    var attrs = {};
    attrs[attr] = attributes;

    return Lib.coerce(contIn, contOut, attrs, attr, dflt);
};

var handleTraceDefaults = function(traceIn, traceOut, coords, layout) {
    for(var i = 0; i < coords.length; i++) {
        handleDefaults(traceIn, traceOut, coords[i] + 'calendar', layout.calendar);
    }
};

// each calendar needs its own default canonical tick. I would love to use
// 2000-01-01 (or even 0000-01-01) for them all but they don't necessarily
// all support either of those dates. Instead I'll use the most significant
// number they *do* support, biased toward the present day.
var CANONICAL_TICK = {
    chinese: '2000-01-01',
    coptic: '2000-01-01',
    discworld: '2000-01-01',
    ethiopian: '2000-01-01',
    hebrew: '5000-01-01',
    islamic: '1000-01-01',
    julian: '2000-01-01',
    mayan: '5000-01-01',
    nanakshahi: '1000-01-01',
    nepali: '2000-01-01',
    persian: '1000-01-01',
    jalali: '1000-01-01',
    taiwan: '1000-01-01',
    thai: '2000-01-01',
    ummalqura: '1400-01-01'
};

// Start on a Sunday - for week ticks
// Discworld and Mayan calendars don't have 7-day weeks but we're going to give them
// 7-day week ticks so start on our Sundays.
// If anyone really cares we can customize the auto tick spacings for these calendars.
var CANONICAL_SUNDAY = {
    chinese: '2000-01-02',
    coptic: '2000-01-03',
    discworld: '2000-01-03',
    ethiopian: '2000-01-05',
    hebrew: '5000-01-01',
    islamic: '1000-01-02',
    julian: '2000-01-03',
    mayan: '5000-01-01',
    nanakshahi: '1000-01-05',
    nepali: '2000-01-05',
    persian: '1000-01-01',
    jalali: '1000-01-01',
    taiwan: '1000-01-04',
    thai: '2000-01-04',
    ummalqura: '1400-01-06'
};

var DFLTRANGE = {
    chinese: ['2000-01-01', '2001-01-01'],
    coptic: ['1700-01-01', '1701-01-01'],
    discworld: ['1800-01-01', '1801-01-01'],
    ethiopian: ['2000-01-01', '2001-01-01'],
    hebrew: ['5700-01-01', '5701-01-01'],
    islamic: ['1400-01-01', '1401-01-01'],
    julian: ['2000-01-01', '2001-01-01'],
    mayan: ['5200-01-01', '5201-01-01'],
    nanakshahi: ['0500-01-01', '0501-01-01'],
    nepali: ['2000-01-01', '2001-01-01'],
    persian: ['1400-01-01', '1401-01-01'],
    jalali: ['1400-01-01', '1401-01-01'],
    taiwan: ['0100-01-01', '0101-01-01'],
    thai: ['2500-01-01', '2501-01-01'],
    ummalqura: ['1400-01-01', '1401-01-01']
};

/*
 * convert d3 templates to world-calendars templates, so our users only need
 * to know d3's specifiers. Map space padding to no padding, and unknown fields
 * to an ugly placeholder
 */
var UNKNOWN = '##';
var d3ToWorldCalendars = {
    'd': {'0': 'dd', '-': 'd'}, // 2-digit or unpadded day of month
    'e': {'0': 'd', '-': 'd'}, // alternate, always unpadded day of month
    'a': {'0': 'D', '-': 'D'}, // short weekday name
    'A': {'0': 'DD', '-': 'DD'}, // full weekday name
    'j': {'0': 'oo', '-': 'o'}, // 3-digit or unpadded day of the year
    'W': {'0': 'ww', '-': 'w'}, // 2-digit or unpadded week of the year (Monday first)
    'm': {'0': 'mm', '-': 'm'}, // 2-digit or unpadded month number
    'b': {'0': 'M', '-': 'M'}, // short month name
    'B': {'0': 'MM', '-': 'MM'}, // full month name
    'y': {'0': 'yy', '-': 'yy'}, // 2-digit year (map unpadded to zero-padded)
    'Y': {'0': 'yyyy', '-': 'yyyy'}, // 4-digit year (map unpadded to zero-padded)
    'U': UNKNOWN, // Sunday-first week of the year
    'w': UNKNOWN, // day of the week [0(sunday),6]
    // combined format, we replace the date part with the world-calendar version
    // and the %X stays there for d3 to handle with time parts
    'c': {'0': 'D M d %X yyyy', '-': 'D M d %X yyyy'},
    'x': {'0': 'mm/dd/yyyy', '-': 'mm/dd/yyyy'}
};

function worldCalFmt(fmt, x, calendar) {
    var dateJD = Math.floor((x + 0.05) / ONEDAY) + EPOCHJD;
    var cDate = getCal(calendar).fromJD(dateJD);
    var i = 0;
    var modifier, directive, directiveLen, directiveObj, replacementPart;

    while((i = fmt.indexOf('%', i)) !== -1) {
        modifier = fmt.charAt(i + 1);
        if(modifier === '0' || modifier === '-' || modifier === '_') {
            directiveLen = 3;
            directive = fmt.charAt(i + 2);
            if(modifier === '_') modifier = '-';
        }
        else {
            directive = modifier;
            modifier = '0';
            directiveLen = 2;
        }
        directiveObj = d3ToWorldCalendars[directive];
        if(!directiveObj) {
            i += directiveLen;
        }
        else {
            // code is recognized as a date part but world-calendars doesn't support it
            if(directiveObj === UNKNOWN) replacementPart = UNKNOWN;

            // format the cDate according to the translated directive
            else replacementPart = cDate.formatDate(directiveObj[modifier]);

            fmt = fmt.substr(0, i) + replacementPart + fmt.substr(i + directiveLen);
            i += replacementPart.length;
        }
    }
    return fmt;
}

// cache world calendars, so we don't have to reinstantiate
// during each date-time conversion
var allCals = {};
function getCal(calendar) {
    var calendarObj = allCals[calendar];
    if(calendarObj) return calendarObj;

    calendarObj = allCals[calendar] = calendars.instance(calendar);
    return calendarObj;
}

function makeAttrs(description) {
    return Lib.extendFlat({}, attributes, { description: description });
}

function makeTraceAttrsDescription(coord) {
    return 'Sets the calendar system to use with `' + coord + '` date data.';
}

var xAttrs = {
    xcalendar: makeAttrs(makeTraceAttrsDescription('x'))
};

var xyAttrs = Lib.extendFlat({}, xAttrs, {
    ycalendar: makeAttrs(makeTraceAttrsDescription('y'))
});

var xyzAttrs = Lib.extendFlat({}, xyAttrs, {
    zcalendar: makeAttrs(makeTraceAttrsDescription('z'))
});

var axisAttrs = makeAttrs([
    'Sets the calendar system to use for `range` and `tick0`',
    'if this is a date axis. This does not set the calendar for',
    'interpreting data on this axis, that\'s specified in the trace',
    'or via the global `layout.calendar`'
].join(' '));

module.exports = {
    moduleType: 'component',
    name: 'calendars',

    schema: {
        traces: {
            scatter: xyAttrs,
            bar: xyAttrs,
            box: xyAttrs,
            heatmap: xyAttrs,
            contour: xyAttrs,
            histogram: xyAttrs,
            histogram2d: xyAttrs,
            histogram2dcontour: xyAttrs,
            scatter3d: xyzAttrs,
            surface: xyzAttrs,
            mesh3d: xyzAttrs,
            scattergl: xyAttrs,
            ohlc: xAttrs,
            candlestick: xAttrs
        },
        layout: {
            calendar: makeAttrs([
                'Sets the default calendar system to use for interpreting and',
                'displaying dates throughout the plot.'
            ].join(' '))
        },
        subplots: {
            xaxis: {calendar: axisAttrs},
            yaxis: {calendar: axisAttrs},
            scene: {
                xaxis: {calendar: axisAttrs},
                // TODO: it's actually redundant to include yaxis and zaxis here
                // because in the scene attributes these are the same object so merging
                // into one merges into them all. However, I left them in for parity with
                // cartesian, where yaxis is unused until we Plotschema.get() when we
                // use its presence or absence to determine whether to delete attributes
                // from yaxis if they only apply to x (rangeselector/rangeslider)
                yaxis: {calendar: axisAttrs},
                zaxis: {calendar: axisAttrs}
            },
            polar: {
                radialaxis: {calendar: axisAttrs}
            }
        },
        transforms: {
            filter: {
                valuecalendar: makeAttrs([
                    'Sets the calendar system to use for `value`, if it is a date.'
                ].join(' ')),
                targetcalendar: makeAttrs([
                    'Sets the calendar system to use for `target`, if it is an',
                    'array of dates. If `target` is a string (eg *x*) we use the',
                    'corresponding trace attribute (eg `xcalendar`) if it exists,',
                    'even if `targetcalendar` is provided.'
                ].join(' '))
            }
        }
    },

    layoutAttributes: attributes,

    handleDefaults: handleDefaults,
    handleTraceDefaults: handleTraceDefaults,

    CANONICAL_SUNDAY: CANONICAL_SUNDAY,
    CANONICAL_TICK: CANONICAL_TICK,
    DFLTRANGE: DFLTRANGE,

    getCal: getCal,
    worldCalFmt: worldCalFmt
};

},{"../../constants/numerical":671,"../../lib":694,"./calendars":568}],570:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


// IMPORTANT - default colors should be in hex for compatibility
exports.defaults = [
    '#1f77b4',  // muted blue
    '#ff7f0e',  // safety orange
    '#2ca02c',  // cooked asparagus green
    '#d62728',  // brick red
    '#9467bd',  // muted purple
    '#8c564b',  // chestnut brown
    '#e377c2',  // raspberry yogurt pink
    '#7f7f7f',  // middle gray
    '#bcbd22',  // curry yellow-green
    '#17becf'   // blue-teal
];

exports.defaultLine = '#444';

exports.lightLine = '#eee';

exports.background = '#fff';

exports.borderLine = '#BEC8D9';

// with axis.color and Color.interp we aren't using lightLine
// itself anymore, instead interpolating between axis.color
// and the background color using tinycolor.mix. lightFraction
// gives back exactly lightLine if the other colors are defaults.
exports.lightFraction = 100 * (0xe - 0x4) / (0xf - 0x4);

},{}],571:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var tinycolor = _dereq_('tinycolor2');
var isNumeric = _dereq_('fast-isnumeric');

var color = module.exports = {};

var colorAttrs = _dereq_('./attributes');
color.defaults = colorAttrs.defaults;
var defaultLine = color.defaultLine = colorAttrs.defaultLine;
color.lightLine = colorAttrs.lightLine;
var background = color.background = colorAttrs.background;

/*
 * tinyRGB: turn a tinycolor into an rgb string, but
 * unlike the built-in tinycolor.toRgbString this never includes alpha
 */
color.tinyRGB = function(tc) {
    var c = tc.toRgb();
    return 'rgb(' + Math.round(c.r) + ', ' +
        Math.round(c.g) + ', ' + Math.round(c.b) + ')';
};

color.rgb = function(cstr) { return color.tinyRGB(tinycolor(cstr)); };

color.opacity = function(cstr) { return cstr ? tinycolor(cstr).getAlpha() : 0; };

color.addOpacity = function(cstr, op) {
    var c = tinycolor(cstr).toRgb();
    return 'rgba(' + Math.round(c.r) + ', ' +
        Math.round(c.g) + ', ' + Math.round(c.b) + ', ' + op + ')';
};

// combine two colors into one apparent color
// if back has transparency or is missing,
// color.background is assumed behind it
color.combine = function(front, back) {
    var fc = tinycolor(front).toRgb();
    if(fc.a === 1) return tinycolor(front).toRgbString();

    var bc = tinycolor(back || background).toRgb();
    var bcflat = bc.a === 1 ? bc : {
        r: 255 * (1 - bc.a) + bc.r * bc.a,
        g: 255 * (1 - bc.a) + bc.g * bc.a,
        b: 255 * (1 - bc.a) + bc.b * bc.a
    };
    var fcflat = {
        r: bcflat.r * (1 - fc.a) + fc.r * fc.a,
        g: bcflat.g * (1 - fc.a) + fc.g * fc.a,
        b: bcflat.b * (1 - fc.a) + fc.b * fc.a
    };
    return tinycolor(fcflat).toRgbString();
};

/*
 * Create a color that contrasts with cstr.
 *
 * If cstr is a dark color, we lighten it; if it's light, we darken.
 *
 * If lightAmount / darkAmount are used, we adjust by these percentages,
 * otherwise we go all the way to white or black.
 */
color.contrast = function(cstr, lightAmount, darkAmount) {
    var tc = tinycolor(cstr);

    if(tc.getAlpha() !== 1) tc = tinycolor(color.combine(cstr, background));

    var newColor = tc.isDark() ?
        (lightAmount ? tc.lighten(lightAmount) : background) :
        (darkAmount ? tc.darken(darkAmount) : defaultLine);

    return newColor.toString();
};

color.stroke = function(s, c) {
    var tc = tinycolor(c);
    s.style({'stroke': color.tinyRGB(tc), 'stroke-opacity': tc.getAlpha()});
};

color.fill = function(s, c) {
    var tc = tinycolor(c);
    s.style({
        'fill': color.tinyRGB(tc),
        'fill-opacity': tc.getAlpha()
    });
};

// search container for colors with the deprecated rgb(fractions) format
// and convert them to rgb(0-255 values)
color.clean = function(container) {
    if(!container || typeof container !== 'object') return;

    var keys = Object.keys(container);
    var i, j, key, val;

    for(i = 0; i < keys.length; i++) {
        key = keys[i];
        val = container[key];

        // only sanitize keys that end in "color" or "colorscale"
        if(key.substr(key.length - 5) === 'color') {
            if(Array.isArray(val)) {
                for(j = 0; j < val.length; j++) val[j] = cleanOne(val[j]);
            }
            else container[key] = cleanOne(val);
        }
        else if(key.substr(key.length - 10) === 'colorscale' && Array.isArray(val)) {
            // colorscales have the format [[0, color1], [frac, color2], ... [1, colorN]]
            for(j = 0; j < val.length; j++) {
                if(Array.isArray(val[j])) val[j][1] = cleanOne(val[j][1]);
            }
        }
        // recurse into arrays of objects, and plain objects
        else if(Array.isArray(val)) {
            var el0 = val[0];
            if(!Array.isArray(el0) && el0 && typeof el0 === 'object') {
                for(j = 0; j < val.length; j++) color.clean(val[j]);
            }
        }
        else if(val && typeof val === 'object') color.clean(val);
    }
};

function cleanOne(val) {
    if(isNumeric(val) || typeof val !== 'string') return val;

    var valTrim = val.trim();
    if(valTrim.substr(0, 3) !== 'rgb') return val;

    var match = valTrim.match(/^rgba?\s*\(([^()]*)\)$/);
    if(!match) return val;

    var parts = match[1].trim().split(/\s*[\s,]\s*/);
    var rgba = valTrim.charAt(3) === 'a' && parts.length === 4;
    if(!rgba && parts.length !== 3) return val;

    for(var i = 0; i < parts.length; i++) {
        if(!parts[i].length) return val;
        parts[i] = Number(parts[i]);

        // all parts must be non-negative numbers
        if(!(parts[i] >= 0)) return val;
        // alpha>1 gets clipped to 1
        if(i === 3) {
            if(parts[i] > 1) parts[i] = 1;
        }
        // r, g, b must be < 1 (ie 1 itself is not allowed)
        else if(parts[i] >= 1) return val;
    }

    var rgbStr = Math.round(parts[0] * 255) + ', ' +
        Math.round(parts[1] * 255) + ', ' +
        Math.round(parts[2] * 255);

    if(rgba) return 'rgba(' + rgbStr + ', ' + parts[3] + ')';
    return 'rgb(' + rgbStr + ')';
}

},{"./attributes":570,"fast-isnumeric":215,"tinycolor2":515}],572:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var axesAttrs = _dereq_('../../plots/cartesian/layout_attributes');
var fontAttrs = _dereq_('../../plots/font_attributes');
var extendFlat = _dereq_('../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;


module.exports = overrideAll({
// TODO: only right is supported currently
//     orient: {
//         valType: 'enumerated',
//         
//         values: ['left', 'right', 'top', 'bottom'],
//         dflt: 'right',
//         
//     },
    thicknessmode: {
        valType: 'enumerated',
        values: ['fraction', 'pixels'],
        
        dflt: 'pixels',
        
    },
    thickness: {
        valType: 'number',
        
        min: 0,
        dflt: 30,
        
    },
    lenmode: {
        valType: 'enumerated',
        values: ['fraction', 'pixels'],
        
        dflt: 'fraction',
        
    },
    len: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        
    },
    x: {
        valType: 'number',
        dflt: 1.02,
        min: -2,
        max: 3,
        
        
    },
    xanchor: {
        valType: 'enumerated',
        values: ['left', 'center', 'right'],
        dflt: 'left',
        
        
    },
    xpad: {
        valType: 'number',
        
        min: 0,
        dflt: 10,
        
    },
    y: {
        valType: 'number',
        
        dflt: 0.5,
        min: -2,
        max: 3,
        
    },
    yanchor: {
        valType: 'enumerated',
        values: ['top', 'middle', 'bottom'],
        
        dflt: 'middle',
        
    },
    ypad: {
        valType: 'number',
        
        min: 0,
        dflt: 10,
        
    },
    // a possible line around the bar itself
    outlinecolor: axesAttrs.linecolor,
    outlinewidth: axesAttrs.linewidth,
    // Should outlinewidth have {dflt: 0} ?
    // another possible line outside the padding and tick labels
    bordercolor: axesAttrs.linecolor,
    borderwidth: {
        valType: 'number',
        
        min: 0,
        dflt: 0,
        
    },
    bgcolor: {
        valType: 'color',
        
        dflt: 'rgba(0,0,0,0)',
        
    },
    // tick and title properties named and function exactly as in axes
    tickmode: axesAttrs.tickmode,
    nticks: axesAttrs.nticks,
    tick0: axesAttrs.tick0,
    dtick: axesAttrs.dtick,
    tickvals: axesAttrs.tickvals,
    ticktext: axesAttrs.ticktext,
    ticks: extendFlat({}, axesAttrs.ticks, {dflt: ''}),
    ticklen: axesAttrs.ticklen,
    tickwidth: axesAttrs.tickwidth,
    tickcolor: axesAttrs.tickcolor,
    showticklabels: axesAttrs.showticklabels,
    tickfont: fontAttrs({
        
    }),
    tickangle: axesAttrs.tickangle,
    tickformat: axesAttrs.tickformat,
    tickformatstops: axesAttrs.tickformatstops,
    tickprefix: axesAttrs.tickprefix,
    showtickprefix: axesAttrs.showtickprefix,
    ticksuffix: axesAttrs.ticksuffix,
    showticksuffix: axesAttrs.showticksuffix,
    separatethousands: axesAttrs.separatethousands,
    exponentformat: axesAttrs.exponentformat,
    showexponent: axesAttrs.showexponent,
    title: {
        text: {
            valType: 'string',
            
            
        },
        font: fontAttrs({
            
        }),
        side: {
            valType: 'enumerated',
            values: ['right', 'top', 'bottom'],
            
            dflt: 'top',
            
        }
    },

    _deprecated: {
        title: {
            valType: 'string',
            
            
        },
        titlefont: fontAttrs({
            
        }),
        titleside: {
            valType: 'enumerated',
            values: ['right', 'top', 'bottom'],
            
            dflt: 'top',
            
        }
    }
}, 'colorbars', 'from-root');

},{"../../lib/extend":684,"../../plot_api/edit_types":725,"../../plots/cartesian/layout_attributes":755,"../../plots/font_attributes":769}],573:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var drawColorbar = _dereq_('./draw');
var flipScale = _dereq_('../colorscale/helpers').flipScale;

/**
 * connectColorbar: create a colorbar from a trace, using its module to
 *   describe the connection.
 *
 * @param {DOM element} gd
 *
 * @param {Array} cd
 *   calcdata entry for this trace. cd[0].trace is the trace itself, and the
 *   colorbar object will be stashed in cd[0].t.cb
 *
 * @param {object|function} moduleOpts
 *   may be a function(gd, cd) to override the standard handling below. If
 *   an object, should have these keys:
 * @param {Optional(string)} moduleOpts.container
 *   name of the container inside the trace where the colorbar and colorscale
 *   attributes live (ie 'marker', 'line') - omit if they're at the trace root.
 * @param {string} moduleOpts.min
 *   name of the attribute holding the value of the minimum color
 * @param {string} moduleOpts.max
 *   name of the attribute holding the value of the maximum color
 * @param {Optional(string)} moduleOpts.vals
 *   name of the attribute holding the (numeric) color data
 *   used only if min/max fail. May be omitted if these are always
 *   pre-calculated.
 */
module.exports = function connectColorbar(gd, cd, moduleOpts) {
    if(typeof moduleOpts === 'function') return moduleOpts(gd, cd);

    var trace = cd[0].trace;
    var cbId = 'cb' + trace.uid;
    moduleOpts = Array.isArray(moduleOpts) ? moduleOpts : [moduleOpts];

    for(var i = 0; i < moduleOpts.length; i++) {
        var containerName = moduleOpts[i].container;

        var container = containerName ? trace[containerName] : trace;

        gd._fullLayout._infolayer.selectAll('.' + cbId).remove();
        if(!container || !container.showscale) continue;

        var cb = cd[0].t.cb = drawColorbar(gd, cbId);

        var scl = container.reversescale ?
            flipScale(container.colorscale) :
            container.colorscale;

        cb.fillgradient(scl)
            .zrange([container[moduleOpts[i].min], container[moduleOpts[i].max]])
            .options(container.colorbar)();

        return;
    }
};

},{"../colorscale/helpers":582,"./draw":576}],574:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    cn: {
        colorbar: 'colorbar',
        cbbg: 'cbbg',
        cbfill: 'cbfill',
        cbfills: 'cbfills',
        cbline: 'cbline',
        cblines: 'cblines',
        cbaxis: 'cbaxis',
        cbtitleunshift: 'cbtitleunshift',
        cbtitle: 'cbtitle',
        cboutline: 'cboutline',
        crisp: 'crisp',
        jsPlaceholder: 'js-placeholder'
    }
};

},{}],575:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var Template = _dereq_('../../plot_api/plot_template');

var handleTickValueDefaults = _dereq_('../../plots/cartesian/tick_value_defaults');
var handleTickMarkDefaults = _dereq_('../../plots/cartesian/tick_mark_defaults');
var handleTickLabelDefaults = _dereq_('../../plots/cartesian/tick_label_defaults');

var attributes = _dereq_('./attributes');

module.exports = function colorbarDefaults(containerIn, containerOut, layout) {
    var colorbarOut = Template.newContainer(containerOut, 'colorbar');
    var colorbarIn = containerIn.colorbar || {};

    function coerce(attr, dflt) {
        return Lib.coerce(colorbarIn, colorbarOut, attributes, attr, dflt);
    }

    var thicknessmode = coerce('thicknessmode');
    coerce('thickness', (thicknessmode === 'fraction') ?
        30 / (layout.width - layout.margin.l - layout.margin.r) :
        30
    );

    var lenmode = coerce('lenmode');
    coerce('len', (lenmode === 'fraction') ?
        1 :
        layout.height - layout.margin.t - layout.margin.b
    );

    coerce('x');
    coerce('xanchor');
    coerce('xpad');
    coerce('y');
    coerce('yanchor');
    coerce('ypad');
    Lib.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']);

    coerce('outlinecolor');
    coerce('outlinewidth');
    coerce('bordercolor');
    coerce('borderwidth');
    coerce('bgcolor');

    handleTickValueDefaults(colorbarIn, colorbarOut, coerce, 'linear');

    var opts = {outerTicks: false, font: layout.font};
    handleTickLabelDefaults(colorbarIn, colorbarOut, coerce, 'linear', opts);
    handleTickMarkDefaults(colorbarIn, colorbarOut, coerce, 'linear', opts);

    coerce('title.text', layout._dfltTitle.colorbar);
    Lib.coerceFont(coerce, 'title.font', layout.font);
    coerce('title.side');
};

},{"../../lib":694,"../../plot_api/plot_template":732,"../../plots/cartesian/tick_label_defaults":762,"../../plots/cartesian/tick_mark_defaults":763,"../../plots/cartesian/tick_value_defaults":764,"./attributes":572}],576:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var tinycolor = _dereq_('tinycolor2');

var Plots = _dereq_('../../plots/plots');
var Registry = _dereq_('../../registry');
var Axes = _dereq_('../../plots/cartesian/axes');
var dragElement = _dereq_('../dragelement');
var Lib = _dereq_('../../lib');
var extendFlat = _dereq_('../../lib/extend').extendFlat;
var setCursor = _dereq_('../../lib/setcursor');
var Drawing = _dereq_('../drawing');
var Color = _dereq_('../color');
var Titles = _dereq_('../titles');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var alignmentConstants = _dereq_('../../constants/alignment');
var LINE_SPACING = alignmentConstants.LINE_SPACING;
var FROM_TL = alignmentConstants.FROM_TL;
var FROM_BR = alignmentConstants.FROM_BR;

var handleAxisDefaults = _dereq_('../../plots/cartesian/axis_defaults');
var handleAxisPositionDefaults = _dereq_('../../plots/cartesian/position_defaults');
var axisLayoutAttrs = _dereq_('../../plots/cartesian/layout_attributes');

var attributes = _dereq_('./attributes');
var cn = _dereq_('./constants').cn;

module.exports = function draw(gd, id) {
    // opts: options object, containing everything from attributes
    // plus a few others that are the equivalent of the colorbar "data"
    var opts = {};
    for(var k in attributes) {
        opts[k] = null;
    }
    // fillcolor can be a d3 scale, domain is z values, range is colors
    // or leave it out for no fill,
    // or set to a string constant for single-color fill
    opts.fillcolor = null;
    // line.color has the same options as fillcolor
    opts.line = {color: null, width: null, dash: null};
    // levels of lines to draw.
    // note that this DOES NOT determine the extent of the bar
    // that's given by the domain of fillcolor
    // (or line.color if no fillcolor domain)
    opts.levels = {start: null, end: null, size: null};
    // separate fill levels (for example, heatmap coloring of a
    // contour map) if this is omitted, fillcolors will be
    // evaluated halfway between levels
    opts.filllevels = null;
    // for continuous colorscales: fill with a gradient instead of explicit levels
    // value should be the colorscale [[0, c0], [v1, c1], ..., [1, cEnd]]
    opts.fillgradient = null;
    // when using a gradient, we need the data range specified separately
    opts.zrange = null;

    function component() {
        var fullLayout = gd._fullLayout;
        var gs = fullLayout._size;
        if((typeof opts.fillcolor !== 'function') &&
                (typeof opts.line.color !== 'function') &&
                !opts.fillgradient) {
            fullLayout._infolayer.selectAll('g.' + id).remove();
            return;
        }
        var zrange = opts.zrange || (d3.extent(((typeof opts.fillcolor === 'function') ?
            opts.fillcolor : opts.line.color).domain()));
        var linelevels = [];
        var filllevels = [];
        var linecolormap = typeof opts.line.color === 'function' ?
            opts.line.color : function() { return opts.line.color; };
        var fillcolormap = typeof opts.fillcolor === 'function' ?
            opts.fillcolor : function() { return opts.fillcolor; };
        var l;
        var i;

        var l0 = opts.levels.end + opts.levels.size / 100;
        var ls = opts.levels.size;
        var zr0 = (1.001 * zrange[0] - 0.001 * zrange[1]);
        var zr1 = (1.001 * zrange[1] - 0.001 * zrange[0]);
        for(i = 0; i < 1e5; i++) {
            l = opts.levels.start + i * ls;
            if(ls > 0 ? (l >= l0) : (l <= l0)) break;
            if(l > zr0 && l < zr1) linelevels.push(l);
        }

        if(opts.fillgradient) {
            filllevels = [0];
        }
        else if(typeof opts.fillcolor === 'function') {
            if(opts.filllevels) {
                l0 = opts.filllevels.end + opts.filllevels.size / 100;
                ls = opts.filllevels.size;
                for(i = 0; i < 1e5; i++) {
                    l = opts.filllevels.start + i * ls;
                    if(ls > 0 ? (l >= l0) : (l <= l0)) break;
                    if(l > zrange[0] && l < zrange[1]) filllevels.push(l);
                }
            }
            else {
                filllevels = linelevels.map(function(v) {
                    return v - opts.levels.size / 2;
                });
                filllevels.push(filllevels[filllevels.length - 1] +
                    opts.levels.size);
            }
        }
        else if(opts.fillcolor && typeof opts.fillcolor === 'string') {
            // doesn't matter what this value is, with a single value
            // we'll make a single fill rect covering the whole bar
            filllevels = [0];
        }

        if(opts.levels.size < 0) {
            linelevels.reverse();
            filllevels.reverse();
        }

        // now make a Plotly Axes object to scale with and draw ticks
        // TODO: does not support orientation other than right

        // we calculate pixel sizes based on the specified graph size,
        // not the actual (in case something pushed the margins around)
        // which is a little odd but avoids an odd iterative effect
        // when the colorbar itself is pushing the margins.
        // but then the fractional size is calculated based on the
        // actual graph size, so that the axes will size correctly.
        var plotHeight = gs.h;
        var plotWidth = gs.w;
        var thickPx = Math.round(opts.thickness * (opts.thicknessmode === 'fraction' ? plotWidth : 1));
        var thickFrac = thickPx / gs.w;
        var lenPx = Math.round(opts.len * (opts.lenmode === 'fraction' ? plotHeight : 1));
        var lenFrac = lenPx / gs.h;
        var xpadFrac = opts.xpad / gs.w;
        var yExtraPx = (opts.borderwidth + opts.outlinewidth) / 2;
        var ypadFrac = opts.ypad / gs.h;

        // x positioning: do it initially just for left anchor,
        // then fix at the end (since we don't know the width yet)
        var xLeft = Math.round(opts.x * gs.w + opts.xpad);
        // for dragging... this is getting a little muddled...
        var xLeftFrac = opts.x - thickFrac * ({middle: 0.5, right: 1}[opts.xanchor]||0);

        // y positioning we can do correctly from the start
        var yBottomFrac = opts.y + lenFrac * (({top: -0.5, bottom: 0.5}[opts.yanchor] || 0) - 0.5);
        var yBottomPx = Math.round(gs.h * (1 - yBottomFrac));
        var yTopPx = yBottomPx - lenPx;

        var titleEl;

        var cbAxisIn = {
            type: 'linear',
            range: zrange,
            tickmode: opts.tickmode,
            nticks: opts.nticks,
            tick0: opts.tick0,
            dtick: opts.dtick,
            tickvals: opts.tickvals,
            ticktext: opts.ticktext,
            ticks: opts.ticks,
            ticklen: opts.ticklen,
            tickwidth: opts.tickwidth,
            tickcolor: opts.tickcolor,
            showticklabels: opts.showticklabels,
            tickfont: opts.tickfont,
            tickangle: opts.tickangle,
            tickformat: opts.tickformat,
            exponentformat: opts.exponentformat,
            separatethousands: opts.separatethousands,
            showexponent: opts.showexponent,
            showtickprefix: opts.showtickprefix,
            tickprefix: opts.tickprefix,
            showticksuffix: opts.showticksuffix,
            ticksuffix: opts.ticksuffix,
            title: opts.title,
            showline: true,
            anchor: 'free',
            side: 'right',
            position: 1
        };
        var cbAxisOut = {
            type: 'linear',
            _id: 'y' + id
        };
        var axisOptions = {
            letter: 'y',
            font: fullLayout.font,
            noHover: true,
            noTickson: true,
            calendar: fullLayout.calendar  // not really necessary (yet?)
        };

        // Coerce w.r.t. Axes layoutAttributes:
        // re-use axes.js logic without updating _fullData
        function coerce(attr, dflt) {
            return Lib.coerce(cbAxisIn, cbAxisOut, axisLayoutAttrs, attr, dflt);
        }

        // Prepare the Plotly axis object
        handleAxisDefaults(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout);
        handleAxisPositionDefaults(cbAxisIn, cbAxisOut, coerce, axisOptions);

        // position can't go in through supplyDefaults
        // because that restricts it to [0,1]
        cbAxisOut.position = opts.x + xpadFrac + thickFrac;

        // save for other callers to access this axis
        component.axis = cbAxisOut;

        if(['top', 'bottom'].indexOf(opts.title.side) !== -1) {
            cbAxisOut.title.side = opts.title.side;
            cbAxisOut.titlex = opts.x + xpadFrac;
            cbAxisOut.titley = yBottomFrac +
                (opts.title.side === 'top' ? lenFrac - ypadFrac : ypadFrac);
        }

        if(opts.line.color && opts.tickmode === 'auto') {
            cbAxisOut.tickmode = 'linear';
            cbAxisOut.tick0 = opts.levels.start;
            var dtick = opts.levels.size;
            // expand if too many contours, so we don't get too many ticks
            var autoNtick = Lib.constrain((yBottomPx - yTopPx) / 50, 4, 15) + 1;
            var dtFactor = (zrange[1] - zrange[0]) / ((opts.nticks || autoNtick) * dtick);
            if(dtFactor > 1) {
                var dtexp = Math.pow(10, Math.floor(
                    Math.log(dtFactor) / Math.LN10));
                dtick *= dtexp * Lib.roundUp(dtFactor / dtexp, [2, 5, 10]);
                // if the contours are at round multiples, reset tick0
                // so they're still at round multiples. Otherwise,
                // keep the first label on the first contour level
                if((Math.abs(opts.levels.start) /
                        opts.levels.size + 1e-6) % 1 < 2e-6) {
                    cbAxisOut.tick0 = 0;
                }
            }
            cbAxisOut.dtick = dtick;
        }

        // set domain after init, because we may want to
        // allow it outside [0,1]
        cbAxisOut.domain = [
            yBottomFrac + ypadFrac,
            yBottomFrac + lenFrac - ypadFrac
        ];
        cbAxisOut.setScale();

        // now draw the elements
        var container = Lib.ensureSingle(fullLayout._infolayer, 'g', id, function(s) {
            s.classed(cn.colorbar, true)
                .each(function() {
                    var s = d3.select(this);
                    s.append('rect').classed(cn.cbbg, true);
                    s.append('g').classed(cn.cbfills, true);
                    s.append('g').classed(cn.cblines, true);
                    s.append('g').classed(cn.cbaxis, true).classed(cn.crisp, true);
                    s.append('g').classed(cn.cbtitleunshift, true)
                        .append('g').classed(cn.cbtitle, true);
                    s.append('rect').classed(cn.cboutline, true);
                    s.select('.cbtitle').datum(0);
                });
        });

        container.attr('transform', 'translate(' + Math.round(gs.l) +
            ',' + Math.round(gs.t) + ')');
        // TODO: this opposite transform is a hack until we make it
        // more rational which items get this offset
        var titleCont = container.select('.cbtitleunshift')
            .attr('transform', 'translate(-' +
                Math.round(gs.l) + ',-' +
                Math.round(gs.t) + ')');

        var axisLayer = container.select('.cbaxis');

        var titleHeight = 0;
        if(['top', 'bottom'].indexOf(opts.title.side) !== -1) {
            // draw the title so we know how much room it needs
            // when we squish the axis. This one only applies to
            // top or bottom titles, not right side.
            var x = gs.l + (opts.x + xpadFrac) * gs.w;
            var fontSize = cbAxisOut.title.font.size;
            var y;

            if(opts.title.side === 'top') {
                y = (1 - (yBottomFrac + lenFrac - ypadFrac)) * gs.h +
                    gs.t + 3 + fontSize * 0.75;
            }
            else {
                y = (1 - (yBottomFrac + ypadFrac)) * gs.h +
                    gs.t - 3 - fontSize * 0.25;
            }
            drawTitle(cbAxisOut._id + 'title', {
                attributes: {x: x, y: y, 'text-anchor': 'start'}
            });
        }

        function drawAxis() {
            if(['top', 'bottom'].indexOf(opts.title.side) !== -1) {
                // squish the axis top to make room for the title
                var titleGroup = container.select('.cbtitle');
                var titleText = titleGroup.select('text');
                var titleTrans = [-opts.outlinewidth / 2, opts.outlinewidth / 2];
                var mathJaxNode = titleGroup
                    .select('.h' + cbAxisOut._id + 'title-math-group')
                    .node();
                var lineSize = 15.6;
                if(titleText.node()) {
                    lineSize =
                        parseInt(titleText.node().style.fontSize, 10) * LINE_SPACING;
                }
                if(mathJaxNode) {
                    titleHeight = Drawing.bBox(mathJaxNode).height;
                    if(titleHeight > lineSize) {
                        // not entirely sure how mathjax is doing
                        // vertical alignment, but this seems to work.
                        titleTrans[1] -= (titleHeight - lineSize) / 2;
                    }
                }
                else if(titleText.node() &&
                        !titleText.classed(cn.jsPlaceholder)) {
                    titleHeight = Drawing.bBox(titleText.node()).height;
                }
                if(titleHeight) {
                    // buffer btwn colorbar and title
                    // TODO: configurable
                    titleHeight += 5;

                    if(opts.title.side === 'top') {
                        cbAxisOut.domain[1] -= titleHeight / gs.h;
                        titleTrans[1] *= -1;
                    }
                    else {
                        cbAxisOut.domain[0] += titleHeight / gs.h;
                        var nlines = svgTextUtils.lineCount(titleText);
                        titleTrans[1] += (1 - nlines) * lineSize;
                    }

                    titleGroup.attr('transform',
                        'translate(' + titleTrans + ')');

                    cbAxisOut.setScale();
                }
            }

            container.selectAll('.cbfills,.cblines')
                .attr('transform', 'translate(0,' +
                    Math.round(gs.h * (1 - cbAxisOut.domain[1])) + ')');

            axisLayer.attr('transform', 'translate(0,' + Math.round(-gs.t) + ')');

            var fills = container.select('.cbfills')
                .selectAll('rect.cbfill')
                    .data(filllevels);
            fills.enter().append('rect')
                .classed(cn.cbfill, true)
                .style('stroke', 'none');
            fills.exit().remove();

            var zBounds = zrange
                .map(cbAxisOut.c2p)
                .map(Math.round)
                .sort(function(a, b) { return a - b; });

            fills.each(function(d, i) {
                var z = [
                    (i === 0) ? zrange[0] :
                        (filllevels[i] + filllevels[i - 1]) / 2,
                    (i === filllevels.length - 1) ? zrange[1] :
                        (filllevels[i] + filllevels[i + 1]) / 2
                ]
                .map(cbAxisOut.c2p)
                .map(Math.round);

                // offset the side adjoining the next rectangle so they
                // overlap, to prevent antialiasing gaps
                z[1] = Lib.constrain(z[1] + (z[1] > z[0]) ? 1 : -1, zBounds[0], zBounds[1]);

                // Colorbar cannot currently support opacities so we
                // use an opaque fill even when alpha channels present
                var fillEl = d3.select(this).attr({
                    x: xLeft,
                    width: Math.max(thickPx, 2),
                    y: d3.min(z),
                    height: Math.max(d3.max(z) - d3.min(z), 2),
                });

                if(opts.fillgradient) {
                    Drawing.gradient(fillEl, gd, id, 'vertical',
                        opts.fillgradient, 'fill');
                }
                else {
                    // Tinycolor can't handle exponents and
                    // at this scale, removing it makes no difference.
                    var colorString = fillcolormap(d).replace('e-', '');
                    fillEl.attr('fill', tinycolor(colorString).toHexString());
                }
            });

            var lines = container.select('.cblines')
                .selectAll('path.cbline')
                    .data(opts.line.color && opts.line.width ?
                        linelevels : []);
            lines.enter().append('path')
                .classed(cn.cbline, true);
            lines.exit().remove();
            lines.each(function(d) {
                d3.select(this)
                    .attr('d', 'M' + xLeft + ',' +
                        (Math.round(cbAxisOut.c2p(d)) + (opts.line.width / 2) % 1) +
                        'h' + thickPx)
                    .call(Drawing.lineGroupStyle,
                        opts.line.width, linecolormap(d), opts.line.dash);
            });

            // force full redraw of labels and ticks
            axisLayer.selectAll('g.' + cbAxisOut._id + 'tick,path').remove();

            // separate out axis and title drawing,
            // so we don't need such complicated logic in Titles.draw
            // if title is on the top or bottom, we've already drawn it
            // this title call only handles side=right
            return Lib.syncOrAsync([
                function() {
                    var shift = xLeft + thickPx +
                        (opts.outlinewidth || 0) / 2 - (opts.ticks === 'outside' ? 1 : 0);

                    var vals = Axes.calcTicks(cbAxisOut);
                    var transFn = Axes.makeTransFn(cbAxisOut);
                    var labelFns = Axes.makeLabelFns(cbAxisOut, shift);
                    var tickSign = Axes.getTickSigns(cbAxisOut)[2];

                    Axes.drawTicks(gd, cbAxisOut, {
                        vals: cbAxisOut.ticks === 'inside' ? Axes.clipEnds(cbAxisOut, vals) : vals,
                        layer: axisLayer,
                        path: Axes.makeTickPath(cbAxisOut, shift, tickSign),
                        transFn: transFn
                    });

                    return Axes.drawLabels(gd, cbAxisOut, {
                        vals: vals,
                        layer: axisLayer,
                        transFn: transFn,
                        labelXFn: labelFns.labelXFn,
                        labelYFn: labelFns.labelYFn,
                        labelAnchorFn: labelFns.labelAnchorFn
                    });
                },
                function() {
                    if(['top', 'bottom'].indexOf(opts.title.side) === -1) {
                        var fontSize = cbAxisOut.title.font.size;
                        var y = cbAxisOut._offset + cbAxisOut._length / 2;
                        var x = gs.l + (cbAxisOut.position || 0) * gs.w + ((cbAxisOut.side === 'right') ?
                            10 + fontSize * ((cbAxisOut.showticklabels ? 1 : 0.5)) :
                            -10 - fontSize * ((cbAxisOut.showticklabels ? 0.5 : 0)));

                        // the 'h' + is a hack to get around the fact that
                        // convertToTspans rotates any 'y...' class by 90 degrees.
                        // TODO: find a better way to control this.
                        drawTitle('h' + cbAxisOut._id + 'title', {
                            avoid: {
                                selection: d3.select(gd).selectAll('g.' + cbAxisOut._id + 'tick'),
                                side: opts.title.side,
                                offsetLeft: gs.l,
                                offsetTop: 0,
                                maxShift: fullLayout.width
                            },
                            attributes: {x: x, y: y, 'text-anchor': 'middle'},
                            transform: {rotate: '-90', offset: 0}
                        });
                    }
                }]);
        }

        function drawTitle(titleClass, titleOpts) {
            var dfltTitleOpts = {
                propContainer: cbAxisOut,
                propName: getPropName('title'),
                traceIndex: getTrace().index,
                placeholder: fullLayout._dfltTitle.colorbar,
                containerGroup: container.select('.cbtitle')
            };

            // this class-to-rotate thing with convertToTspans is
            // getting hackier and hackier... delete groups with the
            // wrong class (in case earlier the colorbar was drawn on
            // a different side, I think?)
            var otherClass = titleClass.charAt(0) === 'h' ?
                titleClass.substr(1) : ('h' + titleClass);
            container.selectAll('.' + otherClass + ',.' + otherClass + '-math-group')
                .remove();

            Titles.draw(gd, titleClass,
                extendFlat(dfltTitleOpts, titleOpts || {}));
        }

        function positionCB() {
            // wait for the axis & title to finish rendering before
            // continuing positioning
            // TODO: why are we redrawing multiple times now with this?
            // I guess autoMargin doesn't like being post-promise?
            var innerWidth = thickPx + opts.outlinewidth / 2 +
                    Drawing.bBox(axisLayer.node()).width;
            titleEl = titleCont.select('text');
            if(titleEl.node() && !titleEl.classed(cn.jsPlaceholder)) {
                var mathJaxNode = titleCont
                        .select('.h' + cbAxisOut._id + 'title-math-group')
                        .node();
                var titleWidth;
                if(mathJaxNode &&
                        ['top', 'bottom'].indexOf(opts.title.side) !== -1) {
                    titleWidth = Drawing.bBox(mathJaxNode).width;
                }
                else {
                    // note: the formula below works for all title sides,
                    // (except for top/bottom mathjax, above)
                    // but the weird gs.l is because the titleunshift
                    // transform gets removed by Drawing.bBox
                    titleWidth =
                        Drawing.bBox(titleCont.node()).right -
                        xLeft - gs.l;
                }
                innerWidth = Math.max(innerWidth, titleWidth);
            }

            var outerwidth = 2 * opts.xpad + innerWidth +
                    opts.borderwidth + opts.outlinewidth / 2;
            var outerheight = yBottomPx - yTopPx;

            container.select('.cbbg').attr({
                x: xLeft - opts.xpad -
                    (opts.borderwidth + opts.outlinewidth) / 2,
                y: yTopPx - yExtraPx,
                width: Math.max(outerwidth, 2),
                height: Math.max(outerheight + 2 * yExtraPx, 2)
            })
            .call(Color.fill, opts.bgcolor)
            .call(Color.stroke, opts.bordercolor)
            .style({'stroke-width': opts.borderwidth});

            container.selectAll('.cboutline').attr({
                x: xLeft,
                y: yTopPx + opts.ypad +
                    (opts.title.side === 'top' ? titleHeight : 0),
                width: Math.max(thickPx, 2),
                height: Math.max(outerheight - 2 * opts.ypad - titleHeight, 2)
            })
            .call(Color.stroke, opts.outlinecolor)
            .style({
                fill: 'None',
                'stroke-width': opts.outlinewidth
            });

            // fix positioning for xanchor!='left'
            var xoffset = ({center: 0.5, right: 1}[opts.xanchor] || 0) *
                outerwidth;
            container.attr('transform',
                'translate(' + (gs.l - xoffset) + ',' + gs.t + ')');

            // auto margin adjustment
            var marginOpts = {};
            var tFrac = FROM_TL[opts.yanchor];
            var bFrac = FROM_BR[opts.yanchor];
            if(opts.lenmode === 'pixels') {
                marginOpts.y = opts.y;
                marginOpts.t = outerheight * tFrac;
                marginOpts.b = outerheight * bFrac;
            }
            else {
                marginOpts.t = marginOpts.b = 0;
                marginOpts.yt = opts.y + opts.len * tFrac;
                marginOpts.yb = opts.y - opts.len * bFrac;
            }

            var lFrac = FROM_TL[opts.xanchor];
            var rFrac = FROM_BR[opts.xanchor];
            if(opts.thicknessmode === 'pixels') {
                marginOpts.x = opts.x;
                marginOpts.l = outerwidth * lFrac;
                marginOpts.r = outerwidth * rFrac;
            }
            else {
                var extraThickness = outerwidth - thickPx;
                marginOpts.l = extraThickness * lFrac;
                marginOpts.r = extraThickness * rFrac;
                marginOpts.xl = opts.x - opts.thickness * lFrac;
                marginOpts.xr = opts.x + opts.thickness * rFrac;
            }
            Plots.autoMargin(gd, id, marginOpts);
        }

        var cbDone = Lib.syncOrAsync([
            Plots.previousPromises,
            drawAxis,
            Plots.previousPromises,
            positionCB
        ], gd);

        if(cbDone && cbDone.then) (gd._promises || []).push(cbDone);

        // dragging...
        if(gd._context.edits.colorbarPosition) {
            var t0,
                xf,
                yf;

            dragElement.init({
                element: container.node(),
                gd: gd,
                prepFn: function() {
                    t0 = container.attr('transform');
                    setCursor(container);
                },
                moveFn: function(dx, dy) {
                    container.attr('transform',
                        t0 + ' ' + 'translate(' + dx + ',' + dy + ')');

                    xf = dragElement.align(xLeftFrac + (dx / gs.w), thickFrac,
                        0, 1, opts.xanchor);
                    yf = dragElement.align(yBottomFrac - (dy / gs.h), lenFrac,
                        0, 1, opts.yanchor);

                    var csr = dragElement.getCursor(xf, yf,
                        opts.xanchor, opts.yanchor);
                    setCursor(container, csr);
                },
                doneFn: function() {
                    setCursor(container);

                    if(xf !== undefined && yf !== undefined) {
                        var update = {};
                        update[getPropName('x')] = xf;
                        update[getPropName('y')] = yf;
                        Registry.call('_guiRestyle', gd, update, getTrace().index);
                    }
                }
            });
        }
        return cbDone;
    }

    function getTrace() {
        var idNum = id.substr(2);
        for(var i = 0; i < gd._fullData.length; i++) {
            var trace = gd._fullData[i];
            if(trace.uid === idNum) return trace;
        }
    }

    function getPropName(suffix) {
        var trace = getTrace();
        var propName = 'colorbar.';
        var containerName = trace._module.colorbar.container;
        if(containerName) propName = containerName + '.' + propName;
        return propName + suffix;
    }

    // setter/getters for every item defined in opts
    Object.keys(opts).forEach(function(name) {
        component[name] = function(v) {
            // getter
            if(!arguments.length) return opts[name];

            // setter - for multi-part properties,
            // set only the parts that are provided
            opts[name] = Lib.isPlainObject(opts[name]) ?
                 Lib.extendFlat(opts[name], v) :
                 v;

            return component;
        };
    });

    // or use .options to set multiple options at once via a dictionary
    component.options = function(o) {
        for(var name in o) {
            // in case something random comes through
            // that's not an option, ignore it
            if(typeof component[name] === 'function') {
                component[name](o[name]);
            }
        }
        return component;
    };

    component._opts = opts;

    return component;
};

},{"../../constants/alignment":666,"../../lib":694,"../../lib/extend":684,"../../lib/setcursor":714,"../../lib/svg_text_utils":718,"../../plots/cartesian/axes":742,"../../plots/cartesian/axis_defaults":744,"../../plots/cartesian/layout_attributes":755,"../../plots/cartesian/position_defaults":758,"../../plots/plots":806,"../../registry":825,"../color":571,"../dragelement":589,"../drawing":592,"../titles":659,"./attributes":572,"./constants":574,"d3":149,"tinycolor2":515}],577:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');


module.exports = function hasColorbar(container) {
    return Lib.isPlainObject(container.colorbar);
};

},{"../../lib":694}],578:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var palettes = _dereq_('./scales.js').scales;
var paletteStr = Object.keys(palettes);

function code(s) {
    return '`' + s + '`';
}

/**
 * Make colorscale attribute declarations for
 *
 * - colorscale,
 * - (c|z)auto, (c|z)min, (c|z)max,
 * - autocolorscale, reversescale,
 * - showscale (optionally)
 * - color (optionally)
 *
 * @param {string} context (dflt: '', i.e. from trace root):
 *     the container this is in ('', *marker*, *marker.line* etc)
 *
 * @param {object} opts:
 *   - cLetter {string} (dflt: 'c'):
 *     leading letter for 'min', 'max and 'auto' attribute (either 'z' or 'c')
 *
 *   - colorAttr {string} (dflt: 'z' if `cLetter: 'z'`, 'color' if `cLetter: 'c'`):
 *     (for descriptions) sets the name of the color attribute that maps to the colorscale.
 *
 *     N.B. if `colorAttr: 'color'`, we include the `color` declaration here.
 *
 *   - onlyIfNumerical {string} (dflt: false' if `cLetter: 'z'`, true if `cLetter: 'c'`):
 *     (for descriptions) set to true if colorscale attribute only
 *
 *   - colorscaleDflt {string}:
 *     overrides the colorscale dflt
 *
 *   - autoColorDflt {boolean} (dflt true):
 *     normally autocolorscale.dflt is `true`, but pass `false` to override
 *
 *   - noScale {boolean} (dflt: true if `context: 'marker.line'`, false otherwise):
 *     set to `false` to not include showscale attribute (e.g. for 'marker.line')
 *
 *   - showScaleDflt {boolean} (dflt: true if `cLetter: 'z'`, false otherwise)
 *
 *   - editTypeOverride {boolean} (dflt: ''):
 *     most of these attributes already require a recalc, but the ones that do not
 *     have editType *style* or *plot* unless you override (presumably with *calc*)
 *
 *   - anim {boolean) (dflt: undefined): is 'color' animatable?
 *
 * @return {object}
 */
module.exports = function colorScaleAttrs(context, opts) {
    context = context || '';
    opts = opts || {};

    var cLetter = opts.cLetter || 'c';
    var onlyIfNumerical = ('onlyIfNumerical' in opts) ? opts.onlyIfNumerical : Boolean(context);
    var noScale = ('noScale' in opts) ? opts.noScale : context === 'marker.line';
    var showScaleDflt = ('showScaleDflt' in opts) ? opts.showScaleDflt : cLetter === 'z';
    var colorscaleDflt = typeof opts.colorscaleDflt === 'string' ? palettes[opts.colorscaleDflt] : null;
    var editTypeOverride = opts.editTypeOverride || '';
    var contextHead = context ? (context + '.') : '';

    var colorAttr, colorAttrFull;

    if('colorAttr' in opts) {
        colorAttr = opts.colorAttr;
        colorAttrFull = opts.colorAttr;
    } else {
        colorAttr = {z: 'z', c: 'color'}[cLetter];
        colorAttrFull = 'in ' + code(contextHead + colorAttr);
    }

    var effectDesc = onlyIfNumerical ?
        ' Has an effect only if ' + colorAttrFull + 'is set to a numerical array.' :
        '';

    var auto = cLetter + 'auto';
    var min = cLetter + 'min';
    var max = cLetter + 'max';
    var minFull = code(contextHead + min);
    var maxFull = code(contextHead + max);
    var minmaxFull = minFull + ' and ' + maxFull;
    var autoImpliedEdits = {};
    autoImpliedEdits[min] = autoImpliedEdits[max] = undefined;
    var minmaxImpliedEdits = {};
    minmaxImpliedEdits[auto] = false;

    var attrs = {};

    if(colorAttr === 'color') {
        attrs.color = {
            valType: 'color',
            arrayOk: true,
            
            editType: editTypeOverride || 'style',
            
        };

        if(opts.anim) {
            attrs.color.anim = true;
        }
    }

    attrs[auto] = {
        valType: 'boolean',
        
        dflt: true,
        editType: 'calc',
        impliedEdits: autoImpliedEdits,
        
    };

    attrs[min] = {
        valType: 'number',
        
        dflt: null,
        editType: editTypeOverride || 'plot',
        impliedEdits: minmaxImpliedEdits,
        
    };

    attrs[max] = {
        valType: 'number',
        
        dflt: null,
        editType: editTypeOverride || 'plot',
        impliedEdits: minmaxImpliedEdits,
        
    };

    attrs.colorscale = {
        valType: 'colorscale',
        
        editType: 'calc',
        dflt: colorscaleDflt,
        impliedEdits: {autocolorscale: false},
        
    };

    attrs.autocolorscale = {
        valType: 'boolean',
        
        // gets overrode in 'heatmap' & 'surface' for backwards comp.
        dflt: opts.autoColorDflt === false ? false : true,
        editType: 'calc',
        impliedEdits: {colorscale: undefined},
        
    };

    attrs.reversescale = {
        valType: 'boolean',
        
        dflt: false,
        editType: 'plot',
        
    };

    if(!noScale) {
        attrs.showscale = {
            valType: 'boolean',
            
            dflt: showScaleDflt,
            editType: 'calc',
            
        };
    }

    return attrs;
};

},{"./scales.js":586}],579:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

module.exports = function calc(gd, trace, opts) {
    var fullLayout = gd._fullLayout;
    var vals = opts.vals;
    var containerStr = opts.containerStr;
    var cLetter = opts.cLetter;

    var container = containerStr ?
        Lib.nestedProperty(trace, containerStr).get() :
        trace;

    var autoAttr = cLetter + 'auto';
    var minAttr = cLetter + 'min';
    var maxAttr = cLetter + 'max';
    var auto = container[autoAttr];
    var min = container[minAttr];
    var max = container[maxAttr];
    var scl = container.colorscale;

    if(auto !== false || min === undefined) {
        min = Lib.aggNums(Math.min, null, vals);
    }

    if(auto !== false || max === undefined) {
        max = Lib.aggNums(Math.max, null, vals);
    }

    if(min === max) {
        min -= 0.5;
        max += 0.5;
    }

    container['_' + minAttr] = container[minAttr] = min;
    container['_' + maxAttr] = container[maxAttr] = max;

    if(container.autocolorscale) {
        if(min * max < 0) scl = fullLayout.colorscale.diverging;
        else if(min >= 0) scl = fullLayout.colorscale.sequential;
        else scl = fullLayout.colorscale.sequentialminus;

        container._colorscale = container.colorscale = scl;
    }
};

},{"../../lib":694}],580:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var hasColorscale = _dereq_('./helpers').hasColorscale;

module.exports = function crossTraceDefaults(fullData) {
    function replace(cont, k) {
        var val = cont['_' + k];
        if(val !== undefined) {
            cont[k] = val;
        }
    }

    function relinkColorAtts(trace, cAttrs) {
        var cont = cAttrs.container ?
            Lib.nestedProperty(trace, cAttrs.container).get() :
            trace;

        if(cont) {
            var isAuto = cont.zauto || cont.cauto;
            var minAttr = cAttrs.min;
            var maxAttr = cAttrs.max;

            if(isAuto || cont[minAttr] === undefined) {
                replace(cont, minAttr);
            }
            if(isAuto || cont[maxAttr] === undefined) {
                replace(cont, maxAttr);
            }
            if(cont.autocolorscale) {
                replace(cont, 'colorscale');
            }
        }
    }

    for(var i = 0; i < fullData.length; i++) {
        var trace = fullData[i];
        var _module = trace._module;

        if(_module.colorbar) {
            relinkColorAtts(trace, _module.colorbar);
        }

        // TODO could generalize _module.colorscale and use it here?

        if(hasColorscale(trace, 'marker.line')) {
            relinkColorAtts(trace, {
                container: 'marker.line',
                min: 'cmin',
                max: 'cmax'
            });
        }

        if(hasColorscale(trace, 'line')) {
            relinkColorAtts(trace, {
                container: 'line',
                min: 'cmin',
                max: 'cmax'
            });
        }
    }
};

},{"../../lib":694,"./helpers":582}],581:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');
var hasColorbar = _dereq_('../colorbar/has_colorbar');
var colorbarDefaults = _dereq_('../colorbar/defaults');

var isValidScale = _dereq_('./scales').isValid;

function npMaybe(cont, prefix) {
    var containerStr = prefix.slice(0, prefix.length - 1);
    return prefix ?
        Lib.nestedProperty(cont, containerStr).get() || {} :
        cont;
}

module.exports = function colorScaleDefaults(traceIn, traceOut, layout, coerce, opts) {
    var prefix = opts.prefix;
    var cLetter = opts.cLetter;
    var containerIn = npMaybe(traceIn, prefix);
    var containerOut = npMaybe(traceOut, prefix);
    var template = npMaybe(traceOut._template || {}, prefix) || {};

    var minIn = containerIn[cLetter + 'min'];
    var maxIn = containerIn[cLetter + 'max'];
    var validMinMax = isNumeric(minIn) && isNumeric(maxIn) && (minIn < maxIn);
    coerce(prefix + cLetter + 'auto', !validMinMax);
    coerce(prefix + cLetter + 'min');
    coerce(prefix + cLetter + 'max');

    // handles both the trace case (autocolorscale is false by default) and
    // the marker and marker.line case (autocolorscale is true by default)
    var sclIn = containerIn.colorscale;
    var sclTemplate = template.colorscale;
    var autoColorscaleDflt;
    if(sclIn !== undefined) autoColorscaleDflt = !isValidScale(sclIn);
    if(sclTemplate !== undefined) autoColorscaleDflt = !isValidScale(sclTemplate);
    coerce(prefix + 'autocolorscale', autoColorscaleDflt);

    coerce(prefix + 'colorscale');
    coerce(prefix + 'reversescale');

    if(!opts.noScale && prefix !== 'marker.line.') {
        // handles both the trace case where the dflt is listed in attributes and
        // the marker case where the dflt is determined by hasColorbar
        var showScaleDflt;
        if(prefix) showScaleDflt = hasColorbar(containerIn);

        var showScale = coerce(prefix + 'showscale', showScaleDflt);
        if(showScale) colorbarDefaults(containerIn, containerOut, layout);
    }
};

},{"../../lib":694,"../colorbar/defaults":575,"../colorbar/has_colorbar":577,"./scales":586,"fast-isnumeric":215}],582:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var tinycolor = _dereq_('tinycolor2');
var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');
var Color = _dereq_('../color');

var isValidScale = _dereq_('./scales').isValid;

function hasColorscale(trace, containerStr) {
    var container = containerStr ?
        Lib.nestedProperty(trace, containerStr).get() || {} :
        trace;
    var color = container.color;

    var isArrayWithOneNumber = false;
    if(Lib.isArrayOrTypedArray(color)) {
        for(var i = 0; i < color.length; i++) {
            if(isNumeric(color[i])) {
                isArrayWithOneNumber = true;
                break;
            }
        }
    }

    return (
        Lib.isPlainObject(container) && (
            isArrayWithOneNumber ||
            container.showscale === true ||
            (isNumeric(container.cmin) && isNumeric(container.cmax)) ||
            isValidScale(container.colorscale) ||
            Lib.isPlainObject(container.colorbar)
        )
    );
}

/**
 * Extract colorscale into numeric domain and color range.
 *
 * @param {object} cont colorscale container (e.g. trace, marker)
 *  - colorscale {array of arrays}
 *  - cmin/zmin {number}
 *  - cmax/zmax {number}
 *  - reversescale {boolean}
 * @param {object} opts
 *  - cLetter {string} 'c' (for cmin/cmax) or 'z' (for zmin/zmax)
 *
 * @return {object}
 *  - domain {array}
 *  - range {array}
 */
function extractScale(cont, opts) {
    var cLetter = opts.cLetter;

    var scl = cont.reversescale ?
        flipScale(cont.colorscale) :
        cont.colorscale;

    // minimum color value (used to clamp scale)
    var cmin = cont[cLetter + 'min'];
    // maximum color value (used to clamp scale)
    var cmax = cont[cLetter + 'max'];

    var N = scl.length;
    var domain = new Array(N);
    var range = new Array(N);

    for(var i = 0; i < N; i++) {
        var si = scl[i];
        domain[i] = cmin + si[0] * (cmax - cmin);
        range[i] = si[1];
    }

    return {
        domain: domain,
        range: range
    };
}

function flipScale(scl) {
    var N = scl.length;
    var sclNew = new Array(N);

    for(var i = N - 1, j = 0; i >= 0; i--, j++) {
        var si = scl[i];
        sclNew[j] = [1 - si[0], si[1]];
    }
    return sclNew;
}

/**
 * General colorscale function generator.
 *
 * @param {object} specs output of Colorscale.extractScale or precomputed domain, range.
 *  - domain {array}
 *  - range {array}
 *
 * @param {object} opts
 *  - noNumericCheck {boolean} if true, scale func bypasses numeric checks
 *  - returnArray {boolean} if true, scale func return 4-item array instead of color strings
 *
 * @return {function}
 */
function makeColorScaleFunc(specs, opts) {
    opts = opts || {};

    var domain = specs.domain;
    var range = specs.range;
    var N = range.length;
    var _range = new Array(N);

    for(var i = 0; i < N; i++) {
        var rgba = tinycolor(range[i]).toRgb();
        _range[i] = [rgba.r, rgba.g, rgba.b, rgba.a];
    }

    var _sclFunc = d3.scale.linear()
        .domain(domain)
        .range(_range)
        .clamp(true);

    var noNumericCheck = opts.noNumericCheck;
    var returnArray = opts.returnArray;
    var sclFunc;

    if(noNumericCheck && returnArray) {
        sclFunc = _sclFunc;
    }
    else if(noNumericCheck) {
        sclFunc = function(v) {
            return colorArray2rbga(_sclFunc(v));
        };
    }
    else if(returnArray) {
        sclFunc = function(v) {
            if(isNumeric(v)) return _sclFunc(v);
            else if(tinycolor(v).isValid()) return v;
            else return Color.defaultLine;
        };
    }
    else {
        sclFunc = function(v) {
            if(isNumeric(v)) return colorArray2rbga(_sclFunc(v));
            else if(tinycolor(v).isValid()) return v;
            else return Color.defaultLine;
        };
    }

    // colorbar draw looks into the d3 scale closure for domain and range

    sclFunc.domain = _sclFunc.domain;

    sclFunc.range = function() { return range; };

    return sclFunc;
}

function colorArray2rbga(colorArray) {
    var colorObj = {
        r: colorArray[0],
        g: colorArray[1],
        b: colorArray[2],
        a: colorArray[3]
    };

    return tinycolor(colorObj).toRgbString();
}

module.exports = {
    hasColorscale: hasColorscale,
    extractScale: extractScale,
    flipScale: flipScale,
    makeColorScaleFunc: makeColorScaleFunc
};

},{"../../lib":694,"../color":571,"./scales":586,"d3":149,"fast-isnumeric":215,"tinycolor2":515}],583:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scales = _dereq_('./scales');
var helpers = _dereq_('./helpers');

module.exports = {
    moduleType: 'component',
    name: 'colorscale',

    attributes: _dereq_('./attributes'),
    layoutAttributes: _dereq_('./layout_attributes'),

    supplyLayoutDefaults: _dereq_('./layout_defaults'),
    handleDefaults: _dereq_('./defaults'),
    crossTraceDefaults: _dereq_('./cross_trace_defaults'),

    calc: _dereq_('./calc'),

    // ./scales.js is required in lib/coerce.js ;
    // it needs to be a seperate module to avoid circular a dependency
    scales: scales.scales,
    defaultScale: scales.defaultScale,
    getScale: scales.get,
    isValidScale: scales.isValid,

    hasColorscale: helpers.hasColorscale,
    flipScale: helpers.flipScale,
    extractScale: helpers.extractScale,
    makeColorScaleFunc: helpers.makeColorScaleFunc
};

},{"./attributes":578,"./calc":579,"./cross_trace_defaults":580,"./defaults":581,"./helpers":582,"./layout_attributes":584,"./layout_defaults":585,"./scales":586}],584:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scales = _dereq_('./scales').scales;

var msg = 'Note that `autocolorscale` must be true for this attribute to work.';

module.exports = {
    editType: 'calc',
    sequential: {
        valType: 'colorscale',
        dflt: scales.Reds,
        
        editType: 'calc',
        
    },
    sequentialminus: {
        valType: 'colorscale',
        dflt: scales.Blues,
        
        editType: 'calc',
        
    },
    diverging: {
        valType: 'colorscale',
        dflt: scales.RdBu,
        
        editType: 'calc',
        
    }
};

},{"./scales":586}],585:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var colorscaleAttrs = _dereq_('./layout_attributes');
var Template = _dereq_('../../plot_api/plot_template');

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
    var colorscaleIn = layoutIn.colorscale;
    var colorscaleOut = Template.newContainer(layoutOut, 'colorscale');
    function coerce(attr, dflt) {
        return Lib.coerce(colorscaleIn, colorscaleOut, colorscaleAttrs, attr, dflt);
    }

    coerce('sequential');
    coerce('sequentialminus');
    coerce('diverging');
};

},{"../../lib":694,"../../plot_api/plot_template":732,"./layout_attributes":584}],586:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var tinycolor = _dereq_('tinycolor2');

var scales = {
    'Greys': [
        [0, 'rgb(0,0,0)'], [1, 'rgb(255,255,255)']
    ],

    'YlGnBu': [
        [0, 'rgb(8,29,88)'], [0.125, 'rgb(37,52,148)'],
        [0.25, 'rgb(34,94,168)'], [0.375, 'rgb(29,145,192)'],
        [0.5, 'rgb(65,182,196)'], [0.625, 'rgb(127,205,187)'],
        [0.75, 'rgb(199,233,180)'], [0.875, 'rgb(237,248,217)'],
        [1, 'rgb(255,255,217)']
    ],

    'Greens': [
        [0, 'rgb(0,68,27)'], [0.125, 'rgb(0,109,44)'],
        [0.25, 'rgb(35,139,69)'], [0.375, 'rgb(65,171,93)'],
        [0.5, 'rgb(116,196,118)'], [0.625, 'rgb(161,217,155)'],
        [0.75, 'rgb(199,233,192)'], [0.875, 'rgb(229,245,224)'],
        [1, 'rgb(247,252,245)']
    ],

    'YlOrRd': [
        [0, 'rgb(128,0,38)'], [0.125, 'rgb(189,0,38)'],
        [0.25, 'rgb(227,26,28)'], [0.375, 'rgb(252,78,42)'],
        [0.5, 'rgb(253,141,60)'], [0.625, 'rgb(254,178,76)'],
        [0.75, 'rgb(254,217,118)'], [0.875, 'rgb(255,237,160)'],
        [1, 'rgb(255,255,204)']
    ],

    'Bluered': [
        [0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']
    ],

    // modified RdBu based on
    // www.sandia.gov/~kmorel/documents/ColorMaps/ColorMapsExpanded.pdf
    'RdBu': [
        [0, 'rgb(5,10,172)'], [0.35, 'rgb(106,137,247)'],
        [0.5, 'rgb(190,190,190)'], [0.6, 'rgb(220,170,132)'],
        [0.7, 'rgb(230,145,90)'], [1, 'rgb(178,10,28)']
    ],

    // Scale for non-negative numeric values
    'Reds': [
        [0, 'rgb(220,220,220)'], [0.2, 'rgb(245,195,157)'],
        [0.4, 'rgb(245,160,105)'], [1, 'rgb(178,10,28)']
    ],

    // Scale for non-positive numeric values
    'Blues': [
        [0, 'rgb(5,10,172)'], [0.35, 'rgb(40,60,190)'],
        [0.5, 'rgb(70,100,245)'], [0.6, 'rgb(90,120,245)'],
        [0.7, 'rgb(106,137,247)'], [1, 'rgb(220,220,220)']
    ],

    'Picnic': [
        [0, 'rgb(0,0,255)'], [0.1, 'rgb(51,153,255)'],
        [0.2, 'rgb(102,204,255)'], [0.3, 'rgb(153,204,255)'],
        [0.4, 'rgb(204,204,255)'], [0.5, 'rgb(255,255,255)'],
        [0.6, 'rgb(255,204,255)'], [0.7, 'rgb(255,153,255)'],
        [0.8, 'rgb(255,102,204)'], [0.9, 'rgb(255,102,102)'],
        [1, 'rgb(255,0,0)']
    ],

    'Rainbow': [
        [0, 'rgb(150,0,90)'], [0.125, 'rgb(0,0,200)'],
        [0.25, 'rgb(0,25,255)'], [0.375, 'rgb(0,152,255)'],
        [0.5, 'rgb(44,255,150)'], [0.625, 'rgb(151,255,0)'],
        [0.75, 'rgb(255,234,0)'], [0.875, 'rgb(255,111,0)'],
        [1, 'rgb(255,0,0)']
    ],

    'Portland': [
        [0, 'rgb(12,51,131)'], [0.25, 'rgb(10,136,186)'],
        [0.5, 'rgb(242,211,56)'], [0.75, 'rgb(242,143,56)'],
        [1, 'rgb(217,30,30)']
    ],

    'Jet': [
        [0, 'rgb(0,0,131)'], [0.125, 'rgb(0,60,170)'],
        [0.375, 'rgb(5,255,255)'], [0.625, 'rgb(255,255,0)'],
        [0.875, 'rgb(250,0,0)'], [1, 'rgb(128,0,0)']
    ],

    'Hot': [
        [0, 'rgb(0,0,0)'], [0.3, 'rgb(230,0,0)'],
        [0.6, 'rgb(255,210,0)'], [1, 'rgb(255,255,255)']
    ],

    'Blackbody': [
        [0, 'rgb(0,0,0)'], [0.2, 'rgb(230,0,0)'],
        [0.4, 'rgb(230,210,0)'], [0.7, 'rgb(255,255,255)'],
        [1, 'rgb(160,200,255)']
    ],

    'Earth': [
        [0, 'rgb(0,0,130)'], [0.1, 'rgb(0,180,180)'],
        [0.2, 'rgb(40,210,40)'], [0.4, 'rgb(230,230,50)'],
        [0.6, 'rgb(120,70,20)'], [1, 'rgb(255,255,255)']
    ],

    'Electric': [
        [0, 'rgb(0,0,0)'], [0.15, 'rgb(30,0,100)'],
        [0.4, 'rgb(120,0,100)'], [0.6, 'rgb(160,90,0)'],
        [0.8, 'rgb(230,200,0)'], [1, 'rgb(255,250,220)']
    ],

    'Viridis': [
        [0, '#440154'], [0.06274509803921569, '#48186a'],
        [0.12549019607843137, '#472d7b'], [0.18823529411764706, '#424086'],
        [0.25098039215686274, '#3b528b'], [0.3137254901960784, '#33638d'],
        [0.3764705882352941, '#2c728e'], [0.4392156862745098, '#26828e'],
        [0.5019607843137255, '#21918c'], [0.5647058823529412, '#1fa088'],
        [0.6274509803921569, '#28ae80'], [0.6901960784313725, '#3fbc73'],
        [0.7529411764705882, '#5ec962'], [0.8156862745098039, '#84d44b'],
        [0.8784313725490196, '#addc30'], [0.9411764705882353, '#d8e219'],
        [1, '#fde725']
    ],

    'Cividis': [
        [0.000000, 'rgb(0,32,76)'], [0.058824, 'rgb(0,42,102)'],
        [0.117647, 'rgb(0,52,110)'], [0.176471, 'rgb(39,63,108)'],
        [0.235294, 'rgb(60,74,107)'], [0.294118, 'rgb(76,85,107)'],
        [0.352941, 'rgb(91,95,109)'], [0.411765, 'rgb(104,106,112)'],
        [0.470588, 'rgb(117,117,117)'], [0.529412, 'rgb(131,129,120)'],
        [0.588235, 'rgb(146,140,120)'], [0.647059, 'rgb(161,152,118)'],
        [0.705882, 'rgb(176,165,114)'], [0.764706, 'rgb(192,177,109)'],
        [0.823529, 'rgb(209,191,102)'], [0.882353, 'rgb(225,204,92)'],
        [0.941176, 'rgb(243,219,79)'], [1.000000, 'rgb(255,233,69)']
    ]
};

var defaultScale = scales.RdBu;

function getScale(scl, dflt) {
    if(!dflt) dflt = defaultScale;
    if(!scl) return dflt;

    function parseScale() {
        try {
            scl = scales[scl] || JSON.parse(scl);
        } catch(e) {
            scl = dflt;
        }
    }

    if(typeof scl === 'string') {
        parseScale();
        // occasionally scl is double-JSON encoded...
        if(typeof scl === 'string') parseScale();
    }

    if(!isValidScaleArray(scl)) return dflt;
    return scl;
}


function isValidScaleArray(scl) {
    var highestVal = 0;

    if(!Array.isArray(scl) || scl.length < 2) return false;

    if(!scl[0] || !scl[scl.length - 1]) return false;

    if(+scl[0][0] !== 0 || +scl[scl.length - 1][0] !== 1) return false;

    for(var i = 0; i < scl.length; i++) {
        var si = scl[i];

        if(si.length !== 2 || +si[0] < highestVal || !tinycolor(si[1]).isValid()) {
            return false;
        }

        highestVal = +si[0];
    }

    return true;
}

function isValidScale(scl) {
    if(scales[scl] !== undefined) return true;
    else return isValidScaleArray(scl);
}

module.exports = {
    scales: scales,
    defaultScale: defaultScale,

    get: getScale,
    isValid: isValidScale
};

},{"tinycolor2":515}],587:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


// for automatic alignment on dragging, <1/3 means left align,
// >2/3 means right, and between is center. Pick the right fraction
// based on where you are, and return the fraction corresponding to
// that position on the object
module.exports = function align(v, dv, v0, v1, anchor) {
    var vmin = (v - v0) / (v1 - v0);
    var vmax = vmin + dv / (v1 - v0);
    var vc = (vmin + vmax) / 2;

    // explicitly specified anchor
    if(anchor === 'left' || anchor === 'bottom') return vmin;
    if(anchor === 'center' || anchor === 'middle') return vc;
    if(anchor === 'right' || anchor === 'top') return vmax;

    // automatic based on position
    if(vmin < (2 / 3) - vc) return vmin;
    if(vmax > (4 / 3) - vc) return vmax;
    return vc;
};

},{}],588:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');


// set cursors pointing toward the closest corner/side,
// to indicate alignment
// x and y are 0-1, fractions of the plot area
var cursorset = [
    ['sw-resize', 's-resize', 'se-resize'],
    ['w-resize', 'move', 'e-resize'],
    ['nw-resize', 'n-resize', 'ne-resize']
];

module.exports = function getCursor(x, y, xanchor, yanchor) {
    if(xanchor === 'left') x = 0;
    else if(xanchor === 'center') x = 1;
    else if(xanchor === 'right') x = 2;
    else x = Lib.constrain(Math.floor(x * 3), 0, 2);

    if(yanchor === 'bottom') y = 0;
    else if(yanchor === 'middle') y = 1;
    else if(yanchor === 'top') y = 2;
    else y = Lib.constrain(Math.floor(y * 3), 0, 2);

    return cursorset[y][x];
};

},{"../../lib":694}],589:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var mouseOffset = _dereq_('mouse-event-offset');
var hasHover = _dereq_('has-hover');
var supportsPassive = _dereq_('has-passive-events');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');

var constants = _dereq_('../../plots/cartesian/constants');
var interactConstants = _dereq_('../../constants/interactions');

var dragElement = module.exports = {};

dragElement.align = _dereq_('./align');
dragElement.getCursor = _dereq_('./cursor');

var unhover = _dereq_('./unhover');
dragElement.unhover = unhover.wrapped;
dragElement.unhoverRaw = unhover.raw;


/**
 * Abstracts click & drag interactions
 *
 * During the interaction, a "coverSlip" element - a transparent
 * div covering the whole page - is created, which has two key effects:
 * - Lets you drag beyond the boundaries of the plot itself without
 *   dropping (but if you drag all the way out of the browser window the
 *   interaction will end)
 * - Freezes the cursor: whatever mouse cursor the drag element had when the
 *   interaction started gets copied to the coverSlip for use until mouseup
 *
 * If the user executes a drag bigger than MINDRAG, callbacks will fire as:
 *      prepFn, moveFn (1 or more times), doneFn
 * If the user does not drag enough, prepFn and clickFn will fire.
 *
 * Note: If you cancel contextmenu, clickFn will fire even with a right click
 * (unlike native events) so you'll get a `plotly_click` event. Cancel context eg:
 *    gd.addEventListener('contextmenu', function(e) { e.preventDefault(); });
 * TODO: we should probably turn this into a `config` parameter, so we can fix it
 * such that if you *don't* cancel contextmenu, we can prevent partial drags, which
 * put you in a weird state.
 *
 * If the user clicks multiple times quickly, clickFn will fire each time
 * but numClicks will increase to help you recognize doubleclicks.
 *
 * @param {object} options with keys:
 *      element (required) the DOM element to drag
 *      prepFn (optional) function(event, startX, startY)
 *          executed on mousedown
 *          startX and startY are the clientX and clientY pixel position
 *          of the mousedown event
 *      moveFn (optional) function(dx, dy)
 *          executed on move, ONLY after we've exceeded MINDRAG
 *          (we keep executing moveFn if you move back to where you started)
 *          dx and dy are the net pixel offset of the drag,
 *          dragged is true/false, has the mouse moved enough to
 *          constitute a drag
 *      doneFn (optional) function(e)
 *          executed on mouseup, ONLY if we exceeded MINDRAG (so you can be
 *          sure that moveFn has been called at least once)
 *          numClicks is how many clicks we've registered within
 *          a doubleclick time
 *          e is the original mouseup event
 *      clickFn (optional) function(numClicks, e)
 *          executed on mouseup if we have NOT exceeded MINDRAG (ie moveFn
 *          has not been called at all)
 *          numClicks is how many clicks we've registered within
 *          a doubleclick time
 *          e is the original mousedown event
 *      clampFn (optional, function(dx, dy) return [dx2, dy2])
 *          Provide custom clamping function for small displacements.
 *          By default, clamping is done using `minDrag` to x and y displacements
 *          independently.
 */
dragElement.init = function init(options) {
    var gd = options.gd;
    var numClicks = 1;
    var DBLCLICKDELAY = interactConstants.DBLCLICKDELAY;
    var element = options.element;

    var startX,
        startY,
        newMouseDownTime,
        cursor,
        dragCover,
        initialEvent,
        initialTarget,
        rightClick;

    if(!gd._mouseDownTime) gd._mouseDownTime = 0;

    element.style.pointerEvents = 'all';

    element.onmousedown = onStart;

    if(!supportsPassive) {
        element.ontouchstart = onStart;
    }
    else {
        if(element._ontouchstart) {
            element.removeEventListener('touchstart', element._ontouchstart);
        }
        element._ontouchstart = onStart;
        element.addEventListener('touchstart', onStart, {passive: false});
    }

    function _clampFn(dx, dy, minDrag) {
        if(Math.abs(dx) < minDrag) dx = 0;
        if(Math.abs(dy) < minDrag) dy = 0;
        return [dx, dy];
    }

    var clampFn = options.clampFn || _clampFn;

    function onStart(e) {
        // make dragging and dragged into properties of gd
        // so that others can look at and modify them
        gd._dragged = false;
        gd._dragging = true;
        var offset = pointerOffset(e);
        startX = offset[0];
        startY = offset[1];
        initialTarget = e.target;
        initialEvent = e;
        rightClick = e.buttons === 2 || e.ctrlKey;

        // fix Fx.hover for touch events
        if(typeof e.clientX === 'undefined' && typeof e.clientY === 'undefined') {
            e.clientX = startX;
            e.clientY = startY;
        }

        newMouseDownTime = (new Date()).getTime();
        if(newMouseDownTime - gd._mouseDownTime < DBLCLICKDELAY) {
            // in a click train
            numClicks += 1;
        }
        else {
            // new click train
            numClicks = 1;
            gd._mouseDownTime = newMouseDownTime;
        }

        if(options.prepFn) options.prepFn(e, startX, startY);

        if(hasHover && !rightClick) {
            dragCover = coverSlip();
            dragCover.style.cursor = window.getComputedStyle(element).cursor;
        }
        else if(!hasHover) {
            // document acts as a dragcover for mobile, bc we can't create dragcover dynamically
            dragCover = document;
            cursor = window.getComputedStyle(document.documentElement).cursor;
            document.documentElement.style.cursor = window.getComputedStyle(element).cursor;
        }

        document.addEventListener('mouseup', onDone);
        document.addEventListener('touchend', onDone);

        if(options.dragmode !== false) {
            e.preventDefault();
            document.addEventListener('mousemove', onMove);
            document.addEventListener('touchmove', onMove);
        }

        return;
    }

    function onMove(e) {
        e.preventDefault();

        var offset = pointerOffset(e);
        var minDrag = options.minDrag || constants.MINDRAG;
        var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag);
        var dx = dxdy[0];
        var dy = dxdy[1];

        if(dx || dy) {
            gd._dragged = true;
            dragElement.unhover(gd);
        }

        if(gd._dragged && options.moveFn && !rightClick) options.moveFn(dx, dy);

        return;
    }

    function onDone(e) {
        if(options.dragmode !== false) {
            e.preventDefault();
            document.removeEventListener('mousemove', onMove);
            document.removeEventListener('touchmove', onMove);
        }

        document.removeEventListener('mouseup', onDone);
        document.removeEventListener('touchend', onDone);

        if(hasHover) {
            Lib.removeElement(dragCover);
        }
        else if(cursor) {
            dragCover.documentElement.style.cursor = cursor;
            cursor = null;
        }

        if(!gd._dragging) {
            gd._dragged = false;
            return;
        }
        gd._dragging = false;

        // don't count as a dblClick unless the mouseUp is also within
        // the dblclick delay
        if((new Date()).getTime() - gd._mouseDownTime > DBLCLICKDELAY) {
            numClicks = Math.max(numClicks - 1, 1);
        }

        if(gd._dragged) {
            if(options.doneFn) options.doneFn();
        }
        else {
            if(options.clickFn) options.clickFn(numClicks, initialEvent);

            // If we haven't dragged, this should be a click. But because of the
            // coverSlip changing the element, the natural system might not generate one,
            // so we need to make our own. But right clicks don't normally generate
            // click events, only contextmenu events, which happen on mousedown.
            if(!rightClick) {
                var e2;

                try {
                    e2 = new MouseEvent('click', e);
                }
                catch(err) {
                    var offset = pointerOffset(e);
                    e2 = document.createEvent('MouseEvents');
                    e2.initMouseEvent('click',
                        e.bubbles, e.cancelable,
                        e.view, e.detail,
                        e.screenX, e.screenY,
                        offset[0], offset[1],
                        e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,
                        e.button, e.relatedTarget);
                }

                initialTarget.dispatchEvent(e2);
            }
        }

        finishDrag(gd);

        gd._dragged = false;

        return;
    }
};

function coverSlip() {
    var cover = document.createElement('div');

    cover.className = 'dragcover';
    var cStyle = cover.style;
    cStyle.position = 'fixed';
    cStyle.left = 0;
    cStyle.right = 0;
    cStyle.top = 0;
    cStyle.bottom = 0;
    cStyle.zIndex = 999999999;
    cStyle.background = 'none';

    document.body.appendChild(cover);

    return cover;
}

dragElement.coverSlip = coverSlip;

function finishDrag(gd) {
    gd._dragging = false;
    if(gd._replotPending) Registry.call('plot', gd);
}

function pointerOffset(e) {
    return mouseOffset(
        e.changedTouches ? e.changedTouches[0] : e,
        document.body
    );
}

},{"../../constants/interactions":670,"../../lib":694,"../../plots/cartesian/constants":748,"../../registry":825,"./align":587,"./cursor":588,"./unhover":590,"has-hover":396,"has-passive-events":397,"mouse-event-offset":422}],590:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


var Events = _dereq_('../../lib/events');
var throttle = _dereq_('../../lib/throttle');
var getGraphDiv = _dereq_('../../lib/get_graph_div');

var hoverConstants = _dereq_('../fx/constants');

var unhover = module.exports = {};


unhover.wrapped = function(gd, evt, subplot) {
    gd = getGraphDiv(gd);

    // Important, clear any queued hovers
    if(gd._fullLayout) {
        throttle.clear(gd._fullLayout._uid + hoverConstants.HOVERID);
    }

    unhover.raw(gd, evt, subplot);
};


// remove hover effects on mouse out, and emit unhover event
unhover.raw = function unhoverRaw(gd, evt) {
    var fullLayout = gd._fullLayout;
    var oldhoverdata = gd._hoverdata;

    if(!evt) evt = {};
    if(evt.target &&
       Events.triggerHandler(gd, 'plotly_beforehover', evt) === false) {
        return;
    }

    fullLayout._hoverlayer.selectAll('g').remove();
    fullLayout._hoverlayer.selectAll('line').remove();
    fullLayout._hoverlayer.selectAll('circle').remove();
    gd._hoverdata = undefined;

    if(evt.target && oldhoverdata) {
        gd.emit('plotly_unhover', {
            event: evt,
            points: oldhoverdata
        });
    }
};

},{"../../lib/events":683,"../../lib/get_graph_div":690,"../../lib/throttle":719,"../fx/constants":604}],591:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

exports.dash = {
    valType: 'string',
    // string type usually doesn't take values... this one should really be
    // a special type or at least a special coercion function, from the GUI
    // you only get these values but elsewhere the user can supply a list of
    // dash lengths in px, and it will be honored
    values: ['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot'],
    dflt: 'solid',
    
    editType: 'style',
    
};

},{}],592:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');
var tinycolor = _dereq_('tinycolor2');

var Registry = _dereq_('../../registry');
var Color = _dereq_('../color');
var Colorscale = _dereq_('../colorscale');
var Lib = _dereq_('../../lib');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');

var xmlnsNamespaces = _dereq_('../../constants/xmlns_namespaces');
var alignment = _dereq_('../../constants/alignment');
var LINE_SPACING = alignment.LINE_SPACING;
var DESELECTDIM = _dereq_('../../constants/interactions').DESELECTDIM;

var subTypes = _dereq_('../../traces/scatter/subtypes');
var makeBubbleSizeFn = _dereq_('../../traces/scatter/make_bubble_size_func');

var drawing = module.exports = {};

// -----------------------------------------------------
// styling functions for plot elements
// -----------------------------------------------------

drawing.font = function(s, family, size, color) {
    // also allow the form font(s, {family, size, color})
    if(Lib.isPlainObject(family)) {
        color = family.color;
        size = family.size;
        family = family.family;
    }
    if(family) s.style('font-family', family);
    if(size + 1) s.style('font-size', size + 'px');
    if(color) s.call(Color.fill, color);
};

/*
 * Positioning helpers
 * Note: do not use `setPosition` with <text> nodes modified by
 * `svgTextUtils.convertToTspans`. Use `svgTextUtils.positionText`
 * instead, so that <tspan.line> elements get updated to match.
 */
drawing.setPosition = function(s, x, y) { s.attr('x', x).attr('y', y); };
drawing.setSize = function(s, w, h) { s.attr('width', w).attr('height', h); };
drawing.setRect = function(s, x, y, w, h) {
    s.call(drawing.setPosition, x, y).call(drawing.setSize, w, h);
};

/** Translate node
 *
 * @param {object} d : calcdata point item
 * @param {sel} sel : d3 selction of node to translate
 * @param {object} xa : corresponding full xaxis object
 * @param {object} ya : corresponding full yaxis object
 *
 * @return {boolean} :
 *  true if selection got translated
 *  false if selection could not get translated
 */
drawing.translatePoint = function(d, sel, xa, ya) {
    var x = xa.c2p(d.x);
    var y = ya.c2p(d.y);

    if(isNumeric(x) && isNumeric(y) && sel.node()) {
        // for multiline text this works better
        if(sel.node().nodeName === 'text') {
            sel.attr('x', x).attr('y', y);
        } else {
            sel.attr('transform', 'translate(' + x + ',' + y + ')');
        }
    } else {
        return false;
    }

    return true;
};

drawing.translatePoints = function(s, xa, ya) {
    s.each(function(d) {
        var sel = d3.select(this);
        drawing.translatePoint(d, sel, xa, ya);
    });
};

drawing.hideOutsideRangePoint = function(d, sel, xa, ya, xcalendar, ycalendar) {
    sel.attr(
        'display',
        (xa.isPtWithinRange(d, xcalendar) && ya.isPtWithinRange(d, ycalendar)) ? null : 'none'
    );
};

drawing.hideOutsideRangePoints = function(traceGroups, subplot) {
    if(!subplot._hasClipOnAxisFalse) return;

    var xa = subplot.xaxis;
    var ya = subplot.yaxis;

    traceGroups.each(function(d) {
        var trace = d[0].trace;
        var xcalendar = trace.xcalendar;
        var ycalendar = trace.ycalendar;
        var selector = trace.type === 'bar' ? '.bartext' : '.point,.textpoint';

        traceGroups.selectAll(selector).each(function(d) {
            drawing.hideOutsideRangePoint(d, d3.select(this), xa, ya, xcalendar, ycalendar);
        });
    });
};

drawing.crispRound = function(gd, lineWidth, dflt) {
    // for lines that disable antialiasing we want to
    // make sure the width is an integer, and at least 1 if it's nonzero

    if(!lineWidth || !isNumeric(lineWidth)) return dflt || 0;

    // but not for static plots - these don't get antialiased anyway.
    if(gd._context.staticPlot) return lineWidth;

    if(lineWidth < 1) return 1;
    return Math.round(lineWidth);
};

drawing.singleLineStyle = function(d, s, lw, lc, ld) {
    s.style('fill', 'none');
    var line = (((d || [])[0] || {}).trace || {}).line || {};
    var lw1 = lw || line.width||0;
    var dash = ld || line.dash || '';

    Color.stroke(s, lc || line.color);
    drawing.dashLine(s, dash, lw1);
};

drawing.lineGroupStyle = function(s, lw, lc, ld) {
    s.style('fill', 'none')
    .each(function(d) {
        var line = (((d || [])[0] || {}).trace || {}).line || {};
        var lw1 = lw || line.width||0;
        var dash = ld || line.dash || '';

        d3.select(this)
            .call(Color.stroke, lc || line.color)
            .call(drawing.dashLine, dash, lw1);
    });
};

drawing.dashLine = function(s, dash, lineWidth) {
    lineWidth = +lineWidth || 0;

    dash = drawing.dashStyle(dash, lineWidth);

    s.style({
        'stroke-dasharray': dash,
        'stroke-width': lineWidth + 'px'
    });
};

drawing.dashStyle = function(dash, lineWidth) {
    lineWidth = +lineWidth || 1;
    var dlw = Math.max(lineWidth, 3);

    if(dash === 'solid') dash = '';
    else if(dash === 'dot') dash = dlw + 'px,' + dlw + 'px';
    else if(dash === 'dash') dash = (3 * dlw) + 'px,' + (3 * dlw) + 'px';
    else if(dash === 'longdash') dash = (5 * dlw) + 'px,' + (5 * dlw) + 'px';
    else if(dash === 'dashdot') {
        dash = (3 * dlw) + 'px,' + dlw + 'px,' + dlw + 'px,' + dlw + 'px';
    }
    else if(dash === 'longdashdot') {
        dash = (5 * dlw) + 'px,' + (2 * dlw) + 'px,' + dlw + 'px,' + (2 * dlw) + 'px';
    }
    // otherwise user wrote the dasharray themselves - leave it be

    return dash;
};

// Same as fillGroupStyle, except in this case the selection may be a transition
drawing.singleFillStyle = function(sel) {
    var node = d3.select(sel.node());
    var data = node.data();
    var fillcolor = (((data[0] || [])[0] || {}).trace || {}).fillcolor;
    if(fillcolor) {
        sel.call(Color.fill, fillcolor);
    }
};

drawing.fillGroupStyle = function(s) {
    s.style('stroke-width', 0)
    .each(function(d) {
        var shape = d3.select(this);
        // N.B. 'd' won't be a calcdata item when
        // fill !== 'none' on a segment-less and marker-less trace
        if(d[0].trace) {
            shape.call(Color.fill, d[0].trace.fillcolor);
        }
    });
};

var SYMBOLDEFS = _dereq_('./symbol_defs');

drawing.symbolNames = [];
drawing.symbolFuncs = [];
drawing.symbolNeedLines = {};
drawing.symbolNoDot = {};
drawing.symbolNoFill = {};
drawing.symbolList = [];

Object.keys(SYMBOLDEFS).forEach(function(k) {
    var symDef = SYMBOLDEFS[k];
    drawing.symbolList = drawing.symbolList.concat(
        [symDef.n, k, symDef.n + 100, k + '-open']);
    drawing.symbolNames[symDef.n] = k;
    drawing.symbolFuncs[symDef.n] = symDef.f;
    if(symDef.needLine) {
        drawing.symbolNeedLines[symDef.n] = true;
    }
    if(symDef.noDot) {
        drawing.symbolNoDot[symDef.n] = true;
    }
    else {
        drawing.symbolList = drawing.symbolList.concat(
            [symDef.n + 200, k + '-dot', symDef.n + 300, k + '-open-dot']);
    }
    if(symDef.noFill) {
        drawing.symbolNoFill[symDef.n] = true;
    }
});

var MAXSYMBOL = drawing.symbolNames.length;
// add a dot in the middle of the symbol
var DOTPATH = 'M0,0.5L0.5,0L0,-0.5L-0.5,0Z';

drawing.symbolNumber = function(v) {
    if(typeof v === 'string') {
        var vbase = 0;
        if(v.indexOf('-open') > 0) {
            vbase = 100;
            v = v.replace('-open', '');
        }
        if(v.indexOf('-dot') > 0) {
            vbase += 200;
            v = v.replace('-dot', '');
        }
        v = drawing.symbolNames.indexOf(v);
        if(v >= 0) { v += vbase; }
    }
    if((v % 100 >= MAXSYMBOL) || v >= 400) { return 0; }
    return Math.floor(Math.max(v, 0));
};

function makePointPath(symbolNumber, r) {
    var base = symbolNumber % 100;
    return drawing.symbolFuncs[base](r) + (symbolNumber >= 200 ? DOTPATH : '');
}

var HORZGRADIENT = {x1: 1, x2: 0, y1: 0, y2: 0};
var VERTGRADIENT = {x1: 0, x2: 0, y1: 1, y2: 0};
var stopFormatter = d3.format('~.1f');
var gradientInfo = {
    radial: {node: 'radialGradient'},
    radialreversed: {node: 'radialGradient', reversed: true},
    horizontal: {node: 'linearGradient', attrs: HORZGRADIENT},
    horizontalreversed: {node: 'linearGradient', attrs: HORZGRADIENT, reversed: true},
    vertical: {node: 'linearGradient', attrs: VERTGRADIENT},
    verticalreversed: {node: 'linearGradient', attrs: VERTGRADIENT, reversed: true}
};

/**
 * gradient: create and apply a gradient fill
 *
 * @param {object} sel: d3 selection to apply this gradient to
 *     You can use `selection.call(Drawing.gradient, ...)`
 * @param {DOM element} gd: the graph div `sel` is part of
 * @param {string} gradientID: a unique (within this plot) identifier
 *     for this gradient, so that we don't create unnecessary definitions
 * @param {string} type: 'radial', 'horizontal', or 'vertical', optionally with
 *     'reversed' at the end. Normally radial goes center to edge,
 *     horizontal goes right to left, and vertical goes bottom to top
 * @param {array} colorscale: as in attribute values, [[fraction, color], ...]
 * @param {string} prop: the property to apply to, 'fill' or 'stroke'
 */
drawing.gradient = function(sel, gd, gradientID, type, colorscale, prop) {
    var len = colorscale.length;
    var info = gradientInfo[type];
    var colorStops = new Array(len);
    for(var i = 0; i < len; i++) {
        if(info.reversed) {
            colorStops[len - 1 - i] = [stopFormatter((1 - colorscale[i][0]) * 100), colorscale[i][1]];
        }
        else {
            colorStops[i] = [stopFormatter(colorscale[i][0] * 100), colorscale[i][1]];
        }
    }

    var fullID = 'g' + gd._fullLayout._uid + '-' + gradientID;

    var gradient = gd._fullLayout._defs.select('.gradients')
        .selectAll('#' + fullID)
        .data([type + colorStops.join(';')], Lib.identity);

    gradient.exit().remove();

    gradient.enter()
        .append(info.node)
        .each(function() {
            var el = d3.select(this);
            if(info.attrs) el.attr(info.attrs);

            el.attr('id', fullID);

            var stops = el.selectAll('stop')
                .data(colorStops);
            stops.exit().remove();
            stops.enter().append('stop');

            stops.each(function(d) {
                var tc = tinycolor(d[1]);
                d3.select(this).attr({
                    offset: d[0] + '%',
                    'stop-color': Color.tinyRGB(tc),
                    'stop-opacity': tc.getAlpha()
                });
            });
        });

    sel.style(prop, 'url(#' + fullID + ')')
        .style(prop + '-opacity', null);
};

/*
 * Make the gradients container and clear out any previous gradients.
 * We never collect all the gradients we need in one place,
 * so we can't ever remove gradients that have stopped being useful,
 * except all at once before a full redraw.
 * The upside of this is arbitrary points can share gradient defs
 */
drawing.initGradients = function(gd) {
    var gradientsGroup = Lib.ensureSingle(gd._fullLayout._defs, 'g', 'gradients');
    gradientsGroup.selectAll('linearGradient,radialGradient').remove();
};


drawing.pointStyle = function(s, trace, gd) {
    if(!s.size()) return;

    var fns = drawing.makePointStyleFns(trace);

    s.each(function(d) {
        drawing.singlePointStyle(d, d3.select(this), trace, fns, gd);
    });
};

drawing.singlePointStyle = function(d, sel, trace, fns, gd) {
    var marker = trace.marker;
    var markerLine = marker.line;

    sel.style('opacity',
        fns.selectedOpacityFn ? fns.selectedOpacityFn(d) :
            (d.mo === undefined ? marker.opacity : d.mo)
    );

    if(fns.ms2mrc) {
        var r;

        // handle multi-trace graph edit case
        if(d.ms === 'various' || marker.size === 'various') {
            r = 3;
        } else {
            r = fns.ms2mrc(d.ms);
        }

        // store the calculated size so hover can use it
        d.mrc = r;

        if(fns.selectedSizeFn) {
            r = d.mrc = fns.selectedSizeFn(d);
        }

        // turn the symbol into a sanitized number
        var x = drawing.symbolNumber(d.mx || marker.symbol) || 0;

        // save if this marker is open
        // because that impacts how to handle colors
        d.om = x % 200 >= 100;

        sel.attr('d', makePointPath(x, r));
    }

    var perPointGradient = false;
    var fillColor, lineColor, lineWidth;

    // 'so' is suspected outliers, for box plots
    if(d.so) {
        lineWidth = markerLine.outlierwidth;
        lineColor = markerLine.outliercolor;
        fillColor = marker.outliercolor;
    } else {
        var markerLineWidth = (markerLine || {}).width;

        lineWidth = (
            d.mlw + 1 ||
            markerLineWidth + 1 ||
            // TODO: we need the latter for legends... can we get rid of it?
            (d.trace ? (d.trace.marker.line || {}).width : 0) + 1
        ) - 1 || 0;

        if('mlc' in d) lineColor = d.mlcc = fns.lineScale(d.mlc);
        // weird case: array wasn't long enough to apply to every point
        else if(Lib.isArrayOrTypedArray(markerLine.color)) lineColor = Color.defaultLine;
        else lineColor = markerLine.color;

        if(Lib.isArrayOrTypedArray(marker.color)) {
            fillColor = Color.defaultLine;
            perPointGradient = true;
        }

        if('mc' in d) {
            fillColor = d.mcc = fns.markerScale(d.mc);
        } else {
            fillColor = marker.color || 'rgba(0,0,0,0)';
        }

        if(fns.selectedColorFn) {
            fillColor = fns.selectedColorFn(d);
        }
    }

    if(d.om) {
        // open markers can't have zero linewidth, default to 1px,
        // and use fill color as stroke color
        sel.call(Color.stroke, fillColor)
            .style({
                'stroke-width': (lineWidth || 1) + 'px',
                fill: 'none'
            });
    } else {
        sel.style('stroke-width', lineWidth + 'px');

        var markerGradient = marker.gradient;

        var gradientType = d.mgt;
        if(gradientType) perPointGradient = true;
        else gradientType = markerGradient && markerGradient.type;

        // for legend - arrays will propagate through here, but we don't need
        // to treat it as per-point.
        if(Array.isArray(gradientType)) {
            gradientType = gradientType[0];
            if(!gradientInfo[gradientType]) gradientType = 0;
        }

        if(gradientType && gradientType !== 'none') {
            var gradientColor = d.mgc;
            if(gradientColor) perPointGradient = true;
            else gradientColor = markerGradient.color;

            var gradientID = trace.uid;
            if(perPointGradient) gradientID += '-' + d.i;

            drawing.gradient(sel, gd, gradientID, gradientType,
                [[0, gradientColor], [1, fillColor]], 'fill');
        } else {
            Color.fill(sel, fillColor);
        }

        if(lineWidth) {
            Color.stroke(sel, lineColor);
        }
    }
};

drawing.makePointStyleFns = function(trace) {
    var out = {};
    var marker = trace.marker;

    // allow array marker and marker line colors to be
    // scaled by given max and min to colorscales
    out.markerScale = drawing.tryColorscale(marker, '');
    out.lineScale = drawing.tryColorscale(marker, 'line');

    if(Registry.traceIs(trace, 'symbols')) {
        out.ms2mrc = subTypes.isBubble(trace) ?
            makeBubbleSizeFn(trace) :
            function() { return (marker.size || 6) / 2; };
    }

    if(trace.selectedpoints) {
        Lib.extendFlat(out, drawing.makeSelectedPointStyleFns(trace));
    }

    return out;
};

drawing.makeSelectedPointStyleFns = function(trace) {
    var out = {};

    var selectedAttrs = trace.selected || {};
    var unselectedAttrs = trace.unselected || {};

    var marker = trace.marker || {};
    var selectedMarker = selectedAttrs.marker || {};
    var unselectedMarker = unselectedAttrs.marker || {};

    var mo = marker.opacity;
    var smo = selectedMarker.opacity;
    var usmo = unselectedMarker.opacity;
    var smoIsDefined = smo !== undefined;
    var usmoIsDefined = usmo !== undefined;

    if(Lib.isArrayOrTypedArray(mo) || smoIsDefined || usmoIsDefined) {
        out.selectedOpacityFn = function(d) {
            var base = d.mo === undefined ? marker.opacity : d.mo;

            if(d.selected) {
                return smoIsDefined ? smo : base;
            } else {
                return usmoIsDefined ? usmo : DESELECTDIM * base;
            }
        };
    }

    var mc = marker.color;
    var smc = selectedMarker.color;
    var usmc = unselectedMarker.color;

    if(smc || usmc) {
        out.selectedColorFn = function(d) {
            var base = d.mcc || mc;

            if(d.selected) {
                return smc || base;
            } else {
                return usmc || base;
            }
        };
    }

    var ms = marker.size;
    var sms = selectedMarker.size;
    var usms = unselectedMarker.size;
    var smsIsDefined = sms !== undefined;
    var usmsIsDefined = usms !== undefined;

    if(Registry.traceIs(trace, 'symbols') && (smsIsDefined || usmsIsDefined)) {
        out.selectedSizeFn = function(d) {
            var base = d.mrc || ms / 2;

            if(d.selected) {
                return smsIsDefined ? sms / 2 : base;
            } else {
                return usmsIsDefined ? usms / 2 : base;
            }
        };
    }

    return out;
};

drawing.makeSelectedTextStyleFns = function(trace) {
    var out = {};

    var selectedAttrs = trace.selected || {};
    var unselectedAttrs = trace.unselected || {};

    var textFont = trace.textfont || {};
    var selectedTextFont = selectedAttrs.textfont || {};
    var unselectedTextFont = unselectedAttrs.textfont || {};

    var tc = textFont.color;
    var stc = selectedTextFont.color;
    var utc = unselectedTextFont.color;

    out.selectedTextColorFn = function(d) {
        var base = d.tc || tc;

        if(d.selected) {
            return stc || base;
        } else {
            if(utc) return utc;
            else return stc ? base : Color.addOpacity(base, DESELECTDIM);
        }
    };

    return out;
};

drawing.selectedPointStyle = function(s, trace) {
    if(!s.size() || !trace.selectedpoints) return;

    var fns = drawing.makeSelectedPointStyleFns(trace);
    var marker = trace.marker || {};
    var seq = [];

    if(fns.selectedOpacityFn) {
        seq.push(function(pt, d) {
            pt.style('opacity', fns.selectedOpacityFn(d));
        });
    }

    if(fns.selectedColorFn) {
        seq.push(function(pt, d) {
            Color.fill(pt, fns.selectedColorFn(d));
        });
    }

    if(fns.selectedSizeFn) {
        seq.push(function(pt, d) {
            var mx = d.mx || marker.symbol || 0;
            var mrc2 = fns.selectedSizeFn(d);

            pt.attr('d', makePointPath(drawing.symbolNumber(mx), mrc2));

            // save for Drawing.selectedTextStyle
            d.mrc2 = mrc2;
        });
    }

    if(seq.length) {
        s.each(function(d) {
            var pt = d3.select(this);
            for(var i = 0; i < seq.length; i++) {
                seq[i](pt, d);
            }
        });
    }
};

drawing.tryColorscale = function(marker, prefix) {
    var cont = prefix ? Lib.nestedProperty(marker, prefix).get() : marker;

    if(cont) {
        var scl = cont.colorscale;
        var colorArray = cont.color;

        if(scl && Lib.isArrayOrTypedArray(colorArray)) {
            return Colorscale.makeColorScaleFunc(
                Colorscale.extractScale(cont, {cLetter: 'c'})
            );
        }
    }
    return Lib.identity;
};

var TEXTOFFSETSIGN = {
    start: 1, end: -1, middle: 0, bottom: 1, top: -1
};

function textPointPosition(s, textPosition, fontSize, markerRadius) {
    var group = d3.select(s.node().parentNode);

    var v = textPosition.indexOf('top') !== -1 ?
        'top' :
        textPosition.indexOf('bottom') !== -1 ? 'bottom' : 'middle';
    var h = textPosition.indexOf('left') !== -1 ?
        'end' :
        textPosition.indexOf('right') !== -1 ? 'start' : 'middle';

    // if markers are shown, offset a little more than
    // the nominal marker size
    // ie 2/1.6 * nominal, bcs some markers are a bit bigger
    var r = markerRadius ? markerRadius / 0.8 + 1 : 0;

    var numLines = (svgTextUtils.lineCount(s) - 1) * LINE_SPACING + 1;
    var dx = TEXTOFFSETSIGN[h] * r;
    var dy = fontSize * 0.75 + TEXTOFFSETSIGN[v] * r +
        (TEXTOFFSETSIGN[v] - 1) * numLines * fontSize / 2;

    // fix the overall text group position
    s.attr('text-anchor', h);
    group.attr('transform', 'translate(' + dx + ',' + dy + ')');
}

function extracTextFontSize(d, trace) {
    var fontSize = d.ts || trace.textfont.size;
    return (isNumeric(fontSize) && fontSize > 0) ? fontSize : 0;
}

// draw text at points
drawing.textPointStyle = function(s, trace, gd) {
    if(!s.size()) return;

    var selectedTextColorFn;

    if(trace.selectedpoints) {
        var fns = drawing.makeSelectedTextStyleFns(trace);
        selectedTextColorFn = fns.selectedTextColorFn;
    }

    s.each(function(d) {
        var p = d3.select(this);
        var text = Lib.extractOption(d, trace, 'tx', 'text');

        if(!text && text !== 0) {
            p.remove();
            return;
        }

        var pos = d.tp || trace.textposition;
        var fontSize = extracTextFontSize(d, trace);
        var fontColor = selectedTextColorFn ?
            selectedTextColorFn(d) :
            (d.tc || trace.textfont.color);

        p.call(drawing.font,
                d.tf || trace.textfont.family,
                fontSize,
                fontColor)
            .text(text)
            .call(svgTextUtils.convertToTspans, gd)
            .call(textPointPosition, pos, fontSize, d.mrc);
    });
};

drawing.selectedTextStyle = function(s, trace) {
    if(!s.size() || !trace.selectedpoints) return;

    var fns = drawing.makeSelectedTextStyleFns(trace);

    s.each(function(d) {
        var tx = d3.select(this);
        var tc = fns.selectedTextColorFn(d);
        var tp = d.tp || trace.textposition;
        var fontSize = extracTextFontSize(d, trace);

        Color.fill(tx, tc);
        textPointPosition(tx, tp, fontSize, d.mrc2 || d.mrc);
    });
};

// generalized Catmull-Rom splines, per
// http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
var CatmullRomExp = 0.5;
drawing.smoothopen = function(pts, smoothness) {
    if(pts.length < 3) { return 'M' + pts.join('L');}
    var path = 'M' + pts[0];
    var tangents = [];
    var i;
    for(i = 1; i < pts.length - 1; i++) {
        tangents.push(makeTangent(pts[i - 1], pts[i], pts[i + 1], smoothness));
    }
    path += 'Q' + tangents[0][0] + ' ' + pts[1];
    for(i = 2; i < pts.length - 1; i++) {
        path += 'C' + tangents[i - 2][1] + ' ' + tangents[i - 1][0] + ' ' + pts[i];
    }
    path += 'Q' + tangents[pts.length - 3][1] + ' ' + pts[pts.length - 1];
    return path;
};

drawing.smoothclosed = function(pts, smoothness) {
    if(pts.length < 3) { return 'M' + pts.join('L') + 'Z'; }
    var path = 'M' + pts[0];
    var pLast = pts.length - 1;
    var tangents = [makeTangent(pts[pLast], pts[0], pts[1], smoothness)];
    var i;
    for(i = 1; i < pLast; i++) {
        tangents.push(makeTangent(pts[i - 1], pts[i], pts[i + 1], smoothness));
    }
    tangents.push(
        makeTangent(pts[pLast - 1], pts[pLast], pts[0], smoothness)
    );

    for(i = 1; i <= pLast; i++) {
        path += 'C' + tangents[i - 1][1] + ' ' + tangents[i][0] + ' ' + pts[i];
    }
    path += 'C' + tangents[pLast][1] + ' ' + tangents[0][0] + ' ' + pts[0] + 'Z';
    return path;
};

function makeTangent(prevpt, thispt, nextpt, smoothness) {
    var d1x = prevpt[0] - thispt[0];
    var d1y = prevpt[1] - thispt[1];
    var d2x = nextpt[0] - thispt[0];
    var d2y = nextpt[1] - thispt[1];
    var d1a = Math.pow(d1x * d1x + d1y * d1y, CatmullRomExp / 2);
    var d2a = Math.pow(d2x * d2x + d2y * d2y, CatmullRomExp / 2);
    var numx = (d2a * d2a * d1x - d1a * d1a * d2x) * smoothness;
    var numy = (d2a * d2a * d1y - d1a * d1a * d2y) * smoothness;
    var denom1 = 3 * d2a * (d1a + d2a);
    var denom2 = 3 * d1a * (d1a + d2a);
    return [
        [
            d3.round(thispt[0] + (denom1 && numx / denom1), 2),
            d3.round(thispt[1] + (denom1 && numy / denom1), 2)
        ], [
            d3.round(thispt[0] - (denom2 && numx / denom2), 2),
            d3.round(thispt[1] - (denom2 && numy / denom2), 2)
        ]
    ];
}

// step paths - returns a generator function for paths
// with the given step shape
var STEPPATH = {
    hv: function(p0, p1) {
        return 'H' + d3.round(p1[0], 2) + 'V' + d3.round(p1[1], 2);
    },
    vh: function(p0, p1) {
        return 'V' + d3.round(p1[1], 2) + 'H' + d3.round(p1[0], 2);
    },
    hvh: function(p0, p1) {
        return 'H' + d3.round((p0[0] + p1[0]) / 2, 2) + 'V' +
            d3.round(p1[1], 2) + 'H' + d3.round(p1[0], 2);
    },
    vhv: function(p0, p1) {
        return 'V' + d3.round((p0[1] + p1[1]) / 2, 2) + 'H' +
            d3.round(p1[0], 2) + 'V' + d3.round(p1[1], 2);
    }
};
var STEPLINEAR = function(p0, p1) {
    return 'L' + d3.round(p1[0], 2) + ',' + d3.round(p1[1], 2);
};
drawing.steps = function(shape) {
    var onestep = STEPPATH[shape] || STEPLINEAR;
    return function(pts) {
        var path = 'M' + d3.round(pts[0][0], 2) + ',' + d3.round(pts[0][1], 2);
        for(var i = 1; i < pts.length; i++) {
            path += onestep(pts[i - 1], pts[i]);
        }
        return path;
    };
};

// off-screen svg render testing element, shared by the whole page
// uses the id 'js-plotly-tester' and stores it in drawing.tester
drawing.makeTester = function() {
    var tester = Lib.ensureSingleById(d3.select('body'), 'svg', 'js-plotly-tester', function(s) {
        s.attr(xmlnsNamespaces.svgAttrs)
            .style({
                position: 'absolute',
                left: '-10000px',
                top: '-10000px',
                width: '9000px',
                height: '9000px',
                'z-index': '1'
            });
    });

    // browsers differ on how they describe the bounding rect of
    // the svg if its contents spill over... so make a 1x1px
    // reference point we can measure off of.
    var testref = Lib.ensureSingle(tester, 'path', 'js-reference-point', function(s) {
        s.attr('d', 'M0,0H1V1H0Z')
            .style({
                'stroke-width': 0,
                fill: 'black'
            });
    });

    drawing.tester = tester;
    drawing.testref = testref;
};

/*
 * use our offscreen tester to get a clientRect for an element,
 * in a reference frame where it isn't translated (or transformed) and
 * its anchor point is at (0,0)
 * always returns a copy of the bbox, so the caller can modify it safely
 *
 * @param {SVGElement} node: the element to measure. If possible this should be
 *   a <text> or MathJax <g> element that's already passed through
 *   `convertToTspans` because in that case we can cache the results, but it's
 *   possible to pass in any svg element.
 *
 * @param {boolean} inTester: is this element already in `drawing.tester`?
 *   If you are measuring a dummy element, rather than one you really intend
 *   to use on the plot, making it in `drawing.tester` in the first place
 *   allows us to test faster because it cuts out cloning and appending it.
 *
 * @param {string} hash: for internal use only, if we already know the cache key
 *   for this element beforehand.
 *
 * @return {object}: a plain object containing the width, height, left, right,
 *   top, and bottom of `node`
 */
drawing.savedBBoxes = {};
var savedBBoxesCount = 0;
var maxSavedBBoxes = 10000;

drawing.bBox = function(node, inTester, hash) {
    /*
     * Cache elements we've already measured so we don't have to
     * remeasure the same thing many times
     * We have a few bBox callers though who pass a node larger than
     * a <text> or a MathJax <g>, such as an axis group containing many labels.
     * These will not generate a hash (unless we figure out an appropriate
     * hash key for them) and thus we will not hash them.
     */
    if(!hash) hash = nodeHash(node);
    var out;
    if(hash) {
        out = drawing.savedBBoxes[hash];
        if(out) return Lib.extendFlat({}, out);
    }
    else if(node.childNodes.length === 1) {
        /*
         * If we have only one child element, which is itself hashable, make
         * a new hash from this element plus its x,y,transform
         * These bounding boxes *include* x,y,transform - mostly for use by
         * callers trying to avoid overlaps (ie titles)
         */
        var innerNode = node.childNodes[0];

        hash = nodeHash(innerNode);
        if(hash) {
            var x = +innerNode.getAttribute('x') || 0;
            var y = +innerNode.getAttribute('y') || 0;
            var transform = innerNode.getAttribute('transform');

            if(!transform) {
                // in this case, just varying x and y, don't bother caching
                // the final bBox because the alteration is quick.
                var innerBB = drawing.bBox(innerNode, false, hash);
                if(x) {
                    innerBB.left += x;
                    innerBB.right += x;
                }
                if(y) {
                    innerBB.top += y;
                    innerBB.bottom += y;
                }
                return innerBB;
            }
            /*
             * else we have a transform - rather than make a complicated
             * (and error-prone and probably slow) transform parser/calculator,
             * just continue on calculating the boundingClientRect of the group
             * and use the new composite hash to cache it.
             * That said, `innerNode.transform.baseVal` is an array of
             * `SVGTransform` objects, that *do* seem to have a nice matrix
             * multiplication interface that we could use to avoid making
             * another getBoundingClientRect call...
             */
            hash += '~' + x + '~' + y + '~' + transform;

            out = drawing.savedBBoxes[hash];
            if(out) return Lib.extendFlat({}, out);
        }
    }
    var testNode, tester;
    if(inTester) {
        testNode = node;
    }
    else {
        tester = drawing.tester.node();

        // copy the node to test into the tester
        testNode = node.cloneNode(true);
        tester.appendChild(testNode);
    }

    // standardize its position (and newline tspans if any)
    d3.select(testNode)
        .attr('transform', null)
        .call(svgTextUtils.positionText, 0, 0);

    var testRect = testNode.getBoundingClientRect();
    var refRect = drawing.testref
        .node()
        .getBoundingClientRect();

    if(!inTester) tester.removeChild(testNode);

    var bb = {
        height: testRect.height,
        width: testRect.width,
        left: testRect.left - refRect.left,
        top: testRect.top - refRect.top,
        right: testRect.right - refRect.left,
        bottom: testRect.bottom - refRect.top
    };

    // make sure we don't have too many saved boxes,
    // or a long session could overload on memory
    // by saving boxes for long-gone elements
    if(savedBBoxesCount >= maxSavedBBoxes) {
        drawing.savedBBoxes = {};
        savedBBoxesCount = 0;
    }

    // cache this bbox
    if(hash) drawing.savedBBoxes[hash] = bb;
    savedBBoxesCount++;

    return Lib.extendFlat({}, bb);
};

// capture everything about a node (at least in our usage) that
// impacts its bounding box, given that bBox clears x, y, and transform
function nodeHash(node) {
    var inputText = node.getAttribute('data-unformatted');
    if(inputText === null) return;
    return inputText +
        node.getAttribute('data-math') +
        node.getAttribute('text-anchor') +
        node.getAttribute('style');
}

/**
 * Set clipPath URL in a way that work for all situations.
 *
 * In details, graphs on pages with <base> HTML tags need to prepend
 * the clip path ids with the page's base url EXCEPT during toImage exports.
 *
 * @param {d3 selection} s : node to add clip-path attribute
 * @param {string} localId : local clip-path (w/o base url) id
 * @param {DOM element || object} gd
 * - context._baseUrl {string}
 * - context._exportedPlot {boolean}
 */
drawing.setClipUrl = function(s, localId, gd) {
    if(!localId) {
        s.attr('clip-path', null);
        return;
    }

    var context = gd._context;
    var baseUrl = context._exportedPlot ? '' : (context._baseUrl || '');

    s.attr('clip-path', 'url(' + baseUrl + '#' + localId + ')');
};

drawing.getTranslate = function(element) {
    // Note the separator [^\d] between x and y in this regex
    // We generally use ',' but IE will convert it to ' '
    var re = /.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/;
    var getter = element.attr ? 'attr' : 'getAttribute';
    var transform = element[getter]('transform') || '';

    var translate = transform.replace(re, function(match, p1, p2) {
        return [p1, p2].join(' ');
    })
    .split(' ');

    return {
        x: +translate[0] || 0,
        y: +translate[1] || 0
    };
};

drawing.setTranslate = function(element, x, y) {
    var re = /(\btranslate\(.*?\);?)/;
    var getter = element.attr ? 'attr' : 'getAttribute';
    var setter = element.attr ? 'attr' : 'setAttribute';
    var transform = element[getter]('transform') || '';

    x = x || 0;
    y = y || 0;

    transform = transform.replace(re, '').trim();
    transform += ' translate(' + x + ', ' + y + ')';
    transform = transform.trim();

    element[setter]('transform', transform);

    return transform;
};

drawing.getScale = function(element) {
    var re = /.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/;
    var getter = element.attr ? 'attr' : 'getAttribute';
    var transform = element[getter]('transform') || '';

    var translate = transform.replace(re, function(match, p1, p2) {
        return [p1, p2].join(' ');
    })
    .split(' ');

    return {
        x: +translate[0] || 1,
        y: +translate[1] || 1
    };
};

drawing.setScale = function(element, x, y) {
    var re = /(\bscale\(.*?\);?)/;
    var getter = element.attr ? 'attr' : 'getAttribute';
    var setter = element.attr ? 'attr' : 'setAttribute';
    var transform = element[getter]('transform') || '';

    x = x || 1;
    y = y || 1;

    transform = transform.replace(re, '').trim();
    transform += ' scale(' + x + ', ' + y + ')';
    transform = transform.trim();

    element[setter]('transform', transform);

    return transform;
};

var SCALE_RE = /\s*sc.*/;

drawing.setPointGroupScale = function(selection, xScale, yScale) {
    xScale = xScale || 1;
    yScale = yScale || 1;

    if(!selection) return;

    // The same scale transform for every point:
    var scale = (xScale === 1 && yScale === 1) ?
        '' :
        ' scale(' + xScale + ',' + yScale + ')';

    selection.each(function() {
        var t = (this.getAttribute('transform') || '').replace(SCALE_RE, '');
        t += scale;
        t = t.trim();
        this.setAttribute('transform', t);
    });
};

var TEXT_POINT_LAST_TRANSLATION_RE = /translate\([^)]*\)\s*$/;

drawing.setTextPointsScale = function(selection, xScale, yScale) {
    if(!selection) return;

    selection.each(function() {
        var transforms;
        var el = d3.select(this);
        var text = el.select('text');

        if(!text.node()) return;

        var x = parseFloat(text.attr('x') || 0);
        var y = parseFloat(text.attr('y') || 0);

        var existingTransform = (el.attr('transform') || '').match(TEXT_POINT_LAST_TRANSLATION_RE);

        if(xScale === 1 && yScale === 1) {
            transforms = [];
        } else {
            transforms = [
                'translate(' + x + ',' + y + ')',
                'scale(' + xScale + ',' + yScale + ')',
                'translate(' + (-x) + ',' + (-y) + ')',
            ];
        }

        if(existingTransform) {
            transforms.push(existingTransform);
        }

        el.attr('transform', transforms.join(' '));
    });
};

},{"../../constants/alignment":666,"../../constants/interactions":670,"../../constants/xmlns_namespaces":672,"../../lib":694,"../../lib/svg_text_utils":718,"../../registry":825,"../../traces/scatter/make_bubble_size_func":1064,"../../traces/scatter/subtypes":1071,"../color":571,"../colorscale":583,"./symbol_defs":593,"d3":149,"fast-isnumeric":215,"tinycolor2":515}],593:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

/** Marker symbol definitions
 * users can specify markers either by number or name
 * add 100 (or '-open') and you get an open marker
 *  open markers have no fill and use line color as the stroke color
 * add 200 (or '-dot') and you get a dot in the middle
 * add both and you get both
 */

module.exports = {
    circle: {
        n: 0,
        f: function(r) {
            var rs = d3.round(r, 2);
            return 'M' + rs + ',0A' + rs + ',' + rs + ' 0 1,1 0,-' + rs +
                'A' + rs + ',' + rs + ' 0 0,1 ' + rs + ',0Z';
        }
    },
    square: {
        n: 1,
        f: function(r) {
            var rs = d3.round(r, 2);
            return 'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z';
        }
    },
    diamond: {
        n: 2,
        f: function(r) {
            var rd = d3.round(r * 1.3, 2);
            return 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z';
        }
    },
    cross: {
        n: 3,
        f: function(r) {
            var rc = d3.round(r * 0.4, 2);
            var rc2 = d3.round(r * 1.2, 2);
            return 'M' + rc2 + ',' + rc + 'H' + rc + 'V' + rc2 + 'H-' + rc +
                'V' + rc + 'H-' + rc2 + 'V-' + rc + 'H-' + rc + 'V-' + rc2 +
                'H' + rc + 'V-' + rc + 'H' + rc2 + 'Z';
        }
    },
    x: {
        n: 4,
        f: function(r) {
            var rx = d3.round(r * 0.8 / Math.sqrt(2), 2);
            var ne = 'l' + rx + ',' + rx;
            var se = 'l' + rx + ',-' + rx;
            var sw = 'l-' + rx + ',-' + rx;
            var nw = 'l-' + rx + ',' + rx;
            return 'M0,' + rx + ne + se + sw + se + sw + nw + sw + nw + ne + nw + ne + 'Z';
        }
    },
    'triangle-up': {
        n: 5,
        f: function(r) {
            var rt = d3.round(r * 2 / Math.sqrt(3), 2);
            var r2 = d3.round(r / 2, 2);
            var rs = d3.round(r, 2);
            return 'M-' + rt + ',' + r2 + 'H' + rt + 'L0,-' + rs + 'Z';
        }
    },
    'triangle-down': {
        n: 6,
        f: function(r) {
            var rt = d3.round(r * 2 / Math.sqrt(3), 2);
            var r2 = d3.round(r / 2, 2);
            var rs = d3.round(r, 2);
            return 'M-' + rt + ',-' + r2 + 'H' + rt + 'L0,' + rs + 'Z';
        }
    },
    'triangle-left': {
        n: 7,
        f: function(r) {
            var rt = d3.round(r * 2 / Math.sqrt(3), 2);
            var r2 = d3.round(r / 2, 2);
            var rs = d3.round(r, 2);
            return 'M' + r2 + ',-' + rt + 'V' + rt + 'L-' + rs + ',0Z';
        }
    },
    'triangle-right': {
        n: 8,
        f: function(r) {
            var rt = d3.round(r * 2 / Math.sqrt(3), 2);
            var r2 = d3.round(r / 2, 2);
            var rs = d3.round(r, 2);
            return 'M-' + r2 + ',-' + rt + 'V' + rt + 'L' + rs + ',0Z';
        }
    },
    'triangle-ne': {
        n: 9,
        f: function(r) {
            var r1 = d3.round(r * 0.6, 2);
            var r2 = d3.round(r * 1.2, 2);
            return 'M-' + r2 + ',-' + r1 + 'H' + r1 + 'V' + r2 + 'Z';
        }
    },
    'triangle-se': {
        n: 10,
        f: function(r) {
            var r1 = d3.round(r * 0.6, 2);
            var r2 = d3.round(r * 1.2, 2);
            return 'M' + r1 + ',-' + r2 + 'V' + r1 + 'H-' + r2 + 'Z';
        }
    },
    'triangle-sw': {
        n: 11,
        f: function(r) {
            var r1 = d3.round(r * 0.6, 2);
            var r2 = d3.round(r * 1.2, 2);
            return 'M' + r2 + ',' + r1 + 'H-' + r1 + 'V-' + r2 + 'Z';
        }
    },
    'triangle-nw': {
        n: 12,
        f: function(r) {
            var r1 = d3.round(r * 0.6, 2);
            var r2 = d3.round(r * 1.2, 2);
            return 'M-' + r1 + ',' + r2 + 'V-' + r1 + 'H' + r2 + 'Z';
        }
    },
    pentagon: {
        n: 13,
        f: function(r) {
            var x1 = d3.round(r * 0.951, 2);
            var x2 = d3.round(r * 0.588, 2);
            var y0 = d3.round(-r, 2);
            var y1 = d3.round(r * -0.309, 2);
            var y2 = d3.round(r * 0.809, 2);
            return 'M' + x1 + ',' + y1 + 'L' + x2 + ',' + y2 + 'H-' + x2 +
                'L-' + x1 + ',' + y1 + 'L0,' + y0 + 'Z';
        }
    },
    hexagon: {
        n: 14,
        f: function(r) {
            var y0 = d3.round(r, 2);
            var y1 = d3.round(r / 2, 2);
            var x = d3.round(r * Math.sqrt(3) / 2, 2);
            return 'M' + x + ',-' + y1 + 'V' + y1 + 'L0,' + y0 +
                'L-' + x + ',' + y1 + 'V-' + y1 + 'L0,-' + y0 + 'Z';
        }
    },
    hexagon2: {
        n: 15,
        f: function(r) {
            var x0 = d3.round(r, 2);
            var x1 = d3.round(r / 2, 2);
            var y = d3.round(r * Math.sqrt(3) / 2, 2);
            return 'M-' + x1 + ',' + y + 'H' + x1 + 'L' + x0 +
                ',0L' + x1 + ',-' + y + 'H-' + x1 + 'L-' + x0 + ',0Z';
        }
    },
    octagon: {
        n: 16,
        f: function(r) {
            var a = d3.round(r * 0.924, 2);
            var b = d3.round(r * 0.383, 2);
            return 'M-' + b + ',-' + a + 'H' + b + 'L' + a + ',-' + b + 'V' + b +
                'L' + b + ',' + a + 'H-' + b + 'L-' + a + ',' + b + 'V-' + b + 'Z';
        }
    },
    star: {
        n: 17,
        f: function(r) {
            var rs = r * 1.4;
            var x1 = d3.round(rs * 0.225, 2);
            var x2 = d3.round(rs * 0.951, 2);
            var x3 = d3.round(rs * 0.363, 2);
            var x4 = d3.round(rs * 0.588, 2);
            var y0 = d3.round(-rs, 2);
            var y1 = d3.round(rs * -0.309, 2);
            var y3 = d3.round(rs * 0.118, 2);
            var y4 = d3.round(rs * 0.809, 2);
            var y5 = d3.round(rs * 0.382, 2);
            return 'M' + x1 + ',' + y1 + 'H' + x2 + 'L' + x3 + ',' + y3 +
                'L' + x4 + ',' + y4 + 'L0,' + y5 + 'L-' + x4 + ',' + y4 +
                'L-' + x3 + ',' + y3 + 'L-' + x2 + ',' + y1 + 'H-' + x1 +
                'L0,' + y0 + 'Z';
        }
    },
    hexagram: {
        n: 18,
        f: function(r) {
            var y = d3.round(r * 0.66, 2);
            var x1 = d3.round(r * 0.38, 2);
            var x2 = d3.round(r * 0.76, 2);
            return 'M-' + x2 + ',0l-' + x1 + ',-' + y + 'h' + x2 +
                'l' + x1 + ',-' + y + 'l' + x1 + ',' + y + 'h' + x2 +
                'l-' + x1 + ',' + y + 'l' + x1 + ',' + y + 'h-' + x2 +
                'l-' + x1 + ',' + y + 'l-' + x1 + ',-' + y + 'h-' + x2 + 'Z';
        }
    },
    'star-triangle-up': {
        n: 19,
        f: function(r) {
            var x = d3.round(r * Math.sqrt(3) * 0.8, 2);
            var y1 = d3.round(r * 0.8, 2);
            var y2 = d3.round(r * 1.6, 2);
            var rc = d3.round(r * 4, 2);
            var aPart = 'A ' + rc + ',' + rc + ' 0 0 1 ';
            return 'M-' + x + ',' + y1 + aPart + x + ',' + y1 +
                aPart + '0,-' + y2 + aPart + '-' + x + ',' + y1 + 'Z';
        }
    },
    'star-triangle-down': {
        n: 20,
        f: function(r) {
            var x = d3.round(r * Math.sqrt(3) * 0.8, 2);
            var y1 = d3.round(r * 0.8, 2);
            var y2 = d3.round(r * 1.6, 2);
            var rc = d3.round(r * 4, 2);
            var aPart = 'A ' + rc + ',' + rc + ' 0 0 1 ';
            return 'M' + x + ',-' + y1 + aPart + '-' + x + ',-' + y1 +
                aPart + '0,' + y2 + aPart + x + ',-' + y1 + 'Z';
        }
    },
    'star-square': {
        n: 21,
        f: function(r) {
            var rp = d3.round(r * 1.1, 2);
            var rc = d3.round(r * 2, 2);
            var aPart = 'A ' + rc + ',' + rc + ' 0 0 1 ';
            return 'M-' + rp + ',-' + rp + aPart + '-' + rp + ',' + rp +
                aPart + rp + ',' + rp + aPart + rp + ',-' + rp +
                aPart + '-' + rp + ',-' + rp + 'Z';
        }
    },
    'star-diamond': {
        n: 22,
        f: function(r) {
            var rp = d3.round(r * 1.4, 2);
            var rc = d3.round(r * 1.9, 2);
            var aPart = 'A ' + rc + ',' + rc + ' 0 0 1 ';
            return 'M-' + rp + ',0' + aPart + '0,' + rp +
                aPart + rp + ',0' + aPart + '0,-' + rp +
                aPart + '-' + rp + ',0' + 'Z';
        }
    },
    'diamond-tall': {
        n: 23,
        f: function(r) {
            var x = d3.round(r * 0.7, 2);
            var y = d3.round(r * 1.4, 2);
            return 'M0,' + y + 'L' + x + ',0L0,-' + y + 'L-' + x + ',0Z';
        }
    },
    'diamond-wide': {
        n: 24,
        f: function(r) {
            var x = d3.round(r * 1.4, 2);
            var y = d3.round(r * 0.7, 2);
            return 'M0,' + y + 'L' + x + ',0L0,-' + y + 'L-' + x + ',0Z';
        }
    },
    hourglass: {
        n: 25,
        f: function(r) {
            var rs = d3.round(r, 2);
            return 'M' + rs + ',' + rs + 'H-' + rs + 'L' + rs + ',-' + rs + 'H-' + rs + 'Z';
        },
        noDot: true
    },
    bowtie: {
        n: 26,
        f: function(r) {
            var rs = d3.round(r, 2);
            return 'M' + rs + ',' + rs + 'V-' + rs + 'L-' + rs + ',' + rs + 'V-' + rs + 'Z';
        },
        noDot: true
    },
    'circle-cross': {
        n: 27,
        f: function(r) {
            var rs = d3.round(r, 2);
            return 'M0,' + rs + 'V-' + rs + 'M' + rs + ',0H-' + rs +
                'M' + rs + ',0A' + rs + ',' + rs + ' 0 1,1 0,-' + rs +
                'A' + rs + ',' + rs + ' 0 0,1 ' + rs + ',0Z';
        },
        needLine: true,
        noDot: true
    },
    'circle-x': {
        n: 28,
        f: function(r) {
            var rs = d3.round(r, 2);
            var rc = d3.round(r / Math.sqrt(2), 2);
            return 'M' + rc + ',' + rc + 'L-' + rc + ',-' + rc +
                'M' + rc + ',-' + rc + 'L-' + rc + ',' + rc +
                'M' + rs + ',0A' + rs + ',' + rs + ' 0 1,1 0,-' + rs +
                'A' + rs + ',' + rs + ' 0 0,1 ' + rs + ',0Z';
        },
        needLine: true,
        noDot: true
    },
    'square-cross': {
        n: 29,
        f: function(r) {
            var rs = d3.round(r, 2);
            return 'M0,' + rs + 'V-' + rs + 'M' + rs + ',0H-' + rs +
                'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z';
        },
        needLine: true,
        noDot: true
    },
    'square-x': {
        n: 30,
        f: function(r) {
            var rs = d3.round(r, 2);
            return 'M' + rs + ',' + rs + 'L-' + rs + ',-' + rs +
                'M' + rs + ',-' + rs + 'L-' + rs + ',' + rs +
                'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z';
        },
        needLine: true,
        noDot: true
    },
    'diamond-cross': {
        n: 31,
        f: function(r) {
            var rd = d3.round(r * 1.3, 2);
            return 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z' +
                'M0,-' + rd + 'V' + rd + 'M-' + rd + ',0H' + rd;
        },
        needLine: true,
        noDot: true
    },
    'diamond-x': {
        n: 32,
        f: function(r) {
            var rd = d3.round(r * 1.3, 2);
            var r2 = d3.round(r * 0.65, 2);
            return 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z' +
                'M-' + r2 + ',-' + r2 + 'L' + r2 + ',' + r2 +
                'M-' + r2 + ',' + r2 + 'L' + r2 + ',-' + r2;
        },
        needLine: true,
        noDot: true
    },
    'cross-thin': {
        n: 33,
        f: function(r) {
            var rc = d3.round(r * 1.4, 2);
            return 'M0,' + rc + 'V-' + rc + 'M' + rc + ',0H-' + rc;
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'x-thin': {
        n: 34,
        f: function(r) {
            var rx = d3.round(r, 2);
            return 'M' + rx + ',' + rx + 'L-' + rx + ',-' + rx +
                'M' + rx + ',-' + rx + 'L-' + rx + ',' + rx;
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    asterisk: {
        n: 35,
        f: function(r) {
            var rc = d3.round(r * 1.2, 2);
            var rs = d3.round(r * 0.85, 2);
            return 'M0,' + rc + 'V-' + rc + 'M' + rc + ',0H-' + rc +
                'M' + rs + ',' + rs + 'L-' + rs + ',-' + rs +
                'M' + rs + ',-' + rs + 'L-' + rs + ',' + rs;
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    hash: {
        n: 36,
        f: function(r) {
            var r1 = d3.round(r / 2, 2);
            var r2 = d3.round(r, 2);
            return 'M' + r1 + ',' + r2 + 'V-' + r2 +
                'm-' + r2 + ',0V' + r2 +
                'M' + r2 + ',' + r1 + 'H-' + r2 +
                'm0,-' + r2 + 'H' + r2;
        },
        needLine: true,
        noFill: true
    },
    'y-up': {
        n: 37,
        f: function(r) {
            var x = d3.round(r * 1.2, 2);
            var y0 = d3.round(r * 1.6, 2);
            var y1 = d3.round(r * 0.8, 2);
            return 'M-' + x + ',' + y1 + 'L0,0M' + x + ',' + y1 + 'L0,0M0,-' + y0 + 'L0,0';
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'y-down': {
        n: 38,
        f: function(r) {
            var x = d3.round(r * 1.2, 2);
            var y0 = d3.round(r * 1.6, 2);
            var y1 = d3.round(r * 0.8, 2);
            return 'M-' + x + ',-' + y1 + 'L0,0M' + x + ',-' + y1 + 'L0,0M0,' + y0 + 'L0,0';
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'y-left': {
        n: 39,
        f: function(r) {
            var y = d3.round(r * 1.2, 2);
            var x0 = d3.round(r * 1.6, 2);
            var x1 = d3.round(r * 0.8, 2);
            return 'M' + x1 + ',' + y + 'L0,0M' + x1 + ',-' + y + 'L0,0M-' + x0 + ',0L0,0';
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'y-right': {
        n: 40,
        f: function(r) {
            var y = d3.round(r * 1.2, 2);
            var x0 = d3.round(r * 1.6, 2);
            var x1 = d3.round(r * 0.8, 2);
            return 'M-' + x1 + ',' + y + 'L0,0M-' + x1 + ',-' + y + 'L0,0M' + x0 + ',0L0,0';
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'line-ew': {
        n: 41,
        f: function(r) {
            var rc = d3.round(r * 1.4, 2);
            return 'M' + rc + ',0H-' + rc;
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'line-ns': {
        n: 42,
        f: function(r) {
            var rc = d3.round(r * 1.4, 2);
            return 'M0,' + rc + 'V-' + rc;
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'line-ne': {
        n: 43,
        f: function(r) {
            var rx = d3.round(r, 2);
            return 'M' + rx + ',-' + rx + 'L-' + rx + ',' + rx;
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'line-nw': {
        n: 44,
        f: function(r) {
            var rx = d3.round(r, 2);
            return 'M' + rx + ',' + rx + 'L-' + rx + ',-' + rx;
        },
        needLine: true,
        noDot: true,
        noFill: true
    }
};

},{"d3":149}],594:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    visible: {
        valType: 'boolean',
        
        editType: 'calc',
        
    },
    type: {
        valType: 'enumerated',
        values: ['percent', 'constant', 'sqrt', 'data'],
        
        editType: 'calc',
        
    },
    symmetric: {
        valType: 'boolean',
        
        editType: 'calc',
        
    },
    array: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    arrayminus: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    value: {
        valType: 'number',
        min: 0,
        dflt: 10,
        
        editType: 'calc',
        
    },
    valueminus: {
        valType: 'number',
        min: 0,
        dflt: 10,
        
        editType: 'calc',
        
    },
    traceref: {
        valType: 'integer',
        min: 0,
        dflt: 0,
        
        editType: 'style'
    },
    tracerefminus: {
        valType: 'integer',
        min: 0,
        dflt: 0,
        
        editType: 'style'
    },
    copy_ystyle: {
        valType: 'boolean',
        
        editType: 'plot'
    },
    copy_zstyle: {
        valType: 'boolean',
        
        editType: 'style'
    },
    color: {
        valType: 'color',
        
        editType: 'style',
        
    },
    thickness: {
        valType: 'number',
        min: 0,
        dflt: 2,
        
        editType: 'style',
        
    },
    width: {
        valType: 'number',
        min: 0,
        
        editType: 'plot',
        
    },
    editType: 'calc',

    _deprecated: {
        opacity: {
            valType: 'number',
            
            editType: 'style',
            
        }
    }
};

},{}],595:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var Registry = _dereq_('../../registry');
var Axes = _dereq_('../../plots/cartesian/axes');
var Lib = _dereq_('../../lib');

var makeComputeError = _dereq_('./compute_error');

module.exports = function calc(gd) {
    var calcdata = gd.calcdata;

    for(var i = 0; i < calcdata.length; i++) {
        var calcTrace = calcdata[i];
        var trace = calcTrace[0].trace;

        if(trace.visible === true && Registry.traceIs(trace, 'errorBarsOK')) {
            var xa = Axes.getFromId(gd, trace.xaxis);
            var ya = Axes.getFromId(gd, trace.yaxis);
            calcOneAxis(calcTrace, trace, xa, 'x');
            calcOneAxis(calcTrace, trace, ya, 'y');
        }
    }
};

function calcOneAxis(calcTrace, trace, axis, coord) {
    var opts = trace['error_' + coord] || {};
    var isVisible = (opts.visible && ['linear', 'log'].indexOf(axis.type) !== -1);
    var vals = [];

    if(!isVisible) return;

    var computeError = makeComputeError(opts);

    for(var i = 0; i < calcTrace.length; i++) {
        var calcPt = calcTrace[i];

        var iIn = calcPt.i;

        // for types that don't include `i` in each calcdata point
        if(iIn === undefined) iIn = i;

        // for stacked area inserted points
        // TODO: errorbars have been tested cursorily with stacked area,
        // but not thoroughly. It's not even really clear what you want to do:
        // Should it just be calculated based on that trace's size data?
        // Should you add errors from below in quadrature?
        // And what about normalization, where in principle the errors shrink
        // again when you get up to the top end?
        // One option would be to forbid errorbars with stacking until we
        // decide how to handle these questions.
        else if(iIn === null) continue;

        var calcCoord = calcPt[coord];

        if(!isNumeric(axis.c2l(calcCoord))) continue;

        var errors = computeError(calcCoord, iIn);
        if(isNumeric(errors[0]) && isNumeric(errors[1])) {
            var shoe = calcPt[coord + 's'] = calcCoord - errors[0];
            var hat = calcPt[coord + 'h'] = calcCoord + errors[1];
            vals.push(shoe, hat);
        }
    }

    var axId = axis._id;
    var baseExtremes = trace._extremes[axId];
    var extremes = Axes.findExtremes(
        axis,
        vals,
        Lib.extendFlat({tozero: baseExtremes.opts.tozero}, {padded: true})
    );
    baseExtremes.min = baseExtremes.min.concat(extremes.min);
    baseExtremes.max = baseExtremes.max.concat(extremes.max);
}

},{"../../lib":694,"../../plots/cartesian/axes":742,"../../registry":825,"./compute_error":596,"fast-isnumeric":215}],596:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


/**
 * Error bar computing function generator
 *
 * N.B. The generated function does not clean the dataPt entries. Non-numeric
 * entries result in undefined error magnitudes.
 *
 * @param {object} opts error bar attributes
 *
 * @return {function} :
 *      @param {numeric} dataPt data point from where to compute the error magnitude
 *      @param {number} index index of dataPt in its corresponding data array
 *      @return {array}
 *        - error[0] : error magnitude in the negative direction
 *        - error[1] : " " " " positive "
 */
module.exports = function makeComputeError(opts) {
    var type = opts.type;
    var symmetric = opts.symmetric;

    if(type === 'data') {
        var array = opts.array || [];

        if(symmetric) {
            return function computeError(dataPt, index) {
                var val = +(array[index]);
                return [val, val];
            };
        }
        else {
            var arrayminus = opts.arrayminus || [];
            return function computeError(dataPt, index) {
                var val = +array[index];
                var valMinus = +arrayminus[index];
                // in case one is present and the other is missing, fill in 0
                // so we still see the present one. Mostly useful during manual
                // data entry.
                if(!isNaN(val) || !isNaN(valMinus)) {
                    return [valMinus || 0, val || 0];
                }
                return [NaN, NaN];
            };
        }
    }
    else {
        var computeErrorValue = makeComputeErrorValue(type, opts.value);
        var computeErrorValueMinus = makeComputeErrorValue(type, opts.valueminus);

        if(symmetric || opts.valueminus === undefined) {
            return function computeError(dataPt) {
                var val = computeErrorValue(dataPt);
                return [val, val];
            };
        }
        else {
            return function computeError(dataPt) {
                return [
                    computeErrorValueMinus(dataPt),
                    computeErrorValue(dataPt)
                ];
            };
        }
    }
};

/**
 * Compute error bar magnitude (for all types except data)
 *
 * @param {string} type error bar type
 * @param {numeric} value error bar value
 *
 * @return {function} :
 *      @param {numeric} dataPt
 */
function makeComputeErrorValue(type, value) {
    if(type === 'percent') {
        return function(dataPt) {
            return Math.abs(dataPt * value / 100);
        };
    }
    if(type === 'constant') {
        return function() {
            return Math.abs(value);
        };
    }
    if(type === 'sqrt') {
        return function(dataPt) {
            return Math.sqrt(Math.abs(dataPt));
        };
    }
}

},{}],597:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Template = _dereq_('../../plot_api/plot_template');

var attributes = _dereq_('./attributes');


module.exports = function(traceIn, traceOut, defaultColor, opts) {
    var objName = 'error_' + opts.axis;
    var containerOut = Template.newContainer(traceOut, objName);
    var containerIn = traceIn[objName] || {};

    function coerce(attr, dflt) {
        return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
    }

    var hasErrorBars = (
        containerIn.array !== undefined ||
        containerIn.value !== undefined ||
        containerIn.type === 'sqrt'
    );

    var visible = coerce('visible', hasErrorBars);

    if(visible === false) return;

    var type = coerce('type', 'array' in containerIn ? 'data' : 'percent');
    var symmetric = true;

    if(type !== 'sqrt') {
        symmetric = coerce('symmetric',
            !((type === 'data' ? 'arrayminus' : 'valueminus') in containerIn));
    }

    if(type === 'data') {
        coerce('array');
        coerce('traceref');
        if(!symmetric) {
            coerce('arrayminus');
            coerce('tracerefminus');
        }
    }
    else if(type === 'percent' || type === 'constant') {
        coerce('value');
        if(!symmetric) coerce('valueminus');
    }

    var copyAttr = 'copy_' + opts.inherit + 'style';
    if(opts.inherit) {
        var inheritObj = traceOut['error_' + opts.inherit];
        if((inheritObj || {}).visible) {
            coerce(copyAttr, !(containerIn.color ||
                               isNumeric(containerIn.thickness) ||
                               isNumeric(containerIn.width)));
        }
    }
    if(!opts.inherit || !containerOut[copyAttr]) {
        coerce('color', defaultColor);
        coerce('thickness');
        coerce('width', Registry.traceIs(traceOut, 'gl3d') ? 0 : 4);
    }
};

},{"../../lib":694,"../../plot_api/plot_template":732,"../../registry":825,"./attributes":594,"fast-isnumeric":215}],598:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;

var attributes = _dereq_('./attributes');

var xyAttrs = {
    error_x: Lib.extendFlat({}, attributes),
    error_y: Lib.extendFlat({}, attributes)
};
delete xyAttrs.error_x.copy_zstyle;
delete xyAttrs.error_y.copy_zstyle;
delete xyAttrs.error_y.copy_ystyle;

var xyzAttrs = {
    error_x: Lib.extendFlat({}, attributes),
    error_y: Lib.extendFlat({}, attributes),
    error_z: Lib.extendFlat({}, attributes)
};
delete xyzAttrs.error_x.copy_ystyle;
delete xyzAttrs.error_y.copy_ystyle;
delete xyzAttrs.error_z.copy_ystyle;
delete xyzAttrs.error_z.copy_zstyle;

module.exports = {
    moduleType: 'component',
    name: 'errorbars',

    schema: {
        traces: {
            scatter: xyAttrs,
            bar: xyAttrs,
            histogram: xyAttrs,
            scatter3d: overrideAll(xyzAttrs, 'calc', 'nested'),
            scattergl: overrideAll(xyAttrs, 'calc', 'nested')
        }
    },

    supplyDefaults: _dereq_('./defaults'),

    calc: _dereq_('./calc'),
    makeComputeError: _dereq_('./compute_error'),

    plot: _dereq_('./plot'),
    style: _dereq_('./style'),
    hoverInfo: hoverInfo
};

function hoverInfo(calcPoint, trace, hoverPoint) {
    if((trace.error_y || {}).visible) {
        hoverPoint.yerr = calcPoint.yh - calcPoint.y;
        if(!trace.error_y.symmetric) hoverPoint.yerrneg = calcPoint.y - calcPoint.ys;
    }
    if((trace.error_x || {}).visible) {
        hoverPoint.xerr = calcPoint.xh - calcPoint.x;
        if(!trace.error_x.symmetric) hoverPoint.xerrneg = calcPoint.x - calcPoint.xs;
    }
}

},{"../../lib":694,"../../plot_api/edit_types":725,"./attributes":594,"./calc":595,"./compute_error":596,"./defaults":597,"./plot":599,"./style":600}],599:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');

var Drawing = _dereq_('../drawing');
var subTypes = _dereq_('../../traces/scatter/subtypes');

module.exports = function plot(gd, traces, plotinfo, transitionOpts) {
    var isNew;

    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    var hasAnimation = transitionOpts && transitionOpts.duration > 0;

    traces.each(function(d) {
        var trace = d[0].trace;
        // || {} is in case the trace (specifically scatterternary)
        // doesn't support error bars at all, but does go through
        // the scatter.plot mechanics, which calls ErrorBars.plot
        // internally
        var xObj = trace.error_x || {};
        var yObj = trace.error_y || {};

        var keyFunc;

        if(trace.ids) {
            keyFunc = function(d) {return d.id;};
        }

        var sparse = (
            subTypes.hasMarkers(trace) &&
            trace.marker.maxdisplayed > 0
        );

        if(!yObj.visible && !xObj.visible) d = [];

        var errorbars = d3.select(this).selectAll('g.errorbar')
            .data(d, keyFunc);

        errorbars.exit().remove();

        if(!d.length) return;

        if(!xObj.visible) errorbars.selectAll('path.xerror').remove();
        if(!yObj.visible) errorbars.selectAll('path.yerror').remove();

        errorbars.style('opacity', 1);

        var enter = errorbars.enter().append('g')
            .classed('errorbar', true);

        if(hasAnimation) {
            enter.style('opacity', 0).transition()
                .duration(transitionOpts.duration)
                .style('opacity', 1);
        }

        Drawing.setClipUrl(errorbars, plotinfo.layerClipId, gd);

        errorbars.each(function(d) {
            var errorbar = d3.select(this);
            var coords = errorCoords(d, xa, ya);

            if(sparse && !d.vis) return;

            var path;

            var yerror = errorbar.select('path.yerror');
            if(yObj.visible && isNumeric(coords.x) &&
                    isNumeric(coords.yh) &&
                    isNumeric(coords.ys)) {
                var yw = yObj.width;

                path = 'M' + (coords.x - yw) + ',' +
                    coords.yh + 'h' + (2 * yw) + // hat
                    'm-' + yw + ',0V' + coords.ys; // bar


                if(!coords.noYS) path += 'm-' + yw + ',0h' + (2 * yw); // shoe

                isNew = !yerror.size();

                if(isNew) {
                    yerror = errorbar.append('path')
                        .style('vector-effect', 'non-scaling-stroke')
                        .classed('yerror', true);
                } else if(hasAnimation) {
                    yerror = yerror
                        .transition()
                            .duration(transitionOpts.duration)
                            .ease(transitionOpts.easing);
                }

                yerror.attr('d', path);
            }
            else yerror.remove();

            var xerror = errorbar.select('path.xerror');
            if(xObj.visible && isNumeric(coords.y) &&
                    isNumeric(coords.xh) &&
                    isNumeric(coords.xs)) {
                var xw = (xObj.copy_ystyle ? yObj : xObj).width;

                path = 'M' + coords.xh + ',' +
                    (coords.y - xw) + 'v' + (2 * xw) + // hat
                    'm0,-' + xw + 'H' + coords.xs; // bar

                if(!coords.noXS) path += 'm0,-' + xw + 'v' + (2 * xw); // shoe

                isNew = !xerror.size();

                if(isNew) {
                    xerror = errorbar.append('path')
                        .style('vector-effect', 'non-scaling-stroke')
                        .classed('xerror', true);
                } else if(hasAnimation) {
                    xerror = xerror
                        .transition()
                            .duration(transitionOpts.duration)
                            .ease(transitionOpts.easing);
                }

                xerror.attr('d', path);
            }
            else xerror.remove();
        });
    });
};

// compute the coordinates of the error-bar objects
function errorCoords(d, xa, ya) {
    var out = {
        x: xa.c2p(d.x),
        y: ya.c2p(d.y)
    };

    // calculate the error bar size and hat and shoe locations
    if(d.yh !== undefined) {
        out.yh = ya.c2p(d.yh);
        out.ys = ya.c2p(d.ys);

        // if the shoes go off-scale (ie log scale, error bars past zero)
        // clip the bar and hide the shoes
        if(!isNumeric(out.ys)) {
            out.noYS = true;
            out.ys = ya.c2p(d.ys, true);
        }
    }

    if(d.xh !== undefined) {
        out.xh = xa.c2p(d.xh);
        out.xs = xa.c2p(d.xs);

        if(!isNumeric(out.xs)) {
            out.noXS = true;
            out.xs = xa.c2p(d.xs, true);
        }
    }

    return out;
}

},{"../../traces/scatter/subtypes":1071,"../drawing":592,"d3":149,"fast-isnumeric":215}],600:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

var Color = _dereq_('../color');


module.exports = function style(traces) {
    traces.each(function(d) {
        var trace = d[0].trace;
        var yObj = trace.error_y || {};
        var xObj = trace.error_x || {};

        var s = d3.select(this);

        s.selectAll('path.yerror')
            .style('stroke-width', yObj.thickness + 'px')
            .call(Color.stroke, yObj.color);

        if(xObj.copy_ystyle) xObj = yObj;

        s.selectAll('path.xerror')
            .style('stroke-width', xObj.thickness + 'px')
            .call(Color.stroke, xObj.color);
    });
};

},{"../color":571,"d3":149}],601:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = _dereq_('../../plots/font_attributes');

module.exports = {
    hoverlabel: {
        bgcolor: {
            valType: 'color',
            
            arrayOk: true,
            editType: 'none',
            
        },
        bordercolor: {
            valType: 'color',
            
            arrayOk: true,
            editType: 'none',
            
        },
        font: fontAttrs({
            arrayOk: true,
            editType: 'none',
            
        }),
        namelength: {
            valType: 'integer',
            min: -1,
            arrayOk: true,
            
            editType: 'none',
            
        },
        editType: 'calc'
    }
};

},{"../../plots/font_attributes":769}],602:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Registry = _dereq_('../../registry');

module.exports = function calc(gd) {
    var calcdata = gd.calcdata;
    var fullLayout = gd._fullLayout;

    function makeCoerceHoverInfo(trace) {
        return function(val) {
            return Lib.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout);
        };
    }

    for(var i = 0; i < calcdata.length; i++) {
        var cd = calcdata[i];
        var trace = cd[0].trace;

        // don't include hover calc fields for pie traces
        // as calcdata items might be sorted by value and
        // won't match the data array order.
        if(Registry.traceIs(trace, 'pie')) continue;

        var fillFn = Registry.traceIs(trace, '2dMap') ? paste : Lib.fillArray;

        fillFn(trace.hoverinfo, cd, 'hi', makeCoerceHoverInfo(trace));

        if(trace.hovertemplate) fillFn(trace.hovertemplate, cd, 'ht');

        if(!trace.hoverlabel) continue;

        fillFn(trace.hoverlabel.bgcolor, cd, 'hbg');
        fillFn(trace.hoverlabel.bordercolor, cd, 'hbc');
        fillFn(trace.hoverlabel.font.size, cd, 'hts');
        fillFn(trace.hoverlabel.font.color, cd, 'htc');
        fillFn(trace.hoverlabel.font.family, cd, 'htf');
        fillFn(trace.hoverlabel.namelength, cd, 'hnl');
    }
};

function paste(traceAttr, cd, cdAttr, fn) {
    fn = fn || Lib.identity;

    if(Array.isArray(traceAttr)) {
        cd[0][cdAttr] = fn(traceAttr);
    }
}

},{"../../lib":694,"../../registry":825}],603:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');
var hover = _dereq_('./hover').hover;

module.exports = function click(gd, evt, subplot) {
    var annotationsDone = Registry.getComponentMethod('annotations', 'onClick')(gd, gd._hoverdata);

    // fallback to fail-safe in case the plot type's hover method doesn't pass the subplot.
    // Ternary, for example, didn't, but it was caught because tested.
    if(subplot !== undefined) {
        // The true flag at the end causes it to re-run the hover computation to figure out *which*
        // point is being clicked. Without this, clicking is somewhat unreliable.
        hover(gd, evt, subplot, true);
    }

    function emitClick() { gd.emit('plotly_click', {points: gd._hoverdata, event: evt}); }

    if(gd._hoverdata && evt && evt.target) {
        if(annotationsDone && annotationsDone.then) {
            annotationsDone.then(emitClick);
        }
        else emitClick();

        // why do we get a double event without this???
        if(evt.stopImmediatePropagation) evt.stopImmediatePropagation();
    }
};

},{"../../registry":825,"./hover":607}],604:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    // hover labels for multiple horizontal bars get tilted by this angle
    YANGLE: 60,

    // size and display constants for hover text

    // pixel size of hover arrows
    HOVERARROWSIZE: 6,
    // pixels padding around text
    HOVERTEXTPAD: 3,
    // hover font
    HOVERFONTSIZE: 13,
    HOVERFONT: 'Arial, sans-serif',

    // minimum time (msec) between hover calls
    HOVERMINTIME: 50,

    // ID suffix (with fullLayout._uid) for hover events in the throttle cache
    HOVERID: '-hover'
};

},{}],605:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var attributes = _dereq_('./attributes');
var handleHoverLabelDefaults = _dereq_('./hoverlabel_defaults');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    handleHoverLabelDefaults(traceIn, traceOut, coerce, layout.hoverlabel);
};

},{"../../lib":694,"./attributes":601,"./hoverlabel_defaults":608}],606:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

// look for either subplot or xaxis and yaxis attributes
// does not handle splom case
exports.getSubplot = function getSubplot(trace) {
    return trace.subplot || (trace.xaxis + trace.yaxis) || trace.geo;
};

// is trace in given list of subplots?
// does handle splom case
exports.isTraceInSubplots = function isTraceInSubplot(trace, subplots) {
    if(trace.type === 'splom') {
        var xaxes = trace.xaxes || [];
        var yaxes = trace.yaxes || [];
        for(var i = 0; i < xaxes.length; i++) {
            for(var j = 0; j < yaxes.length; j++) {
                if(subplots.indexOf(xaxes[i] + yaxes[j]) !== -1) {
                    return true;
                }
            }
        }
        return false;
    }

    return subplots.indexOf(exports.getSubplot(trace)) !== -1;
};

// convenience functions for mapping all relevant axes
exports.flat = function flat(subplots, v) {
    var out = new Array(subplots.length);
    for(var i = 0; i < subplots.length; i++) {
        out[i] = v;
    }
    return out;
};

exports.p2c = function p2c(axArray, v) {
    var out = new Array(axArray.length);
    for(var i = 0; i < axArray.length; i++) {
        out[i] = axArray[i].p2c(v);
    }
    return out;
};

exports.getDistanceFunction = function getDistanceFunction(mode, dx, dy, dxy) {
    if(mode === 'closest') return dxy || exports.quadrature(dx, dy);
    return mode === 'x' ? dx : dy;
};

exports.getClosest = function getClosest(cd, distfn, pointData) {
    // do we already have a point number? (array mode only)
    if(pointData.index !== false) {
        if(pointData.index >= 0 && pointData.index < cd.length) {
            pointData.distance = 0;
        }
        else pointData.index = false;
    }
    else {
        // apply the distance function to each data point
        // this is the longest loop... if this bogs down, we may need
        // to create pre-sorted data (by x or y), not sure how to
        // do this for 'closest'
        for(var i = 0; i < cd.length; i++) {
            var newDistance = distfn(cd[i]);
            if(newDistance <= pointData.distance) {
                pointData.index = i;
                pointData.distance = newDistance;
            }
        }
    }
    return pointData;
};

/*
 * pseudo-distance function for hover effects on areas: inside the region
 * distance is finite (`passVal`), outside it's Infinity.
 *
 * @param {number} v0: signed difference between the current position and the left edge
 * @param {number} v1: signed difference between the current position and the right edge
 * @param {number} passVal: the value to return on success
 */
exports.inbox = function inbox(v0, v1, passVal) {
    return (v0 * v1 < 0 || v0 === 0) ? passVal : Infinity;
};

exports.quadrature = function quadrature(dx, dy) {
    return function(di) {
        var x = dx(di);
        var y = dy(di);
        return Math.sqrt(x * x + y * y);
    };
};

/** Fill event data point object for hover and selection.
 *  Invokes _module.eventData if present.
 *
 * N.B. note that point 'index' corresponds to input data array index
 *  whereas 'number' is its post-transform version.
 *
 * If the hovered/selected pt corresponds to an multiple input points
 * (e.g. for histogram and transformed traces), 'pointNumbers` and 'pointIndices'
 * are include in the event data.
 *
 * @param {object} pt
 * @param {object} trace
 * @param {object} cd
 * @return {object}
 */
exports.makeEventData = function makeEventData(pt, trace, cd) {
    // hover uses 'index', select uses 'pointNumber'
    var pointNumber = 'index' in pt ? pt.index : pt.pointNumber;

    var out = {
        data: trace._input,
        fullData: trace,
        curveNumber: trace.index,
        pointNumber: pointNumber
    };

    if(trace._indexToPoints) {
        var pointIndices = trace._indexToPoints[pointNumber];

        if(pointIndices.length === 1) {
            out.pointIndex = pointIndices[0];
        } else {
            out.pointIndices = pointIndices;
        }
    } else {
        out.pointIndex = pointNumber;
    }

    if(trace._module.eventData) {
        out = trace._module.eventData(out, pt, trace, cd, pointNumber);
    } else {
        if('xVal' in pt) out.x = pt.xVal;
        else if('x' in pt) out.x = pt.x;

        if('yVal' in pt) out.y = pt.yVal;
        else if('y' in pt) out.y = pt.y;

        if(pt.xa) out.xaxis = pt.xa;
        if(pt.ya) out.yaxis = pt.ya;
        if(pt.zLabelVal !== undefined) out.z = pt.zLabelVal;
    }

    exports.appendArrayPointValue(out, trace, pointNumber);

    return out;
};

/** Appends values inside array attributes corresponding to given point number
 *
 * @param {object} pointData : point data object (gets mutated here)
 * @param {object} trace : full trace object
 * @param {number|Array(number)} pointNumber : point number. May be a length-2 array
 *     [row, col] to dig into 2D arrays
 */
exports.appendArrayPointValue = function(pointData, trace, pointNumber) {
    var arrayAttrs = trace._arrayAttrs;

    if(!arrayAttrs) {
        return;
    }

    for(var i = 0; i < arrayAttrs.length; i++) {
        var astr = arrayAttrs[i];
        var key = getPointKey(astr);

        if(pointData[key] === undefined) {
            var val = Lib.nestedProperty(trace, astr).get();
            var pointVal = getPointData(val, pointNumber);

            if(pointVal !== undefined) pointData[key] = pointVal;
        }
    }
};

/**
 * Appends values inside array attributes corresponding to given point number array
 * For use when pointData references a plot entity that arose (or potentially arose)
 * from multiple points in the input data
 *
 * @param {object} pointData : point data object (gets mutated here)
 * @param {object} trace : full trace object
 * @param {Array(number)|Array(Array(number))} pointNumbers : Array of point numbers.
 *     Each entry in the array may itself be a length-2 array [row, col] to dig into 2D arrays
 */
exports.appendArrayMultiPointValues = function(pointData, trace, pointNumbers) {
    var arrayAttrs = trace._arrayAttrs;

    if(!arrayAttrs) {
        return;
    }

    for(var i = 0; i < arrayAttrs.length; i++) {
        var astr = arrayAttrs[i];
        var key = getPointKey(astr);

        if(pointData[key] === undefined) {
            var val = Lib.nestedProperty(trace, astr).get();
            var keyVal = new Array(pointNumbers.length);

            for(var j = 0; j < pointNumbers.length; j++) {
                keyVal[j] = getPointData(val, pointNumbers[j]);
            }
            pointData[key] = keyVal;
        }
    }
};

var pointKeyMap = {
    ids: 'id',
    locations: 'location',
    labels: 'label',
    values: 'value',
    'marker.colors': 'color'
};

function getPointKey(astr) {
    return pointKeyMap[astr] || astr;
}

function getPointData(val, pointNumber) {
    if(Array.isArray(pointNumber)) {
        if(Array.isArray(val) && Array.isArray(val[pointNumber[0]])) {
            return val[pointNumber[0]][pointNumber[1]];
        }
    } else {
        return val[pointNumber];
    }
}

},{"../../lib":694}],607:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');
var tinycolor = _dereq_('tinycolor2');

var Lib = _dereq_('../../lib');
var Events = _dereq_('../../lib/events');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var overrideCursor = _dereq_('../../lib/override_cursor');
var Drawing = _dereq_('../drawing');
var Color = _dereq_('../color');
var dragElement = _dereq_('../dragelement');
var Axes = _dereq_('../../plots/cartesian/axes');
var Registry = _dereq_('../../registry');

var helpers = _dereq_('./helpers');
var constants = _dereq_('./constants');

// hover labels for multiple horizontal bars get tilted by some angle,
// then need to be offset differently if they overlap
var YANGLE = constants.YANGLE;
var YA_RADIANS = Math.PI * YANGLE / 180;

// expansion of projected height
var YFACTOR = 1 / Math.sin(YA_RADIANS);

// to make the appropriate post-rotation x offset,
// you need both x and y offsets
var YSHIFTX = Math.cos(YA_RADIANS);
var YSHIFTY = Math.sin(YA_RADIANS);

// size and display constants for hover text
var HOVERARROWSIZE = constants.HOVERARROWSIZE;
var HOVERTEXTPAD = constants.HOVERTEXTPAD;

// fx.hover: highlight data on hover
// evt can be a mousemove event, or an object with data about what points
//   to hover on
//      {xpx,ypx[,hovermode]} - pixel locations from top left
//          (with optional overriding hovermode)
//      {xval,yval[,hovermode]} - data values
//      [{curveNumber,(pointNumber|xval and/or yval)}] -
//              array of specific points to highlight
//          pointNumber is a single integer if gd.data[curveNumber] is 1D,
//              or a two-element array if it's 2D
//          xval and yval are data values,
//              1D data may specify either or both,
//              2D data must specify both
// subplot is an id string (default "xy")
// makes use of gl.hovermode, which can be:
//      x (find the points with the closest x values, ie a column),
//      closest (find the single closest point)
//    internally there are two more that occasionally get used:
//      y (pick out a row - only used for multiple horizontal bar charts)
//      array (used when the user specifies an explicit
//          array of points to hover on)
//
// We wrap the hovers in a timer, to limit their frequency.
// The actual rendering is done by private function _hover.
exports.hover = function hover(gd, evt, subplot, noHoverEvent) {
    gd = Lib.getGraphDiv(gd);

    Lib.throttle(
        gd._fullLayout._uid + constants.HOVERID,
        constants.HOVERMINTIME,
        function() { _hover(gd, evt, subplot, noHoverEvent); }
    );
};

/*
 * Draw a single hover item in a pre-existing svg container somewhere
 * hoverItem should have keys:
 *    - x and y (or x0, x1, y0, and y1):
 *      the pixel position to mark, relative to opts.container
 *    - xLabel, yLabel, zLabel, text, and name:
 *      info to go in the label
 *    - color:
 *      the background color for the label.
 *    - idealAlign (optional):
 *      'left' or 'right' for which side of the x/y box to try to put this on first
 *    - borderColor (optional):
 *      color for the border, defaults to strongest contrast with color
 *    - fontFamily (optional):
 *      string, the font for this label, defaults to constants.HOVERFONT
 *    - fontSize (optional):
 *      the label font size, defaults to constants.HOVERFONTSIZE
 *    - fontColor (optional):
 *      defaults to borderColor
 * opts should have keys:
 *    - bgColor:
 *      the background color this is against, used if the trace is
 *      non-opaque, and for the name, which goes outside the box
 *    - container:
 *      a <svg> or <g> element to add the hover label to
 *    - outerContainer:
 *      normally a parent of `container`, sets the bounding box to use to
 *      constrain the hover label and determine whether to show it on the left or right
 */
exports.loneHover = function loneHover(hoverItem, opts) {
    var pointData = {
        color: hoverItem.color || Color.defaultLine,
        x0: hoverItem.x0 || hoverItem.x || 0,
        x1: hoverItem.x1 || hoverItem.x || 0,
        y0: hoverItem.y0 || hoverItem.y || 0,
        y1: hoverItem.y1 || hoverItem.y || 0,
        xLabel: hoverItem.xLabel,
        yLabel: hoverItem.yLabel,
        zLabel: hoverItem.zLabel,
        text: hoverItem.text,
        name: hoverItem.name,
        idealAlign: hoverItem.idealAlign,

        // optional extra bits of styling
        borderColor: hoverItem.borderColor,
        fontFamily: hoverItem.fontFamily,
        fontSize: hoverItem.fontSize,
        fontColor: hoverItem.fontColor,

        // filler to make createHoverText happy
        trace: hoverItem.trace || {
            index: 0,
            hoverinfo: ''
        },
        xa: {_offset: 0},
        ya: {_offset: 0},
        index: 0,

        hovertemplate: hoverItem.hovertemplate || false,
        eventData: hoverItem.eventData || false,
        hovertemplateLabels: hoverItem.hovertemplateLabels || false,
    };

    var container3 = d3.select(opts.container);
    var outerContainer3 = opts.outerContainer ?
        d3.select(opts.outerContainer) : container3;

    var fullOpts = {
        hovermode: 'closest',
        rotateLabels: false,
        bgColor: opts.bgColor || Color.background,
        container: container3,
        outerContainer: outerContainer3
    };
    var hoverLabel = createHoverText([pointData], fullOpts, opts.gd);
    alignHoverText(hoverLabel, fullOpts.rotateLabels);

    return hoverLabel.node();
};

exports.multiHovers = function multiHovers(hoverItems, opts) {

    if(!Array.isArray(hoverItems)) {
        hoverItems = [hoverItems];
    }

    var pointsData = hoverItems.map(function(hoverItem) {
        return {
            color: hoverItem.color || Color.defaultLine,
            x0: hoverItem.x0 || hoverItem.x || 0,
            x1: hoverItem.x1 || hoverItem.x || 0,
            y0: hoverItem.y0 || hoverItem.y || 0,
            y1: hoverItem.y1 || hoverItem.y || 0,
            xLabel: hoverItem.xLabel,
            yLabel: hoverItem.yLabel,
            zLabel: hoverItem.zLabel,
            text: hoverItem.text,
            name: hoverItem.name,
            idealAlign: hoverItem.idealAlign,

            // optional extra bits of styling
            borderColor: hoverItem.borderColor,
            fontFamily: hoverItem.fontFamily,
            fontSize: hoverItem.fontSize,
            fontColor: hoverItem.fontColor,

            // filler to make createHoverText happy
            trace: hoverItem.trace || {
                index: 0,
                hoverinfo: ''
            },
            xa: {_offset: 0},
            ya: {_offset: 0},
            index: 0,

            hovertemplate: hoverItem.hovertemplate || false,
            eventData: hoverItem.eventData || false,
            hovertemplateLabels: hoverItem.hovertemplateLabels || false,
        };
    });


    var container3 = d3.select(opts.container);
    var outerContainer3 = opts.outerContainer ? d3.select(opts.outerContainer) : container3;

    var fullOpts = {
        hovermode: 'closest',
        rotateLabels: false,
        bgColor: opts.bgColor || Color.background,
        container: container3,
        outerContainer: outerContainer3
    };

    var hoverLabel = createHoverText(pointsData, fullOpts, opts.gd);

    // Fix vertical overlap
    var tooltipSpacing = 5;
    var lastBottomY = 0;
    hoverLabel
        .sort(function(a, b) {return a.y0 - b.y0;})
        .each(function(d) {
            var topY = d.y0 - d.by / 2;

            if((topY - tooltipSpacing) < lastBottomY) {
                d.offset = (lastBottomY - topY) + tooltipSpacing;
            } else {
                d.offset = 0;
            }

            lastBottomY = topY + d.by + d.offset;
        });


    alignHoverText(hoverLabel, fullOpts.rotateLabels);

    return hoverLabel.node();
};

// The actual implementation is here:
function _hover(gd, evt, subplot, noHoverEvent) {
    if(!subplot) subplot = 'xy';

    // if the user passed in an array of subplots,
    // use those instead of finding overlayed plots
    var subplots = Array.isArray(subplot) ? subplot : [subplot];

    var fullLayout = gd._fullLayout;
    var plots = fullLayout._plots || [];
    var plotinfo = plots[subplot];
    var hasCartesian = fullLayout._has('cartesian');

    // list of all overlaid subplots to look at
    if(plotinfo) {
        var overlayedSubplots = plotinfo.overlays.map(function(pi) {
            return pi.id;
        });

        subplots = subplots.concat(overlayedSubplots);
    }

    var len = subplots.length;
    var xaArray = new Array(len);
    var yaArray = new Array(len);
    var supportsCompare = false;

    for(var i = 0; i < len; i++) {
        var spId = subplots[i];

        // 'cartesian' case
        var plotObj = plots[spId];
        if(plotObj) {
            supportsCompare = true;

            // TODO make sure that fullLayout_plots axis refs
            // get updated properly so that we don't have
            // to use Axes.getFromId in general.

            xaArray[i] = Axes.getFromId(gd, plotObj.xaxis._id);
            yaArray[i] = Axes.getFromId(gd, plotObj.yaxis._id);
            continue;
        }

        // other subplot types
        var _subplot = fullLayout[spId]._subplot;
        xaArray[i] = _subplot.xaxis;
        yaArray[i] = _subplot.yaxis;
    }

    var hovermode = evt.hovermode || fullLayout.hovermode;

    if(hovermode && !supportsCompare) hovermode = 'closest';

    if(['x', 'y', 'closest'].indexOf(hovermode) === -1 || !gd.calcdata ||
            gd.querySelector('.zoombox') || gd._dragging) {
        return dragElement.unhoverRaw(gd, evt);
    }

    var hoverdistance = fullLayout.hoverdistance === -1 ? Infinity : fullLayout.hoverdistance;
    var spikedistance = fullLayout.spikedistance === -1 ? Infinity : fullLayout.spikedistance;

    // hoverData: the set of candidate points we've found to highlight
    var hoverData = [];

    // searchData: the data to search in. Mostly this is just a copy of
    // gd.calcdata, filtered to the subplot and overlays we're on
    // but if a point array is supplied it will be a mapping
    // of indicated curves
    var searchData = [];

    // [x|y]valArray: the axis values of the hover event
    // mapped onto each of the currently selected overlaid subplots
    var xvalArray, yvalArray;

    var itemnum, curvenum, cd, trace, subplotId, subploti, mode,
        xval, yval, pointData, closedataPreviousLength;

    // spikePoints: the set of candidate points we've found to draw spikes to
    var spikePoints = {
        hLinePoint: null,
        vLinePoint: null
    };

    // does subplot have one (or more) horizontal traces?
    // This is used to determine whether we rotate the labels or not
    var hasOneHorizontalTrace = false;

    // Figure out what we're hovering on:
    // mouse location or user-supplied data

    if(Array.isArray(evt)) {
        // user specified an array of points to highlight
        hovermode = 'array';
        for(itemnum = 0; itemnum < evt.length; itemnum++) {
            cd = gd.calcdata[evt[itemnum].curveNumber || 0];
            if(cd) {
                trace = cd[0].trace;
                if(cd[0].trace.hoverinfo !== 'skip') {
                    searchData.push(cd);
                    if(trace.orientation === 'h') {
                        hasOneHorizontalTrace = true;
                    }
                }
            }
        }
    }
    else {
        for(curvenum = 0; curvenum < gd.calcdata.length; curvenum++) {
            cd = gd.calcdata[curvenum];
            trace = cd[0].trace;
            if(trace.hoverinfo !== 'skip' && helpers.isTraceInSubplots(trace, subplots)) {
                searchData.push(cd);
                if(trace.orientation === 'h') {
                    hasOneHorizontalTrace = true;
                }
            }
        }

        // [x|y]px: the pixels (from top left) of the mouse location
        // on the currently selected plot area
        // add pointerX|Y property for drawing the spikes in spikesnap 'cursor' situation
        var hasUserCalledHover = !evt.target;
        var xpx, ypx;

        if(hasUserCalledHover) {
            if('xpx' in evt) xpx = evt.xpx;
            else xpx = xaArray[0]._length / 2;

            if('ypx' in evt) ypx = evt.ypx;
            else ypx = yaArray[0]._length / 2;
        }
        else {
            // fire the beforehover event and quit if it returns false
            // note that we're only calling this on real mouse events, so
            // manual calls to fx.hover will always run.
            if(Events.triggerHandler(gd, 'plotly_beforehover', evt) === false) {
                return;
            }

            var dbb = evt.target.getBoundingClientRect();

            xpx = evt.clientX - dbb.left;
            ypx = evt.clientY - dbb.top;

            // in case hover was called from mouseout into hovertext,
            // it's possible you're not actually over the plot anymore
            if(xpx < 0 || xpx > xaArray[0]._length || ypx < 0 || ypx > yaArray[0]._length) {
                return dragElement.unhoverRaw(gd, evt);
            }
        }

        evt.pointerX = xpx + xaArray[0]._offset;
        evt.pointerY = ypx + yaArray[0]._offset;

        if('xval' in evt) xvalArray = helpers.flat(subplots, evt.xval);
        else xvalArray = helpers.p2c(xaArray, xpx);

        if('yval' in evt) yvalArray = helpers.flat(subplots, evt.yval);
        else yvalArray = helpers.p2c(yaArray, ypx);

        if(!isNumeric(xvalArray[0]) || !isNumeric(yvalArray[0])) {
            Lib.warn('Fx.hover failed', evt, gd);
            return dragElement.unhoverRaw(gd, evt);
        }
    }

    // the pixel distance to beat as a matching point
    // in 'x' or 'y' mode this resets for each trace
    var distance = Infinity;

    // find the closest point in each trace
    // this is minimum dx and/or dy, depending on mode
    // and the pixel position for the label (labelXpx, labelYpx)
    for(curvenum = 0; curvenum < searchData.length; curvenum++) {
        cd = searchData[curvenum];

        // filter out invisible or broken data
        if(!cd || !cd[0] || !cd[0].trace || cd[0].trace.visible !== true) continue;

        trace = cd[0].trace;

        // Explicitly bail out for these two. I don't know how to otherwise prevent
        // the rest of this function from running and failing
        if(['carpet', 'contourcarpet'].indexOf(trace._module.name) !== -1) continue;

        if(trace.type === 'splom') {
            // splom traces do not generate overlay subplots,
            // it is safe to assume here splom traces correspond to the 0th subplot
            subploti = 0;
            subplotId = subplots[subploti];
        } else {
            subplotId = helpers.getSubplot(trace);
            subploti = subplots.indexOf(subplotId);
        }

        // within one trace mode can sometimes be overridden
        mode = hovermode;

        // container for new point, also used to pass info into module.hoverPoints
        pointData = {
            // trace properties
            cd: cd,
            trace: trace,
            xa: xaArray[subploti],
            ya: yaArray[subploti],

            // max distances for hover and spikes - for points that want to show but do not
            // want to override other points, set distance/spikeDistance equal to max*Distance
            // and it will not get filtered out but it will be guaranteed to have a greater
            // distance than any point that calculated a real distance.
            maxHoverDistance: hoverdistance,
            maxSpikeDistance: spikedistance,

            // point properties - override all of these
            index: false, // point index in trace - only used by plotly.js hoverdata consumers
            distance: Math.min(distance, hoverdistance), // pixel distance or pseudo-distance

            // distance/pseudo-distance for spikes. This distance should always be calculated
            // as if in "closest" mode, and should only be set if this point should
            // generate a spike.
            spikeDistance: Infinity,

            // in some cases the spikes have different positioning from the hover label
            // they don't need x0/x1, just one position
            xSpike: undefined,
            ySpike: undefined,

            // where and how to display the hover label
            color: Color.defaultLine, // trace color
            name: trace.name,
            x0: undefined,
            x1: undefined,
            y0: undefined,
            y1: undefined,
            xLabelVal: undefined,
            yLabelVal: undefined,
            zLabelVal: undefined,
            text: undefined
        };

        // add ref to subplot object (non-cartesian case)
        if(fullLayout[subplotId]) {
            pointData.subplot = fullLayout[subplotId]._subplot;
        }
        // add ref to splom scene
        if(fullLayout._splomScenes && fullLayout._splomScenes[trace.uid]) {
            pointData.scene = fullLayout._splomScenes[trace.uid];
        }

        closedataPreviousLength = hoverData.length;

        // for a highlighting array, figure out what
        // we're searching for with this element
        if(mode === 'array') {
            var selection = evt[curvenum];
            if('pointNumber' in selection) {
                pointData.index = selection.pointNumber;
                mode = 'closest';
            }
            else {
                mode = '';
                if('xval' in selection) {
                    xval = selection.xval;
                    mode = 'x';
                }
                if('yval' in selection) {
                    yval = selection.yval;
                    mode = mode ? 'closest' : 'y';
                }
            }
        }
        else {
            xval = xvalArray[subploti];
            yval = yvalArray[subploti];
        }

        // Now if there is range to look in, find the points to hover.
        if(hoverdistance !== 0) {
            if(trace._module && trace._module.hoverPoints) {
                var newPoints = trace._module.hoverPoints(pointData, xval, yval, mode, fullLayout._hoverlayer);
                if(newPoints) {
                    var newPoint;
                    for(var newPointNum = 0; newPointNum < newPoints.length; newPointNum++) {
                        newPoint = newPoints[newPointNum];
                        if(isNumeric(newPoint.x0) && isNumeric(newPoint.y0)) {
                            hoverData.push(cleanPoint(newPoint, hovermode));
                        }
                    }
                }
            }
            else {
                Lib.log('Unrecognized trace type in hover:', trace);
            }
        }

        // in closest mode, remove any existing (farther) points
        // and don't look any farther than this latest point (or points, some
        // traces like box & violin make multiple hover labels at once)
        if(hovermode === 'closest' && hoverData.length > closedataPreviousLength) {
            hoverData.splice(0, closedataPreviousLength);
            distance = hoverData[0].distance;
        }

        // Now if there is range to look in, find the points to draw the spikelines
        // Do it only if there is no hoverData
        if(hasCartesian && (spikedistance !== 0)) {
            if(hoverData.length === 0) {
                pointData.distance = spikedistance;
                pointData.index = false;
                var closestPoints = trace._module.hoverPoints(pointData, xval, yval, 'closest', fullLayout._hoverlayer);
                if(closestPoints) {
                    closestPoints = closestPoints.filter(function(point) {
                        // some hover points, like scatter fills, do not allow spikes,
                        // so will generate a hover point but without a valid spikeDistance
                        return point.spikeDistance <= spikedistance;
                    });
                }
                if(closestPoints && closestPoints.length) {
                    var tmpPoint;
                    var closestVPoints = closestPoints.filter(function(point) {
                        return point.xa.showspikes;
                    });
                    if(closestVPoints.length) {
                        var closestVPt = closestVPoints[0];
                        if(isNumeric(closestVPt.x0) && isNumeric(closestVPt.y0)) {
                            tmpPoint = fillSpikePoint(closestVPt);
                            if(!spikePoints.vLinePoint || (spikePoints.vLinePoint.spikeDistance > tmpPoint.spikeDistance)) {
                                spikePoints.vLinePoint = tmpPoint;
                            }
                        }
                    }

                    var closestHPoints = closestPoints.filter(function(point) {
                        return point.ya.showspikes;
                    });
                    if(closestHPoints.length) {
                        var closestHPt = closestHPoints[0];
                        if(isNumeric(closestHPt.x0) && isNumeric(closestHPt.y0)) {
                            tmpPoint = fillSpikePoint(closestHPt);
                            if(!spikePoints.hLinePoint || (spikePoints.hLinePoint.spikeDistance > tmpPoint.spikeDistance)) {
                                spikePoints.hLinePoint = tmpPoint;
                            }
                        }
                    }
                }
            }
        }
    }

    function selectClosestPoint(pointsData, spikedistance) {
        var resultPoint = null;
        var minDistance = Infinity;
        var thisSpikeDistance;
        for(var i = 0; i < pointsData.length; i++) {
            thisSpikeDistance = pointsData[i].spikeDistance;
            if(thisSpikeDistance < minDistance && thisSpikeDistance <= spikedistance) {
                resultPoint = pointsData[i];
                minDistance = thisSpikeDistance;
            }
        }
        return resultPoint;
    }

    function fillSpikePoint(point) {
        if(!point) return null;
        return {
            xa: point.xa,
            ya: point.ya,
            x: point.xSpike !== undefined ? point.xSpike : (point.x0 + point.x1) / 2,
            y: point.ySpike !== undefined ? point.ySpike : (point.y0 + point.y1) / 2,
            distance: point.distance,
            spikeDistance: point.spikeDistance,
            curveNumber: point.trace.index,
            color: point.color,
            pointNumber: point.index
        };
    }

    var spikelineOpts = {
        fullLayout: fullLayout,
        container: fullLayout._hoverlayer,
        outerContainer: fullLayout._paperdiv,
        event: evt
    };
    var oldspikepoints = gd._spikepoints;
    var newspikepoints = {
        vLinePoint: spikePoints.vLinePoint,
        hLinePoint: spikePoints.hLinePoint
    };
    gd._spikepoints = newspikepoints;

    // Now if it is not restricted by spikedistance option, set the points to draw the spikelines
    if(hasCartesian && (spikedistance !== 0)) {
        if(hoverData.length !== 0) {
            var tmpHPointData = hoverData.filter(function(point) {
                return point.ya.showspikes;
            });
            var tmpHPoint = selectClosestPoint(tmpHPointData, spikedistance);
            spikePoints.hLinePoint = fillSpikePoint(tmpHPoint);

            var tmpVPointData = hoverData.filter(function(point) {
                return point.xa.showspikes;
            });
            var tmpVPoint = selectClosestPoint(tmpVPointData, spikedistance);
            spikePoints.vLinePoint = fillSpikePoint(tmpVPoint);
        }
    }

    // if hoverData is empty check for the spikes to draw and quit if there are none
    if(hoverData.length === 0) {
        var result = dragElement.unhoverRaw(gd, evt);
        if(hasCartesian && ((spikePoints.hLinePoint !== null) || (spikePoints.vLinePoint !== null))) {
            if(spikesChanged(oldspikepoints)) {
                createSpikelines(spikePoints, spikelineOpts);
            }
        }
        return result;
    }

    if(hasCartesian) {
        if(spikesChanged(oldspikepoints)) {
            createSpikelines(spikePoints, spikelineOpts);
        }
    }

    hoverData.sort(function(d1, d2) { return d1.distance - d2.distance; });

    // lastly, emit custom hover/unhover events
    var oldhoverdata = gd._hoverdata;
    var newhoverdata = [];

    // pull out just the data that's useful to
    // other people and send it to the event
    for(itemnum = 0; itemnum < hoverData.length; itemnum++) {
        var pt = hoverData[itemnum];
        var eventData = helpers.makeEventData(pt, pt.trace, pt.cd);

        var ht = false;
        if(pt.cd[pt.index] && pt.cd[pt.index].ht) ht = pt.cd[pt.index].ht;
        hoverData[itemnum].hovertemplate = ht || pt.trace.hovertemplate || false;
        hoverData[itemnum].eventData = [eventData];

        newhoverdata.push(eventData);
    }

    gd._hoverdata = newhoverdata;

    var rotateLabels = (
        (hovermode === 'y' && (searchData.length > 1 || hoverData.length > 1)) ||
        (hovermode === 'closest' && hasOneHorizontalTrace && hoverData.length > 1)
    );

    var bgColor = Color.combine(
        fullLayout.plot_bgcolor || Color.background,
        fullLayout.paper_bgcolor
    );

    var labelOpts = {
        hovermode: hovermode,
        rotateLabels: rotateLabels,
        bgColor: bgColor,
        container: fullLayout._hoverlayer,
        outerContainer: fullLayout._paperdiv,
        commonLabelOpts: fullLayout.hoverlabel,
        hoverdistance: fullLayout.hoverdistance
    };

    var hoverLabels = createHoverText(hoverData, labelOpts, gd);

    hoverAvoidOverlaps(hoverData, rotateLabels ? 'xa' : 'ya', fullLayout);

    alignHoverText(hoverLabels, rotateLabels);

    // TODO: tagName hack is needed to appease geo.js's hack of using evt.target=true
    // we should improve the "fx" API so other plots can use it without these hack.
    if(evt.target && evt.target.tagName) {
        var hasClickToShow = Registry.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata);
        overrideCursor(d3.select(evt.target), hasClickToShow ? 'pointer' : '');
    }

    // don't emit events if called manually
    if(!evt.target || noHoverEvent || !hoverChanged(gd, evt, oldhoverdata)) return;

    if(oldhoverdata) {
        gd.emit('plotly_unhover', {
            event: evt,
            points: oldhoverdata
        });
    }

    gd.emit('plotly_hover', {
        event: evt,
        points: gd._hoverdata,
        xaxes: xaArray,
        yaxes: yaArray,
        xvals: xvalArray,
        yvals: yvalArray
    });
}

var EXTRA_STRING_REGEX = /<extra>([\s\S]*)<\/extra>/;

function createHoverText(hoverData, opts, gd) {
    var hovermode = opts.hovermode;
    var rotateLabels = opts.rotateLabels;
    var bgColor = opts.bgColor;
    var container = opts.container;
    var outerContainer = opts.outerContainer;
    var commonLabelOpts = opts.commonLabelOpts || {};

    // opts.fontFamily/Size are used for the common label
    // and as defaults for each hover label, though the individual labels
    // can override this.
    var fontFamily = opts.fontFamily || constants.HOVERFONT;
    var fontSize = opts.fontSize || constants.HOVERFONTSIZE;

    var c0 = hoverData[0];
    var xa = c0.xa;
    var ya = c0.ya;
    var commonAttr = hovermode === 'y' ? 'yLabel' : 'xLabel';
    var t0 = c0[commonAttr];
    var t00 = (String(t0) || '').split(' ')[0];
    var outerContainerBB = outerContainer.node().getBoundingClientRect();
    var outerTop = outerContainerBB.top;
    var outerWidth = outerContainerBB.width;
    var outerHeight = outerContainerBB.height;

    // show the common label, if any, on the axis
    // never show a common label in array mode,
    // even if sometimes there could be one
    var showCommonLabel = (
        (t0 !== undefined) &&
        (c0.distance <= opts.hoverdistance) &&
        (hovermode === 'x' || hovermode === 'y')
    );

    // all hover traces hoverinfo must contain the hovermode
    // to have common labels
    if(showCommonLabel) {
        var allHaveZ = true;
        var i, traceHoverinfo;
        for(i = 0; i < hoverData.length; i++) {
            if(allHaveZ && hoverData[i].zLabel === undefined) allHaveZ = false;

            traceHoverinfo = hoverData[i].hoverinfo || hoverData[i].trace.hoverinfo;
            if(traceHoverinfo) {
                var parts = Array.isArray(traceHoverinfo) ? traceHoverinfo : traceHoverinfo.split('+');
                if(parts.indexOf('all') === -1 &&
                    parts.indexOf(hovermode) === -1) {
                    showCommonLabel = false;
                    break;
                }
            }
        }

        // xyz labels put all info in their main label, so have no need of a common label
        if(allHaveZ) showCommonLabel = false;
    }

    var commonLabel = container.selectAll('g.axistext')
        .data(showCommonLabel ? [0] : []);
    commonLabel.enter().append('g')
        .classed('axistext', true);
    commonLabel.exit().remove();

    commonLabel.each(function() {
        var label = d3.select(this);
        var lpath = Lib.ensureSingle(label, 'path', '', function(s) {
            s.style({'stroke-width': '1px'});
        });
        var ltext = Lib.ensureSingle(label, 'text', '', function(s) {
            // prohibit tex interpretation until we can handle
            // tex and regular text together
            s.attr('data-notex', 1);
        });

        var commonBgColor = commonLabelOpts.bgcolor || Color.defaultLine;
        var commonStroke = commonLabelOpts.bordercolor || Color.contrast(commonBgColor);
        var contrastColor = Color.contrast(commonBgColor);

        lpath.style({
            fill: commonBgColor,
            stroke: commonStroke
        });

        ltext.text(t0)
            .call(Drawing.font,
                commonLabelOpts.font.family || fontFamily,
                commonLabelOpts.font.size || fontSize,
                commonLabelOpts.font.color || contrastColor
             )
            .call(svgTextUtils.positionText, 0, 0)
            .call(svgTextUtils.convertToTspans, gd);

        label.attr('transform', '');

        var tbb = ltext.node().getBoundingClientRect();
        if(hovermode === 'x') {
            ltext.attr('text-anchor', 'middle')
                .call(svgTextUtils.positionText, 0, (xa.side === 'top' ?
                    (outerTop - tbb.bottom - HOVERARROWSIZE - HOVERTEXTPAD) :
                    (outerTop - tbb.top + HOVERARROWSIZE + HOVERTEXTPAD)));

            var topsign = xa.side === 'top' ? '-' : '';
            lpath.attr('d', 'M0,0' +
                'L' + HOVERARROWSIZE + ',' + topsign + HOVERARROWSIZE +
                'H' + (HOVERTEXTPAD + tbb.width / 2) +
                'v' + topsign + (HOVERTEXTPAD * 2 + tbb.height) +
                'H-' + (HOVERTEXTPAD + tbb.width / 2) +
                'V' + topsign + HOVERARROWSIZE + 'H-' + HOVERARROWSIZE + 'Z');

            label.attr('transform', 'translate(' +
                (xa._offset + (c0.x0 + c0.x1) / 2) + ',' +
                (ya._offset + (xa.side === 'top' ? 0 : ya._length)) + ')');
        }
        else {
            ltext.attr('text-anchor', ya.side === 'right' ? 'start' : 'end')
                .call(svgTextUtils.positionText,
                    (ya.side === 'right' ? 1 : -1) * (HOVERTEXTPAD + HOVERARROWSIZE),
                    outerTop - tbb.top - tbb.height / 2);

            var leftsign = ya.side === 'right' ? '' : '-';
            lpath.attr('d', 'M0,0' +
                'L' + leftsign + HOVERARROWSIZE + ',' + HOVERARROWSIZE +
                'V' + (HOVERTEXTPAD + tbb.height / 2) +
                'h' + leftsign + (HOVERTEXTPAD * 2 + tbb.width) +
                'V-' + (HOVERTEXTPAD + tbb.height / 2) +
                'H' + leftsign + HOVERARROWSIZE + 'V-' + HOVERARROWSIZE + 'Z');

            label.attr('transform', 'translate(' +
                (xa._offset + (ya.side === 'right' ? xa._length : 0)) + ',' +
                (ya._offset + (c0.y0 + c0.y1) / 2) + ')');
        }
        // remove the "close but not quite" points
        // because of error bars, only take up to a space
        hoverData = hoverData.filter(function(d) {
            return (d.zLabelVal !== undefined) ||
                (d[commonAttr] || '').split(' ')[0] === t00;
        });
    });

    // show all the individual labels

    // first create the objects
    var hoverLabels = container.selectAll('g.hovertext')
        .data(hoverData, function(d) {
            return [d.trace.index, d.index, d.x0, d.y0, d.name, d.attr, d.xa, d.ya || ''].join(',');
        });
    hoverLabels.enter().append('g')
        .classed('hovertext', true)
        .each(function() {
            var g = d3.select(this);
            // trace name label (rect and text.name)
            g.append('rect')
                .call(Color.fill, Color.addOpacity(bgColor, 0.8));
            g.append('text').classed('name', true);
            // trace data label (path and text.nums)
            g.append('path')
                .style('stroke-width', '1px');
            g.append('text').classed('nums', true)
                .call(Drawing.font, fontFamily, fontSize);
        });
    hoverLabels.exit().remove();

    // then put the text in, position the pointer to the data,
    // and figure out sizes
    hoverLabels.each(function(d) {
        var g = d3.select(this).attr('transform', '');
        var name = '';
        var text = '';

        // combine possible non-opaque trace color with bgColor
        var color0 = d.bgcolor || d.color;
        // color for 'nums' part of the label
        var numsColor = Color.combine(
            Color.opacity(color0) ? color0 : Color.defaultLine,
            bgColor
        );
        // color for 'name' part of the label
        var nameColor = Color.combine(
            Color.opacity(d.color) ? d.color : Color.defaultLine,
            bgColor
        );
        // find a contrasting color for border and text
        var contrastColor = d.borderColor || Color.contrast(numsColor);

        // to get custom 'name' labels pass cleanPoint
        if(d.nameOverride !== undefined) d.name = d.nameOverride;

        if(d.name) {
            name = svgTextUtils.plainText(d.name || '', {
                len: d.nameLength,
                allowedTags: ['br', 'sub', 'sup', 'b', 'i', 'em']
            });
        }

        if(d.zLabel !== undefined) {
            if(d.xLabel !== undefined) text += 'x: ' + d.xLabel + '<br>';
            if(d.yLabel !== undefined) text += 'y: ' + d.yLabel + '<br>';
            text += (text ? 'z: ' : '') + d.zLabel;
        }
        else if(showCommonLabel && d[hovermode + 'Label'] === t0) {
            text = d[(hovermode === 'x' ? 'y' : 'x') + 'Label'] || '';
        }
        else if(d.xLabel === undefined) {
            if(d.yLabel !== undefined) text = d.yLabel;
        }
        else if(d.yLabel === undefined) text = d.xLabel;
        else text = '(' + d.xLabel + ', ' + d.yLabel + ')';

        if((d.text || d.text === 0) && !Array.isArray(d.text)) {
            text += (text ? '<br>' : '') + d.text;
        }

        // used by other modules (initially just ternary) that
        // manage their own hoverinfo independent of cleanPoint
        // the rest of this will still apply, so such modules
        // can still put things in (x|y|z)Label, text, and name
        // and hoverinfo will still determine their visibility
        if(d.extraText !== undefined) text += (text ? '<br>' : '') + d.extraText;

        // if 'text' is empty at this point,
        // and hovertemplate is not defined,
        // put 'name' in main label and don't show secondary label
        if(text === '' && !d.hovertemplate) {
            // if 'name' is also empty, remove entire label
            if(name === '') g.remove();
            text = name;
        }

        // hovertemplate
        var hovertemplate = d.hovertemplate || false;
        var hovertemplateLabels = d.hovertemplateLabels || d;
        var eventData = d.eventData[0] || {};
        if(hovertemplate) {
            text = Lib.hovertemplateString(hovertemplate, hovertemplateLabels, eventData);

            text = text.replace(EXTRA_STRING_REGEX, function(match, extra) {
                name = extra; // Assign name for secondary text label
                return ''; // Remove from main text label
            });
        }

        // main label
        var tx = g.select('text.nums')
            .call(Drawing.font,
                d.fontFamily || fontFamily,
                d.fontSize || fontSize,
                d.fontColor || contrastColor)
            .text(text)
            .attr('data-notex', 1)
            .call(svgTextUtils.positionText, 0, 0)
            .call(svgTextUtils.convertToTspans, gd);

        var tx2 = g.select('text.name');
        var tx2width = 0;
        var tx2height = 0;

        // secondary label for non-empty 'name'
        if(name && name !== text) {
            tx2.call(Drawing.font,
                    d.fontFamily || fontFamily,
                    d.fontSize || fontSize,
                    nameColor)
                .text(name)
                .attr('data-notex', 1)
                .call(svgTextUtils.positionText, 0, 0)
                .call(svgTextUtils.convertToTspans, gd);

            var t2bb = tx2.node().getBoundingClientRect();
            tx2width = t2bb.width + 2 * HOVERTEXTPAD;
            tx2height = t2bb.height + 2 * HOVERTEXTPAD;
        } else {
            tx2.remove();
            g.select('rect').remove();
        }

        g.select('path').style({
            fill: numsColor,
            stroke: contrastColor
        });

        var tbb = tx.node().getBoundingClientRect();
        var htx = d.xa._offset + (d.x0 + d.x1) / 2;
        var hty = d.ya._offset + (d.y0 + d.y1) / 2;
        var dx = Math.abs(d.x1 - d.x0);
        var dy = Math.abs(d.y1 - d.y0);
        var txTotalWidth = tbb.width + HOVERARROWSIZE + HOVERTEXTPAD + tx2width;
        var anchorStartOK, anchorEndOK;

        d.ty0 = outerTop - tbb.top;
        d.bx = tbb.width + 2 * HOVERTEXTPAD;
        d.by = Math.max(tbb.height + 2 * HOVERTEXTPAD, tx2height);
        d.anchor = 'start';
        d.txwidth = tbb.width;
        d.tx2width = tx2width;
        d.offset = 0;

        if(rotateLabels) {
            d.pos = htx;
            anchorStartOK = hty + dy / 2 + txTotalWidth <= outerHeight;
            anchorEndOK = hty - dy / 2 - txTotalWidth >= 0;
            if((d.idealAlign === 'top' || !anchorStartOK) && anchorEndOK) {
                hty -= dy / 2;
                d.anchor = 'end';
            } else if(anchorStartOK) {
                hty += dy / 2;
                d.anchor = 'start';
            } else d.anchor = 'middle';
        }
        else {
            d.pos = hty;
            anchorStartOK = htx + dx / 2 + txTotalWidth <= outerWidth;
            anchorEndOK = htx - dx / 2 - txTotalWidth >= 0;
            if((d.idealAlign === 'left' || !anchorStartOK) && anchorEndOK) {
                htx -= dx / 2;
                d.anchor = 'end';
            } else if(anchorStartOK) {
                htx += dx / 2;
                d.anchor = 'start';
            } else d.anchor = 'middle';
        }

        tx.attr('text-anchor', d.anchor);
        if(tx2width) tx2.attr('text-anchor', d.anchor);
        g.attr('transform', 'translate(' + htx + ',' + hty + ')' +
            (rotateLabels ? 'rotate(' + YANGLE + ')' : ''));
    });

    return hoverLabels;
}

// Make groups of touching points, and within each group
// move each point so that no labels overlap, but the average
// label position is the same as it was before moving. Indicentally,
// this is equivalent to saying all the labels are on equal linear
// springs about their initial position. Initially, each point is
// its own group, but as we find overlaps we will clump the points.
//
// Also, there are hard constraints at the edges of the graphs,
// that push all groups to the middle so they are visible. I don't
// know what happens if the group spans all the way from one edge to
// the other, though it hardly matters - there's just too much
// information then.
function hoverAvoidOverlaps(hoverData, ax, fullLayout) {
    var nummoves = 0;
    var axSign = 1;

    // make groups of touching points
    var pointgroups = hoverData.map(function(d, i) {
        var axis = d[ax];
        var axIsX = axis._id.charAt(0) === 'x';
        var rng = axis.range;
        if(!i && rng && ((rng[0] > rng[1]) !== axIsX)) axSign = -1;
        return [{
            i: i,
            traceIndex: d.trace.index,
            dp: 0,
            pos: d.pos,
            posref: d.posref,
            size: d.by * (axIsX ? YFACTOR : 1) / 2,
            pmin: 0,
            pmax: (axIsX ? fullLayout.width : fullLayout.height)
        }];
    })
    .sort(function(a, b) {
        return (a[0].posref - b[0].posref) ||
            // for equal positions, sort trace indices increasing or decreasing
            // depending on whether the axis is reversed or not... so stacked
            // traces will generally keep their order even if one trace adds
            // nothing to the stack.
            (axSign * (b[0].traceIndex - a[0].traceIndex));
    });

    var donepositioning, topOverlap, bottomOverlap, i, j, pti, sumdp;

    function constrainGroup(grp) {
        var minPt = grp[0];
        var maxPt = grp[grp.length - 1];

        // overlap with the top - positive vals are overlaps
        topOverlap = minPt.pmin - minPt.pos - minPt.dp + minPt.size;

        // overlap with the bottom - positive vals are overlaps
        bottomOverlap = maxPt.pos + maxPt.dp + maxPt.size - minPt.pmax;

        // check for min overlap first, so that we always
        // see the largest labels
        // allow for .01px overlap, so we don't get an
        // infinite loop from rounding errors
        if(topOverlap > 0.01) {
            for(j = grp.length - 1; j >= 0; j--) grp[j].dp += topOverlap;
            donepositioning = false;
        }
        if(bottomOverlap < 0.01) return;
        if(topOverlap < -0.01) {
            // make sure we're not pushing back and forth
            for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap;
            donepositioning = false;
        }
        if(!donepositioning) return;

        // no room to fix positioning, delete off-screen points

        // first see how many points we need to delete
        var deleteCount = 0;
        for(i = 0; i < grp.length; i++) {
            pti = grp[i];
            if(pti.pos + pti.dp + pti.size > minPt.pmax) deleteCount++;
        }

        // start by deleting points whose data is off screen
        for(i = grp.length - 1; i >= 0; i--) {
            if(deleteCount <= 0) break;
            pti = grp[i];

            // pos has already been constrained to [pmin,pmax]
            // so look for points close to that to delete
            if(pti.pos > minPt.pmax - 1) {
                pti.del = true;
                deleteCount--;
            }
        }
        for(i = 0; i < grp.length; i++) {
            if(deleteCount <= 0) break;
            pti = grp[i];

            // pos has already been constrained to [pmin,pmax]
            // so look for points close to that to delete
            if(pti.pos < minPt.pmin + 1) {
                pti.del = true;
                deleteCount--;

                // shift the whole group minus into this new space
                bottomOverlap = pti.size * 2;
                for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap;
            }
        }
        // then delete points that go off the bottom
        for(i = grp.length - 1; i >= 0; i--) {
            if(deleteCount <= 0) break;
            pti = grp[i];
            if(pti.pos + pti.dp + pti.size > minPt.pmax) {
                pti.del = true;
                deleteCount--;
            }
        }
    }

    // loop through groups, combining them if they overlap,
    // until nothing moves
    while(!donepositioning && nummoves <= hoverData.length) {
        // to avoid infinite loops, don't move more times
        // than there are traces
        nummoves++;

        // assume nothing will move in this iteration,
        // reverse this if it does
        donepositioning = true;
        i = 0;
        while(i < pointgroups.length - 1) {
                // the higher (g0) and lower (g1) point group
            var g0 = pointgroups[i];
            var g1 = pointgroups[i + 1];

            // the lowest point in the higher group (p0)
            // the highest point in the lower group (p1)
            var p0 = g0[g0.length - 1];
            var p1 = g1[0];
            topOverlap = p0.pos + p0.dp + p0.size - p1.pos - p1.dp + p1.size;

            // Only group points that lie on the same axes
            if(topOverlap > 0.01 && (p0.pmin === p1.pmin) && (p0.pmax === p1.pmax)) {
                // push the new point(s) added to this group out of the way
                for(j = g1.length - 1; j >= 0; j--) g1[j].dp += topOverlap;

                // add them to the group
                g0.push.apply(g0, g1);
                pointgroups.splice(i + 1, 1);

                // adjust for minimum average movement
                sumdp = 0;
                for(j = g0.length - 1; j >= 0; j--) sumdp += g0[j].dp;
                bottomOverlap = sumdp / g0.length;
                for(j = g0.length - 1; j >= 0; j--) g0[j].dp -= bottomOverlap;
                donepositioning = false;
            }
            else i++;
        }

        // check if we're going off the plot on either side and fix
        pointgroups.forEach(constrainGroup);
    }

    // now put these offsets into hoverData
    for(i = pointgroups.length - 1; i >= 0; i--) {
        var grp = pointgroups[i];
        for(j = grp.length - 1; j >= 0; j--) {
            var pt = grp[j];
            var hoverPt = hoverData[pt.i];
            hoverPt.offset = pt.dp;
            hoverPt.del = pt.del;
        }
    }
}

function alignHoverText(hoverLabels, rotateLabels) {
    // finally set the text positioning relative to the data and draw the
    // box around it
    hoverLabels.each(function(d) {
        var g = d3.select(this);
        if(d.del) {
            g.remove();
            return;
        }

        var horzSign = d.anchor === 'end' ? -1 : 1;
        var tx = g.select('text.nums');
        var alignShift = {start: 1, end: -1, middle: 0}[d.anchor];
        var txx = alignShift * (HOVERARROWSIZE + HOVERTEXTPAD);
        var tx2x = txx + alignShift * (d.txwidth + HOVERTEXTPAD);
        var offsetX = 0;
        var offsetY = d.offset;

        if(d.anchor === 'middle') {
            txx -= d.tx2width / 2;
            tx2x += d.txwidth / 2 + HOVERTEXTPAD;
        }
        if(rotateLabels) {
            offsetY *= -YSHIFTY;
            offsetX = d.offset * YSHIFTX;
        }

        g.select('path').attr('d', d.anchor === 'middle' ?
            // middle aligned: rect centered on data
            ('M-' + (d.bx / 2 + d.tx2width / 2) + ',' + (offsetY - d.by / 2) +
              'h' + d.bx + 'v' + d.by + 'h-' + d.bx + 'Z') :
            // left or right aligned: side rect with arrow to data
            ('M0,0L' + (horzSign * HOVERARROWSIZE + offsetX) + ',' + (HOVERARROWSIZE + offsetY) +
                'v' + (d.by / 2 - HOVERARROWSIZE) +
                'h' + (horzSign * d.bx) +
                'v-' + d.by +
                'H' + (horzSign * HOVERARROWSIZE + offsetX) +
                'V' + (offsetY - HOVERARROWSIZE) +
                'Z'));

        tx.call(svgTextUtils.positionText,
            txx + offsetX, offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD);

        if(d.tx2width) {
            g.select('text.name')
                .call(svgTextUtils.positionText,
                    tx2x + alignShift * HOVERTEXTPAD + offsetX,
                    offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD);
            g.select('rect')
                .call(Drawing.setRect,
                    tx2x + (alignShift - 1) * d.tx2width / 2 + offsetX,
                    offsetY - d.by / 2 - 1,
                    d.tx2width, d.by + 2);
        }
    });
}

function cleanPoint(d, hovermode) {
    var index = d.index;
    var trace = d.trace || {};
    var cd0 = d.cd[0];
    var cd = d.cd[index] || {};

    var getVal = Array.isArray(index) ?
        function(calcKey, traceKey) {
            return Lib.castOption(cd0, index, calcKey) ||
                Lib.extractOption({}, trace, '', traceKey);
        } :
        function(calcKey, traceKey) {
            return Lib.extractOption(cd, trace, calcKey, traceKey);
        };

    function fill(key, calcKey, traceKey) {
        var val = getVal(calcKey, traceKey);
        if(val) d[key] = val;
    }

    fill('hoverinfo', 'hi', 'hoverinfo');
    fill('bgcolor', 'hbg', 'hoverlabel.bgcolor');
    fill('borderColor', 'hbc', 'hoverlabel.bordercolor');
    fill('fontFamily', 'htf', 'hoverlabel.font.family');
    fill('fontSize', 'hts', 'hoverlabel.font.size');
    fill('fontColor', 'htc', 'hoverlabel.font.color');
    fill('nameLength', 'hnl', 'hoverlabel.namelength');

    d.posref = (hovermode === 'y' || (hovermode === 'closest' && trace.orientation === 'h')) ?
        (d.xa._offset + (d.x0 + d.x1) / 2) :
        (d.ya._offset + (d.y0 + d.y1) / 2);

    // then constrain all the positions to be on the plot
    d.x0 = Lib.constrain(d.x0, 0, d.xa._length);
    d.x1 = Lib.constrain(d.x1, 0, d.xa._length);
    d.y0 = Lib.constrain(d.y0, 0, d.ya._length);
    d.y1 = Lib.constrain(d.y1, 0, d.ya._length);

    // and convert the x and y label values into formatted text
    if(d.xLabelVal !== undefined) {
        d.xLabel = ('xLabel' in d) ? d.xLabel : Axes.hoverLabelText(d.xa, d.xLabelVal);
        d.xVal = d.xa.c2d(d.xLabelVal);
    }
    if(d.yLabelVal !== undefined) {
        d.yLabel = ('yLabel' in d) ? d.yLabel : Axes.hoverLabelText(d.ya, d.yLabelVal);
        d.yVal = d.ya.c2d(d.yLabelVal);
    }

    // Traces like heatmaps generate the zLabel in their hoverPoints function
    if(d.zLabelVal !== undefined && d.zLabel === undefined) {
        d.zLabel = String(d.zLabelVal);
    }

    // for box means and error bars, add the range to the label
    if(!isNaN(d.xerr) && !(d.xa.type === 'log' && d.xerr <= 0)) {
        var xeText = Axes.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text;
        if(d.xerrneg !== undefined) {
            d.xLabel += ' +' + xeText + ' / -' +
                Axes.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text;
        }
        else d.xLabel += ' ± ' + xeText;

        // small distance penalty for error bars, so that if there are
        // traces with errors and some without, the error bar label will
        // hoist up to the point
        if(hovermode === 'x') d.distance += 1;
    }
    if(!isNaN(d.yerr) && !(d.ya.type === 'log' && d.yerr <= 0)) {
        var yeText = Axes.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text;
        if(d.yerrneg !== undefined) {
            d.yLabel += ' +' + yeText + ' / -' +
                Axes.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text;
        }
        else d.yLabel += ' ± ' + yeText;

        if(hovermode === 'y') d.distance += 1;
    }

    var infomode = d.hoverinfo || d.trace.hoverinfo;

    if(infomode && infomode !== 'all') {
        infomode = Array.isArray(infomode) ? infomode : infomode.split('+');
        if(infomode.indexOf('x') === -1) d.xLabel = undefined;
        if(infomode.indexOf('y') === -1) d.yLabel = undefined;
        if(infomode.indexOf('z') === -1) d.zLabel = undefined;
        if(infomode.indexOf('text') === -1) d.text = undefined;
        if(infomode.indexOf('name') === -1) d.name = undefined;
    }

    return d;
}

function createSpikelines(closestPoints, opts) {
    var container = opts.container;
    var fullLayout = opts.fullLayout;
    var evt = opts.event;
    var showY = !!closestPoints.hLinePoint;
    var showX = !!closestPoints.vLinePoint;

    var xa, ya;

    // Remove old spikeline items
    container.selectAll('.spikeline').remove();

    if(!(showX || showY)) return;

    var contrastColor = Color.combine(fullLayout.plot_bgcolor, fullLayout.paper_bgcolor);

    // Horizontal line (to y-axis)
    if(showY) {
        var hLinePoint = closestPoints.hLinePoint;
        var hLinePointX, hLinePointY;

        xa = hLinePoint && hLinePoint.xa;
        ya = hLinePoint && hLinePoint.ya;
        var ySnap = ya.spikesnap;

        if(ySnap === 'cursor') {
            hLinePointX = evt.pointerX;
            hLinePointY = evt.pointerY;
        } else {
            hLinePointX = xa._offset + hLinePoint.x;
            hLinePointY = ya._offset + hLinePoint.y;
        }
        var dfltHLineColor = tinycolor.readability(hLinePoint.color, contrastColor) < 1.5 ?
            Color.contrast(contrastColor) : hLinePoint.color;
        var yMode = ya.spikemode;
        var yThickness = ya.spikethickness;
        var yColor = ya.spikecolor || dfltHLineColor;
        var yBB = ya._boundingBox;
        var xEdge = ((yBB.left + yBB.right) / 2) < hLinePointX ? yBB.right : yBB.left;
        var xBase, xEndSpike;

        if(yMode.indexOf('toaxis') !== -1 || yMode.indexOf('across') !== -1) {
            if(yMode.indexOf('toaxis') !== -1) {
                xBase = xEdge;
                xEndSpike = hLinePointX;
            }
            if(yMode.indexOf('across') !== -1) {
                xBase = ya._counterSpan[0];
                xEndSpike = ya._counterSpan[1];
            }

            // Foreground horizontal line (to y-axis)
            container.insert('line', ':first-child')
                .attr({
                    x1: xBase,
                    x2: xEndSpike,
                    y1: hLinePointY,
                    y2: hLinePointY,
                    'stroke-width': yThickness,
                    stroke: yColor,
                    'stroke-dasharray': Drawing.dashStyle(ya.spikedash, yThickness)
                })
                .classed('spikeline', true)
                .classed('crisp', true);

            // Background horizontal Line (to y-axis)
            container.insert('line', ':first-child')
                .attr({
                    x1: xBase,
                    x2: xEndSpike,
                    y1: hLinePointY,
                    y2: hLinePointY,
                    'stroke-width': yThickness + 2,
                    stroke: contrastColor
                })
                .classed('spikeline', true)
                .classed('crisp', true);
        }
        // Y axis marker
        if(yMode.indexOf('marker') !== -1) {
            container.insert('circle', ':first-child')
                .attr({
                    cx: xEdge + (ya.side !== 'right' ? yThickness : -yThickness),
                    cy: hLinePointY,
                    r: yThickness,
                    fill: yColor
                })
                .classed('spikeline', true);
        }
    }

    if(showX) {
        var vLinePoint = closestPoints.vLinePoint;
        var vLinePointX, vLinePointY;

        xa = vLinePoint && vLinePoint.xa;
        ya = vLinePoint && vLinePoint.ya;
        var xSnap = xa.spikesnap;

        if(xSnap === 'cursor') {
            vLinePointX = evt.pointerX;
            vLinePointY = evt.pointerY;
        } else {
            vLinePointX = xa._offset + vLinePoint.x;
            vLinePointY = ya._offset + vLinePoint.y;
        }
        var dfltVLineColor = tinycolor.readability(vLinePoint.color, contrastColor) < 1.5 ?
            Color.contrast(contrastColor) : vLinePoint.color;
        var xMode = xa.spikemode;
        var xThickness = xa.spikethickness;
        var xColor = xa.spikecolor || dfltVLineColor;
        var xBB = xa._boundingBox;
        var yEdge = ((xBB.top + xBB.bottom) / 2) < vLinePointY ? xBB.bottom : xBB.top;
        var yBase, yEndSpike;

        if(xMode.indexOf('toaxis') !== -1 || xMode.indexOf('across') !== -1) {
            if(xMode.indexOf('toaxis') !== -1) {
                yBase = yEdge;
                yEndSpike = vLinePointY;
            }
            if(xMode.indexOf('across') !== -1) {
                yBase = xa._counterSpan[0];
                yEndSpike = xa._counterSpan[1];
            }

            // Foreground vertical line (to x-axis)
            container.insert('line', ':first-child')
                .attr({
                    x1: vLinePointX,
                    x2: vLinePointX,
                    y1: yBase,
                    y2: yEndSpike,
                    'stroke-width': xThickness,
                    stroke: xColor,
                    'stroke-dasharray': Drawing.dashStyle(xa.spikedash, xThickness)
                })
                .classed('spikeline', true)
                .classed('crisp', true);

            // Background vertical line (to x-axis)
            container.insert('line', ':first-child')
                .attr({
                    x1: vLinePointX,
                    x2: vLinePointX,
                    y1: yBase,
                    y2: yEndSpike,
                    'stroke-width': xThickness + 2,
                    stroke: contrastColor
                })
                .classed('spikeline', true)
                .classed('crisp', true);
        }

        // X axis marker
        if(xMode.indexOf('marker') !== -1) {
            container.insert('circle', ':first-child')
                .attr({
                    cx: vLinePointX,
                    cy: yEdge - (xa.side !== 'top' ? xThickness : -xThickness),
                    r: xThickness,
                    fill: xColor
                })
                .classed('spikeline', true);
        }
    }
}

function hoverChanged(gd, evt, oldhoverdata) {
    // don't emit any events if nothing changed
    if(!oldhoverdata || oldhoverdata.length !== gd._hoverdata.length) return true;

    for(var i = oldhoverdata.length - 1; i >= 0; i--) {
        var oldPt = oldhoverdata[i];
        var newPt = gd._hoverdata[i];

        if(oldPt.curveNumber !== newPt.curveNumber ||
            String(oldPt.pointNumber) !== String(newPt.pointNumber) ||
            String(oldPt.pointNumbers) !== String(newPt.pointNumbers)
        ) {
            return true;
        }
    }
    return false;
}

function spikesChanged(gd, oldspikepoints) {
    // don't relayout the plot because of new spikelines if spikelines points didn't change
    if(!oldspikepoints) return true;
    if(oldspikepoints.vLinePoint !== gd._spikepoints.vLinePoint ||
        oldspikepoints.hLinePoint !== gd._spikepoints.hLinePoint
    ) return true;
    return false;
}

},{"../../lib":694,"../../lib/events":683,"../../lib/override_cursor":705,"../../lib/svg_text_utils":718,"../../plots/cartesian/axes":742,"../../registry":825,"../color":571,"../dragelement":589,"../drawing":592,"./constants":604,"./helpers":606,"d3":149,"fast-isnumeric":215,"tinycolor2":515}],608:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

module.exports = function handleHoverLabelDefaults(contIn, contOut, coerce, opts) {
    opts = opts || {};

    coerce('hoverlabel.bgcolor', opts.bgcolor);
    coerce('hoverlabel.bordercolor', opts.bordercolor);
    coerce('hoverlabel.namelength', opts.namelength);
    Lib.coerceFont(coerce, 'hoverlabel.font', opts.font);
};

},{"../../lib":694}],609:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function(opts, extra) {
    opts = opts || {};
    extra = extra || {};

    var descPart = extra.description ? ' ' + extra.description : '';
    var keys = extra.keys || [];
    if(keys.length > 0) {
        var quotedKeys = [];
        for(var i = 0; i < keys.length; i++) {
            quotedKeys[i] = '`' + keys[i] + '`';
        }
        descPart = descPart + 'Finally, the template string has access to ';
        if(keys.length === 1) {
            descPart = 'variable ' + quotedKeys[0];
        } else {
            descPart = 'variables ' + quotedKeys.slice(0, -1).join(', ') + ' and ' + quotedKeys.slice(-1) + '.';
        }
    }

    var hovertemplate = {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        editType: 'none',
        
    };

    return hovertemplate;
};

},{}],610:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var Lib = _dereq_('../../lib');
var dragElement = _dereq_('../dragelement');
var helpers = _dereq_('./helpers');
var layoutAttributes = _dereq_('./layout_attributes');
var hoverModule = _dereq_('./hover');

module.exports = {
    moduleType: 'component',
    name: 'fx',

    constants: _dereq_('./constants'),
    schema: {
        layout: layoutAttributes
    },

    attributes: _dereq_('./attributes'),
    layoutAttributes: layoutAttributes,

    supplyLayoutGlobalDefaults: _dereq_('./layout_global_defaults'),
    supplyDefaults: _dereq_('./defaults'),
    supplyLayoutDefaults: _dereq_('./layout_defaults'),

    calc: _dereq_('./calc'),

    getDistanceFunction: helpers.getDistanceFunction,
    getClosest: helpers.getClosest,
    inbox: helpers.inbox,
    quadrature: helpers.quadrature,
    appendArrayPointValue: helpers.appendArrayPointValue,

    castHoverOption: castHoverOption,
    castHoverinfo: castHoverinfo,

    hover: hoverModule.hover,
    unhover: dragElement.unhover,

    loneHover: hoverModule.loneHover,
    multiHovers: hoverModule.multiHovers,
    loneUnhover: loneUnhover,

    click: _dereq_('./click')
};

function loneUnhover(containerOrSelection) {
    // duck type whether the arg is a d3 selection because ie9 doesn't
    // handle instanceof like modern browsers do.
    var selection = Lib.isD3Selection(containerOrSelection) ?
            containerOrSelection :
            d3.select(containerOrSelection);

    selection.selectAll('g.hovertext').remove();
    selection.selectAll('.spikeline').remove();
}

// helpers for traces that use Fx.loneHover

function castHoverOption(trace, ptNumber, attr) {
    return Lib.castOption(trace, ptNumber, 'hoverlabel.' + attr);
}

function castHoverinfo(trace, fullLayout, ptNumber) {
    function _coerce(val) {
        return Lib.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout);
    }

    return Lib.castOption(trace, ptNumber, 'hoverinfo', _coerce);
}

},{"../../lib":694,"../dragelement":589,"./attributes":601,"./calc":602,"./click":603,"./constants":604,"./defaults":605,"./helpers":606,"./hover":607,"./layout_attributes":611,"./layout_defaults":612,"./layout_global_defaults":613,"d3":149}],611:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var constants = _dereq_('./constants');

var fontAttrs = _dereq_('../../plots/font_attributes')({
    editType: 'none',
    
});
fontAttrs.family.dflt = constants.HOVERFONT;
fontAttrs.size.dflt = constants.HOVERFONTSIZE;

module.exports = {
    clickmode: {
        valType: 'flaglist',
        
        flags: ['event', 'select'],
        dflt: 'event',
        editType: 'plot',
        extras: ['none'],
        
    },
    dragmode: {
        valType: 'enumerated',
        
        values: ['zoom', 'pan', 'select', 'lasso', 'orbit', 'turntable', false],
        dflt: 'zoom',
        editType: 'modebar',
        
    },
    hovermode: {
        valType: 'enumerated',
        
        values: ['x', 'y', 'closest', false],
        editType: 'modebar',
        
    },
    hoverdistance: {
        valType: 'integer',
        min: -1,
        dflt: 20,
        
        editType: 'none',
        
    },
    spikedistance: {
        valType: 'integer',
        min: -1,
        dflt: 20,
        
        editType: 'none',
        
    },
    hoverlabel: {
        bgcolor: {
            valType: 'color',
            
            editType: 'none',
            
        },
        bordercolor: {
            valType: 'color',
            
            editType: 'none',
            
        },
        font: fontAttrs,
        namelength: {
            valType: 'integer',
            min: -1,
            dflt: 15,
            
            editType: 'none',
            
        },
        editType: 'none'
    },
    selectdirection: {
        valType: 'enumerated',
        
        values: ['h', 'v', 'd', 'any'],
        dflt: 'any',
        
        editType: 'none'
    }
};

},{"../../plots/font_attributes":769,"./constants":604}],612:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var layoutAttributes = _dereq_('./layout_attributes');

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
    function coerce(attr, dflt) {
        return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
    }

    var clickmode = coerce('clickmode');

    var dragMode = coerce('dragmode');
    if(dragMode === 'select') coerce('selectdirection');

    var hovermodeDflt;
    if(layoutOut._has('cartesian')) {
        if(clickmode.indexOf('select') > -1) {
            hovermodeDflt = 'closest';
        } else {
            // flag for 'horizontal' plots:
            // determines the state of the mode bar 'compare' hovermode button
            layoutOut._isHoriz = isHoriz(fullData);
            hovermodeDflt = layoutOut._isHoriz ? 'y' : 'x';
        }
    }
    else hovermodeDflt = 'closest';

    var hoverMode = coerce('hovermode', hovermodeDflt);
    if(hoverMode) {
        coerce('hoverdistance');
        coerce('spikedistance');
    }

    // if only mapbox or geo subplots is present on graph,
    // reset 'zoom' dragmode to 'pan' until 'zoom' is implemented,
    // so that the correct modebar button is active
    var hasMapbox = layoutOut._has('mapbox');
    var hasGeo = layoutOut._has('geo');
    var len = layoutOut._basePlotModules.length;

    if(layoutOut.dragmode === 'zoom' && (
        ((hasMapbox || hasGeo) && len === 1) ||
        (hasMapbox && hasGeo && len === 2)
    )) {
        layoutOut.dragmode = 'pan';
    }
};

function isHoriz(fullData) {
    var out = true;

    for(var i = 0; i < fullData.length; i++) {
        var trace = fullData[i];

        if(trace.orientation !== 'h') {
            out = false;
            break;
        }
    }

    return out;
}

},{"../../lib":694,"./layout_attributes":611}],613:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var handleHoverLabelDefaults = _dereq_('./hoverlabel_defaults');
var layoutAttributes = _dereq_('./layout_attributes');

module.exports = function supplyLayoutGlobalDefaults(layoutIn, layoutOut) {
    function coerce(attr, dflt) {
        return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
    }

    handleHoverLabelDefaults(layoutIn, layoutOut, coerce);
};

},{"../../lib":694,"./hoverlabel_defaults":608,"./layout_attributes":611}],614:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var counterRegex = _dereq_('../../lib/regex').counter;
var domainAttrs = _dereq_('../../plots/domain').attributes;
var cartesianIdRegex = _dereq_('../../plots/cartesian/constants').idRegex;
var Template = _dereq_('../../plot_api/plot_template');

var gridAttrs = {
    rows: {
        valType: 'integer',
        min: 1,
        
        editType: 'plot',
        
    },
    roworder: {
        valType: 'enumerated',
        values: ['top to bottom', 'bottom to top'],
        dflt: 'top to bottom',
        
        editType: 'plot',
        
    },
    columns: {
        valType: 'integer',
        min: 1,
        
        editType: 'plot',
        
    },
    subplots: {
        valType: 'info_array',
        freeLength: true,
        dimensions: 2,
        items: {valType: 'enumerated', values: [counterRegex('xy').toString(), ''], editType: 'plot'},
        
        editType: 'plot',
        
    },
    xaxes: {
        valType: 'info_array',
        freeLength: true,
        items: {valType: 'enumerated', values: [cartesianIdRegex.x.toString(), ''], editType: 'plot'},
        
        editType: 'plot',
        
    },
    yaxes: {
        valType: 'info_array',
        freeLength: true,
        items: {valType: 'enumerated', values: [cartesianIdRegex.y.toString(), ''], editType: 'plot'},
        
        editType: 'plot',
        
    },
    pattern: {
        valType: 'enumerated',
        values: ['independent', 'coupled'],
        dflt: 'coupled',
        
        editType: 'plot',
        
    },
    xgap: {
        valType: 'number',
        min: 0,
        max: 1,
        
        editType: 'plot',
        
    },
    ygap: {
        valType: 'number',
        min: 0,
        max: 1,
        
        editType: 'plot',
        
    },
    domain: domainAttrs({name: 'grid', editType: 'plot', noGridCell: true}, {
        
    }),
    xside: {
        valType: 'enumerated',
        values: ['bottom', 'bottom plot', 'top plot', 'top'],
        dflt: 'bottom plot',
        
        editType: 'plot',
        
    },
    yside: {
        valType: 'enumerated',
        values: ['left', 'left plot', 'right plot', 'right'],
        dflt: 'left plot',
        
        editType: 'plot',
        
    },
    editType: 'plot'
};

function getAxes(layout, grid, axLetter) {
    var gridVal = grid[axLetter + 'axes'];
    var splomVal = Object.keys((layout._splomAxes || {})[axLetter] || {});

    if(Array.isArray(gridVal)) return gridVal;
    if(splomVal.length) return splomVal;
}

// the shape of the grid - this needs to be done BEFORE supplyDataDefaults
// so that non-subplot traces can place themselves in the grid
function sizeDefaults(layoutIn, layoutOut) {
    var gridIn = layoutIn.grid || {};
    var xAxes = getAxes(layoutOut, gridIn, 'x');
    var yAxes = getAxes(layoutOut, gridIn, 'y');

    if(!layoutIn.grid && !xAxes && !yAxes) return;

    var hasSubplotGrid = Array.isArray(gridIn.subplots) && Array.isArray(gridIn.subplots[0]);
    var hasXaxes = Array.isArray(xAxes);
    var hasYaxes = Array.isArray(yAxes);
    var isSplomGenerated = (
        hasXaxes && xAxes !== gridIn.xaxes &&
        hasYaxes && yAxes !== gridIn.yaxes
    );

    var dfltRows, dfltColumns;

    if(hasSubplotGrid) {
        dfltRows = gridIn.subplots.length;
        dfltColumns = gridIn.subplots[0].length;
    }
    else {
        if(hasYaxes) dfltRows = yAxes.length;
        if(hasXaxes) dfltColumns = xAxes.length;
    }

    var gridOut = Template.newContainer(layoutOut, 'grid');

    function coerce(attr, dflt) {
        return Lib.coerce(gridIn, gridOut, gridAttrs, attr, dflt);
    }

    var rows = coerce('rows', dfltRows);
    var columns = coerce('columns', dfltColumns);

    if(!(rows * columns > 1)) {
        delete layoutOut.grid;
        return;
    }

    if(!hasSubplotGrid && !hasXaxes && !hasYaxes) {
        var useDefaultSubplots = coerce('pattern') === 'independent';
        if(useDefaultSubplots) hasSubplotGrid = true;
    }
    gridOut._hasSubplotGrid = hasSubplotGrid;

    var rowOrder = coerce('roworder');
    var reversed = rowOrder === 'top to bottom';

    var dfltGapX = hasSubplotGrid ? 0.2 : 0.1;
    var dfltGapY = hasSubplotGrid ? 0.3 : 0.1;

    var dfltSideX, dfltSideY;
    if(isSplomGenerated && layoutOut._splomGridDflt) {
        dfltSideX = layoutOut._splomGridDflt.xside;
        dfltSideY = layoutOut._splomGridDflt.yside;
    }

    gridOut._domains = {
        x: fillGridPositions('x', coerce, dfltGapX, dfltSideX, columns),
        y: fillGridPositions('y', coerce, dfltGapY, dfltSideY, rows, reversed)
    };
}

// coerce x or y sizing attributes and return an array of domains for this direction
function fillGridPositions(axLetter, coerce, dfltGap, dfltSide, len, reversed) {
    var dirGap = coerce(axLetter + 'gap', dfltGap);
    var domain = coerce('domain.' + axLetter);
    coerce(axLetter + 'side', dfltSide);

    var out = new Array(len);
    var start = domain[0];
    var step = (domain[1] - start) / (len - dirGap);
    var cellDomain = step * (1 - dirGap);
    for(var i = 0; i < len; i++) {
        var cellStart = start + step * i;
        out[reversed ? (len - 1 - i) : i] = [cellStart, cellStart + cellDomain];
    }
    return out;
}

// the (cartesian) contents of the grid - this needs to happen AFTER supplyDataDefaults
// so that we know what cartesian subplots are available
function contentDefaults(layoutIn, layoutOut) {
    var gridOut = layoutOut.grid;
    // make sure we got to the end of handleGridSizing
    if(!gridOut || !gridOut._domains) return;

    var gridIn = layoutIn.grid || {};
    var subplots = layoutOut._subplots;
    var hasSubplotGrid = gridOut._hasSubplotGrid;
    var rows = gridOut.rows;
    var columns = gridOut.columns;
    var useDefaultSubplots = gridOut.pattern === 'independent';

    var i, j, xId, yId, subplotId, subplotsOut, yPos;

    var axisMap = gridOut._axisMap = {};

    if(hasSubplotGrid) {
        var subplotsIn = gridIn.subplots || [];
        subplotsOut = gridOut.subplots = new Array(rows);
        var index = 1;

        for(i = 0; i < rows; i++) {
            var rowOut = subplotsOut[i] = new Array(columns);
            var rowIn = subplotsIn[i] || [];
            for(j = 0; j < columns; j++) {
                if(useDefaultSubplots) {
                    subplotId = (index === 1) ? 'xy' : ('x' + index + 'y' + index);
                    index++;
                }
                else subplotId = rowIn[j];

                rowOut[j] = '';

                if(subplots.cartesian.indexOf(subplotId) !== -1) {
                    yPos = subplotId.indexOf('y');
                    xId = subplotId.slice(0, yPos);
                    yId = subplotId.slice(yPos);
                    if((axisMap[xId] !== undefined && axisMap[xId] !== j) ||
                        (axisMap[yId] !== undefined && axisMap[yId] !== i)
                    ) {
                        continue;
                    }

                    rowOut[j] = subplotId;
                    axisMap[xId] = j;
                    axisMap[yId] = i;
                }
            }
        }
    }
    else {
        var xAxes = getAxes(layoutOut, gridIn, 'x');
        var yAxes = getAxes(layoutOut, gridIn, 'y');
        gridOut.xaxes = fillGridAxes(xAxes, subplots.xaxis, columns, axisMap, 'x');
        gridOut.yaxes = fillGridAxes(yAxes, subplots.yaxis, rows, axisMap, 'y');
    }

    var anchors = gridOut._anchors = {};
    var reversed = gridOut.roworder === 'top to bottom';

    for(var axisId in axisMap) {
        var axLetter = axisId.charAt(0);
        var side = gridOut[axLetter + 'side'];

        var i0, inc, iFinal;

        if(side.length < 8) {
            // grid edge -  ie not "* plot" - make these as free axes
            // since we're not guaranteed to have a subplot there at all
            anchors[axisId] = 'free';
        }
        else if(axLetter === 'x') {
            if((side.charAt(0) === 't') === reversed) {
                i0 = 0;
                inc = 1;
                iFinal = rows;
            }
            else {
                i0 = rows - 1;
                inc = -1;
                iFinal = -1;
            }
            if(hasSubplotGrid) {
                var column = axisMap[axisId];
                for(i = i0; i !== iFinal; i += inc) {
                    subplotId = subplotsOut[i][column];
                    if(!subplotId) continue;
                    yPos = subplotId.indexOf('y');
                    if(subplotId.slice(0, yPos) === axisId) {
                        anchors[axisId] = subplotId.slice(yPos);
                        break;
                    }
                }
            }
            else {
                for(i = i0; i !== iFinal; i += inc) {
                    yId = gridOut.yaxes[i];
                    if(subplots.cartesian.indexOf(axisId + yId) !== -1) {
                        anchors[axisId] = yId;
                        break;
                    }
                }
            }
        }
        else {
            if((side.charAt(0) === 'l')) {
                i0 = 0;
                inc = 1;
                iFinal = columns;
            }
            else {
                i0 = columns - 1;
                inc = -1;
                iFinal = -1;
            }
            if(hasSubplotGrid) {
                var row = axisMap[axisId];
                for(i = i0; i !== iFinal; i += inc) {
                    subplotId = subplotsOut[row][i];
                    if(!subplotId) continue;
                    yPos = subplotId.indexOf('y');
                    if(subplotId.slice(yPos) === axisId) {
                        anchors[axisId] = subplotId.slice(0, yPos);
                        break;
                    }
                }
            }
            else {
                for(i = i0; i !== iFinal; i += inc) {
                    xId = gridOut.xaxes[i];
                    if(subplots.cartesian.indexOf(xId + axisId) !== -1) {
                        anchors[axisId] = xId;
                        break;
                    }
                }
            }
        }
    }
}

function fillGridAxes(axesIn, axesAllowed, len, axisMap, axLetter) {
    var out = new Array(len);
    var i;

    function fillOneAxis(i, axisId) {
        if(axesAllowed.indexOf(axisId) !== -1 && axisMap[axisId] === undefined) {
            out[i] = axisId;
            axisMap[axisId] = i;
        }
        else out[i] = '';
    }

    if(Array.isArray(axesIn)) {
        for(i = 0; i < len; i++) {
            fillOneAxis(i, axesIn[i]);
        }
    }
    else {
        // default axis list is the first `len` axis ids
        fillOneAxis(0, axLetter);
        for(i = 1; i < len; i++) {
            fillOneAxis(i, axLetter + (i + 1));
        }
    }

    return out;
}

module.exports = {
    moduleType: 'component',
    name: 'grid',

    schema: {
        layout: {grid: gridAttrs}
    },

    layoutAttributes: gridAttrs,
    sizeDefaults: sizeDefaults,
    contentDefaults: contentDefaults
};

},{"../../lib":694,"../../lib/regex":710,"../../plot_api/plot_template":732,"../../plots/cartesian/constants":748,"../../plots/domain":768}],615:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var cartesianConstants = _dereq_('../../plots/cartesian/constants');
var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;


module.exports = templatedArray('image', {
    visible: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'arraydraw',
        
    },

    source: {
        valType: 'string',
        
        editType: 'arraydraw',
        
    },

    layer: {
        valType: 'enumerated',
        values: ['below', 'above'],
        dflt: 'above',
        
        editType: 'arraydraw',
        
    },

    sizex: {
        valType: 'number',
        
        dflt: 0,
        editType: 'arraydraw',
        
    },

    sizey: {
        valType: 'number',
        
        dflt: 0,
        editType: 'arraydraw',
        
    },

    sizing: {
        valType: 'enumerated',
        values: ['fill', 'contain', 'stretch'],
        dflt: 'contain',
        
        editType: 'arraydraw',
        
    },

    opacity: {
        valType: 'number',
        
        min: 0,
        max: 1,
        dflt: 1,
        editType: 'arraydraw',
        
    },

    x: {
        valType: 'any',
        
        dflt: 0,
        editType: 'arraydraw',
        
    },

    y: {
        valType: 'any',
        
        dflt: 0,
        editType: 'arraydraw',
        
    },

    xanchor: {
        valType: 'enumerated',
        values: ['left', 'center', 'right'],
        dflt: 'left',
        
        editType: 'arraydraw',
        
    },

    yanchor: {
        valType: 'enumerated',
        values: ['top', 'middle', 'bottom'],
        dflt: 'top',
        
        editType: 'arraydraw',
        
    },

    xref: {
        valType: 'enumerated',
        values: [
            'paper',
            cartesianConstants.idRegex.x.toString()
        ],
        dflt: 'paper',
        
        editType: 'arraydraw',
        
    },

    yref: {
        valType: 'enumerated',
        values: [
            'paper',
            cartesianConstants.idRegex.y.toString()
        ],
        dflt: 'paper',
        
        editType: 'arraydraw',
        
    },
    editType: 'arraydraw'
});

},{"../../plot_api/plot_template":732,"../../plots/cartesian/constants":748}],616:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var toLogRange = _dereq_('../../lib/to_log_range');

/*
 * convertCoords: when converting an axis between log and linear
 * you need to alter any images on that axis to keep them
 * pointing at the same data point.
 * In v2.0 this will become obsolete (or perhaps size will still need conversion?)
 * we convert size by declaring that the maximum extent *in data units* should be
 * the same, assuming the image is anchored by its center (could remove that restriction
 * if we think it's important) even though the actual left and right values will not be
 * quite the same since the scale becomes nonlinear (and central anchor means the pixel
 * center of the image, not the data units center)
 *
 * gd: the plot div
 * ax: the axis being changed
 * newType: the type it's getting
 * doExtra: function(attr, val) from inside relayout that sets the attribute.
 *     Use this to make the changes as it's aware if any other changes in the
 *     same relayout call should override this conversion.
 */
module.exports = function convertCoords(gd, ax, newType, doExtra) {
    ax = ax || {};

    var toLog = (newType === 'log') && (ax.type === 'linear');
    var fromLog = (newType === 'linear') && (ax.type === 'log');

    if(!(toLog || fromLog)) return;

    var images = gd._fullLayout.images;
    var axLetter = ax._id.charAt(0);
    var image;
    var attrPrefix;

    for(var i = 0; i < images.length; i++) {
        image = images[i];
        attrPrefix = 'images[' + i + '].';

        if(image[axLetter + 'ref'] === ax._id) {
            var currentPos = image[axLetter];
            var currentSize = image['size' + axLetter];
            var newPos = null;
            var newSize = null;

            if(toLog) {
                newPos = toLogRange(currentPos, ax.range);

                // this is the inverse of the conversion we do in fromLog below
                // so that the conversion is reversible (notice the fromLog conversion
                // is like sinh, and this one looks like arcsinh)
                var dx = currentSize / Math.pow(10, newPos) / 2;
                newSize = 2 * Math.log(dx + Math.sqrt(1 + dx * dx)) / Math.LN10;
            }
            else {
                newPos = Math.pow(10, currentPos);
                newSize = newPos * (Math.pow(10, currentSize / 2) - Math.pow(10, -currentSize / 2));
            }

            // if conversion failed, delete the value so it can get a default later on
            if(!isNumeric(newPos)) {
                newPos = null;
                newSize = null;
            }
            else if(!isNumeric(newSize)) newSize = null;

            doExtra(attrPrefix + axLetter, newPos);
            doExtra(attrPrefix + 'size' + axLetter, newSize);
        }
    }
};

},{"../../lib/to_log_range":720,"fast-isnumeric":215}],617:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');
var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');

var attributes = _dereq_('./attributes');
var name = 'images';

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
    var opts = {
        name: name,
        handleItemDefaults: imageDefaults
    };

    handleArrayContainerDefaults(layoutIn, layoutOut, opts);
};


function imageDefaults(imageIn, imageOut, fullLayout) {

    function coerce(attr, dflt) {
        return Lib.coerce(imageIn, imageOut, attributes, attr, dflt);
    }

    var source = coerce('source');
    var visible = coerce('visible', !!source);

    if(!visible) return imageOut;

    coerce('layer');
    coerce('xanchor');
    coerce('yanchor');
    coerce('sizex');
    coerce('sizey');
    coerce('sizing');
    coerce('opacity');

    var gdMock = { _fullLayout: fullLayout };
    var axLetters = ['x', 'y'];

    for(var i = 0; i < 2; i++) {
        // 'paper' is the fallback axref
        var axLetter = axLetters[i];
        var axRef = Axes.coerceRef(imageIn, imageOut, gdMock, axLetter, 'paper');

        if(axRef !== 'paper') {
            var ax = Axes.getFromId(gdMock, axRef);
            ax._imgIndices.push(imageOut._index);
        }

        Axes.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0);
    }

    return imageOut;
}

},{"../../lib":694,"../../plots/array_container_defaults":738,"../../plots/cartesian/axes":742,"./attributes":615}],618:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var Drawing = _dereq_('../drawing');
var Axes = _dereq_('../../plots/cartesian/axes');
var xmlnsNamespaces = _dereq_('../../constants/xmlns_namespaces');

module.exports = function draw(gd) {
    var fullLayout = gd._fullLayout;
    var imageDataAbove = [];
    var imageDataSubplot = {};
    var imageDataBelow = [];
    var subplot;
    var i;

    // Sort into top, subplot, and bottom layers
    for(i = 0; i < fullLayout.images.length; i++) {
        var img = fullLayout.images[i];

        if(img.visible) {
            if(img.layer === 'below' && img.xref !== 'paper' && img.yref !== 'paper') {
                subplot = img.xref + img.yref;

                var plotinfo = fullLayout._plots[subplot];

                if(!plotinfo) {
                    // Fall back to _imageLowerLayer in case the requested subplot doesn't exist.
                    // This can happen if you reference the image to an x / y axis combination
                    // that doesn't have any data on it (and layer is below)
                    imageDataBelow.push(img);
                    continue;
                }

                if(plotinfo.mainplot) {
                    subplot = plotinfo.mainplot.id;
                }

                if(!imageDataSubplot[subplot]) {
                    imageDataSubplot[subplot] = [];
                }
                imageDataSubplot[subplot].push(img);
            } else if(img.layer === 'above') {
                imageDataAbove.push(img);
            } else {
                imageDataBelow.push(img);
            }
        }
    }


    var anchors = {
        x: {
            left: { sizing: 'xMin', offset: 0 },
            center: { sizing: 'xMid', offset: -1 / 2 },
            right: { sizing: 'xMax', offset: -1 }
        },
        y: {
            top: { sizing: 'YMin', offset: 0 },
            middle: { sizing: 'YMid', offset: -1 / 2 },
            bottom: { sizing: 'YMax', offset: -1 }
        }
    };


    // Images must be converted to dataURL's for exporting.
    function setImage(d) {
        var thisImage = d3.select(this);

        if(this.img && this.img.src === d.source) {
            return;
        }

        thisImage.attr('xmlns', xmlnsNamespaces.svg);

        var imagePromise = new Promise(function(resolve) {

            var img = new Image();
            this.img = img;

            // If not set, a `tainted canvas` error is thrown
            img.setAttribute('crossOrigin', 'anonymous');
            img.onerror = errorHandler;
            img.onload = function() {
                var canvas = document.createElement('canvas');
                canvas.width = this.width;
                canvas.height = this.height;

                var ctx = canvas.getContext('2d');
                ctx.drawImage(this, 0, 0);

                var dataURL = canvas.toDataURL('image/png');

                thisImage.attr('xlink:href', dataURL);

                // resolve promise in onload handler instead of on 'load' to support IE11
                // see https://github.com/plotly/plotly.js/issues/1685
                // for more details
                resolve();
            };


            thisImage.on('error', errorHandler);

            img.src = d.source;

            function errorHandler() {
                thisImage.remove();
                resolve();
            }
        }.bind(this));

        gd._promises.push(imagePromise);
    }

    function applyAttributes(d) {
        var thisImage = d3.select(this);

        // Axes if specified
        var xa = Axes.getFromId(gd, d.xref);
        var ya = Axes.getFromId(gd, d.yref);

        var size = fullLayout._size;
        var width = xa ? Math.abs(xa.l2p(d.sizex) - xa.l2p(0)) : d.sizex * size.w;
        var height = ya ? Math.abs(ya.l2p(d.sizey) - ya.l2p(0)) : d.sizey * size.h;

        // Offsets for anchor positioning
        var xOffset = width * anchors.x[d.xanchor].offset;
        var yOffset = height * anchors.y[d.yanchor].offset;

        var sizing = anchors.x[d.xanchor].sizing + anchors.y[d.yanchor].sizing;

        // Final positions
        var xPos = (xa ? xa.r2p(d.x) + xa._offset : d.x * size.w + size.l) + xOffset;
        var yPos = (ya ? ya.r2p(d.y) + ya._offset : size.h - d.y * size.h + size.t) + yOffset;

        // Construct the proper aspectRatio attribute
        switch(d.sizing) {
            case 'fill':
                sizing += ' slice';
                break;

            case 'stretch':
                sizing = 'none';
                break;
        }

        thisImage.attr({
            x: xPos,
            y: yPos,
            width: width,
            height: height,
            preserveAspectRatio: sizing,
            opacity: d.opacity
        });


        // Set proper clipping on images
        var xId = xa ? xa._id : '';
        var yId = ya ? ya._id : '';
        var clipAxes = xId + yId;

        Drawing.setClipUrl(
            thisImage,
            clipAxes ? ('clip' + fullLayout._uid + clipAxes) : null,
            gd
        );
    }

    var imagesBelow = fullLayout._imageLowerLayer.selectAll('image')
        .data(imageDataBelow);
    var imagesAbove = fullLayout._imageUpperLayer.selectAll('image')
        .data(imageDataAbove);

    imagesBelow.enter().append('image');
    imagesAbove.enter().append('image');

    imagesBelow.exit().remove();
    imagesAbove.exit().remove();

    imagesBelow.each(function(d) {
        setImage.bind(this)(d);
        applyAttributes.bind(this)(d);
    });
    imagesAbove.each(function(d) {
        setImage.bind(this)(d);
        applyAttributes.bind(this)(d);
    });

    var allSubplots = Object.keys(fullLayout._plots);
    for(i = 0; i < allSubplots.length; i++) {
        subplot = allSubplots[i];
        var subplotObj = fullLayout._plots[subplot];

        // filter out overlaid plots (which havd their images on the main plot)
        // and gl2d plots (which don't support below images, at least not yet)
        if(!subplotObj.imagelayer) continue;

        var imagesOnSubplot = subplotObj.imagelayer.selectAll('image')
            // even if there are no images on this subplot, we need to run
            // enter and exit in case there were previously
            .data(imageDataSubplot[subplot] || []);

        imagesOnSubplot.enter().append('image');
        imagesOnSubplot.exit().remove();

        imagesOnSubplot.each(function(d) {
            setImage.bind(this)(d);
            applyAttributes.bind(this)(d);
        });
    }
};

},{"../../constants/xmlns_namespaces":672,"../../plots/cartesian/axes":742,"../drawing":592,"d3":149}],619:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'component',
    name: 'images',

    layoutAttributes: _dereq_('./attributes'),
    supplyLayoutDefaults: _dereq_('./defaults'),
    includeBasePlot: _dereq_('../../plots/cartesian/include_components')('images'),

    draw: _dereq_('./draw'),

    convertCoords: _dereq_('./convert_coords')
};

},{"../../plots/cartesian/include_components":753,"./attributes":615,"./convert_coords":616,"./defaults":617,"./draw":618}],620:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = _dereq_('../../plots/font_attributes');
var colorAttrs = _dereq_('../color/attributes');


module.exports = {
    bgcolor: {
        valType: 'color',
        
        editType: 'legend',
        
    },
    bordercolor: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'legend',
        
    },
    borderwidth: {
        valType: 'number',
        min: 0,
        dflt: 0,
        
        editType: 'legend',
        
    },
    font: fontAttrs({
        editType: 'legend',
        
    }),
    orientation: {
        valType: 'enumerated',
        values: ['v', 'h'],
        dflt: 'v',
        
        editType: 'legend',
        
    },
    traceorder: {
        valType: 'flaglist',
        flags: ['reversed', 'grouped'],
        extras: ['normal'],
        
        editType: 'legend',
        
    },
    tracegroupgap: {
        valType: 'number',
        min: 0,
        dflt: 10,
        
        editType: 'legend',
        
    },
    x: {
        valType: 'number',
        min: -2,
        max: 3,
        dflt: 1.02,
        
        editType: 'legend',
        
    },
    xanchor: {
        valType: 'enumerated',
        values: ['auto', 'left', 'center', 'right'],
        dflt: 'left',
        
        editType: 'legend',
        
    },
    y: {
        valType: 'number',
        min: -2,
        max: 3,
        dflt: 1,
        
        editType: 'legend',
        
    },
    yanchor: {
        valType: 'enumerated',
        values: ['auto', 'top', 'middle', 'bottom'],
        dflt: 'auto',
        
        editType: 'legend',
        
    },
    uirevision: {
        valType: 'any',
        
        editType: 'none',
        
    },
    valign: {
        valType: 'enumerated',
        values: ['top', 'middle', 'bottom'],
        dflt: 'middle',
        
        editType: 'legend',
        
    },
    editType: 'legend'
};

},{"../../plots/font_attributes":769,"../color/attributes":570}],621:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    scrollBarWidth: 6,
    scrollBarMinHeight: 20,
    scrollBarColor: '#808BA4',
    scrollBarMargin: 4,
    textOffsetX: 40
};

},{}],622:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Template = _dereq_('../../plot_api/plot_template');

var attributes = _dereq_('./attributes');
var basePlotLayoutAttributes = _dereq_('../../plots/layout_attributes');
var helpers = _dereq_('./helpers');


module.exports = function legendDefaults(layoutIn, layoutOut, fullData) {
    var containerIn = layoutIn.legend || {};

    var legendTraceCount = 0;
    var legendReallyHasATrace = false;
    var defaultOrder = 'normal';

    var defaultX, defaultY, defaultXAnchor, defaultYAnchor;

    for(var i = 0; i < fullData.length; i++) {
        var trace = fullData[i];

        if(!trace.visible) continue;

        // Note that we explicitly count any trace that is either shown or
        // *would* be shown by default, toward the two traces you need to
        // ensure the legend is shown by default, because this can still help
        // disambiguate.
        if(trace.showlegend || trace._dfltShowLegend) {
            legendTraceCount++;
            if(trace.showlegend) {
                legendReallyHasATrace = true;
                // Always show the legend by default if there's a pie,
                // or if there's only one trace but it's explicitly shown
                if(Registry.traceIs(trace, 'pie') ||
                    trace._input.showlegend === true
                ) {
                    legendTraceCount++;
                }
            }
        }

        if((Registry.traceIs(trace, 'bar') && layoutOut.barmode === 'stack') ||
                ['tonextx', 'tonexty'].indexOf(trace.fill) !== -1) {
            defaultOrder = helpers.isGrouped({traceorder: defaultOrder}) ?
                'grouped+reversed' : 'reversed';
        }

        if(trace.legendgroup !== undefined && trace.legendgroup !== '') {
            defaultOrder = helpers.isReversed({traceorder: defaultOrder}) ?
                'reversed+grouped' : 'grouped';
        }
    }

    var showLegend = Lib.coerce(layoutIn, layoutOut,
        basePlotLayoutAttributes, 'showlegend',
        legendReallyHasATrace && legendTraceCount > 1);

    if(showLegend === false && !containerIn.uirevision) return;

    var containerOut = Template.newContainer(layoutOut, 'legend');

    function coerce(attr, dflt) {
        return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
    }

    coerce('uirevision', layoutOut.uirevision);

    if(showLegend === false) return;

    coerce('bgcolor', layoutOut.paper_bgcolor);
    coerce('bordercolor');
    coerce('borderwidth');
    Lib.coerceFont(coerce, 'font', layoutOut.font);

    coerce('orientation');
    if(containerOut.orientation === 'h') {
        var xaxis = layoutIn.xaxis;
        if(Registry.getComponentMethod('rangeslider', 'isVisible')(xaxis)) {
            defaultX = 0;
            defaultXAnchor = 'left';
            defaultY = 1.1;
            defaultYAnchor = 'bottom';
        }
        else {
            defaultX = 0;
            defaultXAnchor = 'left';
            defaultY = -0.1;
            defaultYAnchor = 'top';
        }
    }

    coerce('traceorder', defaultOrder);
    if(helpers.isGrouped(layoutOut.legend)) coerce('tracegroupgap');

    coerce('x', defaultX);
    coerce('xanchor', defaultXAnchor);
    coerce('y', defaultY);
    coerce('yanchor', defaultYAnchor);
    coerce('valign');
    Lib.noneOrAll(containerIn, containerOut, ['x', 'y']);
};

},{"../../lib":694,"../../plot_api/plot_template":732,"../../plots/layout_attributes":797,"../../registry":825,"./attributes":620,"./helpers":626}],623:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Lib = _dereq_('../../lib');
var Plots = _dereq_('../../plots/plots');
var Registry = _dereq_('../../registry');
var Events = _dereq_('../../lib/events');
var dragElement = _dereq_('../dragelement');
var Drawing = _dereq_('../drawing');
var Color = _dereq_('../color');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var handleClick = _dereq_('./handle_click');

var constants = _dereq_('./constants');
var interactConstants = _dereq_('../../constants/interactions');
var alignmentConstants = _dereq_('../../constants/alignment');
var LINE_SPACING = alignmentConstants.LINE_SPACING;
var FROM_TL = alignmentConstants.FROM_TL;
var FROM_BR = alignmentConstants.FROM_BR;

var getLegendData = _dereq_('./get_legend_data');
var style = _dereq_('./style');
var helpers = _dereq_('./helpers');

var DBLCLICKDELAY = interactConstants.DBLCLICKDELAY;

module.exports = function draw(gd) {
    var fullLayout = gd._fullLayout;
    var clipId = 'legend' + fullLayout._uid;

    if(!fullLayout._infolayer || !gd.calcdata) return;

    if(!gd._legendMouseDownTime) gd._legendMouseDownTime = 0;

    var opts = fullLayout.legend;
    var legendData = fullLayout.showlegend && getLegendData(gd.calcdata, opts);
    var hiddenSlices = fullLayout.hiddenlabels || [];

    if(!fullLayout.showlegend || !legendData.length) {
        fullLayout._infolayer.selectAll('.legend').remove();
        fullLayout._topdefs.select('#' + clipId).remove();

        Plots.autoMargin(gd, 'legend');
        return;
    }

    var maxLength = 0;
    for(var i = 0; i < legendData.length; i++) {
        for(var j = 0; j < legendData[i].length; j++) {
            var item = legendData[i][j][0];
            var trace = item.trace;
            var isPie = Registry.traceIs(trace, 'pie');
            var name = isPie ? item.label : trace.name;
            maxLength = Math.max(maxLength, name && name.length || 0);
        }
    }

    var firstRender = false;
    var legend = Lib.ensureSingle(fullLayout._infolayer, 'g', 'legend', function(s) {
        s.attr('pointer-events', 'all');
        firstRender = true;
    });

    var clipPath = Lib.ensureSingleById(fullLayout._topdefs, 'clipPath', clipId, function(s) {
        s.append('rect');
    });

    var bg = Lib.ensureSingle(legend, 'rect', 'bg', function(s) {
        s.attr('shape-rendering', 'crispEdges');
    });

    bg.call(Color.stroke, opts.bordercolor)
        .call(Color.fill, opts.bgcolor)
        .style('stroke-width', opts.borderwidth + 'px');

    var scrollBox = Lib.ensureSingle(legend, 'g', 'scrollbox');

    var scrollBar = Lib.ensureSingle(legend, 'rect', 'scrollbar', function(s) {
        s.attr({
            rx: 20,
            ry: 3,
            width: 0,
            height: 0
        })
        .call(Color.fill, '#808BA4');
    });

    var groups = scrollBox.selectAll('g.groups')
        .data(legendData);

    groups.enter().append('g')
        .attr('class', 'groups');

    groups.exit().remove();

    var traces = groups.selectAll('g.traces')
        .data(Lib.identity);

    traces.enter().append('g').attr('class', 'traces');
    traces.exit().remove();

    traces.style('opacity', function(d) {
        var trace = d[0].trace;
        if(Registry.traceIs(trace, 'pie')) {
            return hiddenSlices.indexOf(d[0].label) !== -1 ? 0.5 : 1;
        } else {
            return trace.visible === 'legendonly' ? 0.5 : 1;
        }
    })
    .each(function() {
        d3.select(this)
            .call(drawTexts, gd, maxLength)
            .call(setupTraceToggle, gd);
    })
    .call(style, gd);

    Lib.syncOrAsync([Plots.previousPromises,
        function() {
            if(firstRender) {
                computeLegendDimensions(gd, groups, traces);
                expandMargin(gd);
            }

            // Position and size the legend
            var lxMin = 0;
            var lxMax = fullLayout.width;
            var lyMin = 0;
            var lyMax = fullLayout.height;

            computeLegendDimensions(gd, groups, traces);

            if(opts._height > lyMax) {
                // If the legend doesn't fit in the plot area,
                // do not expand the vertical margins.
                expandHorizontalMargin(gd);
            } else {
                expandMargin(gd);
            }

            // Scroll section must be executed after repositionLegend.
            // It requires the legend width, height, x and y to position the scrollbox
            // and these values are mutated in repositionLegend.
            var gs = fullLayout._size;
            var lx = gs.l + gs.w * opts.x;
            var ly = gs.t + gs.h * (1 - opts.y);

            if(Lib.isRightAnchor(opts)) {
                lx -= opts._width;
            }
            else if(Lib.isCenterAnchor(opts)) {
                lx -= opts._width / 2;
            }

            if(Lib.isBottomAnchor(opts)) {
                ly -= opts._height;
            }
            else if(Lib.isMiddleAnchor(opts)) {
                ly -= opts._height / 2;
            }

            // Make sure the legend left and right sides are visible
            var legendWidth = opts._width;
            var legendWidthMax = gs.w;

            if(legendWidth > legendWidthMax) {
                lx = gs.l;
                legendWidth = legendWidthMax;
            }
            else {
                if(lx + legendWidth > lxMax) lx = lxMax - legendWidth;
                if(lx < lxMin) lx = lxMin;
                legendWidth = Math.min(lxMax - lx, opts._width);
            }

            // Make sure the legend top and bottom are visible
            // (legends with a scroll bar are not allowed to stretch beyond the extended
            // margins)
            var legendHeight = opts._height;
            var legendHeightMax = gs.h;

            if(legendHeight > legendHeightMax) {
                ly = gs.t;
                legendHeight = legendHeightMax;
            }
            else {
                if(ly + legendHeight > lyMax) ly = lyMax - legendHeight;
                if(ly < lyMin) ly = lyMin;
                legendHeight = Math.min(lyMax - ly, opts._height);
            }

            // Set size and position of all the elements that make up a legend:
            // legend, background and border, scroll box and scroll bar
            Drawing.setTranslate(legend, lx, ly);

            // to be safe, remove previous listeners
            scrollBar.on('.drag', null);
            legend.on('wheel', null);

            if(opts._height <= legendHeight || gd._context.staticPlot) {
                // if scrollbar should not be shown.
                bg.attr({
                    width: legendWidth - opts.borderwidth,
                    height: legendHeight - opts.borderwidth,
                    x: opts.borderwidth / 2,
                    y: opts.borderwidth / 2
                });

                Drawing.setTranslate(scrollBox, 0, 0);

                clipPath.select('rect').attr({
                    width: legendWidth - 2 * opts.borderwidth,
                    height: legendHeight - 2 * opts.borderwidth,
                    x: opts.borderwidth,
                    y: opts.borderwidth
                });

                Drawing.setClipUrl(scrollBox, clipId, gd);

                Drawing.setRect(scrollBar, 0, 0, 0, 0);
                delete opts._scrollY;
            }
            else {
                var scrollBarHeight = Math.max(constants.scrollBarMinHeight,
                    legendHeight * legendHeight / opts._height);
                var scrollBarYMax = legendHeight -
                    scrollBarHeight -
                    2 * constants.scrollBarMargin;
                var scrollBoxYMax = opts._height - legendHeight;
                var scrollRatio = scrollBarYMax / scrollBoxYMax;

                var scrollBoxY = Math.min(opts._scrollY || 0, scrollBoxYMax);

                // increase the background and clip-path width
                // by the scrollbar width and margin
                bg.attr({
                    width: legendWidth -
                        2 * opts.borderwidth +
                        constants.scrollBarWidth +
                        constants.scrollBarMargin,
                    height: legendHeight - opts.borderwidth,
                    x: opts.borderwidth / 2,
                    y: opts.borderwidth / 2
                });

                clipPath.select('rect').attr({
                    width: legendWidth -
                        2 * opts.borderwidth +
                        constants.scrollBarWidth +
                        constants.scrollBarMargin,
                    height: legendHeight - 2 * opts.borderwidth,
                    x: opts.borderwidth,
                    y: opts.borderwidth + scrollBoxY
                });

                Drawing.setClipUrl(scrollBox, clipId, gd);

                scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio);

                legend.on('wheel', function() {
                    scrollBoxY = Lib.constrain(
                        opts._scrollY +
                            d3.event.deltaY / scrollBarYMax * scrollBoxYMax,
                        0, scrollBoxYMax);
                    scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio);
                    if(scrollBoxY !== 0 && scrollBoxY !== scrollBoxYMax) {
                        d3.event.preventDefault();
                    }
                });

                var eventY0, scrollBoxY0;

                var drag = d3.behavior.drag()
                .on('dragstart', function() {
                    eventY0 = d3.event.sourceEvent.clientY;
                    scrollBoxY0 = scrollBoxY;
                })
                .on('drag', function() {
                    var e = d3.event.sourceEvent;
                    if(e.buttons === 2 || e.ctrlKey) return;

                    scrollBoxY = Lib.constrain(
                        (e.clientY - eventY0) / scrollRatio + scrollBoxY0,
                        0, scrollBoxYMax);
                    scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio);
                });

                scrollBar.call(drag);
            }


            function scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio) {
                opts._scrollY = gd._fullLayout.legend._scrollY = scrollBoxY;
                Drawing.setTranslate(scrollBox, 0, -scrollBoxY);

                Drawing.setRect(
                    scrollBar,
                    legendWidth,
                    constants.scrollBarMargin + scrollBoxY * scrollRatio,
                    constants.scrollBarWidth,
                    scrollBarHeight
                );
                clipPath.select('rect').attr({
                    y: opts.borderwidth + scrollBoxY
                });
            }

            if(gd._context.edits.legendPosition) {
                var xf, yf, x0, y0;

                legend.classed('cursor-move', true);

                dragElement.init({
                    element: legend.node(),
                    gd: gd,
                    prepFn: function() {
                        var transform = Drawing.getTranslate(legend);

                        x0 = transform.x;
                        y0 = transform.y;
                    },
                    moveFn: function(dx, dy) {
                        var newX = x0 + dx;
                        var newY = y0 + dy;

                        Drawing.setTranslate(legend, newX, newY);

                        xf = dragElement.align(newX, 0, gs.l, gs.l + gs.w, opts.xanchor);
                        yf = dragElement.align(newY, 0, gs.t + gs.h, gs.t, opts.yanchor);
                    },
                    doneFn: function() {
                        if(xf !== undefined && yf !== undefined) {
                            Registry.call('_guiRelayout', gd, {'legend.x': xf, 'legend.y': yf});
                        }
                    },
                    clickFn: function(numClicks, e) {
                        var clickedTrace = fullLayout._infolayer.selectAll('g.traces').filter(function() {
                            var bbox = this.getBoundingClientRect();
                            return (
                                e.clientX >= bbox.left && e.clientX <= bbox.right &&
                                e.clientY >= bbox.top && e.clientY <= bbox.bottom
                            );
                        });
                        if(clickedTrace.size() > 0) {
                            clickOrDoubleClick(gd, legend, clickedTrace, numClicks, e);
                        }
                    }
                });
            }
        }], gd);
};

function clickOrDoubleClick(gd, legend, legendItem, numClicks, evt) {
    var trace = legendItem.data()[0][0].trace;

    var evtData = {
        event: evt,
        node: legendItem.node(),
        curveNumber: trace.index,
        expandedIndex: trace._expandedIndex,
        data: gd.data,
        layout: gd.layout,
        frames: gd._transitionData._frames,
        config: gd._context,
        fullData: gd._fullData,
        fullLayout: gd._fullLayout
    };

    if(trace._group) {
        evtData.group = trace._group;
    }
    if(trace.type === 'pie') {
        evtData.label = legendItem.datum()[0].label;
    }

    var clickVal = Events.triggerHandler(gd, 'plotly_legendclick', evtData);
    if(clickVal === false) return;

    if(numClicks === 1) {
        legend._clickTimeout = setTimeout(function() {
            handleClick(legendItem, gd, numClicks);
        }, DBLCLICKDELAY);
    }
    else if(numClicks === 2) {
        if(legend._clickTimeout) clearTimeout(legend._clickTimeout);
        gd._legendMouseDownTime = 0;

        var dblClickVal = Events.triggerHandler(gd, 'plotly_legenddoubleclick', evtData);
        if(dblClickVal !== false) handleClick(legendItem, gd, numClicks);
    }
}

function drawTexts(g, gd, maxLength) {
    var legendItem = g.data()[0][0];
    var fullLayout = gd._fullLayout;
    var trace = legendItem.trace;
    var isPie = Registry.traceIs(trace, 'pie');
    var traceIndex = trace.index;
    var name = isPie ? legendItem.label : trace.name;
    var isEditable = gd._context.edits.legendText && !isPie;

    var textEl = Lib.ensureSingle(g, 'text', 'legendtext');

    textEl.attr('text-anchor', 'start')
        .classed('user-select-none', true)
        .call(Drawing.font, fullLayout.legend.font)
        .text(isEditable ? ensureLength(name, maxLength) : name);

    svgTextUtils.positionText(textEl, constants.textOffsetX, 0);

    function textLayout(s) {
        svgTextUtils.convertToTspans(s, gd, function() {
            computeTextDimensions(g, gd);
        });
    }

    if(isEditable) {
        textEl.call(svgTextUtils.makeEditable, {gd: gd, text: name})
            .call(textLayout)
            .on('edit', function(newName) {
                this.text(ensureLength(newName, maxLength))
                    .call(textLayout);

                var fullInput = legendItem.trace._fullInput || {};
                var update = {};

                if(Registry.hasTransform(fullInput, 'groupby')) {
                    var groupbyIndices = Registry.getTransformIndices(fullInput, 'groupby');
                    var index = groupbyIndices[groupbyIndices.length - 1];

                    var kcont = Lib.keyedContainer(fullInput, 'transforms[' + index + '].styles', 'target', 'value.name');

                    kcont.set(legendItem.trace._group, newName);

                    update = kcont.constructUpdate();
                } else {
                    update.name = newName;
                }

                return Registry.call('_guiRestyle', gd, update, traceIndex);
            });
    } else {
        textLayout(textEl);
    }
}

/*
 * Make sure we have a reasonably clickable region.
 * If this string is missing or very short, pad it with spaces out to at least
 * 4 characters, up to the max length of other labels, on the assumption that
 * most characters are wider than spaces so a string of spaces will usually be
 * no wider than the real labels.
 */
function ensureLength(str, maxLength) {
    var targetLength = Math.max(4, maxLength);
    if(str && str.trim().length >= targetLength / 2) return str;
    str = str || '';
    for(var i = targetLength - str.length; i > 0; i--) str += ' ';
    return str;
}

function setupTraceToggle(g, gd) {
    var newMouseDownTime;
    var numClicks = 1;

    var traceToggle = Lib.ensureSingle(g, 'rect', 'legendtoggle', function(s) {
        s.style('cursor', 'pointer')
            .attr('pointer-events', 'all')
            .call(Color.fill, 'rgba(0,0,0,0)');
    });

    traceToggle.on('mousedown', function() {
        newMouseDownTime = (new Date()).getTime();
        if(newMouseDownTime - gd._legendMouseDownTime < DBLCLICKDELAY) {
            // in a click train
            numClicks += 1;
        }
        else {
            // new click train
            numClicks = 1;
            gd._legendMouseDownTime = newMouseDownTime;
        }
    });
    traceToggle.on('mouseup', function() {
        if(gd._dragged || gd._editing) return;
        var legend = gd._fullLayout.legend;

        if((new Date()).getTime() - gd._legendMouseDownTime > DBLCLICKDELAY) {
            numClicks = Math.max(numClicks - 1, 1);
        }

        clickOrDoubleClick(gd, legend, g, numClicks, d3.event);
    });
}

function computeTextDimensions(g, gd) {
    var legendItem = g.data()[0][0];

    if(!legendItem.trace.showlegend) {
        g.remove();
        return;
    }

    var mathjaxGroup = g.select('g[class*=math-group]');
    var mathjaxNode = mathjaxGroup.node();
    var opts = gd._fullLayout.legend;
    var lineHeight = opts.font.size * LINE_SPACING;
    var height, width;

    if(mathjaxNode) {
        var mathjaxBB = Drawing.bBox(mathjaxNode);

        height = mathjaxBB.height;
        width = mathjaxBB.width;

        Drawing.setTranslate(mathjaxGroup, 0, (height / 4));
    } else {
        var text = g.select('.legendtext');
        var textLines = svgTextUtils.lineCount(text);
        var textNode = text.node();

        height = lineHeight * textLines;
        width = textNode ? Drawing.bBox(textNode).width : 0;

        // approximation to height offset to center the font
        // to avoid getBoundingClientRect
        var textY = lineHeight * (0.3 + (1 - textLines) / 2);
        svgTextUtils.positionText(text, constants.textOffsetX, textY);
    }

    legendItem.lineHeight = lineHeight;
    legendItem.height = Math.max(height, 16) + 3;
    legendItem.width = width;
}

function computeLegendDimensions(gd, groups, traces) {
    var fullLayout = gd._fullLayout;
    var opts = fullLayout.legend;
    var borderwidth = opts.borderwidth;
    var isGrouped = helpers.isGrouped(opts);

    var extraWidth = 0;

    opts._width = 0;
    opts._height = 0;

    if(helpers.isVertical(opts)) {
        if(isGrouped) {
            groups.each(function(d, i) {
                Drawing.setTranslate(this, 0, i * opts.tracegroupgap);
            });
        }

        traces.each(function(d) {
            var legendItem = d[0];
            var textHeight = legendItem.height;
            var textWidth = legendItem.width;

            Drawing.setTranslate(this,
                borderwidth,
                (5 + borderwidth + opts._height + textHeight / 2));

            opts._height += textHeight;
            opts._width = Math.max(opts._width, textWidth);
        });

        opts._width += 45 + borderwidth * 2;
        opts._height += 10 + borderwidth * 2;

        if(isGrouped) {
            opts._height += (opts._lgroupsLength - 1) * opts.tracegroupgap;
        }

        extraWidth = 40;
    }
    else if(isGrouped) {
        var groupXOffsets = [opts._width];
        var groupData = groups.data();

        for(var i = 0, n = groupData.length; i < n; i++) {
            var textWidths = groupData[i].map(function(legendItemArray) {
                return legendItemArray[0].width;
            });

            var groupWidth = 40 + Math.max.apply(null, textWidths);

            opts._width += opts.tracegroupgap + groupWidth;

            groupXOffsets.push(opts._width);
        }

        groups.each(function(d, i) {
            Drawing.setTranslate(this, groupXOffsets[i], 0);
        });

        groups.each(function() {
            var group = d3.select(this);
            var groupTraces = group.selectAll('g.traces');
            var groupHeight = 0;

            groupTraces.each(function(d) {
                var legendItem = d[0];
                var textHeight = legendItem.height;

                Drawing.setTranslate(this,
                    0,
                    (5 + borderwidth + groupHeight + textHeight / 2));

                groupHeight += textHeight;
            });

            opts._height = Math.max(opts._height, groupHeight);
        });

        opts._height += 10 + borderwidth * 2;
        opts._width += borderwidth * 2;
    }
    else {
        var rowHeight = 0;
        var maxTraceHeight = 0;
        var maxTraceWidth = 0;
        var offsetX = 0;
        var fullTracesWidth = 0;
        var traceGap = opts.tracegroupgap || 5;

        // calculate largest width for traces and use for width of all legend items
        traces.each(function(d) {
            maxTraceWidth = Math.max(40 + d[0].width, maxTraceWidth);
            fullTracesWidth += 40 + d[0].width + traceGap;
        });

        // check if legend fits in one row
        var oneRowLegend = fullLayout._size.w > borderwidth + fullTracesWidth - traceGap;

        traces.each(function(d) {
            var legendItem = d[0];
            var traceWidth = oneRowLegend ? 40 + d[0].width : maxTraceWidth;

            if((borderwidth + offsetX + traceGap + traceWidth) > fullLayout._size.w) {
                offsetX = 0;
                rowHeight += maxTraceHeight;
                opts._height += maxTraceHeight;
                // reset for next row
                maxTraceHeight = 0;
            }

            Drawing.setTranslate(this,
                (borderwidth + offsetX),
                (5 + borderwidth + legendItem.height / 2) + rowHeight);

            opts._width += traceGap + traceWidth;

            // keep track of tallest trace in group
            offsetX += traceGap + traceWidth;
            maxTraceHeight = Math.max(legendItem.height, maxTraceHeight);
        });

        if(oneRowLegend) {
            opts._height = maxTraceHeight;
        } else {
            opts._height += maxTraceHeight;
        }

        opts._width += borderwidth * 2;
        opts._height += 10 + borderwidth * 2;
    }

    // make sure we're only getting full pixels
    opts._width = Math.ceil(opts._width);
    opts._height = Math.ceil(opts._height);

    var isEditable = (
        gd._context.edits.legendText ||
        gd._context.edits.legendPosition
    );

    traces.each(function(d) {
        var legendItem = d[0];
        var bg = d3.select(this).select('.legendtoggle');

        Drawing.setRect(bg,
            0,
            -legendItem.height / 2,
            (isEditable ? 0 : opts._width) + extraWidth,
            legendItem.height
        );
    });
}

function expandMargin(gd) {
    var fullLayout = gd._fullLayout;
    var opts = fullLayout.legend;

    var xanchor = 'left';
    if(Lib.isRightAnchor(opts)) {
        xanchor = 'right';
    }
    else if(Lib.isCenterAnchor(opts)) {
        xanchor = 'center';
    }

    var yanchor = 'top';
    if(Lib.isBottomAnchor(opts)) {
        yanchor = 'bottom';
    }
    else if(Lib.isMiddleAnchor(opts)) {
        yanchor = 'middle';
    }

    // lastly check if the margin auto-expand has changed
    Plots.autoMargin(gd, 'legend', {
        x: opts.x,
        y: opts.y,
        l: opts._width * (FROM_TL[xanchor]),
        r: opts._width * (FROM_BR[xanchor]),
        b: opts._height * (FROM_BR[yanchor]),
        t: opts._height * (FROM_TL[yanchor])
    });
}

function expandHorizontalMargin(gd) {
    var fullLayout = gd._fullLayout;
    var opts = fullLayout.legend;

    var xanchor = 'left';
    if(Lib.isRightAnchor(opts)) {
        xanchor = 'right';
    }
    else if(Lib.isCenterAnchor(opts)) {
        xanchor = 'center';
    }

    // lastly check if the margin auto-expand has changed
    Plots.autoMargin(gd, 'legend', {
        x: opts.x,
        y: 0.5,
        l: opts._width * (FROM_TL[xanchor]),
        r: opts._width * (FROM_BR[xanchor]),
        b: 0,
        t: 0
    });
}

},{"../../constants/alignment":666,"../../constants/interactions":670,"../../lib":694,"../../lib/events":683,"../../lib/svg_text_utils":718,"../../plots/plots":806,"../../registry":825,"../color":571,"../dragelement":589,"../drawing":592,"./constants":621,"./get_legend_data":624,"./handle_click":625,"./helpers":626,"./style":628,"d3":149}],624:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../../registry');
var helpers = _dereq_('./helpers');


module.exports = function getLegendData(calcdata, opts) {
    var lgroupToTraces = {};
    var lgroups = [];
    var hasOneNonBlankGroup = false;
    var slicesShown = {};
    var lgroupi = 0;
    var i, j;

    function addOneItem(legendGroup, legendItem) {
        // each '' legend group is treated as a separate group
        if(legendGroup === '' || !helpers.isGrouped(opts)) {
            var uniqueGroup = '~~i' + lgroupi; // TODO: check this against fullData legendgroups?

            lgroups.push(uniqueGroup);
            lgroupToTraces[uniqueGroup] = [[legendItem]];
            lgroupi++;
        }
        else if(lgroups.indexOf(legendGroup) === -1) {
            lgroups.push(legendGroup);
            hasOneNonBlankGroup = true;
            lgroupToTraces[legendGroup] = [[legendItem]];
        }
        else lgroupToTraces[legendGroup].push([legendItem]);
    }

    // build an { legendgroup: [cd0, cd0], ... } object
    for(i = 0; i < calcdata.length; i++) {
        var cd = calcdata[i];
        var cd0 = cd[0];
        var trace = cd0.trace;
        var lgroup = trace.legendgroup;

        if(!trace.visible || !trace.showlegend) continue;

        if(Registry.traceIs(trace, 'pie')) {
            if(!slicesShown[lgroup]) slicesShown[lgroup] = {};

            for(j = 0; j < cd.length; j++) {
                var labelj = cd[j].label;

                if(!slicesShown[lgroup][labelj]) {
                    addOneItem(lgroup, {
                        label: labelj,
                        color: cd[j].color,
                        i: cd[j].i,
                        trace: trace,
                        pts: cd[j].pts
                    });

                    slicesShown[lgroup][labelj] = true;
                }
            }
        }

        else addOneItem(lgroup, cd0);
    }

    // won't draw a legend in this case
    if(!lgroups.length) return [];

    // rearrange lgroupToTraces into a d3-friendly array of arrays
    var lgroupsLength = lgroups.length;
    var ltraces;
    var legendData;

    if(hasOneNonBlankGroup && helpers.isGrouped(opts)) {
        legendData = new Array(lgroupsLength);

        for(i = 0; i < lgroupsLength; i++) {
            ltraces = lgroupToTraces[lgroups[i]];
            legendData[i] = helpers.isReversed(opts) ? ltraces.reverse() : ltraces;
        }
    }
    else {
        // collapse all groups into one if all groups are blank
        legendData = [new Array(lgroupsLength)];

        for(i = 0; i < lgroupsLength; i++) {
            ltraces = lgroupToTraces[lgroups[i]][0];
            legendData[0][helpers.isReversed(opts) ? lgroupsLength - i - 1 : i] = ltraces;
        }
        lgroupsLength = 1;
    }

    // needed in repositionLegend
    opts._lgroupsLength = lgroupsLength;
    return legendData;
};

},{"../../registry":825,"./helpers":626}],625:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Registry = _dereq_('../../registry');

var SHOWISOLATETIP = true;

module.exports = function handleClick(g, gd, numClicks) {
    if(gd._dragged || gd._editing) return;

    var hiddenSlices = gd._fullLayout.hiddenlabels ?
        gd._fullLayout.hiddenlabels.slice() :
        [];

    var legendItem = g.data()[0][0];
    var fullData = gd._fullData;
    var fullTrace = legendItem.trace;
    var legendgroup = fullTrace.legendgroup;

    var i, j, kcont, key, keys, val;
    var attrUpdate = {};
    var attrIndices = [];
    var carrs = [];
    var carrIdx = [];

    function insertUpdate(traceIndex, key, value) {
        var attrIndex = attrIndices.indexOf(traceIndex);
        var valueArray = attrUpdate[key];
        if(!valueArray) {
            valueArray = attrUpdate[key] = [];
        }

        if(attrIndices.indexOf(traceIndex) === -1) {
            attrIndices.push(traceIndex);
            attrIndex = attrIndices.length - 1;
        }

        valueArray[attrIndex] = value;

        return attrIndex;
    }

    function setVisibility(fullTrace, visibility) {
        var fullInput = fullTrace._fullInput;
        if(Registry.hasTransform(fullInput, 'groupby')) {
            var kcont = carrs[fullInput.index];
            if(!kcont) {
                var groupbyIndices = Registry.getTransformIndices(fullInput, 'groupby');
                var lastGroupbyIndex = groupbyIndices[groupbyIndices.length - 1];
                kcont = Lib.keyedContainer(fullInput, 'transforms[' + lastGroupbyIndex + '].styles', 'target', 'value.visible');
                carrs[fullInput.index] = kcont;
            }

            var curState = kcont.get(fullTrace._group);

            // If not specified, assume visible. This happens if there are other style
            // properties set for a group but not the visibility. There are many similar
            // ways to do this (e.g. why not just `curState = fullTrace.visible`??? The
            // answer is: because it breaks other things like groupby trace names in
            // subtle ways.)
            if(curState === undefined) {
                curState = true;
            }

            if(curState !== false) {
                // true -> legendonly. All others toggle to true:
                kcont.set(fullTrace._group, visibility);
            }
            carrIdx[fullInput.index] = insertUpdate(fullInput.index, 'visible', fullInput.visible === false ? false : true);
        } else {
            // false -> false (not possible since will not be visible in legend)
            // true -> legendonly
            // legendonly -> true
            var nextVisibility = fullInput.visible === false ? false : visibility;

            insertUpdate(fullInput.index, 'visible', nextVisibility);
        }
    }

    if(numClicks === 1 && SHOWISOLATETIP && gd.data && gd._context.showTips) {
        Lib.notifier(Lib._(gd, 'Double-click on legend to isolate one trace'), 'long');
        SHOWISOLATETIP = false;
    } else {
        SHOWISOLATETIP = false;
    }

    if(Registry.traceIs(fullTrace, 'pie')) {
        var thisLabel = legendItem.label;
        var thisLabelIndex = hiddenSlices.indexOf(thisLabel);

        if(numClicks === 1) {
            if(thisLabelIndex === -1) hiddenSlices.push(thisLabel);
            else hiddenSlices.splice(thisLabelIndex, 1);
        } else if(numClicks === 2) {
            hiddenSlices = [];
            gd.calcdata[0].forEach(function(d) {
                if(thisLabel !== d.label) {
                    hiddenSlices.push(d.label);
                }
            });
            if(gd._fullLayout.hiddenlabels && gd._fullLayout.hiddenlabels.length === hiddenSlices.length && thisLabelIndex === -1) {
                hiddenSlices = [];
            }
        }

        Registry.call('_guiRelayout', gd, 'hiddenlabels', hiddenSlices);
    } else {
        var hasLegendgroup = legendgroup && legendgroup.length;
        var traceIndicesInGroup = [];
        var tracei;
        if(hasLegendgroup) {
            for(i = 0; i < fullData.length; i++) {
                tracei = fullData[i];
                if(!tracei.visible) continue;
                if(tracei.legendgroup === legendgroup) {
                    traceIndicesInGroup.push(i);
                }
            }
        }

        if(numClicks === 1) {
            var nextVisibility;

            switch(fullTrace.visible) {
                case true:
                    nextVisibility = 'legendonly';
                    break;
                case false:
                    nextVisibility = false;
                    break;
                case 'legendonly':
                    nextVisibility = true;
                    break;
            }

            if(hasLegendgroup) {
                for(i = 0; i < fullData.length; i++) {
                    if(fullData[i].visible !== false && fullData[i].legendgroup === legendgroup) {
                        setVisibility(fullData[i], nextVisibility);
                    }
                }
            } else {
                setVisibility(fullTrace, nextVisibility);
            }
        } else if(numClicks === 2) {
            // Compute the clicked index. expandedIndex does what we want for expanded traces
            // but also culls hidden traces. That means we have some work to do.
            var isClicked, isInGroup, otherState;
            var isIsolated = true;
            for(i = 0; i < fullData.length; i++) {
                isClicked = fullData[i] === fullTrace;
                if(isClicked) continue;

                isInGroup = (hasLegendgroup && fullData[i].legendgroup === legendgroup);

                if(!isInGroup && fullData[i].visible === true && !Registry.traceIs(fullData[i], 'notLegendIsolatable')) {
                    isIsolated = false;
                    break;
                }
            }

            for(i = 0; i < fullData.length; i++) {
                // False is sticky; we don't change it.
                if(fullData[i].visible === false) continue;

                if(Registry.traceIs(fullData[i], 'notLegendIsolatable')) {
                    continue;
                }

                switch(fullTrace.visible) {
                    case 'legendonly':
                        setVisibility(fullData[i], true);
                        break;
                    case true:
                        otherState = isIsolated ? true : 'legendonly';
                        isClicked = fullData[i] === fullTrace;
                        isInGroup = isClicked || (hasLegendgroup && fullData[i].legendgroup === legendgroup);
                        setVisibility(fullData[i], isInGroup ? true : otherState);
                        break;
                }
            }
        }

        for(i = 0; i < carrs.length; i++) {
            kcont = carrs[i];
            if(!kcont) continue;
            var update = kcont.constructUpdate();

            var updateKeys = Object.keys(update);
            for(j = 0; j < updateKeys.length; j++) {
                key = updateKeys[j];
                val = attrUpdate[key] = attrUpdate[key] || [];
                val[carrIdx[i]] = update[key];
            }
        }

        // The length of the value arrays should be equal and any unspecified
        // values should be explicitly undefined for them to get properly culled
        // as updates and not accidentally reset to the default value. This fills
        // out sparse arrays with the required number of undefined values:
        keys = Object.keys(attrUpdate);
        for(i = 0; i < keys.length; i++) {
            key = keys[i];
            for(j = 0; j < attrIndices.length; j++) {
                // Use hasOwnPropety to protect against falsey values:
                if(!attrUpdate[key].hasOwnProperty(j)) {
                    attrUpdate[key][j] = undefined;
                }
            }
        }

        Registry.call('_guiRestyle', gd, attrUpdate, attrIndices);
    }
};

},{"../../lib":694,"../../registry":825}],626:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

exports.isGrouped = function isGrouped(legendLayout) {
    return (legendLayout.traceorder || '').indexOf('grouped') !== -1;
};

exports.isVertical = function isVertical(legendLayout) {
    return legendLayout.orientation !== 'h';
};

exports.isReversed = function isReversed(legendLayout) {
    return (legendLayout.traceorder || '').indexOf('reversed') !== -1;
};

},{}],627:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


module.exports = {
    moduleType: 'component',
    name: 'legend',

    layoutAttributes: _dereq_('./attributes'),
    supplyLayoutDefaults: _dereq_('./defaults'),

    draw: _dereq_('./draw'),
    style: _dereq_('./style')
};

},{"./attributes":620,"./defaults":622,"./draw":623,"./style":628}],628:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Drawing = _dereq_('../drawing');
var Color = _dereq_('../color');

var subTypes = _dereq_('../../traces/scatter/subtypes');
var stylePie = _dereq_('../../traces/pie/style_one');

module.exports = function style(s, gd) {
    s.each(function(d) {
        var traceGroup = d3.select(this);

        var layers = Lib.ensureSingle(traceGroup, 'g', 'layers');
        layers.style('opacity', d[0].trace.opacity);

        // Marker vertical alignment
        var valign = gd._fullLayout.legend.valign;
        var lineHeight = d[0].lineHeight;
        var height = d[0].height;

        if(valign === 'middle' || !lineHeight || !height) {
            layers.attr('transform', null);
        } else {
            var factor = {top: 1, bottom: -1}[valign];
            var markerOffsetY = factor * (0.5 * (lineHeight - height + 3));
            layers.attr('transform', 'translate(0,' + markerOffsetY + ')');
        }

        var fill = layers
            .selectAll('g.legendfill')
                .data([d]);
        fill.enter().append('g')
            .classed('legendfill', true);

        var line = layers
            .selectAll('g.legendlines')
                .data([d]);
        line.enter().append('g')
            .classed('legendlines', true);

        var symbol = layers
            .selectAll('g.legendsymbols')
                .data([d]);
        symbol.enter().append('g')
            .classed('legendsymbols', true);

        symbol.selectAll('g.legendpoints')
            .data([d])
          .enter().append('g')
            .classed('legendpoints', true);
    })
    .each(styleBars)
    .each(styleBoxes)
    .each(stylePies)
    .each(styleLines)
    .each(stylePoints)
    .each(styleCandles)
    .each(styleOHLC);

    function styleLines(d) {
        var trace = d[0].trace;
        var showFill = trace.visible && trace.fill && trace.fill !== 'none';
        var showLine = subTypes.hasLines(trace);
        var contours = trace.contours;
        var showGradientLine = false;
        var showGradientFill = false;

        if(contours) {
            var coloring = contours.coloring;

            if(coloring === 'lines') {
                showGradientLine = true;
            }
            else {
                showLine = coloring === 'none' || coloring === 'heatmap' ||
                    contours.showlines;
            }

            if(contours.type === 'constraint') {
                showFill = contours._operation !== '=';
            }
            else if(coloring === 'fill' || coloring === 'heatmap') {
                showGradientFill = true;
            }
        }

        // with fill and no markers or text, move the line and fill up a bit
        // so it's more centered
        var markersOrText = subTypes.hasMarkers(trace) || subTypes.hasText(trace);
        var anyFill = showFill || showGradientFill;
        var anyLine = showLine || showGradientLine;
        var pathStart = (markersOrText || !anyFill) ? 'M5,0' :
            // with a line leave it slightly below center, to leave room for the
            // line thickness and because the line is usually more prominent
            anyLine ? 'M5,-2' : 'M5,-3';

        var this3 = d3.select(this);

        var fill = this3.select('.legendfill').selectAll('path')
            .data(showFill || showGradientFill ? [d] : []);
        fill.enter().append('path').classed('js-fill', true);
        fill.exit().remove();
        fill.attr('d', pathStart + 'h30v6h-30z')
            .call(showFill ? Drawing.fillGroupStyle : fillGradient);

        var line = this3.select('.legendlines').selectAll('path')
            .data(showLine || showGradientLine ? [d] : []);
        line.enter().append('path').classed('js-line', true);
        line.exit().remove();

        // this is ugly... but you can't apply a gradient to a perfectly
        // horizontal or vertical line. Presumably because then
        // the system doesn't know how to scale vertical variation, even
        // though there *is* no vertical variation in this case.
        // so add an invisibly small angle to the line
        // This issue (and workaround) exist across (Mac) Chrome, FF, and Safari
        line.attr('d', pathStart + (showGradientLine ? 'l30,0.0001' : 'h30'))
            .call(showLine ? Drawing.lineGroupStyle : lineGradient);

        function fillGradient(s) {
            if(s.size()) {
                var gradientID = 'legendfill-' + trace.uid;
                Drawing.gradient(s, gd, gradientID, 'horizontalreversed',
                    trace.colorscale, 'fill');
            }
        }

        function lineGradient(s) {
            if(s.size()) {
                var gradientID = 'legendline-' + trace.uid;
                Drawing.lineGroupStyle(s);
                Drawing.gradient(s, gd, gradientID, 'horizontalreversed',
                    trace.colorscale, 'stroke');
            }
        }

    }

    function stylePoints(d) {
        var d0 = d[0];
        var trace = d0.trace;
        var showMarkers = subTypes.hasMarkers(trace);
        var showText = subTypes.hasText(trace);
        var showLines = subTypes.hasLines(trace);
        var dMod, tMod;

        // 'scatter3d' don't use gd.calcdata,
        // use d0.trace to infer arrayOk attributes

        function boundVal(attrIn, arrayToValFn, bounds) {
            var valIn = Lib.nestedProperty(trace, attrIn).get();
            var valToBound = (Lib.isArrayOrTypedArray(valIn) && arrayToValFn) ?
                arrayToValFn(valIn) :
                valIn;

            if(bounds) {
                if(valToBound < bounds[0]) return bounds[0];
                else if(valToBound > bounds[1]) return bounds[1];
            }
            return valToBound;
        }

        function pickFirst(array) { return array[0]; }

        // constrain text, markers, etc so they'll fit on the legend
        if(showMarkers || showText || showLines) {
            var dEdit = {};
            var tEdit = {};

            if(showMarkers) {
                dEdit.mc = boundVal('marker.color', pickFirst);
                dEdit.mx = boundVal('marker.symbol', pickFirst);
                dEdit.mo = boundVal('marker.opacity', Lib.mean, [0.2, 1]);
                dEdit.mlc = boundVal('marker.line.color', pickFirst);
                dEdit.mlw = boundVal('marker.line.width', Lib.mean, [0, 5]);
                tEdit.marker = {
                    sizeref: 1,
                    sizemin: 1,
                    sizemode: 'diameter'
                };

                var ms = boundVal('marker.size', Lib.mean, [2, 16]);
                dEdit.ms = ms;
                tEdit.marker.size = ms;
            }

            if(showLines) {
                tEdit.line = {
                    width: boundVal('line.width', pickFirst, [0, 10])
                };
            }

            if(showText) {
                dEdit.tx = 'Aa';
                dEdit.tp = boundVal('textposition', pickFirst);
                dEdit.ts = 10;
                dEdit.tc = boundVal('textfont.color', pickFirst);
                dEdit.tf = boundVal('textfont.family', pickFirst);
            }

            dMod = [Lib.minExtend(d0, dEdit)];
            tMod = Lib.minExtend(trace, tEdit);

            // always show legend items in base state
            tMod.selectedpoints = null;
        }

        var ptgroup = d3.select(this).select('g.legendpoints');

        var pts = ptgroup.selectAll('path.scatterpts')
            .data(showMarkers ? dMod : []);
        // make sure marker is on the bottom, in case it enters after text
        pts.enter().insert('path', ':first-child')
            .classed('scatterpts', true)
            .attr('transform', 'translate(20,0)');
        pts.exit().remove();
        pts.call(Drawing.pointStyle, tMod, gd);

        // 'mrc' is set in pointStyle and used in textPointStyle:
        // constrain it here
        if(showMarkers) dMod[0].mrc = 3;

        var txt = ptgroup.selectAll('g.pointtext')
            .data(showText ? dMod : []);
        txt.enter()
            .append('g').classed('pointtext', true)
                .append('text').attr('transform', 'translate(20,0)');
        txt.exit().remove();
        txt.selectAll('text').call(Drawing.textPointStyle, tMod, gd);
    }

    function styleBars(d) {
        var trace = d[0].trace;
        var marker = trace.marker || {};
        var markerLine = marker.line || {};

        var barpath = d3.select(this).select('g.legendpoints')
            .selectAll('path.legendbar')
            .data(Registry.traceIs(trace, 'bar') ? [d] : []);
        barpath.enter().append('path').classed('legendbar', true)
            .attr('d', 'M6,6H-6V-6H6Z')
            .attr('transform', 'translate(20,0)');
        barpath.exit().remove();

        barpath.each(function(d) {
            var p = d3.select(this);
            var d0 = d[0];
            var w = (d0.mlw + 1 || markerLine.width + 1) - 1;

            p.style('stroke-width', w + 'px')
                .call(Color.fill, d0.mc || marker.color);

            if(w) {
                p.call(Color.stroke, d0.mlc || markerLine.color);
            }
        });
    }

    function styleBoxes(d) {
        var trace = d[0].trace;

        var pts = d3.select(this).select('g.legendpoints')
            .selectAll('path.legendbox')
            .data(Registry.traceIs(trace, 'box-violin') && trace.visible ? [d] : []);
        pts.enter().append('path').classed('legendbox', true)
            // if we want the median bar, prepend M6,0H-6
            .attr('d', 'M6,6H-6V-6H6Z')
            .attr('transform', 'translate(20,0)');
        pts.exit().remove();

        pts.each(function() {
            var w = trace.line.width;
            var p = d3.select(this);

            p.style('stroke-width', w + 'px')
                .call(Color.fill, trace.fillcolor);

            if(w) {
                Color.stroke(p, trace.line.color);
            }
        });
    }

    function styleCandles(d) {
        var trace = d[0].trace;

        var pts = d3.select(this).select('g.legendpoints')
            .selectAll('path.legendcandle')
            .data(trace.type === 'candlestick' && trace.visible ? [d, d] : []);
        pts.enter().append('path').classed('legendcandle', true)
            .attr('d', function(_, i) {
                if(i) return 'M-15,0H-8M-8,6V-6H8Z'; // increasing
                return 'M15,0H8M8,-6V6H-8Z'; // decreasing
            })
            .attr('transform', 'translate(20,0)')
            .style('stroke-miterlimit', 1);
        pts.exit().remove();

        pts.each(function(_, i) {
            var container = trace[i ? 'increasing' : 'decreasing'];
            var w = container.line.width;
            var p = d3.select(this);

            p.style('stroke-width', w + 'px')
                .call(Color.fill, container.fillcolor);

            if(w) {
                Color.stroke(p, container.line.color);
            }
        });
    }

    function styleOHLC(d) {
        var trace = d[0].trace;

        var pts = d3.select(this).select('g.legendpoints')
            .selectAll('path.legendohlc')
            .data(trace.type === 'ohlc' && trace.visible ? [d, d] : []);
        pts.enter().append('path').classed('legendohlc', true)
            .attr('d', function(_, i) {
                if(i) return 'M-15,0H0M-8,-6V0'; // increasing
                return 'M15,0H0M8,6V0'; // decreasing
            })
            .attr('transform', 'translate(20,0)')
            .style('stroke-miterlimit', 1);
        pts.exit().remove();

        pts.each(function(_, i) {
            var container = trace[i ? 'increasing' : 'decreasing'];
            var w = container.line.width;
            var p = d3.select(this);

            p.style('fill', 'none')
                .call(Drawing.dashLine, container.line.dash, w);

            if(w) {
                Color.stroke(p, container.line.color);
            }
        });
    }

    function stylePies(d) {
        var trace = d[0].trace;

        var pts = d3.select(this).select('g.legendpoints')
            .selectAll('path.legendpie')
            .data(Registry.traceIs(trace, 'pie') && trace.visible ? [d] : []);
        pts.enter().append('path').classed('legendpie', true)
            .attr('d', 'M6,6H-6V-6H6Z')
            .attr('transform', 'translate(20,0)');
        pts.exit().remove();

        if(pts.size()) pts.call(stylePie, d[0], trace);
    }
};

},{"../../lib":694,"../../registry":825,"../../traces/pie/style_one":1033,"../../traces/scatter/subtypes":1071,"../color":571,"../drawing":592,"d3":149}],629:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../../registry');
var Plots = _dereq_('../../plots/plots');
var axisIds = _dereq_('../../plots/cartesian/axis_ids');
var Lib = _dereq_('../../lib');
var Icons = _dereq_('../../../build/ploticon');

var _ = Lib._;

var modeBarButtons = module.exports = {};

/**
 * ModeBar buttons configuration
 *
 * @param {string} name
 *      name / id of the buttons (for tracking)
 * @param {string} title
 *      text that appears while hovering over the button,
 *      enter null, false or '' for no hover text
 * @param {string} icon
 *      svg icon object associated with the button
 *      can be linked to Plotly.Icons to use the default plotly icons
 * @param {string} [gravity]
 *      icon positioning
 * @param {function} click
 *      click handler associated with the button, a function of
 *      'gd' (the main graph object) and
 *      'ev' (the event object)
 * @param {string} [attr]
 *      attribute associated with button,
 *      use this with 'val' to keep track of the state
 * @param {*} [val]
 *      initial 'attr' value, can be a function of gd
 * @param {boolean} [toggle]
 *      is the button a toggle button?
 */

modeBarButtons.toImage = {
    name: 'toImage',
    title: function(gd) {
        var opts = gd._context.toImageButtonOptions || {};
        var format = opts.format || 'png';
        return format === 'png' ?
            _(gd, 'Download plot as a png') : // legacy text
            _(gd, 'Download plot'); // generic non-PNG text
    },
    icon: Icons.camera,
    click: function(gd) {
        var toImageButtonOptions = gd._context.toImageButtonOptions;
        var opts = {format: toImageButtonOptions.format || 'png'};

        Lib.notifier(_(gd, 'Taking snapshot - this may take a few seconds'), 'long');

        if(opts.format !== 'svg' && Lib.isIE()) {
            Lib.notifier(_(gd, 'IE only supports svg.  Changing format to svg.'), 'long');
            opts.format = 'svg';
        }

        ['filename', 'width', 'height', 'scale'].forEach(function(key) {
            if(toImageButtonOptions[key]) {
                opts[key] = toImageButtonOptions[key];
            }
        });

        Registry.call('downloadImage', gd, opts)
          .then(function(filename) {
              Lib.notifier(_(gd, 'Snapshot succeeded') + ' - ' + filename, 'long');
          })
          .catch(function() {
              Lib.notifier(_(gd, 'Sorry, there was a problem downloading your snapshot!'), 'long');
          });
    }
};

modeBarButtons.sendDataToCloud = {
    name: 'sendDataToCloud',
    title: function(gd) { return _(gd, 'Edit in Chart Studio'); },
    icon: Icons.disk,
    click: function(gd) {
        Plots.sendDataToCloud(gd);
    }
};

modeBarButtons.zoom2d = {
    name: 'zoom2d',
    title: function(gd) { return _(gd, 'Zoom'); },
    attr: 'dragmode',
    val: 'zoom',
    icon: Icons.zoombox,
    click: handleCartesian
};

modeBarButtons.pan2d = {
    name: 'pan2d',
    title: function(gd) { return _(gd, 'Pan'); },
    attr: 'dragmode',
    val: 'pan',
    icon: Icons.pan,
    click: handleCartesian
};

modeBarButtons.select2d = {
    name: 'select2d',
    title: function(gd) { return _(gd, 'Box Select'); },
    attr: 'dragmode',
    val: 'select',
    icon: Icons.selectbox,
    click: handleCartesian
};

modeBarButtons.lasso2d = {
    name: 'lasso2d',
    title: function(gd) { return _(gd, 'Lasso Select'); },
    attr: 'dragmode',
    val: 'lasso',
    icon: Icons.lasso,
    click: handleCartesian
};

modeBarButtons.zoomIn2d = {
    name: 'zoomIn2d',
    title: function(gd) { return _(gd, 'Zoom in'); },
    attr: 'zoom',
    val: 'in',
    icon: Icons.zoom_plus,
    click: handleCartesian
};

modeBarButtons.zoomOut2d = {
    name: 'zoomOut2d',
    title: function(gd) { return _(gd, 'Zoom out'); },
    attr: 'zoom',
    val: 'out',
    icon: Icons.zoom_minus,
    click: handleCartesian
};

modeBarButtons.autoScale2d = {
    name: 'autoScale2d',
    title: function(gd) { return _(gd, 'Autoscale'); },
    attr: 'zoom',
    val: 'auto',
    icon: Icons.autoscale,
    click: handleCartesian
};

modeBarButtons.resetScale2d = {
    name: 'resetScale2d',
    title: function(gd) { return _(gd, 'Reset axes'); },
    attr: 'zoom',
    val: 'reset',
    icon: Icons.home,
    click: handleCartesian
};

modeBarButtons.hoverClosestCartesian = {
    name: 'hoverClosestCartesian',
    title: function(gd) { return _(gd, 'Show closest data on hover'); },
    attr: 'hovermode',
    val: 'closest',
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: handleCartesian
};

modeBarButtons.hoverCompareCartesian = {
    name: 'hoverCompareCartesian',
    title: function(gd) { return _(gd, 'Compare data on hover'); },
    attr: 'hovermode',
    val: function(gd) {
        return gd._fullLayout._isHoriz ? 'y' : 'x';
    },
    icon: Icons.tooltip_compare,
    gravity: 'ne',
    click: handleCartesian
};

function handleCartesian(gd, ev) {
    var button = ev.currentTarget;
    var astr = button.getAttribute('data-attr');
    var val = button.getAttribute('data-val') || true;
    var fullLayout = gd._fullLayout;
    var aobj = {};
    var axList = axisIds.list(gd, null, true);
    var allSpikesEnabled = 'on';

    var ax, i;

    if(astr === 'zoom') {
        var mag = (val === 'in') ? 0.5 : 2;
        var r0 = (1 + mag) / 2;
        var r1 = (1 - mag) / 2;
        var axName;

        for(i = 0; i < axList.length; i++) {
            ax = axList[i];

            if(!ax.fixedrange) {
                axName = ax._name;
                if(val === 'auto') aobj[axName + '.autorange'] = true;
                else if(val === 'reset') {
                    if(ax._rangeInitial === undefined) {
                        aobj[axName + '.autorange'] = true;
                    }
                    else {
                        var rangeInitial = ax._rangeInitial.slice();
                        aobj[axName + '.range[0]'] = rangeInitial[0];
                        aobj[axName + '.range[1]'] = rangeInitial[1];
                    }
                    if(ax._showSpikeInitial !== undefined) {
                        aobj[axName + '.showspikes'] = ax._showSpikeInitial;
                        if(allSpikesEnabled === 'on' && !ax._showSpikeInitial) {
                            allSpikesEnabled = 'off';
                        }
                    }
                }
                else {
                    var rangeNow = [
                        ax.r2l(ax.range[0]),
                        ax.r2l(ax.range[1]),
                    ];

                    var rangeNew = [
                        r0 * rangeNow[0] + r1 * rangeNow[1],
                        r0 * rangeNow[1] + r1 * rangeNow[0]
                    ];

                    aobj[axName + '.range[0]'] = ax.l2r(rangeNew[0]);
                    aobj[axName + '.range[1]'] = ax.l2r(rangeNew[1]);
                }
            }
        }
        fullLayout._cartesianSpikesEnabled = allSpikesEnabled;
    }
    else {
        // if ALL traces have orientation 'h', 'hovermode': 'x' otherwise: 'y'
        if(astr === 'hovermode' && (val === 'x' || val === 'y')) {
            val = fullLayout._isHoriz ? 'y' : 'x';
            button.setAttribute('data-val', val);
        } else if(astr === 'hovermode' && val === 'closest') {
            for(i = 0; i < axList.length; i++) {
                ax = axList[i];
                if(allSpikesEnabled === 'on' && !ax.showspikes) {
                    allSpikesEnabled = 'off';
                }
            }
            fullLayout._cartesianSpikesEnabled = allSpikesEnabled;
        }

        aobj[astr] = val;
    }

    Registry.call('_guiRelayout', gd, aobj);
}

modeBarButtons.zoom3d = {
    name: 'zoom3d',
    title: function(gd) { return _(gd, 'Zoom'); },
    attr: 'scene.dragmode',
    val: 'zoom',
    icon: Icons.zoombox,
    click: handleDrag3d
};

modeBarButtons.pan3d = {
    name: 'pan3d',
    title: function(gd) { return _(gd, 'Pan'); },
    attr: 'scene.dragmode',
    val: 'pan',
    icon: Icons.pan,
    click: handleDrag3d
};

modeBarButtons.orbitRotation = {
    name: 'orbitRotation',
    title: function(gd) { return _(gd, 'Orbital rotation'); },
    attr: 'scene.dragmode',
    val: 'orbit',
    icon: Icons['3d_rotate'],
    click: handleDrag3d
};

modeBarButtons.tableRotation = {
    name: 'tableRotation',
    title: function(gd) { return _(gd, 'Turntable rotation'); },
    attr: 'scene.dragmode',
    val: 'turntable',
    icon: Icons['z-axis'],
    click: handleDrag3d
};

function handleDrag3d(gd, ev) {
    var button = ev.currentTarget;
    var attr = button.getAttribute('data-attr');
    var val = button.getAttribute('data-val') || true;
    var sceneIds = gd._fullLayout._subplots.gl3d;
    var layoutUpdate = {};

    var parts = attr.split('.');

    for(var i = 0; i < sceneIds.length; i++) {
        layoutUpdate[sceneIds[i] + '.' + parts[1]] = val;
    }

    // for multi-type subplots
    var val2d = (val === 'pan') ? val : 'zoom';
    layoutUpdate.dragmode = val2d;

    Registry.call('_guiRelayout', gd, layoutUpdate);
}

modeBarButtons.resetCameraDefault3d = {
    name: 'resetCameraDefault3d',
    title: function(gd) { return _(gd, 'Reset camera to default'); },
    attr: 'resetDefault',
    icon: Icons.home,
    click: handleCamera3d
};

modeBarButtons.resetCameraLastSave3d = {
    name: 'resetCameraLastSave3d',
    title: function(gd) { return _(gd, 'Reset camera to last save'); },
    attr: 'resetLastSave',
    icon: Icons.movie,
    click: handleCamera3d
};

function handleCamera3d(gd, ev) {
    var button = ev.currentTarget;
    var attr = button.getAttribute('data-attr');
    var fullLayout = gd._fullLayout;
    var sceneIds = fullLayout._subplots.gl3d;
    var aobj = {};

    for(var i = 0; i < sceneIds.length; i++) {
        var sceneId = sceneIds[i];
        var key = sceneId + '.camera';
        var scene = fullLayout[sceneId]._scene;

        if(attr === 'resetDefault') {
            aobj[key] = null;
        }
        else if(attr === 'resetLastSave') {
            aobj[key] = Lib.extendDeep({}, scene.cameraInitial);
        }
    }

    Registry.call('_guiRelayout', gd, aobj);
}

modeBarButtons.hoverClosest3d = {
    name: 'hoverClosest3d',
    title: function(gd) { return _(gd, 'Toggle show closest data on hover'); },
    attr: 'hovermode',
    val: null,
    toggle: true,
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: handleHover3d
};

function getNextHover3d(gd, ev) {
    var button = ev.currentTarget;
    var val = button._previousVal;
    var fullLayout = gd._fullLayout;
    var sceneIds = fullLayout._subplots.gl3d;

    var axes = ['xaxis', 'yaxis', 'zaxis'];

    // initialize 'current spike' object to be stored in the DOM
    var currentSpikes = {};
    var layoutUpdate = {};

    if(val) {
        layoutUpdate = val;
        button._previousVal = null;
    }
    else {
        for(var i = 0; i < sceneIds.length; i++) {
            var sceneId = sceneIds[i];
            var sceneLayout = fullLayout[sceneId];

            var hovermodeAStr = sceneId + '.hovermode';
            currentSpikes[hovermodeAStr] = sceneLayout.hovermode;
            layoutUpdate[hovermodeAStr] = false;

            // copy all the current spike attrs
            for(var j = 0; j < 3; j++) {
                var axis = axes[j];
                var spikeAStr = sceneId + '.' + axis + '.showspikes';
                layoutUpdate[spikeAStr] = false;
                currentSpikes[spikeAStr] = sceneLayout[axis].showspikes;
            }
        }

        button._previousVal = currentSpikes;
    }
    return layoutUpdate;
}

function handleHover3d(gd, ev) {
    var layoutUpdate = getNextHover3d(gd, ev);
    Registry.call('_guiRelayout', gd, layoutUpdate);
}

modeBarButtons.zoomInGeo = {
    name: 'zoomInGeo',
    title: function(gd) { return _(gd, 'Zoom in'); },
    attr: 'zoom',
    val: 'in',
    icon: Icons.zoom_plus,
    click: handleGeo
};

modeBarButtons.zoomOutGeo = {
    name: 'zoomOutGeo',
    title: function(gd) { return _(gd, 'Zoom out'); },
    attr: 'zoom',
    val: 'out',
    icon: Icons.zoom_minus,
    click: handleGeo
};

modeBarButtons.resetGeo = {
    name: 'resetGeo',
    title: function(gd) { return _(gd, 'Reset'); },
    attr: 'reset',
    val: null,
    icon: Icons.autoscale,
    click: handleGeo
};

modeBarButtons.hoverClosestGeo = {
    name: 'hoverClosestGeo',
    title: function(gd) { return _(gd, 'Toggle show closest data on hover'); },
    attr: 'hovermode',
    val: null,
    toggle: true,
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: toggleHover
};

function handleGeo(gd, ev) {
    var button = ev.currentTarget;
    var attr = button.getAttribute('data-attr');
    var val = button.getAttribute('data-val') || true;
    var fullLayout = gd._fullLayout;
    var geoIds = fullLayout._subplots.geo;

    for(var i = 0; i < geoIds.length; i++) {
        var id = geoIds[i];
        var geoLayout = fullLayout[id];

        if(attr === 'zoom') {
            var scale = geoLayout.projection.scale;
            var newScale = (val === 'in') ? 2 * scale : 0.5 * scale;

            Registry.call('_guiRelayout', gd, id + '.projection.scale', newScale);
        } else if(attr === 'reset') {
            resetView(gd, 'geo');
        }
    }
}

modeBarButtons.hoverClosestGl2d = {
    name: 'hoverClosestGl2d',
    title: function(gd) { return _(gd, 'Toggle show closest data on hover'); },
    attr: 'hovermode',
    val: null,
    toggle: true,
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: toggleHover
};

modeBarButtons.hoverClosestPie = {
    name: 'hoverClosestPie',
    title: function(gd) { return _(gd, 'Toggle show closest data on hover'); },
    attr: 'hovermode',
    val: 'closest',
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: toggleHover
};

function getNextHover(gd) {
    var fullLayout = gd._fullLayout;

    if(fullLayout.hovermode) return false;

    if(fullLayout._has('cartesian')) {
        return fullLayout._isHoriz ? 'y' : 'x';
    }
    return 'closest';
}

function toggleHover(gd) {
    var newHover = getNextHover(gd);
    Registry.call('_guiRelayout', gd, 'hovermode', newHover);
}

// buttons when more then one plot types are present

modeBarButtons.toggleHover = {
    name: 'toggleHover',
    title: function(gd) { return _(gd, 'Toggle show closest data on hover'); },
    attr: 'hovermode',
    val: null,
    toggle: true,
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: function(gd, ev) {
        var layoutUpdate = getNextHover3d(gd, ev);
        layoutUpdate.hovermode = getNextHover(gd);

        Registry.call('_guiRelayout', gd, layoutUpdate);
    }
};

modeBarButtons.resetViews = {
    name: 'resetViews',
    title: function(gd) { return _(gd, 'Reset views'); },
    icon: Icons.home,
    click: function(gd, ev) {
        var button = ev.currentTarget;

        button.setAttribute('data-attr', 'zoom');
        button.setAttribute('data-val', 'reset');
        handleCartesian(gd, ev);

        button.setAttribute('data-attr', 'resetLastSave');
        handleCamera3d(gd, ev);

        resetView(gd, 'geo');
        resetView(gd, 'mapbox');
    }
};

modeBarButtons.toggleSpikelines = {
    name: 'toggleSpikelines',
    title: function(gd) { return _(gd, 'Toggle Spike Lines'); },
    icon: Icons.spikeline,
    attr: '_cartesianSpikesEnabled',
    val: 'on',
    click: function(gd) {
        var fullLayout = gd._fullLayout;

        fullLayout._cartesianSpikesEnabled = fullLayout._cartesianSpikesEnabled === 'on' ? 'off' : 'on';

        var aobj = setSpikelineVisibility(gd);

        Registry.call('_guiRelayout', gd, aobj);
    }
};

function setSpikelineVisibility(gd) {
    var fullLayout = gd._fullLayout;
    var axList = axisIds.list(gd, null, true);
    var aobj = {};

    var ax, axName;

    for(var i = 0; i < axList.length; i++) {
        ax = axList[i];
        axName = ax._name;
        aobj[axName + '.showspikes'] = fullLayout._cartesianSpikesEnabled === 'on' ? true : ax._showSpikeInitial;
    }

    return aobj;
}

modeBarButtons.resetViewMapbox = {
    name: 'resetViewMapbox',
    title: function(gd) { return _(gd, 'Reset view'); },
    attr: 'reset',
    icon: Icons.home,
    click: function(gd) {
        resetView(gd, 'mapbox');
    }
};

function resetView(gd, subplotType) {
    var fullLayout = gd._fullLayout;
    var subplotIds = fullLayout._subplots[subplotType];
    var aObj = {};

    for(var i = 0; i < subplotIds.length; i++) {
        var id = subplotIds[i];
        var subplotObj = fullLayout[id]._subplot;
        var viewInitial = subplotObj.viewInitial;
        var viewKeys = Object.keys(viewInitial);

        for(var j = 0; j < viewKeys.length; j++) {
            var key = viewKeys[j];
            aObj[id + '.' + key] = viewInitial[key];
        }
    }

    Registry.call('_guiRelayout', gd, aObj);
}

},{"../../../build/ploticon":2,"../../lib":694,"../../plots/cartesian/axis_ids":745,"../../plots/plots":806,"../../registry":825}],630:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

exports.manage = _dereq_('./manage');

},{"./manage":631}],631:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var axisIds = _dereq_('../../plots/cartesian/axis_ids');
var scatterSubTypes = _dereq_('../../traces/scatter/subtypes');
var Registry = _dereq_('../../registry');

var createModeBar = _dereq_('./modebar');
var modeBarButtons = _dereq_('./buttons');

/**
 * ModeBar wrapper around 'create' and 'update',
 * chooses buttons to pass to ModeBar constructor based on
 * plot type and plot config.
 *
 * @param {object} gd main plot object
 *
 */
module.exports = function manageModeBar(gd) {
    var fullLayout = gd._fullLayout;
    var context = gd._context;
    var modeBar = fullLayout._modeBar;

    if(!context.displayModeBar && !context.watermark) {
        if(modeBar) {
            modeBar.destroy();
            delete fullLayout._modeBar;
        }
        return;
    }

    if(!Array.isArray(context.modeBarButtonsToRemove)) {
        throw new Error([
            '*modeBarButtonsToRemove* configuration options',
            'must be an array.'
        ].join(' '));
    }

    if(!Array.isArray(context.modeBarButtonsToAdd)) {
        throw new Error([
            '*modeBarButtonsToAdd* configuration options',
            'must be an array.'
        ].join(' '));
    }

    var customButtons = context.modeBarButtons;
    var buttonGroups;

    if(Array.isArray(customButtons) && customButtons.length) {
        buttonGroups = fillCustomButton(customButtons);
    }
    else if(!context.displayModeBar && context.watermark) {
        buttonGroups = [];
    }
    else {
        buttonGroups = getButtonGroups(
            gd,
            context.modeBarButtonsToRemove,
            context.modeBarButtonsToAdd,
            context.showSendToCloud
        );
    }

    if(modeBar) modeBar.update(gd, buttonGroups);
    else fullLayout._modeBar = createModeBar(gd, buttonGroups);
};

// logic behind which buttons are displayed by default
function getButtonGroups(gd, buttonsToRemove, buttonsToAdd, showSendToCloud) {
    var fullLayout = gd._fullLayout;
    var fullData = gd._fullData;

    var hasCartesian = fullLayout._has('cartesian');
    var hasGL3D = fullLayout._has('gl3d');
    var hasGeo = fullLayout._has('geo');
    var hasPie = fullLayout._has('pie');
    var hasGL2D = fullLayout._has('gl2d');
    var hasTernary = fullLayout._has('ternary');
    var hasMapbox = fullLayout._has('mapbox');
    var hasPolar = fullLayout._has('polar');
    var allAxesFixed = areAllAxesFixed(fullLayout);

    var groups = [];

    function addGroup(newGroup) {
        if(!newGroup.length) return;

        var out = [];

        for(var i = 0; i < newGroup.length; i++) {
            var button = newGroup[i];
            if(buttonsToRemove.indexOf(button) !== -1) continue;
            out.push(modeBarButtons[button]);
        }

        groups.push(out);
    }

    // buttons common to all plot types
    var commonGroup = ['toImage'];
    if(showSendToCloud) commonGroup.push('sendDataToCloud');
    addGroup(commonGroup);

    var zoomGroup = [];
    var hoverGroup = [];
    var resetGroup = [];
    var dragModeGroup = [];

    if((hasCartesian || hasGL2D || hasPie || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasPolar > 1) {
        // graphs with more than one plot types get 'union buttons'
        // which reset the view or toggle hover labels across all subplots.
        hoverGroup = ['toggleHover'];
        resetGroup = ['resetViews'];
    }
    else if(hasGeo) {
        zoomGroup = ['zoomInGeo', 'zoomOutGeo'];
        hoverGroup = ['hoverClosestGeo'];
        resetGroup = ['resetGeo'];
    }
    else if(hasGL3D) {
        hoverGroup = ['hoverClosest3d'];
        resetGroup = ['resetCameraDefault3d', 'resetCameraLastSave3d'];
    }
    else if(hasMapbox) {
        hoverGroup = ['toggleHover'];
        resetGroup = ['resetViewMapbox'];
    }
    else if(hasGL2D) {
        hoverGroup = ['hoverClosestGl2d'];
    }
    else if(hasPie) {
        hoverGroup = ['hoverClosestPie'];
    }
    else { // hasPolar, hasTernary
        // always show at least one hover icon.
        hoverGroup = ['toggleHover'];
    }
    // if we have cartesian, allow switching between closest and compare
    // regardless of what other types are on the plot, since they'll all
    // just treat any truthy hovermode as 'closest'
    if(hasCartesian) {
        hoverGroup = ['toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian'];
    }

    if((hasCartesian || hasGL2D) && !allAxesFixed) {
        zoomGroup = ['zoomIn2d', 'zoomOut2d', 'autoScale2d'];
        if(resetGroup[0] !== 'resetViews') resetGroup = ['resetScale2d'];
    }

    if(hasGL3D) {
        dragModeGroup = ['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation'];
    }
    else if(((hasCartesian || hasGL2D) && !allAxesFixed) || hasTernary) {
        dragModeGroup = ['zoom2d', 'pan2d'];
    }
    else if(hasMapbox || hasGeo) {
        dragModeGroup = ['pan2d'];
    }
    else if(hasPolar) {
        dragModeGroup = ['zoom2d'];
    }
    if(isSelectable(fullData)) {
        dragModeGroup.push('select2d', 'lasso2d');
    }

    addGroup(dragModeGroup);
    addGroup(zoomGroup.concat(resetGroup));
    addGroup(hoverGroup);

    return appendButtonsToGroups(groups, buttonsToAdd);
}

function areAllAxesFixed(fullLayout) {
    var axList = axisIds.list({_fullLayout: fullLayout}, null, true);

    for(var i = 0; i < axList.length; i++) {
        if(!axList[i].fixedrange) {
            return false;
        }
    }

    return true;
}

// look for traces that support selection
// to be updated as we add more selectPoints handlers
function isSelectable(fullData) {
    var selectable = false;

    for(var i = 0; i < fullData.length; i++) {
        if(selectable) break;

        var trace = fullData[i];

        if(!trace._module || !trace._module.selectPoints) continue;

        if(Registry.traceIs(trace, 'scatter-like')) {
            if(scatterSubTypes.hasMarkers(trace) || scatterSubTypes.hasText(trace)) {
                selectable = true;
            }
        } else if(Registry.traceIs(trace, 'box-violin')) {
            if(trace.boxpoints === 'all' || trace.points === 'all') {
                selectable = true;
            }
        }
        // assume that in general if the trace module has selectPoints,
        // then it's selectable. Scatter is an exception to this because it must
        // have markers or text, not just be a scatter type.
        else selectable = true;
    }

    return selectable;
}

function appendButtonsToGroups(groups, buttons) {
    if(buttons.length) {
        if(Array.isArray(buttons[0])) {
            for(var i = 0; i < buttons.length; i++) {
                groups.push(buttons[i]);
            }
        }
        else groups.push(buttons);
    }

    return groups;
}

// fill in custom buttons referring to default mode bar buttons
function fillCustomButton(customButtons) {
    for(var i = 0; i < customButtons.length; i++) {
        var buttonGroup = customButtons[i];

        for(var j = 0; j < buttonGroup.length; j++) {
            var button = buttonGroup[j];

            if(typeof button === 'string') {
                if(modeBarButtons[button] !== undefined) {
                    customButtons[i][j] = modeBarButtons[button];
                }
                else {
                    throw new Error([
                        '*modeBarButtons* configuration options',
                        'invalid button name'
                    ].join(' '));
                }
            }
        }
    }

    return customButtons;
}

},{"../../plots/cartesian/axis_ids":745,"../../registry":825,"../../traces/scatter/subtypes":1071,"./buttons":629,"./modebar":632}],632:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');
var Icons = _dereq_('../../../build/ploticon');
var Parser = new DOMParser();

/**
 * UI controller for interactive plots
 * @Class
 * @Param {object} opts
 * @Param {object} opts.buttons    nested arrays of grouped buttons config objects
 * @Param {object} opts.container  container div to append modeBar
 * @Param {object} opts.graphInfo  primary plot object containing data and layout
 */
function ModeBar(opts) {
    this.container = opts.container;
    this.element = document.createElement('div');

    this.update(opts.graphInfo, opts.buttons);

    this.container.appendChild(this.element);
}

var proto = ModeBar.prototype;

/**
 * Update modeBar (buttons and logo)
 *
 * @param {object} graphInfo  primary plot object containing data and layout
 * @param {array of arrays} buttons nested arrays of grouped buttons to initialize
 *
 */
proto.update = function(graphInfo, buttons) {
    this.graphInfo = graphInfo;

    var context = this.graphInfo._context;
    var fullLayout = this.graphInfo._fullLayout;
    var modeBarId = 'modebar-' + fullLayout._uid;

    this.element.setAttribute('id', modeBarId);
    this._uid = modeBarId;

    this.element.className = 'modebar';
    if(context.displayModeBar === 'hover') this.element.className += ' modebar--hover ease-bg';

    if(fullLayout.modebar.orientation === 'v') {
        this.element.className += ' vertical';
        buttons = buttons.reverse();
    }

    var style = fullLayout.modebar;
    var bgSelector = context.displayModeBar === 'hover' ? '.js-plotly-plot .plotly:hover ' : '';

    Lib.deleteRelatedStyleRule(modeBarId);
    Lib.addRelatedStyleRule(modeBarId, bgSelector + '#' + modeBarId, 'background-color: ' + style.bgcolor);
    Lib.addRelatedStyleRule(modeBarId, '#' + modeBarId + ' .modebar-btn .icon path', 'fill: ' + style.color);
    Lib.addRelatedStyleRule(modeBarId, '#' + modeBarId + ' .modebar-btn:hover .icon path', 'fill: ' + style.activecolor);
    Lib.addRelatedStyleRule(modeBarId, '#' + modeBarId + ' .modebar-btn.active .icon path', 'fill: ' + style.activecolor);

    // if buttons or logo have changed, redraw modebar interior
    var needsNewButtons = !this.hasButtons(buttons);
    var needsNewLogo = (this.hasLogo !== context.displaylogo);
    var needsNewLocale = (this.locale !== context.locale);

    this.locale = context.locale;

    if(needsNewButtons || needsNewLogo || needsNewLocale) {
        this.removeAllButtons();

        this.updateButtons(buttons);

        if(context.watermark || context.displaylogo) {
            var logoGroup = this.getLogo();
            if(context.watermark) {
                logoGroup.className = logoGroup.className + ' watermark';
            }

            if(fullLayout.modebar.orientation === 'v') {
                this.element.insertBefore(logoGroup, this.element.childNodes[0]);
            } else {
                this.element.appendChild(logoGroup);
            }

            this.hasLogo = true;
        }
    }

    this.updateActiveButton();
};

proto.updateButtons = function(buttons) {
    var _this = this;

    this.buttons = buttons;
    this.buttonElements = [];
    this.buttonsNames = [];

    this.buttons.forEach(function(buttonGroup) {
        var group = _this.createGroup();

        buttonGroup.forEach(function(buttonConfig) {
            var buttonName = buttonConfig.name;
            if(!buttonName) {
                throw new Error('must provide button \'name\' in button config');
            }
            if(_this.buttonsNames.indexOf(buttonName) !== -1) {
                throw new Error('button name \'' + buttonName + '\' is taken');
            }
            _this.buttonsNames.push(buttonName);

            var button = _this.createButton(buttonConfig);
            _this.buttonElements.push(button);
            group.appendChild(button);
        });

        _this.element.appendChild(group);
    });
};

/**
 * Empty div for containing a group of buttons
 * @Return {HTMLelement}
 */
proto.createGroup = function() {
    var group = document.createElement('div');
    group.className = 'modebar-group';
    return group;
};

/**
 * Create a new button div and set constant and configurable attributes
 * @Param {object} config (see ./buttons.js for more info)
 * @Return {HTMLelement}
 */
proto.createButton = function(config) {
    var _this = this;
    var button = document.createElement('a');

    button.setAttribute('rel', 'tooltip');
    button.className = 'modebar-btn';

    var title = config.title;
    if(title === undefined) title = config.name;
    // for localization: allow title to be a callable that takes gd as arg
    else if(typeof title === 'function') title = title(this.graphInfo);

    if(title || title === 0) button.setAttribute('data-title', title);

    if(config.attr !== undefined) button.setAttribute('data-attr', config.attr);

    var val = config.val;
    if(val !== undefined) {
        if(typeof val === 'function') val = val(this.graphInfo);
        button.setAttribute('data-val', val);
    }

    var click = config.click;
    if(typeof click !== 'function') {
        throw new Error('must provide button \'click\' function in button config');
    }
    else {
        button.addEventListener('click', function(ev) {
            config.click(_this.graphInfo, ev);

            // only needed for 'hoverClosestGeo' which does not call relayout
            _this.updateActiveButton(ev.currentTarget);
        });
    }

    button.setAttribute('data-toggle', config.toggle || false);
    if(config.toggle) d3.select(button).classed('active', true);

    var icon = config.icon;
    if(typeof icon === 'function') {
        button.appendChild(icon());
    }
    else {
        button.appendChild(this.createIcon(icon || Icons.question));
    }
    button.setAttribute('data-gravity', config.gravity || 'n');

    return button;
};

/**
 * Add an icon to a button
 * @Param {object} thisIcon
 * @Param {number} thisIcon.width
 * @Param {string} thisIcon.path
 * @Param {string} thisIcon.color
 * @Return {HTMLelement}
 */
proto.createIcon = function(thisIcon) {
    var iconHeight = isNumeric(thisIcon.height) ?
        Number(thisIcon.height) :
        thisIcon.ascent - thisIcon.descent;
    var svgNS = 'http://www.w3.org/2000/svg';
    var icon;

    if(thisIcon.path) {
        icon = document.createElementNS(svgNS, 'svg');
        icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' '));
        icon.setAttribute('class', 'icon');

        var path = document.createElementNS(svgNS, 'path');
        path.setAttribute('d', thisIcon.path);

        if(thisIcon.transform) {
            path.setAttribute('transform', thisIcon.transform);
        }
        else if(thisIcon.ascent !== undefined) {
            // Legacy icon transform calculation
            path.setAttribute('transform', 'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')');
        }

        icon.appendChild(path);
    }

    if(thisIcon.svg) {
        var svgDoc = Parser.parseFromString(thisIcon.svg, 'application/xml');
        icon = svgDoc.childNodes[0];
    }

    icon.setAttribute('height', '1em');
    icon.setAttribute('width', '1em');

    return icon;
};

/**
 * Updates active button with attribute specified in layout
 * @Param {object} graphInfo plot object containing data and layout
 * @Return {HTMLelement}
 */
proto.updateActiveButton = function(buttonClicked) {
    var fullLayout = this.graphInfo._fullLayout;
    var dataAttrClicked = (buttonClicked !== undefined) ?
        buttonClicked.getAttribute('data-attr') :
        null;

    this.buttonElements.forEach(function(button) {
        var thisval = button.getAttribute('data-val') || true;
        var dataAttr = button.getAttribute('data-attr');
        var isToggleButton = (button.getAttribute('data-toggle') === 'true');
        var button3 = d3.select(button);

        // Use 'data-toggle' and 'buttonClicked' to toggle buttons
        // that have no one-to-one equivalent in fullLayout
        if(isToggleButton) {
            if(dataAttr === dataAttrClicked) {
                button3.classed('active', !button3.classed('active'));
            }
        }
        else {
            var val = (dataAttr === null) ?
                dataAttr :
                Lib.nestedProperty(fullLayout, dataAttr).get();

            button3.classed('active', val === thisval);
        }

    });
};

/**
 * Check if modeBar is configured as button configuration argument
 *
 * @Param {object} buttons 2d array of grouped button config objects
 * @Return {boolean}
 */
proto.hasButtons = function(buttons) {
    var currentButtons = this.buttons;

    if(!currentButtons) return false;

    if(buttons.length !== currentButtons.length) return false;

    for(var i = 0; i < buttons.length; ++i) {
        if(buttons[i].length !== currentButtons[i].length) return false;
        for(var j = 0; j < buttons[i].length; j++) {
            if(buttons[i][j].name !== currentButtons[i][j].name) return false;
        }
    }

    return true;
};

/**
 * @return {HTMLDivElement} The logo image wrapped in a group
 */
proto.getLogo = function() {
    var group = this.createGroup();
    var a = document.createElement('a');

    a.href = 'https://plot.ly/';
    a.target = '_blank';
    a.setAttribute('data-title', Lib._(this.graphInfo, 'Produced with Plotly'));
    a.className = 'modebar-btn plotlyjsicon modebar-btn--logo';

    a.appendChild(this.createIcon(Icons.newplotlylogo));

    group.appendChild(a);
    return group;
};

proto.removeAllButtons = function() {
    while(this.element.firstChild) {
        this.element.removeChild(this.element.firstChild);
    }

    this.hasLogo = false;
};

proto.destroy = function() {
    Lib.removeElement(this.container.querySelector('.modebar'));
    Lib.deleteRelatedStyleRule(this._uid);
};

function createModeBar(gd, buttons) {
    var fullLayout = gd._fullLayout;

    var modeBar = new ModeBar({
        graphInfo: gd,
        container: fullLayout._paperdiv.node(),
        buttons: buttons
    });

    if(fullLayout._privateplot) {
        d3.select(modeBar.element).append('span')
            .classed('badge-private float--left', true)
            .text('PRIVATE');
    }

    return modeBar;
}

module.exports = createModeBar;

},{"../../../build/ploticon":2,"../../lib":694,"d3":149,"fast-isnumeric":215}],633:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = _dereq_('../../plots/font_attributes');
var colorAttrs = _dereq_('../color/attributes');
var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;

var buttonAttrs = templatedArray('button', {
    visible: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'plot',
        
    },
    step: {
        valType: 'enumerated',
        
        values: ['month', 'year', 'day', 'hour', 'minute', 'second', 'all'],
        dflt: 'month',
        editType: 'plot',
        
    },
    stepmode: {
        valType: 'enumerated',
        
        values: ['backward', 'todate'],
        dflt: 'backward',
        editType: 'plot',
        
    },
    count: {
        valType: 'number',
        
        min: 0,
        dflt: 1,
        editType: 'plot',
        
    },
    label: {
        valType: 'string',
        
        editType: 'plot',
        
    },
    editType: 'plot',
    
});

module.exports = {
    visible: {
        valType: 'boolean',
        
        editType: 'plot',
        
    },

    buttons: buttonAttrs,

    x: {
        valType: 'number',
        min: -2,
        max: 3,
        
        editType: 'plot',
        
    },
    xanchor: {
        valType: 'enumerated',
        values: ['auto', 'left', 'center', 'right'],
        dflt: 'left',
        
        editType: 'plot',
        
    },
    y: {
        valType: 'number',
        min: -2,
        max: 3,
        
        editType: 'plot',
        
    },
    yanchor: {
        valType: 'enumerated',
        values: ['auto', 'top', 'middle', 'bottom'],
        dflt: 'bottom',
        
        editType: 'plot',
        
    },

    font: fontAttrs({
        editType: 'plot',
        
    }),

    bgcolor: {
        valType: 'color',
        dflt: colorAttrs.lightLine,
        
        editType: 'plot',
        
    },
    activecolor: {
        valType: 'color',
        
        editType: 'plot',
        
    },
    bordercolor: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'plot',
        
    },
    borderwidth: {
        valType: 'number',
        min: 0,
        dflt: 0,
        
        editType: 'plot',
        
    },
    editType: 'plot'
};

},{"../../plot_api/plot_template":732,"../../plots/font_attributes":769,"../color/attributes":570}],634:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {

    // 'y' position pad above counter axis domain
    yPad: 0.02,

    // minimum button width (regardless of text size)
    minButtonWidth: 30,

    // buttons rect radii
    rx: 3,
    ry: 3,

    // light fraction used to compute the 'activecolor' default
    lightAmount: 25,
    darkAmount: 10
};

},{}],635:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Color = _dereq_('../color');
var Template = _dereq_('../../plot_api/plot_template');
var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');

var attributes = _dereq_('./attributes');
var constants = _dereq_('./constants');


module.exports = function handleDefaults(containerIn, containerOut, layout, counterAxes, calendar) {
    var selectorIn = containerIn.rangeselector || {};
    var selectorOut = Template.newContainer(containerOut, 'rangeselector');

    function coerce(attr, dflt) {
        return Lib.coerce(selectorIn, selectorOut, attributes, attr, dflt);
    }

    var buttons = handleArrayContainerDefaults(selectorIn, selectorOut, {
        name: 'buttons',
        handleItemDefaults: buttonDefaults,
        calendar: calendar
    });

    var visible = coerce('visible', buttons.length > 0);
    if(visible) {
        var posDflt = getPosDflt(containerOut, layout, counterAxes);
        coerce('x', posDflt[0]);
        coerce('y', posDflt[1]);
        Lib.noneOrAll(containerIn, containerOut, ['x', 'y']);

        coerce('xanchor');
        coerce('yanchor');

        Lib.coerceFont(coerce, 'font', layout.font);

        var bgColor = coerce('bgcolor');
        coerce('activecolor', Color.contrast(bgColor, constants.lightAmount, constants.darkAmount));
        coerce('bordercolor');
        coerce('borderwidth');
    }
};

function buttonDefaults(buttonIn, buttonOut, selectorOut, opts) {
    var calendar = opts.calendar;

    function coerce(attr, dflt) {
        return Lib.coerce(buttonIn, buttonOut, attributes.buttons, attr, dflt);
    }

    var visible = coerce('visible');

    if(visible) {
        var step = coerce('step');
        if(step !== 'all') {
            if(calendar && calendar !== 'gregorian' && (step === 'month' || step === 'year')) {
                buttonOut.stepmode = 'backward';
            }
            else {
                coerce('stepmode');
            }

            coerce('count');
        }

        coerce('label');
    }
}

function getPosDflt(containerOut, layout, counterAxes) {
    var anchoredList = counterAxes.filter(function(ax) {
        return layout[ax].anchor === containerOut._id;
    });

    var posY = 0;
    for(var i = 0; i < anchoredList.length; i++) {
        var domain = layout[anchoredList[i]].domain;
        if(domain) posY = Math.max(domain[1], posY);
    }

    return [containerOut.domain[0], posY + constants.yPad];
}

},{"../../lib":694,"../../plot_api/plot_template":732,"../../plots/array_container_defaults":738,"../color":571,"./attributes":633,"./constants":634}],636:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Registry = _dereq_('../../registry');
var Plots = _dereq_('../../plots/plots');
var Color = _dereq_('../color');
var Drawing = _dereq_('../drawing');
var Lib = _dereq_('../../lib');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var axisIds = _dereq_('../../plots/cartesian/axis_ids');

var alignmentConstants = _dereq_('../../constants/alignment');
var LINE_SPACING = alignmentConstants.LINE_SPACING;
var FROM_TL = alignmentConstants.FROM_TL;
var FROM_BR = alignmentConstants.FROM_BR;

var constants = _dereq_('./constants');
var getUpdateObject = _dereq_('./get_update_object');


module.exports = function draw(gd) {
    var fullLayout = gd._fullLayout;

    var selectors = fullLayout._infolayer.selectAll('.rangeselector')
        .data(makeSelectorData(gd), selectorKeyFunc);

    selectors.enter().append('g')
        .classed('rangeselector', true);

    selectors.exit().remove();

    selectors.style({
        cursor: 'pointer',
        'pointer-events': 'all'
    });

    selectors.each(function(d) {
        var selector = d3.select(this);
        var axisLayout = d;
        var selectorLayout = axisLayout.rangeselector;

        var buttons = selector.selectAll('g.button')
            .data(Lib.filterVisible(selectorLayout.buttons));

        buttons.enter().append('g')
            .classed('button', true);

        buttons.exit().remove();

        buttons.each(function(d) {
            var button = d3.select(this);
            var update = getUpdateObject(axisLayout, d);

            d._isActive = isActive(axisLayout, d, update);

            button.call(drawButtonRect, selectorLayout, d);
            button.call(drawButtonText, selectorLayout, d, gd);

            button.on('click', function() {
                if(gd._dragged) return;

                Registry.call('_guiRelayout', gd, update);
            });

            button.on('mouseover', function() {
                d._isHovered = true;
                button.call(drawButtonRect, selectorLayout, d);
            });

            button.on('mouseout', function() {
                d._isHovered = false;
                button.call(drawButtonRect, selectorLayout, d);
            });
        });

        reposition(gd, buttons, selectorLayout, axisLayout._name, selector);
    });

};

function makeSelectorData(gd) {
    var axes = axisIds.list(gd, 'x', true);
    var data = [];

    for(var i = 0; i < axes.length; i++) {
        var axis = axes[i];

        if(axis.rangeselector && axis.rangeselector.visible) {
            data.push(axis);
        }
    }

    return data;
}

function selectorKeyFunc(d) {
    return d._id;
}

function isActive(axisLayout, opts, update) {
    if(opts.step === 'all') {
        return axisLayout.autorange === true;
    }
    else {
        var keys = Object.keys(update);

        return (
            axisLayout.range[0] === update[keys[0]] &&
            axisLayout.range[1] === update[keys[1]]
        );
    }
}

function drawButtonRect(button, selectorLayout, d) {
    var rect = Lib.ensureSingle(button, 'rect', 'selector-rect', function(s) {
        s.attr('shape-rendering', 'crispEdges');
    });

    rect.attr({
        'rx': constants.rx,
        'ry': constants.ry
    });

    rect.call(Color.stroke, selectorLayout.bordercolor)
        .call(Color.fill, getFillColor(selectorLayout, d))
        .style('stroke-width', selectorLayout.borderwidth + 'px');
}

function getFillColor(selectorLayout, d) {
    return (d._isActive || d._isHovered) ?
        selectorLayout.activecolor :
        selectorLayout.bgcolor;
}

function drawButtonText(button, selectorLayout, d, gd) {
    function textLayout(s) {
        svgTextUtils.convertToTspans(s, gd);
    }

    var text = Lib.ensureSingle(button, 'text', 'selector-text', function(s) {
        s.classed('user-select-none', true)
            .attr('text-anchor', 'middle');
    });

    text.call(Drawing.font, selectorLayout.font)
        .text(getLabel(d))
        .call(textLayout);
}

function getLabel(opts) {
    if(opts.label) return opts.label;

    if(opts.step === 'all') return 'all';

    return opts.count + opts.step.charAt(0);
}

function reposition(gd, buttons, opts, axName, selector) {
    var width = 0;
    var height = 0;

    var borderWidth = opts.borderwidth;

    buttons.each(function() {
        var button = d3.select(this);
        var text = button.select('.selector-text');

        var tHeight = opts.font.size * LINE_SPACING;
        var hEff = Math.max(tHeight * svgTextUtils.lineCount(text), 16) + 3;

        height = Math.max(height, hEff);
    });

    buttons.each(function() {
        var button = d3.select(this);
        var rect = button.select('.selector-rect');
        var text = button.select('.selector-text');

        var tWidth = text.node() && Drawing.bBox(text.node()).width;
        var tHeight = opts.font.size * LINE_SPACING;
        var tLines = svgTextUtils.lineCount(text);

        var wEff = Math.max(tWidth + 10, constants.minButtonWidth);

        // TODO add MathJax support

        // TODO add buttongap attribute

        button.attr('transform', 'translate(' +
            (borderWidth + width) + ',' + borderWidth +
        ')');

        rect.attr({
            x: 0,
            y: 0,
            width: wEff,
            height: height
        });

        svgTextUtils.positionText(text, wEff / 2,
            height / 2 - ((tLines - 1) * tHeight / 2) + 3);

        width += wEff + 5;
    });

    var graphSize = gd._fullLayout._size;
    var lx = graphSize.l + graphSize.w * opts.x;
    var ly = graphSize.t + graphSize.h * (1 - opts.y);

    var xanchor = 'left';
    if(Lib.isRightAnchor(opts)) {
        lx -= width;
        xanchor = 'right';
    }
    if(Lib.isCenterAnchor(opts)) {
        lx -= width / 2;
        xanchor = 'center';
    }

    var yanchor = 'top';
    if(Lib.isBottomAnchor(opts)) {
        ly -= height;
        yanchor = 'bottom';
    }
    if(Lib.isMiddleAnchor(opts)) {
        ly -= height / 2;
        yanchor = 'middle';
    }

    width = Math.ceil(width);
    height = Math.ceil(height);
    lx = Math.round(lx);
    ly = Math.round(ly);

    Plots.autoMargin(gd, axName + '-range-selector', {
        x: opts.x,
        y: opts.y,
        l: width * FROM_TL[xanchor],
        r: width * FROM_BR[xanchor],
        b: height * FROM_BR[yanchor],
        t: height * FROM_TL[yanchor]
    });

    selector.attr('transform', 'translate(' + lx + ',' + ly + ')');
}

},{"../../constants/alignment":666,"../../lib":694,"../../lib/svg_text_utils":718,"../../plots/cartesian/axis_ids":745,"../../plots/plots":806,"../../registry":825,"../color":571,"../drawing":592,"./constants":634,"./get_update_object":637,"d3":149}],637:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

module.exports = function getUpdateObject(axisLayout, buttonLayout) {
    var axName = axisLayout._name;
    var update = {};

    if(buttonLayout.step === 'all') {
        update[axName + '.autorange'] = true;
    }
    else {
        var xrange = getXRange(axisLayout, buttonLayout);

        update[axName + '.range[0]'] = xrange[0];
        update[axName + '.range[1]'] = xrange[1];
    }

    return update;
};

function getXRange(axisLayout, buttonLayout) {
    var currentRange = axisLayout.range;
    var base = new Date(axisLayout.r2l(currentRange[1]));
    var step = buttonLayout.step;
    var count = buttonLayout.count;
    var range0;

    switch(buttonLayout.stepmode) {
        case 'backward':
            range0 = axisLayout.l2r(+d3.time[step].utc.offset(base, -count));
            break;

        case 'todate':
            var base2 = d3.time[step].utc.offset(base, -count);

            range0 = axisLayout.l2r(+d3.time[step].utc.ceil(base2));
            break;
    }

    var range1 = currentRange[1];

    return [range0, range1];
}

},{"d3":149}],638:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'component',
    name: 'rangeselector',

    schema: {
        subplots: {
            xaxis: {rangeselector: _dereq_('./attributes')}
        }
    },

    layoutAttributes: _dereq_('./attributes'),
    handleDefaults: _dereq_('./defaults'),

    draw: _dereq_('./draw')
};

},{"./attributes":633,"./defaults":635,"./draw":636}],639:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorAttributes = _dereq_('../color/attributes');

module.exports = {
    bgcolor: {
        valType: 'color',
        dflt: colorAttributes.background,
        
        editType: 'plot',
        
    },
    bordercolor: {
        valType: 'color',
        dflt: colorAttributes.defaultLine,
        
        editType: 'plot',
        
    },
    borderwidth: {
        valType: 'integer',
        dflt: 0,
        min: 0,
        
        editType: 'plot',
        
    },
    autorange: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'calc',
        impliedEdits: {'range[0]': undefined, 'range[1]': undefined},
        
    },
    range: {
        valType: 'info_array',
        
        items: [
            {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}},
            {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}}
        ],
        editType: 'calc',
        impliedEdits: {'autorange': false},
        
    },
    thickness: {
        valType: 'number',
        dflt: 0.15,
        min: 0,
        max: 1,
        
        editType: 'plot',
        
    },
    visible: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'calc',
        
    },
    editType: 'calc'
};

},{"../color/attributes":570}],640:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var listAxes = _dereq_('../../plots/cartesian/axis_ids').list;
var getAutoRange = _dereq_('../../plots/cartesian/autorange').getAutoRange;
var constants = _dereq_('./constants');

module.exports = function calcAutorange(gd) {
    var axes = listAxes(gd, 'x', true);

    // Compute new slider range using axis autorange if necessary.
    //
    // Copy back range to input range slider container to skip
    // this step in subsequent draw calls.

    for(var i = 0; i < axes.length; i++) {
        var ax = axes[i];
        var opts = ax[constants.name];

        if(opts && opts.visible && opts.autorange) {
            opts._input.autorange = true;
            opts._input.range = opts.range = getAutoRange(gd, ax);
        }
    }
};

},{"../../plots/cartesian/autorange":741,"../../plots/cartesian/axis_ids":745,"./constants":641}],641:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {

    // attribute container name
    name: 'rangeslider',

    // class names

    containerClassName: 'rangeslider-container',
    bgClassName: 'rangeslider-bg',
    rangePlotClassName: 'rangeslider-rangeplot',

    maskMinClassName: 'rangeslider-mask-min',
    maskMaxClassName: 'rangeslider-mask-max',
    slideBoxClassName: 'rangeslider-slidebox',

    grabberMinClassName: 'rangeslider-grabber-min',
    grabAreaMinClassName: 'rangeslider-grabarea-min',
    handleMinClassName: 'rangeslider-handle-min',

    grabberMaxClassName: 'rangeslider-grabber-max',
    grabAreaMaxClassName: 'rangeslider-grabarea-max',
    handleMaxClassName: 'rangeslider-handle-max',

    maskMinOppAxisClassName: 'rangeslider-mask-min-opp-axis',
    maskMaxOppAxisClassName: 'rangeslider-mask-max-opp-axis',

    // style constants

    maskColor: 'rgba(0,0,0,0.4)',
    maskOppAxisColor: 'rgba(0,0,0,0.2)',

    slideBoxFill: 'transparent',
    slideBoxCursor: 'ew-resize',

    grabAreaFill: 'transparent',
    grabAreaCursor: 'col-resize',
    grabAreaWidth: 10,

    handleWidth: 4,
    handleRadius: 1,
    handleStrokeWidth: 1,

    extraPad: 15
};

},{}],642:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Template = _dereq_('../../plot_api/plot_template');
var axisIds = _dereq_('../../plots/cartesian/axis_ids');

var attributes = _dereq_('./attributes');
var oppAxisAttrs = _dereq_('./oppaxis_attributes');

module.exports = function handleDefaults(layoutIn, layoutOut, axName) {
    var axIn = layoutIn[axName];
    var axOut = layoutOut[axName];

    if(!(axIn.rangeslider || layoutOut._requestRangeslider[axOut._id])) return;

    // not super proud of this (maybe store _ in axis object instead
    if(!Lib.isPlainObject(axIn.rangeslider)) {
        axIn.rangeslider = {};
    }

    var containerIn = axIn.rangeslider;
    var containerOut = Template.newContainer(axOut, 'rangeslider');

    function coerce(attr, dflt) {
        return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
    }

    var rangeContainerIn, rangeContainerOut;
    function coerceRange(attr, dflt) {
        return Lib.coerce(rangeContainerIn, rangeContainerOut, oppAxisAttrs, attr, dflt);
    }

    var visible = coerce('visible');
    if(!visible) return;

    coerce('bgcolor', layoutOut.plot_bgcolor);
    coerce('bordercolor');
    coerce('borderwidth');
    coerce('thickness');

    coerce('autorange', !axOut.isValidRange(containerIn.range));
    coerce('range');

    var subplots = layoutOut._subplots;
    if(subplots) {
        var yIds = subplots.cartesian
            .filter(function(subplotId) {
                return subplotId.substr(0, subplotId.indexOf('y')) === axisIds.name2id(axName);
            })
            .map(function(subplotId) {
                return subplotId.substr(subplotId.indexOf('y'), subplotId.length);
            });
        var yNames = Lib.simpleMap(yIds, axisIds.id2name);
        for(var i = 0; i < yNames.length; i++) {
            var yName = yNames[i];

            rangeContainerIn = containerIn[yName] || {};
            rangeContainerOut = Template.newContainer(containerOut, yName, 'yaxis');

            var yAxOut = layoutOut[yName];

            var rangemodeDflt;
            if(rangeContainerIn.range && yAxOut.isValidRange(rangeContainerIn.range)) {
                rangemodeDflt = 'fixed';
            }

            var rangeMode = coerceRange('rangemode', rangemodeDflt);
            if(rangeMode !== 'match') {
                coerceRange('range', yAxOut.range.slice());
            }
        }
    }

    // to map back range slider (auto) range
    containerOut._input = containerIn;
};

},{"../../lib":694,"../../plot_api/plot_template":732,"../../plots/cartesian/axis_ids":745,"./attributes":639,"./oppaxis_attributes":646}],643:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Registry = _dereq_('../../registry');
var Plots = _dereq_('../../plots/plots');

var Lib = _dereq_('../../lib');
var Drawing = _dereq_('../drawing');
var Color = _dereq_('../color');
var Titles = _dereq_('../titles');

var Cartesian = _dereq_('../../plots/cartesian');
var axisIDs = _dereq_('../../plots/cartesian/axis_ids');

var dragElement = _dereq_('../dragelement');
var setCursor = _dereq_('../../lib/setcursor');

var constants = _dereq_('./constants');

module.exports = function(gd) {
    var fullLayout = gd._fullLayout;
    var rangeSliderData = fullLayout._rangeSliderData;
    for(var i = 0; i < rangeSliderData.length; i++) {
        var opts = rangeSliderData[i][constants.name];
        // fullLayout._uid may not exist when we call makeData
        opts._clipId = opts._id + '-' + fullLayout._uid;
    }

    /*
     * <g container />
     *  <rect bg />
     *  < .... range plot />
     *  <rect mask-min />
     *  <rect mask-max />
     *  <rect slidebox />
     *  <g grabber-min />
     *      <rect handle-min />
     *      <rect grabare-min />
     *  <g grabber-max />
     *      <rect handle-max />
     *      <rect grabare-max />
     *
     *  ...
     */

    function keyFunction(axisOpts) {
        return axisOpts._name;
    }

    var rangeSliders = fullLayout._infolayer
        .selectAll('g.' + constants.containerClassName)
        .data(rangeSliderData, keyFunction);

    // remove exiting sliders and their corresponding clip paths
    rangeSliders.exit().each(function(axisOpts) {
        var opts = axisOpts[constants.name];
        fullLayout._topdefs.select('#' + opts._clipId).remove();
    }).remove();

    // return early if no range slider is visible
    if(rangeSliderData.length === 0) return;

    rangeSliders.enter().append('g')
        .classed(constants.containerClassName, true)
        .attr('pointer-events', 'all');

    // for all present range sliders
    rangeSliders.each(function(axisOpts) {
        var rangeSlider = d3.select(this);
        var opts = axisOpts[constants.name];
        var oppAxisOpts = fullLayout[axisIDs.id2name(axisOpts.anchor)];
        var oppAxisRangeOpts = opts[axisIDs.id2name(axisOpts.anchor)];

        // update range
        // Expand slider range to the axis range
        if(opts.range) {
            var rng = Lib.simpleMap(opts.range, axisOpts.r2l);
            var axRng = Lib.simpleMap(axisOpts.range, axisOpts.r2l);
            var newRng;

            if(axRng[0] < axRng[1]) {
                newRng = [
                    Math.min(rng[0], axRng[0]),
                    Math.max(rng[1], axRng[1])
                ];
            } else {
                newRng = [
                    Math.max(rng[0], axRng[0]),
                    Math.min(rng[1], axRng[1])
                ];
            }

            opts.range = opts._input.range = Lib.simpleMap(newRng, axisOpts.l2r);
        }

        axisOpts.cleanRange('rangeslider.range');

        // update range slider dimensions

        var margin = fullLayout.margin;
        var graphSize = fullLayout._size;
        var domain = axisOpts.domain;
        var tickHeight = opts._tickHeight;

        var oppBottom = opts._oppBottom;

        opts._width = graphSize.w * (domain[1] - domain[0]);

        var x = Math.round(margin.l + (graphSize.w * domain[0]));

        var y = Math.round(
            graphSize.t + graphSize.h * (1 - oppBottom) +
            tickHeight +
            opts._offsetShift + constants.extraPad
        );

        rangeSlider.attr('transform', 'translate(' + x + ',' + y + ')');

        // update data <--> pixel coordinate conversion methods

        var range0 = axisOpts.r2l(opts.range[0]);
        var range1 = axisOpts.r2l(opts.range[1]);
        var dist = range1 - range0;

        opts.p2d = function(v) {
            return (v / opts._width) * dist + range0;
        };

        opts.d2p = function(v) {
            return (v - range0) / dist * opts._width;
        };

        opts._rl = [range0, range1];

        if(oppAxisRangeOpts.rangemode !== 'match') {
            var range0OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[0]);
            var range1OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[1]);
            var distOppAxis = range1OppAxis - range0OppAxis;

            opts.d2pOppAxis = function(v) {
                return (v - range0OppAxis) / distOppAxis * opts._height;
            };
        }

        // update inner nodes

        rangeSlider
            .call(drawBg, gd, axisOpts, opts)
            .call(addClipPath, gd, axisOpts, opts)
            .call(drawRangePlot, gd, axisOpts, opts)
            .call(drawMasks, gd, axisOpts, opts, oppAxisRangeOpts)
            .call(drawSlideBox, gd, axisOpts, opts)
            .call(drawGrabbers, gd, axisOpts, opts);

        // setup drag element
        setupDragElement(rangeSlider, gd, axisOpts, opts);

        // update current range
        setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts);

        // title goes next to range slider instead of tick labels, so
        // just take it over and draw it from here
        if(axisOpts.side === 'bottom') {
            Titles.draw(gd, axisOpts._id + 'title', {
                propContainer: axisOpts,
                propName: axisOpts._name + '.title',
                placeholder: fullLayout._dfltTitle.x,
                attributes: {
                    x: axisOpts._offset + axisOpts._length / 2,
                    y: y + opts._height + opts._offsetShift + 10 + 1.5 * axisOpts.title.font.size,
                    'text-anchor': 'middle'
                }
            });
        }
    });
};

function setupDragElement(rangeSlider, gd, axisOpts, opts) {
    var slideBox = rangeSlider.select('rect.' + constants.slideBoxClassName).node();
    var grabAreaMin = rangeSlider.select('rect.' + constants.grabAreaMinClassName).node();
    var grabAreaMax = rangeSlider.select('rect.' + constants.grabAreaMaxClassName).node();

    rangeSlider.on('mousedown', function() {
        var event = d3.event;
        var target = event.target;
        var startX = event.clientX;
        var offsetX = startX - rangeSlider.node().getBoundingClientRect().left;
        var minVal = opts.d2p(axisOpts._rl[0]);
        var maxVal = opts.d2p(axisOpts._rl[1]);

        var dragCover = dragElement.coverSlip();

        dragCover.addEventListener('mousemove', mouseMove);
        dragCover.addEventListener('mouseup', mouseUp);

        function mouseMove(e) {
            var delta = +e.clientX - startX;
            var pixelMin, pixelMax, cursor;

            switch(target) {
                case slideBox:
                    cursor = 'ew-resize';
                    pixelMin = minVal + delta;
                    pixelMax = maxVal + delta;
                    break;

                case grabAreaMin:
                    cursor = 'col-resize';
                    pixelMin = minVal + delta;
                    pixelMax = maxVal;
                    break;

                case grabAreaMax:
                    cursor = 'col-resize';
                    pixelMin = minVal;
                    pixelMax = maxVal + delta;
                    break;

                default:
                    cursor = 'ew-resize';
                    pixelMin = offsetX;
                    pixelMax = offsetX + delta;
                    break;
            }

            if(pixelMax < pixelMin) {
                var tmp = pixelMax;
                pixelMax = pixelMin;
                pixelMin = tmp;
            }

            opts._pixelMin = pixelMin;
            opts._pixelMax = pixelMax;

            setCursor(d3.select(dragCover), cursor);
            setDataRange(rangeSlider, gd, axisOpts, opts);
        }

        function mouseUp() {
            dragCover.removeEventListener('mousemove', mouseMove);
            dragCover.removeEventListener('mouseup', mouseUp);
            Lib.removeElement(dragCover);
        }
    });
}

function setDataRange(rangeSlider, gd, axisOpts, opts) {

    function clamp(v) {
        return axisOpts.l2r(Lib.constrain(v, opts._rl[0], opts._rl[1]));
    }

    var dataMin = clamp(opts.p2d(opts._pixelMin));
    var dataMax = clamp(opts.p2d(opts._pixelMax));

    window.requestAnimationFrame(function() {
        Registry.call('_guiRelayout', gd, axisOpts._name + '.range', [dataMin, dataMax]);
    });
}

function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) {
    var hw2 = constants.handleWidth / 2;

    function clamp(v) {
        return Lib.constrain(v, 0, opts._width);
    }

    function clampOppAxis(v) {
        return Lib.constrain(v, 0, opts._height);
    }

    function clampHandle(v) {
        return Lib.constrain(v, -hw2, opts._width + hw2);
    }

    var pixelMin = clamp(opts.d2p(axisOpts._rl[0]));
    var pixelMax = clamp(opts.d2p(axisOpts._rl[1]));

    rangeSlider.select('rect.' + constants.slideBoxClassName)
        .attr('x', pixelMin)
        .attr('width', pixelMax - pixelMin);

    rangeSlider.select('rect.' + constants.maskMinClassName)
        .attr('width', pixelMin);

    rangeSlider.select('rect.' + constants.maskMaxClassName)
        .attr('x', pixelMax)
        .attr('width', opts._width - pixelMax);

    if(oppAxisRangeOpts.rangemode !== 'match') {
        var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1]));
        var pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0]));

        rangeSlider.select('rect.' + constants.maskMinOppAxisClassName)
            .attr('x', pixelMin)
            .attr('height', pixelMinOppAxis)
            .attr('width', pixelMax - pixelMin);

        rangeSlider.select('rect.' + constants.maskMaxOppAxisClassName)
            .attr('x', pixelMin)
            .attr('y', pixelMaxOppAxis)
            .attr('height', opts._height - pixelMaxOppAxis)
            .attr('width', pixelMax - pixelMin);

        rangeSlider.select('rect.' + constants.slideBoxClassName)
            .attr('y', pixelMinOppAxis)
            .attr('height', pixelMaxOppAxis - pixelMinOppAxis);
    }

    // add offset for crispier corners
    // https://github.com/plotly/plotly.js/pull/1409
    var offset = 0.5;

    var xMin = Math.round(clampHandle(pixelMin - hw2)) - offset;
    var xMax = Math.round(clampHandle(pixelMax - hw2)) + offset;

    rangeSlider.select('g.' + constants.grabberMinClassName)
        .attr('transform', 'translate(' + xMin + ',' + offset + ')');

    rangeSlider.select('g.' + constants.grabberMaxClassName)
        .attr('transform', 'translate(' + xMax + ',' + offset + ')');
}

function drawBg(rangeSlider, gd, axisOpts, opts) {
    var bg = Lib.ensureSingle(rangeSlider, 'rect', constants.bgClassName, function(s) {
        s.attr({
            x: 0,
            y: 0,
            'shape-rendering': 'crispEdges'
        });
    });

    var borderCorrect = (opts.borderwidth % 2) === 0 ?
        opts.borderwidth :
        opts.borderwidth - 1;

    var offsetShift = -opts._offsetShift;
    var lw = Drawing.crispRound(gd, opts.borderwidth);

    bg.attr({
        width: opts._width + borderCorrect,
        height: opts._height + borderCorrect,
        transform: 'translate(' + offsetShift + ',' + offsetShift + ')',
        fill: opts.bgcolor,
        stroke: opts.bordercolor,
        'stroke-width': lw
    });
}

function addClipPath(rangeSlider, gd, axisOpts, opts) {
    var fullLayout = gd._fullLayout;

    var clipPath = Lib.ensureSingleById(fullLayout._topdefs, 'clipPath', opts._clipId, function(s) {
        s.append('rect').attr({ x: 0, y: 0 });
    });

    clipPath.select('rect').attr({
        width: opts._width,
        height: opts._height
    });
}

function drawRangePlot(rangeSlider, gd, axisOpts, opts) {
    var calcData = gd.calcdata;

    var rangePlots = rangeSlider.selectAll('g.' + constants.rangePlotClassName)
        .data(axisOpts._subplotsWith, Lib.identity);

    rangePlots.enter().append('g')
        .attr('class', function(id) { return constants.rangePlotClassName + ' ' + id; })
        .call(Drawing.setClipUrl, opts._clipId, gd);

    rangePlots.order();

    rangePlots.exit().remove();

    var mainplotinfo;

    rangePlots.each(function(id, i) {
        var plotgroup = d3.select(this);
        var isMainPlot = (i === 0);

        var oppAxisOpts = axisIDs.getFromId(gd, id, 'y');
        var oppAxisName = oppAxisOpts._name;
        var oppAxisRangeOpts = opts[oppAxisName];

        var mockFigure = {
            data: [],
            layout: {
                xaxis: {
                    type: axisOpts.type,
                    domain: [0, 1],
                    range: opts.range.slice(),
                    calendar: axisOpts.calendar
                },
                width: opts._width,
                height: opts._height,
                margin: { t: 0, b: 0, l: 0, r: 0 }
            },
            _context: gd._context
        };

        mockFigure.layout[oppAxisName] = {
            type: oppAxisOpts.type,
            domain: [0, 1],
            range: oppAxisRangeOpts.rangemode !== 'match' ? oppAxisRangeOpts.range.slice() : oppAxisOpts.range.slice(),
            calendar: oppAxisOpts.calendar
        };

        Plots.supplyDefaults(mockFigure);

        var xa = mockFigure._fullLayout.xaxis;
        var ya = mockFigure._fullLayout[oppAxisName];

        xa.clearCalc();
        xa.setScale();
        ya.clearCalc();
        ya.setScale();

        var plotinfo = {
            id: id,
            plotgroup: plotgroup,
            xaxis: xa,
            yaxis: ya,
            isRangePlot: true
        };

        if(isMainPlot) mainplotinfo = plotinfo;
        else {
            plotinfo.mainplot = 'xy';
            plotinfo.mainplotinfo = mainplotinfo;
        }

        Cartesian.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id));
    });
}

function filterRangePlotCalcData(calcData, subplotId) {
    var out = [];

    for(var i = 0; i < calcData.length; i++) {
        var calcTrace = calcData[i];
        var trace = calcTrace[0].trace;

        if(trace.xaxis + trace.yaxis === subplotId) {
            out.push(calcTrace);
        }
    }

    return out;
}

function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) {
    var maskMin = Lib.ensureSingle(rangeSlider, 'rect', constants.maskMinClassName, function(s) {
        s.attr({
            x: 0,
            y: 0,
            'shape-rendering': 'crispEdges'
        });
    });

    maskMin
        .attr('height', opts._height)
        .call(Color.fill, constants.maskColor);

    var maskMax = Lib.ensureSingle(rangeSlider, 'rect', constants.maskMaxClassName, function(s) {
        s.attr({
            y: 0,
            'shape-rendering': 'crispEdges'
        });
    });

    maskMax
        .attr('height', opts._height)
        .call(Color.fill, constants.maskColor);

    // masks used for oppAxis zoom
    if(oppAxisRangeOpts.rangemode !== 'match') {
        var maskMinOppAxis = Lib.ensureSingle(rangeSlider, 'rect', constants.maskMinOppAxisClassName, function(s) {
            s.attr({
                y: 0,
                'shape-rendering': 'crispEdges'
            });
        });

        maskMinOppAxis
            .attr('width', opts._width)
            .call(Color.fill, constants.maskOppAxisColor);

        var maskMaxOppAxis = Lib.ensureSingle(rangeSlider, 'rect', constants.maskMaxOppAxisClassName, function(s) {
            s.attr({
                y: 0,
                'shape-rendering': 'crispEdges'
            });
        });

        maskMaxOppAxis
            .attr('width', opts._width)
            .style('border-top', constants.maskOppBorder)
            .call(Color.fill, constants.maskOppAxisColor);
    }
}

function drawSlideBox(rangeSlider, gd, axisOpts, opts) {
    if(gd._context.staticPlot) return;

    var slideBox = Lib.ensureSingle(rangeSlider, 'rect', constants.slideBoxClassName, function(s) {
        s.attr({
            y: 0,
            cursor: constants.slideBoxCursor,
            'shape-rendering': 'crispEdges'
        });
    });

    slideBox.attr({
        height: opts._height,
        fill: constants.slideBoxFill
    });
}

function drawGrabbers(rangeSlider, gd, axisOpts, opts) {
    // <g grabber />
    var grabberMin = Lib.ensureSingle(rangeSlider, 'g', constants.grabberMinClassName);
    var grabberMax = Lib.ensureSingle(rangeSlider, 'g', constants.grabberMaxClassName);

    // <g handle />
    var handleFixAttrs = {
        x: 0,
        width: constants.handleWidth,
        rx: constants.handleRadius,
        fill: Color.background,
        stroke: Color.defaultLine,
        'stroke-width': constants.handleStrokeWidth,
        'shape-rendering': 'crispEdges'
    };
    var handleDynamicAttrs = {
        y: Math.round(opts._height / 4),
        height: Math.round(opts._height / 2),
    };
    var handleMin = Lib.ensureSingle(grabberMin, 'rect', constants.handleMinClassName, function(s) {
        s.attr(handleFixAttrs);
    });
    handleMin.attr(handleDynamicAttrs);

    var handleMax = Lib.ensureSingle(grabberMax, 'rect', constants.handleMaxClassName, function(s) {
        s.attr(handleFixAttrs);
    });
    handleMax.attr(handleDynamicAttrs);

    // <g grabarea />
    if(gd._context.staticPlot) return;

    var grabAreaFixAttrs = {
        width: constants.grabAreaWidth,
        x: 0,
        y: 0,
        fill: constants.grabAreaFill,
        cursor: constants.grabAreaCursor
    };

    var grabAreaMin = Lib.ensureSingle(grabberMin, 'rect', constants.grabAreaMinClassName, function(s) {
        s.attr(grabAreaFixAttrs);
    });
    grabAreaMin.attr('height', opts._height);

    var grabAreaMax = Lib.ensureSingle(grabberMax, 'rect', constants.grabAreaMaxClassName, function(s) {
        s.attr(grabAreaFixAttrs);
    });
    grabAreaMax.attr('height', opts._height);
}

},{"../../lib":694,"../../lib/setcursor":714,"../../plots/cartesian":754,"../../plots/cartesian/axis_ids":745,"../../plots/plots":806,"../../registry":825,"../color":571,"../dragelement":589,"../drawing":592,"../titles":659,"./constants":641,"d3":149}],644:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var axisIDs = _dereq_('../../plots/cartesian/axis_ids');
var constants = _dereq_('./constants');
var name = constants.name;

function isVisible(ax) {
    var rangeSlider = ax && ax[name];
    return rangeSlider && rangeSlider.visible;
}
exports.isVisible = isVisible;

exports.makeData = function(fullLayout) {
    var axes = axisIDs.list({ _fullLayout: fullLayout }, 'x', true);
    var margin = fullLayout.margin;
    var rangeSliderData = [];

    if(!fullLayout._has('gl2d')) {
        for(var i = 0; i < axes.length; i++) {
            var ax = axes[i];

            if(isVisible(ax)) {
                rangeSliderData.push(ax);

                var opts = ax[name];
                opts._id = name + ax._id;
                opts._height = (fullLayout.height - margin.b - margin.t) * opts.thickness;
                opts._offsetShift = Math.floor(opts.borderwidth / 2);
            }
        }
    }

    fullLayout._rangeSliderData = rangeSliderData;
};

exports.autoMarginOpts = function(gd, ax) {
    var opts = ax[name];

    var oppBottom = Infinity;
    var counterAxes = ax._counterAxes;
    for(var j = 0; j < counterAxes.length; j++) {
        var counterId = counterAxes[j];
        var oppAxis = axisIDs.getFromId(gd, counterId);
        oppBottom = Math.min(oppBottom, oppAxis.domain[0]);
    }
    opts._oppBottom = oppBottom;

    var tickHeight = (ax.side === 'bottom' && ax._boundingBox.height) || 0;
    opts._tickHeight = tickHeight;

    return {
        x: 0,
        y: oppBottom,
        l: 0,
        r: 0,
        t: 0,
        b: opts._height + gd._fullLayout.margin.b + tickHeight,
        pad: constants.extraPad + opts._offsetShift * 2
    };
};

},{"../../plots/cartesian/axis_ids":745,"./constants":641}],645:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var attrs = _dereq_('./attributes');
var oppAxisAttrs = _dereq_('./oppaxis_attributes');
var helpers = _dereq_('./helpers');

module.exports = {
    moduleType: 'component',
    name: 'rangeslider',

    schema: {
        subplots: {
            xaxis: {
                rangeslider: Lib.extendFlat({}, attrs, {
                    yaxis: oppAxisAttrs
                })
            }
        }
    },

    layoutAttributes: _dereq_('./attributes'),
    handleDefaults: _dereq_('./defaults'),
    calcAutorange: _dereq_('./calc_autorange'),
    draw: _dereq_('./draw'),
    isVisible: helpers.isVisible,
    makeData: helpers.makeData,
    autoMarginOpts: helpers.autoMarginOpts
};

},{"../../lib":694,"./attributes":639,"./calc_autorange":640,"./defaults":642,"./draw":643,"./helpers":644,"./oppaxis_attributes":646}],646:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    // not really a 'subplot' attribute container,
    // but this is the flag we use to denote attributes that
    // support yaxis, yaxis2, yaxis3, ... counters
    _isSubplotObj: true,

    rangemode: {
        valType: 'enumerated',
        values: ['auto', 'fixed', 'match'],
        dflt: 'match',
        
        editType: 'calc',
        
    },
    range: {
        valType: 'info_array',
        
        items: [
            {valType: 'any', editType: 'plot'},
            {valType: 'any', editType: 'plot'}
        ],
        editType: 'plot',
        
    },
    editType: 'calc'
};

},{}],647:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var annAttrs = _dereq_('../annotations/attributes');
var scatterLineAttrs = _dereq_('../../traces/scatter/attributes').line;
var dash = _dereq_('../drawing/attributes').dash;
var extendFlat = _dereq_('../../lib/extend').extendFlat;
var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;

module.exports = templatedArray('shape', {
    visible: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'calc+arraydraw',
        
    },

    type: {
        valType: 'enumerated',
        values: ['circle', 'rect', 'path', 'line'],
        
        editType: 'calc+arraydraw',
        
    },

    layer: {
        valType: 'enumerated',
        values: ['below', 'above'],
        dflt: 'above',
        
        editType: 'arraydraw',
        
    },

    xref: extendFlat({}, annAttrs.xref, {
        
    }),
    xsizemode: {
        valType: 'enumerated',
        values: ['scaled', 'pixel'],
        dflt: 'scaled',
        
        editType: 'calc+arraydraw',
        
    },
    xanchor: {
        valType: 'any',
        
        editType: 'calc+arraydraw',
        
    },
    x0: {
        valType: 'any',
        
        editType: 'calc+arraydraw',
        
    },
    x1: {
        valType: 'any',
        
        editType: 'calc+arraydraw',
        
    },

    yref: extendFlat({}, annAttrs.yref, {
        
    }),
    ysizemode: {
        valType: 'enumerated',
        values: ['scaled', 'pixel'],
        dflt: 'scaled',
        
        editType: 'calc+arraydraw',
        
    },
    yanchor: {
        valType: 'any',
        
        editType: 'calc+arraydraw',
        
    },
    y0: {
        valType: 'any',
        
        editType: 'calc+arraydraw',
        
    },
    y1: {
        valType: 'any',
        
        editType: 'calc+arraydraw',
        
    },

    path: {
        valType: 'string',
        
        editType: 'calc+arraydraw',
        
    },

    opacity: {
        valType: 'number',
        min: 0,
        max: 1,
        dflt: 1,
        
        editType: 'arraydraw',
        
    },
    line: {
        color: extendFlat({}, scatterLineAttrs.color, {editType: 'arraydraw'}),
        width: extendFlat({}, scatterLineAttrs.width, {editType: 'calc+arraydraw'}),
        dash: extendFlat({}, dash, {editType: 'arraydraw'}),
        
        editType: 'calc+arraydraw'
    },
    fillcolor: {
        valType: 'color',
        dflt: 'rgba(0,0,0,0)',
        
        editType: 'arraydraw',
        
    },
    editType: 'arraydraw'
});

},{"../../lib/extend":684,"../../plot_api/plot_template":732,"../../traces/scatter/attributes":1047,"../annotations/attributes":554,"../drawing/attributes":591}],648:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');

var constants = _dereq_('./constants');
var helpers = _dereq_('./helpers');


module.exports = function calcAutorange(gd) {
    var fullLayout = gd._fullLayout;
    var shapeList = Lib.filterVisible(fullLayout.shapes);

    if(!shapeList.length || !gd._fullData.length) return;

    for(var i = 0; i < shapeList.length; i++) {
        var shape = shapeList[i];
        shape._extremes = {};

        var ax, bounds;

        if(shape.xref !== 'paper') {
            var vx0 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x0;
            var vx1 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x1;
            ax = Axes.getFromId(gd, shape.xref);

            bounds = shapeBounds(ax, vx0, vx1, shape.path, constants.paramIsX);
            if(bounds) {
                shape._extremes[ax._id] = Axes.findExtremes(ax, bounds, calcXPaddingOptions(shape));
            }
        }

        if(shape.yref !== 'paper') {
            var vy0 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y0;
            var vy1 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y1;
            ax = Axes.getFromId(gd, shape.yref);

            bounds = shapeBounds(ax, vy0, vy1, shape.path, constants.paramIsY);
            if(bounds) {
                shape._extremes[ax._id] = Axes.findExtremes(ax, bounds, calcYPaddingOptions(shape));
            }
        }
    }
};

function calcXPaddingOptions(shape) {
    return calcPaddingOptions(shape.line.width, shape.xsizemode, shape.x0, shape.x1, shape.path, false);
}

function calcYPaddingOptions(shape) {
    return calcPaddingOptions(shape.line.width, shape.ysizemode, shape.y0, shape.y1, shape.path, true);
}

function calcPaddingOptions(lineWidth, sizeMode, v0, v1, path, isYAxis) {
    var ppad = lineWidth / 2;
    var axisDirectionReverted = isYAxis;

    if(sizeMode === 'pixel') {
        var coords = path ?
            helpers.extractPathCoords(path, isYAxis ? constants.paramIsY : constants.paramIsX) :
            [v0, v1];
        var maxValue = Lib.aggNums(Math.max, null, coords);
        var minValue = Lib.aggNums(Math.min, null, coords);
        var beforePad = minValue < 0 ? Math.abs(minValue) + ppad : ppad;
        var afterPad = maxValue > 0 ? maxValue + ppad : ppad;

        return {
            ppad: ppad,
            ppadplus: axisDirectionReverted ? beforePad : afterPad,
            ppadminus: axisDirectionReverted ? afterPad : beforePad
        };
    } else {
        return {ppad: ppad};
    }
}

function shapeBounds(ax, v0, v1, path, paramsToUse) {
    var convertVal = (ax.type === 'category' || ax.type === 'multicategory') ? ax.r2c : ax.d2c;

    if(v0 !== undefined) return [convertVal(v0), convertVal(v1)];
    if(!path) return;

    var min = Infinity;
    var max = -Infinity;
    var segments = path.match(constants.segmentRE);
    var i;
    var segment;
    var drawnParam;
    var params;
    var val;

    if(ax.type === 'date') convertVal = helpers.decodeDate(convertVal);

    for(i = 0; i < segments.length; i++) {
        segment = segments[i];
        drawnParam = paramsToUse[segment.charAt(0)].drawn;
        if(drawnParam === undefined) continue;

        params = segments[i].substr(1).match(constants.paramRE);
        if(!params || params.length < drawnParam) continue;

        val = convertVal(params[drawnParam]);
        if(val < min) min = val;
        if(val > max) max = val;
    }
    if(max >= min) return [min, max];
}

},{"../../lib":694,"../../plots/cartesian/axes":742,"./constants":649,"./helpers":652}],649:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


module.exports = {
    segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g,
    paramRE: /[^\s,]+/g,

    // which numbers in each path segment are x (or y) values
    // drawn is which param is a drawn point, as opposed to a
    // control point (which doesn't count toward autorange.
    // TODO: this means curved paths could extend beyond the
    // autorange bounds. This is a bit tricky to get right
    // unless we revert to bounding boxes, but perhaps there's
    // a calculation we could do...)
    paramIsX: {
        M: {0: true, drawn: 0},
        L: {0: true, drawn: 0},
        H: {0: true, drawn: 0},
        V: {},
        Q: {0: true, 2: true, drawn: 2},
        C: {0: true, 2: true, 4: true, drawn: 4},
        T: {0: true, drawn: 0},
        S: {0: true, 2: true, drawn: 2},
        // A: {0: true, 5: true},
        Z: {}
    },

    paramIsY: {
        M: {1: true, drawn: 1},
        L: {1: true, drawn: 1},
        H: {},
        V: {0: true, drawn: 0},
        Q: {1: true, 3: true, drawn: 3},
        C: {1: true, 3: true, 5: true, drawn: 5},
        T: {1: true, drawn: 1},
        S: {1: true, 3: true, drawn: 5},
        // A: {1: true, 6: true},
        Z: {}
    },

    numParams: {
        M: 2,
        L: 2,
        H: 1,
        V: 1,
        Q: 4,
        C: 6,
        T: 2,
        S: 4,
        // A: 7,
        Z: 0
    }
};

},{}],650:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');
var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');

var attributes = _dereq_('./attributes');
var helpers = _dereq_('./helpers');


module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
    handleArrayContainerDefaults(layoutIn, layoutOut, {
        name: 'shapes',
        handleItemDefaults: handleShapeDefaults
    });
};

function handleShapeDefaults(shapeIn, shapeOut, fullLayout) {
    function coerce(attr, dflt) {
        return Lib.coerce(shapeIn, shapeOut, attributes, attr, dflt);
    }

    var visible = coerce('visible');

    if(!visible) return;

    coerce('layer');
    coerce('opacity');
    coerce('fillcolor');
    coerce('line.color');
    coerce('line.width');
    coerce('line.dash');

    var dfltType = shapeIn.path ? 'path' : 'rect';
    var shapeType = coerce('type', dfltType);
    var xSizeMode = coerce('xsizemode');
    var ySizeMode = coerce('ysizemode');

    // positioning
    var axLetters = ['x', 'y'];
    for(var i = 0; i < 2; i++) {
        var axLetter = axLetters[i];
        var attrAnchor = axLetter + 'anchor';
        var sizeMode = axLetter === 'x' ? xSizeMode : ySizeMode;
        var gdMock = {_fullLayout: fullLayout};
        var ax;
        var pos2r;
        var r2pos;

        // xref, yref
        var axRef = Axes.coerceRef(shapeIn, shapeOut, gdMock, axLetter, '', 'paper');

        if(axRef !== 'paper') {
            ax = Axes.getFromId(gdMock, axRef);
            ax._shapeIndices.push(shapeOut._index);
            r2pos = helpers.rangeToShapePosition(ax);
            pos2r = helpers.shapePositionToRange(ax);
        }
        else {
            pos2r = r2pos = Lib.identity;
        }

        // Coerce x0, x1, y0, y1
        if(shapeType !== 'path') {
            var dflt0 = 0.25;
            var dflt1 = 0.75;

            // hack until V2.0 when log has regular range behavior - make it look like other
            // ranges to send to coerce, then put it back after
            // this is all to give reasonable default position behavior on log axes, which is
            // a pretty unimportant edge case so we could just ignore this.
            var attr0 = axLetter + '0';
            var attr1 = axLetter + '1';
            var in0 = shapeIn[attr0];
            var in1 = shapeIn[attr1];
            shapeIn[attr0] = pos2r(shapeIn[attr0], true);
            shapeIn[attr1] = pos2r(shapeIn[attr1], true);

            if(sizeMode === 'pixel') {
                coerce(attr0, 0);
                coerce(attr1, 10);
            } else {
                Axes.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflt0);
                Axes.coercePosition(shapeOut, gdMock, coerce, axRef, attr1, dflt1);
            }

            // hack part 2
            shapeOut[attr0] = r2pos(shapeOut[attr0]);
            shapeOut[attr1] = r2pos(shapeOut[attr1]);
            shapeIn[attr0] = in0;
            shapeIn[attr1] = in1;
        }

        // Coerce xanchor and yanchor
        if(sizeMode === 'pixel') {
            // Hack for log axis described above
            var inAnchor = shapeIn[attrAnchor];
            shapeIn[attrAnchor] = pos2r(shapeIn[attrAnchor], true);

            Axes.coercePosition(shapeOut, gdMock, coerce, axRef, attrAnchor, 0.25);

            // Hack part 2
            shapeOut[attrAnchor] = r2pos(shapeOut[attrAnchor]);
            shapeIn[attrAnchor] = inAnchor;
        }
    }

    if(shapeType === 'path') {
        coerce('path');
    }
    else {
        Lib.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']);
    }
}

},{"../../lib":694,"../../plots/array_container_defaults":738,"../../plots/cartesian/axes":742,"./attributes":647,"./helpers":652}],651:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');
var Color = _dereq_('../color');
var Drawing = _dereq_('../drawing');
var arrayEditor = _dereq_('../../plot_api/plot_template').arrayEditor;

var dragElement = _dereq_('../dragelement');
var setCursor = _dereq_('../../lib/setcursor');

var constants = _dereq_('./constants');
var helpers = _dereq_('./helpers');


// Shapes are stored in gd.layout.shapes, an array of objects
// index can point to one item in this array,
//  or non-numeric to simply add a new one
//  or -1 to modify all existing
// opt can be the full options object, or one key (to be set to value)
//  or undefined to simply redraw
// if opt is blank, val can be 'add' or a full options object to add a new
//  annotation at that point in the array, or 'remove' to delete this one

module.exports = {
    draw: draw,
    drawOne: drawOne
};

function draw(gd) {
    var fullLayout = gd._fullLayout;

    // Remove previous shapes before drawing new in shapes in fullLayout.shapes
    fullLayout._shapeUpperLayer.selectAll('path').remove();
    fullLayout._shapeLowerLayer.selectAll('path').remove();

    for(var k in fullLayout._plots) {
        var shapelayer = fullLayout._plots[k].shapelayer;
        if(shapelayer) shapelayer.selectAll('path').remove();
    }

    for(var i = 0; i < fullLayout.shapes.length; i++) {
        if(fullLayout.shapes[i].visible) {
            drawOne(gd, i);
        }
    }

    // may need to resurrect this if we put text (LaTeX) in shapes
    // return Plots.previousPromises(gd);
}

function drawOne(gd, index) {
    // remove the existing shape if there is one.
    // because indices can change, we need to look in all shape layers
    gd._fullLayout._paperdiv
        .selectAll('.shapelayer [data-index="' + index + '"]')
        .remove();

    var options = gd._fullLayout.shapes[index] || {};

    // this shape is gone - quit now after deleting it
    // TODO: use d3 idioms instead of deleting and redrawing every time
    if(!options._input || options.visible === false) return;

    if(options.layer !== 'below') {
        drawShape(gd._fullLayout._shapeUpperLayer);
    }
    else if(options.xref === 'paper' || options.yref === 'paper') {
        drawShape(gd._fullLayout._shapeLowerLayer);
    }
    else {
        var plotinfo = gd._fullLayout._plots[options.xref + options.yref];
        if(plotinfo) {
            var mainPlot = plotinfo.mainplotinfo || plotinfo;
            drawShape(mainPlot.shapelayer);
        }
        else {
            // Fall back to _shapeLowerLayer in case the requested subplot doesn't exist.
            // This can happen if you reference the shape to an x / y axis combination
            // that doesn't have any data on it (and layer is below)
            drawShape(gd._fullLayout._shapeLowerLayer);
        }
    }

    function drawShape(shapeLayer) {
        var attrs = {
            'data-index': index,
            'fill-rule': 'evenodd',
            d: getPathString(gd, options)
        };
        var lineColor = options.line.width ? options.line.color : 'rgba(0,0,0,0)';

        var path = shapeLayer.append('path')
            .attr(attrs)
            .style('opacity', options.opacity)
            .call(Color.stroke, lineColor)
            .call(Color.fill, options.fillcolor)
            .call(Drawing.dashLine, options.line.dash, options.line.width);

        setClipPath(path, gd, options);

        if(gd._context.edits.shapePosition) setupDragElement(gd, path, options, index, shapeLayer);
    }
}

function setClipPath(shapePath, gd, shapeOptions) {
    // note that for layer="below" the clipAxes can be different from the
    // subplot we're drawing this in. This could cause problems if the shape
    // spans two subplots. See https://github.com/plotly/plotly.js/issues/1452
    var clipAxes = (shapeOptions.xref + shapeOptions.yref).replace(/paper/g, '');

    Drawing.setClipUrl(
        shapePath,
        clipAxes ? 'clip' + gd._fullLayout._uid + clipAxes : null,
        gd
    );
}

function setupDragElement(gd, shapePath, shapeOptions, index, shapeLayer) {
    var MINWIDTH = 10;
    var MINHEIGHT = 10;

    var xPixelSized = shapeOptions.xsizemode === 'pixel';
    var yPixelSized = shapeOptions.ysizemode === 'pixel';
    var isLine = shapeOptions.type === 'line';
    var isPath = shapeOptions.type === 'path';

    var editHelpers = arrayEditor(gd.layout, 'shapes', shapeOptions);
    var modifyItem = editHelpers.modifyItem;

    var x0, y0, x1, y1, xAnchor, yAnchor;
    var n0, s0, w0, e0, optN, optS, optW, optE;
    var pathIn;

    // setup conversion functions
    var xa = Axes.getFromId(gd, shapeOptions.xref);
    var ya = Axes.getFromId(gd, shapeOptions.yref);
    var x2p = helpers.getDataToPixel(gd, xa);
    var y2p = helpers.getDataToPixel(gd, ya, true);
    var p2x = helpers.getPixelToData(gd, xa);
    var p2y = helpers.getPixelToData(gd, ya, true);

    var sensoryElement = obtainSensoryElement();
    var dragOptions = {
        element: sensoryElement.node(),
        gd: gd,
        prepFn: startDrag,
        doneFn: endDrag,
        clickFn: abortDrag
    };
    var dragMode;

    dragElement.init(dragOptions);

    sensoryElement.node().onmousemove = updateDragMode;

    function obtainSensoryElement() {
        return isLine ? createLineDragHandles() : shapePath;
    }

    function createLineDragHandles() {
        var minSensoryWidth = 10;
        var sensoryWidth = Math.max(shapeOptions.line.width, minSensoryWidth);

        // Helper shapes group
        // Note that by setting the `data-index` attr, it is ensured that
        // the helper group is purged in this modules `draw` function
        var g = shapeLayer.append('g')
          .attr('data-index', index);

        // Helper path for moving
        g.append('path')
          .attr('d', shapePath.attr('d'))
          .style({
              'cursor': 'move',
              'stroke-width': sensoryWidth,
              'stroke-opacity': '0' // ensure not visible
          });

        // Helper circles for resizing
        var circleStyle = {
            'fill-opacity': '0' // ensure not visible
        };
        var circleRadius = sensoryWidth / 2 > minSensoryWidth ? sensoryWidth / 2 : minSensoryWidth;

        g.append('circle')
          .attr({
              'data-line-point': 'start-point',
              'cx': xPixelSized ? x2p(shapeOptions.xanchor) + shapeOptions.x0 : x2p(shapeOptions.x0),
              'cy': yPixelSized ? y2p(shapeOptions.yanchor) - shapeOptions.y0 : y2p(shapeOptions.y0),
              'r': circleRadius
          })
          .style(circleStyle)
          .classed('cursor-grab', true);

        g.append('circle')
          .attr({
              'data-line-point': 'end-point',
              'cx': xPixelSized ? x2p(shapeOptions.xanchor) + shapeOptions.x1 : x2p(shapeOptions.x1),
              'cy': yPixelSized ? y2p(shapeOptions.yanchor) - shapeOptions.y1 : y2p(shapeOptions.y1),
              'r': circleRadius
          })
          .style(circleStyle)
          .classed('cursor-grab', true);

        return g;
    }

    function updateDragMode(evt) {
        if(isLine) {
            if(evt.target.tagName === 'path') {
                dragMode = 'move';
            } else {
                dragMode = evt.target.attributes['data-line-point'].value === 'start-point' ?
                  'resize-over-start-point' : 'resize-over-end-point';
            }
        } else {
            // element might not be on screen at time of setup,
            // so obtain bounding box here
            var dragBBox = dragOptions.element.getBoundingClientRect();

            // choose 'move' or 'resize'
            // based on initial position of cursor within the drag element
            var w = dragBBox.right - dragBBox.left;
            var h = dragBBox.bottom - dragBBox.top;
            var x = evt.clientX - dragBBox.left;
            var y = evt.clientY - dragBBox.top;
            var cursor = (!isPath && w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey) ?
                dragElement.getCursor(x / w, 1 - y / h) :
                'move';

            setCursor(shapePath, cursor);

            // possible values 'move', 'sw', 'w', 'se', 'e', 'ne', 'n', 'nw' and 'w'
            dragMode = cursor.split('-')[0];
        }
    }

    function startDrag(evt) {
        // setup update strings and initial values
        if(xPixelSized) {
            xAnchor = x2p(shapeOptions.xanchor);
        }
        if(yPixelSized) {
            yAnchor = y2p(shapeOptions.yanchor);
        }

        if(shapeOptions.type === 'path') {
            pathIn = shapeOptions.path;
        }
        else {
            x0 = xPixelSized ? shapeOptions.x0 : x2p(shapeOptions.x0);
            y0 = yPixelSized ? shapeOptions.y0 : y2p(shapeOptions.y0);
            x1 = xPixelSized ? shapeOptions.x1 : x2p(shapeOptions.x1);
            y1 = yPixelSized ? shapeOptions.y1 : y2p(shapeOptions.y1);
        }

        if(x0 < x1) {
            w0 = x0;
            optW = 'x0';
            e0 = x1;
            optE = 'x1';
        }
        else {
            w0 = x1;
            optW = 'x1';
            e0 = x0;
            optE = 'x0';
        }

        // For fixed size shapes take opposing direction of y-axis into account.
        // Hint: For data sized shapes this is done by the y2p function.
        if((!yPixelSized && y0 < y1) || (yPixelSized && y0 > y1)) {
            n0 = y0;
            optN = 'y0';
            s0 = y1;
            optS = 'y1';
        }
        else {
            n0 = y1;
            optN = 'y1';
            s0 = y0;
            optS = 'y0';
        }

        // setup dragMode and the corresponding handler
        updateDragMode(evt);
        renderVisualCues(shapeLayer, shapeOptions);
        deactivateClipPathTemporarily(shapePath, shapeOptions, gd);
        dragOptions.moveFn = (dragMode === 'move') ? moveShape : resizeShape;
    }

    function endDrag() {
        setCursor(shapePath);
        removeVisualCues(shapeLayer);

        // Don't rely on clipPath being activated during re-layout
        setClipPath(shapePath, gd, shapeOptions);
        Registry.call('_guiRelayout', gd, editHelpers.getUpdateObj());
    }

    function abortDrag() {
        removeVisualCues(shapeLayer);
    }

    function moveShape(dx, dy) {
        if(shapeOptions.type === 'path') {
            var noOp = function(coord) { return coord; };
            var moveX = noOp;
            var moveY = noOp;

            if(xPixelSized) {
                modifyItem('xanchor', shapeOptions.xanchor = p2x(xAnchor + dx));
            } else {
                moveX = function moveX(x) { return p2x(x2p(x) + dx); };
                if(xa && xa.type === 'date') moveX = helpers.encodeDate(moveX);
            }

            if(yPixelSized) {
                modifyItem('yanchor', shapeOptions.yanchor = p2y(yAnchor + dy));
            } else {
                moveY = function moveY(y) { return p2y(y2p(y) + dy); };
                if(ya && ya.type === 'date') moveY = helpers.encodeDate(moveY);
            }

            modifyItem('path', shapeOptions.path = movePath(pathIn, moveX, moveY));
        }
        else {
            if(xPixelSized) {
                modifyItem('xanchor', shapeOptions.xanchor = p2x(xAnchor + dx));
            } else {
                modifyItem('x0', shapeOptions.x0 = p2x(x0 + dx));
                modifyItem('x1', shapeOptions.x1 = p2x(x1 + dx));
            }

            if(yPixelSized) {
                modifyItem('yanchor', shapeOptions.yanchor = p2y(yAnchor + dy));
            } else {
                modifyItem('y0', shapeOptions.y0 = p2y(y0 + dy));
                modifyItem('y1', shapeOptions.y1 = p2y(y1 + dy));
            }
        }

        shapePath.attr('d', getPathString(gd, shapeOptions));
        renderVisualCues(shapeLayer, shapeOptions);
    }

    function resizeShape(dx, dy) {
        if(isPath) {
            // TODO: implement path resize, don't forget to update dragMode code
            var noOp = function(coord) { return coord; };
            var moveX = noOp;
            var moveY = noOp;

            if(xPixelSized) {
                modifyItem('xanchor', shapeOptions.xanchor = p2x(xAnchor + dx));
            } else {
                moveX = function moveX(x) { return p2x(x2p(x) + dx); };
                if(xa && xa.type === 'date') moveX = helpers.encodeDate(moveX);
            }

            if(yPixelSized) {
                modifyItem('yanchor', shapeOptions.yanchor = p2y(yAnchor + dy));
            } else {
                moveY = function moveY(y) { return p2y(y2p(y) + dy); };
                if(ya && ya.type === 'date') moveY = helpers.encodeDate(moveY);
            }

            modifyItem('path', shapeOptions.path = movePath(pathIn, moveX, moveY));
        }
        else if(isLine) {
            if(dragMode === 'resize-over-start-point') {
                var newX0 = x0 + dx;
                var newY0 = yPixelSized ? y0 - dy : y0 + dy;
                modifyItem('x0', shapeOptions.x0 = xPixelSized ? newX0 : p2x(newX0));
                modifyItem('y0', shapeOptions.y0 = yPixelSized ? newY0 : p2y(newY0));
            } else if(dragMode === 'resize-over-end-point') {
                var newX1 = x1 + dx;
                var newY1 = yPixelSized ? y1 - dy : y1 + dy;
                modifyItem('x1', shapeOptions.x1 = xPixelSized ? newX1 : p2x(newX1));
                modifyItem('y1', shapeOptions.y1 = yPixelSized ? newY1 : p2y(newY1));
            }
        }
        else {
            var newN = (~dragMode.indexOf('n')) ? n0 + dy : n0;
            var newS = (~dragMode.indexOf('s')) ? s0 + dy : s0;
            var newW = (~dragMode.indexOf('w')) ? w0 + dx : w0;
            var newE = (~dragMode.indexOf('e')) ? e0 + dx : e0;

            // Do things in opposing direction for y-axis.
            // Hint: for data-sized shapes the reversal of axis direction is done in p2y.
            if(~dragMode.indexOf('n') && yPixelSized) newN = n0 - dy;
            if(~dragMode.indexOf('s') && yPixelSized) newS = s0 - dy;

            // Update shape eventually. Again, be aware of the
            // opposing direction of the y-axis of fixed size shapes.
            if((!yPixelSized && newS - newN > MINHEIGHT) ||
              (yPixelSized && newN - newS > MINHEIGHT)) {
                modifyItem(optN, shapeOptions[optN] = yPixelSized ? newN : p2y(newN));
                modifyItem(optS, shapeOptions[optS] = yPixelSized ? newS : p2y(newS));
            }
            if(newE - newW > MINWIDTH) {
                modifyItem(optW, shapeOptions[optW] = xPixelSized ? newW : p2x(newW));
                modifyItem(optE, shapeOptions[optE] = xPixelSized ? newE : p2x(newE));
            }
        }

        shapePath.attr('d', getPathString(gd, shapeOptions));
        renderVisualCues(shapeLayer, shapeOptions);
    }

    function renderVisualCues(shapeLayer, shapeOptions) {
        if(xPixelSized || yPixelSized) {
            renderAnchor();
        }

        function renderAnchor() {
            var isNotPath = shapeOptions.type !== 'path';

            // d3 join with dummy data to satisfy d3 data-binding
            var visualCues = shapeLayer.selectAll('.visual-cue').data([0]);

            // Enter
            var strokeWidth = 1;
            visualCues.enter()
              .append('path')
              .attr({
                  'fill': '#fff',
                  'fill-rule': 'evenodd',
                  'stroke': '#000',
                  'stroke-width': strokeWidth
              })
              .classed('visual-cue', true);

            // Update
            var posX = x2p(
              xPixelSized ?
                shapeOptions.xanchor :
                Lib.midRange(
                  isNotPath ?
                    [shapeOptions.x0, shapeOptions.x1] :
                    helpers.extractPathCoords(shapeOptions.path, constants.paramIsX))
            );
            var posY = y2p(
              yPixelSized ?
                shapeOptions.yanchor :
                Lib.midRange(
                  isNotPath ?
                    [shapeOptions.y0, shapeOptions.y1] :
                    helpers.extractPathCoords(shapeOptions.path, constants.paramIsY))
            );

            posX = helpers.roundPositionForSharpStrokeRendering(posX, strokeWidth);
            posY = helpers.roundPositionForSharpStrokeRendering(posY, strokeWidth);

            if(xPixelSized && yPixelSized) {
                var crossPath = 'M' + (posX - 1 - strokeWidth) + ',' + (posY - 1 - strokeWidth) +
                  'h-8v2h8 v8h2v-8 h8v-2h-8 v-8h-2 Z';
                visualCues.attr('d', crossPath);
            } else if(xPixelSized) {
                var vBarPath = 'M' + (posX - 1 - strokeWidth) + ',' + (posY - 9 - strokeWidth) +
                  'v18 h2 v-18 Z';
                visualCues.attr('d', vBarPath);
            } else {
                var hBarPath = 'M' + (posX - 9 - strokeWidth) + ',' + (posY - 1 - strokeWidth) +
                  'h18 v2 h-18 Z';
                visualCues.attr('d', hBarPath);
            }
        }
    }

    function removeVisualCues(shapeLayer) {
        shapeLayer.selectAll('.visual-cue').remove();
    }

    function deactivateClipPathTemporarily(shapePath, shapeOptions, gd) {
        var xref = shapeOptions.xref;
        var yref = shapeOptions.yref;
        var xa = Axes.getFromId(gd, xref);
        var ya = Axes.getFromId(gd, yref);

        var clipAxes = '';
        if(xref !== 'paper' && !xa.autorange) clipAxes += xref;
        if(yref !== 'paper' && !ya.autorange) clipAxes += yref;

        Drawing.setClipUrl(
            shapePath,
            clipAxes ? 'clip' + gd._fullLayout._uid + clipAxes : null,
            gd
        );
    }
}

function getPathString(gd, options) {
    var type = options.type;
    var xa = Axes.getFromId(gd, options.xref);
    var ya = Axes.getFromId(gd, options.yref);
    var gs = gd._fullLayout._size;
    var x2r, x2p, y2r, y2p;
    var x0, x1, y0, y1;

    if(xa) {
        x2r = helpers.shapePositionToRange(xa);
        x2p = function(v) { return xa._offset + xa.r2p(x2r(v, true)); };
    }
    else {
        x2p = function(v) { return gs.l + gs.w * v; };
    }

    if(ya) {
        y2r = helpers.shapePositionToRange(ya);
        y2p = function(v) { return ya._offset + ya.r2p(y2r(v, true)); };
    }
    else {
        y2p = function(v) { return gs.t + gs.h * (1 - v); };
    }

    if(type === 'path') {
        if(xa && xa.type === 'date') x2p = helpers.decodeDate(x2p);
        if(ya && ya.type === 'date') y2p = helpers.decodeDate(y2p);
        return convertPath(options, x2p, y2p);
    }

    if(options.xsizemode === 'pixel') {
        var xAnchorPos = x2p(options.xanchor);
        x0 = xAnchorPos + options.x0;
        x1 = xAnchorPos + options.x1;
    }
    else {
        x0 = x2p(options.x0);
        x1 = x2p(options.x1);
    }

    if(options.ysizemode === 'pixel') {
        var yAnchorPos = y2p(options.yanchor);
        y0 = yAnchorPos - options.y0;
        y1 = yAnchorPos - options.y1;
    }
    else {
        y0 = y2p(options.y0);
        y1 = y2p(options.y1);
    }

    if(type === 'line') return 'M' + x0 + ',' + y0 + 'L' + x1 + ',' + y1;
    if(type === 'rect') return 'M' + x0 + ',' + y0 + 'H' + x1 + 'V' + y1 + 'H' + x0 + 'Z';

    // circle
    var cx = (x0 + x1) / 2;
    var cy = (y0 + y1) / 2;
    var rx = Math.abs(cx - x0);
    var ry = Math.abs(cy - y0);
    var rArc = 'A' + rx + ',' + ry;
    var rightPt = (cx + rx) + ',' + cy;
    var topPt = cx + ',' + (cy - ry);
    return 'M' + rightPt + rArc + ' 0 1,1 ' + topPt +
        rArc + ' 0 0,1 ' + rightPt + 'Z';
}


function convertPath(options, x2p, y2p) {
    var pathIn = options.path;
    var xSizemode = options.xsizemode;
    var ySizemode = options.ysizemode;
    var xAnchor = options.xanchor;
    var yAnchor = options.yanchor;

    return pathIn.replace(constants.segmentRE, function(segment) {
        var paramNumber = 0;
        var segmentType = segment.charAt(0);
        var xParams = constants.paramIsX[segmentType];
        var yParams = constants.paramIsY[segmentType];
        var nParams = constants.numParams[segmentType];

        var paramString = segment.substr(1).replace(constants.paramRE, function(param) {
            if(xParams[paramNumber]) {
                if(xSizemode === 'pixel') param = x2p(xAnchor) + Number(param);
                else param = x2p(param);
            }
            else if(yParams[paramNumber]) {
                if(ySizemode === 'pixel') param = y2p(yAnchor) - Number(param);
                else param = y2p(param);
            }
            paramNumber++;

            if(paramNumber > nParams) param = 'X';
            return param;
        });

        if(paramNumber > nParams) {
            paramString = paramString.replace(/[\s,]*X.*/, '');
            Lib.log('Ignoring extra params in segment ' + segment);
        }

        return segmentType + paramString;
    });
}

function movePath(pathIn, moveX, moveY) {
    return pathIn.replace(constants.segmentRE, function(segment) {
        var paramNumber = 0;
        var segmentType = segment.charAt(0);
        var xParams = constants.paramIsX[segmentType];
        var yParams = constants.paramIsY[segmentType];
        var nParams = constants.numParams[segmentType];

        var paramString = segment.substr(1).replace(constants.paramRE, function(param) {
            if(paramNumber >= nParams) return param;

            if(xParams[paramNumber]) param = moveX(param);
            else if(yParams[paramNumber]) param = moveY(param);

            paramNumber++;

            return param;
        });

        return segmentType + paramString;
    });
}

},{"../../lib":694,"../../lib/setcursor":714,"../../plot_api/plot_template":732,"../../plots/cartesian/axes":742,"../../registry":825,"../color":571,"../dragelement":589,"../drawing":592,"./constants":649,"./helpers":652}],652:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var constants = _dereq_('./constants');

var Lib = _dereq_('../../lib');

// special position conversion functions... category axis positions can't be
// specified by their data values, because they don't make a continuous mapping.
// so these have to be specified in terms of the category serial numbers,
// but can take fractional values. Other axis types we specify position based on
// the actual data values.
// TODO: in V2.0 (when log axis ranges are in data units) range and shape position
// will be identical, so rangeToShapePosition and shapePositionToRange can be
// removed entirely.

exports.rangeToShapePosition = function(ax) {
    return (ax.type === 'log') ? ax.r2d : function(v) { return v; };
};

exports.shapePositionToRange = function(ax) {
    return (ax.type === 'log') ? ax.d2r : function(v) { return v; };
};

exports.decodeDate = function(convertToPx) {
    return function(v) {
        if(v.replace) v = v.replace('_', ' ');
        return convertToPx(v);
    };
};

exports.encodeDate = function(convertToDate) {
    return function(v) { return convertToDate(v).replace(' ', '_'); };
};

exports.extractPathCoords = function(path, paramsToUse) {
    var extractedCoordinates = [];

    var segments = path.match(constants.segmentRE);
    segments.forEach(function(segment) {
        var relevantParamIdx = paramsToUse[segment.charAt(0)].drawn;
        if(relevantParamIdx === undefined) return;

        var params = segment.substr(1).match(constants.paramRE);
        if(!params || params.length < relevantParamIdx) return;

        extractedCoordinates.push(Lib.cleanNumber(params[relevantParamIdx]));
    });

    return extractedCoordinates;
};

exports.getDataToPixel = function(gd, axis, isVertical) {
    var gs = gd._fullLayout._size;
    var dataToPixel;

    if(axis) {
        var d2r = exports.shapePositionToRange(axis);

        dataToPixel = function(v) {
            return axis._offset + axis.r2p(d2r(v, true));
        };

        if(axis.type === 'date') dataToPixel = exports.decodeDate(dataToPixel);
    }
    else if(isVertical) {
        dataToPixel = function(v) { return gs.t + gs.h * (1 - v); };
    }
    else {
        dataToPixel = function(v) { return gs.l + gs.w * v; };
    }

    return dataToPixel;
};

exports.getPixelToData = function(gd, axis, isVertical) {
    var gs = gd._fullLayout._size;
    var pixelToData;

    if(axis) {
        var r2d = exports.rangeToShapePosition(axis);
        pixelToData = function(p) { return r2d(axis.p2r(p - axis._offset)); };
    }
    else if(isVertical) {
        pixelToData = function(p) { return 1 - (p - gs.t) / gs.h; };
    }
    else {
        pixelToData = function(p) { return (p - gs.l) / gs.w; };
    }

    return pixelToData;
};

/**
 * Based on the given stroke width, rounds the passed
 * position value to represent either a full or half pixel.
 *
 * In case of an odd stroke width (e.g. 1), this measure ensures
 * that a stroke positioned at the returned position isn't rendered
 * blurry due to anti-aliasing.
 *
 * In case of an even stroke width (e.g. 2), this measure ensures
 * that the position value is transformed to a full pixel value
 * so that anti-aliasing doesn't take effect either.
 *
 * @param {number} pos The raw position value to be transformed
 * @param {number} strokeWidth The stroke width
 * @returns {number} either an integer or a .5 decimal number
 */
exports.roundPositionForSharpStrokeRendering = function(pos, strokeWidth) {
    var strokeWidthIsOdd = Math.round(strokeWidth % 2) === 1;
    var posValAsInt = Math.round(pos);

    return strokeWidthIsOdd ? posValAsInt + 0.5 : posValAsInt;
};

},{"../../lib":694,"./constants":649}],653:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var drawModule = _dereq_('./draw');

module.exports = {
    moduleType: 'component',
    name: 'shapes',

    layoutAttributes: _dereq_('./attributes'),
    supplyLayoutDefaults: _dereq_('./defaults'),
    includeBasePlot: _dereq_('../../plots/cartesian/include_components')('shapes'),

    calcAutorange: _dereq_('./calc_autorange'),
    draw: drawModule.draw,
    drawOne: drawModule.drawOne
};

},{"../../plots/cartesian/include_components":753,"./attributes":647,"./calc_autorange":648,"./defaults":650,"./draw":651}],654:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = _dereq_('../../plots/font_attributes');
var padAttrs = _dereq_('../../plots/pad_attributes');
var extendDeepAll = _dereq_('../../lib/extend').extendDeepAll;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
var animationAttrs = _dereq_('../../plots/animation_attributes');
var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;
var constants = _dereq_('./constants');

var stepsAttrs = templatedArray('step', {
    visible: {
        valType: 'boolean',
        
        dflt: true,
        
    },
    method: {
        valType: 'enumerated',
        values: ['restyle', 'relayout', 'animate', 'update', 'skip'],
        dflt: 'restyle',
        
        
    },
    args: {
        valType: 'info_array',
        
        freeLength: true,
        items: [
            { valType: 'any' },
            { valType: 'any' },
            { valType: 'any' }
        ],
        
    },
    label: {
        valType: 'string',
        
        
    },
    value: {
        valType: 'string',
        
        
    },
    execute: {
        valType: 'boolean',
        
        dflt: true,
        
    }
});

module.exports = overrideAll(templatedArray('slider', {
    visible: {
        valType: 'boolean',
        
        dflt: true,
        
    },

    active: {
        valType: 'number',
        
        min: 0,
        dflt: 0,
        
    },

    steps: stepsAttrs,

    lenmode: {
        valType: 'enumerated',
        values: ['fraction', 'pixels'],
        
        dflt: 'fraction',
        
    },
    len: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        
    },
    x: {
        valType: 'number',
        min: -2,
        max: 3,
        dflt: 0,
        
        
    },
    pad: extendDeepAll(padAttrs({editType: 'arraydraw'}), {
        
    }, {t: {dflt: 20}}),
    xanchor: {
        valType: 'enumerated',
        values: ['auto', 'left', 'center', 'right'],
        dflt: 'left',
        
        
    },
    y: {
        valType: 'number',
        min: -2,
        max: 3,
        dflt: 0,
        
        
    },
    yanchor: {
        valType: 'enumerated',
        values: ['auto', 'top', 'middle', 'bottom'],
        dflt: 'top',
        
        
    },

    transition: {
        duration: {
            valType: 'number',
            
            min: 0,
            dflt: 150,
            
        },
        easing: {
            valType: 'enumerated',
            values: animationAttrs.transition.easing.values,
            
            dflt: 'cubic-in-out',
            
        }
    },

    currentvalue: {
        visible: {
            valType: 'boolean',
            
            dflt: true,
            
        },

        xanchor: {
            valType: 'enumerated',
            values: ['left', 'center', 'right'],
            dflt: 'left',
            
            
        },

        offset: {
            valType: 'number',
            dflt: 10,
            
            
        },

        prefix: {
            valType: 'string',
            
            
        },

        suffix: {
            valType: 'string',
            
            
        },

        font: fontAttrs({
            
        })
    },

    font: fontAttrs({
        
    }),

    activebgcolor: {
        valType: 'color',
        
        dflt: constants.gripBgActiveColor,
        
    },
    bgcolor: {
        valType: 'color',
        
        dflt: constants.railBgColor,
        
    },
    bordercolor: {
        valType: 'color',
        dflt: constants.railBorderColor,
        
        
    },
    borderwidth: {
        valType: 'number',
        min: 0,
        dflt: constants.railBorderWidth,
        
        
    },
    ticklen: {
        valType: 'number',
        min: 0,
        dflt: constants.tickLength,
        
        
    },
    tickcolor: {
        valType: 'color',
        dflt: constants.tickColor,
        
        
    },
    tickwidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        
    },
    minorticklen: {
        valType: 'number',
        min: 0,
        dflt: constants.minorTickLength,
        
        
    }
}), 'arraydraw', 'from-root');

},{"../../lib/extend":684,"../../plot_api/edit_types":725,"../../plot_api/plot_template":732,"../../plots/animation_attributes":737,"../../plots/font_attributes":769,"../../plots/pad_attributes":805,"./constants":655}],655:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


module.exports = {

    // layout attribute name
    name: 'sliders',

    // class names
    containerClassName: 'slider-container',
    groupClassName: 'slider-group',
    inputAreaClass: 'slider-input-area',
    railRectClass: 'slider-rail-rect',
    railTouchRectClass: 'slider-rail-touch-rect',
    gripRectClass: 'slider-grip-rect',
    tickRectClass: 'slider-tick-rect',
    inputProxyClass: 'slider-input-proxy',
    labelsClass: 'slider-labels',
    labelGroupClass: 'slider-label-group',
    labelClass: 'slider-label',
    currentValueClass: 'slider-current-value',

    railHeight: 5,

    // DOM attribute name in button group keeping track
    // of active update menu
    menuIndexAttrName: 'slider-active-index',

    // id root pass to Plots.autoMargin
    autoMarginIdRoot: 'slider-',

    // min item width / height
    minWidth: 30,
    minHeight: 30,

    // padding around item text
    textPadX: 40,

    // arrow offset off right edge
    arrowOffsetX: 4,

    railRadius: 2,
    railWidth: 5,
    railBorder: 4,
    railBorderWidth: 1,
    railBorderColor: '#bec8d9',
    railBgColor: '#f8fafc',

    // The distance of the rail from the edge of the touchable area
    // Slightly less than the step inset because of the curved edges
    // of the rail
    railInset: 8,

    // The distance from the extremal tick marks to the edge of the
    // touchable area. This is basically the same as the grip radius,
    // but for other styles it wouldn't really need to be.
    stepInset: 10,

    gripRadius: 10,
    gripWidth: 20,
    gripHeight: 20,
    gripBorder: 20,
    gripBorderWidth: 1,
    gripBorderColor: '#bec8d9',
    gripBgColor: '#f6f8fa',
    gripBgActiveColor: '#dbdde0',

    labelPadding: 8,
    labelOffset: 0,

    tickWidth: 1,
    tickColor: '#333',
    tickOffset: 25,
    tickLength: 7,

    minorTickOffset: 25,
    minorTickColor: '#333',
    minorTickLength: 4,

    // Extra space below the current value label:
    currentValuePadding: 8,
    currentValueInset: 0,
};

},{}],656:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');

var attributes = _dereq_('./attributes');
var constants = _dereq_('./constants');

var name = constants.name;
var stepAttrs = attributes.steps;


module.exports = function slidersDefaults(layoutIn, layoutOut) {
    handleArrayContainerDefaults(layoutIn, layoutOut, {
        name: name,
        handleItemDefaults: sliderDefaults
    });
};

function sliderDefaults(sliderIn, sliderOut, layoutOut) {

    function coerce(attr, dflt) {
        return Lib.coerce(sliderIn, sliderOut, attributes, attr, dflt);
    }

    var steps = handleArrayContainerDefaults(sliderIn, sliderOut, {
        name: 'steps',
        handleItemDefaults: stepDefaults
    });

    var stepCount = 0;
    for(var i = 0; i < steps.length; i++) {
        if(steps[i].visible) stepCount++;
    }

    var visible;
    // If it has fewer than two options, it's not really a slider
    if(stepCount < 2) visible = sliderOut.visible = false;
    else visible = coerce('visible');
    if(!visible) return;

    sliderOut._stepCount = stepCount;
    var visSteps = sliderOut._visibleSteps = Lib.filterVisible(steps);

    var active = coerce('active');
    if(!(steps[active] || {}).visible) sliderOut.active = visSteps[0]._index;

    coerce('x');
    coerce('y');
    Lib.noneOrAll(sliderIn, sliderOut, ['x', 'y']);

    coerce('xanchor');
    coerce('yanchor');

    coerce('len');
    coerce('lenmode');

    coerce('pad.t');
    coerce('pad.r');
    coerce('pad.b');
    coerce('pad.l');

    Lib.coerceFont(coerce, 'font', layoutOut.font);

    var currentValueIsVisible = coerce('currentvalue.visible');

    if(currentValueIsVisible) {
        coerce('currentvalue.xanchor');
        coerce('currentvalue.prefix');
        coerce('currentvalue.suffix');
        coerce('currentvalue.offset');

        Lib.coerceFont(coerce, 'currentvalue.font', sliderOut.font);
    }

    coerce('transition.duration');
    coerce('transition.easing');

    coerce('bgcolor');
    coerce('activebgcolor');
    coerce('bordercolor');
    coerce('borderwidth');
    coerce('ticklen');
    coerce('tickwidth');
    coerce('tickcolor');
    coerce('minorticklen');
}

function stepDefaults(valueIn, valueOut) {
    function coerce(attr, dflt) {
        return Lib.coerce(valueIn, valueOut, stepAttrs, attr, dflt);
    }

    var visible;
    if(valueIn.method !== 'skip' && !Array.isArray(valueIn.args)) {
        visible = valueOut.visible = false;
    }
    else visible = coerce('visible');

    if(visible) {
        coerce('method');
        coerce('args');
        var label = coerce('label', 'step-' + valueOut._index);
        coerce('value', label);
        coerce('execute');
    }
}

},{"../../lib":694,"../../plots/array_container_defaults":738,"./attributes":654,"./constants":655}],657:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Plots = _dereq_('../../plots/plots');
var Color = _dereq_('../color');
var Drawing = _dereq_('../drawing');
var Lib = _dereq_('../../lib');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var arrayEditor = _dereq_('../../plot_api/plot_template').arrayEditor;

var constants = _dereq_('./constants');
var alignmentConstants = _dereq_('../../constants/alignment');
var LINE_SPACING = alignmentConstants.LINE_SPACING;
var FROM_TL = alignmentConstants.FROM_TL;
var FROM_BR = alignmentConstants.FROM_BR;

module.exports = function draw(gd) {
    var fullLayout = gd._fullLayout;
    var sliderData = makeSliderData(fullLayout, gd);

    // draw a container for *all* sliders:
    var sliders = fullLayout._infolayer
        .selectAll('g.' + constants.containerClassName)
        .data(sliderData.length > 0 ? [0] : []);

    sliders.enter().append('g')
        .classed(constants.containerClassName, true)
        .style('cursor', 'ew-resize');

    function clearSlider(sliderOpts) {
        if(sliderOpts._commandObserver) {
            sliderOpts._commandObserver.remove();
            delete sliderOpts._commandObserver;
        }

        // Most components don't need to explicitly remove autoMargin, because
        // marginPushers does this - but slider updates don't go through
        // a full replot so we need to explicitly remove it.
        Plots.autoMargin(gd, autoMarginId(sliderOpts));
    }

    sliders.exit().each(function() {
        d3.select(this).selectAll('g.' + constants.groupClassName)
            .each(clearSlider);
    })
    .remove();

    // Return early if no menus visible:
    if(sliderData.length === 0) return;

    var sliderGroups = sliders.selectAll('g.' + constants.groupClassName)
        .data(sliderData, keyFunction);

    sliderGroups.enter().append('g')
        .classed(constants.groupClassName, true);

    sliderGroups.exit()
        .each(clearSlider)
        .remove();

    // Find the dimensions of the sliders:
    for(var i = 0; i < sliderData.length; i++) {
        var sliderOpts = sliderData[i];
        findDimensions(gd, sliderOpts);
    }

    sliderGroups.each(function(sliderOpts) {
        var gSlider = d3.select(this);

        computeLabelSteps(sliderOpts);

        Plots.manageCommandObserver(gd, sliderOpts, sliderOpts._visibleSteps, function(data) {
            // NB: Same as below. This is *not* always the same as sliderOpts since
            // if a new set of steps comes in, the reference in this callback would
            // be invalid. We need to refetch it from the slider group, which is
            // the join data that creates this slider. So if this slider still exists,
            // the group should be valid, *to the best of my knowledge.* If not,
            // we'd have to look it up by d3 data join index/key.
            var opts = gSlider.data()[0];

            if(opts.active === data.index) return;
            if(opts._dragging) return;

            setActive(gd, gSlider, opts, data.index, false, true);
        });

        drawSlider(gd, d3.select(this), sliderOpts);
    });
};

function autoMarginId(sliderOpts) {
    return constants.autoMarginIdRoot + sliderOpts._index;
}

// This really only just filters by visibility:
function makeSliderData(fullLayout, gd) {
    var contOpts = fullLayout[constants.name];
    var sliderData = [];

    for(var i = 0; i < contOpts.length; i++) {
        var item = contOpts[i];
        if(!item.visible) continue;
        item._gd = gd;
        sliderData.push(item);
    }

    return sliderData;
}

// This is set in the defaults step:
function keyFunction(opts) {
    return opts._index;
}

// Compute the dimensions (mutates sliderOpts):
function findDimensions(gd, sliderOpts) {
    var sliderLabels = Drawing.tester.selectAll('g.' + constants.labelGroupClass)
        .data(sliderOpts._visibleSteps);

    sliderLabels.enter().append('g')
        .classed(constants.labelGroupClass, true);

    // loop over fake buttons to find width / height
    var maxLabelWidth = 0;
    var labelHeight = 0;
    sliderLabels.each(function(stepOpts) {
        var labelGroup = d3.select(this);

        var text = drawLabel(labelGroup, {step: stepOpts}, sliderOpts);

        var textNode = text.node();
        if(textNode) {
            var bBox = Drawing.bBox(textNode);
            labelHeight = Math.max(labelHeight, bBox.height);
            maxLabelWidth = Math.max(maxLabelWidth, bBox.width);
        }
    });

    sliderLabels.remove();

    var dims = sliderOpts._dims = {};

    dims.inputAreaWidth = Math.max(
        constants.railWidth,
        constants.gripHeight
    );

    // calculate some overall dimensions - some of these are needed for
    // calculating the currentValue dimensions
    var graphSize = gd._fullLayout._size;
    dims.lx = graphSize.l + graphSize.w * sliderOpts.x;
    dims.ly = graphSize.t + graphSize.h * (1 - sliderOpts.y);

    if(sliderOpts.lenmode === 'fraction') {
        // fraction:
        dims.outerLength = Math.round(graphSize.w * sliderOpts.len);
    } else {
        // pixels:
        dims.outerLength = sliderOpts.len;
    }

    // The length of the rail, *excluding* padding on either end:
    dims.inputAreaStart = 0;
    dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r);

    var textableInputLength = dims.inputAreaLength - 2 * constants.stepInset;
    var availableSpacePerLabel = textableInputLength / (sliderOpts._stepCount - 1);
    var computedSpacePerLabel = maxLabelWidth + constants.labelPadding;
    dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel));
    dims.labelHeight = labelHeight;

    // loop over all possible values for currentValue to find the
    // area we need for it
    dims.currentValueMaxWidth = 0;
    dims.currentValueHeight = 0;
    dims.currentValueTotalHeight = 0;
    dims.currentValueMaxLines = 1;

    if(sliderOpts.currentvalue.visible) {
        // Get the dimensions of the current value label:
        var dummyGroup = Drawing.tester.append('g');

        sliderLabels.each(function(stepOpts) {
            var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label);
            var curValSize = (curValPrefix.node() && Drawing.bBox(curValPrefix.node())) || {width: 0, height: 0};
            var lines = svgTextUtils.lineCount(curValPrefix);
            dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width));
            dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height));
            dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines);
        });

        dims.currentValueTotalHeight = dims.currentValueHeight + sliderOpts.currentvalue.offset;

        dummyGroup.remove();
    }

    dims.height = dims.currentValueTotalHeight + constants.tickOffset + sliderOpts.ticklen + constants.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b;

    var xanchor = 'left';
    if(Lib.isRightAnchor(sliderOpts)) {
        dims.lx -= dims.outerLength;
        xanchor = 'right';
    }
    if(Lib.isCenterAnchor(sliderOpts)) {
        dims.lx -= dims.outerLength / 2;
        xanchor = 'center';
    }

    var yanchor = 'top';
    if(Lib.isBottomAnchor(sliderOpts)) {
        dims.ly -= dims.height;
        yanchor = 'bottom';
    }
    if(Lib.isMiddleAnchor(sliderOpts)) {
        dims.ly -= dims.height / 2;
        yanchor = 'middle';
    }

    dims.outerLength = Math.ceil(dims.outerLength);
    dims.height = Math.ceil(dims.height);
    dims.lx = Math.round(dims.lx);
    dims.ly = Math.round(dims.ly);

    var marginOpts = {
        y: sliderOpts.y,
        b: dims.height * FROM_BR[yanchor],
        t: dims.height * FROM_TL[yanchor]
    };

    if(sliderOpts.lenmode === 'fraction') {
        marginOpts.l = 0;
        marginOpts.xl = sliderOpts.x - sliderOpts.len * FROM_TL[xanchor];
        marginOpts.r = 0;
        marginOpts.xr = sliderOpts.x + sliderOpts.len * FROM_BR[xanchor];
    }
    else {
        marginOpts.x = sliderOpts.x;
        marginOpts.l = dims.outerLength * FROM_TL[xanchor];
        marginOpts.r = dims.outerLength * FROM_BR[xanchor];
    }

    Plots.autoMargin(gd, autoMarginId(sliderOpts), marginOpts);
}

function drawSlider(gd, sliderGroup, sliderOpts) {
    // This is related to the other long notes in this file regarding what happens
    // when slider steps disappear. This particular fix handles what happens when
    // the *current* slider step is removed. The drawing functions will error out
    // when they fail to find it, so the fix for now is that it will just draw the
    // slider in the first position but will not execute the command.
    if(!((sliderOpts.steps[sliderOpts.active] || {}).visible)) {
        sliderOpts.active = sliderOpts._visibleSteps[0]._index;
    }

    // These are carefully ordered for proper z-ordering:
    sliderGroup
        .call(drawCurrentValue, sliderOpts)
        .call(drawRail, sliderOpts)
        .call(drawLabelGroup, sliderOpts)
        .call(drawTicks, sliderOpts)
        .call(drawTouchRect, gd, sliderOpts)
        .call(drawGrip, gd, sliderOpts);

    var dims = sliderOpts._dims;

    // Position the rectangle:
    Drawing.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t);

    sliderGroup.call(setGripPosition, sliderOpts, false);
    sliderGroup.call(drawCurrentValue, sliderOpts);

}

function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) {
    if(!sliderOpts.currentvalue.visible) return;

    var dims = sliderOpts._dims;
    var x0, textAnchor;

    switch(sliderOpts.currentvalue.xanchor) {
        case 'right':
            // This is anchored left and adjusted by the width of the longest label
            // so that the prefix doesn't move. The goal of this is to emphasize
            // what's actually changing and make the update less distracting.
            x0 = dims.inputAreaLength - constants.currentValueInset - dims.currentValueMaxWidth;
            textAnchor = 'left';
            break;
        case 'center':
            x0 = dims.inputAreaLength * 0.5;
            textAnchor = 'middle';
            break;
        default:
            x0 = constants.currentValueInset;
            textAnchor = 'left';
    }

    var text = Lib.ensureSingle(sliderGroup, 'text', constants.labelClass, function(s) {
        s.classed('user-select-none', true)
            .attr({
                'text-anchor': textAnchor,
                'data-notex': 1
            });
    });

    var str = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : '';

    if(typeof valueOverride === 'string') {
        str += valueOverride;
    } else {
        var curVal = sliderOpts.steps[sliderOpts.active].label;
        str += curVal;
    }

    if(sliderOpts.currentvalue.suffix) {
        str += sliderOpts.currentvalue.suffix;
    }

    text.call(Drawing.font, sliderOpts.currentvalue.font)
        .text(str)
        .call(svgTextUtils.convertToTspans, sliderOpts._gd);

    var lines = svgTextUtils.lineCount(text);

    var y0 = (dims.currentValueMaxLines + 1 - lines) *
        sliderOpts.currentvalue.font.size * LINE_SPACING;

    svgTextUtils.positionText(text, x0, y0);

    return text;
}

function drawGrip(sliderGroup, gd, sliderOpts) {
    var grip = Lib.ensureSingle(sliderGroup, 'rect', constants.gripRectClass, function(s) {
        s.call(attachGripEvents, gd, sliderGroup, sliderOpts)
            .style('pointer-events', 'all');
    });

    grip.attr({
        width: constants.gripWidth,
        height: constants.gripHeight,
        rx: constants.gripRadius,
        ry: constants.gripRadius,
    })
    .call(Color.stroke, sliderOpts.bordercolor)
    .call(Color.fill, sliderOpts.bgcolor)
    .style('stroke-width', sliderOpts.borderwidth + 'px');
}

function drawLabel(item, data, sliderOpts) {
    var text = Lib.ensureSingle(item, 'text', constants.labelClass, function(s) {
        s.classed('user-select-none', true)
            .attr({
                'text-anchor': 'middle',
                'data-notex': 1
            });
    });

    text.call(Drawing.font, sliderOpts.font)
        .text(data.step.label)
        .call(svgTextUtils.convertToTspans, sliderOpts._gd);

    return text;
}

function drawLabelGroup(sliderGroup, sliderOpts) {
    var labels = Lib.ensureSingle(sliderGroup, 'g', constants.labelsClass);
    var dims = sliderOpts._dims;

    var labelItems = labels.selectAll('g.' + constants.labelGroupClass)
        .data(dims.labelSteps);

    labelItems.enter().append('g')
        .classed(constants.labelGroupClass, true);

    labelItems.exit().remove();

    labelItems.each(function(d) {
        var item = d3.select(this);

        item.call(drawLabel, d, sliderOpts);

        Drawing.setTranslate(item,
            normalizedValueToPosition(sliderOpts, d.fraction),
            constants.tickOffset +
                sliderOpts.ticklen +
                // position is the baseline of the top line of text only, even
                // if the label spans multiple lines
                sliderOpts.font.size * LINE_SPACING +
                constants.labelOffset +
                dims.currentValueTotalHeight
        );
    });

}

function handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, doTransition) {
    var quantizedPosition = Math.round(normalizedPosition * (sliderOpts._stepCount - 1));
    var quantizedIndex = sliderOpts._visibleSteps[quantizedPosition]._index;

    if(quantizedIndex !== sliderOpts.active) {
        setActive(gd, sliderGroup, sliderOpts, quantizedIndex, true, doTransition);
    }
}

function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) {
    var previousActive = sliderOpts.active;
    sliderOpts.active = index;

    // due to templating, it's possible this slider doesn't even exist yet
    arrayEditor(gd.layout, constants.name, sliderOpts)
        .applyUpdate('active', index);

    var step = sliderOpts.steps[sliderOpts.active];

    sliderGroup.call(setGripPosition, sliderOpts, doTransition);
    sliderGroup.call(drawCurrentValue, sliderOpts);

    gd.emit('plotly_sliderchange', {
        slider: sliderOpts,
        step: sliderOpts.steps[sliderOpts.active],
        interaction: doCallback,
        previousActive: previousActive
    });

    if(step && step.method && doCallback) {
        if(sliderGroup._nextMethod) {
            // If we've already queued up an update, just overwrite it with the most recent:
            sliderGroup._nextMethod.step = step;
            sliderGroup._nextMethod.doCallback = doCallback;
            sliderGroup._nextMethod.doTransition = doTransition;
        } else {
            sliderGroup._nextMethod = {step: step, doCallback: doCallback, doTransition: doTransition};
            sliderGroup._nextMethodRaf = window.requestAnimationFrame(function() {
                var _step = sliderGroup._nextMethod.step;
                if(!_step.method) return;

                if(_step.execute) {
                    Plots.executeAPICommand(gd, _step.method, _step.args);
                }

                sliderGroup._nextMethod = null;
                sliderGroup._nextMethodRaf = null;
            });
        }
    }
}

function attachGripEvents(item, gd, sliderGroup) {
    var node = sliderGroup.node();
    var $gd = d3.select(gd);

    // NB: This is *not* the same as sliderOpts itself! These callbacks
    // are in a closure so this array won't actually be correct if the
    // steps have changed since this was initialized. The sliderGroup,
    // however, has not changed since that *is* the slider, so it must
    // be present to receive mouse events.
    function getSliderOpts() {
        return sliderGroup.data()[0];
    }

    item.on('mousedown', function() {
        var sliderOpts = getSliderOpts();
        gd.emit('plotly_sliderstart', {slider: sliderOpts});

        var grip = sliderGroup.select('.' + constants.gripRectClass);

        d3.event.stopPropagation();
        d3.event.preventDefault();
        grip.call(Color.fill, sliderOpts.activebgcolor);

        var normalizedPosition = positionToNormalizedValue(sliderOpts, d3.mouse(node)[0]);
        handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true);
        sliderOpts._dragging = true;

        $gd.on('mousemove', function() {
            var sliderOpts = getSliderOpts();
            var normalizedPosition = positionToNormalizedValue(sliderOpts, d3.mouse(node)[0]);
            handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, false);
        });

        $gd.on('mouseup', function() {
            var sliderOpts = getSliderOpts();
            sliderOpts._dragging = false;
            grip.call(Color.fill, sliderOpts.bgcolor);
            $gd.on('mouseup', null);
            $gd.on('mousemove', null);

            gd.emit('plotly_sliderend', {
                slider: sliderOpts,
                step: sliderOpts.steps[sliderOpts.active]
            });
        });
    });
}

function drawTicks(sliderGroup, sliderOpts) {
    var tick = sliderGroup.selectAll('rect.' + constants.tickRectClass)
        .data(sliderOpts._visibleSteps);
    var dims = sliderOpts._dims;

    tick.enter().append('rect')
        .classed(constants.tickRectClass, true);

    tick.exit().remove();

    tick.attr({
        width: sliderOpts.tickwidth + 'px',
        'shape-rendering': 'crispEdges'
    });

    tick.each(function(d, i) {
        var isMajor = i % dims.labelStride === 0;
        var item = d3.select(this);

        item
            .attr({height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen})
            .call(Color.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor);

        Drawing.setTranslate(item,
            normalizedValueToPosition(sliderOpts, i / (sliderOpts._stepCount - 1)) - 0.5 * sliderOpts.tickwidth,
            (isMajor ? constants.tickOffset : constants.minorTickOffset) + dims.currentValueTotalHeight
        );
    });

}

function computeLabelSteps(sliderOpts) {
    var dims = sliderOpts._dims;
    dims.labelSteps = [];
    var nsteps = sliderOpts._stepCount;

    for(var i = 0; i < nsteps; i += dims.labelStride) {
        dims.labelSteps.push({
            fraction: i / (nsteps - 1),
            step: sliderOpts._visibleSteps[i]
        });
    }
}

function setGripPosition(sliderGroup, sliderOpts, doTransition) {
    var grip = sliderGroup.select('rect.' + constants.gripRectClass);

    var quantizedIndex = 0;
    for(var i = 0; i < sliderOpts._stepCount; i++) {
        if(sliderOpts._visibleSteps[i]._index === sliderOpts.active) {
            quantizedIndex = i;
            break;
        }
    }

    var x = normalizedValueToPosition(sliderOpts, quantizedIndex / (sliderOpts._stepCount - 1));

    // If this is true, then *this component* is already invoking its own command
    // and has triggered its own animation.
    if(sliderOpts._invokingCommand) return;

    var el = grip;
    if(doTransition && sliderOpts.transition.duration > 0) {
        el = el.transition()
            .duration(sliderOpts.transition.duration)
            .ease(sliderOpts.transition.easing);
    }

    // Drawing.setTranslate doesn't work here becasue of the transition duck-typing.
    // It's also not necessary because there are no other transitions to preserve.
    el.attr('transform', 'translate(' + (x - constants.gripWidth * 0.5) + ',' + (sliderOpts._dims.currentValueTotalHeight) + ')');
}

// Convert a number from [0-1] to a pixel position relative to the slider group container:
function normalizedValueToPosition(sliderOpts, normalizedPosition) {
    var dims = sliderOpts._dims;
    return dims.inputAreaStart + constants.stepInset +
        (dims.inputAreaLength - 2 * constants.stepInset) * Math.min(1, Math.max(0, normalizedPosition));
}

// Convert a position relative to the slider group to a nubmer in [0, 1]
function positionToNormalizedValue(sliderOpts, position) {
    var dims = sliderOpts._dims;
    return Math.min(1, Math.max(0, (position - constants.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * constants.stepInset - 2 * dims.inputAreaStart)));
}

function drawTouchRect(sliderGroup, gd, sliderOpts) {
    var dims = sliderOpts._dims;
    var rect = Lib.ensureSingle(sliderGroup, 'rect', constants.railTouchRectClass, function(s) {
        s.call(attachGripEvents, gd, sliderGroup, sliderOpts)
            .style('pointer-events', 'all');
    });

    rect.attr({
        width: dims.inputAreaLength,
        height: Math.max(dims.inputAreaWidth, constants.tickOffset + sliderOpts.ticklen + dims.labelHeight)
    })
        .call(Color.fill, sliderOpts.bgcolor)
        .attr('opacity', 0);

    Drawing.setTranslate(rect, 0, dims.currentValueTotalHeight);
}

function drawRail(sliderGroup, sliderOpts) {
    var dims = sliderOpts._dims;
    var computedLength = dims.inputAreaLength - constants.railInset * 2;
    var rect = Lib.ensureSingle(sliderGroup, 'rect', constants.railRectClass);

    rect.attr({
        width: computedLength,
        height: constants.railWidth,
        rx: constants.railRadius,
        ry: constants.railRadius,
        'shape-rendering': 'crispEdges'
    })
    .call(Color.stroke, sliderOpts.bordercolor)
    .call(Color.fill, sliderOpts.bgcolor)
    .style('stroke-width', sliderOpts.borderwidth + 'px');

    Drawing.setTranslate(rect,
        constants.railInset,
        (dims.inputAreaWidth - constants.railWidth) * 0.5 + dims.currentValueTotalHeight
    );
}

},{"../../constants/alignment":666,"../../lib":694,"../../lib/svg_text_utils":718,"../../plot_api/plot_template":732,"../../plots/plots":806,"../color":571,"../drawing":592,"./constants":655,"d3":149}],658:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var constants = _dereq_('./constants');

module.exports = {
    moduleType: 'component',
    name: constants.name,

    layoutAttributes: _dereq_('./attributes'),
    supplyLayoutDefaults: _dereq_('./defaults'),

    draw: _dereq_('./draw')
};

},{"./attributes":654,"./constants":655,"./defaults":656,"./draw":657}],659:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');

var Plots = _dereq_('../../plots/plots');
var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Drawing = _dereq_('../drawing');
var Color = _dereq_('../color');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var interactConstants = _dereq_('../../constants/interactions');

module.exports = {
    draw: draw
};

var numStripRE = / [XY][0-9]* /;

/**
 * Titles - (re)draw titles on the axes and plot:
 * @param {DOM element} gd - the graphDiv
 * @param {string} titleClass - the css class of this title
 * @param {object} options - how and what to draw
 *      propContainer - the layout object containing `title` and `titlefont`
 *          attributes that apply to this title
 *      propName - the full name of the title property (for Plotly.relayout)
 *      [traceIndex] - include only if this property applies to one trace
 *          (such as a colorbar title) - then editing pipes to Plotly.restyle
 *          instead of Plotly.relayout
 *      placeholder - placeholder text for an empty editable title
 *      [avoid] {object} - include if this title should move to avoid other elements
 *          selection - d3 selection of elements to avoid
 *          side - which direction to move if there is a conflict
 *          [offsetLeft] - if these elements are subject to a translation
 *              wrt the title element
 *          [offsetTop]
 *      attributes {object} - position and alignment attributes
 *          x - pixels
 *          y - pixels
 *          text-anchor - start|middle|end
 *      transform {object} - how to transform the title after positioning
 *          rotate - degrees
 *          offset - shift up/down in the rotated frame (unused?)
 *      containerGroup - if an svg <g> element already exists to hold this
 *          title, include here. Otherwise it will go in fullLayout._infolayer
 *
 *  @return {selection} d3 selection of title container group
 */
function draw(gd, titleClass, options) {
    var cont = options.propContainer;
    var prop = options.propName;
    var placeholder = options.placeholder;
    var traceIndex = options.traceIndex;
    var avoid = options.avoid || {};
    var attributes = options.attributes;
    var transform = options.transform;
    var group = options.containerGroup;

    var fullLayout = gd._fullLayout;

    var opacity = 1;
    var isplaceholder = false;
    var title = cont.title;
    var txt = (title && title.text ? title.text : '').trim();

    var font = title && title.font ? title.font : {};
    var fontFamily = font.family;
    var fontSize = font.size;
    var fontColor = font.color;

    // only make this title editable if we positively identify its property
    // as one that has editing enabled.
    var editAttr;
    if(prop === 'title.text') editAttr = 'titleText';
    else if(prop.indexOf('axis') !== -1) editAttr = 'axisTitleText';
    else if(prop.indexOf('colorbar' !== -1)) editAttr = 'colorbarTitleText';
    var editable = gd._context.edits[editAttr];

    if(txt === '') opacity = 0;
    // look for placeholder text while stripping out numbers from eg X2, Y3
    // this is just for backward compatibility with the old version that had
    // "Click to enter X2 title" and may have gotten saved in some old plots,
    // we don't want this to show up when these are displayed.
    else if(txt.replace(numStripRE, ' % ') === placeholder.replace(numStripRE, ' % ')) {
        opacity = 0.2;
        isplaceholder = true;
        if(!editable) txt = '';
    }

    if(fullLayout.meta) {
        txt = Lib.templateString(txt, {meta: fullLayout.meta});
    }

    var elShouldExist = txt || editable;

    if(!group) {
        group = Lib.ensureSingle(fullLayout._infolayer, 'g', 'g-' + titleClass);
    }

    var el = group.selectAll('text')
        .data(elShouldExist ? [0] : []);
    el.enter().append('text');
    el.text(txt)
        // this is hacky, but convertToTspans uses the class
        // to determine whether to rotate mathJax...
        // so we need to clear out any old class and put the
        // correct one (only relevant for colorbars, at least
        // for now) - ie don't use .classed
        .attr('class', titleClass);
    el.exit().remove();

    if(!elShouldExist) return group;

    function titleLayout(titleEl) {
        Lib.syncOrAsync([drawTitle, scootTitle], titleEl);
    }

    function drawTitle(titleEl) {
        var transformVal;

        if(transform) {
            transformVal = '';
            if(transform.rotate) {
                transformVal += 'rotate(' + [transform.rotate, attributes.x, attributes.y] + ')';
            }
            if(transform.offset) {
                transformVal += 'translate(0, ' + transform.offset + ')';
            }
        } else {
            transformVal = null;
        }

        titleEl.attr('transform', transformVal);

        titleEl.style({
            'font-family': fontFamily,
            'font-size': d3.round(fontSize, 2) + 'px',
            fill: Color.rgb(fontColor),
            opacity: opacity * Color.opacity(fontColor),
            'font-weight': Plots.fontWeight
        })
        .attr(attributes)
        .call(svgTextUtils.convertToTspans, gd);

        return Plots.previousPromises(gd);
    }

    function scootTitle(titleElIn) {
        var titleGroup = d3.select(titleElIn.node().parentNode);

        if(avoid && avoid.selection && avoid.side && txt) {
            titleGroup.attr('transform', null);

            // move toward avoid.side (= left, right, top, bottom) if needed
            // can include pad (pixels, default 2)
            var shift = 0;
            var backside = {
                left: 'right',
                right: 'left',
                top: 'bottom',
                bottom: 'top'
            }[avoid.side];
            var shiftSign = (['left', 'top'].indexOf(avoid.side) !== -1) ?
                    -1 : 1;
            var pad = isNumeric(avoid.pad) ? avoid.pad : 2;
            var titlebb = Drawing.bBox(titleGroup.node());
            var paperbb = {
                left: 0,
                top: 0,
                right: fullLayout.width,
                bottom: fullLayout.height
            };
            var maxshift = avoid.maxShift || (
                (paperbb[avoid.side] - titlebb[avoid.side]) *
                ((avoid.side === 'left' || avoid.side === 'top') ? -1 : 1));
            // Prevent the title going off the paper
            if(maxshift < 0) shift = maxshift;
            else {
                // so we don't have to offset each avoided element,
                // give the title the opposite offset
                var offsetLeft = avoid.offsetLeft || 0;
                var offsetTop = avoid.offsetTop || 0;
                titlebb.left -= offsetLeft;
                titlebb.right -= offsetLeft;
                titlebb.top -= offsetTop;
                titlebb.bottom -= offsetTop;

                // iterate over a set of elements (avoid.selection)
                // to avoid collisions with
                avoid.selection.each(function() {
                    var avoidbb = Drawing.bBox(this);

                    if(Lib.bBoxIntersect(titlebb, avoidbb, pad)) {
                        shift = Math.max(shift, shiftSign * (
                            avoidbb[avoid.side] - titlebb[backside]) + pad);
                    }
                });
                shift = Math.min(maxshift, shift);
            }
            if(shift > 0 || maxshift < 0) {
                var shiftTemplate = {
                    left: [-shift, 0],
                    right: [shift, 0],
                    top: [0, -shift],
                    bottom: [0, shift]
                }[avoid.side];
                titleGroup.attr('transform',
                    'translate(' + shiftTemplate + ')');
            }
        }
    }

    el.call(titleLayout);

    function setPlaceholder() {
        opacity = 0;
        isplaceholder = true;
        el.text(placeholder)
            .on('mouseover.opacity', function() {
                d3.select(this).transition()
                    .duration(interactConstants.SHOW_PLACEHOLDER).style('opacity', 1);
            })
            .on('mouseout.opacity', function() {
                d3.select(this).transition()
                    .duration(interactConstants.HIDE_PLACEHOLDER).style('opacity', 0);
            });
    }

    if(editable) {
        if(!txt) setPlaceholder();
        else el.on('.opacity', null);

        el.call(svgTextUtils.makeEditable, {gd: gd})
            .on('edit', function(text) {
                if(traceIndex !== undefined) {
                    Registry.call('_guiRestyle', gd, prop, text, traceIndex);
                } else {
                    Registry.call('_guiRelayout', gd, prop, text);
                }
            })
            .on('cancel', function() {
                this.text(this.attr('data-unformatted'))
                    .call(titleLayout);
            })
            .on('input', function(d) {
                this.text(d || ' ')
                    .call(svgTextUtils.positionText, attributes.x, attributes.y);
            });
    }
    el.classed('js-placeholder', isplaceholder);

    return group;
}

},{"../../constants/interactions":670,"../../lib":694,"../../lib/svg_text_utils":718,"../../plots/plots":806,"../../registry":825,"../color":571,"../drawing":592,"d3":149,"fast-isnumeric":215}],660:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = _dereq_('../../plots/font_attributes');
var colorAttrs = _dereq_('../color/attributes');
var extendFlat = _dereq_('../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
var padAttrs = _dereq_('../../plots/pad_attributes');
var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;

var buttonsAttrs = templatedArray('button', {
    visible: {
        valType: 'boolean',
        
        
    },
    method: {
        valType: 'enumerated',
        values: ['restyle', 'relayout', 'animate', 'update', 'skip'],
        dflt: 'restyle',
        
        
    },
    args: {
        valType: 'info_array',
        
        freeLength: true,
        items: [
            {valType: 'any'},
            {valType: 'any'},
            {valType: 'any'}
        ],
        
    },
    label: {
        valType: 'string',
        
        dflt: '',
        
    },
    execute: {
        valType: 'boolean',
        
        dflt: true,
        
    }
});

module.exports = overrideAll(templatedArray('updatemenu', {
    _arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],

    visible: {
        valType: 'boolean',
        
        
    },

    type: {
        valType: 'enumerated',
        values: ['dropdown', 'buttons'],
        dflt: 'dropdown',
        
        
    },

    direction: {
        valType: 'enumerated',
        values: ['left', 'right', 'up', 'down'],
        dflt: 'down',
        
        
    },

    active: {
        valType: 'integer',
        
        min: -1,
        dflt: 0,
        
    },

    showactive: {
        valType: 'boolean',
        
        dflt: true,
        
    },

    buttons: buttonsAttrs,

    x: {
        valType: 'number',
        min: -2,
        max: 3,
        dflt: -0.05,
        
        
    },
    xanchor: {
        valType: 'enumerated',
        values: ['auto', 'left', 'center', 'right'],
        dflt: 'right',
        
        
    },
    y: {
        valType: 'number',
        min: -2,
        max: 3,
        dflt: 1,
        
        
    },
    yanchor: {
        valType: 'enumerated',
        values: ['auto', 'top', 'middle', 'bottom'],
        dflt: 'top',
        
        
    },

    pad: extendFlat(padAttrs({editType: 'arraydraw'}), {
        
    }),

    font: fontAttrs({
        
    }),

    bgcolor: {
        valType: 'color',
        
        
    },
    bordercolor: {
        valType: 'color',
        dflt: colorAttrs.borderLine,
        
        
    },
    borderwidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'arraydraw',
        
    }
}), 'arraydraw', 'from-root');

},{"../../lib/extend":684,"../../plot_api/edit_types":725,"../../plot_api/plot_template":732,"../../plots/font_attributes":769,"../../plots/pad_attributes":805,"../color/attributes":570}],661:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


module.exports = {

    // layout attribute name
    name: 'updatemenus',

    // class names
    containerClassName: 'updatemenu-container',
    headerGroupClassName: 'updatemenu-header-group',
    headerClassName: 'updatemenu-header',
    headerArrowClassName: 'updatemenu-header-arrow',
    dropdownButtonGroupClassName: 'updatemenu-dropdown-button-group',
    dropdownButtonClassName: 'updatemenu-dropdown-button',
    buttonClassName: 'updatemenu-button',
    itemRectClassName: 'updatemenu-item-rect',
    itemTextClassName: 'updatemenu-item-text',

    // DOM attribute name in button group keeping track
    // of active update menu
    menuIndexAttrName: 'updatemenu-active-index',

    // id root pass to Plots.autoMargin
    autoMarginIdRoot: 'updatemenu-',

    // options when 'active: -1'
    blankHeaderOpts: { label: '  ' },

    // min item width / height
    minWidth: 30,
    minHeight: 30,

    // padding around item text
    textPadX: 24,
    arrowPadX: 16,

    // item rect radii
    rx: 2,
    ry: 2,

    // item  text x offset off left edge
    textOffsetX: 12,

    // item  text y offset (w.r.t. middle)
    textOffsetY: 3,

    // arrow offset off right edge
    arrowOffsetX: 4,

    // gap between header and buttons
    gapButtonHeader: 5,

    // gap between between buttons
    gapButton: 2,

    // color given to active buttons
    activeColor: '#F4FAFF',

    // color given to hovered buttons
    hoverColor: '#F4FAFF',

    // symbol for menu open arrow
    arrowSymbol: {
        left: '◄',
        right: '►',
        up: '▲',
        down: '▼'
    }
};

},{}],662:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');

var attributes = _dereq_('./attributes');
var constants = _dereq_('./constants');

var name = constants.name;
var buttonAttrs = attributes.buttons;


module.exports = function updateMenusDefaults(layoutIn, layoutOut) {
    var opts = {
        name: name,
        handleItemDefaults: menuDefaults
    };

    handleArrayContainerDefaults(layoutIn, layoutOut, opts);
};

function menuDefaults(menuIn, menuOut, layoutOut) {

    function coerce(attr, dflt) {
        return Lib.coerce(menuIn, menuOut, attributes, attr, dflt);
    }

    var buttons = handleArrayContainerDefaults(menuIn, menuOut, {
        name: 'buttons',
        handleItemDefaults: buttonDefaults
    });

    var visible = coerce('visible', buttons.length > 0);
    if(!visible) return;

    coerce('active');
    coerce('direction');
    coerce('type');
    coerce('showactive');

    coerce('x');
    coerce('y');
    Lib.noneOrAll(menuIn, menuOut, ['x', 'y']);

    coerce('xanchor');
    coerce('yanchor');

    coerce('pad.t');
    coerce('pad.r');
    coerce('pad.b');
    coerce('pad.l');

    Lib.coerceFont(coerce, 'font', layoutOut.font);

    coerce('bgcolor', layoutOut.paper_bgcolor);
    coerce('bordercolor');
    coerce('borderwidth');
}

function buttonDefaults(buttonIn, buttonOut) {
    function coerce(attr, dflt) {
        return Lib.coerce(buttonIn, buttonOut, buttonAttrs, attr, dflt);
    }

    var visible = coerce('visible',
        (buttonIn.method === 'skip' || Array.isArray(buttonIn.args)));
    if(visible) {
        coerce('method');
        coerce('args');
        coerce('label');
        coerce('execute');
    }
}

},{"../../lib":694,"../../plots/array_container_defaults":738,"./attributes":660,"./constants":661}],663:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

var Plots = _dereq_('../../plots/plots');
var Color = _dereq_('../color');
var Drawing = _dereq_('../drawing');
var Lib = _dereq_('../../lib');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var arrayEditor = _dereq_('../../plot_api/plot_template').arrayEditor;

var LINE_SPACING = _dereq_('../../constants/alignment').LINE_SPACING;

var constants = _dereq_('./constants');
var ScrollBox = _dereq_('./scrollbox');

module.exports = function draw(gd) {
    var fullLayout = gd._fullLayout;
    var menuData = Lib.filterVisible(fullLayout[constants.name]);

    /* Update menu data is bound to the header-group.
     * The items in the header group are always present.
     *
     * Upon clicking on a header its corresponding button
     * data is bound to the button-group.
     *
     * We draw all headers in one group before all buttons
     * so that the buttons *always* appear above the headers.
     *
     * Note that only one set of buttons are visible at once.
     *
     * <g container />
     *
     *     <g header-group />
     *         <g item header />
     *         <text item header-arrow />
     *     <g header-group />
     *         <g item header />
     *         <text item header-arrow />
     *     ...
     *
     *     <g button-group />
     *         <g item button />
     *         <g item button />
     *         ...
     */

    function clearAutoMargin(menuOpts) {
        Plots.autoMargin(gd, autoMarginId(menuOpts));
    }

    // draw update menu container
    var menus = fullLayout._menulayer
        .selectAll('g.' + constants.containerClassName)
        .data(menuData.length > 0 ? [0] : []);

    menus.enter().append('g')
        .classed(constants.containerClassName, true)
        .style('cursor', 'pointer');

    menus.exit().each(function() {
        // Most components don't need to explicitly remove autoMargin, because
        // marginPushers does this - but updatemenu updates don't go through
        // a full replot so we need to explicitly remove it.
        // This is for removing *all* updatemenus, removing individuals is
        // handled below, in headerGroups.exit
        d3.select(this).selectAll('g.' + constants.headerGroupClassName)
            .each(clearAutoMargin);
    }).remove();

    // return early if no update menus are visible
    if(menuData.length === 0) return;

    // join header group
    var headerGroups = menus.selectAll('g.' + constants.headerGroupClassName)
        .data(menuData, keyFunction);

    headerGroups.enter().append('g')
        .classed(constants.headerGroupClassName, true);

    // draw dropdown button container
    var gButton = Lib.ensureSingle(menus, 'g', constants.dropdownButtonGroupClassName, function(s) {
        s.style('pointer-events', 'all');
    });

    // find dimensions before plotting anything (this mutates menuOpts)
    for(var i = 0; i < menuData.length; i++) {
        var menuOpts = menuData[i];
        findDimensions(gd, menuOpts);
    }

    // setup scrollbox
    var scrollBoxId = 'updatemenus' + fullLayout._uid;
    var scrollBox = new ScrollBox(gd, gButton, scrollBoxId);

    // remove exiting header, remove dropped buttons and reset margins
    if(headerGroups.enter().size()) {
        // make sure gButton is on top of all headers
        gButton.node().parentNode.appendChild(gButton.node());
        gButton.call(removeAllButtons);
    }

    headerGroups.exit().each(function(menuOpts) {
        gButton.call(removeAllButtons);
        clearAutoMargin(menuOpts);
    }).remove();

    // draw headers!
    headerGroups.each(function(menuOpts) {
        var gHeader = d3.select(this);

        var _gButton = menuOpts.type === 'dropdown' ? gButton : null;
        Plots.manageCommandObserver(gd, menuOpts, menuOpts.buttons, function(data) {
            setActive(gd, menuOpts, menuOpts.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true);
        });

        if(menuOpts.type === 'dropdown') {
            drawHeader(gd, gHeader, gButton, scrollBox, menuOpts);

            // if this menu is active, update the dropdown container
            if(isActive(gButton, menuOpts)) {
                drawButtons(gd, gHeader, gButton, scrollBox, menuOpts);
            }
        } else {
            drawButtons(gd, gHeader, null, null, menuOpts);
        }

    });
};

// Note that '_index' is set at the default step,
// it corresponds to the menu index in the user layout update menu container.
// Because a menu can be set invisible,
// this is a more 'consistent' field than the index in the menuData.
function keyFunction(menuOpts) {
    return menuOpts._index;
}

function isFolded(gButton) {
    return +gButton.attr(constants.menuIndexAttrName) === -1;
}

function isActive(gButton, menuOpts) {
    return +gButton.attr(constants.menuIndexAttrName) === menuOpts._index;
}

function setActive(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) {
    // update 'active' attribute in menuOpts
    menuOpts.active = buttonIndex;

    // due to templating, it's possible this slider doesn't even exist yet
    arrayEditor(gd.layout, constants.name, menuOpts)
        .applyUpdate('active', buttonIndex);

    if(menuOpts.type === 'buttons') {
        drawButtons(gd, gHeader, null, null, menuOpts);
    }
    else if(menuOpts.type === 'dropdown') {
        // fold up buttons and redraw header
        gButton.attr(constants.menuIndexAttrName, '-1');

        drawHeader(gd, gHeader, gButton, scrollBox, menuOpts);

        if(!isSilentUpdate) {
            drawButtons(gd, gHeader, gButton, scrollBox, menuOpts);
        }
    }
}

function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) {
    var header = Lib.ensureSingle(gHeader, 'g', constants.headerClassName, function(s) {
        s.style('pointer-events', 'all');
    });

    var dims = menuOpts._dims;
    var active = menuOpts.active;
    var headerOpts = menuOpts.buttons[active] || constants.blankHeaderOpts;
    var posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 };
    var positionOverrides = {
        width: dims.headerWidth,
        height: dims.headerHeight
    };

    header
        .call(drawItem, menuOpts, headerOpts, gd)
        .call(setItemPosition, menuOpts, posOpts, positionOverrides);

    // draw drop arrow at the right edge
    var arrow = Lib.ensureSingle(gHeader, 'text', constants.headerArrowClassName, function(s) {
        s.classed('user-select-none', true)
            .attr('text-anchor', 'end')
            .call(Drawing.font, menuOpts.font)
            .text(constants.arrowSymbol[menuOpts.direction]);
    });

    arrow.attr({
        x: dims.headerWidth - constants.arrowOffsetX + menuOpts.pad.l,
        y: dims.headerHeight / 2 + constants.textOffsetY + menuOpts.pad.t
    });

    header.on('click', function() {
        gButton.call(removeAllButtons,
            String(isActive(gButton, menuOpts) ? -1 : menuOpts._index)
        );

        drawButtons(gd, gHeader, gButton, scrollBox, menuOpts);
    });

    header.on('mouseover', function() {
        header.call(styleOnMouseOver);
    });

    header.on('mouseout', function() {
        header.call(styleOnMouseOut, menuOpts);
    });

    // translate header group
    Drawing.setTranslate(gHeader, dims.lx, dims.ly);
}

function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) {
    // If this is a set of buttons, set pointer events = all since we play
    // some minor games with which container is which in order to simplify
    // the drawing of *either* buttons or menus
    if(!gButton) {
        gButton = gHeader;
        gButton.attr('pointer-events', 'all');
    }

    var buttonData = (!isFolded(gButton) || menuOpts.type === 'buttons') ?
        menuOpts.buttons :
        [];

    var klass = menuOpts.type === 'dropdown' ? constants.dropdownButtonClassName : constants.buttonClassName;

    var buttons = gButton.selectAll('g.' + klass)
        .data(Lib.filterVisible(buttonData));

    var enter = buttons.enter().append('g')
        .classed(klass, true);

    var exit = buttons.exit();

    if(menuOpts.type === 'dropdown') {
        enter.attr('opacity', '0')
            .transition()
            .attr('opacity', '1');

        exit.transition()
            .attr('opacity', '0')
            .remove();
    } else {
        exit.remove();
    }

    var x0 = 0;
    var y0 = 0;
    var dims = menuOpts._dims;

    var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1;

    if(menuOpts.type === 'dropdown') {
        if(isVertical) {
            y0 = dims.headerHeight + constants.gapButtonHeader;
        } else {
            x0 = dims.headerWidth + constants.gapButtonHeader;
        }
    }

    if(menuOpts.type === 'dropdown' && menuOpts.direction === 'up') {
        y0 = -constants.gapButtonHeader + constants.gapButton - dims.openHeight;
    }

    if(menuOpts.type === 'dropdown' && menuOpts.direction === 'left') {
        x0 = -constants.gapButtonHeader + constants.gapButton - dims.openWidth;
    }

    var posOpts = {
        x: dims.lx + x0 + menuOpts.pad.l,
        y: dims.ly + y0 + menuOpts.pad.t,
        yPad: constants.gapButton,
        xPad: constants.gapButton,
        index: 0,
    };

    var scrollBoxPosition = {
        l: posOpts.x + menuOpts.borderwidth,
        t: posOpts.y + menuOpts.borderwidth
    };

    buttons.each(function(buttonOpts, buttonIndex) {
        var button = d3.select(this);

        button
            .call(drawItem, menuOpts, buttonOpts, gd)
            .call(setItemPosition, menuOpts, posOpts);

        button.on('click', function() {
            // skip `dragend` events
            if(d3.event.defaultPrevented) return;

            setActive(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex);

            if(buttonOpts.execute) {
                Plots.executeAPICommand(gd, buttonOpts.method, buttonOpts.args);
            }

            gd.emit('plotly_buttonclicked', {menu: menuOpts, button: buttonOpts, active: menuOpts.active});
        });

        button.on('mouseover', function() {
            button.call(styleOnMouseOver);
        });

        button.on('mouseout', function() {
            button.call(styleOnMouseOut, menuOpts);
            buttons.call(styleButtons, menuOpts);
        });
    });

    buttons.call(styleButtons, menuOpts);

    if(isVertical) {
        scrollBoxPosition.w = Math.max(dims.openWidth, dims.headerWidth);
        scrollBoxPosition.h = posOpts.y - scrollBoxPosition.t;
    }
    else {
        scrollBoxPosition.w = posOpts.x - scrollBoxPosition.l;
        scrollBoxPosition.h = Math.max(dims.openHeight, dims.headerHeight);
    }

    scrollBoxPosition.direction = menuOpts.direction;

    if(scrollBox) {
        if(buttons.size()) {
            drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, scrollBoxPosition);
        }
        else {
            hideScrollBox(scrollBox);
        }
    }
}

function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) {
    // enable the scrollbox
    var direction = menuOpts.direction;
    var isVertical = (direction === 'up' || direction === 'down');
    var dims = menuOpts._dims;

    var active = menuOpts.active;
    var translateX, translateY;
    var i;
    if(isVertical) {
        translateY = 0;
        for(i = 0; i < active; i++) {
            translateY += dims.heights[i] + constants.gapButton;
        }
    }
    else {
        translateX = 0;
        for(i = 0; i < active; i++) {
            translateX += dims.widths[i] + constants.gapButton;
        }
    }

    scrollBox.enable(position, translateX, translateY);

    if(scrollBox.hbar) {
        scrollBox.hbar
            .attr('opacity', '0')
            .transition()
            .attr('opacity', '1');
    }

    if(scrollBox.vbar) {
        scrollBox.vbar
            .attr('opacity', '0')
            .transition()
            .attr('opacity', '1');
    }
}

function hideScrollBox(scrollBox) {
    var hasHBar = !!scrollBox.hbar;
    var hasVBar = !!scrollBox.vbar;

    if(hasHBar) {
        scrollBox.hbar
            .transition()
            .attr('opacity', '0')
            .each('end', function() {
                hasHBar = false;
                if(!hasVBar) scrollBox.disable();
            });
    }

    if(hasVBar) {
        scrollBox.vbar
            .transition()
            .attr('opacity', '0')
            .each('end', function() {
                hasVBar = false;
                if(!hasHBar) scrollBox.disable();
            });
    }
}

function drawItem(item, menuOpts, itemOpts, gd) {
    item.call(drawItemRect, menuOpts)
        .call(drawItemText, menuOpts, itemOpts, gd);
}

function drawItemRect(item, menuOpts) {
    var rect = Lib.ensureSingle(item, 'rect', constants.itemRectClassName, function(s) {
        s.attr({
            rx: constants.rx,
            ry: constants.ry,
            'shape-rendering': 'crispEdges'
        });
    });

    rect.call(Color.stroke, menuOpts.bordercolor)
        .call(Color.fill, menuOpts.bgcolor)
        .style('stroke-width', menuOpts.borderwidth + 'px');
}

function drawItemText(item, menuOpts, itemOpts, gd) {
    var text = Lib.ensureSingle(item, 'text', constants.itemTextClassName, function(s) {
        s.classed('user-select-none', true)
            .attr({
                'text-anchor': 'start',
                'data-notex': 1
            });
    });

    text.call(Drawing.font, menuOpts.font)
        .text(itemOpts.label)
        .call(svgTextUtils.convertToTspans, gd);
}

function styleButtons(buttons, menuOpts) {
    var active = menuOpts.active;

    buttons.each(function(buttonOpts, i) {
        var button = d3.select(this);

        if(i === active && menuOpts.showactive) {
            button.select('rect.' + constants.itemRectClassName)
                .call(Color.fill, constants.activeColor);
        }
    });
}

function styleOnMouseOver(item) {
    item.select('rect.' + constants.itemRectClassName)
        .call(Color.fill, constants.hoverColor);
}

function styleOnMouseOut(item, menuOpts) {
    item.select('rect.' + constants.itemRectClassName)
        .call(Color.fill, menuOpts.bgcolor);
}

// find item dimensions (this mutates menuOpts)
function findDimensions(gd, menuOpts) {
    var dims = menuOpts._dims = {
        width1: 0,
        height1: 0,
        heights: [],
        widths: [],
        totalWidth: 0,
        totalHeight: 0,
        openWidth: 0,
        openHeight: 0,
        lx: 0,
        ly: 0
    };

    var fakeButtons = Drawing.tester.selectAll('g.' + constants.dropdownButtonClassName)
        .data(Lib.filterVisible(menuOpts.buttons));

    fakeButtons.enter().append('g')
        .classed(constants.dropdownButtonClassName, true);

    var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1;

    // loop over fake buttons to find width / height
    fakeButtons.each(function(buttonOpts, i) {
        var button = d3.select(this);

        button.call(drawItem, menuOpts, buttonOpts, gd);

        var text = button.select('.' + constants.itemTextClassName);

        // width is given by max width of all buttons
        var tWidth = text.node() && Drawing.bBox(text.node()).width;
        var wEff = Math.max(tWidth + constants.textPadX, constants.minWidth);

        // height is determined by item text
        var tHeight = menuOpts.font.size * LINE_SPACING;
        var tLines = svgTextUtils.lineCount(text);
        var hEff = Math.max(tHeight * tLines, constants.minHeight) + constants.textOffsetY;

        hEff = Math.ceil(hEff);
        wEff = Math.ceil(wEff);

        // Store per-item sizes since a row of horizontal buttons, for example,
        // don't all need to be the same width:
        dims.widths[i] = wEff;
        dims.heights[i] = hEff;

        // Height and width of individual element:
        dims.height1 = Math.max(dims.height1, hEff);
        dims.width1 = Math.max(dims.width1, wEff);

        if(isVertical) {
            dims.totalWidth = Math.max(dims.totalWidth, wEff);
            dims.openWidth = dims.totalWidth;
            dims.totalHeight += hEff + constants.gapButton;
            dims.openHeight += hEff + constants.gapButton;
        } else {
            dims.totalWidth += wEff + constants.gapButton;
            dims.openWidth += wEff + constants.gapButton;
            dims.totalHeight = Math.max(dims.totalHeight, hEff);
            dims.openHeight = dims.totalHeight;
        }
    });

    if(isVertical) {
        dims.totalHeight -= constants.gapButton;
    } else {
        dims.totalWidth -= constants.gapButton;
    }


    dims.headerWidth = dims.width1 + constants.arrowPadX;
    dims.headerHeight = dims.height1;

    if(menuOpts.type === 'dropdown') {
        if(isVertical) {
            dims.width1 += constants.arrowPadX;
            dims.totalHeight = dims.height1;
        } else {
            dims.totalWidth = dims.width1;
        }
        dims.totalWidth += constants.arrowPadX;
    }

    fakeButtons.remove();

    var paddedWidth = dims.totalWidth + menuOpts.pad.l + menuOpts.pad.r;
    var paddedHeight = dims.totalHeight + menuOpts.pad.t + menuOpts.pad.b;

    var graphSize = gd._fullLayout._size;
    dims.lx = graphSize.l + graphSize.w * menuOpts.x;
    dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y);

    var xanchor = 'left';
    if(Lib.isRightAnchor(menuOpts)) {
        dims.lx -= paddedWidth;
        xanchor = 'right';
    }
    if(Lib.isCenterAnchor(menuOpts)) {
        dims.lx -= paddedWidth / 2;
        xanchor = 'center';
    }

    var yanchor = 'top';
    if(Lib.isBottomAnchor(menuOpts)) {
        dims.ly -= paddedHeight;
        yanchor = 'bottom';
    }
    if(Lib.isMiddleAnchor(menuOpts)) {
        dims.ly -= paddedHeight / 2;
        yanchor = 'middle';
    }

    dims.totalWidth = Math.ceil(dims.totalWidth);
    dims.totalHeight = Math.ceil(dims.totalHeight);
    dims.lx = Math.round(dims.lx);
    dims.ly = Math.round(dims.ly);

    Plots.autoMargin(gd, autoMarginId(menuOpts), {
        x: menuOpts.x,
        y: menuOpts.y,
        l: paddedWidth * ({right: 1, center: 0.5}[xanchor] || 0),
        r: paddedWidth * ({left: 1, center: 0.5}[xanchor] || 0),
        b: paddedHeight * ({top: 1, middle: 0.5}[yanchor] || 0),
        t: paddedHeight * ({bottom: 1, middle: 0.5}[yanchor] || 0)
    });
}

function autoMarginId(menuOpts) {
    return constants.autoMarginIdRoot + menuOpts._index;
}

// set item positions (mutates posOpts)
function setItemPosition(item, menuOpts, posOpts, overrideOpts) {
    overrideOpts = overrideOpts || {};
    var rect = item.select('.' + constants.itemRectClassName);
    var text = item.select('.' + constants.itemTextClassName);
    var borderWidth = menuOpts.borderwidth;
    var index = posOpts.index;
    var dims = menuOpts._dims;

    Drawing.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y);

    var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1;
    var finalHeight = overrideOpts.height || (isVertical ? dims.heights[index] : dims.height1);

    rect.attr({
        x: 0,
        y: 0,
        width: overrideOpts.width || (isVertical ? dims.width1 : dims.widths[index]),
        height: finalHeight
    });

    var tHeight = menuOpts.font.size * LINE_SPACING;
    var tLines = svgTextUtils.lineCount(text);
    var spanOffset = ((tLines - 1) * tHeight / 2);

    svgTextUtils.positionText(text, constants.textOffsetX,
        finalHeight / 2 - spanOffset + constants.textOffsetY);

    if(isVertical) {
        posOpts.y += dims.heights[index] + posOpts.yPad;
    } else {
        posOpts.x += dims.widths[index] + posOpts.xPad;
    }

    posOpts.index++;
}

function removeAllButtons(gButton, newMenuIndexAttr) {
    gButton
        .attr(constants.menuIndexAttrName, newMenuIndexAttr || '-1')
        .selectAll('g.' + constants.dropdownButtonClassName).remove();
}

},{"../../constants/alignment":666,"../../lib":694,"../../lib/svg_text_utils":718,"../../plot_api/plot_template":732,"../../plots/plots":806,"../color":571,"../drawing":592,"./constants":661,"./scrollbox":665,"d3":149}],664:[function(_dereq_,module,exports){
arguments[4][658][0].apply(exports,arguments)
},{"./attributes":660,"./constants":661,"./defaults":662,"./draw":663,"dup":658}],665:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = ScrollBox;

var d3 = _dereq_('d3');

var Color = _dereq_('../color');
var Drawing = _dereq_('../drawing');

var Lib = _dereq_('../../lib');

/**
 * Helper class to setup a scroll box
 *
 * @class
 * @param           gd          Plotly's graph div
 * @param           container   Container to be scroll-boxed (as a D3 selection)
 * @param {string}  id          Id for the clip path to implement the scroll box
 */
function ScrollBox(gd, container, id) {
    this.gd = gd;
    this.container = container;
    this.id = id;

    // See ScrollBox.prototype.enable for further definition
    this.position = null;  // scrollbox position
    this.translateX = null;  // scrollbox horizontal translation
    this.translateY = null;  // scrollbox vertical translation
    this.hbar = null;  // horizontal scrollbar D3 selection
    this.vbar = null;  // vertical scrollbar D3 selection

    // <rect> element to capture pointer events
    this.bg = this.container.selectAll('rect.scrollbox-bg').data([0]);

    this.bg.exit()
        .on('.drag', null)
        .on('wheel', null)
        .remove();

    this.bg.enter().append('rect')
        .classed('scrollbox-bg', true)
        .style('pointer-events', 'all')
        .attr({
            opacity: 0,
            x: 0,
            y: 0,
            width: 0,
            height: 0
        });
}

// scroll bar dimensions
ScrollBox.barWidth = 2;
ScrollBox.barLength = 20;
ScrollBox.barRadius = 2;
ScrollBox.barPad = 1;
ScrollBox.barColor = '#808BA4';

/**
 * If needed, setup a clip path and scrollbars
 *
 * @method
 * @param {Object}  position
 * @param {number}  position.l  Left side position (in pixels)
 * @param {number}  position.t  Top side (in pixels)
 * @param {number}  position.w  Width (in pixels)
 * @param {number}  position.h  Height (in pixels)
 * @param {string}  [position.direction='down']
 *                  Either 'down', 'left', 'right' or 'up'
 * @param {number}  [translateX=0]  Horizontal offset (in pixels)
 * @param {number}  [translateY=0]  Vertical offset (in pixels)
 */
ScrollBox.prototype.enable = function enable(position, translateX, translateY) {
    var fullLayout = this.gd._fullLayout;
    var fullWidth = fullLayout.width;
    var fullHeight = fullLayout.height;

    // compute position of scrollbox
    this.position = position;

    var l = this.position.l;
    var w = this.position.w;
    var t = this.position.t;
    var h = this.position.h;
    var direction = this.position.direction;
    var isDown = (direction === 'down');
    var isLeft = (direction === 'left');
    var isRight = (direction === 'right');
    var isUp = (direction === 'up');
    var boxW = w;
    var boxH = h;
    var boxL, boxR;
    var boxT, boxB;

    if(!isDown && !isLeft && !isRight && !isUp) {
        this.position.direction = 'down';
        isDown = true;
    }

    var isVertical = isDown || isUp;
    if(isVertical) {
        boxL = l;
        boxR = boxL + boxW;

        if(isDown) {
            // anchor to top side
            boxT = t;
            boxB = Math.min(boxT + boxH, fullHeight);
            boxH = boxB - boxT;
        }
        else {
            // anchor to bottom side
            boxB = t + boxH;
            boxT = Math.max(boxB - boxH, 0);
            boxH = boxB - boxT;
        }
    }
    else {
        boxT = t;
        boxB = boxT + boxH;

        if(isLeft) {
            // anchor to right side
            boxR = l + boxW;
            boxL = Math.max(boxR - boxW, 0);
            boxW = boxR - boxL;
        }
        else {
            // anchor to left side
            boxL = l;
            boxR = Math.min(boxL + boxW, fullWidth);
            boxW = boxR - boxL;
        }
    }

    this._box = {
        l: boxL,
        t: boxT,
        w: boxW,
        h: boxH
    };

    // compute position of horizontal scroll bar
    var needsHorizontalScrollBar = (w > boxW);
    var hbarW = ScrollBox.barLength + 2 * ScrollBox.barPad;
    var hbarH = ScrollBox.barWidth + 2 * ScrollBox.barPad;
    // draw horizontal scrollbar on the bottom side
    var hbarL = l;
    var hbarT = t + h;

    if(hbarT + hbarH > fullHeight) hbarT = fullHeight - hbarH;

    var hbar = this.container.selectAll('rect.scrollbar-horizontal').data(
            (needsHorizontalScrollBar) ? [0] : []);

    hbar.exit()
        .on('.drag', null)
        .remove();

    hbar.enter().append('rect')
        .classed('scrollbar-horizontal', true)
        .call(Color.fill, ScrollBox.barColor);

    if(needsHorizontalScrollBar) {
        this.hbar = hbar.attr({
            'rx': ScrollBox.barRadius,
            'ry': ScrollBox.barRadius,
            'x': hbarL,
            'y': hbarT,
            'width': hbarW,
            'height': hbarH
        });

        // hbar center moves between hbarXMin and hbarXMin + hbarTranslateMax
        this._hbarXMin = hbarL + hbarW / 2;
        this._hbarTranslateMax = boxW - hbarW;
    }
    else {
        delete this.hbar;
        delete this._hbarXMin;
        delete this._hbarTranslateMax;
    }

    // compute position of vertical scroll bar
    var needsVerticalScrollBar = (h > boxH);
    var vbarW = ScrollBox.barWidth + 2 * ScrollBox.barPad;
    var vbarH = ScrollBox.barLength + 2 * ScrollBox.barPad;
    // draw vertical scrollbar on the right side
    var vbarL = l + w;
    var vbarT = t;

    if(vbarL + vbarW > fullWidth) vbarL = fullWidth - vbarW;

    var vbar = this.container.selectAll('rect.scrollbar-vertical').data(
            (needsVerticalScrollBar) ? [0] : []);

    vbar.exit()
        .on('.drag', null)
        .remove();

    vbar.enter().append('rect')
        .classed('scrollbar-vertical', true)
        .call(Color.fill, ScrollBox.barColor);

    if(needsVerticalScrollBar) {
        this.vbar = vbar.attr({
            'rx': ScrollBox.barRadius,
            'ry': ScrollBox.barRadius,
            'x': vbarL,
            'y': vbarT,
            'width': vbarW,
            'height': vbarH
        });

        // vbar center moves between vbarYMin and vbarYMin + vbarTranslateMax
        this._vbarYMin = vbarT + vbarH / 2;
        this._vbarTranslateMax = boxH - vbarH;
    }
    else {
        delete this.vbar;
        delete this._vbarYMin;
        delete this._vbarTranslateMax;
    }

    // setup a clip path (if scroll bars are needed)
    var clipId = this.id;
    var clipL = boxL - 0.5;
    var clipR = (needsVerticalScrollBar) ? boxR + vbarW + 0.5 : boxR + 0.5;
    var clipT = boxT - 0.5;
    var clipB = (needsHorizontalScrollBar) ? boxB + hbarH + 0.5 : boxB + 0.5;

    var clipPath = fullLayout._topdefs.selectAll('#' + clipId)
        .data((needsHorizontalScrollBar || needsVerticalScrollBar) ? [0] : []);

    clipPath.exit().remove();

    clipPath.enter()
        .append('clipPath').attr('id', clipId)
        .append('rect');

    if(needsHorizontalScrollBar || needsVerticalScrollBar) {
        this._clipRect = clipPath.select('rect').attr({
            x: Math.floor(clipL),
            y: Math.floor(clipT),
            width: Math.ceil(clipR) - Math.floor(clipL),
            height: Math.ceil(clipB) - Math.floor(clipT)
        });

        this.container.call(Drawing.setClipUrl, clipId, this.gd);

        this.bg.attr({
            x: l,
            y: t,
            width: w,
            height: h
        });
    }
    else {
        this.bg.attr({
            width: 0,
            height: 0
        });
        this.container
            .on('wheel', null)
            .on('.drag', null)
            .call(Drawing.setClipUrl, null);
        delete this._clipRect;
    }

    // set up drag listeners (if scroll bars are needed)
    if(needsHorizontalScrollBar || needsVerticalScrollBar) {
        var onBoxDrag = d3.behavior.drag()
            .on('dragstart', function() {
                d3.event.sourceEvent.preventDefault();
            })
            .on('drag', this._onBoxDrag.bind(this));

        this.container
            .on('wheel', null)
            .on('wheel', this._onBoxWheel.bind(this))
            .on('.drag', null)
            .call(onBoxDrag);

        var onBarDrag = d3.behavior.drag()
            .on('dragstart', function() {
                d3.event.sourceEvent.preventDefault();
                d3.event.sourceEvent.stopPropagation();
            })
            .on('drag', this._onBarDrag.bind(this));

        if(needsHorizontalScrollBar) {
            this.hbar
                .on('.drag', null)
                .call(onBarDrag);
        }

        if(needsVerticalScrollBar) {
            this.vbar
                .on('.drag', null)
                .call(onBarDrag);
        }
    }

    // set scrollbox translation
    this.setTranslate(translateX, translateY);
};

/**
 * If present, remove clip-path and scrollbars
 *
 * @method
 */
ScrollBox.prototype.disable = function disable() {
    if(this.hbar || this.vbar) {
        this.bg.attr({
            width: 0,
            height: 0
        });
        this.container
            .on('wheel', null)
            .on('.drag', null)
            .call(Drawing.setClipUrl, null);
        delete this._clipRect;
    }

    if(this.hbar) {
        this.hbar.on('.drag', null);
        this.hbar.remove();
        delete this.hbar;
        delete this._hbarXMin;
        delete this._hbarTranslateMax;
    }

    if(this.vbar) {
        this.vbar.on('.drag', null);
        this.vbar.remove();
        delete this.vbar;
        delete this._vbarYMin;
        delete this._vbarTranslateMax;
    }
};

/**
 * Handles scroll box drag events
 *
 * @method
 */
ScrollBox.prototype._onBoxDrag = function onBarDrag() {
    var translateX = this.translateX;
    var translateY = this.translateY;

    if(this.hbar) {
        translateX -= d3.event.dx;
    }

    if(this.vbar) {
        translateY -= d3.event.dy;
    }

    this.setTranslate(translateX, translateY);
};

/**
 * Handles scroll box wheel events
 *
 * @method
 */
ScrollBox.prototype._onBoxWheel = function onBarWheel() {
    var translateX = this.translateX;
    var translateY = this.translateY;

    if(this.hbar) {
        translateX += d3.event.deltaY;
    }

    if(this.vbar) {
        translateY += d3.event.deltaY;
    }

    this.setTranslate(translateX, translateY);
};

/**
 * Handles scroll bar drag events
 *
 * @method
 */
ScrollBox.prototype._onBarDrag = function onBarDrag() {
    var translateX = this.translateX;
    var translateY = this.translateY;

    if(this.hbar) {
        var xMin = translateX + this._hbarXMin;
        var xMax = xMin + this._hbarTranslateMax;
        var x = Lib.constrain(d3.event.x, xMin, xMax);
        var xf = (x - xMin) / (xMax - xMin);

        var translateXMax = this.position.w - this._box.w;

        translateX = xf * translateXMax;
    }

    if(this.vbar) {
        var yMin = translateY + this._vbarYMin;
        var yMax = yMin + this._vbarTranslateMax;
        var y = Lib.constrain(d3.event.y, yMin, yMax);
        var yf = (y - yMin) / (yMax - yMin);

        var translateYMax = this.position.h - this._box.h;

        translateY = yf * translateYMax;
    }

    this.setTranslate(translateX, translateY);
};

/**
 * Set clip path and scroll bar translate transform
 *
 * @method
 * @param {number}  [translateX=0]  Horizontal offset (in pixels)
 * @param {number}  [translateY=0]  Vertical offset (in pixels)
 */
ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) {
    // store translateX and translateY (needed by mouse event handlers)
    var translateXMax = this.position.w - this._box.w;
    var translateYMax = this.position.h - this._box.h;

    translateX = Lib.constrain(translateX || 0, 0, translateXMax);
    translateY = Lib.constrain(translateY || 0, 0, translateYMax);

    this.translateX = translateX;
    this.translateY = translateY;

    this.container.call(Drawing.setTranslate,
        this._box.l - this.position.l - translateX,
        this._box.t - this.position.t - translateY);

    if(this._clipRect) {
        this._clipRect.attr({
            x: Math.floor(this.position.l + translateX - 0.5),
            y: Math.floor(this.position.t + translateY - 0.5)
        });
    }

    if(this.hbar) {
        var xf = translateX / translateXMax;

        this.hbar.call(Drawing.setTranslate,
            translateX + xf * this._hbarTranslateMax,
            translateY);
    }

    if(this.vbar) {
        var yf = translateY / translateYMax;

        this.vbar.call(Drawing.setTranslate,
            translateX,
            translateY + yf * this._vbarTranslateMax);
    }
};

},{"../../lib":694,"../color":571,"../drawing":592,"d3":149}],666:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// fraction of some size to get to a named position
module.exports = {
    // from bottom left: this is the origin of our paper-reference
    // positioning system
    FROM_BL: {
        left: 0,
        center: 0.5,
        right: 1,
        bottom: 0,
        middle: 0.5,
        top: 1
    },
    // from top left: this is the screen pixel positioning origin
    FROM_TL: {
        left: 0,
        center: 0.5,
        right: 1,
        bottom: 1,
        middle: 0.5,
        top: 0
    },
    // from bottom right: sometimes you just need the opposite of ^^
    FROM_BR: {
        left: 1,
        center: 0.5,
        right: 0,
        bottom: 0,
        middle: 0.5,
        top: 1
    },
    // multiple of fontSize to get the vertical offset between lines
    LINE_SPACING: 1.3,

    // multiple of fontSize to shift from the baseline
    // to the cap (captical letter) line
    // (to use when we don't calculate this shift from Drawing.bBox)
    // This is an approximation since in reality cap height can differ
    // from font to font. However, according to Wikipedia
    //   an "average" font might have a cap height of 70% of the em
    // https://en.wikipedia.org/wiki/Em_(typography)#History
    CAP_SHIFT: 0.70,

    // half the cap height (distance between baseline and cap line)
    // of an "average" font (for more info see above).
    MID_SHIFT: 0.35,

    OPPOSITE_SIDE: {
        left: 'right',
        right: 'left',
        top: 'bottom',
        bottom: 'top'
    }
};

},{}],667:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    COMPARISON_OPS: ['=', '!=', '<', '>=', '>', '<='],
    COMPARISON_OPS2: ['=', '<', '>=', '>', '<='],
    INTERVAL_OPS: ['[]', '()', '[)', '(]', '][', ')(', '](', ')['],
    SET_OPS: ['{}', '}{'],
    CONSTRAINT_REDUCTION: {
        // for contour constraints, open/closed endpoints are equivalent
        '=': '=',

        '<': '<',
        '<=': '<',

        '>': '>',
        '>=': '>',

        '[]': '[]',
        '()': '[]',
        '[)': '[]',
        '(]': '[]',

        '][': '][',
        ')(': '][',
        '](': '][',
        ')[': ']['
    }
};

},{}],668:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = {
    solid: [[], 0],
    dot: [[0.5, 1], 200],
    dash: [[0.5, 1], 50],
    longdash: [[0.5, 1], 10],
    dashdot: [[0.5, 0.625, 0.875, 1], 50],
    longdashdot: [[0.5, 0.7, 0.8, 1], 10]
};

},{}],669:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = {
    circle: '●',
    'circle-open': '○',
    square: '■',
    'square-open': '□',
    diamond: '◆',
    'diamond-open': '◇',
    cross: '+',
    x: '❌'
};

},{}],670:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    /**
     * Timing information for interactive elements
     */
    SHOW_PLACEHOLDER: 100,
    HIDE_PLACEHOLDER: 1000,

    // ms between first mousedown and 2nd mouseup to constitute dblclick...
    // we don't seem to have access to the system setting
    DBLCLICKDELAY: 300,

    // opacity dimming fraction for points that are not in selection
    DESELECTDIM: 0.2
};

},{}],671:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    /**
     * Standardize all missing data in calcdata to use undefined
     * never null or NaN.
     * That way we can use !==undefined, or !== BADNUM,
     * to test for real data
     */
    BADNUM: undefined,

    /*
     * Limit certain operations to well below floating point max value
     * to avoid glitches: Make sure that even when you multiply it by the
     * number of pixels on a giant screen it still works
     */
    FP_SAFE: Number.MAX_VALUE / 10000,

    /*
     * conversion of date units to milliseconds
     * year and month constants are marked "AVG"
     * to remind us that not all years and months
     * have the same length
     */
    ONEAVGYEAR: 31557600000, // 365.25 days
    ONEAVGMONTH: 2629800000, // 1/12 of ONEAVGYEAR
    ONEDAY: 86400000,
    ONEHOUR: 3600000,
    ONEMIN: 60000,
    ONESEC: 1000,

    /*
     * For fast conversion btwn world calendars and epoch ms, the Julian Day Number
     * of the unix epoch. From calendars.instance().newDate(1970, 1, 1).toJD()
     */
    EPOCHJD: 2440587.5,

    /*
     * Are two values nearly equal? Compare to 1PPM
     */
    ALMOST_EQUAL: 1 - 1e-6,

    /*
     * If we're asked to clip a non-positive log value, how far off-screen
     * do we put it?
     */
    LOG_CLIP: 10,

    /*
     * not a number, but for displaying numbers: the "minus sign" symbol is
     * wider than the regular ascii dash "-"
     */
    MINUS_SIGN: '\u2212'
};

},{}],672:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


exports.xmlns = 'http://www.w3.org/2000/xmlns/';
exports.svg = 'http://www.w3.org/2000/svg';
exports.xlink = 'http://www.w3.org/1999/xlink';

// the 'old' d3 quirk got fix in v3.5.7
// https://github.com/mbostock/d3/commit/a6f66e9dd37f764403fc7c1f26be09ab4af24fed
exports.svgAttrs = {
    xmlns: exports.svg,
    'xmlns:xlink': exports.xlink
};

},{}],673:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// package version injected by `npm run preprocess`
exports.version = '1.44.4';

// inject promise polyfill
_dereq_('es6-promise').polyfill();

// inject plot css
_dereq_('../build/plotcss');

// inject default MathJax config
_dereq_('./fonts/mathjax_config')();

// include registry module and expose register method
var Registry = _dereq_('./registry');
var register = exports.register = Registry.register;

// expose plot api methods
var plotApi = _dereq_('./plot_api');
var methodNames = Object.keys(plotApi);
for(var i = 0; i < methodNames.length; i++) {
    var name = methodNames[i];
    // _ -> private API methods, but still registered for internal use
    if(name.charAt(0) !== '_') exports[name] = plotApi[name];
    register({
        moduleType: 'apiMethod',
        name: name,
        fn: plotApi[name]
    });
}

// scatter is the only trace included by default
register(_dereq_('./traces/scatter'));

// register all registrable components modules
register([
    _dereq_('./components/fx'),
    _dereq_('./components/legend'),
    _dereq_('./components/annotations'),
    _dereq_('./components/annotations3d'),
    _dereq_('./components/shapes'),
    _dereq_('./components/images'),
    _dereq_('./components/updatemenus'),
    _dereq_('./components/sliders'),
    _dereq_('./components/rangeslider'),
    _dereq_('./components/rangeselector'),
    _dereq_('./components/grid'),
    _dereq_('./components/errorbars'),
    _dereq_('./components/colorscale')
]);

// locales en and en-US are required for default behavior
register([
    _dereq_('./locale-en'),
    _dereq_('./locale-en-us')
]);

// plot icons
exports.Icons = _dereq_('../build/ploticon');

// unofficial 'beta' plot methods, use at your own risk
exports.Plots = _dereq_('./plots/plots');
exports.Fx = _dereq_('./components/fx');
exports.Snapshot = _dereq_('./snapshot');
exports.PlotSchema = _dereq_('./plot_api/plot_schema');
exports.Queue = _dereq_('./lib/queue');

// export d3 used in the bundle
exports.d3 = _dereq_('d3');

},{"../build/plotcss":1,"../build/ploticon":2,"./components/annotations":562,"./components/annotations3d":567,"./components/colorscale":583,"./components/errorbars":598,"./components/fx":610,"./components/grid":614,"./components/images":619,"./components/legend":627,"./components/rangeselector":638,"./components/rangeslider":645,"./components/shapes":653,"./components/sliders":658,"./components/updatemenus":664,"./fonts/mathjax_config":674,"./lib/queue":709,"./locale-en":723,"./locale-en-us":722,"./plot_api":727,"./plot_api/plot_schema":731,"./plots/plots":806,"./registry":825,"./snapshot":830,"./traces/scatter":1059,"d3":149,"es6-promise":204}],674:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/* global MathJax:false */

module.exports = function() {
    if(typeof MathJax !== 'undefined') {
        var globalConfig = (window.PlotlyConfig || {}).MathJaxConfig !== 'local';

        if(globalConfig) {
            MathJax.Hub.Config({
                messageStyle: 'none',
                skipStartupTypeset: true,
                displayAlign: 'left',
                tex2jax: {
                    inlineMath: [['$', '$'], ['\\(', '\\)']]
                }
            });
            MathJax.Hub.Configured();
        }
    }
};

},{}],675:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


/**
 * Determine the position anchor property of x/y xanchor/yanchor components.
 *
 * - values < 1/3 align the low side at that fraction,
 * - values [1/3, 2/3] align the center at that fraction,
 * - values > 2/3 align the right at that fraction.
 */


exports.isLeftAnchor = function isLeftAnchor(opts) {
    return (
      opts.xanchor === 'left' ||
      (opts.xanchor === 'auto' && opts.x <= 1 / 3)
    );
};

exports.isCenterAnchor = function isCenterAnchor(opts) {
    return (
        opts.xanchor === 'center' ||
        (opts.xanchor === 'auto' && opts.x > 1 / 3 && opts.x < 2 / 3)
    );
};

exports.isRightAnchor = function isRightAnchor(opts) {
    return (
      opts.xanchor === 'right' ||
      (opts.xanchor === 'auto' && opts.x >= 2 / 3)
    );
};

exports.isTopAnchor = function isTopAnchor(opts) {
    return (
        opts.yanchor === 'top' ||
        (opts.yanchor === 'auto' && opts.y >= 2 / 3)
    );
};

exports.isMiddleAnchor = function isMiddleAnchor(opts) {
    return (
        opts.yanchor === 'middle' ||
        (opts.yanchor === 'auto' && opts.y > 1 / 3 && opts.y < 2 / 3)
    );
};

exports.isBottomAnchor = function isBottomAnchor(opts) {
    return (
      opts.yanchor === 'bottom' ||
      (opts.yanchor === 'auto' && opts.y <= 1 / 3)
    );
};

},{}],676:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var modModule = _dereq_('./mod');
var mod = modModule.mod;
var modHalf = modModule.modHalf;

var PI = Math.PI;
var twoPI = 2 * PI;

function deg2rad(deg) { return deg / 180 * PI; }

function rad2deg(rad) { return rad / PI * 180; }

/**
 * is sector a full circle?
 * ... this comes up a lot in SVG path-drawing routines
 *
 * N.B. we consider all sectors that span more that 2pi 'full' circles
 *
 * @param {2-item array} aBnds : angular bounds in *radians*
 * @return {boolean}
 */
function isFullCircle(aBnds) {
    return Math.abs(aBnds[1] - aBnds[0]) > twoPI - 1e-15;
}

/**
 * angular delta between angle 'a' and 'b'
 * solution taken from: https://stackoverflow.com/a/2007279
 *
 * @param {number} a : first angle in *radians*
 * @param {number} b : second angle in *radians*
 * @return {number} angular delta in *radians*
 */
function angleDelta(a, b) {
    return modHalf(b - a, twoPI);
}

/**
 * angular distance between angle 'a' and 'b'
 *
 * @param {number} a : first angle in *radians*
 * @param {number} b : second angle in *radians*
 * @return {number} angular distance in *radians*
 */
function angleDist(a, b) {
    return Math.abs(angleDelta(a, b));
}

/**
 * is angle inside sector?
 *
 * @param {number} a : angle to test in *radians*
 * @param {2-item array} aBnds : sector's angular bounds in *radians*
 * @param {boolean}
 */
function isAngleInsideSector(a, aBnds) {
    if(isFullCircle(aBnds)) return true;

    var s0, s1;

    if(aBnds[0] < aBnds[1]) {
        s0 = aBnds[0];
        s1 = aBnds[1];
    } else {
        s0 = aBnds[1];
        s1 = aBnds[0];
    }

    s0 = mod(s0, twoPI);
    s1 = mod(s1, twoPI);
    if(s0 > s1) s1 += twoPI;

    var a0 = mod(a, twoPI);
    var a1 = a0 + twoPI;

    return (a0 >= s0 && a0 <= s1) || (a1 >= s0 && a1 <= s1);
}

/**
 * is pt (r,a) inside sector?
 *
 * @param {number} r : pt's radial coordinate
 * @param {number} a : pt's angular coordinate in *radians*
 * @param {2-item array} rBnds : sector's radial bounds
 * @param {2-item array} aBnds : sector's angular bounds in *radians*
 * @return {boolean}
 */
function isPtInsideSector(r, a, rBnds, aBnds) {
    if(!isAngleInsideSector(a, aBnds)) return false;

    var r0, r1;

    if(rBnds[0] < rBnds[1]) {
        r0 = rBnds[0];
        r1 = rBnds[1];
    } else {
        r0 = rBnds[1];
        r1 = rBnds[0];
    }

    return r >= r0 && r <= r1;
}

// common to pathArc, pathSector and pathAnnulus
function _path(r0, r1, a0, a1, cx, cy, isClosed) {
    cx = cx || 0;
    cy = cy || 0;

    var isCircle = isFullCircle([a0, a1]);
    var aStart, aMid, aEnd;
    var rStart, rEnd;

    if(isCircle) {
        aStart = 0;
        aMid = PI;
        aEnd = twoPI;
    } else {
        if(a0 < a1) {
            aStart = a0;
            aEnd = a1;
        } else {
            aStart = a1;
            aEnd = a0;
        }
    }

    if(r0 < r1) {
        rStart = r0;
        rEnd = r1;
    } else {
        rStart = r1;
        rEnd = r0;
    }

    // N.B. svg coordinates here, where y increases downward
    function pt(r, a) {
        return [r * Math.cos(a) + cx, cy - r * Math.sin(a)];
    }

    var largeArc = Math.abs(aEnd - aStart) <= PI ? 0 : 1;
    function arc(r, a, cw) {
        return 'A' + [r, r] + ' ' + [0, largeArc, cw] + ' ' + pt(r, a);
    }

    var p;

    if(isCircle) {
        if(rStart === null) {
            p = 'M' + pt(rEnd, aStart) +
                arc(rEnd, aMid, 0) +
                arc(rEnd, aEnd, 0) + 'Z';
        } else {
            p = 'M' + pt(rStart, aStart) +
                arc(rStart, aMid, 0) +
                arc(rStart, aEnd, 0) + 'Z' +
                'M' + pt(rEnd, aStart) +
                arc(rEnd, aMid, 1) +
                arc(rEnd, aEnd, 1) + 'Z';
        }
    } else {
        if(rStart === null) {
            p = 'M' + pt(rEnd, aStart) + arc(rEnd, aEnd, 0);
            if(isClosed) p += 'L0,0Z';
        } else {
            p = 'M' + pt(rStart, aStart) +
                'L' + pt(rEnd, aStart) +
                arc(rEnd, aEnd, 0) +
                'L' + pt(rStart, aEnd) +
                arc(rStart, aStart, 1) + 'Z';
        }
    }

    return p;
}

/**
 * path an arc
 *
 * @param {number} r : radius
 * @param {number} a0 : first angular coordinate in *radians*
 * @param {number} a1 : second angular coordinate in *radians*
 * @param {number (optional)} cx : x coordinate of center
 * @param {number (optional)} cy : y coordinate of center
 * @return {string} svg path
 */
function pathArc(r, a0, a1, cx, cy) {
    return _path(null, r, a0, a1, cx, cy, 0);
}

/**
 * path a sector
 *
 * @param {number} r : radius
 * @param {number} a0 : first angular coordinate in *radians*
 * @param {number} a1 : second angular coordinate in *radians*
 * @param {number (optional)} cx : x coordinate of center
 * @param {number (optional)} cy : y coordinate of center
 * @return {string} svg path
 */
function pathSector(r, a0, a1, cx, cy) {
    return _path(null, r, a0, a1, cx, cy, 1);
}

/**
 * path an annulus
 *
 * @param {number} r0 : first radial coordinate
 * @param {number} r1 : second radial coordinate
 * @param {number} a0 : first angular coordinate in *radians*
 * @param {number} a1 : second angular coordinate in *radians*
 * @param {number (optional)} cx : x coordinate of center
 * @param {number (optional)} cy : y coordinate of center
 * @return {string} svg path
 */
function pathAnnulus(r0, r1, a0, a1, cx, cy) {
    return _path(r0, r1, a0, a1, cx, cy, 1);
}

module.exports = {
    deg2rad: deg2rad,
    rad2deg: rad2deg,
    angleDelta: angleDelta,
    angleDist: angleDist,
    isFullCircle: isFullCircle,
    isAngleInsideSector: isAngleInsideSector,
    isPtInsideSector: isPtInsideSector,
    pathArc: pathArc,
    pathSector: pathSector,
    pathAnnulus: pathAnnulus
};

},{"./mod":701}],677:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isArray = Array.isArray;

// IE9 fallbacks

var ab = (typeof ArrayBuffer === 'undefined' || !ArrayBuffer.isView) ?
    {isView: function() { return false; }} :
    ArrayBuffer;

var dv = (typeof DataView === 'undefined') ?
    function() {} :
    DataView;

function isTypedArray(a) {
    return ab.isView(a) && !(a instanceof dv);
}
exports.isTypedArray = isTypedArray;

function isArrayOrTypedArray(a) {
    return isArray(a) || isTypedArray(a);
}
exports.isArrayOrTypedArray = isArrayOrTypedArray;

/*
 * Test whether an input object is 1D.
 *
 * Assumes we already know the object is an array.
 *
 * Looks only at the first element, if the dimensionality is
 * not consistent we won't figure that out here.
 */
function isArray1D(a) {
    return !isArrayOrTypedArray(a[0]);
}
exports.isArray1D = isArray1D;

/*
 * Ensures an array has the right amount of storage space. If it doesn't
 * exist, it creates an array. If it does exist, it returns it if too
 * short or truncates it in-place.
 *
 * The goal is to just reuse memory to avoid a bit of excessive garbage
 * collection.
 */
exports.ensureArray = function(out, n) {
    // TODO: typed array support here? This is only used in
    // traces/carpet/compute_control_points
    if(!isArray(out)) out = [];

    // If too long, truncate. (If too short, it will grow
    // automatically so we don't care about that case)
    out.length = n;

    return out;
};

/*
 * TypedArray-compatible concatenation of n arrays
 * if all arrays are the same type it will preserve that type,
 * otherwise it falls back on Array.
 * Also tries to avoid copying, in case one array has zero length
 * But never mutates an existing array
 */
exports.concat = function() {
    var args = [];
    var allArray = true;
    var totalLen = 0;

    var _constructor, arg0, i, argi, posi, leni, out, j;

    for(i = 0; i < arguments.length; i++) {
        argi = arguments[i];
        leni = argi.length;
        if(leni) {
            if(arg0) args.push(argi);
            else {
                arg0 = argi;
                posi = leni;
            }

            if(isArray(argi)) {
                _constructor = false;
            }
            else {
                allArray = false;
                if(!totalLen) {
                    _constructor = argi.constructor;
                }
                else if(_constructor !== argi.constructor) {
                    // TODO: in principle we could upgrade here,
                    // ie keep typed array but convert all to Float64Array?
                    _constructor = false;
                }
            }

            totalLen += leni;
        }
    }

    if(!totalLen) return [];
    if(!args.length) return arg0;

    if(allArray) return arg0.concat.apply(arg0, args);
    if(_constructor) {
        // matching typed arrays
        out = new _constructor(totalLen);
        out.set(arg0);
        for(i = 0; i < args.length; i++) {
            argi = args[i];
            out.set(argi, posi);
            posi += argi.length;
        }
        return out;
    }

    // mismatched types or Array + typed
    out = new Array(totalLen);
    for(j = 0; j < arg0.length; j++) out[j] = arg0[j];
    for(i = 0; i < args.length; i++) {
        argi = args[i];
        for(j = 0; j < argi.length; j++) out[posi + j] = argi[j];
        posi += j;
    }
    return out;
};

exports.maxRowLength = function(z) {
    return _rowLength(z, Math.max, 0);
};

exports.minRowLength = function(z) {
    return _rowLength(z, Math.min, Infinity);
};

function _rowLength(z, fn, len0) {
    if(isArrayOrTypedArray(z)) {
        if(isArrayOrTypedArray(z[0])) {
            var len = len0;
            for(var i = 0; i < z.length; i++) {
                len = fn(len, z[i].length);
            }
            return len;
        } else {
            return z.length;
        }
    }
    return 0;
}

},{}],678:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var BADNUM = _dereq_('../constants/numerical').BADNUM;

// precompile for speed
var JUNK = /^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g;

/**
 * cleanNumber: remove common leading and trailing cruft
 * Always returns either a number or BADNUM.
 */
module.exports = function cleanNumber(v) {
    if(typeof v === 'string') {
        v = v.replace(JUNK, '');
    }

    if(isNumeric(v)) return Number(v);

    return BADNUM;
};

},{"../constants/numerical":671,"fast-isnumeric":215}],679:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * Clear gl frame (if any). This is a common pattern as
 * we usually set `preserveDrawingBuffer: true` during
 * gl context creation (e.g. via `reglUtils.prepare`).
 *
 * @param {DOM node or object} gd : graph div object
 */
module.exports = function clearGlCanvases(gd) {
    var fullLayout = gd._fullLayout;

    if(fullLayout._glcanvas && fullLayout._glcanvas.size()) {
        fullLayout._glcanvas.each(function(d) {
            if(d.regl) d.regl.clear({color: true, depth: true});
        });
    }
};

},{}],680:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * Clear responsive handlers (if any).
 *
 * @param {DOM node or object} gd : graph div object
 */
module.exports = function clearResponsive(gd) {
    if(gd._responsiveChartHandler) {
        window.removeEventListener('resize', gd._responsiveChartHandler);
        delete gd._responsiveChartHandler;
    }
};

},{}],681:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var tinycolor = _dereq_('tinycolor2');

var baseTraceAttrs = _dereq_('../plots/attributes');
var scales = _dereq_('../components/colorscale/scales');
var DESELECTDIM = _dereq_('../constants/interactions').DESELECTDIM;

var nestedProperty = _dereq_('./nested_property');
var counterRegex = _dereq_('./regex').counter;
var modHalf = _dereq_('./mod').modHalf;
var isArrayOrTypedArray = _dereq_('./array').isArrayOrTypedArray;

exports.valObjectMeta = {
    data_array: {
        // You can use *dflt=[] to force said array to exist though.
        
        
        
        coerceFunction: function(v, propOut, dflt) {
            // TODO maybe `v: {type: 'float32', vals: [/* ... */]}` also
            if(isArrayOrTypedArray(v)) propOut.set(v);
            else if(dflt !== undefined) propOut.set(dflt);
        }
    },
    enumerated: {
        
        
        
        coerceFunction: function(v, propOut, dflt, opts) {
            if(opts.coerceNumber) v = +v;
            if(opts.values.indexOf(v) === -1) propOut.set(dflt);
            else propOut.set(v);
        },
        validateFunction: function(v, opts) {
            if(opts.coerceNumber) v = +v;

            var values = opts.values;
            for(var i = 0; i < values.length; i++) {
                var k = String(values[i]);

                if((k.charAt(0) === '/' && k.charAt(k.length - 1) === '/')) {
                    var regex = new RegExp(k.substr(1, k.length - 2));
                    if(regex.test(v)) return true;
                } else if(v === values[i]) return true;
            }
            return false;
        }
    },
    'boolean': {
        
        
        
        coerceFunction: function(v, propOut, dflt) {
            if(v === true || v === false) propOut.set(v);
            else propOut.set(dflt);
        }
    },
    number: {
        
        
        
        coerceFunction: function(v, propOut, dflt, opts) {
            if(!isNumeric(v) ||
                    (opts.min !== undefined && v < opts.min) ||
                    (opts.max !== undefined && v > opts.max)) {
                propOut.set(dflt);
            }
            else propOut.set(+v);
        }
    },
    integer: {
        
        
        
        coerceFunction: function(v, propOut, dflt, opts) {
            if(v % 1 || !isNumeric(v) ||
                    (opts.min !== undefined && v < opts.min) ||
                    (opts.max !== undefined && v > opts.max)) {
                propOut.set(dflt);
            }
            else propOut.set(+v);
        }
    },
    string: {
        
        
        // TODO 'values shouldn't be in there (edge case: 'dash' in Scatter)
        
        coerceFunction: function(v, propOut, dflt, opts) {
            if(typeof v !== 'string') {
                var okToCoerce = (typeof v === 'number');

                if(opts.strict === true || !okToCoerce) propOut.set(dflt);
                else propOut.set(String(v));
            }
            else if(opts.noBlank && !v) propOut.set(dflt);
            else propOut.set(v);
        }
    },
    color: {
        
        
        
        coerceFunction: function(v, propOut, dflt) {
            if(tinycolor(v).isValid()) propOut.set(v);
            else propOut.set(dflt);
        }
    },
    colorlist: {
        
        
        
        coerceFunction: function(v, propOut, dflt) {
            function isColor(color) {
                return tinycolor(color).isValid();
            }
            if(!Array.isArray(v) || !v.length) propOut.set(dflt);
            else if(v.every(isColor)) propOut.set(v);
            else propOut.set(dflt);
        }
    },
    colorscale: {
        
        
        
        coerceFunction: function(v, propOut, dflt) {
            propOut.set(scales.get(v, dflt));
        }
    },
    angle: {
        
        
        
        coerceFunction: function(v, propOut, dflt) {
            if(v === 'auto') propOut.set('auto');
            else if(!isNumeric(v)) propOut.set(dflt);
            else propOut.set(modHalf(+v, 360));
        }
    },
    subplotid: {
        
        
        
        coerceFunction: function(v, propOut, dflt, opts) {
            var regex = opts.regex || counterRegex(dflt);
            if(typeof v === 'string' && regex.test(v)) {
                propOut.set(v);
                return;
            }
            propOut.set(dflt);
        },
        validateFunction: function(v, opts) {
            var dflt = opts.dflt;

            if(v === dflt) return true;
            if(typeof v !== 'string') return false;
            if(counterRegex(dflt).test(v)) return true;

            return false;
        }
    },
    flaglist: {
        
        
        
        coerceFunction: function(v, propOut, dflt, opts) {
            if(typeof v !== 'string') {
                propOut.set(dflt);
                return;
            }
            if((opts.extras || []).indexOf(v) !== -1) {
                propOut.set(v);
                return;
            }
            var vParts = v.split('+');
            var i = 0;
            while(i < vParts.length) {
                var vi = vParts[i];
                if(opts.flags.indexOf(vi) === -1 || vParts.indexOf(vi) < i) {
                    vParts.splice(i, 1);
                }
                else i++;
            }
            if(!vParts.length) propOut.set(dflt);
            else propOut.set(vParts.join('+'));
        }
    },
    any: {
        
        
        
        coerceFunction: function(v, propOut, dflt) {
            if(v === undefined) propOut.set(dflt);
            else propOut.set(v);
        }
    },
    info_array: {
        
        
        // set `dimensions=2` for a 2D array or '1-2' for either
        // `items` may be a single object instead of an array, in which case
        // `freeLength` must be true.
        // if `dimensions='1-2'` and items is a 1D array, then the value can
        // either be a matching 1D array or an array of such matching 1D arrays
        
        coerceFunction: function(v, propOut, dflt, opts) {

            // simplified coerce function just for array items
            function coercePart(v, opts, dflt) {
                var out;
                var propPart = {set: function(v) { out = v; }};

                if(dflt === undefined) dflt = opts.dflt;

                exports.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts);

                return out;
            }

            var twoD = opts.dimensions === 2 || (opts.dimensions === '1-2' && Array.isArray(v) && Array.isArray(v[0]));

            if(!Array.isArray(v)) {
                propOut.set(dflt);
                return;
            }

            var items = opts.items;
            var vOut = [];
            var arrayItems = Array.isArray(items);
            var arrayItems2D = arrayItems && twoD && Array.isArray(items[0]);
            var innerItemsOnly = twoD && arrayItems && !arrayItems2D;
            var len = (arrayItems && !innerItemsOnly) ? items.length : v.length;

            var i, j, row, item, len2, vNew;

            dflt = Array.isArray(dflt) ? dflt : [];

            if(twoD) {
                for(i = 0; i < len; i++) {
                    vOut[i] = [];
                    row = Array.isArray(v[i]) ? v[i] : [];
                    if(innerItemsOnly) len2 = items.length;
                    else if(arrayItems) len2 = items[i].length;
                    else len2 = row.length;

                    for(j = 0; j < len2; j++) {
                        if(innerItemsOnly) item = items[j];
                        else if(arrayItems) item = items[i][j];
                        else item = items;

                        vNew = coercePart(row[j], item, (dflt[i] || [])[j]);
                        if(vNew !== undefined) vOut[i][j] = vNew;
                    }
                }
            }
            else {
                for(i = 0; i < len; i++) {
                    vNew = coercePart(v[i], arrayItems ? items[i] : items, dflt[i]);
                    if(vNew !== undefined) vOut[i] = vNew;
                }
            }

            propOut.set(vOut);
        },
        validateFunction: function(v, opts) {
            if(!Array.isArray(v)) return false;

            var items = opts.items;
            var arrayItems = Array.isArray(items);
            var twoD = opts.dimensions === 2;

            // when free length is off, input and declared lengths must match
            if(!opts.freeLength && v.length !== items.length) return false;

            // valid when all input items are valid
            for(var i = 0; i < v.length; i++) {
                if(twoD) {
                    if(!Array.isArray(v[i]) || (!opts.freeLength && v[i].length !== items[i].length)) {
                        return false;
                    }
                    for(var j = 0; j < v[i].length; j++) {
                        if(!validate(v[i][j], arrayItems ? items[i][j] : items)) {
                            return false;
                        }
                    }
                }
                else if(!validate(v[i], arrayItems ? items[i] : items)) return false;
            }

            return true;
        }
    }
};

/**
 * Ensures that container[attribute] has a valid value.
 *
 * attributes[attribute] is an object with possible keys:
 * - valType: data_array, enumerated, boolean, ... as in valObjectMeta
 * - values: (enumerated only) array of allowed vals
 * - min, max: (number, integer only) inclusive bounds on allowed vals
 *      either or both may be omitted
 * - dflt: if attribute is invalid or missing, use this default
 *      if dflt is provided as an argument to lib.coerce it takes precedence
 *      as a convenience, returns the value it finally set
 */
exports.coerce = function(containerIn, containerOut, attributes, attribute, dflt) {
    var opts = nestedProperty(attributes, attribute).get();
    var propIn = nestedProperty(containerIn, attribute);
    var propOut = nestedProperty(containerOut, attribute);
    var v = propIn.get();

    var template = containerOut._template;
    if(v === undefined && template) {
        v = nestedProperty(template, attribute).get();
        // already used the template value, so short-circuit the second check
        template = 0;
    }

    if(dflt === undefined) dflt = opts.dflt;

    /**
     * arrayOk: value MAY be an array, then we do no value checking
     * at this point, because it can be more complicated than the
     * individual form (eg. some array vals can be numbers, even if the
     * single values must be color strings)
     */
    if(opts.arrayOk && isArrayOrTypedArray(v)) {
        propOut.set(v);
        return v;
    }

    var coerceFunction = exports.valObjectMeta[opts.valType].coerceFunction;
    coerceFunction(v, propOut, dflt, opts);

    var out = propOut.get();
    // in case v was provided but invalid, try the template again so it still
    // overrides the regular default
    if(template && out === dflt && !validate(v, opts)) {
        v = nestedProperty(template, attribute).get();
        coerceFunction(v, propOut, dflt, opts);
        out = propOut.get();
    }
    return out;
};

/**
 * Variation on coerce
 *
 * Uses coerce to get attribute value if user input is valid,
 * returns attribute default if user input it not valid or
 * returns false if there is no user input.
 */
exports.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) {
    var propIn = nestedProperty(containerIn, attribute);
    var propOut = exports.coerce(containerIn, containerOut, attributes, attribute, dflt);
    var valIn = propIn.get();

    return (valIn !== undefined && valIn !== null) ? propOut : false;
};

/*
 * Shortcut to coerce the three font attributes
 *
 * 'coerce' is a lib.coerce wrapper with implied first three arguments
 */
exports.coerceFont = function(coerce, attr, dfltObj) {
    var out = {};

    dfltObj = dfltObj || {};

    out.family = coerce(attr + '.family', dfltObj.family);
    out.size = coerce(attr + '.size', dfltObj.size);
    out.color = coerce(attr + '.color', dfltObj.color);

    return out;
};

/** Coerce shortcut for 'hoverinfo'
 * handling 1-vs-multi-trace dflt logic
 *
 * @param {object} traceIn : user trace object
 * @param {object} traceOut : full trace object (requires _module ref)
 * @param {object} layoutOut : full layout object (require _dataLength ref)
 * @return {any} : the coerced value
 */
exports.coerceHoverinfo = function(traceIn, traceOut, layoutOut) {
    var moduleAttrs = traceOut._module.attributes;
    var attrs = moduleAttrs.hoverinfo ? moduleAttrs : baseTraceAttrs;

    var valObj = attrs.hoverinfo;
    var dflt;

    if(layoutOut._dataLength === 1) {
        var flags = valObj.dflt === 'all' ?
            valObj.flags.slice() :
            valObj.dflt.split('+');

        flags.splice(flags.indexOf('name'), 1);
        dflt = flags.join('+');
    }

    return exports.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt);
};

/** Coerce shortcut for [un]selected.marker.opacity,
 *  which has special default logic, to ensure that it corresponds to the
 *  default selection behavior while allowing to be overtaken by any other
 *  [un]selected attribute.
 *
 *  N.B. This must be called *after* coercing all the other [un]selected attrs,
 *  to give the intended result.
 *
 * @param {object} traceOut : fullData item
 * @param {function} coerce : lib.coerce wrapper with implied first three arguments
 */
exports.coerceSelectionMarkerOpacity = function(traceOut, coerce) {
    if(!traceOut.marker) return;

    var mo = traceOut.marker.opacity;
    // you can still have a `marker` container with no markers if there's text
    if(mo === undefined) return;

    var smoDflt;
    var usmoDflt;

    // Don't give [un]selected.marker.opacity a default value if
    // marker.opacity is an array: handle this during style step.
    //
    // Only give [un]selected.marker.opacity a default value if you don't
    // set any other [un]selected attributes.
    if(!isArrayOrTypedArray(mo) && !traceOut.selected && !traceOut.unselected) {
        smoDflt = mo;
        usmoDflt = DESELECTDIM * mo;
    }

    coerce('selected.marker.opacity', smoDflt);
    coerce('unselected.marker.opacity', usmoDflt);
};

function validate(value, opts) {
    var valObjectDef = exports.valObjectMeta[opts.valType];

    if(opts.arrayOk && isArrayOrTypedArray(value)) return true;

    if(valObjectDef.validateFunction) {
        return valObjectDef.validateFunction(value, opts);
    }

    var failed = {};
    var out = failed;
    var propMock = { set: function(v) { out = v; } };

    // 'failed' just something mutable that won't be === anything else

    valObjectDef.coerceFunction(value, propMock, failed, opts);
    return out !== failed;
}
exports.validate = validate;

},{"../components/colorscale/scales":586,"../constants/interactions":670,"../plots/attributes":739,"./array":677,"./mod":701,"./nested_property":702,"./regex":710,"fast-isnumeric":215,"tinycolor2":515}],682:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');

var Loggers = _dereq_('./loggers');
var mod = _dereq_('./mod').mod;

var constants = _dereq_('../constants/numerical');
var BADNUM = constants.BADNUM;
var ONEDAY = constants.ONEDAY;
var ONEHOUR = constants.ONEHOUR;
var ONEMIN = constants.ONEMIN;
var ONESEC = constants.ONESEC;
var EPOCHJD = constants.EPOCHJD;

var Registry = _dereq_('../registry');

var utcFormat = d3.time.format.utc;

var DATETIME_REGEXP = /^\s*(-?\d\d\d\d|\d\d)(-(\d?\d)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d:?\d\d)?)?)?)?)?\s*$/m;
// special regex for chinese calendars to support yyyy-mmi-dd etc for intercalary months
var DATETIME_REGEXP_CN = /^\s*(-?\d\d\d\d|\d\d)(-(\d?\di?)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d:?\d\d)?)?)?)?)?\s*$/m;

// for 2-digit years, the first year we map them onto
var YFIRST = new Date().getFullYear() - 70;

function isWorldCalendar(calendar) {
    return (
        calendar &&
        Registry.componentsRegistry.calendars &&
        typeof calendar === 'string' && calendar !== 'gregorian'
    );
}

/*
 * dateTick0: get the canonical tick for this calendar
 *
 * bool sunday is for week ticks, shift it to a Sunday.
 */
exports.dateTick0 = function(calendar, sunday) {
    if(isWorldCalendar(calendar)) {
        return sunday ?
            Registry.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] :
            Registry.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar];
    }
    else {
        return sunday ? '2000-01-02' : '2000-01-01';
    }
};

/*
 * dfltRange: for each calendar, give a valid default range
 */
exports.dfltRange = function(calendar) {
    if(isWorldCalendar(calendar)) {
        return Registry.getComponentMethod('calendars', 'DFLTRANGE')[calendar];
    }
    else {
        return ['2000-01-01', '2001-01-01'];
    }
};

// is an object a javascript date?
exports.isJSDate = function(v) {
    return typeof v === 'object' && v !== null && typeof v.getTime === 'function';
};

// The absolute limits of our date-time system
// This is a little weird: we use MIN_MS and MAX_MS in dateTime2ms
// but we use dateTime2ms to calculate them (after defining it!)
var MIN_MS, MAX_MS;

/**
 * dateTime2ms - turn a date object or string s into milliseconds
 * (relative to 1970-01-01, per javascript standard)
 * optional calendar (string) to use a non-gregorian calendar
 *
 * Returns BADNUM if it doesn't find a date
 *
 * strings should have the form:
 *
 *    -?YYYY-mm-dd<sep>HH:MM:SS.sss<tzInfo>?
 *
 * <sep>: space (our normal standard) or T or t (ISO-8601)
 * <tzInfo>: Z, z, or [+\-]HH:?MM and we THROW IT AWAY
 * this format comes from https://tools.ietf.org/html/rfc3339#section-5.6
 * but we allow it even with a space as the separator
 *
 * May truncate after any full field, and sss can be any length
 * even >3 digits, though javascript dates truncate to milliseconds,
 * we keep as much as javascript numeric precision can hold, but we only
 * report back up to 100 microsecond precision, because most dates support
 * this precision (close to 1970 support more, very far away support less)
 *
 * Expanded to support negative years to -9999 but you must always
 * give 4 digits, except for 2-digit positive years which we assume are
 * near the present time.
 * Note that we follow ISO 8601:2004: there *is* a year 0, which
 * is 1BC/BCE, and -1===2BC etc.
 *
 * World calendars: not all of these *have* agreed extensions to this full range,
 * if you have another calendar system but want a date range outside its validity,
 * you can use a gregorian date string prefixed with 'G' or 'g'.
 *
 * Where to cut off 2-digit years between 1900s and 2000s?
 * from http://support.microsoft.com/kb/244664:
 *   1930-2029 (the most retro of all...)
 * but in my mac chrome from eg. d=new Date(Date.parse('8/19/50')):
 *   1950-2049
 * by Java, from http://stackoverflow.com/questions/2024273/:
 *   now-80 - now+19
 * or FileMaker Pro, from
 *      http://www.filemaker.com/12help/html/add_view_data.4.21.html:
 *   now-70 - now+29
 * but python strptime etc, via
 *      http://docs.python.org/py3k/library/time.html:
 *   1969-2068 (super forward-looking, but static, not sliding!)
 *
 * lets go with now-70 to now+29, and if anyone runs into this problem
 * they can learn the hard way not to use 2-digit years, as no choice we
 * make now will cover all possibilities. mostly this will all be taken
 * care of in initial parsing, should only be an issue for hand-entered data
 * currently (2016) this range is:
 *   1946-2045
 */
exports.dateTime2ms = function(s, calendar) {
    // first check if s is a date object
    if(exports.isJSDate(s)) {
        // Convert to the UTC milliseconds that give the same
        // hours as this date has in the local timezone
        var tzOffset = s.getTimezoneOffset() * ONEMIN;
        var offsetTweak = (s.getUTCMinutes() - s.getMinutes()) * ONEMIN +
            (s.getUTCSeconds() - s.getSeconds()) * ONESEC +
            (s.getUTCMilliseconds() - s.getMilliseconds());

        if(offsetTweak) {
            var comb = 3 * ONEMIN;
            tzOffset = tzOffset - comb / 2 + mod(offsetTweak - tzOffset + comb / 2, comb);
        }
        s = Number(s) - tzOffset;
        if(s >= MIN_MS && s <= MAX_MS) return s;
        return BADNUM;
    }
    // otherwise only accept strings and numbers
    if(typeof s !== 'string' && typeof s !== 'number') return BADNUM;

    s = String(s);

    var isWorld = isWorldCalendar(calendar);

    // to handle out-of-range dates in international calendars, accept
    // 'G' as a prefix to force the built-in gregorian calendar.
    var s0 = s.charAt(0);
    if(isWorld && (s0 === 'G' || s0 === 'g')) {
        s = s.substr(1);
        calendar = '';
    }

    var isChinese = isWorld && calendar.substr(0, 7) === 'chinese';

    var match = s.match(isChinese ? DATETIME_REGEXP_CN : DATETIME_REGEXP);
    if(!match) return BADNUM;
    var y = match[1];
    var m = match[3] || '1';
    var d = Number(match[5] || 1);
    var H = Number(match[7] || 0);
    var M = Number(match[9] || 0);
    var S = Number(match[11] || 0);

    if(isWorld) {
        // disallow 2-digit years for world calendars
        if(y.length === 2) return BADNUM;
        y = Number(y);

        var cDate;
        try {
            var calInstance = Registry.getComponentMethod('calendars', 'getCal')(calendar);
            if(isChinese) {
                var isIntercalary = m.charAt(m.length - 1) === 'i';
                m = parseInt(m, 10);
                cDate = calInstance.newDate(y, calInstance.toMonthIndex(y, m, isIntercalary), d);
            }
            else {
                cDate = calInstance.newDate(y, Number(m), d);
            }
        }
        catch(e) { return BADNUM; } // Invalid ... date

        if(!cDate) return BADNUM;

        return ((cDate.toJD() - EPOCHJD) * ONEDAY) +
            (H * ONEHOUR) + (M * ONEMIN) + (S * ONESEC);
    }

    if(y.length === 2) {
        y = (Number(y) + 2000 - YFIRST) % 100 + YFIRST;
    }
    else y = Number(y);

    // new Date uses months from 0; subtract 1 here just so we
    // don't have to do it again during the validity test below
    m -= 1;

    // javascript takes new Date(0..99,m,d) to mean 1900-1999, so
    // to support years 0-99 we need to use setFullYear explicitly
    // Note that 2000 is a leap year.
    var date = new Date(Date.UTC(2000, m, d, H, M));
    date.setUTCFullYear(y);

    if(date.getUTCMonth() !== m) return BADNUM;
    if(date.getUTCDate() !== d) return BADNUM;

    return date.getTime() + S * ONESEC;
};

MIN_MS = exports.MIN_MS = exports.dateTime2ms('-9999');
MAX_MS = exports.MAX_MS = exports.dateTime2ms('9999-12-31 23:59:59.9999');

// is string s a date? (see above)
exports.isDateTime = function(s, calendar) {
    return (exports.dateTime2ms(s, calendar) !== BADNUM);
};

// pad a number with zeroes, to given # of digits before the decimal point
function lpad(val, digits) {
    return String(val + Math.pow(10, digits)).substr(1);
}

/**
 * Turn ms into string of the form YYYY-mm-dd HH:MM:SS.ssss
 * Crop any trailing zeros in time, except never stop right after hours
 * (we could choose to crop '-01' from date too but for now we always
 * show the whole date)
 * Optional range r is the data range that applies, also in ms.
 * If rng is big, the later parts of time will be omitted
 */
var NINETYDAYS = 90 * ONEDAY;
var THREEHOURS = 3 * ONEHOUR;
var FIVEMIN = 5 * ONEMIN;
exports.ms2DateTime = function(ms, r, calendar) {
    if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return BADNUM;

    if(!r) r = 0;

    var msecTenths = Math.floor(mod(ms + 0.05, 1) * 10);
    var msRounded = Math.round(ms - msecTenths / 10);
    var dateStr, h, m, s, msec10, d;

    if(isWorldCalendar(calendar)) {
        var dateJD = Math.floor(msRounded / ONEDAY) + EPOCHJD;
        var timeMs = Math.floor(mod(ms, ONEDAY));
        try {
            dateStr = Registry.getComponentMethod('calendars', 'getCal')(calendar)
                .fromJD(dateJD).formatDate('yyyy-mm-dd');
        } catch(e) {
            // invalid date in this calendar - fall back to Gyyyy-mm-dd
            dateStr = utcFormat('G%Y-%m-%d')(new Date(msRounded));
        }

        // yyyy does NOT guarantee 4-digit years. YYYY mostly does, but does
        // other things for a few calendars, so we can't trust it. Just pad
        // it manually (after the '-' if there is one)
        if(dateStr.charAt(0) === '-') {
            while(dateStr.length < 11) dateStr = '-0' + dateStr.substr(1);
        } else {
            while(dateStr.length < 10) dateStr = '0' + dateStr;
        }

        // TODO: if this is faster, we could use this block for extracting
        // the time components of regular gregorian too
        h = (r < NINETYDAYS) ? Math.floor(timeMs / ONEHOUR) : 0;
        m = (r < NINETYDAYS) ? Math.floor((timeMs % ONEHOUR) / ONEMIN) : 0;
        s = (r < THREEHOURS) ? Math.floor((timeMs % ONEMIN) / ONESEC) : 0;
        msec10 = (r < FIVEMIN) ? (timeMs % ONESEC) * 10 + msecTenths : 0;
    }
    else {
        d = new Date(msRounded);

        dateStr = utcFormat('%Y-%m-%d')(d);

        // <90 days: add hours and minutes - never *only* add hours
        h = (r < NINETYDAYS) ? d.getUTCHours() : 0;
        m = (r < NINETYDAYS) ? d.getUTCMinutes() : 0;
        // <3 hours: add seconds
        s = (r < THREEHOURS) ? d.getUTCSeconds() : 0;
        // <5 minutes: add ms (plus one extra digit, this is msec*10)
        msec10 = (r < FIVEMIN) ? d.getUTCMilliseconds() * 10 + msecTenths : 0;
    }

    return includeTime(dateStr, h, m, s, msec10);
};

// For converting old-style milliseconds to date strings,
// we use the local timezone rather than UTC like we use
// everywhere else, both for backward compatibility and
// because that's how people mostly use javasript date objects.
// Clip one extra day off our date range though so we can't get
// thrown beyond the range by the timezone shift.
exports.ms2DateTimeLocal = function(ms) {
    if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return BADNUM;

    var msecTenths = Math.floor(mod(ms + 0.05, 1) * 10);
    var d = new Date(Math.round(ms - msecTenths / 10));
    var dateStr = d3.time.format('%Y-%m-%d')(d);
    var h = d.getHours();
    var m = d.getMinutes();
    var s = d.getSeconds();
    var msec10 = d.getUTCMilliseconds() * 10 + msecTenths;

    return includeTime(dateStr, h, m, s, msec10);
};

function includeTime(dateStr, h, m, s, msec10) {
    // include each part that has nonzero data in or after it
    if(h || m || s || msec10) {
        dateStr += ' ' + lpad(h, 2) + ':' + lpad(m, 2);
        if(s || msec10) {
            dateStr += ':' + lpad(s, 2);
            if(msec10) {
                var digits = 4;
                while(msec10 % 10 === 0) {
                    digits -= 1;
                    msec10 /= 10;
                }
                dateStr += '.' + lpad(msec10, digits);
            }
        }
    }
    return dateStr;
}

// normalize date format to date string, in case it starts as
// a Date object or milliseconds
// optional dflt is the return value if cleaning fails
exports.cleanDate = function(v, dflt, calendar) {
    // let us use cleanDate to provide a missing default without an error
    if(v === BADNUM) return dflt;
    if(exports.isJSDate(v) || (typeof v === 'number' && isFinite(v))) {
        // do not allow milliseconds (old) or jsdate objects (inherently
        // described as gregorian dates) with world calendars
        if(isWorldCalendar(calendar)) {
            Loggers.error('JS Dates and milliseconds are incompatible with world calendars', v);
            return dflt;
        }

        // NOTE: if someone puts in a year as a number rather than a string,
        // this will mistakenly convert it thinking it's milliseconds from 1970
        // that is: '2012' -> Jan. 1, 2012, but 2012 -> 2012 epoch milliseconds
        v = exports.ms2DateTimeLocal(+v);
        if(!v && dflt !== undefined) return dflt;
    }
    else if(!exports.isDateTime(v, calendar)) {
        Loggers.error('unrecognized date', v);
        return dflt;
    }
    return v;
};

/*
 *  Date formatting for ticks and hovertext
 */

/*
 * modDateFormat: Support world calendars, and add one item to
 * d3's vocabulary:
 * %{n}f where n is the max number of digits of fractional seconds
 */
var fracMatch = /%\d?f/g;
function modDateFormat(fmt, x, formatter, calendar) {

    fmt = fmt.replace(fracMatch, function(match) {
        var digits = Math.min(+(match.charAt(1)) || 6, 6);
        var fracSecs = ((x / 1000 % 1) + 2)
            .toFixed(digits)
            .substr(2).replace(/0+$/, '') || '0';
        return fracSecs;
    });

    var d = new Date(Math.floor(x + 0.05));

    if(isWorldCalendar(calendar)) {
        try {
            fmt = Registry.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar);
        }
        catch(e) {
            return 'Invalid';
        }
    }
    return formatter(fmt)(d);
}

/*
 * formatTime: create a time string from:
 *   x: milliseconds
 *   tr: tickround ('M', 'S', or # digits)
 * only supports UTC times (where every day is 24 hours and 0 is at midnight)
 */
var MAXSECONDS = [59, 59.9, 59.99, 59.999, 59.9999];
function formatTime(x, tr) {
    var timePart = mod(x + 0.05, ONEDAY);

    var timeStr = lpad(Math.floor(timePart / ONEHOUR), 2) + ':' +
        lpad(mod(Math.floor(timePart / ONEMIN), 60), 2);

    if(tr !== 'M') {
        if(!isNumeric(tr)) tr = 0; // should only be 'S'

        /*
         * this is a weird one - and shouldn't come up unless people
         * monkey with tick0 in weird ways, but we need to do something!
         * IN PARTICULAR we had better not display garbage (see below)
         * for numbers we always round to the nearest increment of the
         * precision we're showing, and this seems like the right way to
         * handle seconds and milliseconds, as they have a decimal point
         * and people will interpret that to mean rounding like numbers.
         * but for larger increments we floor the value: it's always
         * 2013 until the ball drops on the new year. We could argue about
         * which field it is where we start rounding (should 12:08:59
         * round to 12:09 if we're stopping at minutes?) but for now I'll
         * say we round seconds but floor everything else. BUT that means
         * we need to never round up to 60 seconds, ie 23:59:60
         */
        var sec = Math.min(mod(x / ONESEC, 60), MAXSECONDS[tr]);

        var secStr = (100 + sec).toFixed(tr).substr(1);
        if(tr > 0) {
            secStr = secStr.replace(/0+$/, '').replace(/[\.]$/, '');
        }

        timeStr += ':' + secStr;
    }
    return timeStr;
}

/*
 * formatDate: turn a date into tick or hover label text.
 *
 *   x: milliseconds, the value to convert
 *   fmt: optional, an explicit format string (d3 format, even for world calendars)
 *   tr: tickround ('y', 'm', 'd', 'M', 'S', or # digits)
 *      used if no explicit fmt is provided
 *   formatter: locale-aware d3 date formatter for standard gregorian calendars
 *      should be the result of exports.getD3DateFormat(gd)
 *   calendar: optional string, the world calendar system to use
 *
 * returns the date/time as a string, potentially with the leading portion
 * on a separate line (after '\n')
 * Note that this means if you provide an explicit format which includes '\n'
 * the axis may choose to strip things after it when they don't change from
 * one tick to the next (as it does with automatic formatting)
 */
exports.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) {
    calendar = isWorldCalendar(calendar) && calendar;

    if(!fmt) {
        if(tr === 'y') fmt = extraFormat.year;
        else if(tr === 'm') fmt = extraFormat.month;
        else if(tr === 'd') {
            fmt = extraFormat.dayMonth + '\n' + extraFormat.year;
        }
        else {
            return formatTime(x, tr) + '\n' + modDateFormat(extraFormat.dayMonthYear, x, formatter, calendar);
        }
    }

    return modDateFormat(fmt, x, formatter, calendar);
};

/*
 * incrementMonth: make a new milliseconds value from the given one,
 * having changed the month
 *
 * special case for world calendars: multiples of 12 are treated as years,
 * even for calendar systems that don't have (always or ever) 12 months/year
 * TODO: perhaps we need a different code for year increments to support this?
 *
 * ms (number): the initial millisecond value
 * dMonth (int): the (signed) number of months to shift
 * calendar (string): the calendar system to use
 *
 * changing month does not (and CANNOT) always preserve day, since
 * months have different lengths. The worst example of this is:
 *   d = new Date(1970,0,31); d.setMonth(1) -> Feb 31 turns into Mar 3
 *
 * But we want to be able to iterate over the last day of each month,
 * regardless of what its number is.
 * So shift 3 days forward, THEN set the new month, then unshift:
 *   1/31 -> 2/28 (or 29) -> 3/31 -> 4/30 -> ...
 *
 * Note that odd behavior still exists if you start from the 26th-28th:
 *   1/28 -> 2/28 -> 3/31
 * but at least you can't shift any dates into the wrong month,
 * and ticks on these days incrementing by month would be very unusual
 */
var THREEDAYS = 3 * ONEDAY;
exports.incrementMonth = function(ms, dMonth, calendar) {
    calendar = isWorldCalendar(calendar) && calendar;

    // pull time out and operate on pure dates, then add time back at the end
    // this gives maximum precision - not that we *normally* care if we're
    // incrementing by month, but better to be safe!
    var timeMs = mod(ms, ONEDAY);
    ms = Math.round(ms - timeMs);

    if(calendar) {
        try {
            var dateJD = Math.round(ms / ONEDAY) + EPOCHJD;
            var calInstance = Registry.getComponentMethod('calendars', 'getCal')(calendar);
            var cDate = calInstance.fromJD(dateJD);

            if(dMonth % 12) calInstance.add(cDate, dMonth, 'm');
            else calInstance.add(cDate, dMonth / 12, 'y');

            return (cDate.toJD() - EPOCHJD) * ONEDAY + timeMs;
        } catch(e) {
            Loggers.error('invalid ms ' + ms + ' in calendar ' + calendar);
            // then keep going in gregorian even though the result will be 'Invalid'
        }
    }

    var y = new Date(ms + THREEDAYS);
    return y.setUTCMonth(y.getUTCMonth() + dMonth) + timeMs - THREEDAYS;
};

/*
 * findExactDates: what fraction of data is exact days, months, or years?
 *
 * data: array of millisecond values
 * calendar (string) the calendar to test against
 */
exports.findExactDates = function(data, calendar) {
    var exactYears = 0;
    var exactMonths = 0;
    var exactDays = 0;
    var blankCount = 0;
    var d;
    var di;

    var calInstance = (
        isWorldCalendar(calendar) &&
        Registry.getComponentMethod('calendars', 'getCal')(calendar)
    );

    for(var i = 0; i < data.length; i++) {
        di = data[i];

        // not date data at all
        if(!isNumeric(di)) {
            blankCount ++;
            continue;
        }

        // not an exact date
        if(di % ONEDAY) continue;

        if(calInstance) {
            try {
                d = calInstance.fromJD(di / ONEDAY + EPOCHJD);
                if(d.day() === 1) {
                    if(d.month() === 1) exactYears++;
                    else exactMonths++;
                }
                else exactDays++;
            }
            catch(e) {
                // invalid date in this calendar - ignore it here.
            }
        }
        else {
            d = new Date(di);
            if(d.getUTCDate() === 1) {
                if(d.getUTCMonth() === 0) exactYears++;
                else exactMonths++;
            }
            else exactDays++;
        }
    }
    exactMonths += exactYears;
    exactDays += exactMonths;

    var dataCount = data.length - blankCount;

    return {
        exactYears: exactYears / dataCount,
        exactMonths: exactMonths / dataCount,
        exactDays: exactDays / dataCount
    };
};

},{"../constants/numerical":671,"../registry":825,"./loggers":698,"./mod":701,"d3":149,"fast-isnumeric":215}],683:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

/* global jQuery:false */

var EventEmitter = _dereq_('events').EventEmitter;

var Events = {

    init: function(plotObj) {

        /*
         * If we have already instantiated an emitter for this plot
         * return early.
         */
        if(plotObj._ev instanceof EventEmitter) return plotObj;

        var ev = new EventEmitter();
        var internalEv = new EventEmitter();

        /*
         * Assign to plot._ev while we still live in a land
         * where plot is a DOM element with stuff attached to it.
         * In the future we can make plot the event emitter itself.
         */
        plotObj._ev = ev;

        /*
         * Create a second event handler that will manage events *internally*.
         * This allows parts of plotly to respond to thing like relayout without
         * having to use the user-facing event handler. They cannot peacefully
         * coexist on the same handler because a user invoking
         * plotObj.removeAllListeners() would detach internal events, breaking
         * plotly.
         */
        plotObj._internalEv = internalEv;

        /*
         * Assign bound methods from the ev to the plot object. These methods
         * will reference the 'this' of plot._ev even though they are methods
         * of plot. This will keep the event machinery away from the plot object
         * which currently is often a DOM element but presents an API that will
         * continue to function when plot becomes an emitter. Not all EventEmitter
         * methods have been bound to `plot` as some do not currently add value to
         * the Plotly event API.
         */
        plotObj.on = ev.on.bind(ev);
        plotObj.once = ev.once.bind(ev);
        plotObj.removeListener = ev.removeListener.bind(ev);
        plotObj.removeAllListeners = ev.removeAllListeners.bind(ev);

        /*
         * Create functions for managing internal events. These are *only* triggered
         * by the mirroring of external events via the emit function.
         */
        plotObj._internalOn = internalEv.on.bind(internalEv);
        plotObj._internalOnce = internalEv.once.bind(internalEv);
        plotObj._removeInternalListener = internalEv.removeListener.bind(internalEv);
        plotObj._removeAllInternalListeners = internalEv.removeAllListeners.bind(internalEv);

        /*
         * We must wrap emit to continue to support JQuery events. The idea
         * is to check to see if the user is using JQuery events, if they are
         * we emit JQuery events to trigger user handlers as well as the EventEmitter
         * events.
         */
        plotObj.emit = function(event, data) {
            if(typeof jQuery !== 'undefined') {
                jQuery(plotObj).trigger(event, data);
            }

            ev.emit(event, data);
            internalEv.emit(event, data);
        };

        return plotObj;
    },

    /*
     * This function behaves like jQuery's triggerHandler. It calls
     * all handlers for a particular event and returns the return value
     * of the LAST handler. This function also triggers jQuery's
     * triggerHandler for backwards compatibility.
     */
    triggerHandler: function(plotObj, event, data) {
        var jQueryHandlerValue;
        var nodeEventHandlerValue;

        /*
         * If jQuery exists run all its handlers for this event and
         * collect the return value of the LAST handler function
         */
        if(typeof jQuery !== 'undefined') {
            jQueryHandlerValue = jQuery(plotObj).triggerHandler(event, data);
        }

        /*
         * Now run all the node style event handlers
         */
        var ev = plotObj._ev;
        if(!ev) return jQueryHandlerValue;

        var handlers = ev._events[event];
        if(!handlers) return jQueryHandlerValue;

        // making sure 'this' is the EventEmitter instance
        function apply(handler) {
            // The 'once' case, we can't just call handler() as we need
            // the return value here. So,
            // - remove handler
            // - call listener and grab return value!
            // - stash 'fired' key to not call handler twice
            if(handler.listener) {
                ev.removeListener(event, handler.listener);
                if(!handler.fired) {
                    handler.fired = true;
                    return handler.listener.apply(ev, [data]);
                }
            } else {
                return handler.apply(ev, [data]);
            }
        }

        // handlers can be function or an array of functions
        handlers = Array.isArray(handlers) ? handlers : [handlers];

        var i;
        for(i = 0; i < handlers.length - 1; i++) {
            apply(handlers[i]);
        }
        // now call the final handler and collect its value
        nodeEventHandlerValue = apply(handlers[i]);

        /*
         * Return either the jQuery handler value if it exists or the
         * nodeEventHandler value. jQuery event value supersedes nodejs
         * events for backwards compatibility reasons.
         */
        return jQueryHandlerValue !== undefined ?
            jQueryHandlerValue :
            nodeEventHandlerValue;
    },

    purge: function(plotObj) {
        delete plotObj._ev;
        delete plotObj.on;
        delete plotObj.once;
        delete plotObj.removeListener;
        delete plotObj.removeAllListeners;
        delete plotObj.emit;

        delete plotObj._ev;
        delete plotObj._internalEv;
        delete plotObj._internalOn;
        delete plotObj._internalOnce;
        delete plotObj._removeInternalListener;
        delete plotObj._removeAllInternalListeners;

        return plotObj;
    }

};

module.exports = Events;

},{"events":93}],684:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isPlainObject = _dereq_('./is_plain_object.js');
var isArray = Array.isArray;

function primitivesLoopSplice(source, target) {
    var i, value;
    for(i = 0; i < source.length; i++) {
        value = source[i];
        if(value !== null && typeof(value) === 'object') {
            return false;
        }
        if(value !== void(0)) {
            target[i] = value;
        }
    }
    return true;
}

exports.extendFlat = function() {
    return _extend(arguments, false, false, false);
};

exports.extendDeep = function() {
    return _extend(arguments, true, false, false);
};

exports.extendDeepAll = function() {
    return _extend(arguments, true, true, false);
};

exports.extendDeepNoArrays = function() {
    return _extend(arguments, true, false, true);
};

/*
 * Inspired by https://github.com/justmoon/node-extend/blob/master/index.js
 * All credit to the jQuery authors for perfecting this amazing utility.
 *
 * API difference with jQuery version:
 * - No optional boolean (true -> deep extend) first argument,
 *   use `extendFlat` for first-level only extend and
 *   use `extendDeep` for a deep extend.
 *
 * Other differences with jQuery version:
 * - Uses a modern (and faster) isPlainObject routine.
 * - Expected to work with object {} and array [] arguments only.
 * - Does not check for circular structure.
 *   FYI: jQuery only does a check across one level.
 *   Warning: this might result in infinite loops.
 *
 */
function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) {
    var target = inputs[0];
    var length = inputs.length;

    var input, key, src, copy, copyIsArray, clone, allPrimitives;

    // TODO does this do the right thing for typed arrays?

    if(length === 2 && isArray(target) && isArray(inputs[1]) && target.length === 0) {

        allPrimitives = primitivesLoopSplice(inputs[1], target);

        if(allPrimitives) {
            return target;
        } else {
            target.splice(0, target.length); // reset target and continue to next block
        }
    }

    for(var i = 1; i < length; i++) {
        input = inputs[i];

        for(key in input) {
            src = target[key];
            copy = input[key];

            // Stop early and just transfer the array if array copies are disallowed:
            if(noArrayCopies && isArray(copy)) {
                target[key] = copy;
            }

            // recurse if we're merging plain objects or arrays
            else if(isDeep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
                if(copyIsArray) {
                    copyIsArray = false;
                    clone = src && isArray(src) ? src : [];
                } else {
                    clone = src && isPlainObject(src) ? src : {};
                }

                // never move original objects, clone them
                target[key] = _extend([clone, copy], isDeep, keepAllKeys, noArrayCopies);
            }

            // don't bring in undefined values, except for extendDeepAll
            else if(typeof copy !== 'undefined' || keepAllKeys) {
                target[key] = copy;
            }
        }
    }

    return target;
}

},{"./is_plain_object.js":695}],685:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


/**
 * Return news array containing only the unique items
 * found in input array.
 *
 * IMPORTANT: Note that items are considered unique
 * if `String({})` is unique. For example;
 *
 *  Lib.filterUnique([ { a: 1 }, { b: 2 } ])
 *
 *  returns [{ a: 1 }]
 *
 * and
 *
 *  Lib.filterUnique([ '1', 1 ])
 *
 *  returns ['1']
 *
 *
 * @param {array} array base array
 * @return {array} new filtered array
 */
module.exports = function filterUnique(array) {
    var seen = {};
    var out = [];
    var j = 0;

    for(var i = 0; i < array.length; i++) {
        var item = array[i];

        if(seen[item] !== 1) {
            seen[item] = 1;
            out[j++] = item;
        }
    }

    return out;
};

},{}],686:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/** Filter out object items with visible !== true
 *  insider array container.
 *
 *  @param {array of objects} container
 *  @return {array of objects} of length <= container
 *
 */
module.exports = function filterVisible(container) {
    var filterFn = isCalcData(container) ? calcDataFilter : baseFilter;
    var out = [];

    for(var i = 0; i < container.length; i++) {
        var item = container[i];
        if(filterFn(item)) out.push(item);
    }

    return out;
};

function baseFilter(item) {
    return item.visible === true;
}

function calcDataFilter(item) {
    return item[0].trace.visible === true;
}

function isCalcData(cont) {
    return (
        Array.isArray(cont) &&
        Array.isArray(cont[0]) &&
        cont[0][0] &&
        cont[0][0].trace
    );
}

},{}],687:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var countryRegex = _dereq_('country-regex');
var Lib = _dereq_('../lib');


// make list of all country iso3 ids from at runtime
var countryIds = Object.keys(countryRegex);

var locationmodeToIdFinder = {
    'ISO-3': Lib.identity,
    'USA-states': Lib.identity,
    'country names': countryNameToISO3
};

exports.locationToFeature = function(locationmode, location, features) {
    if(!location || typeof location !== 'string') return false;

    var locationId = getLocationId(locationmode, location);

    if(locationId) {
        for(var i = 0; i < features.length; i++) {
            var feature = features[i];

            if(feature.id === locationId) return feature;
        }

        Lib.log([
            'Location with id', locationId,
            'does not have a matching topojson feature at this resolution.'
        ].join(' '));
    }

    return false;
};

function getLocationId(locationmode, location) {
    var idFinder = locationmodeToIdFinder[locationmode];
    return idFinder(location);
}

function countryNameToISO3(countryName) {
    for(var i = 0; i < countryIds.length; i++) {
        var iso3 = countryIds[i];
        var regex = new RegExp(countryRegex[iso3]);

        if(regex.test(countryName.trim().toLowerCase())) return iso3;
    }

    Lib.log('Unrecognized country name: ' + countryName + '.');

    return false;
}

},{"../lib":694,"country-regex":123}],688:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var BADNUM = _dereq_('../constants/numerical').BADNUM;

/**
 * Convert calcTrace to GeoJSON 'MultiLineString' coordinate arrays
 *
 * @param {object} calcTrace
 *  gd.calcdata item.
 *  Note that calcTrace[i].lonlat is assumed to be defined
 *
 * @return {array}
 *  return line coords array (or array of arrays)
 *
 */
exports.calcTraceToLineCoords = function(calcTrace) {
    var trace = calcTrace[0].trace;
    var connectgaps = trace.connectgaps;

    var coords = [];
    var lineString = [];

    for(var i = 0; i < calcTrace.length; i++) {
        var calcPt = calcTrace[i];
        var lonlat = calcPt.lonlat;

        if(lonlat[0] !== BADNUM) {
            lineString.push(lonlat);
        } else if(!connectgaps && lineString.length > 0) {
            coords.push(lineString);
            lineString = [];
        }
    }

    if(lineString.length > 0) {
        coords.push(lineString);
    }

    return coords;
};


/**
 * Make line ('LineString' or 'MultiLineString') GeoJSON
 *
 * @param {array} coords
 *  results form calcTraceToLineCoords
 * @return {object} out
 *  GeoJSON object
 *
 */
exports.makeLine = function(coords) {
    if(coords.length === 1) {
        return {
            type: 'LineString',
            coordinates: coords[0]
        };
    } else {
        return {
            type: 'MultiLineString',
            coordinates: coords
        };
    }
};

/**
 * Make polygon ('Polygon' or 'MultiPolygon') GeoJSON
 *
 * @param {array} coords
 *  results form calcTraceToLineCoords
 * @return {object} out
 *  GeoJSON object
 */
exports.makePolygon = function(coords) {
    if(coords.length === 1) {
        return {
            type: 'Polygon',
            coordinates: coords
        };
    } else {
        var _coords = new Array(coords.length);

        for(var i = 0; i < coords.length; i++) {
            _coords[i] = [coords[i]];
        }

        return {
            type: 'MultiPolygon',
            coordinates: _coords
        };
    }
};

/**
 * Make blank GeoJSON
 *
 * @return {object}
 *  Blank GeoJSON object
 *
 */
exports.makeBlank = function() {
    return {
        type: 'Point',
        coordinates: []
    };
};

},{"../constants/numerical":671}],689:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var mod = _dereq_('./mod').mod;

/*
 * look for intersection of two line segments
 *   (1->2 and 3->4) - returns array [x,y] if they do, null if not
 */
exports.segmentsIntersect = segmentsIntersect;
function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) {
    var a = x2 - x1;
    var b = x3 - x1;
    var c = x4 - x3;
    var d = y2 - y1;
    var e = y3 - y1;
    var f = y4 - y3;
    var det = a * f - c * d;
    // parallel lines? intersection is undefined
    // ignore the case where they are colinear
    if(det === 0) return null;
    var t = (b * f - c * e) / det;
    var u = (b * d - a * e) / det;
    // segments do not intersect?
    if(u < 0 || u > 1 || t < 0 || t > 1) return null;

    return {x: x1 + a * t, y: y1 + d * t};
}

/*
 * find the minimum distance between two line segments (1->2 and 3->4)
 */
exports.segmentDistance = function segmentDistance(x1, y1, x2, y2, x3, y3, x4, y4) {
    if(segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4)) return 0;

    // the two segments and their lengths squared
    var x12 = x2 - x1;
    var y12 = y2 - y1;
    var x34 = x4 - x3;
    var y34 = y4 - y3;
    var ll12 = x12 * x12 + y12 * y12;
    var ll34 = x34 * x34 + y34 * y34;

    // calculate distance squared, then take the sqrt at the very end
    var dist2 = Math.min(
        perpDistance2(x12, y12, ll12, x3 - x1, y3 - y1),
        perpDistance2(x12, y12, ll12, x4 - x1, y4 - y1),
        perpDistance2(x34, y34, ll34, x1 - x3, y1 - y3),
        perpDistance2(x34, y34, ll34, x2 - x3, y2 - y3)
    );

    return Math.sqrt(dist2);
};

/*
 * distance squared from segment ab to point c
 * [xab, yab] is the vector b-a
 * [xac, yac] is the vector c-a
 * llab is the length squared of (b-a), just to simplify calculation
 */
function perpDistance2(xab, yab, llab, xac, yac) {
    var fcAB = (xac * xab + yac * yab);
    if(fcAB < 0) {
        // point c is closer to point a
        return xac * xac + yac * yac;
    }
    else if(fcAB > llab) {
        // point c is closer to point b
        var xbc = xac - xab;
        var ybc = yac - yab;
        return xbc * xbc + ybc * ybc;
    }
    else {
        // perpendicular distance is the shortest
        var crossProduct = xac * yab - yac * xab;
        return crossProduct * crossProduct / llab;
    }
}

// a very short-term cache for getTextLocation, just because
// we're often looping over the same locations multiple times
// invalidated as soon as we look at a different path
var locationCache, workingPath, workingTextWidth;

// turn a path and position along it into x, y, and angle for the given text
exports.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) {
    if(path !== workingPath || textWidth !== workingTextWidth) {
        locationCache = {};
        workingPath = path;
        workingTextWidth = textWidth;
    }
    if(locationCache[positionOnPath]) {
        return locationCache[positionOnPath];
    }

    // for the angle, use points on the path separated by the text width
    // even though due to curvature, the text will cover a bit more than that
    var p0 = path.getPointAtLength(mod(positionOnPath - textWidth / 2, totalPathLen));
    var p1 = path.getPointAtLength(mod(positionOnPath + textWidth / 2, totalPathLen));
    // note: atan handles 1/0 nicely
    var theta = Math.atan((p1.y - p0.y) / (p1.x - p0.x));
    // center the text at 2/3 of the center position plus 1/3 the p0/p1 midpoint
    // that's the average position of this segment, assuming it's roughly quadratic
    var pCenter = path.getPointAtLength(mod(positionOnPath, totalPathLen));
    var x = (pCenter.x * 4 + p0.x + p1.x) / 6;
    var y = (pCenter.y * 4 + p0.y + p1.y) / 6;

    var out = {x: x, y: y, theta: theta};
    locationCache[positionOnPath] = out;
    return out;
};

exports.clearLocationCache = function() {
    workingPath = null;
};

/*
 * Find the segment of `path` that's within the visible area
 * given by `bounds` {left, right, top, bottom}, to within a
 * precision of `buffer` px
 *
 * returns: undefined if nothing is visible, else object:
 * {
 *   min: position where the path first enters bounds, or 0 if it
 *        starts within bounds
 *   max: position where the path last exits bounds, or the path length
 *        if it finishes within bounds
 *   len: max - min, ie the length of visible path
 *   total: the total path length - just included so the caller doesn't
 *        need to call path.getTotalLength() again
 *   isClosed: true iff the start and end points of the path are both visible
 *        and are at the same point
 * }
 *
 * Works by starting from either end and repeatedly finding the distance from
 * that point to the plot area, and if it's outside the plot, moving along the
 * path by that distance (because the plot must be at least that far away on
 * the path). Note that if a path enters, exits, and re-enters the plot, we
 * will not capture this behavior.
 */
exports.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) {
    var left = bounds.left;
    var right = bounds.right;
    var top = bounds.top;
    var bottom = bounds.bottom;

    var pMin = 0;
    var pTotal = path.getTotalLength();
    var pMax = pTotal;

    var pt0, ptTotal;

    function getDistToPlot(len) {
        var pt = path.getPointAtLength(len);

        // hold on to the start and end points for `closed`
        if(len === 0) pt0 = pt;
        else if(len === pTotal) ptTotal = pt;

        var dx = (pt.x < left) ? left - pt.x : (pt.x > right ? pt.x - right : 0);
        var dy = (pt.y < top) ? top - pt.y : (pt.y > bottom ? pt.y - bottom : 0);
        return Math.sqrt(dx * dx + dy * dy);
    }

    var distToPlot = getDistToPlot(pMin);
    while(distToPlot) {
        pMin += distToPlot + buffer;
        if(pMin > pMax) return;
        distToPlot = getDistToPlot(pMin);
    }

    distToPlot = getDistToPlot(pMax);
    while(distToPlot) {
        pMax -= distToPlot + buffer;
        if(pMin > pMax) return;
        distToPlot = getDistToPlot(pMax);
    }

    return {
        min: pMin,
        max: pMax,
        len: pMax - pMin,
        total: pTotal,
        isClosed: pMin === 0 && pMax === pTotal &&
            Math.abs(pt0.x - ptTotal.x) < 0.1 &&
            Math.abs(pt0.y - ptTotal.y) < 0.1
    };
};

/**
 * Find point on SVG path corresponding to a given constraint coordinate
 *
 * @param {SVGPathElement} path
 * @param {Number} val : constraint coordinate value
 * @param {String} coord : 'x' or 'y' the constraint coordinate
 * @param {Object} opts :
 *  - {Number} pathLength : supply total path length before hand
 *  - {Number} tolerance
 *  - {Number} iterationLimit
 * @return {SVGPoint}
 */
exports.findPointOnPath = function findPointOnPath(path, val, coord, opts) {
    opts = opts || {};

    var pathLength = opts.pathLength || path.getTotalLength();
    var tolerance = opts.tolerance || 1e-3;
    var iterationLimit = opts.iterationLimit || 30;

    // if path starts at a val greater than the path tail (like on vertical violins),
    // we must flip the sign of the computed diff.
    var mul = path.getPointAtLength(0)[coord] > path.getPointAtLength(pathLength)[coord] ? -1 : 1;

    var i = 0;
    var b0 = 0;
    var b1 = pathLength;
    var mid;
    var pt;
    var diff;

    while(i < iterationLimit) {
        mid = (b0 + b1) / 2;
        pt = path.getPointAtLength(mid);
        diff = pt[coord] - val;

        if(Math.abs(diff) < tolerance) {
            return pt;
        } else {
            if(mul * diff > 0) {
                b1 = mid;
            } else {
                b0 = mid;
            }
            i++;
        }
    }
    return pt;
};

},{"./mod":701}],690:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * Allow referencing a graph DOM element either directly
 * or by its id string
 *
 * @param {HTMLDivElement|string} gd: a graph element or its id
 *
 * @returns {HTMLDivElement} the DOM element of the graph
 */
module.exports = function(gd) {
    var gdElement;

    if(typeof gd === 'string') {
        gdElement = document.getElementById(gd);

        if(gdElement === null) {
            throw new Error('No DOM element with id \'' + gd + '\' exists on the page.');
        }

        return gdElement;
    }
    else if(gd === null || gd === undefined) {
        throw new Error('DOM element provided is null or undefined');
    }

    return gd;  // otherwise assume that gd is a DOM element
};

},{}],691:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var tinycolor = _dereq_('tinycolor2');
var rgba = _dereq_('color-normalize');

var Colorscale = _dereq_('../components/colorscale');
var colorDflt = _dereq_('../components/color/attributes').defaultLine;
var isArrayOrTypedArray = _dereq_('./array').isArrayOrTypedArray;

var colorDfltRgba = rgba(colorDflt);
var opacityDflt = 1;

function calculateColor(colorIn, opacityIn) {
    var colorOut = colorIn;
    colorOut[3] *= opacityIn;
    return colorOut;
}

function validateColor(colorIn) {
    if(isNumeric(colorIn)) return colorDfltRgba;

    var colorOut = rgba(colorIn);

    return colorOut.length ? colorOut : colorDfltRgba;
}

function validateOpacity(opacityIn) {
    return isNumeric(opacityIn) ? opacityIn : opacityDflt;
}

function formatColor(containerIn, opacityIn, len) {
    var colorIn = containerIn.color;
    var isArrayColorIn = isArrayOrTypedArray(colorIn);
    var isArrayOpacityIn = isArrayOrTypedArray(opacityIn);
    var colorOut = [];

    var sclFunc, getColor, getOpacity, colori, opacityi;

    if(containerIn.colorscale !== undefined) {
        sclFunc = Colorscale.makeColorScaleFunc(
            Colorscale.extractScale(containerIn, {cLetter: 'c'})
        );
    }
    else {
        sclFunc = validateColor;
    }

    if(isArrayColorIn) {
        getColor = function(c, i) {
            // FIXME: there is double work, considering that sclFunc does the opposite
            return c[i] === undefined ? colorDfltRgba : rgba(sclFunc(c[i]));
        };
    }
    else getColor = validateColor;

    if(isArrayOpacityIn) {
        getOpacity = function(o, i) {
            return o[i] === undefined ? opacityDflt : validateOpacity(o[i]);
        };
    }
    else getOpacity = validateOpacity;

    if(isArrayColorIn || isArrayOpacityIn) {
        for(var i = 0; i < len; i++) {
            colori = getColor(colorIn, i);
            opacityi = getOpacity(opacityIn, i);
            colorOut[i] = calculateColor(colori, opacityi);
        }
    }
    else colorOut = calculateColor(rgba(colorIn), opacityIn);

    return colorOut;
}

function parseColorScale(cont, alpha) {
    if(alpha === undefined) alpha = 1;

    var colorscale = cont.reversescale ?
        Colorscale.flipScale(cont.colorscale) :
        cont.colorscale;

    return colorscale.map(function(elem) {
        var index = elem[0];
        var color = tinycolor(elem[1]);
        var rgb = color.toRgb();
        return {
            index: index,
            rgb: [rgb.r, rgb.g, rgb.b, alpha]
        };
    });
}

module.exports = {
    formatColor: formatColor,
    parseColorScale: parseColorScale
};

},{"../components/color/attributes":570,"../components/colorscale":583,"./array":677,"color-normalize":109,"fast-isnumeric":215,"tinycolor2":515}],692:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var identity = _dereq_('./identity');

function wrap(d) {return [d];}

module.exports = {

    // The D3 data binding concept and the General Update Pattern promotes the idea of
    // traversing into the scenegraph by using the `.data(fun, keyFun)` call.
    // The `fun` is most often a `repeat`, ie. the elements beneath a `<g>` element need
    // access to the same data, or a `descend`, which fans a scenegraph node into a bunch of
    // of elements, e.g. points, lines, rows, requiring an array as input.
    // The role of the `keyFun` is to identify what elements are being entered/exited/updated,
    // otherwise D3 reverts to using a plain index which would screw up `transition`s.
    keyFun: function(d) {return d.key;},
    repeat: wrap,
    descend: identity,

    // Plotly.js uses a convention of storing the actual contents of the `calcData` as the
    // element zero of a container array. These helpers are just used for clarity as a
    // newcomer to the codebase may not know what the `[0]` is, and whether there can be further
    // elements (not atm).
    wrap: wrap,
    unwrap: function(d) {return d[0];}
};

},{"./identity":693}],693:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// Simple helper functions
// none of these need any external deps

module.exports = function identity(d) { return d; };

},{}],694:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');

var numConstants = _dereq_('../constants/numerical');
var FP_SAFE = numConstants.FP_SAFE;
var BADNUM = numConstants.BADNUM;

var lib = module.exports = {};

lib.nestedProperty = _dereq_('./nested_property');
lib.keyedContainer = _dereq_('./keyed_container');
lib.relativeAttr = _dereq_('./relative_attr');
lib.isPlainObject = _dereq_('./is_plain_object');
lib.toLogRange = _dereq_('./to_log_range');
lib.relinkPrivateKeys = _dereq_('./relink_private');

var arrayModule = _dereq_('./array');
lib.isTypedArray = arrayModule.isTypedArray;
lib.isArrayOrTypedArray = arrayModule.isArrayOrTypedArray;
lib.isArray1D = arrayModule.isArray1D;
lib.ensureArray = arrayModule.ensureArray;
lib.concat = arrayModule.concat;
lib.maxRowLength = arrayModule.maxRowLength;
lib.minRowLength = arrayModule.minRowLength;

var modModule = _dereq_('./mod');
lib.mod = modModule.mod;
lib.modHalf = modModule.modHalf;

var coerceModule = _dereq_('./coerce');
lib.valObjectMeta = coerceModule.valObjectMeta;
lib.coerce = coerceModule.coerce;
lib.coerce2 = coerceModule.coerce2;
lib.coerceFont = coerceModule.coerceFont;
lib.coerceHoverinfo = coerceModule.coerceHoverinfo;
lib.coerceSelectionMarkerOpacity = coerceModule.coerceSelectionMarkerOpacity;
lib.validate = coerceModule.validate;

var datesModule = _dereq_('./dates');
lib.dateTime2ms = datesModule.dateTime2ms;
lib.isDateTime = datesModule.isDateTime;
lib.ms2DateTime = datesModule.ms2DateTime;
lib.ms2DateTimeLocal = datesModule.ms2DateTimeLocal;
lib.cleanDate = datesModule.cleanDate;
lib.isJSDate = datesModule.isJSDate;
lib.formatDate = datesModule.formatDate;
lib.incrementMonth = datesModule.incrementMonth;
lib.dateTick0 = datesModule.dateTick0;
lib.dfltRange = datesModule.dfltRange;
lib.findExactDates = datesModule.findExactDates;
lib.MIN_MS = datesModule.MIN_MS;
lib.MAX_MS = datesModule.MAX_MS;

var searchModule = _dereq_('./search');
lib.findBin = searchModule.findBin;
lib.sorterAsc = searchModule.sorterAsc;
lib.sorterDes = searchModule.sorterDes;
lib.distinctVals = searchModule.distinctVals;
lib.roundUp = searchModule.roundUp;
lib.sort = searchModule.sort;
lib.findIndexOfMin = searchModule.findIndexOfMin;

var statsModule = _dereq_('./stats');
lib.aggNums = statsModule.aggNums;
lib.len = statsModule.len;
lib.mean = statsModule.mean;
lib.midRange = statsModule.midRange;
lib.variance = statsModule.variance;
lib.stdev = statsModule.stdev;
lib.interp = statsModule.interp;

var matrixModule = _dereq_('./matrix');
lib.init2dArray = matrixModule.init2dArray;
lib.transposeRagged = matrixModule.transposeRagged;
lib.dot = matrixModule.dot;
lib.translationMatrix = matrixModule.translationMatrix;
lib.rotationMatrix = matrixModule.rotationMatrix;
lib.rotationXYMatrix = matrixModule.rotationXYMatrix;
lib.apply2DTransform = matrixModule.apply2DTransform;
lib.apply2DTransform2 = matrixModule.apply2DTransform2;

var anglesModule = _dereq_('./angles');
lib.deg2rad = anglesModule.deg2rad;
lib.rad2deg = anglesModule.rad2deg;
lib.angleDelta = anglesModule.angleDelta;
lib.angleDist = anglesModule.angleDist;
lib.isFullCircle = anglesModule.isFullCircle;
lib.isAngleInsideSector = anglesModule.isAngleInsideSector;
lib.isPtInsideSector = anglesModule.isPtInsideSector;
lib.pathArc = anglesModule.pathArc;
lib.pathSector = anglesModule.pathSector;
lib.pathAnnulus = anglesModule.pathAnnulus;

var anchorUtils = _dereq_('./anchor_utils');
lib.isLeftAnchor = anchorUtils.isLeftAnchor;
lib.isCenterAnchor = anchorUtils.isCenterAnchor;
lib.isRightAnchor = anchorUtils.isRightAnchor;
lib.isTopAnchor = anchorUtils.isTopAnchor;
lib.isMiddleAnchor = anchorUtils.isMiddleAnchor;
lib.isBottomAnchor = anchorUtils.isBottomAnchor;

var geom2dModule = _dereq_('./geometry2d');
lib.segmentsIntersect = geom2dModule.segmentsIntersect;
lib.segmentDistance = geom2dModule.segmentDistance;
lib.getTextLocation = geom2dModule.getTextLocation;
lib.clearLocationCache = geom2dModule.clearLocationCache;
lib.getVisibleSegment = geom2dModule.getVisibleSegment;
lib.findPointOnPath = geom2dModule.findPointOnPath;

var extendModule = _dereq_('./extend');
lib.extendFlat = extendModule.extendFlat;
lib.extendDeep = extendModule.extendDeep;
lib.extendDeepAll = extendModule.extendDeepAll;
lib.extendDeepNoArrays = extendModule.extendDeepNoArrays;

var loggersModule = _dereq_('./loggers');
lib.log = loggersModule.log;
lib.warn = loggersModule.warn;
lib.error = loggersModule.error;

var regexModule = _dereq_('./regex');
lib.counterRegex = regexModule.counter;

var throttleModule = _dereq_('./throttle');
lib.throttle = throttleModule.throttle;
lib.throttleDone = throttleModule.done;
lib.clearThrottle = throttleModule.clear;

lib.getGraphDiv = _dereq_('./get_graph_div');

lib.clearResponsive = _dereq_('./clear_responsive');

lib.makeTraceGroups = _dereq_('./make_trace_groups');

lib._ = _dereq_('./localize');

lib.notifier = _dereq_('./notifier');

lib.filterUnique = _dereq_('./filter_unique');
lib.filterVisible = _dereq_('./filter_visible');
lib.pushUnique = _dereq_('./push_unique');

lib.cleanNumber = _dereq_('./clean_number');

lib.ensureNumber = function num(v) {
    if(!isNumeric(v)) return BADNUM;
    v = Number(v);
    if(v < -FP_SAFE || v > FP_SAFE) return BADNUM;
    return isNumeric(v) ? Number(v) : BADNUM;
};

/**
 * Is v a valid array index? Accepts numeric strings as well as numbers.
 *
 * @param {any} v: the value to test
 * @param {Optional[integer]} len: the array length we are indexing
 *
 * @return {bool}: v is a valid array index
 */
lib.isIndex = function(v, len) {
    if(len !== undefined && v >= len) return false;
    return isNumeric(v) && (v >= 0) && (v % 1 === 0);
};

lib.noop = _dereq_('./noop');
lib.identity = _dereq_('./identity');

/**
 * create an array of length 'cnt' filled with 'v' at all indices
 *
 * @param {any} v
 * @param {number} cnt
 * @return {array}
 */
lib.repeat = function(v, cnt) {
    var out = new Array(cnt);
    for(var i = 0; i < cnt; i++) {
        out[i] = v;
    }
    return out;
};

/**
 * swap x and y of the same attribute in container cont
 * specify attr with a ? in place of x/y
 * you can also swap other things than x/y by providing part1 and part2
 */
lib.swapAttrs = function(cont, attrList, part1, part2) {
    if(!part1) part1 = 'x';
    if(!part2) part2 = 'y';
    for(var i = 0; i < attrList.length; i++) {
        var attr = attrList[i];
        var xp = lib.nestedProperty(cont, attr.replace('?', part1));
        var yp = lib.nestedProperty(cont, attr.replace('?', part2));
        var temp = xp.get();
        xp.set(yp.get());
        yp.set(temp);
    }
};

/**
 * SVG painter's algo worked around with reinsertion
 */
lib.raiseToTop = function raiseToTop(elem) {
    elem.parentNode.appendChild(elem);
};

/**
 * cancel a possibly pending transition; returned selection may be used by caller
 */
lib.cancelTransition = function(selection) {
    return selection.transition().duration(0);
};

// constrain - restrict a number v to be between v0 and v1
lib.constrain = function(v, v0, v1) {
    if(v0 > v1) return Math.max(v1, Math.min(v0, v));
    return Math.max(v0, Math.min(v1, v));
};

/**
 * do two bounding boxes from getBoundingClientRect,
 * ie {left,right,top,bottom,width,height}, overlap?
 * takes optional padding pixels
 */
lib.bBoxIntersect = function(a, b, pad) {
    pad = pad || 0;
    return (a.left <= b.right + pad &&
            b.left <= a.right + pad &&
            a.top <= b.bottom + pad &&
            b.top <= a.bottom + pad);
};

/*
 * simpleMap: alternative to Array.map that only
 * passes on the element and up to 2 extra args you
 * provide (but not the array index or the whole array)
 *
 * array: the array to map it to
 * func: the function to apply
 * x1, x2: optional extra args
 */
lib.simpleMap = function(array, func, x1, x2) {
    var len = array.length;
    var out = new Array(len);
    for(var i = 0; i < len; i++) out[i] = func(array[i], x1, x2);
    return out;
};

/**
 * Random string generator
 *
 * @param {object} existing
 *     pass in strings to avoid as keys with truthy values
 * @param {int} bits
 *     bits of information in the output string, default 24
 * @param {int} base
 *     base of string representation, default 16. Should be a power of 2.
 */
lib.randstr = function randstr(existing, bits, base, _recursion) {
    if(!base) base = 16;
    if(bits === undefined) bits = 24;
    if(bits <= 0) return '0';

    var digits = Math.log(Math.pow(2, bits)) / Math.log(base);
    var res = '';
    var i, b, x;

    for(i = 2; digits === Infinity; i *= 2) {
        digits = Math.log(Math.pow(2, bits / i)) / Math.log(base) * i;
    }

    var rem = digits - Math.floor(digits);

    for(i = 0; i < Math.floor(digits); i++) {
        x = Math.floor(Math.random() * base).toString(base);
        res = x + res;
    }

    if(rem) {
        b = Math.pow(base, rem);
        x = Math.floor(Math.random() * b).toString(base);
        res = x + res;
    }

    var parsed = parseInt(res, base);
    if((existing && existing[res]) ||
         (parsed !== Infinity && parsed >= Math.pow(2, bits))) {
        if(_recursion > 10) {
            lib.warn('randstr failed uniqueness');
            return res;
        }
        return randstr(existing, bits, base, (_recursion || 0) + 1);
    }
    else return res;
};

lib.OptionControl = function(opt, optname) {
    /*
     * An environment to contain all option setters and
     * getters that collectively modify opts.
     *
     * You can call up opts from any function in new object
     * as this.optname || this.opt
     *
     * See FitOpts for example of usage
     */
    if(!opt) opt = {};
    if(!optname) optname = 'opt';

    var self = {};
    self.optionList = [];

    self._newoption = function(optObj) {
        optObj[optname] = opt;
        self[optObj.name] = optObj;
        self.optionList.push(optObj);
    };

    self['_' + optname] = opt;
    return self;
};

/**
 * lib.smooth: smooth arrayIn by convolving with
 * a hann window with given full width at half max
 * bounce the ends in, so the output has the same length as the input
 */
lib.smooth = function(arrayIn, FWHM) {
    FWHM = Math.round(FWHM) || 0; // only makes sense for integers
    if(FWHM < 2) return arrayIn;

    var alen = arrayIn.length;
    var alen2 = 2 * alen;
    var wlen = 2 * FWHM - 1;
    var w = new Array(wlen);
    var arrayOut = new Array(alen);
    var i;
    var j;
    var k;
    var v;

    // first make the window array
    for(i = 0; i < wlen; i++) {
        w[i] = (1 - Math.cos(Math.PI * (i + 1) / FWHM)) / (2 * FWHM);
    }

    // now do the convolution
    for(i = 0; i < alen; i++) {
        v = 0;
        for(j = 0; j < wlen; j++) {
            k = i + j + 1 - FWHM;

            // multibounce
            if(k < -alen) k -= alen2 * Math.round(k / alen2);
            else if(k >= alen2) k -= alen2 * Math.floor(k / alen2);

            // single bounce
            if(k < 0) k = - 1 - k;
            else if(k >= alen) k = alen2 - 1 - k;

            v += arrayIn[k] * w[j];
        }
        arrayOut[i] = v;
    }

    return arrayOut;
};

/**
 * syncOrAsync: run a sequence of functions synchronously
 * as long as its returns are not promises (ie have no .then)
 * includes one argument arg to send to all functions...
 * this is mainly just to prevent us having to make wrapper functions
 * when the only purpose of the wrapper is to reference gd
 * and a final step to be executed at the end
 * TODO: if there's an error and everything is sync,
 * this doesn't happen yet because we want to make sure
 * that it gets reported
 */
lib.syncOrAsync = function(sequence, arg, finalStep) {
    var ret, fni;

    function continueAsync() {
        return lib.syncOrAsync(sequence, arg, finalStep);
    }

    while(sequence.length) {
        fni = sequence.splice(0, 1)[0];
        ret = fni(arg);

        if(ret && ret.then) {
            return ret.then(continueAsync)
                .then(undefined, lib.promiseError);
        }
    }

    return finalStep && finalStep(arg);
};


/**
 * Helper to strip trailing slash, from
 * http://stackoverflow.com/questions/6680825/return-string-without-trailing-slash
 */
lib.stripTrailingSlash = function(str) {
    if(str.substr(-1) === '/') return str.substr(0, str.length - 1);
    return str;
};

lib.noneOrAll = function(containerIn, containerOut, attrList) {
    /**
     * some attributes come together, so if you have one of them
     * in the input, you should copy the default values of the others
     * to the input as well.
     */
    if(!containerIn) return;

    var hasAny = false;
    var hasAll = true;
    var i;
    var val;

    for(i = 0; i < attrList.length; i++) {
        val = containerIn[attrList[i]];
        if(val !== undefined && val !== null) hasAny = true;
        else hasAll = false;
    }

    if(hasAny && !hasAll) {
        for(i = 0; i < attrList.length; i++) {
            containerIn[attrList[i]] = containerOut[attrList[i]];
        }
    }
};

/** merges calcdata field (given by cdAttr) with traceAttr values
 *
 * N.B. Loop over minimum of cd.length and traceAttr.length
 * i.e. it does not try to fill in beyond traceAttr.length-1
 *
 * @param {array} traceAttr : trace attribute
 * @param {object} cd : calcdata trace
 * @param {string} cdAttr : calcdata key
 */
lib.mergeArray = function(traceAttr, cd, cdAttr) {
    if(lib.isArrayOrTypedArray(traceAttr)) {
        var imax = Math.min(traceAttr.length, cd.length);
        for(var i = 0; i < imax; i++) cd[i][cdAttr] = traceAttr[i];
    }
};

/** fills calcdata field (given by cdAttr) with traceAttr values
 *  or function of traceAttr values (e.g. some fallback)
 *
 * N.B. Loops over all cd items.
 *
 * @param {array} traceAttr : trace attribute
 * @param {object} cd : calcdata trace
 * @param {string} cdAttr : calcdata key
 * @param {function} [fn] : optional function to apply to each array item
 */
lib.fillArray = function(traceAttr, cd, cdAttr, fn) {
    fn = fn || lib.identity;

    if(lib.isArrayOrTypedArray(traceAttr)) {
        for(var i = 0; i < cd.length; i++) {
            cd[i][cdAttr] = fn(traceAttr[i]);
        }
    }
};

/** Handler for trace-wide vs per-point options
 *
 * @param {object} trace : (full) trace object
 * @param {number} ptNumber : index of the point in question
 * @param {string} astr : attribute string
 * @param {function} [fn] : optional function to apply to each array item
 *
 * @return {any}
 */
lib.castOption = function(trace, ptNumber, astr, fn) {
    fn = fn || lib.identity;

    var val = lib.nestedProperty(trace, astr).get();

    if(lib.isArrayOrTypedArray(val)) {
        if(Array.isArray(ptNumber) && lib.isArrayOrTypedArray(val[ptNumber[0]])) {
            return fn(val[ptNumber[0]][ptNumber[1]]);
        } else {
            return fn(val[ptNumber]);
        }
    } else {
        return val;
    }
};

/** Extract option from calcdata item, correctly falling back to
 *  trace value if not found.
 *
 *  @param {object} calcPt : calcdata[i][j] item
 *  @param {object} trace : (full) trace object
 *  @param {string} calcKey : calcdata key
 *  @param {string} traceKey : aka trace attribute string
 *  @return {any}
 */
lib.extractOption = function(calcPt, trace, calcKey, traceKey) {
    if(calcKey in calcPt) return calcPt[calcKey];

    // fallback to trace value,
    //   must check if value isn't itself an array
    //   which means the trace attribute has a corresponding
    //   calcdata key, but its value is falsy
    var traceVal = lib.nestedProperty(trace, traceKey).get();
    if(!Array.isArray(traceVal)) return traceVal;
};

function makePtIndex2PtNumber(indexToPoints) {
    var ptIndex2ptNumber = {};
    for(var k in indexToPoints) {
        var pts = indexToPoints[k];
        for(var j = 0; j < pts.length; j++) {
            ptIndex2ptNumber[pts[j]] = +k;
        }
    }
    return ptIndex2ptNumber;
}

/** Tag selected calcdata items
 *
 * N.B. note that point 'index' corresponds to input data array index
 *  whereas 'number' is its post-transform version.
 *
 * @param {array} calcTrace
 * @param {object} trace
 *  - selectedpoints {array}
 *  - _indexToPoints {object}
 * @param {ptNumber2cdIndex} ptNumber2cdIndex (optional)
 *  optional map object for trace types that do not have 1-to-1 point number to
 *  calcdata item index correspondence (e.g. histogram)
 */
lib.tagSelected = function(calcTrace, trace, ptNumber2cdIndex) {
    var selectedpoints = trace.selectedpoints;
    var indexToPoints = trace._indexToPoints;
    var ptIndex2ptNumber;

    // make pt index-to-number map object, which takes care of transformed traces
    if(indexToPoints) {
        ptIndex2ptNumber = makePtIndex2PtNumber(indexToPoints);
    }

    function isCdIndexValid(v) {
        return v !== undefined && v < calcTrace.length;
    }

    for(var i = 0; i < selectedpoints.length; i++) {
        var ptIndex = selectedpoints[i];

        if(lib.isIndex(ptIndex)) {
            var ptNumber = ptIndex2ptNumber ? ptIndex2ptNumber[ptIndex] : ptIndex;
            var cdIndex = ptNumber2cdIndex ? ptNumber2cdIndex[ptNumber] : ptNumber;

            if(isCdIndexValid(cdIndex)) {
                calcTrace[cdIndex].selected = 1;
            }
        }
    }
};

lib.selIndices2selPoints = function(trace) {
    var selectedpoints = trace.selectedpoints;
    var indexToPoints = trace._indexToPoints;

    if(indexToPoints) {
        var ptIndex2ptNumber = makePtIndex2PtNumber(indexToPoints);
        var out = [];

        for(var i = 0; i < selectedpoints.length; i++) {
            var ptIndex = selectedpoints[i];
            if(lib.isIndex(ptIndex)) {
                var ptNumber = ptIndex2ptNumber[ptIndex];
                if(lib.isIndex(ptNumber)) {
                    out.push(ptNumber);
                }
            }
        }

        return out;
    } else {
        return selectedpoints;
    }
};

/** Returns target as set by 'target' transform attribute
 *
 * @param {object} trace : full trace object
 * @param {object} transformOpts : transform option object
 *  - target (string} :
 *      either an attribute string referencing an array in the trace object, or
 *      a set array.
 *
 * @return {array or false} : the target array (NOT a copy!!) or false if invalid
 */
lib.getTargetArray = function(trace, transformOpts) {
    var target = transformOpts.target;

    if(typeof target === 'string' && target) {
        var array = lib.nestedProperty(trace, target).get();
        return Array.isArray(array) ? array : false;
    } else if(Array.isArray(target)) {
        return target;
    }

    return false;
};

/**
 * modified version of jQuery's extend to strip out private objs and functions,
 * and cut arrays down to first <arraylen> or 1 elements
 * because extend-like algorithms are hella slow
 * obj2 is assumed to already be clean of these things (including no arrays)
 */
lib.minExtend = function(obj1, obj2) {
    var objOut = {};
    if(typeof obj2 !== 'object') obj2 = {};
    var arrayLen = 3;
    var keys = Object.keys(obj1);
    var i, k, v;

    for(i = 0; i < keys.length; i++) {
        k = keys[i];
        v = obj1[k];
        if(k.charAt(0) === '_' || typeof v === 'function') continue;
        else if(k === 'module') objOut[k] = v;
        else if(Array.isArray(v)) {
            if(k === 'colorscale') {
                objOut[k] = v.slice();
            } else {
                objOut[k] = v.slice(0, arrayLen);
            }
        }
        else if(v && (typeof v === 'object')) objOut[k] = lib.minExtend(obj1[k], obj2[k]);
        else objOut[k] = v;
    }

    keys = Object.keys(obj2);
    for(i = 0; i < keys.length; i++) {
        k = keys[i];
        v = obj2[k];
        if(typeof v !== 'object' || !(k in objOut) || typeof objOut[k] !== 'object') {
            objOut[k] = v;
        }
    }

    return objOut;
};

lib.titleCase = function(s) {
    return s.charAt(0).toUpperCase() + s.substr(1);
};

lib.containsAny = function(s, fragments) {
    for(var i = 0; i < fragments.length; i++) {
        if(s.indexOf(fragments[i]) !== -1) return true;
    }
    return false;
};

lib.isPlotDiv = function(el) {
    var el3 = d3.select(el);
    return el3.node() instanceof HTMLElement &&
        el3.size() &&
        el3.classed('js-plotly-plot');
};

lib.removeElement = function(el) {
    var elParent = el && el.parentNode;
    if(elParent) elParent.removeChild(el);
};

/**
 * for dynamically adding style rules
 * makes one stylesheet that contains all rules added
 * by all calls to this function
 */
lib.addStyleRule = function(selector, styleString) {
    lib.addRelatedStyleRule('global', selector, styleString);
};

/**
 * for dynamically adding style rules
 * to a stylesheet uniquely identified by a uid
 */
lib.addRelatedStyleRule = function(uid, selector, styleString) {
    var id = 'plotly.js-style-' + uid;
    var style = document.getElementById(id);
    if(!style) {
        style = document.createElement('style');
        style.setAttribute('id', id);
        // WebKit hack :(
        style.appendChild(document.createTextNode(''));
        document.head.appendChild(style);
    }
    var styleSheet = style.sheet;

    if(styleSheet.insertRule) {
        styleSheet.insertRule(selector + '{' + styleString + '}', 0);
    }
    else if(styleSheet.addRule) {
        styleSheet.addRule(selector, styleString, 0);
    }
    else lib.warn('addStyleRule failed');
};

/**
 * to remove from the page a stylesheet identified by a given uid
 */
lib.deleteRelatedStyleRule = function(uid) {
    var id = 'plotly.js-style-' + uid;
    var style = document.getElementById(id);
    if(style) lib.removeElement(style);
};

lib.isIE = function() {
    return typeof window.navigator.msSaveBlob !== 'undefined';
};

/**
 * Duck typing to recognize a d3 selection, mostly for IE9's benefit
 * because it doesn't handle instanceof like modern browsers
 */
lib.isD3Selection = function(obj) {
    return obj && (typeof obj.classed === 'function');
};

/**
 * Append element to DOM only if not present.
 *
 * @param {d3 selection} parent : parent selection of the element in question
 * @param {string} nodeType : node type of element to append
 * @param {string} className (optional) : class name of element in question
 * @param {fn} enterFn (optional) : optional fn applied to entering elements only
 * @return {d3 selection} selection of new layer
 *
 * Previously, we were using the following pattern:
 *
 * ```
 * var sel = parent.selectAll('.' + className)
 *     .data([0]);
 *
 * sel.enter().append(nodeType)
 *     .classed(className, true);
 *
 * return sel;
 * ```
 *
 * in numerous places in our codebase to achieve the same behavior.
 *
 * The logic below performs much better, mostly as we are using
 * `.select` instead `.selectAll` that is `querySelector` instead of
 * `querySelectorAll`.
 *
 */
lib.ensureSingle = function(parent, nodeType, className, enterFn) {
    var sel = parent.select(nodeType + (className ? '.' + className : ''));
    if(sel.size()) return sel;

    var layer = parent.append(nodeType);
    if(className) layer.classed(className, true);
    if(enterFn) layer.call(enterFn);

    return layer;
};

/**
 * Same as Lib.ensureSingle, but using id as selector.
 * This version is mostly used for clipPath nodes.
 *
 * @param {d3 selection} parent : parent selection of the element in question
 * @param {string} nodeType : node type of element to append
 * @param {string} id : id of element in question
 * @param {fn} enterFn (optional) : optional fn applied to entering elements only
 * @return {d3 selection} selection of new layer
 */
lib.ensureSingleById = function(parent, nodeType, id, enterFn) {
    var sel = parent.select(nodeType + '#' + id);
    if(sel.size()) return sel;

    var layer = parent.append(nodeType).attr('id', id);
    if(enterFn) layer.call(enterFn);

    return layer;
};

/**
 * Converts a string path to an object.
 *
 * When given a string containing an array element, it will create a `null`
 * filled array of the given size.
 *
 * @example
 * lib.objectFromPath('nested.test[2].path', 'value');
 * // returns { nested: { test: [null, null, { path: 'value' }]}
 *
 * @param   {string}    path to nested value
 * @param   {*}         any value to be set
 *
 * @return {Object} the constructed object with a full nested path
 */
lib.objectFromPath = function(path, value) {
    var keys = path.split('.');
    var tmpObj;
    var obj = tmpObj = {};

    for(var i = 0; i < keys.length; i++) {
        var key = keys[i];
        var el = null;

        var parts = keys[i].match(/(.*)\[([0-9]+)\]/);

        if(parts) {
            key = parts[1];
            el = parts[2];

            tmpObj = tmpObj[key] = [];

            if(i === keys.length - 1) {
                tmpObj[el] = value;
            } else {
                tmpObj[el] = {};
            }

            tmpObj = tmpObj[el];
        } else {

            if(i === keys.length - 1) {
                tmpObj[key] = value;
            } else {
                tmpObj[key] = {};
            }

            tmpObj = tmpObj[key];
        }
    }

    return obj;
};

/**
 * Iterate through an object in-place, converting dotted properties to objects.
 *
 * Examples:
 *
 *   lib.expandObjectPaths({'nested.test.path': 'value'});
 *     => { nested: { test: {path: 'value'}}}
 *
 * It also handles array notation, e.g.:
 *
 *   lib.expandObjectPaths({'foo[1].bar': 'value'});
 *     => { foo: [null, {bar: value}] }
 *
 * It handles merges the results when two properties are specified in parallel:
 *
 *   lib.expandObjectPaths({'foo[1].bar': 10, 'foo[0].bar': 20});
 *     => { foo: [{bar: 10}, {bar: 20}] }
 *
 * It does NOT, however, merge mulitple mutliply-nested arrays::
 *
 *   lib.expandObjectPaths({'marker[1].range[1]': 5, 'marker[1].range[0]': 4})
 *     => { marker: [null, {range: 4}] }
 */

// Store this to avoid recompiling regex on *every* prop since this may happen many
// many times for animations. Could maybe be inside the function. Not sure about
// scoping vs. recompilation tradeoff, but at least it's not just inlining it into
// the inner loop.
var dottedPropertyRegex = /^([^\[\.]+)\.(.+)?/;
var indexedPropertyRegex = /^([^\.]+)\[([0-9]+)\](\.)?(.+)?/;

lib.expandObjectPaths = function(data) {
    var match, key, prop, datum, idx, dest, trailingPath;
    if(typeof data === 'object' && !Array.isArray(data)) {
        for(key in data) {
            if(data.hasOwnProperty(key)) {
                if((match = key.match(dottedPropertyRegex))) {
                    datum = data[key];
                    prop = match[1];

                    delete data[key];

                    data[prop] = lib.extendDeepNoArrays(data[prop] || {}, lib.objectFromPath(key, lib.expandObjectPaths(datum))[prop]);
                } else if((match = key.match(indexedPropertyRegex))) {
                    datum = data[key];

                    prop = match[1];
                    idx = parseInt(match[2]);

                    delete data[key];

                    data[prop] = data[prop] || [];

                    if(match[3] === '.') {
                        // This is the case where theere are subsequent properties into which
                        // we must recurse, e.g. transforms[0].value
                        trailingPath = match[4];
                        dest = data[prop][idx] = data[prop][idx] || {};

                        // NB: Extend deep no arrays prevents this from working on multiple
                        // nested properties in the same object, e.g.
                        //
                        // {
                        //   foo[0].bar[1].range
                        //   foo[0].bar[0].range
                        // }
                        //
                        // In this case, the extendDeepNoArrays will overwrite one array with
                        // the other, so that both properties *will not* be present in the
                        // result. Fixing this would require a more intelligent tracking
                        // of changes and merging than extendDeepNoArrays currently accomplishes.
                        lib.extendDeepNoArrays(dest, lib.objectFromPath(trailingPath, lib.expandObjectPaths(datum)));
                    } else {
                        // This is the case where this property is the end of the line,
                        // e.g. xaxis.range[0]
                        data[prop][idx] = lib.expandObjectPaths(datum);
                    }
                } else {
                    data[key] = lib.expandObjectPaths(data[key]);
                }
            }
        }
    }

    return data;
};

/**
 * Converts value to string separated by the provided separators.
 *
 * @example
 * lib.numSeparate(2016, '.,');
 * // returns '2016'
 *
 * @example
 * lib.numSeparate(3000, '.,', true);
 * // returns '3,000'
 *
 * @example
 * lib.numSeparate(1234.56, '|,')
 * // returns '1,234|56'
 *
 * @param   {string|number} value       the value to be converted
 * @param   {string}    separators  string of decimal, then thousands separators
 * @param   {boolean}    separatethousands  boolean, 4-digit integers are separated if true
 *
 * @return  {string}    the value that has been separated
 */
lib.numSeparate = function(value, separators, separatethousands) {
    if(!separatethousands) separatethousands = false;

    if(typeof separators !== 'string' || separators.length === 0) {
        throw new Error('Separator string required for formatting!');
    }

    if(typeof value === 'number') {
        value = String(value);
    }

    var thousandsRe = /(\d+)(\d{3})/;
    var decimalSep = separators.charAt(0);
    var thouSep = separators.charAt(1);

    var x = value.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? decimalSep + x[1] : '';

    // Years are ignored for thousands separators
    if(thouSep && (x.length > 1 || x1.length > 4 || separatethousands)) {
        while(thousandsRe.test(x1)) {
            x1 = x1.replace(thousandsRe, '$1' + thouSep + '$2');
        }
    }

    return x1 + x2;
};

var TEMPLATE_STRING_REGEX = /%{([^\s%{}:]*)(:[^}]*)?}/g;
var SIMPLE_PROPERTY_REGEX = /^\w*$/;

/**
 * Substitute values from an object into a string
 *
 * Examples:
 *  Lib.templateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
 *  Lib.templateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
 *
 * @param {string}  input string containing %{...} template strings
 * @param {obj}     data object containing substitution values
 *
 * @return {string} templated string
 */
lib.templateString = function(string, obj) {
    // Not all that useful, but cache nestedProperty instantiation
    // just in case it speeds things up *slightly*:
    var getterCache = {};

    return string.replace(TEMPLATE_STRING_REGEX, function(dummy, key) {
        if(SIMPLE_PROPERTY_REGEX.test(key)) {
            return obj[key] || '';
        }
        getterCache[key] = getterCache[key] || lib.nestedProperty(obj, key).get;
        return getterCache[key]() || '';
    });
};

var TEMPLATE_STRING_FORMAT_SEPARATOR = /^:/;
var numberOfHoverTemplateWarnings = 0;
var maximumNumberOfHoverTemplateWarnings = 10;
/**
 * Substitute values from an object into a string and optionally formats them using d3-format,
 * or fallback to associated labels.
 *
 * Examples:
 *  Lib.templateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
 *  Lib.templateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
 *  Lib.templateString('price: %{y:$.2f}', {y: 1}) --> 'price: $1.00'
 *
 * @param {string}  input string containing %{...:...} template strings
 * @param {obj}     data object containing fallback text when no formatting is specified, ex.: {yLabel: 'formattedYValue'}
 * @param {obj}     data objects containing substitution values
 *
 * @return {string} templated string
 */
lib.hovertemplateString = function(string, labels) {
    var args = arguments;
    // Not all that useful, but cache nestedProperty instantiation
    // just in case it speeds things up *slightly*:
    var getterCache = {};

    return string.replace(TEMPLATE_STRING_REGEX, function(match, key, format) {
        var obj, value, i;
        for(i = 2; i < args.length; i++) {
            obj = args[i];
            if(obj.hasOwnProperty(key)) {
                value = obj[key];
                break;
            }

            if(!SIMPLE_PROPERTY_REGEX.test(key)) {
                value = getterCache[key] || lib.nestedProperty(obj, key).get();
                if(value) getterCache[key] = value;
            }
            if(value !== undefined) break;
        }

        if(value === undefined) {
            if(numberOfHoverTemplateWarnings < maximumNumberOfHoverTemplateWarnings) {
                lib.warn('Variable \'' + key + '\' in hovertemplate could not be found!');
                value = match;
            }

            if(numberOfHoverTemplateWarnings === maximumNumberOfHoverTemplateWarnings) {
                lib.warn('Too many hovertemplate warnings - additional warnings will be suppressed');
            }
            numberOfHoverTemplateWarnings++;
        }

        if(format) {
            value = d3.format(format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ''))(value);
        } else {
            if(labels.hasOwnProperty(key + 'Label')) value = labels[key + 'Label'];
        }
        return value;
    });
};

/*
 * alphanumeric string sort, tailored for subplot IDs like scene2, scene10, x10y13 etc
 */
var char0 = 48;
var char9 = 57;
lib.subplotSort = function(a, b) {
    var l = Math.min(a.length, b.length) + 1;
    var numA = 0;
    var numB = 0;
    for(var i = 0; i < l; i++) {
        var charA = a.charCodeAt(i) || 0;
        var charB = b.charCodeAt(i) || 0;
        var isNumA = charA >= char0 && charA <= char9;
        var isNumB = charB >= char0 && charB <= char9;

        if(isNumA) numA = 10 * numA + charA - char0;
        if(isNumB) numB = 10 * numB + charB - char0;

        if(!isNumA || !isNumB) {
            if(numA !== numB) return numA - numB;
            if(charA !== charB) return charA - charB;
        }
    }
    return numB - numA;
};

// repeatable pseudorandom generator
var randSeed = 2000000000;

lib.seedPseudoRandom = function() {
    randSeed = 2000000000;
};

lib.pseudoRandom = function() {
    var lastVal = randSeed;
    randSeed = (69069 * randSeed + 1) % 4294967296;
    // don't let consecutive vals be too close together
    // gets away from really trying to be random, in favor of better local uniformity
    if(Math.abs(randSeed - lastVal) < 429496729) return lib.pseudoRandom();
    return randSeed / 4294967296;
};

},{"../constants/numerical":671,"./anchor_utils":675,"./angles":676,"./array":677,"./clean_number":678,"./clear_responsive":680,"./coerce":681,"./dates":682,"./extend":684,"./filter_unique":685,"./filter_visible":686,"./geometry2d":689,"./get_graph_div":690,"./identity":693,"./is_plain_object":695,"./keyed_container":696,"./localize":697,"./loggers":698,"./make_trace_groups":699,"./matrix":700,"./mod":701,"./nested_property":702,"./noop":703,"./notifier":704,"./push_unique":708,"./regex":710,"./relative_attr":711,"./relink_private":712,"./search":713,"./stats":716,"./throttle":719,"./to_log_range":720,"d3":149,"fast-isnumeric":215}],695:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

// more info: http://stackoverflow.com/questions/18531624/isplainobject-thing
module.exports = function isPlainObject(obj) {

    // We need to be a little less strict in the `imagetest` container because
    // of how async image requests are handled.
    //
    // N.B. isPlainObject(new Constructor()) will return true in `imagetest`
    if(window && window.process && window.process.versions) {
        return Object.prototype.toString.call(obj) === '[object Object]';
    }

    return (
        Object.prototype.toString.call(obj) === '[object Object]' &&
        Object.getPrototypeOf(obj) === Object.prototype
    );
};

},{}],696:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var nestedProperty = _dereq_('./nested_property');

var SIMPLE_PROPERTY_REGEX = /^\w*$/;

// bitmask for deciding what's updated. Sometimes the name needs to be updated,
// sometimes the value needs to be updated, and sometimes both do. This is just
// a simple way to track what's updated such that it's a simple OR operation to
// assimilate new updates.
//
// The only exception is the UNSET bit that tracks when we need to explicitly
// unset and remove the property. This concrn arises because of the special
// way in which nestedProperty handles null/undefined. When you specify `null`,
// it prunes any unused items in the tree. I ran into some issues with it getting
// null vs undefined confused, so UNSET is just a bit that forces the property
// update to send `null`, removing the property explicitly rather than setting
// it to undefined.
var NONE = 0;
var NAME = 1;
var VALUE = 2;
var BOTH = 3;
var UNSET = 4;

module.exports = function keyedContainer(baseObj, path, keyName, valueName) {
    keyName = keyName || 'name';
    valueName = valueName || 'value';
    var i, arr, baseProp;
    var changeTypes = {};

    if(path && path.length) {
        baseProp = nestedProperty(baseObj, path);
        arr = baseProp.get();
    } else {
        arr = baseObj;
    }

    path = path || '';

    // Construct an index:
    var indexLookup = {};
    if(arr) {
        for(i = 0; i < arr.length; i++) {
            indexLookup[arr[i][keyName]] = i;
        }
    }

    var isSimpleValueProp = SIMPLE_PROPERTY_REGEX.test(valueName);

    var obj = {
        set: function(name, value) {
            var changeType = value === null ? UNSET : NONE;

            // create the base array if necessary
            if(!arr) {
                if(!baseProp || changeType === UNSET) return;

                arr = [];
                baseProp.set(arr);
            }

            var idx = indexLookup[name];
            if(idx === undefined) {
                if(changeType === UNSET) return;

                changeType = changeType | BOTH;
                idx = arr.length;
                indexLookup[name] = idx;
            } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : nestedProperty(arr[idx], valueName).get())) {
                changeType = changeType | VALUE;
            }

            var newValue = arr[idx] = arr[idx] || {};
            newValue[keyName] = name;

            if(isSimpleValueProp) {
                newValue[valueName] = value;
            } else {
                nestedProperty(newValue, valueName).set(value);
            }

            // If it's not an unset, force that bit to be unset. This is all related to the fact
            // that undefined and null are a bit specially implemented in nestedProperties.
            if(value !== null) {
                changeType = changeType & ~UNSET;
            }

            changeTypes[idx] = changeTypes[idx] | changeType;

            return obj;
        },
        get: function(name) {
            if(!arr) return;

            var idx = indexLookup[name];

            if(idx === undefined) {
                return undefined;
            } else if(isSimpleValueProp) {
                return arr[idx][valueName];
            } else {
                return nestedProperty(arr[idx], valueName).get();
            }
        },
        rename: function(name, newName) {
            var idx = indexLookup[name];

            if(idx === undefined) return obj;
            changeTypes[idx] = changeTypes[idx] | NAME;

            indexLookup[newName] = idx;
            delete indexLookup[name];

            arr[idx][keyName] = newName;

            return obj;
        },
        remove: function(name) {
            var idx = indexLookup[name];

            if(idx === undefined) return obj;

            var object = arr[idx];
            if(Object.keys(object).length > 2) {
                // This object contains more than just the key/value, so unset
                // the value without modifying the entry otherwise:
                changeTypes[idx] = changeTypes[idx] | VALUE;
                return obj.set(name, null);
            }

            if(isSimpleValueProp) {
                for(i = idx; i < arr.length; i++) {
                    changeTypes[i] = changeTypes[i] | BOTH;
                }
                for(i = idx; i < arr.length; i++) {
                    indexLookup[arr[i][keyName]]--;
                }
                arr.splice(idx, 1);
                delete(indexLookup[name]);
            } else {
                // Perform this update *strictly* so we can check whether the result's
                // been pruned. If so, it's a removal. If not, it's a value unset only.
                nestedProperty(object, valueName).set(null);

                // Now check if the top level nested property has any keys left. If so,
                // the object still has values so we only want to unset the key. If not,
                // the entire object can be removed since there's no other data.
                // var topLevelKeys = Object.keys(object[valueName.split('.')[0]] || []);

                changeTypes[idx] = changeTypes[idx] | VALUE | UNSET;
            }

            return obj;
        },
        constructUpdate: function() {
            var astr, idx;
            var update = {};
            var changed = Object.keys(changeTypes);
            for(var i = 0; i < changed.length; i++) {
                idx = changed[i];
                astr = path + '[' + idx + ']';
                if(arr[idx]) {
                    if(changeTypes[idx] & NAME) {
                        update[astr + '.' + keyName] = arr[idx][keyName];
                    }
                    if(changeTypes[idx] & VALUE) {
                        if(isSimpleValueProp) {
                            update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : arr[idx][valueName];
                        } else {
                            update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : nestedProperty(arr[idx], valueName).get();
                        }
                    }
                } else {
                    update[astr] = null;
                }
            }

            return update;
        }
    };

    return obj;
};

},{"./nested_property":702}],697:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../registry');

/**
 * localize: translate a string for the current locale
 *
 * @param {object} gd: the graphDiv for context
 *  gd._context.locale determines the language (& optional region/country)
 *  the dictionary for each locale may either be supplied in
 *  gd._context.locales or globally via Plotly.register
 * @param {string} s: the string to translate
 */
module.exports = function localize(gd, s) {
    var locale = gd._context.locale;

    /*
     * Priority of lookup:
     *     contextDicts[locale],
     *     registeredDicts[locale],
     *     contextDicts[baseLocale], (if baseLocale is distinct)
     *     registeredDicts[baseLocale]
     * Return the first translation we find.
     * This way if you have a regionalization you are allowed to specify
     * only what's different from the base locale, everything else will
     * fall back on the base.
     */
    for(var i = 0; i < 2; i++) {
        var locales = gd._context.locales;
        for(var j = 0; j < 2; j++) {
            var dict = (locales[locale] || {}).dictionary;
            if(dict) {
                var out = dict[s];
                if(out) return out;
            }
            locales = Registry.localeRegistry;
        }

        var baseLocale = locale.split('-')[0];
        if(baseLocale === locale) break;
        locale = baseLocale;
    }

    return s;
};

},{"../registry":825}],698:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/* eslint-disable no-console */

var dfltConfig = _dereq_('../plot_api/plot_config').dfltConfig;

var loggers = module.exports = {};

/**
 * ------------------------------------------
 * debugging tools
 * ------------------------------------------
 */

loggers.log = function() {
    if(dfltConfig.logging > 1) {
        var messages = ['LOG:'];

        for(var i = 0; i < arguments.length; i++) {
            messages.push(arguments[i]);
        }

        apply(console.trace || console.log, messages);
    }
};

loggers.warn = function() {
    if(dfltConfig.logging > 0) {
        var messages = ['WARN:'];

        for(var i = 0; i < arguments.length; i++) {
            messages.push(arguments[i]);
        }

        apply(console.trace || console.log, messages);
    }
};

loggers.error = function() {
    if(dfltConfig.logging > 0) {
        var messages = ['ERROR:'];

        for(var i = 0; i < arguments.length; i++) {
            messages.push(arguments[i]);
        }

        apply(console.error, messages);
    }
};

/*
 * Robust apply, for IE9 where console.log doesn't support
 * apply like other functions do
 */
function apply(f, args) {
    if(f && f.apply) {
        try {
            // `this` should always be console, since here we're always
            // applying a method of the console object.
            f.apply(console, args);
            return;
        }
        catch(e) { /* in case apply failed, fall back on the code below */ }
    }

    // no apply - just try calling the function on each arg independently
    for(var i = 0; i < args.length; i++) {
        try {
            f(args[i]);
        }
        catch(e) {
            // still fails - last resort simple console.log
            console.log(args[i]);
        }
    }
}

},{"../plot_api/plot_config":730}],699:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

/**
 * General helper to manage trace groups based on calcdata
 *
 * @param {d3.selection} traceLayer: a selection containing a single group
 *     to draw these traces into
 * @param {array} cdModule: array of calcdata items for this
 *     module and subplot combination. Assumes the calcdata item for each
 *     trace is an array with the fullData trace attached to the first item.
 * @param {string} cls: the class attribute to give each trace group
 *     so you can give multiple classes separated by spaces
 */
module.exports = function makeTraceGroups(traceLayer, cdModule, cls) {
    var traces = traceLayer.selectAll('g.' + cls.replace(/\s/g, '.'))
        .data(cdModule, function(cd) { return cd[0].trace.uid; });

    traces.exit().remove();

    traces.enter().append('g')
        .attr('class', cls);

    traces.order();

    return traces;
};

},{}],700:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


exports.init2dArray = function(rowLength, colLength) {
    var array = new Array(rowLength);
    for(var i = 0; i < rowLength; i++) array[i] = new Array(colLength);
    return array;
};

/**
 * transpose a (possibly ragged) 2d array z. inspired by
 * http://stackoverflow.com/questions/17428587/
 * transposing-a-2d-array-in-javascript
 */
exports.transposeRagged = function(z) {
    var maxlen = 0;
    var zlen = z.length;
    var i, j;
    // Maximum row length:
    for(i = 0; i < zlen; i++) maxlen = Math.max(maxlen, z[i].length);

    var t = new Array(maxlen);
    for(i = 0; i < maxlen; i++) {
        t[i] = new Array(zlen);
        for(j = 0; j < zlen; j++) t[i][j] = z[j][i];
    }

    return t;
};

// our own dot function so that we don't need to include numeric
exports.dot = function(x, y) {
    if(!(x.length && y.length) || x.length !== y.length) return null;

    var len = x.length;
    var out;
    var i;

    if(x[0].length) {
        // mat-vec or mat-mat
        out = new Array(len);
        for(i = 0; i < len; i++) out[i] = exports.dot(x[i], y);
    }
    else if(y[0].length) {
        // vec-mat
        var yTranspose = exports.transposeRagged(y);
        out = new Array(yTranspose.length);
        for(i = 0; i < yTranspose.length; i++) out[i] = exports.dot(x, yTranspose[i]);
    }
    else {
        // vec-vec
        out = 0;
        for(i = 0; i < len; i++) out += x[i] * y[i];
    }

    return out;
};

// translate by (x,y)
exports.translationMatrix = function(x, y) {
    return [[1, 0, x], [0, 1, y], [0, 0, 1]];
};

// rotate by alpha around (0,0)
exports.rotationMatrix = function(alpha) {
    var a = alpha * Math.PI / 180;
    return [[Math.cos(a), -Math.sin(a), 0],
            [Math.sin(a), Math.cos(a), 0],
            [0, 0, 1]];
};

// rotate by alpha around (x,y)
exports.rotationXYMatrix = function(a, x, y) {
    return exports.dot(
        exports.dot(exports.translationMatrix(x, y),
                    exports.rotationMatrix(a)),
        exports.translationMatrix(-x, -y));
};

// applies a 2D transformation matrix to either x and y params or an [x,y] array
exports.apply2DTransform = function(transform) {
    return function() {
        var args = arguments;
        if(args.length === 3) {
            args = args[0];
        }// from map
        var xy = arguments.length === 1 ? args[0] : [args[0], args[1]];
        return exports.dot(transform, [xy[0], xy[1], 1]).slice(0, 2);
    };
};

// applies a 2D transformation matrix to an [x1,y1,x2,y2] array (to transform a segment)
exports.apply2DTransform2 = function(transform) {
    var at = exports.apply2DTransform(transform);
    return function(xys) {
        return at(xys.slice(0, 2)).concat(at(xys.slice(2, 4)));
    };
};

},{}],701:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * sanitized modulus function that always returns in the range [0, d)
 * rather than (-d, 0] if v is negative
 */
function mod(v, d) {
    var out = v % d;
    return out < 0 ? out + d : out;
}

/**
 * sanitized modulus function that always returns in the range [-d/2, d/2]
 * rather than (-d, 0] if v is negative
 */
function modHalf(v, d) {
    return Math.abs(v) > (d / 2) ?
        v - Math.round(v / d) * d :
        v;
}

module.exports = {
    mod: mod,
    modHalf: modHalf
};

},{}],702:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var isArrayOrTypedArray = _dereq_('./array').isArrayOrTypedArray;

/**
 * convert a string s (such as 'xaxis.range[0]')
 * representing a property of nested object into set and get methods
 * also return the string and object so we don't have to keep track of them
 * allows [-1] for an array index, to set a property inside all elements
 * of an array
 * eg if obj = {arr: [{a: 1}, {a: 2}]}
 * you can do p = nestedProperty(obj, 'arr[-1].a')
 * but you cannot set the array itself this way, to do that
 * just set the whole array.
 * eg if obj = {arr: [1, 2, 3]}
 * you can't do nestedProperty(obj, 'arr[-1]').set(5)
 * but you can do nestedProperty(obj, 'arr').set([5, 5, 5])
 */
module.exports = function nestedProperty(container, propStr) {
    if(isNumeric(propStr)) propStr = String(propStr);
    else if(typeof propStr !== 'string' ||
            propStr.substr(propStr.length - 4) === '[-1]') {
        throw 'bad property string';
    }

    var j = 0;
    var propParts = propStr.split('.');
    var indexed;
    var indices;
    var i;

    // check for parts of the nesting hierarchy that are numbers (ie array elements)
    while(j < propParts.length) {
        // look for non-bracket chars, then any number of [##] blocks
        indexed = String(propParts[j]).match(/^([^\[\]]*)((\[\-?[0-9]*\])+)$/);
        if(indexed) {
            if(indexed[1]) propParts[j] = indexed[1];
            // allow propStr to start with bracketed array indices
            else if(j === 0) propParts.splice(0, 1);
            else throw 'bad property string';

            indices = indexed[2]
                .substr(1, indexed[2].length - 2)
                .split('][');

            for(i = 0; i < indices.length; i++) {
                j++;
                propParts.splice(j, 0, Number(indices[i]));
            }
        }
        j++;
    }

    if(typeof container !== 'object') {
        return badContainer(container, propStr, propParts);
    }

    return {
        set: npSet(container, propParts, propStr),
        get: npGet(container, propParts),
        astr: propStr,
        parts: propParts,
        obj: container
    };
};

function npGet(cont, parts) {
    return function() {
        var curCont = cont;
        var curPart;
        var allSame;
        var out;
        var i;
        var j;

        for(i = 0; i < parts.length - 1; i++) {
            curPart = parts[i];
            if(curPart === -1) {
                allSame = true;
                out = [];
                for(j = 0; j < curCont.length; j++) {
                    out[j] = npGet(curCont[j], parts.slice(i + 1))();
                    if(out[j] !== out[0]) allSame = false;
                }
                return allSame ? out[0] : out;
            }
            if(typeof curPart === 'number' && !isArrayOrTypedArray(curCont)) {
                return undefined;
            }
            curCont = curCont[curPart];
            if(typeof curCont !== 'object' || curCont === null) {
                return undefined;
            }
        }

        // only hit this if parts.length === 1
        if(typeof curCont !== 'object' || curCont === null) return undefined;

        out = curCont[parts[i]];
        if(out === null) return undefined;
        return out;
    };
}

/*
 * Can this value be deleted? We can delete `undefined`, and `null` except INSIDE an
 * *args* array.
 *
 * Previously we also deleted some `{}` and `[]`, in order to try and make set/unset
 * a net noop; but this causes far more complication than it's worth, and still had
 * lots of exceptions. See https://github.com/plotly/plotly.js/issues/1410
 *
 * *args* arrays get passed directly to API methods and we should respect null if
 * the user put it there, but otherwise null is deleted as we use it as code
 * in restyle/relayout/update for "delete this value" whereas undefined means
 * "ignore this edit"
 */
var ARGS_PATTERN = /(^|\.)args\[/;
function isDeletable(val, propStr) {
    return (val === undefined) || (val === null && !propStr.match(ARGS_PATTERN));
}

function npSet(cont, parts, propStr) {
    return function(val) {
        var curCont = cont;
        var propPart = '';
        var containerLevels = [[cont, propPart]];
        var toDelete = isDeletable(val, propStr);
        var curPart;
        var i;

        for(i = 0; i < parts.length - 1; i++) {
            curPart = parts[i];

            if(typeof curPart === 'number' && !isArrayOrTypedArray(curCont)) {
                throw 'array index but container is not an array';
            }

            // handle special -1 array index
            if(curPart === -1) {
                toDelete = !setArrayAll(curCont, parts.slice(i + 1), val, propStr);
                if(toDelete) break;
                else return;
            }

            if(!checkNewContainer(curCont, curPart, parts[i + 1], toDelete)) {
                break;
            }

            curCont = curCont[curPart];

            if(typeof curCont !== 'object' || curCont === null) {
                throw 'container is not an object';
            }

            propPart = joinPropStr(propPart, curPart);

            containerLevels.push([curCont, propPart]);
        }

        if(toDelete) {
            if(i === parts.length - 1) {
                delete curCont[parts[i]];

                // The one bit of pruning we still do: drop `undefined` from the end of arrays.
                // In case someone has already unset previous items, continue until we hit a
                // non-undefined value.
                if(Array.isArray(curCont) && +parts[i] === curCont.length - 1) {
                    while(curCont.length && curCont[curCont.length - 1] === undefined) {
                        curCont.pop();
                    }
                }
            }
        }
        else curCont[parts[i]] = val;
    };
}

function joinPropStr(propStr, newPart) {
    var toAdd = newPart;
    if(isNumeric(newPart)) toAdd = '[' + newPart + ']';
    else if(propStr) toAdd = '.' + newPart;

    return propStr + toAdd;
}

// handle special -1 array index
function setArrayAll(containerArray, innerParts, val, propStr) {
    var arrayVal = isArrayOrTypedArray(val);
    var allSet = true;
    var thisVal = val;
    var thisPropStr = propStr.replace('-1', 0);
    var deleteThis = arrayVal ? false : isDeletable(val, thisPropStr);
    var firstPart = innerParts[0];
    var i;

    for(i = 0; i < containerArray.length; i++) {
        thisPropStr = propStr.replace('-1', i);
        if(arrayVal) {
            thisVal = val[i % val.length];
            deleteThis = isDeletable(thisVal, thisPropStr);
        }
        if(deleteThis) allSet = false;
        if(!checkNewContainer(containerArray, i, firstPart, deleteThis)) {
            continue;
        }
        npSet(containerArray[i], innerParts, propStr.replace('-1', i))(thisVal);
    }
    return allSet;
}

/**
 * make new sub-container as needed.
 * returns false if there's no container and none is needed
 * because we're only deleting an attribute
 */
function checkNewContainer(container, part, nextPart, toDelete) {
    if(container[part] === undefined) {
        if(toDelete) return false;

        if(typeof nextPart === 'number') container[part] = [];
        else container[part] = {};
    }
    return true;
}

function badContainer(container, propStr, propParts) {
    return {
        set: function() { throw 'bad container'; },
        get: function() {},
        astr: propStr,
        parts: propParts,
        obj: container
    };
}

},{"./array":677,"fast-isnumeric":215}],703:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// Simple helper functions
// none of these need any external deps

module.exports = function noop() {};

},{}],704:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');

var NOTEDATA = [];

/**
 * notifier
 * @param {String} text The person's user name
 * @param {Number} [delay=1000] The delay time in milliseconds
 *          or 'long' which provides 2000 ms delay time.
 * @return {undefined} this function does not return a value
 */
module.exports = function(text, displayLength) {
    if(NOTEDATA.indexOf(text) !== -1) return;

    NOTEDATA.push(text);

    var ts = 1000;
    if(isNumeric(displayLength)) ts = displayLength;
    else if(displayLength === 'long') ts = 3000;

    var notifierContainer = d3.select('body')
        .selectAll('.plotly-notifier')
        .data([0]);
    notifierContainer.enter()
        .append('div')
        .classed('plotly-notifier', true);

    var notes = notifierContainer.selectAll('.notifier-note').data(NOTEDATA);

    function killNote(transition) {
        transition
            .duration(700)
            .style('opacity', 0)
            .each('end', function(thisText) {
                var thisIndex = NOTEDATA.indexOf(thisText);
                if(thisIndex !== -1) NOTEDATA.splice(thisIndex, 1);
                d3.select(this).remove();
            });
    }

    notes.enter().append('div')
        .classed('notifier-note', true)
        .style('opacity', 0)
        .each(function(thisText) {
            var note = d3.select(this);

            note.append('button')
                .classed('notifier-close', true)
                .html('&times;')
                .on('click', function() {
                    note.transition().call(killNote);
                });

            var p = note.append('p');
            var lines = thisText.split(/<br\s*\/?>/g);
            for(var i = 0; i < lines.length; i++) {
                if(i) p.append('br');
                p.append('span').text(lines[i]);
            }

            note.transition()
                    .duration(700)
                    .style('opacity', 1)
                .transition()
                    .delay(ts)
                    .call(killNote);
        });
};

},{"d3":149,"fast-isnumeric":215}],705:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var setCursor = _dereq_('./setcursor');

var STASHATTR = 'data-savedcursor';
var NO_CURSOR = '!!';

/*
 * works with our CSS cursor classes (see css/_cursor.scss)
 * to override a previous cursor set on d3 single-element selections,
 * by moving the name of the original cursor to the data-savedcursor attr.
 * omit cursor to revert to the previously set value.
 */
module.exports = function overrideCursor(el3, csr) {
    var savedCursor = el3.attr(STASHATTR);
    if(csr) {
        if(!savedCursor) {
            var classes = (el3.attr('class') || '').split(' ');
            for(var i = 0; i < classes.length; i++) {
                var cls = classes[i];
                if(cls.indexOf('cursor-') === 0) {
                    el3.attr(STASHATTR, cls.substr(7))
                        .classed(cls, false);
                }
            }
            if(!el3.attr(STASHATTR)) {
                el3.attr(STASHATTR, NO_CURSOR);
            }
        }
        setCursor(el3, csr);
    }
    else if(savedCursor) {
        el3.attr(STASHATTR, null);

        if(savedCursor === NO_CURSOR) setCursor(el3);
        else setCursor(el3, savedCursor);
    }
};

},{"./setcursor":714}],706:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var dot = _dereq_('./matrix').dot;
var BADNUM = _dereq_('../constants/numerical').BADNUM;

var polygon = module.exports = {};

/**
 * Turn an array of [x, y] pairs into a polygon object
 * that can test if points are inside it
 *
 * @param ptsIn Array of [x, y] pairs
 *
 * @returns polygon Object {xmin, xmax, ymin, ymax, pts, contains}
 *      (x|y)(min|max) are the bounding rect of the polygon
 *      pts is the original array, with the first pair repeated at the end
 *      contains is a function: (pt, omitFirstEdge)
 *          pt is the [x, y] pair to test
 *          omitFirstEdge truthy means points exactly on the first edge don't
 *              count. This is for use adding one polygon to another so we
 *              don't double-count the edge where they meet.
 *          returns boolean: is pt inside the polygon (including on its edges)
 */
polygon.tester = function tester(ptsIn) {
    var pts = ptsIn.slice();
    var xmin = pts[0][0];
    var xmax = xmin;
    var ymin = pts[0][1];
    var ymax = ymin;
    var i;

    pts.push(pts[0]);
    for(i = 1; i < pts.length; i++) {
        xmin = Math.min(xmin, pts[i][0]);
        xmax = Math.max(xmax, pts[i][0]);
        ymin = Math.min(ymin, pts[i][1]);
        ymax = Math.max(ymax, pts[i][1]);
    }

    // do we have a rectangle? Handle this here, so we can use the same
    // tester for the rectangular case without sacrificing speed

    var isRect = false;
    var rectFirstEdgeTest;

    if(pts.length === 5) {
        if(pts[0][0] === pts[1][0]) { // vert, horz, vert, horz
            if(pts[2][0] === pts[3][0] &&
                    pts[0][1] === pts[3][1] &&
                    pts[1][1] === pts[2][1]) {
                isRect = true;
                rectFirstEdgeTest = function(pt) { return pt[0] === pts[0][0]; };
            }
        }
        else if(pts[0][1] === pts[1][1]) { // horz, vert, horz, vert
            if(pts[2][1] === pts[3][1] &&
                    pts[0][0] === pts[3][0] &&
                    pts[1][0] === pts[2][0]) {
                isRect = true;
                rectFirstEdgeTest = function(pt) { return pt[1] === pts[0][1]; };
            }
        }
    }

    function rectContains(pt, omitFirstEdge) {
        var x = pt[0];
        var y = pt[1];

        if(x === BADNUM || x < xmin || x > xmax || y === BADNUM || y < ymin || y > ymax) {
            // pt is outside the bounding box of polygon
            return false;
        }
        if(omitFirstEdge && rectFirstEdgeTest(pt)) return false;

        return true;
    }

    function contains(pt, omitFirstEdge) {
        var x = pt[0];
        var y = pt[1];

        if(x === BADNUM || x < xmin || x > xmax || y === BADNUM || y < ymin || y > ymax) {
            // pt is outside the bounding box of polygon
            return false;
        }

        var imax = pts.length;
        var x1 = pts[0][0];
        var y1 = pts[0][1];
        var crossings = 0;
        var i;
        var x0;
        var y0;
        var xmini;
        var ycross;

        for(i = 1; i < imax; i++) {
            // find all crossings of a vertical line upward from pt with
            // polygon segments
            // crossings exactly at xmax don't count, unless the point is
            // exactly on the segment, then it counts as inside.
            x0 = x1;
            y0 = y1;
            x1 = pts[i][0];
            y1 = pts[i][1];
            xmini = Math.min(x0, x1);

            // outside the bounding box of this segment, it's only a crossing
            // if it's below the box.
            if(x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) {
                continue;
            }
            else if(y < Math.min(y0, y1)) {
                // don't count the left-most point of the segment as a crossing
                // because we don't want to double-count adjacent crossings
                // UNLESS the polygon turns past vertical at exactly this x
                // Note that this is repeated below, but we can't factor it out
                // because
                if(x !== xmini) crossings++;
            }
            // inside the bounding box, check the actual line intercept
            else {
                // vertical segment - we know already that the point is exactly
                // on the segment, so mark the crossing as exactly at the point.
                if(x1 === x0) ycross = y;
                // any other angle
                else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0);

                // exactly on the edge: counts as inside the polygon, unless it's the
                // first edge and we're omitting it.
                if(y === ycross) {
                    if(i === 1 && omitFirstEdge) return false;
                    return true;
                }

                if(y <= ycross && x !== xmini) crossings++;
            }
        }

        // if we've gotten this far, odd crossings means inside, even is outside
        return crossings % 2 === 1;
    }

    // detect if poly is degenerate
    var degenerate = true;
    var lastPt = pts[0];
    for(i = 1; i < pts.length; i++) {
        if(lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) {
            degenerate = false;
            break;
        }
    }

    return {
        xmin: xmin,
        xmax: xmax,
        ymin: ymin,
        ymax: ymax,
        pts: pts,
        contains: isRect ? rectContains : contains,
        isRect: isRect,
        degenerate: degenerate
    };
};

/**
 * Test if a segment of a points array is bent or straight
 *
 * @param pts Array of [x, y] pairs
 * @param start the index of the proposed start of the straight section
 * @param end the index of the proposed end point
 * @param tolerance the max distance off the line connecting start and end
 *      before the line counts as bent
 * @returns boolean: true means this segment is bent, false means straight
 */
var isBent = polygon.isSegmentBent = function isBent(pts, start, end, tolerance) {
    var startPt = pts[start];
    var segment = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]];
    var segmentSquared = dot(segment, segment);
    var segmentLen = Math.sqrt(segmentSquared);
    var unitPerp = [-segment[1] / segmentLen, segment[0] / segmentLen];
    var i;
    var part;
    var partParallel;

    for(i = start + 1; i < end; i++) {
        part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]];
        partParallel = dot(part, segment);

        if(partParallel < 0 || partParallel > segmentSquared ||
            Math.abs(dot(part, unitPerp)) > tolerance) return true;
    }
    return false;
};

/**
 * Make a filtering polygon, to minimize the number of segments
 *
 * @param pts Array of [x, y] pairs (must start with at least 1 pair)
 * @param tolerance the maximum deviation from straight allowed for
 *      removing points to simplify the polygon
 *
 * @returns Object {addPt, raw, filtered}
 *      addPt is a function(pt: [x, y] pair) to add a raw point and
 *          continue filtering
 *      raw is all the input points
 *      filtered is the resulting filtered Array of [x, y] pairs
 */
polygon.filter = function filter(pts, tolerance) {
    var ptsFiltered = [pts[0]];
    var doneRawIndex = 0;
    var doneFilteredIndex = 0;

    function addPt(pt) {
        pts.push(pt);
        var prevFilterLen = ptsFiltered.length;
        var iLast = doneRawIndex;
        ptsFiltered.splice(doneFilteredIndex + 1);

        for(var i = iLast + 1; i < pts.length; i++) {
            if(i === pts.length - 1 || isBent(pts, iLast, i + 1, tolerance)) {
                ptsFiltered.push(pts[i]);
                if(ptsFiltered.length < prevFilterLen - 2) {
                    doneRawIndex = i;
                    doneFilteredIndex = ptsFiltered.length - 1;
                }
                iLast = i;
            }
        }
    }

    if(pts.length > 1) {
        var lastPt = pts.pop();
        addPt(lastPt);
    }

    return {
        addPt: addPt,
        raw: pts,
        filtered: ptsFiltered
    };
};

},{"../constants/numerical":671,"./matrix":700}],707:[function(_dereq_,module,exports){
(function (global){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var showNoWebGlMsg = _dereq_('./show_no_webgl_msg');

// Note that this module should be ONLY required into
// files corresponding to regl trace modules
// so that bundles with non-regl only don't include
// regl and all its bytes.
var createRegl = _dereq_('regl');

/**
 * Idempotent version of createRegl. Create regl instances
 * in the correct canvases with the correct attributes and
 * options
 *
 * @param {DOM node or object} gd : graph div object
 * @param {array} extensions : list of extension to pass to createRegl
 *
 * @return {boolean} true if all createRegl calls succeeded, false otherwise
 */
module.exports = function prepareRegl(gd, extensions) {
    var fullLayout = gd._fullLayout;
    var success = true;

    fullLayout._glcanvas.each(function(d) {
        if(d.regl) return;
        // only parcoords needs pick layer
        if(d.pick && !fullLayout._has('parcoords')) return;

        try {
            d.regl = createRegl({
                canvas: this,
                attributes: {
                    antialias: !d.pick,
                    preserveDrawingBuffer: true
                },
                pixelRatio: gd._context.plotGlPixelRatio || global.devicePixelRatio,
                extensions: extensions || []
            });
        } catch(e) {
            success = false;
        }

        if(success) {
            this.addEventListener('webglcontextlost', function(event) {
                if(gd && gd.emit) {
                    gd.emit('plotly_webglcontextlost', {
                        event: event,
                        layer: d.key
                    });
                }
            }, false);
        }
    });

    if(!success) {
        showNoWebGlMsg({container: fullLayout._glcontainer.node()});
    }
    return success;
};

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./show_no_webgl_msg":715,"regl":480}],708:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * Push array with unique items
 *
 * Ignores falsy items, except 0 so we can use it to construct arrays of indices.
 *
 * @param {array} array
 *  array to be filled
 * @param {any} item
 *  item to be or not to be inserted
 * @return {array}
 *  ref to array (now possibly containing one more item)
 *
 */
module.exports = function pushUnique(array, item) {
    if(item instanceof RegExp) {
        var itemStr = item.toString();
        for(var i = 0; i < array.length; i++) {
            if(array[i] instanceof RegExp && array[i].toString() === itemStr) {
                return array;
            }
        }
        array.push(item);
    }
    else if((item || item === 0) && array.indexOf(item) === -1) array.push(item);

    return array;
};

},{}],709:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../lib');
var dfltConfig = _dereq_('../plot_api/plot_config').dfltConfig;

/**
 * Copy arg array *without* removing `undefined` values from objects.
 *
 * @param gd
 * @param args
 * @returns {Array}
 */
function copyArgArray(gd, args) {
    var copy = [];
    var arg;

    for(var i = 0; i < args.length; i++) {
        arg = args[i];

        if(arg === gd) copy[i] = arg;
        else if(typeof arg === 'object') {
            copy[i] = Array.isArray(arg) ?
                Lib.extendDeep([], arg) :
                Lib.extendDeepAll({}, arg);
        }
        else copy[i] = arg;
    }

    return copy;
}


// -----------------------------------------------------
// Undo/Redo queue for plots
// -----------------------------------------------------


var queue = {};

// TODO: disable/enable undo and redo buttons appropriately

/**
 * Add an item to the undoQueue for a graphDiv
 *
 * @param gd
 * @param undoFunc Function undo this operation
 * @param undoArgs Args to supply undoFunc with
 * @param redoFunc Function to redo this operation
 * @param redoArgs Args to supply redoFunc with
 */
queue.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) {
    var queueObj,
        queueIndex;

    // make sure we have the queue and our position in it
    gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false};
    queueIndex = gd.undoQueue.index;

    // if we're already playing an undo or redo, or if this is an auto operation
    // (like pane resize... any others?) then we don't save this to the undo queue
    if(gd.autoplay) {
        if(!gd.undoQueue.inSequence) gd.autoplay = false;
        return;
    }

    // if we're not in a sequence or are just starting, we need a new queue item
    if(!gd.undoQueue.sequence || gd.undoQueue.beginSequence) {
        queueObj = {undo: {calls: [], args: []}, redo: {calls: [], args: []}};
        gd.undoQueue.queue.splice(queueIndex, gd.undoQueue.queue.length - queueIndex, queueObj);
        gd.undoQueue.index += 1;
    } else {
        queueObj = gd.undoQueue.queue[queueIndex - 1];
    }
    gd.undoQueue.beginSequence = false;

    // we unshift to handle calls for undo in a forward for loop later
    if(queueObj) {
        queueObj.undo.calls.unshift(undoFunc);
        queueObj.undo.args.unshift(undoArgs);
        queueObj.redo.calls.push(redoFunc);
        queueObj.redo.args.push(redoArgs);
    }

    if(gd.undoQueue.queue.length > dfltConfig.queueLength) {
        gd.undoQueue.queue.shift();
        gd.undoQueue.index--;
    }
};

/**
 * Begin a sequence of undoQueue changes
 *
 * @param gd
 */
queue.startSequence = function(gd) {
    gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false};
    gd.undoQueue.sequence = true;
    gd.undoQueue.beginSequence = true;
};

/**
 * Stop a sequence of undoQueue changes
 *
 * Call this *after* you're sure your undo chain has ended
 *
 * @param gd
 */
queue.stopSequence = function(gd) {
    gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false};
    gd.undoQueue.sequence = false;
    gd.undoQueue.beginSequence = false;
};

/**
 * Move one step back in the undo queue, and undo the object there.
 *
 * @param gd
 */
queue.undo = function undo(gd) {
    var queueObj, i;

    if(gd.framework && gd.framework.isPolar) {
        gd.framework.undo();
        return;
    }
    if(gd.undoQueue === undefined ||
            isNaN(gd.undoQueue.index) ||
            gd.undoQueue.index <= 0) {
        return;
    }

    // index is pointing to next *forward* queueObj, point to the one we're undoing
    gd.undoQueue.index--;

    // get the queueObj for instructions on how to undo
    queueObj = gd.undoQueue.queue[gd.undoQueue.index];

    // this sequence keeps things from adding to the queue during undo/redo
    gd.undoQueue.inSequence = true;
    for(i = 0; i < queueObj.undo.calls.length; i++) {
        queue.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]);
    }
    gd.undoQueue.inSequence = false;
    gd.autoplay = false;
};

/**
 * Redo the current object in the undo, then move forward in the queue.
 *
 * @param gd
 */
queue.redo = function redo(gd) {
    var queueObj, i;

    if(gd.framework && gd.framework.isPolar) {
        gd.framework.redo();
        return;
    }
    if(gd.undoQueue === undefined ||
            isNaN(gd.undoQueue.index) ||
            gd.undoQueue.index >= gd.undoQueue.queue.length) {
        return;
    }

    // get the queueObj for instructions on how to undo
    queueObj = gd.undoQueue.queue[gd.undoQueue.index];

    // this sequence keeps things from adding to the queue during undo/redo
    gd.undoQueue.inSequence = true;
    for(i = 0; i < queueObj.redo.calls.length; i++) {
        queue.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]);
    }
    gd.undoQueue.inSequence = false;
    gd.autoplay = false;

    // index is pointing to the thing we just redid, move it
    gd.undoQueue.index++;
};

/**
 * Called by undo/redo to make the actual changes.
 *
 * Not meant to be called publically, but included for mocking out in tests.
 *
 * @param gd
 * @param func
 * @param args
 */
queue.plotDo = function(gd, func, args) {
    gd.autoplay = true;

    // this *won't* copy gd and it preserves `undefined` properties!
    args = copyArgArray(gd, args);

    // call the supplied function
    func.apply(null, args);
};

module.exports = queue;

},{"../lib":694,"../plot_api/plot_config":730}],710:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/*
 * make a regex for matching counter ids/names ie xaxis, xaxis2, xaxis10...
 *
 * @param {string} head: the head of the pattern, eg 'x' matches 'x', 'x2', 'x10' etc.
 *      'xy' is a special case for cartesian subplots: it matches 'x2y3' etc
 * @param {Optional(string)} tail: a fixed piece after the id
 *      eg counterRegex('scene', '.annotations') for scene2.annotations etc.
 * @param {boolean} openEnded: if true, the string may continue past the match.
 * @param {boolean} matchBeginning: if false, the string may start before the match.
 */
exports.counter = function(head, tail, openEnded, matchBeginning) {
    var fullTail = (tail || '') + (openEnded ? '' : '$');
    var startWithPrefix = matchBeginning === false ? '' : '^';
    if(head === 'xy') {
        return new RegExp(startWithPrefix + 'x([2-9]|[1-9][0-9]+)?y([2-9]|[1-9][0-9]+)?' + fullTail);
    }
    return new RegExp(startWithPrefix + head + '([2-9]|[1-9][0-9]+)?' + fullTail);
};

},{}],711:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

// ASCEND: chop off the last nesting level - either [<n>] or .<key> - to ascend
// the attribute tree. the remaining attrString is in match[1]
var ASCEND = /^(.*)(\.[^\.\[\]]+|\[\d\])$/;

// SIMPLEATTR: is this an un-nested attribute? (no dots or brackets)
var SIMPLEATTR = /^[^\.\[\]]+$/;

/*
 * calculate a relative attribute string, similar to a relative path
 *
 * @param {string} baseAttr:
 *   an attribute string, such as 'annotations[3].x'. The "current location"
 *   is the attribute string minus the last component ('annotations[3]')
 * @param {string} relativeAttr:
 *   a route to the desired attribute string, using '^' to ascend
 *
 * @return {string} attrString:
 *   for example:
 *     relativeAttr('annotations[3].x', 'y') = 'annotations[3].y'
 *     relativeAttr('annotations[3].x', '^[2].z') = 'annotations[2].z'
 *     relativeAttr('annotations[3].x', '^^margin') = 'margin'
 *     relativeAttr('annotations[3].x', '^^margin.r') = 'margin.r'
 */
module.exports = function(baseAttr, relativeAttr) {
    while(relativeAttr) {
        var match = baseAttr.match(ASCEND);

        if(match) baseAttr = match[1];
        else if(baseAttr.match(SIMPLEATTR)) baseAttr = '';
        else throw new Error('bad relativeAttr call:' + [baseAttr, relativeAttr]);

        if(relativeAttr.charAt(0) === '^') relativeAttr = relativeAttr.slice(1);
        else break;
    }

    if(baseAttr && relativeAttr.charAt(0) !== '[') {
        return baseAttr + '.' + relativeAttr;
    }
    return baseAttr + relativeAttr;
};

},{}],712:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isArrayOrTypedArray = _dereq_('./array').isArrayOrTypedArray;
var isPlainObject = _dereq_('./is_plain_object');

/**
 * Relink private _keys and keys with a function value from one container
 * to the new container.
 * Relink means copying if object is pass-by-value and adding a reference
 * if object is pass-by-ref.
 * This prevents deepCopying massive structures like a webgl context.
 */
module.exports = function relinkPrivateKeys(toContainer, fromContainer) {
    for(var k in fromContainer) {
        var fromVal = fromContainer[k];
        var toVal = toContainer[k];

        if(toVal === fromVal) {
            continue;
        }
        if(k.charAt(0) === '_' || typeof fromVal === 'function') {

            // if it already exists at this point, it's something
            // that we recreate each time around, so ignore it
            if(k in toContainer) continue;

            toContainer[k] = fromVal;
        }
        else if(isArrayOrTypedArray(fromVal) && isArrayOrTypedArray(toVal) && isPlainObject(fromVal[0])) {

            // filter out data_array items that can contain user objects
            // most of the time the toVal === fromVal check will catch these early
            // but if the user makes new ones we also don't want to recurse in.
            if(k === 'customdata' || k === 'ids') continue;

            // recurse into arrays containers
            var minLen = Math.min(fromVal.length, toVal.length);
            for(var j = 0; j < minLen; j++) {
                if((toVal[j] !== fromVal[j]) && isPlainObject(fromVal[j]) && isPlainObject(toVal[j])) {
                    relinkPrivateKeys(toVal[j], fromVal[j]);
                }
            }
        }
        else if(isPlainObject(fromVal) && isPlainObject(toVal)) {

            // recurse into objects, but only if they still exist
            relinkPrivateKeys(toVal, fromVal);

            if(!Object.keys(toVal).length) delete toContainer[k];
        }
    }
};

},{"./array":677,"./is_plain_object":695}],713:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var loggers = _dereq_('./loggers');
var identity = _dereq_('./identity');

// don't trust floating point equality - fraction of bin size to call
// "on the line" and ensure that they go the right way specified by
// linelow
var roundingError = 1e-9;


/**
 * findBin - find the bin for val - note that it can return outside the
 * bin range any pos. or neg. integer for linear bins, or -1 or
 * bins.length-1 for explicit.
 * bins is either an object {start,size,end} or an array length #bins+1
 * bins can be either increasing or decreasing but must be monotonic
 * for linear bins, we can just calculate. For listed bins, run a binary
 * search linelow (truthy) says the bin boundary should be attributed to
 * the lower bin rather than the default upper bin
 */
exports.findBin = function(val, bins, linelow) {
    if(isNumeric(bins.start)) {
        return linelow ?
            Math.ceil((val - bins.start) / bins.size - roundingError) - 1 :
            Math.floor((val - bins.start) / bins.size + roundingError);
    }
    else {
        var n1 = 0;
        var n2 = bins.length;
        var c = 0;
        var binSize = (n2 > 1) ? (bins[n2 - 1] - bins[0]) / (n2 - 1) : 1;
        var n, test;
        if(binSize >= 0) {
            test = linelow ? lessThan : lessOrEqual;
        } else {
            test = linelow ? greaterOrEqual : greaterThan;
        }
        val += binSize * roundingError * (linelow ? -1 : 1) * (binSize >= 0 ? 1 : -1);
        // c is just to avoid infinite loops if there's an error
        while(n1 < n2 && c++ < 100) {
            n = Math.floor((n1 + n2) / 2);
            if(test(bins[n], val)) n1 = n + 1;
            else n2 = n;
        }
        if(c > 90) loggers.log('Long binary search...');
        return n1 - 1;
    }
};

function lessThan(a, b) { return a < b; }
function lessOrEqual(a, b) { return a <= b; }
function greaterThan(a, b) { return a > b; }
function greaterOrEqual(a, b) { return a >= b; }

exports.sorterAsc = function(a, b) { return a - b; };
exports.sorterDes = function(a, b) { return b - a; };

/**
 * find distinct values in an array, lumping together ones that appear to
 * just be off by a rounding error
 * return the distinct values and the minimum difference between any two
 */
exports.distinctVals = function(valsIn) {
    var vals = valsIn.slice();  // otherwise we sort the original array...
    vals.sort(exports.sorterAsc);

    var l = vals.length - 1;
    var minDiff = (vals[l] - vals[0]) || 1;
    var errDiff = minDiff / (l || 1) / 10000;
    var v2 = [vals[0]];

    for(var i = 0; i < l; i++) {
        // make sure values aren't just off by a rounding error
        if(vals[i + 1] > vals[i] + errDiff) {
            minDiff = Math.min(minDiff, vals[i + 1] - vals[i]);
            v2.push(vals[i + 1]);
        }
    }

    return {vals: v2, minDiff: minDiff};
};

/**
 * return the smallest element from (sorted) array arrayIn that's bigger than val,
 * or (reverse) the largest element smaller than val
 * used to find the best tick given the minimum (non-rounded) tick
 * particularly useful for date/time where things are not powers of 10
 * binary search is probably overkill here...
 */
exports.roundUp = function(val, arrayIn, reverse) {
    var low = 0;
    var high = arrayIn.length - 1;
    var mid;
    var c = 0;
    var dlow = reverse ? 0 : 1;
    var dhigh = reverse ? 1 : 0;
    var rounded = reverse ? Math.ceil : Math.floor;
    // c is just to avoid infinite loops if there's an error
    while(low < high && c++ < 100) {
        mid = rounded((low + high) / 2);
        if(arrayIn[mid] <= val) low = mid + dlow;
        else high = mid - dhigh;
    }
    return arrayIn[low];
};

/**
 * Tweak to Array.sort(sortFn) that improves performance for pre-sorted arrays
 *
 * Note that newer browsers (such as Chrome v70+) are starting to pick up
 * on pre-sorted arrays which may render the following optimization unnecessary
 * in the future.
 *
 * Motivation: sometimes we need to sort arrays but the input is likely to
 * already be sorted. Browsers don't seem to pick up on pre-sorted arrays,
 * and in fact Chrome is actually *slower* sorting pre-sorted arrays than purely
 * random arrays. FF is at least faster if the array is pre-sorted, but still
 * not as fast as it could be.
 * Here's how this plays out sorting a length-1e6 array:
 *
 * Calls to Sort FN  |  Chrome bare  |  FF bare  |  Chrome tweak  |  FF tweak
 *                   |  v68.0 Mac    |  v61.0 Mac|                |
 * ------------------+---------------+-----------+----------------+------------
 * ordered           |  30.4e6       |  10.1e6   |  1e6           |  1e6
 * reversed          |  29.4e6       |  9.9e6    |  1e6 + reverse |  1e6 + reverse
 * random            |  ~21e6        |  ~18.7e6  |  ~21e6         |  ~18.7e6
 *
 * So this is a substantial win for pre-sorted (ordered or exactly reversed)
 * arrays. Including this wrapper on an unsorted array adds a penalty that will
 * in general be only a few calls to the sort function. The only case this
 * penalty will be significant is if the array is mostly sorted but there are
 * a few unsorted items near the end, but the penalty is still at most N calls
 * out of (for N=1e6) ~20N total calls
 *
 * @param {Array} array: the array, to be sorted in place
 * @param {function} sortFn: As in Array.sort, function(a, b) that puts
 *     item a before item b if the return is negative, a after b if positive,
 *     and no change if zero.
 * @return {Array}: the original array, sorted in place.
 */
exports.sort = function(array, sortFn) {
    var notOrdered = 0;
    var notReversed = 0;
    for(var i = 1; i < array.length; i++) {
        var pairOrder = sortFn(array[i], array[i - 1]);
        if(pairOrder < 0) notOrdered = 1;
        else if(pairOrder > 0) notReversed = 1;
        if(notOrdered && notReversed) return array.sort(sortFn);
    }
    return notReversed ? array : array.reverse();
};

/**
 * find index in array 'arr' that minimizes 'fn'
 *
 * @param {array} arr : array where to search
 * @param {fn (optional)} fn : function to minimize,
 *   if not given, fn is the identity function
 * @return {integer}
 */
exports.findIndexOfMin = function(arr, fn) {
    fn = fn || identity;

    var min = Infinity;
    var ind;

    for(var i = 0; i < arr.length; i++) {
        var v = fn(arr[i]);
        if(v < min) {
            min = v;
            ind = i;
        }
    }
    return ind;
};

},{"./identity":693,"./loggers":698,"fast-isnumeric":215}],714:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

// works with our CSS cursor classes (see css/_cursor.scss)
// to apply cursors to d3 single-element selections.
// omit cursor to revert to the default.
module.exports = function setCursor(el3, csr) {
    (el3.attr('class') || '').split(' ').forEach(function(cls) {
        if(cls.indexOf('cursor-') === 0) el3.classed(cls, false);
    });

    if(csr) el3.classed('cursor-' + csr, true);
};

},{}],715:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Color = _dereq_('../components/color');

var noop = function() {};


/**
 * Prints a no webgl error message into the scene container
 * @param {scene instance} scene
 *
 * Expects 'scene' to have property 'container'
 *
 */
module.exports = function showNoWebGlMsg(scene) {
    for(var prop in scene) {
        if(typeof scene[prop] === 'function') scene[prop] = noop;
    }

    scene.destroy = function() {
        scene.container.parentNode.removeChild(scene.container);
    };

    var div = document.createElement('div');
    div.className = 'no-webgl';
    div.style.cursor = 'pointer';
    div.style.fontSize = '24px';
    div.style.color = Color.defaults[0];
    div.style.position = 'absolute';
    div.style.left = div.style.top = '0px';
    div.style.width = div.style.height = '100%';
    div.style['background-color'] = Color.lightLine;
    div.style['z-index'] = 30;

    var p = document.createElement('p');
    p.textContent = 'WebGL is not supported by your browser - visit https://get.webgl.org for more info';
    p.style.position = 'relative';
    p.style.top = '50%';
    p.style.left = '50%';
    p.style.height = '30%';
    p.style.width = '50%';
    p.style.margin = '-15% 0 0 -25%';

    div.appendChild(p);
    scene.container.appendChild(div);
    scene.container.style.background = '#FFFFFF';
    scene.container.onclick = function() {
        window.open('https://get.webgl.org');
    };

    // return before setting up camera and onrender methods
    return false;
};

},{"../components/color":571}],716:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var isArrayOrTypedArray = _dereq_('./array').isArrayOrTypedArray;

/**
 * aggNums() returns the result of an aggregate function applied to an array of
 * values, where non-numerical values have been tossed out.
 *
 * @param {function} f - aggregation function (e.g., Math.min)
 * @param {Number} v - initial value (continuing from previous calls)
 *      if there's no continuing value, use null for selector-type
 *      functions (max,min), or 0 for summations
 * @param {Array} a - array to aggregate (may be nested, we will recurse,
 *                    but all elements must have the same dimension)
 * @param {Number} len - maximum length of a to aggregate
 * @return {Number} - result of f applied to a starting from v
 */
exports.aggNums = function(f, v, a, len) {
    var i,
        b;
    if(!len || len > a.length) len = a.length;
    if(!isNumeric(v)) v = false;
    if(isArrayOrTypedArray(a[0])) {
        b = new Array(len);
        for(i = 0; i < len; i++) b[i] = exports.aggNums(f, v, a[i]);
        a = b;
    }

    for(i = 0; i < len; i++) {
        if(!isNumeric(v)) v = a[i];
        else if(isNumeric(a[i])) v = f(+v, +a[i]);
    }
    return v;
};

/**
 * mean & std dev functions using aggNums, so it handles non-numerics nicely
 * even need to use aggNums instead of .length, to toss out non-numerics
 */
exports.len = function(data) {
    return exports.aggNums(function(a) { return a + 1; }, 0, data);
};

exports.mean = function(data, len) {
    if(!len) len = exports.len(data);
    return exports.aggNums(function(a, b) { return a + b; }, 0, data) / len;
};

exports.midRange = function(numArr) {
    if(numArr === undefined || numArr.length === 0) return undefined;
    return (exports.aggNums(Math.max, null, numArr) + exports.aggNums(Math.min, null, numArr)) / 2;
};

exports.variance = function(data, len, mean) {
    if(!len) len = exports.len(data);
    if(!isNumeric(mean)) mean = exports.mean(data, len);

    return exports.aggNums(function(a, b) {
        return a + Math.pow(b - mean, 2);
    }, 0, data) / len;
};

exports.stdev = function(data, len, mean) {
    return Math.sqrt(exports.variance(data, len, mean));
};

/**
 * interp() computes a percentile (quantile) for a given distribution.
 * We interpolate the distribution (to compute quantiles, we follow method #10 here:
 * http://www.amstat.org/publications/jse/v14n3/langford.html).
 * Typically the index or rank (n * arr.length) may be non-integer.
 * For reference: ends are clipped to the extreme values in the array;
 * For box plots: index you get is half a point too high (see
 * http://en.wikipedia.org/wiki/Percentile#Nearest_rank) but note that this definition
 * indexes from 1 rather than 0, so we subtract 1/2 (instead of add).
 *
 * @param {Array} arr - This array contains the values that make up the distribution.
 * @param {Number} n - Between 0 and 1, n = p/100 is such that we compute the p^th percentile.
 * For example, the 50th percentile (or median) corresponds to n = 0.5
 * @return {Number} - percentile
 */
exports.interp = function(arr, n) {
    if(!isNumeric(n)) throw 'n should be a finite number';
    n = n * arr.length - 0.5;
    if(n < 0) return arr[0];
    if(n > arr.length - 1) return arr[arr.length - 1];
    var frac = n % 1;
    return frac * arr[Math.ceil(n)] + (1 - frac) * arr[Math.floor(n)];
};

},{"./array":677,"fast-isnumeric":215}],717:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var rgba = _dereq_('color-normalize');

function str2RgbaArray(color) {
    if(!color) return [0, 0, 0, 1];
    return rgba(color);
}

module.exports = str2RgbaArray;

},{"color-normalize":109}],718:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

/* global MathJax:false */

var d3 = _dereq_('d3');

var Lib = _dereq_('../lib');
var xmlnsNamespaces = _dereq_('../constants/xmlns_namespaces');
var LINE_SPACING = _dereq_('../constants/alignment').LINE_SPACING;

// text converter

function getSize(_selection, _dimension) {
    return _selection.node().getBoundingClientRect()[_dimension];
}

var FIND_TEX = /([^$]*)([$]+[^$]*[$]+)([^$]*)/;

exports.convertToTspans = function(_context, gd, _callback) {
    var str = _context.text();

    // Until we get tex integrated more fully (so it can be used along with non-tex)
    // allow some elements to prohibit it by attaching 'data-notex' to the original
    var tex = (!_context.attr('data-notex')) &&
        (typeof MathJax !== 'undefined') &&
        str.match(FIND_TEX);

    var parent = d3.select(_context.node().parentNode);
    if(parent.empty()) return;
    var svgClass = (_context.attr('class')) ? _context.attr('class').split(' ')[0] : 'text';
    svgClass += '-math';
    parent.selectAll('svg.' + svgClass).remove();
    parent.selectAll('g.' + svgClass + '-group').remove();
    _context.style('display', null)
        .attr({
            // some callers use data-unformatted *from the <text> element* in 'cancel'
            // so we need it here even if we're going to turn it into math
            // these two (plus style and text-anchor attributes) form the key we're
            // going to use for Drawing.bBox
            'data-unformatted': str,
            'data-math': 'N'
        });

    function showText() {
        if(!parent.empty()) {
            svgClass = _context.attr('class') + '-math';
            parent.select('svg.' + svgClass).remove();
        }
        _context.text('')
            .style('white-space', 'pre');

        var hasLink = buildSVGText(_context.node(), str);

        if(hasLink) {
            // at least in Chrome, pointer-events does not seem
            // to be honored in children of <text> elements
            // so if we have an anchor, we have to make the
            // whole element respond
            _context.style('pointer-events', 'all');
        }

        exports.positionText(_context);

        if(_callback) _callback.call(_context);
    }

    if(tex) {
        ((gd && gd._promises) || []).push(new Promise(function(resolve) {
            _context.style('display', 'none');
            var fontSize = parseInt(_context.node().style.fontSize, 10);
            var config = {fontSize: fontSize};

            texToSVG(tex[2], config, function(_svgEl, _glyphDefs, _svgBBox) {
                parent.selectAll('svg.' + svgClass).remove();
                parent.selectAll('g.' + svgClass + '-group').remove();

                var newSvg = _svgEl && _svgEl.select('svg');
                if(!newSvg || !newSvg.node()) {
                    showText();
                    resolve();
                    return;
                }

                var mathjaxGroup = parent.append('g')
                    .classed(svgClass + '-group', true)
                    .attr({
                        'pointer-events': 'none',
                        'data-unformatted': str,
                        'data-math': 'Y'
                    });

                mathjaxGroup.node().appendChild(newSvg.node());

                // stitch the glyph defs
                if(_glyphDefs && _glyphDefs.node()) {
                    newSvg.node().insertBefore(_glyphDefs.node().cloneNode(true),
                                               newSvg.node().firstChild);
                }

                newSvg.attr({
                    'class': svgClass,
                    height: _svgBBox.height,
                    preserveAspectRatio: 'xMinYMin meet'
                })
                .style({overflow: 'visible', 'pointer-events': 'none'});

                var fill = _context.node().style.fill || 'black';
                newSvg.select('g').attr({fill: fill, stroke: fill});

                var newSvgW = getSize(newSvg, 'width');
                var newSvgH = getSize(newSvg, 'height');
                var newX = +_context.attr('x') - newSvgW *
                    {start: 0, middle: 0.5, end: 1}[_context.attr('text-anchor') || 'start'];
                // font baseline is about 1/4 fontSize below centerline
                var textHeight = fontSize || getSize(_context, 'height');
                var dy = -textHeight / 4;

                if(svgClass[0] === 'y') {
                    mathjaxGroup.attr({
                        transform: 'rotate(' + [-90, +_context.attr('x'), +_context.attr('y')] +
                        ') translate(' + [-newSvgW / 2, dy - newSvgH / 2] + ')'
                    });
                    newSvg.attr({x: +_context.attr('x'), y: +_context.attr('y')});
                }
                else if(svgClass[0] === 'l') {
                    newSvg.attr({x: _context.attr('x'), y: dy - (newSvgH / 2)});
                }
                else if(svgClass[0] === 'a' && svgClass.indexOf('atitle') !== 0) {
                    newSvg.attr({x: 0, y: dy});
                }
                else {
                    newSvg.attr({x: newX, y: (+_context.attr('y') + dy - newSvgH / 2)});
                }

                if(_callback) _callback.call(_context, mathjaxGroup);
                resolve(mathjaxGroup);
            });
        }));
    }
    else showText();

    return _context;
};


// MathJax

var LT_MATCH = /(<|&lt;|&#60;)/g;
var GT_MATCH = /(>|&gt;|&#62;)/g;

function cleanEscapesForTex(s) {
    return s.replace(LT_MATCH, '\\lt ')
        .replace(GT_MATCH, '\\gt ');
}

function texToSVG(_texString, _config, _callback) {

    var originalRenderer,
        originalConfig,
        originalProcessSectionDelay,
        tmpDiv;

    MathJax.Hub.Queue(
    function() {
        originalConfig = Lib.extendDeepAll({}, MathJax.Hub.config);

        originalProcessSectionDelay = MathJax.Hub.processSectionDelay;
        if(MathJax.Hub.processSectionDelay !== undefined) {
            // MathJax 2.5+
            MathJax.Hub.processSectionDelay = 0;
        }

        return MathJax.Hub.Config({
            messageStyle: 'none',
            tex2jax: {
                inlineMath: [['$', '$'], ['\\(', '\\)']]
            },
            displayAlign: 'left',
        });
    },
    function() {
        // Get original renderer
        originalRenderer = MathJax.Hub.config.menuSettings.renderer;
        if(originalRenderer !== 'SVG') {
            return MathJax.Hub.setRenderer('SVG');
        }
    },
    function() {
        var randomID = 'math-output-' + Lib.randstr({}, 64);
        tmpDiv = d3.select('body').append('div')
            .attr({id: randomID})
            .style({visibility: 'hidden', position: 'absolute'})
            .style({'font-size': _config.fontSize + 'px'})
            .text(cleanEscapesForTex(_texString));

        return MathJax.Hub.Typeset(tmpDiv.node());
    },
    function() {
        var glyphDefs = d3.select('body').select('#MathJax_SVG_glyphs');

        if(tmpDiv.select('.MathJax_SVG').empty() || !tmpDiv.select('svg').node()) {
            Lib.log('There was an error in the tex syntax.', _texString);
            _callback();
        }
        else {
            var svgBBox = tmpDiv.select('svg').node().getBoundingClientRect();
            _callback(tmpDiv.select('.MathJax_SVG'), glyphDefs, svgBBox);
        }

        tmpDiv.remove();

        if(originalRenderer !== 'SVG') {
            return MathJax.Hub.setRenderer(originalRenderer);
        }
    },
    function() {
        if(originalProcessSectionDelay !== undefined) {
            MathJax.Hub.processSectionDelay = originalProcessSectionDelay;
        }
        return MathJax.Hub.Config(originalConfig);
    });
}

var TAG_STYLES = {
    // would like to use baseline-shift for sub/sup but FF doesn't support it
    // so we need to use dy along with the uber hacky shift-back-to
    // baseline below
    sup: 'font-size:70%',
    sub: 'font-size:70%',
    b: 'font-weight:bold',
    i: 'font-style:italic',
    a: 'cursor:pointer',
    span: '',
    em: 'font-style:italic;font-weight:bold'
};

// baseline shifts for sub and sup
var SHIFT_DY = {
    sub: '0.3em',
    sup: '-0.6em'
};
// reset baseline by adding a tspan (empty except for a zero-width space)
// with dy of -70% * SHIFT_DY (because font-size=70%)
var RESET_DY = {
    sub: '-0.21em',
    sup: '0.42em'
};
var ZERO_WIDTH_SPACE = '\u200b';

/*
 * Whitelist of protocols in user-supplied urls. Mostly we want to avoid javascript
 * and related attack vectors. The empty items are there for IE, that in various
 * versions treats relative paths as having different flavors of no protocol, while
 * other browsers have these explicitly inherit the protocol of the page they're in.
 */
var PROTOCOLS = ['http:', 'https:', 'mailto:', '', undefined, ':'];

var NEWLINES = /(\r\n?|\n)/g;

var SPLIT_TAGS = /(<[^<>]*>)/;

var ONE_TAG = /<(\/?)([^ >]*)(\s+(.*))?>/i;

var BR_TAG = /<br(\s+.*)?>/i;

/*
 * style and href: pull them out of either single or double quotes. Also
 * - target: (_blank|_self|_parent|_top|framename)
 *     note that you can't use target to get a popup but if you use popup,
 *     a `framename` will be passed along as the name of the popup window.
 *     per the spec, cannot contain whitespace.
 *     for backward compatibility we default to '_blank'
 * - popup: a custom one for us to enable popup (new window) links. String
 *     for window.open -> strWindowFeatures, like 'menubar=yes,width=500,height=550'
 *     note that at least in Chrome, you need to give at least one property
 *     in this string or the page will open in a new tab anyway. We follow this
 *     convention and will not make a popup if this string is empty.
 *     per the spec, cannot contain whitespace.
 *
 * Because we hack in other attributes with style (sub & sup), drop any trailing
 * semicolon in user-supplied styles so we can consistently append the tag-dependent style
 *
 * These are for tag attributes; Chrome anyway will convert entities in
 * attribute values, but not in attribute names
 * you can test this by for example:
 * > p = document.createElement('p')
 * > p.innerHTML = '<span styl&#x65;="font-color:r&#x65;d;">Hi</span>'
 * > p.innerHTML
 * <- '<span styl&#x65;="font-color:red;">Hi</span>'
 */
var STYLEMATCH = /(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i;
var HREFMATCH = /(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i;
var TARGETMATCH = /(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i;
var POPUPMATCH = /(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;

// dedicated matcher for these quoted regexes, that can return their results
// in two different places
function getQuotedMatch(_str, re) {
    if(!_str) return null;
    var match = _str.match(re);
    var result = match && (match[3] || match[4]);
    return result && convertEntities(result);
}

var COLORMATCH = /(^|;)\s*color:/;

/**
 * Strip string of tags
 *
 * @param {string} _str : input string
 * @param {object} opts :
 * - maxLen {number} max length of output string
 * - allowedTags {array} list of pseudo-html tags to NOT strip
 * @return {string}
 */
exports.plainText = function(_str, opts) {
    opts = opts || {};

    var len = (opts.len !== undefined && opts.len !== -1) ? opts.len : Infinity;
    var allowedTags = opts.allowedTags !== undefined ? opts.allowedTags : ['br'];

    var ellipsis = '...';
    var eLen = ellipsis.length;

    var oldParts = _str.split(SPLIT_TAGS);
    var newParts = [];
    var prevTag = '';
    var l = 0;

    for(var i = 0; i < oldParts.length; i++) {
        var p = oldParts[i];
        var match = p.match(ONE_TAG);
        var tagType = match && match[2].toLowerCase();

        if(tagType) {
            // N.B. tags do not count towards string length
            if(allowedTags.indexOf(tagType) !== -1) {
                newParts.push(p);
                prevTag = tagType;
            }
        } else {
            var pLen = p.length;

            if((l + pLen) < len) {
                newParts.push(p);
                l += pLen;
            } else if(l < len) {
                var pLen2 = len - l;

                if(prevTag && (prevTag !== 'br' || pLen2 <= eLen || pLen <= eLen)) {
                    newParts.pop();
                }

                if(len > eLen) {
                    newParts.push(p.substr(0, pLen2 - eLen) + ellipsis);
                } else {
                    newParts.push(p.substr(0, pLen2));
                }
                break;
            }

            prevTag = '';
        }
    }

    return newParts.join('');
};

/*
 * N.B. HTML entities are listed without the leading '&' and trailing ';'
 * https://www.freeformatter.com/html-entities.html
 *
 * FWIW if we wanted to support the full set, it has 2261 entries:
 * https://www.w3.org/TR/html5/entities.json
 * though I notice that some of these are duplicates and/or are missing ";"
 * eg: "&amp;", "&amp", "&AMP;", and "&AMP" all map to "&"
 * We no longer need to include numeric entities here, these are now handled
 * by String.fromCodePoint/fromCharCode
 *
 * Anyway the only ones that are really important to allow are the HTML special
 * chars <, >, and &, because these ones can trigger special processing if not
 * replaced by the corresponding entity.
 */
var entityToUnicode = {
    mu: 'μ',
    amp: '&',
    lt: '<',
    gt: '>',
    nbsp: ' ',
    times: '×',
    plusmn: '±',
    deg: '°'
};

// NOTE: in general entities can contain uppercase too (so [a-zA-Z]) but all the
// ones we support use only lowercase. If we ever change that, update the regex.
var ENTITY_MATCH = /&(#\d+|#x[\da-fA-F]+|[a-z]+);/g;
function convertEntities(_str) {
    return _str.replace(ENTITY_MATCH, function(fullMatch, innerMatch) {
        var outChar;
        if(innerMatch.charAt(0) === '#') {
            // cannot use String.fromCodePoint in IE
            outChar = fromCodePoint(
                innerMatch.charAt(1) === 'x' ?
                    parseInt(innerMatch.substr(2), 16) :
                    parseInt(innerMatch.substr(1), 10)
            );
        }
        else outChar = entityToUnicode[innerMatch];

        // as in regular HTML, if we didn't decode the entity just
        // leave the raw text in place.
        return outChar || fullMatch;
    });
}
exports.convertEntities = convertEntities;

function fromCodePoint(code) {
    // Don't allow overflow. In Chrome this turns into � but I feel like it's
    // more useful to just not convert it at all.
    if(code > 0x10FFFF) return;
    var stringFromCodePoint = String.fromCodePoint;
    if(stringFromCodePoint) return stringFromCodePoint(code);

    // IE doesn't have String.fromCodePoint
    // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint
    var stringFromCharCode = String.fromCharCode;
    if(code <= 0xFFFF) return stringFromCharCode(code);
    return stringFromCharCode(
        (code >> 10) + 0xD7C0,
        (code % 0x400) + 0xDC00
    );
}

/*
 * buildSVGText: convert our pseudo-html into SVG tspan elements, and attach these
 * to containerNode
 *
 * @param {svg text element} containerNode: the <text> node to insert this text into
 * @param {string} str: the pseudo-html string to convert to svg
 *
 * @returns {bool}: does the result contain any links? We need to handle the text element
 *   somewhat differently if it does, so just keep track of this when it happens.
 */
function buildSVGText(containerNode, str) {
    /*
     * Normalize behavior between IE and others wrt newlines and whitespace:pre
     * this combination makes IE barf https://github.com/plotly/plotly.js/issues/746
     * Chrome and FF display \n, \r, or \r\n as a space in this mode.
     * I feel like at some point we turned these into <br> but currently we don't so
     * I'm just going to cement what we do now in Chrome and FF
     */
    str = str.replace(NEWLINES, ' ');

    var hasLink = false;

    // as we're building the text, keep track of what elements we're nested inside
    // nodeStack will be an array of {node, type, style, href, target, popup}
    // where only type: 'a' gets the last 3 and node is only added when it's created
    var nodeStack = [];
    var currentNode;
    var currentLine = -1;

    function newLine() {
        currentLine++;

        var lineNode = document.createElementNS(xmlnsNamespaces.svg, 'tspan');
        d3.select(lineNode).attr({
            class: 'line',
            dy: (currentLine * LINE_SPACING) + 'em'
        });
        containerNode.appendChild(lineNode);

        currentNode = lineNode;

        var oldNodeStack = nodeStack;
        nodeStack = [{node: lineNode}];

        if(oldNodeStack.length > 1) {
            for(var i = 1; i < oldNodeStack.length; i++) {
                enterNode(oldNodeStack[i]);
            }
        }
    }

    function enterNode(nodeSpec) {
        var type = nodeSpec.type;
        var nodeAttrs = {};
        var nodeType;

        if(type === 'a') {
            nodeType = 'a';
            var target = nodeSpec.target;
            var href = nodeSpec.href;
            var popup = nodeSpec.popup;
            if(href) {
                nodeAttrs = {
                    'xlink:xlink:show': (target === '_blank' || target.charAt(0) !== '_') ? 'new' : 'replace',
                    target: target,
                    'xlink:xlink:href': href
                };
                if(popup) {
                    // security: href and target are not inserted as code but
                    // as attributes. popup is, but limited to /[A-Za-z0-9_=,]/
                    nodeAttrs.onclick = 'window.open(this.href.baseVal,this.target.baseVal,"' +
                        popup + '");return false;';
                }
            }
        }
        else nodeType = 'tspan';

        if(nodeSpec.style) nodeAttrs.style = nodeSpec.style;

        var newNode = document.createElementNS(xmlnsNamespaces.svg, nodeType);

        if(type === 'sup' || type === 'sub') {
            addTextNode(currentNode, ZERO_WIDTH_SPACE);
            currentNode.appendChild(newNode);

            var resetter = document.createElementNS(xmlnsNamespaces.svg, 'tspan');
            addTextNode(resetter, ZERO_WIDTH_SPACE);
            d3.select(resetter).attr('dy', RESET_DY[type]);
            nodeAttrs.dy = SHIFT_DY[type];

            currentNode.appendChild(newNode);
            currentNode.appendChild(resetter);
        }
        else {
            currentNode.appendChild(newNode);
        }

        d3.select(newNode).attr(nodeAttrs);

        currentNode = nodeSpec.node = newNode;
        nodeStack.push(nodeSpec);
    }

    function addTextNode(node, text) {
        node.appendChild(document.createTextNode(text));
    }

    function exitNode(type) {
        // A bare closing tag can't close the root node. If we encounter this it
        // means there's an extra closing tag that can just be ignored:
        if(nodeStack.length === 1) {
            Lib.log('Ignoring unexpected end tag </' + type + '>.', str);
            return;
        }

        var innerNode = nodeStack.pop();

        if(type !== innerNode.type) {
            Lib.log('Start tag <' + innerNode.type + '> doesnt match end tag <' +
                type + '>. Pretending it did match.', str);
        }
        currentNode = nodeStack[nodeStack.length - 1].node;
    }

    var hasLines = BR_TAG.test(str);

    if(hasLines) newLine();
    else {
        currentNode = containerNode;
        nodeStack = [{node: containerNode}];
    }

    var parts = str.split(SPLIT_TAGS);
    for(var i = 0; i < parts.length; i++) {
        var parti = parts[i];
        var match = parti.match(ONE_TAG);
        var tagType = match && match[2].toLowerCase();
        var tagStyle = TAG_STYLES[tagType];

        if(tagType === 'br') {
            newLine();
        }
        else if(tagStyle === undefined) {
            addTextNode(currentNode, convertEntities(parti));
        }
        else {
            // tag - open or close
            if(match[1]) {
                exitNode(tagType);
            }
            else {
                var extra = match[4];

                var nodeSpec = {type: tagType};

                // now add style, from both the tag name and any extra css
                // Most of the svg css that users will care about is just like html,
                // but font color is different (uses fill). Let our users ignore this.
                var css = getQuotedMatch(extra, STYLEMATCH);
                if(css) {
                    css = css.replace(COLORMATCH, '$1 fill:');
                    if(tagStyle) css += ';' + tagStyle;
                }
                else if(tagStyle) css = tagStyle;

                if(css) nodeSpec.style = css;

                if(tagType === 'a') {
                    hasLink = true;

                    var href = getQuotedMatch(extra, HREFMATCH);

                    if(href) {
                        // check safe protocols
                        var dummyAnchor = document.createElement('a');
                        dummyAnchor.href = href;
                        if(PROTOCOLS.indexOf(dummyAnchor.protocol) !== -1) {
                            // Decode href to allow both already encoded and not encoded
                            // URIs. Without decoding prior encoding, an already encoded
                            // URI would be encoded twice producing a semantically different URI.
                            nodeSpec.href = encodeURI(decodeURI(href));
                            nodeSpec.target = getQuotedMatch(extra, TARGETMATCH) || '_blank';
                            nodeSpec.popup = getQuotedMatch(extra, POPUPMATCH);
                        }
                    }
                }

                enterNode(nodeSpec);
            }
        }
    }

    return hasLink;
}

exports.lineCount = function lineCount(s) {
    return s.selectAll('tspan.line').size() || 1;
};

exports.positionText = function positionText(s, x, y) {
    return s.each(function() {
        var text = d3.select(this);

        function setOrGet(attr, val) {
            if(val === undefined) {
                val = text.attr(attr);
                if(val === null) {
                    text.attr(attr, 0);
                    val = 0;
                }
            }
            else text.attr(attr, val);
            return val;
        }

        var thisX = setOrGet('x', x);
        var thisY = setOrGet('y', y);

        if(this.nodeName === 'text') {
            text.selectAll('tspan.line').attr({x: thisX, y: thisY});
        }
    });
};

function alignHTMLWith(_base, container, options) {
    var alignH = options.horizontalAlign;
    var alignV = options.verticalAlign || 'top';
    var bRect = _base.node().getBoundingClientRect();
    var cRect = container.node().getBoundingClientRect();
    var thisRect;
    var getTop;
    var getLeft;

    if(alignV === 'bottom') {
        getTop = function() { return bRect.bottom - thisRect.height; };
    } else if(alignV === 'middle') {
        getTop = function() { return bRect.top + (bRect.height - thisRect.height) / 2; };
    } else { // default: top
        getTop = function() { return bRect.top; };
    }

    if(alignH === 'right') {
        getLeft = function() { return bRect.right - thisRect.width; };
    } else if(alignH === 'center') {
        getLeft = function() { return bRect.left + (bRect.width - thisRect.width) / 2; };
    } else { // default: left
        getLeft = function() { return bRect.left; };
    }

    return function() {
        thisRect = this.node().getBoundingClientRect();
        this.style({
            top: (getTop() - cRect.top) + 'px',
            left: (getLeft() - cRect.left) + 'px',
            'z-index': 1000
        });
        return this;
    };
}

/*
 * Editable title
 * @param {d3.selection} context: the element being edited. Normally text,
 *   but if it isn't, you should provide the styling options
 * @param {object} options:
 *   @param {div} options.gd: graphDiv
 *   @param {d3.selection} options.delegate: item to bind events to if not this
 *   @param {boolean} options.immediate: start editing now (true) or on click (false, default)
 *   @param {string} options.fill: font color if not as shown
 *   @param {string} options.background: background color if not as shown
 *   @param {string} options.text: initial text, if not as shown
 *   @param {string} options.horizontalAlign: alignment of the edit box wrt. the bound element
 *   @param {string} options.verticalAlign: alignment of the edit box wrt. the bound element
 */

exports.makeEditable = function(context, options) {
    var gd = options.gd;
    var _delegate = options.delegate;
    var dispatch = d3.dispatch('edit', 'input', 'cancel');
    var handlerElement = _delegate || context;

    context.style({'pointer-events': _delegate ? 'none' : 'all'});

    if(context.size() !== 1) throw new Error('boo');

    function handleClick() {
        appendEditable();
        context.style({opacity: 0});
        // also hide any mathjax svg
        var svgClass = handlerElement.attr('class');
        var mathjaxClass;
        if(svgClass) mathjaxClass = '.' + svgClass.split(' ')[0] + '-math-group';
        else mathjaxClass = '[class*=-math-group]';
        if(mathjaxClass) {
            d3.select(context.node().parentNode).select(mathjaxClass).style({opacity: 0});
        }
    }

    function selectElementContents(_el) {
        var el = _el.node();
        var range = document.createRange();
        range.selectNodeContents(el);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
        el.focus();
    }

    function appendEditable() {
        var plotDiv = d3.select(gd);
        var container = plotDiv.select('.svg-container');
        var div = container.append('div');
        var cStyle = context.node().style;
        var fontSize = parseFloat(cStyle.fontSize || 12);

        var initialText = options.text;
        if(initialText === undefined) initialText = context.attr('data-unformatted');

        div.classed('plugin-editable editable', true)
            .style({
                position: 'absolute',
                'font-family': cStyle.fontFamily || 'Arial',
                'font-size': fontSize,
                color: options.fill || cStyle.fill || 'black',
                opacity: 1,
                'background-color': options.background || 'transparent',
                outline: '#ffffff33 1px solid',
                margin: [-fontSize / 8 + 1, 0, 0, -1].join('px ') + 'px',
                padding: '0',
                'box-sizing': 'border-box'
            })
            .attr({contenteditable: true})
            .text(initialText)
            .call(alignHTMLWith(context, container, options))
            .on('blur', function() {
                gd._editing = false;
                context.text(this.textContent)
                    .style({opacity: 1});
                var svgClass = d3.select(this).attr('class');
                var mathjaxClass;
                if(svgClass) mathjaxClass = '.' + svgClass.split(' ')[0] + '-math-group';
                else mathjaxClass = '[class*=-math-group]';
                if(mathjaxClass) {
                    d3.select(context.node().parentNode).select(mathjaxClass).style({opacity: 0});
                }
                var text = this.textContent;
                d3.select(this).transition().duration(0).remove();
                d3.select(document).on('mouseup', null);
                dispatch.edit.call(context, text);
            })
            .on('focus', function() {
                var editDiv = this;
                gd._editing = true;
                d3.select(document).on('mouseup', function() {
                    if(d3.event.target === editDiv) return false;
                    if(document.activeElement === div.node()) div.node().blur();
                });
            })
            .on('keyup', function() {
                if(d3.event.which === 27) {
                    gd._editing = false;
                    context.style({opacity: 1});
                    d3.select(this)
                        .style({opacity: 0})
                        .on('blur', function() { return false; })
                        .transition().remove();
                    dispatch.cancel.call(context, this.textContent);
                }
                else {
                    dispatch.input.call(context, this.textContent);
                    d3.select(this).call(alignHTMLWith(context, container, options));
                }
            })
            .on('keydown', function() {
                if(d3.event.which === 13) this.blur();
            })
            .call(selectElementContents);
    }

    if(options.immediate) handleClick();
    else handlerElement.on('click', handleClick);

    return d3.rebind(context, dispatch, 'on');
};

},{"../constants/alignment":666,"../constants/xmlns_namespaces":672,"../lib":694,"d3":149}],719:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var timerCache = {};

/**
 * Throttle a callback. `callback` executes synchronously only if
 * more than `minInterval` milliseconds have already elapsed since the latest
 * call (if any). Otherwise we wait until `minInterval` is over and execute the
 * last callback received while waiting.
 * So the first and last events in a train are always executed (eventually)
 * but some of the events in the middle can be dropped.
 *
 * @param {string} id: an identifier to mark events to throttle together
 * @param {number} minInterval: minimum time, in milliseconds, between
 *   invocations of `callback`
 * @param {function} callback: the function to throttle. `callback` itself
 *   should be a purely synchronous function.
 */
exports.throttle = function throttle(id, minInterval, callback) {
    var cache = timerCache[id];
    var now = Date.now();

    if(!cache) {
        /*
         * Throw out old items before making a new one, to prevent the cache
         * getting overgrown, for example from old plots that have been replaced.
         * 1 minute age is arbitrary.
         */
        for(var idi in timerCache) {
            if(timerCache[idi].ts < now - 60000) {
                delete timerCache[idi];
            }
        }
        cache = timerCache[id] = {ts: 0, timer: null};
    }

    _clearTimeout(cache);

    function exec() {
        callback();
        cache.ts = Date.now();
        if(cache.onDone) {
            cache.onDone();
            cache.onDone = null;
        }
    }

    if(now > cache.ts + minInterval) {
        exec();
        return;
    }

    cache.timer = setTimeout(function() {
        exec();
        cache.timer = null;
    }, minInterval);
};

exports.done = function(id) {
    var cache = timerCache[id];
    if(!cache || !cache.timer) return Promise.resolve();

    return new Promise(function(resolve) {
        var previousOnDone = cache.onDone;
        cache.onDone = function onDone() {
            if(previousOnDone) previousOnDone();
            resolve();
            cache.onDone = null;
        };
    });
};

/**
 * Clear the throttle cache for one or all timers
 * @param {optional string} id:
 *   if provided, clear just this timer
 *   if omitted, clear all timers (mainly useful for testing)
 */
exports.clear = function(id) {
    if(id) {
        _clearTimeout(timerCache[id]);
        delete timerCache[id];
    }
    else {
        for(var idi in timerCache) exports.clear(idi);
    }
};

function _clearTimeout(cache) {
    if(cache && cache.timer !== null) {
        clearTimeout(cache.timer);
        cache.timer = null;
    }
}

},{}],720:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');

/**
 * convert a linear value into a logged value, folding negative numbers into
 * the given range
 */
module.exports = function toLogRange(val, range) {
    if(val > 0) return Math.log(val) / Math.LN10;

    // move a negative value reference to a log axis - just put the
    // result at the lowest range value on the plot (or if the range also went negative,
    // one millionth of the top of the range)
    var newVal = Math.log(Math.min(range[0], range[1])) / Math.LN10;
    if(!isNumeric(newVal)) newVal = Math.log(Math.max(range[0], range[1])) / Math.LN10 - 6;
    return newVal;
};

},{"fast-isnumeric":215}],721:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var topojsonUtils = module.exports = {};

var locationmodeToLayer = _dereq_('../plots/geo/constants').locationmodeToLayer;
var topojsonFeature = _dereq_('topojson-client').feature;

topojsonUtils.getTopojsonName = function(geoLayout) {
    return [
        geoLayout.scope.replace(/ /g, '-'), '_',
        geoLayout.resolution.toString(), 'm'
    ].join('');
};

topojsonUtils.getTopojsonPath = function(topojsonURL, topojsonName) {
    return topojsonURL + topojsonName + '.json';
};

topojsonUtils.getTopojsonFeatures = function(trace, topojson) {
    var layer = locationmodeToLayer[trace.locationmode];
    var obj = topojson.objects[layer];

    return topojsonFeature(topojson, obj).features;
};

},{"../plots/geo/constants":771,"topojson-client":518}],722:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'locale',
    name: 'en-US',
    dictionary: {
        'Click to enter Colorscale title': 'Click to enter Colorscale title'
    },
    format: {
        date: '%m/%d/%Y'
    }
};

},{}],723:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'locale',
    name: 'en',
    dictionary: {
        'Click to enter Colorscale title': 'Click to enter Colourscale title'
    },
    format: {
        days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
        shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
        months: [
            'January', 'February', 'March', 'April', 'May', 'June',
            'July', 'August', 'September', 'October', 'November', 'December'
        ],
        shortMonths: [
            'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
        ],
        periods: ['AM', 'PM'],
        dateTime: '%a %b %e %X %Y',
        date: '%d/%m/%Y',
        time: '%H:%M:%S',
        decimal: '.',
        thousands: ',',
        grouping: [3],
        currency: ['$', ''],
        year: '%Y',
        month: '%b %Y',
        dayMonth: '%b %-d',
        dayMonthYear: '%b %-d, %Y'
    }
};

},{}],724:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../registry');

/*
 * containerArrayMatch: does this attribute string point into a
 * layout container array?
 *
 * @param {String} astr: an attribute string, like *annotations[2].text*
 *
 * @returns {Object | false} Returns false if `astr` doesn't match a container
 *  array. If it does, returns:
 *     {array: {String}, index: {Number}, property: {String}}
 *  ie the attribute string for the array, the index within the array (or ''
 *  if the whole array) and the property within that (or '' if the whole array
 *  or the whole object)
 */
module.exports = function containerArrayMatch(astr) {
    var rootContainers = Registry.layoutArrayContainers;
    var regexpContainers = Registry.layoutArrayRegexes;
    var rootPart = astr.split('[')[0];
    var arrayStr;
    var match;

    // look for regexp matches first, because they may be nested inside root matches
    // eg updatemenus[i].buttons is nested inside updatemenus
    for(var i = 0; i < regexpContainers.length; i++) {
        match = astr.match(regexpContainers[i]);
        if(match && match.index === 0) {
            arrayStr = match[0];
            break;
        }
    }

    // now look for root matches
    if(!arrayStr) arrayStr = rootContainers[rootContainers.indexOf(rootPart)];

    if(!arrayStr) return false;

    var tail = astr.substr(arrayStr.length);
    if(!tail) return {array: arrayStr, index: '', property: ''};

    match = tail.match(/^\[(0|[1-9][0-9]*)\](\.(.+))?$/);
    if(!match) return false;

    return {array: arrayStr, index: Number(match[1]), property: match[3] || ''};
};

},{"../registry":825}],725:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../lib');
var extendFlat = Lib.extendFlat;
var isPlainObject = Lib.isPlainObject;

var traceOpts = {
    valType: 'flaglist',
    extras: ['none'],
    flags: ['calc', 'clearAxisTypes', 'plot', 'style', 'markerSize', 'colorbars'],
    
};

var layoutOpts = {
    valType: 'flaglist',
    extras: ['none'],
    flags: [
        'calc', 'plot', 'legend', 'ticks', 'axrange',
        'layoutstyle', 'modebar', 'camera', 'arraydraw'
    ],
    
};

// flags for inside restyle/relayout include a few extras
// that shouldn't be used in attributes, to deal with certain
// combinations and conditionals efficiently
var traceEditTypeFlags = traceOpts.flags.slice()
    .concat(['fullReplot']);

var layoutEditTypeFlags = layoutOpts.flags.slice()
    .concat('layoutReplot');

module.exports = {
    traces: traceOpts,
    layout: layoutOpts,
    /*
     * default (all false) edit flags for restyle (traces)
     * creates a new object each call, so the caller can mutate freely
     */
    traceFlags: function() { return falseObj(traceEditTypeFlags); },

    /*
     * default (all false) edit flags for relayout
     * creates a new object each call, so the caller can mutate freely
     */
    layoutFlags: function() { return falseObj(layoutEditTypeFlags); },

    /*
     * update `flags` with the `editType` values found in `attr`
     */
    update: function(flags, attr) {
        var editType = attr.editType;
        if(editType && editType !== 'none') {
            var editTypeParts = editType.split('+');
            for(var i = 0; i < editTypeParts.length; i++) {
                flags[editTypeParts[i]] = true;
            }
        }
    },

    overrideAll: overrideAll
};

function falseObj(keys) {
    var out = {};
    for(var i = 0; i < keys.length; i++) out[keys[i]] = false;
    return out;
}

/**
 * For attributes that are largely copied from elsewhere into a plot type that doesn't
 * support partial redraws - overrides the editType field of all attributes in the object
 *
 * @param {object} attrs: the attributes to override. Will not be mutated.
 * @param {string} editTypeOverride: the new editType to use
 * @param {'nested'|'from-root'} overrideContainers:
 *   - 'nested' will override editType for nested containers but not the root.
 *   - 'from-root' will also override editType of the root container.
 *   Containers below the absolute top level (trace or layout root) DO need an
 *   editType even if they are not `valObject`s themselves (eg `scatter.marker`)
 *   to handle the case where you edit the whole container.
 *
 * @return {object} a new attributes object with `editType` modified as directed
 */
function overrideAll(attrs, editTypeOverride, overrideContainers) {
    var out = extendFlat({}, attrs);
    for(var key in out) {
        var attr = out[key];
        if(isPlainObject(attr)) {
            out[key] = overrideOne(attr, editTypeOverride, overrideContainers, key);
        }
    }
    if(overrideContainers === 'from-root') out.editType = editTypeOverride;

    return out;
}

function overrideOne(attr, editTypeOverride, overrideContainers, key) {
    if(attr.valType) {
        var out = extendFlat({}, attr);
        out.editType = editTypeOverride;

        if(Array.isArray(attr.items)) {
            out.items = new Array(attr.items.length);
            for(var i = 0; i < attr.items.length; i++) {
                out.items[i] = overrideOne(attr.items[i], editTypeOverride, 'from-root');
            }
        }
        return out;
    }
    else {
        // don't provide an editType for the _deprecated container
        return overrideAll(attr, editTypeOverride,
            (key.charAt(0) === '_') ? 'nested' : 'from-root');
    }
}

},{"../lib":694}],726:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var m4FromQuat = _dereq_('gl-mat4/fromQuat');

var Registry = _dereq_('../registry');
var Lib = _dereq_('../lib');
var Plots = _dereq_('../plots/plots');
var AxisIds = _dereq_('../plots/cartesian/axis_ids');
var cleanId = AxisIds.cleanId;
var getFromTrace = AxisIds.getFromTrace;
var Color = _dereq_('../components/color');


// clear the promise queue if one of them got rejected
exports.clearPromiseQueue = function(gd) {
    if(Array.isArray(gd._promises) && gd._promises.length > 0) {
        Lib.log('Clearing previous rejected promises from queue.');
    }

    gd._promises = [];
};

// make a few changes to the layout right away
// before it gets used for anything
// backward compatibility and cleanup of nonstandard options
exports.cleanLayout = function(layout) {
    var i, j;

    if(!layout) layout = {};

    // cannot have (x|y)axis1, numbering goes axis, axis2, axis3...
    if(layout.xaxis1) {
        if(!layout.xaxis) layout.xaxis = layout.xaxis1;
        delete layout.xaxis1;
    }
    if(layout.yaxis1) {
        if(!layout.yaxis) layout.yaxis = layout.yaxis1;
        delete layout.yaxis1;
    }
    if(layout.scene1) {
        if(!layout.scene) layout.scene = layout.scene1;
        delete layout.scene1;
    }

    var axisAttrRegex = (Plots.subplotsRegistry.cartesian || {}).attrRegex;
    var polarAttrRegex = (Plots.subplotsRegistry.polar || {}).attrRegex;
    var ternaryAttrRegex = (Plots.subplotsRegistry.ternary || {}).attrRegex;
    var sceneAttrRegex = (Plots.subplotsRegistry.gl3d || {}).attrRegex;

    var keys = Object.keys(layout);
    for(i = 0; i < keys.length; i++) {
        var key = keys[i];

        // modifications to cartesian axes
        if(axisAttrRegex && axisAttrRegex.test(key)) {
            var ax = layout[key];
            if(ax.anchor && ax.anchor !== 'free') {
                ax.anchor = cleanId(ax.anchor);
            }
            if(ax.overlaying) ax.overlaying = cleanId(ax.overlaying);

            // old method of axis type - isdate and islog (before category existed)
            if(!ax.type) {
                if(ax.isdate) ax.type = 'date';
                else if(ax.islog) ax.type = 'log';
                else if(ax.isdate === false && ax.islog === false) ax.type = 'linear';
            }
            if(ax.autorange === 'withzero' || ax.autorange === 'tozero') {
                ax.autorange = true;
                ax.rangemode = 'tozero';
            }
            delete ax.islog;
            delete ax.isdate;
            delete ax.categories; // replaced by _categories

            // prune empty domain arrays made before the new nestedProperty
            if(emptyContainer(ax, 'domain')) delete ax.domain;

            // autotick -> tickmode
            if(ax.autotick !== undefined) {
                if(ax.tickmode === undefined) {
                    ax.tickmode = ax.autotick ? 'auto' : 'linear';
                }
                delete ax.autotick;
            }

            cleanTitle(ax);
        }

        // modifications for polar
        else if(polarAttrRegex && polarAttrRegex.test(key)) {
            var polar = layout[key];

            cleanTitle(polar.radialaxis);
        }

        // modifications for ternary
        else if(ternaryAttrRegex && ternaryAttrRegex.test(key)) {
            var ternary = layout[key];

            cleanTitle(ternary.aaxis);
            cleanTitle(ternary.baxis);
            cleanTitle(ternary.caxis);
        }

        // modifications for 3D scenes
        else if(sceneAttrRegex && sceneAttrRegex.test(key)) {
            var scene = layout[key];

            // clean old Camera coords
            var cameraposition = scene.cameraposition;

            if(Array.isArray(cameraposition) && cameraposition[0].length === 4) {
                var rotation = cameraposition[0];
                var center = cameraposition[1];
                var radius = cameraposition[2];
                var mat = m4FromQuat([], rotation);
                var eye = [];

                for(j = 0; j < 3; ++j) {
                    eye[j] = center[j] + radius * mat[2 + 4 * j];
                }

                scene.camera = {
                    eye: {x: eye[0], y: eye[1], z: eye[2]},
                    center: {x: center[0], y: center[1], z: center[2]},
                    up: {x: 0, y: 0, z: 1} // we just ignore calculating camera z up in this case
                };

                delete scene.cameraposition;
            }

            // clean axis titles
            cleanTitle(scene.xaxis);
            cleanTitle(scene.yaxis);
            cleanTitle(scene.zaxis);
        }
    }

    var annotationsLen = Array.isArray(layout.annotations) ? layout.annotations.length : 0;
    for(i = 0; i < annotationsLen; i++) {
        var ann = layout.annotations[i];

        if(!Lib.isPlainObject(ann)) continue;

        if(ann.ref) {
            if(ann.ref === 'paper') {
                ann.xref = 'paper';
                ann.yref = 'paper';
            }
            else if(ann.ref === 'data') {
                ann.xref = 'x';
                ann.yref = 'y';
            }
            delete ann.ref;
        }

        cleanAxRef(ann, 'xref');
        cleanAxRef(ann, 'yref');
    }

    var shapesLen = Array.isArray(layout.shapes) ? layout.shapes.length : 0;
    for(i = 0; i < shapesLen; i++) {
        var shape = layout.shapes[i];

        if(!Lib.isPlainObject(shape)) continue;

        cleanAxRef(shape, 'xref');
        cleanAxRef(shape, 'yref');
    }

    var legend = layout.legend;
    if(legend) {
        // check for old-style legend positioning (x or y is +/- 100)
        if(legend.x > 3) {
            legend.x = 1.02;
            legend.xanchor = 'left';
        }
        else if(legend.x < -2) {
            legend.x = -0.02;
            legend.xanchor = 'right';
        }

        if(legend.y > 3) {
            legend.y = 1.02;
            legend.yanchor = 'bottom';
        }
        else if(legend.y < -2) {
            legend.y = -0.02;
            legend.yanchor = 'top';
        }
    }

    // clean plot title
    cleanTitle(layout);

    /*
     * Moved from rotate -> orbit for dragmode
     */
    if(layout.dragmode === 'rotate') layout.dragmode = 'orbit';

    // sanitize rgb(fractions) and rgba(fractions) that old tinycolor
    // supported, but new tinycolor does not because they're not valid css
    Color.clean(layout);

    // clean the layout container in layout.template
    if(layout.template && layout.template.layout) {
        exports.cleanLayout(layout.template.layout);
    }

    return layout;
};

function cleanAxRef(container, attr) {
    var valIn = container[attr];
    var axLetter = attr.charAt(0);
    if(valIn && valIn !== 'paper') {
        container[attr] = cleanId(valIn, axLetter);
    }
}

/**
 * Cleans up old title attribute structure (flat) in favor of the new one (nested).
 *
 * @param {Object} titleContainer - an object potentially including deprecated title attributes
 */
function cleanTitle(titleContainer) {
    if(titleContainer) {

        // title -> title.text
        // (although title used to be a string attribute,
        // numbers are accepted as well)
        if(typeof titleContainer.title === 'string' || typeof titleContainer.title === 'number') {
            titleContainer.title = {
                text: titleContainer.title
            };
        }

        rewireAttr('titlefont', 'font');
        rewireAttr('titleposition', 'position');
        rewireAttr('titleside', 'side');
        rewireAttr('titleoffset', 'offset');
    }

    function rewireAttr(oldAttrName, newAttrName) {
        var oldAttrSet = titleContainer[oldAttrName];
        var newAttrSet = titleContainer.title && titleContainer.title[newAttrName];

        if(oldAttrSet && !newAttrSet) {

            // Ensure title object exists
            if(!titleContainer.title) {
                titleContainer.title = {};
            }

            titleContainer.title[newAttrName] = titleContainer[oldAttrName];
            delete titleContainer[oldAttrName];
        }
    }
}

/*
 * cleanData: Make a few changes to the data for backward compatibility
 * before it gets used for anything. Modifies the data traces users provide.
 *
 * Important: if you're going to add something here that modifies a data array,
 * update it in place so the new array === the old one.
 */
exports.cleanData = function(data) {
    for(var tracei = 0; tracei < data.length; tracei++) {
        var trace = data[tracei];
        var i;

        // use xbins to bin data in x, and ybins to bin data in y
        if(trace.type === 'histogramy' && 'xbins' in trace && !('ybins' in trace)) {
            trace.ybins = trace.xbins;
            delete trace.xbins;
        }

        // error_y.opacity is obsolete - merge into color
        if(trace.error_y && 'opacity' in trace.error_y) {
            var dc = Color.defaults;
            var yeColor = trace.error_y.color || (Registry.traceIs(trace, 'bar') ?
                Color.defaultLine :
                dc[tracei % dc.length]);
            trace.error_y.color = Color.addOpacity(
                Color.rgb(yeColor),
                Color.opacity(yeColor) * trace.error_y.opacity);
            delete trace.error_y.opacity;
        }

        // convert bardir to orientation, and put the data into
        // the axes it's eventually going to be used with
        if('bardir' in trace) {
            if(trace.bardir === 'h' && (Registry.traceIs(trace, 'bar') ||
                     trace.type.substr(0, 9) === 'histogram')) {
                trace.orientation = 'h';
                exports.swapXYData(trace);
            }
            delete trace.bardir;
        }

        // now we have only one 1D histogram type, and whether
        // it uses x or y data depends on trace.orientation
        if(trace.type === 'histogramy') exports.swapXYData(trace);
        if(trace.type === 'histogramx' || trace.type === 'histogramy') {
            trace.type = 'histogram';
        }

        // scl->scale, reversescl->reversescale
        if('scl' in trace && !('colorscale' in trace)) {
            trace.colorscale = trace.scl;
            delete trace.scl;
        }
        if('reversescl' in trace && !('reversescale' in trace)) {
            trace.reversescale = trace.reversescl;
            delete trace.reversescl;
        }

        // axis ids x1 -> x, y1-> y
        if(trace.xaxis) trace.xaxis = cleanId(trace.xaxis, 'x');
        if(trace.yaxis) trace.yaxis = cleanId(trace.yaxis, 'y');

        // scene ids scene1 -> scene
        if(Registry.traceIs(trace, 'gl3d') && trace.scene) {
            trace.scene = Plots.subplotsRegistry.gl3d.cleanId(trace.scene);
        }

        if(!Registry.traceIs(trace, 'pie') && !Registry.traceIs(trace, 'bar')) {
            if(Array.isArray(trace.textposition)) {
                for(i = 0; i < trace.textposition.length; i++) {
                    trace.textposition[i] = cleanTextPosition(trace.textposition[i]);
                }
            }
            else if(trace.textposition) {
                trace.textposition = cleanTextPosition(trace.textposition);
            }
        }

        // fix typo in colorscale definition
        var _module = Registry.getModule(trace);
        if(_module && _module.colorbar) {
            var containerName = _module.colorbar.container;
            var container = containerName ? trace[containerName] : trace;
            if(container && container.colorscale) {
                if(container.colorscale === 'YIGnBu') container.colorscale = 'YlGnBu';
                if(container.colorscale === 'YIOrRd') container.colorscale = 'YlOrRd';
            }
        }

        // fix typo in surface 'highlight*' definitions
        if(trace.type === 'surface' && Lib.isPlainObject(trace.contours)) {
            var dims = ['x', 'y', 'z'];

            for(i = 0; i < dims.length; i++) {
                var opts = trace.contours[dims[i]];

                if(!Lib.isPlainObject(opts)) continue;

                if(opts.highlightColor) {
                    opts.highlightcolor = opts.highlightColor;
                    delete opts.highlightColor;
                }

                if(opts.highlightWidth) {
                    opts.highlightwidth = opts.highlightWidth;
                    delete opts.highlightWidth;
                }
            }
        }

        // fixes from converting finance from transforms to real trace types
        if(trace.type === 'candlestick' || trace.type === 'ohlc') {
            var increasingShowlegend = (trace.increasing || {}).showlegend !== false;
            var decreasingShowlegend = (trace.decreasing || {}).showlegend !== false;
            var increasingName = cleanFinanceDir(trace.increasing);
            var decreasingName = cleanFinanceDir(trace.decreasing);

            // now figure out something smart to do with the separate direction
            // names we removed
            if((increasingName !== false) && (decreasingName !== false)) {
                // both sub-names existed: base name previously had no effect
                // so ignore it and try to find a shared part of the sub-names

                var newName = commonPrefix(
                    increasingName, decreasingName,
                    increasingShowlegend, decreasingShowlegend
                );
                // if no common part, leave whatever name was (or wasn't) there
                if(newName) trace.name = newName;
            }
            else if((increasingName || decreasingName) && !trace.name) {
                // one sub-name existed but not the base name - just use the sub-name
                trace.name = increasingName || decreasingName;
            }
        }

        // transforms backward compatibility fixes
        if(Array.isArray(trace.transforms)) {
            var transforms = trace.transforms;

            for(i = 0; i < transforms.length; i++) {
                var transform = transforms[i];

                if(!Lib.isPlainObject(transform)) continue;

                switch(transform.type) {
                    case 'filter':
                        if(transform.filtersrc) {
                            transform.target = transform.filtersrc;
                            delete transform.filtersrc;
                        }

                        if(transform.calendar) {
                            if(!transform.valuecalendar) {
                                transform.valuecalendar = transform.calendar;
                            }
                            delete transform.calendar;
                        }
                        break;

                    case 'groupby':
                        // Name has changed from `style` to `styles`, so use `style` but prefer `styles`:
                        transform.styles = transform.styles || transform.style;

                        if(transform.styles && !Array.isArray(transform.styles)) {
                            var prevStyles = transform.styles;
                            var styleKeys = Object.keys(prevStyles);

                            transform.styles = [];
                            for(var j = 0; j < styleKeys.length; j++) {
                                transform.styles.push({
                                    target: styleKeys[j],
                                    value: prevStyles[styleKeys[j]]
                                });
                            }
                        }
                        break;
                }
            }
        }

        // prune empty containers made before the new nestedProperty
        if(emptyContainer(trace, 'line')) delete trace.line;
        if('marker' in trace) {
            if(emptyContainer(trace.marker, 'line')) delete trace.marker.line;
            if(emptyContainer(trace, 'marker')) delete trace.marker;
        }

        // sanitize rgb(fractions) and rgba(fractions) that old tinycolor
        // supported, but new tinycolor does not because they're not valid css
        Color.clean(trace);

        // remove obsolete autobin(x|y) attributes, but only if true
        // if false, this needs to happen in Histogram.calc because it
        // can be a one-time autobin so we need to know the results before
        // we can push them back into the trace.
        if(trace.autobinx) {
            delete trace.autobinx;
            delete trace.xbins;
        }
        if(trace.autobiny) {
            delete trace.autobiny;
            delete trace.ybins;
        }

        cleanTitle(trace);
        if(trace.colorbar) cleanTitle(trace.colorbar);
        if(trace.marker && trace.marker.colorbar) cleanTitle(trace.marker.colorbar);
        if(trace.line && trace.line.colorbar) cleanTitle(trace.line.colorbar);
        if(trace.aaxis) cleanTitle(trace.aaxis);
        if(trace.baxis) cleanTitle(trace.baxis);
    }
};

function cleanFinanceDir(dirContainer) {
    if(!Lib.isPlainObject(dirContainer)) return false;

    var dirName = dirContainer.name;

    delete dirContainer.name;
    delete dirContainer.showlegend;

    return (typeof dirName === 'string' || typeof dirName === 'number') && String(dirName);
}

function commonPrefix(name1, name2, show1, show2) {
    // if only one is shown in the legend, use that
    if(show1 && !show2) return name1;
    if(show2 && !show1) return name2;

    // if both or neither are in the legend, check if one is blank (or whitespace)
    // and use the other one
    // note that hover labels can still use the name even if the legend doesn't
    if(!name1.trim()) return name2;
    if(!name2.trim()) return name1;

    var minLen = Math.min(name1.length, name2.length);
    var i;
    for(i = 0; i < minLen; i++) {
        if(name1.charAt(i) !== name2.charAt(i)) break;
    }

    var out = name1.substr(0, i);
    return out.trim();
}

// textposition - support partial attributes (ie just 'top')
// and incorrect use of middle / center etc.
function cleanTextPosition(textposition) {
    var posY = 'middle';
    var posX = 'center';

    if(typeof textposition === 'string') {
        if(textposition.indexOf('top') !== -1) posY = 'top';
        else if(textposition.indexOf('bottom') !== -1) posY = 'bottom';

        if(textposition.indexOf('left') !== -1) posX = 'left';
        else if(textposition.indexOf('right') !== -1) posX = 'right';
    }

    return posY + ' ' + posX;
}

function emptyContainer(outer, innerStr) {
    return (innerStr in outer) &&
        (typeof outer[innerStr] === 'object') &&
        (Object.keys(outer[innerStr]).length === 0);
}


// swap all the data and data attributes associated with x and y
exports.swapXYData = function(trace) {
    var i;
    Lib.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']);
    if(Array.isArray(trace.z) && Array.isArray(trace.z[0])) {
        if(trace.transpose) delete trace.transpose;
        else trace.transpose = true;
    }
    if(trace.error_x && trace.error_y) {
        var errorY = trace.error_y;
        var copyYstyle = ('copy_ystyle' in errorY) ?
            errorY.copy_ystyle :
            !(errorY.color || errorY.thickness || errorY.width);
        Lib.swapAttrs(trace, ['error_?.copy_ystyle']);
        if(copyYstyle) {
            Lib.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']);
        }
    }
    if(typeof trace.hoverinfo === 'string') {
        var hoverInfoParts = trace.hoverinfo.split('+');
        for(i = 0; i < hoverInfoParts.length; i++) {
            if(hoverInfoParts[i] === 'x') hoverInfoParts[i] = 'y';
            else if(hoverInfoParts[i] === 'y') hoverInfoParts[i] = 'x';
        }
        trace.hoverinfo = hoverInfoParts.join('+');
    }
};

// coerce traceIndices input to array of trace indices
exports.coerceTraceIndices = function(gd, traceIndices) {
    if(isNumeric(traceIndices)) {
        return [traceIndices];
    }
    else if(!Array.isArray(traceIndices) || !traceIndices.length) {
        return gd.data.map(function(_, i) { return i; });
    }
    else if(Array.isArray(traceIndices)) {
        var traceIndicesOut = [];
        for(var i = 0; i < traceIndices.length; i++) {
            if(Lib.isIndex(traceIndices[i], gd.data.length)) {
                traceIndicesOut.push(traceIndices[i]);
            } else {
                Lib.warn('trace index (', traceIndices[i], ') is not a number or is out of bounds');
            }
        }
        return traceIndicesOut;
    }

    return traceIndices;
};

/**
 * Manages logic around array container item creation / deletion / update
 * that nested property alone can't handle.
 *
 * @param {Object} np
 *  nested property of update attribute string about trace or layout object
 * @param {*} newVal
 *  update value passed to restyle / relayout / update
 * @param {Object} undoit
 *  undo hash (N.B. undoit may be mutated here).
 *
 */
exports.manageArrayContainers = function(np, newVal, undoit) {
    var obj = np.obj;
    var parts = np.parts;
    var pLength = parts.length;
    var pLast = parts[pLength - 1];

    var pLastIsNumber = isNumeric(pLast);

    // delete item
    if(pLastIsNumber && newVal === null) {

        // Clear item in array container when new value is null
        var contPath = parts.slice(0, pLength - 1).join('.');
        var cont = Lib.nestedProperty(obj, contPath).get();
        cont.splice(pLast, 1);

        // Note that nested property clears null / undefined at end of
        // array container, but not within them.
    }
    // create item
    else if(pLastIsNumber && np.get() === undefined) {

        // When adding a new item, make sure undo command will remove it
        if(np.get() === undefined) undoit[np.astr] = null;

        np.set(newVal);
    }
    // update item
    else {

        // If the last part of attribute string isn't a number,
        // np.set is all we need.
        np.set(newVal);
    }
};

/*
 * Match the part to strip off to turn an attribute into its parent
 * really it should be either '.some_characters' or '[number]'
 * but we're a little more permissive here and match either
 * '.not_brackets_or_dot' or '[not_brackets_or_dot]'
 */
var ATTR_TAIL_RE = /(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/;

function getParent(attr) {
    var tail = attr.search(ATTR_TAIL_RE);
    if(tail > 0) return attr.substr(0, tail);
}

/*
 * hasParent: does an attribute object contain a parent of the given attribute?
 * for example, given 'images[2].x' do we also have 'images' or 'images[2]'?
 *
 * @param {Object} aobj
 *  update object, whose keys are attribute strings and values are their new settings
 * @param {string} attr
 *  the attribute string to test against
 * @returns {Boolean}
 *  is a parent of attr present in aobj?
 */
exports.hasParent = function(aobj, attr) {
    var attrParent = getParent(attr);
    while(attrParent) {
        if(attrParent in aobj) return true;
        attrParent = getParent(attrParent);
    }
    return false;
};

/**
 * Empty out types for all axes containing these traces so we auto-set them again
 *
 * @param {object} gd
 * @param {[integer]} traces: trace indices to search for axes to clear the types of
 * @param {object} layoutUpdate: any update being done concurrently to the layout,
 *   which may supercede clearing the axis types
 */
var axLetters = ['x', 'y', 'z'];
exports.clearAxisTypes = function(gd, traces, layoutUpdate) {
    for(var i = 0; i < traces.length; i++) {
        var trace = gd._fullData[i];
        for(var j = 0; j < 3; j++) {
            var ax = getFromTrace(gd, trace, axLetters[j]);

            // do not clear log type - that's never an auto result so must have been intentional
            if(ax && ax.type !== 'log') {
                var axAttr = ax._name;
                var sceneName = ax._id.substr(1);
                if(sceneName.substr(0, 5) === 'scene') {
                    if(layoutUpdate[sceneName] !== undefined) continue;
                    axAttr = sceneName + '.' + axAttr;
                }
                var typeAttr = axAttr + '.type';

                if(layoutUpdate[axAttr] === undefined && layoutUpdate[typeAttr] === undefined) {
                    Lib.nestedProperty(gd.layout, typeAttr).set(null);
                }
            }
        }
    }
};

},{"../components/color":571,"../lib":694,"../plots/cartesian/axis_ids":745,"../plots/plots":806,"../registry":825,"fast-isnumeric":215,"gl-mat4/fromQuat":253}],727:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var main = _dereq_('./plot_api');

exports.plot = main.plot;
exports.newPlot = main.newPlot;
exports.restyle = main.restyle;
exports.relayout = main.relayout;
exports.redraw = main.redraw;
exports.update = main.update;
exports._guiRestyle = main._guiRestyle;
exports._guiRelayout = main._guiRelayout;
exports._guiUpdate = main._guiUpdate;
exports._storeDirectGUIEdit = main._storeDirectGUIEdit;
exports.react = main.react;
exports.extendTraces = main.extendTraces;
exports.prependTraces = main.prependTraces;
exports.addTraces = main.addTraces;
exports.deleteTraces = main.deleteTraces;
exports.moveTraces = main.moveTraces;
exports.purge = main.purge;
exports.addFrames = main.addFrames;
exports.deleteFrames = main.deleteFrames;
exports.animate = main.animate;
exports.setPlotConfig = main.setPlotConfig;

exports.toImage = _dereq_('./to_image');
exports.validate = _dereq_('./validate');
exports.downloadImage = _dereq_('../snapshot/download');

var templateApi = _dereq_('./template_api');
exports.makeTemplate = templateApi.makeTemplate;
exports.validateTemplate = templateApi.validateTemplate;

},{"../snapshot/download":827,"./plot_api":729,"./template_api":734,"./to_image":735,"./validate":736}],728:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isPlainObject = _dereq_('../lib/is_plain_object');
var noop = _dereq_('../lib/noop');
var Loggers = _dereq_('../lib/loggers');
var sorterAsc = _dereq_('../lib/search').sorterAsc;
var Registry = _dereq_('../registry');


exports.containerArrayMatch = _dereq_('./container_array_match');

var isAddVal = exports.isAddVal = function isAddVal(val) {
    return val === 'add' || isPlainObject(val);
};

var isRemoveVal = exports.isRemoveVal = function isRemoveVal(val) {
    return val === null || val === 'remove';
};

/*
 * applyContainerArrayChanges: for managing arrays of layout components in relayout
 * handles them all with a consistent interface.
 *
 * Here are the supported actions -> relayout calls -> edits we get here
 * (as prepared in _relayout):
 *
 * add an empty obj -> {'annotations[2]': 'add'} -> {2: {'': 'add'}}
 * add a specific obj -> {'annotations[2]': {attrs}} -> {2: {'': {attrs}}}
 * delete an obj -> {'annotations[2]': 'remove'} -> {2: {'': 'remove'}}
 *               -> {'annotations[2]': null} -> {2: {'': null}}
 * delete the whole array -> {'annotations': 'remove'} -> {'': {'': 'remove'}}
 *                        -> {'annotations': null} -> {'': {'': null}}
 * edit an object -> {'annotations[2].text': 'boo'} -> {2: {'text': 'boo'}}
 *
 * You can combine many edits to different objects. Objects are added and edited
 * in ascending order, then removed in descending order.
 * For example, starting with [a, b, c], if you want to:
 * - replace b with d:
 *   {'annotations[1]': d, 'annotations[2]': null} (b is item 2 after adding d)
 * - add a new item d between a and b, and edit b:
 *    {'annotations[1]': d, 'annotations[2].x': newX} (b is item 2 after adding d)
 * - delete b and edit c:
 *    {'annotations[1]': null, 'annotations[2].x': newX} (c is edited before b is removed)
 *
 * You CANNOT combine adding/deleting an item at index `i` with edits to the same index `i`
 * You CANNOT combine replacing/deleting the whole array with anything else (for the same array).
 *
 * @param {HTMLDivElement} gd
 *  the DOM element of the graph container div
 * @param {Lib.nestedProperty} componentType: the array we are editing
 * @param {Object} edits
 *  the changes to make; keys are indices to edit, values are themselves objects:
 *  {attr: newValue} of changes to make to that index (with add/remove behavior
 *  in special values of the empty attr)
 * @param {Object} flags
 *  the flags for which actions we're going to perform to display these (and
 *  any other) changes. If we're already `recalc`ing, we don't need to redraw
 *  individual items
 * @param {function} _nestedProperty
 *  a (possibly modified for gui edits) nestedProperty constructor
 *  The modified version takes a 3rd argument, for a prefix to the attribute
 *  string necessary for storing GUI edits
 *
 * @returns {bool} `true` if it managed to complete drawing of the changes
 *  `false` would mean the parent should replot.
 */
exports.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags, _nestedProperty) {
    var componentType = np.astr;
    var supplyComponentDefaults = Registry.getComponentMethod(componentType, 'supplyLayoutDefaults');
    var draw = Registry.getComponentMethod(componentType, 'draw');
    var drawOne = Registry.getComponentMethod(componentType, 'drawOne');
    var replotLater = flags.replot || flags.recalc || (supplyComponentDefaults === noop) || (draw === noop);
    var layout = gd.layout;
    var fullLayout = gd._fullLayout;

    if(edits['']) {
        if(Object.keys(edits).length > 1) {
            Loggers.warn('Full array edits are incompatible with other edits',
                componentType);
        }

        var fullVal = edits[''][''];

        if(isRemoveVal(fullVal)) np.set(null);
        else if(Array.isArray(fullVal)) np.set(fullVal);
        else {
            Loggers.warn('Unrecognized full array edit value', componentType, fullVal);
            return true;
        }

        if(replotLater) return false;

        supplyComponentDefaults(layout, fullLayout);
        draw(gd);
        return true;
    }

    var componentNums = Object.keys(edits).map(Number).sort(sorterAsc);
    var componentArrayIn = np.get();
    var componentArray = componentArrayIn || [];
    // componentArrayFull is used just to keep splices in line between
    // full and input arrays, so private keys can be copied over after
    // redoing supplyDefaults
    // TODO: this assumes componentArray is in gd.layout - which will not be
    // true after we extend this to restyle
    var componentArrayFull = _nestedProperty(fullLayout, componentType).get();

    var deletes = [];
    var firstIndexChange = -1;
    var maxIndex = componentArray.length;
    var i;
    var j;
    var componentNum;
    var objEdits;
    var objKeys;
    var objVal;
    var adding, prefix;

    // first make the add and edit changes
    for(i = 0; i < componentNums.length; i++) {
        componentNum = componentNums[i];
        objEdits = edits[componentNum];
        objKeys = Object.keys(objEdits);
        objVal = objEdits[''],
        adding = isAddVal(objVal);

        if(componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) {
            Loggers.warn('index out of range', componentType, componentNum);
            continue;
        }

        if(objVal !== undefined) {
            if(objKeys.length > 1) {
                Loggers.warn(
                    'Insertion & removal are incompatible with edits to the same index.',
                    componentType, componentNum);
            }

            if(isRemoveVal(objVal)) {
                deletes.push(componentNum);
            }
            else if(adding) {
                if(objVal === 'add') objVal = {};
                componentArray.splice(componentNum, 0, objVal);
                if(componentArrayFull) componentArrayFull.splice(componentNum, 0, {});
            }
            else {
                Loggers.warn('Unrecognized full object edit value',
                    componentType, componentNum, objVal);
            }

            if(firstIndexChange === -1) firstIndexChange = componentNum;
        }
        else {
            for(j = 0; j < objKeys.length; j++) {
                prefix = componentType + '[' + componentNum + '].';
                _nestedProperty(componentArray[componentNum], objKeys[j], prefix)
                    .set(objEdits[objKeys[j]]);
            }
        }
    }

    // now do deletes
    for(i = deletes.length - 1; i >= 0; i--) {
        componentArray.splice(deletes[i], 1);
        // TODO: this drops private keys that had been stored in componentArrayFull
        // does this have any ill effects?
        if(componentArrayFull) componentArrayFull.splice(deletes[i], 1);
    }

    if(!componentArray.length) np.set(null);
    else if(!componentArrayIn) np.set(componentArray);

    if(replotLater) return false;

    supplyComponentDefaults(layout, fullLayout);

    // finally draw all the components we need to
    // if we added or removed any, redraw all after it
    if(drawOne !== noop) {
        var indicesToDraw;
        if(firstIndexChange === -1) {
            // there's no re-indexing to do, so only redraw components that changed
            indicesToDraw = componentNums;
        }
        else {
            // in case the component array was shortened, we still need do call
            // drawOne on the latter items so they get properly removed
            maxIndex = Math.max(componentArray.length, maxIndex);
            indicesToDraw = [];
            for(i = 0; i < componentNums.length; i++) {
                componentNum = componentNums[i];
                if(componentNum >= firstIndexChange) break;
                indicesToDraw.push(componentNum);
            }
            for(i = firstIndexChange; i < maxIndex; i++) {
                indicesToDraw.push(i);
            }
        }
        for(i = 0; i < indicesToDraw.length; i++) {
            drawOne(gd, indicesToDraw[i]);
        }
    }
    else draw(gd);

    return true;
};

},{"../lib/is_plain_object":695,"../lib/loggers":698,"../lib/noop":703,"../lib/search":713,"../registry":825,"./container_array_match":724}],729:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');
var hasHover = _dereq_('has-hover');

var Lib = _dereq_('../lib');
var nestedProperty = Lib.nestedProperty;

var Events = _dereq_('../lib/events');
var Queue = _dereq_('../lib/queue');

var Registry = _dereq_('../registry');
var PlotSchema = _dereq_('./plot_schema');
var Plots = _dereq_('../plots/plots');
var Polar = _dereq_('../plots/polar/legacy');

var Axes = _dereq_('../plots/cartesian/axes');
var Drawing = _dereq_('../components/drawing');
var Color = _dereq_('../components/color');
var connectColorbar = _dereq_('../components/colorbar/connect');
var initInteractions = _dereq_('../plots/cartesian/graph_interact').initInteractions;
var xmlnsNamespaces = _dereq_('../constants/xmlns_namespaces');
var svgTextUtils = _dereq_('../lib/svg_text_utils');

var dfltConfig = _dereq_('./plot_config').dfltConfig;
var manageArrays = _dereq_('./manage_arrays');
var helpers = _dereq_('./helpers');
var subroutines = _dereq_('./subroutines');
var editTypes = _dereq_('./edit_types');

var AX_NAME_PATTERN = _dereq_('../plots/cartesian/constants').AX_NAME_PATTERN;

var numericNameWarningCount = 0;
var numericNameWarningCountLimit = 5;

/**
 * Main plot-creation function
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 * @param {array of objects} data
 *      array of traces, containing the data and display information for each trace
 * @param {object} layout
 *      object describing the overall display of the plot,
 *      all the stuff that doesn't pertain to any individual trace
 * @param {object} config
 *      configuration options (see ./plot_config.js for more info)
 *
 * OR
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 * @param {object} figure
 *      object containing `data`, `layout`, `config`, and `frames` members
 *
 */
exports.plot = function(gd, data, layout, config) {
    var frames;

    gd = Lib.getGraphDiv(gd);

    // Events.init is idempotent and bails early if gd has already been init'd
    Events.init(gd);

    if(Lib.isPlainObject(data)) {
        var obj = data;
        data = obj.data;
        layout = obj.layout;
        config = obj.config;
        frames = obj.frames;
    }

    var okToPlot = Events.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]);
    if(okToPlot === false) return Promise.reject();

    // if there's no data or layout, and this isn't yet a plotly plot
    // container, log a warning to help plotly.js users debug
    if(!data && !layout && !Lib.isPlotDiv(gd)) {
        Lib.warn('Calling Plotly.plot as if redrawing ' +
            'but this container doesn\'t yet have a plot.', gd);
    }

    function addFrames() {
        if(frames) {
            return exports.addFrames(gd, frames);
        }
    }

    // transfer configuration options to gd until we move over to
    // a more OO like model
    setPlotContext(gd, config);

    if(!layout) layout = {};

    // hook class for plots main container (in case of plotly.js
    // this won't be #embedded-graph or .js-tab-contents)
    d3.select(gd).classed('js-plotly-plot', true);

    // off-screen getBoundingClientRect testing space,
    // in #js-plotly-tester (and stored as Drawing.tester)
    // so we can share cached text across tabs
    Drawing.makeTester();

    // collect promises for any async actions during plotting
    // any part of the plotting code can push to gd._promises, then
    // before we move to the next step, we check that they're all
    // complete, and empty out the promise list again.
    if(!Array.isArray(gd._promises)) gd._promises = [];

    var graphWasEmpty = ((gd.data || []).length === 0 && Array.isArray(data));

    // if there is already data on the graph, append the new data
    // if you only want to redraw, pass a non-array for data
    if(Array.isArray(data)) {
        helpers.cleanData(data);

        if(graphWasEmpty) gd.data = data;
        else gd.data.push.apply(gd.data, data);

        // for routines outside graph_obj that want a clean tab
        // (rather than appending to an existing one) gd.empty
        // is used to determine whether to make a new tab
        gd.empty = false;
    }

    if(!gd.layout || graphWasEmpty) gd.layout = helpers.cleanLayout(layout);

    // if the user is trying to drag the axes, allow new data and layout
    // to come in but don't allow a replot.
    if(gd._dragging && !gd._transitioning) {
        // signal to drag handler that after everything else is done
        // we need to replot, because something has changed
        gd._replotPending = true;
        return Promise.reject();
    } else {
        // we're going ahead with a replot now
        gd._replotPending = false;
    }

    Plots.supplyDefaults(gd);

    var fullLayout = gd._fullLayout;
    var hasCartesian = fullLayout._has('cartesian');

    // Legacy polar plots
    if(!fullLayout._has('polar') && data && data[0] && data[0].r) {
        Lib.log('Legacy polar charts are deprecated!');
        return plotLegacyPolar(gd, data, layout);
    }

    // so we don't try to re-call Plotly.plot from inside
    // legend and colorbar, if margins changed
    fullLayout._replotting = true;

    // make or remake the framework if we need to
    if(graphWasEmpty) makePlotFramework(gd);

    // polar need a different framework
    if(gd.framework !== makePlotFramework) {
        gd.framework = makePlotFramework;
        makePlotFramework(gd);
    }

    // clear gradient defs on each .plot call, because we know we'll loop through all traces
    Drawing.initGradients(gd);

    // save initial show spikes once per graph
    if(graphWasEmpty) Axes.saveShowSpikeInitial(gd);

    // prepare the data and find the autorange

    // generate calcdata, if we need to
    // to force redoing calcdata, just delete it before calling Plotly.plot
    var recalc = !gd.calcdata || gd.calcdata.length !== (gd._fullData || []).length;
    if(recalc) Plots.doCalcdata(gd);

    // in case it has changed, attach fullData traces to calcdata
    for(var i = 0; i < gd.calcdata.length; i++) {
        gd.calcdata[i][0].trace = gd._fullData[i];
    }

    // make the figure responsive
    if(gd._context.responsive) {
        if(!gd._responsiveChartHandler) {
            // Keep a reference to the resize handler to purge it down the road
            gd._responsiveChartHandler = function() {Plots.resize(gd);};

            // Listen to window resize
            window.addEventListener('resize', gd._responsiveChartHandler);
        }
    } else {
        Lib.clearResponsive(gd);
    }

    /*
     * start async-friendly code - now we're actually drawing things
     */

    var oldmargins = JSON.stringify(fullLayout._size);

    // draw framework first so that margin-pushing
    // components can position themselves correctly
    var drawFrameworkCalls = 0;
    function drawFramework() {
        var basePlotModules = fullLayout._basePlotModules;

        for(var i = 0; i < basePlotModules.length; i++) {
            if(basePlotModules[i].drawFramework) {
                basePlotModules[i].drawFramework(gd);
            }
        }

        if(!fullLayout._glcanvas && fullLayout._has('gl')) {
            fullLayout._glcanvas = fullLayout._glcontainer.selectAll('.gl-canvas').data([{
                key: 'contextLayer',
                context: true,
                pick: false
            }, {
                key: 'focusLayer',
                context: false,
                pick: false
            }, {
                key: 'pickLayer',
                context: false,
                pick: true
            }], function(d) { return d.key; });

            fullLayout._glcanvas.enter().append('canvas')
                .attr('class', function(d) {
                    return 'gl-canvas gl-canvas-' + d.key.replace('Layer', '');
                })
                .style({
                    'position': 'absolute',
                    'top': 0,
                    'left': 0,
                    'width': '100%',
                    'height': '100%',
                    'overflow': 'visible',
                    'pointer-events': 'none'
                });
        }

        if(fullLayout._glcanvas) {
            fullLayout._glcanvas
                .attr('width', fullLayout.width)
                .attr('height', fullLayout.height);

            var regl = fullLayout._glcanvas.data()[0].regl;
            if(regl) {
                // Unfortunately, this can happen when relayouting to large
                // width/height on some browsers.
                if(Math.floor(fullLayout.width) !== regl._gl.drawingBufferWidth ||
                    Math.floor(fullLayout.height) !== regl._gl.drawingBufferHeight
                 ) {
                    var msg = 'WebGL context buffer and canvas dimensions do not match due to browser/WebGL bug.';
                    if(drawFrameworkCalls) {
                        Lib.error(msg);
                    } else {
                        Lib.log(msg + ' Clearing graph and plotting again.');
                        Plots.cleanPlot([], {}, gd._fullData, fullLayout);
                        Plots.supplyDefaults(gd);
                        fullLayout = gd._fullLayout;
                        Plots.doCalcdata(gd);
                        drawFrameworkCalls++;
                        return drawFramework();
                    }
                }
            }
        }

        return Plots.previousPromises(gd);
    }

    // draw anything that can affect margins.
    function marginPushers() {
        var calcdata = gd.calcdata;
        var i, cd, trace;

        // First reset the list of things that are allowed to change the margins
        // So any deleted traces or components will be wiped out of the
        // automargin calculation.
        // This means *every* margin pusher must be listed here, even if it
        // doesn't actually try to push the margins until later.
        Plots.clearAutoMarginIds(gd);

        subroutines.drawMarginPushers(gd);
        Axes.allowAutoMargin(gd);

        for(i = 0; i < calcdata.length; i++) {
            cd = calcdata[i];
            trace = cd[0].trace;
            var colorbarOpts = trace._module.colorbar;
            if(trace.visible !== true || !colorbarOpts) {
                Plots.autoMargin(gd, 'cb' + trace.uid);
            }
            else connectColorbar(gd, cd, colorbarOpts);
        }

        Plots.doAutoMargin(gd);
        return Plots.previousPromises(gd);
    }

    // in case the margins changed, draw margin pushers again
    function marginPushersAgain() {
        if(JSON.stringify(fullLayout._size) === oldmargins) return;

        return Lib.syncOrAsync([
            marginPushers,
            subroutines.layoutStyles
        ], gd);
    }

    function positionAndAutorange() {
        if(!recalc) {
            doAutoRangeAndConstraints();
            return;
        }

        // TODO: autosize extra for text markers and images
        // see https://github.com/plotly/plotly.js/issues/1111
        return Lib.syncOrAsync([
            Registry.getComponentMethod('shapes', 'calcAutorange'),
            Registry.getComponentMethod('annotations', 'calcAutorange'),
            doAutoRangeAndConstraints
        ], gd);
    }

    function doAutoRangeAndConstraints() {
        if(gd._transitioning) return;

        subroutines.doAutoRangeAndConstraints(gd);

        // store initial ranges *after* enforcing constraints, otherwise
        // we will never look like we're at the initial ranges
        if(graphWasEmpty) Axes.saveRangeInitial(gd);

        // this one is different from shapes/annotations calcAutorange
        // the others incorporate those components into ax._extremes,
        // this one actually sets the ranges in rangesliders.
        Registry.getComponentMethod('rangeslider', 'calcAutorange')(gd);
    }

    // draw ticks, titles, and calculate axis scaling (._b, ._m)
    function drawAxes() {
        return Axes.draw(gd, graphWasEmpty ? '' : 'redraw');
    }

    var seq = [
        Plots.previousPromises,
        addFrames,
        drawFramework,
        marginPushers,
        marginPushersAgain
    ];

    if(hasCartesian) seq.push(positionAndAutorange);

    seq.push(subroutines.layoutStyles);
    if(hasCartesian) seq.push(drawAxes);

    seq.push(
        subroutines.drawData,
        subroutines.finalDraw,
        initInteractions,
        Plots.addLinks,
        Plots.rehover,
        // TODO: doAutoMargin is only needed here for axis automargin, which
        // happens outside of marginPushers where all the other automargins are
        // calculated. Would be much better to separate margin calculations from
        // component drawing - see https://github.com/plotly/plotly.js/issues/2704
        Plots.doAutoMargin,
        Plots.previousPromises
    );

    // even if everything we did was synchronous, return a promise
    // so that the caller doesn't care which route we took
    var plotDone = Lib.syncOrAsync(seq, gd);
    if(!plotDone || !plotDone.then) plotDone = Promise.resolve();

    return plotDone.then(function() {
        emitAfterPlot(gd);
        return gd;
    });
};

function emitAfterPlot(gd) {
    var fullLayout = gd._fullLayout;

    if(fullLayout._redrawFromAutoMarginCount) {
        fullLayout._redrawFromAutoMarginCount--;
    } else {
        gd.emit('plotly_afterplot');
    }
}

exports.setPlotConfig = function setPlotConfig(obj) {
    return Lib.extendFlat(dfltConfig, obj);
};

function setBackground(gd, bgColor) {
    try {
        gd._fullLayout._paper.style('background', bgColor);
    } catch(e) {
        Lib.error(e);
    }
}

function opaqueSetBackground(gd, bgColor) {
    var blend = Color.combine(bgColor, 'white');
    setBackground(gd, blend);
}

function setPlotContext(gd, config) {
    if(!gd._context) {
        gd._context = Lib.extendDeep({}, dfltConfig);

        // stash <base> href, used to make robust clipPath URLs
        var base = d3.select('base');
        gd._context._baseUrl = base.size() && base.attr('href') ?
            window.location.href.split('#')[0] :
            '';
    }

    var context = gd._context;

    var i, keys, key;

    if(config) {
        keys = Object.keys(config);
        for(i = 0; i < keys.length; i++) {
            key = keys[i];
            if(key === 'editable' || key === 'edits') continue;
            if(key in context) {
                if(key === 'setBackground' && config[key] === 'opaque') {
                    context[key] = opaqueSetBackground;
                } else {
                    context[key] = config[key];
                }
            }
        }

        // map plot3dPixelRatio to plotGlPixelRatio for backward compatibility
        if(config.plot3dPixelRatio && !context.plotGlPixelRatio) {
            context.plotGlPixelRatio = context.plot3dPixelRatio;
        }

        // now deal with editable and edits - first editable overrides
        // everything, then edits refines
        var editable = config.editable;
        if(editable !== undefined) {
            // we're not going to *use* context.editable, we're only going to
            // use context.edits... but keep it for the record
            context.editable = editable;

            keys = Object.keys(context.edits);
            for(i = 0; i < keys.length; i++) {
                context.edits[keys[i]] = editable;
            }
        }
        if(config.edits) {
            keys = Object.keys(config.edits);
            for(i = 0; i < keys.length; i++) {
                key = keys[i];
                if(key in context.edits) {
                    context.edits[key] = config.edits[key];
                }
            }
        }

        // not part of the user-facing config options
        context._exportedPlot = config._exportedPlot;
    }

    // staticPlot forces a bunch of others:
    if(context.staticPlot) {
        context.editable = false;
        context.edits = {};
        context.autosizable = false;
        context.scrollZoom = false;
        context.doubleClick = false;
        context.showTips = false;
        context.showLink = false;
        context.displayModeBar = false;
    }

    // make sure hover-only devices have mode bar visible
    if(context.displayModeBar === 'hover' && !hasHover) {
        context.displayModeBar = true;
    }

    // default and fallback for setBackground
    if(context.setBackground === 'transparent' || typeof context.setBackground !== 'function') {
        context.setBackground = setBackground;
    }

    // Check if gd has a specified widht/height to begin with
    context._hasZeroHeight = context._hasZeroHeight || gd.clientHeight === 0;
    context._hasZeroWidth = context._hasZeroWidth || gd.clientWidth === 0;

    // fill context._scrollZoom helper to help manage scrollZoom flaglist
    var szIn = context.scrollZoom;
    var szOut = context._scrollZoom = {};
    if(szIn === true) {
        szOut.cartesian = 1;
        szOut.gl3d = 1;
        szOut.geo = 1;
        szOut.mapbox = 1;
    } else if(typeof szIn === 'string') {
        var parts = szIn.split('+');
        for(i = 0; i < parts.length; i++) {
            szOut[parts[i]] = 1;
        }
    } else if(szIn !== false) {
        szOut.gl3d = 1;
        szOut.geo = 1;
        szOut.mapbox = 1;
    }
}

function plotLegacyPolar(gd, data, layout) {
    // build or reuse the container skeleton
    var plotContainer = d3.select(gd).selectAll('.plot-container')
        .data([0]);
    plotContainer.enter()
        .insert('div', ':first-child')
        .classed('plot-container plotly', true);
    var paperDiv = plotContainer.selectAll('.svg-container')
        .data([0]);
    paperDiv.enter().append('div')
        .classed('svg-container', true)
        .style('position', 'relative');

    // empty it everytime for now
    paperDiv.html('');

    // fulfill gd requirements
    if(data) gd.data = data;
    if(layout) gd.layout = layout;
    Polar.manager.fillLayout(gd);

    // resize canvas
    paperDiv.style({
        width: gd._fullLayout.width + 'px',
        height: gd._fullLayout.height + 'px'
    });

    // instantiate framework
    gd.framework = Polar.manager.framework(gd);

    // plot
    gd.framework({data: gd.data, layout: gd.layout}, paperDiv.node());

    // set undo point
    gd.framework.setUndoPoint();

    // get the resulting svg for extending it
    var polarPlotSVG = gd.framework.svg();

    // editable title
    var opacity = 1;
    var txt = gd._fullLayout.title ? gd._fullLayout.title.text : '';
    if(txt === '' || !txt) opacity = 0;

    var titleLayout = function() {
        this.call(svgTextUtils.convertToTspans, gd);
        // TODO: html/mathjax
        // TODO: center title
    };

    var title = polarPlotSVG.select('.title-group text')
        .call(titleLayout);

    if(gd._context.edits.titleText) {
        var placeholderText = Lib._(gd, 'Click to enter Plot title');
        if(!txt || txt === placeholderText) {
            opacity = 0.2;
            // placeholder is not going through convertToTspans
            // so needs explicit data-unformatted
            title.attr({'data-unformatted': placeholderText})
                .text(placeholderText)
                .style({opacity: opacity})
                .on('mouseover.opacity', function() {
                    d3.select(this).transition().duration(100)
                        .style('opacity', 1);
                })
                .on('mouseout.opacity', function() {
                    d3.select(this).transition().duration(1000)
                        .style('opacity', 0);
                });
        }

        var setContenteditable = function() {
            this.call(svgTextUtils.makeEditable, {gd: gd})
                .on('edit', function(text) {
                    gd.framework({layout: {title: {text: text}}});
                    this.text(text)
                        .call(titleLayout);
                    this.call(setContenteditable);
                })
                .on('cancel', function() {
                    var txt = this.attr('data-unformatted');
                    this.text(txt).call(titleLayout);
                });
        };
        title.call(setContenteditable);
    }

    gd._context.setBackground(gd, gd._fullLayout.paper_bgcolor);
    Plots.addLinks(gd);

    return Promise.resolve();
}

// convenience function to force a full redraw, mostly for use by plotly.js
exports.redraw = function(gd) {
    gd = Lib.getGraphDiv(gd);

    if(!Lib.isPlotDiv(gd)) {
        throw new Error('This element is not a Plotly plot: ' + gd);
    }

    helpers.cleanData(gd.data);
    helpers.cleanLayout(gd.layout);

    gd.calcdata = undefined;
    return exports.plot(gd).then(function() {
        gd.emit('plotly_redraw');
        return gd;
    });
};

/**
 * Convenience function to make idempotent plot option obvious to users.
 *
 * @param gd
 * @param {Object[]} data
 * @param {Object} layout
 * @param {Object} config
 */
exports.newPlot = function(gd, data, layout, config) {
    gd = Lib.getGraphDiv(gd);

    // remove gl contexts
    Plots.cleanPlot([], {}, gd._fullData || [], gd._fullLayout || {});

    Plots.purge(gd);
    return exports.plot(gd, data, layout, config);
};

/**
 * Wrap negative indicies to their positive counterparts.
 *
 * @param {Number[]} indices An array of indices
 * @param {Number} maxIndex The maximum index allowable (arr.length - 1)
 */
function positivifyIndices(indices, maxIndex) {
    var parentLength = maxIndex + 1;
    var positiveIndices = [];
    var i;
    var index;

    for(i = 0; i < indices.length; i++) {
        index = indices[i];
        if(index < 0) {
            positiveIndices.push(parentLength + index);
        } else {
            positiveIndices.push(index);
        }
    }
    return positiveIndices;
}

/**
 * Ensures that an index array for manipulating gd.data is valid.
 *
 * Intended for use with addTraces, deleteTraces, and moveTraces.
 *
 * @param gd
 * @param indices
 * @param arrayName
 */
function assertIndexArray(gd, indices, arrayName) {
    var i,
        index;

    for(i = 0; i < indices.length; i++) {
        index = indices[i];

        // validate that indices are indeed integers
        if(index !== parseInt(index, 10)) {
            throw new Error('all values in ' + arrayName + ' must be integers');
        }

        // check that all indices are in bounds for given gd.data array length
        if(index >= gd.data.length || index < -gd.data.length) {
            throw new Error(arrayName + ' must be valid indices for gd.data.');
        }

        // check that indices aren't repeated
        if(indices.indexOf(index, i + 1) > -1 ||
                index >= 0 && indices.indexOf(-gd.data.length + index) > -1 ||
                index < 0 && indices.indexOf(gd.data.length + index) > -1) {
            throw new Error('each index in ' + arrayName + ' must be unique.');
        }
    }
}

/**
 * Private function used by Plotly.moveTraces to check input args
 *
 * @param gd
 * @param currentIndices
 * @param newIndices
 */
function checkMoveTracesArgs(gd, currentIndices, newIndices) {

    // check that gd has attribute 'data' and 'data' is array
    if(!Array.isArray(gd.data)) {
        throw new Error('gd.data must be an array.');
    }

    // validate currentIndices array
    if(typeof currentIndices === 'undefined') {
        throw new Error('currentIndices is a required argument.');
    } else if(!Array.isArray(currentIndices)) {
        currentIndices = [currentIndices];
    }
    assertIndexArray(gd, currentIndices, 'currentIndices');

    // validate newIndices array if it exists
    if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {
        newIndices = [newIndices];
    }
    if(typeof newIndices !== 'undefined') {
        assertIndexArray(gd, newIndices, 'newIndices');
    }

    // check currentIndices and newIndices are the same length if newIdices exists
    if(typeof newIndices !== 'undefined' && currentIndices.length !== newIndices.length) {
        throw new Error('current and new indices must be of equal length.');
    }

}
/**
 * A private function to reduce the type checking clutter in addTraces.
 *
 * @param gd
 * @param traces
 * @param newIndices
 */
function checkAddTracesArgs(gd, traces, newIndices) {
    var i, value;

    // check that gd has attribute 'data' and 'data' is array
    if(!Array.isArray(gd.data)) {
        throw new Error('gd.data must be an array.');
    }

    // make sure traces exists
    if(typeof traces === 'undefined') {
        throw new Error('traces must be defined.');
    }

    // make sure traces is an array
    if(!Array.isArray(traces)) {
        traces = [traces];
    }

    // make sure each value in traces is an object
    for(i = 0; i < traces.length; i++) {
        value = traces[i];
        if(typeof value !== 'object' || (Array.isArray(value) || value === null)) {
            throw new Error('all values in traces array must be non-array objects');
        }
    }

    // make sure we have an index for each trace
    if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {
        newIndices = [newIndices];
    }
    if(typeof newIndices !== 'undefined' && newIndices.length !== traces.length) {
        throw new Error(
            'if indices is specified, traces.length must equal indices.length'
        );
    }
}

/**
 * A private function to reduce the type checking clutter in spliceTraces.
 * Get all update Properties from gd.data. Validate inputs and outputs.
 * Used by prependTrace and extendTraces
 *
 * @param gd
 * @param update
 * @param indices
 * @param maxPoints
 */
function assertExtendTracesArgs(gd, update, indices, maxPoints) {

    var maxPointsIsObject = Lib.isPlainObject(maxPoints);

    if(!Array.isArray(gd.data)) {
        throw new Error('gd.data must be an array');
    }
    if(!Lib.isPlainObject(update)) {
        throw new Error('update must be a key:value object');
    }

    if(typeof indices === 'undefined') {
        throw new Error('indices must be an integer or array of integers');
    }

    assertIndexArray(gd, indices, 'indices');

    for(var key in update) {

        /*
         * Verify that the attribute to be updated contains as many trace updates
         * as indices. Failure must result in throw and no-op
         */
        if(!Array.isArray(update[key]) || update[key].length !== indices.length) {
            throw new Error('attribute ' + key + ' must be an array of length equal to indices array length');
        }

        /*
         * if maxPoints is an object it must match keys and array lengths of 'update' 1:1
         */
        if(maxPointsIsObject &&
            (!(key in maxPoints) || !Array.isArray(maxPoints[key]) ||
            maxPoints[key].length !== update[key].length)) {
            throw new Error('when maxPoints is set as a key:value object it must contain a 1:1 ' +
                            'corrispondence with the keys and number of traces in the update object');
        }
    }
}

/**
 * A private function to reduce the type checking clutter in spliceTraces.
 *
 * @param {Object|HTMLDivElement} gd
 * @param {Object} update
 * @param {Number[]} indices
 * @param {Number||Object} maxPoints
 * @return {Object[]}
 */
function getExtendProperties(gd, update, indices, maxPoints) {

    var maxPointsIsObject = Lib.isPlainObject(maxPoints);
    var updateProps = [];
    var trace, target, prop, insert, maxp;

    // allow scalar index to represent a single trace position
    if(!Array.isArray(indices)) indices = [indices];

    // negative indices are wrapped around to their positive value. Equivalent to python indexing.
    indices = positivifyIndices(indices, gd.data.length - 1);

    // loop through all update keys and traces and harvest validated data.
    for(var key in update) {

        for(var j = 0; j < indices.length; j++) {

            /*
             * Choose the trace indexed by the indices map argument and get the prop setter-getter
             * instance that references the key and value for this particular trace.
             */
            trace = gd.data[indices[j]];
            prop = nestedProperty(trace, key);

            /*
             * Target is the existing gd.data.trace.dataArray value like "x" or "marker.size"
             * Target must exist as an Array to allow the extend operation to be performed.
             */
            target = prop.get();
            insert = update[key][j];

            if(!Lib.isArrayOrTypedArray(insert)) {
                throw new Error('attribute: ' + key + ' index: ' + j + ' must be an array');
            }
            if(!Lib.isArrayOrTypedArray(target)) {
                throw new Error('cannot extend missing or non-array attribute: ' + key);
            }
            if(target.constructor !== insert.constructor) {
                throw new Error('cannot extend array with an array of a different type: ' + key);
            }

            /*
             * maxPoints may be an object map or a scalar. If object select the key:value, else
             * Use the scalar maxPoints for all key and trace combinations.
             */
            maxp = maxPointsIsObject ? maxPoints[key][j] : maxPoints;

            // could have chosen null here, -1 just tells us to not take a window
            if(!isNumeric(maxp)) maxp = -1;

            /*
             * Wrap the nestedProperty in an object containing required data
             * for lengthening and windowing this particular trace - key combination.
             * Flooring maxp mirrors the behaviour of floats in the Array.slice JSnative function.
             */
            updateProps.push({
                prop: prop,
                target: target,
                insert: insert,
                maxp: Math.floor(maxp)
            });
        }
    }

    // all target and insertion data now validated
    return updateProps;
}

/**
 * A private function to key Extend and Prepend traces DRY
 *
 * @param {Object|HTMLDivElement} gd
 * @param {Object} update
 * @param {Number[]} indices
 * @param {Number||Object} maxPoints
 * @param {Function} updateArray
 * @return {Object}
 */
function spliceTraces(gd, update, indices, maxPoints, updateArray) {
    assertExtendTracesArgs(gd, update, indices, maxPoints);

    var updateProps = getExtendProperties(gd, update, indices, maxPoints);
    var undoUpdate = {};
    var undoPoints = {};

    for(var i = 0; i < updateProps.length; i++) {
        var prop = updateProps[i].prop;
        var maxp = updateProps[i].maxp;

        // return new array and remainder
        var out = updateArray(updateProps[i].target, updateProps[i].insert, maxp);
        prop.set(out[0]);

        // build the inverse update object for the undo operation
        if(!Array.isArray(undoUpdate[prop.astr])) undoUpdate[prop.astr] = [];
        undoUpdate[prop.astr].push(out[1]);

         // build the matching maxPoints undo object containing original trace lengths
        if(!Array.isArray(undoPoints[prop.astr])) undoPoints[prop.astr] = [];
        undoPoints[prop.astr].push(updateProps[i].target.length);
    }

    return {update: undoUpdate, maxPoints: undoPoints};
}

function concatTypedArray(arr0, arr1) {
    var arr2 = new arr0.constructor(arr0.length + arr1.length);
    arr2.set(arr0);
    arr2.set(arr1, arr0.length);
    return arr2;
}

/**
 * extend && prepend traces at indices with update arrays, window trace lengths to maxPoints
 *
 * Extend and Prepend have identical APIs. Prepend inserts an array at the head while Extend
 * inserts an array off the tail. Prepend truncates the tail of the array - counting maxPoints
 * from the head, whereas Extend truncates the head of the array, counting backward maxPoints
 * from the tail.
 *
 * If maxPoints is undefined, nonNumeric, negative or greater than extended trace length no
 * truncation / windowing will be performed. If its zero, well the whole trace is truncated.
 *
 * @param {Object|HTMLDivElement} gd The graph div
 * @param {Object} update The key:array map of target attributes to extend
 * @param {Number|Number[]} indices The locations of traces to be extended
 * @param {Number|Object} [maxPoints] Number of points for trace window after lengthening.
 *
 */
exports.extendTraces = function extendTraces(gd, update, indices, maxPoints) {
    gd = Lib.getGraphDiv(gd);

    function updateArray(target, insert, maxp) {
        var newArray, remainder;

        if(Lib.isTypedArray(target)) {
            if(maxp < 0) {
                var none = new target.constructor(0);
                var both = concatTypedArray(target, insert);

                if(maxp < 0) {
                    newArray = both;
                    remainder = none;
                } else {
                    newArray = none;
                    remainder = both;
                }
            } else {
                newArray = new target.constructor(maxp);
                remainder = new target.constructor(target.length + insert.length - maxp);

                if(maxp === insert.length) {
                    newArray.set(insert);
                    remainder.set(target);
                } else if(maxp < insert.length) {
                    var numberOfItemsFromInsert = insert.length - maxp;

                    newArray.set(insert.subarray(numberOfItemsFromInsert));
                    remainder.set(target);
                    remainder.set(insert.subarray(0, numberOfItemsFromInsert), target.length);
                } else {
                    var numberOfItemsFromTarget = maxp - insert.length;
                    var targetBegin = target.length - numberOfItemsFromTarget;

                    newArray.set(target.subarray(targetBegin));
                    newArray.set(insert, numberOfItemsFromTarget);
                    remainder.set(target.subarray(0, targetBegin));
                }
            }
        } else {
            newArray = target.concat(insert);
            remainder = (maxp >= 0 && maxp < newArray.length) ?
                newArray.splice(0, newArray.length - maxp) :
                [];
        }

        return [newArray, remainder];
    }

    var undo = spliceTraces(gd, update, indices, maxPoints, updateArray);
    var promise = exports.redraw(gd);
    var undoArgs = [gd, undo.update, indices, undo.maxPoints];
    Queue.add(gd, exports.prependTraces, undoArgs, extendTraces, arguments);

    return promise;
};

exports.prependTraces = function prependTraces(gd, update, indices, maxPoints) {
    gd = Lib.getGraphDiv(gd);

    function updateArray(target, insert, maxp) {
        var newArray, remainder;

        if(Lib.isTypedArray(target)) {
            if(maxp <= 0) {
                var none = new target.constructor(0);
                var both = concatTypedArray(insert, target);

                if(maxp < 0) {
                    newArray = both;
                    remainder = none;
                } else {
                    newArray = none;
                    remainder = both;
                }
            } else {
                newArray = new target.constructor(maxp);
                remainder = new target.constructor(target.length + insert.length - maxp);

                if(maxp === insert.length) {
                    newArray.set(insert);
                    remainder.set(target);
                } else if(maxp < insert.length) {
                    var numberOfItemsFromInsert = insert.length - maxp;

                    newArray.set(insert.subarray(0, numberOfItemsFromInsert));
                    remainder.set(insert.subarray(numberOfItemsFromInsert));
                    remainder.set(target, numberOfItemsFromInsert);
                } else {
                    var numberOfItemsFromTarget = maxp - insert.length;

                    newArray.set(insert);
                    newArray.set(target.subarray(0, numberOfItemsFromTarget), insert.length);
                    remainder.set(target.subarray(numberOfItemsFromTarget));
                }
            }
        } else {
            newArray = insert.concat(target);
            remainder = (maxp >= 0 && maxp < newArray.length) ?
                newArray.splice(maxp, newArray.length) :
                [];
        }

        return [newArray, remainder];
    }

    var undo = spliceTraces(gd, update, indices, maxPoints, updateArray);
    var promise = exports.redraw(gd);
    var undoArgs = [gd, undo.update, indices, undo.maxPoints];
    Queue.add(gd, exports.extendTraces, undoArgs, prependTraces, arguments);

    return promise;
};

/**
 * Add data traces to an existing graph div.
 *
 * @param {Object|HTMLDivElement} gd The graph div
 * @param {Object[]} gd.data The array of traces we're adding to
 * @param {Object[]|Object} traces The object or array of objects to add
 * @param {Number[]|Number} [newIndices=[gd.data.length]] Locations to add traces
 *
 */
exports.addTraces = function addTraces(gd, traces, newIndices) {
    gd = Lib.getGraphDiv(gd);

    var currentIndices = [];
    var undoFunc = exports.deleteTraces;
    var redoFunc = addTraces;
    var undoArgs = [gd, currentIndices];
    var redoArgs = [gd, traces];  // no newIndices here
    var i;
    var promise;

    // all validation is done elsewhere to remove clutter here
    checkAddTracesArgs(gd, traces, newIndices);

    // make sure traces is an array
    if(!Array.isArray(traces)) {
        traces = [traces];
    }

    // make sure traces do not repeat existing ones
    traces = traces.map(function(trace) {
        return Lib.extendFlat({}, trace);
    });

    helpers.cleanData(traces);

    // add the traces to gd.data (no redrawing yet!)
    for(i = 0; i < traces.length; i++) {
        gd.data.push(traces[i]);
    }

    // to continue, we need to call moveTraces which requires currentIndices
    for(i = 0; i < traces.length; i++) {
        currentIndices.push(-traces.length + i);
    }

    // if the user didn't define newIndices, they just want the traces appended
    // i.e., we can simply redraw and be done
    if(typeof newIndices === 'undefined') {
        promise = exports.redraw(gd);
        Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
        return promise;
    }

    // make sure indices is property defined
    if(!Array.isArray(newIndices)) {
        newIndices = [newIndices];
    }

    try {

        // this is redundant, but necessary to not catch later possible errors!
        checkMoveTracesArgs(gd, currentIndices, newIndices);
    }
    catch(error) {

        // something went wrong, reset gd to be safe and rethrow error
        gd.data.splice(gd.data.length - traces.length, traces.length);
        throw error;
    }

    // if we're here, the user has defined specific places to place the new traces
    // this requires some extra work that moveTraces will do
    Queue.startSequence(gd);
    Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
    promise = exports.moveTraces(gd, currentIndices, newIndices);
    Queue.stopSequence(gd);
    return promise;
};

/**
 * Delete traces at `indices` from gd.data array.
 *
 * @param {Object|HTMLDivElement} gd The graph div
 * @param {Object[]} gd.data The array of traces we're removing from
 * @param {Number|Number[]} indices The indices
 */
exports.deleteTraces = function deleteTraces(gd, indices) {
    gd = Lib.getGraphDiv(gd);

    var traces = [];
    var undoFunc = exports.addTraces;
    var redoFunc = deleteTraces;
    var undoArgs = [gd, traces, indices];
    var redoArgs = [gd, indices];
    var i;
    var deletedTrace;

    // make sure indices are defined
    if(typeof indices === 'undefined') {
        throw new Error('indices must be an integer or array of integers.');
    } else if(!Array.isArray(indices)) {
        indices = [indices];
    }
    assertIndexArray(gd, indices, 'indices');

    // convert negative indices to positive indices
    indices = positivifyIndices(indices, gd.data.length - 1);

    // we want descending here so that splicing later doesn't affect indexing
    indices.sort(Lib.sorterDes);
    for(i = 0; i < indices.length; i += 1) {
        deletedTrace = gd.data.splice(indices[i], 1)[0];
        traces.push(deletedTrace);
    }

    var promise = exports.redraw(gd);
    Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);

    return promise;
};

/**
 * Move traces at currentIndices array to locations in newIndices array.
 *
 * If newIndices is omitted, currentIndices will be moved to the end. E.g.,
 * these are equivalent:
 *
 * Plotly.moveTraces(gd, [1, 2, 3], [-3, -2, -1])
 * Plotly.moveTraces(gd, [1, 2, 3])
 *
 * @param {Object|HTMLDivElement} gd The graph div
 * @param {Object[]} gd.data The array of traces we're removing from
 * @param {Number|Number[]} currentIndices The locations of traces to be moved
 * @param {Number|Number[]} [newIndices] The locations to move traces to
 *
 * Example calls:
 *
 *      // move trace i to location x
 *      Plotly.moveTraces(gd, i, x)
 *
 *      // move trace i to end of array
 *      Plotly.moveTraces(gd, i)
 *
 *      // move traces i, j, k to end of array (i != j != k)
 *      Plotly.moveTraces(gd, [i, j, k])
 *
 *      // move traces [i, j, k] to [x, y, z] (i != j != k) (x != y != z)
 *      Plotly.moveTraces(gd, [i, j, k], [x, y, z])
 *
 *      // reorder all traces (assume there are 5--a, b, c, d, e)
 *      Plotly.moveTraces(gd, [b, d, e, a, c])  // same as 'move to end'
 */
exports.moveTraces = function moveTraces(gd, currentIndices, newIndices) {
    gd = Lib.getGraphDiv(gd);

    var newData = [];
    var movingTraceMap = [];
    var undoFunc = moveTraces;
    var redoFunc = moveTraces;
    var undoArgs = [gd, newIndices, currentIndices];
    var redoArgs = [gd, currentIndices, newIndices];
    var i;

    // to reduce complexity here, check args elsewhere
    // this throws errors where appropriate
    checkMoveTracesArgs(gd, currentIndices, newIndices);

    // make sure currentIndices is an array
    currentIndices = Array.isArray(currentIndices) ? currentIndices : [currentIndices];

    // if undefined, define newIndices to point to the end of gd.data array
    if(typeof newIndices === 'undefined') {
        newIndices = [];
        for(i = 0; i < currentIndices.length; i++) {
            newIndices.push(-currentIndices.length + i);
        }
    }

    // make sure newIndices is an array if it's user-defined
    newIndices = Array.isArray(newIndices) ? newIndices : [newIndices];

    // convert negative indices to positive indices (they're the same length)
    currentIndices = positivifyIndices(currentIndices, gd.data.length - 1);
    newIndices = positivifyIndices(newIndices, gd.data.length - 1);

    // at this point, we've coerced the index arrays into predictable forms

    // get the traces that aren't being moved around
    for(i = 0; i < gd.data.length; i++) {

        // if index isn't in currentIndices, include it in ignored!
        if(currentIndices.indexOf(i) === -1) {
            newData.push(gd.data[i]);
        }
    }

    // get a mapping of indices to moving traces
    for(i = 0; i < currentIndices.length; i++) {
        movingTraceMap.push({newIndex: newIndices[i], trace: gd.data[currentIndices[i]]});
    }

    // reorder this mapping by newIndex, ascending
    movingTraceMap.sort(function(a, b) {
        return a.newIndex - b.newIndex;
    });

    // now, add the moving traces back in, in order!
    for(i = 0; i < movingTraceMap.length; i += 1) {
        newData.splice(movingTraceMap[i].newIndex, 0, movingTraceMap[i].trace);
    }

    gd.data = newData;

    var promise = exports.redraw(gd);
    Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);

    return promise;
};

/**
 * restyle: update trace attributes of an existing plot
 *
 * Can be called two ways.
 *
 * Signature 1:
 * @param {String | HTMLDivElement} gd
 *  the id or DOM element of the graph container div
 * @param {String} astr
 *  attribute string (like `'marker.symbol'`) to update
 * @param {*} val
 *  value to give this attribute
 * @param {Number[] | Number} [traces]
 *  integer or array of integers for the traces to alter (all if omitted)
 *
 * Signature 2:
 * @param {String | HTMLDivElement} gd
 *  (as in signature 1)
 * @param {Object} aobj
 *  attribute object `{astr1: val1, astr2: val2 ...}`
 *  allows setting multiple attributes simultaneously
 * @param {Number[] | Number} [traces]
 *  (as in signature 1)
 *
 * `val` (or `val1`, `val2` ... in the object form) can be an array,
 * to apply different values to each trace.
 *
 * If the array is too short, it will wrap around (useful for
 * style files that want to specify cyclical default values).
 */
function restyle(gd, astr, val, _traces) {
    gd = Lib.getGraphDiv(gd);
    helpers.clearPromiseQueue(gd);

    var aobj = {};
    if(typeof astr === 'string') aobj[astr] = val;
    else if(Lib.isPlainObject(astr)) {
        // the 3-arg form
        aobj = Lib.extendFlat({}, astr);
        if(_traces === undefined) _traces = val;
    }
    else {
        Lib.warn('Restyle fail.', astr, val, _traces);
        return Promise.reject();
    }

    if(Object.keys(aobj).length) gd.changed = true;

    var traces = helpers.coerceTraceIndices(gd, _traces);

    var specs = _restyle(gd, aobj, traces);
    var flags = specs.flags;

    // clear calcdata and/or axis types if required so they get regenerated
    if(flags.calc) gd.calcdata = undefined;
    if(flags.clearAxisTypes) helpers.clearAxisTypes(gd, traces, {});

    // fill in redraw sequence
    var seq = [];

    if(flags.fullReplot) {
        seq.push(exports.plot);
    } else {
        seq.push(Plots.previousPromises);

        // maybe only call Plots.supplyDataDefaults in the splom case,
        // to skip over long and slow axes defaults
        Plots.supplyDefaults(gd);

        if(flags.markerSize) {
            Plots.doCalcdata(gd);
            addAxRangeSequence(seq);

            // TODO
            // if all axes have autorange:false, then
            // proceed to subroutines.doTraceStyle(),
            // otherwise we must go through addAxRangeSequence,
            // which in general must redraws 'all' axes
        }

        if(flags.style) seq.push(subroutines.doTraceStyle);
        if(flags.colorbars) seq.push(subroutines.doColorBars);

        seq.push(emitAfterPlot);
    }

    seq.push(Plots.rehover);

    Queue.add(gd,
        restyle, [gd, specs.undoit, specs.traces],
        restyle, [gd, specs.redoit, specs.traces]
    );

    var plotDone = Lib.syncOrAsync(seq, gd);
    if(!plotDone || !plotDone.then) plotDone = Promise.resolve();

    return plotDone.then(function() {
        gd.emit('plotly_restyle', specs.eventData);
        return gd;
    });
}
exports.restyle = restyle;

// for undo: undefined initial vals must be turned into nulls
// so that we unset rather than ignore them
function undefinedToNull(val) {
    if(val === undefined) return null;
    return val;
}

/**
 * Factory function to wrap nestedProperty with GUI edits if necessary
 * with GUI edits we add an optional prefix to the nestedProperty constructor
 * to prepend to the attribute string in the preGUI store.
 */
function makeNP(preGUI, guiEditFlag) {
    if(!guiEditFlag) return nestedProperty;

    return function(container, attr, prefix) {
        var np = nestedProperty(container, attr);
        var npSet = np.set;
        np.set = function(val) {
            var fullAttr = (prefix || '') + attr;
            storeCurrent(fullAttr, np.get(), val, preGUI);
            npSet(val);
        };
        return np;
    };
}

function storeCurrent(attr, val, newVal, preGUI) {
    if(Array.isArray(val) || Array.isArray(newVal)) {
        var arrayVal = Array.isArray(val) ? val : [];
        var arrayNew = Array.isArray(newVal) ? newVal : [];
        var maxLen = Math.max(arrayVal.length, arrayNew.length);
        for(var i = 0; i < maxLen; i++) {
            storeCurrent(attr + '[' + i + ']', arrayVal[i], arrayNew[i], preGUI);
        }
    }
    else if(Lib.isPlainObject(val) || Lib.isPlainObject(newVal)) {
        var objVal = Lib.isPlainObject(val) ? val : {};
        var objNew = Lib.isPlainObject(newVal) ? newVal : {};
        var objBoth = Lib.extendFlat({}, objVal, objNew);
        for(var key in objBoth) {
            storeCurrent(attr + '.' + key, objVal[key], objNew[key], preGUI);
        }
    }
    else if(preGUI[attr] === undefined) {
        preGUI[attr] = undefinedToNull(val);
    }
}

/**
 * storeDirectGUIEdit: for routines that skip restyle/relayout and mock it
 * by emitting a plotly_restyle or plotly_relayout event, this routine
 * keeps track of the initial state in _preGUI for use by uirevision
 * Does *not* apply these changes to data/layout - that's the responsibility
 * of the calling routine.
 *
 * @param {object} container: the input attributes container (eg `layout` or a `trace`)
 * @param {object} preGUI: where original values should be stored, either
 *     `layout._preGUI` or `layout._tracePreGUI[uid]`
 * @param {object} edits: the {attr: val} object as normally passed to `relayout` etc
 */
exports._storeDirectGUIEdit = function(container, preGUI, edits) {
    for(var attr in edits) {
        var np = nestedProperty(container, attr);
        storeCurrent(attr, np.get(), edits[attr], preGUI);
    }
};

function _restyle(gd, aobj, traces) {
    var fullLayout = gd._fullLayout;
    var fullData = gd._fullData;
    var data = gd.data;
    var guiEditFlag = fullLayout._guiEditing;
    var layoutNP = makeNP(fullLayout._preGUI, guiEditFlag);
    var eventData = Lib.extendDeepAll({}, aobj);
    var i;

    cleanDeprecatedAttributeKeys(aobj);

    // initialize flags
    var flags = editTypes.traceFlags();

    // copies of the change (and previous values of anything affected)
    // for the undo / redo queue
    var redoit = {};
    var undoit = {};
    var axlist;

    // make a new empty vals array for undoit
    function a0() { return traces.map(function() { return undefined; }); }

    // for autoranging multiple axes
    function addToAxlist(axid) {
        var axName = Axes.id2name(axid);
        if(axlist.indexOf(axName) === -1) axlist.push(axName);
    }

    function autorangeAttr(axName) { return 'LAYOUT' + axName + '.autorange'; }

    function rangeAttr(axName) { return 'LAYOUT' + axName + '.range'; }

    function getFullTrace(traceIndex) {
        // usually fullData maps 1:1 onto data, but with groupby transforms
        // the fullData index can be greater. Take the *first* matching trace.
        for(var j = traceIndex; j < fullData.length; j++) {
            if(fullData[j]._input === data[traceIndex]) return fullData[j];
        }
        // should never get here - and if we *do* it should cause an error
        // later on undefined fullTrace is passed to nestedProperty.
    }

    // for attrs that interact (like scales & autoscales), save the
    // old vals before making the change
    // val=undefined will not set a value, just record what the value was.
    // val=null will delete the attribute
    // attr can be an array to set several at once (all to the same val)
    function doextra(attr, val, i) {
        if(Array.isArray(attr)) {
            attr.forEach(function(a) { doextra(a, val, i); });
            return;
        }
        // quit if explicitly setting this elsewhere
        if(attr in aobj || helpers.hasParent(aobj, attr)) return;

        var extraparam;
        if(attr.substr(0, 6) === 'LAYOUT') {
            extraparam = layoutNP(gd.layout, attr.replace('LAYOUT', ''));
        } else {
            var tracei = traces[i];
            var preGUI = fullLayout._tracePreGUI[getFullTrace(tracei)._fullInput.uid];
            extraparam = makeNP(preGUI, guiEditFlag)(data[tracei], attr);
        }

        if(!(attr in undoit)) {
            undoit[attr] = a0();
        }
        if(undoit[attr][i] === undefined) {
            undoit[attr][i] = undefinedToNull(extraparam.get());
        }
        if(val !== undefined) {
            extraparam.set(val);
        }
    }

    function allBins(binAttr) {
        return function(j) {
            return fullData[j][binAttr];
        };
    }

    function arrayBins(binAttr) {
        return function(vij, j) {
            return vij === false ? fullData[traces[j]][binAttr] : null;
        };
    }

    // now make the changes to gd.data (and occasionally gd.layout)
    // and figure out what kind of graphics update we need to do
    for(var ai in aobj) {
        if(helpers.hasParent(aobj, ai)) {
            throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously');
        }

        var vi = aobj[ai];
        var cont;
        var contFull;
        var param;
        var oldVal;
        var newVal;
        var valObject;

        // Backward compatibility shim for turning histogram autobin on,
        // or freezing previous autobinned values.
        // Replace obsolete `autobin(x|y): true` with `(x|y)bins: null`
        // and `autobin(x|y): false` with the `(x|y)bins` in `fullData`
        if(ai === 'autobinx' || ai === 'autobiny') {
            ai = ai.charAt(ai.length - 1) + 'bins';
            if(Array.isArray(vi)) vi = vi.map(arrayBins(ai));
            else if(vi === false) vi = traces.map(allBins(ai));
            else vi = null;
        }

        redoit[ai] = vi;

        if(ai.substr(0, 6) === 'LAYOUT') {
            param = layoutNP(gd.layout, ai.replace('LAYOUT', ''));
            undoit[ai] = [undefinedToNull(param.get())];
            // since we're allowing val to be an array, allow it here too,
            // even though that's meaningless
            param.set(Array.isArray(vi) ? vi[0] : vi);
            // ironically, the layout attrs in restyle only require replot,
            // not relayout
            flags.calc = true;
            continue;
        }

        // set attribute in gd.data
        undoit[ai] = a0();
        for(i = 0; i < traces.length; i++) {
            cont = data[traces[i]];
            contFull = getFullTrace(traces[i]);
            var preGUI = fullLayout._tracePreGUI[contFull._fullInput.uid];
            param = makeNP(preGUI, guiEditFlag)(cont, ai);
            oldVal = param.get();
            newVal = Array.isArray(vi) ? vi[i % vi.length] : vi;

            if(newVal === undefined) continue;

            var finalPart = param.parts[param.parts.length - 1];
            var prefix = ai.substr(0, ai.length - finalPart.length - 1);
            var prefixDot = prefix ? prefix + '.' : '';
            var innerContFull = prefix ?
                nestedProperty(contFull, prefix).get() : contFull;

            valObject = PlotSchema.getTraceValObject(contFull, param.parts);

            if(valObject && valObject.impliedEdits && newVal !== null) {
                for(var impliedKey in valObject.impliedEdits) {
                    doextra(Lib.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i);
                }
            }

            // changing colorbar size modes,
            // make the resulting size not change
            // note that colorbar fractional sizing is based on the
            // original plot size, before anything (like a colorbar)
            // increases the margins
            else if((finalPart === 'thicknessmode' || finalPart === 'lenmode') &&
                    oldVal !== newVal &&
                    (newVal === 'fraction' || newVal === 'pixels') &&
                    innerContFull
            ) {
                var gs = fullLayout._size;
                var orient = innerContFull.orient;
                var topOrBottom = (orient === 'top') || (orient === 'bottom');
                if(finalPart === 'thicknessmode') {
                    var thicknorm = topOrBottom ? gs.h : gs.w;
                    doextra(prefixDot + 'thickness', innerContFull.thickness *
                        (newVal === 'fraction' ? 1 / thicknorm : thicknorm), i);
                }
                else {
                    var lennorm = topOrBottom ? gs.w : gs.h;
                    doextra(prefixDot + 'len', innerContFull.len *
                        (newVal === 'fraction' ? 1 / lennorm : lennorm), i);
                }
            }

            else if(ai === 'type' && (newVal === 'pie') !== (oldVal === 'pie')) {
                var labelsTo = 'x';
                var valuesTo = 'y';
                if((newVal === 'bar' || oldVal === 'bar') && cont.orientation === 'h') {
                    labelsTo = 'y';
                    valuesTo = 'x';
                }
                Lib.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo);
                Lib.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo);
                Lib.swapAttrs(cont, ['?', '?src'], 'values', valuesTo);

                if(oldVal === 'pie') {
                    nestedProperty(cont, 'marker.color')
                        .set(nestedProperty(cont, 'marker.colors').get());

                    // super kludgy - but if all pies are gone we won't remove them otherwise
                    fullLayout._pielayer.selectAll('g.trace').remove();
                } else if(Registry.traceIs(cont, 'cartesian')) {
                    nestedProperty(cont, 'marker.colors')
                        .set(nestedProperty(cont, 'marker.color').get());
                }
            }

            undoit[ai][i] = undefinedToNull(oldVal);
            // set the new value - if val is an array, it's one el per trace
            // first check for attributes that get more complex alterations
            var swapAttrs = [
                'swapxy', 'swapxyaxes', 'orientation', 'orientationaxes'
            ];
            if(swapAttrs.indexOf(ai) !== -1) {
                // setting an orientation: make sure it's changing
                // before we swap everything else
                if(ai === 'orientation') {
                    param.set(newVal);
                    // obnoxious that we need this level of coupling... but in order to
                    // properly handle setting orientation to `null` we need to mimic
                    // the logic inside Bars.supplyDefaults for default orientation
                    var defaultOrientation = (cont.x && !cont.y) ? 'h' : 'v';
                    if((param.get() || defaultOrientation) === contFull.orientation) {
                        continue;
                    }
                }
                // orientationaxes has no value,
                // it flips everything and the axes
                else if(ai === 'orientationaxes') {
                    cont.orientation =
                        {v: 'h', h: 'v'}[contFull.orientation];
                }
                helpers.swapXYData(cont);
                flags.calc = flags.clearAxisTypes = true;
            }
            else if(Plots.dataArrayContainers.indexOf(param.parts[0]) !== -1) {
                // TODO: use manageArrays.applyContainerArrayChanges here too
                helpers.manageArrayContainers(param, newVal, undoit);
                flags.calc = true;
            }
            else {
                if(valObject) {
                    // must redo calcdata when restyling array values of arrayOk attributes
                    // ... but no need to this for regl-based traces
                    if(valObject.arrayOk &&
                        !Registry.traceIs(contFull, 'regl') &&
                        (Lib.isArrayOrTypedArray(newVal) || Lib.isArrayOrTypedArray(oldVal))
                    ) {
                        flags.calc = true;
                    }
                    else editTypes.update(flags, valObject);
                }
                else {
                    /*
                     * if we couldn't find valObject,  assume a full recalc.
                     * This can happen if you're changing type and making
                     * some other edits too, so the modules we're
                     * looking at don't have these attributes in them.
                     */
                    flags.calc = true;
                }

                // all the other ones, just modify that one attribute
                param.set(newVal);
            }
        }

        // swap the data attributes of the relevant x and y axes?
        if(['swapxyaxes', 'orientationaxes'].indexOf(ai) !== -1) {
            Axes.swap(gd, traces);
        }

        // swap hovermode if set to "compare x/y data"
        if(ai === 'orientationaxes') {
            var hovermode = nestedProperty(gd.layout, 'hovermode');
            if(hovermode.get() === 'x') {
                hovermode.set('y');
            } else if(hovermode.get() === 'y') {
                hovermode.set('x');
            }
        }

        // Major enough changes deserve autoscale and
        // non-reversed axes so people don't get confused
        //
        // Note: autobin (or its new analog bin clearing) is not included here
        // since we're not pushing bins back to gd.data, so if we have bin
        // info it was explicitly provided by the user.
        if(['orientation', 'type'].indexOf(ai) !== -1) {
            axlist = [];
            for(i = 0; i < traces.length; i++) {
                var trace = data[traces[i]];

                if(Registry.traceIs(trace, 'cartesian')) {
                    addToAxlist(trace.xaxis || 'x');
                    addToAxlist(trace.yaxis || 'y');
                }
            }

            doextra(axlist.map(autorangeAttr), true, 0);
            doextra(axlist.map(rangeAttr), [0, 1], 0);
        }
    }

    if(flags.calc || flags.plot) {
        flags.fullReplot = true;
    }

    return {
        flags: flags,
        undoit: undoit,
        redoit: redoit,
        traces: traces,
        eventData: Lib.extendDeepNoArrays([], [eventData, traces])
    };
}

/**
 * Converts deprecated attribute keys to
 * the current API to ensure backwards compatibility.
 *
 * This is needed for the update mechanism to determine which
 * subroutines to run based on the actual attribute
 * definitions (that don't include the deprecated ones).
 *
 * E.g. Maps {'xaxis.title': 'A chart'} to {'xaxis.title.text': 'A chart'}
 * and {titlefont: {...}} to {'title.font': {...}}.
 *
 * @param aobj
 */
function cleanDeprecatedAttributeKeys(aobj) {
    var oldAxisTitleRegex = Lib.counterRegex('axis', '\.title', false, false);
    var colorbarRegex = /colorbar\.title$/;
    var keys = Object.keys(aobj);
    var i, key, value;

    for(i = 0; i < keys.length; i++) {
        key = keys[i];
        value = aobj[key];

        if((key === 'title' || oldAxisTitleRegex.test(key) || colorbarRegex.test(key)) &&
          (typeof value === 'string' || typeof value === 'number')) {
            replace(key, key.replace('title', 'title.text'));
        } else if(key.indexOf('titlefont') > -1) {
            replace(key, key.replace('titlefont', 'title.font'));
        } else if(key.indexOf('titleposition') > -1) {
            replace(key, key.replace('titleposition', 'title.position'));
        } else if(key.indexOf('titleside') > -1) {
            replace(key, key.replace('titleside', 'title.side'));
        } else if(key.indexOf('titleoffset') > -1) {
            replace(key, key.replace('titleoffset', 'title.offset'));
        }
    }

    function replace(oldAttrStr, newAttrStr) {
        aobj[newAttrStr] = aobj[oldAttrStr];
        delete aobj[oldAttrStr];
    }
}

/**
 * relayout: update layout attributes of an existing plot
 *
 * Can be called two ways:
 *
 * Signature 1:
 * @param {String | HTMLDivElement} gd
 *  the id or dom element of the graph container div
 * @param {String} astr
 *  attribute string (like `'xaxis.range[0]'`) to update
 * @param {*} val
 *  value to give this attribute
 *
 * Signature 2:
 * @param {String | HTMLDivElement} gd
 *  (as in signature 1)
 * @param {Object} aobj
 *  attribute object `{astr1: val1, astr2: val2 ...}`
 *  allows setting multiple attributes simultaneously
 */
function relayout(gd, astr, val) {
    gd = Lib.getGraphDiv(gd);
    helpers.clearPromiseQueue(gd);

    if(gd.framework && gd.framework.isPolar) {
        return Promise.resolve(gd);
    }

    var aobj = {};
    if(typeof astr === 'string') {
        aobj[astr] = val;
    } else if(Lib.isPlainObject(astr)) {
        aobj = Lib.extendFlat({}, astr);
    } else {
        Lib.warn('Relayout fail.', astr, val);
        return Promise.reject();
    }

    if(Object.keys(aobj).length) gd.changed = true;

    var specs = _relayout(gd, aobj);
    var flags = specs.flags;

    // clear calcdata if required
    if(flags.calc) gd.calcdata = undefined;

    // fill in redraw sequence

    // even if we don't have anything left in aobj,
    // something may have happened within relayout that we
    // need to wait for
    var seq = [Plots.previousPromises];

    if(flags.layoutReplot) {
        seq.push(subroutines.layoutReplot);
    }
    else if(Object.keys(aobj).length) {
        axRangeSupplyDefaultsByPass(gd, flags, specs) || Plots.supplyDefaults(gd);

        if(flags.legend) seq.push(subroutines.doLegend);
        if(flags.layoutstyle) seq.push(subroutines.layoutStyles);
        if(flags.axrange) addAxRangeSequence(seq, specs.rangesAltered);
        if(flags.ticks) seq.push(subroutines.doTicksRelayout);
        if(flags.modebar) seq.push(subroutines.doModeBar);
        if(flags.camera) seq.push(subroutines.doCamera);

        seq.push(emitAfterPlot);
    }

    seq.push(Plots.rehover);

    Queue.add(gd,
        relayout, [gd, specs.undoit],
        relayout, [gd, specs.redoit]
    );

    var plotDone = Lib.syncOrAsync(seq, gd);
    if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd);

    return plotDone.then(function() {
        gd.emit('plotly_relayout', specs.eventData);
        return gd;
    });
}
exports.relayout = relayout;

// Optimization mostly for large splom traces where
// Plots.supplyDefaults can take > 100ms
function axRangeSupplyDefaultsByPass(gd, flags, specs) {
    var k;

    if(!flags.axrange) return false;

    for(k in flags) {
        if(k !== 'axrange' && flags[k]) return false;
    }

    for(k in specs.rangesAltered) {
        var axName = Axes.id2name(k);
        var axIn = gd.layout[axName];
        var axOut = gd._fullLayout[axName];
        axOut.autorange = axIn.autorange;
        axOut.range = axIn.range.slice();
        axOut.cleanRange();
    }
    return true;
}

function addAxRangeSequence(seq, rangesAltered) {
    // N.B. leave as sequence of subroutines (for now) instead of
    // subroutine of its own so that finalDraw always gets
    // executed after drawData
    var drawAxes = rangesAltered ?
        function(gd) {
            var opts = {skipTitle: true};
            for(var id in rangesAltered) {
                if(Axes.getFromId(gd, id).automargin) {
                    opts = {};
                    break;
                }
            }
            return Axes.draw(gd, Object.keys(rangesAltered), opts);
        } :
        function(gd) {
            return Axes.draw(gd, 'redraw');
        };

    seq.push(
        subroutines.doAutoRangeAndConstraints,
        drawAxes,
        subroutines.drawData,
        subroutines.finalDraw
    );
}

var AX_RANGE_RE = /^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/;
var AX_AUTORANGE_RE = /^[xyz]axis[0-9]*\.autorange$/;
var AX_DOMAIN_RE = /^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/;

function _relayout(gd, aobj) {
    var layout = gd.layout;
    var fullLayout = gd._fullLayout;
    var guiEditFlag = fullLayout._guiEditing;
    var layoutNP = makeNP(fullLayout._preGUI, guiEditFlag);
    var keys = Object.keys(aobj);
    var axes = Axes.list(gd);
    var eventData = Lib.extendDeepAll({}, aobj);
    var arrayEdits = {};

    var arrayStr, i, j;

    cleanDeprecatedAttributeKeys(aobj);
    keys = Object.keys(aobj);

    // look for 'allaxes', split out into all axes
    // in case of 3D the axis are nested within a scene which is held in _id
    for(i = 0; i < keys.length; i++) {
        if(keys[i].indexOf('allaxes') === 0) {
            for(j = 0; j < axes.length; j++) {
                var scene = axes[j]._id.substr(1);
                var axisAttr = (scene.indexOf('scene') !== -1) ? (scene + '.') : '';
                var newkey = keys[i].replace('allaxes', axisAttr + axes[j]._name);

                if(!aobj[newkey]) aobj[newkey] = aobj[keys[i]];
            }

            delete aobj[keys[i]];
        }
    }

    // initialize flags
    var flags = editTypes.layoutFlags();

    // copies of the change (and previous values of anything affected)
    // for the undo / redo queue
    var redoit = {};
    var undoit = {};

    // for attrs that interact (like scales & autoscales), save the
    // old vals before making the change
    // val=undefined will not set a value, just record what the value was.
    // attr can be an array to set several at once (all to the same val)
    function doextra(attr, val) {
        if(Array.isArray(attr)) {
            attr.forEach(function(a) { doextra(a, val); });
            return;
        }

        // if we have another value for this attribute (explicitly or
        // via a parent) do not override with this auto-generated extra
        if(attr in aobj || helpers.hasParent(aobj, attr)) return;

        var p = layoutNP(layout, attr);
        if(!(attr in undoit)) {
            undoit[attr] = undefinedToNull(p.get());
        }
        if(val !== undefined) p.set(val);
    }

    // for constraint enforcement: keep track of all axes (as {id: name})
    // we're editing the (auto)range of, so we can tell the others constrained
    // to scale with them that it's OK for them to shrink
    var rangesAltered = {};
    var axId;

    function recordAlteredAxis(pleafPlus) {
        var axId = Axes.name2id(pleafPlus.split('.')[0]);
        rangesAltered[axId] = 1;
        return axId;
    }

    // alter gd.layout
    for(var ai in aobj) {
        if(helpers.hasParent(aobj, ai)) {
            throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously');
        }

        var p = layoutNP(layout, ai);
        var vi = aobj[ai];
        var plen = p.parts.length;
        // p.parts may end with an index integer if the property is an array
        var pend = plen - 1;
        while(pend > 0 && typeof p.parts[pend] !== 'string') pend--;
        // last property in chain (leaf node)
        var pleaf = p.parts[pend];
        // leaf plus immediate parent
        var pleafPlus = p.parts[pend - 1] + '.' + pleaf;
        // trunk nodes (everything except the leaf)
        var ptrunk = p.parts.slice(0, pend).join('.');
        var parentIn = nestedProperty(gd.layout, ptrunk).get();
        var parentFull = nestedProperty(fullLayout, ptrunk).get();
        var vOld = p.get();

        if(vi === undefined) continue;

        redoit[ai] = vi;

        // axis reverse is special - it is its own inverse
        // op and has no flag.
        undoit[ai] = (pleaf === 'reverse') ? vi : undefinedToNull(vOld);

        var valObject = PlotSchema.getLayoutValObject(fullLayout, p.parts);

        if(valObject && valObject.impliedEdits && vi !== null) {
            for(var impliedKey in valObject.impliedEdits) {
                doextra(Lib.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]);
            }
        }

        // Setting width or height to null must reset the graph's width / height
        // back to its initial value as computed during the first pass in Plots.plotAutoSize.
        //
        // To do so, we must manually set them back here using the _initialAutoSize cache.
        // can't use impliedEdits for this because behavior depends on vi
        if(['width', 'height'].indexOf(ai) !== -1) {
            if(vi) {
                doextra('autosize', null);
                // currently we don't support autosize one dim only - so
                // explicitly set the other one. Note that doextra will
                // ignore this if the same relayout call also provides oppositeAttr
                var oppositeAttr = ai === 'height' ? 'width' : 'height';
                doextra(oppositeAttr, fullLayout[oppositeAttr]);
            }
            else {
                fullLayout[ai] = gd._initialAutoSize[ai];
            }
        }
        else if(ai === 'autosize') {
            // depends on vi here too, so again can't use impliedEdits
            doextra('width', vi ? null : fullLayout.width);
            doextra('height', vi ? null : fullLayout.height);
        }
        // check autorange vs range
        else if(pleafPlus.match(AX_RANGE_RE)) {
            recordAlteredAxis(pleafPlus);
            nestedProperty(fullLayout, ptrunk + '._inputRange').set(null);
        }
        else if(pleafPlus.match(AX_AUTORANGE_RE)) {
            recordAlteredAxis(pleafPlus);
            nestedProperty(fullLayout, ptrunk + '._inputRange').set(null);
            var axFull = nestedProperty(fullLayout, ptrunk).get();
            if(axFull._inputDomain) {
                // if we're autoranging and this axis has a constrained domain,
                // reset it so we don't get locked into a shrunken size
                axFull._input.domain = axFull._inputDomain.slice();
            }
        }
        else if(pleafPlus.match(AX_DOMAIN_RE)) {
            nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null);
        }

        // toggling axis type between log and linear: we need to convert
        // positions for components that are still using linearized values,
        // not data values like newer components.
        // previously we did this for log <-> not-log, but now only do it
        // for log <-> linear
        if(pleaf === 'type') {
            var ax = parentIn;
            var toLog = parentFull.type === 'linear' && vi === 'log';
            var fromLog = parentFull.type === 'log' && vi === 'linear';

            if(toLog || fromLog) {
                if(!ax || !ax.range) {
                    // 2D never gets here, but 3D does
                    // I don't think this is needed, but left here in case there
                    // are edge cases I'm not thinking of.
                    doextra(ptrunk + '.autorange', true);
                }
                else if(!parentFull.autorange) {
                    // toggling log without autorange: need to also recalculate ranges
                    // because log axes use linearized values for range endpoints
                    var r0 = ax.range[0];
                    var r1 = ax.range[1];
                    if(toLog) {
                        // if both limits are negative, autorange
                        if(r0 <= 0 && r1 <= 0) {
                            doextra(ptrunk + '.autorange', true);
                        }
                        // if one is negative, set it 6 orders below the other.
                        if(r0 <= 0) r0 = r1 / 1e6;
                        else if(r1 <= 0) r1 = r0 / 1e6;
                        // now set the range values as appropriate
                        doextra(ptrunk + '.range[0]', Math.log(r0) / Math.LN10);
                        doextra(ptrunk + '.range[1]', Math.log(r1) / Math.LN10);
                    }
                    else {
                        doextra(ptrunk + '.range[0]', Math.pow(10, r0));
                        doextra(ptrunk + '.range[1]', Math.pow(10, r1));
                    }
                }
                else if(toLog) {
                    // just make sure the range is positive and in the right
                    // order, it'll get recalculated later
                    ax.range = (ax.range[1] > ax.range[0]) ? [1, 2] : [2, 1];
                }

                // clear polar view initial stash for radial range so that
                // value get recomputed in correct units
                if(Array.isArray(fullLayout._subplots.polar) &&
                    fullLayout._subplots.polar.length &&
                    fullLayout[p.parts[0]] &&
                    p.parts[1] === 'radialaxis'
                ) {
                    delete fullLayout[p.parts[0]]._subplot.viewInitial['radialaxis.range'];
                }

                // Annotations and images also need to convert to/from linearized coords
                // Shapes do not need this :)
                Registry.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra);
                Registry.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra);
            }
            else {
                // any other type changes: the range from the previous type
                // will not make sense, so autorange it.
                doextra(ptrunk + '.autorange', true);
                doextra(ptrunk + '.range', null);
            }
            nestedProperty(fullLayout, ptrunk + '._inputRange').set(null);
        }
        else if(pleaf.match(AX_NAME_PATTERN)) {
            var fullProp = nestedProperty(fullLayout, ai).get();
            var newType = (vi || {}).type;

            // This can potentially cause strange behavior if the autotype is not
            // numeric (linear, because we don't auto-log) but the previous type
            // was log. That's a very strange edge case though
            if(!newType || newType === '-') newType = 'linear';
            Registry.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra);
            Registry.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra);
        }

        // alter gd.layout

        // collect array component edits for execution all together
        // so we can ensure consistent behavior adding/removing items
        // and order-independence for add/remove/edit all together in
        // one relayout call
        var containerArrayMatch = manageArrays.containerArrayMatch(ai);
        if(containerArrayMatch) {
            arrayStr = containerArrayMatch.array;
            i = containerArrayMatch.index;
            var propStr = containerArrayMatch.property;
            var updateValObject = valObject || {editType: 'calc'};

            if(i !== '' && propStr === '') {
                // special handling of undoit if we're adding or removing an element
                // ie 'annotations[2]' which can be {...} (add) or null,
                // does not work when replacing the entire array
                if(manageArrays.isAddVal(vi)) {
                    undoit[ai] = null;
                } else if(manageArrays.isRemoveVal(vi)) {
                    undoit[ai] = (nestedProperty(layout, arrayStr).get() || [])[i];
                } else {
                    Lib.warn('unrecognized full object value', aobj);
                }
            }
            editTypes.update(flags, updateValObject);

            // prepare the edits object we'll send to applyContainerArrayChanges
            if(!arrayEdits[arrayStr]) arrayEdits[arrayStr] = {};
            var objEdits = arrayEdits[arrayStr][i];
            if(!objEdits) objEdits = arrayEdits[arrayStr][i] = {};
            objEdits[propStr] = vi;

            delete aobj[ai];
        }
        // handle axis reversal explicitly, as there's no 'reverse' attribute
        else if(pleaf === 'reverse') {
            if(parentIn.range) parentIn.range.reverse();
            else {
                doextra(ptrunk + '.autorange', true);
                parentIn.range = [1, 0];
            }

            if(parentFull.autorange) flags.calc = true;
            else flags.plot = true;
        }
        else {
            if((fullLayout._has('scatter-like') && fullLayout._has('regl')) &&
                (ai === 'dragmode' &&
                (vi === 'lasso' || vi === 'select') &&
                !(vOld === 'lasso' || vOld === 'select'))
            ) {
                flags.plot = true;
            }
            else if(valObject) editTypes.update(flags, valObject);
            else flags.calc = true;

            p.set(vi);
        }
    }

    // now we've collected component edits - execute them all together
    for(arrayStr in arrayEdits) {
        var finished = manageArrays.applyContainerArrayChanges(gd,
            layoutNP(layout, arrayStr), arrayEdits[arrayStr], flags, layoutNP);
        if(!finished) flags.plot = true;
    }

    // figure out if we need to recalculate axis constraints
    var constraints = fullLayout._axisConstraintGroups || [];
    for(axId in rangesAltered) {
        for(i = 0; i < constraints.length; i++) {
            var group = constraints[i];
            if(group[axId]) {
                // Always recalc if we're changing constrained ranges.
                // Otherwise it's possible to violate the constraints by
                // specifying arbitrary ranges for all axes in the group.
                // this way some ranges may expand beyond what's specified,
                // as they do at first draw, to satisfy the constraints.
                flags.calc = true;
                for(var groupAxId in group) {
                    if(!rangesAltered[groupAxId]) {
                        Axes.getFromId(gd, groupAxId)._constraintShrinkable = true;
                    }
                }
            }
        }
    }

    // If the autosize changed or height or width was explicitly specified,
    // this triggers a redraw
    // TODO: do we really need special aobj.height/width handling here?
    // couldn't editType do this?
    if(updateAutosize(gd) || aobj.height || aobj.width) flags.plot = true;

    if(flags.plot || flags.calc) {
        flags.layoutReplot = true;
    }

    // now all attribute mods are done, as are
    // redo and undo so we can save them

    return {
        flags: flags,
        rangesAltered: rangesAltered,
        undoit: undoit,
        redoit: redoit,
        eventData: eventData
    };
}

/*
 * updateAutosize: we made a change, does it change the autosize result?
 * puts the new size into fullLayout
 * returns true if either height or width changed
 */
function updateAutosize(gd) {
    var fullLayout = gd._fullLayout;
    var oldWidth = fullLayout.width;
    var oldHeight = fullLayout.height;

    // calculate autosizing
    if(gd.layout.autosize) Plots.plotAutoSize(gd, gd.layout, fullLayout);

    return (fullLayout.width !== oldWidth) || (fullLayout.height !== oldHeight);
}

/**
 * update: update trace and layout attributes of an existing plot
 *
 * @param {String | HTMLDivElement} gd
 *  the id or DOM element of the graph container div
 * @param {Object} traceUpdate
 *  attribute object `{astr1: val1, astr2: val2 ...}`
 *  corresponding to updates in the plot's traces
 * @param {Object} layoutUpdate
 *  attribute object `{astr1: val1, astr2: val2 ...}`
 *  corresponding to updates in the plot's layout
 * @param {Number[] | Number} [traces]
 *  integer or array of integers for the traces to alter (all if omitted)
 *
 */
function update(gd, traceUpdate, layoutUpdate, _traces) {
    gd = Lib.getGraphDiv(gd);
    helpers.clearPromiseQueue(gd);

    if(gd.framework && gd.framework.isPolar) {
        return Promise.resolve(gd);
    }

    if(!Lib.isPlainObject(traceUpdate)) traceUpdate = {};
    if(!Lib.isPlainObject(layoutUpdate)) layoutUpdate = {};

    if(Object.keys(traceUpdate).length) gd.changed = true;
    if(Object.keys(layoutUpdate).length) gd.changed = true;

    var traces = helpers.coerceTraceIndices(gd, _traces);

    var restyleSpecs = _restyle(gd, Lib.extendFlat({}, traceUpdate), traces);
    var restyleFlags = restyleSpecs.flags;

    var relayoutSpecs = _relayout(gd, Lib.extendFlat({}, layoutUpdate));
    var relayoutFlags = relayoutSpecs.flags;

    // clear calcdata and/or axis types if required
    if(restyleFlags.calc || relayoutFlags.calc) gd.calcdata = undefined;
    if(restyleFlags.clearAxisTypes) helpers.clearAxisTypes(gd, traces, layoutUpdate);

    // fill in redraw sequence
    var seq = [];

    if(restyleFlags.fullReplot && relayoutFlags.layoutReplot) {
        var data = gd.data;
        var layout = gd.layout;

        // clear existing data/layout on gd
        // so that Plotly.plot doesn't try to extend them
        gd.data = undefined;
        gd.layout = undefined;

        seq.push(function() { return exports.plot(gd, data, layout); });
    }
    else if(restyleFlags.fullReplot) {
        seq.push(exports.plot);
    }
    else if(relayoutFlags.layoutReplot) {
        seq.push(subroutines.layoutReplot);
    }
    else {
        seq.push(Plots.previousPromises);
        axRangeSupplyDefaultsByPass(gd, relayoutFlags, relayoutSpecs) || Plots.supplyDefaults(gd);

        if(restyleFlags.style) seq.push(subroutines.doTraceStyle);
        if(restyleFlags.colorbars) seq.push(subroutines.doColorBars);
        if(relayoutFlags.legend) seq.push(subroutines.doLegend);
        if(relayoutFlags.layoutstyle) seq.push(subroutines.layoutStyles);
        if(relayoutFlags.axrange) addAxRangeSequence(seq, relayoutSpecs.rangesAltered);
        if(relayoutFlags.ticks) seq.push(subroutines.doTicksRelayout);
        if(relayoutFlags.modebar) seq.push(subroutines.doModeBar);
        if(relayoutFlags.camera) seq.push(subroutines.doCamera);

        seq.push(emitAfterPlot);
    }

    seq.push(Plots.rehover);

    Queue.add(gd,
        update, [gd, restyleSpecs.undoit, relayoutSpecs.undoit, restyleSpecs.traces],
        update, [gd, restyleSpecs.redoit, relayoutSpecs.redoit, restyleSpecs.traces]
    );

    var plotDone = Lib.syncOrAsync(seq, gd);
    if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd);

    return plotDone.then(function() {
        gd.emit('plotly_update', {
            data: restyleSpecs.eventData,
            layout: relayoutSpecs.eventData
        });

        return gd;
    });
}
exports.update = update;

/*
 * internal-use-only restyle/relayout/update variants that record the initial
 * values in (fullLayout|fullTrace)._preGUI so changes can be persisted across
 * Plotly.react data updates, dependent on uirevision attributes
 */
function guiEdit(func) {
    return function wrappedEdit(gd) {
        gd._fullLayout._guiEditing = true;
        var p = func.apply(null, arguments);
        gd._fullLayout._guiEditing = false;
        return p;
    };
}
exports._guiRestyle = guiEdit(restyle);
exports._guiRelayout = guiEdit(relayout);
exports._guiUpdate = guiEdit(update);

// For connecting edited layout attributes to uirevision attrs
// If no `attr` we use `match[1] + '.uirevision'`
// Ordered by most common edits first, to minimize our search time
var layoutUIControlPatterns = [
    {pattern: /^hiddenlabels/, attr: 'legend.uirevision'},
    {pattern: /^((x|y)axis\d*)\.((auto)?range|title\.text)/},

    // showspikes and modes include those nested inside scenes
    {pattern: /axis\d*\.showspikes$/, attr: 'modebar.uirevision'},
    {pattern: /(hover|drag)mode$/, attr: 'modebar.uirevision'},

    {pattern: /^(scene\d*)\.camera/},
    {pattern: /^(geo\d*)\.(projection|center)/},
    {pattern: /^(ternary\d*\.[abc]axis)\.(min|title\.text)$/},
    {pattern: /^(polar\d*\.radialaxis)\.((auto)?range|angle|title\.text)/},
    {pattern: /^(polar\d*\.angularaxis)\.rotation/},
    {pattern: /^(mapbox\d*)\.(center|zoom|bearing|pitch)/},

    {pattern: /^legend\.(x|y)$/, attr: 'editrevision'},
    {pattern: /^(shapes|annotations)/, attr: 'editrevision'},
    {pattern: /^title\.text$/, attr: 'editrevision'}
];

// same for trace attributes: if `attr` is given it's in layout,
// or with no `attr` we use `trace.uirevision`
var traceUIControlPatterns = [
    {pattern: /^selectedpoints$/, attr: 'selectionrevision'},
    // "visible" includes trace.transforms[i].styles[j].value.visible
    {pattern: /(^|value\.)visible$/, attr: 'legend.uirevision'},
    {pattern: /^dimensions\[\d+\]\.constraintrange/},

    // below this you must be in editable: true mode
    // TODO: I still put name and title with `trace.uirevision`
    // reasonable or should these be `editrevision`?
    // Also applies to axis titles up in the layout section

    // "name" also includes transform.styles
    {pattern: /(^|value\.)name$/},
    // including nested colorbar attributes (ie marker.colorbar)
    {pattern: /colorbar\.title\.text$/},
    {pattern: /colorbar\.(x|y)$/, attr: 'editrevision'}
];

function findUIPattern(key, patternSpecs) {
    for(var i = 0; i < patternSpecs.length; i++) {
        var spec = patternSpecs[i];
        var match = key.match(spec.pattern);
        if(match) {
            return {head: match[1], attr: spec.attr};
        }
    }
}

// We're finding the new uirevision before supplyDefaults, so do the
// inheritance manually. Note that only `undefined` inherits - other
// falsy values are returned.
function getNewRev(revAttr, container) {
    var newRev = nestedProperty(container, revAttr).get();
    if(newRev !== undefined) return newRev;

    var parts = revAttr.split('.');
    parts.pop();
    while(parts.length > 1) {
        parts.pop();
        newRev = nestedProperty(container, parts.join('.') + '.uirevision').get();
        if(newRev !== undefined) return newRev;
    }

    return container.uirevision;
}

function getFullTraceIndexFromUid(uid, fullData) {
    for(var i = 0; i < fullData.length; i++) {
        if(fullData[i]._fullInput.uid === uid) return i;
    }
    return -1;
}

function getTraceIndexFromUid(uid, data, tracei) {
    for(var i = 0; i < data.length; i++) {
        if(data[i].uid === uid) return i;
    }
    // fall back on trace order, but only if user didn't provide a uid for that trace
    return (!data[tracei] || data[tracei].uid) ? -1 : tracei;
}

function valsMatch(v1, v2) {
    var v1IsObj = Lib.isPlainObject(v1);
    var v1IsArray = Array.isArray(v1);
    if(v1IsObj || v1IsArray) {
        return (
            (v1IsObj && Lib.isPlainObject(v2)) ||
            (v1IsArray && Array.isArray(v2))
        ) && JSON.stringify(v1) === JSON.stringify(v2);
    }
    return v1 === v2;
}

function applyUIRevisions(data, layout, oldFullData, oldFullLayout) {
    var layoutPreGUI = oldFullLayout._preGUI;
    var key, revAttr, oldRev, newRev, match, preGUIVal, newNP, newVal;
    var bothInheritAutorange = [];
    var newRangeAccepted = {};
    for(key in layoutPreGUI) {
        match = findUIPattern(key, layoutUIControlPatterns);
        if(match) {
            revAttr = match.attr || (match.head + '.uirevision');
            oldRev = nestedProperty(oldFullLayout, revAttr).get();
            newRev = oldRev && getNewRev(revAttr, layout);
            if(newRev && (newRev === oldRev)) {
                preGUIVal = layoutPreGUI[key];
                if(preGUIVal === null) preGUIVal = undefined;
                newNP = nestedProperty(layout, key);
                newVal = newNP.get();
                if(valsMatch(newVal, preGUIVal)) {
                    if(newVal === undefined && key.substr(key.length - 9) === 'autorange') {
                        bothInheritAutorange.push(key.substr(0, key.length - 10));
                    }
                    newNP.set(undefinedToNull(nestedProperty(oldFullLayout, key).get()));
                    continue;
                }
            }
        }
        else {
            Lib.warn('unrecognized GUI edit: ' + key);
        }
        // if we got this far, the new value was accepted as the new starting
        // point (either because it changed or revision changed)
        // so remove it from _preGUI for next time.
        delete layoutPreGUI[key];

        if(key.substr(key.length - 8, 6) === 'range[') {
            newRangeAccepted[key.substr(0, key.length - 9)] = 1;
        }
    }

    // Special logic for `autorange`, since it interacts with `range`:
    // If the new figure's matching `range` was kept, and `autorange`
    // wasn't supplied explicitly in either the original or the new figure,
    // we shouldn't alter that - but we may just have done that, so fix it.
    for(var i = 0; i < bothInheritAutorange.length; i++) {
        var axAttr = bothInheritAutorange[i];
        if(newRangeAccepted[axAttr]) {
            var newAx = nestedProperty(layout, axAttr).get();
            if(newAx) delete newAx.autorange;
        }
    }

    // Now traces - try to match them up by uid (in case we added/deleted in
    // the middle), then fall back on index.
    var allTracePreGUI = oldFullLayout._tracePreGUI;
    for(var uid in allTracePreGUI) {
        var tracePreGUI = allTracePreGUI[uid];
        var newTrace = null;
        var fullInput;
        for(key in tracePreGUI) {
            // wait until we know we have preGUI values to look for traces
            // but if we don't find both, stop looking at this uid
            if(!newTrace) {
                var fulli = getFullTraceIndexFromUid(uid, oldFullData);
                if(fulli < 0) {
                    // Somehow we didn't even have this trace in oldFullData...
                    // I guess this could happen with `deleteTraces` or something
                    delete allTracePreGUI[uid];
                    break;
                }
                var fullTrace = oldFullData[fulli];
                fullInput = fullTrace._fullInput;

                var newTracei = getTraceIndexFromUid(uid, data, fullInput.index);
                if(newTracei < 0) {
                    // No match in new data
                    delete allTracePreGUI[uid];
                    break;
                }
                newTrace = data[newTracei];
            }

            match = findUIPattern(key, traceUIControlPatterns);
            if(match) {
                if(match.attr) {
                    oldRev = nestedProperty(oldFullLayout, match.attr).get();
                    newRev = oldRev && getNewRev(match.attr, layout);
                }
                else {
                    oldRev = fullInput.uirevision;
                    // inheritance for trace.uirevision is simple, just layout.uirevision
                    newRev = newTrace.uirevision;
                    if(newRev === undefined) newRev = layout.uirevision;
                }

                if(newRev && newRev === oldRev) {
                    preGUIVal = tracePreGUI[key];
                    if(preGUIVal === null) preGUIVal = undefined;
                    newNP = nestedProperty(newTrace, key);
                    newVal = newNP.get();
                    if(valsMatch(newVal, preGUIVal)) {
                        newNP.set(undefinedToNull(nestedProperty(fullInput, key).get()));
                        continue;
                    }
                }
            }
            else {
                Lib.warn('unrecognized GUI edit: ' + key + ' in trace uid ' + uid);
            }
            delete tracePreGUI[key];
        }
    }
}

/**
 * Plotly.react:
 * A plot/update method that takes the full plot state (same API as plot/newPlot)
 * and diffs to determine the minimal update pathway
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 * @param {array of objects} data
 *      array of traces, containing the data and display information for each trace
 * @param {object} layout
 *      object describing the overall display of the plot,
 *      all the stuff that doesn't pertain to any individual trace
 * @param {object} config
 *      configuration options (see ./plot_config.js for more info)
 *
 * OR
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 * @param {object} figure
 *      object containing `data`, `layout`, `config`, and `frames` members
 *
 */
exports.react = function(gd, data, layout, config) {
    var frames, plotDone;

    function addFrames() { return exports.addFrames(gd, frames); }

    gd = Lib.getGraphDiv(gd);

    var oldFullData = gd._fullData;
    var oldFullLayout = gd._fullLayout;

    // you can use this as the initial draw as well as to update
    if(!Lib.isPlotDiv(gd) || !oldFullData || !oldFullLayout) {
        plotDone = exports.newPlot(gd, data, layout, config);
    }
    else {

        if(Lib.isPlainObject(data)) {
            var obj = data;
            data = obj.data;
            layout = obj.layout;
            config = obj.config;
            frames = obj.frames;
        }

        var configChanged = false;
        // assume that if there's a config at all, we're reacting to it too,
        // and completely replace the previous config
        if(config) {
            var oldConfig = Lib.extendDeep({}, gd._context);
            gd._context = undefined;
            setPlotContext(gd, config);
            configChanged = diffConfig(oldConfig, gd._context);
        }

        gd.data = data || [];
        helpers.cleanData(gd.data);
        gd.layout = layout || {};
        helpers.cleanLayout(gd.layout);

        applyUIRevisions(gd.data, gd.layout, oldFullData, oldFullLayout);

        // "true" skips updating calcdata and remapping arrays from calcTransforms,
        // which supplyDefaults usually does at the end, but we may need to NOT do
        // if the diff (which we haven't determined yet) says we'll recalc
        Plots.supplyDefaults(gd, {skipUpdateCalc: true});

        var newFullData = gd._fullData;
        var newFullLayout = gd._fullLayout;
        var immutable = newFullLayout.datarevision === undefined;
        var transition = newFullLayout.transition;

        var relayoutFlags = diffLayout(gd, oldFullLayout, newFullLayout, immutable, transition);
        var newDataRevision = relayoutFlags.newDataRevision;
        var restyleFlags = diffData(gd, oldFullData, newFullData, immutable, transition, newDataRevision);

        // TODO: how to translate this part of relayout to Plotly.react?
        // // Setting width or height to null must reset the graph's width / height
        // // back to its initial value as computed during the first pass in Plots.plotAutoSize.
        // //
        // // To do so, we must manually set them back here using the _initialAutoSize cache.
        // if(['width', 'height'].indexOf(ai) !== -1 && vi === null) {
        //     fullLayout[ai] = gd._initialAutoSize[ai];
        // }

        if(updateAutosize(gd)) relayoutFlags.layoutReplot = true;

        // clear calcdata if required
        if(restyleFlags.calc || relayoutFlags.calc) gd.calcdata = undefined;
        // otherwise do the calcdata updates and calcTransform array remaps that we skipped earlier
        else Plots.supplyDefaultsUpdateCalc(gd.calcdata, newFullData);

        // Note: what restyle/relayout use impliedEdits and clearAxisTypes for
        // must be handled by the user when using Plotly.react.

        // fill in redraw sequence
        var seq = [];

        if(frames) {
            gd._transitionData = {};
            Plots.createTransitionData(gd);
            seq.push(addFrames);
        }

        // Transition pathway,
        // only used when 'transition' is set by user and
        // when at least one animatable attribute has changed,
        // N.B. config changed aren't animatable
        if(newFullLayout.transition && !configChanged && (restyleFlags.anim || relayoutFlags.anim)) {
            Plots.doCalcdata(gd);
            subroutines.doAutoRangeAndConstraints(gd);

            seq.push(function() {
                return Plots.transitionFromReact(gd, restyleFlags, relayoutFlags, oldFullLayout);
            });
        }
        else if(restyleFlags.fullReplot || relayoutFlags.layoutReplot || configChanged) {
            gd._fullLayout._skipDefaults = true;
            seq.push(exports.plot);
        }
        else {
            for(var componentType in relayoutFlags.arrays) {
                var indices = relayoutFlags.arrays[componentType];
                if(indices.length) {
                    var drawOne = Registry.getComponentMethod(componentType, 'drawOne');
                    if(drawOne !== Lib.noop) {
                        for(var i = 0; i < indices.length; i++) {
                            drawOne(gd, indices[i]);
                        }
                    }
                    else {
                        var draw = Registry.getComponentMethod(componentType, 'draw');
                        if(draw === Lib.noop) {
                            throw new Error('cannot draw components: ' + componentType);
                        }
                        draw(gd);
                    }
                }
            }

            seq.push(Plots.previousPromises);
            if(restyleFlags.style) seq.push(subroutines.doTraceStyle);
            if(restyleFlags.colorbars) seq.push(subroutines.doColorBars);
            if(relayoutFlags.legend) seq.push(subroutines.doLegend);
            if(relayoutFlags.layoutstyle) seq.push(subroutines.layoutStyles);
            if(relayoutFlags.axrange) addAxRangeSequence(seq);
            if(relayoutFlags.ticks) seq.push(subroutines.doTicksRelayout);
            if(relayoutFlags.modebar) seq.push(subroutines.doModeBar);
            if(relayoutFlags.camera) seq.push(subroutines.doCamera);
            seq.push(emitAfterPlot);
        }

        seq.push(Plots.rehover);

        plotDone = Lib.syncOrAsync(seq, gd);
        if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd);
    }

    return plotDone.then(function() {
        gd.emit('plotly_react', {
            data: data,
            layout: layout
        });

        return gd;
    });

};

function diffData(gd, oldFullData, newFullData, immutable, transition, newDataRevision) {
    var sameTraceLength = oldFullData.length === newFullData.length;

    if(!transition && !sameTraceLength) {
        return {
            fullReplot: true,
            calc: true
        };
    }

    var flags = editTypes.traceFlags();
    flags.arrays = {};
    flags.nChanges = 0;
    flags.nChangesAnim = 0;

    var i, trace;

    function getTraceValObject(parts) {
        return PlotSchema.getTraceValObject(trace, parts);
    }

    var diffOpts = {
        getValObject: getTraceValObject,
        flags: flags,
        immutable: immutable,
        transition: transition,
        newDataRevision: newDataRevision,
        gd: gd
    };

    var seenUIDs = {};

    for(i = 0; i < oldFullData.length; i++) {
        if(newFullData[i]) {
            trace = newFullData[i]._fullInput;
            if(Plots.hasMakesDataTransform(trace)) trace = newFullData[i];
            if(seenUIDs[trace.uid]) continue;
            seenUIDs[trace.uid] = 1;

            getDiffFlags(oldFullData[i]._fullInput, trace, [], diffOpts);
        }
    }

    if(flags.calc || flags.plot) {
        flags.fullReplot = true;
    }

    if(transition && flags.nChanges && flags.nChangesAnim) {
        flags.anim = (flags.nChanges === flags.nChangesAnim) && sameTraceLength ? 'all' : 'some';
    }

    return flags;
}

function diffLayout(gd, oldFullLayout, newFullLayout, immutable, transition) {
    var flags = editTypes.layoutFlags();
    flags.arrays = {};
    flags.rangesAltered = {};
    flags.nChanges = 0;
    flags.nChangesAnim = 0;

    function getLayoutValObject(parts) {
        return PlotSchema.getLayoutValObject(newFullLayout, parts);
    }

    var diffOpts = {
        getValObject: getLayoutValObject,
        flags: flags,
        immutable: immutable,
        transition: transition,
        gd: gd
    };

    getDiffFlags(oldFullLayout, newFullLayout, [], diffOpts);

    if(flags.plot || flags.calc) {
        flags.layoutReplot = true;
    }

    if(transition && flags.nChanges && flags.nChangesAnim) {
        flags.anim = flags.nChanges === flags.nChangesAnim ? 'all' : 'some';
    }

    return flags;
}

function getDiffFlags(oldContainer, newContainer, outerparts, opts) {
    var valObject, key, astr;

    var getValObject = opts.getValObject;
    var flags = opts.flags;
    var immutable = opts.immutable;
    var inArray = opts.inArray;
    var arrayIndex = opts.arrayIndex;

    function changed() {
        var editType = valObject.editType;
        if(inArray && editType.indexOf('arraydraw') !== -1) {
            Lib.pushUnique(flags.arrays[inArray], arrayIndex);
            return;
        }
        editTypes.update(flags, valObject);

        if(editType !== 'none') {
            flags.nChanges++;
        }

        // track animatable changes
        if(opts.transition && valObject.anim) {
            flags.nChangesAnim++;
        }

        // track cartesian axes with altered ranges
        if(AX_RANGE_RE.test(astr) || AX_AUTORANGE_RE.test(astr)) {
            flags.rangesAltered[outerparts[0]] = 1;
        }

        // clear _inputDomain on cartesian axes with altered domains
        if(AX_DOMAIN_RE.test(astr)) {
            nestedProperty(newContainer, '_inputDomain').set(null);
        }

        // track datarevision changes
        if(key === 'datarevision') {
            flags.newDataRevision = 1;
        }
    }

    function valObjectCanBeDataArray(valObject) {
        return valObject.valType === 'data_array' || valObject.arrayOk;
    }

    for(key in oldContainer) {
        // short-circuit based on previous calls or previous keys that already maximized the pathway
        if(flags.calc && !opts.transition) return;

        var oldVal = oldContainer[key];
        var newVal = newContainer[key];
        var parts = outerparts.concat(key);
        astr = parts.join('.');

        if(key.charAt(0) === '_' || typeof oldVal === 'function' || oldVal === newVal) continue;

        // FIXME: ax.tick0 and dtick get filled in during plotting (except for geo subplots),
        // and unlike other auto values they don't make it back into the input,
        // so newContainer won't have them.
        if((key === 'tick0' || key === 'dtick') && outerparts[0] !== 'geo') {
            var tickMode = newContainer.tickmode;
            if(tickMode === 'auto' || tickMode === 'array' || !tickMode) continue;
        }
        // FIXME: Similarly for axis ranges for 3D
        // contourcarpet doesn't HAVE zmin/zmax, they're just auto-added. It needs them.
        if(key === 'range' && newContainer.autorange) continue;
        if((key === 'zmin' || key === 'zmax') && newContainer.type === 'contourcarpet') continue;

        valObject = getValObject(parts);

        // in case type changed, we may not even *have* a valObject.
        if(!valObject) continue;

        if(valObject._compareAsJSON && JSON.stringify(oldVal) === JSON.stringify(newVal)) continue;

        var valType = valObject.valType;
        var i;

        var canBeDataArray = valObjectCanBeDataArray(valObject);
        var wasArray = Array.isArray(oldVal);
        var nowArray = Array.isArray(newVal);

        // hack for traces that modify the data in supplyDefaults, like
        // converting 1D to 2D arrays, which will always create new objects
        if(wasArray && nowArray) {
            var inputKey = '_input_' + key;
            var oldValIn = oldContainer[inputKey];
            var newValIn = newContainer[inputKey];
            if(Array.isArray(oldValIn) && oldValIn === newValIn) continue;
        }

        if(newVal === undefined) {
            if(canBeDataArray && wasArray) flags.calc = true;
            else changed();
        }
        else if(valObject._isLinkedToArray) {
            var arrayEditIndices = [];
            var extraIndices = false;
            if(!inArray) flags.arrays[key] = arrayEditIndices;

            var minLen = Math.min(oldVal.length, newVal.length);
            var maxLen = Math.max(oldVal.length, newVal.length);
            if(minLen !== maxLen) {
                if(valObject.editType === 'arraydraw') {
                    extraIndices = true;
                }
                else {
                    changed();
                    continue;
                }
            }

            for(i = 0; i < minLen; i++) {
                getDiffFlags(oldVal[i], newVal[i], parts.concat(i),
                    // add array indices, but not if we're already in an array
                    Lib.extendFlat({inArray: key, arrayIndex: i}, opts));
            }

            // put this at the end so that we know our collected array indices are sorted
            // but the check for length changes happens up front so we can short-circuit
            // diffing if appropriate
            if(extraIndices) {
                for(i = minLen; i < maxLen; i++) {
                    arrayEditIndices.push(i);
                }
            }
        }
        else if(!valType && Lib.isPlainObject(oldVal)) {
            getDiffFlags(oldVal, newVal, parts, opts);
        }
        else if(canBeDataArray) {
            if(wasArray && nowArray) {

                // don't try to diff two data arrays. If immutable we know the data changed,
                // if not, assume it didn't and let `layout.datarevision` tell us if it did
                if(immutable) {
                    flags.calc = true;
                }

                // look for animatable attributes when the data changed
                if(immutable || opts.newDataRevision) {
                    changed();
                }
            }
            else if(wasArray !== nowArray) {
                flags.calc = true;
            }
            else changed();
        }
        else if(wasArray && nowArray) {
            // info array, colorscale, 'any' - these are short, just stringify.
            // I don't *think* that covers up any real differences post-validation, does it?
            // otherwise we need to dive in 1 (info_array) or 2 (colorscale) levels and compare
            // all elements.
            if(oldVal.length !== newVal.length || String(oldVal) !== String(newVal)) {
                changed();
            }
        }
        else {
            changed();
        }
    }

    for(key in newContainer) {
        if(!(key in oldContainer || key.charAt(0) === '_' || typeof newContainer[key] === 'function')) {
            valObject = getValObject(outerparts.concat(key));

            if(valObjectCanBeDataArray(valObject) && Array.isArray(newContainer[key])) {
                flags.calc = true;
                return;
            }
            else changed();
        }
    }
}

/*
 * simple diff for config - for now, just treat all changes as equivalent
 */
function diffConfig(oldConfig, newConfig) {
    var key;

    for(key in oldConfig) {
        if(key.charAt(0) === '_') continue;
        var oldVal = oldConfig[key];
        var newVal = newConfig[key];
        if(oldVal !== newVal) {
            if(Lib.isPlainObject(oldVal) && Lib.isPlainObject(newVal)) {
                if(diffConfig(oldVal, newVal)) {
                    return true;
                }
            }
            else if(Array.isArray(oldVal) && Array.isArray(newVal)) {
                if(oldVal.length !== newVal.length) {
                    return true;
                }
                for(var i = 0; i < oldVal.length; i++) {
                    if(oldVal[i] !== newVal[i]) {
                        if(Lib.isPlainObject(oldVal[i]) && Lib.isPlainObject(newVal[i])) {
                            if(diffConfig(oldVal[i], newVal[i])) {
                                return true;
                            }
                        }
                        else {
                            return true;
                        }
                    }
                }
            }
            else {
                return true;
            }
        }
    }
}

/**
 * Animate to a frame, sequence of frame, frame group, or frame definition
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 *
 * @param {string or object or array of strings or array of objects} frameOrGroupNameOrFrameList
 *      a single frame, array of frames, or group to which to animate. The intent is
 *      inferred by the type of the input. Valid inputs are:
 *
 *      - string, e.g. 'groupname': animate all frames of a given `group` in the order
 *            in which they are defined via `Plotly.addFrames`.
 *
 *      - array of strings, e.g. ['frame1', frame2']: a list of frames by name to which
 *            to animate in sequence
 *
 *      - object: {data: ...}: a frame definition to which to animate. The frame is not
 *            and does not need to be added via `Plotly.addFrames`. It may contain any of
 *            the properties of a frame, including `data`, `layout`, and `traces`. The
 *            frame is used as provided and does not use the `baseframe` property.
 *
 *      - array of objects, e.g. [{data: ...}, {data: ...}]: a list of frame objects,
 *            each following the same rules as a single `object`.
 *
 * @param {object} animationOpts
 *      configuration for the animation
 */
exports.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts) {
    gd = Lib.getGraphDiv(gd);

    if(!Lib.isPlotDiv(gd)) {
        throw new Error(
            'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' +
            'to create a plot before animating it. For more details, see ' +
            'https://plot.ly/javascript/animations/'
        );
    }

    var trans = gd._transitionData;

    // This is the queue of frames that will be animated as soon as possible. They
    // are popped immediately upon the *start* of a transition:
    if(!trans._frameQueue) {
        trans._frameQueue = [];
    }

    animationOpts = Plots.supplyAnimationDefaults(animationOpts);
    var transitionOpts = animationOpts.transition;
    var frameOpts = animationOpts.frame;

    // Since frames are popped immediately, an empty queue only means all frames have
    // *started* to transition, not that the animation is complete. To solve that,
    // track a separate counter that increments at the same time as frames are added
    // to the queue, but decrements only when the transition is complete.
    if(trans._frameWaitingCnt === undefined) {
        trans._frameWaitingCnt = 0;
    }

    function getTransitionOpts(i) {
        if(Array.isArray(transitionOpts)) {
            if(i >= transitionOpts.length) {
                return transitionOpts[0];
            } else {
                return transitionOpts[i];
            }
        } else {
            return transitionOpts;
        }
    }

    function getFrameOpts(i) {
        if(Array.isArray(frameOpts)) {
            if(i >= frameOpts.length) {
                return frameOpts[0];
            } else {
                return frameOpts[i];
            }
        } else {
            return frameOpts;
        }
    }

    // Execute a callback after the wrapper function has been called n times.
    // This is used to defer the resolution until a transition has resovled *and*
    // the frame has completed. If it's not done this way, then we get a race
    // condition in which the animation might resolve before a transition is complete
    // or vice versa.
    function callbackOnNthTime(cb, n) {
        var cnt = 0;
        return function() {
            if(cb && ++cnt === n) {
                return cb();
            }
        };
    }

    return new Promise(function(resolve, reject) {
        function discardExistingFrames() {
            if(trans._frameQueue.length === 0) {
                return;
            }

            while(trans._frameQueue.length) {
                var next = trans._frameQueue.pop();
                if(next.onInterrupt) {
                    next.onInterrupt();
                }
            }

            gd.emit('plotly_animationinterrupted', []);
        }

        function queueFrames(frameList) {
            if(frameList.length === 0) return;

            for(var i = 0; i < frameList.length; i++) {
                var computedFrame;

                if(frameList[i].type === 'byname') {
                    // If it's a named frame, compute it:
                    computedFrame = Plots.computeFrame(gd, frameList[i].name);
                } else {
                    // Otherwise we must have been given a simple object, so treat
                    // the input itself as the computed frame.
                    computedFrame = frameList[i].data;
                }

                var frameOpts = getFrameOpts(i);
                var transitionOpts = getTransitionOpts(i);

                // It doesn't make much sense for the transition duration to be greater than
                // the frame duration, so limit it:
                transitionOpts.duration = Math.min(transitionOpts.duration, frameOpts.duration);

                var nextFrame = {
                    frame: computedFrame,
                    name: frameList[i].name,
                    frameOpts: frameOpts,
                    transitionOpts: transitionOpts,
                };
                if(i === frameList.length - 1) {
                    // The last frame in this .animate call stores the promise resolve
                    // and reject callbacks. This is how we ensure that the animation
                    // loop (which may exist as a result of a *different* .animate call)
                    // still resolves or rejecdts this .animate call's promise. once it's
                    // complete.
                    nextFrame.onComplete = callbackOnNthTime(resolve, 2);
                    nextFrame.onInterrupt = reject;
                }

                trans._frameQueue.push(nextFrame);
            }

            // Set it as never having transitioned to a frame. This will cause the animation
            // loop to immediately transition to the next frame (which, for immediate mode,
            // is the first frame in the list since all others would have been discarded
            // below)
            if(animationOpts.mode === 'immediate') {
                trans._lastFrameAt = -Infinity;
            }

            // Only it's not already running, start a RAF loop. This could be avoided in the
            // case that there's only one frame, but it significantly complicated the logic
            // and only sped things up by about 5% or so for a lorenz attractor simulation.
            // It would be a fine thing to implement, but the benefit of that optimization
            // doesn't seem worth the extra complexity.
            if(!trans._animationRaf) {
                beginAnimationLoop();
            }
        }

        function stopAnimationLoop() {
            gd.emit('plotly_animated');

            // Be sure to unset also since it's how we know whether a loop is already running:
            window.cancelAnimationFrame(trans._animationRaf);
            trans._animationRaf = null;
        }

        function nextFrame() {
            if(trans._currentFrame && trans._currentFrame.onComplete) {
                // Execute the callback and unset it to ensure it doesn't
                // accidentally get called twice
                trans._currentFrame.onComplete();
            }

            var newFrame = trans._currentFrame = trans._frameQueue.shift();

            if(newFrame) {
                // Since it's sometimes necessary to do deep digging into frame data,
                // we'll consider it not 100% impossible for nulls or numbers to sneak through,
                // so check when casting the name, just to be absolutely certain:
                var stringName = newFrame.name ? newFrame.name.toString() : null;
                gd._fullLayout._currentFrame = stringName;

                trans._lastFrameAt = Date.now();
                trans._timeToNext = newFrame.frameOpts.duration;

                // This is simply called and it's left to .transition to decide how to manage
                // interrupting current transitions. That means we don't need to worry about
                // how it resolves or what happens after this:
                Plots.transition(gd,
                    newFrame.frame.data,
                    newFrame.frame.layout,
                    helpers.coerceTraceIndices(gd, newFrame.frame.traces),
                    newFrame.frameOpts,
                    newFrame.transitionOpts
                ).then(function() {
                    if(newFrame.onComplete) {
                        newFrame.onComplete();
                    }

                });

                gd.emit('plotly_animatingframe', {
                    name: stringName,
                    frame: newFrame.frame,
                    animation: {
                        frame: newFrame.frameOpts,
                        transition: newFrame.transitionOpts,
                    }
                });
            } else {
                // If there are no more frames, then stop the RAF loop:
                stopAnimationLoop();
            }
        }

        function beginAnimationLoop() {
            gd.emit('plotly_animating');

            // If no timer is running, then set last frame = long ago so that the next
            // frame is immediately transitioned:
            trans._lastFrameAt = -Infinity;
            trans._timeToNext = 0;
            trans._runningTransitions = 0;
            trans._currentFrame = null;

            var doFrame = function() {
                // This *must* be requested before nextFrame since nextFrame may decide
                // to cancel it if there's nothing more to animated:
                trans._animationRaf = window.requestAnimationFrame(doFrame);

                // Check if we're ready for a new frame:
                if(Date.now() - trans._lastFrameAt > trans._timeToNext) {
                    nextFrame();
                }
            };

            doFrame();
        }

        // This is an animate-local counter that helps match up option input list
        // items with the particular frame.
        var configCounter = 0;
        function setTransitionConfig(frame) {
            if(Array.isArray(transitionOpts)) {
                if(configCounter >= transitionOpts.length) {
                    frame.transitionOpts = transitionOpts[configCounter];
                } else {
                    frame.transitionOpts = transitionOpts[0];
                }
            } else {
                frame.transitionOpts = transitionOpts;
            }
            configCounter++;
            return frame;
        }

        // Disambiguate what's sort of frames have been received
        var i, frame;
        var frameList = [];
        var allFrames = frameOrGroupNameOrFrameList === undefined || frameOrGroupNameOrFrameList === null;
        var isFrameArray = Array.isArray(frameOrGroupNameOrFrameList);
        var isSingleFrame = !allFrames && !isFrameArray && Lib.isPlainObject(frameOrGroupNameOrFrameList);

        if(isSingleFrame) {
            // In this case, a simple object has been passed to animate.
            frameList.push({
                type: 'object',
                data: setTransitionConfig(Lib.extendFlat({}, frameOrGroupNameOrFrameList))
            });
        } else if(allFrames || ['string', 'number'].indexOf(typeof frameOrGroupNameOrFrameList) !== -1) {
            // In this case, null or undefined has been passed so that we want to
            // animate *all* currently defined frames
            for(i = 0; i < trans._frames.length; i++) {
                frame = trans._frames[i];

                if(!frame) continue;

                if(allFrames || String(frame.group) === String(frameOrGroupNameOrFrameList)) {
                    frameList.push({
                        type: 'byname',
                        name: String(frame.name),
                        data: setTransitionConfig({name: frame.name})
                    });
                }
            }
        } else if(isFrameArray) {
            for(i = 0; i < frameOrGroupNameOrFrameList.length; i++) {
                var frameOrName = frameOrGroupNameOrFrameList[i];
                if(['number', 'string'].indexOf(typeof frameOrName) !== -1) {
                    frameOrName = String(frameOrName);
                    // In this case, there's an array and this frame is a string name:
                    frameList.push({
                        type: 'byname',
                        name: frameOrName,
                        data: setTransitionConfig({name: frameOrName})
                    });
                } else if(Lib.isPlainObject(frameOrName)) {
                    frameList.push({
                        type: 'object',
                        data: setTransitionConfig(Lib.extendFlat({}, frameOrName))
                    });
                }
            }
        }

        // Verify that all of these frames actually exist; return and reject if not:
        for(i = 0; i < frameList.length; i++) {
            frame = frameList[i];
            if(frame.type === 'byname' && !trans._frameHash[frame.data.name]) {
                Lib.warn('animate failure: frame not found: "' + frame.data.name + '"');
                reject();
                return;
            }
        }

        // If the mode is either next or immediate, then all currently queued frames must
        // be dumped and the corresponding .animate promises rejected.
        if(['next', 'immediate'].indexOf(animationOpts.mode) !== -1) {
            discardExistingFrames();
        }

        if(animationOpts.direction === 'reverse') {
            frameList.reverse();
        }

        var currentFrame = gd._fullLayout._currentFrame;
        if(currentFrame && animationOpts.fromcurrent) {
            var idx = -1;
            for(i = 0; i < frameList.length; i++) {
                frame = frameList[i];
                if(frame.type === 'byname' && frame.name === currentFrame) {
                    idx = i;
                    break;
                }
            }

            if(idx > 0 && idx < frameList.length - 1) {
                var filteredFrameList = [];
                for(i = 0; i < frameList.length; i++) {
                    frame = frameList[i];
                    if(frameList[i].type !== 'byname' || i > idx) {
                        filteredFrameList.push(frame);
                    }
                }
                frameList = filteredFrameList;
            }
        }

        if(frameList.length > 0) {
            queueFrames(frameList);
        } else {
            // This is the case where there were simply no frames. It's a little strange
            // since there's not much to do:
            gd.emit('plotly_animated');
            resolve();
        }
    });
};

/**
 * Register new frames
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 *
 * @param {array of objects} frameList
 *      list of frame definitions, in which each object includes any of:
 *      - name: {string} name of frame to add
 *      - data: {array of objects} trace data
 *      - layout {object} layout definition
 *      - traces {array} trace indices
 *      - baseframe {string} name of frame from which this frame gets defaults
 *
 *  @param {array of integers} indices
 *      an array of integer indices matching the respective frames in `frameList`. If not
 *      provided, an index will be provided in serial order. If already used, the frame
 *      will be overwritten.
 */
exports.addFrames = function(gd, frameList, indices) {
    gd = Lib.getGraphDiv(gd);

    if(frameList === null || frameList === undefined) {
        return Promise.resolve();
    }

    if(!Lib.isPlotDiv(gd)) {
        throw new Error(
            'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' +
            'to create a plot before adding frames. For more details, see ' +
            'https://plot.ly/javascript/animations/'
        );
    }

    var i, frame, j, idx;
    var _frames = gd._transitionData._frames;
    var _frameHash = gd._transitionData._frameHash;


    if(!Array.isArray(frameList)) {
        throw new Error('addFrames failure: frameList must be an Array of frame definitions' + frameList);
    }

    // Create a sorted list of insertions since we run into lots of problems if these
    // aren't in ascending order of index:
    //
    // Strictly for sorting. Make sure this is guaranteed to never collide with any
    // already-exisisting indices:
    var bigIndex = _frames.length + frameList.length * 2;

    var insertions = [];
    var _frameHashLocal = {};
    for(i = frameList.length - 1; i >= 0; i--) {
        if(!Lib.isPlainObject(frameList[i])) continue;

        // The entire logic for checking for this type of name collision can be removed once we migrate to ES6 and
        // use a Map instead of an Object instance, as Map keys aren't converted to strings.
        var lookupName = frameList[i].name;
        var name = (_frameHash[lookupName] || _frameHashLocal[lookupName] || {}).name;
        var newName = frameList[i].name;
        var collisionPresent = _frameHash[name] || _frameHashLocal[name];

        if(name && newName && typeof newName === 'number' && collisionPresent && numericNameWarningCount < numericNameWarningCountLimit) {
            numericNameWarningCount++;

            Lib.warn('addFrames: overwriting frame "' + (_frameHash[name] || _frameHashLocal[name]).name +
                '" with a frame whose name of type "number" also equates to "' +
                name + '". This is valid but may potentially lead to unexpected ' +
                'behavior since all plotly.js frame names are stored internally ' +
                'as strings.');

            if(numericNameWarningCount === numericNameWarningCountLimit) {
                Lib.warn('addFrames: This API call has yielded too many of these warnings. ' +
                    'For the rest of this call, further warnings about numeric frame ' +
                    'names will be suppressed.');
            }
        }

        _frameHashLocal[lookupName] = {name: lookupName};

        insertions.push({
            frame: Plots.supplyFrameDefaults(frameList[i]),
            index: (indices && indices[i] !== undefined && indices[i] !== null) ? indices[i] : bigIndex + i
        });
    }

    // Sort this, taking note that undefined insertions end up at the end:
    insertions.sort(function(a, b) {
        if(a.index > b.index) return -1;
        if(a.index < b.index) return 1;
        return 0;
    });

    var ops = [];
    var revops = [];
    var frameCount = _frames.length;

    for(i = insertions.length - 1; i >= 0; i--) {
        frame = insertions[i].frame;

        if(typeof frame.name === 'number') {
            Lib.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' +
                'implicitly cast to strings');

        }

        if(!frame.name) {
            // Repeatedly assign a default name, incrementing the counter each time until
            // we get a name that's not in the hashed lookup table:
            while(_frameHash[(frame.name = 'frame ' + gd._transitionData._counter++)]);
        }

        if(_frameHash[frame.name]) {
            // If frame is present, overwrite its definition:
            for(j = 0; j < _frames.length; j++) {
                if((_frames[j] || {}).name === frame.name) break;
            }
            ops.push({type: 'replace', index: j, value: frame});
            revops.unshift({type: 'replace', index: j, value: _frames[j]});
        } else {
            // Otherwise insert it at the end of the list:
            idx = Math.max(0, Math.min(insertions[i].index, frameCount));

            ops.push({type: 'insert', index: idx, value: frame});
            revops.unshift({type: 'delete', index: idx});
            frameCount++;
        }
    }

    var undoFunc = Plots.modifyFrames;
    var redoFunc = Plots.modifyFrames;
    var undoArgs = [gd, revops];
    var redoArgs = [gd, ops];

    if(Queue) Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);

    return Plots.modifyFrames(gd, ops);
};

/**
 * Delete frame
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 *
 * @param {array of integers} frameList
 *      list of integer indices of frames to be deleted
 */
exports.deleteFrames = function(gd, frameList) {
    gd = Lib.getGraphDiv(gd);

    if(!Lib.isPlotDiv(gd)) {
        throw new Error('This element is not a Plotly plot: ' + gd);
    }

    var i, idx;
    var _frames = gd._transitionData._frames;
    var ops = [];
    var revops = [];

    if(!frameList) {
        frameList = [];
        for(i = 0; i < _frames.length; i++) {
            frameList.push(i);
        }
    }

    frameList = frameList.slice(0);
    frameList.sort();

    for(i = frameList.length - 1; i >= 0; i--) {
        idx = frameList[i];
        ops.push({type: 'delete', index: idx});
        revops.unshift({type: 'insert', index: idx, value: _frames[idx]});
    }

    var undoFunc = Plots.modifyFrames;
    var redoFunc = Plots.modifyFrames;
    var undoArgs = [gd, revops];
    var redoArgs = [gd, ops];

    if(Queue) Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);

    return Plots.modifyFrames(gd, ops);
};

/**
 * Purge a graph container div back to its initial pre-Plotly.plot state
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 */
exports.purge = function purge(gd) {
    gd = Lib.getGraphDiv(gd);

    var fullLayout = gd._fullLayout || {};
    var fullData = gd._fullData || [];

    // remove gl contexts
    Plots.cleanPlot([], {}, fullData, fullLayout);

    // purge properties
    Plots.purge(gd);

    // purge event emitter methods
    Events.purge(gd);

    // remove plot container
    if(fullLayout._container) fullLayout._container.remove();

    // in contrast to Plotly.Plots.purge which does NOT clear _context!
    delete gd._context;

    return gd;
};

// -------------------------------------------------------
// makePlotFramework: Create the plot container and axes
// -------------------------------------------------------
function makePlotFramework(gd) {
    var gd3 = d3.select(gd);
    var fullLayout = gd._fullLayout;

    // Plot container
    fullLayout._container = gd3.selectAll('.plot-container').data([0]);
    fullLayout._container.enter().insert('div', ':first-child')
        .classed('plot-container', true)
        .classed('plotly', true);

    // Make the svg container
    fullLayout._paperdiv = fullLayout._container.selectAll('.svg-container').data([0]);
    fullLayout._paperdiv.enter().append('div')
        .classed('svg-container', true)
        .style('position', 'relative');

    // Make the graph containers
    // start fresh each time we get here, so we know the order comes out
    // right, rather than enter/exit which can muck up the order
    // TODO: sort out all the ordering so we don't have to
    // explicitly delete anything
    // FIXME: parcoords reuses this object, not the best pattern
    fullLayout._glcontainer = fullLayout._paperdiv.selectAll('.gl-container')
        .data([{}]);

    fullLayout._glcontainer.enter().append('div')
        .classed('gl-container', true);

    fullLayout._paperdiv.selectAll('.main-svg').remove();

    fullLayout._paper = fullLayout._paperdiv.insert('svg', ':first-child')
        .classed('main-svg', true);

    fullLayout._toppaper = fullLayout._paperdiv.append('svg')
        .classed('main-svg', true);

    if(!fullLayout._uid) {
        var otherUids = {};
        d3.selectAll('defs').each(function() {
            if(this.id) otherUids[this.id.split('-')[1]] = 1;
        });
        fullLayout._uid = Lib.randstr(otherUids);
    }

    fullLayout._paperdiv.selectAll('.main-svg')
        .attr(xmlnsNamespaces.svgAttrs);

    fullLayout._defs = fullLayout._paper.append('defs')
        .attr('id', 'defs-' + fullLayout._uid);

    fullLayout._clips = fullLayout._defs.append('g')
        .classed('clips', true);

    fullLayout._topdefs = fullLayout._toppaper.append('defs')
        .attr('id', 'topdefs-' + fullLayout._uid);

    fullLayout._topclips = fullLayout._topdefs.append('g')
        .classed('clips', true);

    fullLayout._bgLayer = fullLayout._paper.append('g')
        .classed('bglayer', true);

    fullLayout._draggers = fullLayout._paper.append('g')
        .classed('draglayer', true);

    // lower shape/image layer - note that this is behind
    // all subplots data/grids but above the backgrounds
    // except inset subplots, whose backgrounds are drawn
    // inside their own group so that they appear above
    // the data for the main subplot
    // lower shapes and images which are fully referenced to
    // a subplot still get drawn within the subplot's group
    // so they will work correctly on insets
    var layerBelow = fullLayout._paper.append('g')
        .classed('layer-below', true);
    fullLayout._imageLowerLayer = layerBelow.append('g')
        .classed('imagelayer', true);
    fullLayout._shapeLowerLayer = layerBelow.append('g')
        .classed('shapelayer', true);

    // single cartesian layer for the whole plot
    fullLayout._cartesianlayer = fullLayout._paper.append('g').classed('cartesianlayer', true);

    // single polar layer for the whole plot
    fullLayout._polarlayer = fullLayout._paper.append('g').classed('polarlayer', true);

    // single ternary layer for the whole plot
    fullLayout._ternarylayer = fullLayout._paper.append('g').classed('ternarylayer', true);

    // single geo layer for the whole plot
    fullLayout._geolayer = fullLayout._paper.append('g').classed('geolayer', true);

    // single pie layer for the whole plot
    fullLayout._pielayer = fullLayout._paper.append('g').classed('pielayer', true);

    // fill in image server scrape-svg
    fullLayout._glimages = fullLayout._paper.append('g').classed('glimages', true);

    // lastly upper shapes, info (legend, annotations) and hover layers go on top
    // these are in a different svg element normally, but get collapsed into a single
    // svg when exporting (after inserting 3D)
    // upper shapes/images are only those drawn above the whole plot, including subplots
    var layerAbove = fullLayout._toppaper.append('g')
        .classed('layer-above', true);
    fullLayout._imageUpperLayer = layerAbove.append('g')
        .classed('imagelayer', true);
    fullLayout._shapeUpperLayer = layerAbove.append('g')
        .classed('shapelayer', true);

    fullLayout._infolayer = fullLayout._toppaper.append('g').classed('infolayer', true);
    fullLayout._menulayer = fullLayout._toppaper.append('g').classed('menulayer', true);
    fullLayout._zoomlayer = fullLayout._toppaper.append('g').classed('zoomlayer', true);
    fullLayout._hoverlayer = fullLayout._toppaper.append('g').classed('hoverlayer', true);

    gd.emit('plotly_framework');
}

},{"../components/color":571,"../components/colorbar/connect":573,"../components/drawing":592,"../constants/xmlns_namespaces":672,"../lib":694,"../lib/events":683,"../lib/queue":709,"../lib/svg_text_utils":718,"../plots/cartesian/axes":742,"../plots/cartesian/constants":748,"../plots/cartesian/graph_interact":752,"../plots/plots":806,"../plots/polar/legacy":814,"../registry":825,"./edit_types":725,"./helpers":726,"./manage_arrays":728,"./plot_config":730,"./plot_schema":731,"./subroutines":733,"d3":149,"fast-isnumeric":215,"has-hover":396}],730:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * This will be transferred over to gd and overridden by
 * config args to Plotly.plot.
 *
 * The defaults are the appropriate settings for plotly.js,
 * so we get the right experience without any config argument.
 *
 * N.B. the config options are not coerced using Lib.coerce so keys
 * like `valType` and `values` are only set for documentation purposes
 * at the moment.
 */

var configAttributes = {
    staticPlot: {
        valType: 'boolean',
        dflt: false,
        
    },

    plotlyServerURL: {
        valType: 'string',
        dflt: 'https://plot.ly',
        
    },

    editable: {
        valType: 'boolean',
        dflt: false,
        
    },
    edits: {
        annotationPosition: {
            valType: 'boolean',
            dflt: false,
            
        },
        annotationTail: {
            valType: 'boolean',
            dflt: false,
            
        },
        annotationText: {
            valType: 'boolean',
            dflt: false,
            
        },
        axisTitleText: {
            valType: 'boolean',
            dflt: false,
            
        },
        colorbarPosition: {
            valType: 'boolean',
            dflt: false,
            
        },
        colorbarTitleText: {
            valType: 'boolean',
            dflt: false,
            
        },
        legendPosition: {
            valType: 'boolean',
            dflt: false,
            
        },
        legendText: {
            valType: 'boolean',
            dflt: false,
            
        },
        shapePosition: {
            valType: 'boolean',
            dflt: false,
            
        },
        titleText: {
            valType: 'boolean',
            dflt: false,
            
        }
    },

    autosizable: {
        valType: 'boolean',
        dflt: false,
        
    },
    responsive: {
        valType: 'boolean',
        dflt: false,
        
    },
    fillFrame: {
        valType: 'boolean',
        dflt: false,
        
    },
    frameMargins: {
        valType: 'number',
        dflt: 0,
        min: 0,
        max: 0.5,
        
    },

    scrollZoom: {
        valType: 'flaglist',
        flags: ['cartesian', 'gl3d', 'geo', 'mapbox'],
        extras: [true, false],
        dflt: 'gl3d+geo+mapbox',
        
    },
    doubleClick: {
        valType: 'enumerated',
        values: [false, 'reset', 'autosize', 'reset+autosize'],
        dflt: 'reset+autosize',
        
    },

    showAxisDragHandles: {
        valType: 'boolean',
        dflt: true,
        
    },
    showAxisRangeEntryBoxes: {
        valType: 'boolean',
        dflt: true,
        
    },

    showTips: {
        valType: 'boolean',
        dflt: true,
        
    },

    showLink: {
        valType: 'boolean',
        dflt: false,
        
    },
    linkText: {
        valType: 'string',
        dflt: 'Edit chart',
        noBlank: true,
        
    },
    sendData: {
        valType: 'boolean',
        dflt: true,
        
    },
    showSources: {
        valType: 'any',
        dflt: false,
        
    },

    displayModeBar: {
        valType: 'enumerated',
        values: ['hover', true, false],
        dflt: 'hover',
        
    },
    showSendToCloud: {
        valType: 'boolean',
        dflt: false,
        
    },
    modeBarButtonsToRemove: {
        valType: 'any',
        dflt: [],
        
    },
    modeBarButtonsToAdd: {
        valType: 'any',
        dflt: [],
        
    },
    modeBarButtons: {
        valType: 'any',
        dflt: false,
        
    },
    toImageButtonOptions: {
        valType: 'any',
        dflt: {},
        
    },
    displaylogo: {
        valType: 'boolean',
        dflt: true,
        
    },
    watermark: {
        valType: 'boolean',
        dflt: false,
        
    },

    plotGlPixelRatio: {
        valType: 'number',
        dflt: 2,
        min: 1,
        max: 4,
        
    },

    setBackground: {
        valType: 'any',
        dflt: 'transparent',
        
    },

    topojsonURL: {
        valType: 'string',
        noBlank: true,
        dflt: 'https://cdn.plot.ly/',
        
    },

    mapboxAccessToken: {
        valType: 'string',
        dflt: null,
        
    },

    logging: {
        valType: 'boolean',
        dflt: 1,
        
    },

    queueLength: {
        valType: 'integer',
        min: 0,
        dflt: 0,
        
    },

    globalTransforms: {
        valType: 'any',
        dflt: [],
        
    },

    locale: {
        valType: 'string',
        dflt: 'en-US',
        
    },

    locales: {
        valType: 'any',
        dflt: {},
        
    }
};

var dfltConfig = {};

function crawl(src, target) {
    for(var k in src) {
        var obj = src[k];
        if(obj.valType) {
            target[k] = obj.dflt;
        } else {
            if(!target[k]) {
                target[k] = {};
            }
            crawl(obj, target[k]);
        }
    }
}

crawl(configAttributes, dfltConfig);

module.exports = {
    configAttributes: configAttributes,
    dfltConfig: dfltConfig
};

},{}],731:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../registry');
var Lib = _dereq_('../lib');

var baseAttributes = _dereq_('../plots/attributes');
var baseLayoutAttributes = _dereq_('../plots/layout_attributes');
var frameAttributes = _dereq_('../plots/frame_attributes');
var animationAttributes = _dereq_('../plots/animation_attributes');
var configAttributes = _dereq_('./plot_config').configAttributes;

// polar attributes are not part of the Registry yet
var polarAreaAttrs = _dereq_('../plots/polar/legacy/area_attributes');
var polarAxisAttrs = _dereq_('../plots/polar/legacy/axis_attributes');

var editTypes = _dereq_('./edit_types');

var extendFlat = Lib.extendFlat;
var extendDeepAll = Lib.extendDeepAll;
var isPlainObject = Lib.isPlainObject;

var IS_SUBPLOT_OBJ = '_isSubplotObj';
var IS_LINKED_TO_ARRAY = '_isLinkedToArray';
var ARRAY_ATTR_REGEXPS = '_arrayAttrRegexps';
var DEPRECATED = '_deprecated';
var UNDERSCORE_ATTRS = [IS_SUBPLOT_OBJ, IS_LINKED_TO_ARRAY, ARRAY_ATTR_REGEXPS, DEPRECATED];

exports.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ;
exports.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY;
exports.DEPRECATED = DEPRECATED;
exports.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS;

/** Outputs the full plotly.js plot schema
 *
 * @return {object}
 *  - defs
 *  - traces
 *  - layout
 *  - transforms
 *  - frames
 *  - animations
 *  - config
 */
exports.get = function() {
    var traces = {};

    Registry.allTypes.concat('area').forEach(function(type) {
        traces[type] = getTraceAttributes(type);
    });

    var transforms = {};

    Object.keys(Registry.transformsRegistry).forEach(function(type) {
        transforms[type] = getTransformAttributes(type);
    });

    return {
        defs: {
            valObjects: Lib.valObjectMeta,
            metaKeys: UNDERSCORE_ATTRS.concat(['description', 'role', 'editType', 'impliedEdits']),
            editType: {
                traces: editTypes.traces,
                layout: editTypes.layout
            },
            impliedEdits: {
                
            }
        },

        traces: traces,
        layout: getLayoutAttributes(),

        transforms: transforms,

        frames: getFramesAttributes(),
        animation: formatAttributes(animationAttributes),

        config: formatAttributes(configAttributes)
    };
};

/**
 * Crawl the attribute tree, recursively calling a callback function
 *
 * @param {object} attrs
 *  The node of the attribute tree (e.g. the root) from which recursion originates
 * @param {Function} callback
 *  A callback function with the signature:
 *          @callback callback
 *          @param {object} attr an attribute
 *          @param {String} attrName name string
 *          @param {object[]} attrs all the attributes
 *          @param {Number} level the recursion level, 0 at the root
 *          @param {String} fullAttrString full attribute name (ie 'marker.line')
 * @param {Number} [specifiedLevel]
 *  The level in the tree, in order to let the callback function detect descend or backtrack,
 *  typically unsupplied (implied 0), just used by the self-recursive call.
 *  The necessity arises because the tree traversal is not controlled by callback return values.
 *  The decision to not use callback return values for controlling tree pruning arose from
 *  the goal of keeping the crawler backwards compatible. Observe that one of the pruning conditions
 *  precedes the callback call.
 * @param {string} [attrString]
 *  the path to the current attribute, as an attribute string (ie 'marker.line')
 *  typically unsupplied, but you may supply it if you want to disambiguate which attrs tree you
 *  are starting from
 *
 * @return {object} transformOut
 *  copy of transformIn that contains attribute defaults
 */
exports.crawl = function(attrs, callback, specifiedLevel, attrString) {
    var level = specifiedLevel || 0;
    attrString = attrString || '';

    Object.keys(attrs).forEach(function(attrName) {
        var attr = attrs[attrName];

        if(UNDERSCORE_ATTRS.indexOf(attrName) !== -1) return;

        var fullAttrString = (attrString ? attrString + '.' : '') + attrName;
        callback(attr, attrName, attrs, level, fullAttrString);

        if(exports.isValObject(attr)) return;

        if(isPlainObject(attr) && attrName !== 'impliedEdits') {
            exports.crawl(attr, callback, level + 1, fullAttrString);
        }
    });
};

/** Is object a value object (or a container object)?
 *
 * @param {object} obj
 * @return {boolean}
 *  returns true for a valid value object and
 *  false for tree nodes in the attribute hierarchy
 */
exports.isValObject = function(obj) {
    return obj && obj.valType !== undefined;
};

/**
 * Find all data array attributes in a given trace object - including
 * `arrayOk` attributes.
 *
 * @param {object} trace
 *  full trace object that contains a reference to `_module.attributes`
 *
 * @return {array} arrayAttributes
 *  list of array attributes for the given trace
 */
exports.findArrayAttributes = function(trace) {
    var arrayAttributes = [];
    var stack = [];
    var isArrayStack = [];
    var baseContainer, baseAttrName;

    function callback(attr, attrName, attrs, level) {
        stack = stack.slice(0, level).concat([attrName]);
        isArrayStack = isArrayStack.slice(0, level).concat([attr && attr._isLinkedToArray]);

        var splittableAttr = (
            attr &&
            (attr.valType === 'data_array' || attr.arrayOk === true) &&
            !(stack[level - 1] === 'colorbar' && (attrName === 'ticktext' || attrName === 'tickvals'))
        );

        // Manually exclude 'colorbar.tickvals' and 'colorbar.ticktext' for now
        // which are declared as `valType: 'data_array'` but scale independently of
        // the coordinate arrays.
        //
        // Down the road, we might want to add a schema field (e.g `uncorrelatedArray: true`)
        // to distinguish attributes of the likes.

        if(!splittableAttr) return;

        crawlIntoTrace(baseContainer, 0, '');
    }

    function crawlIntoTrace(container, i, astrPartial) {
        var item = container[stack[i]];
        var newAstrPartial = astrPartial + stack[i];
        if(i === stack.length - 1) {
            if(Lib.isArrayOrTypedArray(item)) {
                arrayAttributes.push(baseAttrName + newAstrPartial);
            }
        }
        else {
            if(isArrayStack[i]) {
                if(Array.isArray(item)) {
                    for(var j = 0; j < item.length; j++) {
                        if(Lib.isPlainObject(item[j])) {
                            crawlIntoTrace(item[j], i + 1, newAstrPartial + '[' + j + '].');
                        }
                    }
                }
            }
            else if(Lib.isPlainObject(item)) {
                crawlIntoTrace(item, i + 1, newAstrPartial + '.');
            }
        }
    }

    baseContainer = trace;
    baseAttrName = '';
    exports.crawl(baseAttributes, callback);
    if(trace._module && trace._module.attributes) {
        exports.crawl(trace._module.attributes, callback);
    }

    var transforms = trace.transforms;
    if(transforms) {
        for(var i = 0; i < transforms.length; i++) {
            var transform = transforms[i];
            var module = transform._module;

            if(module) {
                baseAttrName = 'transforms[' + i + '].';
                baseContainer = transform;

                exports.crawl(module.attributes, callback);
            }
        }
    }

    return arrayAttributes;
};

/*
 * Find the valObject for one attribute in an existing trace
 *
 * @param {object} trace
 *  full trace object that contains a reference to `_module.attributes`
 * @param {object} parts
 *  an array of parts, like ['transforms', 1, 'value']
 *  typically from nestedProperty(...).parts
 *
 * @return {object|false}
 *  the valObject for this attribute, or the last found parent
 *  in some cases the innermost valObject will not exist, for example
 *  `valType: 'any'` attributes where we might set a part of the attribute.
 *  In that case, stop at the deepest valObject we *do* find.
 */
exports.getTraceValObject = function(trace, parts) {
    var head = parts[0];
    var i = 1; // index to start recursing from
    var moduleAttrs, valObject;

    if(head === 'transforms') {
        if(parts.length === 1) {
            return baseAttributes.transforms;
        }
        var transforms = trace.transforms;
        if(!Array.isArray(transforms) || !transforms.length) return false;
        var tNum = parts[1];
        if(!isIndex(tNum) || tNum >= transforms.length) {
            return false;
        }
        moduleAttrs = (Registry.transformsRegistry[transforms[tNum].type] || {}).attributes;
        valObject = moduleAttrs && moduleAttrs[parts[2]];
        i = 3; // start recursing only inside the transform
    }
    else if(trace.type === 'area') {
        valObject = polarAreaAttrs[head];
    }
    else {
        // first look in the module for this trace
        // components have already merged their trace attributes in here
        var _module = trace._module;
        if(!_module) _module = (Registry.modules[trace.type || baseAttributes.type.dflt] || {})._module;
        if(!_module) return false;

        moduleAttrs = _module.attributes;
        valObject = moduleAttrs && moduleAttrs[head];

        // then look in the subplot attributes
        if(!valObject) {
            var subplotModule = _module.basePlotModule;
            if(subplotModule && subplotModule.attributes) {
                valObject = subplotModule.attributes[head];
            }
        }

        // finally look in the global attributes
        if(!valObject) valObject = baseAttributes[head];
    }

    return recurseIntoValObject(valObject, parts, i);
};

/*
 * Find the valObject for one layout attribute
 *
 * @param {array} parts
 *  an array of parts, like ['annotations', 1, 'x']
 *  typically from nestedProperty(...).parts
 *
 * @return {object|false}
 *  the valObject for this attribute, or the last found parent
 *  in some cases the innermost valObject will not exist, for example
 *  `valType: 'any'` attributes where we might set a part of the attribute.
 *  In that case, stop at the deepest valObject we *do* find.
 */
exports.getLayoutValObject = function(fullLayout, parts) {
    var valObject = layoutHeadAttr(fullLayout, parts[0]);

    return recurseIntoValObject(valObject, parts, 1);
};

function layoutHeadAttr(fullLayout, head) {
    var i, key, _module, attributes;

    // look for attributes of the subplot types used on the plot
    var basePlotModules = fullLayout._basePlotModules;
    if(basePlotModules) {
        var out;
        for(i = 0; i < basePlotModules.length; i++) {
            _module = basePlotModules[i];
            if(_module.attrRegex && _module.attrRegex.test(head)) {
                // if a module defines overrides, these take precedence
                // initially this is to allow gl2d different editTypes from svg cartesian
                if(_module.layoutAttrOverrides) return _module.layoutAttrOverrides;

                // otherwise take the first attributes we find
                if(!out && _module.layoutAttributes) out = _module.layoutAttributes;
            }

            // a module can also override the behavior of base (and component) module layout attrs
            // again see gl2d for initial use case
            var baseOverrides = _module.baseLayoutAttrOverrides;
            if(baseOverrides && head in baseOverrides) return baseOverrides[head];
        }
        if(out) return out;
    }

    // look for layout attributes contributed by traces on the plot
    var modules = fullLayout._modules;
    if(modules) {
        for(i = 0; i < modules.length; i++) {
            attributes = modules[i].layoutAttributes;
            if(attributes && head in attributes) {
                return attributes[head];
            }
        }
    }

    /*
     * Next look in components.
     * Components that define a schema have already merged this into
     * base and subplot attribute defs, so ignore these.
     * Others (older style) all put all their attributes
     * inside a container matching the module `name`
     * eg `attributes` (array) or `legend` (object)
     */
    for(key in Registry.componentsRegistry) {
        _module = Registry.componentsRegistry[key];
        if(!_module.schema && (head === _module.name)) {
            return _module.layoutAttributes;
        }
    }

    if(head in baseLayoutAttributes) return baseLayoutAttributes[head];

    // Polar doesn't populate _modules or _basePlotModules
    // just fall back on these when the others fail
    if(head === 'radialaxis' || head === 'angularaxis') {
        return polarAxisAttrs[head];
    }
    return polarAxisAttrs.layout[head] || false;
}

function recurseIntoValObject(valObject, parts, i) {
    if(!valObject) return false;

    if(valObject._isLinkedToArray) {
        // skip array index, abort if we try to dive into an array without an index
        if(isIndex(parts[i])) i++;
        else if(i < parts.length) return false;
    }

    // now recurse as far as we can. Occasionally we have an attribute
    // setting an internal part below what's in the schema; just return
    // the innermost schema item we find.
    for(; i < parts.length; i++) {
        var newValObject = valObject[parts[i]];
        if(isPlainObject(newValObject)) valObject = newValObject;
        else break;

        if(i === parts.length - 1) break;

        if(valObject._isLinkedToArray) {
            i++;
            if(!isIndex(parts[i])) return false;
        }
        else if(valObject.valType === 'info_array') {
            i++;
            var index = parts[i];
            if(!isIndex(index)) return false;

            var items = valObject.items;
            if(Array.isArray(items)) {
                if(index >= items.length) return false;
                if(valObject.dimensions === 2) {
                    i++;
                    if(parts.length === i) return valObject;
                    var index2 = parts[i];
                    if(!isIndex(index2)) return false;
                    valObject = items[index][index2];
                }
                else valObject = items[index];
            }
            else {
                valObject = items;
            }
        }
    }

    return valObject;
}

// note: this is different from Lib.isIndex, this one doesn't accept numeric
// strings, only actual numbers.
function isIndex(val) {
    return val === Math.round(val) && val >= 0;
}

function getTraceAttributes(type) {
    var _module, basePlotModule;

    if(type === 'area') {
        _module = { attributes: polarAreaAttrs };
        basePlotModule = {};
    }
    else {
        _module = Registry.modules[type]._module,
        basePlotModule = _module.basePlotModule;
    }

    var attributes = {};

    // make 'type' the first attribute in the object
    attributes.type = null;


    var copyBaseAttributes = extendDeepAll({}, baseAttributes);
    var copyModuleAttributes = extendDeepAll({}, _module.attributes);

    // prune global-level trace attributes that are already defined in a trace
    exports.crawl(copyModuleAttributes, function(attr, attrName, attrs, level, fullAttrString) {
        Lib.nestedProperty(copyBaseAttributes, fullAttrString).set(undefined);
        // Prune undefined attributes
        if(attr === undefined) Lib.nestedProperty(copyModuleAttributes, fullAttrString).set(undefined);
    });

    // base attributes (same for all trace types)
    extendDeepAll(attributes, copyBaseAttributes);

    // module attributes
    extendDeepAll(attributes, copyModuleAttributes);

    // subplot attributes
    if(basePlotModule.attributes) {
        extendDeepAll(attributes, basePlotModule.attributes);
    }

    // 'type' gets overwritten by baseAttributes; reset it here
    attributes.type = type;

    var out = {
        meta: _module.meta || {},
        attributes: formatAttributes(attributes),
    };

    // trace-specific layout attributes
    if(_module.layoutAttributes) {
        var layoutAttributes = {};

        extendDeepAll(layoutAttributes, _module.layoutAttributes);
        out.layoutAttributes = formatAttributes(layoutAttributes);
    }

    return out;
}

function getLayoutAttributes() {
    var layoutAttributes = {};
    var key, _module;

    // global layout attributes
    extendDeepAll(layoutAttributes, baseLayoutAttributes);

    // add base plot module layout attributes
    for(key in Registry.subplotsRegistry) {
        _module = Registry.subplotsRegistry[key];

        if(!_module.layoutAttributes) continue;

        if(Array.isArray(_module.attr)) {
            for(var i = 0; i < _module.attr.length; i++) {
                handleBasePlotModule(layoutAttributes, _module, _module.attr[i]);
            }
        } else {
            var astr = _module.attr === 'subplot' ? _module.name : _module.attr;
            handleBasePlotModule(layoutAttributes, _module, astr);
        }
    }

    // polar layout attributes
    layoutAttributes = assignPolarLayoutAttrs(layoutAttributes);

    // add registered components layout attributes
    for(key in Registry.componentsRegistry) {
        _module = Registry.componentsRegistry[key];
        var schema = _module.schema;

        /*
         * Components with defined schema have already been merged in at register time
         * but a few components define attributes that apply only to xaxis
         * not yaxis (rangeselector, rangeslider) - delete from y schema.
         * Note that the input attributes for xaxis/yaxis are the same object
         * so it's not possible to only add them to xaxis from the start.
         * If we ever have such asymmetry the other way, or anywhere else,
         * we will need to extend both this code and mergeComponentAttrsToSubplot
         * (which will not find yaxis only for example)
         */
        if(schema && (schema.subplots || schema.layout)) {
            var subplots = schema.subplots;
            if(subplots && subplots.xaxis && !subplots.yaxis) {
                for(var xkey in subplots.xaxis) delete layoutAttributes.yaxis[xkey];
            }
        }
        // older style without schema need to be explicitly merged in now
        else if(_module.layoutAttributes) {
            insertAttrs(layoutAttributes, _module.layoutAttributes, _module.name);
        }
    }

    return {
        layoutAttributes: formatAttributes(layoutAttributes)
    };
}

function getTransformAttributes(type) {
    var _module = Registry.transformsRegistry[type];
    var attributes = extendDeepAll({}, _module.attributes);

    // add registered components transform attributes
    Object.keys(Registry.componentsRegistry).forEach(function(k) {
        var _module = Registry.componentsRegistry[k];

        if(_module.schema && _module.schema.transforms && _module.schema.transforms[type]) {
            Object.keys(_module.schema.transforms[type]).forEach(function(v) {
                insertAttrs(attributes, _module.schema.transforms[type][v], v);
            });
        }
    });

    return {
        attributes: formatAttributes(attributes)
    };
}

function getFramesAttributes() {
    var attrs = {
        frames: Lib.extendDeepAll({}, frameAttributes)
    };

    formatAttributes(attrs);

    return attrs.frames;
}

function formatAttributes(attrs) {
    mergeValTypeAndRole(attrs);
    formatArrayContainers(attrs);
    stringify(attrs);

    return attrs;
}

function mergeValTypeAndRole(attrs) {

    function makeSrcAttr(attrName) {
        return {
            valType: 'string',
            
            
            editType: 'none'
        };
    }

    function callback(attr, attrName, attrs) {
        if(exports.isValObject(attr)) {
            if(attr.valType === 'data_array') {
                // all 'data_array' attrs have role 'data'
                attr.role = 'data';
                // all 'data_array' attrs have a corresponding 'src' attr
                attrs[attrName + 'src'] = makeSrcAttr(attrName);
            }
            else if(attr.arrayOk === true) {
                // all 'arrayOk' attrs have a corresponding 'src' attr
                attrs[attrName + 'src'] = makeSrcAttr(attrName);
            }
        }
        else if(isPlainObject(attr)) {
            // all attrs container objects get role 'object'
            attr.role = 'object';
        }
    }

    exports.crawl(attrs, callback);
}

function formatArrayContainers(attrs) {

    function callback(attr, attrName, attrs) {
        if(!attr) return;

        var itemName = attr[IS_LINKED_TO_ARRAY];

        if(!itemName) return;

        delete attr[IS_LINKED_TO_ARRAY];

        attrs[attrName] = { items: {} };
        attrs[attrName].items[itemName] = attr;
        attrs[attrName].role = 'object';
    }

    exports.crawl(attrs, callback);
}

// this can take around 10ms and should only be run from PlotSchema.get(),
// to ensure JSON.stringify(PlotSchema.get()) gives the intended result.
function stringify(attrs) {
    function walk(attr) {
        for(var k in attr) {
            if(isPlainObject(attr[k])) {
                walk(attr[k]);
            } else if(Array.isArray(attr[k])) {
                for(var i = 0; i < attr[k].length; i++) {
                    walk(attr[k][i]);
                }
            } else {
                // as JSON.stringify(/test/) // => {}
                if(attr[k] instanceof RegExp) {
                    attr[k] = attr[k].toString();
                }
            }
        }
    }

    walk(attrs);
}

function assignPolarLayoutAttrs(layoutAttributes) {
    extendFlat(layoutAttributes, {
        radialaxis: polarAxisAttrs.radialaxis,
        angularaxis: polarAxisAttrs.angularaxis
    });

    extendFlat(layoutAttributes, polarAxisAttrs.layout);

    return layoutAttributes;
}

function handleBasePlotModule(layoutAttributes, _module, astr) {
    var np = Lib.nestedProperty(layoutAttributes, astr);
    var attrs = extendDeepAll({}, _module.layoutAttributes);

    attrs[IS_SUBPLOT_OBJ] = true;
    np.set(attrs);
}

function insertAttrs(baseAttrs, newAttrs, astr) {
    var np = Lib.nestedProperty(baseAttrs, astr);

    np.set(extendDeepAll(np.get() || {}, newAttrs));
}

},{"../lib":694,"../plots/animation_attributes":737,"../plots/attributes":739,"../plots/frame_attributes":770,"../plots/layout_attributes":797,"../plots/polar/legacy/area_attributes":812,"../plots/polar/legacy/axis_attributes":813,"../registry":825,"./edit_types":725,"./plot_config":730}],732:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../lib');
var plotAttributes = _dereq_('../plots/attributes');

var TEMPLATEITEMNAME = 'templateitemname';

var templateAttrs = {
    name: {
        valType: 'string',
        
        editType: 'none',
        
    }
};
templateAttrs[TEMPLATEITEMNAME] = {
    valType: 'string',
    
    editType: 'calc',
    
};

/**
 * templatedArray: decorate an attributes object with templating (and array)
 * properties.
 *
 * @param {string} name: the singular form of the array name. Sets
 *     `_isLinkedToArray` to this, so the schema knows to treat this as an array.
 * @param {object} attrs: the item attributes. Since all callers are expected
 *     to be constructing this object on the spot, we mutate it here for
 *     performance, rather than extending a new object with it.
 *
 * @returns {object}: the decorated `attrs` object
 */
exports.templatedArray = function(name, attrs) {
    attrs._isLinkedToArray = name;
    attrs.name = templateAttrs.name;
    attrs[TEMPLATEITEMNAME] = templateAttrs[TEMPLATEITEMNAME];
    return attrs;
};

/**
 * traceTemplater: logic for matching traces to trace templates
 *
 * @param {object} dataTemplate: collection of {traceType: [{template}, ...]}
 *     ie each type the template applies to contains a list of template objects,
 *     to be provided cyclically to data traces of that type.
 *
 * @returns {object}: {newTrace}, a function:
 *     newTrace(traceIn): that takes the input traceIn, coerces its type, then
 *         uses that type to find the next template to apply. returns the output
 *         traceOut with template attached, ready to continue supplyDefaults.
 */
exports.traceTemplater = function(dataTemplate) {
    var traceCounts = {};
    var traceType, typeTemplates;

    for(traceType in dataTemplate) {
        typeTemplates = dataTemplate[traceType];
        if(Array.isArray(typeTemplates) && typeTemplates.length) {
            traceCounts[traceType] = 0;
        }
    }

    function newTrace(traceIn) {
        traceType = Lib.coerce(traceIn, {}, plotAttributes, 'type');
        var traceOut = {type: traceType, _template: null};
        if(traceType in traceCounts) {
            typeTemplates = dataTemplate[traceType];
            // cycle through traces in the template set for this type
            var typei = traceCounts[traceType] % typeTemplates.length;
            traceCounts[traceType]++;
            traceOut._template = typeTemplates[typei];
        }
        else {
            // TODO: anything we should do for types missing from the template?
            // try to apply some other type? Or just bail as we do here?
            // Actually I think yes, we should apply other types; would be nice
            // if all scatter* could inherit from each other, and if histogram
            // could inherit from bar, etc... but how to specify this? And do we
            // compose them, or if a type is present require it to be complete?
            // Actually this could apply to layout too - 3D annotations
            // inheriting from 2D, axes of different types inheriting from each
            // other...
        }
        return traceOut;
    }

    return {
        newTrace: newTrace
        // TODO: function to figure out what's left & what didn't work
    };
};

/**
 * newContainer: Create a new sub-container inside `container` and propagate any
 * applicable template to it. If there's no template, still propagates
 * `undefined` so relinkPrivate will not retain an old template!
 *
 * @param {object} container: the outer container, should already have _template
 *     if there *is* a template for this plot
 * @param {string} name: the key of the new container to make
 * @param {string} baseName: if applicable, a base attribute to take the
 *     template from, ie for xaxis3 the base would be xaxis
 *
 * @returns {object}: an object for inclusion _full*, empty except for the
 *     appropriate template piece
 */
exports.newContainer = function(container, name, baseName) {
    var template = container._template;
    var part = template && (template[name] || (baseName && template[baseName]));
    if(!Lib.isPlainObject(part)) part = null;

    var out = container[name] = {_template: part};
    return out;
};

/**
 * arrayTemplater: special logic for templating both defaults and specific items
 * in a container array (annotations etc)
 *
 * @param {object} container: the outer container, should already have _template
 *     if there *is* a template for this plot
 * @param {string} name: the name of the array to template (ie 'annotations')
 *     will be used to find default ('annotationdefaults' object) and specific
 *     ('annotations' array) template specs.
 * @param {string} inclusionAttr: the attribute determining this item's
 *     inclusion in the output, usually 'visible' or 'enabled'
 *
 * @returns {object}: {newItem, defaultItems}, both functions:
 *     newItem(itemIn): create an output item, bare except for the correct
 *         template and name(s), as the base for supplyDefaults
 *     defaultItems(): to be called after all newItem calls, return any
 *         specific template items that have not already beeen included,
 *         also as bare output items ready for supplyDefaults.
 */
exports.arrayTemplater = function(container, name, inclusionAttr) {
    var template = container._template;
    var defaultsTemplate = template && template[arrayDefaultKey(name)];
    var templateItems = template && template[name];
    if(!Array.isArray(templateItems) || !templateItems.length) {
        templateItems = [];
    }

    var usedNames = {};

    function newItem(itemIn) {
        // include name and templateitemname in the output object for ALL
        // container array items. Note: you could potentially use different
        // name and templateitemname, if you're using one template to make
        // another template. templateitemname would be the name in the original
        // template, and name is the new "subclassed" item name.
        var out = {name: itemIn.name, _input: itemIn};
        var templateItemName = out[TEMPLATEITEMNAME] = itemIn[TEMPLATEITEMNAME];

        // no itemname: use the default template
        if(!validItemName(templateItemName)) {
            out._template = defaultsTemplate;
            return out;
        }

        // look for an item matching this itemname
        // note these do not inherit from the default template, only the item.
        for(var i = 0; i < templateItems.length; i++) {
            var templateItem = templateItems[i];
            if(templateItem.name === templateItemName) {
                // Note: it's OK to use a template item more than once
                // but using it at least once will stop it from generating
                // a default item at the end.
                usedNames[templateItemName] = 1;
                out._template = templateItem;
                return out;
            }
        }

        // Didn't find a matching template item, so since this item is intended
        // to only be modifications it's most likely broken. Hide it unless
        // it's explicitly marked visible - in which case it gets NO template,
        // not even the default.
        out[inclusionAttr] = itemIn[inclusionAttr] || false;
        // special falsy value we can look for in validateTemplate
        out._template = false;
        return out;
    }

    function defaultItems() {
        var out = [];
        for(var i = 0; i < templateItems.length; i++) {
            var templateItem = templateItems[i];
            var name = templateItem.name;
            // only allow named items to be added as defaults,
            // and only allow each name once
            if(validItemName(name) && !usedNames[name]) {
                var outi = {
                    _template: templateItem,
                    name: name,
                    _input: {_templateitemname: name}
                };
                outi[TEMPLATEITEMNAME] = templateItem[TEMPLATEITEMNAME];
                out.push(outi);
                usedNames[name] = 1;
            }
        }
        return out;
    }

    return {
        newItem: newItem,
        defaultItems: defaultItems
    };
};

function validItemName(name) {
    return name && typeof name === 'string';
}

function arrayDefaultKey(name) {
    var lastChar = name.length - 1;
    if(name.charAt(lastChar) !== 's') {
        Lib.warn('bad argument to arrayDefaultKey: ' + name);
    }
    return name.substr(0, name.length - 1) + 'defaults';
}
exports.arrayDefaultKey = arrayDefaultKey;

/**
 * arrayEditor: helper for editing array items that may have come from
 *     template defaults (in which case they will not exist in the input yet)
 *
 * @param {object} parentIn: the input container (eg gd.layout)
 * @param {string} containerStr: the attribute string for the container inside
 *     `parentIn`.
 * @param {object} itemOut: the _full* item (eg gd._fullLayout.annotations[0])
 *     that we'll be editing. Assumed to have been created by `arrayTemplater`.
 *
 * @returns {object}: {modifyBase, modifyItem, getUpdateObj, applyUpdate}, all functions:
 *     modifyBase(attr, value): Add an update that's *not* related to the item.
 *         `attr` is the full attribute string.
 *     modifyItem(attr, value): Add an update to the item. `attr` is just the
 *         portion of the attribute string inside the item.
 *     getUpdateObj(): Get the final constructed update object, to use in
 *         `restyle` or `relayout`. Also resets the update object in case this
 *         update was canceled.
 *     applyUpdate(attr, value): optionally add an update `attr: value`,
 *         then apply it to `parent` which should be the parent of `containerIn`,
 *         ie the object to which `containerStr` is the attribute string.
 */
exports.arrayEditor = function(parentIn, containerStr, itemOut) {
    var lengthIn = (Lib.nestedProperty(parentIn, containerStr).get() || []).length;
    var index = itemOut._index;
    // Check that we are indeed off the end of this container.
    // Otherwise a devious user could put a key `_templateitemname` in their
    // own input and break lots of things.
    var templateItemName = (index >= lengthIn) && (itemOut._input || {})._templateitemname;
    if(templateItemName) index = lengthIn;
    var itemStr = containerStr + '[' + index + ']';

    var update;
    function resetUpdate() {
        update = {};
        if(templateItemName) {
            update[itemStr] = {};
            update[itemStr][TEMPLATEITEMNAME] = templateItemName;
        }
    }
    resetUpdate();

    function modifyBase(attr, value) {
        update[attr] = value;
    }

    function modifyItem(attr, value) {
        if(templateItemName) {
            // we're making a new object: edit that object
            Lib.nestedProperty(update[itemStr], attr).set(value);
        }
        else {
            // we're editing an existing object: include *just* the edit
            update[itemStr + '.' + attr] = value;
        }
    }

    function getUpdateObj() {
        var updateOut = update;
        resetUpdate();
        return updateOut;
    }

    function applyUpdate(attr, value) {
        if(attr) modifyItem(attr, value);
        var updateToApply = getUpdateObj();
        for(var key in updateToApply) {
            Lib.nestedProperty(parentIn, key).set(updateToApply[key]);
        }
    }

    return {
        modifyBase: modifyBase,
        modifyItem: modifyItem,
        getUpdateObj: getUpdateObj,
        applyUpdate: applyUpdate
    };
};

},{"../lib":694,"../plots/attributes":739}],733:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var Registry = _dereq_('../registry');
var Plots = _dereq_('../plots/plots');

var Lib = _dereq_('../lib');
var clearGlCanvases = _dereq_('../lib/clear_gl_canvases');

var Color = _dereq_('../components/color');
var Drawing = _dereq_('../components/drawing');
var Titles = _dereq_('../components/titles');
var ModeBar = _dereq_('../components/modebar');

var Axes = _dereq_('../plots/cartesian/axes');
var alignmentConstants = _dereq_('../constants/alignment');
var axisConstraints = _dereq_('../plots/cartesian/constraints');
var enforceAxisConstraints = axisConstraints.enforce;
var cleanAxisConstraints = axisConstraints.clean;
var doAutoRange = _dereq_('../plots/cartesian/autorange').doAutoRange;

var SVG_TEXT_ANCHOR_START = 'start';
var SVG_TEXT_ANCHOR_MIDDLE = 'middle';
var SVG_TEXT_ANCHOR_END = 'end';

exports.layoutStyles = function(gd) {
    return Lib.syncOrAsync([Plots.doAutoMargin, lsInner], gd);
};

function overlappingDomain(xDomain, yDomain, domains) {
    for(var i = 0; i < domains.length; i++) {
        var existingX = domains[i][0];
        var existingY = domains[i][1];

        if(existingX[0] >= xDomain[1] || existingX[1] <= xDomain[0]) {
            continue;
        }
        if(existingY[0] < yDomain[1] && existingY[1] > yDomain[0]) {
            return true;
        }
    }
    return false;
}

function lsInner(gd) {
    var fullLayout = gd._fullLayout;
    var gs = fullLayout._size;
    var pad = gs.p;
    var axList = Axes.list(gd, '', true);
    var i, subplot, plotinfo, ax, xa, ya;

    fullLayout._paperdiv.style({
        width: (gd._context.responsive && fullLayout.autosize && !gd._context._hasZeroWidth && !gd.layout.width) ? '100%' : fullLayout.width + 'px',
        height: (gd._context.responsive && fullLayout.autosize && !gd._context._hasZeroHeight && !gd.layout.height) ? '100%' : fullLayout.height + 'px'
    })
    .selectAll('.main-svg')
    .call(Drawing.setSize, fullLayout.width, fullLayout.height);
    gd._context.setBackground(gd, fullLayout.paper_bgcolor);

    exports.drawMainTitle(gd);
    ModeBar.manage(gd);

    // _has('cartesian') means SVG specifically, not GL2D - but GL2D
    // can still get here because it makes some of the SVG structure
    // for shared features like selections.
    if(!fullLayout._has('cartesian')) {
        return gd._promises.length && Promise.all(gd._promises);
    }

    function getLinePosition(ax, counterAx, side) {
        var lwHalf = ax._lw / 2;

        if(ax._id.charAt(0) === 'x') {
            if(!counterAx) return gs.t + gs.h * (1 - (ax.position || 0)) + (lwHalf % 1);
            else if(side === 'top') return counterAx._offset - pad - lwHalf;
            return counterAx._offset + counterAx._length + pad + lwHalf;
        }

        if(!counterAx) return gs.l + gs.w * (ax.position || 0) + (lwHalf % 1);
        else if(side === 'right') return counterAx._offset + counterAx._length + pad + lwHalf;
        return counterAx._offset - pad - lwHalf;
    }

    // some preparation of axis position info
    for(i = 0; i < axList.length; i++) {
        ax = axList[i];

        var counterAx = ax._anchorAxis;

        // clear axis line positions, to be set in the subplot loop below
        ax._linepositions = {};

        // stash crispRounded linewidth so we don't need to pass gd all over the place
        ax._lw = Drawing.crispRound(gd, ax.linewidth, 1);

        // figure out the main axis line and main mirror line position.
        // it's easier to follow the logic if we handle these separately from
        // ax._linepositions, which are only used by mirror=allticks
        // for non-main-subplot ticks, and mirror=all(ticks)? for zero line
        // hiding logic
        ax._mainLinePosition = getLinePosition(ax, counterAx, ax.side);
        ax._mainMirrorPosition = (ax.mirror && counterAx) ?
            getLinePosition(ax, counterAx,
                alignmentConstants.OPPOSITE_SIDE[ax.side]) : null;
    }

    // figure out which backgrounds we need to draw,
    // and in which layers to put them
    var lowerBackgroundIDs = [];
    var backgroundIds = [];
    var lowerDomains = [];
    // no need to draw background when paper and plot color are the same color,
    // activate mode just for large splom (which benefit the most from this
    // optimization), but this could apply to all cartesian subplots.
    var noNeedForBg = (
        Color.opacity(fullLayout.paper_bgcolor) === 1 &&
        Color.opacity(fullLayout.plot_bgcolor) === 1 &&
        fullLayout.paper_bgcolor === fullLayout.plot_bgcolor
    );

    for(subplot in fullLayout._plots) {
        plotinfo = fullLayout._plots[subplot];

        if(plotinfo.mainplot) {
            // mainplot is a reference to the main plot this one is overlaid on
            // so if it exists, this is an overlaid plot and we don't need to
            // give it its own background
            if(plotinfo.bg) {
                plotinfo.bg.remove();
            }
            plotinfo.bg = undefined;
        } else {
            var xDomain = plotinfo.xaxis.domain;
            var yDomain = plotinfo.yaxis.domain;
            var plotgroup = plotinfo.plotgroup;

            if(overlappingDomain(xDomain, yDomain, lowerDomains)) {
                var pgNode = plotgroup.node();
                var plotgroupBg = plotinfo.bg = Lib.ensureSingle(plotgroup, 'rect', 'bg');
                pgNode.insertBefore(plotgroupBg.node(), pgNode.childNodes[0]);
                backgroundIds.push(subplot);
            } else {
                plotgroup.select('rect.bg').remove();
                lowerDomains.push([xDomain, yDomain]);
                if(!noNeedForBg) {
                    lowerBackgroundIDs.push(subplot);
                    backgroundIds.push(subplot);
                }
            }
        }
    }

    // now create all the lower-layer backgrounds at once now that
    // we have the list of subplots that need them
    var lowerBackgrounds = fullLayout._bgLayer.selectAll('.bg')
        .data(lowerBackgroundIDs);

    lowerBackgrounds.enter().append('rect')
        .classed('bg', true);

    lowerBackgrounds.exit().remove();

    lowerBackgrounds.each(function(subplot) {
        fullLayout._plots[subplot].bg = d3.select(this);
    });

    // style all backgrounds
    for(i = 0; i < backgroundIds.length; i++) {
        plotinfo = fullLayout._plots[backgroundIds[i]];
        xa = plotinfo.xaxis;
        ya = plotinfo.yaxis;

        if(plotinfo.bg) {
            plotinfo.bg
                .call(Drawing.setRect,
                    xa._offset - pad, ya._offset - pad,
                    xa._length + 2 * pad, ya._length + 2 * pad)
                .call(Color.fill, fullLayout.plot_bgcolor)
                .style('stroke-width', 0);
        }
    }

    if(!fullLayout._hasOnlyLargeSploms) {
        for(subplot in fullLayout._plots) {
            plotinfo = fullLayout._plots[subplot];
            xa = plotinfo.xaxis;
            ya = plotinfo.yaxis;

            // Clip so that data only shows up on the plot area.
            var clipId = plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot';

            var plotClip = Lib.ensureSingleById(fullLayout._clips, 'clipPath', clipId, function(s) {
                s.classed('plotclip', true)
                    .append('rect');
            });

            plotinfo.clipRect = plotClip.select('rect').attr({
                width: xa._length,
                height: ya._length
            });

            Drawing.setTranslate(plotinfo.plot, xa._offset, ya._offset);

            var plotClipId;
            var layerClipId;

            if(plotinfo._hasClipOnAxisFalse) {
                plotClipId = null;
                layerClipId = clipId;
            } else {
                plotClipId = clipId;
                layerClipId = null;
            }

            Drawing.setClipUrl(plotinfo.plot, plotClipId, gd);

            // stash layer clipId value (null or same as clipId)
            // to DRY up Drawing.setClipUrl calls on trace-module and trace layers
            // downstream
            plotinfo.layerClipId = layerClipId;
        }
    }

    var xLinesXLeft, xLinesXRight, xLinesYBottom, xLinesYTop,
        leftYLineWidth, rightYLineWidth;
    var yLinesYBottom, yLinesYTop, yLinesXLeft, yLinesXRight,
        connectYBottom, connectYTop;
    var extraSubplot;

    function xLinePath(y) {
        return 'M' + xLinesXLeft + ',' + y + 'H' + xLinesXRight;
    }

    function xLinePathFree(y) {
        return 'M' + xa._offset + ',' + y + 'h' + xa._length;
    }

    function yLinePath(x) {
        return 'M' + x + ',' + yLinesYTop + 'V' + yLinesYBottom;
    }

    function yLinePathFree(x) {
        return 'M' + x + ',' + ya._offset + 'v' + ya._length;
    }

    function mainPath(ax, pathFn, pathFnFree) {
        if(!ax.showline || subplot !== ax._mainSubplot) return '';
        if(!ax._anchorAxis) return pathFnFree(ax._mainLinePosition);
        var out = pathFn(ax._mainLinePosition);
        if(ax.mirror) out += pathFn(ax._mainMirrorPosition);
        return out;
    }

    for(subplot in fullLayout._plots) {
        plotinfo = fullLayout._plots[subplot];
        xa = plotinfo.xaxis;
        ya = plotinfo.yaxis;

        /*
         * x lines get longer where they meet y lines, to make a crisp corner.
         * The x lines get the padding (margin.pad) plus the y line width to
         * fill up the corner nicely. Free x lines are excluded - they always
         * span exactly the data area of the plot
         *
         *  | XXXXX
         *  | XXXXX
         *  |
         *  +------
         *     x1
         *    -----
         *     x2
         */
        var xPath = 'M0,0';
        if(shouldShowLinesOrTicks(xa, subplot)) {
            leftYLineWidth = findCounterAxisLineWidth(xa, 'left', ya, axList);
            xLinesXLeft = xa._offset - (leftYLineWidth ? (pad + leftYLineWidth) : 0);
            rightYLineWidth = findCounterAxisLineWidth(xa, 'right', ya, axList);
            xLinesXRight = xa._offset + xa._length + (rightYLineWidth ? (pad + rightYLineWidth) : 0);
            xLinesYBottom = getLinePosition(xa, ya, 'bottom');
            xLinesYTop = getLinePosition(xa, ya, 'top');

            // save axis line positions for extra ticks to reference
            // each subplot that gets ticks from "allticks" gets an entry:
            //    [left or bottom, right or top]
            extraSubplot = (!xa._anchorAxis || subplot !== xa._mainSubplot);
            if(extraSubplot && (xa.mirror === 'allticks' || xa.mirror === 'all')) {
                xa._linepositions[subplot] = [xLinesYBottom, xLinesYTop];
            }

            xPath = mainPath(xa, xLinePath, xLinePathFree);
            if(extraSubplot && xa.showline && (xa.mirror === 'all' || xa.mirror === 'allticks')) {
                xPath += xLinePath(xLinesYBottom) + xLinePath(xLinesYTop);
            }

            plotinfo.xlines
                .style('stroke-width', xa._lw + 'px')
                .call(Color.stroke, xa.showline ?
                    xa.linecolor : 'rgba(0,0,0,0)');
        }
        plotinfo.xlines.attr('d', xPath);

        /*
         * y lines that meet x axes get longer only by margin.pad, because
         * the x axes fill in the corner space. Free y axes, like free x axes,
         * always span exactly the data area of the plot
         *
         *   |   | XXXX
         * y2| y1| XXXX
         *   |   | XXXX
         *       |
         *       +-----
         */
        var yPath = 'M0,0';
        if(shouldShowLinesOrTicks(ya, subplot)) {
            connectYBottom = findCounterAxisLineWidth(ya, 'bottom', xa, axList);
            yLinesYBottom = ya._offset + ya._length + (connectYBottom ? pad : 0);
            connectYTop = findCounterAxisLineWidth(ya, 'top', xa, axList);
            yLinesYTop = ya._offset - (connectYTop ? pad : 0);
            yLinesXLeft = getLinePosition(ya, xa, 'left');
            yLinesXRight = getLinePosition(ya, xa, 'right');

            extraSubplot = (!ya._anchorAxis || subplot !== ya._mainSubplot);
            if(extraSubplot && (ya.mirror === 'allticks' || ya.mirror === 'all')) {
                ya._linepositions[subplot] = [yLinesXLeft, yLinesXRight];
            }

            yPath = mainPath(ya, yLinePath, yLinePathFree);
            if(extraSubplot && ya.showline && (ya.mirror === 'all' || ya.mirror === 'allticks')) {
                yPath += yLinePath(yLinesXLeft) + yLinePath(yLinesXRight);
            }

            plotinfo.ylines
                .style('stroke-width', ya._lw + 'px')
                .call(Color.stroke, ya.showline ?
                    ya.linecolor : 'rgba(0,0,0,0)');
        }
        plotinfo.ylines.attr('d', yPath);
    }

    Axes.makeClipPaths(gd);

    return gd._promises.length && Promise.all(gd._promises);
}

function shouldShowLinesOrTicks(ax, subplot) {
    return (ax.ticks || ax.showline) &&
        (subplot === ax._mainSubplot || ax.mirror === 'all' || ax.mirror === 'allticks');
}

/*
 * should we draw a line on counterAx at this side of ax?
 * It's assumed that counterAx is known to overlay the subplot we're working on
 * but it may not be its main axis.
 */
function shouldShowLineThisSide(ax, side, counterAx) {
    // does counterAx get a line at all?
    if(!counterAx.showline || !counterAx._lw) return false;

    // are we drawing *all* lines for counterAx?
    if(counterAx.mirror === 'all' || counterAx.mirror === 'allticks') return true;

    var anchorAx = counterAx._anchorAxis;

    // is this a free axis? free axes can only have a subplot side-line with all(ticks)? mirroring
    if(!anchorAx) return false;

    // in order to handle cases where the user forgot to anchor this axis correctly
    // (because its default anchor has the same domain on the relevant end)
    // check whether the relevant position is the same.
    var sideIndex = alignmentConstants.FROM_BL[side];
    if(counterAx.side === side) {
        return anchorAx.domain[sideIndex] === ax.domain[sideIndex];
    }
    return counterAx.mirror && anchorAx.domain[1 - sideIndex] === ax.domain[1 - sideIndex];
}

/*
 * Is there another axis intersecting `side` end of `ax`?
 * First look at `counterAx` (the axis for this subplot),
 * then at all other potential counteraxes on or overlaying this subplot.
 * Take the line width from the first one that has a line.
 */
function findCounterAxisLineWidth(ax, side, counterAx, axList) {
    if(shouldShowLineThisSide(ax, side, counterAx)) {
        return counterAx._lw;
    }
    for(var i = 0; i < axList.length; i++) {
        var axi = axList[i];
        if(axi._mainAxis === counterAx._mainAxis && shouldShowLineThisSide(ax, side, axi)) {
            return axi._lw;
        }
    }
    return 0;
}

exports.drawMainTitle = function(gd) {
    var fullLayout = gd._fullLayout;

    var textAnchor = getMainTitleTextAnchor(fullLayout);
    var dy = getMainTitleDy(fullLayout);

    Titles.draw(gd, 'gtitle', {
        propContainer: fullLayout,
        propName: 'title.text',
        placeholder: fullLayout._dfltTitle.plot,
        attributes: {
            x: getMainTitleX(fullLayout, textAnchor),
            y: getMainTitleY(fullLayout, dy),
            'text-anchor': textAnchor,
            dy: dy
        }
    });
};

function getMainTitleX(fullLayout, textAnchor) {
    var title = fullLayout.title;
    var gs = fullLayout._size;
    var hPadShift = 0;

    if(textAnchor === SVG_TEXT_ANCHOR_START) {
        hPadShift = title.pad.l;
    } else if(textAnchor === SVG_TEXT_ANCHOR_END) {
        hPadShift = -title.pad.r;
    }

    switch(title.xref) {
        case 'paper':
            return gs.l + gs.w * title.x + hPadShift;
        case 'container':
        default:
            return fullLayout.width * title.x + hPadShift;
    }
}

function getMainTitleY(fullLayout, dy) {
    var title = fullLayout.title;
    var gs = fullLayout._size;
    var vPadShift = 0;

    if(dy === '0em' || !dy) {
        vPadShift = -title.pad.b;
    } else if(dy === alignmentConstants.CAP_SHIFT + 'em') {
        vPadShift = title.pad.t;
    }

    if(title.y === 'auto') {
        return gs.t / 2;
    } else {
        switch(title.yref) {
            case 'paper':
                return gs.t + gs.h - gs.h * title.y + vPadShift;
            case 'container':
            default:
                return fullLayout.height - fullLayout.height * title.y + vPadShift;
        }
    }
}

function getMainTitleTextAnchor(fullLayout) {
    var title = fullLayout.title;

    var textAnchor = SVG_TEXT_ANCHOR_MIDDLE;
    if(Lib.isRightAnchor(title)) {
        textAnchor = SVG_TEXT_ANCHOR_END;
    } else if(Lib.isLeftAnchor(title)) {
        textAnchor = SVG_TEXT_ANCHOR_START;
    }

    return textAnchor;
}

function getMainTitleDy(fullLayout) {
    var title = fullLayout.title;

    var dy = '0em';
    if(Lib.isTopAnchor(title)) {
        dy = alignmentConstants.CAP_SHIFT + 'em';
    } else if(Lib.isMiddleAnchor(title)) {
        dy = alignmentConstants.MID_SHIFT + 'em';
    }

    return dy;
}

exports.doTraceStyle = function(gd) {
    var calcdata = gd.calcdata;
    var editStyleCalls = [];
    var i;

    for(i = 0; i < calcdata.length; i++) {
        var cd = calcdata[i];
        var cd0 = cd[0] || {};
        var trace = cd0.trace || {};
        var _module = trace._module || {};

        // See if we need to do arraysToCalcdata
        // call it regardless of what change we made, in case
        // supplyDefaults brought in an array that was already
        // in gd.data but not in gd._fullData previously
        var arraysToCalcdata = _module.arraysToCalcdata;
        if(arraysToCalcdata) arraysToCalcdata(cd, trace);

        var editStyle = _module.editStyle;
        if(editStyle) editStyleCalls.push({fn: editStyle, cd0: cd0});
    }

    if(editStyleCalls.length) {
        for(i = 0; i < editStyleCalls.length; i++) {
            var edit = editStyleCalls[i];
            edit.fn(gd, edit.cd0);
        }
        clearGlCanvases(gd);
        exports.redrawReglTraces(gd);
    }

    Plots.style(gd);
    Registry.getComponentMethod('legend', 'draw')(gd);

    return Plots.previousPromises(gd);
};

exports.doColorBars = function(gd) {
    for(var i = 0; i < gd.calcdata.length; i++) {
        var cdi0 = gd.calcdata[i][0];

        if((cdi0.t || {}).cb) {
            var trace = cdi0.trace;
            var cb = cdi0.t.cb;

            if(Registry.traceIs(trace, 'contour')) {
                cb.line({
                    width: trace.contours.showlines !== false ?
                        trace.line.width : 0,
                    dash: trace.line.dash,
                    color: trace.contours.coloring === 'line' ?
                        cb._opts.line.color : trace.line.color
                });
            }
            var moduleOpts = trace._module.colorbar;
            var containerName = moduleOpts.container;
            var opts = (containerName ? trace[containerName] : trace).colorbar;
            cb.options(opts)();
        }
    }

    return Plots.previousPromises(gd);
};

// force plot() to redo the layout and replot with the modified layout
exports.layoutReplot = function(gd) {
    var layout = gd.layout;
    gd.layout = undefined;
    return Registry.call('plot', gd, '', layout);
};

exports.doLegend = function(gd) {
    Registry.getComponentMethod('legend', 'draw')(gd);
    return Plots.previousPromises(gd);
};

exports.doTicksRelayout = function(gd) {
    Axes.draw(gd, 'redraw');

    if(gd._fullLayout._hasOnlyLargeSploms) {
        Registry.subplotsRegistry.splom.updateGrid(gd);
        clearGlCanvases(gd);
        exports.redrawReglTraces(gd);
    }

    exports.drawMainTitle(gd);
    return Plots.previousPromises(gd);
};

exports.doModeBar = function(gd) {
    var fullLayout = gd._fullLayout;

    ModeBar.manage(gd);

    for(var i = 0; i < fullLayout._basePlotModules.length; i++) {
        var updateFx = fullLayout._basePlotModules[i].updateFx;
        if(updateFx) updateFx(gd);
    }

    return Plots.previousPromises(gd);
};

exports.doCamera = function(gd) {
    var fullLayout = gd._fullLayout;
    var sceneIds = fullLayout._subplots.gl3d;

    for(var i = 0; i < sceneIds.length; i++) {
        var sceneLayout = fullLayout[sceneIds[i]];
        var scene = sceneLayout._scene;

        scene.setCamera(sceneLayout.camera);
    }
};

exports.drawData = function(gd) {
    var fullLayout = gd._fullLayout;
    var calcdata = gd.calcdata;
    var i;

    // remove old colorbars explicitly
    for(i = 0; i < calcdata.length; i++) {
        var trace = calcdata[i][0].trace;
        if(trace.visible !== true || !trace._module.colorbar) {
            fullLayout._infolayer.select('.cb' + trace.uid).remove();
        }
    }

    clearGlCanvases(gd);

    // loop over the base plot modules present on graph
    var basePlotModules = fullLayout._basePlotModules;
    for(i = 0; i < basePlotModules.length; i++) {
        basePlotModules[i].plot(gd);
    }

    exports.redrawReglTraces(gd);

    // styling separate from drawing
    Plots.style(gd);

    // show annotations and shapes
    Registry.getComponentMethod('shapes', 'draw')(gd);
    Registry.getComponentMethod('annotations', 'draw')(gd);

    // Mark the first render as complete
    fullLayout._replotting = false;

    return Plots.previousPromises(gd);
};

// Draw (or redraw) all regl-based traces in one go,
// useful during drag and selection where buffers of targeted traces are updated,
// but all traces need to be redrawn following clearGlCanvases.
//
// Note that _module.plot for regl trace does NOT draw things
// on the canvas, they only update the buffers.
// Drawing is perform here.
//
// TODO try adding per-subplot option using gl.SCISSOR_TEST for
// non-overlaying, disjoint subplots.
//
// TODO try to include parcoords in here.
// https://github.com/plotly/plotly.js/issues/3069
exports.redrawReglTraces = function(gd) {
    var fullLayout = gd._fullLayout;

    if(fullLayout._has('regl')) {
        var fullData = gd._fullData;
        var cartesianIds = [];
        var polarIds = [];
        var i, sp;

        if(fullLayout._hasOnlyLargeSploms) {
            fullLayout._splomGrid.draw();
        }

        // N.B.
        // - Loop over fullData (not _splomScenes) to preserve splom trace-to-trace ordering
        // - Fill list if subplot ids (instead of fullLayout._subplots) to handle cases where all traces
        //   of a given module are `visible !== true`
        for(i = 0; i < fullData.length; i++) {
            var trace = fullData[i];

            if(trace.visible === true) {
                if(trace.type === 'splom') {
                    fullLayout._splomScenes[trace.uid].draw();
                } else if(trace.type === 'scattergl') {
                    Lib.pushUnique(cartesianIds, trace.xaxis + trace.yaxis);
                } else if(trace.type === 'scatterpolargl') {
                    Lib.pushUnique(polarIds, trace.subplot);
                }
            }
        }

        for(i = 0; i < cartesianIds.length; i++) {
            sp = fullLayout._plots[cartesianIds[i]];
            if(sp._scene) sp._scene.draw();
        }

        for(i = 0; i < polarIds.length; i++) {
            sp = fullLayout[polarIds[i]]._subplot;
            if(sp._scene) sp._scene.draw();
        }
    }
};

exports.doAutoRangeAndConstraints = function(gd) {
    var axList = Axes.list(gd, '', true);

    for(var i = 0; i < axList.length; i++) {
        var ax = axList[i];
        cleanAxisConstraints(gd, ax);
        // in case margins changed, update scale
        ax.setScale();
        doAutoRange(gd, ax);
    }

    enforceAxisConstraints(gd);
};

// An initial paint must be completed before these components can be
// correctly sized and the whole plot re-margined. fullLayout._replotting must
// be set to false before these will work properly.
exports.finalDraw = function(gd) {
    Registry.getComponentMethod('shapes', 'draw')(gd);
    Registry.getComponentMethod('images', 'draw')(gd);
    Registry.getComponentMethod('annotations', 'draw')(gd);
    // TODO: rangesliders really belong in marginPushers but they need to be
    // drawn after data - can we at least get the margin pushing part separated
    // out and done earlier?
    Registry.getComponentMethod('rangeslider', 'draw')(gd);
    // TODO: rangeselector only needs to be here (in addition to drawMarginPushers)
    // because the margins need to be fully determined before we can call
    // autorange and update axis ranges (which rangeselector needs to know which
    // button is active). Can we break out its automargin step from its draw step?
    Registry.getComponentMethod('rangeselector', 'draw')(gd);
};

exports.drawMarginPushers = function(gd) {
    Registry.getComponentMethod('legend', 'draw')(gd);
    Registry.getComponentMethod('rangeselector', 'draw')(gd);
    Registry.getComponentMethod('sliders', 'draw')(gd);
    Registry.getComponentMethod('updatemenus', 'draw')(gd);
};

},{"../components/color":571,"../components/drawing":592,"../components/modebar":630,"../components/titles":659,"../constants/alignment":666,"../lib":694,"../lib/clear_gl_canvases":679,"../plots/cartesian/autorange":741,"../plots/cartesian/axes":742,"../plots/cartesian/constraints":750,"../plots/plots":806,"../registry":825,"d3":149}],734:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../lib');
var isPlainObject = Lib.isPlainObject;
var PlotSchema = _dereq_('./plot_schema');
var Plots = _dereq_('../plots/plots');
var plotAttributes = _dereq_('../plots/attributes');
var Template = _dereq_('./plot_template');
var dfltConfig = _dereq_('./plot_config').dfltConfig;

/**
 * Plotly.makeTemplate: create a template off an existing figure to reuse
 * style attributes on other figures.
 *
 * Note: separated from the rest of templates because otherwise we get circular
 * references due to PlotSchema.
 *
 * @param {object|DOM element|string} figure: The figure to base the template on
 *     should contain a trace array `figure.data`
 *     and a layout object `figure.layout`
 * @returns {object} template: the extracted template - can then be used as
 *     `layout.template` in another figure.
 */
exports.makeTemplate = function(figure) {
    figure = Lib.isPlainObject(figure) ? figure : Lib.getGraphDiv(figure);
    figure = Lib.extendDeep({_context: dfltConfig}, {data: figure.data, layout: figure.layout});
    Plots.supplyDefaults(figure);
    var data = figure.data || [];
    var layout = figure.layout || {};
    // copy over a few items to help follow the schema
    layout._basePlotModules = figure._fullLayout._basePlotModules;
    layout._modules = figure._fullLayout._modules;

    var template = {
        data: {},
        layout: {}
    };

    /*
     * Note: we do NOT validate template values, we just take what's in the
     * user inputs data and layout, not the validated values in fullData and
     * fullLayout. Even if we were to validate here, there's no guarantee that
     * these values would still be valid when applied to a new figure, which
     * may contain different trace modes, different axes, etc. So it's
     * important that when applying a template we still validate the template
     * values, rather than just using them as defaults.
     */

    data.forEach(function(trace) {
        // TODO: What if no style info is extracted for this trace. We may
        // not want an empty object as the null value.
        // TODO: allow transforms to contribute to templates?
        // as it stands they are ignored, which may be for the best...

        var traceTemplate = {};
        walkStyleKeys(trace, traceTemplate, getTraceInfo.bind(null, trace));

        var traceType = Lib.coerce(trace, {}, plotAttributes, 'type');
        var typeTemplates = template.data[traceType];
        if(!typeTemplates) typeTemplates = template.data[traceType] = [];
        typeTemplates.push(traceTemplate);
    });

    walkStyleKeys(layout, template.layout, getLayoutInfo.bind(null, layout));

    /*
     * Compose the new template with an existing one to the same effect
     *
     * NOTE: there's a possibility of slightly different behavior: if the plot
     * has an invalid value and the old template has a valid value for the same
     * attribute, the plot will use the old template value but this routine
     * will pull the invalid value (resulting in the original default).
     * In the general case it's not possible to solve this with a single value,
     * since valid options can be context-dependent. It could be solved with
     * a *list* of values, but that would be huge complexity for little gain.
     */
    delete template.layout.template;
    var oldTemplate = layout.template;
    if(isPlainObject(oldTemplate)) {
        var oldLayoutTemplate = oldTemplate.layout;

        var i, traceType, oldTypeTemplates, oldTypeLen, typeTemplates, typeLen;

        if(isPlainObject(oldLayoutTemplate)) {
            mergeTemplates(oldLayoutTemplate, template.layout);
        }
        var oldDataTemplate = oldTemplate.data;
        if(isPlainObject(oldDataTemplate)) {
            for(traceType in template.data) {
                oldTypeTemplates = oldDataTemplate[traceType];
                if(Array.isArray(oldTypeTemplates)) {
                    typeTemplates = template.data[traceType];
                    typeLen = typeTemplates.length;
                    oldTypeLen = oldTypeTemplates.length;
                    for(i = 0; i < typeLen; i++) {
                        mergeTemplates(oldTypeTemplates[i % oldTypeLen], typeTemplates[i]);
                    }
                    for(i = typeLen; i < oldTypeLen; i++) {
                        typeTemplates.push(Lib.extendDeep({}, oldTypeTemplates[i]));
                    }
                }
            }
            for(traceType in oldDataTemplate) {
                if(!(traceType in template.data)) {
                    template.data[traceType] = Lib.extendDeep([], oldDataTemplate[traceType]);
                }
            }
        }
    }

    return template;
};

function mergeTemplates(oldTemplate, newTemplate) {
    // we don't care about speed here, just make sure we have a totally
    // distinct object from the previous template
    oldTemplate = Lib.extendDeep({}, oldTemplate);

    // sort keys so we always get annotationdefaults before annotations etc
    // so arrayTemplater will work right
    var oldKeys = Object.keys(oldTemplate).sort();
    var i, j;

    function mergeOne(oldVal, newVal, key) {
        if(isPlainObject(newVal) && isPlainObject(oldVal)) {
            mergeTemplates(oldVal, newVal);
        }
        else if(Array.isArray(newVal) && Array.isArray(oldVal)) {
            // Note: omitted `inclusionAttr` from arrayTemplater here,
            // it's irrelevant as we only want the resulting `_template`.
            var templater = Template.arrayTemplater({_template: oldTemplate}, key);
            for(j = 0; j < newVal.length; j++) {
                var item = newVal[j];
                var oldItem = templater.newItem(item)._template;
                if(oldItem) mergeTemplates(oldItem, item);
            }
            var defaultItems = templater.defaultItems();
            for(j = 0; j < defaultItems.length; j++) newVal.push(defaultItems[j]._template);

            // templateitemname only applies to receiving plots
            for(j = 0; j < newVal.length; j++) delete newVal[j].templateitemname;
        }
    }

    for(i = 0; i < oldKeys.length; i++) {
        var key = oldKeys[i];
        var oldVal = oldTemplate[key];
        if(key in newTemplate) {
            mergeOne(oldVal, newTemplate[key], key);
        }
        else newTemplate[key] = oldVal;

        // if this is a base key from the old template (eg xaxis), look for
        // extended keys (eg xaxis2) in the new template to merge into
        if(getBaseKey(key) === key) {
            for(var key2 in newTemplate) {
                var baseKey2 = getBaseKey(key2);
                if(key2 !== baseKey2 && baseKey2 === key && !(key2 in oldTemplate)) {
                    mergeOne(oldVal, newTemplate[key2], key);
                }
            }
        }
    }
}

function getBaseKey(key) {
    return key.replace(/[0-9]+$/, '');
}

function walkStyleKeys(parent, templateOut, getAttributeInfo, path, basePath) {
    var pathAttr = basePath && getAttributeInfo(basePath);
    for(var key in parent) {
        var child = parent[key];
        var nextPath = getNextPath(parent, key, path);
        var nextBasePath = getNextPath(parent, key, basePath);
        var attr = getAttributeInfo(nextBasePath);
        if(!attr) {
            var baseKey = getBaseKey(key);
            if(baseKey !== key) {
                nextBasePath = getNextPath(parent, baseKey, basePath);
                attr = getAttributeInfo(nextBasePath);
            }
        }

        // we'll get an attr if path starts with a valid part, then has an
        // invalid ending. Make sure we got all the way to the end.
        if(pathAttr && (pathAttr === attr)) continue;

        if(!attr || attr._noTemplating ||
            attr.valType === 'data_array' ||
            (attr.arrayOk && Array.isArray(child))
        ) {
            continue;
        }

        if(!attr.valType && isPlainObject(child)) {
            walkStyleKeys(child, templateOut, getAttributeInfo, nextPath, nextBasePath);
        }
        else if(attr._isLinkedToArray && Array.isArray(child)) {
            var dfltDone = false;
            var namedIndex = 0;
            var usedNames = {};
            for(var i = 0; i < child.length; i++) {
                var item = child[i];
                if(isPlainObject(item)) {
                    var name = item.name;
                    if(name) {
                        if(!usedNames[name]) {
                            // named array items: allow all attributes except data arrays
                            walkStyleKeys(item, templateOut, getAttributeInfo,
                                getNextPath(child, namedIndex, nextPath),
                                getNextPath(child, namedIndex, nextBasePath));
                            namedIndex++;
                            usedNames[name] = 1;
                        }
                    }
                    else if(!dfltDone) {
                        var dfltKey = Template.arrayDefaultKey(key);
                        var dfltPath = getNextPath(parent, dfltKey, path);

                        // getAttributeInfo will fail if we try to use dfltKey directly.
                        // Instead put this item into the next array element, then
                        // pull it out and move it to dfltKey.
                        var pathInArray = getNextPath(child, namedIndex, nextPath);
                        walkStyleKeys(item, templateOut, getAttributeInfo, pathInArray,
                            getNextPath(child, namedIndex, nextBasePath));
                        var itemPropInArray = Lib.nestedProperty(templateOut, pathInArray);
                        var dfltProp = Lib.nestedProperty(templateOut, dfltPath);
                        dfltProp.set(itemPropInArray.get());
                        itemPropInArray.set(null);

                        dfltDone = true;
                    }
                }
            }
        }
        else {
            var templateProp = Lib.nestedProperty(templateOut, nextPath);
            templateProp.set(child);
        }
    }
}

function getLayoutInfo(layout, path) {
    return PlotSchema.getLayoutValObject(
        layout, Lib.nestedProperty({}, path).parts
    );
}

function getTraceInfo(trace, path) {
    return PlotSchema.getTraceValObject(
        trace, Lib.nestedProperty({}, path).parts
    );
}

function getNextPath(parent, key, path) {
    var nextPath;
    if(!path) nextPath = key;
    else if(Array.isArray(parent)) nextPath = path + '[' + key + ']';
    else nextPath = path + '.' + key;

    return nextPath;
}

/**
 * validateTemplate: Test for consistency between the given figure and
 * a template, either already included in the figure or given separately.
 * Note that not every issue we identify here is necessarily a problem,
 * it depends on what you're using the template for.
 *
 * @param {object|DOM element} figure: the plot, with {data, layout} members,
 *     to test the template against
 * @param {Optional(object)} template: the template, with its own {data, layout},
 *     to test. If omitted, we will look for a template already attached as the
 *     plot's `layout.template` attribute.
 *
 * @returns {array} array of error objects each containing:
 *  - {string} code
 *      error code ('missing', 'unused', 'reused', 'noLayout', 'noData')
 *  - {string} msg
 *      a full readable description of the issue.
 */
exports.validateTemplate = function(figureIn, template) {
    var figure = Lib.extendDeep({}, {
        _context: dfltConfig,
        data: figureIn.data,
        layout: figureIn.layout
    });
    var layout = figure.layout || {};
    if(!isPlainObject(template)) template = layout.template || {};
    var layoutTemplate = template.layout;
    var dataTemplate = template.data;
    var errorList = [];

    figure.layout = layout;
    figure.layout.template = template;
    Plots.supplyDefaults(figure);

    var fullLayout = figure._fullLayout;
    var fullData = figure._fullData;

    var layoutPaths = {};
    function crawlLayoutForContainers(obj, paths) {
        for(var key in obj) {
            if(key.charAt(0) !== '_' && isPlainObject(obj[key])) {
                var baseKey = getBaseKey(key);
                var nextPaths = [];
                var i;
                for(i = 0; i < paths.length; i++) {
                    nextPaths.push(getNextPath(obj, key, paths[i]));
                    if(baseKey !== key) nextPaths.push(getNextPath(obj, baseKey, paths[i]));
                }
                for(i = 0; i < nextPaths.length; i++) {
                    layoutPaths[nextPaths[i]] = 1;
                }
                crawlLayoutForContainers(obj[key], nextPaths);
            }
        }
    }

    function crawlLayoutTemplateForContainers(obj, path) {
        for(var key in obj) {
            if(key.indexOf('defaults') === -1 && isPlainObject(obj[key])) {
                var nextPath = getNextPath(obj, key, path);
                if(layoutPaths[nextPath]) {
                    crawlLayoutTemplateForContainers(obj[key], nextPath);
                }
                else {
                    errorList.push({code: 'unused', path: nextPath});
                }
            }
        }
    }

    if(!isPlainObject(layoutTemplate)) {
        errorList.push({code: 'layout'});
    }
    else {
        crawlLayoutForContainers(fullLayout, ['layout']);
        crawlLayoutTemplateForContainers(layoutTemplate, 'layout');
    }

    if(!isPlainObject(dataTemplate)) {
        errorList.push({code: 'data'});
    }
    else {
        var typeCount = {};
        var traceType;
        for(var i = 0; i < fullData.length; i++) {
            var fullTrace = fullData[i];
            traceType = fullTrace.type;
            typeCount[traceType] = (typeCount[traceType] || 0) + 1;
            if(!fullTrace._fullInput._template) {
                // this takes care of the case of traceType in the data but not
                // the template
                errorList.push({
                    code: 'missing',
                    index: fullTrace._fullInput.index,
                    traceType: traceType
                });
            }
        }
        for(traceType in dataTemplate) {
            var templateCount = dataTemplate[traceType].length;
            var dataCount = typeCount[traceType] || 0;
            if(templateCount > dataCount) {
                errorList.push({
                    code: 'unused',
                    traceType: traceType,
                    templateCount: templateCount,
                    dataCount: dataCount
                });
            }
            else if(dataCount > templateCount) {
                errorList.push({
                    code: 'reused',
                    traceType: traceType,
                    templateCount: templateCount,
                    dataCount: dataCount
                });
            }
        }
    }

    // _template: false is when someone tried to modify an array item
    // but there was no template with matching name
    function crawlForMissingTemplates(obj, path) {
        for(var key in obj) {
            if(key.charAt(0) === '_') continue;
            var val = obj[key];
            var nextPath = getNextPath(obj, key, path);
            if(isPlainObject(val)) {
                if(Array.isArray(obj) && val._template === false && val.templateitemname) {
                    errorList.push({
                        code: 'missing',
                        path: nextPath,
                        templateitemname: val.templateitemname
                    });
                }
                crawlForMissingTemplates(val, nextPath);
            }
            else if(Array.isArray(val) && hasPlainObject(val)) {
                crawlForMissingTemplates(val, nextPath);
            }
        }
    }
    crawlForMissingTemplates({data: fullData, layout: fullLayout}, '');

    if(errorList.length) return errorList.map(format);
};

function hasPlainObject(arr) {
    for(var i = 0; i < arr.length; i++) {
        if(isPlainObject(arr[i])) return true;
    }
}

function format(opts) {
    var msg;
    switch(opts.code) {
        case 'data':
            msg = 'The template has no key data.';
            break;
        case 'layout':
            msg = 'The template has no key layout.';
            break;
        case 'missing':
            if(opts.path) {
                msg = 'There are no templates for item ' + opts.path +
                    ' with name ' + opts.templateitemname;
            }
            else {
                msg = 'There are no templates for trace ' + opts.index +
                    ', of type ' + opts.traceType + '.';
            }
            break;
        case 'unused':
            if(opts.path) {
                msg = 'The template item at ' + opts.path +
                    ' was not used in constructing the plot.';
            }
            else if(opts.dataCount) {
                msg = 'Some of the templates of type ' + opts.traceType +
                    ' were not used. The template has ' + opts.templateCount +
                    ' traces, the data only has ' + opts.dataCount +
                    ' of this type.';
            }
            else {
                msg = 'The template has ' + opts.templateCount +
                    ' traces of type ' + opts.traceType +
                    ' but there are none in the data.';
            }
            break;
        case 'reused':
            msg = 'Some of the templates of type ' + opts.traceType +
                ' were used more than once. The template has ' +
                opts.templateCount + ' traces, the data has ' +
                opts.dataCount + ' of this type.';
            break;
    }
    opts.msg = msg;

    return opts;
}

},{"../lib":694,"../plots/attributes":739,"../plots/plots":806,"./plot_config":730,"./plot_schema":731,"./plot_template":732}],735:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var plotApi = _dereq_('./plot_api');
var Lib = _dereq_('../lib');

var helpers = _dereq_('../snapshot/helpers');
var toSVG = _dereq_('../snapshot/tosvg');
var svgToImg = _dereq_('../snapshot/svgtoimg');

var attrs = {
    format: {
        valType: 'enumerated',
        values: ['png', 'jpeg', 'webp', 'svg'],
        dflt: 'png',
        
    },
    width: {
        valType: 'number',
        min: 1,
        
    },
    height: {
        valType: 'number',
        min: 1,
        
    },
    scale: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
    },
    setBackground: {
        valType: 'any',
        dflt: false,
        
    },
    imageDataOnly: {
        valType: 'boolean',
        dflt: false,
        
    }
};

var IMAGE_URL_PREFIX = /^data:image\/\w+;base64,/;

/** Plotly.toImage
 *
 * @param {object | string | HTML div} gd
 *   can either be a data/layout/config object
 *   or an existing graph <div>
 *   or an id to an existing graph <div>
 * @param {object} opts (see above)
 * @return {promise}
 */
function toImage(gd, opts) {
    opts = opts || {};

    var data;
    var layout;
    var config;

    if(Lib.isPlainObject(gd)) {
        data = gd.data || [];
        layout = gd.layout || {};
        config = gd.config || {};
    } else {
        gd = Lib.getGraphDiv(gd);
        data = Lib.extendDeep([], gd.data);
        layout = Lib.extendDeep({}, gd.layout);
        config = gd._context;
    }

    function isImpliedOrValid(attr) {
        return !(attr in opts) || Lib.validate(opts[attr], attrs[attr]);
    }

    if(!isImpliedOrValid('width') || !isImpliedOrValid('height')) {
        throw new Error('Height and width should be pixel values.');
    }

    if(!isImpliedOrValid('format')) {
        throw new Error('Image format is not jpeg, png, svg or webp.');
    }

    var fullOpts = {};

    function coerce(attr, dflt) {
        return Lib.coerce(opts, fullOpts, attrs, attr, dflt);
    }

    var format = coerce('format');
    var width = coerce('width');
    var height = coerce('height');
    var scale = coerce('scale');
    var setBackground = coerce('setBackground');
    var imageDataOnly = coerce('imageDataOnly');

    // put the cloned div somewhere off screen before attaching to DOM
    var clonedGd = document.createElement('div');
    clonedGd.style.position = 'absolute';
    clonedGd.style.left = '-5000px';
    document.body.appendChild(clonedGd);

    // extend layout with image options
    var layoutImage = Lib.extendFlat({}, layout);
    if(width) layoutImage.width = width;
    if(height) layoutImage.height = height;

    // extend config for static plot
    var configImage = Lib.extendFlat({}, config, {
        _exportedPlot: true,
        staticPlot: true,
        setBackground: setBackground
    });

    var redrawFunc = helpers.getRedrawFunc(clonedGd);

    function wait() {
        return new Promise(function(resolve) {
            setTimeout(resolve, helpers.getDelay(clonedGd._fullLayout));
        });
    }

    function convert() {
        return new Promise(function(resolve, reject) {
            var svg = toSVG(clonedGd, format, scale);
            var width = clonedGd._fullLayout.width;
            var height = clonedGd._fullLayout.height;

            plotApi.purge(clonedGd);
            document.body.removeChild(clonedGd);

            if(format === 'svg') {
                if(imageDataOnly) {
                    return resolve(svg);
                } else {
                    return resolve('data:image/svg+xml,' + encodeURIComponent(svg));
                }
            }

            var canvas = document.createElement('canvas');
            canvas.id = Lib.randstr();

            svgToImg({
                format: format,
                width: width,
                height: height,
                scale: scale,
                canvas: canvas,
                svg: svg,
                // ask svgToImg to return a Promise
                //  rather than EventEmitter
                //  leave EventEmitter for backward
                //  compatibility
                promise: true
            })
            .then(resolve)
            .catch(reject);
        });
    }

    function urlToImageData(url) {
        if(imageDataOnly) {
            return url.replace(IMAGE_URL_PREFIX, '');
        } else {
            return url;
        }
    }

    return new Promise(function(resolve, reject) {
        plotApi.plot(clonedGd, data, layoutImage, configImage)
            .then(redrawFunc)
            .then(wait)
            .then(convert)
            .then(function(url) { resolve(urlToImageData(url)); })
            .catch(function(err) { reject(err); });
    });
}

module.exports = toImage;

},{"../lib":694,"../snapshot/helpers":829,"../snapshot/svgtoimg":831,"../snapshot/tosvg":833,"./plot_api":729}],736:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../lib');
var Plots = _dereq_('../plots/plots');
var PlotSchema = _dereq_('./plot_schema');
var dfltConfig = _dereq_('./plot_config').dfltConfig;

var isPlainObject = Lib.isPlainObject;
var isArray = Array.isArray;
var isArrayOrTypedArray = Lib.isArrayOrTypedArray;

/**
 * Validate a data array and layout object.
 *
 * @param {array} data
 * @param {object} layout
 *
 * @return {array} array of error objects each containing:
 *  - {string} code
 *      error code ('object', 'array', 'schema', 'unused', 'invisible' or 'value')
 *  - {string} container
 *      container where the error occurs ('data' or 'layout')
 *  - {number} trace
 *      trace index of the 'data' container where the error occurs
 *  - {array} path
 *      nested path to the key that causes the error
 *  - {string} astr
 *      attribute string variant of 'path' compatible with Plotly.restyle and
 *      Plotly.relayout.
 *  - {string} msg
 *      error message (shown in console in logger config argument is enable)
 */
module.exports = function validate(data, layout) {
    var schema = PlotSchema.get();
    var errorList = [];
    var gd = {_context: Lib.extendFlat({}, dfltConfig)};

    var dataIn, layoutIn;

    if(isArray(data)) {
        gd.data = Lib.extendDeep([], data);
        dataIn = data;
    }
    else {
        gd.data = [];
        dataIn = [];
        errorList.push(format('array', 'data'));
    }

    if(isPlainObject(layout)) {
        gd.layout = Lib.extendDeep({}, layout);
        layoutIn = layout;
    }
    else {
        gd.layout = {};
        layoutIn = {};
        if(arguments.length > 1) {
            errorList.push(format('object', 'layout'));
        }
    }

    // N.B. dataIn and layoutIn are in general not the same as
    // gd.data and gd.layout after supplyDefaults as some attributes
    // in gd.data and gd.layout (still) get mutated during this step.

    Plots.supplyDefaults(gd);

    var dataOut = gd._fullData;
    var len = dataIn.length;

    for(var i = 0; i < len; i++) {
        var traceIn = dataIn[i];
        var base = ['data', i];

        if(!isPlainObject(traceIn)) {
            errorList.push(format('object', base));
            continue;
        }

        var traceOut = dataOut[i];
        var traceType = traceOut.type;
        var traceSchema = schema.traces[traceType].attributes;

        // PlotSchema does something fancy with trace 'type', reset it here
        // to make the trace schema compatible with Lib.validate.
        traceSchema.type = {
            valType: 'enumerated',
            values: [traceType]
        };

        if(traceOut.visible === false && traceIn.visible !== false) {
            errorList.push(format('invisible', base));
        }

        crawl(traceIn, traceOut, traceSchema, errorList, base);

        var transformsIn = traceIn.transforms;
        var transformsOut = traceOut.transforms;

        if(transformsIn) {
            if(!isArray(transformsIn)) {
                errorList.push(format('array', base, ['transforms']));
            }

            base.push('transforms');

            for(var j = 0; j < transformsIn.length; j++) {
                var path = ['transforms', j];
                var transformType = transformsIn[j].type;

                if(!isPlainObject(transformsIn[j])) {
                    errorList.push(format('object', base, path));
                    continue;
                }

                var transformSchema = schema.transforms[transformType] ?
                    schema.transforms[transformType].attributes :
                    {};

                // add 'type' to transform schema to validate the transform type
                transformSchema.type = {
                    valType: 'enumerated',
                    values: Object.keys(schema.transforms)
                };

                crawl(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path);
            }
        }
    }

    var layoutOut = gd._fullLayout;
    var layoutSchema = fillLayoutSchema(schema, dataOut);

    crawl(layoutIn, layoutOut, layoutSchema, errorList, 'layout');

    // return undefined if no validation errors were found
    return (errorList.length === 0) ? void(0) : errorList;
};

function crawl(objIn, objOut, schema, list, base, path) {
    path = path || [];

    var keys = Object.keys(objIn);

    for(var i = 0; i < keys.length; i++) {
        var k = keys[i];

        // transforms are handled separately
        if(k === 'transforms') continue;

        var p = path.slice();
        p.push(k);

        var valIn = objIn[k];
        var valOut = objOut[k];

        var nestedSchema = getNestedSchema(schema, k);
        var isInfoArray = (nestedSchema || {}).valType === 'info_array';
        var isColorscale = (nestedSchema || {}).valType === 'colorscale';
        var items = (nestedSchema || {}).items;

        if(!isInSchema(schema, k)) {
            list.push(format('schema', base, p));
        }
        else if(isPlainObject(valIn) && isPlainObject(valOut)) {
            crawl(valIn, valOut, nestedSchema, list, base, p);
        }
        else if(isInfoArray && isArray(valIn)) {
            if(valIn.length > valOut.length) {
                list.push(format('unused', base, p.concat(valOut.length)));
            }
            var len = valOut.length;
            var arrayItems = Array.isArray(items);
            if(arrayItems) len = Math.min(len, items.length);
            var m, n, item, valInPart, valOutPart;
            if(nestedSchema.dimensions === 2) {
                for(n = 0; n < len; n++) {
                    if(isArray(valIn[n])) {
                        if(valIn[n].length > valOut[n].length) {
                            list.push(format('unused', base, p.concat(n, valOut[n].length)));
                        }
                        var len2 = valOut[n].length;
                        for(m = 0; m < (arrayItems ? Math.min(len2, items[n].length) : len2); m++) {
                            item = arrayItems ? items[n][m] : items;
                            valInPart = valIn[n][m];
                            valOutPart = valOut[n][m];
                            if(!Lib.validate(valInPart, item)) {
                                list.push(format('value', base, p.concat(n, m), valInPart));
                            }
                            else if(valOutPart !== valInPart && valOutPart !== +valInPart) {
                                list.push(format('dynamic', base, p.concat(n, m), valInPart, valOutPart));
                            }
                        }
                    }
                    else {
                        list.push(format('array', base, p.concat(n), valIn[n]));
                    }
                }
            }
            else {
                for(n = 0; n < len; n++) {
                    item = arrayItems ? items[n] : items;
                    valInPart = valIn[n];
                    valOutPart = valOut[n];
                    if(!Lib.validate(valInPart, item)) {
                        list.push(format('value', base, p.concat(n), valInPart));
                    }
                    else if(valOutPart !== valInPart && valOutPart !== +valInPart) {
                        list.push(format('dynamic', base, p.concat(n), valInPart, valOutPart));
                    }
                }
            }
        }
        else if(nestedSchema.items && !isInfoArray && isArray(valIn)) {
            var _nestedSchema = items[Object.keys(items)[0]];
            var indexList = [];

            var j, _p;

            // loop over valOut items while keeping track of their
            // corresponding input container index (given by _index)
            for(j = 0; j < valOut.length; j++) {
                var _index = valOut[j]._index || j;

                _p = p.slice();
                _p.push(_index);

                if(isPlainObject(valIn[_index]) && isPlainObject(valOut[j])) {
                    indexList.push(_index);
                    var valInj = valIn[_index];
                    var valOutj = valOut[j];
                    if(isPlainObject(valInj) && valInj.visible !== false && valOutj.visible === false) {
                        list.push(format('invisible', base, _p));
                    }
                    else crawl(valInj, valOutj, _nestedSchema, list, base, _p);
                }
            }

            // loop over valIn to determine where it went wrong for some items
            for(j = 0; j < valIn.length; j++) {
                _p = p.slice();
                _p.push(j);

                if(!isPlainObject(valIn[j])) {
                    list.push(format('object', base, _p, valIn[j]));
                }
                else if(indexList.indexOf(j) === -1) {
                    list.push(format('unused', base, _p));
                }
            }
        }
        else if(!isPlainObject(valIn) && isPlainObject(valOut)) {
            list.push(format('object', base, p, valIn));
        }
        else if(!isArrayOrTypedArray(valIn) && isArrayOrTypedArray(valOut) && !isInfoArray && !isColorscale) {
            list.push(format('array', base, p, valIn));
        }
        else if(!(k in objOut)) {
            list.push(format('unused', base, p, valIn));
        }
        else if(!Lib.validate(valIn, nestedSchema)) {
            list.push(format('value', base, p, valIn));
        }
        else if(nestedSchema.valType === 'enumerated' &&
            ((nestedSchema.coerceNumber && valIn !== +valOut) || valIn !== valOut)
        ) {
            list.push(format('dynamic', base, p, valIn, valOut));
        }
    }

    return list;
}

// the 'full' layout schema depends on the traces types presents
function fillLayoutSchema(schema, dataOut) {
    var layoutSchema = schema.layout.layoutAttributes;

    for(var i = 0; i < dataOut.length; i++) {
        var traceOut = dataOut[i];
        var traceSchema = schema.traces[traceOut.type];
        var traceLayoutAttr = traceSchema.layoutAttributes;

        if(traceLayoutAttr) {
            if(traceOut.subplot) {
                Lib.extendFlat(layoutSchema[traceSchema.attributes.subplot.dflt], traceLayoutAttr);
            } else {
                Lib.extendFlat(layoutSchema, traceLayoutAttr);
            }
        }
    }

    return layoutSchema;
}

// validation error codes
var code2msgFunc = {
    object: function(base, astr) {
        var prefix;

        if(base === 'layout' && astr === '') prefix = 'The layout argument';
        else if(base[0] === 'data' && astr === '') {
            prefix = 'Trace ' + base[1] + ' in the data argument';
        }
        else prefix = inBase(base) + 'key ' + astr;

        return prefix + ' must be linked to an object container';
    },
    array: function(base, astr) {
        var prefix;

        if(base === 'data') prefix = 'The data argument';
        else prefix = inBase(base) + 'key ' + astr;

        return prefix + ' must be linked to an array container';
    },
    schema: function(base, astr) {
        return inBase(base) + 'key ' + astr + ' is not part of the schema';
    },
    unused: function(base, astr, valIn) {
        var target = isPlainObject(valIn) ? 'container' : 'key';

        return inBase(base) + target + ' ' + astr + ' did not get coerced';
    },
    dynamic: function(base, astr, valIn, valOut) {
        return [
            inBase(base) + 'key',
            astr,
            '(set to \'' + valIn + '\')',
            'got reset to',
            '\'' + valOut + '\'',
            'during defaults.'
        ].join(' ');
    },
    invisible: function(base, astr) {
        return (
            astr ? (inBase(base) + 'item ' + astr) : ('Trace ' + base[1])
        ) + ' got defaulted to be not visible';
    },
    value: function(base, astr, valIn) {
        return [
            inBase(base) + 'key ' + astr,
            'is set to an invalid value (' + valIn + ')'
        ].join(' ');
    }
};

function inBase(base) {
    if(isArray(base)) return 'In data trace ' + base[1] + ', ';

    return 'In ' + base + ', ';
}

function format(code, base, path, valIn, valOut) {
    path = path || '';

    var container, trace;

    // container is either 'data' or 'layout
    // trace is the trace index if 'data', null otherwise

    if(isArray(base)) {
        container = base[0];
        trace = base[1];
    }
    else {
        container = base;
        trace = null;
    }

    var astr = convertPathToAttributeString(path);
    var msg = code2msgFunc[code](base, astr, valIn, valOut);

    // log to console if logger config option is enabled
    Lib.log(msg);

    return {
        code: code,
        container: container,
        trace: trace,
        path: path,
        astr: astr,
        msg: msg
    };
}

function isInSchema(schema, key) {
    var parts = splitKey(key);
    var keyMinusId = parts.keyMinusId;
    var id = parts.id;

    if((keyMinusId in schema) && schema[keyMinusId]._isSubplotObj && id) {
        return true;
    }

    return (key in schema);
}

function getNestedSchema(schema, key) {
    if(key in schema) return schema[key];

    var parts = splitKey(key);

    return schema[parts.keyMinusId];
}

var idRegex = Lib.counterRegex('([a-z]+)');

function splitKey(key) {
    var idMatch = key.match(idRegex);

    return {
        keyMinusId: idMatch && idMatch[1],
        id: idMatch && idMatch[2]
    };
}

function convertPathToAttributeString(path) {
    if(!isArray(path)) return String(path);

    var astr = '';

    for(var i = 0; i < path.length; i++) {
        var p = path[i];

        if(typeof p === 'number') {
            astr = astr.substr(0, astr.length - 1) + '[' + p + ']';
        }
        else {
            astr += p;
        }

        if(i < path.length - 1) astr += '.';
    }

    return astr;
}

},{"../lib":694,"../plots/plots":806,"./plot_config":730,"./plot_schema":731}],737:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    mode: {
        valType: 'enumerated',
        dflt: 'afterall',
        
        values: ['immediate', 'next', 'afterall'],
        
    },
    direction: {
        valType: 'enumerated',
        
        values: ['forward', 'reverse'],
        dflt: 'forward',
        
    },
    fromcurrent: {
        valType: 'boolean',
        dflt: false,
        
        
    },
    frame: {
        duration: {
            valType: 'number',
            
            min: 0,
            dflt: 500,
            
        },
        redraw: {
            valType: 'boolean',
            
            dflt: true,
            
        },
    },
    transition: {
        duration: {
            valType: 'number',
            
            min: 0,
            dflt: 500,
            editType: 'none',
            
        },
        easing: {
            valType: 'enumerated',
            dflt: 'cubic-in-out',
            values: [
                'linear',
                'quad',
                'cubic',
                'sin',
                'exp',
                'circle',
                'elastic',
                'back',
                'bounce',
                'linear-in',
                'quad-in',
                'cubic-in',
                'sin-in',
                'exp-in',
                'circle-in',
                'elastic-in',
                'back-in',
                'bounce-in',
                'linear-out',
                'quad-out',
                'cubic-out',
                'sin-out',
                'exp-out',
                'circle-out',
                'elastic-out',
                'back-out',
                'bounce-out',
                'linear-in-out',
                'quad-in-out',
                'cubic-in-out',
                'sin-in-out',
                'exp-in-out',
                'circle-in-out',
                'elastic-in-out',
                'back-in-out',
                'bounce-in-out'
            ],
            
            editType: 'none',
            
        },
        ordering: {
            valType: 'enumerated',
            values: ['layout first', 'traces first'],
            dflt: 'layout first',
            
            editType: 'none',
            
        }
    }
};

},{}],738:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../lib');
var Template = _dereq_('../plot_api/plot_template');

/** Convenience wrapper for making array container logic DRY and consistent
 *
 * @param {object} parentObjIn
 *  user input object where the container in question is linked
 *  (i.e. either a user trace object or the user layout object)
 *
 * @param {object} parentObjOut
 *  full object where the coerced container will be linked
 *  (i.e. either a full trace object or the full layout object)
 *
 * @param {object} opts
 *  options object:
 *   - name {string}
 *      name of the key linking the container in question
 *   - inclusionAttr {string}
 *      name of the item attribute for inclusion/exclusion. Default is 'visible'.
 *      Since inclusion is true, use eg 'enabled' instead of 'disabled'.
 *   - handleItemDefaults {function}
 *      defaults method to be called on each item in the array container in question
 *
 *      Its arguments are:
 *          - itemIn {object} item in user layout
 *          - itemOut {object} item in full layout
 *          - parentObj {object} (as in closure)
 *          - opts {object} (as in closure)
 * N.B.
 *
 *  - opts is passed to handleItemDefaults so it can also store
 *    links to supplementary data (e.g. fullData for layout components)
 *
 */
module.exports = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) {
    var name = opts.name;
    var inclusionAttr = opts.inclusionAttr || 'visible';

    var previousContOut = parentObjOut[name];

    var contIn = Lib.isArrayOrTypedArray(parentObjIn[name]) ? parentObjIn[name] : [];
    var contOut = parentObjOut[name] = [];
    var templater = Template.arrayTemplater(parentObjOut, name, inclusionAttr);
    var i, itemOut;

    for(i = 0; i < contIn.length; i++) {
        var itemIn = contIn[i];

        if(!Lib.isPlainObject(itemIn)) {
            itemOut = templater.newItem({});
            itemOut[inclusionAttr] = false;
        }
        else {
            itemOut = templater.newItem(itemIn);
        }

        itemOut._index = i;

        if(itemOut[inclusionAttr] !== false) {
            opts.handleItemDefaults(itemIn, itemOut, parentObjOut, opts);
        }

        contOut.push(itemOut);
    }

    var defaultItems = templater.defaultItems();
    for(i = 0; i < defaultItems.length; i++) {
        itemOut = defaultItems[i];
        itemOut._index = contOut.length;
        opts.handleItemDefaults({}, itemOut, parentObjOut, opts, {});
        contOut.push(itemOut);
    }

    // in case this array gets its defaults rebuilt independent of the whole layout,
    // relink the private keys just for this array.
    if(Lib.isArrayOrTypedArray(previousContOut)) {
        var len = Math.min(previousContOut.length, contOut.length);
        for(i = 0; i < len; i++) {
            Lib.relinkPrivateKeys(contOut[i], previousContOut[i]);
        }
    }

    return contOut;
};

},{"../lib":694,"../plot_api/plot_template":732}],739:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fxAttrs = _dereq_('../components/fx/attributes');

module.exports = {
    type: {
        valType: 'enumerated',
        
        values: [],     // listed dynamically
        dflt: 'scatter',
        editType: 'calc+clearAxisTypes',
        _noTemplating: true // we handle this at a higher level
    },
    visible: {
        valType: 'enumerated',
        values: [true, false, 'legendonly'],
        
        dflt: true,
        editType: 'calc',
        
    },
    showlegend: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'style',
        
    },
    legendgroup: {
        valType: 'string',
        
        dflt: '',
        editType: 'style',
        
    },
    opacity: {
        valType: 'number',
        
        min: 0,
        max: 1,
        dflt: 1,
        editType: 'style',
        
    },
    name: {
        valType: 'string',
        
        editType: 'style',
        
    },
    uid: {
        valType: 'string',
        
        editType: 'plot',
        anim: true,
        
    },
    ids: {
        valType: 'data_array',
        editType: 'calc',
        anim: true,
        
    },
    customdata: {
        valType: 'data_array',
        editType: 'calc',
        
    },

    // N.B. these cannot be 'data_array' as they do not have the same length as
    // other data arrays and arrayOk attributes in general
    //
    // Maybe add another valType:
    // https://github.com/plotly/plotly.js/issues/1894
    selectedpoints: {
        valType: 'any',
        
        editType: 'calc',
        
    },

    hoverinfo: {
        valType: 'flaglist',
        
        flags: ['x', 'y', 'z', 'text', 'name'],
        extras: ['all', 'none', 'skip'],
        arrayOk: true,
        dflt: 'all',
        editType: 'none',
        
    },
    hoverlabel: fxAttrs.hoverlabel,
    stream: {
        token: {
            valType: 'string',
            noBlank: true,
            strict: true,
            
            editType: 'calc',
            
        },
        maxpoints: {
            valType: 'number',
            min: 0,
            max: 10000,
            dflt: 500,
            
            editType: 'calc',
            
        },
        editType: 'calc'
    },
    transforms: {
        _isLinkedToArray: 'transform',
        editType: 'calc',
        
    },
    uirevision: {
        valType: 'any',
        
        editType: 'none',
        
    }
};

},{"../components/fx/attributes":601}],740:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    xaxis: {
        valType: 'subplotid',
        
        dflt: 'x',
        editType: 'calc+clearAxisTypes',
        
    },
    yaxis: {
        valType: 'subplotid',
        
        dflt: 'y',
        editType: 'calc+clearAxisTypes',
        
    }
};

},{}],741:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');
var FP_SAFE = _dereq_('../../constants/numerical').FP_SAFE;
var Registry = _dereq_('../../registry');

module.exports = {
    getAutoRange: getAutoRange,
    makePadFn: makePadFn,
    doAutoRange: doAutoRange,
    findExtremes: findExtremes,
    concatExtremes: concatExtremes
};

/**
 * getAutoRange
 *
 * Collects all _extremes values corresponding to a given axis
 * and computes its auto range.
 *
 * Note that getAutoRange uses return values from findExtremes.
 *
 * @param {object} gd:
 *   graph div object with filled-in fullData and fullLayout, in particular
 *   with filled-in '_extremes' containers:
 *   {
 *      val: calcdata value,
 *      pad: extra pixels beyond this value,
 *      extrapad: bool, does this point want 5% extra padding
 *   }
 * @param {object} ax:
 *   full axis object, in particular with filled-in '_traceIndices'
 *   and '_annIndices' / '_shapeIndices' if applicable
 * @return {array}
 *   an array of [min, max]. These are calcdata for log and category axes
 *   and data for linear and date axes.
 *
 * TODO: we want to change log to data as well, but it's hard to do this
 * maintaining backward compatibility. category will always have to use calcdata
 * though, because otherwise values between categories (or outside all categories)
 * would be impossible.
 */
function getAutoRange(gd, ax) {
    var i, j;
    var newRange = [];

    var getPad = makePadFn(ax);
    var extremes = concatExtremes(gd, ax);
    var minArray = extremes.min;
    var maxArray = extremes.max;

    if(minArray.length === 0 || maxArray.length === 0) {
        return Lib.simpleMap(ax.range, ax.r2l);
    }

    var minmin = minArray[0].val;
    var maxmax = maxArray[0].val;

    for(i = 1; i < minArray.length; i++) {
        if(minmin !== maxmax) break;
        minmin = Math.min(minmin, minArray[i].val);
    }
    for(i = 1; i < maxArray.length; i++) {
        if(minmin !== maxmax) break;
        maxmax = Math.max(maxmax, maxArray[i].val);
    }

    var axReverse = false;

    if(ax.range) {
        var rng = Lib.simpleMap(ax.range, ax.r2l);
        axReverse = rng[1] < rng[0];
    }
    // one-time setting to easily reverse the axis
    // when plotting from code
    if(ax.autorange === 'reversed') {
        axReverse = true;
        ax.autorange = true;
    }

    var rangeMode = ax.rangemode;
    var toZero = rangeMode === 'tozero';
    var nonNegative = rangeMode === 'nonnegative';
    var axLen = ax._length;
    // don't allow padding to reduce the data to < 10% of the length
    var minSpan = axLen / 10;

    var mbest = 0;
    var minpt, maxpt, minbest, maxbest, dp, dv;

    for(i = 0; i < minArray.length; i++) {
        minpt = minArray[i];
        for(j = 0; j < maxArray.length; j++) {
            maxpt = maxArray[j];
            dv = maxpt.val - minpt.val;
            if(dv > 0) {
                dp = axLen - getPad(minpt) - getPad(maxpt);
                if(dp > minSpan) {
                    if(dv / dp > mbest) {
                        minbest = minpt;
                        maxbest = maxpt;
                        mbest = dv / dp;
                    }
                }
                else if(dv / axLen > mbest) {
                    // in case of padding longer than the axis
                    // at least include the unpadded data values.
                    minbest = {val: minpt.val, pad: 0};
                    maxbest = {val: maxpt.val, pad: 0};
                    mbest = dv / axLen;
                }
            }
        }
    }

    function getMaxPad(prev, pt) {
        return Math.max(prev, getPad(pt));
    }

    if(minmin === maxmax) {
        var lower = minmin - 1;
        var upper = minmin + 1;
        if(toZero) {
            if(minmin === 0) {
                // The only value we have on this axis is 0, and we want to
                // autorange so zero is one end.
                // In principle this could be [0, 1] or [-1, 0] but usually
                // 'tozero' pins 0 to the low end, so follow that.
                newRange = [0, 1];
            }
            else {
                var maxPad = (minmin > 0 ? maxArray : minArray).reduce(getMaxPad, 0);
                // we're pushing a single value away from the edge due to its
                // padding, with the other end clamped at zero
                // 0.5 means don't push it farther than the center.
                var rangeEnd = minmin / (1 - Math.min(0.5, maxPad / axLen));
                newRange = minmin > 0 ? [0, rangeEnd] : [rangeEnd, 0];
            }
        } else if(nonNegative) {
            newRange = [Math.max(0, lower), Math.max(1, upper)];
        } else {
            newRange = [lower, upper];
        }
    }
    else {
        if(toZero) {
            if(minbest.val >= 0) {
                minbest = {val: 0, pad: 0};
            }
            if(maxbest.val <= 0) {
                maxbest = {val: 0, pad: 0};
            }
        }
        else if(nonNegative) {
            if(minbest.val - mbest * getPad(minbest) < 0) {
                minbest = {val: 0, pad: 0};
            }
            if(maxbest.val <= 0) {
                maxbest = {val: 1, pad: 0};
            }
        }

        // in case it changed again...
        mbest = (maxbest.val - minbest.val) /
            (axLen - getPad(minbest) - getPad(maxbest));

        newRange = [
            minbest.val - mbest * getPad(minbest),
            maxbest.val + mbest * getPad(maxbest)
        ];
    }

    // maintain reversal
    if(axReverse) newRange.reverse();

    return Lib.simpleMap(newRange, ax.l2r || Number);
}

/*
 * calculate the pixel padding for ax._min and ax._max entries with
 * optional extrapad as 5% of the total axis length
 */
function makePadFn(ax) {
    // 5% padding for points that specify extrapad: true
    var extrappad = ax._length / 20;

    // domain-constrained axes: base extrappad on the unconstrained
    // domain so it's consistent as the domain changes
    if((ax.constrain === 'domain') && ax._inputDomain) {
        extrappad *= (ax._inputDomain[1] - ax._inputDomain[0]) /
            (ax.domain[1] - ax.domain[0]);
    }

    return function getPad(pt) { return pt.pad + (pt.extrapad ? extrappad : 0); };
}

function concatExtremes(gd, ax) {
    var axId = ax._id;
    var fullData = gd._fullData;
    var fullLayout = gd._fullLayout;
    var minArray = [];
    var maxArray = [];
    var i, j, d;

    function _concat(cont, indices) {
        for(i = 0; i < indices.length; i++) {
            var item = cont[indices[i]];
            var extremes = (item._extremes || {})[axId];
            if(item.visible === true && extremes) {
                for(j = 0; j < extremes.min.length; j++) {
                    d = extremes.min[j];
                    collapseMinArray(minArray, d.val, d.pad, {extrapad: d.extrapad});
                }
                for(j = 0; j < extremes.max.length; j++) {
                    d = extremes.max[j];
                    collapseMaxArray(maxArray, d.val, d.pad, {extrapad: d.extrapad});
                }
            }
        }
    }

    _concat(fullData, ax._traceIndices);
    _concat(fullLayout.annotations || [], ax._annIndices || []);
    _concat(fullLayout.shapes || [], ax._shapeIndices || []);

    return {min: minArray, max: maxArray};
}

function doAutoRange(gd, ax) {
    if(ax.autorange) {
        ax.range = getAutoRange(gd, ax);

        ax._r = ax.range.slice();
        ax._rl = Lib.simpleMap(ax._r, ax.r2l);

        // doAutoRange will get called on fullLayout,
        // but we want to report its results back to layout

        var axIn = ax._input;

        // before we edit _input, store preGUI values
        var edits = {};
        edits[ax._attr + '.range'] = ax.range;
        edits[ax._attr + '.autorange'] = ax.autorange;
        Registry.call('_storeDirectGUIEdit', gd.layout, gd._fullLayout._preGUI, edits);

        axIn.range = ax.range.slice();
        axIn.autorange = ax.autorange;
    }

    var anchorAx = ax._anchorAxis;

    if(anchorAx && anchorAx.rangeslider) {
        var axeRangeOpts = anchorAx.rangeslider[ax._name];
        if(axeRangeOpts) {
            if(axeRangeOpts.rangemode === 'auto') {
                axeRangeOpts.range = getAutoRange(gd, ax);
            }
        }
        anchorAx._input.rangeslider[ax._name] = Lib.extendFlat({}, axeRangeOpts);
    }
}

/**
 * findExtremes
 *
 * Find min/max extremes of an array of coordinates on a given axis.
 *
 * Note that findExtremes is called during `calc`, when we don't yet know the axis
 * length; all the inputs should be based solely on the trace data, nothing
 * about the axis layout.
 *
 * Note that `ppad` and `vpad` as well as their asymmetric variants refer to
 * the before and after padding of the passed `data` array, not to the whole axis.
 *
 * @param {object} ax: full axis object
 *   relies on
 *   - ax.type
 *   - ax._m (just its sign)
 *   - ax.d2l
 * @param {array} data:
 *  array of numbers (i.e. already run though ax.d2c)
 * @param {object} opts:
 *  available keys are:
 *      vpad: (number or number array) pad values (data value +-vpad)
 *      ppad: (number or number array) pad pixels (pixel location +-ppad)
 *      ppadplus, ppadminus, vpadplus, vpadminus:
 *          separate padding for each side, overrides symmetric
 *      padded: (boolean) add 5% padding to both ends
 *          (unless one end is overridden by tozero)
 *      tozero: (boolean) make sure to include zero if axis is linear,
 *          and make it a tight bound if possible
 *
 * @return {object}
 *  - min {array of objects}
 *  - max {array of objects}
 *  each object item has fields:
 *    - val {number}
 *    - pad {number}
 *    - extrappad {number}
 *  - opts {object}: a ref to the passed "options" object
 */
function findExtremes(ax, data, opts) {
    if(!opts) opts = {};
    if(!ax._m) ax.setScale();

    var minArray = [];
    var maxArray = [];

    var len = data.length;
    var extrapad = opts.padded || false;
    var tozero = opts.tozero && (ax.type === 'linear' || ax.type === '-');
    var isLog = ax.type === 'log';
    var hasArrayOption = false;
    var i, v, di, dmin, dmax, ppadiplus, ppadiminus, vmin, vmax;

    function makePadAccessor(item) {
        if(Array.isArray(item)) {
            hasArrayOption = true;
            return function(i) { return Math.max(Number(item[i]||0), 0); };
        }
        else {
            var v = Math.max(Number(item||0), 0);
            return function() { return v; };
        }
    }

    var ppadplus = makePadAccessor((ax._m > 0 ?
        opts.ppadplus : opts.ppadminus) || opts.ppad || 0);
    var ppadminus = makePadAccessor((ax._m > 0 ?
        opts.ppadminus : opts.ppadplus) || opts.ppad || 0);
    var vpadplus = makePadAccessor(opts.vpadplus || opts.vpad);
    var vpadminus = makePadAccessor(opts.vpadminus || opts.vpad);

    if(!hasArrayOption) {
        // with no arrays other than `data` we don't need to consider
        // every point, only the extreme data points
        vmin = Infinity;
        vmax = -Infinity;

        if(isLog) {
            for(i = 0; i < len; i++) {
                v = data[i];
                // data is not linearized yet so we still have to filter out negative logs
                if(v < vmin && v > 0) vmin = v;
                if(v > vmax && v < FP_SAFE) vmax = v;
            }
        } else {
            for(i = 0; i < len; i++) {
                v = data[i];
                if(v < vmin && v > -FP_SAFE) vmin = v;
                if(v > vmax && v < FP_SAFE) vmax = v;
            }
        }

        data = [vmin, vmax];
        len = 2;
    }

    var collapseOpts = {tozero: tozero, extrapad: extrapad};

    function addItem(i) {
        di = data[i];
        if(!isNumeric(di)) return;
        ppadiplus = ppadplus(i);
        ppadiminus = ppadminus(i);
        vmin = di - vpadminus(i);
        vmax = di + vpadplus(i);
        // special case for log axes: if vpad makes this object span
        // more than an order of mag, clip it to one order. This is so
        // we don't have non-positive errors or absurdly large lower
        // range due to rounding errors
        if(isLog && vmin < vmax / 10) vmin = vmax / 10;

        dmin = ax.c2l(vmin);
        dmax = ax.c2l(vmax);

        if(tozero) {
            dmin = Math.min(0, dmin);
            dmax = Math.max(0, dmax);
        }
        if(goodNumber(dmin)) {
            collapseMinArray(minArray, dmin, ppadiminus, collapseOpts);
        }
        if(goodNumber(dmax)) {
            collapseMaxArray(maxArray, dmax, ppadiplus, collapseOpts);
        }
    }

    // For efficiency covering monotonic or near-monotonic data,
    // check a few points at both ends first and then sweep
    // through the middle
    var iMax = Math.min(6, len);
    for(i = 0; i < iMax; i++) addItem(i);
    for(i = len - 1; i >= iMax; i--) addItem(i);

    return {
        min: minArray,
        max: maxArray,
        opts: opts
    };
}

function collapseMinArray(array, newVal, newPad, opts) {
    collapseArray(array, newVal, newPad, opts, lessOrEqual);
}

function collapseMaxArray(array, newVal, newPad, opts) {
    collapseArray(array, newVal, newPad, opts, greaterOrEqual);
}

/**
 * collapseArray
 *
 * Takes items from 'array' and compares them to 'newVal', 'newPad'.
 *
 * @param {array} array:
 *  current set of min or max extremes
 * @param {number} newVal:
 *  new value to compare against
 * @param {number} newPad:
 *  pad value associated with 'newVal'
 * @param {object} opts:
 *  - tozero {boolean}
 *  - extrapad {number}
 * @param {function} atLeastAsExtreme:
 *  comparison function, use
 *  - lessOrEqual for min 'array' and
 *  - greaterOrEqual for max 'array'
 *
 * In practice, 'array' is either
 *  - 'extremes[ax._id].min' or
 *  - 'extremes[ax._id].max
 *  found in traces and layout items that affect autorange.
 *
 * Since we don't yet know the relationship between pixels and values
 * (that's what we're trying to figure out!) AND we don't yet know how
 * many pixels `extrapad` represents (it's going to be 5% of the length,
 * but we don't want to have to redo calc just because length changed)
 * two point must satisfy three criteria simultaneously for one to supersede the other:
 *  - at least as extreme a `val`
 *  - at least as big a `pad`
 *  - an unpadded point cannot supersede a padded point, but any other combination can
 *
 * Then:
 * - If the item supersedes the new point, set includeThis false
 * - If the new pt supersedes the item, delete it from 'array'
 */
function collapseArray(array, newVal, newPad, opts, atLeastAsExtreme) {
    var tozero = opts.tozero;
    var extrapad = opts.extrapad;
    var includeThis = true;

    for(var j = 0; j < array.length && includeThis; j++) {
        var v = array[j];
        if(atLeastAsExtreme(v.val, newVal) && v.pad >= newPad && (v.extrapad || !extrapad)) {
            includeThis = false;
            break;
        } else if(atLeastAsExtreme(newVal, v.val) && v.pad <= newPad && (extrapad || !v.extrapad)) {
            array.splice(j, 1);
            j--;
        }
    }
    if(includeThis) {
        var clipAtZero = (tozero && newVal === 0);
        array.push({
            val: newVal,
            pad: clipAtZero ? 0 : newPad,
            extrapad: clipAtZero ? false : extrapad
        });
    }
}

// In order to stop overflow errors, don't consider points
// too close to the limits of js floating point
function goodNumber(v) {
    return isNumeric(v) && Math.abs(v) < FP_SAFE;
}

function lessOrEqual(v0, v1) { return v0 <= v1; }
function greaterOrEqual(v0, v1) { return v0 >= v1; }

},{"../../constants/numerical":671,"../../lib":694,"../../registry":825,"fast-isnumeric":215}],742:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');
var Plots = _dereq_('../../plots/plots');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var Titles = _dereq_('../../components/titles');
var Color = _dereq_('../../components/color');
var Drawing = _dereq_('../../components/drawing');

var axAttrs = _dereq_('./layout_attributes');
var cleanTicks = _dereq_('./clean_ticks');

var constants = _dereq_('../../constants/numerical');
var ONEAVGYEAR = constants.ONEAVGYEAR;
var ONEAVGMONTH = constants.ONEAVGMONTH;
var ONEDAY = constants.ONEDAY;
var ONEHOUR = constants.ONEHOUR;
var ONEMIN = constants.ONEMIN;
var ONESEC = constants.ONESEC;
var MINUS_SIGN = constants.MINUS_SIGN;
var BADNUM = constants.BADNUM;

var MID_SHIFT = _dereq_('../../constants/alignment').MID_SHIFT;
var LINE_SPACING = _dereq_('../../constants/alignment').LINE_SPACING;

var axes = module.exports = {};

axes.setConvert = _dereq_('./set_convert');
var autoType = _dereq_('./axis_autotype');

var axisIds = _dereq_('./axis_ids');
axes.id2name = axisIds.id2name;
axes.name2id = axisIds.name2id;
axes.cleanId = axisIds.cleanId;
axes.list = axisIds.list;
axes.listIds = axisIds.listIds;
axes.getFromId = axisIds.getFromId;
axes.getFromTrace = axisIds.getFromTrace;

var autorange = _dereq_('./autorange');
axes.getAutoRange = autorange.getAutoRange;
axes.findExtremes = autorange.findExtremes;

/*
 * find the list of possible axes to reference with an xref or yref attribute
 * and coerce it to that list
 *
 * attr: the attribute we're generating a reference for. Should end in 'x' or 'y'
 *     but can be prefixed, like 'ax' for annotation's arrow x
 * dflt: the default to coerce to, or blank to use the first axis (falling back on
 *     extraOption if there is no axis)
 * extraOption: aside from existing axes with this letter, what non-axis value is allowed?
 *     Only required if it's different from `dflt`
 */
axes.coerceRef = function(containerIn, containerOut, gd, attr, dflt, extraOption) {
    var axLetter = attr.charAt(attr.length - 1);
    var axlist = gd._fullLayout._subplots[axLetter + 'axis'];
    var refAttr = attr + 'ref';
    var attrDef = {};

    if(!dflt) dflt = axlist[0] || extraOption;
    if(!extraOption) extraOption = dflt;

    // data-ref annotations are not supported in gl2d yet

    attrDef[refAttr] = {
        valType: 'enumerated',
        values: axlist.concat(extraOption ? [extraOption] : []),
        dflt: dflt
    };

    // xref, yref
    return Lib.coerce(containerIn, containerOut, attrDef, refAttr);
};

/*
 * coerce position attributes (range-type) that can be either on axes or absolute
 * (paper or pixel) referenced. The biggest complication here is that we don't know
 * before looking at the axis whether the value must be a number or not (it may be
 * a date string), so we can't use the regular valType='number' machinery
 *
 * axRef (string): the axis this position is referenced to, or:
 *     paper: fraction of the plot area
 *     pixel: pixels relative to some starting position
 * attr (string): the attribute in containerOut we are coercing
 * dflt (number): the default position, as a fraction or pixels. If the attribute
 *     is to be axis-referenced, this will be converted to an axis data value
 *
 * Also cleans the values, since the attribute definition itself has to say
 * valType: 'any' to handle date axes. This allows us to accept:
 * - for category axes: category names, and convert them here into serial numbers.
 *   Note that this will NOT work for axis range endpoints, because we don't know
 *   the category list yet (it's set by ax.makeCalcdata during calc)
 *   but it works for component (note, shape, images) positions.
 * - for date axes: JS Dates or milliseconds, and convert to date strings
 * - for other types: coerce them to numbers
 */
axes.coercePosition = function(containerOut, gd, coerce, axRef, attr, dflt) {
    var cleanPos, pos;

    if(axRef === 'paper' || axRef === 'pixel') {
        cleanPos = Lib.ensureNumber;
        pos = coerce(attr, dflt);
    } else {
        var ax = axes.getFromId(gd, axRef);
        dflt = ax.fraction2r(dflt);
        pos = coerce(attr, dflt);
        cleanPos = ax.cleanPos;
    }

    containerOut[attr] = cleanPos(pos);
};

axes.cleanPosition = function(pos, gd, axRef) {
    var cleanPos = (axRef === 'paper' || axRef === 'pixel') ?
        Lib.ensureNumber :
        axes.getFromId(gd, axRef).cleanPos;

    return cleanPos(pos);
};

axes.redrawComponents = function(gd, axIds) {
    axIds = axIds ? axIds : axes.listIds(gd);

    var fullLayout = gd._fullLayout;

    function _redrawOneComp(moduleName, methodName, stashName, shortCircuit) {
        var method = Registry.getComponentMethod(moduleName, methodName);
        var stash = {};

        for(var i = 0; i < axIds.length; i++) {
            var ax = fullLayout[axes.id2name(axIds[i])];
            var indices = ax[stashName];

            for(var j = 0; j < indices.length; j++) {
                var ind = indices[j];

                if(!stash[ind]) {
                    method(gd, ind);
                    stash[ind] = 1;
                    // once is enough for images (which doesn't use the `i` arg anyway)
                    if(shortCircuit) return;
                }
            }
        }
    }

    // annotations and shapes 'draw' method is slow,
    // use the finer-grained 'drawOne' method instead
    _redrawOneComp('annotations', 'drawOne', '_annIndices');
    _redrawOneComp('shapes', 'drawOne', '_shapeIndices');
    _redrawOneComp('images', 'draw', '_imgIndices', true);
};

var getDataConversions = axes.getDataConversions = function(gd, trace, target, targetArray) {
    var ax;

    // If target points to an axis, use the type we already have for that
    // axis to find the data type. Otherwise use the values to autotype.
    var d2cTarget = (target === 'x' || target === 'y' || target === 'z') ?
        target :
        targetArray;

    // In the case of an array target, make a mock data array
    // and call supplyDefaults to the data type and
    // setup the data-to-calc method.
    if(Array.isArray(d2cTarget)) {
        ax = {
            type: autoType(targetArray),
            _categories: []
        };
        axes.setConvert(ax);

        // build up ax._categories (usually done during ax.makeCalcdata()
        if(ax.type === 'category') {
            for(var i = 0; i < targetArray.length; i++) {
                ax.d2c(targetArray[i]);
            }
        }
        // TODO what to do for transforms?
    } else {
        ax = axes.getFromTrace(gd, trace, d2cTarget);
    }

    // if 'target' has corresponding axis
    // -> use setConvert method
    if(ax) return {d2c: ax.d2c, c2d: ax.c2d};

    // special case for 'ids'
    // -> cast to String
    if(d2cTarget === 'ids') return {d2c: toString, c2d: toString};

    // otherwise (e.g. numeric-array of 'marker.color' or 'marker.size')
    // -> cast to Number

    return {d2c: toNum, c2d: toNum};
};

function toNum(v) { return +v; }
function toString(v) { return String(v); }

axes.getDataToCoordFunc = function(gd, trace, target, targetArray) {
    return getDataConversions(gd, trace, target, targetArray).d2c;
};

// get counteraxis letter for this axis (name or id)
// this can also be used as the id for default counter axis
axes.counterLetter = function(id) {
    var axLetter = id.charAt(0);
    if(axLetter === 'x') return 'y';
    if(axLetter === 'y') return 'x';
};

// incorporate a new minimum difference and first tick into
// forced
// note that _forceTick0 is linearized, so needs to be turned into
// a range value for setting tick0
axes.minDtick = function(ax, newDiff, newFirst, allow) {
    // doesn't make sense to do forced min dTick on log or category axes,
    // and the plot itself may decide to cancel (ie non-grouped bars)
    if(['log', 'category', 'multicategory'].indexOf(ax.type) !== -1 || !allow) {
        ax._minDtick = 0;
    }
    // undefined means there's nothing there yet
    else if(ax._minDtick === undefined) {
        ax._minDtick = newDiff;
        ax._forceTick0 = newFirst;
    }
    else if(ax._minDtick) {
        // existing minDtick is an integer multiple of newDiff
        // (within rounding err)
        // and forceTick0 can be shifted to newFirst
        if((ax._minDtick / newDiff + 1e-6) % 1 < 2e-6 &&
                (((newFirst - ax._forceTick0) / newDiff % 1) +
                    1.000001) % 1 < 2e-6) {
            ax._minDtick = newDiff;
            ax._forceTick0 = newFirst;
        }
        // if the converse is true (newDiff is a multiple of minDtick and
        // newFirst can be shifted to forceTick0) then do nothing - same
        // forcing stands. Otherwise, cancel forced minimum
        else if((newDiff / ax._minDtick + 1e-6) % 1 > 2e-6 ||
                (((newFirst - ax._forceTick0) / ax._minDtick % 1) +
                    1.000001) % 1 > 2e-6) {
            ax._minDtick = 0;
        }
    }
};

// save a copy of the initial axis ranges in fullLayout
// use them in mode bar and dblclick events
axes.saveRangeInitial = function(gd, overwrite) {
    var axList = axes.list(gd, '', true);
    var hasOneAxisChanged = false;

    for(var i = 0; i < axList.length; i++) {
        var ax = axList[i];
        var isNew = (ax._rangeInitial === undefined);
        var hasChanged = isNew || !(
            ax.range[0] === ax._rangeInitial[0] &&
            ax.range[1] === ax._rangeInitial[1]
        );

        if((isNew && ax.autorange === false) || (overwrite && hasChanged)) {
            ax._rangeInitial = ax.range.slice();
            hasOneAxisChanged = true;
        }
    }

    return hasOneAxisChanged;
};

// save a copy of the initial spike visibility
axes.saveShowSpikeInitial = function(gd, overwrite) {
    var axList = axes.list(gd, '', true);
    var hasOneAxisChanged = false;
    var allSpikesEnabled = 'on';

    for(var i = 0; i < axList.length; i++) {
        var ax = axList[i];
        var isNew = (ax._showSpikeInitial === undefined);
        var hasChanged = isNew || !(ax.showspikes === ax._showspikes);

        if(isNew || (overwrite && hasChanged)) {
            ax._showSpikeInitial = ax.showspikes;
            hasOneAxisChanged = true;
        }

        if(allSpikesEnabled === 'on' && !ax.showspikes) {
            allSpikesEnabled = 'off';
        }
    }
    gd._fullLayout._cartesianSpikesEnabled = allSpikesEnabled;
    return hasOneAxisChanged;
};

axes.autoBin = function(data, ax, nbins, is2d, calendar, size) {
    var dataMin = Lib.aggNums(Math.min, null, data);
    var dataMax = Lib.aggNums(Math.max, null, data);

    if(ax.type === 'category' || ax.type === 'multicategory') {
        return {
            start: dataMin - 0.5,
            end: dataMax + 0.5,
            size: Math.max(1, Math.round(size) || 1),
            _dataSpan: dataMax - dataMin,
        };
    }

    if(!calendar) calendar = ax.calendar;

    // piggyback off tick code to make "nice" bin sizes and edges
    var dummyAx;
    if(ax.type === 'log') {
        dummyAx = {
            type: 'linear',
            range: [dataMin, dataMax]
        };
    } else {
        dummyAx = {
            type: ax.type,
            range: Lib.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar),
            calendar: calendar
        };
    }
    axes.setConvert(dummyAx);

    size = size && cleanTicks.dtick(size, dummyAx.type);

    if(size) {
        dummyAx.dtick = size;
        dummyAx.tick0 = cleanTicks.tick0(undefined, dummyAx.type, calendar);
    }
    else {
        var size0;
        if(nbins) size0 = ((dataMax - dataMin) / nbins);
        else {
            // totally auto: scale off std deviation so the highest bin is
            // somewhat taller than the total number of bins, but don't let
            // the size get smaller than the 'nice' rounded down minimum
            // difference between values
            var distinctData = Lib.distinctVals(data);
            var msexp = Math.pow(10, Math.floor(
                Math.log(distinctData.minDiff) / Math.LN10));
            var minSize = msexp * Lib.roundUp(
                distinctData.minDiff / msexp, [0.9, 1.9, 4.9, 9.9], true);
            size0 = Math.max(minSize, 2 * Lib.stdev(data) /
                Math.pow(data.length, is2d ? 0.25 : 0.4));

            // fallback if ax.d2c output BADNUMs
            // e.g. when user try to plot categorical bins
            // on a layout.xaxis.type: 'linear'
            if(!isNumeric(size0)) size0 = 1;
        }

        axes.autoTicks(dummyAx, size0);
    }


    var finalSize = dummyAx.dtick;
    var binStart = axes.tickIncrement(
            axes.tickFirst(dummyAx), finalSize, 'reverse', calendar);
    var binEnd, bincount;

    // check for too many data points right at the edges of bins
    // (>50% within 1% of bin edges) or all data points integral
    // and offset the bins accordingly
    if(typeof finalSize === 'number') {
        binStart = autoShiftNumericBins(binStart, data, dummyAx, dataMin, dataMax);

        bincount = 1 + Math.floor((dataMax - binStart) / finalSize);
        binEnd = binStart + bincount * finalSize;
    }
    else {
        // month ticks - should be the only nonlinear kind we have at this point.
        // dtick (as supplied by axes.autoTick) only has nonlinear values on
        // date and log axes, but even if you display a histogram on a log axis
        // we bin it on a linear axis (which one could argue against, but that's
        // a separate issue)
        if(dummyAx.dtick.charAt(0) === 'M') {
            binStart = autoShiftMonthBins(binStart, data, finalSize, dataMin, calendar);
        }

        // calculate the endpoint for nonlinear ticks - you have to
        // just increment until you're done
        binEnd = binStart;
        bincount = 0;
        while(binEnd <= dataMax) {
            binEnd = axes.tickIncrement(binEnd, finalSize, false, calendar);
            bincount++;
        }
    }

    return {
        start: ax.c2r(binStart, 0, calendar),
        end: ax.c2r(binEnd, 0, calendar),
        size: finalSize,
        _dataSpan: dataMax - dataMin
    };
};


function autoShiftNumericBins(binStart, data, ax, dataMin, dataMax) {
    var edgecount = 0;
    var midcount = 0;
    var intcount = 0;
    var blankCount = 0;

    function nearEdge(v) {
        // is a value within 1% of a bin edge?
        return (1 + (v - binStart) * 100 / ax.dtick) % 100 < 2;
    }

    for(var i = 0; i < data.length; i++) {
        if(data[i] % 1 === 0) intcount++;
        else if(!isNumeric(data[i])) blankCount++;

        if(nearEdge(data[i])) edgecount++;
        if(nearEdge(data[i] + ax.dtick / 2)) midcount++;
    }
    var dataCount = data.length - blankCount;

    if(intcount === dataCount && ax.type !== 'date') {
        // all integers: if bin size is <1, it's because
        // that was specifically requested (large nbins)
        // so respect that... but center the bins containing
        // integers on those integers
        if(ax.dtick < 1) {
            binStart = dataMin - 0.5 * ax.dtick;
        }
        // otherwise start half an integer down regardless of
        // the bin size, just enough to clear up endpoint
        // ambiguity about which integers are in which bins.
        else {
            binStart -= 0.5;
            if(binStart + ax.dtick < dataMin) binStart += ax.dtick;
        }
    }
    else if(midcount < dataCount * 0.1) {
        if(edgecount > dataCount * 0.3 ||
                nearEdge(dataMin) || nearEdge(dataMax)) {
            // lots of points at the edge, not many in the middle
            // shift half a bin
            var binshift = ax.dtick / 2;
            binStart += (binStart + binshift < dataMin) ? binshift : -binshift;
        }
    }
    return binStart;
}


function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) {
    var stats = Lib.findExactDates(data, calendar);
    // number of data points that needs to be an exact value
    // to shift that increment to (near) the bin center
    var threshold = 0.8;

    if(stats.exactDays > threshold) {
        var numMonths = Number(dtick.substr(1));

        if((stats.exactYears > threshold) && (numMonths % 12 === 0)) {
            // The exact middle of a non-leap-year is 1.5 days into July
            // so if we start the bins here, all but leap years will
            // get hover-labeled as exact years.
            binStart = axes.tickIncrement(binStart, 'M6', 'reverse') + ONEDAY * 1.5;
        }
        else if(stats.exactMonths > threshold) {
            // Months are not as clean, but if we shift half the *longest*
            // month (31/2 days) then 31-day months will get labeled exactly
            // and shorter months will get labeled with the correct month
            // but shifted 12-36 hours into it.
            binStart = axes.tickIncrement(binStart, 'M1', 'reverse') + ONEDAY * 15.5;
        }
        else {
            // Shifting half a day is exact, but since these are month bins it
            // will always give a somewhat odd-looking label, until we do something
            // smarter like showing the bin boundaries (or the bounds of the actual
            // data in each bin)
            binStart -= ONEDAY / 2;
        }
        var nextBinStart = axes.tickIncrement(binStart, dtick);

        if(nextBinStart <= dataMin) return nextBinStart;
    }
    return binStart;
}

// ----------------------------------------------------
// Ticks and grids
// ----------------------------------------------------

// ensure we have tick0, dtick, and tick rounding calculated
axes.prepTicks = function(ax) {
    var rng = Lib.simpleMap(ax.range, ax.r2l);

    // calculate max number of (auto) ticks to display based on plot size
    if(ax.tickmode === 'auto' || !ax.dtick) {
        var nt = ax.nticks;
        var minPx;

        if(!nt) {
            if(ax.type === 'category' || ax.type === 'multicategory') {
                minPx = ax.tickfont ? (ax.tickfont.size || 12) * 1.2 : 15;
                nt = ax._length / minPx;
            } else {
                minPx = ax._id.charAt(0) === 'y' ? 40 : 80;
                nt = Lib.constrain(ax._length / minPx, 4, 9) + 1;
            }

            // radial axes span half their domain,
            // multiply nticks value by two to get correct number of auto ticks.
            if(ax._name === 'radialaxis') nt *= 2;
        }

        // add a couple of extra digits for filling in ticks when we
        // have explicit tickvals without tick text
        if(ax.tickmode === 'array') nt *= 100;

        axes.autoTicks(ax, Math.abs(rng[1] - rng[0]) / nt);
        // check for a forced minimum dtick
        if(ax._minDtick > 0 && ax.dtick < ax._minDtick * 2) {
            ax.dtick = ax._minDtick;
            ax.tick0 = ax.l2r(ax._forceTick0);
        }
    }

    // check for missing tick0
    if(!ax.tick0) {
        ax.tick0 = (ax.type === 'date') ? '2000-01-01' : 0;
    }

    // ensure we don't try to make ticks below our minimum precision
    // see https://github.com/plotly/plotly.js/issues/2892
    if(ax.type === 'date' && ax.dtick < 0.1) ax.dtick = 0.1;

    // now figure out rounding of tick values
    autoTickRound(ax);
};

// calculate the ticks: text, values, positioning
// if ticks are set to automatic, determine the right values (tick0,dtick)
// in any case, set tickround to # of digits to round tick labels to,
// or codes to this effect for log and date scales
axes.calcTicks = function calcTicks(ax) {
    axes.prepTicks(ax);
    var rng = Lib.simpleMap(ax.range, ax.r2l);

    // now that we've figured out the auto values for formatting
    // in case we're missing some ticktext, we can break out for array ticks
    if(ax.tickmode === 'array') return arrayTicks(ax);

    // find the first tick
    ax._tmin = axes.tickFirst(ax);

    // add a tiny bit so we get ticks which may have rounded out
    var startTick = rng[0] * 1.0001 - rng[1] * 0.0001;
    var endTick = rng[1] * 1.0001 - rng[0] * 0.0001;
    // check for reversed axis
    var axrev = (rng[1] < rng[0]);

    // No visible ticks? Quit.
    // I've only seen this on category axes with all categories off the edge.
    if((ax._tmin < startTick) !== axrev) return [];

    // return the full set of tick vals
    var vals = [];
    if(ax.type === 'category' || ax.type === 'multicategory') {
        endTick = (axrev) ? Math.max(-0.5, endTick) :
            Math.min(ax._categories.length - 0.5, endTick);
    }

    var xPrevious = null;
    var maxTicks = Math.max(1000, ax._length || 0);
    for(var x = ax._tmin;
            (axrev) ? (x >= endTick) : (x <= endTick);
            x = axes.tickIncrement(x, ax.dtick, axrev, ax.calendar)) {
        // prevent infinite loops - no more than one tick per pixel,
        // and make sure each value is different from the previous
        if(vals.length > maxTicks || x === xPrevious) break;
        xPrevious = x;

        vals.push(x);
    }

    // If same angle over a full circle, the last tick vals is a duplicate.
    // TODO must do something similar for angular date axes.
    if(isAngular(ax) && Math.abs(rng[1] - rng[0]) === 360) {
        vals.pop();
    }

    // save the last tick as well as first, so we can
    // show the exponent only on the last one
    ax._tmax = vals[vals.length - 1];

    // for showing the rest of a date when the main tick label is only the
    // latter part: ax._prevDateHead holds what we showed most recently.
    // Start with it cleared and mark that we're in calcTicks (ie calculating a
    // whole string of these so we should care what the previous date head was!)
    ax._prevDateHead = '';
    ax._inCalcTicks = true;

    var ticksOut = new Array(vals.length);
    for(var i = 0; i < vals.length; i++) ticksOut[i] = axes.tickText(ax, vals[i]);

    ax._inCalcTicks = false;

    return ticksOut;
};

function arrayTicks(ax) {
    var vals = ax.tickvals;
    var text = ax.ticktext;
    var ticksOut = new Array(vals.length);
    var rng = Lib.simpleMap(ax.range, ax.r2l);
    var r0expanded = rng[0] * 1.0001 - rng[1] * 0.0001;
    var r1expanded = rng[1] * 1.0001 - rng[0] * 0.0001;
    var tickMin = Math.min(r0expanded, r1expanded);
    var tickMax = Math.max(r0expanded, r1expanded);
    var j = 0;

    // without a text array, just format the given values as any other ticks
    // except with more precision to the numbers
    if(!Array.isArray(text)) text = [];

    // make sure showing ticks doesn't accidentally add new categories
    // TODO multicategory, if we allow ticktext / tickvals
    var tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l;

    // array ticks on log axes always show the full number
    // (if no explicit ticktext overrides it)
    if(ax.type === 'log' && String(ax.dtick).charAt(0) !== 'L') {
        ax.dtick = 'L' + Math.pow(10, Math.floor(Math.min(ax.range[0], ax.range[1])) - 1);
    }

    for(var i = 0; i < vals.length; i++) {
        var vali = tickVal2l(vals[i]);
        if(vali > tickMin && vali < tickMax) {
            if(text[i] === undefined) ticksOut[j] = axes.tickText(ax, vali);
            else ticksOut[j] = tickTextObj(ax, vali, String(text[i]));
            j++;
        }
    }

    if(j < vals.length) ticksOut.splice(j, vals.length - j);

    return ticksOut;
}

var roundBase10 = [2, 5, 10];
var roundBase24 = [1, 2, 3, 6, 12];
var roundBase60 = [1, 2, 5, 10, 15, 30];
// 2&3 day ticks are weird, but need something btwn 1&7
var roundDays = [1, 2, 3, 7, 14];
// approx. tick positions for log axes, showing all (1) and just 1, 2, 5 (2)
// these don't have to be exact, just close enough to round to the right value
var roundLog1 = [-0.046, 0, 0.301, 0.477, 0.602, 0.699, 0.778, 0.845, 0.903, 0.954, 1];
var roundLog2 = [-0.301, 0, 0.301, 0.699, 1];
// N.B. `thetaunit; 'radians' angular axes must be converted to degrees
var roundAngles = [15, 30, 45, 90, 180];

function roundDTick(roughDTick, base, roundingSet) {
    return base * Lib.roundUp(roughDTick / base, roundingSet);
}

// autoTicks: calculate best guess at pleasant ticks for this axis
// inputs:
//      ax - an axis object
//      roughDTick - rough tick spacing (to be turned into a nice round number)
// outputs (into ax):
//   tick0: starting point for ticks (not necessarily on the graph)
//      usually 0 for numeric (=10^0=1 for log) or jan 1, 2000 for dates
//   dtick: the actual, nice round tick spacing, usually a little larger than roughDTick
//      if the ticks are spaced linearly (linear scale, categories,
//          log with only full powers, date ticks < month),
//          this will just be a number
//      months: M#
//      years: M# where # is 12*number of years
//      log with linear ticks: L# where # is the linear tick spacing
//      log showing powers plus some intermediates:
//          D1 shows all digits, D2 shows 2 and 5
axes.autoTicks = function(ax, roughDTick) {
    var base;

    function getBase(v) {
        return Math.pow(v, Math.floor(Math.log(roughDTick) / Math.LN10));
    }

    if(ax.type === 'date') {
        ax.tick0 = Lib.dateTick0(ax.calendar);
        // the criteria below are all based on the rough spacing we calculate
        // being > half of the final unit - so precalculate twice the rough val
        var roughX2 = 2 * roughDTick;

        if(roughX2 > ONEAVGYEAR) {
            roughDTick /= ONEAVGYEAR;
            base = getBase(10);
            ax.dtick = 'M' + (12 * roundDTick(roughDTick, base, roundBase10));
        }
        else if(roughX2 > ONEAVGMONTH) {
            roughDTick /= ONEAVGMONTH;
            ax.dtick = 'M' + roundDTick(roughDTick, 1, roundBase24);
        }
        else if(roughX2 > ONEDAY) {
            ax.dtick = roundDTick(roughDTick, ONEDAY, roundDays);
            // get week ticks on sunday
            // this will also move the base tick off 2000-01-01 if dtick is
            // 2 or 3 days... but that's a weird enough case that we'll ignore it.
            ax.tick0 = Lib.dateTick0(ax.calendar, true);
        }
        else if(roughX2 > ONEHOUR) {
            ax.dtick = roundDTick(roughDTick, ONEHOUR, roundBase24);
        }
        else if(roughX2 > ONEMIN) {
            ax.dtick = roundDTick(roughDTick, ONEMIN, roundBase60);
        }
        else if(roughX2 > ONESEC) {
            ax.dtick = roundDTick(roughDTick, ONESEC, roundBase60);
        }
        else {
            // milliseconds
            base = getBase(10);
            ax.dtick = roundDTick(roughDTick, base, roundBase10);
        }
    }
    else if(ax.type === 'log') {
        ax.tick0 = 0;
        var rng = Lib.simpleMap(ax.range, ax.r2l);

        if(roughDTick > 0.7) {
            // only show powers of 10
            ax.dtick = Math.ceil(roughDTick);
        }
        else if(Math.abs(rng[1] - rng[0]) < 1) {
            // span is less than one power of 10
            var nt = 1.5 * Math.abs((rng[1] - rng[0]) / roughDTick);

            // ticks on a linear scale, labeled fully
            roughDTick = Math.abs(Math.pow(10, rng[1]) -
                Math.pow(10, rng[0])) / nt;
            base = getBase(10);
            ax.dtick = 'L' + roundDTick(roughDTick, base, roundBase10);
        }
        else {
            // include intermediates between powers of 10,
            // labeled with small digits
            // ax.dtick = "D2" (show 2 and 5) or "D1" (show all digits)
            ax.dtick = (roughDTick > 0.3) ? 'D2' : 'D1';
        }
    }
    else if(ax.type === 'category' || ax.type === 'multicategory') {
        ax.tick0 = 0;
        ax.dtick = Math.ceil(Math.max(roughDTick, 1));
    }
    else if(isAngular(ax)) {
        ax.tick0 = 0;
        base = 1;
        ax.dtick = roundDTick(roughDTick, base, roundAngles);
    }
    else {
        // auto ticks always start at 0
        ax.tick0 = 0;
        base = getBase(10);
        ax.dtick = roundDTick(roughDTick, base, roundBase10);
    }

    // prevent infinite loops
    if(ax.dtick === 0) ax.dtick = 1;

    // TODO: this is from log axis histograms with autorange off
    if(!isNumeric(ax.dtick) && typeof ax.dtick !== 'string') {
        var olddtick = ax.dtick;
        ax.dtick = 1;
        throw 'ax.dtick error: ' + String(olddtick);
    }
};

// after dtick is already known, find tickround = precision
// to display in tick labels
//   for numeric ticks, integer # digits after . to round to
//   for date ticks, the last date part to show (y,m,d,H,M,S)
//      or an integer # digits past seconds
function autoTickRound(ax) {
    var dtick = ax.dtick;

    ax._tickexponent = 0;
    if(!isNumeric(dtick) && typeof dtick !== 'string') {
        dtick = 1;
    }

    if(ax.type === 'category' || ax.type === 'multicategory') {
        ax._tickround = null;
    }
    if(ax.type === 'date') {
        // If tick0 is unusual, give tickround a bit more information
        // not necessarily *all* the information in tick0 though, if it's really odd
        // minimal string length for tick0: 'd' is 10, 'M' is 16, 'S' is 19
        // take off a leading minus (year < 0) and i (intercalary month) so length is consistent
        var tick0ms = ax.r2l(ax.tick0);
        var tick0str = ax.l2r(tick0ms).replace(/(^-|i)/g, '');
        var tick0len = tick0str.length;

        if(String(dtick).charAt(0) === 'M') {
            // any tick0 more specific than a year: alway show the full date
            if(tick0len > 10 || tick0str.substr(5) !== '01-01') ax._tickround = 'd';
            // show the month unless ticks are full multiples of a year
            else ax._tickround = (+(dtick.substr(1)) % 12 === 0) ? 'y' : 'm';
        }
        else if((dtick >= ONEDAY && tick0len <= 10) || (dtick >= ONEDAY * 15)) ax._tickround = 'd';
        else if((dtick >= ONEMIN && tick0len <= 16) || (dtick >= ONEHOUR)) ax._tickround = 'M';
        else if((dtick >= ONESEC && tick0len <= 19) || (dtick >= ONEMIN)) ax._tickround = 'S';
        else {
            // tickround is a number of digits of fractional seconds
            // of any two adjacent ticks, at least one will have the maximum fractional digits
            // of all possible ticks - so take the max. length of tick0 and the next one
            var tick1len = ax.l2r(tick0ms + dtick).replace(/^-/, '').length;
            ax._tickround = Math.max(tick0len, tick1len) - 20;

            // We shouldn't get here... but in case there's a situation I'm
            // not thinking of where tick0str and tick1str are identical or
            // something, fall back on maximum precision
            if(ax._tickround < 0) ax._tickround = 4;
        }
    }
    else if(isNumeric(dtick) || dtick.charAt(0) === 'L') {
        // linear or log (except D1, D2)
        var rng = ax.range.map(ax.r2d || Number);
        if(!isNumeric(dtick)) dtick = Number(dtick.substr(1));
        // 2 digits past largest digit of dtick
        ax._tickround = 2 - Math.floor(Math.log(dtick) / Math.LN10 + 0.01);

        var maxend = Math.max(Math.abs(rng[0]), Math.abs(rng[1]));

        var rangeexp = Math.floor(Math.log(maxend) / Math.LN10 + 0.01);
        if(Math.abs(rangeexp) > 3) {
            if(isSIFormat(ax.exponentformat) && !beyondSI(rangeexp)) {
                ax._tickexponent = 3 * Math.round((rangeexp - 1) / 3);
            }
            else ax._tickexponent = rangeexp;
        }
    }
    // D1 or D2 (log)
    else ax._tickround = null;
}

// months and years don't have constant millisecond values
// (but a year is always 12 months so we only need months)
// log-scale ticks are also not consistently spaced, except
// for pure powers of 10
// numeric ticks always have constant differences, other datetime ticks
// can all be calculated as constant number of milliseconds
axes.tickIncrement = function(x, dtick, axrev, calendar) {
    var axSign = axrev ? -1 : 1;

    // includes linear, all dates smaller than month, and pure 10^n in log
    if(isNumeric(dtick)) return x + axSign * dtick;

    // everything else is a string, one character plus a number
    var tType = dtick.charAt(0);
    var dtSigned = axSign * Number(dtick.substr(1));

    // Dates: months (or years - see Lib.incrementMonth)
    if(tType === 'M') return Lib.incrementMonth(x, dtSigned, calendar);

    // Log scales: Linear, Digits
    else if(tType === 'L') return Math.log(Math.pow(10, x) + dtSigned) / Math.LN10;

    // log10 of 2,5,10, or all digits (logs just have to be
    // close enough to round)
    else if(tType === 'D') {
        var tickset = (dtick === 'D2') ? roundLog2 : roundLog1;
        var x2 = x + axSign * 0.01;
        var frac = Lib.roundUp(Lib.mod(x2, 1), tickset, axrev);

        return Math.floor(x2) +
            Math.log(d3.round(Math.pow(10, frac), 1)) / Math.LN10;
    }
    else throw 'unrecognized dtick ' + String(dtick);
};

// calculate the first tick on an axis
axes.tickFirst = function(ax) {
    var r2l = ax.r2l || Number;
    var rng = Lib.simpleMap(ax.range, r2l);
    var axrev = rng[1] < rng[0];
    var sRound = axrev ? Math.floor : Math.ceil;
    // add a tiny extra bit to make sure we get ticks
    // that may have been rounded out
    var r0 = rng[0] * 1.0001 - rng[1] * 0.0001;
    var dtick = ax.dtick;
    var tick0 = r2l(ax.tick0);

    if(isNumeric(dtick)) {
        var tmin = sRound((r0 - tick0) / dtick) * dtick + tick0;

        // make sure no ticks outside the category list
        if(ax.type === 'category' || ax.type === 'multicategory') {
            tmin = Lib.constrain(tmin, 0, ax._categories.length - 1);
        }
        return tmin;
    }

    var tType = dtick.charAt(0);
    var dtNum = Number(dtick.substr(1));

    // Dates: months (or years)
    if(tType === 'M') {
        var cnt = 0;
        var t0 = tick0;
        var t1, mult, newDTick;

        // This algorithm should work for *any* nonlinear (but close to linear!)
        // tick spacing. Limit to 10 iterations, for gregorian months it's normally <=3.
        while(cnt < 10) {
            t1 = axes.tickIncrement(t0, dtick, axrev, ax.calendar);
            if((t1 - r0) * (t0 - r0) <= 0) {
                // t1 and t0 are on opposite sides of r0! we've succeeded!
                if(axrev) return Math.min(t0, t1);
                return Math.max(t0, t1);
            }
            mult = (r0 - ((t0 + t1) / 2)) / (t1 - t0);
            newDTick = tType + ((Math.abs(Math.round(mult)) || 1) * dtNum);
            t0 = axes.tickIncrement(t0, newDTick, mult < 0 ? !axrev : axrev, ax.calendar);
            cnt++;
        }
        Lib.error('tickFirst did not converge', ax);
        return t0;
    }

    // Log scales: Linear, Digits
    else if(tType === 'L') {
        return Math.log(sRound(
            (Math.pow(10, r0) - tick0) / dtNum) * dtNum + tick0) / Math.LN10;
    }
    else if(tType === 'D') {
        var tickset = (dtick === 'D2') ? roundLog2 : roundLog1;
        var frac = Lib.roundUp(Lib.mod(r0, 1), tickset, axrev);

        return Math.floor(r0) +
            Math.log(d3.round(Math.pow(10, frac), 1)) / Math.LN10;
    }
    else throw 'unrecognized dtick ' + String(dtick);
};

// draw the text for one tick.
// px,py are the location on gd.paper
// prefix is there so the x axis ticks can be dropped a line
// ax is the axis layout, x is the tick value
// hover is a (truthy) flag for whether to show numbers with a bit
// more precision for hovertext
axes.tickText = function(ax, x, hover) {
    var out = tickTextObj(ax, x);
    var arrayMode = ax.tickmode === 'array';
    var extraPrecision = hover || arrayMode;
    var axType = ax.type;
    // TODO multicategory, if we allow ticktext / tickvals
    var tickVal2l = axType === 'category' ? ax.d2l_noadd : ax.d2l;
    var i;

    if(arrayMode && Array.isArray(ax.ticktext)) {
        var rng = Lib.simpleMap(ax.range, ax.r2l);
        var minDiff = Math.abs(rng[1] - rng[0]) / 10000;

        for(i = 0; i < ax.ticktext.length; i++) {
            if(Math.abs(x - tickVal2l(ax.tickvals[i])) < minDiff) break;
        }
        if(i < ax.ticktext.length) {
            out.text = String(ax.ticktext[i]);
            return out;
        }
    }

    function isHidden(showAttr) {
        if(showAttr === undefined) return true;
        if(hover) return showAttr === 'none';

        var firstOrLast = {
            first: ax._tmin,
            last: ax._tmax
        }[showAttr];

        return showAttr !== 'all' && x !== firstOrLast;
    }

    var hideexp = hover ?
        'never' :
        ax.exponentformat !== 'none' && isHidden(ax.showexponent) ? 'hide' : '';

    if(axType === 'date') formatDate(ax, out, hover, extraPrecision);
    else if(axType === 'log') formatLog(ax, out, hover, extraPrecision, hideexp);
    else if(axType === 'category') formatCategory(ax, out);
    else if(axType === 'multicategory') formatMultiCategory(ax, out, hover);
    else if(isAngular(ax)) formatAngle(ax, out, hover, extraPrecision, hideexp);
    else formatLinear(ax, out, hover, extraPrecision, hideexp);

    // add prefix and suffix
    if(ax.tickprefix && !isHidden(ax.showtickprefix)) out.text = ax.tickprefix + out.text;
    if(ax.ticksuffix && !isHidden(ax.showticksuffix)) out.text += ax.ticksuffix;

    // Setup ticks and grid lines boundaries
    // at 1/2 a 'category' to the left/bottom
    if(ax.tickson === 'boundaries' || ax.showdividers) {
        var inbounds = function(v) {
            var p = ax.l2p(v);
            return p >= 0 && p <= ax._length ? v : null;
        };

        out.xbnd = [
            inbounds(out.x - 0.5),
            inbounds(out.x + ax.dtick - 0.5)
        ];
    }

    return out;
};

/**
 * create text for a hover label on this axis, with special handling of
 * log axes (where negative values can't be displayed but can appear in hover text)
 *
 * @param {object} ax: the axis to format text for
 * @param {number} val: calcdata value to format
 * @param {Optional(number)} val2: a second value to display
 *
 * @returns {string} `val` formatted as a string appropriate to this axis, or
 *     `val` and `val2` as a range (ie '<val> - <val2>') if `val2` is provided and
 *     it's different from `val`.
 */
axes.hoverLabelText = function(ax, val, val2) {
    if(val2 !== BADNUM && val2 !== val) {
        return axes.hoverLabelText(ax, val) + ' - ' + axes.hoverLabelText(ax, val2);
    }

    var logOffScale = (ax.type === 'log' && val <= 0);
    var tx = axes.tickText(ax, ax.c2l(logOffScale ? -val : val), 'hover').text;

    if(logOffScale) {
        return val === 0 ? '0' : MINUS_SIGN + tx;
    }

    // TODO: should we do something special if the axis calendar and
    // the data calendar are different? Somehow display both dates with
    // their system names? Right now it will just display in the axis calendar
    // but users could add the other one as text.
    return tx;
};

function tickTextObj(ax, x, text) {
    var tf = ax.tickfont || {};

    return {
        x: x,
        dx: 0,
        dy: 0,
        text: text || '',
        fontSize: tf.size,
        font: tf.family,
        fontColor: tf.color
    };
}

function formatDate(ax, out, hover, extraPrecision) {
    var tr = ax._tickround;
    var fmt = (hover && ax.hoverformat) || axes.getTickFormat(ax);

    if(extraPrecision) {
        // second or sub-second precision: extra always shows max digits.
        // for other fields, extra precision just adds one field.
        if(isNumeric(tr)) tr = 4;
        else tr = {y: 'm', m: 'd', d: 'M', M: 'S', S: 4}[tr];
    }

    var dateStr = Lib.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat);
    var headStr;

    var splitIndex = dateStr.indexOf('\n');
    if(splitIndex !== -1) {
        headStr = dateStr.substr(splitIndex + 1);
        dateStr = dateStr.substr(0, splitIndex);
    }

    if(extraPrecision) {
        // if extraPrecision led to trailing zeros, strip them off
        // actually, this can lead to removing even more zeros than
        // in the original rounding, but that's fine because in these
        // contexts uniformity is not so important (if there's even
        // anything to be uniform with!)

        // can we remove the whole time part?
        if(dateStr === '00:00:00' || dateStr === '00:00') {
            dateStr = headStr;
            headStr = '';
        }
        else if(dateStr.length === 8) {
            // strip off seconds if they're zero (zero fractional seconds
            // are already omitted)
            // but we never remove minutes and leave just hours
            dateStr = dateStr.replace(/:00$/, '');
        }
    }

    if(headStr) {
        if(hover) {
            // hover puts it all on one line, so headPart works best up front
            // except for year headPart: turn this into "Jan 1, 2000" etc.
            if(tr === 'd') dateStr += ', ' + headStr;
            else dateStr = headStr + (dateStr ? ', ' + dateStr : '');
        }
        else if(!ax._inCalcTicks || (headStr !== ax._prevDateHead)) {
            dateStr += '<br>' + headStr;
            ax._prevDateHead = headStr;
        }
    }

    out.text = dateStr;
}

function formatLog(ax, out, hover, extraPrecision, hideexp) {
    var dtick = ax.dtick;
    var x = out.x;
    var tickformat = ax.tickformat;
    var dtChar0 = typeof dtick === 'string' && dtick.charAt(0);

    if(hideexp === 'never') {
        // If this is a hover label, then we must *never* hide the exponent
        // for the sake of display, which could give the wrong value by
        // potentially many orders of magnitude. If hideexp was 'never', then
        // it's now succeeded by preventing the other condition from automating
        // this choice. Thus we can unset it so that the axis formatting takes
        // precedence.
        hideexp = '';
    }

    if(extraPrecision && (dtChar0 !== 'L')) {
        dtick = 'L3';
        dtChar0 = 'L';
    }

    if(tickformat || (dtChar0 === 'L')) {
        out.text = numFormat(Math.pow(10, x), ax, hideexp, extraPrecision);
    }
    else if(isNumeric(dtick) || ((dtChar0 === 'D') && (Lib.mod(x + 0.01, 1) < 0.1))) {
        var p = Math.round(x);
        var absP = Math.abs(p);
        var exponentFormat = ax.exponentformat;
        if(exponentFormat === 'power' || (isSIFormat(exponentFormat) && beyondSI(p))) {
            if(p === 0) out.text = 1;
            else if(p === 1) out.text = '10';
            else out.text = '10<sup>' + (p > 1 ? '' : MINUS_SIGN) + absP + '</sup>';

            out.fontSize *= 1.25;
        }
        else if((exponentFormat === 'e' || exponentFormat === 'E') && absP > 2) {
            out.text = '1' + exponentFormat + (p > 0 ? '+' : MINUS_SIGN) + absP;
        }
        else {
            out.text = numFormat(Math.pow(10, x), ax, '', 'fakehover');
            if(dtick === 'D1' && ax._id.charAt(0) === 'y') {
                out.dy -= out.fontSize / 6;
            }
        }
    }
    else if(dtChar0 === 'D') {
        out.text = String(Math.round(Math.pow(10, Lib.mod(x, 1))));
        out.fontSize *= 0.75;
    }
    else throw 'unrecognized dtick ' + String(dtick);

    // if 9's are printed on log scale, move the 10's away a bit
    if(ax.dtick === 'D1') {
        var firstChar = String(out.text).charAt(0);
        if(firstChar === '0' || firstChar === '1') {
            if(ax._id.charAt(0) === 'y') {
                out.dx -= out.fontSize / 4;
            }
            else {
                out.dy += out.fontSize / 2;
                out.dx += (ax.range[1] > ax.range[0] ? 1 : -1) *
                    out.fontSize * (x < 0 ? 0.5 : 0.25);
            }
        }
    }
}

function formatCategory(ax, out) {
    var tt = ax._categories[Math.round(out.x)];
    if(tt === undefined) tt = '';
    out.text = String(tt);
}

function formatMultiCategory(ax, out, hover) {
    var v = Math.round(out.x);
    var cats = ax._categories[v] || [];
    var tt = cats[1] === undefined ? '' : String(cats[1]);
    var tt2 = cats[0] === undefined ? '' : String(cats[0]);

    if(hover) {
        // TODO is this what we want?
        out.text = tt2 + ' - ' + tt;
    } else {
        // setup for secondary labels
        out.text = tt;
        out.text2 = tt2;
    }
}

function formatLinear(ax, out, hover, extraPrecision, hideexp) {
    if(hideexp === 'never') {
        // If this is a hover label, then we must *never* hide the exponent
        // for the sake of display, which could give the wrong value by
        // potentially many orders of magnitude. If hideexp was 'never', then
        // it's now succeeded by preventing the other condition from automating
        // this choice. Thus we can unset it so that the axis formatting takes
        // precedence.
        hideexp = '';
    } else if(ax.showexponent === 'all' && Math.abs(out.x / ax.dtick) < 1e-6) {
        // don't add an exponent to zero if we're showing all exponents
        // so the only reason you'd show an exponent on zero is if it's the
        // ONLY tick to get an exponent (first or last)
        hideexp = 'hide';
    }
    out.text = numFormat(out.x, ax, hideexp, extraPrecision);
}

function formatAngle(ax, out, hover, extraPrecision, hideexp) {
    if(ax.thetaunit === 'radians' && !hover) {
        var num = out.x / 180;

        if(num === 0) {
            out.text = '0';
        } else {
            var frac = num2frac(num);

            if(frac[1] >= 100) {
                out.text = numFormat(Lib.deg2rad(out.x), ax, hideexp, extraPrecision);
            } else {
                var isNeg = out.x < 0;

                if(frac[1] === 1) {
                    if(frac[0] === 1) out.text = 'π';
                    else out.text = frac[0] + 'π';
                } else {
                    out.text = [
                        '<sup>', frac[0], '</sup>',
                        '⁄',
                        '<sub>', frac[1], '</sub>',
                        'π'
                    ].join('');
                }

                if(isNeg) out.text = MINUS_SIGN + out.text;
            }
        }
    } else {
        out.text = numFormat(out.x, ax, hideexp, extraPrecision);
    }
}

// inspired by
// https://github.com/yisibl/num2fraction/blob/master/index.js
function num2frac(num) {
    function almostEq(a, b) {
        return Math.abs(a - b) <= 1e-6;
    }

    function findGCD(a, b) {
        return almostEq(b, 0) ? a : findGCD(b, a % b);
    }

    function findPrecision(n) {
        var e = 1;
        while(!almostEq(Math.round(n * e) / e, n)) {
            e *= 10;
        }
        return e;
    }

    var precision = findPrecision(num);
    var number = num * precision;
    var gcd = Math.abs(findGCD(number, precision));

    return [
        // numerator
        Math.round(number / gcd),
        // denominator
        Math.round(precision / gcd)
    ];
}

// format a number (tick value) according to the axis settings
// new, more reliable procedure than d3.round or similar:
// add half the rounding increment, then stringify and truncate
// also automatically switch to sci. notation
var SIPREFIXES = ['f', 'p', 'n', 'μ', 'm', '', 'k', 'M', 'G', 'T'];

function isSIFormat(exponentFormat) {
    return exponentFormat === 'SI' || exponentFormat === 'B';
}

// are we beyond the range of common SI prefixes?
// 10^-16 -> 1x10^-16
// 10^-15 -> 1f
// ...
// 10^14 -> 100T
// 10^15 -> 1x10^15
// 10^16 -> 1x10^16
function beyondSI(exponent) {
    return exponent > 14 || exponent < -15;
}

function numFormat(v, ax, fmtoverride, hover) {
    var isNeg = v < 0;
    // max number of digits past decimal point to show
    var tickRound = ax._tickround;
    var exponentFormat = fmtoverride || ax.exponentformat || 'B';
    var exponent = ax._tickexponent;
    var tickformat = axes.getTickFormat(ax);
    var separatethousands = ax.separatethousands;

    // special case for hover: set exponent just for this value, and
    // add a couple more digits of precision over tick labels
    if(hover) {
        // make a dummy axis obj to get the auto rounding and exponent
        var ah = {
            exponentformat: exponentFormat,
            dtick: ax.showexponent === 'none' ? ax.dtick :
                (isNumeric(v) ? Math.abs(v) || 1 : 1),
            // if not showing any exponents, don't change the exponent
            // from what we calculate
            range: ax.showexponent === 'none' ? ax.range.map(ax.r2d) : [0, v || 1]
        };
        autoTickRound(ah);
        tickRound = (Number(ah._tickround) || 0) + 4;
        exponent = ah._tickexponent;
        if(ax.hoverformat) tickformat = ax.hoverformat;
    }

    if(tickformat) return ax._numFormat(tickformat)(v).replace(/-/g, MINUS_SIGN);

    // 'epsilon' - rounding increment
    var e = Math.pow(10, -tickRound) / 2;

    // exponentFormat codes:
    // 'e' (1.2e+6, default)
    // 'E' (1.2E+6)
    // 'SI' (1.2M)
    // 'B' (same as SI except 10^9=B not G)
    // 'none' (1200000)
    // 'power' (1.2x10^6)
    // 'hide' (1.2, use 3rd argument=='hide' to eg
    //      only show exponent on last tick)
    if(exponentFormat === 'none') exponent = 0;

    // take the sign out, put it back manually at the end
    // - makes cases easier
    v = Math.abs(v);
    if(v < e) {
        // 0 is just 0, but may get exponent if it's the last tick
        v = '0';
        isNeg = false;
    }
    else {
        v += e;
        // take out a common exponent, if any
        if(exponent) {
            v *= Math.pow(10, -exponent);
            tickRound += exponent;
        }
        // round the mantissa
        if(tickRound === 0) v = String(Math.floor(v));
        else if(tickRound < 0) {
            v = String(Math.round(v));
            v = v.substr(0, v.length + tickRound);
            for(var i = tickRound; i < 0; i++) v += '0';
        }
        else {
            v = String(v);
            var dp = v.indexOf('.') + 1;
            if(dp) v = v.substr(0, dp + tickRound).replace(/\.?0+$/, '');
        }
        // insert appropriate decimal point and thousands separator
        v = Lib.numSeparate(v, ax._separators, separatethousands);
    }

    // add exponent
    if(exponent && exponentFormat !== 'hide') {
        if(isSIFormat(exponentFormat) && beyondSI(exponent)) exponentFormat = 'power';

        var signedExponent;
        if(exponent < 0) signedExponent = MINUS_SIGN + -exponent;
        else if(exponentFormat !== 'power') signedExponent = '+' + exponent;
        else signedExponent = String(exponent);

        if(exponentFormat === 'e' || exponentFormat === 'E') {
            v += exponentFormat + signedExponent;
        }
        else if(exponentFormat === 'power') {
            v += '×10<sup>' + signedExponent + '</sup>';
        }
        else if(exponentFormat === 'B' && exponent === 9) {
            v += 'B';
        }
        else if(isSIFormat(exponentFormat)) {
            v += SIPREFIXES[exponent / 3 + 5];
        }
    }

    // put sign back in and return
    // replace standard minus character (which is technically a hyphen)
    // with a true minus sign
    if(isNeg) return MINUS_SIGN + v;
    return v;
}

axes.getTickFormat = function(ax) {
    var i;

    function convertToMs(dtick) {
        return typeof dtick !== 'string' ? dtick : Number(dtick.replace('M', '')) * ONEAVGMONTH;
    }

    function compareLogTicks(left, right) {
        var priority = ['L', 'D'];
        if(typeof left === typeof right) {
            if(typeof left === 'number') {
                return left - right;
            } else {
                var leftPriority = priority.indexOf(left.charAt(0));
                var rightPriority = priority.indexOf(right.charAt(0));
                if(leftPriority === rightPriority) {
                    return Number(left.replace(/(L|D)/g, '')) - Number(right.replace(/(L|D)/g, ''));
                } else {
                    return leftPriority - rightPriority;
                }
            }
        } else {
            return typeof left === 'number' ? 1 : -1;
        }
    }

    function isProperStop(dtick, range, convert) {
        var convertFn = convert || function(x) { return x;};
        var leftDtick = range[0];
        var rightDtick = range[1];
        return ((!leftDtick && typeof leftDtick !== 'number') || convertFn(leftDtick) <= convertFn(dtick)) &&
               ((!rightDtick && typeof rightDtick !== 'number') || convertFn(rightDtick) >= convertFn(dtick));
    }

    function isProperLogStop(dtick, range) {
        var isLeftDtickNull = range[0] === null;
        var isRightDtickNull = range[1] === null;
        var isDtickInRangeLeft = compareLogTicks(dtick, range[0]) >= 0;
        var isDtickInRangeRight = compareLogTicks(dtick, range[1]) <= 0;
        return (isLeftDtickNull || isDtickInRangeLeft) && (isRightDtickNull || isDtickInRangeRight);
    }

    var tickstop, stopi;
    if(ax.tickformatstops && ax.tickformatstops.length > 0) {
        switch(ax.type) {
            case 'date':
            case 'linear': {
                for(i = 0; i < ax.tickformatstops.length; i++) {
                    stopi = ax.tickformatstops[i];
                    if(stopi.enabled && isProperStop(ax.dtick, stopi.dtickrange, convertToMs)) {
                        tickstop = stopi;
                        break;
                    }
                }
                break;
            }
            case 'log': {
                for(i = 0; i < ax.tickformatstops.length; i++) {
                    stopi = ax.tickformatstops[i];
                    if(stopi.enabled && isProperLogStop(ax.dtick, stopi.dtickrange)) {
                        tickstop = stopi;
                        break;
                    }
                }
                break;
            }
            default:
        }
    }
    return tickstop ? tickstop.value : ax.tickformat;
};

// getSubplots - extract all subplot IDs we need
// as an array of items like 'xy', 'x2y', 'x2y2'...
// sorted by x (x,x2,x3...) then y
// optionally restrict to only subplots containing axis object ax
//
// NOTE: this is currently only used OUTSIDE plotly.js (toolpanel, webapp)
// ideally we get rid of it there (or just copy this there) and remove it here
axes.getSubplots = function(gd, ax) {
    var subplotObj = gd._fullLayout._subplots;
    var allSubplots = subplotObj.cartesian.concat(subplotObj.gl2d || []);

    var out = ax ? axes.findSubplotsWithAxis(allSubplots, ax) : allSubplots;

    out.sort(function(a, b) {
        var aParts = a.substr(1).split('y');
        var bParts = b.substr(1).split('y');

        if(aParts[0] === bParts[0]) return +aParts[1] - +bParts[1];
        return +aParts[0] - +bParts[0];
    });

    return out;
};

// find all subplots with axis 'ax'
// NOTE: this is only used in axes.getSubplots (only used outside plotly.js) and
// gl2d/convert (where it restricts axis subplots to only those with gl2d)
axes.findSubplotsWithAxis = function(subplots, ax) {
    var axMatch = new RegExp(
        (ax._id.charAt(0) === 'x') ? ('^' + ax._id + 'y') : (ax._id + '$')
    );
    var subplotsWithAx = [];

    for(var i = 0; i < subplots.length; i++) {
        var sp = subplots[i];
        if(axMatch.test(sp)) subplotsWithAx.push(sp);
    }

    return subplotsWithAx;
};

// makeClipPaths: prepare clipPaths for all single axes and all possible xy pairings
axes.makeClipPaths = function(gd) {
    var fullLayout = gd._fullLayout;

    // for more info: https://github.com/plotly/plotly.js/issues/2595
    if(fullLayout._hasOnlyLargeSploms) return;

    var fullWidth = {_offset: 0, _length: fullLayout.width, _id: ''};
    var fullHeight = {_offset: 0, _length: fullLayout.height, _id: ''};
    var xaList = axes.list(gd, 'x', true);
    var yaList = axes.list(gd, 'y', true);
    var clipList = [];
    var i, j;

    for(i = 0; i < xaList.length; i++) {
        clipList.push({x: xaList[i], y: fullHeight});
        for(j = 0; j < yaList.length; j++) {
            if(i === 0) clipList.push({x: fullWidth, y: yaList[j]});
            clipList.push({x: xaList[i], y: yaList[j]});
        }
    }

    // selectors don't work right with camelCase tags,
    // have to use class instead
    // https://groups.google.com/forum/#!topic/d3-js/6EpAzQ2gU9I
    var axClips = fullLayout._clips.selectAll('.axesclip')
        .data(clipList, function(d) { return d.x._id + d.y._id; });

    axClips.enter().append('clipPath')
        .classed('axesclip', true)
        .attr('id', function(d) { return 'clip' + fullLayout._uid + d.x._id + d.y._id; })
      .append('rect');

    axClips.exit().remove();

    axClips.each(function(d) {
        d3.select(this).select('rect').attr({
            x: d.x._offset || 0,
            y: d.y._offset || 0,
            width: d.x._length || 1,
            height: d.y._length || 1
        });
    });
};

/**
 * Main multi-axis drawing routine!
 *
 * @param {DOM element} gd : graph div
 * @param {string or array of strings} arg : polymorphic argument
 * @param {object} opts:
 * - @param {boolean} skipTitle : optional flag to skip axis title draw/update
 *
 * Signature 1: Axes.draw(gd, 'redraw')
 *   use this to clear and redraw all axes on graph
 *
 * Signature 2: Axes.draw(gd, '')
 *   use this to draw all axes on graph w/o the selectAll().remove()
 *   of the 'redraw' signature
 *
 * Signature 3: Axes.draw(gd, [axId, axId2, ...])
 *   where the items are axis id string,
 *   use this to update multiple axes in one call
 *
 * N.B draw updates:
 * - ax._r (stored range for use by zoom/pan)
 * - ax._rl (stored linearized range for use by zoom/pan)
 */
axes.draw = function(gd, arg, opts) {
    var fullLayout = gd._fullLayout;

    if(arg === 'redraw') {
        fullLayout._paper.selectAll('g.subplot').each(function(d) {
            var id = d[0];
            var plotinfo = fullLayout._plots[id];
            var xa = plotinfo.xaxis;
            var ya = plotinfo.yaxis;

            plotinfo.xaxislayer.selectAll('.' + xa._id + 'tick').remove();
            plotinfo.yaxislayer.selectAll('.' + ya._id + 'tick').remove();
            plotinfo.xaxislayer.selectAll('.' + xa._id + 'tick2').remove();
            plotinfo.yaxislayer.selectAll('.' + ya._id + 'tick2').remove();
            plotinfo.xaxislayer.selectAll('.' + xa._id + 'divider').remove();
            plotinfo.yaxislayer.selectAll('.' + ya._id + 'divider').remove();

            if(plotinfo.gridlayer) plotinfo.gridlayer.selectAll('path').remove();
            if(plotinfo.zerolinelayer) plotinfo.zerolinelayer.selectAll('path').remove();

            fullLayout._infolayer.select('.g-' + xa._id + 'title').remove();
            fullLayout._infolayer.select('.g-' + ya._id + 'title').remove();
        });
    }

    var axList = (!arg || arg === 'redraw') ? axes.listIds(gd) : arg;

    return Lib.syncOrAsync(axList.map(function(axId) {
        return function() {
            if(!axId) return;

            var ax = axes.getFromId(gd, axId);
            var axDone = axes.drawOne(gd, ax, opts);

            ax._r = ax.range.slice();
            ax._rl = Lib.simpleMap(ax._r, ax.r2l);

            return axDone;
        };
    }));
};

/**
 * Draw one cartesian axis
 *
 * @param {DOM element} gd
 * @param {object} ax (full) axis object
 * @param {object} opts
 * - @param {boolean} skipTitle (set to true to skip axis title draw call)
 */
axes.drawOne = function(gd, ax, opts) {
    opts = opts || {};

    var i, sp, plotinfo;

    ax.setScale();

    var fullLayout = gd._fullLayout;
    var axId = ax._id;
    var axLetter = axId.charAt(0);
    var counterLetter = axes.counterLetter(axId);
    var mainSubplot = ax._mainSubplot;
    var mainLinePosition = ax._mainLinePosition;
    var mainMirrorPosition = ax._mainMirrorPosition;
    var mainPlotinfo = fullLayout._plots[mainSubplot];
    var mainAxLayer = mainPlotinfo[axLetter + 'axislayer'];
    var subplotsWithAx = ax._subplotsWith;

    var vals = ax._vals = axes.calcTicks(ax);

    // Add a couple of axis properties that should cause us to recreate
    // elements. Used in d3 data function.
    var axInfo = [ax.mirror, mainLinePosition, mainMirrorPosition].join('_');
    for(i = 0; i < vals.length; i++) {
        vals[i].axInfo = axInfo;
    }

    if(!ax.visible) return;

    // stash selections to avoid DOM queries e.g.
    // - stash tickLabels selection, so that drawTitle can use it to scoot title
    ax._selections = {};
    // stash tick angle (including the computed 'auto' values) per tick-label class
    ax._tickAngles = {};

    var transFn = axes.makeTransFn(ax);
    var tickVals;
    // We remove zero lines, grid lines, and inside ticks if they're within 1px of the end
    // The key case here is removing zero lines when the axis bound is zero
    var valsClipped;

    if(ax.tickson === 'boundaries') {
        var boundaryVals = getBoundaryVals(ax, vals);
        valsClipped = axes.clipEnds(ax, boundaryVals);
        tickVals = ax.ticks === 'inside' ? valsClipped : boundaryVals;
    } else {
        valsClipped = axes.clipEnds(ax, vals);
        tickVals = ax.ticks === 'inside' ? valsClipped : vals;
    }

    var gridVals = ax._gridVals = valsClipped;
    var dividerVals = getDividerVals(ax, vals);

    if(!fullLayout._hasOnlyLargeSploms) {
        // keep track of which subplots (by main conteraxis) we've already
        // drawn grids for, so we don't overdraw overlaying subplots
        var finishedGrids = {};

        for(i = 0; i < subplotsWithAx.length; i++) {
            sp = subplotsWithAx[i];
            plotinfo = fullLayout._plots[sp];

            var counterAxis = plotinfo[counterLetter + 'axis'];
            var mainCounterID = counterAxis._mainAxis._id;
            if(finishedGrids[mainCounterID]) continue;
            finishedGrids[mainCounterID] = 1;

            var gridPath = axLetter === 'x' ?
                'M0,' + counterAxis._offset + 'v' + counterAxis._length :
                'M' + counterAxis._offset + ',0h' + counterAxis._length;

            axes.drawGrid(gd, ax, {
                vals: gridVals,
                counterAxis: counterAxis,
                layer: plotinfo.gridlayer.select('.' + axId),
                path: gridPath,
                transFn: transFn
            });
            axes.drawZeroLine(gd, ax, {
                counterAxis: counterAxis,
                layer: plotinfo.zerolinelayer,
                path: gridPath,
                transFn: transFn
            });
        }
    }

    var tickSigns = axes.getTickSigns(ax);
    var tickSubplots = [];

    if(ax.ticks) {
        var mainTickPath = axes.makeTickPath(ax, mainLinePosition, tickSigns[2]);
        var mirrorTickPath;
        var fullTickPath;
        if(ax._anchorAxis && ax.mirror && ax.mirror !== true) {
            mirrorTickPath = axes.makeTickPath(ax, mainMirrorPosition, tickSigns[3]);
            fullTickPath = mainTickPath + mirrorTickPath;
        } else {
            mirrorTickPath = '';
            fullTickPath = mainTickPath;
        }

        var tickPath;
        if(ax.showdividers && ax.ticks === 'outside' && ax.tickson === 'boundaries') {
            var dividerLookup = {};
            for(i = 0; i < dividerVals.length; i++) {
                dividerLookup[dividerVals[i].x] = 1;
            }
            tickPath = function(d) {
                return dividerLookup[d.x] ? mirrorTickPath : fullTickPath;
            };
        } else {
            tickPath = fullTickPath;
        }

        axes.drawTicks(gd, ax, {
            vals: tickVals,
            layer: mainAxLayer,
            path: tickPath,
            transFn: transFn
        });

        tickSubplots = Object.keys(ax._linepositions || {});
    }

    for(i = 0; i < tickSubplots.length; i++) {
        sp = tickSubplots[i];
        plotinfo = fullLayout._plots[sp];
        // [bottom or left, top or right], free and main are handled above
        var linepositions = ax._linepositions[sp] || [];
        var spTickPath = axes.makeTickPath(ax, linepositions[0], tickSigns[0]) +
            axes.makeTickPath(ax, linepositions[1], tickSigns[1]);

        axes.drawTicks(gd, ax, {
            vals: tickVals,
            layer: plotinfo[axLetter + 'axislayer'],
            path: spTickPath,
            transFn: transFn
        });
    }

    var seq = [];

    // tick labels - for now just the main labels.
    // TODO: mirror labels, esp for subplots

    seq.push(function() {
        var labelFns = axes.makeLabelFns(ax, mainLinePosition);
        return axes.drawLabels(gd, ax, {
            vals: vals,
            layer: mainAxLayer,
            transFn: transFn,
            labelXFn: labelFns.labelXFn,
            labelYFn: labelFns.labelYFn,
            labelAnchorFn: labelFns.labelAnchorFn,
        });
    });

    if(ax.type === 'multicategory') {
        var labelLength = 0;
        var pad = {x: 2, y: 10}[axLetter];
        var sgn = tickSigns[2] * (ax.ticks === 'inside' ? -1 : 1);

        seq.push(function() {
            labelLength += getLabelLevelSpan(ax, axId + 'tick') + pad;
            labelLength += ax._tickAngles[axId + 'tick'] ? ax.tickfont.size * LINE_SPACING : 0;
            var secondaryPosition = mainLinePosition + labelLength * sgn;
            var secondaryLabelFns = axes.makeLabelFns(ax, secondaryPosition);

            return axes.drawLabels(gd, ax, {
                vals: getSecondaryLabelVals(ax, vals),
                layer: mainAxLayer,
                cls: axId + 'tick2',
                repositionOnUpdate: true,
                secondary: true,
                transFn: transFn,
                labelXFn: secondaryLabelFns.labelXFn,
                labelYFn: secondaryLabelFns.labelYFn,
                labelAnchorFn: secondaryLabelFns.labelAnchorFn,
            });
        });

        seq.push(function() {
            labelLength += getLabelLevelSpan(ax, axId + 'tick2');
            ax._labelLength = labelLength;

            return drawDividers(gd, ax, {
                vals: dividerVals,
                layer: mainAxLayer,
                path: axes.makeTickPath(ax, mainLinePosition, sgn, labelLength),
                transFn: transFn
            });
        });
    }

    function extendRange(range, newRange) {
        range[0] = Math.min(range[0], newRange[0]);
        range[1] = Math.max(range[1], newRange[1]);
    }

    function calcBoundingBox() {
        if(ax.showticklabels) {
            var gdBB = gd.getBoundingClientRect();
            var bBox = mainAxLayer.node().getBoundingClientRect();

            /*
             * the way we're going to use this, the positioning that matters
             * is relative to the origin of gd. This is important particularly
             * if gd is scrollable, and may have been scrolled between the time
             * we calculate this and the time we use it
             */

            ax._boundingBox = {
                width: bBox.width,
                height: bBox.height,
                left: bBox.left - gdBB.left,
                right: bBox.right - gdBB.left,
                top: bBox.top - gdBB.top,
                bottom: bBox.bottom - gdBB.top
            };
        } else {
            var gs = fullLayout._size;
            var pos;

            // set dummy bbox for ticklabel-less axes

            if(axLetter === 'x') {
                pos = ax.anchor === 'free' ?
                    gs.t + gs.h * (1 - ax.position) :
                    gs.t + gs.h * (1 - ax._anchorAxis.domain[{bottom: 0, top: 1}[ax.side]]);

                ax._boundingBox = {
                    top: pos,
                    bottom: pos,
                    left: ax._offset,
                    right: ax._offset + ax._length,
                    width: ax._length,
                    height: 0
                };
            } else {
                pos = ax.anchor === 'free' ?
                    gs.l + gs.w * ax.position :
                    gs.l + gs.w * ax._anchorAxis.domain[{left: 0, right: 1}[ax.side]];

                ax._boundingBox = {
                    left: pos,
                    right: pos,
                    bottom: ax._offset + ax._length,
                    top: ax._offset,
                    height: ax._length,
                    width: 0
                };
            }
        }

        /*
         * for spikelines: what's the full domain of positions in the
         * opposite direction that are associated with this axis?
         * This means any axes that we make a subplot with, plus the
         * position of the axis itself if it's free.
         */
        if(subplotsWithAx) {
            var fullRange = ax._counterSpan = [Infinity, -Infinity];

            for(var i = 0; i < subplotsWithAx.length; i++) {
                var plotinfo = fullLayout._plots[subplotsWithAx[i]];
                var counterAxis = plotinfo[(axLetter === 'x') ? 'yaxis' : 'xaxis'];

                extendRange(fullRange, [
                    counterAxis._offset,
                    counterAxis._offset + counterAxis._length
                ]);
            }

            if(ax.anchor === 'free') {
                extendRange(fullRange, (axLetter === 'x') ?
                    [ax._boundingBox.bottom, ax._boundingBox.top] :
                    [ax._boundingBox.right, ax._boundingBox.left]);
            }
        }
    }

    var hasRangeSlider = Registry.getComponentMethod('rangeslider', 'isVisible')(ax);

    function doAutoMargins() {
        var s = ax.side.charAt(0);
        var push;
        var rangeSliderPush;

        if(hasRangeSlider) {
            rangeSliderPush = Registry.getComponentMethod('rangeslider', 'autoMarginOpts')(gd, ax);
        }
        Plots.autoMargin(gd, rangeSliderAutoMarginID(ax), rangeSliderPush);

        if(ax.automargin && (!hasRangeSlider || s !== 'b')) {
            push = {x: 0, y: 0, r: 0, l: 0, t: 0, b: 0};

            var bbox = ax._boundingBox;
            var counterAx = mainPlotinfo[counterLetter + 'axis'];
            var anchorAxDomainIndex;
            var offset;

            switch(axLetter + s) {
                case 'xb':
                    anchorAxDomainIndex = 0;
                    offset = bbox.top - counterAx._length - counterAx._offset;
                    push[s] = bbox.height;
                    break;
                case 'xt':
                    anchorAxDomainIndex = 1;
                    offset = counterAx._offset - bbox.bottom;
                    push[s] = bbox.height;
                    break;
                case 'yl':
                    anchorAxDomainIndex = 0;
                    offset = counterAx._offset - bbox.right;
                    push[s] = bbox.width;
                    break;
                case 'yr':
                    anchorAxDomainIndex = 1;
                    offset = bbox.left - counterAx._length - counterAx._offset;
                    push[s] = bbox.width;
                    break;
            }

            push[counterLetter] = ax.anchor === 'free' ?
                ax.position :
                ax._anchorAxis.domain[anchorAxDomainIndex];

            if(push[s] > 0) {
                push[s] += offset;
            }
            if(ax.title.text !== fullLayout._dfltTitle[axLetter]) {
                push[s] += ax.title.font.size;
            }
        }

        Plots.autoMargin(gd, axAutoMarginID(ax), push);
    }

    seq.push(calcBoundingBox, doAutoMargins);

    if(!opts.skipTitle &&
        !(hasRangeSlider && ax._boundingBox && ax.side === 'bottom')
    ) {
        seq.push(function() { return drawTitle(gd, ax); });
    }

    return Lib.syncOrAsync(seq);
};

function getBoundaryVals(ax, vals) {
    var out = [];
    var i;

    // boundaryVals are never used for labels;
    // no need to worry about the other tickTextObj keys
    var _push = function(d, bndIndex) {
        var xb = d.xbnd[bndIndex];
        if(xb !== null) {
            out.push(Lib.extendFlat({}, d, {x: xb}));
        }
    };

    if(vals.length) {
        for(i = 0; i < vals.length; i++) {
            _push(vals[i], 0);
        }
        _push(vals[i - 1], 1);
    }

    return out;
}

function getSecondaryLabelVals(ax, vals) {
    var out = [];
    var lookup = {};

    for(var i = 0; i < vals.length; i++) {
        var d = vals[i];
        if(lookup[d.text2]) {
            lookup[d.text2].push(d.x);
        } else {
            lookup[d.text2] = [d.x];
        }
    }

    for(var k in lookup) {
        out.push(tickTextObj(ax, Lib.interp(lookup[k], 0.5), k));
    }

    return out;
}

function getDividerVals(ax, vals) {
    var out = [];
    var i, current;

    // never used for labels;
    // no need to worry about the other tickTextObj keys
    var _push = function(d, bndIndex) {
        var xb = d.xbnd[bndIndex];
        if(xb !== null) {
            out.push(Lib.extendFlat({}, d, {x: xb}));
        }
    };

    if(ax.showdividers && vals.length) {
        for(i = 0; i < vals.length; i++) {
            var d = vals[i];
            if(d.text2 !== current) {
                _push(d, 0);
            }
            current = d.text2;
        }
        _push(vals[i - 1], 1);
    }

    return out;
}

function getLabelLevelSpan(ax, cls) {
    var axLetter = ax._id.charAt(0);
    var angle = ax._tickAngles[cls] || 0;
    var rad = Lib.deg2rad(angle);
    var sinA = Math.sin(rad);
    var cosA = Math.cos(rad);
    var maxX = 0;
    var maxY = 0;

    // N.B. Drawing.bBox does not take into account rotate transforms

    ax._selections[cls].each(function() {
        var thisLabel = selectTickLabel(this);
        var bb = Drawing.bBox(thisLabel.node());
        var w = bb.width;
        var h = bb.height;
        maxX = Math.max(maxX, cosA * w, sinA * h);
        maxY = Math.max(maxY, sinA * w, cosA * h);
    });

    return {x: maxY, y: maxX}[axLetter];
}

/**
 * Which direction do the 'ax.side' values, and free ticks go?
 *
 * @param {object} ax (full) axis object
 *  - {string} _id (starting with 'x' or 'y')
 *  - {string} side
 *  - {string} ticks
 * @return {array} all entries are either -1 or 1
 *  - [0]: sign for top/right ticks (i.e. negative SVG direction)
 *  - [1]: sign for bottom/left ticks (i.e. positive SVG direction)
 *  - [2]: sign for ticks corresponding to 'ax.side'
 *  - [3]: sign for ticks mirroring 'ax.side'
 */
axes.getTickSigns = function(ax) {
    var axLetter = ax._id.charAt(0);
    var sideOpposite = {x: 'top', y: 'right'}[axLetter];
    var main = ax.side === sideOpposite ? 1 : -1;
    var out = [-1, 1, main, -main];
    // then we flip if outside XOR y axis
    if((ax.ticks !== 'inside') === (axLetter === 'x')) {
        out = out.map(function(v) { return -v; });
    }
    return out;
};

/**
 * Make axis translate transform function
 *
 * @param {object} ax (full) axis object
 *  - {string} _id
 *  - {number} _offset
 *  - {fn} l2p
 * @return {fn} function of calcTicks items
 */
axes.makeTransFn = function(ax) {
    var axLetter = ax._id.charAt(0);
    var offset = ax._offset;
    return axLetter === 'x' ?
        function(d) { return 'translate(' + (offset + ax.l2p(d.x)) + ',0)'; } :
        function(d) { return 'translate(0,' + (offset + ax.l2p(d.x)) + ')'; };
};

/**
 * Make axis tick path string
 *
 * @param {object} ax (full) axis object
 *  - {string} _id
 *  - {number} ticklen
 *  - {number} linewidth
 * @param {number} shift along direction of ticklen
 * @param {1 or -1} sng tick sign
 * @param {number (optional)} len tick length
 * @return {string}
 */
axes.makeTickPath = function(ax, shift, sgn, len) {
    len = len !== undefined ? len : ax.ticklen;

    var axLetter = ax._id.charAt(0);
    var pad = (ax.linewidth || 1) / 2;

    return axLetter === 'x' ?
        'M0,' + (shift + pad * sgn) + 'v' + (len * sgn) :
        'M' + (shift + pad * sgn) + ',0h' + (len * sgn);
};

/**
 * Make axis tick label x, y and anchor functions
 *
 * @param {object} ax (full) axis object
 *  - {string} _id
 *  - {string} ticks
 *  - {number} ticklen
 *  - {string} side
 *  - {number} linewidth
 *  - {number} tickfont.size
 *  - {boolean} showline
 * @param {number} shift
 * @param {number} angle [in degrees] ...
 * @return {object}
 *  - {fn} labelXFn
 *  - {fn} labelYFn
 *  - {fn} labelAnchorFn
 *  - {number} labelStandoff
 *  - {number} labelShift
 */
axes.makeLabelFns = function(ax, shift, angle) {
    var axLetter = ax._id.charAt(0);
    var pad = (ax.linewidth || 1) / 2;
    var ticksOnOutsideLabels = ax.tickson !== 'boundaries' && ax.ticks === 'outside';

    var labelStandoff = ticksOnOutsideLabels ? ax.ticklen : 0;
    var labelShift = 0;

    if(angle && ax.ticks === 'outside') {
        var rad = Lib.deg2rad(angle);
        labelStandoff = ax.ticklen * Math.cos(rad) + 1;
        labelShift = ax.ticklen * Math.sin(rad);
    }

    if(ax.showticklabels && (ticksOnOutsideLabels || ax.showline)) {
        labelStandoff += 0.2 * ax.tickfont.size;
    }

    // Used in polar angular label x/y functions
    // TODO generalize makeLabelFns so that it just work for angular axes
    var out = {
        labelStandoff: labelStandoff,
        labelShift: labelShift
    };

    var x0, y0, ff, flipIt;
    if(axLetter === 'x') {
        flipIt = ax.side === 'bottom' ? 1 : -1;
        x0 = labelShift * flipIt;
        y0 = shift + (labelStandoff + pad) * flipIt;
        ff = ax.side === 'bottom' ? 1 : -0.2;

        out.labelXFn = function(d) { return d.dx + x0; };
        out.labelYFn = function(d) { return d.dy + y0 + d.fontSize * ff; };
        out.labelAnchorFn = function(a) {
            if(!isNumeric(a) || a === 0 || a === 180) {
                return 'middle';
            }
            return (a * flipIt < 0) ? 'end' : 'start';
        };
    } else if(axLetter === 'y') {
        flipIt = ax.side === 'right' ? 1 : -1;
        x0 = labelStandoff + pad;
        y0 = -labelShift * flipIt;
        ff = Math.abs(ax.tickangle) === 90 ? 0.5 : 0;

        out.labelXFn = function(d) { return d.dx + shift + (x0 + d.fontSize * ff) * flipIt; };
        out.labelYFn = function(d) { return d.dy + y0 + d.fontSize * MID_SHIFT; };
        out.labelAnchorFn = function(a) {
            if(isNumeric(a) && Math.abs(a) === 90) {
                return 'middle';
            }
            return ax.side === 'right' ? 'start' : 'end';
        };
    }

    return out;
};

function tickDataFn(d) {
    return [d.text, d.x, d.axInfo, d.font, d.fontSize, d.fontColor].join('_');
}

/**
 * Draw axis ticks
 *
 * @param {DOM element} gd
 * @param {object} ax (full) axis object
 *  - {string} _id
 *  - {string} ticks
 *  - {number} linewidth
 *  - {string} tickcolor
 * @param {object} opts
 * - {array of object} vals (calcTicks output-like)
 * - {d3 selection} layer
 * - {string or fn} path
 * - {fn} transFn
 * - {boolean} crisp (set to false to unset crisp-edge SVG rendering)
 */
axes.drawTicks = function(gd, ax, opts) {
    opts = opts || {};

    var cls = ax._id + 'tick';

    var ticks = opts.layer.selectAll('path.' + cls)
        .data(ax.ticks ? opts.vals : [], tickDataFn);

    ticks.exit().remove();

    ticks.enter().append('path')
        .classed(cls, 1)
        .classed('ticks', 1)
        .classed('crisp', opts.crisp !== false)
        .call(Color.stroke, ax.tickcolor)
        .style('stroke-width', Drawing.crispRound(gd, ax.tickwidth, 1) + 'px')
        .attr('d', opts.path);

    ticks.attr('transform', opts.transFn);
};

/**
 * Draw axis grid
 *
 * @param {DOM element} gd
 * @param {object} ax (full) axis object
 *  - {string} _id
 *  - {boolean} showgrid
 *  - {string} gridcolor
 *  - {string} gridwidth
 *  - {boolean} zeroline
 *  - {string} type
 *  - {string} dtick
 * @param {object} opts
 * - {array of object} vals (calcTicks output-like)
 * - {d3 selection} layer
 * - {object} counterAxis (full axis object corresponding to counter axis)
 *     optional - only required if this axis supports zero lines
 * - {string or fn} path
 * - {fn} transFn
 * - {boolean} crisp (set to false to unset crisp-edge SVG rendering)
 */
axes.drawGrid = function(gd, ax, opts) {
    opts = opts || {};

    var cls = ax._id + 'grid';
    var vals = opts.vals;
    var counterAx = opts.counterAxis;
    if(ax.showgrid === false) {
        vals = [];
    }
    else if(counterAx && axes.shouldShowZeroLine(gd, ax, counterAx)) {
        var isArrayMode = ax.tickmode === 'array';
        for(var i = 0; i < vals.length; i++) {
            var xi = vals[i].x;
            if(isArrayMode ? !xi : (Math.abs(xi) < ax.dtick / 100)) {
                vals = vals.slice(0, i).concat(vals.slice(i + 1));
                // In array mode you can in principle have multiple
                // ticks at 0, so test them all. Otherwise once we found
                // one we can stop.
                if(isArrayMode) i--;
                else break;
            }
        }
    }

    var grid = opts.layer.selectAll('path.' + cls)
        .data(vals, tickDataFn);

    grid.exit().remove();

    grid.enter().append('path')
        .classed(cls, 1)
        .classed('crisp', opts.crisp !== false);

    ax._gw = Drawing.crispRound(gd, ax.gridwidth, 1);

    grid.attr('transform', opts.transFn)
        .attr('d', opts.path)
        .call(Color.stroke, ax.gridcolor || '#ddd')
        .style('stroke-width', ax._gw + 'px');

    if(typeof opts.path === 'function') grid.attr('d', opts.path);
};

/**
 * Draw axis zero-line
 *
 * @param {DOM element} gd
 * @param {object} ax (full) axis object
 *  - {string} _id
 *  - {boolean} zeroline
 *  - {number} zerolinewidth
 *  - {string} zerolinecolor
 *  - {number (optional)} _gridWidthCrispRound
 * @param {object} opts
 * - {d3 selection} layer
 * - {object} counterAxis (full axis object corresponding to counter axis)
 * - {string or fn} path
 * - {fn} transFn
 * - {boolean} crisp (set to false to unset crisp-edge SVG rendering)
 */
axes.drawZeroLine = function(gd, ax, opts) {
    opts = opts || opts;

    var cls = ax._id + 'zl';
    var show = axes.shouldShowZeroLine(gd, ax, opts.counterAxis);

    var zl = opts.layer.selectAll('path.' + cls)
        .data(show ? [{x: 0, id: ax._id}] : []);

    zl.exit().remove();

    zl.enter().append('path')
        .classed(cls, 1)
        .classed('zl', 1)
        .classed('crisp', opts.crisp !== false)
        .each(function() {
            // use the fact that only one element can enter to trigger a sort.
            // If several zerolines enter at the same time we will sort once per,
            // but generally this should be a minimal overhead.
            opts.layer.selectAll('path').sort(function(da, db) {
                return axisIds.idSort(da.id, db.id);
            });
        });

    zl.attr('transform', opts.transFn)
        .attr('d', opts.path)
        .call(Color.stroke, ax.zerolinecolor || Color.defaultLine)
        .style('stroke-width', Drawing.crispRound(gd, ax.zerolinewidth, ax._gw || 1) + 'px');
};

/**
 * Draw axis tick labels
 *
 * @param {DOM element} gd
 * @param {object} ax (full) axis object
 *  - {string} _id
 *  - {boolean} showticklabels
 *  - {number} tickangle
 *  - {object (optional)} _selections
 *  - {object} (optional)} _tickAngles
 * @param {object} opts
 * - {array of object} vals (calcTicks output-like)
 * - {d3 selection} layer
 * - {string (optional)} cls (node className)
 * - {boolean} repositionOnUpdate (set to true to reposition update selection)
 * - {boolean} secondary
 * - {fn} transFn
 * - {fn} labelXFn
 * - {fn} labelYFn
 * - {fn} labelAnchorFn
 */
axes.drawLabels = function(gd, ax, opts) {
    opts = opts || {};

    var axId = ax._id;
    var axLetter = axId.charAt(0);
    var cls = opts.cls || axId + 'tick';
    var vals = opts.vals;
    var labelXFn = opts.labelXFn;
    var labelYFn = opts.labelYFn;
    var labelAnchorFn = opts.labelAnchorFn;
    var tickAngle = opts.secondary ? 0 : ax.tickangle;
    var lastAngle = (ax._tickAngles || {})[cls];

    var tickLabels = opts.layer.selectAll('g.' + cls)
        .data(ax.showticklabels ? vals : [], tickDataFn);

    var labelsReady = [];

    tickLabels.enter().append('g')
        .classed(cls, 1)
        .append('text')
            // only so tex has predictable alignment that we can
            // alter later
            .attr('text-anchor', 'middle')
            .each(function(d) {
                var thisLabel = d3.select(this);
                var newPromise = gd._promises.length;

                thisLabel
                    .call(svgTextUtils.positionText, labelXFn(d), labelYFn(d))
                    .call(Drawing.font, d.font, d.fontSize, d.fontColor)
                    .text(d.text)
                    .call(svgTextUtils.convertToTspans, gd);

                if(gd._promises[newPromise]) {
                    // if we have an async label, we'll deal with that
                    // all here so take it out of gd._promises and
                    // instead position the label and promise this in
                    // labelsReady
                    labelsReady.push(gd._promises.pop().then(function() {
                        positionLabels(thisLabel, tickAngle);
                    }));
                } else {
                    // sync label: just position it now.
                    positionLabels(thisLabel, tickAngle);
                }
            });

    tickLabels.exit().remove();

    if(opts.repositionOnUpdate) {
        tickLabels.each(function(d) {
            d3.select(this).select('text')
                .call(svgTextUtils.positionText, labelXFn(d), labelYFn(d));
        });
    }

    // How much to shift a multi-line label to center it vertically.
    function getAnchorHeight(lineCount, lineHeight, angle) {
        var h = (lineCount - 1) * lineHeight;
        if(axLetter === 'x') {
            if(angle < -60 || 60 < angle) {
                return -0.5 * h;
            } else if(ax.side === 'top') {
                return -h;
            }
        } else {
            angle *= ax.side === 'left' ? 1 : -1;
            if(angle < -30) {
                return -h;
            } else if(angle < 30) {
                return -0.5 * h;
            }
        }
        return 0;
    }

    function positionLabels(s, angle) {
        s.each(function(d) {
            var thisLabel = d3.select(this);
            var mathjaxGroup = thisLabel.select('.text-math-group');
            var anchor = labelAnchorFn(angle, d);

            var transform = opts.transFn.call(thisLabel.node(), d) +
                ((isNumeric(angle) && +angle !== 0) ?
                (' rotate(' + angle + ',' + labelXFn(d) + ',' +
                    (labelYFn(d) - d.fontSize / 2) + ')') :
                '');

            var anchorHeight = getAnchorHeight(
                svgTextUtils.lineCount(thisLabel),
                LINE_SPACING * d.fontSize,
                isNumeric(angle) ? +angle : 0
            );

            if(anchorHeight) {
                transform += ' translate(0, ' + anchorHeight + ')';
            }

            if(mathjaxGroup.empty()) {
                thisLabel.select('text').attr({
                    transform: transform,
                    'text-anchor': anchor
                });
            } else {
                var mjWidth = Drawing.bBox(mathjaxGroup.node()).width;
                var mjShift = mjWidth * {end: -0.5, start: 0.5}[anchor];
                mathjaxGroup.attr('transform', transform + (mjShift ? 'translate(' + mjShift + ',0)' : ''));
            }
        });
    }

    // make sure all labels are correctly positioned at their base angle
    // the positionLabels call above is only for newly drawn labels.
    // do this without waiting, using the last calculated angle to
    // minimize flicker, then do it again when we know all labels are
    // there, putting back the prescribed angle to check for overlaps.
    positionLabels(tickLabels, lastAngle || tickAngle);

    function allLabelsReady() {
        return labelsReady.length && Promise.all(labelsReady);
    }

    function fixLabelOverlaps() {
        positionLabels(tickLabels, tickAngle);

        var autoangle = null;

        // check for auto-angling if x labels overlap
        // don't auto-angle at all for log axes with
        // base and digit format
        if(vals.length && axLetter === 'x' && !isNumeric(tickAngle) &&
            (ax.type !== 'log' || String(ax.dtick).charAt(0) !== 'D')
        ) {
            autoangle = 0;

            var maxFontSize = 0;
            var lbbArray = [];
            var i;

            tickLabels.each(function(d) {
                maxFontSize = Math.max(maxFontSize, d.fontSize);

                var x = ax.l2p(d.x);
                var thisLabel = selectTickLabel(this);
                var bb = Drawing.bBox(thisLabel.node());

                lbbArray.push({
                    // ignore about y, just deal with x overlaps
                    top: 0,
                    bottom: 10,
                    height: 10,
                    left: x - bb.width / 2,
                    // impose a 2px gap
                    right: x + bb.width / 2 + 2,
                    width: bb.width + 2
                });
            });

            if((ax.tickson === 'boundaries' || ax.showdividers) && !opts.secondary) {
                var gap = 2;
                if(ax.ticks) gap += ax.tickwidth / 2;

                // TODO should secondary labels also fall into this fix-overlap regime?

                for(i = 0; i < lbbArray.length; i++) {
                    var xbnd = vals[i].xbnd;
                    var lbb = lbbArray[i];
                    if(
                        (xbnd[0] !== null && (lbb.left - ax.l2p(xbnd[0])) < gap) ||
                        (xbnd[1] !== null && (ax.l2p(xbnd[1]) - lbb.right) < gap)
                    ) {
                        autoangle = 90;
                        break;
                    }
                }
            } else {
                var vLen = vals.length;
                var tickSpacing = Math.abs((vals[vLen - 1].x - vals[0].x) * ax._m) / (vLen - 1);
                var rotate90 = (tickSpacing < maxFontSize * 2.5) || ax.type === 'multicategory';

                // any overlap at all - set 30 degrees or 90 degrees
                for(i = 0; i < lbbArray.length - 1; i++) {
                    if(Lib.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) {
                        autoangle = rotate90 ? 90 : 30;
                        break;
                    }
                }
            }

            if(autoangle) {
                positionLabels(tickLabels, autoangle);
            }
        }

        if(ax._tickAngles) {
            ax._tickAngles[cls] = autoangle === null ?
                (isNumeric(tickAngle) ? tickAngle : 0) :
                autoangle;
        }
    }

    if(ax._selections) {
        ax._selections[cls] = tickLabels;
    }

    var done = Lib.syncOrAsync([allLabelsReady, fixLabelOverlaps]);
    if(done && done.then) gd._promises.push(done);
    return done;
};

/**
 * Draw axis dividers
 *
 * @param {DOM element} gd
 * @param {object} ax (full) axis object
 *  - {string} _id
 *  - {string} showdividers
 *  - {number} dividerwidth
 *  - {string} dividercolor
 * @param {object} opts
 * - {array of object} vals (calcTicks output-like)
 * - {d3 selection} layer
 * - {fn} path
 * - {fn} transFn
 */
function drawDividers(gd, ax, opts) {
    var cls = ax._id + 'divider';
    var vals = opts.vals;

    var dividers = opts.layer.selectAll('path.' + cls)
        .data(vals, tickDataFn);

    dividers.exit().remove();

    dividers.enter().insert('path', ':first-child')
        .classed(cls, 1)
        .classed('crisp', 1)
        .call(Color.stroke, ax.dividercolor)
        .style('stroke-width', Drawing.crispRound(gd, ax.dividerwidth, 1) + 'px');

    dividers
        .attr('transform', opts.transFn)
        .attr('d', opts.path);
}

function drawTitle(gd, ax) {
    var fullLayout = gd._fullLayout;
    var axId = ax._id;
    var axLetter = axId.charAt(0);
    var gs = fullLayout._size;
    var fontSize = ax.title.font.size;

    var titleStandoff;
    if(ax.type === 'multicategory') {
        titleStandoff = ax._labelLength;
    } else {
        var offsetBase = 1.5;
        titleStandoff = 10 + fontSize * offsetBase + (ax.linewidth ? ax.linewidth - 1 : 0);
    }

    var transform, counterAxis, x, y;

    if(axLetter === 'x') {
        counterAxis = (ax.anchor === 'free') ?
            {_offset: gs.t + (1 - (ax.position || 0)) * gs.h, _length: 0} :
            axisIds.getFromId(gd, ax.anchor);

        x = ax._offset + ax._length / 2;

        if(ax.side === 'top') {
            y = -titleStandoff - fontSize * (ax.showticklabels ? 1 : 0);
        } else {
            y = counterAxis._length + titleStandoff +
                fontSize * (ax.showticklabels ? 1.5 : 0.5);
        }
        y += counterAxis._offset;
    } else {
        counterAxis = (ax.anchor === 'free') ?
            {_offset: gs.l + (ax.position || 0) * gs.w, _length: 0} :
            axisIds.getFromId(gd, ax.anchor);

        y = ax._offset + ax._length / 2;

        if(ax.side === 'right') {
            x = counterAxis._length + titleStandoff +
                fontSize * (ax.showticklabels ? 1 : 0.5);
        } else {
            x = -titleStandoff - fontSize * (ax.showticklabels ? 0.5 : 0);
        }
        x += counterAxis._offset;

        transform = {rotate: '-90', offset: 0};
    }

    var avoid;

    if(ax.type !== 'multicategory') {
        var tickLabels = ax._selections[ax._id + 'tick'];

        avoid = {
            selection: tickLabels,
            side: ax.side
        };

        if(tickLabels && tickLabels.node() && tickLabels.node().parentNode) {
            var translation = Drawing.getTranslate(tickLabels.node().parentNode);
            avoid.offsetLeft = translation.x;
            avoid.offsetTop = translation.y;
        }
    }

    return Titles.draw(gd, axId + 'title', {
        propContainer: ax,
        propName: ax._name + '.title.text',
        placeholder: fullLayout._dfltTitle[axLetter],
        avoid: avoid,
        transform: transform,
        attributes: {x: x, y: y, 'text-anchor': 'middle'}
    });
}

axes.shouldShowZeroLine = function(gd, ax, counterAxis) {
    var rng = Lib.simpleMap(ax.range, ax.r2l);
    return (
        (rng[0] * rng[1] <= 0) &&
        ax.zeroline &&
        (ax.type === 'linear' || ax.type === '-') &&
        ax._gridVals.length &&
        (
            clipEnds(ax, 0) ||
            !anyCounterAxLineAtZero(gd, ax, counterAxis, rng) ||
            hasBarsOrFill(gd, ax)
        )
    );
};

axes.clipEnds = function(ax, vals) {
    return vals.filter(function(d) { return clipEnds(ax, d.x); });
};

function clipEnds(ax, l) {
    var p = ax.l2p(l);
    return (p > 1 && p < ax._length - 1);
}

function anyCounterAxLineAtZero(gd, ax, counterAxis, rng) {
    var mainCounterAxis = counterAxis._mainAxis;
    if(!mainCounterAxis) return;

    var fullLayout = gd._fullLayout;
    var axLetter = ax._id.charAt(0);
    var counterLetter = axes.counterLetter(ax._id);

    var zeroPosition = ax._offset + (
        ((Math.abs(rng[0]) < Math.abs(rng[1])) === (axLetter === 'x')) ?
        0 : ax._length
    );

    function lineNearZero(ax2) {
        if(!ax2.showline || !ax2.linewidth) return false;
        var tolerance = Math.max((ax2.linewidth + ax.zerolinewidth) / 2, 1);

        function closeEnough(pos2) {
            return typeof pos2 === 'number' && Math.abs(pos2 - zeroPosition) < tolerance;
        }

        if(closeEnough(ax2._mainLinePosition) || closeEnough(ax2._mainMirrorPosition)) {
            return true;
        }
        var linePositions = ax2._linepositions || {};
        for(var k in linePositions) {
            if(closeEnough(linePositions[k][0]) || closeEnough(linePositions[k][1])) {
                return true;
            }
        }
    }

    var plotinfo = fullLayout._plots[counterAxis._mainSubplot];
    if(!(plotinfo.mainplotinfo || plotinfo).overlays.length) {
        return lineNearZero(counterAxis, zeroPosition);
    }

    var counterLetterAxes = axes.list(gd, counterLetter);
    for(var i = 0; i < counterLetterAxes.length; i++) {
        var counterAxis2 = counterLetterAxes[i];
        if(
            counterAxis2._mainAxis === mainCounterAxis &&
            lineNearZero(counterAxis2, zeroPosition)
        ) {
            return true;
        }
    }
}

function hasBarsOrFill(gd, ax) {
    var fullData = gd._fullData;
    var subplot = ax._mainSubplot;
    var axLetter = ax._id.charAt(0);

    for(var i = 0; i < fullData.length; i++) {
        var trace = fullData[i];

        if(trace.visible === true &&
            (trace.xaxis + trace.yaxis) === subplot &&
            (
                Registry.traceIs(trace, 'bar') && trace.orientation === {x: 'h', y: 'v'}[axLetter] ||
                trace.fill && trace.fill.charAt(trace.fill.length - 1) === axLetter
            )
        ) {
            return true;
        }
    }
    return false;
}

function selectTickLabel(gTick) {
    var s = d3.select(gTick);
    var mj = s.select('.text-math-group');
    return mj.empty() ? s.select('text') : mj;
}

/**
 * Find all margin pushers for 2D axes and reserve them for later use
 * Both label and rangeslider automargin calculations happen later so
 * we need to explicitly allow their ids in order to not delete them.
 *
 * TODO: can we pull the actual automargin calls forward to avoid this hack?
 * We're probably also doing multiple redraws in this case, would be faster
 * if we can just do the whole calculation ahead of time and draw once.
 */
axes.allowAutoMargin = function(gd) {
    var axList = axes.list(gd, '', true);
    for(var i = 0; i < axList.length; i++) {
        var ax = axList[i];
        if(ax.automargin) {
            Plots.allowAutoMargin(gd, axAutoMarginID(ax));
        }
        if(Registry.getComponentMethod('rangeslider', 'isVisible')(ax)) {
            Plots.allowAutoMargin(gd, rangeSliderAutoMarginID(ax));
        }
    }
};

function axAutoMarginID(ax) { return ax._id + '.automargin'; }
function rangeSliderAutoMarginID(ax) { return ax._id + '.rangeslider'; }

// swap all the presentation attributes of the axes showing these traces
axes.swap = function(gd, traces) {
    var axGroups = makeAxisGroups(gd, traces);

    for(var i = 0; i < axGroups.length; i++) {
        swapAxisGroup(gd, axGroups[i].x, axGroups[i].y);
    }
};

function makeAxisGroups(gd, traces) {
    var groups = [];
    var i, j;

    for(i = 0; i < traces.length; i++) {
        var groupsi = [];
        var xi = gd._fullData[traces[i]].xaxis;
        var yi = gd._fullData[traces[i]].yaxis;
        if(!xi || !yi) continue; // not a 2D cartesian trace?

        for(j = 0; j < groups.length; j++) {
            if(groups[j].x.indexOf(xi) !== -1 || groups[j].y.indexOf(yi) !== -1) {
                groupsi.push(j);
            }
        }

        if(!groupsi.length) {
            groups.push({x: [xi], y: [yi]});
            continue;
        }

        var group0 = groups[groupsi[0]];
        var groupj;

        if(groupsi.length > 1) {
            for(j = 1; j < groupsi.length; j++) {
                groupj = groups[groupsi[j]];
                mergeAxisGroups(group0.x, groupj.x);
                mergeAxisGroups(group0.y, groupj.y);
            }
        }
        mergeAxisGroups(group0.x, [xi]);
        mergeAxisGroups(group0.y, [yi]);
    }

    return groups;
}

function mergeAxisGroups(intoSet, fromSet) {
    for(var i = 0; i < fromSet.length; i++) {
        if(intoSet.indexOf(fromSet[i]) === -1) intoSet.push(fromSet[i]);
    }
}

function swapAxisGroup(gd, xIds, yIds) {
    var xFullAxes = [];
    var yFullAxes = [];
    var layout = gd.layout;
    var i, j;

    for(i = 0; i < xIds.length; i++) xFullAxes.push(axes.getFromId(gd, xIds[i]));
    for(i = 0; i < yIds.length; i++) yFullAxes.push(axes.getFromId(gd, yIds[i]));

    var allAxKeys = Object.keys(axAttrs);

    var noSwapAttrs = [
        'anchor', 'domain', 'overlaying', 'position', 'side', 'tickangle', 'editType'
    ];
    var numericTypes = ['linear', 'log'];

    for(i = 0; i < allAxKeys.length; i++) {
        var keyi = allAxKeys[i];
        var xVal = xFullAxes[0][keyi];
        var yVal = yFullAxes[0][keyi];
        var allEqual = true;
        var coerceLinearX = false;
        var coerceLinearY = false;
        if(keyi.charAt(0) === '_' || typeof xVal === 'function' ||
                noSwapAttrs.indexOf(keyi) !== -1) {
            continue;
        }
        for(j = 1; j < xFullAxes.length && allEqual; j++) {
            var xVali = xFullAxes[j][keyi];
            if(keyi === 'type' && numericTypes.indexOf(xVal) !== -1 &&
                    numericTypes.indexOf(xVali) !== -1 && xVal !== xVali) {
                // type is special - if we find a mixture of linear and log,
                // coerce them all to linear on flipping
                coerceLinearX = true;
            }
            else if(xVali !== xVal) allEqual = false;
        }
        for(j = 1; j < yFullAxes.length && allEqual; j++) {
            var yVali = yFullAxes[j][keyi];
            if(keyi === 'type' && numericTypes.indexOf(yVal) !== -1 &&
                    numericTypes.indexOf(yVali) !== -1 && yVal !== yVali) {
                // type is special - if we find a mixture of linear and log,
                // coerce them all to linear on flipping
                coerceLinearY = true;
            }
            else if(yFullAxes[j][keyi] !== yVal) allEqual = false;
        }
        if(allEqual) {
            if(coerceLinearX) layout[xFullAxes[0]._name].type = 'linear';
            if(coerceLinearY) layout[yFullAxes[0]._name].type = 'linear';
            swapAxisAttrs(layout, keyi, xFullAxes, yFullAxes, gd._fullLayout._dfltTitle);
        }
    }

    // now swap x&y for any annotations anchored to these x & y
    for(i = 0; i < gd._fullLayout.annotations.length; i++) {
        var ann = gd._fullLayout.annotations[i];
        if(xIds.indexOf(ann.xref) !== -1 &&
                yIds.indexOf(ann.yref) !== -1) {
            Lib.swapAttrs(layout.annotations[i], ['?']);
        }
    }
}

function swapAxisAttrs(layout, key, xFullAxes, yFullAxes, dfltTitle) {
    // in case the value is the default for either axis,
    // look at the first axis in each list and see if
    // this key's value is undefined
    var np = Lib.nestedProperty;
    var xVal = np(layout[xFullAxes[0]._name], key).get();
    var yVal = np(layout[yFullAxes[0]._name], key).get();
    var i;

    if(key === 'title') {
        // special handling of placeholder titles
        if(xVal && xVal.text === dfltTitle.x) {
            xVal.text = dfltTitle.y;
        }
        if(yVal && yVal.text === dfltTitle.y) {
            yVal.text = dfltTitle.x;
        }
    }

    for(i = 0; i < xFullAxes.length; i++) {
        np(layout, xFullAxes[i]._name + '.' + key).set(yVal);
    }
    for(i = 0; i < yFullAxes.length; i++) {
        np(layout, yFullAxes[i]._name + '.' + key).set(xVal);
    }
}

function isAngular(ax) {
    return ax._id === 'angularaxis';
}

},{"../../components/color":571,"../../components/drawing":592,"../../components/titles":659,"../../constants/alignment":666,"../../constants/numerical":671,"../../lib":694,"../../lib/svg_text_utils":718,"../../plots/plots":806,"../../registry":825,"./autorange":741,"./axis_autotype":743,"./axis_ids":745,"./clean_ticks":747,"./layout_attributes":755,"./set_convert":761,"d3":149,"fast-isnumeric":215}],743:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

module.exports = function autoType(array, calendar, opts) {
    opts = opts || {};

    if(!opts.noMultiCategory && multiCategory(array)) return 'multicategory';
    if(moreDates(array, calendar)) return 'date';
    if(category(array)) return 'category';
    if(linearOK(array)) return 'linear';
    else return '-';
};

// is there at least one number in array? If not, we should leave
// ax.type empty so it can be autoset later
function linearOK(array) {
    if(!array) return false;

    for(var i = 0; i < array.length; i++) {
        if(isNumeric(array[i])) return true;
    }

    return false;
}

// does the array a have mostly dates rather than numbers?
// note: some values can be neither (such as blanks, text)
// 2- or 4-digit integers can be both, so require twice as many
// dates as non-dates, to exclude cases with mostly 2 & 4 digit
// numbers and a few dates
// as with categories, consider DISTINCT values only.
function moreDates(a, calendar) {
    // test at most 1000 points, evenly spaced
    var inc = Math.max(1, (a.length - 1) / 1000);
    var dcnt = 0;
    var ncnt = 0;
    var seen = {};

    for(var i = 0; i < a.length; i += inc) {
        var ai = a[Math.round(i)];
        var stri = String(ai);
        if(seen[stri]) continue;
        seen[stri] = 1;

        if(Lib.isDateTime(ai, calendar)) dcnt += 1;
        if(isNumeric(ai)) ncnt += 1;
    }

    return (dcnt > ncnt * 2);
}

// are the (x,y)-values in gd.data mostly text?
// require twice as many DISTINCT categories as distinct numbers
function category(a) {
    // test at most 1000 points
    var inc = Math.max(1, (a.length - 1) / 1000);
    var curvenums = 0;
    var curvecats = 0;
    var seen = {};

    for(var i = 0; i < a.length; i += inc) {
        var ai = a[Math.round(i)];
        var stri = String(ai);
        if(seen[stri]) continue;
        seen[stri] = 1;

        if(typeof ai === 'boolean') curvecats++;
        else if(Lib.cleanNumber(ai) !== BADNUM) curvenums++;
        else if(typeof ai === 'string') curvecats++;
    }

    return curvecats > curvenums * 2;
}

// very-loose requirements for multicategory,
// trace modules that should never auto-type to multicategory
// should be declared with 'noMultiCategory'
function multiCategory(a) {
    return Lib.isArrayOrTypedArray(a[0]) && Lib.isArrayOrTypedArray(a[1]);
}

},{"../../constants/numerical":671,"../../lib":694,"fast-isnumeric":215}],744:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');

var layoutAttributes = _dereq_('./layout_attributes');
var handleTickValueDefaults = _dereq_('./tick_value_defaults');
var handleTickMarkDefaults = _dereq_('./tick_mark_defaults');
var handleTickLabelDefaults = _dereq_('./tick_label_defaults');
var handleCategoryOrderDefaults = _dereq_('./category_order_defaults');
var handleLineGridDefaults = _dereq_('./line_grid_defaults');
var setConvert = _dereq_('./set_convert');

/**
 * options: object containing:
 *
 *  letter: 'x' or 'y'
 *  title: name of the axis (ie 'Colorbar') to go in default title
 *  font: the default font to inherit
 *  outerTicks: boolean, should ticks default to outside?
 *  showGrid: boolean, should gridlines be shown by default?
 *  noHover: boolean, this axis doesn't support hover effects?
 *  noTickson: boolean, this axis doesn't support 'tickson'
 *  data: the plot data, used to manage categories
 *  bgColor: the plot background color, to calculate default gridline colors
 */
module.exports = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) {
    var letter = options.letter;
    var font = options.font || {};
    var splomStash = options.splomStash || {};

    var visible = coerce('visible', !options.cheateronly);

    var axType = containerOut.type;

    if(axType === 'date') {
        var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleDefaults');
        handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar);
    }

    setConvert(containerOut, layoutOut);

    var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range));
    if(autoRange && (axType === 'linear' || axType === '-')) coerce('rangemode');

    coerce('range');
    containerOut.cleanRange();

    handleCategoryOrderDefaults(containerIn, containerOut, coerce, options);

    if(axType !== 'category' && !options.noHover) coerce('hoverformat');

    if(!visible) return containerOut;

    var dfltColor = coerce('color');
    // if axis.color was provided, use it for fonts too; otherwise,
    // inherit from global font color in case that was provided.
    // Compare to dflt rather than to containerIn, so we can provide color via
    // template too.
    var dfltFontColor = (dfltColor !== layoutAttributes.color.dflt) ? dfltColor : font.color;
    // try to get default title from splom trace, fallback to graph-wide value
    var dfltTitle = splomStash.label || layoutOut._dfltTitle[letter];

    coerce('title.text', dfltTitle);
    Lib.coerceFont(coerce, 'title.font', {
        family: font.family,
        size: Math.round(font.size * 1.2),
        color: dfltFontColor
    });

    handleTickValueDefaults(containerIn, containerOut, coerce, axType);
    handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options);
    handleTickMarkDefaults(containerIn, containerOut, coerce, options);
    handleLineGridDefaults(containerIn, containerOut, coerce, {
        dfltColor: dfltColor,
        bgColor: options.bgColor,
        showGrid: options.showGrid,
        attributes: layoutAttributes
    });

    if(containerOut.showline || containerOut.ticks) coerce('mirror');

    if(options.automargin) coerce('automargin');

    var isMultiCategory = containerOut.type === 'multicategory';

    if(!options.noTickson &&
        (containerOut.type === 'category' || isMultiCategory) &&
        (containerOut.ticks || containerOut.showgrid)
    ) {
        var ticksonDflt;
        if(isMultiCategory) ticksonDflt = 'boundaries';
        coerce('tickson', ticksonDflt);
    }

    if(isMultiCategory) {
        var showDividers = coerce('showdividers');
        if(showDividers) {
            coerce('dividercolor');
            coerce('dividerwidth');
        }
    }

    return containerOut;
};

},{"../../lib":694,"../../registry":825,"./category_order_defaults":746,"./layout_attributes":755,"./line_grid_defaults":757,"./set_convert":761,"./tick_label_defaults":762,"./tick_mark_defaults":763,"./tick_value_defaults":764}],745:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');

var constants = _dereq_('./constants');


// convert between axis names (xaxis, xaxis2, etc, elements of gd.layout)
// and axis id's (x, x2, etc). Would probably have ditched 'xaxis'
// completely in favor of just 'x' if it weren't ingrained in the API etc.
exports.id2name = function id2name(id) {
    if(typeof id !== 'string' || !id.match(constants.AX_ID_PATTERN)) return;
    var axNum = id.substr(1);
    if(axNum === '1') axNum = '';
    return id.charAt(0) + 'axis' + axNum;
};

exports.name2id = function name2id(name) {
    if(!name.match(constants.AX_NAME_PATTERN)) return;
    var axNum = name.substr(5);
    if(axNum === '1') axNum = '';
    return name.charAt(0) + axNum;
};

exports.cleanId = function cleanId(id, axLetter) {
    if(!id.match(constants.AX_ID_PATTERN)) return;
    if(axLetter && id.charAt(0) !== axLetter) return;

    var axNum = id.substr(1).replace(/^0+/, '');
    if(axNum === '1') axNum = '';
    return id.charAt(0) + axNum;
};

// get all axis objects, as restricted in listNames
exports.list = function(gd, axLetter, only2d) {
    var fullLayout = gd._fullLayout;
    if(!fullLayout) return [];

    var idList = exports.listIds(gd, axLetter);
    var out = new Array(idList.length);
    var i;

    for(i = 0; i < idList.length; i++) {
        var idi = idList[i];
        out[i] = fullLayout[idi.charAt(0) + 'axis' + idi.substr(1)];
    }

    if(!only2d) {
        var sceneIds3D = fullLayout._subplots.gl3d || [];

        for(i = 0; i < sceneIds3D.length; i++) {
            var scene = fullLayout[sceneIds3D[i]];

            if(axLetter) out.push(scene[axLetter + 'axis']);
            else out.push(scene.xaxis, scene.yaxis, scene.zaxis);
        }
    }

    return out;
};

// get all axis ids, optionally restricted by letter
// this only makes sense for 2d axes
exports.listIds = function(gd, axLetter) {
    var fullLayout = gd._fullLayout;
    if(!fullLayout) return [];

    var subplotLists = fullLayout._subplots;
    if(axLetter) return subplotLists[axLetter + 'axis'];
    return subplotLists.xaxis.concat(subplotLists.yaxis);
};

// get an axis object from its id 'x','x2' etc
// optionally, id can be a subplot (ie 'x2y3') and type gets x or y from it
exports.getFromId = function(gd, id, type) {
    var fullLayout = gd._fullLayout;

    if(type === 'x') id = id.replace(/y[0-9]*/, '');
    else if(type === 'y') id = id.replace(/x[0-9]*/, '');

    return fullLayout[exports.id2name(id)];
};

// get an axis object of specified type from the containing trace
exports.getFromTrace = function(gd, fullTrace, type) {
    var fullLayout = gd._fullLayout;
    var ax = null;

    if(Registry.traceIs(fullTrace, 'gl3d')) {
        var scene = fullTrace.scene;
        if(scene.substr(0, 5) === 'scene') {
            ax = fullLayout[scene][type + 'axis'];
        }
    }
    else {
        ax = exports.getFromId(gd, fullTrace[type + 'axis'] || type);
    }

    return ax;
};

// sort x, x2, x10, y, y2, y10...
exports.idSort = function(id1, id2) {
    var letter1 = id1.charAt(0);
    var letter2 = id2.charAt(0);
    if(letter1 !== letter2) return letter1 > letter2 ? 1 : -1;
    return +(id1.substr(1) || 1) - +(id2.substr(1) || 1);
};

},{"../../registry":825,"./constants":748}],746:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

function findCategories(ax, opts) {
    var dataAttr = opts.dataAttr || ax._id.charAt(0);
    var lookup = {};
    var axData;
    var i, j;

    if(opts.axData) {
        // non-x/y case
        axData = opts.axData;
    } else {
        // x/y case
        axData = [];
        for(i = 0; i < opts.data.length; i++) {
            var trace = opts.data[i];
            if(trace[dataAttr + 'axis'] === ax._id) {
                axData.push(trace);
            }
        }
    }

    for(i = 0; i < axData.length; i++) {
        var vals = axData[i][dataAttr];
        for(j = 0; j < vals.length; j++) {
            var v = vals[j];
            if(v !== null && v !== undefined) {
                lookup[v] = 1;
            }
        }
    }

    return Object.keys(lookup);
}

/**
 * Fills in category* default and initial categories.
 *
 * @param {object} containerIn : input axis object
 * @param {object} containerOut : full axis object
 * @param {function} coerce : Lib.coerce fn wrapper
 * @param {object} opts :
 *   - data {array} : (full) data trace
 * OR
 *   - axData {array} : (full) data associated with axis being coerced here
 *   - dataAttr {string} : attribute name corresponding to coordinate array
 */
module.exports = function handleCategoryOrderDefaults(containerIn, containerOut, coerce, opts) {
    if(containerOut.type !== 'category') return;

    var arrayIn = containerIn.categoryarray;
    var isValidArray = (Array.isArray(arrayIn) && arrayIn.length > 0);

    // override default 'categoryorder' value when non-empty array is supplied
    var orderDefault;
    if(isValidArray) orderDefault = 'array';

    var order = coerce('categoryorder', orderDefault);
    var array;

    // coerce 'categoryarray' only in array order case
    if(order === 'array') {
        array = coerce('categoryarray');
    }

    // cannot set 'categoryorder' to 'array' with an invalid 'categoryarray'
    if(!isValidArray && order === 'array') {
        order = containerOut.categoryorder = 'trace';
    }

    // set up things for makeCalcdata
    if(order === 'trace') {
        containerOut._initialCategories = [];
    } else if(order === 'array') {
        containerOut._initialCategories = array.slice();
    } else {
        array = findCategories(containerOut, opts).sort();
        if(order === 'category ascending') {
            containerOut._initialCategories = array;
        } else if(order === 'category descending') {
            containerOut._initialCategories = array.reverse();
        }
    }
};

},{}],747:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var Lib = _dereq_('../../lib');
var ONEDAY = _dereq_('../../constants/numerical').ONEDAY;

/**
 * Return a validated dtick value for this axis
 *
 * @param {any} dtick: the candidate dtick. valid values are numbers and strings,
 *     and further constrained depending on the axis type.
 * @param {string} axType: the axis type
 */
exports.dtick = function(dtick, axType) {
    var isLog = axType === 'log';
    var isDate = axType === 'date';
    var isCat = axType === 'category';
    var dtickDflt = isDate ? ONEDAY : 1;

    if(!dtick) return dtickDflt;

    if(isNumeric(dtick)) {
        dtick = Number(dtick);
        if(dtick <= 0) return dtickDflt;
        if(isCat) {
            // category dtick must be positive integers
            return Math.max(1, Math.round(dtick));
        }
        if(isDate) {
            // date dtick must be at least 0.1ms (our current precision)
            return Math.max(0.1, dtick);
        }
        return dtick;
    }

    if(typeof dtick !== 'string' || !(isDate || isLog)) {
        return dtickDflt;
    }

    var prefix = dtick.charAt(0);
    var dtickNum = dtick.substr(1);
    dtickNum = isNumeric(dtickNum) ? Number(dtickNum) : 0;

    if((dtickNum <= 0) || !(
            // "M<n>" gives ticks every (integer) n months
            (isDate && prefix === 'M' && dtickNum === Math.round(dtickNum)) ||
            // "L<f>" gives ticks linearly spaced in data (not in position) every (float) f
            (isLog && prefix === 'L') ||
            // "D1" gives powers of 10 with all small digits between, "D2" gives only 2 and 5
            (isLog && prefix === 'D' && (dtickNum === 1 || dtickNum === 2))
        )) {
        return dtickDflt;
    }

    return dtick;
};

/**
 * Return a validated tick0 for this axis
 *
 * @param {any} tick0: the candidate tick0. Valid values are numbers and strings,
 *     further constrained depending on the axis type
 * @param {string} axType: the axis type
 * @param {string} calendar: for date axes, the calendar to validate/convert with
 * @param {any} dtick: an already valid dtick. Only used for D1 and D2 log dticks,
 *     which do not support tick0 at all.
 */
exports.tick0 = function(tick0, axType, calendar, dtick) {
    if(axType === 'date') {
        return Lib.cleanDate(tick0, Lib.dateTick0(calendar));
    }
    if(dtick === 'D1' || dtick === 'D2') {
        // D1 and D2 modes ignore tick0 entirely
        return undefined;
    }
    // Aside from date axes, tick0 must be numeric
    return isNumeric(tick0) ? Number(tick0) : 0;
};

},{"../../constants/numerical":671,"../../lib":694,"fast-isnumeric":215}],748:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';
var counterRegex = _dereq_('../../lib/regex').counter;


module.exports = {

    idRegex: {
        x: counterRegex('x'),
        y: counterRegex('y')
    },

    attrRegex: counterRegex('[xy]axis'),

    // axis match regular expression
    xAxisMatch: counterRegex('xaxis'),
    yAxisMatch: counterRegex('yaxis'),

    // pattern matching axis ids and names
    // note that this is more permissive than counterRegex, as
    // id2name, name2id, and cleanId accept "x1" etc
    AX_ID_PATTERN: /^[xyz][0-9]*$/,
    AX_NAME_PATTERN: /^[xyz]axis[0-9]*$/,

    // and for 2D subplots
    SUBPLOT_PATTERN: /^x([0-9]*)y([0-9]*)$/,

    // pixels to move mouse before you stop clamping to starting point
    MINDRAG: 8,

    // smallest dimension allowed for a select box
    MINSELECT: 12,

    // smallest dimension allowed for a zoombox
    MINZOOM: 20,

    // width of axis drag regions
    DRAGGERSIZE: 20,

    // max pixels off straight before a lasso select line counts as bent
    BENDPX: 1.5,

    // delay before a redraw (relayout) after smooth panning and zooming
    REDRAWDELAY: 50,

    // throttling limit (ms) for selectPoints calls
    SELECTDELAY: 100,

    // cache ID suffix for throttle
    SELECTID: '-select',

    // last resort axis ranges for x and y axes if we have no data
    DFLTRANGEX: [-1, 6],
    DFLTRANGEY: [-1, 4],

    // Layers to keep trace types in the right order
    // N.B. each  'unique' plot method must have its own layer
    traceLayerClasses: [
        'heatmaplayer',
        'contourcarpetlayer', 'contourlayer',
        'barlayer',
        'carpetlayer',
        'violinlayer',
        'boxlayer',
        'ohlclayer',
        'scattercarpetlayer', 'scatterlayer'
    ],

    layerValue2layerClass: {
        'above traces': 'above',
        'below traces': 'below'
    }
};

},{"../../lib/regex":710}],749:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var id2name = _dereq_('./axis_ids').id2name;


module.exports = function handleConstraintDefaults(containerIn, containerOut, coerce, allAxisIds, layoutOut) {
    var constraintGroups = layoutOut._axisConstraintGroups;
    var thisID = containerOut._id;
    var letter = thisID.charAt(0);

    if(containerOut.fixedrange) return;

    // coerce the constraint mechanics even if this axis has no scaleanchor
    // because it may be the anchor of another axis.
    coerce('constrain');
    Lib.coerce(containerIn, containerOut, {
        constraintoward: {
            valType: 'enumerated',
            values: letter === 'x' ? ['left', 'center', 'right'] : ['bottom', 'middle', 'top'],
            dflt: letter === 'x' ? 'center' : 'middle'
        }
    }, 'constraintoward');

    if(!containerIn.scaleanchor) return;

    var constraintOpts = getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut);

    var scaleanchor = Lib.coerce(containerIn, containerOut, {
        scaleanchor: {
            valType: 'enumerated',
            values: constraintOpts.linkableAxes
        }
    }, 'scaleanchor');

    if(scaleanchor) {
        var scaleratio = coerce('scaleratio');
        // TODO: I suppose I could do attribute.min: Number.MIN_VALUE to avoid zero,
        // but that seems hacky. Better way to say "must be a positive number"?
        // Of course if you use several super-tiny values you could eventually
        // force a product of these to zero and all hell would break loose...
        // Likewise with super-huge values.
        if(!scaleratio) scaleratio = containerOut.scaleratio = 1;

        updateConstraintGroups(constraintGroups, constraintOpts.thisGroup,
            thisID, scaleanchor, scaleratio);
    }
    else if(allAxisIds.indexOf(containerIn.scaleanchor) !== -1) {
        Lib.warn('ignored ' + containerOut._name + '.scaleanchor: "' +
            containerIn.scaleanchor + '" to avoid either an infinite loop ' +
            'and possibly inconsistent scaleratios, or because the target' +
            'axis has fixed range.');
    }
};

function getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut) {
    // If this axis is already part of a constraint group, we can't
    // scaleanchor any other axis in that group, or we'd make a loop.
    // Filter allAxisIds to enforce this, also matching axis types.

    var thisType = layoutOut[id2name(thisID)].type;

    var i, j, idj, axj;

    var linkableAxes = [];
    for(j = 0; j < allAxisIds.length; j++) {
        idj = allAxisIds[j];
        if(idj === thisID) continue;

        axj = layoutOut[id2name(idj)];
        if(axj.type === thisType && !axj.fixedrange) linkableAxes.push(idj);
    }

    for(i = 0; i < constraintGroups.length; i++) {
        if(constraintGroups[i][thisID]) {
            var thisGroup = constraintGroups[i];

            var linkableAxesNoLoops = [];
            for(j = 0; j < linkableAxes.length; j++) {
                idj = linkableAxes[j];
                if(!thisGroup[idj]) linkableAxesNoLoops.push(idj);
            }
            return {linkableAxes: linkableAxesNoLoops, thisGroup: thisGroup};
        }
    }

    return {linkableAxes: linkableAxes, thisGroup: null};
}


/*
 * Add this axis to the axis constraint groups, which is the collection
 * of axes that are all constrained together on scale.
 *
 * constraintGroups: a list of objects. each object is
 * {axis_id: scale_within_group}, where scale_within_group is
 * only important relative to the rest of the group, and defines
 * the relative scales between all axes in the group
 *
 * thisGroup: the group the current axis is already in
 * thisID: the id if the current axis
 * scaleanchor: the id of the axis to scale it with
 * scaleratio: the ratio of this axis to the scaleanchor axis
 */
function updateConstraintGroups(constraintGroups, thisGroup, thisID, scaleanchor, scaleratio) {
    var i, j, groupi, keyj, thisGroupIndex;

    if(thisGroup === null) {
        thisGroup = {};
        thisGroup[thisID] = 1;
        thisGroupIndex = constraintGroups.length;
        constraintGroups.push(thisGroup);
    }
    else {
        thisGroupIndex = constraintGroups.indexOf(thisGroup);
    }

    var thisGroupKeys = Object.keys(thisGroup);

    // we know that this axis isn't in any other groups, but we don't know
    // about the scaleanchor axis. If it is, we need to merge the groups.
    for(i = 0; i < constraintGroups.length; i++) {
        groupi = constraintGroups[i];
        if(i !== thisGroupIndex && groupi[scaleanchor]) {
            var baseScale = groupi[scaleanchor];
            for(j = 0; j < thisGroupKeys.length; j++) {
                keyj = thisGroupKeys[j];
                groupi[keyj] = baseScale * scaleratio * thisGroup[keyj];
            }
            constraintGroups.splice(thisGroupIndex, 1);
            return;
        }
    }

    // otherwise, we insert the new scaleanchor axis as the base scale (1)
    // in its group, and scale the rest of the group to it
    if(scaleratio !== 1) {
        for(j = 0; j < thisGroupKeys.length; j++) {
            thisGroup[thisGroupKeys[j]] *= scaleratio;
        }
    }
    thisGroup[scaleanchor] = 1;
}

},{"../../lib":694,"./axis_ids":745}],750:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var id2name = _dereq_('./axis_ids').id2name;
var scaleZoom = _dereq_('./scale_zoom');
var makePadFn = _dereq_('./autorange').makePadFn;
var concatExtremes = _dereq_('./autorange').concatExtremes;

var ALMOST_EQUAL = _dereq_('../../constants/numerical').ALMOST_EQUAL;

var FROM_BL = _dereq_('../../constants/alignment').FROM_BL;


exports.enforce = function enforceAxisConstraints(gd) {
    var fullLayout = gd._fullLayout;
    var constraintGroups = fullLayout._axisConstraintGroups || [];

    var i, j, axisID, ax, normScale, mode, factor;

    for(i = 0; i < constraintGroups.length; i++) {
        var group = constraintGroups[i];
        var axisIDs = Object.keys(group);

        var minScale = Infinity;
        var maxScale = 0;
        // mostly matchScale will be the same as minScale
        // ie we expand axis ranges to encompass *everything*
        // that's currently in any of their ranges, but during
        // autorange of a subset of axes we will ignore other
        // axes for this purpose.
        var matchScale = Infinity;
        var normScales = {};
        var axes = {};
        var hasAnyDomainConstraint = false;

        // find the (normalized) scale of each axis in the group
        for(j = 0; j < axisIDs.length; j++) {
            axisID = axisIDs[j];
            axes[axisID] = ax = fullLayout[id2name(axisID)];

            if(ax._inputDomain) ax.domain = ax._inputDomain.slice();
            else ax._inputDomain = ax.domain.slice();

            if(!ax._inputRange) ax._inputRange = ax.range.slice();

            // set axis scale here so we can use _m rather than
            // having to calculate it from length and range
            ax.setScale();

            // abs: inverted scales still satisfy the constraint
            normScales[axisID] = normScale = Math.abs(ax._m) / group[axisID];
            minScale = Math.min(minScale, normScale);
            if(ax.constrain === 'domain' || !ax._constraintShrinkable) {
                matchScale = Math.min(matchScale, normScale);
            }

            // this has served its purpose, so remove it
            delete ax._constraintShrinkable;
            maxScale = Math.max(maxScale, normScale);

            if(ax.constrain === 'domain') hasAnyDomainConstraint = true;
        }

        // Do we have a constraint mismatch? Give a small buffer for rounding errors
        if(minScale > ALMOST_EQUAL * maxScale && !hasAnyDomainConstraint) continue;

        // now increase any ranges we need to until all normalized scales are equal
        for(j = 0; j < axisIDs.length; j++) {
            axisID = axisIDs[j];
            normScale = normScales[axisID];
            ax = axes[axisID];
            mode = ax.constrain;

            // even if the scale didn't change, if we're shrinking domain
            // we need to recalculate in case `constraintoward` changed
            if(normScale !== matchScale || mode === 'domain') {
                factor = normScale / matchScale;

                if(mode === 'range') {
                    scaleZoom(ax, factor);
                }
                else {
                    // mode === 'domain'

                    var inputDomain = ax._inputDomain;
                    var domainShrunk = (ax.domain[1] - ax.domain[0]) /
                        (inputDomain[1] - inputDomain[0]);
                    var rangeShrunk = (ax.r2l(ax.range[1]) - ax.r2l(ax.range[0])) /
                        (ax.r2l(ax._inputRange[1]) - ax.r2l(ax._inputRange[0]));

                    factor /= domainShrunk;

                    if(factor * rangeShrunk < 1) {
                        // we've asked to magnify the axis more than we can just by
                        // enlarging the domain - so we need to constrict range
                        ax.domain = ax._input.domain = inputDomain.slice();
                        scaleZoom(ax, factor);
                        continue;
                    }

                    if(rangeShrunk < 1) {
                        // the range has previously been constricted by ^^, but we've
                        // switched to the domain-constricted regime, so reset range
                        ax.range = ax._input.range = ax._inputRange.slice();
                        factor *= rangeShrunk;
                    }

                    if(ax.autorange) {
                        /*
                         * range & factor may need to change because range was
                         * calculated for the larger scaling, so some pixel
                         * paddings may get cut off when we reduce the domain.
                         *
                         * This is easier than the regular autorange calculation
                         * because we already know the scaling `m`, but we still
                         * need to cut out impossible constraints (like
                         * annotations with super-long arrows). That's what
                         * outerMin/Max are for - if the expansion was going to
                         * go beyond the original domain, it must be impossible
                         */
                        var rl0 = ax.r2l(ax.range[0]);
                        var rl1 = ax.r2l(ax.range[1]);
                        var rangeCenter = (rl0 + rl1) / 2;
                        var rangeMin = rangeCenter;
                        var rangeMax = rangeCenter;
                        var halfRange = Math.abs(rl1 - rangeCenter);
                        // extra tiny bit for rounding errors, in case we actually
                        // *are* expanding to the full domain
                        var outerMin = rangeCenter - halfRange * factor * 1.0001;
                        var outerMax = rangeCenter + halfRange * factor * 1.0001;
                        var getPad = makePadFn(ax);

                        updateDomain(ax, factor);
                        var m = Math.abs(ax._m);
                        var extremes = concatExtremes(gd, ax);
                        var minArray = extremes.min;
                        var maxArray = extremes.max;
                        var newVal;
                        var k;

                        for(k = 0; k < minArray.length; k++) {
                            newVal = minArray[k].val - getPad(minArray[k]) / m;
                            if(newVal > outerMin && newVal < rangeMin) {
                                rangeMin = newVal;
                            }
                        }

                        for(k = 0; k < maxArray.length; k++) {
                            newVal = maxArray[k].val + getPad(maxArray[k]) / m;
                            if(newVal < outerMax && newVal > rangeMax) {
                                rangeMax = newVal;
                            }
                        }

                        var domainExpand = (rangeMax - rangeMin) / (2 * halfRange);
                        factor /= domainExpand;

                        rangeMin = ax.l2r(rangeMin);
                        rangeMax = ax.l2r(rangeMax);
                        ax.range = ax._input.range = (rl0 < rl1) ?
                            [rangeMin, rangeMax] : [rangeMax, rangeMin];
                    }

                    updateDomain(ax, factor);
                }
            }
        }
    }
};

// For use before autoranging, check if this axis was previously constrained
// by domain but no longer is
exports.clean = function cleanConstraints(gd, ax) {
    if(ax._inputDomain) {
        var isConstrained = false;
        var axId = ax._id;
        var constraintGroups = gd._fullLayout._axisConstraintGroups;
        for(var j = 0; j < constraintGroups.length; j++) {
            if(constraintGroups[j][axId]) {
                isConstrained = true;
                break;
            }
        }
        if(!isConstrained || ax.constrain !== 'domain') {
            ax._input.domain = ax.domain = ax._inputDomain;
            delete ax._inputDomain;
        }
    }
};

function updateDomain(ax, factor) {
    var inputDomain = ax._inputDomain;
    var centerFraction = FROM_BL[ax.constraintoward];
    var center = inputDomain[0] + (inputDomain[1] - inputDomain[0]) * centerFraction;

    ax.domain = ax._input.domain = [
        center + (inputDomain[0] - center) / factor,
        center + (inputDomain[1] - center) / factor
    ];
    ax.setScale();
}

},{"../../constants/alignment":666,"../../constants/numerical":671,"./autorange":741,"./axis_ids":745,"./scale_zoom":759}],751:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var tinycolor = _dereq_('tinycolor2');
var supportsPassive = _dereq_('has-passive-events');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var Color = _dereq_('../../components/color');
var Drawing = _dereq_('../../components/drawing');
var Fx = _dereq_('../../components/fx');
var Axes = _dereq_('./axes');
var setCursor = _dereq_('../../lib/setcursor');
var dragElement = _dereq_('../../components/dragelement');
var FROM_TL = _dereq_('../../constants/alignment').FROM_TL;
var clearGlCanvases = _dereq_('../../lib/clear_gl_canvases');
var redrawReglTraces = _dereq_('../../plot_api/subroutines').redrawReglTraces;

var Plots = _dereq_('../plots');

var getFromId = _dereq_('./axis_ids').getFromId;
var prepSelect = _dereq_('./select').prepSelect;
var clearSelect = _dereq_('./select').clearSelect;
var selectOnClick = _dereq_('./select').selectOnClick;
var scaleZoom = _dereq_('./scale_zoom');

var constants = _dereq_('./constants');
var MINDRAG = constants.MINDRAG;
var MINZOOM = constants.MINZOOM;


// flag for showing "doubleclick to zoom out" only at the beginning
var SHOWZOOMOUTTIP = true;

// dragBox: create an element to drag one or more axis ends
// inputs:
//      plotinfo - which subplot are we making dragboxes on?
//      x,y,w,h - left, top, width, height of the box
//      ns - how does this drag the vertical axis?
//          'n' - top only
//          's' - bottom only
//          'ns' - top and bottom together, difference unchanged
//      ew - same for horizontal axis
function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) {
    // mouseDown stores ms of first mousedown event in the last
    // DBLCLICKDELAY ms on the drag bars
    // numClicks stores how many mousedowns have been seen
    // within DBLCLICKDELAY so we can check for click or doubleclick events
    // dragged stores whether a drag has occurred, so we don't have to
    // redraw unnecessarily, ie if no move bigger than MINDRAG or MINZOOM px
    var zoomlayer = gd._fullLayout._zoomlayer;
    var isMainDrag = (ns + ew === 'nsew');
    var singleEnd = (ns + ew).length === 1;

    // main subplot x and y (i.e. found in plotinfo - the main ones)
    var xa0, ya0;
    // {ax._id: ax} hash objects
    var xaHash, yaHash;
    // xaHash/yaHash values (arrays)
    var xaxes, yaxes;
    // main axis offsets
    var xs, ys;
    // main axis lengths
    var pw, ph;
    // contains keys 'xaHash', 'yaHash', 'xaxes', and 'yaxes'
    // which are the x/y {ax._id: ax} hash objects and their values
    // for linked axis relative to this subplot
    var links;
    // set to ew/ns val when active, set to '' when inactive
    var xActive, yActive;
    // are all axes in this subplot are fixed?
    var allFixedRanges;
    // is subplot constrained?
    var isSubplotConstrained;
    // do we need to edit x/y ranges?
    var editX, editY;
    // graph-wide optimization flags
    var hasScatterGl, hasSplom, hasSVG;
    // collected changes to be made to the plot by relayout at the end
    var updates;

    function recomputeAxisLists() {
        xa0 = plotinfo.xaxis;
        ya0 = plotinfo.yaxis;
        pw = xa0._length;
        ph = ya0._length;
        xs = xa0._offset;
        ys = ya0._offset;

        xaHash = {};
        xaHash[xa0._id] = xa0;
        yaHash = {};
        yaHash[ya0._id] = ya0;

        // if we're dragging two axes at once, also drag overlays
        if(ns && ew) {
            var overlays = plotinfo.overlays;
            for(var i = 0; i < overlays.length; i++) {
                var xa = overlays[i].xaxis;
                xaHash[xa._id] = xa;
                var ya = overlays[i].yaxis;
                yaHash[ya._id] = ya;
            }
        }

        xaxes = hashValues(xaHash);
        yaxes = hashValues(yaHash);
        xActive = isDirectionActive(xaxes, ew);
        yActive = isDirectionActive(yaxes, ns);
        allFixedRanges = !yActive && !xActive;

        links = calcLinks(gd, xaHash, yaHash);
        isSubplotConstrained = links.isSubplotConstrained;
        editX = ew || isSubplotConstrained;
        editY = ns || isSubplotConstrained;

        var fullLayout = gd._fullLayout;
        hasScatterGl = fullLayout._has('scattergl');
        hasSplom = fullLayout._has('splom');
        hasSVG = fullLayout._has('svg');
    }

    recomputeAxisLists();

    var cursor = getDragCursor(yActive + xActive, gd._fullLayout.dragmode, isMainDrag);
    var dragger = makeRectDragger(plotinfo, ns + ew + 'drag', cursor, x, y, w, h);

    // still need to make the element if the axes are disabled
    // but nuke its events (except for maindrag which needs them for hover)
    // and stop there
    if(allFixedRanges && !isMainDrag) {
        dragger.onmousedown = null;
        dragger.style.pointerEvents = 'none';
        return dragger;
    }

    var dragOptions = {
        element: dragger,
        gd: gd,
        plotinfo: plotinfo
    };

    dragOptions.prepFn = function(e, startX, startY) {
        var dragModePrev = dragOptions.dragmode;
        var dragModeNow = gd._fullLayout.dragmode;
        if(dragModeNow !== dragModePrev) {
            dragOptions.dragmode = dragModeNow;
        }

        recomputeAxisLists();

        if(!allFixedRanges) {
            if(isMainDrag) {
                // main dragger handles all drag modes, and changes
                // to pan (or to zoom if it already is pan) on shift
                if(e.shiftKey) {
                    if(dragModeNow === 'pan') dragModeNow = 'zoom';
                    else if(!isSelectOrLasso(dragModeNow)) dragModeNow = 'pan';
                }
                else if(e.ctrlKey) {
                    dragModeNow = 'pan';
                }
            }
            // all other draggers just pan
            else dragModeNow = 'pan';
        }

        if(dragModeNow === 'lasso') dragOptions.minDrag = 1;
        else dragOptions.minDrag = undefined;

        if(isSelectOrLasso(dragModeNow)) {
            dragOptions.xaxes = xaxes;
            dragOptions.yaxes = yaxes;
            // this attaches moveFn, clickFn, doneFn on dragOptions
            prepSelect(e, startX, startY, dragOptions, dragModeNow);
        } else {
            dragOptions.clickFn = clickFn;
            if(isSelectOrLasso(dragModePrev)) {
                // TODO Fix potential bug
                // Note: clearing / resetting selection state only happens, when user
                // triggers at least one interaction in pan/zoom mode. Otherwise, the
                // select/lasso outlines are deleted (in plots.js.cleanPlot) but the selection
                // cache isn't cleared. So when the user switches back to select/lasso and
                // 'adds to a selection' with Shift, the "old", seemingly removed outlines
                // are redrawn again because the selection cache still holds their coordinates.
                // However, this isn't easily solved, since plots.js would need
                // to have a reference to the dragOptions object (which holds the
                // selection cache).
                clearAndResetSelect();
            }

            if(!allFixedRanges) {
                if(dragModeNow === 'zoom') {
                    dragOptions.moveFn = zoomMove;
                    dragOptions.doneFn = zoomDone;

                    // zoomMove takes care of the threshold, but we need to
                    // minimize this so that constrained zoom boxes will flip
                    // orientation at the right place
                    dragOptions.minDrag = 1;

                    zoomPrep(e, startX, startY);
                } else if(dragModeNow === 'pan') {
                    dragOptions.moveFn = plotDrag;
                    dragOptions.doneFn = dragTail;
                }
            }
        }
    };

    function clearAndResetSelect() {
        // clear selection polygon cache (if any)
        dragOptions.plotinfo.selection = false;
        // clear selection outlines
        clearSelect(zoomlayer);
    }

    function clickFn(numClicks, evt) {
        var clickmode = gd._fullLayout.clickmode;

        removeZoombox(gd);

        if(numClicks === 2 && !singleEnd) doubleClick();

        if(isMainDrag) {
            if(clickmode.indexOf('select') > -1) {
                selectOnClick(evt, gd, xaxes, yaxes, plotinfo.id, dragOptions);
            }

            if(clickmode.indexOf('event') > -1) {
                Fx.click(gd, evt, plotinfo.id);
            }
        }
        else if(numClicks === 1 && singleEnd) {
            var ax = ns ? ya0 : xa0;
            var end = (ns === 's' || ew === 'w') ? 0 : 1;
            var attrStr = ax._name + '.range[' + end + ']';
            var initialText = getEndText(ax, end);
            var hAlign = 'left';
            var vAlign = 'middle';

            if(ax.fixedrange) return;

            if(ns) {
                vAlign = (ns === 'n') ? 'top' : 'bottom';
                if(ax.side === 'right') hAlign = 'right';
            }
            else if(ew === 'e') hAlign = 'right';

            if(gd._context.showAxisRangeEntryBoxes) {
                d3.select(dragger)
                    .call(svgTextUtils.makeEditable, {
                        gd: gd,
                        immediate: true,
                        background: gd._fullLayout.paper_bgcolor,
                        text: String(initialText),
                        fill: ax.tickfont ? ax.tickfont.color : '#444',
                        horizontalAlign: hAlign,
                        verticalAlign: vAlign
                    })
                    .on('edit', function(text) {
                        var v = ax.d2r(text);
                        if(v !== undefined) {
                            Registry.call('_guiRelayout', gd, attrStr, v);
                        }
                    });
            }
        }
    }

    dragElement.init(dragOptions);

    var x0,
        y0,
        box,
        lum,
        path0,
        dimmed,
        zoomMode,
        zb,
        corners;

    // zoom takes over minDrag, so it also has to take over gd._dragged
    var zoomDragged;

    function zoomPrep(e, startX, startY) {
        var dragBBox = dragger.getBoundingClientRect();
        x0 = startX - dragBBox.left;
        y0 = startY - dragBBox.top;
        box = {l: x0, r: x0, w: 0, t: y0, b: y0, h: 0};
        lum = gd._hmpixcount ?
            (gd._hmlumcount / gd._hmpixcount) :
            tinycolor(gd._fullLayout.plot_bgcolor).getLuminance();
        path0 = 'M0,0H' + pw + 'V' + ph + 'H0V0';
        dimmed = false;
        zoomMode = 'xy';
        zoomDragged = false;

        zb = makeZoombox(zoomlayer, lum, xs, ys, path0);

        corners = makeCorners(zoomlayer, xs, ys);
    }

    function zoomMove(dx0, dy0) {
        if(gd._transitioningWithDuration) {
            return false;
        }

        var x1 = Math.max(0, Math.min(pw, dx0 + x0));
        var y1 = Math.max(0, Math.min(ph, dy0 + y0));
        var dx = Math.abs(x1 - x0);
        var dy = Math.abs(y1 - y0);

        box.l = Math.min(x0, x1);
        box.r = Math.max(x0, x1);
        box.t = Math.min(y0, y1);
        box.b = Math.max(y0, y1);

        function noZoom() {
            zoomMode = '';
            box.r = box.l;
            box.t = box.b;
            corners.attr('d', 'M0,0Z');
        }

        if(isSubplotConstrained) {
            if(dx > MINZOOM || dy > MINZOOM) {
                zoomMode = 'xy';
                if(dx / pw > dy / ph) {
                    dy = dx * ph / pw;
                    if(y0 > y1) box.t = y0 - dy;
                    else box.b = y0 + dy;
                }
                else {
                    dx = dy * pw / ph;
                    if(x0 > x1) box.l = x0 - dx;
                    else box.r = x0 + dx;
                }
                corners.attr('d', xyCorners(box));
            }
            else {
                noZoom();
            }
        }
        // look for small drags in one direction or the other,
        // and only drag the other axis
        else if(!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) {
            if(dx < MINDRAG || !xActive) {
                noZoom();
            } else {
                box.t = 0;
                box.b = ph;
                zoomMode = 'x';
                corners.attr('d', xCorners(box, y0));
            }
        }
        else if(!xActive || dx < Math.min(dy * 0.6, MINZOOM)) {
            box.l = 0;
            box.r = pw;
            zoomMode = 'y';
            corners.attr('d', yCorners(box, x0));
        }
        else {
            zoomMode = 'xy';
            corners.attr('d', xyCorners(box));
        }
        box.w = box.r - box.l;
        box.h = box.b - box.t;

        if(zoomMode) zoomDragged = true;
        gd._dragged = zoomDragged;

        updateZoombox(zb, corners, box, path0, dimmed, lum);
        dimmed = true;
    }

    function zoomDone() {
        updates = {};

        // more strict than dragged, which allows you to come back to where you started
        // and still count as dragged
        if(Math.min(box.h, box.w) < MINDRAG * 2) {
            return removeZoombox(gd);
        }

        // TODO: edit linked axes in zoomAxRanges and in dragTail
        if(zoomMode === 'xy' || zoomMode === 'x') {
            zoomAxRanges(xaxes, box.l / pw, box.r / pw, updates, links.xaxes);
        }
        if(zoomMode === 'xy' || zoomMode === 'y') {
            zoomAxRanges(yaxes, (ph - box.b) / ph, (ph - box.t) / ph, updates, links.yaxes);
        }

        removeZoombox(gd);
        dragTail();
        showDoubleClickNotifier(gd);
    }

    // scroll zoom, on all draggers except corners
    var scrollViewBox = [0, 0, pw, ph];
    // wait a little after scrolling before redrawing
    var redrawTimer = null;
    var REDRAWDELAY = constants.REDRAWDELAY;
    var mainplot = plotinfo.mainplot ? gd._fullLayout._plots[plotinfo.mainplot] : plotinfo;

    function zoomWheel(e) {
        // deactivate mousewheel scrolling on embedded graphs
        // devs can override this with layout._enablescrollzoom,
        // but _ ensures this setting won't leave their page
        if(!gd._context._scrollZoom.cartesian && !gd._fullLayout._enablescrollzoom) {
            return;
        }

        clearAndResetSelect();

        // If a transition is in progress, then disable any behavior:
        if(gd._transitioningWithDuration) {
            e.preventDefault();
            e.stopPropagation();
            return;
        }

        recomputeAxisLists();

        clearTimeout(redrawTimer);

        var wheelDelta = -e.deltaY;
        if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10;
        if(!isFinite(wheelDelta)) {
            Lib.log('Did not find wheel motion attributes: ', e);
            return;
        }

        var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200);
        var gbb = mainplot.draglayer.select('.nsewdrag').node().getBoundingClientRect();
        var xfrac = (e.clientX - gbb.left) / gbb.width;
        var yfrac = (gbb.bottom - e.clientY) / gbb.height;
        var i;

        function zoomWheelOneAxis(ax, centerFraction, zoom) {
            if(ax.fixedrange) return;

            var axRange = Lib.simpleMap(ax.range, ax.r2l);
            var v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction;
            function doZoom(v) { return ax.l2r(v0 + (v - v0) * zoom); }
            ax.range = axRange.map(doZoom);
        }

        if(editX) {
            // if we're only zooming this axis because of constraints,
            // zoom it about the center
            if(!ew) xfrac = 0.5;

            for(i = 0; i < xaxes.length; i++) {
                zoomWheelOneAxis(xaxes[i], xfrac, zoom);
            }

            scrollViewBox[2] *= zoom;
            scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1);
        }
        if(editY) {
            if(!ns) yfrac = 0.5;

            for(i = 0; i < yaxes.length; i++) {
                zoomWheelOneAxis(yaxes[i], yfrac, zoom);
            }

            scrollViewBox[3] *= zoom;
            scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1);
        }

        // viewbox redraw at first
        updateSubplots(scrollViewBox);
        ticksAndAnnotations();

        // then replot after a delay to make sure
        // no more scrolling is coming
        redrawTimer = setTimeout(function() {
            scrollViewBox = [0, 0, pw, ph];
            dragTail();
        }, REDRAWDELAY);

        e.preventDefault();
        return;
    }

    // everything but the corners gets wheel zoom
    if(ns.length * ew.length !== 1) {
        attachWheelEventHandler(dragger, zoomWheel);
    }

    // plotDrag: move the plot in response to a drag
    function plotDrag(dx, dy) {
        // If a transition is in progress, then disable any behavior:
        if(gd._transitioningWithDuration) {
            return;
        }

        // prevent axis drawing from monkeying with margins until we're done
        gd._fullLayout._replotting = true;

        if(xActive === 'ew' || yActive === 'ns') {
            if(xActive) dragAxList(xaxes, dx);
            if(yActive) dragAxList(yaxes, dy);
            updateSubplots([xActive ? -dx : 0, yActive ? -dy : 0, pw, ph]);
            ticksAndAnnotations();
            return;
        }

        // dz: set a new value for one end (0 or 1) of an axis array axArray,
        // and return a pixel shift for that end for the viewbox
        // based on pixel drag distance d
        // TODO: this makes (generally non-fatal) errors when you get
        // near floating point limits
        function dz(axArray, end, d) {
            var otherEnd = 1 - end;
            var movedAx;
            var newLinearizedEnd;
            for(var i = 0; i < axArray.length; i++) {
                var axi = axArray[i];
                if(axi.fixedrange) continue;
                movedAx = axi;
                newLinearizedEnd = axi._rl[otherEnd] +
                    (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length);
                var newEnd = axi.l2r(newLinearizedEnd);

                // if l2r comes back false or undefined, it means we've dragged off
                // the end of valid ranges - so stop.
                if(newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd;
            }
            return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) /
                (movedAx._rl[end] - movedAx._rl[otherEnd]);
        }

        if(isSubplotConstrained && xActive && yActive) {
            // dragging a corner of a constrained subplot:
            // respect the fixed corner, but harmonize dx and dy
            var dxySign = ((xActive === 'w') === (yActive === 'n')) ? 1 : -1;
            var dxyFraction = (dx / pw + dxySign * dy / ph) / 2;
            dx = dxyFraction * pw;
            dy = dxySign * dxyFraction * ph;
        }

        if(xActive === 'w') dx = dz(xaxes, 0, dx);
        else if(xActive === 'e') dx = dz(xaxes, 1, -dx);
        else if(!xActive) dx = 0;

        if(yActive === 'n') dy = dz(yaxes, 1, dy);
        else if(yActive === 's') dy = dz(yaxes, 0, -dy);
        else if(!yActive) dy = 0;

        var x0 = (xActive === 'w') ? dx : 0;
        var y0 = (yActive === 'n') ? dy : 0;

        if(isSubplotConstrained) {
            var i;
            if(!xActive && yActive.length === 1) {
                // dragging one end of the y axis of a constrained subplot
                // scale the other axis the same about its middle
                for(i = 0; i < xaxes.length; i++) {
                    xaxes[i].range = xaxes[i]._r.slice();
                    scaleZoom(xaxes[i], 1 - dy / ph);
                }
                dx = dy * pw / ph;
                x0 = dx / 2;
            }
            if(!yActive && xActive.length === 1) {
                for(i = 0; i < yaxes.length; i++) {
                    yaxes[i].range = yaxes[i]._r.slice();
                    scaleZoom(yaxes[i], 1 - dx / pw);
                }
                dy = dx * ph / pw;
                y0 = dy / 2;
            }
        }

        updateSubplots([x0, y0, pw - dx, ph - dy]);
        ticksAndAnnotations();
    }

    // Draw ticks and annotations (and other components) when ranges change.
    // Also records the ranges that have changed for use by update at the end.
    function ticksAndAnnotations() {
        var activeAxIds = [];
        var i;

        function pushActiveAxIds(axList) {
            for(i = 0; i < axList.length; i++) {
                if(!axList[i].fixedrange) activeAxIds.push(axList[i]._id);
            }
        }

        if(editX) {
            pushActiveAxIds(xaxes);
            pushActiveAxIds(links.xaxes);
        }
        if(editY) {
            pushActiveAxIds(yaxes);
            pushActiveAxIds(links.yaxes);
        }

        updates = {};
        for(i = 0; i < activeAxIds.length; i++) {
            var axId = activeAxIds[i];
            var ax = getFromId(gd, axId);
            Axes.drawOne(gd, ax, {skipTitle: true});
            updates[ax._name + '.range[0]'] = ax.range[0];
            updates[ax._name + '.range[1]'] = ax.range[1];
        }

        Axes.redrawComponents(gd, activeAxIds);
    }

    function doubleClick() {
        if(gd._transitioningWithDuration) return;

        var doubleClickConfig = gd._context.doubleClick;
        var axList = (xActive ? xaxes : []).concat(yActive ? yaxes : []);
        var attrs = {};

        var ax, i, rangeInitial;

        // For reset+autosize mode:
        // If *any* of the main axes is not at its initial range
        // (or autoranged, if we have no initial range, to match the logic in
        // doubleClickConfig === 'reset' below), we reset.
        // If they are *all* at their initial ranges, then we autosize.
        if(doubleClickConfig === 'reset+autosize') {

            doubleClickConfig = 'autosize';

            for(i = 0; i < axList.length; i++) {
                ax = axList[i];
                if((ax._rangeInitial && (
                        ax.range[0] !== ax._rangeInitial[0] ||
                        ax.range[1] !== ax._rangeInitial[1]
                    )) ||
                    (!ax._rangeInitial && !ax.autorange)
                ) {
                    doubleClickConfig = 'reset';
                    break;
                }
            }
        }

        if(doubleClickConfig === 'autosize') {
            // don't set the linked axes here, so relayout marks them as shrinkable
            // and we autosize just to the requested axis/axes
            for(i = 0; i < axList.length; i++) {
                ax = axList[i];
                if(!ax.fixedrange) attrs[ax._name + '.autorange'] = true;
            }
        }
        else if(doubleClickConfig === 'reset') {
            // when we're resetting, reset all linked axes too, so we get back
            // to the fully-auto-with-constraints situation
            if(xActive || isSubplotConstrained) axList = axList.concat(links.xaxes);
            if(yActive && !isSubplotConstrained) axList = axList.concat(links.yaxes);

            if(isSubplotConstrained) {
                if(!xActive) axList = axList.concat(xaxes);
                else if(!yActive) axList = axList.concat(yaxes);
            }

            for(i = 0; i < axList.length; i++) {
                ax = axList[i];

                if(!ax.fixedrange) {
                    if(!ax._rangeInitial) {
                        attrs[ax._name + '.autorange'] = true;
                    } else {
                        rangeInitial = ax._rangeInitial;
                        attrs[ax._name + '.range[0]'] = rangeInitial[0];
                        attrs[ax._name + '.range[1]'] = rangeInitial[1];
                    }
                }
            }
        }

        gd.emit('plotly_doubleclick', null);
        Registry.call('_guiRelayout', gd, attrs);
    }

    // dragTail - finish a drag event with a redraw
    function dragTail() {
        // put the subplot viewboxes back to default (Because we're going to)
        // be repositioning the data in the relayout. But DON'T call
        // ticksAndAnnotations again - it's unnecessary and would overwrite `updates`
        updateSubplots([0, 0, pw, ph]);

        // since we may have been redrawing some things during the drag, we may have
        // accumulated MathJax promises - wait for them before we relayout.
        Lib.syncOrAsync([
            Plots.previousPromises,
            function() {
                gd._fullLayout._replotting = false;
                Registry.call('_guiRelayout', gd, updates);
            }
        ], gd);
    }

    // x/y scaleFactor stash,
    // minimizes number of per-point DOM updates in updateSubplots below
    var xScaleFactorOld, yScaleFactorOld;

    // updateSubplots - find all plot viewboxes that should be
    // affected by this drag, and update them. look for all plots
    // sharing an affected axis (including the one being dragged),
    // includes also scattergl and splom logic.
    function updateSubplots(viewBox) {
        var fullLayout = gd._fullLayout;
        var plotinfos = fullLayout._plots;
        var subplots = fullLayout._subplots.cartesian;
        var i, sp, xa, ya;

        if(hasSplom) {
            Registry.subplotsRegistry.splom.drag(gd);
        }

        if(hasScatterGl) {
            for(i = 0; i < subplots.length; i++) {
                sp = plotinfos[subplots[i]];
                xa = sp.xaxis;
                ya = sp.yaxis;

                if(sp._scene) {
                    var xrng = Lib.simpleMap(xa.range, xa.r2l);
                    var yrng = Lib.simpleMap(ya.range, ya.r2l);
                    sp._scene.update({range: [xrng[0], yrng[0], xrng[1], yrng[1]]});
                }
            }
        }

        if(hasSplom || hasScatterGl) {
            clearGlCanvases(gd);
            redrawReglTraces(gd);
        }

        if(hasSVG) {
            var xScaleFactor = viewBox[2] / xa0._length;
            var yScaleFactor = viewBox[3] / ya0._length;

            for(i = 0; i < subplots.length; i++) {
                sp = plotinfos[subplots[i]];
                xa = sp.xaxis;
                ya = sp.yaxis;

                var editX2 = editX && !xa.fixedrange && xaHash[xa._id];
                var editY2 = editY && !ya.fixedrange && yaHash[ya._id];

                var xScaleFactor2, yScaleFactor2;
                var clipDx, clipDy;

                if(editX2) {
                    xScaleFactor2 = xScaleFactor;
                    clipDx = ew ? viewBox[0] : getShift(xa, xScaleFactor2);
                } else {
                    xScaleFactor2 = getLinkedScaleFactor(xa, xScaleFactor, yScaleFactor);
                    clipDx = scaleAndGetShift(xa, xScaleFactor2);
                }

                if(editY2) {
                    yScaleFactor2 = yScaleFactor;
                    clipDy = ns ? viewBox[1] : getShift(ya, yScaleFactor2);
                } else {
                    yScaleFactor2 = getLinkedScaleFactor(ya, xScaleFactor, yScaleFactor);
                    clipDy = scaleAndGetShift(ya, yScaleFactor2);
                }

                // don't scale at all if neither axis is scalable here
                if(!xScaleFactor2 && !yScaleFactor2) {
                    continue;
                }

                // but if only one is, reset the other axis scaling
                if(!xScaleFactor2) xScaleFactor2 = 1;
                if(!yScaleFactor2) yScaleFactor2 = 1;

                var plotDx = xa._offset - clipDx / xScaleFactor2;
                var plotDy = ya._offset - clipDy / yScaleFactor2;

                // TODO could be more efficient here:
                // setTranslate and setScale do a lot of extra work
                // when working independently, should perhaps combine
                // them into a single routine.
                sp.clipRect
                    .call(Drawing.setTranslate, clipDx, clipDy)
                    .call(Drawing.setScale, xScaleFactor2, yScaleFactor2);

                sp.plot
                    .call(Drawing.setTranslate, plotDx, plotDy)
                    .call(Drawing.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2);

                // apply an inverse scale to individual points to counteract
                // the scale of the trace group.
                // apply only when scale changes, as adjusting the scale of
                // all the points can be expansive.
                if(xScaleFactor2 !== xScaleFactorOld || yScaleFactor2 !== yScaleFactorOld) {
                    Drawing.setPointGroupScale(sp.zoomScalePts, xScaleFactor2, yScaleFactor2);
                    Drawing.setTextPointsScale(sp.zoomScaleTxt, xScaleFactor2, yScaleFactor2);
                }

                Drawing.hideOutsideRangePoints(sp.clipOnAxisFalseTraces, sp);

                // update x/y scaleFactor stash
                xScaleFactorOld = xScaleFactor2;
                yScaleFactorOld = yScaleFactor2;
            }
        }
    }

    // Find the appropriate scaling for this axis, if it's linked to the
    // dragged axes by constraints. 0 is special, it means this axis shouldn't
    // ever be scaled (will be converted to 1 if the other axis is scaled)
    function getLinkedScaleFactor(ax, xScaleFactor, yScaleFactor) {
        if(ax.fixedrange) return 0;

        if(editX && links.xaHash[ax._id]) {
            return xScaleFactor;
        }
        if(editY && (isSubplotConstrained ? links.xaHash : links.yaHash)[ax._id]) {
            return yScaleFactor;
        }
        return 0;
    }

    function scaleAndGetShift(ax, scaleFactor) {
        if(scaleFactor) {
            ax.range = ax._r.slice();
            scaleZoom(ax, scaleFactor);
            return getShift(ax, scaleFactor);
        }
        return 0;
    }

    function getShift(ax, scaleFactor) {
        return ax._length * (1 - scaleFactor) * FROM_TL[ax.constraintoward || 'middle'];
    }

    return dragger;
}

function makeDragger(plotinfo, nodeName, dragClass, cursor) {
    var dragger3 = Lib.ensureSingle(plotinfo.draglayer, nodeName, dragClass, function(s) {
        s.classed('drag', true)
            .style({fill: 'transparent', 'stroke-width': 0})
            .attr('data-subplot', plotinfo.id);
    });

    dragger3.call(setCursor, cursor);

    return dragger3.node();
}

function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) {
    var dragger = makeDragger(plotinfo, 'rect', dragClass, cursor);
    d3.select(dragger).call(Drawing.setRect, x, y, w, h);
    return dragger;
}

function isDirectionActive(axList, activeVal) {
    for(var i = 0; i < axList.length; i++) {
        if(!axList[i].fixedrange) return activeVal;
    }
    return '';
}

function getEndText(ax, end) {
    var initialVal = ax.range[end];
    var diff = Math.abs(initialVal - ax.range[1 - end]);
    var dig;

    // TODO: this should basically be ax.r2d but we're doing extra
    // rounding here... can we clean up at all?
    if(ax.type === 'date') {
        return initialVal;
    }
    else if(ax.type === 'log') {
        dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3;
        return d3.format('.' + dig + 'g')(Math.pow(10, initialVal));
    }
    else { // linear numeric (or category... but just show numbers here)
        dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) -
            Math.floor(Math.log(diff) / Math.LN10) + 4;
        return d3.format('.' + String(dig) + 'g')(initialVal);
    }
}

function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) {
    var i,
        axi,
        axRangeLinear0,
        axRangeLinearSpan;

    for(i = 0; i < axList.length; i++) {
        axi = axList[i];
        if(axi.fixedrange) continue;

        axRangeLinear0 = axi._rl[0];
        axRangeLinearSpan = axi._rl[1] - axRangeLinear0;
        axi.range = [
            axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction),
            axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction)
        ];

        updates[axi._name + '.range[0]'] = axi.range[0];
        updates[axi._name + '.range[1]'] = axi.range[1];
    }

    // zoom linked axes about their centers
    if(linkedAxes && linkedAxes.length) {
        var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2;

        zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates);
    }
}

function dragAxList(axList, pix) {
    for(var i = 0; i < axList.length; i++) {
        var axi = axList[i];
        if(!axi.fixedrange) {
            axi.range = [
                axi.l2r(axi._rl[0] - pix / axi._m),
                axi.l2r(axi._rl[1] - pix / axi._m)
            ];
        }
    }
}

// common transform for dragging one end of an axis
// d>0 is compressing scale (cursor is over the plot,
//  the axis end should move with the cursor)
// d<0 is expanding (cursor is off the plot, axis end moves
//  nonlinearly so you can expand far)
function dZoom(d) {
    return 1 - ((d >= 0) ? Math.min(d, 0.9) :
        1 / (1 / Math.max(d, -0.3) + 3.222));
}

function getDragCursor(nsew, dragmode, isMainDrag) {
    if(!nsew) return 'pointer';
    if(nsew === 'nsew') {
        // in this case here, clear cursor and
        // use the cursor style set on <g .draglayer>
        if(isMainDrag) return '';
        if(dragmode === 'pan') return 'move';
        return 'crosshair';
    }
    return nsew.toLowerCase() + '-resize';
}

function makeZoombox(zoomlayer, lum, xs, ys, path0) {
    return zoomlayer.append('path')
        .attr('class', 'zoombox')
        .style({
            'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)',
            'stroke-width': 0
        })
        .attr('transform', 'translate(' + xs + ', ' + ys + ')')
        .attr('d', path0 + 'Z');
}

function makeCorners(zoomlayer, xs, ys) {
    return zoomlayer.append('path')
        .attr('class', 'zoombox-corners')
        .style({
            fill: Color.background,
            stroke: Color.defaultLine,
            'stroke-width': 1,
            opacity: 0
        })
        .attr('transform', 'translate(' + xs + ', ' + ys + ')')
        .attr('d', 'M0,0Z');
}

function updateZoombox(zb, corners, box, path0, dimmed, lum) {
    zb.attr('d',
        path0 + 'M' + (box.l) + ',' + (box.t) + 'v' + (box.h) +
        'h' + (box.w) + 'v-' + (box.h) + 'h-' + (box.w) + 'Z');
    transitionZoombox(zb, corners, dimmed, lum);
}

function transitionZoombox(zb, corners, dimmed, lum) {
    if(!dimmed) {
        zb.transition()
            .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' :
                'rgba(255,255,255,0.3)')
            .duration(200);
        corners.transition()
            .style('opacity', 1)
            .duration(200);
    }
}

function removeZoombox(gd) {
    d3.select(gd)
        .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners')
        .remove();
}

function showDoubleClickNotifier(gd) {
    if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) {
        Lib.notifier(Lib._(gd, 'Double-click to zoom back out'), 'long');
        SHOWZOOMOUTTIP = false;
    }
}

function isSelectOrLasso(dragmode) {
    return dragmode === 'lasso' || dragmode === 'select';
}

function xCorners(box, y0) {
    return 'M' +
        (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) +
        'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' +
        (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) +
        'h3v' + (2 * MINZOOM + 1) + 'h-3Z';
}

function yCorners(box, x0) {
    return 'M' +
        (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) +
        'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' +
        (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) +
        'v3h' + (2 * MINZOOM + 1) + 'v-3Z';
}

function xyCorners(box) {
    var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2);
    return 'M' +
        (box.l - 3.5) + ',' + (box.t - 0.5 + clen) + 'h3v' + (-clen) +
            'h' + clen + 'v-3h-' + (clen + 3) + 'ZM' +
        (box.r + 3.5) + ',' + (box.t - 0.5 + clen) + 'h-3v' + (-clen) +
            'h' + (-clen) + 'v-3h' + (clen + 3) + 'ZM' +
        (box.r + 3.5) + ',' + (box.b + 0.5 - clen) + 'h-3v' + clen +
            'h' + (-clen) + 'v3h' + (clen + 3) + 'ZM' +
        (box.l - 3.5) + ',' + (box.b + 0.5 - clen) + 'h3v' + clen +
            'h' + clen + 'v3h-' + (clen + 3) + 'Z';
}

function calcLinks(gd, xaHash, yaHash) {
    var constraintGroups = gd._fullLayout._axisConstraintGroups;
    var isSubplotConstrained = false;
    var xLinks = {};
    var yLinks = {};
    var xID, yID, xLinkID, yLinkID;

    for(var i = 0; i < constraintGroups.length; i++) {
        var group = constraintGroups[i];
        // check if any of the x axes we're dragging is in this constraint group
        for(xID in xaHash) {
            if(group[xID]) {
                // put the rest of these axes into xLinks, if we're not already
                // dragging them, so we know to scale these axes automatically too
                // to match the changes in the dragged x axes
                for(xLinkID in group) {
                    if(!(xLinkID.charAt(0) === 'x' ? xaHash : yaHash)[xLinkID]) {
                        xLinks[xLinkID] = 1;
                    }
                }

                // check if the x and y axes of THIS drag are linked
                for(yID in yaHash) {
                    if(group[yID]) isSubplotConstrained = true;
                }
            }
        }

        // now check if any of the y axes we're dragging is in this constraint group
        // only look for outside links, as we've already checked for links within the dragger
        for(yID in yaHash) {
            if(group[yID]) {
                for(yLinkID in group) {
                    if(!(yLinkID.charAt(0) === 'x' ? xaHash : yaHash)[yLinkID]) {
                        yLinks[yLinkID] = 1;
                    }
                }
            }
        }
    }

    if(isSubplotConstrained) {
        // merge xLinks and yLinks if the subplot is constrained,
        // since we'll always apply both anyway and the two will contain
        // duplicates
        Lib.extendFlat(xLinks, yLinks);
        yLinks = {};
    }

    var xaHashLinked = {};
    var xaxesLinked = [];
    for(xLinkID in xLinks) {
        var xa = getFromId(gd, xLinkID);
        xaxesLinked.push(xa);
        xaHashLinked[xa._id] = xa;
    }

    var yaHashLinked = {};
    var yaxesLinked = [];
    for(yLinkID in yLinks) {
        var ya = getFromId(gd, yLinkID);
        yaxesLinked.push(ya);
        yaHashLinked[ya._id] = ya;
    }

    return {
        xaHash: xaHashLinked,
        yaHash: yaHashLinked,
        xaxes: xaxesLinked,
        yaxes: yaxesLinked,
        isSubplotConstrained: isSubplotConstrained
    };
}

// still seems to be some confusion about onwheel vs onmousewheel...
function attachWheelEventHandler(element, handler) {
    if(!supportsPassive) {
        if(element.onwheel !== undefined) element.onwheel = handler;
        else if(element.onmousewheel !== undefined) element.onmousewheel = handler;
    }
    else {
        var wheelEventName = element.onwheel !== undefined ? 'wheel' : 'mousewheel';

        if(element._onwheel) {
            element.removeEventListener(wheelEventName, element._onwheel);
        }
        element._onwheel = handler;

        element.addEventListener(wheelEventName, handler, {passive: false});
    }
}

function hashValues(hash) {
    var out = [];
    for(var k in hash) out.push(hash[k]);
    return out;
}

module.exports = {
    makeDragBox: makeDragBox,

    makeDragger: makeDragger,
    makeRectDragger: makeRectDragger,
    makeZoombox: makeZoombox,
    makeCorners: makeCorners,

    updateZoombox: updateZoombox,
    xyCorners: xyCorners,
    transitionZoombox: transitionZoombox,
    removeZoombox: removeZoombox,
    showDoubleClickNotifier: showDoubleClickNotifier,

    attachWheelEventHandler: attachWheelEventHandler
};

},{"../../components/color":571,"../../components/dragelement":589,"../../components/drawing":592,"../../components/fx":610,"../../constants/alignment":666,"../../lib":694,"../../lib/clear_gl_canvases":679,"../../lib/setcursor":714,"../../lib/svg_text_utils":718,"../../plot_api/subroutines":733,"../../registry":825,"../plots":806,"./axes":742,"./axis_ids":745,"./constants":748,"./scale_zoom":759,"./select":760,"d3":149,"has-passive-events":397,"tinycolor2":515}],752:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

var Fx = _dereq_('../../components/fx');
var dragElement = _dereq_('../../components/dragelement');
var setCursor = _dereq_('../../lib/setcursor');

var makeDragBox = _dereq_('./dragbox').makeDragBox;
var DRAGGERSIZE = _dereq_('./constants').DRAGGERSIZE;

exports.initInteractions = function initInteractions(gd) {
    var fullLayout = gd._fullLayout;

    if(gd._context.staticPlot) {
        // this sweeps up more than just cartesian drag elements...
        d3.select(gd).selectAll('.drag').remove();
        return;
    }

    if(!fullLayout._has('cartesian') && !fullLayout._has('splom')) return;

    var subplots = Object.keys(fullLayout._plots || {}).sort(function(a, b) {
        // sort overlays last, then by x axis number, then y axis number
        if((fullLayout._plots[a].mainplot && true) ===
            (fullLayout._plots[b].mainplot && true)) {
            var aParts = a.split('y');
            var bParts = b.split('y');
            return (aParts[0] === bParts[0]) ?
                (Number(aParts[1] || 1) - Number(bParts[1] || 1)) :
                (Number(aParts[0] || 1) - Number(bParts[0] || 1));
        }
        return fullLayout._plots[a].mainplot ? 1 : -1;
    });

    subplots.forEach(function(subplot) {
        var plotinfo = fullLayout._plots[subplot];
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;

        // main and corner draggers need not be repeated for
        // overlaid subplots - these draggers drag them all
        if(!plotinfo.mainplot) {
            // main dragger goes over the grids and data, so we use its
            // mousemove events for all data hover effects
            var maindrag = makeDragBox(gd, plotinfo, xa._offset, ya._offset,
                xa._length, ya._length, 'ns', 'ew');

            maindrag.onmousemove = function(evt) {
                // This is on `gd._fullLayout`, *not* fullLayout because the reference
                // changes by the time this is called again.
                gd._fullLayout._rehover = function() {
                    if(gd._fullLayout._hoversubplot === subplot) {
                        Fx.hover(gd, evt, subplot);
                    }
                };

                Fx.hover(gd, evt, subplot);

                // Note that we have *not* used the cached fullLayout variable here
                // since that may be outdated when this is called as a callback later on
                gd._fullLayout._lasthover = maindrag;
                gd._fullLayout._hoversubplot = subplot;
            };

            /*
             * IMPORTANT:
             * We must check for the presence of the drag cover here.
             * If we don't, a 'mouseout' event is triggered on the
             * maindrag before each 'click' event, which has the effect
             * of clearing the hoverdata; thus, cancelling the click event.
             */
            maindrag.onmouseout = function(evt) {
                if(gd._dragging) return;

                // When the mouse leaves this maindrag, unset the hovered subplot.
                // This may cause problems if it leaves the subplot directly *onto*
                // another subplot, but that's a tiny corner case at the moment.
                gd._fullLayout._hoversubplot = null;

                dragElement.unhover(gd, evt);
            };

            // corner draggers
            if(gd._context.showAxisDragHandles) {
                makeDragBox(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE,
                    DRAGGERSIZE, DRAGGERSIZE, 'n', 'w');
                makeDragBox(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE,
                    DRAGGERSIZE, DRAGGERSIZE, 'n', 'e');
                makeDragBox(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length,
                    DRAGGERSIZE, DRAGGERSIZE, 's', 'w');
                makeDragBox(gd, plotinfo, xa._offset + xa._length, ya._offset + ya._length,
                    DRAGGERSIZE, DRAGGERSIZE, 's', 'e');
            }
        }
        if(gd._context.showAxisDragHandles) {
            // x axis draggers - if you have overlaid plots,
            // these drag each axis separately
            if(subplot === xa._mainSubplot) {
                // the y position of the main x axis line
                var y0 = xa._mainLinePosition;
                if(xa.side === 'top') y0 -= DRAGGERSIZE;
                makeDragBox(gd, plotinfo, xa._offset + xa._length * 0.1, y0,
                    xa._length * 0.8, DRAGGERSIZE, '', 'ew');
                makeDragBox(gd, plotinfo, xa._offset, y0,
                    xa._length * 0.1, DRAGGERSIZE, '', 'w');
                makeDragBox(gd, plotinfo, xa._offset + xa._length * 0.9, y0,
                    xa._length * 0.1, DRAGGERSIZE, '', 'e');
            }
            // y axis draggers
            if(subplot === ya._mainSubplot) {
                // the x position of the main y axis line
                var x0 = ya._mainLinePosition;
                if(ya.side !== 'right') x0 -= DRAGGERSIZE;
                makeDragBox(gd, plotinfo, x0, ya._offset + ya._length * 0.1,
                    DRAGGERSIZE, ya._length * 0.8, 'ns', '');
                makeDragBox(gd, plotinfo, x0, ya._offset + ya._length * 0.9,
                    DRAGGERSIZE, ya._length * 0.1, 's', '');
                makeDragBox(gd, plotinfo, x0, ya._offset,
                    DRAGGERSIZE, ya._length * 0.1, 'n', '');
            }
        }
    });

    // In case you mousemove over some hovertext, send it to Fx.hover too
    // we do this so that we can put the hover text in front of everything,
    // but still be able to interact with everything as if it isn't there
    var hoverLayer = fullLayout._hoverlayer.node();

    hoverLayer.onmousemove = function(evt) {
        evt.target = gd._fullLayout._lasthover;
        Fx.hover(gd, evt, fullLayout._hoversubplot);
    };

    hoverLayer.onclick = function(evt) {
        evt.target = gd._fullLayout._lasthover;
        Fx.click(gd, evt);
    };

    // also delegate mousedowns... TODO: does this actually work?
    hoverLayer.onmousedown = function(evt) {
        gd._fullLayout._lasthover.onmousedown(evt);
    };

    exports.updateFx(gd);
};

// Minimal set of update needed on 'modebar' edits.
// We only need to update the <g .draglayer> cursor style.
//
// Note that changing the axis configuration and/or the fixedrange attribute
// should trigger a full initInteractions.
exports.updateFx = function(gd) {
    var fullLayout = gd._fullLayout;
    var cursor = fullLayout.dragmode === 'pan' ? 'move' : 'crosshair';
    setCursor(fullLayout._draggers, cursor);
};

},{"../../components/dragelement":589,"../../components/fx":610,"../../lib/setcursor":714,"./constants":748,"./dragbox":751,"d3":149}],753:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');

/**
 * Factory function for checking component arrays for subplot references.
 *
 * @param {string} containerArrayName: the top-level array in gd.layout to check
 *   If an item in this container is found that references a cartesian x and/or y axis,
 *   ensure cartesian is marked as a base plot module and record the axes (and subplot
 *   if both refs are axes) in gd._fullLayout
 *
 * @return {function}: with args layoutIn (gd.layout) and layoutOut (gd._fullLayout)
 * as expected of a component includeBasePlot method
 */
module.exports = function makeIncludeComponents(containerArrayName) {
    return function includeComponents(layoutIn, layoutOut) {
        var array = layoutIn[containerArrayName];
        if(!Array.isArray(array)) return;

        var Cartesian = Registry.subplotsRegistry.cartesian;
        var idRegex = Cartesian.idRegex;
        var subplots = layoutOut._subplots;
        var xaList = subplots.xaxis;
        var yaList = subplots.yaxis;
        var cartesianList = subplots.cartesian;
        var hasCartesianOrGL2D = layoutOut._has('cartesian') || layoutOut._has('gl2d');

        for(var i = 0; i < array.length; i++) {
            var itemi = array[i];
            if(!Lib.isPlainObject(itemi)) continue;

            var xref = itemi.xref;
            var yref = itemi.yref;

            var hasXref = idRegex.x.test(xref);
            var hasYref = idRegex.y.test(yref);
            if(hasXref || hasYref) {
                if(!hasCartesianOrGL2D) Lib.pushUnique(layoutOut._basePlotModules, Cartesian);

                var newAxis = false;
                if(hasXref && xaList.indexOf(xref) === -1) {
                    xaList.push(xref);
                    newAxis = true;
                }
                if(hasYref && yaList.indexOf(yref) === -1) {
                    yaList.push(yref);
                    newAxis = true;
                }

                /*
                 * Notice the logic here: only add a subplot for a component if
                 * it's referencing both x and y axes AND it's creating a new axis
                 * so for example if your plot already has xy and x2y2, an annotation
                 * on x2y or xy2 will not create a new subplot.
                 */
                if(newAxis && hasXref && hasYref) {
                    cartesianList.push(xref + yref);
                }
            }
        }
    };
};

},{"../../lib":694,"../../registry":825}],754:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Plots = _dereq_('../plots');
var Drawing = _dereq_('../../components/drawing');

var getModuleCalcData = _dereq_('../get_data').getModuleCalcData;
var axisIds = _dereq_('./axis_ids');
var constants = _dereq_('./constants');
var xmlnsNamespaces = _dereq_('../../constants/xmlns_namespaces');

var ensureSingle = Lib.ensureSingle;

function ensureSingleAndAddDatum(parent, nodeType, className) {
    return Lib.ensureSingle(parent, nodeType, className, function(s) {
        s.datum(className);
    });
}

exports.name = 'cartesian';

exports.attr = ['xaxis', 'yaxis'];

exports.idRoot = ['x', 'y'];

exports.idRegex = constants.idRegex;

exports.attrRegex = constants.attrRegex;

exports.attributes = _dereq_('./attributes');

exports.layoutAttributes = _dereq_('./layout_attributes');

exports.supplyLayoutDefaults = _dereq_('./layout_defaults');

exports.transitionAxes = _dereq_('./transition_axes');

exports.finalizeSubplots = function(layoutIn, layoutOut) {
    var subplots = layoutOut._subplots;
    var xList = subplots.xaxis;
    var yList = subplots.yaxis;
    var spSVG = subplots.cartesian;
    var spAll = spSVG.concat(subplots.gl2d || []);
    var allX = {};
    var allY = {};
    var i, xi, yi;

    for(i = 0; i < spAll.length; i++) {
        var parts = spAll[i].split('y');
        allX[parts[0]] = 1;
        allY['y' + parts[1]] = 1;
    }

    // check for x axes with no subplot, and make one from the anchor of that x axis
    for(i = 0; i < xList.length; i++) {
        xi = xList[i];
        if(!allX[xi]) {
            yi = (layoutIn[axisIds.id2name(xi)] || {}).anchor;
            if(!constants.idRegex.y.test(yi)) yi = 'y';
            spSVG.push(xi + yi);
            spAll.push(xi + yi);

            if(!allY[yi]) {
                allY[yi] = 1;
                Lib.pushUnique(yList, yi);
            }
        }
    }

    // same for y axes with no subplot
    for(i = 0; i < yList.length; i++) {
        yi = yList[i];
        if(!allY[yi]) {
            xi = (layoutIn[axisIds.id2name(yi)] || {}).anchor;
            if(!constants.idRegex.x.test(xi)) xi = 'x';
            spSVG.push(xi + yi);
            spAll.push(xi + yi);

            if(!allX[xi]) {
                allX[xi] = 1;
                Lib.pushUnique(xList, xi);
            }
        }
    }

    // finally, if we've gotten here we're supposed to show cartesian...
    // so if there are NO subplots at all, make one from the first
    // x & y axes in the input layout
    if(!spAll.length) {
        xi = '';
        yi = '';
        for(var ki in layoutIn) {
            if(constants.attrRegex.test(ki)) {
                var axLetter = ki.charAt(0);
                if(axLetter === 'x') {
                    if(!xi || (+ki.substr(5) < +xi.substr(5))) {
                        xi = ki;
                    }
                }
                else if(!yi || (+ki.substr(5) < +yi.substr(5))) {
                    yi = ki;
                }
            }
        }
        xi = xi ? axisIds.name2id(xi) : 'x';
        yi = yi ? axisIds.name2id(yi) : 'y';
        xList.push(xi);
        yList.push(yi);
        spSVG.push(xi + yi);
    }
};

/**
 * Cartesian.plot
 *
 * @param {DOM div | object} gd
 * @param {array | null} (optional) traces
 *  array of traces indices to plot
 *  if undefined, plots all cartesian traces,
 *  if null, plots no traces
 * @param {object} (optional) transitionOpts
 *  transition option object
 * @param {function} (optional) makeOnCompleteCallback
 *  transition make callback function from Plots.transition
 */
exports.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) {
    var fullLayout = gd._fullLayout;
    var subplots = fullLayout._subplots.cartesian;
    var calcdata = gd.calcdata;
    var i;

    if(traces === null) {
        // this means no updates required, must return here
        // so that plotOne doesn't remove the trace layers
        return;
    } else if(!Array.isArray(traces)) {
        // If traces is not provided, then it's a complete replot and missing
        // traces are removed
        traces = [];
        for(i = 0; i < calcdata.length; i++) traces.push(i);
    }

    for(i = 0; i < subplots.length; i++) {
        var subplot = subplots[i];
        var subplotInfo = fullLayout._plots[subplot];

        // Get all calcdata for this subplot:
        var cdSubplot = [];
        var pcd;

        for(var j = 0; j < calcdata.length; j++) {
            var cd = calcdata[j];
            var trace = cd[0].trace;

            // Skip trace if whitelist provided and it's not whitelisted:
            // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue;
            if(trace.xaxis + trace.yaxis === subplot) {
                // XXX: Should trace carpet dependencies. Only replot all carpet plots if the carpet
                // axis has actually changed:
                //
                // If this trace is specifically requested, add it to the list:
                if(traces.indexOf(trace.index) !== -1 || trace.carpet) {
                    // Okay, so example: traces 0, 1, and 2 have fill = tonext. You animate
                    // traces 0 and 2. Trace 1 also needs to be updated, otherwise its fill
                    // is outdated. So this retroactively adds the previous trace if the
                    // traces are interdependent.
                    if(
                        pcd &&
                        pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot &&
                        ['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1 &&
                        cdSubplot.indexOf(pcd) === -1
                    ) {
                        cdSubplot.push(pcd);
                    }

                    cdSubplot.push(cd);
                }

                // Track the previous trace on this subplot for the retroactive-add step
                // above:
                pcd = cd;
            }
        }

        plotOne(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback);
    }
};

function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) {
    var traceLayerClasses = constants.traceLayerClasses;
    var fullLayout = gd._fullLayout;
    var modules = fullLayout._modules;
    var _module, cdModuleAndOthers, cdModule;

    var layerData = [];
    var zoomScaleQueryParts = [];

    for(var i = 0; i < modules.length; i++) {
        _module = modules[i];
        var name = _module.name;
        var categories = Registry.modules[name].categories;

        if(categories.svg) {
            var className = (_module.layerName || name + 'layer');
            var plotMethod = _module.plot;

            // plot all visible traces of this type on this subplot at once
            cdModuleAndOthers = getModuleCalcData(cdSubplot, plotMethod);
            cdModule = cdModuleAndOthers[0];
            // don't need to search the found traces again - in fact we need to NOT
            // so that if two modules share the same plotter we don't double-plot
            cdSubplot = cdModuleAndOthers[1];

            if(cdModule.length) {
                layerData.push({
                    i: traceLayerClasses.indexOf(className),
                    className: className,
                    plotMethod: plotMethod,
                    cdModule: cdModule
                });
            }

            if(categories.zoomScale) {
                zoomScaleQueryParts.push('.' + className);
            }
        }
    }

    layerData.sort(function(a, b) { return a.i - b.i; });

    var layers = plotinfo.plot.selectAll('g.mlayer')
        .data(layerData, function(d) { return d.className; });

    layers.enter().append('g')
        .attr('class', function(d) { return d.className; })
        .classed('mlayer', true);

    layers.exit().remove();

    layers.order();

    layers.each(function(d) {
        var sel = d3.select(this);
        var className = d.className;

        d.plotMethod(
            gd, plotinfo, d.cdModule, sel,
            transitionOpts, makeOnCompleteCallback
        );

        // layers that allow `cliponaxis: false`
        if(className !== 'scatterlayer' && className !== 'barlayer') {
            Drawing.setClipUrl(sel, plotinfo.layerClipId, gd);
        }
    });

    // call Scattergl.plot separately
    if(fullLayout._has('scattergl')) {
        _module = Registry.getModule('scattergl');
        cdModule = getModuleCalcData(cdSubplot, _module)[0];
        _module.plot(gd, plotinfo, cdModule);
    }

    // stash "hot" selections for faster interaction on drag and scroll
    if(!gd._context.staticPlot) {
        if(plotinfo._hasClipOnAxisFalse) {
            plotinfo.clipOnAxisFalseTraces = plotinfo.plot
                .selectAll('.scatterlayer, .barlayer')
                .selectAll('.trace');
        }

        if(zoomScaleQueryParts.length) {
            var traces = plotinfo.plot
                .selectAll(zoomScaleQueryParts.join(','))
                .selectAll('.trace');

            plotinfo.zoomScalePts = traces.selectAll('path.point');
            plotinfo.zoomScaleTxt = traces.selectAll('.textpoint');
        }
    }
}

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var oldPlots = oldFullLayout._plots || {};
    var newPlots = newFullLayout._plots || {};
    var oldSubplotList = oldFullLayout._subplots || {};
    var plotinfo;
    var i, k;

    // when going from a large splom graph to something else,
    // we need to clear <g subplot> so that the new cartesian subplot
    // can have the correct layer ordering
    if(oldFullLayout._hasOnlyLargeSploms && !newFullLayout._hasOnlyLargeSploms) {
        for(k in oldPlots) {
            plotinfo = oldPlots[k];
            if(plotinfo.plotgroup) plotinfo.plotgroup.remove();
        }
    }

    var hadGl = (oldFullLayout._has && oldFullLayout._has('gl'));
    var hasGl = (newFullLayout._has && newFullLayout._has('gl'));

    if(hadGl && !hasGl) {
        for(k in oldPlots) {
            plotinfo = oldPlots[k];
            if(plotinfo._scene) plotinfo._scene.destroy();
        }
    }

    // delete any titles we don't need anymore
    // check if axis list has changed, and if so clear old titles
    if(oldSubplotList.xaxis && oldSubplotList.yaxis) {
        var oldAxIDs = axisIds.listIds({_fullLayout: oldFullLayout});
        for(i = 0; i < oldAxIDs.length; i++) {
            var oldAxId = oldAxIDs[i];
            if(!newFullLayout[axisIds.id2name(oldAxId)]) {
                oldFullLayout._infolayer.selectAll('.g-' + oldAxId + 'title').remove();
            }
        }
    }

    // if we've gotten rid of all cartesian traces, remove all the subplot svg items
    var hadCartesian = (oldFullLayout._has && oldFullLayout._has('cartesian'));
    var hasCartesian = (newFullLayout._has && newFullLayout._has('cartesian'));

    if(hadCartesian && !hasCartesian) {
        purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll('.subplot'), oldFullLayout);
        oldFullLayout._defs.selectAll('.axesclip').remove();
        delete oldFullLayout._axisConstraintGroups;
    }
    // otherwise look for subplots we need to remove
    else if(oldSubplotList.cartesian) {
        for(i = 0; i < oldSubplotList.cartesian.length; i++) {
            var oldSubplotId = oldSubplotList.cartesian[i];
            if(!newPlots[oldSubplotId]) {
                var selector = '.' + oldSubplotId + ',.' + oldSubplotId + '-x,.' + oldSubplotId + '-y';
                oldFullLayout._cartesianlayer.selectAll(selector).remove();
                removeSubplotExtras(oldSubplotId, oldFullLayout);
            }
        }
    }
};

exports.drawFramework = function(gd) {
    var fullLayout = gd._fullLayout;
    var subplotData = makeSubplotData(gd);

    var subplotLayers = fullLayout._cartesianlayer.selectAll('.subplot')
        .data(subplotData, String);

    subplotLayers.enter().append('g')
        .attr('class', function(d) { return 'subplot ' + d[0]; });

    subplotLayers.order();

    subplotLayers.exit()
        .call(purgeSubplotLayers, fullLayout);

    subplotLayers.each(function(d) {
        var id = d[0];
        var plotinfo = fullLayout._plots[id];

        plotinfo.plotgroup = d3.select(this);
        makeSubplotLayer(gd, plotinfo);

        // make separate drag layers for each subplot,
        // but append them to paper rather than the plot groups,
        // so they end up on top of the rest
        plotinfo.draglayer = ensureSingle(fullLayout._draggers, 'g', id);
    });
};

exports.rangePlot = function(gd, plotinfo, cdSubplot) {
    makeSubplotLayer(gd, plotinfo);
    plotOne(gd, plotinfo, cdSubplot);
    Plots.style(gd);
};

function makeSubplotData(gd) {
    var fullLayout = gd._fullLayout;
    var ids = fullLayout._subplots.cartesian;
    var len = ids.length;
    var i, j, id, plotinfo, xa, ya;

    // split 'regular' and 'overlaying' subplots
    var regulars = [];
    var overlays = [];

    for(i = 0; i < len; i++) {
        id = ids[i];
        plotinfo = fullLayout._plots[id];
        xa = plotinfo.xaxis;
        ya = plotinfo.yaxis;

        var xa2 = xa._mainAxis;
        var ya2 = ya._mainAxis;
        var mainplot = xa2._id + ya2._id;
        var mainplotinfo = fullLayout._plots[mainplot];
        plotinfo.overlays = [];

        if(mainplot !== id && mainplotinfo) {
            plotinfo.mainplot = mainplot;
            plotinfo.mainplotinfo = mainplotinfo;
            overlays.push(id);
        } else {
            plotinfo.mainplot = undefined;
            plotinfo.mainPlotinfo = undefined;
            regulars.push(id);
        }
    }

    // fill in list of overlaying subplots in 'main plot'
    for(i = 0; i < overlays.length; i++) {
        id = overlays[i];
        plotinfo = fullLayout._plots[id];
        plotinfo.mainplotinfo.overlays.push(plotinfo);
    }

    // put 'regular' subplot data before 'overlaying'
    var subplotIds = regulars.concat(overlays);
    var subplotData = new Array(len);

    for(i = 0; i < len; i++) {
        id = subplotIds[i];
        plotinfo = fullLayout._plots[id];
        xa = plotinfo.xaxis;
        ya = plotinfo.yaxis;

        // use info about axis layer and overlaying pattern
        // to clean what need to be cleaned up in exit selection
        var d = [id, xa.layer, ya.layer, xa.overlaying || '', ya.overlaying || ''];
        for(j = 0; j < plotinfo.overlays.length; j++) {
            d.push(plotinfo.overlays[j].id);
        }
        subplotData[i] = d;
    }

    return subplotData;
}

function makeSubplotLayer(gd, plotinfo) {
    var plotgroup = plotinfo.plotgroup;
    var id = plotinfo.id;
    var xLayer = constants.layerValue2layerClass[plotinfo.xaxis.layer];
    var yLayer = constants.layerValue2layerClass[plotinfo.yaxis.layer];
    var hasOnlyLargeSploms = gd._fullLayout._hasOnlyLargeSploms;

    if(!plotinfo.mainplot) {
        if(hasOnlyLargeSploms) {
            // TODO could do even better
            // - we don't need plot (but we would have to mock it in lsInner
            //   and other places
            // - we don't (x|y)lines and (x|y)axislayer for most subplots
            //   usually just the bottom x and left y axes.
            plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above');
            plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above');
            plotinfo.xaxislayer = ensureSingle(plotgroup, 'g', 'xaxislayer-above');
            plotinfo.yaxislayer = ensureSingle(plotgroup, 'g', 'yaxislayer-above');
        }
        else {
            var backLayer = ensureSingle(plotgroup, 'g', 'layer-subplot');
            plotinfo.shapelayer = ensureSingle(backLayer, 'g', 'shapelayer');
            plotinfo.imagelayer = ensureSingle(backLayer, 'g', 'imagelayer');

            plotinfo.gridlayer = ensureSingle(plotgroup, 'g', 'gridlayer');
            plotinfo.zerolinelayer = ensureSingle(plotgroup, 'g', 'zerolinelayer');

            ensureSingle(plotgroup, 'path', 'xlines-below');
            ensureSingle(plotgroup, 'path', 'ylines-below');
            plotinfo.overlinesBelow = ensureSingle(plotgroup, 'g', 'overlines-below');

            ensureSingle(plotgroup, 'g', 'xaxislayer-below');
            ensureSingle(plotgroup, 'g', 'yaxislayer-below');
            plotinfo.overaxesBelow = ensureSingle(plotgroup, 'g', 'overaxes-below');

            plotinfo.plot = ensureSingle(plotgroup, 'g', 'plot');
            plotinfo.overplot = ensureSingle(plotgroup, 'g', 'overplot');

            plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above');
            plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above');
            plotinfo.overlinesAbove = ensureSingle(plotgroup, 'g', 'overlines-above');

            ensureSingle(plotgroup, 'g', 'xaxislayer-above');
            ensureSingle(plotgroup, 'g', 'yaxislayer-above');
            plotinfo.overaxesAbove = ensureSingle(plotgroup, 'g', 'overaxes-above');

            // set refs to correct layers as determined by 'axis.layer'
            plotinfo.xlines = plotgroup.select('.xlines-' + xLayer);
            plotinfo.ylines = plotgroup.select('.ylines-' + yLayer);
            plotinfo.xaxislayer = plotgroup.select('.xaxislayer-' + xLayer);
            plotinfo.yaxislayer = plotgroup.select('.yaxislayer-' + yLayer);
        }
    }
    else {
        var mainplotinfo = plotinfo.mainplotinfo;
        var mainplotgroup = mainplotinfo.plotgroup;
        var xId = id + '-x';
        var yId = id + '-y';

        // now make the components of overlaid subplots
        // overlays don't have backgrounds, and append all
        // their other components to the corresponding
        // extra groups of their main plots.

        plotinfo.gridlayer = mainplotinfo.gridlayer;
        plotinfo.zerolinelayer = mainplotinfo.zerolinelayer;

        ensureSingle(mainplotinfo.overlinesBelow, 'path', xId);
        ensureSingle(mainplotinfo.overlinesBelow, 'path', yId);
        ensureSingle(mainplotinfo.overaxesBelow, 'g', xId);
        ensureSingle(mainplotinfo.overaxesBelow, 'g', yId);

        plotinfo.plot = ensureSingle(mainplotinfo.overplot, 'g', id);

        ensureSingle(mainplotinfo.overlinesAbove, 'path', xId);
        ensureSingle(mainplotinfo.overlinesAbove, 'path', yId);
        ensureSingle(mainplotinfo.overaxesAbove, 'g', xId);
        ensureSingle(mainplotinfo.overaxesAbove, 'g', yId);

        // set refs to correct layers as determined by 'abovetraces'
        plotinfo.xlines = mainplotgroup.select('.overlines-' + xLayer).select('.' + xId);
        plotinfo.ylines = mainplotgroup.select('.overlines-' + yLayer).select('.' + yId);
        plotinfo.xaxislayer = mainplotgroup.select('.overaxes-' + xLayer).select('.' + xId);
        plotinfo.yaxislayer = mainplotgroup.select('.overaxes-' + yLayer).select('.' + yId);
    }

    // common attributes for all subplots, overlays or not

    if(!hasOnlyLargeSploms) {
        ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.xaxis._id);
        ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.yaxis._id);
        plotinfo.gridlayer.selectAll('g')
            .map(function(d) { return d[0]; })
            .sort(axisIds.idSort);
    }

    plotinfo.xlines
        .style('fill', 'none')
        .classed('crisp', true);

    plotinfo.ylines
        .style('fill', 'none')
        .classed('crisp', true);
}

function purgeSubplotLayers(layers, fullLayout) {
    if(!layers) return;

    var overlayIdsToRemove = {};

    layers.each(function(d) {
        var id = d[0];
        var plotgroup = d3.select(this);

        plotgroup.remove();
        removeSubplotExtras(id, fullLayout);
        overlayIdsToRemove[id] = true;

        // do not remove individual axis <clipPath>s here
        // as other subplots may need them
    });

    // must remove overlaid subplot trace layers 'manually'

    for(var k in fullLayout._plots) {
        var subplotInfo = fullLayout._plots[k];
        var overlays = subplotInfo.overlays || [];

        for(var j = 0; j < overlays.length; j++) {
            var overlayInfo = overlays[j];

            if(overlayIdsToRemove[overlayInfo.id]) {
                overlayInfo.plot.selectAll('.trace').remove();
            }
        }
    }
}

function removeSubplotExtras(subplotId, fullLayout) {
    fullLayout._draggers.selectAll('g.' + subplotId).remove();
    fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove();
}

exports.toSVG = function(gd) {
    var imageRoot = gd._fullLayout._glimages;
    var root = d3.select(gd).selectAll('.svg-container');
    var canvases = root.filter(function(d, i) {return i === root.size() - 1;})
        .selectAll('.gl-canvas-context, .gl-canvas-focus');

    function canvasToImage() {
        var canvas = this;
        var imageData = canvas.toDataURL('image/png');
        var image = imageRoot.append('svg:image');

        image.attr({
            xmlns: xmlnsNamespaces.svg,
            'xlink:href': imageData,
            preserveAspectRatio: 'none',
            x: 0,
            y: 0,
            width: canvas.width,
            height: canvas.height
        });
    }

    canvases.each(canvasToImage);
};

exports.updateFx = _dereq_('./graph_interact').updateFx;

},{"../../components/drawing":592,"../../constants/xmlns_namespaces":672,"../../lib":694,"../../registry":825,"../get_data":779,"../plots":806,"./attributes":740,"./axis_ids":745,"./constants":748,"./graph_interact":752,"./layout_attributes":755,"./layout_defaults":756,"./transition_axes":765,"d3":149}],755:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = _dereq_('../font_attributes');
var colorAttrs = _dereq_('../../components/color/attributes');
var dash = _dereq_('../../components/drawing/attributes').dash;
var extendFlat = _dereq_('../../lib/extend').extendFlat;
var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;

var constants = _dereq_('./constants');


module.exports = {
    visible: {
        valType: 'boolean',
        
        editType: 'plot',
        
    },
    color: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'ticks',
        
    },
    title: {
        text: {
            valType: 'string',
            
            editType: 'ticks',
            
        },
        font: fontAttrs({
            editType: 'ticks',
            
        }),
        editType: 'ticks'
    },
    type: {
        valType: 'enumerated',
        // '-' means we haven't yet run autotype or couldn't find any data
        // it gets turned into linear in gd._fullLayout but not copied back
        // to gd.data like the others are.
        values: ['-', 'linear', 'log', 'date', 'category', 'multicategory'],
        dflt: '-',
        
        editType: 'calc',
        // we forget when an axis has been autotyped, just writing the auto
        // value back to the input - so it doesn't make sense to template this.
        // Note: we do NOT prohibit this in `coerce`, so if someone enters a
        // type in the template explicitly it will be honored as the default.
        _noTemplating: true,
        
    },
    autorange: {
        valType: 'enumerated',
        values: [true, false, 'reversed'],
        dflt: true,
        
        editType: 'axrange',
        impliedEdits: {'range[0]': undefined, 'range[1]': undefined},
        
    },
    rangemode: {
        valType: 'enumerated',
        values: ['normal', 'tozero', 'nonnegative'],
        dflt: 'normal',
        
        editType: 'plot',
        
    },
    range: {
        valType: 'info_array',
        
        items: [
            {valType: 'any', editType: 'axrange', impliedEdits: {'^autorange': false}, anim: true},
            {valType: 'any', editType: 'axrange', impliedEdits: {'^autorange': false}, anim: true}
        ],
        editType: 'axrange',
        impliedEdits: {'autorange': false},
        anim: true,
        
    },
    fixedrange: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'calc',
        
    },
    // scaleanchor: not used directly, just put here for reference
    // values are any opposite-letter axis id
    scaleanchor: {
        valType: 'enumerated',
        values: [
            constants.idRegex.x.toString(),
            constants.idRegex.y.toString()
        ],
        
        editType: 'plot',
        
    },
    scaleratio: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'plot',
        
    },
    constrain: {
        valType: 'enumerated',
        values: ['range', 'domain'],
        dflt: 'range',
        
        editType: 'plot',
        
    },
    // constraintoward: not used directly, just put here for reference
    constraintoward: {
        valType: 'enumerated',
        values: ['left', 'center', 'right', 'top', 'middle', 'bottom'],
        
        editType: 'plot',
        
    },
    // ticks
    tickmode: {
        valType: 'enumerated',
        values: ['auto', 'linear', 'array'],
        
        editType: 'ticks',
        impliedEdits: {tick0: undefined, dtick: undefined},
        
    },
    nticks: {
        valType: 'integer',
        min: 0,
        dflt: 0,
        
        editType: 'ticks',
        
    },
    tick0: {
        valType: 'any',
        
        editType: 'ticks',
        impliedEdits: {tickmode: 'linear'},
        
    },
    dtick: {
        valType: 'any',
        
        editType: 'ticks',
        impliedEdits: {tickmode: 'linear'},
        
    },
    tickvals: {
        valType: 'data_array',
        editType: 'ticks',
        
    },
    ticktext: {
        valType: 'data_array',
        editType: 'ticks',
        
    },
    ticks: {
        valType: 'enumerated',
        values: ['outside', 'inside', ''],
        
        editType: 'ticks',
        
    },
    tickson: {
        valType: 'enumerated',
        values: ['labels', 'boundaries'],
        
        dflt: 'labels',
        editType: 'ticks',
        
    },
    mirror: {
        valType: 'enumerated',
        values: [true, 'ticks', false, 'all', 'allticks'],
        dflt: false,
        
        editType: 'ticks+layoutstyle',
        
    },
    ticklen: {
        valType: 'number',
        min: 0,
        dflt: 5,
        
        editType: 'ticks',
        
    },
    tickwidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'ticks',
        
    },
    tickcolor: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'ticks',
        
    },
    showticklabels: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'ticks',
        
    },
    automargin: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'ticks',
        
    },
    showspikes: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'modebar',
        
    },
    spikecolor: {
        valType: 'color',
        dflt: null,
        
        editType: 'none',
        
    },
    spikethickness: {
        valType: 'number',
        dflt: 3,
        
        editType: 'none',
        
    },
    spikedash: extendFlat({}, dash, {dflt: 'dash', editType: 'none'}),
    spikemode: {
        valType: 'flaglist',
        flags: ['toaxis', 'across', 'marker'],
        
        dflt: 'toaxis',
        editType: 'none',
        
    },
    spikesnap: {
        valType: 'enumerated',
        values: ['data', 'cursor'],
        dflt: 'data',
        
        editType: 'none',
        
    },
    tickfont: fontAttrs({
        editType: 'ticks',
        
    }),
    tickangle: {
        valType: 'angle',
        dflt: 'auto',
        
        editType: 'ticks',
        
    },
    tickprefix: {
        valType: 'string',
        dflt: '',
        
        editType: 'ticks',
        
    },
    showtickprefix: {
        valType: 'enumerated',
        values: ['all', 'first', 'last', 'none'],
        dflt: 'all',
        
        editType: 'ticks',
        
    },
    ticksuffix: {
        valType: 'string',
        dflt: '',
        
        editType: 'ticks',
        
    },
    showticksuffix: {
        valType: 'enumerated',
        values: ['all', 'first', 'last', 'none'],
        dflt: 'all',
        
        editType: 'ticks',
        
    },
    showexponent: {
        valType: 'enumerated',
        values: ['all', 'first', 'last', 'none'],
        dflt: 'all',
        
        editType: 'ticks',
        
    },
    exponentformat: {
        valType: 'enumerated',
        values: ['none', 'e', 'E', 'power', 'SI', 'B'],
        dflt: 'B',
        
        editType: 'ticks',
        
    },
    separatethousands: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'ticks',
        
    },
    tickformat: {
        valType: 'string',
        dflt: '',
        
        editType: 'ticks',
        
    },
    tickformatstops: templatedArray('tickformatstop', {
        enabled: {
            valType: 'boolean',
            
            dflt: true,
            editType: 'ticks',
            
        },
        dtickrange: {
            valType: 'info_array',
            
            items: [
                {valType: 'any', editType: 'ticks'},
                {valType: 'any', editType: 'ticks'}
            ],
            editType: 'ticks',
            
        },
        value: {
            valType: 'string',
            dflt: '',
            
            editType: 'ticks',
            
        },
        editType: 'ticks'
    }),
    hoverformat: {
        valType: 'string',
        dflt: '',
        
        editType: 'none',
        
    },
    // lines and grids
    showline: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'ticks+layoutstyle',
        
    },
    linecolor: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'layoutstyle',
        
    },
    linewidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'ticks+layoutstyle',
        
    },
    showgrid: {
        valType: 'boolean',
        
        editType: 'ticks',
        
    },
    gridcolor: {
        valType: 'color',
        dflt: colorAttrs.lightLine,
        
        editType: 'ticks',
        
    },
    gridwidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'ticks',
        
    },
    zeroline: {
        valType: 'boolean',
        
        editType: 'ticks',
        
    },
    zerolinecolor: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'ticks',
        
    },
    zerolinewidth: {
        valType: 'number',
        dflt: 1,
        
        editType: 'ticks',
        
    },

    showdividers: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'ticks',
        
    },
    dividercolor: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'ticks',
        
    },
    dividerwidth: {
        valType: 'number',
        dflt: 1,
        
        editType: 'ticks',
        
    },
    // TODO dividerlen: that would override "to label base" length?

    // positioning attributes
    // anchor: not used directly, just put here for reference
    // values are any opposite-letter axis id
    anchor: {
        valType: 'enumerated',
        values: [
            'free',
            constants.idRegex.x.toString(),
            constants.idRegex.y.toString()
        ],
        
        editType: 'plot',
        
    },
    // side: not used directly, as values depend on direction
    // values are top, bottom for x axes, and left, right for y
    side: {
        valType: 'enumerated',
        values: ['top', 'bottom', 'left', 'right'],
        
        editType: 'plot',
        
    },
    // overlaying: not used directly, just put here for reference
    // values are false and any other same-letter axis id that's not
    // itself overlaying anything
    overlaying: {
        valType: 'enumerated',
        values: [
            'free',
            constants.idRegex.x.toString(),
            constants.idRegex.y.toString()
        ],
        
        editType: 'plot',
        
    },
    layer: {
        valType: 'enumerated',
        values: ['above traces', 'below traces'],
        dflt: 'above traces',
        
        editType: 'plot',
        
    },
    domain: {
        valType: 'info_array',
        
        items: [
            {valType: 'number', min: 0, max: 1, editType: 'plot'},
            {valType: 'number', min: 0, max: 1, editType: 'plot'}
        ],
        dflt: [0, 1],
        editType: 'plot',
        
    },
    position: {
        valType: 'number',
        min: 0,
        max: 1,
        dflt: 0,
        
        editType: 'plot',
        
    },
    categoryorder: {
        valType: 'enumerated',
        values: [
            'trace', 'category ascending', 'category descending', 'array'
            /* , 'value ascending', 'value descending'*/ // value ascending / descending to be implemented later
        ],
        dflt: 'trace',
        
        editType: 'calc',
        
    },
    categoryarray: {
        valType: 'data_array',
        
        editType: 'calc',
        
    },
    uirevision: {
        valType: 'any',
        
        editType: 'none',
        
    },
    editType: 'calc',

    _deprecated: {
        autotick: {
            valType: 'boolean',
            
            editType: 'ticks',
            
        },
        title: {
            valType: 'string',
            
            editType: 'ticks',
            
        },
        titlefont: fontAttrs({
            editType: 'ticks',
            
        })
    }
};

},{"../../components/color/attributes":570,"../../components/drawing/attributes":591,"../../lib/extend":684,"../../plot_api/plot_template":732,"../font_attributes":769,"./constants":748}],756:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var Color = _dereq_('../../components/color');
var Template = _dereq_('../../plot_api/plot_template');
var basePlotLayoutAttributes = _dereq_('../layout_attributes');

var layoutAttributes = _dereq_('./layout_attributes');
var handleTypeDefaults = _dereq_('./type_defaults');
var handleAxisDefaults = _dereq_('./axis_defaults');
var handleConstraintDefaults = _dereq_('./constraint_defaults');
var handlePositionDefaults = _dereq_('./position_defaults');

var axisIds = _dereq_('./axis_ids');
var id2name = axisIds.id2name;
var name2id = axisIds.name2id;

var Registry = _dereq_('../../registry');
var traceIs = Registry.traceIs;
var getComponentMethod = Registry.getComponentMethod;

function appendList(cont, k, item) {
    if(Array.isArray(cont[k])) cont[k].push(item);
    else cont[k] = [item];
}

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
    var ax2traces = {};
    var xaCheater = {};
    var xaNonCheater = {};
    var outerTicks = {};
    var noGrids = {};
    var i, j;

    // look for axes in the data
    for(i = 0; i < fullData.length; i++) {
        var trace = fullData[i];
        if(!traceIs(trace, 'cartesian') && !traceIs(trace, 'gl2d')) continue;

        var xaName;
        if(trace.xaxis) {
            xaName = id2name(trace.xaxis);
            appendList(ax2traces, xaName, trace);
        } else if(trace.xaxes) {
            for(j = 0; j < trace.xaxes.length; j++) {
                appendList(ax2traces, id2name(trace.xaxes[j]), trace);
            }
        }

        var yaName;
        if(trace.yaxis) {
            yaName = id2name(trace.yaxis);
            appendList(ax2traces, yaName, trace);
        } else if(trace.yaxes) {
            for(j = 0; j < trace.yaxes.length; j++) {
                appendList(ax2traces, id2name(trace.yaxes[j]), trace);
            }
        }

        // Two things trigger axis visibility:
        // 1. is not carpet
        // 2. carpet that's not cheater
        if(!traceIs(trace, 'carpet') || (trace.type === 'carpet' && !trace._cheater)) {
            if(xaName) xaNonCheater[xaName] = 1;
        }

        // The above check for definitely-not-cheater is not adequate. This
        // second list tracks which axes *could* be a cheater so that the
        // full condition triggering hiding is:
        //   *could* be a cheater and *is not definitely visible*
        if(trace.type === 'carpet' && trace._cheater) {
            if(xaName) xaCheater[xaName] = 1;
        }

        // check for default formatting tweaks
        if(traceIs(trace, '2dMap')) {
            outerTicks[xaName] = 1;
            outerTicks[yaName] = 1;
        }

        if(traceIs(trace, 'oriented')) {
            var positionAxis = trace.orientation === 'h' ? yaName : xaName;
            noGrids[positionAxis] = 1;
        }
    }

    var subplots = layoutOut._subplots;
    var xIds = subplots.xaxis;
    var yIds = subplots.yaxis;
    var xNames = Lib.simpleMap(xIds, id2name);
    var yNames = Lib.simpleMap(yIds, id2name);
    var axNames = xNames.concat(yNames);

    // plot_bgcolor only makes sense if there's a (2D) plot!
    // TODO: bgcolor for each subplot, to inherit from the main one
    var plotBgColor = Color.background;
    if(xIds.length && yIds.length) {
        plotBgColor = Lib.coerce(layoutIn, layoutOut, basePlotLayoutAttributes, 'plot_bgcolor');
    }

    var bgColor = Color.combine(plotBgColor, layoutOut.paper_bgcolor);

    var axName, axLetter, axLayoutIn, axLayoutOut;

    function coerce(attr, dflt) {
        return Lib.coerce(axLayoutIn, axLayoutOut, layoutAttributes, attr, dflt);
    }

    function coerce2(attr, dflt) {
        return Lib.coerce2(axLayoutIn, axLayoutOut, layoutAttributes, attr, dflt);
    }

    function getCounterAxes(axLetter) {
        return (axLetter === 'x') ? yIds : xIds;
    }

    var counterAxes = {x: getCounterAxes('x'), y: getCounterAxes('y')};

    function getOverlayableAxes(axLetter, axName) {
        var list = (axLetter === 'x') ? xNames : yNames;
        var out = [];

        for(var j = 0; j < list.length; j++) {
            var axName2 = list[j];

            if(axName2 !== axName && !(layoutIn[axName2] || {}).overlaying) {
                out.push(name2id(axName2));
            }
        }

        return out;
    }

    // first pass creates the containers, determines types, and handles most of the settings
    for(i = 0; i < axNames.length; i++) {
        axName = axNames[i];
        axLetter = axName.charAt(0);

        if(!Lib.isPlainObject(layoutIn[axName])) {
            layoutIn[axName] = {};
        }

        axLayoutIn = layoutIn[axName];
        axLayoutOut = Template.newContainer(layoutOut, axName, axLetter + 'axis');

        var traces = ax2traces[axName] || [];
        axLayoutOut._traceIndices = traces.map(function(t) { return t._expandedIndex; });
        axLayoutOut._annIndices = [];
        axLayoutOut._shapeIndices = [];
        axLayoutOut._imgIndices = [];
        axLayoutOut._subplotsWith = [];
        axLayoutOut._counterAxes = [];

        // set up some private properties
        axLayoutOut._name = axLayoutOut._attr = axName;
        var id = axLayoutOut._id = name2id(axName);

        var overlayableAxes = getOverlayableAxes(axLetter, axName);

        var defaultOptions = {
            letter: axLetter,
            font: layoutOut.font,
            outerTicks: outerTicks[axName],
            showGrid: !noGrids[axName],
            data: traces,
            bgColor: bgColor,
            calendar: layoutOut.calendar,
            automargin: true,
            cheateronly: axLetter === 'x' && xaCheater[axName] && !xaNonCheater[axName],
            splomStash: ((layoutOut._splomAxes || {})[axLetter] || {})[id]
        };

        coerce('uirevision', layoutOut.uirevision);

        handleTypeDefaults(axLayoutIn, axLayoutOut, coerce, defaultOptions);
        handleAxisDefaults(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut);

        var spikecolor = coerce2('spikecolor');
        var spikethickness = coerce2('spikethickness');
        var spikedash = coerce2('spikedash');
        var spikemode = coerce2('spikemode');
        var spikesnap = coerce2('spikesnap');
        var showSpikes = coerce('showspikes', !!spikecolor || !!spikethickness || !!spikedash || !!spikemode || !!spikesnap);

        if(!showSpikes) {
            delete axLayoutOut.spikecolor;
            delete axLayoutOut.spikethickness;
            delete axLayoutOut.spikedash;
            delete axLayoutOut.spikemode;
            delete axLayoutOut.spikesnap;
        }

        var positioningOptions = {
            letter: axLetter,
            counterAxes: counterAxes[axLetter],
            overlayableAxes: overlayableAxes,
            grid: layoutOut.grid
        };

        handlePositionDefaults(axLayoutIn, axLayoutOut, coerce, positioningOptions);

        axLayoutOut._input = axLayoutIn;
    }

    // quick second pass for range slider and selector defaults
    var rangeSliderDefaults = getComponentMethod('rangeslider', 'handleDefaults');
    var rangeSelectorDefaults = getComponentMethod('rangeselector', 'handleDefaults');

    for(i = 0; i < xNames.length; i++) {
        axName = xNames[i];
        axLayoutIn = layoutIn[axName];
        axLayoutOut = layoutOut[axName];

        rangeSliderDefaults(layoutIn, layoutOut, axName);

        if(axLayoutOut.type === 'date') {
            rangeSelectorDefaults(
                axLayoutIn,
                axLayoutOut,
                layoutOut,
                yNames,
                axLayoutOut.calendar
            );
        }

        coerce('fixedrange');
    }

    for(i = 0; i < yNames.length; i++) {
        axName = yNames[i];
        axLayoutIn = layoutIn[axName];
        axLayoutOut = layoutOut[axName];

        var anchoredAxis = layoutOut[id2name(axLayoutOut.anchor)];

        var fixedRangeDflt = getComponentMethod('rangeslider', 'isVisible')(anchoredAxis);

        coerce('fixedrange', fixedRangeDflt);
    }

    // Finally, handle scale constraints. We need to do this after all axes have
    // coerced both `type` (so we link only axes of the same type) and
    // `fixedrange` (so we can avoid linking from OR TO a fixed axis).

    // sets of axes linked by `scaleanchor` along with the scaleratios compounded
    // together, populated in handleConstraintDefaults
    layoutOut._axisConstraintGroups = [];
    var allAxisIds = counterAxes.x.concat(counterAxes.y);

    for(i = 0; i < axNames.length; i++) {
        axName = axNames[i];
        axLetter = axName.charAt(0);

        axLayoutIn = layoutIn[axName];
        axLayoutOut = layoutOut[axName];

        handleConstraintDefaults(axLayoutIn, axLayoutOut, coerce, allAxisIds, layoutOut);
    }
};

},{"../../components/color":571,"../../lib":694,"../../plot_api/plot_template":732,"../../registry":825,"../layout_attributes":797,"./axis_defaults":744,"./axis_ids":745,"./constraint_defaults":749,"./layout_attributes":755,"./position_defaults":758,"./type_defaults":766}],757:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorMix = _dereq_('tinycolor2').mix;
var lightFraction = _dereq_('../../components/color/attributes').lightFraction;
var Lib = _dereq_('../../lib');

/**
 * @param {object} opts :
 *   - dfltColor {string} : default axis color
 *   - bgColor {string} : combined subplot bg color
 *   - blend {number, optional} : blend percentage (to compute dflt grid color)
 *   - showLine {boolean} : show line by default
 *   - showGrid {boolean} : show grid by default
 *   - noZeroLine {boolean} : don't coerce zeroline* attributes
 *   - attributes {object} : attribute object associated with input containers
 */
module.exports = function handleLineGridDefaults(containerIn, containerOut, coerce, opts) {
    opts = opts || {};

    var dfltColor = opts.dfltColor;

    function coerce2(attr, dflt) {
        return Lib.coerce2(containerIn, containerOut, opts.attributes, attr, dflt);
    }

    var lineColor = coerce2('linecolor', dfltColor);
    var lineWidth = coerce2('linewidth');
    var showLine = coerce('showline', opts.showLine || !!lineColor || !!lineWidth);

    if(!showLine) {
        delete containerOut.linecolor;
        delete containerOut.linewidth;
    }

    var gridColorDflt = colorMix(dfltColor, opts.bgColor, opts.blend || lightFraction).toRgbString();
    var gridColor = coerce2('gridcolor', gridColorDflt);
    var gridWidth = coerce2('gridwidth');
    var showGridLines = coerce('showgrid', opts.showGrid || !!gridColor || !!gridWidth);

    if(!showGridLines) {
        delete containerOut.gridcolor;
        delete containerOut.gridwidth;
    }

    if(!opts.noZeroLine) {
        var zeroLineColor = coerce2('zerolinecolor', dfltColor);
        var zeroLineWidth = coerce2('zerolinewidth');
        var showZeroLine = coerce('zeroline', opts.showGrid || !!zeroLineColor || !!zeroLineWidth);

        if(!showZeroLine) {
            delete containerOut.zerolinecolor;
            delete containerOut.zerolinewidth;
        }
    }
};

},{"../../components/color/attributes":570,"../../lib":694,"tinycolor2":515}],758:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');


module.exports = function handlePositionDefaults(containerIn, containerOut, coerce, options) {
    var counterAxes = options.counterAxes || [];
    var overlayableAxes = options.overlayableAxes || [];
    var letter = options.letter;
    var grid = options.grid;

    var dfltAnchor, dfltDomain, dfltSide, dfltPosition;

    if(grid) {
        dfltDomain = grid._domains[letter][grid._axisMap[containerOut._id]];
        dfltAnchor = grid._anchors[containerOut._id];
        if(dfltDomain) {
            dfltSide = grid[letter + 'side'].split(' ')[0];
            dfltPosition = grid.domain[letter][dfltSide === 'right' || dfltSide === 'top' ? 1 : 0];
        }
    }

    // Even if there's a grid, this axis may not be in it - fall back on non-grid defaults
    dfltDomain = dfltDomain || [0, 1];
    dfltAnchor = dfltAnchor || (isNumeric(containerIn.position) ? 'free' : (counterAxes[0] || 'free'));
    dfltSide = dfltSide || (letter === 'x' ? 'bottom' : 'left');
    dfltPosition = dfltPosition || 0;

    var anchor = Lib.coerce(containerIn, containerOut, {
        anchor: {
            valType: 'enumerated',
            values: ['free'].concat(counterAxes),
            dflt: dfltAnchor
        }
    }, 'anchor');

    if(anchor === 'free') coerce('position', dfltPosition);

    Lib.coerce(containerIn, containerOut, {
        side: {
            valType: 'enumerated',
            values: letter === 'x' ? ['bottom', 'top'] : ['left', 'right'],
            dflt: dfltSide
        }
    }, 'side');

    var overlaying = false;
    if(overlayableAxes.length) {
        overlaying = Lib.coerce(containerIn, containerOut, {
            overlaying: {
                valType: 'enumerated',
                values: [false].concat(overlayableAxes),
                dflt: false
            }
        }, 'overlaying');
    }

    if(!overlaying) {
        // TODO: right now I'm copying this domain over to overlaying axes
        // in ax.setscale()... but this means we still need (imperfect) logic
        // in the axes popover to hide domain for the overlaying axis.
        // perhaps I should make a private version _domain that all axes get???
        var domain = coerce('domain', dfltDomain);

        // according to https://www.npmjs.com/package/canvas-size
        // the minimum value of max canvas width across browsers and devices is 4096
        // which applied in the calculation below:
        if(domain[0] > domain[1] - 1 / 4096) containerOut.domain = dfltDomain;
        Lib.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain);
    }

    coerce('layer');

    return containerOut;
};

},{"../../lib":694,"fast-isnumeric":215}],759:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var FROM_BL = _dereq_('../../constants/alignment').FROM_BL;

module.exports = function scaleZoom(ax, factor, centerFraction) {
    if(centerFraction === undefined) {
        centerFraction = FROM_BL[ax.constraintoward || 'center'];
    }

    var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])];
    var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction;

    ax.range = ax._input.range = [
        ax.l2r(center + (rangeLinear[0] - center) * factor),
        ax.l2r(center + (rangeLinear[1] - center) * factor)
    ];
};

},{"../../constants/alignment":666}],760:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var polybool = _dereq_('polybooljs');

var Registry = _dereq_('../../registry');
var Color = _dereq_('../../components/color');
var Fx = _dereq_('../../components/fx');

var polygon = _dereq_('../../lib/polygon');
var throttle = _dereq_('../../lib/throttle');
var makeEventData = _dereq_('../../components/fx/helpers').makeEventData;
var getFromId = _dereq_('./axis_ids').getFromId;
var clearGlCanvases = _dereq_('../../lib/clear_gl_canvases');
var redrawReglTraces = _dereq_('../../plot_api/subroutines').redrawReglTraces;

var constants = _dereq_('./constants');
var MINSELECT = constants.MINSELECT;

var filteredPolygon = polygon.filter;
var polygonTester = polygon.tester;

function getAxId(ax) { return ax._id; }

function prepSelect(e, startX, startY, dragOptions, mode) {
    var gd = dragOptions.gd;
    var fullLayout = gd._fullLayout;
    var zoomLayer = fullLayout._zoomlayer;
    var dragBBox = dragOptions.element.getBoundingClientRect();
    var plotinfo = dragOptions.plotinfo;
    var xs = plotinfo.xaxis._offset;
    var ys = plotinfo.yaxis._offset;
    var x0 = startX - dragBBox.left;
    var y0 = startY - dragBBox.top;
    var x1 = x0;
    var y1 = y0;
    var path0 = 'M' + x0 + ',' + y0;
    var pw = dragOptions.xaxes[0]._length;
    var ph = dragOptions.yaxes[0]._length;
    var allAxes = dragOptions.xaxes.concat(dragOptions.yaxes);
    var subtract = e.altKey;

    var filterPoly, selectionTester, mergedPolygons, currentPolygon;
    var i, searchInfo, eventData;

    coerceSelectionsCache(e, gd, dragOptions);

    if(mode === 'lasso') {
        filterPoly = filteredPolygon([[x0, y0]], constants.BENDPX);
    }

    var outlines = zoomLayer.selectAll('path.select-outline-' + plotinfo.id).data([1, 2]);

    outlines.enter()
        .append('path')
        .attr('class', function(d) { return 'select-outline select-outline-' + d + ' select-outline-' + plotinfo.id; })
        .attr('transform', 'translate(' + xs + ', ' + ys + ')')
        .attr('d', path0 + 'Z');

    var corners = zoomLayer.append('path')
        .attr('class', 'zoombox-corners')
        .style({
            fill: Color.background,
            stroke: Color.defaultLine,
            'stroke-width': 1
        })
        .attr('transform', 'translate(' + xs + ', ' + ys + ')')
        .attr('d', 'M0,0Z');


    var throttleID = fullLayout._uid + constants.SELECTID;
    var selection = [];

    // find the traces to search for selection points
    var searchTraces = determineSearchTraces(gd, dragOptions.xaxes,
      dragOptions.yaxes, dragOptions.subplot);

    function axValue(ax) {
        var index = (ax._id.charAt(0) === 'y') ? 1 : 0;
        return function(v) { return ax.p2d(v[index]); };
    }

    function ascending(a, b) { return a - b; }

    // allow subplots to override fillRangeItems routine
    var fillRangeItems;

    if(plotinfo.fillRangeItems) {
        fillRangeItems = plotinfo.fillRangeItems;
    } else {
        if(mode === 'select') {
            fillRangeItems = function(eventData, poly) {
                var ranges = eventData.range = {};

                for(i = 0; i < allAxes.length; i++) {
                    var ax = allAxes[i];
                    var axLetter = ax._id.charAt(0);

                    ranges[ax._id] = [
                        ax.p2d(poly[axLetter + 'min']),
                        ax.p2d(poly[axLetter + 'max'])
                    ].sort(ascending);
                }
            };
        } else {
            fillRangeItems = function(eventData, poly, filterPoly) {
                var dataPts = eventData.lassoPoints = {};

                for(i = 0; i < allAxes.length; i++) {
                    var ax = allAxes[i];
                    dataPts[ax._id] = filterPoly.filtered.map(axValue(ax));
                }
            };
        }
    }

    dragOptions.moveFn = function(dx0, dy0) {
        x1 = Math.max(0, Math.min(pw, dx0 + x0));
        y1 = Math.max(0, Math.min(ph, dy0 + y0));

        var dx = Math.abs(x1 - x0);
        var dy = Math.abs(y1 - y0);

        if(mode === 'select') {
            var direction = fullLayout.selectdirection;

            if(fullLayout.selectdirection === 'any') {
                if(dy < Math.min(dx * 0.6, MINSELECT)) direction = 'h';
                else if(dx < Math.min(dy * 0.6, MINSELECT)) direction = 'v';
                else direction = 'd';
            }
            else {
                direction = fullLayout.selectdirection;
            }

            if(direction === 'h') {
                // horizontal motion: make a vertical box
                currentPolygon = [[x0, 0], [x0, ph], [x1, ph], [x1, 0]];
                currentPolygon.xmin = Math.min(x0, x1);
                currentPolygon.xmax = Math.max(x0, x1);
                currentPolygon.ymin = Math.min(0, ph);
                currentPolygon.ymax = Math.max(0, ph);
                // extras to guide users in keeping a straight selection
                corners.attr('d', 'M' + currentPolygon.xmin + ',' + (y0 - MINSELECT) +
                    'h-4v' + (2 * MINSELECT) + 'h4Z' +
                    'M' + (currentPolygon.xmax - 1) + ',' + (y0 - MINSELECT) +
                    'h4v' + (2 * MINSELECT) + 'h-4Z');

            }
            else if(direction === 'v') {
                // vertical motion: make a horizontal box
                currentPolygon = [[0, y0], [0, y1], [pw, y1], [pw, y0]];
                currentPolygon.xmin = Math.min(0, pw);
                currentPolygon.xmax = Math.max(0, pw);
                currentPolygon.ymin = Math.min(y0, y1);
                currentPolygon.ymax = Math.max(y0, y1);
                corners.attr('d', 'M' + (x0 - MINSELECT) + ',' + currentPolygon.ymin +
                    'v-4h' + (2 * MINSELECT) + 'v4Z' +
                    'M' + (x0 - MINSELECT) + ',' + (currentPolygon.ymax - 1) +
                    'v4h' + (2 * MINSELECT) + 'v-4Z');
            }
            else if(direction === 'd') {
                // diagonal motion
                currentPolygon = [[x0, y0], [x0, y1], [x1, y1], [x1, y0]];
                currentPolygon.xmin = Math.min(x0, x1);
                currentPolygon.xmax = Math.max(x0, x1);
                currentPolygon.ymin = Math.min(y0, y1);
                currentPolygon.ymax = Math.max(y0, y1);
                corners.attr('d', 'M0,0Z');
            }
        }
        else if(mode === 'lasso') {
            filterPoly.addPt([x1, y1]);
            currentPolygon = filterPoly.filtered;
        }

        // create outline & tester
        if(dragOptions.selectionDefs && dragOptions.selectionDefs.length) {
            mergedPolygons = mergePolygons(dragOptions.mergedPolygons, currentPolygon, subtract);
            currentPolygon.subtract = subtract;
            selectionTester = multiTester(dragOptions.selectionDefs.concat([currentPolygon]));
        }
        else {
            mergedPolygons = [currentPolygon];
            selectionTester = polygonTester(currentPolygon);
        }

        // draw selection
        drawSelection(mergedPolygons, outlines);


        throttle.throttle(
            throttleID,
            constants.SELECTDELAY,
            function() {
                selection = [];

                var thisSelection;
                var traceSelections = [];
                var traceSelection;
                for(i = 0; i < searchTraces.length; i++) {
                    searchInfo = searchTraces[i];

                    traceSelection = searchInfo._module.selectPoints(searchInfo, selectionTester);
                    traceSelections.push(traceSelection);

                    thisSelection = fillSelectionItem(traceSelection, searchInfo);

                    if(selection.length) {
                        for(var j = 0; j < thisSelection.length; j++) {
                            selection.push(thisSelection[j]);
                        }
                    }
                    else selection = thisSelection;
                }

                eventData = {points: selection};
                updateSelectedState(gd, searchTraces, eventData);
                fillRangeItems(eventData, currentPolygon, filterPoly);
                dragOptions.gd.emit('plotly_selecting', eventData);
            }
        );
    };

    dragOptions.clickFn = function(numClicks, evt) {
        var clickmode = fullLayout.clickmode;

        corners.remove();

        throttle.done(throttleID).then(function() {
            throttle.clear(throttleID);
            if(numClicks === 2) {
                // clear selection on doubleclick
                outlines.remove();
                for(i = 0; i < searchTraces.length; i++) {
                    searchInfo = searchTraces[i];
                    searchInfo._module.selectPoints(searchInfo, false);
                }

                updateSelectedState(gd, searchTraces);

                clearSelectionsCache(dragOptions);

                gd.emit('plotly_deselect', null);
            } else {
                if(clickmode.indexOf('select') > -1) {
                    selectOnClick(evt, gd, dragOptions.xaxes, dragOptions.yaxes,
                      dragOptions.subplot, dragOptions, outlines);
                }

                if(clickmode === 'event') {
                    // TODO: remove in v2 - this was probably never intended to work as it does,
                    // but in case anyone depends on it we don't want to break it now.
                    // Note that click-to-select introduced pre v2 also emitts proper
                    // event data when clickmode is having 'select' in its flag list.
                    gd.emit('plotly_selected', undefined);
                }
            }

            Fx.click(gd, evt);
        });
    };

    dragOptions.doneFn = function() {
        corners.remove();

        throttle.done(throttleID).then(function() {
            throttle.clear(throttleID);
            dragOptions.gd.emit('plotly_selected', eventData);

            if(currentPolygon && dragOptions.selectionDefs) {
                // save last polygons
                currentPolygon.subtract = subtract;
                dragOptions.selectionDefs.push(currentPolygon);

                // we have to keep reference to arrays container
                dragOptions.mergedPolygons.length = 0;
                [].push.apply(dragOptions.mergedPolygons, mergedPolygons);
            }
        });
    };
}

function selectOnClick(evt, gd, xAxes, yAxes, subplot, dragOptions, polygonOutlines) {
    var hoverData = gd._hoverdata;
    var clickmode = gd._fullLayout.clickmode;
    var sendEvents = clickmode.indexOf('event') > -1;
    var selection = [];
    var searchTraces, searchInfo, currentSelectionDef, selectionTester, traceSelection;
    var thisTracesSelection, pointOrBinSelected, subtract, eventData, i;

    if(isHoverDataSet(hoverData)) {
        coerceSelectionsCache(evt, gd, dragOptions);
        searchTraces = determineSearchTraces(gd, xAxes, yAxes, subplot);
        var clickedPtInfo = extractClickedPtInfo(hoverData, searchTraces);
        var isBinnedTrace = clickedPtInfo.pointNumbers.length > 0;


        // Note: potentially costly operation isPointOrBinSelected is
        // called as late as possible through the use of an assignment
        // in an if condition.
        if(isBinnedTrace ?
            isOnlyThisBinSelected(searchTraces, clickedPtInfo) :
            isOnlyOnePointSelected(searchTraces) &&
                (pointOrBinSelected = isPointOrBinSelected(clickedPtInfo)))
        {
            if(polygonOutlines) polygonOutlines.remove();
            for(i = 0; i < searchTraces.length; i++) {
                searchInfo = searchTraces[i];
                searchInfo._module.selectPoints(searchInfo, false);
            }

            updateSelectedState(gd, searchTraces);

            clearSelectionsCache(dragOptions);

            if(sendEvents) {
                gd.emit('plotly_deselect', null);
            }
        } else {
            subtract = evt.shiftKey &&
              (pointOrBinSelected !== undefined ?
                pointOrBinSelected :
                isPointOrBinSelected(clickedPtInfo));
            currentSelectionDef = newPointSelectionDef(clickedPtInfo.pointNumber, clickedPtInfo.searchInfo, subtract);

            var allSelectionDefs = dragOptions.selectionDefs.concat([currentSelectionDef]);
            selectionTester = multiTester(allSelectionDefs);

            for(i = 0; i < searchTraces.length; i++) {
                traceSelection = searchTraces[i]._module.selectPoints(searchTraces[i], selectionTester);
                thisTracesSelection = fillSelectionItem(traceSelection, searchTraces[i]);

                if(selection.length) {
                    for(var j = 0; j < thisTracesSelection.length; j++) {
                        selection.push(thisTracesSelection[j]);
                    }
                }
                else selection = thisTracesSelection;
            }

            eventData = {points: selection};
            updateSelectedState(gd, searchTraces, eventData);

            if(currentSelectionDef && dragOptions) {
                dragOptions.selectionDefs.push(currentSelectionDef);
            }

            if(polygonOutlines) drawSelection(dragOptions.mergedPolygons, polygonOutlines);

            if(sendEvents) {
                gd.emit('plotly_selected', eventData);
            }
        }
    }
}

/**
 * Constructs a new point selection definition object.
 */
function newPointSelectionDef(pointNumber, searchInfo, subtract) {
    return {
        pointNumber: pointNumber,
        searchInfo: searchInfo,
        subtract: subtract
    };
}

function isPointSelectionDef(o) {
    return 'pointNumber' in o && 'searchInfo' in o;
}

/*
 * Constructs a new point number tester.
 */
function newPointNumTester(pointSelectionDef) {
    return {
        xmin: 0,
        xmax: 0,
        ymin: 0,
        ymax: 0,
        pts: [],
        contains: function(pt, omitFirstEdge, pointNumber, searchInfo) {
            var idxWantedTrace = pointSelectionDef.searchInfo.cd[0].trace._expandedIndex;
            var idxActualTrace = searchInfo.cd[0].trace._expandedIndex;
            return idxActualTrace === idxWantedTrace &&
              pointNumber === pointSelectionDef.pointNumber;
        },
        isRect: false,
        degenerate: false,
        subtract: pointSelectionDef.subtract
    };
}

/**
 * Wraps multiple selection testers.
 *
 * @param {Array} list - An array of selection testers.
 *
 * @return a selection tester object with a contains function
 * that can be called to evaluate a point against all wrapped
 * selection testers that were passed in list.
 */
function multiTester(list) {
    var testers = [];
    var xmin = isPointSelectionDef(list[0]) ? 0 : list[0][0][0];
    var xmax = xmin;
    var ymin = isPointSelectionDef(list[0]) ? 0 : list[0][0][1];
    var ymax = ymin;

    for(var i = 0; i < list.length; i++) {
        if(isPointSelectionDef(list[i])) {
            testers.push(newPointNumTester(list[i]));
        } else {
            var tester = polygon.tester(list[i]);
            tester.subtract = list[i].subtract;
            testers.push(tester);
            xmin = Math.min(xmin, tester.xmin);
            xmax = Math.max(xmax, tester.xmax);
            ymin = Math.min(ymin, tester.ymin);
            ymax = Math.max(ymax, tester.ymax);
        }
    }

    /**
     * Tests if the given point is within this tester.
     *
     * @param {Array} pt - [0] is the x coordinate, [1] is the y coordinate of the point.
     * @param {*} arg - An optional parameter to pass down to wrapped testers.
     * @param {number} pointNumber - The point number of the point within the underlying data array.
     * @param {number} searchInfo - An object identifying the trace the point is contained in.
     *
     * @return {boolean} true if point is considered to be selected, false otherwise.
     */
    function contains(pt, arg, pointNumber, searchInfo) {
        var contained = false;
        for(var i = 0; i < testers.length; i++) {
            if(testers[i].contains(pt, arg, pointNumber, searchInfo)) {
                // if contained by subtract tester - exclude the point
                contained = testers[i].subtract === false;
            }
        }

        return contained;
    }

    return {
        xmin: xmin,
        xmax: xmax,
        ymin: ymin,
        ymax: ymax,
        pts: [],
        contains: contains,
        isRect: false,
        degenerate: false
    };
}

function coerceSelectionsCache(evt, gd, dragOptions) {
    var fullLayout = gd._fullLayout;
    var zoomLayer = fullLayout._zoomlayer;
    var plotinfo = dragOptions.plotinfo;

    var selectingOnSameSubplot = (
      fullLayout._lastSelectedSubplot &&
      fullLayout._lastSelectedSubplot === plotinfo.id
    );
    var hasModifierKey = evt.shiftKey || evt.altKey;
    if(selectingOnSameSubplot && hasModifierKey &&
      (plotinfo.selection && plotinfo.selection.selectionDefs) && !dragOptions.selectionDefs) {
        // take over selection definitions from prev mode, if any
        dragOptions.selectionDefs = plotinfo.selection.selectionDefs;
        dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons;
    } else if(!hasModifierKey || !plotinfo.selection) {
        clearSelectionsCache(dragOptions);
    }

    // clear selection outline when selecting a different subplot
    if(!selectingOnSameSubplot) {
        clearSelect(zoomLayer);
        fullLayout._lastSelectedSubplot = plotinfo.id;
    }
}

function clearSelectionsCache(dragOptions) {
    var plotinfo = dragOptions.plotinfo;

    plotinfo.selection = {};
    plotinfo.selection.selectionDefs = dragOptions.selectionDefs = [];
    plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = [];
}

function determineSearchTraces(gd, xAxes, yAxes, subplot) {
    var searchTraces = [];
    var xAxisIds = xAxes.map(getAxId);
    var yAxisIds = yAxes.map(getAxId);
    var cd, trace, i;

    for(i = 0; i < gd.calcdata.length; i++) {
        cd = gd.calcdata[i];
        trace = cd[0].trace;

        if(trace.visible !== true || !trace._module || !trace._module.selectPoints) continue;

        if(subplot && (trace.subplot === subplot || trace.geo === subplot)) {
            searchTraces.push(createSearchInfo(trace._module, cd, xAxes[0], yAxes[0]));
        } else if(
          trace.type === 'splom' &&
          // FIXME: make sure we don't have more than single axis for splom
          trace._xaxes[xAxisIds[0]] && trace._yaxes[yAxisIds[0]]
        ) {
            var info = createSearchInfo(trace._module, cd, xAxes[0], yAxes[0]);
            info.scene = gd._fullLayout._splomScenes[trace.uid];
            searchTraces.push(info);
        } else {
            if(xAxisIds.indexOf(trace.xaxis) === -1) continue;
            if(yAxisIds.indexOf(trace.yaxis) === -1) continue;

            searchTraces.push(createSearchInfo(trace._module, cd,
              getFromId(gd, trace.xaxis), getFromId(gd, trace.yaxis)));
        }
    }

    return searchTraces;

    function createSearchInfo(module, calcData, xaxis, yaxis) {
        return {
            _module: module,
            cd: calcData,
            xaxis: xaxis,
            yaxis: yaxis
        };
    }
}

function drawSelection(polygons, outlines) {
    var paths = [];
    var i, d;

    for(i = 0; i < polygons.length; i++) {
        var ppts = polygons[i];
        paths.push(ppts.join('L') + 'L' + ppts[0]);
    }

    d = polygons.length > 0 ?
      'M' + paths.join('M') + 'Z' :
      'M0,0Z';
    outlines.attr('d', d);
}

function isHoverDataSet(hoverData) {
    return hoverData &&
      Array.isArray(hoverData) &&
      hoverData[0].hoverOnBox !== true;
}

function extractClickedPtInfo(hoverData, searchTraces) {
    var hoverDatum = hoverData[0];
    var pointNumber = -1;
    var pointNumbers = [];
    var searchInfo, i;

    for(i = 0; i < searchTraces.length; i++) {
        searchInfo = searchTraces[i];
        if(hoverDatum.fullData._expandedIndex === searchInfo.cd[0].trace._expandedIndex) {

            // Special case for box (and violin)
            if(hoverDatum.hoverOnBox === true) {
                break;
            }

            // Hint: in some traces like histogram, one graphical element
            // doesn't correspond to one particular data point, but to
            // bins of data points. Thus, hoverDatum can have a binNumber
            // property instead of pointNumber.
            if(hoverDatum.pointNumber !== undefined) {
                pointNumber = hoverDatum.pointNumber;
            } else if(hoverDatum.binNumber !== undefined) {
                pointNumber = hoverDatum.binNumber;
                pointNumbers = hoverDatum.pointNumbers;
            }

            break;
        }
    }

    return {
        pointNumber: pointNumber,
        pointNumbers: pointNumbers,
        searchInfo: searchInfo
    };
}

function isPointOrBinSelected(clickedPtInfo) {
    var trace = clickedPtInfo.searchInfo.cd[0].trace;
    var ptNum = clickedPtInfo.pointNumber;
    var ptNums = clickedPtInfo.pointNumbers;
    var ptNumsSet = ptNums.length > 0;

    // When pointsNumbers is set (e.g. histogram's binning),
    // it is assumed that when the first point of
    // a bin is selected, all others are as well
    var ptNumToTest = ptNumsSet ? ptNums[0] : ptNum;

    // TODO potential performance improvement
    // Primarily we need this function to determine if a click adds
    // or subtracts from a selection.
    // In cases `trace.selectedpoints` is a huge array, indexOf
    // might be slow. One remedy would be to introduce a hash somewhere.
    return trace.selectedpoints ? trace.selectedpoints.indexOf(ptNumToTest) > -1 : false;
}

function isOnlyThisBinSelected(searchTraces, clickedPtInfo) {
    var tracesWithSelectedPts = [];
    var searchInfo, trace, isSameTrace, i;

    for(i = 0; i < searchTraces.length; i++) {
        searchInfo = searchTraces[i];
        if(searchInfo.cd[0].trace.selectedpoints && searchInfo.cd[0].trace.selectedpoints.length > 0) {
            tracesWithSelectedPts.push(searchInfo);
        }
    }

    if(tracesWithSelectedPts.length === 1) {
        isSameTrace = tracesWithSelectedPts[0] === clickedPtInfo.searchInfo;
        if(isSameTrace) {
            trace = clickedPtInfo.searchInfo.cd[0].trace;
            if(trace.selectedpoints.length === clickedPtInfo.pointNumbers.length) {
                for(i = 0; i < clickedPtInfo.pointNumbers.length; i++) {
                    if(trace.selectedpoints.indexOf(clickedPtInfo.pointNumbers[i]) < 0) {
                        return false;
                    }
                }
                return true;
            }
        }
    }

    return false;
}

function isOnlyOnePointSelected(searchTraces) {
    var len = 0;
    var searchInfo, trace, i;

    for(i = 0; i < searchTraces.length; i++) {
        searchInfo = searchTraces[i];
        trace = searchInfo.cd[0].trace;
        if(trace.selectedpoints) {
            if(trace.selectedpoints.length > 1) return false;

            len += trace.selectedpoints.length;
            if(len > 1) return false;
        }
    }

    return len === 1;
}

function updateSelectedState(gd, searchTraces, eventData) {
    var i, searchInfo, cd, trace;

    // before anything else, update preGUI if necessary
    for(i = 0; i < searchTraces.length; i++) {
        var fullInputTrace = searchTraces[i].cd[0].trace._fullInput;
        var tracePreGUI = gd._fullLayout._tracePreGUI[fullInputTrace.uid];
        if(tracePreGUI.selectedpoints === undefined) {
            tracePreGUI.selectedpoints = fullInputTrace._input.selectedpoints || null;
        }
    }

    if(eventData) {
        var pts = eventData.points || [];

        for(i = 0; i < searchTraces.length; i++) {
            trace = searchTraces[i].cd[0].trace;
            trace._input.selectedpoints = trace._fullInput.selectedpoints = [];
            if(trace._fullInput !== trace) trace.selectedpoints = [];
        }

        for(i = 0; i < pts.length; i++) {
            var pt = pts[i];
            var data = pt.data;
            var fullData = pt.fullData;

            if(pt.pointIndices) {
                [].push.apply(data.selectedpoints, pt.pointIndices);
                if(trace._fullInput !== trace) {
                    [].push.apply(fullData.selectedpoints, pt.pointIndices);
                }
            } else {
                data.selectedpoints.push(pt.pointIndex);
                if(trace._fullInput !== trace) {
                    fullData.selectedpoints.push(pt.pointIndex);
                }
            }
        }
    }
    else {
        for(i = 0; i < searchTraces.length; i++) {
            trace = searchTraces[i].cd[0].trace;
            delete trace.selectedpoints;
            delete trace._input.selectedpoints;
            if(trace._fullInput !== trace) {
                delete trace._fullInput.selectedpoints;
            }
        }
    }

    var hasRegl = false;

    for(i = 0; i < searchTraces.length; i++) {
        searchInfo = searchTraces[i];
        cd = searchInfo.cd;
        trace = cd[0].trace;

        if(Registry.traceIs(trace, 'regl')) {
            hasRegl = true;
        }

        var _module = searchInfo._module;
        var fn = _module.styleOnSelect || _module.style;
        if(fn) fn(gd, cd);
    }

    if(hasRegl) {
        clearGlCanvases(gd);
        redrawReglTraces(gd);
    }
}

function mergePolygons(list, poly, subtract) {
    var res;

    if(subtract) {
        res = polybool.difference({
            regions: list,
            inverted: false
        }, {
            regions: [poly],
            inverted: false
        });

        return res.regions;
    }

    res = polybool.union({
        regions: list,
        inverted: false
    }, {
        regions: [poly],
        inverted: false
    });

    return res.regions;
}

function fillSelectionItem(selection, searchInfo) {
    if(Array.isArray(selection)) {
        var cd = searchInfo.cd;
        var trace = searchInfo.cd[0].trace;

        for(var i = 0; i < selection.length; i++) {
            selection[i] = makeEventData(selection[i], trace, cd);
        }
    }

    return selection;
}

function clearSelect(zoomlayer) {
    // until we get around to persistent selections, remove the outline
    // here. The selection itself will be removed when the plot redraws
    // at the end.
    zoomlayer.selectAll('.select-outline').remove();
}

module.exports = {
    prepSelect: prepSelect,
    clearSelect: clearSelect,
    selectOnClick: selectOnClick
};

},{"../../components/color":571,"../../components/fx":610,"../../components/fx/helpers":606,"../../lib/clear_gl_canvases":679,"../../lib/polygon":706,"../../lib/throttle":719,"../../plot_api/subroutines":733,"../../registry":825,"./axis_ids":745,"./constants":748,"polybooljs":459}],761:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');
var cleanNumber = Lib.cleanNumber;
var ms2DateTime = Lib.ms2DateTime;
var dateTime2ms = Lib.dateTime2ms;
var ensureNumber = Lib.ensureNumber;
var isArrayOrTypedArray = Lib.isArrayOrTypedArray;

var numConstants = _dereq_('../../constants/numerical');
var FP_SAFE = numConstants.FP_SAFE;
var BADNUM = numConstants.BADNUM;
var LOG_CLIP = numConstants.LOG_CLIP;

var constants = _dereq_('./constants');
var axisIds = _dereq_('./axis_ids');

function fromLog(v) {
    return Math.pow(10, v);
}

function isValidCategory(v) {
    return v !== null && v !== undefined;
}

/**
 * Define the conversion functions for an axis data is used in 5 ways:
 *
 *  d: data, in whatever form it's provided
 *  c: calcdata: turned into numbers, but not linearized
 *  l: linearized - same as c except for log axes (and other nonlinear
 *      mappings later?) this is used when we need to know if it's
 *      *possible* to show some data on this axis, without caring about
 *      the current range
 *  p: pixel value - mapped to the screen with current size and zoom
 *  r: ranges, tick0, and annotation positions match one of the above
 *     but are handled differently for different types:
 *     - linear and date: data format (d)
 *     - category: calcdata format (c), and will stay that way because
 *       the data format has no continuous mapping
 *     - log: linearized (l) format
 *       TODO: in v2.0 we plan to change it to data format. At that point
 *       shapes will work the same way as ranges, tick0, and annotations
 *       so they can use this conversion too.
 *
 * Creates/updates these conversion functions, and a few more utilities
 * like cleanRange, and makeCalcdata
 *
 * also clears the autotick constraints ._minDtick, ._forceTick0
 */
module.exports = function setConvert(ax, fullLayout) {
    fullLayout = fullLayout || {};

    var axLetter = (ax._id || 'x').charAt(0);

    function toLog(v, clip) {
        if(v > 0) return Math.log(v) / Math.LN10;

        else if(v <= 0 && clip && ax.range && ax.range.length === 2) {
            // clip NaN (ie past negative infinity) to LOG_CLIP axis
            // length past the negative edge
            var r0 = ax.range[0];
            var r1 = ax.range[1];
            return 0.5 * (r0 + r1 - 2 * LOG_CLIP * Math.abs(r0 - r1));
        }

        else return BADNUM;
    }

    /*
     * wrapped dateTime2ms that:
     * - accepts ms numbers for backward compatibility
     * - inserts a dummy arg so calendar is the 3rd arg (see notes below).
     * - defaults to ax.calendar
     */
    function dt2ms(v, _, calendar) {
        // NOTE: Changed this behavior: previously we took any numeric value
        // to be a ms, even if it was a string that could be a bare year.
        // Now we convert it as a date if at all possible, and only try
        // as (local) ms if that fails.
        var ms = dateTime2ms(v, calendar || ax.calendar);
        if(ms === BADNUM) {
            if(isNumeric(v)) {
                v = +v;
                // keep track of tenths of ms, that `new Date` will drop
                // same logic as in Lib.ms2DateTime
                var msecTenths = Math.floor(Lib.mod(v + 0.05, 1) * 10);
                var msRounded = Math.round(v - msecTenths / 10);
                ms = dateTime2ms(new Date(msRounded)) + msecTenths / 10;
            }
            else return BADNUM;
        }
        return ms;
    }

    // wrapped ms2DateTime to insert default ax.calendar
    function ms2dt(v, r, calendar) {
        return ms2DateTime(v, r, calendar || ax.calendar);
    }

    function getCategoryName(v) {
        return ax._categories[Math.round(v)];
    }

    /*
     * setCategoryIndex: return the index of category v,
     * inserting it in the list if it's not already there
     *
     * this will enter the categories in the order it
     * encounters them, ie all the categories from the
     * first data set, then all the ones from the second
     * that aren't in the first etc.
     *
     * it is assumed that this function is being invoked in the
     * already sorted category order; otherwise there would be
     * a disconnect between the array and the index returned
     */
    function setCategoryIndex(v) {
        if(isValidCategory(v)) {
            if(ax._categoriesMap === undefined) {
                ax._categoriesMap = {};
            }

            if(ax._categoriesMap[v] !== undefined) {
                return ax._categoriesMap[v];
            } else {
                ax._categories.push(v);

                var curLength = ax._categories.length - 1;
                ax._categoriesMap[v] = curLength;

                return curLength;
            }
        }
        return BADNUM;
    }

    function setMultiCategoryIndex(arrayIn, len) {
        var arrayOut = new Array(len);

        for(var i = 0; i < len; i++) {
            var v0 = (arrayIn[0] || [])[i];
            var v1 = (arrayIn[1] || [])[i];
            arrayOut[i] = getCategoryIndex([v0, v1]);
        }

        return arrayOut;
    }

    function getCategoryIndex(v) {
        if(ax._categoriesMap) {
            return ax._categoriesMap[v];
        }
    }

    function getCategoryPosition(v) {
        // d2l/d2c variant that that won't add categories but will also
        // allow numbers to be mapped to the linearized axis positions
        var index = getCategoryIndex(v);
        if(index !== undefined) return index;
        if(isNumeric(v)) return +v;
    }

    function l2p(v) {
        if(!isNumeric(v)) return BADNUM;

        // include 2 fractional digits on pixel, for PDF zooming etc
        return d3.round(ax._b + ax._m * v, 2);
    }

    function p2l(px) { return (px - ax._b) / ax._m; }

    // conversions among c/l/p are fairly simple - do them together for all axis types
    ax.c2l = (ax.type === 'log') ? toLog : ensureNumber;
    ax.l2c = (ax.type === 'log') ? fromLog : ensureNumber;

    ax.l2p = l2p;
    ax.p2l = p2l;

    ax.c2p = (ax.type === 'log') ? function(v, clip) { return l2p(toLog(v, clip)); } : l2p;
    ax.p2c = (ax.type === 'log') ? function(px) { return fromLog(p2l(px)); } : p2l;

    /*
     * now type-specific conversions for **ALL** other combinations
     * they're all written out, instead of being combinations of each other, for
     * both clarity and speed.
     */
    if(['linear', '-'].indexOf(ax.type) !== -1) {
        // all are data vals, but d and r need cleaning
        ax.d2r = ax.r2d = ax.d2c = ax.r2c = ax.d2l = ax.r2l = cleanNumber;
        ax.c2d = ax.c2r = ax.l2d = ax.l2r = ensureNumber;

        ax.d2p = ax.r2p = function(v) { return ax.l2p(cleanNumber(v)); };
        ax.p2d = ax.p2r = p2l;

        ax.cleanPos = ensureNumber;
    }
    else if(ax.type === 'log') {
        // d and c are data vals, r and l are logged (but d and r need cleaning)
        ax.d2r = ax.d2l = function(v, clip) { return toLog(cleanNumber(v), clip); };
        ax.r2d = ax.r2c = function(v) { return fromLog(cleanNumber(v)); };

        ax.d2c = ax.r2l = cleanNumber;
        ax.c2d = ax.l2r = ensureNumber;

        ax.c2r = toLog;
        ax.l2d = fromLog;

        ax.d2p = function(v, clip) { return ax.l2p(ax.d2r(v, clip)); };
        ax.p2d = function(px) { return fromLog(p2l(px)); };

        ax.r2p = function(v) { return ax.l2p(cleanNumber(v)); };
        ax.p2r = p2l;

        ax.cleanPos = ensureNumber;
    }
    else if(ax.type === 'date') {
        // r and d are date strings, l and c are ms

        /*
         * Any of these functions with r and d on either side, calendar is the
         * **3rd** argument. log has reserved the second argument.
         *
         * Unless you need the special behavior of the second arg (ms2DateTime
         * uses this to limit precision, toLog uses true to clip negatives
         * to offscreen low rather than undefined), it's safe to pass 0.
         */
        ax.d2r = ax.r2d = Lib.identity;

        ax.d2c = ax.r2c = ax.d2l = ax.r2l = dt2ms;
        ax.c2d = ax.c2r = ax.l2d = ax.l2r = ms2dt;

        ax.d2p = ax.r2p = function(v, _, calendar) { return ax.l2p(dt2ms(v, 0, calendar)); };
        ax.p2d = ax.p2r = function(px, r, calendar) { return ms2dt(p2l(px), r, calendar); };

        ax.cleanPos = function(v) { return Lib.cleanDate(v, BADNUM, ax.calendar); };
    }
    else if(ax.type === 'category') {
        // d is categories (string)
        // c and l are indices (numbers)
        // r is categories or numbers

        ax.d2c = ax.d2l = setCategoryIndex;
        ax.r2d = ax.c2d = ax.l2d = getCategoryName;

        ax.d2r = ax.d2l_noadd = getCategoryPosition;

        ax.r2c = function(v) {
            var index = getCategoryPosition(v);
            return index !== undefined ? index : ax.fraction2r(0.5);
        };

        ax.l2r = ax.c2r = ensureNumber;
        ax.r2l = getCategoryPosition;

        ax.d2p = function(v) { return ax.l2p(ax.r2c(v)); };
        ax.p2d = function(px) { return getCategoryName(p2l(px)); };
        ax.r2p = ax.d2p;
        ax.p2r = p2l;

        ax.cleanPos = function(v) {
            if(typeof v === 'string' && v !== '') return v;
            return ensureNumber(v);
        };
    }
    else if(ax.type === 'multicategory') {
        // N.B. multicategory axes don't define d2c and d2l,
        // as 'data-to-calcdata' conversion needs to take into
        // account all data array items as in ax.makeCalcdata.

        ax.r2d = ax.c2d = ax.l2d = getCategoryName;
        ax.d2r = ax.d2l_noadd = getCategoryPosition;

        ax.r2c = function(v) {
            var index = getCategoryPosition(v);
            return index !== undefined ? index : ax.fraction2r(0.5);
        };

        ax.r2c_just_indices = getCategoryIndex;

        ax.l2r = ax.c2r = ensureNumber;
        ax.r2l = getCategoryPosition;

        ax.d2p = function(v) { return ax.l2p(ax.r2c(v)); };
        ax.p2d = function(px) { return getCategoryName(p2l(px)); };
        ax.r2p = ax.d2p;
        ax.p2r = p2l;

        ax.cleanPos = function(v) {
            if(Array.isArray(v) || (typeof v === 'string' && v !== '')) return v;
            return ensureNumber(v);
        };

        ax.setupMultiCategory = function(fullData) {
            var traceIndices = ax._traceIndices;
            var i, j;

            // [ [cnt, {$cat: index}], for 1,2 ]
            var seen = ax._multicatSeen = [[0, {}], [0, {}]];
            // [ [arrayIn[0][i], arrayIn[1][i]], for i .. N ]
            var list = ax._multicatList = [];

            for(i = 0; i < traceIndices.length; i++) {
                var trace = fullData[traceIndices[i]];

                if(axLetter in trace) {
                    var arrayIn = trace[axLetter];
                    var len = trace._length || Lib.minRowLength(arrayIn);

                    if(isArrayOrTypedArray(arrayIn[0]) && isArrayOrTypedArray(arrayIn[1])) {
                        for(j = 0; j < len; j++) {
                            var v0 = arrayIn[0][j];
                            var v1 = arrayIn[1][j];

                            if(isValidCategory(v0) && isValidCategory(v1)) {
                                list.push([v0, v1]);

                                if(!(v0 in seen[0][1])) {
                                    seen[0][1][v0] = seen[0][0]++;
                                }
                                if(!(v1 in seen[1][1])) {
                                    seen[1][1][v1] = seen[1][0]++;
                                }
                            }
                        }
                    }
                }
            }

            list.sort(function(a, b) {
                var ind0 = seen[0][1];
                var d = ind0[a[0]] - ind0[b[0]];
                if(d) return d;

                var ind1 = seen[1][1];
                return ind1[a[1]] - ind1[b[1]];
            });

            for(i = 0; i < list.length; i++) {
                setCategoryIndex(list[i]);
            }
        };
    }

    // find the range value at the specified (linear) fraction of the axis
    ax.fraction2r = function(v) {
        var rl0 = ax.r2l(ax.range[0]);
        var rl1 = ax.r2l(ax.range[1]);
        return ax.l2r(rl0 + v * (rl1 - rl0));
    };

    // find the fraction of the range at the specified range value
    ax.r2fraction = function(v) {
        var rl0 = ax.r2l(ax.range[0]);
        var rl1 = ax.r2l(ax.range[1]);
        return (ax.r2l(v) - rl0) / (rl1 - rl0);
    };

    /*
     * cleanRange: make sure range is a couplet of valid & distinct values
     * keep numbers away from the limits of floating point numbers,
     * and dates away from the ends of our date system (+/- 9999 years)
     *
     * optional param rangeAttr: operate on a different attribute, like
     * ax._r, rather than ax.range
     */
    ax.cleanRange = function(rangeAttr, opts) {
        if(!opts) opts = {};
        if(!rangeAttr) rangeAttr = 'range';

        var range = Lib.nestedProperty(ax, rangeAttr).get();
        var i, dflt;

        if(ax.type === 'date') dflt = Lib.dfltRange(ax.calendar);
        else if(axLetter === 'y') dflt = constants.DFLTRANGEY;
        else dflt = opts.dfltRange || constants.DFLTRANGEX;

        // make sure we don't later mutate the defaults
        dflt = dflt.slice();

        if(!range || range.length !== 2) {
            Lib.nestedProperty(ax, rangeAttr).set(dflt);
            return;
        }

        if(ax.type === 'date') {
            // check if milliseconds or js date objects are provided for range
            // and convert to date strings
            range[0] = Lib.cleanDate(range[0], BADNUM, ax.calendar);
            range[1] = Lib.cleanDate(range[1], BADNUM, ax.calendar);
        }

        for(i = 0; i < 2; i++) {
            if(ax.type === 'date') {
                if(!Lib.isDateTime(range[i], ax.calendar)) {
                    ax[rangeAttr] = dflt;
                    break;
                }

                if(ax.r2l(range[0]) === ax.r2l(range[1])) {
                    // split by +/- 1 second
                    var linCenter = Lib.constrain(ax.r2l(range[0]),
                        Lib.MIN_MS + 1000, Lib.MAX_MS - 1000);
                    range[0] = ax.l2r(linCenter - 1000);
                    range[1] = ax.l2r(linCenter + 1000);
                    break;
                }
            }
            else {
                if(!isNumeric(range[i])) {
                    if(isNumeric(range[1 - i])) {
                        range[i] = range[1 - i] * (i ? 10 : 0.1);
                    }
                    else {
                        ax[rangeAttr] = dflt;
                        break;
                    }
                }

                if(range[i] < -FP_SAFE) range[i] = -FP_SAFE;
                else if(range[i] > FP_SAFE) range[i] = FP_SAFE;

                if(range[0] === range[1]) {
                    // somewhat arbitrary: split by 1 or 1ppm, whichever is bigger
                    var inc = Math.max(1, Math.abs(range[0] * 1e-6));
                    range[0] -= inc;
                    range[1] += inc;
                }
            }
        }
    };

    // set scaling to pixels
    ax.setScale = function(usePrivateRange) {
        var gs = fullLayout._size;

        // make sure we have a domain (pull it in from the axis
        // this one is overlaying if necessary)
        if(ax.overlaying) {
            var ax2 = axisIds.getFromId({ _fullLayout: fullLayout }, ax.overlaying);
            ax.domain = ax2.domain;
        }

        // While transitions are occuring, occurring, we get a double-transform
        // issue if we transform the drawn layer *and* use the new axis range to
        // draw the data. This allows us to construct setConvert using the pre-
        // interaction values of the range:
        var rangeAttr = (usePrivateRange && ax._r) ? '_r' : 'range';
        var calendar = ax.calendar;
        ax.cleanRange(rangeAttr);

        var rl0 = ax.r2l(ax[rangeAttr][0], calendar);
        var rl1 = ax.r2l(ax[rangeAttr][1], calendar);

        if(axLetter === 'y') {
            ax._offset = gs.t + (1 - ax.domain[1]) * gs.h;
            ax._length = gs.h * (ax.domain[1] - ax.domain[0]);
            ax._m = ax._length / (rl0 - rl1);
            ax._b = -ax._m * rl1;
        }
        else {
            ax._offset = gs.l + ax.domain[0] * gs.w;
            ax._length = gs.w * (ax.domain[1] - ax.domain[0]);
            ax._m = ax._length / (rl1 - rl0);
            ax._b = -ax._m * rl0;
        }

        if(!isFinite(ax._m) || !isFinite(ax._b)) {
            fullLayout._replotting = false;
            throw new Error('Something went wrong with axis scaling');
        }
    };

    // makeCalcdata: takes an x or y array and converts it
    // to a position on the axis object "ax"
    // inputs:
    //      trace - a data object from gd.data
    //      axLetter - a string, either 'x' or 'y', for which item
    //          to convert (TODO: is this now always the same as
    //          the first letter of ax._id?)
    // in case the expected data isn't there, make a list of
    // integers based on the opposite data
    ax.makeCalcdata = function(trace, axLetter) {
        var arrayIn, arrayOut, i, len;

        var axType = ax.type;
        var cal = axType === 'date' && trace[axLetter + 'calendar'];

        if(axLetter in trace) {
            arrayIn = trace[axLetter];
            len = trace._length || Lib.minRowLength(arrayIn);

            if(Lib.isTypedArray(arrayIn) && (axType === 'linear' || axType === 'log')) {
                if(len === arrayIn.length) {
                    return arrayIn;
                } else if(arrayIn.subarray) {
                    return arrayIn.subarray(0, len);
                }
            }

            if(axType === 'multicategory') {
                return setMultiCategoryIndex(arrayIn, len);
            }

            arrayOut = new Array(len);
            for(i = 0; i < len; i++) {
                arrayOut[i] = ax.d2c(arrayIn[i], 0, cal);
            }
        }
        else {
            var v0 = ((axLetter + '0') in trace) ? ax.d2c(trace[axLetter + '0'], 0, cal) : 0;
            var dv = (trace['d' + axLetter]) ? Number(trace['d' + axLetter]) : 1;

            // the opposing data, for size if we have x and dx etc
            arrayIn = trace[{x: 'y', y: 'x'}[axLetter]];
            len = trace._length || arrayIn.length;
            arrayOut = new Array(len);

            for(i = 0; i < len; i++) {
                arrayOut[i] = v0 + i * dv;
            }
        }

        return arrayOut;
    };

    ax.isValidRange = function(range) {
        return (
            Array.isArray(range) &&
            range.length === 2 &&
            isNumeric(ax.r2l(range[0])) &&
            isNumeric(ax.r2l(range[1]))
        );
    };

    ax.isPtWithinRange = function(d, calendar) {
        var coord = ax.c2l(d[axLetter], null, calendar);
        var r0 = ax.r2l(ax.range[0]);
        var r1 = ax.r2l(ax.range[1]);

        if(r0 < r1) {
            return r0 <= coord && coord <= r1;
        } else {
            // Reversed axis case.
            return r1 <= coord && coord <= r0;
        }
    };

    ax.clearCalc = function() {
        // initialize the category list, if there is one, so we start over
        // to be filled in later by ax.d2c
        ax._categories = (ax._initialCategories || []).slice();

        // Build the lookup map for initialized categories
        ax._categoriesMap = {};
        for(var j = 0; j < ax._categories.length; j++) {
            ax._categoriesMap[ax._categories[j]] = j;
        }
    };

    // Propagate localization into the axis so that
    // methods in Axes can use it w/o having to pass fullLayout
    // Default (non-d3) number formatting uses separators directly
    // dates and d3-formatted numbers use the d3 locale
    // Fall back on default format for dummy axes that don't care about formatting
    var locale = fullLayout._d3locale;
    if(ax.type === 'date') {
        ax._dateFormat = locale ? locale.timeFormat.utc : d3.time.format.utc;
        ax._extraFormat = fullLayout._extraFormat;
    }
    // occasionally we need _numFormat to pass through
    // even though it won't be needed by this axis
    ax._separators = fullLayout.separators;
    ax._numFormat = locale ? locale.numberFormat : d3.format;

    // and for bar charts and box plots: reset forced minimum tick spacing
    delete ax._minDtick;
    delete ax._forceTick0;
};

},{"../../constants/numerical":671,"../../lib":694,"./axis_ids":745,"./constants":748,"d3":149,"fast-isnumeric":215}],762:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var layoutAttributes = _dereq_('./layout_attributes');
var handleArrayContainerDefaults = _dereq_('../array_container_defaults');

module.exports = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options) {
    var showAttrDflt = getShowAttrDflt(containerIn);

    var tickPrefix = coerce('tickprefix');
    if(tickPrefix) coerce('showtickprefix', showAttrDflt);

    var tickSuffix = coerce('ticksuffix', options.tickSuffixDflt);
    if(tickSuffix) coerce('showticksuffix', showAttrDflt);

    var showTickLabels = coerce('showticklabels');
    if(showTickLabels) {
        var font = options.font || {};
        var contColor = containerOut.color;
        // as with titlefont.color, inherit axis.color only if one was
        // explicitly provided
        var dfltFontColor = (contColor && contColor !== layoutAttributes.color.dflt) ?
            contColor : font.color;
        Lib.coerceFont(coerce, 'tickfont', {
            family: font.family,
            size: font.size,
            color: dfltFontColor
        });
        coerce('tickangle');

        if(axType !== 'category') {
            var tickFormat = coerce('tickformat');
            var tickformatStops = containerIn.tickformatstops;
            if(Array.isArray(tickformatStops) && tickformatStops.length) {
                handleArrayContainerDefaults(containerIn, containerOut, {
                    name: 'tickformatstops',
                    inclusionAttr: 'enabled',
                    handleItemDefaults: tickformatstopDefaults
                });
            }
            if(!tickFormat && axType !== 'date') {
                coerce('showexponent', showAttrDflt);
                coerce('exponentformat');
                coerce('separatethousands');
            }
        }
    }
};

/*
 * Attributes 'showexponent', 'showtickprefix' and 'showticksuffix'
 * share values.
 *
 * If only 1 attribute is set,
 * the remaining attributes inherit that value.
 *
 * If 2 attributes are set to the same value,
 * the remaining attribute inherits that value.
 *
 * If 2 attributes are set to different values,
 * the remaining is set to its dflt value.
 *
 */
function getShowAttrDflt(containerIn) {
    var showAttrsAll = ['showexponent', 'showtickprefix', 'showticksuffix'];
    var showAttrs = showAttrsAll.filter(function(a) {
        return containerIn[a] !== undefined;
    });
    var sameVal = function(a) {
        return containerIn[a] === containerIn[showAttrs[0]];
    };

    if(showAttrs.every(sameVal) || showAttrs.length === 1) {
        return containerIn[showAttrs[0]];
    }
}

function tickformatstopDefaults(valueIn, valueOut) {
    function coerce(attr, dflt) {
        return Lib.coerce(valueIn, valueOut, layoutAttributes.tickformatstops, attr, dflt);
    }

    var enabled = coerce('enabled');
    if(enabled) {
        coerce('dtickrange');
        coerce('value');
    }
}

},{"../../lib":694,"../array_container_defaults":738,"./layout_attributes":755}],763:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

var layoutAttributes = _dereq_('./layout_attributes');


/**
 * options: inherits outerTicks from axes.handleAxisDefaults
 */
module.exports = function handleTickDefaults(containerIn, containerOut, coerce, options) {
    var tickLen = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'ticklen');
    var tickWidth = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'tickwidth');
    var tickColor = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'tickcolor', containerOut.color);
    var showTicks = coerce('ticks', (options.outerTicks || tickLen || tickWidth || tickColor) ? 'outside' : '');

    if(!showTicks) {
        delete containerOut.ticklen;
        delete containerOut.tickwidth;
        delete containerOut.tickcolor;
    }
};

},{"../../lib":694,"./layout_attributes":755}],764:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var cleanTicks = _dereq_('./clean_ticks');

module.exports = function handleTickValueDefaults(containerIn, containerOut, coerce, axType) {
    var tickmode;

    if(containerIn.tickmode === 'array' &&
            (axType === 'log' || axType === 'date')) {
        tickmode = containerOut.tickmode = 'auto';
    } else {
        var tickmodeDefault = Array.isArray(containerIn.tickvals) ? 'array' :
            containerIn.dtick ? 'linear' :
            'auto';
        tickmode = coerce('tickmode', tickmodeDefault);
    }

    if(tickmode === 'auto') coerce('nticks');
    else if(tickmode === 'linear') {
        // dtick is usually a positive number, but there are some
        // special strings available for log or date axes
        // tick0 also has special logic
        var dtick = containerOut.dtick = cleanTicks.dtick(
            containerIn.dtick, axType);
        containerOut.tick0 = cleanTicks.tick0(
            containerIn.tick0, axType, containerOut.calendar, dtick);
    } else if(axType !== 'multicategory') {
        var tickvals = coerce('tickvals');
        if(tickvals === undefined) containerOut.tickmode = 'auto';
        else coerce('ticktext');
    }
};

},{"./clean_ticks":747}],765:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Registry = _dereq_('../../registry');
var Drawing = _dereq_('../../components/drawing');
var Axes = _dereq_('./axes');

/**
 * transitionAxes
 *
 * transition axes from one set of ranges to another, using a svg
 * transformations, similar to during panning.
 *
 * @param {DOM element | object} gd
 * @param {array} edits : array of 'edits', each item with
 * - plotinfo {object} subplot object
 * - xr0 {array} initial x-range
 * - xr1 {array} end x-range
 * - yr0 {array} initial y-range
 * - yr1 {array} end y-range
 * @param {object} transitionOpts
 * @param {function} makeOnCompleteCallback
 */
module.exports = function transitionAxes(gd, edits, transitionOpts, makeOnCompleteCallback) {
    var fullLayout = gd._fullLayout;

    // special case for redraw:false Plotly.animate that relies on this
    // to update axis-referenced layout components
    if(edits.length === 0) {
        Axes.redrawComponents(gd);
        return;
    }

    function unsetSubplotTransform(subplot) {
        var xa = subplot.xaxis;
        var ya = subplot.yaxis;

        fullLayout._defs.select('#' + subplot.clipId + '> rect')
            .call(Drawing.setTranslate, 0, 0)
            .call(Drawing.setScale, 1, 1);

        subplot.plot
            .call(Drawing.setTranslate, xa._offset, ya._offset)
            .call(Drawing.setScale, 1, 1);

        var traceGroups = subplot.plot.selectAll('.scatterlayer .trace');

        // This is specifically directed at scatter traces, applying an inverse
        // scale to individual points to counteract the scale of the trace
        // as a whole:
        traceGroups.selectAll('.point')
            .call(Drawing.setPointGroupScale, 1, 1);
        traceGroups.selectAll('.textpoint')
            .call(Drawing.setTextPointsScale, 1, 1);
        traceGroups
            .call(Drawing.hideOutsideRangePoints, subplot);
    }

    function updateSubplot(edit, progress) {
        var plotinfo = edit.plotinfo;
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;

        var xr0 = edit.xr0;
        var xr1 = edit.xr1;
        var xlen = xa._length;
        var yr0 = edit.yr0;
        var yr1 = edit.yr1;
        var ylen = ya._length;

        var editX = !!xr1;
        var editY = !!yr1;
        var viewBox = [];

        if(editX) {
            var dx0 = xr0[1] - xr0[0];
            var dx1 = xr1[1] - xr1[0];
            viewBox[0] = (xr0[0] * (1 - progress) + progress * xr1[0] - xr0[0]) / (xr0[1] - xr0[0]) * xlen;
            viewBox[2] = xlen * ((1 - progress) + progress * dx1 / dx0);
            xa.range[0] = xr0[0] * (1 - progress) + progress * xr1[0];
            xa.range[1] = xr0[1] * (1 - progress) + progress * xr1[1];
        } else {
            viewBox[0] = 0;
            viewBox[2] = xlen;
        }

        if(editY) {
            var dy0 = yr0[1] - yr0[0];
            var dy1 = yr1[1] - yr1[0];
            viewBox[1] = (yr0[1] * (1 - progress) + progress * yr1[1] - yr0[1]) / (yr0[0] - yr0[1]) * ylen;
            viewBox[3] = ylen * ((1 - progress) + progress * dy1 / dy0);
            ya.range[0] = yr0[0] * (1 - progress) + progress * yr1[0];
            ya.range[1] = yr0[1] * (1 - progress) + progress * yr1[1];
        } else {
            viewBox[1] = 0;
            viewBox[3] = ylen;
        }

        Axes.drawOne(gd, xa, {skipTitle: true});
        Axes.drawOne(gd, ya, {skipTitle: true});
        Axes.redrawComponents(gd, [xa._id, ya._id]);

        var xScaleFactor = editX ? xlen / viewBox[2] : 1;
        var yScaleFactor = editY ? ylen / viewBox[3] : 1;
        var clipDx = editX ? viewBox[0] : 0;
        var clipDy = editY ? viewBox[1] : 0;
        var fracDx = editX ? (viewBox[0] / viewBox[2] * xlen) : 0;
        var fracDy = editY ? (viewBox[1] / viewBox[3] * ylen) : 0;
        var plotDx = xa._offset - fracDx;
        var plotDy = ya._offset - fracDy;

        plotinfo.clipRect
            .call(Drawing.setTranslate, clipDx, clipDy)
            .call(Drawing.setScale, 1 / xScaleFactor, 1 / yScaleFactor);

        plotinfo.plot
            .call(Drawing.setTranslate, plotDx, plotDy)
            .call(Drawing.setScale, xScaleFactor, yScaleFactor);

        // apply an inverse scale to individual points to counteract
        // the scale of the trace group.
        Drawing.setPointGroupScale(plotinfo.zoomScalePts, 1 / xScaleFactor, 1 / yScaleFactor);
        Drawing.setTextPointsScale(plotinfo.zoomScaleTxt, 1 / xScaleFactor, 1 / yScaleFactor);
    }

    var onComplete;
    if(makeOnCompleteCallback) {
        // This module makes the choice whether or not it notifies Plotly.transition
        // about completion:
        onComplete = makeOnCompleteCallback();
    }

    function transitionComplete() {
        var aobj = {};

        for(var i = 0; i < edits.length; i++) {
            var edit = edits[i];
            if(edit.xr1) aobj[edit.plotinfo.xaxis._name + '.range'] = edit.xr1.slice();
            if(edit.yr1) aobj[edit.plotinfo.yaxis._name + '.range'] = edit.yr1.slice();
        }

        // Signal that this transition has completed:
        onComplete && onComplete();

        return Registry.call('relayout', gd, aobj).then(function() {
            for(var i = 0; i < edits.length; i++) {
                unsetSubplotTransform(edits[i].plotinfo);
            }
        });
    }

    function transitionInterrupt() {
        var aobj = {};

        for(var i = 0; i < edits.length; i++) {
            var edit = edits[i];
            if(edit.xr0) aobj[edit.plotinfo.xaxis._name + '.range'] = edit.xr0.slice();
            if(edit.yr0) aobj[edit.plotinfo.yaxis._name + '.range'] = edit.yr0.slice();
        }

        return Registry.call('relayout', gd, aobj).then(function() {
            for(var i = 0; i < edits.length; i++) {
                unsetSubplotTransform(edits[i].plotinfo);
            }
        });
    }

    var t1, t2, raf;
    var easeFn = d3.ease(transitionOpts.easing);

    gd._transitionData._interruptCallbacks.push(function() {
        window.cancelAnimationFrame(raf);
        raf = null;
        return transitionInterrupt();
    });

    function doFrame() {
        t2 = Date.now();

        var tInterp = Math.min(1, (t2 - t1) / transitionOpts.duration);
        var progress = easeFn(tInterp);

        for(var i = 0; i < edits.length; i++) {
            updateSubplot(edits[i], progress);
        }

        if(t2 - t1 > transitionOpts.duration) {
            transitionComplete();
            raf = window.cancelAnimationFrame(doFrame);
        } else {
            raf = window.requestAnimationFrame(doFrame);
        }
    }

    t1 = Date.now();
    raf = window.requestAnimationFrame(doFrame);

    return Promise.resolve();
};

},{"../../components/drawing":592,"../../registry":825,"./axes":742,"d3":149}],766:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var traceIs = _dereq_('../../registry').traceIs;
var autoType = _dereq_('./axis_autotype');

/*
 *  data: the plot data to use in choosing auto type
 *  name: axis object name (ie 'xaxis') if one should be stored
 */
module.exports = function handleTypeDefaults(containerIn, containerOut, coerce, options) {
    var axType = coerce('type', (options.splomStash || {}).type);

    if(axType === '-') {
        setAutoType(containerOut, options.data);

        if(containerOut.type === '-') {
            containerOut.type = 'linear';
        } else {
            // copy autoType back to input axis
            // note that if this object didn't exist
            // in the input layout, we have to put it in
            // this happens in the main supplyDefaults function
            containerIn.type = containerOut.type;
        }
    }
};

function setAutoType(ax, data) {
    // new logic: let people specify any type they want,
    // only autotype if type is '-'
    if(ax.type !== '-') return;

    var id = ax._id;
    var axLetter = id.charAt(0);

    // support 3d
    if(id.indexOf('scene') !== -1) id = axLetter;

    var d0 = getFirstNonEmptyTrace(data, id, axLetter);
    if(!d0) return;

    // first check for histograms, as the count direction
    // should always default to a linear axis
    if(d0.type === 'histogram' &&
            axLetter === {v: 'y', h: 'x'}[d0.orientation || 'v']) {
        ax.type = 'linear';
        return;
    }

    var calAttr = axLetter + 'calendar';
    var calendar = d0[calAttr];
    var opts = {noMultiCategory: !traceIs(d0, 'cartesian') || traceIs(d0, 'noMultiCategory')};
    var i;

    // check all boxes on this x axis to see
    // if they're dates, numbers, or categories
    if(isBoxWithoutPositionCoords(d0, axLetter)) {
        var posLetter = getBoxPosLetter(d0);
        var boxPositions = [];

        for(i = 0; i < data.length; i++) {
            var trace = data[i];
            if(!traceIs(trace, 'box-violin') || (trace[axLetter + 'axis'] || axLetter) !== id) continue;

            if(trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]);
            else if(trace.name !== undefined) boxPositions.push(trace.name);
            else boxPositions.push('text');

            if(trace[calAttr] !== calendar) calendar = undefined;
        }

        ax.type = autoType(boxPositions, calendar, opts);
    }
    else if(d0.type === 'splom') {
        var dimensions = d0.dimensions;
        var diag = d0._diag;
        for(i = 0; i < dimensions.length; i++) {
            var dim = dimensions[i];
            if(dim.visible && (diag[i][0] === id || diag[i][1] === id)) {
                ax.type = autoType(dim.values, calendar, opts);
                break;
            }
        }
    }
    else {
        ax.type = autoType(d0[axLetter] || [d0[axLetter + '0']], calendar, opts);
    }
}

function getFirstNonEmptyTrace(data, id, axLetter) {
    for(var i = 0; i < data.length; i++) {
        var trace = data[i];

        if(trace.type === 'splom' &&
                trace._length > 0 &&
                (trace['_' + axLetter + 'axes'] || {})[id]
        ) {
            return trace;
        }

        if((trace[axLetter + 'axis'] || axLetter) === id) {
            if(isBoxWithoutPositionCoords(trace, axLetter)) {
                return trace;
            }
            else if((trace[axLetter] || []).length || trace[axLetter + '0']) {
                return trace;
            }
        }
    }
}

function getBoxPosLetter(trace) {
    return {v: 'x', h: 'y'}[trace.orientation || 'v'];
}

function isBoxWithoutPositionCoords(trace, axLetter) {
    var posLetter = getBoxPosLetter(trace);
    var isBox = traceIs(trace, 'box-violin');
    var isCandlestick = traceIs(trace._fullInput || {}, 'candlestick');

    return (
        isBox &&
        !isCandlestick &&
        axLetter === posLetter &&
        trace[posLetter] === undefined &&
        trace[posLetter + '0'] === undefined
    );
}

},{"../../registry":825,"./axis_autotype":743}],767:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../registry');
var Lib = _dereq_('../lib');

/*
 * Create or update an observer. This function is designed to be
 * idempotent so that it can be called over and over as the component
 * updates, and will attach and detach listeners as needed.
 *
 * @param {optional object} container
 *      An object on which the observer is stored. This is the mechanism
 *      by which it is idempotent. If it already exists, another won't be
 *      added. Each time it's called, the value lookup table is updated.
 * @param {array} commandList
 *      An array of commands, following either `buttons` of `updatemenus`
 *      or `steps` of `sliders`.
 * @param {function} onchange
 *      A listener called when the value is changed. Receives data object
 *      with information about the new state.
 */
exports.manageCommandObserver = function(gd, container, commandList, onchange) {
    var ret = {};
    var enabled = true;

    if(container && container._commandObserver) {
        ret = container._commandObserver;
    }

    if(!ret.cache) {
        ret.cache = {};
    }

    // Either create or just recompute this:
    ret.lookupTable = {};

    var binding = exports.hasSimpleAPICommandBindings(gd, commandList, ret.lookupTable);

    if(container && container._commandObserver) {
        if(!binding) {
            // If container exists and there are no longer any bindings,
            // remove existing:
            if(container._commandObserver.remove) {
                container._commandObserver.remove();
                container._commandObserver = null;
                return ret;
            }
        } else {
            // If container exists and there *are* bindings, then the lookup
            // table should have been updated and check is already attached,
            // so there's nothing to be done:
            return ret;


        }
    }

    // Determine whether there's anything to do for this binding:

    if(binding) {
        // Build the cache:
        bindingValueHasChanged(gd, binding, ret.cache);

        ret.check = function check() {
            if(!enabled) return;

            var update = bindingValueHasChanged(gd, binding, ret.cache);

            if(update.changed && onchange) {
                // Disable checks for the duration of this command in order to avoid
                // infinite loops:
                if(ret.lookupTable[update.value] !== undefined) {
                    ret.disable();
                    Promise.resolve(onchange({
                        value: update.value,
                        type: binding.type,
                        prop: binding.prop,
                        traces: binding.traces,
                        index: ret.lookupTable[update.value]
                    })).then(ret.enable, ret.enable);
                }
            }

            return update.changed;
        };

        var checkEvents = [
            'plotly_relayout',
            'plotly_redraw',
            'plotly_restyle',
            'plotly_update',
            'plotly_animatingframe',
            'plotly_afterplot'
        ];

        for(var i = 0; i < checkEvents.length; i++) {
            gd._internalOn(checkEvents[i], ret.check);
        }

        ret.remove = function() {
            for(var i = 0; i < checkEvents.length; i++) {
                gd._removeInternalListener(checkEvents[i], ret.check);
            }
        };
    } else {
        // TODO: It'd be really neat to actually give a *reason* for this, but at least a warning
        // is a start
        Lib.log('Unable to automatically bind plot updates to API command');

        ret.lookupTable = {};
        ret.remove = function() {};
    }

    ret.disable = function disable() {
        enabled = false;
    };

    ret.enable = function enable() {
        enabled = true;
    };

    if(container) {
        container._commandObserver = ret;
    }

    return ret;
};

/*
 * This function checks to see if an array of objects containing
 * method and args properties is compatible with automatic two-way
 * binding. The criteria right now are that
 *
 *   1. multiple traces may be affected
 *   2. only one property may be affected
 *   3. the same property must be affected by all commands
 */
exports.hasSimpleAPICommandBindings = function(gd, commandList, bindingsByValue) {
    var i;
    var n = commandList.length;

    var refBinding;

    for(i = 0; i < n; i++) {
        var binding;
        var command = commandList[i];
        var method = command.method;
        var args = command.args;

        if(!Array.isArray(args)) args = [];

        // If any command has no method, refuse to bind:
        if(!method) {
            return false;
        }
        var bindings = exports.computeAPICommandBindings(gd, method, args);

        // Right now, handle one and *only* one property being set:
        if(bindings.length !== 1) {
            return false;
        }

        if(!refBinding) {
            refBinding = bindings[0];
            if(Array.isArray(refBinding.traces)) {
                refBinding.traces.sort();
            }
        } else {
            binding = bindings[0];
            if(binding.type !== refBinding.type) {
                return false;
            }
            if(binding.prop !== refBinding.prop) {
                return false;
            }
            if(Array.isArray(refBinding.traces)) {
                if(Array.isArray(binding.traces)) {
                    binding.traces.sort();
                    for(var j = 0; j < refBinding.traces.length; j++) {
                        if(refBinding.traces[j] !== binding.traces[j]) {
                            return false;
                        }
                    }
                } else {
                    return false;
                }
            } else {
                if(binding.prop !== refBinding.prop) {
                    return false;
                }
            }
        }

        binding = bindings[0];
        var value = binding.value;
        if(Array.isArray(value)) {
            if(value.length === 1) {
                value = value[0];
            } else {
                return false;
            }
        }
        if(bindingsByValue) {
            bindingsByValue[value] = i;
        }
    }

    return refBinding;
};

function bindingValueHasChanged(gd, binding, cache) {
    var container, value, obj;
    var changed = false;

    if(binding.type === 'data') {
        // If it's data, we need to get a trace. Based on the limited scope
        // of what we cover, we can just take the first trace from the list,
        // or otherwise just the first trace:
        container = gd._fullData[binding.traces !== null ? binding.traces[0] : 0];
    } else if(binding.type === 'layout') {
        container = gd._fullLayout;
    } else {
        return false;
    }

    value = Lib.nestedProperty(container, binding.prop).get();

    obj = cache[binding.type] = cache[binding.type] || {};

    if(obj.hasOwnProperty(binding.prop)) {
        if(obj[binding.prop] !== value) {
            changed = true;
        }
    }

    obj[binding.prop] = value;

    return {
        changed: changed,
        value: value
    };
}

/*
 * Execute an API command. There's really not much to this; it just provides
 * a common hook so that implementations don't need to be synchronized across
 * multiple components with the ability to invoke API commands.
 *
 * @param {string} method
 *      The name of the plotly command to execute. Must be one of 'animate',
 *      'restyle', 'relayout', 'update'.
 * @param {array} args
 *      A list of arguments passed to the API command
 */
exports.executeAPICommand = function(gd, method, args) {
    if(method === 'skip') return Promise.resolve();

    var _method = Registry.apiMethodRegistry[method];
    var allArgs = [gd];
    if(!Array.isArray(args)) args = [];

    for(var i = 0; i < args.length; i++) {
        allArgs.push(args[i]);
    }

    return _method.apply(null, allArgs).catch(function(err) {
        Lib.warn('API call to Plotly.' + method + ' rejected.', err);
        return Promise.reject(err);
    });
};

exports.computeAPICommandBindings = function(gd, method, args) {
    var bindings;

    if(!Array.isArray(args)) args = [];

    switch(method) {
        case 'restyle':
            bindings = computeDataBindings(gd, args);
            break;
        case 'relayout':
            bindings = computeLayoutBindings(gd, args);
            break;
        case 'update':
            bindings = computeDataBindings(gd, [args[0], args[2]])
                .concat(computeLayoutBindings(gd, [args[1]]));
            break;
        case 'animate':
            bindings = computeAnimateBindings(gd, args);
            break;
        default:
            // This is the case where intelligent logic about what affects
            // this command is not implemented. It causes no ill effects.
            // For example, addFrames simply won't bind to a control component.
            bindings = [];
    }
    return bindings;
};

function computeAnimateBindings(gd, args) {
    // We'll assume that the only relevant modification an animation
    // makes that's meaningfully tracked is the frame:
    if(Array.isArray(args[0]) && args[0].length === 1 && ['string', 'number'].indexOf(typeof args[0][0]) !== -1) {
        return [{type: 'layout', prop: '_currentFrame', value: args[0][0].toString()}];
    } else {
        return [];
    }
}

function computeLayoutBindings(gd, args) {
    var bindings = [];

    var astr = args[0];
    var aobj = {};
    if(typeof astr === 'string') {
        aobj[astr] = args[1];
    } else if(Lib.isPlainObject(astr)) {
        aobj = astr;
    } else {
        return bindings;
    }

    crawl(aobj, function(path, attrName, attr) {
        bindings.push({type: 'layout', prop: path, value: attr});
    }, '', 0);

    return bindings;
}

function computeDataBindings(gd, args) {
    var traces, astr, val, aobj;
    var bindings = [];

    // Logic copied from Plotly.restyle:
    astr = args[0];
    val = args[1];
    traces = args[2];
    aobj = {};
    if(typeof astr === 'string') {
        aobj[astr] = val;
    } else if(Lib.isPlainObject(astr)) {
        // the 3-arg form
        aobj = astr;

        if(traces === undefined) {
            traces = val;
        }
    } else {
        return bindings;
    }

    if(traces === undefined) {
        // Explicitly assign this to null instead of undefined:
        traces = null;
    }

    crawl(aobj, function(path, attrName, attr) {
        var thisTraces;
        if(Array.isArray(attr)) {
            var nAttr = Math.min(attr.length, gd.data.length);
            if(traces) {
                nAttr = Math.min(nAttr, traces.length);
            }
            thisTraces = [];
            for(var j = 0; j < nAttr; j++) {
                thisTraces[j] = traces ? traces[j] : j;
            }
        } else {
            thisTraces = traces ? traces.slice(0) : null;
        }

        // Convert [7] to just 7 when traces is null:
        if(thisTraces === null) {
            if(Array.isArray(attr)) {
                attr = attr[0];
            }
        } else if(Array.isArray(thisTraces)) {
            if(!Array.isArray(attr)) {
                var tmp = attr;
                attr = [];
                for(var i = 0; i < thisTraces.length; i++) {
                    attr[i] = tmp;
                }
            }
            attr.length = Math.min(thisTraces.length, attr.length);
        }

        bindings.push({
            type: 'data',
            prop: path,
            traces: thisTraces,
            value: attr
        });
    }, '', 0);

    return bindings;
}

function crawl(attrs, callback, path, depth) {
    Object.keys(attrs).forEach(function(attrName) {
        var attr = attrs[attrName];

        if(attrName[0] === '_') return;

        var thisPath = path + (depth > 0 ? '.' : '') + attrName;

        if(Lib.isPlainObject(attr)) {
            crawl(attr, callback, thisPath, depth + 1);
        } else {
            // Only execute the callback on leaf nodes:
            callback(thisPath, attrName, attr);
        }
    });
}

},{"../lib":694,"../registry":825}],768:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var extendFlat = _dereq_('../lib/extend').extendFlat;

/**
 * Make a xy domain attribute group
 *
 * @param {object} opts
 *   @param {string}
 *     opts.name: name to be inserted in the default description
 *   @param {boolean}
 *     opts.trace: set to true for trace containers
 *   @param {string}
 *     opts.editType: editType for all pieces
 *   @param {boolean}
 *     opts.noGridCell: set to true to omit `row` and `column`
 *
 * @param {object} extra
 *   @param {string}
 *     extra.description: extra description. N.B we use
 *     a separate extra container to make it compatible with
 *     the compress_attributes transform.
 *
 * @return {object} attributes object containing {x,y} as specified
 */
exports.attributes = function(opts, extra) {
    opts = opts || {};
    extra = extra || {};

    var base = {
        valType: 'info_array',
        
        editType: opts.editType,
        items: [
            {valType: 'number', min: 0, max: 1, editType: opts.editType},
            {valType: 'number', min: 0, max: 1, editType: opts.editType}
        ],
        dflt: [0, 1]
    };

    var namePart = opts.name ? opts.name + ' ' : '';
    var contPart = opts.trace ? 'trace ' : 'subplot ';
    var descPart = extra.description ? ' ' + extra.description : '';

    var out = {
        x: extendFlat({}, base, {
            
        }),
        y: extendFlat({}, base, {
            
        }),
        editType: opts.editType
    };

    if(!opts.noGridCell) {
        out.row = {
            valType: 'integer',
            min: 0,
            dflt: 0,
            
            editType: opts.editType,
            
        };
        out.column = {
            valType: 'integer',
            min: 0,
            dflt: 0,
            
            editType: opts.editType,
            
        };
    }

    return out;
};

exports.defaults = function(containerOut, layout, coerce, dfltDomains) {
    var dfltX = (dfltDomains && dfltDomains.x) || [0, 1];
    var dfltY = (dfltDomains && dfltDomains.y) || [0, 1];

    var grid = layout.grid;
    if(grid) {
        var column = coerce('domain.column');
        if(column !== undefined) {
            if(column < grid.columns) dfltX = grid._domains.x[column];
            else delete containerOut.domain.column;
        }

        var row = coerce('domain.row');
        if(row !== undefined) {
            if(row < grid.rows) dfltY = grid._domains.y[row];
            else delete containerOut.domain.row;
        }
    }

    coerce('domain.x', dfltX);
    coerce('domain.y', dfltY);
};

},{"../lib/extend":684}],769:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/*
 * make a font attribute group
 *
 * @param {object} opts
 *   @param {string}
 *     opts.description: where & how this font is used
 *   @param {optional bool} arrayOk:
 *     should each part (family, size, color) be arrayOk? default false.
 *   @param {string} editType:
 *     the editType for all pieces of this font
 *   @param {optional string} colorEditType:
 *     a separate editType just for color
 *
 * @return {object} attributes object containing {family, size, color} as specified
 */
module.exports = function(opts) {
    var editType = opts.editType;
    var colorEditType = opts.colorEditType;
    if(colorEditType === undefined) colorEditType = editType;
    var attrs = {
        family: {
            valType: 'string',
            
            noBlank: true,
            strict: true,
            editType: editType,
            
        },
        size: {
            valType: 'number',
            
            min: 1,
            editType: editType
        },
        color: {
            valType: 'color',
            
            editType: colorEditType
        },
        editType: editType,
        // blank strings so compress_attributes can remove
        // TODO - that's uber hacky... better solution?
        
    };

    if(opts.arrayOk) {
        attrs.family.arrayOk = true;
        attrs.size.arrayOk = true;
        attrs.color.arrayOk = true;
    }

    return attrs;
};

},{}],770:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    _isLinkedToArray: 'frames_entry',

    group: {
        valType: 'string',
        
        
    },
    name: {
        valType: 'string',
        
        
    },
    traces: {
        valType: 'any',
        
        
    },
    baseframe: {
        valType: 'string',
        
        
    },
    data: {
        valType: 'any',
        
        
    },
    layout: {
        valType: 'any',
        
        
    }
};

},{}],771:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// projection names to d3 function name
exports.projNames = {
    // d3.geo.projection
    'equirectangular': 'equirectangular',
    'mercator': 'mercator',
    'orthographic': 'orthographic',
    'natural earth': 'naturalEarth',
    'kavrayskiy7': 'kavrayskiy7',
    'miller': 'miller',
    'robinson': 'robinson',
    'eckert4': 'eckert4',
    'azimuthal equal area': 'azimuthalEqualArea',
    'azimuthal equidistant': 'azimuthalEquidistant',
    'conic equal area': 'conicEqualArea',
    'conic conformal': 'conicConformal',
    'conic equidistant': 'conicEquidistant',
    'gnomonic': 'gnomonic',
    'stereographic': 'stereographic',
    'mollweide': 'mollweide',
    'hammer': 'hammer',
    'transverse mercator': 'transverseMercator',
    'albers usa': 'albersUsa',
    'winkel tripel': 'winkel3',
    'aitoff': 'aitoff',
    'sinusoidal': 'sinusoidal'
};

// name of the axes
exports.axesNames = ['lonaxis', 'lataxis'];

// max longitudinal angular span (EXPERIMENTAL)
exports.lonaxisSpan = {
    'orthographic': 180,
    'azimuthal equal area': 360,
    'azimuthal equidistant': 360,
    'conic conformal': 180,
    'gnomonic': 160,
    'stereographic': 180,
    'transverse mercator': 180,
    '*': 360
};

// max latitudinal angular span (EXPERIMENTAL)
exports.lataxisSpan = {
    'conic conformal': 150,
    'stereographic': 179.5,
    '*': 180
};

// defaults for each scope
exports.scopeDefaults = {
    world: {
        lonaxisRange: [-180, 180],
        lataxisRange: [-90, 90],
        projType: 'equirectangular',
        projRotate: [0, 0, 0]
    },
    usa: {
        lonaxisRange: [-180, -50],
        lataxisRange: [15, 80],
        projType: 'albers usa'
    },
    europe: {
        lonaxisRange: [-30, 60],
        lataxisRange: [30, 85],
        projType: 'conic conformal',
        projRotate: [15, 0, 0],
        projParallels: [0, 60]
    },
    asia: {
        lonaxisRange: [22, 160],
        lataxisRange: [-15, 55],
        projType: 'mercator',
        projRotate: [0, 0, 0]
    },
    africa: {
        lonaxisRange: [-30, 60],
        lataxisRange: [-40, 40],
        projType: 'mercator',
        projRotate: [0, 0, 0]
    },
    'north america': {
        lonaxisRange: [-180, -45],
        lataxisRange: [5, 85],
        projType: 'conic conformal',
        projRotate: [-100, 0, 0],
        projParallels: [29.5, 45.5]
    },
    'south america': {
        lonaxisRange: [-100, -30],
        lataxisRange: [-60, 15],
        projType: 'mercator',
        projRotate: [0, 0, 0]
    }
};

// angular pad to avoid rounding error around clip angles
exports.clipPad = 1e-3;

// map projection precision
exports.precision = 0.1;

// default land and water fill colors
exports.landColor = '#F0DC82';
exports.waterColor = '#3399FF';

// locationmode to layer name
exports.locationmodeToLayer = {
    'ISO-3': 'countries',
    'USA-states': 'subunits',
    'country names': 'countries'
};

// SVG element for a sphere (use to frame maps)
exports.sphereSVG = {type: 'Sphere'};

// N.B. base layer names must be the same as in the topojson files

// base layer with a fill color
exports.fillLayers = {
    ocean: 1,
    land: 1,
    lakes: 1
};

// base layer with a only a line color
exports.lineLayers = {
    subunits: 1,
    countries: 1,
    coastlines: 1,
    rivers: 1,
    frame: 1
};

exports.layers = [
    'bg',
    'ocean', 'land', 'lakes',
    'subunits', 'countries', 'coastlines', 'rivers',
    'lataxis', 'lonaxis', 'frame',
    'backplot',
    'frontplot'
];

exports.layersForChoropleth = [
    'bg',
    'ocean', 'land',
    'subunits', 'countries', 'coastlines',
    'lataxis', 'lonaxis', 'frame',
    'backplot',
    'rivers', 'lakes',
    'frontplot'
];

exports.layerNameToAdjective = {
    ocean: 'ocean',
    land: 'land',
    lakes: 'lake',
    subunits: 'subunit',
    countries: 'country',
    coastlines: 'coastline',
    rivers: 'river',
    frame: 'frame'
};

},{}],772:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/* global PlotlyGeoAssets:false */

var d3 = _dereq_('d3');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Color = _dereq_('../../components/color');
var Drawing = _dereq_('../../components/drawing');
var Fx = _dereq_('../../components/fx');
var Plots = _dereq_('../plots');
var Axes = _dereq_('../cartesian/axes');
var dragElement = _dereq_('../../components/dragelement');
var prepSelect = _dereq_('../cartesian/select').prepSelect;
var selectOnClick = _dereq_('../cartesian/select').selectOnClick;

var createGeoZoom = _dereq_('./zoom');
var constants = _dereq_('./constants');

var topojsonUtils = _dereq_('../../lib/topojson_utils');
var topojsonFeature = _dereq_('topojson-client').feature;

_dereq_('./projections')(d3);

function Geo(opts) {
    this.id = opts.id;
    this.graphDiv = opts.graphDiv;
    this.container = opts.container;
    this.topojsonURL = opts.topojsonURL;
    this.isStatic = opts.staticPlot;

    this.topojsonName = null;
    this.topojson = null;

    this.projection = null;
    this.viewInitial = null;
    this.fitScale = null;
    this.bounds = null;
    this.midPt = null;

    this.hasChoropleth = false;
    this.traceHash = {};

    this.layers = {};
    this.basePaths = {};
    this.dataPaths = {};
    this.dataPoints = {};

    this.clipDef = null;
    this.clipRect = null;
    this.bgRect = null;

    this.makeFramework();
}

var proto = Geo.prototype;

module.exports = function createGeo(opts) {
    return new Geo(opts);
};

proto.plot = function(geoCalcData, fullLayout, promises) {
    var _this = this;
    var geoLayout = fullLayout[this.id];
    var topojsonNameNew = topojsonUtils.getTopojsonName(geoLayout);

    if(_this.topojson === null || topojsonNameNew !== _this.topojsonName) {
        _this.topojsonName = topojsonNameNew;

        if(PlotlyGeoAssets.topojson[_this.topojsonName] === undefined) {
            promises.push(_this.fetchTopojson().then(function(topojson) {
                PlotlyGeoAssets.topojson[_this.topojsonName] = topojson;
                _this.topojson = topojson;
                _this.update(geoCalcData, fullLayout);
            }));
        } else {
            _this.topojson = PlotlyGeoAssets.topojson[_this.topojsonName];
            _this.update(geoCalcData, fullLayout);
        }
    } else {
        _this.update(geoCalcData, fullLayout);
    }
};

proto.fetchTopojson = function() {
    var topojsonPath = topojsonUtils.getTopojsonPath(
        this.topojsonURL,
        this.topojsonName
    );
    return new Promise(function(resolve, reject) {
        d3.json(topojsonPath, function(err, topojson) {
            if(err) {
                if(err.status === 404) {
                    return reject(new Error([
                        'plotly.js could not find topojson file at',
                        topojsonPath, '.',
                        'Make sure the *topojsonURL* plot config option',
                        'is set properly.'
                    ].join(' ')));
                } else {
                    return reject(new Error([
                        'unexpected error while fetching topojson file at',
                        topojsonPath
                    ].join(' ')));
                }
            }
            resolve(topojson);
        });
    });
};

proto.update = function(geoCalcData, fullLayout) {
    var geoLayout = fullLayout[this.id];

    var hasInvalidBounds = this.updateProjection(fullLayout, geoLayout);
    if(hasInvalidBounds) return;

    // important: maps with choropleth traces have a different layer order
    this.hasChoropleth = false;
    for(var i = 0; i < geoCalcData.length; i++) {
        if(geoCalcData[i][0].trace.type === 'choropleth') {
            this.hasChoropleth = true;
            break;
        }
    }

    if(!this.viewInitial) {
        this.saveViewInitial(geoLayout);
    }

    this.updateBaseLayers(fullLayout, geoLayout);
    this.updateDims(fullLayout, geoLayout);
    this.updateFx(fullLayout, geoLayout);

    Plots.generalUpdatePerTraceModule(this.graphDiv, this, geoCalcData, geoLayout);

    var scatterLayer = this.layers.frontplot.select('.scatterlayer');
    this.dataPoints.point = scatterLayer.selectAll('.point');
    this.dataPoints.text = scatterLayer.selectAll('text');
    this.dataPaths.line = scatterLayer.selectAll('.js-line');

    var choroplethLayer = this.layers.backplot.select('.choroplethlayer');
    this.dataPaths.choropleth = choroplethLayer.selectAll('path');

    this.render();
};

proto.updateProjection = function(fullLayout, geoLayout) {
    var gs = fullLayout._size;
    var domain = geoLayout.domain;
    var projLayout = geoLayout.projection;
    var rotation = projLayout.rotation || {};
    var center = geoLayout.center || {};

    var projection = this.projection = getProjection(geoLayout);

    // set 'pre-fit' projection
    projection
        .center([center.lon - rotation.lon, center.lat - rotation.lat])
        .rotate([-rotation.lon, -rotation.lat, rotation.roll])
        .parallels(projLayout.parallels);

    // setup subplot extent [[x0,y0], [x1,y1]]
    var extent = [[
        gs.l + gs.w * domain.x[0],
        gs.t + gs.h * (1 - domain.y[1])
    ], [
        gs.l + gs.w * domain.x[1],
        gs.t + gs.h * (1 - domain.y[0])
    ]];

    var lonaxis = geoLayout.lonaxis;
    var lataxis = geoLayout.lataxis;
    var rangeBox = makeRangeBox(lonaxis.range, lataxis.range);

    // fit projection 'scale' and 'translate' to set lon/lat ranges
    projection.fitExtent(extent, rangeBox);

    var b = this.bounds = projection.getBounds(rangeBox);
    var s = this.fitScale = projection.scale();
    var t = projection.translate();

    if(
        !isFinite(b[0][0]) || !isFinite(b[0][1]) ||
        !isFinite(b[1][0]) || !isFinite(b[1][1]) ||
        isNaN(t[0]) || isNaN(t[0])
    ) {
        var gd = this.graphDiv;
        var attrToUnset = ['projection.rotation', 'center', 'lonaxis.range', 'lataxis.range'];
        var msg = 'Invalid geo settings, relayout\'ing to default view.';
        var updateObj = {};

        // clear all attribute that could cause invalid bounds,
        // clear viewInitial to update reset-view behavior

        for(var i = 0; i < attrToUnset.length; i++) {
            updateObj[this.id + '.' + attrToUnset[i]] = null;
        }

        this.viewInitial = null;

        Lib.warn(msg);
        gd._promises.push(Registry.call('relayout', gd, updateObj));
        return msg;
    }

    // px coordinates of view mid-point,
    // useful to update `geo.center` after interactions
    var midPt = this.midPt = [
        (b[0][0] + b[1][0]) / 2,
        (b[0][1] + b[1][1]) / 2
    ];

    // adjust projection to user setting
    projection
        .scale(projLayout.scale * s)
        .translate([t[0] + (midPt[0] - t[0]), t[1] + (midPt[1] - t[1])])
        .clipExtent(b);

    // the 'albers usa' projection does not expose a 'center' method
    // so here's this hack to make it respond to 'geoLayout.center'
    if(geoLayout._isAlbersUsa) {
        var centerPx = projection([center.lon, center.lat]);
        var tt = projection.translate();

        projection.translate([
            tt[0] - (centerPx[0] - tt[0]),
            tt[1] - (centerPx[1] - tt[1])
        ]);
    }
};

proto.updateBaseLayers = function(fullLayout, geoLayout) {
    var _this = this;
    var topojson = _this.topojson;
    var layers = _this.layers;
    var basePaths = _this.basePaths;

    function isAxisLayer(d) {
        return (d === 'lonaxis' || d === 'lataxis');
    }

    function isLineLayer(d) {
        return Boolean(constants.lineLayers[d]);
    }

    function isFillLayer(d) {
        return Boolean(constants.fillLayers[d]);
    }

    var allLayers = this.hasChoropleth ?
        constants.layersForChoropleth :
        constants.layers;

    var layerData = allLayers.filter(function(d) {
        return (isLineLayer(d) || isFillLayer(d)) ? geoLayout['show' + d] :
            isAxisLayer(d) ? geoLayout[d].showgrid :
            true;
    });

    var join = _this.framework.selectAll('.layer')
        .data(layerData, String);

    join.exit().each(function(d) {
        delete layers[d];
        delete basePaths[d];
        d3.select(this).remove();
    });

    join.enter().append('g')
        .attr('class', function(d) { return 'layer ' + d; })
        .each(function(d) {
            var layer = layers[d] = d3.select(this);

            if(d === 'bg') {
                _this.bgRect = layer.append('rect')
                    .style('pointer-events', 'all');
            } else if(isAxisLayer(d)) {
                basePaths[d] = layer.append('path')
                    .style('fill', 'none');
            } else if(d === 'backplot') {
                layer.append('g')
                    .classed('choroplethlayer', true);
            } else if(d === 'frontplot') {
                layer.append('g')
                    .classed('scatterlayer', true);
            } else if(isLineLayer(d)) {
                basePaths[d] = layer.append('path')
                    .style('fill', 'none')
                    .style('stroke-miterlimit', 2);
            } else if(isFillLayer(d)) {
                basePaths[d] = layer.append('path')
                    .style('stroke', 'none');
            }
        });

    join.order();

    join.each(function(d) {
        var path = basePaths[d];
        var adj = constants.layerNameToAdjective[d];

        if(d === 'frame') {
            path.datum(constants.sphereSVG);
        } else if(isLineLayer(d) || isFillLayer(d)) {
            path.datum(topojsonFeature(topojson, topojson.objects[d]));
        } else if(isAxisLayer(d)) {
            path.datum(makeGraticule(d, geoLayout))
                .call(Color.stroke, geoLayout[d].gridcolor)
                .call(Drawing.dashLine, '', geoLayout[d].gridwidth);
        }

        if(isLineLayer(d)) {
            path.call(Color.stroke, geoLayout[adj + 'color'])
                .call(Drawing.dashLine, '', geoLayout[adj + 'width']);
        } else if(isFillLayer(d)) {
            path.call(Color.fill, geoLayout[adj + 'color']);
        }
    });
};

proto.updateDims = function(fullLayout, geoLayout) {
    var b = this.bounds;
    var hFrameWidth = (geoLayout.framewidth || 0) / 2;

    var l = b[0][0] - hFrameWidth;
    var t = b[0][1] - hFrameWidth;
    var w = b[1][0] - l + hFrameWidth;
    var h = b[1][1] - t + hFrameWidth;

    Drawing.setRect(this.clipRect, l, t, w, h);

    this.bgRect
        .call(Drawing.setRect, l, t, w, h)
        .call(Color.fill, geoLayout.bgcolor);

    this.xaxis._offset = l;
    this.xaxis._length = w;

    this.yaxis._offset = t;
    this.yaxis._length = h;
};

proto.updateFx = function(fullLayout, geoLayout) {
    var _this = this;
    var gd = _this.graphDiv;
    var bgRect = _this.bgRect;
    var dragMode = fullLayout.dragmode;
    var clickMode = fullLayout.clickmode;

    if(_this.isStatic) return;

    function zoomReset() {
        var viewInitial = _this.viewInitial;
        var updateObj = {};

        for(var k in viewInitial) {
            updateObj[_this.id + '.' + k] = viewInitial[k];
        }

        Registry.call('_guiRelayout', gd, updateObj);
        gd.emit('plotly_doubleclick', null);
    }

    function invert(lonlat) {
        return _this.projection.invert([
            lonlat[0] + _this.xaxis._offset,
            lonlat[1] + _this.yaxis._offset
        ]);
    }

    var fillRangeItems;

    if(dragMode === 'select') {
        fillRangeItems = function(eventData, poly) {
            var ranges = eventData.range = {};
            ranges[_this.id] = [
                invert([poly.xmin, poly.ymin]),
                invert([poly.xmax, poly.ymax])
            ];
        };
    } else if(dragMode === 'lasso') {
        fillRangeItems = function(eventData, poly, pts) {
            var dataPts = eventData.lassoPoints = {};
            dataPts[_this.id] = pts.filtered.map(invert);
        };
    }

    // Note: dragOptions is needed to be declared for all dragmodes because
    // it's the object that holds persistent selection state.
    var dragOptions = {
        element: _this.bgRect.node(),
        gd: gd,
        plotinfo: {
            id: _this.id,
            xaxis: _this.xaxis,
            yaxis: _this.yaxis,
            fillRangeItems: fillRangeItems
        },
        xaxes: [_this.xaxis],
        yaxes: [_this.yaxis],
        subplot: _this.id,
        clickFn: function(numClicks) {
            if(numClicks === 2) {
                fullLayout._zoomlayer.selectAll('.select-outline').remove();
            }
        }
    };

    if(dragMode === 'pan') {
        bgRect.node().onmousedown = null;
        bgRect.call(createGeoZoom(_this, geoLayout));
        bgRect.on('dblclick.zoom', zoomReset);
        if(!gd._context._scrollZoom.geo) {
            bgRect.on('wheel.zoom', null);
        }
    }
    else if(dragMode === 'select' || dragMode === 'lasso') {
        bgRect.on('.zoom', null);

        dragOptions.prepFn = function(e, startX, startY) {
            prepSelect(e, startX, startY, dragOptions, dragMode);
        };

        dragElement.init(dragOptions);
    }

    bgRect.on('mousemove', function() {
        var lonlat = _this.projection.invert(d3.mouse(this));

        if(!lonlat || isNaN(lonlat[0]) || isNaN(lonlat[1])) {
            return dragElement.unhover(gd, d3.event);
        }

        _this.xaxis.p2c = function() { return lonlat[0]; };
        _this.yaxis.p2c = function() { return lonlat[1]; };

        Fx.hover(gd, d3.event, _this.id);
    });

    bgRect.on('mouseout', function() {
        if(gd._dragging) return;
        dragElement.unhover(gd, d3.event);
    });

    bgRect.on('click', function() {
        // For select and lasso the dragElement is handling clicks
        if(dragMode !== 'select' && dragMode !== 'lasso') {
            if(clickMode.indexOf('select') > -1) {
                selectOnClick(d3.event, gd, [_this.xaxis], [_this.yaxis],
                  _this.id, dragOptions);
            }

            if(clickMode.indexOf('event') > -1) {
                // TODO: like pie and mapbox, this doesn't support right-click
                // actually this one is worse, as right-click starts a pan, or leaves
                // select in a weird state.
                // Also, only tangentially related, we should cancel hover during pan
                Fx.click(gd, d3.event);
            }
        }
    });
};

proto.makeFramework = function() {
    var _this = this;
    var gd = _this.graphDiv;
    var fullLayout = gd._fullLayout;
    var clipId = 'clip' + fullLayout._uid + _this.id;

    _this.clipDef = fullLayout._clips.append('clipPath')
        .attr('id', clipId);

    _this.clipRect = _this.clipDef.append('rect');

    _this.framework = d3.select(_this.container).append('g')
        .attr('class', 'geo ' + _this.id)
        .call(Drawing.setClipUrl, clipId, gd);

    // sane lonlat to px
    _this.project = function(v) {
        var px = _this.projection(v);
        return px ?
            [px[0] - _this.xaxis._offset, px[1] - _this.yaxis._offset] :
            [null, null];
    };

    _this.xaxis = {
        _id: 'x',
        c2p: function(v) { return _this.project(v)[0]; }
    };

    _this.yaxis = {
        _id: 'y',
        c2p: function(v) { return _this.project(v)[1]; }
    };

    // mock axis for hover formatting
    _this.mockAxis = {
        type: 'linear',
        showexponent: 'all',
        exponentformat: 'B'
    };
    Axes.setConvert(_this.mockAxis, fullLayout);
};

proto.saveViewInitial = function(geoLayout) {
    var center = geoLayout.center || {};
    var projLayout = geoLayout.projection;
    var rotation = projLayout.rotation || {};

    if(geoLayout._isScoped) {
        this.viewInitial = {
            'center.lon': center.lon,
            'center.lat': center.lat,
            'projection.scale': projLayout.scale
        };
    } else if(geoLayout._isClipped) {
        this.viewInitial = {
            'projection.scale': projLayout.scale,
            'projection.rotation.lon': rotation.lon,
            'projection.rotation.lat': rotation.lat
        };
    } else {
        this.viewInitial = {
            'center.lon': center.lon,
            'center.lat': center.lat,
            'projection.scale': projLayout.scale,
            'projection.rotation.lon': rotation.lon
        };
    }
};

// [hot code path] (re)draw all paths which depend on the projection
proto.render = function() {
    var projection = this.projection;
    var pathFn = projection.getPath();
    var k;

    function translatePoints(d) {
        var lonlatPx = projection(d.lonlat);
        return lonlatPx ?
            'translate(' + lonlatPx[0] + ',' + lonlatPx[1] + ')' :
             null;
    }

    function hideShowPoints(d) {
        return projection.isLonLatOverEdges(d.lonlat) ? 'none' : null;
    }

    for(k in this.basePaths) {
        this.basePaths[k].attr('d', pathFn);
    }

    for(k in this.dataPaths) {
        this.dataPaths[k].attr('d', function(d) { return pathFn(d.geojson); });
    }

    for(k in this.dataPoints) {
        this.dataPoints[k]
            .attr('display', hideShowPoints)
            .attr('transform', translatePoints);
    }
};

// Helper that wraps d3.geo[/* projection name /*]() which:
//
// - adds 'fitExtent' (available in d3 v4)
// - adds 'getPath', 'getBounds' convenience methods
// - scopes logic related to 'clipAngle'
// - adds 'isLonLatOverEdges' method
// - sets projection precision
// - sets methods that aren't always defined depending
//   on the projection type to a dummy 'd3-esque' function,
//
// This wrapper alleviates subsequent code of (many) annoying if-statements.
function getProjection(geoLayout) {
    var projLayout = geoLayout.projection;
    var projType = projLayout.type;

    var projection = d3.geo[constants.projNames[projType]]();

    var clipAngle = geoLayout._isClipped ?
        constants.lonaxisSpan[projType] / 2 :
        null;

    var methods = ['center', 'rotate', 'parallels', 'clipExtent'];
    var dummyFn = function(_) { return _ ? projection : []; };

    for(var i = 0; i < methods.length; i++) {
        var m = methods[i];
        if(typeof projection[m] !== 'function') {
            projection[m] = dummyFn;
        }
    }

    projection.isLonLatOverEdges = function(lonlat) {
        if(projection(lonlat) === null) {
            return true;
        }

        if(clipAngle) {
            var r = projection.rotate();
            var angle = d3.geo.distance(lonlat, [-r[0], -r[1]]);
            var maxAngle = clipAngle * Math.PI / 180;
            return angle > maxAngle;
        } else {
            return false;
        }
    };

    projection.getPath = function() {
        return d3.geo.path().projection(projection);
    };

    projection.getBounds = function(object) {
        return projection.getPath().bounds(object);
    };

    // adapted from d3 v4:
    // https://github.com/d3/d3-geo/blob/master/src/projection/fit.js
    projection.fitExtent = function(extent, object) {
        var w = extent[1][0] - extent[0][0];
        var h = extent[1][1] - extent[0][1];
        var clip = projection.clipExtent && projection.clipExtent();

        projection
            .scale(150)
            .translate([0, 0]);

        if(clip) projection.clipExtent(null);

        var b = projection.getBounds(object);
        var k = Math.min(w / (b[1][0] - b[0][0]), h / (b[1][1] - b[0][1]));
        var x = +extent[0][0] + (w - k * (b[1][0] + b[0][0])) / 2;
        var y = +extent[0][1] + (h - k * (b[1][1] + b[0][1])) / 2;

        if(clip) projection.clipExtent(clip);

        return projection
            .scale(k * 150)
            .translate([x, y]);
    };

    projection.precision(constants.precision);

    if(clipAngle) {
        projection.clipAngle(clipAngle - constants.clipPad);
    }

    return projection;
}

function makeGraticule(axisName, geoLayout) {
    var axisLayout = geoLayout[axisName];
    var dtick = axisLayout.dtick;
    var scopeDefaults = constants.scopeDefaults[geoLayout.scope];
    var lonaxisRange = scopeDefaults.lonaxisRange;
    var lataxisRange = scopeDefaults.lataxisRange;
    var step = axisName === 'lonaxis' ? [dtick] : [0, dtick];

    return d3.geo.graticule()
        .extent([
            [lonaxisRange[0], lataxisRange[0]],
            [lonaxisRange[1], lataxisRange[1]]
        ])
        .step(step);
}

// Returns polygon GeoJSON corresponding to lon/lat range box
// with well-defined direction
//
// Note that clipPad padding is added around range to avoid aliasing.
function makeRangeBox(lon, lat) {
    var clipPad = constants.clipPad;
    var lon0 = lon[0] + clipPad;
    var lon1 = lon[1] - clipPad;
    var lat0 = lat[0] + clipPad;
    var lat1 = lat[1] - clipPad;

    // to cross antimeridian w/o ambiguity
    if(lon0 > 0 && lon1 < 0) lon1 += 360;

    var dlon4 = (lon1 - lon0) / 4;

    return {
        type: 'Polygon',
        coordinates: [[
            [lon0, lat0],
            [lon0, lat1],
            [lon0 + dlon4, lat1],
            [lon0 + 2 * dlon4, lat1],
            [lon0 + 3 * dlon4, lat1],
            [lon1, lat1],
            [lon1, lat0],
            [lon1 - dlon4, lat0],
            [lon1 - 2 * dlon4, lat0],
            [lon1 - 3 * dlon4, lat0],
            [lon0, lat0]
        ]]
    };
}

},{"../../components/color":571,"../../components/dragelement":589,"../../components/drawing":592,"../../components/fx":610,"../../lib":694,"../../lib/topojson_utils":721,"../../registry":825,"../cartesian/axes":742,"../cartesian/select":760,"../plots":806,"./constants":771,"./projections":777,"./zoom":778,"d3":149,"topojson-client":518}],773:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var createGeo = _dereq_('./geo');
var getSubplotCalcData = _dereq_('../../plots/get_data').getSubplotCalcData;
var counterRegex = _dereq_('../../lib').counterRegex;

var GEO = 'geo';

exports.name = GEO;

exports.attr = GEO;

exports.idRoot = GEO;

exports.idRegex = exports.attrRegex = counterRegex(GEO);

exports.attributes = _dereq_('./layout/attributes');

exports.layoutAttributes = _dereq_('./layout/layout_attributes');

exports.supplyLayoutDefaults = _dereq_('./layout/defaults');

exports.plot = function plotGeo(gd) {
    var fullLayout = gd._fullLayout;
    var calcData = gd.calcdata;
    var geoIds = fullLayout._subplots[GEO];

    /**
     * If 'plotly-geo-assets.js' is not included,
     * initialize object to keep reference to every loaded topojson
     */
    if(window.PlotlyGeoAssets === undefined) {
        window.PlotlyGeoAssets = {topojson: {}};
    }

    for(var i = 0; i < geoIds.length; i++) {
        var geoId = geoIds[i];
        var geoCalcData = getSubplotCalcData(calcData, GEO, geoId);
        var geoLayout = fullLayout[geoId];
        var geo = geoLayout._subplot;

        if(!geo) {
            geo = createGeo({
                id: geoId,
                graphDiv: gd,
                container: fullLayout._geolayer.node(),
                topojsonURL: gd._context.topojsonURL,
                staticPlot: gd._context.staticPlot
            });

            fullLayout[geoId]._subplot = geo;
        }

        geo.plot(geoCalcData, fullLayout, gd._promises);
    }
};

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var oldGeoKeys = oldFullLayout._subplots[GEO] || [];

    for(var i = 0; i < oldGeoKeys.length; i++) {
        var oldGeoKey = oldGeoKeys[i];
        var oldGeo = oldFullLayout[oldGeoKey]._subplot;

        if(!newFullLayout[oldGeoKey] && !!oldGeo) {
            oldGeo.framework.remove();
            oldGeo.clipDef.remove();
        }
    }
};

exports.updateFx = function(gd) {
    var fullLayout = gd._fullLayout;
    var subplotIds = fullLayout._subplots[GEO];

    for(var i = 0; i < subplotIds.length; i++) {
        var subplotLayout = fullLayout[subplotIds[i]];
        var subplotObj = subplotLayout._subplot;
        subplotObj.updateFx(fullLayout, subplotLayout);
    }
};

},{"../../lib":694,"../../plots/get_data":779,"./geo":772,"./layout/attributes":774,"./layout/defaults":775,"./layout/layout_attributes":776}],774:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    geo: {
        valType: 'subplotid',
        
        dflt: 'geo',
        editType: 'calc',
        
    }
};

},{}],775:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var handleSubplotDefaults = _dereq_('../../subplot_defaults');
var constants = _dereq_('../constants');
var layoutAttributes = _dereq_('./layout_attributes');

var axesNames = constants.axesNames;

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
    handleSubplotDefaults(layoutIn, layoutOut, fullData, {
        type: 'geo',
        attributes: layoutAttributes,
        handleDefaults: handleGeoDefaults,
        partition: 'y'
    });
};

function handleGeoDefaults(geoLayoutIn, geoLayoutOut, coerce) {
    var show;

    var resolution = coerce('resolution');
    var scope = coerce('scope');
    var scopeParams = constants.scopeDefaults[scope];

    var projType = coerce('projection.type', scopeParams.projType);
    var isAlbersUsa = geoLayoutOut._isAlbersUsa = projType === 'albers usa';

    // no other scopes are allowed for 'albers usa' projection
    if(isAlbersUsa) scope = geoLayoutOut.scope = 'usa';

    var isScoped = geoLayoutOut._isScoped = (scope !== 'world');
    var isConic = geoLayoutOut._isConic = projType.indexOf('conic') !== -1;
    geoLayoutOut._isClipped = !!constants.lonaxisSpan[projType];

    for(var i = 0; i < axesNames.length; i++) {
        var axisName = axesNames[i];
        var dtickDflt = [30, 10][i];
        var rangeDflt;

        if(isScoped) {
            rangeDflt = scopeParams[axisName + 'Range'];
        } else {
            var dfltSpans = constants[axisName + 'Span'];
            var hSpan = (dfltSpans[projType] || dfltSpans['*']) / 2;
            var rot = coerce(
                'projection.rotation.' + axisName.substr(0, 3),
                scopeParams.projRotate[i]
            );
            rangeDflt = [rot - hSpan, rot + hSpan];
        }

        var range = coerce(axisName + '.range', rangeDflt);

        coerce(axisName + '.tick0', range[0]);
        coerce(axisName + '.dtick', dtickDflt);

        show = coerce(axisName + '.showgrid');
        if(show) {
            coerce(axisName + '.gridcolor');
            coerce(axisName + '.gridwidth');
        }
    }

    var lonRange = geoLayoutOut.lonaxis.range;
    var latRange = geoLayoutOut.lataxis.range;

    // to cross antimeridian w/o ambiguity
    var lon0 = lonRange[0];
    var lon1 = lonRange[1];
    if(lon0 > 0 && lon1 < 0) lon1 += 360;

    var centerLon = (lon0 + lon1) / 2;
    var projLon;

    if(!isAlbersUsa) {
        var dfltProjRotate = isScoped ? scopeParams.projRotate : [centerLon, 0, 0];

        projLon = coerce('projection.rotation.lon', dfltProjRotate[0]);
        coerce('projection.rotation.lat', dfltProjRotate[1]);
        coerce('projection.rotation.roll', dfltProjRotate[2]);

        show = coerce('showcoastlines', !isScoped);
        if(show) {
            coerce('coastlinecolor');
            coerce('coastlinewidth');
        }

        show = coerce('showocean');
        if(show) coerce('oceancolor');
    }

    var centerLonDflt;
    var centerLatDflt;

    if(isAlbersUsa) {
        // 'albers usa' does not have a 'center',
        // these values were found using via:
        //   projection.invert([geoLayout.center.lon, geoLayoutIn.center.lat])
        centerLonDflt = -96.6;
        centerLatDflt = 38.7;
    } else {
        centerLonDflt = isScoped ? centerLon : projLon;
        centerLatDflt = (latRange[0] + latRange[1]) / 2;
    }

    coerce('center.lon', centerLonDflt);
    coerce('center.lat', centerLatDflt);

    if(isConic) {
        var dfltProjParallels = scopeParams.projParallels || [0, 60];
        coerce('projection.parallels', dfltProjParallels);
    }

    coerce('projection.scale');

    show = coerce('showland');
    if(show) coerce('landcolor');

    show = coerce('showlakes');
    if(show) coerce('lakecolor');

    show = coerce('showrivers');
    if(show) {
        coerce('rivercolor');
        coerce('riverwidth');
    }

    show = coerce('showcountries', isScoped && scope !== 'usa');
    if(show) {
        coerce('countrycolor');
        coerce('countrywidth');
    }

    if(scope === 'usa' || (scope === 'north america' && resolution === 50)) {
        // Only works for:
        //   USA states at 110m
        //   USA states + Canada provinces at 50m
        coerce('showsubunits', true);
        coerce('subunitcolor');
        coerce('subunitwidth');
    }

    if(!isScoped) {
        // Does not work in non-world scopes
        show = coerce('showframe', true);
        if(show) {
            coerce('framecolor');
            coerce('framewidth');
        }
    }

    coerce('bgcolor');
}

},{"../../subplot_defaults":820,"../constants":771,"./layout_attributes":776}],776:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorAttrs = _dereq_('../../../components/color/attributes');
var domainAttrs = _dereq_('../../domain').attributes;
var constants = _dereq_('../constants');
var overrideAll = _dereq_('../../../plot_api/edit_types').overrideAll;

var geoAxesAttrs = {
    range: {
        valType: 'info_array',
        
        items: [
            {valType: 'number'},
            {valType: 'number'}
        ],
        
    },
    showgrid: {
        valType: 'boolean',
        
        dflt: false,
        
    },
    tick0: {
        valType: 'number',
        
        
    },
    dtick: {
        valType: 'number',
        
        
    },
    gridcolor: {
        valType: 'color',
        
        dflt: colorAttrs.lightLine,
        
    },
    gridwidth: {
        valType: 'number',
        
        min: 0,
        dflt: 1,
        
    }
};

var attrs = module.exports = overrideAll({
    domain: domainAttrs({name: 'geo'}, {
        
    }),

    resolution: {
        valType: 'enumerated',
        values: [110, 50],
        
        dflt: 110,
        coerceNumber: true,
        
    },
    scope: {
        valType: 'enumerated',
        
        values: Object.keys(constants.scopeDefaults),
        dflt: 'world',
        
    },
    projection: {
        type: {
            valType: 'enumerated',
            
            values: Object.keys(constants.projNames),
            
        },
        rotation: {
            lon: {
                valType: 'number',
                
                
            },
            lat: {
                valType: 'number',
                
                
            },
            roll: {
                valType: 'number',
                
                
            }
        },
        parallels: {
            valType: 'info_array',
            
            items: [
                {valType: 'number'},
                {valType: 'number'}
            ],
            
        },
        scale: {
            valType: 'number',
            
            min: 0,
            dflt: 1,
            
        },
    },
    center: {
        lon: {
            valType: 'number',
            
            
        },
        lat: {
            valType: 'number',
            
            
        }
    },
    showcoastlines: {
        valType: 'boolean',
        
        
    },
    coastlinecolor: {
        valType: 'color',
        
        dflt: colorAttrs.defaultLine,
        
    },
    coastlinewidth: {
        valType: 'number',
        
        min: 0,
        dflt: 1,
        
    },
    showland: {
        valType: 'boolean',
        
        dflt: false,
        
    },
    landcolor: {
        valType: 'color',
        
        dflt: constants.landColor,
        
    },
    showocean: {
        valType: 'boolean',
        
        dflt: false,
        
    },
    oceancolor: {
        valType: 'color',
        
        dflt: constants.waterColor,
        
    },
    showlakes: {
        valType: 'boolean',
        
        dflt: false,
        
    },
    lakecolor: {
        valType: 'color',
        
        dflt: constants.waterColor,
        
    },
    showrivers: {
        valType: 'boolean',
        
        dflt: false,
        
    },
    rivercolor: {
        valType: 'color',
        
        dflt: constants.waterColor,
        
    },
    riverwidth: {
        valType: 'number',
        
        min: 0,
        dflt: 1,
        
    },
    showcountries: {
        valType: 'boolean',
        
        
    },
    countrycolor: {
        valType: 'color',
        
        dflt: colorAttrs.defaultLine,
        
    },
    countrywidth: {
        valType: 'number',
        
        min: 0,
        dflt: 1,
        
    },
    showsubunits: {
        valType: 'boolean',
        
        
    },
    subunitcolor: {
        valType: 'color',
        
        dflt: colorAttrs.defaultLine,
        
    },
    subunitwidth: {
        valType: 'number',
        
        min: 0,
        dflt: 1,
        
    },
    showframe: {
        valType: 'boolean',
        
        
    },
    framecolor: {
        valType: 'color',
        
        dflt: colorAttrs.defaultLine,
        
    },
    framewidth: {
        valType: 'number',
        
        min: 0,
        dflt: 1,
        
    },
    bgcolor: {
        valType: 'color',
        
        dflt: colorAttrs.background,
        
    },
    lonaxis: geoAxesAttrs,
    lataxis: geoAxesAttrs
}, 'plot', 'from-root');

// set uirevision outside of overrideAll so it can be `editType: 'none'`
attrs.uirevision = {
    valType: 'any',
    
    editType: 'none',
    
};

},{"../../../components/color/attributes":570,"../../../plot_api/edit_types":725,"../../domain":768,"../constants":771}],777:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

/*
 * Generated by https://github.com/etpinard/d3-geo-projection-picker
 *
 * which is hand-picks projection from https://github.com/d3/d3-geo-projection
 *
 * into a CommonJS require-able module.
 */

'use strict';

/* eslint-disable */

function addProjectionsToD3(d3) {
  d3.geo.project = function(object, projection) {
    var stream = projection.stream;
    if (!stream) throw new Error("not yet supported");
    return (object && d3_geo_projectObjectType.hasOwnProperty(object.type) ? d3_geo_projectObjectType[object.type] : d3_geo_projectGeometry)(object, stream);
  };
  function d3_geo_projectFeature(object, stream) {
    return {
      type: "Feature",
      id: object.id,
      properties: object.properties,
      geometry: d3_geo_projectGeometry(object.geometry, stream)
    };
  }
  function d3_geo_projectGeometry(geometry, stream) {
    if (!geometry) return null;
    if (geometry.type === "GeometryCollection") return {
      type: "GeometryCollection",
      geometries: object.geometries.map(function(geometry) {
        return d3_geo_projectGeometry(geometry, stream);
      })
    };
    if (!d3_geo_projectGeometryType.hasOwnProperty(geometry.type)) return null;
    var sink = d3_geo_projectGeometryType[geometry.type];
    d3.geo.stream(geometry, stream(sink));
    return sink.result();
  }
  var d3_geo_projectObjectType = {
    Feature: d3_geo_projectFeature,
    FeatureCollection: function(object, stream) {
      return {
        type: "FeatureCollection",
        features: object.features.map(function(feature) {
          return d3_geo_projectFeature(feature, stream);
        })
      };
    }
  };
  var d3_geo_projectPoints = [], d3_geo_projectLines = [];
  var d3_geo_projectPoint = {
    point: function(x, y) {
      d3_geo_projectPoints.push([ x, y ]);
    },
    result: function() {
      var result = !d3_geo_projectPoints.length ? null : d3_geo_projectPoints.length < 2 ? {
        type: "Point",
        coordinates: d3_geo_projectPoints[0]
      } : {
        type: "MultiPoint",
        coordinates: d3_geo_projectPoints
      };
      d3_geo_projectPoints = [];
      return result;
    }
  };
  var d3_geo_projectLine = {
    lineStart: d3_geo_projectNoop,
    point: function(x, y) {
      d3_geo_projectPoints.push([ x, y ]);
    },
    lineEnd: function() {
      if (d3_geo_projectPoints.length) d3_geo_projectLines.push(d3_geo_projectPoints),
      d3_geo_projectPoints = [];
    },
    result: function() {
      var result = !d3_geo_projectLines.length ? null : d3_geo_projectLines.length < 2 ? {
        type: "LineString",
        coordinates: d3_geo_projectLines[0]
      } : {
        type: "MultiLineString",
        coordinates: d3_geo_projectLines
      };
      d3_geo_projectLines = [];
      return result;
    }
  };
  var d3_geo_projectPolygon = {
    polygonStart: d3_geo_projectNoop,
    lineStart: d3_geo_projectNoop,
    point: function(x, y) {
      d3_geo_projectPoints.push([ x, y ]);
    },
    lineEnd: function() {
      var n = d3_geo_projectPoints.length;
      if (n) {
        do d3_geo_projectPoints.push(d3_geo_projectPoints[0].slice()); while (++n < 4);
        d3_geo_projectLines.push(d3_geo_projectPoints), d3_geo_projectPoints = [];
      }
    },
    polygonEnd: d3_geo_projectNoop,
    result: function() {
      if (!d3_geo_projectLines.length) return null;
      var polygons = [], holes = [];
      d3_geo_projectLines.forEach(function(ring) {
        if (d3_geo_projectClockwise(ring)) polygons.push([ ring ]); else holes.push(ring);
      });
      holes.forEach(function(hole) {
        var point = hole[0];
        polygons.some(function(polygon) {
          if (d3_geo_projectContains(polygon[0], point)) {
            polygon.push(hole);
            return true;
          }
        }) || polygons.push([ hole ]);
      });
      d3_geo_projectLines = [];
      return !polygons.length ? null : polygons.length > 1 ? {
        type: "MultiPolygon",
        coordinates: polygons
      } : {
        type: "Polygon",
        coordinates: polygons[0]
      };
    }
  };
  var d3_geo_projectGeometryType = {
    Point: d3_geo_projectPoint,
    MultiPoint: d3_geo_projectPoint,
    LineString: d3_geo_projectLine,
    MultiLineString: d3_geo_projectLine,
    Polygon: d3_geo_projectPolygon,
    MultiPolygon: d3_geo_projectPolygon,
    Sphere: d3_geo_projectPolygon
  };
  function d3_geo_projectNoop() {}
  function d3_geo_projectClockwise(ring) {
    if ((n = ring.length) < 4) return false;
    var i = 0, n, area = ring[n - 1][1] * ring[0][0] - ring[n - 1][0] * ring[0][1];
    while (++i < n) area += ring[i - 1][1] * ring[i][0] - ring[i - 1][0] * ring[i][1];
    return area <= 0;
  }
  function d3_geo_projectContains(ring, point) {
    var x = point[0], y = point[1], contains = false;
    for (var i = 0, n = ring.length, j = n - 1; i < n; j = i++) {
      var pi = ring[i], xi = pi[0], yi = pi[1], pj = ring[j], xj = pj[0], yj = pj[1];
      if (yi > y ^ yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi) contains = !contains;
    }
    return contains;
  }
  var ε = 1e-6, ε2 = ε * ε, π = Math.PI, halfπ = π / 2, sqrtπ = Math.sqrt(π), radians = π / 180, degrees = 180 / π;
  function sinci(x) {
    return x ? x / Math.sin(x) : 1;
  }
  function sgn(x) {
    return x > 0 ? 1 : x < 0 ? -1 : 0;
  }
  function asin(x) {
    return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x);
  }
  function acos(x) {
    return x > 1 ? 0 : x < -1 ? π : Math.acos(x);
  }
  function asqrt(x) {
    return x > 0 ? Math.sqrt(x) : 0;
  }
  var projection = d3.geo.projection, projectionMutator = d3.geo.projectionMutator;
  d3.geo.interrupt = function(project) {
    var lobes = [ [ [ [ -π, 0 ], [ 0, halfπ ], [ π, 0 ] ] ], [ [ [ -π, 0 ], [ 0, -halfπ ], [ π, 0 ] ] ] ];
    var bounds;
    function forward(λ, φ) {
      var sign = φ < 0 ? -1 : +1, hemilobes = lobes[+(φ < 0)];
      for (var i = 0, n = hemilobes.length - 1; i < n && λ > hemilobes[i][2][0]; ++i) ;
      var coordinates = project(λ - hemilobes[i][1][0], φ);
      coordinates[0] += project(hemilobes[i][1][0], sign * φ > sign * hemilobes[i][0][1] ? hemilobes[i][0][1] : φ)[0];
      return coordinates;
    }
    function reset() {
      bounds = lobes.map(function(hemilobes) {
        return hemilobes.map(function(lobe) {
          var x0 = project(lobe[0][0], lobe[0][1])[0], x1 = project(lobe[2][0], lobe[2][1])[0], y0 = project(lobe[1][0], lobe[0][1])[1], y1 = project(lobe[1][0], lobe[1][1])[1], t;
          if (y0 > y1) t = y0, y0 = y1, y1 = t;
          return [ [ x0, y0 ], [ x1, y1 ] ];
        });
      });
    }
    if (project.invert) forward.invert = function(x, y) {
      var hemibounds = bounds[+(y < 0)], hemilobes = lobes[+(y < 0)];
      for (var i = 0, n = hemibounds.length; i < n; ++i) {
        var b = hemibounds[i];
        if (b[0][0] <= x && x < b[1][0] && b[0][1] <= y && y < b[1][1]) {
          var coordinates = project.invert(x - project(hemilobes[i][1][0], 0)[0], y);
          coordinates[0] += hemilobes[i][1][0];
          return pointEqual(forward(coordinates[0], coordinates[1]), [ x, y ]) ? coordinates : null;
        }
      }
    };
    var projection = d3.geo.projection(forward), stream_ = projection.stream;
    projection.stream = function(stream) {
      var rotate = projection.rotate(), rotateStream = stream_(stream), sphereStream = (projection.rotate([ 0, 0 ]),
      stream_(stream));
      projection.rotate(rotate);
      rotateStream.sphere = function() {
        d3.geo.stream(sphere(), sphereStream);
      };
      return rotateStream;
    };
    projection.lobes = function(_) {
      if (!arguments.length) return lobes.map(function(lobes) {
        return lobes.map(function(lobe) {
          return [ [ lobe[0][0] * 180 / π, lobe[0][1] * 180 / π ], [ lobe[1][0] * 180 / π, lobe[1][1] * 180 / π ], [ lobe[2][0] * 180 / π, lobe[2][1] * 180 / π ] ];
        });
      });
      lobes = _.map(function(lobes) {
        return lobes.map(function(lobe) {
          return [ [ lobe[0][0] * π / 180, lobe[0][1] * π / 180 ], [ lobe[1][0] * π / 180, lobe[1][1] * π / 180 ], [ lobe[2][0] * π / 180, lobe[2][1] * π / 180 ] ];
        });
      });
      reset();
      return projection;
    };
    function sphere() {
      var ε = 1e-6, coordinates = [];
      for (var i = 0, n = lobes[0].length; i < n; ++i) {
        var lobe = lobes[0][i], λ0 = lobe[0][0] * 180 / π, φ0 = lobe[0][1] * 180 / π, φ1 = lobe[1][1] * 180 / π, λ2 = lobe[2][0] * 180 / π, φ2 = lobe[2][1] * 180 / π;
        coordinates.push(resample([ [ λ0 + ε, φ0 + ε ], [ λ0 + ε, φ1 - ε ], [ λ2 - ε, φ1 - ε ], [ λ2 - ε, φ2 + ε ] ], 30));
      }
      for (var i = lobes[1].length - 1; i >= 0; --i) {
        var lobe = lobes[1][i], λ0 = lobe[0][0] * 180 / π, φ0 = lobe[0][1] * 180 / π, φ1 = lobe[1][1] * 180 / π, λ2 = lobe[2][0] * 180 / π, φ2 = lobe[2][1] * 180 / π;
        coordinates.push(resample([ [ λ2 - ε, φ2 - ε ], [ λ2 - ε, φ1 + ε ], [ λ0 + ε, φ1 + ε ], [ λ0 + ε, φ0 - ε ] ], 30));
      }
      return {
        type: "Polygon",
        coordinates: [ d3.merge(coordinates) ]
      };
    }
    function resample(coordinates, m) {
      var i = -1, n = coordinates.length, p0 = coordinates[0], p1, dx, dy, resampled = [];
      while (++i < n) {
        p1 = coordinates[i];
        dx = (p1[0] - p0[0]) / m;
        dy = (p1[1] - p0[1]) / m;
        for (var j = 0; j < m; ++j) resampled.push([ p0[0] + j * dx, p0[1] + j * dy ]);
        p0 = p1;
      }
      resampled.push(p1);
      return resampled;
    }
    function pointEqual(a, b) {
      return Math.abs(a[0] - b[0]) < ε && Math.abs(a[1] - b[1]) < ε;
    }
    return projection;
  };
  function eckert4(λ, φ) {
    var k = (2 + halfπ) * Math.sin(φ);
    φ /= 2;
    for (var i = 0, δ = Infinity; i < 10 && Math.abs(δ) > ε; i++) {
      var cosφ = Math.cos(φ);
      φ -= δ = (φ + Math.sin(φ) * (cosφ + 2) - k) / (2 * cosφ * (1 + cosφ));
    }
    return [ 2 / Math.sqrt(π * (4 + π)) * λ * (1 + Math.cos(φ)), 2 * Math.sqrt(π / (4 + π)) * Math.sin(φ) ];
  }
  eckert4.invert = function(x, y) {
    var A = .5 * y * Math.sqrt((4 + π) / π), k = asin(A), c = Math.cos(k);
    return [ x / (2 / Math.sqrt(π * (4 + π)) * (1 + c)), asin((k + A * (c + 2)) / (2 + halfπ)) ];
  };
  (d3.geo.eckert4 = function() {
    return projection(eckert4);
  }).raw = eckert4;
  var hammerAzimuthalEqualArea = d3.geo.azimuthalEqualArea.raw;
  function hammer(A, B) {
    if (arguments.length < 2) B = A;
    if (B === 1) return hammerAzimuthalEqualArea;
    if (B === Infinity) return hammerQuarticAuthalic;
    function forward(λ, φ) {
      var coordinates = hammerAzimuthalEqualArea(λ / B, φ);
      coordinates[0] *= A;
      return coordinates;
    }
    forward.invert = function(x, y) {
      var coordinates = hammerAzimuthalEqualArea.invert(x / A, y);
      coordinates[0] *= B;
      return coordinates;
    };
    return forward;
  }
  function hammerProjection() {
    var B = 2, m = projectionMutator(hammer), p = m(B);
    p.coefficient = function(_) {
      if (!arguments.length) return B;
      return m(B = +_);
    };
    return p;
  }
  function hammerQuarticAuthalic(λ, φ) {
    return [ λ * Math.cos(φ) / Math.cos(φ /= 2), 2 * Math.sin(φ) ];
  }
  hammerQuarticAuthalic.invert = function(x, y) {
    var φ = 2 * asin(y / 2);
    return [ x * Math.cos(φ / 2) / Math.cos(φ), φ ];
  };
  (d3.geo.hammer = hammerProjection).raw = hammer;
  function kavrayskiy7(λ, φ) {
    return [ 3 * λ / (2 * π) * Math.sqrt(π * π / 3 - φ * φ), φ ];
  }
  kavrayskiy7.invert = function(x, y) {
    return [ 2 / 3 * π * x / Math.sqrt(π * π / 3 - y * y), y ];
  };
  (d3.geo.kavrayskiy7 = function() {
    return projection(kavrayskiy7);
  }).raw = kavrayskiy7;
  function miller(λ, φ) {
    return [ λ, 1.25 * Math.log(Math.tan(π / 4 + .4 * φ)) ];
  }
  miller.invert = function(x, y) {
    return [ x, 2.5 * Math.atan(Math.exp(.8 * y)) - .625 * π ];
  };
  (d3.geo.miller = function() {
    return projection(miller);
  }).raw = miller;
  function mollweideBromleyθ(Cp) {
    return function(θ) {
      var Cpsinθ = Cp * Math.sin(θ), i = 30, δ;
      do θ -= δ = (θ + Math.sin(θ) - Cpsinθ) / (1 + Math.cos(θ)); while (Math.abs(δ) > ε && --i > 0);
      return θ / 2;
    };
  }
  function mollweideBromley(Cx, Cy, Cp) {
    var θ = mollweideBromleyθ(Cp);
    function forward(λ, φ) {
      return [ Cx * λ * Math.cos(φ = θ(φ)), Cy * Math.sin(φ) ];
    }
    forward.invert = function(x, y) {
      var θ = asin(y / Cy);
      return [ x / (Cx * Math.cos(θ)), asin((2 * θ + Math.sin(2 * θ)) / Cp) ];
    };
    return forward;
  }
  var mollweideθ = mollweideBromleyθ(π), mollweide = mollweideBromley(Math.SQRT2 / halfπ, Math.SQRT2, π);
  (d3.geo.mollweide = function() {
    return projection(mollweide);
  }).raw = mollweide;
  function naturalEarth(λ, φ) {
    var φ2 = φ * φ, φ4 = φ2 * φ2;
    return [ λ * (.8707 - .131979 * φ2 + φ4 * (-.013791 + φ4 * (.003971 * φ2 - .001529 * φ4))), φ * (1.007226 + φ2 * (.015085 + φ4 * (-.044475 + .028874 * φ2 - .005916 * φ4))) ];
  }
  naturalEarth.invert = function(x, y) {
    var φ = y, i = 25, δ;
    do {
      var φ2 = φ * φ, φ4 = φ2 * φ2;
      φ -= δ = (φ * (1.007226 + φ2 * (.015085 + φ4 * (-.044475 + .028874 * φ2 - .005916 * φ4))) - y) / (1.007226 + φ2 * (.015085 * 3 + φ4 * (-.044475 * 7 + .028874 * 9 * φ2 - .005916 * 11 * φ4)));
    } while (Math.abs(δ) > ε && --i > 0);
    return [ x / (.8707 + (φ2 = φ * φ) * (-.131979 + φ2 * (-.013791 + φ2 * φ2 * φ2 * (.003971 - .001529 * φ2)))), φ ];
  };
  (d3.geo.naturalEarth = function() {
    return projection(naturalEarth);
  }).raw = naturalEarth;
  var robinsonConstants = [ [ .9986, -.062 ], [ 1, 0 ], [ .9986, .062 ], [ .9954, .124 ], [ .99, .186 ], [ .9822, .248 ], [ .973, .31 ], [ .96, .372 ], [ .9427, .434 ], [ .9216, .4958 ], [ .8962, .5571 ], [ .8679, .6176 ], [ .835, .6769 ], [ .7986, .7346 ], [ .7597, .7903 ], [ .7186, .8435 ], [ .6732, .8936 ], [ .6213, .9394 ], [ .5722, .9761 ], [ .5322, 1 ] ];
  robinsonConstants.forEach(function(d) {
    d[1] *= 1.0144;
  });
  function robinson(λ, φ) {
    var i = Math.min(18, Math.abs(φ) * 36 / π), i0 = Math.floor(i), di = i - i0, ax = (k = robinsonConstants[i0])[0], ay = k[1], bx = (k = robinsonConstants[++i0])[0], by = k[1], cx = (k = robinsonConstants[Math.min(19, ++i0)])[0], cy = k[1], k;
    return [ λ * (bx + di * (cx - ax) / 2 + di * di * (cx - 2 * bx + ax) / 2), (φ > 0 ? halfπ : -halfπ) * (by + di * (cy - ay) / 2 + di * di * (cy - 2 * by + ay) / 2) ];
  }
  robinson.invert = function(x, y) {
    var yy = y / halfπ, φ = yy * 90, i = Math.min(18, Math.abs(φ / 5)), i0 = Math.max(0, Math.floor(i));
    do {
      var ay = robinsonConstants[i0][1], by = robinsonConstants[i0 + 1][1], cy = robinsonConstants[Math.min(19, i0 + 2)][1], u = cy - ay, v = cy - 2 * by + ay, t = 2 * (Math.abs(yy) - by) / u, c = v / u, di = t * (1 - c * t * (1 - 2 * c * t));
      if (di >= 0 || i0 === 1) {
        φ = (y >= 0 ? 5 : -5) * (di + i);
        var j = 50, δ;
        do {
          i = Math.min(18, Math.abs(φ) / 5);
          i0 = Math.floor(i);
          di = i - i0;
          ay = robinsonConstants[i0][1];
          by = robinsonConstants[i0 + 1][1];
          cy = robinsonConstants[Math.min(19, i0 + 2)][1];
          φ -= (δ = (y >= 0 ? halfπ : -halfπ) * (by + di * (cy - ay) / 2 + di * di * (cy - 2 * by + ay) / 2) - y) * degrees;
        } while (Math.abs(δ) > ε2 && --j > 0);
        break;
      }
    } while (--i0 >= 0);
    var ax = robinsonConstants[i0][0], bx = robinsonConstants[i0 + 1][0], cx = robinsonConstants[Math.min(19, i0 + 2)][0];
    return [ x / (bx + di * (cx - ax) / 2 + di * di * (cx - 2 * bx + ax) / 2), φ * radians ];
  };
  (d3.geo.robinson = function() {
    return projection(robinson);
  }).raw = robinson;
  function sinusoidal(λ, φ) {
    return [ λ * Math.cos(φ), φ ];
  }
  sinusoidal.invert = function(x, y) {
    return [ x / Math.cos(y), y ];
  };
  (d3.geo.sinusoidal = function() {
    return projection(sinusoidal);
  }).raw = sinusoidal;
  function aitoff(λ, φ) {
    var cosφ = Math.cos(φ), sinciα = sinci(acos(cosφ * Math.cos(λ /= 2)));
    return [ 2 * cosφ * Math.sin(λ) * sinciα, Math.sin(φ) * sinciα ];
  }
  aitoff.invert = function(x, y) {
    if (x * x + 4 * y * y > π * π + ε) return;
    var λ = x, φ = y, i = 25;
    do {
      var sinλ = Math.sin(λ), sinλ_2 = Math.sin(λ / 2), cosλ_2 = Math.cos(λ / 2), sinφ = Math.sin(φ), cosφ = Math.cos(φ), sin_2φ = Math.sin(2 * φ), sin2φ = sinφ * sinφ, cos2φ = cosφ * cosφ, sin2λ_2 = sinλ_2 * sinλ_2, C = 1 - cos2φ * cosλ_2 * cosλ_2, E = C ? acos(cosφ * cosλ_2) * Math.sqrt(F = 1 / C) : F = 0, F, fx = 2 * E * cosφ * sinλ_2 - x, fy = E * sinφ - y, δxδλ = F * (cos2φ * sin2λ_2 + E * cosφ * cosλ_2 * sin2φ), δxδφ = F * (.5 * sinλ * sin_2φ - E * 2 * sinφ * sinλ_2), δyδλ = F * .25 * (sin_2φ * sinλ_2 - E * sinφ * cos2φ * sinλ), δyδφ = F * (sin2φ * cosλ_2 + E * sin2λ_2 * cosφ), denominator = δxδφ * δyδλ - δyδφ * δxδλ;
      if (!denominator) break;
      var δλ = (fy * δxδφ - fx * δyδφ) / denominator, δφ = (fx * δyδλ - fy * δxδλ) / denominator;
      λ -= δλ, φ -= δφ;
    } while ((Math.abs(δλ) > ε || Math.abs(δφ) > ε) && --i > 0);
    return [ λ, φ ];
  };
  (d3.geo.aitoff = function() {
    return projection(aitoff);
  }).raw = aitoff;
  function winkel3(λ, φ) {
    var coordinates = aitoff(λ, φ);
    return [ (coordinates[0] + λ / halfπ) / 2, (coordinates[1] + φ) / 2 ];
  }
  winkel3.invert = function(x, y) {
    var λ = x, φ = y, i = 25;
    do {
      var cosφ = Math.cos(φ), sinφ = Math.sin(φ), sin_2φ = Math.sin(2 * φ), sin2φ = sinφ * sinφ, cos2φ = cosφ * cosφ, sinλ = Math.sin(λ), cosλ_2 = Math.cos(λ / 2), sinλ_2 = Math.sin(λ / 2), sin2λ_2 = sinλ_2 * sinλ_2, C = 1 - cos2φ * cosλ_2 * cosλ_2, E = C ? acos(cosφ * cosλ_2) * Math.sqrt(F = 1 / C) : F = 0, F, fx = .5 * (2 * E * cosφ * sinλ_2 + λ / halfπ) - x, fy = .5 * (E * sinφ + φ) - y, δxδλ = .5 * F * (cos2φ * sin2λ_2 + E * cosφ * cosλ_2 * sin2φ) + .5 / halfπ, δxδφ = F * (sinλ * sin_2φ / 4 - E * sinφ * sinλ_2), δyδλ = .125 * F * (sin_2φ * sinλ_2 - E * sinφ * cos2φ * sinλ), δyδφ = .5 * F * (sin2φ * cosλ_2 + E * sin2λ_2 * cosφ) + .5, denominator = δxδφ * δyδλ - δyδφ * δxδλ, δλ = (fy * δxδφ - fx * δyδφ) / denominator, δφ = (fx * δyδλ - fy * δxδλ) / denominator;
      λ -= δλ, φ -= δφ;
    } while ((Math.abs(δλ) > ε || Math.abs(δφ) > ε) && --i > 0);
    return [ λ, φ ];
  };
  (d3.geo.winkel3 = function() {
    return projection(winkel3);
  }).raw = winkel3;
}

module.exports = addProjectionsToD3;

},{}],778:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var Lib = _dereq_('../../lib');
var Registry = _dereq_('../../registry');

var radians = Math.PI / 180;
var degrees = 180 / Math.PI;
var zoomstartStyle = {cursor: 'pointer'};
var zoomendStyle = {cursor: 'auto'};

function createGeoZoom(geo, geoLayout) {
    var projection = geo.projection;
    var zoomConstructor;

    if(geoLayout._isScoped) {
        zoomConstructor = zoomScoped;
    } else if(geoLayout._isClipped) {
        zoomConstructor = zoomClipped;
    } else {
        zoomConstructor = zoomNonClipped;
    }

    // TODO add a conic-specific zoom

    return zoomConstructor(geo, projection);
}

module.exports = createGeoZoom;

// common to all zoom types
function initZoom(geo, projection) {
    return d3.behavior.zoom()
        .translate(projection.translate())
        .scale(projection.scale());
}

// sync zoom updates with user & full layout
function sync(geo, projection, cb) {
    var id = geo.id;
    var gd = geo.graphDiv;
    var layout = gd.layout;
    var userOpts = layout[id];
    var fullLayout = gd._fullLayout;
    var fullOpts = fullLayout[id];

    var preGUI = {};
    var eventData = {};

    function set(propStr, val) {
        preGUI[id + '.' + propStr] = Lib.nestedProperty(userOpts, propStr).get();
        Registry.call('_storeDirectGUIEdit', layout, fullLayout._preGUI, preGUI);

        var fullNp = Lib.nestedProperty(fullOpts, propStr);
        if(fullNp.get() !== val) {
            fullNp.set(val);
            Lib.nestedProperty(userOpts, propStr).set(val);
            eventData[id + '.' + propStr] = val;
        }
    }

    cb(set);
    set('projection.scale', projection.scale() / geo.fitScale);
    gd.emit('plotly_relayout', eventData);
}

// zoom for scoped projections
function zoomScoped(geo, projection) {
    var zoom = initZoom(geo, projection);

    function handleZoomstart() {
        d3.select(this).style(zoomstartStyle);
    }

    function handleZoom() {
        projection
            .scale(d3.event.scale)
            .translate(d3.event.translate);
        geo.render();
    }

    function syncCb(set) {
        var center = projection.invert(geo.midPt);

        set('center.lon', center[0]);
        set('center.lat', center[1]);
    }

    function handleZoomend() {
        d3.select(this).style(zoomendStyle);
        sync(geo, projection, syncCb);
    }

    zoom
        .on('zoomstart', handleZoomstart)
        .on('zoom', handleZoom)
        .on('zoomend', handleZoomend);

    return zoom;
}

// zoom for non-clipped projections
function zoomNonClipped(geo, projection) {
    var zoom = initZoom(geo, projection);

    var INSIDETOLORANCEPXS = 2;

    var mouse0, rotate0, translate0, lastRotate, zoomPoint,
        mouse1, rotate1, point1, didZoom;

    function position(x) { return projection.invert(x); }

    function outside(x) {
        var pos = position(x);
        if(!pos) return true;

        var pt = projection(pos);
        return (
            Math.abs(pt[0] - x[0]) > INSIDETOLORANCEPXS ||
            Math.abs(pt[1] - x[1]) > INSIDETOLORANCEPXS
        );
    }

    function handleZoomstart() {
        d3.select(this).style(zoomstartStyle);

        mouse0 = d3.mouse(this);
        rotate0 = projection.rotate();
        translate0 = projection.translate();
        lastRotate = rotate0;
        zoomPoint = position(mouse0);
    }

    function handleZoom() {
        mouse1 = d3.mouse(this);

        if(outside(mouse0)) {
            zoom.scale(projection.scale());
            zoom.translate(projection.translate());
            return;
        }

        projection.scale(d3.event.scale);
        projection.translate([translate0[0], d3.event.translate[1]]);

        if(!zoomPoint) {
            mouse0 = mouse1;
            zoomPoint = position(mouse0);
        }
        else if(position(mouse1)) {
            point1 = position(mouse1);
            rotate1 = [lastRotate[0] + (point1[0] - zoomPoint[0]), rotate0[1], rotate0[2]];
            projection.rotate(rotate1);
            lastRotate = rotate1;
        }

        didZoom = true;
        geo.render();
    }

    function handleZoomend() {
        d3.select(this).style(zoomendStyle);
        if(didZoom) sync(geo, projection, syncCb);
    }

    function syncCb(set) {
        var rotate = projection.rotate();
        var center = projection.invert(geo.midPt);

        set('projection.rotation.lon', -rotate[0]);
        set('center.lon', center[0]);
        set('center.lat', center[1]);
    }

    zoom
        .on('zoomstart', handleZoomstart)
        .on('zoom', handleZoom)
        .on('zoomend', handleZoomend);

    return zoom;
}

// zoom for clipped projections
// inspired by https://www.jasondavies.com/maps/d3.geo.zoom.js
function zoomClipped(geo, projection) {
    var view = {r: projection.rotate(), k: projection.scale()};
    var zoom = initZoom(geo, projection);
    var event = d3eventDispatch(zoom, 'zoomstart', 'zoom', 'zoomend');
    var zooming = 0;
    var zoomOn = zoom.on;

    var zoomPoint;

    zoom.on('zoomstart', function() {
        d3.select(this).style(zoomstartStyle);

        var mouse0 = d3.mouse(this);
        var rotate0 = projection.rotate();
        var lastRotate = rotate0;
        var translate0 = projection.translate();
        var q = quaternionFromEuler(rotate0);

        zoomPoint = position(projection, mouse0);

        zoomOn.call(zoom, 'zoom', function() {
            var mouse1 = d3.mouse(this);

            projection.scale(view.k = d3.event.scale);

            if(!zoomPoint) {
                // if no zoomPoint, the mouse wasn't over the actual geography yet
                // maybe this point is the start... we'll find out next time!
                mouse0 = mouse1;
                zoomPoint = position(projection, mouse0);
            }
            // check if the point is on the map
            // if not, don't do anything new but scale
            // if it is, then we can assume between will exist below
            // so we don't need the 'bank' function, whatever that is.
            else if(position(projection, mouse1)) {
                // go back to original projection temporarily
                // except for scale... that's kind of independent?
                projection
                    .rotate(rotate0)
                    .translate(translate0);

                // calculate the new params
                var point1 = position(projection, mouse1);
                var between = rotateBetween(zoomPoint, point1);
                var newEuler = eulerFromQuaternion(multiply(q, between));
                var rotateAngles = view.r = unRoll(newEuler, zoomPoint, lastRotate);

                if(!isFinite(rotateAngles[0]) || !isFinite(rotateAngles[1]) ||
                   !isFinite(rotateAngles[2])) {
                    rotateAngles = lastRotate;
                }

                // update the projection
                projection.rotate(rotateAngles);
                lastRotate = rotateAngles;
            }

            zoomed(event.of(this, arguments));
        });

        zoomstarted(event.of(this, arguments));
    })
    .on('zoomend', function() {
        d3.select(this).style(zoomendStyle);
        zoomOn.call(zoom, 'zoom', null);
        zoomended(event.of(this, arguments));
        sync(geo, projection, syncCb);
    })
    .on('zoom.redraw', function() {
        geo.render();
    });

    function zoomstarted(dispatch) {
        if(!zooming++) dispatch({type: 'zoomstart'});
    }

    function zoomed(dispatch) {
        dispatch({type: 'zoom'});
    }

    function zoomended(dispatch) {
        if(!--zooming) dispatch({type: 'zoomend'});
    }

    function syncCb(set) {
        var _rotate = projection.rotate();
        set('projection.rotation.lon', -_rotate[0]);
        set('projection.rotation.lat', -_rotate[1]);
    }

    return d3.rebind(zoom, event, 'on');
}

// -- helper functions for zoomClipped

function position(projection, point) {
    var spherical = projection.invert(point);
    return spherical && isFinite(spherical[0]) && isFinite(spherical[1]) && cartesian(spherical);
}

function quaternionFromEuler(euler) {
    var lambda = 0.5 * euler[0] * radians;
    var phi = 0.5 * euler[1] * radians;
    var gamma = 0.5 * euler[2] * radians;
    var sinLambda = Math.sin(lambda);
    var cosLambda = Math.cos(lambda);
    var sinPhi = Math.sin(phi);
    var cosPhi = Math.cos(phi);
    var sinGamma = Math.sin(gamma);
    var cosGamma = Math.cos(gamma);
    return [
        cosLambda * cosPhi * cosGamma + sinLambda * sinPhi * sinGamma,
        sinLambda * cosPhi * cosGamma - cosLambda * sinPhi * sinGamma,
        cosLambda * sinPhi * cosGamma + sinLambda * cosPhi * sinGamma,
        cosLambda * cosPhi * sinGamma - sinLambda * sinPhi * cosGamma
    ];
}

function multiply(a, b) {
    var a0 = a[0];
    var a1 = a[1];
    var a2 = a[2];
    var a3 = a[3];
    var b0 = b[0];
    var b1 = b[1];
    var b2 = b[2];
    var b3 = b[3];
    return [
        a0 * b0 - a1 * b1 - a2 * b2 - a3 * b3,
        a0 * b1 + a1 * b0 + a2 * b3 - a3 * b2,
        a0 * b2 - a1 * b3 + a2 * b0 + a3 * b1,
        a0 * b3 + a1 * b2 - a2 * b1 + a3 * b0
    ];
}

function rotateBetween(a, b) {
    if(!a || !b) return;
    var axis = cross(a, b);
    var norm = Math.sqrt(dot(axis, axis));
    var halfgamma = 0.5 * Math.acos(Math.max(-1, Math.min(1, dot(a, b))));
    var k = Math.sin(halfgamma) / norm;
    return norm && [Math.cos(halfgamma), axis[2] * k, -axis[1] * k, axis[0] * k];
}

// input:
//   rotateAngles: a calculated set of Euler angles
//   pt: a point (cartesian in 3-space) to keep fixed
//   roll0: an initial roll, to be preserved
// output:
//   a set of Euler angles that preserve the projection of pt
//     but set roll (output[2]) equal to roll0
//     note that this doesn't depend on the particular projection,
//     just on the rotation angles
function unRoll(rotateAngles, pt, lastRotate) {
    // calculate the fixed point transformed by these Euler angles
    // but with the desired roll undone
    var ptRotated = rotateCartesian(pt, 2, rotateAngles[0]);
    ptRotated = rotateCartesian(ptRotated, 1, rotateAngles[1]);
    ptRotated = rotateCartesian(ptRotated, 0, rotateAngles[2] - lastRotate[2]);

    var x = pt[0];
    var y = pt[1];
    var z = pt[2];
    var f = ptRotated[0];
    var g = ptRotated[1];
    var h = ptRotated[2];

    // the following essentially solves:
    // ptRotated = rotateCartesian(rotateCartesian(pt, 2, newYaw), 1, newPitch)
    // for newYaw and newPitch, as best it can
    var theta = Math.atan2(y, x) * degrees;
    var a = Math.sqrt(x * x + y * y);
    var b;
    var newYaw1;

    if(Math.abs(g) > a) {
        newYaw1 = (g > 0 ? 90 : -90) - theta;
        b = 0;
    } else {
        newYaw1 = Math.asin(g / a) * degrees - theta;
        b = Math.sqrt(a * a - g * g);
    }

    var newYaw2 = 180 - newYaw1 - 2 * theta;
    var newPitch1 = (Math.atan2(h, f) - Math.atan2(z, b)) * degrees;
    var newPitch2 = (Math.atan2(h, f) - Math.atan2(z, -b)) * degrees;

    // which is closest to lastRotate[0,1]: newYaw/Pitch or newYaw2/Pitch2?
    var dist1 = angleDistance(lastRotate[0], lastRotate[1], newYaw1, newPitch1);
    var dist2 = angleDistance(lastRotate[0], lastRotate[1], newYaw2, newPitch2);

    if(dist1 <= dist2) return [newYaw1, newPitch1, lastRotate[2]];
    else return [newYaw2, newPitch2, lastRotate[2]];
}

function angleDistance(yaw0, pitch0, yaw1, pitch1) {
    var dYaw = angleMod(yaw1 - yaw0);
    var dPitch = angleMod(pitch1 - pitch0);
    return Math.sqrt(dYaw * dYaw + dPitch * dPitch);
}

// reduce an angle in degrees to [-180,180]
function angleMod(angle) {
    return (angle % 360 + 540) % 360 - 180;
}

// rotate a cartesian vector
// axis is 0 (x), 1 (y), or 2 (z)
// angle is in degrees
function rotateCartesian(vector, axis, angle) {
    var angleRads = angle * radians;
    var vectorOut = vector.slice();
    var ax1 = (axis === 0) ? 1 : 0;
    var ax2 = (axis === 2) ? 1 : 2;
    var cosa = Math.cos(angleRads);
    var sina = Math.sin(angleRads);

    vectorOut[ax1] = vector[ax1] * cosa - vector[ax2] * sina;
    vectorOut[ax2] = vector[ax2] * cosa + vector[ax1] * sina;

    return vectorOut;
}
function eulerFromQuaternion(q) {
    return [
        Math.atan2(2 * (q[0] * q[1] + q[2] * q[3]), 1 - 2 * (q[1] * q[1] + q[2] * q[2])) * degrees,
        Math.asin(Math.max(-1, Math.min(1, 2 * (q[0] * q[2] - q[3] * q[1])))) * degrees,
        Math.atan2(2 * (q[0] * q[3] + q[1] * q[2]), 1 - 2 * (q[2] * q[2] + q[3] * q[3])) * degrees
    ];
}

function cartesian(spherical) {
    var lambda = spherical[0] * radians;
    var phi = spherical[1] * radians;
    var cosPhi = Math.cos(phi);
    return [
        cosPhi * Math.cos(lambda),
        cosPhi * Math.sin(lambda),
        Math.sin(phi)
    ];
}

function dot(a, b) {
    var s = 0;
    for(var i = 0, n = a.length; i < n; ++i) s += a[i] * b[i];
    return s;
}

function cross(a, b) {
    return [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0]
    ];
}

// Like d3.dispatch, but for custom events abstracting native UI events. These
// events have a target component (such as a brush), a target element (such as
// the svg:g element containing the brush) and the standard arguments `d` (the
// target element's data) and `i` (the selection index of the target element).
function d3eventDispatch(target) {
    var i = 0;
    var n = arguments.length;
    var argumentz = [];

    while(++i < n) argumentz.push(arguments[i]);

    var dispatch = d3.dispatch.apply(null, argumentz);

    // Creates a dispatch context for the specified `thiz` (typically, the target
    // DOM element that received the source event) and `argumentz` (typically, the
    // data `d` and index `i` of the target element). The returned function can be
    // used to dispatch an event to any registered listeners; the function takes a
    // single argument as input, being the event to dispatch. The event must have
    // a "type" attribute which corresponds to a type registered in the
    // constructor. This context will automatically populate the "sourceEvent" and
    // "target" attributes of the event, as well as setting the `d3.event` global
    // for the duration of the notification.
    dispatch.of = function(thiz, argumentz) {
        return function(e1) {
            var e0;
            try {
                e0 = e1.sourceEvent = d3.event;
                e1.target = target;
                d3.event = e1;
                dispatch[e1.type].apply(thiz, argumentz);
            } finally {
                d3.event = e0;
            }
        };
    };

    return dispatch;
}

},{"../../lib":694,"../../registry":825,"d3":149}],779:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../registry');
var SUBPLOT_PATTERN = _dereq_('./cartesian/constants').SUBPLOT_PATTERN;

/**
 * Get calcdata trace(s) associated with a given subplot
 *
 * @param {array} calcData: as in gd.calcdata
 * @param {string} type: subplot type
 * @param {string} subplotId: subplot id to look for
 *
 * @return {array} array of calcdata traces
 */
exports.getSubplotCalcData = function(calcData, type, subplotId) {
    var basePlotModule = Registry.subplotsRegistry[type];
    if(!basePlotModule) return [];

    var attr = basePlotModule.attr;
    var subplotCalcData = [];

    for(var i = 0; i < calcData.length; i++) {
        var calcTrace = calcData[i];
        var trace = calcTrace[0].trace;

        if(trace[attr] === subplotId) subplotCalcData.push(calcTrace);
    }

    return subplotCalcData;
};
/**
 * Get calcdata trace(s) that can be plotted with a given module
 * NOTE: this isn't necessarily just exactly matching trace type,
 * if multiple trace types use the same plotting routine, they will be
 * collected here.
 * In order to not plot the same thing multiple times, we return two arrays,
 * the calcdata we *will* plot with this module, and the ones we *won't*
 *
 * @param {array} calcdata: as in gd.calcdata
 * @param {object|string|fn} arg1:
 *  the plotting module, or its name, or its plot method
 *
 * @return {array[array]} [foundCalcdata, remainingCalcdata]
 */
exports.getModuleCalcData = function(calcdata, arg1) {
    var moduleCalcData = [];
    var remainingCalcData = [];

    var plotMethod;
    if(typeof arg1 === 'string') {
        plotMethod = Registry.getModule(arg1).plot;
    } else if(typeof arg1 === 'function') {
        plotMethod = arg1;
    } else {
        plotMethod = arg1.plot;
    }
    if(!plotMethod) {
        return [moduleCalcData, calcdata];
    }

    for(var i = 0; i < calcdata.length; i++) {
        var cd = calcdata[i];
        var trace = cd[0].trace;
        // N.B. 'legendonly' traces do not make it past here
        if(trace.visible !== true) continue;

        // group calcdata trace not by 'module' (as the name of this function
        // would suggest), but by 'module plot method' so that if some traces
        // share the same module plot method (e.g. bar and histogram), we
        // only call it one!
        if(trace._module.plot === plotMethod) {
            moduleCalcData.push(cd);
        } else {
            remainingCalcData.push(cd);
        }
    }

    return [moduleCalcData, remainingCalcData];
};

/**
 * Get the data trace(s) associated with a given subplot.
 *
 * @param {array} data  plotly full data array.
 * @param {string} type subplot type to look for.
 * @param {string} subplotId subplot id to look for.
 *
 * @return {array} list of trace objects.
 *
 */
exports.getSubplotData = function getSubplotData(data, type, subplotId) {
    if(!Registry.subplotsRegistry[type]) return [];

    var attr = Registry.subplotsRegistry[type].attr;
    var subplotData = [];
    var trace, subplotX, subplotY;

    if(type === 'gl2d') {
        var spmatch = subplotId.match(SUBPLOT_PATTERN);
        subplotX = 'x' + spmatch[1];
        subplotY = 'y' + spmatch[2];
    }

    for(var i = 0; i < data.length; i++) {
        trace = data[i];

        if(type === 'gl2d' && Registry.traceIs(trace, 'gl2d')) {
            if(trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) {
                subplotData.push(trace);
            }
        }
        else {
            if(trace[attr] === subplotId) subplotData.push(trace);
        }
    }

    return subplotData;
};

},{"../registry":825,"./cartesian/constants":748}],780:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var mouseChange = _dereq_('mouse-change');
var mouseWheel = _dereq_('mouse-wheel');
var mouseOffset = _dereq_('mouse-event-offset');
var cartesianConstants = _dereq_('../cartesian/constants');
var hasPassive = _dereq_('has-passive-events');

module.exports = createCamera;

function Camera2D(element, plot) {
    this.element = element;
    this.plot = plot;
    this.mouseListener = null;
    this.wheelListener = null;
    this.lastInputTime = Date.now();
    this.lastPos = [0, 0];
    this.boxEnabled = false;
    this.boxInited = false;
    this.boxStart = [0, 0];
    this.boxEnd = [0, 0];
    this.dragStart = [0, 0];
}


function createCamera(scene) {
    var element = scene.mouseContainer;
    var plot = scene.glplot;
    var result = new Camera2D(element, plot);

    function unSetAutoRange() {
        scene.xaxis.autorange = false;
        scene.yaxis.autorange = false;
    }

    function getSubplotConstraint() {
        // note: this assumes we only have one x and one y axis on this subplot
        // when this constraint is lifted this block won't make sense
        var constraints = scene.graphDiv._fullLayout._axisConstraintGroups;
        var xaId = scene.xaxis._id;
        var yaId = scene.yaxis._id;
        for(var i = 0; i < constraints.length; i++) {
            if(constraints[i][xaId] !== -1) {
                if(constraints[i][yaId] !== -1) return true;
                break;
            }
        }
        return false;
    }

    result.mouseListener = mouseChange(element, handleInteraction);

    // enable simple touch interactions
    element.addEventListener('touchstart', function(ev) {
        var xy = mouseOffset(ev.changedTouches[0], element);
        handleInteraction(0, xy[0], xy[1]);
        handleInteraction(1, xy[0], xy[1]);

        ev.preventDefault();
    }, hasPassive ? {passive: false} : false);
    element.addEventListener('touchmove', function(ev) {
        ev.preventDefault();
        var xy = mouseOffset(ev.changedTouches[0], element);
        handleInteraction(1, xy[0], xy[1]);

        ev.preventDefault();
    }, hasPassive ? {passive: false} : false);
    element.addEventListener('touchend', function(ev) {
        handleInteraction(0, result.lastPos[0], result.lastPos[1]);

        ev.preventDefault();
    }, hasPassive ? {passive: false} : false);

    function handleInteraction(buttons, x, y) {
        var dataBox = scene.calcDataBox();
        var viewBox = plot.viewBox;

        var lastX = result.lastPos[0];
        var lastY = result.lastPos[1];

        var MINDRAG = cartesianConstants.MINDRAG * plot.pixelRatio;
        var MINZOOM = cartesianConstants.MINZOOM * plot.pixelRatio;

        var dx, dy;

        x *= plot.pixelRatio;
        y *= plot.pixelRatio;

        // mouseChange gives y about top; convert to about bottom
        y = (viewBox[3] - viewBox[1]) - y;

        function updateRange(i0, start, end) {
            var range0 = Math.min(start, end);
            var range1 = Math.max(start, end);

            if(range0 !== range1) {
                dataBox[i0] = range0;
                dataBox[i0 + 2] = range1;
                result.dataBox = dataBox;
                scene.setRanges(dataBox);
            }
            else {
                scene.selectBox.selectBox = [0, 0, 1, 1];
                scene.glplot.setDirty();
            }
        }

        switch(scene.fullLayout.dragmode) {
            case 'zoom':
                if(buttons) {
                    var dataX = x /
                            (viewBox[2] - viewBox[0]) * (dataBox[2] - dataBox[0]) +
                        dataBox[0];
                    var dataY = y /
                            (viewBox[3] - viewBox[1]) * (dataBox[3] - dataBox[1]) +
                        dataBox[1];

                    if(!result.boxInited) {
                        result.boxStart[0] = dataX;
                        result.boxStart[1] = dataY;
                        result.dragStart[0] = x;
                        result.dragStart[1] = y;
                    }

                    result.boxEnd[0] = dataX;
                    result.boxEnd[1] = dataY;

                    // we need to mark the box as initialized right away
                    // so that we can tell the start and end points apart
                    result.boxInited = true;

                    // but don't actually enable the box until the cursor moves
                    if(!result.boxEnabled && (
                        result.boxStart[0] !== result.boxEnd[0] ||
                        result.boxStart[1] !== result.boxEnd[1])
                    ) {
                        result.boxEnabled = true;
                    }

                    // constrain aspect ratio if the axes require it
                    var smallDx = Math.abs(result.dragStart[0] - x) < MINZOOM;
                    var smallDy = Math.abs(result.dragStart[1] - y) < MINZOOM;
                    if(getSubplotConstraint() && !(smallDx && smallDy)) {
                        dx = result.boxEnd[0] - result.boxStart[0];
                        dy = result.boxEnd[1] - result.boxStart[1];
                        var dydx = (dataBox[3] - dataBox[1]) / (dataBox[2] - dataBox[0]);

                        if(Math.abs(dx * dydx) > Math.abs(dy)) {
                            result.boxEnd[1] = result.boxStart[1] +
                                Math.abs(dx) * dydx * (dy >= 0 ? 1 : -1);

                            // gl-select-box clips to the plot area bounds,
                            // which breaks the axis constraint, so don't allow
                            // this box to go out of bounds
                            if(result.boxEnd[1] < dataBox[1]) {
                                result.boxEnd[1] = dataBox[1];
                                result.boxEnd[0] = result.boxStart[0] +
                                    (dataBox[1] - result.boxStart[1]) / Math.abs(dydx);
                            }
                            else if(result.boxEnd[1] > dataBox[3]) {
                                result.boxEnd[1] = dataBox[3];
                                result.boxEnd[0] = result.boxStart[0] +
                                    (dataBox[3] - result.boxStart[1]) / Math.abs(dydx);
                            }
                        }
                        else {
                            result.boxEnd[0] = result.boxStart[0] +
                                Math.abs(dy) / dydx * (dx >= 0 ? 1 : -1);

                            if(result.boxEnd[0] < dataBox[0]) {
                                result.boxEnd[0] = dataBox[0];
                                result.boxEnd[1] = result.boxStart[1] +
                                    (dataBox[0] - result.boxStart[0]) * Math.abs(dydx);
                            }
                            else if(result.boxEnd[0] > dataBox[2]) {
                                result.boxEnd[0] = dataBox[2];
                                result.boxEnd[1] = result.boxStart[1] +
                                    (dataBox[2] - result.boxStart[0]) * Math.abs(dydx);
                            }
                        }
                    }
                    // otherwise clamp small changes to the origin so we get 1D zoom
                    else {
                        if(smallDx) result.boxEnd[0] = result.boxStart[0];
                        if(smallDy) result.boxEnd[1] = result.boxStart[1];
                    }
                }
                else if(result.boxEnabled) {
                    dx = result.boxStart[0] !== result.boxEnd[0];
                    dy = result.boxStart[1] !== result.boxEnd[1];
                    if(dx || dy) {
                        if(dx) {
                            updateRange(0, result.boxStart[0], result.boxEnd[0]);
                            scene.xaxis.autorange = false;
                        }
                        if(dy) {
                            updateRange(1, result.boxStart[1], result.boxEnd[1]);
                            scene.yaxis.autorange = false;
                        }
                        scene.relayoutCallback();
                    }
                    else {
                        scene.glplot.setDirty();
                    }
                    result.boxEnabled = false;
                    result.boxInited = false;
                }
                // if box was inited but button released then - reset the box
                else if(result.boxInited) {
                    result.boxInited = false;
                }
                break;

            case 'pan':
                result.boxEnabled = false;
                result.boxInited = false;

                if(buttons) {
                    if(!result.panning) {
                        result.dragStart[0] = x;
                        result.dragStart[1] = y;
                    }

                    if(Math.abs(result.dragStart[0] - x) < MINDRAG) x = result.dragStart[0];
                    if(Math.abs(result.dragStart[1] - y) < MINDRAG) y = result.dragStart[1];

                    dx = (lastX - x) * (dataBox[2] - dataBox[0]) /
                        (plot.viewBox[2] - plot.viewBox[0]);
                    dy = (lastY - y) * (dataBox[3] - dataBox[1]) /
                        (plot.viewBox[3] - plot.viewBox[1]);

                    dataBox[0] += dx;
                    dataBox[2] += dx;
                    dataBox[1] += dy;
                    dataBox[3] += dy;

                    scene.setRanges(dataBox);

                    result.panning = true;
                    result.lastInputTime = Date.now();
                    unSetAutoRange();
                    scene.cameraChanged();
                    scene.handleAnnotations();
                }
                else if(result.panning) {
                    result.panning = false;
                    scene.relayoutCallback();
                }
                break;
        }

        result.lastPos[0] = x;
        result.lastPos[1] = y;
    }

    result.wheelListener = mouseWheel(element, function(dx, dy) {
        if(!scene.scrollZoom) return false;

        var dataBox = scene.calcDataBox();
        var viewBox = plot.viewBox;

        var lastX = result.lastPos[0];
        var lastY = result.lastPos[1];

        var scale = Math.exp(5.0 * dy / (viewBox[3] - viewBox[1]));

        var cx = lastX /
                (viewBox[2] - viewBox[0]) * (dataBox[2] - dataBox[0]) +
            dataBox[0];
        var cy = lastY /
                (viewBox[3] - viewBox[1]) * (dataBox[3] - dataBox[1]) +
            dataBox[1];

        dataBox[0] = (dataBox[0] - cx) * scale + cx;
        dataBox[2] = (dataBox[2] - cx) * scale + cx;
        dataBox[1] = (dataBox[1] - cy) * scale + cy;
        dataBox[3] = (dataBox[3] - cy) * scale + cy;

        scene.setRanges(dataBox);

        result.lastInputTime = Date.now();
        unSetAutoRange();
        scene.cameraChanged();
        scene.handleAnnotations();
        scene.relayoutCallback();

        return true;
    }, true);

    return result;
}

},{"../cartesian/constants":748,"has-passive-events":397,"mouse-change":421,"mouse-event-offset":422,"mouse-wheel":424}],781:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Axes = _dereq_('../cartesian/axes');

var str2RGBArray = _dereq_('../../lib/str2rgbarray');

function Axes2DOptions(scene) {
    this.scene = scene;
    this.gl = scene.gl;
    this.pixelRatio = scene.pixelRatio;

    this.screenBox = [0, 0, 1, 1];
    this.viewBox = [0, 0, 1, 1];
    this.dataBox = [-1, -1, 1, 1];

    this.borderLineEnable = [false, false, false, false];
    this.borderLineWidth = [1, 1, 1, 1];
    this.borderLineColor = [
        [0, 0, 0, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 1]
    ];

    this.ticks = [[], []];
    this.tickEnable = [true, true, false, false];
    this.tickPad = [15, 15, 15, 15];
    this.tickAngle = [0, 0, 0, 0];
    this.tickColor = [
        [0, 0, 0, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 1]
    ];
    this.tickMarkLength = [0, 0, 0, 0];
    this.tickMarkWidth = [0, 0, 0, 0];
    this.tickMarkColor = [
        [0, 0, 0, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 1]
    ];

    this.labels = ['x', 'y'];
    this.labelEnable = [true, true, false, false];
    this.labelAngle = [0, Math.PI / 2, 0, 3.0 * Math.PI / 2];
    this.labelPad = [15, 15, 15, 15];
    this.labelSize = [12, 12];
    this.labelFont = ['sans-serif', 'sans-serif'];
    this.labelColor = [
        [0, 0, 0, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 1]
    ];

    this.title = '';
    this.titleEnable = true;
    this.titleCenter = [0, 0, 0, 0];
    this.titleAngle = 0;
    this.titleColor = [0, 0, 0, 1];
    this.titleFont = 'sans-serif';
    this.titleSize = 18;

    this.gridLineEnable = [true, true];
    this.gridLineColor = [
        [0, 0, 0, 0.5],
        [0, 0, 0, 0.5]
    ];
    this.gridLineWidth = [1, 1];

    this.zeroLineEnable = [true, true];
    this.zeroLineWidth = [1, 1];
    this.zeroLineColor = [
        [0, 0, 0, 1],
        [0, 0, 0, 1]
    ];

    this.borderColor = false;
    this.backgroundColor = [0, 0, 0, 0];

    this.static = this.scene.staticPlot;
}

var proto = Axes2DOptions.prototype;

var AXES = ['xaxis', 'yaxis'];

proto.merge = function(options) {

    // titles are rendered in SVG
    this.titleEnable = false;
    this.backgroundColor = str2RGBArray(options.plot_bgcolor);

    var axisName, ax, axTitle, axMirror;
    var hasAxisInDfltPos, hasAxisInAltrPos, hasSharedAxis, mirrorLines, mirrorTicks;
    var i, j;

    for(i = 0; i < 2; ++i) {
        axisName = AXES[i];
        var axisLetter = axisName.charAt(0);

        // get options relevant to this subplot,
        // '_name' is e.g. xaxis, xaxis2, yaxis, yaxis4 ...
        ax = options[this.scene[axisName]._name];

        axTitle = ax.title.text === this.scene.fullLayout._dfltTitle[axisLetter] ? '' : ax.title.text;

        for(j = 0; j <= 2; j += 2) {
            this.labelEnable[i + j] = false;
            this.labels[i + j] = axTitle;
            this.labelColor[i + j] = str2RGBArray(ax.title.font.color);
            this.labelFont[i + j] = ax.title.font.family;
            this.labelSize[i + j] = ax.title.font.size;
            this.labelPad[i + j] = this.getLabelPad(axisName, ax);

            this.tickEnable[i + j] = false;
            this.tickColor[i + j] = str2RGBArray((ax.tickfont || {}).color);
            this.tickAngle[i + j] = (ax.tickangle === 'auto') ?
                0 :
                Math.PI * -ax.tickangle / 180;
            this.tickPad[i + j] = this.getTickPad(ax);

            this.tickMarkLength[i + j] = 0;
            this.tickMarkWidth[i + j] = ax.tickwidth || 0;
            this.tickMarkColor[i + j] = str2RGBArray(ax.tickcolor);

            this.borderLineEnable[i + j] = false;
            this.borderLineColor[i + j] = str2RGBArray(ax.linecolor);
            this.borderLineWidth[i + j] = ax.linewidth || 0;
        }

        hasSharedAxis = this.hasSharedAxis(ax);
        hasAxisInDfltPos = this.hasAxisInDfltPos(axisName, ax) && !hasSharedAxis;
        hasAxisInAltrPos = this.hasAxisInAltrPos(axisName, ax) && !hasSharedAxis;

        axMirror = ax.mirror || false;
        mirrorLines = hasSharedAxis ?
            (String(axMirror).indexOf('all') !== -1) :  // 'all' or 'allticks'
            !!axMirror;                                 // all but false
        mirrorTicks = hasSharedAxis ?
            (axMirror === 'allticks') :
            (String(axMirror).indexOf('ticks') !== -1); // 'ticks' or 'allticks'

        // Axis titles and tick labels can only appear of one side of the scene
        //  and are never show on subplots that share existing axes.

        if(hasAxisInDfltPos) this.labelEnable[i] = true;
        else if(hasAxisInAltrPos) this.labelEnable[i + 2] = true;

        if(hasAxisInDfltPos) this.tickEnable[i] = ax.showticklabels;
        else if(hasAxisInAltrPos) this.tickEnable[i + 2] = ax.showticklabels;

        // Grid lines and ticks can appear on both sides of the scene
        //  and can appear on subplot that share existing axes via `ax.mirror`.

        if(hasAxisInDfltPos || mirrorLines) this.borderLineEnable[i] = ax.showline;
        if(hasAxisInAltrPos || mirrorLines) this.borderLineEnable[i + 2] = ax.showline;

        if(hasAxisInDfltPos || mirrorTicks) this.tickMarkLength[i] = this.getTickMarkLength(ax);
        if(hasAxisInAltrPos || mirrorTicks) this.tickMarkLength[i + 2] = this.getTickMarkLength(ax);

        this.gridLineEnable[i] = ax.showgrid;
        this.gridLineColor[i] = str2RGBArray(ax.gridcolor);
        this.gridLineWidth[i] = ax.gridwidth;

        this.zeroLineEnable[i] = ax.zeroline;
        this.zeroLineColor[i] = str2RGBArray(ax.zerolinecolor);
        this.zeroLineWidth[i] = ax.zerolinewidth;
    }
};

// is an axis shared with an already-drawn subplot ?
proto.hasSharedAxis = function(ax) {
    var scene = this.scene;
    var subplotIds = scene.fullLayout._subplots.gl2d;
    var list = Axes.findSubplotsWithAxis(subplotIds, ax);

    // if index === 0, then the subplot is already drawn as subplots
    // are drawn in order.
    return (list.indexOf(scene.id) !== 0);
};

// has an axis in default position (i.e. bottom/left) ?
proto.hasAxisInDfltPos = function(axisName, ax) {
    var axSide = ax.side;

    if(axisName === 'xaxis') return (axSide === 'bottom');
    else if(axisName === 'yaxis') return (axSide === 'left');
};

// has an axis in alternate position (i.e. top/right) ?
proto.hasAxisInAltrPos = function(axisName, ax) {
    var axSide = ax.side;

    if(axisName === 'xaxis') return (axSide === 'top');
    else if(axisName === 'yaxis') return (axSide === 'right');
};

proto.getLabelPad = function(axisName, ax) {
    var offsetBase = 1.5;
    var fontSize = ax.title.font.size;
    var showticklabels = ax.showticklabels;

    if(axisName === 'xaxis') {
        return (ax.side === 'top') ?
            -10 + fontSize * (offsetBase + (showticklabels ? 1 : 0)) :
            -10 + fontSize * (offsetBase + (showticklabels ? 0.5 : 0));
    }
    else if(axisName === 'yaxis') {
        return (ax.side === 'right') ?
            10 + fontSize * (offsetBase + (showticklabels ? 1 : 0.5)) :
            10 + fontSize * (offsetBase + (showticklabels ? 0.5 : 0));
    }
};

proto.getTickPad = function(ax) {
    return (ax.ticks === 'outside') ? 10 + ax.ticklen : 15;
};

proto.getTickMarkLength = function(ax) {
    if(!ax.ticks) return 0;

    var ticklen = ax.ticklen;

    return (ax.ticks === 'inside') ? -ticklen : ticklen;
};


function createAxes2D(scene) {
    return new Axes2DOptions(scene);
}

module.exports = createAxes2D;

},{"../../lib/str2rgbarray":717,"../cartesian/axes":742}],782:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;

var Scene2D = _dereq_('./scene2d');
var layoutGlobalAttrs = _dereq_('../layout_attributes');
var xmlnsNamespaces = _dereq_('../../constants/xmlns_namespaces');
var constants = _dereq_('../cartesian/constants');
var Cartesian = _dereq_('../cartesian');
var fxAttrs = _dereq_('../../components/fx/layout_attributes');
var getSubplotData = _dereq_('../get_data').getSubplotData;

exports.name = 'gl2d';

exports.attr = ['xaxis', 'yaxis'];

exports.idRoot = ['x', 'y'];

exports.idRegex = constants.idRegex;

exports.attrRegex = constants.attrRegex;

exports.attributes = _dereq_('../cartesian/attributes');

exports.supplyLayoutDefaults = function(layoutIn, layoutOut, fullData) {
    if(!layoutOut._has('cartesian')) {
        Cartesian.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
    }
};

// gl2d uses svg axis attributes verbatim, but overrides editType
// this could potentially be just `layoutAttributes` but it would
// still need special handling somewhere to give it precedence over
// the svg version when both are in use on one plot
exports.layoutAttrOverrides = overrideAll(Cartesian.layoutAttributes, 'plot', 'from-root');

// similar overrides for base plot attributes (and those added by components)
exports.baseLayoutAttrOverrides = overrideAll({
    plot_bgcolor: layoutGlobalAttrs.plot_bgcolor,
    hoverlabel: fxAttrs.hoverlabel
    // dragmode needs calc but only when transitioning TO lasso or select
    // so for now it's left inside _relayout
    // dragmode: fxAttrs.dragmode
}, 'plot', 'nested');

exports.plot = function plotGl2d(gd) {
    var fullLayout = gd._fullLayout;
    var fullData = gd._fullData;
    var subplotIds = fullLayout._subplots.gl2d;

    for(var i = 0; i < subplotIds.length; i++) {
        var subplotId = subplotIds[i];
        var subplotObj = fullLayout._plots[subplotId];
        var fullSubplotData = getSubplotData(fullData, 'gl2d', subplotId);

        // ref. to corresp. Scene instance
        var scene = subplotObj._scene2d;

        // If Scene is not instantiated, create one!
        if(scene === undefined) {
            scene = new Scene2D({
                id: subplotId,
                graphDiv: gd,
                container: gd.querySelector('.gl-container'),
                staticPlot: gd._context.staticPlot,
                plotGlPixelRatio: gd._context.plotGlPixelRatio
            },
                fullLayout
            );

            // set ref to Scene instance
            subplotObj._scene2d = scene;
        }

        scene.plot(fullSubplotData, gd.calcdata, fullLayout, gd.layout);
    }
};

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var oldSceneKeys = oldFullLayout._subplots.gl2d || [];

    for(var i = 0; i < oldSceneKeys.length; i++) {
        var id = oldSceneKeys[i];
        var oldSubplot = oldFullLayout._plots[id];

        // old subplot wasn't gl2d; nothing to do
        if(!oldSubplot._scene2d) continue;

        // if no traces are present, delete gl2d subplot
        var subplotData = getSubplotData(newFullData, 'gl2d', id);
        if(subplotData.length === 0) {
            oldSubplot._scene2d.destroy();
            delete oldFullLayout._plots[id];
        }
    }

    // since we use cartesian interactions, do cartesian clean
    Cartesian.clean.apply(this, arguments);
};

exports.drawFramework = function(gd) {
    if(!gd._context.staticPlot) {
        Cartesian.drawFramework(gd);
    }
};

exports.toSVG = function(gd) {
    var fullLayout = gd._fullLayout;
    var subplotIds = fullLayout._subplots.gl2d;

    for(var i = 0; i < subplotIds.length; i++) {
        var subplot = fullLayout._plots[subplotIds[i]];
        var scene = subplot._scene2d;

        var imageData = scene.toImage('png');
        var image = fullLayout._glimages.append('svg:image');

        image.attr({
            xmlns: xmlnsNamespaces.svg,
            'xlink:href': imageData,
            x: 0,
            y: 0,
            width: '100%',
            height: '100%',
            preserveAspectRatio: 'none'
        });

        scene.destroy();
    }
};

exports.updateFx = function(gd) {
    var fullLayout = gd._fullLayout;
    var subplotIds = fullLayout._subplots.gl2d;

    for(var i = 0; i < subplotIds.length; i++) {
        var subplotObj = fullLayout._plots[subplotIds[i]]._scene2d;
        subplotObj.updateFx(fullLayout.dragmode);
    }
};

},{"../../components/fx/layout_attributes":611,"../../constants/xmlns_namespaces":672,"../../plot_api/edit_types":725,"../cartesian":754,"../cartesian/attributes":740,"../cartesian/constants":748,"../get_data":779,"../layout_attributes":797,"./scene2d":783}],783:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../../registry');
var Axes = _dereq_('../../plots/cartesian/axes');
var Fx = _dereq_('../../components/fx');

var createPlot2D = _dereq_('gl-plot2d');
var createSpikes = _dereq_('gl-spikes2d');
var createSelectBox = _dereq_('gl-select-box');
var getContext = _dereq_('webgl-context');

var createOptions = _dereq_('./convert');
var createCamera = _dereq_('./camera');
var showNoWebGlMsg = _dereq_('../../lib/show_no_webgl_msg');
var axisConstraints = _dereq_('../cartesian/constraints');
var enforceAxisConstraints = axisConstraints.enforce;
var cleanAxisConstraints = axisConstraints.clean;
var doAutoRange = _dereq_('../cartesian/autorange').doAutoRange;

var AXES = ['xaxis', 'yaxis'];
var STATIC_CANVAS, STATIC_CONTEXT;

var SUBPLOT_PATTERN = _dereq_('../cartesian/constants').SUBPLOT_PATTERN;


function Scene2D(options, fullLayout) {
    this.container = options.container;
    this.graphDiv = options.graphDiv;
    this.pixelRatio = options.plotGlPixelRatio || window.devicePixelRatio;
    this.id = options.id;
    this.staticPlot = !!options.staticPlot;
    this.scrollZoom = this.graphDiv._context._scrollZoom.cartesian;

    this.fullData = null;
    this.updateRefs(fullLayout);

    this.makeFramework();
    if(this.stopped) return;

    // update options
    this.glplotOptions = createOptions(this);
    this.glplotOptions.merge(fullLayout);

    // create the plot
    this.glplot = createPlot2D(this.glplotOptions);

    // create camera
    this.camera = createCamera(this);

    // trace set
    this.traces = {};

    // create axes spikes
    this.spikes = createSpikes(this.glplot);

    this.selectBox = createSelectBox(this.glplot, {
        innerFill: false,
        outerFill: true
    });

    // last button state
    this.lastButtonState = 0;

    // last pick result
    this.pickResult = null;

    // is the mouse over the plot?
    // it's OK if this says true when it's not, so long as
    // when we get a mouseout we set it to false before handling
    this.isMouseOver = true;

    // flag to stop render loop
    this.stopped = false;

    // redraw the plot
    this.redraw = this.draw.bind(this);
    this.redraw();
}

module.exports = Scene2D;

var proto = Scene2D.prototype;

proto.makeFramework = function() {

    // create canvas and gl context
    if(this.staticPlot) {
        if(!STATIC_CONTEXT) {
            STATIC_CANVAS = document.createElement('canvas');

            STATIC_CONTEXT = getContext({
                canvas: STATIC_CANVAS,
                preserveDrawingBuffer: false,
                premultipliedAlpha: true,
                antialias: true
            });

            if(!STATIC_CONTEXT) {
                throw new Error('Error creating static canvas/context for image server');
            }
        }

        this.canvas = STATIC_CANVAS;
        this.gl = STATIC_CONTEXT;
    }
    else {
        var liveCanvas = this.container.querySelector('.gl-canvas-focus');

        var gl = getContext({
            canvas: liveCanvas,
            preserveDrawingBuffer: true,
            premultipliedAlpha: true
        });

        if(!gl) {
            showNoWebGlMsg(this);
            this.stopped = true;
            return;
        }

        this.canvas = liveCanvas;
        this.gl = gl;
    }

    // position the canvas
    var canvas = this.canvas;

    canvas.style.width = '100%';
    canvas.style.height = '100%';
    canvas.style.position = 'absolute';
    canvas.style.top = '0px';
    canvas.style.left = '0px';
    canvas.style['pointer-events'] = 'none';

    this.updateSize(canvas);

    // disabling user select on the canvas
    // sanitizes double-clicks interactions
    // ref: https://github.com/plotly/plotly.js/issues/744
    canvas.className += ' user-select-none';

    // create SVG container for hover text
    var svgContainer = this.svgContainer = document.createElementNS(
        'http://www.w3.org/2000/svg',
        'svg');
    svgContainer.style.position = 'absolute';
    svgContainer.style.top = svgContainer.style.left = '0px';
    svgContainer.style.width = svgContainer.style.height = '100%';
    svgContainer.style['z-index'] = 20;
    svgContainer.style['pointer-events'] = 'none';

    // create div to catch the mouse event
    var mouseContainer = this.mouseContainer = document.createElement('div');
    mouseContainer.style.position = 'absolute';
    mouseContainer.style['pointer-events'] = 'auto';

    this.pickCanvas = this.container.querySelector('.gl-canvas-pick');


    // append canvas, hover svg and mouse div to container
    var container = this.container;
    container.appendChild(svgContainer);
    container.appendChild(mouseContainer);

    var self = this;
    mouseContainer.addEventListener('mouseout', function() {
        self.isMouseOver = false;
        self.unhover();
    });
    mouseContainer.addEventListener('mouseover', function() {
        self.isMouseOver = true;
    });
};

proto.toImage = function(format) {
    if(!format) format = 'png';

    this.stopped = true;

    if(this.staticPlot) this.container.appendChild(STATIC_CANVAS);

    // update canvas size
    this.updateSize(this.canvas);


    // grab context and yank out pixels
    var gl = this.glplot.gl;
    var w = gl.drawingBufferWidth;
    var h = gl.drawingBufferHeight;

    // force redraw
    gl.clearColor(1, 1, 1, 0);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    this.glplot.setDirty();
    this.glplot.draw();

    gl.bindFramebuffer(gl.FRAMEBUFFER, null);

    var pixels = new Uint8Array(w * h * 4);
    gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, pixels);

    // flip pixels
    for(var j = 0, k = h - 1; j < k; ++j, --k) {
        for(var i = 0; i < w; ++i) {
            for(var l = 0; l < 4; ++l) {
                var tmp = pixels[4 * (w * j + i) + l];
                pixels[4 * (w * j + i) + l] = pixels[4 * (w * k + i) + l];
                pixels[4 * (w * k + i) + l] = tmp;
            }
        }
    }

    var canvas = document.createElement('canvas');
    canvas.width = w;
    canvas.height = h;

    var context = canvas.getContext('2d');
    var imageData = context.createImageData(w, h);
    imageData.data.set(pixels);
    context.putImageData(imageData, 0, 0);

    var dataURL;

    switch(format) {
        case 'jpeg':
            dataURL = canvas.toDataURL('image/jpeg');
            break;
        case 'webp':
            dataURL = canvas.toDataURL('image/webp');
            break;
        default:
            dataURL = canvas.toDataURL('image/png');
    }

    if(this.staticPlot) this.container.removeChild(STATIC_CANVAS);

    return dataURL;
};

proto.updateSize = function(canvas) {
    if(!canvas) canvas = this.canvas;

    var pixelRatio = this.pixelRatio;
    var fullLayout = this.fullLayout;

    var width = fullLayout.width;
    var height = fullLayout.height;
    var pixelWidth = Math.ceil(pixelRatio * width) |0;
    var pixelHeight = Math.ceil(pixelRatio * height) |0;

    // check for resize
    if(canvas.width !== pixelWidth || canvas.height !== pixelHeight) {
        canvas.width = pixelWidth;
        canvas.height = pixelHeight;
    }

    return canvas;
};

proto.computeTickMarks = function() {
    this.xaxis.setScale();
    this.yaxis.setScale();

    var nextTicks = [
        Axes.calcTicks(this.xaxis),
        Axes.calcTicks(this.yaxis)
    ];

    for(var j = 0; j < 2; ++j) {
        for(var i = 0; i < nextTicks[j].length; ++i) {
            // coercing tick value (may not be a string) to a string
            nextTicks[j][i].text = nextTicks[j][i].text + '';
        }
    }

    return nextTicks;
};

function compareTicks(a, b) {
    for(var i = 0; i < 2; ++i) {
        var aticks = a[i];
        var bticks = b[i];

        if(aticks.length !== bticks.length) return true;

        for(var j = 0; j < aticks.length; ++j) {
            if(aticks[j].x !== bticks[j].x) return true;
        }
    }

    return false;
}

proto.updateRefs = function(newFullLayout) {
    this.fullLayout = newFullLayout;

    var spmatch = this.id.match(SUBPLOT_PATTERN);
    var xaxisName = 'xaxis' + spmatch[1];
    var yaxisName = 'yaxis' + spmatch[2];

    this.xaxis = this.fullLayout[xaxisName];
    this.yaxis = this.fullLayout[yaxisName];
};

proto.relayoutCallback = function() {
    var graphDiv = this.graphDiv;
    var xaxis = this.xaxis;
    var yaxis = this.yaxis;
    var layout = graphDiv.layout;

    // make a meaningful value to be passed on to possible 'plotly_relayout' subscriber(s)
    var update = {};
    var xrange = update[xaxis._name + '.range'] = xaxis.range.slice();
    var yrange = update[yaxis._name + '.range'] = yaxis.range.slice();
    update[xaxis._name + '.autorange'] = xaxis.autorange;
    update[yaxis._name + '.autorange'] = yaxis.autorange;

    Registry.call('_storeDirectGUIEdit', graphDiv.layout, graphDiv._fullLayout._preGUI, update);

    // update the input layout
    var xaIn = layout[xaxis._name];
    xaIn.range = xrange;
    xaIn.autorange = xaxis.autorange;

    var yaIn = layout[yaxis._name];
    yaIn.range = yrange;
    yaIn.autorange = yaxis.autorange;

    // lastInputTime helps determine which one is the latest input (if async)
    update.lastInputTime = this.camera.lastInputTime;
    graphDiv.emit('plotly_relayout', update);
};

proto.cameraChanged = function() {
    var camera = this.camera;

    this.glplot.setDataBox(this.calcDataBox());

    var nextTicks = this.computeTickMarks();
    var curTicks = this.glplotOptions.ticks;

    if(compareTicks(nextTicks, curTicks)) {
        this.glplotOptions.ticks = nextTicks;
        this.glplotOptions.dataBox = camera.dataBox;
        this.glplot.update(this.glplotOptions);
        this.handleAnnotations();
    }
};

proto.handleAnnotations = function() {
    var gd = this.graphDiv;
    var annotations = this.fullLayout.annotations;

    for(var i = 0; i < annotations.length; i++) {
        var ann = annotations[i];

        if(ann.xref === this.xaxis._id && ann.yref === this.yaxis._id) {
            Registry.getComponentMethod('annotations', 'drawOne')(gd, i);
        }
    }
};

proto.destroy = function() {
    if(!this.glplot) return;

    var traces = this.traces;

    if(traces) {
        Object.keys(traces).map(function(key) {
            traces[key].dispose();
            delete traces[key];
        });
    }

    this.glplot.dispose();

    this.container.removeChild(this.svgContainer);
    this.container.removeChild(this.mouseContainer);

    this.fullData = null;
    this.glplot = null;
    this.stopped = true;
    this.camera.mouseListener.enabled = false;
    this.mouseContainer.removeEventListener('wheel', this.camera.wheelListener);
    this.camera = null;
};

proto.plot = function(fullData, calcData, fullLayout) {
    var glplot = this.glplot;

    this.updateRefs(fullLayout);
    this.xaxis.clearCalc();
    this.yaxis.clearCalc();
    this.updateTraces(fullData, calcData);
    this.updateFx(fullLayout.dragmode);

    var width = fullLayout.width;
    var height = fullLayout.height;

    this.updateSize(this.canvas);

    var options = this.glplotOptions;
    options.merge(fullLayout);
    options.screenBox = [0, 0, width, height];

    var mockGraphDiv = {_fullLayout: {
        _axisConstraintGroups: this.graphDiv._fullLayout._axisConstraintGroups,
        xaxis: this.xaxis,
        yaxis: this.yaxis
    }};

    cleanAxisConstraints(mockGraphDiv, this.xaxis);
    cleanAxisConstraints(mockGraphDiv, this.yaxis);

    var size = fullLayout._size;
    var domainX = this.xaxis.domain;
    var domainY = this.yaxis.domain;

    options.viewBox = [
        size.l + domainX[0] * size.w,
        size.b + domainY[0] * size.h,
        (width - size.r) - (1 - domainX[1]) * size.w,
        (height - size.t) - (1 - domainY[1]) * size.h
    ];

    this.mouseContainer.style.width = size.w * (domainX[1] - domainX[0]) + 'px';
    this.mouseContainer.style.height = size.h * (domainY[1] - domainY[0]) + 'px';
    this.mouseContainer.height = size.h * (domainY[1] - domainY[0]);
    this.mouseContainer.style.left = size.l + domainX[0] * size.w + 'px';
    this.mouseContainer.style.top = size.t + (1 - domainY[1]) * size.h + 'px';

    var ax, i;

    for(i = 0; i < 2; ++i) {
        ax = this[AXES[i]];
        ax._length = options.viewBox[i + 2] - options.viewBox[i];

        doAutoRange(this.graphDiv, ax);
        ax.setScale();
    }

    enforceAxisConstraints(mockGraphDiv);

    options.ticks = this.computeTickMarks();

    options.dataBox = this.calcDataBox();

    options.merge(fullLayout);
    glplot.update(options);

    // force redraw so that promise is returned when rendering is completed
    this.glplot.draw();
};

proto.calcDataBox = function() {
    var xaxis = this.xaxis;
    var yaxis = this.yaxis;
    var xrange = xaxis.range;
    var yrange = yaxis.range;
    var xr2l = xaxis.r2l;
    var yr2l = yaxis.r2l;

    return [xr2l(xrange[0]), yr2l(yrange[0]), xr2l(xrange[1]), yr2l(yrange[1])];
};

proto.setRanges = function(dataBox) {
    var xaxis = this.xaxis;
    var yaxis = this.yaxis;
    var xl2r = xaxis.l2r;
    var yl2r = yaxis.l2r;

    xaxis.range = [xl2r(dataBox[0]), xl2r(dataBox[2])];
    yaxis.range = [yl2r(dataBox[1]), yl2r(dataBox[3])];
};

proto.updateTraces = function(fullData, calcData) {
    var traceIds = Object.keys(this.traces);
    var i, j, fullTrace;

    this.fullData = fullData;

    // remove empty traces
    traceIdLoop:
    for(i = 0; i < traceIds.length; i++) {
        var oldUid = traceIds[i];
        var oldTrace = this.traces[oldUid];

        for(j = 0; j < fullData.length; j++) {
            fullTrace = fullData[j];

            if(fullTrace.uid === oldUid && fullTrace.type === oldTrace.type) {
                continue traceIdLoop;
            }
        }

        oldTrace.dispose();
        delete this.traces[oldUid];
    }

    // update / create trace objects
    for(i = 0; i < fullData.length; i++) {
        fullTrace = fullData[i];
        var calcTrace = calcData[i];
        var traceObj = this.traces[fullTrace.uid];

        if(traceObj) traceObj.update(fullTrace, calcTrace);
        else {
            traceObj = fullTrace._module.plot(this, fullTrace, calcTrace);
            this.traces[fullTrace.uid] = traceObj;
        }
    }

    // order object per traces
    this.glplot.objects.sort(function(a, b) {
        return a._trace.index - b._trace.index;
    });
};

proto.updateFx = function(dragmode) {
    // switch to svg interactions in lasso/select mode
    if(dragmode === 'lasso' || dragmode === 'select') {
        this.pickCanvas.style['pointer-events'] = 'none';
        this.mouseContainer.style['pointer-events'] = 'none';
    } else {
        this.pickCanvas.style['pointer-events'] = 'auto';
        this.mouseContainer.style['pointer-events'] = 'auto';
    }

    // set proper cursor
    if(dragmode === 'pan') {
        this.mouseContainer.style.cursor = 'move';
    }
    else if(dragmode === 'zoom') {
        this.mouseContainer.style.cursor = 'crosshair';
    }
    else {
        this.mouseContainer.style.cursor = null;
    }
};

proto.emitPointAction = function(nextSelection, eventType) {
    var uid = nextSelection.trace.uid;
    var ptNumber = nextSelection.pointIndex;
    var trace;

    for(var i = 0; i < this.fullData.length; i++) {
        if(this.fullData[i].uid === uid) {
            trace = this.fullData[i];
        }
    }

    var pointData = {
        x: nextSelection.traceCoord[0],
        y: nextSelection.traceCoord[1],
        curveNumber: trace.index,
        pointNumber: ptNumber,
        data: trace._input,
        fullData: this.fullData,
        xaxis: this.xaxis,
        yaxis: this.yaxis
    };

    Fx.appendArrayPointValue(pointData, trace, ptNumber);

    this.graphDiv.emit(eventType, {points: [pointData]});
};

proto.draw = function() {
    if(this.stopped) return;

    requestAnimationFrame(this.redraw);

    var glplot = this.glplot;
    var camera = this.camera;
    var mouseListener = camera.mouseListener;
    var mouseUp = this.lastButtonState === 1 && mouseListener.buttons === 0;
    var fullLayout = this.fullLayout;

    this.lastButtonState = mouseListener.buttons;

    this.cameraChanged();

    var x = mouseListener.x * glplot.pixelRatio;
    var y = this.canvas.height - glplot.pixelRatio * mouseListener.y;

    var result;

    if(camera.boxEnabled && fullLayout.dragmode === 'zoom') {
        this.selectBox.enabled = true;

        var selectBox = this.selectBox.selectBox = [
            Math.min(camera.boxStart[0], camera.boxEnd[0]),
            Math.min(camera.boxStart[1], camera.boxEnd[1]),
            Math.max(camera.boxStart[0], camera.boxEnd[0]),
            Math.max(camera.boxStart[1], camera.boxEnd[1])
        ];

        // 1D zoom
        for(var i = 0; i < 2; i++) {
            if(camera.boxStart[i] === camera.boxEnd[i]) {
                selectBox[i] = glplot.dataBox[i];
                selectBox[i + 2] = glplot.dataBox[i + 2];
            }
        }

        glplot.setDirty();
    }
    else if(!camera.panning && this.isMouseOver) {
        this.selectBox.enabled = false;

        var size = fullLayout._size;
        var domainX = this.xaxis.domain;
        var domainY = this.yaxis.domain;

        result = glplot.pick(
            (x / glplot.pixelRatio) + size.l + domainX[0] * size.w,
            (y / glplot.pixelRatio) - (size.t + (1 - domainY[1]) * size.h)
        );

        var nextSelection = result && result.object._trace.handlePick(result);

        if(nextSelection && mouseUp) {
            this.emitPointAction(nextSelection, 'plotly_click');
        }

        if(result && result.object._trace.hoverinfo !== 'skip' && fullLayout.hovermode) {

            if(nextSelection && (
                !this.lastPickResult ||
                this.lastPickResult.traceUid !== nextSelection.trace.uid ||
                this.lastPickResult.dataCoord[0] !== nextSelection.dataCoord[0] ||
                this.lastPickResult.dataCoord[1] !== nextSelection.dataCoord[1])
            ) {
                var selection = nextSelection;

                this.lastPickResult = {
                    traceUid: nextSelection.trace ? nextSelection.trace.uid : null,
                    dataCoord: nextSelection.dataCoord.slice()
                };
                this.spikes.update({ center: result.dataCoord });

                selection.screenCoord = [
                    ((glplot.viewBox[2] - glplot.viewBox[0]) *
                    (result.dataCoord[0] - glplot.dataBox[0]) /
                        (glplot.dataBox[2] - glplot.dataBox[0]) + glplot.viewBox[0]) /
                            glplot.pixelRatio,
                    (this.canvas.height - (glplot.viewBox[3] - glplot.viewBox[1]) *
                    (result.dataCoord[1] - glplot.dataBox[1]) /
                        (glplot.dataBox[3] - glplot.dataBox[1]) - glplot.viewBox[1]) /
                            glplot.pixelRatio
                ];

                // this needs to happen before the next block that deletes traceCoord data
                // also it's important to copy, otherwise data is lost by the time event data is read
                this.emitPointAction(nextSelection, 'plotly_hover');

                var trace = this.fullData[selection.trace.index] || {};
                var ptNumber = selection.pointIndex;
                var hoverinfo = Fx.castHoverinfo(trace, fullLayout, ptNumber);

                if(hoverinfo && hoverinfo !== 'all') {
                    var parts = hoverinfo.split('+');
                    if(parts.indexOf('x') === -1) selection.traceCoord[0] = undefined;
                    if(parts.indexOf('y') === -1) selection.traceCoord[1] = undefined;
                    if(parts.indexOf('z') === -1) selection.traceCoord[2] = undefined;
                    if(parts.indexOf('text') === -1) selection.textLabel = undefined;
                    if(parts.indexOf('name') === -1) selection.name = undefined;
                }

                Fx.loneHover({
                    x: selection.screenCoord[0],
                    y: selection.screenCoord[1],
                    xLabel: this.hoverFormatter('xaxis', selection.traceCoord[0]),
                    yLabel: this.hoverFormatter('yaxis', selection.traceCoord[1]),
                    zLabel: selection.traceCoord[2],
                    text: selection.textLabel,
                    name: selection.name,
                    color: Fx.castHoverOption(trace, ptNumber, 'bgcolor') || selection.color,
                    borderColor: Fx.castHoverOption(trace, ptNumber, 'bordercolor'),
                    fontFamily: Fx.castHoverOption(trace, ptNumber, 'font.family'),
                    fontSize: Fx.castHoverOption(trace, ptNumber, 'font.size'),
                    fontColor: Fx.castHoverOption(trace, ptNumber, 'font.color')
                }, {
                    container: this.svgContainer,
                    gd: this.graphDiv
                });
            }
        }
    }

    // Remove hover effects if we're not over a point OR
    // if we're zooming or panning (in which case result is not set)
    if(!result) {
        this.unhover();
    }

    glplot.draw();
};

proto.unhover = function() {
    if(this.lastPickResult) {
        this.spikes.update({});
        this.lastPickResult = null;
        this.graphDiv.emit('plotly_unhover');
        Fx.loneUnhover(this.svgContainer);
    }
};

proto.hoverFormatter = function(axisName, val) {
    if(val === undefined) return undefined;

    var axis = this[axisName];
    return Axes.tickText(axis, axis.c2l(val), 'hover').text;
};

},{"../../components/fx":610,"../../lib/show_no_webgl_msg":715,"../../plots/cartesian/axes":742,"../../registry":825,"../cartesian/autorange":741,"../cartesian/constants":748,"../cartesian/constraints":750,"./camera":780,"./convert":781,"gl-plot2d":277,"gl-select-box":288,"gl-spikes2d":297,"webgl-context":534}],784:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = createCamera;

var now = _dereq_('right-now');
var createView = _dereq_('3d-view');
var mouseChange = _dereq_('mouse-change');
var mouseWheel = _dereq_('mouse-wheel');
var mouseOffset = _dereq_('mouse-event-offset');
var supportsPassive = _dereq_('has-passive-events');

function createCamera(element, options) {
    element = element || document.body;
    options = options || {};

    var limits = [ 0.01, Infinity ];
    if('distanceLimits' in options) {
        limits[0] = options.distanceLimits[0];
        limits[1] = options.distanceLimits[1];
    }
    if('zoomMin' in options) {
        limits[0] = options.zoomMin;
    }
    if('zoomMax' in options) {
        limits[1] = options.zoomMax;
    }

    var view = createView({
        center: options.center || [0, 0, 0],
        up: options.up || [0, 1, 0],
        eye: options.eye || [0, 0, 10],
        mode: options.mode || 'orbit',
        distanceLimits: limits
    });

    var pmatrix = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
    var distance = 0.0;
    var width = element.clientWidth;
    var height = element.clientHeight;

    var camera = {
        keyBindingMode: 'rotate',
        enableWheel: true,
        view: view,
        element: element,
        delay: options.delay || 16,
        rotateSpeed: options.rotateSpeed || 1,
        zoomSpeed: options.zoomSpeed || 1,
        translateSpeed: options.translateSpeed || 1,
        flipX: !!options.flipX,
        flipY: !!options.flipY,
        modes: view.modes,
        tick: function() {
            var t = now();
            var delay = this.delay;
            var ctime = t - 2 * delay;
            view.idle(t - delay);
            view.recalcMatrix(ctime);
            view.flush(t - (100 + delay * 2));
            var allEqual = true;
            var matrix = view.computedMatrix;
            for(var i = 0; i < 16; ++i) {
                allEqual = allEqual && (pmatrix[i] === matrix[i]);
                pmatrix[i] = matrix[i];
            }
            var sizeChanged =
                element.clientWidth === width &&
                element.clientHeight === height;
            width = element.clientWidth;
            height = element.clientHeight;
            if(allEqual) return !sizeChanged;
            distance = Math.exp(view.computedRadius[0]);
            return true;
        },
        lookAt: function(center, eye, up) {
            view.lookAt(view.lastT(), center, eye, up);
        },
        rotate: function(pitch, yaw, roll) {
            view.rotate(view.lastT(), pitch, yaw, roll);
        },
        pan: function(dx, dy, dz) {
            view.pan(view.lastT(), dx, dy, dz);
        },
        translate: function(dx, dy, dz) {
            view.translate(view.lastT(), dx, dy, dz);
        }
    };

    Object.defineProperties(camera, {
        matrix: {
            get: function() {
                return view.computedMatrix;
            },
            set: function(mat) {
                view.setMatrix(view.lastT(), mat);
                return view.computedMatrix;
            },
            enumerable: true
        },
        mode: {
            get: function() {
                return view.getMode();
            },
            set: function(mode) {
                var curUp = view.computedUp.slice();
                var curEye = view.computedEye.slice();
                var curCenter = view.computedCenter.slice();
                view.setMode(mode);
                if(mode === 'turntable') {
                    // Hacky time warping stuff to generate smooth animation
                    var t0 = now();
                    view._active.lookAt(t0, curEye, curCenter, curUp);
                    view._active.lookAt(t0 + 500, curEye, curCenter, [0, 0, 1]);
                    view._active.flush(t0);
                }
                return view.getMode();
            },
            enumerable: true
        },
        center: {
            get: function() {
                return view.computedCenter;
            },
            set: function(ncenter) {
                view.lookAt(view.lastT(), null, ncenter);
                return view.computedCenter;
            },
            enumerable: true
        },
        eye: {
            get: function() {
                return view.computedEye;
            },
            set: function(neye) {
                view.lookAt(view.lastT(), neye);
                return view.computedEye;
            },
            enumerable: true
        },
        up: {
            get: function() {
                return view.computedUp;
            },
            set: function(nup) {
                view.lookAt(view.lastT(), null, null, nup);
                return view.computedUp;
            },
            enumerable: true
        },
        distance: {
            get: function() {
                return distance;
            },
            set: function(d) {
                view.setDistance(view.lastT(), d);
                return d;
            },
            enumerable: true
        },
        distanceLimits: {
            get: function() {
                return view.getDistanceLimits(limits);
            },
            set: function(v) {
                view.setDistanceLimits(v);
                return v;
            },
            enumerable: true
        }
    });

    element.addEventListener('contextmenu', function(ev) {
        ev.preventDefault();
        return false;
    });

    var lastX = 0;
    var lastY = 0;
    var lastMods = {shift: false, control: false, alt: false, meta: false};
    camera.mouseListener = mouseChange(element, handleInteraction);

    // enable simple touch interactions
    element.addEventListener('touchstart', function(ev) {
        var xy = mouseOffset(ev.changedTouches[0], element);
        handleInteraction(0, xy[0], xy[1], lastMods);
        handleInteraction(1, xy[0], xy[1], lastMods);

        ev.preventDefault();
    }, supportsPassive ? {passive: false} : false);
    element.addEventListener('touchmove', function(ev) {
        var xy = mouseOffset(ev.changedTouches[0], element);
        handleInteraction(1, xy[0], xy[1], lastMods);

        ev.preventDefault();
    }, supportsPassive ? {passive: false} : false);
    element.addEventListener('touchend', function(ev) {
        handleInteraction(0, lastX, lastY, lastMods);

        ev.preventDefault();
    }, supportsPassive ? {passive: false} : false);

    function handleInteraction(buttons, x, y, mods) {
        var keyBindingMode = camera.keyBindingMode;

        if(keyBindingMode === false) return;

        var rotate = keyBindingMode === 'rotate';
        var pan = keyBindingMode === 'pan';
        var zoom = keyBindingMode === 'zoom';

        var ctrl = !!mods.control;
        var alt = !!mods.alt;
        var shift = !!mods.shift;
        var left = !!(buttons & 1);
        var right = !!(buttons & 2);
        var middle = !!(buttons & 4);

        var scale = 1.0 / element.clientHeight;
        var dx = scale * (x - lastX);
        var dy = scale * (y - lastY);

        var flipX = camera.flipX ? 1 : -1;
        var flipY = camera.flipY ? 1 : -1;

        var t = now();

        var drot = Math.PI * camera.rotateSpeed;

        if((rotate && left && !ctrl && !alt && !shift) || (left && !ctrl && !alt && shift)) {
            // Rotate
            view.rotate(t, flipX * drot * dx, -flipY * drot * dy, 0);
        }

        if((pan && left && !ctrl && !alt && !shift) || right || (left && ctrl && !alt && !shift)) {
            // Pan
            view.pan(t, -camera.translateSpeed * dx * distance, camera.translateSpeed * dy * distance, 0);
        }

        if((zoom && left && !ctrl && !alt && !shift) || middle || (left && !ctrl && alt && !shift)) {
            // Zoom
            var kzoom = -camera.zoomSpeed * dy / window.innerHeight * (t - view.lastT()) * 100;
            view.pan(t, 0, 0, distance * (Math.exp(kzoom) - 1));
        }

        lastX = x;
        lastY = y;
        lastMods = mods;

        return true;
    }

    camera.wheelListener = mouseWheel(element, function(dx, dy) {
        // TODO remove now that we can disable scroll via scrollZoom?
        if(camera.keyBindingMode === false) return;
        if(!camera.enableWheel) return;

        var flipX = camera.flipX ? 1 : -1;
        var flipY = camera.flipY ? 1 : -1;
        var t = now();
        if(Math.abs(dx) > Math.abs(dy)) {
            view.rotate(t, 0, 0, -dx * flipX * Math.PI * camera.rotateSpeed / window.innerWidth);
        } else {
            var kzoom = -camera.zoomSpeed * flipY * dy / window.innerHeight * (t - view.lastT()) / 20.0;
            view.pan(t, 0, 0, distance * (Math.exp(kzoom) - 1));
        }
    }, true);

    return camera;
}

},{"3d-view":46,"has-passive-events":397,"mouse-change":421,"mouse-event-offset":422,"mouse-wheel":424,"right-now":482}],785:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
var fxAttrs = _dereq_('../../components/fx/layout_attributes');

var Scene = _dereq_('./scene');
var getSubplotData = _dereq_('../get_data').getSubplotData;
var Lib = _dereq_('../../lib');
var xmlnsNamespaces = _dereq_('../../constants/xmlns_namespaces');

var GL3D = 'gl3d';
var SCENE = 'scene';


exports.name = GL3D;

exports.attr = SCENE;

exports.idRoot = SCENE;

exports.idRegex = exports.attrRegex = Lib.counterRegex('scene');

exports.attributes = _dereq_('./layout/attributes');

exports.layoutAttributes = _dereq_('./layout/layout_attributes');

exports.baseLayoutAttrOverrides = overrideAll({
    hoverlabel: fxAttrs.hoverlabel
}, 'plot', 'nested');

exports.supplyLayoutDefaults = _dereq_('./layout/defaults');

exports.plot = function plotGl3d(gd) {
    var fullLayout = gd._fullLayout;
    var fullData = gd._fullData;
    var sceneIds = fullLayout._subplots[GL3D];

    for(var i = 0; i < sceneIds.length; i++) {
        var sceneId = sceneIds[i];
        var fullSceneData = getSubplotData(fullData, GL3D, sceneId);
        var sceneLayout = fullLayout[sceneId];
        var scene = sceneLayout._scene;

        if(!scene) {
            scene = new Scene({
                id: sceneId,
                graphDiv: gd,
                container: gd.querySelector('.gl-container'),
                staticPlot: gd._context.staticPlot,
                plotGlPixelRatio: gd._context.plotGlPixelRatio
            },
                fullLayout
            );

            // set ref to Scene instance
            sceneLayout._scene = scene;
        }

        // save 'initial' camera settings for modebar button
        if(!scene.cameraInitial) {
            scene.cameraInitial = Lib.extendDeep({}, sceneLayout.camera);
        }

        scene.plot(fullSceneData, fullLayout, gd.layout);
    }
};

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var oldSceneKeys = oldFullLayout._subplots[GL3D] || [];

    for(var i = 0; i < oldSceneKeys.length; i++) {
        var oldSceneKey = oldSceneKeys[i];

        if(!newFullLayout[oldSceneKey] && !!oldFullLayout[oldSceneKey]._scene) {
            oldFullLayout[oldSceneKey]._scene.destroy();

            if(oldFullLayout._infolayer) {
                oldFullLayout._infolayer
                    .selectAll('.annotation-' + oldSceneKey)
                    .remove();
            }
        }
    }
};

exports.toSVG = function(gd) {
    var fullLayout = gd._fullLayout;
    var sceneIds = fullLayout._subplots[GL3D];
    var size = fullLayout._size;

    for(var i = 0; i < sceneIds.length; i++) {
        var sceneLayout = fullLayout[sceneIds[i]];
        var domain = sceneLayout.domain;
        var scene = sceneLayout._scene;

        var imageData = scene.toImage('png');
        var image = fullLayout._glimages.append('svg:image');

        image.attr({
            xmlns: xmlnsNamespaces.svg,
            'xlink:href': imageData,
            x: size.l + size.w * domain.x[0],
            y: size.t + size.h * (1 - domain.y[1]),
            width: size.w * (domain.x[1] - domain.x[0]),
            height: size.h * (domain.y[1] - domain.y[0]),
            preserveAspectRatio: 'none'
        });

        scene.destroy();
    }
};

// clean scene ids, 'scene1' -> 'scene'
exports.cleanId = function cleanId(id) {
    if(!id.match(/^scene[0-9]*$/)) return;

    var sceneNum = id.substr(5);
    if(sceneNum === '1') sceneNum = '';

    return SCENE + sceneNum;
};

exports.updateFx = function(gd) {
    var fullLayout = gd._fullLayout;
    var subplotIds = fullLayout._subplots[GL3D];

    for(var i = 0; i < subplotIds.length; i++) {
        var subplotObj = fullLayout[subplotIds[i]]._scene;
        subplotObj.updateFx(fullLayout.dragmode, fullLayout.hovermode);
    }
};

},{"../../components/fx/layout_attributes":611,"../../constants/xmlns_namespaces":672,"../../lib":694,"../../plot_api/edit_types":725,"../get_data":779,"./layout/attributes":786,"./layout/defaults":790,"./layout/layout_attributes":791,"./scene":795}],786:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    scene: {
        valType: 'subplotid',
        
        dflt: 'scene',
        editType: 'calc+clearAxisTypes',
        
    }
};

},{}],787:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Color = _dereq_('../../../components/color');
var axesAttrs = _dereq_('../../cartesian/layout_attributes');
var extendFlat = _dereq_('../../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../../plot_api/edit_types').overrideAll;

module.exports = overrideAll({
    visible: axesAttrs.visible,
    showspikes: {
        valType: 'boolean',
        
        dflt: true,
        
    },
    spikesides: {
        valType: 'boolean',
        
        dflt: true,
        
    },
    spikethickness: {
        valType: 'number',
        
        min: 0,
        dflt: 2,
        
    },
    spikecolor: {
        valType: 'color',
        
        dflt: Color.defaultLine,
        
    },
    showbackground: {
        valType: 'boolean',
        
        dflt: false,
        
    },
    backgroundcolor: {
        valType: 'color',
        
        dflt: 'rgba(204, 204, 204, 0.5)',
        
    },
    showaxeslabels: {
        valType: 'boolean',
        
        dflt: true,
        
    },
    color: axesAttrs.color,
    categoryorder: axesAttrs.categoryorder,
    categoryarray: axesAttrs.categoryarray,
    title: axesAttrs.title,
    type: extendFlat({}, axesAttrs.type, {
        values: ['-', 'linear', 'log', 'date', 'category']
    }),
    autorange: axesAttrs.autorange,
    rangemode: axesAttrs.rangemode,
    range: extendFlat({}, axesAttrs.range, {
        items: [
            {valType: 'any', editType: 'plot', impliedEdits: {'^autorange': false}},
            {valType: 'any', editType: 'plot', impliedEdits: {'^autorange': false}}
        ],
        anim: false
    }),
    // ticks
    tickmode: axesAttrs.tickmode,
    nticks: axesAttrs.nticks,
    tick0: axesAttrs.tick0,
    dtick: axesAttrs.dtick,
    tickvals: axesAttrs.tickvals,
    ticktext: axesAttrs.ticktext,
    ticks: axesAttrs.ticks,
    mirror: axesAttrs.mirror,
    ticklen: axesAttrs.ticklen,
    tickwidth: axesAttrs.tickwidth,
    tickcolor: axesAttrs.tickcolor,
    showticklabels: axesAttrs.showticklabels,
    tickfont: axesAttrs.tickfont,
    tickangle: axesAttrs.tickangle,
    tickprefix: axesAttrs.tickprefix,
    showtickprefix: axesAttrs.showtickprefix,
    ticksuffix: axesAttrs.ticksuffix,
    showticksuffix: axesAttrs.showticksuffix,
    showexponent: axesAttrs.showexponent,
    exponentformat: axesAttrs.exponentformat,
    separatethousands: axesAttrs.separatethousands,
    tickformat: axesAttrs.tickformat,
    tickformatstops: axesAttrs.tickformatstops,
    hoverformat: axesAttrs.hoverformat,
    // lines and grids
    showline: axesAttrs.showline,
    linecolor: axesAttrs.linecolor,
    linewidth: axesAttrs.linewidth,
    showgrid: axesAttrs.showgrid,
    gridcolor: extendFlat({}, axesAttrs.gridcolor,  // shouldn't this be on-par with 2D?
        {dflt: 'rgb(204, 204, 204)'}),
    gridwidth: axesAttrs.gridwidth,
    zeroline: axesAttrs.zeroline,
    zerolinecolor: axesAttrs.zerolinecolor,
    zerolinewidth: axesAttrs.zerolinewidth,
    _deprecated: {
        title: axesAttrs._deprecated.title,
        titlefont: axesAttrs._deprecated.titlefont
    }
}, 'plot', 'from-root');

},{"../../../components/color":571,"../../../lib/extend":684,"../../../plot_api/edit_types":725,"../../cartesian/layout_attributes":755}],788:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var colorMix = _dereq_('tinycolor2').mix;

var Lib = _dereq_('../../../lib');
var Template = _dereq_('../../../plot_api/plot_template');

var layoutAttributes = _dereq_('./axis_attributes');
var handleTypeDefaults = _dereq_('../../cartesian/type_defaults');
var handleAxisDefaults = _dereq_('../../cartesian/axis_defaults');

var axesNames = ['xaxis', 'yaxis', 'zaxis'];

// TODO: hard-coded lightness fraction based on gridline default colors
// that differ from other subplot types.
var gridLightness = 100 * (204 - 0x44) / (255 - 0x44);

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, options) {
    var containerIn, containerOut;

    function coerce(attr, dflt) {
        return Lib.coerce(containerIn, containerOut, layoutAttributes, attr, dflt);
    }

    for(var j = 0; j < axesNames.length; j++) {
        var axName = axesNames[j];
        containerIn = layoutIn[axName] || {};

        containerOut = Template.newContainer(layoutOut, axName);
        containerOut._id = axName[0] + options.scene;
        containerOut._name = axName;

        handleTypeDefaults(containerIn, containerOut, coerce, options);

        handleAxisDefaults(
            containerIn,
            containerOut,
            coerce,
            {
                font: options.font,
                letter: axName[0],
                data: options.data,
                showGrid: true,
                noTickson: true,
                bgColor: options.bgColor,
                calendar: options.calendar
            },
            options.fullLayout);

        coerce('gridcolor', colorMix(containerOut.color, options.bgColor, gridLightness).toRgbString());
        coerce('title.text', axName[0]);  // shouldn't this be on-par with 2D?

        containerOut.setScale = Lib.noop;

        if(coerce('showspikes')) {
            coerce('spikesides');
            coerce('spikethickness');
            coerce('spikecolor', containerOut.color);
        }

        coerce('showaxeslabels');
        if(coerce('showbackground')) coerce('backgroundcolor');
    }
};

},{"../../../lib":694,"../../../plot_api/plot_template":732,"../../cartesian/axis_defaults":744,"../../cartesian/type_defaults":766,"./axis_attributes":787,"tinycolor2":515}],789:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var str2RgbaArray = _dereq_('../../../lib/str2rgbarray');
var Lib = _dereq_('../../../lib');

var AXES_NAMES = ['xaxis', 'yaxis', 'zaxis'];

function AxesOptions() {
    this.bounds = [
        [-10, -10, -10],
        [10, 10, 10]
    ];

    this.ticks = [ [], [], [] ];
    this.tickEnable = [ true, true, true ];
    this.tickFont = [ 'sans-serif', 'sans-serif', 'sans-serif' ];
    this.tickSize = [ 12, 12, 12 ];
    this.tickAngle = [ 0, 0, 0 ];
    this.tickColor = [ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1] ];
    this.tickPad = [ 18, 18, 18 ];

    this.labels = [ 'x', 'y', 'z' ];
    this.labelEnable = [ true, true, true ];
    this.labelFont = ['Open Sans', 'Open Sans', 'Open Sans'];
    this.labelSize = [ 20, 20, 20 ];
    this.labelColor = [ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1] ];
    this.labelPad = [ 30, 30, 30 ];

    this.lineEnable = [ true, true, true ];
    this.lineMirror = [ false, false, false ];
    this.lineWidth = [ 1, 1, 1 ];
    this.lineColor = [ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1] ];

    this.lineTickEnable = [ true, true, true ];
    this.lineTickMirror = [ false, false, false ];
    this.lineTickLength = [ 10, 10, 10 ];
    this.lineTickWidth = [ 1, 1, 1 ];
    this.lineTickColor = [ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1] ];

    this.gridEnable = [ true, true, true ];
    this.gridWidth = [ 1, 1, 1 ];
    this.gridColor = [ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1] ];

    this.zeroEnable = [ true, true, true ];
    this.zeroLineColor = [ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1] ];
    this.zeroLineWidth = [ 2, 2, 2 ];

    this.backgroundEnable = [ true, true, true ];
    this.backgroundColor = [ [0.8, 0.8, 0.8, 0.5],
                              [0.8, 0.8, 0.8, 0.5],
                              [0.8, 0.8, 0.8, 0.5] ];

    // some default values are stored for applying model transforms
    this._defaultTickPad = this.tickPad.slice();
    this._defaultLabelPad = this.labelPad.slice();
    this._defaultLineTickLength = this.lineTickLength.slice();
}

var proto = AxesOptions.prototype;

proto.merge = function(fullLayout, sceneLayout) {
    var opts = this;
    for(var i = 0; i < 3; ++i) {
        var axes = sceneLayout[AXES_NAMES[i]];

        if(!axes.visible) {
            opts.tickEnable[i] = false;
            opts.labelEnable[i] = false;
            opts.lineEnable[i] = false;
            opts.lineTickEnable[i] = false;
            opts.gridEnable[i] = false;
            opts.zeroEnable[i] = false;
            opts.backgroundEnable[i] = false;
            continue;
        }

        // Axes labels
        opts.labels[i] = fullLayout.meta ?
            Lib.templateString(axes.title.text, {meta: fullLayout.meta}) :
            axes.title.text;

        if('font' in axes.title) {
            if(axes.title.font.color) opts.labelColor[i] = str2RgbaArray(axes.title.font.color);
            if(axes.title.font.family) opts.labelFont[i] = axes.title.font.family;
            if(axes.title.font.size) opts.labelSize[i] = axes.title.font.size;
        }

        // Lines
        if('showline' in axes) opts.lineEnable[i] = axes.showline;
        if('linecolor' in axes) opts.lineColor[i] = str2RgbaArray(axes.linecolor);
        if('linewidth' in axes) opts.lineWidth[i] = axes.linewidth;

        if('showgrid' in axes) opts.gridEnable[i] = axes.showgrid;
        if('gridcolor' in axes) opts.gridColor[i] = str2RgbaArray(axes.gridcolor);
        if('gridwidth' in axes) opts.gridWidth[i] = axes.gridwidth;

        // Remove zeroline if axis type is log
        // otherwise the zeroline is incorrectly drawn at 1 on log axes
        if(axes.type === 'log') opts.zeroEnable[i] = false;
        else if('zeroline' in axes) opts.zeroEnable[i] = axes.zeroline;
        if('zerolinecolor' in axes) opts.zeroLineColor[i] = str2RgbaArray(axes.zerolinecolor);
        if('zerolinewidth' in axes) opts.zeroLineWidth[i] = axes.zerolinewidth;

        // tick lines
        if('ticks' in axes && !!axes.ticks) opts.lineTickEnable[i] = true;
        else opts.lineTickEnable[i] = false;

        if('ticklen' in axes) {
            opts.lineTickLength[i] = opts._defaultLineTickLength[i] = axes.ticklen;
        }
        if('tickcolor' in axes) opts.lineTickColor[i] = str2RgbaArray(axes.tickcolor);
        if('tickwidth' in axes) opts.lineTickWidth[i] = axes.tickwidth;
        if('tickangle' in axes) {
            opts.tickAngle[i] = (axes.tickangle === 'auto') ?
                -3600 : // i.e. special number to set auto option
                Math.PI * -axes.tickangle / 180;
        }

        // tick labels
        if('showticklabels' in axes) opts.tickEnable[i] = axes.showticklabels;
        if('tickfont' in axes) {
            if(axes.tickfont.color) opts.tickColor[i] = str2RgbaArray(axes.tickfont.color);
            if(axes.tickfont.family) opts.tickFont[i] = axes.tickfont.family;
            if(axes.tickfont.size) opts.tickSize[i] = axes.tickfont.size;
        }

        if('mirror' in axes) {
            if(['ticks', 'all', 'allticks'].indexOf(axes.mirror) !== -1) {
                opts.lineTickMirror[i] = true;
                opts.lineMirror[i] = true;
            } else if(axes.mirror === true) {
                opts.lineTickMirror[i] = false;
                opts.lineMirror[i] = true;
            } else {
                opts.lineTickMirror[i] = false;
                opts.lineMirror[i] = false;
            }
        } else opts.lineMirror[i] = false;

        // grid background
        if('showbackground' in axes && axes.showbackground !== false) {
            opts.backgroundEnable[i] = true;
            opts.backgroundColor[i] = str2RgbaArray(axes.backgroundcolor);
        } else opts.backgroundEnable[i] = false;
    }
};


function createAxesOptions(fullLayout, sceneLayout) {
    var result = new AxesOptions();
    result.merge(fullLayout, sceneLayout);
    return result;
}

module.exports = createAxesOptions;

},{"../../../lib":694,"../../../lib/str2rgbarray":717}],790:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../../lib');
var Color = _dereq_('../../../components/color');
var Registry = _dereq_('../../../registry');

var handleSubplotDefaults = _dereq_('../../subplot_defaults');
var supplyGl3dAxisLayoutDefaults = _dereq_('./axis_defaults');
var layoutAttributes = _dereq_('./layout_attributes');
var getSubplotData = _dereq_('../../get_data').getSubplotData;

var GL3D = 'gl3d';

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
    var hasNon3D = layoutOut._basePlotModules.length > 1;

    // some layout-wide attribute are used in all scenes
    // if 3D is the only visible plot type
    function getDfltFromLayout(attr) {
        if(hasNon3D) return;

        var isValid = Lib.validate(layoutIn[attr], layoutAttributes[attr]);
        if(isValid) return layoutIn[attr];
    }

    handleSubplotDefaults(layoutIn, layoutOut, fullData, {
        type: GL3D,
        attributes: layoutAttributes,
        handleDefaults: handleGl3dDefaults,
        fullLayout: layoutOut,
        font: layoutOut.font,
        fullData: fullData,
        getDfltFromLayout: getDfltFromLayout,
        paper_bgcolor: layoutOut.paper_bgcolor,
        calendar: layoutOut.calendar
    });
};

function handleGl3dDefaults(sceneLayoutIn, sceneLayoutOut, coerce, opts) {
    /*
     * Scene numbering proceeds as follows
     * scene
     * scene2
     * scene3
     *
     * and d.scene will be undefined or some number or number string
     *
     * Also write back a blank scene object to user layout so that some
     * attributes like aspectratio can be written back dynamically.
     */

    var bgcolor = coerce('bgcolor');
    var bgColorCombined = Color.combine(bgcolor, opts.paper_bgcolor);

    var cameraKeys = ['up', 'center', 'eye'];

    for(var j = 0; j < cameraKeys.length; j++) {
        coerce('camera.' + cameraKeys[j] + '.x');
        coerce('camera.' + cameraKeys[j] + '.y');
        coerce('camera.' + cameraKeys[j] + '.z');
    }

    /*
     * coerce to positive number (min 0) but also do not accept 0 (>0 not >=0)
     * note that 0's go false with the !! call
     */
    var hasAspect = !!coerce('aspectratio.x') &&
                    !!coerce('aspectratio.y') &&
                    !!coerce('aspectratio.z');

    var defaultAspectMode = hasAspect ? 'manual' : 'auto';
    var aspectMode = coerce('aspectmode', defaultAspectMode);

    /*
     * We need aspectratio object in all the Layouts as it is dynamically set
     * in the calculation steps, ie, we cant set the correct data now, it happens later.
     * We must also account for the case the user sends bad ratio data with 'manual' set
     * for the mode. In this case we must force change it here as the default coerce
     * misses it above.
     */
    if(!hasAspect) {
        sceneLayoutIn.aspectratio = sceneLayoutOut.aspectratio = {x: 1, y: 1, z: 1};

        if(aspectMode === 'manual') sceneLayoutOut.aspectmode = 'auto';

        /*
         * kind of like autorange - we need the calculated aspectmode back in
         * the input layout or relayout can cause problems later
         */
        sceneLayoutIn.aspectmode = sceneLayoutOut.aspectmode;
    }

    var fullGl3dData = getSubplotData(opts.fullData, GL3D, opts.id);

    supplyGl3dAxisLayoutDefaults(sceneLayoutIn, sceneLayoutOut, {
        font: opts.font,
        scene: opts.id,
        data: fullGl3dData,
        bgColor: bgColorCombined,
        calendar: opts.calendar,
        fullLayout: opts.fullLayout
    });

    Registry.getComponentMethod('annotations3d', 'handleDefaults')(
        sceneLayoutIn, sceneLayoutOut, opts
    );

    var dragmode = opts.getDfltFromLayout('dragmode');

    if(dragmode !== false) {
        if(!dragmode) {

            dragmode = 'orbit';

            if(sceneLayoutIn.camera &&
                sceneLayoutIn.camera.up) {

                var x = sceneLayoutIn.camera.up.x;
                var y = sceneLayoutIn.camera.up.y;
                var z = sceneLayoutIn.camera.up.z;

                if(z !== 0) {
                    if(!x || !y || !z) {
                        dragmode = 'turntable';
                    } else if(z / Math.sqrt(x * x + y * y + z * z) > 0.999) {
                        dragmode = 'turntable';
                    }
                }
            } else {
                dragmode = 'turntable';
            }
        }
    }

    coerce('dragmode', dragmode);
    coerce('hovermode', opts.getDfltFromLayout('hovermode'));
}

},{"../../../components/color":571,"../../../lib":694,"../../../registry":825,"../../get_data":779,"../../subplot_defaults":820,"./axis_defaults":788,"./layout_attributes":791}],791:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var gl3dAxisAttrs = _dereq_('./axis_attributes');
var domainAttrs = _dereq_('../../domain').attributes;
var extendFlat = _dereq_('../../../lib/extend').extendFlat;
var counterRegex = _dereq_('../../../lib').counterRegex;

function makeCameraVector(x, y, z) {
    return {
        x: {
            valType: 'number',
            
            dflt: x,
            editType: 'camera'
        },
        y: {
            valType: 'number',
            
            dflt: y,
            editType: 'camera'
        },
        z: {
            valType: 'number',
            
            dflt: z,
            editType: 'camera'
        },
        editType: 'camera'
    };
}

module.exports = {
    _arrayAttrRegexps: [counterRegex('scene', '.annotations', true)],

    bgcolor: {
        valType: 'color',
        
        dflt: 'rgba(0,0,0,0)',
        editType: 'plot'
    },
    camera: {
        up: extendFlat(makeCameraVector(0, 0, 1), {
            
        }),
        center: extendFlat(makeCameraVector(0, 0, 0), {
            
        }),
        eye: extendFlat(makeCameraVector(1.25, 1.25, 1.25), {
            
        }),
        editType: 'camera'
    },
    domain: domainAttrs({name: 'scene', editType: 'plot'}),
    aspectmode: {
        valType: 'enumerated',
        
        values: ['auto', 'cube', 'data', 'manual'],
        dflt: 'auto',
        editType: 'plot',
        impliedEdits: {
            'aspectratio.x': undefined,
            'aspectratio.y': undefined,
            'aspectratio.z': undefined
        },
        
    },
    aspectratio: { // must be positive (0's are coerced to 1)
        x: {
            valType: 'number',
            
            min: 0,
            editType: 'plot',
            impliedEdits: {'^aspectmode': 'manual'}
        },
        y: {
            valType: 'number',
            
            min: 0,
            editType: 'plot',
            impliedEdits: {'^aspectmode': 'manual'}
        },
        z: {
            valType: 'number',
            
            min: 0,
            editType: 'plot',
            impliedEdits: {'^aspectmode': 'manual'}
        },
        editType: 'plot',
        impliedEdits: {aspectmode: 'manual'},
        
    },

    xaxis: gl3dAxisAttrs,
    yaxis: gl3dAxisAttrs,
    zaxis: gl3dAxisAttrs,

    dragmode: {
        valType: 'enumerated',
        
        values: ['orbit', 'turntable', 'zoom', 'pan', false],
        editType: 'plot',
        
    },
    hovermode: {
        valType: 'enumerated',
        
        values: ['closest', false],
        dflt: 'closest',
        editType: 'modebar',
        
    },
    uirevision: {
        valType: 'any',
        
        editType: 'none',
        
    },
    editType: 'plot',

    _deprecated: {
        cameraposition: {
            valType: 'info_array',
            
            editType: 'camera',
            
        }
    }
};

},{"../../../lib":694,"../../../lib/extend":684,"../../domain":768,"./axis_attributes":787}],792:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var str2RGBArray = _dereq_('../../../lib/str2rgbarray');

var AXES_NAMES = ['xaxis', 'yaxis', 'zaxis'];

function SpikeOptions() {
    this.enabled = [true, true, true];
    this.colors = [[0, 0, 0, 1],
                   [0, 0, 0, 1],
                   [0, 0, 0, 1]];
    this.drawSides = [true, true, true];
    this.lineWidth = [1, 1, 1];
}

var proto = SpikeOptions.prototype;

proto.merge = function(sceneLayout) {
    for(var i = 0; i < 3; ++i) {
        var axes = sceneLayout[AXES_NAMES[i]];

        if(!axes.visible) {
            this.enabled[i] = false;
            this.drawSides[i] = false;
            continue;
        }

        this.enabled[i] = axes.showspikes;
        this.colors[i] = str2RGBArray(axes.spikecolor);
        this.drawSides[i] = axes.spikesides;
        this.lineWidth[i] = axes.spikethickness;
    }
};

function createSpikeOptions(layout) {
    var result = new SpikeOptions();
    result.merge(layout);
    return result;
}

module.exports = createSpikeOptions;

},{"../../../lib/str2rgbarray":717}],793:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

/* eslint block-scoped-var: 0*/
/* eslint no-redeclare: 0*/

'use strict';

module.exports = computeTickMarks;

var Axes = _dereq_('../../cartesian/axes');
var Lib = _dereq_('../../../lib');

var AXES_NAMES = ['xaxis', 'yaxis', 'zaxis'];

var centerPoint = [0, 0, 0];

function contourLevelsFromTicks(ticks) {
    var result = new Array(3);
    for(var i = 0; i < 3; ++i) {
        var tlevel = ticks[i];
        var clevel = new Array(tlevel.length);
        for(var j = 0; j < tlevel.length; ++j) {
            clevel[j] = tlevel[j].x;
        }
        result[i] = clevel;
    }
    return result;
}

function computeTickMarks(scene) {
    var axesOptions = scene.axesOptions;
    var glRange = scene.glplot.axesPixels;
    var sceneLayout = scene.fullSceneLayout;

    var ticks = [[], [], []];

    for(var i = 0; i < 3; ++i) {
        var axes = sceneLayout[AXES_NAMES[i]];

        axes._length = (glRange[i].hi - glRange[i].lo) *
            glRange[i].pixelsPerDataUnit / scene.dataScale[i];

        if(Math.abs(axes._length) === Infinity ||
           isNaN(axes._length)) {
            ticks[i] = [];
        } else {
            axes._input_range = axes.range.slice();
            axes.range[0] = (glRange[i].lo) / scene.dataScale[i];
            axes.range[1] = (glRange[i].hi) / scene.dataScale[i];
            axes._m = 1.0 / (scene.dataScale[i] * glRange[i].pixelsPerDataUnit);

            if(axes.range[0] === axes.range[1]) {
                axes.range[0] -= 1;
                axes.range[1] += 1;
            }
            // this is necessary to short-circuit the 'y' handling
            // in autotick part of calcTicks... Treating all axes as 'y' in this case
            // running the autoticks here, then setting
            // autoticks to false to get around the 2D handling in calcTicks.
            var tickModeCached = axes.tickmode;
            if(axes.tickmode === 'auto') {
                axes.tickmode = 'linear';
                var nticks = axes.nticks || Lib.constrain((axes._length / 40), 4, 9);
                Axes.autoTicks(axes, Math.abs(axes.range[1] - axes.range[0]) / nticks);
            }
            var dataTicks = Axes.calcTicks(axes);
            for(var j = 0; j < dataTicks.length; ++j) {
                dataTicks[j].x = dataTicks[j].x * scene.dataScale[i];

                if(axes.type === 'date') {
                    dataTicks[j].text =
                    dataTicks[j].text.replace(/\<br\>/g, ' ');
                }
            }
            ticks[i] = dataTicks;


            axes.tickmode = tickModeCached;
        }
    }

    axesOptions.ticks = ticks;

    // Calculate tick lengths dynamically
    for(var i = 0; i < 3; ++i) {
        centerPoint[i] = 0.5 * (scene.glplot.bounds[0][i] + scene.glplot.bounds[1][i]);
        for(var j = 0; j < 2; ++j) {
            axesOptions.bounds[j][i] = scene.glplot.bounds[j][i];
        }
    }

    scene.contourLevels = contourLevelsFromTicks(ticks);
}

},{"../../../lib":694,"../../cartesian/axes":742}],794:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

function xformMatrix(m, v) {
    var out = [0, 0, 0, 0];
    var i, j;

    for(i = 0; i < 4; ++i) {
        for(j = 0; j < 4; ++j) {
            out[j] += m[4 * i + j] * v[i];
        }
    }

    return out;
}

function project(camera, v) {
    var p = xformMatrix(camera.projection,
        xformMatrix(camera.view,
        xformMatrix(camera.model, [v[0], v[1], v[2], 1])));
    return p;
}

module.exports = project;

},{}],795:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var createPlot = _dereq_('gl-plot3d');
var getContext = _dereq_('webgl-context');
var passiveSupported = _dereq_('has-passive-events');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');

var Axes = _dereq_('../../plots/cartesian/axes');
var Fx = _dereq_('../../components/fx');

var str2RGBAarray = _dereq_('../../lib/str2rgbarray');
var showNoWebGlMsg = _dereq_('../../lib/show_no_webgl_msg');

var createCamera = _dereq_('./camera');
var project = _dereq_('./project');
var createAxesOptions = _dereq_('./layout/convert');
var createSpikeOptions = _dereq_('./layout/spikes');
var computeTickMarks = _dereq_('./layout/tick_marks');


var STATIC_CANVAS, STATIC_CONTEXT;

function render(scene) {
    var trace;

    // update size of svg container
    var svgContainer = scene.svgContainer;
    var clientRect = scene.container.getBoundingClientRect();
    var width = clientRect.width;
    var height = clientRect.height;
    svgContainer.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height);
    svgContainer.setAttributeNS(null, 'width', width);
    svgContainer.setAttributeNS(null, 'height', height);

    computeTickMarks(scene);
    scene.glplot.axes.update(scene.axesOptions);

    // check if pick has changed
    var keys = Object.keys(scene.traces);
    var lastPicked = null;
    var selection = scene.glplot.selection;
    for(var i = 0; i < keys.length; ++i) {
        trace = scene.traces[keys[i]];
        if(trace.data.hoverinfo !== 'skip' && trace.handlePick(selection)) {
            lastPicked = trace;
        }

        if(trace.setContourLevels) trace.setContourLevels();
    }

    function formatter(axisName, val) {
        var axis = scene.fullSceneLayout[axisName];

        return Axes.tickText(axis, axis.d2l(val), 'hover').text;
    }

    var oldEventData;

    if(lastPicked !== null) {
        var pdata = project(scene.glplot.cameraParams, selection.dataCoordinate);
        trace = lastPicked.data;
        var ptNumber = selection.index;
        var hoverinfo = Fx.castHoverinfo(trace, scene.fullLayout, ptNumber);
        var hoverinfoParts = hoverinfo.split('+');
        var isHoverinfoAll = hoverinfo === 'all';

        var xVal = formatter('xaxis', selection.traceCoordinate[0]);
        var yVal = formatter('yaxis', selection.traceCoordinate[1]);
        var zVal = formatter('zaxis', selection.traceCoordinate[2]);

        if(!isHoverinfoAll) {
            if(hoverinfoParts.indexOf('x') === -1) xVal = undefined;
            if(hoverinfoParts.indexOf('y') === -1) yVal = undefined;
            if(hoverinfoParts.indexOf('z') === -1) zVal = undefined;
            if(hoverinfoParts.indexOf('text') === -1) selection.textLabel = undefined;
            if(hoverinfoParts.indexOf('name') === -1) lastPicked.name = undefined;
        }

        var tx;
        var vectorTx = [];

        if(trace.type === 'cone' || trace.type === 'streamtube') {
            if(isHoverinfoAll || hoverinfoParts.indexOf('u') !== -1) {
                vectorTx.push('u: ' + formatter('xaxis', selection.traceCoordinate[3]));
            }
            if(isHoverinfoAll || hoverinfoParts.indexOf('v') !== -1) {
                vectorTx.push('v: ' + formatter('yaxis', selection.traceCoordinate[4]));
            }
            if(isHoverinfoAll || hoverinfoParts.indexOf('w') !== -1) {
                vectorTx.push('w: ' + formatter('zaxis', selection.traceCoordinate[5]));
            }
            if(isHoverinfoAll || hoverinfoParts.indexOf('norm') !== -1) {
                vectorTx.push('norm: ' + selection.traceCoordinate[6].toPrecision(3));
            }
            if(trace.type === 'streamtube' && (isHoverinfoAll || hoverinfoParts.indexOf('divergence') !== -1)) {
                vectorTx.push('divergence: ' + selection.traceCoordinate[7].toPrecision(3));
            }
            if(selection.textLabel) {
                vectorTx.push(selection.textLabel);
            }
            tx = vectorTx.join('<br>');
        } else if(trace.type === 'isosurface') {
            vectorTx.push('value: ' + Axes.tickText(scene.mockAxis, scene.mockAxis.d2l(selection.traceCoordinate[3]), 'hover').text);
            if(selection.textLabel) {
                vectorTx.push(selection.textLabel);
            }
            tx = vectorTx.join('<br>');
        } else {
            tx = selection.textLabel;
        }

        if(scene.fullSceneLayout.hovermode) {
            Fx.loneHover({
                x: (0.5 + 0.5 * pdata[0] / pdata[3]) * width,
                y: (0.5 - 0.5 * pdata[1] / pdata[3]) * height,
                xLabel: xVal,
                yLabel: yVal,
                zLabel: zVal,
                text: tx,
                name: lastPicked.name,
                color: Fx.castHoverOption(trace, ptNumber, 'bgcolor') || lastPicked.color,
                borderColor: Fx.castHoverOption(trace, ptNumber, 'bordercolor'),
                fontFamily: Fx.castHoverOption(trace, ptNumber, 'font.family'),
                fontSize: Fx.castHoverOption(trace, ptNumber, 'font.size'),
                fontColor: Fx.castHoverOption(trace, ptNumber, 'font.color')
            }, {
                container: svgContainer,
                gd: scene.graphDiv
            });
        }

        // TODO not sure if streamtube x/y/z should be emitted as x/y/z
        var pointData = {
            x: selection.traceCoordinate[0],
            y: selection.traceCoordinate[1],
            z: selection.traceCoordinate[2],
            data: trace._input,
            fullData: trace,
            curveNumber: trace.index,
            pointNumber: ptNumber
        };

        if(trace._module.eventData) {
            pointData = trace._module.eventData(pointData, selection, trace, {}, ptNumber);
        }

        Fx.appendArrayPointValue(pointData, trace, ptNumber);

        var eventData = {points: [pointData]};

        if(selection.buttons && selection.distance < 5) {
            scene.graphDiv.emit('plotly_click', eventData);
        }
        else {
            scene.graphDiv.emit('plotly_hover', eventData);
        }

        oldEventData = eventData;
    }
    else {
        Fx.loneUnhover(svgContainer);
        scene.graphDiv.emit('plotly_unhover', oldEventData);
    }

    scene.drawAnnotations(scene);
}

function initializeGLPlot(scene, canvas, gl) {
    var gd = scene.graphDiv;

    var glplotOptions = {
        canvas: canvas,
        gl: gl,
        container: scene.container,
        axes: scene.axesOptions,
        spikes: scene.spikeOptions,
        pickRadius: 10,
        snapToData: true,
        autoScale: true,
        autoBounds: false
    };

    // for static plots, we reuse the WebGL context
    //  as WebKit doesn't collect them reliably
    if(scene.staticMode) {
        if(!STATIC_CONTEXT) {
            STATIC_CANVAS = document.createElement('canvas');
            STATIC_CONTEXT = getContext({
                canvas: STATIC_CANVAS,
                preserveDrawingBuffer: true,
                premultipliedAlpha: true,
                antialias: true
            });
            if(!STATIC_CONTEXT) {
                throw new Error('error creating static canvas/context for image server');
            }
        }
        glplotOptions.pixelRatio = scene.pixelRatio;
        glplotOptions.gl = STATIC_CONTEXT;
        glplotOptions.canvas = STATIC_CANVAS;
    }

    try {
        scene.glplot = createPlot(glplotOptions);
    }
    catch(e) {
        /*
        * createPlot will throw when webgl is not enabled in the client.
        * Lets return an instance of the module with all functions noop'd.
        * The destroy method - which will remove the container from the DOM
        * is overridden with a function that removes the container only.
        */
        return showNoWebGlMsg(scene);
    }

    var relayoutCallback = function(scene) {
        if(scene.fullSceneLayout.dragmode === false) return;

        var update = {};
        update[scene.id + '.camera'] = getLayoutCamera(scene.camera);
        scene.saveCamera(gd.layout);
        scene.graphDiv.emit('plotly_relayout', update);
    };

    scene.glplot.canvas.addEventListener('mouseup', function() {
        relayoutCallback(scene);
    });

    scene.glplot.canvas.addEventListener('wheel', function() {
        if(gd._context._scrollZoom.gl3d) {
            relayoutCallback(scene);
        }
    }, passiveSupported ? {passive: false} : false);

    if(!scene.staticMode) {
        scene.glplot.canvas.addEventListener('webglcontextlost', function(event) {
            if(gd && gd.emit) {
                gd.emit('plotly_webglcontextlost', {
                    event: event,
                    layer: scene.id
                });
            }
        }, false);
    }

    if(!scene.camera) {
        var cameraData = scene.fullSceneLayout.camera;
        scene.camera = createCamera(scene.container, {
            center: [cameraData.center.x, cameraData.center.y, cameraData.center.z],
            eye: [cameraData.eye.x, cameraData.eye.y, cameraData.eye.z],
            up: [cameraData.up.x, cameraData.up.y, cameraData.up.z],
            zoomMin: 0.1,
            zoomMax: 100,
            mode: 'orbit'
        });
    }

    scene.glplot.camera = scene.camera;

    scene.glplot.oncontextloss = function() {
        scene.recoverContext();
    };

    scene.glplot.onrender = render.bind(null, scene);

    // List of scene objects
    scene.traces = {};

    scene.make4thDimension();

    return true;
}

function Scene(options, fullLayout) {

    // create sub container for plot
    var sceneContainer = document.createElement('div');
    var plotContainer = options.container;

    // keep a ref to the graph div to fire hover+click events
    this.graphDiv = options.graphDiv;

    // create SVG container for hover text
    var svgContainer = document.createElementNS(
        'http://www.w3.org/2000/svg',
        'svg');
    svgContainer.style.position = 'absolute';
    svgContainer.style.top = svgContainer.style.left = '0px';
    svgContainer.style.width = svgContainer.style.height = '100%';
    svgContainer.style['z-index'] = 20;
    svgContainer.style['pointer-events'] = 'none';
    sceneContainer.appendChild(svgContainer);
    this.svgContainer = svgContainer;

    // Tag the container with the sceneID
    sceneContainer.id = options.id;
    sceneContainer.style.position = 'absolute';
    sceneContainer.style.top = sceneContainer.style.left = '0px';
    sceneContainer.style.width = sceneContainer.style.height = '100%';
    plotContainer.appendChild(sceneContainer);

    this.fullLayout = fullLayout;
    this.id = options.id || 'scene';
    this.fullSceneLayout = fullLayout[this.id];

    // Saved from last call to plot()
    this.plotArgs = [ [], {}, {} ];

    /*
     * Move this to calc step? Why does it work here?
     */
    this.axesOptions = createAxesOptions(fullLayout, fullLayout[this.id]);
    this.spikeOptions = createSpikeOptions(fullLayout[this.id]);
    this.container = sceneContainer;
    this.staticMode = !!options.staticPlot;
    this.pixelRatio = options.plotGlPixelRatio || 2;

    // Coordinate rescaling
    this.dataScale = [1, 1, 1];

    this.contourLevels = [ [], [], [] ];

    this.convertAnnotations = Registry.getComponentMethod('annotations3d', 'convert');
    this.drawAnnotations = Registry.getComponentMethod('annotations3d', 'draw');

    if(!initializeGLPlot(this)) return; // todo check the necessity for this line
}

var proto = Scene.prototype;

proto.recoverContext = function() {
    var scene = this;
    var gl = this.glplot.gl;
    var canvas = this.glplot.canvas;
    this.glplot.dispose();

    function tryRecover() {
        if(gl.isContextLost()) {
            requestAnimationFrame(tryRecover);
            return;
        }
        if(!initializeGLPlot(scene, canvas, gl)) {
            Lib.error('Catastrophic and unrecoverable WebGL error. Context lost.');
            return;
        }
        scene.plot.apply(scene, scene.plotArgs);
    }
    requestAnimationFrame(tryRecover);
};

var axisProperties = [ 'xaxis', 'yaxis', 'zaxis' ];

function computeTraceBounds(scene, trace, bounds) {
    var sceneLayout = scene.fullSceneLayout;

    for(var d = 0; d < 3; d++) {
        var axisName = axisProperties[d];
        var axLetter = axisName.charAt(0);
        var ax = sceneLayout[axisName];
        var coords = trace[axLetter];
        var calendar = trace[axLetter + 'calendar'];
        var len = trace['_' + axLetter + 'length'];

        if(!Lib.isArrayOrTypedArray(coords)) {
            bounds[0][d] = Math.min(bounds[0][d], 0);
            bounds[1][d] = Math.max(bounds[1][d], len - 1);
        } else {
            var v;

            for(var i = 0; i < (len || coords.length); i++) {
                if(Lib.isArrayOrTypedArray(coords[i])) {
                    for(var j = 0; j < coords[i].length; ++j) {
                        v = ax.d2l(coords[i][j], 0, calendar);
                        if(!isNaN(v) && isFinite(v)) {
                            bounds[0][d] = Math.min(bounds[0][d], v);
                            bounds[1][d] = Math.max(bounds[1][d], v);
                        }
                    }
                } else {
                    v = ax.d2l(coords[i], 0, calendar);
                    if(!isNaN(v) && isFinite(v)) {
                        bounds[0][d] = Math.min(bounds[0][d], v);
                        bounds[1][d] = Math.max(bounds[1][d], v);
                    }
                }
            }
        }
    }
}

function computeAnnotationBounds(scene, bounds) {
    var sceneLayout = scene.fullSceneLayout;
    var annotations = sceneLayout.annotations || [];

    for(var d = 0; d < 3; d++) {
        var axisName = axisProperties[d];
        var axLetter = axisName.charAt(0);
        var ax = sceneLayout[axisName];

        for(var j = 0; j < annotations.length; j++) {
            var ann = annotations[j];

            if(ann.visible) {
                var pos = ax.r2l(ann[axLetter]);
                if(!isNaN(pos) && isFinite(pos)) {
                    bounds[0][d] = Math.min(bounds[0][d], pos);
                    bounds[1][d] = Math.max(bounds[1][d], pos);
                }
            }
        }
    }
}

proto.plot = function(sceneData, fullLayout, layout) {
    // Save parameters
    this.plotArgs = [sceneData, fullLayout, layout];

    if(this.glplot.contextLost) return;

    var data, trace;
    var i, j, axis, axisType;
    var fullSceneLayout = fullLayout[this.id];
    var sceneLayout = layout[this.id];

    if(fullSceneLayout.bgcolor) this.glplot.clearColor = str2RGBAarray(fullSceneLayout.bgcolor);
    else this.glplot.clearColor = [0, 0, 0, 0];

    this.glplot.snapToData = true;

    // Update layout
    this.fullLayout = fullLayout;
    this.fullSceneLayout = fullSceneLayout;

    this.glplotLayout = fullSceneLayout;
    this.axesOptions.merge(fullLayout, fullSceneLayout);
    this.spikeOptions.merge(fullSceneLayout);

    // Update camera and camera mode
    this.setCamera(fullSceneLayout.camera);
    this.updateFx(fullSceneLayout.dragmode, fullSceneLayout.hovermode);
    this.camera.enableWheel = this.graphDiv._context._scrollZoom.gl3d;

    // Update scene
    this.glplot.update({});

    // Update axes functions BEFORE updating traces
    this.setConvert(axis);

    // Convert scene data
    if(!sceneData) sceneData = [];
    else if(!Array.isArray(sceneData)) sceneData = [sceneData];

    // Compute trace bounding box
    var dataBounds = [
        [Infinity, Infinity, Infinity],
        [-Infinity, -Infinity, -Infinity]
    ];

    for(i = 0; i < sceneData.length; ++i) {
        data = sceneData[i];
        if(data.visible !== true) continue;

        computeTraceBounds(this, data, dataBounds);
    }
    computeAnnotationBounds(this, dataBounds);

    var dataScale = [1, 1, 1];
    for(j = 0; j < 3; ++j) {
        if(dataBounds[1][j] === dataBounds[0][j]) {
            dataScale[j] = 1.0;
        } else {
            dataScale[j] = 1.0 / (dataBounds[1][j] - dataBounds[0][j]);
        }
    }

    // Save scale
    this.dataScale = dataScale;

    // after computeTraceBounds where ax._categories are filled in
    this.convertAnnotations(this);

    // Update traces
    for(i = 0; i < sceneData.length; ++i) {
        data = sceneData[i];
        if(data.visible !== true) {
            continue;
        }
        trace = this.traces[data.uid];
        if(trace) {
            if(trace.data.type === data.type) {
                trace.update(data);
            } else {
                trace.dispose();
                trace = data._module.plot(this, data);
                this.traces[data.uid] = trace;
            }
        } else {
            trace = data._module.plot(this, data);
            this.traces[data.uid] = trace;
        }
        trace.name = data.name;
    }

    // Remove empty traces
    var traceIds = Object.keys(this.traces);

    traceIdLoop:
    for(i = 0; i < traceIds.length; ++i) {
        for(j = 0; j < sceneData.length; ++j) {
            if(sceneData[j].uid === traceIds[i] && sceneData[j].visible === true) {
                continue traceIdLoop;
            }
        }
        trace = this.traces[traceIds[i]];
        trace.dispose();
        delete this.traces[traceIds[i]];
    }

    // order object per trace index
    this.glplot.objects.sort(function(a, b) {
        return a._trace.data.index - b._trace.data.index;
    });

    // Update ranges (needs to be called *after* objects are added due to updates)
    var sceneBounds = [[0, 0, 0], [0, 0, 0]];
    var axisDataRange = [];
    var axisTypeRatios = {};

    for(i = 0; i < 3; ++i) {
        axis = fullSceneLayout[axisProperties[i]];
        axisType = axis.type;

        if(axisType in axisTypeRatios) {
            axisTypeRatios[axisType].acc *= dataScale[i];
            axisTypeRatios[axisType].count += 1;
        }
        else {
            axisTypeRatios[axisType] = {
                acc: dataScale[i],
                count: 1
            };
        }

        if(axis.autorange) {
            sceneBounds[0][i] = Infinity;
            sceneBounds[1][i] = -Infinity;

            var objects = this.glplot.objects;
            var annotations = this.fullSceneLayout.annotations || [];
            var axLetter = axis._name.charAt(0);

            for(j = 0; j < objects.length; j++) {
                var obj = objects[j];
                var objBounds = obj.bounds;
                var pad = obj._trace.data._pad || 0;

                if(obj.constructor.name === 'ErrorBars' && axis._lowerLogErrorBound) {
                    sceneBounds[0][i] = Math.min(sceneBounds[0][i], axis._lowerLogErrorBound);
                } else {
                    sceneBounds[0][i] = Math.min(sceneBounds[0][i], objBounds[0][i] / dataScale[i] - pad);
                }
                sceneBounds[1][i] = Math.max(sceneBounds[1][i], objBounds[1][i] / dataScale[i] + pad);
            }

            for(j = 0; j < annotations.length; j++) {
                var ann = annotations[j];

                // N.B. not taking into consideration the arrowhead
                if(ann.visible) {
                    var pos = axis.r2l(ann[axLetter]);
                    sceneBounds[0][i] = Math.min(sceneBounds[0][i], pos);
                    sceneBounds[1][i] = Math.max(sceneBounds[1][i], pos);
                }
            }

            if('rangemode' in axis && axis.rangemode === 'tozero') {
                sceneBounds[0][i] = Math.min(sceneBounds[0][i], 0);
                sceneBounds[1][i] = Math.max(sceneBounds[1][i], 0);
            }
            if(sceneBounds[0][i] > sceneBounds[1][i]) {
                sceneBounds[0][i] = -1;
                sceneBounds[1][i] = 1;
            } else {
                var d = sceneBounds[1][i] - sceneBounds[0][i];
                sceneBounds[0][i] -= d / 32.0;
                sceneBounds[1][i] += d / 32.0;
            }

            if(axis.autorange === 'reversed') {
                // swap bounds:
                var tmp = sceneBounds[0][i];
                sceneBounds[0][i] = sceneBounds[1][i];
                sceneBounds[1][i] = tmp;
            }
        } else {
            var range = axis.range;
            sceneBounds[0][i] = axis.r2l(range[0]);
            sceneBounds[1][i] = axis.r2l(range[1]);
        }
        if(sceneBounds[0][i] === sceneBounds[1][i]) {
            sceneBounds[0][i] -= 1;
            sceneBounds[1][i] += 1;
        }
        axisDataRange[i] = sceneBounds[1][i] - sceneBounds[0][i];

        // Update plot bounds
        this.glplot.bounds[0][i] = sceneBounds[0][i] * dataScale[i];
        this.glplot.bounds[1][i] = sceneBounds[1][i] * dataScale[i];
    }

    var axesScaleRatio = [1, 1, 1];

    // Compute axis scale per category
    for(i = 0; i < 3; ++i) {
        axis = fullSceneLayout[axisProperties[i]];
        axisType = axis.type;
        var axisRatio = axisTypeRatios[axisType];
        axesScaleRatio[i] = Math.pow(axisRatio.acc, 1.0 / axisRatio.count) / dataScale[i];
    }

    /*
     * Dynamically set the aspect ratio depending on the users aspect settings
     */
    var axisAutoScaleFactor = 4;
    var aspectRatio;

    if(fullSceneLayout.aspectmode === 'auto') {

        if(Math.max.apply(null, axesScaleRatio) / Math.min.apply(null, axesScaleRatio) <= axisAutoScaleFactor) {

            /*
             * USE DATA MODE WHEN AXIS RANGE DIMENSIONS ARE RELATIVELY EQUAL
             */

            aspectRatio = axesScaleRatio;
        } else {

            /*
             * USE EQUAL MODE WHEN AXIS RANGE DIMENSIONS ARE HIGHLY UNEQUAL
             */
            aspectRatio = [1, 1, 1];
        }

    } else if(fullSceneLayout.aspectmode === 'cube') {
        aspectRatio = [1, 1, 1];

    } else if(fullSceneLayout.aspectmode === 'data') {
        aspectRatio = axesScaleRatio;

    } else if(fullSceneLayout.aspectmode === 'manual') {
        var userRatio = fullSceneLayout.aspectratio;
        aspectRatio = [userRatio.x, userRatio.y, userRatio.z];

    } else {
        throw new Error('scene.js aspectRatio was not one of the enumerated types');
    }

    /*
     * Write aspect Ratio back to user data and fullLayout so that it is modifies as user
     * manipulates the aspectmode settings and the fullLayout is up-to-date.
     */
    fullSceneLayout.aspectratio.x = sceneLayout.aspectratio.x = aspectRatio[0];
    fullSceneLayout.aspectratio.y = sceneLayout.aspectratio.y = aspectRatio[1];
    fullSceneLayout.aspectratio.z = sceneLayout.aspectratio.z = aspectRatio[2];

    /*
     * Finally assign the computed aspecratio to the glplot module. This will have an effect
     * on the next render cycle.
     */
    this.glplot.aspect = aspectRatio;


    // Update frame position for multi plots
    var domain = fullSceneLayout.domain || null;
    var size = fullLayout._size || null;

    if(domain && size) {
        var containerStyle = this.container.style;
        containerStyle.position = 'absolute';
        containerStyle.left = (size.l + domain.x[0] * size.w) + 'px';
        containerStyle.top = (size.t + (1 - domain.y[1]) * size.h) + 'px';
        containerStyle.width = (size.w * (domain.x[1] - domain.x[0])) + 'px';
        containerStyle.height = (size.h * (domain.y[1] - domain.y[0])) + 'px';
    }

    // force redraw so that promise is returned when rendering is completed
    this.glplot.redraw();
};

proto.destroy = function() {
    if(!this.glplot) return;

    this.camera.mouseListener.enabled = false;
    this.container.removeEventListener('wheel', this.camera.wheelListener);
    this.camera = this.glplot.camera = null;
    this.glplot.dispose();
    this.container.parentNode.removeChild(this.container);
    this.glplot = null;
};

// getOrbitCamera :: plotly_coords -> orbit_camera_coords
// inverse of getLayoutCamera
function getOrbitCamera(camera) {
    return [
        [camera.eye.x, camera.eye.y, camera.eye.z],
        [camera.center.x, camera.center.y, camera.center.z],
        [camera.up.x, camera.up.y, camera.up.z]
    ];
}

// getLayoutCamera :: orbit_camera_coords -> plotly_coords
// inverse of getOrbitCamera
function getLayoutCamera(camera) {
    return {
        up: {x: camera.up[0], y: camera.up[1], z: camera.up[2]},
        center: {x: camera.center[0], y: camera.center[1], z: camera.center[2]},
        eye: {x: camera.eye[0], y: camera.eye[1], z: camera.eye[2]}
    };
}

// get camera position in plotly coords from 'orbit-camera' coords
proto.getCamera = function getCamera() {
    this.glplot.camera.view.recalcMatrix(this.camera.view.lastT());
    return getLayoutCamera(this.glplot.camera);
};

// set camera position with a set of plotly coords
proto.setCamera = function setCamera(cameraData) {
    this.glplot.camera.lookAt.apply(this, getOrbitCamera(cameraData));
};

// save camera to user layout (i.e. gd.layout)
proto.saveCamera = function saveCamera(layout) {
    var fullLayout = this.fullLayout;
    var cameraData = this.getCamera();
    var cameraNestedProp = Lib.nestedProperty(layout, this.id + '.camera');
    var cameraDataLastSave = cameraNestedProp.get();
    var hasChanged = false;

    function same(x, y, i, j) {
        var vectors = ['up', 'center', 'eye'];
        var components = ['x', 'y', 'z'];
        return y[vectors[i]] && (x[vectors[i]][components[j]] === y[vectors[i]][components[j]]);
    }

    if(cameraDataLastSave === undefined) {
        hasChanged = true;
    } else {
        for(var i = 0; i < 3; i++) {
            for(var j = 0; j < 3; j++) {
                if(!same(cameraData, cameraDataLastSave, i, j)) {
                    hasChanged = true;
                    break;
                }
            }
        }
    }

    if(hasChanged) {
        var preGUI = {};
        preGUI[this.id + '.camera'] = cameraDataLastSave;
        Registry.call('_storeDirectGUIEdit', layout, fullLayout._preGUI, preGUI);

        cameraNestedProp.set(cameraData);

        var cameraFullNP = Lib.nestedProperty(fullLayout, this.id + '.camera');
        cameraFullNP.set(cameraData);
    }

    return hasChanged;
};

proto.updateFx = function(dragmode, hovermode) {
    var camera = this.camera;

    if(camera) {
        // rotate and orbital are synonymous
        if(dragmode === 'orbit') {
            camera.mode = 'orbit';
            camera.keyBindingMode = 'rotate';

        } else if(dragmode === 'turntable') {
            camera.up = [0, 0, 1];
            camera.mode = 'turntable';
            camera.keyBindingMode = 'rotate';

            // The setter for camera.mode animates the transition to z-up,
            // but only if we *don't* explicitly set z-up earlier via the
            // relayout. So push `up` back to layout & fullLayout manually now.
            var gd = this.graphDiv;
            var fullLayout = gd._fullLayout;
            var fullCamera = this.fullSceneLayout.camera;
            var x = fullCamera.up.x;
            var y = fullCamera.up.y;
            var z = fullCamera.up.z;
            // only push `up` back to (full)layout if it's going to change
            if(z / Math.sqrt(x * x + y * y + z * z) > 0.999) return;

            var attr = this.id + '.camera.up';
            var zUp = {x: 0, y: 0, z: 1};
            var edits = {};
            edits[attr] = zUp;
            var layout = gd.layout;
            Registry.call('_storeDirectGUIEdit', layout, fullLayout._preGUI, edits);
            fullCamera.up = zUp;
            Lib.nestedProperty(layout, attr).set(zUp);
        } else {
            // none rotation modes [pan or zoom]
            camera.keyBindingMode = dragmode;
        }
    }

    // to put dragmode and hovermode on the same grounds from relayout
    this.fullSceneLayout.hovermode = hovermode;
};

proto.toImage = function(format) {
    if(!format) format = 'png';

    if(this.staticMode) this.container.appendChild(STATIC_CANVAS);

    // Force redraw
    this.glplot.redraw();

    // Grab context and yank out pixels
    var gl = this.glplot.gl;
    var w = gl.drawingBufferWidth;
    var h = gl.drawingBufferHeight;

    gl.bindFramebuffer(gl.FRAMEBUFFER, null);

    var pixels = new Uint8Array(w * h * 4);
    gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, pixels);

    // Flip pixels
    for(var j = 0, k = h - 1; j < k; ++j, --k) {
        for(var i = 0; i < w; ++i) {
            for(var l = 0; l < 4; ++l) {
                var tmp = pixels[4 * (w * j + i) + l];
                pixels[4 * (w * j + i) + l] = pixels[4 * (w * k + i) + l];
                pixels[4 * (w * k + i) + l] = tmp;
            }
        }
    }

    var canvas = document.createElement('canvas');
    canvas.width = w;
    canvas.height = h;
    var context = canvas.getContext('2d');
    var imageData = context.createImageData(w, h);
    imageData.data.set(pixels);
    context.putImageData(imageData, 0, 0);

    var dataURL;

    switch(format) {
        case 'jpeg':
            dataURL = canvas.toDataURL('image/jpeg');
            break;
        case 'webp':
            dataURL = canvas.toDataURL('image/webp');
            break;
        default:
            dataURL = canvas.toDataURL('image/png');
    }

    if(this.staticMode) this.container.removeChild(STATIC_CANVAS);

    return dataURL;
};

proto.setConvert = function() {
    for(var i = 0; i < 3; i++) {
        var ax = this.fullSceneLayout[axisProperties[i]];
        Axes.setConvert(ax, this.fullLayout);
        ax.setScale = Lib.noop;
    }
};

proto.make4thDimension = function() {

    var _this = this;
    var gd = _this.graphDiv;
    var fullLayout = gd._fullLayout;

    // mock axis for hover formatting
    _this.mockAxis = {
        type: 'linear',
        showexponent: 'all',
        exponentformat: 'B'
    };
    Axes.setConvert(_this.mockAxis, fullLayout);
};

module.exports = Scene;

},{"../../components/fx":610,"../../lib":694,"../../lib/show_no_webgl_msg":715,"../../lib/str2rgbarray":717,"../../plots/cartesian/axes":742,"../../registry":825,"./camera":784,"./layout/convert":789,"./layout/spikes":792,"./layout/tick_marks":793,"./project":794,"gl-plot3d":279,"has-passive-events":397,"webgl-context":534}],796:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function zip3(x, y, z, len) {
    len = len || x.length;

    var result = new Array(len);
    for(var i = 0; i < len; i++) {
        result[i] = [x[i], y[i], z[i]];
    }
    return result;
};

},{}],797:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = _dereq_('./font_attributes');
var animationAttrs = _dereq_('./animation_attributes');
var colorAttrs = _dereq_('../components/color/attributes');
var colorscaleAttrs = _dereq_('../components/colorscale/layout_attributes');
var padAttrs = _dereq_('./pad_attributes');
var extendFlat = _dereq_('../lib/extend').extendFlat;

var globalFont = fontAttrs({
    editType: 'calc',
    
});
globalFont.family.dflt = '"Open Sans", verdana, arial, sans-serif';
globalFont.size.dflt = 12;
globalFont.color.dflt = colorAttrs.defaultLine;

module.exports = {
    font: globalFont,
    title: {
        text: {
            valType: 'string',
            
            editType: 'layoutstyle',
            
        },
        font: fontAttrs({
            editType: 'layoutstyle',
            
        }),
        xref: {
            valType: 'enumerated',
            dflt: 'container',
            values: ['container', 'paper'],
            
            editType: 'layoutstyle',
            
        },
        yref: {
            valType: 'enumerated',
            dflt: 'container',
            values: ['container', 'paper'],
            
            editType: 'layoutstyle',
            
        },
        x: {
            valType: 'number',
            min: 0,
            max: 1,
            dflt: 0.5,
            
            editType: 'layoutstyle',
            
        },
        y: {
            valType: 'number',
            min: 0,
            max: 1,
            dflt: 'auto',
            
            editType: 'layoutstyle',
            
        },
        xanchor: {
            valType: 'enumerated',
            dflt: 'auto',
            values: ['auto', 'left', 'center', 'right'],
            
            editType: 'layoutstyle',
            
        },
        yanchor: {
            valType: 'enumerated',
            dflt: 'auto',
            values: ['auto', 'top', 'middle', 'bottom'],
            
            editType: 'layoutstyle',
            
        },
        pad: extendFlat(padAttrs({editType: 'layoutstyle'}), {
            
        }),
        editType: 'layoutstyle'
    },
    autosize: {
        valType: 'boolean',
        
        dflt: false,
        // autosize, width, and height get special editType treatment in _relayout
        // so we can handle noop resizes more efficiently
        editType: 'none',
        
    },
    width: {
        valType: 'number',
        
        min: 10,
        dflt: 700,
        editType: 'plot',
        
    },
    height: {
        valType: 'number',
        
        min: 10,
        dflt: 450,
        editType: 'plot',
        
    },
    margin: {
        l: {
            valType: 'number',
            
            min: 0,
            dflt: 80,
            editType: 'plot',
            
        },
        r: {
            valType: 'number',
            
            min: 0,
            dflt: 80,
            editType: 'plot',
            
        },
        t: {
            valType: 'number',
            
            min: 0,
            dflt: 100,
            editType: 'plot',
            
        },
        b: {
            valType: 'number',
            
            min: 0,
            dflt: 80,
            editType: 'plot',
            
        },
        pad: {
            valType: 'number',
            
            min: 0,
            dflt: 0,
            editType: 'plot',
            
        },
        autoexpand: {
            valType: 'boolean',
            
            dflt: true,
            editType: 'plot'
        },
        editType: 'plot'
    },
    paper_bgcolor: {
        valType: 'color',
        
        dflt: colorAttrs.background,
        editType: 'plot',
        
    },
    plot_bgcolor: {
        // defined here, but set in cartesian.supplyLayoutDefaults
        // because it needs to know if there are (2D) axes or not
        valType: 'color',
        
        dflt: colorAttrs.background,
        editType: 'layoutstyle',
        
    },
    separators: {
        valType: 'string',
        
        editType: 'plot',
        
    },
    hidesources: {
        valType: 'boolean',
        
        dflt: false,
        editType: 'plot',
        
    },
    showlegend: {
        // handled in legend.supplyLayoutDefaults
        // but included here because it's not in the legend object
        valType: 'boolean',
        
        editType: 'legend',
        
    },
    colorway: {
        valType: 'colorlist',
        dflt: colorAttrs.defaults,
        
        editType: 'calc',
        
    },
    colorscale: colorscaleAttrs,
    datarevision: {
        valType: 'any',
        
        editType: 'calc',
        
    },
    uirevision: {
        valType: 'any',
        
        editType: 'none',
        
    },
    editrevision: {
        valType: 'any',
        
        editType: 'none',
        
    },
    selectionrevision: {
        valType: 'any',
        
        editType: 'none',
        
    },
    template: {
        valType: 'any',
        
        editType: 'calc',
        
    },
    modebar: {
        orientation: {
            valType: 'enumerated',
            values: ['v', 'h'],
            dflt: 'h',
            
            editType: 'modebar',
            
        },
        bgcolor: {
            valType: 'color',
            
            editType: 'modebar',
            
        },
        color: {
            valType: 'color',
            
            editType: 'modebar',
            
        },
        activecolor: {
            valType: 'color',
            
            editType: 'modebar',
            
        },
        uirevision: {
            valType: 'any',
            
            editType: 'none',
            
        },
        editType: 'modebar'
    },

    meta: {
        valType: 'data_array',
        editType: 'plot',
        
    },

    transition: extendFlat({}, animationAttrs.transition, {
        
        editType: 'none'
    }),

    _deprecated: {
        title: {
            valType: 'string',
            
            editType: 'layoutstyle',
            
        },
        titlefont: fontAttrs({
            editType: 'layoutstyle',
            
        })
    }
};

},{"../components/color/attributes":570,"../components/colorscale/layout_attributes":584,"../lib/extend":684,"./animation_attributes":737,"./font_attributes":769,"./pad_attributes":805}],798:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var requiredVersion = '0.45.0';

module.exports = {
    requiredVersion: requiredVersion,

    styleUrlPrefix: 'mapbox://styles/mapbox/',
    styleUrlSuffix: 'v9',

    controlContainerClassName: 'mapboxgl-control-container',

    wrongVersionErrorMsg: [
        'Your custom plotly.js bundle is not using the correct mapbox-gl version',
        'Please install mapbox-gl@' + requiredVersion + '.'
    ].join('\n'),

    noAccessTokenErrorMsg: [
        'Missing Mapbox access token.',
        'Mapbox trace type require a Mapbox access token to be registered.',
        'For example:',
        '  Plotly.plot(gd, data, layout, { mapboxAccessToken: \'my-access-token\' });',
        'More info here: https://www.mapbox.com/help/define-access-token/'
    ].join('\n'),

    mapOnErrorMsg: 'Mapbox error.',

    // a subset of node_modules/mapbox-gl/dist/mapbox-gl.css
    styleRules: {
        map: 'overflow:hidden;position:relative;',
        'missing-css': 'display:none',
    }
};

},{}],799:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

/**
 * Convert plotly.js 'textposition' to mapbox-gl 'anchor' and 'offset'
 * (with the help of the icon size).
 *
 * @param {string} textpostion : plotly.js textposition value
 * @param {number} iconSize : plotly.js icon size (e.g. marker.size for traces)
 *
 * @return {object}
 *      - anchor
 *      - offset
 */
module.exports = function convertTextOpts(textposition, iconSize) {
    var parts = textposition.split(' ');
    var vPos = parts[0];
    var hPos = parts[1];

    // ballpack values
    var factor = Lib.isArrayOrTypedArray(iconSize) ? Lib.mean(iconSize) : iconSize;
    var xInc = 0.5 + (factor / 100);
    var yInc = 1.5 + (factor / 100);

    var anchorVals = ['', ''];
    var offset = [0, 0];

    switch(vPos) {
        case 'top':
            anchorVals[0] = 'top';
            offset[1] = -yInc;
            break;
        case 'bottom':
            anchorVals[0] = 'bottom';
            offset[1] = yInc;
            break;
    }

    switch(hPos) {
        case 'left':
            anchorVals[1] = 'right';
            offset[0] = -xInc;
            break;
        case 'right':
            anchorVals[1] = 'left';
            offset[0] = xInc;
            break;
    }

    // Mapbox text-anchor must be one of:
    //  center, left, right, top, bottom,
    //  top-left, top-right, bottom-left, bottom-right

    var anchor;
    if(anchorVals[0] && anchorVals[1]) anchor = anchorVals.join('-');
    else if(anchorVals[0]) anchor = anchorVals[0];
    else if(anchorVals[1]) anchor = anchorVals[1];
    else anchor = 'center';

    return { anchor: anchor, offset: offset };
};

},{"../../lib":694}],800:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var mapboxgl = _dereq_('mapbox-gl');

var Lib = _dereq_('../../lib');
var getSubplotCalcData = _dereq_('../../plots/get_data').getSubplotCalcData;
var xmlnsNamespaces = _dereq_('../../constants/xmlns_namespaces');

var createMapbox = _dereq_('./mapbox');
var constants = _dereq_('./constants');

var MAPBOX = 'mapbox';

for(var k in constants.styleRules) {
    Lib.addStyleRule('.mapboxgl-' + k, constants.styleRules[k]);
}

exports.name = MAPBOX;

exports.attr = 'subplot';

exports.idRoot = MAPBOX;

exports.idRegex = exports.attrRegex = Lib.counterRegex(MAPBOX);

exports.attributes = {
    subplot: {
        valType: 'subplotid',
        
        dflt: 'mapbox',
        editType: 'calc',
        
    }
};

exports.layoutAttributes = _dereq_('./layout_attributes');

exports.supplyLayoutDefaults = _dereq_('./layout_defaults');

exports.plot = function plotMapbox(gd) {
    var fullLayout = gd._fullLayout;
    var calcData = gd.calcdata;
    var mapboxIds = fullLayout._subplots[MAPBOX];

    if(mapboxgl.version !== constants.requiredVersion) {
        throw new Error(constants.wrongVersionErrorMsg);
    }

    var accessToken = findAccessToken(gd, mapboxIds);
    mapboxgl.accessToken = accessToken;

    for(var i = 0; i < mapboxIds.length; i++) {
        var id = mapboxIds[i];
        var subplotCalcData = getSubplotCalcData(calcData, MAPBOX, id);
        var opts = fullLayout[id];
        var mapbox = opts._subplot;

        if(!mapbox) {
            mapbox = createMapbox({
                gd: gd,
                container: fullLayout._glcontainer.node(),
                id: id,
                fullLayout: fullLayout,
                staticPlot: gd._context.staticPlot
            });

            fullLayout[id]._subplot = mapbox;
        }

        if(!mapbox.viewInitial) {
            mapbox.viewInitial = {
                center: Lib.extendFlat({}, opts.center),
                zoom: opts.zoom,
                bearing: opts.bearing,
                pitch: opts.pitch
            };
        }

        mapbox.plot(subplotCalcData, fullLayout, gd._promises);
    }
};

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var oldMapboxKeys = oldFullLayout._subplots[MAPBOX] || [];

    for(var i = 0; i < oldMapboxKeys.length; i++) {
        var oldMapboxKey = oldMapboxKeys[i];

        if(!newFullLayout[oldMapboxKey] && !!oldFullLayout[oldMapboxKey]._subplot) {
            oldFullLayout[oldMapboxKey]._subplot.destroy();
        }
    }
};

exports.toSVG = function(gd) {
    var fullLayout = gd._fullLayout;
    var subplotIds = fullLayout._subplots[MAPBOX];
    var size = fullLayout._size;

    for(var i = 0; i < subplotIds.length; i++) {
        var opts = fullLayout[subplotIds[i]];
        var domain = opts.domain;
        var mapbox = opts._subplot;

        var imageData = mapbox.toImage('png');
        var image = fullLayout._glimages.append('svg:image');

        image.attr({
            xmlns: xmlnsNamespaces.svg,
            'xlink:href': imageData,
            x: size.l + size.w * domain.x[0],
            y: size.t + size.h * (1 - domain.y[1]),
            width: size.w * (domain.x[1] - domain.x[0]),
            height: size.h * (domain.y[1] - domain.y[0]),
            preserveAspectRatio: 'none'
        });

        mapbox.destroy();
    }
};

function findAccessToken(gd, mapboxIds) {
    var fullLayout = gd._fullLayout;
    var context = gd._context;

    // special case for Mapbox Atlas users
    if(context.mapboxAccessToken === '') return '';

    // Take the first token we find in a mapbox subplot.
    // These default to the context value but may be overridden.
    for(var i = 0; i < mapboxIds.length; i++) {
        var opts = fullLayout[mapboxIds[i]];

        if(opts.accesstoken) {
            return opts.accesstoken;
        }
    }

    throw new Error(constants.noAccessTokenErrorMsg);
}

exports.updateFx = function(gd) {
    var fullLayout = gd._fullLayout;
    var subplotIds = fullLayout._subplots[MAPBOX];

    for(var i = 0; i < subplotIds.length; i++) {
        var subplotObj = fullLayout[subplotIds[i]]._subplot;
        subplotObj.updateFx(fullLayout);
    }
};

},{"../../constants/xmlns_namespaces":672,"../../lib":694,"../../plots/get_data":779,"./constants":798,"./layout_attributes":802,"./layout_defaults":803,"./mapbox":804,"mapbox-gl":412}],801:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var convertTextOpts = _dereq_('./convert_text_opts');

function MapboxLayer(mapbox, index) {
    this.mapbox = mapbox;
    this.map = mapbox.map;

    this.uid = mapbox.uid + '-' + 'layer' + index;

    this.idSource = this.uid + '-source';
    this.idLayer = this.uid + '-layer';

    // some state variable to check if a remove/add step is needed
    this.sourceType = null;
    this.source = null;
    this.layerType = null;
    this.below = null;

    // is layer currently visible
    this.visible = false;
}

var proto = MapboxLayer.prototype;

proto.update = function update(opts) {
    if(!this.visible) {
        // IMPORTANT: must create source before layer to not cause errors
        this.updateSource(opts);
        this.updateLayer(opts);
    } else if(this.needsNewSource(opts)) {
        // IMPORTANT: must delete layer before source to not cause errors
        this.removeLayer();
        this.updateSource(opts);
        this.updateLayer(opts);
    } else if(this.needsNewLayer(opts)) {
        this.updateLayer(opts);
    } else {
        this.updateStyle(opts);
    }

    this.visible = isVisible(opts);
};

proto.needsNewSource = function(opts) {
    // for some reason changing layer to 'fill' or 'symbol'
    // w/o changing the source throws an exception in mapbox-gl 0.18 ;
    // stay safe and make new source on type changes
    return (
        this.sourceType !== opts.sourcetype ||
        this.source !== opts.source ||
        this.layerType !== opts.type
    );
};

proto.needsNewLayer = function(opts) {
    return (
        this.layerType !== opts.type ||
        this.below !== opts.below
    );
};

proto.updateSource = function(opts) {
    var map = this.map;

    if(map.getSource(this.idSource)) map.removeSource(this.idSource);

    this.sourceType = opts.sourcetype;
    this.source = opts.source;

    if(!isVisible(opts)) return;

    var sourceOpts = convertSourceOpts(opts);

    map.addSource(this.idSource, sourceOpts);
};

proto.updateLayer = function(opts) {
    var map = this.map;
    var convertedOpts = convertOpts(opts);

    this.removeLayer();
    this.layerType = opts.type;

    if(isVisible(opts)) {
        map.addLayer({
            id: this.idLayer,
            source: this.idSource,
            'source-layer': opts.sourcelayer || '',
            type: opts.type,
            layout: convertedOpts.layout,
            paint: convertedOpts.paint
        }, opts.below);
    }
};

proto.updateStyle = function(opts) {
    if(isVisible(opts)) {
        var convertedOpts = convertOpts(opts);
        this.mapbox.setOptions(this.idLayer, 'setLayoutProperty', convertedOpts.layout);
        this.mapbox.setOptions(this.idLayer, 'setPaintProperty', convertedOpts.paint);
    }
};

proto.removeLayer = function() {
    var map = this.map;
    if(map.getLayer(this.idLayer)) {
        map.removeLayer(this.idLayer);
    }
};

proto.dispose = function dispose() {
    var map = this.map;
    map.removeLayer(this.idLayer);
    map.removeSource(this.idSource);
};

function isVisible(opts) {
    var source = opts.source;

    return opts.visible && (
        Lib.isPlainObject(source) ||
        (typeof source === 'string' && source.length > 0)
    );
}

function convertOpts(opts) {
    var layout = {};
    var paint = {};

    switch(opts.type) {

        case 'circle':
            Lib.extendFlat(paint, {
                'circle-radius': opts.circle.radius,
                'circle-color': opts.color,
                'circle-opacity': opts.opacity
            });
            break;

        case 'line':
            Lib.extendFlat(paint, {
                'line-width': opts.line.width,
                'line-color': opts.color,
                'line-opacity': opts.opacity
            });
            break;

        case 'fill':
            Lib.extendFlat(paint, {
                'fill-color': opts.color,
                'fill-outline-color': opts.fill.outlinecolor,
                'fill-opacity': opts.opacity

                // no way to pass specify outline width at the moment
            });
            break;

        case 'symbol':
            var symbol = opts.symbol;
            var textOpts = convertTextOpts(symbol.textposition, symbol.iconsize);

            Lib.extendFlat(layout, {
                'icon-image': symbol.icon + '-15',
                'icon-size': symbol.iconsize / 10,

                'text-field': symbol.text,
                'text-size': symbol.textfont.size,
                'text-anchor': textOpts.anchor,
                'text-offset': textOpts.offset

                // TODO font family
                // 'text-font': symbol.textfont.family.split(', '),
            });

            Lib.extendFlat(paint, {
                'icon-color': opts.color,
                'text-color': symbol.textfont.color,
                'text-opacity': opts.opacity
            });
            break;
    }

    return { layout: layout, paint: paint };
}

function convertSourceOpts(opts) {
    var sourceType = opts.sourcetype;
    var source = opts.source;
    var sourceOpts = {type: sourceType};
    var field;

    if(sourceType === 'geojson') {
        field = 'data';
    } else if(sourceType === 'vector') {
        field = typeof source === 'string' ? 'url' : 'tiles';
    }

    sourceOpts[field] = source;
    return sourceOpts;
}

module.exports = function createMapboxLayer(mapbox, index, opts) {
    var mapboxLayer = new MapboxLayer(mapbox, index);

    mapboxLayer.update(opts);

    return mapboxLayer;
};

},{"../../lib":694,"./convert_text_opts":799}],802:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var defaultLine = _dereq_('../../components/color').defaultLine;
var domainAttrs = _dereq_('../domain').attributes;
var fontAttrs = _dereq_('../font_attributes');
var textposition = _dereq_('../../traces/scatter/attributes').textposition;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;

var fontAttr = fontAttrs({
    
});
fontAttr.family.dflt = 'Open Sans Regular, Arial Unicode MS Regular';

var attrs = module.exports = overrideAll({
    _arrayAttrRegexps: [Lib.counterRegex('mapbox', '.layers', true)],

    domain: domainAttrs({name: 'mapbox'}),

    accesstoken: {
        valType: 'string',
        noBlank: true,
        strict: true,
        
        
    },
    style: {
        valType: 'any',
        values: ['basic', 'streets', 'outdoors', 'light', 'dark', 'satellite', 'satellite-streets'],
        dflt: 'basic',
        
        
    },

    center: {
        lon: {
            valType: 'number',
            dflt: 0,
            
            
        },
        lat: {
            valType: 'number',
            dflt: 0,
            
            
        }
    },
    zoom: {
        valType: 'number',
        dflt: 1,
        
        
    },
    bearing: {
        valType: 'number',
        dflt: 0,
        
        
    },
    pitch: {
        valType: 'number',
        dflt: 0,
        
        
    },

    layers: templatedArray('layer', {
        visible: {
            valType: 'boolean',
            
            dflt: true,
            
        },
        sourcetype: {
            valType: 'enumerated',
            values: ['geojson', 'vector'],
            dflt: 'geojson',
            
            
        },

        source: {
            valType: 'any',
            
            
        },

        sourcelayer: {
            valType: 'string',
            dflt: '',
            
            
        },

        type: {
            valType: 'enumerated',
            values: ['circle', 'line', 'fill', 'symbol'],
            dflt: 'circle',
            
            
        },

        // attributes shared between all types
        below: {
            valType: 'string',
            dflt: '',
            
            
        },
        color: {
            valType: 'color',
            dflt: defaultLine,
            
            
        },
        opacity: {
            valType: 'number',
            min: 0,
            max: 1,
            dflt: 1,
            
            
        },

        // type-specific style attributes
        circle: {
            radius: {
                valType: 'number',
                dflt: 15,
                
                
            }
        },

        line: {
            width: {
                valType: 'number',
                dflt: 2,
                
                
            }
        },

        fill: {
            outlinecolor: {
                valType: 'color',
                dflt: defaultLine,
                
                
            }
        },

        symbol: {
            icon: {
                valType: 'string',
                dflt: 'marker',
                
                
            },
            iconsize: {
                valType: 'number',
                dflt: 10,
                
                
            },
            text: {
                valType: 'string',
                dflt: '',
                
                
            },
            textfont: fontAttr,
            textposition: Lib.extendFlat({}, textposition, { arrayOk: false })
        }
    })
}, 'plot', 'from-root');

// set uirevision outside of overrideAll so it can be `editType: 'none'`
attrs.uirevision = {
    valType: 'any',
    
    editType: 'none',
    
};

},{"../../components/color":571,"../../lib":694,"../../plot_api/edit_types":725,"../../plot_api/plot_template":732,"../../traces/scatter/attributes":1047,"../domain":768,"../font_attributes":769}],803:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

var handleSubplotDefaults = _dereq_('../subplot_defaults');
var handleArrayContainerDefaults = _dereq_('../array_container_defaults');
var layoutAttributes = _dereq_('./layout_attributes');


module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
    handleSubplotDefaults(layoutIn, layoutOut, fullData, {
        type: 'mapbox',
        attributes: layoutAttributes,
        handleDefaults: handleDefaults,
        partition: 'y',
        accessToken: layoutOut._mapboxAccessToken
    });
};

function handleDefaults(containerIn, containerOut, coerce, opts) {
    coerce('accesstoken', opts.accessToken);
    coerce('style');
    coerce('center.lon');
    coerce('center.lat');
    coerce('zoom');
    coerce('bearing');
    coerce('pitch');

    handleArrayContainerDefaults(containerIn, containerOut, {
        name: 'layers',
        handleItemDefaults: handleLayerDefaults
    });

    // copy ref to input container to update 'center' and 'zoom' on map move
    containerOut._input = containerIn;
}

function handleLayerDefaults(layerIn, layerOut) {
    function coerce(attr, dflt) {
        return Lib.coerce(layerIn, layerOut, layoutAttributes.layers, attr, dflt);
    }

    var visible = coerce('visible');
    if(visible) {
        var sourceType = coerce('sourcetype');
        coerce('source');

        if(sourceType === 'vector') coerce('sourcelayer');

        // maybe add smart default based off GeoJSON geometry?
        var type = coerce('type');

        coerce('below');
        coerce('color');
        coerce('opacity');

        if(type === 'circle') {
            coerce('circle.radius');
        }

        if(type === 'line') {
            coerce('line.width');
        }

        if(type === 'fill') {
            coerce('fill.outlinecolor');
        }

        if(type === 'symbol') {
            coerce('symbol.icon');
            coerce('symbol.iconsize');

            coerce('symbol.text');
            Lib.coerceFont(coerce, 'symbol.textfont');
            coerce('symbol.textposition');
        }
    }
}

},{"../../lib":694,"../array_container_defaults":738,"../subplot_defaults":820,"./layout_attributes":802}],804:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var mapboxgl = _dereq_('mapbox-gl');

var Fx = _dereq_('../../components/fx');
var Lib = _dereq_('../../lib');
var Registry = _dereq_('../../registry');
var dragElement = _dereq_('../../components/dragelement');
var prepSelect = _dereq_('../cartesian/select').prepSelect;
var selectOnClick = _dereq_('../cartesian/select').selectOnClick;
var constants = _dereq_('./constants');
var layoutAttributes = _dereq_('./layout_attributes');
var createMapboxLayer = _dereq_('./layers');

function Mapbox(opts) {
    this.id = opts.id;
    this.gd = opts.gd;
    this.container = opts.container;
    this.isStatic = opts.staticPlot;

    var fullLayout = opts.fullLayout;

    // unique id for this Mapbox instance
    this.uid = fullLayout._uid + '-' + this.id;

    // create framework on instantiation for a smoother first plot call
    this.div = null;
    this.xaxis = null;
    this.yaxis = null;
    this.createFramework(fullLayout);

    // state variables used to infer how and what to update
    this.map = null;
    this.accessToken = null;
    this.styleObj = null;
    this.traceHash = {};
    this.layerList = [];
}

var proto = Mapbox.prototype;

module.exports = function createMapbox(opts) {
    return new Mapbox(opts);
};

proto.plot = function(calcData, fullLayout, promises) {
    var self = this;
    var opts = fullLayout[self.id];

    // remove map and create a new map if access token has change
    if(self.map && (opts.accesstoken !== self.accessToken)) {
        self.map.remove();
        self.map = null;
        self.styleObj = null;
        self.traceHash = [];
        self.layerList = {};
    }

    var promise;

    if(!self.map) {
        promise = new Promise(function(resolve, reject) {
            self.createMap(calcData, fullLayout, resolve, reject);
        });
    } else {
        promise = new Promise(function(resolve, reject) {
            self.updateMap(calcData, fullLayout, resolve, reject);
        });
    }

    promises.push(promise);
};

proto.createMap = function(calcData, fullLayout, resolve, reject) {
    var self = this;
    var gd = self.gd;
    var opts = fullLayout[self.id];

    // store style id and URL or object
    var styleObj = self.styleObj = getStyleObj(opts.style);

    // store access token associated with this map
    self.accessToken = opts.accesstoken;

    // create the map!
    var map = self.map = new mapboxgl.Map({
        container: self.div,

        style: styleObj.style,
        center: convertCenter(opts.center),
        zoom: opts.zoom,
        bearing: opts.bearing,
        pitch: opts.pitch,

        interactive: !self.isStatic,
        preserveDrawingBuffer: self.isStatic,

        doubleClickZoom: false,
        boxZoom: false
    });

    // clear navigation container
    var className = constants.controlContainerClassName;
    var controlContainer = self.div.getElementsByClassName(className)[0];
    self.div.removeChild(controlContainer);

    // make sure canvas does not inherit left and top css
    map._canvas.style.left = '0px';
    map._canvas.style.top = '0px';

    self.rejectOnError(reject);

    map.once('load', function() {
        self.updateData(calcData);
        self.updateLayout(fullLayout);
        self.resolveOnRender(resolve);
    });

    if(self.isStatic) return;

    var wheeling = false;

    // keep track of pan / zoom in user layout and emit relayout event
    map.on('moveend', function(eventData) {
        if(!self.map) return;

        // 'moveend' gets triggered by map.setCenter, map.setZoom,
        // map.setBearing and map.setPitch.
        //
        // Here, we make sure that state updates amd 'plotly_relayout'
        // are triggered only when the 'moveend' originates from a
        // mouse target (filtering out API calls) to not
        // duplicate 'plotly_relayout' events.

        if(eventData.originalEvent || wheeling) {
            var optsNow = gd._fullLayout[self.id];
            Registry.call('_storeDirectGUIEdit', gd.layout, gd._fullLayout._preGUI, self.getViewEdits(optsNow));

            var viewNow = self.getView();
            optsNow._input.center = optsNow.center = viewNow.center;
            optsNow._input.zoom = optsNow.zoom = viewNow.zoom;
            optsNow._input.bearing = optsNow.bearing = viewNow.bearing;
            optsNow._input.pitch = optsNow.pitch = viewNow.pitch;

            gd.emit('plotly_relayout', self.getViewEdits(viewNow));
        }
        wheeling = false;
    });

    map.on('wheel', function() {
        wheeling = true;
    });

    map.on('mousemove', function(evt) {
        var bb = self.div.getBoundingClientRect();

        // some hackery to get Fx.hover to work
        evt.clientX = evt.point.x + bb.left;
        evt.clientY = evt.point.y + bb.top;

        evt.target.getBoundingClientRect = function() { return bb; };

        self.xaxis.p2c = function() { return evt.lngLat.lng; };
        self.yaxis.p2c = function() { return evt.lngLat.lat; };

        Fx.hover(gd, evt, self.id);
    });

    function unhover() {
        Fx.loneUnhover(fullLayout._toppaper);
    }

    map.on('dragstart', unhover);
    map.on('zoomstart', unhover);

    map.on('dblclick', function() {
        var optsNow = gd._fullLayout[self.id];
        Registry.call('_storeDirectGUIEdit', gd.layout, gd._fullLayout._preGUI, self.getViewEdits(optsNow));

        var viewInitial = self.viewInitial;
        map.setCenter(convertCenter(viewInitial.center));
        map.setZoom(viewInitial.zoom);
        map.setBearing(viewInitial.bearing);
        map.setPitch(viewInitial.pitch);

        var viewNow = self.getView();
        optsNow._input.center = optsNow.center = viewNow.center;
        optsNow._input.zoom = optsNow.zoom = viewNow.zoom;
        optsNow._input.bearing = optsNow.bearing = viewNow.bearing;
        optsNow._input.pitch = optsNow.pitch = viewNow.pitch;

        gd.emit('plotly_doubleclick', null);
        gd.emit('plotly_relayout', self.getViewEdits(viewNow));
    });

    // define event handlers on map creation, to keep one ref per map,
    // so that map.on / map.off in updateFx works as expected
    self.clearSelect = function() {
        gd._fullLayout._zoomlayer.selectAll('.select-outline').remove();
    };

    /**
     * Returns a click handler function that is supposed
     * to handle clicks in pan mode.
     */
    self.onClickInPanFn = function(dragOptions) {
        return function(evt) {
            var clickMode = gd._fullLayout.clickmode;

            if(clickMode.indexOf('select') > -1) {
                selectOnClick(evt.originalEvent, gd, [self.xaxis], [self.yaxis], self.id, dragOptions);
            }

            if(clickMode.indexOf('event') > -1) {
                // TODO: this does not support right-click. If we want to support it, we
                // would likely need to change mapbox to use dragElement instead of straight
                // mapbox event binding. Or perhaps better, make a simple wrapper with the
                // right mousedown, mousemove, and mouseup handlers just for a left/right click
                // pie would use this too.
                Fx.click(gd, evt.originalEvent);
            }
        };
    };
};

proto.updateMap = function(calcData, fullLayout, resolve, reject) {
    var self = this;
    var map = self.map;
    var opts = fullLayout[this.id];

    self.rejectOnError(reject);

    var styleObj = getStyleObj(opts.style);

    if(self.styleObj.id !== styleObj.id) {
        self.styleObj = styleObj;
        map.setStyle(styleObj.style);

        map.once('styledata', function() {
            // need to rebuild trace layers on reload
            // to avoid 'lost event' errors
            self.traceHash = {};
            self.updateData(calcData);
            self.updateLayout(fullLayout);
            self.resolveOnRender(resolve);
        });
    } else {
        self.updateData(calcData);
        self.updateLayout(fullLayout);
        self.resolveOnRender(resolve);
    }

    if(this.gd._context._scrollZoom.mapbox) {
        map.scrollZoom.enable();
    } else {
        map.scrollZoom.disable();
    }
};

proto.updateData = function(calcData) {
    var traceHash = this.traceHash;
    var traceObj, trace, i, j;

    // update or create trace objects
    for(i = 0; i < calcData.length; i++) {
        var calcTrace = calcData[i];

        trace = calcTrace[0].trace;
        traceObj = traceHash[trace.uid];

        if(traceObj) {
            traceObj.update(calcTrace);
        } else if(trace._module) {
            traceHash[trace.uid] = trace._module.plot(this, calcTrace);
        }
    }

    // remove empty trace objects
    var ids = Object.keys(traceHash);
    idLoop:
    for(i = 0; i < ids.length; i++) {
        var id = ids[i];

        for(j = 0; j < calcData.length; j++) {
            trace = calcData[j][0].trace;
            if(id === trace.uid) continue idLoop;
        }

        traceObj = traceHash[id];
        traceObj.dispose();
        delete traceHash[id];
    }
};

proto.updateLayout = function(fullLayout) {
    var map = this.map;
    var opts = fullLayout[this.id];

    map.setCenter(convertCenter(opts.center));
    map.setZoom(opts.zoom);
    map.setBearing(opts.bearing);
    map.setPitch(opts.pitch);

    this.updateLayers(fullLayout);
    this.updateFramework(fullLayout);
    this.updateFx(fullLayout);
    this.map.resize();
};

proto.resolveOnRender = function(resolve) {
    var map = this.map;

    map.on('render', function onRender() {
        if(map.loaded()) {
            map.off('render', onRender);
            // resolve at end of render loop
            setTimeout(resolve, 0);
        }
    });
};

proto.rejectOnError = function(reject) {
    var map = this.map;

    function handler() {
        reject(new Error(constants.mapOnErrorMsg));
    }

    map.once('error', handler);
    map.once('style.error', handler);
    map.once('source.error', handler);
    map.once('tile.error', handler);
    map.once('layer.error', handler);
};

proto.createFramework = function(fullLayout) {
    var self = this;

    var div = self.div = document.createElement('div');
    div.id = self.uid;
    div.style.position = 'absolute';
    self.container.appendChild(div);

    // create mock x/y axes for hover routine
    self.xaxis = {
        _id: 'x',
        c2p: function(v) { return self.project(v).x; }
    };
    self.yaxis = {
        _id: 'y',
        c2p: function(v) { return self.project(v).y; }
    };

    self.updateFramework(fullLayout);
};

proto.updateFx = function(fullLayout) {
    var self = this;
    var map = self.map;
    var gd = self.gd;

    if(self.isStatic) return;

    function invert(pxpy) {
        var obj = self.map.unproject(pxpy);
        return [obj.lng, obj.lat];
    }

    var dragMode = fullLayout.dragmode;
    var fillRangeItems;

    if(dragMode === 'select') {
        fillRangeItems = function(eventData, poly) {
            var ranges = eventData.range = {};
            ranges[self.id] = [
                invert([poly.xmin, poly.ymin]),
                invert([poly.xmax, poly.ymax])
            ];
        };
    } else {
        fillRangeItems = function(eventData, poly, pts) {
            var dataPts = eventData.lassoPoints = {};
            dataPts[self.id] = pts.filtered.map(invert);
        };
    }

    // Note: dragOptions is needed to be declared for all dragmodes because
    // it's the object that holds persistent selection state.
    // Merge old dragOptions with new to keep possibly initialized
    // persistent selection state.
    var oldDragOptions = self.dragOptions;
    self.dragOptions = Lib.extendDeep(oldDragOptions || {}, {
        element: self.div,
        gd: gd,
        plotinfo: {
            id: self.id,
            xaxis: self.xaxis,
            yaxis: self.yaxis,
            fillRangeItems: fillRangeItems
        },
        xaxes: [self.xaxis],
        yaxes: [self.yaxis],
        subplot: self.id
    });

    // Unregister the old handler before potentially registering
    // a new one. Otherwise multiple click handlers might
    // be registered resulting in unwanted behavior.
    map.off('click', self.onClickInPanHandler);
    if(dragMode === 'select' || dragMode === 'lasso') {
        map.dragPan.disable();
        map.on('zoomstart', self.clearSelect);

        self.dragOptions.prepFn = function(e, startX, startY) {
            prepSelect(e, startX, startY, self.dragOptions, dragMode);
        };

        dragElement.init(self.dragOptions);
    } else {
        map.dragPan.enable();
        map.off('zoomstart', self.clearSelect);
        self.div.onmousedown = null;

        // TODO: this does not support right-click. If we want to support it, we
        // would likely need to change mapbox to use dragElement instead of straight
        // mapbox event binding. Or perhaps better, make a simple wrapper with the
        // right mousedown, mousemove, and mouseup handlers just for a left/right click
        // pie would use this too.
        self.onClickInPanHandler = self.onClickInPanFn(self.dragOptions);
        map.on('click', self.onClickInPanHandler);
    }
};

proto.updateFramework = function(fullLayout) {
    var domain = fullLayout[this.id].domain;
    var size = fullLayout._size;

    var style = this.div.style;
    style.width = size.w * (domain.x[1] - domain.x[0]) + 'px';
    style.height = size.h * (domain.y[1] - domain.y[0]) + 'px';
    style.left = size.l + domain.x[0] * size.w + 'px';
    style.top = size.t + (1 - domain.y[1]) * size.h + 'px';

    this.xaxis._offset = size.l + domain.x[0] * size.w;
    this.xaxis._length = size.w * (domain.x[1] - domain.x[0]);

    this.yaxis._offset = size.t + (1 - domain.y[1]) * size.h;
    this.yaxis._length = size.h * (domain.y[1] - domain.y[0]);
};

proto.updateLayers = function(fullLayout) {
    var opts = fullLayout[this.id];
    var layers = opts.layers;
    var layerList = this.layerList;
    var i;

    // if the layer arrays don't match,
    // don't try to be smart,
    // delete them all, and start all over.

    if(layers.length !== layerList.length) {
        for(i = 0; i < layerList.length; i++) {
            layerList[i].dispose();
        }

        layerList = this.layerList = [];

        for(i = 0; i < layers.length; i++) {
            layerList.push(createMapboxLayer(this, i, layers[i]));
        }
    } else {
        for(i = 0; i < layers.length; i++) {
            layerList[i].update(layers[i]);
        }
    }
};

proto.destroy = function() {
    if(this.map) {
        this.map.remove();
        this.map = null;
        this.container.removeChild(this.div);
    }
};

proto.toImage = function() {
    this.map.stop();
    return this.map.getCanvas().toDataURL();
};

// convenience wrapper to create set multiple layer
// 'layout' or 'paint options at once.
proto.setOptions = function(id, methodName, opts) {
    for(var k in opts) {
        this.map[methodName](id, k, opts[k]);
    }
};

// convenience method to project a [lon, lat] array to pixel coords
proto.project = function(v) {
    return this.map.project(new mapboxgl.LngLat(v[0], v[1]));
};

// get map's current view values in plotly.js notation
proto.getView = function() {
    var map = this.map;
    var mapCenter = map.getCenter();
    var center = { lon: mapCenter.lng, lat: mapCenter.lat };

    return {
        center: center,
        zoom: map.getZoom(),
        bearing: map.getBearing(),
        pitch: map.getPitch()
    };
};

proto.getViewEdits = function(cont) {
    var id = this.id;
    var keys = ['center', 'zoom', 'bearing', 'pitch'];
    var obj = {};

    for(var i = 0; i < keys.length; i++) {
        var k = keys[i];
        obj[id + '.' + k] = cont[k];
    }

    return obj;
};

function getStyleObj(val) {
    var styleValues = layoutAttributes.style.values;
    var styleDflt = layoutAttributes.style.dflt;
    var styleObj = {};

    if(Lib.isPlainObject(val)) {
        styleObj.id = val.id;
        styleObj.style = val;
    } else if(typeof val === 'string') {
        styleObj.id = val;
        styleObj.style = (styleValues.indexOf(val) !== -1) ?
             convertStyleVal(val) :
             val;
    } else {
        styleObj.id = styleDflt;
        styleObj.style = convertStyleVal(styleDflt);
    }

    styleObj.transition = {duration: 0, delay: 0};

    return styleObj;
}

// if style is part of the 'official' mapbox values, add URL prefix and suffix
function convertStyleVal(val) {
    return constants.styleUrlPrefix + val + '-' + constants.styleUrlSuffix;
}

function convertCenter(center) {
    return [center.lon, center.lat];
}

},{"../../components/dragelement":589,"../../components/fx":610,"../../lib":694,"../../registry":825,"../cartesian/select":760,"./constants":798,"./layers":801,"./layout_attributes":802,"mapbox-gl":412}],805:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * Creates a set of padding attributes.
 *
 * @param {object} opts
 *   @param {string} editType:
 *     the editType for all pieces of this padding definition
 *
 * @return {object} attributes object containing {t, r, b, l} as specified
 */
module.exports = function(opts) {
    var editType = opts.editType;
    return {
        t: {
            valType: 'number',
            dflt: 0,
            
            editType: editType,
            
        },
        r: {
            valType: 'number',
            dflt: 0,
            
            editType: editType,
            
        },
        b: {
            valType: 'number',
            dflt: 0,
            
            editType: editType,
            
        },
        l: {
            valType: 'number',
            dflt: 0,
            
            editType: editType,
            
        },
        editType: editType
    };
};

},{}],806:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');

var Registry = _dereq_('../registry');
var PlotSchema = _dereq_('../plot_api/plot_schema');
var Template = _dereq_('../plot_api/plot_template');
var Lib = _dereq_('../lib');
var Color = _dereq_('../components/color');
var BADNUM = _dereq_('../constants/numerical').BADNUM;

var axisIDs = _dereq_('../plots/cartesian/axis_ids');

var animationAttrs = _dereq_('./animation_attributes');
var frameAttrs = _dereq_('./frame_attributes');

var relinkPrivateKeys = Lib.relinkPrivateKeys;
var _ = Lib._;

var plots = module.exports = {};

// Expose registry methods on Plots for backward-compatibility
Lib.extendFlat(plots, Registry);

plots.attributes = _dereq_('./attributes');
plots.attributes.type.values = plots.allTypes;
plots.fontAttrs = _dereq_('./font_attributes');
plots.layoutAttributes = _dereq_('./layout_attributes');

// TODO make this a plot attribute?
plots.fontWeight = 'normal';

var transformsRegistry = plots.transformsRegistry;

var commandModule = _dereq_('./command');
plots.executeAPICommand = commandModule.executeAPICommand;
plots.computeAPICommandBindings = commandModule.computeAPICommandBindings;
plots.manageCommandObserver = commandModule.manageCommandObserver;
plots.hasSimpleAPICommandBindings = commandModule.hasSimpleAPICommandBindings;

// in some cases the browser doesn't seem to know how big
// the text is at first, so it needs to draw it,
// then wait a little, then draw it again
plots.redrawText = function(gd) {
    gd = Lib.getGraphDiv(gd);

    // do not work if polar is present
    if((gd.data && gd.data[0] && gd.data[0].r)) return;

    return new Promise(function(resolve) {
        setTimeout(function() {
            Registry.getComponentMethod('annotations', 'draw')(gd);
            Registry.getComponentMethod('legend', 'draw')(gd);

            (gd.calcdata || []).forEach(function(d) {
                if(d[0] && d[0].t && d[0].t.cb) d[0].t.cb();
            });

            resolve(plots.previousPromises(gd));
        }, 300);
    });
};

// resize plot about the container size
plots.resize = function(gd) {
    gd = Lib.getGraphDiv(gd);

    return new Promise(function(resolve, reject) {

        function isHidden(gd) {
            var display = window.getComputedStyle(gd).display;
            return !display || display === 'none';
        }

        if(!gd || isHidden(gd)) {
            reject(new Error('Resize must be passed a displayed plot div element.'));
        }

        if(gd._redrawTimer) clearTimeout(gd._redrawTimer);

        gd._redrawTimer = setTimeout(function() {
            // return if there is nothing to resize or is hidden
            if(!gd.layout || (gd.layout.width && gd.layout.height) || isHidden(gd)) {
                resolve(gd);
                return;
            }

            delete gd.layout.width;
            delete gd.layout.height;

            // autosizing doesn't count as a change that needs saving
            var oldchanged = gd.changed;

            // nor should it be included in the undo queue
            gd.autoplay = true;

            Registry.call('relayout', gd, {autosize: true}).then(function() {
                gd.changed = oldchanged;
                resolve(gd);
            });
        }, 100);
    });
};


// for use in Lib.syncOrAsync, check if there are any
// pending promises in this plot and wait for them
plots.previousPromises = function(gd) {
    if((gd._promises || []).length) {
        return Promise.all(gd._promises)
            .then(function() { gd._promises = []; });
    }
};

/**
 * Adds the 'Edit chart' link.
 * Note that now Plotly.plot() calls this so it can regenerate whenever it replots
 *
 * Add source links to your graph inside the 'showSources' config argument.
 */
plots.addLinks = function(gd) {
    // Do not do anything if showLink and showSources are not set to true in config
    if(!gd._context.showLink && !gd._context.showSources) return;

    var fullLayout = gd._fullLayout;

    var linkContainer = Lib.ensureSingle(fullLayout._paper, 'text', 'js-plot-link-container', function(s) {
        s.style({
            'font-family': '"Open Sans", Arial, sans-serif',
            'font-size': '12px',
            'fill': Color.defaultLine,
            'pointer-events': 'all'
        })
        .each(function() {
            var links = d3.select(this);
            links.append('tspan').classed('js-link-to-tool', true);
            links.append('tspan').classed('js-link-spacer', true);
            links.append('tspan').classed('js-sourcelinks', true);
        });
    });

    // The text node inside svg
    var text = linkContainer.node();
    var attrs = {y: fullLayout._paper.attr('height') - 9};

    // If text's width is bigger than the layout
    // Check that text is a child node or document.body
    // because otherwise IE/Edge might throw an exception
    // when calling getComputedTextLength().
    // Apparently offsetParent is null for invisibles.
    if(document.body.contains(text) && text.getComputedTextLength() >= (fullLayout.width - 20)) {
        // Align the text at the left
        attrs['text-anchor'] = 'start';
        attrs.x = 5;
    }
    else {
        // Align the text at the right
        attrs['text-anchor'] = 'end';
        attrs.x = fullLayout._paper.attr('width') - 7;
    }

    linkContainer.attr(attrs);

    var toolspan = linkContainer.select('.js-link-to-tool');
    var spacespan = linkContainer.select('.js-link-spacer');
    var sourcespan = linkContainer.select('.js-sourcelinks');

    if(gd._context.showSources) gd._context.showSources(gd);

    // 'view in plotly' link for embedded plots
    if(gd._context.showLink) positionPlayWithData(gd, toolspan);

    // separator if we have both sources and tool link
    spacespan.text((toolspan.text() && sourcespan.text()) ? ' - ' : '');
};

// note that now this function is only adding the brand in
// iframes and 3rd-party apps
function positionPlayWithData(gd, container) {
    container.text('');
    var link = container.append('a')
        .attr({
            'xlink:xlink:href': '#',
            'class': 'link--impt link--embedview',
            'font-weight': 'bold'
        })
        .text(gd._context.linkText + ' ' + String.fromCharCode(187));

    if(gd._context.sendData) {
        link.on('click', function() {
            plots.sendDataToCloud(gd);
        });
    }
    else {
        var path = window.location.pathname.split('/');
        var query = window.location.search;
        link.attr({
            'xlink:xlink:show': 'new',
            'xlink:xlink:href': '/' + path[2].split('.')[0] + '/' + path[1] + query
        });
    }
}

plots.sendDataToCloud = function(gd) {
    gd.emit('plotly_beforeexport');

    var baseUrl = (window.PLOTLYENV || {}).BASE_URL || gd._context.plotlyServerURL;

    var hiddenformDiv = d3.select(gd)
        .append('div')
        .attr('id', 'hiddenform')
        .style('display', 'none');

    var hiddenform = hiddenformDiv
        .append('form')
        .attr({
            action: baseUrl + '/external',
            method: 'post',
            target: '_blank'
        });

    var hiddenformInput = hiddenform
        .append('input')
        .attr({
            type: 'text',
            name: 'data'
        });

    hiddenformInput.node().value = plots.graphJson(gd, false, 'keepdata');
    hiddenform.node().submit();
    hiddenformDiv.remove();

    gd.emit('plotly_afterexport');
    return false;
};

var d3FormatKeys = [
    'days', 'shortDays', 'months', 'shortMonths', 'periods',
    'dateTime', 'date', 'time',
    'decimal', 'thousands', 'grouping', 'currency'
];

var extraFormatKeys = [
    'year', 'month', 'dayMonth', 'dayMonthYear'
];

/*
 * Fill in default values
 * @param {DOM element} gd
 * @param {object} opts
 * @param {boolean} opts.skipUpdateCalc: normally if the existing gd.calcdata looks
 *   compatible with the new gd._fullData we finish by linking the new _fullData traces
 *   to the old gd.calcdata, so it's correctly set if we're not going to recalc. But also,
 *   if there are calcTransforms on the trace, we first remap data arrays from the old full
 *   trace into the new one. Use skipUpdateCalc to defer this (needed by Plotly.react)
 *
 * gd.data, gd.layout:
 *   are precisely what the user specified (except as modified by cleanData/cleanLayout),
 *   these fields shouldn't be modified (except for filling in some auto values)
 *   nor used directly after the supply defaults step.
 *
 * gd._fullData, gd._fullLayout:
 *   are complete descriptions of how to draw the plot,
 *   use these fields in all required computations.
 *
 * gd._fullLayout._modules
 *   is a list of all the trace modules required to draw the plot.
 *
 * gd._fullLayout._visibleModules
 *   subset of _modules, a list of modules corresponding to visible:true traces.
 *
 * gd._fullLayout._basePlotModules
 *   is a list of all the plot modules required to draw the plot.
 *
 * gd._fullLayout._transformModules
 *   is a list of all the transform modules invoked.
 *
 */
plots.supplyDefaults = function(gd, opts) {
    var skipUpdateCalc = opts && opts.skipUpdateCalc;
    var oldFullLayout = gd._fullLayout || {};

    if(oldFullLayout._skipDefaults) {
        delete oldFullLayout._skipDefaults;
        return;
    }

    var newFullLayout = gd._fullLayout = {};
    var newLayout = gd.layout || {};

    var oldFullData = gd._fullData || [];
    var newFullData = gd._fullData = [];
    var newData = gd.data || [];

    var oldCalcdata = gd.calcdata || [];

    var context = gd._context || {};

    var i;

    // Create all the storage space for frames, but only if doesn't already exist
    if(!gd._transitionData) plots.createTransitionData(gd);

    // So we only need to do this once (and since we have gd here)
    // get the translated placeholder titles.
    // These ones get used as default values so need to be known at supplyDefaults
    // others keep their blank defaults but render the placeholder as desired later
    // TODO: make these work the same way, only inserting the placeholder text at draw time?
    // The challenge is that this has slightly different behavior right now in editable mode:
    // using the placeholder as default makes this text permanently (but lightly) visible,
    // but explicit '' for these titles gives you a placeholder that's hidden until you mouse
    // over it - so you're not distracted by it if you really don't want a title, but if you do
    // and you're new to plotly you may not be able to find it.
    // When editable=false the two behave the same, no title is drawn.
    newFullLayout._dfltTitle = {
        plot: _(gd, 'Click to enter Plot title'),
        x: _(gd, 'Click to enter X axis title'),
        y: _(gd, 'Click to enter Y axis title'),
        colorbar: _(gd, 'Click to enter Colorscale title'),
        annotation: _(gd, 'new text')
    };
    newFullLayout._traceWord = _(gd, 'trace');

    var formatObj = getFormatObj(gd, d3FormatKeys);

    // stash the token from context so mapbox subplots can use it as default
    newFullLayout._mapboxAccessToken = context.mapboxAccessToken;

    // first fill in what we can of layout without looking at data
    // because fullData needs a few things from layout
    if(oldFullLayout._initialAutoSizeIsDone) {

        // coerce the updated layout while preserving width and height
        var oldWidth = oldFullLayout.width;
        var oldHeight = oldFullLayout.height;

        plots.supplyLayoutGlobalDefaults(newLayout, newFullLayout, formatObj);

        if(!newLayout.width) newFullLayout.width = oldWidth;
        if(!newLayout.height) newFullLayout.height = oldHeight;
        plots.sanitizeMargins(newFullLayout);
    }
    else {

        // coerce the updated layout and autosize if needed
        plots.supplyLayoutGlobalDefaults(newLayout, newFullLayout, formatObj);

        var missingWidthOrHeight = (!newLayout.width || !newLayout.height);
        var autosize = newFullLayout.autosize;
        var autosizable = context.autosizable;
        var initialAutoSize = missingWidthOrHeight && (autosize || autosizable);

        if(initialAutoSize) plots.plotAutoSize(gd, newLayout, newFullLayout);
        else if(missingWidthOrHeight) plots.sanitizeMargins(newFullLayout);

        // for backwards-compatibility with Plotly v1.x.x
        if(!autosize && missingWidthOrHeight) {
            newLayout.width = newFullLayout.width;
            newLayout.height = newFullLayout.height;
        }
    }

    newFullLayout._d3locale = getFormatter(formatObj, newFullLayout.separators);
    newFullLayout._extraFormat = getFormatObj(gd, extraFormatKeys);

    newFullLayout._initialAutoSizeIsDone = true;

    // keep track of how many traces are inputted
    newFullLayout._dataLength = newData.length;

    // clear the lists of trace and baseplot modules, and subplots
    newFullLayout._modules = [];
    newFullLayout._visibleModules = [];
    newFullLayout._basePlotModules = [];
    var subplots = newFullLayout._subplots = emptySubplotLists();

    // initialize axis and subplot hash objects for splom-generated grids
    var splomAxes = newFullLayout._splomAxes = {x: {}, y: {}};
    var splomSubplots = newFullLayout._splomSubplots = {};
    // initialize splom grid defaults
    newFullLayout._splomGridDflt = {};

    // for stacked area traces to share config across traces
    newFullLayout._scatterStackOpts = {};
    // for the first scatter trace on each subplot (so it knows tonext->tozero)
    newFullLayout._firstScatter = {};

    // for traces to request a default rangeslider on their x axes
    // eg set `_requestRangeslider.x2 = true` for xaxis2
    newFullLayout._requestRangeslider = {};

    // pull uids from old data to use as new defaults
    newFullLayout._traceUids = getTraceUids(oldFullData, newData);

    // then do the data
    newFullLayout._globalTransforms = (gd._context || {}).globalTransforms;
    plots.supplyDataDefaults(newData, newFullData, newLayout, newFullLayout);

    // redo grid size defaults with info about splom x/y axes,
    // and fill in generated cartesian axes and subplots
    var splomXa = Object.keys(splomAxes.x);
    var splomYa = Object.keys(splomAxes.y);
    if(splomXa.length > 1 && splomYa.length > 1) {
        Registry.getComponentMethod('grid', 'sizeDefaults')(newLayout, newFullLayout);

        for(i = 0; i < splomXa.length; i++) {
            Lib.pushUnique(subplots.xaxis, splomXa[i]);
        }
        for(i = 0; i < splomYa.length; i++) {
            Lib.pushUnique(subplots.yaxis, splomYa[i]);
        }
        for(var k in splomSubplots) {
            Lib.pushUnique(subplots.cartesian, k);
        }
    }

    // attach helper method to check whether a plot type is present on graph
    newFullLayout._has = plots._hasPlotType.bind(newFullLayout);

    if(oldFullData.length === newFullData.length) {
        for(i = 0; i < newFullData.length; i++) {
            relinkPrivateKeys(newFullData[i], oldFullData[i]);
        }
    }

    // finally, fill in the pieces of layout that may need to look at data
    plots.supplyLayoutModuleDefaults(newLayout, newFullLayout, newFullData, gd._transitionData);

    // Special cases that introduce interactions between traces.
    // This is after relinkPrivateKeys so we can use those in crossTraceDefaults
    // and after layout module defaults, so we can use eg barmode
    var _modules = newFullLayout._visibleModules;
    var crossTraceDefaultsFuncs = [];
    for(i = 0; i < _modules.length; i++) {
        var funci = _modules[i].crossTraceDefaults;
        // some trace types share crossTraceDefaults (ie histogram2d, histogram2dcontour)
        if(funci) Lib.pushUnique(crossTraceDefaultsFuncs, funci);
    }
    for(i = 0; i < crossTraceDefaultsFuncs.length; i++) {
        crossTraceDefaultsFuncs[i](newFullData, newFullLayout);
    }
    Registry.getComponentMethod('colorscale', 'crossTraceDefaults')(newFullData, newFullLayout);

    // turn on flag to optimize large splom-only graphs
    // mostly by omitting SVG layers during Cartesian.drawFramework
    newFullLayout._hasOnlyLargeSploms = (
        newFullLayout._basePlotModules.length === 1 &&
        newFullLayout._basePlotModules[0].name === 'splom' &&
        splomXa.length > 15 &&
        splomYa.length > 15 &&
        newFullLayout.shapes.length === 0 &&
        newFullLayout.images.length === 0
    );

    // TODO remove in v2.0.0
    // add has-plot-type refs to fullLayout for backward compatibility
    newFullLayout._hasCartesian = newFullLayout._has('cartesian');
    newFullLayout._hasGeo = newFullLayout._has('geo');
    newFullLayout._hasGL3D = newFullLayout._has('gl3d');
    newFullLayout._hasGL2D = newFullLayout._has('gl2d');
    newFullLayout._hasTernary = newFullLayout._has('ternary');
    newFullLayout._hasPie = newFullLayout._has('pie');

    // relink / initialize subplot axis objects
    plots.linkSubplots(newFullData, newFullLayout, oldFullData, oldFullLayout);

    // clean subplots and other artifacts from previous plot calls
    plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout);

    // relink functions and _ attributes to promote consistency between plots
    relinkPrivateKeys(newFullLayout, oldFullLayout);

    // For persisting GUI-driven changes in layout
    // _preGUI and _tracePreGUI were already copied over in relinkPrivateKeys
    if(!newFullLayout._preGUI) newFullLayout._preGUI = {};
    // track trace GUI changes by uid rather than by trace index
    if(!newFullLayout._tracePreGUI) newFullLayout._tracePreGUI = {};
    var tracePreGUI = newFullLayout._tracePreGUI;
    var uids = {};
    var uid;
    for(uid in tracePreGUI) uids[uid] = 'old';
    for(i = 0; i < newFullData.length; i++) {
        uid = newFullData[i]._fullInput.uid;
        if(!uids[uid]) tracePreGUI[uid] = {};
        uids[uid] = 'new';
    }
    for(uid in uids) {
        if(uids[uid] === 'old') delete tracePreGUI[uid];
    }

    // set up containers for margin calculations
    initMargins(newFullLayout);

    // collect and do some initial calculations for rangesliders
    Registry.getComponentMethod('rangeslider', 'makeData')(newFullLayout);

    // update object references in calcdata
    if(!skipUpdateCalc && oldCalcdata.length === newFullData.length) {
        plots.supplyDefaultsUpdateCalc(oldCalcdata, newFullData);
    }
};

plots.supplyDefaultsUpdateCalc = function(oldCalcdata, newFullData) {
    for(var i = 0; i < newFullData.length; i++) {
        var newTrace = newFullData[i];
        var cd0 = (oldCalcdata[i] || [])[0];
        if(cd0 && cd0.trace) {
            var oldTrace = cd0.trace;
            if(oldTrace._hasCalcTransform) {
                var arrayAttrs = oldTrace._arrayAttrs;
                var j, astr, oldArrayVal;

                for(j = 0; j < arrayAttrs.length; j++) {
                    astr = arrayAttrs[j];
                    oldArrayVal = Lib.nestedProperty(oldTrace, astr).get().slice();
                    Lib.nestedProperty(newTrace, astr).set(oldArrayVal);
                }
            }
            cd0.trace = newTrace;
        }
    }
};

/**
 * Create a list of uid strings satisfying (in this order of importance):
 * 1. all unique, all strings
 * 2. matches input uids if provided
 * 3. matches previous data uids
 */
function getTraceUids(oldFullData, newData) {
    var len = newData.length;
    var oldFullInput = [];
    var i, prevFullInput;
    for(i = 0; i < oldFullData.length; i++) {
        var thisFullInput = oldFullData[i]._fullInput;
        if(thisFullInput !== prevFullInput) oldFullInput.push(thisFullInput);
        prevFullInput = thisFullInput;
    }
    var oldLen = oldFullInput.length;
    var out = new Array(len);
    var seenUids = {};

    function setUid(uid, i) {
        out[i] = uid;
        seenUids[uid] = 1;
    }

    function tryUid(uid, i) {
        if(uid && typeof uid === 'string' && !seenUids[uid]) {
            setUid(uid, i);
            return true;
        }
    }

    for(i = 0; i < len; i++) {
        var newUid = newData[i].uid;
        if(typeof newUid === 'number') newUid = String(newUid);

        if(tryUid(newUid, i)) continue;
        if(i < oldLen && tryUid(oldFullInput[i].uid, i)) continue;
        setUid(Lib.randstr(seenUids), i);
    }

    return out;
}

/**
 * Make a container for collecting subplots we need to display.
 *
 * Finds all subplot types we need to enumerate once and caches it,
 * but makes a new output object each time.
 * Single-trace subplots (which have no `id`) such as pie, table, etc
 * do not need to be collected because we just draw all visible traces.
 */
function emptySubplotLists() {
    var collectableSubplotTypes = Registry.collectableSubplotTypes;
    var out = {};
    var i, j;

    if(!collectableSubplotTypes) {
        collectableSubplotTypes = [];

        var subplotsRegistry = Registry.subplotsRegistry;

        for(var subplotType in subplotsRegistry) {
            var subplotModule = subplotsRegistry[subplotType];
            var subplotAttr = subplotModule.attr;

            if(subplotAttr) {
                collectableSubplotTypes.push(subplotType);

                // special case, currently just for cartesian:
                // we need to enumerate axes, not just subplots
                if(Array.isArray(subplotAttr)) {
                    for(j = 0; j < subplotAttr.length; j++) {
                        Lib.pushUnique(collectableSubplotTypes, subplotAttr[j]);
                    }
                }
            }
        }
    }

    for(i = 0; i < collectableSubplotTypes.length; i++) {
        out[collectableSubplotTypes[i]] = [];
    }
    return out;
}

/**
 * getFormatObj: use _context to get the format object from locale.
 * Used to get d3.locale argument object and extraFormat argument object
 *
 * Regarding d3.locale argument :
 * decimal and thousands can be overridden later by layout.separators
 * grouping and currency are not presently used by our automatic number
 * formatting system but can be used by custom formats.
 *
 * @returns {object} d3.locale format object
 */
function getFormatObj(gd, formatKeys) {
    var locale = gd._context.locale;
    if(!locale) locale === 'en-US';

    var formatDone = false;
    var formatObj = {};

    function includeFormat(newFormat) {
        var formatFinished = true;
        for(var i = 0; i < formatKeys.length; i++) {
            var formatKey = formatKeys[i];
            if(!formatObj[formatKey]) {
                if(newFormat[formatKey]) {
                    formatObj[formatKey] = newFormat[formatKey];
                }
                else formatFinished = false;
            }
        }
        if(formatFinished) formatDone = true;
    }

    // same as localize, look for format parts in each format spec in the chain
    for(var i = 0; i < 2; i++) {
        var locales = gd._context.locales;
        for(var j = 0; j < 2; j++) {
            var formatj = (locales[locale] || {}).format;
            if(formatj) {
                includeFormat(formatj);
                if(formatDone) break;
            }
            locales = Registry.localeRegistry;
        }

        var baseLocale = locale.split('-')[0];
        if(formatDone || baseLocale === locale) break;
        locale = baseLocale;
    }

    // lastly pick out defaults from english (non-US, as DMY is so much more common)
    if(!formatDone) includeFormat(Registry.localeRegistry.en.format);

    return formatObj;
}

/**
 * getFormatter: combine the final separators with the locale formatting object
 * we pulled earlier to generate number and time formatters
 * TODO: remove separators in v2, only use locale, so we don't need this step?
 *
 * @param {object} formatObj: d3.locale format object
 * @param {string} separators: length-2 string to override decimal and thousands
 *   separators in number formatting
 *
 * @returns {object} {numberFormat, timeFormat} d3 formatter factory functions
 *   for numbers and time
 */
function getFormatter(formatObj, separators) {
    formatObj.decimal = separators.charAt(0);
    formatObj.thousands = separators.charAt(1);

    return d3.locale(formatObj);
}

// Create storage for all of the data related to frames and transitions:
plots.createTransitionData = function(gd) {
    // Set up the default keyframe if it doesn't exist:
    if(!gd._transitionData) {
        gd._transitionData = {};
    }

    if(!gd._transitionData._frames) {
        gd._transitionData._frames = [];
    }

    if(!gd._transitionData._frameHash) {
        gd._transitionData._frameHash = {};
    }

    if(!gd._transitionData._counter) {
        gd._transitionData._counter = 0;
    }

    if(!gd._transitionData._interruptCallbacks) {
        gd._transitionData._interruptCallbacks = [];
    }
};

// helper function to be bound to fullLayout to check
// whether a certain plot type is present on plot
// or trace has a category
plots._hasPlotType = function(category) {
    var i;

    // check base plot modules
    var basePlotModules = this._basePlotModules || [];
    for(i = 0; i < basePlotModules.length; i++) {
        if(basePlotModules[i].name === category) return true;
    }

    // check trace modules (including non-visible:true)
    var modules = this._modules || [];
    for(i = 0; i < modules.length; i++) {
        var name = modules[i].name;
        if(name === category) return true;
        // N.B. this is modules[i] along with 'categories' as a hash object
        var _module = Registry.modules[name];
        if(_module && _module.categories[category]) return true;
    }

    return false;
};

plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var i, j;

    var basePlotModules = oldFullLayout._basePlotModules || [];
    for(i = 0; i < basePlotModules.length; i++) {
        var _module = basePlotModules[i];

        if(_module.clean) {
            _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout);
        }
    }

    var hadGl = oldFullLayout._has && oldFullLayout._has('gl');
    var hasGl = newFullLayout._has && newFullLayout._has('gl');

    if(hadGl && !hasGl) {
        if(oldFullLayout._glcontainer !== undefined) {
            oldFullLayout._glcontainer.selectAll('.gl-canvas').remove();
            oldFullLayout._glcontainer.selectAll('.no-webgl').remove();
            oldFullLayout._glcanvas = null;
        }
    }

    var hasInfoLayer = !!oldFullLayout._infolayer;

    oldLoop:
    for(i = 0; i < oldFullData.length; i++) {
        var oldTrace = oldFullData[i];
        var oldUid = oldTrace.uid;

        for(j = 0; j < newFullData.length; j++) {
            var newTrace = newFullData[j];

            if(oldUid === newTrace.uid) continue oldLoop;
        }

        // clean old colorbars
        if(hasInfoLayer) {
            oldFullLayout._infolayer.select('.cb' + oldUid).remove();
        }
    }

    if(oldFullLayout._zoomlayer) {
        oldFullLayout._zoomlayer.selectAll('.select-outline').remove();
    }
};

plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var i, j;

    var oldSubplots = oldFullLayout._plots || {};
    var newSubplots = newFullLayout._plots = {};
    var newSubplotList = newFullLayout._subplots;

    var mockGd = {
        _fullData: newFullData,
        _fullLayout: newFullLayout
    };

    var ids = newSubplotList.cartesian.concat(newSubplotList.gl2d || []);

    for(i = 0; i < ids.length; i++) {
        var id = ids[i];
        var oldSubplot = oldSubplots[id];
        var xaxis = axisIDs.getFromId(mockGd, id, 'x');
        var yaxis = axisIDs.getFromId(mockGd, id, 'y');
        var plotinfo;

        // link or create subplot object
        if(oldSubplot) {
            plotinfo = newSubplots[id] = oldSubplot;
        } else {
            plotinfo = newSubplots[id] = {};
            plotinfo.id = id;
        }

        // add these axis ids to each others' subplot lists
        xaxis._counterAxes.push(yaxis._id);
        yaxis._counterAxes.push(xaxis._id);
        xaxis._subplotsWith.push(id);
        yaxis._subplotsWith.push(id);

        // update x and y axis layout object refs
        plotinfo.xaxis = xaxis;
        plotinfo.yaxis = yaxis;

        // By default, we clip at the subplot level,
        // but if one trace on a given subplot has *cliponaxis* set to false,
        // we need to clip at the trace module layer level;
        // find this out here, once of for all.
        plotinfo._hasClipOnAxisFalse = false;

        for(j = 0; j < newFullData.length; j++) {
            var trace = newFullData[j];

            if(
                trace.xaxis === plotinfo.xaxis._id &&
                trace.yaxis === plotinfo.yaxis._id &&
                trace.cliponaxis === false
            ) {
                plotinfo._hasClipOnAxisFalse = true;
                break;
            }
        }
    }

    // while we're at it, link overlaying axes to their main axes and
    // anchored axes to the axes they're anchored to
    var axList = axisIDs.list(mockGd, null, true);
    var ax;
    for(i = 0; i < axList.length; i++) {
        ax = axList[i];
        var mainAx = null;

        if(ax.overlaying) {
            mainAx = axisIDs.getFromId(mockGd, ax.overlaying);

            // you cannot overlay an axis that's already overlaying another
            if(mainAx && mainAx.overlaying) {
                ax.overlaying = false;
                mainAx = null;
            }
        }
        ax._mainAxis = mainAx || ax;

        /*
         * For now force overlays to overlay completely... so they
         * can drag together correctly and share backgrounds.
         * Later perhaps we make separate axis domain and
         * tick/line domain or something, so they can still share
         * the (possibly larger) dragger and background but don't
         * have to both be drawn over that whole domain
         */
        if(mainAx) ax.domain = mainAx.domain.slice();

        ax._anchorAxis = ax.anchor === 'free' ?
            null :
            axisIDs.getFromId(mockGd, ax.anchor);
    }

    // finally, we can find the main subplot for each axis
    // (on which the ticks & labels are drawn)
    for(i = 0; i < axList.length; i++) {
        ax = axList[i];
        ax._counterAxes.sort(axisIDs.idSort);
        ax._subplotsWith.sort(Lib.subplotSort);
        ax._mainSubplot = findMainSubplot(ax, newFullLayout);
    }
};

function findMainSubplot(ax, fullLayout) {
    var mockGd = {_fullLayout: fullLayout};

    var isX = ax._id.charAt(0) === 'x';
    var anchorAx = ax._mainAxis._anchorAxis;
    var mainSubplotID = '';
    var nextBestMainSubplotID = '';
    var anchorID = '';

    // First try the main ID with the anchor
    if(anchorAx) {
        anchorID = anchorAx._mainAxis._id;
        mainSubplotID = isX ? (ax._id + anchorID) : (anchorID + ax._id);
    }

    // Then look for a subplot with the counteraxis overlaying the anchor
    // If that fails just use the first subplot including this axis
    if(!mainSubplotID || !fullLayout._plots[mainSubplotID]) {
        mainSubplotID = '';

        var counterIDs = ax._counterAxes;
        for(var j = 0; j < counterIDs.length; j++) {
            var counterPart = counterIDs[j];
            var id = isX ? (ax._id + counterPart) : (counterPart + ax._id);
            if(!nextBestMainSubplotID) nextBestMainSubplotID = id;
            var counterAx = axisIDs.getFromId(mockGd, counterPart);
            if(anchorID && counterAx.overlaying === anchorID) {
                mainSubplotID = id;
                break;
            }
        }
    }

    return mainSubplotID || nextBestMainSubplotID;
}

// This function clears any trace attributes with valType: color and
// no set dflt filed in the plot schema. This is needed because groupby (which
// is the only transform for which this currently applies) supplies parent
// trace defaults, then expanded trace defaults. The result is that `null`
// colors are default-supplied and inherited as a color instead of a null.
// The result is that expanded trace default colors have no effect, with
// the final result that groups are indistinguishable. This function clears
// those colors so that individual groupby groups get unique colors.
plots.clearExpandedTraceDefaultColors = function(trace) {
    var colorAttrs, path, i;

    // This uses weird closure state in order to satisfy the linter rule
    // that we can't create functions in a loop.
    function locateColorAttrs(attr, attrName, attrs, level) {
        path[level] = attrName;
        path.length = level + 1;
        if(attr.valType === 'color' && attr.dflt === undefined) {
            colorAttrs.push(path.join('.'));
        }
    }

    path = [];

    // Get the cached colorAttrs:
    colorAttrs = trace._module._colorAttrs;

    // Or else compute and cache the colorAttrs on the module:
    if(!colorAttrs) {
        trace._module._colorAttrs = colorAttrs = [];
        PlotSchema.crawl(
            trace._module.attributes,
            locateColorAttrs
        );
    }

    for(i = 0; i < colorAttrs.length; i++) {
        var origprop = Lib.nestedProperty(trace, '_input.' + colorAttrs[i]);

        if(!origprop.get()) {
            Lib.nestedProperty(trace, colorAttrs[i]).set(null);
        }
    }
};


plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) {
    var modules = fullLayout._modules;
    var visibleModules = fullLayout._visibleModules;
    var basePlotModules = fullLayout._basePlotModules;
    var cnt = 0;
    var colorCnt = 0;

    var i, fullTrace, trace;

    fullLayout._transformModules = [];

    function pushModule(fullTrace) {
        dataOut.push(fullTrace);

        var _module = fullTrace._module;
        if(!_module) return;

        Lib.pushUnique(modules, _module);
        if(fullTrace.visible === true) Lib.pushUnique(visibleModules, _module);
        Lib.pushUnique(basePlotModules, fullTrace._module.basePlotModule);
        cnt++;

        // TODO: do we really want color not to increment for explicitly invisible traces?
        // This logic is weird, but matches previous behavior: traces that you explicitly
        // set to visible:false do not increment the color, but traces WE determine to be
        // empty or invalid (and thus set to visible:false) DO increment color.
        // I kind of think we should just let all traces increment color, visible or not.
        // see mock: axes-autotype-empty vs. a test of restyling visible: false that
        // I can't find right now...
        if(fullTrace._input.visible !== false) colorCnt++;
    }

    var carpetIndex = {};
    var carpetDependents = [];
    var dataTemplate = (layout.template || {}).data || {};
    var templater = Template.traceTemplater(dataTemplate);

    for(i = 0; i < dataIn.length; i++) {
        trace = dataIn[i];

        // reuse uid we may have pulled out of oldFullData
        // Note: templater supplies trace type
        fullTrace = templater.newTrace(trace);
        fullTrace.uid = fullLayout._traceUids[i];
        plots.supplyTraceDefaults(trace, fullTrace, colorCnt, fullLayout, i);

        fullTrace.index = i;
        fullTrace._input = trace;
        fullTrace._expandedIndex = cnt;

        if(fullTrace.transforms && fullTrace.transforms.length) {
            var sdInvisible = trace.visible !== false && fullTrace.visible === false;

            var expandedTraces = applyTransforms(fullTrace, dataOut, layout, fullLayout);

            for(var j = 0; j < expandedTraces.length; j++) {
                var expandedTrace = expandedTraces[j];

                // No further templating during transforms.
                var fullExpandedTrace = {
                    _template: fullTrace._template,
                    type: fullTrace.type,
                    // set uid using parent uid and expanded index
                    // to promote consistency between update calls
                    uid: fullTrace.uid + j
                };

                // If the first supplyDefaults created `visible: false`,
                // clear it before running supplyDefaults a second time,
                // because sometimes there are items we still want to coerce
                // inside trace modules before determining that the trace is
                // again `visible: false`, for example partial visibilities
                // in `splom` traces.
                if(sdInvisible && expandedTrace.visible === false) {
                    delete expandedTrace.visible;
                }

                plots.supplyTraceDefaults(expandedTrace, fullExpandedTrace, cnt, fullLayout, i);

                // relink private (i.e. underscore) keys expanded trace to full expanded trace so
                // that transform supply-default methods can set _ keys for future use.
                relinkPrivateKeys(fullExpandedTrace, expandedTrace);

                // add info about parent data trace
                fullExpandedTrace.index = i;
                fullExpandedTrace._input = trace;
                fullExpandedTrace._fullInput = fullTrace;

                // add info about the expanded data
                fullExpandedTrace._expandedIndex = cnt;
                fullExpandedTrace._expandedInput = expandedTrace;

                pushModule(fullExpandedTrace);
            }
        }
        else {
            // add identify refs for consistency with transformed traces
            fullTrace._fullInput = fullTrace;
            fullTrace._expandedInput = fullTrace;

            pushModule(fullTrace);
        }

        if(Registry.traceIs(fullTrace, 'carpetAxis')) {
            carpetIndex[fullTrace.carpet] = fullTrace;
        }

        if(Registry.traceIs(fullTrace, 'carpetDependent')) {
            carpetDependents.push(i);
        }
    }

    for(i = 0; i < carpetDependents.length; i++) {
        fullTrace = dataOut[carpetDependents[i]];

        if(!fullTrace.visible) continue;

        var carpetAxis = carpetIndex[fullTrace.carpet];
        fullTrace._carpet = carpetAxis;

        if(!carpetAxis || !carpetAxis.visible) {
            fullTrace.visible = false;
            continue;
        }

        fullTrace.xaxis = carpetAxis.xaxis;
        fullTrace.yaxis = carpetAxis.yaxis;
    }
};

plots.supplyAnimationDefaults = function(opts) {
    opts = opts || {};
    var i;
    var optsOut = {};

    function coerce(attr, dflt) {
        return Lib.coerce(opts || {}, optsOut, animationAttrs, attr, dflt);
    }

    coerce('mode');
    coerce('direction');
    coerce('fromcurrent');

    if(Array.isArray(opts.frame)) {
        optsOut.frame = [];
        for(i = 0; i < opts.frame.length; i++) {
            optsOut.frame[i] = plots.supplyAnimationFrameDefaults(opts.frame[i] || {});
        }
    } else {
        optsOut.frame = plots.supplyAnimationFrameDefaults(opts.frame || {});
    }

    if(Array.isArray(opts.transition)) {
        optsOut.transition = [];
        for(i = 0; i < opts.transition.length; i++) {
            optsOut.transition[i] = plots.supplyAnimationTransitionDefaults(opts.transition[i] || {});
        }
    } else {
        optsOut.transition = plots.supplyAnimationTransitionDefaults(opts.transition || {});
    }

    return optsOut;
};

plots.supplyAnimationFrameDefaults = function(opts) {
    var optsOut = {};

    function coerce(attr, dflt) {
        return Lib.coerce(opts || {}, optsOut, animationAttrs.frame, attr, dflt);
    }

    coerce('duration');
    coerce('redraw');

    return optsOut;
};

plots.supplyAnimationTransitionDefaults = function(opts) {
    var optsOut = {};

    function coerce(attr, dflt) {
        return Lib.coerce(opts || {}, optsOut, animationAttrs.transition, attr, dflt);
    }

    coerce('duration');
    coerce('easing');

    return optsOut;
};

plots.supplyFrameDefaults = function(frameIn) {
    var frameOut = {};

    function coerce(attr, dflt) {
        return Lib.coerce(frameIn, frameOut, frameAttrs, attr, dflt);
    }

    coerce('group');
    coerce('name');
    coerce('traces');
    coerce('baseframe');
    coerce('data');
    coerce('layout');

    return frameOut;
};

plots.supplyTraceDefaults = function(traceIn, traceOut, colorIndex, layout, traceInIndex) {
    var colorway = layout.colorway || Color.defaults;
    var defaultColor = colorway[colorIndex % colorway.length];

    var i;

    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, plots.attributes, attr, dflt);
    }

    var visible = coerce('visible');

    coerce('type');
    coerce('name', layout._traceWord + ' ' + traceInIndex);

    coerce('uirevision', layout.uirevision);

    // we want even invisible traces to make their would-be subplots visible
    // so coerce the subplot id(s) now no matter what
    var _module = plots.getModule(traceOut);

    traceOut._module = _module;
    if(_module) {
        var basePlotModule = _module.basePlotModule;
        var subplotAttr = basePlotModule.attr;
        var subplotAttrs = basePlotModule.attributes;
        if(subplotAttr && subplotAttrs) {
            var subplots = layout._subplots;
            var subplotId = '';

            // TODO - currently if we draw an empty gl2d subplot, it draws
            // nothing then gets stuck and you can't get it back without newPlot
            // sort this out in the regl refactor? but for now just drop empty gl2d subplots
            if(basePlotModule.name !== 'gl2d' || visible) {
                if(Array.isArray(subplotAttr)) {
                    for(i = 0; i < subplotAttr.length; i++) {
                        var attri = subplotAttr[i];
                        var vali = Lib.coerce(traceIn, traceOut, subplotAttrs, attri);

                        if(subplots[attri]) Lib.pushUnique(subplots[attri], vali);
                        subplotId += vali;
                    }
                }
                else {
                    subplotId = Lib.coerce(traceIn, traceOut, subplotAttrs, subplotAttr);
                }

                if(subplots[basePlotModule.name]) {
                    Lib.pushUnique(subplots[basePlotModule.name], subplotId);
                }
            }
        }
    }

    function coerceUnlessPruned(attr, dflt, cb) {
        if(_module && (attr in _module.attributes) && _module.attributes[attr] === undefined) {
            // Pruned
        } else {
            if(cb && typeof cb === 'function') {
                cb();
            } else {
                coerce(attr, dflt);
            }
        }
    }

    if(visible) {
        coerce('customdata');
        coerce('ids');

        if(Registry.traceIs(traceOut, 'showLegend')) {
            traceOut._dfltShowLegend = true;
            coerce('showlegend');
            coerce('legendgroup');
        }
        else {
            traceOut._dfltShowLegend = false;
        }

        coerceUnlessPruned('hoverlabel', '', function() {
            Registry.getComponentMethod(
                'fx',
                'supplyDefaults'
            )(traceIn, traceOut, defaultColor, layout);
        });

        // TODO add per-base-plot-module trace defaults step

        if(_module) {
            _module.supplyDefaults(traceIn, traceOut, defaultColor, layout);
            if(!traceOut.hovertemplate) Lib.coerceHoverinfo(traceIn, traceOut, layout);
        }

        if(!Registry.traceIs(traceOut, 'noOpacity')) coerce('opacity');

        if(Registry.traceIs(traceOut, 'notLegendIsolatable')) {
            // This clears out the legendonly state for traces like carpet that
            // cannot be isolated in the legend
            traceOut.visible = !!traceOut.visible;
        }

        if(_module && _module.selectPoints) {
            coerce('selectedpoints');
        }

        plots.supplyTransformDefaults(traceIn, traceOut, layout);
    }

    return traceOut;
};

/**
 * hasMakesDataTransform: does this trace have a transform that makes its own
 * data, either by grabbing it from somewhere else or by creating it from input
 * parameters? If so, we should still keep going with supplyDefaults
 * even if the trace is invisible, which may just be because it has no data yet.
 */
function hasMakesDataTransform(trace) {
    var transforms = trace.transforms;
    if(Array.isArray(transforms) && transforms.length) {
        for(var i = 0; i < transforms.length; i++) {
            var ti = transforms[i];
            var _module = ti._module || transformsRegistry[ti.type];
            if(_module && _module.makesData) return true;
        }
    }
    return false;
}

plots.hasMakesDataTransform = hasMakesDataTransform;

plots.supplyTransformDefaults = function(traceIn, traceOut, layout) {
    // For now we only allow transforms on 1D traces, ie those that specify a _length.
    // If we were to implement 2D transforms, we'd need to have each transform
    // describe its own applicability and disable itself when it doesn't apply.
    // Also allow transforms that make their own data, but not in globalTransforms
    if(!(traceOut._length || hasMakesDataTransform(traceIn))) return;

    var globalTransforms = layout._globalTransforms || [];
    var transformModules = layout._transformModules || [];

    if(!Array.isArray(traceIn.transforms) && globalTransforms.length === 0) return;

    var containerIn = traceIn.transforms || [];
    var transformList = globalTransforms.concat(containerIn);
    var containerOut = traceOut.transforms = [];

    for(var i = 0; i < transformList.length; i++) {
        var transformIn = transformList[i];
        var type = transformIn.type;
        var _module = transformsRegistry[type];
        var transformOut;

        /*
         * Supply defaults may run twice. First pass runs all supply defaults steps
         * and adds the _module to any output transforms.
         * If transforms exist another pass is run so that any generated traces also
         * go through supply defaults. This has the effect of rerunning
         * supplyTransformDefaults. If the transform does not have a `transform`
         * function it could not have generated any new traces and the second stage
         * is unnecessary. We detect this case with the following variables.
         */
        var isFirstStage = !(transformIn._module && transformIn._module === _module);
        var doLaterStages = _module && typeof _module.transform === 'function';

        if(!_module) Lib.warn('Unrecognized transform type ' + type + '.');

        if(_module && _module.supplyDefaults && (isFirstStage || doLaterStages)) {
            transformOut = _module.supplyDefaults(transformIn, traceOut, layout, traceIn);
            transformOut.type = type;
            transformOut._module = _module;

            Lib.pushUnique(transformModules, _module);
        }
        else {
            transformOut = Lib.extendFlat({}, transformIn);
        }

        containerOut.push(transformOut);
    }
};

function applyTransforms(fullTrace, fullData, layout, fullLayout) {
    var container = fullTrace.transforms;
    var dataOut = [fullTrace];

    for(var i = 0; i < container.length; i++) {
        var transform = container[i];
        var _module = transformsRegistry[transform.type];

        if(_module && _module.transform) {
            dataOut = _module.transform(dataOut, {
                transform: transform,
                fullTrace: fullTrace,
                fullData: fullData,
                layout: layout,
                fullLayout: fullLayout,
                transformIndex: i
            });
        }
    }

    return dataOut;
}

plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) {
    function coerce(attr, dflt) {
        return Lib.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt);
    }

    var template = layoutIn.template;
    if(Lib.isPlainObject(template)) {
        layoutOut.template = template;
        layoutOut._template = template.layout;
        layoutOut._dataTemplate = template.data;
    }

    var globalFont = Lib.coerceFont(coerce, 'font');

    coerce('title.text', layoutOut._dfltTitle.plot);

    Lib.coerceFont(coerce, 'title.font', {
        family: globalFont.family,
        size: Math.round(globalFont.size * 1.4),
        color: globalFont.color
    });

    coerce('title.xref');
    coerce('title.yref');
    coerce('title.x');
    coerce('title.y');
    coerce('title.xanchor');
    coerce('title.yanchor');
    coerce('title.pad.t');
    coerce('title.pad.r');
    coerce('title.pad.b');
    coerce('title.pad.l');

    // Make sure that autosize is defaulted to *true*
    // on layouts with no set width and height for backward compatibly,
    // in particular https://plot.ly/javascript/responsive-fluid-layout/
    //
    // Before https://github.com/plotly/plotly.js/pull/635 ,
    // layouts with no set width and height were set temporary set to 'initial'
    // to pass through the autosize routine
    //
    // This behavior is subject to change in v2.
    coerce('autosize', !(layoutIn.width && layoutIn.height));

    coerce('width');
    coerce('height');
    coerce('margin.l');
    coerce('margin.r');
    coerce('margin.t');
    coerce('margin.b');
    coerce('margin.pad');
    coerce('margin.autoexpand');

    if(layoutIn.width && layoutIn.height) plots.sanitizeMargins(layoutOut);

    Registry.getComponentMethod('grid', 'sizeDefaults')(layoutIn, layoutOut);

    coerce('paper_bgcolor');

    coerce('separators', formatObj.decimal + formatObj.thousands);
    coerce('hidesources');

    coerce('colorway');

    coerce('datarevision');
    var uirevision = coerce('uirevision');
    coerce('editrevision', uirevision);
    coerce('selectionrevision', uirevision);

    coerce('modebar.orientation');
    coerce('modebar.bgcolor', Color.addOpacity(layoutOut.paper_bgcolor, 0.5));
    var modebarDefaultColor = Color.contrast(Color.rgb(layoutOut.modebar.bgcolor));
    coerce('modebar.color', Color.addOpacity(modebarDefaultColor, 0.3));
    coerce('modebar.activecolor', Color.addOpacity(modebarDefaultColor, 0.7));
    coerce('modebar.uirevision', uirevision);

    coerce('meta');

    // do not include defaults in fullLayout when users do not set transition
    if(Lib.isPlainObject(layoutIn.transition)) {
        coerce('transition.duration');
        coerce('transition.easing');
        coerce('transition.ordering');
    }

    Registry.getComponentMethod(
        'calendars',
        'handleDefaults'
    )(layoutIn, layoutOut, 'calendar');

    Registry.getComponentMethod(
        'fx',
        'supplyLayoutGlobalDefaults'
    )(layoutIn, layoutOut, coerce);
};

plots.plotAutoSize = function plotAutoSize(gd, layout, fullLayout) {
    var context = gd._context || {};
    var frameMargins = context.frameMargins;
    var newWidth;
    var newHeight;

    var isPlotDiv = Lib.isPlotDiv(gd);

    if(isPlotDiv) gd.emit('plotly_autosize');

    // embedded in an iframe - just take the full iframe size
    // if we get to this point, with no aspect ratio restrictions
    if(context.fillFrame) {
        newWidth = window.innerWidth;
        newHeight = window.innerHeight;

        // somehow we get a few extra px height sometimes...
        // just hide it
        document.body.style.overflow = 'hidden';
    }
    else {
        // plotly.js - let the developers do what they want, either
        // provide height and width for the container div,
        // specify size in layout, or take the defaults,
        // but don't enforce any ratio restrictions
        var computedStyle = isPlotDiv ? window.getComputedStyle(gd) : {};

        newWidth = parseFloat(computedStyle.width) || parseFloat(computedStyle.maxWidth) || fullLayout.width;
        newHeight = parseFloat(computedStyle.height) || parseFloat(computedStyle.maxHeight) || fullLayout.height;

        if(isNumeric(frameMargins) && frameMargins > 0) {
            var factor = 1 - 2 * frameMargins;
            newWidth = Math.round(factor * newWidth);
            newHeight = Math.round(factor * newHeight);
        }
    }

    var minWidth = plots.layoutAttributes.width.min;
    var minHeight = plots.layoutAttributes.height.min;
    if(newWidth < minWidth) newWidth = minWidth;
    if(newHeight < minHeight) newHeight = minHeight;

    var widthHasChanged = !layout.width &&
        (Math.abs(fullLayout.width - newWidth) > 1);
    var heightHasChanged = !layout.height &&
        (Math.abs(fullLayout.height - newHeight) > 1);

    if(heightHasChanged || widthHasChanged) {
        if(widthHasChanged) fullLayout.width = newWidth;
        if(heightHasChanged) fullLayout.height = newHeight;
    }

    // cache initial autosize value, used in relayout when
    // width or height values are set to null
    if(!gd._initialAutoSize) {
        gd._initialAutoSize = { width: newWidth, height: newHeight };
    }

    plots.sanitizeMargins(fullLayout);
};

plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, transitionData) {
    var componentsRegistry = Registry.componentsRegistry;
    var basePlotModules = layoutOut._basePlotModules;
    var component, i, _module;

    var Cartesian = Registry.subplotsRegistry.cartesian;

    // check if any components need to add more base plot modules
    // that weren't captured by traces
    for(component in componentsRegistry) {
        _module = componentsRegistry[component];

        if(_module.includeBasePlot) {
            _module.includeBasePlot(layoutIn, layoutOut);
        }
    }

    // make sure we *at least* have some cartesian axes
    if(!basePlotModules.length) {
        basePlotModules.push(Cartesian);
    }

    // ensure all cartesian axes have at least one subplot
    if(layoutOut._has('cartesian')) {
        Registry.getComponentMethod('grid', 'contentDefaults')(layoutIn, layoutOut);
        Cartesian.finalizeSubplots(layoutIn, layoutOut);
    }

    // sort subplot lists
    for(var subplotType in layoutOut._subplots) {
        layoutOut._subplots[subplotType].sort(Lib.subplotSort);
    }

    // base plot module layout defaults
    for(i = 0; i < basePlotModules.length; i++) {
        _module = basePlotModules[i];

        // e.g. pie does not have a layout-defaults step
        if(_module.supplyLayoutDefaults) {
            _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
        }
    }

    // trace module layout defaults
    // use _modules rather than _visibleModules so that even
    // legendonly traces can include settings - eg barmode, which affects
    // legend.traceorder default value.
    var modules = layoutOut._modules;
    for(i = 0; i < modules.length; i++) {
        _module = modules[i];

        if(_module.supplyLayoutDefaults) {
            _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
        }
    }

    // transform module layout defaults
    var transformModules = layoutOut._transformModules;
    for(i = 0; i < transformModules.length; i++) {
        _module = transformModules[i];

        if(_module.supplyLayoutDefaults) {
            _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData, transitionData);
        }
    }

    for(component in componentsRegistry) {
        _module = componentsRegistry[component];

        if(_module.supplyLayoutDefaults) {
            _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
        }
    }
};

// Remove all plotly attributes from a div so it can be replotted fresh
// TODO: these really need to be encapsulated into a much smaller set...
plots.purge = function(gd) {
    // note: we DO NOT remove _context because it doesn't change when we insert
    // a new plot, and may have been set outside of our scope.

    var fullLayout = gd._fullLayout || {};
    if(fullLayout._glcontainer !== undefined) {
        fullLayout._glcontainer.selectAll('.gl-canvas').remove();
        fullLayout._glcontainer.remove();
        fullLayout._glcanvas = null;
    }
    if(fullLayout._geocontainer !== undefined) fullLayout._geocontainer.remove();

    // remove modebar
    if(fullLayout._modeBar) fullLayout._modeBar.destroy();

    if(gd._transitionData) {
        // Ensure any dangling callbacks are simply dropped if the plot is purged.
        // This is more or less only actually important for testing.
        if(gd._transitionData._interruptCallbacks) {
            gd._transitionData._interruptCallbacks.length = 0;
        }

        if(gd._transitionData._animationRaf) {
            window.cancelAnimationFrame(gd._transitionData._animationRaf);
        }
    }

    // remove any planned throttles
    Lib.clearThrottle();

    // remove responsive handler
    Lib.clearResponsive(gd);

    // data and layout
    delete gd.data;
    delete gd.layout;
    delete gd._fullData;
    delete gd._fullLayout;
    delete gd.calcdata;
    delete gd.framework;
    delete gd.empty;

    delete gd.fid;

    delete gd.undoqueue; // action queue
    delete gd.undonum;
    delete gd.autoplay; // are we doing an action that doesn't go in undo queue?
    delete gd.changed;

    // these get recreated on Plotly.plot anyway, but just to be safe
    // (and to have a record of them...)
    delete gd._promises;
    delete gd._redrawTimer;
    delete gd._hmlumcount;
    delete gd._hmpixcount;
    delete gd._transitionData;
    delete gd._transitioning;
    delete gd._initialAutoSize;
    delete gd._transitioningWithDuration;

    // created during certain events, that *should* clean them up
    // themselves, but may not if there was an error
    delete gd._dragging;
    delete gd._dragged;
    delete gd._hoverdata;
    delete gd._snapshotInProgress;
    delete gd._editing;
    delete gd._replotPending;
    delete gd._mouseDownTime;
    delete gd._legendMouseDownTime;

    // remove all event listeners
    if(gd.removeAllListeners) gd.removeAllListeners();
};

plots.style = function(gd) {
    var _modules = gd._fullLayout._visibleModules;
    var styleModules = [];
    var i;

    // some trace modules reuse the same style method,
    // make sure to not unnecessary call them multiple times.

    for(i = 0; i < _modules.length; i++) {
        var _module = _modules[i];
        if(_module.style) {
            Lib.pushUnique(styleModules, _module.style);
        }
    }

    for(i = 0; i < styleModules.length; i++) {
        styleModules[i](gd);
    }
};

plots.sanitizeMargins = function(fullLayout) {
    // polar doesn't do margins...
    if(!fullLayout || !fullLayout.margin) return;

    var width = fullLayout.width;
    var height = fullLayout.height;
    var margin = fullLayout.margin;
    var plotWidth = width - (margin.l + margin.r);
    var plotHeight = height - (margin.t + margin.b);
    var correction;

    // if margin.l + margin.r = 0 then plotWidth > 0
    // as width >= 10 by supplyDefaults
    // similarly for margin.t + margin.b

    if(plotWidth < 0) {
        correction = (width - 1) / (margin.l + margin.r);
        margin.l = Math.floor(correction * margin.l);
        margin.r = Math.floor(correction * margin.r);
    }

    if(plotHeight < 0) {
        correction = (height - 1) / (margin.t + margin.b);
        margin.t = Math.floor(correction * margin.t);
        margin.b = Math.floor(correction * margin.b);
    }
};

plots.clearAutoMarginIds = function(gd) {
    gd._fullLayout._pushmarginIds = {};
};

plots.allowAutoMargin = function(gd, id) {
    gd._fullLayout._pushmarginIds[id] = 1;
};

function initMargins(fullLayout) {
    var margin = fullLayout.margin;

    if(!fullLayout._size) {
        var gs = fullLayout._size = {
            l: Math.round(margin.l),
            r: Math.round(margin.r),
            t: Math.round(margin.t),
            b: Math.round(margin.b),
            p: Math.round(margin.pad)
        };
        gs.w = Math.round(fullLayout.width) - gs.l - gs.r;
        gs.h = Math.round(fullLayout.height) - gs.t - gs.b;
    }
    if(!fullLayout._pushmargin) fullLayout._pushmargin = {};
    if(!fullLayout._pushmarginIds) fullLayout._pushmarginIds = {};
}

/**
 * autoMargin: called by components that may need to expand the margins to
 * be rendered on-plot.
 *
 * @param {DOM element} gd
 * @param {string} id - an identifier unique (within this plot) to this object,
 *     so we can remove a previous margin expansion from the same object.
 * @param {object} o - the margin requirements of this object, or omit to delete
 *     this entry (like if it's hidden). Keys are:
 *     x, y: plot fraction of the anchor point.
 *     xl, xr, yt, yb: if the object has an extent defined in plot fraction,
 *         you can specify both edges as plot fractions in each dimension
 *     l, r, t, b: the pixels to pad past the plot fraction x[l|r] and y[t|b]
 *     pad: extra pixels to add in all directions, default 12 (why?)
 */
plots.autoMargin = function(gd, id, o) {
    var fullLayout = gd._fullLayout;

    var pushMargin = fullLayout._pushmargin;
    var pushMarginIds = fullLayout._pushmarginIds;

    if(fullLayout.margin.autoexpand !== false) {
        if(!o) {
            delete pushMargin[id];
            delete pushMarginIds[id];
        }
        else {
            var pad = o.pad;
            if(pad === undefined) {
                var margin = fullLayout.margin;
                // if no explicit pad is given, use 12px unless there's a
                // specified margin that's smaller than that
                pad = Math.min(12, margin.l, margin.r, margin.t, margin.b);
            }

            // if the item is too big, just give it enough automargin to
            // make sure you can still grab it and bring it back
            if(o.l + o.r > fullLayout.width * 0.5) o.l = o.r = 0;
            if(o.b + o.t > fullLayout.height * 0.5) o.b = o.t = 0;

            var xl = o.xl !== undefined ? o.xl : o.x;
            var xr = o.xr !== undefined ? o.xr : o.x;
            var yt = o.yt !== undefined ? o.yt : o.y;
            var yb = o.yb !== undefined ? o.yb : o.y;

            pushMargin[id] = {
                l: {val: xl, size: o.l + pad},
                r: {val: xr, size: o.r + pad},
                b: {val: yb, size: o.b + pad},
                t: {val: yt, size: o.t + pad}
            };
            pushMarginIds[id] = 1;
        }

        if(!fullLayout._replotting) plots.doAutoMargin(gd);
    }
};

plots.doAutoMargin = function(gd) {
    var fullLayout = gd._fullLayout;
    if(!fullLayout._size) fullLayout._size = {};
    initMargins(fullLayout);

    var gs = fullLayout._size;
    var oldmargins = JSON.stringify(gs);
    var margin = fullLayout.margin;

    // adjust margins for outside components
    // fullLayout.margin is the requested margin,
    // fullLayout._size has margins and plotsize after adjustment
    var ml = margin.l;
    var mr = margin.r;
    var mt = margin.t;
    var mb = margin.b;
    var pushMargin = fullLayout._pushmargin;
    var pushMarginIds = fullLayout._pushmarginIds;

    if(fullLayout.margin.autoexpand !== false) {

        for(var k in pushMargin) {
            if(!pushMarginIds[k]) delete pushMargin[k];
        }

        // fill in the requested margins
        pushMargin.base = {
            l: {val: 0, size: ml},
            r: {val: 1, size: mr},
            t: {val: 1, size: mt},
            b: {val: 0, size: mb}
        };

        // now cycle through all the combinations of l and r
        // (and t and b) to find the required margins

        for(var k1 in pushMargin) {

            var pushleft = pushMargin[k1].l || {};
            var pushbottom = pushMargin[k1].b || {};
            var fl = pushleft.val;
            var pl = pushleft.size;
            var fb = pushbottom.val;
            var pb = pushbottom.size;

            for(var k2 in pushMargin) {
                if(isNumeric(pl) && pushMargin[k2].r) {
                    var fr = pushMargin[k2].r.val;
                    var pr = pushMargin[k2].r.size;

                    if(fr > fl) {
                        var newl = (pl * fr +
                            (pr - fullLayout.width) * fl) / (fr - fl);
                        var newr = (pr * (1 - fl) +
                            (pl - fullLayout.width) * (1 - fr)) / (fr - fl);
                        if(newl >= 0 && newr >= 0 && newl + newr > ml + mr) {
                            ml = newl;
                            mr = newr;
                        }
                    }
                }

                if(isNumeric(pb) && pushMargin[k2].t) {
                    var ft = pushMargin[k2].t.val;
                    var pt = pushMargin[k2].t.size;

                    if(ft > fb) {
                        var newb = (pb * ft +
                            (pt - fullLayout.height) * fb) / (ft - fb);
                        var newt = (pt * (1 - fb) +
                            (pb - fullLayout.height) * (1 - ft)) / (ft - fb);
                        if(newb >= 0 && newt >= 0 && newb + newt > mb + mt) {
                            mb = newb;
                            mt = newt;
                        }
                    }
                }
            }
        }
    }

    gs.l = Math.round(ml);
    gs.r = Math.round(mr);
    gs.t = Math.round(mt);
    gs.b = Math.round(mb);
    gs.p = Math.round(margin.pad);
    gs.w = Math.round(fullLayout.width) - gs.l - gs.r;
    gs.h = Math.round(fullLayout.height) - gs.t - gs.b;

    // if things changed and we're not already redrawing, trigger a redraw
    if(!fullLayout._replotting &&
        oldmargins !== '{}' &&
        oldmargins !== JSON.stringify(fullLayout._size)
    ) {
        if('_redrawFromAutoMarginCount' in fullLayout) {
            fullLayout._redrawFromAutoMarginCount++;
        } else {
            fullLayout._redrawFromAutoMarginCount = 1;
        }
        return Registry.call('plot', gd);
    }
};

/**
 * JSONify the graph data and layout
 *
 * This function needs to recurse because some src can be inside
 * sub-objects.
 *
 * It also strips out functions and private (starts with _) elements.
 * Therefore, we can add temporary things to data and layout that don't
 * get saved.
 *
 * @param gd The graphDiv
 * @param {Boolean} dataonly If true, don't return layout.
 * @param {'keepref'|'keepdata'|'keepall'} [mode='keepref'] Filter what's kept
 *      keepref: remove data for which there's a src present
 *          eg if there's xsrc present (and xsrc is well-formed,
 *          ie has : and some chars before it), strip out x
 *      keepdata: remove all src tags, don't remove the data itself
 *      keepall: keep data and src
 * @param {String} output If you specify 'object', the result will not be stringified
 * @param {Boolean} useDefaults If truthy, use _fullLayout and _fullData
 * @returns {Object|String}
 */
plots.graphJson = function(gd, dataonly, mode, output, useDefaults) {
    // if the defaults aren't supplied yet, we need to do that...
    if((useDefaults && dataonly && !gd._fullData) ||
            (useDefaults && !dataonly && !gd._fullLayout)) {
        plots.supplyDefaults(gd);
    }

    var data = (useDefaults) ? gd._fullData : gd.data;
    var layout = (useDefaults) ? gd._fullLayout : gd.layout;
    var frames = (gd._transitionData || {})._frames;

    function stripObj(d) {
        if(typeof d === 'function') {
            return null;
        }
        if(Lib.isPlainObject(d)) {
            var o = {};
            var v, src;
            for(v in d) {
                // remove private elements and functions
                // _ is for private, [ is a mistake ie [object Object]
                if(typeof d[v] === 'function' ||
                        ['_', '['].indexOf(v.charAt(0)) !== -1) {
                    continue;
                }

                // look for src/data matches and remove the appropriate one
                if(mode === 'keepdata') {
                    // keepdata: remove all ...src tags
                    if(v.substr(v.length - 3) === 'src') {
                        continue;
                    }
                }
                else if(mode === 'keepstream') {
                    // keep sourced data if it's being streamed.
                    // similar to keepref, but if the 'stream' object exists
                    // in a trace, we will keep the data array.
                    src = d[v + 'src'];
                    if(typeof src === 'string' && src.indexOf(':') > 0) {
                        if(!Lib.isPlainObject(d.stream)) {
                            continue;
                        }
                    }
                }
                else if(mode !== 'keepall') {
                    // keepref: remove sourced data but only
                    // if the source tag is well-formed
                    src = d[v + 'src'];
                    if(typeof src === 'string' && src.indexOf(':') > 0) {
                        continue;
                    }
                }

                // OK, we're including this... recurse into it
                o[v] = stripObj(d[v]);
            }
            return o;
        }

        if(Array.isArray(d)) {
            return d.map(stripObj);
        }

        if(Lib.isTypedArray(d)) {
            return Lib.simpleMap(d, Lib.identity);
        }

        // convert native dates to date strings...
        // mostly for external users exporting to plotly
        if(Lib.isJSDate(d)) return Lib.ms2DateTimeLocal(+d);

        return d;
    }

    var obj = {
        data: (data || []).map(function(v) {
            var d = stripObj(v);
            // fit has some little arrays in it that don't contain data,
            // just fit params and meta
            if(dataonly) { delete d.fit; }
            return d;
        })
    };
    if(!dataonly) { obj.layout = stripObj(layout); }

    if(gd.framework && gd.framework.isPolar) obj = gd.framework.getConfig();

    if(frames) obj.frames = stripObj(frames);

    return (output === 'object') ? obj : JSON.stringify(obj);
};

/**
 * Modify a keyframe using a list of operations:
 *
 * @param {array of objects} operations
 *      Sequence of operations to be performed on the keyframes
 */
plots.modifyFrames = function(gd, operations) {
    var i, op, frame;
    var _frames = gd._transitionData._frames;
    var _frameHash = gd._transitionData._frameHash;

    for(i = 0; i < operations.length; i++) {
        op = operations[i];

        switch(op.type) {
            // No reason this couldn't exist, but is currently unused/untested:
            /* case 'rename':
                frame = _frames[op.index];
                delete _frameHash[frame.name];
                _frameHash[op.name] = frame;
                frame.name = op.name;
                break;*/
            case 'replace':
                frame = op.value;
                var oldName = (_frames[op.index] || {}).name;
                var newName = frame.name;
                _frames[op.index] = _frameHash[newName] = frame;

                if(newName !== oldName) {
                    // If name has changed in addition to replacement, then update
                    // the lookup table:
                    delete _frameHash[oldName];
                    _frameHash[newName] = frame;
                }

                break;
            case 'insert':
                frame = op.value;
                _frameHash[frame.name] = frame;
                _frames.splice(op.index, 0, frame);
                break;
            case 'delete':
                frame = _frames[op.index];
                delete _frameHash[frame.name];
                _frames.splice(op.index, 1);
                break;
        }
    }

    return Promise.resolve();
};

/*
 * Compute a keyframe. Merge a keyframe into its base frame(s) and
 * expand properties.
 *
 * @param {object} frameLookup
 *      An object containing frames keyed by name (i.e. gd._transitionData._frameHash)
 * @param {string} frame
 *      The name of the keyframe to be computed
 *
 * Returns: a new object with the merged content
 */
plots.computeFrame = function(gd, frameName) {
    var frameLookup = gd._transitionData._frameHash;
    var i, traceIndices, traceIndex, destIndex;

    // Null or undefined will fail on .toString(). We'll allow numbers since we
    // make it clear frames must be given string names, but we'll allow numbers
    // here since they're otherwise fine for looking up frames as long as they're
    // properly cast to strings. We really just want to ensure here that this
    // 1) doesn't fail, and
    // 2) doens't give an incorrect answer (which String(frameName) would)
    if(!frameName) {
        throw new Error('computeFrame must be given a string frame name');
    }

    var framePtr = frameLookup[frameName.toString()];

    // Return false if the name is invalid:
    if(!framePtr) {
        return false;
    }

    var frameStack = [framePtr];
    var frameNameStack = [framePtr.name];

    // Follow frame pointers:
    while(framePtr.baseframe && (framePtr = frameLookup[framePtr.baseframe.toString()])) {
        // Avoid infinite loops:
        if(frameNameStack.indexOf(framePtr.name) !== -1) break;

        frameStack.push(framePtr);
        frameNameStack.push(framePtr.name);
    }

    // A new object for the merged result:
    var result = {};

    // Merge, starting with the last and ending with the desired frame:
    while((framePtr = frameStack.pop())) {
        if(framePtr.layout) {
            result.layout = plots.extendLayout(result.layout, framePtr.layout);
        }

        if(framePtr.data) {
            if(!result.data) {
                result.data = [];
            }
            traceIndices = framePtr.traces;

            if(!traceIndices) {
                // If not defined, assume serial order starting at zero
                traceIndices = [];
                for(i = 0; i < framePtr.data.length; i++) {
                    traceIndices[i] = i;
                }
            }

            if(!result.traces) {
                result.traces = [];
            }

            for(i = 0; i < framePtr.data.length; i++) {
                // Loop through this frames data, find out where it should go,
                // and merge it!
                traceIndex = traceIndices[i];
                if(traceIndex === undefined || traceIndex === null) {
                    continue;
                }

                destIndex = result.traces.indexOf(traceIndex);
                if(destIndex === -1) {
                    destIndex = result.data.length;
                    result.traces[destIndex] = traceIndex;
                }

                result.data[destIndex] = plots.extendTrace(result.data[destIndex], framePtr.data[i]);
            }
        }
    }

    return result;
};

/*
 * Recompute the lookup table that maps frame name -> frame object. addFrames/
 * deleteFrames already manages this data one at a time, so the only time this
 * is necessary is if you poke around manually in `gd._transitionData._frames`
 * and create and haven't updated the lookup table.
 */
plots.recomputeFrameHash = function(gd) {
    var hash = gd._transitionData._frameHash = {};
    var frames = gd._transitionData._frames;
    for(var i = 0; i < frames.length; i++) {
        var frame = frames[i];
        if(frame && frame.name) {
            hash[frame.name] = frame;
        }
    }
};

/**
 * Extend an object, treating container arrays very differently by extracting
 * their contents and merging them separately.
 *
 * This exists so that we can extendDeepNoArrays and avoid stepping into data
 * arrays without knowledge of the plot schema, but so that we may also manually
 * recurse into known container arrays, such as transforms.
 *
 * See extendTrace and extendLayout below for usage.
 */
plots.extendObjectWithContainers = function(dest, src, containerPaths) {
    var containerProp, containerVal, i, j, srcProp, destProp, srcContainer, destContainer;
    var copy = Lib.extendDeepNoArrays({}, src || {});
    var expandedObj = Lib.expandObjectPaths(copy);
    var containerObj = {};

    // Step through and extract any container properties. Otherwise extendDeepNoArrays
    // will clobber any existing properties with an empty array and then supplyDefaults
    // will reset everything to defaults.
    if(containerPaths && containerPaths.length) {
        for(i = 0; i < containerPaths.length; i++) {
            containerProp = Lib.nestedProperty(expandedObj, containerPaths[i]);
            containerVal = containerProp.get();

            if(containerVal === undefined) {
                Lib.nestedProperty(containerObj, containerPaths[i]).set(null);
            }
            else {
                containerProp.set(null);
                Lib.nestedProperty(containerObj, containerPaths[i]).set(containerVal);
            }
        }
    }

    dest = Lib.extendDeepNoArrays(dest || {}, expandedObj);

    if(containerPaths && containerPaths.length) {
        for(i = 0; i < containerPaths.length; i++) {
            srcProp = Lib.nestedProperty(containerObj, containerPaths[i]);
            srcContainer = srcProp.get();

            if(!srcContainer) continue;

            destProp = Lib.nestedProperty(dest, containerPaths[i]);
            destContainer = destProp.get();

            if(!Array.isArray(destContainer)) {
                destContainer = [];
                destProp.set(destContainer);
            }

            for(j = 0; j < srcContainer.length; j++) {
                var srcObj = srcContainer[j];

                if(srcObj === null) destContainer[j] = null;
                else {
                    destContainer[j] = plots.extendObjectWithContainers(destContainer[j], srcObj);
                }
            }

            destProp.set(destContainer);
        }
    }

    return dest;
};

plots.dataArrayContainers = ['transforms', 'dimensions'];
plots.layoutArrayContainers = Registry.layoutArrayContainers;

/*
 * Extend a trace definition. This method:
 *
 *  1. directly transfers any array references
 *  2. manually recurses into container arrays like transforms
 *
 * The result is the original object reference with the new contents merged in.
 */
plots.extendTrace = function(destTrace, srcTrace) {
    return plots.extendObjectWithContainers(destTrace, srcTrace, plots.dataArrayContainers);
};

/*
 * Extend a layout definition. This method:
 *
 *  1. directly transfers any array references (not critically important for
 *     layout since there aren't really data arrays)
 *  2. manually recurses into container arrays like annotations
 *
 * The result is the original object reference with the new contents merged in.
 */
plots.extendLayout = function(destLayout, srcLayout) {
    return plots.extendObjectWithContainers(destLayout, srcLayout, plots.layoutArrayContainers);
};

/**
 * Transition to a set of new data and layout properties from Plotly.animate
 *
 * @param {DOM element} gd
 * @param {Object[]} data
 *      an array of data objects following the normal Plotly data definition format
 * @param {Object} layout
 *      a layout object, following normal Plotly layout format
 * @param {Number[]} traces
 *      indices of the corresponding traces specified in `data`
 * @param {Object} frameOpts
 *      options for the frame (i.e. whether to redraw post-transition)
 * @param {Object} transitionOpts
 *      options for the transition
 */
plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) {
    var opts = {redraw: frameOpts.redraw};
    var transitionedTraces = [];
    var axEdits = [];

    opts.prepareFn = function() {
        var dataLength = Array.isArray(data) ? data.length : 0;
        var traceIndices = traces.slice(0, dataLength);

        for(var i = 0; i < traceIndices.length; i++) {
            var traceIdx = traceIndices[i];
            var trace = gd._fullData[traceIdx];
            var module = trace._module;

            // There's nothing to do if this module is not defined:
            if(!module) continue;

            // Don't register the trace as transitioned if it doesn't know what to do.
            // If it *is* registered, it will receive a callback that it's responsible
            // for calling in order to register the transition as having completed.
            if(module.animatable) {
                transitionedTraces.push(traceIdx);
            }

            gd.data[traceIndices[i]] = plots.extendTrace(gd.data[traceIndices[i]], data[i]);
        }

        // Follow the same procedure. Clone it so we don't mangle the input, then
        // expand any object paths so we can merge deep into gd.layout:
        var layoutUpdate = Lib.expandObjectPaths(Lib.extendDeepNoArrays({}, layout));

        // Before merging though, we need to modify the incoming layout. We only
        // know how to *transition* layout ranges, so it's imperative that a new
        // range not be sent to the layout before the transition has started. So
        // we must remove the things we can transition:
        var axisAttrRe = /^[xy]axis[0-9]*$/;
        for(var attr in layoutUpdate) {
            if(!axisAttrRe.test(attr)) continue;
            delete layoutUpdate[attr].range;
        }

        plots.extendLayout(gd.layout, layoutUpdate);

        // Supply defaults after applying the incoming properties. Note that any attempt
        // to simplify this step and reduce the amount of work resulted in the reconstruction
        // of essentially the whole supplyDefaults step, so that it seems sensible to just use
        // supplyDefaults even though it's heavier than would otherwise be desired for
        // transitions:

        // first delete calcdata so supplyDefaults knows a calc step is coming
        delete gd.calcdata;

        plots.supplyDefaults(gd);
        plots.doCalcdata(gd);

        var newLayout = Lib.expandObjectPaths(layout);

        if(newLayout) {
            var subplots = gd._fullLayout._plots;

            for(var k in subplots) {
                var plotinfo = subplots[k];
                var xa = plotinfo.xaxis;
                var ya = plotinfo.yaxis;
                var xr0 = xa.range.slice();
                var yr0 = ya.range.slice();

                var xr1;
                if(Array.isArray(newLayout[xa._name + '.range'])) {
                    xr1 = newLayout[xa._name + '.range'].slice();
                } else if(Array.isArray((newLayout[xa._name] || {}).range)) {
                    xr1 = newLayout[xa._name].range.slice();
                }

                var yr1;
                if(Array.isArray(newLayout[ya._name + '.range'])) {
                    yr1 = newLayout[ya._name + '.range'].slice();
                } else if(Array.isArray((newLayout[ya._name] || {}).range)) {
                    yr1 = newLayout[ya._name].range.slice();
                }

                var editX;
                if(xr0 && xr1 && (xr0[0] !== xr1[0] || xr0[1] !== xr1[1])) {
                    editX = {xr0: xr0, xr1: xr1};
                }

                var editY;
                if(yr0 && yr1 && (yr0[0] !== yr1[0] || yr0[1] !== yr1[1])) {
                    editY = {yr0: yr0, yr1: yr1};
                }

                if(editX || editY) {
                    axEdits.push(Lib.extendFlat({plotinfo: plotinfo}, editX, editY));
                }
            }
        }

        return Promise.resolve();
    };

    opts.runFn = function(makeCallback) {
        var traceTransitionOpts;
        var basePlotModules = gd._fullLayout._basePlotModules;
        var hasAxisTransition = axEdits.length;
        var i;

        if(layout) {
            for(i = 0; i < basePlotModules.length; i++) {
                if(basePlotModules[i].transitionAxes) {
                    basePlotModules[i].transitionAxes(gd, axEdits, transitionOpts, makeCallback);
                }
            }
        }

        // Here handle the exception that we refuse to animate scales and axes at the same
        // time. In other words, if there's an axis transition, then set the data transition
        // to instantaneous.
        if(hasAxisTransition) {
            traceTransitionOpts = Lib.extendFlat({}, transitionOpts);
            traceTransitionOpts.duration = 0;
            // This means do not transition traces,
            // this happens on layout-only (e.g. axis range) animations
            transitionedTraces = null;
        } else {
            traceTransitionOpts = transitionOpts;
        }

        for(i = 0; i < basePlotModules.length; i++) {
            // Note that we pass a callback to *create* the callback that must be invoked on completion.
            // This is since not all traces know about transitions, so it greatly simplifies matters if
            // the trace is responsible for creating a callback, if needed, and then executing it when
            // the time is right.
            basePlotModules[i].plot(gd, transitionedTraces, traceTransitionOpts, makeCallback);
        }
    };

    return _transition(gd, transitionOpts, opts);
};

/**
 * Transition to a set of new data and layout properties from Plotly.react
 *
 * @param {DOM element} gd
 * @param {object} restyleFlags
 * - anim {'all'|'some'}
 * @param {object} relayoutFlags
 * - anim {'all'|'some'}
 * @param {object} oldFullLayout : old (pre Plotly.react) fullLayout
 */
plots.transitionFromReact = function(gd, restyleFlags, relayoutFlags, oldFullLayout) {
    var fullLayout = gd._fullLayout;
    var transitionOpts = fullLayout.transition;
    var opts = {};
    var axEdits = [];

    opts.prepareFn = function() {
        var subplots = fullLayout._plots;

        // no need to redraw at end of transition,
        // if all changes are animatable
        opts.redraw = false;
        if(restyleFlags.anim === 'some') opts.redraw = true;
        if(relayoutFlags.anim === 'some') opts.redraw = true;

        for(var k in subplots) {
            var plotinfo = subplots[k];
            var xa = plotinfo.xaxis;
            var ya = plotinfo.yaxis;
            var xr0 = oldFullLayout[xa._name].range.slice();
            var yr0 = oldFullLayout[ya._name].range.slice();
            var xr1 = xa.range.slice();
            var yr1 = ya.range.slice();

            xa.setScale();
            ya.setScale();

            var editX;
            if(xr0[0] !== xr1[0] || xr0[1] !== xr1[1]) {
                editX = {xr0: xr0, xr1: xr1};
            }

            var editY;
            if(yr0[0] !== yr1[0] || yr0[1] !== yr1[1]) {
                editY = {yr0: yr0, yr1: yr1};
            }

            if(editX || editY) {
                axEdits.push(Lib.extendFlat({plotinfo: plotinfo}, editX, editY));
            }
        }

        return Promise.resolve();
    };

    opts.runFn = function(makeCallback) {
        var fullData = gd._fullData;
        var fullLayout = gd._fullLayout;
        var basePlotModules = fullLayout._basePlotModules;

        var axisTransitionOpts;
        var traceTransitionOpts;
        var transitionedTraces;

        var allTraceIndices = [];
        for(var i = 0; i < fullData.length; i++) {
            allTraceIndices.push(i);
        }

        function transitionAxes() {
            for(var j = 0; j < basePlotModules.length; j++) {
                if(basePlotModules[j].transitionAxes) {
                    basePlotModules[j].transitionAxes(gd, axEdits, axisTransitionOpts, makeCallback);
                }
            }
        }

        function transitionTraces() {
            for(var j = 0; j < basePlotModules.length; j++) {
                basePlotModules[j].plot(gd, transitionedTraces, traceTransitionOpts, makeCallback);
            }
        }

        if(axEdits.length && restyleFlags.anim) {
            if(transitionOpts.ordering === 'traces first') {
                axisTransitionOpts = Lib.extendFlat({}, transitionOpts, {duration: 0});
                transitionedTraces = allTraceIndices;
                traceTransitionOpts = transitionOpts;
                transitionTraces();
                setTimeout(transitionAxes, transitionOpts.duration);
            } else {
                axisTransitionOpts = transitionOpts;
                transitionedTraces = null;
                traceTransitionOpts = Lib.extendFlat({}, transitionOpts, {duration: 0});
                transitionAxes();
                transitionTraces();
            }
        } else if(axEdits.length) {
            axisTransitionOpts = transitionOpts;
            transitionAxes();
        } else if(restyleFlags.anim) {
            transitionedTraces = allTraceIndices;
            traceTransitionOpts = transitionOpts;
            transitionTraces();
        }
    };

    return _transition(gd, transitionOpts, opts);
};

/**
 * trace/layout transition wrapper that works
 * for transitions initiated by Plotly.animate and Plotly.react.
 *
 * @param {DOM element} gd
 * @param {object} transitionOpts
 * @param {object} opts
 * - redraw {boolean}
 * - prepareFn {function} *should return a Promise*
 * - runFn {function} ran inside executeTransitions
 */
function _transition(gd, transitionOpts, opts) {
    var aborted = false;

    function executeCallbacks(list) {
        var p = Promise.resolve();
        if(!list) return p;
        while(list.length) {
            p = p.then((list.shift()));
        }
        return p;
    }

    function flushCallbacks(list) {
        if(!list) return;
        while(list.length) {
            list.shift();
        }
    }

    function executeTransitions() {
        gd.emit('plotly_transitioning', []);

        return new Promise(function(resolve) {
            // This flag is used to disabled things like autorange:
            gd._transitioning = true;

            // When instantaneous updates are coming through quickly, it's too much to simply disable
            // all interaction, so store this flag so we can disambiguate whether mouse interactions
            // should be fully disabled or not:
            if(transitionOpts.duration > 0) {
                gd._transitioningWithDuration = true;
            }

            // If another transition is triggered, this callback will be executed simply because it's
            // in the interruptCallbacks queue. If this transition completes, it will instead flush
            // that queue and forget about this callback.
            gd._transitionData._interruptCallbacks.push(function() {
                aborted = true;
            });

            if(opts.redraw) {
                gd._transitionData._interruptCallbacks.push(function() {
                    return Registry.call('redraw', gd);
                });
            }

            // Emit this and make sure it happens last:
            gd._transitionData._interruptCallbacks.push(function() {
                gd.emit('plotly_transitioninterrupted', []);
            });

            // Construct callbacks that are executed on transition end. This ensures the d3 transitions
            // are *complete* before anything else is done.
            var numCallbacks = 0;
            var numCompleted = 0;
            function makeCallback() {
                numCallbacks++;
                return function() {
                    numCompleted++;
                    // When all are complete, perform a redraw:
                    if(!aborted && numCompleted === numCallbacks) {
                        completeTransition(resolve);
                    }
                };
            }

            opts.runFn(makeCallback);

            // If nothing else creates a callback, then this will trigger the completion in the next tick:
            setTimeout(makeCallback());
        });
    }

    function completeTransition(callback) {
        // This a simple workaround for tests which purge the graph before animations
        // have completed. That's not a very common case, so this is the simplest
        // fix.
        if(!gd._transitionData) return;

        flushCallbacks(gd._transitionData._interruptCallbacks);

        return Promise.resolve().then(function() {
            if(opts.redraw) {
                return Registry.call('redraw', gd);
            }
        }).then(function() {
            // Set transitioning false again once the redraw has occurred. This is used, for example,
            // to prevent the trailing redraw from autoranging:
            gd._transitioning = false;
            gd._transitioningWithDuration = false;

            gd.emit('plotly_transitioned', []);
        }).then(callback);
    }

    function interruptPreviousTransitions() {
        // Fail-safe against purged plot:
        if(!gd._transitionData) return;

        // If a transition is interrupted, set this to false. At the moment, the only thing that would
        // interrupt a transition is another transition, so that it will momentarily be set to true
        // again, but this determines whether autorange or dragbox work, so it's for the sake of
        // cleanliness:
        gd._transitioning = false;

        return executeCallbacks(gd._transitionData._interruptCallbacks);
    }

    var seq = [
        plots.previousPromises,
        interruptPreviousTransitions,
        opts.prepareFn,
        plots.rehover,
        executeTransitions
    ];

    var transitionStarting = Lib.syncOrAsync(seq, gd);

    if(!transitionStarting || !transitionStarting.then) {
        transitionStarting = Promise.resolve();
    }

    return transitionStarting.then(function() { return gd; });
}

plots.doCalcdata = function(gd, traces) {
    var axList = axisIDs.list(gd);
    var fullData = gd._fullData;
    var fullLayout = gd._fullLayout;

    var trace, _module, i, j;

    // XXX: Is this correct? Needs a closer look so that *some* traces can be recomputed without
    // *all* needing doCalcdata:
    var calcdata = new Array(fullData.length);
    var oldCalcdata = (gd.calcdata || []).slice(0);
    gd.calcdata = calcdata;

    // extra helper variables

    // how many box/violins plots do we have (in case they're grouped)
    fullLayout._numBoxes = 0;
    fullLayout._numViolins = 0;

    // initialize violin per-scale-group stats container
    fullLayout._violinScaleGroupStats = {};

    // for calculating avg luminosity of heatmaps
    gd._hmpixcount = 0;
    gd._hmlumcount = 0;

    // for sharing colors across pies (and for legend)
    fullLayout._piecolormap = {};

    // If traces were specified and this trace was not included,
    // then transfer it over from the old calcdata:
    for(i = 0; i < fullData.length; i++) {
        if(Array.isArray(traces) && traces.indexOf(i) === -1) {
            calcdata[i] = oldCalcdata[i];
            continue;
        }
    }

    for(i = 0; i < fullData.length; i++) {
        trace = fullData[i];

        trace._arrayAttrs = PlotSchema.findArrayAttributes(trace);

        // keep track of trace extremes (for autorange) in here
        trace._extremes = {};
    }

    // add polar axes to axis list
    var polarIds = fullLayout._subplots.polar || [];
    for(i = 0; i < polarIds.length; i++) {
        axList.push(
            fullLayout[polarIds[i]].radialaxis,
            fullLayout[polarIds[i]].angularaxis
        );
    }

    setupAxisCategories(axList, fullData);

    var hasCalcTransform = false;

    // transform loop
    for(i = 0; i < fullData.length; i++) {
        trace = fullData[i];

        if(trace.visible === true && trace.transforms) {
            _module = trace._module;

            // we need one round of trace module calc before
            // the calc transform to 'fill in' the categories list
            // used for example in the data-to-coordinate method
            if(_module && _module.calc) {
                var cdi = _module.calc(gd, trace);

                // must clear scene 'batches', so that 2nd
                // _module.calc call starts from scratch
                if(cdi[0] && cdi[0].t && cdi[0].t._scene) {
                    delete cdi[0].t._scene.dirty;
                }
            }

            for(j = 0; j < trace.transforms.length; j++) {
                var transform = trace.transforms[j];

                _module = transformsRegistry[transform.type];
                if(_module && _module.calcTransform) {
                    trace._hasCalcTransform = true;
                    hasCalcTransform = true;
                    _module.calcTransform(gd, trace, transform);
                }
            }
        }
    }

    // clear stuff that should recomputed in 'regular' loop
    if(hasCalcTransform) setupAxisCategories(axList, fullData);

    function calci(i, isContainer) {
        trace = fullData[i];
        _module = trace._module;

        if(!!_module.isContainer !== isContainer) return;

        var cd = [];

        if(trace.visible === true) {

            // clear existing ref in case it got relinked
            delete trace._indexToPoints;
            // keep ref of index-to-points map object of the *last* enabled transform,
            // this index-to-points map object is required to determine the calcdata indices
            // that correspond to input indices (e.g. from 'selectedpoints')
            var transforms = trace.transforms || [];
            for(j = transforms.length - 1; j >= 0; j--) {
                if(transforms[j].enabled) {
                    trace._indexToPoints = transforms[j]._indexToPoints;
                    break;
                }
            }

            if(_module && _module.calc) {
                cd = _module.calc(gd, trace);
            }
        }

        // Make sure there is a first point.
        //
        // This ensures there is a calcdata item for every trace,
        // even if cartesian logic doesn't handle it (for things like legends).
        if(!Array.isArray(cd) || !cd[0]) {
            cd = [{x: BADNUM, y: BADNUM}];
        }

        // add the trace-wide properties to the first point,
        // per point properties to every point
        // t is the holder for trace-wide properties
        if(!cd[0].t) cd[0].t = {};
        cd[0].trace = trace;

        calcdata[i] = cd;
    }

    // 'regular' loop - make sure container traces (eg carpet) calc before
    // contained traces (eg contourcarpet)
    for(i = 0; i < fullData.length; i++) calci(i, true);
    for(i = 0; i < fullData.length; i++) calci(i, false);

    doCrossTraceCalc(gd);

    Registry.getComponentMethod('fx', 'calc')(gd);
    Registry.getComponentMethod('errorbars', 'calc')(gd);
};

function setupAxisCategories(axList, fullData) {
    for(var i = 0; i < axList.length; i++) {
        var ax = axList[i];
        ax.clearCalc();
        if(ax.type === 'multicategory') {
            ax.setupMultiCategory(fullData);
        }
    }
}

function doCrossTraceCalc(gd) {
    var fullLayout = gd._fullLayout;
    var modules = fullLayout._visibleModules;
    var hash = {};
    var i, j, k;

    // position and range calculations for traces that
    // depend on each other ie bars (stacked or grouped)
    // and boxes (grouped) push each other out of the way

    for(j = 0; j < modules.length; j++) {
        var _module = modules[j];
        var fn = _module.crossTraceCalc;
        if(fn) {
            var spType = _module.basePlotModule.name;
            if(hash[spType]) {
                Lib.pushUnique(hash[spType], fn);
            } else {
                hash[spType] = [fn];
            }
        }
    }

    for(k in hash) {
        var methods = hash[k];
        var subplots = fullLayout._subplots[k];

        if(Array.isArray(subplots)) {
            for(i = 0; i < subplots.length; i++) {
                var sp = subplots[i];
                var spInfo = k === 'cartesian' ?
                    fullLayout._plots[sp] :
                    fullLayout[sp];

                for(j = 0; j < methods.length; j++) {
                    methods[j](gd, spInfo, sp);
                }
            }
        }
        else {
            for(j = 0; j < methods.length; j++) {
                methods[j](gd);
            }
        }
    }
}

plots.rehover = function(gd) {
    if(gd._fullLayout._rehover) {
        gd._fullLayout._rehover();
    }
};

plots.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subplotLayout) {
    var traceHashOld = subplot.traceHash;
    var traceHash = {};
    var i;

    // build up moduleName -> calcData hash
    for(i = 0; i < subplotCalcData.length; i++) {
        var calcTraces = subplotCalcData[i];
        var trace = calcTraces[0].trace;

        // skip over visible === false traces
        // as they don't have `_module` ref
        if(trace.visible) {
            traceHash[trace.type] = traceHash[trace.type] || [];
            traceHash[trace.type].push(calcTraces);
        }
    }

    // when a trace gets deleted, make sure that its module's
    // plot method is called so that it is properly
    // removed from the DOM.
    for(var moduleNameOld in traceHashOld) {
        if(!traceHash[moduleNameOld]) {
            var fakeCalcTrace = traceHashOld[moduleNameOld][0];
            var fakeTrace = fakeCalcTrace[0].trace;

            fakeTrace.visible = false;
            traceHash[moduleNameOld] = [fakeCalcTrace];
        }
    }

    // call module plot method
    for(var moduleName in traceHash) {
        var moduleCalcData = traceHash[moduleName];
        var _module = moduleCalcData[0][0].trace._module;

        _module.plot(gd, subplot, Lib.filterVisible(moduleCalcData), subplotLayout);
    }

    // update moduleName -> calcData hash
    subplot.traceHash = traceHash;
};

},{"../components/color":571,"../constants/numerical":671,"../lib":694,"../plot_api/plot_schema":731,"../plot_api/plot_template":732,"../plots/cartesian/axis_ids":745,"../registry":825,"./animation_attributes":737,"./attributes":739,"./command":767,"./font_attributes":769,"./frame_attributes":770,"./layout_attributes":797,"d3":149,"fast-isnumeric":215}],807:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    attr: 'subplot',
    name: 'polar',

    axisNames: ['angularaxis', 'radialaxis'],
    axisName2dataArray: {angularaxis: 'theta', radialaxis: 'r'},

    layerNames: [
        'draglayer',
        'plotbg',
        'backplot',
        'angular-grid',
        'radial-grid',
        'frontplot',
        'angular-line',
        'radial-line',
        'angular-axis',
        'radial-axis'
    ],

    radialDragBoxSize: 50,
    angularDragBoxSize: 30,
    cornerLen: 25,
    cornerHalfWidth: 2,

    // pixels to move mouse before you stop clamping to starting point
    MINDRAG: 8,
    // smallest radial distance [px] allowed for a zoombox
    MINZOOM: 20,
    // distance [px] off (r=0) or (r=radius) where we transition
    // from single-sided to two-sided radial zoom
    OFFEDGE: 20
};

},{}],808:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var polygonTester = _dereq_('../../lib/polygon').tester;

var findIndexOfMin = Lib.findIndexOfMin;
var isAngleInsideSector = Lib.isAngleInsideSector;
var angleDelta = Lib.angleDelta;
var angleDist = Lib.angleDist;

/**
 * is pt (r,a) inside polygon made up vertices at angles 'vangles'
 * inside a given polar sector
 *
 * @param {number} r : pt's radial coordinate
 * @param {number} a : pt's angular coordinate in *radians*
 * @param {2-item array} rBnds : sector's radial bounds
 * @param {2-item array} aBnds : sector's angular bounds *radians*
 * @param {array} vangles : angles of polygon vertices in *radians*
 * @return {boolean}
 */
function isPtInsidePolygon(r, a, rBnds, aBnds, vangles) {
    if(!isAngleInsideSector(a, aBnds)) return false;

    var r0, r1;

    if(rBnds[0] < rBnds[1]) {
        r0 = rBnds[0];
        r1 = rBnds[1];
    } else {
        r0 = rBnds[1];
        r1 = rBnds[0];
    }

    var polygonIn = polygonTester(makePolygon(r0, aBnds[0], aBnds[1], vangles));
    var polygonOut = polygonTester(makePolygon(r1, aBnds[0], aBnds[1], vangles));
    var xy = [r * Math.cos(a), r * Math.sin(a)];
    return polygonOut.contains(xy) && !polygonIn.contains(xy);
}

// find intersection of 'v0' <-> 'v1' edge with a ray at angle 'a'
// (i.e. a line that starts from the origin at angle 'a')
// given an (xp,yp) pair on the 'v0' <-> 'v1' line
// (N.B. 'v0' and 'v1' are angles in radians)
function findIntersectionXY(v0, v1, a, xpyp) {
    var xstar, ystar;

    var xp = xpyp[0];
    var yp = xpyp[1];
    var dsin = clampTiny(Math.sin(v1) - Math.sin(v0));
    var dcos = clampTiny(Math.cos(v1) - Math.cos(v0));
    var tanA = Math.tan(a);
    var cotanA = clampTiny(1 / tanA);
    var m = dsin / dcos;
    var b = yp - m * xp;

    if(cotanA) {
        if(dsin && dcos) {
            // given
            //  g(x) := v0 -> v1 line = m*x + b
            //  h(x) := ray at angle 'a' = m*x = tanA*x
            // solve g(xstar) = h(xstar)
            xstar = b / (tanA - m);
            ystar = tanA * xstar;
        } else if(dcos) {
            // horizontal v0 -> v1
            xstar = yp * cotanA;
            ystar = yp;
        } else {
            // vertical v0 -> v1
            xstar = xp;
            ystar = xp * tanA;
        }
    } else {
        // vertical ray
        if(dsin && dcos) {
            xstar = 0;
            ystar = b;
        } else if(dcos) {
            xstar = 0;
            ystar = yp;
        } else {
            // does this case exists?
            xstar = ystar = NaN;
        }
    }

    return [xstar, ystar];
}

// solves l^2 = (f(x)^2 - yp)^2 + (x - xp)^2
// rearranged into 0 = a*x^2 + b * x + c
//
// where f(x) = m*x + t + yp
// and   (x0, x1) = (-b +/- del) / (2*a)
function findXYatLength(l, m, xp, yp) {
    var t = -m * xp;
    var a = m * m + 1;
    var b = 2 * (m * t - xp);
    var c = t * t + xp * xp - l * l;
    var del = Math.sqrt(b * b - 4 * a * c);
    var x0 = (-b + del) / (2 * a);
    var x1 = (-b - del) / (2 * a);
    return [
        [x0, m * x0 + t + yp],
        [x1, m * x1 + t + yp]
    ];
}

function makeRegularPolygon(r, vangles) {
    var len = vangles.length;
    var vertices = new Array(len + 1);
    var i;
    for(i = 0; i < len; i++) {
        var va = vangles[i];
        vertices[i] = [r * Math.cos(va), r * Math.sin(va)];
    }
    vertices[i] = vertices[0].slice();
    return vertices;
}

function makeClippedPolygon(r, a0, a1, vangles) {
    var len = vangles.length;
    var vertices = [];
    var i, j;

    function a2xy(a) {
        return [r * Math.cos(a), r * Math.sin(a)];
    }

    function findXY(va0, va1, s) {
        return findIntersectionXY(va0, va1, s, a2xy(va0));
    }

    function cycleIndex(ind) {
        return Lib.mod(ind, len);
    }

    function isInside(v) {
        return isAngleInsideSector(v, [a0, a1]);
    }

    // find index in sector closest to a0
    // use it to find intersection of v[i0] <-> v[i0-1] edge with sector radius
    var i0 = findIndexOfMin(vangles, function(v) {
        return isInside(v) ? angleDist(v, a0) : Infinity;
    });
    var xy0 = findXY(vangles[i0], vangles[cycleIndex(i0 - 1)], a0);
    vertices.push(xy0);

    // fill in in-sector vertices
    for(i = i0, j = 0; j < len; i++, j++) {
        var va = vangles[cycleIndex(i)];
        if(!isInside(va)) break;
        vertices.push(a2xy(va));
    }

    // find index in sector closest to a1,
    // use it to find intersection of v[iN] <-> v[iN+1] edge with sector radius
    var iN = findIndexOfMin(vangles, function(v) {
        return isInside(v) ? angleDist(v, a1) : Infinity;
    });
    var xyN = findXY(vangles[iN], vangles[cycleIndex(iN + 1)], a1);
    vertices.push(xyN);

    vertices.push([0, 0]);
    vertices.push(vertices[0].slice());

    return vertices;
}

function makePolygon(r, a0, a1, vangles) {
    return Lib.isFullCircle([a0, a1]) ?
        makeRegularPolygon(r, vangles) :
        makeClippedPolygon(r, a0, a1, vangles);
}

function findPolygonOffset(r, a0, a1, vangles) {
    var minX = Infinity;
    var minY = Infinity;
    var vertices = makePolygon(r, a0, a1, vangles);

    for(var i = 0; i < vertices.length; i++) {
        var v = vertices[i];
        minX = Math.min(minX, v[0]);
        minY = Math.min(minY, -v[1]);
    }
    return [minX, minY];
}

/**
 * find vertex angles (in 'vangles') the enclose angle 'a'
 *
 * @param {number} a : angle in *radians*
 * @param {array} vangles : angles of polygon vertices in *radians*
 * @return {2-item array}
 */
function findEnclosingVertexAngles(a, vangles) {
    var minFn = function(v) {
        var adelta = angleDelta(v, a);
        return adelta > 0 ? adelta : Infinity;
    };
    var i0 = findIndexOfMin(vangles, minFn);
    var i1 = Lib.mod(i0 + 1, vangles.length);
    return [vangles[i0], vangles[i1]];
}

// to more easily catch 'almost zero' numbers in if-else blocks
function clampTiny(v) {
    return Math.abs(v) > 1e-10 ? v : 0;
}

function transformForSVG(pts0, cx, cy) {
    cx = cx || 0;
    cy = cy || 0;

    var len = pts0.length;
    var pts1 = new Array(len);

    for(var i = 0; i < len; i++) {
        var pt = pts0[i];
        pts1[i] = [cx + pt[0], cy - pt[1]];
    }
    return pts1;
}

/**
 * path polygon
 *
 * @param {number} r : polygon 'radius'
 * @param {number} a0 : first angular coordinate in *radians*
 * @param {number} a1 : second angular coordinate in *radians*
 * @param {array} vangles : angles of polygon vertices in *radians*
 * @param {number (optional)} cx : x coordinate of center
 * @param {number (optional)} cy : y coordinate of center
 * @return {string} svg path
 *
 */
function pathPolygon(r, a0, a1, vangles, cx, cy) {
    var poly = makePolygon(r, a0, a1, vangles);
    return 'M' + transformForSVG(poly, cx, cy).join('L');
}

/**
 * path a polygon 'annulus'
 * i.e. a polygon with a concentric hole
 *
 * N.B. this routine uses the evenodd SVG rule
 *
 * @param {number} r0 : first radial coordinate
 * @param {number} r1 : second radial coordinate
 * @param {number} a0 : first angular coordinate in *radians*
 * @param {number} a1 : second angular coordinate in *radians*
 * @param {array} vangles : angles of polygon vertices in *radians*
 * @param {number (optional)} cx : x coordinate of center
 * @param {number (optional)} cy : y coordinate of center
 * @return {string} svg path
 *
 */
function pathPolygonAnnulus(r0, r1, a0, a1, vangles, cx, cy) {
    var rStart, rEnd;

    if(r0 < r1) {
        rStart = r0;
        rEnd = r1;
    } else {
        rStart = r1;
        rEnd = r0;
    }

    var inner = transformForSVG(makePolygon(rStart, a0, a1, vangles), cx, cy);
    var outer = transformForSVG(makePolygon(rEnd, a0, a1, vangles), cx, cy);
    return 'M' + outer.reverse().join('L') + 'M' + inner.join('L');
}

module.exports = {
    isPtInsidePolygon: isPtInsidePolygon,
    findPolygonOffset: findPolygonOffset,
    findEnclosingVertexAngles: findEnclosingVertexAngles,
    findIntersectionXY: findIntersectionXY,
    findXYatLength: findXYatLength,
    clampTiny: clampTiny,
    pathPolygon: pathPolygon,
    pathPolygonAnnulus: pathPolygonAnnulus
};

},{"../../lib":694,"../../lib/polygon":706}],809:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var getSubplotCalcData = _dereq_('../get_data').getSubplotCalcData;
var counterRegex = _dereq_('../../lib').counterRegex;

var createPolar = _dereq_('./polar');
var constants = _dereq_('./constants');

var attr = constants.attr;
var name = constants.name;
var counter = counterRegex(name);

var attributes = {};
attributes[attr] = {
    valType: 'subplotid',
    
    dflt: name,
    editType: 'calc',
    
};

function plot(gd) {
    var fullLayout = gd._fullLayout;
    var calcData = gd.calcdata;
    var subplotIds = fullLayout._subplots[name];

    for(var i = 0; i < subplotIds.length; i++) {
        var id = subplotIds[i];
        var subplotCalcData = getSubplotCalcData(calcData, name, id);
        var subplot = fullLayout[id]._subplot;

        if(!subplot) {
            subplot = createPolar(gd, id);
            fullLayout[id]._subplot = subplot;
        }

        subplot.plot(subplotCalcData, fullLayout, gd._promises);
    }
}

function clean(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var oldIds = oldFullLayout._subplots[name] || [];
    var hadGl = (oldFullLayout._has && oldFullLayout._has('gl'));
    var hasGl = (newFullLayout._has && newFullLayout._has('gl'));
    var mustCleanScene = hadGl && !hasGl;

    for(var i = 0; i < oldIds.length; i++) {
        var id = oldIds[i];
        var oldSubplot = oldFullLayout[id]._subplot;

        if(!newFullLayout[id] && !!oldSubplot) {
            oldSubplot.framework.remove();
            oldSubplot.layers['radial-axis-title'].remove();

            for(var k in oldSubplot.clipPaths) {
                oldSubplot.clipPaths[k].remove();
            }
        }

        if(mustCleanScene && oldSubplot._scene) {
            oldSubplot._scene.destroy();
            oldSubplot._scene = null;
        }
    }
}

module.exports = {
    attr: attr,
    name: name,
    idRoot: name,
    idRegex: counter,
    attrRegex: counter,
    attributes: attributes,
    layoutAttributes: _dereq_('./layout_attributes'),
    supplyLayoutDefaults: _dereq_('./layout_defaults'),
    plot: plot,
    clean: clean,
    toSVG: _dereq_('../cartesian').toSVG
};

},{"../../lib":694,"../cartesian":754,"../get_data":779,"./constants":807,"./layout_attributes":810,"./layout_defaults":811,"./polar":818}],810:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorAttrs = _dereq_('../../components/color/attributes');
var axesAttrs = _dereq_('../cartesian/layout_attributes');
var domainAttrs = _dereq_('../domain').attributes;
var extendFlat = _dereq_('../../lib').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;

var axisLineGridAttr = overrideAll({
    color: axesAttrs.color,
    showline: extendFlat({}, axesAttrs.showline, {dflt: true}),
    linecolor: axesAttrs.linecolor,
    linewidth: axesAttrs.linewidth,
    showgrid: extendFlat({}, axesAttrs.showgrid, {dflt: true}),
    gridcolor: axesAttrs.gridcolor,
    gridwidth: axesAttrs.gridwidth

    // TODO add spike* attributes down the road

    // should we add zeroline* attributes?

}, 'plot', 'from-root');

var axisTickAttrs = overrideAll({
    tickmode: axesAttrs.tickmode,
    nticks: axesAttrs.nticks,
    tick0: axesAttrs.tick0,
    dtick: axesAttrs.dtick,
    tickvals: axesAttrs.tickvals,
    ticktext: axesAttrs.ticktext,
    ticks: axesAttrs.ticks,
    ticklen: axesAttrs.ticklen,
    tickwidth: axesAttrs.tickwidth,
    tickcolor: axesAttrs.tickcolor,
    showticklabels: axesAttrs.showticklabels,
    showtickprefix: axesAttrs.showtickprefix,
    tickprefix: axesAttrs.tickprefix,
    showticksuffix: axesAttrs.showticksuffix,
    ticksuffix: axesAttrs.ticksuffix,
    showexponent: axesAttrs.showexponent,
    exponentformat: axesAttrs.exponentformat,
    separatethousands: axesAttrs.separatethousands,
    tickfont: axesAttrs.tickfont,
    tickangle: axesAttrs.tickangle,
    tickformat: axesAttrs.tickformat,
    tickformatstops: axesAttrs.tickformatstops,
    layer: axesAttrs.layer
}, 'plot', 'from-root');

var radialAxisAttrs = {
    visible: extendFlat({}, axesAttrs.visible, {dflt: true}),
    type: extendFlat({}, axesAttrs.type, {
        values: ['-', 'linear', 'log', 'date', 'category']
    }),

    autorange: extendFlat({}, axesAttrs.autorange, {editType: 'plot'}),
    rangemode: {
        valType: 'enumerated',
        values: ['tozero', 'nonnegative', 'normal'],
        dflt: 'tozero',
        
        editType: 'calc',
        
    },
    range: extendFlat({}, axesAttrs.range, {
        items: [
            {valType: 'any', editType: 'plot', impliedEdits: {'^autorange': false}},
            {valType: 'any', editType: 'plot', impliedEdits: {'^autorange': false}}
        ],
        editType: 'plot'
    }),

    categoryorder: axesAttrs.categoryorder,
    categoryarray: axesAttrs.categoryarray,

    angle: {
        valType: 'angle',
        editType: 'plot',
        
        
    },

    side: {
        valType: 'enumerated',
        // TODO add 'center' for `showline: false` radial axes
        values: ['clockwise', 'counterclockwise'],
        dflt: 'clockwise',
        editType: 'plot',
        
        
    },


    title: overrideAll(axesAttrs.title, 'plot', 'from-root'),
    // might need a 'titleside' and even 'titledirection' down the road

    hoverformat: axesAttrs.hoverformat,

    uirevision: {
        valType: 'any',
        
        editType: 'none',
        
    },

    editType: 'calc',

    _deprecated: {
        title: axesAttrs._deprecated.title,
        titlefont: axesAttrs._deprecated.titlefont
    }
};

// radial title is not gui-editable, so it needs dflt: '', similar to carpet axes.
radialAxisAttrs.title.text.dflt = '';

extendFlat(
    radialAxisAttrs,

    // N.B. radialaxis grid lines are circular,
    // but radialaxis lines are straight from circle center to outer bound
    axisLineGridAttr,
    axisTickAttrs
);

var angularAxisAttrs = {
    visible: extendFlat({}, axesAttrs.visible, {dflt: true}),
    type: {
        valType: 'enumerated',
        // 'linear' should maybe be called 'angle' or 'angular' here
        // to make clear that axis here is periodic and more tightly match
        // `thetaunit`?
        //
        // skip 'date' for first push
        // no 'log' for now
        values: ['-', 'linear', 'category'],
        dflt: '-',
        
        editType: 'calc',
        _noTemplating: true,
        
    },

    categoryorder: axesAttrs.categoryorder,
    categoryarray: axesAttrs.categoryarray,

    thetaunit: {
        valType: 'enumerated',
        values: ['radians', 'degrees'],
        dflt: 'degrees',
        
        editType: 'calc',
        
    },

    period: {
        valType: 'number',
        editType: 'calc',
        min: 0,
        
        
        // Examples for date axes:
        //
        // - period that equals the timeseries length
        //  http://flowingdata.com/2017/01/24/one-dataset-visualized-25-ways/18-polar-coordinates/
        // - and 1-year periods (focusing on seasonal change0
        //  http://otexts.org/fpp2/seasonal-plots.html
        //  https://blogs.scientificamerican.com/sa-visual/why-are-so-many-babies-born-around-8-00-a-m/
        //  http://www.seasonaladjustment.com/2012/09/05/clock-plot-visualising-seasonality-using-r-and-ggplot2-part-3/
        //  https://i.pinimg.com/736x/49/b9/72/49b972ccb3206a1a6d6f870dac543280.jpg
        //  https://www.climate-lab-book.ac.uk/spirals/
    },

    direction: {
        valType: 'enumerated',
        values: ['counterclockwise', 'clockwise'],
        dflt: 'counterclockwise',
        
        editType: 'calc',
        
    },

    rotation: {
        valType: 'angle',
        editType: 'calc',
        
        
    },

    hoverformat: axesAttrs.hoverformat,

    uirevision: {
        valType: 'any',
        
        editType: 'none',
        
    },

    editType: 'calc'
};

extendFlat(
    angularAxisAttrs,

    // N.B. angular grid lines are straight lines from circle center to outer bound
    // the angular line is circular bounding the polar plot area.
    axisLineGridAttr,

    // N.B. ticksuffix defaults to '°' for angular axes with `thetaunit: 'degrees'`
    axisTickAttrs
);

module.exports = {
    // TODO for x/y/zoom system for paper-based zooming:
    // x: {},
    // y: {},
    // zoom: {},

    domain: domainAttrs({name: 'polar', editType: 'plot'}),

    sector: {
        valType: 'info_array',
        items: [
            {valType: 'number', editType: 'plot'},
            {valType: 'number', editType: 'plot'}
        ],
        dflt: [0, 360],
        
        editType: 'plot',
        
    },
    hole: {
        valType: 'number',
        min: 0,
        max: 1,
        dflt: 0,
        editType: 'plot',
        
        
    },

    bgcolor: {
        valType: 'color',
        
        editType: 'plot',
        dflt: colorAttrs.background,
        
    },

    radialaxis: radialAxisAttrs,
    angularaxis: angularAxisAttrs,

    gridshape: {
        valType: 'enumerated',
        values: ['circular', 'linear'],
        dflt: 'circular',
        
        editType: 'plot',
        
    },

    // TODO maybe?
    // annotations:

    uirevision: {
        valType: 'any',
        
        editType: 'none',
        
    },

    editType: 'calc'
};

},{"../../components/color/attributes":570,"../../lib":694,"../../plot_api/edit_types":725,"../cartesian/layout_attributes":755,"../domain":768}],811:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Color = _dereq_('../../components/color');
var Template = _dereq_('../../plot_api/plot_template');

var handleSubplotDefaults = _dereq_('../subplot_defaults');
var getSubplotData = _dereq_('../get_data').getSubplotData;

var handleTickValueDefaults = _dereq_('../cartesian/tick_value_defaults');
var handleTickMarkDefaults = _dereq_('../cartesian/tick_mark_defaults');
var handleTickLabelDefaults = _dereq_('../cartesian/tick_label_defaults');
var handleCategoryOrderDefaults = _dereq_('../cartesian/category_order_defaults');
var handleLineGridDefaults = _dereq_('../cartesian/line_grid_defaults');
var autoType = _dereq_('../cartesian/axis_autotype');

var layoutAttributes = _dereq_('./layout_attributes');
var setConvert = _dereq_('./set_convert');
var constants = _dereq_('./constants');
var axisNames = constants.axisNames;

function handleDefaults(contIn, contOut, coerce, opts) {
    var bgColor = coerce('bgcolor');
    opts.bgColor = Color.combine(bgColor, opts.paper_bgcolor);

    var sector = coerce('sector');
    coerce('hole');

    // could optimize, subplotData is not always needed!
    var subplotData = getSubplotData(opts.fullData, constants.name, opts.id);
    var layoutOut = opts.layoutOut;
    var axName;

    function coerceAxis(attr, dflt) {
        return coerce(axName + '.' + attr, dflt);
    }

    for(var i = 0; i < axisNames.length; i++) {
        axName = axisNames[i];

        if(!Lib.isPlainObject(contIn[axName])) {
            contIn[axName] = {};
        }

        var axIn = contIn[axName];
        var axOut = Template.newContainer(contOut, axName);
        axOut._id = axOut._name = axName;
        axOut._attr = opts.id + '.' + axName;
        axOut._traceIndices = subplotData.map(function(t) { return t._expandedIndex; });

        var dataAttr = constants.axisName2dataArray[axName];
        var axType = handleAxisTypeDefaults(axIn, axOut, coerceAxis, subplotData, dataAttr);

        handleCategoryOrderDefaults(axIn, axOut, coerceAxis, {
            axData: subplotData,
            dataAttr: dataAttr
        });

        var visible = coerceAxis('visible');
        setConvert(axOut, contOut, layoutOut);

        coerceAxis('uirevision', contOut.uirevision);

        var dfltColor;
        var dfltFontColor;

        if(visible) {
            dfltColor = coerceAxis('color');
            dfltFontColor = (dfltColor === axIn.color) ? dfltColor : opts.font.color;
        }

        // We don't want to make downstream code call ax.setScale,
        // as both radial and angular axes don't have a set domain.
        // Furthermore, angular axes don't have a set range.
        //
        // Mocked domains and ranges are set by the polar subplot instances,
        // but Axes.findExtremes uses the sign of _m to determine which padding value
        // to use.
        //
        // By setting, _m to 1 here, we make Axes.findExtremes think that
        // range[1] > range[0], and vice-versa for `autorange: 'reversed'` below.
        axOut._m = 1;

        switch(axName) {
            case 'radialaxis':
                var autoRange = coerceAxis('autorange', !axOut.isValidRange(axIn.range));
                axIn.autorange = autoRange;
                if(autoRange && (axType === 'linear' || axType === '-')) coerceAxis('rangemode');
                if(autoRange === 'reversed') axOut._m = -1;

                coerceAxis('range');
                axOut.cleanRange('range', {dfltRange: [0, 1]});

                if(visible) {
                    coerceAxis('side');
                    coerceAxis('angle', sector[0]);

                    coerceAxis('title.text');
                    Lib.coerceFont(coerceAxis, 'title.font', {
                        family: opts.font.family,
                        size: Math.round(opts.font.size * 1.2),
                        color: dfltFontColor
                    });
                }
                break;

            case 'angularaxis':
                // We do not support 'true' date angular axes yet,
                // users can still plot dates on angular axes by setting
                // `angularaxis.type: 'category'`.
                //
                // Here, if a date angular axes is detected, we make
                // all its corresponding traces invisible, so that
                // when we do add support for data angular axes, the new
                // behavior won't conflict with existing behavior
                if(axType === 'date') {
                    Lib.log('Polar plots do not support date angular axes yet.');

                    for(var j = 0; j < subplotData.length; j++) {
                        subplotData[j].visible = false;
                    }

                    // turn this into a 'dummy' linear axis so that
                    // the subplot still renders ok
                    axType = axIn.type = axOut.type = 'linear';
                }

                if(axType === 'linear') {
                    coerceAxis('thetaunit');
                } else {
                    coerceAxis('period');
                }

                var direction = coerceAxis('direction');
                coerceAxis('rotation', {counterclockwise: 0, clockwise: 90}[direction]);
                break;
        }

        if(visible) {
            handleTickValueDefaults(axIn, axOut, coerceAxis, axOut.type);
            handleTickLabelDefaults(axIn, axOut, coerceAxis, axOut.type, {
                tickSuffixDflt: axOut.thetaunit === 'degrees' ? '°' : undefined
            });
            handleTickMarkDefaults(axIn, axOut, coerceAxis, {outerTicks: true});

            var showTickLabels = coerceAxis('showticklabels');
            if(showTickLabels) {
                Lib.coerceFont(coerceAxis, 'tickfont', {
                    family: opts.font.family,
                    size: opts.font.size,
                    color: dfltFontColor
                });
                coerceAxis('tickangle');
                coerceAxis('tickformat');
            }

            handleLineGridDefaults(axIn, axOut, coerceAxis, {
                dfltColor: dfltColor,
                bgColor: opts.bgColor,
                // default grid color is darker here (60%, vs cartesian default ~91%)
                // because the grid is not square so the eye needs heavier cues to follow
                blend: 60,
                showLine: true,
                showGrid: true,
                noZeroLine: true,
                attributes: layoutAttributes[axName]
            });

            coerceAxis('layer');
        }

        if(axType !== 'category') coerceAxis('hoverformat');

        axOut._input = axIn;
    }

    if(contOut.angularaxis.type === 'category') {
        coerce('gridshape');
    }
}

function handleAxisTypeDefaults(axIn, axOut, coerce, subplotData, dataAttr) {
    var axType = coerce('type');

    if(axType === '-') {
        var trace;

        for(var i = 0; i < subplotData.length; i++) {
            if(subplotData[i].visible) {
                trace = subplotData[i];
                break;
            }
        }

        if(trace && trace[dataAttr]) {
            axOut.type = autoType(trace[dataAttr], 'gregorian');
        }

        if(axOut.type === '-') {
            axOut.type = 'linear';
        } else {
            // copy autoType back to input axis
            // note that if this object didn't exist
            // in the input layout, we have to put it in
            // this happens in the main supplyDefaults function
            axIn.type = axOut.type;
        }
    }

    return axOut.type;
}

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
    handleSubplotDefaults(layoutIn, layoutOut, fullData, {
        type: constants.name,
        attributes: layoutAttributes,
        handleDefaults: handleDefaults,
        font: layoutOut.font,
        paper_bgcolor: layoutOut.paper_bgcolor,
        fullData: fullData,
        layoutOut: layoutOut
    });
};

},{"../../components/color":571,"../../lib":694,"../../plot_api/plot_template":732,"../cartesian/axis_autotype":743,"../cartesian/category_order_defaults":746,"../cartesian/line_grid_defaults":757,"../cartesian/tick_label_defaults":762,"../cartesian/tick_mark_defaults":763,"../cartesian/tick_value_defaults":764,"../get_data":779,"../subplot_defaults":820,"./constants":807,"./layout_attributes":810,"./set_convert":819}],812:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterAttrs = _dereq_('../../../traces/scatter/attributes');
var scatterMarkerAttrs = scatterAttrs.marker;
var extendFlat = _dereq_('../../../lib/extend').extendFlat;

var deprecationWarning = [
    'Area traces are deprecated!',
    'Please switch to the *barpolar* trace type.'
].join(' ');

module.exports = {
    r: extendFlat({}, scatterAttrs.r, {
        
    }),
    t: extendFlat({}, scatterAttrs.t, {
        
    }),
    marker: {
        color: extendFlat({}, scatterMarkerAttrs.color, {
            
        }),
        size: extendFlat({}, scatterMarkerAttrs.size, {
            
        }),
        symbol: extendFlat({}, scatterMarkerAttrs.symbol, {
            
        }),
        opacity: extendFlat({}, scatterMarkerAttrs.opacity, {
            
        }),
        editType: 'calc'
    }
};

},{"../../../lib/extend":684,"../../../traces/scatter/attributes":1047}],813:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var axesAttrs = _dereq_('../../cartesian/layout_attributes');
var extendFlat = _dereq_('../../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../../plot_api/edit_types').overrideAll;

var deprecationWarning = [
    'Legacy polar charts are deprecated!',
    'Please switch to *polar* subplots.'
].join(' ');

var domainAttr = extendFlat({}, axesAttrs.domain, {
    
});

function mergeAttrs(axisName, nonCommonAttrs) {
    var commonAttrs = {
        showline: {
            valType: 'boolean',
            
            
        },
        showticklabels: {
            valType: 'boolean',
            
            
        },
        tickorientation: {
            valType: 'enumerated',
            values: ['horizontal', 'vertical'],
            
            
        },
        ticklen: {
            valType: 'number',
            min: 0,
            
            
        },
        tickcolor: {
            valType: 'color',
            
            
        },
        ticksuffix: {
            valType: 'string',
            
            
        },
        endpadding: {
            valType: 'number',
            
            description: deprecationWarning,
        },
        visible: {
            valType: 'boolean',
            
            
        }
    };

    return extendFlat({}, nonCommonAttrs, commonAttrs);
}

module.exports = overrideAll({
    radialaxis: mergeAttrs('radial', {
        range: {
            valType: 'info_array',
            
            items: [
                { valType: 'number' },
                { valType: 'number' }
            ],
            
        },
        domain: domainAttr,
        orientation: {
            valType: 'number',
            
            
        }
    }),

    angularaxis: mergeAttrs('angular', {
        range: {
            valType: 'info_array',
            
            items: [
                { valType: 'number', dflt: 0 },
                { valType: 'number', dflt: 360 }
            ],
            
        },
        domain: domainAttr
    }),

    // attributes that appear at layout root
    layout: {
        direction: {
            valType: 'enumerated',
            values: ['clockwise', 'counterclockwise'],
            
            
        },
        orientation: {
            valType: 'angle',
            
            
        }
    }
}, 'plot', 'nested');

},{"../../../lib/extend":684,"../../../plot_api/edit_types":725,"../../cartesian/layout_attributes":755}],814:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Polar = module.exports = _dereq_('./micropolar');

Polar.manager = _dereq_('./micropolar_manager');

},{"./micropolar":815,"./micropolar_manager":816}],815:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

var d3 = _dereq_('d3');
var Lib = _dereq_('../../../lib');
var extendDeepAll = Lib.extendDeepAll;
var MID_SHIFT = _dereq_('../../../constants/alignment').MID_SHIFT;

var µ = module.exports = { version: '0.2.2' };

µ.Axis = function module() {
    var config = {
        data: [],
        layout: {}
    }, inputConfig = {}, liveConfig = {};
    var svg, container, dispatch = d3.dispatch('hover'), radialScale, angularScale;
    var exports = {};
    function render(_container) {
        container = _container || container;
        var data = config.data;
        var axisConfig = config.layout;
        if (typeof container == 'string' || container.nodeName) container = d3.select(container);
        container.datum(data).each(function(_data, _index) {
            var dataOriginal = _data.slice();
            liveConfig = {
                data: µ.util.cloneJson(dataOriginal),
                layout: µ.util.cloneJson(axisConfig)
            };
            var colorIndex = 0;
            dataOriginal.forEach(function(d, i) {
                if (!d.color) {
                    d.color = axisConfig.defaultColorRange[colorIndex];
                    colorIndex = (colorIndex + 1) % axisConfig.defaultColorRange.length;
                }
                if (!d.strokeColor) {
                    d.strokeColor = d.geometry === 'LinePlot' ? d.color : d3.rgb(d.color).darker().toString();
                }
                liveConfig.data[i].color = d.color;
                liveConfig.data[i].strokeColor = d.strokeColor;
                liveConfig.data[i].strokeDash = d.strokeDash;
                liveConfig.data[i].strokeSize = d.strokeSize;
            });
            var data = dataOriginal.filter(function(d, i) {
                var visible = d.visible;
                return typeof visible === 'undefined' || visible === true;
            });
            var isStacked = false;
            var dataWithGroupId = data.map(function(d, i) {
                isStacked = isStacked || typeof d.groupId !== 'undefined';
                return d;
            });
            if (isStacked) {
                var grouped = d3.nest().key(function(d, i) {
                    return typeof d.groupId != 'undefined' ? d.groupId : 'unstacked';
                }).entries(dataWithGroupId);
                var dataYStack = [];
                var stacked = grouped.map(function(d, i) {
                    if (d.key === 'unstacked') return d.values; else {
                        var prevArray = d.values[0].r.map(function(d, i) {
                            return 0;
                        });
                        d.values.forEach(function(d, i, a) {
                            d.yStack = [ prevArray ];
                            dataYStack.push(prevArray);
                            prevArray = µ.util.sumArrays(d.r, prevArray);
                        });
                        return d.values;
                    }
                });
                data = d3.merge(stacked);
            }
            data.forEach(function(d, i) {
                d.t = Array.isArray(d.t[0]) ? d.t : [ d.t ];
                d.r = Array.isArray(d.r[0]) ? d.r : [ d.r ];
            });
            var radius = Math.min(axisConfig.width - axisConfig.margin.left - axisConfig.margin.right, axisConfig.height - axisConfig.margin.top - axisConfig.margin.bottom) / 2;
            radius = Math.max(10, radius);
            var chartCenter = [ axisConfig.margin.left + radius, axisConfig.margin.top + radius ];
            var extent;
            if (isStacked) {
                var highestStackedValue = d3.max(µ.util.sumArrays(µ.util.arrayLast(data).r[0], µ.util.arrayLast(dataYStack)));
                extent = [ 0, highestStackedValue ];
            } else extent = d3.extent(µ.util.flattenArray(data.map(function(d, i) {
                return d.r;
            })));
            if (axisConfig.radialAxis.domain != µ.DATAEXTENT) extent[0] = 0;
            radialScale = d3.scale.linear().domain(axisConfig.radialAxis.domain != µ.DATAEXTENT && axisConfig.radialAxis.domain ? axisConfig.radialAxis.domain : extent).range([ 0, radius ]);
            liveConfig.layout.radialAxis.domain = radialScale.domain();
            var angularDataMerged = µ.util.flattenArray(data.map(function(d, i) {
                return d.t;
            }));
            var isOrdinal = typeof angularDataMerged[0] === 'string';
            var ticks;
            if (isOrdinal) {
                angularDataMerged = µ.util.deduplicate(angularDataMerged);
                ticks = angularDataMerged.slice();
                angularDataMerged = d3.range(angularDataMerged.length);
                data = data.map(function(d, i) {
                    var result = d;
                    d.t = [ angularDataMerged ];
                    if (isStacked) result.yStack = d.yStack;
                    return result;
                });
            }
            var hasOnlyLineOrDotPlot = data.filter(function(d, i) {
                return d.geometry === 'LinePlot' || d.geometry === 'DotPlot';
            }).length === data.length;
            var needsEndSpacing = axisConfig.needsEndSpacing === null ? isOrdinal || !hasOnlyLineOrDotPlot : axisConfig.needsEndSpacing;
            var useProvidedDomain = axisConfig.angularAxis.domain && axisConfig.angularAxis.domain != µ.DATAEXTENT && !isOrdinal && axisConfig.angularAxis.domain[0] >= 0;
            var angularDomain = useProvidedDomain ? axisConfig.angularAxis.domain : d3.extent(angularDataMerged);
            var angularDomainStep = Math.abs(angularDataMerged[1] - angularDataMerged[0]);
            if (hasOnlyLineOrDotPlot && !isOrdinal) angularDomainStep = 0;
            var angularDomainWithPadding = angularDomain.slice();
            if (needsEndSpacing && isOrdinal) angularDomainWithPadding[1] += angularDomainStep;
            var tickCount = axisConfig.angularAxis.ticksCount || 4;
            if (tickCount > 8) tickCount = tickCount / (tickCount / 8) + tickCount % 8;
            if (axisConfig.angularAxis.ticksStep) {
                tickCount = (angularDomainWithPadding[1] - angularDomainWithPadding[0]) / tickCount;
            }
            var angularTicksStep = axisConfig.angularAxis.ticksStep || (angularDomainWithPadding[1] - angularDomainWithPadding[0]) / (tickCount * (axisConfig.minorTicks + 1));
            if (ticks) angularTicksStep = Math.max(Math.round(angularTicksStep), 1);
            if (!angularDomainWithPadding[2]) angularDomainWithPadding[2] = angularTicksStep;
            var angularAxisRange = d3.range.apply(this, angularDomainWithPadding);
            angularAxisRange = angularAxisRange.map(function(d, i) {
                return parseFloat(d.toPrecision(12));
            });
            angularScale = d3.scale.linear().domain(angularDomainWithPadding.slice(0, 2)).range(axisConfig.direction === 'clockwise' ? [ 0, 360 ] : [ 360, 0 ]);
            liveConfig.layout.angularAxis.domain = angularScale.domain();
            liveConfig.layout.angularAxis.endPadding = needsEndSpacing ? angularDomainStep : 0;
            svg = d3.select(this).select('svg.chart-root');
            if (typeof svg === 'undefined' || svg.empty()) {
                var skeleton = "<svg xmlns='http://www.w3.org/2000/svg' class='chart-root'>' + '<g class='outer-group'>' + '<g class='chart-group'>' + '<circle class='background-circle'></circle>' + '<g class='geometry-group'></g>' + '<g class='radial axis-group'>' + '<circle class='outside-circle'></circle>' + '</g>' + '<g class='angular axis-group'></g>' + '<g class='guides-group'><line></line><circle r='0'></circle></g>' + '</g>' + '<g class='legend-group'></g>' + '<g class='tooltips-group'></g>' + '<g class='title-group'><text></text></g>' + '</g>' + '</svg>";
                var doc = new DOMParser().parseFromString(skeleton, 'application/xml');
                var newSvg = this.appendChild(this.ownerDocument.importNode(doc.documentElement, true));
                svg = d3.select(newSvg);
            }
            svg.select('.guides-group').style({
                'pointer-events': 'none'
            });
            svg.select('.angular.axis-group').style({
                'pointer-events': 'none'
            });
            svg.select('.radial.axis-group').style({
                'pointer-events': 'none'
            });
            var chartGroup = svg.select('.chart-group');
            var lineStyle = {
                fill: 'none',
                stroke: axisConfig.tickColor
            };
            var fontStyle = {
                'font-size': axisConfig.font.size,
                'font-family': axisConfig.font.family,
                fill: axisConfig.font.color,
                'text-shadow': [ '-1px 0px', '1px -1px', '-1px 1px', '1px 1px' ].map(function(d, i) {
                    return ' ' + d + ' 0 ' + axisConfig.font.outlineColor;
                }).join(',')
            };
            var legendContainer;
            if (axisConfig.showLegend) {
                legendContainer = svg.select('.legend-group').attr({
                    transform: 'translate(' + [ radius, axisConfig.margin.top ] + ')'
                }).style({
                    display: 'block'
                });
                var elements = data.map(function(d, i) {
                    var datumClone = µ.util.cloneJson(d);
                    datumClone.symbol = d.geometry === 'DotPlot' ? d.dotType || 'circle' : d.geometry != 'LinePlot' ? 'square' : 'line';
                    datumClone.visibleInLegend = typeof d.visibleInLegend === 'undefined' || d.visibleInLegend;
                    datumClone.color = d.geometry === 'LinePlot' ? d.strokeColor : d.color;
                    return datumClone;
                });

                µ.Legend().config({
                    data: data.map(function(d, i) {
                        return d.name || 'Element' + i;
                    }),
                    legendConfig: extendDeepAll({},
                        µ.Legend.defaultConfig().legendConfig,
                        {
                            container: legendContainer,
                            elements: elements,
                            reverseOrder: axisConfig.legend.reverseOrder
                        }
                    )
                })();

                var legendBBox = legendContainer.node().getBBox();
                radius = Math.min(axisConfig.width - legendBBox.width - axisConfig.margin.left - axisConfig.margin.right, axisConfig.height - axisConfig.margin.top - axisConfig.margin.bottom) / 2;
                radius = Math.max(10, radius);
                chartCenter = [ axisConfig.margin.left + radius, axisConfig.margin.top + radius ];
                radialScale.range([ 0, radius ]);
                liveConfig.layout.radialAxis.domain = radialScale.domain();
                legendContainer.attr('transform', 'translate(' + [ chartCenter[0] + radius, chartCenter[1] - radius ] + ')');
            } else {
                legendContainer = svg.select('.legend-group').style({
                    display: 'none'
                });
            }
            svg.attr({
                width: axisConfig.width,
                height: axisConfig.height
            }).style({
                opacity: axisConfig.opacity
            });
            chartGroup.attr('transform', 'translate(' + chartCenter + ')').style({
                cursor: 'crosshair'
            });
            var centeringOffset = [ (axisConfig.width - (axisConfig.margin.left + axisConfig.margin.right + radius * 2 + (legendBBox ? legendBBox.width : 0))) / 2, (axisConfig.height - (axisConfig.margin.top + axisConfig.margin.bottom + radius * 2)) / 2 ];
            centeringOffset[0] = Math.max(0, centeringOffset[0]);
            centeringOffset[1] = Math.max(0, centeringOffset[1]);
            svg.select('.outer-group').attr('transform', 'translate(' + centeringOffset + ')');
            if (axisConfig.title && axisConfig.title.text) {
                var title = svg.select('g.title-group text').style(fontStyle).text(axisConfig.title.text);
                var titleBBox = title.node().getBBox();
                title.attr({
                    x: chartCenter[0] - titleBBox.width / 2,
                    y: chartCenter[1] - radius - 20
                });
            }
            var radialAxis = svg.select('.radial.axis-group');
            if (axisConfig.radialAxis.gridLinesVisible) {
                var gridCircles = radialAxis.selectAll('circle.grid-circle').data(radialScale.ticks(5));
                gridCircles.enter().append('circle').attr({
                    'class': 'grid-circle'
                }).style(lineStyle);
                gridCircles.attr('r', radialScale);
                gridCircles.exit().remove();
            }
            radialAxis.select('circle.outside-circle').attr({
                r: radius
            }).style(lineStyle);
            var backgroundCircle = svg.select('circle.background-circle').attr({
                r: radius
            }).style({
                fill: axisConfig.backgroundColor,
                stroke: axisConfig.stroke
            });
            function currentAngle(d, i) {
                return angularScale(d) % 360 + axisConfig.orientation;
            }
            if (axisConfig.radialAxis.visible) {
                var axis = d3.svg.axis().scale(radialScale).ticks(5).tickSize(5);
                radialAxis.call(axis).attr({
                    transform: 'rotate(' + axisConfig.radialAxis.orientation + ')'
                });
                radialAxis.selectAll('.domain').style(lineStyle);
                radialAxis.selectAll('g>text').text(function(d, i) {
                    return this.textContent + axisConfig.radialAxis.ticksSuffix;
                }).style(fontStyle).style({
                    'text-anchor': 'start'
                }).attr({
                    x: 0,
                    y: 0,
                    dx: 0,
                    dy: 0,
                    transform: function(d, i) {
                        if (axisConfig.radialAxis.tickOrientation === 'horizontal') {
                            return 'rotate(' + -axisConfig.radialAxis.orientation + ') translate(' + [ 0, fontStyle['font-size'] ] + ')';
                        } else return 'translate(' + [ 0, fontStyle['font-size'] ] + ')';
                    }
                });
                radialAxis.selectAll('g>line').style({
                    stroke: 'black'
                });
            }
            var angularAxis = svg.select('.angular.axis-group').selectAll('g.angular-tick').data(angularAxisRange);
            var angularAxisEnter = angularAxis.enter().append('g').classed('angular-tick', true);
            angularAxis.attr({
                transform: function(d, i) {
                    return 'rotate(' + currentAngle(d, i) + ')';
                }
            }).style({
                display: axisConfig.angularAxis.visible ? 'block' : 'none'
            });
            angularAxis.exit().remove();
            angularAxisEnter.append('line').classed('grid-line', true).classed('major', function(d, i) {
                return i % (axisConfig.minorTicks + 1) == 0;
            }).classed('minor', function(d, i) {
                return !(i % (axisConfig.minorTicks + 1) == 0);
            }).style(lineStyle);
            angularAxisEnter.selectAll('.minor').style({
                stroke: axisConfig.minorTickColor
            });
            angularAxis.select('line.grid-line').attr({
                x1: axisConfig.tickLength ? radius - axisConfig.tickLength : 0,
                x2: radius
            }).style({
                display: axisConfig.angularAxis.gridLinesVisible ? 'block' : 'none'
            });
            angularAxisEnter.append('text').classed('axis-text', true).style(fontStyle);
            var ticksText = angularAxis.select('text.axis-text').attr({
                x: radius + axisConfig.labelOffset,
                dy: MID_SHIFT + 'em',
                transform: function(d, i) {
                    var angle = currentAngle(d, i);
                    var rad = radius + axisConfig.labelOffset;
                    var orient = axisConfig.angularAxis.tickOrientation;
                    if (orient == 'horizontal') return 'rotate(' + -angle + ' ' + rad + ' 0)'; else if (orient == 'radial') return angle < 270 && angle > 90 ? 'rotate(180 ' + rad + ' 0)' : null; else return 'rotate(' + (angle <= 180 && angle > 0 ? -90 : 90) + ' ' + rad + ' 0)';
                }
            }).style({
                'text-anchor': 'middle',
                display: axisConfig.angularAxis.labelsVisible ? 'block' : 'none'
            }).text(function(d, i) {
                if (i % (axisConfig.minorTicks + 1) != 0) return '';
                if (ticks) {
                    return ticks[d] + axisConfig.angularAxis.ticksSuffix;
                } else return d + axisConfig.angularAxis.ticksSuffix;
            }).style(fontStyle);
            if (axisConfig.angularAxis.rewriteTicks) ticksText.text(function(d, i) {
                if (i % (axisConfig.minorTicks + 1) != 0) return '';
                return axisConfig.angularAxis.rewriteTicks(this.textContent, i);
            });
            var rightmostTickEndX = d3.max(chartGroup.selectAll('.angular-tick text')[0].map(function(d, i) {
                return d.getCTM().e + d.getBBox().width;
            }));
            legendContainer.attr({
                transform: 'translate(' + [ radius + rightmostTickEndX, axisConfig.margin.top ] + ')'
            });
            var hasGeometry = svg.select('g.geometry-group').selectAll('g').size() > 0;
            var geometryContainer = svg.select('g.geometry-group').selectAll('g.geometry').data(data);
            geometryContainer.enter().append('g').attr({
                'class': function(d, i) {
                    return 'geometry geometry' + i;
                }
            });
            geometryContainer.exit().remove();
            if (data[0] || hasGeometry) {
                var geometryConfigs = [];
                data.forEach(function(d, i) {
                    var geometryConfig = {};
                    geometryConfig.radialScale = radialScale;
                    geometryConfig.angularScale = angularScale;
                    geometryConfig.container = geometryContainer.filter(function(dB, iB) {
                        return iB == i;
                    });
                    geometryConfig.geometry = d.geometry;
                    geometryConfig.orientation = axisConfig.orientation;
                    geometryConfig.direction = axisConfig.direction;
                    geometryConfig.index = i;
                    geometryConfigs.push({
                        data: d,
                        geometryConfig: geometryConfig
                    });
                });
                var geometryConfigsGrouped = d3.nest().key(function(d, i) {
                    return typeof d.data.groupId != 'undefined' || 'unstacked';
                }).entries(geometryConfigs);
                var geometryConfigsGrouped2 = [];
                geometryConfigsGrouped.forEach(function(d, i) {
                    if (d.key === 'unstacked') geometryConfigsGrouped2 = geometryConfigsGrouped2.concat(d.values.map(function(d, i) {
                        return [ d ];
                    })); else geometryConfigsGrouped2.push(d.values);
                });
                geometryConfigsGrouped2.forEach(function(d, i) {
                    var geometry;
                    if (Array.isArray(d)) geometry = d[0].geometryConfig.geometry; else geometry = d.geometryConfig.geometry;
                    var finalGeometryConfig = d.map(function(dB, iB) {
                        return extendDeepAll(µ[geometry].defaultConfig(), dB);
                    });
                    µ[geometry]().config(finalGeometryConfig)();
                });
            }
            var guides = svg.select('.guides-group');
            var tooltipContainer = svg.select('.tooltips-group');
            var angularTooltip = µ.tooltipPanel().config({
                container: tooltipContainer,
                fontSize: 8
            })();
            var radialTooltip = µ.tooltipPanel().config({
                container: tooltipContainer,
                fontSize: 8
            })();
            var geometryTooltip = µ.tooltipPanel().config({
                container: tooltipContainer,
                hasTick: true
            })();
            var angularValue, radialValue;
            if (!isOrdinal) {
                var angularGuideLine = guides.select('line').attr({
                    x1: 0,
                    y1: 0,
                    y2: 0
                }).style({
                    stroke: 'grey',
                    'pointer-events': 'none'
                });
                chartGroup.on('mousemove.angular-guide', function(d, i) {
                    var mouseAngle = µ.util.getMousePos(backgroundCircle).angle;
                    angularGuideLine.attr({
                        x2: -radius,
                        transform: 'rotate(' + mouseAngle + ')'
                    }).style({
                        opacity: .5
                    });
                    var angleWithOriginOffset = (mouseAngle + 180 + 360 - axisConfig.orientation) % 360;
                    angularValue = angularScale.invert(angleWithOriginOffset);
                    var pos = µ.util.convertToCartesian(radius + 12, mouseAngle + 180);
                    angularTooltip.text(µ.util.round(angularValue)).move([ pos[0] + chartCenter[0], pos[1] + chartCenter[1] ]);
                }).on('mouseout.angular-guide', function(d, i) {
                    guides.select('line').style({
                        opacity: 0
                    });
                });
            }
            var angularGuideCircle = guides.select('circle').style({
                stroke: 'grey',
                fill: 'none'
            });
            chartGroup.on('mousemove.radial-guide', function(d, i) {
                var r = µ.util.getMousePos(backgroundCircle).radius;
                angularGuideCircle.attr({
                    r: r
                }).style({
                    opacity: .5
                });
                radialValue = radialScale.invert(µ.util.getMousePos(backgroundCircle).radius);
                var pos = µ.util.convertToCartesian(r, axisConfig.radialAxis.orientation);
                radialTooltip.text(µ.util.round(radialValue)).move([ pos[0] + chartCenter[0], pos[1] + chartCenter[1] ]);
            }).on('mouseout.radial-guide', function(d, i) {
                angularGuideCircle.style({
                    opacity: 0
                });
                geometryTooltip.hide();
                angularTooltip.hide();
                radialTooltip.hide();
            });
            svg.selectAll('.geometry-group .mark').on('mouseover.tooltip', function(d, i) {
                var el = d3.select(this);
                var color = this.style.fill;
                var newColor = 'black';
                var opacity = this.style.opacity || 1;
                el.attr({
                    'data-opacity': opacity
                });
                if (color && color !== 'none') {
                    el.attr({
                        'data-fill': color
                    });
                    newColor = d3.hsl(color).darker().toString();
                    el.style({
                        fill: newColor,
                        opacity: 1
                    });
                    var textData = {
                        t: µ.util.round(d[0]),
                        r: µ.util.round(d[1])
                    };
                    if (isOrdinal) textData.t = ticks[d[0]];
                    var text = 't: ' + textData.t + ', r: ' + textData.r;
                    var bbox = this.getBoundingClientRect();
                    var svgBBox = svg.node().getBoundingClientRect();
                    var pos = [ bbox.left + bbox.width / 2 - centeringOffset[0] - svgBBox.left, bbox.top + bbox.height / 2 - centeringOffset[1] - svgBBox.top ];
                    geometryTooltip.config({
                        color: newColor
                    }).text(text);
                    geometryTooltip.move(pos);
                } else {
                    color = this.style.stroke || 'black';
                    el.attr({
                        'data-stroke': color
                    });
                    newColor = d3.hsl(color).darker().toString();
                    el.style({
                        stroke: newColor,
                        opacity: 1
                    });
                }
            }).on('mousemove.tooltip', function(d, i) {
                if (d3.event.which != 0) return false;
                if (d3.select(this).attr('data-fill')) geometryTooltip.show();
            }).on('mouseout.tooltip', function(d, i) {
                geometryTooltip.hide();
                var el = d3.select(this);
                var fillColor = el.attr('data-fill');
                if (fillColor) el.style({
                    fill: fillColor,
                    opacity: el.attr('data-opacity')
                }); else el.style({
                    stroke: el.attr('data-stroke'),
                    opacity: el.attr('data-opacity')
                });
            });
        });
        return exports;
    }
    exports.render = function(_container) {
        render(_container);
        return this;
    };
    exports.config = function(_x) {
        if (!arguments.length) return config;
        var xClone = µ.util.cloneJson(_x);
        xClone.data.forEach(function(d, i) {
            if (!config.data[i]) config.data[i] = {};
            extendDeepAll(config.data[i], µ.Axis.defaultConfig().data[0]);
            extendDeepAll(config.data[i], d);
        });
        extendDeepAll(config.layout, µ.Axis.defaultConfig().layout);
        extendDeepAll(config.layout, xClone.layout);
        return this;
    };
    exports.getLiveConfig = function() {
        return liveConfig;
    };
    exports.getinputConfig = function() {
        return inputConfig;
    };
    exports.radialScale = function(_x) {
        return radialScale;
    };
    exports.angularScale = function(_x) {
        return angularScale;
    };
    exports.svg = function() {
        return svg;
    };
    d3.rebind(exports, dispatch, 'on');
    return exports;
};

µ.Axis.defaultConfig = function(d, i) {
    var config = {
        data: [ {
            t: [ 1, 2, 3, 4 ],
            r: [ 10, 11, 12, 13 ],
            name: 'Line1',
            geometry: 'LinePlot',
            color: null,
            strokeDash: 'solid',
            strokeColor: null,
            strokeSize: '1',
            visibleInLegend: true,
            opacity: 1
        } ],
        layout: {
            defaultColorRange: d3.scale.category10().range(),
            title: null,
            height: 450,
            width: 500,
            margin: {
                top: 40,
                right: 40,
                bottom: 40,
                left: 40
            },
            font: {
                size: 12,
                color: 'gray',
                outlineColor: 'white',
                family: 'Tahoma, sans-serif'
            },
            direction: 'clockwise',
            orientation: 0,
            labelOffset: 10,
            radialAxis: {
                domain: null,
                orientation: -45,
                ticksSuffix: '',
                visible: true,
                gridLinesVisible: true,
                tickOrientation: 'horizontal',
                rewriteTicks: null
            },
            angularAxis: {
                domain: [ 0, 360 ],
                ticksSuffix: '',
                visible: true,
                gridLinesVisible: true,
                labelsVisible: true,
                tickOrientation: 'horizontal',
                rewriteTicks: null,
                ticksCount: null,
                ticksStep: null
            },
            minorTicks: 0,
            tickLength: null,
            tickColor: 'silver',
            minorTickColor: '#eee',
            backgroundColor: 'none',
            needsEndSpacing: null,
            showLegend: true,
            legend: {
                reverseOrder: false
            },
            opacity: 1
        }
    };
    return config;
};

µ.util = {};

µ.DATAEXTENT = 'dataExtent';

µ.AREA = 'AreaChart';

µ.LINE = 'LinePlot';

µ.DOT = 'DotPlot';

µ.BAR = 'BarChart';

µ.util._override = function(_objA, _objB) {
    for (var x in _objA) if (x in _objB) _objB[x] = _objA[x];
};

µ.util._extend = function(_objA, _objB) {
    for (var x in _objA) _objB[x] = _objA[x];
};

µ.util._rndSnd = function() {
    return Math.random() * 2 - 1 + (Math.random() * 2 - 1) + (Math.random() * 2 - 1);
};

µ.util.dataFromEquation2 = function(_equation, _step) {
    var step = _step || 6;
    var data = d3.range(0, 360 + step, step).map(function(deg, index) {
        var theta = deg * Math.PI / 180;
        var radius = _equation(theta);
        return [ deg, radius ];
    });
    return data;
};

µ.util.dataFromEquation = function(_equation, _step, _name) {
    var step = _step || 6;
    var t = [], r = [];
    d3.range(0, 360 + step, step).forEach(function(deg, index) {
        var theta = deg * Math.PI / 180;
        var radius = _equation(theta);
        t.push(deg);
        r.push(radius);
    });
    var result = {
        t: t,
        r: r
    };
    if (_name) result.name = _name;
    return result;
};

µ.util.ensureArray = function(_val, _count) {
    if (typeof _val === 'undefined') return null;
    var arr = [].concat(_val);
    return d3.range(_count).map(function(d, i) {
        return arr[i] || arr[0];
    });
};

µ.util.fillArrays = function(_obj, _valueNames, _count) {
    _valueNames.forEach(function(d, i) {
        _obj[d] = µ.util.ensureArray(_obj[d], _count);
    });
    return _obj;
};

µ.util.cloneJson = function(json) {
    return JSON.parse(JSON.stringify(json));
};

µ.util.validateKeys = function(obj, keys) {
    if (typeof keys === 'string') keys = keys.split('.');
    var next = keys.shift();
    return obj[next] && (!keys.length || objHasKeys(obj[next], keys));
};

µ.util.sumArrays = function(a, b) {
    return d3.zip(a, b).map(function(d, i) {
        return d3.sum(d);
    });
};

µ.util.arrayLast = function(a) {
    return a[a.length - 1];
};

µ.util.arrayEqual = function(a, b) {
    var i = Math.max(a.length, b.length, 1);
    while (i-- >= 0 && a[i] === b[i]) ;
    return i === -2;
};

µ.util.flattenArray = function(arr) {
    var r = [];
    while (!µ.util.arrayEqual(r, arr)) {
        r = arr;
        arr = [].concat.apply([], arr);
    }
    return arr;
};

µ.util.deduplicate = function(arr) {
    return arr.filter(function(v, i, a) {
        return a.indexOf(v) == i;
    });
};

µ.util.convertToCartesian = function(radius, theta) {
    var thetaRadians = theta * Math.PI / 180;
    var x = radius * Math.cos(thetaRadians);
    var y = radius * Math.sin(thetaRadians);
    return [ x, y ];
};

µ.util.round = function(_value, _digits) {
    var digits = _digits || 2;
    var mult = Math.pow(10, digits);
    return Math.round(_value * mult) / mult;
};

µ.util.getMousePos = function(_referenceElement) {
    var mousePos = d3.mouse(_referenceElement.node());
    var mouseX = mousePos[0];
    var mouseY = mousePos[1];
    var mouse = {};
    mouse.x = mouseX;
    mouse.y = mouseY;
    mouse.pos = mousePos;
    mouse.angle = (Math.atan2(mouseY, mouseX) + Math.PI) * 180 / Math.PI;
    mouse.radius = Math.sqrt(mouseX * mouseX + mouseY * mouseY);
    return mouse;
};

µ.util.duplicatesCount = function(arr) {
    var uniques = {}, val;
    var dups = {};
    for (var i = 0, len = arr.length; i < len; i++) {
        val = arr[i];
        if (val in uniques) {
            uniques[val]++;
            dups[val] = uniques[val];
        } else {
            uniques[val] = 1;
        }
    }
    return dups;
};

µ.util.duplicates = function(arr) {
    return Object.keys(µ.util.duplicatesCount(arr));
};

µ.util.translator = function(obj, sourceBranch, targetBranch, reverse) {
    if (reverse) {
        var targetBranchCopy = targetBranch.slice();
        targetBranch = sourceBranch;
        sourceBranch = targetBranchCopy;
    }
    var value = sourceBranch.reduce(function(previousValue, currentValue) {
        if (typeof previousValue != 'undefined') return previousValue[currentValue];
    }, obj);
    if (typeof value === 'undefined') return;
    sourceBranch.reduce(function(previousValue, currentValue, index) {
        if (typeof previousValue == 'undefined') return;
        if (index === sourceBranch.length - 1) delete previousValue[currentValue];
        return previousValue[currentValue];
    }, obj);
    targetBranch.reduce(function(previousValue, currentValue, index) {
        if (typeof previousValue[currentValue] === 'undefined') previousValue[currentValue] = {};
        if (index === targetBranch.length - 1) previousValue[currentValue] = value;
        return previousValue[currentValue];
    }, obj);
};

µ.PolyChart = function module() {
    var config = [ µ.PolyChart.defaultConfig() ];
    var dispatch = d3.dispatch('hover');
    var dashArray = {
        solid: 'none',
        dash: [ 5, 2 ],
        dot: [ 2, 5 ]
    };
    var colorScale;
    function exports() {
        var geometryConfig = config[0].geometryConfig;
        var container = geometryConfig.container;
        if (typeof container == 'string') container = d3.select(container);
        container.datum(config).each(function(_config, _index) {
            var isStack = !!_config[0].data.yStack;
            var data = _config.map(function(d, i) {
                if (isStack) return d3.zip(d.data.t[0], d.data.r[0], d.data.yStack[0]); else return d3.zip(d.data.t[0], d.data.r[0]);
            });
            var angularScale = geometryConfig.angularScale;
            var domainMin = geometryConfig.radialScale.domain()[0];
            var generator = {};
            generator.bar = function(d, i, pI) {
                var dataConfig = _config[pI].data;
                var h = geometryConfig.radialScale(d[1]) - geometryConfig.radialScale(0);
                var stackTop = geometryConfig.radialScale(d[2] || 0);
                var w = dataConfig.barWidth;
                d3.select(this).attr({
                    'class': 'mark bar',
                    d: 'M' + [ [ h + stackTop, -w / 2 ], [ h + stackTop, w / 2 ], [ stackTop, w / 2 ], [ stackTop, -w / 2 ] ].join('L') + 'Z',
                    transform: function(d, i) {
                        return 'rotate(' + (geometryConfig.orientation + angularScale(d[0])) + ')';
                    }
                });
            };
            generator.dot = function(d, i, pI) {
                var stackedData = d[2] ? [ d[0], d[1] + d[2] ] : d;
                var symbol = d3.svg.symbol().size(_config[pI].data.dotSize).type(_config[pI].data.dotType)(d, i);
                d3.select(this).attr({
                    'class': 'mark dot',
                    d: symbol,
                    transform: function(d, i) {
                        var coord = convertToCartesian(getPolarCoordinates(stackedData));
                        return 'translate(' + [ coord.x, coord.y ] + ')';
                    }
                });
            };
            var line = d3.svg.line.radial().interpolate(_config[0].data.lineInterpolation).radius(function(d) {
                return geometryConfig.radialScale(d[1]);
            }).angle(function(d) {
                return geometryConfig.angularScale(d[0]) * Math.PI / 180;
            });
            generator.line = function(d, i, pI) {
                var lineData = d[2] ? data[pI].map(function(d, i) {
                    return [ d[0], d[1] + d[2] ];
                }) : data[pI];
                d3.select(this).each(generator['dot']).style({
                    opacity: function(dB, iB) {
                        return +_config[pI].data.dotVisible;
                    },
                    fill: markStyle.stroke(d, i, pI)
                }).attr({
                    'class': 'mark dot'
                });
                if (i > 0) return;
                var lineSelection = d3.select(this.parentNode).selectAll('path.line').data([ 0 ]);
                lineSelection.enter().insert('path');
                lineSelection.attr({
                    'class': 'line',
                    d: line(lineData),
                    transform: function(dB, iB) {
                        return 'rotate(' + (geometryConfig.orientation + 90) + ')';
                    },
                    'pointer-events': 'none'
                }).style({
                    fill: function(dB, iB) {
                        return markStyle.fill(d, i, pI);
                    },
                    'fill-opacity': 0,
                    stroke: function(dB, iB) {
                        return markStyle.stroke(d, i, pI);
                    },
                    'stroke-width': function(dB, iB) {
                        return markStyle['stroke-width'](d, i, pI);
                    },
                    'stroke-dasharray': function(dB, iB) {
                        return markStyle['stroke-dasharray'](d, i, pI);
                    },
                    opacity: function(dB, iB) {
                        return markStyle.opacity(d, i, pI);
                    },
                    display: function(dB, iB) {
                        return markStyle.display(d, i, pI);
                    }
                });
            };
            var angularRange = geometryConfig.angularScale.range();
            var triangleAngle = Math.abs(angularRange[1] - angularRange[0]) / data[0].length * Math.PI / 180;
            var arc = d3.svg.arc().startAngle(function(d) {
                return -triangleAngle / 2;
            }).endAngle(function(d) {
                return triangleAngle / 2;
            }).innerRadius(function(d) {
                return geometryConfig.radialScale(domainMin + (d[2] || 0));
            }).outerRadius(function(d) {
                return geometryConfig.radialScale(domainMin + (d[2] || 0)) + geometryConfig.radialScale(d[1]);
            });
            generator.arc = function(d, i, pI) {
                d3.select(this).attr({
                    'class': 'mark arc',
                    d: arc,
                    transform: function(d, i) {
                        return 'rotate(' + (geometryConfig.orientation + angularScale(d[0]) + 90) + ')';
                    }
                });
            };
            var markStyle = {
                fill: function(d, i, pI) {
                    return _config[pI].data.color;
                },
                stroke: function(d, i, pI) {
                    return _config[pI].data.strokeColor;
                },
                'stroke-width': function(d, i, pI) {
                    return _config[pI].data.strokeSize + 'px';
                },
                'stroke-dasharray': function(d, i, pI) {
                    return dashArray[_config[pI].data.strokeDash];
                },
                opacity: function(d, i, pI) {
                    return _config[pI].data.opacity;
                },
                display: function(d, i, pI) {
                    return typeof _config[pI].data.visible === 'undefined' || _config[pI].data.visible ? 'block' : 'none';
                }
            };
            var geometryLayer = d3.select(this).selectAll('g.layer').data(data);
            geometryLayer.enter().append('g').attr({
                'class': 'layer'
            });
            var geometry = geometryLayer.selectAll('path.mark').data(function(d, i) {
                return d;
            });
            geometry.enter().append('path').attr({
                'class': 'mark'
            });
            geometry.style(markStyle).each(generator[geometryConfig.geometryType]);
            geometry.exit().remove();
            geometryLayer.exit().remove();
            function getPolarCoordinates(d, i) {
                var r = geometryConfig.radialScale(d[1]);
                var t = (geometryConfig.angularScale(d[0]) + geometryConfig.orientation) * Math.PI / 180;
                return {
                    r: r,
                    t: t
                };
            }
            function convertToCartesian(polarCoordinates) {
                var x = polarCoordinates.r * Math.cos(polarCoordinates.t);
                var y = polarCoordinates.r * Math.sin(polarCoordinates.t);
                return {
                    x: x,
                    y: y
                };
            }
        });
    }
    exports.config = function(_x) {
        if (!arguments.length) return config;
        _x.forEach(function(d, i) {
            if (!config[i]) config[i] = {};
            extendDeepAll(config[i], µ.PolyChart.defaultConfig());
            extendDeepAll(config[i], d);
        });
        return this;
    };
    exports.getColorScale = function() {
        return colorScale;
    };
    d3.rebind(exports, dispatch, 'on');
    return exports;
};

µ.PolyChart.defaultConfig = function() {
    var config = {
        data: {
            name: 'geom1',
            t: [ [ 1, 2, 3, 4 ] ],
            r: [ [ 1, 2, 3, 4 ] ],
            dotType: 'circle',
            dotSize: 64,
            dotVisible: false,
            barWidth: 20,
            color: '#ffa500',
            strokeSize: 1,
            strokeColor: 'silver',
            strokeDash: 'solid',
            opacity: 1,
            index: 0,
            visible: true,
            visibleInLegend: true
        },
        geometryConfig: {
            geometry: 'LinePlot',
            geometryType: 'arc',
            direction: 'clockwise',
            orientation: 0,
            container: 'body',
            radialScale: null,
            angularScale: null,
            colorScale: d3.scale.category20()
        }
    };
    return config;
};

µ.BarChart = function module() {
    return µ.PolyChart();
};

µ.BarChart.defaultConfig = function() {
    var config = {
        geometryConfig: {
            geometryType: 'bar'
        }
    };
    return config;
};

µ.AreaChart = function module() {
    return µ.PolyChart();
};

µ.AreaChart.defaultConfig = function() {
    var config = {
        geometryConfig: {
            geometryType: 'arc'
        }
    };
    return config;
};

µ.DotPlot = function module() {
    return µ.PolyChart();
};

µ.DotPlot.defaultConfig = function() {
    var config = {
        geometryConfig: {
            geometryType: 'dot',
            dotType: 'circle'
        }
    };
    return config;
};

µ.LinePlot = function module() {
    return µ.PolyChart();
};

µ.LinePlot.defaultConfig = function() {
    var config = {
        geometryConfig: {
            geometryType: 'line'
        }
    };
    return config;
};

µ.Legend = function module() {
    var config = µ.Legend.defaultConfig();
    var dispatch = d3.dispatch('hover');
    function exports() {
        var legendConfig = config.legendConfig;
        var flattenData = config.data.map(function(d, i) {
            return [].concat(d).map(function(dB, iB) {
                var element = extendDeepAll({}, legendConfig.elements[i]);
                element.name = dB;
                element.color = [].concat(legendConfig.elements[i].color)[iB];
                return element;
            });
        });
        var data = d3.merge(flattenData);
        data = data.filter(function(d, i) {
            return legendConfig.elements[i] && (legendConfig.elements[i].visibleInLegend || typeof legendConfig.elements[i].visibleInLegend === 'undefined');
        });
        if (legendConfig.reverseOrder) data = data.reverse();
        var container = legendConfig.container;
        if (typeof container == 'string' || container.nodeName) container = d3.select(container);
        var colors = data.map(function(d, i) {
            return d.color;
        });
        var lineHeight = legendConfig.fontSize;
        var isContinuous = legendConfig.isContinuous == null ? typeof data[0] === 'number' : legendConfig.isContinuous;
        var height = isContinuous ? legendConfig.height : lineHeight * data.length;
        var legendContainerGroup = container.classed('legend-group', true);
        var svg = legendContainerGroup.selectAll('svg').data([ 0 ]);
        var svgEnter = svg.enter().append('svg').attr({
            width: 300,
            height: height + lineHeight,
            xmlns: 'http://www.w3.org/2000/svg',
            'xmlns:xlink': 'http://www.w3.org/1999/xlink',
            version: '1.1'
        });
        svgEnter.append('g').classed('legend-axis', true);
        svgEnter.append('g').classed('legend-marks', true);
        var dataNumbered = d3.range(data.length);
        var colorScale = d3.scale[isContinuous ? 'linear' : 'ordinal']().domain(dataNumbered).range(colors);
        var dataScale = d3.scale[isContinuous ? 'linear' : 'ordinal']().domain(dataNumbered)[isContinuous ? 'range' : 'rangePoints']([ 0, height ]);
        var shapeGenerator = function(_type, _size) {
            var squareSize = _size * 3;
            if (_type === 'line') {
                return 'M' + [ [ -_size / 2, -_size / 12 ], [ _size / 2, -_size / 12 ], [ _size / 2, _size / 12 ], [ -_size / 2, _size / 12 ] ] + 'Z';
            } else if (d3.svg.symbolTypes.indexOf(_type) != -1) return d3.svg.symbol().type(_type).size(squareSize)(); else return d3.svg.symbol().type('square').size(squareSize)();
        };
        if (isContinuous) {
            var gradient = svg.select('.legend-marks').append('defs').append('linearGradient').attr({
                id: 'grad1',
                x1: '0%',
                y1: '0%',
                x2: '0%',
                y2: '100%'
            }).selectAll('stop').data(colors);
            gradient.enter().append('stop');
            gradient.attr({
                offset: function(d, i) {
                    return i / (colors.length - 1) * 100 + '%';
                }
            }).style({
                'stop-color': function(d, i) {
                    return d;
                }
            });
            svg.append('rect').classed('legend-mark', true).attr({
                height: legendConfig.height,
                width: legendConfig.colorBandWidth,
                fill: 'url(#grad1)'
            });
        } else {
            var legendElement = svg.select('.legend-marks').selectAll('path.legend-mark').data(data);
            legendElement.enter().append('path').classed('legend-mark', true);
            legendElement.attr({
                transform: function(d, i) {
                    return 'translate(' + [ lineHeight / 2, dataScale(i) + lineHeight / 2 ] + ')';
                },
                d: function(d, i) {
                    var symbolType = d.symbol;
                    return shapeGenerator(symbolType, lineHeight);
                },
                fill: function(d, i) {
                    return colorScale(i);
                }
            });
            legendElement.exit().remove();
        }
        var legendAxis = d3.svg.axis().scale(dataScale).orient('right');
        var axis = svg.select('g.legend-axis').attr({
            transform: 'translate(' + [ isContinuous ? legendConfig.colorBandWidth : lineHeight, lineHeight / 2 ] + ')'
        }).call(legendAxis);
        axis.selectAll('.domain').style({
            fill: 'none',
            stroke: 'none'
        });
        axis.selectAll('line').style({
            fill: 'none',
            stroke: isContinuous ? legendConfig.textColor : 'none'
        });
        axis.selectAll('text').style({
            fill: legendConfig.textColor,
            'font-size': legendConfig.fontSize
        }).text(function(d, i) {
            return data[i].name;
        });
        return exports;
    }
    exports.config = function(_x) {
        if (!arguments.length) return config;
        extendDeepAll(config, _x);
        return this;
    };
    d3.rebind(exports, dispatch, 'on');
    return exports;
};

µ.Legend.defaultConfig = function(d, i) {
    var config = {
        data: [ 'a', 'b', 'c' ],
        legendConfig: {
            elements: [ {
                symbol: 'line',
                color: 'red'
            }, {
                symbol: 'square',
                color: 'yellow'
            }, {
                symbol: 'diamond',
                color: 'limegreen'
            } ],
            height: 150,
            colorBandWidth: 30,
            fontSize: 12,
            container: 'body',
            isContinuous: null,
            textColor: 'grey',
            reverseOrder: false
        }
    };
    return config;
};

µ.tooltipPanel = function() {
    var tooltipEl, tooltipTextEl, backgroundEl;
    var config = {
        container: null,
        hasTick: false,
        fontSize: 12,
        color: 'white',
        padding: 5
    };
    var id = 'tooltip-' + µ.tooltipPanel.uid++;
    var tickSize = 10;
    var exports = function() {
        tooltipEl = config.container.selectAll('g.' + id).data([ 0 ]);
        var tooltipEnter = tooltipEl.enter().append('g').classed(id, true).style({
            'pointer-events': 'none',
            display: 'none'
        });
        backgroundEl = tooltipEnter.append('path').style({
            fill: 'white',
            'fill-opacity': .9
        }).attr({
            d: 'M0 0'
        });
        tooltipTextEl = tooltipEnter.append('text').attr({
            dx: config.padding + tickSize,
            dy: +config.fontSize * .3
        });
        return exports;
    };
    exports.text = function(_text) {
        var l = d3.hsl(config.color).l;
        var strokeColor = l >= .5 ? '#aaa' : 'white';
        var fillColor = l >= .5 ? 'black' : 'white';
        var text = _text || '';
        tooltipTextEl.style({
            fill: fillColor,
            'font-size': config.fontSize + 'px'
        }).text(text);
        var padding = config.padding;
        var bbox = tooltipTextEl.node().getBBox();
        var boxStyle = {
            fill: config.color,
            stroke: strokeColor,
            'stroke-width': '2px'
        };
        var backGroundW = bbox.width + padding * 2 + tickSize;
        var backGroundH = bbox.height + padding * 2;
        backgroundEl.attr({
            d: 'M' + [ [ tickSize, -backGroundH / 2 ], [ tickSize, -backGroundH / 4 ], [ config.hasTick ? 0 : tickSize, 0 ], [ tickSize, backGroundH / 4 ], [ tickSize, backGroundH / 2 ], [ backGroundW, backGroundH / 2 ], [ backGroundW, -backGroundH / 2 ] ].join('L') + 'Z'
        }).style(boxStyle);
        tooltipEl.attr({
            transform: 'translate(' + [ tickSize, -backGroundH / 2 + padding * 2 ] + ')'
        });
        tooltipEl.style({
            display: 'block'
        });
        return exports;
    };
    exports.move = function(_pos) {
        if (!tooltipEl) return;
        tooltipEl.attr({
            transform: 'translate(' + [ _pos[0], _pos[1] ] + ')'
        }).style({
            display: 'block'
        });
        return exports;
    };
    exports.hide = function() {
        if (!tooltipEl) return;
        tooltipEl.style({
            display: 'none'
        });
        return exports;
    };
    exports.show = function() {
        if (!tooltipEl) return;
        tooltipEl.style({
            display: 'block'
        });
        return exports;
    };
    exports.config = function(_x) {
        extendDeepAll(config, _x);
        return exports;
    };
    return exports;
};

µ.tooltipPanel.uid = 1;

µ.adapter = {};

µ.adapter.plotly = function module() {
    var exports = {};
    exports.convert = function(_inputConfig, reverse) {
        var outputConfig = {};
        if (_inputConfig.data) {
            outputConfig.data = _inputConfig.data.map(function(d, i) {
                var r = extendDeepAll({}, d);
                var toTranslate = [
                    [ r, [ 'marker', 'color' ], [ 'color' ] ],
                    [ r, [ 'marker', 'opacity' ], [ 'opacity' ] ],
                    [ r, [ 'marker', 'line', 'color' ], [ 'strokeColor' ] ],
                    [ r, [ 'marker', 'line', 'dash' ], [ 'strokeDash' ] ],
                    [ r, [ 'marker', 'line', 'width' ], [ 'strokeSize' ] ],
                    [ r, [ 'marker', 'symbol' ], [ 'dotType' ] ],
                    [ r, [ 'marker', 'size' ], [ 'dotSize' ] ],
                    [ r, [ 'marker', 'barWidth' ], [ 'barWidth' ] ],
                    [ r, [ 'line', 'interpolation' ], [ 'lineInterpolation' ] ],
                    [ r, [ 'showlegend' ], [ 'visibleInLegend' ] ]
                ];
                toTranslate.forEach(function(d, i) {
                    µ.util.translator.apply(null, d.concat(reverse));
                });

                if (!reverse) delete r.marker;
                if (reverse) delete r.groupId;
                if (!reverse) {
                    if (r.type === 'scatter') {
                        if (r.mode === 'lines') r.geometry = 'LinePlot'; else if (r.mode === 'markers') r.geometry = 'DotPlot'; else if (r.mode === 'lines+markers') {
                            r.geometry = 'LinePlot';
                            r.dotVisible = true;
                        }
                    } else if (r.type === 'area') r.geometry = 'AreaChart'; else if (r.type === 'bar') r.geometry = 'BarChart';
                    delete r.mode;
                    delete r.type;
                } else {
                    if (r.geometry === 'LinePlot') {
                        r.type = 'scatter';
                        if (r.dotVisible === true) {
                            delete r.dotVisible;
                            r.mode = 'lines+markers';
                        } else r.mode = 'lines';
                    } else if (r.geometry === 'DotPlot') {
                        r.type = 'scatter';
                        r.mode = 'markers';
                    } else if (r.geometry === 'AreaChart') r.type = 'area'; else if (r.geometry === 'BarChart') r.type = 'bar';
                    delete r.geometry;
                }
                return r;
            });
            if (!reverse && _inputConfig.layout && _inputConfig.layout.barmode === 'stack') {
                var duplicates = µ.util.duplicates(outputConfig.data.map(function(d, i) {
                    return d.geometry;
                }));
                outputConfig.data.forEach(function(d, i) {
                    var idx = duplicates.indexOf(d.geometry);
                    if (idx != -1) outputConfig.data[i].groupId = idx;
                });
            }
        }
        if (_inputConfig.layout) {
            var r = extendDeepAll({}, _inputConfig.layout);
            var toTranslate = [
                [ r, [ 'plot_bgcolor' ], [ 'backgroundColor' ] ],
                [ r, [ 'showlegend' ], [ 'showLegend' ] ],
                [ r, [ 'radialaxis' ], [ 'radialAxis' ] ],
                [ r, [ 'angularaxis' ], [ 'angularAxis' ] ],
                [ r.angularaxis, [ 'showline' ], [ 'gridLinesVisible' ] ],
                [ r.angularaxis, [ 'showticklabels' ], [ 'labelsVisible' ] ],
                [ r.angularaxis, [ 'nticks' ], [ 'ticksCount' ] ],
                [ r.angularaxis, [ 'tickorientation' ], [ 'tickOrientation' ] ],
                [ r.angularaxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ],
                [ r.angularaxis, [ 'range' ], [ 'domain' ] ],
                [ r.angularaxis, [ 'endpadding' ], [ 'endPadding' ] ],
                [ r.radialaxis, [ 'showline' ], [ 'gridLinesVisible' ] ],
                [ r.radialaxis, [ 'tickorientation' ], [ 'tickOrientation' ] ],
                [ r.radialaxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ],
                [ r.radialaxis, [ 'range' ], [ 'domain' ] ],
                [ r.angularAxis, [ 'showline' ], [ 'gridLinesVisible' ] ],
                [ r.angularAxis, [ 'showticklabels' ], [ 'labelsVisible' ] ],
                [ r.angularAxis, [ 'nticks' ], [ 'ticksCount' ] ],
                [ r.angularAxis, [ 'tickorientation' ], [ 'tickOrientation' ] ],
                [ r.angularAxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ],
                [ r.angularAxis, [ 'range' ], [ 'domain' ] ],
                [ r.angularAxis, [ 'endpadding' ], [ 'endPadding' ] ],
                [ r.radialAxis, [ 'showline' ], [ 'gridLinesVisible' ] ],
                [ r.radialAxis, [ 'tickorientation' ], [ 'tickOrientation' ] ],
                [ r.radialAxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ],
                [ r.radialAxis, [ 'range' ], [ 'domain' ] ],
                [ r.font, [ 'outlinecolor' ], [ 'outlineColor' ] ],
                [ r.legend, [ 'traceorder' ], [ 'reverseOrder' ] ],
                [ r, [ 'labeloffset' ], [ 'labelOffset' ] ],
                [ r, [ 'defaultcolorrange' ], [ 'defaultColorRange' ] ]
            ];
            toTranslate.forEach(function(d, i) {
                µ.util.translator.apply(null, d.concat(reverse));
            });

            if (!reverse) {
                if (r.angularAxis && typeof r.angularAxis.ticklen !== 'undefined') r.tickLength = r.angularAxis.ticklen;
                if (r.angularAxis && typeof r.angularAxis.tickcolor !== 'undefined') r.tickColor = r.angularAxis.tickcolor;
            } else {
                if (typeof r.tickLength !== 'undefined') {
                    r.angularaxis.ticklen = r.tickLength;
                    delete r.tickLength;
                }
                if (r.tickColor) {
                    r.angularaxis.tickcolor = r.tickColor;
                    delete r.tickColor;
                }
            }
            if (r.legend && typeof r.legend.reverseOrder != 'boolean') {
                r.legend.reverseOrder = r.legend.reverseOrder != 'normal';
            }
            if (r.legend && typeof r.legend.traceorder == 'boolean') {
                r.legend.traceorder = r.legend.traceorder ? 'reversed' : 'normal';
                delete r.legend.reverseOrder;
            }
            if (r.margin && typeof r.margin.t != 'undefined') {
                var source = [ 't', 'r', 'b', 'l', 'pad' ];
                var target = [ 'top', 'right', 'bottom', 'left', 'pad' ];
                var margin = {};
                d3.entries(r.margin).forEach(function(dB, iB) {
                    margin[target[source.indexOf(dB.key)]] = dB.value;
                });
                r.margin = margin;
            }
            if (reverse) {
                delete r.needsEndSpacing;
                delete r.minorTickColor;
                delete r.minorTicks;
                delete r.angularaxis.ticksCount;
                delete r.angularaxis.ticksCount;
                delete r.angularaxis.ticksStep;
                delete r.angularaxis.rewriteTicks;
                delete r.angularaxis.nticks;
                delete r.radialaxis.ticksCount;
                delete r.radialaxis.ticksCount;
                delete r.radialaxis.ticksStep;
                delete r.radialaxis.rewriteTicks;
                delete r.radialaxis.nticks;
            }
            outputConfig.layout = r;
        }
        return outputConfig;
    };
    return exports;
};

},{"../../../constants/alignment":666,"../../../lib":694,"d3":149}],816:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

/* eslint-disable new-cap */

'use strict';

var d3 = _dereq_('d3');
var Lib = _dereq_('../../../lib');
var Color = _dereq_('../../../components/color');

var micropolar = _dereq_('./micropolar');
var UndoManager = _dereq_('./undo_manager');
var extendDeepAll = Lib.extendDeepAll;

var manager = module.exports = {};

manager.framework = function(_gd) {
    var config, previousConfigClone, plot, convertedInput, container;
    var undoManager = new UndoManager();

    function exports(_inputConfig, _container) {
        if(_container) container = _container;
        d3.select(d3.select(container).node().parentNode).selectAll('.svg-container>*:not(.chart-root)').remove();

        config = (!config) ?
            _inputConfig :
            extendDeepAll(config, _inputConfig);

        if(!plot) plot = micropolar.Axis();
        convertedInput = micropolar.adapter.plotly().convert(config);
        plot.config(convertedInput).render(container);
        _gd.data = config.data;
        _gd.layout = config.layout;
        manager.fillLayout(_gd);
        return config;
    }
    exports.isPolar = true;
    exports.svg = function() { return plot.svg(); };
    exports.getConfig = function() { return config; };
    exports.getLiveConfig = function() {
        return micropolar.adapter.plotly().convert(plot.getLiveConfig(), true);
    };
    exports.getLiveScales = function() { return {t: plot.angularScale(), r: plot.radialScale()}; };
    exports.setUndoPoint = function() {
        var that = this;
        var configClone = micropolar.util.cloneJson(config);
        (function(_configClone, _previousConfigClone) {
            undoManager.add({
                undo: function() {
                    if(_previousConfigClone) that(_previousConfigClone);
                },
                redo: function() {
                    that(_configClone);
                }
            });
        })(configClone, previousConfigClone);
        previousConfigClone = micropolar.util.cloneJson(configClone);
    };
    exports.undo = function() { undoManager.undo(); };
    exports.redo = function() { undoManager.redo(); };
    return exports;
};

manager.fillLayout = function(_gd) {
    var container = d3.select(_gd).selectAll('.plot-container');
    var paperDiv = container.selectAll('.svg-container');
    var paper = _gd.framework && _gd.framework.svg && _gd.framework.svg();
    var dflts = {
        width: 800,
        height: 600,
        paper_bgcolor: Color.background,
        _container: container,
        _paperdiv: paperDiv,
        _paper: paper
    };

    _gd._fullLayout = extendDeepAll(dflts, _gd.layout);
};

},{"../../../components/color":571,"../../../lib":694,"./micropolar":815,"./undo_manager":817,"d3":149}],817:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// Modified from https://github.com/ArthurClemens/Javascript-Undo-Manager
// Copyright (c) 2010-2013 Arthur Clemens, arthur@visiblearea.com
module.exports = function UndoManager() {
    var undoCommands = [];
    var index = -1;
    var isExecuting = false;
    var callback;

    function execute(command, action) {
        if(!command) return this;

        isExecuting = true;
        command[action]();
        isExecuting = false;

        return this;
    }

    return {
        add: function(command) {
            if(isExecuting) return this;
            undoCommands.splice(index + 1, undoCommands.length - index);
            undoCommands.push(command);
            index = undoCommands.length - 1;
            return this;
        },
        setCallback: function(callbackFunc) { callback = callbackFunc; },
        undo: function() {
            var command = undoCommands[index];
            if(!command) return this;
            execute(command, 'undo');
            index -= 1;
            if(callback) callback(command.undo);
            return this;
        },
        redo: function() {
            var command = undoCommands[index + 1];
            if(!command) return this;
            execute(command, 'redo');
            index += 1;
            if(callback) callback(command.redo);
            return this;
        },
        clear: function() {
            undoCommands = [];
            index = -1;
        },
        hasUndo: function() { return index !== -1; },
        hasRedo: function() { return index < (undoCommands.length - 1); },
        getCommands: function() { return undoCommands; },
        getPreviousCommand: function() { return undoCommands[index - 1]; },
        getIndex: function() { return index; }
    };
};

},{}],818:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var tinycolor = _dereq_('tinycolor2');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Color = _dereq_('../../components/color');
var Drawing = _dereq_('../../components/drawing');
var Plots = _dereq_('../plots');
var Axes = _dereq_('../../plots/cartesian/axes');
var setConvertCartesian = _dereq_('../cartesian/set_convert');
var setConvertPolar = _dereq_('./set_convert');
var doAutoRange = _dereq_('../cartesian/autorange').doAutoRange;
var dragBox = _dereq_('../cartesian/dragbox');
var dragElement = _dereq_('../../components/dragelement');
var Fx = _dereq_('../../components/fx');
var Titles = _dereq_('../../components/titles');
var prepSelect = _dereq_('../cartesian/select').prepSelect;
var selectOnClick = _dereq_('../cartesian/select').selectOnClick;
var clearSelect = _dereq_('../cartesian/select').clearSelect;
var setCursor = _dereq_('../../lib/setcursor');
var clearGlCanvases = _dereq_('../../lib/clear_gl_canvases');
var redrawReglTraces = _dereq_('../../plot_api/subroutines').redrawReglTraces;

var MID_SHIFT = _dereq_('../../constants/alignment').MID_SHIFT;
var constants = _dereq_('./constants');
var helpers = _dereq_('./helpers');

var _ = Lib._;
var mod = Lib.mod;
var deg2rad = Lib.deg2rad;
var rad2deg = Lib.rad2deg;

function Polar(gd, id) {
    this.id = id;
    this.gd = gd;

    this._hasClipOnAxisFalse = null;
    this.vangles = null;
    this.radialAxisAngle = null;
    this.traceHash = {};
    this.layers = {};
    this.clipPaths = {};
    this.clipIds = {};
    this.viewInitial = {};

    var fullLayout = gd._fullLayout;
    var clipIdBase = 'clip' + fullLayout._uid + id;

    this.clipIds.forTraces = clipIdBase + '-for-traces';
    this.clipPaths.forTraces = fullLayout._clips.append('clipPath')
        .attr('id', this.clipIds.forTraces);
    this.clipPaths.forTraces.append('path');

    this.framework = fullLayout._polarlayer.append('g')
        .attr('class', id);

    // unfortunately, we have to keep track of some axis tick settings
    // as polar subplots do not implement the 'ticks' editType
    this.radialTickLayout = null;
    this.angularTickLayout = null;
}

var proto = Polar.prototype;

module.exports = function createPolar(gd, id) {
    return new Polar(gd, id);
};

proto.plot = function(polarCalcData, fullLayout) {
    var _this = this;
    var polarLayout = fullLayout[_this.id];

    _this._hasClipOnAxisFalse = false;
    for(var i = 0; i < polarCalcData.length; i++) {
        var trace = polarCalcData[i][0].trace;
        if(trace.cliponaxis === false) {
            _this._hasClipOnAxisFalse = true;
            break;
        }
    }

    _this.updateLayers(fullLayout, polarLayout);
    _this.updateLayout(fullLayout, polarLayout);
    Plots.generalUpdatePerTraceModule(_this.gd, _this, polarCalcData, polarLayout);
    _this.updateFx(fullLayout, polarLayout);
};

proto.updateLayers = function(fullLayout, polarLayout) {
    var _this = this;
    var layers = _this.layers;
    var radialLayout = polarLayout.radialaxis;
    var angularLayout = polarLayout.angularaxis;
    var layerNames = constants.layerNames;

    var frontPlotIndex = layerNames.indexOf('frontplot');
    var layerData = layerNames.slice(0, frontPlotIndex);
    var isAngularAxisBelowTraces = angularLayout.layer === 'below traces';
    var isRadialAxisBelowTraces = radialLayout.layer === 'below traces';

    if(isAngularAxisBelowTraces) layerData.push('angular-line');
    if(isRadialAxisBelowTraces) layerData.push('radial-line');
    if(isAngularAxisBelowTraces) layerData.push('angular-axis');
    if(isRadialAxisBelowTraces) layerData.push('radial-axis');

    layerData.push('frontplot');

    if(!isAngularAxisBelowTraces) layerData.push('angular-line');
    if(!isRadialAxisBelowTraces) layerData.push('radial-line');
    if(!isAngularAxisBelowTraces) layerData.push('angular-axis');
    if(!isRadialAxisBelowTraces) layerData.push('radial-axis');

    var join = _this.framework.selectAll('.polarsublayer')
        .data(layerData, String);

    join.enter().append('g')
        .attr('class', function(d) { return 'polarsublayer ' + d;})
        .each(function(d) {
            var sel = layers[d] = d3.select(this);

            switch(d) {
                case 'frontplot':
                    // TODO add option to place in 'backplot' layer??
                    sel.append('g').classed('barlayer', true);
                    sel.append('g').classed('scatterlayer', true);
                    break;
                case 'backplot':
                    sel.append('g').classed('maplayer', true);
                    break;
                case 'plotbg':
                    layers.bg = sel.append('path');
                    break;
                case 'radial-grid':
                    sel.style('fill', 'none');
                    break;
                case 'angular-grid':
                    sel.style('fill', 'none');
                    break;
                case 'radial-line':
                    sel.append('line').style('fill', 'none');
                    break;
                case 'angular-line':
                    sel.append('path').style('fill', 'none');
                    break;
            }
        });

    join.order();
};

/* Polar subplots juggle with 6 'axis objects' (!), these are:
 *
 * - polarLayout.radialaxis (aka radialLayout in this file):
 * - polarLayout.angularaxis (aka angularLayout in this file):
 *   used for data -> calcdata conversions (aka d2c) during the calc step
 *
 * - this.radialAxis
 *   extends polarLayout.radialaxis, adds mocked 'domain' and
 *   few other keys in order to reuse Cartesian doAutoRange and the Axes
 *   drawing routines.
 *   used for calcdata -> geometric conversions (aka c2g) during the plot step
 *   + setGeometry setups ax.c2g for given ax.range
 *   + setScale setups ax._m,ax._b for given ax.range
 *
 * - this.angularAxis
 *   extends polarLayout.angularaxis, adds mocked 'range' and 'domain' and
 *   a few other keys in order to reuse the Axes drawing routines.
 *   used for calcdata -> geometric conversions (aka c2g) during the plot step
 *   + setGeometry setups ax.c2g given ax.rotation, ax.direction & ax._categories,
 *                 and mocks ax.range
 *   + setScale setups ax._m,ax._b with that mocked ax.range
 *
 * - this.xaxis
 * - this.yaxis
 *   setup so that polar traces can reuse plot methods of Cartesian traces
 *   which mostly rely on 2pixel methods (e.g ax.c2p)
 */
proto.updateLayout = function(fullLayout, polarLayout) {
    var _this = this;
    var layers = _this.layers;
    var gs = fullLayout._size;

    // axis attributes
    var radialLayout = polarLayout.radialaxis;
    var angularLayout = polarLayout.angularaxis;
    // layout domains
    var xDomain = polarLayout.domain.x;
    var yDomain = polarLayout.domain.y;
    // offsets from paper edge to layout domain box
    _this.xOffset = gs.l + gs.w * xDomain[0];
    _this.yOffset = gs.t + gs.h * (1 - yDomain[1]);
    // lengths of the layout domain box
    var xLength = _this.xLength = gs.w * (xDomain[1] - xDomain[0]);
    var yLength = _this.yLength = gs.h * (yDomain[1] - yDomain[0]);
    // sector to plot
    var sector = polarLayout.sector;
    _this.sectorInRad = sector.map(deg2rad);
    var sectorBBox = _this.sectorBBox = computeSectorBBox(sector);
    var dxSectorBBox = sectorBBox[2] - sectorBBox[0];
    var dySectorBBox = sectorBBox[3] - sectorBBox[1];
    // aspect ratios
    var arDomain = yLength / xLength;
    var arSector = Math.abs(dySectorBBox / dxSectorBBox);
    // actual lengths and domains of subplot box
    var xLength2, yLength2;
    var xDomain2, yDomain2;
    var gap;
    if(arDomain > arSector) {
        xLength2 = xLength;
        yLength2 = xLength * arSector;
        gap = (yLength - yLength2) / gs.h / 2;
        xDomain2 = [xDomain[0], xDomain[1]];
        yDomain2 = [yDomain[0] + gap, yDomain[1] - gap];
    } else {
        xLength2 = yLength / arSector;
        yLength2 = yLength;
        gap = (xLength - xLength2) / gs.w / 2;
        xDomain2 = [xDomain[0] + gap, xDomain[1] - gap];
        yDomain2 = [yDomain[0], yDomain[1]];
    }
    _this.xLength2 = xLength2;
    _this.yLength2 = yLength2;
    _this.xDomain2 = xDomain2;
    _this.yDomain2 = yDomain2;
    // actual offsets from paper edge to the subplot box top-left corner
    var xOffset2 = _this.xOffset2 = gs.l + gs.w * xDomain2[0];
    var yOffset2 = _this.yOffset2 = gs.t + gs.h * (1 - yDomain2[1]);
    // circle radius in px
    var radius = _this.radius = xLength2 / dxSectorBBox;
    // 'inner' radius in px (when polar.hole is set)
    var innerRadius = _this.innerRadius = polarLayout.hole * radius;
    // circle center position in px
    var cx = _this.cx = xOffset2 - radius * sectorBBox[0];
    var cy = _this.cy = yOffset2 + radius * sectorBBox[3];
    // circle center in the coordinate system of plot area
    var cxx = _this.cxx = cx - xOffset2;
    var cyy = _this.cyy = cy - yOffset2;

    _this.radialAxis = _this.mockAxis(fullLayout, polarLayout, radialLayout, {
        // make this an 'x' axis to make positioning (especially rotation) easier
        _id: 'x',
        // convert to 'x' axis equivalent
        side: {
            counterclockwise: 'top',
            clockwise: 'bottom'
        }[radialLayout.side],
        // spans length 1 radius
        domain: [innerRadius / gs.w, radius / gs.w]
    });

    _this.angularAxis = _this.mockAxis(fullLayout, polarLayout, angularLayout, {
        side: 'right',
        // to get auto nticks right
        domain: [0, Math.PI],
        // don't pass through autorange logic
        autorange: false
    });

    _this.doAutoRange(fullLayout, polarLayout);
    // N.B. this sets _this.vangles
    _this.updateAngularAxis(fullLayout, polarLayout);
    // N.B. this sets _this.radialAxisAngle
    _this.updateRadialAxis(fullLayout, polarLayout);
    _this.updateRadialAxisTitle(fullLayout, polarLayout);

    _this.xaxis = _this.mockCartesianAxis(fullLayout, polarLayout, {
        _id: 'x',
        domain: xDomain2
    });

    _this.yaxis = _this.mockCartesianAxis(fullLayout, polarLayout, {
        _id: 'y',
        domain: yDomain2
    });

    var dPath = _this.pathSubplot();

    _this.clipPaths.forTraces.select('path')
        .attr('d', dPath)
        .attr('transform', strTranslate(cxx, cyy));

    layers.frontplot
        .attr('transform', strTranslate(xOffset2, yOffset2))
        .call(Drawing.setClipUrl, _this._hasClipOnAxisFalse ? null : _this.clipIds.forTraces, _this.gd);

    layers.bg
        .attr('d', dPath)
        .attr('transform', strTranslate(cx, cy))
        .call(Color.fill, polarLayout.bgcolor);
};

proto.mockAxis = function(fullLayout, polarLayout, axLayout, opts) {
    var commonOpts = {
        // to get _boundingBox computation right when showticklabels is false
        anchor: 'free',
        position: 0
    };

    var ax = Lib.extendFlat(commonOpts, axLayout, opts);
    setConvertPolar(ax, polarLayout, fullLayout);
    return ax;
};

proto.mockCartesianAxis = function(fullLayout, polarLayout, opts) {
    var _this = this;
    var axId = opts._id;

    var ax = Lib.extendFlat({type: 'linear'}, opts);
    setConvertCartesian(ax, fullLayout);

    var bboxIndices = {
        x: [0, 2],
        y: [1, 3]
    };

    ax.setRange = function() {
        var sectorBBox = _this.sectorBBox;
        var ind = bboxIndices[axId];
        var rl = _this.radialAxis._rl;
        var drl = (rl[1] - rl[0]) / (1 - polarLayout.hole);
        ax.range = [sectorBBox[ind[0]] * drl, sectorBBox[ind[1]] * drl];
    };

    ax.isPtWithinRange = axId === 'x' ?
        function(d) { return _this.isPtInside(d); } :
        function() { return true; };

    ax.setRange();
    ax.setScale();
    return ax;
};

proto.doAutoRange = function(fullLayout, polarLayout) {
    var gd = this.gd;
    var radialAxis = this.radialAxis;
    var radialLayout = polarLayout.radialaxis;

    radialAxis.setScale();
    doAutoRange(gd, radialAxis);

    var rng = radialAxis.range;
    radialLayout.range = rng.slice();
    radialLayout._input.range = rng.slice();

    radialAxis._rl = [
        radialAxis.r2l(rng[0], null, 'gregorian'),
        radialAxis.r2l(rng[1], null, 'gregorian')
    ];
};

proto.updateRadialAxis = function(fullLayout, polarLayout) {
    var _this = this;
    var gd = _this.gd;
    var layers = _this.layers;
    var radius = _this.radius;
    var innerRadius = _this.innerRadius;
    var cx = _this.cx;
    var cy = _this.cy;
    var radialLayout = polarLayout.radialaxis;
    var a0 = mod(polarLayout.sector[0], 360);
    var ax = _this.radialAxis;
    var hasRoomForIt = innerRadius < radius;

    _this.fillViewInitialKey('radialaxis.angle', radialLayout.angle);
    _this.fillViewInitialKey('radialaxis.range', ax.range.slice());

    ax.setGeometry();

    // rotate auto tick labels by 180 if in quadrant II and III to make them
    // readable from left-to-right
    //
    // TODO try moving deeper in Axes.drawLabels for better results?
    if(ax.tickangle === 'auto' && (a0 > 90 && a0 <= 270)) {
        ax.tickangle = 180;
    }

    // easier to set rotate angle with custom translate function
    var transFn = function(d) {
        return 'translate(' + (ax.l2p(d.x) + innerRadius) + ',0)';
    };

    // set special grid path function
    var gridPathFn = function(d) {
        return _this.pathArc(ax.r2p(d.x) + innerRadius);
    };

    var newTickLayout = strTickLayout(radialLayout);
    if(_this.radialTickLayout !== newTickLayout) {
        layers['radial-axis'].selectAll('.xtick').remove();
        _this.radialTickLayout = newTickLayout;
    }

    if(hasRoomForIt) {
        ax.setScale();

        var vals = Axes.calcTicks(ax);
        var valsClipped = Axes.clipEnds(ax, vals);
        var labelFns = Axes.makeLabelFns(ax, 0);
        var tickSign = Axes.getTickSigns(ax)[2];

        Axes.drawTicks(gd, ax, {
            vals: vals,
            layer: layers['radial-axis'],
            path: Axes.makeTickPath(ax, 0, tickSign),
            transFn: transFn,
            crisp: false
        });

        Axes.drawGrid(gd, ax, {
            vals: valsClipped,
            layer: layers['radial-grid'],
            path: gridPathFn,
            transFn: Lib.noop,
            crisp: false
        });

        Axes.drawLabels(gd, ax, {
            vals: vals,
            layer: layers['radial-axis'],
            transFn: transFn,
            labelXFn: labelFns.labelXFn,
            labelYFn: labelFns.labelYFn,
            labelAnchorFn: labelFns.labelAnchorFn
        });
    }

    // stash 'actual' radial axis angle for drag handlers (in degrees)
    var angle = _this.radialAxisAngle = _this.vangles ?
        rad2deg(snapToVertexAngle(deg2rad(radialLayout.angle), _this.vangles)) :
        radialLayout.angle;

    var tLayer = strTranslate(cx, cy);
    var tLayer2 = tLayer + strRotate(-angle);

    updateElement(
        layers['radial-axis'],
        hasRoomForIt && (radialLayout.showticklabels || radialLayout.ticks),
        {transform: tLayer2}
    );

    updateElement(
        layers['radial-grid'],
        hasRoomForIt && radialLayout.showgrid,
        {transform: tLayer}
    );

    updateElement(
        layers['radial-line'].select('line'),
        hasRoomForIt && radialLayout.showline,
        {
            x1: innerRadius,
            y1: 0,
            x2: radius,
            y2: 0,
            transform: tLayer2
        }
    )
    .attr('stroke-width', radialLayout.linewidth)
    .call(Color.stroke, radialLayout.linecolor);
};

proto.updateRadialAxisTitle = function(fullLayout, polarLayout, _angle) {
    var _this = this;
    var gd = _this.gd;
    var radius = _this.radius;
    var cx = _this.cx;
    var cy = _this.cy;
    var radialLayout = polarLayout.radialaxis;
    var titleClass = _this.id + 'title';

    var angle = _angle !== undefined ? _angle : _this.radialAxisAngle;
    var angleRad = deg2rad(angle);
    var cosa = Math.cos(angleRad);
    var sina = Math.sin(angleRad);

    var pad = 0;

    // Hint: no need to check if there is in fact a title.text set
    // because if plot is editable, pad needs to be calculated anyways
    // to properly show placeholder text when title is empty.
    if(radialLayout.title) {
        var h = Drawing.bBox(_this.layers['radial-axis'].node()).height;
        var ts = radialLayout.title.font.size;
        pad = radialLayout.side === 'counterclockwise' ?
            -h - ts * 0.4 :
            h + ts * 0.8;
    }

    _this.layers['radial-axis-title'] = Titles.draw(gd, titleClass, {
        propContainer: radialLayout,
        propName: _this.id + '.radialaxis.title',
        placeholder: _(gd, 'Click to enter radial axis title'),
        attributes: {
            x: cx + (radius / 2) * cosa + pad * sina,
            y: cy - (radius / 2) * sina + pad * cosa,
            'text-anchor': 'middle'
        },
        transform: {rotate: -angle}
    });
};

proto.updateAngularAxis = function(fullLayout, polarLayout) {
    var _this = this;
    var gd = _this.gd;
    var layers = _this.layers;
    var radius = _this.radius;
    var innerRadius = _this.innerRadius;
    var cx = _this.cx;
    var cy = _this.cy;
    var angularLayout = polarLayout.angularaxis;
    var ax = _this.angularAxis;

    _this.fillViewInitialKey('angularaxis.rotation', angularLayout.rotation);

    ax.setGeometry();
    ax.setScale();

    // 't'ick to 'g'eometric radians is used all over the place here
    var t2g = function(d) { return ax.t2g(d.x); };

    // run rad2deg on tick0 and ditck for thetaunit: 'radians' axes
    if(ax.type === 'linear' && ax.thetaunit === 'radians') {
        ax.tick0 = rad2deg(ax.tick0);
        ax.dtick = rad2deg(ax.dtick);
    }

    var _transFn = function(rad) {
        return strTranslate(cx + radius * Math.cos(rad), cy - radius * Math.sin(rad));
    };

    var transFn = function(d) {
        return _transFn(t2g(d));
    };

    var transFn2 = function(d) {
        var rad = t2g(d);
        return _transFn(rad) + strRotate(-rad2deg(rad));
    };

    var gridPathFn = function(d) {
        var rad = t2g(d);
        var cosRad = Math.cos(rad);
        var sinRad = Math.sin(rad);
        return 'M' + [cx + innerRadius * cosRad, cy - innerRadius * sinRad] +
            'L' + [cx + radius * cosRad, cy - radius * sinRad];
    };

    var out = Axes.makeLabelFns(ax, 0);
    var labelStandoff = out.labelStandoff;
    var labelShift = out.labelShift;
    var offset4fontsize = (angularLayout.ticks !== 'outside' ? 0.7 : 0.5);
    var pad = (ax.linewidth || 1) / 2;

    var labelXFn = function(d) {
        var rad = t2g(d);

        var offset4tx = signSin(rad) === 0 ?
            0 :
            Math.cos(rad) * (labelStandoff + pad + offset4fontsize * d.fontSize);
        var offset4tick = signCos(rad) * (d.dx + labelStandoff + pad);

        return offset4tx + offset4tick;
    };

    var labelYFn = function(d) {
        var rad = t2g(d);

        var offset4tx = d.dy + d.fontSize * MID_SHIFT - labelShift;
        var offset4tick = -Math.sin(rad) * (labelStandoff + pad + offset4fontsize * d.fontSize);

        return offset4tx + offset4tick;
    };

    // TODO maybe switch angle, d ordering ??
    var labelAnchorFn = function(angle, d) {
        var rad = t2g(d);
        return signSin(rad) === 0 ?
            (signCos(rad) > 0 ? 'start' : 'end') :
            'middle';
    };

    var newTickLayout = strTickLayout(angularLayout);
    if(_this.angularTickLayout !== newTickLayout) {
        layers['angular-axis'].selectAll('.' + ax._id + 'tick').remove();
        _this.angularTickLayout = newTickLayout;
    }

    var vals = Axes.calcTicks(ax);

    // angle of polygon vertices in geometric radians (null means circles)
    // TODO what to do when ax.period > ax._categories ??
    var vangles;
    if(polarLayout.gridshape === 'linear') {
        vangles = vals.map(t2g);

        // ax._vals should be always ordered, make them
        // always turn counterclockwise for convenience here
        if(Lib.angleDelta(vangles[0], vangles[1]) < 0) {
            vangles = vangles.slice().reverse();
        }
    } else {
        vangles = null;
    }
    _this.vangles = vangles;

    // Use tickval filter for category axes instead of tweaking
    // the range w.r.t sector, so that sectors that cross 360 can
    // show all their ticks.
    if(ax.type === 'category') {
        vals = vals.filter(function(d) {
            return Lib.isAngleInsideSector(t2g(d), _this.sectorInRad);
        });
    }

    if(ax.visible) {
        var tickSign = ax.ticks === 'inside' ? -1 : 1;

        Axes.drawTicks(gd, ax, {
            vals: vals,
            layer: layers['angular-axis'],
            path: 'M' + (tickSign * pad) + ',0h' + (tickSign * ax.ticklen),
            transFn: transFn2,
            crisp: false
        });

        Axes.drawGrid(gd, ax, {
            vals: vals,
            layer: layers['angular-grid'],
            path: gridPathFn,
            transFn: Lib.noop,
            crisp: false
        });

        Axes.drawLabels(gd, ax, {
            vals: vals,
            layer: layers['angular-axis'],
            repositionOnUpdate: true,
            transFn: transFn,
            labelXFn: labelXFn,
            labelYFn: labelYFn,
            labelAnchorFn: labelAnchorFn
        });
    }

    // TODO maybe two arcs is better here?
    // maybe split style attributes between inner and outer angular axes?

    updateElement(layers['angular-line'].select('path'), angularLayout.showline, {
        d: _this.pathSubplot(),
        transform: strTranslate(cx, cy)
    })
    .attr('stroke-width', angularLayout.linewidth)
    .call(Color.stroke, angularLayout.linecolor);
};

proto.updateFx = function(fullLayout, polarLayout) {
    if(!this.gd._context.staticPlot) {
        this.updateAngularDrag(fullLayout);
        this.updateRadialDrag(fullLayout, polarLayout, 0);
        this.updateRadialDrag(fullLayout, polarLayout, 1);
        this.updateMainDrag(fullLayout);
    }
};

proto.updateMainDrag = function(fullLayout) {
    var _this = this;
    var gd = _this.gd;
    var layers = _this.layers;
    var zoomlayer = fullLayout._zoomlayer;
    var MINZOOM = constants.MINZOOM;
    var OFFEDGE = constants.OFFEDGE;
    var radius = _this.radius;
    var innerRadius = _this.innerRadius;
    var cx = _this.cx;
    var cy = _this.cy;
    var cxx = _this.cxx;
    var cyy = _this.cyy;
    var sectorInRad = _this.sectorInRad;
    var vangles = _this.vangles;
    var radialAxis = _this.radialAxis;
    var clampTiny = helpers.clampTiny;
    var findXYatLength = helpers.findXYatLength;
    var findEnclosingVertexAngles = helpers.findEnclosingVertexAngles;
    var chw = constants.cornerHalfWidth;
    var chl = constants.cornerLen / 2;

    var mainDrag = dragBox.makeDragger(layers, 'path', 'maindrag', 'crosshair');

    d3.select(mainDrag)
        .attr('d', _this.pathSubplot())
        .attr('transform', strTranslate(cx, cy));

    var dragOpts = {
        element: mainDrag,
        gd: gd,
        subplot: _this.id,
        plotinfo: {
            id: _this.id,
            xaxis: _this.xaxis,
            yaxis: _this.yaxis
        },
        xaxes: [_this.xaxis],
        yaxes: [_this.yaxis]
    };

    // mouse px position at drag start (0), move (1)
    var x0, y0;
    // radial distance from circle center at drag start (0), move (1)
    var r0, r1;
    // zoombox persistent quantities
    var path0, dimmed, lum;
    // zoombox, corners elements
    var zb, corners;

    function norm(x, y) {
        return Math.sqrt(x * x + y * y);
    }

    function xy2r(x, y) {
        return norm(x - cxx, y - cyy);
    }

    function xy2a(x, y) {
        return Math.atan2(cyy - y, x - cxx);
    }

    function ra2xy(r, a) {
        return [r * Math.cos(a), r * Math.sin(-a)];
    }

    function pathCorner(r, a) {
        if(r === 0) return _this.pathSector(2 * chw);

        var da = chl / r;
        var am = a - da;
        var ap = a + da;
        var rb = Math.max(0, Math.min(r, radius));
        var rm = rb - chw;
        var rp = rb + chw;

        return 'M' + ra2xy(rm, am) +
            'A' + [rm, rm] + ' 0,0,0 ' + ra2xy(rm, ap) +
            'L' + ra2xy(rp, ap) +
            'A' + [rp, rp] + ' 0,0,1 ' + ra2xy(rp, am) +
            'Z';
    }

    // (x,y) is the pt at middle of the va0 <-> va1 edge
    //
    // ... we could eventually add another mode for cursor
    // angles 'close to' enough to a particular vertex.
    function pathCornerForPolygons(r, va0, va1) {
        if(r === 0) return _this.pathSector(2 * chw);

        var xy0 = ra2xy(r, va0);
        var xy1 = ra2xy(r, va1);
        var x = clampTiny((xy0[0] + xy1[0]) / 2);
        var y = clampTiny((xy0[1] + xy1[1]) / 2);
        var innerPts, outerPts;

        if(x && y) {
            var m = y / x;
            var mperp = -1 / m;
            var midPts = findXYatLength(chw, m, x, y);
            innerPts = findXYatLength(chl, mperp, midPts[0][0], midPts[0][1]);
            outerPts = findXYatLength(chl, mperp, midPts[1][0], midPts[1][1]);
        } else {
            var dx, dy;
            if(y) {
                // horizontal handles
                dx = chl;
                dy = chw;
            } else {
                // vertical handles
                dx = chw;
                dy = chl;
            }
            innerPts = [[x - dx, y - dy], [x + dx, y - dy]];
            outerPts = [[x - dx, y + dy], [x + dx, y + dy]];
        }

        return 'M' + innerPts.join('L') +
            'L' + outerPts.reverse().join('L') + 'Z';
    }

    function zoomPrep() {
        r0 = null;
        r1 = null;
        path0 = _this.pathSubplot();
        dimmed = false;

        var polarLayoutNow = gd._fullLayout[_this.id];
        lum = tinycolor(polarLayoutNow.bgcolor).getLuminance();

        zb = dragBox.makeZoombox(zoomlayer, lum, cx, cy, path0);
        zb.attr('fill-rule', 'evenodd');
        corners = dragBox.makeCorners(zoomlayer, cx, cy);
        clearSelect(zoomlayer);
    }

    // N.B. this sets scoped 'r0' and 'r1'
    // return true if 'valid' zoom distance, false otherwise
    function clampAndSetR0R1(rr0, rr1) {
        rr1 = Math.max(Math.min(rr1, radius), innerRadius);

        // starting or ending drag near center (outer edge),
        // clamps radial distance at origin (at r=radius)
        if(rr0 < OFFEDGE) rr0 = 0;
        else if((radius - rr0) < OFFEDGE) rr0 = radius;
        else if(rr1 < OFFEDGE) rr1 = 0;
        else if((radius - rr1) < OFFEDGE) rr1 = radius;

        // make sure r0 < r1,
        // to get correct fill pattern in path1 below
        if(Math.abs(rr1 - rr0) > MINZOOM) {
            if(rr0 < rr1) {
                r0 = rr0;
                r1 = rr1;
            } else {
                r0 = rr1;
                r1 = rr0;
            }
            return true;
        } else {
            r0 = null;
            r1 = null;
            return false;
        }
    }

    function applyZoomMove(path1, cpath) {
        path1 = path1 || path0;
        cpath = cpath || 'M0,0Z';

        zb.attr('d', path1);
        corners.attr('d', cpath);
        dragBox.transitionZoombox(zb, corners, dimmed, lum);
        dimmed = true;
    }

    function zoomMove(dx, dy) {
        var x1 = x0 + dx;
        var y1 = y0 + dy;
        var rr0 = xy2r(x0, y0);
        var rr1 = Math.min(xy2r(x1, y1), radius);
        var a0 = xy2a(x0, y0);
        var path1;
        var cpath;

        if(clampAndSetR0R1(rr0, rr1)) {
            path1 = path0 + _this.pathSector(r1);
            if(r0) path1 += _this.pathSector(r0);
            // keep 'starting' angle
            cpath = pathCorner(r0, a0) + pathCorner(r1, a0);
        }
        applyZoomMove(path1, cpath);
    }

    function findPolygonRadius(x, y, va0, va1) {
        var xy = helpers.findIntersectionXY(va0, va1, va0, [x - cxx, cyy - y]);
        return norm(xy[0], xy[1]);
    }

    function zoomMoveForPolygons(dx, dy) {
        var x1 = x0 + dx;
        var y1 = y0 + dy;
        var a0 = xy2a(x0, y0);
        var a1 = xy2a(x1, y1);
        var vangles0 = findEnclosingVertexAngles(a0, vangles);
        var vangles1 = findEnclosingVertexAngles(a1, vangles);
        var rr0 = findPolygonRadius(x0, y0, vangles0[0], vangles0[1]);
        var rr1 = Math.min(findPolygonRadius(x1, y1, vangles1[0], vangles1[1]), radius);
        var path1;
        var cpath;

        if(clampAndSetR0R1(rr0, rr1)) {
            path1 = path0 + _this.pathSector(r1);
            if(r0) path1 += _this.pathSector(r0);
            // keep 'starting' angle here too
            cpath = [
                pathCornerForPolygons(r0, vangles0[0], vangles0[1]),
                pathCornerForPolygons(r1, vangles0[0], vangles0[1])
            ].join(' ');
        }
        applyZoomMove(path1, cpath);
    }

    function zoomDone() {
        dragBox.removeZoombox(gd);

        if(r0 === null || r1 === null) return;

        dragBox.showDoubleClickNotifier(gd);

        var rl = radialAxis._rl;
        var m = (rl[1] - rl[0]) / (1 - innerRadius / radius) / radius;
        var newRng = [
            rl[0] + (r0 - innerRadius) * m,
            rl[0] + (r1 - innerRadius) * m
        ];
        Registry.call('_guiRelayout', gd, _this.id + '.radialaxis.range', newRng);
    }

    function zoomClick(numClicks, evt) {
        var clickMode = gd._fullLayout.clickmode;

        dragBox.removeZoombox(gd);

        // TODO double once vs twice logic (autorange vs fixed range)
        if(numClicks === 2) {
            var updateObj = {};
            for(var k in _this.viewInitial) {
                updateObj[_this.id + '.' + k] = _this.viewInitial[k];
            }

            gd.emit('plotly_doubleclick', null);
            Registry.call('_guiRelayout', gd, updateObj);
        }

        if(clickMode.indexOf('select') > -1 && numClicks === 1) {
            selectOnClick(evt, gd, [_this.xaxis], [_this.yaxis], _this.id, dragOpts);
        }

        if(clickMode.indexOf('event') > -1) {
            Fx.click(gd, evt, _this.id);
        }
    }

    dragOpts.prepFn = function(evt, startX, startY) {
        var dragModeNow = gd._fullLayout.dragmode;

        var bbox = mainDrag.getBoundingClientRect();
        x0 = startX - bbox.left;
        y0 = startY - bbox.top;

        // need to offset x/y as bbox center does not
        // match origin for asymmetric polygons
        if(vangles) {
            var offset = helpers.findPolygonOffset(radius, sectorInRad[0], sectorInRad[1], vangles);
            x0 += cxx + offset[0];
            y0 += cyy + offset[1];
        }

        switch(dragModeNow) {
            case 'zoom':
                if(vangles) {
                    dragOpts.moveFn = zoomMoveForPolygons;
                } else {
                    dragOpts.moveFn = zoomMove;
                }
                dragOpts.clickFn = zoomClick;
                dragOpts.doneFn = zoomDone;
                zoomPrep(evt, startX, startY);
                break;
            case 'select':
            case 'lasso':
                prepSelect(evt, startX, startY, dragOpts, dragModeNow);
                break;
        }
    };

    mainDrag.onmousemove = function(evt) {
        Fx.hover(gd, evt, _this.id);
        gd._fullLayout._lasthover = mainDrag;
        gd._fullLayout._hoversubplot = _this.id;
    };

    mainDrag.onmouseout = function(evt) {
        if(gd._dragging) return;
        dragElement.unhover(gd, evt);
    };

    dragElement.init(dragOpts);
};

proto.updateRadialDrag = function(fullLayout, polarLayout, rngIndex) {
    var _this = this;
    var gd = _this.gd;
    var layers = _this.layers;
    var radius = _this.radius;
    var innerRadius = _this.innerRadius;
    var cx = _this.cx;
    var cy = _this.cy;
    var radialAxis = _this.radialAxis;
    var bl = constants.radialDragBoxSize;
    var bl2 = bl / 2;

    if(!radialAxis.visible) return;

    var angle0 = deg2rad(_this.radialAxisAngle);
    var rl = radialAxis._rl;
    var rl0 = rl[0];
    var rl1 = rl[1];
    var rbase = rl[rngIndex];
    var m = 0.75 * (rl[1] - rl[0]) / (1 - polarLayout.hole) / radius;

    var tx, ty, className;
    if(rngIndex) {
        tx = cx + (radius + bl2) * Math.cos(angle0);
        ty = cy - (radius + bl2) * Math.sin(angle0);
        className = 'radialdrag';
    } else {
        // the 'inner' box can get called:
        // - when polar.hole>0
        // - when polar.sector isn't a full circle
        // otherwise it is hidden behind the main drag.
        tx = cx + (innerRadius - bl2) * Math.cos(angle0);
        ty = cy - (innerRadius - bl2) * Math.sin(angle0);
        className = 'radialdrag-inner';
    }

    var radialDrag = dragBox.makeRectDragger(layers, className, 'crosshair', -bl2, -bl2, bl, bl);
    var dragOpts = {element: radialDrag, gd: gd};

    updateElement(d3.select(radialDrag), radialAxis.visible && innerRadius < radius, {
        transform: strTranslate(tx, ty)
    });

    // move function (either rotate or re-range flavor)
    var moveFn2;
    // rotate angle on done
    var angle1;
    // re-range range[1] (or range[0]) on done
    var rprime;

    function moveFn(dx, dy) {
        if(moveFn2) {
            moveFn2(dx, dy);
        } else {
            var dvec = [dx, -dy];
            var rvec = [Math.cos(angle0), Math.sin(angle0)];
            var comp = Math.abs(Lib.dot(dvec, rvec) / Math.sqrt(Lib.dot(dvec, dvec)));

            // mostly perpendicular motions rotate,
            // mostly parallel motions re-range
            if(!isNaN(comp)) {
                moveFn2 = comp < 0.5 ? rotateMove : rerangeMove;
            }
        }
    }

    function doneFn() {
        if(angle1 !== null) {
            Registry.call('_guiRelayout', gd, _this.id + '.radialaxis.angle', angle1);
        } else if(rprime !== null) {
            Registry.call('_guiRelayout', gd, _this.id + '.radialaxis.range[' + rngIndex + ']', rprime);
        }
    }

    function rotateMove(dx, dy) {
        // disable for inner drag boxes
        if(rngIndex === 0) return;

        var x1 = tx + dx;
        var y1 = ty + dy;

        angle1 = Math.atan2(cy - y1, x1 - cx);
        if(_this.vangles) angle1 = snapToVertexAngle(angle1, _this.vangles);
        angle1 = rad2deg(angle1);

        var transform = strTranslate(cx, cy) + strRotate(-angle1);
        layers['radial-axis'].attr('transform', transform);
        layers['radial-line'].select('line').attr('transform', transform);

        var fullLayoutNow = _this.gd._fullLayout;
        var polarLayoutNow = fullLayoutNow[_this.id];
        _this.updateRadialAxisTitle(fullLayoutNow, polarLayoutNow, angle1);
    }

    function rerangeMove(dx, dy) {
        // project (dx, dy) unto unit radial axis vector
        var dr = Lib.dot([dx, -dy], [Math.cos(angle0), Math.sin(angle0)]);
        rprime = rbase - m * dr;

        // make sure rprime does not change the range[0] -> range[1] sign
        if((m > 0) !== (rngIndex ? rprime > rl0 : rprime < rl1)) {
            rprime = null;
            return;
        }

        var fullLayoutNow = gd._fullLayout;
        var polarLayoutNow = fullLayoutNow[_this.id];

        // update radial range -> update c2g -> update _m,_b
        radialAxis.range[rngIndex] = rprime;
        radialAxis._rl[rngIndex] = rprime;
        _this.updateRadialAxis(fullLayoutNow, polarLayoutNow);

        _this.xaxis.setRange();
        _this.xaxis.setScale();
        _this.yaxis.setRange();
        _this.yaxis.setScale();

        var hasRegl = false;

        for(var traceType in _this.traceHash) {
            var moduleCalcData = _this.traceHash[traceType];
            var moduleCalcDataVisible = Lib.filterVisible(moduleCalcData);
            var _module = moduleCalcData[0][0].trace._module;
            _module.plot(gd, _this, moduleCalcDataVisible, polarLayoutNow);
            if(Registry.traceIs(traceType, 'gl') && moduleCalcDataVisible.length) hasRegl = true;
        }

        if(hasRegl) {
            clearGlCanvases(gd);
            redrawReglTraces(gd);
        }
    }

    dragOpts.prepFn = function() {
        moveFn2 = null;
        angle1 = null;
        rprime = null;

        dragOpts.moveFn = moveFn;
        dragOpts.doneFn = doneFn;

        clearSelect(fullLayout._zoomlayer);
    };

    dragOpts.clampFn = function(dx, dy) {
        if(Math.sqrt(dx * dx + dy * dy) < constants.MINDRAG) {
            dx = 0;
            dy = 0;
        }
        return [dx, dy];
    };

    dragElement.init(dragOpts);
};

proto.updateAngularDrag = function(fullLayout) {
    var _this = this;
    var gd = _this.gd;
    var layers = _this.layers;
    var radius = _this.radius;
    var angularAxis = _this.angularAxis;
    var cx = _this.cx;
    var cy = _this.cy;
    var cxx = _this.cxx;
    var cyy = _this.cyy;
    var dbs = constants.angularDragBoxSize;

    var angularDrag = dragBox.makeDragger(layers, 'path', 'angulardrag', 'move');
    var dragOpts = {element: angularDrag, gd: gd};

    d3.select(angularDrag)
        .attr('d', _this.pathAnnulus(radius, radius + dbs))
        .attr('transform', strTranslate(cx, cy))
        .call(setCursor, 'move');

    function xy2a(x, y) {
        return Math.atan2(cyy + dbs - y, x - cxx - dbs);
    }

    // scatter trace, points and textpoints selections
    var scatterTraces = layers.frontplot.select('.scatterlayer').selectAll('.trace');
    var scatterPoints = scatterTraces.selectAll('.point');
    var scatterTextPoints = scatterTraces.selectAll('.textpoint');

    // mouse px position at drag start (0), move (1)
    var x0, y0;
    // angular axis angle rotation at drag start (0), move (1)
    var rot0, rot1;
    // induced radial axis rotation (only used on polygon grids)
    var rrot1;
    // angle about circle center at drag start
    var a0;

    function moveFn(dx, dy) {
        var fullLayoutNow = _this.gd._fullLayout;
        var polarLayoutNow = fullLayoutNow[_this.id];

        var x1 = x0 + dx;
        var y1 = y0 + dy;
        var a1 = xy2a(x1, y1);
        var da = rad2deg(a1 - a0);
        rot1 = rot0 + da;

        layers.frontplot.attr('transform',
            strTranslate(_this.xOffset2, _this.yOffset2) + strRotate([-da, cxx, cyy])
        );

        if(_this.vangles) {
            rrot1 = _this.radialAxisAngle + da;

            var trans = strTranslate(cx, cy) + strRotate(-da);
            var trans2 = strTranslate(cx, cy) + strRotate(-rrot1);

            layers.bg.attr('transform', trans);
            layers['radial-grid'].attr('transform', trans);
            layers['radial-axis'].attr('transform', trans2);
            layers['radial-line'].select('line').attr('transform', trans2);
            _this.updateRadialAxisTitle(fullLayoutNow, polarLayoutNow, rrot1);
        } else {
            _this.clipPaths.forTraces.select('path').attr('transform',
                strTranslate(cxx, cyy) + strRotate(da)
            );
        }

        // 'un-rotate' marker and text points
        scatterPoints.each(function() {
            var sel = d3.select(this);
            var xy = Drawing.getTranslate(sel);
            sel.attr('transform', strTranslate(xy.x, xy.y) + strRotate([da]));
        });
        scatterTextPoints.each(function() {
            var sel = d3.select(this);
            var tx = sel.select('text');
            var xy = Drawing.getTranslate(sel);
            // N.B rotate -> translate ordering matters
            sel.attr('transform', strRotate([da, tx.attr('x'), tx.attr('y')]) + strTranslate(xy.x, xy.y));
        });

        // update rotation -> range -> _m,_b
        angularAxis.rotation = Lib.modHalf(rot1, 360);
        _this.updateAngularAxis(fullLayoutNow, polarLayoutNow);

        if(_this._hasClipOnAxisFalse && !Lib.isFullCircle(_this.sectorInRad)) {
            scatterTraces.call(Drawing.hideOutsideRangePoints, _this);
        }

        var hasRegl = false;

        for(var traceType in _this.traceHash) {
            if(Registry.traceIs(traceType, 'gl')) {
                var moduleCalcData = _this.traceHash[traceType];
                var moduleCalcDataVisible = Lib.filterVisible(moduleCalcData);
                var _module = moduleCalcData[0][0].trace._module;
                _module.plot(gd, _this, moduleCalcDataVisible, polarLayoutNow);
                if(moduleCalcDataVisible.length) hasRegl = true;
            }
        }

        if(hasRegl) {
            clearGlCanvases(gd);
            redrawReglTraces(gd);
        }
    }

    function doneFn() {
        scatterTextPoints.select('text').attr('transform', null);

        var updateObj = {};
        updateObj[_this.id + '.angularaxis.rotation'] = rot1;

        if(_this.vangles) {
            updateObj[_this.id + '.radialaxis.angle'] = rrot1;
        }

        Registry.call('_guiRelayout', gd, updateObj);
    }

    dragOpts.prepFn = function(evt, startX, startY) {
        var polarLayoutNow = fullLayout[_this.id];
        rot0 = polarLayoutNow.angularaxis.rotation;

        var bbox = angularDrag.getBoundingClientRect();
        x0 = startX - bbox.left;
        y0 = startY - bbox.top;
        a0 = xy2a(x0, y0);

        dragOpts.moveFn = moveFn;
        dragOpts.doneFn = doneFn;

        clearSelect(fullLayout._zoomlayer);
    };

    // I don't what we should do in this case, skip we now
    if(_this.vangles && !Lib.isFullCircle(_this.sectorInRad)) {
        dragOpts.prepFn = Lib.noop;
        setCursor(d3.select(angularDrag), null);
    }

    dragElement.init(dragOpts);
};

proto.isPtInside = function(d) {
    var sectorInRad = this.sectorInRad;
    var vangles = this.vangles;
    var thetag = this.angularAxis.c2g(d.theta);
    var radialAxis = this.radialAxis;
    var r = radialAxis.c2l(d.r);
    var rl = radialAxis._rl;

    var fn = vangles ? helpers.isPtInsidePolygon : Lib.isPtInsideSector;
    return fn(r, thetag, rl, sectorInRad, vangles);
};

proto.pathArc = function(r) {
    var sectorInRad = this.sectorInRad;
    var vangles = this.vangles;
    var fn = vangles ? helpers.pathPolygon : Lib.pathArc;
    return fn(r, sectorInRad[0], sectorInRad[1], vangles);
};

proto.pathSector = function(r) {
    var sectorInRad = this.sectorInRad;
    var vangles = this.vangles;
    var fn = vangles ? helpers.pathPolygon : Lib.pathSector;
    return fn(r, sectorInRad[0], sectorInRad[1], vangles);
};

proto.pathAnnulus = function(r0, r1) {
    var sectorInRad = this.sectorInRad;
    var vangles = this.vangles;
    var fn = vangles ? helpers.pathPolygonAnnulus : Lib.pathAnnulus;
    return fn(r0, r1, sectorInRad[0], sectorInRad[1], vangles);
};

proto.pathSubplot = function() {
    var r0 = this.innerRadius;
    var r1 = this.radius;
    return r0 ? this.pathAnnulus(r0, r1) : this.pathSector(r1);
};

proto.fillViewInitialKey = function(key, val) {
    if(!(key in this.viewInitial)) {
        this.viewInitial[key] = val;
    }
};

function strTickLayout(axLayout) {
    var out = axLayout.ticks + String(axLayout.ticklen) + String(axLayout.showticklabels);
    if('side' in axLayout) out += axLayout.side;
    return out;
}

// Finds the bounding box of a given circle sector,
// inspired by https://math.stackexchange.com/q/1852703
//
// assumes:
// - sector[0] < sector[1]
// - counterclockwise rotation
function computeSectorBBox(sector) {
    var s0 = sector[0];
    var s1 = sector[1];
    var arc = s1 - s0;
    var a0 = mod(s0, 360);
    var a1 = a0 + arc;

    var ax0 = Math.cos(deg2rad(a0));
    var ay0 = Math.sin(deg2rad(a0));
    var ax1 = Math.cos(deg2rad(a1));
    var ay1 = Math.sin(deg2rad(a1));

    var x0, y0, x1, y1;

    if((a0 <= 90 && a1 >= 90) || (a0 > 90 && a1 >= 450)) {
        y1 = 1;
    } else if(ay0 <= 0 && ay1 <= 0) {
        y1 = 0;
    } else {
        y1 = Math.max(ay0, ay1);
    }

    if((a0 <= 180 && a1 >= 180) || (a0 > 180 && a1 >= 540)) {
        x0 = -1;
    } else if(ax0 >= 0 && ax1 >= 0) {
        x0 = 0;
    } else {
        x0 = Math.min(ax0, ax1);
    }

    if((a0 <= 270 && a1 >= 270) || (a0 > 270 && a1 >= 630)) {
        y0 = -1;
    } else if(ay0 >= 0 && ay1 >= 0) {
        y0 = 0;
    } else {
        y0 = Math.min(ay0, ay1);
    }

    if(a1 >= 360) {
        x1 = 1;
    } else if(ax0 <= 0 && ax1 <= 0) {
        x1 = 0;
    } else {
        x1 = Math.max(ax0, ax1);
    }

    return [x0, y0, x1, y1];
}

function snapToVertexAngle(a, vangles) {
    var fn = function(v) { return Lib.angleDist(a, v); };
    var ind = Lib.findIndexOfMin(vangles, fn);
    return vangles[ind];
}

function updateElement(sel, showAttr, attrs) {
    if(showAttr) {
        sel.attr('display', null);
        sel.attr(attrs);
    } else if(sel) {
        sel.attr('display', 'none');
    }
    return sel;
}

function strTranslate(x, y) {
    return 'translate(' + x + ',' + y + ')';
}

function strRotate(angle) {
    return 'rotate(' + angle + ')';
}

// because Math.sign(Math.cos(Math.PI / 2)) === 1
// oh javascript ;)
function sign(v) {
    return Math.abs(v) < 1e-10 ? 0 :
        v > 0 ? 1 : -1;
}

function signCos(v) {
    return sign(Math.cos(v));
}

function signSin(v) {
    return sign(Math.sin(v));
}

},{"../../components/color":571,"../../components/dragelement":589,"../../components/drawing":592,"../../components/fx":610,"../../components/titles":659,"../../constants/alignment":666,"../../lib":694,"../../lib/clear_gl_canvases":679,"../../lib/setcursor":714,"../../plot_api/subroutines":733,"../../plots/cartesian/axes":742,"../../registry":825,"../cartesian/autorange":741,"../cartesian/dragbox":751,"../cartesian/select":760,"../cartesian/set_convert":761,"../plots":806,"./constants":807,"./helpers":808,"./set_convert":819,"d3":149,"tinycolor2":515}],819:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var setConvertCartesian = _dereq_('../cartesian/set_convert');

var deg2rad = Lib.deg2rad;
var rad2deg = Lib.rad2deg;

/**
 * setConvert for polar axes!
 *
 * @param {object} ax
 *   axis in question (works for both radial and angular axes)
 * @param {object} polarLayout
 *   full polar layout of the subplot associated with 'ax'
 * @param {object} fullLayout
 *   full layout
 *
 * Here, reuse some of the Cartesian setConvert logic,
 * but we must extend some of it, as both radial and angular axes
 * don't have domains and angular axes don't have _true_ ranges.
 *
 * Moreover, we introduce two new coordinate systems:
 * - 'g' for geometric coordinates and
 * - 't' for angular ticks
 *
 * Radial axis coordinate systems:
 * - d, c and l: same as for cartesian axes
 * - g: like calcdata but translated about `radialaxis.range[0]` & `polar.hole`
 *
 * Angular axis coordinate systems:
 * - d: data, in whatever form it's provided
 * - c: calcdata, turned into radians (for linear axes)
 *      or category indices (category axes)
 * - t: tick calcdata, just like 'c' but in degrees for linear axes
 * - g: geometric calcdata, radians coordinates that take into account
 *      axis rotation and direction
 *
 * Then, 'g'eometric data is ready to be converted to (x,y).
 */
module.exports = function setConvert(ax, polarLayout, fullLayout) {
    setConvertCartesian(ax, fullLayout);

    switch(ax._id) {
        case 'x':
        case 'radialaxis':
            setConvertRadial(ax, polarLayout);
            break;
        case 'angularaxis':
            setConvertAngular(ax, polarLayout);
            break;
    }
};

function setConvertRadial(ax, polarLayout) {
    var subplot = polarLayout._subplot;

    ax.setGeometry = function() {
        var rl0 = ax._rl[0];
        var rl1 = ax._rl[1];

        var b = subplot.innerRadius;
        var m = (subplot.radius - b) / (rl1 - rl0);
        var b2 = b / m;

        var rFilter = rl0 > rl1 ?
            function(v) { return v <= 0; } :
            function(v) { return v >= 0; };

        ax.c2g = function(v) {
            var r = ax.c2l(v) - rl0;
            return (rFilter(r) ? r : 0) + b2;
        };

        ax.g2c = function(v) {
            return ax.l2c(v + rl0 - b2);
        };

        ax.g2p = function(v) { return v * m; };
        ax.c2p = function(v) { return ax.g2p(ax.c2g(v)); };
    };
}

function toRadians(v, unit) {
    return unit === 'degrees' ? deg2rad(v) : v;
}

function fromRadians(v, unit) {
    return unit === 'degrees' ? rad2deg(v) : v;
}

function setConvertAngular(ax, polarLayout) {
    var axType = ax.type;

    if(axType === 'linear') {
        var _d2c = ax.d2c;
        var _c2d = ax.c2d;

        ax.d2c = function(v, unit) { return toRadians(_d2c(v), unit); };
        ax.c2d = function(v, unit) { return _c2d(fromRadians(v, unit)); };
    }

    // override makeCalcdata to handle thetaunit and special theta0/dtheta logic
    ax.makeCalcdata = function(trace, coord) {
        var arrayIn = trace[coord];
        var len = trace._length;
        var arrayOut, i;

        var _d2c = function(v) { return ax.d2c(v, trace.thetaunit); };

        if(arrayIn) {
            if(Lib.isTypedArray(arrayIn) && axType === 'linear') {
                if(len === arrayIn.length) {
                    return arrayIn;
                } else if(arrayIn.subarray) {
                    return arrayIn.subarray(0, len);
                }
            }

            arrayOut = new Array(len);
            for(i = 0; i < len; i++) {
                arrayOut[i] = _d2c(arrayIn[i]);
            }
        } else {
            var coord0 = coord + '0';
            var dcoord = 'd' + coord;
            var v0 = (coord0 in trace) ? _d2c(trace[coord0]) : 0;
            var dv = (trace[dcoord]) ? _d2c(trace[dcoord]) : (ax.period || 2 * Math.PI) / len;

            arrayOut = new Array(len);
            for(i = 0; i < len; i++) {
                arrayOut[i] = v0 + i * dv;
            }
        }

        return arrayOut;
    };

    // N.B. we mock the axis 'range' here
    ax.setGeometry = function() {
        var sector = polarLayout.sector;
        var sectorInRad = sector.map(deg2rad);
        var dir = {clockwise: -1, counterclockwise: 1}[ax.direction];
        var rot = deg2rad(ax.rotation);

        var rad2g = function(v) { return dir * v + rot; };
        var g2rad = function(v) { return (v - rot) / dir; };

        var rad2c, c2rad;
        var rad2t, t2rad;

        switch(axType) {
            case 'linear':
                c2rad = rad2c = Lib.identity;
                t2rad = deg2rad;
                rad2t = rad2deg;

                // Set the angular range in degrees to make auto-tick computation cleaner,
                // changing rotation/direction should not affect the angular tick value.
                ax.range = Lib.isFullCircle(sectorInRad) ?
                    [sector[0], sector[0] + 360] :
                    sectorInRad.map(g2rad).map(rad2deg);
                break;

            case 'category':
                var catLen = ax._categories.length;
                var _period = ax.period ? Math.max(ax.period, catLen) : catLen;

                c2rad = t2rad = function(v) { return v * 2 * Math.PI / _period; };
                rad2c = rad2t = function(v) { return v * _period / Math.PI / 2; };

                ax.range = [0, _period];
                break;
        }

        ax.c2g = function(v) { return rad2g(c2rad(v)); };
        ax.g2c = function(v) { return rad2c(g2rad(v)); };

        ax.t2g = function(v) { return rad2g(t2rad(v)); };
        ax.g2t = function(v) { return rad2t(g2rad(v)); };
    };
}

},{"../../lib":694,"../cartesian/set_convert":761}],820:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../lib');
var Template = _dereq_('../plot_api/plot_template');
var handleDomainDefaults = _dereq_('./domain').defaults;


/**
 * Find and supply defaults to all subplots of a given type
 * This handles subplots that are contained within one container - so
 * gl3d, geo, ternary... but not 2d axes which have separate x and y axes
 * finds subplots, coerces their `domain` attributes, then calls the
 * given handleDefaults function to fill in everything else.
 *
 * layoutIn: the complete user-supplied input layout
 * layoutOut: the complete finished layout
 * fullData: the finished data array, used only to find subplots
 * opts: {
 *  type: subplot type string
 *  attributes: subplot attributes object
 *  partition: 'x' or 'y', which direction to divide domain space by default
 *      (default 'x', ie side-by-side subplots)
 *      TODO: this option is only here because 3D and geo made opposite
 *      choices in this regard previously and I didn't want to change it.
 *      Instead we should do:
 *      - something consistent
 *      - something more square (4 cuts 2x2, 5/6 cuts 2x3, etc.)
 *      - something that includes all subplot types in one arrangement,
 *        now that we can have them together!
 *  handleDefaults: function of (subplotLayoutIn, subplotLayoutOut, coerce, opts)
 *      this opts object is passed through to handleDefaults, so attach any
 *      additional items needed by this function here as well
 * }
 */
module.exports = function handleSubplotDefaults(layoutIn, layoutOut, fullData, opts) {
    var subplotType = opts.type;
    var subplotAttributes = opts.attributes;
    var handleDefaults = opts.handleDefaults;
    var partition = opts.partition || 'x';

    var ids = layoutOut._subplots[subplotType];
    var idsLength = ids.length;

    var baseId = idsLength && ids[0].replace(/\d+$/, '');

    var subplotLayoutIn, subplotLayoutOut;

    function coerce(attr, dflt) {
        return Lib.coerce(subplotLayoutIn, subplotLayoutOut, subplotAttributes, attr, dflt);
    }

    for(var i = 0; i < idsLength; i++) {
        var id = ids[i];

        // ternary traces get a layout ternary for free!
        if(layoutIn[id]) subplotLayoutIn = layoutIn[id];
        else subplotLayoutIn = layoutIn[id] = {};

        subplotLayoutOut = Template.newContainer(layoutOut, id, baseId);

        // All subplot containers get a `uirevision` inheriting from the base.
        // Currently all subplots containers have some user interaction
        // attributes, but if we ever add one that doesn't, we would need an
        // option to skip this step.
        coerce('uirevision', layoutOut.uirevision);

        var dfltDomains = {};
        dfltDomains[partition] = [i / idsLength, (i + 1) / idsLength];
        handleDomainDefaults(subplotLayoutOut, layoutOut, coerce, dfltDomains);

        opts.id = id;
        handleDefaults(subplotLayoutIn, subplotLayoutOut, coerce, opts);
    }
};

},{"../lib":694,"../plot_api/plot_template":732,"./domain":768}],821:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Ternary = _dereq_('./ternary');

var getSubplotCalcData = _dereq_('../../plots/get_data').getSubplotCalcData;
var counterRegex = _dereq_('../../lib').counterRegex;
var TERNARY = 'ternary';

exports.name = TERNARY;

var attr = exports.attr = 'subplot';

exports.idRoot = TERNARY;

exports.idRegex = exports.attrRegex = counterRegex(TERNARY);

var attributes = exports.attributes = {};
attributes[attr] = {
    valType: 'subplotid',
    
    dflt: 'ternary',
    editType: 'calc',
    
};

exports.layoutAttributes = _dereq_('./layout_attributes');

exports.supplyLayoutDefaults = _dereq_('./layout_defaults');

exports.plot = function plotTernary(gd) {
    var fullLayout = gd._fullLayout;
    var calcData = gd.calcdata;
    var ternaryIds = fullLayout._subplots[TERNARY];

    for(var i = 0; i < ternaryIds.length; i++) {
        var ternaryId = ternaryIds[i];
        var ternaryCalcData = getSubplotCalcData(calcData, TERNARY, ternaryId);
        var ternary = fullLayout[ternaryId]._subplot;

        // If ternary is not instantiated, create one!
        if(!ternary) {
            ternary = new Ternary({
                id: ternaryId,
                graphDiv: gd,
                container: fullLayout._ternarylayer.node()
            },
                fullLayout
            );

            fullLayout[ternaryId]._subplot = ternary;
        }

        ternary.plot(ternaryCalcData, fullLayout, gd._promises);
    }
};

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var oldTernaryKeys = oldFullLayout._subplots[TERNARY] || [];

    for(var i = 0; i < oldTernaryKeys.length; i++) {
        var oldTernaryKey = oldTernaryKeys[i];
        var oldTernary = oldFullLayout[oldTernaryKey]._subplot;

        if(!newFullLayout[oldTernaryKey] && !!oldTernary) {
            oldTernary.plotContainer.remove();
            oldTernary.clipDef.remove();
            oldTernary.clipDefRelative.remove();
            oldTernary.layers['a-title'].remove();
            oldTernary.layers['b-title'].remove();
            oldTernary.layers['c-title'].remove();
        }
    }
};

},{"../../lib":694,"../../plots/get_data":779,"./layout_attributes":822,"./layout_defaults":823,"./ternary":824}],822:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorAttrs = _dereq_('../../components/color/attributes');
var domainAttrs = _dereq_('../domain').attributes;
var axesAttrs = _dereq_('../cartesian/layout_attributes');

var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
var extendFlat = _dereq_('../../lib/extend').extendFlat;

var ternaryAxesAttrs = {
    title: axesAttrs.title,
    color: axesAttrs.color,
    // ticks
    tickmode: axesAttrs.tickmode,
    nticks: extendFlat({}, axesAttrs.nticks, {dflt: 6, min: 1}),
    tick0: axesAttrs.tick0,
    dtick: axesAttrs.dtick,
    tickvals: axesAttrs.tickvals,
    ticktext: axesAttrs.ticktext,
    ticks: axesAttrs.ticks,
    ticklen: axesAttrs.ticklen,
    tickwidth: axesAttrs.tickwidth,
    tickcolor: axesAttrs.tickcolor,
    showticklabels: axesAttrs.showticklabels,
    showtickprefix: axesAttrs.showtickprefix,
    tickprefix: axesAttrs.tickprefix,
    showticksuffix: axesAttrs.showticksuffix,
    ticksuffix: axesAttrs.ticksuffix,
    showexponent: axesAttrs.showexponent,
    exponentformat: axesAttrs.exponentformat,
    separatethousands: axesAttrs.separatethousands,
    tickfont: axesAttrs.tickfont,
    tickangle: axesAttrs.tickangle,
    tickformat: axesAttrs.tickformat,
    tickformatstops: axesAttrs.tickformatstops,
    hoverformat: axesAttrs.hoverformat,
    // lines and grids
    showline: extendFlat({}, axesAttrs.showline, {dflt: true}),
    linecolor: axesAttrs.linecolor,
    linewidth: axesAttrs.linewidth,
    showgrid: extendFlat({}, axesAttrs.showgrid, {dflt: true}),
    gridcolor: axesAttrs.gridcolor,
    gridwidth: axesAttrs.gridwidth,
    layer: axesAttrs.layer,
    // range
    min: {
        valType: 'number',
        dflt: 0,
        
        min: 0,
        
    },
    _deprecated: {
        title: axesAttrs._deprecated.title,
        titlefont: axesAttrs._deprecated.titlefont
    }
};

var attrs = module.exports = overrideAll({
    domain: domainAttrs({name: 'ternary'}),

    bgcolor: {
        valType: 'color',
        
        dflt: colorAttrs.background,
        
    },
    sum: {
        valType: 'number',
        
        dflt: 1,
        min: 0,
        
    },
    aaxis: ternaryAxesAttrs,
    baxis: ternaryAxesAttrs,
    caxis: ternaryAxesAttrs
}, 'plot', 'from-root');

// set uirevisions outside of `overrideAll` so we can get `editType: none`
attrs.uirevision = {
    valType: 'any',
    
    editType: 'none',
    
};

attrs.aaxis.uirevision = attrs.baxis.uirevision = attrs.caxis.uirevision = {
    valType: 'any',
    
    editType: 'none',
    
};

},{"../../components/color/attributes":570,"../../lib/extend":684,"../../plot_api/edit_types":725,"../cartesian/layout_attributes":755,"../domain":768}],823:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Color = _dereq_('../../components/color');
var Template = _dereq_('../../plot_api/plot_template');
var Lib = _dereq_('../../lib');

var handleSubplotDefaults = _dereq_('../subplot_defaults');
var handleTickLabelDefaults = _dereq_('../cartesian/tick_label_defaults');
var handleTickMarkDefaults = _dereq_('../cartesian/tick_mark_defaults');
var handleTickValueDefaults = _dereq_('../cartesian/tick_value_defaults');
var handleLineGridDefaults = _dereq_('../cartesian/line_grid_defaults');
var layoutAttributes = _dereq_('./layout_attributes');

var axesNames = ['aaxis', 'baxis', 'caxis'];

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
    handleSubplotDefaults(layoutIn, layoutOut, fullData, {
        type: 'ternary',
        attributes: layoutAttributes,
        handleDefaults: handleTernaryDefaults,
        font: layoutOut.font,
        paper_bgcolor: layoutOut.paper_bgcolor
    });
};

function handleTernaryDefaults(ternaryLayoutIn, ternaryLayoutOut, coerce, options) {
    var bgColor = coerce('bgcolor');
    var sum = coerce('sum');
    options.bgColor = Color.combine(bgColor, options.paper_bgcolor);
    var axName, containerIn, containerOut;

    // TODO: allow most (if not all) axis attributes to be set
    // in the outer container and used as defaults in the individual axes?

    for(var j = 0; j < axesNames.length; j++) {
        axName = axesNames[j];
        containerIn = ternaryLayoutIn[axName] || {};
        containerOut = Template.newContainer(ternaryLayoutOut, axName);
        containerOut._name = axName;

        handleAxisDefaults(containerIn, containerOut, options, ternaryLayoutOut);
    }

    // if the min values contradict each other, set them all to default (0)
    // and delete *all* the inputs so the user doesn't get confused later by
    // changing one and having them all change.
    var aaxis = ternaryLayoutOut.aaxis;
    var baxis = ternaryLayoutOut.baxis;
    var caxis = ternaryLayoutOut.caxis;
    if(aaxis.min + baxis.min + caxis.min >= sum) {
        aaxis.min = 0;
        baxis.min = 0;
        caxis.min = 0;
        if(ternaryLayoutIn.aaxis) delete ternaryLayoutIn.aaxis.min;
        if(ternaryLayoutIn.baxis) delete ternaryLayoutIn.baxis.min;
        if(ternaryLayoutIn.caxis) delete ternaryLayoutIn.caxis.min;
    }
}

function handleAxisDefaults(containerIn, containerOut, options, ternaryLayoutOut) {
    var axAttrs = layoutAttributes[containerOut._name];

    function coerce(attr, dflt) {
        return Lib.coerce(containerIn, containerOut, axAttrs, attr, dflt);
    }

    coerce('uirevision', ternaryLayoutOut.uirevision);

    containerOut.type = 'linear'; // no other types allowed for ternary

    var dfltColor = coerce('color');
    // if axis.color was provided, use it for fonts too; otherwise,
    // inherit from global font color in case that was provided.
    var dfltFontColor = (dfltColor !== axAttrs.color.dflt) ? dfltColor : options.font.color;

    var axName = containerOut._name;
    var letterUpper = axName.charAt(0).toUpperCase();
    var dfltTitle = 'Component ' + letterUpper;

    var title = coerce('title.text', dfltTitle);
    containerOut._hovertitle = title === dfltTitle ? title : letterUpper;

    Lib.coerceFont(coerce, 'title.font', {
        family: options.font.family,
        size: Math.round(options.font.size * 1.2),
        color: dfltFontColor
    });

    // range is just set by 'min' - max is determined by the other axes mins
    coerce('min');

    handleTickValueDefaults(containerIn, containerOut, coerce, 'linear');
    handleTickLabelDefaults(containerIn, containerOut, coerce, 'linear', {});
    handleTickMarkDefaults(containerIn, containerOut, coerce,
        { outerTicks: true });

    var showTickLabels = coerce('showticklabels');
    if(showTickLabels) {
        Lib.coerceFont(coerce, 'tickfont', {
            family: options.font.family,
            size: options.font.size,
            color: dfltFontColor
        });
        coerce('tickangle');
        coerce('tickformat');
    }

    handleLineGridDefaults(containerIn, containerOut, coerce, {
        dfltColor: dfltColor,
        bgColor: options.bgColor,
        // default grid color is darker here (60%, vs cartesian default ~91%)
        // because the grid is not square so the eye needs heavier cues to follow
        blend: 60,
        showLine: true,
        showGrid: true,
        noZeroLine: true,
        attributes: axAttrs
    });

    coerce('hoverformat');
    coerce('layer');
}

},{"../../components/color":571,"../../lib":694,"../../plot_api/plot_template":732,"../cartesian/line_grid_defaults":757,"../cartesian/tick_label_defaults":762,"../cartesian/tick_mark_defaults":763,"../cartesian/tick_value_defaults":764,"../subplot_defaults":820,"./layout_attributes":822}],824:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var tinycolor = _dereq_('tinycolor2');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var _ = Lib._;
var Color = _dereq_('../../components/color');
var Drawing = _dereq_('../../components/drawing');
var setConvert = _dereq_('../cartesian/set_convert');
var extendFlat = _dereq_('../../lib/extend').extendFlat;
var Plots = _dereq_('../plots');
var Axes = _dereq_('../cartesian/axes');
var dragElement = _dereq_('../../components/dragelement');
var Fx = _dereq_('../../components/fx');
var Titles = _dereq_('../../components/titles');
var prepSelect = _dereq_('../cartesian/select').prepSelect;
var selectOnClick = _dereq_('../cartesian/select').selectOnClick;
var clearSelect = _dereq_('../cartesian/select').clearSelect;
var constants = _dereq_('../cartesian/constants');

function Ternary(options, fullLayout) {
    this.id = options.id;
    this.graphDiv = options.graphDiv;
    this.init(fullLayout);
    this.makeFramework(fullLayout);

    // unfortunately, we have to keep track of some axis tick settings
    // as ternary subplots do not implement the 'ticks' editType
    this.aTickLayout = null;
    this.bTickLayout = null;
    this.cTickLayout = null;
}

module.exports = Ternary;

var proto = Ternary.prototype;

proto.init = function(fullLayout) {
    this.container = fullLayout._ternarylayer;
    this.defs = fullLayout._defs;
    this.layoutId = fullLayout._uid;
    this.traceHash = {};
    this.layers = {};
};

proto.plot = function(ternaryCalcData, fullLayout) {
    var _this = this;
    var ternaryLayout = fullLayout[_this.id];
    var graphSize = fullLayout._size;

    _this._hasClipOnAxisFalse = false;
    for(var i = 0; i < ternaryCalcData.length; i++) {
        var trace = ternaryCalcData[i][0].trace;

        if(trace.cliponaxis === false) {
            _this._hasClipOnAxisFalse = true;
            break;
        }
    }

    _this.updateLayers(ternaryLayout);
    _this.adjustLayout(ternaryLayout, graphSize);
    Plots.generalUpdatePerTraceModule(_this.graphDiv, _this, ternaryCalcData, ternaryLayout);
    _this.layers.plotbg.select('path').call(Color.fill, ternaryLayout.bgcolor);
};

proto.makeFramework = function(fullLayout) {
    var _this = this;
    var gd = _this.graphDiv;
    var ternaryLayout = fullLayout[_this.id];

    var clipId = _this.clipId = 'clip' + _this.layoutId + _this.id;
    var clipIdRelative = _this.clipIdRelative = 'clip-relative' + _this.layoutId + _this.id;

    // clippath for this ternary subplot
    _this.clipDef = Lib.ensureSingleById(fullLayout._clips, 'clipPath', clipId, function(s) {
        s.append('path').attr('d', 'M0,0Z');
    });

    // 'relative' clippath (i.e. no translation) for this ternary subplot
    _this.clipDefRelative = Lib.ensureSingleById(fullLayout._clips, 'clipPath', clipIdRelative, function(s) {
        s.append('path').attr('d', 'M0,0Z');
    });

    // container for everything in this ternary subplot
    _this.plotContainer = Lib.ensureSingle(_this.container, 'g', _this.id);
    _this.updateLayers(ternaryLayout);

    Drawing.setClipUrl(_this.layers.backplot, clipId, gd);
    Drawing.setClipUrl(_this.layers.grids, clipId, gd);
};

proto.updateLayers = function(ternaryLayout) {
    var _this = this;
    var layers = _this.layers;

    // inside that container, we have one container for the data, and
    // one each for the three axes around it.

    var plotLayers = ['draglayer', 'plotbg', 'backplot', 'grids'];

    if(ternaryLayout.aaxis.layer === 'below traces') {
        plotLayers.push('aaxis', 'aline');
    }
    if(ternaryLayout.baxis.layer === 'below traces') {
        plotLayers.push('baxis', 'bline');
    }
    if(ternaryLayout.caxis.layer === 'below traces') {
        plotLayers.push('caxis', 'cline');
    }

    plotLayers.push('frontplot');

    if(ternaryLayout.aaxis.layer === 'above traces') {
        plotLayers.push('aaxis', 'aline');
    }
    if(ternaryLayout.baxis.layer === 'above traces') {
        plotLayers.push('baxis', 'bline');
    }
    if(ternaryLayout.caxis.layer === 'above traces') {
        plotLayers.push('caxis', 'cline');
    }

    var toplevel = _this.plotContainer.selectAll('g.toplevel')
        .data(plotLayers, String);

    var grids = ['agrid', 'bgrid', 'cgrid'];

    toplevel.enter().append('g')
        .attr('class', function(d) { return 'toplevel ' + d; })
        .each(function(d) {
            var s = d3.select(this);
            layers[d] = s;

            // containers for different trace types.
            // NOTE - this is different from cartesian, where all traces
            // are in front of grids. Here I'm putting maps behind the grids
            // so the grids will always be visible if they're requested.
            // Perhaps we want that for cartesian too?
            if(d === 'frontplot') {
                s.append('g').classed('scatterlayer', true);
            } else if(d === 'backplot') {
                s.append('g').classed('maplayer', true);
            } else if(d === 'plotbg') {
                s.append('path').attr('d', 'M0,0Z');
            } else if(d === 'aline' || d === 'bline' || d === 'cline') {
                s.append('path');
            } else if(d === 'grids') {
                grids.forEach(function(d) {
                    layers[d] = s.append('g').classed('grid ' + d, true);
                });
            }
        });

    toplevel.order();
};

var whRatio = Math.sqrt(4 / 3);

proto.adjustLayout = function(ternaryLayout, graphSize) {
    var _this = this;
    var domain = ternaryLayout.domain;
    var xDomainCenter = (domain.x[0] + domain.x[1]) / 2;
    var yDomainCenter = (domain.y[0] + domain.y[1]) / 2;
    var xDomain = domain.x[1] - domain.x[0];
    var yDomain = domain.y[1] - domain.y[0];
    var wmax = xDomain * graphSize.w;
    var hmax = yDomain * graphSize.h;
    var sum = ternaryLayout.sum;
    var amin = ternaryLayout.aaxis.min;
    var bmin = ternaryLayout.baxis.min;
    var cmin = ternaryLayout.caxis.min;

    var x0, y0, w, h, xDomainFinal, yDomainFinal;

    if(wmax > whRatio * hmax) {
        h = hmax;
        w = h * whRatio;
    }
    else {
        w = wmax;
        h = w / whRatio;
    }

    xDomainFinal = xDomain * w / wmax;
    yDomainFinal = yDomain * h / hmax;

    x0 = graphSize.l + graphSize.w * xDomainCenter - w / 2;
    y0 = graphSize.t + graphSize.h * (1 - yDomainCenter) - h / 2;

    _this.x0 = x0;
    _this.y0 = y0;
    _this.w = w;
    _this.h = h;
    _this.sum = sum;

    // set up the x and y axis objects we'll use to lay out the points
    _this.xaxis = {
        type: 'linear',
        range: [amin + 2 * cmin - sum, sum - amin - 2 * bmin],
        domain: [
            xDomainCenter - xDomainFinal / 2,
            xDomainCenter + xDomainFinal / 2
        ],
        _id: 'x'
    };
    setConvert(_this.xaxis, _this.graphDiv._fullLayout);
    _this.xaxis.setScale();
    _this.xaxis.isPtWithinRange = function(d) {
        return (
            d.a >= _this.aaxis.range[0] &&
            d.a <= _this.aaxis.range[1] &&
            d.b >= _this.baxis.range[1] &&
            d.b <= _this.baxis.range[0] &&
            d.c >= _this.caxis.range[1] &&
            d.c <= _this.caxis.range[0]
        );
    };

    _this.yaxis = {
        type: 'linear',
        range: [amin, sum - bmin - cmin],
        domain: [
            yDomainCenter - yDomainFinal / 2,
            yDomainCenter + yDomainFinal / 2
        ],
        _id: 'y'
    };
    setConvert(_this.yaxis, _this.graphDiv._fullLayout);
    _this.yaxis.setScale();
    _this.yaxis.isPtWithinRange = function() { return true; };

    // set up the modified axes for tick drawing
    var yDomain0 = _this.yaxis.domain[0];

    // aaxis goes up the left side. Set it up as a y axis, but with
    // fictitious angles and domain, but then rotate and translate
    // it into place at the end
    var aaxis = _this.aaxis = extendFlat({}, ternaryLayout.aaxis, {
        range: [amin, sum - bmin - cmin],
        side: 'left',
        // tickangle = 'auto' means 0 anyway for a y axis, need to coerce to 0 here
        // so we can shift by 30.
        tickangle: (+ternaryLayout.aaxis.tickangle || 0) - 30,
        domain: [yDomain0, yDomain0 + yDomainFinal * whRatio],
        anchor: 'free',
        position: 0,
        _id: 'y',
        _length: w
    });
    setConvert(aaxis, _this.graphDiv._fullLayout);
    aaxis.setScale();

    // baxis goes across the bottom (backward). We can set it up as an x axis
    // without any enclosing transformation.
    var baxis = _this.baxis = extendFlat({}, ternaryLayout.baxis, {
        range: [sum - amin - cmin, bmin],
        side: 'bottom',
        domain: _this.xaxis.domain,
        anchor: 'free',
        position: 0,
        _id: 'x',
        _length: w
    });
    setConvert(baxis, _this.graphDiv._fullLayout);
    baxis.setScale();

    // caxis goes down the right side. Set it up as a y axis, with
    // post-transformation similar to aaxis
    var caxis = _this.caxis = extendFlat({}, ternaryLayout.caxis, {
        range: [sum - amin - bmin, cmin],
        side: 'right',
        tickangle: (+ternaryLayout.caxis.tickangle || 0) + 30,
        domain: [yDomain0, yDomain0 + yDomainFinal * whRatio],
        anchor: 'free',
        position: 0,
        _id: 'y',
        _length: w
    });
    setConvert(caxis, _this.graphDiv._fullLayout);
    caxis.setScale();

    var triangleClip = 'M' + x0 + ',' + (y0 + h) + 'h' + w + 'l-' + (w / 2) + ',-' + h + 'Z';
    _this.clipDef.select('path').attr('d', triangleClip);
    _this.layers.plotbg.select('path').attr('d', triangleClip);

    var triangleClipRelative = 'M0,' + h + 'h' + w + 'l-' + (w / 2) + ',-' + h + 'Z';
    _this.clipDefRelative.select('path').attr('d', triangleClipRelative);

    var plotTransform = 'translate(' + x0 + ',' + y0 + ')';
    _this.plotContainer.selectAll('.scatterlayer,.maplayer')
        .attr('transform', plotTransform);

    _this.clipDefRelative.select('path').attr('transform', null);

    // TODO: shift axes to accommodate linewidth*sin(30) tick mark angle

    // TODO: there's probably an easier way to handle these translations/offsets now...
    var bTransform = 'translate(' + (x0 - baxis._offset) + ',' + (y0 + h) + ')';

    _this.layers.baxis.attr('transform', bTransform);
    _this.layers.bgrid.attr('transform', bTransform);

    var aTransform = 'translate(' + (x0 + w / 2) + ',' + y0 +
        ')rotate(30)translate(0,' + -aaxis._offset + ')';
    _this.layers.aaxis.attr('transform', aTransform);
    _this.layers.agrid.attr('transform', aTransform);

    var cTransform = 'translate(' + (x0 + w / 2) + ',' + y0 +
        ')rotate(-30)translate(0,' + -caxis._offset + ')';
    _this.layers.caxis.attr('transform', cTransform);
    _this.layers.cgrid.attr('transform', cTransform);

    _this.drawAxes(true);

    _this.layers.aline.select('path')
        .attr('d', aaxis.showline ?
            'M' + x0 + ',' + (y0 + h) + 'l' + (w / 2) + ',-' + h : 'M0,0')
        .call(Color.stroke, aaxis.linecolor || '#000')
        .style('stroke-width', (aaxis.linewidth || 0) + 'px');
    _this.layers.bline.select('path')
        .attr('d', baxis.showline ?
            'M' + x0 + ',' + (y0 + h) + 'h' + w : 'M0,0')
        .call(Color.stroke, baxis.linecolor || '#000')
        .style('stroke-width', (baxis.linewidth || 0) + 'px');
    _this.layers.cline.select('path')
        .attr('d', caxis.showline ?
            'M' + (x0 + w / 2) + ',' + y0 + 'l' + (w / 2) + ',' + h : 'M0,0')
        .call(Color.stroke, caxis.linecolor || '#000')
        .style('stroke-width', (caxis.linewidth || 0) + 'px');

    if(!_this.graphDiv._context.staticPlot) {
        _this.initInteractions();
    }

    Drawing.setClipUrl(
        _this.layers.frontplot,
        _this._hasClipOnAxisFalse ? null : _this.clipId,
        _this.graphDiv
    );
};

proto.drawAxes = function(doTitles) {
    var _this = this;
    var gd = _this.graphDiv;
    var titlesuffix = _this.id.substr(7) + 'title';
    var layers = _this.layers;
    var aaxis = _this.aaxis;
    var baxis = _this.baxis;
    var caxis = _this.caxis;

    _this.drawAx(aaxis);
    _this.drawAx(baxis);
    _this.drawAx(caxis);

    if(doTitles) {
        var apad = Math.max(aaxis.showticklabels ? aaxis.tickfont.size / 2 : 0,
            (caxis.showticklabels ? caxis.tickfont.size * 0.75 : 0) +
            (caxis.ticks === 'outside' ? caxis.ticklen * 0.87 : 0));
        var bpad = (baxis.showticklabels ? baxis.tickfont.size : 0) +
            (baxis.ticks === 'outside' ? baxis.ticklen : 0) + 3;

        layers['a-title'] = Titles.draw(gd, 'a' + titlesuffix, {
            propContainer: aaxis,
            propName: _this.id + '.aaxis.title',
            placeholder: _(gd, 'Click to enter Component A title'),
            attributes: {
                x: _this.x0 + _this.w / 2,
                y: _this.y0 - aaxis.title.font.size / 3 - apad,
                'text-anchor': 'middle'
            }
        });
        layers['b-title'] = Titles.draw(gd, 'b' + titlesuffix, {
            propContainer: baxis,
            propName: _this.id + '.baxis.title',
            placeholder: _(gd, 'Click to enter Component B title'),
            attributes: {
                x: _this.x0 - bpad,
                y: _this.y0 + _this.h + baxis.title.font.size * 0.83 + bpad,
                'text-anchor': 'middle'
            }
        });
        layers['c-title'] = Titles.draw(gd, 'c' + titlesuffix, {
            propContainer: caxis,
            propName: _this.id + '.caxis.title',
            placeholder: _(gd, 'Click to enter Component C title'),
            attributes: {
                x: _this.x0 + _this.w + bpad,
                y: _this.y0 + _this.h + caxis.title.font.size * 0.83 + bpad,
                'text-anchor': 'middle'
            }
        });
    }
};

proto.drawAx = function(ax) {
    var _this = this;
    var gd = _this.graphDiv;
    var axName = ax._name;
    var axLetter = axName.charAt(0);
    var axId = ax._id;
    var axLayer = _this.layers[axName];
    var counterAngle = 30;

    var stashKey = axLetter + 'tickLayout';
    var newTickLayout = strTickLayout(ax);
    if(_this[stashKey] !== newTickLayout) {
        axLayer.selectAll('.' + axId + 'tick').remove();
        _this[stashKey] = newTickLayout;
    }

    ax.setScale();

    var vals = Axes.calcTicks(ax);
    var valsClipped = Axes.clipEnds(ax, vals);
    var transFn = Axes.makeTransFn(ax);
    var tickSign = Axes.getTickSigns(ax)[2];

    var caRad = Lib.deg2rad(counterAngle);
    var pad = tickSign * (ax.linewidth || 1) / 2;
    var len = tickSign * ax.ticklen;
    var w = _this.w;
    var h = _this.h;

    var tickPath = axLetter === 'b' ?
        'M0,' + pad + 'l' + (Math.sin(caRad) * len) + ',' + (Math.cos(caRad) * len) :
        'M' + pad + ',0l' + (Math.cos(caRad) * len) + ',' + (-Math.sin(caRad) * len);

    var gridPath = {
        a: 'M0,0l' + h + ',-' + (w / 2),
        b: 'M0,0l-' + (w / 2) + ',-' + h,
        c: 'M0,0l-' + h + ',' + (w / 2)
    }[axLetter];

    Axes.drawTicks(gd, ax, {
        vals: ax.ticks === 'inside' ? valsClipped : vals,
        layer: axLayer,
        path: tickPath,
        transFn: transFn,
        crisp: false
    });

    Axes.drawGrid(gd, ax, {
        vals: valsClipped,
        layer: _this.layers[axLetter + 'grid'],
        path: gridPath,
        transFn: transFn,
        crisp: false
    });

    var labelFns = Axes.makeLabelFns(ax, 0, counterAngle);

    Axes.drawLabels(gd, ax, {
        vals: vals,
        layer: axLayer,
        transFn: transFn,
        labelXFn: labelFns.labelXFn,
        labelYFn: labelFns.labelYFn,
        labelAnchorFn: labelFns.labelAnchorFn
    });
};

function strTickLayout(axLayout) {
    return axLayout.ticks + String(axLayout.ticklen) + String(axLayout.showticklabels);
}

// hard coded paths for zoom corners
// uses the same sizing as cartesian, length is MINZOOM/2, width is 3px
var CLEN = constants.MINZOOM / 2 + 0.87;
var BLPATH = 'm-0.87,.5h' + CLEN + 'v3h-' + (CLEN + 5.2) +
    'l' + (CLEN / 2 + 2.6) + ',-' + (CLEN * 0.87 + 4.5) +
    'l2.6,1.5l-' + (CLEN / 2) + ',' + (CLEN * 0.87) + 'Z';
var BRPATH = 'm0.87,.5h-' + CLEN + 'v3h' + (CLEN + 5.2) +
    'l-' + (CLEN / 2 + 2.6) + ',-' + (CLEN * 0.87 + 4.5) +
    'l-2.6,1.5l' + (CLEN / 2) + ',' + (CLEN * 0.87) + 'Z';
var TOPPATH = 'm0,1l' + (CLEN / 2) + ',' + (CLEN * 0.87) +
    'l2.6,-1.5l-' + (CLEN / 2 + 2.6) + ',-' + (CLEN * 0.87 + 4.5) +
    'l-' + (CLEN / 2 + 2.6) + ',' + (CLEN * 0.87 + 4.5) +
    'l2.6,1.5l' + (CLEN / 2) + ',-' + (CLEN * 0.87) + 'Z';
var STARTMARKER = 'm0.5,0.5h5v-2h-5v-5h-2v5h-5v2h5v5h2Z';

// I guess this could be shared with cartesian... but for now it's separate.
var SHOWZOOMOUTTIP = true;

proto.initInteractions = function() {
    var _this = this;
    var dragger = _this.layers.plotbg.select('path').node();
    var gd = _this.graphDiv;
    var zoomContainer = gd._fullLayout._zoomlayer;

    // use plotbg for the main interactions
    var dragOptions = {
        element: dragger,
        gd: gd,
        plotinfo: {
            id: _this.id,
            xaxis: _this.xaxis,
            yaxis: _this.yaxis
        },
        subplot: _this.id,
        prepFn: function(e, startX, startY) {
            // these aren't available yet when initInteractions
            // is called
            dragOptions.xaxes = [_this.xaxis];
            dragOptions.yaxes = [_this.yaxis];
            var dragModeNow = gd._fullLayout.dragmode;

            if(dragModeNow === 'lasso') dragOptions.minDrag = 1;
            else dragOptions.minDrag = undefined;

            if(dragModeNow === 'zoom') {
                dragOptions.moveFn = zoomMove;
                dragOptions.clickFn = clickZoomPan;
                dragOptions.doneFn = zoomDone;
                zoomPrep(e, startX, startY);
            }
            else if(dragModeNow === 'pan') {
                dragOptions.moveFn = plotDrag;
                dragOptions.clickFn = clickZoomPan;
                dragOptions.doneFn = dragDone;
                panPrep();
                clearSelect(zoomContainer);
            }
            else if(dragModeNow === 'select' || dragModeNow === 'lasso') {
                prepSelect(e, startX, startY, dragOptions, dragModeNow);
            }
        }
    };

    var x0, y0, mins0, span0, mins, lum, path0, dimmed, zb, corners;

    function makeUpdate(_mins) {
        var attrs = {};
        attrs[_this.id + '.aaxis.min'] = _mins.a;
        attrs[_this.id + '.baxis.min'] = _mins.b;
        attrs[_this.id + '.caxis.min'] = _mins.c;
        return attrs;
    }

    function clickZoomPan(numClicks, evt) {
        var clickMode = gd._fullLayout.clickmode;

        removeZoombox(gd);

        if(numClicks === 2) {
            gd.emit('plotly_doubleclick', null);
            Registry.call('_guiRelayout', gd, makeUpdate({a: 0, b: 0, c: 0}));
        }

        if(clickMode.indexOf('select') > -1 && numClicks === 1) {
            selectOnClick(evt, gd, [_this.xaxis], [_this.yaxis], _this.id, dragOptions);
        }

        if(clickMode.indexOf('event') > -1) {
            Fx.click(gd, evt, _this.id);
        }
    }

    function zoomPrep(e, startX, startY) {
        var dragBBox = dragger.getBoundingClientRect();
        x0 = startX - dragBBox.left;
        y0 = startY - dragBBox.top;
        mins0 = {
            a: _this.aaxis.range[0],
            b: _this.baxis.range[1],
            c: _this.caxis.range[1]
        };
        mins = mins0;
        span0 = _this.aaxis.range[1] - mins0.a;
        lum = tinycolor(_this.graphDiv._fullLayout[_this.id].bgcolor).getLuminance();
        path0 = 'M0,' + _this.h + 'L' + (_this.w / 2) + ', 0L' + _this.w + ',' + _this.h + 'Z';
        dimmed = false;

        zb = zoomContainer.append('path')
            .attr('class', 'zoombox')
            .attr('transform', 'translate(' + _this.x0 + ', ' + _this.y0 + ')')
            .style({
                'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)',
                'stroke-width': 0
            })
            .attr('d', path0);

        corners = zoomContainer.append('path')
            .attr('class', 'zoombox-corners')
            .attr('transform', 'translate(' + _this.x0 + ', ' + _this.y0 + ')')
            .style({
                fill: Color.background,
                stroke: Color.defaultLine,
                'stroke-width': 1,
                opacity: 0
            })
            .attr('d', 'M0,0Z');

        clearSelect(zoomContainer);
    }

    function getAFrac(x, y) { return 1 - (y / _this.h); }
    function getBFrac(x, y) { return 1 - ((x + (_this.h - y) / Math.sqrt(3)) / _this.w); }
    function getCFrac(x, y) { return ((x - (_this.h - y) / Math.sqrt(3)) / _this.w); }

    function zoomMove(dx0, dy0) {
        var x1 = x0 + dx0;
        var y1 = y0 + dy0;
        var afrac = Math.max(0, Math.min(1, getAFrac(x0, y0), getAFrac(x1, y1)));
        var bfrac = Math.max(0, Math.min(1, getBFrac(x0, y0), getBFrac(x1, y1)));
        var cfrac = Math.max(0, Math.min(1, getCFrac(x0, y0), getCFrac(x1, y1)));
        var xLeft = ((afrac / 2) + cfrac) * _this.w;
        var xRight = (1 - (afrac / 2) - bfrac) * _this.w;
        var xCenter = (xLeft + xRight) / 2;
        var xSpan = xRight - xLeft;
        var yBottom = (1 - afrac) * _this.h;
        var yTop = yBottom - xSpan / whRatio;

        if(xSpan < constants.MINZOOM) {
            mins = mins0;
            zb.attr('d', path0);
            corners.attr('d', 'M0,0Z');
        }
        else {
            mins = {
                a: mins0.a + afrac * span0,
                b: mins0.b + bfrac * span0,
                c: mins0.c + cfrac * span0
            };
            zb.attr('d', path0 + 'M' + xLeft + ',' + yBottom +
                'H' + xRight + 'L' + xCenter + ',' + yTop +
                'L' + xLeft + ',' + yBottom + 'Z');
            corners.attr('d', 'M' + x0 + ',' + y0 + STARTMARKER +
                'M' + xLeft + ',' + yBottom + BLPATH +
                'M' + xRight + ',' + yBottom + BRPATH +
                'M' + xCenter + ',' + yTop + TOPPATH);
        }

        if(!dimmed) {
            zb.transition()
                .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' :
                    'rgba(255,255,255,0.3)')
                .duration(200);
            corners.transition()
                .style('opacity', 1)
                .duration(200);
            dimmed = true;
        }
    }

    function zoomDone() {
        removeZoombox(gd);

        if(mins === mins0) return;

        Registry.call('_guiRelayout', gd, makeUpdate(mins));

        if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) {
            Lib.notifier(_(gd, 'Double-click to zoom back out'), 'long');
            SHOWZOOMOUTTIP = false;
        }
    }

    function panPrep() {
        mins0 = {
            a: _this.aaxis.range[0],
            b: _this.baxis.range[1],
            c: _this.caxis.range[1]
        };
        mins = mins0;
    }

    function plotDrag(dx, dy) {
        var dxScaled = dx / _this.xaxis._m;
        var dyScaled = dy / _this.yaxis._m;
        mins = {
            a: mins0.a - dyScaled,
            b: mins0.b + (dxScaled + dyScaled) / 2,
            c: mins0.c - (dxScaled - dyScaled) / 2
        };
        var minsorted = [mins.a, mins.b, mins.c].sort();
        var minindices = {
            a: minsorted.indexOf(mins.a),
            b: minsorted.indexOf(mins.b),
            c: minsorted.indexOf(mins.c)
        };
        if(minsorted[0] < 0) {
            if(minsorted[1] + minsorted[0] / 2 < 0) {
                minsorted[2] += minsorted[0] + minsorted[1];
                minsorted[0] = minsorted[1] = 0;
            }
            else {
                minsorted[2] += minsorted[0] / 2;
                minsorted[1] += minsorted[0] / 2;
                minsorted[0] = 0;
            }
            mins = {
                a: minsorted[minindices.a],
                b: minsorted[minindices.b],
                c: minsorted[minindices.c]
            };
            dy = (mins0.a - mins.a) * _this.yaxis._m;
            dx = (mins0.c - mins.c - mins0.b + mins.b) * _this.xaxis._m;
        }

        // move the data (translate, don't redraw)
        var plotTransform = 'translate(' + (_this.x0 + dx) + ',' + (_this.y0 + dy) + ')';
        _this.plotContainer.selectAll('.scatterlayer,.maplayer')
            .attr('transform', plotTransform);

        var plotTransform2 = 'translate(' + -dx + ',' + -dy + ')';
        _this.clipDefRelative.select('path').attr('transform', plotTransform2);

        // move the ticks
        _this.aaxis.range = [mins.a, _this.sum - mins.b - mins.c];
        _this.baxis.range = [_this.sum - mins.a - mins.c, mins.b];
        _this.caxis.range = [_this.sum - mins.a - mins.b, mins.c];

        _this.drawAxes(false);

        if(_this._hasClipOnAxisFalse) {
            _this.plotContainer
                .select('.scatterlayer').selectAll('.trace')
                .call(Drawing.hideOutsideRangePoints, _this);
        }
    }

    function dragDone() {
        Registry.call('_guiRelayout', gd, makeUpdate(mins));
    }

    // finally, set up hover and click
    // these event handlers must already be set before dragElement.init
    // so it can stash them and override them.
    dragger.onmousemove = function(evt) {
        Fx.hover(gd, evt, _this.id);
        gd._fullLayout._lasthover = dragger;
        gd._fullLayout._hoversubplot = _this.id;
    };

    dragger.onmouseout = function(evt) {
        if(gd._dragging) return;

        dragElement.unhover(gd, evt);
    };

    dragElement.init(dragOptions);
};

function removeZoombox(gd) {
    d3.select(gd)
        .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners')
        .remove();
}

},{"../../components/color":571,"../../components/dragelement":589,"../../components/drawing":592,"../../components/fx":610,"../../components/titles":659,"../../lib":694,"../../lib/extend":684,"../../registry":825,"../cartesian/axes":742,"../cartesian/constants":748,"../cartesian/select":760,"../cartesian/set_convert":761,"../plots":806,"d3":149,"tinycolor2":515}],825:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Loggers = _dereq_('./lib/loggers');
var noop = _dereq_('./lib/noop');
var pushUnique = _dereq_('./lib/push_unique');
var isPlainObject = _dereq_('./lib/is_plain_object');
var ExtendModule = _dereq_('./lib/extend');

var basePlotAttributes = _dereq_('./plots/attributes');
var baseLayoutAttributes = _dereq_('./plots/layout_attributes');

var extendFlat = ExtendModule.extendFlat;
var extendDeepAll = ExtendModule.extendDeepAll;

exports.modules = {};
exports.allCategories = {};
exports.allTypes = [];
exports.subplotsRegistry = {};
exports.transformsRegistry = {};
exports.componentsRegistry = {};
exports.layoutArrayContainers = [];
exports.layoutArrayRegexes = [];
exports.traceLayoutAttributes = {};
exports.localeRegistry = {};
exports.apiMethodRegistry = {};
exports.collectableSubplotTypes = null;

/**
 * Top-level register routine, exported as Plotly.register
 *
 * @param {object array or array of objects} _modules :
 *  module object or list of module object to register.
 *
 *  A valid `moduleType: 'trace'` module has fields:
 *  - name {string} : the trace type
 *  - categories {array} : categories associated with this trace type,
 *                         tested with Register.traceIs()
 *  - meta {object} : meta info (mostly for plot-schema)
 *
 *  A valid `moduleType: 'locale'` module has fields:
 *  - name {string} : the locale name. Should be a 2-digit language string ('en', 'de')
 *                    optionally with a country/region code ('en-GB', 'de-CH'). If a country
 *                    code is used but the base language locale has not yet been supplied,
 *                    we will use this locale for the base as well.
 *  - dictionary {object} : the dictionary mapping input strings to localized strings
 *                          generally the keys should be the literal input strings, but
 *                          if default translations are provided you can use any string as a key.
 *  - format {object} : a `d3.locale` format specifier for this locale
 *                      any omitted keys we'll fall back on en-US.
 *
 *  A valid `moduleType: 'transform'` module has fields:
 *  - name {string} : transform name
 *  - transform {function} : default-level transform function
 *  - calcTransform {function} : calc-level transform function
 *  - attributes {object} : transform attributes declarations
 *  - supplyDefaults {function} : attributes default-supply function
 *
 *  A valid `moduleType: 'component'` module has fields:
 *  - name {string} : the component name, used it with Register.getComponentMethod()
 *                    to employ component method.
 *
 *  A valid `moduleType: 'apiMethod'` module has fields:
 *  - name {string} : the api method name.
 *  - fn {function} : the api method called with Register.call();
 *
 */
exports.register = function register(_modules) {
    exports.collectableSubplotTypes = null;

    if(!_modules) {
        throw new Error('No argument passed to Plotly.register.');
    } else if(_modules && !Array.isArray(_modules)) {
        _modules = [_modules];
    }

    for(var i = 0; i < _modules.length; i++) {
        var newModule = _modules[i];

        if(!newModule) {
            throw new Error('Invalid module was attempted to be registered!');
        }

        switch(newModule.moduleType) {
            case 'trace':
                registerTraceModule(newModule);
                break;
            case 'transform':
                registerTransformModule(newModule);
                break;
            case 'component':
                registerComponentModule(newModule);
                break;
            case 'locale':
                registerLocale(newModule);
                break;
            case 'apiMethod':
                var name = newModule.name;
                exports.apiMethodRegistry[name] = newModule.fn;
                break;
            default:
                throw new Error('Invalid module was attempted to be registered!');
        }
    }
};

/**
 * Get registered module using trace object or trace type
 *
 * @param {object||string} trace
 *  trace object with prop 'type' or trace type as a string
 * @return {object}
 *  module object corresponding to trace type
 */
exports.getModule = function(trace) {
    var _module = exports.modules[getTraceType(trace)];
    if(!_module) return false;
    return _module._module;
};

/**
 * Determine if this trace type is in a given category
 *
 * @param {object||string} traceType
 *  a trace (object) or trace type (string)
 * @param {string} category
 *  category in question
 * @return {boolean}
 */
exports.traceIs = function(traceType, category) {
    traceType = getTraceType(traceType);

    // old plot.ly workspace hack, nothing to see here
    if(traceType === 'various') return false;

    var _module = exports.modules[traceType];

    if(!_module) {
        if(traceType && traceType !== 'area') {
            Loggers.log('Unrecognized trace type ' + traceType + '.');
        }

        _module = exports.modules[basePlotAttributes.type.dflt];
    }

    return !!_module.categories[category];
};

/**
 * Determine if this trace has a transform of the given type and return
 * array of matching indices.
 *
 * @param {object} data
 *  a trace object (member of data or fullData)
 * @param {string} type
 *  type of trace to test
 * @return {array}
 *  array of matching indices. If none found, returns []
 */
exports.getTransformIndices = function(data, type) {
    var indices = [];
    var transforms = data.transforms || [];
    for(var i = 0; i < transforms.length; i++) {
        if(transforms[i].type === type) {
            indices.push(i);
        }
    }
    return indices;
};

/**
 * Determine if this trace has a transform of the given type
 *
 * @param {object} data
 *  a trace object (member of data or fullData)
 * @param {string} type
 *  type of trace to test
 * @return {boolean}
 */
exports.hasTransform = function(data, type) {
    var transforms = data.transforms || [];
    for(var i = 0; i < transforms.length; i++) {
        if(transforms[i].type === type) {
            return true;
        }
    }
    return false;
};

/**
 * Retrieve component module method. Falls back on noop if either the
 * module or the method is missing, so the result can always be safely called
 *
 * @param {string} name
 *  name of component (as declared in component module)
 * @param {string} method
 *  name of component module method
 * @return {function}
 */
exports.getComponentMethod = function(name, method) {
    var _module = exports.componentsRegistry[name];

    if(!_module) return noop;
    return _module[method] || noop;
};

/**
 * Call registered api method.
 *
 * @param {string} name : api method name
 * @param {...array} args : arguments passed to api method
 * @return {any} : returns api method output
 */
exports.call = function() {
    var name = arguments[0];
    var args = [].slice.call(arguments, 1);
    return exports.apiMethodRegistry[name].apply(null, args);
};

function registerTraceModule(_module) {
    var thisType = _module.name;
    var categoriesIn = _module.categories;
    var meta = _module.meta;

    if(exports.modules[thisType]) {
        Loggers.log('Type ' + thisType + ' already registered');
        return;
    }

    if(!exports.subplotsRegistry[_module.basePlotModule.name]) {
        registerSubplot(_module.basePlotModule);
    }

    var categoryObj = {};
    for(var i = 0; i < categoriesIn.length; i++) {
        categoryObj[categoriesIn[i]] = true;
        exports.allCategories[categoriesIn[i]] = true;
    }

    exports.modules[thisType] = {
        _module: _module,
        categories: categoryObj
    };

    if(meta && Object.keys(meta).length) {
        exports.modules[thisType].meta = meta;
    }

    exports.allTypes.push(thisType);

    for(var componentName in exports.componentsRegistry) {
        mergeComponentAttrsToTrace(componentName, thisType);
    }

    /*
     * Collect all trace layout attributes in one place for easier lookup later
     * but don't merge them into the base schema as it would confuse the docs
     * (at least after https://github.com/plotly/documentation/issues/202 gets done!)
     */
    if(_module.layoutAttributes) {
        extendFlat(exports.traceLayoutAttributes, _module.layoutAttributes);
    }
}

function registerSubplot(_module) {
    var plotType = _module.name;

    if(exports.subplotsRegistry[plotType]) {
        Loggers.log('Plot type ' + plotType + ' already registered.');
        return;
    }

    // relayout array handling will look for component module methods with this
    // name and won't find them because this is a subplot module... but that
    // should be fine, it will just fall back on redrawing the plot.
    findArrayRegexps(_module);

    // not sure what's best for the 'cartesian' type at this point
    exports.subplotsRegistry[plotType] = _module;

    for(var componentName in exports.componentsRegistry) {
        mergeComponentAttrsToSubplot(componentName, _module.name);
    }
}

function registerComponentModule(_module) {
    if(typeof _module.name !== 'string') {
        throw new Error('Component module *name* must be a string.');
    }

    var name = _module.name;
    exports.componentsRegistry[name] = _module;

    if(_module.layoutAttributes) {
        if(_module.layoutAttributes._isLinkedToArray) {
            pushUnique(exports.layoutArrayContainers, name);
        }
        findArrayRegexps(_module);
    }

    for(var traceType in exports.modules) {
        mergeComponentAttrsToTrace(name, traceType);
    }

    for(var subplotName in exports.subplotsRegistry) {
        mergeComponentAttrsToSubplot(name, subplotName);
    }

    for(var transformType in exports.transformsRegistry) {
        mergeComponentAttrsToTransform(name, transformType);
    }

    if(_module.schema && _module.schema.layout) {
        extendDeepAll(baseLayoutAttributes, _module.schema.layout);
    }
}

function registerTransformModule(_module) {
    if(typeof _module.name !== 'string') {
        throw new Error('Transform module *name* must be a string.');
    }

    var prefix = 'Transform module ' + _module.name;
    var hasTransform = typeof _module.transform === 'function';
    var hasCalcTransform = typeof _module.calcTransform === 'function';

    if(!hasTransform && !hasCalcTransform) {
        throw new Error(prefix + ' is missing a *transform* or *calcTransform* method.');
    }
    if(hasTransform && hasCalcTransform) {
        Loggers.log([
            prefix + ' has both a *transform* and *calcTransform* methods.',
            'Please note that all *transform* methods are executed',
            'before all *calcTransform* methods.'
        ].join(' '));
    }
    if(!isPlainObject(_module.attributes)) {
        Loggers.log(prefix + ' registered without an *attributes* object.');
    }
    if(typeof _module.supplyDefaults !== 'function') {
        Loggers.log(prefix + ' registered without a *supplyDefaults* method.');
    }

    exports.transformsRegistry[_module.name] = _module;

    for(var componentName in exports.componentsRegistry) {
        mergeComponentAttrsToTransform(componentName, _module.name);
    }
}

function registerLocale(_module) {
    var locale = _module.name;
    var baseLocale = locale.split('-')[0];

    var newDict = _module.dictionary;
    var newFormat = _module.format;
    var hasDict = newDict && Object.keys(newDict).length;
    var hasFormat = newFormat && Object.keys(newFormat).length;

    var locales = exports.localeRegistry;

    var localeObj = locales[locale];
    if(!localeObj) locales[locale] = localeObj = {};

    // Should we use this dict for the base locale?
    // In case we're overwriting a previous dict for this locale, check
    // whether the base matches the full locale dict now. If we're not
    // overwriting, locales[locale] is undefined so this just checks if
    // baseLocale already had a dict or not.
    // Same logic for dateFormats
    if(baseLocale !== locale) {
        var baseLocaleObj = locales[baseLocale];
        if(!baseLocaleObj) locales[baseLocale] = baseLocaleObj = {};

        if(hasDict && baseLocaleObj.dictionary === localeObj.dictionary) {
            baseLocaleObj.dictionary = newDict;
        }
        if(hasFormat && baseLocaleObj.format === localeObj.format) {
            baseLocaleObj.format = newFormat;
        }
    }

    if(hasDict) localeObj.dictionary = newDict;
    if(hasFormat) localeObj.format = newFormat;
}

function findArrayRegexps(_module) {
    if(_module.layoutAttributes) {
        var arrayAttrRegexps = _module.layoutAttributes._arrayAttrRegexps;
        if(arrayAttrRegexps) {
            for(var i = 0; i < arrayAttrRegexps.length; i++) {
                pushUnique(exports.layoutArrayRegexes, arrayAttrRegexps[i]);
            }
        }
    }
}

function mergeComponentAttrsToTrace(componentName, traceType) {
    var componentSchema = exports.componentsRegistry[componentName].schema;
    if(!componentSchema || !componentSchema.traces) return;

    var traceAttrs = componentSchema.traces[traceType];
    if(traceAttrs) {
        extendDeepAll(exports.modules[traceType]._module.attributes, traceAttrs);
    }
}

function mergeComponentAttrsToTransform(componentName, transformType) {
    var componentSchema = exports.componentsRegistry[componentName].schema;
    if(!componentSchema || !componentSchema.transforms) return;

    var transformAttrs = componentSchema.transforms[transformType];
    if(transformAttrs) {
        extendDeepAll(exports.transformsRegistry[transformType].attributes, transformAttrs);
    }
}

function mergeComponentAttrsToSubplot(componentName, subplotName) {
    var componentSchema = exports.componentsRegistry[componentName].schema;
    if(!componentSchema || !componentSchema.subplots) return;

    var subplotModule = exports.subplotsRegistry[subplotName];
    var subplotAttrs = subplotModule.layoutAttributes;
    var subplotAttr = subplotModule.attr === 'subplot' ? subplotModule.name : subplotModule.attr;
    if(Array.isArray(subplotAttr)) subplotAttr = subplotAttr[0];

    var componentLayoutAttrs = componentSchema.subplots[subplotAttr];
    if(subplotAttrs && componentLayoutAttrs) {
        extendDeepAll(subplotAttrs, componentLayoutAttrs);
    }
}

function getTraceType(traceType) {
    if(typeof traceType === 'object') traceType = traceType.type;
    return traceType;
}

},{"./lib/extend":684,"./lib/is_plain_object":695,"./lib/loggers":698,"./lib/noop":703,"./lib/push_unique":708,"./plots/attributes":739,"./plots/layout_attributes":797}],826:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../lib');

var extendFlat = Lib.extendFlat;
var extendDeep = Lib.extendDeep;

// Put default plotTile layouts here
function cloneLayoutOverride(tileClass) {
    var override;

    switch(tileClass) {
        case 'themes__thumb':
            override = {
                autosize: true,
                width: 150,
                height: 150,
                title: {text: ''},
                showlegend: false,
                margin: {l: 5, r: 5, t: 5, b: 5, pad: 0},
                annotations: []
            };
            break;

        case 'thumbnail':
            override = {
                title: {text: ''},
                hidesources: true,
                showlegend: false,
                borderwidth: 0,
                bordercolor: '',
                margin: {l: 1, r: 1, t: 1, b: 1, pad: 0},
                annotations: []
            };
            break;

        default:
            override = {};
    }


    return override;
}

function keyIsAxis(keyName) {
    var types = ['xaxis', 'yaxis', 'zaxis'];
    return (types.indexOf(keyName.slice(0, 5)) > -1);
}


module.exports = function clonePlot(graphObj, options) {

    // Polar plot compatibility
    if(graphObj.framework && graphObj.framework.isPolar) {
        graphObj = graphObj.framework.getConfig();
    }

    var i;
    var oldData = graphObj.data;
    var oldLayout = graphObj.layout;
    var newData = extendDeep([], oldData);
    var newLayout = extendDeep({}, oldLayout, cloneLayoutOverride(options.tileClass));
    var context = graphObj._context || {};

    if(options.width) newLayout.width = options.width;
    if(options.height) newLayout.height = options.height;

    if(options.tileClass === 'thumbnail' || options.tileClass === 'themes__thumb') {
        // kill annotations
        newLayout.annotations = [];
        var keys = Object.keys(newLayout);

        for(i = 0; i < keys.length; i++) {
            if(keyIsAxis(keys[i])) {
                newLayout[keys[i]].title = {text: ''};
            }
        }

        // kill colorbar and pie labels
        for(i = 0; i < newData.length; i++) {
            var trace = newData[i];
            trace.showscale = false;
            if(trace.marker) trace.marker.showscale = false;
            if(trace.type === 'pie') trace.textposition = 'none';
        }
    }

    if(Array.isArray(options.annotations)) {
        for(i = 0; i < options.annotations.length; i++) {
            newLayout.annotations.push(options.annotations[i]);
        }
    }

    // TODO: does this scene modification really belong here?
    // If we still need it, can it move into the gl3d module?
    var sceneIds = Object.keys(newLayout).filter(function(key) {
        return key.match(/^scene\d*$/);
    });
    if(sceneIds.length) {
        var axesImageOverride = {};
        if(options.tileClass === 'thumbnail') {
            axesImageOverride = {
                title: {text: ''},
                showaxeslabels: false,
                showticklabels: false,
                linetickenable: false
            };
        }
        for(i = 0; i < sceneIds.length; i++) {
            var scene = newLayout[sceneIds[i]];

            if(!scene.xaxis) {
                scene.xaxis = {};
            }

            if(!scene.yaxis) {
                scene.yaxis = {};
            }

            if(!scene.zaxis) {
                scene.zaxis = {};
            }

            extendFlat(scene.xaxis, axesImageOverride);
            extendFlat(scene.yaxis, axesImageOverride);
            extendFlat(scene.zaxis, axesImageOverride);

            // TODO what does this do?
            scene._scene = null;
        }
    }

    var gd = document.createElement('div');
    if(options.tileClass) gd.className = options.tileClass;

    var plotTile = {
        gd: gd,
        td: gd, // for external (image server) compatibility
        layout: newLayout,
        data: newData,
        config: {
            staticPlot: (options.staticPlot === undefined) ?
                true :
                options.staticPlot,
            plotGlPixelRatio: (options.plotGlPixelRatio === undefined) ?
                2 :
                options.plotGlPixelRatio,
            displaylogo: options.displaylogo || false,
            showLink: options.showLink || false,
            showTips: options.showTips || false,
            mapboxAccessToken: context.mapboxAccessToken
        }
    };

    if(options.setBackground !== 'transparent') {
        plotTile.config.setBackground = options.setBackground || 'opaque';
    }

    // attaching the default Layout the gd, so you can grab it later
    plotTile.gd.defaultLayout = cloneLayoutOverride(options.tileClass);

    return plotTile;
};

},{"../lib":694}],827:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var toImage = _dereq_('../plot_api/to_image');
var Lib = _dereq_('../lib'); // for isIE
var fileSaver = _dereq_('./filesaver');

/** Plotly.downloadImage
 *
 * @param {object | string | HTML div} gd
 *   can either be a data/layout/config object
 *   or an existing graph <div>
 *   or an id to an existing graph <div>
 * @param {object} opts (see ../plot_api/to_image)
 * @return {promise}
 */
function downloadImage(gd, opts) {
    var _gd;
    if(!Lib.isPlainObject(gd)) _gd = Lib.getGraphDiv(gd);

    // check for undefined opts
    opts = opts || {};
    // default to png
    opts.format = opts.format || 'png';

    return new Promise(function(resolve, reject) {
        if(_gd && _gd._snapshotInProgress) {
            reject(new Error('Snapshotting already in progress.'));
        }

        // see comments within svgtoimg for additional
        //   discussion of problems with IE
        //   can now draw to canvas, but CORS tainted canvas
        //   does not allow toDataURL
        //   svg format will work though
        if(Lib.isIE() && opts.format !== 'svg') {
            reject(new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.'));
        }

        if(_gd) _gd._snapshotInProgress = true;
        var promise = toImage(gd, opts);

        var filename = opts.filename || gd.fn || 'newplot';
        filename += '.' + opts.format;

        promise.then(function(result) {
            if(_gd) _gd._snapshotInProgress = false;
            return fileSaver(result, filename);
        }).then(function(name) {
            resolve(name);
        }).catch(function(err) {
            if(_gd) _gd._snapshotInProgress = false;
            reject(err);
        });
    });
}

module.exports = downloadImage;

},{"../lib":694,"../plot_api/to_image":735,"./filesaver":828}],828:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

/*
* substantial portions of this code from FileSaver.js
* https://github.com/eligrey/FileSaver.js
* License: https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
* FileSaver.js
* A saveAs() FileSaver implementation.
* 1.1.20160328
*
* By Eli Grey, http://eligrey.com
* License: MIT
*   See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
*/

'use strict';

var fileSaver = function(url, name) {
    var saveLink = document.createElement('a');
    var canUseSaveLink = 'download' in saveLink;
    var isSafari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent);
    var promise = new Promise(function(resolve, reject) {
        // IE <10 is explicitly unsupported
        if(typeof navigator !== 'undefined' && /MSIE [1-9]\./.test(navigator.userAgent)) {
            reject(new Error('IE < 10 unsupported'));
        }

        // First try a.download, then web filesystem, then object URLs
        if(isSafari) {
            // Safari doesn't allow downloading of blob urls
            document.location.href = 'data:application/octet-stream' + url.slice(url.search(/[,;]/));
            resolve(name);
        }

        if(!name) {
            name = 'download';
        }

        if(canUseSaveLink) {
            saveLink.href = url;
            saveLink.download = name;
            document.body.appendChild(saveLink);
            saveLink.click();
            document.body.removeChild(saveLink);
            resolve(name);
        }

        // IE 10+ (native saveAs)
        if(typeof navigator !== 'undefined' && navigator.msSaveBlob) {
            // At this point we are only dealing with a SVG encoded as
            // a data URL (since IE only supports SVG)
            var encoded = url.split(/^data:image\/svg\+xml,/)[1];
            var svg = decodeURIComponent(encoded);
            navigator.msSaveBlob(new Blob([svg]), name);
            resolve(name);
        }

        reject(new Error('download error'));
    });

    return promise;
};

module.exports = fileSaver;

},{}],829:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

exports.getDelay = function(fullLayout) {
    if(!fullLayout._has) return 0;

    return (
        fullLayout._has('gl3d') ||
        fullLayout._has('gl2d') ||
        fullLayout._has('mapbox')
    ) ? 500 : 0;
};

exports.getRedrawFunc = function(gd) {
    var fullLayout = gd._fullLayout || {};
    var hasPolar = fullLayout._has && fullLayout._has('polar');
    var hasLegacyPolar = !hasPolar && gd.data && gd.data[0] && gd.data[0].r;

    // do not work for legacy polar
    if(hasLegacyPolar) return;

    return function() {
        (gd.calcdata || []).forEach(function(d) {
            if(d[0] && d[0].t && d[0].t.cb) d[0].t.cb();
        });
    };
};

},{}],830:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var helpers = _dereq_('./helpers');

var Snapshot = {
    getDelay: helpers.getDelay,
    getRedrawFunc: helpers.getRedrawFunc,
    clone: _dereq_('./cloneplot'),
    toSVG: _dereq_('./tosvg'),
    svgToImg: _dereq_('./svgtoimg'),
    toImage: _dereq_('./toimage'),
    downloadImage: _dereq_('./download')
};

module.exports = Snapshot;

},{"./cloneplot":826,"./download":827,"./helpers":829,"./svgtoimg":831,"./toimage":832,"./tosvg":833}],831:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../lib');
var EventEmitter = _dereq_('events').EventEmitter;

function svgToImg(opts) {
    var ev = opts.emitter || new EventEmitter();

    var promise = new Promise(function(resolve, reject) {
        var Image = window.Image;
        var svg = opts.svg;
        var format = opts.format || 'png';

        // IE only support svg
        if(Lib.isIE() && format !== 'svg') {
            var ieSvgError = new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.');
            reject(ieSvgError);
            // eventually remove the ev
            //  in favor of promises
            if(!opts.promise) {
                return ev.emit('error', ieSvgError);
            } else {
                return promise;
            }
        }

        var canvas = opts.canvas;
        var scale = opts.scale || 1;
        var w0 = opts.width || 300;
        var h0 = opts.height || 150;
        var w1 = scale * w0;
        var h1 = scale * h0;

        var ctx = canvas.getContext('2d');
        var img = new Image();

        // for Safari support, eliminate createObjectURL
        //  this decision could cause problems if content
        //  is not restricted to svg
        var url = 'data:image/svg+xml,' + encodeURIComponent(svg);

        canvas.width = w1;
        canvas.height = h1;

        img.onload = function() {
            var imgData;

            // don't need to draw to canvas if svg
            //  save some time and also avoid failure on IE
            if(format !== 'svg') {
                ctx.drawImage(img, 0, 0, w1, h1);
            }

            switch(format) {
                case 'jpeg':
                    imgData = canvas.toDataURL('image/jpeg');
                    break;
                case 'png':
                    imgData = canvas.toDataURL('image/png');
                    break;
                case 'webp':
                    imgData = canvas.toDataURL('image/webp');
                    break;
                case 'svg':
                    imgData = url;
                    break;
                default:
                    var errorMsg = 'Image format is not jpeg, png, svg or webp.';
                    reject(new Error(errorMsg));
                    // eventually remove the ev
                    //  in favor of promises
                    if(!opts.promise) {
                        return ev.emit('error', errorMsg);
                    }
            }
            resolve(imgData);
            // eventually remove the ev
            //  in favor of promises
            if(!opts.promise) {
                ev.emit('success', imgData);
            }
        };

        img.onerror = function(err) {
            reject(err);
            // eventually remove the ev
            //  in favor of promises
            if(!opts.promise) {
                return ev.emit('error', err);
            }
        };

        img.src = url;
    });

    // temporary for backward compatibility
    //  move to only Promise in 2.0.0
    //  and eliminate the EventEmitter
    if(opts.promise) {
        return promise;
    }

    return ev;
}

module.exports = svgToImg;

},{"../lib":694,"events":93}],832:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var EventEmitter = _dereq_('events').EventEmitter;

var Registry = _dereq_('../registry');
var Lib = _dereq_('../lib');

var helpers = _dereq_('./helpers');
var clonePlot = _dereq_('./cloneplot');
var toSVG = _dereq_('./tosvg');
var svgToImg = _dereq_('./svgtoimg');

/**
 * @param {object} gd figure Object
 * @param {object} opts option object
 * @param opts.format 'jpeg' | 'png' | 'webp' | 'svg'
 */
function toImage(gd, opts) {

    // first clone the GD so we can operate in a clean environment
    var ev = new EventEmitter();

    var clone = clonePlot(gd, {format: 'png'});
    var clonedGd = clone.gd;

    // put the cloned div somewhere off screen before attaching to DOM
    clonedGd.style.position = 'absolute';
    clonedGd.style.left = '-5000px';
    document.body.appendChild(clonedGd);

    function wait() {
        var delay = helpers.getDelay(clonedGd._fullLayout);

        setTimeout(function() {
            var svg = toSVG(clonedGd);

            var canvas = document.createElement('canvas');
            canvas.id = Lib.randstr();

            ev = svgToImg({
                format: opts.format,
                width: clonedGd._fullLayout.width,
                height: clonedGd._fullLayout.height,
                canvas: canvas,
                emitter: ev,
                svg: svg
            });

            ev.clean = function() {
                if(clonedGd) document.body.removeChild(clonedGd);
            };

        }, delay);
    }

    var redrawFunc = helpers.getRedrawFunc(clonedGd);

    Registry.call('plot', clonedGd, clone.data, clone.layout, clone.config)
        .then(redrawFunc)
        .then(wait)
        .catch(function(err) {
            ev.emit('error', err);
        });


    return ev;
}

module.exports = toImage;

},{"../lib":694,"../registry":825,"./cloneplot":826,"./helpers":829,"./svgtoimg":831,"./tosvg":833,"events":93}],833:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

var Lib = _dereq_('../lib');
var Drawing = _dereq_('../components/drawing');
var Color = _dereq_('../components/color');

var xmlnsNamespaces = _dereq_('../constants/xmlns_namespaces');
var DOUBLEQUOTE_REGEX = /"/g;
var DUMMY_SUB = 'TOBESTRIPPED';
var DUMMY_REGEX = new RegExp('("' + DUMMY_SUB + ')|(' + DUMMY_SUB + '")', 'g');

function htmlEntityDecode(s) {
    var hiddenDiv = d3.select('body').append('div').style({display: 'none'}).html('');
    var replaced = s.replace(/(&[^;]*;)/gi, function(d) {
        if(d === '&lt;') { return '&#60;'; } // special handling for brackets
        if(d === '&rt;') { return '&#62;'; }
        if(d.indexOf('<') !== -1 || d.indexOf('>') !== -1) { return ''; }
        return hiddenDiv.html(d).text(); // everything else, let the browser decode it to unicode
    });
    hiddenDiv.remove();
    return replaced;
}

function xmlEntityEncode(str) {
    return str.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g, '&amp;');
}

module.exports = function toSVG(gd, format, scale) {
    var fullLayout = gd._fullLayout;
    var svg = fullLayout._paper;
    var toppaper = fullLayout._toppaper;
    var width = fullLayout.width;
    var height = fullLayout.height;
    var i;

    // make background color a rect in the svg, then revert after scraping
    // all other alterations have been dealt with by properly preparing the svg
    // in the first place... like setting cursors with css classes so we don't
    // have to remove them, and providing the right namespaces in the svg to
    // begin with
    svg.insert('rect', ':first-child')
        .call(Drawing.setRect, 0, 0, width, height)
        .call(Color.fill, fullLayout.paper_bgcolor);

    // subplot-specific to-SVG methods
    // which notably add the contents of the gl-container
    // into the main svg node
    var basePlotModules = fullLayout._basePlotModules || [];
    for(i = 0; i < basePlotModules.length; i++) {
        var _module = basePlotModules[i];

        if(_module.toSVG) _module.toSVG(gd);
    }

    // add top items above them assumes everything in toppaper is either
    // a group or a defs, and if it's empty (like hoverlayer) we can ignore it.
    if(toppaper) {
        var nodes = toppaper.node().childNodes;

        // make copy of nodes as childNodes prop gets mutated in loop below
        var topGroups = Array.prototype.slice.call(nodes);

        for(i = 0; i < topGroups.length; i++) {
            var topGroup = topGroups[i];

            if(topGroup.childNodes.length) svg.node().appendChild(topGroup);
        }
    }

    // remove draglayer for Adobe Illustrator compatibility
    if(fullLayout._draggers) {
        fullLayout._draggers.remove();
    }

    // in case the svg element had an explicit background color, remove this
    // we want the rect to get the color so it's the right size; svg bg will
    // fill whatever container it's displayed in regardless of plot size.
    svg.node().style.background = '';

    svg.selectAll('text')
        .attr({'data-unformatted': null, 'data-math': null})
        .each(function() {
            var txt = d3.select(this);

            // hidden text is pre-formatting mathjax, the browser ignores it
            // but in a static plot it's useless and it can confuse batik
            // we've tried to standardize on display:none but make sure we still
            // catch visibility:hidden if it ever arises
            if(this.style.visibility === 'hidden' || this.style.display === 'none') {
                txt.remove();
                return;
            }
            else {
                // clear other visibility/display values to default
                // to not potentially confuse non-browser SVG implementations
                txt.style({visibility: null, display: null});
            }

            // Font family styles break things because of quotation marks,
            // so we must remove them *after* the SVG DOM has been serialized
            // to a string (browsers convert singles back)
            var ff = this.style.fontFamily;
            if(ff && ff.indexOf('"') !== -1) {
                txt.style('font-family', ff.replace(DOUBLEQUOTE_REGEX, DUMMY_SUB));
            }
        });

    svg.selectAll('.point, .scatterpts, .legendfill>path, .legendlines>path, .cbfill').each(function() {
        var pt = d3.select(this);

        // similar to font family styles above,
        // we must remove " after the SVG DOM has been serialized
        var fill = this.style.fill;
        if(fill && fill.indexOf('url(') !== -1) {
            pt.style('fill', fill.replace(DOUBLEQUOTE_REGEX, DUMMY_SUB));
        }

        var stroke = this.style.stroke;
        if(stroke && stroke.indexOf('url(') !== -1) {
            pt.style('stroke', stroke.replace(DOUBLEQUOTE_REGEX, DUMMY_SUB));
        }
    });

    if(format === 'pdf' || format === 'eps') {
        // these formats make the extra line MathJax adds around symbols look super thick in some cases
        // it looks better if this is removed entirely.
        svg.selectAll('#MathJax_SVG_glyphs path')
            .attr('stroke-width', 0);
    }

    // fix for IE namespacing quirk?
    // http://stackoverflow.com/questions/19610089/unwanted-namespaces-on-svg-markup-when-using-xmlserializer-in-javascript-with-ie
    svg.node().setAttributeNS(xmlnsNamespaces.xmlns, 'xmlns', xmlnsNamespaces.svg);
    svg.node().setAttributeNS(xmlnsNamespaces.xmlns, 'xmlns:xlink', xmlnsNamespaces.xlink);

    if(format === 'svg' && scale) {
        svg.attr('width', scale * width);
        svg.attr('height', scale * height);
        svg.attr('viewBox', '0 0 ' + width + ' ' + height);
    }

    var s = new window.XMLSerializer().serializeToString(svg.node());
    s = htmlEntityDecode(s);
    s = xmlEntityEncode(s);

    // Fix quotations around font strings and gradient URLs
    s = s.replace(DUMMY_REGEX, '\'');

    // IE is very strict, so we will need to clean
    //  svg with the following regex
    //  yes this is messy, but do not know a better way
    // Even with this IE will not work due to tainted canvas
    //  see https://github.com/kangax/fabric.js/issues/1957
    //      http://stackoverflow.com/questions/18112047/canvas-todataurl-working-in-all-browsers-except-ie10
    // Leave here just in case the CORS/tainted IE issue gets resolved
    if(Lib.isIE()) {
        // replace double quote with single quote
        s = s.replace(/"/gi, '\'');
        // url in svg are single quoted
        //   since we changed double to single
        //   we'll need to change these to double-quoted
        s = s.replace(/(\('#)([^']*)('\))/gi, '(\"#$2\")');
        // font names with spaces will be escaped single-quoted
        //   we'll need to change these to double-quoted
        s = s.replace(/(\\')/gi, '\"');
    }

    return s;
};

},{"../components/color":571,"../components/drawing":592,"../constants/xmlns_namespaces":672,"../lib":694,"d3":149}],834:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var mergeArray = _dereq_('../../lib').mergeArray;


// arrayOk attributes, merge them into calcdata array
module.exports = function arraysToCalcdata(cd, trace) {
    for(var i = 0; i < cd.length; i++) cd[i].i = i;

    mergeArray(trace.text, cd, 'tx');
    mergeArray(trace.hovertext, cd, 'htx');

    var marker = trace.marker;
    if(marker) {
        mergeArray(marker.opacity, cd, 'mo');
        mergeArray(marker.color, cd, 'mc');

        var markerLine = marker.line;
        if(markerLine) {
            mergeArray(markerLine.color, cd, 'mlc');
            mergeArray(markerLine.width, cd, 'mlw');
        }
    }
};

},{"../../lib":694}],835:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterAttrs = _dereq_('../scatter/attributes');
var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var colorAttributes = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
var fontAttrs = _dereq_('../../plots/font_attributes');
var constants = _dereq_('./constants.js');

var extendFlat = _dereq_('../../lib/extend').extendFlat;

var textFontAttrs = fontAttrs({
    editType: 'calc',
    arrayOk: true,
    colorEditType: 'style',
    
});

var scatterMarkerAttrs = scatterAttrs.marker;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;

var markerLineWidth = extendFlat({},
    scatterMarkerLineAttrs.width, { dflt: 0 });

var markerLine = extendFlat({
    width: markerLineWidth,
    editType: 'calc'
}, colorAttributes('marker.line'));

var marker = extendFlat({
    line: markerLine,
    editType: 'calc'
}, colorAttributes('marker'), {
    colorbar: colorbarAttrs,
    opacity: {
        valType: 'number',
        arrayOk: true,
        dflt: 1,
        min: 0,
        max: 1,
        
        editType: 'style',
        
    }
});

module.exports = {
    x: scatterAttrs.x,
    x0: scatterAttrs.x0,
    dx: scatterAttrs.dx,
    y: scatterAttrs.y,
    y0: scatterAttrs.y0,
    dy: scatterAttrs.dy,

    text: scatterAttrs.text,
    hovertext: scatterAttrs.hovertext,
    hovertemplate: hovertemplateAttrs({}, {
        keys: constants.eventDataKeys
    }),

    textposition: {
        valType: 'enumerated',
        
        values: ['inside', 'outside', 'auto', 'none'],
        dflt: 'none',
        arrayOk: true,
        editType: 'calc',
        
    },

    textfont: extendFlat({}, textFontAttrs, {
        
    }),

    insidetextfont: extendFlat({}, textFontAttrs, {
        
    }),

    outsidetextfont: extendFlat({}, textFontAttrs, {
        
    }),

    constraintext: {
        valType: 'enumerated',
        values: ['inside', 'outside', 'both', 'none'],
        
        dflt: 'both',
        editType: 'calc',
        
    },

    cliponaxis: extendFlat({}, scatterAttrs.cliponaxis, {
        
    }),

    orientation: {
        valType: 'enumerated',
        
        values: ['v', 'h'],
        editType: 'calc+clearAxisTypes',
        
    },

    base: {
        valType: 'any',
        dflt: null,
        arrayOk: true,
        
        editType: 'calc',
        
    },

    offset: {
        valType: 'number',
        dflt: null,
        arrayOk: true,
        
        editType: 'calc',
        
    },

    width: {
        valType: 'number',
        dflt: null,
        min: 0,
        arrayOk: true,
        
        editType: 'calc',
        
    },

    marker: marker,

    selected: {
        marker: {
            opacity: scatterAttrs.selected.marker.opacity,
            color: scatterAttrs.selected.marker.color,
            editType: 'style'
        },
        textfont: scatterAttrs.selected.textfont,
        editType: 'style'
    },
    unselected: {
        marker: {
            opacity: scatterAttrs.unselected.marker.opacity,
            color: scatterAttrs.unselected.marker.color,
            editType: 'style'
        },
        textfont: scatterAttrs.unselected.textfont,
        editType: 'style'
    },

    r: scatterAttrs.r,
    t: scatterAttrs.t,

    _deprecated: {
        bardir: {
            valType: 'enumerated',
            
            editType: 'calc',
            values: ['v', 'h'],
            
        }
    }
};

},{"../../components/colorbar/attributes":572,"../../components/colorscale/attributes":578,"../../components/fx/hovertemplate_attributes":609,"../../lib/extend":684,"../../plots/font_attributes":769,"../scatter/attributes":1047,"./constants.js":837}],836:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Axes = _dereq_('../../plots/cartesian/axes');
var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
var colorscaleCalc = _dereq_('../../components/colorscale/calc');
var arraysToCalcdata = _dereq_('./arrays_to_calcdata');
var calcSelection = _dereq_('../scatter/calc_selection');

module.exports = function calc(gd, trace) {
    var xa = Axes.getFromId(gd, trace.xaxis || 'x');
    var ya = Axes.getFromId(gd, trace.yaxis || 'y');
    var size, pos;

    if(trace.orientation === 'h') {
        size = xa.makeCalcdata(trace, 'x');
        pos = ya.makeCalcdata(trace, 'y');
    } else {
        size = ya.makeCalcdata(trace, 'y');
        pos = xa.makeCalcdata(trace, 'x');
    }

    // create the "calculated data" to plot
    var serieslen = Math.min(pos.length, size.length);
    var cd = new Array(serieslen);

    // set position and size
    for(var i = 0; i < serieslen; i++) {
        cd[i] = { p: pos[i], s: size[i] };

        if(trace.ids) {
            cd[i].id = String(trace.ids[i]);
        }
    }

    // auto-z and autocolorscale if applicable
    if(hasColorscale(trace, 'marker')) {
        colorscaleCalc(gd, trace, {
            vals: trace.marker.color,
            containerStr: 'marker',
            cLetter: 'c'
        });
    }
    if(hasColorscale(trace, 'marker.line')) {
        colorscaleCalc(gd, trace, {
            vals: trace.marker.line.color,
            containerStr: 'marker.line',
            cLetter: 'c'
        });
    }

    arraysToCalcdata(cd, trace);
    calcSelection(cd, trace);

    return cd;
};

},{"../../components/colorscale/calc":579,"../../components/colorscale/helpers":582,"../../plots/cartesian/axes":742,"../scatter/calc_selection":1049,"./arrays_to_calcdata":834}],837:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = {
    eventDataKeys: []
};

},{}],838:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

var Registry = _dereq_('../../registry');
var Axes = _dereq_('../../plots/cartesian/axes');
var Sieve = _dereq_('./sieve.js');

/*
 * Bar chart stacking/grouping positioning and autoscaling calculations
 * for each direction separately calculate the ranges and positions
 * note that this handles histograms too
 * now doing this one subplot at a time
 */

function crossTraceCalc(gd, plotinfo) {
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    var fullTraces = gd._fullData;
    var calcTraces = gd.calcdata;
    var calcTracesHorizontal = [];
    var calcTracesVertical = [];

    for(var i = 0; i < fullTraces.length; i++) {
        var fullTrace = fullTraces[i];
        if(
            fullTrace.visible === true &&
            Registry.traceIs(fullTrace, 'bar') &&
            fullTrace.xaxis === xa._id &&
            fullTrace.yaxis === ya._id
        ) {
            if(fullTrace.orientation === 'h') {
                calcTracesHorizontal.push(calcTraces[i]);
            } else {
                calcTracesVertical.push(calcTraces[i]);
            }
        }
    }

    setGroupPositions(gd, xa, ya, calcTracesVertical);
    setGroupPositions(gd, ya, xa, calcTracesHorizontal);
}

function setGroupPositions(gd, pa, sa, calcTraces) {
    if(!calcTraces.length) return;

    var barmode = gd._fullLayout.barmode;
    var overlay = (barmode === 'overlay');
    var group = (barmode === 'group');
    var excluded;
    var included;
    var i, calcTrace, fullTrace;

    initBase(gd, pa, sa, calcTraces);

    if(overlay) {
        setGroupPositionsInOverlayMode(gd, pa, sa, calcTraces);
    } else if(group) {
        // exclude from the group those traces for which the user set an offset
        excluded = [];
        included = [];
        for(i = 0; i < calcTraces.length; i++) {
            calcTrace = calcTraces[i];
            fullTrace = calcTrace[0].trace;

            if(fullTrace.offset === undefined) included.push(calcTrace);
            else excluded.push(calcTrace);
        }

        if(included.length) {
            setGroupPositionsInGroupMode(gd, pa, sa, included);
        }
        if(excluded.length) {
            setGroupPositionsInOverlayMode(gd, pa, sa, excluded);
        }
    } else {
        // exclude from the stack those traces for which the user set a base
        excluded = [];
        included = [];
        for(i = 0; i < calcTraces.length; i++) {
            calcTrace = calcTraces[i];
            fullTrace = calcTrace[0].trace;

            if(fullTrace.base === undefined) included.push(calcTrace);
            else excluded.push(calcTrace);
        }

        if(included.length) {
            setGroupPositionsInStackOrRelativeMode(gd, pa, sa, included);
        }
        if(excluded.length) {
            setGroupPositionsInOverlayMode(gd, pa, sa, excluded);
        }
    }

    collectExtents(calcTraces, pa);
}

function initBase(gd, pa, sa, calcTraces) {
    var i, j;

    for(i = 0; i < calcTraces.length; i++) {
        var cd = calcTraces[i];
        var trace = cd[0].trace;
        var base = trace.base;
        var b;

        // not sure if it really makes sense to have dates for bar size data...
        // ideally if we want to make gantt charts or something we'd treat
        // the actual size (trace.x or y) as time delta but base as absolute
        // time. But included here for completeness.
        var scalendar = trace.orientation === 'h' ? trace.xcalendar : trace.ycalendar;

        // 'base' on categorical axes makes no sense
        var d2c = sa.type === 'category' || sa.type === 'multicategory' ?
            function() { return null; } :
            sa.d2c;

        if(isArrayOrTypedArray(base)) {
            for(j = 0; j < Math.min(base.length, cd.length); j++) {
                b = d2c(base[j], 0, scalendar);
                if(isNumeric(b)) {
                    cd[j].b = +b;
                    cd[j].hasB = 1;
                }
                else cd[j].b = 0;
            }
            for(; j < cd.length; j++) {
                cd[j].b = 0;
            }
        } else {
            b = d2c(base, 0, scalendar);
            var hasBase = isNumeric(b);
            b = hasBase ? b : 0;
            for(j = 0; j < cd.length; j++) {
                cd[j].b = b;
                if(hasBase) cd[j].hasB = 1;
            }
        }
    }
}

function setGroupPositionsInOverlayMode(gd, pa, sa, calcTraces) {
    var barnorm = gd._fullLayout.barnorm;
    var separateNegativeValues = false;
    var dontMergeOverlappingData = !barnorm;

    // update position axis and set bar offsets and widths
    for(var i = 0; i < calcTraces.length; i++) {
        var calcTrace = calcTraces[i];
        var sieve = new Sieve([calcTrace], separateNegativeValues, dontMergeOverlappingData);

        // set bar offsets and widths, and update position axis
        setOffsetAndWidth(gd, pa, sieve);

        // set bar bases and sizes, and update size axis
        //
        // (note that `setGroupPositionsInOverlayMode` handles the case barnorm
        // is defined, because this function is also invoked for traces that
        // can't be grouped or stacked)
        if(barnorm) {
            sieveBars(gd, sa, sieve);
            normalizeBars(gd, sa, sieve);
        } else {
            setBaseAndTop(gd, sa, sieve);
        }
    }
}

function setGroupPositionsInGroupMode(gd, pa, sa, calcTraces) {
    var fullLayout = gd._fullLayout;
    var barnorm = fullLayout.barnorm;
    var separateNegativeValues = false;
    var dontMergeOverlappingData = !barnorm;
    var sieve = new Sieve(calcTraces, separateNegativeValues, dontMergeOverlappingData);

    // set bar offsets and widths, and update position axis
    setOffsetAndWidthInGroupMode(gd, pa, sieve);

    // set bar bases and sizes, and update size axis
    if(barnorm) {
        sieveBars(gd, sa, sieve);
        normalizeBars(gd, sa, sieve);
    } else {
        setBaseAndTop(gd, sa, sieve);
    }
}

function setGroupPositionsInStackOrRelativeMode(gd, pa, sa, calcTraces) {
    var fullLayout = gd._fullLayout;
    var barmode = fullLayout.barmode;
    var stack = barmode === 'stack';
    var relative = barmode === 'relative';
    var barnorm = fullLayout.barnorm;
    var separateNegativeValues = relative;
    var dontMergeOverlappingData = !(barnorm || stack || relative);
    var sieve = new Sieve(calcTraces, separateNegativeValues, dontMergeOverlappingData);

    // set bar offsets and widths, and update position axis
    setOffsetAndWidth(gd, pa, sieve);

    // set bar bases and sizes, and update size axis
    stackBars(gd, sa, sieve);

    // flag the outmost bar (for text display purposes)
    for(var i = 0; i < calcTraces.length; i++) {
        var calcTrace = calcTraces[i];

        for(var j = 0; j < calcTrace.length; j++) {
            var bar = calcTrace[j];

            if(bar.s !== BADNUM) {
                var isOutmostBar = ((bar.b + bar.s) === sieve.get(bar.p, bar.s));
                if(isOutmostBar) bar._outmost = true;
            }
        }
    }

    // Note that marking the outmost bars has to be done
    // before `normalizeBars` changes `bar.b` and `bar.s`.
    if(barnorm) normalizeBars(gd, sa, sieve);
}

function setOffsetAndWidth(gd, pa, sieve) {
    var fullLayout = gd._fullLayout;
    var bargap = fullLayout.bargap;
    var bargroupgap = fullLayout.bargroupgap || 0;
    var minDiff = sieve.minDiff;
    var calcTraces = sieve.traces;

    // set bar offsets and widths
    var barGroupWidth = minDiff * (1 - bargap);
    var barWidthPlusGap = barGroupWidth;
    var barWidth = barWidthPlusGap * (1 - bargroupgap);

    // computer bar group center and bar offset
    var offsetFromCenter = -barWidth / 2;

    for(var i = 0; i < calcTraces.length; i++) {
        var calcTrace = calcTraces[i];
        var t = calcTrace[0].t;

        // store bar width and offset for this trace
        t.barwidth = barWidth;
        t.poffset = offsetFromCenter;
        t.bargroupwidth = barGroupWidth;
        t.bardelta = minDiff;
    }

    // stack bars that only differ by rounding
    sieve.binWidth = calcTraces[0][0].t.barwidth / 100;

    // if defined, apply trace offset and width
    applyAttributes(sieve);

    // store the bar center in each calcdata item
    setBarCenterAndWidth(gd, pa, sieve);

    // update position axes
    updatePositionAxis(gd, pa, sieve);
}

function setOffsetAndWidthInGroupMode(gd, pa, sieve) {
    var fullLayout = gd._fullLayout;
    var bargap = fullLayout.bargap;
    var bargroupgap = fullLayout.bargroupgap || 0;
    var positions = sieve.positions;
    var distinctPositions = sieve.distinctPositions;
    var minDiff = sieve.minDiff;
    var calcTraces = sieve.traces;

    // if there aren't any overlapping positions,
    // let them have full width even if mode is group
    var overlap = (positions.length !== distinctPositions.length);

    var nTraces = calcTraces.length;
    var barGroupWidth = minDiff * (1 - bargap);
    var barWidthPlusGap = (overlap) ? barGroupWidth / nTraces : barGroupWidth;
    var barWidth = barWidthPlusGap * (1 - bargroupgap);

    for(var i = 0; i < nTraces; i++) {
        var calcTrace = calcTraces[i];
        var t = calcTrace[0].t;

        // computer bar group center and bar offset
        var offsetFromCenter = overlap ?
            ((2 * i + 1 - nTraces) * barWidthPlusGap - barWidth) / 2 :
            -barWidth / 2;

        // store bar width and offset for this trace
        t.barwidth = barWidth;
        t.poffset = offsetFromCenter;
        t.bargroupwidth = barGroupWidth;
        t.bardelta = minDiff;
    }

    // stack bars that only differ by rounding
    sieve.binWidth = calcTraces[0][0].t.barwidth / 100;

    // if defined, apply trace width
    applyAttributes(sieve);

    // store the bar center in each calcdata item
    setBarCenterAndWidth(gd, pa, sieve);

    // update position axes
    updatePositionAxis(gd, pa, sieve, overlap);
}

function applyAttributes(sieve) {
    var calcTraces = sieve.traces;
    var i, j;

    for(i = 0; i < calcTraces.length; i++) {
        var calcTrace = calcTraces[i];
        var calcTrace0 = calcTrace[0];
        var fullTrace = calcTrace0.trace;
        var t = calcTrace0.t;
        var offset = fullTrace._offset || fullTrace.offset;
        var initialPoffset = t.poffset;
        var newPoffset;

        if(isArrayOrTypedArray(offset)) {
            // if offset is an array, then clone it into t.poffset.
            newPoffset = Array.prototype.slice.call(offset, 0, calcTrace.length);

            // guard against non-numeric items
            for(j = 0; j < newPoffset.length; j++) {
                if(!isNumeric(newPoffset[j])) {
                    newPoffset[j] = initialPoffset;
                }
            }

            // if the length of the array is too short,
            // then extend it with the initial value of t.poffset
            for(j = newPoffset.length; j < calcTrace.length; j++) {
                newPoffset.push(initialPoffset);
            }

            t.poffset = newPoffset;
        } else if(offset !== undefined) {
            t.poffset = offset;
        }

        var width = fullTrace._width || fullTrace.width;
        var initialBarwidth = t.barwidth;

        if(isArrayOrTypedArray(width)) {
            // if width is an array, then clone it into t.barwidth.
            var newBarwidth = Array.prototype.slice.call(width, 0, calcTrace.length);

            // guard against non-numeric items
            for(j = 0; j < newBarwidth.length; j++) {
                if(!isNumeric(newBarwidth[j])) newBarwidth[j] = initialBarwidth;
            }

            // if the length of the array is too short,
            // then extend it with the initial value of t.barwidth
            for(j = newBarwidth.length; j < calcTrace.length; j++) {
                newBarwidth.push(initialBarwidth);
            }

            t.barwidth = newBarwidth;

            // if user didn't set offset,
            // then correct t.poffset to ensure bars remain centered
            if(offset === undefined) {
                newPoffset = [];
                for(j = 0; j < calcTrace.length; j++) {
                    newPoffset.push(
                        initialPoffset + (initialBarwidth - newBarwidth[j]) / 2
                    );
                }
                t.poffset = newPoffset;
            }
        } else if(width !== undefined) {
            t.barwidth = width;

            // if user didn't set offset,
            // then correct t.poffset to ensure bars remain centered
            if(offset === undefined) {
                t.poffset = initialPoffset + (initialBarwidth - width) / 2;
            }
        }
    }
}

function setBarCenterAndWidth(gd, pa, sieve) {
    var calcTraces = sieve.traces;
    var pLetter = getAxisLetter(pa);

    for(var i = 0; i < calcTraces.length; i++) {
        var calcTrace = calcTraces[i];
        var t = calcTrace[0].t;
        var poffset = t.poffset;
        var poffsetIsArray = Array.isArray(poffset);
        var barwidth = t.barwidth;
        var barwidthIsArray = Array.isArray(barwidth);

        for(var j = 0; j < calcTrace.length; j++) {
            var calcBar = calcTrace[j];

            // store the actual bar width and position, for use by hover
            var width = calcBar.w = barwidthIsArray ? barwidth[j] : barwidth;
            calcBar[pLetter] = calcBar.p + (poffsetIsArray ? poffset[j] : poffset) + width / 2;
        }
    }
}

function updatePositionAxis(gd, pa, sieve, allowMinDtick) {
    var calcTraces = sieve.traces;
    var minDiff = sieve.minDiff;
    var vpad = minDiff / 2;

    Axes.minDtick(pa, sieve.minDiff, sieve.distinctPositions[0], allowMinDtick);

    for(var i = 0; i < calcTraces.length; i++) {
        var calcTrace = calcTraces[i];
        var calcTrace0 = calcTrace[0];
        var fullTrace = calcTrace0.trace;
        var pts = [];
        var bar, l, r, j;

        for(j = 0; j < calcTrace.length; j++) {
            bar = calcTrace[j];
            l = bar.p - vpad;
            r = bar.p + vpad;
            pts.push(l, r);
        }

        if(fullTrace.width || fullTrace.offset) {
            var t = calcTrace0.t;
            var poffset = t.poffset;
            var barwidth = t.barwidth;
            var poffsetIsArray = Array.isArray(poffset);
            var barwidthIsArray = Array.isArray(barwidth);

            for(j = 0; j < calcTrace.length; j++) {
                bar = calcTrace[j];
                var calcBarOffset = poffsetIsArray ? poffset[j] : poffset;
                var calcBarWidth = barwidthIsArray ? barwidth[j] : barwidth;
                l = bar.p + calcBarOffset;
                r = l + calcBarWidth;
                pts.push(l, r);
            }
        }

        fullTrace._extremes[pa._id] = Axes.findExtremes(pa, pts, {padded: false});
    }
}

// store these bar bases and tops in calcdata
// and make sure the size axis includes zero,
// along with the bases and tops of each bar.
function setBaseAndTop(gd, sa, sieve) {
    var calcTraces = sieve.traces;
    var sLetter = getAxisLetter(sa);

    for(var i = 0; i < calcTraces.length; i++) {
        var calcTrace = calcTraces[i];
        var fullTrace = calcTrace[0].trace;
        var pts = [];
        var allBarBaseAboveZero = true;

        for(var j = 0; j < calcTrace.length; j++) {
            var bar = calcTrace[j];
            var barBase = bar.b;
            var barTop = barBase + bar.s;

            bar[sLetter] = barTop;
            pts.push(barTop);
            if(bar.hasB) pts.push(barBase);

            if(!bar.hasB || !(bar.b > 0 && bar.s > 0)) {
                allBarBaseAboveZero = false;
            }
        }

        fullTrace._extremes[sa._id] = Axes.findExtremes(sa, pts, {
            tozero: !allBarBaseAboveZero,
            padded: true
        });
    }
}

function stackBars(gd, sa, sieve) {
    var fullLayout = gd._fullLayout;
    var barnorm = fullLayout.barnorm;
    var sLetter = getAxisLetter(sa);
    var calcTraces = sieve.traces;

    for(var i = 0; i < calcTraces.length; i++) {
        var calcTrace = calcTraces[i];
        var fullTrace = calcTrace[0].trace;
        var pts = [];

        for(var j = 0; j < calcTrace.length; j++) {
            var bar = calcTrace[j];

            if(bar.s !== BADNUM) {
                // stack current bar and get previous sum
                var barBase = sieve.put(bar.p, bar.b + bar.s);
                var barTop = barBase + bar.b + bar.s;

                // store the bar base and top in each calcdata item
                bar.b = barBase;
                bar[sLetter] = barTop;

                if(!barnorm) {
                    pts.push(barTop);
                    if(bar.hasB) pts.push(barBase);
                }
            }
        }

        // if barnorm is set, let normalizeBars update the axis range
        if(!barnorm) {
            fullTrace._extremes[sa._id] = Axes.findExtremes(sa, pts, {
                // N.B. we don't stack base with 'base',
                // so set tozero:true always!
                tozero: true,
                padded: true
            });
        }
    }
}

function sieveBars(gd, sa, sieve) {
    var calcTraces = sieve.traces;

    for(var i = 0; i < calcTraces.length; i++) {
        var calcTrace = calcTraces[i];

        for(var j = 0; j < calcTrace.length; j++) {
            var bar = calcTrace[j];

            if(bar.s !== BADNUM) sieve.put(bar.p, bar.b + bar.s);
        }
    }
}

// Note:
//
// normalizeBars requires that either sieveBars or stackBars has been
// previously invoked.
function normalizeBars(gd, sa, sieve) {
    var fullLayout = gd._fullLayout;
    var calcTraces = sieve.traces;
    var sLetter = getAxisLetter(sa);
    var sTop = fullLayout.barnorm === 'fraction' ? 1 : 100;
    var sTiny = sTop / 1e9; // in case of rounding error in sum
    var sMin = sa.l2c(sa.c2l(0));
    var sMax = fullLayout.barmode === 'stack' ? sTop : sMin;

    function needsPadding(v) {
        return (
            isNumeric(sa.c2l(v)) &&
            ((v < sMin - sTiny) || (v > sMax + sTiny) || !isNumeric(sMin))
        );
    }

    for(var i = 0; i < calcTraces.length; i++) {
        var calcTrace = calcTraces[i];
        var fullTrace = calcTrace[0].trace;
        var pts = [];
        var allBarBaseAboveZero = true;
        var padded = false;

        for(var j = 0; j < calcTrace.length; j++) {
            var bar = calcTrace[j];

            if(bar.s !== BADNUM) {
                var scale = Math.abs(sTop / sieve.get(bar.p, bar.s));
                bar.b *= scale;
                bar.s *= scale;

                var barBase = bar.b;
                var barTop = barBase + bar.s;

                bar[sLetter] = barTop;
                pts.push(barTop);
                padded = padded || needsPadding(barTop);

                if(bar.hasB) {
                    pts.push(barBase);
                    padded = padded || needsPadding(barBase);
                }

                if(!bar.hasB || !(bar.b > 0 && bar.s > 0)) {
                    allBarBaseAboveZero = false;
                }
            }
        }

        fullTrace._extremes[sa._id] = Axes.findExtremes(sa, pts, {
            tozero: !allBarBaseAboveZero,
            padded: padded
        });
    }
}

// find the full position span of bars at each position
// for use by hover, to ensure labels move in if bars are
// narrower than the space they're in.
// run once per trace group (subplot & direction) and
// the same mapping is attached to all calcdata traces
function collectExtents(calcTraces, pa) {
    var pLetter = getAxisLetter(pa);
    var extents = {};
    var i, j, cd;

    var pMin = Infinity;
    var pMax = -Infinity;

    for(i = 0; i < calcTraces.length; i++) {
        cd = calcTraces[i];
        for(j = 0; j < cd.length; j++) {
            var p = cd[j].p;
            if(isNumeric(p)) {
                pMin = Math.min(pMin, p);
                pMax = Math.max(pMax, p);
            }
        }
    }

    // this is just for positioning of hover labels, and nobody will care if
    // the label is 1px too far out; so round positions to 1/10K in case
    // position values don't exactly match from trace to trace
    var roundFactor = 10000 / (pMax - pMin);
    var round = extents.round = function(p) {
        return String(Math.round(roundFactor * (p - pMin)));
    };

    for(i = 0; i < calcTraces.length; i++) {
        cd = calcTraces[i];
        cd[0].t.extents = extents;

        var poffset = cd[0].t.poffset;
        var poffsetIsArray = Array.isArray(poffset);

        for(j = 0; j < cd.length; j++) {
            var di = cd[j];
            var p0 = di[pLetter] - di.w / 2;

            if(isNumeric(p0)) {
                var p1 = di[pLetter] + di.w / 2;
                var pVal = round(di.p);
                if(extents[pVal]) {
                    extents[pVal] = [Math.min(p0, extents[pVal][0]), Math.max(p1, extents[pVal][1])];
                } else {
                    extents[pVal] = [p0, p1];
                }
            }

            di.p0 = di.p + (poffsetIsArray ? poffset[j] : poffset);
            di.p1 = di.p0 + di.w;
            di.s0 = di.b;
            di.s1 = di.s0 + di.s;
        }
    }
}

function getAxisLetter(ax) {
    return ax._id.charAt(0);
}

module.exports = {
    crossTraceCalc: crossTraceCalc,
    setGroupPositions: setGroupPositions
};

},{"../../constants/numerical":671,"../../lib":694,"../../plots/cartesian/axes":742,"../../registry":825,"./sieve.js":847,"fast-isnumeric":215}],839:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var Color = _dereq_('../../components/color');
var Registry = _dereq_('../../registry');

var handleXYDefaults = _dereq_('../scatter/xy_defaults');
var handleStyleDefaults = _dereq_('../bar/style_defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var coerceFont = Lib.coerceFont;

    var len = handleXYDefaults(traceIn, traceOut, layout, coerce);
    if(!len) {
        traceOut.visible = false;
        return;
    }

    coerce('orientation', (traceOut.x && !traceOut.y) ? 'h' : 'v');
    coerce('base');
    coerce('offset');
    coerce('width');

    coerce('text');
    coerce('hovertext');
    coerce('hovertemplate');

    var textPosition = coerce('textposition');

    var hasBoth = Array.isArray(textPosition) || textPosition === 'auto';
    var hasInside = hasBoth || textPosition === 'inside';
    var hasOutside = hasBoth || textPosition === 'outside';

    if(hasInside || hasOutside) {
        var textFont = coerceFont(coerce, 'textfont', layout.font);

        // Note that coercing `insidetextfont` is always needed –
        // even if `textposition` is `outside` for each trace – since
        // an outside label can become an inside one, for example because
        // of a bar being stacked on top of it.
        var insideTextFontDefault = Lib.extendFlat({}, textFont);
        var isTraceTextfontColorSet = traceIn.textfont && traceIn.textfont.color;
        var isColorInheritedFromLayoutFont = !isTraceTextfontColorSet;
        if(isColorInheritedFromLayoutFont) {
            delete insideTextFontDefault.color;
        }
        coerceFont(coerce, 'insidetextfont', insideTextFontDefault);

        if(hasOutside) coerceFont(coerce, 'outsidetextfont', textFont);

        coerce('constraintext');
        coerce('selected.textfont.color');
        coerce('unselected.textfont.color');
        coerce('cliponaxis');
    }

    handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout);

    var lineColor = (traceOut.marker.line || {}).color;

    // override defaultColor for error bars with defaultLine
    var errorBarsSupplyDefaults = Registry.getComponentMethod('errorbars', 'supplyDefaults');
    errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color.defaultLine, {axis: 'y'});
    errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color.defaultLine, {axis: 'x', inherit: 'y'});

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};

},{"../../components/color":571,"../../lib":694,"../../registry":825,"../bar/style_defaults":849,"../scatter/xy_defaults":1073,"./attributes":835}],840:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var tinycolor = _dereq_('tinycolor2');

exports.coerceString = function(attributeDefinition, value, defaultValue) {
    if(typeof value === 'string') {
        if(value || !attributeDefinition.noBlank) return value;
    } else if(typeof value === 'number') {
        if(!attributeDefinition.strict) return String(value);
    }

    return (defaultValue !== undefined) ?
      defaultValue :
      attributeDefinition.dflt;
};

exports.coerceNumber = function(attributeDefinition, value, defaultValue) {
    if(isNumeric(value)) {
        value = +value;

        var min = attributeDefinition.min;
        var max = attributeDefinition.max;
        var isOutOfBounds = (min !== undefined && value < min) ||
              (max !== undefined && value > max);

        if(!isOutOfBounds) return value;
    }

    return (defaultValue !== undefined) ?
      defaultValue :
      attributeDefinition.dflt;
};

exports.coerceColor = function(attributeDefinition, value, defaultValue) {
    if(tinycolor(value).isValid()) return value;

    return (defaultValue !== undefined) ?
      defaultValue :
      attributeDefinition.dflt;
};

exports.coerceEnumerated = function(attributeDefinition, value, defaultValue) {
    if(attributeDefinition.coerceNumber) value = +value;

    if(attributeDefinition.values.indexOf(value) !== -1) return value;

    return (defaultValue !== undefined) ?
      defaultValue :
      attributeDefinition.dflt;
};

exports.getValue = function(arrayOrScalar, index) {
    var value;
    if(!Array.isArray(arrayOrScalar)) value = arrayOrScalar;
    else if(index < arrayOrScalar.length) value = arrayOrScalar[index];
    return value;
};

},{"fast-isnumeric":215,"tinycolor2":515}],841:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Fx = _dereq_('../../components/fx');
var Registry = _dereq_('../../registry');
var Color = _dereq_('../../components/color');
var fillHoverText = _dereq_('../scatter/fill_hover_text');

function hoverPoints(pointData, xval, yval, hovermode) {
    var cd = pointData.cd;
    var trace = cd[0].trace;
    var t = cd[0].t;
    var isClosest = (hovermode === 'closest');
    var maxHoverDistance = pointData.maxHoverDistance;
    var maxSpikeDistance = pointData.maxSpikeDistance;

    var posVal, sizeVal, posLetter, sizeLetter, dx, dy, pRangeCalc;

    function thisBarMinPos(di) { return di[posLetter] - di.w / 2; }
    function thisBarMaxPos(di) { return di[posLetter] + di.w / 2; }

    var minPos = isClosest ?
        thisBarMinPos :
        function(di) {
            /*
             * In compare mode, accept a bar if you're on it *or* its group.
             * Nearly always it's the group that matters, but in case the bar
             * was explicitly set wider than its group we'd better accept the
             * whole bar.
             *
             * use `bardelta` instead of `bargroupwidth` so we accept hover
             * in the gap. That way hover doesn't flash on and off as you
             * mouse over the plot in compare modes.
             * In 'closest' mode though the flashing seems inevitable,
             * without far more complex logic
             */
            return Math.min(thisBarMinPos(di), di.p - t.bardelta / 2);
        };

    var maxPos = isClosest ?
        thisBarMaxPos :
        function(di) {
            return Math.max(thisBarMaxPos(di), di.p + t.bardelta / 2);
        };

    function _positionFn(_minPos, _maxPos) {
        // add a little to the pseudo-distance for wider bars, so that like scatter,
        // if you are over two overlapping bars, the narrower one wins.
        return Fx.inbox(_minPos - posVal, _maxPos - posVal,
            maxHoverDistance + Math.min(1, Math.abs(_maxPos - _minPos) / pRangeCalc) - 1);
    }

    function positionFn(di) {
        return _positionFn(minPos(di), maxPos(di));
    }

    function thisBarPositionFn(di) {
        return _positionFn(thisBarMinPos(di), thisBarMaxPos(di));
    }

    function sizeFn(di) {
        // add a gradient so hovering near the end of a
        // bar makes it a little closer match
        return Fx.inbox(di.b - sizeVal, di[sizeLetter] - sizeVal,
            maxHoverDistance + (di[sizeLetter] - sizeVal) / (di[sizeLetter] - di.b) - 1);
    }

    if(trace.orientation === 'h') {
        posVal = yval;
        sizeVal = xval;
        posLetter = 'y';
        sizeLetter = 'x';
        dx = sizeFn;
        dy = positionFn;
    }
    else {
        posVal = xval;
        sizeVal = yval;
        posLetter = 'x';
        sizeLetter = 'y';
        dy = sizeFn;
        dx = positionFn;
    }

    var pa = pointData[posLetter + 'a'];
    var sa = pointData[sizeLetter + 'a'];

    pRangeCalc = Math.abs(pa.r2c(pa.range[1]) - pa.r2c(pa.range[0]));

    function dxy(di) { return (dx(di) + dy(di)) / 2; }
    var distfn = Fx.getDistanceFunction(hovermode, dx, dy, dxy);
    Fx.getClosest(cd, distfn, pointData);

    // skip the rest (for this trace) if we didn't find a close point
    if(pointData.index === false) return;

    // if we get here and we're not in 'closest' mode, push min/max pos back
    // onto the group - even though that means occasionally the mouse will be
    // over the hover label.
    if(!isClosest) {
        minPos = function(di) {
            return Math.min(thisBarMinPos(di), di.p - t.bargroupwidth / 2);
        };
        maxPos = function(di) {
            return Math.max(thisBarMaxPos(di), di.p + t.bargroupwidth / 2);
        };
    }

    // the closest data point
    var index = pointData.index;
    var di = cd[index];

    var size = (trace.base) ? di.b + di.s : di.s;
    pointData[sizeLetter + '0'] = pointData[sizeLetter + '1'] = sa.c2p(di[sizeLetter], true);
    pointData[sizeLetter + 'LabelVal'] = size;

    var extent = t.extents[t.extents.round(di.p)];
    pointData[posLetter + '0'] = pa.c2p(isClosest ? minPos(di) : extent[0], true);
    pointData[posLetter + '1'] = pa.c2p(isClosest ? maxPos(di) : extent[1], true);
    pointData[posLetter + 'LabelVal'] = di.p;

    // spikelines always want "closest" distance regardless of hovermode
    pointData.spikeDistance = (sizeFn(di) + thisBarPositionFn(di)) / 2 + maxSpikeDistance - maxHoverDistance;
    // they also want to point to the data value, regardless of where the label goes
    // in case of bars shifted within groups
    pointData[posLetter + 'Spike'] = pa.c2p(di.p, true);

    pointData.color = getTraceColor(trace, di);
    fillHoverText(di, trace, pointData);
    Registry.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData);

    pointData.hovertemplate = trace.hovertemplate;
    return [pointData];
}

function getTraceColor(trace, di) {
    var mc = di.mcc || trace.marker.color;
    var mlc = di.mlcc || trace.marker.line.color;
    var mlw = di.mlw || trace.marker.line.width;

    if(Color.opacity(mc)) return mc;
    else if(Color.opacity(mlc) && mlw) return mlc;
}

module.exports = {
    hoverPoints: hoverPoints,
    getTraceColor: getTraceColor
};

},{"../../components/color":571,"../../components/fx":610,"../../registry":825,"../scatter/fill_hover_text":1055}],842:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Bar = {};

Bar.attributes = _dereq_('./attributes');
Bar.layoutAttributes = _dereq_('./layout_attributes');
Bar.supplyDefaults = _dereq_('./defaults');
Bar.supplyLayoutDefaults = _dereq_('./layout_defaults');
Bar.calc = _dereq_('./calc');
Bar.crossTraceCalc = _dereq_('./cross_trace_calc').crossTraceCalc;
Bar.colorbar = _dereq_('../scatter/marker_colorbar');
Bar.arraysToCalcdata = _dereq_('./arrays_to_calcdata');
Bar.plot = _dereq_('./plot');
Bar.style = _dereq_('./style').style;
Bar.styleOnSelect = _dereq_('./style').styleOnSelect;
Bar.hoverPoints = _dereq_('./hover').hoverPoints;
Bar.selectPoints = _dereq_('./select');

Bar.moduleType = 'trace';
Bar.name = 'bar';
Bar.basePlotModule = _dereq_('../../plots/cartesian');
Bar.categories = ['cartesian', 'svg', 'bar', 'oriented', 'errorBarsOK', 'showLegend', 'zoomScale'];
Bar.meta = {
    
};

module.exports = Bar;

},{"../../plots/cartesian":754,"../scatter/marker_colorbar":1065,"./arrays_to_calcdata":834,"./attributes":835,"./calc":836,"./cross_trace_calc":838,"./defaults":839,"./hover":841,"./layout_attributes":843,"./layout_defaults":844,"./plot":845,"./select":846,"./style":848}],843:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    barmode: {
        valType: 'enumerated',
        values: ['stack', 'group', 'overlay', 'relative'],
        dflt: 'group',
        
        editType: 'calc',
        
    },
    barnorm: {
        valType: 'enumerated',
        values: ['', 'fraction', 'percent'],
        dflt: '',
        
        editType: 'calc',
        
    },
    bargap: {
        valType: 'number',
        min: 0,
        max: 1,
        
        editType: 'calc',
        
    },
    bargroupgap: {
        valType: 'number',
        min: 0,
        max: 1,
        dflt: 0,
        
        editType: 'calc',
        
    }
};

},{}],844:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../../registry');
var Axes = _dereq_('../../plots/cartesian/axes');
var Lib = _dereq_('../../lib');

var layoutAttributes = _dereq_('./layout_attributes');


module.exports = function(layoutIn, layoutOut, fullData) {
    function coerce(attr, dflt) {
        return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
    }

    var hasBars = false;
    var shouldBeGapless = false;
    var gappedAnyway = false;
    var usedSubplots = {};

    for(var i = 0; i < fullData.length; i++) {
        var trace = fullData[i];
        if(Registry.traceIs(trace, 'bar') && trace.visible) hasBars = true;
        else continue;

        // if we have at least 2 grouped bar traces on the same subplot,
        // we should default to a gap anyway, even if the data is histograms
        if(layoutIn.barmode !== 'overlay' && layoutIn.barmode !== 'stack') {
            var subploti = trace.xaxis + trace.yaxis;
            if(usedSubplots[subploti]) gappedAnyway = true;
            usedSubplots[subploti] = true;
        }

        if(trace.visible && trace.type === 'histogram') {
            var pa = Axes.getFromId({_fullLayout: layoutOut},
                        trace[trace.orientation === 'v' ? 'xaxis' : 'yaxis']);
            if(pa.type !== 'category') shouldBeGapless = true;
        }
    }

    if(!hasBars) return;

    var mode = coerce('barmode');
    if(mode !== 'overlay') coerce('barnorm');

    coerce('bargap', (shouldBeGapless && !gappedAnyway) ? 0 : 0.2);
    coerce('bargroupgap');
};

},{"../../lib":694,"../../plots/cartesian/axes":742,"../../registry":825,"./layout_attributes":843}],845:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');

var Color = _dereq_('../../components/color');
var Drawing = _dereq_('../../components/drawing');
var Registry = _dereq_('../../registry');

var attributes = _dereq_('./attributes');
var attributeText = attributes.text;
var attributeTextPosition = attributes.textposition;
var helpers = _dereq_('./helpers');
var style = _dereq_('./style');

// padding in pixels around text
var TEXTPAD = 3;

module.exports = function plot(gd, plotinfo, cdbar, barLayer) {
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;
    var fullLayout = gd._fullLayout;

    var bartraces = Lib.makeTraceGroups(barLayer, cdbar, 'trace bars').each(function(cd) {
        var plotGroup = d3.select(this);
        var cd0 = cd[0];
        var trace = cd0.trace;

        if(!plotinfo.isRangePlot) cd0.node3 = plotGroup;

        var pointGroup = Lib.ensureSingle(plotGroup, 'g', 'points');

        var bars = pointGroup.selectAll('g.point').data(Lib.identity);

        bars.enter().append('g')
            .classed('point', true);

        bars.exit().remove();

        bars.each(function(di, i) {
            var bar = d3.select(this);

            // now display the bar
            // clipped xf/yf (2nd arg true): non-positive
            // log values go off-screen by plotwidth
            // so you see them continue if you drag the plot
            var x0, x1, y0, y1;
            if(trace.orientation === 'h') {
                y0 = ya.c2p(di.p0, true);
                y1 = ya.c2p(di.p1, true);
                x0 = xa.c2p(di.s0, true);
                x1 = xa.c2p(di.s1, true);

                // for selections
                di.ct = [x1, (y0 + y1) / 2];
            }
            else {
                x0 = xa.c2p(di.p0, true);
                x1 = xa.c2p(di.p1, true);
                y0 = ya.c2p(di.s0, true);
                y1 = ya.c2p(di.s1, true);

                // for selections
                di.ct = [(x0 + x1) / 2, y1];
            }

            if(!isNumeric(x0) || !isNumeric(x1) ||
                    !isNumeric(y0) || !isNumeric(y1) ||
                    x0 === x1 || y0 === y1) {
                bar.remove();
                return;
            }

            var lw = (di.mlw + 1 || trace.marker.line.width + 1 ||
                    (di.trace ? di.trace.marker.line.width : 0) + 1) - 1;
            var offset = d3.round((lw / 2) % 1, 2);

            function roundWithLine(v) {
                // if there are explicit gaps, don't round,
                // it can make the gaps look crappy
                return (fullLayout.bargap === 0 && fullLayout.bargroupgap === 0) ?
                    d3.round(Math.round(v) - offset, 2) : v;
            }

            function expandToVisible(v, vc) {
                // if it's not in danger of disappearing entirely,
                // round more precisely
                return Math.abs(v - vc) >= 2 ? roundWithLine(v) :
                // but if it's very thin, expand it so it's
                // necessarily visible, even if it might overlap
                // its neighbor
                (v > vc ? Math.ceil(v) : Math.floor(v));
            }

            if(!gd._context.staticPlot) {
                // if bars are not fully opaque or they have a line
                // around them, round to integer pixels, mainly for
                // safari so we prevent overlaps from its expansive
                // pixelation. if the bars ARE fully opaque and have
                // no line, expand to a full pixel to make sure we
                // can see them
                var op = Color.opacity(di.mc || trace.marker.color);
                var fixpx = (op < 1 || lw > 0.01) ? roundWithLine : expandToVisible;
                x0 = fixpx(x0, x1);
                x1 = fixpx(x1, x0);
                y0 = fixpx(y0, y1);
                y1 = fixpx(y1, y0);
            }

            Lib.ensureSingle(bar, 'path')
                .style('vector-effect', 'non-scaling-stroke')
                .attr('d',
                    'M' + x0 + ',' + y0 + 'V' + y1 + 'H' + x1 + 'V' + y0 + 'Z')
                .call(Drawing.setClipUrl, plotinfo.layerClipId, gd);

            appendBarText(gd, bar, cd, i, x0, x1, y0, y1);

            if(plotinfo.layerClipId) {
                Drawing.hideOutsideRangePoint(di, bar.select('text'), xa, ya, trace.xcalendar, trace.ycalendar);
            }
        });

        // lastly, clip points groups of `cliponaxis !== false` traces
        // on `plotinfo._hasClipOnAxisFalse === true` subplots
        var hasClipOnAxisFalse = cd0.trace.cliponaxis === false;
        Drawing.setClipUrl(plotGroup, hasClipOnAxisFalse ? null : plotinfo.layerClipId, gd);
    });

    // error bars are on the top
    Registry.getComponentMethod('errorbars', 'plot')(gd, bartraces, plotinfo);
};

function appendBarText(gd, bar, calcTrace, i, x0, x1, y0, y1) {
    var textPosition;

    function appendTextNode(bar, text, textFont) {
        var textSelection = Lib.ensureSingle(bar, 'text')
            .text(text)
            .attr({
                'class': 'bartext bartext-' + textPosition,
                transform: '',
                'text-anchor': 'middle',
                // prohibit tex interpretation until we can handle
                // tex and regular text together
                'data-notex': 1
            })
            .call(Drawing.font, textFont)
            .call(svgTextUtils.convertToTspans, gd);

        return textSelection;
    }

    // get trace attributes
    var trace = calcTrace[0].trace;
    var orientation = trace.orientation;

    var text = getText(trace, i);
    textPosition = getTextPosition(trace, i);

    if(!text || textPosition === 'none') {
        bar.select('text').remove();
        return;
    }

    var layoutFont = gd._fullLayout.font;
    var barColor = style.getBarColor(calcTrace[i], trace);
    var insideTextFont = style.getInsideTextFont(trace, i, layoutFont, barColor);
    var outsideTextFont = style.getOutsideTextFont(trace, i, layoutFont);

    // compute text position
    var barmode = gd._fullLayout.barmode;
    var inStackMode = (barmode === 'stack');
    var inRelativeMode = (barmode === 'relative');
    var inStackOrRelativeMode = inStackMode || inRelativeMode;

    var calcBar = calcTrace[i];
    var isOutmostBar = !inStackOrRelativeMode || calcBar._outmost;

    var barWidth = Math.abs(x1 - x0) - 2 * TEXTPAD;  // padding excluded
    var barHeight = Math.abs(y1 - y0) - 2 * TEXTPAD;  // padding excluded

    var textSelection;
    var textBB;
    var textWidth;
    var textHeight;

    if(textPosition === 'outside') {
        if(!isOutmostBar && !calcBar.hasB) textPosition = 'inside';
    }

    if(textPosition === 'auto') {
        if(isOutmostBar) {
            // draw text using insideTextFont and check if it fits inside bar
            textPosition = 'inside';
            textSelection = appendTextNode(bar, text, insideTextFont);

            textBB = Drawing.bBox(textSelection.node()),
            textWidth = textBB.width,
            textHeight = textBB.height;

            var textHasSize = (textWidth > 0 && textHeight > 0);
            var fitsInside = (textWidth <= barWidth && textHeight <= barHeight);
            var fitsInsideIfRotated = (textWidth <= barHeight && textHeight <= barWidth);
            var fitsInsideIfShrunk = (orientation === 'h') ?
                (barWidth >= textWidth * (barHeight / textHeight)) :
                (barHeight >= textHeight * (barWidth / textWidth));

            if(textHasSize &&
                    (fitsInside || fitsInsideIfRotated || fitsInsideIfShrunk)) {
                textPosition = 'inside';
            }
            else {
                textPosition = 'outside';
                textSelection.remove();
                textSelection = null;
            }
        }
        else textPosition = 'inside';
    }

    if(!textSelection) {
        textSelection = appendTextNode(bar, text,
                (textPosition === 'outside') ?
                outsideTextFont : insideTextFont);

        textBB = Drawing.bBox(textSelection.node()),
        textWidth = textBB.width,
        textHeight = textBB.height;

        if(textWidth <= 0 || textHeight <= 0) {
            textSelection.remove();
            return;
        }
    }

    // compute text transform
    var transform, constrained;
    if(textPosition === 'outside') {
        constrained = trace.constraintext === 'both' || trace.constraintext === 'outside';
        transform = getTransformToMoveOutsideBar(x0, x1, y0, y1, textBB,
            orientation, constrained);
    }
    else {
        constrained = trace.constraintext === 'both' || trace.constraintext === 'inside';
        transform = getTransformToMoveInsideBar(x0, x1, y0, y1, textBB,
            orientation, constrained);
    }

    textSelection.attr('transform', transform);
}

function getTransformToMoveInsideBar(x0, x1, y0, y1, textBB, orientation, constrained) {
    // compute text and target positions
    var textWidth = textBB.width;
    var textHeight = textBB.height;
    var textX = (textBB.left + textBB.right) / 2;
    var textY = (textBB.top + textBB.bottom) / 2;
    var barWidth = Math.abs(x1 - x0);
    var barHeight = Math.abs(y1 - y0);
    var targetWidth;
    var targetHeight;
    var targetX;
    var targetY;

    // apply text padding
    var textpad;
    if(barWidth > (2 * TEXTPAD) && barHeight > (2 * TEXTPAD)) {
        textpad = TEXTPAD;
        barWidth -= 2 * textpad;
        barHeight -= 2 * textpad;
    }
    else textpad = 0;

    // compute rotation and scale
    var rotate,
        scale;

    if(textWidth <= barWidth && textHeight <= barHeight) {
        // no scale or rotation is required
        rotate = false;
        scale = 1;
    }
    else if(textWidth <= barHeight && textHeight <= barWidth) {
        // only rotation is required
        rotate = true;
        scale = 1;
    }
    else if((textWidth < textHeight) === (barWidth < barHeight)) {
        // only scale is required
        rotate = false;
        scale = constrained ? Math.min(barWidth / textWidth, barHeight / textHeight) : 1;
    }
    else {
        // both scale and rotation are required
        rotate = true;
        scale = constrained ? Math.min(barHeight / textWidth, barWidth / textHeight) : 1;
    }

    if(rotate) rotate = 90;  // rotate clockwise

    // compute text and target positions
    if(rotate) {
        targetWidth = scale * textHeight;
        targetHeight = scale * textWidth;
    }
    else {
        targetWidth = scale * textWidth;
        targetHeight = scale * textHeight;
    }

    if(orientation === 'h') {
        if(x1 < x0) {
            // bar end is on the left hand side
            targetX = x1 + textpad + targetWidth / 2;
            targetY = (y0 + y1) / 2;
        }
        else {
            targetX = x1 - textpad - targetWidth / 2;
            targetY = (y0 + y1) / 2;
        }
    }
    else {
        if(y1 > y0) {
            // bar end is on the bottom
            targetX = (x0 + x1) / 2;
            targetY = y1 - textpad - targetHeight / 2;
        }
        else {
            targetX = (x0 + x1) / 2;
            targetY = y1 + textpad + targetHeight / 2;
        }
    }

    return getTransform(textX, textY, targetX, targetY, scale, rotate);
}

function getTransformToMoveOutsideBar(x0, x1, y0, y1, textBB, orientation, constrained) {
    var barWidth = (orientation === 'h') ?
        Math.abs(y1 - y0) :
        Math.abs(x1 - x0);
    var textpad;

    // Keep the padding so the text doesn't sit right against
    // the bars, but don't factor it into barWidth
    if(barWidth > 2 * TEXTPAD) {
        textpad = TEXTPAD;
    }

    // compute rotation and scale
    var scale = 1;
    if(constrained) {
        scale = (orientation === 'h') ?
            Math.min(1, barWidth / textBB.height) :
            Math.min(1, barWidth / textBB.width);
    }

    // compute text and target positions
    var textX = (textBB.left + textBB.right) / 2;
    var textY = (textBB.top + textBB.bottom) / 2;
    var targetWidth;
    var targetHeight;
    var targetX;
    var targetY;

    targetWidth = scale * textBB.width;
    targetHeight = scale * textBB.height;

    if(orientation === 'h') {
        if(x1 < x0) {
            // bar end is on the left hand side
            targetX = x1 - textpad - targetWidth / 2;
            targetY = (y0 + y1) / 2;
        }
        else {
            targetX = x1 + textpad + targetWidth / 2;
            targetY = (y0 + y1) / 2;
        }
    }
    else {
        if(y1 > y0) {
            // bar end is on the bottom
            targetX = (x0 + x1) / 2;
            targetY = y1 + textpad + targetHeight / 2;
        }
        else {
            targetX = (x0 + x1) / 2;
            targetY = y1 - textpad - targetHeight / 2;
        }
    }

    return getTransform(textX, textY, targetX, targetY, scale, false);
}

function getTransform(textX, textY, targetX, targetY, scale, rotate) {
    var transformScale;
    var transformRotate;
    var transformTranslate;

    if(scale < 1) transformScale = 'scale(' + scale + ') ';
    else {
        scale = 1;
        transformScale = '';
    }

    transformRotate = (rotate) ?
        'rotate(' + rotate + ' ' + textX + ' ' + textY + ') ' : '';

    // Note that scaling also affects the center of the text box
    var translateX = (targetX - scale * textX);
    var translateY = (targetY - scale * textY);
    transformTranslate = 'translate(' + translateX + ' ' + translateY + ')';

    return transformTranslate + transformScale + transformRotate;
}

function getText(trace, index) {
    var value = helpers.getValue(trace.text, index);
    return helpers.coerceString(attributeText, value);
}

function getTextPosition(trace, index) {
    var value = helpers.getValue(trace.textposition, index);
    return helpers.coerceEnumerated(attributeTextPosition, value);
}

},{"../../components/color":571,"../../components/drawing":592,"../../lib":694,"../../lib/svg_text_utils":718,"../../registry":825,"./attributes":835,"./helpers":840,"./style":848,"d3":149,"fast-isnumeric":215}],846:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function selectPoints(searchInfo, selectionTester) {
    var cd = searchInfo.cd;
    var xa = searchInfo.xaxis;
    var ya = searchInfo.yaxis;
    var selection = [];
    var i;

    if(selectionTester === false) {
        // clear selection
        for(i = 0; i < cd.length; i++) {
            cd[i].selected = 0;
        }
    } else {
        for(i = 0; i < cd.length; i++) {
            var di = cd[i];

            if(selectionTester.contains(di.ct, false, i, searchInfo)) {
                selection.push({
                    pointNumber: i,
                    x: xa.c2d(di.x),
                    y: ya.c2d(di.y)
                });
                di.selected = 1;
            } else {
                di.selected = 0;
            }
        }
    }

    return selection;
};

},{}],847:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = Sieve;

var Lib = _dereq_('../../lib');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

/**
 * Helper class to sieve data from traces into bins
 *
 * @class
 * @param {Array}   traces
 *                  Array of calculated traces
 * @param {boolean} [separateNegativeValues]
 *                  If true, then split data at the same position into a bar
 *                  for positive values and another for negative values
 * @param {boolean} [dontMergeOverlappingData]
 *                  If true, then don't merge overlapping bars into a single bar
 */
function Sieve(traces, separateNegativeValues, dontMergeOverlappingData) {
    this.traces = traces;
    this.separateNegativeValues = separateNegativeValues;
    this.dontMergeOverlappingData = dontMergeOverlappingData;

    // for single-bin histograms - see histogram/calc
    var width1 = Infinity;

    var positions = [];
    for(var i = 0; i < traces.length; i++) {
        var trace = traces[i];
        for(var j = 0; j < trace.length; j++) {
            var bar = trace[j];
            if(bar.p !== BADNUM) positions.push(bar.p);
        }
        if(trace[0] && trace[0].width1) {
            width1 = Math.min(trace[0].width1, width1);
        }
    }
    this.positions = positions;

    var dv = Lib.distinctVals(positions);
    this.distinctPositions = dv.vals;
    if(dv.vals.length === 1 && width1 !== Infinity) this.minDiff = width1;
    else this.minDiff = Math.min(dv.minDiff, width1);

    this.binWidth = this.minDiff;

    this.bins = {};
}

/**
 * Sieve datum
 *
 * @method
 * @param {number} position
 * @param {number} value
 * @returns {number} Previous bin value
 */
Sieve.prototype.put = function put(position, value) {
    var label = this.getLabel(position, value);
    var oldValue = this.bins[label] || 0;

    this.bins[label] = oldValue + value;

    return oldValue;
};

/**
 * Get current bin value for a given datum
 *
 * @method
 * @param {number} position  Position of datum
 * @param {number} [value]   Value of datum
 *                           (required if this.separateNegativeValues is true)
 * @returns {number} Current bin value
 */
Sieve.prototype.get = function put(position, value) {
    var label = this.getLabel(position, value);
    return this.bins[label] || 0;
};

/**
 * Get bin label for a given datum
 *
 * @method
 * @param {number} position  Position of datum
 * @param {number} [value]   Value of datum
 *                           (required if this.separateNegativeValues is true)
 * @returns {string} Bin label
 * (prefixed with a 'v' if value is negative and this.separateNegativeValues is
 * true; otherwise prefixed with '^')
 */
Sieve.prototype.getLabel = function getLabel(position, value) {
    var prefix = (value < 0 && this.separateNegativeValues) ? 'v' : '^';
    var label = (this.dontMergeOverlappingData) ?
        position :
        Math.round(position / this.binWidth);
    return prefix + label;
};

},{"../../constants/numerical":671,"../../lib":694}],848:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var Color = _dereq_('../../components/color');
var Drawing = _dereq_('../../components/drawing');
var Lib = _dereq_('../../lib');
var Registry = _dereq_('../../registry');

var attributes = _dereq_('./attributes');
var attributeTextFont = attributes.textfont;
var attributeInsideTextFont = attributes.insidetextfont;
var attributeOutsideTextFont = attributes.outsidetextfont;
var helpers = _dereq_('./helpers');

function style(gd, cd) {
    var s = cd ? cd[0].node3 : d3.select(gd).selectAll('g.trace.bars');
    var barcount = s.size();
    var fullLayout = gd._fullLayout;

    // trace styling
    s.style('opacity', function(d) { return d[0].trace.opacity; })

    // for gapless (either stacked or neighboring grouped) bars use
    // crispEdges to turn off antialiasing so an artificial gap
    // isn't introduced.
    .each(function(d) {
        if((fullLayout.barmode === 'stack' && barcount > 1) ||
                (fullLayout.bargap === 0 &&
                 fullLayout.bargroupgap === 0 &&
                 !d[0].trace.marker.line.width)) {
            d3.select(this).attr('shape-rendering', 'crispEdges');
        }
    });

    s.selectAll('g.points').each(function(d) {
        var sel = d3.select(this);
        var trace = d[0].trace;
        stylePoints(sel, trace, gd);
    });

    Registry.getComponentMethod('errorbars', 'style')(s);
}

function stylePoints(sel, trace, gd) {
    var pts = sel.selectAll('path');
    var txs = sel.selectAll('text');

    Drawing.pointStyle(pts, trace, gd);

    txs.each(function(d) {
        var tx = d3.select(this);
        var font = determineFont(tx, d, trace, gd);
        Drawing.font(tx, font);
    });
}

function styleOnSelect(gd, cd) {
    var s = cd[0].node3;
    var trace = cd[0].trace;

    if(trace.selectedpoints) {
        stylePointsInSelectionMode(s, trace, gd);
    } else {
        stylePoints(s, trace, gd);
    }
}

function stylePointsInSelectionMode(s, trace, gd) {
    Drawing.selectedPointStyle(s.selectAll('path'), trace);
    styleTextInSelectionMode(s.selectAll('text'), trace, gd);
}

function styleTextInSelectionMode(txs, trace, gd) {
    txs.each(function(d) {
        var tx = d3.select(this);
        var font;

        if(d.selected) {
            font = Lib.extendFlat({}, determineFont(tx, d, trace, gd));

            var selectedFontColor = trace.selected.textfont && trace.selected.textfont.color;
            if(selectedFontColor) {
                font.color = selectedFontColor;
            }

            Drawing.font(tx, font);
        } else {
            Drawing.selectedTextStyle(tx, trace);
        }
    });
}

function determineFont(tx, d, trace, gd) {
    var layoutFont = gd._fullLayout.font;
    var textFont = trace.textfont;

    if(tx.classed('bartext-inside')) {
        var barColor = getBarColor(d, trace);
        textFont = getInsideTextFont(trace, d.i, layoutFont, barColor);
    } else if(tx.classed('bartext-outside')) {
        textFont = getOutsideTextFont(trace, d.i, layoutFont);
    }

    return textFont;
}

function getTextFont(trace, index, defaultValue) {
    return getFontValue(
      attributeTextFont, trace.textfont, index, defaultValue);
}

function getInsideTextFont(trace, index, layoutFont, barColor) {
    var defaultFont = getTextFont(trace, index, layoutFont);

    var wouldFallBackToLayoutFont =
      (trace._input.textfont === undefined || trace._input.textfont.color === undefined) ||
      (Array.isArray(trace.textfont.color) && trace.textfont.color[index] === undefined);
    if(wouldFallBackToLayoutFont) {
        defaultFont = {
            color: Color.contrast(barColor),
            family: defaultFont.family,
            size: defaultFont.size
        };
    }

    return getFontValue(
      attributeInsideTextFont, trace.insidetextfont, index, defaultFont);
}

function getOutsideTextFont(trace, index, layoutFont) {
    var defaultFont = getTextFont(trace, index, layoutFont);
    return getFontValue(
      attributeOutsideTextFont, trace.outsidetextfont, index, defaultFont);
}

function getFontValue(attributeDefinition, attributeValue, index, defaultValue) {
    attributeValue = attributeValue || {};

    var familyValue = helpers.getValue(attributeValue.family, index);
    var sizeValue = helpers.getValue(attributeValue.size, index);
    var colorValue = helpers.getValue(attributeValue.color, index);

    return {
        family: helpers.coerceString(
          attributeDefinition.family, familyValue, defaultValue.family),
        size: helpers.coerceNumber(
          attributeDefinition.size, sizeValue, defaultValue.size),
        color: helpers.coerceColor(
          attributeDefinition.color, colorValue, defaultValue.color)
    };
}

function getBarColor(cd, trace) {
    return cd.mc || trace.marker.color;
}

module.exports = {
    style: style,
    styleOnSelect: styleOnSelect,
    getInsideTextFont: getInsideTextFont,
    getOutsideTextFont: getOutsideTextFont,
    getBarColor: getBarColor
};

},{"../../components/color":571,"../../components/drawing":592,"../../lib":694,"../../registry":825,"./attributes":835,"./helpers":840,"d3":149}],849:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Color = _dereq_('../../components/color');
var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');

module.exports = function handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout) {
    coerce('marker.color', defaultColor);

    if(hasColorscale(traceIn, 'marker')) {
        colorscaleDefaults(
            traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'}
        );
    }

    coerce('marker.line.color', Color.defaultLine);

    if(hasColorscale(traceIn, 'marker.line')) {
        colorscaleDefaults(
            traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'}
        );
    }

    coerce('marker.line.width');
    coerce('marker.opacity');
    coerce('selected.marker.color');
    coerce('unselected.marker.color');
};

},{"../../components/color":571,"../../components/colorscale/defaults":581,"../../components/colorscale/helpers":582}],850:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var extendFlat = _dereq_('../../lib/extend').extendFlat;
var scatterPolarAttrs = _dereq_('../scatterpolar/attributes');
var barAttrs = _dereq_('../bar/attributes');

module.exports = {
    r: scatterPolarAttrs.r,
    theta: scatterPolarAttrs.theta,
    r0: scatterPolarAttrs.r0,
    dr: scatterPolarAttrs.dr,
    theta0: scatterPolarAttrs.theta0,
    dtheta: scatterPolarAttrs.dtheta,
    thetaunit: scatterPolarAttrs.thetaunit,

    // orientation: {
    //     valType: 'enumerated',
    //     
    //     values: ['radial', 'angular'],
    //     editType: 'calc+clearAxisTypes',
    //     
    // },

    base: extendFlat({}, barAttrs.base, {
        
    }),
    offset: extendFlat({}, barAttrs.offset, {
        
    }),
    width: extendFlat({}, barAttrs.width, {
        
    }),

    text: extendFlat({}, barAttrs.text, {
        
    }),
    // hovertext: barAttrs.hovertext,

    // textposition: {},
    // textfont: {},
    // insidetextfont: {},
    // outsidetextfont: {},
    // constraintext: {},
    // cliponaxis: extendFlat({}, barAttrs.cliponaxis, {dflt: false}),

    marker: barAttrs.marker,

    hoverinfo: scatterPolarAttrs.hoverinfo,
    hovertemplate: hovertemplateAttrs(),

    selected: barAttrs.selected,
    unselected: barAttrs.unselected

    // error_x (error_r, error_theta)
    // error_y
};

},{"../../components/fx/hovertemplate_attributes":609,"../../lib/extend":684,"../bar/attributes":835,"../scatterpolar/attributes":1109}],851:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
var colorscaleCalc = _dereq_('../../components/colorscale/calc');
var arraysToCalcdata = _dereq_('../bar/arrays_to_calcdata');
var setGroupPositions = _dereq_('../bar/cross_trace_calc').setGroupPositions;
var calcSelection = _dereq_('../scatter/calc_selection');
var traceIs = _dereq_('../../registry').traceIs;
var extendFlat = _dereq_('../../lib').extendFlat;

function calc(gd, trace) {
    var fullLayout = gd._fullLayout;
    var subplotId = trace.subplot;
    var radialAxis = fullLayout[subplotId].radialaxis;
    var angularAxis = fullLayout[subplotId].angularaxis;
    var rArray = radialAxis.makeCalcdata(trace, 'r');
    var thetaArray = angularAxis.makeCalcdata(trace, 'theta');
    var len = trace._length;
    var cd = new Array(len);

    // 'size' axis variables
    var sArray = rArray;
    // 'pos' axis variables
    var pArray = thetaArray;

    for(var i = 0; i < len; i++) {
        cd[i] = {p: pArray[i], s: sArray[i]};
    }

    // convert width and offset in 'c' coordinate,
    // set 'c' value(s) in trace._width and trace._offset,
    // to make Bar.crossTraceCalc "just work"
    function d2c(attr) {
        var val = trace[attr];
        if(val !== undefined) {
            trace['_' + attr] = Array.isArray(val) ?
                angularAxis.makeCalcdata(trace, attr) :
                angularAxis.d2c(val, trace.thetaunit);
        }
    }

    if(angularAxis.type === 'linear') {
        d2c('width');
        d2c('offset');
    }

    if(hasColorscale(trace, 'marker')) {
        colorscaleCalc(gd, trace, {
            vals: trace.marker.color,
            containerStr: 'marker',
            cLetter: 'c'
        });
    }
    if(hasColorscale(trace, 'marker.line')) {
        colorscaleCalc(gd, trace, {
            vals: trace.marker.line.color,
            containerStr: 'marker.line',
            cLetter: 'c'
        });
    }

    arraysToCalcdata(cd, trace);
    calcSelection(cd, trace);

    return cd;
}

function crossTraceCalc(gd, polarLayout, subplotId) {
    var calcdata = gd.calcdata;
    var barPolarCd = [];

    for(var i = 0; i < calcdata.length; i++) {
        var cdi = calcdata[i];
        var trace = cdi[0].trace;

        if(trace.visible === true && traceIs(trace, 'bar') &&
            trace.subplot === subplotId
        ) {
            barPolarCd.push(cdi);
        }
    }

    // to make _extremes is filled in correctly so that
    // polar._subplot.radialAxis can get auotrange'd
    // TODO clean up!
    // I think we want to call getAutorange on polar.radialaxis
    // NOT on polar._subplot.radialAxis
    var rAxis = extendFlat({}, polarLayout.radialaxis, {_id: 'x'});
    var aAxis = polarLayout.angularaxis;

    // 'bargap', 'barmode' are in _fullLayout.polar
    // TODO clean up setGroupPositions API instead
    var mockGd = {_fullLayout: polarLayout};

    setGroupPositions(mockGd, aAxis, rAxis, barPolarCd);
}

module.exports = {
    calc: calc,
    crossTraceCalc: crossTraceCalc
};

},{"../../components/colorscale/calc":579,"../../components/colorscale/helpers":582,"../../lib":694,"../../registry":825,"../bar/arrays_to_calcdata":834,"../bar/cross_trace_calc":838,"../scatter/calc_selection":1049}],852:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

var handleRThetaDefaults = _dereq_('../scatterpolar/defaults').handleRThetaDefaults;
var handleStyleDefaults = _dereq_('../bar/style_defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var len = handleRThetaDefaults(traceIn, traceOut, layout, coerce);
    if(!len) {
        traceOut.visible = false;
        return;
    }

    // coerce('orientation', (traceOut.theta && !traceOut.r) ? 'angular' : 'radial');

    coerce('thetaunit');
    coerce('base');
    coerce('offset');
    coerce('width');

    coerce('text');
    coerce('hovertemplate');
    // coerce('hovertext');

    // var textPosition = coerce('textposition');
    // var hasBoth = Array.isArray(textPosition) || textPosition === 'auto';
    // var hasInside = hasBoth || textPosition === 'inside';
    // var hasOutside = hasBoth || textPosition === 'outside';

    // if(hasInside || hasOutside) {
    //     var textFont = coerceFont(coerce, 'textfont', layout.font);
    //     if(hasInside) coerceFont(coerce, 'insidetextfont', textFont);
    //     if(hasOutside) coerceFont(coerce, 'outsidetextfont', textFont);
    //     coerce('constraintext');
    //     coerce('selected.textfont.color');
    //     coerce('unselected.textfont.color');
    //     coerce('cliponaxis');
    // }

    handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout);

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};

},{"../../lib":694,"../bar/style_defaults":849,"../scatterpolar/defaults":1111,"./attributes":850}],853:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Fx = _dereq_('../../components/fx');
var Lib = _dereq_('../../lib');
var getTraceColor = _dereq_('../bar/hover').getTraceColor;
var fillHoverText = _dereq_('../scatter/fill_hover_text');
var makeHoverPointText = _dereq_('../scatterpolar/hover').makeHoverPointText;
var isPtInsidePolygon = _dereq_('../../plots/polar/helpers').isPtInsidePolygon;

module.exports = function hoverPoints(pointData, xval, yval) {
    var cd = pointData.cd;
    var trace = cd[0].trace;

    var subplot = pointData.subplot;
    var radialAxis = subplot.radialAxis;
    var angularAxis = subplot.angularAxis;
    var vangles = subplot.vangles;
    var inboxFn = vangles ? isPtInsidePolygon : Lib.isPtInsideSector;
    var maxHoverDistance = pointData.maxHoverDistance;
    var period = angularAxis._period || 2 * Math.PI;

    var rVal = Math.abs(radialAxis.g2p(Math.sqrt(xval * xval + yval * yval)));
    var thetaVal = Math.atan2(yval, xval);

    // polar.(x|y)axis.p2c doesn't get the reversed radial axis range case right
    if(radialAxis.range[0] > radialAxis.range[1]) {
        thetaVal += Math.PI;
    }

    var distFn = function(di) {
        if(inboxFn(rVal, thetaVal, [di.rp0, di.rp1], [di.thetag0, di.thetag1], vangles)) {
            return maxHoverDistance +
                // add a little to the pseudo-distance for wider bars, so that like scatter,
                // if you are over two overlapping bars, the narrower one wins.
                Math.min(1, Math.abs(di.thetag1 - di.thetag0) / period) - 1 +
                // add a gradient so hovering near the end of a
                // bar makes it a little closer match
                (di.rp1 - rVal) / (di.rp1 - di.rp0) - 1;
        } else {
            return Infinity;
        }
    };

    Fx.getClosest(cd, distFn, pointData);
    if(pointData.index === false) return;

    var index = pointData.index;
    var cdi = cd[index];

    pointData.x0 = pointData.x1 = cdi.ct[0];
    pointData.y0 = pointData.y1 = cdi.ct[1];

    var _cdi = Lib.extendFlat({}, cdi, {r: cdi.s, theta: cdi.p});
    fillHoverText(cdi, trace, pointData);
    makeHoverPointText(_cdi, trace, subplot, pointData);
    pointData.hovertemplate = trace.hovertemplate;
    pointData.color = getTraceColor(trace, cdi);
    pointData.xLabelVal = pointData.yLabelVal = undefined;

    if(cdi.s < 0) {
        pointData.idealAlign = 'left';
    }

    return [pointData];
};

},{"../../components/fx":610,"../../lib":694,"../../plots/polar/helpers":808,"../bar/hover":841,"../scatter/fill_hover_text":1055,"../scatterpolar/hover":1112}],854:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'trace',
    name: 'barpolar',
    basePlotModule: _dereq_('../../plots/polar'),
    categories: ['polar', 'bar', 'showLegend'],

    attributes: _dereq_('./attributes'),
    layoutAttributes: _dereq_('./layout_attributes'),
    supplyDefaults: _dereq_('./defaults'),
    supplyLayoutDefaults: _dereq_('./layout_defaults'),

    calc: _dereq_('./calc').calc,
    crossTraceCalc: _dereq_('./calc').crossTraceCalc,

    plot: _dereq_('./plot'),
    colorbar: _dereq_('../scatter/marker_colorbar'),
    style: _dereq_('../bar/style').style,

    hoverPoints: _dereq_('./hover'),
    selectPoints: _dereq_('../bar/select'),

    meta: {
        
        
    }
};

},{"../../plots/polar":809,"../bar/select":846,"../bar/style":848,"../scatter/marker_colorbar":1065,"./attributes":850,"./calc":851,"./defaults":852,"./hover":853,"./layout_attributes":855,"./layout_defaults":856,"./plot":857}],855:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    barmode: {
        valType: 'enumerated',
        values: ['stack', 'overlay'],
        dflt: 'stack',
        
        editType: 'calc',
        
    },
    bargap: {
        valType: 'number',
        dflt: 0.1,
        min: 0,
        max: 1,
        
        editType: 'calc',
        
    }
};

},{}],856:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var attrs = _dereq_('./layout_attributes');

module.exports = function(layoutIn, layoutOut, fullData) {
    var subplotsDone = {};
    var sp;

    function coerce(attr, dflt) {
        return Lib.coerce(layoutIn[sp] || {}, layoutOut[sp], attrs, attr, dflt);
    }

    for(var i = 0; i < fullData.length; i++) {
        var trace = fullData[i];
        if(trace.type === 'barpolar' && trace.visible === true) {
            sp = trace.subplot;
            if(!subplotsDone[sp]) {
                coerce('barmode');
                coerce('bargap');
                subplotsDone[sp] = 1;
            }
        }
    }
};

},{"../../lib":694,"./layout_attributes":855}],857:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');
var Drawing = _dereq_('../../components/drawing');
var helpers = _dereq_('../../plots/polar/helpers');

module.exports = function plot(gd, subplot, cdbar) {
    var xa = subplot.xaxis;
    var ya = subplot.yaxis;
    var radialAxis = subplot.radialAxis;
    var angularAxis = subplot.angularAxis;
    var pathFn = makePathFn(subplot);
    var barLayer = subplot.layers.frontplot.select('g.barlayer');

    Lib.makeTraceGroups(barLayer, cdbar, 'trace bars').each(function(cd) {
        var plotGroup = cd[0].node3 = d3.select(this);
        var pointGroup = Lib.ensureSingle(plotGroup, 'g', 'points');
        var bars = pointGroup.selectAll('g.point').data(Lib.identity);

        bars.enter().append('g')
            .style('vector-effect', 'non-scaling-stroke')
            .style('stroke-miterlimit', 2)
            .classed('point', true);

        bars.exit().remove();

        bars.each(function(di) {
            var bar = d3.select(this);

            var rp0 = di.rp0 = radialAxis.c2p(di.s0);
            var rp1 = di.rp1 = radialAxis.c2p(di.s1);
            var thetag0 = di.thetag0 = angularAxis.c2g(di.p0);
            var thetag1 = di.thetag1 = angularAxis.c2g(di.p1);

            var dPath;

            if(!isNumeric(rp0) || !isNumeric(rp1) ||
                !isNumeric(thetag0) || !isNumeric(thetag1) ||
                rp0 === rp1 || thetag0 === thetag1
            ) {
                // do not remove blank bars, to keep data-to-node
                // mapping intact during radial drag, that we
                // can skip calling _module.style during interactions
                dPath = 'M0,0Z';
            } else {
                // this 'center' pt is used for selections and hover labels
                var rg1 = radialAxis.c2g(di.s1);
                var thetagMid = (thetag0 + thetag1) / 2;
                di.ct = [
                    xa.c2p(rg1 * Math.cos(thetagMid)),
                    ya.c2p(rg1 * Math.sin(thetagMid))
                ];

                dPath = pathFn(rp0, rp1, thetag0, thetag1);
            }

            Lib.ensureSingle(bar, 'path').attr('d', dPath);
        });

        // clip plotGroup, when trace layer isn't clipped
        Drawing.setClipUrl(
            plotGroup,
            subplot._hasClipOnAxisFalse ? subplot.clipIds.forTraces : null,
            gd
        );
    });
};

function makePathFn(subplot) {
    var cxx = subplot.cxx;
    var cyy = subplot.cyy;

    if(subplot.vangles) {
        return function(r0, r1, _a0, _a1) {
            var a0, a1;

            if(Lib.angleDelta(_a0, _a1) > 0) {
                a0 = _a0;
                a1 = _a1;
            } else {
                a0 = _a1;
                a1 = _a0;
            }

            var va0 = helpers.findEnclosingVertexAngles(a0, subplot.vangles)[0];
            var va1 = helpers.findEnclosingVertexAngles(a1, subplot.vangles)[1];
            var vaBar = [va0, (a0 + a1) / 2, va1];
            return helpers.pathPolygonAnnulus(r0, r1, a0, a1, vaBar, cxx, cyy);
        };
    }

    return function(r0, r1, a0, a1) {
        return Lib.pathAnnulus(r0, r1, a0, a1, cxx, cyy);
    };
}

},{"../../components/drawing":592,"../../lib":694,"../../plots/polar/helpers":808,"d3":149,"fast-isnumeric":215}],858:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterAttrs = _dereq_('../scatter/attributes');
var colorAttrs = _dereq_('../../components/color/attributes');
var extendFlat = _dereq_('../../lib/extend').extendFlat;

var scatterMarkerAttrs = scatterAttrs.marker;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;

module.exports = {
    y: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },
    x: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },
    x0: {
        valType: 'any',
        
        editType: 'calc+clearAxisTypes',
        
    },
    y0: {
        valType: 'any',
        
        editType: 'calc+clearAxisTypes',
        
    },
    name: {
        valType: 'string',
        
        editType: 'calc+clearAxisTypes',
        
    },
    text: extendFlat({}, scatterAttrs.text, {
        
    }),
    whiskerwidth: {
        valType: 'number',
        min: 0,
        max: 1,
        dflt: 0.5,
        
        editType: 'calc',
        
    },
    notched: {
        valType: 'boolean',
        
        editType: 'calc',
        
    },
    notchwidth: {
        valType: 'number',
        min: 0,
        max: 0.5,
        dflt: 0.25,
        
        editType: 'calc',
        
    },
    boxpoints: {
        valType: 'enumerated',
        values: ['all', 'outliers', 'suspectedoutliers', false],
        dflt: 'outliers',
        
        editType: 'calc',
        
    },
    boxmean: {
        valType: 'enumerated',
        values: [true, 'sd', false],
        dflt: false,
        
        editType: 'calc',
        
    },
    jitter: {
        valType: 'number',
        min: 0,
        max: 1,
        
        editType: 'calc',
        
    },
    pointpos: {
        valType: 'number',
        min: -2,
        max: 2,
        
        editType: 'calc',
        
    },
    orientation: {
        valType: 'enumerated',
        values: ['v', 'h'],
        
        editType: 'calc+clearAxisTypes',
        
    },

    width: {
        valType: 'number',
        min: 0,
        
        dflt: 0,
        editType: 'calc',
        
    },

    marker: {
        outliercolor: {
            valType: 'color',
            dflt: 'rgba(0, 0, 0, 0)',
            
            editType: 'style',
            
        },
        symbol: extendFlat({}, scatterMarkerAttrs.symbol,
            {arrayOk: false, editType: 'plot'}),
        opacity: extendFlat({}, scatterMarkerAttrs.opacity,
            {arrayOk: false, dflt: 1, editType: 'style'}),
        size: extendFlat({}, scatterMarkerAttrs.size,
            {arrayOk: false, editType: 'calc'}),
        color: extendFlat({}, scatterMarkerAttrs.color,
            {arrayOk: false, editType: 'style'}),
        line: {
            color: extendFlat({}, scatterMarkerLineAttrs.color,
                {arrayOk: false, dflt: colorAttrs.defaultLine, editType: 'style'}
            ),
            width: extendFlat({}, scatterMarkerLineAttrs.width,
                {arrayOk: false, dflt: 0, editType: 'style'}
            ),
            outliercolor: {
                valType: 'color',
                
                editType: 'style',
                
            },
            outlierwidth: {
                valType: 'number',
                min: 0,
                dflt: 1,
                
                editType: 'style',
                
            },
            editType: 'style'
        },
        editType: 'plot'
    },
    line: {
        color: {
            valType: 'color',
            
            editType: 'style',
            
        },
        width: {
            valType: 'number',
            
            min: 0,
            dflt: 2,
            editType: 'style',
            
        },
        editType: 'plot'
    },
    fillcolor: scatterAttrs.fillcolor,

    selected: {
        marker: scatterAttrs.selected.marker,
        editType: 'style'
    },
    unselected: {
        marker: scatterAttrs.unselected.marker,
        editType: 'style'
    },
    hoveron: {
        valType: 'flaglist',
        flags: ['boxes', 'points'],
        dflt: 'boxes+points',
        
        editType: 'style',
        
    }
};

},{"../../components/color/attributes":570,"../../lib/extend":684,"../scatter/attributes":1047}],859:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');
var _ = Lib._;
var Axes = _dereq_('../../plots/cartesian/axes');

// outlier definition based on http://www.physics.csbsju.edu/stats/box2.html
module.exports = function calc(gd, trace) {
    var fullLayout = gd._fullLayout;
    var xa = Axes.getFromId(gd, trace.xaxis || 'x');
    var ya = Axes.getFromId(gd, trace.yaxis || 'y');
    var cd = [];

    // N.B. violin reuses same Box.calc
    var numKey = trace.type === 'violin' ? '_numViolins' : '_numBoxes';

    var i;
    var valAxis, valLetter;
    var posAxis, posLetter;

    if(trace.orientation === 'h') {
        valAxis = xa;
        valLetter = 'x';
        posAxis = ya;
        posLetter = 'y';
    } else {
        valAxis = ya;
        valLetter = 'y';
        posAxis = xa;
        posLetter = 'x';
    }

    var val = valAxis.makeCalcdata(trace, valLetter);
    var pos = getPos(trace, posLetter, posAxis, val, fullLayout[numKey]);

    var dv = Lib.distinctVals(pos);
    var posDistinct = dv.vals;
    var dPos = dv.minDiff / 2;
    var posBins = makeBins(posDistinct, dPos);

    var pLen = posDistinct.length;
    var ptsPerBin = initNestedArray(pLen);

    // bin pts info per position bins
    for(i = 0; i < trace._length; i++) {
        var v = val[i];
        if(!isNumeric(v)) continue;

        var n = Lib.findBin(pos[i], posBins);
        if(n >= 0 && n < pLen) {
            var pt = {v: v, i: i};
            arraysToCalcdata(pt, trace, i);
            ptsPerBin[n].push(pt);
        }
    }

    var cdi;
    var ptFilterFn = (trace.boxpoints || trace.points) === 'all' ?
        Lib.identity :
        function(pt) { return (pt.v < cdi.lf || pt.v > cdi.uf); };

    // build calcdata trace items, one item per distinct position
    for(i = 0; i < pLen; i++) {
        if(ptsPerBin[i].length > 0) {
            var pts = ptsPerBin[i].sort(sortByVal);
            var boxVals = pts.map(extractVal);
            var bvLen = boxVals.length;

            cdi = {};
            cdi.pos = posDistinct[i];
            cdi.pts = pts;

            cdi.min = boxVals[0];
            cdi.max = boxVals[bvLen - 1];
            cdi.mean = Lib.mean(boxVals, bvLen);
            cdi.sd = Lib.stdev(boxVals, bvLen, cdi.mean);

            // first quartile
            cdi.q1 = Lib.interp(boxVals, 0.25);
             // median
            cdi.med = Lib.interp(boxVals, 0.5);
            // third quartile
            cdi.q3 = Lib.interp(boxVals, 0.75);

            // lower and upper fences - last point inside
            // 1.5 interquartile ranges from quartiles
            cdi.lf = Math.min(
                cdi.q1,
                boxVals[Math.min(
                    Lib.findBin(2.5 * cdi.q1 - 1.5 * cdi.q3, boxVals, true) + 1,
                    bvLen - 1
                )]
            );
            cdi.uf = Math.max(
                cdi.q3,
                boxVals[Math.max(
                    Lib.findBin(2.5 * cdi.q3 - 1.5 * cdi.q1, boxVals),
                    0
                )]
            );

            // lower and upper outliers - 3 IQR out (don't clip to max/min,
            // this is only for discriminating suspected & far outliers)
            cdi.lo = 4 * cdi.q1 - 3 * cdi.q3;
            cdi.uo = 4 * cdi.q3 - 3 * cdi.q1;

            // lower and upper notches ~95% Confidence Intervals for median
            var iqr = cdi.q3 - cdi.q1;
            var mci = 1.57 * iqr / Math.sqrt(bvLen);
            cdi.ln = cdi.med - mci;
            cdi.un = cdi.med + mci;

            cdi.pts2 = pts.filter(ptFilterFn);

            cd.push(cdi);
        }
    }

    calcSelection(cd, trace);
    var extremes = Axes.findExtremes(valAxis, val, {padded: true});
    trace._extremes[valAxis._id] = extremes;

    if(cd.length > 0) {
        cd[0].t = {
            num: fullLayout[numKey],
            dPos: dPos,
            posLetter: posLetter,
            valLetter: valLetter,
            labels: {
                med: _(gd, 'median:'),
                min: _(gd, 'min:'),
                q1: _(gd, 'q1:'),
                q3: _(gd, 'q3:'),
                max: _(gd, 'max:'),
                mean: trace.boxmean === 'sd' ? _(gd, 'mean ± σ:') : _(gd, 'mean:'),
                lf: _(gd, 'lower fence:'),
                uf: _(gd, 'upper fence:')
            }
        };

        fullLayout[numKey]++;
        return cd;
    } else {
        return [{t: {empty: true}}];
    }
};

// In vertical (horizontal) box plots:
// if no x (y) data, use x0 (y0), or name
// so if you want one box
// per trace, set x0 (y0) to the x (y) value or category for this trace
// (or set x (y) to a constant array matching y (x))
function getPos(trace, posLetter, posAxis, val, num) {
    if(posLetter in trace) {
        return posAxis.makeCalcdata(trace, posLetter);
    }

    var pos0;

    if(posLetter + '0' in trace) {
        pos0 = trace[posLetter + '0'];
    } else if('name' in trace && (
        posAxis.type === 'category' || (
            isNumeric(trace.name) &&
            ['linear', 'log'].indexOf(posAxis.type) !== -1
        ) || (
            Lib.isDateTime(trace.name) &&
            posAxis.type === 'date'
        )
    )) {
        pos0 = trace.name;
    } else {
        pos0 = num;
    }

    var pos0c = posAxis.type === 'multicategory' ?
        posAxis.r2c_just_indices(pos0) :
        posAxis.d2c(pos0, 0, trace[posLetter + 'calendar']);

    return val.map(function() { return pos0c; });
}

function makeBins(x, dx) {
    var len = x.length;
    var bins = new Array(len + 1);

    for(var i = 0; i < len; i++) {
        bins[i] = x[i] - dx;
    }
    bins[len] = x[len - 1] + dx;

    return bins;
}

function initNestedArray(len) {
    var arr = new Array(len);
    for(var i = 0; i < len; i++) {
        arr[i] = [];
    }
    return arr;
}

function arraysToCalcdata(pt, trace, i) {
    var trace2calc = {
        text: 'tx'
    };

    for(var k in trace2calc) {
        if(Array.isArray(trace[k])) {
            pt[trace2calc[k]] = trace[k][i];
        }
    }
}

function calcSelection(cd, trace) {
    if(Lib.isArrayOrTypedArray(trace.selectedpoints)) {
        for(var i = 0; i < cd.length; i++) {
            var pts = cd[i].pts || [];
            var ptNumber2cdIndex = {};

            for(var j = 0; j < pts.length; j++) {
                ptNumber2cdIndex[pts[j].i] = j;
            }

            Lib.tagSelected(pts, trace, ptNumber2cdIndex);
        }
    }
}

function sortByVal(a, b) { return a.v - b.v; }

function extractVal(o) { return o.v; }

},{"../../lib":694,"../../plots/cartesian/axes":742,"fast-isnumeric":215}],860:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Axes = _dereq_('../../plots/cartesian/axes');
var Lib = _dereq_('../../lib');

var orientations = ['v', 'h'];

function crossTraceCalc(gd, plotinfo) {
    var calcdata = gd.calcdata;
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    for(var i = 0; i < orientations.length; i++) {
        var orientation = orientations[i];
        var posAxis = orientation === 'h' ? ya : xa;
        var boxList = [];

        // make list of boxes / candlesticks
        // For backward compatibility, candlesticks are treated as if they *are* box traces here
        for(var j = 0; j < calcdata.length; j++) {
            var cd = calcdata[j];
            var t = cd[0].t;
            var trace = cd[0].trace;

            if(trace.visible === true &&
                    (trace.type === 'box' || trace.type === 'candlestick') &&
                    !t.empty &&
                    (trace.orientation || 'v') === orientation &&
                    trace.xaxis === xa._id &&
                    trace.yaxis === ya._id
              ) {
                boxList.push(j);
            }
        }

        setPositionOffset('box', gd, boxList, posAxis);
    }
}

function setPositionOffset(traceType, gd, boxList, posAxis) {
    var calcdata = gd.calcdata;
    var fullLayout = gd._fullLayout;
    var axId = posAxis._id;
    var axLetter = axId.charAt(0);

    // N.B. reused in violin
    var numKey = traceType === 'violin' ? '_numViolins' : '_numBoxes';

    var i, j, calcTrace;
    var pointList = [];
    var shownPts = 0;

    // make list of box points
    for(i = 0; i < boxList.length; i++) {
        calcTrace = calcdata[boxList[i]];
        for(j = 0; j < calcTrace.length; j++) {
            pointList.push(calcTrace[j].pos);
            shownPts += (calcTrace[j].pts2 || []).length;
        }
    }

    if(!pointList.length) return;

    // box plots - update dPos based on multiple traces
    var boxdv = Lib.distinctVals(pointList);
    var dPos0 = boxdv.minDiff / 2;

    // check for forced minimum dtick
    Axes.minDtick(posAxis, boxdv.minDiff, boxdv.vals[0], true);

    var num = fullLayout[numKey];
    var group = (fullLayout[traceType + 'mode'] === 'group' && num > 1);
    var groupFraction = 1 - fullLayout[traceType + 'gap'];
    var groupGapFraction = 1 - fullLayout[traceType + 'groupgap'];

    for(i = 0; i < boxList.length; i++) {
        calcTrace = calcdata[boxList[i]];

        var trace = calcTrace[0].trace;
        var t = calcTrace[0].t;
        var width = trace.width;
        var side = trace.side;

        // position coordinate delta
        var dPos;
        // box half width;
        var bdPos;
        // box center offset
        var bPos;
        // half-width within which to accept hover for this box/violin
        // always split the distance to the closest box/violin
        var wHover;

        if(width) {
            dPos = bdPos = wHover = width / 2;
            bPos = 0;
        } else {
            dPos = dPos0;
            bdPos = dPos * groupFraction * groupGapFraction / (group ? num : 1);
            bPos = group ? 2 * dPos * (-0.5 + (t.num + 0.5) / num) * groupFraction : 0;
            wHover = dPos * (group ? groupFraction / num : 1);
        }
        t.dPos = dPos;
        t.bPos = bPos;
        t.bdPos = bdPos;
        t.wHover = wHover;

        // box/violin-only value-space push value
        var pushplus;
        var pushminus;
        // edge of box/violin
        var edge = bPos + bdPos;
        var edgeplus;
        var edgeminus;

        if(side === 'positive') {
            pushplus = dPos * (width ? 1 : 0.5);
            edgeplus = edge;
            pushminus = edgeplus = bPos;
        } else if(side === 'negative') {
            pushplus = edgeplus = bPos;
            pushminus = dPos * (width ? 1 : 0.5);
            edgeminus = edge;
        } else {
            pushplus = pushminus = dPos;
            edgeplus = edgeminus = edge;
        }

        // value-space padding
        var vpadplus;
        var vpadminus;
        // pixel-space padding
        var ppadplus;
        var ppadminus;
        // do we add 5% of both sides (for points beyond box/violin)
        var padded = false;
        // does this trace show points?
        var hasPts = (trace.boxpoints || trace.points) && (shownPts > 0);

        if(hasPts) {
            var pointpos = trace.pointpos;
            var jitter = trace.jitter;
            var ms = trace.marker.size / 2;

            var pp = 0;
            if((pointpos + jitter) >= 0) {
                pp = edge * (pointpos + jitter);
                if(pp > pushplus) {
                    // (++) beyond plus-value, use pp
                    padded = true;
                    ppadplus = ms;
                    vpadplus = pp;
                } else if(pp > edgeplus) {
                    // (+), use push-value (it's bigger), but add px-pad
                    ppadplus = ms;
                    vpadplus = pushplus;
                }
            }
            if(pp <= pushplus) {
                // (->) fallback to push value
                vpadplus = pushplus;
            }

            var pm = 0;
            if((pointpos - jitter) <= 0) {
                pm = -edge * (pointpos - jitter);
                if(pm > pushminus) {
                    // (--) beyond plus-value, use pp
                    padded = true;
                    ppadminus = ms;
                    vpadminus = pm;
                } else if(pm > edgeminus) {
                    // (-), use push-value (it's bigger), but add px-pad
                    ppadminus = ms;
                    vpadminus = pushminus;
                }
            }
            if(pm <= pushminus) {
                // (<-) fallback to push value
                vpadminus = pushminus;
            }
        } else {
            vpadplus = pushplus;
            vpadminus = pushminus;
        }

        // calcdata[i][j] are in ascending order
        var firstPos = calcTrace[0].pos;
        var lastPos = calcTrace[calcTrace.length - 1].pos;

        trace._extremes[axId] = Axes.findExtremes(posAxis, [firstPos, lastPos], {
            padded: padded,
            vpadminus: vpadminus,
            vpadplus: vpadplus,
            // N.B. SVG px-space positive/negative
            ppadminus: {x: ppadminus, y: ppadplus}[axLetter],
            ppadplus: {x: ppadplus, y: ppadminus}[axLetter],
        });
    }
}

module.exports = {
    crossTraceCalc: crossTraceCalc,
    setPositionOffset: setPositionOffset
};

},{"../../lib":694,"../../plots/cartesian/axes":742}],861:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Registry = _dereq_('../../registry');
var Color = _dereq_('../../components/color');

var attributes = _dereq_('./attributes');

function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    handleSampleDefaults(traceIn, traceOut, coerce, layout);
    if(traceOut.visible === false) return;

    coerce('line.color', (traceIn.marker || {}).color || defaultColor);
    coerce('line.width');
    coerce('fillcolor', Color.addOpacity(traceOut.line.color, 0.5));

    coerce('whiskerwidth');
    coerce('boxmean');
    coerce('width');

    var notched = coerce('notched', traceIn.notchwidth !== undefined);
    if(notched) coerce('notchwidth');

    handlePointsDefaults(traceIn, traceOut, coerce, {prefix: 'box'});
}

function handleSampleDefaults(traceIn, traceOut, coerce, layout) {
    var y = coerce('y');
    var x = coerce('x');
    var hasX = x && x.length;

    var defaultOrientation, len;

    if(y && y.length) {
        defaultOrientation = 'v';
        if(hasX) {
            len = Math.min(Lib.minRowLength(x), Lib.minRowLength(y));
        } else {
            coerce('x0');
            len = Lib.minRowLength(y);
        }
    } else if(hasX) {
        defaultOrientation = 'h';
        coerce('y0');
        len = Lib.minRowLength(x);
    } else {
        traceOut.visible = false;
        return;
    }
    traceOut._length = len;

    var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
    handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout);

    coerce('orientation', defaultOrientation);
}

function handlePointsDefaults(traceIn, traceOut, coerce, opts) {
    var prefix = opts.prefix;

    var outlierColorDflt = Lib.coerce2(traceIn, traceOut, attributes, 'marker.outliercolor');
    var lineoutliercolor = coerce('marker.line.outliercolor');

    var points = coerce(
        prefix + 'points',
        (outlierColorDflt || lineoutliercolor) ? 'suspectedoutliers' : undefined
    );

    if(points) {
        coerce('jitter', points === 'all' ? 0.3 : 0);
        coerce('pointpos', points === 'all' ? -1.5 : 0);

        coerce('marker.symbol');
        coerce('marker.opacity');
        coerce('marker.size');
        coerce('marker.color', traceOut.line.color);
        coerce('marker.line.color');
        coerce('marker.line.width');

        if(points === 'suspectedoutliers') {
            coerce('marker.line.outliercolor', traceOut.marker.color);
            coerce('marker.line.outlierwidth');
        }

        coerce('selected.marker.color');
        coerce('unselected.marker.color');
        coerce('selected.marker.size');
        coerce('unselected.marker.size');

        coerce('text');
    } else {
        delete traceOut.marker;
    }

    coerce('hoveron');

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
}

module.exports = {
    supplyDefaults: supplyDefaults,
    handleSampleDefaults: handleSampleDefaults,
    handlePointsDefaults: handlePointsDefaults
};

},{"../../components/color":571,"../../lib":694,"../../registry":825,"./attributes":858}],862:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function eventData(out, pt) {

    // Note: hoverOnBox property is needed for click-to-select
    // to ignore when a box was clicked. This is the reason box
    // implements this custom eventData function.
    if(pt.hoverOnBox) out.hoverOnBox = pt.hoverOnBox;

    if('xVal' in pt) out.x = pt.xVal;
    if('yVal' in pt) out.y = pt.yVal;
    if(pt.xa) out.xaxis = pt.xa;
    if(pt.ya) out.yaxis = pt.ya;

    return out;
};

},{}],863:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Axes = _dereq_('../../plots/cartesian/axes');
var Lib = _dereq_('../../lib');
var Fx = _dereq_('../../components/fx');
var Color = _dereq_('../../components/color');
var fillHoverText = _dereq_('../scatter/fill_hover_text');

function hoverPoints(pointData, xval, yval, hovermode) {
    var cd = pointData.cd;
    var trace = cd[0].trace;
    var hoveron = trace.hoveron;
    var closeBoxData = [];
    var closePtData;

    if(hoveron.indexOf('boxes') !== -1) {
        closeBoxData = closeBoxData.concat(hoverOnBoxes(pointData, xval, yval, hovermode));
    }

    if(hoveron.indexOf('points') !== -1) {
        closePtData = hoverOnPoints(pointData, xval, yval);
    }

    // If there's a point in range and hoveron has points, show the best single point only.
    // If hoveron has boxes and there's no point in range (or hoveron doesn't have points), show the box stats.
    if(hovermode === 'closest') {
        if(closePtData) return [closePtData];
        return closeBoxData;
    }

    // Otherwise in compare mode, allow a point AND the box stats to be labeled
    // If there are multiple boxes in range (ie boxmode = 'overlay') we'll see stats for all of them.
    if(closePtData) {
        closeBoxData.push(closePtData);
        return closeBoxData;
    }
    return closeBoxData;
}

function hoverOnBoxes(pointData, xval, yval, hovermode) {
    var cd = pointData.cd;
    var xa = pointData.xa;
    var ya = pointData.ya;
    var trace = cd[0].trace;
    var t = cd[0].t;
    var isViolin = trace.type === 'violin';
    var closeBoxData = [];

    var pLetter, vLetter, pAxis, vAxis, vVal, pVal, dx, dy, dPos,
        hoverPseudoDistance, spikePseudoDistance;

    var boxDelta = t.bdPos;
    var posAcceptance = t.wHover;
    var shiftPos = function(di) { return di.pos + t.bPos - pVal; };

    if(isViolin && trace.side !== 'both') {
        if(trace.side === 'positive') {
            dPos = function(di) {
                var pos = shiftPos(di);
                return Fx.inbox(pos, pos + posAcceptance, hoverPseudoDistance);
            };
        }
        if(trace.side === 'negative') {
            dPos = function(di) {
                var pos = shiftPos(di);
                return Fx.inbox(pos - posAcceptance, pos, hoverPseudoDistance);
            };
        }
    } else {
        dPos = function(di) {
            var pos = shiftPos(di);
            return Fx.inbox(pos - posAcceptance, pos + posAcceptance, hoverPseudoDistance);
        };
    }

    var dVal;

    if(isViolin) {
        dVal = function(di) {
            return Fx.inbox(di.span[0] - vVal, di.span[1] - vVal, hoverPseudoDistance);
        };
    } else {
        dVal = function(di) {
            return Fx.inbox(di.min - vVal, di.max - vVal, hoverPseudoDistance);
        };
    }

    if(trace.orientation === 'h') {
        vVal = xval;
        pVal = yval;
        dx = dVal;
        dy = dPos;
        pLetter = 'y';
        pAxis = ya;
        vLetter = 'x';
        vAxis = xa;
    } else {
        vVal = yval;
        pVal = xval;
        dx = dPos;
        dy = dVal;
        pLetter = 'x';
        pAxis = xa;
        vLetter = 'y';
        vAxis = ya;
    }

    // if two boxes are overlaying, let the narrowest one win
    var pseudoDistance = Math.min(1, boxDelta / Math.abs(pAxis.r2c(pAxis.range[1]) - pAxis.r2c(pAxis.range[0])));
    hoverPseudoDistance = pointData.maxHoverDistance - pseudoDistance;
    spikePseudoDistance = pointData.maxSpikeDistance - pseudoDistance;

    function dxy(di) { return (dx(di) + dy(di)) / 2; }
    var distfn = Fx.getDistanceFunction(hovermode, dx, dy, dxy);
    Fx.getClosest(cd, distfn, pointData);

    // skip the rest (for this trace) if we didn't find a close point
    // and create the item(s) in closedata for this point
    if(pointData.index === false) return [];

    var di = cd[pointData.index];
    var lc = trace.line.color;
    var mc = (trace.marker || {}).color;

    if(Color.opacity(lc) && trace.line.width) pointData.color = lc;
    else if(Color.opacity(mc) && trace.boxpoints) pointData.color = mc;
    else pointData.color = trace.fillcolor;

    pointData[pLetter + '0'] = pAxis.c2p(di.pos + t.bPos - boxDelta, true);
    pointData[pLetter + '1'] = pAxis.c2p(di.pos + t.bPos + boxDelta, true);

    pointData[pLetter + 'LabelVal'] = di.pos;

    var spikePosAttr = pLetter + 'Spike';
    pointData.spikeDistance = dxy(di) * spikePseudoDistance / hoverPseudoDistance;
    pointData[spikePosAttr] = pAxis.c2p(di.pos, true);

    // box plots: each "point" gets many labels
    var usedVals = {};
    var attrs = ['med', 'min', 'q1', 'q3', 'max'];

    if(trace.boxmean || (trace.meanline || {}).visible) {
        attrs.push('mean');
    }
    if(trace.boxpoints || trace.points) {
        attrs.push('lf', 'uf');
    }

    for(var i = 0; i < attrs.length; i++) {
        var attr = attrs[i];

        if(!(attr in di) || (di[attr] in usedVals)) continue;
        usedVals[di[attr]] = true;

        // copy out to a new object for each value to label
        var val = di[attr];
        var valPx = vAxis.c2p(val, true);
        var pointData2 = Lib.extendFlat({}, pointData);

        pointData2[vLetter + '0'] = pointData2[vLetter + '1'] = valPx;
        pointData2[vLetter + 'LabelVal'] = val;
        pointData2[vLetter + 'Label'] = (t.labels ? t.labels[attr] + ' ' : '') + Axes.hoverLabelText(vAxis, val);

        // Note: introduced to be able to distinguish a
        // clicked point from a box during click-to-select
        pointData2.hoverOnBox = true;

        if(attr === 'mean' && ('sd' in di) && trace.boxmean === 'sd') {
            pointData2[vLetter + 'err'] = di.sd;
        }
        // only keep name and spikes on the first item (median)
        pointData.name = '';
        pointData.spikeDistance = undefined;
        pointData[spikePosAttr] = undefined;

        closeBoxData.push(pointData2);
    }

    return closeBoxData;
}

function hoverOnPoints(pointData, xval, yval) {
    var cd = pointData.cd;
    var xa = pointData.xa;
    var ya = pointData.ya;
    var trace = cd[0].trace;
    var xPx = xa.c2p(xval);
    var yPx = ya.c2p(yval);
    var closePtData;

    var dx = function(di) {
        var rad = Math.max(3, di.mrc || 0);
        return Math.max(Math.abs(xa.c2p(di.x) - xPx) - rad, 1 - 3 / rad);
    };
    var dy = function(di) {
        var rad = Math.max(3, di.mrc || 0);
        return Math.max(Math.abs(ya.c2p(di.y) - yPx) - rad, 1 - 3 / rad);
    };
    var distfn = Fx.quadrature(dx, dy);

    // show one point per trace
    var ijClosest = false;
    var di, pt;

    for(var i = 0; i < cd.length; i++) {
        di = cd[i];

        for(var j = 0; j < (di.pts || []).length; j++) {
            pt = di.pts[j];

            var newDistance = distfn(pt);
            if(newDistance <= pointData.distance) {
                pointData.distance = newDistance;
                ijClosest = [i, j];
            }
        }
    }

    if(!ijClosest) return false;

    di = cd[ijClosest[0]];
    pt = di.pts[ijClosest[1]];

    var xc = xa.c2p(pt.x, true);
    var yc = ya.c2p(pt.y, true);
    var rad = pt.mrc || 1;

    closePtData = Lib.extendFlat({}, pointData, {
        // corresponds to index in x/y input data array
        index: pt.i,
        color: (trace.marker || {}).color,
        name: trace.name,
        x0: xc - rad,
        x1: xc + rad,
        y0: yc - rad,
        y1: yc + rad,
        spikeDistance: pointData.distance
    });

    var pa;
    if(trace.orientation === 'h') {
        pa = ya;
        closePtData.xLabelVal = pt.x;
        closePtData.yLabelVal = di.pos;
    } else {
        pa = xa;
        closePtData.xLabelVal = di.pos;
        closePtData.yLabelVal = pt.y;
    }

    var pLetter = pa._id.charAt(0);
    closePtData[pLetter + 'Spike'] = pa.c2p(di.pos, true);

    fillHoverText(pt, trace, closePtData);

    return closePtData;
}

module.exports = {
    hoverPoints: hoverPoints,
    hoverOnBoxes: hoverOnBoxes,
    hoverOnPoints: hoverOnPoints
};

},{"../../components/color":571,"../../components/fx":610,"../../lib":694,"../../plots/cartesian/axes":742,"../scatter/fill_hover_text":1055}],864:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Box = {};

Box.attributes = _dereq_('./attributes');
Box.layoutAttributes = _dereq_('./layout_attributes');
Box.supplyDefaults = _dereq_('./defaults').supplyDefaults;
Box.supplyLayoutDefaults = _dereq_('./layout_defaults').supplyLayoutDefaults;
Box.calc = _dereq_('./calc');
Box.crossTraceCalc = _dereq_('./cross_trace_calc').crossTraceCalc;
Box.plot = _dereq_('./plot').plot;
Box.style = _dereq_('./style').style;
Box.styleOnSelect = _dereq_('./style').styleOnSelect;
Box.hoverPoints = _dereq_('./hover').hoverPoints;
Box.eventData = _dereq_('./event_data');
Box.selectPoints = _dereq_('./select');

Box.moduleType = 'trace';
Box.name = 'box';
Box.basePlotModule = _dereq_('../../plots/cartesian');
Box.categories = ['cartesian', 'svg', 'symbols', 'oriented', 'box-violin', 'showLegend', 'boxLayout', 'zoomScale'];
Box.meta = {
    
};

module.exports = Box;

},{"../../plots/cartesian":754,"./attributes":858,"./calc":859,"./cross_trace_calc":860,"./defaults":861,"./event_data":862,"./hover":863,"./layout_attributes":865,"./layout_defaults":866,"./plot":867,"./select":868,"./style":869}],865:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    boxmode: {
        valType: 'enumerated',
        values: ['group', 'overlay'],
        dflt: 'overlay',
        
        editType: 'calc',
        
    },
    boxgap: {
        valType: 'number',
        min: 0,
        max: 1,
        dflt: 0.3,
        
        editType: 'calc',
        
    },
    boxgroupgap: {
        valType: 'number',
        min: 0,
        max: 1,
        dflt: 0.3,
        
        editType: 'calc',
        
    }
};

},{}],866:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var layoutAttributes = _dereq_('./layout_attributes');

function _supply(layoutIn, layoutOut, fullData, coerce, traceType) {
    var hasTraceType;
    var category = traceType + 'Layout';
    for(var i = 0; i < fullData.length; i++) {
        if(Registry.traceIs(fullData[i], category)) {
            hasTraceType = true;
            break;
        }
    }
    if(!hasTraceType) return;

    coerce(traceType + 'mode');
    coerce(traceType + 'gap');
    coerce(traceType + 'groupgap');
}

function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
    function coerce(attr, dflt) {
        return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
    }
    _supply(layoutIn, layoutOut, fullData, coerce, 'box');
}

module.exports = {
    supplyLayoutDefaults: supplyLayoutDefaults,
    _supply: _supply
};

},{"../../lib":694,"../../registry":825,"./layout_attributes":865}],867:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Lib = _dereq_('../../lib');
var Drawing = _dereq_('../../components/drawing');

// constants for dynamic jitter (ie less jitter for sparser points)
var JITTERCOUNT = 5; // points either side of this to include
var JITTERSPREAD = 0.01; // fraction of IQR to count as "dense"

function plot(gd, plotinfo, cdbox, boxLayer) {
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    Lib.makeTraceGroups(boxLayer, cdbox, 'trace boxes').each(function(cd) {
        var plotGroup = d3.select(this);
        var cd0 = cd[0];
        var t = cd0.t;
        var trace = cd0.trace;
        if(!plotinfo.isRangePlot) cd0.node3 = plotGroup;

        // whisker width
        t.wdPos = t.bdPos * trace.whiskerwidth;

        if(trace.visible !== true || t.empty) {
            plotGroup.remove();
            return;
        }

        var posAxis, valAxis;

        if(trace.orientation === 'h') {
            posAxis = ya;
            valAxis = xa;
        } else {
            posAxis = xa;
            valAxis = ya;
        }

        plotBoxAndWhiskers(plotGroup, {pos: posAxis, val: valAxis}, trace, t);
        plotPoints(plotGroup, {x: xa, y: ya}, trace, t);
        plotBoxMean(plotGroup, {pos: posAxis, val: valAxis}, trace, t);
    });
}

function plotBoxAndWhiskers(sel, axes, trace, t) {
    var posAxis = axes.pos;
    var valAxis = axes.val;
    var bPos = t.bPos;
    var wdPos = t.wdPos || 0;
    var bPosPxOffset = t.bPosPxOffset || 0;
    var whiskerWidth = trace.whiskerwidth || 0;
    var notched = trace.notched || false;
    var nw = notched ? 1 - 2 * trace.notchwidth : 1;

    // to support for one-sided box
    var bdPos0;
    var bdPos1;
    if(Array.isArray(t.bdPos)) {
        bdPos0 = t.bdPos[0];
        bdPos1 = t.bdPos[1];
    } else {
        bdPos0 = t.bdPos;
        bdPos1 = t.bdPos;
    }

    var paths = sel.selectAll('path.box').data((
        trace.type !== 'violin' ||
        trace.box.visible
    ) ? Lib.identity : []);

    paths.enter().append('path')
        .style('vector-effect', 'non-scaling-stroke')
        .attr('class', 'box');

    paths.exit().remove();

    paths.each(function(d) {
        if(d.empty) return 'M0,0Z';

        var pos = d.pos;
        var posc = posAxis.c2p(pos + bPos, true) + bPosPxOffset;
        var pos0 = posAxis.c2p(pos + bPos - bdPos0, true) + bPosPxOffset;
        var pos1 = posAxis.c2p(pos + bPos + bdPos1, true) + bPosPxOffset;
        var posw0 = posAxis.c2p(pos + bPos - wdPos, true) + bPosPxOffset;
        var posw1 = posAxis.c2p(pos + bPos + wdPos, true) + bPosPxOffset;
        var posm0 = posAxis.c2p(pos + bPos - bdPos0 * nw, true) + bPosPxOffset;
        var posm1 = posAxis.c2p(pos + bPos + bdPos1 * nw, true) + bPosPxOffset;
        var q1 = valAxis.c2p(d.q1, true);
        var q3 = valAxis.c2p(d.q3, true);
        // make sure median isn't identical to either of the
        // quartiles, so we can see it
        var m = Lib.constrain(
            valAxis.c2p(d.med, true),
            Math.min(q1, q3) + 1, Math.max(q1, q3) - 1
        );

        // for compatibility with box, violin, and candlestick
        // perhaps we should put this into cd0.t instead so it's more explicit,
        // but what we have now is:
        // - box always has d.lf, but boxpoints can be anything
        // - violin has d.lf and should always use it (boxpoints is undefined)
        // - candlestick has only min/max
        var useExtremes = (d.lf === undefined) || (trace.boxpoints === false);
        var lf = valAxis.c2p(useExtremes ? d.min : d.lf, true);
        var uf = valAxis.c2p(useExtremes ? d.max : d.uf, true);
        var ln = valAxis.c2p(d.ln, true);
        var un = valAxis.c2p(d.un, true);

        if(trace.orientation === 'h') {
            d3.select(this).attr('d',
                'M' + m + ',' + posm0 + 'V' + posm1 + // median line
                'M' + q1 + ',' + pos0 + 'V' + pos1 + // left edge
                (notched ? 'H' + ln + 'L' + m + ',' + posm1 + 'L' + un + ',' + pos1 : '') + // top notched edge
                'H' + q3 + // end of the top edge
                'V' + pos0 + // right edge
                (notched ? 'H' + un + 'L' + m + ',' + posm0 + 'L' + ln + ',' + pos0 : '') + // bottom notched edge
                'Z' + // end of the box
                'M' + q1 + ',' + posc + 'H' + lf + 'M' + q3 + ',' + posc + 'H' + uf + // whiskers
                ((whiskerWidth === 0) ? '' : // whisker caps
                    'M' + lf + ',' + posw0 + 'V' + posw1 + 'M' + uf + ',' + posw0 + 'V' + posw1));
        } else {
            d3.select(this).attr('d',
                'M' + posm0 + ',' + m + 'H' + posm1 + // median line
                'M' + pos0 + ',' + q1 + 'H' + pos1 + // top of the box
                (notched ? 'V' + ln + 'L' + posm1 + ',' + m + 'L' + pos1 + ',' + un : '') + // notched right edge
                'V' + q3 + // end of the right edge
                'H' + pos0 + // bottom of the box
                (notched ? 'V' + un + 'L' + posm0 + ',' + m + 'L' + pos0 + ',' + ln : '') + // notched left edge
                'Z' + // end of the box
                'M' + posc + ',' + q1 + 'V' + lf + 'M' + posc + ',' + q3 + 'V' + uf + // whiskers
                ((whiskerWidth === 0) ? '' : // whisker caps
                    'M' + posw0 + ',' + lf + 'H' + posw1 + 'M' + posw0 + ',' + uf + 'H' + posw1));
        }
    });
}

function plotPoints(sel, axes, trace, t) {
    var xa = axes.x;
    var ya = axes.y;
    var bdPos = t.bdPos;
    var bPos = t.bPos;

    // to support violin points
    var mode = trace.boxpoints || trace.points;

    // repeatable pseudo-random number generator
    Lib.seedPseudoRandom();

    // since box plot points get an extra level of nesting, each
    // box needs the trace styling info
    var fn = function(d) {
        d.forEach(function(v) {
            v.t = t;
            v.trace = trace;
        });
        return d;
    };

    var gPoints = sel.selectAll('g.points')
        .data(mode ? fn : []);

    gPoints.enter().append('g')
        .attr('class', 'points');

    gPoints.exit().remove();

    var paths = gPoints.selectAll('path')
        .data(function(d) {
            var i;
            var pts = d.pts2;

            // normally use IQR, but if this is 0 or too small, use max-min
            var typicalSpread = Math.max((d.max - d.min) / 10, d.q3 - d.q1);
            var minSpread = typicalSpread * 1e-9;
            var spreadLimit = typicalSpread * JITTERSPREAD;
            var jitterFactors = [];
            var maxJitterFactor = 0;
            var newJitter;

            // dynamic jitter
            if(trace.jitter) {
                if(typicalSpread === 0) {
                    // edge case of no spread at all: fall back to max jitter
                    maxJitterFactor = 1;
                    jitterFactors = new Array(pts.length);
                    for(i = 0; i < pts.length; i++) {
                        jitterFactors[i] = 1;
                    }
                } else {
                    for(i = 0; i < pts.length; i++) {
                        var i0 = Math.max(0, i - JITTERCOUNT);
                        var pmin = pts[i0].v;
                        var i1 = Math.min(pts.length - 1, i + JITTERCOUNT);
                        var pmax = pts[i1].v;

                        if(mode !== 'all') {
                            if(pts[i].v < d.lf) pmax = Math.min(pmax, d.lf);
                            else pmin = Math.max(pmin, d.uf);
                        }

                        var jitterFactor = Math.sqrt(spreadLimit * (i1 - i0) / (pmax - pmin + minSpread)) || 0;
                        jitterFactor = Lib.constrain(Math.abs(jitterFactor), 0, 1);

                        jitterFactors.push(jitterFactor);
                        maxJitterFactor = Math.max(jitterFactor, maxJitterFactor);
                    }
                }
                newJitter = trace.jitter * 2 / (maxJitterFactor || 1);
            }

            // fills in 'x' and 'y' in calcdata 'pts' item
            for(i = 0; i < pts.length; i++) {
                var pt = pts[i];
                var v = pt.v;

                var jitterOffset = trace.jitter ?
                    (newJitter * jitterFactors[i] * (Lib.pseudoRandom() - 0.5)) :
                    0;

                var posPx = d.pos + bPos + bdPos * (trace.pointpos + jitterOffset);

                if(trace.orientation === 'h') {
                    pt.y = posPx;
                    pt.x = v;
                } else {
                    pt.x = posPx;
                    pt.y = v;
                }

                // tag suspected outliers
                if(mode === 'suspectedoutliers' && v < d.uo && v > d.lo) {
                    pt.so = true;
                }
            }

            return pts;
        });

    paths.enter().append('path')
        .classed('point', true);

    paths.exit().remove();

    paths.call(Drawing.translatePoints, xa, ya);
}

function plotBoxMean(sel, axes, trace, t) {
    var posAxis = axes.pos;
    var valAxis = axes.val;
    var bPos = t.bPos;
    var bPosPxOffset = t.bPosPxOffset || 0;

    // to support violin mean lines
    var mode = trace.boxmean || (trace.meanline || {}).visible;

    // to support for one-sided box
    var bdPos0;
    var bdPos1;
    if(Array.isArray(t.bdPos)) {
        bdPos0 = t.bdPos[0];
        bdPos1 = t.bdPos[1];
    } else {
        bdPos0 = t.bdPos;
        bdPos1 = t.bdPos;
    }

    var paths = sel.selectAll('path.mean').data((
        (trace.type === 'box' && trace.boxmean) ||
        (trace.type === 'violin' && trace.box.visible && trace.meanline.visible)
    ) ? Lib.identity : []);

    paths.enter().append('path')
        .attr('class', 'mean')
        .style({
            fill: 'none',
            'vector-effect': 'non-scaling-stroke'
        });

    paths.exit().remove();

    paths.each(function(d) {
        var posc = posAxis.c2p(d.pos + bPos, true) + bPosPxOffset;
        var pos0 = posAxis.c2p(d.pos + bPos - bdPos0, true) + bPosPxOffset;
        var pos1 = posAxis.c2p(d.pos + bPos + bdPos1, true) + bPosPxOffset;
        var m = valAxis.c2p(d.mean, true);
        var sl = valAxis.c2p(d.mean - d.sd, true);
        var sh = valAxis.c2p(d.mean + d.sd, true);

        if(trace.orientation === 'h') {
            d3.select(this).attr('d',
                'M' + m + ',' + pos0 + 'V' + pos1 +
                (mode === 'sd' ?
                    'm0,0L' + sl + ',' + posc + 'L' + m + ',' + pos0 + 'L' + sh + ',' + posc + 'Z' :
                    '')
            );
        } else {
            d3.select(this).attr('d',
                'M' + pos0 + ',' + m + 'H' + pos1 +
                (mode === 'sd' ?
                    'm0,0L' + posc + ',' + sl + 'L' + pos0 + ',' + m + 'L' + posc + ',' + sh + 'Z' :
                    '')
            );
        }
    });
}

module.exports = {
    plot: plot,
    plotBoxAndWhiskers: plotBoxAndWhiskers,
    plotPoints: plotPoints,
    plotBoxMean: plotBoxMean
};

},{"../../components/drawing":592,"../../lib":694,"d3":149}],868:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function selectPoints(searchInfo, selectionTester) {
    var cd = searchInfo.cd;
    var xa = searchInfo.xaxis;
    var ya = searchInfo.yaxis;
    var selection = [];
    var i, j;

    if(selectionTester === false) {
        for(i = 0; i < cd.length; i++) {
            for(j = 0; j < (cd[i].pts || []).length; j++) {
                // clear selection
                cd[i].pts[j].selected = 0;
            }
        }
    } else {
        for(i = 0; i < cd.length; i++) {
            for(j = 0; j < (cd[i].pts || []).length; j++) {
                var pt = cd[i].pts[j];
                var x = xa.c2p(pt.x);
                var y = ya.c2p(pt.y);

                if(selectionTester.contains([x, y], null, pt.i, searchInfo)) {
                    selection.push({
                        pointNumber: pt.i,
                        x: xa.c2d(pt.x),
                        y: ya.c2d(pt.y)
                    });
                    pt.selected = 1;
                } else {
                    pt.selected = 0;
                }
            }
        }
    }

    return selection;
};

},{}],869:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var Color = _dereq_('../../components/color');
var Drawing = _dereq_('../../components/drawing');

function style(gd, cd) {
    var s = cd ? cd[0].node3 : d3.select(gd).selectAll('g.trace.boxes');

    s.style('opacity', function(d) { return d[0].trace.opacity; });

    s.each(function(d) {
        var el = d3.select(this);
        var trace = d[0].trace;
        var lineWidth = trace.line.width;

        function styleBox(boxSel, lineWidth, lineColor, fillColor) {
            boxSel.style('stroke-width', lineWidth + 'px')
                .call(Color.stroke, lineColor)
                .call(Color.fill, fillColor);
        }

        var allBoxes = el.selectAll('path.box');

        if(trace.type === 'candlestick') {
            allBoxes.each(function(boxData) {
                if(boxData.empty) return;

                var thisBox = d3.select(this);
                var container = trace[boxData.dir]; // dir = 'increasing' or 'decreasing'
                styleBox(thisBox, container.line.width, container.line.color, container.fillcolor);
                // TODO: custom selection style for candlesticks
                thisBox.style('opacity', trace.selectedpoints && !boxData.selected ? 0.3 : 1);
            });
        } else {
            styleBox(allBoxes, lineWidth, trace.line.color, trace.fillcolor);
            el.selectAll('path.mean')
                .style({
                    'stroke-width': lineWidth,
                    'stroke-dasharray': (2 * lineWidth) + 'px,' + lineWidth + 'px'
                })
                .call(Color.stroke, trace.line.color);

            var pts = el.selectAll('path.point');
            Drawing.pointStyle(pts, trace, gd);
        }
    });
}

function styleOnSelect(gd, cd) {
    var s = cd[0].node3;
    var trace = cd[0].trace;
    var pts = s.selectAll('path.point');

    if(trace.selectedpoints) {
        Drawing.selectedPointStyle(pts, trace);
    } else {
        Drawing.pointStyle(pts, trace, gd);
    }
}

module.exports = {
    style: style,
    styleOnSelect: styleOnSelect
};

},{"../../components/color":571,"../../components/drawing":592,"d3":149}],870:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var extendFlat = _dereq_('../../lib').extendFlat;
var OHLCattrs = _dereq_('../ohlc/attributes');
var boxAttrs = _dereq_('../box/attributes');

function directionAttrs(lineColorDefault) {
    return {
        line: {
            color: extendFlat({}, boxAttrs.line.color, {dflt: lineColorDefault}),
            width: boxAttrs.line.width,
            editType: 'style'
        },

        fillcolor: boxAttrs.fillcolor,
        editType: 'style'
    };
}

module.exports = {
    x: OHLCattrs.x,
    open: OHLCattrs.open,
    high: OHLCattrs.high,
    low: OHLCattrs.low,
    close: OHLCattrs.close,

    line: {
        width: extendFlat({}, boxAttrs.line.width, {
            
        }),
        editType: 'style'
    },

    increasing: directionAttrs(OHLCattrs.increasing.line.color.dflt),

    decreasing: directionAttrs(OHLCattrs.decreasing.line.color.dflt),

    text: OHLCattrs.text,
    whiskerwidth: extendFlat({}, boxAttrs.whiskerwidth, { dflt: 0 }),

    hoverlabel: OHLCattrs.hoverlabel,
};

},{"../../lib":694,"../box/attributes":858,"../ohlc/attributes":995}],871:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');

var calcCommon = _dereq_('../ohlc/calc').calcCommon;

module.exports = function(gd, trace) {
    var fullLayout = gd._fullLayout;
    var xa = Axes.getFromId(gd, trace.xaxis);
    var ya = Axes.getFromId(gd, trace.yaxis);

    var x = xa.makeCalcdata(trace, 'x');

    var cd = calcCommon(gd, trace, x, ya, ptFunc);

    if(cd.length) {
        Lib.extendFlat(cd[0].t, {
            num: fullLayout._numBoxes,
            dPos: Lib.distinctVals(x).minDiff / 2,
            posLetter: 'x',
            valLetter: 'y',
        });

        fullLayout._numBoxes++;
        return cd;
    } else {
        return [{t: {empty: true}}];
    }
};

function ptFunc(o, h, l, c) {
    return {
        min: l,
        q1: Math.min(o, c),
        med: c,
        q3: Math.max(o, c),
        max: h,
    };
}

},{"../../lib":694,"../../plots/cartesian/axes":742,"../ohlc/calc":996}],872:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var Color = _dereq_('../../components/color');
var handleOHLC = _dereq_('../ohlc/ohlc_defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var len = handleOHLC(traceIn, traceOut, coerce, layout);
    if(!len) {
        traceOut.visible = false;
        return;
    }

    coerce('line.width');

    handleDirection(traceIn, traceOut, coerce, 'increasing');
    handleDirection(traceIn, traceOut, coerce, 'decreasing');

    coerce('text');
    coerce('whiskerwidth');

    layout._requestRangeslider[traceOut.xaxis] = true;
};

function handleDirection(traceIn, traceOut, coerce, direction) {
    var lineColor = coerce(direction + '.line.color');
    coerce(direction + '.line.width', traceOut.line.width);
    coerce(direction + '.fillcolor', Color.addOpacity(lineColor, 0.5));
}

},{"../../components/color":571,"../../lib":694,"../ohlc/ohlc_defaults":1000,"./attributes":870}],873:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'trace',
    name: 'candlestick',
    basePlotModule: _dereq_('../../plots/cartesian'),
    categories: ['cartesian', 'svg', 'showLegend', 'candlestick', 'boxLayout'],
    meta: {
        
    },

    attributes: _dereq_('./attributes'),
    layoutAttributes: _dereq_('../box/layout_attributes'),
    supplyLayoutDefaults: _dereq_('../box/layout_defaults').supplyLayoutDefaults,
    crossTraceCalc: _dereq_('../box/cross_trace_calc').crossTraceCalc,
    supplyDefaults: _dereq_('./defaults'),
    calc: _dereq_('./calc'),
    plot: _dereq_('../box/plot').plot,
    layerName: 'boxlayer',
    style: _dereq_('../box/style').style,
    hoverPoints: _dereq_('../ohlc/hover').hoverPoints,
    selectPoints: _dereq_('../ohlc/select')
};

},{"../../plots/cartesian":754,"../box/cross_trace_calc":860,"../box/layout_attributes":865,"../box/layout_defaults":866,"../box/plot":867,"../box/style":869,"../ohlc/hover":998,"../ohlc/select":1002,"./attributes":870,"./calc":871,"./defaults":872}],874:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var handleAxisDefaults = _dereq_('./axis_defaults');
var Template = _dereq_('../../plot_api/plot_template');

module.exports = function handleABDefaults(traceIn, traceOut, fullLayout, coerce, dfltColor) {
    var a = coerce('a');

    if(!a) {
        coerce('da');
        coerce('a0');
    }

    var b = coerce('b');

    if(!b) {
        coerce('db');
        coerce('b0');
    }

    mimickAxisDefaults(traceIn, traceOut, fullLayout, dfltColor);
};

function mimickAxisDefaults(traceIn, traceOut, fullLayout, dfltColor) {
    var axesList = ['aaxis', 'baxis'];

    axesList.forEach(function(axName) {
        var axLetter = axName.charAt(0);
        var axIn = traceIn[axName] || {};
        var axOut = Template.newContainer(traceOut, axName);

        var defaultOptions = {
            tickfont: 'x',
            id: axLetter + 'axis',
            letter: axLetter,
            font: traceOut.font,
            name: axName,
            data: traceIn[axLetter],
            calendar: traceOut.calendar,
            dfltColor: dfltColor,
            bgColor: fullLayout.paper_bgcolor,
            fullLayout: fullLayout
        };

        handleAxisDefaults(axIn, axOut, defaultOptions);
        axOut._categories = axOut._categories || [];

        // so we don't have to repeat autotype unnecessarily,
        // copy an autotype back to traceIn
        if(!traceIn[axName] && axIn.type !== '-') {
            traceIn[axName] = {type: axIn.type};
        }
    });
}

},{"../../plot_api/plot_template":732,"./axis_defaults":879}],875:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;

module.exports = function(a) {
    return minMax(a, 0);
};

function minMax(a, depth) {
    // Limit to ten dimensional datasets. This seems *exceedingly* unlikely to
    // ever cause problems or even be a concern. It's include strictly so that
    // circular arrays could never cause this to loop.
    if(!isArrayOrTypedArray(a) || depth >= 10) {
        return null;
    }

    var min = Infinity;
    var max = -Infinity;
    var n = a.length;
    for(var i = 0; i < n; i++) {
        var datum = a[i];

        if(isArrayOrTypedArray(datum)) {
            var result = minMax(datum, depth + 1);

            if(result) {
                min = Math.min(result[0], min);
                max = Math.max(result[1], max);
            }
        } else {
            min = Math.min(datum, min);
            max = Math.max(datum, max);
        }
    }

    return [min, max];
}

},{"../../lib":694}],876:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = _dereq_('../../plots/font_attributes');
var axisAttrs = _dereq_('./axis_attributes');
var colorAttrs = _dereq_('../../components/color/attributes');

var carpetFont = fontAttrs({
    editType: 'calc',
    
});
// TODO: inherit from global font
carpetFont.family.dflt = '"Open Sans", verdana, arial, sans-serif';
carpetFont.size.dflt = 12;
carpetFont.color.dflt = colorAttrs.defaultLine;

module.exports = {
    carpet: {
        valType: 'string',
        
        editType: 'calc',
        
    },
    x: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },
    y: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },
    a: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    a0: {
        valType: 'number',
        dflt: 0,
        
        editType: 'calc',
        
    },
    da: {
        valType: 'number',
        dflt: 1,
        
        editType: 'calc',
        
    },
    b: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    b0: {
        valType: 'number',
        dflt: 0,
        
        editType: 'calc',
        
    },
    db: {
        valType: 'number',
        dflt: 1,
        
        editType: 'calc',
        
    },
    cheaterslope: {
        valType: 'number',
        
        dflt: 1,
        editType: 'calc',
        
    },
    aaxis: axisAttrs,
    baxis: axisAttrs,
    font: carpetFont,
    color: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'plot',
        
    },
    transforms: undefined
};

},{"../../components/color/attributes":570,"../../plots/font_attributes":769,"./axis_attributes":878}],877:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;

/* This function retrns a set of control points that define a curve aligned along
 * either the a or b axis. Exactly one of a or b must be an array defining the range
 * spanned.
 *
 * Honestly this is the most complicated function I've implemente here so far because
 * of the way it handles knot insertion and direction/axis-agnostic slices.
 */
module.exports = function(carpet, carpetcd, a, b) {
    var idx, tangent, tanIsoIdx, tanIsoPar, segment, refidx;
    var p0, p1, v0, v1, start, end, range;

    var axis = isArrayOrTypedArray(a) ? 'a' : 'b';
    var ax = axis === 'a' ? carpet.aaxis : carpet.baxis;
    var smoothing = ax.smoothing;
    var toIdx = axis === 'a' ? carpet.a2i : carpet.b2j;
    var pt = axis === 'a' ? a : b;
    var iso = axis === 'a' ? b : a;
    var n = axis === 'a' ? carpetcd.a.length : carpetcd.b.length;
    var m = axis === 'a' ? carpetcd.b.length : carpetcd.a.length;
    var isoIdx = Math.floor(axis === 'a' ? carpet.b2j(iso) : carpet.a2i(iso));

    var xy = axis === 'a' ? function(value) {
        return carpet.evalxy([], value, isoIdx);
    } : function(value) {
        return carpet.evalxy([], isoIdx, value);
    };

    if(smoothing) {
        tanIsoIdx = Math.max(0, Math.min(m - 2, isoIdx));
        tanIsoPar = isoIdx - tanIsoIdx;
        tangent = axis === 'a' ? function(i, ti) {
            return carpet.dxydi([], i, tanIsoIdx, ti, tanIsoPar);
        } : function(j, tj) {
            return carpet.dxydj([], tanIsoIdx, j, tanIsoPar, tj);
        };
    }

    var vstart = toIdx(pt[0]);
    var vend = toIdx(pt[1]);

    // So that we can make this work in two directions, flip all of the
    // math functions if the direction is from higher to lower indices:
    //
    // Note that the tolerance is directional!
    var dir = vstart < vend ? 1 : -1;
    var tol = (vend - vstart) * 1e-8;
    var dirfloor = dir > 0 ? Math.floor : Math.ceil;
    var dirceil = dir > 0 ? Math.ceil : Math.floor;
    var dirmin = dir > 0 ? Math.min : Math.max;
    var dirmax = dir > 0 ? Math.max : Math.min;

    var idx0 = dirfloor(vstart + tol);
    var idx1 = dirceil(vend - tol);

    p0 = xy(vstart);
    var segments = [[p0]];

    for(idx = idx0; idx * dir < idx1 * dir; idx += dir) {
        segment = [];
        start = dirmax(vstart, idx);
        end = dirmin(vend, idx + dir);
        range = end - start;

        // In order to figure out which cell we're in for the derivative (remember,
        // the derivatives are *not* constant across grid lines), let's just average
        // the start and end points. This cuts out just a tiny bit of logic and
        // there's really no computational difference:
        refidx = Math.max(0, Math.min(n - 2, Math.floor(0.5 * (start + end))));

        p1 = xy(end);
        if(smoothing) {
            v0 = tangent(refidx, start - refidx);
            v1 = tangent(refidx, end - refidx);

            segment.push([
                p0[0] + v0[0] / 3 * range,
                p0[1] + v0[1] / 3 * range
            ]);

            segment.push([
                p1[0] - v1[0] / 3 * range,
                p1[1] - v1[1] / 3 * range
            ]);
        }

        segment.push(p1);

        segments.push(segment);
        p0 = p1;
    }

    return segments;
};

},{"../../lib":694}],878:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = _dereq_('../../plots/font_attributes');
var colorAttrs = _dereq_('../../components/color/attributes');
var axesAttrs = _dereq_('../../plots/cartesian/layout_attributes');
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;

module.exports = {
    color: {
        valType: 'color',
        
        editType: 'calc',
        
    },
    smoothing: {
        valType: 'number',
        dflt: 1,
        min: 0,
        max: 1.3,
        
        editType: 'calc'
    },
    title: {
        text: {
            valType: 'string',
            dflt: '',
            
            editType: 'calc',
            
        },
        font: fontAttrs({
            editType: 'calc',
            
        }),
        offset: {
            valType: 'number',
            
            dflt: 10,
            editType: 'calc',
            
        },
        editType: 'calc',
    },
    type: {
        valType: 'enumerated',
        // '-' means we haven't yet run autotype or couldn't find any data
        // it gets turned into linear in gd._fullLayout but not copied back
        // to gd.data like the others are.
        values: ['-', 'linear', 'date', 'category'],
        dflt: '-',
        
        editType: 'calc',
        
    },
    autorange: {
        valType: 'enumerated',
        values: [true, false, 'reversed'],
        dflt: true,
        
        editType: 'calc',
        
    },
    rangemode: {
        valType: 'enumerated',
        values: ['normal', 'tozero', 'nonnegative'],
        dflt: 'normal',
        
        editType: 'calc',
        
    },
    range: {
        valType: 'info_array',
        
        editType: 'calc',
        items: [
            {valType: 'any', editType: 'calc'},
            {valType: 'any', editType: 'calc'}
        ],
        
    },

    fixedrange: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'calc',
        
    },
    cheatertype: {
        valType: 'enumerated',
        values: ['index', 'value'],
        dflt: 'value',
        
        editType: 'calc'
    },
    tickmode: {
        valType: 'enumerated',
        values: ['linear', 'array'],
        dflt: 'array',
        
        editType: 'calc'
    },
    nticks: {
        valType: 'integer',
        min: 0,
        dflt: 0,
        
        editType: 'calc',
        
    },
    tickvals: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    ticktext: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    showticklabels: {
        valType: 'enumerated',
        values: ['start', 'end', 'both', 'none'],
        dflt: 'start',
        
        editType: 'calc',
        
    },
    tickfont: fontAttrs({
        editType: 'calc',
        
    }),
    tickangle: {
        valType: 'angle',
        dflt: 'auto',
        
        editType: 'calc',
        
    },
    tickprefix: {
        valType: 'string',
        dflt: '',
        
        editType: 'calc',
        
    },
    showtickprefix: {
        valType: 'enumerated',
        values: ['all', 'first', 'last', 'none'],
        dflt: 'all',
        
        editType: 'calc',
        
    },
    ticksuffix: {
        valType: 'string',
        dflt: '',
        
        editType: 'calc',
        
    },
    showticksuffix: {
        valType: 'enumerated',
        values: ['all', 'first', 'last', 'none'],
        dflt: 'all',
        
        editType: 'calc',
        
    },
    showexponent: {
        valType: 'enumerated',
        values: ['all', 'first', 'last', 'none'],
        dflt: 'all',
        
        editType: 'calc',
        
    },
    exponentformat: {
        valType: 'enumerated',
        values: ['none', 'e', 'E', 'power', 'SI', 'B'],
        dflt: 'B',
        
        editType: 'calc',
        
    },
    separatethousands: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'calc',
        
    },
    tickformat: {
        valType: 'string',
        dflt: '',
        
        editType: 'calc',
        
    },
    tickformatstops: overrideAll(axesAttrs.tickformatstops, 'calc', 'from-root'),
    categoryorder: {
        valType: 'enumerated',
        values: [
            'trace', 'category ascending', 'category descending', 'array'
            /* , 'value ascending', 'value descending'*/ // value ascending / descending to be implemented later
        ],
        dflt: 'trace',
        
        editType: 'calc',
        
    },
    categoryarray: {
        valType: 'data_array',
        
        editType: 'calc',
        
    },
    labelpadding: {
        valType: 'integer',
        
        dflt: 10,
        editType: 'calc',
        
    },
    labelprefix: {
        valType: 'string',
        
        editType: 'calc',
        
    },
    labelsuffix: {
        valType: 'string',
        dflt: '',
        
        editType: 'calc',
        
    },
    // lines and grids
    showline: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'calc',
        
    },
    linecolor: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'calc',
        
    },
    linewidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'calc',
        
    },
    gridcolor: {
        valType: 'color',
        
        editType: 'calc',
        
    },
    gridwidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'calc',
        
    },
    showgrid: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'calc',
        
    },
    minorgridcount: {
        valType: 'integer',
        min: 0,
        dflt: 0,
        
        editType: 'calc',
        
    },
    minorgridwidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'calc',
        
    },
    minorgridcolor: {
        valType: 'color',
        dflt: colorAttrs.lightLine,
        
        editType: 'calc',
        
    },
    startline: {
        valType: 'boolean',
        
        editType: 'calc',
        
    },
    startlinecolor: {
        valType: 'color',
        
        editType: 'calc',
        
    },
    startlinewidth: {
        valType: 'number',
        dflt: 1,
        
        editType: 'calc',
        
    },
    endline: {
        valType: 'boolean',
        
        editType: 'calc',
        
    },
    endlinewidth: {
        valType: 'number',
        dflt: 1,
        
        editType: 'calc',
        
    },
    endlinecolor: {
        valType: 'color',
        
        editType: 'calc',
        
    },
    tick0: {
        valType: 'number',
        min: 0,
        dflt: 0,
        
        editType: 'calc',
        
    },
    dtick: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'calc',
        
    },
    arraytick0: {
        valType: 'integer',
        min: 0,
        dflt: 0,
        
        editType: 'calc',
        
    },
    arraydtick: {
        valType: 'integer',
        min: 1,
        dflt: 1,
        
        editType: 'calc',
        
    },

    _deprecated: {
        title: {
            valType: 'string',
            
            editType: 'calc',
            
        },
        titlefont: fontAttrs({
            editType: 'calc',
            
        }),
        titleoffset: {
            valType: 'number',
            
            dflt: 10,
            editType: 'calc',
            
        }
    },

    editType: 'calc'
};

},{"../../components/color/attributes":570,"../../plot_api/edit_types":725,"../../plots/cartesian/layout_attributes":755,"../../plots/font_attributes":769}],879:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var carpetAttrs = _dereq_('./attributes');

var addOpacity = _dereq_('../../components/color').addOpacity;
var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var handleTickValueDefaults = _dereq_('../../plots/cartesian/tick_value_defaults');
var handleTickLabelDefaults = _dereq_('../../plots/cartesian/tick_label_defaults');
var handleCategoryOrderDefaults = _dereq_('../../plots/cartesian/category_order_defaults');
var setConvert = _dereq_('../../plots/cartesian/set_convert');
var autoType = _dereq_('../../plots/cartesian/axis_autotype');

/**
 * options: object containing:
 *
 *  letter: 'a' or 'b'
 *  title: name of the axis (ie 'Colorbar') to go in default title
 *  name: axis object name (ie 'xaxis') if one should be stored
 *  font: the default font to inherit
 *  outerTicks: boolean, should ticks default to outside?
 *  showGrid: boolean, should gridlines be shown by default?
 *  data: the plot data to use in choosing auto type
 *  bgColor: the plot background color, to calculate default gridline colors
 */
module.exports = function handleAxisDefaults(containerIn, containerOut, options) {
    var letter = options.letter;
    var font = options.font || {};
    var attributes = carpetAttrs[letter + 'axis'];

    function coerce(attr, dflt) {
        return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
    }

    function coerce2(attr, dflt) {
        return Lib.coerce2(containerIn, containerOut, attributes, attr, dflt);
    }

    // set up some private properties
    if(options.name) {
        containerOut._name = options.name;
        containerOut._id = options.name;
    }

    // now figure out type and do some more initialization
    var axType = coerce('type');
    if(axType === '-') {
        if(options.data) setAutoType(containerOut, options.data);

        if(containerOut.type === '-') {
            containerOut.type = 'linear';
        }
        else {
            // copy autoType back to input axis
            // note that if this object didn't exist
            // in the input layout, we have to put it in
            // this happens in the main supplyDefaults function
            axType = containerIn.type = containerOut.type;
        }
    }

    coerce('smoothing');
    coerce('cheatertype');

    coerce('showticklabels');
    coerce('labelprefix', letter + ' = ');
    coerce('labelsuffix');
    coerce('showtickprefix');
    coerce('showticksuffix');

    coerce('separatethousands');
    coerce('tickformat');
    coerce('exponentformat');
    coerce('showexponent');
    coerce('categoryorder');

    coerce('tickmode');
    coerce('tickvals');
    coerce('ticktext');
    coerce('tick0');
    coerce('dtick');

    if(containerOut.tickmode === 'array') {
        coerce('arraytick0');
        coerce('arraydtick');
    }

    coerce('labelpadding');

    containerOut._hovertitle = letter;


    if(axType === 'date') {
        var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleDefaults');
        handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar);
    }

    // we need some of the other functions setConvert attaches, but for
    // path finding, override pixel scaling to simple passthrough (identity)
    setConvert(containerOut, options.fullLayout);
    containerOut.c2p = Lib.identity;

    var dfltColor = coerce('color', options.dfltColor);
    // if axis.color was provided, use it for fonts too; otherwise,
    // inherit from global font color in case that was provided.
    var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color;

    var title = coerce('title.text');
    if(title) {
        Lib.coerceFont(coerce, 'title.font', {
            family: font.family,
            size: Math.round(font.size * 1.2),
            color: dfltFontColor
        });
        coerce('title.offset');
    }

    coerce('tickangle');

    var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range));

    if(autoRange) coerce('rangemode');

    coerce('range');
    containerOut.cleanRange();

    coerce('fixedrange');

    handleTickValueDefaults(containerIn, containerOut, coerce, axType);
    handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options);
    handleCategoryOrderDefaults(containerIn, containerOut, coerce, {
        data: options.data,
        dataAttr: letter
    });

    var gridColor = coerce2('gridcolor', addOpacity(dfltColor, 0.3));
    var gridWidth = coerce2('gridwidth');
    var showGrid = coerce('showgrid');

    if(!showGrid) {
        delete containerOut.gridcolor;
        delete containerOut.gridwidth;
    }

    var startLineColor = coerce2('startlinecolor', dfltColor);
    var startLineWidth = coerce2('startlinewidth', gridWidth);
    var showStartLine = coerce('startline', containerOut.showgrid || !!startLineColor || !!startLineWidth);

    if(!showStartLine) {
        delete containerOut.startlinecolor;
        delete containerOut.startlinewidth;
    }

    var endLineColor = coerce2('endlinecolor', dfltColor);
    var endLineWidth = coerce2('endlinewidth', gridWidth);
    var showEndLine = coerce('endline', containerOut.showgrid || !!endLineColor || !!endLineWidth);

    if(!showEndLine) {
        delete containerOut.endlinecolor;
        delete containerOut.endlinewidth;
    }

    if(!showGrid) {
        delete containerOut.gridcolor;
        delete containerOut.gridWidth;
    } else {
        coerce('minorgridcount');
        coerce('minorgridwidth', gridWidth);
        coerce('minorgridcolor', addOpacity(gridColor, 0.06));

        if(!containerOut.minorgridcount) {
            delete containerOut.minorgridwidth;
            delete containerOut.minorgridcolor;
        }
    }

    if(containerOut.showticklabels === 'none') {
        delete containerOut.tickfont;
        delete containerOut.tickangle;
        delete containerOut.showexponent;
        delete containerOut.exponentformat;
        delete containerOut.tickformat;
        delete containerOut.showticksuffix;
        delete containerOut.showtickprefix;
    }

    if(!containerOut.showticksuffix) {
        delete containerOut.ticksuffix;
    }

    if(!containerOut.showtickprefix) {
        delete containerOut.tickprefix;
    }

    // It needs to be coerced, then something above overrides this deep in the axis code,
    // but no, we *actually* want to coerce this.
    coerce('tickmode');

    return containerOut;
};

function setAutoType(ax, data) {
    // new logic: let people specify any type they want,
    // only autotype if type is '-'
    if(ax.type !== '-') return;

    var id = ax._id;
    var axLetter = id.charAt(0);

    var calAttr = axLetter + 'calendar';
    var calendar = ax[calAttr];

    ax.type = autoType(data, calendar);
}

},{"../../components/color":571,"../../lib":694,"../../plots/cartesian/axis_autotype":743,"../../plots/cartesian/category_order_defaults":746,"../../plots/cartesian/set_convert":761,"../../plots/cartesian/tick_label_defaults":762,"../../plots/cartesian/tick_value_defaults":764,"../../registry":825,"./attributes":876}],880:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Axes = _dereq_('../../plots/cartesian/axes');
var isArray1D = _dereq_('../../lib').isArray1D;
var cheaterBasis = _dereq_('./cheater_basis');
var arrayMinmax = _dereq_('./array_minmax');
var calcGridlines = _dereq_('./calc_gridlines');
var calcLabels = _dereq_('./calc_labels');
var calcClipPath = _dereq_('./calc_clippath');
var clean2dArray = _dereq_('../heatmap/clean_2d_array');
var smoothFill2dArray = _dereq_('./smooth_fill_2d_array');
var convertColumnData = _dereq_('../heatmap/convert_column_xyz');
var setConvert = _dereq_('./set_convert');

module.exports = function calc(gd, trace) {
    var xa = Axes.getFromId(gd, trace.xaxis);
    var ya = Axes.getFromId(gd, trace.yaxis);
    var aax = trace.aaxis;
    var bax = trace.baxis;

    var x = trace.x;
    var y = trace.y;
    var cols = [];
    if(x && isArray1D(x)) cols.push('x');
    if(y && isArray1D(y)) cols.push('y');

    if(cols.length) {
        convertColumnData(trace, aax, bax, 'a', 'b', cols);
    }

    var a = trace._a = trace._a || trace.a;
    var b = trace._b = trace._b || trace.b;
    x = trace._x || trace.x;
    y = trace._y || trace.y;

    var t = {};

    if(trace._cheater) {
        var avals = aax.cheatertype === 'index' ? a.length : a;
        var bvals = bax.cheatertype === 'index' ? b.length : b;
        x = cheaterBasis(avals, bvals, trace.cheaterslope);
    }

    trace._x = x = clean2dArray(x);
    trace._y = y = clean2dArray(y);

    // Fill in any undefined values with elliptic smoothing. This doesn't take
    // into account the spacing of the values. That is, the derivatives should
    // be modified to use a and b values. It's not that hard, but this is already
    // moderate overkill for just filling in missing values.
    smoothFill2dArray(x, a, b);
    smoothFill2dArray(y, a, b);

    setConvert(trace);

    // create conversion functions that depend on the data
    trace.setScale();

    // This is a rather expensive scan. Nothing guarantees monotonicity,
    // so we need to scan through all data to get proper ranges:
    var xrange = arrayMinmax(x);
    var yrange = arrayMinmax(y);

    var dx = 0.5 * (xrange[1] - xrange[0]);
    var xc = 0.5 * (xrange[1] + xrange[0]);

    var dy = 0.5 * (yrange[1] - yrange[0]);
    var yc = 0.5 * (yrange[1] + yrange[0]);

    // Expand the axes to fit the plot, except just grow it by a factor of 1.3
    // because the labels should be taken into account except that's difficult
    // hence 1.3.
    var grow = 1.3;
    xrange = [xc - dx * grow, xc + dx * grow];
    yrange = [yc - dy * grow, yc + dy * grow];

    trace._extremes[xa._id] = Axes.findExtremes(xa, xrange, {padded: true});
    trace._extremes[ya._id] = Axes.findExtremes(ya, yrange, {padded: true});

    // Enumerate the gridlines, both major and minor, and store them on the trace
    // object:
    calcGridlines(trace, 'a', 'b');
    calcGridlines(trace, 'b', 'a');

    // Calculate the text labels for each major gridline and store them on the
    // trace object:
    calcLabels(trace, aax);
    calcLabels(trace, bax);

    // Tabulate points for the four segments that bound the axes so that we can
    // map to pixel coordinates in the plot function and create a clip rect:
    t.clipsegments = calcClipPath(trace._xctrl, trace._yctrl, aax, bax);

    t.x = x;
    t.y = y;
    t.a = a;
    t.b = b;

    return [t];
};

},{"../../lib":694,"../../plots/cartesian/axes":742,"../heatmap/clean_2d_array":946,"../heatmap/convert_column_xyz":948,"./array_minmax":875,"./calc_clippath":881,"./calc_gridlines":882,"./calc_labels":883,"./cheater_basis":885,"./set_convert":898,"./smooth_fill_2d_array":899}],881:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = function makeClipPath(xctrl, yctrl, aax, bax) {
    var i, x, y;
    var segments = [];

    var asmoothing = !!aax.smoothing;
    var bsmoothing = !!bax.smoothing;
    var nea1 = xctrl[0].length - 1;
    var neb1 = xctrl.length - 1;

    // Along the lower a axis:
    for(i = 0, x = [], y = []; i <= nea1; i++) {
        x[i] = xctrl[0][i];
        y[i] = yctrl[0][i];
    }
    segments.push({x: x, y: y, bicubic: asmoothing});

    // Along the upper b axis:
    for(i = 0, x = [], y = []; i <= neb1; i++) {
        x[i] = xctrl[i][nea1];
        y[i] = yctrl[i][nea1];
    }
    segments.push({x: x, y: y, bicubic: bsmoothing});

    // Backwards along the upper a axis:
    for(i = nea1, x = [], y = []; i >= 0; i--) {
        x[nea1 - i] = xctrl[neb1][i];
        y[nea1 - i] = yctrl[neb1][i];
    }
    segments.push({x: x, y: y, bicubic: asmoothing});

    // Backwards along the lower b axis:
    for(i = neb1, x = [], y = []; i >= 0; i--) {
        x[neb1 - i] = xctrl[i][0];
        y[neb1 - i] = yctrl[i][0];
    }
    segments.push({x: x, y: y, bicubic: bsmoothing});

    return segments;
};

},{}],882:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Axes = _dereq_('../../plots/cartesian/axes');
var extendFlat = _dereq_('../../lib/extend').extendFlat;

module.exports = function calcGridlines(trace, axisLetter, crossAxisLetter) {
    var i, j, j0;
    var eps, bounds, n1, n2, n, value, v;
    var j1, v0, v1, d;

    var data = trace['_' + axisLetter];
    var axis = trace[axisLetter + 'axis'];

    var gridlines = axis._gridlines = [];
    var minorgridlines = axis._minorgridlines = [];
    var boundarylines = axis._boundarylines = [];

    var crossData = trace['_' + crossAxisLetter];
    var crossAxis = trace[crossAxisLetter + 'axis'];

    if(axis.tickmode === 'array') {
        axis.tickvals = data.slice();
    }

    var xcp = trace._xctrl;
    var ycp = trace._yctrl;
    var nea = xcp[0].length;
    var neb = xcp.length;
    var na = trace._a.length;
    var nb = trace._b.length;

    Axes.prepTicks(axis);

    // don't leave tickvals in axis looking like an attribute
    if(axis.tickmode === 'array') delete axis.tickvals;

    // The default is an empty array that will cause the join to remove the gridline if
    // it's just disappeared:
    // axis._startline = axis._endline = [];

    // If the cross axis uses bicubic interpolation, then the grid
    // lines fall once every three expanded grid row/cols:
    var stride = axis.smoothing ? 3 : 1;

    function constructValueGridline(value) {
        var i, j, j0, tj, pxy, i0, ti, xy, dxydi0, dxydi1, dxydj0, dxydj1;
        var xpoints = [];
        var ypoints = [];
        var ret = {};
        // Search for the fractional grid index giving this line:
        if(axisLetter === 'b') {
            // For the position we use just the i-j coordinates:
            j = trace.b2j(value);

            // The derivatives for catmull-rom splines are discontinuous across cell
            // boundaries though, so we need to provide both the cell and the position
            // within the cell separately:
            j0 = Math.floor(Math.max(0, Math.min(nb - 2, j)));
            tj = j - j0;

            ret.length = nb;
            ret.crossLength = na;

            ret.xy = function(i) {
                return trace.evalxy([], i, j);
            };

            ret.dxy = function(i0, ti) {
                return trace.dxydi([], i0, j0, ti, tj);
            };

            for(i = 0; i < na; i++) {
                i0 = Math.min(na - 2, i);
                ti = i - i0;
                xy = trace.evalxy([], i, j);

                if(crossAxis.smoothing && i > 0) {
                    // First control point:
                    dxydi0 = trace.dxydi([], i - 1, j0, 0, tj);
                    xpoints.push(pxy[0] + dxydi0[0] / 3);
                    ypoints.push(pxy[1] + dxydi0[1] / 3);

                    // Second control point:
                    dxydi1 = trace.dxydi([], i - 1, j0, 1, tj);
                    xpoints.push(xy[0] - dxydi1[0] / 3);
                    ypoints.push(xy[1] - dxydi1[1] / 3);
                }

                xpoints.push(xy[0]);
                ypoints.push(xy[1]);

                pxy = xy;
            }
        } else {
            i = trace.a2i(value);
            i0 = Math.floor(Math.max(0, Math.min(na - 2, i)));
            ti = i - i0;

            ret.length = na;
            ret.crossLength = nb;

            ret.xy = function(j) {
                return trace.evalxy([], i, j);
            };

            ret.dxy = function(j0, tj) {
                return trace.dxydj([], i0, j0, ti, tj);
            };

            for(j = 0; j < nb; j++) {
                j0 = Math.min(nb - 2, j);
                tj = j - j0;
                xy = trace.evalxy([], i, j);

                if(crossAxis.smoothing && j > 0) {
                    // First control point:
                    dxydj0 = trace.dxydj([], i0, j - 1, ti, 0);
                    xpoints.push(pxy[0] + dxydj0[0] / 3);
                    ypoints.push(pxy[1] + dxydj0[1] / 3);

                    // Second control point:
                    dxydj1 = trace.dxydj([], i0, j - 1, ti, 1);
                    xpoints.push(xy[0] - dxydj1[0] / 3);
                    ypoints.push(xy[1] - dxydj1[1] / 3);
                }

                xpoints.push(xy[0]);
                ypoints.push(xy[1]);

                pxy = xy;
            }
        }

        ret.axisLetter = axisLetter;
        ret.axis = axis;
        ret.crossAxis = crossAxis;
        ret.value = value;
        ret.constvar = crossAxisLetter;
        ret.index = n;
        ret.x = xpoints;
        ret.y = ypoints;
        ret.smoothing = crossAxis.smoothing;

        return ret;
    }

    function constructArrayGridline(idx) {
        var j, i0, j0, ti, tj;
        var xpoints = [];
        var ypoints = [];
        var ret = {};
        ret.length = data.length;
        ret.crossLength = crossData.length;

        if(axisLetter === 'b') {
            j0 = Math.max(0, Math.min(nb - 2, idx));
            tj = Math.min(1, Math.max(0, idx - j0));

            ret.xy = function(i) {
                return trace.evalxy([], i, idx);
            };

            ret.dxy = function(i0, ti) {
                return trace.dxydi([], i0, j0, ti, tj);
            };

            // In the tickmode: array case, this operation is a simple
            // transfer of data:
            for(j = 0; j < nea; j++) {
                xpoints[j] = xcp[idx * stride][j];
                ypoints[j] = ycp[idx * stride][j];
            }
        } else {
            i0 = Math.max(0, Math.min(na - 2, idx));
            ti = Math.min(1, Math.max(0, idx - i0));

            ret.xy = function(j) {
                return trace.evalxy([], idx, j);
            };

            ret.dxy = function(j0, tj) {
                return trace.dxydj([], i0, j0, ti, tj);
            };

            // In the tickmode: array case, this operation is a simple
            // transfer of data:
            for(j = 0; j < neb; j++) {
                xpoints[j] = xcp[j][idx * stride];
                ypoints[j] = ycp[j][idx * stride];
            }
        }

        ret.axisLetter = axisLetter;
        ret.axis = axis;
        ret.crossAxis = crossAxis;
        ret.value = data[idx];
        ret.constvar = crossAxisLetter;
        ret.index = idx;
        ret.x = xpoints;
        ret.y = ypoints;
        ret.smoothing = crossAxis.smoothing;

        return ret;
    }

    if(axis.tickmode === 'array') {
        // var j0 = axis.startline ? 1 : 0;
        // var j1 = data.length - (axis.endline ? 1 : 0);

        eps = 5e-15;
        bounds = [
            Math.floor(((data.length - 1) - axis.arraytick0) / axis.arraydtick * (1 + eps)),
            Math.ceil((- axis.arraytick0) / axis.arraydtick / (1 + eps))
        ].sort(function(a, b) {return a - b;});

        // Unpack sorted values so we can be sure to avoid infinite loops if something
        // is backwards:
        n1 = bounds[0] - 1;
        n2 = bounds[1] + 1;

        // If the axes fall along array lines, then this is a much simpler process since
        // we already have all the control points we need
        for(n = n1; n < n2; n++) {
            j = axis.arraytick0 + axis.arraydtick * n;
            if(j < 0 || j > data.length - 1) continue;
            gridlines.push(extendFlat(constructArrayGridline(j), {
                color: axis.gridcolor,
                width: axis.gridwidth
            }));
        }

        for(n = n1; n < n2; n++) {
            j0 = axis.arraytick0 + axis.arraydtick * n;
            j1 = Math.min(j0 + axis.arraydtick, data.length - 1);

            // TODO: fix the bounds computation so we don't have to do a large range and then throw
            // out unneeded numbers
            if(j0 < 0 || j0 > data.length - 1) continue;
            if(j1 < 0 || j1 > data.length - 1) continue;

            v0 = data[j0];
            v1 = data[j1];

            for(i = 0; i < axis.minorgridcount; i++) {
                d = j1 - j0;

                // TODO: fix the bounds computation so we don't have to do a large range and then throw
                // out unneeded numbers
                if(d <= 0) continue;

                // XXX: This calculation isn't quite right. Off by one somewhere?
                v = v0 + (v1 - v0) * (i + 1) / (axis.minorgridcount + 1) * (axis.arraydtick / d);

                // TODO: fix the bounds computation so we don't have to do a large range and then throw
                // out unneeded numbers
                if(v < data[0] || v > data[data.length - 1]) continue;
                minorgridlines.push(extendFlat(constructValueGridline(v), {
                    color: axis.minorgridcolor,
                    width: axis.minorgridwidth
                }));
            }
        }

        if(axis.startline) {
            boundarylines.push(extendFlat(constructArrayGridline(0), {
                color: axis.startlinecolor,
                width: axis.startlinewidth
            }));
        }

        if(axis.endline) {
            boundarylines.push(extendFlat(constructArrayGridline(data.length - 1), {
                color: axis.endlinecolor,
                width: axis.endlinewidth
            }));
        }
    } else {
        // If the lines do not fall along the axes, then we have to interpolate
        // the contro points and so some math to figure out where the lines are
        // in the first place.

        // Compute the integer boudns of tick0 + n * dtick that fall within the range
        // (roughly speaking):
        // Give this a nice generous epsilon. We use at as * (1 + eps) in order to make
        // inequalities a little tolerant in a more or less correct manner:
        eps = 5e-15;
        bounds = [
            Math.floor((data[data.length - 1] - axis.tick0) / axis.dtick * (1 + eps)),
            Math.ceil((data[0] - axis.tick0) / axis.dtick / (1 + eps))
        ].sort(function(a, b) {return a - b;});

        // Unpack sorted values so we can be sure to avoid infinite loops if something
        // is backwards:
        n1 = bounds[0];
        n2 = bounds[1];

        for(n = n1; n <= n2; n++) {
            value = axis.tick0 + axis.dtick * n;

            gridlines.push(extendFlat(constructValueGridline(value), {
                color: axis.gridcolor,
                width: axis.gridwidth
            }));
        }

        for(n = n1 - 1; n < n2 + 1; n++) {
            value = axis.tick0 + axis.dtick * n;

            for(i = 0; i < axis.minorgridcount; i++) {
                v = value + axis.dtick * (i + 1) / (axis.minorgridcount + 1);
                if(v < data[0] || v > data[data.length - 1]) continue;
                minorgridlines.push(extendFlat(constructValueGridline(v), {
                    color: axis.minorgridcolor,
                    width: axis.minorgridwidth
                }));
            }
        }

        if(axis.startline) {
            boundarylines.push(extendFlat(constructValueGridline(data[0]), {
                color: axis.startlinecolor,
                width: axis.startlinewidth
            }));
        }

        if(axis.endline) {
            boundarylines.push(extendFlat(constructValueGridline(data[data.length - 1]), {
                color: axis.endlinecolor,
                width: axis.endlinewidth
            }));
        }
    }
};

},{"../../lib/extend":684,"../../plots/cartesian/axes":742}],883:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Axes = _dereq_('../../plots/cartesian/axes');
var extendFlat = _dereq_('../../lib/extend').extendFlat;

module.exports = function calcLabels(trace, axis) {
    var i, tobj, prefix, suffix, gridline;

    var labels = axis._labels = [];
    var gridlines = axis._gridlines;

    for(i = 0; i < gridlines.length; i++) {
        gridline = gridlines[i];

        if(['start', 'both'].indexOf(axis.showticklabels) !== -1) {
            tobj = Axes.tickText(axis, gridline.value);

            extendFlat(tobj, {
                prefix: prefix,
                suffix: suffix,
                endAnchor: true,
                xy: gridline.xy(0),
                dxy: gridline.dxy(0, 0),
                axis: gridline.axis,
                length: gridline.crossAxis.length,
                font: gridline.axis.tickfont,
                isFirst: i === 0,
                isLast: i === gridlines.length - 1
            });

            labels.push(tobj);
        }

        if(['end', 'both'].indexOf(axis.showticklabels) !== -1) {
            tobj = Axes.tickText(axis, gridline.value);

            extendFlat(tobj, {
                endAnchor: false,
                xy: gridline.xy(gridline.crossLength - 1),
                dxy: gridline.dxy(gridline.crossLength - 2, 1),
                axis: gridline.axis,
                length: gridline.crossAxis.length,
                font: gridline.axis.tickfont,
                isFirst: i === 0,
                isLast: i === gridlines.length - 1
            });

            labels.push(tobj);
        }
    }
};

},{"../../lib/extend":684,"../../plots/cartesian/axes":742}],884:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/*
 * Compute the tangent vector according to catmull-rom cubic splines (centripetal,
 * I think). That differs from the control point in two ways:
 *   1. It is a vector, not a position relative to the point
 *   2. the vector is longer than the position relative to p1 by a factor of 3
 *
 * Close to the boundaries, we'll use these as *quadratic control points, so that
 * to make a nice grid, we'll need to divide the tangent by 2 instead of 3. (The
 * math works out this way if you work through the bezier derivatives)
 */
var CatmullRomExp = 0.5;
module.exports = function makeControlPoints(p0, p1, p2, smoothness) {
    var d1x = p0[0] - p1[0];
    var d1y = p0[1] - p1[1];
    var d2x = p2[0] - p1[0];
    var d2y = p2[1] - p1[1];
    var d1a = Math.pow(d1x * d1x + d1y * d1y, CatmullRomExp / 2);
    var d2a = Math.pow(d2x * d2x + d2y * d2y, CatmullRomExp / 2);
    var numx = (d2a * d2a * d1x - d1a * d1a * d2x) * smoothness;
    var numy = (d2a * d2a * d1y - d1a * d1a * d2y) * smoothness;
    var denom1 = d2a * (d1a + d2a) * 3;
    var denom2 = d1a * (d1a + d2a) * 3;

    return [[
        p1[0] + (denom1 && numx / denom1),
        p1[1] + (denom1 && numy / denom1)
    ], [
        p1[0] - (denom2 && numx / denom2),
        p1[1] - (denom2 && numy / denom2)
    ]];
};

},{}],885:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;

/*
 * Construct a 2D array of cheater values given a, b, and a slope.
 * If
 */
module.exports = function(a, b, cheaterslope) {
    var i, j, ascal, bscal, aval, bval;
    var data = [];

    var na = isArrayOrTypedArray(a) ? a.length : a;
    var nb = isArrayOrTypedArray(b) ? b.length : b;
    var adata = isArrayOrTypedArray(a) ? a : null;
    var bdata = isArrayOrTypedArray(b) ? b : null;

    // If we're using data, scale it so that for data that's just barely
    // not evenly spaced, the switch to value-based indexing is continuous.
    // This means evenly spaced data should look the same whether value
    // or index cheatertype.
    if(adata) {
        ascal = (adata.length - 1) / (adata[adata.length - 1] - adata[0]) / (na - 1);
    }

    if(bdata) {
        bscal = (bdata.length - 1) / (bdata[bdata.length - 1] - bdata[0]) / (nb - 1);
    }

    var xval;
    var xmin = Infinity;
    var xmax = -Infinity;
    for(j = 0; j < nb; j++) {
        data[j] = [];
        bval = bdata ? (bdata[j] - bdata[0]) * bscal : j / (nb - 1);
        for(i = 0; i < na; i++) {
            aval = adata ? (adata[i] - adata[0]) * ascal : i / (na - 1);
            xval = aval - bval * cheaterslope;
            xmin = Math.min(xval, xmin);
            xmax = Math.max(xval, xmax);
            data[j][i] = xval;
        }
    }

    // Normalize cheater values to the 0-1 range. This comes into play when you have
    // multiple cheater plots. After careful consideration, it seems better if cheater
    // values are normalized to a consistent range. Otherwise one cheater affects the
    // layout of other cheaters on the same axis.
    var slope = 1.0 / (xmax - xmin);
    var offset = -xmin * slope;
    for(j = 0; j < nb; j++) {
        for(i = 0; i < na; i++) {
            data[j][i] = slope * data[j][i] + offset;
        }
    }

    return data;
};

},{"../../lib":694}],886:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var makeControlPoints = _dereq_('./catmull_rom');
var ensureArray = _dereq_('../../lib').ensureArray;

/*
 * Turns a coarse grid into a fine grid with control points.
 *
 * Here's an ASCII representation:
 *
 *       o ----- o ----- o ----- o
 *       |       |       |       |
 *       |       |       |       |
 *       |       |       |       |
 *       o ----- o ----- o ----- o
 *       |       |       |       |
 *       |       |       |       |
 *    ^  |       |       |       |
 *    |  o ----- o ----- o ----- o
 *  b |  |       |       |       |
 *    |  |       |       |       |
 *    |  |       |       |       |
 *       o ----- o ----- o ----- o
 *         ------>
 *           a
 *
 * First of all, note that we want to do this in *cartesian* space. This means
 * we might run into problems when there are extreme differences in x/y scaling,
 * but the alternative is that the topology of the contours might actually be
 * view-dependent, which seems worse. As a fallback, the only parameter that
 * actually affects the result is the *aspect ratio*, so that we can at least
 * improve the situation a bit without going all the way to screen coordinates.
 *
 * This function flattens the points + tangents  into a slightly denser grid of
 * *control points*. The resulting grid looks like this:
 *
 *       9 +--o-o--+ -o-o--+--o-o--+
 *       8 o  o o  o  o o  o  o o  o
 *         |       |       |       |
 *       7 o  o o  o  o o  o  o o  o
 *       6 +--o-o--+ -o-o--+--o-o--+
 *       5 o  o o  o  o o  o  o o  o
 *         |       |       |       |
 *    ^  4 o  o o  o  o o  o  o o  o
 *    |  3 +--o-o--+ -o-o--+--o-o--+
 *  b |  2 o  o o  o  o o  o  o o  o
 *    |    |       |       |       |
 *    |  1 o  o o  o  o o  o  o o  o
 *       0 +--o-o--+ -o-o--+--o-o--+
 *         0  1 2  3  4 5  6  7 8  9
 *         ------>
 *           a
 *
 * where `o`s represent newly-computed control points. the resulting dimension is
 *
 *     (m - 1) * 3 + 1
 *   = 3 * m - 2
 *
 * We could simply store the tangents separately, but that's a nightmare to organize
 * in two dimensions since we'll be slicing grid lines in both directions and since
 * that basically requires very nearly just as much storage as just storing the dense
 * grid.
 *
 * Wow!
 */


/*
 * Catmull-rom is biased at the boundaries toward the interior and we actually
 * can't use catmull-rom to compute the control point closest to (but inside)
 * the boundary.
 *
 * A note on plotly's spline interpolation. It uses the catmull rom control point
 * closest to the boundary *as* a quadratic control point. This seems incorrect,
 * so I've elected not to follow that. Given control points 0 and 1, regular plotly
 * splines give *equivalent* cubic control points:
 *
 * Input:
 *
 *   boundary
 *     |                    |
 *     p0           p2      p3    --> interior
 *     0.0          0.667   1.0
 *     |                    |
 *
 * Cubic-equivalent of what plotly splines draw::
 *
 *   boundary
 *     |                    |
 *     p0   p1      p2      p3    --> interior
 *     0.0  0.4444  0.8888  1.0
 *     |                    |
 *
 * What this function fills in:
 *
 *   boundary
 *     |                    |
 *     p0    p1     p2      p3    --> interior
 *     0.0   0.333  0.667   1.0
 *     |                    |
 *
 * Parameters:
 *   p0: boundary point
 *   p2: catmull rom point based on computation at p3
 *   p3: first grid point
 *
 * Of course it works whichever way it's oriented; you just need to interpret the
 * input/output accordingly.
 */
function inferCubicControlPoint(p0, p2, p3) {
    // Extend p1 away from p0 by 50%. This is the equivalent quadratic point that
    // would give the same slope as catmull rom at p0.
    var p2e0 = -0.5 * p3[0] + 1.5 * p2[0];
    var p2e1 = -0.5 * p3[1] + 1.5 * p2[1];

    return [
        (2 * p2e0 + p0[0]) / 3,
        (2 * p2e1 + p0[1]) / 3,
    ];
}

module.exports = function computeControlPoints(xe, ye, x, y, asmoothing, bsmoothing) {
    var i, j, ie, je, xej, yej, xj, yj, cp, p1;
    // At this point, we know these dimensions are correct and representative of
    // the whole 2D arrays:
    var na = x[0].length;
    var nb = x.length;

    // (n)umber of (e)xpanded points:
    var nea = asmoothing ? 3 * na - 2 : na;
    var neb = bsmoothing ? 3 * nb - 2 : nb;

    xe = ensureArray(xe, neb);
    ye = ensureArray(ye, neb);

    for(ie = 0; ie < neb; ie++) {
        xe[ie] = ensureArray(xe[ie], nea);
        ye[ie] = ensureArray(ye[ie], nea);
    }

    // This loop fills in the X'd points:
    //
    //    .       .       .       .
    //    .       .       .       .
    //    |       |       |       |
    //    |       |       |       |
    //    X ----- X ----- X ----- X
    //    |       |       |       |
    //    |       |       |       |
    //    |       |       |       |
    //    X ----- X ----- X ----- X
    //
    //
    // ie = (i) (e)xpanded:
    for(j = 0, je = 0; j < nb; j++, je += bsmoothing ? 3 : 1) {
        xej = xe[je];
        yej = ye[je];
        xj = x[j];
        yj = y[j];

        // je = (j) (e)xpanded:
        for(i = 0, ie = 0; i < na; i++, ie += asmoothing ? 3 : 1) {
            xej[ie] = xj[i];
            yej[ie] = yj[i];
        }
    }

    if(asmoothing) {
        // If there's a-smoothing, this loop fills in the X'd points with catmull-rom
        // control points computed along the a-axis:
        //     .       .       .       .
        //     .       .       .       .
        //     |       |       |       |
        //     |       |       |       |
        //     o -Y-X- o -X-X- o -X-Y- o
        //     |       |       |       |
        //     |       |       |       |
        //     |       |       |       |
        //     o -Y-X- o -X-X- o -X-Y- o
        //
        // i:  0       1       2       3
        // ie: 0  1 3  3  4 5  6  7 8  9
        //
        //           ------>
        //             a
        //
        for(j = 0, je = 0; j < nb; j++, je += bsmoothing ? 3 : 1) {
            // Fill in the points marked X for this a-row:
            for(i = 1, ie = 3; i < na - 1; i++, ie += 3) {
                cp = makeControlPoints(
                    [x[j][i - 1], y[j][i - 1]],
                    [x[j][i ], y[j][i]],
                    [x[j][i + 1], y[j][i + 1]],
                    asmoothing
                );

                xe[je][ie - 1] = cp[0][0];
                ye[je][ie - 1] = cp[0][1];
                xe[je][ie + 1] = cp[1][0];
                ye[je][ie + 1] = cp[1][1];
            }

            // The very first cubic interpolation point (to the left for i = 1 above) is
            // used as a *quadratic* interpolation point by the spline drawing function
            // which isn't really correct. But for the sake of consistency, we'll use it
            // as such. Since we're using cubic splines, that means we need to shorten the
            // tangent by 1/3 and also construct a new cubic spline control point 1/3 from
            // the original to the i = 0 point.
            p1 = inferCubicControlPoint(
                [xe[je][0], ye[je][0]],
                [xe[je][2], ye[je][2]],
                [xe[je][3], ye[je][3]]
            );
            xe[je][1] = p1[0];
            ye[je][1] = p1[1];

            // Ditto last points, sans explanation:
            p1 = inferCubicControlPoint(
                [xe[je][nea - 1], ye[je][nea - 1]],
                [xe[je][nea - 3], ye[je][nea - 3]],
                [xe[je][nea - 4], ye[je][nea - 4]]
            );
            xe[je][nea - 2] = p1[0];
            ye[je][nea - 2] = p1[1];
        }
    }

    if(bsmoothing) {
        // If there's a-smoothing, this loop fills in the X'd points with catmull-rom
        // control points computed along the b-axis:
        //     .       .       .       .
        //     X  X X  X  X X  X  X X  X
        //     |       |       |       |
        //     X  X X  X  X X  X  X X  X
        //     o -o-o- o -o-o- o -o-o- o
        //     X  X X  X  X X  X  X X  X
        //     |       |       |       |
        //     Y  Y Y  Y  Y Y  Y  Y Y  Y
        //     o -o-o- o -o-o- o -o-o- o
        //
        // i:  0       1       2       3
        // ie: 0  1 3  3  4 5  6  7 8  9
        //
        //           ------>
        //             a
        //
        for(ie = 0; ie < nea; ie++) {
            for(je = 3; je < neb - 3; je += 3) {
                cp = makeControlPoints(
                    [xe[je - 3][ie], ye[je - 3][ie]],
                    [xe[je][ie], ye[je][ie]],
                    [xe[je + 3][ie], ye[je + 3][ie]],
                    bsmoothing
                );

                xe[je - 1][ie] = cp[0][0];
                ye[je - 1][ie] = cp[0][1];
                xe[je + 1][ie] = cp[1][0];
                ye[je + 1][ie] = cp[1][1];
            }
            // Do the same boundary condition magic for these control points marked Y above:
            p1 = inferCubicControlPoint(
                [xe[0][ie], ye[0][ie]],
                [xe[2][ie], ye[2][ie]],
                [xe[3][ie], ye[3][ie]]
            );
            xe[1][ie] = p1[0];
            ye[1][ie] = p1[1];

            p1 = inferCubicControlPoint(
                [xe[neb - 1][ie], ye[neb - 1][ie]],
                [xe[neb - 3][ie], ye[neb - 3][ie]],
                [xe[neb - 4][ie], ye[neb - 4][ie]]
            );
            xe[neb - 2][ie] = p1[0];
            ye[neb - 2][ie] = p1[1];
        }
    }

    if(asmoothing && bsmoothing) {
        // Do one more pass, this time recomputing exactly what we just computed.
        // It's overdetermined since we're peforming catmull-rom in two directions,
        // so we'll just average the overdetermined. These points don't lie along the
        // grid lines, so note that only grid lines will follow normal plotly spline
        // interpolation.
        //
        // Unless of course there was no b smoothing. Then these intermediate points
        // don't actually exist and this section is bypassed.
        //     .       .       .       .
        //     o  X X  o  X X  o  X X  o
        //     |       |       |       |
        //     o  X X  o  X X  o  X X  o
        //     o -o-o- o -o-o- o -o-o- o
        //     o  X X  o  X X  o  X X  o
        //     |       |       |       |
        //     o  Y Y  o  Y Y  o  Y Y  o
        //     o -o-o- o -o-o- o -o-o- o
        //
        // i:  0       1       2       3
        // ie: 0  1 3  3  4 5  6  7 8  9
        //
        //           ------>
        //             a
        //
        for(je = 1; je < neb; je += (je + 1) % 3 === 0 ? 2 : 1) {
            // Fill in the points marked X for this a-row:
            for(ie = 3; ie < nea - 3; ie += 3) {
                cp = makeControlPoints(
                    [xe[je][ie - 3], ye[je][ie - 3]],
                    [xe[je][ie], ye[je][ie]],
                    [xe[je][ie + 3], ye[je][ie + 3]],
                    asmoothing
                );

                xe[je][ie - 1] = 0.5 * (xe[je][ie - 1] + cp[0][0]);
                ye[je][ie - 1] = 0.5 * (ye[je][ie - 1] + cp[0][1]);
                xe[je][ie + 1] = 0.5 * (xe[je][ie + 1] + cp[1][0]);
                ye[je][ie + 1] = 0.5 * (ye[je][ie + 1] + cp[1][1]);
            }

            // This case is just slightly different. The computation is the same,
            // but having computed this, we'll average with the existing result.
            p1 = inferCubicControlPoint(
                [xe[je][0], ye[je][0]],
                [xe[je][2], ye[je][2]],
                [xe[je][3], ye[je][3]]
            );
            xe[je][1] = 0.5 * (xe[je][1] + p1[0]);
            ye[je][1] = 0.5 * (ye[je][1] + p1[1]);

            p1 = inferCubicControlPoint(
                [xe[je][nea - 1], ye[je][nea - 1]],
                [xe[je][nea - 3], ye[je][nea - 3]],
                [xe[je][nea - 4], ye[je][nea - 4]]
            );
            xe[je][nea - 2] = 0.5 * (xe[je][nea - 2] + p1[0]);
            ye[je][nea - 2] = 0.5 * (ye[je][nea - 2] + p1[1]);
        }
    }

    return [xe, ye];
};

},{"../../lib":694,"./catmull_rom":884}],887:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = {
    RELATIVE_CULL_TOLERANCE: 1e-6
};

},{}],888:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/*
 * Evaluates the derivative of a list of control point arrays. That is, it expects an array or arrays
 * that are expanded relative to the raw data to include the bicubic control points, if applicable. If
 * only linear interpolation is desired, then the data points correspond 1-1 along that axis to the
 * data itself. Since it's catmull-rom splines in either direction note in particular that the
 * derivatives are discontinuous across cell boundaries. That's the reason you need both the *cell*
 * and the *point within the cell*.
 *
 * Also note that the discontinuity of the derivative is in magnitude only. The direction *is*
 * continuous across cell boundaries.
 *
 * For example, to compute the derivative of the xcoordinate halfway betwen the 7 and 8th i-gridpoints
 * and the 10th and 11th j-gridpoints given bicubic smoothing in both dimensions, you'd write:
 *
 *     var deriv = createIDerivativeEvaluator([x], 1, 1);
 *
 *     var dxdi = deriv([], 7, 10, 0.5, 0.5);
 *     // => [0.12345]
 *
 * Since there'd be a bunch of duplicate computation to compute multiple derivatives, you can double
 * this up by providing more arrays:
 *
 *     var deriv = createIDerivativeEvaluator([x, y], 1, 1);
 *
 *     var dxdi = deriv([], 7, 10, 0.5, 0.5);
 *     // => [0.12345, 0.78910]
 *
 * NB: It's presumed that at this point all data has been sanitized and is valid numerical data arrays
 * of the correct dimension.
 */
module.exports = function(arrays, asmoothing, bsmoothing) {
    if(asmoothing && bsmoothing) {
        return function(out, i0, j0, u, v) {
            if(!out) out = [];
            var f0, f1, f2, f3, ak, k;

            // Since it's a grid of control points, the actual indices are * 3:
            i0 *= 3;
            j0 *= 3;

            // Precompute some numbers:
            var u2 = u * u;
            var ou = 1 - u;
            var ou2 = ou * ou;
            var ouu2 = ou * u * 2;
            var a = -3 * ou2;
            var b = 3 * (ou2 - ouu2);
            var c = 3 * (ouu2 - u2);
            var d = 3 * u2;

            var v2 = v * v;
            var v3 = v2 * v;
            var ov = 1 - v;
            var ov2 = ov * ov;
            var ov3 = ov2 * ov;

            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];
                // Compute the derivatives in the u-direction:
                f0 = a * ak[j0 ][i0] + b * ak[j0 ][i0 + 1] + c * ak[j0 ][i0 + 2] + d * ak[j0 ][i0 + 3];
                f1 = a * ak[j0 + 1][i0] + b * ak[j0 + 1][i0 + 1] + c * ak[j0 + 1][i0 + 2] + d * ak[j0 + 1][i0 + 3];
                f2 = a * ak[j0 + 2][i0] + b * ak[j0 + 2][i0 + 1] + c * ak[j0 + 2][i0 + 2] + d * ak[j0 + 2][i0 + 3];
                f3 = a * ak[j0 + 3][i0] + b * ak[j0 + 3][i0 + 1] + c * ak[j0 + 3][i0 + 2] + d * ak[j0 + 3][i0 + 3];

                // Now just interpolate in the v-direction since it's all separable:
                out[k] = ov3 * f0 + 3 * (ov2 * v * f1 + ov * v2 * f2) + v3 * f3;
            }

            return out;
        };
    } else if(asmoothing) {
        // Handle smooth in the a-direction but linear in the b-direction by performing four
        // linear interpolations followed by one cubic interpolation of the result
        return function(out, i0, j0, u, v) {
            if(!out) out = [];
            var f0, f1, k, ak;
            i0 *= 3;
            var u2 = u * u;
            var ou = 1 - u;
            var ou2 = ou * ou;
            var ouu2 = ou * u * 2;
            var a = -3 * ou2;
            var b = 3 * (ou2 - ouu2);
            var c = 3 * (ouu2 - u2);
            var d = 3 * u2;
            var ov = 1 - v;
            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];
                f0 = a * ak[j0 ][i0] + b * ak[j0 ][i0 + 1] + c * ak[j0 ][i0 + 2] + d * ak[j0 ][i0 + 3];
                f1 = a * ak[j0 + 1][i0] + b * ak[j0 + 1][i0 + 1] + c * ak[j0 + 1][i0 + 2] + d * ak[j0 + 1][i0 + 3];

                out[k] = ov * f0 + v * f1;
            }
            return out;
        };
    } else if(bsmoothing) {
        // Same as the above case, except reversed. I've disabled the no-unused vars rule
        // so that this function is fully interpolation-agnostic. Otherwise it would need
        // to be called differently in different cases. Which wouldn't be the worst, but
        /* eslint-disable no-unused-vars */
        return function(out, i0, j0, u, v) {
        /* eslint-enable no-unused-vars */
            if(!out) out = [];
            var f0, f1, f2, f3, k, ak;
            j0 *= 3;
            var v2 = v * v;
            var v3 = v2 * v;
            var ov = 1 - v;
            var ov2 = ov * ov;
            var ov3 = ov2 * ov;
            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];
                f0 = ak[j0][i0 + 1] - ak[j0][i0];
                f1 = ak[j0 + 1][i0 + 1] - ak[j0 + 1][i0];
                f2 = ak[j0 + 2][i0 + 1] - ak[j0 + 2][i0];
                f3 = ak[j0 + 3][i0 + 1] - ak[j0 + 3][i0];

                out[k] = ov3 * f0 + 3 * (ov2 * v * f1 + ov * v2 * f2) + v3 * f3;
            }
            return out;
        };
    } else {
        // Finally, both directions are linear:
        /* eslint-disable no-unused-vars */
        return function(out, i0, j0, u, v) {
        /* eslint-enable no-unused-vars */
            if(!out) out = [];
            var f0, f1, k, ak;
            var ov = 1 - v;
            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];
                f0 = ak[j0][i0 + 1] - ak[j0][i0];
                f1 = ak[j0 + 1][i0 + 1] - ak[j0 + 1][i0];

                out[k] = ov * f0 + v * f1;
            }
            return out;
        };
    }
};

},{}],889:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function(arrays, asmoothing, bsmoothing) {
    if(asmoothing && bsmoothing) {
        return function(out, i0, j0, u, v) {
            if(!out) out = [];
            var f0, f1, f2, f3, ak, k;

            // Since it's a grid of control points, the actual indices are * 3:
            i0 *= 3;
            j0 *= 3;

            // Precompute some numbers:
            var u2 = u * u;
            var u3 = u2 * u;
            var ou = 1 - u;
            var ou2 = ou * ou;
            var ou3 = ou2 * ou;

            var v2 = v * v;
            var ov = 1 - v;
            var ov2 = ov * ov;
            var ovv2 = ov * v * 2;
            var a = -3 * ov2;
            var b = 3 * (ov2 - ovv2);
            var c = 3 * (ovv2 - v2);
            var d = 3 * v2;

            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];

                // Compute the derivatives in the v-direction:
                f0 = a * ak[j0][i0] + b * ak[j0 + 1][i0] + c * ak[j0 + 2][i0] + d * ak[j0 + 3][i0];
                f1 = a * ak[j0][i0 + 1] + b * ak[j0 + 1][i0 + 1] + c * ak[j0 + 2][i0 + 1] + d * ak[j0 + 3][i0 + 1];
                f2 = a * ak[j0][i0 + 2] + b * ak[j0 + 1][i0 + 2] + c * ak[j0 + 2][i0 + 2] + d * ak[j0 + 3][i0 + 2];
                f3 = a * ak[j0][i0 + 3] + b * ak[j0 + 1][i0 + 3] + c * ak[j0 + 2][i0 + 3] + d * ak[j0 + 3][i0 + 3];

                // Now just interpolate in the v-direction since it's all separable:
                out[k] = ou3 * f0 + 3 * (ou2 * u * f1 + ou * u2 * f2) + u3 * f3;
            }

            return out;
        };
    } else if(asmoothing) {
        // Handle smooth in the a-direction but linear in the b-direction by performing four
        // linear interpolations followed by one cubic interpolation of the result
        return function(out, i0, j0, v, u) {
            if(!out) out = [];
            var f0, f1, f2, f3, k, ak;
            i0 *= 3;
            var u2 = u * u;
            var u3 = u2 * u;
            var ou = 1 - u;
            var ou2 = ou * ou;
            var ou3 = ou2 * ou;
            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];

                f0 = ak[j0 + 1][i0] - ak[j0][i0];
                f1 = ak[j0 + 1][i0 + 1] - ak[j0][i0 + 1];
                f2 = ak[j0 + 1][i0 + 2] - ak[j0][i0 + 2];
                f3 = ak[j0 + 1][i0 + 3] - ak[j0][i0 + 3];

                out[k] = ou3 * f0 + 3 * (ou2 * u * f1 + ou * u2 * f2) + u3 * f3;

                // mathematically equivalent:
                // f0 = ou3 * ak[j0    ][i0] + 3 * (ou2 * u * ak[j0    ][i0 + 1] + ou * u2 * ak[j0    ][i0 + 2]) + u3 * ak[j0    ][i0 + 3];
                // f1 = ou3 * ak[j0 + 1][i0] + 3 * (ou2 * u * ak[j0 + 1][i0 + 1] + ou * u2 * ak[j0 + 1][i0 + 2]) + u3 * ak[j0 + 1][i0 + 3];
                // out[k] = f1 - f0;
            }
            return out;
        };
    } else if(bsmoothing) {
        // Same as the above case, except reversed:
        /* eslint-disable no-unused-vars */
        return function(out, i0, j0, u, v) {
        /* eslint-enable no-unused-vars */
            if(!out) out = [];
            var f0, f1, k, ak;
            j0 *= 3;
            var ou = 1 - u;
            var v2 = v * v;
            var ov = 1 - v;
            var ov2 = ov * ov;
            var ovv2 = ov * v * 2;
            var a = -3 * ov2;
            var b = 3 * (ov2 - ovv2);
            var c = 3 * (ovv2 - v2);
            var d = 3 * v2;
            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];
                f0 = a * ak[j0][i0] + b * ak[j0 + 1][i0] + c * ak[j0 + 2][i0] + d * ak[j0 + 3][i0];
                f1 = a * ak[j0][i0 + 1] + b * ak[j0 + 1][i0 + 1] + c * ak[j0 + 2][i0 + 1] + d * ak[j0 + 3][i0 + 1];

                out[k] = ou * f0 + u * f1;
            }
            return out;
        };
    } else {
        // Finally, both directions are linear:
        /* eslint-disable no-unused-vars */
        return function(out, i0, j0, v, u) {
        /* eslint-enable no-unused-vars */
            if(!out) out = [];
            var f0, f1, k, ak;
            var ov = 1 - v;
            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];
                f0 = ak[j0 + 1][i0] - ak[j0][i0];
                f1 = ak[j0 + 1][i0 + 1] - ak[j0][i0 + 1];

                out[k] = ov * f0 + v * f1;
            }
            return out;
        };
    }

};

},{}],890:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/*
 * Return a function that evaluates a set of linear or bicubic control points.
 * This will get evaluated a lot, so we'll at least do a bit of extra work to
 * flatten some of the choices. In particular, we'll unroll the linear/bicubic
 * combinations and we'll allow computing results in parallel to cut down
 * on repeated arithmetic.
 *
 * Take note that we don't search for the correct range in this function. The
 * reason is for consistency due to the corrresponding derivative function. In
 * particular, the derivatives aren't continuous across cells, so it's important
 * to be able control whether the derivative at a cell boundary is approached
 * from one side or the other.
 */
module.exports = function(arrays, na, nb, asmoothing, bsmoothing) {
    var imax = na - 2;
    var jmax = nb - 2;

    if(asmoothing && bsmoothing) {
        return function(out, i, j) {
            if(!out) out = [];
            var f0, f1, f2, f3, ak, k;

            var i0 = Math.max(0, Math.min(Math.floor(i), imax));
            var j0 = Math.max(0, Math.min(Math.floor(j), jmax));
            var u = Math.max(0, Math.min(1, i - i0));
            var v = Math.max(0, Math.min(1, j - j0));

            // Since it's a grid of control points, the actual indices are * 3:
            i0 *= 3;
            j0 *= 3;

            // Precompute some numbers:
            var u2 = u * u;
            var u3 = u2 * u;
            var ou = 1 - u;
            var ou2 = ou * ou;
            var ou3 = ou2 * ou;

            var v2 = v * v;
            var v3 = v2 * v;
            var ov = 1 - v;
            var ov2 = ov * ov;
            var ov3 = ov2 * ov;

            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];
                f0 = ou3 * ak[j0][i0] + 3 * (ou2 * u * ak[j0][i0 + 1] + ou * u2 * ak[j0][i0 + 2]) + u3 * ak[j0][i0 + 3];
                f1 = ou3 * ak[j0 + 1][i0] + 3 * (ou2 * u * ak[j0 + 1][i0 + 1] + ou * u2 * ak[j0 + 1][i0 + 2]) + u3 * ak[j0 + 1][i0 + 3];
                f2 = ou3 * ak[j0 + 2][i0] + 3 * (ou2 * u * ak[j0 + 2][i0 + 1] + ou * u2 * ak[j0 + 2][i0 + 2]) + u3 * ak[j0 + 2][i0 + 3];
                f3 = ou3 * ak[j0 + 3][i0] + 3 * (ou2 * u * ak[j0 + 3][i0 + 1] + ou * u2 * ak[j0 + 3][i0 + 2]) + u3 * ak[j0 + 3][i0 + 3];
                out[k] = ov3 * f0 + 3 * (ov2 * v * f1 + ov * v2 * f2) + v3 * f3;
            }

            return out;
        };
    } else if(asmoothing) {
        // Handle smooth in the a-direction but linear in the b-direction by performing four
        // linear interpolations followed by one cubic interpolation of the result
        return function(out, i, j) {
            if(!out) out = [];

            var i0 = Math.max(0, Math.min(Math.floor(i), imax));
            var j0 = Math.max(0, Math.min(Math.floor(j), jmax));
            var u = Math.max(0, Math.min(1, i - i0));
            var v = Math.max(0, Math.min(1, j - j0));

            var f0, f1, f2, f3, k, ak;
            i0 *= 3;
            var u2 = u * u;
            var u3 = u2 * u;
            var ou = 1 - u;
            var ou2 = ou * ou;
            var ou3 = ou2 * ou;
            var ov = 1 - v;
            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];
                f0 = ov * ak[j0][i0] + v * ak[j0 + 1][i0];
                f1 = ov * ak[j0][i0 + 1] + v * ak[j0 + 1][i0 + 1];
                f2 = ov * ak[j0][i0 + 2] + v * ak[j0 + 1][i0 + 1];
                f3 = ov * ak[j0][i0 + 3] + v * ak[j0 + 1][i0 + 1];

                out[k] = ou3 * f0 + 3 * (ou2 * u * f1 + ou * u2 * f2) + u3 * f3;
            }
            return out;
        };
    } else if(bsmoothing) {
        // Same as the above case, except reversed:
        return function(out, i, j) {
            if(!out) out = [];

            var i0 = Math.max(0, Math.min(Math.floor(i), imax));
            var j0 = Math.max(0, Math.min(Math.floor(j), jmax));
            var u = Math.max(0, Math.min(1, i - i0));
            var v = Math.max(0, Math.min(1, j - j0));

            var f0, f1, f2, f3, k, ak;
            j0 *= 3;
            var v2 = v * v;
            var v3 = v2 * v;
            var ov = 1 - v;
            var ov2 = ov * ov;
            var ov3 = ov2 * ov;
            var ou = 1 - u;
            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];
                f0 = ou * ak[j0][i0] + u * ak[j0][i0 + 1];
                f1 = ou * ak[j0 + 1][i0] + u * ak[j0 + 1][i0 + 1];
                f2 = ou * ak[j0 + 2][i0] + u * ak[j0 + 2][i0 + 1];
                f3 = ou * ak[j0 + 3][i0] + u * ak[j0 + 3][i0 + 1];

                out[k] = ov3 * f0 + 3 * (ov2 * v * f1 + ov * v2 * f2) + v3 * f3;
            }
            return out;
        };
    } else {
        // Finally, both directions are linear:
        return function(out, i, j) {
            if(!out) out = [];

            var i0 = Math.max(0, Math.min(Math.floor(i), imax));
            var j0 = Math.max(0, Math.min(Math.floor(j), jmax));
            var u = Math.max(0, Math.min(1, i - i0));
            var v = Math.max(0, Math.min(1, j - j0));

            var f0, f1, k, ak;
            var ov = 1 - v;
            var ou = 1 - u;
            for(k = 0; k < arrays.length; k++) {
                ak = arrays[k];
                f0 = ou * ak[j0][i0] + u * ak[j0][i0 + 1];
                f1 = ou * ak[j0 + 1][i0] + u * ak[j0 + 1][i0 + 1];

                out[k] = ov * f0 + v * f1;
            }
            return out;
        };
    }

};

},{}],891:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var handleXYDefaults = _dereq_('./xy_defaults');
var handleABDefaults = _dereq_('./ab_defaults');
var attributes = _dereq_('./attributes');
var colorAttrs = _dereq_('../../components/color/attributes');

module.exports = function supplyDefaults(traceIn, traceOut, dfltColor, fullLayout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    traceOut._clipPathId = 'clip' + traceOut.uid + 'carpet';

    var defaultColor = coerce('color', colorAttrs.defaultLine);
    Lib.coerceFont(coerce, 'font');

    coerce('carpet');

    handleABDefaults(traceIn, traceOut, fullLayout, coerce, defaultColor);

    if(!traceOut.a || !traceOut.b) {
        traceOut.visible = false;
        return;
    }

    if(traceOut.a.length < 3) {
        traceOut.aaxis.smoothing = 0;
    }

    if(traceOut.b.length < 3) {
        traceOut.baxis.smoothing = 0;
    }

    // NB: the input is x/y arrays. You should know that the *first* dimension of x and y
    // corresponds to b and the second to a. This sounds backwards but ends up making sense
    // the important part to know is that when you write y[j][i], j goes from 0 to b.length - 1
    // and i goes from 0 to a.length - 1.
    var validData = handleXYDefaults(traceIn, traceOut, coerce);
    if(!validData) {
        traceOut.visible = false;
    }

    if(traceOut._cheater) {
        coerce('cheaterslope');
    }
};

},{"../../components/color/attributes":570,"../../lib":694,"./ab_defaults":874,"./attributes":876,"./xy_defaults":900}],892:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Carpet = {};

Carpet.attributes = _dereq_('./attributes');
Carpet.supplyDefaults = _dereq_('./defaults');
Carpet.plot = _dereq_('./plot');
Carpet.calc = _dereq_('./calc');
Carpet.animatable = true;
Carpet.isContainer = true; // so carpet traces get `calc` before other traces

Carpet.moduleType = 'trace';
Carpet.name = 'carpet';
Carpet.basePlotModule = _dereq_('../../plots/cartesian');
Carpet.categories = ['cartesian', 'svg', 'carpet', 'carpetAxis', 'notLegendIsolatable', 'noMultiCategory'];
Carpet.meta = {
    
};

module.exports = Carpet;

},{"../../plots/cartesian":754,"./attributes":876,"./calc":880,"./defaults":891,"./plot":897}],893:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/*
 * Given a trace, look up the carpet axis by carpet.
 */
module.exports = function(gd, trace) {
    var n = gd._fullData.length;
    var firstAxis;
    for(var i = 0; i < n; i++) {
        var maybeCarpet = gd._fullData[i];

        if(maybeCarpet.index === trace.index) continue;

        if(maybeCarpet.type === 'carpet') {
            if(!firstAxis) {
                firstAxis = maybeCarpet;
            }

            if(maybeCarpet.carpet === trace.carpet) {
                return maybeCarpet;
            }
        }
    }

    return firstAxis;
};

},{}],894:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function makePath(xp, yp, isBicubic) {
    // Prevent d3 errors that would result otherwise:
    if(xp.length === 0) return '';

    var i;
    var path = [];
    var stride = isBicubic ? 3 : 1;
    for(i = 0; i < xp.length; i += stride) {
        path.push(xp[i] + ',' + yp[i]);

        if(isBicubic && i < xp.length - stride) {
            path.push('C');
            path.push([
                xp[i + 1] + ',' + yp[i + 1],
                xp[i + 2] + ',' + yp[i + 2] + ' ',
            ].join(' '));
        }
    }
    return path.join(isBicubic ? '' : 'L');
};

},{}],895:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;

/*
 * Map an array of x or y coordinates (c) to screen-space pixel coordinates (p).
 * The output array is optional, but if provided, it will be reused without
 * reallocation to the extent possible.
 */
module.exports = function mapArray(out, data, func) {
    var i;

    if(!isArrayOrTypedArray(out)) {
        // If not an array, make it an array:
        out = [];
    } else if(out.length > data.length) {
        // If too long, truncate. (If too short, it will grow
        // automatically so we don't care about that case)
        out = out.slice(0, data.length);
    }

    for(i = 0; i < data.length; i++) {
        out[i] = func(data[i]);
    }

    return out;
};

},{"../../lib":694}],896:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = function orientText(trace, xaxis, yaxis, xy, dxy, refDxy) {
    var dx = dxy[0] * trace.dpdx(xaxis);
    var dy = dxy[1] * trace.dpdy(yaxis);
    var flip = 1;

    var offsetMultiplier = 1.0;
    if(refDxy) {
        var l1 = Math.sqrt(dxy[0] * dxy[0] + dxy[1] * dxy[1]);
        var l2 = Math.sqrt(refDxy[0] * refDxy[0] + refDxy[1] * refDxy[1]);
        var dot = (dxy[0] * refDxy[0] + dxy[1] * refDxy[1]) / l1 / l2;
        offsetMultiplier = Math.max(0.0, dot);
    }

    var angle = Math.atan2(dy, dx) * 180 / Math.PI;
    if(angle < -90) {
        angle += 180;
        flip = -flip;
    } else if(angle > 90) {
        angle -= 180;
        flip = -flip;
    }

    return {
        angle: angle,
        flip: flip,
        p: trace.c2p(xy, xaxis, yaxis),
        offsetMultplier: offsetMultiplier
    };
};

},{}],897:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var Drawing = _dereq_('../../components/drawing');
var map1dArray = _dereq_('./map_1d_array');
var makepath = _dereq_('./makepath');
var orientText = _dereq_('./orient_text');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var Lib = _dereq_('../../lib');
var alignmentConstants = _dereq_('../../constants/alignment');

module.exports = function plot(gd, plotinfo, cdcarpet, carpetLayer) {
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;
    var fullLayout = gd._fullLayout;
    var clipLayer = fullLayout._clips;

    Lib.makeTraceGroups(carpetLayer, cdcarpet, 'trace').each(function(cd) {
        var axisLayer = d3.select(this);
        var cd0 = cd[0];
        var trace = cd0.trace;
        var aax = trace.aaxis;
        var bax = trace.baxis;

        var minorLayer = Lib.ensureSingle(axisLayer, 'g', 'minorlayer');
        var majorLayer = Lib.ensureSingle(axisLayer, 'g', 'majorlayer');
        var boundaryLayer = Lib.ensureSingle(axisLayer, 'g', 'boundarylayer');
        var labelLayer = Lib.ensureSingle(axisLayer, 'g', 'labellayer');

        axisLayer.style('opacity', trace.opacity);

        drawGridLines(xa, ya, majorLayer, aax, 'a', aax._gridlines, true);
        drawGridLines(xa, ya, majorLayer, bax, 'b', bax._gridlines, true);
        drawGridLines(xa, ya, minorLayer, aax, 'a', aax._minorgridlines, true);
        drawGridLines(xa, ya, minorLayer, bax, 'b', bax._minorgridlines, true);

        // NB: These are not ommitted if the lines are not active. The joins must be executed
        // in order for them to get cleaned up without a full redraw
        drawGridLines(xa, ya, boundaryLayer, aax, 'a-boundary', aax._boundarylines);
        drawGridLines(xa, ya, boundaryLayer, bax, 'b-boundary', bax._boundarylines);

        var labelOrientationA = drawAxisLabels(gd, xa, ya, trace, cd0, labelLayer, aax._labels, 'a-label');
        var labelOrientationB = drawAxisLabels(gd, xa, ya, trace, cd0, labelLayer, bax._labels, 'b-label');

        drawAxisTitles(gd, labelLayer, trace, cd0, xa, ya, labelOrientationA, labelOrientationB);

        drawClipPath(trace, cd0, clipLayer, xa, ya);
    });
};

function drawClipPath(trace, t, layer, xaxis, yaxis) {
    var seg, xp, yp, i;

    var clip = layer.select('#' + trace._clipPathId);

    if(!clip.size()) {
        clip = layer.append('clipPath')
            .classed('carpetclip', true);
    }

    var path = Lib.ensureSingle(clip, 'path', 'carpetboundary');
    var segments = t.clipsegments;
    var segs = [];

    for(i = 0; i < segments.length; i++) {
        seg = segments[i];
        xp = map1dArray([], seg.x, xaxis.c2p);
        yp = map1dArray([], seg.y, yaxis.c2p);
        segs.push(makepath(xp, yp, seg.bicubic));
    }

    // This could be optimized ever so slightly to avoid no-op L segments
    // at the corners, but it's so negligible that I don't think it's worth
    // the extra complexity
    var clipPathData = 'M' + segs.join('L') + 'Z';
    clip.attr('id', trace._clipPathId);
    path.attr('d', clipPathData);
}

function drawGridLines(xaxis, yaxis, layer, axis, axisLetter, gridlines) {
    var lineClass = 'const-' + axisLetter + '-lines';
    var gridJoin = layer.selectAll('.' + lineClass).data(gridlines);

    gridJoin.enter().append('path')
        .classed(lineClass, true)
        .style('vector-effect', 'non-scaling-stroke');

    gridJoin.each(function(d) {
        var gridline = d;
        var x = gridline.x;
        var y = gridline.y;

        var xp = map1dArray([], x, xaxis.c2p);
        var yp = map1dArray([], y, yaxis.c2p);

        var path = 'M' + makepath(xp, yp, gridline.smoothing);

        var el = d3.select(this);

        el.attr('d', path)
            .style('stroke-width', gridline.width)
            .style('stroke', gridline.color)
            .style('fill', 'none');
    });

    gridJoin.exit().remove();
}

function drawAxisLabels(gd, xaxis, yaxis, trace, t, layer, labels, labelClass) {
    var labelJoin = layer.selectAll('text.' + labelClass).data(labels);

    labelJoin.enter().append('text')
        .classed(labelClass, true);

    var maxExtent = 0;
    var labelOrientation = {};

    labelJoin.each(function(label, i) {
        // Most of the positioning is done in calc_labels. Only the parts that depend upon
        // the screen space representation of the x and y axes are here:
        var orientation;
        if(label.axis.tickangle === 'auto') {
            orientation = orientText(trace, xaxis, yaxis, label.xy, label.dxy);
        } else {
            var angle = (label.axis.tickangle + 180.0) * Math.PI / 180.0;
            orientation = orientText(trace, xaxis, yaxis, label.xy, [Math.cos(angle), Math.sin(angle)]);
        }

        if(!i) {
            // TODO: offsetMultiplier? Not currently used anywhere...
            labelOrientation = {angle: orientation.angle, flip: orientation.flip};
        }
        var direction = (label.endAnchor ? -1 : 1) * orientation.flip;

        var labelEl = d3.select(this)
            .attr({
                'text-anchor': direction > 0 ? 'start' : 'end',
                'data-notex': 1
            })
            .call(Drawing.font, label.font)
            .text(label.text)
            .call(svgTextUtils.convertToTspans, gd);

        var bbox = Drawing.bBox(this);

        labelEl.attr('transform',
                // Translate to the correct point:
                'translate(' + orientation.p[0] + ',' + orientation.p[1] + ') ' +
                // Rotate to line up with grid line tangent:
                'rotate(' + orientation.angle + ')' +
                // Adjust the baseline and indentation:
                'translate(' + label.axis.labelpadding * direction + ',' + bbox.height * 0.3 + ')'
            );

        maxExtent = Math.max(maxExtent, bbox.width + label.axis.labelpadding);
    });

    labelJoin.exit().remove();

    labelOrientation.maxExtent = maxExtent;
    return labelOrientation;
}

function drawAxisTitles(gd, layer, trace, t, xa, ya, labelOrientationA, labelOrientationB) {
    var a, b, xy, dxy;

    a = 0.5 * (trace.a[0] + trace.a[trace.a.length - 1]);
    b = trace.b[0];
    xy = trace.ab2xy(a, b, true);
    dxy = trace.dxyda_rough(a, b);
    if(labelOrientationA.angle === undefined) {
        Lib.extendFlat(labelOrientationA, orientText(trace, xa, ya, xy, trace.dxydb_rough(a, b)));
    }
    drawAxisTitle(gd, layer, trace, t, xy, dxy, trace.aaxis, xa, ya, labelOrientationA, 'a-title');

    a = trace.a[0];
    b = 0.5 * (trace.b[0] + trace.b[trace.b.length - 1]);
    xy = trace.ab2xy(a, b, true);
    dxy = trace.dxydb_rough(a, b);
    if(labelOrientationB.angle === undefined) {
        Lib.extendFlat(labelOrientationB, orientText(trace, xa, ya, xy, trace.dxyda_rough(a, b)));
    }
    drawAxisTitle(gd, layer, trace, t, xy, dxy, trace.baxis, xa, ya, labelOrientationB, 'b-title');
}

var lineSpacing = alignmentConstants.LINE_SPACING;
var midShift = ((1 - alignmentConstants.MID_SHIFT) / lineSpacing) + 1;

function drawAxisTitle(gd, layer, trace, t, xy, dxy, axis, xa, ya, labelOrientation, labelClass) {
    var data = [];
    if(axis.title.text) data.push(axis.title.text);
    var titleJoin = layer.selectAll('text.' + labelClass).data(data);
    var offset = labelOrientation.maxExtent;

    titleJoin.enter().append('text')
        .classed(labelClass, true);

    // There's only one, but we'll do it as a join so it's updated nicely:
    titleJoin.each(function() {
        var orientation = orientText(trace, xa, ya, xy, dxy);

        if(['start', 'both'].indexOf(axis.showticklabels) === -1) {
            offset = 0;
        }

        // In addition to the size of the labels, add on some extra padding:
        var titleSize = axis.title.font.size;
        offset += titleSize + axis.title.offset;

        var labelNorm = labelOrientation.angle + (labelOrientation.flip < 0 ? 180 : 0);
        var angleDiff = (labelNorm - orientation.angle + 450) % 360;
        var reverseTitle = angleDiff > 90 && angleDiff < 270;

        var el = d3.select(this);

        el.text(axis.title.text)
            .call(svgTextUtils.convertToTspans, gd);

        if(reverseTitle) {
            offset = (-svgTextUtils.lineCount(el) + midShift) * lineSpacing * titleSize - offset;
        }

        el.attr('transform',
                'translate(' + orientation.p[0] + ',' + orientation.p[1] + ') ' +
                'rotate(' + orientation.angle + ') ' +
                'translate(0,' + offset + ')'
            )
            .classed('user-select-none', true)
            .attr('text-anchor', 'middle')
            .call(Drawing.font, axis.title.font);
    });

    titleJoin.exit().remove();
}

},{"../../components/drawing":592,"../../constants/alignment":666,"../../lib":694,"../../lib/svg_text_utils":718,"./makepath":894,"./map_1d_array":895,"./orient_text":896,"d3":149}],898:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var constants = _dereq_('./constants');
var search = _dereq_('../../lib/search').findBin;
var computeControlPoints = _dereq_('./compute_control_points');
var createSplineEvaluator = _dereq_('./create_spline_evaluator');
var createIDerivativeEvaluator = _dereq_('./create_i_derivative_evaluator');
var createJDerivativeEvaluator = _dereq_('./create_j_derivative_evaluator');

/*
 * Create conversion functions to go from one basis to another. In particular the letter
 * abbreviations are:
 *
 *   i: i/j coordinates along the grid. Integer values correspond to data points
 *   a: real-valued coordinates along the a/b axes
 *   c: cartesian x-y coordinates
 *   p: screen-space pixel coordinates
 */
module.exports = function setConvert(trace) {
    var a = trace._a;
    var b = trace._b;
    var na = a.length;
    var nb = b.length;
    var aax = trace.aaxis;
    var bax = trace.baxis;

    // Grab the limits once rather than recomputing the bounds for every point
    // independently:
    var amin = a[0];
    var amax = a[na - 1];
    var bmin = b[0];
    var bmax = b[nb - 1];
    var arange = a[a.length - 1] - a[0];
    var brange = b[b.length - 1] - b[0];

    // Compute the tolerance so that points are visible slightly outside the
    // defined carpet axis:
    var atol = arange * constants.RELATIVE_CULL_TOLERANCE;
    var btol = brange * constants.RELATIVE_CULL_TOLERANCE;

    // Expand the limits to include the relative tolerance:
    amin -= atol;
    amax += atol;
    bmin -= btol;
    bmax += btol;

    trace.isVisible = function(a, b) {
        return a > amin && a < amax && b > bmin && b < bmax;
    };

    trace.isOccluded = function(a, b) {
        return a < amin || a > amax || b < bmin || b > bmax;
    };

    trace.setScale = function() {
        var x = trace._x;
        var y = trace._y;

        // This is potentially a very expensive step! It does the bulk of the work of constructing
        // an expanded basis of control points. Note in particular that it overwrites the existing
        // basis without creating a new array since that would potentially thrash the garbage
        // collector.
        var result = computeControlPoints(trace._xctrl, trace._yctrl, x, y, aax.smoothing, bax.smoothing);
        trace._xctrl = result[0];
        trace._yctrl = result[1];

        // This step is the second step in the process, but it's somewhat simpler. It just unrolls
        // some logic since it would be unnecessarily expensive to compute both interpolations
        // nearly identically but separately and to include a bunch of linear vs. bicubic logic in
        // every single call.
        trace.evalxy = createSplineEvaluator([trace._xctrl, trace._yctrl], na, nb, aax.smoothing, bax.smoothing);

        trace.dxydi = createIDerivativeEvaluator([trace._xctrl, trace._yctrl], aax.smoothing, bax.smoothing);
        trace.dxydj = createJDerivativeEvaluator([trace._xctrl, trace._yctrl], aax.smoothing, bax.smoothing);
    };

    /*
     * Convert from i/j data grid coordinates to a/b values. Note in particular that this
     * is *linear* interpolation, even if the data is interpolated bicubically.
     */
    trace.i2a = function(i) {
        var i0 = Math.max(0, Math.floor(i[0]), na - 2);
        var ti = i[0] - i0;
        return (1 - ti) * a[i0] + ti * a[i0 + 1];
    };

    trace.j2b = function(j) {
        var j0 = Math.max(0, Math.floor(j[1]), na - 2);
        var tj = j[1] - j0;
        return (1 - tj) * b[j0] + tj * b[j0 + 1];
    };

    trace.ij2ab = function(ij) {
        return [trace.i2a(ij[0]), trace.j2b(ij[1])];
    };

    /*
     * Convert from a/b coordinates to i/j grid-numbered coordinates. This requires searching
     * through the a/b data arrays and assumes they are monotonic, which is presumed to have
     * been enforced already.
     */
    trace.a2i = function(aval) {
        var i0 = Math.max(0, Math.min(search(aval, a), na - 2));
        var a0 = a[i0];
        var a1 = a[i0 + 1];
        return Math.max(0, Math.min(na - 1, i0 + (aval - a0) / (a1 - a0)));
    };

    trace.b2j = function(bval) {
        var j0 = Math.max(0, Math.min(search(bval, b), nb - 2));
        var b0 = b[j0];
        var b1 = b[j0 + 1];
        return Math.max(0, Math.min(nb - 1, j0 + (bval - b0) / (b1 - b0)));
    };

    trace.ab2ij = function(ab) {
        return [trace.a2i(ab[0]), trace.b2j(ab[1])];
    };

    /*
     * Convert from i/j coordinates to x/y caretesian coordinates. This means either bilinear
     * or bicubic spline evaluation, but the hard part is already done at this point.
     */
    trace.i2c = function(i, j) {
        return trace.evalxy([], i, j);
    };

    trace.ab2xy = function(aval, bval, extrapolate) {
        if(!extrapolate && (aval < a[0] || aval > a[na - 1] | bval < b[0] || bval > b[nb - 1])) {
            return [false, false];
        }
        var i = trace.a2i(aval);
        var j = trace.b2j(bval);

        var pt = trace.evalxy([], i, j);

        if(extrapolate) {
            // This section uses the boundary derivatives to extrapolate linearly outside
            // the defined range. Consider a scatter line with one point inside the carpet
            // axis and one point outside. If we don't extrapolate, we can't draw the line
            // at all.
            var iex = 0;
            var jex = 0;
            var der = [];

            var i0, ti, j0, tj;
            if(aval < a[0]) {
                i0 = 0;
                ti = 0;
                iex = (aval - a[0]) / (a[1] - a[0]);
            } else if(aval > a[na - 1]) {
                i0 = na - 2;
                ti = 1;
                iex = (aval - a[na - 1]) / (a[na - 1] - a[na - 2]);
            } else {
                i0 = Math.max(0, Math.min(na - 2, Math.floor(i)));
                ti = i - i0;
            }

            if(bval < b[0]) {
                j0 = 0;
                tj = 0;
                jex = (bval - b[0]) / (b[1] - b[0]);
            } else if(bval > b[nb - 1]) {
                j0 = nb - 2;
                tj = 1;
                jex = (bval - b[nb - 1]) / (b[nb - 1] - b[nb - 2]);
            } else {
                j0 = Math.max(0, Math.min(nb - 2, Math.floor(j)));
                tj = j - j0;
            }

            if(iex) {
                trace.dxydi(der, i0, j0, ti, tj);
                pt[0] += der[0] * iex;
                pt[1] += der[1] * iex;
            }

            if(jex) {
                trace.dxydj(der, i0, j0, ti, tj);
                pt[0] += der[0] * jex;
                pt[1] += der[1] * jex;
            }
        }

        return pt;
    };


    trace.c2p = function(xy, xa, ya) {
        return [xa.c2p(xy[0]), ya.c2p(xy[1])];
    };

    trace.p2x = function(p, xa, ya) {
        return [xa.p2c(p[0]), ya.p2c(p[1])];
    };

    trace.dadi = function(i /* , u*/) {
        // Right now only a piecewise linear a or b basis is permitted since smoother interpolation
        // would cause monotonicity problems. As a retult, u is entirely disregarded in this
        // computation, though we'll specify it as a parameter for the sake of completeness and
        // future-proofing. It would be possible to use monotonic cubic interpolation, for example.
        //
        // See: https://en.wikipedia.org/wiki/Monotone_cubic_interpolation

        // u = u || 0;

        var i0 = Math.max(0, Math.min(a.length - 2, i));

        // The step (demoninator) is implicitly 1 since that's the grid spacing.
        return a[i0 + 1] - a[i0];
    };

    trace.dbdj = function(j /* , v*/) {
        // See above caveats for dadi which also apply here
        var j0 = Math.max(0, Math.min(b.length - 2, j));

        // The step (demoninator) is implicitly 1 since that's the grid spacing.
        return b[j0 + 1] - b[j0];
    };

    // Takes: grid cell coordinate (i, j) and fractional grid cell coordinates (u, v)
    // Returns: (dx/da, dy/db)
    //
    // NB: separate grid cell + fractional grid cell coordinate format is due to the discontinuous
    // derivative, as described better in create_i_derivative_evaluator.js
    trace.dxyda = function(i0, j0, u, v) {
        var dxydi = trace.dxydi(null, i0, j0, u, v);
        var dadi = trace.dadi(i0, u);

        return [dxydi[0] / dadi, dxydi[1] / dadi];
    };

    trace.dxydb = function(i0, j0, u, v) {
        var dxydj = trace.dxydj(null, i0, j0, u, v);
        var dbdj = trace.dbdj(j0, v);

        return [dxydj[0] / dbdj, dxydj[1] / dbdj];
    };

    // Sometimes we don't care about precision and all we really want is decent rough
    // directions (as is the case with labels). In that case, we can do a very rough finite
    // difference and spare having to worry about precise grid coordinates:
    trace.dxyda_rough = function(a, b, reldiff) {
        var h = arange * (reldiff || 0.1);
        var plus = trace.ab2xy(a + h, b, true);
        var minus = trace.ab2xy(a - h, b, true);

        return [
            (plus[0] - minus[0]) * 0.5 / h,
            (plus[1] - minus[1]) * 0.5 / h
        ];
    };

    trace.dxydb_rough = function(a, b, reldiff) {
        var h = brange * (reldiff || 0.1);
        var plus = trace.ab2xy(a, b + h, true);
        var minus = trace.ab2xy(a, b - h, true);

        return [
            (plus[0] - minus[0]) * 0.5 / h,
            (plus[1] - minus[1]) * 0.5 / h
        ];
    };

    trace.dpdx = function(xa) {
        return xa._m;
    };

    trace.dpdy = function(ya) {
        return ya._m;
    };
};

},{"../../lib/search":713,"./compute_control_points":886,"./constants":887,"./create_i_derivative_evaluator":888,"./create_j_derivative_evaluator":889,"./create_spline_evaluator":890}],899:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

/*
 * Given a 2D array as well as a basis in either direction, this function fills in the
 * 2D array using a combination of smoothing and extrapolation. This is rather important
 * for carpet plots since it's used for layout so that we can't simply omit or blank out
 * points. We need a reasonable guess so that the interpolation puts points somewhere
 * even if we were to somehow represent that the data was missing later on.
 *
 * input:
 *  - data: 2D array of arrays
 *  - a: array such that a.length === data[0].length
 *  - b: array such that b.length === data.length
 */
module.exports = function smoothFill2dArray(data, a, b) {
    var i, j, k;
    var ip = [];
    var jp = [];
    // var neighborCnts = [];

    var ni = data[0].length;
    var nj = data.length;

    function avgSurrounding(i, j) {
        // As a low-quality start, we can simply average surrounding points (in a not
        // non-uniform grid aware manner):
        var sum = 0.0;
        var val;
        var cnt = 0;
        if(i > 0 && (val = data[j][i - 1]) !== undefined) {
            cnt++;
            sum += val;
        }
        if(i < ni - 1 && (val = data[j][i + 1]) !== undefined) {
            cnt++;
            sum += val;
        }
        if(j > 0 && (val = data[j - 1][i]) !== undefined) {
            cnt++;
            sum += val;
        }
        if(j < nj - 1 && (val = data[j + 1][i]) !== undefined) {
            cnt++;
            sum += val;
        }
        return sum / Math.max(1, cnt);

    }

    // This loop iterates over all cells. Any cells that are null will be noted and those
    // are the only points we will loop over and update via laplace's equation. Points with
    // any neighbors will receive the average. If there are no neighboring points, then they
    // will be set to zero. Also as we go, track the maximum magnitude so that we can scale
    // our tolerance accordingly.
    var dmax = 0.0;
    for(i = 0; i < ni; i++) {
        for(j = 0; j < nj; j++) {
            if(data[j][i] === undefined) {
                ip.push(i);
                jp.push(j);

                data[j][i] = avgSurrounding(i, j);
                // neighborCnts.push(result.neighbors);
            }
            dmax = Math.max(dmax, Math.abs(data[j][i]));
        }
    }

    if(!ip.length) return data;

    // The tolerance doesn't need to be excessive. It's just for display positioning
    var dxp, dxm, dap, dam, dbp, dbm, c, d, diff, reldiff, overrelaxation;
    var tol = 1e-5;
    var resid = 0;
    var itermax = 100;
    var iter = 0;
    var n = ip.length;
    do {
        resid = 0;
        // Normally we'd loop in two dimensions, but not all points are blank and need
        // an update, so we instead loop only over the points that were tabulated above
        for(k = 0; k < n; k++) {
            i = ip[k];
            j = jp[k];
            // neighborCnt = neighborCnts[k];

            // Track a counter for how many contributions there are. We'll use this counter
            // to average at the end, which reduces to laplace's equation with neumann boundary
            // conditions on the first derivative (second derivative is zero so that we get
            // a nice linear extrapolation at the boundaries).
            var boundaryCnt = 0;
            var newVal = 0;

            var d0, d1, x0, x1, i0, j0;
            if(i === 0) {
                // If this lies along the i = 0 boundary, extrapolate from the two points
                // to the right of this point. Note that the finite differences take into
                // account non-uniform grid spacing:
                i0 = Math.min(ni - 1, 2);
                x0 = a[i0];
                x1 = a[1];
                d0 = data[j][i0];
                d1 = data[j][1];
                newVal += d1 + (d1 - d0) * (a[0] - x1) / (x1 - x0);
                boundaryCnt++;
            } else if(i === ni - 1) {
                // If along the high i boundary, extrapolate from the two points to the
                // left of this point
                i0 = Math.max(0, ni - 3);
                x0 = a[i0];
                x1 = a[ni - 2];
                d0 = data[j][i0];
                d1 = data[j][ni - 2];
                newVal += d1 + (d1 - d0) * (a[ni - 1] - x1) / (x1 - x0);
                boundaryCnt++;
            }

            if((i === 0 || i === ni - 1) && (j > 0 && j < nj - 1)) {
                // If along the min(i) or max(i) boundaries, also smooth vertically as long
                // as we're not in a corner. Note that the finite differences used here
                // are also aware of nonuniform grid spacing:
                dxp = b[j + 1] - b[j];
                dxm = b[j] - b[j - 1];
                newVal += (dxm * data[j + 1][i] + dxp * data[j - 1][i]) / (dxm + dxp);
                boundaryCnt++;
            }

            if(j === 0) {
                // If along the j = 0 boundary, extrpolate this point from the two points
                // above it
                j0 = Math.min(nj - 1, 2);
                x0 = b[j0];
                x1 = b[1];
                d0 = data[j0][i];
                d1 = data[1][i];
                newVal += d1 + (d1 - d0) * (b[0] - x1) / (x1 - x0);
                boundaryCnt++;
            } else if(j === nj - 1) {
                // Same for the max j boundary from the cells below it:
                j0 = Math.max(0, nj - 3);
                x0 = b[j0];
                x1 = b[nj - 2];
                d0 = data[j0][i];
                d1 = data[nj - 2][i];
                newVal += d1 + (d1 - d0) * (b[nj - 1] - x1) / (x1 - x0);
                boundaryCnt++;
            }

            if((j === 0 || j === nj - 1) && (i > 0 && i < ni - 1)) {
                // Now average points to the left/right as long as not in a corner:
                dxp = a[i + 1] - a[i];
                dxm = a[i] - a[i - 1];
                newVal += (dxm * data[j][i + 1] + dxp * data[j][i - 1]) / (dxm + dxp);
                boundaryCnt++;
            }

            if(!boundaryCnt) {
                // If none of the above conditions were triggered, then this is an interior
                // point and we can just do a laplace equation update. As above, these differences
                // are aware of nonuniform grid spacing:
                dap = a[i + 1] - a[i];
                dam = a[i] - a[i - 1];
                dbp = b[j + 1] - b[j];
                dbm = b[j] - b[j - 1];

                // These are just some useful constants for the iteration, which is perfectly
                // straightforward but a little long to derive from f_xx + f_yy = 0.
                c = dap * dam * (dap + dam);
                d = dbp * dbm * (dbp + dbm);

                newVal = (c * (dbm * data[j + 1][i] + dbp * data[j - 1][i]) +
                          d * (dam * data[j][i + 1] + dap * data[j][i - 1])) /
                          (d * (dam + dap) + c * (dbm + dbp));
            } else {
                // If we did have contributions from the boundary conditions, then average
                // the result from the various contributions:
                newVal /= boundaryCnt;
            }

            // Jacobi updates are ridiculously slow to converge, so this approach uses a
            // Gauss-seidel iteration which is dramatically faster.
            diff = newVal - data[j][i];
            reldiff = diff / dmax;
            resid += reldiff * reldiff;

            // Gauss-Seidel-ish iteration, omega chosen based on heuristics and some
            // quick tests.
            //
            // NB: Don't overrelax the boundarie. Otherwise set an overrelaxation factor
            // which is a little low but safely optimal-ish:
            overrelaxation = boundaryCnt ? 0 : 0.85;

            // If there are four non-null neighbors, then we want a simple average without
            // overrelaxation. If all the surrouding points are null, then we want the full
            // overrelaxation
            //
            // Based on experiments, this actually seems to slow down convergence just a bit.
            // I'll leave it here for reference in case this needs to be revisited, but
            // it seems to work just fine without this.
            // if (overrelaxation) overrelaxation *= (4 - neighborCnt) / 4;

            data[j][i] += diff * (1 + overrelaxation);
        }

        resid = Math.sqrt(resid);
    } while(iter++ < itermax && resid > tol);

    Lib.log('Smoother converged to', resid, 'after', iter, 'iterations');

    return data;
};

},{"../../lib":694}],900:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isArray1D = _dereq_('../../lib').isArray1D;

module.exports = function handleXYDefaults(traceIn, traceOut, coerce) {
    var x = coerce('x');
    var hasX = x && x.length;
    var y = coerce('y');
    var hasY = y && y.length;
    if(!hasX && !hasY) return false;

    traceOut._cheater = !x;

    if((!hasX || isArray1D(x)) && (!hasY || isArray1D(y))) {
        var len = hasX ? x.length : Infinity;
        if(hasY) len = Math.min(len, y.length);
        if(traceOut.a && traceOut.a.length) len = Math.min(len, traceOut.a.length);
        if(traceOut.b && traceOut.b.length) len = Math.min(len, traceOut.b.length);
        traceOut._length = len;
    }
    else traceOut._length = null;

    return true;
};

},{"../../lib":694}],901:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var scatterGeoAttrs = _dereq_('../scattergeo/attributes');
var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
var plotAttrs = _dereq_('../../plots/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;

var scatterGeoMarkerLineAttrs = scatterGeoAttrs.marker.line;

module.exports = extendFlat({
    locations: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    locationmode: scatterGeoAttrs.locationmode,
    z: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    text: extendFlat({}, scatterGeoAttrs.text, {
        
    }),
    marker: {
        line: {
            color: scatterGeoMarkerLineAttrs.color,
            width: extendFlat({}, scatterGeoMarkerLineAttrs.width, {dflt: 1}),
            editType: 'calc'
        },
        opacity: {
            valType: 'number',
            arrayOk: true,
            min: 0,
            max: 1,
            dflt: 1,
            
            editType: 'style',
            
        },
        editType: 'calc'
    },

    selected: {
        marker: {
            opacity: scatterGeoAttrs.selected.marker.opacity,
            editType: 'plot'
        },
        editType: 'plot'
    },
    unselected: {
        marker: {
            opacity: scatterGeoAttrs.unselected.marker.opacity,
            editType: 'plot'
        },
        editType: 'plot'
    },

    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
        editType: 'calc',
        flags: ['location', 'z', 'text', 'name']
    }),
    hovertemplate: hovertemplateAttrs(),
},

    colorscaleAttrs('', {
        cLetter: 'z',
        editTypeOverride: 'calc'
    }),
    {colorbar: colorbarAttrs}
);

},{"../../components/colorbar/attributes":572,"../../components/colorscale/attributes":578,"../../components/fx/hovertemplate_attributes":609,"../../lib/extend":684,"../../plots/attributes":739,"../scattergeo/attributes":1087}],902:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

var colorscaleCalc = _dereq_('../../components/colorscale/calc');
var arraysToCalcdata = _dereq_('../scatter/arrays_to_calcdata');
var calcSelection = _dereq_('../scatter/calc_selection');

module.exports = function calc(gd, trace) {
    var len = trace._length;
    var calcTrace = new Array(len);

    for(var i = 0; i < len; i++) {
        var calcPt = calcTrace[i] = {};
        var loc = trace.locations[i];
        var z = trace.z[i];

        calcPt.loc = typeof loc === 'string' ? loc : null;
        calcPt.z = isNumeric(z) ? z : BADNUM;
    }

    arraysToCalcdata(calcTrace, trace);
    colorscaleCalc(gd, trace, {
        vals: trace.z,
        containerStr: '',
        cLetter: 'z'
    });
    calcSelection(calcTrace, trace);

    return calcTrace;
};

},{"../../components/colorscale/calc":579,"../../constants/numerical":671,"../scatter/arrays_to_calcdata":1046,"../scatter/calc_selection":1049,"fast-isnumeric":215}],903:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var locations = coerce('locations');
    var z = coerce('z');

    if(!(locations && locations.length && Lib.isArrayOrTypedArray(z) && z.length)) {
        traceOut.visible = false;
        return;
    }
    traceOut._length = Math.min(locations.length, z.length);

    coerce('locationmode');

    coerce('text');
    coerce('hovertemplate');

    coerce('marker.line.color');
    coerce('marker.line.width');
    coerce('marker.opacity');

    colorscaleDefaults(
        traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'}
    );

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};

},{"../../components/colorscale/defaults":581,"../../lib":694,"./attributes":901}],904:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = function eventData(out, pt) {
    out.location = pt.location;
    out.z = pt.z;

    return out;
};

},{}],905:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Axes = _dereq_('../../plots/cartesian/axes');
var attributes = _dereq_('./attributes');
var fillHoverText = _dereq_('../scatter/fill_hover_text');

module.exports = function hoverPoints(pointData, xval, yval) {
    var cd = pointData.cd;
    var trace = cd[0].trace;
    var geo = pointData.subplot;

    var pt, i, j, isInside;

    for(i = 0; i < cd.length; i++) {
        pt = cd[i];
        isInside = false;

        if(pt._polygons) {
            for(j = 0; j < pt._polygons.length; j++) {
                if(pt._polygons[j].contains([xval, yval])) {
                    isInside = !isInside;
                }
                // for polygons that cross antimeridian as xval is in [-180, 180]
                if(pt._polygons[j].contains([xval + 360, yval])) {
                    isInside = !isInside;
                }
            }

            if(isInside) break;
        }
    }

    if(!isInside || !pt) return;

    pointData.x0 = pointData.x1 = pointData.xa.c2p(pt.ct);
    pointData.y0 = pointData.y1 = pointData.ya.c2p(pt.ct);

    pointData.index = pt.index;
    pointData.location = pt.loc;
    pointData.z = pt.z;
    pointData.hovertemplate = pt.hovertemplate;

    makeHoverInfo(pointData, trace, pt, geo.mockAxis);

    return [pointData];
};

function makeHoverInfo(pointData, trace, pt, axis) {
    if(trace.hovertemplate) {
        return;
    }

    var hoverinfo = pt.hi || trace.hoverinfo;

    var parts = (hoverinfo === 'all') ?
        attributes.hoverinfo.flags :
        hoverinfo.split('+');

    var hasName = (parts.indexOf('name') !== -1);
    var hasLocation = (parts.indexOf('location') !== -1);
    var hasZ = (parts.indexOf('z') !== -1);
    var hasText = (parts.indexOf('text') !== -1);
    var hasIdAsNameLabel = !hasName && hasLocation;

    var text = [];

    function formatter(val) {
        return Axes.tickText(axis, axis.c2l(val), 'hover').text;
    }

    if(hasIdAsNameLabel) {
        pointData.nameOverride = pt.loc;
    } else {
        if(hasName) pointData.nameOverride = trace.name;
        if(hasLocation) text.push(pt.loc);
    }

    if(hasZ) text.push(formatter(pt.z));
    if(hasText) {
        fillHoverText(pt, trace, text);
    }

    pointData.extraText = text.join('<br>');
}

},{"../../plots/cartesian/axes":742,"../scatter/fill_hover_text":1055,"./attributes":901}],906:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Choropleth = {};

Choropleth.attributes = _dereq_('./attributes');
Choropleth.supplyDefaults = _dereq_('./defaults');
Choropleth.colorbar = _dereq_('../heatmap/colorbar');
Choropleth.calc = _dereq_('./calc');
Choropleth.plot = _dereq_('./plot');
Choropleth.style = _dereq_('./style').style;
Choropleth.styleOnSelect = _dereq_('./style').styleOnSelect;
Choropleth.hoverPoints = _dereq_('./hover');
Choropleth.eventData = _dereq_('./event_data');
Choropleth.selectPoints = _dereq_('./select');

Choropleth.moduleType = 'trace';
Choropleth.name = 'choropleth';
Choropleth.basePlotModule = _dereq_('../../plots/geo');
Choropleth.categories = ['geo', 'noOpacity'];
Choropleth.meta = {
    
};

module.exports = Choropleth;

},{"../../plots/geo":773,"../heatmap/colorbar":947,"./attributes":901,"./calc":902,"./defaults":903,"./event_data":904,"./hover":905,"./plot":907,"./select":908,"./style":909}],907:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Lib = _dereq_('../../lib');
var polygon = _dereq_('../../lib/polygon');

var getTopojsonFeatures = _dereq_('../../lib/topojson_utils').getTopojsonFeatures;
var locationToFeature = _dereq_('../../lib/geo_location_utils').locationToFeature;
var style = _dereq_('./style').style;

module.exports = function plot(gd, geo, calcData) {
    for(var i = 0; i < calcData.length; i++) {
        calcGeoJSON(calcData[i], geo.topojson);
    }

    var choroplethLayer = geo.layers.backplot.select('.choroplethlayer');
    Lib.makeTraceGroups(choroplethLayer, calcData, 'trace choropleth').each(function(calcTrace) {
        var sel = calcTrace[0].node3 = d3.select(this);

        var paths = sel.selectAll('path.choroplethlocation')
            .data(Lib.identity);

        paths.enter().append('path')
            .classed('choroplethlocation', true);

        paths.exit().remove();

        // call style here within topojson request callback
        style(gd, calcTrace);
    });
};

function calcGeoJSON(calcTrace, topojson) {
    var trace = calcTrace[0].trace;
    var len = calcTrace.length;
    var features = getTopojsonFeatures(trace, topojson);

    for(var i = 0; i < len; i++) {
        var calcPt = calcTrace[i];
        var feature = locationToFeature(trace.locationmode, calcPt.loc, features);

        if(!feature) {
            calcPt.geojson = null;
            continue;
        }


        calcPt.geojson = feature;
        calcPt.ct = feature.properties.ct;
        calcPt.index = i;
        calcPt._polygons = feature2polygons(feature);
    }
}

function feature2polygons(feature) {
    var geometry = feature.geometry;
    var coords = geometry.coordinates;
    var loc = feature.id;

    var polygons = [];
    var appendPolygon, j, k, m;

    function doesCrossAntiMerdian(pts) {
        for(var l = 0; l < pts.length - 1; l++) {
            if(pts[l][0] > 0 && pts[l + 1][0] < 0) return l;
        }
        return null;
    }

    if(loc === 'RUS' || loc === 'FJI') {
        // Russia and Fiji have landmasses that cross the antimeridian,
        // we need to add +360 to their longitude coordinates, so that
        // polygon 'contains' doesn't get confused when crossing the antimeridian.
        //
        // Note that other countries have polygons on either side of the antimeridian
        // (e.g. some Aleutian island for the USA), but those don't confuse
        // the 'contains' method; these are skipped here.
        appendPolygon = function(_pts) {
            var pts;

            if(doesCrossAntiMerdian(_pts) === null) {
                pts = _pts;
            } else {
                pts = new Array(_pts.length);
                for(m = 0; m < _pts.length; m++) {
                    // do nut mutate calcdata[i][j].geojson !!
                    pts[m] = [
                        _pts[m][0] < 0 ? _pts[m][0] + 360 : _pts[m][0],
                        _pts[m][1]
                    ];
                }
            }

            polygons.push(polygon.tester(pts));
        };
    } else if(loc === 'ATA') {
        // Antarctica has a landmass that wraps around every longitudes which
        // confuses the 'contains' methods.
        appendPolygon = function(pts) {
            var crossAntiMeridianIndex = doesCrossAntiMerdian(pts);

            // polygon that do not cross anti-meridian need no special handling
            if(crossAntiMeridianIndex === null) {
                return polygons.push(polygon.tester(pts));
            }

            // stitch polygon by adding pt over South Pole,
            // so that it covers the projected region covers all latitudes
            //
            // Note that the algorithm below only works for polygons that
            // start and end on longitude -180 (like the ones built by
            // https://github.com/etpinard/sane-topojson).
            var stitch = new Array(pts.length + 1);
            var si = 0;

            for(m = 0; m < pts.length; m++) {
                if(m > crossAntiMeridianIndex) {
                    stitch[si++] = [pts[m][0] + 360, pts[m][1]];
                } else if(m === crossAntiMeridianIndex) {
                    stitch[si++] = pts[m];
                    stitch[si++] = [pts[m][0], -90];
                } else {
                    stitch[si++] = pts[m];
                }
            }

            // polygon.tester by default appends pt[0] to the points list,
            // we must remove it here, to avoid a jump in longitude from 180 to -180,
            // that would confuse the 'contains' method
            var tester = polygon.tester(stitch);
            tester.pts.pop();
            polygons.push(tester);
        };
    } else {
        // otherwise using same array ref is fine
        appendPolygon = function(pts) {
            polygons.push(polygon.tester(pts));
        };
    }

    switch(geometry.type) {
        case 'MultiPolygon':
            for(j = 0; j < coords.length; j++) {
                for(k = 0; k < coords[j].length; k++) {
                    appendPolygon(coords[j][k]);
                }
            }
            break;
        case 'Polygon':
            for(j = 0; j < coords.length; j++) {
                appendPolygon(coords[j]);
            }
            break;
    }

    return polygons;
}

},{"../../lib":694,"../../lib/geo_location_utils":687,"../../lib/polygon":706,"../../lib/topojson_utils":721,"./style":909,"d3":149}],908:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function selectPoints(searchInfo, selectionTester) {
    var cd = searchInfo.cd;
    var xa = searchInfo.xaxis;
    var ya = searchInfo.yaxis;
    var selection = [];

    var i, di, ct, x, y;

    if(selectionTester === false) {
        for(i = 0; i < cd.length; i++) {
            cd[i].selected = 0;
        }
    } else {
        for(i = 0; i < cd.length; i++) {
            di = cd[i];
            ct = di.ct;

            if(!ct) continue;

            x = xa.c2p(ct);
            y = ya.c2p(ct);

            if(selectionTester.contains([x, y], null, i, searchInfo)) {
                selection.push({
                    pointNumber: i,
                    lon: ct[0],
                    lat: ct[1]
                });
                di.selected = 1;
            } else {
                di.selected = 0;
            }
        }
    }

    return selection;
};

},{}],909:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var Color = _dereq_('../../components/color');
var Drawing = _dereq_('../../components/drawing');
var Colorscale = _dereq_('../../components/colorscale');

function style(gd, calcTrace) {
    if(calcTrace) styleTrace(gd, calcTrace);
}

function styleTrace(gd, calcTrace) {
    var trace = calcTrace[0].trace;
    var s = calcTrace[0].node3;
    var locs = s.selectAll('.choroplethlocation');
    var marker = trace.marker || {};
    var markerLine = marker.line || {};

    var sclFunc = Colorscale.makeColorScaleFunc(
        Colorscale.extractScale(trace, {cLetter: 'z'})
    );

    locs.each(function(d) {
        d3.select(this)
            .attr('fill', sclFunc(d.z))
            .call(Color.stroke, d.mlc || markerLine.color)
            .call(Drawing.dashLine, '', d.mlw || markerLine.width || 0)
            .style('opacity', marker.opacity);
    });

    Drawing.selectedPointStyle(locs, trace, gd);
}

function styleOnSelect(gd, calcTrace) {
    var s = calcTrace[0].node3;
    var trace = calcTrace[0].trace;

    if(trace.selectedpoints) {
        Drawing.selectedPointStyle(s.selectAll('.choroplethlocation'), trace, gd);
    } else {
        styleTrace(gd, calcTrace);
    }
}

module.exports = {
    style: style,
    styleOnSelect: styleOnSelect
};

},{"../../components/color":571,"../../components/colorscale":583,"../../components/drawing":592,"d3":149}],910:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
var mesh3dAttrs = _dereq_('../mesh3d/attributes');
var baseAttrs = _dereq_('../../plots/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;

var attrs = {
    x: {
        valType: 'data_array',
        
        editType: 'calc+clearAxisTypes',
        
    },
    y: {
        valType: 'data_array',
        
        editType: 'calc+clearAxisTypes',
        
    },
    z: {
        valType: 'data_array',
        
        editType: 'calc+clearAxisTypes',
        
    },

    u: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    v: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    w: {
        valType: 'data_array',
        editType: 'calc',
        
    },

    // TODO add way to specify cone positions independently of the vector field
    // provided, similar to MATLAB's coneplot Cx/Cy/Cz meshgrids,
    // see https://www.mathworks.com/help/matlab/ref/coneplot.html
    //
    // Alternatively, if our goal is only to 'fill in gaps' in the vector data,
    // we could try to extend the heatmap 'connectgaps' algorithm to 3D.
    // From AJ: this particular algorithm which amounts to a Poisson equation,
    // both for interpolation and extrapolation - is the right one to use for
    // cones too.  It makes a field with zero divergence, which is a good
    // baseline assumption for vector fields.
    //
    // cones: {
    //     // potential attributes to add:
    //     //
    //     // - meshmode: 'cartesian-product', 'pts', 'grid'
    //     //
    //     // under `meshmode: 'grid'`
    //     // - (x|y|z)grid.start
    //     // - (x|y|z)grid.end
    //     // - (x|y|z)grid.size
    //
    //     x: {
    //         valType: 'data_array',
    //         editType: 'calc',
    //         
    //     },
    //     y: {
    //         valType: 'data_array',
    //         editType: 'calc',
    //         
    //     },
    //     z: {
    //         valType: 'data_array',
    //         editType: 'calc',
    //         
    //     },
    //
    //     editType: 'calc',
    //     
    // },

    sizemode: {
        valType: 'enumerated',
        values: ['scaled', 'absolute'],
        
        editType: 'calc',
        dflt: 'scaled',
        
    },
    sizeref: {
        valType: 'number',
        
        editType: 'calc',
        min: 0,
        
    },

    anchor: {
        valType: 'enumerated',
        
        editType: 'calc',
        values: ['tip', 'tail', 'cm', 'center'],
        dflt: 'cm',
        
    },

    text: {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        editType: 'calc',
        
    }
};

extendFlat(attrs, colorscaleAttrs('', {
    colorAttr: 'u/v/w norm',
    showScaleDflt: true,
    editTypeOverride: 'calc'
}), {
    colorbar: colorbarAttrs
});

var fromMesh3d = ['opacity', 'lightposition', 'lighting'];

fromMesh3d.forEach(function(k) {
    attrs[k] = mesh3dAttrs[k];
});

attrs.hoverinfo = extendFlat({}, baseAttrs.hoverinfo, {
    editType: 'calc',
    flags: ['x', 'y', 'z', 'u', 'v', 'w', 'norm', 'text', 'name'],
    dflt: 'x+y+z+norm+text+name'
});

attrs.transforms = undefined;

module.exports = attrs;

},{"../../components/colorbar/attributes":572,"../../components/colorscale/attributes":578,"../../lib/extend":684,"../../plots/attributes":739,"../mesh3d/attributes":990}],911:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorscaleCalc = _dereq_('../../components/colorscale/calc');

module.exports = function calc(gd, trace) {
    var u = trace.u;
    var v = trace.v;
    var w = trace.w;
    var len = Math.min(
        trace.x.length, trace.y.length, trace.z.length,
        u.length, v.length, w.length
    );
    var normMax = -Infinity;
    var normMin = Infinity;

    for(var i = 0; i < len; i++) {
        var uu = u[i];
        var vv = v[i];
        var ww = w[i];
        var norm = Math.sqrt(uu * uu + vv * vv + ww * ww);

        normMax = Math.max(normMax, norm);
        normMin = Math.min(normMin, norm);
    }

    trace._len = len;
    trace._normMax = normMax;

    colorscaleCalc(gd, trace, {
        vals: [normMin, normMax],
        containerStr: '',
        cLetter: 'c'
    });
};

},{"../../components/colorscale/calc":579}],912:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var conePlot = _dereq_('gl-cone3d');
var createConeMesh = _dereq_('gl-cone3d').createConeMesh;

var simpleMap = _dereq_('../../lib').simpleMap;
var parseColorScale = _dereq_('../../lib/gl_format_color').parseColorScale;
var zip3 = _dereq_('../../plots/gl3d/zip3');

function Cone(scene, uid) {
    this.scene = scene;
    this.uid = uid;
    this.mesh = null;
    this.data = null;
}

var proto = Cone.prototype;

proto.handlePick = function(selection) {
    if(selection.object === this.mesh) {
        var selectIndex = selection.index = selection.data.index;
        var xx = this.data.x[selectIndex];
        var yy = this.data.y[selectIndex];
        var zz = this.data.z[selectIndex];
        var uu = this.data.u[selectIndex];
        var vv = this.data.v[selectIndex];
        var ww = this.data.w[selectIndex];

        selection.traceCoordinate = [
            xx, yy, zz,
            uu, vv, ww,
            Math.sqrt(uu * uu + vv * vv + ww * ww)
        ];

        var text = this.data.text;
        if(Array.isArray(text) && text[selectIndex] !== undefined) {
            selection.textLabel = text[selectIndex];
        } else if(text) {
            selection.textLabel = text;
        }

        return true;
    }
};

var axisName2scaleIndex = {xaxis: 0, yaxis: 1, zaxis: 2};
var anchor2coneOffset = {tip: 1, tail: 0, cm: 0.25, center: 0.5};
var anchor2coneSpan = {tip: 1, tail: 1, cm: 0.75, center: 0.5};

function convert(scene, trace) {
    var sceneLayout = scene.fullSceneLayout;
    var dataScale = scene.dataScale;
    var coneOpts = {};

    function toDataCoords(arr, axisName) {
        var ax = sceneLayout[axisName];
        var scale = dataScale[axisName2scaleIndex[axisName]];
        return simpleMap(arr, function(v) { return ax.d2l(v) * scale; });
    }

    coneOpts.vectors = zip3(
        toDataCoords(trace.u, 'xaxis'),
        toDataCoords(trace.v, 'yaxis'),
        toDataCoords(trace.w, 'zaxis'),
        trace._len
    );

    coneOpts.positions = zip3(
        toDataCoords(trace.x, 'xaxis'),
        toDataCoords(trace.y, 'yaxis'),
        toDataCoords(trace.z, 'zaxis'),
        trace._len
    );

    coneOpts.colormap = parseColorScale(trace);
    coneOpts.vertexIntensityBounds = [trace.cmin / trace._normMax, trace.cmax / trace._normMax];
    coneOpts.coneOffset = anchor2coneOffset[trace.anchor];

    if(trace.sizemode === 'scaled') {
        // unitless sizeref
        coneOpts.coneSize = trace.sizeref || 0.5;
    } else {
        // sizeref here has unit of velocity
        coneOpts.coneSize = trace.sizeref && trace._normMax ?
            trace.sizeref / trace._normMax :
            0.5;
    }

    var meshData = conePlot(coneOpts);

    // pass gl-mesh3d lighting attributes
    var lp = trace.lightposition;
    meshData.lightPosition = [lp.x, lp.y, lp.z];
    meshData.ambient = trace.lighting.ambient;
    meshData.diffuse = trace.lighting.diffuse;
    meshData.specular = trace.lighting.specular;
    meshData.roughness = trace.lighting.roughness;
    meshData.fresnel = trace.lighting.fresnel;
    meshData.opacity = trace.opacity;

    // stash autorange pad value
    trace._pad = anchor2coneSpan[trace.anchor] * meshData.vectorScale * meshData.coneScale * trace._normMax;

    return meshData;
}

proto.update = function(data) {
    this.data = data;

    var meshData = convert(this.scene, data);
    this.mesh.update(meshData);
};

proto.dispose = function() {
    this.scene.glplot.remove(this.mesh);
    this.mesh.dispose();
};

function createConeTrace(scene, data) {
    var gl = scene.glplot.gl;

    var meshData = convert(scene, data);
    var mesh = createConeMesh(gl, meshData);

    var cone = new Cone(scene, data.uid);
    cone.mesh = mesh;
    cone.data = data;
    mesh._trace = cone;

    scene.glplot.add(mesh);

    return cone;
}

module.exports = createConeTrace;

},{"../../lib":694,"../../lib/gl_format_color":691,"../../plots/gl3d/zip3":796,"gl-cone3d":232}],913:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var u = coerce('u');
    var v = coerce('v');
    var w = coerce('w');

    var x = coerce('x');
    var y = coerce('y');
    var z = coerce('z');

    if(
        !u || !u.length || !v || !v.length || !w || !w.length ||
        !x || !x.length || !y || !y.length || !z || !z.length
    ) {
        traceOut.visible = false;
        return;
    }

    coerce('sizeref');
    coerce('sizemode');

    coerce('anchor');

    coerce('lighting.ambient');
    coerce('lighting.diffuse');
    coerce('lighting.specular');
    coerce('lighting.roughness');
    coerce('lighting.fresnel');
    coerce('lightposition.x');
    coerce('lightposition.y');
    coerce('lightposition.z');

    colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'c'});

    coerce('text');

    // disable 1D transforms (for now)
    traceOut._length = null;
};

},{"../../components/colorscale/defaults":581,"../../lib":694,"./attributes":910}],914:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'trace',
    name: 'cone',
    basePlotModule: _dereq_('../../plots/gl3d'),
    categories: ['gl3d'],

    attributes: _dereq_('./attributes'),
    supplyDefaults: _dereq_('./defaults'),
    colorbar: {
        min: 'cmin',
        max: 'cmax'
    },
    calc: _dereq_('./calc'),
    plot: _dereq_('./convert'),

    meta: {
        
    }
};

},{"../../plots/gl3d":785,"./attributes":910,"./calc":911,"./convert":912,"./defaults":913}],915:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var heatmapAttrs = _dereq_('../heatmap/attributes');
var scatterAttrs = _dereq_('../scatter/attributes');
var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
var dash = _dereq_('../../components/drawing/attributes').dash;
var fontAttrs = _dereq_('../../plots/font_attributes');
var extendFlat = _dereq_('../../lib/extend').extendFlat;

var filterOps = _dereq_('../../constants/filter_ops');
var COMPARISON_OPS2 = filterOps.COMPARISON_OPS2;
var INTERVAL_OPS = filterOps.INTERVAL_OPS;

var scatterLineAttrs = scatterAttrs.line;

module.exports = extendFlat({
    z: heatmapAttrs.z,
    x: heatmapAttrs.x,
    x0: heatmapAttrs.x0,
    dx: heatmapAttrs.dx,
    y: heatmapAttrs.y,
    y0: heatmapAttrs.y0,
    dy: heatmapAttrs.dy,
    text: heatmapAttrs.text,
    transpose: heatmapAttrs.transpose,
    xtype: heatmapAttrs.xtype,
    ytype: heatmapAttrs.ytype,
    zhoverformat: heatmapAttrs.zhoverformat,

    connectgaps: heatmapAttrs.connectgaps,

    fillcolor: {
        valType: 'color',
        
        editType: 'calc',
        
    },

    autocontour: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'calc',
        impliedEdits: {
            'contours.start': undefined,
            'contours.end': undefined,
            'contours.size': undefined
        },
        
    },
    ncontours: {
        valType: 'integer',
        dflt: 15,
        min: 1,
        
        editType: 'calc',
        
    },

    contours: {
        type: {
            valType: 'enumerated',
            values: ['levels', 'constraint'],
            dflt: 'levels',
            
            editType: 'calc',
            
        },
        start: {
            valType: 'number',
            dflt: null,
            
            editType: 'plot',
            impliedEdits: {'^autocontour': false},
            
        },
        end: {
            valType: 'number',
            dflt: null,
            
            editType: 'plot',
            impliedEdits: {'^autocontour': false},
            
        },
        size: {
            valType: 'number',
            dflt: null,
            min: 0,
            
            editType: 'plot',
            impliedEdits: {'^autocontour': false},
            
        },
        coloring: {
            valType: 'enumerated',
            values: ['fill', 'heatmap', 'lines', 'none'],
            dflt: 'fill',
            
            editType: 'calc',
            
        },
        showlines: {
            valType: 'boolean',
            dflt: true,
            
            editType: 'plot',
            
        },
        showlabels: {
            valType: 'boolean',
            dflt: false,
            
            editType: 'plot',
            
        },
        labelfont: fontAttrs({
            editType: 'plot',
            colorEditType: 'style',
            
        }),
        labelformat: {
            valType: 'string',
            dflt: '',
            
            editType: 'plot',
            
        },
        operation: {
            valType: 'enumerated',
            values: [].concat(COMPARISON_OPS2).concat(INTERVAL_OPS),
            
            dflt: '=',
            editType: 'calc',
            
        },
        value: {
            valType: 'any',
            dflt: 0,
            
            editType: 'calc',
            
        },
        editType: 'calc',
        impliedEdits: {'autocontour': false}
    },

    line: {
        color: extendFlat({}, scatterLineAttrs.color, {
            editType: 'style+colorbars',
            
        }),
        width: extendFlat({}, scatterLineAttrs.width, {
            editType: 'style+colorbars'
        }),
        dash: dash,
        smoothing: extendFlat({}, scatterLineAttrs.smoothing, {
            
        }),
        editType: 'plot'
    }
},
    colorscaleAttrs('', {
        cLetter: 'z',
        autoColorDflt: false,
        editTypeOverride: 'calc'
    }),
    { colorbar: colorbarAttrs }
);

},{"../../components/colorbar/attributes":572,"../../components/colorscale/attributes":578,"../../components/drawing/attributes":591,"../../constants/filter_ops":667,"../../lib/extend":684,"../../plots/font_attributes":769,"../heatmap/attributes":944,"../scatter/attributes":1047}],916:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var heatmapCalc = _dereq_('../heatmap/calc');
var setContours = _dereq_('./set_contours');

// most is the same as heatmap calc, then adjust it
// though a few things inside heatmap calc still look for
// contour maps, because the makeBoundArray calls are too entangled
module.exports = function calc(gd, trace) {
    var cd = heatmapCalc(gd, trace);
    setContours(trace);
    return cd;
};

},{"../heatmap/calc":945,"./set_contours":934}],917:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function(pathinfo, operation, perimeter, trace) {
    // Abandon all hope, ye who enter here.
    var i, v1, v2;
    var pi0 = pathinfo[0];
    var na = pi0.x.length;
    var nb = pi0.y.length;
    var z = pi0.z;
    var contours = trace.contours;

    var boundaryMax = -Infinity;
    var boundaryMin = Infinity;

    for(i = 0; i < nb; i++) {
        boundaryMin = Math.min(boundaryMin, z[i][0]);
        boundaryMin = Math.min(boundaryMin, z[i][na - 1]);
        boundaryMax = Math.max(boundaryMax, z[i][0]);
        boundaryMax = Math.max(boundaryMax, z[i][na - 1]);
    }

    for(i = 1; i < na - 1; i++) {
        boundaryMin = Math.min(boundaryMin, z[0][i]);
        boundaryMin = Math.min(boundaryMin, z[nb - 1][i]);
        boundaryMax = Math.max(boundaryMax, z[0][i]);
        boundaryMax = Math.max(boundaryMax, z[nb - 1][i]);
    }

    pi0.prefixBoundary = false;

    switch(operation) {
        case '>':
            if(contours.value > boundaryMax) {
                pi0.prefixBoundary = true;
            }
            break;
        case '<':
            if(contours.value < boundaryMin) {
                pi0.prefixBoundary = true;
            }
            break;
        case '[]':
            v1 = Math.min.apply(null, contours.value);
            v2 = Math.max.apply(null, contours.value);
            if(v2 < boundaryMin || v1 > boundaryMax) {
                pi0.prefixBoundary = true;
            }
            break;
        case '][':
            v1 = Math.min.apply(null, contours.value);
            v2 = Math.max.apply(null, contours.value);
            if(v1 < boundaryMin && v2 > boundaryMax) {
                pi0.prefixBoundary = true;
            }
            break;
    }
};

},{}],918:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var drawColorbar = _dereq_('../../components/colorbar/draw');

var makeColorMap = _dereq_('./make_color_map');
var endPlus = _dereq_('./end_plus');


module.exports = function colorbar(gd, cd) {
    var trace = cd[0].trace;
    var cbId = 'cb' + trace.uid;

    gd._fullLayout._infolayer.selectAll('.' + cbId).remove();

    if(!trace.showscale) return;

    var cb = cd[0].t.cb = drawColorbar(gd, cbId);

    var contours = trace.contours;
    var line = trace.line;
    var cs = contours.size || 1;
    var coloring = contours.coloring;

    var colorMap = makeColorMap(trace, {isColorbar: true});

    cb.fillgradient(coloring === 'heatmap' ? trace.colorscale : '')
        .zrange(coloring === 'heatmap' ? [trace.zmin, trace.zmax] : '')
        .fillcolor((coloring === 'fill') ? colorMap : '')
        .line({
            color: coloring === 'lines' ? colorMap : line.color,
            width: contours.showlines !== false ? line.width : 0,
            dash: line.dash
        })
        .levels({
            start: contours.start,
            end: endPlus(contours),
            size: cs
        })
        .options(trace.colorbar)();
};

},{"../../components/colorbar/draw":576,"./end_plus":926,"./make_color_map":931}],919:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';
module.exports = {
    // some constants to help with marching squares algorithm
    // where does the path start for each index?
    BOTTOMSTART: [1, 9, 13, 104, 713],
    TOPSTART: [4, 6, 7, 104, 713],
    LEFTSTART: [8, 12, 14, 208, 1114],
    RIGHTSTART: [2, 3, 11, 208, 1114],

    // which way [dx,dy] do we leave a given index?
    // saddles are already disambiguated
    NEWDELTA: [
        null, [-1, 0], [0, -1], [-1, 0],
        [1, 0], null, [0, -1], [-1, 0],
        [0, 1], [0, 1], null, [0, 1],
        [1, 0], [1, 0], [0, -1]
    ],

    // for each saddle, the first index here is used
    // for dx||dy<0, the second for dx||dy>0
    CHOOSESADDLE: {
        104: [4, 1],
        208: [2, 8],
        713: [7, 13],
        1114: [11, 14]
    },

    // after one index has been used for a saddle, which do we
    // substitute to be used up later?
    SADDLEREMAINDER: {1: 4, 2: 8, 4: 1, 7: 13, 8: 2, 11: 14, 13: 7, 14: 11},

    // length of a contour, as a multiple of the plot area diagonal, per label
    LABELDISTANCE: 2,

    // number of contour levels after which we start increasing the number of
    // labels we draw. Many contours means they will generally be close
    // together, so it will be harder to follow a long way to find a label
    LABELINCREASE: 10,

    // minimum length of a contour line, as a multiple of the label length,
    // at which we draw *any* labels
    LABELMIN: 3,

    // max number of labels to draw on a single contour path, no matter how long
    LABELMAX: 10,

    // constants for the label position cost function
    LABELOPTIMIZER: {
        // weight given to edge proximity
        EDGECOST: 1,
        // weight given to the angle off horizontal
        ANGLECOST: 1,
        // weight given to distance from already-placed labels
        NEIGHBORCOST: 5,
        // cost multiplier for labels on the same level
        SAMELEVELFACTOR: 10,
        // minimum distance (as a multiple of the label length)
        // for labels on the same level
        SAMELEVELDISTANCE: 5,
        // maximum cost before we won't even place the label
        MAXCOST: 100,
        // number of evenly spaced points to look at in the first
        // iteration of the search
        INITIALSEARCHPOINTS: 10,
        // number of binary search iterations after the initial wide search
        ITERATIONS: 5
    }
};

},{}],920:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';
var isNumeric = _dereq_('fast-isnumeric');

var handleLabelDefaults = _dereq_('./label_defaults');

var Color = _dereq_('../../components/color');
var addOpacity = Color.addOpacity;
var opacity = Color.opacity;

var filterOps = _dereq_('../../constants/filter_ops');
var CONSTRAINT_REDUCTION = filterOps.CONSTRAINT_REDUCTION;
var COMPARISON_OPS2 = filterOps.COMPARISON_OPS2;

module.exports = function handleConstraintDefaults(traceIn, traceOut, coerce, layout, defaultColor, opts) {
    var contours = traceOut.contours;
    var showLines, lineColor, fillColor;

    var operation = coerce('contours.operation');
    contours._operation = CONSTRAINT_REDUCTION[operation];

    handleConstraintValueDefaults(coerce, contours);

    if(operation === '=') {
        showLines = contours.showlines = true;
    }
    else {
        showLines = coerce('contours.showlines');
        fillColor = coerce('fillcolor', addOpacity(
            (traceIn.line || {}).color || defaultColor, 0.5
        ));
    }

    if(showLines) {
        var lineDfltColor = fillColor && opacity(fillColor) ?
            addOpacity(traceOut.fillcolor, 1) :
            defaultColor;
        lineColor = coerce('line.color', lineDfltColor);
        coerce('line.width', 2);
        coerce('line.dash');
    }

    coerce('line.smoothing');

    handleLabelDefaults(coerce, layout, lineColor, opts);
};

function handleConstraintValueDefaults(coerce, contours) {
    var zvalue;

    if(COMPARISON_OPS2.indexOf(contours.operation) === -1) {
        // Requires an array of two numbers:
        coerce('contours.value', [0, 1]);

        if(!Array.isArray(contours.value)) {
            if(isNumeric(contours.value)) {
                zvalue = parseFloat(contours.value);
                contours.value = [zvalue, zvalue + 1];
            }
        } else if(contours.value.length > 2) {
            contours.value = contours.value.slice(2);
        } else if(contours.length === 0) {
            contours.value = [0, 1];
        } else if(contours.length < 2) {
            zvalue = parseFloat(contours.value[0]);
            contours.value = [zvalue, zvalue + 1];
        } else {
            contours.value = [
                parseFloat(contours.value[0]),
                parseFloat(contours.value[1])
            ];
        }
    } else {
        // Requires a single scalar:
        coerce('contours.value', 0);

        if(!isNumeric(contours.value)) {
            if(Array.isArray(contours.value)) {
                contours.value = parseFloat(contours.value[0]);
            } else {
                contours.value = 0;
            }
        }
    }
}

},{"../../components/color":571,"../../constants/filter_ops":667,"./label_defaults":930,"fast-isnumeric":215}],921:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var filterOps = _dereq_('../../constants/filter_ops');
var isNumeric = _dereq_('fast-isnumeric');

// This syntax conforms to the existing filter transform syntax, but we don't care
// about open vs. closed intervals for simply drawing contours constraints:
module.exports = {
    '[]': makeRangeSettings('[]'),
    '][': makeRangeSettings(']['),
    '>': makeInequalitySettings('>'),
    '<': makeInequalitySettings('<'),
    '=': makeInequalitySettings('=')
};

// This does not in any way shape or form support calendars. It's adapted from
// transforms/filter.js.
function coerceValue(operation, value) {
    var hasArrayValue = Array.isArray(value);

    var coercedValue;

    function coerce(value) {
        return isNumeric(value) ? (+value) : null;
    }

    if(filterOps.COMPARISON_OPS2.indexOf(operation) !== -1) {
        coercedValue = hasArrayValue ? coerce(value[0]) : coerce(value);
    } else if(filterOps.INTERVAL_OPS.indexOf(operation) !== -1) {
        coercedValue = hasArrayValue ?
            [coerce(value[0]), coerce(value[1])] :
            [coerce(value), coerce(value)];
    } else if(filterOps.SET_OPS.indexOf(operation) !== -1) {
        coercedValue = hasArrayValue ? value.map(coerce) : [coerce(value)];
    }

    return coercedValue;
}

// Returns a parabola scaled so that the min/max is either +/- 1 and zero at the two values
// provided. The data is mapped by this function when constructing intervals so that it's
// very easy to construct contours as normal.
function makeRangeSettings(operation) {
    return function(value) {
        value = coerceValue(operation, value);

        // Ensure proper ordering:
        var min = Math.min(value[0], value[1]);
        var max = Math.max(value[0], value[1]);

        return {
            start: min,
            end: max,
            size: max - min
        };
    };
}

function makeInequalitySettings(operation) {
    return function(value) {
        value = coerceValue(operation, value);

        return {
            start: value,
            end: Infinity,
            size: Infinity
        };
    };
}

},{"../../constants/filter_ops":667,"fast-isnumeric":215}],922:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function handleContourDefaults(traceIn, traceOut, coerce, coerce2) {
    var contourStart = coerce2('contours.start');
    var contourEnd = coerce2('contours.end');
    var missingEnd = (contourStart === false) || (contourEnd === false);

    // normally we only need size if autocontour is off. But contour.calc
    // pushes its calculated contour size back to the input trace, so for
    // things like restyle that can call supplyDefaults without calc
    // after the initial draw, we can just reuse the previous calculation
    var contourSize = coerce('contours.size');
    var autoContour;

    if(missingEnd) autoContour = traceOut.autocontour = true;
    else autoContour = coerce('autocontour', false);

    if(autoContour || !contourSize) coerce('ncontours');
};

},{}],923:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

// The contour extraction is great, except it totally fails for constraints because we
// need weird range loops and flipped contours instead of the usual format. This function
// does some weird manipulation of the extracted pathinfo data such that it magically
// draws contours correctly *as* constraints.
module.exports = function(pathinfo, operation) {
    var i, pi0, pi1;

    var op0 = function(arr) { return arr.reverse(); };
    var op1 = function(arr) { return arr; };

    switch(operation) {
        case '=':
        case '<':
            return pathinfo;
        case '>':
            if(pathinfo.length !== 1) {
                Lib.warn('Contour data invalid for the specified inequality operation.');
            }

            // In this case there should be exactly two contour levels in pathinfo. We
            // simply concatenate the info into one pathinfo and flip all of the data
            // in one. This will draw the contour as closed.
            pi0 = pathinfo[0];

            for(i = 0; i < pi0.edgepaths.length; i++) {
                pi0.edgepaths[i] = op0(pi0.edgepaths[i]);
            }

            for(i = 0; i < pi0.paths.length; i++) {
                pi0.paths[i] = op0(pi0.paths[i]);
            }
            return pathinfo;
        case '][':
            var tmp = op0;
            op0 = op1;
            op1 = tmp;
            // It's a nice rule, except this definitely *is* what's intended here.
            /* eslint-disable: no-fallthrough */
        case '[]':
            /* eslint-enable: no-fallthrough */
            if(pathinfo.length !== 2) {
                Lib.warn('Contour data invalid for the specified inequality range operation.');
            }

            // In this case there should be exactly two contour levels in pathinfo. We
            // simply concatenate the info into one pathinfo and flip all of the data
            // in one. This will draw the contour as closed.
            pi0 = copyPathinfo(pathinfo[0]);
            pi1 = copyPathinfo(pathinfo[1]);

            for(i = 0; i < pi0.edgepaths.length; i++) {
                pi0.edgepaths[i] = op0(pi0.edgepaths[i]);
            }

            for(i = 0; i < pi0.paths.length; i++) {
                pi0.paths[i] = op0(pi0.paths[i]);
            }

            while(pi1.edgepaths.length) {
                pi0.edgepaths.push(op1(pi1.edgepaths.shift()));
            }
            while(pi1.paths.length) {
                pi0.paths.push(op1(pi1.paths.shift()));
            }
            return [pi0];
    }
};

function copyPathinfo(pi) {
    return Lib.extendFlat({}, pi, {
        edgepaths: Lib.extendDeep([], pi.edgepaths),
        paths: Lib.extendDeep([], pi.paths)
    });
}

},{"../../lib":694}],924:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

var handleXYZDefaults = _dereq_('../heatmap/xyz_defaults');
var handleConstraintDefaults = _dereq_('./constraint_defaults');
var handleContoursDefaults = _dereq_('./contours_defaults');
var handleStyleDefaults = _dereq_('./style_defaults');
var attributes = _dereq_('./attributes');


module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    function coerce2(attr) {
        return Lib.coerce2(traceIn, traceOut, attributes, attr);
    }

    var len = handleXYZDefaults(traceIn, traceOut, coerce, layout);
    if(!len) {
        traceOut.visible = false;
        return;
    }

    coerce('text');
    var isConstraint = (coerce('contours.type') === 'constraint');
    coerce('connectgaps', Lib.isArray1D(traceOut.z));

    if(isConstraint) {
        handleConstraintDefaults(traceIn, traceOut, coerce, layout, defaultColor);
    }
    else {
        handleContoursDefaults(traceIn, traceOut, coerce, coerce2);
        handleStyleDefaults(traceIn, traceOut, coerce, layout);
    }
};

},{"../../lib":694,"../heatmap/xyz_defaults":958,"./attributes":915,"./constraint_defaults":920,"./contours_defaults":922,"./style_defaults":936}],925:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var constraintMapping = _dereq_('./constraint_mapping');
var endPlus = _dereq_('./end_plus');

module.exports = function emptyPathinfo(contours, plotinfo, cd0) {
    var contoursFinal = (contours.type === 'constraint') ?
        constraintMapping[contours._operation](contours.value) :
        contours;

    var cs = contoursFinal.size;
    var pathinfo = [];
    var end = endPlus(contoursFinal);

    var carpet = cd0.trace._carpetTrace;

    var basePathinfo = carpet ? {
        // store axes so we can convert to px
        xaxis: carpet.aaxis,
        yaxis: carpet.baxis,
        // full data arrays to use for interpolation
        x: cd0.a,
        y: cd0.b
    } : {
        xaxis: plotinfo.xaxis,
        yaxis: plotinfo.yaxis,
        x: cd0.x,
        y: cd0.y
    };

    for(var ci = contoursFinal.start; ci < end; ci += cs) {
        pathinfo.push(Lib.extendFlat({
            level: ci,
            // all the cells with nontrivial marching index
            crossings: {},
            // starting points on the edges of the lattice for each contour
            starts: [],
            // all unclosed paths (may have less items than starts,
            // if a path is closed by rounding)
            edgepaths: [],
            // all closed paths
            paths: [],
            z: cd0.z,
            smoothing: cd0.trace.line.smoothing
        }, basePathinfo));

        if(pathinfo.length > 1000) {
            Lib.warn('Too many contours, clipping at 1000', contours);
            break;
        }
    }
    return pathinfo;
};

},{"../../lib":694,"./constraint_mapping":921,"./end_plus":926}],926:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

/*
 * tiny helper to move the end of the contours a little to prevent
 * losing the last contour to rounding errors
 */
module.exports = function endPlus(contours) {
    return contours.end + contours.size / 1e6;
};

},{}],927:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var constants = _dereq_('./constants');

module.exports = function findAllPaths(pathinfo, xtol, ytol) {
    var cnt,
        startLoc,
        i,
        pi,
        j;

    // Default just passes these values through as they were before:
    xtol = xtol || 0.01;
    ytol = ytol || 0.01;

    for(i = 0; i < pathinfo.length; i++) {
        pi = pathinfo[i];

        for(j = 0; j < pi.starts.length; j++) {
            startLoc = pi.starts[j];
            makePath(pi, startLoc, 'edge', xtol, ytol);
        }

        cnt = 0;
        while(Object.keys(pi.crossings).length && cnt < 10000) {
            cnt++;
            startLoc = Object.keys(pi.crossings)[0].split(',').map(Number);
            makePath(pi, startLoc, undefined, xtol, ytol);
        }
        if(cnt === 10000) Lib.log('Infinite loop in contour?');
    }
};

function equalPts(pt1, pt2, xtol, ytol) {
    return Math.abs(pt1[0] - pt2[0]) < xtol &&
           Math.abs(pt1[1] - pt2[1]) < ytol;
}

// distance in index units - uses the 3rd and 4th items in points
function ptDist(pt1, pt2) {
    var dx = pt1[2] - pt2[2];
    var dy = pt1[3] - pt2[3];
    return Math.sqrt(dx * dx + dy * dy);
}

function makePath(pi, loc, edgeflag, xtol, ytol) {
    var startLocStr = loc.join(',');
    var locStr = startLocStr;
    var mi = pi.crossings[locStr];
    var marchStep = startStep(mi, edgeflag, loc);
    // start by going backward a half step and finding the crossing point
    var pts = [getInterpPx(pi, loc, [-marchStep[0], -marchStep[1]])];
    var startStepStr = marchStep.join(',');
    var m = pi.z.length;
    var n = pi.z[0].length;
    var cnt;

    // now follow the path
    for(cnt = 0; cnt < 10000; cnt++) { // just to avoid infinite loops
        if(mi > 20) {
            mi = constants.CHOOSESADDLE[mi][(marchStep[0] || marchStep[1]) < 0 ? 0 : 1];
            pi.crossings[locStr] = constants.SADDLEREMAINDER[mi];
        }
        else {
            delete pi.crossings[locStr];
        }

        marchStep = constants.NEWDELTA[mi];
        if(!marchStep) {
            Lib.log('Found bad marching index:', mi, loc, pi.level);
            break;
        }

        // find the crossing a half step forward, and then take the full step
        pts.push(getInterpPx(pi, loc, marchStep));
        loc[0] += marchStep[0];
        loc[1] += marchStep[1];

        // don't include the same point multiple times
        if(equalPts(pts[pts.length - 1], pts[pts.length - 2], xtol, ytol)) pts.pop();
        locStr = loc.join(',');

        var atEdge = (marchStep[0] && (loc[0] < 0 || loc[0] > n - 2)) ||
                (marchStep[1] && (loc[1] < 0 || loc[1] > m - 2));
        var closedLoop = (locStr === startLocStr) && (marchStep.join(',') === startStepStr);

        // have we completed a loop, or reached an edge?
        if((closedLoop) || (edgeflag && atEdge)) break;

        mi = pi.crossings[locStr];
    }

    if(cnt === 10000) {
        Lib.log('Infinite loop in contour?');
    }
    var closedpath = equalPts(pts[0], pts[pts.length - 1], xtol, ytol);
    var totaldist = 0;
    var distThresholdFactor = 0.2 * pi.smoothing;
    var alldists = [];
    var cropstart = 0;
    var distgroup, cnt2, cnt3, newpt, ptcnt, ptavg, thisdist,
        i, j, edgepathi, edgepathj;

    /*
     * Check for points that are too close together (<1/5 the average dist
     * *in grid index units* (important for log axes and nonuniform grids),
     * less if less smoothed) and just take the center (or avg of center 2).
     * This cuts down on funny behavior when a point is very close to a
     * contour level.
     */
    for(cnt = 1; cnt < pts.length; cnt++) {
        thisdist = ptDist(pts[cnt], pts[cnt - 1]);
        totaldist += thisdist;
        alldists.push(thisdist);
    }

    var distThreshold = totaldist / alldists.length * distThresholdFactor;

    function getpt(i) { return pts[i % pts.length]; }

    for(cnt = pts.length - 2; cnt >= cropstart; cnt--) {
        distgroup = alldists[cnt];
        if(distgroup < distThreshold) {
            cnt3 = 0;
            for(cnt2 = cnt - 1; cnt2 >= cropstart; cnt2--) {
                if(distgroup + alldists[cnt2] < distThreshold) {
                    distgroup += alldists[cnt2];
                }
                else break;
            }

            // closed path with close points wrapping around the boundary?
            if(closedpath && cnt === pts.length - 2) {
                for(cnt3 = 0; cnt3 < cnt2; cnt3++) {
                    if(distgroup + alldists[cnt3] < distThreshold) {
                        distgroup += alldists[cnt3];
                    }
                    else break;
                }
            }
            ptcnt = cnt - cnt2 + cnt3 + 1;
            ptavg = Math.floor((cnt + cnt2 + cnt3 + 2) / 2);

            // either endpoint included: keep the endpoint
            if(!closedpath && cnt === pts.length - 2) newpt = pts[pts.length - 1];
            else if(!closedpath && cnt2 === -1) newpt = pts[0];

            // odd # of points - just take the central one
            else if(ptcnt % 2) newpt = getpt(ptavg);

            // even # of pts - average central two
            else {
                newpt = [(getpt(ptavg)[0] + getpt(ptavg + 1)[0]) / 2,
                    (getpt(ptavg)[1] + getpt(ptavg + 1)[1]) / 2];
            }

            pts.splice(cnt2 + 1, cnt - cnt2 + 1, newpt);
            cnt = cnt2 + 1;
            if(cnt3) cropstart = cnt3;
            if(closedpath) {
                if(cnt === pts.length - 2) pts[cnt3] = pts[pts.length - 1];
                else if(cnt === 0) pts[pts.length - 1] = pts[0];
            }
        }
    }
    pts.splice(0, cropstart);

    // done with the index parts - remove them so path generation works right
    // because it depends on only having [xpx, ypx]
    for(cnt = 0; cnt < pts.length; cnt++) pts[cnt].length = 2;

    // don't return single-point paths (ie all points were the same
    // so they got deleted?)
    if(pts.length < 2) return;
    else if(closedpath) {
        pts.pop();
        pi.paths.push(pts);
    }
    else {
        if(!edgeflag) {
            Lib.log('Unclosed interior contour?',
                pi.level, startLocStr, pts.join('L'));
        }

        // edge path - does it start where an existing edge path ends, or vice versa?
        var merged = false;
        for(i = 0; i < pi.edgepaths.length; i++) {
            edgepathi = pi.edgepaths[i];
            if(!merged && equalPts(edgepathi[0], pts[pts.length - 1], xtol, ytol)) {
                pts.pop();
                merged = true;

                // now does it ALSO meet the end of another (or the same) path?
                var doublemerged = false;
                for(j = 0; j < pi.edgepaths.length; j++) {
                    edgepathj = pi.edgepaths[j];
                    if(equalPts(edgepathj[edgepathj.length - 1], pts[0], xtol, ytol)) {
                        doublemerged = true;
                        pts.shift();
                        pi.edgepaths.splice(i, 1);
                        if(j === i) {
                            // the path is now closed
                            pi.paths.push(pts.concat(edgepathj));
                        }
                        else {
                            if(j > i) j--;
                            pi.edgepaths[j] = edgepathj.concat(pts, edgepathi);
                        }
                        break;
                    }
                }
                if(!doublemerged) {
                    pi.edgepaths[i] = pts.concat(edgepathi);
                }
            }
        }
        for(i = 0; i < pi.edgepaths.length; i++) {
            if(merged) break;
            edgepathi = pi.edgepaths[i];
            if(equalPts(edgepathi[edgepathi.length - 1], pts[0], xtol, ytol)) {
                pts.shift();
                pi.edgepaths[i] = edgepathi.concat(pts);
                merged = true;
            }
        }

        if(!merged) pi.edgepaths.push(pts);
    }
}

// special function to get the marching step of the
// first point in the path (leading to loc)
function startStep(mi, edgeflag, loc) {
    var dx = 0;
    var dy = 0;
    if(mi > 20 && edgeflag) {
        // these saddles start at +/- x
        if(mi === 208 || mi === 1114) {
            // if we're starting at the left side, we must be going right
            dx = loc[0] === 0 ? 1 : -1;
        }
        else {
            // if we're starting at the bottom, we must be going up
            dy = loc[1] === 0 ? 1 : -1;
        }
    }
    else if(constants.BOTTOMSTART.indexOf(mi) !== -1) dy = 1;
    else if(constants.LEFTSTART.indexOf(mi) !== -1) dx = 1;
    else if(constants.TOPSTART.indexOf(mi) !== -1) dy = -1;
    else dx = -1;
    return [dx, dy];
}

/*
 * Find the pixel coordinates of a particular crossing
 *
 * @param {object} pi: the pathinfo object at this level
 * @param {array} loc: the grid index [x, y] of the crossing
 * @param {array} step: the direction [dx, dy] we're moving on the grid
 *
 * @return {array} [xpx, ypx, xi, yi]: the first two are the pixel location,
 *   the next two are the interpolated grid indices, which we use for
 *   distance calculations to delete points that are too close together.
 *   This is important when the grid is nonuniform (and most dramatically when
 *   we're on log axes and include invalid (0 or negative) values.
 *   It's crucial to delete these extra two before turning an array of these
 *   points into a path, because those routines require length-2 points.
 */
function getInterpPx(pi, loc, step) {
    var locx = loc[0] + Math.max(step[0], 0);
    var locy = loc[1] + Math.max(step[1], 0);
    var zxy = pi.z[locy][locx];
    var xa = pi.xaxis;
    var ya = pi.yaxis;

    if(step[1]) {
        var dx = (pi.level - zxy) / (pi.z[locy][locx + 1] - zxy);

        return [xa.c2p((1 - dx) * pi.x[locx] + dx * pi.x[locx + 1], true),
            ya.c2p(pi.y[locy], true),
            locx + dx, locy];
    }
    else {
        var dy = (pi.level - zxy) / (pi.z[locy + 1][locx] - zxy);
        return [xa.c2p(pi.x[locx], true),
            ya.c2p((1 - dy) * pi.y[locy] + dy * pi.y[locy + 1], true),
            locx, locy + dy];
    }
}

},{"../../lib":694,"./constants":919}],928:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Color = _dereq_('../../components/color');

var heatmapHoverPoints = _dereq_('../heatmap/hover');

module.exports = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer) {
    var hoverData = heatmapHoverPoints(pointData, xval, yval, hovermode, hoverLayer, true);

    if(hoverData) {
        hoverData.forEach(function(hoverPt) {
            var trace = hoverPt.trace;
            if(trace.contours.type === 'constraint') {
                if(trace.fillcolor && Color.opacity(trace.fillcolor)) {
                    hoverPt.color = Color.addOpacity(trace.fillcolor, 1);
                }
                else if(trace.contours.showlines && Color.opacity(trace.line.color)) {
                    hoverPt.color = Color.addOpacity(trace.line.color, 1);
                }
            }
        });
    }

    return hoverData;
};

},{"../../components/color":571,"../heatmap/hover":951}],929:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Contour = {};

Contour.attributes = _dereq_('./attributes');
Contour.supplyDefaults = _dereq_('./defaults');
Contour.calc = _dereq_('./calc');
Contour.plot = _dereq_('./plot').plot;
Contour.style = _dereq_('./style');
Contour.colorbar = _dereq_('./colorbar');
Contour.hoverPoints = _dereq_('./hover');

Contour.moduleType = 'trace';
Contour.name = 'contour';
Contour.basePlotModule = _dereq_('../../plots/cartesian');
Contour.categories = ['cartesian', 'svg', '2dMap', 'contour', 'showLegend'];
Contour.meta = {
    
};

module.exports = Contour;

},{"../../plots/cartesian":754,"./attributes":915,"./calc":916,"./colorbar":918,"./defaults":924,"./hover":928,"./plot":933,"./style":935}],930:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

module.exports = function handleLabelDefaults(coerce, layout, lineColor, opts) {
    if(!opts) opts = {};
    var showLabels = coerce('contours.showlabels');
    if(showLabels) {
        var globalFont = layout.font;
        Lib.coerceFont(coerce, 'contours.labelfont', {
            family: globalFont.family,
            size: globalFont.size,
            color: lineColor
        });
        coerce('contours.labelformat');
    }

    if(opts.hasHover !== false) coerce('zhoverformat');
};

},{"../../lib":694}],931:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var Colorscale = _dereq_('../../components/colorscale');
var endPlus = _dereq_('./end_plus');

module.exports = function makeColorMap(trace) {
    var contours = trace.contours;
    var start = contours.start;
    var end = endPlus(contours);
    var cs = contours.size || 1;
    var nc = Math.floor((end - start) / cs) + 1;
    var extra = contours.coloring === 'lines' ? 0 : 1;

    if(!isFinite(cs)) {
        cs = 1;
        nc = 1;
    }

    var scl = trace.reversescale ?
        Colorscale.flipScale(trace.colorscale) :
        trace.colorscale;

    var len = scl.length;
    var domain = new Array(len);
    var range = new Array(len);

    var si, i;

    if(contours.coloring === 'heatmap') {
        if(trace.zauto && trace.autocontour === false) {
            trace.zmin = start - cs / 2;
            trace.zmax = trace.zmin + nc * cs;
        }

        for(i = 0; i < len; i++) {
            si = scl[i];

            domain[i] = si[0] * (trace.zmax - trace.zmin) + trace.zmin;
            range[i] = si[1];
        }

        // do the contours extend beyond the colorscale?
        // if so, extend the colorscale with constants
        var zRange = d3.extent([
            trace.zmin,
            trace.zmax,
            contours.start,
            contours.start + cs * (nc - 1)
        ]);
        var zmin = zRange[trace.zmin < trace.zmax ? 0 : 1];
        var zmax = zRange[trace.zmin < trace.zmax ? 1 : 0];

        if(zmin !== trace.zmin) {
            domain.splice(0, 0, zmin);
            range.splice(0, 0, Range[0]);
        }

        if(zmax !== trace.zmax) {
            domain.push(zmax);
            range.push(range[range.length - 1]);
        }
    }
    else {
        for(i = 0; i < len; i++) {
            si = scl[i];

            domain[i] = (si[0] * (nc + extra - 1) - (extra / 2)) * cs + start;
            range[i] = si[1];
        }
    }

    return Colorscale.makeColorScaleFunc({
        domain: domain,
        range: range,
    }, {
        noNumericCheck: true
    });
};

},{"../../components/colorscale":583,"./end_plus":926,"d3":149}],932:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var constants = _dereq_('./constants');

// Calculate all the marching indices, for ALL levels at once.
// since we want to be exhaustive we'll check for contour crossings
// at every intersection, rather than just following a path
// TODO: shorten the inner loop to only the relevant levels
module.exports = function makeCrossings(pathinfo) {
    var z = pathinfo[0].z;
    var m = z.length;
    var n = z[0].length; // we already made sure z isn't ragged in interp2d
    var twoWide = m === 2 || n === 2;
    var xi;
    var yi;
    var startIndices;
    var ystartIndices;
    var label;
    var corners;
    var mi;
    var pi;
    var i;

    for(yi = 0; yi < m - 1; yi++) {
        ystartIndices = [];
        if(yi === 0) ystartIndices = ystartIndices.concat(constants.BOTTOMSTART);
        if(yi === m - 2) ystartIndices = ystartIndices.concat(constants.TOPSTART);

        for(xi = 0; xi < n - 1; xi++) {
            startIndices = ystartIndices.slice();
            if(xi === 0) startIndices = startIndices.concat(constants.LEFTSTART);
            if(xi === n - 2) startIndices = startIndices.concat(constants.RIGHTSTART);

            label = xi + ',' + yi;
            corners = [[z[yi][xi], z[yi][xi + 1]],
                       [z[yi + 1][xi], z[yi + 1][xi + 1]]];
            for(i = 0; i < pathinfo.length; i++) {
                pi = pathinfo[i];
                mi = getMarchingIndex(pi.level, corners);
                if(!mi) continue;

                pi.crossings[label] = mi;
                if(startIndices.indexOf(mi) !== -1) {
                    pi.starts.push([xi, yi]);
                    if(twoWide && startIndices.indexOf(mi,
                            startIndices.indexOf(mi) + 1) !== -1) {
                        // the same square has starts from opposite sides
                        // it's not possible to have starts on opposite edges
                        // of a corner, only a start and an end...
                        // but if the array is only two points wide (either way)
                        // you can have starts on opposite sides.
                        pi.starts.push([xi, yi]);
                    }
                }
            }
        }
    }
};

// modified marching squares algorithm,
// so we disambiguate the saddle points from the start
// and we ignore the cases with no crossings
// the index I'm using is based on:
// http://en.wikipedia.org/wiki/Marching_squares
// except that the saddles bifurcate and I represent them
// as the decimal combination of the two appropriate
// non-saddle indices
function getMarchingIndex(val, corners) {
    var mi = (corners[0][0] > val ? 0 : 1) +
             (corners[0][1] > val ? 0 : 2) +
             (corners[1][1] > val ? 0 : 4) +
             (corners[1][0] > val ? 0 : 8);
    if(mi === 5 || mi === 10) {
        var avg = (corners[0][0] + corners[0][1] +
                   corners[1][0] + corners[1][1]) / 4;
        // two peaks with a big valley
        if(val > avg) return (mi === 5) ? 713 : 1114;
        // two valleys with a big ridge
        return (mi === 5) ? 104 : 208;
    }
    return (mi === 15) ? 0 : mi;
}

},{"./constants":919}],933:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

var Lib = _dereq_('../../lib');
var Drawing = _dereq_('../../components/drawing');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');
var Axes = _dereq_('../../plots/cartesian/axes');
var setConvert = _dereq_('../../plots/cartesian/set_convert');

var heatmapPlot = _dereq_('../heatmap/plot');
var makeCrossings = _dereq_('./make_crossings');
var findAllPaths = _dereq_('./find_all_paths');
var emptyPathinfo = _dereq_('./empty_pathinfo');
var convertToConstraints = _dereq_('./convert_to_constraints');
var closeBoundaries = _dereq_('./close_boundaries');
var constants = _dereq_('./constants');
var costConstants = constants.LABELOPTIMIZER;

exports.plot = function plot(gd, plotinfo, cdcontours, contourLayer) {
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    Lib.makeTraceGroups(contourLayer, cdcontours, 'contour').each(function(cd) {
        var plotGroup = d3.select(this);
        var cd0 = cd[0];
        var trace = cd0.trace;
        var x = cd0.x;
        var y = cd0.y;
        var contours = trace.contours;
        var pathinfo = emptyPathinfo(contours, plotinfo, cd0);

        // use a heatmap to fill - draw it behind the lines
        var heatmapColoringLayer = Lib.ensureSingle(plotGroup, 'g', 'heatmapcoloring');
        var cdheatmaps = [];
        if(contours.coloring === 'heatmap') {
            if(trace.zauto && (trace.autocontour === false)) {
                trace._input.zmin = trace.zmin =
                    contours.start - contours.size / 2;
                trace._input.zmax = trace.zmax =
                    trace.zmin + pathinfo.length * contours.size;
            }
            cdheatmaps = [cd];
        }
        heatmapPlot(gd, plotinfo, cdheatmaps, heatmapColoringLayer);

        makeCrossings(pathinfo);
        findAllPaths(pathinfo);

        var leftedge = xa.c2p(x[0], true);
        var rightedge = xa.c2p(x[x.length - 1], true);
        var bottomedge = ya.c2p(y[0], true);
        var topedge = ya.c2p(y[y.length - 1], true);
        var perimeter = [
            [leftedge, topedge],
            [rightedge, topedge],
            [rightedge, bottomedge],
            [leftedge, bottomedge]
        ];

        var fillPathinfo = pathinfo;
        if(contours.type === 'constraint') {
            fillPathinfo = convertToConstraints(pathinfo, contours._operation);
            closeBoundaries(fillPathinfo, contours._operation, perimeter, trace);
        }

        // draw everything
        makeBackground(plotGroup, perimeter, contours);
        makeFills(plotGroup, fillPathinfo, perimeter, contours);
        makeLinesAndLabels(plotGroup, pathinfo, gd, cd0, contours, perimeter);
        clipGaps(plotGroup, plotinfo, gd, cd0, perimeter);
    });
};

function makeBackground(plotgroup, perimeter, contours) {
    var bggroup = Lib.ensureSingle(plotgroup, 'g', 'contourbg');

    var bgfill = bggroup.selectAll('path')
        .data(contours.coloring === 'fill' ? [0] : []);
    bgfill.enter().append('path');
    bgfill.exit().remove();
    bgfill
        .attr('d', 'M' + perimeter.join('L') + 'Z')
        .style('stroke', 'none');
}

function makeFills(plotgroup, pathinfo, perimeter, contours) {
    var fillgroup = Lib.ensureSingle(plotgroup, 'g', 'contourfill');

    var fillitems = fillgroup.selectAll('path')
        .data(contours.coloring === 'fill' || (contours.type === 'constraint' && contours._operation !== '=') ? pathinfo : []);
    fillitems.enter().append('path');
    fillitems.exit().remove();
    fillitems.each(function(pi) {
        // join all paths for this level together into a single path
        // first follow clockwise around the perimeter to close any open paths
        // if the whole perimeter is above this level, start with a path
        // enclosing the whole thing. With all that, the parity should mean
        // that we always fill everything above the contour, nothing below
        var fullpath = joinAllPaths(pi, perimeter);

        if(!fullpath) d3.select(this).remove();
        else d3.select(this).attr('d', fullpath).style('stroke', 'none');
    });
}

function initFullPath(pi, perimeter) {
    var prefixBoundary = pi.prefixBoundary;
    if(prefixBoundary === undefined) {
        var edgeVal2 = Math.min(pi.z[0][0], pi.z[0][1]);
        prefixBoundary = (!pi.edgepaths.length && edgeVal2 > pi.level);
    }

    if(prefixBoundary) {
        // TODO: why does ^^ not work for constraints?
        // pi.prefixBoundary gets set by closeBoundaries
        return 'M' + perimeter.join('L') + 'Z';
    }
    return '';
}

function joinAllPaths(pi, perimeter) {
    var fullpath = initFullPath(pi, perimeter);
    var i = 0;
    var startsleft = pi.edgepaths.map(function(v, i) { return i; });
    var newloop = true;
    var endpt;
    var newendpt;
    var cnt;
    var nexti;
    var possiblei;
    var addpath;

    function istop(pt) { return Math.abs(pt[1] - perimeter[0][1]) < 0.01; }
    function isbottom(pt) { return Math.abs(pt[1] - perimeter[2][1]) < 0.01; }
    function isleft(pt) { return Math.abs(pt[0] - perimeter[0][0]) < 0.01; }
    function isright(pt) { return Math.abs(pt[0] - perimeter[2][0]) < 0.01; }

    while(startsleft.length) {
        addpath = Drawing.smoothopen(pi.edgepaths[i], pi.smoothing);
        fullpath += newloop ? addpath : addpath.replace(/^M/, 'L');
        startsleft.splice(startsleft.indexOf(i), 1);
        endpt = pi.edgepaths[i][pi.edgepaths[i].length - 1];
        nexti = -1;

        // now loop through sides, moving our endpoint until we find a new start
        for(cnt = 0; cnt < 4; cnt++) { // just to prevent infinite loops
            if(!endpt) {
                Lib.log('Missing end?', i, pi);
                break;
            }

            if(istop(endpt) && !isright(endpt)) newendpt = perimeter[1]; // right top
            else if(isleft(endpt)) newendpt = perimeter[0]; // left top
            else if(isbottom(endpt)) newendpt = perimeter[3]; // right bottom
            else if(isright(endpt)) newendpt = perimeter[2]; // left bottom

            for(possiblei = 0; possiblei < pi.edgepaths.length; possiblei++) {
                var ptNew = pi.edgepaths[possiblei][0];
                // is ptNew on the (horz. or vert.) segment from endpt to newendpt?
                if(Math.abs(endpt[0] - newendpt[0]) < 0.01) {
                    if(Math.abs(endpt[0] - ptNew[0]) < 0.01 &&
                            (ptNew[1] - endpt[1]) * (newendpt[1] - ptNew[1]) >= 0) {
                        newendpt = ptNew;
                        nexti = possiblei;
                    }
                }
                else if(Math.abs(endpt[1] - newendpt[1]) < 0.01) {
                    if(Math.abs(endpt[1] - ptNew[1]) < 0.01 &&
                            (ptNew[0] - endpt[0]) * (newendpt[0] - ptNew[0]) >= 0) {
                        newendpt = ptNew;
                        nexti = possiblei;
                    }
                }
                else {
                    Lib.log('endpt to newendpt is not vert. or horz.',
                        endpt, newendpt, ptNew);
                }
            }

            endpt = newendpt;

            if(nexti >= 0) break;
            fullpath += 'L' + newendpt;
        }

        if(nexti === pi.edgepaths.length) {
            Lib.log('unclosed perimeter path');
            break;
        }

        i = nexti;

        // if we closed back on a loop we already included,
        // close it and start a new loop
        newloop = (startsleft.indexOf(i) === -1);
        if(newloop) {
            i = startsleft[0];
            fullpath += 'Z';
        }
    }

    // finally add the interior paths
    for(i = 0; i < pi.paths.length; i++) {
        fullpath += Drawing.smoothclosed(pi.paths[i], pi.smoothing);
    }

    return fullpath;
}

function makeLinesAndLabels(plotgroup, pathinfo, gd, cd0, contours, perimeter) {
    var lineContainer = Lib.ensureSingle(plotgroup, 'g', 'contourlines');
    var showLines = contours.showlines !== false;
    var showLabels = contours.showlabels;
    var clipLinesForLabels = showLines && showLabels;

    // Even if we're not going to show lines, we need to create them
    // if we're showing labels, because the fill paths include the perimeter
    // so can't be used to position the labels correctly.
    // In this case we'll remove the lines after making the labels.
    var linegroup = exports.createLines(lineContainer, showLines || showLabels, pathinfo);

    var lineClip = exports.createLineClip(lineContainer, clipLinesForLabels, gd, cd0.trace.uid);

    var labelGroup = plotgroup.selectAll('g.contourlabels')
        .data(showLabels ? [0] : []);

    labelGroup.exit().remove();

    labelGroup.enter().append('g')
        .classed('contourlabels', true);

    if(showLabels) {
        var labelClipPathData = [];
        var labelData = [];

        // invalidate the getTextLocation cache in case paths changed
        Lib.clearLocationCache();

        var contourFormat = exports.labelFormatter(contours, cd0.t.cb, gd._fullLayout);

        var dummyText = Drawing.tester.append('text')
            .attr('data-notex', 1)
            .call(Drawing.font, contours.labelfont);

        var xa = pathinfo[0].xaxis;
        var ya = pathinfo[0].yaxis;
        var xLen = xa._length;
        var yLen = ya._length;
        var xRng = xa.range;
        var yRng = ya.range;
        var x0 = Math.max(perimeter[0][0], 0);
        var x1 = Math.min(perimeter[2][0], xLen);
        var y0 = Math.max(perimeter[0][1], 0);
        var y1 = Math.min(perimeter[2][1], yLen);

        // visible bounds of the contour trace (and the midpoints, to
        // help with cost calculations)
        var bounds = {};

        if(xRng[0] < xRng[1]) {
            bounds.left = x0;
            bounds.right = x1;
        } else {
            bounds.left = x1;
            bounds.right = x0;
        }

        if(yRng[0] < yRng[1]) {
            bounds.top = y0;
            bounds.bottom = y1;
        } else {
            bounds.top = y1;
            bounds.bottom = y0;
        }

        bounds.middle = (bounds.top + bounds.bottom) / 2;
        bounds.center = (bounds.left + bounds.right) / 2;

        labelClipPathData.push([
            [bounds.left, bounds.top],
            [bounds.right, bounds.top],
            [bounds.right, bounds.bottom],
            [bounds.left, bounds.bottom]
        ]);

        var plotDiagonal = Math.sqrt(xLen * xLen + yLen * yLen);

        // the path length to use to scale the number of labels to draw:
        var normLength = constants.LABELDISTANCE * plotDiagonal /
            Math.max(1, pathinfo.length / constants.LABELINCREASE);

        linegroup.each(function(d) {
            var textOpts = exports.calcTextOpts(d.level, contourFormat, dummyText, gd);

            d3.select(this).selectAll('path').each(function() {
                var path = this;
                var pathBounds = Lib.getVisibleSegment(path, bounds, textOpts.height / 2);
                if(!pathBounds) return;

                if(pathBounds.len < (textOpts.width + textOpts.height) * constants.LABELMIN) return;

                var maxLabels = Math.min(Math.ceil(pathBounds.len / normLength),
                    constants.LABELMAX);

                for(var i = 0; i < maxLabels; i++) {
                    var loc = exports.findBestTextLocation(path, pathBounds, textOpts,
                        labelData, bounds);

                    if(!loc) break;

                    exports.addLabelData(loc, textOpts, labelData, labelClipPathData);
                }
            });
        });

        dummyText.remove();

        exports.drawLabels(labelGroup, labelData, gd, lineClip,
            clipLinesForLabels ? labelClipPathData : null);
    }

    if(showLabels && !showLines) linegroup.remove();
}

exports.createLines = function(lineContainer, makeLines, pathinfo) {
    var smoothing = pathinfo[0].smoothing;

    var linegroup = lineContainer.selectAll('g.contourlevel')
        .data(makeLines ? pathinfo : []);

    linegroup.exit().remove();
    linegroup.enter().append('g')
        .classed('contourlevel', true);

    if(makeLines) {
        // pedgepaths / ppaths are used by contourcarpet, for the paths transformed from a/b to x/y
        // edgepaths / paths are used by contour since it's in x/y from the start
        var opencontourlines = linegroup.selectAll('path.openline')
            .data(function(d) { return d.pedgepaths || d.edgepaths; });

        opencontourlines.exit().remove();
        opencontourlines.enter().append('path')
            .classed('openline', true);

        opencontourlines
            .attr('d', function(d) {
                return Drawing.smoothopen(d, smoothing);
            })
            .style('stroke-miterlimit', 1)
            .style('vector-effect', 'non-scaling-stroke');

        var closedcontourlines = linegroup.selectAll('path.closedline')
            .data(function(d) { return d.ppaths || d.paths; });

        closedcontourlines.exit().remove();
        closedcontourlines.enter().append('path')
            .classed('closedline', true);

        closedcontourlines
            .attr('d', function(d) {
                return Drawing.smoothclosed(d, smoothing);
            })
            .style('stroke-miterlimit', 1)
            .style('vector-effect', 'non-scaling-stroke');
    }

    return linegroup;
};

exports.createLineClip = function(lineContainer, clipLinesForLabels, gd, uid) {
    var clips = gd._fullLayout._clips;
    var clipId = clipLinesForLabels ? ('clipline' + uid) : null;

    var lineClip = clips.selectAll('#' + clipId)
        .data(clipLinesForLabels ? [0] : []);
    lineClip.exit().remove();

    lineClip.enter().append('clipPath')
        .classed('contourlineclip', true)
        .attr('id', clipId);

    Drawing.setClipUrl(lineContainer, clipId, gd);

    return lineClip;
};

exports.labelFormatter = function(contours, colorbar, fullLayout) {
    if(contours.labelformat) {
        return fullLayout._d3locale.numberFormat(contours.labelformat);
    }
    else {
        var formatAxis;
        if(colorbar) {
            formatAxis = colorbar.axis;
        }
        else {
            formatAxis = {
                type: 'linear',
                _id: 'ycontour',
                showexponent: 'all',
                exponentformat: 'B'
            };

            if(contours.type === 'constraint') {
                var value = contours.value;
                if(Array.isArray(value)) {
                    formatAxis.range = [value[0], value[value.length - 1]];
                }
                else formatAxis.range = [value, value];
            }
            else {
                formatAxis.range = [contours.start, contours.end];
                formatAxis.nticks = (contours.end - contours.start) / contours.size;
            }

            if(formatAxis.range[0] === formatAxis.range[1]) {
                formatAxis.range[1] += formatAxis.range[0] || 1;
            }
            if(!formatAxis.nticks) formatAxis.nticks = 1000;

            setConvert(formatAxis, fullLayout);
            Axes.prepTicks(formatAxis);
            formatAxis._tmin = null;
            formatAxis._tmax = null;
        }
        return function(v) {
            return Axes.tickText(formatAxis, v).text;
        };
    }
};

exports.calcTextOpts = function(level, contourFormat, dummyText, gd) {
    var text = contourFormat(level);
    dummyText.text(text)
        .call(svgTextUtils.convertToTspans, gd);
    var bBox = Drawing.bBox(dummyText.node(), true);

    return {
        text: text,
        width: bBox.width,
        height: bBox.height,
        level: level,
        dy: (bBox.top + bBox.bottom) / 2
    };
};

exports.findBestTextLocation = function(path, pathBounds, textOpts, labelData, plotBounds) {
    var textWidth = textOpts.width;

    var p0, dp, pMax, pMin, loc;
    if(pathBounds.isClosed) {
        dp = pathBounds.len / costConstants.INITIALSEARCHPOINTS;
        p0 = pathBounds.min + dp / 2;
        pMax = pathBounds.max;
    }
    else {
        dp = (pathBounds.len - textWidth) / (costConstants.INITIALSEARCHPOINTS + 1);
        p0 = pathBounds.min + dp + textWidth / 2;
        pMax = pathBounds.max - (dp + textWidth) / 2;
    }

    var cost = Infinity;
    for(var j = 0; j < costConstants.ITERATIONS; j++) {
        for(var p = p0; p < pMax; p += dp) {
            var newLocation = Lib.getTextLocation(path, pathBounds.total, p, textWidth);
            var newCost = locationCost(newLocation, textOpts, labelData, plotBounds);
            if(newCost < cost) {
                cost = newCost;
                loc = newLocation;
                pMin = p;
            }
        }
        if(cost > costConstants.MAXCOST * 2) break;

        // subsequent iterations just look half steps away from the
        // best we found in the previous iteration
        if(j) dp /= 2;
        p0 = pMin - dp / 2;
        pMax = p0 + dp * 1.5;
    }
    if(cost <= costConstants.MAXCOST) return loc;
};

/*
 * locationCost: a cost function for label locations
 * composed of three kinds of penalty:
 * - for open paths, being close to the end of the path
 * - the angle away from horizontal
 * - being too close to already placed neighbors
 */
function locationCost(loc, textOpts, labelData, bounds) {
    var halfWidth = textOpts.width / 2;
    var halfHeight = textOpts.height / 2;
    var x = loc.x;
    var y = loc.y;
    var theta = loc.theta;
    var dx = Math.cos(theta) * halfWidth;
    var dy = Math.sin(theta) * halfWidth;

    // cost for being near an edge
    var normX = ((x > bounds.center) ? (bounds.right - x) : (x - bounds.left)) /
        (dx + Math.abs(Math.sin(theta) * halfHeight));
    var normY = ((y > bounds.middle) ? (bounds.bottom - y) : (y - bounds.top)) /
        (Math.abs(dy) + Math.cos(theta) * halfHeight);
    if(normX < 1 || normY < 1) return Infinity;
    var cost = costConstants.EDGECOST * (1 / (normX - 1) + 1 / (normY - 1));

    // cost for not being horizontal
    cost += costConstants.ANGLECOST * theta * theta;

    // cost for being close to other labels
    var x1 = x - dx;
    var y1 = y - dy;
    var x2 = x + dx;
    var y2 = y + dy;
    for(var i = 0; i < labelData.length; i++) {
        var labeli = labelData[i];
        var dxd = Math.cos(labeli.theta) * labeli.width / 2;
        var dyd = Math.sin(labeli.theta) * labeli.width / 2;
        var dist = Lib.segmentDistance(
            x1, y1,
            x2, y2,
            labeli.x - dxd, labeli.y - dyd,
            labeli.x + dxd, labeli.y + dyd
        ) * 2 / (textOpts.height + labeli.height);

        var sameLevel = labeli.level === textOpts.level;
        var distOffset = sameLevel ? costConstants.SAMELEVELDISTANCE : 1;

        if(dist <= distOffset) return Infinity;

        var distFactor = costConstants.NEIGHBORCOST *
            (sameLevel ? costConstants.SAMELEVELFACTOR : 1);

        cost += distFactor / (dist - distOffset);
    }

    return cost;
}

exports.addLabelData = function(loc, textOpts, labelData, labelClipPathData) {
    var halfWidth = textOpts.width / 2;
    var halfHeight = textOpts.height / 2;

    var x = loc.x;
    var y = loc.y;
    var theta = loc.theta;

    var sin = Math.sin(theta);
    var cos = Math.cos(theta);
    var dxw = halfWidth * cos;
    var dxh = halfHeight * sin;
    var dyw = halfWidth * sin;
    var dyh = -halfHeight * cos;
    var bBoxPts = [
        [x - dxw - dxh, y - dyw - dyh],
        [x + dxw - dxh, y + dyw - dyh],
        [x + dxw + dxh, y + dyw + dyh],
        [x - dxw + dxh, y - dyw + dyh],
    ];

    labelData.push({
        text: textOpts.text,
        x: x,
        y: y,
        dy: textOpts.dy,
        theta: theta,
        level: textOpts.level,
        width: textOpts.width,
        height: textOpts.height
    });

    labelClipPathData.push(bBoxPts);
};

exports.drawLabels = function(labelGroup, labelData, gd, lineClip, labelClipPathData) {
    var labels = labelGroup.selectAll('text')
        .data(labelData, function(d) {
            return d.text + ',' + d.x + ',' + d.y + ',' + d.theta;
        });

    labels.exit().remove();

    labels.enter().append('text')
        .attr({
            'data-notex': 1,
            'text-anchor': 'middle'
        })
        .each(function(d) {
            var x = d.x + Math.sin(d.theta) * d.dy;
            var y = d.y - Math.cos(d.theta) * d.dy;
            d3.select(this)
                .text(d.text)
                .attr({
                    x: x,
                    y: y,
                    transform: 'rotate(' + (180 * d.theta / Math.PI) + ' ' + x + ' ' + y + ')'
                })
                .call(svgTextUtils.convertToTspans, gd);
        });

    if(labelClipPathData) {
        var clipPath = '';
        for(var i = 0; i < labelClipPathData.length; i++) {
            clipPath += 'M' + labelClipPathData[i].join('L') + 'Z';
        }

        var lineClipPath = Lib.ensureSingle(lineClip, 'path', '');
        lineClipPath.attr('d', clipPath);
    }
};

function clipGaps(plotGroup, plotinfo, gd, cd0, perimeter) {
    var clips = gd._fullLayout._clips;
    var clipId = 'clip' + cd0.trace.uid;

    var clipPath = clips.selectAll('#' + clipId)
        .data(cd0.trace.connectgaps ? [] : [0]);
    clipPath.enter().append('clipPath')
        .classed('contourclip', true)
        .attr('id', clipId);
    clipPath.exit().remove();

    if(cd0.trace.connectgaps === false) {
        var clipPathInfo = {
            // fraction of the way from missing to present point
            // to draw the boundary.
            // if you make this 1 (or 1-epsilon) then a point in
            // a sea of missing data will disappear entirely.
            level: 0.9,
            crossings: {},
            starts: [],
            edgepaths: [],
            paths: [],
            xaxis: plotinfo.xaxis,
            yaxis: plotinfo.yaxis,
            x: cd0.x,
            y: cd0.y,
            // 0 = no data, 1 = data
            z: makeClipMask(cd0),
            smoothing: 0
        };

        makeCrossings([clipPathInfo]);
        findAllPaths([clipPathInfo]);
        var fullpath = joinAllPaths(clipPathInfo, perimeter);

        var path = Lib.ensureSingle(clipPath, 'path', '');
        path.attr('d', fullpath);
    }
    else clipId = null;

    Drawing.setClipUrl(plotGroup, clipId, gd);
}

function makeClipMask(cd0) {
    var empties = cd0.trace._emptypoints;
    var z = [];
    var m = cd0.z.length;
    var n = cd0.z[0].length;
    var i;
    var row = [];
    var emptyPoint;

    for(i = 0; i < n; i++) row.push(1);
    for(i = 0; i < m; i++) z.push(row.slice());
    for(i = 0; i < empties.length; i++) {
        emptyPoint = empties[i];
        z[emptyPoint[0]][emptyPoint[1]] = 0;
    }
    // save this mask to determine whether to show this data in hover
    cd0.zmask = z;
    return z;
}

},{"../../components/drawing":592,"../../lib":694,"../../lib/svg_text_utils":718,"../../plots/cartesian/axes":742,"../../plots/cartesian/set_convert":761,"../heatmap/plot":955,"./close_boundaries":917,"./constants":919,"./convert_to_constraints":923,"./empty_pathinfo":925,"./find_all_paths":927,"./make_crossings":932,"d3":149}],934:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Axes = _dereq_('../../plots/cartesian/axes');
var Lib = _dereq_('../../lib');


module.exports = function setContours(trace) {
    var contours = trace.contours;

    // check if we need to auto-choose contour levels
    if(trace.autocontour) {
        var zmin = trace.zmin;
        var zmax = trace.zmax;
        if(zmin === undefined || zmax === undefined) {
            zmin = Lib.aggNums(Math.min, null, trace._z);
            zmax = Lib.aggNums(Math.max, null, trace._z);
        }
        var dummyAx = autoContours(zmin, zmax, trace.ncontours);

        contours.size = dummyAx.dtick;

        contours.start = Axes.tickFirst(dummyAx);
        dummyAx.range.reverse();
        contours.end = Axes.tickFirst(dummyAx);

        if(contours.start === zmin) contours.start += contours.size;
        if(contours.end === zmax) contours.end -= contours.size;

        // if you set a small ncontours, *and* the ends are exactly on zmin/zmax
        // there's an edge case where start > end now. Make sure there's at least
        // one meaningful contour, put it midway between the crossed values
        if(contours.start > contours.end) {
            contours.start = contours.end = (contours.start + contours.end) / 2;
        }

        // copy auto-contour info back to the source data.
        // previously we copied the whole contours object back, but that had
        // other info (coloring, showlines) that should be left to supplyDefaults
        if(!trace._input.contours) trace._input.contours = {};
        Lib.extendFlat(trace._input.contours, {
            start: contours.start,
            end: contours.end,
            size: contours.size
        });
        trace._input.autocontour = true;
    }
    else if(contours.type !== 'constraint') {
        // sanity checks on manually-supplied start/end/size
        var start = contours.start;
        var end = contours.end;
        var inputContours = trace._input.contours;

        if(start > end) {
            contours.start = inputContours.start = end;
            end = contours.end = inputContours.end = start;
            start = contours.start;
        }

        if(!(contours.size > 0)) {
            var sizeOut;
            if(start === end) sizeOut = 1;
            else sizeOut = autoContours(start, end, trace.ncontours).dtick;

            inputContours.size = contours.size = sizeOut;
        }
    }
};


/*
 * autoContours: make a dummy axis object with dtick we can use
 * as contours.size, and if needed we can use Axes.tickFirst
 * with this axis object to calculate the start and end too
 *
 * start: the value to start the contours at
 * end: the value to end at (must be > start)
 * ncontours: max number of contours to make, like roughDTick
 *
 * returns: an axis object
 */
function autoContours(start, end, ncontours) {
    var dummyAx = {
        type: 'linear',
        range: [start, end]
    };

    Axes.autoTicks(
        dummyAx,
        (end - start) / (ncontours || 15)
    );

    return dummyAx;
}

},{"../../lib":694,"../../plots/cartesian/axes":742}],935:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

var Drawing = _dereq_('../../components/drawing');
var heatmapStyle = _dereq_('../heatmap/style');

var makeColorMap = _dereq_('./make_color_map');


module.exports = function style(gd) {
    var contours = d3.select(gd).selectAll('g.contour');

    contours.style('opacity', function(d) {
        return d[0].trace.opacity;
    });

    contours.each(function(d) {
        var c = d3.select(this);
        var trace = d[0].trace;
        var contours = trace.contours;
        var line = trace.line;
        var cs = contours.size || 1;
        var start = contours.start;

        // for contourcarpet only - is this a constraint-type contour trace?
        var isConstraintType = contours.type === 'constraint';
        var colorLines = !isConstraintType && contours.coloring === 'lines';
        var colorFills = !isConstraintType && contours.coloring === 'fill';

        var colorMap = (colorLines || colorFills) ? makeColorMap(trace) : null;

        c.selectAll('g.contourlevel').each(function(d) {
            d3.select(this).selectAll('path')
                .call(Drawing.lineGroupStyle,
                    line.width,
                    colorLines ? colorMap(d.level) : line.color,
                    line.dash);
        });

        var labelFont = contours.labelfont;
        c.selectAll('g.contourlabels text').each(function(d) {
            Drawing.font(d3.select(this), {
                family: labelFont.family,
                size: labelFont.size,
                color: labelFont.color || (colorLines ? colorMap(d.level) : line.color)
            });
        });

        if(isConstraintType) {
            c.selectAll('g.contourfill path')
                .style('fill', trace.fillcolor);
        }
        else if(colorFills) {
            var firstFill;

            c.selectAll('g.contourfill path')
                .style('fill', function(d) {
                    if(firstFill === undefined) firstFill = d.level;
                    return colorMap(d.level + 0.5 * cs);
                });

            if(firstFill === undefined) firstFill = start;

            c.selectAll('g.contourbg path')
                .style('fill', colorMap(firstFill - 0.5 * cs));
        }
    });

    heatmapStyle(gd);
};

},{"../../components/drawing":592,"../heatmap/style":956,"./make_color_map":931,"d3":149}],936:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
var handleLabelDefaults = _dereq_('./label_defaults');


module.exports = function handleStyleDefaults(traceIn, traceOut, coerce, layout, opts) {
    var coloring = coerce('contours.coloring');

    var showLines;
    var lineColor = '';
    if(coloring === 'fill') showLines = coerce('contours.showlines');

    if(showLines !== false) {
        if(coloring !== 'lines') lineColor = coerce('line.color', '#000');
        coerce('line.width', 0.5);
        coerce('line.dash');
    }

    if(coloring !== 'none') {
        // plots/plots always coerces showlegend to true, but in this case
        // we default to false and (by default) show a colorbar instead
        if(traceIn.showlegend !== true) traceOut.showlegend = false;
        traceOut._dfltShowLegend = false;

        colorscaleDefaults(
            traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'}
        );
    }

    coerce('line.smoothing');

    handleLabelDefaults(coerce, layout, lineColor, opts);
};

},{"../../components/colorscale/defaults":581,"./label_defaults":930}],937:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var heatmapAttrs = _dereq_('../heatmap/attributes');
var contourAttrs = _dereq_('../contour/attributes');
var contourContourAttrs = contourAttrs.contours;
var scatterAttrs = _dereq_('../scatter/attributes');
var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;

var scatterLineAttrs = scatterAttrs.line;

module.exports = extendFlat({
    carpet: {
        valType: 'string',
        
        editType: 'calc',
        
    },
    z: heatmapAttrs.z,
    a: heatmapAttrs.x,
    a0: heatmapAttrs.x0,
    da: heatmapAttrs.dx,
    b: heatmapAttrs.y,
    b0: heatmapAttrs.y0,
    db: heatmapAttrs.dy,
    text: heatmapAttrs.text,
    transpose: heatmapAttrs.transpose,
    atype: heatmapAttrs.xtype,
    btype: heatmapAttrs.ytype,

    fillcolor: contourAttrs.fillcolor,

    autocontour: contourAttrs.autocontour,
    ncontours: contourAttrs.ncontours,

    contours: {
        type: contourContourAttrs.type,
        start: contourContourAttrs.start,
        end: contourContourAttrs.end,
        size: contourContourAttrs.size,
        coloring: {
            // from contourAttrs.contours.coloring but no 'heatmap' option
            valType: 'enumerated',
            values: ['fill', 'lines', 'none'],
            dflt: 'fill',
            
            editType: 'calc',
            
        },
        showlines: contourContourAttrs.showlines,
        showlabels: contourContourAttrs.showlabels,
        labelfont: contourContourAttrs.labelfont,
        labelformat: contourContourAttrs.labelformat,
        operation: contourContourAttrs.operation,
        value: contourContourAttrs.value,
        editType: 'calc',
        impliedEdits: {'autocontour': false}
    },

    line: {
        color: extendFlat({}, scatterLineAttrs.color, {
            
        }),
        width: scatterLineAttrs.width,
        dash: scatterLineAttrs.dash,
        smoothing: extendFlat({}, scatterLineAttrs.smoothing, {
            
        }),
        editType: 'plot'
    },
    transforms: undefined
},

    colorscaleAttrs('', {
        cLetter: 'z',
        autoColorDflt: false
    }),
    { colorbar: colorbarAttrs }
);

},{"../../components/colorbar/attributes":572,"../../components/colorscale/attributes":578,"../../lib/extend":684,"../contour/attributes":915,"../heatmap/attributes":944,"../scatter/attributes":1047}],938:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorscaleCalc = _dereq_('../../components/colorscale/calc');
var Lib = _dereq_('../../lib');

var convertColumnData = _dereq_('../heatmap/convert_column_xyz');
var clean2dArray = _dereq_('../heatmap/clean_2d_array');
var interp2d = _dereq_('../heatmap/interp2d');
var findEmpties = _dereq_('../heatmap/find_empties');
var makeBoundArray = _dereq_('../heatmap/make_bound_array');
var supplyDefaults = _dereq_('./defaults');
var lookupCarpet = _dereq_('../carpet/lookup_carpetid');
var setContours = _dereq_('../contour/set_contours');

// most is the same as heatmap calc, then adjust it
// though a few things inside heatmap calc still look for
// contour maps, because the makeBoundArray calls are too entangled
module.exports = function calc(gd, trace) {
    var carpet = trace._carpetTrace = lookupCarpet(gd, trace);
    if(!carpet || !carpet.visible || carpet.visible === 'legendonly') return;

    if(!trace.a || !trace.b) {
        // Look up the original incoming carpet data:
        var carpetdata = gd.data[carpet.index];

        // Look up the incoming trace data, *except* perform a shallow
        // copy so that we're not actually modifying it when we use it
        // to supply defaults:
        var tracedata = gd.data[trace.index];
        // var tracedata = extendFlat({}, gd.data[trace.index]);

        // If the data is not specified
        if(!tracedata.a) tracedata.a = carpetdata.a;
        if(!tracedata.b) tracedata.b = carpetdata.b;

        supplyDefaults(tracedata, trace, trace._defaultColor, gd._fullLayout);
    }

    var cd = heatmappishCalc(gd, trace);

    setContours(trace);

    return cd;
};

function heatmappishCalc(gd, trace) {
    // prepare the raw data
    // run makeCalcdata on x and y even for heatmaps, in case of category mappings
    var carpet = trace._carpetTrace;
    var aax = carpet.aaxis;
    var bax = carpet.baxis;
    var a,
        a0,
        da,
        b,
        b0,
        db,
        z;

    // cancel minimum tick spacings (only applies to bars and boxes)
    aax._minDtick = 0;
    bax._minDtick = 0;

    if(Lib.isArray1D(trace.z)) convertColumnData(trace, aax, bax, 'a', 'b', ['z']);
    a = trace._a = trace._a || trace.a;
    b = trace._b = trace._b || trace.b;

    a = a ? aax.makeCalcdata(trace, '_a') : [];
    b = b ? bax.makeCalcdata(trace, '_b') : [];
    a0 = trace.a0 || 0;
    da = trace.da || 1;
    b0 = trace.b0 || 0;
    db = trace.db || 1;

    z = trace._z = clean2dArray(trace._z || trace.z, trace.transpose);

    trace._emptypoints = findEmpties(z);
    interp2d(z, trace._emptypoints);

    // create arrays of brick boundaries, to be used by autorange and heatmap.plot
    var xlen = Lib.maxRowLength(z);
    var xIn = trace.xtype === 'scaled' ? '' : a;
    var xArray = makeBoundArray(trace, xIn, a0, da, xlen, aax);
    var yIn = trace.ytype === 'scaled' ? '' : b;
    var yArray = makeBoundArray(trace, yIn, b0, db, z.length, bax);

    var cd0 = {
        a: xArray,
        b: yArray,
        z: z,
    };

    if(trace.contours.type === 'levels' && trace.contours.coloring !== 'none') {
        // auto-z and autocolorscale if applicable
        colorscaleCalc(gd, trace, {
            vals: z,
            containerStr: '',
            cLetter: 'z'
        });
    }

    return [cd0];
}

},{"../../components/colorscale/calc":579,"../../lib":694,"../carpet/lookup_carpetid":893,"../contour/set_contours":934,"../heatmap/clean_2d_array":946,"../heatmap/convert_column_xyz":948,"../heatmap/find_empties":950,"../heatmap/interp2d":953,"../heatmap/make_bound_array":954,"./defaults":939}],939:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

var handleXYZDefaults = _dereq_('../heatmap/xyz_defaults');
var attributes = _dereq_('./attributes');
var handleConstraintDefaults = _dereq_('../contour/constraint_defaults');
var handleContoursDefaults = _dereq_('../contour/contours_defaults');
var handleStyleDefaults = _dereq_('../contour/style_defaults');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    function coerce2(attr) {
        return Lib.coerce2(traceIn, traceOut, attributes, attr);
    }

    coerce('carpet');

    // If either a or b is not present, then it's not a valid trace *unless* the carpet
    // axis has the a or b values we're looking for. So if these are not found, just defer
    // that decision until the calc step.
    //
    // NB: the calc step will modify the original data input by assigning whichever of
    // a or b are missing. This is necessary because panning goes right from supplyDefaults
    // to plot (skipping calc). That means on subsequent updates, this *will* need to be
    // able to find a and b.
    //
    // The long-term proper fix is that this should perhaps use underscored attributes to
    // at least modify the user input to a slightly lesser extent. Fully removing the
    // input mutation is challenging. The underscore approach is not currently taken since
    // it requires modification to all of the functions below that expect the coerced
    // attribute name to match the property name -- except '_a' !== 'a' so that is not
    // straightforward.
    if(traceIn.a && traceIn.b) {

        var len = handleXYZDefaults(traceIn, traceOut, coerce, layout, 'a', 'b');

        if(!len) {
            traceOut.visible = false;
            return;
        }

        coerce('text');
        var isConstraint = (coerce('contours.type') === 'constraint');

        if(isConstraint) {
            handleConstraintDefaults(traceIn, traceOut, coerce, layout, defaultColor, {hasHover: false});
        } else {
            handleContoursDefaults(traceIn, traceOut, coerce, coerce2);
            handleStyleDefaults(traceIn, traceOut, coerce, layout, {hasHover: false});
        }
    } else {
        traceOut._defaultColor = defaultColor;
        traceOut._length = null;
    }
};

},{"../../lib":694,"../contour/constraint_defaults":920,"../contour/contours_defaults":922,"../contour/style_defaults":936,"../heatmap/xyz_defaults":958,"./attributes":937}],940:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var ContourCarpet = {};

ContourCarpet.attributes = _dereq_('./attributes');
ContourCarpet.supplyDefaults = _dereq_('./defaults');
ContourCarpet.colorbar = _dereq_('../contour/colorbar');
ContourCarpet.calc = _dereq_('./calc');
ContourCarpet.plot = _dereq_('./plot');
ContourCarpet.style = _dereq_('../contour/style');

ContourCarpet.moduleType = 'trace';
ContourCarpet.name = 'contourcarpet';
ContourCarpet.basePlotModule = _dereq_('../../plots/cartesian');
ContourCarpet.categories = ['cartesian', 'svg', 'carpet', 'contour', 'symbols', 'showLegend', 'hasLines', 'carpetDependent'];
ContourCarpet.meta = {
    
    
};

module.exports = ContourCarpet;

},{"../../plots/cartesian":754,"../contour/colorbar":918,"../contour/style":935,"./attributes":937,"./calc":938,"./defaults":939,"./plot":943}],941:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Drawing = _dereq_('../../components/drawing');
var axisAlignedLine = _dereq_('../carpet/axis_aligned_line');
var Lib = _dereq_('../../lib');

module.exports = function joinAllPaths(trace, pi, perimeter, ab2p, carpet, carpetcd, xa, ya) {
    var i;
    var fullpath = '';

    var startsleft = pi.edgepaths.map(function(v, i) { return i; });
    var newloop = true;
    var endpt, newendpt, cnt, nexti, possiblei, addpath;

    var atol = Math.abs(perimeter[0][0] - perimeter[2][0]) * 1e-4;
    var btol = Math.abs(perimeter[0][1] - perimeter[2][1]) * 1e-4;

    function istop(pt) { return Math.abs(pt[1] - perimeter[0][1]) < btol; }
    function isbottom(pt) { return Math.abs(pt[1] - perimeter[2][1]) < btol; }
    function isleft(pt) { return Math.abs(pt[0] - perimeter[0][0]) < atol; }
    function isright(pt) { return Math.abs(pt[0] - perimeter[2][0]) < atol; }

    function pathto(pt0, pt1) {
        var i, j, segments, axis;
        var path = '';

        if((istop(pt0) && !isright(pt0)) || (isbottom(pt0) && !isleft(pt0))) {
            axis = carpet.aaxis;
            segments = axisAlignedLine(carpet, carpetcd, [pt0[0], pt1[0]], 0.5 * (pt0[1] + pt1[1]));
        } else {
            axis = carpet.baxis;
            segments = axisAlignedLine(carpet, carpetcd, 0.5 * (pt0[0] + pt1[0]), [pt0[1], pt1[1]]);
        }

        for(i = 1; i < segments.length; i++) {
            path += axis.smoothing ? 'C' : 'L';
            for(j = 0; j < segments[i].length; j++) {
                var pt = segments[i][j];
                path += [xa.c2p(pt[0]), ya.c2p(pt[1])] + ' ';
            }
        }

        return path;
    }

    i = 0;
    endpt = null;
    while(startsleft.length) {
        var startpt = pi.edgepaths[i][0];

        if(endpt) {
            fullpath += pathto(endpt, startpt);
        }

        addpath = Drawing.smoothopen(pi.edgepaths[i].map(ab2p), pi.smoothing);
        fullpath += newloop ? addpath : addpath.replace(/^M/, 'L');
        startsleft.splice(startsleft.indexOf(i), 1);
        endpt = pi.edgepaths[i][pi.edgepaths[i].length - 1];
        nexti = -1;

        // now loop through sides, moving our endpoint until we find a new start
        for(cnt = 0; cnt < 4; cnt++) { // just to prevent infinite loops
            if(!endpt) {
                Lib.log('Missing end?', i, pi);
                break;
            }

            if(istop(endpt) && !isright(endpt)) {
                newendpt = perimeter[1]; // left top ---> right top
            } else if(isleft(endpt)) {
                newendpt = perimeter[0]; // left bottom ---> left top
            } else if(isbottom(endpt)) {
                newendpt = perimeter[3]; // right bottom
            } else if(isright(endpt)) {
                newendpt = perimeter[2]; // left bottom
            }

            for(possiblei = 0; possiblei < pi.edgepaths.length; possiblei++) {
                var ptNew = pi.edgepaths[possiblei][0];
                // is ptNew on the (horz. or vert.) segment from endpt to newendpt?
                if(Math.abs(endpt[0] - newendpt[0]) < atol) {
                    if(Math.abs(endpt[0] - ptNew[0]) < atol && (ptNew[1] - endpt[1]) * (newendpt[1] - ptNew[1]) >= 0) {
                        newendpt = ptNew;
                        nexti = possiblei;
                    }
                } else if(Math.abs(endpt[1] - newendpt[1]) < btol) {
                    if(Math.abs(endpt[1] - ptNew[1]) < btol && (ptNew[0] - endpt[0]) * (newendpt[0] - ptNew[0]) >= 0) {
                        newendpt = ptNew;
                        nexti = possiblei;
                    }
                } else {
                    Lib.log('endpt to newendpt is not vert. or horz.', endpt, newendpt, ptNew);
                }
            }

            if(nexti >= 0) break;
            fullpath += pathto(endpt, newendpt);
            endpt = newendpt;
        }

        if(nexti === pi.edgepaths.length) {
            Lib.log('unclosed perimeter path');
            break;
        }

        i = nexti;

        // if we closed back on a loop we already included,
        // close it and start a new loop
        newloop = (startsleft.indexOf(i) === -1);
        if(newloop) {
            i = startsleft[0];
            fullpath += pathto(endpt, newendpt) + 'Z';
            endpt = null;
        }
    }

    // finally add the interior paths
    for(i = 0; i < pi.paths.length; i++) {
        fullpath += Drawing.smoothclosed(pi.paths[i].map(ab2p), pi.smoothing);
    }

    return fullpath;
};

},{"../../components/drawing":592,"../../lib":694,"../carpet/axis_aligned_line":877}],942:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function mapPathinfo(pathinfo, map) {
    var i, j, k, pi, pedgepaths, ppaths, pedgepath, ppath, path;

    for(i = 0; i < pathinfo.length; i++) {
        pi = pathinfo[i];
        pedgepaths = pi.pedgepaths = [];
        ppaths = pi.ppaths = [];
        for(j = 0; j < pi.edgepaths.length; j++) {
            path = pi.edgepaths[j];
            pedgepath = [];
            for(k = 0; k < path.length; k++) {
                pedgepath[k] = map(path[k]);
            }
            pedgepaths.push(pedgepath);
        }
        for(j = 0; j < pi.paths.length; j++) {
            path = pi.paths[j];
            ppath = [];
            for(k = 0; k < path.length; k++) {
                ppath[k] = map(path[k]);
            }
            ppaths.push(ppath);
        }
    }
};

},{}],943:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var map1dArray = _dereq_('../carpet/map_1d_array');
var makepath = _dereq_('../carpet/makepath');
var Drawing = _dereq_('../../components/drawing');
var Lib = _dereq_('../../lib');

var makeCrossings = _dereq_('../contour/make_crossings');
var findAllPaths = _dereq_('../contour/find_all_paths');
var contourPlot = _dereq_('../contour/plot');
var constants = _dereq_('../contour/constants');
var convertToConstraints = _dereq_('../contour/convert_to_constraints');
var joinAllPaths = _dereq_('./join_all_paths');
var emptyPathinfo = _dereq_('../contour/empty_pathinfo');
var mapPathinfo = _dereq_('./map_pathinfo');
var lookupCarpet = _dereq_('../carpet/lookup_carpetid');
var closeBoundaries = _dereq_('../contour/close_boundaries');

module.exports = function plot(gd, plotinfo, cdcontours, contourcarpetLayer) {
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    Lib.makeTraceGroups(contourcarpetLayer, cdcontours, 'contour').each(function(cd) {
        var plotGroup = d3.select(this);
        var cd0 = cd[0];
        var trace = cd0.trace;

        var carpet = trace._carpetTrace = lookupCarpet(gd, trace);
        var carpetcd = gd.calcdata[carpet.index][0];

        if(!carpet.visible || carpet.visible === 'legendonly') return;

        var a = cd0.a;
        var b = cd0.b;
        var contours = trace.contours;
        var pathinfo = emptyPathinfo(contours, plotinfo, cd0);
        var isConstraint = contours.type === 'constraint';
        var operation = contours._operation;
        var coloring = isConstraint ? (operation === '=' ? 'lines' : 'fill') : contours.coloring;

        // Map [a, b] (data) --> [i, j] (pixels)
        function ab2p(ab) {
            var pt = carpet.ab2xy(ab[0], ab[1], true);
            return [xa.c2p(pt[0]), ya.c2p(pt[1])];
        }

        // Define the perimeter in a/b coordinates:
        var perimeter = [
            [a[0], b[b.length - 1]],
            [a[a.length - 1], b[b.length - 1]],
            [a[a.length - 1], b[0]],
            [a[0], b[0]]
        ];

        // Extract the contour levels:
        makeCrossings(pathinfo);
        var atol = (a[a.length - 1] - a[0]) * 1e-8;
        var btol = (b[b.length - 1] - b[0]) * 1e-8;
        findAllPaths(pathinfo, atol, btol);

        // Constraints might need to be draw inverted, which is not something contours
        // handle by default since they're assumed fully opaque so that they can be
        // drawn overlapping. This function flips the paths as necessary so that they're
        // drawn correctly.
        //
        // TODO: Perhaps this should be generalized and *all* paths should be drawn as
        // closed regions so that translucent contour levels would be valid.
        // See: https://github.com/plotly/plotly.js/issues/1356
        var fillPathinfo = pathinfo;
        if(contours.type === 'constraint') {
            fillPathinfo = convertToConstraints(pathinfo, operation);
            closeBoundaries(fillPathinfo, operation, perimeter, trace);
        }

        // Map the paths in a/b coordinates to pixel coordinates:
        mapPathinfo(pathinfo, ab2p);

        // draw everything

        // Compute the boundary path
        var seg, xp, yp, i;
        var segs = [];
        for(i = carpetcd.clipsegments.length - 1; i >= 0; i--) {
            seg = carpetcd.clipsegments[i];
            xp = map1dArray([], seg.x, xa.c2p);
            yp = map1dArray([], seg.y, ya.c2p);
            xp.reverse();
            yp.reverse();
            segs.push(makepath(xp, yp, seg.bicubic));
        }

        var boundaryPath = 'M' + segs.join('L') + 'Z';

        // Draw the baseline background fill that fills in the space behind any other
        // contour levels:
        makeBackground(plotGroup, carpetcd.clipsegments, xa, ya, isConstraint, coloring);

        // Draw the specific contour fills. As a simplification, they're assumed to be
        // fully opaque so that it's easy to draw them simply overlapping. The alternative
        // would be to flip adjacent paths and draw closed paths for each level instead.
        makeFills(trace, plotGroup, xa, ya, fillPathinfo, perimeter, ab2p, carpet, carpetcd, coloring, boundaryPath);

        // Draw contour lines:
        makeLinesAndLabels(plotGroup, pathinfo, gd, cd0, contours, plotinfo, carpet);

        // Clip the boundary of the plot
        Drawing.setClipUrl(plotGroup, carpet._clipPathId, gd);
    });
};

function makeLinesAndLabels(plotgroup, pathinfo, gd, cd0, contours, plotinfo, carpet) {
    var lineContainer = Lib.ensureSingle(plotgroup, 'g', 'contourlines');
    var showLines = contours.showlines !== false;
    var showLabels = contours.showlabels;
    var clipLinesForLabels = showLines && showLabels;

    // Even if we're not going to show lines, we need to create them
    // if we're showing labels, because the fill paths include the perimeter
    // so can't be used to position the labels correctly.
    // In this case we'll remove the lines after making the labels.
    var linegroup = contourPlot.createLines(lineContainer, showLines || showLabels, pathinfo);

    var lineClip = contourPlot.createLineClip(lineContainer, clipLinesForLabels, gd, cd0.trace.uid);

    var labelGroup = plotgroup.selectAll('g.contourlabels')
        .data(showLabels ? [0] : []);

    labelGroup.exit().remove();

    labelGroup.enter().append('g')
        .classed('contourlabels', true);

    if(showLabels) {
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        var xLen = xa._length;
        var yLen = ya._length;
        // for simplicity use the xy box for label clipping outline.
        var labelClipPathData = [[
            [0, 0],
            [xLen, 0],
            [xLen, yLen],
            [0, yLen]
        ]];


        var labelData = [];

        // invalidate the getTextLocation cache in case paths changed
        Lib.clearLocationCache();

        var contourFormat = contourPlot.labelFormatter(contours, cd0.t.cb, gd._fullLayout);

        var dummyText = Drawing.tester.append('text')
            .attr('data-notex', 1)
            .call(Drawing.font, contours.labelfont);

        // use `bounds` only to keep labels away from the x/y boundaries
        // `constrainToCarpet` below ensures labels don't go off the
        // carpet edges
        var bounds = {
            left: 0,
            right: xLen,
            center: xLen / 2,
            top: 0,
            bottom: yLen,
            middle: yLen / 2
        };

        var plotDiagonal = Math.sqrt(xLen * xLen + yLen * yLen);

        // the path length to use to scale the number of labels to draw:
        var normLength = constants.LABELDISTANCE * plotDiagonal /
            Math.max(1, pathinfo.length / constants.LABELINCREASE);

        linegroup.each(function(d) {
            var textOpts = contourPlot.calcTextOpts(d.level, contourFormat, dummyText, gd);

            d3.select(this).selectAll('path').each(function(pathData) {
                var path = this;
                var pathBounds = Lib.getVisibleSegment(path, bounds, textOpts.height / 2);
                if(!pathBounds) return;

                constrainToCarpet(path, pathData, d, pathBounds, carpet, textOpts.height);

                if(pathBounds.len < (textOpts.width + textOpts.height) * constants.LABELMIN) return;

                var maxLabels = Math.min(Math.ceil(pathBounds.len / normLength),
                    constants.LABELMAX);

                for(var i = 0; i < maxLabels; i++) {
                    var loc = contourPlot.findBestTextLocation(path, pathBounds, textOpts,
                        labelData, bounds);

                    if(!loc) break;

                    contourPlot.addLabelData(loc, textOpts, labelData, labelClipPathData);
                }
            });
        });

        dummyText.remove();

        contourPlot.drawLabels(labelGroup, labelData, gd, lineClip,
            clipLinesForLabels ? labelClipPathData : null);
    }

    if(showLabels && !showLines) linegroup.remove();
}

// figure out if this path goes off the edge of the carpet
// and shorten the part we call visible to keep labels away from the edge
function constrainToCarpet(path, pathData, levelData, pathBounds, carpet, textHeight) {
    var pathABData;
    for(var i = 0; i < levelData.pedgepaths.length; i++) {
        if(pathData === levelData.pedgepaths[i]) {
            pathABData = levelData.edgepaths[i];
        }
    }
    if(!pathABData) return;

    var aMin = carpet.a[0];
    var aMax = carpet.a[carpet.a.length - 1];
    var bMin = carpet.b[0];
    var bMax = carpet.b[carpet.b.length - 1];

    function getOffset(abPt, pathVector) {
        var offset = 0;
        var edgeVector;
        var dAB = 0.1;
        if(Math.abs(abPt[0] - aMin) < dAB || Math.abs(abPt[0] - aMax) < dAB) {
            edgeVector = normalizeVector(carpet.dxydb_rough(abPt[0], abPt[1], dAB));
            offset = Math.max(offset, textHeight * vectorTan(pathVector, edgeVector) / 2);
        }

        if(Math.abs(abPt[1] - bMin) < dAB || Math.abs(abPt[1] - bMax) < dAB) {
            edgeVector = normalizeVector(carpet.dxyda_rough(abPt[0], abPt[1], dAB));
            offset = Math.max(offset, textHeight * vectorTan(pathVector, edgeVector) / 2);
        }
        return offset;
    }

    var startVector = getUnitVector(path, 0, 1);
    var endVector = getUnitVector(path, pathBounds.total, pathBounds.total - 1);
    var minStart = getOffset(pathABData[0], startVector);
    var maxEnd = pathBounds.total - getOffset(pathABData[pathABData.length - 1], endVector);

    if(pathBounds.min < minStart) pathBounds.min = minStart;
    if(pathBounds.max > maxEnd) pathBounds.max = maxEnd;

    pathBounds.len = pathBounds.max - pathBounds.min;
}

function getUnitVector(path, p0, p1) {
    var pt0 = path.getPointAtLength(p0);
    var pt1 = path.getPointAtLength(p1);
    var dx = pt1.x - pt0.x;
    var dy = pt1.y - pt0.y;
    var len = Math.sqrt(dx * dx + dy * dy);
    return [dx / len, dy / len];
}

function normalizeVector(v) {
    var len = Math.sqrt(v[0] * v[0] + v[1] * v[1]);
    return [v[0] / len, v[1] / len];
}

function vectorTan(v0, v1) {
    var cos = Math.abs(v0[0] * v1[0] + v0[1] * v1[1]);
    var sin = Math.sqrt(1 - cos * cos);
    return sin / cos;
}

function makeBackground(plotgroup, clipsegments, xaxis, yaxis, isConstraint, coloring) {
    var seg, xp, yp, i;
    var bggroup = Lib.ensureSingle(plotgroup, 'g', 'contourbg');

    var bgfill = bggroup.selectAll('path')
        .data((coloring === 'fill' && !isConstraint) ? [0] : []);
    bgfill.enter().append('path');
    bgfill.exit().remove();

    var segs = [];
    for(i = 0; i < clipsegments.length; i++) {
        seg = clipsegments[i];
        xp = map1dArray([], seg.x, xaxis.c2p);
        yp = map1dArray([], seg.y, yaxis.c2p);
        segs.push(makepath(xp, yp, seg.bicubic));
    }

    bgfill
        .attr('d', 'M' + segs.join('L') + 'Z')
        .style('stroke', 'none');
}

function makeFills(trace, plotgroup, xa, ya, pathinfo, perimeter, ab2p, carpet, carpetcd, coloring, boundaryPath) {
    var fillgroup = Lib.ensureSingle(plotgroup, 'g', 'contourfill');

    var fillitems = fillgroup.selectAll('path')
        .data(coloring === 'fill' ? pathinfo : []);
    fillitems.enter().append('path');
    fillitems.exit().remove();
    fillitems.each(function(pi) {
        // join all paths for this level together into a single path
        // first follow clockwise around the perimeter to close any open paths
        // if the whole perimeter is above this level, start with a path
        // enclosing the whole thing. With all that, the parity should mean
        // that we always fill everything above the contour, nothing below
        var fullpath = joinAllPaths(trace, pi, perimeter, ab2p, carpet, carpetcd, xa, ya);

        if(pi.prefixBoundary) {
            fullpath = boundaryPath + fullpath;
        }

        if(!fullpath) {
            d3.select(this).remove();
        } else {
            d3.select(this)
                .attr('d', fullpath)
                .style('stroke', 'none');
        }
    });
}

},{"../../components/drawing":592,"../../lib":694,"../carpet/lookup_carpetid":893,"../carpet/makepath":894,"../carpet/map_1d_array":895,"../contour/close_boundaries":917,"../contour/constants":919,"../contour/convert_to_constraints":923,"../contour/empty_pathinfo":925,"../contour/find_all_paths":927,"../contour/make_crossings":932,"../contour/plot":933,"./join_all_paths":941,"./map_pathinfo":942,"d3":149}],944:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterAttrs = _dereq_('../scatter/attributes');
var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;

module.exports = extendFlat({
    z: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    x: extendFlat({}, scatterAttrs.x, {impliedEdits: {xtype: 'array'}}),
    x0: extendFlat({}, scatterAttrs.x0, {impliedEdits: {xtype: 'scaled'}}),
    dx: extendFlat({}, scatterAttrs.dx, {impliedEdits: {xtype: 'scaled'}}),
    y: extendFlat({}, scatterAttrs.y, {impliedEdits: {ytype: 'array'}}),
    y0: extendFlat({}, scatterAttrs.y0, {impliedEdits: {ytype: 'scaled'}}),
    dy: extendFlat({}, scatterAttrs.dy, {impliedEdits: {ytype: 'scaled'}}),

    text: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    transpose: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'calc',
        
    },
    xtype: {
        valType: 'enumerated',
        values: ['array', 'scaled'],
        
        editType: 'calc+clearAxisTypes',
        
    },
    ytype: {
        valType: 'enumerated',
        values: ['array', 'scaled'],
        
        editType: 'calc+clearAxisTypes',
        
    },
    zsmooth: {
        valType: 'enumerated',
        values: ['fast', 'best', false],
        dflt: false,
        
        editType: 'calc',
        
    },
    connectgaps: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'calc',
        
    },
    xgap: {
        valType: 'number',
        dflt: 0,
        min: 0,
        
        editType: 'plot',
        
    },
    ygap: {
        valType: 'number',
        dflt: 0,
        min: 0,
        
        editType: 'plot',
        
    },
    zhoverformat: {
        valType: 'string',
        dflt: '',
        
        editType: 'none',
        
    },
    transforms: undefined
},
    colorscaleAttrs('', {
        cLetter: 'z',
        autoColorDflt: false
    }),
    { colorbar: colorbarAttrs }
);

},{"../../components/colorbar/attributes":572,"../../components/colorscale/attributes":578,"../../lib/extend":684,"../scatter/attributes":1047}],945:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');

var histogram2dCalc = _dereq_('../histogram2d/calc');
var colorscaleCalc = _dereq_('../../components/colorscale/calc');
var convertColumnData = _dereq_('./convert_column_xyz');
var clean2dArray = _dereq_('./clean_2d_array');
var interp2d = _dereq_('./interp2d');
var findEmpties = _dereq_('./find_empties');
var makeBoundArray = _dereq_('./make_bound_array');


module.exports = function calc(gd, trace) {
    // prepare the raw data
    // run makeCalcdata on x and y even for heatmaps, in case of category mappings
    var xa = Axes.getFromId(gd, trace.xaxis || 'x');
    var ya = Axes.getFromId(gd, trace.yaxis || 'y');
    var isContour = Registry.traceIs(trace, 'contour');
    var isHist = Registry.traceIs(trace, 'histogram');
    var isGL2D = Registry.traceIs(trace, 'gl2d');
    var zsmooth = isContour ? 'best' : trace.zsmooth;
    var x;
    var x0;
    var dx;
    var y;
    var y0;
    var dy;
    var z;
    var i;
    var binned;

    // cancel minimum tick spacings (only applies to bars and boxes)
    xa._minDtick = 0;
    ya._minDtick = 0;

    if(isHist) {
        binned = histogram2dCalc(gd, trace);
        x = binned.x;
        x0 = binned.x0;
        dx = binned.dx;
        y = binned.y;
        y0 = binned.y0;
        dy = binned.dy;
        z = binned.z;
    }
    else {
        var zIn = trace.z;
        if(Lib.isArray1D(zIn)) {
            convertColumnData(trace, xa, ya, 'x', 'y', ['z']);
            x = trace._x;
            y = trace._y;
            zIn = trace._z;
        } else {
            x = trace.x ? xa.makeCalcdata(trace, 'x') : [];
            y = trace.y ? ya.makeCalcdata(trace, 'y') : [];
        }

        x0 = trace.x0 || 0;
        dx = trace.dx || 1;
        y0 = trace.y0 || 0;
        dy = trace.dy || 1;

        z = clean2dArray(zIn, trace.transpose);

        if(isContour || trace.connectgaps) {
            trace._emptypoints = findEmpties(z);
            interp2d(z, trace._emptypoints);
        }
    }

    function noZsmooth(msg) {
        zsmooth = trace._input.zsmooth = trace.zsmooth = false;
        Lib.warn('cannot use zsmooth: "fast": ' + msg);
    }

    // check whether we really can smooth (ie all boxes are about the same size)
    if(zsmooth === 'fast') {
        if(xa.type === 'log' || ya.type === 'log') {
            noZsmooth('log axis found');
        }
        else if(!isHist) {
            if(x.length) {
                var avgdx = (x[x.length - 1] - x[0]) / (x.length - 1);
                var maxErrX = Math.abs(avgdx / 100);
                for(i = 0; i < x.length - 1; i++) {
                    if(Math.abs(x[i + 1] - x[i] - avgdx) > maxErrX) {
                        noZsmooth('x scale is not linear');
                        break;
                    }
                }
            }
            if(y.length && zsmooth === 'fast') {
                var avgdy = (y[y.length - 1] - y[0]) / (y.length - 1);
                var maxErrY = Math.abs(avgdy / 100);
                for(i = 0; i < y.length - 1; i++) {
                    if(Math.abs(y[i + 1] - y[i] - avgdy) > maxErrY) {
                        noZsmooth('y scale is not linear');
                        break;
                    }
                }
            }
        }
    }

    // create arrays of brick boundaries, to be used by autorange and heatmap.plot
    var xlen = Lib.maxRowLength(z);
    var xIn = trace.xtype === 'scaled' ? '' : x;
    var xArray = makeBoundArray(trace, xIn, x0, dx, xlen, xa);
    var yIn = trace.ytype === 'scaled' ? '' : y;
    var yArray = makeBoundArray(trace, yIn, y0, dy, z.length, ya);

    // handled in gl2d convert step
    if(!isGL2D) {
        trace._extremes[xa._id] = Axes.findExtremes(xa, xArray);
        trace._extremes[ya._id] = Axes.findExtremes(ya, yArray);
    }

    var cd0 = {
        x: xArray,
        y: yArray,
        z: z,
        text: trace._text || trace.text
    };

    if(xIn && xIn.length === xArray.length - 1) cd0.xCenter = xIn;
    if(yIn && yIn.length === yArray.length - 1) cd0.yCenter = yIn;

    if(isHist) {
        cd0.xRanges = binned.xRanges;
        cd0.yRanges = binned.yRanges;
        cd0.pts = binned.pts;
    }

    // auto-z and autocolorscale if applicable
    if(!isContour || trace.contours.type !== 'constraint') {
        colorscaleCalc(gd, trace, {
            vals: z,
            containerStr: '',
            cLetter: 'z'
        });
    }

    if(isContour && trace.contours && trace.contours.coloring === 'heatmap') {
        var dummyTrace = {
            type: trace.type === 'contour' ? 'heatmap' : 'histogram2d',
            xcalendar: trace.xcalendar,
            ycalendar: trace.ycalendar
        };
        cd0.xfill = makeBoundArray(dummyTrace, xIn, x0, dx, xlen, xa);
        cd0.yfill = makeBoundArray(dummyTrace, yIn, y0, dy, z.length, ya);
    }

    return [cd0];
};

},{"../../components/colorscale/calc":579,"../../lib":694,"../../plots/cartesian/axes":742,"../../registry":825,"../histogram2d/calc":976,"./clean_2d_array":946,"./convert_column_xyz":948,"./find_empties":950,"./interp2d":953,"./make_bound_array":954}],946:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');

module.exports = function clean2dArray(zOld, transpose) {
    var rowlen, collen, getCollen, old2new, i, j;

    function cleanZvalue(v) {
        if(!isNumeric(v)) return undefined;
        return +v;
    }

    if(transpose) {
        rowlen = 0;
        for(i = 0; i < zOld.length; i++) rowlen = Math.max(rowlen, zOld[i].length);
        if(rowlen === 0) return false;
        getCollen = function(zOld) { return zOld.length; };
        old2new = function(zOld, i, j) { return zOld[j][i]; };
    }
    else {
        rowlen = zOld.length;
        getCollen = function(zOld, i) { return zOld[i].length; };
        old2new = function(zOld, i, j) { return zOld[i][j]; };
    }

    var zNew = new Array(rowlen);

    for(i = 0; i < rowlen; i++) {
        collen = getCollen(zOld, i);
        zNew[i] = new Array(collen);
        for(j = 0; j < collen; j++) zNew[i][j] = cleanZvalue(old2new(zOld, i, j));
    }

    return zNew;
};

},{"fast-isnumeric":215}],947:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    min: 'zmin',
    max: 'zmax'
};

},{}],948:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

module.exports = function convertColumnData(trace, ax1, ax2, var1Name, var2Name, arrayVarNames) {
    var colLen = trace._length;
    var col1 = ax1.makeCalcdata(trace, var1Name);
    var col2 = ax2.makeCalcdata(trace, var2Name);
    var textCol = trace.text;
    var hasColumnText = (textCol !== undefined && Lib.isArray1D(textCol));
    var i, j;

    var col1dv = Lib.distinctVals(col1);
    var col1vals = col1dv.vals;
    var col2dv = Lib.distinctVals(col2);
    var col2vals = col2dv.vals;
    var newArrays = [];
    var text;

    for(i = 0; i < arrayVarNames.length; i++) {
        newArrays[i] = Lib.init2dArray(col2vals.length, col1vals.length);
    }

    if(hasColumnText) {
        text = Lib.init2dArray(col2vals.length, col1vals.length);
    }

    for(i = 0; i < colLen; i++) {
        if(col1[i] !== BADNUM && col2[i] !== BADNUM) {
            var i1 = Lib.findBin(col1[i] + col1dv.minDiff / 2, col1vals);
            var i2 = Lib.findBin(col2[i] + col2dv.minDiff / 2, col2vals);

            for(j = 0; j < arrayVarNames.length; j++) {
                var arrayVarName = arrayVarNames[j];
                var arrayVar = trace[arrayVarName];
                var newArray = newArrays[j];
                newArray[i2][i1] = arrayVar[i];
            }

            if(hasColumnText) text[i2][i1] = textCol[i];
        }
    }

    trace['_' + var1Name] = col1vals;
    trace['_' + var2Name] = col2vals;
    for(j = 0; j < arrayVarNames.length; j++) {
        trace['_' + arrayVarNames[j]] = newArrays[j];
    }
    if(hasColumnText) trace._text = text;
};

},{"../../constants/numerical":671,"../../lib":694}],949:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

var handleXYZDefaults = _dereq_('./xyz_defaults');
var handleStyleDefaults = _dereq_('./style_defaults');
var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
var attributes = _dereq_('./attributes');


module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var validData = handleXYZDefaults(traceIn, traceOut, coerce, layout);
    if(!validData) {
        traceOut.visible = false;
        return;
    }

    coerce('text');

    handleStyleDefaults(traceIn, traceOut, coerce, layout);

    coerce('connectgaps', Lib.isArray1D(traceOut.z) && (traceOut.zsmooth !== false));

    colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'});
};

},{"../../components/colorscale/defaults":581,"../../lib":694,"./attributes":944,"./style_defaults":957,"./xyz_defaults":958}],950:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var maxRowLength = _dereq_('../../lib').maxRowLength;

/* Return a list of empty points in 2D array z
 * each empty point z[i][j] gives an array [i, j, neighborCount]
 * neighborCount is the count of 4 nearest neighbors that DO exist
 * this is to give us an order of points to evaluate for interpolation.
 * if no neighbors exist, we iteratively look for neighbors that HAVE
 * neighbors, and add a fractional neighborCount
 */
module.exports = function findEmpties(z) {
    var empties = [];
    var neighborHash = {};
    var noNeighborList = [];
    var nextRow = z[0];
    var row = [];
    var blank = [0, 0, 0];
    var rowLength = maxRowLength(z);
    var prevRow;
    var i;
    var j;
    var thisPt;
    var p;
    var neighborCount;
    var newNeighborHash;
    var foundNewNeighbors;

    for(i = 0; i < z.length; i++) {
        prevRow = row;
        row = nextRow;
        nextRow = z[i + 1] || [];
        for(j = 0; j < rowLength; j++) {
            if(row[j] === undefined) {
                neighborCount = (row[j - 1] !== undefined ? 1 : 0) +
                    (row[j + 1] !== undefined ? 1 : 0) +
                    (prevRow[j] !== undefined ? 1 : 0) +
                    (nextRow[j] !== undefined ? 1 : 0);

                if(neighborCount) {
                    // for this purpose, don't count off-the-edge points
                    // as undefined neighbors
                    if(i === 0) neighborCount++;
                    if(j === 0) neighborCount++;
                    if(i === z.length - 1) neighborCount++;
                    if(j === row.length - 1) neighborCount++;

                    // if all neighbors that could exist do, we don't
                    // need this for finding farther neighbors
                    if(neighborCount < 4) {
                        neighborHash[[i, j]] = [i, j, neighborCount];
                    }

                    empties.push([i, j, neighborCount]);
                }
                else noNeighborList.push([i, j]);
            }
        }
    }

    while(noNeighborList.length) {
        newNeighborHash = {};
        foundNewNeighbors = false;

        // look for cells that now have neighbors but didn't before
        for(p = noNeighborList.length - 1; p >= 0; p--) {
            thisPt = noNeighborList[p];
            i = thisPt[0];
            j = thisPt[1];

            neighborCount = ((neighborHash[[i - 1, j]] || blank)[2] +
                (neighborHash[[i + 1, j]] || blank)[2] +
                (neighborHash[[i, j - 1]] || blank)[2] +
                (neighborHash[[i, j + 1]] || blank)[2]) / 20;

            if(neighborCount) {
                newNeighborHash[thisPt] = [i, j, neighborCount];
                noNeighborList.splice(p, 1);
                foundNewNeighbors = true;
            }
        }

        if(!foundNewNeighbors) {
            throw 'findEmpties iterated with no new neighbors';
        }

        // put these new cells into the main neighbor list
        for(thisPt in newNeighborHash) {
            neighborHash[thisPt] = newNeighborHash[thisPt];
            empties.push(newNeighborHash[thisPt]);
        }
    }

    // sort the full list in descending order of neighbor count
    return empties.sort(function(a, b) { return b[2] - a[2]; });
};

},{"../../lib":694}],951:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Fx = _dereq_('../../components/fx');
var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');

module.exports = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer, contour) {
    var cd0 = pointData.cd[0];
    var trace = cd0.trace;
    var xa = pointData.xa;
    var ya = pointData.ya;
    var x = cd0.x;
    var y = cd0.y;
    var z = cd0.z;
    var xc = cd0.xCenter;
    var yc = cd0.yCenter;
    var zmask = cd0.zmask;
    var range = [trace.zmin, trace.zmax];
    var zhoverformat = trace.zhoverformat;
    var x2 = x;
    var y2 = y;

    var xl, yl, nx, ny;

    if(pointData.index !== false) {
        try {
            nx = Math.round(pointData.index[1]);
            ny = Math.round(pointData.index[0]);
        }
        catch(e) {
            Lib.error('Error hovering on heatmap, ' +
                'pointNumber must be [row,col], found:', pointData.index);
            return;
        }
        if(nx < 0 || nx >= z[0].length || ny < 0 || ny > z.length) {
            return;
        }
    }
    else if(Fx.inbox(xval - x[0], xval - x[x.length - 1], 0) > 0 ||
            Fx.inbox(yval - y[0], yval - y[y.length - 1], 0) > 0) {
        return;
    }
    else {
        if(contour) {
            var i2;
            x2 = [2 * x[0] - x[1]];

            for(i2 = 1; i2 < x.length; i2++) {
                x2.push((x[i2] + x[i2 - 1]) / 2);
            }
            x2.push([2 * x[x.length - 1] - x[x.length - 2]]);

            y2 = [2 * y[0] - y[1]];
            for(i2 = 1; i2 < y.length; i2++) {
                y2.push((y[i2] + y[i2 - 1]) / 2);
            }
            y2.push([2 * y[y.length - 1] - y[y.length - 2]]);
        }
        nx = Math.max(0, Math.min(x2.length - 2, Lib.findBin(xval, x2)));
        ny = Math.max(0, Math.min(y2.length - 2, Lib.findBin(yval, y2)));
    }

    var x0 = xa.c2p(x[nx]);
    var x1 = xa.c2p(x[nx + 1]);
    var y0 = ya.c2p(y[ny]);
    var y1 = ya.c2p(y[ny + 1]);

    if(contour) {
        x1 = x0;
        xl = x[nx];
        y1 = y0;
        yl = y[ny];
    }
    else {
        xl = xc ? xc[nx] : ((x[nx] + x[nx + 1]) / 2);
        yl = yc ? yc[ny] : ((y[ny] + y[ny + 1]) / 2);
        if(trace.zsmooth) {
            x0 = x1 = xa.c2p(xl);
            y0 = y1 = ya.c2p(yl);
        }
    }

    var zVal = z[ny][nx];
    if(zmask && !zmask[ny][nx]) zVal = undefined;

    var text;
    if(Array.isArray(cd0.text) && Array.isArray(cd0.text[ny])) {
        text = cd0.text[ny][nx];
    }

    var zLabel;
    // dummy axis for formatting the z value
    var dummyAx = {
        type: 'linear',
        range: range,
        hoverformat: zhoverformat,
        _separators: xa._separators,
        _numFormat: xa._numFormat
    };
    var zLabelObj = Axes.tickText(dummyAx, zVal, 'hover');
    zLabel = zLabelObj.text;

    return [Lib.extendFlat(pointData, {
        index: [ny, nx],
        // never let a 2D override 1D type as closest point
        distance: pointData.maxHoverDistance,
        spikeDistance: pointData.maxSpikeDistance,
        x0: x0,
        x1: x1,
        y0: y0,
        y1: y1,
        xLabelVal: xl,
        yLabelVal: yl,
        zLabelVal: zVal,
        zLabel: zLabel,
        text: text
    })];
};

},{"../../components/fx":610,"../../lib":694,"../../plots/cartesian/axes":742}],952:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Heatmap = {};

Heatmap.attributes = _dereq_('./attributes');
Heatmap.supplyDefaults = _dereq_('./defaults');
Heatmap.calc = _dereq_('./calc');
Heatmap.plot = _dereq_('./plot');
Heatmap.colorbar = _dereq_('./colorbar');
Heatmap.style = _dereq_('./style');
Heatmap.hoverPoints = _dereq_('./hover');

Heatmap.moduleType = 'trace';
Heatmap.name = 'heatmap';
Heatmap.basePlotModule = _dereq_('../../plots/cartesian');
Heatmap.categories = ['cartesian', 'svg', '2dMap'];
Heatmap.meta = {
    
};

module.exports = Heatmap;

},{"../../plots/cartesian":754,"./attributes":944,"./calc":945,"./colorbar":947,"./defaults":949,"./hover":951,"./plot":955,"./style":956}],953:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

var INTERPTHRESHOLD = 1e-2;
var NEIGHBORSHIFTS = [[-1, 0], [1, 0], [0, -1], [0, 1]];

function correctionOvershoot(maxFractionalChange) {
    // start with less overshoot, until we know it's converging,
    // then ramp up the overshoot for faster convergence
    return 0.5 - 0.25 * Math.min(1, maxFractionalChange * 0.5);
}

/*
 * interp2d: Fill in missing data from a 2D array using an iterative
 *   poisson equation solver with zero-derivative BC at edges.
 *   Amazingly, this just amounts to repeatedly averaging all the existing
 *   nearest neighbors, at least if we don't take x/y scaling into account,
 *   which is the right approach here where x and y may not even have the
 *   same units.
 *
 * @param {array of arrays} z
 *      The 2D array to fill in. Will be mutated here. Assumed to already be
 *      cleaned, so all entries are numbers except gaps, which are `undefined`.
 * @param {array of arrays} emptyPoints
 *      Each entry [i, j, neighborCount] for empty points z[i][j] and the number
 *      of neighbors that are *not* missing. Assumed to be sorted from most to
 *      least neighbors, as produced by heatmap/find_empties.
 */
module.exports = function interp2d(z, emptyPoints) {
    var maxFractionalChange = 1;
    var i;

    // one pass to fill in a starting value for all the empties
    iterateInterp2d(z, emptyPoints);

    // we're don't need to iterate lone empties - remove them
    for(i = 0; i < emptyPoints.length; i++) {
        if(emptyPoints[i][2] < 4) break;
    }
    // but don't remove these points from the original array,
    // we'll use them for masking, so make a copy.
    emptyPoints = emptyPoints.slice(i);

    for(i = 0; i < 100 && maxFractionalChange > INTERPTHRESHOLD; i++) {
        maxFractionalChange = iterateInterp2d(z, emptyPoints,
            correctionOvershoot(maxFractionalChange));
    }
    if(maxFractionalChange > INTERPTHRESHOLD) {
        Lib.log('interp2d didn\'t converge quickly', maxFractionalChange);
    }

    return z;
};

function iterateInterp2d(z, emptyPoints, overshoot) {
    var maxFractionalChange = 0;
    var thisPt;
    var i;
    var j;
    var p;
    var q;
    var neighborShift;
    var neighborRow;
    var neighborVal;
    var neighborCount;
    var neighborSum;
    var initialVal;
    var minNeighbor;
    var maxNeighbor;

    for(p = 0; p < emptyPoints.length; p++) {
        thisPt = emptyPoints[p];
        i = thisPt[0];
        j = thisPt[1];
        initialVal = z[i][j];
        neighborSum = 0;
        neighborCount = 0;

        for(q = 0; q < 4; q++) {
            neighborShift = NEIGHBORSHIFTS[q];
            neighborRow = z[i + neighborShift[0]];
            if(!neighborRow) continue;
            neighborVal = neighborRow[j + neighborShift[1]];
            if(neighborVal !== undefined) {
                if(neighborSum === 0) {
                    minNeighbor = maxNeighbor = neighborVal;
                }
                else {
                    minNeighbor = Math.min(minNeighbor, neighborVal);
                    maxNeighbor = Math.max(maxNeighbor, neighborVal);
                }
                neighborCount++;
                neighborSum += neighborVal;
            }
        }

        if(neighborCount === 0) {
            throw 'iterateInterp2d order is wrong: no defined neighbors';
        }

        // this is the laplace equation interpolation:
        // each point is just the average of its neighbors
        // note that this ignores differential x/y scaling
        // which I think is the right approach, since we
        // don't know what that scaling means
        z[i][j] = neighborSum / neighborCount;

        if(initialVal === undefined) {
            if(neighborCount < 4) maxFractionalChange = 1;
        }
        else {
            // we can make large empty regions converge faster
            // if we overshoot the change vs the previous value
            z[i][j] = (1 + overshoot) * z[i][j] - overshoot * initialVal;

            if(maxNeighbor > minNeighbor) {
                maxFractionalChange = Math.max(maxFractionalChange,
                    Math.abs(z[i][j] - initialVal) / (maxNeighbor - minNeighbor));
            }
        }
    }

    return maxFractionalChange;
}

},{"../../lib":694}],954:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');
var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;

module.exports = function makeBoundArray(trace, arrayIn, v0In, dvIn, numbricks, ax) {
    var arrayOut = [];
    var isContour = Registry.traceIs(trace, 'contour');
    var isHist = Registry.traceIs(trace, 'histogram');
    var isGL2D = Registry.traceIs(trace, 'gl2d');
    var v0;
    var dv;
    var i;

    var isArrayOfTwoItemsOrMore = isArrayOrTypedArray(arrayIn) && arrayIn.length > 1;

    if(isArrayOfTwoItemsOrMore && !isHist && (ax.type !== 'category')) {
        var len = arrayIn.length;

        // given vals are brick centers
        // hopefully length === numbricks, but use this method even if too few are supplied
        // and extend it linearly based on the last two points
        if(len <= numbricks) {
            // contour plots only want the centers
            if(isContour || isGL2D) arrayOut = arrayIn.slice(0, numbricks);
            else if(numbricks === 1) {
                arrayOut = [arrayIn[0] - 0.5, arrayIn[0] + 0.5];
            }
            else {
                arrayOut = [1.5 * arrayIn[0] - 0.5 * arrayIn[1]];

                for(i = 1; i < len; i++) {
                    arrayOut.push((arrayIn[i - 1] + arrayIn[i]) * 0.5);
                }

                arrayOut.push(1.5 * arrayIn[len - 1] - 0.5 * arrayIn[len - 2]);
            }

            if(len < numbricks) {
                var lastPt = arrayOut[arrayOut.length - 1];
                var delta = lastPt - arrayOut[arrayOut.length - 2];

                for(i = len; i < numbricks; i++) {
                    lastPt += delta;
                    arrayOut.push(lastPt);
                }
            }
        }
        else {
            // hopefully length === numbricks+1, but do something regardless:
            // given vals are brick boundaries
            return isContour ?
                arrayIn.slice(0, numbricks) :  // we must be strict for contours
                arrayIn.slice(0, numbricks + 1);
        }
    }
    else {
        dv = dvIn || 1;

        var calendar = trace[ax._id.charAt(0) + 'calendar'];

        if(isHist || ax.type === 'category' || ax.type === 'multicategory') {
            v0 = ax.r2c(v0In, 0, calendar) || 0;
        } else if(isArrayOrTypedArray(arrayIn) && arrayIn.length === 1) {
            v0 = arrayIn[0];
        } else if(v0In === undefined) {
            v0 = 0;
        } else {
            v0 = ax.d2c(v0In, 0, calendar);
        }

        for(i = (isContour || isGL2D) ? 0 : -0.5; i < numbricks; i++) {
            arrayOut.push(v0 + dv * i);
        }
    }

    return arrayOut;
};

},{"../../lib":694,"../../registry":825}],955:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var tinycolor = _dereq_('tinycolor2');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Colorscale = _dereq_('../../components/colorscale');
var xmlnsNamespaces = _dereq_('../../constants/xmlns_namespaces');

module.exports = function(gd, plotinfo, cdheatmaps, heatmapLayer) {
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    Lib.makeTraceGroups(heatmapLayer, cdheatmaps, 'hm').each(function(cd) {
        var plotGroup = d3.select(this);
        var cd0 = cd[0];
        var trace = cd0.trace;

        var z = cd0.z;
        var x = cd0.x;
        var y = cd0.y;
        var xc = cd0.xCenter;
        var yc = cd0.yCenter;
        var isContour = Registry.traceIs(trace, 'contour');
        var zsmooth = isContour ? 'best' : trace.zsmooth;

        // get z dims
        var m = z.length;
        var n = Lib.maxRowLength(z);
        var xrev = false;
        var yrev = false;

        var left, right, temp, top, bottom, i;

        // TODO: if there are multiple overlapping categorical heatmaps,
        // or if we allow category sorting, then the categories may not be
        // sequential... may need to reorder and/or expand z

        // Get edges of png in pixels (xa.c2p() maps axes coordinates to pixel coordinates)
        // figure out if either axis is reversed (y is usually reversed, in pixel coords)
        // also clip the image to maximum 50% outside the visible plot area
        // bigger image lets you pan more naturally, but slows performance.
        // TODO: use low-resolution images outside the visible plot for panning
        // these while loops find the first and last brick bounds that are defined
        // (in case of log of a negative)
        i = 0;
        while(left === undefined && i < x.length - 1) {
            left = xa.c2p(x[i]);
            i++;
        }
        i = x.length - 1;
        while(right === undefined && i > 0) {
            right = xa.c2p(x[i]);
            i--;
        }

        if(right < left) {
            temp = right;
            right = left;
            left = temp;
            xrev = true;
        }

        i = 0;
        while(top === undefined && i < y.length - 1) {
            top = ya.c2p(y[i]);
            i++;
        }
        i = y.length - 1;
        while(bottom === undefined && i > 0) {
            bottom = ya.c2p(y[i]);
            i--;
        }

        if(bottom < top) {
            temp = top;
            top = bottom;
            bottom = temp;
            yrev = true;
        }

        // for contours with heatmap fill, we generate the boundaries based on
        // brick centers but then use the brick edges for drawing the bricks
        if(isContour) {
            xc = x;
            yc = y;
            x = cd0.xfill;
            y = cd0.yfill;
        }

        // make an image that goes at most half a screen off either side, to keep
        // time reasonable when you zoom in. if zsmooth is true/fast, don't worry
        // about this, because zooming doesn't increase number of pixels
        // if zsmooth is best, don't include anything off screen because it takes too long
        if(zsmooth !== 'fast') {
            var extra = zsmooth === 'best' ? 0 : 0.5;
            left = Math.max(-extra * xa._length, left);
            right = Math.min((1 + extra) * xa._length, right);
            top = Math.max(-extra * ya._length, top);
            bottom = Math.min((1 + extra) * ya._length, bottom);
        }

        var imageWidth = Math.round(right - left);
        var imageHeight = Math.round(bottom - top);

        // setup image nodes

        // if image is entirely off-screen, don't even draw it
        var isOffScreen = (imageWidth <= 0 || imageHeight <= 0);

        if(isOffScreen) {
            var noImage = plotGroup.selectAll('image').data([]);
            noImage.exit().remove();
            return;
        }

        // generate image data

        var canvasW, canvasH;
        if(zsmooth === 'fast') {
            canvasW = n;
            canvasH = m;
        } else {
            canvasW = imageWidth;
            canvasH = imageHeight;
        }

        var canvas = document.createElement('canvas');
        canvas.width = canvasW;
        canvas.height = canvasH;
        var context = canvas.getContext('2d');

        var sclFunc = Colorscale.makeColorScaleFunc(
            Colorscale.extractScale(trace, {cLetter: 'z'}),
            { noNumericCheck: true, returnArray: true }
        );

        // map brick boundaries to image pixels
        var xpx,
            ypx;
        if(zsmooth === 'fast') {
            xpx = xrev ?
                function(index) { return n - 1 - index; } :
                Lib.identity;
            ypx = yrev ?
                function(index) { return m - 1 - index; } :
                Lib.identity;
        }
        else {
            xpx = function(index) {
                return Lib.constrain(Math.round(xa.c2p(x[index]) - left),
                    0, imageWidth);
            };
            ypx = function(index) {
                return Lib.constrain(Math.round(ya.c2p(y[index]) - top),
                    0, imageHeight);
            };
        }

        // build the pixel map brick-by-brick
        // cruise through z-matrix row-by-row
        // build a brick at each z-matrix value
        var yi = ypx(0);
        var yb = [yi, yi];
        var xbi = xrev ? 0 : 1;
        var ybi = yrev ? 0 : 1;
        // for collecting an average luminosity of the heatmap
        var pixcount = 0;
        var rcount = 0;
        var gcount = 0;
        var bcount = 0;

        var xb, j, xi, v, row, c;

        function setColor(v, pixsize) {
            if(v !== undefined) {
                var c = sclFunc(v);
                c[0] = Math.round(c[0]);
                c[1] = Math.round(c[1]);
                c[2] = Math.round(c[2]);

                pixcount += pixsize;
                rcount += c[0] * pixsize;
                gcount += c[1] * pixsize;
                bcount += c[2] * pixsize;
                return c;
            }
            return [0, 0, 0, 0];
        }

        function interpColor(r0, r1, xinterp, yinterp) {
            var z00 = r0[xinterp.bin0];
            if(z00 === undefined) return setColor(undefined, 1);

            var z01 = r0[xinterp.bin1];
            var z10 = r1[xinterp.bin0];
            var z11 = r1[xinterp.bin1];
            var dx = (z01 - z00) || 0;
            var dy = (z10 - z00) || 0;
            var dxy;

            // the bilinear interpolation term needs different calculations
            // for all the different permutations of missing data
            // among the neighbors of the main point, to ensure
            // continuity across brick boundaries.
            if(z01 === undefined) {
                if(z11 === undefined) dxy = 0;
                else if(z10 === undefined) dxy = 2 * (z11 - z00);
                else dxy = (2 * z11 - z10 - z00) * 2 / 3;
            }
            else if(z11 === undefined) {
                if(z10 === undefined) dxy = 0;
                else dxy = (2 * z00 - z01 - z10) * 2 / 3;
            }
            else if(z10 === undefined) dxy = (2 * z11 - z01 - z00) * 2 / 3;
            else dxy = (z11 + z00 - z01 - z10);

            return setColor(z00 + xinterp.frac * dx + yinterp.frac * (dy + xinterp.frac * dxy));
        }

        if(zsmooth) { // best or fast, works fastest with imageData
            var pxIndex = 0;
            var pixels;

            try {
                pixels = new Uint8Array(imageWidth * imageHeight * 4);
            } catch(e) {
                pixels = new Array(imageWidth * imageHeight * 4);
            }

            if(zsmooth === 'best') {
                var xForPx = xc || x;
                var yForPx = yc || y;
                var xPixArray = new Array(xForPx.length);
                var yPixArray = new Array(yForPx.length);
                var xinterpArray = new Array(imageWidth);
                var findInterpX = xc ? findInterpFromCenters : findInterp;
                var findInterpY = yc ? findInterpFromCenters : findInterp;
                var yinterp, r0, r1;

                // first make arrays of x and y pixel locations of brick boundaries
                for(i = 0; i < xForPx.length; i++) xPixArray[i] = Math.round(xa.c2p(xForPx[i]) - left);
                for(i = 0; i < yForPx.length; i++) yPixArray[i] = Math.round(ya.c2p(yForPx[i]) - top);

                // then make arrays of interpolations
                // (bin0=closest, bin1=next, frac=fractional dist.)
                for(i = 0; i < imageWidth; i++) xinterpArray[i] = findInterpX(i, xPixArray);

                // now do the interpolations and fill the png
                for(j = 0; j < imageHeight; j++) {
                    yinterp = findInterpY(j, yPixArray);
                    r0 = z[yinterp.bin0];
                    r1 = z[yinterp.bin1];
                    for(i = 0; i < imageWidth; i++, pxIndex += 4) {
                        c = interpColor(r0, r1, xinterpArray[i], yinterp);
                        putColor(pixels, pxIndex, c);
                    }
                }
            }
            else { // zsmooth = fast
                for(j = 0; j < m; j++) {
                    row = z[j];
                    yb = ypx(j);
                    for(i = 0; i < imageWidth; i++) {
                        c = setColor(row[i], 1);
                        pxIndex = (yb * imageWidth + xpx(i)) * 4;
                        putColor(pixels, pxIndex, c);
                    }
                }
            }

            var imageData = context.createImageData(imageWidth, imageHeight);
            try {
                imageData.data.set(pixels);
            } catch(e) {
                var pxArray = imageData.data;
                var dlen = pxArray.length;
                for(j = 0; j < dlen; j ++) {
                    pxArray[j] = pixels[j];
                }
            }

            context.putImageData(imageData, 0, 0);
        } else { // zsmooth = false -> filling potentially large bricks works fastest with fillRect

            // gaps do not need to be exact integers, but if they *are* we will get
            // cleaner edges by rounding at least one edge
            var xGap = trace.xgap;
            var yGap = trace.ygap;
            var xGapLeft = Math.floor(xGap / 2);
            var yGapTop = Math.floor(yGap / 2);

            for(j = 0; j < m; j++) {
                row = z[j];
                yb.reverse();
                yb[ybi] = ypx(j + 1);
                if(yb[0] === yb[1] || yb[0] === undefined || yb[1] === undefined) {
                    continue;
                }
                xi = xpx(0);
                xb = [xi, xi];
                for(i = 0; i < n; i++) {
                    // build one color brick!
                    xb.reverse();
                    xb[xbi] = xpx(i + 1);
                    if(xb[0] === xb[1] || xb[0] === undefined || xb[1] === undefined) {
                        continue;
                    }
                    v = row[i];
                    c = setColor(v, (xb[1] - xb[0]) * (yb[1] - yb[0]));
                    context.fillStyle = 'rgba(' + c.join(',') + ')';

                    context.fillRect(xb[0] + xGapLeft, yb[0] + yGapTop,
                        xb[1] - xb[0] - xGap, yb[1] - yb[0] - yGap);
                }
            }
        }

        rcount = Math.round(rcount / pixcount);
        gcount = Math.round(gcount / pixcount);
        bcount = Math.round(bcount / pixcount);
        var avgColor = tinycolor('rgb(' + rcount + ',' + gcount + ',' + bcount + ')');

        gd._hmpixcount = (gd._hmpixcount||0) + pixcount;
        gd._hmlumcount = (gd._hmlumcount||0) + pixcount * avgColor.getLuminance();

        var image3 = plotGroup.selectAll('image')
            .data(cd);

        image3.enter().append('svg:image').attr({
            xmlns: xmlnsNamespaces.svg,
            preserveAspectRatio: 'none'
        });

        image3.attr({
            height: imageHeight,
            width: imageWidth,
            x: left,
            y: top,
            'xlink:href': canvas.toDataURL('image/png')
        });
    });
};

// get interpolated bin value. Returns {bin0:closest bin, frac:fractional dist to next, bin1:next bin}
function findInterp(pixel, pixArray) {
    var maxBin = pixArray.length - 2;
    var bin = Lib.constrain(Lib.findBin(pixel, pixArray), 0, maxBin);
    var pix0 = pixArray[bin];
    var pix1 = pixArray[bin + 1];
    var interp = Lib.constrain(bin + (pixel - pix0) / (pix1 - pix0) - 0.5, 0, maxBin);
    var bin0 = Math.round(interp);
    var frac = Math.abs(interp - bin0);

    if(!interp || interp === maxBin || !frac) {
        return {
            bin0: bin0,
            bin1: bin0,
            frac: 0
        };
    }
    return {
        bin0: bin0,
        frac: frac,
        bin1: Math.round(bin0 + frac / (interp - bin0))
    };
}

function findInterpFromCenters(pixel, centerPixArray) {
    var maxBin = centerPixArray.length - 1;
    var bin = Lib.constrain(Lib.findBin(pixel, centerPixArray), 0, maxBin);
    var pix0 = centerPixArray[bin];
    var pix1 = centerPixArray[bin + 1];
    var frac = ((pixel - pix0) / (pix1 - pix0)) || 0;
    if(frac <= 0) {
        return {
            bin0: bin,
            bin1: bin,
            frac: 0
        };
    }
    if(frac < 0.5) {
        return {
            bin0: bin,
            bin1: bin + 1,
            frac: frac
        };
    }
    return {
        bin0: bin + 1,
        bin1: bin,
        frac: 1 - frac
    };
}

function putColor(pixels, pxIndex, c) {
    pixels[pxIndex] = c[0];
    pixels[pxIndex + 1] = c[1];
    pixels[pxIndex + 2] = c[2];
    pixels[pxIndex + 3] = Math.round(c[3] * 255);
}

},{"../../components/colorscale":583,"../../constants/xmlns_namespaces":672,"../../lib":694,"../../registry":825,"d3":149,"tinycolor2":515}],956:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

module.exports = function style(gd) {
    d3.select(gd).selectAll('.hm image')
        .style('opacity', function(d) {
            return d.trace.opacity;
        });
};

},{"d3":149}],957:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = function handleStyleDefaults(traceIn, traceOut, coerce) {
    var zsmooth = coerce('zsmooth');
    if(zsmooth === false) {
        // ensure that xgap and ygap are coerced only when zsmooth allows them to have an effect.
        coerce('xgap');
        coerce('ygap');
    }

    coerce('zhoverformat');
};

},{}],958:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var Lib = _dereq_('../../lib');

var Registry = _dereq_('../../registry');

module.exports = function handleXYZDefaults(traceIn, traceOut, coerce, layout, xName, yName) {
    var z = coerce('z');
    xName = xName || 'x';
    yName = yName || 'y';
    var x, y;

    if(z === undefined || !z.length) return 0;

    if(Lib.isArray1D(traceIn.z)) {
        x = coerce(xName);
        y = coerce(yName);

        var xlen = Lib.minRowLength(x);
        var ylen = Lib.minRowLength(y);

        // column z must be accompanied by xName and yName arrays
        if(xlen === 0 || ylen === 0) return 0;

        traceOut._length = Math.min(xlen, ylen, z.length);
    }
    else {
        x = coordDefaults(xName, coerce);
        y = coordDefaults(yName, coerce);

        // TODO put z validation elsewhere
        if(!isValidZ(z)) return 0;

        coerce('transpose');

        traceOut._length = null;
    }

    var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
    handleCalendarDefaults(traceIn, traceOut, [xName, yName], layout);

    return true;
};

function coordDefaults(coordStr, coerce) {
    var coord = coerce(coordStr);
    var coordType = coord ? coerce(coordStr + 'type', 'array') : 'scaled';

    if(coordType === 'scaled') {
        coerce(coordStr + '0');
        coerce('d' + coordStr);
    }

    return coord;
}

function isValidZ(z) {
    var allRowsAreArrays = true;
    var oneRowIsFilled = false;
    var hasOneNumber = false;
    var zi;

    /*
     * Without this step:
     *
     * hasOneNumber = false breaks contour but not heatmap
     * allRowsAreArrays = false breaks contour but not heatmap
     * oneRowIsFilled = false breaks both
     */

    for(var i = 0; i < z.length; i++) {
        zi = z[i];
        if(!Lib.isArrayOrTypedArray(zi)) {
            allRowsAreArrays = false;
            break;
        }
        if(zi.length > 0) oneRowIsFilled = true;
        for(var j = 0; j < zi.length; j++) {
            if(isNumeric(zi[j])) {
                hasOneNumber = true;
                break;
            }
        }
    }

    return (allRowsAreArrays && oneRowIsFilled && hasOneNumber);
}

},{"../../lib":694,"../../registry":825,"fast-isnumeric":215}],959:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


var heatmapAttrs = _dereq_('../heatmap/attributes');
var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;


var commonList = [
    'z',
    'x', 'x0', 'dx',
    'y', 'y0', 'dy',
    'text', 'transpose',
    'xtype', 'ytype'
];

var attrs = {};

for(var i = 0; i < commonList.length; i++) {
    var k = commonList[i];
    attrs[k] = heatmapAttrs[k];
}

extendFlat(
    attrs,
    colorscaleAttrs('', {cLetter: 'z', autoColorDflt: false}),
    {colorbar: colorbarAttrs}
);

module.exports = overrideAll(attrs, 'calc', 'nested');

},{"../../components/colorbar/attributes":572,"../../components/colorscale/attributes":578,"../../lib/extend":684,"../../plot_api/edit_types":725,"../heatmap/attributes":944}],960:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var createHeatmap2D = _dereq_('gl-heatmap2d');
var Axes = _dereq_('../../plots/cartesian/axes');
var str2RGBArray = _dereq_('../../lib/str2rgbarray');


function Heatmap(scene, uid) {
    this.scene = scene;
    this.uid = uid;
    this.type = 'heatmapgl';

    this.name = '';
    this.hoverinfo = 'all';

    this.xData = [];
    this.yData = [];
    this.zData = [];
    this.textLabels = [];

    this.idToIndex = [];
    this.bounds = [0, 0, 0, 0];

    this.options = {
        z: [],
        x: [],
        y: [],
        shape: [0, 0],
        colorLevels: [0],
        colorValues: [0, 0, 0, 1]
    };

    this.heatmap = createHeatmap2D(scene.glplot, this.options);
    this.heatmap._trace = this;
}

var proto = Heatmap.prototype;

proto.handlePick = function(pickResult) {
    var options = this.options;
    var shape = options.shape;
    var index = pickResult.pointId;
    var xIndex = index % shape[0];
    var yIndex = Math.floor(index / shape[0]);
    var zIndex = index;

    return {
        trace: this,
        dataCoord: pickResult.dataCoord,
        traceCoord: [
            options.x[xIndex],
            options.y[yIndex],
            options.z[zIndex]
        ],
        textLabel: this.textLabels[index],
        name: this.name,
        pointIndex: [yIndex, xIndex],
        hoverinfo: this.hoverinfo
    };
};

proto.update = function(fullTrace, calcTrace) {
    var calcPt = calcTrace[0];

    this.index = fullTrace.index;
    this.name = fullTrace.name;
    this.hoverinfo = fullTrace.hoverinfo;

    // convert z from 2D -> 1D
    var z = calcPt.z;
    this.options.z = [].concat.apply([], z);

    var rowLen = z[0].length;
    var colLen = z.length;
    this.options.shape = [rowLen, colLen];

    this.options.x = calcPt.x;
    this.options.y = calcPt.y;

    var colorOptions = convertColorscale(fullTrace);
    this.options.colorLevels = colorOptions.colorLevels;
    this.options.colorValues = colorOptions.colorValues;

    // convert text from 2D -> 1D
    this.textLabels = [].concat.apply([], fullTrace.text);

    this.heatmap.update(this.options);

    var xa = this.scene.xaxis;
    var ya = this.scene.yaxis;
    fullTrace._extremes[xa._id] = Axes.findExtremes(xa, calcPt.x);
    fullTrace._extremes[ya._id] = Axes.findExtremes(ya, calcPt.y);
};

proto.dispose = function() {
    this.heatmap.dispose();
};

function convertColorscale(fullTrace) {
    var scl = fullTrace.colorscale;
    var zmin = fullTrace.zmin;
    var zmax = fullTrace.zmax;

    var N = scl.length;
    var domain = new Array(N);
    var range = new Array(4 * N);

    for(var i = 0; i < N; i++) {
        var si = scl[i];
        var color = str2RGBArray(si[1]);

        domain[i] = zmin + si[0] * (zmax - zmin);

        for(var j = 0; j < 4; j++) {
            range[(4 * i) + j] = color[j];
        }
    }

    return {
        colorLevels: domain,
        colorValues: range
    };
}

function createHeatmap(scene, fullTrace, calcTrace) {
    var plot = new Heatmap(scene, fullTrace.uid);
    plot.update(fullTrace, calcTrace);
    return plot;
}

module.exports = createHeatmap;

},{"../../lib/str2rgbarray":717,"../../plots/cartesian/axes":742,"gl-heatmap2d":242}],961:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var HeatmapGl = {};

HeatmapGl.attributes = _dereq_('./attributes');
HeatmapGl.supplyDefaults = _dereq_('../heatmap/defaults');
HeatmapGl.colorbar = _dereq_('../heatmap/colorbar');

HeatmapGl.calc = _dereq_('../heatmap/calc');
HeatmapGl.plot = _dereq_('./convert');

HeatmapGl.moduleType = 'trace';
HeatmapGl.name = 'heatmapgl';
HeatmapGl.basePlotModule = _dereq_('../../plots/gl2d');
HeatmapGl.categories = ['gl', 'gl2d', '2dMap'];
HeatmapGl.meta = {
    
};

module.exports = HeatmapGl;

},{"../../plots/gl2d":782,"../heatmap/calc":945,"../heatmap/colorbar":947,"../heatmap/defaults":949,"./attributes":959,"./convert":960}],962:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var barAttrs = _dereq_('../bar/attributes');
var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var makeBinAttrs = _dereq_('./bin_attributes');
var constants = _dereq_('./constants');

module.exports = {
    x: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },
    y: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },

    text: barAttrs.text,
    orientation: barAttrs.orientation,

    histfunc: {
        valType: 'enumerated',
        values: ['count', 'sum', 'avg', 'min', 'max'],
        
        dflt: 'count',
        editType: 'calc',
        
    },
    histnorm: {
        valType: 'enumerated',
        values: ['', 'percent', 'probability', 'density', 'probability density'],
        dflt: '',
        
        editType: 'calc',
        
    },

    cumulative: {
        enabled: {
            valType: 'boolean',
            dflt: false,
            
            editType: 'calc',
            
        },

        direction: {
            valType: 'enumerated',
            values: ['increasing', 'decreasing'],
            dflt: 'increasing',
            
            editType: 'calc',
            
        },

        currentbin: {
            valType: 'enumerated',
            values: ['include', 'exclude', 'half'],
            dflt: 'include',
            
            editType: 'calc',
            
        },
        editType: 'calc'
    },
    nbinsx: {
        valType: 'integer',
        min: 0,
        dflt: 0,
        
        editType: 'calc',
        
    },
    xbins: makeBinAttrs('x', true),

    nbinsy: {
        valType: 'integer',
        min: 0,
        dflt: 0,
        
        editType: 'calc',
        
    },
    ybins: makeBinAttrs('y', true),
    autobinx: {
        valType: 'boolean',
        dflt: null,
        
        editType: 'calc',
        
    },
    autobiny: {
        valType: 'boolean',
        dflt: null,
        
        editType: 'calc',
        
    },

    hovertemplate: hovertemplateAttrs({}, {
        keys: constants.eventDataKeys
    }),

    marker: barAttrs.marker,

    selected: barAttrs.selected,
    unselected: barAttrs.unselected,

    _deprecated: {
        bardir: barAttrs._deprecated.bardir
    }
};

},{"../../components/fx/hovertemplate_attributes":609,"../bar/attributes":835,"./bin_attributes":964,"./constants":968}],963:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


module.exports = function doAvg(size, counts) {
    var nMax = size.length;
    var total = 0;
    for(var i = 0; i < nMax; i++) {
        if(counts[i]) {
            size[i] /= counts[i];
            total += size[i];
        }
        else size[i] = null;
    }
    return total;
};

},{}],964:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function makeBinAttrs(axLetter, match) {
    return {
        start: {
            valType: 'any', // for date axes
            
            editType: 'calc',
            
        },
        end: {
            valType: 'any', // for date axes
            
            editType: 'calc',
            
        },
        size: {
            valType: 'any', // for date axes
            
            editType: 'calc',
            
        },
        editType: 'calc'
    };
};

},{}],965:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');


module.exports = {
    count: function(n, i, size) {
        size[n]++;
        return 1;
    },

    sum: function(n, i, size, counterData) {
        var v = counterData[i];
        if(isNumeric(v)) {
            v = Number(v);
            size[n] += v;
            return v;
        }
        return 0;
    },

    avg: function(n, i, size, counterData, counts) {
        var v = counterData[i];
        if(isNumeric(v)) {
            v = Number(v);
            size[n] += v;
            counts[n]++;
        }
        return 0;
    },

    min: function(n, i, size, counterData) {
        var v = counterData[i];
        if(isNumeric(v)) {
            v = Number(v);
            if(!isNumeric(size[n])) {
                size[n] = v;
                return v;
            }
            else if(size[n] > v) {
                var delta = v - size[n];
                size[n] = v;
                return delta;
            }
        }
        return 0;
    },

    max: function(n, i, size, counterData) {
        var v = counterData[i];
        if(isNumeric(v)) {
            v = Number(v);
            if(!isNumeric(size[n])) {
                size[n] = v;
                return v;
            }
            else if(size[n] < v) {
                var delta = v - size[n];
                size[n] = v;
                return delta;
            }
        }
        return 0;
    }
};

},{"fast-isnumeric":215}],966:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var numConstants = _dereq_('../../constants/numerical');
var oneYear = numConstants.ONEAVGYEAR;
var oneMonth = numConstants.ONEAVGMONTH;
var oneDay = numConstants.ONEDAY;
var oneHour = numConstants.ONEHOUR;
var oneMin = numConstants.ONEMIN;
var oneSec = numConstants.ONESEC;
var tickIncrement = _dereq_('../../plots/cartesian/axes').tickIncrement;


/*
 * make a function that will find rounded bin edges
 * @param {number} leftGap: how far from the left edge of any bin is the closest data value?
 * @param {number} rightGap: how far from the right edge of any bin is the closest data value?
 * @param {Array[number]} binEdges: the actual edge values used in binning
 * @param {object} pa: the position axis
 * @param {string} calendar: the data calendar
 *
 * @return {function(v, isRightEdge)}:
 *   find the start (isRightEdge is falsy) or end (truthy) label value for a bin edge `v`
 */
module.exports = function getBinSpanLabelRound(leftGap, rightGap, binEdges, pa, calendar) {
    // the rounding digit is the largest digit that changes in *all* of 4 regions:
    // - inside the rightGap before binEdges[0] (shifted 10% to the left)
    // - inside the leftGap after binEdges[0] (expanded by 10% of rightGap on each end)
    // - same for binEdges[1]
    var dv0 = -1.1 * rightGap;
    var dv1 = -0.1 * rightGap;
    var dv2 = leftGap - dv1;
    var edge0 = binEdges[0];
    var edge1 = binEdges[1];
    var leftDigit = Math.min(
        biggestDigitChanged(edge0 + dv1, edge0 + dv2, pa, calendar),
        biggestDigitChanged(edge1 + dv1, edge1 + dv2, pa, calendar)
    );
    var rightDigit = Math.min(
        biggestDigitChanged(edge0 + dv0, edge0 + dv1, pa, calendar),
        biggestDigitChanged(edge1 + dv0, edge1 + dv1, pa, calendar)
    );

    // normally we try to make the label for the right edge different from
    // the left edge label, so it's unambiguous which bin gets data on the edge.
    // but if this results in more than 3 extra digits (or for dates, more than
    // 2 fields ie hr&min or min&sec, which is 3600x), it'll be more clutter than
    // useful so keep the label cleaner instead
    var digit, disambiguateEdges;
    if(leftDigit > rightDigit && rightDigit < Math.abs(edge1 - edge0) / 4000) {
        digit = leftDigit;
        disambiguateEdges = false;
    }
    else {
        digit = Math.min(leftDigit, rightDigit);
        disambiguateEdges = true;
    }

    if(pa.type === 'date' && digit > oneDay) {
        var dashExclude = (digit === oneYear) ? 1 : 6;
        var increment = (digit === oneYear) ? 'M12' : 'M1';

        return function(v, isRightEdge) {
            var dateStr = pa.c2d(v, oneYear, calendar);
            var dashPos = dateStr.indexOf('-', dashExclude);
            if(dashPos > 0) dateStr = dateStr.substr(0, dashPos);
            var roundedV = pa.d2c(dateStr, 0, calendar);

            if(roundedV < v) {
                var nextV = tickIncrement(roundedV, increment, false, calendar);
                if((roundedV + nextV) / 2 < v + leftGap) roundedV = nextV;
            }

            if(isRightEdge && disambiguateEdges) {
                return tickIncrement(roundedV, increment, true, calendar);
            }

            return roundedV;
        };
    }

    return function(v, isRightEdge) {
        var roundedV = digit * Math.round(v / digit);
        // if we rounded down and we could round up and still be < leftGap
        // (or what leftGap values round to), do that
        if(roundedV + (digit / 10) < v && roundedV + (digit * 0.9) < v + leftGap) {
            roundedV += digit;
        }
        // finally for the right edge back off one digit - but only if we can do that
        // and not clip off any data that's potentially in the bin
        if(isRightEdge && disambiguateEdges) {
            roundedV -= digit;
        }
        return roundedV;
    };
};

/*
 * Find the largest digit that changes within a (calcdata) region [v1, v2]
 * if dates, "digit" means date/time part when it's bigger than a second
 * returns the unit value to round to this digit, eg 0.01 to round to hundredths, or
 * 100 to round to hundreds. returns oneMonth or oneYear for month or year rounding,
 * so that Math.min will work, rather than 'M1' and 'M12'
 */
function biggestDigitChanged(v1, v2, pa, calendar) {
    // are we crossing zero? can't say anything.
    // in principle this doesn't apply to dates but turns out this doesn't matter.
    if(v1 * v2 <= 0) return Infinity;

    var dv = Math.abs(v2 - v1);
    var isDate = pa.type === 'date';
    var digit = biggestGuaranteedDigitChanged(dv, isDate);
    // see if a larger digit also changed
    for(var i = 0; i < 10; i++) {
        // numbers: next digit needs to be >10x but <100x then gets rounded down.
        // dates: next digit can be as much as 60x (then rounded down)
        var nextDigit = biggestGuaranteedDigitChanged(digit * 80, isDate);
        // if we get to years, the chain stops
        if(digit === nextDigit) break;
        if(didDigitChange(nextDigit, v1, v2, isDate, pa, calendar)) digit = nextDigit;
        else break;
    }
    return digit;
}

/*
 * Find the largest digit that *definitely* changes in a region [v, v + dv] for any v
 * for nonuniform date regions (months/years) pick the largest
 */
function biggestGuaranteedDigitChanged(dv, isDate) {
    if(isDate && dv > oneSec) {
        // this is supposed to be the biggest *guaranteed* change
        // so compare to the longest month and year across any calendar,
        // and we'll iterate back up later
        // note: does not support rounding larger than one year. We could add
        // that if anyone wants it, but seems unusual and not strictly necessary.
        if(dv > oneDay) {
            if(dv > oneYear * 1.1) return oneYear;
            if(dv > oneMonth * 1.1) return oneMonth;
            return oneDay;
        }

        if(dv > oneHour) return oneHour;
        if(dv > oneMin) return oneMin;
        return oneSec;
    }
    return Math.pow(10, Math.floor(Math.log(dv) / Math.LN10));
}

function didDigitChange(digit, v1, v2, isDate, pa, calendar) {
    if(isDate && digit > oneDay) {
        var dateParts1 = dateParts(v1, pa, calendar);
        var dateParts2 = dateParts(v2, pa, calendar);
        var parti = (digit === oneYear) ? 0 : 1;
        return dateParts1[parti] !== dateParts2[parti];

    }
    return Math.floor(v2 / digit) - Math.floor(v1 / digit) > 0.1;
}

function dateParts(v, pa, calendar) {
    var parts = pa.c2d(v, oneYear, calendar).split('-');
    if(parts[0] === '') {
        parts.unshift();
        parts[0] = '-' + parts[0];
    }
    return parts;
}

},{"../../constants/numerical":671,"../../plots/cartesian/axes":742}],967:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');

var arraysToCalcdata = _dereq_('../bar/arrays_to_calcdata');
var binFunctions = _dereq_('./bin_functions');
var normFunctions = _dereq_('./norm_functions');
var doAvg = _dereq_('./average');
var getBinSpanLabelRound = _dereq_('./bin_label_vals');

module.exports = function calc(gd, trace) {
    // ignore as much processing as possible (and including in autorange) if not visible
    if(trace.visible !== true) return;

    // depending on orientation, set position and size axes and data ranges
    // note: this logic for choosing orientation is duplicated in graph_obj->setstyles
    var pos = [];
    var size = [];
    var pa = Axes.getFromId(gd, trace.orientation === 'h' ?
        (trace.yaxis || 'y') : (trace.xaxis || 'x'));
    var mainData = trace.orientation === 'h' ? 'y' : 'x';
    var counterData = {x: 'y', y: 'x'}[mainData];
    var calendar = trace[mainData + 'calendar'];
    var cumulativeSpec = trace.cumulative;
    var i;

    var binsAndPos = calcAllAutoBins(gd, trace, pa, mainData);
    var binSpec = binsAndPos[0];
    var pos0 = binsAndPos[1];

    var nonuniformBins = typeof binSpec.size === 'string';
    var binEdges = [];
    var bins = nonuniformBins ? binEdges : binSpec;
    // make the empty bin array
    var inc = [];
    var counts = [];
    var inputPoints = [];
    var total = 0;
    var norm = trace.histnorm;
    var func = trace.histfunc;
    var densityNorm = norm.indexOf('density') !== -1;
    var i2, binEnd, n;

    if(cumulativeSpec.enabled && densityNorm) {
        // we treat "cumulative" like it means "integral" if you use a density norm,
        // which in the end means it's the same as without "density"
        norm = norm.replace(/ ?density$/, '');
        densityNorm = false;
    }

    var extremeFunc = func === 'max' || func === 'min';
    var sizeInit = extremeFunc ? null : 0;
    var binFunc = binFunctions.count;
    var normFunc = normFunctions[norm];
    var isAvg = false;
    var pr2c = function(v) { return pa.r2c(v, 0, calendar); };
    var rawCounterData;

    if(Lib.isArrayOrTypedArray(trace[counterData]) && func !== 'count') {
        rawCounterData = trace[counterData];
        isAvg = func === 'avg';
        binFunc = binFunctions[func];
    }

    // create the bins (and any extra arrays needed)
    // assume more than 1e6 bins is an error, so we don't crash the browser
    i = pr2c(binSpec.start);

    // decrease end a little in case of rounding errors
    binEnd = pr2c(binSpec.end) + (i - Axes.tickIncrement(i, binSpec.size, false, calendar)) / 1e6;

    while(i < binEnd && pos.length < 1e6) {
        i2 = Axes.tickIncrement(i, binSpec.size, false, calendar);
        pos.push((i + i2) / 2);
        size.push(sizeInit);
        inputPoints.push([]);
        // nonuniform bins (like months) we need to search,
        // rather than straight calculate the bin we're in
        binEdges.push(i);
        // nonuniform bins also need nonuniform normalization factors
        if(densityNorm) inc.push(1 / (i2 - i));
        if(isAvg) counts.push(0);
        // break to avoid infinite loops
        if(i2 <= i) break;
        i = i2;
    }
    binEdges.push(i);

    // for date axes we need bin bounds to be calcdata. For nonuniform bins
    // we already have this, but uniform with start/end/size they're still strings.
    if(!nonuniformBins && pa.type === 'date') {
        bins = {
            start: pr2c(bins.start),
            end: pr2c(bins.end),
            size: bins.size
        };
    }

    // bin the data
    // and make histogram-specific pt-number-to-cd-index map object
    var nMax = size.length;
    var uniqueValsPerBin = true;
    var leftGap = Infinity;
    var rightGap = Infinity;
    var ptNumber2cdIndex = {};
    for(i = 0; i < pos0.length; i++) {
        var posi = pos0[i];
        n = Lib.findBin(posi, bins);
        if(n >= 0 && n < nMax) {
            total += binFunc(n, i, size, rawCounterData, counts);
            if(uniqueValsPerBin && inputPoints[n].length && posi !== pos0[inputPoints[n][0]]) {
                uniqueValsPerBin = false;
            }
            inputPoints[n].push(i);
            ptNumber2cdIndex[i] = n;

            leftGap = Math.min(leftGap, posi - binEdges[n]);
            rightGap = Math.min(rightGap, binEdges[n + 1] - posi);
        }
    }

    var roundFn;
    if(!uniqueValsPerBin) {
        roundFn = getBinSpanLabelRound(leftGap, rightGap, binEdges, pa, calendar);
    }

    // average and/or normalize the data, if needed
    if(isAvg) total = doAvg(size, counts);
    if(normFunc) normFunc(size, total, inc);

    // after all normalization etc, now we can accumulate if desired
    if(cumulativeSpec.enabled) cdf(size, cumulativeSpec.direction, cumulativeSpec.currentbin);


    var seriesLen = Math.min(pos.length, size.length);
    var cd = [];
    var firstNonzero = 0;
    var lastNonzero = seriesLen - 1;

    // look for empty bins at the ends to remove, so autoscale omits them
    for(i = 0; i < seriesLen; i++) {
        if(size[i]) {
            firstNonzero = i;
            break;
        }
    }
    for(i = seriesLen - 1; i >= firstNonzero; i--) {
        if(size[i]) {
            lastNonzero = i;
            break;
        }
    }

    // create the "calculated data" to plot
    for(i = firstNonzero; i <= lastNonzero; i++) {
        if((isNumeric(pos[i]) && isNumeric(size[i]))) {
            var cdi = {
                p: pos[i],
                s: size[i],
                b: 0
            };

            // setup hover and event data fields,
            // N.B. pts and "hover" positions ph0/ph1 don't seem to make much sense
            // for cumulative distributions
            if(!cumulativeSpec.enabled) {
                cdi.pts = inputPoints[i];
                if(uniqueValsPerBin) {
                    cdi.ph0 = cdi.ph1 = (inputPoints[i].length) ? pos0[inputPoints[i][0]] : pos[i];
                }
                else {
                    cdi.ph0 = roundFn(binEdges[i]);
                    cdi.ph1 = roundFn(binEdges[i + 1], true);
                }
            }
            cd.push(cdi);
        }
    }

    if(cd.length === 1) {
        // when we collapse to a single bin, calcdata no longer describes bin size
        // so we need to explicitly specify it
        cd[0].width1 = Axes.tickIncrement(cd[0].p, binSpec.size, false, calendar) - cd[0].p;
    }

    arraysToCalcdata(cd, trace);

    if(Lib.isArrayOrTypedArray(trace.selectedpoints)) {
        Lib.tagSelected(cd, trace, ptNumber2cdIndex);
    }

    return cd;
};

/*
 * calcAllAutoBins: we want all histograms on the same axes to share bin specs
 * if they're grouped or stacked. If the user has explicitly specified differing
 * bin specs, there's nothing we can do, but if possible we will try to use the
 * smallest bins of any of the auto values for all histograms grouped/stacked
 * together.
 */
function calcAllAutoBins(gd, trace, pa, mainData, _overlayEdgeCase) {
    var binAttr = mainData + 'bins';
    var fullLayout = gd._fullLayout;
    var isOverlay = fullLayout.barmode === 'overlay';
    var i, traces, tracei, calendar, pos0, autoVals, cumulativeSpec;

    var cleanBound = (pa.type === 'date') ?
        function(v) { return (v || v === 0) ? Lib.cleanDate(v, null, pa.calendar) : null; } :
        function(v) { return isNumeric(v) ? Number(v) : null; };

    function setBound(attr, bins, newBins) {
        if(bins[attr + 'Found']) {
            bins[attr] = cleanBound(bins[attr]);
            if(bins[attr] === null) bins[attr] = newBins[attr];
        }
        else {
            autoVals[attr] = bins[attr] = newBins[attr];
            Lib.nestedProperty(traces[0], binAttr + '.' + attr).set(newBins[attr]);
        }
    }

    var binOpts = fullLayout._histogramBinOpts[trace._groupName];

    // all but the first trace in this group has already been marked finished
    // clear this flag, so next time we run calc we will run autobin again
    if(trace._autoBinFinished) {
        delete trace._autoBinFinished;
    }
    else {
        traces = binOpts.traces;
        var sizeFound = binOpts.sizeFound;
        var allPos = [];
        autoVals = traces[0]._autoBin = {};
        // Note: we're including `legendonly` traces here for autobin purposes,
        // so that showing & hiding from the legend won't affect bins.
        // But this complicates things a bit since those traces don't `calc`,
        // hence `isFirstVisible`.
        var isFirstVisible = true;
        for(i = 0; i < traces.length; i++) {
            tracei = traces[i];
            if(tracei.visible) {
                pos0 = tracei._pos0 = pa.makeCalcdata(tracei, mainData);
                allPos = Lib.concat(allPos, pos0);
                delete tracei._autoBinFinished;
                if(trace.visible === true) {
                    if(isFirstVisible) {
                        isFirstVisible = false;
                    }
                    else {
                        delete tracei._autoBin;
                        tracei._autoBinFinished = 1;
                    }
                }
            }
        }
        calendar = traces[0][mainData + 'calendar'];
        var newBinSpec = Axes.autoBin(
            allPos, pa, binOpts.nbins, false, calendar, sizeFound && binOpts.size);

        // Edge case: single-valued histogram overlaying others
        // Use them all together to calculate the bin size for the single-valued one
        if(isOverlay && newBinSpec._dataSpan === 0 &&
            pa.type !== 'category' && pa.type !== 'multicategory') {
            // Several single-valued histograms! Stop infinite recursion,
            // just return an extra flag that tells handleSingleValueOverlays
            // to sort out this trace too
            if(_overlayEdgeCase) return [newBinSpec, pos0, true];

            newBinSpec = handleSingleValueOverlays(gd, trace, pa, mainData, binAttr);
        }

        // adjust for CDF edge cases
        cumulativeSpec = tracei.cumulative;
        if(cumulativeSpec.enabled && (cumulativeSpec.currentbin !== 'include')) {
            if(cumulativeSpec.direction === 'decreasing') {
                newBinSpec.start = pa.c2r(Axes.tickIncrement(
                    pa.r2c(newBinSpec.start, 0, calendar),
                    newBinSpec.size, true, calendar
                ));
            }
            else {
                newBinSpec.end = pa.c2r(Axes.tickIncrement(
                    pa.r2c(newBinSpec.end, 0, calendar),
                    newBinSpec.size, false, calendar
                ));
            }
        }

        binOpts.size = newBinSpec.size;
        if(!sizeFound) {
            autoVals.size = newBinSpec.size;
            Lib.nestedProperty(traces[0], binAttr + '.size').set(newBinSpec.size);
        }

        setBound('start', binOpts, newBinSpec);
        setBound('end', binOpts, newBinSpec);
    }

    pos0 = trace._pos0;
    delete trace._pos0;

    // Each trace can specify its own start/end, or if omitted
    // we ensure they're beyond the bounds of this trace's data,
    // and we need to make sure start is aligned with the main start
    var traceInputBins = trace._input[binAttr] || {};
    var traceBinOptsCalc = Lib.extendFlat({}, binOpts);
    var mainStart = binOpts.start;
    var startIn = pa.r2l(traceInputBins.start);
    var hasStart = startIn !== undefined;
    if((binOpts.startFound || hasStart) && startIn !== pa.r2l(mainStart)) {
        // We have an explicit start to reconcile across traces
        // if this trace has an explicit start, shift it down to a bin edge
        // if another trace had an explicit start, shift it down to a
        // bin edge past our data
        var traceStart = hasStart ?
            startIn :
            Lib.aggNums(Math.min, null, pos0);

        var dummyAx = {
            type: (pa.type === 'category' || pa.type === 'multicategory') ? 'linear' : pa.type,
            r2l: pa.r2l,
            dtick: binOpts.size,
            tick0: mainStart,
            calendar: calendar,
            range: ([traceStart, Axes.tickIncrement(traceStart, binOpts.size, false, calendar)]).map(pa.l2r)
        };
        var newStart = Axes.tickFirst(dummyAx);
        if(newStart > pa.r2l(traceStart)) {
            newStart = Axes.tickIncrement(newStart, binOpts.size, true, calendar);
        }
        traceBinOptsCalc.start = pa.l2r(newStart);
        if(!hasStart) Lib.nestedProperty(trace, binAttr + '.start').set(traceBinOptsCalc.start);
    }

    var mainEnd = binOpts.end;
    var endIn = pa.r2l(traceInputBins.end);
    var hasEnd = endIn !== undefined;
    if((binOpts.endFound || hasEnd) && endIn !== pa.r2l(mainEnd)) {
        // Reconciling an explicit end is easier, as it doesn't need to
        // match bin edges
        var traceEnd = hasEnd ?
            endIn :
            Lib.aggNums(Math.max, null, pos0);

        traceBinOptsCalc.end = pa.l2r(traceEnd);
        if(!hasEnd) Lib.nestedProperty(trace, binAttr + '.start').set(traceBinOptsCalc.end);
    }

    // Backward compatibility for one-time autobinning.
    // autobin: true is handled in cleanData, but autobin: false
    // needs to be here where we have determined the values.
    var autoBinAttr = 'autobin' + mainData;
    if(trace._input[autoBinAttr] === false) {
        trace._input[binAttr] = Lib.extendFlat({}, trace[binAttr] || {});
        delete trace._input[autoBinAttr];
        delete trace[autoBinAttr];
    }

    return [traceBinOptsCalc, pos0];
}

/*
 * Adjust single-value histograms in overlay mode to make as good a
 * guess as we can at autobin values the user would like.
 *
 * Returns the binSpec for the trace that sparked all this
 */
function handleSingleValueOverlays(gd, trace, pa, mainData, binAttr) {
    var overlaidTraceGroup = getConnectedHistograms(gd, trace);
    var pastThisTrace = false;
    var minSize = Infinity;
    var singleValuedTraces = [trace];
    var i, tracei;

    // first collect all the:
    // - min bin size from all multi-valued traces
    // - single-valued traces
    for(i = 0; i < overlaidTraceGroup.length; i++) {
        tracei = overlaidTraceGroup[i];
        if(tracei === trace) pastThisTrace = true;
        else if(!pastThisTrace) {
            // This trace has already had its autobins calculated
            // (so must not have been single-valued).
            minSize = Math.min(minSize, tracei[binAttr].size);
        }
        else {
            var resulti = calcAllAutoBins(gd, tracei, pa, mainData, true);
            var binSpeci = resulti[0];
            var isSingleValued = resulti[2];

            // so we can use this result when we get to tracei in the normal
            // course of events, mark it as done and put _pos0 back
            tracei._autoBinFinished = 1;
            tracei._pos0 = resulti[1];

            if(isSingleValued) {
                singleValuedTraces.push(tracei);
            }
            else {
                minSize = Math.min(minSize, binSpeci.size);
            }
        }
    }

    // find the real data values for each single-valued trace
    // hunt through pos0 for the first valid value
    var dataVals = new Array(singleValuedTraces.length);
    for(i = 0; i < singleValuedTraces.length; i++) {
        var pos0 = singleValuedTraces[i]._pos0;
        for(var j = 0; j < pos0.length; j++) {
            if(pos0[j] !== undefined) {
                dataVals[i] = pos0[j];
                break;
            }
        }
    }

    // are ALL traces are single-valued? use the min difference between
    // all of their values (which defaults to 1 if there's still only one)
    if(!isFinite(minSize)) {
        minSize = Lib.distinctVals(dataVals).minDiff;
    }

    // now apply the min size we found to all single-valued traces
    for(i = 0; i < singleValuedTraces.length; i++) {
        tracei = singleValuedTraces[i];
        var calendar = tracei[mainData + 'calendar'];

        tracei._input[binAttr] = tracei[binAttr] = {
            start: pa.c2r(dataVals[i] - minSize / 2, 0, calendar),
            end: pa.c2r(dataVals[i] + minSize / 2, 0, calendar),
            size: minSize
        };
    }

    return trace[binAttr];
}

/*
 * Return an array of histograms that share axes and orientation.
 *
 * Only considers histograms. In principle we could include bars in a
 * similar way to how we do manually binned histograms, though this
 * would have tons of edge cases and value judgments to make.
 */
function getConnectedHistograms(gd, trace) {
    var xid = trace.xaxis;
    var yid = trace.yaxis;
    var orientation = trace.orientation;

    var out = [];
    var fullData = gd._fullData;
    for(var i = 0; i < fullData.length; i++) {
        var tracei = fullData[i];
        if(tracei.type === 'histogram' &&
            tracei.visible === true &&
            tracei.orientation === orientation &&
            tracei.xaxis === xid && tracei.yaxis === yid
        ) {
            out.push(tracei);
        }
    }

    return out;
}


function cdf(size, direction, currentBin) {
    var i, vi, prevSum;

    function firstHalfPoint(i) {
        prevSum = size[i];
        size[i] /= 2;
    }

    function nextHalfPoint(i) {
        vi = size[i];
        size[i] = prevSum + vi / 2;
        prevSum += vi;
    }

    if(currentBin === 'half') {

        if(direction === 'increasing') {
            firstHalfPoint(0);
            for(i = 1; i < size.length; i++) {
                nextHalfPoint(i);
            }
        }
        else {
            firstHalfPoint(size.length - 1);
            for(i = size.length - 2; i >= 0; i--) {
                nextHalfPoint(i);
            }
        }
    }
    else if(direction === 'increasing') {
        for(i = 1; i < size.length; i++) {
            size[i] += size[i - 1];
        }

        // 'exclude' is identical to 'include' just shifted one bin over
        if(currentBin === 'exclude') {
            size.unshift(0);
            size.pop();
        }
    }
    else {
        for(i = size.length - 2; i >= 0; i--) {
            size[i] += size[i + 1];
        }

        if(currentBin === 'exclude') {
            size.push(0);
            size.shift();
        }
    }
}

},{"../../lib":694,"../../plots/cartesian/axes":742,"../bar/arrays_to_calcdata":834,"./average":963,"./bin_functions":965,"./bin_label_vals":966,"./norm_functions":974,"fast-isnumeric":215}],968:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = {
    eventDataKeys: ['binNumber']
};

},{}],969:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var nestedProperty = Lib.nestedProperty;

var attributes = _dereq_('./attributes');

var BINATTRS = {
    x: [
        {aStr: 'xbins.start', name: 'start'},
        {aStr: 'xbins.end', name: 'end'},
        {aStr: 'xbins.size', name: 'size'},
        {aStr: 'nbinsx', name: 'nbins'}
    ],
    y: [
        {aStr: 'ybins.start', name: 'start'},
        {aStr: 'ybins.end', name: 'end'},
        {aStr: 'ybins.size', name: 'size'},
        {aStr: 'nbinsy', name: 'nbins'}
    ]
};

// handle bin attrs and relink auto-determined values so fullData is complete
module.exports = function crossTraceDefaults(fullData, fullLayout) {
    var allBinOpts = fullLayout._histogramBinOpts = {};
    var isOverlay = fullLayout.barmode === 'overlay';
    var i, j, traceOut, traceIn, binDirection, group, binOpts;

    function coerce(attr) {
        return Lib.coerce(traceOut._input, traceOut, attributes, attr);
    }

    for(i = 0; i < fullData.length; i++) {
        traceOut = fullData[i];
        if(traceOut.type !== 'histogram') continue;

        // TODO: this shouldn't be relinked as it's only used within calc
        // https://github.com/plotly/plotly.js/issues/749
        delete traceOut._autoBinFinished;

        binDirection = traceOut.orientation === 'v' ? 'x' : 'y';
        // in overlay mode make a separate group for each trace
        // otherwise collect all traces of the same subplot & orientation
        group = isOverlay ? traceOut.uid : (traceOut.xaxis + traceOut.yaxis + binDirection);
        traceOut._groupName = group;

        binOpts = allBinOpts[group];

        if(binOpts) {
            binOpts.traces.push(traceOut);
        }
        else {
            binOpts = allBinOpts[group] = {
                traces: [traceOut],
                direction: binDirection
            };
        }
    }

    for(group in allBinOpts) {
        binOpts = allBinOpts[group];
        binDirection = binOpts.direction;
        var attrs = BINATTRS[binDirection];
        for(j = 0; j < attrs.length; j++) {
            var attrSpec = attrs[j];
            var attr = attrSpec.name;

            // nbins(x|y) is moot if we have a size. This depends on
            // nbins coming after size in binAttrs.
            if(attr === 'nbins' && binOpts.sizeFound) continue;

            var aStr = attrSpec.aStr;
            for(i = 0; i < binOpts.traces.length; i++) {
                traceOut = binOpts.traces[i];
                traceIn = traceOut._input;
                if(nestedProperty(traceIn, aStr).get() !== undefined) {
                    binOpts[attr] = coerce(aStr);
                    binOpts[attr + 'Found'] = true;
                    break;
                }
                var autoVals = traceOut._autoBin;
                if(autoVals && autoVals[attr]) {
                    // if this is the *first* autoval
                    nestedProperty(traceOut, aStr).set(autoVals[attr]);
                }
            }
            // start and end we need to coerce anyway, after having collected the
            // first of each into binOpts, in case a trace wants to restrict its
            // data to a certain range
            if(attr === 'start' || attr === 'end') {
                for(; i < binOpts.traces.length; i++) {
                    traceOut = binOpts.traces[i];
                    coerce(aStr, (traceOut._autoBin || {})[attr]);
                }
            }

            if(attr === 'nbins' && !binOpts.sizeFound && !binOpts.nbinsFound) {
                traceOut = binOpts.traces[0];
                binOpts[attr] = coerce(aStr);
            }
        }
    }
};

},{"../../lib":694,"./attributes":962}],970:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Color = _dereq_('../../components/color');

var handleStyleDefaults = _dereq_('../bar/style_defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var x = coerce('x');
    var y = coerce('y');

    var cumulative = coerce('cumulative.enabled');
    if(cumulative) {
        coerce('cumulative.direction');
        coerce('cumulative.currentbin');
    }

    coerce('text');

    var orientation = coerce('orientation', (y && !x) ? 'h' : 'v');
    var sampleLetter = orientation === 'v' ? 'x' : 'y';
    var aggLetter = orientation === 'v' ? 'y' : 'x';

    var len = (x && y) ?
        Math.min(Lib.minRowLength(x) && Lib.minRowLength(y)) :
        Lib.minRowLength(traceOut[sampleLetter] || []);

    if(!len) {
        traceOut.visible = false;
        return;
    }

    traceOut._length = len;

    var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
    handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout);

    var hasAggregationData = traceOut[aggLetter];
    if(hasAggregationData) coerce('histfunc');
    coerce('histnorm');

    // Note: bin defaults are now handled in Histogram.crossTraceDefaults
    // autobin(x|y) are only included here to appease Plotly.validate
    coerce('autobin' + sampleLetter);

    coerce('hovertemplate');

    handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout);

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);

    var lineColor = (traceOut.marker.line || {}).color;

    // override defaultColor for error bars with defaultLine
    var errorBarsSupplyDefaults = Registry.getComponentMethod('errorbars', 'supplyDefaults');
    errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color.defaultLine, {axis: 'y'});
    errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color.defaultLine, {axis: 'x', inherit: 'y'});
};

},{"../../components/color":571,"../../lib":694,"../../registry":825,"../bar/style_defaults":849,"./attributes":962}],971:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function eventData(out, pt, trace, cd, pointNumber) {
    // standard cartesian event data
    out.x = 'xVal' in pt ? pt.xVal : pt.x;
    out.y = 'yVal' in pt ? pt.yVal : pt.y;

    if(pt.xa) out.xaxis = pt.xa;
    if(pt.ya) out.yaxis = pt.ya;

    // specific to histogram - CDFs do not have pts (yet?)
    if(!(trace.cumulative || {}).enabled) {
        var pts = Array.isArray(pointNumber) ?
            cd[0].pts[pointNumber[0]][pointNumber[1]] :
            cd[pointNumber].pts;

        out.pointNumbers = pts;
        out.binNumber = out.pointNumber;
        delete out.pointNumber;
        delete out.pointIndex;

        var pointIndices;
        if(trace._indexToPoints) {
            pointIndices = [];
            for(var i = 0; i < pts.length; i++) {
                pointIndices = pointIndices.concat(trace._indexToPoints[pts[i]]);
            }
        } else {
            pointIndices = pts;
        }

        out.pointIndices = pointIndices;
    }

    return out;
};

},{}],972:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var barHover = _dereq_('../bar/hover').hoverPoints;
var hoverLabelText = _dereq_('../../plots/cartesian/axes').hoverLabelText;

module.exports = function hoverPoints(pointData, xval, yval, hovermode) {
    var pts = barHover(pointData, xval, yval, hovermode);

    if(!pts) return;

    pointData = pts[0];
    var di = pointData.cd[pointData.index];
    var trace = pointData.cd[0].trace;

    if(!trace.cumulative.enabled) {
        var posLetter = trace.orientation === 'h' ? 'y' : 'x';

        pointData[posLetter + 'Label'] = hoverLabelText(pointData[posLetter + 'a'], di.ph0, di.ph1);
    }

    if(trace.hovermplate) pointData.hovertemplate = trace.hovertemplate;

    return pts;
};

},{"../../plots/cartesian/axes":742,"../bar/hover":841}],973:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

/**
 * Histogram has its own attribute, defaults and calc steps,
 * but uses bar's plot to display
 * and bar's crossTraceCalc (formerly known as setPositions) for stacking and grouping
 */

/**
 * histogram errorBarsOK is debatable, but it's put in for backward compat.
 * there are use cases for it - sqrt for a simple histogram works right now,
 * constant and % work but they're not so meaningful. I guess it could be cool
 * to allow quadrature combination of errors in summed histograms...
 */


var Histogram = {};

Histogram.attributes = _dereq_('./attributes');
Histogram.layoutAttributes = _dereq_('../bar/layout_attributes');
Histogram.supplyDefaults = _dereq_('./defaults');
Histogram.crossTraceDefaults = _dereq_('./cross_trace_defaults');
Histogram.supplyLayoutDefaults = _dereq_('../bar/layout_defaults');
Histogram.calc = _dereq_('./calc');
Histogram.crossTraceCalc = _dereq_('../bar/cross_trace_calc').crossTraceCalc;
Histogram.plot = _dereq_('../bar/plot');
Histogram.layerName = 'barlayer';
Histogram.style = _dereq_('../bar/style').style;
Histogram.styleOnSelect = _dereq_('../bar/style').styleOnSelect;
Histogram.colorbar = _dereq_('../scatter/marker_colorbar');
Histogram.hoverPoints = _dereq_('./hover');
Histogram.selectPoints = _dereq_('../bar/select');
Histogram.eventData = _dereq_('./event_data');

Histogram.moduleType = 'trace';
Histogram.name = 'histogram';
Histogram.basePlotModule = _dereq_('../../plots/cartesian');
Histogram.categories = ['cartesian', 'svg', 'bar', 'histogram', 'oriented', 'errorBarsOK', 'showLegend'];
Histogram.meta = {
    
};

module.exports = Histogram;

},{"../../plots/cartesian":754,"../bar/cross_trace_calc":838,"../bar/layout_attributes":843,"../bar/layout_defaults":844,"../bar/plot":845,"../bar/select":846,"../bar/style":848,"../scatter/marker_colorbar":1065,"./attributes":962,"./calc":967,"./cross_trace_defaults":969,"./defaults":970,"./event_data":971,"./hover":972}],974:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


module.exports = {
    percent: function(size, total) {
        var nMax = size.length;
        var norm = 100 / total;
        for(var n = 0; n < nMax; n++) size[n] *= norm;
    },
    probability: function(size, total) {
        var nMax = size.length;
        for(var n = 0; n < nMax; n++) size[n] /= total;
    },
    density: function(size, total, inc, yinc) {
        var nMax = size.length;
        yinc = yinc || 1;
        for(var n = 0; n < nMax; n++) size[n] *= inc[n] * yinc;
    },
    'probability density': function(size, total, inc, yinc) {
        var nMax = size.length;
        if(yinc) total /= yinc;
        for(var n = 0; n < nMax; n++) size[n] *= inc[n] / total;
    }
};

},{}],975:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var histogramAttrs = _dereq_('../histogram/attributes');
var makeBinAttrs = _dereq_('../histogram/bin_attributes');
var heatmapAttrs = _dereq_('../heatmap/attributes');
var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;

module.exports = extendFlat(
    {
        x: histogramAttrs.x,
        y: histogramAttrs.y,

        z: {
            valType: 'data_array',
            editType: 'calc',
            
        },
        marker: {
            color: {
                valType: 'data_array',
                editType: 'calc',
                
            },
            editType: 'calc'
        },

        histnorm: histogramAttrs.histnorm,
        histfunc: histogramAttrs.histfunc,
        nbinsx: histogramAttrs.nbinsx,
        xbins: makeBinAttrs('x'),
        nbinsy: histogramAttrs.nbinsy,
        ybins: makeBinAttrs('y'),
        autobinx: histogramAttrs.autobinx,
        autobiny: histogramAttrs.autobiny,

        xgap: heatmapAttrs.xgap,
        ygap: heatmapAttrs.ygap,
        zsmooth: heatmapAttrs.zsmooth,
        zhoverformat: heatmapAttrs.zhoverformat
    },
    colorscaleAttrs('', {
        cLetter: 'z',
        autoColorDflt: false
    }),
    { colorbar: colorbarAttrs }
);

},{"../../components/colorbar/attributes":572,"../../components/colorscale/attributes":578,"../../lib/extend":684,"../heatmap/attributes":944,"../histogram/attributes":962,"../histogram/bin_attributes":964}],976:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');

var binFunctions = _dereq_('../histogram/bin_functions');
var normFunctions = _dereq_('../histogram/norm_functions');
var doAvg = _dereq_('../histogram/average');
var getBinSpanLabelRound = _dereq_('../histogram/bin_label_vals');


module.exports = function calc(gd, trace) {
    var xa = Axes.getFromId(gd, trace.xaxis || 'x');
    var x = trace.x ? xa.makeCalcdata(trace, 'x') : [];
    var ya = Axes.getFromId(gd, trace.yaxis || 'y');
    var y = trace.y ? ya.makeCalcdata(trace, 'y') : [];
    var xcalendar = trace.xcalendar;
    var ycalendar = trace.ycalendar;
    var xr2c = function(v) { return xa.r2c(v, 0, xcalendar); };
    var yr2c = function(v) { return ya.r2c(v, 0, ycalendar); };
    var xc2r = function(v) { return xa.c2r(v, 0, xcalendar); };
    var yc2r = function(v) { return ya.c2r(v, 0, ycalendar); };

    var i, j, n, m;

    var serieslen = trace._length;
    if(x.length > serieslen) x.splice(serieslen, x.length - serieslen);
    if(y.length > serieslen) y.splice(serieslen, y.length - serieslen);

    // calculate the bins
    doAutoBin(trace, 'x', x, xa, xr2c, xc2r, xcalendar);
    doAutoBin(trace, 'y', y, ya, yr2c, yc2r, ycalendar);

    // make the empty bin array & scale the map
    var z = [];
    var onecol = [];
    var zerocol = [];
    var nonuniformBinsX = (typeof(trace.xbins.size) === 'string');
    var nonuniformBinsY = (typeof(trace.ybins.size) === 'string');
    var xEdges = [];
    var yEdges = [];
    var xbins = nonuniformBinsX ? xEdges : trace.xbins;
    var ybins = nonuniformBinsY ? yEdges : trace.ybins;
    var total = 0;
    var counts = [];
    var inputPoints = [];
    var norm = trace.histnorm;
    var func = trace.histfunc;
    var densitynorm = (norm.indexOf('density') !== -1);
    var extremefunc = (func === 'max' || func === 'min');
    var sizeinit = (extremefunc ? null : 0);
    var binfunc = binFunctions.count;
    var normfunc = normFunctions[norm];
    var doavg = false;
    var xinc = [];
    var yinc = [];

    // set a binning function other than count?
    // for binning functions: check first for 'z',
    // then 'mc' in case we had a colored scatter plot
    // and want to transfer these colors to the 2D histo
    // TODO: axe this, make it the responsibility of the app changing type? or an impliedEdit?
    var rawCounterData = ('z' in trace) ?
        trace.z :
        (('marker' in trace && Array.isArray(trace.marker.color)) ?
            trace.marker.color : '');
    if(rawCounterData && func !== 'count') {
        doavg = func === 'avg';
        binfunc = binFunctions[func];
    }

    // decrease end a little in case of rounding errors
    var binSpec = trace.xbins;
    var binStart = xr2c(binSpec.start);
    var binEnd = xr2c(binSpec.end) +
        (binStart - Axes.tickIncrement(binStart, binSpec.size, false, xcalendar)) / 1e6;

    for(i = binStart; i < binEnd; i = Axes.tickIncrement(i, binSpec.size, false, xcalendar)) {
        onecol.push(sizeinit);
        xEdges.push(i);
        if(doavg) zerocol.push(0);
    }
    xEdges.push(i);

    var nx = onecol.length;
    var x0c = xr2c(trace.xbins.start);
    var dx = (i - x0c) / nx;
    var x0 = xc2r(x0c + dx / 2);

    binSpec = trace.ybins;
    binStart = yr2c(binSpec.start);
    binEnd = yr2c(binSpec.end) +
        (binStart - Axes.tickIncrement(binStart, binSpec.size, false, ycalendar)) / 1e6;

    for(i = binStart; i < binEnd; i = Axes.tickIncrement(i, binSpec.size, false, ycalendar)) {
        z.push(onecol.slice());
        yEdges.push(i);
        var ipCol = new Array(nx);
        for(j = 0; j < nx; j++) ipCol[j] = [];
        inputPoints.push(ipCol);
        if(doavg) counts.push(zerocol.slice());
    }
    yEdges.push(i);

    var ny = z.length;
    var y0c = yr2c(trace.ybins.start);
    var dy = (i - y0c) / ny;
    var y0 = yc2r(y0c + dy / 2);

    if(densitynorm) {
        xinc = makeIncrements(onecol.length, xbins, dx, nonuniformBinsX);
        yinc = makeIncrements(z.length, ybins, dy, nonuniformBinsY);
    }

    // for date axes we need bin bounds to be calcdata. For nonuniform bins
    // we already have this, but uniform with start/end/size they're still strings.
    if(!nonuniformBinsX && xa.type === 'date') xbins = binsToCalc(xr2c, xbins);
    if(!nonuniformBinsY && ya.type === 'date') ybins = binsToCalc(yr2c, ybins);

    // put data into bins
    var uniqueValsPerX = true;
    var uniqueValsPerY = true;
    var xVals = new Array(nx);
    var yVals = new Array(ny);
    var xGapLow = Infinity;
    var xGapHigh = Infinity;
    var yGapLow = Infinity;
    var yGapHigh = Infinity;
    for(i = 0; i < serieslen; i++) {
        var xi = x[i];
        var yi = y[i];
        n = Lib.findBin(xi, xbins);
        m = Lib.findBin(yi, ybins);
        if(n >= 0 && n < nx && m >= 0 && m < ny) {
            total += binfunc(n, i, z[m], rawCounterData, counts[m]);
            inputPoints[m][n].push(i);

            if(uniqueValsPerX) {
                if(xVals[n] === undefined) xVals[n] = xi;
                else if(xVals[n] !== xi) uniqueValsPerX = false;
            }
            if(uniqueValsPerY) {
                if(yVals[n] === undefined) yVals[n] = yi;
                else if(yVals[n] !== yi) uniqueValsPerY = false;
            }

            xGapLow = Math.min(xGapLow, xi - xEdges[n]);
            xGapHigh = Math.min(xGapHigh, xEdges[n + 1] - xi);
            yGapLow = Math.min(yGapLow, yi - yEdges[m]);
            yGapHigh = Math.min(yGapHigh, yEdges[m + 1] - yi);
        }
    }
    // normalize, if needed
    if(doavg) {
        for(m = 0; m < ny; m++) total += doAvg(z[m], counts[m]);
    }
    if(normfunc) {
        for(m = 0; m < ny; m++) normfunc(z[m], total, xinc, yinc[m]);
    }

    return {
        x: x,
        xRanges: getRanges(xEdges, uniqueValsPerX && xVals, xGapLow, xGapHigh, xa, xcalendar),
        x0: x0,
        dx: dx,
        y: y,
        yRanges: getRanges(yEdges, uniqueValsPerY && yVals, yGapLow, yGapHigh, ya, ycalendar),
        y0: y0,
        dy: dy,
        z: z,
        pts: inputPoints
    };
};

function doAutoBin(trace, axLetter, data, ax, r2c, c2r, calendar) {
    var binAttr = axLetter + 'bins';
    var binSpec = trace[binAttr];
    if(!binSpec) binSpec = trace[binAttr] = {};
    var inputBinSpec = trace._input[binAttr] || {};
    var autoBin = trace._autoBin = {};

    // clear out any previously added autobin info
    if(!inputBinSpec.size) delete binSpec.size;
    if(inputBinSpec.start === undefined) delete binSpec.start;
    if(inputBinSpec.end === undefined) delete binSpec.end;

    var autoSize = !binSpec.size;
    var autoStart = binSpec.start === undefined;
    var autoEnd = binSpec.end === undefined;

    if(autoSize || autoStart || autoEnd) {
        var newBinSpec = Axes.autoBin(data, ax, trace['nbins' + axLetter], '2d', calendar, binSpec.size);
        if(trace.type === 'histogram2dcontour') {
            // the "true" 2nd argument reverses the tick direction (which we can't
            // just do with a minus sign because of month bins)
            if(autoStart) {
                newBinSpec.start = c2r(Axes.tickIncrement(
                    r2c(newBinSpec.start), newBinSpec.size, true, calendar));
            }
            if(autoEnd) {
                newBinSpec.end = c2r(Axes.tickIncrement(
                    r2c(newBinSpec.end), newBinSpec.size, false, calendar));
            }
        }
        if(autoSize) binSpec.size = autoBin.size = newBinSpec.size;
        if(autoStart) binSpec.start = autoBin.start = newBinSpec.start;
        if(autoEnd) binSpec.end = autoBin.end = newBinSpec.end;
    }

    // Backward compatibility for one-time autobinning.
    // autobin: true is handled in cleanData, but autobin: false
    // needs to be here where we have determined the values.
    var autoBinAttr = 'autobin' + axLetter;
    if(trace._input[autoBinAttr] === false) {
        trace._input[binAttr] = Lib.extendFlat({}, binSpec);
        delete trace._input[autoBinAttr];
        delete trace[autoBinAttr];
    }
}

function makeIncrements(len, bins, dv, nonuniform) {
    var out = new Array(len);
    var i;
    if(nonuniform) {
        for(i = 0; i < len; i++) out[i] = 1 / (bins[i + 1] - bins[i]);
    }
    else {
        var inc = 1 / dv;
        for(i = 0; i < len; i++) out[i] = inc;
    }
    return out;
}

function binsToCalc(r2c, bins) {
    return {
        start: r2c(bins.start),
        end: r2c(bins.end),
        size: bins.size
    };
}

function getRanges(edges, uniqueVals, gapLow, gapHigh, ax, calendar) {
    var i;
    var len = edges.length - 1;
    var out = new Array(len);
    if(uniqueVals) {
        for(i = 0; i < len; i++) out[i] = [uniqueVals[i], uniqueVals[i]];
    }
    else {
        var roundFn = getBinSpanLabelRound(gapLow, gapHigh, edges, ax, calendar);
        for(i = 0; i < len; i++) out[i] = [roundFn(edges[i]), roundFn(edges[i + 1], true)];
    }
    return out;
}

},{"../../lib":694,"../../plots/cartesian/axes":742,"../histogram/average":963,"../histogram/bin_functions":965,"../histogram/bin_label_vals":966,"../histogram/norm_functions":974}],977:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


var isNumeric = _dereq_('fast-isnumeric');

var BADNUM = _dereq_('../../constants/numerical').BADNUM;
var axisIds = _dereq_('../../plots/cartesian/axis_ids');
var Lib = _dereq_('../../lib');

var attributes = _dereq_('./attributes');

var BINDIRECTIONS = ['x', 'y'];

// Handle bin attrs and relink auto-determined values so fullData is complete
// does not have cross-trace coupling, but moved out here so we have axis types
// and relinked trace._autoBin
module.exports = function crossTraceDefaults(fullData, fullLayout) {
    var i, j, traceOut, binDirection;

    function coerce(attr) {
        return Lib.coerce(traceOut._input, traceOut, attributes, attr);
    }

    for(i = 0; i < fullData.length; i++) {
        traceOut = fullData[i];
        var type = traceOut.type;
        if(type !== 'histogram2d' && type !== 'histogram2dcontour') continue;

        for(j = 0; j < BINDIRECTIONS.length; j++) {
            binDirection = BINDIRECTIONS[j];
            var binAttr = binDirection + 'bins';
            var autoBins = (traceOut._autoBin || {})[binDirection] || {};
            coerce(binAttr + '.start', autoBins.start);
            coerce(binAttr + '.end', autoBins.end);
            coerce(binAttr + '.size', autoBins.size);

            cleanBins(traceOut, binDirection, fullLayout, autoBins);

            if(!(traceOut[binAttr] || {}).size) coerce('nbins' + binDirection);
        }
    }
};

function cleanBins(trace, binDirection, fullLayout, autoBins) {
    var ax = fullLayout[axisIds.id2name(trace[binDirection + 'axis'])];
    var axType = ax.type;
    var binAttr = binDirection + 'bins';
    var bins = trace[binAttr];
    var calendar = trace[binDirection + 'calendar'];

    if(!bins) bins = trace[binAttr] = {};

    var cleanBound = (axType === 'date') ?
        function(v, dflt) { return (v || v === 0) ? Lib.cleanDate(v, BADNUM, calendar) : dflt; } :
        function(v, dflt) { return isNumeric(v) ? Number(v) : dflt; };

    bins.start = cleanBound(bins.start, autoBins.start);
    bins.end = cleanBound(bins.end, autoBins.end);

    // logic for bin size is very similar to dtick (cartesian/tick_value_defaults)
    // but without the extra string options for log axes
    // ie the only strings we accept are M<n> for months
    var sizeDflt = autoBins.size;
    var binSize = bins.size;

    if(isNumeric(binSize)) {
        bins.size = (binSize > 0) ? Number(binSize) : sizeDflt;
    }
    else if(typeof binSize !== 'string') {
        bins.size = sizeDflt;
    }
    else {
        // date special case: "M<n>" gives bins every (integer) n months
        var prefix = binSize.charAt(0);
        var sizeNum = binSize.substr(1);

        sizeNum = isNumeric(sizeNum) ? Number(sizeNum) : 0;
        if((sizeNum <= 0) || !(
                axType === 'date' && prefix === 'M' && sizeNum === Math.round(sizeNum)
            )) {
            bins.size = sizeDflt;
        }
    }
}

},{"../../constants/numerical":671,"../../lib":694,"../../plots/cartesian/axis_ids":745,"./attributes":975,"fast-isnumeric":215}],978:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

var handleSampleDefaults = _dereq_('./sample_defaults');
var handleStyleDefaults = _dereq_('../heatmap/style_defaults');
var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
var attributes = _dereq_('./attributes');


module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    handleSampleDefaults(traceIn, traceOut, coerce, layout);
    if(traceOut.visible === false) return;

    handleStyleDefaults(traceIn, traceOut, coerce, layout);
    colorscaleDefaults(
        traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'}
    );
};

},{"../../components/colorscale/defaults":581,"../../lib":694,"../heatmap/style_defaults":957,"./attributes":975,"./sample_defaults":981}],979:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var heatmapHover = _dereq_('../heatmap/hover');
var hoverLabelText = _dereq_('../../plots/cartesian/axes').hoverLabelText;

module.exports = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer, contour) {
    var pts = heatmapHover(pointData, xval, yval, hovermode, hoverLayer, contour);

    if(!pts) return;

    pointData = pts[0];
    var indices = pointData.index;
    var ny = indices[0];
    var nx = indices[1];
    var cd0 = pointData.cd[0];
    var xRange = cd0.xRanges[nx];
    var yRange = cd0.yRanges[ny];

    pointData.xLabel = hoverLabelText(pointData.xa, xRange[0], xRange[1]);
    pointData.yLabel = hoverLabelText(pointData.ya, yRange[0], yRange[1]);

    return pts;
};

},{"../../plots/cartesian/axes":742,"../heatmap/hover":951}],980:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Histogram2D = {};

Histogram2D.attributes = _dereq_('./attributes');
Histogram2D.supplyDefaults = _dereq_('./defaults');
Histogram2D.crossTraceDefaults = _dereq_('./cross_trace_defaults');
Histogram2D.calc = _dereq_('../heatmap/calc');
Histogram2D.plot = _dereq_('../heatmap/plot');
Histogram2D.layerName = 'heatmaplayer';
Histogram2D.colorbar = _dereq_('../heatmap/colorbar');
Histogram2D.style = _dereq_('../heatmap/style');
Histogram2D.hoverPoints = _dereq_('./hover');
Histogram2D.eventData = _dereq_('../histogram/event_data');

Histogram2D.moduleType = 'trace';
Histogram2D.name = 'histogram2d';
Histogram2D.basePlotModule = _dereq_('../../plots/cartesian');
Histogram2D.categories = ['cartesian', 'svg', '2dMap', 'histogram'];
Histogram2D.meta = {
    
    
};

module.exports = Histogram2D;

},{"../../plots/cartesian":754,"../heatmap/calc":945,"../heatmap/colorbar":947,"../heatmap/plot":955,"../heatmap/style":956,"../histogram/event_data":971,"./attributes":975,"./cross_trace_defaults":977,"./defaults":978,"./hover":979}],981:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');

module.exports = function handleSampleDefaults(traceIn, traceOut, coerce, layout) {
    var x = coerce('x');
    var y = coerce('y');
    var xlen = Lib.minRowLength(x);
    var ylen = Lib.minRowLength(y);

    // we could try to accept x0 and dx, etc...
    // but that's a pretty weird use case.
    // for now require both x and y explicitly specified.
    if(!xlen || !ylen) {
        traceOut.visible = false;
        return;
    }

    traceOut._length = Math.min(xlen, ylen);

    var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
    handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout);

    // if marker.color is an array, we can use it in aggregation instead of z
    var hasAggregationData = coerce('z') || coerce('marker.color');

    if(hasAggregationData) coerce('histfunc');
    coerce('histnorm');

    // Note: bin defaults are now handled in Histogram2D.crossTraceDefaults
    // autobin(x|y) are only included here to appease Plotly.validate
    coerce('autobinx');
    coerce('autobiny');
};

},{"../../lib":694,"../../registry":825}],982:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var histogram2dAttrs = _dereq_('../histogram2d/attributes');
var contourAttrs = _dereq_('../contour/attributes');
var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;

module.exports = extendFlat({
    x: histogram2dAttrs.x,
    y: histogram2dAttrs.y,
    z: histogram2dAttrs.z,
    marker: histogram2dAttrs.marker,

    histnorm: histogram2dAttrs.histnorm,
    histfunc: histogram2dAttrs.histfunc,
    nbinsx: histogram2dAttrs.nbinsx,
    xbins: histogram2dAttrs.xbins,
    nbinsy: histogram2dAttrs.nbinsy,
    ybins: histogram2dAttrs.ybins,
    autobinx: histogram2dAttrs.autobinx,
    autobiny: histogram2dAttrs.autobiny,

    autocontour: contourAttrs.autocontour,
    ncontours: contourAttrs.ncontours,
    contours: contourAttrs.contours,
    line: contourAttrs.line,
    zhoverformat: histogram2dAttrs.zhoverformat
},
    colorscaleAttrs('', {
        cLetter: 'z',
        editTypeOverride: 'calc'
    }),
    { colorbar: colorbarAttrs }
);

},{"../../components/colorbar/attributes":572,"../../components/colorscale/attributes":578,"../../lib/extend":684,"../contour/attributes":915,"../histogram2d/attributes":975}],983:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

var handleSampleDefaults = _dereq_('../histogram2d/sample_defaults');
var handleContoursDefaults = _dereq_('../contour/contours_defaults');
var handleStyleDefaults = _dereq_('../contour/style_defaults');
var attributes = _dereq_('./attributes');


module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    function coerce2(attr) {
        return Lib.coerce2(traceIn, traceOut, attributes, attr);
    }

    handleSampleDefaults(traceIn, traceOut, coerce, layout);
    if(traceOut.visible === false) return;

    handleContoursDefaults(traceIn, traceOut, coerce, coerce2);
    handleStyleDefaults(traceIn, traceOut, coerce, layout);
};

},{"../../lib":694,"../contour/contours_defaults":922,"../contour/style_defaults":936,"../histogram2d/sample_defaults":981,"./attributes":982}],984:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Histogram2dContour = {};

Histogram2dContour.attributes = _dereq_('./attributes');
Histogram2dContour.supplyDefaults = _dereq_('./defaults');
Histogram2dContour.crossTraceDefaults = _dereq_('../histogram2d/cross_trace_defaults');
Histogram2dContour.calc = _dereq_('../contour/calc');
Histogram2dContour.plot = _dereq_('../contour/plot').plot;
Histogram2dContour.layerName = 'contourlayer';
Histogram2dContour.style = _dereq_('../contour/style');
Histogram2dContour.colorbar = _dereq_('../contour/colorbar');
Histogram2dContour.hoverPoints = _dereq_('../contour/hover');

Histogram2dContour.moduleType = 'trace';
Histogram2dContour.name = 'histogram2dcontour';
Histogram2dContour.basePlotModule = _dereq_('../../plots/cartesian');
Histogram2dContour.categories = ['cartesian', 'svg', '2dMap', 'contour', 'histogram', 'showLegend'];
Histogram2dContour.meta = {
    
    
};

module.exports = Histogram2dContour;

},{"../../plots/cartesian":754,"../contour/calc":916,"../contour/colorbar":918,"../contour/hover":928,"../contour/plot":933,"../contour/style":935,"../histogram2d/cross_trace_defaults":977,"./attributes":982,"./defaults":983}],985:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
var surfaceAtts = _dereq_('../surface/attributes');
var meshAttrs = _dereq_('../mesh3d/attributes');
var baseAttrs = _dereq_('../../plots/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;

function makeSliceAttr(axLetter) {
    return {
        show: {
            valType: 'boolean',
            
            dflt: false,
            
        },
        locations: {
            valType: 'data_array',
            dflt: [],
            
            
        },
        fill: {
            valType: 'number',
            
            min: 0,
            max: 1,
            dflt: 1,
            
        }
    };
}

function makeCapAttr(axLetter) {
    return {
        show: {
            valType: 'boolean',
            
            dflt: true,
            
        },
        fill: {
            valType: 'number',
            
            min: 0,
            max: 1,
            dflt: 1,
            
        }
    };
}

var attrs = module.exports = overrideAll(extendFlat({
    x: {
        valType: 'data_array',
        
        
    },
    y: {
        valType: 'data_array',
        
        
    },
    z: {
        valType: 'data_array',
        
        
    },
    value: {
        valType: 'data_array',
        
        
    },
    isomin: {
        valType: 'number',
        
        
    },
    isomax: {
        valType: 'number',
        
        
    },

    surface: {
        show: {
            valType: 'boolean',
            
            dflt: true,
            
        },
        count: {
            valType: 'integer',
            
            dflt: 2,
            min: 1,
            
        },
        fill: {
            valType: 'number',
            
            min: 0,
            max: 1,
            dflt: 1,
            
        },
        pattern: {
            valType: 'flaglist',
            flags: ['A', 'B', 'C', 'D', 'E'],
            extras: ['all', 'odd', 'even'],
            dflt: 'all',
            
            
        }
    },

    spaceframe: {
        show: {
            valType: 'boolean',
            
            dflt: false,
            
        },
        fill: {
            valType: 'number',
            
            min: 0,
            max: 1,
            dflt: 0.15,
            
        }
    },

    slices: {
        x: makeSliceAttr('x'),
        y: makeSliceAttr('y'),
        z: makeSliceAttr('z')
    },

    caps: {
        x: makeCapAttr('x'),
        y: makeCapAttr('y'),
        z: makeCapAttr('z')
    },

    text: {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        
    },
},

colorscaleAttrs('', {
    colorAttr: '`value`',
    showScaleDflt: true,
    editTypeOverride: 'calc'
}), {

    colorbar: colorbarAttrs,

    // Flat shaded mode
    flatshading: {
        valType: 'boolean',
        
        dflt: false,
        
    },

    contour: {
        show: extendFlat({}, surfaceAtts.contours.x.show, {
            
        }),
        color: surfaceAtts.contours.x.color,
        width: surfaceAtts.contours.x.width
    },

    lightposition: {
        x: extendFlat({}, surfaceAtts.lightposition.x, {dflt: 1e5}),
        y: extendFlat({}, surfaceAtts.lightposition.y, {dflt: 1e5}),
        z: extendFlat({}, surfaceAtts.lightposition.z, {dflt: 0})
    },
    lighting: meshAttrs.lighting,

    hoverinfo: extendFlat({}, baseAttrs.hoverinfo)
}), 'calc', 'nested');

attrs.x.editType = attrs.y.editType = attrs.z.editType = attrs.value.editType = 'calc+clearAxisTypes';
attrs.transforms = undefined;

},{"../../components/colorbar/attributes":572,"../../components/colorscale/attributes":578,"../../lib/extend":684,"../../plot_api/edit_types":725,"../../plots/attributes":739,"../mesh3d/attributes":990,"../surface/attributes":1134}],986:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorscaleCalc = _dereq_('../../components/colorscale/calc');

module.exports = function calc(gd, trace) {

    trace._len = Math.min(trace.x.length, trace.y.length, trace.z.length, trace.value.length);

    var min = Infinity;
    var max = -Infinity;
    var len = trace.value.length;
    for(var i = 0; i < len; i++) {
        var v = trace.value[i];
        min = Math.min(min, v);
        max = Math.max(max, v);
    }

    trace._minValues = min;
    trace._maxValues = max;

    trace._vMin = (trace.isomin === undefined || trace.isomin === null) ? min : trace.isomin;
    trace._vMax = (trace.isomax === undefined || trace.isomin === null) ? max : trace.isomax;

    colorscaleCalc(gd, trace, {
        vals: [trace._vMin, trace._vMax],
        containerStr: '',
        cLetter: 'c'
    });
};

},{"../../components/colorscale/calc":579}],987:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var createMesh = _dereq_('gl-mesh3d');

var parseColorScale = _dereq_('../../lib/gl_format_color').parseColorScale;
var str2RgbaArray = _dereq_('../../lib/str2rgbarray');
var zip3 = _dereq_('../../plots/gl3d/zip3');
var Lib = _dereq_('../../lib');

function distinctVals(col) {
    return Lib.distinctVals(col).vals;
}

function IsosurfaceTrace(scene, mesh, uid) {
    this.scene = scene;
    this.uid = uid;
    this.mesh = mesh;
    this.name = '';
    this.data = null;
    this.showContour = false;
}

var proto = IsosurfaceTrace.prototype;

function findNearestOnAxis(w, arr) {
    for(var q = arr.length - 1; q > 0; q--) {
        var min = Math.min(arr[q], arr[q - 1]);
        var max = Math.max(arr[q], arr[q - 1]);
        if(max > min && min < w && w <= max) {
            return {
                id: q,
                distRatio: (max - w) / (max - min)
            };
        }
    }
    return {
        id: 0,
        distRatio: 0
    };
}

proto.handlePick = function(selection) {
    if(selection.object === this.mesh) {

        var rawId = selection.data.index;

        var x = this.data._x[rawId];
        var y = this.data._y[rawId];
        var z = this.data._z[rawId];

        var height = this.data._Ys.length;
        var depth = this.data._Zs.length;

        var i = findNearestOnAxis(x, this.data._Xs).id;
        var j = findNearestOnAxis(y, this.data._Ys).id;
        var k = findNearestOnAxis(z, this.data._Zs).id;

        var selectIndex = selection.index = k + depth * j + depth * height * i;

        selection.traceCoordinate = [
            this.data._x[selectIndex],
            this.data._y[selectIndex],
            this.data._z[selectIndex],
            this.data.value[selectIndex]
        ];

        var text = this.data.text;
        if(Array.isArray(text) && text[selectIndex] !== undefined) {
            selection.textLabel = text[selectIndex];
        } else if(text) {
            selection.textLabel = text;
        }

        return true;
    }
};

proto.update = function(data) {
    var scene = this.scene;
    var layout = scene.fullSceneLayout;

    this.data = generateIsosurfaceMesh(data);

    // Unpack position data
    function toDataCoords(axis, coord, scale, calendar) {
        return coord.map(function(x) {
            return axis.d2l(x, 0, calendar) * scale;
        });
    }

    var positions = zip3(
        toDataCoords(layout.xaxis, data._x, scene.dataScale[0], data.xcalendar),
        toDataCoords(layout.yaxis, data._y, scene.dataScale[1], data.ycalendar),
        toDataCoords(layout.zaxis, data._z, scene.dataScale[2], data.zcalendar));

    var cells = zip3(data._i, data._j, data._k);

    var config = {
        positions: positions,
        cells: cells,
        lightPosition: [data.lightposition.x, data.lightposition.y, data.lightposition.z],
        ambient: data.lighting.ambient,
        diffuse: data.lighting.diffuse,
        specular: data.lighting.specular,
        roughness: data.lighting.roughness,
        fresnel: data.lighting.fresnel,
        vertexNormalsEpsilon: data.lighting.vertexnormalsepsilon,
        faceNormalsEpsilon: data.lighting.facenormalsepsilon,
        opacity: 1, // Note: no need to create transparent surfaces
        contourEnable: data.contour.show,
        contourColor: str2RgbaArray(data.contour.color).slice(0, 3),
        contourWidth: data.contour.width,
        useFacetNormals: data.flatshading
    };

    config.vertexIntensity = data._intensity;
    config.vertexIntensityBounds = [data.cmin, data.cmax];
    config.colormap = parseColorScale(data);

    // Update mesh
    this.mesh.update(config);
};

proto.dispose = function() {
    this.scene.glplot.remove(this.mesh);
    this.mesh.dispose();
};

function generateIsosurfaceMesh(data) {

    data._i = [];
    data._j = [];
    data._k = [];

    var showSurface = data.surface.show;
    var showSpaceframe = data.spaceframe.show;

    var surfaceFill = data.surface.fill;
    var spaceframeFill = data.spaceframe.fill;

    var drawingSurface = false;
    var drawingSpaceframe = false;
    var drawingEdge = false;

    var numFaces = 0;
    var numVertices;
    var beginVertextLength;

    var Xs = distinctVals(data.x.slice(0, data._len));
    var Ys = distinctVals(data.y.slice(0, data._len));
    var Zs = distinctVals(data.z.slice(0, data._len));

    var width = Xs.length;
    var height = Ys.length;
    var depth = Zs.length;

    function getIndex(i, j, k) {
        return k + depth * j + depth * height * i;
    }

    var minValues = data._minValues;
    var maxValues = data._maxValues;

    var vMin = data._vMin;
    var vMax = data._vMax;

    var allXs;
    var allYs;
    var allZs;
    var allVs;

    function findVertexId(x, y, z) {
        // could be used to find the vertex id of previously generated vertex within the group

        var len = allVs.length;
        for(var f = beginVertextLength; f < len; f++) {
            if(
                x === allXs[f] &&
                y === allYs[f] &&
                z === allZs[f]
            ) {
                return f;
            }
        }
        return -1;
    }

    function beginGroup() {
        beginVertextLength = numVertices;
    }

    function emptyVertices() {
        allXs = [];
        allYs = [];
        allZs = [];
        allVs = [];
        numVertices = 0;

        beginGroup();
    }

    function addVertex(x, y, z, v) {
        allXs.push(x);
        allYs.push(y);
        allZs.push(z);
        allVs.push(v);
        numVertices++;

        return numVertices - 1;
    }

    function addFace(a, b, c) {
        data._i.push(a);
        data._j.push(b);
        data._k.push(c);
        numFaces++;

        return numFaces - 1;
    }

    function getCenter(A, B, C) {
        var M = [];
        for(var i = 0; i < A.length; i++) {
            M[i] = (A[i] + B[i] + C[i]) / 3.0;
        }
        return M;
    }

    function getBetween(A, B, r) {
        var M = [];
        for(var i = 0; i < A.length; i++) {
            M[i] = A[i] * (1 - r) + r * B[i];
        }
        return M;
    }

    var activeFill;
    function setFill(fill) {
        activeFill = fill;
    }

    function createOpenTri(xyzv, abc) {
        var A = xyzv[0];
        var B = xyzv[1];
        var C = xyzv[2];
        var G = getCenter(A, B, C);

        var r = Math.sqrt(1 - activeFill);
        var p1 = getBetween(G, A, r);
        var p2 = getBetween(G, B, r);
        var p3 = getBetween(G, C, r);

        var a = abc[0];
        var b = abc[1];
        var c = abc[2];

        return {
            xyzv: [
                [A, B, p2], [p2, p1, A],
                [B, C, p3], [p3, p2, B],
                [C, A, p1], [p1, p3, C]
            ],
            abc: [
                [a, b, -1], [-1, -1, a],
                [b, c, -1], [-1, -1, b],
                [c, a, -1], [-1, -1, c]
            ]
        };
    }

    function styleIncludes(style, char) {
        if(style === 'all' || style === null) return true;
        return (style.indexOf(char) > -1);
    }

    function mapValue(style, value) {
        if(style === null) return value;
        return style;
    }

    function drawTri(style, xyzv, abc) {

        beginGroup();

        var allXYZVs = [xyzv];
        var allABCs = [abc];
        if(activeFill >= 1) {
            allXYZVs = [xyzv];
            allABCs = [abc];
        } else if(activeFill > 0) {
            var openTri = createOpenTri(xyzv, abc);
            allXYZVs = openTri.xyzv;
            allABCs = openTri.abc;
        }

        for(var f = 0; f < allXYZVs.length; f++) {

            xyzv = allXYZVs[f];
            abc = allABCs[f];

            var pnts = [];
            for(var i = 0; i < 3; i++) {

                var x = xyzv[i][0];
                var y = xyzv[i][1];
                var z = xyzv[i][2];
                var v = xyzv[i][3];

                var id = (abc[i] > -1) ? abc[i] : findVertexId(x, y, z);
                if(id > -1) {
                    pnts[i] = id;
                } else {
                    pnts[i] = addVertex(x, y, z, mapValue(style, v));
                }
            }

            addFace(pnts[0], pnts[1], pnts[2]);
        }
    }

    function drawQuad(style, xyzv, abcd) {
        var makeTri = function(i, j, k) {
            drawTri(style, [xyzv[i], xyzv[j], xyzv[k]], [abcd[i], abcd[j], abcd[k]]);
        };

        makeTri(0, 1, 2);
        makeTri(2, 3, 0);
    }

    function drawTetra(style, xyzv, abcd) {
        var makeTri = function(i, j, k) {
            drawTri(style, [xyzv[i], xyzv[j], xyzv[k]], [abcd[i], abcd[j], abcd[k]]);
        };

        makeTri(0, 1, 2);
        makeTri(3, 0, 1);
        makeTri(2, 3, 0);
        makeTri(1, 2, 3);
    }

    function calcIntersection(pointOut, pointIn, min, max) {
        var value = pointOut[3];

        if(value < min) value = min;
        if(value > max) value = max;

        var ratio = (pointOut[3] - value) / (pointOut[3] - pointIn[3]);

        var result = [];
        for(var s = 0; s < 4; s++) {
            result[s] = (1 - ratio) * pointOut[s] + ratio * pointIn[s];
        }
        return result;
    }

    function inRange(value, min, max) {
        return (
            value >= min &&
            value <= max
        );
    }

    function almostInFinalRange(value) {
        var vErr = 0.01 * (vMax - vMin);
        return (
            value >= vMin - vErr &&
            value <= vMax + vErr
        );
    }

    function getXYZV(indecies) {
        var xyzv = [];
        for(var q = 0; q < 4; q++) {
            var index = indecies[q];
            xyzv.push(
                [
                    data.x[index],
                    data.y[index],
                    data.z[index],
                    data.value[index]
                ]
            );
        }

        return xyzv;
    }

    function tryCreateTri(style, xyzv, abc, min, max, isSecondPass) {

        abc = [-1, -1, -1]; // Note: for the moment we had to override indices
        // for planar surfaces (i.e. caps and slices) due to group shading
        // bug of gl-mesh3d. But don't worry this would run faster!

        var tryDrawTri = function(style, xyzv, abc) {
            if( // we check here if the points are in `real` iso-min/max range
                almostInFinalRange(xyzv[0][3]) &&
                almostInFinalRange(xyzv[1][3]) &&
                almostInFinalRange(xyzv[2][3])
            ) {
                drawTri(style, xyzv, abc);
            } else if(!isSecondPass) {
                tryCreateTri(style, xyzv, abc, vMin, vMax, true); // i.e. second pass
            }
        };

        var ok = [
            inRange(xyzv[0][3], min, max),
            inRange(xyzv[1][3], min, max),
            inRange(xyzv[2][3], min, max)
        ];

        var interpolated = false;

        if(!ok[0] && !ok[1] && !ok[2]) {
            return interpolated;
        }

        if(ok[0] && ok[1] && ok[2]) {
            if(!drawingEdge) {
                tryDrawTri(style, xyzv, abc);
            }
            return interpolated;
        }

        [
            [0, 1, 2],
            [2, 0, 1],
            [1, 2, 0]
        ].forEach(function(e) {
            if(ok[e[0]] && ok[e[1]] && !ok[e[2]]) {
                var A = xyzv[e[0]];
                var B = xyzv[e[1]];
                var C = xyzv[e[2]];

                var p1 = calcIntersection(C, A, min, max);
                var p2 = calcIntersection(C, B, min, max);

                tryDrawTri(style, [p2, p1, A], [-1, -1, abc[e[0]]]);
                tryDrawTri(style, [A, B, p2], [abc[e[0]], abc[e[1]], -1]);

                interpolated = true;
            }
        });
        if(interpolated) return interpolated;

        [
            [0, 1, 2],
            [1, 2, 0],
            [2, 0, 1]
        ].forEach(function(e) {
            if(ok[e[0]] && !ok[e[1]] && !ok[e[2]]) {
                var A = xyzv[e[0]];
                var B = xyzv[e[1]];
                var C = xyzv[e[2]];

                var p1 = calcIntersection(B, A, min, max);
                var p2 = calcIntersection(C, A, min, max);

                tryDrawTri(style, [p2, p1, A], [-1, -1, abc[e[0]]]);

                interpolated = true;
            }
        });
        return interpolated;
    }

    function tryCreateTetra(style, abcd, min, max) {

        var xyzv = getXYZV(abcd);

        var ok = [
            inRange(xyzv[0][3], min, max),
            inRange(xyzv[1][3], min, max),
            inRange(xyzv[2][3], min, max),
            inRange(xyzv[3][3], min, max)
        ];

        var interpolated = false;

        if(!ok[0] && !ok[1] && !ok[2] && !ok[3]) {
            return interpolated;
        }

        if(ok[0] && ok[1] && ok[2] && ok[3]) {
            if(drawingSpaceframe) {
                drawTetra(style, xyzv, abcd);
            }
            return interpolated;
        }

        [
            [0, 1, 2, 3],
            [3, 0, 1, 2],
            [2, 3, 0, 1],
            [1, 2, 3, 0]
        ].forEach(function(e) {
            if(ok[e[0]] && ok[e[1]] && ok[e[2]] && !ok[e[3]]) {
                var A = xyzv[e[0]];
                var B = xyzv[e[1]];
                var C = xyzv[e[2]];
                var D = xyzv[e[3]];

                if(drawingSpaceframe) {
                    drawTri(style, [A, B, C], [abcd[e[0]], abcd[e[1]], abcd[e[2]]]);
                } else {
                    var p1 = calcIntersection(D, A, min, max);
                    var p2 = calcIntersection(D, B, min, max);
                    var p3 = calcIntersection(D, C, min, max);

                    drawTri(null, [p1, p2, p3], [-1, -1, -1]);
                }

                interpolated = true;
            }
        });
        if(interpolated) return interpolated;

        [
            [0, 1, 2, 3],
            [1, 2, 3, 0],
            [2, 3, 0, 1],
            [3, 0, 1, 2],
            [0, 2, 3, 1],
            [1, 3, 2, 0]
        ].forEach(function(e) {
            if(ok[e[0]] && ok[e[1]] && !ok[e[2]] && !ok[e[3]]) {
                var A = xyzv[e[0]];
                var B = xyzv[e[1]];
                var C = xyzv[e[2]];
                var D = xyzv[e[3]];

                var p1 = calcIntersection(C, A, min, max);
                var p2 = calcIntersection(C, B, min, max);
                var p3 = calcIntersection(D, B, min, max);
                var p4 = calcIntersection(D, A, min, max);

                if(drawingSpaceframe) {
                    drawTri(style, [A, p4, p1], [abcd[e[0]], -1, -1]);
                    drawTri(style, [B, p2, p3], [abcd[e[1]], -1, -1]);
                } else {
                    drawQuad(null, [p1, p2, p3, p4], [-1, -1, -1, -1]);
                }

                interpolated = true;
            }
        });
        if(interpolated) return interpolated;

        [
            [0, 1, 2, 3],
            [1, 2, 3, 0],
            [2, 3, 0, 1],
            [3, 0, 1, 2]
        ].forEach(function(e) {
            if(ok[e[0]] && !ok[e[1]] && !ok[e[2]] && !ok[e[3]]) {
                var A = xyzv[e[0]];
                var B = xyzv[e[1]];
                var C = xyzv[e[2]];
                var D = xyzv[e[3]];

                var p1 = calcIntersection(B, A, min, max);
                var p2 = calcIntersection(C, A, min, max);
                var p3 = calcIntersection(D, A, min, max);

                if(drawingSpaceframe) {
                    drawTri(style, [A, p1, p2], [abcd[e[0]], -1, -1]);
                    drawTri(style, [A, p2, p3], [abcd[e[0]], -1, -1]);
                    drawTri(style, [A, p3, p1], [abcd[e[0]], -1, -1]);
                } else {
                    drawTri(null, [p1, p2, p3], [-1, -1, -1]);
                }

                interpolated = true;
            }
        });
        return interpolated;
    }

    function addCube(style, p000, p001, p010, p011, p100, p101, p110, p111, min, max) {

        if(drawingSurface) {
            if(styleIncludes(style, 'A')) {
                tryCreateTetra(null, [p000, p001, p010, p100], min, max);
            }
            if(styleIncludes(style, 'B')) {
                tryCreateTetra(null, [p001, p010, p011, p111], min, max);
            }
            if(styleIncludes(style, 'C')) {
                tryCreateTetra(null, [p001, p100, p101, p111], min, max);
            }
            if(styleIncludes(style, 'D')) {
                tryCreateTetra(null, [p010, p100, p110, p111], min, max);
            }
            if(styleIncludes(style, 'E')) {
                tryCreateTetra(null, [p001, p010, p100, p111], min, max);
            }
        }

        if(drawingSpaceframe) {
            tryCreateTetra(style, [p001, p010, p100, p111], min, max);
        }
    }

    function addRect(style, a, b, c, d, min, max) {
        tryCreateTri(style, getXYZV([a, b, c]), [a, b, c], min, max);
        tryCreateTri(style, getXYZV([c, d, a]), [c, d, a], min, max);
    }

    function begin2dCell(style, p00, p01, p10, p11, min, max, isEven) {
        // used to create caps and/or slices on exact axis points
        if(isEven) {
            addRect(style, p00, p01, p11, p10, min, max);
        } else {
            addRect(style, p01, p11, p10, p00, min, max);
        }
    }

    function beginSection(style, i, j, k, min, max, distRatios) {
        // used to create slices between axis points

        var A, B, C, D;

        var makeSection = function() {
            tryCreateTri(style, [A, B, C], [-1, -1, -1], min, max);
            tryCreateTri(style, [C, D, A], [-1, -1, -1], min, max);
        };

        var rX = distRatios[0];
        var rY = distRatios[1];
        var rZ = distRatios[2];

        if(rX) {
            A = getBetween(getXYZV([getIndex(i, j - 0, k - 0)])[0], getXYZV([getIndex(i - 1, j - 0, k - 0)])[0], rX);
            B = getBetween(getXYZV([getIndex(i, j - 0, k - 1)])[0], getXYZV([getIndex(i - 1, j - 0, k - 1)])[0], rX);
            C = getBetween(getXYZV([getIndex(i, j - 1, k - 1)])[0], getXYZV([getIndex(i - 1, j - 1, k - 1)])[0], rX);
            D = getBetween(getXYZV([getIndex(i, j - 1, k - 0)])[0], getXYZV([getIndex(i - 1, j - 1, k - 0)])[0], rX);
            makeSection();
        }

        if(rY) {
            A = getBetween(getXYZV([getIndex(i - 0, j, k - 0)])[0], getXYZV([getIndex(i - 0, j - 1, k - 0)])[0], rY);
            B = getBetween(getXYZV([getIndex(i - 0, j, k - 1)])[0], getXYZV([getIndex(i - 0, j - 1, k - 1)])[0], rY);
            C = getBetween(getXYZV([getIndex(i - 1, j, k - 1)])[0], getXYZV([getIndex(i - 1, j - 1, k - 1)])[0], rY);
            D = getBetween(getXYZV([getIndex(i - 1, j, k - 0)])[0], getXYZV([getIndex(i - 1, j - 1, k - 0)])[0], rY);
            makeSection();
        }

        if(rZ) {
            A = getBetween(getXYZV([getIndex(i - 0, j - 0, k)])[0], getXYZV([getIndex(i - 0, j - 0, k - 1)])[0], rZ);
            B = getBetween(getXYZV([getIndex(i - 0, j - 1, k)])[0], getXYZV([getIndex(i - 0, j - 1, k - 1)])[0], rZ);
            C = getBetween(getXYZV([getIndex(i - 1, j - 1, k)])[0], getXYZV([getIndex(i - 1, j - 1, k - 1)])[0], rZ);
            D = getBetween(getXYZV([getIndex(i - 1, j - 0, k)])[0], getXYZV([getIndex(i - 1, j - 0, k - 1)])[0], rZ);
            makeSection();
        }
    }

    function begin3dCell(style, p000, p001, p010, p011, p100, p101, p110, p111, min, max, isEven) {
        // used to create spaceframe and/or iso-surfaces
        var cellStyle = style;
        if(isEven) {
            if(drawingSurface && style === 'even') cellStyle = null;
            addCube(cellStyle, p000, p001, p010, p011, p100, p101, p110, p111, min, max);
        } else {
            if(drawingSurface && style === 'odd') cellStyle = null;
            addCube(cellStyle, p111, p110, p101, p100, p011, p010, p001, p000, min, max);
        }
    }

    function draw2dX(style, items, min, max) {
        for(var q = 0; q < items.length; q++) {
            var i = items[q];
            for(var k = 1; k < depth; k++) {
                for(var j = 1; j < height; j++) {
                    begin2dCell(style,
                        getIndex(i, j - 1, k - 1),
                        getIndex(i, j - 1, k),
                        getIndex(i, j, k - 1),
                        getIndex(i, j, k),
                        min,
                        max,
                        (i + j + k) % 2
                    );
                }
            }
        }
    }

    function draw2dY(style, items, min, max) {
        for(var q = 0; q < items.length; q++) {
            var j = items[q];
            for(var i = 1; i < width; i++) {
                for(var k = 1; k < depth; k++) {
                    begin2dCell(style,
                        getIndex(i - 1, j, k - 1),
                        getIndex(i, j, k - 1),
                        getIndex(i - 1, j, k),
                        getIndex(i, j, k),
                        min,
                        max,
                        (i + j + k) % 2
                    );
                }
            }
        }
    }

    function draw2dZ(style, items, min, max) {
        for(var q = 0; q < items.length; q++) {
            var k = items[q];
            for(var j = 1; j < height; j++) {
                for(var i = 1; i < width; i++) {
                    begin2dCell(style,
                        getIndex(i - 1, j - 1, k),
                        getIndex(i - 1, j, k),
                        getIndex(i, j - 1, k),
                        getIndex(i, j, k),
                        min,
                        max,
                        (i + j + k) % 2
                    );
                }
            }
        }
    }

    function draw3d(style, min, max) {
        for(var k = 1; k < depth; k++) {
            for(var j = 1; j < height; j++) {
                for(var i = 1; i < width; i++) {
                    begin3dCell(style,
                        getIndex(i - 1, j - 1, k - 1),
                        getIndex(i - 1, j - 1, k),
                        getIndex(i - 1, j, k - 1),
                        getIndex(i - 1, j, k),
                        getIndex(i, j - 1, k - 1),
                        getIndex(i, j - 1, k),
                        getIndex(i, j, k - 1),
                        getIndex(i, j, k),
                        min,
                        max,
                        (i + j + k) % 2
                    );
                }
            }
        }
    }

    function drawSpaceframe(style, min, max) {
        drawingSpaceframe = true;
        draw3d(style, min, max);
        drawingSpaceframe = false;
    }

    function drawSurface(style, min, max) {
        drawingSurface = true;
        draw3d(style, min, max);
        drawingSurface = false;
    }

    function drawSectionX(style, items, min, max, distRatios) {
        for(var q = 0; q < items.length; q++) {
            var i = items[q];
            for(var k = 1; k < depth; k++) {
                for(var j = 1; j < height; j++) {
                    beginSection(style, i, j, k, min, max, distRatios[q]);
                }
            }
        }
    }

    function drawSectionY(style, items, min, max, distRatios) {
        for(var q = 0; q < items.length; q++) {
            var j = items[q];
            for(var i = 1; i < width; i++) {
                for(var k = 1; k < depth; k++) {
                    beginSection(style, i, j, k, min, max, distRatios[q]);
                }
            }
        }
    }

    function drawSectionZ(style, items, min, max, distRatios) {
        for(var q = 0; q < items.length; q++) {
            var k = items[q];
            for(var j = 1; j < height; j++) {
                for(var i = 1; i < width; i++) {
                    beginSection(style, i, j, k, min, max, distRatios[q]);
                }
            }
        }
    }

    function createRange(a, b) {
        var range = [];
        for(var q = a; q < b; q++) {
            range.push(q);
        }
        return range;
    }

    function insertGridPoints() {
        for(var i = 0; i < width; i++) {
            for(var j = 0; j < height; j++) {
                for(var k = 0; k < depth; k++) {
                    var index = getIndex(i, j, k);
                    addVertex(
                        data.x[index],
                        data.y[index],
                        data.z[index],
                        data.value[index]
                    );
                }
            }
        }
    }

    function drawAll() {

        emptyVertices();

        // insert grid points
        insertGridPoints();

        var activeStyle = null;

        // draw spaceframes
        if(showSpaceframe && spaceframeFill) {
            setFill(spaceframeFill);

            drawSpaceframe(activeStyle, vMin, vMax);
        }

        // draw iso-surfaces
        if(showSurface && surfaceFill) {
            setFill(surfaceFill);

            var surfacePattern = data.surface.pattern;
            var surfaceCount = data.surface.count;
            for(var q = 0; q < surfaceCount; q++) {
                var ratio = (surfaceCount === 1) ? 0.5 : q / (surfaceCount - 1);
                var level = (1 - ratio) * vMin + ratio * vMax;

                var d1 = Math.abs(level - minValues);
                var d2 = Math.abs(level - maxValues);
                var ranges = (d1 > d2) ?
                    [minValues, level] :
                    [level, maxValues];

                drawSurface(surfacePattern, ranges[0], ranges[1]);
            }
        }

        var setupMinMax = [
            [ Math.min(vMin, maxValues), Math.max(vMin, maxValues) ],
            [ Math.min(minValues, vMax), Math.max(minValues, vMax) ]
        ];

        ['x', 'y', 'z'].forEach(function(e) {
            for(var s = 0; s < setupMinMax.length; s++) {

                drawingEdge = (s === 0) ? false : true;

                var activeMin = setupMinMax[s][0];
                var activeMax = setupMinMax[s][1];

                // draw slices
                var slice = data.slices[e];
                if(slice.show && slice.fill) {
                    setFill(slice.fill);

                    var exactIndices = [];
                    var ceilIndices = [];
                    var distRatios = [];
                    if(slice.locations.length) {

                        for(var q = 0; q < slice.locations.length; q++) {

                            var near = findNearestOnAxis(
                                slice.locations[q],
                                (e === 'x') ? Xs :
                                (e === 'y') ? Ys : Zs
                            );

                            if(near.distRatio === 0) {
                                exactIndices.push(near.id);
                            } else if(near.id > 0) {
                                ceilIndices.push(near.id);
                                if(e === 'x') {
                                    distRatios.push([near.distRatio, 0, 0]);
                                } else if(e === 'y') {
                                    distRatios.push([0, near.distRatio, 0]);
                                } else {
                                    distRatios.push([0, 0, near.distRatio]);
                                }
                            }
                        }
                    } else {
                        if(e === 'x') {
                            exactIndices = createRange(1, width - 1);
                        } else if(e === 'y') {
                            exactIndices = createRange(1, height - 1);
                        } else {
                            exactIndices = createRange(1, depth - 1);
                        }
                    }

                    if(ceilIndices.length > 0) {
                        if(e === 'x') {
                            drawSectionX(activeStyle, ceilIndices, activeMin, activeMax, distRatios);
                        } else if(e === 'y') {
                            drawSectionY(activeStyle, ceilIndices, activeMin, activeMax, distRatios);
                        } else {
                            drawSectionZ(activeStyle, ceilIndices, activeMin, activeMax, distRatios);
                        }
                    }

                    if(exactIndices.length > 0) {
                        if(e === 'x') {
                            draw2dX(activeStyle, exactIndices, activeMin, activeMax);
                        } else if(e === 'y') {
                            draw2dY(activeStyle, exactIndices, activeMin, activeMax);
                        } else {
                            draw2dZ(activeStyle, exactIndices, activeMin, activeMax);
                        }
                    }
                }

                // draw caps
                var cap = data.caps[e];
                if(cap.show && cap.fill) {
                    setFill(cap.fill);
                    if(e === 'x') {
                        draw2dX(activeStyle, [0, width - 1], activeMin, activeMax);
                    } else if(e === 'y') {
                        draw2dY(activeStyle, [0, height - 1], activeMin, activeMax);
                    } else {
                        draw2dZ(activeStyle, [0, depth - 1], activeMin, activeMax);
                    }
                }
            }
        });

        // remove vertices arrays (i.e. grid points) in case no face was created.
        if(numFaces === 0) {
            emptyVertices();
        }

        data._x = allXs;
        data._y = allYs;
        data._z = allZs;
        data._intensity = allVs;

        data._Xs = Xs;
        data._Ys = Ys;
        data._Zs = Zs;
    }

    drawAll();

    return data;
}

function createIsosurfaceTrace(scene, data) {

    var gl = scene.glplot.gl;
    var mesh = createMesh({gl: gl});
    var result = new IsosurfaceTrace(scene, mesh, data.uid);

    mesh._trace = result;
    result.update(data);
    scene.glplot.add(mesh);
    return result;
}

module.exports = createIsosurfaceTrace;

},{"../../lib":694,"../../lib/gl_format_color":691,"../../lib/str2rgbarray":717,"../../plots/gl3d/zip3":796,"gl-mesh3d":270}],988:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var isomin = coerce('isomin');
    var isomax = coerce('isomax');

    if(isomax !== undefined && isomax !== null &&
        isomin !== undefined && isomin !== null &&
         isomin > isomax) {
        // applying default values in this case:
        traceOut.isomin = null;
        traceOut.isomax = null;
    }

    var x = coerce('x');
    var y = coerce('y');
    var z = coerce('z');
    var value = coerce('value');

    if(
        !x || !x.length ||
        !y || !y.length ||
        !z || !z.length ||
        !value || !value.length
    ) {
        traceOut.visible = false;
        return;
    }

    var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
    handleCalendarDefaults(traceIn, traceOut, ['x', 'y', 'z'], layout);

    ['x', 'y', 'z'].forEach(function(dim) {

        var capDim = 'caps.' + dim;
        var showCap = coerce(capDim + '.show');
        if(showCap) {
            coerce(capDim + '.fill');
        }

        var sliceDim = 'slices.' + dim;
        var showSlice = coerce(sliceDim + '.show');
        if(showSlice) {
            coerce(sliceDim + '.fill');
            coerce(sliceDim + '.locations');
        }
    });

    var showSpaceframe = coerce('spaceframe.show');
    if(showSpaceframe) {
        coerce('spaceframe.fill');
    }

    var showSurface = coerce('surface.show');
    if(showSurface) {
        coerce('surface.count');
        coerce('surface.fill');
        coerce('surface.pattern');
    }

    var showContour = coerce('contour.show');
    if(showContour) {
        coerce('contour.color');
        coerce('contour.width');
    }

    // Coerce remaining properties
    [
        'text',
        'lighting.ambient',
        'lighting.diffuse',
        'lighting.specular',
        'lighting.roughness',
        'lighting.fresnel',
        'lighting.vertexnormalsepsilon',
        'lighting.facenormalsepsilon',
        'lightposition.x',
        'lightposition.y',
        'lightposition.z',
        'flatshading',
    ].forEach(function(x) { coerce(x); });

    colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'c'});

    // disable 1D transforms (for now)
    traceOut._length = null;
};

},{"../../components/colorscale/defaults":581,"../../lib":694,"../../registry":825,"./attributes":985}],989:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Isosurface = {};

Isosurface.attributes = _dereq_('./attributes');
Isosurface.supplyDefaults = _dereq_('./defaults');
Isosurface.calc = _dereq_('./calc');
Isosurface.colorbar = {
    min: 'cmin',
    max: 'cmax'
};
Isosurface.plot = _dereq_('./convert');

Isosurface.moduleType = 'trace';
Isosurface.name = 'isosurface',
Isosurface.basePlotModule = _dereq_('../../plots/gl3d');
Isosurface.categories = ['gl3d'];
Isosurface.meta = {
    
};

module.exports = Isosurface;

},{"../../plots/gl3d":785,"./attributes":985,"./calc":986,"./convert":987,"./defaults":988}],990:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
var surfaceAtts = _dereq_('../surface/attributes');
var baseAttrs = _dereq_('../../plots/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;

module.exports = extendFlat({
    x: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },
    y: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },
    z: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },

    i: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    j: {
        valType: 'data_array',
        editType: 'calc',
        

    },
    k: {
        valType: 'data_array',
        editType: 'calc',
        

    },

    text: {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        editType: 'calc',
        
    },

    delaunayaxis: {
        valType: 'enumerated',
        
        values: [ 'x', 'y', 'z' ],
        dflt: 'z',
        editType: 'calc',
        
    },

    alphahull: {
        valType: 'number',
        
        dflt: -1,
        editType: 'calc',
        
    },

    intensity: {
        valType: 'data_array',
        editType: 'calc',
        
    },

    // Color field
    color: {
        valType: 'color',
        
        editType: 'calc',
        
    },
    vertexcolor: {
        valType: 'data_array',
        
        editType: 'calc',
        
    },
    facecolor: {
        valType: 'data_array',
        
        editType: 'calc',
        
    },
    transforms: undefined
},

colorscaleAttrs('', {
    colorAttr: '`intensity`',
    showScaleDflt: true,
    editTypeOverride: 'calc'
}), {

    colorbar: colorbarAttrs,

    opacity: surfaceAtts.opacity,

    // Flat shaded mode
    flatshading: {
        valType: 'boolean',
        
        dflt: false,
        editType: 'calc',
        
    },

    contour: {
        show: extendFlat({}, surfaceAtts.contours.x.show, {
            
        }),
        color: surfaceAtts.contours.x.color,
        width: surfaceAtts.contours.x.width,
        editType: 'calc'
    },

    lightposition: {
        x: extendFlat({}, surfaceAtts.lightposition.x, {dflt: 1e5}),
        y: extendFlat({}, surfaceAtts.lightposition.y, {dflt: 1e5}),
        z: extendFlat({}, surfaceAtts.lightposition.z, {dflt: 0}),
        editType: 'calc'
    },
    lighting: extendFlat({
        vertexnormalsepsilon: {
            valType: 'number',
            
            min: 0.00,
            max: 1,
            dflt: 1e-12, // otherwise finely tessellated things eg. the brain will have no specular light reflection
            editType: 'calc',
            
        },
        facenormalsepsilon: {
            valType: 'number',
            
            min: 0.00,
            max: 1,
            dflt: 1e-6, // even the brain model doesn't appear to need finer than this
            editType: 'calc',
            
        },
        editType: 'calc'
    }, surfaceAtts.lighting),

    hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {editType: 'calc'})
});

},{"../../components/colorbar/attributes":572,"../../components/colorscale/attributes":578,"../../lib/extend":684,"../../plots/attributes":739,"../surface/attributes":1134}],991:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorscaleCalc = _dereq_('../../components/colorscale/calc');

module.exports = function calc(gd, trace) {
    if(trace.intensity) {
        colorscaleCalc(gd, trace, {
            vals: trace.intensity,
            containerStr: '',
            cLetter: 'c'
        });
    }
};

},{"../../components/colorscale/calc":579}],992:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var createMesh = _dereq_('gl-mesh3d');
var triangulate = _dereq_('delaunay-triangulate');
var alphaShape = _dereq_('alpha-shape');
var convexHull = _dereq_('convex-hull');

var parseColorScale = _dereq_('../../lib/gl_format_color').parseColorScale;
var str2RgbaArray = _dereq_('../../lib/str2rgbarray');
var zip3 = _dereq_('../../plots/gl3d/zip3');

function Mesh3DTrace(scene, mesh, uid) {
    this.scene = scene;
    this.uid = uid;
    this.mesh = mesh;
    this.name = '';
    this.color = '#fff';
    this.data = null;
    this.showContour = false;
}

var proto = Mesh3DTrace.prototype;

proto.handlePick = function(selection) {
    if(selection.object === this.mesh) {
        var selectIndex = selection.index = selection.data.index;

        selection.traceCoordinate = [
            this.data.x[selectIndex],
            this.data.y[selectIndex],
            this.data.z[selectIndex]
        ];

        var text = this.data.text;
        if(Array.isArray(text) && text[selectIndex] !== undefined) {
            selection.textLabel = text[selectIndex];
        } else if(text) {
            selection.textLabel = text;
        }

        return true;
    }
};

function parseColorArray(colors) {
    var b = [];
    var len = colors.length;
    for(var i = 0; i < len; i++) {
        b[i] = str2RgbaArray(colors[i]);
    }
    return b;
}

// Unpack position data
function toDataCoords(axis, coord, scale, calendar) {
    var b = [];
    var len = coord.length;
    for(var i = 0; i < len; i++) {
        b[i] = axis.d2l(coord[i], 0, calendar) * scale;
    }
    return b;
}

// Round indices if passed as floats
function toRoundIndex(a) {
    var b = [];
    var len = a.length;
    for(var i = 0; i < len; i++) {
        b[i] = Math.round(a[i]);
    }
    return b;
}

function delaunayCells(delaunayaxis, positions) {
    var d = ['x', 'y', 'z'].indexOf(delaunayaxis);
    var b = [];
    var len = positions.length;
    for(var i = 0; i < len; i++) {
        b[i] = [positions[i][(d + 1) % 3], positions[i][(d + 2) % 3]];
    }
    return triangulate(b);
}

// Validate indices
function hasValidIndices(list, numVertices) {
    var len = list.length;
    for(var i = 0; i < len; i++) {
        if(list[i] <= -0.5 || list[i] >= numVertices - 0.5) { // Note: the indices would be rounded -0.49 is valid.
            return false;
        }
    }
    return true;
}

proto.update = function(data) {
    var scene = this.scene;
    var layout = scene.fullSceneLayout;

    this.data = data;

    var numVertices = data.x.length;

    var positions = zip3(
        toDataCoords(layout.xaxis, data.x, scene.dataScale[0], data.xcalendar),
        toDataCoords(layout.yaxis, data.y, scene.dataScale[1], data.ycalendar),
        toDataCoords(layout.zaxis, data.z, scene.dataScale[2], data.zcalendar)
    );

    var cells;
    if(data.i && data.j && data.k) {

        if(
            data.i.length !== data.j.length ||
            data.j.length !== data.k.length ||
            !hasValidIndices(data.i, numVertices) ||
            !hasValidIndices(data.j, numVertices) ||
            !hasValidIndices(data.k, numVertices)
        ) {
            return;
        }
        cells = zip3(
            toRoundIndex(data.i),
            toRoundIndex(data.j),
            toRoundIndex(data.k)
        );
    } else if(data.alphahull === 0) {
        cells = convexHull(positions);
    } else if(data.alphahull > 0) {
        cells = alphaShape(data.alphahull, positions);
    } else {
        cells = delaunayCells(data.delaunayaxis, positions);
    }

    var config = {
        positions: positions,
        cells: cells,
        lightPosition: [data.lightposition.x, data.lightposition.y, data.lightposition.z],
        ambient: data.lighting.ambient,
        diffuse: data.lighting.diffuse,
        specular: data.lighting.specular,
        roughness: data.lighting.roughness,
        fresnel: data.lighting.fresnel,
        vertexNormalsEpsilon: data.lighting.vertexnormalsepsilon,
        faceNormalsEpsilon: data.lighting.facenormalsepsilon,
        opacity: data.opacity,
        contourEnable: data.contour.show,
        contourColor: str2RgbaArray(data.contour.color).slice(0, 3),
        contourWidth: data.contour.width,
        useFacetNormals: data.flatshading
    };

    if(data.intensity) {
        this.color = '#fff';
        config.vertexIntensity = data.intensity;
        config.vertexIntensityBounds = [data.cmin, data.cmax];
        config.colormap = parseColorScale(data);
    } else if(data.vertexcolor) {
        this.color = data.vertexcolor[0];
        config.vertexColors = parseColorArray(data.vertexcolor);
    } else if(data.facecolor) {
        this.color = data.facecolor[0];
        config.cellColors = parseColorArray(data.facecolor);
    } else {
        this.color = data.color;
        config.meshColor = str2RgbaArray(data.color);
    }

    // Update mesh
    this.mesh.update(config);
};

proto.dispose = function() {
    this.scene.glplot.remove(this.mesh);
    this.mesh.dispose();
};

function createMesh3DTrace(scene, data) {
    var gl = scene.glplot.gl;
    var mesh = createMesh({gl: gl});
    var result = new Mesh3DTrace(scene, mesh, data.uid);
    mesh._trace = result;
    result.update(data);
    scene.glplot.add(mesh);
    return result;
}

module.exports = createMesh3DTrace;

},{"../../lib/gl_format_color":691,"../../lib/str2rgbarray":717,"../../plots/gl3d/zip3":796,"alpha-shape":53,"convex-hull":119,"delaunay-triangulate":151,"gl-mesh3d":270}],993:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    // read in face/vertex properties
    function readComponents(array) {
        var ret = array.map(function(attr) {
            var result = coerce(attr);

            if(result && Lib.isArrayOrTypedArray(result)) return result;
            return null;
        });

        return ret.every(function(x) {
            return x && x.length === ret[0].length;
        }) && ret;
    }

    var coords = readComponents(['x', 'y', 'z']);
    if(!coords) {
        traceOut.visible = false;
        return;
    }

    readComponents(['i', 'j', 'k']);
    // three indices should be all provided or not
    if(
        (traceOut.i && (!traceOut.j || !traceOut.k)) ||
        (traceOut.j && (!traceOut.k || !traceOut.i)) ||
        (traceOut.k && (!traceOut.i || !traceOut.j))
    ) {
        traceOut.visible = false;
        return;
    }

    var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
    handleCalendarDefaults(traceIn, traceOut, ['x', 'y', 'z'], layout);

    // Coerce remaining properties
    [
        'lighting.ambient',
        'lighting.diffuse',
        'lighting.specular',
        'lighting.roughness',
        'lighting.fresnel',
        'lighting.vertexnormalsepsilon',
        'lighting.facenormalsepsilon',
        'lightposition.x',
        'lightposition.y',
        'lightposition.z',
        'contour.show',
        'contour.color',
        'contour.width',
        'colorscale',
        'reversescale',
        'flatshading',
        'alphahull',
        'delaunayaxis',
        'opacity'
    ].forEach(function(x) { coerce(x); });

    if('intensity' in traceIn) {
        coerce('intensity');
        colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'c'});
    } else {
        traceOut.showscale = false;

        if('facecolor' in traceIn) coerce('facecolor');
        else if('vertexcolor' in traceIn) coerce('vertexcolor');
        else coerce('color', defaultColor);
    }

    coerce('text');

    // disable 1D transforms
    // x/y/z should match lengths, and i/j/k should match as well, but
    // the two sets have different lengths so transforms wouldn't work.
    traceOut._length = null;
};

},{"../../components/colorscale/defaults":581,"../../lib":694,"../../registry":825,"./attributes":990}],994:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Mesh3D = {};

Mesh3D.attributes = _dereq_('./attributes');
Mesh3D.supplyDefaults = _dereq_('./defaults');
Mesh3D.calc = _dereq_('./calc');
Mesh3D.colorbar = {
    min: 'cmin',
    max: 'cmax'
};
Mesh3D.plot = _dereq_('./convert');

Mesh3D.moduleType = 'trace';
Mesh3D.name = 'mesh3d',
Mesh3D.basePlotModule = _dereq_('../../plots/gl3d');
Mesh3D.categories = ['gl3d'];
Mesh3D.meta = {
    
};

module.exports = Mesh3D;

},{"../../plots/gl3d":785,"./attributes":990,"./calc":991,"./convert":992,"./defaults":993}],995:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var extendFlat = _dereq_('../../lib').extendFlat;
var scatterAttrs = _dereq_('../scatter/attributes');
var dash = _dereq_('../../components/drawing/attributes').dash;
var fxAttrs = _dereq_('../../components/fx/attributes');

var INCREASING_COLOR = '#3D9970';
var DECREASING_COLOR = '#FF4136';

var lineAttrs = scatterAttrs.line;

function directionAttrs(lineColorDefault) {
    return {
        line: {
            color: extendFlat({}, lineAttrs.color, {dflt: lineColorDefault}),
            width: lineAttrs.width,
            dash: dash,
            editType: 'style'
        },
        editType: 'style'
    };
}

module.exports = {

    x: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },

    open: {
        valType: 'data_array',
        editType: 'calc',
        
    },

    high: {
        valType: 'data_array',
        editType: 'calc',
        
    },

    low: {
        valType: 'data_array',
        editType: 'calc',
        
    },

    close: {
        valType: 'data_array',
        editType: 'calc',
        
    },

    line: {
        width: extendFlat({}, lineAttrs.width, {
            
        }),
        dash: extendFlat({}, dash, {
            
        }),
        editType: 'style'
    },

    increasing: directionAttrs(INCREASING_COLOR),

    decreasing: directionAttrs(DECREASING_COLOR),

    text: {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        editType: 'calc',
        
    },

    tickwidth: {
        valType: 'number',
        min: 0,
        max: 0.5,
        dflt: 0.3,
        
        editType: 'calc',
        
    },

    hoverlabel: extendFlat({}, fxAttrs.hoverlabel, {
        split: {
            valType: 'boolean',
            
            dflt: false,
            editType: 'style',
            
        }
    }),
};

},{"../../components/drawing/attributes":591,"../../components/fx/attributes":601,"../../lib":694,"../scatter/attributes":1047}],996:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var _ = Lib._;
var Axes = _dereq_('../../plots/cartesian/axes');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

function calc(gd, trace) {
    var xa = Axes.getFromId(gd, trace.xaxis);
    var ya = Axes.getFromId(gd, trace.yaxis);

    var tickLen = convertTickWidth(gd, xa, trace);
    var minDiff = trace._minDiff;
    trace._minDiff = null;
    var x = trace._xcalc;
    trace._xcalc = null;

    var cd = calcCommon(gd, trace, x, ya, ptFunc);

    trace._extremes[xa._id] = Axes.findExtremes(xa, x, {vpad: minDiff / 2});
    if(cd.length) {
        Lib.extendFlat(cd[0].t, {
            wHover: minDiff / 2,
            tickLen: tickLen
        });
        return cd;
    } else {
        return [{t: {empty: true}}];
    }
}

function ptFunc(o, h, l, c) {
    return {
        o: o,
        h: h,
        l: l,
        c: c
    };
}


// shared between OHLC and candlestick
// ptFunc makes a calcdata point specific to each trace type, from oi, hi, li, ci
function calcCommon(gd, trace, x, ya, ptFunc) {
    var o = ya.makeCalcdata(trace, 'open');
    var h = ya.makeCalcdata(trace, 'high');
    var l = ya.makeCalcdata(trace, 'low');
    var c = ya.makeCalcdata(trace, 'close');

    var hasTextArray = Array.isArray(trace.text);

    // we're optimists - before we have any changing data, assume increasing
    var increasing = true;
    var cPrev = null;

    var cd = [];
    for(var i = 0; i < x.length; i++) {
        var xi = x[i];
        var oi = o[i];
        var hi = h[i];
        var li = l[i];
        var ci = c[i];

        if(xi !== BADNUM && oi !== BADNUM && hi !== BADNUM && li !== BADNUM && ci !== BADNUM) {
            if(ci === oi) {
                // if open == close, look for a change from the previous close
                if(cPrev !== null && ci !== cPrev) increasing = ci > cPrev;
                // else (c === cPrev or cPrev is null) no change
            }
            else increasing = ci > oi;

            cPrev = ci;

            var pt = ptFunc(oi, hi, li, ci);

            pt.pos = xi;
            pt.yc = (oi + ci) / 2;
            pt.i = i;
            pt.dir = increasing ? 'increasing' : 'decreasing';

            if(hasTextArray) pt.tx = trace.text[i];

            cd.push(pt);
        } else {
            cd.push({empty: true});
        }
    }

    trace._extremes[ya._id] = Axes.findExtremes(ya, Lib.concat(l, h), {padded: true});

    if(cd.length) {
        cd[0].t = {
            labels: {
                open: _(gd, 'open:') + ' ',
                high: _(gd, 'high:') + ' ',
                low: _(gd, 'low:') + ' ',
                close: _(gd, 'close:') + ' '
            }
        };
    }

    return cd;
}

/*
 * find min x-coordinates difference of all traces
 * attached to this x-axis and stash the result in _minDiff
 * in all traces; when a trace uses this in its
 * calc step it deletes _minDiff, so that next calc this is
 * done again in case the data changed.
 * also since we need it here, stash _xcalc on the trace
 */
function convertTickWidth(gd, xa, trace) {
    var minDiff = trace._minDiff;

    if(!minDiff) {
        var fullData = gd._fullData;
        var ohlcTracesOnThisXaxis = [];

        minDiff = Infinity;

        var i;

        for(i = 0; i < fullData.length; i++) {
            var tracei = fullData[i];

            if(tracei.type === 'ohlc' &&
                tracei.visible === true &&
                tracei.xaxis === xa._id
            ) {
                ohlcTracesOnThisXaxis.push(tracei);

                var xcalc = xa.makeCalcdata(tracei, 'x');
                tracei._xcalc = xcalc;

                var _minDiff = Lib.distinctVals(xcalc).minDiff;
                if(_minDiff && isFinite(_minDiff)) {
                    minDiff = Math.min(minDiff, _minDiff);
                }
            }
        }

        // if minDiff is still Infinity here, set it to 1
        if(minDiff === Infinity) minDiff = 1;

        for(i = 0; i < ohlcTracesOnThisXaxis.length; i++) {
            ohlcTracesOnThisXaxis[i]._minDiff = minDiff;
        }
    }

    return minDiff * trace.tickwidth;
}

module.exports = {
    calc: calc,
    calcCommon: calcCommon
};

},{"../../constants/numerical":671,"../../lib":694,"../../plots/cartesian/axes":742}],997:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');
var handleOHLC = _dereq_('./ohlc_defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var len = handleOHLC(traceIn, traceOut, coerce, layout);
    if(!len) {
        traceOut.visible = false;
        return;
    }

    coerce('line.width');
    coerce('line.dash');

    handleDirection(traceIn, traceOut, coerce, 'increasing');
    handleDirection(traceIn, traceOut, coerce, 'decreasing');

    coerce('text');
    coerce('tickwidth');

    layout._requestRangeslider[traceOut.xaxis] = true;
};

function handleDirection(traceIn, traceOut, coerce, direction) {
    coerce(direction + '.line.color');
    coerce(direction + '.line.width', traceOut.line.width);
    coerce(direction + '.line.dash', traceOut.line.dash);
}

},{"../../lib":694,"./attributes":995,"./ohlc_defaults":1000}],998:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Axes = _dereq_('../../plots/cartesian/axes');
var Lib = _dereq_('../../lib');
var Fx = _dereq_('../../components/fx');
var Color = _dereq_('../../components/color');
var fillHoverText = _dereq_('../scatter/fill_hover_text');

var DIRSYMBOL = {
    increasing: '▲',
    decreasing: '▼'
};

function hoverPoints(pointData, xval, yval, hovermode) {
    var cd = pointData.cd;
    var trace = cd[0].trace;

    if(trace.hoverlabel.split) {
        return hoverSplit(pointData, xval, yval, hovermode);
    }

    return hoverOnPoints(pointData, xval, yval, hovermode);
}

function getClosestPoint(pointData, xval, yval, hovermode) {
    var cd = pointData.cd;
    var xa = pointData.xa;
    var trace = cd[0].trace;
    var t = cd[0].t;

    var type = trace.type;
    var minAttr = type === 'ohlc' ? 'l' : 'min';
    var maxAttr = type === 'ohlc' ? 'h' : 'max';

    var hoverPseudoDistance, spikePseudoDistance;

    // potentially shift xval for grouped candlesticks
    var centerShift = t.bPos || 0;
    var shiftPos = function(di) { return di.pos + centerShift - xval; };

    // ohlc and candlestick call displayHalfWidth different things...
    var displayHalfWidth = t.bdPos || t.tickLen;
    var hoverHalfWidth = t.wHover;

    // if two figures are overlaying, let the narrowest one win
    var pseudoDistance = Math.min(1, displayHalfWidth / Math.abs(xa.r2c(xa.range[1]) - xa.r2c(xa.range[0])));
    hoverPseudoDistance = pointData.maxHoverDistance - pseudoDistance;
    spikePseudoDistance = pointData.maxSpikeDistance - pseudoDistance;

    function dx(di) {
        var pos = shiftPos(di);
        return Fx.inbox(pos - hoverHalfWidth, pos + hoverHalfWidth, hoverPseudoDistance);
    }

    function dy(di) {
        var min = di[minAttr];
        var max = di[maxAttr];
        return min === max || Fx.inbox(min - yval, max - yval, hoverPseudoDistance);
    }

    function dxy(di) { return (dx(di) + dy(di)) / 2; }

    var distfn = Fx.getDistanceFunction(hovermode, dx, dy, dxy);
    Fx.getClosest(cd, distfn, pointData);

    if(pointData.index === false) return null;

    var di = cd[pointData.index];

    if(di.empty) return null;

    var dir = di.dir;
    var container = trace[dir];
    var lc = container.line.color;

    if(Color.opacity(lc) && container.line.width) pointData.color = lc;
    else pointData.color = container.fillcolor;

    pointData.x0 = xa.c2p(di.pos + centerShift - displayHalfWidth, true);
    pointData.x1 = xa.c2p(di.pos + centerShift + displayHalfWidth, true);

    pointData.xLabelVal = di.pos;

    pointData.spikeDistance = dxy(di) * spikePseudoDistance / hoverPseudoDistance;
    pointData.xSpike = xa.c2p(di.pos, true);

    return pointData;
}

function hoverSplit(pointData, xval, yval, hovermode) {
    var cd = pointData.cd;
    var ya = pointData.ya;
    var trace = cd[0].trace;
    var t = cd[0].t;
    var closeBoxData = [];

    var closestPoint = getClosestPoint(pointData, xval, yval, hovermode);
    // skip the rest (for this trace) if we didn't find a close point
    if(!closestPoint) return [];

    var cdIndex = closestPoint.index;
    var di = cd[cdIndex];
    var hoverinfo = di.hi || trace.hoverinfo;
    var hoverParts = hoverinfo.split('+');
    var isAll = hoverinfo === 'all';
    var hasY = isAll || hoverParts.indexOf('y') !== -1;

    // similar to hoverOnPoints, we return nothing
    // if all or y is not present.
    if(!hasY) return [];

    var attrs = ['high', 'open', 'close', 'low'];

    // several attributes can have the same y-coordinate. We will
    // bunch them together in a single text block. For this, we keep
    // a dictionary mapping y-coord -> point data.
    var usedVals = {};

    for(var i = 0; i < attrs.length; i++) {
        var attr = attrs[i];

        var val = trace[attr][closestPoint.index];
        var valPx = ya.c2p(val, true);
        var pointData2;
        if(val in usedVals) {
            pointData2 = usedVals[val];
            pointData2.yLabel += '<br>' + t.labels[attr] + Axes.hoverLabelText(ya, val);
        }
        else {
            // copy out to a new object for each new y-value to label
            pointData2 = Lib.extendFlat({}, closestPoint);

            pointData2.y0 = pointData2.y1 = valPx;
            pointData2.yLabelVal = val;
            pointData2.yLabel = t.labels[attr] + Axes.hoverLabelText(ya, val);

            pointData2.name = '';

            closeBoxData.push(pointData2);
            usedVals[val] = pointData2;
        }
    }

    return closeBoxData;
}

function hoverOnPoints(pointData, xval, yval, hovermode) {
    var cd = pointData.cd;
    var ya = pointData.ya;
    var trace = cd[0].trace;
    var t = cd[0].t;

    var closestPoint = getClosestPoint(pointData, xval, yval, hovermode);
    // skip the rest (for this trace) if we didn't find a close point
    if(!closestPoint) return [];

    // we don't make a calcdata point if we're missing any piece (x/o/h/l/c)
    // so we need to fix the index here to point to the data arrays
    var cdIndex = closestPoint.index;
    var di = cd[cdIndex];
    var i = closestPoint.index = di.i;
    var dir = di.dir;

    function getLabelLine(attr) {
        return t.labels[attr] + Axes.hoverLabelText(ya, trace[attr][i]);
    }

    var hoverinfo = di.hi || trace.hoverinfo;
    var hoverParts = hoverinfo.split('+');
    var isAll = hoverinfo === 'all';
    var hasY = isAll || hoverParts.indexOf('y') !== -1;
    var hasText = isAll || hoverParts.indexOf('text') !== -1;

    var textParts = hasY ? [
        getLabelLine('open'),
        getLabelLine('high'),
        getLabelLine('low'),
        getLabelLine('close') + '  ' + DIRSYMBOL[dir]
    ] : [];
    if(hasText) fillHoverText(di, trace, textParts);

    // don't make .yLabelVal or .text, since we're managing hoverinfo
    // put it all in .extraText
    closestPoint.extraText = textParts.join('<br>');

    // this puts the label *and the spike* at the midpoint of the box, ie
    // halfway between open and close, not between high and low.
    closestPoint.y0 = closestPoint.y1 = ya.c2p(di.yc, true);

    return [closestPoint];
}

module.exports = {
    hoverPoints: hoverPoints,
    hoverSplit: hoverSplit,
    hoverOnPoints: hoverOnPoints
};

},{"../../components/color":571,"../../components/fx":610,"../../lib":694,"../../plots/cartesian/axes":742,"../scatter/fill_hover_text":1055}],999:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'trace',
    name: 'ohlc',
    basePlotModule: _dereq_('../../plots/cartesian'),
    categories: ['cartesian', 'svg', 'showLegend'],
    meta: {
        
    },

    attributes: _dereq_('./attributes'),
    supplyDefaults: _dereq_('./defaults'),
    calc: _dereq_('./calc').calc,
    plot: _dereq_('./plot'),
    style: _dereq_('./style'),
    hoverPoints: _dereq_('./hover').hoverPoints,
    selectPoints: _dereq_('./select')
};

},{"../../plots/cartesian":754,"./attributes":995,"./calc":996,"./defaults":997,"./hover":998,"./plot":1001,"./select":1002,"./style":1003}],1000:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');

module.exports = function handleOHLC(traceIn, traceOut, coerce, layout) {
    var x = coerce('x');
    var open = coerce('open');
    var high = coerce('high');
    var low = coerce('low');
    var close = coerce('close');

    coerce('hoverlabel.split');

    var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
    handleCalendarDefaults(traceIn, traceOut, ['x'], layout);

    if(!(open && high && low && close)) return;

    var len = Math.min(open.length, high.length, low.length, close.length);
    if(x) len = Math.min(len, Lib.minRowLength(x));
    traceOut._length = len;

    return len;
};

},{"../../lib":694,"../../registry":825}],1001:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Lib = _dereq_('../../lib');

module.exports = function plot(gd, plotinfo, cdOHLC, ohlcLayer) {
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    Lib.makeTraceGroups(ohlcLayer, cdOHLC, 'trace ohlc').each(function(cd) {
        var plotGroup = d3.select(this);
        var cd0 = cd[0];
        var t = cd0.t;
        var trace = cd0.trace;
        if(!plotinfo.isRangePlot) cd0.node3 = plotGroup;

        if(trace.visible !== true || t.empty) {
            plotGroup.remove();
            return;
        }

        var tickLen = t.tickLen;

        var paths = plotGroup.selectAll('path').data(Lib.identity);

        paths.enter().append('path');

        paths.exit().remove();

        paths.attr('d', function(d) {
            if(d.empty) return 'M0,0Z';

            var x = xa.c2p(d.pos, true);
            var xo = xa.c2p(d.pos - tickLen, true);
            var xc = xa.c2p(d.pos + tickLen, true);

            var yo = ya.c2p(d.o, true);
            var yh = ya.c2p(d.h, true);
            var yl = ya.c2p(d.l, true);
            var yc = ya.c2p(d.c, true);

            return 'M' + xo + ',' + yo + 'H' + x +
                'M' + x + ',' + yh + 'V' + yl +
                'M' + xc + ',' + yc + 'H' + x;
        });
    });
};

},{"../../lib":694,"d3":149}],1002:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function selectPoints(searchInfo, selectionTester) {
    var cd = searchInfo.cd;
    var xa = searchInfo.xaxis;
    var ya = searchInfo.yaxis;
    var selection = [];
    var i;
    // for (potentially grouped) candlesticks
    var posOffset = cd[0].t.bPos || 0;

    if(selectionTester === false) {
        // clear selection
        for(i = 0; i < cd.length; i++) {
            cd[i].selected = 0;
        }
    } else {
        for(i = 0; i < cd.length; i++) {
            var di = cd[i];

            if(selectionTester.contains([xa.c2p(di.pos + posOffset), ya.c2p(di.yc)], null, di.i, searchInfo)) {
                selection.push({
                    pointNumber: di.i,
                    x: xa.c2d(di.pos),
                    y: ya.c2d(di.yc)
                });
                di.selected = 1;
            } else {
                di.selected = 0;
            }
        }
    }

    return selection;
};

},{}],1003:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var Drawing = _dereq_('../../components/drawing');
var Color = _dereq_('../../components/color');

module.exports = function style(gd, cd) {
    var s = cd ? cd[0].node3 : d3.select(gd).selectAll('g.ohlclayer').selectAll('g.trace');

    s.style('opacity', function(d) {
        return d[0].trace.opacity;
    });

    s.each(function(d) {
        var trace = d[0].trace;

        d3.select(this).selectAll('path').each(function(di) {
            if(di.empty) return;

            var dirLine = trace[di.dir].line;
            d3.select(this)
                .style('fill', 'none')
                .call(Color.stroke, dirLine.color)
                .call(Drawing.dashLine, dirLine.dash, dirLine.width)
                // TODO: custom selection style for OHLC
                .style('opacity', trace.selectedpoints && !di.selected ? 0.3 : 1);
        });
    });
};

},{"../../components/color":571,"../../components/drawing":592,"d3":149}],1004:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var extendFlat = _dereq_('../../lib/extend').extendFlat;
var plotAttrs = _dereq_('../../plots/attributes');
var fontAttrs = _dereq_('../../plots/font_attributes');
var colorAttributes = _dereq_('../../components/colorscale/attributes');
var domainAttrs = _dereq_('../../plots/domain').attributes;
var scatterAttrs = _dereq_('../scatter/attributes');
var scatterLineAttrs = scatterAttrs.line;
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');

var line = extendFlat({
    editType: 'calc'
}, colorAttributes('line', {editType: 'calc'}),
    {
        showscale: scatterLineAttrs.showscale,
        colorbar: colorbarAttrs,
        shape: {
            valType: 'enumerated',
            values: ['linear', 'hspline'],
            dflt: 'linear',
            
            editType: 'plot',
            
        }
    });

module.exports = {
    domain: domainAttrs({name: 'parcats', trace: true, editType: 'calc'}),
    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
        flags: ['count', 'probability'],
        editType: 'plot',
        arrayOk: false
        // plotAttrs.hoverinfo description is appropriate
    }),
    hoveron: {
        valType: 'enumerated',
        values: ['category', 'color', 'dimension'],
        dflt: 'category',
        
        editType: 'plot',
        
    },
    arrangement: {
        valType: 'enumerated',
        values: ['perpendicular', 'freeform', 'fixed'],
        dflt: 'perpendicular',
        
        editType: 'plot',
        
    },
    bundlecolors: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'plot',
        
    },
    sortpaths: {
        valType: 'enumerated',
        values: ['forward', 'backward'],
        dflt: 'forward',
        
        editType: 'plot',
        
    },
    labelfont: fontAttrs({
        editType: 'calc',
        
    }),

    tickfont: fontAttrs({
        editType: 'calc',
        
    }),

    dimensions: {
        _isLinkedToArray: 'dimension',
        label: {
            valType: 'string',
            
            editType: 'calc',
            
        },
        categoryorder: {
            valType: 'enumerated',
            values: [
                'trace', 'category ascending', 'category descending', 'array'
            ],
            dflt: 'trace',
            
            editType: 'calc',
            
        },
        categoryarray: {
            valType: 'data_array',
            
            editType: 'calc',
            
        },
        ticktext: {
            valType: 'data_array',
            
            editType: 'calc',
            
        },
        values: {
            valType: 'data_array',
            
            dflt: [],
            editType: 'calc',
            
        },
        displayindex: {
            valType: 'integer',
            
            editType: 'calc',
            
        },
        editType: 'calc',
        
        visible: {
            valType: 'boolean',
            dflt: true,
            
            editType: 'calc',
            
        }
    },

    line: line,
    counts: {
        valType: 'number',
        min: 0,
        dflt: 1,
        arrayOk: true,
        
        editType: 'calc',
        
    },

    // Hide unsupported top-level properties from plot-schema
    customdata: undefined,
    hoverlabel: undefined,
    ids: undefined,
    legendgroup: undefined,
    opacity: undefined,
    selectedpoints: undefined,
    showlegend: undefined
};

},{"../../components/colorbar/attributes":572,"../../components/colorscale/attributes":578,"../../lib/extend":684,"../../plots/attributes":739,"../../plots/domain":768,"../../plots/font_attributes":769,"../scatter/attributes":1047}],1005:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var getModuleCalcData = _dereq_('../../plots/get_data').getModuleCalcData;
var parcatsPlot = _dereq_('./plot');

var PARCATS = 'parcats';
exports.name = PARCATS;

exports.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) {

    var cdModuleAndOthers = getModuleCalcData(gd.calcdata, PARCATS);

    if(cdModuleAndOthers.length) {
        var calcData = cdModuleAndOthers[0];
        parcatsPlot(gd, calcData, transitionOpts, makeOnCompleteCallback);
    }
};

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var hadTable = (oldFullLayout._has && oldFullLayout._has('parcats'));
    var hasTable = (newFullLayout._has && newFullLayout._has('parcats'));

    if(hadTable && !hasTable) {
        oldFullLayout._paperdiv.selectAll('.parcats').remove();
    }
};

},{"../../plots/get_data":779,"./plot":1010}],1006:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// Requirements
// ============
var wrap = _dereq_('../../lib/gup').wrap;
var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
var colorscaleCalc = _dereq_('../../components/colorscale/calc');
var filterUnique = _dereq_('../../lib/filter_unique.js');
var Drawing = _dereq_('../../components/drawing');
var Lib = _dereq_('../../lib');

/**
 * Create a wrapped ParcatsModel object from trace
 *
 * Note: trace defaults have already been applied
 * @param {Object} gd
 * @param {Object} trace
 * @return {Array.<ParcatsModel>}
 */
module.exports = function calc(gd, trace) {
    var visibleDims = Lib.filterVisible(trace.dimensions);

    if(visibleDims.length === 0) return [];

    var uniqueInfoDims = visibleDims.map(function(dim) {
        var categoryValues;
        if(dim.categoryorder === 'trace') {
            // Use order of first occurrence in trace
            categoryValues = null;
        } else if(dim.categoryorder === 'array') {
            // Use categories specified in `categoryarray` first,
            // then add extra to the end in trace order
            categoryValues = dim.categoryarray;
        } else {
            // Get all categories up front so we can order them
            // Should we check for numbers as sort numerically?
            categoryValues = filterUnique(dim.values).sort();
            if(dim.categoryorder === 'category descending') {
                categoryValues = categoryValues.reverse();
            }
        }
        return getUniqueInfo(dim.values, categoryValues);
    });

    var counts,
        count,
        totalCount;
    if(Lib.isArrayOrTypedArray(trace.counts)) {
        counts = trace.counts;
    } else {
        counts = [trace.counts];
    }

    validateDimensionDisplayInds(visibleDims);

    visibleDims.forEach(function(dim, dimInd) {
        validateCategoryProperties(dim, uniqueInfoDims[dimInd]);
    });

    // Handle path colors
    // ------------------
    var line = trace.line;
    var markerColorscale;

    // Process colorscale
    if(line) {
        if(hasColorscale(trace, 'line')) {
            colorscaleCalc(gd, trace, {
                vals: trace.line.color,
                containerStr: 'line',
                cLetter: 'c'
            });
        }
        markerColorscale = Drawing.tryColorscale(line);
    } else {
        markerColorscale = Lib.identity;
    }

    // Build color generation function
    function getMarkerColorInfo(index) {
        var value;
        if(Lib.isArrayOrTypedArray(line.color)) {
            value = line.color[index % line.color.length];
        } else {
            value = line.color;
        }

        return {color: markerColorscale(value), rawColor: value};
    }

    // Number of values and counts
    // ---------------------------
    var numValues = visibleDims[0].values.length;

    // Build path info
    // ---------------
    // Mapping from category inds to PathModel objects
    var pathModels = {};

    // Category inds array for each dimension
    var categoryIndsDims = uniqueInfoDims.map(function(di) {return di.inds;});

    // Initialize total count
    totalCount = 0;
    var valueInd;
    var d;

    for(valueInd = 0; valueInd < numValues; valueInd++) {

        // Category inds for this input value across dimensions
        var categoryIndsPath = [];
        for(d = 0; d < categoryIndsDims.length; d++) {
            categoryIndsPath.push(categoryIndsDims[d][valueInd]);
        }

        // Count
        count = counts[valueInd % counts.length];

        // Update total count
        totalCount += count;

        // Path color
        var pathColorInfo = getMarkerColorInfo(valueInd);

        // path key
        var pathKey = categoryIndsPath + '-' + pathColorInfo.rawColor;

        // Create / Update PathModel
        if(pathModels[pathKey] === undefined) {
            pathModels[pathKey] = createPathModel(categoryIndsPath,
                pathColorInfo.color,
                pathColorInfo.rawColor);
        }
        updatePathModel(pathModels[pathKey], valueInd, count);
    }

    var dimensionModels = visibleDims.map(function(di, i) {
        return createDimensionModel(i, di._index, di._displayindex, di.label, totalCount);
    });


    for(valueInd = 0; valueInd < numValues; valueInd++) {

        count = counts[valueInd % counts.length];

        for(d = 0; d < dimensionModels.length; d++) {
            var containerInd = dimensionModels[d].containerInd;
            var catInd = uniqueInfoDims[d].inds[valueInd];
            var cats = dimensionModels[d].categories;

            if(cats[catInd] === undefined) {
                var catValue = trace.dimensions[containerInd]._categoryarray[catInd];
                var catLabel = trace.dimensions[containerInd]._ticktext[catInd];
                cats[catInd] = createCategoryModel(d, catInd, catValue, catLabel);
            }

            updateCategoryModel(cats[catInd], valueInd, count);
        }
    }

    // Compute unique
    return wrap(createParcatsModel(dimensionModels, pathModels, totalCount));
};

// Models
// ======

// Parcats Model
// -------------
/**
 * @typedef {Object} ParcatsModel
 *  Object containing calculated information about a parcats trace
 *
 * @property {Array.<DimensionModel>} dimensions
 *  Array of dimension models
 * @property {Object.<string,PathModel>} paths
 *  Dictionary from category inds string (e.g. "1,2,1,1") to path model
 * @property {Number} maxCats
 *  The maximum number of categories of any dimension in the diagram
 * @property {Number} count
 *  Total number of input values
 * @property {Object} trace
 */

/**
 * Create and new ParcatsModel object
 * @param {Array.<DimensionModel>} dimensions
 * @param {Object.<string,PathModel>} paths
 * @param {Number} count
 * @return {ParcatsModel}
 */
function createParcatsModel(dimensions, paths, count) {
    var maxCats = dimensions
        .map(function(d) {return d.categories.length;})
        .reduce(function(v1, v2) {return Math.max(v1, v2);});
    return {dimensions: dimensions, paths: paths, trace: undefined, maxCats: maxCats, count: count};
}

// Dimension Model
// ---------------
/**
 * @typedef {Object} DimensionModel
 *  Object containing calculated information about a single dimension
 *
 * @property {Number} dimensionInd
 *  The index of this dimension among the *visible* dimensions
 * @property {Number} containerInd
 *  The index of this dimension in the original dimensions container,
 *  irrespective of dimension visibility
 * @property {Number} displayInd
 *  The display index of this dimension (where 0 is the left most dimension)
 * @property {String} dimensionLabel
 *  The label of this dimension
 * @property {Number} count
 *  Total number of input values
 * @property {Array.<CategoryModel>} categories
 * @property {Number|null} dragX
 *  The x position of dimension that is currently being dragged. null if not being dragged
 */

/**
 * Create and new DimensionModel object with an empty categories array
 * @param {Number} dimensionInd
 * @param {Number} containerInd
 * @param {Number} displayInd
 * @param {String} dimensionLabel
 * @param {Number} count
 *  Total number of input values
 * @return {DimensionModel}
 */
function createDimensionModel(dimensionInd, containerInd, displayInd, dimensionLabel, count) {
    return {
        dimensionInd: dimensionInd,
        containerInd: containerInd,
        displayInd: displayInd,
        dimensionLabel: dimensionLabel,
        count: count,
        categories: [],
        dragX: null
    };
}

// Category Model
// --------------
/**
 * @typedef {Object} CategoryModel
 *  Object containing calculated information about a single category.
 *
 * @property {Number} dimensionInd
 *  The index of this categories dimension
 * @property {Number} categoryInd
 *  The index of this category
 * @property {Number} displayInd
 *  The display index of this category (where 0 is the topmost category)
 * @property {String} categoryLabel
 *  The name of this category
 * @property categoryValue: Raw value of the category
 * @property {Array} valueInds
 *  Array of indices (into the original value array) of all samples in this category
 * @property {Number} count
 *  The number of elements from the original array in this path
 * @property {Number|null} dragY
 *  The y position of category that is currently being dragged. null if not being dragged
 */

/**
 * Create and return a new CategoryModel object
 * @param {Number} dimensionInd
 * @param {Number} categoryInd
 *  The display index of this category (where 0 is the topmost category)
 * @param {String} categoryValue
 * @param {String} categoryLabel
 * @return {CategoryModel}
 */
function createCategoryModel(dimensionInd, categoryInd, categoryValue, categoryLabel) {
    return {
        dimensionInd: dimensionInd,
        categoryInd: categoryInd,
        categoryValue: categoryValue,
        displayInd: categoryInd,
        categoryLabel: categoryLabel,
        valueInds: [],
        count: 0,
        dragY: null
    };
}

/**
 * Update a CategoryModel object with a new value index
 * Note: The calling parameter is modified in place.
 *
 * @param {CategoryModel} categoryModel
 * @param {Number} valueInd
 * @param {Number} count
 */
function updateCategoryModel(categoryModel, valueInd, count) {
    categoryModel.valueInds.push(valueInd);
    categoryModel.count += count;
}


// Path Model
// ----------
/**
 * @typedef {Object} PathModel
 *  Object containing calculated information about the samples in a path.
 *
 * @property {Array} categoryInds
 *  Array of category indices for each dimension (length `numDimensions`)
 * @param {String} pathColor
 *  Color of this path. (Note: Any colorscaling has already taken place)
 * @property {Array} valueInds
 *  Array of indices (into the original value array) of all samples in this path
 * @property {Number} count
 *  The number of elements from the original array in this path
 * @property {String} color
 *  The path's color (ass CSS color string)
 * @property rawColor
 *  The raw color value specified by the user. May be a CSS color string or a Number
 */

/**
 * Create and return a new PathModel object
 * @param {Array} categoryInds
 * @param color
 * @param rawColor
 * @return {PathModel}
 */
function createPathModel(categoryInds, color, rawColor) {
    return {
        categoryInds: categoryInds,
        color: color,
        rawColor: rawColor,
        valueInds: [],
        count: 0
    };
}

/**
 * Update a PathModel object with a new value index
 * Note: The calling parameter is modified in place.
 *
 * @param {PathModel} pathModel
 * @param {Number} valueInd
 * @param {Number} count
 */
function updatePathModel(pathModel, valueInd, count) {
    pathModel.valueInds.push(valueInd);
    pathModel.count += count;
}

// Unique calculations
// ===================
/**
 * @typedef {Object} UniqueInfo
 *  Object containing information about the unique values of an input array
 *
 * @property {Array} uniqueValues
 *  The unique values in the input array
 * @property {Array} uniqueCounts
 *  The number of times each entry in uniqueValues occurs in input array.
 *  This has the same length as `uniqueValues`
 * @property {Array} inds
 *  Indices into uniqueValues that would reproduce original input array
 */

/**
 * Compute unique value information for an array
 *
 * IMPORTANT: Note that values are considered unique
 * if their string representations are unique.
 *
 * @param {Array} values
 * @param {Array|undefined} uniqueValues
 *  Array of expected unique values. The uniqueValues property of the resulting UniqueInfo object will begin with
 *  these entries. Entries are included even if there are zero occurrences in the values array. Entries found in
 *  the values array that are not present in uniqueValues will be included at the end of the array in the
 *  UniqueInfo object.
 * @return {UniqueInfo}
 */
function getUniqueInfo(values, uniqueValues) {

    // Initialize uniqueValues if not specified
    if(uniqueValues === undefined || uniqueValues === null) {
        uniqueValues = [];
    } else {
        // Shallow copy so append below doesn't alter input array
        uniqueValues = uniqueValues.map(function(e) {return e;});
    }

    // Initialize Variables
    var uniqueValueCounts = {};
    var uniqueValueInds = {};
    var inds = [];

    // Initialize uniqueValueCounts and
    uniqueValues.forEach(function(uniqueVal, valInd) {
        uniqueValueCounts[uniqueVal] = 0;
        uniqueValueInds[uniqueVal] = valInd;
    });

    // Compute the necessary unique info in a single pass
    for(var i = 0; i < values.length; i++) {
        var item = values[i];
        var itemInd;

        if(uniqueValueCounts[item] === undefined) {
            // This item has a previously unseen value
            uniqueValueCounts[item] = 1;
            itemInd = uniqueValues.push(item) - 1;
            uniqueValueInds[item] = itemInd;
        } else {
            // Increment count for this item
            uniqueValueCounts[item]++;
            itemInd = uniqueValueInds[item];
        }
        inds.push(itemInd);
    }

    // Build UniqueInfo
    var uniqueCounts = uniqueValues.map(function(v) { return uniqueValueCounts[v]; });

    return {
        uniqueValues: uniqueValues,
        uniqueCounts: uniqueCounts,
        inds: inds
    };
}


/**
 * Validate the requested display order for the dimensions.
 * If the display order is a permutation of 0 through dimensions.length - 1, link to _displayindex
 * Otherwise, replace the display order with the dimension order
 * @param {Object} trace
 */
function validateDimensionDisplayInds(visibleDims) {
    var displayInds = visibleDims.map(function(d) { return d.displayindex; });
    var i;

    if(isRangePermutation(displayInds)) {
        for(i = 0; i < visibleDims.length; i++) {
            visibleDims[i]._displayindex = visibleDims[i].displayindex;
        }
    } else {
        for(i = 0; i < visibleDims.length; i++) {
            visibleDims[i]._displayindex = i;
        }
    }
}


/**
 * Update category properties based on the unique values found for this dimension
 * @param {Object} dim
 * @param {UniqueInfo} uniqueInfoDim
 */
function validateCategoryProperties(dim, uniqueInfoDim) {

    // Update categoryarray
    dim._categoryarray = uniqueInfoDim.uniqueValues;

    // Handle ticktext
    if(dim.ticktext === null || dim.ticktext === undefined) {
        dim._ticktext = [];
    } else {
        // Shallow copy to avoid modifying input array
        dim._ticktext = dim.ticktext.slice();
    }

    // Extend ticktext with elements from uniqueInfoDim.uniqueValues
    for(var i = dim._ticktext.length; i < uniqueInfoDim.uniqueValues.length; i++) {
        dim._ticktext.push(uniqueInfoDim.uniqueValues[i]);
    }
}

/**
 * Determine whether an array contains a permutation of the integers from 0 to the array's length - 1
 * @param {Array} inds
 * @return {boolean}
 */
function isRangePermutation(inds) {
    var indsSpecified = new Array(inds.length);

    for(var i = 0; i < inds.length; i++) {
        // Check for out of bounds
        if(inds[i] < 0 || inds[i] >= inds.length) {
            return false;
        }

        // Check for collisions with already specified index
        if(indsSpecified[inds[i]] !== undefined) {
            return false;
        }

        indsSpecified[inds[i]] = true;
    }

    // Nothing out of bounds and no collisions. We have a permutation
    return true;
}

},{"../../components/colorscale/calc":579,"../../components/colorscale/helpers":582,"../../components/drawing":592,"../../lib":694,"../../lib/filter_unique.js":685,"../../lib/gup":692}],1007:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
var handleDomainDefaults = _dereq_('../../plots/domain').defaults;
var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');

var attributes = _dereq_('./attributes');
var mergeLength = _dereq_('../parcoords/merge_length');

function handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce) {

    coerce('line.shape');
    var lineColor = coerce('line.color', layout.colorway[0]);
    if(hasColorscale(traceIn, 'line') && Lib.isArrayOrTypedArray(lineColor)) {
        if(lineColor.length) {
            coerce('line.colorscale');
            colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'});
            return lineColor.length;
        }
        else {
            traceOut.line.color = defaultColor;
        }
    }
    return Infinity;
}

function dimensionDefaults(dimensionIn, dimensionOut) {
    function coerce(attr, dflt) {
        return Lib.coerce(dimensionIn, dimensionOut, attributes.dimensions, attr, dflt);
    }

    var values = coerce('values');
    var visible = coerce('visible');
    if(!(values && values.length)) {
        visible = dimensionOut.visible = false;
    }

    if(visible) {
        // Dimension level
        coerce('label');
        coerce('displayindex', dimensionOut._index);

        // Category level
        var arrayIn = dimensionIn.categoryarray;
        var isValidArray = (Array.isArray(arrayIn) && arrayIn.length > 0);

        var orderDefault;
        if(isValidArray) orderDefault = 'array';
        var order = coerce('categoryorder', orderDefault);

        // coerce 'categoryarray' only in array order case
        if(order === 'array') {
            coerce('categoryarray');
            coerce('ticktext');
        } else {
            delete dimensionIn.categoryarray;
            delete dimensionIn.ticktext;
        }

        // cannot set 'categoryorder' to 'array' with an invalid 'categoryarray'
        if(!isValidArray && order === 'array') {
            dimensionOut.categoryorder = 'trace';
        }
    }
}

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {

    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var dimensions = handleArrayContainerDefaults(traceIn, traceOut, {
        name: 'dimensions',
        handleItemDefaults: dimensionDefaults
    });

    var len = handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);

    handleDomainDefaults(traceOut, layout, coerce);

    if(!Array.isArray(dimensions) || !dimensions.length) {
        traceOut.visible = false;
    }

    mergeLength(traceOut, dimensions, 'values', len);

    coerce('hoveron');
    coerce('arrangement');
    coerce('bundlecolors');
    coerce('sortpaths');
    coerce('counts');

    var labelfontDflt = {
        family: layout.font.family,
        size: Math.round(layout.font.size),
        color: layout.font.color
    };

    Lib.coerceFont(coerce, 'labelfont', labelfontDflt);

    var categoryfontDefault = {
        family: layout.font.family,
        size: Math.round(layout.font.size / 1.2),
        color: layout.font.color
    };

    Lib.coerceFont(coerce, 'tickfont', categoryfontDefault);
};

},{"../../components/colorscale/defaults":581,"../../components/colorscale/helpers":582,"../../lib":694,"../../plots/array_container_defaults":738,"../../plots/domain":768,"../parcoords/merge_length":1019,"./attributes":1004}],1008:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Parcats = {};

Parcats.attributes = _dereq_('./attributes');
Parcats.supplyDefaults = _dereq_('./defaults');
Parcats.calc = _dereq_('./calc');
Parcats.plot = _dereq_('./plot');
Parcats.colorbar = {
    container: 'line',
    min: 'cmin',
    max: 'cmax'
};

Parcats.moduleType = 'trace';
Parcats.name = 'parcats';
Parcats.basePlotModule = _dereq_('./base_plot');
Parcats.categories = ['noOpacity'];
Parcats.meta = {
    
};

module.exports = Parcats;

},{"./attributes":1004,"./base_plot":1005,"./calc":1006,"./defaults":1007,"./plot":1010}],1009:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var Plotly = _dereq_('../../plot_api/plot_api');
var Fx = _dereq_('../../components/fx');
var Lib = _dereq_('../../lib');
var Drawing = _dereq_('../../components/drawing');
var tinycolor = _dereq_('tinycolor2');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');

function performPlot(parcatsModels, graphDiv, layout, svg) {

    var viewModels = parcatsModels.map(createParcatsViewModel.bind(0, graphDiv, layout));

    // Get (potentially empty) parcatslayer selection with bound data to single element array
    var layerSelection = svg.selectAll('g.parcatslayer').data([null]);

    // Initialize single parcatslayer group if it doesn't exist
    layerSelection.enter()
        .append('g')
        .attr('class', 'parcatslayer')
        .style('pointer-events', 'all');

    // Bind data to children of layerSelection and get reference to traceSelection
    var traceSelection = layerSelection
        .selectAll('g.trace.parcats')
        .data(viewModels, key);

    // Initialize group for each trace/dimensions
    var traceEnter = traceSelection.enter()
        .append('g')
        .attr('class', 'trace parcats');

    // Update properties for each trace
    traceSelection
        .attr('transform', function(d) {
            return 'translate(' + d.x + ', ' + d.y + ')';
        });

    // Initialize paths group
    traceEnter
        .append('g')
        .attr('class', 'paths');

    // Update paths transform
    var pathsSelection = traceSelection
        .select('g.paths');

    // Get paths selection
    var pathSelection = pathsSelection
        .selectAll('path.path')
        .data(function(d) {
            return d.paths;
        }, key);

    // Update existing path colors
    pathSelection
        .attr('fill', function(d) {
            return d.model.color;
        });

    // Create paths
    var pathSelectionEnter = pathSelection
        .enter()
        .append('path')
        .attr('class', 'path')
        .attr('stroke-opacity', 0)
        .attr('fill', function(d) {
            return d.model.color;
        })
        .attr('fill-opacity', 0);

    stylePathsNoHover(pathSelectionEnter);

    // Set path geometry
    pathSelection
        .attr('d', function(d) {
            return d.svgD;
        });

    // sort paths
    if(!pathSelectionEnter.empty()) {
        // Only sort paths if there has been a change.
        // Otherwise paths are already sorted or a hover operation may be in progress
        pathSelection.sort(compareRawColor);
    }

    // Remove any old paths
    pathSelection.exit().remove();

    // Path hover
    pathSelection
        .on('mouseover', mouseoverPath)
        .on('mouseout', mouseoutPath)
        .on('click', clickPath);

    // Initialize dimensions group
    traceEnter.append('g').attr('class', 'dimensions');

    // Update dimensions transform
    var dimensionsSelection = traceSelection
        .select('g.dimensions');

    // Get dimension selection
    var dimensionSelection = dimensionsSelection
        .selectAll('g.dimension')
        .data(function(d) {
            return d.dimensions;
        }, key);

    // Create dimension groups
    dimensionSelection.enter()
        .append('g')
        .attr('class', 'dimension');

    // Update dimension group transforms
    dimensionSelection.attr('transform', function(d) {
        return 'translate(' + d.x + ', 0)';
    });

    // Remove any old dimensions
    dimensionSelection.exit().remove();

    // Get category selection
    var categorySelection = dimensionSelection
        .selectAll('g.category')
        .data(function(d) {
            return d.categories;
        }, key);

    // Initialize category groups
    var categoryGroupEnterSelection = categorySelection
        .enter()
        .append('g')
        .attr('class', 'category');

    // Update category transforms
    categorySelection
        .attr('transform', function(d) {
            return 'translate(0, ' + d.y + ')';
        });


    // Initialize rectangle
    categoryGroupEnterSelection
        .append('rect')
        .attr('class', 'catrect')
        .attr('pointer-events', 'none');


    // Update rectangle
    categorySelection.select('rect.catrect')
        .attr('fill', 'none')
        .attr('width', function(d) {
            return d.width;
        })
        .attr('height', function(d) {
            return d.height;
        });

    styleCategoriesNoHover(categoryGroupEnterSelection);

    // Initialize color band rects
    var bandSelection = categorySelection
        .selectAll('rect.bandrect')
        .data(
            /** @param {CategoryViewModel} catViewModel*/
            function(catViewModel) {
                return catViewModel.bands;
            }, key);

    // Raise all update bands to the top so that fading enter/exit bands will be behind
    bandSelection.each(function() {Lib.raiseToTop(this);});

    // Update band color
    bandSelection
        .attr('fill', function(d) {
            return d.color;
        });

    var bandsSelectionEnter = bandSelection.enter()
        .append('rect')
        .attr('class', 'bandrect')
        .attr('stroke-opacity', 0)
        .attr('fill', function(d) {
            return d.color;
        })
        .attr('fill-opacity', 0);

    bandSelection
        .attr('fill', function(d) {
            return d.color;
        })
        .attr('width', function(d) {
            return d.width;
        })
        .attr('height', function(d) {
            return d.height;
        })
        .attr('y', function(d) {
            return d.y;
        })
        .attr('cursor',
            /** @param {CategoryBandViewModel} bandModel*/
            function(bandModel) {
                if(bandModel.parcatsViewModel.arrangement === 'fixed') {
                    return 'default';
                } else if(bandModel.parcatsViewModel.arrangement === 'perpendicular') {
                    return 'ns-resize';
                } else {
                    return 'move';
                }
            });

    styleBandsNoHover(bandsSelectionEnter);

    bandSelection.exit().remove();

    // Initialize category label
    categoryGroupEnterSelection
        .append('text')
        .attr('class', 'catlabel')
        .attr('pointer-events', 'none');

    var paperColor = graphDiv._fullLayout.paper_bgcolor;

    // Update category label
    categorySelection.select('text.catlabel')
        .attr('text-anchor',
            function(d) {
                if(catInRightDim(d)) {
                    // Place label to the right of category
                    return 'start';
                } else {
                    // Place label to the left of category
                    return 'end';
                }
            })
        .attr('alignment-baseline', 'middle')

        .style('text-shadow',
            paperColor + ' -1px  1px 2px, ' +
            paperColor + ' 1px  1px 2px, ' +
            paperColor + '  1px -1px 2px, ' +
            paperColor + ' -1px -1px 2px')
        .style('fill', 'rgb(0, 0, 0)')
        .attr('x',
            function(d) {
                if(catInRightDim(d)) {
                    // Place label to the right of category
                    return d.width + 5;
                } else {
                    // Place label to the left of category
                    return -5;
                }
            })
        .attr('y', function(d) {
            return d.height / 2;
        })
        .text(function(d) {
            return d.model.categoryLabel;
        })
        .each(
            /** @param {CategoryViewModel} catModel*/
            function(catModel) {
                Drawing.font(d3.select(this), catModel.parcatsViewModel.categorylabelfont);
                svgTextUtils.convertToTspans(d3.select(this), graphDiv);
            });

    // Initialize dimension label
    categoryGroupEnterSelection
        .append('text')
        .attr('class', 'dimlabel');

    // Update dimension label
    categorySelection.select('text.dimlabel')
        .attr('text-anchor', 'middle')
        .attr('alignment-baseline', 'baseline')
        .attr('cursor',
             /** @param {CategoryViewModel} catModel*/
            function(catModel) {
                if(catModel.parcatsViewModel.arrangement === 'fixed') {
                    return 'default';
                } else {
                    return 'ew-resize';
                }
            })
        .attr('x', function(d) {
            return d.width / 2;
        })
        .attr('y', -5)
        .text(function(d, i) {
            if(i === 0) {
                // Add dimension label above topmost category
                return d.parcatsViewModel.model.dimensions[d.model.dimensionInd].dimensionLabel;
            } else {
                return null;
            }
        })
        .each(
            /** @param {CategoryViewModel} catModel*/
            function(catModel) {
                Drawing.font(d3.select(this), catModel.parcatsViewModel.labelfont);
            });

    // Category hover
    // categorySelection.select('rect.catrect')
    categorySelection.selectAll('rect.bandrect')
        .on('mouseover', mouseoverCategoryBand)
        .on('mouseout', mouseoutCategory);

    // Remove unused categories
    categorySelection.exit().remove();

    // Setup drag
    dimensionSelection.call(d3.behavior.drag()
        .origin(function(d) {
            return {x: d.x, y: 0};
        })
        .on('dragstart', dragDimensionStart)
        .on('drag', dragDimension)
        .on('dragend', dragDimensionEnd));


    // Save off selections to view models
    traceSelection.each(function(d) {
        d.traceSelection = d3.select(this);
        d.pathSelection = d3.select(this).selectAll('g.paths').selectAll('path.path');
        d.dimensionSelection = d3.select(this).selectAll('g.dimensions').selectAll('g.dimension');
    });

    // Remove any orphan traces
    traceSelection.exit().remove();
}

/**
 * Create / update parcat traces
 *
 * @param {Object} graphDiv
 * @param {Object} svg
 * @param {Array.<ParcatsModel>} parcatsModels
 * @param {Layout} layout
 */
module.exports = function(graphDiv, svg, parcatsModels, layout) {
    performPlot(parcatsModels, graphDiv, layout, svg);
};

/**
 * Function the returns the key property of an object for use with as D3 join function
 * @param d
 */
function key(d) {
    return d.key;
}

 /** True if a category view model is in the right-most display dimension
  * @param {CategoryViewModel} d */
function catInRightDim(d) {
    var numDims = d.parcatsViewModel.dimensions.length;
    var leftDimInd = d.parcatsViewModel.dimensions[numDims - 1].model.dimensionInd;
    return d.model.dimensionInd === leftDimInd;
}

/**
 * @param {PathViewModel} a
 * @param {PathViewModel} b
 */
function compareRawColor(a, b) {
    if(a.model.rawColor > b.model.rawColor) {
        return 1;
    } else if(a.model.rawColor < b.model.rawColor) {
        return -1;
    } else {
        return 0;
    }
}

/**
 * Handle path mouseover
 * @param {PathViewModel} d
 */
function mouseoverPath(d) {

    if(!d.parcatsViewModel.dragDimension) {
        // We're not currently dragging

        if(d.parcatsViewModel.hoverinfoItems.indexOf('skip') === -1) {
            // hoverinfo is not skip, so we at least style the paths and emit interaction events

            // Raise path to top
            Lib.raiseToTop(this);

            stylePathsHover(d3.select(this));

            // Emit hover event
            var points = buildPointsArrayForPath(d);
            d.parcatsViewModel.graphDiv.emit('plotly_hover', {points: points, event: d3.event});

            // Handle hover label
            if(d.parcatsViewModel.hoverinfoItems.indexOf('none') === -1) {
                // hoverinfo is a combination of 'count' and 'probability'

                // Mouse
                var hoverX = d3.mouse(this)[0];

                // Label
                var gd = d.parcatsViewModel.graphDiv;
                var fullLayout = gd._fullLayout;
                var rootBBox = fullLayout._paperdiv.node().getBoundingClientRect();
                var graphDivBBox = d.parcatsViewModel.graphDiv.getBoundingClientRect();

                // Find path center in path coordinates
                var pathCenterX,
                    pathCenterY,
                    dimInd;

                for(dimInd = 0; dimInd < (d.leftXs.length - 1); dimInd++) {
                    if(d.leftXs[dimInd] + d.dimWidths[dimInd] - 2 <= hoverX && hoverX <= d.leftXs[dimInd + 1] + 2) {
                        var leftDim = d.parcatsViewModel.dimensions[dimInd];
                        var rightDim = d.parcatsViewModel.dimensions[dimInd + 1];
                        pathCenterX = (leftDim.x + leftDim.width + rightDim.x) / 2;
                        pathCenterY = (d.topYs[dimInd] + d.topYs[dimInd + 1] + d.height) / 2;
                        break;
                    }
                }

                // Find path center in root coordinates
                var hoverCenterX = d.parcatsViewModel.x + pathCenterX;
                var hoverCenterY = d.parcatsViewModel.y + pathCenterY;

                var textColor = tinycolor.mostReadable(d.model.color, ['black', 'white']);

                // Build hover text
                var hovertextParts = [];
                if(d.parcatsViewModel.hoverinfoItems.indexOf('count') !== -1) {
                    hovertextParts.push(['Count:', d.model.count].join(' '));
                }
                if(d.parcatsViewModel.hoverinfoItems.indexOf('probability') !== -1) {
                    hovertextParts.push(['P:', (d.model.count / d.parcatsViewModel.model.count).toFixed(3)].join(' '));
                }

                var hovertext = hovertextParts.join('<br>');
                var mouseX = d3.mouse(gd)[0];

                Fx.loneHover({
                    x: hoverCenterX - rootBBox.left + graphDivBBox.left,
                    y: hoverCenterY - rootBBox.top + graphDivBBox.top,
                    text: hovertext,
                    color: d.model.color,
                    borderColor: 'black',
                    fontFamily: 'Monaco, "Courier New", monospace',
                    fontSize: 10,
                    fontColor: textColor,
                    idealAlign: mouseX < hoverCenterX ? 'right' : 'left'
                }, {
                    container: fullLayout._hoverlayer.node(),
                    outerContainer: fullLayout._paper.node(),
                    gd: gd
                });
            }
        }
    }
}

/**
 * Handle path mouseout
 * @param {PathViewModel} d
 */
function mouseoutPath(d) {
    if(!d.parcatsViewModel.dragDimension) {
        // We're not currently dragging
        stylePathsNoHover(d3.select(this));

        // Remove and hover label
        Fx.loneUnhover(d.parcatsViewModel.graphDiv._fullLayout._hoverlayer.node());

        // Restore path order
        d.parcatsViewModel.pathSelection.sort(compareRawColor);

        // Emit unhover event
        if(d.parcatsViewModel.hoverinfoItems.indexOf('skip') === -1) {
            var points = buildPointsArrayForPath(d);
            d.parcatsViewModel.graphDiv.emit('plotly_unhover', {points: points, event: d3.event});
        }
    }
}

/**
 * Build array of point objects for a path
 *
 * For use in click/hover events
 * @param {PathViewModel} d
 */
function buildPointsArrayForPath(d) {
    var points = [];
    var curveNumber = getTraceIndex(d.parcatsViewModel);

    for(var i = 0; i < d.model.valueInds.length; i++) {
        var pointNumber = d.model.valueInds[i];
        points.push({
            curveNumber: curveNumber,
            pointNumber: pointNumber
        });
    }
    return points;
}

/**
 * Handle path click
 * @param {PathViewModel} d
 */
function clickPath(d) {
    if(d.parcatsViewModel.hoverinfoItems.indexOf('skip') === -1) {
        // hoverinfo it's skip, so interaction events aren't disabled
        var points = buildPointsArrayForPath(d);
        d.parcatsViewModel.graphDiv.emit('plotly_click', {points: points, event: d3.event});
    }
}

function stylePathsNoHover(pathSelection) {
    pathSelection
        .attr('fill', function(d) {
            return d.model.color;
        })
        .attr('fill-opacity', 0.6)
        .attr('stroke', 'lightgray')
        .attr('stroke-width', 0.2)
        .attr('stroke-opacity', 1.0);
}

function stylePathsHover(pathSelection) {
    pathSelection
        .attr('fill-opacity', 0.8)
        .attr('stroke', function(d) {
            return tinycolor.mostReadable(d.model.color, ['black', 'white']);
        })
        .attr('stroke-width', 0.3);
}

function styleCategoryHover(categorySelection) {
    categorySelection
        .select('rect.catrect')
        .attr('stroke', 'black')
        .attr('stroke-width', 2.5);
}

function styleCategoriesNoHover(categorySelection) {
    categorySelection
        .select('rect.catrect')
        .attr('stroke', 'black')
        .attr('stroke-width', 1)
        .attr('stroke-opacity', 1);
}

function styleBandsHover(bandsSelection) {
    bandsSelection
        .attr('stroke', 'black')
        .attr('stroke-width', 1.5);
}

function styleBandsNoHover(bandsSelection) {
    bandsSelection
        .attr('stroke', 'black')
        .attr('stroke-width', 0.2)
        .attr('stroke-opacity', 1.0)
        .attr('fill-opacity', 1.0);
}

/**
 * Return selection of all paths that pass through the specified category
 * @param {CategoryBandViewModel} catBandViewModel
 */
function selectPathsThroughCategoryBandColor(catBandViewModel) {

    var allPaths = catBandViewModel.parcatsViewModel.pathSelection;
    var dimInd = catBandViewModel.categoryViewModel.model.dimensionInd;
    var catInd = catBandViewModel.categoryViewModel.model.categoryInd;

    return allPaths
        .filter(
            /** @param {PathViewModel} pathViewModel */
            function(pathViewModel) {
                return pathViewModel.model.categoryInds[dimInd] === catInd &&
                    pathViewModel.model.color === catBandViewModel.color;
            });
}


/**
 * Perform hover styling for all paths that pass though the specified band element's category
 *
 * @param {HTMLElement} bandElement
 *  HTML element for band
 *
 */
function styleForCategoryHovermode(bandElement) {

    // Get all bands in the current category
    var bandSel = d3.select(bandElement.parentNode).selectAll('rect.bandrect');

    // Raise and style paths
    bandSel.each(function(bvm) {
        var paths = selectPathsThroughCategoryBandColor(bvm);
        stylePathsHover(paths);
        paths.each(function() {
            // Raise path to top
            Lib.raiseToTop(this);
        });
    });

    // Style category
    styleCategoryHover(d3.select(bandElement.parentNode));
}

/**
 * Perform hover styling for all paths that pass though the category of the specified band element and share the
 * same color
 *
 * @param {HTMLElement} bandElement
 *  HTML element for band
 *
 */
function styleForColorHovermode(bandElement) {
    var bandViewModel = d3.select(bandElement).datum();
    var catPaths = selectPathsThroughCategoryBandColor(bandViewModel);
    stylePathsHover(catPaths);
    catPaths.each(function() {
        // Raise path to top
        Lib.raiseToTop(this);
    });

    // Style category for drag
    d3.select(bandElement.parentNode)
        .selectAll('rect.bandrect')
        .filter(function(b) {return b.color === bandViewModel.color;})
        .each(function() {
            Lib.raiseToTop(this);
            styleBandsHover(d3.select(this));
        });
}


/**
 * @param {HTMLElement} bandElement
 *  HTML element for band
 * @param eventName
 *  Event name (plotly_hover or plotly_click)
 * @param event
 *  Mouse Event
 */
function emitPointsEventCategoryHovermode(bandElement, eventName, event) {
    // Get all bands in the current category
    var bandViewModel = d3.select(bandElement).datum();
    var gd = bandViewModel.parcatsViewModel.graphDiv;
    var bandSel = d3.select(bandElement.parentNode).selectAll('rect.bandrect');

    var points = [];
    bandSel.each(function(bvm) {
        var paths = selectPathsThroughCategoryBandColor(bvm);
        paths.each(function(pathViewModel) {
            // Extend points array
            Array.prototype.push.apply(points, buildPointsArrayForPath(pathViewModel));
        });
    });

    gd.emit(eventName, {points: points, event: event});
}

/**
 * @param {HTMLElement} bandElement
 *  HTML element for band
 * @param eventName
 *  Event name (plotly_hover or plotly_click)
 * @param event
 *  Mouse Event
 */
function emitPointsEventColorHovermode(bandElement, eventName, event) {
    var bandViewModel = d3.select(bandElement).datum();
    var gd = bandViewModel.parcatsViewModel.graphDiv;
    var paths = selectPathsThroughCategoryBandColor(bandViewModel);

    var points = [];
    paths.each(function(pathViewModel) {
        // Extend points array
        Array.prototype.push.apply(points, buildPointsArrayForPath(pathViewModel));
    });

    gd.emit(eventName, {points: points, event: event});
}

/**
 * Create hover label for a band element's category (for use when hoveron === 'category')
 *
 * @param {ClientRect} rootBBox
 *  Client bounding box for root of figure
 * @param {HTMLElement} bandElement
 *  HTML element for band
 *
 */
function createHoverLabelForCategoryHovermode(rootBBox, bandElement) {
    // Selections
    var rectSelection = d3.select(bandElement.parentNode).select('rect.catrect');
    var rectBoundingBox = rectSelection.node().getBoundingClientRect();

    // Models
    /** @type {CategoryViewModel} */
    var catViewModel = rectSelection.datum();
    var parcatsViewModel = catViewModel.parcatsViewModel;
    var dimensionModel = parcatsViewModel.model.dimensions[catViewModel.model.dimensionInd];

    // Positions
    var hoverCenterY = rectBoundingBox.top + rectBoundingBox.height / 2;
    var hoverCenterX,
        hoverLabelIdealAlign;

    if(parcatsViewModel.dimensions.length > 1 &&
        dimensionModel.displayInd === parcatsViewModel.dimensions.length - 1) {

        // right most dimension
        hoverCenterX = rectBoundingBox.left;
        hoverLabelIdealAlign = 'left';
    } else {
        hoverCenterX = rectBoundingBox.left + rectBoundingBox.width;
        hoverLabelIdealAlign = 'right';
    }

    // Hover label text
    var hoverinfoParts = [];
    if(catViewModel.parcatsViewModel.hoverinfoItems.indexOf('count') !== -1) {
        hoverinfoParts.push(['Count:', catViewModel.model.count].join(' '));
    }
    if(catViewModel.parcatsViewModel.hoverinfoItems.indexOf('probability') !== -1) {
        hoverinfoParts.push([
            'P(' + catViewModel.model.categoryLabel + '):',
            (catViewModel.model.count / catViewModel.parcatsViewModel.model.count).toFixed(3)].join(' '));
    }

    var hovertext = hoverinfoParts.join('<br>');
    return {
        x: hoverCenterX - rootBBox.left,
        y: hoverCenterY - rootBBox.top,
        text: hovertext,
        color: 'lightgray',
        borderColor: 'black',
        fontFamily: 'Monaco, "Courier New", monospace',
        fontSize: 12,
        fontColor: 'black',
        idealAlign: hoverLabelIdealAlign
    };
}

/**
 * Create hover label for a band element's category (for use when hoveron === 'category')
 *
 * @param {ClientRect} rootBBox
 *  Client bounding box for root of figure
 * @param {HTMLElement} bandElement
 *  HTML element for band
 *
 */
function createHoverLabelForDimensionHovermode(rootBBox, bandElement) {

    var allHoverlabels = [];

    d3.select(bandElement.parentNode.parentNode)
        .selectAll('g.category')
        .select('rect.catrect')
        .each(function() {
            var bandNode = this;
            allHoverlabels.push(createHoverLabelForCategoryHovermode(rootBBox, bandNode));
        });

    return allHoverlabels;
}

/**
 * Create hover labels for a band element's category (for use when hoveron === 'dimension')
 *
 * @param {ClientRect} rootBBox
 *  Client bounding box for root of figure
 * @param {HTMLElement} bandElement
 *  HTML element for band
 *
 */
function createHoverLabelForColorHovermode(rootBBox, bandElement) {

    var bandBoundingBox = bandElement.getBoundingClientRect();

    // Models
    /** @type {CategoryBandViewModel} */
    var bandViewModel = d3.select(bandElement).datum();
    var catViewModel = bandViewModel.categoryViewModel;
    var parcatsViewModel = catViewModel.parcatsViewModel;
    var dimensionModel = parcatsViewModel.model.dimensions[catViewModel.model.dimensionInd];

    // positions
    var hoverCenterY = bandBoundingBox.y + bandBoundingBox.height / 2;

    var hoverCenterX,
        hoverLabelIdealAlign;
    if(parcatsViewModel.dimensions.length > 1 &&
        dimensionModel.displayInd === parcatsViewModel.dimensions.length - 1) {
        // right most dimension
        hoverCenterX = bandBoundingBox.left;
        hoverLabelIdealAlign = 'left';
    } else {
        hoverCenterX = bandBoundingBox.left + bandBoundingBox.width;
        hoverLabelIdealAlign = 'right';
    }

    // Labels
    var catLabel = catViewModel.model.categoryLabel;

    // Counts
    var totalCount = bandViewModel.parcatsViewModel.model.count;

    var bandColorCount = 0;
    bandViewModel.categoryViewModel.bands.forEach(function(b) {
        if(b.color === bandViewModel.color) {
            bandColorCount += b.count;
        }
    });

    var catCount = catViewModel.model.count;

    var colorCount = 0;
    parcatsViewModel.pathSelection.each(
        /** @param {PathViewModel} pathViewModel */
        function(pathViewModel) {
            if(pathViewModel.model.color === bandViewModel.color) {
                colorCount += pathViewModel.model.count;
            }
        });

    // Hover label text
    var hoverinfoParts = [];
    if(catViewModel.parcatsViewModel.hoverinfoItems.indexOf('count') !== -1) {
        hoverinfoParts.push(['Count:', bandColorCount].join(' '));
    }
    if(catViewModel.parcatsViewModel.hoverinfoItems.indexOf('probability') !== -1) {
        var pColorAndCatLable = 'P(color ∩ ' + catLabel + '): ';
        var pColorAndCatValue = (bandColorCount / totalCount).toFixed(3);
        var pColorAndCatRow = pColorAndCatLable + pColorAndCatValue;
        hoverinfoParts.push(pColorAndCatRow);

        var pCatGivenColorLabel = 'P(' + catLabel + ' | color): ';
        var pCatGivenColorValue = (bandColorCount / colorCount).toFixed(3);
        var pCatGivenColorRow = pCatGivenColorLabel + pCatGivenColorValue;
        hoverinfoParts.push(pCatGivenColorRow);

        var pColorGivenCatLabel = 'P(color | ' + catLabel + '): ';
        var pColorGivenCatValue = (bandColorCount / catCount).toFixed(3);
        var pColorGivenCatRow = pColorGivenCatLabel + pColorGivenCatValue;
        hoverinfoParts.push(pColorGivenCatRow);
    }

    var hovertext = hoverinfoParts.join('<br>');

    // Compute text color
    var textColor = tinycolor.mostReadable(bandViewModel.color, ['black', 'white']);

    return {
        x: hoverCenterX - rootBBox.left,
        y: hoverCenterY - rootBBox.top,
        // name: 'NAME',
        text: hovertext,
        color: bandViewModel.color,
        borderColor: 'black',
        fontFamily: 'Monaco, "Courier New", monospace',
        fontColor: textColor,
        fontSize: 10,
        idealAlign: hoverLabelIdealAlign
    };
}

/**
 * Handle dimension mouseover
 * @param {CategoryBandViewModel} bandViewModel
 */
function mouseoverCategoryBand(bandViewModel) {
    if(!bandViewModel.parcatsViewModel.dragDimension) {
        // We're not currently dragging

        if(bandViewModel.parcatsViewModel.hoverinfoItems.indexOf('skip') === -1) {
            // hoverinfo is not skip, so we at least style the bands and emit interaction events

            // Mouse
            var mouseY = d3.mouse(this)[1];
            if(mouseY < -1) {
                // Hover is above above the category rectangle (probably the dimension title text)
                return;
            }

            var gd = bandViewModel.parcatsViewModel.graphDiv;
            var fullLayout = gd._fullLayout;
            var rootBBox = fullLayout._paperdiv.node().getBoundingClientRect();
            var hoveron = bandViewModel.parcatsViewModel.hoveron;

            /** @type {HTMLElement} */
            var bandElement = this;

            // Handle style and events
            if(hoveron === 'color') {
                styleForColorHovermode(bandElement);
                emitPointsEventColorHovermode(bandElement, 'plotly_hover', d3.event);
            } else {
                styleForCategoryHovermode(bandElement);
                emitPointsEventCategoryHovermode(bandElement, 'plotly_hover', d3.event);
            }

            // Handle hover label
            if(bandViewModel.parcatsViewModel.hoverinfoItems.indexOf('none') === -1) {
                var hoverItems;
                if(hoveron === 'category') {
                    hoverItems = createHoverLabelForCategoryHovermode(rootBBox, bandElement);
                } else if(hoveron === 'color') {
                    hoverItems = createHoverLabelForColorHovermode(rootBBox, bandElement);
                } else if(hoveron === 'dimension') {
                    hoverItems = createHoverLabelForDimensionHovermode(rootBBox, bandElement);
                }

                if(hoverItems) {
                    Fx.multiHovers(hoverItems, {
                        container: fullLayout._hoverlayer.node(),
                        outerContainer: fullLayout._paper.node(),
                        gd: gd
                    });
                }
            }
        }
    }
}


/**
 * Handle dimension mouseover
 * @param {CategoryBandViewModel} bandViewModel
 */
function mouseoutCategory(bandViewModel) {

    var parcatsViewModel = bandViewModel.parcatsViewModel;

    if(!parcatsViewModel.dragDimension) {
        // We're not dragging anything

        // Reset unhovered styles
        stylePathsNoHover(parcatsViewModel.pathSelection);
        styleCategoriesNoHover(parcatsViewModel.dimensionSelection.selectAll('g.category'));
        styleBandsNoHover(parcatsViewModel.dimensionSelection.selectAll('g.category').selectAll('rect.bandrect'));

        // Remove hover label
        Fx.loneUnhover(parcatsViewModel.graphDiv._fullLayout._hoverlayer.node());

        // Restore path order
        parcatsViewModel.pathSelection.sort(compareRawColor);

        // Emit unhover event
        if(parcatsViewModel.hoverinfoItems.indexOf('skip') === -1) {

            var hoveron = bandViewModel.parcatsViewModel.hoveron;
            var bandElement = this;

            // Handle style and events
            if(hoveron === 'color') {
                emitPointsEventColorHovermode(bandElement, 'plotly_unhover', d3.event);
            } else {
                emitPointsEventCategoryHovermode(bandElement, 'plotly_unhover', d3.event);
            }
        }
    }
}


/**
 * Handle dimension drag start
 * @param {DimensionViewModel} d
 */
function dragDimensionStart(d) {

    // Check if dragging is supported
    if(d.parcatsViewModel.arrangement === 'fixed') {
        return;
    }

    // Save off initial drag indexes for dimension
    d.dragDimensionDisplayInd = d.model.displayInd;
    d.initialDragDimensionDisplayInds = d.parcatsViewModel.model.dimensions.map(function(d) {return d.displayInd;});
    d.dragHasMoved = false;

    // Check for category hit
    d.dragCategoryDisplayInd = null;
    d3.select(this)
        .selectAll('g.category')
        .select('rect.catrect')
        .each(
            /** @param {CategoryViewModel} catViewModel */
            function(catViewModel) {
                var catMouseX = d3.mouse(this)[0];
                var catMouseY = d3.mouse(this)[1];


                if(-2 <= catMouseX && catMouseX <= catViewModel.width + 2 &&
                    -2 <= catMouseY && catMouseY <= catViewModel.height + 2) {

                    // Save off initial drag indexes for categories
                    d.dragCategoryDisplayInd = catViewModel.model.displayInd;
                    d.initialDragCategoryDisplayInds = d.model.categories.map(function(c) {
                        return c.displayInd;
                    });

                    // Initialize categories dragY to be the current y position
                    catViewModel.model.dragY = catViewModel.y;

                    // Raise category
                    Lib.raiseToTop(this.parentNode);

                    // Get band element
                    d3.select(this.parentNode)
                        .selectAll('rect.bandrect')
                        /** @param {CategoryBandViewModel} bandViewModel */
                        .each(function(bandViewModel) {
                            if(bandViewModel.y < catMouseY && catMouseY <= bandViewModel.y + bandViewModel.height) {
                                d.potentialClickBand = this;
                            }
                        });
                }
            });

    // Update toplevel drag dimension
    d.parcatsViewModel.dragDimension = d;

    // Remove hover label if any
    Fx.loneUnhover(d.parcatsViewModel.graphDiv._fullLayout._hoverlayer.node());
}

/**
 * Handle dimension drag
 * @param {DimensionViewModel} d
 */
function dragDimension(d) {

    // Check if dragging is supported
    if(d.parcatsViewModel.arrangement === 'fixed') {
        return;
    }

    d.dragHasMoved = true;

    if(d.dragDimensionDisplayInd === null) {
        return;
    }

    var dragDimInd = d.dragDimensionDisplayInd;
    var prevDimInd = dragDimInd - 1;
    var nextDimInd = dragDimInd + 1;

    var dragDimension = d.parcatsViewModel
        .dimensions[dragDimInd];

    // Update category
    if(d.dragCategoryDisplayInd !== null) {

        var dragCategory = dragDimension.categories[d.dragCategoryDisplayInd];

        // Update dragY by dy
        dragCategory.model.dragY += d3.event.dy;
        var categoryY = dragCategory.model.dragY;

        // Check for category drag swaps
        var catDisplayInd = dragCategory.model.displayInd;
        var dimCategoryViews = dragDimension.categories;

        var catAbove = dimCategoryViews[catDisplayInd - 1];
        var catBelow = dimCategoryViews[catDisplayInd + 1];

        // Check for overlap above
        if(catAbove !== undefined) {

            if(categoryY < (catAbove.y + catAbove.height / 2.0)) {

                // Swap display inds
                dragCategory.model.displayInd = catAbove.model.displayInd;
                catAbove.model.displayInd = catDisplayInd;
            }
        }

        if(catBelow !== undefined) {

            if((categoryY + dragCategory.height) > (catBelow.y + catBelow.height / 2.0)) {

                // Swap display inds
                dragCategory.model.displayInd = catBelow.model.displayInd;
                catBelow.model.displayInd = catDisplayInd;
            }
        }

        // Update category drag display index
        d.dragCategoryDisplayInd = dragCategory.model.displayInd;
    }

    // Update dimension position
    if(d.dragCategoryDisplayInd === null || d.parcatsViewModel.arrangement === 'freeform') {
        dragDimension.model.dragX = d3.event.x;

        // Check for dimension swaps
        var prevDimension = d.parcatsViewModel.dimensions[prevDimInd];
        var nextDimension = d.parcatsViewModel.dimensions[nextDimInd];

        if(prevDimension !== undefined) {
            if(dragDimension.model.dragX < (prevDimension.x + prevDimension.width)) {

                // Swap display inds
                dragDimension.model.displayInd = prevDimension.model.displayInd;
                prevDimension.model.displayInd = dragDimInd;
            }
        }

        if(nextDimension !== undefined) {
            if((dragDimension.model.dragX + dragDimension.width) > nextDimension.x) {

                // Swap display inds
                dragDimension.model.displayInd = nextDimension.model.displayInd;
                nextDimension.model.displayInd = d.dragDimensionDisplayInd;
            }
        }

        // Update drag display index
        d.dragDimensionDisplayInd = dragDimension.model.displayInd;
    }

    // Update view models
    updateDimensionViewModels(d.parcatsViewModel);
    updatePathViewModels(d.parcatsViewModel);

    // Update svg geometry
    updateSvgCategories(d.parcatsViewModel);
    updateSvgPaths(d.parcatsViewModel);
}


/**
 * Handle dimension drag end
 * @param {DimensionViewModel} d
 */
function dragDimensionEnd(d) {

    // Check if dragging is supported
    if(d.parcatsViewModel.arrangement === 'fixed') {
        return;
    }

    if(d.dragDimensionDisplayInd === null) {
        return;
    }

    d3.select(this).selectAll('text').attr('font-weight', 'normal');

    // Compute restyle command
    // -----------------------
    var restyleData = {};
    var traceInd = getTraceIndex(d.parcatsViewModel);

    // ### Handle dimension reordering ###
    var finalDragDimensionDisplayInds = d.parcatsViewModel.model.dimensions.map(function(d) {return d.displayInd;});
    var anyDimsReordered = d.initialDragDimensionDisplayInds.some(function(initDimDisplay, dimInd) {
        return initDimDisplay !== finalDragDimensionDisplayInds[dimInd];
    });

    if(anyDimsReordered) {
        finalDragDimensionDisplayInds.forEach(function(finalDimDisplay, dimInd) {
            var containerInd = d.parcatsViewModel.model.dimensions[dimInd].containerInd;
            restyleData['dimensions[' + containerInd + '].displayindex'] = finalDimDisplay;
        });
    }

    // ### Handle category reordering ###
    var anyCatsReordered = false;
    if(d.dragCategoryDisplayInd !== null) {
        var finalDragCategoryDisplayInds = d.model.categories.map(function(c) {
            return c.displayInd;
        });

        anyCatsReordered = d.initialDragCategoryDisplayInds.some(function(initCatDisplay, catInd) {
            return initCatDisplay !== finalDragCategoryDisplayInds[catInd];
        });

        if(anyCatsReordered) {

            // Sort a shallow copy of the category models by display index
            var sortedCategoryModels = d.model.categories.slice().sort(
                function(a, b) { return a.displayInd - b.displayInd; });

            // Get new categoryarray and ticktext values
            var newCategoryArray = sortedCategoryModels.map(function(v) { return v.categoryValue; });
            var newCategoryLabels = sortedCategoryModels.map(function(v) { return v.categoryLabel; });

            restyleData['dimensions[' + d.model.containerInd + '].categoryarray'] = [newCategoryArray];
            restyleData['dimensions[' + d.model.containerInd + '].ticktext'] = [newCategoryLabels];
            restyleData['dimensions[' + d.model.containerInd + '].categoryorder'] = 'array';
        }
    }

    // Handle potential click event
    // ----------------------------
    if(d.parcatsViewModel.hoverinfoItems.indexOf('skip') === -1) {
        if(!d.dragHasMoved && d.potentialClickBand) {
            if(d.parcatsViewModel.hoveron === 'color') {
                emitPointsEventColorHovermode(d.potentialClickBand, 'plotly_click', d3.event.sourceEvent);
            } else {
                emitPointsEventCategoryHovermode(d.potentialClickBand, 'plotly_click', d3.event.sourceEvent);
            }
        }
    }

    // Nullify drag states
    // -------------------
    d.model.dragX = null;
    if(d.dragCategoryDisplayInd !== null) {
        var dragCategory = d.parcatsViewModel
            .dimensions[d.dragDimensionDisplayInd]
            .categories[d.dragCategoryDisplayInd];

        dragCategory.model.dragY = null;
        d.dragCategoryDisplayInd = null;
    }

    d.dragDimensionDisplayInd = null;
    d.parcatsViewModel.dragDimension = null;
    d.dragHasMoved = null;
    d.potentialClickBand = null;

    // Update view models
    // ------------------
    updateDimensionViewModels(d.parcatsViewModel);
    updatePathViewModels(d.parcatsViewModel);

    // Perform transition
    // ------------------
    var transition = d3.transition()
        .duration(300)
        .ease('cubic-in-out');

    transition
        .each(function() {
            updateSvgCategories(d.parcatsViewModel, true);
            updateSvgPaths(d.parcatsViewModel, true);
        })
        .each('end', function() {
            if(anyDimsReordered || anyCatsReordered) {
                // Perform restyle if the order of categories or dimensions changed
                Plotly.restyle(d.parcatsViewModel.graphDiv, restyleData, [traceInd]);
            }
        });
}

/**
 *
 * @param {ParcatsViewModel} parcatsViewModel
 */
function getTraceIndex(parcatsViewModel) {
    var traceInd;
    var allTraces = parcatsViewModel.graphDiv._fullData;
    for(var i = 0; i < allTraces.length; i++) {
        if(parcatsViewModel.key === allTraces[i].uid) {
            traceInd = i;
            break;
        }
    }
    return traceInd;
}

/** Update the svg paths for view model
 * @param {ParcatsViewModel} parcatsViewModel
 * @param {boolean} hasTransition Whether to update element with transition
 */
function updateSvgPaths(parcatsViewModel, hasTransition) {

    if(hasTransition === undefined) {
        hasTransition = false;
    }

    function transition(selection) {
        return hasTransition ? selection.transition() : selection;
    }

    // Update binding
    parcatsViewModel.pathSelection.data(function(d) {
        return d.paths;
    }, key);

    // Update paths
    transition(parcatsViewModel.pathSelection).attr('d', function(d) {
        return d.svgD;
    });
}

/** Update the svg paths for view model
 * @param {ParcatsViewModel} parcatsViewModel
 * @param {boolean} hasTransition Whether to update element with transition
 */
function updateSvgCategories(parcatsViewModel, hasTransition) {

    if(hasTransition === undefined) {
        hasTransition = false;
    }

    function transition(selection) {
        return hasTransition ? selection.transition() : selection;
    }

    // Update binding
    parcatsViewModel.dimensionSelection
        .data(function(d) {
            return d.dimensions;}, key);

    var categorySelection = parcatsViewModel.dimensionSelection
        .selectAll('g.category')
        .data(function(d) {return d.categories;}, key);

    // Update dimension position
    transition(parcatsViewModel.dimensionSelection)
        .attr('transform', function(d) {
            return 'translate(' + d.x + ', 0)';
        });

    // Update category position
    transition(categorySelection)
        .attr('transform', function(d) {
            return 'translate(0, ' + d.y + ')';
        });

    var dimLabelSelection = categorySelection.select('.dimlabel');

    // ### Update dimension label
    // Only the top-most display category should have the dimension label
    dimLabelSelection
        .text(function(d, i) {
            if(i === 0) {
                // Add dimension label above topmost category
                return d.parcatsViewModel.model.dimensions[d.model.dimensionInd].dimensionLabel;
            } else {
                return null;
            }
        });

    // Update category label
    // Categories in the right-most display dimension have their labels on
    // the right, all others on the left
    var catLabelSelection = categorySelection.select('.catlabel');
    catLabelSelection
        .attr('text-anchor',
            function(d) {
                if(catInRightDim(d)) {
                    // Place label to the right of category
                    return 'start';
                } else {
                    // Place label to the left of category
                    return 'end';
                }
            })
        .attr('x',
            function(d) {
                if(catInRightDim(d)) {
                    // Place label to the right of category
                    return d.width + 5;
                } else {
                    // Place label to the left of category
                    return -5;
                }
            })
        .each(function(d) {
            // Update attriubutes of <tspan> elements
            var newX;
            var newAnchor;
            if(catInRightDim(d)) {
                // Place label to the right of category
                newX = d.width + 5;
                newAnchor = 'start';
            } else {
                // Place label to the left of category
                newX = -5;
                newAnchor = 'end';
            }
            d3.select(this)
                .selectAll('tspan')
                .attr('x', newX)
                .attr('text-anchor', newAnchor);
        });

    // Update bands
    // Initialize color band rects
    var bandSelection = categorySelection
        .selectAll('rect.bandrect')
        .data(
            /** @param {CategoryViewModel} catViewModel*/
            function(catViewModel) {
                return catViewModel.bands;
            }, key);

    var bandsSelectionEnter = bandSelection.enter()
        .append('rect')
        .attr('class', 'bandrect')
        .attr('cursor', 'move')
        .attr('stroke-opacity', 0)
        .attr('fill', function(d) {
            return d.color;
        })
        .attr('fill-opacity', 0);

    bandSelection
        .attr('fill', function(d) {
            return d.color;
        })
        .attr('width', function(d) {
            return d.width;
        })
        .attr('height', function(d) {
            return d.height;
        })
        .attr('y', function(d) {
            return d.y;
        });

    styleBandsNoHover(bandsSelectionEnter);

    // Raise bands to the top
    bandSelection.each(function() {Lib.raiseToTop(this);});

    // Remove unused bands
    bandSelection.exit().remove();
}

/**
 * Create a ParcatsViewModel traces
 * @param {Object} graphDiv
 *  Top-level graph div element
 * @param {Layout} layout
 *  SVG layout object
 * @param {Array.<ParcatsModel>} wrappedParcatsModel
 *  Wrapped ParcatsModel for this trace
 * @return {ParcatsViewModel}
 */
function createParcatsViewModel(graphDiv, layout, wrappedParcatsModel) {
    // Unwrap model
    var parcatsModel = wrappedParcatsModel[0];

    // Compute margin
    var margin = layout.margin || {l: 80, r: 80, t: 100, b: 80};

    // Compute pixel position/extents
    var trace = parcatsModel.trace;
    var domain = trace.domain;
    var figureWidth = layout.width;
    var figureHeight = layout.height;
    var traceWidth = Math.floor(figureWidth * (domain.x[1] - domain.x[0]));
    var traceHeight = Math.floor(figureHeight * (domain.y[1] - domain.y[0]));
    var traceX = domain.x[0] * figureWidth + margin.l;
    var traceY = layout.height - domain.y[1] * layout.height + margin.t;

    // Handle path shape
    // -----------------
    var pathShape = trace.line.shape;

    // Handle hover info
    // -----------------
    var hoverinfoItems;
    if(trace.hoverinfo === 'all') {
        hoverinfoItems = ['count', 'probability'];
    } else {
        hoverinfoItems = trace.hoverinfo.split('+');
    }

    // Construct parcatsViewModel
    // --------------------------
    var parcatsViewModel = {
        key: trace.uid,
        model: parcatsModel,
        x: traceX,
        y: traceY,
        width: traceWidth,
        height: traceHeight,
        hoveron: trace.hoveron,
        hoverinfoItems: hoverinfoItems,
        arrangement: trace.arrangement,
        bundlecolors: trace.bundlecolors,
        sortpaths: trace.sortpaths,
        labelfont: trace.labelfont,
        categorylabelfont: trace.tickfont,
        pathShape: pathShape,
        dragDimension: null,
        margin: margin,
        paths: [],
        dimensions: [],
        graphDiv: graphDiv,
        traceSelection: null,
        pathSelection: null,
        dimensionSelection: null
    };

    // Update dimension view models if we have at least 1 dimension
    if(parcatsModel.dimensions) {
        updateDimensionViewModels(parcatsViewModel);

        // Update path view models if we have at least 2 dimensions
        updatePathViewModels(parcatsViewModel);
    }
    // Inside a categories view model
    return parcatsViewModel;
}

/**
 * Build the SVG string to represents a parallel categories path
 * @param {Array.<Number>} leftXPositions
 *  Array of the x positions of the left edge of each dimension (in display order)
 * @param {Array.<Number>} pathYs
 *  Array of the y positions of the top of the path at each dimension (in display order)
 * @param {Array.<Number>} dimWidths
 *  Array of the widths of each dimension in display order
 * @param {Number} pathHeight
 *  The height of the path in pixels
 * @param {Number} curvature
 *  The curvature factor for the path. 0 results in a straight line and values greater than zero result in curved paths
 * @return {string}
 */
function buildSvgPath(leftXPositions, pathYs, dimWidths, pathHeight, curvature) {

    // Compute the x midpoint of each path segment
    var xRefPoints1 = [];
    var xRefPoints2 = [];
    var refInterpolator;
    var d;

    for(d = 0; d < dimWidths.length - 1; d++) {
        refInterpolator = d3.interpolateNumber(dimWidths[d] + leftXPositions[d], leftXPositions[d + 1]);
        xRefPoints1.push(refInterpolator(curvature));
        xRefPoints2.push(refInterpolator(1 - curvature));
    }

    // Move to top of path on left edge of left-most category
    var svgD = 'M ' + leftXPositions[0] + ',' + pathYs[0];

    // Horizontal line to right edge
    svgD += 'l' + dimWidths[0] + ',0 ';

    // Horizontal line to right edge
    for(d = 1; d < dimWidths.length; d++) {

        // Curve to left edge of category
        svgD += 'C' + xRefPoints1[d - 1] + ',' + pathYs[d - 1] +
              ' ' + xRefPoints2[d - 1] + ',' + pathYs[d] +
              ' ' + leftXPositions[d] + ',' + pathYs[d];

        // svgD += 'L' + leftXPositions[d] + ',' + pathYs[d];

        // Horizontal line to right edge
        svgD += 'l' + dimWidths[d] + ',0 ';
    }

    // Line down
    svgD += 'l' + '0,' + pathHeight + ' ';

    // Line to left edge of right-most category
    svgD += 'l -' + dimWidths[dimWidths.length - 1] + ',0 ';

    for(d = dimWidths.length - 2; d >= 0; d--) {

        // Curve to right edge of category
        svgD += 'C' + xRefPoints2[d] + ',' + (pathYs[d + 1] + pathHeight) +
             ' ' + xRefPoints1[d] + ',' + (pathYs[d] + pathHeight) +
             ' ' + (leftXPositions[d] + dimWidths[d]) + ',' + (pathYs[d] + pathHeight);

        // svgD += 'L' + (leftXPositions[d] + dimWidths[d]) + ',' + (pathYs[d] + pathHeight);

        // Horizontal line to right edge
        svgD += 'l-' + dimWidths[d] + ',0 ';
    }

    // Close path
    svgD += 'Z';
    return svgD;
}

/**
 * Update the path view models based on the dimension view models in a ParcatsViewModel
 *
 * @param {ParcatsViewModel} parcatsViewModel
 *  View model for trace
 */
function updatePathViewModels(parcatsViewModel) {

    // Initialize an array of the y position of the top of the next path to be added to each category.
    //
    // nextYPositions[d][c] is the y position of the next path through category with index c of dimension with index d
    var dimensionViewModels = parcatsViewModel.dimensions;
    var parcatsModel = parcatsViewModel.model;
    var nextYPositions = dimensionViewModels.map(
        function(d) {
            return d.categories.map(
                function(c) {
                    return c.y;
                });
        });

    // Array from category index to category display index for each true dimension index
    var catToDisplayIndPerDim = parcatsViewModel.model.dimensions.map(
        function(d) {
            return d.categories.map(function(c) {return c.displayInd;});
        });

    // Array from true dimension index to dimension display index
    var dimToDisplayInd = parcatsViewModel.model.dimensions.map(function(d) {return d.displayInd;});
    var displayToDimInd = parcatsViewModel.dimensions.map(function(d) {return d.model.dimensionInd;});

    // Array of the x position of the left edge of the rectangles for each dimension
    var leftXPositions = dimensionViewModels.map(
        function(d) {
            return d.x;
        });

    // Compute dimension widths
    var dimWidths = dimensionViewModels.map(function(d) {return d.width;});

    // Build sorted Array of PathModel objects
    var pathModels = [];
    for(var p in parcatsModel.paths) {
        if(parcatsModel.paths.hasOwnProperty(p)) {
            pathModels.push(parcatsModel.paths[p]);
        }
    }

    // Compute category display inds to use for sorting paths
    function pathDisplayCategoryInds(pathModel) {
        var dimensionInds = pathModel.categoryInds.map(function(catInd, dimInd) {return catToDisplayIndPerDim[dimInd][catInd];});
        var displayInds = displayToDimInd.map(function(dimInd) {
            return dimensionInds[dimInd];
        });
        return displayInds;
    }

    // Sort in ascending order by display index array
    pathModels.sort(function(v1, v2) {

        // Build display inds for each path
        var sortArray1 = pathDisplayCategoryInds(v1);
        var sortArray2 = pathDisplayCategoryInds(v2);

        // Handle path sort order
        if(parcatsViewModel.sortpaths === 'backward') {
            sortArray1.reverse();
            sortArray2.reverse();
        }

        // Append the first value index of the path to break ties
        sortArray1.push(v1.valueInds[0]);
        sortArray2.push(v2.valueInds[0]);

        // Handle color bundling
        if(parcatsViewModel.bundlecolors) {
            // Prepend sort array with the raw color value
            sortArray1.unshift(v1.rawColor);
            sortArray2.unshift(v2.rawColor);
        }

        // colors equal, sort by display categories
        if(sortArray1 < sortArray2) {
            return -1;
        }
        if(sortArray1 > sortArray2) {
            return 1;
        }

        return 0;
    });

    // Create path models
    var pathViewModels = new Array(pathModels.length);
    var totalCount = dimensionViewModels[0].model.count;
    var totalHeight = dimensionViewModels[0].categories
        .map(function(c) { return c.height; })
        .reduce(function(v1, v2) { return v1 + v2; });


    for(var pathNumber = 0; pathNumber < pathModels.length; pathNumber++) {
        var pathModel = pathModels[pathNumber];

        var pathHeight;
        if(totalCount > 0) {
            pathHeight = totalHeight * (pathModel.count / totalCount);
        } else {
            pathHeight = 0;
        }

        // Build path y coords
        var pathYs = new Array(nextYPositions.length);
        for(var d = 0; d < pathModel.categoryInds.length; d++) {
            var catInd = pathModel.categoryInds[d];
            var catDisplayInd = catToDisplayIndPerDim[d][catInd];
            var dimDisplayInd = dimToDisplayInd[d];

            // Update next y position
            pathYs[dimDisplayInd] = nextYPositions[dimDisplayInd][catDisplayInd];
            nextYPositions[dimDisplayInd][catDisplayInd] += pathHeight;

            // Update category color information
            var catViewModle = parcatsViewModel.dimensions[dimDisplayInd].categories[catDisplayInd];
            var numBands = catViewModle.bands.length;
            var lastCatBand = catViewModle.bands[numBands - 1];

            if(lastCatBand === undefined || pathModel.rawColor !== lastCatBand.rawColor) {
                // Create a new band
                var bandY = lastCatBand === undefined ? 0 : lastCatBand.y + lastCatBand.height;
                catViewModle.bands.push({
                    key: bandY,
                    color: pathModel.color,
                    rawColor: pathModel.rawColor,
                    height: pathHeight,
                    width: catViewModle.width,
                    count: pathModel.count,
                    y: bandY,
                    categoryViewModel: catViewModle,
                    parcatsViewModel: parcatsViewModel
                });
            } else {
                // Extend current band
                var currentBand = catViewModle.bands[numBands - 1];
                currentBand.height += pathHeight;
                currentBand.count += pathModel.count;
            }
        }

        // build svg path
        var svgD;
        if(parcatsViewModel.pathShape === 'hspline') {
            svgD = buildSvgPath(leftXPositions, pathYs, dimWidths, pathHeight, 0.5);
        } else {
            svgD = buildSvgPath(leftXPositions, pathYs, dimWidths, pathHeight, 0);
        }

        pathViewModels[pathNumber] = {
            key: pathModel.valueInds[0],
            model: pathModel,
            height: pathHeight,
            leftXs: leftXPositions,
            topYs: pathYs,
            dimWidths: dimWidths,
            svgD: svgD,
            parcatsViewModel: parcatsViewModel
        };
    }

    parcatsViewModel.paths = pathViewModels;

 // * @property key
 // *  Unique key for this model
 // * @property {PathModel} model
 // *  Source path model
 // * @property {Number} height
 // *  Height of this path (pixels)
 // * @property {String} svgD
 // *  SVG path "d" attribute string
}

/**
 * Update the dimension view models based on the dimension models in a ParcatsViewModel
 *
 * @param {ParcatsViewModel} parcatsViewModel
 *  View model for trace
 */
function updateDimensionViewModels(parcatsViewModel) {

    // Compute dimension ordering
    var dimensionsIndInfo = parcatsViewModel.model.dimensions.map(function(d) {
        return {displayInd: d.displayInd, dimensionInd: d.dimensionInd};
    });

    dimensionsIndInfo.sort(function(a, b) {
        return a.displayInd - b.displayInd;
    });

    var dimensions = [];
    for(var displayInd in dimensionsIndInfo) {
        var dimensionInd = dimensionsIndInfo[displayInd].dimensionInd;
        var dimModel = parcatsViewModel.model.dimensions[dimensionInd];
        dimensions.push(createDimensionViewModel(parcatsViewModel, dimModel));
    }

    parcatsViewModel.dimensions = dimensions;
}

/**
 * Create a parcats DimensionViewModel
 *
 * @param {ParcatsViewModel} parcatsViewModel
 *  View model for trace
 * @param {DimensionModel} dimensionModel
 * @return {DimensionViewModel}
 */
function createDimensionViewModel(parcatsViewModel, dimensionModel) {

    // Compute dimension x position
    var categoryLabelPad = 40;
    var dimWidth = 16;
    var numDimensions = parcatsViewModel.model.dimensions.length;
    var displayInd = dimensionModel.displayInd;

    // Compute x coordinate values
    var dimDx;
    var dimX0;
    var dimX;

    if(numDimensions > 1) {
        dimDx = (parcatsViewModel.width - 2 * categoryLabelPad - dimWidth) / (numDimensions - 1);
    } else {
        dimDx = 0;
    }
    dimX0 = categoryLabelPad;
    dimX = dimX0 + dimDx * displayInd;

    // Compute categories
    var categories = [];
    var maxCats = parcatsViewModel.model.maxCats;
    var numCats = dimensionModel.categories.length;
    var catSpacing = 8;
    var totalCount = dimensionModel.count;
    var totalHeight = parcatsViewModel.height - catSpacing * (maxCats - 1);
    var nextCatHeight;
    var nextCatModel;
    var nextCat;
    var catInd;
    var catDisplayInd;

    // Compute starting Y offset
    var nextCatY = (maxCats - numCats) * catSpacing / 2.0;

    // Compute category ordering
    var categoryIndInfo = dimensionModel.categories.map(function(c) {
        return {displayInd: c.displayInd, categoryInd: c.categoryInd};
    });

    categoryIndInfo.sort(function(a, b) {
        return a.displayInd - b.displayInd;
    });

    for(catDisplayInd = 0; catDisplayInd < numCats; catDisplayInd++) {
        catInd = categoryIndInfo[catDisplayInd].categoryInd;
        nextCatModel = dimensionModel.categories[catInd];

        if(totalCount > 0) {
            nextCatHeight = (nextCatModel.count / totalCount) * totalHeight;
        } else {
            nextCatHeight = 0;
        }

        nextCat = {
            key: nextCatModel.valueInds[0],
            model: nextCatModel,
            width: dimWidth,
            height: nextCatHeight,
            y: nextCatModel.dragY !== null ? nextCatModel.dragY : nextCatY,
            bands: [],
            parcatsViewModel: parcatsViewModel
        };

        nextCatY = nextCatY + nextCatHeight + catSpacing;
        categories.push(nextCat);
    }

    return {
        key: dimensionModel.dimensionInd,
        x: dimensionModel.dragX !== null ? dimensionModel.dragX : dimX,
        y: 0,
        width: dimWidth,
        model: dimensionModel,
        categories: categories,
        parcatsViewModel: parcatsViewModel,
        dragCategoryDisplayInd: null,
        dragDimensionDisplayInd: null,
        initialDragDimensionDisplayInds: null,
        initialDragCategoryDisplayInds: null,
        dragHasMoved: null,
        potentialClickBand: null
    };
}

// JSDoc typedefs
// ==============
/**
 * @typedef {Object} Layout
 *  Object containing svg layout information
 *
 * @property {Number} width (pixels)
 *  Usable width for Figure (after margins are removed)
 * @property {Number} height (pixels)
 *  Usable height for Figure (after margins are removed)
 * @property {Margin} margin
 *  Margin around the Figure (pixels)
 */

/**
 * @typedef {Object} Margin
 *  Object containing padding information in pixels
 *
 * @property {Number} t
 *  Top margin
 * @property {Number} r
 *  Right margin
 * @property {Number} b
 *  Bottom margin
 * @property {Number} l
 *  Left margin
 */

/**
 * @typedef {Object} Font
 *  Object containing font information
 *
 * @property {Number} size: Font size
 * @property {String} color: Font color
 * @property {String} family: Font family
 */

/**
 * @typedef {Object} ParcatsViewModel
 *  Object containing calculated parcats view information
 *
 *  These are quantities that require Layout information to calculate
 * @property key
 *  Unique key for this model
 * @property {ParcatsModel} model
 *  Source parcats model
 * @property {Array.<DimensionViewModel>} dimensions
 *  Array of dimension view models
 * @property {Number} width
 *  Width for this trace (pixels)
 * @property {Number} height
 *  Height for this trace (pixels)
 * @property {Number} x
 *  X position of this trace with respect to the Figure (pixels)
 * @property {Number} y
 *  Y position of this trace with respect to the Figure (pixels)
 * @property {String} hoveron
 *  Hover interaction mode. One of: 'category', 'color', or 'dimension'
 * @property {Array.<String>} hoverinfoItems
 *  Info to display on hover. Array with a combination of 'counts' and/or 'probabilities', or 'none', or 'skip'
 * @property {String} arrangement
 *  Category arrangement. One of: 'perpendicular', 'freeform', or 'fixed'
 * @property {Boolean} bundlecolors
 *  Whether paths should be sorted so that like colors are bundled together as they pass through categories
 * @property {String} sortpaths
 *  If 'forward' then sort paths based on dimensions from left to right. If 'backward' sort based on dimensions
 *  from right to left
 * @property {Font} labelfont
 *  Font for the dimension labels
 * @property {Font} categorylabelfont
 *  Font for the category labels
 * @property {String} pathShape
 *  The shape of the paths. Either 'linear' or 'hspline'.
 * @property {DimensionViewModel|null} dragDimension
 *  Dimension currently being dragged. Null if no drag in progress
 * @property {Margin} margin
 *  Margin around the Figure
 * @property {Object} graphDiv
 *  Top-level graph div element
 * @property {Object} traceSelection
 *  D3 selection of this view models trace group element
 * @property {Object} pathSelection
 *  D3 selection of this view models path elements
 * @property {Object} dimensionSelection
 *  D3 selection of this view models dimension group element
 */

/**
 * @typedef {Object} DimensionViewModel
 *  Object containing calculated parcats dimension view information
 *
 *  These are quantities that require Layout information to calculate
 * @property key
 *  Unique key for this model
 * @property {DimensionModel} model
 *  Source dimension model
 * @property {Number} x
 *  X position of the center of this dimension with respect to the Figure (pixels)
 * @property {Number} y
 *  Y position of the top of this dimension with respect to the Figure (pixels)
 * @property {Number} width
 *  Width of categories in this dimension (pixels)
 * @property {ParcatsViewModel} parcatsViewModel
 *  The parent trace's view model
 * @property {Array.<CategoryViewModel>} categories
 *  Dimensions category view models
 * @property {Number|null} dragCategoryDisplayInd
 *  Display index of category currently being dragged. null if no category is being dragged
 * @property {Number|null} dragDimensionDisplayInd
 *  Display index of the dimension being dragged. null if no dimension is being dragged
 * @property {Array.<Number>|null} initialDragDimensionDisplayInds
 *  Dimensions display indexes at the beginning of the current drag. null if no dimension is being dragged
 * @property {Array.<Number>|null} initialDragCategoryDisplayInds
 *  Category display indexes for the at the beginning of the current drag. null if no category is being dragged
 * @property {HTMLElement} potentialClickBand
 *  Band under mouse when current drag began. If no drag movement takes place then a click will be emitted for this
 *  band. Null if not drag in progress.
 * @property {Boolean} dragHasMoved
 *  True if there is an active drag and the drag has moved. If drag doesn't move before being ended then
 *  this may be interpreted as a click. Null if no drag in progress
 */

/**
 * @typedef {Object} CategoryViewModel
 *  Object containing calculated parcats category view information
 *
 *  These are quantities that require Layout information to calculate
 * @property key
 *  Unique key for this model
 * @property {CategoryModel} model
 *  Source category model
 * @property {Number} width
 *  Width for this category (pixels)
 * @property {Number} height
 *  Height for this category (pixels)
 * @property {Number} y
 *  Y position of this cateogry with respect to the Figure (pixels)
 * @property {Array.<CategoryBandViewModel>} bands
 *  Array of color bands inside the category
 * @property {ParcatsViewModel} parcatsViewModel
 *  The parent trace's view model
 */

/**
 * @typedef {Object} CategoryBandViewModel
 *  Object containing calculated category band information. A category band is a region inside a category covering
 *  paths of a single color
 *
 * @property key
 *  Unique key for this model
 * @property color
 *  Band color
 * @property rawColor
 *  Raw color value for band
 * @property {Number} width
 *  Band width
 * @property {Number} height
 *  Band height
 * @property {Number} y
 *  Y position of top of the band with respect to the category
 * @property {Number} count
 *  The number of samples represented by the band
 * @property {CategoryViewModel} categoryViewModel
 *  The parent categorie's view model
 * @property {ParcatsViewModel} parcatsViewModel
 *  The parent trace's view model
 */

/**
 * @typedef {Object} PathViewModel
 *  Object containing calculated parcats path view information
 *
 *  These are quantities that require Layout information to calculate
 * @property key
 *  Unique key for this model
 * @property {PathModel} model
 *  Source path model
 * @property {Number} height
 *  Height of this path (pixels)
 * @property {Array.<Number>} leftXs
 *  The x position of the left edge of each display dimension
 * @property {Array.<Number>} topYs
 *  The y position of the top of the path for each display dimension
 * @property {Array.<Number>} dimWidths
 *  The width of each display dimension
 * @property {String} svgD
 *  SVG path "d" attribute string
 * @property {ParcatsViewModel} parcatsViewModel
 *  The parent trace's view model
 */

},{"../../components/drawing":592,"../../components/fx":610,"../../lib":694,"../../lib/svg_text_utils":718,"../../plot_api/plot_api":729,"d3":149,"tinycolor2":515}],1010:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


var parcats = _dereq_('./parcats');

/**
 * Create / update parcat traces
 *
 * @param {Object} graphDiv
 * @param {Array.<ParcatsModel>} parcatsModels
 */
module.exports = function plot(graphDiv, parcatsModels, transitionOpts, makeOnCompleteCallback) {
    var fullLayout = graphDiv._fullLayout;
    var svg = fullLayout._paper;
    var size = fullLayout._size;

    parcats(
        graphDiv,
        svg,
        parcatsModels,
        {
            width: size.w,
            height: size.h,
            margin: {
                t: size.t,
                r: size.r,
                b: size.b,
                l: size.l
            }
        },
        transitionOpts,
        makeOnCompleteCallback
    );
};

},{"./parcats":1009}],1011:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorAttributes = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
var axesAttrs = _dereq_('../../plots/cartesian/layout_attributes');
var fontAttrs = _dereq_('../../plots/font_attributes');
var domainAttrs = _dereq_('../../plots/domain').attributes;

var extendFlat = _dereq_('../../lib/extend').extendFlat;
var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;

module.exports = {
    domain: domainAttrs({name: 'parcoords', trace: true, editType: 'calc'}),

    hoverlabel: undefined,

    labelfont: fontAttrs({
        editType: 'calc',
        
    }),
    tickfont: fontAttrs({
        editType: 'calc',
        
    }),
    rangefont: fontAttrs({
        editType: 'calc',
        
    }),

    dimensions: templatedArray('dimension', {
        label: {
            valType: 'string',
            
            editType: 'calc',
            
        },
        // TODO: better way to determine ordinal vs continuous axes,
        // so users can use tickvals/ticktext with a continuous axis.
        tickvals: extendFlat({}, axesAttrs.tickvals, {editType: 'calc'}),
        ticktext: extendFlat({}, axesAttrs.ticktext, {editType: 'calc'}),
        tickformat: {
            valType: 'string',
            dflt: '3s',
            
            editType: 'calc',
            
        },
        visible: {
            valType: 'boolean',
            dflt: true,
            
            editType: 'calc',
            
        },
        range: {
            valType: 'info_array',
            
            items: [
                {valType: 'number', editType: 'calc'},
                {valType: 'number', editType: 'calc'}
            ],
            editType: 'calc',
            
        },
        constraintrange: {
            valType: 'info_array',
            
            freeLength: true,
            dimensions: '1-2',
            items: [
                {valType: 'number', editType: 'calc'},
                {valType: 'number', editType: 'calc'}
            ],
            editType: 'calc',
            
        },
        multiselect: {
            valType: 'boolean',
            dflt: true,
            
            editType: 'calc',
            
        },
        values: {
            valType: 'data_array',
            
            editType: 'calc',
            
        },
        editType: 'calc',
        
    }),

    line: extendFlat(
        colorAttributes('line', {
            // the default autocolorscale isn't quite usable for parcoords due to context ambiguity around 0 (grey, off-white)
            // autocolorscale therefore defaults to false too, to avoid being overridden by the  blue-white-red autocolor palette
            colorscaleDflt: 'Viridis',
            autoColorDflt: false,
            editTypeOverride: 'calc'
        }), {
            colorbar: colorbarAttrs,
            editType: 'calc'
        })
};

},{"../../components/colorbar/attributes":572,"../../components/colorscale/attributes":578,"../../lib/extend":684,"../../plot_api/plot_template":732,"../../plots/cartesian/layout_attributes":755,"../../plots/domain":768,"../../plots/font_attributes":769}],1012:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var c = _dereq_('./constants');
var d3 = _dereq_('d3');
var keyFun = _dereq_('../../lib/gup').keyFun;
var repeat = _dereq_('../../lib/gup').repeat;
var sortAsc = _dereq_('../../lib').sorterAsc;

var snapRatio = c.bar.snapRatio;
function snapOvershoot(v, vAdjacent) { return v * (1 - snapRatio) + vAdjacent * snapRatio; }

var snapClose = c.bar.snapClose;
function closeToCovering(v, vAdjacent) { return v * (1 - snapClose) + vAdjacent * snapClose; }

// snap for the low end of a range on an ordinal scale
// on an ordinal scale, always show some overshoot from the exact value,
// so it's clear we're covering it
// find the interval we're in, and snap to 1/4 the distance to the next
// these two could be unified at a slight loss of readability / perf
function ordinalScaleSnapLo(a, v, existingRanges) {
    if(overlappingExisting(v, existingRanges)) return v;

    var aPrev = a[0];
    var aPrevPrev = aPrev;
    for(var i = 1; i < a.length; i++) {
        var aNext = a[i];

        // very close to the previous - snap down to it
        if(v < closeToCovering(aPrev, aNext)) return snapOvershoot(aPrev, aPrevPrev);
        if(v < aNext || i === a.length - 1) return snapOvershoot(aNext, aPrev);

        aPrevPrev = aPrev;
        aPrev = aNext;
    }
}

function ordinalScaleSnapHi(a, v, existingRanges) {
    if(overlappingExisting(v, existingRanges)) return v;

    var aPrev = a[a.length - 1];
    var aPrevPrev = aPrev;
    for(var i = a.length - 2; i >= 0; i--) {
        var aNext = a[i];

        // very close to the previous - snap down to it
        if(v > closeToCovering(aPrev, aNext)) return snapOvershoot(aPrev, aPrevPrev);
        if(v > aNext || i === a.length - 1) return snapOvershoot(aNext, aPrev);

        aPrevPrev = aPrev;
        aPrev = aNext;
    }
}

function overlappingExisting(v, existingRanges) {
    for(var i = 0; i < existingRanges.length; i++) {
        if(v >= existingRanges[i][0] && v <= existingRanges[i][1]) return true;
    }
    return false;
}

function barHorizontalSetup(selection) {
    selection
        .attr('x', -c.bar.captureWidth / 2)
        .attr('width', c.bar.captureWidth);
}

function backgroundBarHorizontalSetup(selection) {
    selection
        .attr('visibility', 'visible')
        .style('visibility', 'visible')
        .attr('fill', 'yellow')
        .attr('opacity', 0);
}

function setHighlight(d) {
    if(!d.brush.filterSpecified) {
        return '0,' + d.height;
    }
    var pixelRanges = unitToPx(d.brush.filter.getConsolidated(), d.height);
    var dashArray = [0]; // we start with a 0 length selection as filter ranges are inclusive, not exclusive
    var p, sectionHeight, iNext;
    var currentGap = pixelRanges.length ? pixelRanges[0][0] : null;
    for(var i = 0; i < pixelRanges.length; i++) {
        p = pixelRanges[i];
        sectionHeight = p[1] - p[0];
        dashArray.push(currentGap);
        dashArray.push(sectionHeight);
        iNext = i + 1;
        if(iNext < pixelRanges.length) {
            currentGap = pixelRanges[iNext][0] - p[1];
        }
    }
    dashArray.push(d.height);
    // d.height is added at the end to ensure that (1) we have an even number of dasharray points, MDN page says
    // "If an odd number of values is provided, then the list of values is repeated to yield an even number of values."
    // and (2) it's _at least_ as long as the full height (even if range is minuscule and at the bottom) though this
    // may not be necessary, maybe duplicating the last point would do too. But no harm in a longer dasharray than line.
    return dashArray;
}

function unitToPx(unitRanges, height) {
    return unitRanges.map(function(pr) {
        return pr.map(function(v) { return v * height; }).sort(sortAsc);
    });
}

// is the cursor over the north, middle, or south of a bar?
// the end handles extend over the last 10% of the bar
function getRegion(fPix, y) {
    var pad = c.bar.handleHeight;
    if(y > fPix[1] + pad || y < fPix[0] - pad) return;
    if(y >= 0.9 * fPix[1] + 0.1 * fPix[0]) return 'n';
    if(y <= 0.9 * fPix[0] + 0.1 * fPix[1]) return 's';
    return 'ns';
}

function clearCursor() {
    d3.select(document.body)
        .style('cursor', null);
}

function styleHighlight(selection) {
    // stroke-dasharray is used to minimize the number of created DOM nodes, because the requirement calls for up to
    // 1000 individual selections on an axis, and there can be 60 axes per parcoords, and multiple parcoords per
    // dashboard. The technique is similar to https://codepen.io/monfera/pen/rLYqWR and using a `polyline` with
    // multiple sections, or a `path` element via its `d` attribute would also be DOM-sparing alternatives.
    selection.attr('stroke-dasharray', setHighlight);
}

function renderHighlight(root, tweenCallback) {
    var bar = d3.select(root).selectAll('.highlight, .highlight-shadow');
    var barToStyle = tweenCallback ? bar.transition().duration(c.bar.snapDuration).each('end', tweenCallback) : bar;
    styleHighlight(barToStyle);
}

function getInterval(d, y) {
    var b = d.brush;
    var active = b.filterSpecified;
    var closestInterval = NaN;
    var out = {};
    var i;

    if(active) {
        var height = d.height;
        var intervals = b.filter.getConsolidated();
        var pixIntervals = unitToPx(intervals, height);
        var hoveredInterval = NaN;
        var previousInterval = NaN;
        var nextInterval = NaN;
        for(i = 0; i <= pixIntervals.length; i++) {
            var p = pixIntervals[i];
            if(p && p[0] <= y && y <= p[1]) {
                // over a bar
                hoveredInterval = i;
                break;
            } else {
                // between bars, or before/after the first/last bar
                previousInterval = i ? i - 1 : NaN;
                if(p && p[0] > y) {
                    nextInterval = i;
                    break; // no point continuing as intervals are non-overlapping and sorted; could use log search
                }
            }
        }

        closestInterval = hoveredInterval;
        if(isNaN(closestInterval)) {
            if(isNaN(previousInterval) || isNaN(nextInterval)) {
                closestInterval = isNaN(previousInterval) ? nextInterval : previousInterval;
            }
            else {
                closestInterval = (y - pixIntervals[previousInterval][1] < pixIntervals[nextInterval][0] - y) ?
                    previousInterval : nextInterval;
            }
        }

        if(!isNaN(closestInterval)) {
            var fPix = pixIntervals[closestInterval];
            var region = getRegion(fPix, y);

            if(region) {
                out.interval = intervals[closestInterval];
                out.intervalPix = fPix;
                out.region = region;
            }
        }
    }

    if(d.ordinal && !out.region) {
        var a = d.unitTickvals;
        var unitLocation = d.unitToPaddedPx.invert(y);
        for(i = 0; i < a.length; i++) {
            var rangei = [
                a[Math.max(i - 1, 0)] * 0.25 + a[i] * 0.75,
                a[Math.min(i + 1, a.length - 1)] * 0.25 + a[i] * 0.75
            ];
            if(unitLocation >= rangei[0] && unitLocation <= rangei[1]) {
                out.clickableOrdinalRange = rangei;
                break;
            }
        }
    }

    return out;
}

function attachDragBehavior(selection) {
    // There's some fiddling with pointer cursor styling so that the cursor preserves its shape while dragging a brush
    // even if the cursor strays from the interacting bar, which is bound to happen as bars are thin and the user
    // will inevitably leave the hotspot strip. In this regard, it does something similar to what the D3 brush would do.
    selection
        .on('mousemove', function(d) {
            d3.event.preventDefault();
            if(!d.parent.inBrushDrag) {
                var y = d.height - d3.mouse(this)[1] - 2 * c.verticalPadding;
                var interval = getInterval(d, y);

                var cursor = 'crosshair';
                if(interval.clickableOrdinalRange) cursor = 'pointer';
                else if(interval.region) cursor = interval.region + '-resize';
                d3.select(document.body)
                    .style('cursor', cursor);
            }
        })
        .on('mouseleave', function(d) {
            if(!d.parent.inBrushDrag) clearCursor();
        })
        .call(d3.behavior.drag()
            .on('dragstart', function(d) {
                d3.event.sourceEvent.stopPropagation();
                var y = d.height - d3.mouse(this)[1] - 2 * c.verticalPadding;
                var unitLocation = d.unitToPaddedPx.invert(y);
                var b = d.brush;
                var interval = getInterval(d, y);
                var unitRange = interval.interval;
                var s = b.svgBrush;
                s.wasDragged = false; // we start assuming there won't be a drag - useful for reset
                s.grabbingBar = interval.region === 'ns';
                if(s.grabbingBar) {
                    var pixelRange = unitRange.map(d.unitToPaddedPx);
                    s.grabPoint = y - pixelRange[0] - c.verticalPadding;
                    s.barLength = pixelRange[1] - pixelRange[0];
                }
                s.clickableOrdinalRange = interval.clickableOrdinalRange;
                s.stayingIntervals = (d.multiselect && b.filterSpecified) ? b.filter.getConsolidated() : [];
                if(unitRange) {
                    s.stayingIntervals = s.stayingIntervals.filter(function(int2) {
                        return int2[0] !== unitRange[0] && int2[1] !== unitRange[1];
                    });
                }
                s.startExtent = interval.region ? unitRange[interval.region === 's' ? 1 : 0] : unitLocation;
                d.parent.inBrushDrag = true;
                s.brushStartCallback();
            })
            .on('drag', function(d) {
                d3.event.sourceEvent.stopPropagation();
                var y = d.height - d3.mouse(this)[1] - 2 * c.verticalPadding;
                var s = d.brush.svgBrush;
                s.wasDragged = true;

                if(s.grabbingBar) { // moving the bar
                    s.newExtent = [y - s.grabPoint, y + s.barLength - s.grabPoint].map(d.unitToPaddedPx.invert);
                } else { // south/north drag or new bar creation
                    s.newExtent = [s.startExtent, d.unitToPaddedPx.invert(y)].sort(sortAsc);
                }

                // take care of the parcoords axis height constraint: bar can't breach it
                var bottomViolation = Math.max(0, -s.newExtent[0]);
                var topViolation = Math.max(0, s.newExtent[1] - 1);
                s.newExtent[0] += bottomViolation;
                s.newExtent[1] -= topViolation;
                if(s.grabbingBar) {
                    // in case of bar dragging (non-resizing interaction, unlike north/south resize or new bar creation)
                    // the constraint adjustment must apply to the other end of the bar as well, otherwise it'd
                    // shorten or lengthen
                    s.newExtent[1] += bottomViolation;
                    s.newExtent[0] -= topViolation;
                }

                d.brush.filterSpecified = true;
                s.extent = s.stayingIntervals.concat([s.newExtent]);
                s.brushCallback(d);
                renderHighlight(this.parentNode);
            })
            .on('dragend', function(d) {
                var e = d3.event;
                e.sourceEvent.stopPropagation();
                var brush = d.brush;
                var filter = brush.filter;
                var s = brush.svgBrush;
                var grabbingBar = s.grabbingBar;
                s.grabbingBar = false;
                s.grabLocation = undefined;
                d.parent.inBrushDrag = false;
                clearCursor(); // instead of clearing, a nicer thing would be to set it according to current location
                if(!s.wasDragged) { // a click+release on the same spot (ie. w/o dragging) means a bar or full reset
                    s.wasDragged = undefined; // logic-wise unneeded, just shows `wasDragged` has no longer a meaning
                    if(s.clickableOrdinalRange) {
                        if(brush.filterSpecified && d.multiselect) {
                            s.extent.push(s.clickableOrdinalRange);
                        }
                        else {
                            s.extent = [s.clickableOrdinalRange];
                            brush.filterSpecified = true;
                        }
                    }
                    else if(grabbingBar) {
                        s.extent = s.stayingIntervals;
                        if(s.extent.length === 0) {
                            brushClear(brush);
                        }
                    } else {
                        brushClear(brush);
                    }
                    s.brushCallback(d);
                    renderHighlight(this.parentNode);
                    s.brushEndCallback(brush.filterSpecified ? filter.getConsolidated() : []);
                    return; // no need to fuse intervals or snap to ordinals, so we can bail early
                }

                var mergeIntervals = function() {
                    // Key piece of logic: once the button is released, possibly overlapping intervals will be fused:
                    // Here it's done immediately on click release while on ordinal snap transition it's done at the end
                    filter.set(filter.getConsolidated());
                };

                if(d.ordinal) {
                    var a = d.unitTickvals;
                    if(a[a.length - 1] < a[0]) a.reverse();
                    s.newExtent = [
                        ordinalScaleSnapLo(a, s.newExtent[0], s.stayingIntervals),
                        ordinalScaleSnapHi(a, s.newExtent[1], s.stayingIntervals)
                    ];
                    var hasNewExtent = s.newExtent[1] > s.newExtent[0];
                    s.extent = s.stayingIntervals.concat(hasNewExtent ? [s.newExtent] : []);
                    if(!s.extent.length) {
                        brushClear(brush);
                    }
                    s.brushCallback(d);
                    if(hasNewExtent) {
                        // merging intervals post the snap tween
                        renderHighlight(this.parentNode, mergeIntervals);
                    }
                    else {
                        // if no new interval, don't animate, just redraw the highlight immediately
                        mergeIntervals();
                        renderHighlight(this.parentNode);
                    }
                } else {
                    mergeIntervals(); // merging intervals immediately
                }
                s.brushEndCallback(brush.filterSpecified ? filter.getConsolidated() : []);
            })
        );
}

function startAsc(a, b) { return a[0] - b[0]; }

function renderAxisBrush(axisBrush) {

    var background = axisBrush.selectAll('.background').data(repeat);

    background.enter()
        .append('rect')
        .classed('background', true)
        .call(barHorizontalSetup)
        .call(backgroundBarHorizontalSetup)
        .style('pointer-events', 'auto') // parent pointer events are disabled; we must have it to register events
        .attr('transform', 'translate(0 ' + c.verticalPadding + ')');

    background
        .call(attachDragBehavior)
        .attr('height', function(d) {
            return d.height - c.verticalPadding;
        });

    var highlightShadow = axisBrush.selectAll('.highlight-shadow').data(repeat); // we have a set here, can't call it `extent`

    highlightShadow.enter()
        .append('line')
        .classed('highlight-shadow', true)
        .attr('x', -c.bar.width / 2)
        .attr('stroke-width', c.bar.width + c.bar.strokeWidth)
        .attr('stroke', c.bar.strokeColor)
        .attr('opacity', c.bar.strokeOpacity)
        .attr('stroke-linecap', 'butt');

    highlightShadow
        .attr('y1', function(d) { return d.height; })
        .call(styleHighlight);

    var highlight = axisBrush.selectAll('.highlight').data(repeat); // we have a set here, can't call it `extent`

    highlight.enter()
        .append('line')
        .classed('highlight', true)
        .attr('x', -c.bar.width / 2)
        .attr('stroke-width', c.bar.width - c.bar.strokeWidth)
        .attr('stroke', c.bar.fillColor)
        .attr('opacity', c.bar.fillOpacity)
        .attr('stroke-linecap', 'butt');

    highlight
        .attr('y1', function(d) { return d.height; })
        .call(styleHighlight);
}

function ensureAxisBrush(axisOverlays) {
    var axisBrush = axisOverlays.selectAll('.' + c.cn.axisBrush)
        .data(repeat, keyFun);

    axisBrush.enter()
        .append('g')
        .classed(c.cn.axisBrush, true);

    renderAxisBrush(axisBrush);
}

function getBrushExtent(brush) {
    return brush.svgBrush.extent.map(function(e) {return e.slice();});
}

function brushClear(brush) {
    brush.filterSpecified = false;
    brush.svgBrush.extent = [[0, 1]];
}

function axisBrushMoved(callback) {
    return function axisBrushMoved(dimension) {
        var brush = dimension.brush;
        var extent = getBrushExtent(brush);
        var newExtent = extent.slice();
        brush.filter.set(newExtent);
        callback();
    };
}

function dedupeRealRanges(intervals) {
    // Fuses elements of intervals if they overlap, yielding discontiguous intervals, results.length <= intervals.length
    // Currently uses closed intervals, ie. dedupeRealRanges([[400, 800], [300, 400]]) -> [300, 800]
    var queue = intervals.slice();
    var result = [];
    var currentInterval;
    var current = queue.shift();
    while(current) { // [].shift === undefined, so we don't descend into an empty array
        currentInterval = current.slice();
        while((current = queue.shift()) && current[0] <= /* right-open interval would need `<` */ currentInterval[1]) {
            currentInterval[1] = Math.max(currentInterval[1], current[1]);
        }
        result.push(currentInterval);
    }
    return result;
}

function makeFilter() {
    var filter = [];
    var consolidated;
    var bounds;
    return {
        set: function(a) {
            filter = a
                .map(function(d) { return d.slice().sort(sortAsc); })
                .sort(startAsc);
            consolidated = dedupeRealRanges(filter);
            bounds = filter.reduce(function(p, n) {
                return [Math.min(p[0], n[0]), Math.max(p[1], n[1])];
            }, [Infinity, -Infinity]);
        },
        get: function() { return filter.slice(); },
        getConsolidated: function() { return consolidated; },
        getBounds: function() { return bounds; }
    };
}

function makeBrush(state, rangeSpecified, initialRange, brushStartCallback, brushCallback, brushEndCallback) {
    var filter = makeFilter();
    filter.set(initialRange);
    return {
        filter: filter,
        filterSpecified: rangeSpecified, // there's a difference between not filtering and filtering a non-proper subset
        svgBrush: {
            extent: [], // this is where the svgBrush writes contents into
            brushStartCallback: brushStartCallback,
            brushCallback: axisBrushMoved(brushCallback),
            brushEndCallback: brushEndCallback
        }
    };
}

// for use by supplyDefaults, but it needed tons of pieces from here so
// seemed to make more sense just to put the whole routine here
function cleanRanges(ranges, dimension) {
    if(Array.isArray(ranges[0])) {
        ranges = ranges.map(function(ri) { return ri.sort(sortAsc); });

        if(!dimension.multiselect) ranges = [ranges[0]];
        else ranges = dedupeRealRanges(ranges.sort(startAsc));
    }
    else ranges = [ranges.sort(sortAsc)];

    // ordinal snapping
    if(dimension.tickvals) {
        var sortedTickVals = dimension.tickvals.slice().sort(sortAsc);
        ranges = ranges.map(function(ri) {
            var rSnapped = [
                ordinalScaleSnapLo(sortedTickVals, ri[0], []),
                ordinalScaleSnapHi(sortedTickVals, ri[1], [])
            ];
            if(rSnapped[1] > rSnapped[0]) return rSnapped;
        })
        .filter(function(ri) { return ri; });

        if(!ranges.length) return;
    }
    return ranges.length > 1 ? ranges : ranges[0];
}

module.exports = {
    makeBrush: makeBrush,
    ensureAxisBrush: ensureAxisBrush,
    cleanRanges: cleanRanges
};

},{"../../lib":694,"../../lib/gup":692,"./constants":1015,"d3":149}],1013:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var getModuleCalcData = _dereq_('../../plots/get_data').getModuleCalcData;
var parcoordsPlot = _dereq_('./plot');
var xmlnsNamespaces = _dereq_('../../constants/xmlns_namespaces');

var PARCOORDS = 'parcoords';

exports.name = PARCOORDS;

exports.plot = function(gd) {
    var calcData = getModuleCalcData(gd.calcdata, PARCOORDS)[0];
    if(calcData.length) parcoordsPlot(gd, calcData);
};

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var hadParcoords = (oldFullLayout._has && oldFullLayout._has(PARCOORDS));
    var hasParcoords = (newFullLayout._has && newFullLayout._has(PARCOORDS));

    if(hadParcoords && !hasParcoords) {
        oldFullLayout._paperdiv.selectAll('.parcoords').remove();
        oldFullLayout._glimages.selectAll('*').remove();
    }
};

exports.toSVG = function(gd) {
    var imageRoot = gd._fullLayout._glimages;
    var root = d3.select(gd).selectAll('.svg-container');
    var canvases = root.filter(function(d, i) {return i === root.size() - 1;})
        .selectAll('.gl-canvas-context, .gl-canvas-focus');

    function canvasToImage() {
        var canvas = this;
        var imageData = canvas.toDataURL('image/png');
        var image = imageRoot.append('svg:image');

        image.attr({
            xmlns: xmlnsNamespaces.svg,
            'xlink:href': imageData,
            preserveAspectRatio: 'none',
            x: 0,
            y: 0,
            width: canvas.width,
            height: canvas.height
        });
    }

    canvases.each(canvasToImage);

    // Chrome / Safari bug workaround - browser apparently loses connection to the defined pattern
    // Without the workaround, these browsers 'lose' the filter brush styling (color etc.) after a snapshot
    // on a subsequent interaction.
    // Firefox works fine without this workaround
    window.setTimeout(function() {
        d3.selectAll('#filterBarPattern')
            .attr('id', 'filterBarPattern');
    }, 60);
};

},{"../../constants/xmlns_namespaces":672,"../../plots/get_data":779,"./plot":1021,"d3":149}],1014:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
var calcColorscale = _dereq_('../../components/colorscale/calc');
var Lib = _dereq_('../../lib');
var wrap = _dereq_('../../lib/gup').wrap;

module.exports = function calc(gd, trace) {
    var cs = !!trace.line.colorscale && Lib.isArrayOrTypedArray(trace.line.color);
    var color = cs ? trace.line.color : constHalf(trace._length);
    var cscale = cs ? trace.line.colorscale : [[0, trace.line.color], [1, trace.line.color]];

    if(hasColorscale(trace, 'line')) {
        calcColorscale(gd, trace, {
            vals: color,
            containerStr: 'line',
            cLetter: 'c'
        });
    }

    return wrap({
        lineColor: color,
        cscale: cscale
    });
};

function constHalf(len) {
    var out = new Array(len);
    for(var i = 0; i < len; i++) {
        out[i] = 0.5;
    }
    return out;
}

},{"../../components/colorscale/calc":579,"../../components/colorscale/helpers":582,"../../lib":694,"../../lib/gup":692}],1015:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    maxDimensionCount: 60, // this cannot be increased without WebGL code refactoring
    overdrag: 45,
    verticalPadding: 2, // otherwise, horizontal lines on top or bottom are of lower width
    tickDistance: 50,
    canvasPixelRatio: 1,
    blockLineCount: 5000,
    layers: ['contextLineLayer', 'focusLineLayer', 'pickLineLayer'],
    axisTitleOffset: 28,
    axisExtentOffset: 10,
    bar: {
        width: 4, // Visible width of the filter bar
        captureWidth: 10, // Mouse-sensitive width for interaction (Fitts law)
        fillColor: 'magenta', // Color of the filter bar fill
        fillOpacity: 1, // Filter bar fill opacity
        snapDuration: 150, // tween duration in ms for brush snap for ordinal axes
        snapRatio: 0.25, // ratio of bar extension relative to the distance between two adjacent ordinal values
        snapClose: 0.01, // fraction of inter-value distance to snap to the closer one, even if you're not over it
        strokeColor: 'white', // Color of the filter bar side lines
        strokeOpacity: 1, // Filter bar side stroke opacity
        strokeWidth: 1, // Filter bar side stroke width in pixels
        handleHeight: 8, // Height of the filter bar vertical resize areas on top and bottom
        handleOpacity: 1, // Opacity of the filter bar vertical resize areas on top and bottom
        handleOverlap: 0 // A larger than 0 value causes overlaps with the filter bar, represented as pixels
    },
    cn: {
        axisExtentText: 'axis-extent-text',
        parcoordsLineLayers: 'parcoords-line-layers',
        parcoordsLineLayer: 'parcoords-lines',
        parcoords: 'parcoords',
        parcoordsControlView: 'parcoords-control-view',
        yAxis: 'y-axis',
        axisOverlays: 'axis-overlays',
        axis: 'axis',
        axisHeading: 'axis-heading',
        axisTitle: 'axis-title',
        axisExtent: 'axis-extent',
        axisExtentTop: 'axis-extent-top',
        axisExtentTopText: 'axis-extent-top-text',
        axisExtentBottom: 'axis-extent-bottom',
        axisExtentBottomText: 'axis-extent-bottom-text',
        axisBrush: 'axis-brush'
    },
    id: {
        filterBarPattern: 'filter-bar-pattern'

    }
};

},{}],1016:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
var handleDomainDefaults = _dereq_('../../plots/domain').defaults;
var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');

var attributes = _dereq_('./attributes');
var axisBrush = _dereq_('./axisbrush');
var maxDimensionCount = _dereq_('./constants').maxDimensionCount;
var mergeLength = _dereq_('./merge_length');

function handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce) {
    var lineColor = coerce('line.color', defaultColor);

    if(hasColorscale(traceIn, 'line') && Lib.isArrayOrTypedArray(lineColor)) {
        if(lineColor.length) {
            coerce('line.colorscale');
            colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'});
            // TODO: I think it would be better to keep showing lines beyond the last line color
            // but I'm not sure what color to give these lines - probably black or white
            // depending on the background color?
            return lineColor.length;
        }
        else {
            traceOut.line.color = defaultColor;
        }
    }
    return Infinity;
}

function dimensionDefaults(dimensionIn, dimensionOut) {
    function coerce(attr, dflt) {
        return Lib.coerce(dimensionIn, dimensionOut, attributes.dimensions, attr, dflt);
    }

    var values = coerce('values');
    var visible = coerce('visible');
    if(!(values && values.length)) {
        visible = dimensionOut.visible = false;
    }

    if(visible) {
        coerce('label');
        coerce('tickvals');
        coerce('ticktext');
        coerce('tickformat');
        coerce('range');

        coerce('multiselect');
        var constraintRange = coerce('constraintrange');
        if(constraintRange) {
            dimensionOut.constraintrange = axisBrush.cleanRanges(constraintRange, dimensionOut);
        }
    }
}

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var dimensionsIn = traceIn.dimensions;
    if(Array.isArray(dimensionsIn) && dimensionsIn.length > maxDimensionCount) {
        Lib.log('parcoords traces support up to ' + maxDimensionCount + ' dimensions at the moment');
        dimensionsIn.splice(maxDimensionCount);
    }

    var dimensions = handleArrayContainerDefaults(traceIn, traceOut, {
        name: 'dimensions',
        handleItemDefaults: dimensionDefaults
    });

    var len = handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);

    handleDomainDefaults(traceOut, layout, coerce);

    if(!Array.isArray(dimensions) || !dimensions.length) {
        traceOut.visible = false;
    }

    mergeLength(traceOut, dimensions, 'values', len);

    // make default font size 10px (default is 12),
    // scale linearly with global font size
    var fontDflt = {
        family: layout.font.family,
        size: Math.round(layout.font.size / 1.2),
        color: layout.font.color
    };

    Lib.coerceFont(coerce, 'labelfont', fontDflt);
    Lib.coerceFont(coerce, 'tickfont', fontDflt);
    Lib.coerceFont(coerce, 'rangefont', fontDflt);
};

},{"../../components/colorscale/defaults":581,"../../components/colorscale/helpers":582,"../../lib":694,"../../plots/array_container_defaults":738,"../../plots/domain":768,"./attributes":1011,"./axisbrush":1012,"./constants":1015,"./merge_length":1019}],1017:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Parcoords = {};

Parcoords.attributes = _dereq_('./attributes');
Parcoords.supplyDefaults = _dereq_('./defaults');
Parcoords.calc = _dereq_('./calc');
Parcoords.plot = _dereq_('./plot');
Parcoords.colorbar = {
    container: 'line',
    min: 'cmin',
    max: 'cmax'
};

Parcoords.moduleType = 'trace';
Parcoords.name = 'parcoords';
Parcoords.basePlotModule = _dereq_('./base_plot');
Parcoords.categories = ['gl', 'regl', 'noOpacity'];
Parcoords.meta = {
    
};

module.exports = Parcoords;

},{"./attributes":1011,"./base_plot":1013,"./calc":1014,"./defaults":1016,"./plot":1021}],1018:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var glslify = _dereq_('glslify');
var vertexShaderSource = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n               p4, p5, p6, p7,\n               p8, p9, pa, pb,\n               pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n             loA, hiA, loB, hiB, loC, hiC, loD, hiD;\n\nuniform vec2 resolution,\n             viewBoxPosition,\n             viewBoxSize;\n\nuniform sampler2D palette;\nuniform sampler2D mask;\nuniform float maskHeight;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec4 unit_1 = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n    return dot(matrixCompMult(p, v) * unit_1, unit_1);\n}\n\nfloat axisY(\n        float x,\n        mat4 d[4],\n        mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n    ) {\n\n    float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n    float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n    return y1 * (1.0 - x) + y2 * x;\n}\n\nconst int bitsPerByte = 8;\n\nint mod2(int a) {\n    return a - 2 * (a / 2);\n}\n\nint mod8(int a) {\n    return a - 8 * (a / 8);\n}\n\nvec4 zero = vec4(0, 0, 0, 0);\nvec4 unit_0 = vec4(1, 1, 1, 1);\nvec2 xyProjection = vec2(1, 1);\n\nmat4 mclamp(mat4 m, mat4 lo, mat4 hi) {\n    return mat4(clamp(m[0], lo[0], hi[0]),\n                clamp(m[1], lo[1], hi[1]),\n                clamp(m[2], lo[2], hi[2]),\n                clamp(m[3], lo[3], hi[3]));\n}\n\nbool mshow(mat4 p, mat4 lo, mat4 hi) {\n    return mclamp(p, lo, hi) == p;\n}\n\nbool withinBoundingBox(\n        mat4 d[4],\n        mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD\n    ) {\n\n    return mshow(d[0], loA, hiA) &&\n           mshow(d[1], loB, hiB) &&\n           mshow(d[2], loC, hiC) &&\n           mshow(d[3], loD, hiD);\n}\n\nbool withinRasterMask(mat4 d[4], sampler2D mask, float height) {\n    bool result = true;\n    int bitInByteStepper;\n    float valY, valueY, scaleX;\n    int hit, bitmask, valX;\n    for(int i = 0; i < 4; i++) {\n        for(int j = 0; j < 4; j++) {\n            for(int k = 0; k < 4; k++) {\n                bitInByteStepper = mod8(j * 4 + k);\n                valX = i * 2 + j / 2;\n                valY = d[i][j][k];\n                valueY = valY * (height - 1.0) + 0.5;\n                scaleX = (float(valX) + 0.5) / 8.0;\n                hit = int(texture2D(mask, vec2(scaleX, (valueY + 0.5) / height))[3] * 255.0) / int(pow(2.0, float(bitInByteStepper)));\n                result = result && mod2(hit) == 1;\n            }\n        }\n    }\n    return result;\n}\n\nvec4 position(\n        float depth,\n        vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n        mat4 dims[4],\n        float signum,\n        mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D,\n        mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD,\n        sampler2D mask, float maskHeight\n    ) {\n\n    float x = 0.5 * signum + 0.5;\n    float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n    float show = float(\n                            withinBoundingBox(dims, loA, hiA, loB, hiB, loC, hiC, loD, hiD)\n                         && withinRasterMask(dims, mask, maskHeight)\n                      );\n\n    vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n    float depthOrHide = depth + 2.0 * (1.0 - show);\n\n    return vec4(\n        xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n        depthOrHide,\n        1.0\n    );\n}\n\nvoid main() {\n\n    float prominence = abs(pf[3]);\n\n    mat4 p[4];\n    p[0] = mat4(p0, p1, p2, p3);\n    p[1] = mat4(p4, p5, p6, p7);\n    p[2] = mat4(p8, p9, pa, pb);\n    p[3] = mat4(pc, pd, pe, abs(pf));\n\n    gl_Position = position(\n        1.0 - prominence,\n        resolution, viewBoxPosition, viewBoxSize,\n        p,\n        sign(pf[3]),\n        dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n        loA, hiA, loB, hiB, loC, hiC, loD, hiD,\n        mask, maskHeight\n    );\n\n    float clampedColorIndex = clamp((prominence - colorClamp[0]) / (colorClamp[1] - colorClamp[0]), 0.0, 1.0);\n    fragColor = texture2D(palette, vec2((clampedColorIndex * 255.0 + 0.5) / 256.0, 0.5));\n}\n"]);
var contextShaderSource = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n               p4, p5, p6, p7,\n               p8, p9, pa, pb,\n               pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D;\n\nuniform vec2 resolution,\n             viewBoxPosition,\n             viewBoxSize;\n\nuniform sampler2D palette;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec2 xyProjection = vec2(1, 1);\n\nvec4 unit = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n    return dot(matrixCompMult(p, v) * unit, unit);\n}\n\nfloat axisY(\n        float x,\n        mat4 d[4],\n        mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n    ) {\n\n    float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n    float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n    return y1 * (1.0 - x) + y2 * x;\n}\n\nvec4 position(\n        float depth,\n        vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n        mat4 dims[4],\n        float signum,\n        mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n    ) {\n\n    float x = 0.5 * signum + 0.5;\n    float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n    vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n\n    return vec4(\n        xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n        depth,\n        1.0\n    );\n}\n\nvoid main() {\n\n    float prominence = abs(pf[3]);\n\n    mat4 p[4];\n    p[0] = mat4(p0, p1, p2, p3);\n    p[1] = mat4(p4, p5, p6, p7);\n    p[2] = mat4(p8, p9, pa, pb);\n    p[3] = mat4(pc, pd, pe, abs(pf));\n\n    gl_Position = position(\n        1.0 - prominence,\n        resolution, viewBoxPosition, viewBoxSize,\n        p,\n        sign(pf[3]),\n        dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D\n    );\n\n    float clampedColorIndex = clamp((prominence - colorClamp[0]) / (colorClamp[1] - colorClamp[0]), 0.0, 1.0);\n    fragColor = texture2D(palette, vec2((clampedColorIndex * 255.0 + 0.5) / 256.0, 0.5));\n}\n"]);
var pickVertexShaderSource = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n               p4, p5, p6, p7,\n               p8, p9, pa, pb,\n               pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n             loA, hiA, loB, hiB, loC, hiC, loD, hiD;\n\nuniform vec2 resolution,\n             viewBoxPosition,\n             viewBoxSize;\n\nuniform sampler2D mask;\nuniform float maskHeight;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec4 unit_1 = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n    return dot(matrixCompMult(p, v) * unit_1, unit_1);\n}\n\nfloat axisY(\n        float x,\n        mat4 d[4],\n        mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n    ) {\n\n    float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n    float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n    return y1 * (1.0 - x) + y2 * x;\n}\n\nconst int bitsPerByte = 8;\n\nint mod2(int a) {\n    return a - 2 * (a / 2);\n}\n\nint mod8(int a) {\n    return a - 8 * (a / 8);\n}\n\nvec4 zero = vec4(0, 0, 0, 0);\nvec4 unit_0 = vec4(1, 1, 1, 1);\nvec2 xyProjection = vec2(1, 1);\n\nmat4 mclamp(mat4 m, mat4 lo, mat4 hi) {\n    return mat4(clamp(m[0], lo[0], hi[0]),\n                clamp(m[1], lo[1], hi[1]),\n                clamp(m[2], lo[2], hi[2]),\n                clamp(m[3], lo[3], hi[3]));\n}\n\nbool mshow(mat4 p, mat4 lo, mat4 hi) {\n    return mclamp(p, lo, hi) == p;\n}\n\nbool withinBoundingBox(\n        mat4 d[4],\n        mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD\n    ) {\n\n    return mshow(d[0], loA, hiA) &&\n           mshow(d[1], loB, hiB) &&\n           mshow(d[2], loC, hiC) &&\n           mshow(d[3], loD, hiD);\n}\n\nbool withinRasterMask(mat4 d[4], sampler2D mask, float height) {\n    bool result = true;\n    int bitInByteStepper;\n    float valY, valueY, scaleX;\n    int hit, bitmask, valX;\n    for(int i = 0; i < 4; i++) {\n        for(int j = 0; j < 4; j++) {\n            for(int k = 0; k < 4; k++) {\n                bitInByteStepper = mod8(j * 4 + k);\n                valX = i * 2 + j / 2;\n                valY = d[i][j][k];\n                valueY = valY * (height - 1.0) + 0.5;\n                scaleX = (float(valX) + 0.5) / 8.0;\n                hit = int(texture2D(mask, vec2(scaleX, (valueY + 0.5) / height))[3] * 255.0) / int(pow(2.0, float(bitInByteStepper)));\n                result = result && mod2(hit) == 1;\n            }\n        }\n    }\n    return result;\n}\n\nvec4 position(\n        float depth,\n        vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n        mat4 dims[4],\n        float signum,\n        mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D,\n        mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD,\n        sampler2D mask, float maskHeight\n    ) {\n\n    float x = 0.5 * signum + 0.5;\n    float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n    float show = float(\n                            withinBoundingBox(dims, loA, hiA, loB, hiB, loC, hiC, loD, hiD)\n                         && withinRasterMask(dims, mask, maskHeight)\n                      );\n\n    vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n    float depthOrHide = depth + 2.0 * (1.0 - show);\n\n    return vec4(\n        xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n        depthOrHide,\n        1.0\n    );\n}\n\nvoid main() {\n\n    float prominence = abs(pf[3]);\n\n    mat4 p[4];\n    p[0] = mat4(p0, p1, p2, p3);\n    p[1] = mat4(p4, p5, p6, p7);\n    p[2] = mat4(p8, p9, pa, pb);\n    p[3] = mat4(pc, pd, pe, abs(pf));\n\n    gl_Position = position(\n        1.0 - prominence,\n        resolution, viewBoxPosition, viewBoxSize,\n        p,\n        sign(pf[3]),\n        dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n        loA, hiA, loB, hiB, loC, hiC, loD, hiD,\n        mask, maskHeight\n    );\n\n    fragColor = vec4(pf.rgb, 1.0);\n}\n"]);
var fragmentShaderSource = glslify(["precision lowp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n    gl_FragColor = fragColor;\n}\n"]);

var Lib = _dereq_('../../lib');

// don't change; otherwise near/far plane lines are lost
var depthLimitEpsilon = 1e-6;
// just enough buffer for an extra bit at single-precision floating point
// which on [0, 1] is 6e-8 (1/2^24)
var filterEpsilon = 1e-7;

// precision of multiselect is the full range divided into this many parts
var maskHeight = 2048;

var gpuDimensionCount = 64;
var sectionVertexCount = 2;
var vec4NumberCount = 4;
var bitsPerByte = 8;
var channelCount = gpuDimensionCount / bitsPerByte; // == 8 bytes needed to have 64 bits

var contextColor = [119, 119, 119]; // middle gray to not drawn the focus; looks good on a black or white background

var dummyPixel = new Uint8Array(4);
var pickPixel = new Uint8Array(4);

var paletteTextureConfig = {
    shape: [256, 1],
    format: 'rgba',
    type: 'uint8',
    mag: 'nearest',
    min: 'nearest'
};

function ensureDraw(regl) {
    regl.read({
        x: 0,
        y: 0,
        width: 1,
        height: 1,
        data: dummyPixel
    });
}

function clear(regl, x, y, width, height) {
    var gl = regl._gl;
    gl.enable(gl.SCISSOR_TEST);
    gl.scissor(x, y, width, height);
    regl.clear({color: [0, 0, 0, 0], depth: 1}); // clearing is done in scissored panel only
}

function renderBlock(regl, glAes, renderState, blockLineCount, sampleCount, item) {

    var rafKey = item.key;

    function render(blockNumber) {

        var count;

        count = Math.min(blockLineCount, sampleCount - blockNumber * blockLineCount);

        item.offset = sectionVertexCount * blockNumber * blockLineCount;
        item.count = sectionVertexCount * count;
        if(blockNumber === 0) {
            // stop drawing possibly stale glyphs before clearing
            window.cancelAnimationFrame(renderState.currentRafs[rafKey]);
            delete renderState.currentRafs[rafKey];
            clear(regl, item.scissorX, item.scissorY, item.scissorWidth, item.viewBoxSize[1]);
        }

        if(renderState.clearOnly) {
            return;
        }

        glAes(item);

        if(blockNumber * blockLineCount + count < sampleCount) {
            renderState.currentRafs[rafKey] = window.requestAnimationFrame(function() {
                render(blockNumber + 1);
            });
        }

        renderState.drawCompleted = false;
    }

    if(!renderState.drawCompleted) {
        ensureDraw(regl);
        renderState.drawCompleted = true;
    }

    // start with rendering item 0; recursion handles the rest
    render(0);
}

function adjustDepth(d) {
    // WebGL matrix operations use floats with limited precision, potentially causing a number near a border of [0, 1]
    // to end up slightly outside the border. With an epsilon, we reduce the chance that a line gets clipped by the
    // near or the far plane.
    return Math.max(depthLimitEpsilon, Math.min(1 - depthLimitEpsilon, d));
}

function palette(unitToColor, context, opacity) {
    var result = [];
    for(var j = 0; j < 256; j++) {
        var c = unitToColor(j / 255);
        result.push((context ? contextColor : c).concat(opacity));
    }

    return result;
}

// Maps the sample index [0...sampleCount - 1] to a range of [0, 1] as the shader expects colors in the [0, 1] range.
// but first it shifts the sample index by 0, 8 or 16 bits depending on rgbIndex [0..2]
// with the end result that each line will be of a unique color, making it possible for the pick handler
// to uniquely identify which line is hovered over (bijective mapping).
// The inverse, i.e. readPixel is invoked from 'parcoords.js'
function calcPickColor(j, rgbIndex) {
    return (j >>> 8 * rgbIndex) % 256 / 255;
}

function makePoints(sampleCount, dimensions, color) {
    var dimensionCount = dimensions.length;

    var points = [];
    for(var j = 0; j < sampleCount; j++) {
        for(var i = 0; i < gpuDimensionCount; i++) {
            points.push(i < dimensionCount ?
                dimensions[i].paddedUnitValues[j] :
                i === (gpuDimensionCount - 1) ?
                    adjustDepth(color[j]) :
                    i >= gpuDimensionCount - 4 ?
                        calcPickColor(j, gpuDimensionCount - 2 - i) :
                        0.5);
        }
    }

    return points;
}

function makeVecAttr(sampleCount, points, vecIndex) {
    var i, j, k;
    var pointPairs = [];

    for(j = 0; j < sampleCount; j++) {
        for(k = 0; k < sectionVertexCount; k++) {
            for(i = 0; i < vec4NumberCount; i++) {
                pointPairs.push(points[j * gpuDimensionCount + vecIndex * vec4NumberCount + i]);
                if(vecIndex * vec4NumberCount + i === gpuDimensionCount - 1 && k % 2 === 0) {
                    pointPairs[pointPairs.length - 1] *= -1;
                }
            }
        }
    }

    return pointPairs;
}

function setAttributes(attributes, sampleCount, points) {
    for(var i = 0; i < 16; i++) {
        attributes['p' + i.toString(16)](makeVecAttr(sampleCount, points, i));
    }
}

function emptyAttributes(regl) {
    var attributes = {};
    for(var i = 0; i < 16; i++) {
        attributes['p' + i.toString(16)] = regl.buffer({usage: 'dynamic', type: 'float', data: new Uint8Array(0)});
    }
    return attributes;
}

module.exports = function(canvasGL, d) {
    // context & pick describe which canvas we're talking about - won't change with new data
    var context = d.context;
    var pick = d.pick;

    var regl = d.regl;

    var renderState = {
        currentRafs: {},
        drawCompleted: true,
        clearOnly: false
    };

    // state to be set by update and used later
    var model;
    var vm;
    var initialDims;
    var sampleCount;
    var attributes = emptyAttributes(regl);
    var maskTexture;
    var paletteTexture = regl.texture(paletteTextureConfig);

    update(d);

    var glAes = regl({

        profile: false,

        blend: {
            enable: context,
            func: {
                srcRGB: 'src alpha',
                dstRGB: 'one minus src alpha',
                srcAlpha: 1,
                dstAlpha: 1 // 'one minus src alpha'
            },
            equation: {
                rgb: 'add',
                alpha: 'add'
            },
            color: [0, 0, 0, 0]
        },

        depth: {
            enable: !context,
            mask: true,
            func: 'less',
            range: [0, 1]
        },

        // for polygons
        cull: {
            enable: true,
            face: 'back'
        },

        scissor: {
            enable: true,
            box: {
                x: regl.prop('scissorX'),
                y: regl.prop('scissorY'),
                width: regl.prop('scissorWidth'),
                height: regl.prop('scissorHeight')
            }
        },

        viewport: {
            x: regl.prop('viewportX'),
            y: regl.prop('viewportY'),
            width: regl.prop('viewportWidth'),
            height: regl.prop('viewportHeight')
        },

        dither: false,

        vert: pick ? pickVertexShaderSource : context ? contextShaderSource : vertexShaderSource,

        frag: fragmentShaderSource,

        primitive: 'lines',
        lineWidth: 1,
        attributes: attributes,
        uniforms: {
            resolution: regl.prop('resolution'),
            viewBoxPosition: regl.prop('viewBoxPosition'),
            viewBoxSize: regl.prop('viewBoxSize'),
            dim1A: regl.prop('dim1A'),
            dim2A: regl.prop('dim2A'),
            dim1B: regl.prop('dim1B'),
            dim2B: regl.prop('dim2B'),
            dim1C: regl.prop('dim1C'),
            dim2C: regl.prop('dim2C'),
            dim1D: regl.prop('dim1D'),
            dim2D: regl.prop('dim2D'),
            loA: regl.prop('loA'),
            hiA: regl.prop('hiA'),
            loB: regl.prop('loB'),
            hiB: regl.prop('hiB'),
            loC: regl.prop('loC'),
            hiC: regl.prop('hiC'),
            loD: regl.prop('loD'),
            hiD: regl.prop('hiD'),
            palette: paletteTexture,
            mask: regl.prop('maskTexture'),
            maskHeight: regl.prop('maskHeight'),
            colorClamp: regl.prop('colorClamp')
        },
        offset: regl.prop('offset'),
        count: regl.prop('count')
    });

    function update(dNew) {
        model = dNew.model;
        vm = dNew.viewModel;
        initialDims = vm.dimensions.slice();
        sampleCount = initialDims[0] ? initialDims[0].values.length : 0;

        var lines = model.lines;
        var color = pick ? lines.color.map(function(_, i) {return i / lines.color.length;}) : lines.color;
        var contextOpacity = Math.max(1 / 255, Math.pow(1 / color.length, 1 / 3));

        var points = makePoints(sampleCount, initialDims, color);
        setAttributes(attributes, sampleCount, points);

        paletteTexture = regl.texture(Lib.extendFlat({
            data: palette(model.unitToColor, context, Math.round((context ? contextOpacity : 1) * 255))
        }, paletteTextureConfig));
    }

    var colorClamp = [0, 1];

    function setColorDomain(unitDomain) {
        colorClamp[0] = unitDomain[0];
        colorClamp[1] = unitDomain[1];
    }

    var previousAxisOrder = [];

    function makeItem(i, ii, x, y, panelSizeX, canvasPanelSizeY, crossfilterDimensionIndex, I, leftmost, rightmost, constraints) {
        var loHi, abcd, d, index;
        var leftRight = [i, ii];

        var dims = [0, 1].map(function() {return [0, 1, 2, 3].map(function() {return new Float32Array(16);});});

        for(loHi = 0; loHi < 2; loHi++) {
            index = leftRight[loHi];
            for(abcd = 0; abcd < 4; abcd++) {
                for(d = 0; d < 16; d++) {
                    dims[loHi][abcd][d] = d + 16 * abcd === index ? 1 : 0;
                }
            }
        }

        var overdrag = model.lines.canvasOverdrag;
        var domain = model.domain;
        var canvasWidth = model.canvasWidth;
        var canvasHeight = model.canvasHeight;

        var itemModel = Lib.extendFlat({
            key: crossfilterDimensionIndex,
            resolution: [canvasWidth, canvasHeight],
            viewBoxPosition: [x + overdrag, y],
            viewBoxSize: [panelSizeX, canvasPanelSizeY],
            i: i,
            ii: ii,

            dim1A: dims[0][0],
            dim1B: dims[0][1],
            dim1C: dims[0][2],
            dim1D: dims[0][3],
            dim2A: dims[1][0],
            dim2B: dims[1][1],
            dim2C: dims[1][2],
            dim2D: dims[1][3],

            colorClamp: colorClamp,

            scissorX: (I === leftmost ? 0 : x + overdrag) + (model.pad.l - overdrag) + model.layoutWidth * domain.x[0],
            scissorWidth: (I === rightmost ? canvasWidth - x + overdrag : panelSizeX + 0.5) + (I === leftmost ? x + overdrag : 0),
            scissorY: y + model.pad.b + model.layoutHeight * domain.y[0],
            scissorHeight: canvasPanelSizeY,

            viewportX: model.pad.l - overdrag + model.layoutWidth * domain.x[0],
            viewportY: model.pad.b + model.layoutHeight * domain.y[0],
            viewportWidth: canvasWidth,
            viewportHeight: canvasHeight
        }, constraints);

        return itemModel;
    }

    function makeConstraints() {
        var loHi, abcd, d;

        var lims = [0, 1].map(function() {return [0, 1, 2, 3].map(function() {return new Float32Array(16);});});

        for(loHi = 0; loHi < 2; loHi++) {
            for(abcd = 0; abcd < 4; abcd++) {
                for(d = 0; d < 16; d++) {
                    var dimP = d + 16 * abcd;
                    var lim;
                    if(dimP < initialDims.length) {
                        lim = initialDims[dimP].brush.filter.getBounds()[loHi];
                    }
                    else lim = loHi;
                    lims[loHi][abcd][d] = lim + (2 * loHi - 1) * filterEpsilon;
                }
            }
        }

        function expandedPixelRange(dim, bounds) {
            var maskHMinus = maskHeight - 1;
            return [
                Math.max(0, Math.floor(bounds[0] * maskHMinus)),
                Math.min(maskHMinus, Math.ceil(bounds[1] * maskHMinus))
            ];
        }

        var mask = Array.apply(null, new Array(maskHeight * channelCount)).map(function() {
            return 255;
        });
        for(var dimIndex = 0; dimIndex < initialDims.length; dimIndex++) {
            var bitIndex = dimIndex % bitsPerByte;
            var byteIndex = (dimIndex - bitIndex) / bitsPerByte;
            var bitMask = Math.pow(2, bitIndex);
            var dim = initialDims[dimIndex];
            var ranges = dim.brush.filter.get();
            if(ranges.length < 2) continue; // bail if the bounding box based filter is sufficient

            var prevEnd = expandedPixelRange(dim, ranges[0])[1];
            for(var ri = 1; ri < ranges.length; ri++) {
                var nextRange = expandedPixelRange(dim, ranges[ri]);
                for(var pi = prevEnd + 1; pi < nextRange[0]; pi++) {
                    mask[pi * channelCount + byteIndex] &= ~bitMask;
                }
                prevEnd = Math.max(prevEnd, nextRange[1]);
            }
        }

        var textureData = {
            // 8 units x 8 bits = 64 bits, just sufficient for the almost 64 dimensions we support
            shape: [channelCount, maskHeight],
            format: 'alpha',
            type: 'uint8',
            mag: 'nearest',
            min: 'nearest',
            data: mask
        };
        if(maskTexture) maskTexture(textureData);
        else maskTexture = regl.texture(textureData);

        return {
            maskTexture: maskTexture,
            maskHeight: maskHeight,
            loA: lims[0][0],
            loB: lims[0][1],
            loC: lims[0][2],
            loD: lims[0][3],
            hiA: lims[1][0],
            hiB: lims[1][1],
            hiC: lims[1][2],
            hiD: lims[1][3]
        };
    }

    function renderGLParcoords(panels, setChanged, clearOnly) {
        var panelCount = panels.length;
        var I;

        var leftmost;
        var rightmost;
        var lowestX = Infinity;
        var highestX = -Infinity;

        for(I = 0; I < panelCount; I++) {
            if(panels[I].dim2.canvasX > highestX) {
                highestX = panels[I].dim2.canvasX;
                rightmost = I;
            }
            if(panels[I].dim1.canvasX < lowestX) {
                lowestX = panels[I].dim1.canvasX;
                leftmost = I;
            }
        }

        if(panelCount === 0) {
            // clear canvas here, as the panel iteration below will not enter the loop body
            clear(regl, 0, 0, model.canvasWidth, model.canvasHeight);
        }
        var constraints = context ? {} : makeConstraints();

        for(I = 0; I < panelCount; I++) {
            var panel = panels[I];
            var dim1 = panel.dim1;
            var i = dim1.crossfilterDimensionIndex;
            var x = panel.canvasX;
            var y = panel.canvasY;
            var dim2 = panel.dim2;
            var ii = dim2.crossfilterDimensionIndex;
            var panelSizeX = panel.panelSizeX;
            var panelSizeY = panel.panelSizeY;
            var xTo = x + panelSizeX;
            if(setChanged || !previousAxisOrder[i] || previousAxisOrder[i][0] !== x || previousAxisOrder[i][1] !== xTo) {
                previousAxisOrder[i] = [x, xTo];
                var item = makeItem(i, ii, x, y, panelSizeX, panelSizeY, dim1.crossfilterDimensionIndex, I, leftmost, rightmost, constraints);
                renderState.clearOnly = clearOnly;
                renderBlock(regl, glAes, renderState, setChanged ? model.lines.blockLineCount : sampleCount, sampleCount, item);
            }
        }
    }

    function readPixel(canvasX, canvasY) {
        regl.read({
            x: canvasX,
            y: canvasY,
            width: 1,
            height: 1,
            data: pickPixel
        });
        return pickPixel;
    }

    function readPixels(canvasX, canvasY, width, height) {
        var pixelArray = new Uint8Array(4 * width * height);
        regl.read({
            x: canvasX,
            y: canvasY,
            width: width,
            height: height,
            data: pixelArray
        });
        return pixelArray;
    }

    function destroy() {
        canvasGL.style['pointer-events'] = 'none';
        paletteTexture.destroy();
        if(maskTexture) maskTexture.destroy();
        for(var k in attributes) attributes[k].destroy();
    }

    return {
        setColorDomain: setColorDomain,
        render: renderGLParcoords,
        readPixel: readPixel,
        readPixels: readPixels,
        destroy: destroy,
        update: update
    };
};

},{"../../lib":694,"glslify":395}],1019:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * mergeLength: set trace length as the minimum of all dimension data lengths
 *     and propagates this length into each dimension
 *
 * @param {object} traceOut: the fullData trace
 * @param {Array(object)} dimensions: array of dimension objects
 * @param {string} dataAttr: the attribute of each dimension containing the data
 * @param {integer} len: an already-existing length from other attributes
 */
module.exports = function(traceOut, dimensions, dataAttr, len) {
    if(!len) len = Infinity;
    var i, dimi;
    for(i = 0; i < dimensions.length; i++) {
        dimi = dimensions[i];
        if(dimi.visible) len = Math.min(len, dimi[dataAttr].length);
    }
    if(len === Infinity) len = 0;

    traceOut._length = len;
    for(i = 0; i < dimensions.length; i++) {
        dimi = dimensions[i];
        if(dimi.visible) dimi._length = len;
    }

    return len;
};

},{}],1020:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Lib = _dereq_('../../lib');
var Drawing = _dereq_('../../components/drawing');
var Colorscale = _dereq_('../../components/colorscale');

var gup = _dereq_('../../lib/gup');
var keyFun = gup.keyFun;
var repeat = gup.repeat;
var unwrap = gup.unwrap;

var c = _dereq_('./constants');
var brush = _dereq_('./axisbrush');
var lineLayerMaker = _dereq_('./lines');

function visible(dimension) { return !('visible' in dimension) || dimension.visible; }

function dimensionExtent(dimension) {

    var lo = dimension.range ? dimension.range[0] : Lib.aggNums(Math.min, null, dimension.values, dimension._length);
    var hi = dimension.range ? dimension.range[1] : Lib.aggNums(Math.max, null, dimension.values, dimension._length);

    if(isNaN(lo) || !isFinite(lo)) {
        lo = 0;
    }

    if(isNaN(hi) || !isFinite(hi)) {
        hi = 0;
    }

    // avoid a degenerate (zero-width) domain
    if(lo === hi) {
        if(lo === 0) {
            // no use to multiplying zero, so add/subtract in this case
            lo -= 1;
            hi += 1;
        } else {
            // this keeps the range in the order of magnitude of the data
            lo *= 0.9;
            hi *= 1.1;
        }
    }

    return [lo, hi];
}

function toText(formatter, texts) {
    if(texts) {
        return function(v, i) {
            var text = texts[i];
            if(text === null || text === undefined) return formatter(v);
            return text;
        };
    }
    return formatter;
}

function domainScale(height, padding, dimension, tickvals, ticktext) {
    var extent = dimensionExtent(dimension);
    if(tickvals) {
        return d3.scale.ordinal()
            .domain(tickvals.map(toText(d3.format(dimension.tickformat), ticktext)))
            .range(tickvals
                .map(function(d) {
                    var unitVal = (d - extent[0]) / (extent[1] - extent[0]);
                    return (height - padding + unitVal * (2 * padding - height));
                })
            );
    }
    return d3.scale.linear()
        .domain(extent)
        .range([height - padding, padding]);
}

function unitToPaddedPx(height, padding) { return d3.scale.linear().range([padding, height - padding]); }

function domainToPaddedUnitScale(dimension, padFraction) {
    return d3.scale.linear()
        .domain(dimensionExtent(dimension))
        .range([padFraction, 1 - padFraction]);
}

function ordinalScale(dimension) {
    if(!dimension.tickvals) return;

    var extent = dimensionExtent(dimension);
    return d3.scale.ordinal()
        .domain(dimension.tickvals)
        .range(dimension.tickvals.map(function(d) {
            return (d - extent[0]) / (extent[1] - extent[0]);
        }));
}

function unitToColorScale(cscale) {

    var colorStops = cscale.map(function(d) { return d[0]; });
    var colorTuples = cscale.map(function(d) { return d3.rgb(d[1]); });
    var prop = function(n) { return function(o) { return o[n]; }; };

    // We can't use d3 color interpolation as we may have non-uniform color palette raster
    // (various color stop distances).
    var polylinearUnitScales = 'rgb'.split('').map(function(key) {
        return d3.scale.linear()
            .clamp(true)
            .domain(colorStops)
            .range(colorTuples.map(prop(key)));
    });

    return function(d) {
        return polylinearUnitScales.map(function(s) {
            return s(d);
        });
    };
}

function someFiltersActive(view) {
    return view.dimensions.some(function(p) {
        return p.brush.filterSpecified;
    });
}

function model(layout, d, i) {
    var cd0 = unwrap(d);
    var trace = cd0.trace;
    var lineColor = cd0.lineColor;
    var line = trace.line;
    var cscale = line.reversescale ? Colorscale.flipScale(cd0.cscale) : cd0.cscale;
    var domain = trace.domain;
    var dimensions = trace.dimensions;
    var width = layout.width;
    var labelFont = trace.labelfont;
    var tickFont = trace.tickfont;
    var rangeFont = trace.rangefont;

    var lines = Lib.extendDeepNoArrays({}, line, {
        color: lineColor.map(d3.scale.linear().domain(dimensionExtent({
            values: lineColor,
            range: [line.cmin, line.cmax],
            _length: trace._length
        }))),
        blockLineCount: c.blockLineCount,
        canvasOverdrag: c.overdrag * c.canvasPixelRatio
    });

    var groupWidth = Math.floor(width * (domain.x[1] - domain.x[0]));
    var groupHeight = Math.floor(layout.height * (domain.y[1] - domain.y[0]));

    var pad = layout.margin || {l: 80, r: 80, t: 100, b: 80};
    var rowContentWidth = groupWidth;
    var rowHeight = groupHeight;

    return {
        key: i,
        colCount: dimensions.filter(visible).length,
        dimensions: dimensions,
        tickDistance: c.tickDistance,
        unitToColor: unitToColorScale(cscale),
        lines: lines,
        labelFont: labelFont,
        tickFont: tickFont,
        rangeFont: rangeFont,
        layoutWidth: width,
        layoutHeight: layout.height,
        domain: domain,
        translateX: domain.x[0] * width,
        translateY: layout.height - domain.y[1] * layout.height,
        pad: pad,
        canvasWidth: rowContentWidth * c.canvasPixelRatio + 2 * lines.canvasOverdrag,
        canvasHeight: rowHeight * c.canvasPixelRatio,
        width: rowContentWidth,
        height: rowHeight,
        canvasPixelRatio: c.canvasPixelRatio
    };
}

function viewModel(state, callbacks, model) {

    var width = model.width;
    var height = model.height;
    var dimensions = model.dimensions;
    var canvasPixelRatio = model.canvasPixelRatio;

    var xScale = function(d) {return width * d / Math.max(1, model.colCount - 1);};

    var unitPad = c.verticalPadding / height;
    var _unitToPaddedPx = unitToPaddedPx(height, c.verticalPadding);

    var viewModel = {
        key: model.key,
        xScale: xScale,
        model: model,
        inBrushDrag: false // consider factoring it out and putting it in a centralized global-ish gesture state object
    };

    var uniqueKeys = {};

    viewModel.dimensions = dimensions.filter(visible).map(function(dimension, i) {
        var domainToPaddedUnit = domainToPaddedUnitScale(dimension, unitPad);
        var foundKey = uniqueKeys[dimension.label];
        uniqueKeys[dimension.label] = (foundKey || 0) + 1;
        var key = dimension.label + (foundKey ? '__' + foundKey : '');
        var specifiedConstraint = dimension.constraintrange;
        var filterRangeSpecified = specifiedConstraint && specifiedConstraint.length;
        if(filterRangeSpecified && !Array.isArray(specifiedConstraint[0])) {
            specifiedConstraint = [specifiedConstraint];
        }
        var filterRange = filterRangeSpecified ?
            specifiedConstraint.map(function(d) { return d.map(domainToPaddedUnit); }) :
            [[0, 1]];
        var brushMove = function() {
            var p = viewModel;
            p.focusLayer && p.focusLayer.render(p.panels, true);
            var filtersActive = someFiltersActive(p);
            if(!state.contextShown() && filtersActive) {
                p.contextLayer && p.contextLayer.render(p.panels, true);
                state.contextShown(true);
            } else if(state.contextShown() && !filtersActive) {
                p.contextLayer && p.contextLayer.render(p.panels, true, true);
                state.contextShown(false);
            }
        };

        var truncatedValues = dimension.values;
        if(truncatedValues.length > dimension._length) {
            truncatedValues = truncatedValues.slice(0, dimension._length);
        }

        var tickvals = dimension.tickvals;
        var ticktext;
        function makeTickItem(v, i) { return {val: v, text: ticktext[i]}; }
        function sortTickItem(a, b) { return a.val - b.val; }
        if(Array.isArray(tickvals) && tickvals.length) {
            ticktext = dimension.ticktext;

            // ensure ticktext and tickvals have same length
            if(!Array.isArray(ticktext) || !ticktext.length) {
                ticktext = tickvals.map(d3.format(dimension.tickformat));
            }
            else if(ticktext.length > tickvals.length) {
                ticktext = ticktext.slice(0, tickvals.length);
            }
            else if(tickvals.length > ticktext.length) {
                tickvals = tickvals.slice(0, ticktext.length);
            }

            // check if we need to sort tickvals/ticktext
            for(var j = 1; j < tickvals.length; j++) {
                if(tickvals[j] < tickvals[j - 1]) {
                    var tickItems = tickvals.map(makeTickItem).sort(sortTickItem);
                    for(var k = 0; k < tickvals.length; k++) {
                        tickvals[k] = tickItems[k].val;
                        ticktext[k] = tickItems[k].text;
                    }
                    break;
                }
            }
        }
        else tickvals = undefined;

        return {
            key: key,
            label: dimension.label,
            tickFormat: dimension.tickformat,
            tickvals: tickvals,
            ticktext: ticktext,
            ordinal: !!tickvals,
            multiselect: dimension.multiselect,
            xIndex: i,
            crossfilterDimensionIndex: i,
            visibleIndex: dimension._index,
            height: height,
            values: truncatedValues,
            paddedUnitValues: truncatedValues.map(domainToPaddedUnit),
            unitTickvals: tickvals && tickvals.map(domainToPaddedUnit),
            xScale: xScale,
            x: xScale(i),
            canvasX: xScale(i) * canvasPixelRatio,
            unitToPaddedPx: _unitToPaddedPx,
            domainScale: domainScale(height, c.verticalPadding, dimension, tickvals, ticktext),
            ordinalScale: ordinalScale(dimension),
            parent: viewModel,
            model: model,
            brush: brush.makeBrush(
                state,
                filterRangeSpecified,
                filterRange,
                function() {
                    state.linePickActive(false);
                },
                brushMove,
                function(f) {
                    var p = viewModel;
                    p.focusLayer.render(p.panels, true);
                    p.pickLayer && p.pickLayer.render(p.panels, true);
                    state.linePickActive(true);
                    if(callbacks && callbacks.filterChanged) {
                        var invScale = domainToPaddedUnit.invert;

                        // update gd.data as if a Plotly.restyle were fired
                        var newRanges = f.map(function(r) {
                            return r.map(invScale).sort(Lib.sorterAsc);
                        }).sort(function(a, b) { return a[0] - b[0]; });
                        callbacks.filterChanged(p.key, dimension._index, newRanges);
                    }
                }
            )
        };
    });

    return viewModel;
}

function styleExtentTexts(selection) {
    selection
        .classed(c.cn.axisExtentText, true)
        .attr('text-anchor', 'middle')
        .style('cursor', 'default')
        .style('user-select', 'none');
}

function parcoordsInteractionState() {
    var linePickActive = true;
    var contextShown = false;
    return {
        linePickActive: function(val) {return arguments.length ? linePickActive = !!val : linePickActive;},
        contextShown: function(val) {return arguments.length ? contextShown = !!val : contextShown;}
    };
}

module.exports = function(root, svg, parcoordsLineLayers, styledData, layout, callbacks) {

    var state = parcoordsInteractionState();

    var vm = styledData
        .filter(function(d) { return unwrap(d).trace.visible; })
        .map(model.bind(0, layout))
        .map(viewModel.bind(0, state, callbacks));

    parcoordsLineLayers.each(function(d, i) {
        return Lib.extendFlat(d, vm[i]);
    });

    var parcoordsLineLayer = parcoordsLineLayers.selectAll('.gl-canvas')
        .each(function(d) {
            // FIXME: figure out how to handle multiple instances
            d.viewModel = vm[0];
            d.model = d.viewModel ? d.viewModel.model : null;
        });

    var lastHovered = null;

    var pickLayer = parcoordsLineLayer.filter(function(d) {return d.pick;});

    // emit hover / unhover event
    pickLayer
        .style('pointer-events', 'auto')
        .on('mousemove', function(d) {
            if(state.linePickActive() && d.lineLayer && callbacks && callbacks.hover) {
                var event = d3.event;
                var cw = this.width;
                var ch = this.height;
                var pointer = d3.mouse(this);
                var x = pointer[0];
                var y = pointer[1];

                if(x < 0 || y < 0 || x >= cw || y >= ch) {
                    return;
                }
                var pixel = d.lineLayer.readPixel(x, ch - 1 - y);
                var found = pixel[3] !== 0;
                // inverse of the calcPickColor in `lines.js`; detailed comment there
                var curveNumber = found ? pixel[2] + 256 * (pixel[1] + 256 * pixel[0]) : null;
                var eventData = {
                    x: x,
                    y: y,
                    clientX: event.clientX,
                    clientY: event.clientY,
                    dataIndex: d.model.key,
                    curveNumber: curveNumber
                };
                if(curveNumber !== lastHovered) { // don't unnecessarily repeat the same hit (or miss)
                    if(found) {
                        callbacks.hover(eventData);
                    } else if(callbacks.unhover) {
                        callbacks.unhover(eventData);
                    }
                    lastHovered = curveNumber;
                }
            }
        });

    parcoordsLineLayer
        .style('opacity', function(d) {return d.pick ? 0.01 : 1;});

    svg.style('background', 'rgba(255, 255, 255, 0)');
    var parcoordsControlOverlay = svg.selectAll('.' + c.cn.parcoords)
        .data(vm, keyFun);

    parcoordsControlOverlay.exit().remove();

    parcoordsControlOverlay.enter()
        .append('g')
        .classed(c.cn.parcoords, true)
        .style('shape-rendering', 'crispEdges')
        .style('pointer-events', 'none');

    parcoordsControlOverlay.attr('transform', function(d) {
        return 'translate(' + d.model.translateX + ',' + d.model.translateY + ')';
    });

    var parcoordsControlView = parcoordsControlOverlay.selectAll('.' + c.cn.parcoordsControlView)
        .data(repeat, keyFun);

    parcoordsControlView.enter()
        .append('g')
        .classed(c.cn.parcoordsControlView, true);

    parcoordsControlView.attr('transform', function(d) {
        return 'translate(' + d.model.pad.l + ',' + d.model.pad.t + ')';
    });

    var yAxis = parcoordsControlView.selectAll('.' + c.cn.yAxis)
        .data(function(vm) { return vm.dimensions; }, keyFun);

    function updatePanelLayout(yAxis, vm) {
        var panels = vm.panels || (vm.panels = []);
        var dimData = yAxis.data();
        var panelCount = dimData.length - 1;
        for(var p = 0; p < panelCount; p++) {
            var panel = panels[p] || (panels[p] = {});
            var dim1 = dimData[p];
            var dim2 = dimData[p + 1];
            panel.dim1 = dim1;
            panel.dim2 = dim2;
            panel.canvasX = dim1.canvasX;
            panel.panelSizeX = dim2.canvasX - dim1.canvasX;
            panel.panelSizeY = vm.model.canvasHeight;
            panel.y = 0;
            panel.canvasY = 0;
        }
    }

    yAxis.enter()
        .append('g')
        .classed(c.cn.yAxis, true);

    parcoordsControlView.each(function(vm) {
        updatePanelLayout(yAxis, vm);
    });

    parcoordsLineLayer
        .each(function(d) {
            if(d.viewModel) {
                if(!d.lineLayer || callbacks) { // recreate in case of having callbacks e.g. restyle. Should we test for callback to be a restyle?
                    d.lineLayer = lineLayerMaker(this, d);
                } else d.lineLayer.update(d);

                if(d.key || d.key === 0) d.viewModel[d.key] = d.lineLayer;

                var setChanged = (!d.context || // don't update background
                                  callbacks);   // unless there is a callback on the context layer. Should we test the callback?

                d.lineLayer.render(d.viewModel.panels, setChanged);
            }
        });

    yAxis.attr('transform', function(d) {
        return 'translate(' + d.xScale(d.xIndex) + ', 0)';
    });

    // drag column for reordering columns
    yAxis.call(d3.behavior.drag()
        .origin(function(d) { return d; })
        .on('drag', function(d) {
            var p = d.parent;
            state.linePickActive(false);
            d.x = Math.max(-c.overdrag, Math.min(d.model.width + c.overdrag, d3.event.x));
            d.canvasX = d.x * d.model.canvasPixelRatio;
            yAxis
                .sort(function(a, b) { return a.x - b.x; })
                .each(function(dd, i) {
                    dd.xIndex = i;
                    dd.x = d === dd ? dd.x : dd.xScale(dd.xIndex);
                    dd.canvasX = dd.x * dd.model.canvasPixelRatio;
                });

            updatePanelLayout(yAxis, p);

            yAxis.filter(function(dd) { return Math.abs(d.xIndex - dd.xIndex) !== 0; })
                .attr('transform', function(d) { return 'translate(' + d.xScale(d.xIndex) + ', 0)'; });
            d3.select(this).attr('transform', 'translate(' + d.x + ', 0)');
            yAxis.each(function(dd, i, ii) { if(ii === d.parent.key) p.dimensions[i] = dd; });
            p.contextLayer && p.contextLayer.render(p.panels, false, !someFiltersActive(p));
            p.focusLayer.render && p.focusLayer.render(p.panels);
        })
        .on('dragend', function(d) {
            var p = d.parent;
            d.x = d.xScale(d.xIndex);
            d.canvasX = d.x * d.model.canvasPixelRatio;
            updatePanelLayout(yAxis, p);
            d3.select(this)
                .attr('transform', function(d) { return 'translate(' + d.x + ', 0)'; });
            p.contextLayer && p.contextLayer.render(p.panels, false, !someFiltersActive(p));
            p.focusLayer && p.focusLayer.render(p.panels);
            p.pickLayer && p.pickLayer.render(p.panels, true);
            state.linePickActive(true);

            if(callbacks && callbacks.axesMoved) {
                callbacks.axesMoved(p.key, p.dimensions.map(function(dd) {return dd.crossfilterDimensionIndex;}));
            }
        })
    );

    yAxis.exit()
        .remove();

    var axisOverlays = yAxis.selectAll('.' + c.cn.axisOverlays)
        .data(repeat, keyFun);

    axisOverlays.enter()
        .append('g')
        .classed(c.cn.axisOverlays, true);

    axisOverlays.selectAll('.' + c.cn.axis).remove();

    var axis = axisOverlays.selectAll('.' + c.cn.axis)
        .data(repeat, keyFun);

    axis.enter()
        .append('g')
        .classed(c.cn.axis, true);

    axis
        .each(function(d) {
            var wantedTickCount = d.model.height / d.model.tickDistance;
            var scale = d.domainScale;
            var sdom = scale.domain();
            d3.select(this)
                .call(d3.svg.axis()
                    .orient('left')
                    .tickSize(4)
                    .outerTickSize(2)
                    .ticks(wantedTickCount, d.tickFormat) // works for continuous scales only...
                    .tickValues(d.ordinal ? // and this works for ordinal scales
                        sdom :
                        null)
                    .tickFormat(d.ordinal ? function(d) { return d; } : null)
                    .scale(scale));
            Drawing.font(axis.selectAll('text'), d.model.tickFont);
        });

    axis.selectAll('.domain, .tick>line')
        .attr('fill', 'none')
        .attr('stroke', 'black')
        .attr('stroke-opacity', 0.25)
        .attr('stroke-width', '1px');

    axis.selectAll('text')
        .style('text-shadow', '1px 1px 1px #fff, -1px -1px 1px #fff, 1px -1px 1px #fff, -1px 1px 1px #fff')
        .style('cursor', 'default')
        .style('user-select', 'none');

    var axisHeading = axisOverlays.selectAll('.' + c.cn.axisHeading)
        .data(repeat, keyFun);

    axisHeading.enter()
        .append('g')
        .classed(c.cn.axisHeading, true);

    var axisTitle = axisHeading.selectAll('.' + c.cn.axisTitle)
        .data(repeat, keyFun);

    axisTitle.enter()
        .append('text')
        .classed(c.cn.axisTitle, true)
        .attr('text-anchor', 'middle')
        .style('cursor', 'ew-resize')
        .style('user-select', 'none')
        .style('pointer-events', 'auto');

    axisTitle
        .attr('transform', 'translate(0,' + -c.axisTitleOffset + ')')
        .text(function(d) { return d.label; })
        .each(function(d) { Drawing.font(d3.select(this), d.model.labelFont); });

    var axisExtent = axisOverlays.selectAll('.' + c.cn.axisExtent)
        .data(repeat, keyFun);

    axisExtent.enter()
        .append('g')
        .classed(c.cn.axisExtent, true);

    var axisExtentTop = axisExtent.selectAll('.' + c.cn.axisExtentTop)
        .data(repeat, keyFun);

    axisExtentTop.enter()
        .append('g')
        .classed(c.cn.axisExtentTop, true);

    axisExtentTop
        .attr('transform', 'translate(' + 0 + ',' + -c.axisExtentOffset + ')');

    var axisExtentTopText = axisExtentTop.selectAll('.' + c.cn.axisExtentTopText)
        .data(repeat, keyFun);

    function extremeText(d, isTop) {
        if(d.ordinal) return '';
        var domain = d.domainScale.domain();
        return d3.format(d.tickFormat)(domain[isTop ? domain.length - 1 : 0]);
    }

    axisExtentTopText.enter()
        .append('text')
        .classed(c.cn.axisExtentTopText, true)
        .call(styleExtentTexts);

    axisExtentTopText
        .text(function(d) { return extremeText(d, true); })
        .each(function(d) { Drawing.font(d3.select(this), d.model.rangeFont); });

    var axisExtentBottom = axisExtent.selectAll('.' + c.cn.axisExtentBottom)
        .data(repeat, keyFun);

    axisExtentBottom.enter()
        .append('g')
        .classed(c.cn.axisExtentBottom, true);

    axisExtentBottom
        .attr('transform', function(d) {
            return 'translate(' + 0 + ',' + (d.model.height + c.axisExtentOffset) + ')';
        });

    var axisExtentBottomText = axisExtentBottom.selectAll('.' + c.cn.axisExtentBottomText)
        .data(repeat, keyFun);

    axisExtentBottomText.enter()
        .append('text')
        .classed(c.cn.axisExtentBottomText, true)
        .attr('dy', '0.75em')
        .call(styleExtentTexts);

    axisExtentBottomText
        .text(function(d) { return extremeText(d); })
        .each(function(d) { Drawing.font(d3.select(this), d.model.rangeFont); });

    brush.ensureAxisBrush(axisOverlays);
};

},{"../../components/colorscale":583,"../../components/drawing":592,"../../lib":694,"../../lib/gup":692,"./axisbrush":1012,"./constants":1015,"./lines":1018,"d3":149}],1021:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var parcoords = _dereq_('./parcoords');
var prepareRegl = _dereq_('../../lib/prepare_regl');

module.exports = function plot(gd, cdparcoords) {
    var fullLayout = gd._fullLayout;
    var svg = fullLayout._toppaper;
    var root = fullLayout._paperdiv;
    var container = fullLayout._glcontainer;

    var success = prepareRegl(gd);
    if(!success) return;

    var gdDimensions = {};
    var gdDimensionsOriginalOrder = {};
    var fullIndices = {};
    var inputIndices = {};

    var size = fullLayout._size;

    cdparcoords.forEach(function(d, i) {
        var trace = d[0].trace;
        fullIndices[i] = trace.index;
        var iIn = inputIndices[i] = trace._fullInput.index;
        gdDimensions[i] = gd.data[iIn].dimensions;
        gdDimensionsOriginalOrder[i] = gd.data[iIn].dimensions.slice();
    });

    var filterChanged = function(i, originalDimensionIndex, newRanges) {

        // Have updated `constraintrange` data on `gd.data` and raise `Plotly.restyle` event
        // without having to incur heavy UI blocking due to an actual `Plotly.restyle` call

        var gdDimension = gdDimensionsOriginalOrder[i][originalDimensionIndex];
        var newConstraints = newRanges.map(function(r) { return r.slice(); });

        // Store constraint range in preGUI
        // This one doesn't work if it's stored in pieces in _storeDirectGUIEdit
        // because it's an array of variable dimensionality. So store the whole
        // thing at once manually.
        var aStr = 'dimensions[' + originalDimensionIndex + '].constraintrange';
        var preGUI = fullLayout._tracePreGUI[gd._fullData[fullIndices[i]]._fullInput.uid];
        if(preGUI[aStr] === undefined) {
            var initialVal = gdDimension.constraintrange;
            preGUI[aStr] = initialVal || null;
        }

        var fullDimension = gd._fullData[fullIndices[i]].dimensions[originalDimensionIndex];

        if(!newConstraints.length) {
            delete gdDimension.constraintrange;
            delete fullDimension.constraintrange;
            newConstraints = null;
        }
        else {
            if(newConstraints.length === 1) newConstraints = newConstraints[0];
            gdDimension.constraintrange = newConstraints;
            fullDimension.constraintrange = newConstraints.slice();
            // wrap in another array for restyle event data
            newConstraints = [newConstraints];
        }

        var restyleData = {};
        restyleData[aStr] = newConstraints;
        gd.emit('plotly_restyle', [restyleData, [inputIndices[i]]]);
    };

    var hover = function(eventData) {
        gd.emit('plotly_hover', eventData);
    };

    var unhover = function(eventData) {
        gd.emit('plotly_unhover', eventData);
    };

    var axesMoved = function(i, visibleIndices) {

        // Have updated order data on `gd.data` and raise `Plotly.restyle` event
        // without having to incur heavy UI blocking due to an actual `Plotly.restyle` call

        function visible(dimension) {return !('visible' in dimension) || dimension.visible;}

        function newIdx(visibleIndices, orig, dim) {
            var origIndex = orig.indexOf(dim);
            var currentIndex = visibleIndices.indexOf(origIndex);
            if(currentIndex === -1) {
                // invisible dimensions initially go to the end
                currentIndex += orig.length;
            }
            return currentIndex;
        }

        function sorter(orig) {
            return function sorter(d1, d2) {
                var i1 = newIdx(visibleIndices, orig, d1);
                var i2 = newIdx(visibleIndices, orig, d2);
                return i1 - i2;
            };
        }

        // drag&drop sorting of the visible dimensions
        var orig = sorter(gdDimensionsOriginalOrder[i].filter(visible));
        gdDimensions[i].sort(orig);

        // invisible dimensions are not interpreted in the context of drag&drop sorting as an invisible dimension
        // cannot be dragged; they're interspersed into their original positions by this subsequent merging step
        gdDimensionsOriginalOrder[i].filter(function(d) {return !visible(d);})
             .sort(function(d) {
                 // subsequent splicing to be done left to right, otherwise indices may be incorrect
                 return gdDimensionsOriginalOrder[i].indexOf(d);
             })
            .forEach(function(d) {
                gdDimensions[i].splice(gdDimensions[i].indexOf(d), 1); // remove from the end
                gdDimensions[i].splice(gdDimensionsOriginalOrder[i].indexOf(d), 0, d); // insert at original index
            });

        // TODO: we can't really store this part of the interaction state
        // directly as below, since it incudes data arrays. If we want to
        // persist column order we may have to do something special for this
        // case to just store the order itself.
        // Registry.call('_storeDirectGUIEdit',
        //     gd.data[inputIndices[i]],
        //     fullLayout._tracePreGUI[gd._fullData[fullIndices[i]]._fullInput.uid],
        //     {dimensions: gdDimensions[i]}
        // );

        gd.emit('plotly_restyle', [{dimensions: [gdDimensions[i]]}, [inputIndices[i]]]);
    };

    parcoords(
        root,
        svg,
        container,
        cdparcoords,
        {
            width: size.w,
            height: size.h,
            margin: {
                t: size.t,
                r: size.r,
                b: size.b,
                l: size.l
            }
        },
        {
            filterChanged: filterChanged,
            hover: hover,
            unhover: unhover,
            axesMoved: axesMoved
        });
};

},{"../../lib/prepare_regl":707,"./parcoords":1020}],1022:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorAttrs = _dereq_('../../components/color/attributes');
var fontAttrs = _dereq_('../../plots/font_attributes');
var plotAttrs = _dereq_('../../plots/attributes');
var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var domainAttrs = _dereq_('../../plots/domain').attributes;

var extendFlat = _dereq_('../../lib/extend').extendFlat;

var textFontAttrs = fontAttrs({
    editType: 'calc',
    arrayOk: true,
    colorEditType: 'plot',
    
});

module.exports = {
    labels: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    // equivalent of x0 and dx, if label is missing
    label0: {
        valType: 'number',
        
        dflt: 0,
        editType: 'calc',
        
    },
    dlabel: {
        valType: 'number',
        
        dflt: 1,
        editType: 'calc',
        
    },

    values: {
        valType: 'data_array',
        editType: 'calc',
        
    },

    marker: {
        colors: {
            valType: 'data_array',  // TODO 'color_array' ?
            editType: 'calc',
            
        },

        line: {
            color: {
                valType: 'color',
                
                dflt: colorAttrs.defaultLine,
                arrayOk: true,
                editType: 'style',
                
            },
            width: {
                valType: 'number',
                
                min: 0,
                dflt: 0,
                arrayOk: true,
                editType: 'style',
                
            },
            editType: 'calc'
        },
        editType: 'calc'
    },

    text: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    hovertext: {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        editType: 'style',
        
    },

// 'see eg:'
// 'https://www.e-education.psu.edu/natureofgeoinfo/sites/www.e-education.psu.edu.natureofgeoinfo/files/image/hisp_pies.gif',
// '(this example involves a map too - may someday be a whole trace type',
// 'of its own. but the point is the size of the whole pie is important.)'
    scalegroup: {
        valType: 'string',
        
        dflt: '',
        editType: 'calc',
        
    },

    // labels (legend is handled by plots.attributes.showlegend and layout.hiddenlabels)
    textinfo: {
        valType: 'flaglist',
        
        flags: ['label', 'text', 'value', 'percent'],
        extras: ['none'],
        editType: 'calc',
        
    },
    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
        flags: ['label', 'text', 'value', 'percent', 'name']
    }),
    hovertemplate: hovertemplateAttrs({}, {
        keys: ['label', 'color', 'value', 'percent', 'text']
    }),
    textposition: {
        valType: 'enumerated',
        
        values: ['inside', 'outside', 'auto', 'none'],
        dflt: 'auto',
        arrayOk: true,
        editType: 'calc',
        
    },
    textfont: extendFlat({}, textFontAttrs, {
        
    }),
    insidetextfont: extendFlat({}, textFontAttrs, {
        
    }),
    outsidetextfont: extendFlat({}, textFontAttrs, {
        
    }),

    title: {
        text: {
            valType: 'string',
            dflt: '',
            
            editType: 'calc',
            
        },
        font: extendFlat({}, textFontAttrs, {
            
        }),
        position: {
            valType: 'enumerated',
            values: [
                'top left', 'top center', 'top right',
                'middle center',
                'bottom left', 'bottom center', 'bottom right'
            ],
            
            editType: 'calc',
            
        },

        editType: 'calc'
    },

    // position and shape
    domain: domainAttrs({name: 'pie', trace: true, editType: 'calc'}),

    hole: {
        valType: 'number',
        
        min: 0,
        max: 1,
        dflt: 0,
        editType: 'calc',
        
    },

    // ordering and direction
    sort: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'calc',
        
    },
    direction: {
        /**
         * there are two common conventions, both of which place the first
         * (largest, if sorted) slice with its left edge at 12 o'clock but
         * succeeding slices follow either cw or ccw from there.
         *
         * see http://visage.co/data-visualization-101-pie-charts/
         */
        valType: 'enumerated',
        values: ['clockwise', 'counterclockwise'],
        
        dflt: 'counterclockwise',
        editType: 'calc',
        
    },
    rotation: {
        valType: 'number',
        
        min: -360,
        max: 360,
        dflt: 0,
        editType: 'calc',
        
    },

    pull: {
        valType: 'number',
        
        min: 0,
        max: 1,
        dflt: 0,
        arrayOk: true,
        editType: 'calc',
        
    },

    _deprecated: {
        title: {
            valType: 'string',
            dflt: '',
            
            editType: 'calc',
            
        },
        titlefont: extendFlat({}, textFontAttrs, {
            
        }),
        titleposition: {
            valType: 'enumerated',
            values: [
                'top left', 'top center', 'top right',
                'middle center',
                'bottom left', 'bottom center', 'bottom right'
            ],
            
            editType: 'calc',
            
        }
    }
};

},{"../../components/color/attributes":570,"../../components/fx/hovertemplate_attributes":609,"../../lib/extend":684,"../../plots/attributes":739,"../../plots/domain":768,"../../plots/font_attributes":769}],1023:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');
var getModuleCalcData = _dereq_('../../plots/get_data').getModuleCalcData;

exports.name = 'pie';

exports.plot = function(gd) {
    var Pie = Registry.getModule('pie');
    var cdPie = getModuleCalcData(gd.calcdata, Pie)[0];

    if(cdPie.length) Pie.plot(gd, cdPie);
};

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var hadPie = (oldFullLayout._has && oldFullLayout._has('pie'));
    var hasPie = (newFullLayout._has && newFullLayout._has('pie'));

    if(hadPie && !hasPie) {
        oldFullLayout._pielayer.selectAll('g.trace').remove();
    }
};

},{"../../plots/get_data":779,"../../registry":825}],1024:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;
var tinycolor = _dereq_('tinycolor2');

var Color = _dereq_('../../components/color');
var helpers = _dereq_('./helpers');

exports.calc = function calc(gd, trace) {
    var vals = trace.values;
    var hasVals = isArrayOrTypedArray(vals) && vals.length;
    var labels = trace.labels;
    var colors = trace.marker.colors || [];
    var cd = [];
    var fullLayout = gd._fullLayout;
    var colorMap = fullLayout._piecolormap;
    var allThisTraceLabels = {};
    var vTotal = 0;
    var hiddenLabels = fullLayout.hiddenlabels || [];

    var i, v, label, hidden, pt;

    if(trace.dlabel) {
        labels = new Array(vals.length);
        for(i = 0; i < vals.length; i++) {
            labels[i] = String(trace.label0 + i * trace.dlabel);
        }
    }

    function pullColor(color, label) {
        if(!color) return false;

        color = tinycolor(color);
        if(!color.isValid()) return false;

        color = Color.addOpacity(color, color.getAlpha());
        if(!colorMap[label]) colorMap[label] = color;

        return color;
    }

    var seriesLen = (hasVals ? vals : labels).length;

    for(i = 0; i < seriesLen; i++) {
        if(hasVals) {
            v = vals[i];
            if(!isNumeric(v)) continue;
            v = +v;
            if(v < 0) continue;
        }
        else v = 1;

        label = labels[i];
        if(label === undefined || label === '') label = i;
        label = String(label);

        var thisLabelIndex = allThisTraceLabels[label];
        if(thisLabelIndex === undefined) {
            allThisTraceLabels[label] = cd.length;

            hidden = hiddenLabels.indexOf(label) !== -1;

            if(!hidden) vTotal += v;

            cd.push({
                v: v,
                label: label,
                color: pullColor(colors[i], label),
                i: i,
                pts: [i],
                hidden: hidden
            });
        }
        else {
            pt = cd[thisLabelIndex];
            pt.v += v;
            pt.pts.push(i);
            if(!pt.hidden) vTotal += v;

            if(pt.color === false && colors[i]) {
                pt.color = pullColor(colors[i], label);
            }
        }
    }

    if(trace.sort) cd.sort(function(a, b) { return b.v - a.v; });

    // include the sum of all values in the first point
    if(cd[0]) cd[0].vTotal = vTotal;

    // now insert text
    if(trace.textinfo && trace.textinfo !== 'none') {
        var hasLabel = trace.textinfo.indexOf('label') !== -1;
        var hasText = trace.textinfo.indexOf('text') !== -1;
        var hasValue = trace.textinfo.indexOf('value') !== -1;
        var hasPercent = trace.textinfo.indexOf('percent') !== -1;
        var separators = fullLayout.separators;

        var thisText;

        for(i = 0; i < cd.length; i++) {
            pt = cd[i];
            thisText = hasLabel ? [pt.label] : [];
            if(hasText) {
                var texti = helpers.getFirstFilled(trace.text, pt.pts);
                if(texti) thisText.push(texti);
            }
            if(hasValue) thisText.push(helpers.formatPieValue(pt.v, separators));
            if(hasPercent) thisText.push(helpers.formatPiePercent(pt.v / vTotal, separators));
            pt.text = thisText.join('<br>');
        }
    }

    return cd;
};

/*
 * `calc` filled in (and collated) explicit colors.
 * Now we need to propagate these explicit colors to other traces,
 * and fill in default colors.
 * This is done after sorting, so we pick defaults
 * in the order slices will be displayed
 */
exports.crossTraceCalc = function(gd) {
    var fullLayout = gd._fullLayout;
    var calcdata = gd.calcdata;
    var pieColorWay = fullLayout.piecolorway;
    var colorMap = fullLayout._piecolormap;

    if(fullLayout.extendpiecolors) {
        pieColorWay = generateExtendedColors(pieColorWay);
    }
    var dfltColorCount = 0;

    var i, j, cd, pt;
    for(i = 0; i < calcdata.length; i++) {
        cd = calcdata[i];
        if(cd[0].trace.type !== 'pie') continue;

        for(j = 0; j < cd.length; j++) {
            pt = cd[j];
            if(pt.color === false) {
                // have we seen this label and assigned a color to it in a previous trace?
                if(colorMap[pt.label]) {
                    pt.color = colorMap[pt.label];
                }
                else {
                    colorMap[pt.label] = pt.color = pieColorWay[dfltColorCount % pieColorWay.length];
                    dfltColorCount++;
                }
            }
        }
    }
};

/**
 * pick a default color from the main default set, augmented by
 * itself lighter then darker before repeating
 */
var extendedColorWays = {};

function generateExtendedColors(colorList) {
    var i;
    var colorString = JSON.stringify(colorList);
    var pieColors = extendedColorWays[colorString];
    if(!pieColors) {
        pieColors = colorList.slice();

        for(i = 0; i < colorList.length; i++) {
            pieColors.push(tinycolor(colorList[i]).lighten(20).toHexString());
        }

        for(i = 0; i < colorList.length; i++) {
            pieColors.push(tinycolor(colorList[i]).darken(20).toHexString());
        }
        extendedColorWays[colorString] = pieColors;
    }

    return pieColors;
}

},{"../../components/color":571,"../../lib":694,"./helpers":1027,"fast-isnumeric":215,"tinycolor2":515}],1025:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var attributes = _dereq_('./attributes');
var handleDomainDefaults = _dereq_('../../plots/domain').defaults;

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var coerceFont = Lib.coerceFont;
    var len;

    var vals = coerce('values');
    var hasVals = Lib.isArrayOrTypedArray(vals);
    var labels = coerce('labels');
    if(Array.isArray(labels)) {
        len = labels.length;
        if(hasVals) len = Math.min(len, vals.length);
    }
    else if(hasVals) {
        len = vals.length;

        coerce('label0');
        coerce('dlabel');
    }

    if(!len) {
        traceOut.visible = false;
        return;
    }
    traceOut._length = len;

    var lineWidth = coerce('marker.line.width');
    if(lineWidth) coerce('marker.line.color');

    coerce('marker.colors');

    coerce('scalegroup');
    // TODO: hole needs to be coerced to the same value within a scaleegroup

    var textData = coerce('text');
    var textInfo = coerce('textinfo', Array.isArray(textData) ? 'text+percent' : 'percent');
    coerce('hovertext');
    coerce('hovertemplate');

    if(textInfo && textInfo !== 'none') {
        var textPosition = coerce('textposition');
        var hasBoth = Array.isArray(textPosition) || textPosition === 'auto';
        var hasInside = hasBoth || textPosition === 'inside';
        var hasOutside = hasBoth || textPosition === 'outside';

        if(hasInside || hasOutside) {
            var dfltFont = coerceFont(coerce, 'textfont', layout.font);
            if(hasInside) {
                var insideTextFontDefault = Lib.extendFlat({}, dfltFont);
                var isTraceTextfontColorSet = traceIn.textfont && traceIn.textfont.color;
                var isColorInheritedFromLayoutFont = !isTraceTextfontColorSet;
                if(isColorInheritedFromLayoutFont) {
                    delete insideTextFontDefault.color;
                }
                coerceFont(coerce, 'insidetextfont', insideTextFontDefault);
            }
            if(hasOutside) coerceFont(coerce, 'outsidetextfont', dfltFont);
        }
    }

    handleDomainDefaults(traceOut, layout, coerce);

    var hole = coerce('hole');
    var title = coerce('title.text');
    if(title) {
        var titlePosition = coerce('title.position', hole ? 'middle center' : 'top center');
        if(!hole && titlePosition === 'middle center') traceOut.title.position = 'top center';
        coerceFont(coerce, 'title.font', layout.font);
    }

    coerce('sort');
    coerce('direction');
    coerce('rotation');

    coerce('pull');
};

},{"../../lib":694,"../../plots/domain":768,"./attributes":1022}],1026:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var appendArrayMultiPointValues = _dereq_('../../components/fx/helpers').appendArrayMultiPointValues;


// Note: like other eventData routines, this creates the data for hover/unhover/click events
// but it has a different API and goes through a totally different pathway.
// So to ensure it doesn't get misused, it's not attached to the Pie module.
module.exports = function eventData(pt, trace) {
    var out = {
        curveNumber: trace.index,
        pointNumbers: pt.pts,
        data: trace._input,
        fullData: trace,
        label: pt.label,
        color: pt.color,
        value: pt.v,
        percent: pt.percent,
        text: pt.text,

        // pt.v (and pt.i below) for backward compatibility
        v: pt.v
    };

    // Only include pointNumber if it's unambiguous
    if(pt.pts.length === 1) out.pointNumber = out.i = pt.pts[0];

    // Add extra data arrays to the output
    // notice that this is the multi-point version ('s' on the end!)
    // so added data will be arrays matching the pointNumbers array.
    appendArrayMultiPointValues(out, trace, pt.pts);

    return out;
};

},{"../../components/fx/helpers":606}],1027:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

exports.formatPiePercent = function formatPiePercent(v, separators) {
    var vRounded = (v * 100).toPrecision(3);
    if(vRounded.lastIndexOf('.') !== -1) {
        vRounded = vRounded.replace(/[.]?0+$/, '');
    }
    return Lib.numSeparate(vRounded, separators) + '%';
};

exports.formatPieValue = function formatPieValue(v, separators) {
    var vRounded = v.toPrecision(10);
    if(vRounded.lastIndexOf('.') !== -1) {
        vRounded = vRounded.replace(/[.]?0+$/, '');
    }
    return Lib.numSeparate(vRounded, separators);
};

exports.getFirstFilled = function getFirstFilled(array, indices) {
    if(!Array.isArray(array)) return;
    for(var i = 0; i < indices.length; i++) {
        var v = array[indices[i]];
        if(v || v === 0) return v;
    }
};

exports.castOption = function castOption(item, indices) {
    if(Array.isArray(item)) return exports.getFirstFilled(item, indices);
    else if(item) return item;
};

},{"../../lib":694}],1028:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Pie = {};

Pie.attributes = _dereq_('./attributes');
Pie.supplyDefaults = _dereq_('./defaults');
Pie.supplyLayoutDefaults = _dereq_('./layout_defaults');
Pie.layoutAttributes = _dereq_('./layout_attributes');

var calcModule = _dereq_('./calc');
Pie.calc = calcModule.calc;
Pie.crossTraceCalc = calcModule.crossTraceCalc;

Pie.plot = _dereq_('./plot');
Pie.style = _dereq_('./style');
Pie.styleOne = _dereq_('./style_one');

Pie.moduleType = 'trace';
Pie.name = 'pie';
Pie.basePlotModule = _dereq_('./base_plot');
Pie.categories = ['pie', 'showLegend'];
Pie.meta = {
    
};

module.exports = Pie;

},{"./attributes":1022,"./base_plot":1023,"./calc":1024,"./defaults":1025,"./layout_attributes":1029,"./layout_defaults":1030,"./plot":1031,"./style":1032,"./style_one":1033}],1029:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    /**
     * hiddenlabels is the pie chart analog of visible:'legendonly'
     * but it can contain many labels, and can hide slices
     * from several pies simultaneously
     */
    hiddenlabels: {
        valType: 'data_array',
        editType: 'calc'
    },
    piecolorway: {
        valType: 'colorlist',
        
        editType: 'calc',
        
    },
    extendpiecolors: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'calc',
        
    }
};

},{}],1030:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

var layoutAttributes = _dereq_('./layout_attributes');

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
    function coerce(attr, dflt) {
        return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
    }
    coerce('hiddenlabels');
    coerce('piecolorway', layoutOut.colorway);
    coerce('extendpiecolors');
};

},{"../../lib":694,"./layout_attributes":1029}],1031:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var Fx = _dereq_('../../components/fx');
var Color = _dereq_('../../components/color');
var Drawing = _dereq_('../../components/drawing');
var Lib = _dereq_('../../lib');
var svgTextUtils = _dereq_('../../lib/svg_text_utils');

var helpers = _dereq_('./helpers');
var eventData = _dereq_('./event_data');

module.exports = function plot(gd, cdpie) {
    var fullLayout = gd._fullLayout;

    prerenderTitles(cdpie, gd);
    scalePies(cdpie, fullLayout._size);

    var pieGroups = Lib.makeTraceGroups(fullLayout._pielayer, cdpie, 'trace').each(function(cd) {
        var pieGroup = d3.select(this);
        var cd0 = cd[0];
        var trace = cd0.trace;

        setCoords(cd);

        // TODO: miter might look better but can sometimes cause problems
        // maybe miter with a small-ish stroke-miterlimit?
        pieGroup.attr('stroke-linejoin', 'round');

        pieGroup.each(function() {
            var slices = d3.select(this).selectAll('g.slice').data(cd);

            slices.enter().append('g')
                .classed('slice', true);
            slices.exit().remove();

            var quadrants = [
                [[], []], // y<0: x<0, x>=0
                [[], []] // y>=0: x<0, x>=0
            ];
            var hasOutsideText = false;

            slices.each(function(pt) {
                if(pt.hidden) {
                    d3.select(this).selectAll('path,g').remove();
                    return;
                }

                // to have consistent event data compared to other traces
                pt.pointNumber = pt.i;
                pt.curveNumber = trace.index;

                quadrants[pt.pxmid[1] < 0 ? 0 : 1][pt.pxmid[0] < 0 ? 0 : 1].push(pt);

                var cx = cd0.cx;
                var cy = cd0.cy;
                var sliceTop = d3.select(this);
                var slicePath = sliceTop.selectAll('path.surface').data([pt]);

                // hover state vars
                // have we drawn a hover label, so it should be cleared later
                var hasHoverLabel = false;
                // have we emitted a hover event, so later an unhover event should be emitted
                // note that click events do not depend on this - you can still get them
                // with hovermode: false or if you were earlier dragging, then clicked
                // in the same slice that you moused up in
                var hasHoverEvent = false;

                function handleMouseOver() {
                    // in case fullLayout or fullData has changed without a replot
                    var fullLayout2 = gd._fullLayout;
                    var trace2 = gd._fullData[trace.index];

                    if(gd._dragging || fullLayout2.hovermode === false) return;

                    var hoverinfo = trace2.hoverinfo;
                    if(Array.isArray(hoverinfo)) {
                        // super hacky: we need to pull out the *first* hoverinfo from
                        // pt.pts, then put it back into an array in a dummy trace
                        // and call castHoverinfo on that.
                        // TODO: do we want to have Fx.castHoverinfo somehow handle this?
                        // it already takes an array for index, for 2D, so this seems tricky.
                        hoverinfo = Fx.castHoverinfo({
                            hoverinfo: [helpers.castOption(hoverinfo, pt.pts)],
                            _module: trace._module
                        }, fullLayout2, 0);
                    }

                    if(hoverinfo === 'all') hoverinfo = 'label+text+value+percent+name';

                    // in case we dragged over the pie from another subplot,
                    // or if hover is turned off
                    if(trace2.hovertemplate || (hoverinfo !== 'none' && hoverinfo !== 'skip' && hoverinfo)) {
                        var rInscribed = getInscribedRadiusFraction(pt, cd0);
                        var hoverCenterX = cx + pt.pxmid[0] * (1 - rInscribed);
                        var hoverCenterY = cy + pt.pxmid[1] * (1 - rInscribed);
                        var separators = fullLayout.separators;
                        var thisText = [];

                        if(hoverinfo && hoverinfo.indexOf('label') !== -1) thisText.push(pt.label);
                        pt.text = helpers.castOption(trace2.hovertext || trace2.text, pt.pts);
                        if(hoverinfo && hoverinfo.indexOf('text') !== -1) {
                            var texti = pt.text;
                            if(texti) thisText.push(texti);
                        }
                        pt.value = pt.v;
                        pt.valueLabel = helpers.formatPieValue(pt.v, separators);
                        if(hoverinfo && hoverinfo.indexOf('value') !== -1) thisText.push(pt.valueLabel);
                        pt.percent = pt.v / cd0.vTotal;
                        pt.percentLabel = helpers.formatPiePercent(pt.percent, separators);
                        if(hoverinfo && hoverinfo.indexOf('percent') !== -1) thisText.push(pt.percentLabel);

                        var hoverLabel = trace.hoverlabel;
                        var hoverFont = hoverLabel.font;

                        Fx.loneHover({
                            x0: hoverCenterX - rInscribed * cd0.r,
                            x1: hoverCenterX + rInscribed * cd0.r,
                            y: hoverCenterY,
                            text: thisText.join('<br>'),
                            name: (trace2.hovertemplate || hoverinfo.indexOf('name') !== -1) ? trace2.name : undefined,
                            idealAlign: pt.pxmid[0] < 0 ? 'left' : 'right',
                            color: helpers.castOption(hoverLabel.bgcolor, pt.pts) || pt.color,
                            borderColor: helpers.castOption(hoverLabel.bordercolor, pt.pts),
                            fontFamily: helpers.castOption(hoverFont.family, pt.pts),
                            fontSize: helpers.castOption(hoverFont.size, pt.pts),
                            fontColor: helpers.castOption(hoverFont.color, pt.pts),

                            trace: trace2,
                            hovertemplate: helpers.castOption(trace2.hovertemplate, pt.pts),
                            hovertemplateLabels: pt,
                            eventData: [eventData(pt, trace2)]
                        }, {
                            container: fullLayout2._hoverlayer.node(),
                            outerContainer: fullLayout2._paper.node(),
                            gd: gd
                        });

                        hasHoverLabel = true;
                    }

                    gd.emit('plotly_hover', {
                        points: [eventData(pt, trace2)],
                        event: d3.event
                    });
                    hasHoverEvent = true;
                }

                function handleMouseOut(evt) {
                    var fullLayout2 = gd._fullLayout;
                    var trace2 = gd._fullData[trace.index];

                    if(hasHoverEvent) {
                        evt.originalEvent = d3.event;
                        gd.emit('plotly_unhover', {
                            points: [eventData(pt, trace2)],
                            event: d3.event
                        });
                        hasHoverEvent = false;
                    }

                    if(hasHoverLabel) {
                        Fx.loneUnhover(fullLayout2._hoverlayer.node());
                        hasHoverLabel = false;
                    }
                }

                function handleClick() {
                    // TODO: this does not support right-click. If we want to support it, we
                    // would likely need to change pie to use dragElement instead of straight
                    // mapbox event binding. Or perhaps better, make a simple wrapper with the
                    // right mousedown, mousemove, and mouseup handlers just for a left/right click
                    // mapbox would use this too.
                    var fullLayout2 = gd._fullLayout;
                    var trace2 = gd._fullData[trace.index];

                    if(gd._dragging || fullLayout2.hovermode === false) return;

                    gd._hoverdata = [eventData(pt, trace2)];
                    Fx.click(gd, d3.event);
                }

                slicePath.enter().append('path')
                    .classed('surface', true)
                    .style({'pointer-events': 'all'});

                sliceTop.select('path.textline').remove();

                sliceTop
                    .on('mouseover', handleMouseOver)
                    .on('mouseout', handleMouseOut)
                    .on('click', handleClick);

                if(trace.pull) {
                    var pull = +helpers.castOption(trace.pull, pt.pts) || 0;
                    if(pull > 0) {
                        cx += pull * pt.pxmid[0];
                        cy += pull * pt.pxmid[1];
                    }
                }

                pt.cxFinal = cx;
                pt.cyFinal = cy;

                function arc(start, finish, cw, scale) {
                    return 'a' + (scale * cd0.r) + ',' + (scale * cd0.r) + ' 0 ' +
                        pt.largeArc + (cw ? ' 1 ' : ' 0 ') +
                        (scale * (finish[0] - start[0])) + ',' + (scale * (finish[1] - start[1]));
                }

                var hole = trace.hole;
                if(pt.v === cd0.vTotal) { // 100% fails bcs arc start and end are identical
                    var outerCircle = 'M' + (cx + pt.px0[0]) + ',' + (cy + pt.px0[1]) +
                        arc(pt.px0, pt.pxmid, true, 1) +
                        arc(pt.pxmid, pt.px0, true, 1) + 'Z';
                    if(hole) {
                        slicePath.attr('d',
                            'M' + (cx + hole * pt.px0[0]) + ',' + (cy + hole * pt.px0[1]) +
                            arc(pt.px0, pt.pxmid, false, hole) +
                            arc(pt.pxmid, pt.px0, false, hole) +
                            'Z' + outerCircle);
                    }
                    else slicePath.attr('d', outerCircle);
                } else {

                    var outerArc = arc(pt.px0, pt.px1, true, 1);

                    if(hole) {
                        var rim = 1 - hole;
                        slicePath.attr('d',
                            'M' + (cx + hole * pt.px1[0]) + ',' + (cy + hole * pt.px1[1]) +
                            arc(pt.px1, pt.px0, false, hole) +
                            'l' + (rim * pt.px0[0]) + ',' + (rim * pt.px0[1]) +
                            outerArc +
                            'Z');
                    } else {
                        slicePath.attr('d',
                            'M' + cx + ',' + cy +
                            'l' + pt.px0[0] + ',' + pt.px0[1] +
                            outerArc +
                            'Z');
                    }
                }

                // add text
                var textPosition = helpers.castOption(trace.textposition, pt.pts);
                var sliceTextGroup = sliceTop.selectAll('g.slicetext')
                    .data(pt.text && (textPosition !== 'none') ? [0] : []);

                sliceTextGroup.enter().append('g')
                    .classed('slicetext', true);
                sliceTextGroup.exit().remove();

                sliceTextGroup.each(function() {
                    var sliceText = Lib.ensureSingle(d3.select(this), 'text', '', function(s) {
                        // prohibit tex interpretation until we can handle
                        // tex and regular text together
                        s.attr('data-notex', 1);
                    });

                    sliceText.text(pt.text)
                        .attr({
                            'class': 'slicetext',
                            transform: '',
                            'text-anchor': 'middle'
                        })
                        .call(Drawing.font, textPosition === 'outside' ?
                          determineOutsideTextFont(trace, pt, gd._fullLayout.font) :
                          determineInsideTextFont(trace, pt, gd._fullLayout.font))
                        .call(svgTextUtils.convertToTspans, gd);

                    // position the text relative to the slice
                    var textBB = Drawing.bBox(sliceText.node());
                    var transform;

                    if(textPosition === 'outside') {
                        transform = transformOutsideText(textBB, pt);
                    } else {
                        transform = transformInsideText(textBB, pt, cd0);
                        if(textPosition === 'auto' && transform.scale < 1) {
                            sliceText.call(Drawing.font, trace.outsidetextfont);
                            if(trace.outsidetextfont.family !== trace.insidetextfont.family ||
                                    trace.outsidetextfont.size !== trace.insidetextfont.size) {
                                textBB = Drawing.bBox(sliceText.node());
                            }
                            transform = transformOutsideText(textBB, pt);
                        }
                    }

                    var translateX = cx + pt.pxmid[0] * transform.rCenter + (transform.x || 0);
                    var translateY = cy + pt.pxmid[1] * transform.rCenter + (transform.y || 0);

                    // save some stuff to use later ensure no labels overlap
                    if(transform.outside) {
                        pt.yLabelMin = translateY - textBB.height / 2;
                        pt.yLabelMid = translateY;
                        pt.yLabelMax = translateY + textBB.height / 2;
                        pt.labelExtraX = 0;
                        pt.labelExtraY = 0;
                        hasOutsideText = true;
                    }

                    sliceText.attr('transform',
                        'translate(' + translateX + ',' + translateY + ')' +
                        (transform.scale < 1 ? ('scale(' + transform.scale + ')') : '') +
                        (transform.rotate ? ('rotate(' + transform.rotate + ')') : '') +
                        'translate(' +
                            (-(textBB.left + textBB.right) / 2) + ',' +
                            (-(textBB.top + textBB.bottom) / 2) +
                        ')');
                });
            });

            // add the title
            var titleTextGroup = d3.select(this).selectAll('g.titletext')
                .data(trace.title.text ? [0] : []);

            titleTextGroup.enter().append('g')
                .classed('titletext', true);
            titleTextGroup.exit().remove();

            titleTextGroup.each(function() {
                var titleText = Lib.ensureSingle(d3.select(this), 'text', '', function(s) {
                    // prohibit tex interpretation as above
                    s.attr('data-notex', 1);
                });

                var txt = fullLayout.meta ?
                    Lib.templateString(trace.title.text, {meta: fullLayout.meta}) :
                    trace.title.text;

                titleText.text(txt)
                    .attr({
                        'class': 'titletext',
                        transform: '',
                        'text-anchor': 'middle',
                    })
                .call(Drawing.font, trace.title.font)
                .call(svgTextUtils.convertToTspans, gd);

                var transform;

                if(trace.title.position === 'middle center') {
                    transform = positionTitleInside(cd0);
                } else {
                    transform = positionTitleOutside(cd0, fullLayout._size);
                }

                titleText.attr('transform',
                    'translate(' + transform.x + ',' + transform.y + ')' +
                    (transform.scale < 1 ? ('scale(' + transform.scale + ')') : '') +
                    'translate(' + transform.tx + ',' + transform.ty + ')');
            });

            // now make sure no labels overlap (at least within one pie)
            if(hasOutsideText) scootLabels(quadrants, trace);
            slices.each(function(pt) {
                if(pt.labelExtraX || pt.labelExtraY) {
                    // first move the text to its new location
                    var sliceTop = d3.select(this);
                    var sliceText = sliceTop.select('g.slicetext text');

                    sliceText.attr('transform', 'translate(' + pt.labelExtraX + ',' + pt.labelExtraY + ')' +
                        sliceText.attr('transform'));

                    // then add a line to the new location
                    var lineStartX = pt.cxFinal + pt.pxmid[0];
                    var lineStartY = pt.cyFinal + pt.pxmid[1];
                    var textLinePath = 'M' + lineStartX + ',' + lineStartY;
                    var finalX = (pt.yLabelMax - pt.yLabelMin) * (pt.pxmid[0] < 0 ? -1 : 1) / 4;

                    if(pt.labelExtraX) {
                        var yFromX = pt.labelExtraX * pt.pxmid[1] / pt.pxmid[0];
                        var yNet = pt.yLabelMid + pt.labelExtraY - (pt.cyFinal + pt.pxmid[1]);

                        if(Math.abs(yFromX) > Math.abs(yNet)) {
                            textLinePath +=
                                'l' + (yNet * pt.pxmid[0] / pt.pxmid[1]) + ',' + yNet +
                                'H' + (lineStartX + pt.labelExtraX + finalX);
                        } else {
                            textLinePath += 'l' + pt.labelExtraX + ',' + yFromX +
                                'v' + (yNet - yFromX) +
                                'h' + finalX;
                        }
                    } else {
                        textLinePath +=
                            'V' + (pt.yLabelMid + pt.labelExtraY) +
                            'h' + finalX;
                    }

                    sliceTop.append('path')
                        .classed('textline', true)
                        .call(Color.stroke, trace.outsidetextfont.color)
                        .attr({
                            'stroke-width': Math.min(2, trace.outsidetextfont.size / 8),
                            d: textLinePath,
                            fill: 'none'
                        });
                }
            });
        });
    });

    // This is for a bug in Chrome (as of 2015-07-22, and does not affect FF)
    // if insidetextfont and outsidetextfont are different sizes, sometimes the size
    // of an "em" gets taken from the wrong element at first so lines are
    // spaced wrong. You just have to tell it to try again later and it gets fixed.
    // I have no idea why we haven't seen this in other contexts. Also, sometimes
    // it gets the initial draw correct but on redraw it gets confused.
    setTimeout(function() {
        pieGroups.selectAll('tspan').each(function() {
            var s = d3.select(this);
            if(s.attr('dy')) s.attr('dy', s.attr('dy'));
        });
    }, 0);
};

function determineOutsideTextFont(trace, pt, layoutFont) {
    var color = helpers.castOption(trace.outsidetextfont.color, pt.pts) ||
      helpers.castOption(trace.textfont.color, pt.pts) ||
      layoutFont.color;

    var family = helpers.castOption(trace.outsidetextfont.family, pt.pts) ||
      helpers.castOption(trace.textfont.family, pt.pts) ||
      layoutFont.family;

    var size = helpers.castOption(trace.outsidetextfont.size, pt.pts) ||
      helpers.castOption(trace.textfont.size, pt.pts) ||
      layoutFont.size;

    return {
        color: color,
        family: family,
        size: size
    };
}

function determineInsideTextFont(trace, pt, layoutFont) {
    var customColor = helpers.castOption(trace.insidetextfont.color, pt.pts);
    if(!customColor && trace._input.textfont) {

        // Why not simply using trace.textfont? Because if not set, it
        // defaults to layout.font which has a default color. But if
        // textfont.color and insidetextfont.color don't supply a value,
        // a contrasting color shall be used.
        customColor = helpers.castOption(trace._input.textfont.color, pt.pts);
    }

    var family = helpers.castOption(trace.insidetextfont.family, pt.pts) ||
      helpers.castOption(trace.textfont.family, pt.pts) ||
      layoutFont.family;

    var size = helpers.castOption(trace.insidetextfont.size, pt.pts) ||
      helpers.castOption(trace.textfont.size, pt.pts) ||
      layoutFont.size;

    return {
        color: customColor || Color.contrast(pt.color),
        family: family,
        size: size
    };
}

function prerenderTitles(cdpie, gd) {
    var fullLayout = gd._fullLayout;

    var cd0, trace;
    // Determine the width and height of the title for each pie.
    for(var i = 0; i < cdpie.length; i++) {
        cd0 = cdpie[i][0];
        trace = cd0.trace;

        if(trace.title.text) {
            var txt = fullLayout.meta ?
                Lib.templateString(trace.title.text, {meta: fullLayout.meta}) :
                trace.title.text;

            var dummyTitle = Drawing.tester.append('text')
              .attr('data-notex', 1)
              .text(txt)
              .call(Drawing.font, trace.title.font)
              .call(svgTextUtils.convertToTspans, gd);
            var bBox = Drawing.bBox(dummyTitle.node(), true);
            cd0.titleBox = {
                width: bBox.width,
                height: bBox.height,
            };
            dummyTitle.remove();
        }
    }
}

function transformInsideText(textBB, pt, cd0) {
    var textDiameter = Math.sqrt(textBB.width * textBB.width + textBB.height * textBB.height);
    var textAspect = textBB.width / textBB.height;
    var halfAngle = Math.PI * Math.min(pt.v / cd0.vTotal, 0.5);
    var ring = 1 - cd0.trace.hole;
    var rInscribed = getInscribedRadiusFraction(pt, cd0);

    // max size text can be inserted inside without rotating it
    // this inscribes the text rectangle in a circle, which is then inscribed
    // in the slice, so it will be an underestimate, which some day we may want
    // to improve so this case can get more use
    var transform = {
        scale: rInscribed * cd0.r * 2 / textDiameter,

        // and the center position and rotation in this case
        rCenter: 1 - rInscribed,
        rotate: 0
    };

    if(transform.scale >= 1) return transform;

        // max size if text is rotated radially
    var Qr = textAspect + 1 / (2 * Math.tan(halfAngle));
    var maxHalfHeightRotRadial = cd0.r * Math.min(
        1 / (Math.sqrt(Qr * Qr + 0.5) + Qr),
        ring / (Math.sqrt(textAspect * textAspect + ring / 2) + textAspect)
    );
    var radialTransform = {
        scale: maxHalfHeightRotRadial * 2 / textBB.height,
        rCenter: Math.cos(maxHalfHeightRotRadial / cd0.r) -
            maxHalfHeightRotRadial * textAspect / cd0.r,
        rotate: (180 / Math.PI * pt.midangle + 720) % 180 - 90
    };

        // max size if text is rotated tangentially
    var aspectInv = 1 / textAspect;
    var Qt = aspectInv + 1 / (2 * Math.tan(halfAngle));
    var maxHalfWidthTangential = cd0.r * Math.min(
        1 / (Math.sqrt(Qt * Qt + 0.5) + Qt),
        ring / (Math.sqrt(aspectInv * aspectInv + ring / 2) + aspectInv)
    );
    var tangentialTransform = {
        scale: maxHalfWidthTangential * 2 / textBB.width,
        rCenter: Math.cos(maxHalfWidthTangential / cd0.r) -
            maxHalfWidthTangential / textAspect / cd0.r,
        rotate: (180 / Math.PI * pt.midangle + 810) % 180 - 90
    };
    // if we need a rotated transform, pick the biggest one
    // even if both are bigger than 1
    var rotatedTransform = tangentialTransform.scale > radialTransform.scale ?
            tangentialTransform : radialTransform;

    if(transform.scale < 1 && rotatedTransform.scale > transform.scale) return rotatedTransform;
    return transform;
}

function getInscribedRadiusFraction(pt, cd0) {
    if(pt.v === cd0.vTotal && !cd0.trace.hole) return 1;// special case of 100% with no hole

    var halfAngle = Math.PI * Math.min(pt.v / cd0.vTotal, 0.5);
    return Math.min(1 / (1 + 1 / Math.sin(halfAngle)), (1 - cd0.trace.hole) / 2);
}

function transformOutsideText(textBB, pt) {
    var x = pt.pxmid[0];
    var y = pt.pxmid[1];
    var dx = textBB.width / 2;
    var dy = textBB.height / 2;

    if(x < 0) dx *= -1;
    if(y < 0) dy *= -1;

    return {
        scale: 1,
        rCenter: 1,
        rotate: 0,
        x: dx + Math.abs(dy) * (dx > 0 ? 1 : -1) / 2,
        y: dy / (1 + x * x / (y * y)),
        outside: true
    };
}

function positionTitleInside(cd0) {
    var textDiameter =
        Math.sqrt(cd0.titleBox.width * cd0.titleBox.width + cd0.titleBox.height * cd0.titleBox.height);
    return {
        x: cd0.cx,
        y: cd0.cy,
        scale: cd0.trace.hole * cd0.r * 2 / textDiameter,
        tx: 0,
        ty: - cd0.titleBox.height / 2 + cd0.trace.title.font.size
    };
}

function positionTitleOutside(cd0, plotSize) {
    var scaleX = 1;
    var scaleY = 1;
    var maxWidth, maxPull;

    var trace = cd0.trace;
    // position of the baseline point of the text box in the plot, before scaling.
    // we anchored the text in the middle, so the baseline is on the bottom middle
    // of the first line of text.
    var topMiddle = {
        x: cd0.cx,
        y: cd0.cy
    };
    // relative translation of the text box after scaling
    var translate = {
        tx: 0,
        ty: 0
    };

    // we reason below as if the baseline is the top middle point of the text box.
    // so we must add the font size to approximate the y-coord. of the top.
    // note that this correction must happen after scaling.
    translate.ty += trace.title.font.size;
    maxPull = getMaxPull(trace);

    if(trace.title.position.indexOf('top') !== -1) {
        topMiddle.y -= (1 + maxPull) * cd0.r;
        translate.ty -= cd0.titleBox.height;
    }
    else if(trace.title.position.indexOf('bottom') !== -1) {
        topMiddle.y += (1 + maxPull) * cd0.r;
    }

    if(trace.title.position.indexOf('left') !== -1) {
        // we start the text at the left edge of the pie
        maxWidth = plotSize.w * (trace.domain.x[1] - trace.domain.x[0]) / 2 + cd0.r;
        topMiddle.x -= (1 + maxPull) * cd0.r;
        translate.tx += cd0.titleBox.width / 2;
    } else if(trace.title.position.indexOf('center') !== -1) {
        maxWidth = plotSize.w * (trace.domain.x[1] - trace.domain.x[0]);
    } else if(trace.title.position.indexOf('right') !== -1) {
        maxWidth = plotSize.w * (trace.domain.x[1] - trace.domain.x[0]) / 2 + cd0.r;
        topMiddle.x += (1 + maxPull) * cd0.r;
        translate.tx -= cd0.titleBox.width / 2;
    }
    scaleX = maxWidth / cd0.titleBox.width;
    scaleY = getTitleSpace(cd0, plotSize) / cd0.titleBox.height;
    return {
        x: topMiddle.x,
        y: topMiddle.y,
        scale: Math.min(scaleX, scaleY),
        tx: translate.tx,
        ty: translate.ty
    };
}

function getTitleSpace(cd0, plotSize) {
    var trace = cd0.trace;
    var pieBoxHeight = plotSize.h * (trace.domain.y[1] - trace.domain.y[0]);
    // use at most half of the plot for the title
    return Math.min(cd0.titleBox.height, pieBoxHeight / 2);
}

function getMaxPull(trace) {
    var maxPull = trace.pull;
    var j;
    if(Array.isArray(maxPull)) {
        maxPull = 0;
        for(j = 0; j < trace.pull.length; j++) {
            if(trace.pull[j] > maxPull) maxPull = trace.pull[j];
        }
    }
    return maxPull;
}

function scootLabels(quadrants, trace) {
    var xHalf, yHalf, equatorFirst, farthestX, farthestY,
        xDiffSign, yDiffSign, thisQuad, oppositeQuad,
        wholeSide, i, thisQuadOutside, firstOppositeOutsidePt;

    function topFirst(a, b) { return a.pxmid[1] - b.pxmid[1]; }
    function bottomFirst(a, b) { return b.pxmid[1] - a.pxmid[1]; }

    function scootOneLabel(thisPt, prevPt) {
        if(!prevPt) prevPt = {};

        var prevOuterY = prevPt.labelExtraY + (yHalf ? prevPt.yLabelMax : prevPt.yLabelMin);
        var thisInnerY = yHalf ? thisPt.yLabelMin : thisPt.yLabelMax;
        var thisOuterY = yHalf ? thisPt.yLabelMax : thisPt.yLabelMin;
        var thisSliceOuterY = thisPt.cyFinal + farthestY(thisPt.px0[1], thisPt.px1[1]);
        var newExtraY = prevOuterY - thisInnerY;

        var xBuffer, i, otherPt, otherOuterY, otherOuterX, newExtraX;

        // make sure this label doesn't overlap other labels
        // this *only* has us move these labels vertically
        if(newExtraY * yDiffSign > 0) thisPt.labelExtraY = newExtraY;

        // make sure this label doesn't overlap any slices
        if(!Array.isArray(trace.pull)) return; // this can only happen with array pulls

        for(i = 0; i < wholeSide.length; i++) {
            otherPt = wholeSide[i];

            // overlap can only happen if the other point is pulled more than this one
            if(otherPt === thisPt || (
                (helpers.castOption(trace.pull, thisPt.pts) || 0) >=
                (helpers.castOption(trace.pull, otherPt.pts) || 0))
            ) {
                continue;
            }

            if((thisPt.pxmid[1] - otherPt.pxmid[1]) * yDiffSign > 0) {
                // closer to the equator - by construction all of these happen first
                // move the text vertically to get away from these slices
                otherOuterY = otherPt.cyFinal + farthestY(otherPt.px0[1], otherPt.px1[1]);
                newExtraY = otherOuterY - thisInnerY - thisPt.labelExtraY;

                if(newExtraY * yDiffSign > 0) thisPt.labelExtraY += newExtraY;

            } else if((thisOuterY + thisPt.labelExtraY - thisSliceOuterY) * yDiffSign > 0) {
                // farther from the equator - happens after we've done all the
                // vertical moving we're going to do
                // move horizontally to get away from these more polar slices

                // if we're moving horz. based on a slice that's several slices away from this one
                // then we need some extra space for the lines to labels between them
                xBuffer = 3 * xDiffSign * Math.abs(i - wholeSide.indexOf(thisPt));

                otherOuterX = otherPt.cxFinal + farthestX(otherPt.px0[0], otherPt.px1[0]);
                newExtraX = otherOuterX + xBuffer - (thisPt.cxFinal + thisPt.pxmid[0]) - thisPt.labelExtraX;

                if(newExtraX * xDiffSign > 0) thisPt.labelExtraX += newExtraX;
            }
        }
    }

    for(yHalf = 0; yHalf < 2; yHalf++) {
        equatorFirst = yHalf ? topFirst : bottomFirst;
        farthestY = yHalf ? Math.max : Math.min;
        yDiffSign = yHalf ? 1 : -1;

        for(xHalf = 0; xHalf < 2; xHalf++) {
            farthestX = xHalf ? Math.max : Math.min;
            xDiffSign = xHalf ? 1 : -1;

            // first sort the array
            // note this is a copy of cd, so cd itself doesn't get sorted
            // but we can still modify points in place.
            thisQuad = quadrants[yHalf][xHalf];
            thisQuad.sort(equatorFirst);

            oppositeQuad = quadrants[1 - yHalf][xHalf];
            wholeSide = oppositeQuad.concat(thisQuad);

            thisQuadOutside = [];
            for(i = 0; i < thisQuad.length; i++) {
                if(thisQuad[i].yLabelMid !== undefined) thisQuadOutside.push(thisQuad[i]);
            }

            firstOppositeOutsidePt = false;
            for(i = 0; yHalf && i < oppositeQuad.length; i++) {
                if(oppositeQuad[i].yLabelMid !== undefined) {
                    firstOppositeOutsidePt = oppositeQuad[i];
                    break;
                }
            }

            // each needs to avoid the previous
            for(i = 0; i < thisQuadOutside.length; i++) {
                var prevPt = i && thisQuadOutside[i - 1];
                // bottom half needs to avoid the first label of the top half
                // top half we still need to call scootOneLabel on the first slice
                // so we can avoid other slices, but we don't pass a prevPt
                if(firstOppositeOutsidePt && !i) prevPt = firstOppositeOutsidePt;
                scootOneLabel(thisQuadOutside[i], prevPt);
            }
        }
    }
}

function scalePies(cdpie, plotSize) {
    var scaleGroups = [];

    var pieBoxWidth, pieBoxHeight, i, j, cd0, trace,
        maxPull, scaleGroup, minPxPerValUnit;

    // first figure out the center and maximum radius for each pie
    for(i = 0; i < cdpie.length; i++) {
        cd0 = cdpie[i][0];
        trace = cd0.trace;

        pieBoxWidth = plotSize.w * (trace.domain.x[1] - trace.domain.x[0]);
        pieBoxHeight = plotSize.h * (trace.domain.y[1] - trace.domain.y[0]);
        // leave some space for the title, if it will be displayed outside
        if(trace.title.text && trace.title.position !== 'middle center') {
            pieBoxHeight -= getTitleSpace(cd0, plotSize);
        }

        maxPull = getMaxPull(trace);

        cd0.r = Math.min(pieBoxWidth, pieBoxHeight) / (2 + 2 * maxPull);

        cd0.cx = plotSize.l + plotSize.w * (trace.domain.x[1] + trace.domain.x[0]) / 2;
        cd0.cy = plotSize.t + plotSize.h * (1 - trace.domain.y[0]) - pieBoxHeight / 2;
        if(trace.title.text && trace.title.position.indexOf('bottom') !== -1) {
            cd0.cy -= getTitleSpace(cd0, plotSize);
        }

        if(trace.scalegroup && scaleGroups.indexOf(trace.scalegroup) === -1) {
            scaleGroups.push(trace.scalegroup);
        }
    }

    // Then scale any pies that are grouped
    for(j = 0; j < scaleGroups.length; j++) {
        minPxPerValUnit = Infinity;
        scaleGroup = scaleGroups[j];

        for(i = 0; i < cdpie.length; i++) {
            cd0 = cdpie[i][0];
            if(cd0.trace.scalegroup === scaleGroup) {
                minPxPerValUnit = Math.min(minPxPerValUnit,
                    cd0.r * cd0.r / cd0.vTotal);
            }
        }

        for(i = 0; i < cdpie.length; i++) {
            cd0 = cdpie[i][0];
            if(cd0.trace.scalegroup === scaleGroup) {
                cd0.r = Math.sqrt(minPxPerValUnit * cd0.vTotal);
            }
        }
    }

}

function setCoords(cd) {
    var cd0 = cd[0];
    var trace = cd0.trace;
    var currentAngle = trace.rotation * Math.PI / 180;
    var angleFactor = 2 * Math.PI / cd0.vTotal;
    var firstPt = 'px0';
    var lastPt = 'px1';

    var i, cdi, currentCoords;

    if(trace.direction === 'counterclockwise') {
        for(i = 0; i < cd.length; i++) {
            if(!cd[i].hidden) break; // find the first non-hidden slice
        }
        if(i === cd.length) return; // all slices hidden

        currentAngle += angleFactor * cd[i].v;
        angleFactor *= -1;
        firstPt = 'px1';
        lastPt = 'px0';
    }

    function getCoords(angle) {
        return [cd0.r * Math.sin(angle), -cd0.r * Math.cos(angle)];
    }

    currentCoords = getCoords(currentAngle);

    for(i = 0; i < cd.length; i++) {
        cdi = cd[i];
        if(cdi.hidden) continue;

        cdi[firstPt] = currentCoords;

        currentAngle += angleFactor * cdi.v / 2;
        cdi.pxmid = getCoords(currentAngle);
        cdi.midangle = currentAngle;

        currentAngle += angleFactor * cdi.v / 2;
        currentCoords = getCoords(currentAngle);

        cdi[lastPt] = currentCoords;

        cdi.largeArc = (cdi.v > cd0.vTotal / 2) ? 1 : 0;
    }
}

},{"../../components/color":571,"../../components/drawing":592,"../../components/fx":610,"../../lib":694,"../../lib/svg_text_utils":718,"./event_data":1026,"./helpers":1027,"d3":149}],1032:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');

var styleOne = _dereq_('./style_one');

module.exports = function style(gd) {
    gd._fullLayout._pielayer.selectAll('.trace').each(function(cd) {
        var cd0 = cd[0];
        var trace = cd0.trace;
        var traceSelection = d3.select(this);

        traceSelection.style({opacity: trace.opacity});

        traceSelection.selectAll('path.surface').each(function(pt) {
            d3.select(this).call(styleOne, pt, trace);
        });
    });
};

},{"./style_one":1033,"d3":149}],1033:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Color = _dereq_('../../components/color');
var castOption = _dereq_('./helpers').castOption;

module.exports = function styleOne(s, pt, trace) {
    var line = trace.marker.line;
    var lineColor = castOption(line.color, pt.pts) || Color.defaultLine;
    var lineWidth = castOption(line.width, pt.pts) || 0;

    s.style({'stroke-width': lineWidth})
        .call(Color.fill, pt.color)
        .call(Color.stroke, lineColor);
};

},{"../../components/color":571,"./helpers":1027}],1034:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterglAttrs = _dereq_('../scatter/attributes');

module.exports = {
    x: scatterglAttrs.x,
    y: scatterglAttrs.y,
    xy: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    indices: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    xbounds: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    ybounds: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    text: scatterglAttrs.text,
    marker: {
        color: {
            valType: 'color',
            arrayOk: false,
            
            editType: 'calc',
            
        },
        opacity: {
            valType: 'number',
            min: 0,
            max: 1,
            dflt: 1,
            arrayOk: false,
            
            editType: 'calc',
            
        },
        blend: {
            valType: 'boolean',
            dflt: null,
            
            editType: 'calc',
            
        },
        sizemin: {
            valType: 'number',
            min: 0.1,
            max: 2,
            dflt: 0.5,
            
            editType: 'calc',
            
        },
        sizemax: {
            valType: 'number',
            min: 0.1,
            dflt: 20,
            
            editType: 'calc',
            
        },
        border: {
            color: {
                valType: 'color',
                arrayOk: false,
                
                editType: 'calc',
                
            },
            arearatio: {
                valType: 'number',
                min: 0,
                max: 1,
                dflt: 0,
                
                editType: 'calc',
                
            },
            editType: 'calc'
        },
        editType: 'calc'
    },
    transforms: undefined
};

},{"../scatter/attributes":1047}],1035:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var createPointCloudRenderer = _dereq_('gl-pointcloud2d');

var str2RGBArray = _dereq_('../../lib/str2rgbarray');
var findExtremes = _dereq_('../../plots/cartesian/autorange').findExtremes;
var getTraceColor = _dereq_('../scatter/get_trace_color');

function Pointcloud(scene, uid) {
    this.scene = scene;
    this.uid = uid;
    this.type = 'pointcloud';

    this.pickXData = [];
    this.pickYData = [];
    this.xData = [];
    this.yData = [];
    this.textLabels = [];
    this.color = 'rgb(0, 0, 0)';
    this.name = '';
    this.hoverinfo = 'all';

    this.idToIndex = new Int32Array(0);
    this.bounds = [0, 0, 0, 0];

    this.pointcloudOptions = {
        positions: new Float32Array(0),
        idToIndex: this.idToIndex,
        sizemin: 0.5,
        sizemax: 12,
        color: [0, 0, 0, 1],
        areaRatio: 1,
        borderColor: [0, 0, 0, 1]
    };
    this.pointcloud = createPointCloudRenderer(scene.glplot, this.pointcloudOptions);
    this.pointcloud._trace = this; // scene2d requires this prop
}

var proto = Pointcloud.prototype;

proto.handlePick = function(pickResult) {
    var index = this.idToIndex[pickResult.pointId];

    // prefer the readout from XY, if present
    return {
        trace: this,
        dataCoord: pickResult.dataCoord,
        traceCoord: this.pickXYData ?
            [this.pickXYData[index * 2], this.pickXYData[index * 2 + 1]] :
            [this.pickXData[index], this.pickYData[index]],
        textLabel: Array.isArray(this.textLabels) ?
            this.textLabels[index] :
            this.textLabels,
        color: this.color,
        name: this.name,
        pointIndex: index,
        hoverinfo: this.hoverinfo
    };
};

proto.update = function(options) {
    this.index = options.index;
    this.textLabels = options.text;
    this.name = options.name;
    this.hoverinfo = options.hoverinfo;
    this.bounds = [Infinity, Infinity, -Infinity, -Infinity];

    this.updateFast(options);

    this.color = getTraceColor(options, {});
};

proto.updateFast = function(options) {
    var x = this.xData = this.pickXData = options.x;
    var y = this.yData = this.pickYData = options.y;
    var xy = this.pickXYData = options.xy;

    var userBounds = options.xbounds && options.ybounds;
    var index = options.indices;

    var len;
    var idToIndex;
    var positions;
    var bounds = this.bounds;

    var xx, yy, i;

    if(xy) {

        positions = xy;

        // dividing xy.length by 2 and truncating to integer if xy.length was not even
        len = xy.length >>> 1;

        if(userBounds) {

            bounds[0] = options.xbounds[0];
            bounds[2] = options.xbounds[1];
            bounds[1] = options.ybounds[0];
            bounds[3] = options.ybounds[1];

        } else {

            for(i = 0; i < len; i++) {

                xx = positions[i * 2];
                yy = positions[i * 2 + 1];

                if(xx < bounds[0]) bounds[0] = xx;
                if(xx > bounds[2]) bounds[2] = xx;
                if(yy < bounds[1]) bounds[1] = yy;
                if(yy > bounds[3]) bounds[3] = yy;
            }

        }

        if(index) {

            idToIndex = index;

        } else {

            idToIndex = new Int32Array(len);

            for(i = 0; i < len; i++) {

                idToIndex[i] = i;

            }

        }

    } else {

        len = x.length;

        positions = new Float32Array(2 * len);
        idToIndex = new Int32Array(len);

        for(i = 0; i < len; i++) {
            xx = x[i];
            yy = y[i];

            idToIndex[i] = i;

            positions[i * 2] = xx;
            positions[i * 2 + 1] = yy;

            if(xx < bounds[0]) bounds[0] = xx;
            if(xx > bounds[2]) bounds[2] = xx;
            if(yy < bounds[1]) bounds[1] = yy;
            if(yy > bounds[3]) bounds[3] = yy;
        }

    }

    this.idToIndex = idToIndex;
    this.pointcloudOptions.idToIndex = idToIndex;

    this.pointcloudOptions.positions = positions;

    var markerColor = str2RGBArray(options.marker.color);
    var borderColor = str2RGBArray(options.marker.border.color);
    var opacity = options.opacity * options.marker.opacity;

    markerColor[3] *= opacity;
    this.pointcloudOptions.color = markerColor;

    // detect blending from the number of points, if undefined
    // because large data with blending hits performance
    var blend = options.marker.blend;
    if(blend === null) {
        var maxPoints = 100;
        blend = x.length < maxPoints || y.length < maxPoints;
    }
    this.pointcloudOptions.blend = blend;

    borderColor[3] *= opacity;
    this.pointcloudOptions.borderColor = borderColor;

    var markerSizeMin = options.marker.sizemin;
    var markerSizeMax = Math.max(options.marker.sizemax, options.marker.sizemin);
    this.pointcloudOptions.sizeMin = markerSizeMin;
    this.pointcloudOptions.sizeMax = markerSizeMax;
    this.pointcloudOptions.areaRatio = options.marker.border.arearatio;

    this.pointcloud.update(this.pointcloudOptions);

    // add item for autorange routine
    var xa = this.scene.xaxis;
    var ya = this.scene.yaxis;
    var pad = markerSizeMax / 2 || 0.5;
    options._extremes[xa._id] = findExtremes(xa, [bounds[0], bounds[2]], {ppad: pad});
    options._extremes[ya._id] = findExtremes(ya, [bounds[1], bounds[3]], {ppad: pad});
};

proto.dispose = function() {
    this.pointcloud.dispose();
};

function createPointcloud(scene, data) {
    var plot = new Pointcloud(scene, data.uid);
    plot.update(data);
    return plot;
}

module.exports = createPointcloud;

},{"../../lib/str2rgbarray":717,"../../plots/cartesian/autorange":741,"../scatter/get_trace_color":1057,"gl-pointcloud2d":281}],1036:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    coerce('x');
    coerce('y');

    coerce('xbounds');
    coerce('ybounds');

    if(traceIn.xy && traceIn.xy instanceof Float32Array) {
        traceOut.xy = traceIn.xy;
    }

    if(traceIn.indices && traceIn.indices instanceof Int32Array) {
        traceOut.indices = traceIn.indices;
    }

    coerce('text');
    coerce('marker.color', defaultColor);
    coerce('marker.opacity');
    coerce('marker.blend');
    coerce('marker.sizemin');
    coerce('marker.sizemax');
    coerce('marker.border.color', defaultColor);
    coerce('marker.border.arearatio');

    // disable 1D transforms - that would defeat the purpose of this trace type, performance!
    traceOut._length = null;
};

},{"../../lib":694,"./attributes":1034}],1037:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var pointcloud = {};

pointcloud.attributes = _dereq_('./attributes');
pointcloud.supplyDefaults = _dereq_('./defaults');

// reuse the Scatter3D 'dummy' calc step so that legends know what to do
pointcloud.calc = _dereq_('../scatter3d/calc');
pointcloud.plot = _dereq_('./convert');

pointcloud.moduleType = 'trace';
pointcloud.name = 'pointcloud';
pointcloud.basePlotModule = _dereq_('../../plots/gl2d');
pointcloud.categories = ['gl', 'gl2d', 'showLegend'];
pointcloud.meta = {
    
};

module.exports = pointcloud;

},{"../../plots/gl2d":782,"../scatter3d/calc":1075,"./attributes":1034,"./convert":1035,"./defaults":1036}],1038:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = _dereq_('../../plots/font_attributes');
var plotAttrs = _dereq_('../../plots/attributes');
var colorAttrs = _dereq_('../../components/color/attributes');
var fxAttrs = _dereq_('../../components/fx/attributes');
var domainAttrs = _dereq_('../../plots/domain').attributes;
var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;

var attrs = module.exports = overrideAll({
    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
        flags: [],
        arrayOk: false,
        
    }),
    hoverlabel: fxAttrs.hoverlabel,
    domain: domainAttrs({name: 'sankey', trace: true}),

    orientation: {
        valType: 'enumerated',
        values: ['v', 'h'],
        dflt: 'h',
        
        
    },

    valueformat: {
        valType: 'string',
        dflt: '.3s',
        
        
    },

    valuesuffix: {
        valType: 'string',
        dflt: '',
        
        
    },

    arrangement: {
        valType: 'enumerated',
        values: ['snap', 'perpendicular', 'freeform', 'fixed'],
        dflt: 'snap',
        
        
    },

    textfont: fontAttrs({
        
    }),

    node: {
        label: {
            valType: 'data_array',
            dflt: [],
            
            
        },
        color: {
            valType: 'color',
            
            arrayOk: true,
            
        },
        line: {
            color: {
                valType: 'color',
                
                dflt: colorAttrs.defaultLine,
                arrayOk: true,
                
            },
            width: {
                valType: 'number',
                
                min: 0,
                dflt: 0.5,
                arrayOk: true,
                
            }
        },
        pad: {
            valType: 'number',
            arrayOk: false,
            min: 0,
            dflt: 20,
            
            
        },
        thickness: {
            valType: 'number',
            arrayOk: false,
            min: 1,
            dflt: 20,
            
            
        },
        hoverinfo: {
            valType: 'enumerated',
            values: ['all', 'none', 'skip'],
            dflt: 'all',
            
            
        },
        hoverlabel: fxAttrs.hoverlabel, // needs editType override,
        hovertemplate: hovertemplateAttrs({}, {
            
            keys: ['value', 'label']
        }),
        
    },

    link: {
        label: {
            valType: 'data_array',
            dflt: [],
            
            
        },
        color: {
            valType: 'color',
            
            arrayOk: true,
            
        },
        line: {
            color: {
                valType: 'color',
                
                dflt: colorAttrs.defaultLine,
                arrayOk: true,
                
            },
            width: {
                valType: 'number',
                
                min: 0,
                dflt: 0,
                arrayOk: true,
                
            }
        },
        source: {
            valType: 'data_array',
            
            dflt: [],
            
        },
        target: {
            valType: 'data_array',
            
            dflt: [],
            
        },
        value: {
            valType: 'data_array',
            dflt: [],
            
            
        },
        hoverinfo: {
            valType: 'enumerated',
            values: ['all', 'none', 'skip'],
            dflt: 'all',
            
            
        },
        hoverlabel: fxAttrs.hoverlabel, // needs editType override,
        hovertemplate: hovertemplateAttrs({}, {
            
            keys: ['value', 'label']
        }),
        
    }
}, 'calc', 'nested');
attrs.transforms = undefined;

},{"../../components/color/attributes":570,"../../components/fx/attributes":601,"../../components/fx/hovertemplate_attributes":609,"../../lib/extend":684,"../../plot_api/edit_types":725,"../../plots/attributes":739,"../../plots/domain":768,"../../plots/font_attributes":769}],1039:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
var getModuleCalcData = _dereq_('../../plots/get_data').getModuleCalcData;
var plot = _dereq_('./plot');
var fxAttrs = _dereq_('../../components/fx/layout_attributes');

var SANKEY = 'sankey';

exports.name = SANKEY;

exports.baseLayoutAttrOverrides = overrideAll({
    hoverlabel: fxAttrs.hoverlabel
}, 'plot', 'nested');

exports.plot = function(gd) {
    var calcData = getModuleCalcData(gd.calcdata, SANKEY)[0];
    plot(gd, calcData);
};

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var hadPlot = (oldFullLayout._has && oldFullLayout._has(SANKEY));
    var hasPlot = (newFullLayout._has && newFullLayout._has(SANKEY));

    if(hadPlot && !hasPlot) {
        oldFullLayout._paperdiv.selectAll('.sankey').remove();
    }
};

},{"../../components/fx/layout_attributes":611,"../../plot_api/edit_types":725,"../../plots/get_data":779,"./plot":1044}],1040:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var tarjan = _dereq_('strongly-connected-components');
var Lib = _dereq_('../../lib');
var wrap = _dereq_('../../lib/gup').wrap;

function circularityPresent(nodeList, sources, targets) {

    var nodeLen = nodeList.length;
    var nodes = Lib.init2dArray(nodeLen, 0);

    for(var i = 0; i < Math.min(sources.length, targets.length); i++) {
        if(Lib.isIndex(sources[i], nodeLen) && Lib.isIndex(targets[i], nodeLen)) {
            if(sources[i] === targets[i]) {
                return true; // self-link which is also a scc of one
            }
            nodes[sources[i]].push(targets[i]);
        }
    }

    var scc = tarjan(nodes);

    // Tarján's strongly connected components algorithm coded by Mikola Lysenko
    // returns at least one non-singular component if there's circularity in the graph
    return scc.components.some(function(c) {
        return c.length > 1;
    });
}

module.exports = function calc(gd, trace) {

    if(circularityPresent(trace.node.label, trace.link.source, trace.link.target)) {
        Lib.error('Circularity is present in the Sankey data. Removing all nodes and links.');
        trace.link.label = [];
        trace.link.source = [];
        trace.link.target = [];
        trace.link.value = [];
        trace.link.color = [];
        trace.node.label = [];
        trace.node.color = [];
    }

    return wrap({
        link: trace.link,
        node: trace.node
    });
};

},{"../../lib":694,"../../lib/gup":692,"strongly-connected-components":508}],1041:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    nodeTextOffsetHorizontal: 4,
    nodeTextOffsetVertical: 3,
    nodePadAcross: 10,
    sankeyIterations: 50,
    forceIterations: 5,
    forceTicksPerFrame: 10,
    duration: 500,
    ease: 'cubic-in-out',
    cn: {
        sankey: 'sankey',
        sankeyLinks: 'sankey-links',
        sankeyLink: 'sankey-link',
        sankeyNodeSet: 'sankey-node-set',
        sankeyNode: 'sankey-node',
        nodeRect: 'node-rect',
        nodeCapture: 'node-capture',
        nodeCentered: 'node-entered',
        nodeLabelGuide: 'node-label-guide',
        nodeLabel: 'node-label',
        nodeLabelTextPath: 'node-label-text-path'
    }
};

},{}],1042:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var attributes = _dereq_('./attributes');
var Color = _dereq_('../../components/color');
var tinycolor = _dereq_('tinycolor2');
var handleDomainDefaults = _dereq_('../../plots/domain').defaults;
var handleHoverLabelDefaults = _dereq_('../../components/fx/hoverlabel_defaults');
var Template = _dereq_('../../plot_api/plot_template');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var hoverlabelDefault = Lib.extendDeep(layout.hoverlabel, traceIn.hoverlabel);

    // node attributes
    var nodeIn = traceIn.node;
    var nodeOut = Template.newContainer(traceOut, 'node');

    function coerceNode(attr, dflt) {
        return Lib.coerce(nodeIn, nodeOut, attributes.node, attr, dflt);
    }
    coerceNode('label');
    coerceNode('pad');
    coerceNode('thickness');
    coerceNode('line.color');
    coerceNode('line.width');
    coerceNode('hoverinfo', traceIn.hoverinfo);
    handleHoverLabelDefaults(nodeIn, nodeOut, coerceNode, hoverlabelDefault);
    coerceNode('hovertemplate');

    var colors = layout.colorway;

    var defaultNodePalette = function(i) {return colors[i % colors.length];};

    coerceNode('color', nodeOut.label.map(function(d, i) {
        return Color.addOpacity(defaultNodePalette(i), 0.8);
    }));

    // link attributes
    var linkIn = traceIn.link;
    var linkOut = Template.newContainer(traceOut, 'link');

    function coerceLink(attr, dflt) {
        return Lib.coerce(linkIn, linkOut, attributes.link, attr, dflt);
    }
    coerceLink('label');
    coerceLink('source');
    coerceLink('target');
    coerceLink('value');
    coerceLink('line.color');
    coerceLink('line.width');
    coerceLink('hoverinfo', traceIn.hoverinfo);
    handleHoverLabelDefaults(linkIn, linkOut, coerceLink, hoverlabelDefault);
    coerceLink('hovertemplate');

    var defaultLinkColor = tinycolor(layout.paper_bgcolor).getLuminance() < 0.333 ?
                'rgba(255, 255, 255, 0.6)' :
                'rgba(0, 0, 0, 0.2)';

    coerceLink('color', Lib.repeat(defaultLinkColor, linkOut.value.length));

    handleDomainDefaults(traceOut, layout, coerce);

    coerce('orientation');
    coerce('valueformat');
    coerce('valuesuffix');
    coerce('arrangement');

    Lib.coerceFont(coerce, 'textfont', Lib.extendFlat({}, layout.font));

    // disable 1D transforms - arrays here are 1D but their lengths/meanings
    // don't match, between nodes and links
    traceOut._length = null;
};

},{"../../components/color":571,"../../components/fx/hoverlabel_defaults":608,"../../lib":694,"../../plot_api/plot_template":732,"../../plots/domain":768,"./attributes":1038,"tinycolor2":515}],1043:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Plot = {};

Plot.attributes = _dereq_('./attributes');
Plot.supplyDefaults = _dereq_('./defaults');
Plot.calc = _dereq_('./calc');
Plot.plot = _dereq_('./plot');

Plot.moduleType = 'trace';
Plot.name = 'sankey';
Plot.basePlotModule = _dereq_('./base_plot');
Plot.categories = ['noOpacity'];
Plot.meta = {
    
};

module.exports = Plot;

},{"./attributes":1038,"./base_plot":1039,"./calc":1040,"./defaults":1042,"./plot":1044}],1044:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var render = _dereq_('./render');
var Fx = _dereq_('../../components/fx');
var Color = _dereq_('../../components/color');
var Lib = _dereq_('../../lib');
var cn = _dereq_('./constants').cn;

var _ = Lib._;

function renderableValuePresent(d) {return d !== '';}

function ownTrace(selection, d) {
    return selection.filter(function(s) {return s.key === d.traceId;});
}

function makeTranslucent(element, alpha) {
    d3.select(element)
        .select('path')
        .style('fill-opacity', alpha);
    d3.select(element)
        .select('rect')
        .style('fill-opacity', alpha);
}

function makeTextContrasty(element) {
    d3.select(element)
        .select('text.name')
        .style('fill', 'black');
}

function relatedLinks(d) {
    return function(l) {
        return d.node.sourceLinks.indexOf(l.link) !== -1 || d.node.targetLinks.indexOf(l.link) !== -1;
    };
}

function relatedNodes(l) {
    return function(d) {
        return d.node.sourceLinks.indexOf(l.link) !== -1 || d.node.targetLinks.indexOf(l.link) !== -1;
    };
}

function nodeHoveredStyle(sankeyNode, d, sankey) {
    if(d && sankey) {
        ownTrace(sankey, d)
            .selectAll('.' + cn.sankeyLink)
            .filter(relatedLinks(d))
            .call(linkHoveredStyle.bind(0, d, sankey, false));
    }
}

function nodeNonHoveredStyle(sankeyNode, d, sankey) {
    if(d && sankey) {
        ownTrace(sankey, d)
            .selectAll('.' + cn.sankeyLink)
            .filter(relatedLinks(d))
            .call(linkNonHoveredStyle.bind(0, d, sankey, false));
    }
}

function linkHoveredStyle(d, sankey, visitNodes, sankeyLink) {

    var label = sankeyLink.datum().link.label;

    sankeyLink.style('fill-opacity', 0.4);

    if(label) {
        ownTrace(sankey, d)
            .selectAll('.' + cn.sankeyLink)
            .filter(function(l) {return l.link.label === label;})
            .style('fill-opacity', 0.4);
    }

    if(visitNodes) {
        ownTrace(sankey, d)
            .selectAll('.' + cn.sankeyNode)
            .filter(relatedNodes(d))
            .call(nodeHoveredStyle);
    }
}

function linkNonHoveredStyle(d, sankey, visitNodes, sankeyLink) {

    var label = sankeyLink.datum().link.label;

    sankeyLink.style('fill-opacity', function(d) {return d.tinyColorAlpha;});

    if(label) {
        ownTrace(sankey, d)
            .selectAll('.' + cn.sankeyLink)
            .filter(function(l) {return l.link.label === label;})
            .style('fill-opacity', function(d) {return d.tinyColorAlpha;});
    }

    if(visitNodes) {
        ownTrace(sankey, d)
            .selectAll(cn.sankeyNode)
            .filter(relatedNodes(d))
            .call(nodeNonHoveredStyle);
    }
}

// does not support array values for now
function castHoverOption(trace, attr) {
    var labelOpts = trace.hoverlabel || {};
    var val = Lib.nestedProperty(labelOpts, attr).get();
    return Array.isArray(val) ? false : val;
}

module.exports = function plot(gd, calcData) {
    var fullLayout = gd._fullLayout;
    var svg = fullLayout._paper;
    var size = fullLayout._size;

    var linkSelect = function(element, d) {
        var evt = d.link;
        evt.originalEvent = d3.event;
        gd._hoverdata = [evt];
        Fx.click(gd, { target: true });
    };

    var linkHover = function(element, d, sankey) {
        if(gd._fullLayout.hovermode === false) return;
        d3.select(element).call(linkHoveredStyle.bind(0, d, sankey, true));
        if(d.link.trace.link.hoverinfo !== 'skip') {
            d.link.fullData = d.link.trace;
            gd.emit('plotly_hover', {
                event: d3.event,
                points: [d.link]
            });
        }

    };

    var sourceLabel = _(gd, 'source:') + ' ';
    var targetLabel = _(gd, 'target:') + ' ';
    var incomingLabel = _(gd, 'incoming flow count:') + ' ';
    var outgoingLabel = _(gd, 'outgoing flow count:') + ' ';

    var linkHoverFollow = function(element, d) {
        if(gd._fullLayout.hovermode === false) return;
        var obj = d.link.trace.link;
        if(obj.hoverinfo === 'none' || obj.hoverinfo === 'skip') return;
        var rootBBox = gd._fullLayout._paperdiv.node().getBoundingClientRect();
        var boundingBox = element.getBoundingClientRect();
        var hoverCenterX = boundingBox.left + boundingBox.width / 2;
        var hoverCenterY = boundingBox.top + boundingBox.height / 2;

        var hovertemplateLabels = {valueLabel: d3.format(d.valueFormat)(d.link.value) + d.valueSuffix};
        d.link.fullData = d.link.trace;

        var tooltip = Fx.loneHover({
            x: hoverCenterX - rootBBox.left,
            y: hoverCenterY - rootBBox.top,
            name: hovertemplateLabels.valueLabel,
            text: [
                d.link.label || '',
                sourceLabel + d.link.source.label,
                targetLabel + d.link.target.label
            ].filter(renderableValuePresent).join('<br>'),
            color: castHoverOption(obj, 'bgcolor') || Color.addOpacity(d.tinyColorHue, 1),
            borderColor: castHoverOption(obj, 'bordercolor'),
            fontFamily: castHoverOption(obj, 'font.family'),
            fontSize: castHoverOption(obj, 'font.size'),
            fontColor: castHoverOption(obj, 'font.color'),
            idealAlign: d3.event.x < hoverCenterX ? 'right' : 'left',

            hovertemplate: obj.hovertemplate,
            hovertemplateLabels: hovertemplateLabels,
            eventData: [d.link]
        }, {
            container: fullLayout._hoverlayer.node(),
            outerContainer: fullLayout._paper.node(),
            gd: gd
        });

        makeTranslucent(tooltip, 0.65);
        makeTextContrasty(tooltip);
    };

    var linkUnhover = function(element, d, sankey) {
        if(gd._fullLayout.hovermode === false) return;
        d3.select(element).call(linkNonHoveredStyle.bind(0, d, sankey, true));
        if(d.link.trace.link.hoverinfo !== 'skip') {
            d.link.fullData = d.link.trace;
            gd.emit('plotly_unhover', {
                event: d3.event,
                points: [d.link]
            });
        }

        Fx.loneUnhover(fullLayout._hoverlayer.node());
    };

    var nodeSelect = function(element, d, sankey) {
        var evt = d.node;
        evt.originalEvent = d3.event;
        gd._hoverdata = [evt];
        d3.select(element).call(nodeNonHoveredStyle, d, sankey);
        Fx.click(gd, { target: true });
    };

    var nodeHover = function(element, d, sankey) {
        if(gd._fullLayout.hovermode === false) return;
        d3.select(element).call(nodeHoveredStyle, d, sankey);
        if(d.node.trace.node.hoverinfo !== 'skip') {
            d.node.fullData = d.node.trace;
            gd.emit('plotly_hover', {
                event: d3.event,
                points: [d.node]
            });
        }
    };

    var nodeHoverFollow = function(element, d) {
        if(gd._fullLayout.hovermode === false) return;

        var obj = d.node.trace.node;
        if(obj.hoverinfo === 'none' || obj.hoverinfo === 'skip') return;
        var nodeRect = d3.select(element).select('.' + cn.nodeRect);
        var rootBBox = gd._fullLayout._paperdiv.node().getBoundingClientRect();
        var boundingBox = nodeRect.node().getBoundingClientRect();
        var hoverCenterX0 = boundingBox.left - 2 - rootBBox.left;
        var hoverCenterX1 = boundingBox.right + 2 - rootBBox.left;
        var hoverCenterY = boundingBox.top + boundingBox.height / 4 - rootBBox.top;

        var hovertemplateLabels = {valueLabel: d3.format(d.valueFormat)(d.node.value) + d.valueSuffix};
        d.node.fullData = d.node.trace;

        var tooltip = Fx.loneHover({
            x0: hoverCenterX0,
            x1: hoverCenterX1,
            y: hoverCenterY,
            name: d3.format(d.valueFormat)(d.node.value) + d.valueSuffix,
            text: [
                d.node.label,
                incomingLabel + d.node.targetLinks.length,
                outgoingLabel + d.node.sourceLinks.length
            ].filter(renderableValuePresent).join('<br>'),
            color: castHoverOption(obj, 'bgcolor') || d.tinyColorHue,
            borderColor: castHoverOption(obj, 'bordercolor'),
            fontFamily: castHoverOption(obj, 'font.family'),
            fontSize: castHoverOption(obj, 'font.size'),
            fontColor: castHoverOption(obj, 'font.color'),
            idealAlign: 'left',

            hovertemplate: obj.hovertemplate,
            hovertemplateLabels: hovertemplateLabels,
            eventData: [d.node]
        }, {
            container: fullLayout._hoverlayer.node(),
            outerContainer: fullLayout._paper.node(),
            gd: gd
        });

        makeTranslucent(tooltip, 0.85);
        makeTextContrasty(tooltip);
    };

    var nodeUnhover = function(element, d, sankey) {
        if(gd._fullLayout.hovermode === false) return;
        d3.select(element).call(nodeNonHoveredStyle, d, sankey);
        if(d.node.trace.node.hoverinfo !== 'skip') {
            d.node.fullData = d.node.trace;
            gd.emit('plotly_unhover', {
                event: d3.event,
                points: [d.node]
            });
        }

        Fx.loneUnhover(fullLayout._hoverlayer.node());
    };

    render(
        svg,
        calcData,
        {
            width: size.w,
            height: size.h,
            margin: {
                t: size.t,
                r: size.r,
                b: size.b,
                l: size.l
            }
        },
        {
            linkEvents: {
                hover: linkHover,
                follow: linkHoverFollow,
                unhover: linkUnhover,
                select: linkSelect
            },
            nodeEvents: {
                hover: nodeHover,
                follow: nodeHoverFollow,
                unhover: nodeUnhover,
                select: nodeSelect
            }
        }
    );
};

},{"../../components/color":571,"../../components/fx":610,"../../lib":694,"./constants":1041,"./render":1045,"d3":149}],1045:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var c = _dereq_('./constants');
var d3 = _dereq_('d3');
var tinycolor = _dereq_('tinycolor2');
var Color = _dereq_('../../components/color');
var Drawing = _dereq_('../../components/drawing');
var d3sankey = _dereq_('@plotly/d3-sankey').sankey;
var d3Force = _dereq_('d3-force');
var Lib = _dereq_('../../lib');
var isArrayOrTypedArray = Lib.isArrayOrTypedArray;
var isIndex = Lib.isIndex;
var gup = _dereq_('../../lib/gup');
var keyFun = gup.keyFun;
var repeat = gup.repeat;
var unwrap = gup.unwrap;

// basic data utilities

function persistOriginalPlace(nodes) {
    var i;
    var distinctLayerPositions = [];
    for(i = 0; i < nodes.length; i++) {
        nodes[i].originalX = nodes[i].x;
        nodes[i].originalY = nodes[i].y;
        if(distinctLayerPositions.indexOf(nodes[i].x) === -1) {
            distinctLayerPositions.push(nodes[i].x);
        }
    }
    distinctLayerPositions.sort(function(a, b) {return a - b;});
    for(i = 0; i < nodes.length; i++) {
        nodes[i].originalLayerIndex = distinctLayerPositions.indexOf(nodes[i].originalX);
        nodes[i].originalLayer = nodes[i].originalLayerIndex / (distinctLayerPositions.length - 1);
    }
}

function saveCurrentDragPosition(d) {
    d.lastDraggedX = d.x;
    d.lastDraggedY = d.y;
}

function sameLayer(d) {
    return function(n) {return n.node.originalX === d.node.originalX;};
}

function switchToForceFormat(nodes) {
    // force uses x, y as centers
    for(var i = 0; i < nodes.length; i++) {
        nodes[i].y = nodes[i].y + nodes[i].dy / 2;
    }
}

function switchToSankeyFormat(nodes) {
    // sankey uses x, y as top left
    for(var i = 0; i < nodes.length; i++) {
        nodes[i].y = nodes[i].y - nodes[i].dy / 2;
    }
}

// view models

function sankeyModel(layout, d, traceIndex) {
    var trace = unwrap(d).trace;
    var domain = trace.domain;
    var nodeSpec = trace.node;
    var linkSpec = trace.link;
    var arrangement = trace.arrangement;
    var horizontal = trace.orientation === 'h';
    var nodePad = trace.node.pad;
    var nodeThickness = trace.node.thickness;
    var nodeLineColor = trace.node.line.color;
    var nodeLineWidth = trace.node.line.width;
    var linkLineColor = trace.link.line.color;
    var linkLineWidth = trace.link.line.width;
    var valueFormat = trace.valueformat;
    var valueSuffix = trace.valuesuffix;
    var textFont = trace.textfont;

    var width = layout.width * (domain.x[1] - domain.x[0]);
    var height = layout.height * (domain.y[1] - domain.y[0]);

    var links = [];
    var hasLinkColorArray = isArrayOrTypedArray(linkSpec.color);
    var linkedNodes = {};

    var nodeCount = nodeSpec.label.length;
    var i;
    for(i = 0; i < linkSpec.value.length; i++) {
        var val = linkSpec.value[i];
        // remove negative values, but keep zeros with special treatment
        var source = linkSpec.source[i];
        var target = linkSpec.target[i];
        if(!(val > 0 && isIndex(source, nodeCount) && isIndex(target, nodeCount))) {
            continue;
        }

        source = +source;
        target = +target;
        linkedNodes[source] = linkedNodes[target] = true;

        links.push({
            pointNumber: i,
            label: linkSpec.label[i],
            color: hasLinkColorArray ? linkSpec.color[i] : linkSpec.color,
            source: source,
            target: target,
            value: +val
        });
    }

    var hasNodeColorArray = isArrayOrTypedArray(nodeSpec.color);
    var nodes = [];
    var removedNodes = false;
    var nodeIndices = {};
    for(i = 0; i < nodeCount; i++) {
        if(linkedNodes[i]) {
            var l = nodeSpec.label[i];
            nodeIndices[i] = nodes.length;
            nodes.push({
                pointNumber: i,
                label: l,
                color: hasNodeColorArray ? nodeSpec.color[i] : nodeSpec.color
            });
        }
        else removedNodes = true;
    }

    // need to re-index links now, since we didn't put all the nodes in
    if(removedNodes) {
        for(i = 0; i < links.length; i++) {
            links[i].source = nodeIndices[links[i].source];
            links[i].target = nodeIndices[links[i].target];
        }
    }

    var sankey = d3sankey()
        .size(horizontal ? [width, height] : [height, width])
        .nodeWidth(nodeThickness)
        .nodePadding(nodePad)
        .nodes(nodes)
        .links(links)
        .layout(c.sankeyIterations);

    if(sankey.nodePadding() < nodePad) {
        Lib.warn('node.pad was reduced to ', sankey.nodePadding(), ' to fit within the figure.');
    }

    var node;
    var sankeyNodes = sankey.nodes();
    for(var n = 0; n < sankeyNodes.length; n++) {
        node = sankeyNodes[n];
        node.width = width;
        node.height = height;
    }

    switchToForceFormat(nodes);

    return {
        key: traceIndex,
        trace: trace,
        guid: Math.floor(1e12 * (1 + Math.random())),
        horizontal: horizontal,
        width: width,
        height: height,
        nodePad: nodePad,
        nodeLineColor: nodeLineColor,
        nodeLineWidth: nodeLineWidth,
        linkLineColor: linkLineColor,
        linkLineWidth: linkLineWidth,
        valueFormat: valueFormat,
        valueSuffix: valueSuffix,
        textFont: textFont,
        translateX: domain.x[0] * layout.width + layout.margin.l,
        translateY: layout.height - domain.y[1] * layout.height + layout.margin.t,
        dragParallel: horizontal ? height : width,
        dragPerpendicular: horizontal ? width : height,
        nodes: nodes,
        links: links,
        arrangement: arrangement,
        sankey: sankey,
        forceLayouts: {},
        interactionState: {
            dragInProgress: false,
            hovered: false
        }
    };
}

function linkModel(uniqueKeys, d, l) {
    var tc = tinycolor(l.color);
    var basicKey = l.source.label + '|' + l.target.label;
    var foundKey = uniqueKeys[basicKey];
    uniqueKeys[basicKey] = (foundKey || 0) + 1;
    var key = basicKey + '__' + uniqueKeys[basicKey];

    // for event data
    l.trace = d.trace;
    l.curveNumber = d.trace.index;

    return {
        key: key,
        traceId: d.key,
        link: l,
        tinyColorHue: Color.tinyRGB(tc),
        tinyColorAlpha: tc.getAlpha(),
        linkLineColor: d.linkLineColor,
        linkLineWidth: d.linkLineWidth,
        valueFormat: d.valueFormat,
        valueSuffix: d.valueSuffix,
        sankey: d.sankey,
        interactionState: d.interactionState
    };
}

function nodeModel(uniqueKeys, d, n) {
    var tc = tinycolor(n.color);
    var zoneThicknessPad = c.nodePadAcross;
    var zoneLengthPad = d.nodePad / 2;
    var visibleThickness = n.dx;
    var visibleLength = Math.max(0.5, n.dy);

    var basicKey = n.label;
    var foundKey = uniqueKeys[basicKey];
    uniqueKeys[basicKey] = (foundKey || 0) + 1;
    var key = basicKey + '__' + uniqueKeys[basicKey];

    // for event data
    n.trace = d.trace;
    n.curveNumber = d.trace.index;

    return {
        key: key,
        traceId: d.key,
        node: n,
        nodePad: d.nodePad,
        nodeLineColor: d.nodeLineColor,
        nodeLineWidth: d.nodeLineWidth,
        textFont: d.textFont,
        size: d.horizontal ? d.height : d.width,
        visibleWidth: Math.ceil(visibleThickness),
        visibleHeight: visibleLength,
        zoneX: -zoneThicknessPad,
        zoneY: -zoneLengthPad,
        zoneWidth: visibleThickness + 2 * zoneThicknessPad,
        zoneHeight: visibleLength + 2 * zoneLengthPad,
        labelY: d.horizontal ? n.dy / 2 + 1 : n.dx / 2 + 1,
        left: n.originalLayer === 1,
        sizeAcross: d.width,
        forceLayouts: d.forceLayouts,
        horizontal: d.horizontal,
        darkBackground: tc.getBrightness() <= 128,
        tinyColorHue: Color.tinyRGB(tc),
        tinyColorAlpha: tc.getAlpha(),
        valueFormat: d.valueFormat,
        valueSuffix: d.valueSuffix,
        sankey: d.sankey,
        arrangement: d.arrangement,
        uniqueNodeLabelPathId: [d.guid, d.key, key].join(' '),
        interactionState: d.interactionState
    };
}

// rendering snippets

function updateNodePositions(sankeyNode) {
    sankeyNode
        .attr('transform', function(d) {
            return 'translate(' + d.node.x.toFixed(3) + ', ' + (d.node.y - d.node.dy / 2).toFixed(3) + ')';
        });
}

function linkPath(d) {
    var nodes = d.sankey.nodes();
    switchToSankeyFormat(nodes);
    var result = d.sankey.link()(d.link);
    switchToForceFormat(nodes);
    return result;
}

function updateNodeShapes(sankeyNode) {
    sankeyNode.call(updateNodePositions);
}

function updateShapes(sankeyNode, sankeyLink) {
    sankeyNode.call(updateNodeShapes);
    sankeyLink.attr('d', linkPath);
}

function sizeNode(rect) {
    rect.attr('width', function(d) {return d.visibleWidth;})
        .attr('height', function(d) {return d.visibleHeight;});
}

function salientEnough(d) {return d.link.dy > 1 || d.linkLineWidth > 0;}

function sankeyTransform(d) {
    var offset = 'translate(' + d.translateX + ',' + d.translateY + ')';
    return offset + (d.horizontal ? 'matrix(1 0 0 1 0 0)' : 'matrix(0 1 1 0 0 0)');
}

function nodeCentering(d) {
    return 'translate(' + (d.horizontal ? 0 : d.labelY) + ' ' + (d.horizontal ? d.labelY : 0) + ')';
}

function textGuidePath(d) {
    return d3.svg.line()([
        [d.horizontal ? (d.left ? -d.sizeAcross : d.visibleWidth + c.nodeTextOffsetHorizontal) : c.nodeTextOffsetHorizontal, 0],
        [d.horizontal ? (d.left ? - c.nodeTextOffsetHorizontal : d.sizeAcross) : d.visibleHeight - c.nodeTextOffsetHorizontal, 0]
    ]);}

function sankeyInverseTransform(d) {return d.horizontal ? 'matrix(1 0 0 1 0 0)' : 'matrix(0 1 1 0 0 0)';}
function textFlip(d) {return d.horizontal ? 'scale(1 1)' : 'scale(-1 1)';}
function nodeTextColor(d) {return d.darkBackground && !d.horizontal ? 'rgb(255,255,255)' : 'rgb(0,0,0)';}
function nodeTextOffset(d) {return d.horizontal && d.left ? '100%' : '0%';}

// event handling

function attachPointerEvents(selection, sankey, eventSet) {
    selection
        .on('.basic', null) // remove any preexisting handlers
        .on('mouseover.basic', function(d) {
            if(!d.interactionState.dragInProgress) {
                eventSet.hover(this, d, sankey);
                d.interactionState.hovered = [this, d];
            }
        })
        .on('mousemove.basic', function(d) {
            if(!d.interactionState.dragInProgress) {
                eventSet.follow(this, d);
                d.interactionState.hovered = [this, d];
            }
        })
        .on('mouseout.basic', function(d) {
            if(!d.interactionState.dragInProgress) {
                eventSet.unhover(this, d, sankey);
                d.interactionState.hovered = false;
            }
        })
        .on('click.basic', function(d) {
            if(d.interactionState.hovered) {
                eventSet.unhover(this, d, sankey);
                d.interactionState.hovered = false;
            }
            if(!d.interactionState.dragInProgress) {
                eventSet.select(this, d, sankey);
            }
        });
}

function attachDragHandler(sankeyNode, sankeyLink, callbacks) {

    var dragBehavior = d3.behavior.drag()

        .origin(function(d) {return d.node;})

        .on('dragstart', function(d) {
            if(d.arrangement === 'fixed') return;
            Lib.raiseToTop(this);
            d.interactionState.dragInProgress = d.node;
            saveCurrentDragPosition(d.node);
            if(d.interactionState.hovered) {
                callbacks.nodeEvents.unhover.apply(0, d.interactionState.hovered);
                d.interactionState.hovered = false;
            }
            if(d.arrangement === 'snap') {
                var forceKey = d.traceId + '|' + Math.floor(d.node.originalX);
                if(d.forceLayouts[forceKey]) {
                    d.forceLayouts[forceKey].alpha(1);
                } else { // make a forceLayout iff needed
                    attachForce(sankeyNode, forceKey, d);
                }
                startForce(sankeyNode, sankeyLink, d, forceKey);
            }
        })

        .on('drag', function(d) {
            if(d.arrangement === 'fixed') return;
            var x = d3.event.x;
            var y = d3.event.y;
            if(d.arrangement === 'snap') {
                d.node.x = x;
                d.node.y = y;
            } else {
                if(d.arrangement === 'freeform') {
                    d.node.x = x;
                }
                d.node.y = Math.max(d.node.dy / 2, Math.min(d.size - d.node.dy / 2, y));
            }
            saveCurrentDragPosition(d.node);
            if(d.arrangement !== 'snap') {
                d.sankey.relayout();
                updateShapes(sankeyNode.filter(sameLayer(d)), sankeyLink);
            }
        })

        .on('dragend', function(d) {
            d.interactionState.dragInProgress = false;
        });

    sankeyNode
        .on('.drag', null) // remove possible previous handlers
        .call(dragBehavior);
}

function attachForce(sankeyNode, forceKey, d) {
    var nodes = d.sankey.nodes().filter(function(n) {return n.originalX === d.node.originalX;});
    d.forceLayouts[forceKey] = d3Force.forceSimulation(nodes)
        .alphaDecay(0)
        .force('collide', d3Force.forceCollide()
            .radius(function(n) {return n.dy / 2 + d.nodePad / 2;})
            .strength(1)
            .iterations(c.forceIterations))
        .force('constrain', snappingForce(sankeyNode, forceKey, nodes, d))
        .stop();
}

function startForce(sankeyNode, sankeyLink, d, forceKey) {
    window.requestAnimationFrame(function faster() {
        for(var i = 0; i < c.forceTicksPerFrame; i++) {
            d.forceLayouts[forceKey].tick();
        }
        d.sankey.relayout();
        updateShapes(sankeyNode.filter(sameLayer(d)), sankeyLink);
        if(d.forceLayouts[forceKey].alpha() > 0) {
            window.requestAnimationFrame(faster);
        }
    });
}

function snappingForce(sankeyNode, forceKey, nodes, d) {
    return function _snappingForce() {
        var maxVelocity = 0;
        for(var i = 0; i < nodes.length; i++) {
            var n = nodes[i];
            if(n === d.interactionState.dragInProgress) { // constrain node position to the dragging pointer
                n.x = n.lastDraggedX;
                n.y = n.lastDraggedY;
            } else {
                n.vx = (n.originalX - n.x) / c.forceTicksPerFrame; // snap to layer
                n.y = Math.min(d.size - n.dy / 2, Math.max(n.dy / 2, n.y)); // constrain to extent
            }
            maxVelocity = Math.max(maxVelocity, Math.abs(n.vx), Math.abs(n.vy));
        }
        if(!d.interactionState.dragInProgress && maxVelocity < 0.1 && d.forceLayouts[forceKey].alpha() > 0) {
            d.forceLayouts[forceKey].alpha(0);
        }
    };
}

// scene graph
module.exports = function(svg, styledData, layout, callbacks) {
    var sankey = svg.selectAll('.' + c.cn.sankey)
        .data(styledData
                .filter(function(d) {return unwrap(d).trace.visible;})
                .map(sankeyModel.bind(null, layout)),
            keyFun);

    sankey.exit()
        .remove();

    sankey.enter()
        .append('g')
        .classed(c.cn.sankey, true)
        .style('box-sizing', 'content-box')
        .style('position', 'absolute')
        .style('left', 0)
        .style('shape-rendering', 'geometricPrecision')
        .style('pointer-events', 'auto')
        .attr('transform', sankeyTransform);

    sankey.transition()
        .ease(c.ease).duration(c.duration)
        .attr('transform', sankeyTransform);

    var sankeyLinks = sankey.selectAll('.' + c.cn.sankeyLinks)
        .data(repeat, keyFun);

    sankeyLinks.enter()
        .append('g')
        .classed(c.cn.sankeyLinks, true)
        .style('fill', 'none');

    var sankeyLink = sankeyLinks.selectAll('.' + c.cn.sankeyLink)
        .data(function(d) {
            var uniqueKeys = {};
            return d.sankey.links()
                .filter(function(l) {return l.value;})
                .map(linkModel.bind(null, uniqueKeys, d));
        }, keyFun);

    sankeyLink.enter()
        .append('path')
        .classed(c.cn.sankeyLink, true)
        .attr('d', linkPath)
        .call(attachPointerEvents, sankey, callbacks.linkEvents);

    sankeyLink
        .style('stroke', function(d) {
            return salientEnough(d) ? Color.tinyRGB(tinycolor(d.linkLineColor)) : d.tinyColorHue;
        })
        .style('stroke-opacity', function(d) {
            return salientEnough(d) ? Color.opacity(d.linkLineColor) : d.tinyColorAlpha;
        })
        .style('stroke-width', function(d) {return salientEnough(d) ? d.linkLineWidth : 1;})
        .style('fill', function(d) {return d.tinyColorHue;})
        .style('fill-opacity', function(d) {return d.tinyColorAlpha;});

    sankeyLink.transition()
        .ease(c.ease).duration(c.duration)
        .attr('d', linkPath);

    sankeyLink.exit().transition()
        .ease(c.ease).duration(c.duration)
        .style('opacity', 0)
        .remove();

    var sankeyNodeSet = sankey.selectAll('.' + c.cn.sankeyNodeSet)
        .data(repeat, keyFun);

    sankeyNodeSet.enter()
        .append('g')
        .classed(c.cn.sankeyNodeSet, true);

    sankeyNodeSet
        .style('cursor', function(d) {
            switch(d.arrangement) {
                case 'fixed': return 'default';
                case 'perpendicular': return 'ns-resize';
                default: return 'move';
            }
        });

    var sankeyNode = sankeyNodeSet.selectAll('.' + c.cn.sankeyNode)
        .data(function(d) {
            var nodes = d.sankey.nodes();
            var uniqueKeys = {};
            persistOriginalPlace(nodes);
            return nodes
                .filter(function(n) {return n.value;})
                .map(nodeModel.bind(null, uniqueKeys, d));
        }, keyFun);

    sankeyNode.enter()
        .append('g')
        .classed(c.cn.sankeyNode, true)
        .call(updateNodePositions)
        .call(attachPointerEvents, sankey, callbacks.nodeEvents);

    sankeyNode
        .call(attachDragHandler, sankeyLink, callbacks); // has to be here as it binds sankeyLink

    sankeyNode.transition()
        .ease(c.ease).duration(c.duration)
        .call(updateNodePositions);

    sankeyNode.exit().transition()
        .ease(c.ease).duration(c.duration)
        .style('opacity', 0)
        .remove();

    var nodeRect = sankeyNode.selectAll('.' + c.cn.nodeRect)
        .data(repeat);

    nodeRect.enter()
        .append('rect')
        .classed(c.cn.nodeRect, true)
        .call(sizeNode);

    nodeRect
        .style('stroke-width', function(d) {return d.nodeLineWidth;})
        .style('stroke', function(d) {return Color.tinyRGB(tinycolor(d.nodeLineColor));})
        .style('stroke-opacity', function(d) {return Color.opacity(d.nodeLineColor);})
        .style('fill', function(d) {return d.tinyColorHue;})
        .style('fill-opacity', function(d) {return d.tinyColorAlpha;});

    nodeRect.transition()
        .ease(c.ease).duration(c.duration)
        .call(sizeNode);

    var nodeCapture = sankeyNode.selectAll('.' + c.cn.nodeCapture)
        .data(repeat);

    nodeCapture.enter()
        .append('rect')
        .classed(c.cn.nodeCapture, true)
        .style('fill-opacity', 0);

    nodeCapture
        .attr('x', function(d) {return d.zoneX;})
        .attr('y', function(d) {return d.zoneY;})
        .attr('width', function(d) {return d.zoneWidth;})
        .attr('height', function(d) {return d.zoneHeight;});

    var nodeCentered = sankeyNode.selectAll('.' + c.cn.nodeCentered)
        .data(repeat);

    nodeCentered.enter()
        .append('g')
        .classed(c.cn.nodeCentered, true)
        .attr('transform', nodeCentering);

    nodeCentered
        .transition()
        .ease(c.ease).duration(c.duration)
        .attr('transform', nodeCentering);

    var nodeLabelGuide = nodeCentered.selectAll('.' + c.cn.nodeLabelGuide)
        .data(repeat);

    nodeLabelGuide.enter()
        .append('path')
        .classed(c.cn.nodeLabelGuide, true)
        .attr('id', function(d) {return d.uniqueNodeLabelPathId;})
        .attr('d', textGuidePath)
        .attr('transform', sankeyInverseTransform);

    nodeLabelGuide
        .transition()
        .ease(c.ease).duration(c.duration)
        .attr('d', textGuidePath)
        .attr('transform', sankeyInverseTransform);

    var nodeLabel = nodeCentered.selectAll('.' + c.cn.nodeLabel)
        .data(repeat);

    nodeLabel.enter()
        .append('text')
        .classed(c.cn.nodeLabel, true)
        .attr('transform', textFlip)
        .style('user-select', 'none')
        .style('cursor', 'default')
        .style('fill', 'black');

    nodeLabel
        .style('text-shadow', function(d) {
            return d.horizontal ? '-1px 1px 1px #fff, 1px 1px 1px #fff, 1px -1px 1px #fff, -1px -1px 1px #fff' : 'none';
        })
        .each(function(d) {Drawing.font(nodeLabel, d.textFont);});

    nodeLabel
        .transition()
        .ease(c.ease).duration(c.duration)
        .attr('transform', textFlip);

    var nodeLabelTextPath = nodeLabel.selectAll('.' + c.cn.nodeLabelTextPath)
        .data(repeat);

    nodeLabelTextPath.enter()
        .append('textPath')
        .classed(c.cn.nodeLabelTextPath, true)
        .attr('alignment-baseline', 'middle')
        .attr('xlink:href', function(d) {return '#' + d.uniqueNodeLabelPathId;})
        .attr('startOffset', nodeTextOffset)
        .style('fill', nodeTextColor);

    nodeLabelTextPath
        .text(function(d) {return d.horizontal || d.node.dy > 5 ? d.node.label : '';})
        .attr('text-anchor', function(d) {return d.horizontal && d.left ? 'end' : 'start';});

    nodeLabelTextPath
        .transition()
        .ease(c.ease).duration(c.duration)
        .attr('startOffset', nodeTextOffset)
        .style('fill', nodeTextColor);
};

},{"../../components/color":571,"../../components/drawing":592,"../../lib":694,"../../lib/gup":692,"./constants":1041,"@plotly/d3-sankey":47,"d3":149,"d3-force":145,"tinycolor2":515}],1046:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');


// arrayOk attributes, merge them into calcdata array
module.exports = function arraysToCalcdata(cd, trace) {

    // so each point knows which index it originally came from
    for(var i = 0; i < cd.length; i++) cd[i].i = i;

    Lib.mergeArray(trace.text, cd, 'tx');
    Lib.mergeArray(trace.hovertext, cd, 'htx');
    Lib.mergeArray(trace.customdata, cd, 'data');
    Lib.mergeArray(trace.textposition, cd, 'tp');
    if(trace.textfont) {
        Lib.mergeArray(trace.textfont.size, cd, 'ts');
        Lib.mergeArray(trace.textfont.color, cd, 'tc');
        Lib.mergeArray(trace.textfont.family, cd, 'tf');
    }

    var marker = trace.marker;
    if(marker) {
        Lib.mergeArray(marker.size, cd, 'ms');
        Lib.mergeArray(marker.opacity, cd, 'mo');
        Lib.mergeArray(marker.symbol, cd, 'mx');
        Lib.mergeArray(marker.color, cd, 'mc');

        var markerLine = marker.line;
        if(marker.line) {
            Lib.mergeArray(markerLine.color, cd, 'mlc');
            Lib.mergeArray(markerLine.width, cd, 'mlw');
        }

        var markerGradient = marker.gradient;
        if(markerGradient && markerGradient.type !== 'none') {
            Lib.mergeArray(markerGradient.type, cd, 'mgt');
            Lib.mergeArray(markerGradient.color, cd, 'mgc');
        }
    }
};

},{"../../lib":694}],1047:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var colorAttributes = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
var fontAttrs = _dereq_('../../plots/font_attributes');
var dash = _dereq_('../../components/drawing/attributes').dash;

var Drawing = _dereq_('../../components/drawing');
var constants = _dereq_('./constants');
var extendFlat = _dereq_('../../lib/extend').extendFlat;

module.exports = {
    x: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        anim: true,
        
    },
    x0: {
        valType: 'any',
        dflt: 0,
        
        editType: 'calc+clearAxisTypes',
        anim: true,
        
    },
    dx: {
        valType: 'number',
        dflt: 1,
        
        editType: 'calc',
        anim: true,
        
    },
    y: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        anim: true,
        
    },
    y0: {
        valType: 'any',
        dflt: 0,
        
        editType: 'calc+clearAxisTypes',
        anim: true,
        
    },
    dy: {
        valType: 'number',
        dflt: 1,
        
        editType: 'calc',
        anim: true,
        
    },

    stackgroup: {
        valType: 'string',
        
        dflt: '',
        editType: 'calc',
        
    },
    orientation: {
        valType: 'enumerated',
        
        values: ['v', 'h'],
        editType: 'calc',
        
    },
    groupnorm: {
        valType: 'enumerated',
        values: ['', 'fraction', 'percent'],
        dflt: '',
        
        editType: 'calc',
        
    },
    stackgaps: {
        valType: 'enumerated',
        values: ['infer zero', 'interpolate'],
        dflt: 'infer zero',
        
        editType: 'calc',
        
    },

    text: {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        editType: 'calc',
        
    },
    hovertext: {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        editType: 'style',
        
    },
    mode: {
        valType: 'flaglist',
        flags: ['lines', 'markers', 'text'],
        extras: ['none'],
        
        editType: 'calc',
        
    },
    hoveron: {
        valType: 'flaglist',
        flags: ['points', 'fills'],
        
        editType: 'style',
        
    },
    hovertemplate: hovertemplateAttrs({}, {
        keys: constants.eventDataKeys
    }),
    line: {
        color: {
            valType: 'color',
            
            editType: 'style',
            anim: true,
            
        },
        width: {
            valType: 'number',
            min: 0,
            dflt: 2,
            
            editType: 'style',
            anim: true,
            
        },
        shape: {
            valType: 'enumerated',
            values: ['linear', 'spline', 'hv', 'vh', 'hvh', 'vhv'],
            dflt: 'linear',
            
            editType: 'plot',
            
        },
        smoothing: {
            valType: 'number',
            min: 0,
            max: 1.3,
            dflt: 1,
            
            editType: 'plot',
            
        },
        dash: extendFlat({}, dash, {editType: 'style'}),
        simplify: {
            valType: 'boolean',
            dflt: true,
            
            editType: 'plot',
            
        },
        editType: 'plot'
    },

    connectgaps: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'calc',
        
    },
    cliponaxis: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'plot',
        
    },

    fill: {
        valType: 'enumerated',
        values: ['none', 'tozeroy', 'tozerox', 'tonexty', 'tonextx', 'toself', 'tonext'],
        
        editType: 'calc',
        
    },
    fillcolor: {
        valType: 'color',
        
        editType: 'style',
        anim: true,
        
    },
    marker: extendFlat({
        symbol: {
            valType: 'enumerated',
            values: Drawing.symbolList,
            dflt: 'circle',
            arrayOk: true,
            
            editType: 'style',
            
        },
        opacity: {
            valType: 'number',
            min: 0,
            max: 1,
            arrayOk: true,
            
            editType: 'style',
            anim: true,
            
        },
        size: {
            valType: 'number',
            min: 0,
            dflt: 6,
            arrayOk: true,
            
            editType: 'calc',
            anim: true,
            
        },
        maxdisplayed: {
            valType: 'number',
            min: 0,
            dflt: 0,
            
            editType: 'plot',
            
        },
        sizeref: {
            valType: 'number',
            dflt: 1,
            
            editType: 'calc',
            
        },
        sizemin: {
            valType: 'number',
            min: 0,
            dflt: 0,
            
            editType: 'calc',
            
        },
        sizemode: {
            valType: 'enumerated',
            values: ['diameter', 'area'],
            dflt: 'diameter',
            
            editType: 'calc',
            
        },

        colorbar: colorbarAttrs,

        line: extendFlat({
            width: {
                valType: 'number',
                min: 0,
                arrayOk: true,
                
                editType: 'style',
                anim: true,
                
            },
            editType: 'calc'
        },
            colorAttributes('marker.line', {anim: true})
        ),
        gradient: {
            type: {
                valType: 'enumerated',
                values: ['radial', 'horizontal', 'vertical', 'none'],
                arrayOk: true,
                dflt: 'none',
                
                editType: 'calc',
                
            },
            color: {
                valType: 'color',
                arrayOk: true,
                
                editType: 'calc',
                
            },
            editType: 'calc'
        },
        editType: 'calc'
    },
        colorAttributes('marker', {anim: true})
    ),
    selected: {
        marker: {
            opacity: {
                valType: 'number',
                min: 0,
                max: 1,
                
                editType: 'style',
                
            },
            color: {
                valType: 'color',
                
                editType: 'style',
                
            },
            size: {
                valType: 'number',
                min: 0,
                
                editType: 'style',
                
            },
            editType: 'style'
        },
        textfont: {
            color: {
                valType: 'color',
                
                editType: 'style',
                
            },
            editType: 'style'
        },
        editType: 'style'
    },
    unselected: {
        marker: {
            opacity: {
                valType: 'number',
                min: 0,
                max: 1,
                
                editType: 'style',
                
            },
            color: {
                valType: 'color',
                
                editType: 'style',
                
            },
            size: {
                valType: 'number',
                min: 0,
                
                editType: 'style',
                
            },
            editType: 'style'
        },
        textfont: {
            color: {
                valType: 'color',
                
                editType: 'style',
                
            },
            editType: 'style'
        },
        editType: 'style'
    },

    textposition: {
        valType: 'enumerated',
        values: [
            'top left', 'top center', 'top right',
            'middle left', 'middle center', 'middle right',
            'bottom left', 'bottom center', 'bottom right'
        ],
        dflt: 'middle center',
        arrayOk: true,
        
        editType: 'calc',
        
    },
    textfont: fontAttrs({
        editType: 'calc',
        colorEditType: 'style',
        arrayOk: true,
        
    }),

    r: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    t: {
        valType: 'data_array',
        editType: 'calc',
        
    }
};

},{"../../components/colorbar/attributes":572,"../../components/colorscale/attributes":578,"../../components/drawing":592,"../../components/drawing/attributes":591,"../../components/fx/hovertemplate_attributes":609,"../../lib/extend":684,"../../plots/font_attributes":769,"./constants":1051}],1048:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var Lib = _dereq_('../../lib');

var Axes = _dereq_('../../plots/cartesian/axes');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

var subTypes = _dereq_('./subtypes');
var calcColorscale = _dereq_('./colorscale_calc');
var arraysToCalcdata = _dereq_('./arrays_to_calcdata');
var calcSelection = _dereq_('./calc_selection');

function calc(gd, trace) {
    var fullLayout = gd._fullLayout;
    var xa = Axes.getFromId(gd, trace.xaxis || 'x');
    var ya = Axes.getFromId(gd, trace.yaxis || 'y');
    var x = xa.makeCalcdata(trace, 'x');
    var y = ya.makeCalcdata(trace, 'y');
    var serieslen = trace._length;
    var cd = new Array(serieslen);
    var ids = trace.ids;
    var stackGroupOpts = getStackOpts(trace, fullLayout, xa, ya);
    var interpolateGaps = false;
    var isV, i, j, k, interpolate, vali;

    setFirstScatter(fullLayout, trace);

    var xAttr = 'x';
    var yAttr = 'y';
    var posAttr;
    if(stackGroupOpts) {
        stackGroupOpts.traceIndices.push(trace.index);
        isV = stackGroupOpts.orientation === 'v';
        // size, like we use for bar
        if(isV) {
            yAttr = 's';
            posAttr = 'x';
        }
        else {
            xAttr = 's';
            posAttr = 'y';
        }
        interpolate = stackGroupOpts.stackgaps === 'interpolate';
    }
    else {
        var ppad = calcMarkerSize(trace, serieslen);
        calcAxisExpansion(gd, trace, xa, ya, x, y, ppad);
    }

    for(i = 0; i < serieslen; i++) {
        var cdi = cd[i] = {};
        var xValid = isNumeric(x[i]);
        var yValid = isNumeric(y[i]);
        if(xValid && yValid) {
            cdi[xAttr] = x[i];
            cdi[yAttr] = y[i];
        }
        // if we're stacking we need to hold on to all valid positions
        // even with invalid sizes
        else if(stackGroupOpts && (isV ? xValid : yValid)) {
            cdi[posAttr] = isV ? x[i] : y[i];
            cdi.gap = true;
            if(interpolate) {
                cdi.s = BADNUM;
                interpolateGaps = true;
            }
            else {
                cdi.s = 0;
            }
        }
        else {
            cdi[xAttr] = cdi[yAttr] = BADNUM;
        }

        if(ids) {
            cdi.id = String(ids[i]);
        }
    }

    arraysToCalcdata(cd, trace);
    calcColorscale(gd, trace);
    calcSelection(cd, trace);

    if(stackGroupOpts) {
        // remove bad positions and sort
        // note that original indices get added to cd in arraysToCalcdata
        i = 0;
        while(i < cd.length) {
            if(cd[i][posAttr] === BADNUM) {
                cd.splice(i, 1);
            }
            else i++;
        }

        Lib.sort(cd, function(a, b) {
            return (a[posAttr] - b[posAttr]) || (a.i - b.i);
        });

        if(interpolateGaps) {
            // first fill the beginning with constant from the first point
            i = 0;
            while(i < cd.length - 1 && cd[i].gap) {
                i++;
            }
            vali = cd[i].s;
            if(!vali) vali = cd[i].s = 0; // in case of no data AT ALL in this trace - use 0
            for(j = 0; j < i; j++) {
                cd[j].s = vali;
            }
            // then fill the end with constant from the last point
            k = cd.length - 1;
            while(k > i && cd[k].gap) {
                k--;
            }
            vali = cd[k].s;
            for(j = cd.length - 1; j > k; j--) {
                cd[j].s = vali;
            }
            // now interpolate internal gaps linearly
            while(i < k) {
                i++;
                if(cd[i].gap) {
                    j = i + 1;
                    while(cd[j].gap) {
                        j++;
                    }
                    var pos0 = cd[i - 1][posAttr];
                    var size0 = cd[i - 1].s;
                    var m = (cd[j].s - size0) / (cd[j][posAttr] - pos0);
                    while(i < j) {
                        cd[i].s = size0 + (cd[i][posAttr] - pos0) * m;
                        i++;
                    }
                }
            }
        }
    }

    return cd;
}

function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) {
    var serieslen = trace._length;
    var fullLayout = gd._fullLayout;
    var xId = xa._id;
    var yId = ya._id;
    var firstScatter = fullLayout._firstScatter[firstScatterGroup(trace)] === trace.uid;
    var stackOrientation = (getStackOpts(trace, fullLayout, xa, ya) || {}).orientation;
    var fill = trace.fill;

    // cancel minimum tick spacings (only applies to bars and boxes)
    xa._minDtick = 0;
    ya._minDtick = 0;

    // check whether bounds should be tight, padded, extended to zero...
    // most cases both should be padded on both ends, so start with that.
    var xOptions = {padded: true};
    var yOptions = {padded: true};

    if(ppad) {
        xOptions.ppad = yOptions.ppad = ppad;
    }

    // TODO: text size

    var openEnded = serieslen < 2 || (x[0] !== x[serieslen - 1]) || (y[0] !== y[serieslen - 1]);

    // include zero (tight) and extremes (padded) if fill to zero
    // (unless the shape is closed, then it's just filling the shape regardless)
    if(openEnded && (
        (fill === 'tozerox') ||
        ((fill === 'tonextx') && (firstScatter || stackOrientation === 'h'))
    )) {
        xOptions.tozero = true;
    }

    // if no error bars, markers or text, or fill to y=0 remove x padding
    else if(!(trace.error_y || {}).visible && (
            (fill === 'tonexty' || fill === 'tozeroy') ||
            (!subTypes.hasMarkers(trace) && !subTypes.hasText(trace))
        )) {
        xOptions.padded = false;
        xOptions.ppad = 0;
    }

    // now check for y - rather different logic, though still mostly padded both ends
    // include zero (tight) and extremes (padded) if fill to zero
    // (unless the shape is closed, then it's just filling the shape regardless)
    if(openEnded && (
        (fill === 'tozeroy') ||
        ((fill === 'tonexty') && (firstScatter || stackOrientation === 'v'))
    )) {
        yOptions.tozero = true;
    }

    // tight y: any x fill
    else if(fill === 'tonextx' || fill === 'tozerox') {
        yOptions.padded = false;
    }

    // N.B. asymmetric splom traces call this with blank {} xa or ya
    if(xId) trace._extremes[xId] = Axes.findExtremes(xa, x, xOptions);
    if(yId) trace._extremes[yId] = Axes.findExtremes(ya, y, yOptions);
}

function calcMarkerSize(trace, serieslen) {
    if(!subTypes.hasMarkers(trace)) return;

    // Treat size like x or y arrays --- Run d2c
    // this needs to go before ppad computation
    var marker = trace.marker;
    var sizeref = 1.6 * (trace.marker.sizeref || 1);
    var markerTrans;

    if(trace.marker.sizemode === 'area') {
        markerTrans = function(v) {
            return Math.max(Math.sqrt((v || 0) / sizeref), 3);
        };
    } else {
        markerTrans = function(v) {
            return Math.max((v || 0) / sizeref, 3);
        };
    }

    if(Lib.isArrayOrTypedArray(marker.size)) {
        // I tried auto-type but category and dates dont make much sense.
        var ax = {type: 'linear'};
        Axes.setConvert(ax);

        var s = ax.makeCalcdata(trace.marker, 'size');

        var sizeOut = new Array(serieslen);
        for(var i = 0; i < serieslen; i++) {
            sizeOut[i] = markerTrans(s[i]);
        }
        return sizeOut;

    } else {
        return markerTrans(marker.size);
    }
}

/**
 * mark the first scatter trace for each subplot
 * note that scatter and scattergl each get their own first trace
 * note also that I'm doing this during calc rather than supplyDefaults
 * so I don't need to worry about transforms, but if we ever do
 * per-trace calc this will get confused.
 */
function setFirstScatter(fullLayout, trace) {
    var group = firstScatterGroup(trace);
    var firstScatter = fullLayout._firstScatter;
    if(!firstScatter[group]) firstScatter[group] = trace.uid;
}

function firstScatterGroup(trace) {
    var stackGroup = trace.stackgroup;
    return trace.xaxis + trace.yaxis + trace.type +
        (stackGroup ? '-' + stackGroup : '');
}

function getStackOpts(trace, fullLayout, xa, ya) {
    var stackGroup = trace.stackgroup;
    if(!stackGroup) return;
    var stackOpts = fullLayout._scatterStackOpts[xa._id + ya._id][stackGroup];
    var stackAx = stackOpts.orientation === 'v' ? ya : xa;
    // Allow stacking only on numeric axes
    // calc is a little late to be figuring this out, but during supplyDefaults
    // we don't know the axis type yet
    if(stackAx.type === 'linear' || stackAx.type === 'log') return stackOpts;
}

module.exports = {
    calc: calc,
    calcMarkerSize: calcMarkerSize,
    calcAxisExpansion: calcAxisExpansion,
    setFirstScatter: setFirstScatter,
    getStackOpts: getStackOpts
};

},{"../../constants/numerical":671,"../../lib":694,"../../plots/cartesian/axes":742,"./arrays_to_calcdata":1046,"./calc_selection":1049,"./colorscale_calc":1050,"./subtypes":1071,"fast-isnumeric":215}],1049:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

module.exports = function calcSelection(cd, trace) {
    if(Lib.isArrayOrTypedArray(trace.selectedpoints)) {
        Lib.tagSelected(cd, trace);
    }
};

},{"../../lib":694}],1050:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
var calcColorscale = _dereq_('../../components/colorscale/calc');

var subTypes = _dereq_('./subtypes');

module.exports = function calcMarkerColorscale(gd, trace) {
    if(subTypes.hasLines(trace) && hasColorscale(trace, 'line')) {
        calcColorscale(gd, trace, {
            vals: trace.line.color,
            containerStr: 'line',
            cLetter: 'c'
        });
    }

    if(subTypes.hasMarkers(trace)) {
        if(hasColorscale(trace, 'marker')) {
            calcColorscale(gd, trace, {
                vals: trace.marker.color,
                containerStr: 'marker',
                cLetter: 'c'
            });
        }
        if(hasColorscale(trace, 'marker.line')) {
            calcColorscale(gd, trace, {
                vals: trace.marker.line.color,
                containerStr: 'marker.line',
                cLetter: 'c'
            });
        }
    }
};

},{"../../components/colorscale/calc":579,"../../components/colorscale/helpers":582,"./subtypes":1071}],1051:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = {
    PTS_LINESONLY: 20,

    // fixed parameters of clustering and clipping algorithms

    // fraction of clustering tolerance "so close we don't even consider it a new point"
    minTolerance: 0.2,
    // how fast does clustering tolerance increase as you get away from the visible region
    toleranceGrowth: 10,

    // number of viewport sizes away from the visible region
    // at which we clip all lines to the perimeter
    maxScreensAway: 20,

    eventDataKeys: []
};

},{}],1052:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var calc = _dereq_('./calc');

/*
 * Scatter stacking & normalization calculations
 * runs per subplot, and can handle multiple stacking groups
 */

module.exports = function crossTraceCalc(gd, plotinfo) {
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;
    var subplot = xa._id + ya._id;

    var subplotStackOpts = gd._fullLayout._scatterStackOpts[subplot];
    if(!subplotStackOpts) return;

    var calcTraces = gd.calcdata;

    var i, j, k, i2, cd, cd0, posj, sumj, norm;
    var groupOpts, interpolate, groupnorm, posAttr, valAttr;
    var hasAnyBlanks;

    for(var stackGroup in subplotStackOpts) {
        groupOpts = subplotStackOpts[stackGroup];
        var indices = groupOpts.traceIndices;

        // can get here with no indices if the stack axis is non-numeric
        if(!indices.length) continue;

        interpolate = groupOpts.stackgaps === 'interpolate';
        groupnorm = groupOpts.groupnorm;
        if(groupOpts.orientation === 'v') {
            posAttr = 'x';
            valAttr = 'y';
        }
        else {
            posAttr = 'y';
            valAttr = 'x';
        }
        hasAnyBlanks = new Array(indices.length);
        for(i = 0; i < hasAnyBlanks.length; i++) {
            hasAnyBlanks[i] = false;
        }

        // Collect the complete set of all positions across ALL traces.
        // Start with the first trace, then interleave items from later traces
        // as needed.
        // Fill in mising items as we go.
        cd0 = calcTraces[indices[0]];
        var allPositions = new Array(cd0.length);
        for(i = 0; i < cd0.length; i++) {
            allPositions[i] = cd0[i][posAttr];
        }

        for(i = 1; i < indices.length; i++) {
            cd = calcTraces[indices[i]];

            for(j = k = 0; j < cd.length; j++) {
                posj = cd[j][posAttr];
                for(; posj > allPositions[k] && k < allPositions.length; k++) {
                    // the current trace is missing a position from some previous trace(s)
                    insertBlank(cd, j, allPositions[k], i, hasAnyBlanks, interpolate, posAttr);
                    j++;
                }
                if(posj !== allPositions[k]) {
                    // previous trace(s) are missing a position from the current trace
                    for(i2 = 0; i2 < i; i2++) {
                        insertBlank(calcTraces[indices[i2]], k, posj, i2, hasAnyBlanks, interpolate, posAttr);
                    }
                    allPositions.splice(k, 0, posj);
                }
                k++;
            }
            for(; k < allPositions.length; k++) {
                insertBlank(cd, j, allPositions[k], i, hasAnyBlanks, interpolate, posAttr);
                j++;
            }
        }

        var serieslen = allPositions.length;

        // stack (and normalize)!
        for(j = 0; j < cd0.length; j++) {
            sumj = cd0[j][valAttr] = cd0[j].s;
            for(i = 1; i < indices.length; i++) {
                cd = calcTraces[indices[i]];
                cd[0].trace._rawLength = cd[0].trace._length;
                cd[0].trace._length = serieslen;
                sumj += cd[j].s;
                cd[j][valAttr] = sumj;
            }

            if(groupnorm) {
                norm = ((groupnorm === 'fraction') ? sumj : (sumj / 100)) || 1;
                for(i = 0; i < indices.length; i++) {
                    var cdj = calcTraces[indices[i]][j];
                    cdj[valAttr] /= norm;
                    cdj.sNorm = cdj.s / norm;
                }
            }
        }

        // autorange
        for(i = 0; i < indices.length; i++) {
            cd = calcTraces[indices[i]];
            var trace = cd[0].trace;
            var ppad = calc.calcMarkerSize(trace, trace._rawLength);
            var arrayPad = Array.isArray(ppad);
            if((ppad && hasAnyBlanks[i]) || arrayPad) {
                var ppadRaw = ppad;
                ppad = new Array(serieslen);
                for(j = 0; j < serieslen; j++) {
                    ppad[j] = cd[j].gap ? 0 : (arrayPad ? ppadRaw[cd[j].i] : ppadRaw);
                }
            }
            var x = new Array(serieslen);
            var y = new Array(serieslen);
            for(j = 0; j < serieslen; j++) {
                x[j] = cd[j].x;
                y[j] = cd[j].y;
            }
            calc.calcAxisExpansion(gd, trace, xa, ya, x, y, ppad);

            // while we're here (in a loop over all traces in the stack)
            // record the orientation, so hover can find it easily
            cd[0].t.orientation = groupOpts.orientation;
        }
    }
};

function insertBlank(calcTrace, index, position, traceIndex, hasAnyBlanks, interpolate, posAttr) {
    hasAnyBlanks[traceIndex] = true;
    var newEntry = {
        i: null,
        gap: true,
        s: 0
    };
    newEntry[posAttr] = position;
    calcTrace.splice(index, 0, newEntry);
    // Even if we're not interpolating, if one trace has multiple
    // values at the same position and this trace only has one value there,
    // we just duplicate that one value rather than insert a zero.
    // We also make it look like a real point - because it's ambiguous which
    // one really is the real one!
    if(index && position === calcTrace[index - 1][posAttr]) {
        var prevEntry = calcTrace[index - 1];
        newEntry.s = prevEntry.s;
        // TODO is it going to cause any problems to have multiple
        // calcdata points with the same index?
        newEntry.i = prevEntry.i;
        newEntry.gap = prevEntry.gap;
    }
    else if(interpolate) {
        newEntry.s = getInterp(calcTrace, index, position, posAttr);
    }
    if(!index) {
        // t and trace need to stay on the first cd entry
        calcTrace[0].t = calcTrace[1].t;
        calcTrace[0].trace = calcTrace[1].trace;
        delete calcTrace[1].t;
        delete calcTrace[1].trace;
    }
}

function getInterp(calcTrace, index, position, posAttr) {
    var pt0 = calcTrace[index - 1];
    var pt1 = calcTrace[index + 1];
    if(!pt1) return pt0.s;
    if(!pt0) return pt1.s;
    return pt0.s + (pt1.s - pt0.s) * (position - pt0[posAttr]) / (pt1[posAttr] - pt0[posAttr]);
}

},{"./calc":1048}],1053:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


// remove opacity for any trace that has a fill or is filled to
module.exports = function crossTraceDefaults(fullData) {
    for(var i = 0; i < fullData.length; i++) {
        var tracei = fullData[i];
        if(tracei.type !== 'scatter') continue;

        var filli = tracei.fill;
        if(filli === 'none' || filli === 'toself') continue;

        tracei.opacity = undefined;

        if(filli === 'tonexty' || filli === 'tonextx') {
            for(var j = i - 1; j >= 0; j--) {
                var tracej = fullData[j];

                if((tracej.type === 'scatter') &&
                        (tracej.xaxis === tracei.xaxis) &&
                        (tracej.yaxis === tracei.yaxis)) {
                    tracej.opacity = undefined;
                    break;
                }
            }
        }
    }
};

},{}],1054:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Registry = _dereq_('../../registry');

var attributes = _dereq_('./attributes');
var constants = _dereq_('./constants');
var subTypes = _dereq_('./subtypes');
var handleXYDefaults = _dereq_('./xy_defaults');
var handleStackDefaults = _dereq_('./stack_defaults');
var handleMarkerDefaults = _dereq_('./marker_defaults');
var handleLineDefaults = _dereq_('./line_defaults');
var handleLineShapeDefaults = _dereq_('./line_shape_defaults');
var handleTextDefaults = _dereq_('./text_defaults');
var handleFillColorDefaults = _dereq_('./fillcolor_defaults');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var len = handleXYDefaults(traceIn, traceOut, layout, coerce);
    if(!len) traceOut.visible = false;

    if(!traceOut.visible) return;

    var stackGroupOpts = handleStackDefaults(traceIn, traceOut, layout, coerce);

    var defaultMode = !stackGroupOpts && (len < constants.PTS_LINESONLY) ?
        'lines+markers' : 'lines';
    coerce('text');
    coerce('hovertext');
    coerce('mode', defaultMode);

    if(subTypes.hasLines(traceOut)) {
        handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
        handleLineShapeDefaults(traceIn, traceOut, coerce);
        coerce('connectgaps');
        coerce('line.simplify');
    }

    if(subTypes.hasMarkers(traceOut)) {
        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true});
    }

    if(subTypes.hasText(traceOut)) {
        handleTextDefaults(traceIn, traceOut, layout, coerce);
    }

    var dfltHoverOn = [];

    if(subTypes.hasMarkers(traceOut) || subTypes.hasText(traceOut)) {
        coerce('cliponaxis');
        coerce('marker.maxdisplayed');
        dfltHoverOn.push('points');
    }

    // It's possible for this default to be changed by a later trace.
    // We handle that case in some hacky code inside handleStackDefaults.
    coerce('fill', stackGroupOpts ? stackGroupOpts.fillDflt : 'none');
    if(traceOut.fill !== 'none') {
        handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
        if(!subTypes.hasLines(traceOut)) handleLineShapeDefaults(traceIn, traceOut, coerce);
    }

    var lineColor = (traceOut.line || {}).color;
    var markerColor = (traceOut.marker || {}).color;

    if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') {
        dfltHoverOn.push('fills');
    }
    coerce('hoveron', dfltHoverOn.join('+') || 'points');
    if(traceOut.hoveron !== 'fills') coerce('hovertemplate');
    var errorBarsSupplyDefaults = Registry.getComponentMethod('errorbars', 'supplyDefaults');
    errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, {axis: 'y'});
    errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, {axis: 'x', inherit: 'y'});

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};

},{"../../lib":694,"../../registry":825,"./attributes":1047,"./constants":1051,"./fillcolor_defaults":1056,"./line_defaults":1060,"./line_shape_defaults":1062,"./marker_defaults":1066,"./stack_defaults":1069,"./subtypes":1071,"./text_defaults":1072,"./xy_defaults":1073}],1055:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

/** Fill hover 'pointData' container with 'correct' hover text value
 *
 * - If trace hoverinfo contains a 'text' flag and hovertext is not set,
 *   the text elements will be seen in the hover labels.
 *
 * - If trace hoverinfo contains a 'text' flag and hovertext is set,
 *   hovertext takes precedence over text
 *   i.e. the hoverinfo elements will be seen in the hover labels
 *
 *  @param {object} calcPt
 *  @param {object} trace
 *  @param {object || array} contOut (mutated here)
 */
module.exports = function fillHoverText(calcPt, trace, contOut) {
    var fill = Array.isArray(contOut) ?
        function(v) { contOut.push(v); } :
        function(v) { contOut.text = v; };

    var htx = Lib.extractOption(calcPt, trace, 'htx', 'hovertext');
    if(isValid(htx)) return fill(htx);

    var tx = Lib.extractOption(calcPt, trace, 'tx', 'text');
    if(isValid(tx)) return fill(tx);
};

// accept all truthy values and 0 (which gets cast to '0' in the hover labels)
function isValid(v) {
    return v || v === 0;
}

},{"../../lib":694}],1056:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Color = _dereq_('../../components/color');
var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;

module.exports = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) {
    var inheritColorFromMarker = false;

    if(traceOut.marker) {
        // don't try to inherit a color array
        var markerColor = traceOut.marker.color;
        var markerLineColor = (traceOut.marker.line || {}).color;

        if(markerColor && !isArrayOrTypedArray(markerColor)) {
            inheritColorFromMarker = markerColor;
        }
        else if(markerLineColor && !isArrayOrTypedArray(markerLineColor)) {
            inheritColorFromMarker = markerLineColor;
        }
    }

    coerce('fillcolor', Color.addOpacity(
        (traceOut.line || {}).color ||
        inheritColorFromMarker ||
        defaultColor, 0.5
    ));
};

},{"../../components/color":571,"../../lib":694}],1057:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Color = _dereq_('../../components/color');
var subtypes = _dereq_('./subtypes');


module.exports = function getTraceColor(trace, di) {
    var lc, tc;

    // TODO: text modes

    if(trace.mode === 'lines') {
        lc = trace.line.color;
        return (lc && Color.opacity(lc)) ?
            lc : trace.fillcolor;
    }
    else if(trace.mode === 'none') {
        return trace.fill ? trace.fillcolor : '';
    }
    else {
        var mc = di.mcc || (trace.marker || {}).color;
        var mlc = di.mlcc || ((trace.marker || {}).line || {}).color;

        tc = (mc && Color.opacity(mc)) ? mc :
            (mlc && Color.opacity(mlc) &&
                (di.mlw || ((trace.marker || {}).line || {}).width)) ? mlc : '';

        if(tc) {
            // make sure the points aren't TOO transparent
            if(Color.opacity(tc) < 0.3) {
                return Color.addOpacity(tc, 0.3);
            }
            else return tc;
        }
        else {
            lc = (trace.line || {}).color;
            return (lc && Color.opacity(lc) &&
                subtypes.hasLines(trace) && trace.line.width) ?
                    lc : trace.fillcolor;
        }
    }
};

},{"../../components/color":571,"./subtypes":1071}],1058:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Fx = _dereq_('../../components/fx');
var Registry = _dereq_('../../registry');
var getTraceColor = _dereq_('./get_trace_color');
var Color = _dereq_('../../components/color');
var fillHoverText = _dereq_('./fill_hover_text');

module.exports = function hoverPoints(pointData, xval, yval, hovermode) {
    var cd = pointData.cd;
    var trace = cd[0].trace;
    var xa = pointData.xa;
    var ya = pointData.ya;
    var xpx = xa.c2p(xval);
    var ypx = ya.c2p(yval);
    var pt = [xpx, ypx];
    var hoveron = trace.hoveron || '';
    var minRad = (trace.mode.indexOf('markers') !== -1) ? 3 : 0.5;

    // look for points to hover on first, then take fills only if we
    // didn't find a point
    if(hoveron.indexOf('points') !== -1) {
        var dx = function(di) {
            // dx and dy are used in compare modes - here we want to always
            // prioritize the closest data point, at least as long as markers are
            // the same size or nonexistent, but still try to prioritize small markers too.
            var rad = Math.max(3, di.mrc || 0);
            var kink = 1 - 1 / rad;
            var dxRaw = Math.abs(xa.c2p(di.x) - xpx);
            var d = (dxRaw < rad) ? (kink * dxRaw / rad) : (dxRaw - rad + kink);
            return d;
        };
        var dy = function(di) {
            var rad = Math.max(3, di.mrc || 0);
            var kink = 1 - 1 / rad;
            var dyRaw = Math.abs(ya.c2p(di.y) - ypx);
            return (dyRaw < rad) ? (kink * dyRaw / rad) : (dyRaw - rad + kink);
        };
        var dxy = function(di) {
            // scatter points: d.mrc is the calculated marker radius
            // adjust the distance so if you're inside the marker it
            // always will show up regardless of point size, but
            // prioritize smaller points
            var rad = Math.max(minRad, di.mrc || 0);
            var dx = xa.c2p(di.x) - xpx;
            var dy = ya.c2p(di.y) - ypx;
            return Math.max(Math.sqrt(dx * dx + dy * dy) - rad, 1 - minRad / rad);
        };
        var distfn = Fx.getDistanceFunction(hovermode, dx, dy, dxy);

        Fx.getClosest(cd, distfn, pointData);

        // skip the rest (for this trace) if we didn't find a close point
        if(pointData.index !== false) {

            // the closest data point
            var di = cd[pointData.index];
            var xc = xa.c2p(di.x, true);
            var yc = ya.c2p(di.y, true);
            var rad = di.mrc || 1;

            // now we're done using the whole `calcdata` array, replace the
            // index with the original index (in case of inserted point from
            // stacked area)
            pointData.index = di.i;

            var orientation = cd[0].t.orientation;
            // TODO: for scatter and bar, option to show (sub)totals and
            // raw data? Currently stacked and/or normalized bars just show
            // the normalized individual sizes, so that's what I'm doing here
            // for now.
            var sizeVal = orientation && (di.sNorm || di.s);
            var xLabelVal = (orientation === 'h') ? sizeVal : di.x;
            var yLabelVal = (orientation === 'v') ? sizeVal : di.y;

            Lib.extendFlat(pointData, {
                color: getTraceColor(trace, di),

                x0: xc - rad,
                x1: xc + rad,
                xLabelVal: xLabelVal,

                y0: yc - rad,
                y1: yc + rad,
                yLabelVal: yLabelVal,

                spikeDistance: dxy(di),
                hovertemplate: trace.hovertemplate
            });

            fillHoverText(di, trace, pointData);
            Registry.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData);

            return [pointData];
        }
    }

    // even if hoveron is 'fills', only use it if we have polygons too
    if(hoveron.indexOf('fills') !== -1 && trace._polygons) {
        var polygons = trace._polygons;
        var polygonsIn = [];
        var inside = false;
        var xmin = Infinity;
        var xmax = -Infinity;
        var ymin = Infinity;
        var ymax = -Infinity;

        var i, j, polygon, pts, xCross, x0, x1, y0, y1;

        for(i = 0; i < polygons.length; i++) {
            polygon = polygons[i];
            // TODO: this is not going to work right for curved edges, it will
            // act as though they're straight. That's probably going to need
            // the elements themselves to capture the events. Worth it?
            if(polygon.contains(pt)) {
                inside = !inside;
                // TODO: need better than just the overall bounding box
                polygonsIn.push(polygon);
                ymin = Math.min(ymin, polygon.ymin);
                ymax = Math.max(ymax, polygon.ymax);
            }
        }

        if(inside) {
            // constrain ymin/max to the visible plot, so the label goes
            // at the middle of the piece you can see
            ymin = Math.max(ymin, 0);
            ymax = Math.min(ymax, ya._length);

            // find the overall left-most and right-most points of the
            // polygon(s) we're inside at their combined vertical midpoint.
            // This is where we will draw the hover label.
            // Note that this might not be the vertical midpoint of the
            // whole trace, if it's disjoint.
            var yAvg = (ymin + ymax) / 2;
            for(i = 0; i < polygonsIn.length; i++) {
                pts = polygonsIn[i].pts;
                for(j = 1; j < pts.length; j++) {
                    y0 = pts[j - 1][1];
                    y1 = pts[j][1];
                    if((y0 > yAvg) !== (y1 >= yAvg)) {
                        x0 = pts[j - 1][0];
                        x1 = pts[j][0];
                        if(y1 - y0) {
                            xCross = x0 + (x1 - x0) * (yAvg - y0) / (y1 - y0);
                            xmin = Math.min(xmin, xCross);
                            xmax = Math.max(xmax, xCross);
                        }
                    }
                }
            }

            // constrain xmin/max to the visible plot now too
            xmin = Math.max(xmin, 0);
            xmax = Math.min(xmax, xa._length);

            // get only fill or line color for the hover color
            var color = Color.defaultLine;
            if(Color.opacity(trace.fillcolor)) color = trace.fillcolor;
            else if(Color.opacity((trace.line || {}).color)) {
                color = trace.line.color;
            }

            Lib.extendFlat(pointData, {
                // never let a 2D override 1D type as closest point
                // also: no spikeDistance, it's not allowed for fills
                distance: pointData.maxHoverDistance,
                x0: xmin,
                x1: xmax,
                y0: yAvg,
                y1: yAvg,
                color: color,
                hovertemplate: '%{name}'
            });

            delete pointData.index;

            if(trace.text && !Array.isArray(trace.text)) {
                pointData.text = String(trace.text);
            }
            else pointData.text = trace.name;

            return [pointData];
        }
    }
};

},{"../../components/color":571,"../../components/fx":610,"../../lib":694,"../../registry":825,"./fill_hover_text":1055,"./get_trace_color":1057}],1059:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Scatter = {};

var subtypes = _dereq_('./subtypes');
Scatter.hasLines = subtypes.hasLines;
Scatter.hasMarkers = subtypes.hasMarkers;
Scatter.hasText = subtypes.hasText;
Scatter.isBubble = subtypes.isBubble;

Scatter.attributes = _dereq_('./attributes');
Scatter.supplyDefaults = _dereq_('./defaults');
Scatter.crossTraceDefaults = _dereq_('./cross_trace_defaults');
Scatter.calc = _dereq_('./calc').calc;
Scatter.crossTraceCalc = _dereq_('./cross_trace_calc');
Scatter.arraysToCalcdata = _dereq_('./arrays_to_calcdata');
Scatter.plot = _dereq_('./plot');
Scatter.colorbar = _dereq_('./marker_colorbar');
Scatter.style = _dereq_('./style').style;
Scatter.styleOnSelect = _dereq_('./style').styleOnSelect;
Scatter.hoverPoints = _dereq_('./hover');
Scatter.selectPoints = _dereq_('./select');
Scatter.animatable = true;

Scatter.moduleType = 'trace';
Scatter.name = 'scatter';
Scatter.basePlotModule = _dereq_('../../plots/cartesian');
Scatter.categories = [
    'cartesian', 'svg', 'symbols', 'errorBarsOK', 'showLegend', 'scatter-like',
    'zoomScale'
];
Scatter.meta = {
    
};

module.exports = Scatter;

},{"../../plots/cartesian":754,"./arrays_to_calcdata":1046,"./attributes":1047,"./calc":1048,"./cross_trace_calc":1052,"./cross_trace_defaults":1053,"./defaults":1054,"./hover":1058,"./marker_colorbar":1065,"./plot":1067,"./select":1068,"./style":1070,"./subtypes":1071}],1060:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;
var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');

module.exports = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) {
    var markerColor = (traceIn.marker || {}).color;

    coerce('line.color', defaultColor);

    if(hasColorscale(traceIn, 'line')) {
        colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'});
    } else {
        var lineColorDflt = (isArrayOrTypedArray(markerColor) ? false : markerColor) || defaultColor;
        coerce('line.color', lineColorDflt);
    }

    coerce('line.width');
    if(!(opts || {}).noDash) coerce('line.dash');
};

},{"../../components/colorscale/defaults":581,"../../components/colorscale/helpers":582,"../../lib":694}],1061:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var numConstants = _dereq_('../../constants/numerical');
var BADNUM = numConstants.BADNUM;
var LOG_CLIP = numConstants.LOG_CLIP;
var LOG_CLIP_PLUS = LOG_CLIP + 0.5;
var LOG_CLIP_MINUS = LOG_CLIP - 0.5;
var Lib = _dereq_('../../lib');
var segmentsIntersect = Lib.segmentsIntersect;
var constrain = Lib.constrain;
var constants = _dereq_('./constants');


module.exports = function linePoints(d, opts) {
    var xa = opts.xaxis;
    var ya = opts.yaxis;
    var xLog = xa.type === 'log';
    var yLog = ya.type === 'log';
    var xLen = xa._length;
    var yLen = ya._length;
    var connectGaps = opts.connectGaps;
    var baseTolerance = opts.baseTolerance;
    var shape = opts.shape;
    var linear = shape === 'linear';
    var segments = [];
    var minTolerance = constants.minTolerance;
    var pts = new Array(d.length);
    var pti = 0;

    var i;

    // pt variables are pixel coordinates [x,y] of one point
    // these four are the outputs of clustering on a line
    var clusterStartPt, clusterEndPt, clusterHighPt, clusterLowPt;

    // "this" is the next point we're considering adding to the cluster
    var thisPt;

    // did we encounter the high point first, then a low point, or vice versa?
    var clusterHighFirst;

    // the first two points in the cluster determine its unit vector
    // so the second is always in the "High" direction
    var clusterUnitVector;

    // the pixel delta from clusterStartPt
    var thisVector;

    // val variables are (signed) pixel distances along the cluster vector
    var clusterRefDist, clusterHighVal, clusterLowVal, thisVal;

    // deviation variables are (signed) pixel distances normal to the cluster vector
    var clusterMinDeviation, clusterMaxDeviation, thisDeviation;

    // turn one calcdata point into pixel coordinates
    function getPt(index) {
        var di = d[index];
        if(!di) return false;
        var x = xa.c2p(di.x);
        var y = ya.c2p(di.y);

        // if non-positive log values, set them VERY far off-screen
        // so the line looks essentially straight from the previous point.
        if(x === BADNUM) {
            if(xLog) x = xa.c2p(di.x, true);
            if(x === BADNUM) return false;
            // If BOTH were bad log values, make the line follow a constant
            // exponent rather than a constant slope
            if(yLog && y === BADNUM) {
                x *= Math.abs(xa._m * yLen * (xa._m > 0 ? LOG_CLIP_PLUS : LOG_CLIP_MINUS) /
                    (ya._m * xLen * (ya._m > 0 ? LOG_CLIP_PLUS : LOG_CLIP_MINUS)));
            }
            x *= 1000;
        }
        if(y === BADNUM) {
            if(yLog) y = ya.c2p(di.y, true);
            if(y === BADNUM) return false;
            y *= 1000;
        }
        return [x, y];
    }

    function crossesViewport(xFrac0, yFrac0, xFrac1, yFrac1) {
        var dx = xFrac1 - xFrac0;
        var dy = yFrac1 - yFrac0;
        var dx0 = 0.5 - xFrac0;
        var dy0 = 0.5 - yFrac0;
        var norm2 = dx * dx + dy * dy;
        var dot = dx * dx0 + dy * dy0;
        if(dot > 0 && dot < norm2) {
            var cross = dx0 * dy - dy0 * dx;
            if(cross * cross < norm2) return true;
        }
    }

    var latestXFrac, latestYFrac;
    // if we're off-screen, increase tolerance over baseTolerance
    function getTolerance(pt, nextPt) {
        var xFrac = pt[0] / xLen;
        var yFrac = pt[1] / yLen;
        var offScreenFraction = Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1);
        if(offScreenFraction && (latestXFrac !== undefined) &&
            crossesViewport(xFrac, yFrac, latestXFrac, latestYFrac)
        ) {
            offScreenFraction = 0;
        }
        if(offScreenFraction && nextPt &&
            crossesViewport(xFrac, yFrac, nextPt[0] / xLen, nextPt[1] / yLen)
        ) {
            offScreenFraction = 0;
        }

        return (1 + constants.toleranceGrowth * offScreenFraction) * baseTolerance;
    }

    function ptDist(pt1, pt2) {
        var dx = pt1[0] - pt2[0];
        var dy = pt1[1] - pt2[1];
        return Math.sqrt(dx * dx + dy * dy);
    }

    // last bit of filtering: clip paths that are VERY far off-screen
    // so we don't get near the browser's hard limit (+/- 2^29 px in Chrome and FF)

    var maxScreensAway = constants.maxScreensAway;

    // find the intersections between the segment from pt1 to pt2
    // and the large rectangle maxScreensAway around the viewport
    // if one of pt1 and pt2 is inside and the other outside, there
    // will be only one intersection.
    // if both are outside there will be 0 or 2 intersections
    // (or 1 if it's right at a corner - we'll treat that like 0)
    // returns an array of intersection pts
    var xEdge0 = -xLen * maxScreensAway;
    var xEdge1 = xLen * (1 + maxScreensAway);
    var yEdge0 = -yLen * maxScreensAway;
    var yEdge1 = yLen * (1 + maxScreensAway);
    var edges = [
        [xEdge0, yEdge0, xEdge1, yEdge0],
        [xEdge1, yEdge0, xEdge1, yEdge1],
        [xEdge1, yEdge1, xEdge0, yEdge1],
        [xEdge0, yEdge1, xEdge0, yEdge0]
    ];
    var xEdge, yEdge, lastXEdge, lastYEdge, lastFarPt, edgePt;

    // for linear line shape, edge intersections should be linearly interpolated
    // spline uses this too, which isn't precisely correct but is actually pretty
    // good, because Catmull-Rom weights far-away points less in creating the curvature
    function getLinearEdgeIntersections(pt1, pt2) {
        var out = [];
        var ptCount = 0;
        for(var i = 0; i < 4; i++) {
            var edge = edges[i];
            var ptInt = segmentsIntersect(pt1[0], pt1[1], pt2[0], pt2[1],
                edge[0], edge[1], edge[2], edge[3]);
            if(ptInt && (!ptCount ||
                Math.abs(ptInt.x - out[0][0]) > 1 ||
                Math.abs(ptInt.y - out[0][1]) > 1
            )) {
                ptInt = [ptInt.x, ptInt.y];
                // if we have 2 intersections, make sure the closest one to pt1 comes first
                if(ptCount && ptDist(ptInt, pt1) < ptDist(out[0], pt1)) out.unshift(ptInt);
                else out.push(ptInt);
                ptCount++;
            }
        }
        return out;
    }

    function onlyConstrainedPoint(pt) {
        if(pt[0] < xEdge0 || pt[0] > xEdge1 || pt[1] < yEdge0 || pt[1] > yEdge1) {
            return [constrain(pt[0], xEdge0, xEdge1), constrain(pt[1], yEdge0, yEdge1)];
        }
    }

    function sameEdge(pt1, pt2) {
        if(pt1[0] === pt2[0] && (pt1[0] === xEdge0 || pt1[0] === xEdge1)) return true;
        if(pt1[1] === pt2[1] && (pt1[1] === yEdge0 || pt1[1] === yEdge1)) return true;
    }

    // for line shapes hv and vh, movement in the two dimensions is decoupled,
    // so all we need to do is constrain each dimension independently
    function getHVEdgeIntersections(pt1, pt2) {
        var out = [];
        var ptInt1 = onlyConstrainedPoint(pt1);
        var ptInt2 = onlyConstrainedPoint(pt2);
        if(ptInt1 && ptInt2 && sameEdge(ptInt1, ptInt2)) return out;

        if(ptInt1) out.push(ptInt1);
        if(ptInt2) out.push(ptInt2);
        return out;
    }

    // hvh and vhv we sometimes have to move one of the intersection points
    // out BEYOND the clipping rect, by a maximum of a factor of 2, so that
    // the midpoint line is drawn in the right place
    function getABAEdgeIntersections(dim, limit0, limit1) {
        return function(pt1, pt2) {
            var ptInt1 = onlyConstrainedPoint(pt1);
            var ptInt2 = onlyConstrainedPoint(pt2);

            var out = [];
            if(ptInt1 && ptInt2 && sameEdge(ptInt1, ptInt2)) return out;

            if(ptInt1) out.push(ptInt1);
            if(ptInt2) out.push(ptInt2);

            var midShift = 2 * Lib.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) -
                ((ptInt1 || pt1)[dim] + (ptInt2 || pt2)[dim]);
            if(midShift) {
                var ptToAlter;
                if(ptInt1 && ptInt2) {
                    ptToAlter = (midShift > 0 === ptInt1[dim] > ptInt2[dim]) ? ptInt1 : ptInt2;
                }
                else ptToAlter = ptInt1 || ptInt2;

                ptToAlter[dim] += midShift;
            }

            return out;
        };
    }

    var getEdgeIntersections;
    if(shape === 'linear' || shape === 'spline') {
        getEdgeIntersections = getLinearEdgeIntersections;
    }
    else if(shape === 'hv' || shape === 'vh') {
        getEdgeIntersections = getHVEdgeIntersections;
    }
    else if(shape === 'hvh') getEdgeIntersections = getABAEdgeIntersections(0, xEdge0, xEdge1);
    else if(shape === 'vhv') getEdgeIntersections = getABAEdgeIntersections(1, yEdge0, yEdge1);

    // a segment pt1->pt2 entirely outside the nearby region:
    // find the corner it gets closest to touching
    function getClosestCorner(pt1, pt2) {
        var dx = pt2[0] - pt1[0];
        var m = (pt2[1] - pt1[1]) / dx;
        var b = (pt1[1] * pt2[0] - pt2[1] * pt1[0]) / dx;

        if(b > 0) return [m > 0 ? xEdge0 : xEdge1, yEdge1];
        else return [m > 0 ? xEdge1 : xEdge0, yEdge0];
    }

    function updateEdge(pt) {
        var x = pt[0];
        var y = pt[1];
        var xSame = x === pts[pti - 1][0];
        var ySame = y === pts[pti - 1][1];
        // duplicate point?
        if(xSame && ySame) return;
        if(pti > 1) {
            // backtracking along an edge?
            var xSame2 = x === pts[pti - 2][0];
            var ySame2 = y === pts[pti - 2][1];
            if(xSame && (x === xEdge0 || x === xEdge1) && xSame2) {
                if(ySame2) pti--; // backtracking exactly - drop prev pt and don't add
                else pts[pti - 1] = pt; // not exact: replace the prev pt
            }
            else if(ySame && (y === yEdge0 || y === yEdge1) && ySame2) {
                if(xSame2) pti--;
                else pts[pti - 1] = pt;
            }
            else pts[pti++] = pt;
        }
        else pts[pti++] = pt;
    }

    function updateEdgesForReentry(pt) {
        // if we're outside the nearby region and going back in,
        // we may need to loop around a corner point
        if(pts[pti - 1][0] !== pt[0] && pts[pti - 1][1] !== pt[1]) {
            updateEdge([lastXEdge, lastYEdge]);
        }
        updateEdge(pt);
        lastFarPt = null;
        lastXEdge = lastYEdge = 0;
    }

    function addPt(pt) {
        latestXFrac = pt[0] / xLen;
        latestYFrac = pt[1] / yLen;
        // Are we more than maxScreensAway off-screen any direction?
        // if so, clip to this box, but in such a way that on-screen
        // drawing is unchanged
        xEdge = (pt[0] < xEdge0) ? xEdge0 : (pt[0] > xEdge1) ? xEdge1 : 0;
        yEdge = (pt[1] < yEdge0) ? yEdge0 : (pt[1] > yEdge1) ? yEdge1 : 0;
        if(xEdge || yEdge) {
            // to get fills right - if first point is far, push it toward the
            // screen in whichever direction(s) are far
            if(!pti) {
                pts[pti++] = [xEdge || pt[0], yEdge || pt[1]];
            }
            else if(lastFarPt) {
                // both this point and the last are outside the nearby region
                // check if we're crossing the nearby region
                var intersections = getEdgeIntersections(lastFarPt, pt);
                if(intersections.length > 1) {
                    updateEdgesForReentry(intersections[0]);
                    pts[pti++] = intersections[1];
                }
            }
            // we're leaving the nearby region - add the point where we left it
            else {
                edgePt = getEdgeIntersections(pts[pti - 1], pt)[0];
                pts[pti++] = edgePt;
            }

            var lastPt = pts[pti - 1];
            if(xEdge && yEdge && (lastPt[0] !== xEdge || lastPt[1] !== yEdge)) {
                // we've gone out beyond a new corner: add the corner too
                // so that the next point will take the right winding
                if(lastFarPt) {
                    if(lastXEdge !== xEdge && lastYEdge !== yEdge) {
                        if(lastXEdge && lastYEdge) {
                            // we've gone around to an opposite corner - we
                            // need to add the correct extra corner
                            // in order to get the right winding
                            updateEdge(getClosestCorner(lastFarPt, pt));
                        }
                        else {
                            // we're coming from a far edge - the extra corner
                            // we need is determined uniquely by the sectors
                            updateEdge([lastXEdge || xEdge, lastYEdge || yEdge]);
                        }
                    }
                    else if(lastXEdge && lastYEdge) {
                        updateEdge([lastXEdge, lastYEdge]);
                    }
                }
                updateEdge([xEdge, yEdge]);
            }
            else if((lastXEdge - xEdge) && (lastYEdge - yEdge)) {
                // we're coming from an edge or far corner to an edge - again the
                // extra corner we need is uniquely determined by the sectors
                updateEdge([xEdge || lastXEdge, yEdge || lastYEdge]);
            }
            lastFarPt = pt;
            lastXEdge = xEdge;
            lastYEdge = yEdge;
        }
        else {
            if(lastFarPt) {
                // this point is in range but the previous wasn't: add its entry pt first
                updateEdgesForReentry(getEdgeIntersections(lastFarPt, pt)[0]);
            }

            pts[pti++] = pt;
        }
    }

    // loop over ALL points in this trace
    for(i = 0; i < d.length; i++) {
        clusterStartPt = getPt(i);
        if(!clusterStartPt) continue;

        pti = 0;
        lastFarPt = null;
        addPt(clusterStartPt);

        // loop over one segment of the trace
        for(i++; i < d.length; i++) {
            clusterHighPt = getPt(i);
            if(!clusterHighPt) {
                if(connectGaps) continue;
                else break;
            }

            // can't decimate if nonlinear line shape
            // TODO: we *could* decimate [hv]{2,3} shapes if we restricted clusters to horz or vert again
            // but spline would be verrry awkward to decimate
            if(!linear || !opts.simplify) {
                addPt(clusterHighPt);
                continue;
            }

            var nextPt = getPt(i + 1);

            clusterRefDist = ptDist(clusterHighPt, clusterStartPt);

            if(clusterRefDist < getTolerance(clusterHighPt, nextPt) * minTolerance) continue;

            clusterUnitVector = [
                (clusterHighPt[0] - clusterStartPt[0]) / clusterRefDist,
                (clusterHighPt[1] - clusterStartPt[1]) / clusterRefDist
            ];

            clusterLowPt = clusterStartPt;
            clusterHighVal = clusterRefDist;
            clusterLowVal = clusterMinDeviation = clusterMaxDeviation = 0;
            clusterHighFirst = false;
            clusterEndPt = clusterHighPt;

            // loop over one cluster of points that collapse onto one line
            for(i++; i < d.length; i++) {
                thisPt = nextPt;
                nextPt = getPt(i + 1);
                if(!thisPt) {
                    if(connectGaps) continue;
                    else break;
                }
                thisVector = [
                    thisPt[0] - clusterStartPt[0],
                    thisPt[1] - clusterStartPt[1]
                ];
                // cross product (or dot with normal to the cluster vector)
                thisDeviation = thisVector[0] * clusterUnitVector[1] - thisVector[1] * clusterUnitVector[0];
                clusterMinDeviation = Math.min(clusterMinDeviation, thisDeviation);
                clusterMaxDeviation = Math.max(clusterMaxDeviation, thisDeviation);

                if(clusterMaxDeviation - clusterMinDeviation > getTolerance(thisPt, nextPt)) break;

                clusterEndPt = thisPt;
                thisVal = thisVector[0] * clusterUnitVector[0] + thisVector[1] * clusterUnitVector[1];

                if(thisVal > clusterHighVal) {
                    clusterHighVal = thisVal;
                    clusterHighPt = thisPt;
                    clusterHighFirst = false;
                } else if(thisVal < clusterLowVal) {
                    clusterLowVal = thisVal;
                    clusterLowPt = thisPt;
                    clusterHighFirst = true;
                }
            }

            // insert this cluster into pts
            // we've already inserted the start pt, now check if we have high and low pts
            if(clusterHighFirst) {
                addPt(clusterHighPt);
                if(clusterEndPt !== clusterLowPt) addPt(clusterLowPt);
            } else {
                if(clusterLowPt !== clusterStartPt) addPt(clusterLowPt);
                if(clusterEndPt !== clusterHighPt) addPt(clusterHighPt);
            }
            // and finally insert the end pt
            addPt(clusterEndPt);

            // have we reached the end of this segment?
            if(i >= d.length || !thisPt) break;

            // otherwise we have an out-of-cluster point to insert as next clusterStartPt
            addPt(thisPt);
            clusterStartPt = thisPt;
        }

        // to get fills right - repeat what we did at the start
        if(lastFarPt) updateEdge([lastXEdge || lastFarPt[0], lastYEdge || lastFarPt[1]]);

        segments.push(pts.slice(0, pti));
    }

    return segments;
};

},{"../../constants/numerical":671,"../../lib":694,"./constants":1051}],1062:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


// common to 'scatter' and 'scatterternary'
module.exports = function handleLineShapeDefaults(traceIn, traceOut, coerce) {
    var shape = coerce('line.shape');
    if(shape === 'spline') coerce('line.smoothing');
};

},{}],1063:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var LINKEDFILLS = {tonextx: 1, tonexty: 1, tonext: 1};

module.exports = function linkTraces(gd, plotinfo, cdscatter) {
    var trace, i, group, prevtrace, groupIndex;

    // first sort traces to keep stacks & filled-together groups together
    var groupIndices = {};
    var needsSort = false;
    var prevGroupIndex = -1;
    var nextGroupIndex = 0;
    var prevUnstackedGroupIndex = -1;
    for(i = 0; i < cdscatter.length; i++) {
        trace = cdscatter[i][0].trace;
        group = trace.stackgroup || '';
        if(group) {
            if(group in groupIndices) {
                groupIndex = groupIndices[group];
            }
            else {
                groupIndex = groupIndices[group] = nextGroupIndex;
                nextGroupIndex++;
            }
        }
        else if(trace.fill in LINKEDFILLS && prevUnstackedGroupIndex >= 0) {
            groupIndex = prevUnstackedGroupIndex;
        }
        else {
            groupIndex = prevUnstackedGroupIndex = nextGroupIndex;
            nextGroupIndex++;
        }

        if(groupIndex < prevGroupIndex) needsSort = true;
        trace._groupIndex = prevGroupIndex = groupIndex;
    }

    var cdscatterSorted = cdscatter.slice();
    if(needsSort) {
        cdscatterSorted.sort(function(a, b) {
            var traceA = a[0].trace;
            var traceB = b[0].trace;
            return (traceA._groupIndex - traceB._groupIndex) ||
                (traceA.index - traceB.index);
        });
    }

    // now link traces to each other
    var prevtraces = {};
    for(i = 0; i < cdscatterSorted.length; i++) {
        trace = cdscatterSorted[i][0].trace;
        group = trace.stackgroup || '';

        // Note: The check which ensures all cdscatter here are for the same axis and
        // are either cartesian or scatterternary has been removed. This code assumes
        // the passed scattertraces have been filtered to the proper plot types and
        // the proper subplots.
        if(trace.visible === true) {
            trace._nexttrace = null;

            if(trace.fill in LINKEDFILLS) {
                prevtrace = prevtraces[group];
                trace._prevtrace = prevtrace || null;

                if(prevtrace) {
                    prevtrace._nexttrace = trace;
                }
            }

            trace._ownfill = (trace.fill && (
                trace.fill.substr(0, 6) === 'tozero' ||
                trace.fill === 'toself' ||
                (trace.fill.substr(0, 2) === 'to' && !trace._prevtrace)
            ));

            prevtraces[group] = trace;
        } else {
            trace._prevtrace = trace._nexttrace = trace._ownfill = null;
        }
    }

    return cdscatterSorted;
};

},{}],1064:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');


// used in the drawing step for 'scatter' and 'scattegeo' and
// in the convert step for 'scatter3d'
module.exports = function makeBubbleSizeFn(trace) {
    var marker = trace.marker;
    var sizeRef = marker.sizeref || 1;
    var sizeMin = marker.sizemin || 0;

    // for bubble charts, allow scaling the provided value linearly
    // and by area or diameter.
    // Note this only applies to the array-value sizes

    var baseFn = (marker.sizemode === 'area') ?
        function(v) { return Math.sqrt(v / sizeRef); } :
        function(v) { return v / sizeRef; };

    // TODO add support for position/negative bubbles?
    // TODO add 'sizeoffset' attribute?
    return function(v) {
        var baseSize = baseFn(v / 2);

        // don't show non-numeric and negative sizes
        return (isNumeric(baseSize) && (baseSize > 0)) ?
            Math.max(baseSize, sizeMin) :
            0;
    };
};

},{"fast-isnumeric":215}],1065:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = {
    container: 'marker',
    min: 'cmin',
    max: 'cmax'
};

},{}],1066:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Color = _dereq_('../../components/color');
var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');

var subTypes = _dereq_('./subtypes');

/*
 * opts: object of flags to control features not all marker users support
 *   noLine: caller does not support marker lines
 *   gradient: caller supports gradients
 *   noSelect: caller does not support selected/unselected attribute containers
 */
module.exports = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) {
    var isBubble = subTypes.isBubble(traceIn);
    var lineColor = (traceIn.line || {}).color;
    var defaultMLC;

    opts = opts || {};

    // marker.color inherit from line.color (even if line.color is an array)
    if(lineColor) defaultColor = lineColor;

    coerce('marker.symbol');
    coerce('marker.opacity', isBubble ? 0.7 : 1);
    coerce('marker.size');

    coerce('marker.color', defaultColor);
    if(hasColorscale(traceIn, 'marker')) {
        colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'});
    }

    if(!opts.noSelect) {
        coerce('selected.marker.color');
        coerce('unselected.marker.color');
        coerce('selected.marker.size');
        coerce('unselected.marker.size');
    }

    if(!opts.noLine) {
        // if there's a line with a different color than the marker, use
        // that line color as the default marker line color
        // (except when it's an array)
        // mostly this is for transparent markers to behave nicely
        if(lineColor && !Array.isArray(lineColor) && (traceOut.marker.color !== lineColor)) {
            defaultMLC = lineColor;
        }
        else if(isBubble) defaultMLC = Color.background;
        else defaultMLC = Color.defaultLine;

        coerce('marker.line.color', defaultMLC);
        if(hasColorscale(traceIn, 'marker.line')) {
            colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'});
        }

        coerce('marker.line.width', isBubble ? 1 : 0);
    }

    if(isBubble) {
        coerce('marker.sizeref');
        coerce('marker.sizemin');
        coerce('marker.sizemode');
    }

    if(opts.gradient) {
        var gradientType = coerce('marker.gradient.type');
        if(gradientType !== 'none') {
            coerce('marker.gradient.color');
        }
    }
};

},{"../../components/color":571,"../../components/colorscale/defaults":581,"../../components/colorscale/helpers":582,"./subtypes":1071}],1067:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var ensureSingle = Lib.ensureSingle;
var identity = Lib.identity;
var Drawing = _dereq_('../../components/drawing');

var subTypes = _dereq_('./subtypes');
var linePoints = _dereq_('./line_points');
var linkTraces = _dereq_('./link_traces');
var polygonTester = _dereq_('../../lib/polygon').tester;

module.exports = function plot(gd, plotinfo, cdscatter, scatterLayer, transitionOpts, makeOnCompleteCallback) {
    var join, onComplete;

    // If transition config is provided, then it is only a partial replot and traces not
    // updated are removed.
    var isFullReplot = !transitionOpts;
    var hasTransition = !!transitionOpts && transitionOpts.duration > 0;

    // Link traces so the z-order of fill layers is correct
    var cdscatterSorted = linkTraces(gd, plotinfo, cdscatter);

    join = scatterLayer.selectAll('g.trace')
        .data(cdscatterSorted, function(d) { return d[0].trace.uid; });

    // Append new traces:
    join.enter().append('g')
        .attr('class', function(d) {
            return 'trace scatter trace' + d[0].trace.uid;
        })
        .style('stroke-miterlimit', 2);
    join.order();

    createFills(gd, join, plotinfo);

    if(hasTransition) {
        if(makeOnCompleteCallback) {
            // If it was passed a callback to register completion, make a callback. If
            // this is created, then it must be executed on completion, otherwise the
            // pos-transition redraw will not execute:
            onComplete = makeOnCompleteCallback();
        }

        var transition = d3.transition()
            .duration(transitionOpts.duration)
            .ease(transitionOpts.easing)
            .each('end', function() {
                onComplete && onComplete();
            })
            .each('interrupt', function() {
                onComplete && onComplete();
            });

        transition.each(function() {
            // Must run the selection again since otherwise enters/updates get grouped together
            // and these get executed out of order. Except we need them in order!
            scatterLayer.selectAll('g.trace').each(function(d, i) {
                plotOne(gd, i, plotinfo, d, cdscatterSorted, this, transitionOpts);
            });
        });
    } else {
        join.each(function(d, i) {
            plotOne(gd, i, plotinfo, d, cdscatterSorted, this, transitionOpts);
        });
    }

    if(isFullReplot) {
        join.exit().remove();
    }

    // remove paths that didn't get used
    scatterLayer.selectAll('path:not([d])').remove();
};

function createFills(gd, traceJoin, plotinfo) {
    traceJoin.each(function(d) {
        var fills = ensureSingle(d3.select(this), 'g', 'fills');
        Drawing.setClipUrl(fills, plotinfo.layerClipId, gd);

        var trace = d[0].trace;

        var fillData = [];
        if(trace._ownfill) fillData.push('_ownFill');
        if(trace._nexttrace) fillData.push('_nextFill');

        var fillJoin = fills.selectAll('g').data(fillData, identity);

        fillJoin.enter().append('g');

        fillJoin.exit()
            .each(function(d) { trace[d] = null; })
            .remove();

        fillJoin.order().each(function(d) {
            // make a path element inside the fill group, just so
            // we can give it its own data later on and the group can
            // keep its simple '_*Fill' data
            trace[d] = ensureSingle(d3.select(this), 'path', 'js-fill');
        });
    });
}

function plotOne(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) {
    var i;

    // Since this has been reorganized and we're executing this on individual traces,
    // we need to pass it the full list of cdscatter as well as this trace's index (idx)
    // since it does an internal n^2 loop over comparisons with other traces:
    selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll);

    var hasTransition = !!transitionOpts && transitionOpts.duration > 0;

    function transition(selection) {
        return hasTransition ? selection.transition() : selection;
    }

    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    var trace = cdscatter[0].trace;
    var line = trace.line;
    var tr = d3.select(element);

    var errorBarGroup = ensureSingle(tr, 'g', 'errorbars');
    var lines = ensureSingle(tr, 'g', 'lines');
    var points = ensureSingle(tr, 'g', 'points');
    var text = ensureSingle(tr, 'g', 'text');

    // error bars are at the bottom
    Registry.getComponentMethod('errorbars', 'plot')(gd, errorBarGroup, plotinfo, transitionOpts);

    if(trace.visible !== true) return;

    transition(tr).style('opacity', trace.opacity);

    // BUILD LINES AND FILLS
    var ownFillEl3, tonext;
    var ownFillDir = trace.fill.charAt(trace.fill.length - 1);
    if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = '';

    // store node for tweaking by selectPoints
    if(!plotinfo.isRangePlot) cdscatter[0].node3 = tr;

    var prevRevpath = '';
    var prevPolygons = [];
    var prevtrace = trace._prevtrace;

    if(prevtrace) {
        prevRevpath = prevtrace._prevRevpath || '';
        tonext = prevtrace._nextFill;
        prevPolygons = prevtrace._polygons;
    }

    var thispath;
    var thisrevpath;
    // fullpath is all paths for this curve, joined together straight
    // across gaps, for filling
    var fullpath = '';
    // revpath is fullpath reversed, for fill-to-next
    var revpath = '';
    // functions for converting a point array to a path
    var pathfn, revpathbase, revpathfn;
    // variables used before and after the data join
    var pt0, lastSegment, pt1, thisPolygons;

    // initialize line join data / method
    var segments = [];
    var makeUpdate = Lib.noop;

    ownFillEl3 = trace._ownFill;

    if(subTypes.hasLines(trace) || trace.fill !== 'none') {

        if(tonext) {
            // This tells .style which trace to use for fill information:
            tonext.datum(cdscatter);
        }

        if(['hv', 'vh', 'hvh', 'vhv'].indexOf(line.shape) !== -1) {
            pathfn = Drawing.steps(line.shape);
            revpathbase = Drawing.steps(
                line.shape.split('').reverse().join('')
            );
        }
        else if(line.shape === 'spline') {
            pathfn = revpathbase = function(pts) {
                var pLast = pts[pts.length - 1];
                if(pts.length > 1 && pts[0][0] === pLast[0] && pts[0][1] === pLast[1]) {
                    // identical start and end points: treat it as a
                    // closed curve so we don't get a kink
                    return Drawing.smoothclosed(pts.slice(1), line.smoothing);
                }
                else {
                    return Drawing.smoothopen(pts, line.smoothing);
                }
            };
        }
        else {
            pathfn = revpathbase = function(pts) {
                return 'M' + pts.join('L');
            };
        }

        revpathfn = function(pts) {
            // note: this is destructive (reverses pts in place) so can't use pts after this
            return revpathbase(pts.reverse());
        };

        segments = linePoints(cdscatter, {
            xaxis: xa,
            yaxis: ya,
            connectGaps: trace.connectgaps,
            baseTolerance: Math.max(line.width || 1, 3) / 4,
            shape: line.shape,
            simplify: line.simplify
        });

        // since we already have the pixel segments here, use them to make
        // polygons for hover on fill
        // TODO: can we skip this if hoveron!=fills? That would mean we
        // need to redraw when you change hoveron...
        thisPolygons = trace._polygons = new Array(segments.length);
        for(i = 0; i < segments.length; i++) {
            trace._polygons[i] = polygonTester(segments[i]);
        }

        if(segments.length) {
            pt0 = segments[0][0];
            lastSegment = segments[segments.length - 1];
            pt1 = lastSegment[lastSegment.length - 1];
        }

        makeUpdate = function(isEnter) {
            return function(pts) {
                thispath = pathfn(pts);
                thisrevpath = revpathfn(pts);
                if(!fullpath) {
                    fullpath = thispath;
                    revpath = thisrevpath;
                }
                else if(ownFillDir) {
                    fullpath += 'L' + thispath.substr(1);
                    revpath = thisrevpath + ('L' + revpath.substr(1));
                }
                else {
                    fullpath += 'Z' + thispath;
                    revpath = thisrevpath + 'Z' + revpath;
                }

                if(subTypes.hasLines(trace) && pts.length > 1) {
                    var el = d3.select(this);

                    // This makes the coloring work correctly:
                    el.datum(cdscatter);

                    if(isEnter) {
                        transition(el.style('opacity', 0)
                            .attr('d', thispath)
                            .call(Drawing.lineGroupStyle))
                                .style('opacity', 1);
                    } else {
                        var sel = transition(el);
                        sel.attr('d', thispath);
                        Drawing.singleLineStyle(cdscatter, sel);
                    }
                }
            };
        };
    }

    var lineJoin = lines.selectAll('.js-line').data(segments);

    transition(lineJoin.exit())
        .style('opacity', 0)
        .remove();

    lineJoin.each(makeUpdate(false));

    lineJoin.enter().append('path')
        .classed('js-line', true)
        .style('vector-effect', 'non-scaling-stroke')
        .call(Drawing.lineGroupStyle)
        .each(makeUpdate(true));

    Drawing.setClipUrl(lineJoin, plotinfo.layerClipId, gd);

    function clearFill(selection) {
        transition(selection).attr('d', 'M0,0Z');
    }

    if(segments.length) {
        if(ownFillEl3) {
            ownFillEl3.datum(cdscatter);
            if(pt0 && pt1) {
                if(ownFillDir) {
                    if(ownFillDir === 'y') {
                        pt0[1] = pt1[1] = ya.c2p(0, true);
                    }
                    else if(ownFillDir === 'x') {
                        pt0[0] = pt1[0] = xa.c2p(0, true);
                    }

                    // fill to zero: full trace path, plus extension of
                    // the endpoints to the appropriate axis
                    // For the sake of animations, wrap the points around so that
                    // the points on the axes are the first two points. Otherwise
                    // animations get a little crazy if the number of points changes.
                    transition(ownFillEl3).attr('d', 'M' + pt1 + 'L' + pt0 + 'L' + fullpath.substr(1))
                        .call(Drawing.singleFillStyle);
                } else {
                    // fill to self: just join the path to itself
                    transition(ownFillEl3).attr('d', fullpath + 'Z')
                        .call(Drawing.singleFillStyle);
                }
            }
        }
        else if(tonext) {
            if(trace.fill.substr(0, 6) === 'tonext' && fullpath && prevRevpath) {
                // fill to next: full trace path, plus the previous path reversed
                if(trace.fill === 'tonext') {
                    // tonext: for use by concentric shapes, like manually constructed
                    // contours, we just add the two paths closed on themselves.
                    // This makes strange results if one path is *not* entirely
                    // inside the other, but then that is a strange usage.
                    transition(tonext).attr('d', fullpath + 'Z' + prevRevpath + 'Z')
                        .call(Drawing.singleFillStyle);
                }
                else {
                    // tonextx/y: for now just connect endpoints with lines. This is
                    // the correct behavior if the endpoints are at the same value of
                    // y/x, but if they *aren't*, we should ideally do more complicated
                    // things depending on whether the new endpoint projects onto the
                    // existing curve or off the end of it
                    transition(tonext).attr('d', fullpath + 'L' + prevRevpath.substr(1) + 'Z')
                        .call(Drawing.singleFillStyle);
                }
                trace._polygons = trace._polygons.concat(prevPolygons);
            }
            else {
                clearFill(tonext);
                trace._polygons = null;
            }
        }
        trace._prevRevpath = revpath;
        trace._prevPolygons = thisPolygons;
    }
    else {
        if(ownFillEl3) clearFill(ownFillEl3);
        else if(tonext) clearFill(tonext);
        trace._polygons = trace._prevRevpath = trace._prevPolygons = null;
    }


    function visFilter(d) {
        return d.filter(function(v) { return !v.gap && v.vis; });
    }

    function visFilterWithGaps(d) {
        return d.filter(function(v) { return v.vis; });
    }

    function gapFilter(d) {
        return d.filter(function(v) { return !v.gap; });
    }

    function keyFunc(d) {
        return d.id;
    }

    // Returns a function if the trace is keyed, otherwise returns undefined
    function getKeyFunc(trace) {
        if(trace.ids) {
            return keyFunc;
        }
    }

    function hideFilter() {
        return false;
    }

    function makePoints(points, text, cdscatter) {
        var join, selection, hasNode;

        var trace = cdscatter[0].trace;
        var showMarkers = subTypes.hasMarkers(trace);
        var showText = subTypes.hasText(trace);

        var keyFunc = getKeyFunc(trace);
        var markerFilter = hideFilter;
        var textFilter = hideFilter;

        if(showMarkers || showText) {
            var showFilter = identity;
            // if we're stacking, "infer zero" gap mode gets markers in the
            // gap points - because we've inferred a zero there - but other
            // modes (currently "interpolate", later "interrupt" hopefully)
            // we don't draw generated markers
            var stackGroup = trace.stackgroup;
            var isInferZero = stackGroup && (
                gd._fullLayout._scatterStackOpts[xa._id + ya._id][stackGroup].stackgaps === 'infer zero');
            if(trace.marker.maxdisplayed || trace._needsCull) {
                showFilter = isInferZero ? visFilterWithGaps : visFilter;
            }
            else if(stackGroup && !isInferZero) {
                showFilter = gapFilter;
            }

            if(showMarkers) markerFilter = showFilter;
            if(showText) textFilter = showFilter;
        }

        // marker points

        selection = points.selectAll('path.point');

        join = selection.data(markerFilter, keyFunc);

        var enter = join.enter().append('path')
            .classed('point', true);

        if(hasTransition) {
            enter
                .call(Drawing.pointStyle, trace, gd)
                .call(Drawing.translatePoints, xa, ya)
                .style('opacity', 0)
                .transition()
                .style('opacity', 1);
        }

        join.order();

        var styleFns;
        if(showMarkers) {
            styleFns = Drawing.makePointStyleFns(trace);
        }

        join.each(function(d) {
            var el = d3.select(this);
            var sel = transition(el);
            hasNode = Drawing.translatePoint(d, sel, xa, ya);

            if(hasNode) {
                Drawing.singlePointStyle(d, sel, trace, styleFns, gd);

                if(plotinfo.layerClipId) {
                    Drawing.hideOutsideRangePoint(d, sel, xa, ya, trace.xcalendar, trace.ycalendar);
                }

                if(trace.customdata) {
                    el.classed('plotly-customdata', d.data !== null && d.data !== undefined);
                }
            } else {
                sel.remove();
            }
        });

        if(hasTransition) {
            join.exit().transition()
                .style('opacity', 0)
                .remove();
        } else {
            join.exit().remove();
        }

        // text points
        selection = text.selectAll('g');
        join = selection.data(textFilter, keyFunc);

        // each text needs to go in its own 'g' in case
        // it gets converted to mathjax
        join.enter().append('g').classed('textpoint', true).append('text');

        join.order();

        join.each(function(d) {
            var g = d3.select(this);
            var sel = transition(g.select('text'));
            hasNode = Drawing.translatePoint(d, sel, xa, ya);

            if(hasNode) {
                if(plotinfo.layerClipId) {
                    Drawing.hideOutsideRangePoint(d, g, xa, ya, trace.xcalendar, trace.ycalendar);
                }
            } else {
                g.remove();
            }
        });

        join.selectAll('text')
            .call(Drawing.textPointStyle, trace, gd)
            .each(function(d) {
                // This just *has* to be totally custom becuase of SVG text positioning :(
                // It's obviously copied from translatePoint; we just can't use that
                var x = xa.c2p(d.x);
                var y = ya.c2p(d.y);

                d3.select(this).selectAll('tspan.line').each(function() {
                    transition(d3.select(this)).attr({x: x, y: y});
                });
            });

        join.exit().remove();
    }

    points.datum(cdscatter);
    text.datum(cdscatter);
    makePoints(points, text, cdscatter);

    // lastly, clip points groups of `cliponaxis !== false` traces
    // on `plotinfo._hasClipOnAxisFalse === true` subplots
    var hasClipOnAxisFalse = trace.cliponaxis === false;
    var clipUrl = hasClipOnAxisFalse ? null : plotinfo.layerClipId;
    Drawing.setClipUrl(points, clipUrl, gd);
    Drawing.setClipUrl(text, clipUrl, gd);
}

function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) {
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;
    var xr = d3.extent(Lib.simpleMap(xa.range, xa.r2c));
    var yr = d3.extent(Lib.simpleMap(ya.range, ya.r2c));

    var trace = cdscatter[0].trace;
    if(!subTypes.hasMarkers(trace)) return;
    // if marker.maxdisplayed is used, select a maximum of
    // mnum markers to show, from the set that are in the viewport
    var mnum = trace.marker.maxdisplayed;

    // TODO: remove some as we get away from the viewport?
    if(mnum === 0) return;

    var cd = cdscatter.filter(function(v) {
        return v.x >= xr[0] && v.x <= xr[1] && v.y >= yr[0] && v.y <= yr[1];
    });
    var inc = Math.ceil(cd.length / mnum);
    var tnum = 0;
    cdscatterAll.forEach(function(cdj, j) {
        var tracei = cdj[0].trace;
        if(subTypes.hasMarkers(tracei) &&
                tracei.marker.maxdisplayed > 0 && j < idx) {
            tnum++;
        }
    });

    // if multiple traces use maxdisplayed, stagger which markers we
    // display this formula offsets successive traces by 1/3 of the
    // increment, adding an extra small amount after each triplet so
    // it's not quite periodic
    var i0 = Math.round(tnum * inc / 3 + Math.floor(tnum / 3) * inc / 7.1);

    // for error bars: save in cd which markers to show
    // so we don't have to repeat this
    cdscatter.forEach(function(v) { delete v.vis; });
    cd.forEach(function(v, i) {
        if(Math.round((i + i0) % inc) === 0) v.vis = true;
    });
}

},{"../../components/drawing":592,"../../lib":694,"../../lib/polygon":706,"../../registry":825,"./line_points":1061,"./link_traces":1063,"./subtypes":1071,"d3":149}],1068:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var subtypes = _dereq_('./subtypes');

module.exports = function selectPoints(searchInfo, selectionTester) {
    var cd = searchInfo.cd;
    var xa = searchInfo.xaxis;
    var ya = searchInfo.yaxis;
    var selection = [];
    var trace = cd[0].trace;
    var i;
    var di;
    var x;
    var y;

    var hasOnlyLines = (!subtypes.hasMarkers(trace) && !subtypes.hasText(trace));
    if(hasOnlyLines) return [];

    if(selectionTester === false) { // clear selection
        for(i = 0; i < cd.length; i++) {
            cd[i].selected = 0;
        }
    }
    else {
        for(i = 0; i < cd.length; i++) {
            di = cd[i];
            x = xa.c2p(di.x);
            y = ya.c2p(di.y);

            if((di.i !== null) && selectionTester.contains([x, y], false, i, searchInfo)) {
                selection.push({
                    pointNumber: di.i,
                    x: xa.c2d(di.x),
                    y: ya.c2d(di.y)
                });
                di.selected = 1;
            } else {
                di.selected = 0;
            }
        }
    }

    return selection;
};

},{"./subtypes":1071}],1069:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var perStackAttrs = ['orientation', 'groupnorm', 'stackgaps'];

module.exports = function handleStackDefaults(traceIn, traceOut, layout, coerce) {
    var stackOpts = layout._scatterStackOpts;

    var stackGroup = coerce('stackgroup');
    if(stackGroup) {
        // use independent stacking options per subplot
        var subplot = traceOut.xaxis + traceOut.yaxis;
        var subplotStackOpts = stackOpts[subplot];
        if(!subplotStackOpts) subplotStackOpts = stackOpts[subplot] = {};

        var groupOpts = subplotStackOpts[stackGroup];
        var firstTrace = false;
        if(groupOpts) {
            groupOpts.traces.push(traceOut);
        }
        else {
            groupOpts = subplotStackOpts[stackGroup] = {
                // keep track of trace indices for use during stacking calculations
                // this will be filled in during `calc` and used during `crossTraceCalc`
                // so it's OK if we don't recreate it during a non-calc edit
                traceIndices: [],
                // Hold on to the whole set of prior traces
                // First one is most important, so we can clear defaults
                // there if we find explicit values only in later traces.
                // We're only going to *use* the values stored in groupOpts,
                // but for the editor and validate we want things self-consistent
                // The full set of traces is used only to fix `fill` default if
                // we find `orientation: 'h'` beyond the first trace
                traces: [traceOut]
            };
            firstTrace = true;
        }
        // TODO: how is this going to work with groupby transforms?
        // in principle it should be OK I guess, as long as explicit group styles
        // don't override explicit base-trace styles?

        var dflts = {
            orientation: (traceOut.x && !traceOut.y) ? 'h' : 'v'
        };

        for(var i = 0; i < perStackAttrs.length; i++) {
            var attr = perStackAttrs[i];
            var attrFound = attr + 'Found';
            if(!groupOpts[attrFound]) {
                var traceHasAttr = traceIn[attr] !== undefined;
                var isOrientation = attr === 'orientation';
                if(traceHasAttr || firstTrace) {
                    groupOpts[attr] = coerce(attr, dflts[attr]);

                    if(isOrientation) {
                        groupOpts.fillDflt = groupOpts[attr] === 'h' ?
                            'tonextx' : 'tonexty';
                    }

                    if(traceHasAttr) {
                        // Note: this will show a value here even if it's invalid
                        // in which case it will revert to default.
                        groupOpts[attrFound] = true;

                        // Note: only one trace in the stack will get a _fullData
                        // entry for a given stack-wide attribute. If no traces
                        // (or the first trace) specify that attribute, the
                        // first trace will get it. If the first trace does NOT
                        // specify it but some later trace does, then it gets
                        // removed from the first trace and only included in the
                        // one that specified it. This is mostly important for
                        // editors (that want to see the full values to know
                        // what settings are available) and Plotly.react diffing.
                        // Editors may want to use fullLayout._scatterStackOpts
                        // directly and make these settings available from all
                        // traces in the stack... then set the new value into
                        // the first trace, and clear all later traces.
                        if(!firstTrace) {
                            delete groupOpts.traces[0][attr];

                            // orientation can affect default fill of previous traces
                            if(isOrientation) {
                                for(var j = 0; j < groupOpts.traces.length - 1; j++) {
                                    var trace2 = groupOpts.traces[j];
                                    if(trace2._input.fill !== trace2.fill) {
                                        trace2.fill = groupOpts.fillDflt;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return groupOpts;
    }
};

},{}],1070:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');
var Drawing = _dereq_('../../components/drawing');
var Registry = _dereq_('../../registry');

function style(gd, cd) {
    var s = cd ? cd[0].node3 : d3.select(gd).selectAll('g.trace.scatter');

    s.style('opacity', function(d) {
        return d[0].trace.opacity;
    });

    s.selectAll('g.points').each(function(d) {
        var sel = d3.select(this);
        var trace = d.trace || d[0].trace;
        stylePoints(sel, trace, gd);
    });

    s.selectAll('g.text').each(function(d) {
        var sel = d3.select(this);
        var trace = d.trace || d[0].trace;
        styleText(sel, trace, gd);
    });

    s.selectAll('g.trace path.js-line')
        .call(Drawing.lineGroupStyle);

    s.selectAll('g.trace path.js-fill')
        .call(Drawing.fillGroupStyle);

    Registry.getComponentMethod('errorbars', 'style')(s);
}

function stylePoints(sel, trace, gd) {
    Drawing.pointStyle(sel.selectAll('path.point'), trace, gd);
}

function styleText(sel, trace, gd) {
    Drawing.textPointStyle(sel.selectAll('text'), trace, gd);
}

function styleOnSelect(gd, cd) {
    var s = cd[0].node3;
    var trace = cd[0].trace;

    if(trace.selectedpoints) {
        Drawing.selectedPointStyle(s.selectAll('path.point'), trace);
        Drawing.selectedTextStyle(s.selectAll('text'), trace);
    } else {
        stylePoints(s, trace, gd);
        styleText(s, trace, gd);
    }
}

module.exports = {
    style: style,
    stylePoints: stylePoints,
    styleText: styleText,
    styleOnSelect: styleOnSelect
};

},{"../../components/drawing":592,"../../registry":825,"d3":149}],1071:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

module.exports = {
    hasLines: function(trace) {
        return trace.visible && trace.mode &&
            trace.mode.indexOf('lines') !== -1;
    },

    hasMarkers: function(trace) {
        return trace.visible && (
            (trace.mode && trace.mode.indexOf('markers') !== -1) ||
            // until splom implements 'mode'
            trace.type === 'splom'
        );
    },

    hasText: function(trace) {
        return trace.visible && trace.mode &&
            trace.mode.indexOf('text') !== -1;
    },

    isBubble: function(trace) {
        return Lib.isPlainObject(trace.marker) &&
            Lib.isArrayOrTypedArray(trace.marker.size);
    }
};

},{"../../lib":694}],1072:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

/*
 * opts: object of flags to control features not all text users support
 *   noSelect: caller does not support selected/unselected attribute containers
 */
module.exports = function(traceIn, traceOut, layout, coerce, opts) {
    opts = opts || {};

    coerce('textposition');
    Lib.coerceFont(coerce, 'textfont', layout.font);

    if(!opts.noSelect) {
        coerce('selected.textfont.color');
        coerce('unselected.textfont.color');
    }
};

},{"../../lib":694}],1073:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Registry = _dereq_('../../registry');

module.exports = function handleXYDefaults(traceIn, traceOut, layout, coerce) {
    var x = coerce('x');
    var y = coerce('y');
    var len;

    var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
    handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout);

    if(x) {
        var xlen = Lib.minRowLength(x);
        if(y) {
            len = Math.min(xlen, Lib.minRowLength(y));
        } else {
            len = xlen;
            coerce('y0');
            coerce('dy');
        }
    } else {
        if(!y) return 0;

        len = Lib.minRowLength(y);
        coerce('x0');
        coerce('dx');
    }

    traceOut._length = len;

    return len;
};

},{"../../lib":694,"../../registry":825}],1074:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterAttrs = _dereq_('../scatter/attributes');
var colorAttributes = _dereq_('../../components/colorscale/attributes');
var baseAttrs = _dereq_('../../plots/attributes');
var DASHES = _dereq_('../../constants/gl3d_dashes');

var MARKER_SYMBOLS = _dereq_('../../constants/gl3d_markers');
var extendFlat = _dereq_('../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;

var scatterLineAttrs = scatterAttrs.line;
var scatterMarkerAttrs = scatterAttrs.marker;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;

var lineAttrs = extendFlat({
    width: scatterLineAttrs.width,
    dash: {
        valType: 'enumerated',
        values: Object.keys(DASHES),
        dflt: 'solid',
        
        
    }
}, colorAttributes('line'));

function makeProjectionAttr(axLetter) {
    return {
        show: {
            valType: 'boolean',
            
            dflt: false,
            
        },
        opacity: {
            valType: 'number',
            
            min: 0,
            max: 1,
            dflt: 1,
            
        },
        scale: {
            valType: 'number',
            
            min: 0,
            max: 10,
            dflt: 2 / 3,
            
        }
    };
}

var attrs = module.exports = overrideAll({
    x: scatterAttrs.x,
    y: scatterAttrs.y,
    z: {
        valType: 'data_array',
        
    },

    text: extendFlat({}, scatterAttrs.text, {
        
    }),
    hovertext: extendFlat({}, scatterAttrs.hovertext, {
        
    }),

    mode: extendFlat({}, scatterAttrs.mode,  // shouldn't this be on-par with 2D?
        {dflt: 'lines+markers'}),
    surfaceaxis: {
        valType: 'enumerated',
        
        values: [-1, 0, 1, 2],
        dflt: -1,
        
    },
    surfacecolor: {
        valType: 'color',
        
        
    },
    projection: {
        x: makeProjectionAttr('x'),
        y: makeProjectionAttr('y'),
        z: makeProjectionAttr('z')
    },

    connectgaps: scatterAttrs.connectgaps,
    line: lineAttrs,

    marker: extendFlat({  // Parity with scatter.js?
        symbol: {
            valType: 'enumerated',
            values: Object.keys(MARKER_SYMBOLS),
            
            dflt: 'circle',
            arrayOk: true,
            
        },
        size: extendFlat({}, scatterMarkerAttrs.size, {dflt: 8}),
        sizeref: scatterMarkerAttrs.sizeref,
        sizemin: scatterMarkerAttrs.sizemin,
        sizemode: scatterMarkerAttrs.sizemode,
        opacity: extendFlat({}, scatterMarkerAttrs.opacity, {
            arrayOk: false,
            
        }),
        colorbar: scatterMarkerAttrs.colorbar,

        line: extendFlat({
            width: extendFlat({}, scatterMarkerLineAttrs.width, {arrayOk: false})
        },
            colorAttributes('marker.line')
        )
    },
        colorAttributes('marker')
    ),

    textposition: extendFlat({}, scatterAttrs.textposition, {dflt: 'top center'}),
    textfont: {
        color: scatterAttrs.textfont.color,
        size: scatterAttrs.textfont.size,
        family: extendFlat({}, scatterAttrs.textfont.family, {arrayOk: false})
    },

    hoverinfo: extendFlat({}, baseAttrs.hoverinfo)
}, 'calc', 'nested');

attrs.x.editType = attrs.y.editType = attrs.z.editType = 'calc+clearAxisTypes';

},{"../../components/colorscale/attributes":578,"../../constants/gl3d_dashes":668,"../../constants/gl3d_markers":669,"../../lib/extend":684,"../../plot_api/edit_types":725,"../../plots/attributes":739,"../scatter/attributes":1047}],1075:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var arraysToCalcdata = _dereq_('../scatter/arrays_to_calcdata');
var calcColorscale = _dereq_('../scatter/colorscale_calc');

/**
 * This is a kludge to put the array attributes into
 * calcdata the way Scatter.plot does, so that legends and
 * popovers know what to do with them.
 */
module.exports = function calc(gd, trace) {
    var cd = [{x: false, y: false, trace: trace, t: {}}];

    arraysToCalcdata(cd, trace);
    calcColorscale(gd, trace);

    return cd;
};

},{"../scatter/arrays_to_calcdata":1046,"../scatter/colorscale_calc":1050}],1076:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');

function calculateAxisErrors(data, params, scaleFactor, axis) {
    if(!params || !params.visible) return null;

    var computeError = Registry.getComponentMethod('errorbars', 'makeComputeError')(params);
    var result = new Array(data.length);

    for(var i = 0; i < data.length; i++) {
        var errors = computeError(+data[i], i);

        if(axis.type === 'log') {
            var point = axis.c2l(data[i]);
            var min = data[i] - errors[0];
            var max = data[i] + errors[1];

            result[i] = [
                (axis.c2l(min, true) - point) * scaleFactor,
                (axis.c2l(max, true) - point) * scaleFactor
            ];

            // Keep track of the lower error bound which isn't negative!
            if(min > 0) {
                var lower = axis.c2l(min);
                if(!axis._lowerLogErrorBound) axis._lowerLogErrorBound = lower;
                axis._lowerErrorBound = Math.min(axis._lowerLogErrorBound, lower);
            }
        } else {
            result[i] = [
                -errors[0] * scaleFactor,
                errors[1] * scaleFactor
            ];
        }
    }

    return result;
}

function dataLength(array) {
    for(var i = 0; i < array.length; i++) {
        if(array[i]) return array[i].length;
    }
    return 0;
}

function calculateErrors(data, scaleFactor, sceneLayout) {
    var errors = [
        calculateAxisErrors(data.x, data.error_x, scaleFactor[0], sceneLayout.xaxis),
        calculateAxisErrors(data.y, data.error_y, scaleFactor[1], sceneLayout.yaxis),
        calculateAxisErrors(data.z, data.error_z, scaleFactor[2], sceneLayout.zaxis)
    ];

    var n = dataLength(errors);
    if(n === 0) return null;

    var errorBounds = new Array(n);

    for(var i = 0; i < n; i++) {
        var bound = [[0, 0, 0], [0, 0, 0]];

        for(var j = 0; j < 3; j++) {
            if(errors[j]) {
                for(var k = 0; k < 2; k++) {
                    bound[k][j] = errors[j][i][k];
                }
            }
        }

        errorBounds[i] = bound;
    }

    return errorBounds;
}

module.exports = calculateErrors;

},{"../../registry":825}],1077:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var createLinePlot = _dereq_('gl-line3d');
var createScatterPlot = _dereq_('gl-scatter3d');
var createErrorBars = _dereq_('gl-error3d');
var createMesh = _dereq_('gl-mesh3d');
var triangulate = _dereq_('delaunay-triangulate');

var Lib = _dereq_('../../lib');
var str2RgbaArray = _dereq_('../../lib/str2rgbarray');
var formatColor = _dereq_('../../lib/gl_format_color').formatColor;
var makeBubbleSizeFn = _dereq_('../scatter/make_bubble_size_func');
var DASH_PATTERNS = _dereq_('../../constants/gl3d_dashes');
var MARKER_SYMBOLS = _dereq_('../../constants/gl3d_markers');

var calculateError = _dereq_('./calc_errors');

function LineWithMarkers(scene, uid) {
    this.scene = scene;
    this.uid = uid;
    this.linePlot = null;
    this.scatterPlot = null;
    this.errorBars = null;
    this.textMarkers = null;
    this.delaunayMesh = null;
    this.color = null;
    this.mode = '';
    this.dataPoints = [];
    this.axesBounds = [
        [-Infinity, -Infinity, -Infinity],
        [Infinity, Infinity, Infinity]
    ];
    this.textLabels = null;
    this.data = null;
}

var proto = LineWithMarkers.prototype;

proto.handlePick = function(selection) {
    if(selection.object &&
        (selection.object === this.linePlot ||
         selection.object === this.delaunayMesh ||
         selection.object === this.textMarkers ||
         selection.object === this.scatterPlot)
    ) {
        var ind = selection.index = selection.data.index;

        if(selection.object.highlight) {
            selection.object.highlight(null);
        }
        if(this.scatterPlot) {
            selection.object = this.scatterPlot;
            this.scatterPlot.highlight(selection.data);
        }

        selection.textLabel = '';
        if(this.textLabels) {
            if(Array.isArray(this.textLabels)) {
                if(this.textLabels[ind] || this.textLabels[ind] === 0) {
                    selection.textLabel = this.textLabels[ind];
                }
            } else {
                selection.textLabel = this.textLabels;
            }
        }

        selection.traceCoordinate = [
            this.data.x[ind],
            this.data.y[ind],
            this.data.z[ind]
        ];

        return true;
    }
};

function constructDelaunay(points, color, axis) {
    var u = (axis + 1) % 3;
    var v = (axis + 2) % 3;
    var filteredPoints = [];
    var filteredIds = [];
    var i;

    for(i = 0; i < points.length; ++i) {
        var p = points[i];
        if(isNaN(p[u]) || !isFinite(p[u]) ||
           isNaN(p[v]) || !isFinite(p[v])) {
            continue;
        }
        filteredPoints.push([p[u], p[v]]);
        filteredIds.push(i);
    }
    var cells = triangulate(filteredPoints);
    for(i = 0; i < cells.length; ++i) {
        var c = cells[i];
        for(var j = 0; j < c.length; ++j) {
            c[j] = filteredIds[c[j]];
        }
    }
    return {
        positions: points,
        cells: cells,
        meshColor: color
    };
}

function calculateErrorParams(errors) {
    var capSize = [0.0, 0.0, 0.0];
    var color = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
    var lineWidth = [1.0, 1.0, 1.0];

    for(var i = 0; i < 3; i++) {
        var e = errors[i];

        if(e && e.copy_zstyle !== false && errors[2].visible !== false) e = errors[2];
        if(!e || !e.visible) continue;

        capSize[i] = e.width / 2;  // ballpark rescaling
        color[i] = str2RgbaArray(e.color);
        lineWidth[i] = e.thickness;

    }

    return {capSize: capSize, color: color, lineWidth: lineWidth};
}

function parseAlignmentX(a) {
    if(a === null || a === undefined) return 0;

    return (a.indexOf('left') > -1) ? -1 :
           (a.indexOf('right') > -1) ? 1 : 0;
}

function parseAlignmentY(a) {
    if(a === null || a === undefined) return 0;

    return (a.indexOf('top') > -1) ? -1 :
           (a.indexOf('bottom') > -1) ? 1 : 0;
}

function calculateTextOffset(tp) {
    // Read out text properties

    var defaultAlignmentX = 0;
    var defaultAlignmentY = 0;

    var textOffset = [
        defaultAlignmentX,
        defaultAlignmentY
    ];

    if(Array.isArray(tp)) {
        for(var i = 0; i < tp.length; i++) {
            textOffset[i] = [
                defaultAlignmentX,
                defaultAlignmentY
            ];
            if(tp[i]) {
                textOffset[i][0] = parseAlignmentX(tp[i]);
                textOffset[i][1] = parseAlignmentY(tp[i]);
            }
        }
    } else {
        textOffset[0] = parseAlignmentX(tp);
        textOffset[1] = parseAlignmentY(tp);
    }

    return textOffset;
}


function calculateSize(sizeIn, sizeFn) {
    // rough parity with Plotly 2D markers
    return sizeFn(sizeIn * 4);
}

function calculateSymbol(symbolIn) {
    return MARKER_SYMBOLS[symbolIn];
}

function formatParam(paramIn, len, calculate, dflt, extraFn) {
    var paramOut = null;

    if(Lib.isArrayOrTypedArray(paramIn)) {
        paramOut = [];

        for(var i = 0; i < len; i++) {
            if(paramIn[i] === undefined) paramOut[i] = dflt;
            else paramOut[i] = calculate(paramIn[i], extraFn);
        }

    }
    else paramOut = calculate(paramIn, Lib.identity);

    return paramOut;
}


function convertPlotlyOptions(scene, data) {
    var points = [];
    var sceneLayout = scene.fullSceneLayout;
    var scaleFactor = scene.dataScale;
    var xaxis = sceneLayout.xaxis;
    var yaxis = sceneLayout.yaxis;
    var zaxis = sceneLayout.zaxis;
    var marker = data.marker;
    var line = data.line;
    var x = data.x || [];
    var y = data.y || [];
    var z = data.z || [];
    var len = x.length;
    var xcalendar = data.xcalendar;
    var ycalendar = data.ycalendar;
    var zcalendar = data.zcalendar;
    var xc, yc, zc;
    var params, i;
    var text;

    // Convert points
    for(i = 0; i < len; i++) {
        // sanitize numbers and apply transforms based on axes.type
        xc = xaxis.d2l(x[i], 0, xcalendar) * scaleFactor[0];
        yc = yaxis.d2l(y[i], 0, ycalendar) * scaleFactor[1];
        zc = zaxis.d2l(z[i], 0, zcalendar) * scaleFactor[2];

        points[i] = [xc, yc, zc];
    }

    // convert text
    if(Array.isArray(data.text)) text = data.text;
    else if(data.text !== undefined) {
        text = new Array(len);
        for(i = 0; i < len; i++) text[i] = data.text;
    }

    // Build object parameters
    params = {
        position: points,
        mode: data.mode,
        text: text
    };

    if('line' in data) {
        params.lineColor = formatColor(line, 1, len);
        params.lineWidth = line.width;
        params.lineDashes = line.dash;
    }

    if('marker' in data) {
        var sizeFn = makeBubbleSizeFn(data);

        params.scatterColor = formatColor(marker, 1, len);
        params.scatterSize = formatParam(marker.size, len, calculateSize, 20, sizeFn);
        params.scatterMarker = formatParam(marker.symbol, len, calculateSymbol, '●');
        params.scatterLineWidth = marker.line.width;  // arrayOk === false
        params.scatterLineColor = formatColor(marker.line, 1, len);
        params.scatterAngle = 0;
    }

    if('textposition' in data) {
        params.textOffset = calculateTextOffset(data.textposition);
        params.textColor = formatColor(data.textfont, 1, len);
        params.textSize = formatParam(data.textfont.size, len, Lib.identity, 12);
        params.textFont = data.textfont.family;  // arrayOk === false
        params.textAngle = 0;
    }

    var dims = ['x', 'y', 'z'];
    params.project = [false, false, false];
    params.projectScale = [1, 1, 1];
    params.projectOpacity = [1, 1, 1];
    for(i = 0; i < 3; ++i) {
        var projection = data.projection[dims[i]];
        if((params.project[i] = projection.show)) {
            params.projectOpacity[i] = projection.opacity;
            params.projectScale[i] = projection.scale;
        }
    }

    params.errorBounds = calculateError(data, scaleFactor, sceneLayout);

    var errorParams = calculateErrorParams([data.error_x, data.error_y, data.error_z]);
    params.errorColor = errorParams.color;
    params.errorLineWidth = errorParams.lineWidth;
    params.errorCapSize = errorParams.capSize;

    params.delaunayAxis = data.surfaceaxis;
    params.delaunayColor = str2RgbaArray(data.surfacecolor);

    return params;
}

function arrayToColor(color) {
    if(Array.isArray(color)) {
        var c = color[0];

        if(Array.isArray(c)) color = c;

        return 'rgb(' + color.slice(0, 3).map(function(x) {
            return Math.round(x * 255);
        }) + ')';
    }

    return null;
}

proto.update = function(data) {
    var gl = this.scene.glplot.gl;
    var lineOptions;
    var scatterOptions;
    var errorOptions;
    var textOptions;
    var dashPattern = DASH_PATTERNS.solid;

    // Save data
    this.data = data;

    // Run data conversion
    var options = convertPlotlyOptions(this.scene, data);

    if('mode' in options) {
        this.mode = options.mode;
    }
    if('lineDashes' in options) {
        if(options.lineDashes in DASH_PATTERNS) {
            dashPattern = DASH_PATTERNS[options.lineDashes];
        }
    }

    this.color = arrayToColor(options.scatterColor) ||
                 arrayToColor(options.lineColor);

    // Save data points
    this.dataPoints = options.position;

    lineOptions = {
        gl: gl,
        position: options.position,
        color: options.lineColor,
        lineWidth: options.lineWidth || 1,
        dashes: dashPattern[0],
        dashScale: dashPattern[1],
        opacity: data.opacity,
        connectGaps: data.connectgaps
    };

    if(this.mode.indexOf('lines') !== -1) {
        if(this.linePlot) this.linePlot.update(lineOptions);
        else {
            this.linePlot = createLinePlot(lineOptions);
            this.linePlot._trace = this;
            this.scene.glplot.add(this.linePlot);
        }
    } else if(this.linePlot) {
        this.scene.glplot.remove(this.linePlot);
        this.linePlot.dispose();
        this.linePlot = null;
    }

    // N.B. marker.opacity must be a scalar for performance
    var scatterOpacity = data.opacity;
    if(data.marker && data.marker.opacity) scatterOpacity *= data.marker.opacity;

    scatterOptions = {
        gl: gl,
        position: options.position,
        color: options.scatterColor,
        size: options.scatterSize,
        glyph: options.scatterMarker,
        opacity: scatterOpacity,
        orthographic: true,
        lineWidth: options.scatterLineWidth,
        lineColor: options.scatterLineColor,
        project: options.project,
        projectScale: options.projectScale,
        projectOpacity: options.projectOpacity
    };

    if(this.mode.indexOf('markers') !== -1) {
        if(this.scatterPlot) this.scatterPlot.update(scatterOptions);
        else {
            this.scatterPlot = createScatterPlot(scatterOptions);
            this.scatterPlot._trace = this;
            this.scatterPlot.highlightScale = 1;
            this.scene.glplot.add(this.scatterPlot);
        }
    } else if(this.scatterPlot) {
        this.scene.glplot.remove(this.scatterPlot);
        this.scatterPlot.dispose();
        this.scatterPlot = null;
    }

    textOptions = {
        gl: gl,
        position: options.position,
        glyph: options.text,
        color: options.textColor,
        size: options.textSize,
        angle: options.textAngle,
        alignment: options.textOffset,
        font: options.textFont,
        orthographic: true,
        lineWidth: 0,
        project: false,
        opacity: data.opacity
    };

    this.textLabels = data.hovertext || data.text;

    if(this.mode.indexOf('text') !== -1) {
        if(this.textMarkers) this.textMarkers.update(textOptions);
        else {
            this.textMarkers = createScatterPlot(textOptions);
            this.textMarkers._trace = this;
            this.textMarkers.highlightScale = 1;
            this.scene.glplot.add(this.textMarkers);
        }
    } else if(this.textMarkers) {
        this.scene.glplot.remove(this.textMarkers);
        this.textMarkers.dispose();
        this.textMarkers = null;
    }

    errorOptions = {
        gl: gl,
        position: options.position,
        color: options.errorColor,
        error: options.errorBounds,
        lineWidth: options.errorLineWidth,
        capSize: options.errorCapSize,
        opacity: data.opacity
    };
    if(this.errorBars) {
        if(options.errorBounds) {
            this.errorBars.update(errorOptions);
        } else {
            this.scene.glplot.remove(this.errorBars);
            this.errorBars.dispose();
            this.errorBars = null;
        }
    } else if(options.errorBounds) {
        this.errorBars = createErrorBars(errorOptions);
        this.errorBars._trace = this;
        this.scene.glplot.add(this.errorBars);
    }

    if(options.delaunayAxis >= 0) {
        var delaunayOptions = constructDelaunay(
            options.position,
            options.delaunayColor,
            options.delaunayAxis
        );
        delaunayOptions.opacity = data.opacity;

        if(this.delaunayMesh) {
            this.delaunayMesh.update(delaunayOptions);
        } else {
            delaunayOptions.gl = gl;
            this.delaunayMesh = createMesh(delaunayOptions);
            this.delaunayMesh._trace = this;
            this.scene.glplot.add(this.delaunayMesh);
        }
    } else if(this.delaunayMesh) {
        this.scene.glplot.remove(this.delaunayMesh);
        this.delaunayMesh.dispose();
        this.delaunayMesh = null;
    }
};

proto.dispose = function() {
    if(this.linePlot) {
        this.scene.glplot.remove(this.linePlot);
        this.linePlot.dispose();
    }
    if(this.scatterPlot) {
        this.scene.glplot.remove(this.scatterPlot);
        this.scatterPlot.dispose();
    }
    if(this.errorBars) {
        this.scene.glplot.remove(this.errorBars);
        this.errorBars.dispose();
    }
    if(this.textMarkers) {
        this.scene.glplot.remove(this.textMarkers);
        this.textMarkers.dispose();
    }
    if(this.delaunayMesh) {
        this.scene.glplot.remove(this.delaunayMesh);
        this.delaunayMesh.dispose();
    }
};

function createLineWithMarkers(scene, data) {
    var plot = new LineWithMarkers(scene, data.uid);
    plot.update(data);
    return plot;
}

module.exports = createLineWithMarkers;

},{"../../constants/gl3d_dashes":668,"../../constants/gl3d_markers":669,"../../lib":694,"../../lib/gl_format_color":691,"../../lib/str2rgbarray":717,"../scatter/make_bubble_size_func":1064,"./calc_errors":1076,"delaunay-triangulate":151,"gl-error3d":238,"gl-line3d":246,"gl-mesh3d":270,"gl-scatter3d":286}],1078:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');

var subTypes = _dereq_('../scatter/subtypes');
var handleMarkerDefaults = _dereq_('../scatter/marker_defaults');
var handleLineDefaults = _dereq_('../scatter/line_defaults');
var handleTextDefaults = _dereq_('../scatter/text_defaults');

var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {

    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var len = handleXYZDefaults(traceIn, traceOut, coerce, layout);
    if(!len) {
        traceOut.visible = false;
        return;
    }

    coerce('text');
    coerce('hovertext');
    coerce('mode');

    if(subTypes.hasLines(traceOut)) {
        coerce('connectgaps');
        handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
    }

    if(subTypes.hasMarkers(traceOut)) {
        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {noSelect: true});
    }

    if(subTypes.hasText(traceOut)) {
        handleTextDefaults(traceIn, traceOut, layout, coerce, {noSelect: true});
    }

    var lineColor = (traceOut.line || {}).color;
    var markerColor = (traceOut.marker || {}).color;
    if(coerce('surfaceaxis') >= 0) coerce('surfacecolor', lineColor || markerColor);

    var dims = ['x', 'y', 'z'];
    for(var i = 0; i < 3; ++i) {
        var projection = 'projection.' + dims[i];
        if(coerce(projection + '.show')) {
            coerce(projection + '.opacity');
            coerce(projection + '.scale');
        }
    }

    var errorBarsSupplyDefaults = Registry.getComponentMethod('errorbars', 'supplyDefaults');
    errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, {axis: 'z'});
    errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, {axis: 'y', inherit: 'z'});
    errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, {axis: 'x', inherit: 'z'});
};

function handleXYZDefaults(traceIn, traceOut, coerce, layout) {
    var len = 0;
    var x = coerce('x');
    var y = coerce('y');
    var z = coerce('z');

    var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
    handleCalendarDefaults(traceIn, traceOut, ['x', 'y', 'z'], layout);

    if(x && y && z) {
        // TODO: what happens if one is missing?
        len = Math.min(x.length, y.length, z.length);
        traceOut._length = traceOut._xlength = traceOut._ylength = traceOut._zlength = len;
    }

    return len;
}

},{"../../lib":694,"../../registry":825,"../scatter/line_defaults":1060,"../scatter/marker_defaults":1066,"../scatter/subtypes":1071,"../scatter/text_defaults":1072,"./attributes":1074}],1079:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Scatter3D = {};

Scatter3D.plot = _dereq_('./convert');
Scatter3D.attributes = _dereq_('./attributes');
Scatter3D.markerSymbols = _dereq_('../../constants/gl3d_markers');
Scatter3D.supplyDefaults = _dereq_('./defaults');
Scatter3D.colorbar = [
    {
        container: 'marker',
        min: 'cmin',
        max: 'cmax'
    }, {
        container: 'line',
        min: 'cmin',
        max: 'cmax'
    }
];
Scatter3D.calc = _dereq_('./calc');

Scatter3D.moduleType = 'trace';
Scatter3D.name = 'scatter3d';
Scatter3D.basePlotModule = _dereq_('../../plots/gl3d');
Scatter3D.categories = ['gl3d', 'symbols', 'showLegend'];
Scatter3D.meta = {
    
    
};

module.exports = Scatter3D;

},{"../../constants/gl3d_markers":669,"../../plots/gl3d":785,"./attributes":1074,"./calc":1075,"./convert":1077,"./defaults":1078}],1080:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterAttrs = _dereq_('../scatter/attributes');
var plotAttrs = _dereq_('../../plots/attributes');
var colorAttributes = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;

var scatterMarkerAttrs = scatterAttrs.marker;
var scatterLineAttrs = scatterAttrs.line;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;

module.exports = {
    carpet: {
        valType: 'string',
        
        editType: 'calc',
        
    },
    a: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    b: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    mode: extendFlat({}, scatterAttrs.mode, {dflt: 'markers'}),
    text: extendFlat({}, scatterAttrs.text, {
        
    }),
    line: {
        color: scatterLineAttrs.color,
        width: scatterLineAttrs.width,
        dash: scatterLineAttrs.dash,
        shape: extendFlat({}, scatterLineAttrs.shape,
            {values: ['linear', 'spline']}),
        smoothing: scatterLineAttrs.smoothing,
        editType: 'calc'
    },
    connectgaps: scatterAttrs.connectgaps,
    fill: extendFlat({}, scatterAttrs.fill, {
        values: ['none', 'toself', 'tonext'],
        dflt: 'none',
        
    }),
    fillcolor: scatterAttrs.fillcolor,
    marker: extendFlat({
        symbol: scatterMarkerAttrs.symbol,
        opacity: scatterMarkerAttrs.opacity,
        maxdisplayed: scatterMarkerAttrs.maxdisplayed,
        size: scatterMarkerAttrs.size,
        sizeref: scatterMarkerAttrs.sizeref,
        sizemin: scatterMarkerAttrs.sizemin,
        sizemode: scatterMarkerAttrs.sizemode,
        line: extendFlat({
            width: scatterMarkerLineAttrs.width,
            editType: 'calc'
        },
            colorAttributes('marker.line')
        ),
        gradient: scatterMarkerAttrs.gradient,
        editType: 'calc'
    }, colorAttributes('marker'), {
        colorbar: colorbarAttrs
    }),

    textfont: scatterAttrs.textfont,
    textposition: scatterAttrs.textposition,

    selected: scatterAttrs.selected,
    unselected: scatterAttrs.unselected,

    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
        flags: ['a', 'b', 'text', 'name']
    }),
    hoveron: scatterAttrs.hoveron,
};

},{"../../components/colorbar/attributes":572,"../../components/colorscale/attributes":578,"../../lib/extend":684,"../../plots/attributes":739,"../scatter/attributes":1047}],1081:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var calcColorscale = _dereq_('../scatter/colorscale_calc');
var arraysToCalcdata = _dereq_('../scatter/arrays_to_calcdata');
var calcSelection = _dereq_('../scatter/calc_selection');
var calcMarkerSize = _dereq_('../scatter/calc').calcMarkerSize;
var lookupCarpet = _dereq_('../carpet/lookup_carpetid');

module.exports = function calc(gd, trace) {
    var carpet = trace._carpetTrace = lookupCarpet(gd, trace);
    if(!carpet || !carpet.visible || carpet.visible === 'legendonly') return;
    var i;

    // Transfer this over from carpet before plotting since this is a necessary
    // condition in order for cartesian to actually plot this trace:
    trace.xaxis = carpet.xaxis;
    trace.yaxis = carpet.yaxis;

    // make the calcdata array
    var serieslen = trace._length;
    var cd = new Array(serieslen);
    var a, b;
    var needsCull = false;
    for(i = 0; i < serieslen; i++) {
        a = trace.a[i];
        b = trace.b[i];
        if(isNumeric(a) && isNumeric(b)) {
            var xy = carpet.ab2xy(+a, +b, true);
            var visible = carpet.isVisible(+a, +b);
            if(!visible) needsCull = true;
            cd[i] = {x: xy[0], y: xy[1], a: a, b: b, vis: visible};
        }
        else cd[i] = {x: false, y: false};
    }

    trace._needsCull = needsCull;

    cd[0].carpet = carpet;
    cd[0].trace = trace;

    calcMarkerSize(trace, serieslen);
    calcColorscale(gd, trace);
    arraysToCalcdata(cd, trace);
    calcSelection(cd, trace);

    return cd;
};

},{"../carpet/lookup_carpetid":893,"../scatter/arrays_to_calcdata":1046,"../scatter/calc":1048,"../scatter/calc_selection":1049,"../scatter/colorscale_calc":1050,"fast-isnumeric":215}],1082:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

var constants = _dereq_('../scatter/constants');
var subTypes = _dereq_('../scatter/subtypes');
var handleMarkerDefaults = _dereq_('../scatter/marker_defaults');
var handleLineDefaults = _dereq_('../scatter/line_defaults');
var handleLineShapeDefaults = _dereq_('../scatter/line_shape_defaults');
var handleTextDefaults = _dereq_('../scatter/text_defaults');
var handleFillColorDefaults = _dereq_('../scatter/fillcolor_defaults');

var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    coerce('carpet');

    // XXX: Don't hard code this
    traceOut.xaxis = 'x';
    traceOut.yaxis = 'y';

    var a = coerce('a');
    var b = coerce('b');
    var len = Math.min(a.length, b.length);

    if(!len) {
        traceOut.visible = false;
        return;
    }

    traceOut._length = len;

    coerce('text');

    var defaultMode = len < constants.PTS_LINESONLY ? 'lines+markers' : 'lines';
    coerce('mode', defaultMode);

    if(subTypes.hasLines(traceOut)) {
        handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
        handleLineShapeDefaults(traceIn, traceOut, coerce);
        coerce('connectgaps');
    }

    if(subTypes.hasMarkers(traceOut)) {
        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true});
    }

    if(subTypes.hasText(traceOut)) {
        handleTextDefaults(traceIn, traceOut, layout, coerce);
    }

    var dfltHoverOn = [];

    if(subTypes.hasMarkers(traceOut) || subTypes.hasText(traceOut)) {
        coerce('marker.maxdisplayed');
        dfltHoverOn.push('points');
    }

    coerce('fill');
    if(traceOut.fill !== 'none') {
        handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
        if(!subTypes.hasLines(traceOut)) handleLineShapeDefaults(traceIn, traceOut, coerce);
    }

    if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') {
        dfltHoverOn.push('fills');
    }
    coerce('hoveron', dfltHoverOn.join('+') || 'points');

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};

},{"../../lib":694,"../scatter/constants":1051,"../scatter/fillcolor_defaults":1056,"../scatter/line_defaults":1060,"../scatter/line_shape_defaults":1062,"../scatter/marker_defaults":1066,"../scatter/subtypes":1071,"../scatter/text_defaults":1072,"./attributes":1080}],1083:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function eventData(out, pt, trace, cd, pointNumber) {
    var cdi = cd[pointNumber];

    out.a = cdi.a;
    out.b = cdi.b;

    return out;
};

},{}],1084:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var scatterHover = _dereq_('../scatter/hover');

module.exports = function hoverPoints(pointData, xval, yval, hovermode) {
    var scatterPointData = scatterHover(pointData, xval, yval, hovermode);
    if(!scatterPointData || scatterPointData[0].index === false) return;

    var newPointData = scatterPointData[0];

    // if hovering on a fill, we don't show any point data so the label is
    // unchanged from what scatter gives us - except that it needs to
    // be constrained to the trianglular plot area, not just the rectangular
    // area defined by the synthetic x and y axes
    // TODO: in some cases the vertical middle of the shape is not within
    // the triangular viewport at all, so the label can become disconnected
    // from the shape entirely. But calculating what portion of the shape
    // is actually visible, as constrained by the diagonal axis lines, is not
    // so easy and anyway we lost the information we would have needed to do
    // this inside scatterHover.
    if(newPointData.index === undefined) {
        var yFracUp = 1 - (newPointData.y0 / pointData.ya._length);
        var xLen = pointData.xa._length;
        var xMin = xLen * yFracUp / 2;
        var xMax = xLen - xMin;
        newPointData.x0 = Math.max(Math.min(newPointData.x0, xMax), xMin);
        newPointData.x1 = Math.max(Math.min(newPointData.x1, xMax), xMin);
        return scatterPointData;
    }

    var cdi = newPointData.cd[newPointData.index];

    newPointData.a = cdi.a;
    newPointData.b = cdi.b;

    newPointData.xLabelVal = undefined;
    newPointData.yLabelVal = undefined;
    // TODO: nice formatting, and label by axis title, for a, b, and c?

    var trace = newPointData.trace;
    var carpet = trace._carpet;
    var hoverinfo = cdi.hi || trace.hoverinfo;
    var parts = hoverinfo.split('+');
    var text = [];

    function textPart(ax, val) {
        var prefix;

        if(ax.labelprefix && ax.labelprefix.length > 0) {
            prefix = ax.labelprefix.replace(/ = $/, '');
        } else {
            prefix = ax._hovertitle;
        }

        text.push(prefix + ': ' + val.toFixed(3) + ax.labelsuffix);
    }

    if(parts.indexOf('all') !== -1) parts = ['a', 'b'];
    if(parts.indexOf('a') !== -1) textPart(carpet.aaxis, cdi.a);
    if(parts.indexOf('b') !== -1) textPart(carpet.baxis, cdi.b);

    var ij = carpet.ab2ij([cdi.a, cdi.b]);
    var i0 = Math.floor(ij[0]);
    var ti = ij[0] - i0;

    var j0 = Math.floor(ij[1]);
    var tj = ij[1] - j0;

    var xy = carpet.evalxy([], i0, j0, ti, tj);
    text.push('y: ' + xy[1].toFixed(3));

    newPointData.extraText = text.join('<br>');

    return scatterPointData;
};

},{"../scatter/hover":1058}],1085:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var ScatterCarpet = {};

ScatterCarpet.attributes = _dereq_('./attributes');
ScatterCarpet.supplyDefaults = _dereq_('./defaults');
ScatterCarpet.colorbar = _dereq_('../scatter/marker_colorbar');
ScatterCarpet.calc = _dereq_('./calc');
ScatterCarpet.plot = _dereq_('./plot');
ScatterCarpet.style = _dereq_('../scatter/style').style;
ScatterCarpet.styleOnSelect = _dereq_('../scatter/style').styleOnSelect;
ScatterCarpet.hoverPoints = _dereq_('./hover');
ScatterCarpet.selectPoints = _dereq_('../scatter/select');
ScatterCarpet.eventData = _dereq_('./event_data');

ScatterCarpet.moduleType = 'trace';
ScatterCarpet.name = 'scattercarpet';
ScatterCarpet.basePlotModule = _dereq_('../../plots/cartesian');
ScatterCarpet.categories = ['svg', 'carpet', 'symbols', 'showLegend', 'carpetDependent', 'zoomScale'];
ScatterCarpet.meta = {
    
    
};

module.exports = ScatterCarpet;

},{"../../plots/cartesian":754,"../scatter/marker_colorbar":1065,"../scatter/select":1068,"../scatter/style":1070,"./attributes":1080,"./calc":1081,"./defaults":1082,"./event_data":1083,"./hover":1084,"./plot":1086}],1086:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var scatterPlot = _dereq_('../scatter/plot');
var Axes = _dereq_('../../plots/cartesian/axes');
var Drawing = _dereq_('../../components/drawing');

module.exports = function plot(gd, plotinfoproxy, data, layer) {
    var i, trace, node;

    var carpet = data[0][0].carpet;
    // mimic cartesian plotinfo
    var plotinfo = {
        xaxis: Axes.getFromId(gd, carpet.xaxis || 'x'),
        yaxis: Axes.getFromId(gd, carpet.yaxis || 'y'),
        plot: plotinfoproxy.plot,
    };

    scatterPlot(gd, plotinfo, data, layer);

    for(i = 0; i < data.length; i++) {
        trace = data[i][0].trace;

        // Note: .select is adequate but seems to mutate the node data,
        // which is at least a bit suprising and causes problems elsewhere
        node = layer.selectAll('g.trace' + trace.uid + ' .js-line');

        // Note: it would be more efficient if this didn't need to be applied
        // separately to all scattercarpet traces, but that would require
        // lots of reorganization of scatter traces that is otherwise not
        // necessary. That makes this a potential optimization.
        Drawing.setClipUrl(node, data[i][0].carpet._clipPathId, gd);
    }
};

},{"../../components/drawing":592,"../../plots/cartesian/axes":742,"../scatter/plot":1067}],1087:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var scatterAttrs = _dereq_('../scatter/attributes');
var plotAttrs = _dereq_('../../plots/attributes');
var colorAttributes = _dereq_('../../components/colorscale/attributes');
var dash = _dereq_('../../components/drawing/attributes').dash;

var extendFlat = _dereq_('../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;

var scatterMarkerAttrs = scatterAttrs.marker;
var scatterLineAttrs = scatterAttrs.line;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;

module.exports = overrideAll({
    lon: {
        valType: 'data_array',
        
    },
    lat: {
        valType: 'data_array',
        
    },

    locations: {
        valType: 'data_array',
        
    },
    locationmode: {
        valType: 'enumerated',
        values: ['ISO-3', 'USA-states', 'country names'],
        
        dflt: 'ISO-3',
        
    },

    mode: extendFlat({}, scatterAttrs.mode, {dflt: 'markers'}),

    text: extendFlat({}, scatterAttrs.text, {
        
    }),
    hovertext: extendFlat({}, scatterAttrs.hovertext, {
        
    }),

    textfont: scatterAttrs.textfont,
    textposition: scatterAttrs.textposition,

    line: {
        color: scatterLineAttrs.color,
        width: scatterLineAttrs.width,
        dash: dash
    },
    connectgaps: scatterAttrs.connectgaps,

    marker: extendFlat({
        symbol: scatterMarkerAttrs.symbol,
        opacity: scatterMarkerAttrs.opacity,
        size: scatterMarkerAttrs.size,
        sizeref: scatterMarkerAttrs.sizeref,
        sizemin: scatterMarkerAttrs.sizemin,
        sizemode: scatterMarkerAttrs.sizemode,
        colorbar: scatterMarkerAttrs.colorbar,
        line: extendFlat({
            width: scatterMarkerLineAttrs.width
        },
            colorAttributes('marker.line')
        ),
        gradient: scatterMarkerAttrs.gradient
    },
        colorAttributes('marker')
    ),

    fill: {
        valType: 'enumerated',
        values: ['none', 'toself'],
        dflt: 'none',
        
        
    },
    fillcolor: scatterAttrs.fillcolor,

    selected: scatterAttrs.selected,
    unselected: scatterAttrs.unselected,

    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
        flags: ['lon', 'lat', 'location', 'text', 'name']
    }),
    hovertemplate: hovertemplateAttrs(),
}, 'calc', 'nested');

},{"../../components/colorscale/attributes":578,"../../components/drawing/attributes":591,"../../components/fx/hovertemplate_attributes":609,"../../lib/extend":684,"../../plot_api/edit_types":725,"../../plots/attributes":739,"../scatter/attributes":1047}],1088:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

var calcMarkerColorscale = _dereq_('../scatter/colorscale_calc');
var arraysToCalcdata = _dereq_('../scatter/arrays_to_calcdata');
var calcSelection = _dereq_('../scatter/calc_selection');

var _ = _dereq_('../../lib')._;

module.exports = function calc(gd, trace) {
    var hasLocationData = Array.isArray(trace.locations);
    var len = hasLocationData ? trace.locations.length : trace._length;
    var calcTrace = new Array(len);

    for(var i = 0; i < len; i++) {
        var calcPt = calcTrace[i] = {};

        if(hasLocationData) {
            var loc = trace.locations[i];
            calcPt.loc = typeof loc === 'string' ? loc : null;
        } else {
            var lon = trace.lon[i];
            var lat = trace.lat[i];

            if(isNumeric(lon) && isNumeric(lat)) calcPt.lonlat = [+lon, +lat];
            else calcPt.lonlat = [BADNUM, BADNUM];
        }
    }

    arraysToCalcdata(calcTrace, trace);
    calcMarkerColorscale(gd, trace);
    calcSelection(calcTrace, trace);

    if(len) {
        calcTrace[0].t = {
            labels: {
                lat: _(gd, 'lat:') + ' ',
                lon: _(gd, 'lon:') + ' '
            }
        };
    }

    return calcTrace;
};

},{"../../constants/numerical":671,"../../lib":694,"../scatter/arrays_to_calcdata":1046,"../scatter/calc_selection":1049,"../scatter/colorscale_calc":1050,"fast-isnumeric":215}],1089:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

var subTypes = _dereq_('../scatter/subtypes');
var handleMarkerDefaults = _dereq_('../scatter/marker_defaults');
var handleLineDefaults = _dereq_('../scatter/line_defaults');
var handleTextDefaults = _dereq_('../scatter/text_defaults');
var handleFillColorDefaults = _dereq_('../scatter/fillcolor_defaults');

var attributes = _dereq_('./attributes');


module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var len = handleLonLatLocDefaults(traceIn, traceOut, coerce);
    if(!len) {
        traceOut.visible = false;
        return;
    }

    coerce('text');
    coerce('hovertext');
    coerce('hovertemplate');
    coerce('mode');

    if(subTypes.hasLines(traceOut)) {
        handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
        coerce('connectgaps');
    }

    if(subTypes.hasMarkers(traceOut)) {
        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true});
    }

    if(subTypes.hasText(traceOut)) {
        handleTextDefaults(traceIn, traceOut, layout, coerce);
    }

    coerce('fill');
    if(traceOut.fill !== 'none') {
        handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
    }

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};

function handleLonLatLocDefaults(traceIn, traceOut, coerce) {
    var len = 0;
    var locations = coerce('locations');

    var lon, lat;

    if(locations) {
        coerce('locationmode');
        len = locations.length;
        return len;
    }

    lon = coerce('lon') || [];
    lat = coerce('lat') || [];
    len = Math.min(lon.length, lat.length);
    traceOut._length = len;

    return len;
}

},{"../../lib":694,"../scatter/fillcolor_defaults":1056,"../scatter/line_defaults":1060,"../scatter/marker_defaults":1066,"../scatter/subtypes":1071,"../scatter/text_defaults":1072,"./attributes":1087}],1090:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


module.exports = function eventData(out, pt) {
    out.lon = pt.lon;
    out.lat = pt.lat;
    out.location = pt.loc ? pt.loc : null;

    return out;
};

},{}],1091:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Fx = _dereq_('../../components/fx');
var Axes = _dereq_('../../plots/cartesian/axes');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

var getTraceColor = _dereq_('../scatter/get_trace_color');
var fillHoverText = _dereq_('../scatter/fill_hover_text');
var attributes = _dereq_('./attributes');

module.exports = function hoverPoints(pointData, xval, yval) {
    var cd = pointData.cd;
    var trace = cd[0].trace;
    var xa = pointData.xa;
    var ya = pointData.ya;
    var geo = pointData.subplot;

    var isLonLatOverEdges = geo.projection.isLonLatOverEdges;
    var project = geo.project;

    function distFn(d) {
        var lonlat = d.lonlat;

        if(lonlat[0] === BADNUM) return Infinity;
        if(isLonLatOverEdges(lonlat)) return Infinity;

        var pt = project(lonlat);
        var px = project([xval, yval]);
        var dx = Math.abs(pt[0] - px[0]);
        var dy = Math.abs(pt[1] - px[1]);
        var rad = Math.max(3, d.mrc || 0);

        // N.B. d.mrc is the calculated marker radius
        // which is only set for trace with 'markers' mode.

        return Math.max(Math.sqrt(dx * dx + dy * dy) - rad, 1 - 3 / rad);
    }

    Fx.getClosest(cd, distFn, pointData);

    // skip the rest (for this trace) if we didn't find a close point
    if(pointData.index === false) return;

    var di = cd[pointData.index];
    var lonlat = di.lonlat;
    var pos = [xa.c2p(lonlat), ya.c2p(lonlat)];
    var rad = di.mrc || 1;

    pointData.x0 = pos[0] - rad;
    pointData.x1 = pos[0] + rad;
    pointData.y0 = pos[1] - rad;
    pointData.y1 = pos[1] + rad;

    pointData.loc = di.loc;
    pointData.lon = lonlat[0];
    pointData.lat = lonlat[1];

    pointData.color = getTraceColor(trace, di);
    pointData.extraText = getExtraText(trace, di, geo.mockAxis, cd[0].t.labels);
    pointData.hovertemplate = trace.hovertemplate;

    return [pointData];
};

function getExtraText(trace, pt, axis, labels) {
    if(trace.hovertemplate) {
        return;
    }

    var hoverinfo = pt.hi || trace.hoverinfo;

    var parts = hoverinfo === 'all' ?
        attributes.hoverinfo.flags :
        hoverinfo.split('+');

    var hasLocation = parts.indexOf('location') !== -1 && Array.isArray(trace.locations);
    var hasLon = (parts.indexOf('lon') !== -1);
    var hasLat = (parts.indexOf('lat') !== -1);
    var hasText = (parts.indexOf('text') !== -1);
    var text = [];

    function format(val) {
        return Axes.tickText(axis, axis.c2l(val), 'hover').text + '\u00B0';
    }

    if(hasLocation) {
        text.push(pt.loc);
    } else if(hasLon && hasLat) {
        text.push('(' + format(pt.lonlat[0]) + ', ' + format(pt.lonlat[1]) + ')');
    } else if(hasLon) {
        text.push(labels.lon + format(pt.lonlat[0]));
    } else if(hasLat) {
        text.push(labels.lat + format(pt.lonlat[1]));
    }

    if(hasText) {
        fillHoverText(pt, trace, text);
    }

    return text.join('<br>');
}

},{"../../components/fx":610,"../../constants/numerical":671,"../../plots/cartesian/axes":742,"../scatter/fill_hover_text":1055,"../scatter/get_trace_color":1057,"./attributes":1087}],1092:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var ScatterGeo = {};

ScatterGeo.attributes = _dereq_('./attributes');
ScatterGeo.supplyDefaults = _dereq_('./defaults');
ScatterGeo.colorbar = _dereq_('../scatter/marker_colorbar');
ScatterGeo.calc = _dereq_('./calc');
ScatterGeo.plot = _dereq_('./plot');
ScatterGeo.style = _dereq_('./style');
ScatterGeo.styleOnSelect = _dereq_('../scatter/style').styleOnSelect;
ScatterGeo.hoverPoints = _dereq_('./hover');
ScatterGeo.eventData = _dereq_('./event_data');
ScatterGeo.selectPoints = _dereq_('./select');

ScatterGeo.moduleType = 'trace';
ScatterGeo.name = 'scattergeo';
ScatterGeo.basePlotModule = _dereq_('../../plots/geo');
ScatterGeo.categories = ['geo', 'symbols', 'showLegend', 'scatter-like'];
ScatterGeo.meta = {
    
    
};

module.exports = ScatterGeo;

},{"../../plots/geo":773,"../scatter/marker_colorbar":1065,"../scatter/style":1070,"./attributes":1087,"./calc":1088,"./defaults":1089,"./event_data":1090,"./hover":1091,"./plot":1093,"./select":1094,"./style":1095}],1093:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = _dereq_('d3');

var Lib = _dereq_('../../lib');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;
var getTopojsonFeatures = _dereq_('../../lib/topojson_utils').getTopojsonFeatures;
var locationToFeature = _dereq_('../../lib/geo_location_utils').locationToFeature;
var geoJsonUtils = _dereq_('../../lib/geojson_utils');
var subTypes = _dereq_('../scatter/subtypes');
var style = _dereq_('./style');

module.exports = function plot(gd, geo, calcData) {
    for(var i = 0; i < calcData.length; i++) {
        calcGeoJSON(calcData[i], geo.topojson);
    }

    function removeBADNUM(d, node) {
        if(d.lonlat[0] === BADNUM) {
            d3.select(node).remove();
        }
    }

    var scatterLayer = geo.layers.frontplot.select('.scatterlayer');
    var gTraces = Lib.makeTraceGroups(scatterLayer, calcData, 'trace scattergeo');

    // TODO find a way to order the inner nodes on update
    gTraces.selectAll('*').remove();

    gTraces.each(function(calcTrace) {
        var s = calcTrace[0].node3 = d3.select(this);
        var trace = calcTrace[0].trace;

        if(subTypes.hasLines(trace) || trace.fill !== 'none') {
            var lineCoords = geoJsonUtils.calcTraceToLineCoords(calcTrace);

            var lineData = (trace.fill !== 'none') ?
                geoJsonUtils.makePolygon(lineCoords) :
                geoJsonUtils.makeLine(lineCoords);

            s.selectAll('path.js-line')
                .data([{geojson: lineData, trace: trace}])
              .enter().append('path')
                .classed('js-line', true)
                .style('stroke-miterlimit', 2);
        }

        if(subTypes.hasMarkers(trace)) {
            s.selectAll('path.point')
                .data(Lib.identity)
             .enter().append('path')
                .classed('point', true)
                .each(function(calcPt) { removeBADNUM(calcPt, this); });
        }

        if(subTypes.hasText(trace)) {
            s.selectAll('g')
                .data(Lib.identity)
              .enter().append('g')
                .append('text')
                .each(function(calcPt) { removeBADNUM(calcPt, this); });
        }

        // call style here within topojson request callback
        style(gd, calcTrace);
    });
};

function calcGeoJSON(calcTrace, topojson) {
    var trace = calcTrace[0].trace;

    if(!Array.isArray(trace.locations)) return;

    var features = getTopojsonFeatures(trace, topojson);
    var locationmode = trace.locationmode;

    for(var i = 0; i < calcTrace.length; i++) {
        var calcPt = calcTrace[i];
        var feature = locationToFeature(locationmode, calcPt.loc, features);

        calcPt.lonlat = feature ? feature.properties.ct : [BADNUM, BADNUM];
    }
}

},{"../../constants/numerical":671,"../../lib":694,"../../lib/geo_location_utils":687,"../../lib/geojson_utils":688,"../../lib/topojson_utils":721,"../scatter/subtypes":1071,"./style":1095,"d3":149}],1094:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var subtypes = _dereq_('../scatter/subtypes');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

module.exports = function selectPoints(searchInfo, selectionTester) {
    var cd = searchInfo.cd;
    var xa = searchInfo.xaxis;
    var ya = searchInfo.yaxis;
    var selection = [];
    var trace = cd[0].trace;

    var di, lonlat, x, y, i;

    var hasOnlyLines = (!subtypes.hasMarkers(trace) && !subtypes.hasText(trace));
    if(hasOnlyLines) return [];

    if(selectionTester === false) {
        for(i = 0; i < cd.length; i++) {
            cd[i].selected = 0;
        }
    } else {
        for(i = 0; i < cd.length; i++) {
            di = cd[i];
            lonlat = di.lonlat;

            // some projection types can't handle BADNUMs
            if(lonlat[0] === BADNUM) continue;

            x = xa.c2p(lonlat);
            y = ya.c2p(lonlat);

            if(selectionTester.contains([x, y], null, i, searchInfo)) {
                selection.push({
                    pointNumber: i,
                    lon: lonlat[0],
                    lat: lonlat[1]
                });
                di.selected = 1;
            } else {
                di.selected = 0;
            }
        }
    }

    return selection;
};

},{"../../constants/numerical":671,"../scatter/subtypes":1071}],1095:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var Drawing = _dereq_('../../components/drawing');
var Color = _dereq_('../../components/color');

var scatterStyle = _dereq_('../scatter/style');
var stylePoints = scatterStyle.stylePoints;
var styleText = scatterStyle.styleText;

module.exports = function style(gd, calcTrace) {
    if(calcTrace) styleTrace(gd, calcTrace);
};

function styleTrace(gd, calcTrace) {
    var trace = calcTrace[0].trace;
    var s = calcTrace[0].node3;

    s.style('opacity', calcTrace[0].trace.opacity);

    stylePoints(s, trace, gd);
    styleText(s, trace, gd);

    // this part is incompatible with Drawing.lineGroupStyle
    s.selectAll('path.js-line')
        .style('fill', 'none')
        .each(function(d) {
            var path = d3.select(this);
            var trace = d.trace;
            var line = trace.line || {};

            path.call(Color.stroke, line.color)
                .call(Drawing.dashLine, line.dash || '', line.width || 0);

            if(trace.fill !== 'none') {
                path.call(Color.fill, trace.fillcolor);
            }
        });
}

},{"../../components/color":571,"../../components/drawing":592,"../scatter/style":1070,"d3":149}],1096:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var plotAttrs = _dereq_('../../plots/attributes');
var scatterAttrs = _dereq_('../scatter/attributes');
var colorAttrs = _dereq_('../../components/colorscale/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
var DASHES = _dereq_('./constants').DASHES;

var scatterLineAttrs = scatterAttrs.line;
var scatterMarkerAttrs = scatterAttrs.marker;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;

var attrs = module.exports = overrideAll({
    x: scatterAttrs.x,
    x0: scatterAttrs.x0,
    dx: scatterAttrs.dx,
    y: scatterAttrs.y,
    y0: scatterAttrs.y0,
    dy: scatterAttrs.dy,

    text: scatterAttrs.text,
    hovertext: scatterAttrs.hovertext,

    textposition: scatterAttrs.textposition,
    textfont: scatterAttrs.textfont,

    mode: {
        valType: 'flaglist',
        flags: ['lines', 'markers', 'text'],
        extras: ['none'],
        
        
    },
    line: {
        color: scatterLineAttrs.color,
        width: scatterLineAttrs.width,
        shape: {
            valType: 'enumerated',
            values: ['linear', 'hv', 'vh', 'hvh', 'vhv'],
            dflt: 'linear',
            
            editType: 'plot',
            
        },
        dash: {
            valType: 'enumerated',
            values: Object.keys(DASHES),
            dflt: 'solid',
            
            
        }
    },
    marker: extendFlat({}, colorAttrs('marker'), {
        symbol: scatterMarkerAttrs.symbol,
        size: scatterMarkerAttrs.size,
        sizeref: scatterMarkerAttrs.sizeref,
        sizemin: scatterMarkerAttrs.sizemin,
        sizemode: scatterMarkerAttrs.sizemode,
        opacity: scatterMarkerAttrs.opacity,
        colorbar: scatterMarkerAttrs.colorbar,
        line: extendFlat({}, colorAttrs('marker.line'), {
            width: scatterMarkerLineAttrs.width
        })
    }),
    connectgaps: scatterAttrs.connectgaps,
    fill: extendFlat({}, scatterAttrs.fill, {dflt: 'none'}),
    fillcolor: scatterAttrs.fillcolor,

    // no hoveron

    selected: {
        marker: scatterAttrs.selected.marker,
        textfont: scatterAttrs.selected.textfont
    },
    unselected: {
        marker: scatterAttrs.unselected.marker,
        textfont: scatterAttrs.unselected.textfont
    },

    opacity: plotAttrs.opacity

}, 'calc', 'nested');

attrs.x.editType = attrs.y.editType = attrs.x0.editType = attrs.y0.editType = 'calc+clearAxisTypes';
attrs.hovertemplate = scatterAttrs.hovertemplate;

},{"../../components/colorscale/attributes":578,"../../lib/extend":684,"../../plot_api/edit_types":725,"../../plots/attributes":739,"../scatter/attributes":1047,"./constants":1097}],1097:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var SYMBOL_SIZE = 20;

module.exports = {
    TOO_MANY_POINTS: 1e5,

    SYMBOL_SDF_SIZE: 200,
    SYMBOL_SIZE: SYMBOL_SIZE,
    SYMBOL_STROKE: SYMBOL_SIZE / 20,

    DOT_RE: /-dot/,
    OPEN_RE: /-open/,

    DASHES: {
        solid: [1],
        dot: [1, 1],
        dash: [4, 1],
        longdash: [8, 1],
        dashdot: [4, 1, 1, 1],
        longdashdot: [8, 1, 1, 1]
    }
};

},{}],1098:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var svgSdf = _dereq_('svg-path-sdf');
var rgba = _dereq_('color-normalize');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var Drawing = _dereq_('../../components/drawing');
var AxisIDs = _dereq_('../../plots/cartesian/axis_ids');

var formatColor = _dereq_('../../lib/gl_format_color').formatColor;
var subTypes = _dereq_('../scatter/subtypes');
var makeBubbleSizeFn = _dereq_('../scatter/make_bubble_size_func');

var constants = _dereq_('./constants');
var DESELECTDIM = _dereq_('../../constants/interactions').DESELECTDIM;

var TEXTOFFSETSIGN = {
    start: 1, left: 1, end: -1, right: -1, middle: 0, center: 0, bottom: 1, top: -1
};

function convertStyle(gd, trace) {
    var i;

    var opts = {
        marker: undefined,
        markerSel: undefined,
        markerUnsel: undefined,
        line: undefined,
        fill: undefined,
        errorX: undefined,
        errorY: undefined,
        text: undefined,
        textSel: undefined,
        textUnsel: undefined
    };

    if(trace.visible !== true) return opts;

    if(subTypes.hasText(trace)) {
        opts.text = convertTextStyle(trace);
        opts.textSel = convertTextSelection(trace, trace.selected);
        opts.textUnsel = convertTextSelection(trace, trace.unselected);
    }

    if(subTypes.hasMarkers(trace)) {
        opts.marker = convertMarkerStyle(trace);
        opts.markerSel = convertMarkerSelection(trace, trace.selected);
        opts.markerUnsel = convertMarkerSelection(trace, trace.unselected);

        if(!trace.unselected && Array.isArray(trace.marker.opacity)) {
            var mo = trace.marker.opacity;
            opts.markerUnsel.opacity = new Array(mo.length);
            for(i = 0; i < mo.length; i++) {
                opts.markerUnsel.opacity[i] = DESELECTDIM * mo[i];
            }
        }
    }

    if(subTypes.hasLines(trace)) {
        opts.line = {
            overlay: true,
            thickness: trace.line.width,
            color: trace.line.color,
            opacity: trace.opacity
        };

        var dashes = (constants.DASHES[trace.line.dash] || [1]).slice();
        for(i = 0; i < dashes.length; ++i) {
            dashes[i] *= trace.line.width;
        }
        opts.line.dashes = dashes;
    }

    if(trace.error_x && trace.error_x.visible) {
        opts.errorX = convertErrorBarStyle(trace, trace.error_x);
    }

    if(trace.error_y && trace.error_y.visible) {
        opts.errorY = convertErrorBarStyle(trace, trace.error_y);
    }

    if(!!trace.fill && trace.fill !== 'none') {
        opts.fill = {
            closed: true,
            fill: trace.fillcolor,
            thickness: 0
        };
    }

    return opts;
}

function convertTextStyle(trace) {
    var count = trace._length;
    var textfontIn = trace.textfont;
    var textpositionIn = trace.textposition;
    var textPos = Array.isArray(textpositionIn) ? textpositionIn : [textpositionIn];
    var tfc = textfontIn.color;
    var tfs = textfontIn.size;
    var tff = textfontIn.family;
    var optsOut = {};
    var i;

    optsOut.text = trace.text;
    optsOut.opacity = trace.opacity;
    optsOut.font = {};
    optsOut.align = [];
    optsOut.baseline = [];

    for(i = 0; i < textPos.length; i++) {
        var tp = textPos[i].split(/\s+/);

        switch(tp[1]) {
            case 'left':
                optsOut.align.push('right');
                break;
            case 'right':
                optsOut.align.push('left');
                break;
            default:
                optsOut.align.push(tp[1]);
        }
        switch(tp[0]) {
            case 'top':
                optsOut.baseline.push('bottom');
                break;
            case 'bottom':
                optsOut.baseline.push('top');
                break;
            default:
                optsOut.baseline.push(tp[0]);
        }
    }

    if(Array.isArray(tfc)) {
        optsOut.color = new Array(count);
        for(i = 0; i < count; i++) {
            optsOut.color[i] = tfc[i];
        }
    } else {
        optsOut.color = tfc;
    }

    if(Array.isArray(tfs) || Array.isArray(tff)) {
        // if any textfont param is array - make render a batch
        optsOut.font = new Array(count);
        for(i = 0; i < count; i++) {
            var fonti = optsOut.font[i] = {};

            fonti.size = Array.isArray(tfs) ?
                (isNumeric(tfs[i]) ? tfs[i] : 0) :
                tfs;

            fonti.family = Array.isArray(tff) ? tff[i] : tff;
        }
    } else {
        // if both are single values, make render fast single-value
        optsOut.font = {size: tfs, family: tff};
    }

    return optsOut;
}


function convertMarkerStyle(trace) {
    var count = trace._length;
    var optsIn = trace.marker;
    var optsOut = {};
    var i;

    var multiSymbol = Array.isArray(optsIn.symbol);
    var multiColor = Lib.isArrayOrTypedArray(optsIn.color);
    var multiLineColor = Lib.isArrayOrTypedArray(optsIn.line.color);
    var multiOpacity = Lib.isArrayOrTypedArray(optsIn.opacity);
    var multiSize = Lib.isArrayOrTypedArray(optsIn.size);
    var multiLineWidth = Lib.isArrayOrTypedArray(optsIn.line.width);

    var isOpen;
    if(!multiSymbol) isOpen = constants.OPEN_RE.test(optsIn.symbol);

    // prepare colors
    if(multiSymbol || multiColor || multiLineColor || multiOpacity) {
        optsOut.colors = new Array(count);
        optsOut.borderColors = new Array(count);

        var colors = formatColor(optsIn, optsIn.opacity, count);
        var borderColors = formatColor(optsIn.line, optsIn.opacity, count);

        if(!Array.isArray(borderColors[0])) {
            var borderColor = borderColors;
            borderColors = Array(count);
            for(i = 0; i < count; i++) {
                borderColors[i] = borderColor;
            }
        }
        if(!Array.isArray(colors[0])) {
            var color = colors;
            colors = Array(count);
            for(i = 0; i < count; i++) {
                colors[i] = color;
            }
        }

        optsOut.colors = colors;
        optsOut.borderColors = borderColors;

        for(i = 0; i < count; i++) {
            if(multiSymbol) {
                var symbol = optsIn.symbol[i];
                isOpen = constants.OPEN_RE.test(symbol);
            }
            if(isOpen) {
                borderColors[i] = colors[i].slice();
                colors[i] = colors[i].slice();
                colors[i][3] = 0;
            }
        }

        optsOut.opacity = trace.opacity;
    } else {
        if(isOpen) {
            optsOut.color = rgba(optsIn.color, 'uint8');
            optsOut.color[3] = 0;
            optsOut.borderColor = rgba(optsIn.color, 'uint8');
        } else {
            optsOut.color = rgba(optsIn.color, 'uint8');
            optsOut.borderColor = rgba(optsIn.line.color, 'uint8');
        }

        optsOut.opacity = trace.opacity * optsIn.opacity;
    }

    // prepare symbols
    if(multiSymbol) {
        optsOut.markers = new Array(count);
        for(i = 0; i < count; i++) {
            optsOut.markers[i] = getSymbolSdf(optsIn.symbol[i]);
        }
    } else {
        optsOut.marker = getSymbolSdf(optsIn.symbol);
    }

    // prepare sizes
    var markerSizeFunc = makeBubbleSizeFn(trace);
    var s;

    if(multiSize || multiLineWidth) {
        var sizes = optsOut.sizes = new Array(count);
        var borderSizes = optsOut.borderSizes = new Array(count);
        var sizeTotal = 0;
        var sizeAvg;

        if(multiSize) {
            for(i = 0; i < count; i++) {
                sizes[i] = markerSizeFunc(optsIn.size[i]);
                sizeTotal += sizes[i];
            }
            sizeAvg = sizeTotal / count;
        } else {
            s = markerSizeFunc(optsIn.size);
            for(i = 0; i < count; i++) {
                sizes[i] = s;
            }
        }

        // See  https://github.com/plotly/plotly.js/pull/1781#discussion_r121820798
        if(multiLineWidth) {
            for(i = 0; i < count; i++) {
                borderSizes[i] = optsIn.line.width[i] / 2;
            }
        } else {
            s = optsIn.line.width / 2;
            for(i = 0; i < count; i++) {
                borderSizes[i] = s;
            }
        }

        optsOut.sizeAvg = sizeAvg;
    } else {
        optsOut.size = markerSizeFunc(optsIn && optsIn.size || 10);
        optsOut.borderSizes = markerSizeFunc(optsIn.line.width);
    }

    return optsOut;
}

function convertMarkerSelection(trace, target) {
    var optsIn = trace.marker;
    var optsOut = {};

    if(!target) return optsOut;

    if(target.marker && target.marker.symbol) {
        optsOut = convertMarkerStyle(Lib.extendFlat({}, optsIn, target.marker));
    } else if(target.marker) {
        if(target.marker.size) optsOut.size = target.marker.size / 2;
        if(target.marker.color) optsOut.colors = target.marker.color;
        if(target.marker.opacity !== undefined) optsOut.opacity = target.marker.opacity;
    }

    return optsOut;
}

function convertTextSelection(trace, target) {
    var optsOut = {};

    if(!target) return optsOut;

    if(target.textfont) {
        var optsIn = {
            opacity: 1,
            text: trace.text,
            textposition: trace.textposition,
            textfont: Lib.extendFlat({}, trace.textfont)
        };
        if(target.textfont) {
            Lib.extendFlat(optsIn.textfont, target.textfont);
        }
        optsOut = convertTextStyle(optsIn);
    }

    return optsOut;
}

function convertErrorBarStyle(trace, target) {
    var optsOut = {
        capSize: target.width * 2,
        lineWidth: target.thickness,
        color: target.color
    };

    if(target.copy_ystyle) {
        optsOut = trace.error_y;
    }

    return optsOut;
}

var SYMBOL_SDF_SIZE = constants.SYMBOL_SDF_SIZE;
var SYMBOL_SIZE = constants.SYMBOL_SIZE;
var SYMBOL_STROKE = constants.SYMBOL_STROKE;
var SYMBOL_SDF = {};
var SYMBOL_SVG_CIRCLE = Drawing.symbolFuncs[0](SYMBOL_SIZE * 0.05);

function getSymbolSdf(symbol) {
    if(symbol === 'circle') return null;

    var symbolPath, symbolSdf;
    var symbolNumber = Drawing.symbolNumber(symbol);
    var symbolFunc = Drawing.symbolFuncs[symbolNumber % 100];
    var symbolNoDot = !!Drawing.symbolNoDot[symbolNumber % 100];
    var symbolNoFill = !!Drawing.symbolNoFill[symbolNumber % 100];

    var isDot = constants.DOT_RE.test(symbol);

    // get symbol sdf from cache or generate it
    if(SYMBOL_SDF[symbol]) return SYMBOL_SDF[symbol];

    if(isDot && !symbolNoDot) {
        symbolPath = symbolFunc(SYMBOL_SIZE * 1.1) + SYMBOL_SVG_CIRCLE;
    }
    else {
        symbolPath = symbolFunc(SYMBOL_SIZE);
    }

    symbolSdf = svgSdf(symbolPath, {
        w: SYMBOL_SDF_SIZE,
        h: SYMBOL_SDF_SIZE,
        viewBox: [-SYMBOL_SIZE, -SYMBOL_SIZE, SYMBOL_SIZE, SYMBOL_SIZE],
        stroke: symbolNoFill ? SYMBOL_STROKE : -SYMBOL_STROKE
    });
    SYMBOL_SDF[symbol] = symbolSdf;

    return symbolSdf || null;
}

function convertLinePositions(gd, trace, positions) {
    var len = positions.length;
    var count = len / 2;
    var linePositions;
    var i;

    if(subTypes.hasLines(trace) && count) {
        if(trace.line.shape === 'hv') {
            linePositions = [];
            for(i = 0; i < count - 1; i++) {
                if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) {
                    linePositions.push(NaN, NaN, NaN, NaN);
                } else {
                    linePositions.push(positions[i * 2], positions[i * 2 + 1]);
                    if(!isNaN(positions[i * 2 + 2]) && !isNaN(positions[i * 2 + 3])) {
                        linePositions.push(positions[i * 2 + 2], positions[i * 2 + 1]);
                    } else {
                        linePositions.push(NaN, NaN);
                    }
                }
            }
            linePositions.push(positions[len - 2], positions[len - 1]);
        } else if(trace.line.shape === 'hvh') {
            linePositions = [];
            for(i = 0; i < count - 1; i++) {
                if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1]) || isNaN(positions[i * 2 + 2]) || isNaN(positions[i * 2 + 3])) {
                    if(!isNaN(positions[i * 2]) && !isNaN(positions[i * 2 + 1])) {
                        linePositions.push(positions[i * 2], positions[i * 2 + 1]);
                    } else {
                        linePositions.push(NaN, NaN);
                    }
                    linePositions.push(NaN, NaN);
                }
                else {
                    var midPtX = (positions[i * 2] + positions[i * 2 + 2]) / 2;
                    linePositions.push(
                        positions[i * 2],
                        positions[i * 2 + 1],
                        midPtX,
                        positions[i * 2 + 1],
                        midPtX,
                        positions[i * 2 + 3]
                    );
                }
            }
            linePositions.push(positions[len - 2], positions[len - 1]);
        } else if(trace.line.shape === 'vhv') {
            linePositions = [];
            for(i = 0; i < count - 1; i++) {
                if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1]) || isNaN(positions[i * 2 + 2]) || isNaN(positions[i * 2 + 3])) {
                    if(!isNaN(positions[i * 2]) && !isNaN(positions[i * 2 + 1])) {
                        linePositions.push(positions[i * 2], positions[i * 2 + 1]);
                    } else {
                        linePositions.push(NaN, NaN);
                    }
                    linePositions.push(NaN, NaN);
                }
                else {
                    var midPtY = (positions[i * 2 + 1] + positions[i * 2 + 3]) / 2;
                    linePositions.push(
                        positions[i * 2],
                        positions[i * 2 + 1],
                        positions[i * 2],
                        midPtY,
                        positions[i * 2 + 2],
                        midPtY
                    );
                }
            }
            linePositions.push(positions[len - 2], positions[len - 1]);
        } else if(trace.line.shape === 'vh') {
            linePositions = [];
            for(i = 0; i < count - 1; i++) {
                if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) {
                    linePositions.push(NaN, NaN, NaN, NaN);
                }
                else {
                    linePositions.push(positions[i * 2], positions[i * 2 + 1]);
                    if(!isNaN(positions[i * 2 + 2]) && !isNaN(positions[i * 2 + 3])) {
                        linePositions.push(positions[i * 2], positions[i * 2 + 3]);
                    } else {
                        linePositions.push(NaN, NaN);
                    }
                }
            }
            linePositions.push(positions[len - 2], positions[len - 1]);
        } else {
            linePositions = positions;
        }
    }

    // If we have data with gaps, we ought to use rect joins
    // FIXME: get rid of this
    var hasNaN = false;
    for(i = 0; i < linePositions.length; i++) {
        if(isNaN(linePositions[i])) {
            hasNaN = true;
            break;
        }
    }

    var join = (hasNaN || linePositions.length > constants.TOO_MANY_POINTS) ? 'rect' :
        subTypes.hasMarkers(trace) ? 'rect' : 'round';

    // fill gaps
    if(hasNaN && trace.connectgaps) {
        var lastX = linePositions[0];
        var lastY = linePositions[1];

        for(i = 0; i < linePositions.length; i += 2) {
            if(isNaN(linePositions[i]) || isNaN(linePositions[i + 1])) {
                linePositions[i] = lastX;
                linePositions[i + 1] = lastY;
            }
            else {
                lastX = linePositions[i];
                lastY = linePositions[i + 1];
            }
        }
    }

    return {
        join: join,
        positions: linePositions
    };
}

function convertErrorBarPositions(gd, trace, positions, x, y) {
    var makeComputeError = Registry.getComponentMethod('errorbars', 'makeComputeError');
    var xa = AxisIDs.getFromId(gd, trace.xaxis);
    var ya = AxisIDs.getFromId(gd, trace.yaxis);
    var count = positions.length / 2;
    var out = {};

    function convertOneAxis(coords, ax) {
        var axLetter = ax._id.charAt(0);
        var opts = trace['error_' + axLetter];

        if(opts && opts.visible && (ax.type === 'linear' || ax.type === 'log')) {
            var computeError = makeComputeError(opts);
            var pOffset = {x: 0, y: 1}[axLetter];
            var eOffset = {x: [0, 1, 2, 3], y: [2, 3, 0, 1]}[axLetter];
            var errors = new Float64Array(4 * count);
            var minShoe = Infinity;
            var maxHat = -Infinity;

            for(var i = 0, j = 0; i < count; i++, j += 4) {
                var dc = coords[i];

                if(isNumeric(dc)) {
                    var dl = positions[i * 2 + pOffset];
                    var vals = computeError(dc, i);
                    var lv = vals[0];
                    var hv = vals[1];

                    if(isNumeric(lv) && isNumeric(hv)) {
                        var shoe = dc - lv;
                        var hat = dc + hv;

                        errors[j + eOffset[0]] = dl - ax.c2l(shoe);
                        errors[j + eOffset[1]] = ax.c2l(hat) - dl;
                        errors[j + eOffset[2]] = 0;
                        errors[j + eOffset[3]] = 0;

                        minShoe = Math.min(minShoe, dc - lv);
                        maxHat = Math.max(maxHat, dc + hv);
                    }
                }
            }

            out[axLetter] = {
                positions: positions,
                errors: errors,
                _bnds: [minShoe, maxHat]
            };
        }
    }

    convertOneAxis(x, xa);
    convertOneAxis(y, ya);
    return out;
}

function convertTextPosition(gd, trace, textOpts, markerOpts) {
    var count = trace._length;
    var out = {};
    var i;

    // corresponds to textPointPosition from component.drawing
    if(subTypes.hasMarkers(trace)) {
        var fontOpts = textOpts.font;
        var align = textOpts.align;
        var baseline = textOpts.baseline;
        out.offset = new Array(count);

        for(i = 0; i < count; i++) {
            var ms = markerOpts.sizes ? markerOpts.sizes[i] : markerOpts.size;
            var fs = Array.isArray(fontOpts) ? fontOpts[i].size : fontOpts.size;

            var a = Array.isArray(align) ?
                (align.length > 1 ? align[i] : align[0]) :
                align;
            var b = Array.isArray(baseline) ?
                (baseline.length > 1 ? baseline[i] : baseline[0]) :
                baseline;

            var hSign = TEXTOFFSETSIGN[a];
            var vSign = TEXTOFFSETSIGN[b];
            var xPad = ms ? ms / 0.8 + 1 : 0;
            var yPad = -vSign * xPad - vSign * 0.5;
            out.offset[i] = [hSign * xPad / fs, yPad / fs];
        }
    }

    return out;
}

module.exports = {
    style: convertStyle,

    markerStyle: convertMarkerStyle,
    markerSelection: convertMarkerSelection,

    linePositions: convertLinePositions,
    errorBarPositions: convertErrorBarPositions,
    textPosition: convertTextPosition
};

},{"../../components/drawing":592,"../../constants/interactions":670,"../../lib":694,"../../lib/gl_format_color":691,"../../plots/cartesian/axis_ids":745,"../../registry":825,"../scatter/make_bubble_size_func":1064,"../scatter/subtypes":1071,"./constants":1097,"color-normalize":109,"fast-isnumeric":215,"svg-path-sdf":513}],1099:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Registry = _dereq_('../../registry');

var attributes = _dereq_('./attributes');
var constants = _dereq_('../scatter/constants');
var subTypes = _dereq_('../scatter/subtypes');
var handleXYDefaults = _dereq_('../scatter/xy_defaults');
var handleMarkerDefaults = _dereq_('../scatter/marker_defaults');
var handleLineDefaults = _dereq_('../scatter/line_defaults');
var handleFillColorDefaults = _dereq_('../scatter/fillcolor_defaults');
var handleTextDefaults = _dereq_('../scatter/text_defaults');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var isOpen = traceIn.marker ? /-open/.test(traceIn.marker.symbol) : false;
    var isBubble = subTypes.isBubble(traceIn);

    var len = handleXYDefaults(traceIn, traceOut, layout, coerce);
    if(!len) {
        traceOut.visible = false;
        return;
    }
    var defaultMode = len < constants.PTS_LINESONLY ? 'lines+markers' : 'lines';

    coerce('text');
    coerce('hovertext');
    coerce('hovertemplate');
    coerce('mode', defaultMode);

    if(subTypes.hasLines(traceOut)) {
        coerce('connectgaps');
        handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
        coerce('line.shape');
    }

    if(subTypes.hasMarkers(traceOut)) {
        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce);
        coerce('marker.line.width', isOpen || isBubble ? 1 : 0);
    }

    if(subTypes.hasText(traceOut)) {
        handleTextDefaults(traceIn, traceOut, layout, coerce);
    }

    var lineColor = (traceOut.line || {}).color;
    var markerColor = (traceOut.marker || {}).color;

    coerce('fill');
    if(traceOut.fill !== 'none') {
        handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
    }

    var errorBarsSupplyDefaults = Registry.getComponentMethod('errorbars', 'supplyDefaults');
    errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, {axis: 'y'});
    errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, {axis: 'x', inherit: 'y'});

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};

},{"../../lib":694,"../../registry":825,"../scatter/constants":1051,"../scatter/fillcolor_defaults":1056,"../scatter/line_defaults":1060,"../scatter/marker_defaults":1066,"../scatter/subtypes":1071,"../scatter/text_defaults":1072,"../scatter/xy_defaults":1073,"./attributes":1096}],1100:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var createScatter = _dereq_('regl-scatter2d');
var createLine = _dereq_('regl-line2d');
var createError = _dereq_('regl-error2d');
var cluster = _dereq_('point-cluster');
var arrayRange = _dereq_('array-range');
var Text = _dereq_('gl-text');

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');
var prepareRegl = _dereq_('../../lib/prepare_regl');
var AxisIDs = _dereq_('../../plots/cartesian/axis_ids');
var findExtremes = _dereq_('../../plots/cartesian/autorange').findExtremes;
var Color = _dereq_('../../components/color');

var subTypes = _dereq_('../scatter/subtypes');
var scatterCalc = _dereq_('../scatter/calc');
var calcMarkerSize = scatterCalc.calcMarkerSize;
var calcAxisExpansion = scatterCalc.calcAxisExpansion;
var setFirstScatter = scatterCalc.setFirstScatter;
var calcColorscale = _dereq_('../scatter/colorscale_calc');
var linkTraces = _dereq_('../scatter/link_traces');
var getTraceColor = _dereq_('../scatter/get_trace_color');
var fillHoverText = _dereq_('../scatter/fill_hover_text');
var convert = _dereq_('./convert');

var BADNUM = _dereq_('../../constants/numerical').BADNUM;
var TOO_MANY_POINTS = _dereq_('./constants').TOO_MANY_POINTS;
var DESELECTDIM = _dereq_('../../constants/interactions').DESELECTDIM;

function calc(gd, trace) {
    var fullLayout = gd._fullLayout;
    var xa = AxisIDs.getFromId(gd, trace.xaxis);
    var ya = AxisIDs.getFromId(gd, trace.yaxis);
    var subplot = fullLayout._plots[trace.xaxis + trace.yaxis];
    var len = trace._length;
    var len2 = len * 2;
    var stash = {};
    var i, xx, yy;

    var x = xa.makeCalcdata(trace, 'x');
    var y = ya.makeCalcdata(trace, 'y');

    // we need hi-precision for scatter2d,
    // regl-scatter2d uses NaNs for bad/missing values
    var positions = new Array(len2);
    for(i = 0; i < len; i++) {
        xx = x[i];
        yy = y[i];
        positions[i * 2] = xx === BADNUM ? NaN : xx;
        positions[i * 2 + 1] = yy === BADNUM ? NaN : yy;
    }

    if(xa.type === 'log') {
        for(i = 0; i < len2; i += 2) {
            positions[i] = xa.c2l(positions[i]);
        }
    }
    if(ya.type === 'log') {
        for(i = 1; i < len2; i += 2) {
            positions[i] = ya.c2l(positions[i]);
        }
    }

    // we don't build a tree for log axes since it takes long to convert log2px
    // and it is also
    if(xa.type !== 'log' && ya.type !== 'log') {
        // FIXME: delegate this to webworker
        stash.tree = cluster(positions);
    } else {
        var ids = stash.ids = new Array(len);
        for(i = 0; i < len; i++) {
            ids[i] = i;
        }
    }

    // create scene options and scene
    calcColorscale(gd, trace);
    var opts = sceneOptions(gd, subplot, trace, positions, x, y);
    var scene = sceneUpdate(gd, subplot);

    // Reuse SVG scatter axis expansion routine.
    // For graphs with very large number of points and array marker.size,
    // use average marker size instead to speed things up.
    setFirstScatter(fullLayout, trace);
    var ppad;
    if(len < TOO_MANY_POINTS) {
        ppad = calcMarkerSize(trace, len);
    } else if(opts.marker) {
        ppad = 2 * (opts.marker.sizeAvg || Math.max(opts.marker.size, 3));
    }
    calcAxisExpansion(gd, trace, xa, ya, x, y, ppad);
    if(opts.errorX) expandForErrorBars(trace, xa, opts.errorX);
    if(opts.errorY) expandForErrorBars(trace, ya, opts.errorY);

    // set flags to create scene renderers
    if(opts.fill && !scene.fill2d) scene.fill2d = true;
    if(opts.marker && !scene.scatter2d) scene.scatter2d = true;
    if(opts.line && !scene.line2d) scene.line2d = true;
    if((opts.errorX || opts.errorY) && !scene.error2d) scene.error2d = true;
    if(opts.text && !scene.glText) scene.glText = true;

    // FIXME: organize it in a more appropriate manner, probably in sceneOptions
    // put point-cluster instance for optimized regl calc
    if(opts.marker && len >= TOO_MANY_POINTS) {
        opts.marker.cluster = stash.tree;
    }

    // save scene opts batch
    scene.lineOptions.push(opts.line);
    scene.errorXOptions.push(opts.errorX);
    scene.errorYOptions.push(opts.errorY);
    scene.fillOptions.push(opts.fill);
    scene.markerOptions.push(opts.marker);
    scene.markerSelectedOptions.push(opts.markerSel);
    scene.markerUnselectedOptions.push(opts.markerUnsel);
    scene.textOptions.push(opts.text);
    scene.textSelectedOptions.push(opts.textSel);
    scene.textUnselectedOptions.push(opts.textUnsel);

    // stash scene ref
    stash._scene = scene;
    stash.index = scene.count;
    stash.x = x;
    stash.y = y;
    stash.positions = positions;
    scene.count++;

    return [{x: false, y: false, t: stash, trace: trace}];
}

function expandForErrorBars(trace, ax, opts) {
    var extremes = trace._extremes[ax._id];
    var errExt = findExtremes(ax, opts._bnds, {padded: true});
    extremes.min = extremes.min.concat(errExt.min);
    extremes.max = extremes.max.concat(errExt.max);
}

// create scene options
function sceneOptions(gd, subplot, trace, positions, x, y) {
    var opts = convert.style(gd, trace);

    if(opts.marker) {
        opts.marker.positions = positions;
    }

    if(opts.line && positions.length > 1) {
        Lib.extendFlat(
            opts.line,
            convert.linePositions(gd, trace, positions)
        );
    }

    if(opts.errorX || opts.errorY) {
        var errors = convert.errorBarPositions(gd, trace, positions, x, y);

        if(opts.errorX) {
            Lib.extendFlat(opts.errorX, errors.x);
        }
        if(opts.errorY) {
            Lib.extendFlat(opts.errorY, errors.y);
        }
    }

    if(opts.text) {
        Lib.extendFlat(
            opts.text,
            {positions: positions},
            convert.textPosition(gd, trace, opts.text, opts.marker)
        );
        Lib.extendFlat(
            opts.textSel,
            {positions: positions},
            convert.textPosition(gd, trace, opts.text, opts.markerSel)
        );
        Lib.extendFlat(
            opts.textUnsel,
            {positions: positions},
            convert.textPosition(gd, trace, opts.text, opts.markerUnsel)
        );
    }

    return opts;
}


// make sure scene exists on subplot, return it
function sceneUpdate(gd, subplot) {
    var scene = subplot._scene;

    var resetOpts = {
        // number of traces in subplot, since scene:subplot → 1:1
        count: 0,
        // whether scene requires init hook in plot call (dirty plot call)
        dirty: true,
        // last used options
        lineOptions: [],
        fillOptions: [],
        markerOptions: [],
        markerSelectedOptions: [],
        markerUnselectedOptions: [],
        errorXOptions: [],
        errorYOptions: [],
        textOptions: [],
        textSelectedOptions: [],
        textUnselectedOptions: []
    };

    var initOpts = {
        selectBatch: null,
        unselectBatch: null,
        // regl- component stubs, initialized in dirty plot call
        fill2d: false,
        scatter2d: false,
        error2d: false,
        line2d: false,
        glText: false,
        select2d: null
    };

    if(!subplot._scene) {
        scene = subplot._scene = {};

        scene.init = function init() {
            Lib.extendFlat(scene, initOpts, resetOpts);
        };

        scene.init();

        // apply new option to all regl components (used on drag)
        scene.update = function update(opt) {
            var opts = Lib.repeat(opt, scene.count);

            if(scene.fill2d) scene.fill2d.update(opts);
            if(scene.scatter2d) scene.scatter2d.update(opts);
            if(scene.line2d) scene.line2d.update(opts);
            if(scene.error2d) scene.error2d.update(opts.concat(opts));
            if(scene.select2d) scene.select2d.update(opts);
            if(scene.glText) {
                for(var i = 0; i < scene.count; i++) {
                    scene.glText[i].update(opt);
                }
            }
        };

        // draw traces in proper order
        scene.draw = function draw() {
            var count = scene.count;
            var fill2d = scene.fill2d;
            var error2d = scene.error2d;
            var line2d = scene.line2d;
            var scatter2d = scene.scatter2d;
            var glText = scene.glText;
            var select2d = scene.select2d;
            var selectBatch = scene.selectBatch;
            var unselectBatch = scene.unselectBatch;

            for(var i = 0; i < count; i++) {
                if(fill2d && scene.fillOrder[i]) {
                    fill2d.draw(scene.fillOrder[i]);
                }
                if(line2d && scene.lineOptions[i]) {
                    line2d.draw(i);
                }
                if(error2d) {
                    if(scene.errorXOptions[i]) error2d.draw(i);
                    if(scene.errorYOptions[i]) error2d.draw(i + count);
                }
                if(scatter2d && scene.markerOptions[i] && (!selectBatch || !selectBatch[i])) {
                    scatter2d.draw(i);
                }
                if(glText[i] && scene.textOptions[i]) {
                    glText[i].render();
                }
            }

            if(scatter2d && select2d && selectBatch) {
                select2d.draw(selectBatch);
                scatter2d.draw(unselectBatch);
            }

            scene.dirty = false;
        };

        // remove scene resources
        scene.destroy = function destroy() {
            if(scene.fill2d && scene.fill2d.destroy) scene.fill2d.destroy();
            if(scene.scatter2d && scene.scatter2d.destroy) scene.scatter2d.destroy();
            if(scene.error2d && scene.error2d.destroy) scene.error2d.destroy();
            if(scene.line2d && scene.line2d.destroy) scene.line2d.destroy();
            if(scene.select2d && scene.select2d.destroy) scene.select2d.destroy();
            if(scene.glText) {
                scene.glText.forEach(function(text) {
                    if(text.destroy) text.destroy();
                });
            }

            scene.lineOptions = null;
            scene.fillOptions = null;
            scene.markerOptions = null;
            scene.markerSelectedOptions = null;
            scene.markerUnselectedOptions = null;
            scene.errorXOptions = null;
            scene.errorYOptions = null;
            scene.textOptions = null;
            scene.textSelectedOptions = null;
            scene.textUnselectedOptions = null;

            scene.selectBatch = null;
            scene.unselectBatch = null;

            // we can't just delete _scene, because `destroy` is called in the
            // middle of supplyDefaults, before relinkPrivateKeys which will put it back.
            subplot._scene = null;
        };
    }

    // In case if we have scene from the last calc - reset data
    if(!scene.dirty) {
        Lib.extendFlat(scene, resetOpts);
    }

    return scene;
}

function getViewport(fullLayout, xaxis, yaxis) {
    var gs = fullLayout._size;
    var width = fullLayout.width;
    var height = fullLayout.height;
    return [
        gs.l + xaxis.domain[0] * gs.w,
        gs.b + yaxis.domain[0] * gs.h,
        (width - gs.r) - (1 - xaxis.domain[1]) * gs.w,
        (height - gs.t) - (1 - yaxis.domain[1]) * gs.h
    ];
}

function plot(gd, subplot, cdata) {
    if(!cdata.length) return;

    var fullLayout = gd._fullLayout;
    var scene = subplot._scene;
    var xaxis = subplot.xaxis;
    var yaxis = subplot.yaxis;
    var i, j;

    // we may have more subplots than initialized data due to Axes.getSubplots method
    if(!scene) return;

    var success = prepareRegl(gd, ['ANGLE_instanced_arrays', 'OES_element_index_uint']);
    if(!success) {
        scene.init();
        return;
    }

    var regl = fullLayout._glcanvas.data()[0].regl;

    // that is needed for fills
    linkTraces(gd, subplot, cdata);

    if(scene.dirty) {
        // make sure scenes are created
        if(scene.error2d === true) {
            scene.error2d = createError(regl);
        }
        if(scene.line2d === true) {
            scene.line2d = createLine(regl);
        }
        if(scene.scatter2d === true) {
            scene.scatter2d = createScatter(regl);
        }
        if(scene.fill2d === true) {
            scene.fill2d = createLine(regl);
        }
        if(scene.glText === true) {
            scene.glText = new Array(scene.count);
            for(i = 0; i < scene.count; i++) {
                scene.glText[i] = new Text(regl);
            }
        }

        // update main marker options
        if(scene.glText) {
            if(scene.count > scene.glText.length) {
                // add gl text marker
                var textsToAdd = scene.count - scene.glText.length;
                for(i = 0; i < textsToAdd; i++) {
                    scene.glText.push(new Text(regl));
                }
            } else if(scene.count < scene.glText.length) {
                // remove gl text marker
                var textsToRemove = scene.glText.length - scene.count;
                var removedTexts = scene.glText.splice(scene.count, textsToRemove);
                removedTexts.forEach(function(text) { text.destroy(); });
            }

            for(i = 0; i < scene.count; i++) {
                scene.glText[i].update(scene.textOptions[i]);
            }
        }
        if(scene.line2d) {
            scene.line2d.update(scene.lineOptions);
            scene.lineOptions = scene.lineOptions.map(function(lineOptions) {
                if(lineOptions && lineOptions.positions) {
                    var srcPos = lineOptions.positions;

                    var firstptdef = 0;
                    while(firstptdef < srcPos.length && (isNaN(srcPos[firstptdef]) || isNaN(srcPos[firstptdef + 1]))) {
                        firstptdef += 2;
                    }
                    var lastptdef = srcPos.length - 2;
                    while(lastptdef > firstptdef && (isNaN(srcPos[lastptdef]) || isNaN(srcPos[lastptdef + 1]))) {
                        lastptdef -= 2;
                    }
                    lineOptions.positions = srcPos.slice(firstptdef, lastptdef + 2);
                }
                return lineOptions;
            });
            scene.line2d.update(scene.lineOptions);
        }
        if(scene.error2d) {
            var errorBatch = (scene.errorXOptions || []).concat(scene.errorYOptions || []);
            scene.error2d.update(errorBatch);
        }
        if(scene.scatter2d) {
            scene.scatter2d.update(scene.markerOptions);
        }

        // fill requires linked traces, so we generate it's positions here
        scene.fillOrder = Lib.repeat(null, scene.count);
        if(scene.fill2d) {
            scene.fillOptions = scene.fillOptions.map(function(fillOptions, i) {
                var cdscatter = cdata[i];
                if(!fillOptions || !cdscatter || !cdscatter[0] || !cdscatter[0].trace) return;
                var cd = cdscatter[0];
                var trace = cd.trace;
                var stash = cd.t;
                var lineOptions = scene.lineOptions[i];
                var last, j;

                var fillData = [];
                if(trace._ownfill) fillData.push(i);
                if(trace._nexttrace) fillData.push(i + 1);
                if(fillData.length) scene.fillOrder[i] = fillData;

                var pos = [];
                var srcPos = (lineOptions && lineOptions.positions) || stash.positions;
                var firstptdef, lastptdef;

                if(trace.fill === 'tozeroy') {
                    firstptdef = 0;
                    while(firstptdef < srcPos.length && isNaN(srcPos[firstptdef + 1])) {
                        firstptdef += 2;
                    }
                    lastptdef = srcPos.length - 2;
                    while(lastptdef > firstptdef && isNaN(srcPos[lastptdef + 1])) {
                        lastptdef -= 2;
                    }
                    if(srcPos[firstptdef + 1] !== 0) {
                        pos = [srcPos[firstptdef], 0];
                    }
                    pos = pos.concat(srcPos.slice(firstptdef, lastptdef + 2));
                    if(srcPos[lastptdef + 1] !== 0) {
                        pos = pos.concat([srcPos[lastptdef], 0]);
                    }
                }
                else if(trace.fill === 'tozerox') {
                    firstptdef = 0;
                    while(firstptdef < srcPos.length && isNaN(srcPos[firstptdef])) {
                        firstptdef += 2;
                    }
                    lastptdef = srcPos.length - 2;
                    while(lastptdef > firstptdef && isNaN(srcPos[lastptdef])) {
                        lastptdef -= 2;
                    }
                    if(srcPos[firstptdef] !== 0) {
                        pos = [0, srcPos[firstptdef + 1]];
                    }
                    pos = pos.concat(srcPos.slice(firstptdef, lastptdef + 2));
                    if(srcPos[lastptdef] !== 0) {
                        pos = pos.concat([ 0, srcPos[lastptdef + 1]]);
                    }
                }
                else if(trace.fill === 'toself' || trace.fill === 'tonext') {
                    pos = [];
                    last = 0;
                    for(j = 0; j < srcPos.length; j += 2) {
                        if(isNaN(srcPos[j]) || isNaN(srcPos[j + 1])) {
                            pos = pos.concat(srcPos.slice(last, j));
                            pos.push(srcPos[last], srcPos[last + 1]);
                            last = j + 2;
                        }
                    }
                    pos = pos.concat(srcPos.slice(last));
                    if(last) {
                        pos.push(srcPos[last], srcPos[last + 1]);
                    }
                }
                else {
                    var nextTrace = trace._nexttrace;

                    if(nextTrace) {
                        var nextOptions = scene.lineOptions[i + 1];

                        if(nextOptions) {
                            var nextPos = nextOptions.positions;
                            if(trace.fill === 'tonexty') {
                                pos = srcPos.slice();

                                for(i = Math.floor(nextPos.length / 2); i--;) {
                                    var xx = nextPos[i * 2];
                                    var yy = nextPos[i * 2 + 1];
                                    if(isNaN(xx) || isNaN(yy)) continue;
                                    pos.push(xx, yy);
                                }
                                fillOptions.fill = nextTrace.fillcolor;
                            }
                        }
                    }
                }

                // detect prev trace positions to exclude from current fill
                if(trace._prevtrace && trace._prevtrace.fill === 'tonext') {
                    var prevLinePos = scene.lineOptions[i - 1].positions;

                    // FIXME: likely this logic should be tested better
                    var offset = pos.length / 2;
                    last = offset;
                    var hole = [last];
                    for(j = 0; j < prevLinePos.length; j += 2) {
                        if(isNaN(prevLinePos[j]) || isNaN(prevLinePos[j + 1])) {
                            hole.push(j / 2 + offset + 1);
                            last = j + 2;
                        }
                    }

                    pos = pos.concat(prevLinePos);
                    fillOptions.hole = hole;
                }
                fillOptions.fillmode = trace.fill;
                fillOptions.opacity = trace.opacity;
                fillOptions.positions = pos;

                return fillOptions;
            });

            scene.fill2d.update(scene.fillOptions);
        }
    }

    // form batch arrays, and check for selected points
    scene.selectBatch = null;
    scene.unselectBatch = null;
    var dragmode = fullLayout.dragmode;
    var selectMode = dragmode === 'lasso' || dragmode === 'select';
    var clickSelectEnabled = fullLayout.clickmode.indexOf('select') > -1;

    for(i = 0; i < cdata.length; i++) {
        var cd0 = cdata[i][0];
        var trace = cd0.trace;
        var stash = cd0.t;
        var index = stash.index;
        var len = trace._length;
        var x = stash.x;
        var y = stash.y;

        if(trace.selectedpoints || selectMode || clickSelectEnabled) {
            if(!selectMode) selectMode = true;

            if(!scene.selectBatch) {
                scene.selectBatch = [];
                scene.unselectBatch = [];
            }

            // regenerate scene batch, if traces number changed during selection
            if(trace.selectedpoints) {
                var selPts = scene.selectBatch[index] = Lib.selIndices2selPoints(trace);

                var selDict = {};
                for(j = 0; j < selPts.length; j++) {
                    selDict[selPts[j]] = 1;
                }
                var unselPts = [];
                for(j = 0; j < len; j++) {
                    if(!selDict[j]) unselPts.push(j);
                }
                scene.unselectBatch[index] = unselPts;
            }

            // precalculate px coords since we are not going to pan during select
            // TODO, could do better here e.g.
            // - spin that in a webworker
            // - compute selection from polygons in data coordinates
            //   (maybe just for linear axes)
            var xpx = stash.xpx = new Array(len);
            var ypx = stash.ypx = new Array(len);
            for(j = 0; j < len; j++) {
                xpx[j] = xaxis.c2p(x[j]);
                ypx[j] = yaxis.c2p(y[j]);
            }
        } else {
            stash.xpx = stash.ypx = null;
        }
    }


    if(selectMode) {
        // create select2d
        if(!scene.select2d) {
            // create scatter instance by cloning scatter2d
            scene.select2d = createScatter(fullLayout._glcanvas.data()[1].regl);
        }

        if(scene.scatter2d && scene.selectBatch && scene.selectBatch.length) {
            // update only traces with selection
            scene.scatter2d.update(scene.markerUnselectedOptions.map(function(opts, i) {
                return scene.selectBatch[i] ? opts : null;
            }));
        }

        if(scene.select2d) {
            scene.select2d.update(scene.markerOptions);
            scene.select2d.update(scene.markerSelectedOptions);
        }

        if(scene.glText) {
            cdata.forEach(function(cdscatter) {
                if(cdscatter && cdscatter[0] && cdscatter[0].trace) {
                    styleTextSelection(cdscatter);
                }
            });
        }
    } else {
        if(scene.scatter2d) {
            // reset scatter2d opts to base opts,
            // thus unsetting markerUnselectedOptions from selection
            scene.scatter2d.update(scene.markerOptions);
        }
    }

    // provide viewport and range
    var vpRange0 = {
        viewport: getViewport(fullLayout, xaxis, yaxis),
        // TODO do we need those fallbacks?
        range: [
            (xaxis._rl || xaxis.range)[0],
            (yaxis._rl || yaxis.range)[0],
            (xaxis._rl || xaxis.range)[1],
            (yaxis._rl || yaxis.range)[1]
        ]
    };
    var vpRange = Lib.repeat(vpRange0, scene.count);

    // upload viewport/range data to GPU
    if(scene.fill2d) {
        scene.fill2d.update(vpRange);
    }
    if(scene.line2d) {
        scene.line2d.update(vpRange);
    }
    if(scene.error2d) {
        scene.error2d.update(vpRange.concat(vpRange));
    }
    if(scene.scatter2d) {
        scene.scatter2d.update(vpRange);
    }
    if(scene.select2d) {
        scene.select2d.update(vpRange);
    }
    if(scene.glText) {
        scene.glText.forEach(function(text) { text.update(vpRange0); });
    }
}


function hoverPoints(pointData, xval, yval, hovermode) {
    var cd = pointData.cd;
    var stash = cd[0].t;
    var trace = cd[0].trace;
    var xa = pointData.xa;
    var ya = pointData.ya;
    var x = stash.x;
    var y = stash.y;
    var xpx = xa.c2p(xval);
    var ypx = ya.c2p(yval);
    var maxDistance = pointData.distance;
    var ids;

    // FIXME: make sure this is a proper way to calc search radius
    if(stash.tree) {
        var xl = xa.p2c(xpx - maxDistance);
        var xr = xa.p2c(xpx + maxDistance);
        var yl = ya.p2c(ypx - maxDistance);
        var yr = ya.p2c(ypx + maxDistance);

        if(hovermode === 'x') {
            ids = stash.tree.range(
                Math.min(xl, xr), Math.min(ya._rl[0], ya._rl[1]),
                Math.max(xl, xr), Math.max(ya._rl[0], ya._rl[1])
            );
        }
        else {
            ids = stash.tree.range(
                Math.min(xl, xr), Math.min(yl, yr),
                Math.max(xl, xr), Math.max(yl, yr)
            );
        }
    }
    else if(stash.ids) {
        ids = stash.ids;
    }
    else return [pointData];

    // pick the id closest to the point
    // note that point possibly may not be found
    var id, ptx, pty, i, dx, dy, dist, dxy;

    var minDist = maxDistance;
    if(hovermode === 'x') {
        for(i = 0; i < ids.length; i++) {
            ptx = x[ids[i]];
            dx = Math.abs(xa.c2p(ptx) - xpx);
            if(dx < minDist) {
                minDist = dx;
                dy = ya.c2p(y[ids[i]]) - ypx;
                dxy = Math.sqrt(dx * dx + dy * dy);
                id = ids[i];
            }
        }
    }
    else {
        for(i = 0; i < ids.length; i++) {
            ptx = x[ids[i]];
            pty = y[ids[i]];
            dx = xa.c2p(ptx) - xpx;
            dy = ya.c2p(pty) - ypx;

            dist = Math.sqrt(dx * dx + dy * dy);
            if(dist < minDist) {
                minDist = dxy = dist;
                id = ids[i];
            }
        }
    }

    pointData.index = id;
    pointData.distance = minDist;
    pointData.dxy = dxy;

    if(id === undefined) return [pointData];

    calcHover(pointData, x, y, trace);

    return [pointData];
}


function calcHover(pointData, x, y, trace) {
    var xa = pointData.xa;
    var ya = pointData.ya;
    var minDist = pointData.distance;
    var dxy = pointData.dxy;
    var id = pointData.index;

    // the closest data point
    var di = {
        pointNumber: id,
        x: x[id],
        y: y[id]
    };

    // that is single-item arrays_to_calcdata excerpt, since we are doing it for a single point and we don't have to do it beforehead for 1e6 points
    di.tx = Array.isArray(trace.text) ? trace.text[id] : trace.text;
    di.htx = Array.isArray(trace.hovertext) ? trace.hovertext[id] : trace.hovertext;
    di.data = Array.isArray(trace.customdata) ? trace.customdata[id] : trace.customdata;
    di.tp = Array.isArray(trace.textposition) ? trace.textposition[id] : trace.textposition;

    var font = trace.textfont;
    if(font) {
        di.ts = Array.isArray(font.size) ? font.size[id] : font.size;
        di.tc = Array.isArray(font.color) ? font.color[id] : font.color;
        di.tf = Array.isArray(font.family) ? font.family[id] : font.family;
    }

    var marker = trace.marker;
    if(marker) {
        di.ms = Lib.isArrayOrTypedArray(marker.size) ? marker.size[id] : marker.size;
        di.mo = Lib.isArrayOrTypedArray(marker.opacity) ? marker.opacity[id] : marker.opacity;
        di.mx = Array.isArray(marker.symbol) ? marker.symbol[id] : marker.symbol;
        di.mc = Lib.isArrayOrTypedArray(marker.color) ? marker.color[id] : marker.color;
    }

    var line = marker && marker.line;
    if(line) {
        di.mlc = Array.isArray(line.color) ? line.color[id] : line.color;
        di.mlw = Lib.isArrayOrTypedArray(line.width) ? line.width[id] : line.width;
    }

    var grad = marker && marker.gradient;
    if(grad && grad.type !== 'none') {
        di.mgt = Array.isArray(grad.type) ? grad.type[id] : grad.type;
        di.mgc = Array.isArray(grad.color) ? grad.color[id] : grad.color;
    }

    var xp = xa.c2p(di.x, true);
    var yp = ya.c2p(di.y, true);
    var rad = di.mrc || 1;

    var hoverlabel = trace.hoverlabel;

    if(hoverlabel) {
        di.hbg = Array.isArray(hoverlabel.bgcolor) ? hoverlabel.bgcolor[id] : hoverlabel.bgcolor;
        di.hbc = Array.isArray(hoverlabel.bordercolor) ? hoverlabel.bordercolor[id] : hoverlabel.bordercolor;
        di.hts = Array.isArray(hoverlabel.font.size) ? hoverlabel.font.size[id] : hoverlabel.font.size;
        di.htc = Array.isArray(hoverlabel.font.color) ? hoverlabel.font.color[id] : hoverlabel.font.color;
        di.htf = Array.isArray(hoverlabel.font.family) ? hoverlabel.font.family[id] : hoverlabel.font.family;
        di.hnl = Array.isArray(hoverlabel.namelength) ? hoverlabel.namelength[id] : hoverlabel.namelength;
    }
    var hoverinfo = trace.hoverinfo;
    if(hoverinfo) {
        di.hi = Array.isArray(hoverinfo) ? hoverinfo[id] : hoverinfo;
    }

    var hovertemplate = trace.hovertemplate;
    if(hovertemplate) {
        di.ht = Array.isArray(hovertemplate) ? hovertemplate[id] : hovertemplate;
    }

    var fakeCd = {};
    fakeCd[pointData.index] = di;

    Lib.extendFlat(pointData, {
        color: getTraceColor(trace, di),

        x0: xp - rad,
        x1: xp + rad,
        xLabelVal: di.x,

        y0: yp - rad,
        y1: yp + rad,
        yLabelVal: di.y,

        cd: fakeCd,
        distance: minDist,
        spikeDistance: dxy,

        hovertemplate: di.ht
    });

    if(di.htx) pointData.text = di.htx;
    else if(di.tx) pointData.text = di.tx;
    else if(trace.text) pointData.text = trace.text;

    fillHoverText(di, trace, pointData);
    Registry.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData);

    return pointData;
}


function selectPoints(searchInfo, selectionTester) {
    var cd = searchInfo.cd;
    var selection = [];
    var trace = cd[0].trace;
    var stash = cd[0].t;
    var len = trace._length;
    var x = stash.x;
    var y = stash.y;
    var scene = stash._scene;

    if(!scene) return selection;

    var hasText = subTypes.hasText(trace);
    var hasMarkers = subTypes.hasMarkers(trace);
    var hasOnlyLines = !hasMarkers && !hasText;
    if(trace.visible !== true || hasOnlyLines) return selection;

    // degenerate polygon does not enable selection
    // filter out points by visible scatter ones
    var els = null;
    var unels = null;
    // FIXME: clearing selection does not work here
    var i;
    if(selectionTester !== false && !selectionTester.degenerate) {
        els = [], unels = [];
        for(i = 0; i < len; i++) {
            if(selectionTester.contains([stash.xpx[i], stash.ypx[i]], false, i, searchInfo)) {
                els.push(i);
                selection.push({
                    pointNumber: i,
                    x: x[i],
                    y: y[i]
                });
            }
            else {
                unels.push(i);
            }
        }
    } else {
        unels = arrayRange(len);
    }

    // make sure selectBatch is created
    if(!scene.selectBatch) {
        scene.selectBatch = [];
        scene.unselectBatch = [];
    }

    if(!scene.selectBatch[stash.index]) {
        // enter every trace select mode
        for(i = 0; i < scene.count; i++) {
            scene.selectBatch[i] = [];
            scene.unselectBatch[i] = [];
        }
        // we should turn scatter2d into unselected once we have any points selected
        if(hasMarkers) {
            scene.scatter2d.update(scene.markerUnselectedOptions);
        }
    }

    scene.selectBatch[stash.index] = els;
    scene.unselectBatch[stash.index] = unels;

    // update text options
    if(hasText) {
        styleTextSelection(cd);
    }

    return selection;
}

function styleTextSelection(cd) {
    var cd0 = cd[0];
    var trace = cd0.trace;
    var stash = cd0.t;
    var scene = stash._scene;
    var index = stash.index;
    var els = scene.selectBatch[index];
    var unels = scene.unselectBatch[index];
    var baseOpts = scene.textOptions[index];
    var selOpts = scene.textSelectedOptions[index] || {};
    var unselOpts = scene.textUnselectedOptions[index] || {};
    var opts = Lib.extendFlat({}, baseOpts);
    var i, j;

    if(els && unels) {
        var stc = selOpts.color;
        var utc = unselOpts.color;
        var base = baseOpts.color;
        var hasArrayBase = Array.isArray(base);
        opts.color = new Array(trace._length);

        for(i = 0; i < els.length; i++) {
            j = els[i];
            opts.color[j] = stc || (hasArrayBase ? base[j] : base);
        }
        for(i = 0; i < unels.length; i++) {
            j = unels[i];
            var basej = hasArrayBase ? base[j] : base;
            opts.color[j] = utc ? utc :
                stc ? basej : Color.addOpacity(basej, DESELECTDIM);
        }
    }

    scene.glText[index].update(opts);
}

module.exports = {
    moduleType: 'trace',
    name: 'scattergl',
    basePlotModule: _dereq_('../../plots/cartesian'),
    categories: ['gl', 'regl', 'cartesian', 'symbols', 'errorBarsOK', 'showLegend', 'scatter-like'],

    attributes: _dereq_('./attributes'),
    supplyDefaults: _dereq_('./defaults'),
    crossTraceDefaults: _dereq_('../scatter/cross_trace_defaults'),
    colorbar: _dereq_('../scatter/marker_colorbar'),
    calc: calc,
    plot: plot,
    hoverPoints: hoverPoints,
    selectPoints: selectPoints,

    sceneUpdate: sceneUpdate,
    calcHover: calcHover,

    meta: {
        
        
    }
};

},{"../../components/color":571,"../../constants/interactions":670,"../../constants/numerical":671,"../../lib":694,"../../lib/prepare_regl":707,"../../plots/cartesian":754,"../../plots/cartesian/autorange":741,"../../plots/cartesian/axis_ids":745,"../../registry":825,"../scatter/calc":1048,"../scatter/colorscale_calc":1050,"../scatter/cross_trace_defaults":1053,"../scatter/fill_hover_text":1055,"../scatter/get_trace_color":1057,"../scatter/link_traces":1063,"../scatter/marker_colorbar":1065,"../scatter/subtypes":1071,"./attributes":1096,"./constants":1097,"./convert":1098,"./defaults":1099,"array-range":56,"gl-text":307,"point-cluster":455,"regl-error2d":476,"regl-line2d":477,"regl-scatter2d":478}],1101:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var scatterGeoAttrs = _dereq_('../scattergeo/attributes');
var scatterAttrs = _dereq_('../scatter/attributes');
var mapboxAttrs = _dereq_('../../plots/mapbox/layout_attributes');
var plotAttrs = _dereq_('../../plots/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;

var lineAttrs = scatterGeoAttrs.line;
var markerAttrs = scatterGeoAttrs.marker;

module.exports = overrideAll({
    lon: scatterGeoAttrs.lon,
    lat: scatterGeoAttrs.lat,

    // locations
    // locationmode

    mode: extendFlat({}, scatterAttrs.mode, {
        dflt: 'markers',
        
    }),

    text: extendFlat({}, scatterAttrs.text, {
        
    }),
    hovertext: extendFlat({}, scatterAttrs.hovertext, {
        
    }),

    line: {
        color: lineAttrs.color,
        width: lineAttrs.width

        // TODO
        // dash: dash
    },

    connectgaps: scatterAttrs.connectgaps,

    marker: {
        symbol: {
            valType: 'string',
            dflt: 'circle',
            
            arrayOk: true,
            
        },
        opacity: markerAttrs.opacity,
        size: markerAttrs.size,
        sizeref: markerAttrs.sizeref,
        sizemin: markerAttrs.sizemin,
        sizemode: markerAttrs.sizemode,
        color: markerAttrs.color,
        colorscale: markerAttrs.colorscale,
        cauto: markerAttrs.cauto,
        cmax: markerAttrs.cmax,
        cmin: markerAttrs.cmin,
        autocolorscale: markerAttrs.autocolorscale,
        reversescale: markerAttrs.reversescale,
        showscale: markerAttrs.showscale,
        colorbar: colorbarAttrs,

        // line
    },

    fill: scatterGeoAttrs.fill,
    fillcolor: scatterAttrs.fillcolor,

    textfont: mapboxAttrs.layers.symbol.textfont,
    textposition: mapboxAttrs.layers.symbol.textposition,

    selected: {
        marker: scatterAttrs.selected.marker
    },
    unselected: {
        marker: scatterAttrs.unselected.marker
    },

    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
        flags: ['lon', 'lat', 'text', 'name']
    }),
    hovertemplate: hovertemplateAttrs(),
}, 'calc', 'nested');

},{"../../components/colorbar/attributes":572,"../../components/fx/hovertemplate_attributes":609,"../../lib/extend":684,"../../plot_api/edit_types":725,"../../plots/attributes":739,"../../plots/mapbox/layout_attributes":802,"../scatter/attributes":1047,"../scattergeo/attributes":1087}],1102:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var Lib = _dereq_('../../lib');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;
var geoJsonUtils = _dereq_('../../lib/geojson_utils');

var Colorscale = _dereq_('../../components/colorscale');
var Drawing = _dereq_('../../components/drawing');
var makeBubbleSizeFn = _dereq_('../scatter/make_bubble_size_func');
var subTypes = _dereq_('../scatter/subtypes');
var convertTextOpts = _dereq_('../../plots/mapbox/convert_text_opts');

module.exports = function convert(calcTrace) {
    var trace = calcTrace[0].trace;

    var isVisible = (trace.visible === true);
    var hasFill = (trace.fill !== 'none');
    var hasLines = subTypes.hasLines(trace);
    var hasMarkers = subTypes.hasMarkers(trace);
    var hasText = subTypes.hasText(trace);
    var hasCircles = (hasMarkers && trace.marker.symbol === 'circle');
    var hasSymbols = (hasMarkers && trace.marker.symbol !== 'circle');

    var fill = initContainer();
    var line = initContainer();
    var circle = initContainer();
    var symbol = initContainer();

    var opts = {
        fill: fill,
        line: line,
        circle: circle,
        symbol: symbol
    };

    // early return if not visible or placeholder
    if(!isVisible) return opts;

    // fill layer and line layer use the same coords
    var lineCoords;
    if(hasFill || hasLines) {
        lineCoords = geoJsonUtils.calcTraceToLineCoords(calcTrace);
    }

    if(hasFill) {
        fill.geojson = geoJsonUtils.makePolygon(lineCoords);
        fill.layout.visibility = 'visible';

        Lib.extendFlat(fill.paint, {
            'fill-color': trace.fillcolor
        });
    }

    if(hasLines) {
        line.geojson = geoJsonUtils.makeLine(lineCoords);
        line.layout.visibility = 'visible';

        Lib.extendFlat(line.paint, {
            'line-width': trace.line.width,
            'line-color': trace.line.color,
            'line-opacity': trace.opacity
        });

        // TODO convert line.dash into line-dasharray
    }

    if(hasCircles) {
        var circleOpts = makeCircleOpts(calcTrace);
        circle.geojson = circleOpts.geojson;
        circle.layout.visibility = 'visible';

        Lib.extendFlat(circle.paint, {
            'circle-color': circleOpts.mcc,
            'circle-radius': circleOpts.mrc,
            'circle-opacity': circleOpts.mo
        });
    }

    if(hasSymbols || hasText) {
        symbol.geojson = makeSymbolGeoJSON(calcTrace);

        Lib.extendFlat(symbol.layout, {
            visibility: 'visible',
            'icon-image': '{symbol}-15',
            'text-field': '{text}'
        });

        if(hasSymbols) {
            Lib.extendFlat(symbol.layout, {
                'icon-size': trace.marker.size / 10
            });

            Lib.extendFlat(symbol.paint, {
                'icon-opacity': trace.opacity * trace.marker.opacity,

                // TODO does not work ??
                'icon-color': trace.marker.color
            });
        }

        if(hasText) {
            var iconSize = (trace.marker || {}).size;
            var textOpts = convertTextOpts(trace.textposition, iconSize);

            // all data-driven below !!

            Lib.extendFlat(symbol.layout, {
                'text-size': trace.textfont.size,
                'text-anchor': textOpts.anchor,
                'text-offset': textOpts.offset

                // TODO font family
                // 'text-font': symbol.textfont.family.split(', '),
            });

            Lib.extendFlat(symbol.paint, {
                'text-color': trace.textfont.color,
                'text-opacity': trace.opacity
            });
        }
    }

    return opts;
};

function initContainer() {
    return {
        geojson: geoJsonUtils.makeBlank(),
        layout: { visibility: 'none' },
        paint: {}
    };
}

function makeCircleOpts(calcTrace) {
    var trace = calcTrace[0].trace;
    var marker = trace.marker;
    var selectedpoints = trace.selectedpoints;
    var arrayColor = Lib.isArrayOrTypedArray(marker.color);
    var arraySize = Lib.isArrayOrTypedArray(marker.size);
    var arrayOpacity = Lib.isArrayOrTypedArray(marker.opacity);
    var i;

    function addTraceOpacity(o) { return trace.opacity * o; }

    function size2radius(s) { return s / 2; }

    var colorFn;
    if(arrayColor) {
        if(Colorscale.hasColorscale(trace, 'marker')) {
            colorFn = Colorscale.makeColorScaleFunc(
                 Colorscale.extractScale(marker, {cLetter: 'c'})
             );
        } else {
            colorFn = Lib.identity;
        }
    }

    var sizeFn;
    if(arraySize) {
        sizeFn = makeBubbleSizeFn(trace);
    }

    var opacityFn;
    if(arrayOpacity) {
        opacityFn = function(mo) {
            var mo2 = isNumeric(mo) ? +Lib.constrain(mo, 0, 1) : 0;
            return addTraceOpacity(mo2);
        };
    }

    var features = [];
    for(i = 0; i < calcTrace.length; i++) {
        var calcPt = calcTrace[i];
        var lonlat = calcPt.lonlat;

        if(isBADNUM(lonlat)) continue;

        var props = {};
        if(colorFn) props.mcc = calcPt.mcc = colorFn(calcPt.mc);
        if(sizeFn) props.mrc = calcPt.mrc = sizeFn(calcPt.ms);
        if(opacityFn) props.mo = opacityFn(calcPt.mo);
        if(selectedpoints) props.selected = calcPt.selected || 0;

        features.push({
            type: 'Feature',
            geometry: {type: 'Point', coordinates: lonlat},
            properties: props
        });
    }

    var fns;
    if(selectedpoints) {
        fns = Drawing.makeSelectedPointStyleFns(trace);

        for(i = 0; i < features.length; i++) {
            var d = features[i].properties;

            if(fns.selectedOpacityFn) {
                d.mo = addTraceOpacity(fns.selectedOpacityFn(d));
            }
            if(fns.selectedColorFn) {
                d.mcc = fns.selectedColorFn(d);
            }
            if(fns.selectedSizeFn) {
                d.mrc = fns.selectedSizeFn(d);
            }
        }
    }

    return {
        geojson: {type: 'FeatureCollection', features: features},
        mcc: arrayColor || (fns && fns.selectedColorFn) ?
            {type: 'identity', property: 'mcc'} :
            marker.color,
        mrc: arraySize || (fns && fns.selectedSizeFn) ?
            {type: 'identity', property: 'mrc'} :
            size2radius(marker.size),
        mo: arrayOpacity || (fns && fns.selectedOpacityFn) ?
            {type: 'identity', property: 'mo'} :
            addTraceOpacity(marker.opacity)
    };
}

function makeSymbolGeoJSON(calcTrace) {
    var trace = calcTrace[0].trace;

    var marker = trace.marker || {};
    var symbol = marker.symbol;
    var text = trace.text;

    var fillSymbol = (symbol !== 'circle') ?
        getFillFunc(symbol) :
        blankFillFunc;

    var fillText = subTypes.hasText(trace) ?
        getFillFunc(text) :
        blankFillFunc;

    var features = [];

    for(var i = 0; i < calcTrace.length; i++) {
        var calcPt = calcTrace[i];

        if(isBADNUM(calcPt.lonlat)) continue;

        features.push({
            type: 'Feature',
            geometry: {
                type: 'Point',
                coordinates: calcPt.lonlat
            },
            properties: {
                symbol: fillSymbol(calcPt.mx),
                text: fillText(calcPt.tx)
            }
        });
    }

    return {
        type: 'FeatureCollection',
        features: features
    };
}

function getFillFunc(attr) {
    if(Lib.isArrayOrTypedArray(attr)) {
        return function(v) { return v; };
    }
    else if(attr) {
        return function() { return attr; };
    }
    else {
        return blankFillFunc;
    }
}

function blankFillFunc() { return ''; }

// only need to check lon (OR lat)
function isBADNUM(lonlat) {
    return lonlat[0] === BADNUM;
}

},{"../../components/colorscale":583,"../../components/drawing":592,"../../constants/numerical":671,"../../lib":694,"../../lib/geojson_utils":688,"../../plots/mapbox/convert_text_opts":799,"../scatter/make_bubble_size_func":1064,"../scatter/subtypes":1071,"fast-isnumeric":215}],1103:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

var subTypes = _dereq_('../scatter/subtypes');
var handleMarkerDefaults = _dereq_('../scatter/marker_defaults');
var handleLineDefaults = _dereq_('../scatter/line_defaults');
var handleTextDefaults = _dereq_('../scatter/text_defaults');
var handleFillColorDefaults = _dereq_('../scatter/fillcolor_defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var len = handleLonLatDefaults(traceIn, traceOut, coerce);
    if(!len) {
        traceOut.visible = false;
        return;
    }

    coerce('text');
    coerce('hovertext');
    coerce('hovertemplate');
    coerce('mode');

    if(subTypes.hasLines(traceOut)) {
        handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce, {noDash: true});
        coerce('connectgaps');
    }

    if(subTypes.hasMarkers(traceOut)) {
        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {noLine: true});

        // array marker.size and marker.color are only supported with circles
        var marker = traceOut.marker;
        if(marker.symbol !== 'circle') {
            if(Lib.isArrayOrTypedArray(marker.size)) marker.size = marker.size[0];
            if(Lib.isArrayOrTypedArray(marker.color)) marker.color = marker.color[0];
        }
    }

    if(subTypes.hasText(traceOut)) {
        handleTextDefaults(traceIn, traceOut, layout, coerce, {noSelect: true});
    }

    coerce('fill');
    if(traceOut.fill !== 'none') {
        handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
    }

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};

function handleLonLatDefaults(traceIn, traceOut, coerce) {
    var lon = coerce('lon') || [];
    var lat = coerce('lat') || [];
    var len = Math.min(lon.length, lat.length);
    traceOut._length = len;

    return len;
}

},{"../../lib":694,"../scatter/fillcolor_defaults":1056,"../scatter/line_defaults":1060,"../scatter/marker_defaults":1066,"../scatter/subtypes":1071,"../scatter/text_defaults":1072,"./attributes":1101}],1104:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


module.exports = function eventData(out, pt) {
    out.lon = pt.lon;
    out.lat = pt.lat;

    return out;
};

},{}],1105:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Fx = _dereq_('../../components/fx');
var Lib = _dereq_('../../lib');
var getTraceColor = _dereq_('../scatter/get_trace_color');
var fillHoverText = _dereq_('../scatter/fill_hover_text');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

module.exports = function hoverPoints(pointData, xval, yval) {
    var cd = pointData.cd;
    var trace = cd[0].trace;
    var xa = pointData.xa;
    var ya = pointData.ya;
    var subplot = pointData.subplot;

    // compute winding number about [-180, 180] globe
    var winding = (xval >= 0) ?
        Math.floor((xval + 180) / 360) :
        Math.ceil((xval - 180) / 360);

    // shift longitude to [-180, 180] to determine closest point
    var lonShift = winding * 360;
    var xval2 = xval - lonShift;

    function distFn(d) {
        var lonlat = d.lonlat;
        if(lonlat[0] === BADNUM) return Infinity;

        var lon = Lib.modHalf(lonlat[0], 360);
        var lat = lonlat[1];
        var pt = subplot.project([lon, lat]);
        var dx = pt.x - xa.c2p([xval2, lat]);
        var dy = pt.y - ya.c2p([lon, yval]);
        var rad = Math.max(3, d.mrc || 0);

        return Math.max(Math.sqrt(dx * dx + dy * dy) - rad, 1 - 3 / rad);
    }

    Fx.getClosest(cd, distFn, pointData);

    // skip the rest (for this trace) if we didn't find a close point
    if(pointData.index === false) return;

    var di = cd[pointData.index];
    var lonlat = di.lonlat;
    var lonlatShifted = [Lib.modHalf(lonlat[0], 360) + lonShift, lonlat[1]];

    // shift labels back to original winded globe
    var xc = xa.c2p(lonlatShifted);
    var yc = ya.c2p(lonlatShifted);
    var rad = di.mrc || 1;

    pointData.x0 = xc - rad;
    pointData.x1 = xc + rad;
    pointData.y0 = yc - rad;
    pointData.y1 = yc + rad;

    pointData.color = getTraceColor(trace, di);
    pointData.extraText = getExtraText(trace, di, cd[0].t.labels);
    pointData.hovertemplate = trace.hovertemplate;

    return [pointData];
};

function getExtraText(trace, di, labels) {
    if(trace.hovertemplate) {
        return;
    }

    var hoverinfo = di.hi || trace.hoverinfo;
    var parts = hoverinfo.split('+');
    var isAll = parts.indexOf('all') !== -1;
    var hasLon = parts.indexOf('lon') !== -1;
    var hasLat = parts.indexOf('lat') !== -1;
    var lonlat = di.lonlat;
    var text = [];

    // TODO should we use a mock axis to format hover?
    // If so, we'll need to make precision be zoom-level dependent
    function format(v) {
        return v + '\u00B0';
    }

    if(isAll || (hasLon && hasLat)) {
        text.push('(' + format(lonlat[0]) + ', ' + format(lonlat[1]) + ')');
    } else if(hasLon) {
        text.push(labels.lon + format(lonlat[0]));
    } else if(hasLat) {
        text.push(labels.lat + format(lonlat[1]));
    }

    if(isAll || parts.indexOf('text') !== -1) {
        fillHoverText(di, trace, text);
    }

    return text.join('<br>');
}

},{"../../components/fx":610,"../../constants/numerical":671,"../../lib":694,"../scatter/fill_hover_text":1055,"../scatter/get_trace_color":1057}],1106:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


var ScatterMapbox = {};

ScatterMapbox.attributes = _dereq_('./attributes');
ScatterMapbox.supplyDefaults = _dereq_('./defaults');
ScatterMapbox.colorbar = _dereq_('../scatter/marker_colorbar');
ScatterMapbox.calc = _dereq_('../scattergeo/calc');
ScatterMapbox.plot = _dereq_('./plot');
ScatterMapbox.hoverPoints = _dereq_('./hover');
ScatterMapbox.eventData = _dereq_('./event_data');
ScatterMapbox.selectPoints = _dereq_('./select');

ScatterMapbox.style = function(_, cd) {
    if(cd) {
        var trace = cd[0].trace;
        trace._glTrace.update(cd);
    }
};

ScatterMapbox.moduleType = 'trace';
ScatterMapbox.name = 'scattermapbox';
ScatterMapbox.basePlotModule = _dereq_('../../plots/mapbox');
ScatterMapbox.categories = ['mapbox', 'gl', 'symbols', 'showLegend', 'scatterlike'];
ScatterMapbox.meta = {
    
    
};

module.exports = ScatterMapbox;

},{"../../plots/mapbox":800,"../scatter/marker_colorbar":1065,"../scattergeo/calc":1088,"./attributes":1101,"./defaults":1103,"./event_data":1104,"./hover":1105,"./plot":1107,"./select":1108}],1107:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var convert = _dereq_('./convert');

function ScatterMapbox(subplot, uid) {
    this.subplot = subplot;
    this.uid = uid;

    this.sourceIds = {
        fill: uid + '-source-fill',
        line: uid + '-source-line',
        circle: uid + '-source-circle',
        symbol: uid + '-source-symbol'
    };

    this.layerIds = {
        fill: uid + '-layer-fill',
        line: uid + '-layer-line',
        circle: uid + '-layer-circle',
        symbol: uid + '-layer-symbol'
    };

    this.order = ['fill', 'line', 'circle', 'symbol'];

    // We could merge the 'fill' source with the 'line' source and
    // the 'circle' source with the 'symbol' source if ever having
    // for up-to 4 sources per 'scattermapbox' traces becomes a problem.
}

var proto = ScatterMapbox.prototype;

proto.addSource = function(k, opts) {
    this.subplot.map.addSource(this.sourceIds[k], {
        type: 'geojson',
        data: opts.geojson
    });
};

proto.setSourceData = function(k, opts) {
    this.subplot.map
        .getSource(this.sourceIds[k])
        .setData(opts.geojson);
};

proto.addLayer = function(k, opts) {
    this.subplot.map.addLayer({
        type: k,
        id: this.layerIds[k],
        source: this.sourceIds[k],
        layout: opts.layout,
        paint: opts.paint
    });
};

proto.update = function update(calcTrace) {
    var subplot = this.subplot;
    var optsAll = convert(calcTrace);

    for(var i = 0; i < this.order.length; i++) {
        var k = this.order[i];
        var opts = optsAll[k];

        subplot.setOptions(this.layerIds[k], 'setLayoutProperty', opts.layout);

        if(opts.layout.visibility === 'visible') {
            this.setSourceData(k, opts);
            subplot.setOptions(this.layerIds[k], 'setPaintProperty', opts.paint);
        }
    }

    // link ref for quick update during selections
    calcTrace[0].trace._glTrace = this;
};

proto.dispose = function dispose() {
    var map = this.subplot.map;

    for(var i = 0; i < this.order.length; i++) {
        var k = this.order[i];
        map.removeLayer(this.layerIds[k]);
        map.removeSource(this.sourceIds[k]);
    }
};

module.exports = function createScatterMapbox(subplot, calcTrace) {
    var trace = calcTrace[0].trace;
    var scatterMapbox = new ScatterMapbox(subplot, trace.uid);
    var optsAll = convert(calcTrace);

    for(var i = 0; i < scatterMapbox.order.length; i++) {
        var k = scatterMapbox.order[i];
        var opts = optsAll[k];

        scatterMapbox.addSource(k, opts);
        scatterMapbox.addLayer(k, opts);
    }

    // link ref for quick update during selections
    calcTrace[0].trace._glTrace = scatterMapbox;

    return scatterMapbox;
};

},{"./convert":1102}],1108:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var subtypes = _dereq_('../scatter/subtypes');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

module.exports = function selectPoints(searchInfo, selectionTester) {
    var cd = searchInfo.cd;
    var xa = searchInfo.xaxis;
    var ya = searchInfo.yaxis;
    var selection = [];
    var trace = cd[0].trace;
    var i;

    if(!subtypes.hasMarkers(trace)) return [];

    if(selectionTester === false) {
        for(i = 0; i < cd.length; i++) {
            cd[i].selected = 0;
        }
    } else {
        for(i = 0; i < cd.length; i++) {
            var di = cd[i];
            var lonlat = di.lonlat;

            if(lonlat[0] !== BADNUM) {
                var lonlat2 = [Lib.modHalf(lonlat[0], 360), lonlat[1]];
                var xy = [xa.c2p(lonlat2), ya.c2p(lonlat2)];

                if(selectionTester.contains(xy, null, i, searchInfo)) {
                    selection.push({
                        pointNumber: i,
                        lon: lonlat[0],
                        lat: lonlat[1]
                    });
                    di.selected = 1;
                } else {
                    di.selected = 0;
                }
            }
        }
    }

    return selection;
};

},{"../../constants/numerical":671,"../../lib":694,"../scatter/subtypes":1071}],1109:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var extendFlat = _dereq_('../../lib/extend').extendFlat;
var scatterAttrs = _dereq_('../scatter/attributes');
var plotAttrs = _dereq_('../../plots/attributes');
var lineAttrs = scatterAttrs.line;

module.exports = {
    mode: scatterAttrs.mode,

    r: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },

    theta: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },

    r0: {
        valType: 'any',
        dflt: 0,
        
        editType: 'calc+clearAxisTypes',
        
    },
    dr: {
        valType: 'number',
        dflt: 1,
        
        editType: 'calc',
        
    },

    theta0: {
        valType: 'any',
        dflt: 0,
        
        editType: 'calc+clearAxisTypes',
        
    },
    dtheta: {
        valType: 'number',
        
        editType: 'calc',
        
    },

    thetaunit: {
        valType: 'enumerated',
        values: ['radians', 'degrees', 'gradians'],
        dflt: 'degrees',
        
        editType: 'calc+clearAxisTypes',
        
    },

    text: scatterAttrs.text,
    hovertext: scatterAttrs.hovertext,

    line: {
        color: lineAttrs.color,
        width: lineAttrs.width,
        dash: lineAttrs.dash,
        shape: extendFlat({}, lineAttrs.shape, {
            values: ['linear', 'spline']
        }),
        smoothing: lineAttrs.smoothing,
        editType: 'calc'
    },
    connectgaps: scatterAttrs.connectgaps,

    marker: scatterAttrs.marker,
    cliponaxis: extendFlat({}, scatterAttrs.cliponaxis, {dflt: false}),

    textposition: scatterAttrs.textposition,
    textfont: scatterAttrs.textfont,

    fill: extendFlat({}, scatterAttrs.fill, {
        values: ['none', 'toself', 'tonext'],
        dflt: 'none',
        
    }),
    fillcolor: scatterAttrs.fillcolor,

    // TODO error bars
    // https://stackoverflow.com/a/26597487/4068492
    // error_x (error_r, error_theta)
    // error_y

    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
        flags: ['r', 'theta', 'text', 'name']
    }),
    hoveron: scatterAttrs.hoveron,
    hovertemplate: hovertemplateAttrs(),

    selected: scatterAttrs.selected,
    unselected: scatterAttrs.unselected
};

},{"../../components/fx/hovertemplate_attributes":609,"../../lib/extend":684,"../../plots/attributes":739,"../scatter/attributes":1047}],1110:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

var Axes = _dereq_('../../plots/cartesian/axes');

var calcColorscale = _dereq_('../scatter/colorscale_calc');
var arraysToCalcdata = _dereq_('../scatter/arrays_to_calcdata');
var calcSelection = _dereq_('../scatter/calc_selection');
var calcMarkerSize = _dereq_('../scatter/calc').calcMarkerSize;

module.exports = function calc(gd, trace) {
    var fullLayout = gd._fullLayout;
    var subplotId = trace.subplot;
    var radialAxis = fullLayout[subplotId].radialaxis;
    var angularAxis = fullLayout[subplotId].angularaxis;
    var rArray = radialAxis.makeCalcdata(trace, 'r');
    var thetaArray = angularAxis.makeCalcdata(trace, 'theta');
    var len = trace._length;
    var cd = new Array(len);

    for(var i = 0; i < len; i++) {
        var r = rArray[i];
        var theta = thetaArray[i];
        var cdi = cd[i] = {};

        if(isNumeric(r) && isNumeric(theta)) {
            cdi.r = r;
            cdi.theta = theta;
        } else {
            cdi.r = BADNUM;
        }
    }

    var ppad = calcMarkerSize(trace, len);
    trace._extremes.x = Axes.findExtremes(radialAxis, rArray, {ppad: ppad});

    calcColorscale(gd, trace);
    arraysToCalcdata(cd, trace);
    calcSelection(cd, trace);

    return cd;
};

},{"../../constants/numerical":671,"../../plots/cartesian/axes":742,"../scatter/arrays_to_calcdata":1046,"../scatter/calc":1048,"../scatter/calc_selection":1049,"../scatter/colorscale_calc":1050,"fast-isnumeric":215}],1111:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

var subTypes = _dereq_('../scatter/subtypes');
var handleMarkerDefaults = _dereq_('../scatter/marker_defaults');
var handleLineDefaults = _dereq_('../scatter/line_defaults');
var handleLineShapeDefaults = _dereq_('../scatter/line_shape_defaults');
var handleTextDefaults = _dereq_('../scatter/text_defaults');
var handleFillColorDefaults = _dereq_('../scatter/fillcolor_defaults');
var PTS_LINESONLY = _dereq_('../scatter/constants').PTS_LINESONLY;

var attributes = _dereq_('./attributes');

function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var len = handleRThetaDefaults(traceIn, traceOut, layout, coerce);
    if(!len) {
        traceOut.visible = false;
        return;
    }

    coerce('thetaunit');
    coerce('mode', len < PTS_LINESONLY ? 'lines+markers' : 'lines');
    coerce('text');
    coerce('hovertext');
    if(traceOut.hoveron !== 'fills') coerce('hovertemplate');

    if(subTypes.hasLines(traceOut)) {
        handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
        handleLineShapeDefaults(traceIn, traceOut, coerce);
        coerce('connectgaps');
    }

    if(subTypes.hasMarkers(traceOut)) {
        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true});
    }

    if(subTypes.hasText(traceOut)) {
        handleTextDefaults(traceIn, traceOut, layout, coerce);
    }

    var dfltHoverOn = [];

    if(subTypes.hasMarkers(traceOut) || subTypes.hasText(traceOut)) {
        coerce('cliponaxis');
        coerce('marker.maxdisplayed');
        dfltHoverOn.push('points');
    }

    coerce('fill');

    if(traceOut.fill !== 'none') {
        handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
        if(!subTypes.hasLines(traceOut)) handleLineShapeDefaults(traceIn, traceOut, coerce);
    }

    if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') {
        dfltHoverOn.push('fills');
    }
    coerce('hoveron', dfltHoverOn.join('+') || 'points');

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
}

function handleRThetaDefaults(traceIn, traceOut, layout, coerce) {
    var r = coerce('r');
    var theta = coerce('theta');
    var len;

    if(r) {
        if(theta) {
            len = Math.min(r.length, theta.length);
        } else {
            len = r.length;
            coerce('theta0');
            coerce('dtheta');
        }
    } else {
        if(!theta) return 0;
        len = traceOut.theta.length;
        coerce('r0');
        coerce('dr');
    }

    traceOut._length = len;
    return len;
}

module.exports = {
    handleRThetaDefaults: handleRThetaDefaults,
    supplyDefaults: supplyDefaults
};

},{"../../lib":694,"../scatter/constants":1051,"../scatter/fillcolor_defaults":1056,"../scatter/line_defaults":1060,"../scatter/line_shape_defaults":1062,"../scatter/marker_defaults":1066,"../scatter/subtypes":1071,"../scatter/text_defaults":1072,"./attributes":1109}],1112:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterHover = _dereq_('../scatter/hover');
var Axes = _dereq_('../../plots/cartesian/axes');
var Lib = _dereq_('../../lib');

function hoverPoints(pointData, xval, yval, hovermode) {
    var scatterPointData = scatterHover(pointData, xval, yval, hovermode);
    if(!scatterPointData || scatterPointData[0].index === false) return;

    var newPointData = scatterPointData[0];

    // hovering on fill case
    if(newPointData.index === undefined) {
        return scatterPointData;
    }

    var subplot = pointData.subplot;
    var cdi = newPointData.cd[newPointData.index];
    var trace = newPointData.trace;

    if(!subplot.isPtInside(cdi)) return;

    newPointData.xLabelVal = undefined;
    newPointData.yLabelVal = undefined;
    makeHoverPointText(cdi, trace, subplot, newPointData);
    newPointData.hovertemplate = trace.hovertemplate;
    return scatterPointData;
}

function makeHoverPointText(cdi, trace, subplot, pointData) {

    var radialAxis = subplot.radialAxis;
    var angularAxis = subplot.angularAxis;
    radialAxis._hovertitle = 'r';
    angularAxis._hovertitle = 'θ';

    var hoverinfo = cdi.hi || trace.hoverinfo;
    var text = [];
    function textPart(ax, val) {
        text.push(ax._hovertitle + ': ' + Axes.tickText(ax, val, 'hover').text);
    }

    if(!trace.hovertemplate) {
        var parts = hoverinfo.split('+');

        if(parts.indexOf('all') !== -1) parts = ['r', 'theta', 'text'];
        if(parts.indexOf('r') !== -1) {
            textPart(radialAxis, radialAxis.c2l(cdi.r));
        }
        if(parts.indexOf('theta') !== -1) {
            var theta = cdi.theta;
            textPart(
                angularAxis,
                angularAxis.thetaunit === 'degrees' ? Lib.rad2deg(theta) : theta
            );
        }
        if(parts.indexOf('text') !== -1 && pointData.text) {
            text.push(pointData.text);
            delete pointData.text;
        }

        pointData.extraText = text.join('<br>');
    }
}

module.exports = {
    hoverPoints: hoverPoints,
    makeHoverPointText: makeHoverPointText
};

},{"../../lib":694,"../../plots/cartesian/axes":742,"../scatter/hover":1058}],1113:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'trace',
    name: 'scatterpolar',
    basePlotModule: _dereq_('../../plots/polar'),
    categories: ['polar', 'symbols', 'showLegend', 'scatter-like'],

    attributes: _dereq_('./attributes'),
    supplyDefaults: _dereq_('./defaults').supplyDefaults,
    colorbar: _dereq_('../scatter/marker_colorbar'),
    calc: _dereq_('./calc'),
    plot: _dereq_('./plot'),
    style: _dereq_('../scatter/style').style,
    hoverPoints: _dereq_('./hover').hoverPoints,
    selectPoints: _dereq_('../scatter/select'),

    meta: {
        
        
    }
};

},{"../../plots/polar":809,"../scatter/marker_colorbar":1065,"../scatter/select":1068,"../scatter/style":1070,"./attributes":1109,"./calc":1110,"./defaults":1111,"./hover":1112,"./plot":1114}],1114:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterPlot = _dereq_('../scatter/plot');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

module.exports = function plot(gd, subplot, moduleCalcData) {
    var mlayer = subplot.layers.frontplot.select('g.scatterlayer');

    var plotinfo = {
        xaxis: subplot.xaxis,
        yaxis: subplot.yaxis,
        plot: subplot.framework,
        layerClipId: subplot._hasClipOnAxisFalse ? subplot.clipIds.forTraces : null
    };

    var radialAxis = subplot.radialAxis;
    var angularAxis = subplot.angularAxis;

    // convert:
    // 'c' (r,theta) -> 'geometric' (r,theta) -> (x,y)
    for(var i = 0; i < moduleCalcData.length; i++) {
        var cdi = moduleCalcData[i];

        for(var j = 0; j < cdi.length; j++) {
            var cd = cdi[j];
            var r = cd.r;

            if(r === BADNUM) {
                cd.x = cd.y = BADNUM;
            } else {
                var rg = radialAxis.c2g(r);
                var thetag = angularAxis.c2g(cd.theta);
                cd.x = rg * Math.cos(thetag);
                cd.y = rg * Math.sin(thetag);
            }
        }
    }

    scatterPlot(gd, plotinfo, moduleCalcData, mlayer);
};

},{"../../constants/numerical":671,"../scatter/plot":1067}],1115:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterPolarAttrs = _dereq_('../scatterpolar/attributes');
var scatterGlAttrs = _dereq_('../scattergl/attributes');

module.exports = {
    mode: scatterPolarAttrs.mode,
    r: scatterPolarAttrs.r,
    theta: scatterPolarAttrs.theta,
    r0: scatterPolarAttrs.r0,
    dr: scatterPolarAttrs.dr,
    theta0: scatterPolarAttrs.theta0,
    dtheta: scatterPolarAttrs.dtheta,
    thetaunit: scatterPolarAttrs.thetaunit,

    text: scatterPolarAttrs.text,
    hovertext: scatterPolarAttrs.hovertext,
    hovertemplate: scatterPolarAttrs.hovertemplate,

    line: scatterGlAttrs.line,
    connectgaps: scatterGlAttrs.connectgaps,

    marker: scatterGlAttrs.marker,
    // no cliponaxis

    fill: scatterGlAttrs.fill,
    fillcolor: scatterGlAttrs.fillcolor,

    textposition: scatterGlAttrs.textposition,
    textfont: scatterGlAttrs.textfont,

    hoverinfo: scatterPolarAttrs.hoverinfo,
    // no hoveron

    selected: scatterPolarAttrs.selected,
    unselected: scatterPolarAttrs.unselected
};

},{"../scattergl/attributes":1096,"../scatterpolar/attributes":1109}],1116:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

var subTypes = _dereq_('../scatter/subtypes');
var handleRThetaDefaults = _dereq_('../scatterpolar/defaults').handleRThetaDefaults;
var handleMarkerDefaults = _dereq_('../scatter/marker_defaults');
var handleLineDefaults = _dereq_('../scatter/line_defaults');
var handleTextDefaults = _dereq_('../scatter/text_defaults');
var handleFillColorDefaults = _dereq_('../scatter/fillcolor_defaults');
var PTS_LINESONLY = _dereq_('../scatter/constants').PTS_LINESONLY;

var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var len = handleRThetaDefaults(traceIn, traceOut, layout, coerce);
    if(!len) {
        traceOut.visible = false;
        return;
    }

    coerce('thetaunit');
    coerce('mode', len < PTS_LINESONLY ? 'lines+markers' : 'lines');
    coerce('text');
    coerce('hovertext');
    if(traceOut.hoveron !== 'fills') coerce('hovertemplate');

    if(subTypes.hasLines(traceOut)) {
        handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
        coerce('connectgaps');
    }

    if(subTypes.hasMarkers(traceOut)) {
        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce);
    }

    if(subTypes.hasText(traceOut)) {
        handleTextDefaults(traceIn, traceOut, layout, coerce);
    }

    coerce('fill');
    if(traceOut.fill !== 'none') {
        handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
    }

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};

},{"../../lib":694,"../scatter/constants":1051,"../scatter/fillcolor_defaults":1056,"../scatter/line_defaults":1060,"../scatter/marker_defaults":1066,"../scatter/subtypes":1071,"../scatter/text_defaults":1072,"../scatterpolar/defaults":1111,"./attributes":1115}],1117:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var cluster = _dereq_('point-cluster');
var isNumeric = _dereq_('fast-isnumeric');

var ScatterGl = _dereq_('../scattergl');
var calcColorscale = _dereq_('../scatter/colorscale_calc');
var calcMarkerSize = _dereq_('../scatter/calc').calcMarkerSize;
var convert = _dereq_('../scattergl/convert');

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');
var makeHoverPointText = _dereq_('../scatterpolar/hover').makeHoverPointText;

var TOO_MANY_POINTS = _dereq_('../scattergl/constants').TOO_MANY_POINTS;

function calc(gd, trace) {
    var fullLayout = gd._fullLayout;
    var subplotId = trace.subplot;
    var radialAxis = fullLayout[subplotId].radialaxis;
    var angularAxis = fullLayout[subplotId].angularaxis;
    var rArray = radialAxis.makeCalcdata(trace, 'r');
    var thetaArray = angularAxis.makeCalcdata(trace, 'theta');
    var len = trace._length;
    var stash = {};

    if(len < rArray.length) rArray = rArray.slice(0, len);
    if(len < thetaArray.length) thetaArray = thetaArray.slice(0, len);

    stash.r = rArray;
    stash.theta = thetaArray;

    calcColorscale(gd, trace);

    // only compute 'style' options in calc, as position options
    // depend on the radial range and must be set in plot
    var opts = stash.opts = convert.style(gd, trace);

    // For graphs with very large number of points and array marker.size,
    // use average marker size instead to speed things up.
    var ppad;
    if(len < TOO_MANY_POINTS) {
        ppad = calcMarkerSize(trace, len);
    } else if(opts.marker) {
        ppad = 2 * (opts.marker.sizeAvg || Math.max(opts.marker.size, 3));
    }
    trace._extremes.x = Axes.findExtremes(radialAxis, rArray, {ppad: ppad});

    return [{x: false, y: false, t: stash, trace: trace}];
}

function plot(gd, subplot, cdata) {
    if(!cdata.length) return;

    var radialAxis = subplot.radialAxis;
    var angularAxis = subplot.angularAxis;
    var scene = ScatterGl.sceneUpdate(gd, subplot);

    cdata.forEach(function(cdscatter) {
        if(!cdscatter || !cdscatter[0] || !cdscatter[0].trace) return;
        var cd = cdscatter[0];
        var trace = cd.trace;
        var stash = cd.t;
        var len = trace._length;
        var rArray = stash.r;
        var thetaArray = stash.theta;
        var opts = stash.opts;
        var i;

        var subRArray = rArray.slice();
        var subThetaArray = thetaArray.slice();

        // filter out by range
        for(i = 0; i < rArray.length; i++) {
            if(!subplot.isPtInside({r: rArray[i], theta: thetaArray[i]})) {
                subRArray[i] = NaN;
                subThetaArray[i] = NaN;
            }
        }

        var positions = new Array(len * 2);
        var x = Array(len);
        var y = Array(len);

        for(i = 0; i < len; i++) {
            var r = subRArray[i];
            var xx, yy;

            if(isNumeric(r)) {
                var rg = radialAxis.c2g(r);
                var thetag = angularAxis.c2g(subThetaArray[i], trace.thetaunit);
                xx = rg * Math.cos(thetag);
                yy = rg * Math.sin(thetag);
            } else {
                xx = yy = NaN;
            }
            x[i] = positions[i * 2] = xx;
            y[i] = positions[i * 2 + 1] = yy;
        }

        stash.tree = cluster(positions);

        // FIXME: see scattergl.js#109
        if(opts.marker && len >= TOO_MANY_POINTS) {
            opts.marker.cluster = stash.tree;
        }

        if(opts.marker) {
            opts.markerSel.positions = opts.markerUnsel.positions = opts.marker.positions = positions;
        }

        if(opts.line && positions.length > 1) {
            Lib.extendFlat(
                opts.line,
                convert.linePositions(gd, trace, positions)
            );
        }

        if(opts.text) {
            Lib.extendFlat(
                opts.text,
                {positions: positions},
                convert.textPosition(gd, trace, opts.text, opts.marker)
            );
            Lib.extendFlat(
                opts.textSel,
                {positions: positions},
                convert.textPosition(gd, trace, opts.text, opts.markerSel)
            );
            Lib.extendFlat(
                opts.textUnsel,
                {positions: positions},
                convert.textPosition(gd, trace, opts.text, opts.markerUnsel)
            );
        }

        if(opts.fill && !scene.fill2d) scene.fill2d = true;
        if(opts.marker && !scene.scatter2d) scene.scatter2d = true;
        if(opts.line && !scene.line2d) scene.line2d = true;
        if(opts.text && !scene.glText) scene.glText = true;

        scene.lineOptions.push(opts.line);
        scene.fillOptions.push(opts.fill);
        scene.markerOptions.push(opts.marker);
        scene.markerSelectedOptions.push(opts.markerSel);
        scene.markerUnselectedOptions.push(opts.markerUnsel);
        scene.textOptions.push(opts.text);
        scene.textSelectedOptions.push(opts.textSel);
        scene.textUnselectedOptions.push(opts.textUnsel);

        stash.x = x;
        stash.y = y;
        stash.rawx = x;
        stash.rawy = y;
        stash.r = rArray;
        stash.theta = thetaArray;
        stash.positions = positions;
        stash._scene = scene;
        stash.index = scene.count;
        scene.count++;
    });

    return ScatterGl.plot(gd, subplot, cdata);
}

function hoverPoints(pointData, xval, yval, hovermode) {
    var cd = pointData.cd;
    var stash = cd[0].t;
    var rArray = stash.r;
    var thetaArray = stash.theta;

    var scatterPointData = ScatterGl.hoverPoints(pointData, xval, yval, hovermode);
    if(!scatterPointData || scatterPointData[0].index === false) return;

    var newPointData = scatterPointData[0];

    if(newPointData.index === undefined) {
        return scatterPointData;
    }

    var subplot = pointData.subplot;
    var cdi = newPointData.cd[newPointData.index];
    var trace = newPointData.trace;

    // augment pointData with r/theta param
    cdi.r = rArray[newPointData.index];
    cdi.theta = thetaArray[newPointData.index];

    if(!subplot.isPtInside(cdi)) return;

    newPointData.xLabelVal = undefined;
    newPointData.yLabelVal = undefined;
    makeHoverPointText(cdi, trace, subplot, newPointData);

    return scatterPointData;
}

module.exports = {
    moduleType: 'trace',
    name: 'scatterpolargl',
    basePlotModule: _dereq_('../../plots/polar'),
    categories: ['gl', 'regl', 'polar', 'symbols', 'showLegend', 'scatter-like'],

    attributes: _dereq_('./attributes'),
    supplyDefaults: _dereq_('./defaults'),
    colorbar: _dereq_('../scatter/marker_colorbar'),

    calc: calc,
    plot: plot,
    hoverPoints: hoverPoints,
    selectPoints: ScatterGl.selectPoints,

    meta: {
        
        
    }
};

},{"../../lib":694,"../../plots/cartesian/axes":742,"../../plots/polar":809,"../scatter/calc":1048,"../scatter/colorscale_calc":1050,"../scatter/marker_colorbar":1065,"../scattergl":1100,"../scattergl/constants":1097,"../scattergl/convert":1098,"../scatterpolar/hover":1112,"./attributes":1115,"./defaults":1116,"fast-isnumeric":215,"point-cluster":455}],1118:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
var scatterAttrs = _dereq_('../scatter/attributes');
var plotAttrs = _dereq_('../../plots/attributes');
var colorAttributes = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
var dash = _dereq_('../../components/drawing/attributes').dash;

var extendFlat = _dereq_('../../lib/extend').extendFlat;

var scatterMarkerAttrs = scatterAttrs.marker;
var scatterLineAttrs = scatterAttrs.line;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;

module.exports = {
    a: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    b: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    c: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    sum: {
        valType: 'number',
        
        dflt: 0,
        min: 0,
        editType: 'calc',
        
    },
    mode: extendFlat({}, scatterAttrs.mode, {dflt: 'markers'}),
    text: extendFlat({}, scatterAttrs.text, {
        
    }),
    hovertext: extendFlat({}, scatterAttrs.hovertext, {
        
    }),
    line: {
        color: scatterLineAttrs.color,
        width: scatterLineAttrs.width,
        dash: dash,
        shape: extendFlat({}, scatterLineAttrs.shape,
            {values: ['linear', 'spline']}),
        smoothing: scatterLineAttrs.smoothing,
        editType: 'calc'
    },
    connectgaps: scatterAttrs.connectgaps,
    cliponaxis: scatterAttrs.cliponaxis,
    fill: extendFlat({}, scatterAttrs.fill, {
        values: ['none', 'toself', 'tonext'],
        dflt: 'none',
        
    }),
    fillcolor: scatterAttrs.fillcolor,
    marker: extendFlat({
        symbol: scatterMarkerAttrs.symbol,
        opacity: scatterMarkerAttrs.opacity,
        maxdisplayed: scatterMarkerAttrs.maxdisplayed,
        size: scatterMarkerAttrs.size,
        sizeref: scatterMarkerAttrs.sizeref,
        sizemin: scatterMarkerAttrs.sizemin,
        sizemode: scatterMarkerAttrs.sizemode,
        line: extendFlat({
            width: scatterMarkerLineAttrs.width,
            editType: 'calc'
        },
            colorAttributes('marker.line')
        ),
        gradient: scatterMarkerAttrs.gradient,
        editType: 'calc'
    }, colorAttributes('marker'), {
        colorbar: colorbarAttrs
    }),

    textfont: scatterAttrs.textfont,
    textposition: scatterAttrs.textposition,

    selected: scatterAttrs.selected,
    unselected: scatterAttrs.unselected,

    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
        flags: ['a', 'b', 'c', 'text', 'name']
    }),
    hoveron: scatterAttrs.hoveron,
    hovertemplate: hovertemplateAttrs(),
};

},{"../../components/colorbar/attributes":572,"../../components/colorscale/attributes":578,"../../components/drawing/attributes":591,"../../components/fx/hovertemplate_attributes":609,"../../lib/extend":684,"../../plots/attributes":739,"../scatter/attributes":1047}],1119:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = _dereq_('fast-isnumeric');

var calcColorscale = _dereq_('../scatter/colorscale_calc');
var arraysToCalcdata = _dereq_('../scatter/arrays_to_calcdata');
var calcSelection = _dereq_('../scatter/calc_selection');
var calcMarkerSize = _dereq_('../scatter/calc').calcMarkerSize;

var dataArrays = ['a', 'b', 'c'];
var arraysToFill = {a: ['b', 'c'], b: ['a', 'c'], c: ['a', 'b']};

module.exports = function calc(gd, trace) {
    var ternary = gd._fullLayout[trace.subplot];
    var displaySum = ternary.sum;
    var normSum = trace.sum || displaySum;
    var arrays = {a: trace.a, b: trace.b, c: trace.c};

    var i, j, dataArray, newArray, fillArray1, fillArray2;

    // fill in one missing component
    for(i = 0; i < dataArrays.length; i++) {
        dataArray = dataArrays[i];
        if(arrays[dataArray]) continue;

        fillArray1 = arrays[arraysToFill[dataArray][0]];
        fillArray2 = arrays[arraysToFill[dataArray][1]];
        newArray = new Array(fillArray1.length);
        for(j = 0; j < fillArray1.length; j++) {
            newArray[j] = normSum - fillArray1[j] - fillArray2[j];
        }
        arrays[dataArray] = newArray;
    }

    // make the calcdata array
    var serieslen = trace._length;
    var cd = new Array(serieslen);
    var a, b, c, norm, x, y;
    for(i = 0; i < serieslen; i++) {
        a = arrays.a[i];
        b = arrays.b[i];
        c = arrays.c[i];
        if(isNumeric(a) && isNumeric(b) && isNumeric(c)) {
            a = +a;
            b = +b;
            c = +c;
            norm = displaySum / (a + b + c);
            if(norm !== 1) {
                a *= norm;
                b *= norm;
                c *= norm;
            }
            // map a, b, c onto x and y where the full scale of y
            // is [0, sum], and x is [-sum, sum]
            // TODO: this makes `a` always the top, `b` the bottom left,
            // and `c` the bottom right. Do we want options to rearrange
            // these?
            y = a;
            x = c - b;
            cd[i] = {x: x, y: y, a: a, b: b, c: c};
        }
        else cd[i] = {x: false, y: false};
    }

    calcMarkerSize(trace, serieslen);
    calcColorscale(gd, trace);
    arraysToCalcdata(cd, trace);
    calcSelection(cd, trace);

    return cd;
};

},{"../scatter/arrays_to_calcdata":1046,"../scatter/calc":1048,"../scatter/calc_selection":1049,"../scatter/colorscale_calc":1050,"fast-isnumeric":215}],1120:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = _dereq_('../../lib');

var constants = _dereq_('../scatter/constants');
var subTypes = _dereq_('../scatter/subtypes');
var handleMarkerDefaults = _dereq_('../scatter/marker_defaults');
var handleLineDefaults = _dereq_('../scatter/line_defaults');
var handleLineShapeDefaults = _dereq_('../scatter/line_shape_defaults');
var handleTextDefaults = _dereq_('../scatter/text_defaults');
var handleFillColorDefaults = _dereq_('../scatter/fillcolor_defaults');

var attributes = _dereq_('./attributes');


module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var a = coerce('a');
    var b = coerce('b');
    var c = coerce('c');
    var len;

    // allow any one array to be missing, len is the minimum length of those
    // present. Note that after coerce data_array's are either Arrays (which
    // are truthy even if empty) or undefined. As in scatter, an empty array
    // is different from undefined, because it can signify that this data is
    // not known yet but expected in the future
    if(a) {
        len = a.length;
        if(b) {
            len = Math.min(len, b.length);
            if(c) len = Math.min(len, c.length);
        }
        else if(c) len = Math.min(len, c.length);
        else len = 0;
    }
    else if(b && c) {
        len = Math.min(b.length, c.length);
    }

    if(!len) {
        traceOut.visible = false;
        return;
    }

    traceOut._length = len;

    coerce('sum');

    coerce('text');
    coerce('hovertext');
    if(traceOut.hoveron !== 'fills') coerce('hovertemplate');

    var defaultMode = len < constants.PTS_LINESONLY ? 'lines+markers' : 'lines';
    coerce('mode', defaultMode);

    if(subTypes.hasLines(traceOut)) {
        handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
        handleLineShapeDefaults(traceIn, traceOut, coerce);
        coerce('connectgaps');
    }

    if(subTypes.hasMarkers(traceOut)) {
        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true});
    }

    if(subTypes.hasText(traceOut)) {
        handleTextDefaults(traceIn, traceOut, layout, coerce);
    }

    var dfltHoverOn = [];

    if(subTypes.hasMarkers(traceOut) || subTypes.hasText(traceOut)) {
        coerce('cliponaxis');
        coerce('marker.maxdisplayed');
        dfltHoverOn.push('points');
    }

    coerce('fill');
    if(traceOut.fill !== 'none') {
        handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
        if(!subTypes.hasLines(traceOut)) handleLineShapeDefaults(traceIn, traceOut, coerce);
    }

    if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') {
        dfltHoverOn.push('fills');
    }
    coerce('hoveron', dfltHoverOn.join('+') || 'points');

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};

},{"../../lib":694,"../scatter/constants":1051,"../scatter/fillcolor_defaults":1056,"../scatter/line_defaults":1060,"../scatter/line_shape_defaults":1062,"../scatter/marker_defaults":1066,"../scatter/subtypes":1071,"../scatter/text_defaults":1072,"./attributes":1118}],1121:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function eventData(out, pt, trace, cd, pointNumber) {
    if(pt.xa) out.xaxis = pt.xa;
    if(pt.ya) out.yaxis = pt.ya;

    if(cd[pointNumber]) {
        var cdi = cd[pointNumber];

        // N.B. These are the normalized coordinates.
        out.a = cdi.a;
        out.b = cdi.b;
        out.c = cdi.c;
    } else {
        // for fill-hover only
        out.a = pt.a;
        out.b = pt.b;
        out.c = pt.c;
    }

    return out;
};

},{}],1122:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var scatterHover = _dereq_('../scatter/hover');
var Axes = _dereq_('../../plots/cartesian/axes');


module.exports = function hoverPoints(pointData, xval, yval, hovermode) {
    var scatterPointData = scatterHover(pointData, xval, yval, hovermode);
    if(!scatterPointData || scatterPointData[0].index === false) return;

    var newPointData = scatterPointData[0];

    // if hovering on a fill, we don't show any point data so the label is
    // unchanged from what scatter gives us - except that it needs to
    // be constrained to the trianglular plot area, not just the rectangular
    // area defined by the synthetic x and y axes
    // TODO: in some cases the vertical middle of the shape is not within
    // the triangular viewport at all, so the label can become disconnected
    // from the shape entirely. But calculating what portion of the shape
    // is actually visible, as constrained by the diagonal axis lines, is not
    // so easy and anyway we lost the information we would have needed to do
    // this inside scatterHover.
    if(newPointData.index === undefined) {
        var yFracUp = 1 - (newPointData.y0 / pointData.ya._length);
        var xLen = pointData.xa._length;
        var xMin = xLen * yFracUp / 2;
        var xMax = xLen - xMin;
        newPointData.x0 = Math.max(Math.min(newPointData.x0, xMax), xMin);
        newPointData.x1 = Math.max(Math.min(newPointData.x1, xMax), xMin);
        return scatterPointData;
    }

    var cdi = newPointData.cd[newPointData.index];

    newPointData.a = cdi.a;
    newPointData.b = cdi.b;
    newPointData.c = cdi.c;

    newPointData.xLabelVal = undefined;
    newPointData.yLabelVal = undefined;
    // TODO: nice formatting, and label by axis title, for a, b, and c?

    var trace = newPointData.trace;
    var ternary = newPointData.subplot;
    var hoverinfo = cdi.hi || trace.hoverinfo;
    var text = [];
    function textPart(ax, val) {
        text.push(ax._hovertitle + ': ' + Axes.tickText(ax, val, 'hover').text);
    }
    if(!trace.hovertemplate) {
        var parts = hoverinfo.split('+');
        if(parts.indexOf('all') !== -1) parts = ['a', 'b', 'c'];
        if(parts.indexOf('a') !== -1) textPart(ternary.aaxis, cdi.a);
        if(parts.indexOf('b') !== -1) textPart(ternary.baxis, cdi.b);
        if(parts.indexOf('c') !== -1) textPart(ternary.caxis, cdi.c);
    }
    newPointData.extraText = text.join('<br>');
    newPointData.hovertemplate = trace.hovertemplate;
    return scatterPointData;
};

},{"../../plots/cartesian/axes":742,"../scatter/hover":1058}],1123:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var ScatterTernary = {};

ScatterTernary.attributes = _dereq_('./attributes');
ScatterTernary.supplyDefaults = _dereq_('./defaults');
ScatterTernary.colorbar = _dereq_('../scatter/marker_colorbar');
ScatterTernary.calc = _dereq_('./calc');
ScatterTernary.plot = _dereq_('./plot');
ScatterTernary.style = _dereq_('../scatter/style').style;
ScatterTernary.styleOnSelect = _dereq_('../scatter/style').styleOnSelect;
ScatterTernary.hoverPoints = _dereq_('./hover');
ScatterTernary.selectPoints = _dereq_('../scatter/select');
ScatterTernary.eventData = _dereq_('./event_data');

ScatterTernary.moduleType = 'trace';
ScatterTernary.name = 'scatterternary';
ScatterTernary.basePlotModule = _dereq_('../../plots/ternary');
ScatterTernary.categories = ['ternary', 'symbols', 'showLegend', 'scatter-like'];
ScatterTernary.meta = {
    
    
};

module.exports = ScatterTernary;

},{"../../plots/ternary":821,"../scatter/marker_colorbar":1065,"../scatter/select":1068,"../scatter/style":1070,"./attributes":1118,"./calc":1119,"./defaults":1120,"./event_data":1121,"./hover":1122,"./plot":1124}],1124:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var scatterPlot = _dereq_('../scatter/plot');

module.exports = function plot(gd, ternary, moduleCalcData) {
    var plotContainer = ternary.plotContainer;

    // remove all nodes inside the scatter layer
    plotContainer.select('.scatterlayer').selectAll('*').remove();

    // mimic cartesian plotinfo
    var plotinfo = {
        xaxis: ternary.xaxis,
        yaxis: ternary.yaxis,
        plot: plotContainer,
        layerClipId: ternary._hasClipOnAxisFalse ? ternary.clipIdRelative : null
    };

    var scatterLayer = ternary.layers.frontplot.select('g.scatterlayer');

    scatterPlot(gd, plotinfo, moduleCalcData, scatterLayer);
};

},{"../scatter/plot":1067}],1125:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterAttrs = _dereq_('../scatter/attributes');
var colorAttrs = _dereq_('../../components/colorscale/attributes');
var scatterGlAttrs = _dereq_('../scattergl/attributes');
var cartesianIdRegex = _dereq_('../../plots/cartesian/constants').idRegex;
var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;
var extendFlat = _dereq_('../../lib/extend').extendFlat;

var scatterMarkerAttrs = scatterAttrs.marker;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;

var markerLineAttrs = extendFlat(colorAttrs('marker.line', {editTypeOverride: 'calc'}), {
    width: extendFlat({}, scatterMarkerLineAttrs.width, {editType: 'calc'}),
    editType: 'calc'
});

var markerAttrs = extendFlat(colorAttrs('marker'), {
    symbol: scatterMarkerAttrs.symbol,
    size: extendFlat({}, scatterMarkerAttrs.size, {editType: 'markerSize'}),
    sizeref: scatterMarkerAttrs.sizeref,
    sizemin: scatterMarkerAttrs.sizemin,
    sizemode: scatterMarkerAttrs.sizemode,
    opacity: scatterMarkerAttrs.opacity,
    colorbar: scatterMarkerAttrs.colorbar,
    line: markerLineAttrs,
    editType: 'calc'
});

markerAttrs.color.editType = markerAttrs.cmin.editType = markerAttrs.cmax.editType = 'style';

function makeAxesValObject(axLetter) {
    return {
        valType: 'info_array',
        freeLength: true,
        
        editType: 'calc',
        items: {
            valType: 'subplotid',
            regex: cartesianIdRegex[axLetter],
            editType: 'plot'
        },
        
    };
}

module.exports = {
    dimensions: templatedArray('dimension', {
        visible: {
            valType: 'boolean',
            
            dflt: true,
            editType: 'calc',
            
        },
        label: {
            valType: 'string',
            
            editType: 'calc',
            
        },
        values: {
            valType: 'data_array',
            
            editType: 'calc+clearAxisTypes',
            
        },

        axis: {
            type: {
                valType: 'enumerated',
                values: ['linear', 'log', 'date', 'category'],
                
                editType: 'calc+clearAxisTypes',
                
            },

            editType: 'calc+clearAxisTypes'
        },

        // TODO should add an attribute to pin down x only vars and y only vars
        // like https://seaborn.pydata.org/generated/seaborn.pairplot.html
        // x_vars and y_vars

        // maybe more axis defaulting option e.g. `showgrid: false`

        editType: 'calc+clearAxisTypes'
    }),

    // mode: {}, (only 'markers' for now)

    text: extendFlat({}, scatterGlAttrs.text, {
        
    }),

    marker: markerAttrs,

    xaxes: makeAxesValObject('x'),
    yaxes: makeAxesValObject('y'),

    diagonal: {
        visible: {
            valType: 'boolean',
            
            dflt: true,
            editType: 'calc',
            
        },

        // type: 'scattergl' | 'histogram' | 'box' | 'violin'
        // ...
        // more options

        editType: 'calc'
    },

    showupperhalf: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'calc',
        
    },
    showlowerhalf: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'calc',
        
    },

    selected: {
        marker: scatterGlAttrs.selected.marker,
        editType: 'calc'
    },
    unselected: {
        marker: scatterGlAttrs.unselected.marker,
        editType: 'calc'
    },

    opacity: scatterGlAttrs.opacity
};

},{"../../components/colorscale/attributes":578,"../../lib/extend":684,"../../plot_api/plot_template":732,"../../plots/cartesian/constants":748,"../scatter/attributes":1047,"../scattergl/attributes":1096}],1126:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var createLine = _dereq_('regl-line2d');

var Registry = _dereq_('../../registry');
var prepareRegl = _dereq_('../../lib/prepare_regl');
var getModuleCalcData = _dereq_('../../plots/get_data').getModuleCalcData;
var Cartesian = _dereq_('../../plots/cartesian');
var getFromId = _dereq_('../../plots/cartesian/axis_ids').getFromId;
var shouldShowZeroLine = _dereq_('../../plots/cartesian/axes').shouldShowZeroLine;

var SPLOM = 'splom';

function plot(gd) {
    var fullLayout = gd._fullLayout;
    var _module = Registry.getModule(SPLOM);
    var splomCalcData = getModuleCalcData(gd.calcdata, _module)[0];

    var success = prepareRegl(gd, ['ANGLE_instanced_arrays', 'OES_element_index_uint']);
    if(!success) return;

    if(fullLayout._hasOnlyLargeSploms) {
        updateGrid(gd);
    }

    _module.plot(gd, {}, splomCalcData);
}

function drag(gd) {
    var cd = gd.calcdata;
    var fullLayout = gd._fullLayout;

    if(fullLayout._hasOnlyLargeSploms) {
        updateGrid(gd);
    }

    for(var i = 0; i < cd.length; i++) {
        var cd0 = cd[i][0];
        var trace = cd0.trace;
        var scene = fullLayout._splomScenes[trace.uid];

        if(trace.type === 'splom' && scene && scene.matrix) {
            dragOne(gd, trace, scene);
        }
    }
}

function dragOne(gd, trace, scene) {
    var visibleLength = scene.matrixOptions.data.length;
    var visibleDims = trace._visibleDims;
    var ranges = scene.viewOpts.ranges = new Array(visibleLength);

    for(var k = 0; k < visibleDims.length; k++) {
        var i = visibleDims[k];
        var rng = ranges[k] = new Array(4);

        var xa = getFromId(gd, trace._diag[i][0]);
        if(xa) {
            rng[0] = xa.r2l(xa.range[0]);
            rng[2] = xa.r2l(xa.range[1]);
        }

        var ya = getFromId(gd, trace._diag[i][1]);
        if(ya) {
            rng[1] = ya.r2l(ya.range[0]);
            rng[3] = ya.r2l(ya.range[1]);
        }
    }

    if(scene.selectBatch) {
        scene.matrix.update({ranges: ranges}, {ranges: ranges});
    } else {
        scene.matrix.update({ranges: ranges});
    }
}

function updateGrid(gd) {
    var fullLayout = gd._fullLayout;
    var regl = fullLayout._glcanvas.data()[0].regl;
    var splomGrid = fullLayout._splomGrid;

    if(!splomGrid) {
        splomGrid = fullLayout._splomGrid = createLine(regl);
    }
    splomGrid.update(makeGridData(gd));
}

function makeGridData(gd) {
    var fullLayout = gd._fullLayout;
    var gs = fullLayout._size;
    var fullView = [0, 0, fullLayout.width, fullLayout.height];
    var lookup = {};
    var k;

    function push(prefix, ax, x0, x1, y0, y1) {
        var lcolor = ax[prefix + 'color'];
        var lwidth = ax[prefix + 'width'];
        var key = String(lcolor + lwidth);

        if(key in lookup) {
            lookup[key].data.push(NaN, NaN, x0, x1, y0, y1);
        } else {
            lookup[key] = {
                data: [x0, x1, y0, y1],
                join: 'rect',
                thickness: lwidth,
                color: lcolor,
                viewport: fullView,
                range: fullView,
                overlay: false
            };
        }
    }

    for(k in fullLayout._splomSubplots) {
        var sp = fullLayout._plots[k];
        var xa = sp.xaxis;
        var ya = sp.yaxis;
        var xVals = xa._vals;
        var yVals = ya._vals;
        // ya.l2p assumes top-to-bottom coordinate system (a la SVG),
        // we need to compute bottom-to-top offsets and slopes:
        var yOffset = gs.b + ya.domain[0] * gs.h;
        var ym = -ya._m;
        var yb = -ym * ya.r2l(ya.range[0], ya.calendar);
        var x, y;

        if(xa.showgrid) {
            for(k = 0; k < xVals.length; k++) {
                x = xa._offset + xa.l2p(xVals[k].x);
                push('grid', xa, x, yOffset, x, yOffset + ya._length);
            }
        }
        if(ya.showgrid) {
            for(k = 0; k < yVals.length; k++) {
                y = yOffset + yb + ym * yVals[k].x;
                push('grid', ya, xa._offset, y, xa._offset + xa._length, y);
            }
        }
        if(shouldShowZeroLine(gd, xa, ya)) {
            x = xa._offset + xa.l2p(0);
            push('zeroline', xa, x, yOffset, x, yOffset + ya._length);
        }
        if(shouldShowZeroLine(gd, ya, xa)) {
            y = yOffset + yb + 0;
            push('zeroline', ya, xa._offset, y, xa._offset + xa._length, y);
        }
    }

    var gridBatches = [];
    for(k in lookup) {
        gridBatches.push(lookup[k]);
    }

    return gridBatches;
}

function clean(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var lookup = {};
    var i;

    if(oldFullLayout._splomScenes) {
        for(i = 0; i < newFullData.length; i++) {
            var newTrace = newFullData[i];
            if(newTrace.type === 'splom') {
                lookup[newTrace.uid] = 1;
            }
        }
        for(i = 0; i < oldFullData.length; i++) {
            var oldTrace = oldFullData[i];
            if(!lookup[oldTrace.uid]) {
                var scene = oldFullLayout._splomScenes[oldTrace.uid];
                if(scene && scene.destroy) scene.destroy();
                // must first set scene to null in order to get garbage collected
                oldFullLayout._splomScenes[oldTrace.uid] = null;
                delete oldFullLayout._splomScenes[oldTrace.uid];
            }
        }
    }

    if(Object.keys(oldFullLayout._splomScenes || {}).length === 0) {
        delete oldFullLayout._splomScenes;
    }

    if(oldFullLayout._splomGrid &&
        (!newFullLayout._hasOnlyLargeSploms && oldFullLayout._hasOnlyLargeSploms)) {
        // must first set scene to null in order to get garbage collected
        oldFullLayout._splomGrid.destroy();
        oldFullLayout._splomGrid = null;
        delete oldFullLayout._splomGrid;
    }

    Cartesian.clean(newFullData, newFullLayout, oldFullData, oldFullLayout);
}

function updateFx(gd) {
    Cartesian.updateFx(gd);

    var fullLayout = gd._fullLayout;
    var dragmode = fullLayout.dragmode;

    // unset selection styles when coming out of a selection mode
    if(dragmode === 'zoom' || dragmode === 'pan') {
        var cd = gd.calcdata;

        for(var i = 0; i < cd.length; i++) {
            var cd0 = cd[i][0];
            var trace = cd0.trace;

            if(trace.type === 'splom') {
                var scene = fullLayout._splomScenes[trace.uid];
                if(scene.selectBatch === null) {
                    scene.matrix.update(scene.matrixOptions, null);
                }
            }
        }
    }
}

module.exports = {
    name: SPLOM,
    attr: Cartesian.attr,
    attrRegex: Cartesian.attrRegex,
    layoutAttributes: Cartesian.layoutAttributes,
    supplyLayoutDefaults: Cartesian.supplyLayoutDefaults,
    drawFramework: Cartesian.drawFramework,
    plot: plot,
    drag: drag,
    updateGrid: updateGrid,
    clean: clean,
    updateFx: updateFx,
    toSVG: Cartesian.toSVG
};

},{"../../lib/prepare_regl":707,"../../plots/cartesian":754,"../../plots/cartesian/axes":742,"../../plots/cartesian/axis_ids":745,"../../plots/get_data":779,"../../registry":825,"regl-line2d":477}],1127:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');

var attributes = _dereq_('./attributes');
var subTypes = _dereq_('../scatter/subtypes');
var handleMarkerDefaults = _dereq_('../scatter/marker_defaults');
var mergeLength = _dereq_('../parcoords/merge_length');
var OPEN_RE = /-open/;

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var dimensions = handleArrayContainerDefaults(traceIn, traceOut, {
        name: 'dimensions',
        handleItemDefaults: dimensionDefaults
    });

    var showDiag = coerce('diagonal.visible');
    var showUpper = coerce('showupperhalf');
    var showLower = coerce('showlowerhalf');

    var dimLength = mergeLength(traceOut, dimensions, 'values');

    if(!dimLength || (!showDiag && !showUpper && !showLower)) {
        traceOut.visible = false;
        return;
    }

    coerce('text');

    handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce);

    var isOpen = OPEN_RE.test(traceOut.marker.symbol);
    var isBubble = subTypes.isBubble(traceOut);
    coerce('marker.line.width', isOpen || isBubble ? 1 : 0);

    handleAxisDefaults(traceIn, traceOut, layout, coerce);

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};

function dimensionDefaults(dimIn, dimOut) {
    function coerce(attr, dflt) {
        return Lib.coerce(dimIn, dimOut, attributes.dimensions, attr, dflt);
    }

    coerce('label');
    var values = coerce('values');

    if(!(values && values.length)) dimOut.visible = false;
    else coerce('visible');

    coerce('axis.type');
}

function handleAxisDefaults(traceIn, traceOut, layout, coerce) {
    var dimensions = traceOut.dimensions;
    var dimLength = dimensions.length;
    var showUpper = traceOut.showupperhalf;
    var showLower = traceOut.showlowerhalf;
    var showDiag = traceOut.diagonal.visible;
    var i, j;

    var xAxesDflt = new Array(dimLength);
    var yAxesDflt = new Array(dimLength);

    for(i = 0; i < dimLength; i++) {
        var suffix = i ? i + 1 : '';
        xAxesDflt[i] = 'x' + suffix;
        yAxesDflt[i] = 'y' + suffix;
    }

    var xaxes = coerce('xaxes', xAxesDflt);
    var yaxes = coerce('yaxes', yAxesDflt);

    // build list of [x,y] axis corresponding to each dimensions[i],
    // very useful for passing options to regl-splom
    var diag = traceOut._diag = new Array(dimLength);

    // lookup for 'drawn' x|y axes, to avoid costly indexOf downstream
    traceOut._xaxes = {};
    traceOut._yaxes = {};

    // list of 'drawn' x|y axes, use to generate list of subplots
    var xList = [];
    var yList = [];

    function fillAxisStashes(axId, dim, list) {
        if(!axId) return;

        var axLetter = axId.charAt(0);
        var stash = layout._splomAxes[axLetter];

        traceOut['_' + axLetter + 'axes'][axId] = 1;
        list.push(axId);

        if(!(axId in stash)) {
            var s = stash[axId] = {};
            if(dim) {
                s.label = dim.label || '';
                if(dim.visible && dim.axis) {
                    s.type = dim.axis.type;
                }
            }
        }
    }

    // cases where showDiag and showLower or showUpper are false
    // no special treatment as the 'drawn' x-axes and y-axes no longer match
    // the dimensions items and xaxes|yaxes 1-to-1
    var mustShiftX = !showDiag && !showLower;
    var mustShiftY = !showDiag && !showUpper;

    for(i = 0; i < dimLength; i++) {
        var dim = dimensions[i];
        var i0 = i === 0;
        var iN = i === dimLength - 1;

        var xaId = (i0 && mustShiftX) || (iN && mustShiftY) ?
            undefined :
            xaxes[i];

        var yaId = (i0 && mustShiftY) || (iN && mustShiftX) ?
            undefined :
            yaxes[i];

        fillAxisStashes(xaId, dim, xList);
        fillAxisStashes(yaId, dim, yList);
        diag[i] = [xaId, yaId];
    }

    // fill in splom subplot keys
    for(i = 0; i < xList.length; i++) {
        for(j = 0; j < yList.length; j++) {
            var id = xList[i] + yList[j];

            if(i > j && showUpper) {
                layout._splomSubplots[id] = 1;
            } else if(i < j && showLower) {
                layout._splomSubplots[id] = 1;
            } else if(i === j && (showDiag || !showLower || !showUpper)) {
                // need to include diagonal subplots when
                // hiding one half and the diagonal
                layout._splomSubplots[id] = 1;
            }
        }
    }

    // when lower half is omitted, or when just the diagonal is gone,
    // override grid default to make sure axes remain on
    // the left/bottom of the plot area
    if(!showLower || (!showDiag && showUpper && showLower)) {
        layout._splomGridDflt.xside = 'bottom';
        layout._splomGridDflt.yside = 'left';
    }
}

},{"../../lib":694,"../../plots/array_container_defaults":738,"../parcoords/merge_length":1019,"../scatter/marker_defaults":1066,"../scatter/subtypes":1071,"./attributes":1125}],1128:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var createMatrix = _dereq_('regl-splom');
var arrayRange = _dereq_('array-range');

var Registry = _dereq_('../../registry');
var Grid = _dereq_('../../components/grid');
var Lib = _dereq_('../../lib');
var AxisIDs = _dereq_('../../plots/cartesian/axis_ids');

var subTypes = _dereq_('../scatter/subtypes');
var calcMarkerSize = _dereq_('../scatter/calc').calcMarkerSize;
var calcAxisExpansion = _dereq_('../scatter/calc').calcAxisExpansion;
var calcColorscale = _dereq_('../scatter/colorscale_calc');
var convertMarkerSelection = _dereq_('../scattergl/convert').markerSelection;
var convertMarkerStyle = _dereq_('../scattergl/convert').markerStyle;
var calcHover = _dereq_('../scattergl').calcHover;

var BADNUM = _dereq_('../../constants/numerical').BADNUM;
var TOO_MANY_POINTS = _dereq_('../scattergl/constants').TOO_MANY_POINTS;

function calc(gd, trace) {
    var dimensions = trace.dimensions;
    var commonLength = trace._length;
    var opts = {};
    // 'c' for calculated, 'l' for linear,
    // only differ here for log axes, pass ldata to createMatrix as 'data'
    var cdata = opts.cdata = [];
    var ldata = opts.data = [];
    // keep track of visible dimensions
    var visibleDims = trace._visibleDims = [];
    var i, k, dim, xa, ya;

    function makeCalcdata(ax, dim) {
        // call makeCalcdata with fake input
        var ccol = ax.makeCalcdata({
            v: dim.values,
            vcalendar: trace.calendar
        }, 'v');

        for(var j = 0; j < ccol.length; j++) {
            ccol[j] = ccol[j] === BADNUM ? NaN : ccol[j];
        }
        cdata.push(ccol);
        ldata.push(ax.type === 'log' ? Lib.simpleMap(ccol, ax.c2l) : ccol);
    }

    for(i = 0; i < dimensions.length; i++) {
        dim = dimensions[i];

        if(dim.visible) {
            xa = AxisIDs.getFromId(gd, trace._diag[i][0]);
            ya = AxisIDs.getFromId(gd, trace._diag[i][1]);

            // if corresponding x & y axes don't have matching types, skip dim
            if(xa && ya && xa.type !== ya.type) {
                Lib.log('Skipping splom dimension ' + i + ' with conflicting axis types');
                continue;
            }

            if(xa) {
                makeCalcdata(xa, dim);
                if(ya && ya.type === 'category') {
                    ya._categories = xa._categories.slice();
                }
            } else {
                // should not make it here, if both xa and ya undefined
                makeCalcdata(ya, dim);
            }

            visibleDims.push(i);
        }
    }

    calcColorscale(gd, trace);
    Lib.extendFlat(opts, convertMarkerStyle(trace));

    var visibleLength = cdata.length;
    var hasTooManyPoints = (visibleLength * commonLength) > TOO_MANY_POINTS;

    // Reuse SVG scatter axis expansion routine.
    // For graphs with very large number of points and array marker.size,
    // use average marker size instead to speed things up.
    var ppad;
    if(hasTooManyPoints) {
        ppad = 2 * (opts.sizeAvg || Math.max(opts.size, 3));
    } else {
        ppad = calcMarkerSize(trace, commonLength);
    }

    for(k = 0; k < visibleDims.length; k++) {
        i = visibleDims[k];
        dim = dimensions[i];
        xa = AxisIDs.getFromId(gd, trace._diag[i][0]) || {};
        ya = AxisIDs.getFromId(gd, trace._diag[i][1]) || {};
        calcAxisExpansion(gd, trace, xa, ya, cdata[k], cdata[k], ppad);
    }

    var scene = sceneUpdate(gd, trace);
    if(!scene.matrix) scene.matrix = true;
    scene.matrixOptions = opts;

    scene.selectedOptions = convertMarkerSelection(trace, trace.selected);
    scene.unselectedOptions = convertMarkerSelection(trace, trace.unselected);

    return [{x: false, y: false, t: {}, trace: trace}];
}

function sceneUpdate(gd, trace) {
    var fullLayout = gd._fullLayout;
    var uid = trace.uid;

    // must place ref to 'scene' in fullLayout, so that:
    // - it can be relinked properly on updates
    // - it can be destroyed properly when needed
    var splomScenes = fullLayout._splomScenes;
    if(!splomScenes) splomScenes = fullLayout._splomScenes = {};

    var reset = {dirty: true};

    var first = {
        selectBatch: null,
        unselectBatch: null,
        matrix: false,
        select: null
    };

    var scene = splomScenes[trace.uid];

    if(!scene) {
        scene = splomScenes[uid] = Lib.extendFlat({}, reset, first);

        scene.draw = function draw() {
            if(scene.matrix && scene.matrix.draw) {
                if(scene.selectBatch) {
                    scene.matrix.draw(scene.unselectBatch, scene.selectBatch);
                } else {
                    scene.matrix.draw();
                }
            }

            scene.dirty = false;
        };

        // remove scene resources
        scene.destroy = function destroy() {
            if(scene.matrix && scene.matrix.destroy) {
                scene.matrix.destroy();
            }
            scene.matrixOptions = null;
            scene.selectBatch = null;
            scene.unselectBatch = null;
            scene = null;
        };
    }

    // In case if we have scene from the last calc - reset data
    if(!scene.dirty) {
        Lib.extendFlat(scene, reset);
    }

    return scene;
}

function plot(gd, _, splomCalcData) {
    if(!splomCalcData.length) return;

    for(var i = 0; i < splomCalcData.length; i++) {
        plotOne(gd, splomCalcData[i][0]);
    }
}

function plotOne(gd, cd0) {
    var fullLayout = gd._fullLayout;
    var gs = fullLayout._size;
    var trace = cd0.trace;
    var stash = cd0.t;
    var scene = fullLayout._splomScenes[trace.uid];
    var matrixOpts = scene.matrixOptions;
    var cdata = matrixOpts.cdata;
    var regl = fullLayout._glcanvas.data()[0].regl;
    var dragmode = fullLayout.dragmode;
    var xa, ya;
    var i, j, k;

    if(cdata.length === 0) return;

    // augment options with proper upper/lower halves
    // regl-splom's default grid starts from bottom-left
    matrixOpts.lower = trace.showupperhalf;
    matrixOpts.upper = trace.showlowerhalf;
    matrixOpts.diagonal = trace.diagonal.visible;

    var visibleDims = trace._visibleDims;
    var visibleLength = cdata.length;
    var viewOpts = scene.viewOpts = {};
    viewOpts.ranges = new Array(visibleLength);
    viewOpts.domains = new Array(visibleLength);

    for(k = 0; k < visibleDims.length; k++) {
        i = visibleDims[k];

        var rng = viewOpts.ranges[k] = new Array(4);
        var dmn = viewOpts.domains[k] = new Array(4);

        xa = AxisIDs.getFromId(gd, trace._diag[i][0]);
        if(xa) {
            rng[0] = xa._rl[0];
            rng[2] = xa._rl[1];
            dmn[0] = xa.domain[0];
            dmn[2] = xa.domain[1];
        }

        ya = AxisIDs.getFromId(gd, trace._diag[i][1]);
        if(ya) {
            rng[1] = ya._rl[0];
            rng[3] = ya._rl[1];
            dmn[1] = ya.domain[0];
            dmn[3] = ya.domain[1];
        }
    }

    viewOpts.viewport = [gs.l, gs.b, gs.w + gs.l, gs.h + gs.b];

    if(scene.matrix === true) {
        scene.matrix = createMatrix(regl);
    }

    var clickSelectEnabled = fullLayout.clickmode.indexOf('select') > -1;
    var selectMode = dragmode === 'lasso' || dragmode === 'select' ||
      !!trace.selectedpoints || clickSelectEnabled;
    scene.selectBatch = null;
    scene.unselectBatch = null;

    if(selectMode) {
        var commonLength = trace._length;

        if(!scene.selectBatch) {
            scene.selectBatch = [];
            scene.unselectBatch = [];
        }

        // regenerate scene batch, if traces number changed during selection
        if(trace.selectedpoints) {
            scene.selectBatch = trace.selectedpoints;

            var selPts = trace.selectedpoints;
            var selDict = {};
            for(i = 0; i < selPts.length; i++) {
                selDict[selPts[i]] = true;
            }
            var unselPts = [];
            for(i = 0; i < commonLength; i++) {
                if(!selDict[i]) unselPts.push(i);
            }
            scene.unselectBatch = unselPts;
        }

        // precalculate px coords since we are not going to pan during select
        var xpx = stash.xpx = new Array(visibleLength);
        var ypx = stash.ypx = new Array(visibleLength);

        for(k = 0; k < visibleDims.length; k++) {
            i = visibleDims[k];

            xa = AxisIDs.getFromId(gd, trace._diag[i][0]);
            if(xa) {
                xpx[k] = new Array(commonLength);
                for(j = 0; j < commonLength; j++) {
                    xpx[k][j] = xa.c2p(cdata[k][j]);
                }
            }

            ya = AxisIDs.getFromId(gd, trace._diag[i][1]);
            if(ya) {
                ypx[k] = new Array(commonLength);
                for(j = 0; j < commonLength; j++) {
                    ypx[k][j] = ya.c2p(cdata[k][j]);
                }
            }
        }

        if(scene.selectBatch) {
            scene.matrix.update(matrixOpts, matrixOpts);
            scene.matrix.update(scene.unselectedOptions, scene.selectedOptions);
            scene.matrix.update(viewOpts, viewOpts);
        }
        else {
            // delete selection pass
            scene.matrix.update(viewOpts, null);
        }
    }
    else {
        var opts = Lib.extendFlat({}, matrixOpts, viewOpts);
        scene.matrix.update(opts, null);
        stash.xpx = stash.ypx = null;
    }
}

function editStyle(gd, cd0) {
    var trace = cd0.trace;
    var scene = gd._fullLayout._splomScenes[trace.uid];

    if(scene) {
        calcColorscale(gd, trace);

        Lib.extendFlat(scene.matrixOptions, convertMarkerStyle(trace));
        // TODO [un]selected styles?

        var opts = Lib.extendFlat({}, scene.matrixOptions, scene.viewOpts);

        // TODO this is too long for arrayOk attributes!
        scene.matrix.update(opts, null);
    }
}

function hoverPoints(pointData, xval, yval) {
    var cd = pointData.cd;
    var trace = cd[0].trace;
    var scene = pointData.scene;
    var cdata = scene.matrixOptions.cdata;
    var xa = pointData.xa;
    var ya = pointData.ya;
    var xpx = xa.c2p(xval);
    var ypx = ya.c2p(yval);
    var maxDistance = pointData.distance;

    var xi = getDimIndex(trace, xa);
    var yi = getDimIndex(trace, ya);
    if(xi === false || yi === false) return [pointData];

    var x = cdata[xi];
    var y = cdata[yi];

    var id, dxy;
    var minDist = maxDistance;

    for(var i = 0; i < x.length; i++) {
        var ptx = x[i];
        var pty = y[i];
        var dx = xa.c2p(ptx) - xpx;
        var dy = ya.c2p(pty) - ypx;
        var dist = Math.sqrt(dx * dx + dy * dy);

        if(dist < minDist) {
            minDist = dxy = dist;
            id = i;
        }
    }

    pointData.index = id;
    pointData.distance = minDist;
    pointData.dxy = dxy;

    if(id === undefined) return [pointData];

    calcHover(pointData, x, y, trace);

    return [pointData];
}

function selectPoints(searchInfo, selectionTester) {
    var cd = searchInfo.cd;
    var trace = cd[0].trace;
    var stash = cd[0].t;
    var scene = searchInfo.scene;
    var cdata = scene.matrixOptions.cdata;
    var xa = searchInfo.xaxis;
    var ya = searchInfo.yaxis;
    var selection = [];
    var i;

    if(!scene) return selection;

    var hasOnlyLines = (!subTypes.hasMarkers(trace) && !subTypes.hasText(trace));
    if(trace.visible !== true || hasOnlyLines) return selection;

    var xi = getDimIndex(trace, xa);
    var yi = getDimIndex(trace, ya);
    if(xi === false || yi === false) return selection;

    var xpx = stash.xpx[xi];
    var ypx = stash.ypx[yi];
    var x = cdata[xi];
    var y = cdata[yi];

    // degenerate polygon does not enable selection
    // filter out points by visible scatter ones
    var els = null;
    var unels = null;
    if(selectionTester !== false && !selectionTester.degenerate) {
        els = [], unels = [];
        for(i = 0; i < x.length; i++) {
            if(selectionTester.contains([xpx[i], ypx[i]], null, i, searchInfo)) {
                els.push(i);
                selection.push({
                    pointNumber: i,
                    x: x[i],
                    y: y[i]
                });
            }
            else {
                unels.push(i);
            }
        }
    } else {
        unels = arrayRange(stash.count);
    }

    // make sure selectBatch is created
    if(!scene.selectBatch) {
        scene.selectBatch = [];
        scene.unselectBatch = [];
    }

    if(!scene.selectBatch) {
        // enter every trace select mode
        for(i = 0; i < scene.count; i++) {
            scene.selectBatch = [];
            scene.unselectBatch = [];
        }
        // we should turn scatter2d into unselected once we have any points selected
        scene.matrix.update(scene.unselectedOptions, scene.selectedOptions);
    }

    scene.selectBatch = els;
    scene.unselectBatch = unels;


    return selection;
}

function getDimIndex(trace, ax) {
    var axId = ax._id;
    var axLetter = axId.charAt(0);
    var ind = {x: 0, y: 1}[axLetter];
    var visibleDims = trace._visibleDims;

    for(var k = 0; k < visibleDims.length; k++) {
        var i = visibleDims[k];
        if(trace._diag[i][ind] === axId) return k;
    }
    return false;
}

module.exports = {
    moduleType: 'trace',
    name: 'splom',

    basePlotModule: _dereq_('./base_plot'),
    categories: ['gl', 'regl', 'cartesian', 'symbols', 'showLegend', 'scatter-like'],

    attributes: _dereq_('./attributes'),
    supplyDefaults: _dereq_('./defaults'),
    colorbar: _dereq_('../scatter/marker_colorbar'),

    calc: calc,
    plot: plot,
    hoverPoints: hoverPoints,
    selectPoints: selectPoints,
    editStyle: editStyle,

    meta: {
        
    }
};

// splom traces use the 'grid' component to generate their axes,
// register it here
Registry.register(Grid);

},{"../../components/grid":614,"../../constants/numerical":671,"../../lib":694,"../../plots/cartesian/axis_ids":745,"../../registry":825,"../scatter/calc":1048,"../scatter/colorscale_calc":1050,"../scatter/marker_colorbar":1065,"../scatter/subtypes":1071,"../scattergl":1100,"../scattergl/constants":1097,"../scattergl/convert":1098,"./attributes":1125,"./base_plot":1126,"./defaults":1127,"array-range":56,"regl-splom":479}],1129:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
var mesh3dAttrs = _dereq_('../mesh3d/attributes');
var baseAttrs = _dereq_('../../plots/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;

var attrs = {
    x: {
        valType: 'data_array',
        
        editType: 'calc+clearAxisTypes',
        
    },
    y: {
        valType: 'data_array',
        
        editType: 'calc+clearAxisTypes',
        
    },
    z: {
        valType: 'data_array',
        
        editType: 'calc+clearAxisTypes',
        
    },

    u: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    v: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    w: {
        valType: 'data_array',
        editType: 'calc',
        
    },

    starts: {
        x: {
            valType: 'data_array',
            editType: 'calc',
            
        },
        y: {
            valType: 'data_array',
            editType: 'calc',
            
        },
        z: {
            valType: 'data_array',
            editType: 'calc',
            
        },
        editType: 'calc'
    },

    maxdisplayed: {
        valType: 'integer',
        min: 0,
        dflt: 1000,
        
        editType: 'calc',
        
    },

    // TODO
    //
    // Should add 'absolute' (like cone traces have), but currently gl-streamtube3d's
    // `absoluteTubeSize` doesn't behave well enough for our needs.
    //
    // 'fixed' would be a nice addition to plot stream 'lines', see
    // https://github.com/plotly/plotly.js/commit/812be20750e21e0a1831975001c248d365850f73#r29129877
    //
    // sizemode: {
    //     valType: 'enumerated',
    //     values: ['scaled', 'absolute', 'fixed'],
    //     dflt: 'scaled',
    //     
    //     editType: 'calc',
    //     
    // },

    sizeref: {
        valType: 'number',
        
        editType: 'calc',
        min: 0,
        dflt: 1,
        
    },

    text: {
        valType: 'string',
        
        dflt: '',
        editType: 'calc',
        
    }
};

extendFlat(attrs, colorscaleAttrs('', {
    colorAttr: 'u/v/w norm',
    showScaleDflt: true,
    editTypeOverride: 'calc'
}), {
    colorbar: colorbarAttrs
});

var fromMesh3d = ['opacity', 'lightposition', 'lighting'];
fromMesh3d.forEach(function(k) {
    attrs[k] = mesh3dAttrs[k];
});

attrs.hoverinfo = extendFlat({}, baseAttrs.hoverinfo, {
    editType: 'calc',
    flags: ['x', 'y', 'z', 'u', 'v', 'w', 'norm', 'divergence', 'text', 'name'],
    dflt: 'x+y+z+norm+text+name'
});

attrs.transforms = undefined;

module.exports = attrs;

},{"../../components/colorbar/attributes":572,"../../components/colorscale/attributes":578,"../../lib/extend":684,"../../plots/attributes":739,"../mesh3d/attributes":990}],1130:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorscaleCalc = _dereq_('../../components/colorscale/calc');

module.exports = function calc(gd, trace) {
    var i;

    var u = trace.u;
    var v = trace.v;
    var w = trace.w;
    var x = trace.x;
    var y = trace.y;
    var z = trace.z;
    var len = Math.min(x.length, y.length, z.length, u.length, v.length, w.length);

    var slen = 0;
    var startx, starty, startz;
    if(trace.starts) {
        startx = trace.starts.x || [];
        starty = trace.starts.y || [];
        startz = trace.starts.z || [];
        slen = Math.min(startx.length, starty.length, startz.length);
    }

    var normMax = 0;
    var normMin = Infinity;

    for(i = 0; i < len; i++) {
        var uu = u[i];
        var vv = v[i];
        var ww = w[i];
        var norm = Math.sqrt(uu * uu + vv * vv + ww * ww);

        normMax = Math.max(normMax, norm);
        normMin = Math.min(normMin, norm);
    }

    colorscaleCalc(gd, trace, {
        vals: [normMin, normMax],
        containerStr: '',
        cLetter: 'c'
    });

    var xMax = -Infinity;
    var xMin = Infinity;
    var yMax = -Infinity;
    var yMin = Infinity;
    var zMax = -Infinity;
    var zMin = Infinity;

    for(i = 0; i < len; i++) {
        var xx = x[i];
        xMax = Math.max(xMax, xx);
        xMin = Math.min(xMin, xx);

        var yy = y[i];
        yMax = Math.max(yMax, yy);
        yMin = Math.min(yMin, yy);

        var zz = z[i];
        zMax = Math.max(zMax, zz);
        zMin = Math.min(zMin, zz);
    }
    for(i = 0; i < slen; i++) {
        var sx = startx[i];
        xMax = Math.max(xMax, sx);
        xMin = Math.min(xMin, sx);

        var sy = starty[i];
        yMax = Math.max(yMax, sy);
        yMin = Math.min(yMin, sy);

        var sz = startz[i];
        zMax = Math.max(zMax, sz);
        zMin = Math.min(zMin, sz);
    }

    trace._len = len;
    trace._slen = slen;
    trace._normMax = normMax;
    trace._xbnds = [xMin, xMax];
    trace._ybnds = [yMin, yMax];
    trace._zbnds = [zMin, zMax];
};

},{"../../components/colorscale/calc":579}],1131:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var tube2mesh = _dereq_('gl-streamtube3d');
var createTubeMesh = tube2mesh.createTubeMesh;

var Lib = _dereq_('../../lib');
var parseColorScale = _dereq_('../../lib/gl_format_color').parseColorScale;
var zip3 = _dereq_('../../plots/gl3d/zip3');

var axisName2scaleIndex = {xaxis: 0, yaxis: 1, zaxis: 2};

function Streamtube(scene, uid) {
    this.scene = scene;
    this.uid = uid;
    this.mesh = null;
    this.data = null;
}

var proto = Streamtube.prototype;

proto.handlePick = function(selection) {
    var sceneLayout = this.scene.fullSceneLayout;
    var dataScale = this.scene.dataScale;

    function fromDataScale(v, axisName) {
        var ax = sceneLayout[axisName];
        var scale = dataScale[axisName2scaleIndex[axisName]];
        return ax.l2c(v) / scale;
    }

    if(selection.object === this.mesh) {
        var pos = selection.data.position;
        var uvx = selection.data.velocity;

        selection.traceCoordinate = [
            fromDataScale(pos[0], 'xaxis'),
            fromDataScale(pos[1], 'yaxis'),
            fromDataScale(pos[2], 'zaxis'),

            fromDataScale(uvx[0], 'xaxis'),
            fromDataScale(uvx[1], 'yaxis'),
            fromDataScale(uvx[2], 'zaxis'),

            // u/v/w norm
            selection.data.intensity * this.data._normMax,
            // divergence
            selection.data.divergence
        ];

        selection.textLabel = this.data.text;

        return true;
    }
};

function distinctVals(col) {
    return Lib.distinctVals(col).vals;
}

function getDfltStartingPositions(vec) {
    var len = vec.length;
    var s;

    if(len > 2) {
        s = vec.slice(1, len - 1);
    } else if(len === 2) {
        s = [(vec[0] + vec[1]) / 2];
    } else {
        s = vec;
    }
    return s;
}

function getBoundPads(vec) {
    var len = vec.length;
    if(len === 1) {
        return [0.5, 0.5];
    } else {
        return [vec[1] - vec[0], vec[len - 1] - vec[len - 2]];
    }
}

function convert(scene, trace) {
    var sceneLayout = scene.fullSceneLayout;
    var dataScale = scene.dataScale;
    var len = trace._len;
    var tubeOpts = {};

    function toDataCoords(arr, axisName) {
        var ax = sceneLayout[axisName];
        var scale = dataScale[axisName2scaleIndex[axisName]];
        return Lib.simpleMap(arr, function(v) { return ax.d2l(v) * scale; });
    }

    tubeOpts.vectors = zip3(
        toDataCoords(trace.u, 'xaxis'),
        toDataCoords(trace.v, 'yaxis'),
        toDataCoords(trace.w, 'zaxis'),
        len
    );

    var valsx = distinctVals(trace.x.slice(0, len));
    var valsy = distinctVals(trace.y.slice(0, len));
    var valsz = distinctVals(trace.z.slice(0, len));

    // Over-specified mesh case, this would error in tube2mesh
    if(valsx.length * valsy.length * valsz.length > len) {
        return {positions: [], cells: []};
    }

    var meshx = toDataCoords(valsx, 'xaxis');
    var meshy = toDataCoords(valsy, 'yaxis');
    var meshz = toDataCoords(valsz, 'zaxis');

    tubeOpts.meshgrid = [meshx, meshy, meshz];

    if(trace.starts) {
        var slen = trace._slen;
        tubeOpts.startingPositions = zip3(
            toDataCoords(trace.starts.x.slice(0, slen), 'xaxis'),
            toDataCoords(trace.starts.y.slice(0, slen), 'yaxis'),
            toDataCoords(trace.starts.z.slice(0, slen), 'zaxis')
        );
    } else {
        // Default starting positions:
        //
        // if len>2, cut xz plane at min-y,
        // takes all x/y/z pts on that plane except those on the edges
        // to generate "well-defined" tubes,
        //
        // if len=2, take position halfway between two the pts,
        //
        // if len=1, take that pt
        var sy0 = meshy[0];
        var sx = getDfltStartingPositions(meshx);
        var sz = getDfltStartingPositions(meshz);
        var startingPositions = new Array(sx.length * sz.length);
        var m = 0;

        for(var i = 0; i < sx.length; i++) {
            for(var k = 0; k < sz.length; k++) {
                startingPositions[m++] = [sx[i], sy0, sz[k]];
            }
        }
        tubeOpts.startingPositions = startingPositions;
    }

    tubeOpts.colormap = parseColorScale(trace);
    tubeOpts.tubeSize = trace.sizeref;
    tubeOpts.maxLength = trace.maxdisplayed;

    // add some padding around the bounds
    // to e.g. allow tubes starting from a slice of the x/y/z mesh
    // to go beyond bounds a little bit w/o getting clipped
    var xbnds = toDataCoords(trace._xbnds, 'xaxis');
    var ybnds = toDataCoords(trace._ybnds, 'yaxis');
    var zbnds = toDataCoords(trace._zbnds, 'zaxis');
    var xpads = getBoundPads(meshx);
    var ypads = getBoundPads(meshy);
    var zpads = getBoundPads(meshz);

    var bounds = [
        [xbnds[0] - xpads[0], ybnds[0] - ypads[0], zbnds[0] - zpads[0]],
        [xbnds[1] + xpads[1], ybnds[1] + ypads[1], zbnds[1] + zpads[1]]
    ];

    var meshData = tube2mesh(tubeOpts, bounds);

    // N.B. cmin/cmax correspond to the min/max vector norm
    // in the u/v/w arrays, which in general is NOT equal to max
    // intensity that colors the tubes.
    meshData.vertexIntensityBounds = [trace.cmin / trace._normMax, trace.cmax / trace._normMax];

    // pass gl-mesh3d lighting attributes
    var lp = trace.lightposition;
    meshData.lightPosition = [lp.x, lp.y, lp.z];
    meshData.ambient = trace.lighting.ambient;
    meshData.diffuse = trace.lighting.diffuse;
    meshData.specular = trace.lighting.specular;
    meshData.roughness = trace.lighting.roughness;
    meshData.fresnel = trace.lighting.fresnel;
    meshData.opacity = trace.opacity;

    // stash autorange pad value
    trace._pad = meshData.tubeScale * trace.sizeref * 2;

    return meshData;
}

proto.update = function(data) {
    this.data = data;

    var meshData = convert(this.scene, data);
    this.mesh.update(meshData);
};

proto.dispose = function() {
    this.scene.glplot.remove(this.mesh);
    this.mesh.dispose();
};

function createStreamtubeTrace(scene, data) {
    var gl = scene.glplot.gl;

    var meshData = convert(scene, data);
    var mesh = createTubeMesh(gl, meshData);

    var streamtube = new Streamtube(scene, data.uid);
    streamtube.mesh = mesh;
    streamtube.data = data;
    mesh._trace = streamtube;

    scene.glplot.add(mesh);

    return streamtube;
}

module.exports = createStreamtubeTrace;

},{"../../lib":694,"../../lib/gl_format_color":691,"../../plots/gl3d/zip3":796,"gl-streamtube3d":303}],1132:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var u = coerce('u');
    var v = coerce('v');
    var w = coerce('w');

    var x = coerce('x');
    var y = coerce('y');
    var z = coerce('z');

    if(
        !u || !u.length || !v || !v.length || !w || !w.length ||
        !x || !x.length || !y || !y.length || !z || !z.length
    ) {
        traceOut.visible = false;
        return;
    }

    coerce('starts.x');
    coerce('starts.y');
    coerce('starts.z');

    coerce('maxdisplayed');
    coerce('sizeref');

    coerce('lighting.ambient');
    coerce('lighting.diffuse');
    coerce('lighting.specular');
    coerce('lighting.roughness');
    coerce('lighting.fresnel');
    coerce('lightposition.x');
    coerce('lightposition.y');
    coerce('lightposition.z');

    colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'c'});

    coerce('text');

    // disable 1D transforms (for now)
    // x/y/z and u/v/w have matching lengths,
    // but they don't have to match with starts.(x|y|z)
    traceOut._length = null;
};

},{"../../components/colorscale/defaults":581,"../../lib":694,"./attributes":1129}],1133:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'trace',
    name: 'streamtube',
    basePlotModule: _dereq_('../../plots/gl3d'),
    categories: ['gl3d'],

    attributes: _dereq_('./attributes'),
    supplyDefaults: _dereq_('./defaults'),
    colorbar: {
        min: 'cmin',
        max: 'cmax'
    },
    calc: _dereq_('./calc'),
    plot: _dereq_('./convert'),
    eventData: function(out, pt) {
        out.tubex = out.x;
        out.tubey = out.y;
        out.tubez = out.z;

        out.tubeu = pt.traceCoordinate[3];
        out.tubev = pt.traceCoordinate[4];
        out.tubew = pt.traceCoordinate[5];

        out.norm = pt.traceCoordinate[6];
        out.divergence = pt.traceCoordinate[7];

        // Does not correspond to input x/y/z, so delete them
        delete out.x;
        delete out.y;
        delete out.z;

        return out;
    },

    meta: {
        
    }
};

},{"../../plots/gl3d":785,"./attributes":1129,"./calc":1130,"./convert":1131,"./defaults":1132}],1134:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Color = _dereq_('../../components/color');
var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
var baseAttrs = _dereq_('../../plots/attributes');

var extendFlat = _dereq_('../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;

function makeContourProjAttr(axLetter) {
    return {
        valType: 'boolean',
        
        dflt: false,
        
    };
}

function makeContourAttr(axLetter) {
    return {
        show: {
            valType: 'boolean',
            
            dflt: false,
            
        },
        project: {
            x: makeContourProjAttr('x'),
            y: makeContourProjAttr('y'),
            z: makeContourProjAttr('z')
        },
        color: {
            valType: 'color',
            
            dflt: Color.defaultLine,
            
        },
        usecolormap: {
            valType: 'boolean',
            
            dflt: false,
            
        },
        width: {
            valType: 'number',
            
            min: 1,
            max: 16,
            dflt: 2,
            
        },
        highlight: {
            valType: 'boolean',
            
            dflt: true,
            
        },
        highlightcolor: {
            valType: 'color',
            
            dflt: Color.defaultLine,
            
        },
        highlightwidth: {
            valType: 'number',
            
            min: 1,
            max: 16,
            dflt: 2,
            
        }
    };
}

var attrs = module.exports = overrideAll(extendFlat({
    z: {
        valType: 'data_array',
        
    },
    x: {
        valType: 'data_array',
        
    },
    y: {
        valType: 'data_array',
        
    },

    text: {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        
    },

    surfacecolor: {
        valType: 'data_array',
        
    },
},

colorscaleAttrs('', {
    colorAttr: 'z or surfacecolor',
    showScaleDflt: true,
    autoColorDflt: false,
    editTypeOverride: 'calc'
}), {
    colorbar: colorbarAttrs,

    contours: {
        x: makeContourAttr('x'),
        y: makeContourAttr('y'),
        z: makeContourAttr('z')
    },
    hidesurface: {
        valType: 'boolean',
        
        dflt: false,
        
    },

    lightposition: {
        x: {
            valType: 'number',
            
            min: -1e5,
            max: 1e5,
            dflt: 10,
            
        },
        y: {
            valType: 'number',
            
            min: -1e5,
            max: 1e5,
            dflt: 1e4,
            
        },
        z: {
            valType: 'number',
            
            min: -1e5,
            max: 1e5,
            dflt: 0,
            
        }
    },

    lighting: {
        ambient: {
            valType: 'number',
            
            min: 0.00,
            max: 1.0,
            dflt: 0.8,
            
        },
        diffuse: {
            valType: 'number',
            
            min: 0.00,
            max: 1.00,
            dflt: 0.8,
            
        },
        specular: {
            valType: 'number',
            
            min: 0.00,
            max: 2.00,
            dflt: 0.05,
            
        },
        roughness: {
            valType: 'number',
            
            min: 0.00,
            max: 1.00,
            dflt: 0.5,
            
        },
        fresnel: {
            valType: 'number',
            
            min: 0.00,
            max: 5.00,
            dflt: 0.2,
            
        }
    },

    opacity: {
        valType: 'number',
        
        min: 0,
        max: 1,
        dflt: 1,
        
    },

    _deprecated: {
        zauto: extendFlat({}, colorscaleAttrs.zauto, {
            
        }),
        zmin: extendFlat({}, colorscaleAttrs.zmin, {
            
        }),
        zmax: extendFlat({}, colorscaleAttrs.zmax, {
            
        })
    },

    hoverinfo: extendFlat({}, baseAttrs.hoverinfo)
}), 'calc', 'nested');

attrs.x.editType = attrs.y.editType = attrs.z.editType = 'calc+clearAxisTypes';
attrs.transforms = undefined;

},{"../../components/color":571,"../../components/colorbar/attributes":572,"../../components/colorscale/attributes":578,"../../lib/extend":684,"../../plot_api/edit_types":725,"../../plots/attributes":739}],1135:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var colorscaleCalc = _dereq_('../../components/colorscale/calc');


// Compute auto-z and autocolorscale if applicable
module.exports = function calc(gd, trace) {
    if(trace.surfacecolor) {
        colorscaleCalc(gd, trace, {
            vals: trace.surfacecolor,
            containerStr: '',
            cLetter: 'c'
        });
    } else {
        colorscaleCalc(gd, trace, {
            vals: trace.z,
            containerStr: '',
            cLetter: 'c'
        });
    }
};

},{"../../components/colorscale/calc":579}],1136:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var createSurface = _dereq_('gl-surface3d');

var ndarray = _dereq_('ndarray');
var homography = _dereq_('ndarray-homography');
var fill = _dereq_('ndarray-fill');

var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;
var parseColorScale = _dereq_('../../lib/gl_format_color').parseColorScale;
var str2RgbaArray = _dereq_('../../lib/str2rgbarray');

function SurfaceTrace(scene, surface, uid) {
    this.scene = scene;
    this.uid = uid;
    this.surface = surface;
    this.data = null;
    this.showContour = [false, false, false];
    this.minValues = [Infinity, Infinity, Infinity];
    this.maxValues = [-Infinity, -Infinity, -Infinity];
    this.dataScaleX = 1.0;
    this.dataScaleY = 1.0;
    this.refineData = true;
}

var proto = SurfaceTrace.prototype;

proto.getXat = function(a, b, calendar, axis) {
    var v = (
       (!isArrayOrTypedArray(this.data.x)) ?
            a :
       (isArrayOrTypedArray(this.data.x[0])) ?
            this.data.x[b][a] :
            this.data.x[a]
    );

    return (calendar === undefined) ? v : axis.d2l(v, 0, calendar);
};

proto.getYat = function(a, b, calendar, axis) {
    var v = (
       (!isArrayOrTypedArray(this.data.y)) ?
            b :
       (isArrayOrTypedArray(this.data.y[0])) ?
            this.data.y[b][a] :
            this.data.y[b]
    );

    return (calendar === undefined) ? v : axis.d2l(v, 0, calendar);
};

proto.getZat = function(a, b, calendar, axis) {
    var v = (
        this.data.z[b][a]
    );

    return (calendar === undefined) ? v : axis.d2l(v, 0, calendar);
};

proto.handlePick = function(selection) {
    if(selection.object === this.surface) {

        var xRatio = (selection.data.index[0] - 1) / this.dataScaleX - 1;
        var yRatio = (selection.data.index[1] - 1) / this.dataScaleY - 1;

        var j = Math.max(Math.min(Math.round(xRatio), this.data.z[0].length - 1), 0);
        var k = Math.max(Math.min(Math.round(yRatio), this.data._ylength - 1), 0);

        selection.index = [j, k];

        selection.traceCoordinate = [
            this.getXat(j, k),
            this.getYat(j, k),
            this.getZat(j, k)
        ];

        selection.dataCoordinate = [
            this.getXat(j, k, this.data.xcalendar, this.scene.fullSceneLayout.xaxis),
            this.getYat(j, k, this.data.ycalendar, this.scene.fullSceneLayout.yaxis),
            this.getZat(j, k, this.data.zcalendar, this.scene.fullSceneLayout.zaxis)
        ];

        for(var i = 0; i < 3; i++) {
            var v = selection.dataCoordinate[i];
            if(v !== null && v !== undefined) {
                selection.dataCoordinate[i] *= this.scene.dataScale[i];
            }
        }

        var text = this.data.text;
        if(Array.isArray(text) && text[k] && text[k][j] !== undefined) {
            selection.textLabel = text[k][j];
        } else if(text) {
            selection.textLabel = text;
        } else {
            selection.textLabel = '';
        }

        selection.data.dataCoordinate = selection.dataCoordinate.slice();

        this.surface.highlight(selection.data);

        // Snap spikes to data coordinate
        this.scene.glplot.spikes.position = selection.dataCoordinate;

        return true;
    }
};

function isColormapCircular(colormap) {
    var first = colormap[0].rgb;
    var last = colormap[colormap.length - 1].rgb;

    return (
        first[0] === last[0] &&
        first[1] === last[1] &&
        first[2] === last[2] &&
        first[3] === last[3]
    );
}

var shortPrimes = [
    2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
    101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
    211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293,
    307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397,
    401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499,
    503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599,
    601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691,
    701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797,
    809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887,
    907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997,
    1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097,
    1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193,
    1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297,
    1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399,
    1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499,
    1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597,
    1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699,
    1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,
    1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889,
    1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999,
    2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099,
    2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179,
    2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297,
    2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399,
    2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477,
    2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593,
    2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699,
    2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797,
    2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897,
    2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999
];

function getPow(a, b) {
    if(a < b) return 0;
    var n = 0;
    while(Math.floor(a % b) === 0) {
        a /= b;
        n++;
    }
    return n;
}

function getFactors(a) {
    var powers = [];
    for(var i = 0; i < shortPrimes.length; i++) {
        var b = shortPrimes[i];
        powers.push(
            getPow(a, b)
        );
    }
    return powers;
}

function smallestDivisor(a) {
    var A = getFactors(a);
    var result = a;
    for(var i = 0; i < shortPrimes.length; i++) {
        if(A[i] > 0) {
            result = shortPrimes[i];
            break;
        }
    }
    return result;
}

function leastCommonMultiple(a, b) {
    if(a < 1 || b < 1) return undefined;
    var A = getFactors(a);
    var B = getFactors(b);
    var n = 1;
    for(var i = 0; i < shortPrimes.length; i++) {
        n *= Math.pow(
            shortPrimes[i], Math.max(A[i], B[i])
        );
    }
    return n;
}

function arrayLCM(A) {
    if(A.length === 0) return undefined;
    var n = 1;
    for(var i = 0; i < A.length; i++) {
        n = leastCommonMultiple(n, A[i]);
    }
    return n;
}

proto.calcXnums = function(xlen) {
    var i;
    var nums = [];
    for(i = 1; i < xlen; i++) {
        var a = this.getXat(i - 1, 0);
        var b = this.getXat(i, 0);

        if(b !== a &&
            a !== undefined && a !== null &&
            b !== undefined && b !== null) {
            nums[i - 1] = Math.abs(b - a);
        } else {
            nums[i - 1] = 0;
        }
    }

    var totalDist = 0;
    for(i = 1; i < xlen; i++) {
        totalDist += nums[i - 1];
    }

    for(i = 1; i < xlen; i++) {
        if(nums[i - 1] === 0) {
            nums[i - 1] = 1;
        } else {
            nums[i - 1] = Math.round(totalDist / nums[i - 1]);
        }
    }

    return nums;
};

proto.calcYnums = function(ylen) {
    var i;
    var nums = [];
    for(i = 1; i < ylen; i++) {
        var a = this.getYat(0, i - 1);
        var b = this.getYat(0, i);

        if(b !== a &&
            a !== undefined && a !== null &&
            b !== undefined && b !== null) {
            nums[i - 1] = Math.abs(b - a);
        } else {
            nums[i - 1] = 0;
        }
    }

    var totalDist = 0;
    for(i = 1; i < ylen; i++) {
        totalDist += nums[i - 1];
    }

    for(i = 1; i < ylen; i++) {
        if(nums[i - 1] === 0) {
            nums[i - 1] = 1;
        } else {
            nums[i - 1] = Math.round(totalDist / nums[i - 1]);
        }
    }

    return nums;
};

var highlyComposites = [1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260];

var MIN_RESOLUTION = highlyComposites[9];
var MAX_RESOLUTION = highlyComposites[13];

proto.estimateScale = function(resSrc, axis) {
    var nums = (axis === 0) ?
        this.calcXnums(resSrc) :
        this.calcYnums(resSrc);

    var resDst = 1 + arrayLCM(nums);

    while(resDst < MIN_RESOLUTION) {
        resDst *= 2;
    }

    while(resDst > MAX_RESOLUTION) {
        resDst--;
        resDst /= smallestDivisor(resDst);
        resDst++;

        if(resDst < MIN_RESOLUTION) {
         // resDst = MIN_RESOLUTION; // option 1: use min resolution
            resDst = MAX_RESOLUTION; // option 2: use max resolution
        }
    }

    var scale = Math.round(resDst / resSrc);
    return (scale > 1) ? scale : 1;
};

proto.refineCoords = function(coords) {

    var scaleW = this.dataScaleX;
    var scaleH = this.dataScaleY;

    var width = coords[0].shape[0];
    var height = coords[0].shape[1];

    var newWidth = Math.floor(coords[0].shape[0] * scaleW + 1) | 0;
    var newHeight = Math.floor(coords[0].shape[1] * scaleH + 1) | 0;

    // Pad coords by +1
    var padWidth = 1 + width + 1;
    var padHeight = 1 + height + 1;
    var padImg = ndarray(new Float32Array(padWidth * padHeight), [padWidth, padHeight]);

    for(var i = 0; i < coords.length; ++i) {

        this.surface.padField(padImg, coords[i]);

        var scaledImg = ndarray(new Float32Array(newWidth * newHeight), [newWidth, newHeight]);
        homography(scaledImg, padImg,
            [
                scaleW, 0, 0,
                0, scaleH, 0,
                0, 0, 1
            ]
        );
        coords[i] = scaledImg;
    }
};

proto.setContourLevels = function() {
    var nlevels = [[], [], []];
    var needsUpdate = false;

    for(var i = 0; i < 3; ++i) {
        if(this.showContour[i]) {
            needsUpdate = true;
            nlevels[i] = this.scene.contourLevels[i];
        }
    }

    if(needsUpdate) {
        this.surface.update({ levels: nlevels });
    }
};

proto.update = function(data) {
    var scene = this.scene;
    var sceneLayout = scene.fullSceneLayout;
    var surface = this.surface;
    var alpha = data.opacity;
    var colormap = parseColorScale(data, alpha);
    var scaleFactor = scene.dataScale;
    var xlen = data.z[0].length;
    var ylen = data._ylength;
    var contourLevels = scene.contourLevels;

    // Save data
    this.data = data;

    /*
     * Fill and transpose zdata.
     * Consistent with 'heatmap' and 'contour', plotly 'surface'
     * 'z' are such that sub-arrays correspond to y-coords
     * and that the sub-array entries correspond to a x-coords,
     * which is the transpose of 'gl-surface-plot'.
     */

    var i, j, k, v;
    var rawCoords = [];
    for(i = 0; i < 3; i++) {
        rawCoords[i] = [];
        for(j = 0; j < xlen; j++) {
            rawCoords[i][j] = [];
            /*
            for(k = 0; k < ylen; k++) {
                rawCoords[i][j][k] = undefined;
            }
            */
        }
    }

    // coords x, y & z
    for(j = 0; j < xlen; j++) {
        for(k = 0; k < ylen; k++) {
            rawCoords[0][j][k] = this.getXat(j, k, data.xcalendar, sceneLayout.xaxis);
            rawCoords[1][j][k] = this.getYat(j, k, data.ycalendar, sceneLayout.yaxis);
            rawCoords[2][j][k] = this.getZat(j, k, data.zcalendar, sceneLayout.zaxis);
        }
    }

    // Note: log axes are not defined in surfaces yet.
    // but they could be defined here...

    for(i = 0; i < 3; i++) {
        for(j = 0; j < xlen; j++) {
            for(k = 0; k < ylen; k++) {
                v = rawCoords[i][j][k];
                if(v === null || v === undefined) {
                    rawCoords[i][j][k] = NaN;
                } else {
                    v = rawCoords[i][j][k] *= scaleFactor[i];
                }
            }
        }
    }

    for(i = 0; i < 3; i++) {
        for(j = 0; j < xlen; j++) {
            for(k = 0; k < ylen; k++) {
                v = rawCoords[i][j][k];
                if(v !== null && v !== undefined) {
                    if(this.minValues[i] > v) {
                        this.minValues[i] = v;
                    }
                    if(this.maxValues[i] < v) {
                        this.maxValues[i] = v;
                    }
                }
            }
        }
    }

    for(i = 0; i < 3; i++) {
        data._objectOffset[i] = 0.5 * (this.minValues[i] + this.maxValues[i]);
    }

    for(i = 0; i < 3; i++) {
        for(j = 0; j < xlen; j++) {
            for(k = 0; k < ylen; k++) {
                v = rawCoords[i][j][k];
                if(v !== null && v !== undefined) {
                    rawCoords[i][j][k] -= data._objectOffset[i];
                }
            }
        }
    }

    // convert processed raw data to Float32 matrices
    var coords = [
        ndarray(new Float32Array(xlen * ylen), [xlen, ylen]),
        ndarray(new Float32Array(xlen * ylen), [xlen, ylen]),
        ndarray(new Float32Array(xlen * ylen), [xlen, ylen])
    ];
    fill(coords[0], function(row, col) { return rawCoords[0][row][col]; });
    fill(coords[1], function(row, col) { return rawCoords[1][row][col]; });
    fill(coords[2], function(row, col) { return rawCoords[2][row][col]; });
    rawCoords = []; // free memory

    var params = {
        colormap: colormap,
        levels: [[], [], []],
        showContour: [true, true, true],
        showSurface: !data.hidesurface,
        contourProject: [
            [false, false, false],
            [false, false, false],
            [false, false, false]
        ],
        contourWidth: [1, 1, 1],
        contourColor: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]],
        contourTint: [1, 1, 1],
        dynamicColor: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]],
        dynamicWidth: [1, 1, 1],
        dynamicTint: [1, 1, 1],
        opacity: data.opacity
    };

    params.intensityBounds = [data.cmin, data.cmax];

    // Refine surface color if necessary
    if(data.surfacecolor) {
        var intensity = ndarray(new Float32Array(xlen * ylen), [xlen, ylen]);

        fill(intensity, function(row, col) {
            return data.surfacecolor[col][row];
        });

        coords.push(intensity);
    }
    else {
        // when 'z' is used as 'intensity',
        // we must scale its value
        params.intensityBounds[0] *= scaleFactor[2];
        params.intensityBounds[1] *= scaleFactor[2];
    }

    if(MAX_RESOLUTION < coords[0].shape[0] ||
        MAX_RESOLUTION < coords[0].shape[1]) {
        this.refineData = false;
    }

    if(this.refineData === true) {
        this.dataScaleX = this.estimateScale(coords[0].shape[0], 0);
        this.dataScaleY = this.estimateScale(coords[0].shape[1], 1);
        if(this.dataScaleX !== 1 || this.dataScaleY !== 1) {
            this.refineCoords(coords);
        }
    }

    if(data.surfacecolor) {
        params.intensity = coords.pop();
    }

    var highlightEnable = [true, true, true];
    var axis = ['x', 'y', 'z'];

    for(i = 0; i < 3; ++i) {
        var contourParams = data.contours[axis[i]];
        highlightEnable[i] = contourParams.highlight;

        params.showContour[i] = contourParams.show || contourParams.highlight;
        if(!params.showContour[i]) continue;

        params.contourProject[i] = [
            contourParams.project.x,
            contourParams.project.y,
            contourParams.project.z
        ];

        if(contourParams.show) {
            this.showContour[i] = true;
            params.levels[i] = contourLevels[i];
            surface.highlightColor[i] = params.contourColor[i] = str2RgbaArray(contourParams.color);

            if(contourParams.usecolormap) {
                surface.highlightTint[i] = params.contourTint[i] = 0;
            }
            else {
                surface.highlightTint[i] = params.contourTint[i] = 1;
            }
            params.contourWidth[i] = contourParams.width;
        } else {
            this.showContour[i] = false;
        }

        if(contourParams.highlight) {
            params.dynamicColor[i] = str2RgbaArray(contourParams.highlightcolor);
            params.dynamicWidth[i] = contourParams.highlightwidth;
        }
    }

    // see https://github.com/plotly/plotly.js/issues/940
    if(isColormapCircular(colormap)) {
        params.vertexColor = true;
    }

    params.objectOffset = [
        data._objectOffset[0],
        data._objectOffset[1],
        data._objectOffset[2]
    ];

    params.coords = coords;
    surface.update(params);

    surface.visible = data.visible;
    surface.enableDynamic = highlightEnable;
    surface.enableHighlight = highlightEnable;

    surface.snapToData = true;

    if('lighting' in data) {
        surface.ambientLight = data.lighting.ambient;
        surface.diffuseLight = data.lighting.diffuse;
        surface.specularLight = data.lighting.specular;
        surface.roughness = data.lighting.roughness;
        surface.fresnel = data.lighting.fresnel;
    }

    if('lightposition' in data) {
        surface.lightPosition = [data.lightposition.x, data.lightposition.y, data.lightposition.z];
    }

    if(alpha && alpha < 1) {
        surface.supportsTransparency = true;
    }
};

proto.dispose = function() {
    this.scene.glplot.remove(this.surface);
    this.surface.dispose();
};

function createSurfaceTrace(scene, data) {
    var gl = scene.glplot.gl;
    var surface = createSurface({ gl: gl });
    var result = new SurfaceTrace(scene, surface, data.uid);
    surface._trace = result;
    result.update(data);
    scene.glplot.add(surface);
    return result;
}

module.exports = createSurfaceTrace;

},{"../../lib":694,"../../lib/gl_format_color":691,"../../lib/str2rgbarray":717,"gl-surface3d":306,"ndarray":436,"ndarray-fill":426,"ndarray-homography":428}],1137:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = _dereq_('../../registry');
var Lib = _dereq_('../../lib');

var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    var i, j;

    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var x = coerce('x');
    var y = coerce('y');

    var z = coerce('z');
    if(!z || !z.length ||
       (x ? (x.length < 1) : false) ||
       (y ? (y.length < 1) : false)
    ) {
        traceOut.visible = false;
        return;
    }

    traceOut._xlength = (Array.isArray(x) && Lib.isArrayOrTypedArray(x[0])) ? z.length : z[0].length;
    traceOut._ylength = z.length;

    traceOut._objectOffset = [0, 0, 0];

    var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
    handleCalendarDefaults(traceIn, traceOut, ['x', 'y', 'z'], layout);

    coerce('text');

    // Coerce remaining properties
    [
        'lighting.ambient',
        'lighting.diffuse',
        'lighting.specular',
        'lighting.roughness',
        'lighting.fresnel',
        'lightposition.x',
        'lightposition.y',
        'lightposition.z',
        'hidesurface',
        'opacity'
    ].forEach(function(x) { coerce(x); });

    var surfaceColor = coerce('surfacecolor');

    var dims = ['x', 'y', 'z'];
    for(i = 0; i < 3; ++i) {

        var contourDim = 'contours.' + dims[i];
        var show = coerce(contourDim + '.show');
        var highlight = coerce(contourDim + '.highlight');

        if(show || highlight) {
            for(j = 0; j < 3; ++j) {
                coerce(contourDim + '.project.' + dims[j]);
            }
        }

        if(show) {
            coerce(contourDim + '.color');
            coerce(contourDim + '.width');
            coerce(contourDim + '.usecolormap');
        }

        if(highlight) {
            coerce(contourDim + '.highlightcolor');
            coerce(contourDim + '.highlightwidth');
        }
    }

    // backward compatibility block
    if(!surfaceColor) {
        mapLegacy(traceIn, 'zmin', 'cmin');
        mapLegacy(traceIn, 'zmax', 'cmax');
        mapLegacy(traceIn, 'zauto', 'cauto');
    }

    // TODO if contours.?.usecolormap are false and hidesurface is true
    // the colorbar shouldn't be shown by default

    colorscaleDefaults(
        traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'c'}
    );

    // disable 1D transforms - currently surface does NOT support column data like heatmap does
    // you can use mesh3d for this use case, but not surface
    traceOut._length = null;
};

function mapLegacy(traceIn, oldAttr, newAttr) {
    if(oldAttr in traceIn && !(newAttr in traceIn)) {
        traceIn[newAttr] = traceIn[oldAttr];
    }
}

},{"../../components/colorscale/defaults":581,"../../lib":694,"../../registry":825,"./attributes":1134}],1138:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Surface = {};

Surface.attributes = _dereq_('./attributes');
Surface.supplyDefaults = _dereq_('./defaults');
Surface.colorbar = {
    min: 'cmin',
    max: 'cmax'
};
Surface.calc = _dereq_('./calc');
Surface.plot = _dereq_('./convert');

Surface.moduleType = 'trace';
Surface.name = 'surface';
Surface.basePlotModule = _dereq_('../../plots/gl3d');
Surface.categories = ['gl3d', '2dMap', 'noOpacity'];
Surface.meta = {
    
};

module.exports = Surface;

},{"../../plots/gl3d":785,"./attributes":1134,"./calc":1135,"./convert":1136,"./defaults":1137}],1139:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var annAttrs = _dereq_('../../components/annotations/attributes');
var extendFlat = _dereq_('../../lib/extend').extendFlat;
var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
var fontAttrs = _dereq_('../../plots/font_attributes');
var domainAttrs = _dereq_('../../plots/domain').attributes;

var attrs = module.exports = overrideAll({
    domain: domainAttrs({name: 'table', trace: true}),

    columnwidth: {
        valType: 'number',
        arrayOk: true,
        dflt: null,
        
        
    },

    columnorder: {
        valType: 'data_array',
        
        
    },

    header: {

        values: {
            valType: 'data_array',
            
            dflt: [],
            
        },

        format: {
            valType: 'data_array',
            
            dflt: [],
            
        },

        prefix: {
            valType: 'string',
            arrayOk: true,
            dflt: null,
            
            
        },

        suffix: {
            valType: 'string',
            arrayOk: true,
            dflt: null,
            
            
        },

        height: {
            valType: 'number',
            dflt: 28,
            
            
        },

        align: extendFlat({}, annAttrs.align, {arrayOk: true}),

        line: {
            width: {
                valType: 'number',
                arrayOk: true,
                dflt: 1,
                
            },
            color: {
                valType: 'color',
                arrayOk: true,
                dflt: 'grey',
                
            }
        },

        fill: {
            color: {
                valType: 'color',
                arrayOk: true,
                dflt: 'white',
                
                
            }
        },

        font: extendFlat({}, fontAttrs({arrayOk: true}))
    },

    cells: {

        values: {
            valType: 'data_array',
            
            dflt: [],
            
        },

        format: {
            valType: 'data_array',
            
            dflt: [],
            
        },

        prefix: {
            valType: 'string',
            arrayOk: true,
            dflt: null,
            
            
        },

        suffix: {
            valType: 'string',
            arrayOk: true,
            dflt: null,
            
            
        },

        height: {
            valType: 'number',
            dflt: 20,
            
            
        },

        align: extendFlat({}, annAttrs.align, {arrayOk: true}),

        line: {
            width: {
                valType: 'number',
                arrayOk: true,
                dflt: 1,
                
            },
            color: {
                valType: 'color',
                arrayOk: true,
                dflt: 'grey',
                
            }
        },

        fill: {
            color: {
                valType: 'color',
                arrayOk: true,
                
                dflt: 'white',
                
            }
        },

        font: extendFlat({}, fontAttrs({arrayOk: true}))
    }
}, 'calc', 'from-root');
attrs.transforms = undefined;

},{"../../components/annotations/attributes":554,"../../lib/extend":684,"../../plot_api/edit_types":725,"../../plots/domain":768,"../../plots/font_attributes":769}],1140:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var getModuleCalcData = _dereq_('../../plots/get_data').getModuleCalcData;
var tablePlot = _dereq_('./plot');

var TABLE = 'table';

exports.name = TABLE;

exports.plot = function(gd) {
    var calcData = getModuleCalcData(gd.calcdata, TABLE)[0];
    if(calcData.length) tablePlot(gd, calcData);
};

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var hadTable = (oldFullLayout._has && oldFullLayout._has(TABLE));
    var hasTable = (newFullLayout._has && newFullLayout._has(TABLE));

    if(hadTable && !hasTable) {
        oldFullLayout._paperdiv.selectAll('.table').remove();
    }
};

},{"../../plots/get_data":779,"./plot":1147}],1141:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var wrap = _dereq_('../../lib/gup').wrap;

module.exports = function calc() {
    // we don't actually need to include the trace here, since that will be added
    // by Plots.doCalcdata, and that's all we actually need later.
    return wrap({});
};

},{"../../lib/gup":692}],1142:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    cellPad: 8,
    columnExtentOffset: 10,
    columnTitleOffset: 28,
    emptyHeaderHeight: 16,
    latexCheck: /^\$.*\$$/,
    goldenRatio: 1.618,
    lineBreaker: '<br>',
    maxDimensionCount: 60,
    overdrag: 45,
    releaseTransitionDuration: 120,
    releaseTransitionEase: 'cubic-out',
    scrollbarCaptureWidth: 18,
    scrollbarHideDelay: 1000,
    scrollbarHideDuration: 1000,
    scrollbarOffset: 5,
    scrollbarWidth: 8,
    transitionDuration: 100,
    transitionEase: 'cubic-out',
    uplift: 5,
    wrapSpacer: ' ',
    wrapSplitCharacter: ' ',
    cn: {
        // general class names
        table: 'table',
        tableControlView: 'table-control-view',
        scrollBackground: 'scroll-background',
        yColumn: 'y-column',
        columnBlock: 'column-block',
        scrollAreaClip: 'scroll-area-clip',
        scrollAreaClipRect: 'scroll-area-clip-rect',
        columnBoundary: 'column-boundary',
        columnBoundaryClippath: 'column-boundary-clippath',
        columnBoundaryRect: 'column-boundary-rect',
        columnCells: 'column-cells',
        columnCell: 'column-cell',
        cellRect: 'cell-rect',
        cellText: 'cell-text',
        cellTextHolder: 'cell-text-holder',

        // scroll related class names
        scrollbarKit: 'scrollbar-kit',
        scrollbar: 'scrollbar',
        scrollbarSlider: 'scrollbar-slider',
        scrollbarGlyph: 'scrollbar-glyph',
        scrollbarCaptureZone: 'scrollbar-capture-zone'
    }
};

},{}],1143:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var c = _dereq_('./constants');
var extendFlat = _dereq_('../../lib/extend').extendFlat;
var isNumeric = _dereq_('fast-isnumeric');

// pure functions, don't alter but passes on `gd` and parts of `trace` without deep copying
module.exports = function calc(gd, trace) {
    var cellsValues = squareStringMatrix(trace.cells.values);
    var slicer = function(a) {
        return a.slice(trace.header.values.length, a.length);
    };
    var headerValuesIn = squareStringMatrix(trace.header.values);
    if(headerValuesIn.length && !headerValuesIn[0].length) {
        headerValuesIn[0] = [''];
        headerValuesIn = squareStringMatrix(headerValuesIn);
    }
    var headerValues = headerValuesIn
        .concat(slicer(cellsValues).map(function() {
            return emptyStrings((headerValuesIn[0] || ['']).length);
        }));

    var domain = trace.domain;
    var groupWidth = Math.floor(gd._fullLayout._size.w * (domain.x[1] - domain.x[0]));
    var groupHeight = Math.floor(gd._fullLayout._size.h * (domain.y[1] - domain.y[0]));
    var headerRowHeights = trace.header.values.length ?
        headerValues[0].map(function() { return trace.header.height; }) :
        [c.emptyHeaderHeight];
    var rowHeights = cellsValues.length ? cellsValues[0].map(function() { return trace.cells.height; }) : [];
    var headerHeight = headerRowHeights.reduce(sum, 0);
    var scrollHeight = groupHeight - headerHeight;
    var minimumFillHeight = scrollHeight + c.uplift;
    var anchorToRowBlock = makeAnchorToRowBlock(rowHeights, minimumFillHeight);
    var anchorToHeaderRowBlock = makeAnchorToRowBlock(headerRowHeights, headerHeight);
    var headerRowBlocks = makeRowBlock(anchorToHeaderRowBlock, []);
    var rowBlocks = makeRowBlock(anchorToRowBlock, headerRowBlocks);
    var uniqueKeys = {};
    var columnOrder = trace._fullInput.columnorder.concat(slicer(cellsValues.map(function(d, i) {return i;})));
    var columnWidths = headerValues.map(function(d, i) {
        var value = Array.isArray(trace.columnwidth) ?
            trace.columnwidth[Math.min(i, trace.columnwidth.length - 1)] :
            trace.columnwidth;
        return isNumeric(value) ? Number(value) : 1;
    });
    var totalColumnWidths = columnWidths.reduce(sum, 0);

    // fit columns in the available vertical space as there's no vertical scrolling now
    columnWidths = columnWidths.map(function(d) { return d / totalColumnWidths * groupWidth; });

    var maxLineWidth = Math.max(arrayMax(trace.header.line.width), arrayMax(trace.cells.line.width));

    var calcdata = {
        // include staticPlot in the key so if it changes we delete and redraw
        key: trace.uid + gd._context.staticPlot,
        translateX: domain.x[0] * gd._fullLayout._size.w,
        translateY: gd._fullLayout._size.h * (1 - domain.y[1]),
        size: gd._fullLayout._size,
        width: groupWidth,
        maxLineWidth: maxLineWidth,
        height: groupHeight,
        columnOrder: columnOrder, // will be mutated on column move, todo use in callback
        groupHeight: groupHeight,
        rowBlocks: rowBlocks,
        headerRowBlocks: headerRowBlocks,
        scrollY: 0, // will be mutated on scroll
        cells: extendFlat({}, trace.cells, {values: cellsValues}),
        headerCells: extendFlat({}, trace.header, {values: headerValues}),
        gdColumns: headerValues.map(function(d) {return d[0];}),
        gdColumnsOriginalOrder: headerValues.map(function(d) {return d[0];}),
        prevPages: [0, 0],
        scrollbarState: {scrollbarScrollInProgress: false},
        columns: headerValues.map(function(label, i) {
            var foundKey = uniqueKeys[label];
            uniqueKeys[label] = (foundKey || 0) + 1;
            var key = label + '__' + uniqueKeys[label];
            return {
                key: key,
                label: label,
                specIndex: i,
                xIndex: columnOrder[i],
                xScale: xScale,
                x: undefined, // initialized below
                calcdata: undefined, // initialized below
                columnWidth: columnWidths[i]
            };
        })
    };

    calcdata.columns.forEach(function(col) {
        col.calcdata = calcdata;
        col.x = xScale(col);
    });

    return calcdata;
};

function arrayMax(maybeArray) {
    if(Array.isArray(maybeArray)) {
        var max = 0;
        for(var i = 0; i < maybeArray.length; i++) {
            max = Math.max(max, arrayMax(maybeArray[i]));
        }
        return max;
    }
    return maybeArray;
}

function sum(a, b) { return a + b; }

// fill matrix in place to equal lengths
// and ensure it's uniformly 2D
function squareStringMatrix(matrixIn) {
    var matrix = matrixIn.slice();
    var minLen = Infinity;
    var maxLen = 0;
    var i;
    for(i = 0; i < matrix.length; i++) {
        if(!Array.isArray(matrix[i])) matrix[i] = [matrix[i]];
        minLen = Math.min(minLen, matrix[i].length);
        maxLen = Math.max(maxLen, matrix[i].length);
    }

    if(minLen !== maxLen) {
        for(i = 0; i < matrix.length; i++) {
            var padLen = maxLen - matrix[i].length;
            if(padLen) matrix[i] = matrix[i].concat(emptyStrings(padLen));
        }
    }
    return matrix;
}

function emptyStrings(len) {
    var padArray = new Array(len);
    for(var j = 0; j < len; j++) padArray[j] = '';
    return padArray;
}

function xScale(d) {
    return d.calcdata.columns.reduce(function(prev, next) {
        return next.xIndex < d.xIndex ? prev + next.columnWidth : prev;
    }, 0);
}

function makeRowBlock(anchorToRowBlock, auxiliary) {
    var blockAnchorKeys = Object.keys(anchorToRowBlock);
    return blockAnchorKeys.map(function(k) {return extendFlat({}, anchorToRowBlock[k], {auxiliaryBlocks: auxiliary});});
}

function makeAnchorToRowBlock(rowHeights, minimumFillHeight) {

    var anchorToRowBlock = {};
    var currentRowHeight;
    var currentAnchor = 0;
    var currentBlockHeight = 0;
    var currentBlock = makeIdentity();
    var currentFirstRowIndex = 0;
    var blockCounter = 0;
    for(var i = 0; i < rowHeights.length; i++) {
        currentRowHeight = rowHeights[i];
        currentBlock.rows.push({
            rowIndex: i,
            rowHeight: currentRowHeight
        });
        currentBlockHeight += currentRowHeight;
        if(currentBlockHeight >= minimumFillHeight || i === rowHeights.length - 1) {
            anchorToRowBlock[currentAnchor] = currentBlock;
            currentBlock.key = blockCounter++;
            currentBlock.firstRowIndex = currentFirstRowIndex;
            currentBlock.lastRowIndex = i;
            currentBlock = makeIdentity();
            currentAnchor += currentBlockHeight;
            currentFirstRowIndex = i + 1;
            currentBlockHeight = 0;
        }
    }

    return anchorToRowBlock;
}

function makeIdentity() {
    return {
        firstRowIndex: null,
        lastRowIndex: null,
        rows: []
    };
}

},{"../../lib/extend":684,"./constants":1142,"fast-isnumeric":215}],1144:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var extendFlat = _dereq_('../../lib/extend').extendFlat;

// pure functions, don't alter but passes on `gd` and parts of `trace` without deep copying

exports.splitToPanels = function(d) {
    var prevPages = [0, 0];
    var headerPanel = extendFlat({}, d, {
        key: 'header',
        type: 'header',
        page: 0,
        prevPages: prevPages,
        currentRepaint: [null, null],
        dragHandle: true,
        values: d.calcdata.headerCells.values[d.specIndex],
        rowBlocks: d.calcdata.headerRowBlocks,
        calcdata: extendFlat({}, d.calcdata, {cells: d.calcdata.headerCells})
    });
    var revolverPanel1 = extendFlat({}, d, {
        key: 'cells1',
        type: 'cells',
        page: 0,
        prevPages: prevPages,
        currentRepaint: [null, null],
        dragHandle: false,
        values: d.calcdata.cells.values[d.specIndex],
        rowBlocks: d.calcdata.rowBlocks
    });
    var revolverPanel2 = extendFlat({}, d, {
        key: 'cells2',
        type: 'cells',
        page: 1,
        prevPages: prevPages,
        currentRepaint: [null, null],
        dragHandle: false,
        values: d.calcdata.cells.values[d.specIndex],
        rowBlocks: d.calcdata.rowBlocks
    });
    // order due to SVG using painter's algo:
    return [revolverPanel1, revolverPanel2, headerPanel];
};

exports.splitToCells = function(d) {
    var fromTo = rowFromTo(d);
    return (d.values || []).slice(fromTo[0], fromTo[1]).map(function(v, i) {
        // By keeping identical key, a DOM node removal, creation and addition is spared, important when visible
        // grid has a lot of elements (quadratic with xcol/ycol count).
        // But it has to be busted when `svgUtil.convertToTspans` is used as it reshapes cell subtrees asynchronously,
        // and by that time the user may have scrolled away, resulting in stale overwrites. The real solution will be
        // to turn `svgUtil.convertToTspans` into a cancelable request, in which case no key busting is needed.
        var buster = (typeof v === 'string') && v.match(/[<$&> ]/) ? '_keybuster_' + Math.random() : '';
        return {
            // keyWithinBlock: /*fromTo[0] + */i, // optimized future version - no busting
            // keyWithinBlock: fromTo[0] + i, // initial always-unoptimized version - janky scrolling with 5+ columns
            keyWithinBlock: i + buster, // current compromise: regular content is very fast; async content is possible
            key: fromTo[0] + i,
            column: d,
            calcdata: d.calcdata,
            page: d.page,
            rowBlocks: d.rowBlocks,
            value: v
        };
    });
};

function rowFromTo(d) {
    var rowBlock = d.rowBlocks[d.page];
    // fixme rowBlock truthiness check is due to ugly hack of placing 2nd panel as d.page = -1
    var rowFrom = rowBlock ? rowBlock.rows[0].rowIndex : 0;
    var rowTo = rowBlock ? rowFrom + rowBlock.rows.length : 0;
    return [rowFrom, rowTo];
}

},{"../../lib/extend":684}],1145:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var attributes = _dereq_('./attributes');
var handleDomainDefaults = _dereq_('../../plots/domain').defaults;

function defaultColumnOrder(traceOut, coerce) {
    var specifiedColumnOrder = traceOut.columnorder || [];
    var commonLength = traceOut.header.values.length;
    var truncated = specifiedColumnOrder.slice(0, commonLength);
    var sorted = truncated.slice().sort(function(a, b) {return a - b;});
    var oneStepped = truncated.map(function(d) {return sorted.indexOf(d);});
    for(var i = oneStepped.length; i < commonLength; i++) {
        oneStepped.push(i);
    }
    coerce('columnorder', oneStepped);
}

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    handleDomainDefaults(traceOut, layout, coerce);

    coerce('columnwidth');

    coerce('header.values');
    coerce('header.format');
    coerce('header.align');

    coerce('header.prefix');
    coerce('header.suffix');
    coerce('header.height');
    coerce('header.line.width');
    coerce('header.line.color');
    coerce('header.fill.color');
    Lib.coerceFont(coerce, 'header.font', Lib.extendFlat({}, layout.font));

    defaultColumnOrder(traceOut, coerce);

    coerce('cells.values');
    coerce('cells.format');
    coerce('cells.align');
    coerce('cells.prefix');
    coerce('cells.suffix');
    coerce('cells.height');
    coerce('cells.line.width');
    coerce('cells.line.color');
    coerce('cells.fill.color');
    Lib.coerceFont(coerce, 'cells.font', Lib.extendFlat({}, layout.font));

    // disable 1D transforms
    traceOut._length = null;
};

},{"../../lib":694,"../../plots/domain":768,"./attributes":1139}],1146:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Table = {};

Table.attributes = _dereq_('./attributes');
Table.supplyDefaults = _dereq_('./defaults');
Table.calc = _dereq_('./calc');
Table.plot = _dereq_('./plot');

Table.moduleType = 'trace';
Table.name = 'table';
Table.basePlotModule = _dereq_('./base_plot');
Table.categories = ['noOpacity'];
Table.meta = {
    
};

module.exports = Table;

},{"./attributes":1139,"./base_plot":1140,"./calc":1141,"./defaults":1145,"./plot":1147}],1147:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var c = _dereq_('./constants');
var d3 = _dereq_('d3');
var gup = _dereq_('../../lib/gup');
var Drawing = _dereq_('../../components/drawing');
var svgUtil = _dereq_('../../lib/svg_text_utils');
var raiseToTop = _dereq_('../../lib').raiseToTop;
var cancelEeaseColumn = _dereq_('../../lib').cancelTransition;
var prepareData = _dereq_('./data_preparation_helper');
var splitData = _dereq_('./data_split_helpers');
var Color = _dereq_('../../components/color');

module.exports = function plot(gd, wrappedTraceHolders) {
    var dynamic = !gd._context.staticPlot;

    var table = gd._fullLayout._paper.selectAll('.' + c.cn.table)
        .data(wrappedTraceHolders.map(function(wrappedTraceHolder) {
            var traceHolder = gup.unwrap(wrappedTraceHolder);
            var trace = traceHolder.trace;
            return prepareData(gd, trace);
        }), gup.keyFun);

    table.exit().remove();

    table.enter()
        .append('g')
        .classed(c.cn.table, true)
        .attr('overflow', 'visible')
        .style('box-sizing', 'content-box')
        .style('position', 'absolute')
        .style('left', 0)
        .style('overflow', 'visible')
        .style('shape-rendering', 'crispEdges')
        .style('pointer-events', 'all');

    table
        .attr('width', function(d) {return d.width + d.size.l + d.size.r;})
        .attr('height', function(d) {return d.height + d.size.t + d.size.b;})
        .attr('transform', function(d) {
            return 'translate(' + d.translateX + ',' + d.translateY + ')';
        });

    var tableControlView = table.selectAll('.' + c.cn.tableControlView)
        .data(gup.repeat, gup.keyFun);

    var cvEnter = tableControlView.enter()
        .append('g')
        .classed(c.cn.tableControlView, true)
        .style('box-sizing', 'content-box');
    if(dynamic) {
        cvEnter
            .on('mousemove', function(d) {
                tableControlView
                    .filter(function(dd) {return d === dd;})
                    .call(renderScrollbarKit, gd);
            })
            .on('mousewheel', function(d) {
                if(d.scrollbarState.wheeling) return;
                d.scrollbarState.wheeling = true;
                var newY = d.scrollY + d3.event.deltaY;
                var noChange = makeDragRow(gd, tableControlView, null, newY)(d);
                if(!noChange) {
                    d3.event.stopPropagation();
                    d3.event.preventDefault();
                }
                d.scrollbarState.wheeling = false;
            })
            .call(renderScrollbarKit, gd, true);
    }

    tableControlView
        .attr('transform', function(d) {return 'translate(' + d.size.l + ' ' + d.size.t + ')';});

    // scrollBackground merely ensures that mouse events are captured even on crazy fast scrollwheeling
    // otherwise rendering glitches may occur
    var scrollBackground = tableControlView.selectAll('.' + c.cn.scrollBackground)
        .data(gup.repeat, gup.keyFun);

    scrollBackground.enter()
        .append('rect')
        .classed(c.cn.scrollBackground, true)
        .attr('fill', 'none');

    scrollBackground
        .attr('width', function(d) {return d.width;})
        .attr('height', function(d) {return d.height;});

    tableControlView.each(function(d) {
        Drawing.setClipUrl(d3.select(this), scrollAreaBottomClipKey(gd, d), gd);
    });

    var yColumn = tableControlView.selectAll('.' + c.cn.yColumn)
        .data(function(vm) {return vm.columns;}, gup.keyFun);

    yColumn.enter()
        .append('g')
        .classed(c.cn.yColumn, true);

    yColumn.exit().remove();

    yColumn.attr('transform', function(d) {return 'translate(' + d.x + ' 0)';});

    if(dynamic) {
        yColumn.call(d3.behavior.drag()
            .origin(function(d) {
                var movedColumn = d3.select(this);
                easeColumn(movedColumn, d, -c.uplift);
                raiseToTop(this);
                d.calcdata.columnDragInProgress = true;
                renderScrollbarKit(tableControlView.filter(function(dd) {return d.calcdata.key === dd.key;}), gd);
                return d;
            })
            .on('drag', function(d) {
                var movedColumn = d3.select(this);
                var getter = function(dd) {return (d === dd ? d3.event.x : dd.x) + dd.columnWidth / 2;};
                d.x = Math.max(-c.overdrag, Math.min(d.calcdata.width + c.overdrag - d.columnWidth, d3.event.x));

                var sortableColumns = flatData(yColumn).filter(function(dd) {return dd.calcdata.key === d.calcdata.key;});
                var newOrder = sortableColumns.sort(function(a, b) {return getter(a) - getter(b);});
                newOrder.forEach(function(dd, i) {
                    dd.xIndex = i;
                    dd.x = d === dd ? dd.x : dd.xScale(dd);
                });

                yColumn.filter(function(dd) {return d !== dd;})
                    .transition()
                    .ease(c.transitionEase)
                    .duration(c.transitionDuration)
                    .attr('transform', function(d) {return 'translate(' + d.x + ' 0)';});
                movedColumn
                    .call(cancelEeaseColumn)
                    .attr('transform', 'translate(' + d.x + ' -' + c.uplift + ' )');
            })
            .on('dragend', function(d) {
                var movedColumn = d3.select(this);
                var p = d.calcdata;
                d.x = d.xScale(d);
                d.calcdata.columnDragInProgress = false;
                easeColumn(movedColumn, d, 0);
                columnMoved(gd, p, p.columns.map(function(dd) {return dd.xIndex;}));
            })
        );
    }

    yColumn.each(function(d) {
        Drawing.setClipUrl(d3.select(this), columnBoundaryClipKey(gd, d), gd);
    });

    var columnBlock = yColumn.selectAll('.' + c.cn.columnBlock)
        .data(splitData.splitToPanels, gup.keyFun);

    columnBlock.enter()
        .append('g')
        .classed(c.cn.columnBlock, true)
        .attr('id', function(d) {return d.key;});

    columnBlock
        .style('cursor', function(d) {
            return d.dragHandle ? 'ew-resize' : d.calcdata.scrollbarState.barWiggleRoom ? 'ns-resize' : 'default';
        });

    var headerColumnBlock = columnBlock.filter(headerBlock);
    var cellsColumnBlock = columnBlock.filter(cellsBlock);

    if(dynamic) {
        cellsColumnBlock.call(d3.behavior.drag()
            .origin(function(d) {
                d3.event.stopPropagation();
                return d;
            })
            .on('drag', makeDragRow(gd, tableControlView, -1))
            .on('dragend', function() {
                // fixme emit plotly notification
            })
        );
    }

    // initial rendering: header is rendered first, as it may may have async LaTeX (show header first)
    // but blocks are _entered_ the way they are due to painter's algo (header on top)
    renderColumnCellTree(gd, tableControlView, headerColumnBlock, columnBlock);
    renderColumnCellTree(gd, tableControlView, cellsColumnBlock, columnBlock);

    var scrollAreaClip = tableControlView.selectAll('.' + c.cn.scrollAreaClip)
        .data(gup.repeat, gup.keyFun);

    scrollAreaClip.enter()
        .append('clipPath')
        .classed(c.cn.scrollAreaClip, true)
        .attr('id', function(d) {return scrollAreaBottomClipKey(gd, d);});

    var scrollAreaClipRect = scrollAreaClip.selectAll('.' + c.cn.scrollAreaClipRect)
        .data(gup.repeat, gup.keyFun);

    scrollAreaClipRect.enter()
        .append('rect')
        .classed(c.cn.scrollAreaClipRect, true)
        .attr('x', -c.overdrag)
        .attr('y', -c.uplift)
        .attr('fill', 'none');

    scrollAreaClipRect
        .attr('width', function(d) {return d.width + 2 * c.overdrag;})
        .attr('height', function(d) {return d.height + c.uplift;});

    var columnBoundary = yColumn.selectAll('.' + c.cn.columnBoundary)
        .data(gup.repeat, gup.keyFun);

    columnBoundary.enter()
        .append('g')
        .classed(c.cn.columnBoundary, true);

    var columnBoundaryClippath = yColumn.selectAll('.' + c.cn.columnBoundaryClippath)
        .data(gup.repeat, gup.keyFun);

    // SVG spec doesn't mandate wrapping into a <defs> and doesn't seem to cause a speed difference
    columnBoundaryClippath.enter()
        .append('clipPath')
        .classed(c.cn.columnBoundaryClippath, true);

    columnBoundaryClippath
        .attr('id', function(d) {return columnBoundaryClipKey(gd, d);});

    var columnBoundaryRect = columnBoundaryClippath.selectAll('.' + c.cn.columnBoundaryRect)
        .data(gup.repeat, gup.keyFun);

    columnBoundaryRect.enter()
        .append('rect')
        .classed(c.cn.columnBoundaryRect, true)
        .attr('fill', 'none');

    columnBoundaryRect
        .attr('width', function(d) { return d.columnWidth + 2 * roundHalfWidth(d); })
        .attr('height', function(d) {return d.calcdata.height + 2 * roundHalfWidth(d) + c.uplift;})
        .attr('x', function(d) { return -roundHalfWidth(d); })
        .attr('y', function(d) { return -roundHalfWidth(d); });

    updateBlockYPosition(null, cellsColumnBlock, tableControlView);
};

function roundHalfWidth(d) {
    return Math.ceil(d.calcdata.maxLineWidth / 2);
}

function scrollAreaBottomClipKey(gd, d) {
    return 'clip' + gd._fullLayout._uid + '_scrollAreaBottomClip_' + d.key;
}

function columnBoundaryClipKey(gd, d) {
    return 'clip' + gd._fullLayout._uid + '_columnBoundaryClippath_' + d.calcdata.key + '_' + d.specIndex;
}

function flatData(selection) {
    return [].concat.apply([], selection.map(function(g) {return g;}))
        .map(function(g) {return g.__data__;});
}

function renderScrollbarKit(tableControlView, gd, bypassVisibleBar) {

    function calcTotalHeight(d) {
        var blocks = d.rowBlocks;
        return firstRowAnchor(blocks, blocks.length - 1) + (blocks.length ? rowsHeight(blocks[blocks.length - 1], Infinity) : 1);
    }

    var scrollbarKit = tableControlView.selectAll('.' + c.cn.scrollbarKit)
        .data(gup.repeat, gup.keyFun);

    scrollbarKit.enter()
        .append('g')
        .classed(c.cn.scrollbarKit, true)
        .style('shape-rendering', 'geometricPrecision');

    scrollbarKit
        .each(function(d) {
            var s = d.scrollbarState;
            s.totalHeight = calcTotalHeight(d);
            s.scrollableAreaHeight = d.groupHeight - headerHeight(d);
            s.currentlyVisibleHeight = Math.min(s.totalHeight, s.scrollableAreaHeight);
            s.ratio = s.currentlyVisibleHeight / s.totalHeight;
            s.barLength = Math.max(s.ratio * s.currentlyVisibleHeight, c.goldenRatio * c.scrollbarWidth);
            s.barWiggleRoom = s.currentlyVisibleHeight - s.barLength;
            s.wiggleRoom = Math.max(0, s.totalHeight - s.scrollableAreaHeight);
            s.topY = s.barWiggleRoom === 0 ? 0 : (d.scrollY / s.wiggleRoom) * s.barWiggleRoom;
            s.bottomY = s.topY + s.barLength;
            s.dragMultiplier = s.wiggleRoom / s.barWiggleRoom;
        })
        .attr('transform', function(d) {
            var xPosition = d.width + c.scrollbarWidth / 2 + c.scrollbarOffset;
            return 'translate(' + xPosition + ' ' + headerHeight(d) + ')';
        });

    var scrollbar = scrollbarKit.selectAll('.' + c.cn.scrollbar)
        .data(gup.repeat, gup.keyFun);

    scrollbar.enter()
        .append('g')
        .classed(c.cn.scrollbar, true);

    var scrollbarSlider = scrollbar.selectAll('.' + c.cn.scrollbarSlider)
        .data(gup.repeat, gup.keyFun);

    scrollbarSlider.enter()
        .append('g')
        .classed(c.cn.scrollbarSlider, true);

    scrollbarSlider
        .attr('transform', function(d) {
            return 'translate(0 ' + (d.scrollbarState.topY || 0) + ')';
        });

    var scrollbarGlyph = scrollbarSlider.selectAll('.' + c.cn.scrollbarGlyph)
        .data(gup.repeat, gup.keyFun);

    scrollbarGlyph.enter()
        .append('line')
        .classed(c.cn.scrollbarGlyph, true)
        .attr('stroke', 'black')
        .attr('stroke-width', c.scrollbarWidth)
        .attr('stroke-linecap', 'round')
        .attr('y1', c.scrollbarWidth / 2);

    scrollbarGlyph
        .attr('y2', function(d) {
            return d.scrollbarState.barLength - c.scrollbarWidth / 2;
        })
        .attr('stroke-opacity', function(d) {
            return d.columnDragInProgress || !d.scrollbarState.barWiggleRoom || bypassVisibleBar ? 0 : 0.4;
        });

    // cancel transition: possible pending (also, delayed) transition
    scrollbarGlyph
        .transition().delay(0).duration(0);

    scrollbarGlyph
        .transition().delay(c.scrollbarHideDelay).duration(c.scrollbarHideDuration)
        .attr('stroke-opacity', 0);

    var scrollbarCaptureZone = scrollbar.selectAll('.' + c.cn.scrollbarCaptureZone)
        .data(gup.repeat, gup.keyFun);

    scrollbarCaptureZone.enter()
        .append('line')
        .classed(c.cn.scrollbarCaptureZone, true)
        .attr('stroke', 'white')
        .attr('stroke-opacity', 0.01) // some browser might get rid of a 0 opacity element
        .attr('stroke-width', c.scrollbarCaptureWidth)
        .attr('stroke-linecap', 'butt')
        .attr('y1', 0)
        .on('mousedown', function(d) {
            var y = d3.event.y;
            var bbox = this.getBoundingClientRect();
            var s = d.scrollbarState;
            var pixelVal = y - bbox.top;
            var inverseScale = d3.scale.linear().domain([0, s.scrollableAreaHeight]).range([0, s.totalHeight]).clamp(true);
            if(!(s.topY <= pixelVal && pixelVal <= s.bottomY)) {
                makeDragRow(gd, tableControlView, null, inverseScale(pixelVal - s.barLength / 2))(d);
            }
        })
        .call(d3.behavior.drag()
            .origin(function(d) {
                d3.event.stopPropagation();
                d.scrollbarState.scrollbarScrollInProgress = true;
                return d;
            })
            .on('drag', makeDragRow(gd, tableControlView))
            .on('dragend', function() {
                // fixme emit Plotly event
            })
        );

    scrollbarCaptureZone
        .attr('y2', function(d) {
            return d.scrollbarState.scrollableAreaHeight;
        });

    // Remove scroll glyph and capture zone on static plots
    // as they don't render properly when converted to PDF
    // in the Chrome PDF viewer
    // https://github.com/plotly/streambed/issues/11618
    if(gd._context.staticPlot) {
        scrollbarGlyph.remove();
        scrollbarCaptureZone.remove();
    }
}

function renderColumnCellTree(gd, tableControlView, columnBlock, allColumnBlock) {
    // fixme this perf hotspot
    // this is performance critical code as scrolling calls it on every revolver switch
    // it appears sufficiently fast but there are plenty of low-hanging fruits for performance optimization

    var columnCells = renderColumnCells(columnBlock);

    var columnCell = renderColumnCell(columnCells);

    supplyStylingValues(columnCell);

    var cellRect = renderCellRect(columnCell);

    sizeAndStyleRect(cellRect);

    var cellTextHolder = renderCellTextHolder(columnCell);

    var cellText = renderCellText(cellTextHolder);

    setFont(cellText);
    populateCellText(cellText, tableControlView, allColumnBlock, gd);

    // doing this at the end when text, and text stlying are set
    setCellHeightAndPositionY(columnCell);
}

function renderColumnCells(columnBlock) {

    var columnCells = columnBlock.selectAll('.' + c.cn.columnCells)
        .data(gup.repeat, gup.keyFun);

    columnCells.enter()
        .append('g')
        .classed(c.cn.columnCells, true);

    columnCells.exit()
        .remove();

    return columnCells;
}

function renderColumnCell(columnCells) {

    var columnCell = columnCells.selectAll('.' + c.cn.columnCell)
        .data(splitData.splitToCells, function(d) {return d.keyWithinBlock;});

    columnCell.enter()
        .append('g')
        .classed(c.cn.columnCell, true);

    columnCell.exit()
        .remove();

    return columnCell;
}

function renderCellRect(columnCell) {

    var cellRect = columnCell.selectAll('.' + c.cn.cellRect)
        .data(gup.repeat, function(d) {return d.keyWithinBlock;});

    cellRect.enter()
        .append('rect')
        .classed(c.cn.cellRect, true);

    return cellRect;
}

function renderCellText(cellTextHolder) {

    var cellText = cellTextHolder.selectAll('.' + c.cn.cellText)
        .data(gup.repeat, function(d) {return d.keyWithinBlock;});

    cellText.enter()
        .append('text')
        .classed(c.cn.cellText, true)
        .style('cursor', function() {return 'auto';})
        .on('mousedown', function() {d3.event.stopPropagation();});

    return cellText;
}

function renderCellTextHolder(columnCell) {

    var cellTextHolder = columnCell.selectAll('.' + c.cn.cellTextHolder)
        .data(gup.repeat, function(d) {return d.keyWithinBlock;});

    cellTextHolder.enter()
        .append('g')
        .classed(c.cn.cellTextHolder, true)
        .style('shape-rendering', 'geometricPrecision');

    return cellTextHolder;
}

function supplyStylingValues(columnCell) {
    columnCell
        .each(function(d, i) {
            var spec = d.calcdata.cells.font;
            var col = d.column.specIndex;
            var font = {
                size: gridPick(spec.size, col, i),
                color: gridPick(spec.color, col, i),
                family: gridPick(spec.family, col, i)
            };
            d.rowNumber = d.key;
            d.align = gridPick(d.calcdata.cells.align, col, i);
            d.cellBorderWidth = gridPick(d.calcdata.cells.line.width, col, i);
            d.font = font;
        });
}

function setFont(cellText) {
    cellText
        .each(function(d) {
            Drawing.font(d3.select(this), d.font);
        });
}

function sizeAndStyleRect(cellRect) {
    cellRect
        .attr('width', function(d) {return d.column.columnWidth;})
        .attr('stroke-width', function(d) {return d.cellBorderWidth;})
        .each(function(d) {
            var atomicSelection = d3.select(this);
            Color.stroke(atomicSelection, gridPick(d.calcdata.cells.line.color, d.column.specIndex, d.rowNumber));
            Color.fill(atomicSelection, gridPick(d.calcdata.cells.fill.color, d.column.specIndex, d.rowNumber));
        });
}

function populateCellText(cellText, tableControlView, allColumnBlock, gd) {
    cellText
        .text(function(d) {

            var col = d.column.specIndex;
            var row = d.rowNumber;

            var userSuppliedContent = d.value;
            var stringSupplied = (typeof userSuppliedContent === 'string');
            var hasBreaks = stringSupplied && userSuppliedContent.match(/<br>/i);
            var userBrokenText = !stringSupplied || hasBreaks;
            d.mayHaveMarkup = stringSupplied && userSuppliedContent.match(/[<&>]/);

            var latex = isLatex(userSuppliedContent);
            d.latex = latex;

            var prefix = latex ? '' : gridPick(d.calcdata.cells.prefix, col, row) || '';
            var suffix = latex ? '' : gridPick(d.calcdata.cells.suffix, col, row) || '';
            var format = latex ? null : gridPick(d.calcdata.cells.format, col, row) || null;

            var prefixSuffixedText = prefix + (format ? d3.format(format)(d.value) : d.value) + suffix;

            var hasWrapSplitCharacter;
            d.wrappingNeeded = !d.wrapped && !userBrokenText && !latex && (hasWrapSplitCharacter = hasWrapCharacter(prefixSuffixedText));
            d.cellHeightMayIncrease = hasBreaks || latex || d.mayHaveMarkup || (hasWrapSplitCharacter === void(0) ? hasWrapCharacter(prefixSuffixedText) : hasWrapSplitCharacter);
            d.needsConvertToTspans = d.mayHaveMarkup || d.wrappingNeeded || d.latex;

            var textToRender;
            if(d.wrappingNeeded) {
                var hrefPreservedText = c.wrapSplitCharacter === ' ' ? prefixSuffixedText.replace(/<a href=/ig, '<a_href=') : prefixSuffixedText;
                var fragments = hrefPreservedText.split(c.wrapSplitCharacter);
                var hrefRestoredFragments = c.wrapSplitCharacter === ' ' ? fragments.map(function(frag) {return frag.replace(/<a_href=/ig, '<a href=');}) : fragments;
                d.fragments = hrefRestoredFragments.map(function(f) {return {text: f, width: null};});
                d.fragments.push({fragment: c.wrapSpacer, width: null});
                textToRender = hrefRestoredFragments.join(c.lineBreaker) + c.lineBreaker + c.wrapSpacer;
            } else {
                delete d.fragments;
                textToRender = prefixSuffixedText;
            }

            return textToRender;
        })
        .attr('dy', function(d) {
            return d.needsConvertToTspans ? 0 : '0.75em';
        })
        .each(function(d) {

            var element = this;
            var selection = d3.select(element);

            // finalize what's in the DOM

            var renderCallback = d.wrappingNeeded ? wrapTextMaker : updateYPositionMaker;
            if(d.needsConvertToTspans) {
                svgUtil.convertToTspans(selection, gd, renderCallback(allColumnBlock, element, tableControlView, gd, d));
            } else {
                d3.select(element.parentNode)
                    // basic cell adjustment - compliance with `cellPad`
                    .attr('transform', function(d) {return 'translate(' + xPosition(d) + ' ' + c.cellPad + ')';})
                    .attr('text-anchor', function(d) {
                        return ({
                            left: 'start',
                            center: 'middle',
                            right: 'end'
                        })[d.align];
                    });
            }
        });
}

function isLatex(content) {
    return typeof content === 'string' && content.match(c.latexCheck);
}

function hasWrapCharacter(text) {return text.indexOf(c.wrapSplitCharacter) !== -1;}

function columnMoved(gd, calcdata, indices) {
    var o = calcdata.gdColumnsOriginalOrder;
    calcdata.gdColumns.sort(function(a, b) {
        return indices[o.indexOf(a)] - indices[o.indexOf(b)];
    });

    calcdata.columnorder = indices;

    // TODO: there's no data here, but also this reordering is not reflected
    // in gd.data or even gd._fullData.
    // For now I will not attempt to persist this in _preGUI
    gd.emit('plotly_restyle');
}

function gridPick(spec, col, row) {
    if(Array.isArray(spec)) {
        var column = spec[Math.min(col, spec.length - 1)];
        if(Array.isArray(column)) {
            return column[Math.min(row, column.length - 1)];
        } else {
            return column;
        }
    } else {
        return spec;
    }
}

function easeColumn(selection, d, y) {
    selection
        .transition()
        .ease(c.releaseTransitionEase)
        .duration(c.releaseTransitionDuration)
        .attr('transform', 'translate(' + d.x + ' ' + y + ')');
}

function cellsBlock(d) {return d.type === 'cells';}
function headerBlock(d) {return d.type === 'header';}

/**
 * Revolver panel and cell contents layouting
 */

function headerHeight(d) {
    var headerBlocks = d.rowBlocks.length ? d.rowBlocks[0].auxiliaryBlocks : [];
    return headerBlocks.reduce(function(p, n) {return p + rowsHeight(n, Infinity);}, 0);
}

function findPagesAndCacheHeights(blocks, scrollY, scrollHeight) {

    var pages = [];
    var pTop = 0;

    for(var blockIndex = 0; blockIndex < blocks.length; blockIndex++) {

        var block = blocks[blockIndex];
        var blockRows = block.rows;
        var rowsHeight = 0;
        for(var i = 0; i < blockRows.length; i++) {
            rowsHeight += blockRows[i].rowHeight;
        }

        // caching allRowsHeight on the block - it's safe as this function is always called from within the code part
        // that handles increases to row heights
        block.allRowsHeight = rowsHeight;

        var pBottom = pTop + rowsHeight;
        var windowTop = scrollY;
        var windowBottom = windowTop + scrollHeight;
        if(windowTop < pBottom && windowBottom > pTop) {
            pages.push(blockIndex);
        }
        pTop += rowsHeight;

        // consider this nice final optimization; put it in `for` condition - caveat, currently the
        // block.allRowsHeight relies on being invalidated, so enabling this opt may not be safe
        // if(pages.length > 1) break;
    }

    return pages;
}

function updateBlockYPosition(gd, cellsColumnBlock, tableControlView) {
    var d = flatData(cellsColumnBlock)[0];
    if(d === undefined) return;
    var blocks = d.rowBlocks;
    var calcdata = d.calcdata;

    var bottom = firstRowAnchor(blocks, blocks.length);
    var scrollHeight = d.calcdata.groupHeight - headerHeight(d);
    var scrollY = calcdata.scrollY = Math.max(0, Math.min(bottom - scrollHeight, calcdata.scrollY));

    var pages = findPagesAndCacheHeights(blocks, scrollY, scrollHeight);
    if(pages.length === 1) {
        if(pages[0] === blocks.length - 1) {
            pages.unshift(pages[0] - 1);
        } else {
            pages.push(pages[0] + 1);
        }
    }

    // make phased out page jump by 2 while leaving stationary page intact
    if(pages[0] % 2) {
        pages.reverse();
    }

    cellsColumnBlock
        .each(function(d, i) {
            // these values will also be needed when a block is translated again due to growing cell height
            d.page = pages[i];
            d.scrollY = scrollY;
        });

    cellsColumnBlock
        .attr('transform', function(d) {
            var yTranslate = firstRowAnchor(d.rowBlocks, d.page) - d.scrollY;
            return 'translate(0 ' + yTranslate + ')';
        });

    // conditionally rerendering panel 0 and 1
    if(gd) {
        conditionalPanelRerender(gd, tableControlView, cellsColumnBlock, pages, d.prevPages, d, 0);
        conditionalPanelRerender(gd, tableControlView, cellsColumnBlock, pages, d.prevPages, d, 1);
        renderScrollbarKit(tableControlView, gd);
    }
}

function makeDragRow(gd, allTableControlView, optionalMultiplier, optionalPosition) {
    return function dragRow(eventD) {
        // may come from whichever DOM event target: drag, wheel, bar... eventD corresponds to event target
        var d = eventD.calcdata ? eventD.calcdata : eventD;
        var tableControlView = allTableControlView.filter(function(dd) {return d.key === dd.key;});
        var multiplier = optionalMultiplier || d.scrollbarState.dragMultiplier;

        var initialScrollY = d.scrollY;

        d.scrollY = optionalPosition === void(0) ? d.scrollY + multiplier * d3.event.dy : optionalPosition;
        var cellsColumnBlock = tableControlView.selectAll('.' + c.cn.yColumn).selectAll('.' + c.cn.columnBlock).filter(cellsBlock);
        updateBlockYPosition(gd, cellsColumnBlock, tableControlView);

        // return false if we've "used" the scroll, ie it did something,
        // so the event shouldn't bubble (if appropriate)
        return d.scrollY === initialScrollY;
    };
}

function conditionalPanelRerender(gd, tableControlView, cellsColumnBlock, pages, prevPages, d, revolverIndex) {
    var shouldComponentUpdate = pages[revolverIndex] !== prevPages[revolverIndex];
    if(shouldComponentUpdate) {
        clearTimeout(d.currentRepaint[revolverIndex]);
        d.currentRepaint[revolverIndex] = setTimeout(function() {
            // setTimeout might lag rendering but yields a smoother scroll, because fast scrolling makes
            // some repaints invisible ie. wasteful (DOM work blocks the main thread)
            var toRerender = cellsColumnBlock.filter(function(d, i) {return i === revolverIndex && pages[i] !== prevPages[i];});
            renderColumnCellTree(gd, tableControlView, toRerender, cellsColumnBlock);
            prevPages[revolverIndex] = pages[revolverIndex];
        });
    }
}

function wrapTextMaker(columnBlock, element, tableControlView, gd) {
    return function wrapText() {
        var cellTextHolder = d3.select(element.parentNode);
        cellTextHolder
            .each(function(d) {
                var fragments = d.fragments;
                cellTextHolder.selectAll('tspan.line').each(function(dd, i) {
                    fragments[i].width = this.getComputedTextLength();
                });
                // last element is only for measuring the separator character, so it's ignored:
                var separatorLength = fragments[fragments.length - 1].width;
                var rest = fragments.slice(0, -1);
                var currentRow = [];
                var currentAddition, currentAdditionLength;
                var currentRowLength = 0;
                var rowLengthLimit = d.column.columnWidth - 2 * c.cellPad;
                d.value = '';
                while(rest.length) {
                    currentAddition = rest.shift();
                    currentAdditionLength = currentAddition.width + separatorLength;
                    if(currentRowLength + currentAdditionLength > rowLengthLimit) {
                        d.value += currentRow.join(c.wrapSpacer) + c.lineBreaker;
                        currentRow = [];
                        currentRowLength = 0;
                    }
                    currentRow.push(currentAddition.text);
                    currentRowLength += currentAdditionLength;
                }
                if(currentRowLength) {
                    d.value += currentRow.join(c.wrapSpacer);
                }
                d.wrapped = true;
            });

        // the pre-wrapped text was rendered only for the text measurements
        cellTextHolder.selectAll('tspan.line').remove();

        // resupply text, now wrapped
        populateCellText(cellTextHolder.select('.' + c.cn.cellText), tableControlView, columnBlock, gd);
        d3.select(element.parentNode.parentNode).call(setCellHeightAndPositionY);
    };
}

function updateYPositionMaker(columnBlock, element, tableControlView, gd, d) {
    return function updateYPosition() {
        if(d.settledY) return;
        var cellTextHolder = d3.select(element.parentNode);
        var l = getBlock(d);
        var rowIndex = d.key - l.firstRowIndex;

        var declaredRowHeight = l.rows[rowIndex].rowHeight;

        var requiredHeight = d.cellHeightMayIncrease ? element.parentNode.getBoundingClientRect().height + 2 * c.cellPad : declaredRowHeight;

        var finalHeight = Math.max(requiredHeight, declaredRowHeight);
        var increase = finalHeight - l.rows[rowIndex].rowHeight;

        if(increase) {

            // current row height increased
            l.rows[rowIndex].rowHeight = finalHeight;

            columnBlock
                .selectAll('.' + c.cn.columnCell)
                .call(setCellHeightAndPositionY);

            updateBlockYPosition(null, columnBlock.filter(cellsBlock), 0);

            // if d.column.type === 'header', then the scrollbar has to be pushed downward to the scrollable area
            // if d.column.type === 'cells', it can still be relevant if total scrolling content height is less than the
            //                               scrollable window, as increases to row heights may need scrollbar updates
            renderScrollbarKit(tableControlView, gd, true);
        }

        cellTextHolder
            .attr('transform', function() {
                // this code block is only invoked for items where d.cellHeightMayIncrease is truthy
                var element = this;
                var columnCellElement = element.parentNode;
                var box = columnCellElement.getBoundingClientRect();
                var rectBox = d3.select(element.parentNode).select('.' + c.cn.cellRect).node().getBoundingClientRect();
                var currentTransform = element.transform.baseVal.consolidate();
                var yPosition = rectBox.top - box.top + (currentTransform ? currentTransform.matrix.f : c.cellPad);
                return 'translate(' + xPosition(d, d3.select(element.parentNode).select('.' + c.cn.cellTextHolder).node().getBoundingClientRect().width) + ' ' + yPosition + ')';
            });

        d.settledY = true;
    };
}

function xPosition(d, optionalWidth) {
    switch(d.align) {
        case 'left': return c.cellPad;
        case 'right': return d.column.columnWidth - (optionalWidth || 0) - c.cellPad;
        case 'center': return (d.column.columnWidth - (optionalWidth || 0)) / 2;
        default: return c.cellPad;
    }
}

function setCellHeightAndPositionY(columnCell) {
    columnCell
        .attr('transform', function(d) {
            var headerHeight = d.rowBlocks[0].auxiliaryBlocks.reduce(function(p, n) {return p + rowsHeight(n, Infinity);}, 0);
            var l = getBlock(d);
            var rowAnchor = rowsHeight(l, d.key);
            var yOffset = rowAnchor + headerHeight;
            return 'translate(0 ' + yOffset + ')';
        })
        .selectAll('.' + c.cn.cellRect)
        .attr('height', function(d) {return getRow(getBlock(d), d.key).rowHeight;});
}

function firstRowAnchor(blocks, page) {
    var total = 0;
    for(var i = page - 1; i >= 0; i--) {
        total += allRowsHeight(blocks[i]);
    }
    return total;
}

function rowsHeight(rowBlock, key) {
    var total = 0;
    for(var i = 0; i < rowBlock.rows.length && rowBlock.rows[i].rowIndex < key; i++) {
        total += rowBlock.rows[i].rowHeight;
    }
    return total;
}

function allRowsHeight(rowBlock) {
    var cached = rowBlock.allRowsHeight;

    if(cached !== void(0)) {
        return cached;
    }

    var total = 0;
    for(var i = 0; i < rowBlock.rows.length; i++) {
        total += rowBlock.rows[i].rowHeight;
    }
    rowBlock.allRowsHeight = total;

    return total;
}

function getBlock(d) {return d.rowBlocks[d.page];}
function getRow(l, i) {return l.rows[i - l.firstRowIndex];}

},{"../../components/color":571,"../../components/drawing":592,"../../lib":694,"../../lib/gup":692,"../../lib/svg_text_utils":718,"./constants":1142,"./data_preparation_helper":1143,"./data_split_helpers":1144,"d3":149}],1148:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var boxAttrs = _dereq_('../box/attributes');
var extendFlat = _dereq_('../../lib/extend').extendFlat;

module.exports = {
    y: boxAttrs.y,
    x: boxAttrs.x,
    x0: boxAttrs.x0,
    y0: boxAttrs.y0,
    name: boxAttrs.name,
    orientation: extendFlat({}, boxAttrs.orientation, {
        
    }),

    bandwidth: {
        valType: 'number',
        min: 0,
        
        editType: 'calc',
        
    },

    scalegroup: {
        valType: 'string',
        
        dflt: '',
        editType: 'calc',
        
    },
    scalemode: {
        valType: 'enumerated',
        values: ['width', 'count'],
        dflt: 'width',
        
        editType: 'calc',
        
    },

    spanmode: {
        valType: 'enumerated',
        values: ['soft', 'hard', 'manual'],
        dflt: 'soft',
        
        editType: 'calc',
        
    },
    span: {
        valType: 'info_array',
        items: [
            {valType: 'any', editType: 'calc'},
            {valType: 'any', editType: 'calc'}
        ],
        
        editType: 'calc',
        
    },

    line: {
        color: {
            valType: 'color',
            
            editType: 'style',
            
        },
        width: {
            valType: 'number',
            
            min: 0,
            dflt: 2,
            editType: 'style',
            
        },
        editType: 'plot'
    },
    fillcolor: boxAttrs.fillcolor,

    points: extendFlat({}, boxAttrs.boxpoints, {
        
    }),
    jitter: extendFlat({}, boxAttrs.jitter, {
        
    }),
    pointpos: extendFlat({}, boxAttrs.pointpos, {
        
    }),

    width: extendFlat({}, boxAttrs.width, {
        
    }),

    marker: boxAttrs.marker,
    text: boxAttrs.text,

    box: {
        visible: {
            valType: 'boolean',
            dflt: false,
            
            editType: 'plot',
            
        },
        width: {
            valType: 'number',
            min: 0,
            max: 1,
            dflt: 0.25,
            
            editType: 'plot',
            
        },
        fillcolor: {
            valType: 'color',
            
            editType: 'style',
            
        },
        line: {
            color: {
                valType: 'color',
                
                editType: 'style',
                
            },
            width: {
                valType: 'number',
                min: 0,
                
                editType: 'style',
                
            },
            editType: 'style'
        },
        editType: 'plot'
    },

    meanline: {
        visible: {
            valType: 'boolean',
            dflt: false,
            
            editType: 'plot',
            
        },
        color: {
            valType: 'color',
            
            editType: 'style',
            
        },
        width: {
            valType: 'number',
            min: 0,
            
            editType: 'style',
            
        },
        editType: 'plot'
    },

    side: {
        valType: 'enumerated',
        values: ['both', 'positive', 'negative'],
        dflt: 'both',
        
        editType: 'calc',
        
    },

    selected: boxAttrs.selected,
    unselected: boxAttrs.unselected,

    hoveron: {
        valType: 'flaglist',
        flags: ['violins', 'points', 'kde'],
        dflt: 'violins+points+kde',
        extras: ['all'],
        
        editType: 'style',
        
    }
};

},{"../../lib/extend":684,"../box/attributes":858}],1149:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');
var boxCalc = _dereq_('../box/calc');
var helpers = _dereq_('./helpers');
var BADNUM = _dereq_('../../constants/numerical').BADNUM;

module.exports = function calc(gd, trace) {
    var cd = boxCalc(gd, trace);

    if(cd[0].t.empty) return cd;

    var fullLayout = gd._fullLayout;
    var valAxis = Axes.getFromId(
        gd,
        trace[trace.orientation === 'h' ? 'xaxis' : 'yaxis']
    );

    var spanMin = Infinity;
    var spanMax = -Infinity;
    var maxKDE = 0;
    var maxCount = 0;

    for(var i = 0; i < cd.length; i++) {
        var cdi = cd[i];
        var vals = cdi.pts.map(helpers.extractVal);

        var bandwidth = cdi.bandwidth = calcBandwidth(trace, cdi, vals);
        var span = cdi.span = calcSpan(trace, cdi, valAxis, bandwidth);

        // step that well covers the bandwidth and is multiple of span distance
        var dist = span[1] - span[0];
        var n = Math.ceil(dist / (bandwidth / 3));
        var step = dist / n;

        if(!isFinite(step) || !isFinite(n)) {
            Lib.error('Something went wrong with computing the violin span');
            cd[0].t.empty = true;
            return cd;
        }

        var kde = helpers.makeKDE(cdi, trace, vals);
        cdi.density = new Array(n);

        for(var k = 0, t = span[0]; t < (span[1] + step / 2); k++, t += step) {
            var v = kde(t);
            cdi.density[k] = {v: v, t: t};
            maxKDE = Math.max(maxKDE, v);
        }

        maxCount = Math.max(maxCount, vals.length);
        spanMin = Math.min(spanMin, span[0]);
        spanMax = Math.max(spanMax, span[1]);
    }

    var extremes = Axes.findExtremes(valAxis, [spanMin, spanMax], {padded: true});
    trace._extremes[valAxis._id] = extremes;

    if(trace.width) {
        cd[0].t.maxKDE = maxKDE;
    } else {
        var violinScaleGroupStats = fullLayout._violinScaleGroupStats;
        var scaleGroup = trace.scalegroup;
        var groupStats = violinScaleGroupStats[scaleGroup];

        if(groupStats) {
            groupStats.maxKDE = Math.max(groupStats.maxKDE, maxKDE);
            groupStats.maxCount = Math.max(groupStats.maxCount, maxCount);
        } else {
            violinScaleGroupStats[scaleGroup] = {
                maxKDE: maxKDE,
                maxCount: maxCount
            };
        }
    }

    cd[0].t.labels.kde = Lib._(gd, 'kde:');

    return cd;
};

// Default to Silveman's rule of thumb
// - https://stats.stackexchange.com/a/6671
// - https://en.wikipedia.org/wiki/Kernel_density_estimation#A_rule-of-thumb_bandwidth_estimator
// - https://github.com/statsmodels/statsmodels/blob/master/statsmodels/nonparametric/bandwidths.py
function silvermanRule(len, ssd, iqr) {
    var a = Math.min(ssd, iqr / 1.349);
    return 1.059 * a * Math.pow(len, -0.2);
}

function calcBandwidth(trace, cdi, vals) {
    var span = cdi.max - cdi.min;

    // plot single-value violin with bandwidth of 1
    if(!span) return 1;

    // Limit how small the bandwidth can be.
    //
    // Silverman's rule of thumb can be "very" small
    // when IQR does a poor job at describing the spread
    // of the distribution.
    // We also want to limit custom bandwidths
    // to not blow up kde computations.

    if(trace.bandwidth) {
        return Math.max(trace.bandwidth, span / 1e4);
    } else {
        var len = vals.length;
        var ssd = Lib.stdev(vals, len - 1, cdi.mean);
        return Math.max(
            silvermanRule(len, ssd, cdi.q3 - cdi.q1),
            span / 100
        );
    }
}

function calcSpan(trace, cdi, valAxis, bandwidth) {
    var spanmode = trace.spanmode;
    var spanIn = trace.span || [];
    var spanTight = [cdi.min, cdi.max];
    var spanLoose = [cdi.min - 2 * bandwidth, cdi.max + 2 * bandwidth];
    var spanOut;

    function calcSpanItem(index) {
        var s = spanIn[index];
        var sc = valAxis.type === 'multicategory' ?
            valAxis.r2c(s) :
            valAxis.d2c(s, 0, trace[cdi.valLetter + 'calendar']);
        return sc === BADNUM ? spanLoose[index] : sc;
    }

    if(spanmode === 'soft') {
        spanOut = spanLoose;
    } else if(spanmode === 'hard') {
        spanOut = spanTight;
    } else {
        spanOut = [calcSpanItem(0), calcSpanItem(1)];
    }

    // to reuse the equal-range-item block
    var dummyAx = {
        type: 'linear',
        range: spanOut
    };
    Axes.setConvert(dummyAx);
    dummyAx.cleanRange();

    return spanOut;
}

},{"../../constants/numerical":671,"../../lib":694,"../../plots/cartesian/axes":742,"../box/calc":859,"./helpers":1152}],1150:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var setPositionOffset = _dereq_('../box/cross_trace_calc').setPositionOffset;
var orientations = ['v', 'h'];

module.exports = function crossTraceCalc(gd, plotinfo) {
    var calcdata = gd.calcdata;
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    for(var i = 0; i < orientations.length; i++) {
        var orientation = orientations[i];
        var posAxis = orientation === 'h' ? ya : xa;
        var violinList = [];

        for(var j = 0; j < calcdata.length; j++) {
            var cd = calcdata[j];
            var t = cd[0].t;
            var trace = cd[0].trace;

            if(trace.visible === true && trace.type === 'violin' &&
                    !t.empty &&
                    trace.orientation === orientation &&
                    trace.xaxis === xa._id &&
                    trace.yaxis === ya._id
              ) {
                violinList.push(j);
            }
        }

        setPositionOffset('violin', gd, violinList, posAxis);
    }
};

},{"../box/cross_trace_calc":860}],1151:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Color = _dereq_('../../components/color');

var boxDefaults = _dereq_('../box/defaults');
var attributes = _dereq_('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }
    function coerce2(attr, dflt) {
        return Lib.coerce2(traceIn, traceOut, attributes, attr, dflt);
    }

    boxDefaults.handleSampleDefaults(traceIn, traceOut, coerce, layout);
    if(traceOut.visible === false) return;

    coerce('bandwidth');
    coerce('side');

    var width = coerce('width');
    if(!width) {
        coerce('scalegroup', traceOut.name);
        coerce('scalemode');
    }

    var span = coerce('span');
    var spanmodeDflt;
    if(Array.isArray(span)) spanmodeDflt = 'manual';
    coerce('spanmode', spanmodeDflt);

    var lineColor = coerce('line.color', (traceIn.marker || {}).color || defaultColor);
    var lineWidth = coerce('line.width');
    var fillColor = coerce('fillcolor', Color.addOpacity(traceOut.line.color, 0.5));

    boxDefaults.handlePointsDefaults(traceIn, traceOut, coerce, {prefix: ''});

    var boxWidth = coerce2('box.width');
    var boxFillColor = coerce2('box.fillcolor', fillColor);
    var boxLineColor = coerce2('box.line.color', lineColor);
    var boxLineWidth = coerce2('box.line.width', lineWidth);
    var boxVisible = coerce('box.visible', Boolean(boxWidth || boxFillColor || boxLineColor || boxLineWidth));
    if(!boxVisible) traceOut.box = {visible: false};

    var meanLineColor = coerce2('meanline.color', lineColor);
    var meanLineWidth = coerce2('meanline.width', lineWidth);
    var meanLineVisible = coerce('meanline.visible', Boolean(meanLineColor || meanLineWidth));
    if(!meanLineVisible) traceOut.meanline = {visible: false};
};

},{"../../components/color":571,"../../lib":694,"../box/defaults":861,"./attributes":1148}],1152:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');

// Maybe add kernels more down the road,
// but note that the default `spanmode: 'soft'` bounds might have
// to become kernel-dependent
var kernels = {
    gaussian: function(v) {
        return (1 / Math.sqrt(2 * Math.PI)) * Math.exp(-0.5 * v * v);
    }
};

exports.makeKDE = function(calcItem, trace, vals) {
    var len = vals.length;
    var kernel = kernels.gaussian;
    var bandwidth = calcItem.bandwidth;
    var factor = 1 / (len * bandwidth);

    // don't use Lib.aggNums to skip isNumeric checks
    return function(x) {
        var sum = 0;
        for(var i = 0; i < len; i++) {
            sum += kernel((x - vals[i]) / bandwidth);
        }
        return factor * sum;
    };
};

exports.getPositionOnKdePath = function(calcItem, trace, valuePx) {
    var posLetter, valLetter;

    if(trace.orientation === 'h') {
        posLetter = 'y';
        valLetter = 'x';
    } else {
        posLetter = 'x';
        valLetter = 'y';
    }

    var pointOnPath = Lib.findPointOnPath(
        calcItem.path,
        valuePx,
        valLetter,
        {pathLength: calcItem.pathLength}
    );

    var posCenterPx = calcItem.posCenterPx;
    var posOnPath0 = pointOnPath[posLetter];
    var posOnPath1 = trace.side === 'both' ?
        2 * posCenterPx - posOnPath0 :
        posCenterPx;

    return [posOnPath0, posOnPath1];
};

exports.getKdeValue = function(calcItem, trace, valueDist) {
    var vals = calcItem.pts.map(exports.extractVal);
    var kde = exports.makeKDE(calcItem, trace, vals);
    return kde(valueDist) / calcItem.posDensityScale;
};

exports.extractVal = function(o) { return o.v; };

},{"../../lib":694}],1153:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var Axes = _dereq_('../../plots/cartesian/axes');
var boxHoverPoints = _dereq_('../box/hover');
var helpers = _dereq_('./helpers');

module.exports = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer) {
    var cd = pointData.cd;
    var trace = cd[0].trace;
    var hoveron = trace.hoveron;
    var hasHoveronViolins = hoveron.indexOf('violins') !== -1;
    var hasHoveronKDE = hoveron.indexOf('kde') !== -1;
    var closeData = [];
    var closePtData;
    var violinLineAttrs;

    if(hasHoveronViolins || hasHoveronKDE) {
        var closeBoxData = boxHoverPoints.hoverOnBoxes(pointData, xval, yval, hovermode);

        if(hasHoveronViolins) {
            closeData = closeData.concat(closeBoxData);
        }

        if(hasHoveronKDE && closeBoxData.length > 0) {
            var xa = pointData.xa;
            var ya = pointData.ya;
            var pLetter, vLetter, pAxis, vAxis, vVal;

            if(trace.orientation === 'h') {
                vVal = xval;
                pLetter = 'y';
                pAxis = ya;
                vLetter = 'x';
                vAxis = xa;
            } else {
                vVal = yval;
                pLetter = 'x';
                pAxis = xa;
                vLetter = 'y';
                vAxis = ya;
            }

            var di = cd[pointData.index];

            if(vVal >= di.span[0] && vVal <= di.span[1]) {
                var kdePointData = Lib.extendFlat({}, pointData);
                var vValPx = vAxis.c2p(vVal, true);
                var kdeVal = helpers.getKdeValue(di, trace, vVal);
                var pOnPath = helpers.getPositionOnKdePath(di, trace, vValPx);
                var paOffset = pAxis._offset;
                var paLength = pAxis._length;

                kdePointData[pLetter + '0'] = pOnPath[0];
                kdePointData[pLetter + '1'] = pOnPath[1];
                kdePointData[vLetter + '0'] = kdePointData[vLetter + '1'] = vValPx;
                kdePointData[vLetter + 'Label'] = vLetter + ': ' + Axes.hoverLabelText(vAxis, vVal) + ', ' + cd[0].t.labels.kde + ' ' + kdeVal.toFixed(3);

                // move the spike to the KDE point
                kdePointData.spikeDistance = closeBoxData[0].spikeDistance;
                var spikePosAttr = pLetter + 'Spike';
                kdePointData[spikePosAttr] = closeBoxData[0][spikePosAttr];
                closeBoxData[0].spikeDistance = undefined;
                closeBoxData[0][spikePosAttr] = undefined;

                closeData.push(kdePointData);

                violinLineAttrs = {stroke: pointData.color};
                violinLineAttrs[pLetter + '1'] = Lib.constrain(paOffset + pOnPath[0], paOffset, paOffset + paLength);
                violinLineAttrs[pLetter + '2'] = Lib.constrain(paOffset + pOnPath[1], paOffset, paOffset + paLength);
                violinLineAttrs[vLetter + '1'] = violinLineAttrs[vLetter + '2'] = vAxis._offset + vValPx;
            }
        }
    }

    if(hoveron.indexOf('points') !== -1) {
        closePtData = boxHoverPoints.hoverOnPoints(pointData, xval, yval);
    }

    // update violin line (if any)
    var violinLine = hoverLayer.selectAll('.violinline-' + trace.uid)
        .data(violinLineAttrs ? [0] : []);
    violinLine.enter().append('line')
        .classed('violinline-' + trace.uid, true)
        .attr('stroke-width', 1.5);
    violinLine.exit().remove();
    violinLine.attr(violinLineAttrs);

    // same combine logic as box hoverPoints
    if(hovermode === 'closest') {
        if(closePtData) return [closePtData];
        return closeData;
    }
    if(closePtData) {
        closeData.push(closePtData);
        return closeData;
    }
    return closeData;
};

},{"../../lib":694,"../../plots/cartesian/axes":742,"../box/hover":863,"./helpers":1152}],1154:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    attributes: _dereq_('./attributes'),
    layoutAttributes: _dereq_('./layout_attributes'),
    supplyDefaults: _dereq_('./defaults'),
    supplyLayoutDefaults: _dereq_('./layout_defaults'),
    calc: _dereq_('./calc'),
    crossTraceCalc: _dereq_('./cross_trace_calc'),
    plot: _dereq_('./plot'),
    style: _dereq_('./style'),
    styleOnSelect: _dereq_('../scatter/style').styleOnSelect,
    hoverPoints: _dereq_('./hover'),
    selectPoints: _dereq_('../box/select'),

    moduleType: 'trace',
    name: 'violin',
    basePlotModule: _dereq_('../../plots/cartesian'),
    categories: ['cartesian', 'svg', 'symbols', 'oriented', 'box-violin', 'showLegend', 'violinLayout', 'zoomScale'],
    meta: {
        
    }
};

},{"../../plots/cartesian":754,"../box/select":868,"../scatter/style":1070,"./attributes":1148,"./calc":1149,"./cross_trace_calc":1150,"./defaults":1151,"./hover":1153,"./layout_attributes":1155,"./layout_defaults":1156,"./plot":1157,"./style":1158}],1155:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var boxLayoutAttrs = _dereq_('../box/layout_attributes');
var extendFlat = _dereq_('../../lib').extendFlat;

module.exports = {
    violinmode: extendFlat({}, boxLayoutAttrs.boxmode, {
        
    }),
    violingap: extendFlat({}, boxLayoutAttrs.boxgap, {
        
    }),
    violingroupgap: extendFlat({}, boxLayoutAttrs.boxgroupgap, {
        
    })
};

},{"../../lib":694,"../box/layout_attributes":865}],1156:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../../lib');
var layoutAttributes = _dereq_('./layout_attributes');
var boxLayoutDefaults = _dereq_('../box/layout_defaults');

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
    function coerce(attr, dflt) {
        return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
    }
    boxLayoutDefaults._supply(layoutIn, layoutOut, fullData, coerce, 'violin');
};

},{"../../lib":694,"../box/layout_defaults":866,"./layout_attributes":1155}],1157:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var Lib = _dereq_('../../lib');
var Drawing = _dereq_('../../components/drawing');

var boxPlot = _dereq_('../box/plot');
var linePoints = _dereq_('../scatter/line_points');
var helpers = _dereq_('./helpers');

module.exports = function plot(gd, plotinfo, cdViolins, violinLayer) {
    var fullLayout = gd._fullLayout;
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    function makePath(pts) {
        var segments = linePoints(pts, {
            xaxis: xa,
            yaxis: ya,
            connectGaps: true,
            baseTolerance: 0.75,
            shape: 'spline',
            simplify: true
        });
        return Drawing.smoothopen(segments[0], 1);
    }

    Lib.makeTraceGroups(violinLayer, cdViolins, 'trace violins').each(function(cd) {
        var plotGroup = d3.select(this);
        var cd0 = cd[0];
        var t = cd0.t;
        var trace = cd0.trace;
        if(!plotinfo.isRangePlot) cd0.node3 = plotGroup;

        if(trace.visible !== true || t.empty) {
            plotGroup.remove();
            return;
        }

        var bPos = t.bPos;
        var bdPos = t.bdPos;
        var valAxis = plotinfo[t.valLetter + 'axis'];
        var posAxis = plotinfo[t.posLetter + 'axis'];
        var hasBothSides = trace.side === 'both';
        var hasPositiveSide = hasBothSides || trace.side === 'positive';
        var hasNegativeSide = hasBothSides || trace.side === 'negative';

        var violins = plotGroup.selectAll('path.violin').data(Lib.identity);

        violins.enter().append('path')
            .style('vector-effect', 'non-scaling-stroke')
            .attr('class', 'violin');

        violins.exit().remove();

        violins.each(function(d) {
            var pathSel = d3.select(this);
            var density = d.density;
            var len = density.length;
            var posCenter = d.pos + bPos;
            var posCenterPx = posAxis.c2p(posCenter);

            var scale;
            if(trace.width) {
                scale = t.maxKDE / bdPos;
            } else {
                var groupStats = fullLayout._violinScaleGroupStats[trace.scalegroup];
                scale = trace.scalemode === 'count' ?
                    (groupStats.maxKDE / bdPos) * (groupStats.maxCount / d.pts.length) :
                    groupStats.maxKDE / bdPos;
            }

            var pathPos, pathNeg, path;
            var i, k, pts, pt;

            if(hasPositiveSide) {
                pts = new Array(len);
                for(i = 0; i < len; i++) {
                    pt = pts[i] = {};
                    pt[t.posLetter] = posCenter + (density[i].v / scale);
                    pt[t.valLetter] = density[i].t;
                }
                pathPos = makePath(pts);
            }

            if(hasNegativeSide) {
                pts = new Array(len);
                for(k = 0, i = len - 1; k < len; k++, i--) {
                    pt = pts[k] = {};
                    pt[t.posLetter] = posCenter - (density[i].v / scale);
                    pt[t.valLetter] = density[i].t;
                }
                pathNeg = makePath(pts);
            }

            if(hasBothSides) {
                path = pathPos + 'L' + pathNeg.substr(1) + 'Z';
            }
            else {
                var startPt = [posCenterPx, valAxis.c2p(density[0].t)];
                var endPt = [posCenterPx, valAxis.c2p(density[len - 1].t)];

                if(trace.orientation === 'h') {
                    startPt.reverse();
                    endPt.reverse();
                }

                if(hasPositiveSide) {
                    path = 'M' + startPt + 'L' + pathPos.substr(1) + 'L' + endPt;
                } else {
                    path = 'M' + endPt + 'L' + pathNeg.substr(1) + 'L' + startPt;
                }
            }
            pathSel.attr('d', path);

            // save a few things used in getPositionOnKdePath, getKdeValue
            // on hover and for meanline draw block below
            d.posCenterPx = posCenterPx;
            d.posDensityScale = scale * bdPos;
            d.path = pathSel.node();
            d.pathLength = d.path.getTotalLength() / (hasBothSides ? 2 : 1);
        });

        var boxAttrs = trace.box;
        var boxWidth = boxAttrs.width;
        var boxLineWidth = (boxAttrs.line || {}).width;
        var bdPosScaled;
        var bPosPxOffset;

        if(hasBothSides) {
            bdPosScaled = bdPos * boxWidth;
            bPosPxOffset = 0;
        } else if(hasPositiveSide) {
            bdPosScaled = [0, bdPos * boxWidth / 2];
            bPosPxOffset = -boxLineWidth;
        } else {
            bdPosScaled = [bdPos * boxWidth / 2, 0];
            bPosPxOffset = boxLineWidth;
        }

        // inner box
        boxPlot.plotBoxAndWhiskers(plotGroup, {pos: posAxis, val: valAxis}, trace, {
            bPos: bPos,
            bdPos: bdPosScaled,
            bPosPxOffset: bPosPxOffset
        });

        // meanline insider box
        boxPlot.plotBoxMean(plotGroup, {pos: posAxis, val: valAxis}, trace, {
            bPos: bPos,
            bdPos: bdPosScaled,
            bPosPxOffset: bPosPxOffset
        });

        var fn;
        if(!trace.box.visible && trace.meanline.visible) {
            fn = Lib.identity;
        }

        // N.B. use different class name than boxPlot.plotBoxMean,
        // to avoid selectAll conflict
        var meanPaths = plotGroup.selectAll('path.meanline').data(fn || []);
        meanPaths.enter().append('path')
            .attr('class', 'meanline')
            .style('fill', 'none')
            .style('vector-effect', 'non-scaling-stroke');
        meanPaths.exit().remove();
        meanPaths.each(function(d) {
            var v = valAxis.c2p(d.mean, true);
            var p = helpers.getPositionOnKdePath(d, trace, v);

            d3.select(this).attr('d',
                trace.orientation === 'h' ?
                    'M' + v + ',' + p[0] + 'V' + p[1] :
                    'M' + p[0] + ',' + v + 'H' + p[1]
            );
        });

        boxPlot.plotPoints(plotGroup, {x: xa, y: ya}, trace, t);
    });
};

},{"../../components/drawing":592,"../../lib":694,"../box/plot":867,"../scatter/line_points":1061,"./helpers":1152,"d3":149}],1158:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = _dereq_('d3');
var Color = _dereq_('../../components/color');
var stylePoints = _dereq_('../scatter/style').stylePoints;

module.exports = function style(gd, cd) {
    var s = cd ? cd[0].node3 : d3.select(gd).selectAll('g.trace.violins');

    s.style('opacity', function(d) { return d[0].trace.opacity; });

    s.each(function(d) {
        var trace = d[0].trace;
        var sel = d3.select(this);
        var box = trace.box || {};
        var boxLine = box.line || {};
        var meanline = trace.meanline || {};
        var meanLineWidth = meanline.width;

        sel.selectAll('path.violin')
            .style('stroke-width', trace.line.width + 'px')
            .call(Color.stroke, trace.line.color)
            .call(Color.fill, trace.fillcolor);

        sel.selectAll('path.box')
            .style('stroke-width', boxLine.width + 'px')
            .call(Color.stroke, boxLine.color)
            .call(Color.fill, box.fillcolor);

        var meanLineStyle = {
            'stroke-width': meanLineWidth + 'px',
            'stroke-dasharray': (2 * meanLineWidth) + 'px,' + meanLineWidth + 'px'
        };

        sel.selectAll('path.mean')
            .style(meanLineStyle)
            .call(Color.stroke, meanline.color);

        sel.selectAll('path.meanline')
            .style(meanLineStyle)
            .call(Color.stroke, meanline.color);

        stylePoints(sel, trace, gd);
    });
};

},{"../../components/color":571,"../scatter/style":1070,"d3":149}],1159:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Axes = _dereq_('../plots/cartesian/axes');
var Lib = _dereq_('../lib');
var PlotSchema = _dereq_('../plot_api/plot_schema');
var pointsAccessorFunction = _dereq_('./helpers').pointsAccessorFunction;
var BADNUM = _dereq_('../constants/numerical').BADNUM;

exports.moduleType = 'transform';

exports.name = 'aggregate';

var attrs = exports.attributes = {
    enabled: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'calc',
        
    },
    groups: {
        // TODO: groupby should support string or array grouping this way too
        // currently groupby only allows a grouping array
        valType: 'string',
        strict: true,
        noBlank: true,
        arrayOk: true,
        dflt: 'x',
        
        editType: 'calc',
        
    },
    aggregations: {
        _isLinkedToArray: 'aggregation',
        target: {
            valType: 'string',
            
            editType: 'calc',
            
        },
        func: {
            valType: 'enumerated',
            values: ['count', 'sum', 'avg', 'median', 'mode', 'rms', 'stddev', 'min', 'max', 'first', 'last', 'change', 'range'],
            dflt: 'first',
            
            editType: 'calc',
            
        },
        funcmode: {
            valType: 'enumerated',
            values: ['sample', 'population'],
            dflt: 'sample',
            
            editType: 'calc',
            
        },
        enabled: {
            valType: 'boolean',
            dflt: true,
            
            editType: 'calc',
            
        },
        editType: 'calc'
    },
    editType: 'calc'
};

var aggAttrs = attrs.aggregations;

/**
 * Supply transform attributes defaults
 *
 * @param {object} transformIn
 *  object linked to trace.transforms[i] with 'func' set to exports.name
 * @param {object} traceOut
 *  the _fullData trace this transform applies to
 * @param {object} layout
 *  the plot's (not-so-full) layout
 * @param {object} traceIn
 *  the input data trace this transform applies to
 *
 * @return {object} transformOut
 *  copy of transformIn that contains attribute defaults
 */
exports.supplyDefaults = function(transformIn, traceOut) {
    var transformOut = {};
    var i;

    function coerce(attr, dflt) {
        return Lib.coerce(transformIn, transformOut, attrs, attr, dflt);
    }

    var enabled = coerce('enabled');

    if(!enabled) return transformOut;

    /*
     * Normally _arrayAttrs is calculated during doCalc, but that comes later.
     * Anyway this can change due to *count* aggregations (see below) so it's not
     * necessarily the same set.
     *
     * For performance we turn it into an object of truthy values
     * we'll use 1 for arrays we haven't aggregated yet, 0 for finished arrays,
     * as distinct from undefined which means this array isn't present in the input
     * missing arrays can still be aggregate outputs for *count* aggregations.
     */
    var arrayAttrArray = PlotSchema.findArrayAttributes(traceOut);
    var arrayAttrs = {};
    for(i = 0; i < arrayAttrArray.length; i++) arrayAttrs[arrayAttrArray[i]] = 1;

    var groups = coerce('groups');

    if(!Array.isArray(groups)) {
        if(!arrayAttrs[groups]) {
            transformOut.enabled = false;
            return transformOut;
        }
        arrayAttrs[groups] = 0;
    }

    var aggregationsIn = transformIn.aggregations || [];
    var aggregationsOut = transformOut.aggregations = new Array(aggregationsIn.length);
    var aggregationOut;

    function coercei(attr, dflt) {
        return Lib.coerce(aggregationsIn[i], aggregationOut, aggAttrs, attr, dflt);
    }

    for(i = 0; i < aggregationsIn.length; i++) {
        aggregationOut = {_index: i};
        var target = coercei('target');
        var func = coercei('func');
        var enabledi = coercei('enabled');

        // add this aggregation to the output only if it's the first instance
        // of a valid target attribute - or an unused target attribute with "count"
        if(enabledi && target && (arrayAttrs[target] || (func === 'count' && arrayAttrs[target] === undefined))) {
            if(func === 'stddev') coercei('funcmode');

            arrayAttrs[target] = 0;
            aggregationsOut[i] = aggregationOut;
        }
        else aggregationsOut[i] = {enabled: false, _index: i};
    }

    // any array attributes we haven't yet covered, fill them with the default aggregation
    for(i = 0; i < arrayAttrArray.length; i++) {
        if(arrayAttrs[arrayAttrArray[i]]) {
            aggregationsOut.push({
                target: arrayAttrArray[i],
                func: aggAttrs.func.dflt,
                enabled: true,
                _index: -1
            });
        }
    }

    return transformOut;
};


exports.calcTransform = function(gd, trace, opts) {
    if(!opts.enabled) return;

    var groups = opts.groups;

    var groupArray = Lib.getTargetArray(trace, {target: groups});
    if(!groupArray) return;

    var i, vi, groupIndex, newGrouping;

    var groupIndices = {};
    var indexToPoints = {};
    var groupings = [];

    var originalPointsAccessor = pointsAccessorFunction(trace.transforms, opts);

    var len = groupArray.length;
    if(trace._length) len = Math.min(len, trace._length);

    for(i = 0; i < len; i++) {
        vi = groupArray[i];
        groupIndex = groupIndices[vi];
        if(groupIndex === undefined) {
            groupIndices[vi] = groupings.length;
            newGrouping = [i];
            groupings.push(newGrouping);
            indexToPoints[groupIndices[vi]] = originalPointsAccessor(i);
        }
        else {
            groupings[groupIndex].push(i);
            indexToPoints[groupIndices[vi]] = (indexToPoints[groupIndices[vi]] || []).concat(originalPointsAccessor(i));
        }
    }

    opts._indexToPoints = indexToPoints;

    var aggregations = opts.aggregations;

    for(i = 0; i < aggregations.length; i++) {
        aggregateOneArray(gd, trace, groupings, aggregations[i]);
    }

    if(typeof groups === 'string') {
        aggregateOneArray(gd, trace, groupings, {
            target: groups,
            func: 'first',
            enabled: true
        });
    }

    trace._length = groupings.length;
};

function aggregateOneArray(gd, trace, groupings, aggregation) {
    if(!aggregation.enabled) return;

    var attr = aggregation.target;
    var targetNP = Lib.nestedProperty(trace, attr);
    var arrayIn = targetNP.get();
    var conversions = Axes.getDataConversions(gd, trace, attr, arrayIn);
    var func = getAggregateFunction(aggregation, conversions);

    var arrayOut = new Array(groupings.length);
    for(var i = 0; i < groupings.length; i++) {
        arrayOut[i] = func(arrayIn, groupings[i]);
    }
    targetNP.set(arrayOut);

    if(aggregation.func === 'count') {
        // count does not depend on an input array, so it's likely not part of _arrayAttrs yet
        // but after this transform it most definitely *is* an array attribute.
        Lib.pushUnique(trace._arrayAttrs, attr);
    }
}

function getAggregateFunction(opts, conversions) {
    var func = opts.func;
    var d2c = conversions.d2c;
    var c2d = conversions.c2d;

    switch(func) {
        // count, first, and last don't depend on anything about the data
        // point back to pure functions for performance
        case 'count':
            return count;
        case 'first':
            return first;
        case 'last':
            return last;

        case 'sum':
            // This will produce output in all cases even though it's nonsensical
            // for date or category data.
            return function(array, indices) {
                var total = 0;
                for(var i = 0; i < indices.length; i++) {
                    var vi = d2c(array[indices[i]]);
                    if(vi !== BADNUM) total += vi;
                }
                return c2d(total);
            };

        case 'avg':
            // Generally meaningless for category data but it still does something.
            return function(array, indices) {
                var total = 0;
                var cnt = 0;
                for(var i = 0; i < indices.length; i++) {
                    var vi = d2c(array[indices[i]]);
                    if(vi !== BADNUM) {
                        total += vi;
                        cnt++;
                    }
                }
                return cnt ? c2d(total / cnt) : BADNUM;
            };

        case 'min':
            return function(array, indices) {
                var out = Infinity;
                for(var i = 0; i < indices.length; i++) {
                    var vi = d2c(array[indices[i]]);
                    if(vi !== BADNUM) out = Math.min(out, vi);
                }
                return (out === Infinity) ? BADNUM : c2d(out);
            };

        case 'max':
            return function(array, indices) {
                var out = -Infinity;
                for(var i = 0; i < indices.length; i++) {
                    var vi = d2c(array[indices[i]]);
                    if(vi !== BADNUM) out = Math.max(out, vi);
                }
                return (out === -Infinity) ? BADNUM : c2d(out);
            };

        case 'range':
            return function(array, indices) {
                var min = Infinity;
                var max = -Infinity;
                for(var i = 0; i < indices.length; i++) {
                    var vi = d2c(array[indices[i]]);
                    if(vi !== BADNUM) {
                        min = Math.min(min, vi);
                        max = Math.max(max, vi);
                    }
                }
                return (max === -Infinity || min === Infinity) ? BADNUM : c2d(max - min);
            };

        case 'change':
            return function(array, indices) {
                var first = d2c(array[indices[0]]);
                var last = d2c(array[indices[indices.length - 1]]);
                return (first === BADNUM || last === BADNUM) ? BADNUM : c2d(last - first);
            };

        case 'median':
            return function(array, indices) {
                var sortCalc = [];
                for(var i = 0; i < indices.length; i++) {
                    var vi = d2c(array[indices[i]]);
                    if(vi !== BADNUM) sortCalc.push(vi);
                }
                if(!sortCalc.length) return BADNUM;
                sortCalc.sort();
                var mid = (sortCalc.length - 1) / 2;
                return c2d((sortCalc[Math.floor(mid)] + sortCalc[Math.ceil(mid)]) / 2);
            };

        case 'mode':
            return function(array, indices) {
                var counts = {};
                var maxCnt = 0;
                var out = BADNUM;
                for(var i = 0; i < indices.length; i++) {
                    var vi = d2c(array[indices[i]]);
                    if(vi !== BADNUM) {
                        var counti = counts[vi] = (counts[vi] || 0) + 1;
                        if(counti > maxCnt) {
                            maxCnt = counti;
                            out = vi;
                        }
                    }
                }
                return maxCnt ? c2d(out) : BADNUM;
            };

        case 'rms':
            return function(array, indices) {
                var total = 0;
                var cnt = 0;
                for(var i = 0; i < indices.length; i++) {
                    var vi = d2c(array[indices[i]]);
                    if(vi !== BADNUM) {
                        total += vi * vi;
                        cnt++;
                    }
                }
                return cnt ? c2d(Math.sqrt(total / cnt)) : BADNUM;
            };

        case 'stddev':
            return function(array, indices) {
                // balance numerical stability with performance:
                // so that we call d2c once per element but don't need to
                // store them, reference all to the first element
                var total = 0;
                var total2 = 0;
                var cnt = 1;
                var v0 = BADNUM;
                var i;
                for(i = 0; i < indices.length && v0 === BADNUM; i++) {
                    v0 = d2c(array[indices[i]]);
                }
                if(v0 === BADNUM) return BADNUM;

                for(; i < indices.length; i++) {
                    var vi = d2c(array[indices[i]]);
                    if(vi !== BADNUM) {
                        var dv = vi - v0;
                        total += dv;
                        total2 += dv * dv;
                        cnt++;
                    }
                }

                // This is population std dev, if we want sample std dev
                // we would need (...) / (cnt - 1)
                // Also note there's no c2d here - that means for dates the result
                // is a number of milliseconds, and for categories it's a number
                // of category differences, which is not generically meaningful but
                // as in other cases we don't forbid it.
                var norm = (opts.funcmode === 'sample') ? (cnt - 1) : cnt;
                // this is debatable: should a count of 1 return sample stddev of
                // 0 or undefined?
                if(!norm) return 0;
                return Math.sqrt((total2 - (total * total / cnt)) / norm);
            };
    }
}

function count(array, indices) {
    return indices.length;
}

function first(array, indices) {
    return array[indices[0]];
}

function last(array, indices) {
    return array[indices[indices.length - 1]];
}

},{"../constants/numerical":671,"../lib":694,"../plot_api/plot_schema":731,"../plots/cartesian/axes":742,"./helpers":1162}],1160:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../lib');
var Registry = _dereq_('../registry');
var Axes = _dereq_('../plots/cartesian/axes');
var pointsAccessorFunction = _dereq_('./helpers').pointsAccessorFunction;

var filterOps = _dereq_('../constants/filter_ops');
var COMPARISON_OPS = filterOps.COMPARISON_OPS;
var INTERVAL_OPS = filterOps.INTERVAL_OPS;
var SET_OPS = filterOps.SET_OPS;

exports.moduleType = 'transform';

exports.name = 'filter';

exports.attributes = {
    enabled: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'calc',
        
    },
    target: {
        valType: 'string',
        strict: true,
        noBlank: true,
        arrayOk: true,
        dflt: 'x',
        
        editType: 'calc',
        
    },
    operation: {
        valType: 'enumerated',
        values: []
            .concat(COMPARISON_OPS)
            .concat(INTERVAL_OPS)
            .concat(SET_OPS),
        dflt: '=',
        
        editType: 'calc',
        
    },
    value: {
        valType: 'any',
        dflt: 0,
        
        editType: 'calc',
        
    },
    preservegaps: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'calc',
        
    },
    editType: 'calc'
};

exports.supplyDefaults = function(transformIn) {
    var transformOut = {};

    function coerce(attr, dflt) {
        return Lib.coerce(transformIn, transformOut, exports.attributes, attr, dflt);
    }

    var enabled = coerce('enabled');

    if(enabled) {
        coerce('preservegaps');
        coerce('operation');
        coerce('value');
        coerce('target');

        var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleDefaults');
        handleCalendarDefaults(transformIn, transformOut, 'valuecalendar', null);
        handleCalendarDefaults(transformIn, transformOut, 'targetcalendar', null);
    }

    return transformOut;
};

exports.calcTransform = function(gd, trace, opts) {
    if(!opts.enabled) return;

    var targetArray = Lib.getTargetArray(trace, opts);
    if(!targetArray) return;

    var target = opts.target;

    var len = targetArray.length;
    if(trace._length) len = Math.min(len, trace._length);

    var targetCalendar = opts.targetcalendar;
    var arrayAttrs = trace._arrayAttrs;
    var preservegaps = opts.preservegaps;

    // even if you provide targetcalendar, if target is a string and there
    // is a calendar attribute matching target it will get used instead.
    if(typeof target === 'string') {
        var attrTargetCalendar = Lib.nestedProperty(trace, target + 'calendar').get();
        if(attrTargetCalendar) targetCalendar = attrTargetCalendar;
    }

    var d2c = Axes.getDataToCoordFunc(gd, trace, target, targetArray);
    var filterFunc = getFilterFunc(opts, d2c, targetCalendar);
    var originalArrays = {};
    var indexToPoints = {};
    var index = 0;

    function forAllAttrs(fn, index) {
        for(var j = 0; j < arrayAttrs.length; j++) {
            var np = Lib.nestedProperty(trace, arrayAttrs[j]);
            fn(np, index);
        }
    }

    var initFn;
    var fillFn;
    if(preservegaps) {
        initFn = function(np) {
            originalArrays[np.astr] = Lib.extendDeep([], np.get());
            np.set(new Array(len));
        };
        fillFn = function(np, index) {
            var val = originalArrays[np.astr][index];
            np.get()[index] = val;
        };
    } else {
        initFn = function(np) {
            originalArrays[np.astr] = Lib.extendDeep([], np.get());
            np.set([]);
        };
        fillFn = function(np, index) {
            var val = originalArrays[np.astr][index];
            np.get().push(val);
        };
    }

    // copy all original array attribute values, and clear arrays in trace
    forAllAttrs(initFn);

    var originalPointsAccessor = pointsAccessorFunction(trace.transforms, opts);

    // loop through filter array, fill trace arrays if passed
    for(var i = 0; i < len; i++) {
        var passed = filterFunc(targetArray[i]);
        if(passed) {
            forAllAttrs(fillFn, i);
            indexToPoints[index++] = originalPointsAccessor(i);
        }
        else if(preservegaps) index++;
    }

    opts._indexToPoints = indexToPoints;
    trace._length = index;
};

function getFilterFunc(opts, d2c, targetCalendar) {
    var operation = opts.operation;
    var value = opts.value;
    var hasArrayValue = Array.isArray(value);

    function isOperationIn(array) {
        return array.indexOf(operation) !== -1;
    }

    var d2cValue = function(v) { return d2c(v, 0, opts.valuecalendar); };
    var d2cTarget = function(v) { return d2c(v, 0, targetCalendar); };

    var coercedValue;

    if(isOperationIn(COMPARISON_OPS)) {
        coercedValue = hasArrayValue ? d2cValue(value[0]) : d2cValue(value);
    }
    else if(isOperationIn(INTERVAL_OPS)) {
        coercedValue = hasArrayValue ?
            [d2cValue(value[0]), d2cValue(value[1])] :
            [d2cValue(value), d2cValue(value)];
    }
    else if(isOperationIn(SET_OPS)) {
        coercedValue = hasArrayValue ? value.map(d2cValue) : [d2cValue(value)];
    }

    switch(operation) {

        case '=':
            return function(v) { return d2cTarget(v) === coercedValue; };

        case '!=':
            return function(v) { return d2cTarget(v) !== coercedValue; };

        case '<':
            return function(v) { return d2cTarget(v) < coercedValue; };

        case '<=':
            return function(v) { return d2cTarget(v) <= coercedValue; };

        case '>':
            return function(v) { return d2cTarget(v) > coercedValue; };

        case '>=':
            return function(v) { return d2cTarget(v) >= coercedValue; };

        case '[]':
            return function(v) {
                var cv = d2cTarget(v);
                return cv >= coercedValue[0] && cv <= coercedValue[1];
            };

        case '()':
            return function(v) {
                var cv = d2cTarget(v);
                return cv > coercedValue[0] && cv < coercedValue[1];
            };

        case '[)':
            return function(v) {
                var cv = d2cTarget(v);
                return cv >= coercedValue[0] && cv < coercedValue[1];
            };

        case '(]':
            return function(v) {
                var cv = d2cTarget(v);
                return cv > coercedValue[0] && cv <= coercedValue[1];
            };

        case '][':
            return function(v) {
                var cv = d2cTarget(v);
                return cv <= coercedValue[0] || cv >= coercedValue[1];
            };

        case ')(':
            return function(v) {
                var cv = d2cTarget(v);
                return cv < coercedValue[0] || cv > coercedValue[1];
            };

        case '](':
            return function(v) {
                var cv = d2cTarget(v);
                return cv <= coercedValue[0] || cv > coercedValue[1];
            };

        case ')[':
            return function(v) {
                var cv = d2cTarget(v);
                return cv < coercedValue[0] || cv >= coercedValue[1];
            };

        case '{}':
            return function(v) {
                return coercedValue.indexOf(d2cTarget(v)) !== -1;
            };

        case '}{':
            return function(v) {
                return coercedValue.indexOf(d2cTarget(v)) === -1;
            };
    }
}

},{"../constants/filter_ops":667,"../lib":694,"../plots/cartesian/axes":742,"../registry":825,"./helpers":1162}],1161:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../lib');
var PlotSchema = _dereq_('../plot_api/plot_schema');
var Plots = _dereq_('../plots/plots');
var pointsAccessorFunction = _dereq_('./helpers').pointsAccessorFunction;

exports.moduleType = 'transform';

exports.name = 'groupby';

exports.attributes = {
    enabled: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'calc',
        
    },
    groups: {
        valType: 'data_array',
        dflt: [],
        
        editType: 'calc',
        
    },
    nameformat: {
        valType: 'string',
        
        editType: 'calc',
        
    },
    styles: {
        _isLinkedToArray: 'style',
        target: {
            valType: 'string',
            
            editType: 'calc',
            
        },
        value: {
            valType: 'any',
            
            dflt: {},
            editType: 'calc',
            
            _compareAsJSON: true
        },
        editType: 'calc'
    },
    editType: 'calc'
};

/**
 * Supply transform attributes defaults
 *
 * @param {object} transformIn
 *  object linked to trace.transforms[i] with 'type' set to exports.name
 * @param {object} traceOut
 *  the _fullData trace this transform applies to
 * @param {object} layout
 *  the plot's (not-so-full) layout
 * @param {object} traceIn
 *  the input data trace this transform applies to
 *
 * @return {object} transformOut
 *  copy of transformIn that contains attribute defaults
 */
exports.supplyDefaults = function(transformIn, traceOut, layout) {
    var i;
    var transformOut = {};

    function coerce(attr, dflt) {
        return Lib.coerce(transformIn, transformOut, exports.attributes, attr, dflt);
    }

    var enabled = coerce('enabled');

    if(!enabled) return transformOut;

    coerce('groups');
    coerce('nameformat', layout._dataLength > 1 ? '%{group} (%{trace})' : '%{group}');

    var styleIn = transformIn.styles;
    var styleOut = transformOut.styles = [];

    if(styleIn) {
        for(i = 0; i < styleIn.length; i++) {
            var thisStyle = styleOut[i] = {};
            Lib.coerce(styleIn[i], styleOut[i], exports.attributes.styles, 'target');
            var value = Lib.coerce(styleIn[i], styleOut[i], exports.attributes.styles, 'value');

            // so that you can edit value in place and have Plotly.react notice it, or
            // rebuild it every time and have Plotly.react NOT think it changed:
            // use _compareAsJSON to say we should diff the _JSON_value
            if(Lib.isPlainObject(value)) thisStyle.value = Lib.extendDeep({}, value);
            else if(value) delete thisStyle.value;
        }
    }

    return transformOut;
};


/**
 * Apply transform !!!
 *
 * @param {array} data
 *  array of transformed traces (is [fullTrace] upon first transform)
 *
 * @param {object} state
 *  state object which includes:
 *      - transform {object} full transform attributes
 *      - fullTrace {object} full trace object which is being transformed
 *      - fullData {array} full pre-transform(s) data array
 *      - layout {object} the plot's (not-so-full) layout
 *
 * @return {object} newData
 *  array of transformed traces
 */
exports.transform = function(data, state) {
    var newTraces, i, j;
    var newData = [];

    for(i = 0; i < data.length; i++) {
        newTraces = transformOne(data[i], state);

        for(j = 0; j < newTraces.length; j++) {
            newData.push(newTraces[j]);
        }
    }

    return newData;
};

function transformOne(trace, state) {
    var i, j, k, attr, srcArray, groupName, newTrace, transforms, arrayLookup;
    var groupNameObj;

    var opts = state.transform;
    var transformIndex = state.transformIndex;
    var groups = trace.transforms[transformIndex].groups;
    var originalPointsAccessor = pointsAccessorFunction(trace.transforms, opts);

    if(!(Array.isArray(groups)) || groups.length === 0) {
        return [trace];
    }

    var groupNames = Lib.filterUnique(groups);
    var newData = new Array(groupNames.length);
    var len = groups.length;

    var arrayAttrs = PlotSchema.findArrayAttributes(trace);

    var styles = opts.styles || [];
    var styleLookup = {};
    for(i = 0; i < styles.length; i++) {
        styleLookup[styles[i].target] = styles[i].value;
    }

    if(opts.styles) {
        groupNameObj = Lib.keyedContainer(opts, 'styles', 'target', 'value.name');
    }

    // An index to map group name --> expanded trace index
    var indexLookup = {};
    var indexCnts = {};

    for(i = 0; i < groupNames.length; i++) {
        groupName = groupNames[i];
        indexLookup[groupName] = i;
        indexCnts[groupName] = 0;

        // Start with a deep extend that just copies array references.
        newTrace = newData[i] = Lib.extendDeepNoArrays({}, trace);
        newTrace._group = groupName;
        newTrace.transforms[transformIndex]._indexToPoints = {};

        var suppliedName = null;
        if(groupNameObj) {
            suppliedName = groupNameObj.get(groupName);
        }

        if(suppliedName || suppliedName === '') {
            newTrace.name = suppliedName;
        } else {
            newTrace.name = Lib.templateString(opts.nameformat, {
                trace: trace.name,
                group: groupName
            });
        }

        // In order for groups to apply correctly to other transform data (e.g.
        // a filter transform), we have to break the connection and clone the
        // transforms so that each group writes grouped values into a different
        // destination. This function does not break the array reference
        // connection between the split transforms it creates. That's handled in
        // initialize, which creates a new empty array for each arrayAttr.
        transforms = newTrace.transforms;
        newTrace.transforms = [];
        for(j = 0; j < transforms.length; j++) {
            newTrace.transforms[j] = Lib.extendDeepNoArrays({}, transforms[j]);
        }

        // Initialize empty arrays for the arrayAttrs, to be split in the next step
        for(j = 0; j < arrayAttrs.length; j++) {
            Lib.nestedProperty(newTrace, arrayAttrs[j]).set([]);
        }
    }

    // For each array attribute including those nested inside this and other
    // transforms (small note that we technically only need to do this for
    // transforms that have not yet been applied):
    for(k = 0; k < arrayAttrs.length; k++) {
        attr = arrayAttrs[k];

        // Cache all the arrays to which we'll push:
        for(j = 0, arrayLookup = []; j < groupNames.length; j++) {
            arrayLookup[j] = Lib.nestedProperty(newData[j], attr).get();
        }

        // Get the input data:
        srcArray = Lib.nestedProperty(trace, attr).get();

        // Send each data point to the appropriate expanded trace:
        for(j = 0; j < len; j++) {
            // Map group data --> trace index --> array and push data onto it
            arrayLookup[indexLookup[groups[j]]].push(srcArray[j]);
        }
    }

    for(j = 0; j < len; j++) {
        newTrace = newData[indexLookup[groups[j]]];

        var indexToPoints = newTrace.transforms[transformIndex]._indexToPoints;
        indexToPoints[indexCnts[groups[j]]] = originalPointsAccessor(j);
        indexCnts[groups[j]]++;
    }

    for(i = 0; i < groupNames.length; i++) {
        groupName = groupNames[i];
        newTrace = newData[i];

        Plots.clearExpandedTraceDefaultColors(newTrace);

        // there's no need to coerce styleLookup[groupName] here
        // as another round of supplyDefaults is done on the transformed traces
        newTrace = Lib.extendDeepNoArrays(newTrace, styleLookup[groupName] || {});
    }

    return newData;
}

},{"../lib":694,"../plot_api/plot_schema":731,"../plots/plots":806,"./helpers":1162}],1162:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

exports.pointsAccessorFunction = function(transforms, opts) {
    var tr;
    var prevIndexToPoints;
    for(var i = 0; i < transforms.length; i++) {
        tr = transforms[i];
        if(tr === opts) break;
        if(!tr._indexToPoints || tr.enabled === false) continue;
        prevIndexToPoints = tr._indexToPoints;
    }
    var originalPointsAccessor = prevIndexToPoints ?
        function(i) {return prevIndexToPoints[i];} :
        function(i) {return [i];};
    return originalPointsAccessor;
};

},{}],1163:[function(_dereq_,module,exports){
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = _dereq_('../lib');
var Axes = _dereq_('../plots/cartesian/axes');
var pointsAccessorFunction = _dereq_('./helpers').pointsAccessorFunction;

exports.moduleType = 'transform';

exports.name = 'sort';

exports.attributes = {
    enabled: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'calc',
        
    },
    target: {
        valType: 'string',
        strict: true,
        noBlank: true,
        arrayOk: true,
        dflt: 'x',
        
        editType: 'calc',
        
    },
    order: {
        valType: 'enumerated',
        values: ['ascending', 'descending'],
        dflt: 'ascending',
        
        editType: 'calc',
        
    },
    editType: 'calc'
};

exports.supplyDefaults = function(transformIn) {
    var transformOut = {};

    function coerce(attr, dflt) {
        return Lib.coerce(transformIn, transformOut, exports.attributes, attr, dflt);
    }

    var enabled = coerce('enabled');

    if(enabled) {
        coerce('target');
        coerce('order');
    }

    return transformOut;
};

exports.calcTransform = function(gd, trace, opts) {
    if(!opts.enabled) return;

    var targetArray = Lib.getTargetArray(trace, opts);
    if(!targetArray) return;

    var target = opts.target;

    var len = targetArray.length;
    if(trace._length) len = Math.min(len, trace._length);

    var arrayAttrs = trace._arrayAttrs;
    var d2c = Axes.getDataToCoordFunc(gd, trace, target, targetArray);
    var indices = getIndices(opts, targetArray, d2c, len);
    var originalPointsAccessor = pointsAccessorFunction(trace.transforms, opts);
    var indexToPoints = {};
    var i, j;

    for(i = 0; i < arrayAttrs.length; i++) {
        var np = Lib.nestedProperty(trace, arrayAttrs[i]);
        var arrayOld = np.get();
        var arrayNew = new Array(len);

        for(j = 0; j < len; j++) {
            arrayNew[j] = arrayOld[indices[j]];
        }

        np.set(arrayNew);
    }

    for(j = 0; j < len; j++) {
        indexToPoints[j] = originalPointsAccessor(indices[j]);
    }

    opts._indexToPoints = indexToPoints;
    trace._length = len;
};

function getIndices(opts, targetArray, d2c, len) {
    var sortedArray = new Array(len);
    var indices = new Array(len);
    var i;

    for(i = 0; i < len; i++) {
        sortedArray[i] = {v: targetArray[i], i: i};
    }

    sortedArray.sort(getSortFunc(opts, d2c));

    for(i = 0; i < len; i++) {
        indices[i] = sortedArray[i].i;
    }

    return indices;
}

function getSortFunc(opts, d2c) {
    switch(opts.order) {
        case 'ascending':
            return function(a, b) { return d2c(a.v) - d2c(b.v); };
        case 'descending':
            return function(a, b) { return d2c(b.v) - d2c(a.v); };
    }
}

},{"../lib":694,"../plots/cartesian/axes":742,"./helpers":1162}]},{},[22])(22)
});

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "99I3":
/*!*****************************************************!*\
  !*** ./node_modules/base16/lib/atelier-lakeside.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'atelier lakeside',
  author: 'bram de haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/lakeside/)',
  base00: '#161b1d',
  base01: '#1f292e',
  base02: '#516d7b',
  base03: '#5a7b8c',
  base04: '#7195a8',
  base05: '#7ea2b4',
  base06: '#c1e4f6',
  base07: '#ebf8ff',
  base08: '#d22d72',
  base09: '#935c25',
  base0A: '#8a8a0f',
  base0B: '#568c3b',
  base0C: '#2d8f6f',
  base0D: '#257fad',
  base0E: '#5d5db1',
  base0F: '#b72dd2'
};
module.exports = exports['default'];

/***/ }),

/***/ "9DXq":
/*!*********************************************************!*\
  !*** ./node_modules/@jupyterlab/console/lib/tracker.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
/* tslint:disable */
/**
 * The console tracker token.
 */
exports.IConsoleTracker = new coreutils_1.Token('@jupyterlab/console:IConsoleTracker');


/***/ }),

/***/ "9E94":
/*!**************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotIcon.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotIcon = function PlotIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M31.875 4.063L20.937 15.001l-7-6.938-9.938 9.938v6l9.938-10 7 7 10.938-11zM4 27.938V.063H0v31.875h32v-4z' })
    );
};

exports.default = PlotIcon;

/***/ }),

/***/ "9ECJ":
/*!**************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/csvviewer/style/index.css ***!
  \**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.jp-CSVViewer {\n  display: flex;\n  flex-direction: column;\n  outline: none;\n  /* This is needed so that all font sizing of children done in ems is\n   * relative to this base size */\n  font-size: var(--jp-ui-font-size1);\n}\n\n.jp-CSVDelimiter {\n  display: flex;\n  flex: 0 0 auto;\n  flex-direction: row;\n  border: none;\n  min-height: 24px;\n  background: var(--jp-toolbar-background);\n  z-index: 1;\n}\n\n.jp-CSVDelimiter .jp-CSVDelimiter-label {\n  color: var(--jp-ui-font-color1);\n  font-size: var(--jp-ui-font-size1);\n  padding-left: 8px;\n  padding-right: 8px;\n}\n\n.jp-CSVDelimiter .jp-CSVDelimiter-dropdown {\n  flex: 0 0 auto;\n  vertical-align: middle;\n  border-radius: 0;\n  outline: none;\n  height: 20px;\n  margin-top: 2px;\n  margin-bottom: 2px;\n}\n\n.jp-CSVDelimiter .jp-CSVDelimiter-dropdown select.jp-mod-styled {\n  font-size: var(--jp-ui-font-size1);\n  background-color: transparent;\n  height: 20px;\n  padding-right: 20px;\n}\n\n.jp-CSVViewer-grid {\n  flex: 1 1 auto;\n}\n", ""]);

// exports


/***/ }),

/***/ "9Ee5":
/*!******************************************************************!*\
  !*** ./node_modules/@jupyterlab/launcher-extension/lib/index.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const launcher_1 = __webpack_require__(/*! @jupyterlab/launcher */ "78yt");
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
__webpack_require__(/*! ../style/index.css */ "S/4p");
/**
 * The command IDs used by the launcher plugin.
 */
var CommandIDs;
(function (CommandIDs) {
    CommandIDs.create = 'launcher:create';
})(CommandIDs || (CommandIDs = {}));
/**
 * A service providing an interface to the the launcher.
 */
const plugin = {
    activate,
    id: '@jupyterlab/launcher-extension:plugin',
    requires: [apputils_1.ICommandPalette],
    provides: launcher_1.ILauncher,
    autoStart: true
};
/**
 * Export the plugin as default.
 */
exports.default = plugin;
/**
 * Activate the launcher.
 */
function activate(app, palette) {
    const { commands, shell } = app;
    const model = new launcher_1.LauncherModel();
    commands.addCommand(CommandIDs.create, {
        label: 'New Launcher',
        execute: (args) => {
            const cwd = args['cwd'] ? String(args['cwd']) : '';
            const id = `launcher-${Private.id++}`;
            const callback = (item) => {
                shell.addToMainArea(item, { ref: id });
            };
            const launcher = new launcher_1.Launcher({ cwd, callback, commands });
            launcher.model = model;
            launcher.title.label = 'Launcher';
            launcher.title.iconClass = 'jp-LauncherIcon';
            let main = new apputils_1.MainAreaWidget({ content: launcher });
            // If there are any other widgets open, remove the launcher close icon.
            main.title.closable = !!algorithm_1.toArray(shell.widgets('main')).length;
            main.id = id;
            shell.addToMainArea(main, { activate: args['activate'] });
            shell.layoutModified.connect(() => {
                // If there is only a launcher open, remove the close icon.
                main.title.closable = algorithm_1.toArray(shell.widgets('main')).length > 1;
            }, main);
            return main;
        }
    });
    palette.addItem({ command: CommandIDs.create, category: 'Launcher' });
    return model;
}
/**
 * The namespace for module private data.
 */
var Private;
(function (Private) {
    /**
     * The incrementing id used for launcher widgets.
     */
    Private.id = 0;
})(Private || (Private = {}));


/***/ }),

/***/ "9F0J":
/*!******************************************************************!*\
  !*** ./node_modules/@icons/material/UnfoldMoreHorizontalIcon.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

var DEFAULT_SIZE = 24;

exports.default = function (_ref) {
  var _ref$fill = _ref.fill,
      fill = _ref$fill === undefined ? 'currentColor' : _ref$fill,
      _ref$width = _ref.width,
      width = _ref$width === undefined ? DEFAULT_SIZE : _ref$width,
      _ref$height = _ref.height,
      height = _ref$height === undefined ? DEFAULT_SIZE : _ref$height,
      _ref$style = _ref.style,
      style = _ref$style === undefined ? {} : _ref$style,
      props = _objectWithoutProperties(_ref, ['fill', 'width', 'height', 'style']);

  return _react2.default.createElement(
    'svg',
    _extends({
      viewBox: '0 0 ' + DEFAULT_SIZE + ' ' + DEFAULT_SIZE,
      style: _extends({ fill: fill, width: width, height: height }, style)
    }, props),
    _react2.default.createElement('path', { d: 'M12,18.17L8.83,15L7.42,16.41L12,21L16.59,16.41L15.17,15M12,5.83L15.17,9L16.58,7.59L12,3L7.41,7.59L8.83,9L12,5.83Z' })
  );
};

/***/ }),

/***/ "9GDS":
/*!********************************************!*\
  !*** ./node_modules/public-encrypt/mgf.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var createHash = __webpack_require__(/*! create-hash */ "mObS")
var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer

module.exports = function (seed, len) {
  var t = Buffer.alloc(0)
  var i = 0
  var c
  while (t.length < len) {
    c = i2ops(i++)
    t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()])
  }
  return t.slice(0, len)
}

function i2ops (c) {
  var out = Buffer.allocUnsafe(4)
  out.writeUInt32BE(c, 0)
  return out
}


/***/ }),

/***/ "9HwK":
/*!***************************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/plots/font_attributes.js ***!
  \***************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



/*
 * make a font attribute group
 *
 * @param {object} opts
 *   @param {string}
 *     opts.description: where & how this font is used
 *   @param {optional bool} arrayOk:
 *     should each part (family, size, color) be arrayOk? default false.
 *   @param {string} editType:
 *     the editType for all pieces of this font
 *   @param {optional string} colorEditType:
 *     a separate editType just for color
 *
 * @return {object} attributes object containing {family, size, color} as specified
 */
module.exports = function(opts) {
    var editType = opts.editType;
    var colorEditType = opts.colorEditType;
    if(colorEditType === undefined) colorEditType = editType;
    var attrs = {
        family: {
            valType: 'string',
            role: 'style',
            noBlank: true,
            strict: true,
            editType: editType,
            description: [
                'HTML font family - the typeface that will be applied by the web browser.',
                'The web browser will only be able to apply a font if it is available on the system',
                'which it operates. Provide multiple font families, separated by commas, to indicate',
                'the preference in which to apply fonts if they aren\'t available on the system.',
                'The plotly service (at https://plot.ly or on-premise) generates images on a server,',
                'where only a select number of',
                'fonts are installed and supported.',
                'These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*,',
                '*Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*,',
                '*PT Sans Narrow*, *Raleway*, *Times New Roman*.'
            ].join(' ')
        },
        size: {
            valType: 'number',
            role: 'style',
            min: 1,
            editType: editType
        },
        color: {
            valType: 'color',
            role: 'style',
            editType: colorEditType
        },
        editType: editType,
        // blank strings so compress_attributes can remove
        // TODO - that's uber hacky... better solution?
        description: '' + (opts.description || '') + ''
    };

    if(opts.arrayOk) {
        attrs.family.arrayOk = true;
        attrs.size.arrayOk = true;
        attrs.color.arrayOk = true;
    }

    return attrs;
};


/***/ }),

/***/ "9Nap":
/*!***************************************!*\
  !*** ./node_modules/lodash/_toKey.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isSymbol = __webpack_require__(/*! ./isSymbol */ "/9aa");

/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;

/**
 * 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;
}

module.exports = toKey;


/***/ }),

/***/ "9Rdn":
/*!*******************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeScatterpolarIcon.js ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeScatterpolarIcon = function TraceTypeScatterpolarIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement('path', { fill: 'none', d: 'M0 0h46v46H0z' }),
        _react2.default.createElement('path', { fill: '#25fdfc', stroke: '#1d9bfb', d: 'M38.985 32.246l-16 9.221L7 32.221l.015-18.467 16-9.221L39 13.779l-.015 18.467z', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2' }),
        _react2.default.createElement('path', { fill: 'none', stroke: '#1d9bfb', d: 'M33.99 29.357l-11 6.339L12 29.339l.01-12.696 11-6.339L34 16.661l-.01 12.696z', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2' }),
        _react2.default.createElement('path', { fill: 'none', stroke: '#1d9bfb', d: 'M28.994 26.467l-6 3.458L17 26.458l.006-6.925 6-3.458L29 19.542l-.006 6.925zM39 32L7 14m0 18l32-18M23 5v36.185', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2' })
    );
};

exports.default = TraceTypeScatterpolarIcon;

/***/ }),

/***/ "9Rtb":
/*!****************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/Dropdown.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactSelect = __webpack_require__(/*! react-select */ "8Fln");

var _reactSelect2 = _interopRequireDefault(_reactSelect);

var _classnames2 = __webpack_require__(/*! classnames */ "TSYQ");

var _classnames3 = _interopRequireDefault(_classnames2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Dropdown = function (_Component) {
  _inherits(Dropdown, _Component);

  function Dropdown(props) {
    _classCallCheck(this, Dropdown);

    var _this = _possibleConstructorReturn(this, (Dropdown.__proto__ || Object.getPrototypeOf(Dropdown)).call(this, props));

    _this.onChange = _this.onChange.bind(_this);
    return _this;
  }

  _createClass(Dropdown, [{
    key: 'onChange',
    value: function onChange(selection) {
      var _props = this.props,
          multi = _props.multi,
          onChange = _props.onChange,
          valueKey = _props.valueKey;


      if (!selection) {
        return onChange(null);
      } else if (multi) {
        return onChange(selection.map(function (s) {
          return s[valueKey];
        }));
      }

      return onChange(selection[valueKey]);
    }
  }, {
    key: 'render',
    value: function render() {
      var _props2 = this.props,
          backspaceToRemoveMessage = _props2.backspaceToRemoveMessage,
          minWidth = _props2.minWidth,
          placeholder = _props2.placeholder,
          clearable = _props2.clearable,
          value = _props2.value,
          options = _props2.options,
          searchable = _props2.searchable,
          multi = _props2.multi,
          optionRenderer = _props2.optionRenderer,
          valueRenderer = _props2.valueRenderer,
          noResultsText = _props2.noResultsText,
          valueKey = _props2.valueKey,
          disabled = _props2.disabled,
          className = _props2.className,
          width = _props2.width;
      var _ = this.context.localize;


      var dropdownStyle = { minWidth: minWidth };
      if (width) {
        dropdownStyle.width = width;
      }

      var opts = options.slice();
      for (var i = 0; i < opts.length; i++) {
        if (typeof opts[i] === 'string') {
          opts[i] = _defineProperty({ label: opts[i] }, valueKey, opts[i]);
        }
      }

      var dropdownContainerClass = (0, _classnames3.default)('dropdown-container', _defineProperty({
        'dropdown--dark': this.props.backgroundDark
      }, this.props.className, this.props.className));

      return _react2.default.createElement(
        'div',
        { className: dropdownContainerClass, style: dropdownStyle },
        _react2.default.createElement(_reactSelect2.default, {
          backspaceToRemoveMessage: backspaceToRemoveMessage,
          placeholder: placeholder || _('Select an Option'),
          clearable: clearable,
          value: value,
          options: opts,
          searchable: searchable,
          onChange: this.onChange,
          multi: multi,
          optionRenderer: optionRenderer,
          valueRenderer: valueRenderer,
          noResultsText: noResultsText || _('No Results'),
          valueKey: valueKey,
          disabled: disabled,
          className: className
        })
      );
    }
  }]);

  return Dropdown;
}(_react.Component);

Dropdown.defaultProps = {
  clearable: true,
  multi: false,
  searchable: false,
  minWidth: '120px',
  valueKey: 'value',
  disabled: false
};

Dropdown.propTypes = {
  backspaceToRemoveMessage: _propTypes2.default.string,
  backgroundDark: _propTypes2.default.bool,
  clearable: _propTypes2.default.bool,
  onChange: _propTypes2.default.func.isRequired,
  options: _propTypes2.default.array.isRequired,
  placeholder: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.object]),
  searchable: _propTypes2.default.bool,
  minWidth: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]),
  valueKey: _propTypes2.default.string,
  value: _propTypes2.default.any,
  multi: _propTypes2.default.bool,
  optionRenderer: _propTypes2.default.func,
  valueRenderer: _propTypes2.default.func,
  noResultsText: _propTypes2.default.string,
  disabled: _propTypes2.default.bool,
  className: _propTypes2.default.string,
  width: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number])
};

Dropdown.contextTypes = {
  localize: _propTypes2.default.func
};

exports.default = Dropdown;
//# sourceMappingURL=Dropdown.js.map

/***/ }),

/***/ "9S6L":
/*!************************************************************!*\
  !*** ./node_modules/@jupyterlab/codemirror/lib/factory.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const editor_1 = __webpack_require__(/*! ./editor */ "zGJM");
/**
 * CodeMirror editor factory.
 */
class CodeMirrorEditorFactory {
    /**
     * Construct an IEditorFactoryService for CodeMirrorEditors.
     */
    constructor(defaults = {}) {
        /**
         * Create a new editor for inline code.
         */
        this.newInlineEditor = (options) => {
            options.host.dataset.type = 'inline';
            return new editor_1.CodeMirrorEditor(Object.assign({}, options, { config: Object.assign({}, this.inlineCodeMirrorConfig, (options.config || {})) }));
        };
        /**
         * Create a new editor for a full document.
         */
        this.newDocumentEditor = (options) => {
            options.host.dataset.type = 'document';
            return new editor_1.CodeMirrorEditor(Object.assign({}, options, { config: Object.assign({}, this.documentCodeMirrorConfig, (options.config || {})) }));
        };
        this.inlineCodeMirrorConfig = Object.assign({}, editor_1.CodeMirrorEditor.defaultConfig, { extraKeys: {
                'Cmd-Right': 'goLineRight',
                End: 'goLineRight',
                'Cmd-Left': 'goLineLeft',
                Tab: 'indentMoreOrinsertTab',
                'Shift-Tab': 'indentLess',
                'Cmd-/': 'toggleComment',
                'Ctrl-/': 'toggleComment'
            } }, defaults);
        this.documentCodeMirrorConfig = Object.assign({}, editor_1.CodeMirrorEditor.defaultConfig, { extraKeys: {
                Tab: 'indentMoreOrinsertTab',
                'Shift-Tab': 'indentLess',
                'Cmd-/': 'toggleComment',
                'Ctrl-/': 'toggleComment',
                'Shift-Enter': () => {
                    /* no-op */
                }
            }, lineNumbers: true, scrollPastEnd: true }, defaults);
    }
}
exports.CodeMirrorEditorFactory = CodeMirrorEditorFactory;


/***/ }),

/***/ "9Td0":
/*!**********************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/gridlayout.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
var domutils_1 = __webpack_require__(/*! @phosphor/domutils */ "XWTc");
var messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
var properties_1 = __webpack_require__(/*! @phosphor/properties */ "3kwb");
var boxengine_1 = __webpack_require__(/*! ./boxengine */ "ovjo");
var layout_1 = __webpack_require__(/*! ./layout */ "yNaG");
var widget_1 = __webpack_require__(/*! ./widget */ "FmDU");
/**
 * A layout which arranges its widgets in a grid.
 */
var GridLayout = (function (_super) {
    __extends(GridLayout, _super);
    /**
     * Construct a new grid layout.
     *
     * @param options - The options for initializing the layout.
     */
    function GridLayout(options) {
        if (options === void 0) { options = {}; }
        var _this = _super.call(this, options) || this;
        _this._dirty = false;
        _this._rowSpacing = 4;
        _this._columnSpacing = 4;
        _this._items = [];
        _this._rowStarts = [];
        _this._columnStarts = [];
        _this._rowSizers = [new boxengine_1.BoxSizer()];
        _this._columnSizers = [new boxengine_1.BoxSizer()];
        _this._box = null;
        if (options.rowCount !== undefined) {
            Private.reallocSizers(_this._rowSizers, options.rowCount);
        }
        if (options.columnCount !== undefined) {
            Private.reallocSizers(_this._columnSizers, options.columnCount);
        }
        if (options.rowSpacing !== undefined) {
            _this._rowSpacing = Private.clampValue(options.rowSpacing);
        }
        if (options.columnSpacing !== undefined) {
            _this._columnSpacing = Private.clampValue(options.columnSpacing);
        }
        return _this;
    }
    /**
     * Dispose of the resources held by the layout.
     */
    GridLayout.prototype.dispose = function () {
        // Dispose of the widgets and layout items.
        algorithm_1.each(this._items, function (item) {
            var widget = item.widget;
            item.dispose();
            widget.dispose();
        });
        // Clear the layout state.
        this._box = null;
        this._items.length = 0;
        this._rowStarts.length = 0;
        this._rowSizers.length = 0;
        this._columnStarts.length = 0;
        this._columnSizers.length = 0;
        // Dispose of the rest of the layout.
        _super.prototype.dispose.call(this);
    };
    Object.defineProperty(GridLayout.prototype, "rowCount", {
        /**
         * Get the number of rows in the layout.
         */
        get: function () {
            return this._rowSizers.length;
        },
        /**
         * Set the number of rows in the layout.
         *
         * #### Notes
         * The minimum row count is `1`.
         */
        set: function (value) {
            // Do nothing if the row count does not change.
            if (value === this.rowCount) {
                return;
            }
            // Reallocate the row sizers.
            Private.reallocSizers(this._rowSizers, value);
            // Schedule a fit of the parent.
            if (this.parent) {
                this.parent.fit();
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GridLayout.prototype, "columnCount", {
        /**
         * Get the number of columns in the layout.
         */
        get: function () {
            return this._columnSizers.length;
        },
        /**
         * Set the number of columns in the layout.
         *
         * #### Notes
         * The minimum column count is `1`.
         */
        set: function (value) {
            // Do nothing if the column count does not change.
            if (value === this.columnCount) {
                return;
            }
            // Reallocate the column sizers.
            Private.reallocSizers(this._columnSizers, value);
            // Schedule a fit of the parent.
            if (this.parent) {
                this.parent.fit();
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GridLayout.prototype, "rowSpacing", {
        /**
         * Get the row spacing for the layout.
         */
        get: function () {
            return this._rowSpacing;
        },
        /**
         * Set the row spacing for the layout.
         */
        set: function (value) {
            // Clamp the spacing to the allowed range.
            value = Private.clampValue(value);
            // Bail if the spacing does not change
            if (this._rowSpacing === value) {
                return;
            }
            // Update the internal spacing.
            this._rowSpacing = value;
            // Schedule a fit of the parent.
            if (this.parent) {
                this.parent.fit();
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GridLayout.prototype, "columnSpacing", {
        /**
         * Get the column spacing for the layout.
         */
        get: function () {
            return this._columnSpacing;
        },
        /**
         * Set the col spacing for the layout.
         */
        set: function (value) {
            // Clamp the spacing to the allowed range.
            value = Private.clampValue(value);
            // Bail if the spacing does not change
            if (this._columnSpacing === value) {
                return;
            }
            // Update the internal spacing.
            this._columnSpacing = value;
            // Schedule a fit of the parent.
            if (this.parent) {
                this.parent.fit();
            }
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Get the stretch factor for a specific row.
     *
     * @param index - The row index of interest.
     *
     * @returns The stretch factor for the row.
     *
     * #### Notes
     * This returns `-1` if the index is out of range.
     */
    GridLayout.prototype.rowStretch = function (index) {
        var sizer = this._rowSizers[index];
        return sizer ? sizer.stretch : -1;
    };
    /**
     * Set the stretch factor for a specific row.
     *
     * @param index - The row index of interest.
     *
     * @param value - The stretch factor for the row.
     *
     * #### Notes
     * This is a no-op if the index is out of range.
     */
    GridLayout.prototype.setRowStretch = function (index, value) {
        // Look up the row sizer.
        var sizer = this._rowSizers[index];
        // Bail if the index is out of range.
        if (!sizer) {
            return;
        }
        // Clamp the value to the allowed range.
        value = Private.clampValue(value);
        // Bail if the stretch does not change.
        if (sizer.stretch === value) {
            return;
        }
        // Update the sizer stretch.
        sizer.stretch = value;
        // Schedule an update of the parent.
        if (this.parent) {
            this.parent.update();
        }
    };
    /**
     * Get the stretch factor for a specific column.
     *
     * @param index - The column index of interest.
     *
     * @returns The stretch factor for the column.
     *
     * #### Notes
     * This returns `-1` if the index is out of range.
     */
    GridLayout.prototype.columnStretch = function (index) {
        var sizer = this._columnSizers[index];
        return sizer ? sizer.stretch : -1;
    };
    /**
     * Set the stretch factor for a specific column.
     *
     * @param index - The column index of interest.
     *
     * @param value - The stretch factor for the column.
     *
     * #### Notes
     * This is a no-op if the index is out of range.
     */
    GridLayout.prototype.setColumnStretch = function (index, value) {
        // Look up the column sizer.
        var sizer = this._columnSizers[index];
        // Bail if the index is out of range.
        if (!sizer) {
            return;
        }
        // Clamp the value to the allowed range.
        value = Private.clampValue(value);
        // Bail if the stretch does not change.
        if (sizer.stretch === value) {
            return;
        }
        // Update the sizer stretch.
        sizer.stretch = value;
        // Schedule an update of the parent.
        if (this.parent) {
            this.parent.update();
        }
    };
    /**
     * Create an iterator over the widgets in the layout.
     *
     * @returns A new iterator over the widgets in the layout.
     */
    GridLayout.prototype.iter = function () {
        return algorithm_1.map(this._items, function (item) { return item.widget; });
    };
    /**
     * Add a widget to the grid layout.
     *
     * @param widget - The widget to add to the layout.
     *
     * #### Notes
     * If the widget is already contained in the layout, this is no-op.
     */
    GridLayout.prototype.addWidget = function (widget) {
        // Look up the index for the widget.
        var i = algorithm_1.ArrayExt.findFirstIndex(this._items, function (it) { return it.widget === widget; });
        // Bail if the widget is already in the layout.
        if (i !== -1) {
            return;
        }
        // Add the widget to the layout.
        this._items.push(new layout_1.LayoutItem(widget));
        // Attach the widget to the parent.
        if (this.parent) {
            this.attachWidget(widget);
        }
    };
    /**
     * Remove a widget from the grid layout.
     *
     * @param widget - The widget to remove from the layout.
     *
     * #### Notes
     * A widget is automatically removed from the layout when its `parent`
     * is set to `null`. This method should only be invoked directly when
     * removing a widget from a layout which has yet to be installed on a
     * parent widget.
     *
     * This method does *not* modify the widget's `parent`.
     */
    GridLayout.prototype.removeWidget = function (widget) {
        // Look up the index for the widget.
        var i = algorithm_1.ArrayExt.findFirstIndex(this._items, function (it) { return it.widget === widget; });
        // Bail if the widget is not in the layout.
        if (i !== -1) {
            return;
        }
        // Remove the widget from the layout.
        var item = algorithm_1.ArrayExt.removeAt(this._items, i);
        // Detach the widget from the parent.
        if (this.parent) {
            this.detachWidget(widget);
        }
        // Dispose the layout item.
        item.dispose();
    };
    /**
     * Perform layout initialization which requires the parent widget.
     */
    GridLayout.prototype.init = function () {
        var _this = this;
        _super.prototype.init.call(this);
        algorithm_1.each(this, function (widget) { _this.attachWidget(widget); });
    };
    /**
     * Attach a widget to the parent's DOM node.
     *
     * @param widget - The widget to attach to the parent.
     */
    GridLayout.prototype.attachWidget = function (widget) {
        // Send a `'before-attach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.BeforeAttach);
        }
        // Add the widget's node to the parent.
        this.parent.node.appendChild(widget.node);
        // Send an `'after-attach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.AfterAttach);
        }
        // Post a fit request for the parent widget.
        this.parent.fit();
    };
    /**
     * Detach a widget from the parent's DOM node.
     *
     * @param widget - The widget to detach from the parent.
     */
    GridLayout.prototype.detachWidget = function (widget) {
        // Send a `'before-detach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.BeforeDetach);
        }
        // Remove the widget's node from the parent.
        this.parent.node.removeChild(widget.node);
        // Send an `'after-detach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.AfterDetach);
        }
        // Post a fit request for the parent widget.
        this.parent.fit();
    };
    /**
     * A message handler invoked on a `'before-show'` message.
     */
    GridLayout.prototype.onBeforeShow = function (msg) {
        _super.prototype.onBeforeShow.call(this, msg);
        this.parent.update();
    };
    /**
     * A message handler invoked on a `'before-attach'` message.
     */
    GridLayout.prototype.onBeforeAttach = function (msg) {
        _super.prototype.onBeforeAttach.call(this, msg);
        this.parent.fit();
    };
    /**
     * A message handler invoked on a `'child-shown'` message.
     */
    GridLayout.prototype.onChildShown = function (msg) {
        this.parent.fit();
    };
    /**
     * A message handler invoked on a `'child-hidden'` message.
     */
    GridLayout.prototype.onChildHidden = function (msg) {
        this.parent.fit();
    };
    /**
     * A message handler invoked on a `'resize'` message.
     */
    GridLayout.prototype.onResize = function (msg) {
        if (this.parent.isVisible) {
            this._update(msg.width, msg.height);
        }
    };
    /**
     * A message handler invoked on an `'update-request'` message.
     */
    GridLayout.prototype.onUpdateRequest = function (msg) {
        if (this.parent.isVisible) {
            this._update(-1, -1);
        }
    };
    /**
     * A message handler invoked on a `'fit-request'` message.
     */
    GridLayout.prototype.onFitRequest = function (msg) {
        if (this.parent.isAttached) {
            this._fit();
        }
    };
    /**
     * Fit the layout to the total size required by the widgets.
     */
    GridLayout.prototype._fit = function () {
        // Reset the min sizes of the sizers.
        for (var i = 0, n = this.rowCount; i < n; ++i) {
            this._rowSizers[i].minSize = 0;
        }
        for (var i = 0, n = this.columnCount; i < n; ++i) {
            this._columnSizers[i].minSize = 0;
        }
        // Filter for the visible layout items.
        var items = this._items.filter(function (it) { return !it.isHidden; });
        // Fit the layout items.
        for (var i = 0, n = items.length; i < n; ++i) {
            items[i].fit();
        }
        // Get the max row and column index.
        var maxRow = this.rowCount - 1;
        var maxCol = this.columnCount - 1;
        // Sort the items by row span.
        items.sort(Private.rowSpanCmp);
        // Update the min sizes of the row sizers.
        for (var i = 0, n = items.length; i < n; ++i) {
            // Fetch the item.
            var item = items[i];
            // Get the row bounds for the item.
            var config = GridLayout.getCellConfig(item.widget);
            var r1 = Math.min(config.row, maxRow);
            var r2 = Math.min(config.row + config.rowSpan - 1, maxRow);
            // Distribute the minimum height to the sizers as needed.
            Private.distributeMin(this._rowSizers, r1, r2, item.minHeight);
        }
        // Sort the items by column span.
        items.sort(Private.columnSpanCmp);
        // Update the min sizes of the column sizers.
        for (var i = 0, n = items.length; i < n; ++i) {
            // Fetch the item.
            var item = items[i];
            // Get the column bounds for the item.
            var config = GridLayout.getCellConfig(item.widget);
            var c1 = Math.min(config.column, maxCol);
            var c2 = Math.min(config.column + config.columnSpan - 1, maxCol);
            // Distribute the minimum width to the sizers as needed.
            Private.distributeMin(this._columnSizers, c1, c2, item.minWidth);
        }
        // If no size constraint is needed, just update the parent.
        if (this.fitPolicy === 'set-no-constraint') {
            messaging_1.MessageLoop.sendMessage(this.parent, widget_1.Widget.Msg.UpdateRequest);
            return;
        }
        // Set up the computed min size.
        var minH = maxRow * this._rowSpacing;
        var minW = maxCol * this._columnSpacing;
        // Add the sizer minimums to the computed min size.
        for (var i = 0, n = this.rowCount; i < n; ++i) {
            minH += this._rowSizers[i].minSize;
        }
        for (var i = 0, n = this.columnCount; i < n; ++i) {
            minW += this._columnSizers[i].minSize;
        }
        // Update the box sizing and add it to the computed min size.
        var box = this._box = domutils_1.ElementExt.boxSizing(this.parent.node);
        minW += box.horizontalSum;
        minH += box.verticalSum;
        // Update the parent's min size constraints.
        var style = this.parent.node.style;
        style.minWidth = minW + "px";
        style.minHeight = minH + "px";
        // Set the dirty flag to ensure only a single update occurs.
        this._dirty = true;
        // Notify the ancestor that it should fit immediately. This may
        // cause a resize of the parent, fulfilling the required update.
        if (this.parent.parent) {
            messaging_1.MessageLoop.sendMessage(this.parent.parent, widget_1.Widget.Msg.FitRequest);
        }
        // If the dirty flag is still set, the parent was not resized.
        // Trigger the required update on the parent widget immediately.
        if (this._dirty) {
            messaging_1.MessageLoop.sendMessage(this.parent, widget_1.Widget.Msg.UpdateRequest);
        }
    };
    /**
     * Update the layout position and size of the widgets.
     *
     * The parent offset dimensions should be `-1` if unknown.
     */
    GridLayout.prototype._update = function (offsetWidth, offsetHeight) {
        // Clear the dirty flag to indicate the update occurred.
        this._dirty = false;
        // Measure the parent if the offset dimensions are unknown.
        if (offsetWidth < 0) {
            offsetWidth = this.parent.node.offsetWidth;
        }
        if (offsetHeight < 0) {
            offsetHeight = this.parent.node.offsetHeight;
        }
        // Ensure the parent box sizing data is computed.
        if (!this._box) {
            this._box = domutils_1.ElementExt.boxSizing(this.parent.node);
        }
        // Compute the layout area adjusted for border and padding.
        var top = this._box.paddingTop;
        var left = this._box.paddingLeft;
        var width = offsetWidth - this._box.horizontalSum;
        var height = offsetHeight - this._box.verticalSum;
        // Get the max row and column index.
        var maxRow = this.rowCount - 1;
        var maxCol = this.columnCount - 1;
        // Compute the total fixed row and column space.
        var fixedRowSpace = maxRow * this._rowSpacing;
        var fixedColSpace = maxCol * this._columnSpacing;
        // Distribute the available space to the box sizers.
        boxengine_1.BoxEngine.calc(this._rowSizers, Math.max(0, height - fixedRowSpace));
        boxengine_1.BoxEngine.calc(this._columnSizers, Math.max(0, width - fixedColSpace));
        // Update the row start positions.
        for (var i = 0, pos = top, n = this.rowCount; i < n; ++i) {
            this._rowStarts[i] = pos;
            pos += this._rowSizers[i].size + this._rowSpacing;
        }
        // Update the column start positions.
        for (var i = 0, pos = left, n = this.columnCount; i < n; ++i) {
            this._columnStarts[i] = pos;
            pos += this._columnSizers[i].size + this._columnSpacing;
        }
        // Update the geometry of the layout items.
        for (var i = 0, n = this._items.length; i < n; ++i) {
            // Fetch the item.
            var item = this._items[i];
            // Ignore hidden items.
            if (item.isHidden) {
                continue;
            }
            // Fetch the cell bounds for the widget.
            var config = GridLayout.getCellConfig(item.widget);
            var r1 = Math.min(config.row, maxRow);
            var c1 = Math.min(config.column, maxCol);
            var r2 = Math.min(config.row + config.rowSpan - 1, maxRow);
            var c2 = Math.min(config.column + config.columnSpan - 1, maxCol);
            // Compute the cell geometry.
            var x = this._columnStarts[c1];
            var y = this._rowStarts[r1];
            var w = this._columnStarts[c2] + this._columnSizers[c2].size - x;
            var h = this._rowStarts[r2] + this._rowSizers[r2].size - y;
            // Update the geometry of the layout item.
            item.update(x, y, w, h);
        }
    };
    return GridLayout;
}(layout_1.Layout));
exports.GridLayout = GridLayout;
/**
 * The namespace for the `GridLayout` class statics.
 */
(function (GridLayout) {
    /**
     * Get the cell config for the given widget.
     *
     * @param widget - The widget of interest.
     *
     * @returns The cell config for the widget.
     */
    function getCellConfig(widget) {
        return Private.cellConfigProperty.get(widget);
    }
    GridLayout.getCellConfig = getCellConfig;
    /**
     * Set the cell config for the given widget.
     *
     * @param widget - The widget of interest.
     *
     * @param value - The value for the cell config.
     */
    function setCellConfig(widget, value) {
        Private.cellConfigProperty.set(widget, Private.normalizeConfig(value));
    }
    GridLayout.setCellConfig = setCellConfig;
})(GridLayout = exports.GridLayout || (exports.GridLayout = {}));
exports.GridLayout = GridLayout;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * The property descriptor for the widget cell config.
     */
    Private.cellConfigProperty = new properties_1.AttachedProperty({
        name: 'cellConfig',
        create: function () { return ({ row: 0, column: 0, rowSpan: 1, columnSpan: 1 }); },
        changed: onChildCellConfigChanged
    });
    /**
     * Normalize a partial cell config object.
     */
    function normalizeConfig(config) {
        var row = Math.max(0, Math.floor(config.row || 0));
        var column = Math.max(0, Math.floor(config.column || 0));
        var rowSpan = Math.max(1, Math.floor(config.rowSpan || 0));
        var columnSpan = Math.max(1, Math.floor(config.columnSpan || 0));
        return { row: row, column: column, rowSpan: rowSpan, columnSpan: columnSpan };
    }
    Private.normalizeConfig = normalizeConfig;
    /**
     * Clamp a value to an integer >= 0.
     */
    function clampValue(value) {
        return Math.max(0, Math.floor(value));
    }
    Private.clampValue = clampValue;
    /**
     * A sort comparison function for row spans.
     */
    function rowSpanCmp(a, b) {
        var c1 = Private.cellConfigProperty.get(a.widget);
        var c2 = Private.cellConfigProperty.get(b.widget);
        return c1.rowSpan - c2.rowSpan;
    }
    Private.rowSpanCmp = rowSpanCmp;
    /**
     * A sort comparison function for column spans.
     */
    function columnSpanCmp(a, b) {
        var c1 = Private.cellConfigProperty.get(a.widget);
        var c2 = Private.cellConfigProperty.get(b.widget);
        return c1.columnSpan - c2.columnSpan;
    }
    Private.columnSpanCmp = columnSpanCmp;
    /**
     * Reallocate the box sizers for the given grid dimensions.
     */
    function reallocSizers(sizers, count) {
        // Coerce the count to the valid range.
        count = Math.max(1, Math.floor(count));
        // Add the missing sizers.
        while (sizers.length < count) {
            sizers.push(new boxengine_1.BoxSizer());
        }
        // Remove the extra sizers.
        if (sizers.length < count) {
            sizers.length = count;
        }
    }
    Private.reallocSizers = reallocSizers;
    /**
     * Distribute a min size constraint across a range of sizers.
     */
    function distributeMin(sizers, i1, i2, minSize) {
        // Sanity check the indices.
        if (i2 < i1) {
            return;
        }
        // Handle the simple case of no cell span.
        if (i1 === i2) {
            var sizer = sizers[i1];
            sizer.minSize = Math.max(sizer.minSize, minSize);
            return;
        }
        // Compute the total current min size of the span.
        var totalMin = 0;
        for (var i = i1; i <= i2; ++i) {
            totalMin += sizers[i].minSize;
        }
        // Do nothing if the total is greater than the required.
        if (totalMin >= minSize) {
            return;
        }
        // Compute the portion of the space to allocate to each sizer.
        var portion = (minSize - totalMin) / (i2 - i1 + 1);
        // Add the portion to each sizer.
        for (var i = i1; i <= i2; ++i) {
            sizers[i].minSize += portion;
        }
    }
    Private.distributeMin = distributeMin;
    /**
     * The change handler for the child cell config property.
     */
    function onChildCellConfigChanged(child) {
        if (child.parent && child.parent.layout instanceof GridLayout) {
            child.parent.fit();
        }
    }
})(Private || (Private = {}));


/***/ }),

/***/ "9XZ3":
/*!**************************************!*\
  !*** ./node_modules/md5.js/index.js ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var inherits = __webpack_require__(/*! inherits */ "P7XM")
var HashBase = __webpack_require__(/*! hash-base */ "k+aG")
var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer

var ARRAY16 = new Array(16)

function MD5 () {
  HashBase.call(this, 64)

  // state
  this._a = 0x67452301
  this._b = 0xefcdab89
  this._c = 0x98badcfe
  this._d = 0x10325476
}

inherits(MD5, HashBase)

MD5.prototype._update = function () {
  var M = ARRAY16
  for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4)

  var a = this._a
  var b = this._b
  var c = this._c
  var d = this._d

  a = fnF(a, b, c, d, M[0], 0xd76aa478, 7)
  d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12)
  c = fnF(c, d, a, b, M[2], 0x242070db, 17)
  b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22)
  a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7)
  d = fnF(d, a, b, c, M[5], 0x4787c62a, 12)
  c = fnF(c, d, a, b, M[6], 0xa8304613, 17)
  b = fnF(b, c, d, a, M[7], 0xfd469501, 22)
  a = fnF(a, b, c, d, M[8], 0x698098d8, 7)
  d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12)
  c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17)
  b = fnF(b, c, d, a, M[11], 0x895cd7be, 22)
  a = fnF(a, b, c, d, M[12], 0x6b901122, 7)
  d = fnF(d, a, b, c, M[13], 0xfd987193, 12)
  c = fnF(c, d, a, b, M[14], 0xa679438e, 17)
  b = fnF(b, c, d, a, M[15], 0x49b40821, 22)

  a = fnG(a, b, c, d, M[1], 0xf61e2562, 5)
  d = fnG(d, a, b, c, M[6], 0xc040b340, 9)
  c = fnG(c, d, a, b, M[11], 0x265e5a51, 14)
  b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20)
  a = fnG(a, b, c, d, M[5], 0xd62f105d, 5)
  d = fnG(d, a, b, c, M[10], 0x02441453, 9)
  c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14)
  b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20)
  a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5)
  d = fnG(d, a, b, c, M[14], 0xc33707d6, 9)
  c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14)
  b = fnG(b, c, d, a, M[8], 0x455a14ed, 20)
  a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5)
  d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9)
  c = fnG(c, d, a, b, M[7], 0x676f02d9, 14)
  b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20)

  a = fnH(a, b, c, d, M[5], 0xfffa3942, 4)
  d = fnH(d, a, b, c, M[8], 0x8771f681, 11)
  c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16)
  b = fnH(b, c, d, a, M[14], 0xfde5380c, 23)
  a = fnH(a, b, c, d, M[1], 0xa4beea44, 4)
  d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11)
  c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16)
  b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23)
  a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4)
  d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11)
  c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16)
  b = fnH(b, c, d, a, M[6], 0x04881d05, 23)
  a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4)
  d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11)
  c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16)
  b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23)

  a = fnI(a, b, c, d, M[0], 0xf4292244, 6)
  d = fnI(d, a, b, c, M[7], 0x432aff97, 10)
  c = fnI(c, d, a, b, M[14], 0xab9423a7, 15)
  b = fnI(b, c, d, a, M[5], 0xfc93a039, 21)
  a = fnI(a, b, c, d, M[12], 0x655b59c3, 6)
  d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10)
  c = fnI(c, d, a, b, M[10], 0xffeff47d, 15)
  b = fnI(b, c, d, a, M[1], 0x85845dd1, 21)
  a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6)
  d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10)
  c = fnI(c, d, a, b, M[6], 0xa3014314, 15)
  b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21)
  a = fnI(a, b, c, d, M[4], 0xf7537e82, 6)
  d = fnI(d, a, b, c, M[11], 0xbd3af235, 10)
  c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15)
  b = fnI(b, c, d, a, M[9], 0xeb86d391, 21)

  this._a = (this._a + a) | 0
  this._b = (this._b + b) | 0
  this._c = (this._c + c) | 0
  this._d = (this._d + d) | 0
}

MD5.prototype._digest = function () {
  // create padding and handle blocks
  this._block[this._blockOffset++] = 0x80
  if (this._blockOffset > 56) {
    this._block.fill(0, this._blockOffset, 64)
    this._update()
    this._blockOffset = 0
  }

  this._block.fill(0, this._blockOffset, 56)
  this._block.writeUInt32LE(this._length[0], 56)
  this._block.writeUInt32LE(this._length[1], 60)
  this._update()

  // produce result
  var buffer = Buffer.allocUnsafe(16)
  buffer.writeInt32LE(this._a, 0)
  buffer.writeInt32LE(this._b, 4)
  buffer.writeInt32LE(this._c, 8)
  buffer.writeInt32LE(this._d, 12)
  return buffer
}

function rotl (x, n) {
  return (x << n) | (x >>> (32 - n))
}

function fnF (a, b, c, d, m, k, s) {
  return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0
}

function fnG (a, b, c, d, m, k, s) {
  return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0
}

function fnH (a, b, c, d, m, k, s) {
  return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0
}

function fnI (a, b, c, d, m, k, s) {
  return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0
}

module.exports = MD5


/***/ }),

/***/ "9Yhm":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/mathjax2/style/index.css ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "IHQy");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "9g5G":
/*!****************************************************!*\
  !*** ./node_modules/mdi-react/EmailOutlineIcon.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var EmailOutlineIcon = function EmailOutlineIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M4,4H20C21.1,4 22,4.9 22,6V18C22,19.1 21.1,20 20,20H4C2.89,20 2,19.1 2,18V6C2,4.89 2.89,4 4,4M12,11L20,6H4L12,11M4,18H20V8.37L12,13.36L4,8.37V18Z' })
  );
};

module.exports = EmailOutlineIcon;


/***/ }),

/***/ "9ggG":
/*!***************************************!*\
  !*** ./node_modules/lodash/_isKey.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isArray = __webpack_require__(/*! ./isArray */ "Z0cm"),
    isSymbol = __webpack_require__(/*! ./isSymbol */ "/9aa");

/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
    reIsPlainProp = /^\w*$/;

/**
 * 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));
}

module.exports = isKey;


/***/ }),

/***/ "9gmq":
/*!***************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/apputils/style/styling.css ***!
  \***************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, Jupyter Development Team.\n|\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\nbutton.jp-mod-styled {\n  font-size: var(--jp-ui-font-size1);\n  color: var(--jp-ui-font-color0);\n  border: none;\n  box-sizing: border-box;\n  text-transform: uppercase;\n  text-align: center;\n  line-height: 32px;\n  height: 32px;\n  padding: 0px 12px;\n  letter-spacing: 0.8px;\n  outline: none;\n  appearance: none;\n  -webkit-appearance: none;\n  -moz-appearance: none;\n}\n\ninput.jp-mod-styled {\n  background: var(--jp-input-background);\n  height: 28px;\n  box-sizing: border-box;\n  border: var(--jp-border-width) solid var(--jp-border-color1);\n  padding-left: 7px;\n  padding-right: 7px;\n  font-size: var(--jp-ui-font-size2);\n  color: var(--jp-ui-font-color0);\n  outline: none;\n  appearance: none;\n  -webkit-appearance: none;\n  -moz-appearance: none;\n}\n\ninput.jp-mod-styled:focus {\n  border: var(--jp-border-width) solid var(--md-blue-500);\n  box-shadow: inset 0 0 4px var(--md-blue-300);\n}\n\n.jp-select-wrapper {\n  display: flex;\n  flex-direction: column;\n  padding: 1px;\n  background-color: var(--jp-layout-color1);\n  height: 28px;\n  box-sizing: border-box;\n  margin-bottom: 12px;\n}\n\n.jp-select-wrapper.jp-mod-focused select.jp-mod-styled {\n  border: var(--jp-border-width) solid var(--jp-input-active-border-color);\n  box-shadow: var(--jp-input-box-shadow);\n  background-color: var(--jp-input-active-background);\n}\n\nselect.jp-mod-styled:hover {\n  background-color: var(--jp-layout-color1);\n  cursor: pointer;\n  color: var(--jp-ui-font-color0);\n  background-color: var(--jp-input-hover-background);\n  box-shadow: inset 0 0px 1px rgba(0, 0, 0, 0.5);\n}\n\nselect.jp-mod-styled {\n  flex: 1 1 auto;\n  height: 32px;\n  width: 100%;\n  font-size: var(--jp-ui-font-size2);\n  background: var(--jp-input-background);\n  color: var(--jp-ui-font-color0);\n  padding-left: 8px;\n  padding-right: 8px;\n  background-image: var(--jp-ui-select-caret);\n  background-repeat: no-repeat;\n  background-position: 99% center;\n  background-size: 18px;\n  border: var(--jp-border-width) solid var(--jp-input-border-color);\n  border-radius: 0px;\n  outline: none;\n  appearance: none;\n  -webkit-appearance: none;\n  -moz-appearance: none;\n}\n", ""]);

// exports


/***/ }),

/***/ "9n51":
/*!**********************************************!*\
  !*** ./node_modules/domutils/lib/helpers.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

// removeSubsets
// Given an array of nodes, remove any member that is contained by another.
exports.removeSubsets = function(nodes) {
	var idx = nodes.length, node, ancestor, replace;

	// Check if each node (or one of its ancestors) is already contained in the
	// array.
	while (--idx > -1) {
		node = ancestor = nodes[idx];

		// Temporarily remove the node under consideration
		nodes[idx] = null;
		replace = true;

		while (ancestor) {
			if (nodes.indexOf(ancestor) > -1) {
				replace = false;
				nodes.splice(idx, 1);
				break;
			}
			ancestor = ancestor.parent;
		}

		// If the node has been found to be unique, re-insert it.
		if (replace) {
			nodes[idx] = node;
		}
	}

	return nodes;
};

// Source: http://dom.spec.whatwg.org/#dom-node-comparedocumentposition
var POSITION = {
	DISCONNECTED: 1,
	PRECEDING: 2,
	FOLLOWING: 4,
	CONTAINS: 8,
	CONTAINED_BY: 16
};

// Compare the position of one node against another node in any other document.
// The return value is a bitmask with the following values:
//
// document order:
// > There is an ordering, document order, defined on all the nodes in the
// > document corresponding to the order in which the first character of the
// > XML representation of each node occurs in the XML representation of the
// > document after expansion of general entities. Thus, the document element
// > node will be the first node. Element nodes occur before their children.
// > Thus, document order orders element nodes in order of the occurrence of
// > their start-tag in the XML (after expansion of entities). The attribute
// > nodes of an element occur after the element and before its children. The
// > relative order of attribute nodes is implementation-dependent./
// Source:
// http://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-document-order
//
// @argument {Node} nodaA The first node to use in the comparison
// @argument {Node} nodeB The second node to use in the comparison
//
// @return {Number} A bitmask describing the input nodes' relative position.
//         See http://dom.spec.whatwg.org/#dom-node-comparedocumentposition for
//         a description of these values.
var comparePos = exports.compareDocumentPosition = function(nodeA, nodeB) {
	var aParents = [];
	var bParents = [];
	var current, sharedParent, siblings, aSibling, bSibling, idx;

	if (nodeA === nodeB) {
		return 0;
	}

	current = nodeA;
	while (current) {
		aParents.unshift(current);
		current = current.parent;
	}
	current = nodeB;
	while (current) {
		bParents.unshift(current);
		current = current.parent;
	}

	idx = 0;
	while (aParents[idx] === bParents[idx]) {
		idx++;
	}

	if (idx === 0) {
		return POSITION.DISCONNECTED;
	}

	sharedParent = aParents[idx - 1];
	siblings = sharedParent.children;
	aSibling = aParents[idx];
	bSibling = bParents[idx];

	if (siblings.indexOf(aSibling) > siblings.indexOf(bSibling)) {
		if (sharedParent === nodeB) {
			return POSITION.FOLLOWING | POSITION.CONTAINED_BY;
		}
		return POSITION.FOLLOWING;
	} else {
		if (sharedParent === nodeA) {
			return POSITION.PRECEDING | POSITION.CONTAINS;
		}
		return POSITION.PRECEDING;
	}
};

// Sort an array of nodes based on their relative position in the document and
// remove any duplicate nodes. If the array contains nodes that do not belong
// to the same document, sort order is unspecified.
//
// @argument {Array} nodes Array of DOM nodes
//
// @returns {Array} collection of unique nodes, sorted in document order
exports.uniqueSort = function(nodes) {
	var idx = nodes.length, node, position;

	nodes = nodes.slice();

	while (--idx > -1) {
		node = nodes[idx];
		position = nodes.indexOf(node);
		if (position > -1 && position < idx) {
			nodes.splice(idx, 1);
		}
	}
	nodes.sort(function(a, b) {
		var relative = comparePos(a, b);
		if (relative & POSITION.PRECEDING) {
			return -1;
		} else if (relative & POSITION.FOLLOWING) {
			return 1;
		}
		return 0;
	});

	return nodes;
};


/***/ }),

/***/ "9q4B":
/*!**********************************************!*\
  !*** ./node_modules/mdi-react/DeleteIcon.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var DeleteIcon = function DeleteIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M19,4H15.5L14.5,3H9.5L8.5,4H5V6H19M6,19C6,20.1 6.9,21 8,21H16C17.1,21 18,20.1 18,19V7H6V19Z' })
  );
};

module.exports = DeleteIcon;


/***/ }),

/***/ "9qiJ":
/*!*********************************************!*\
  !*** ./node_modules/xterm/lib/BufferSet.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Buffer_1 = __webpack_require__(/*! ./Buffer */ "MsZC");
var EventEmitter_1 = __webpack_require__(/*! ./EventEmitter */ "t2YR");
var BufferSet = (function (_super) {
    __extends(BufferSet, _super);
    function BufferSet(_terminal) {
        var _this = _super.call(this) || this;
        _this._terminal = _terminal;
        _this._normal = new Buffer_1.Buffer(_this._terminal, true);
        _this._normal.fillViewportRows();
        _this._alt = new Buffer_1.Buffer(_this._terminal, false);
        _this._activeBuffer = _this._normal;
        _this.setupTabStops();
        return _this;
    }
    Object.defineProperty(BufferSet.prototype, "alt", {
        get: function () {
            return this._alt;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(BufferSet.prototype, "active", {
        get: function () {
            return this._activeBuffer;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(BufferSet.prototype, "normal", {
        get: function () {
            return this._normal;
        },
        enumerable: true,
        configurable: true
    });
    BufferSet.prototype.activateNormalBuffer = function () {
        if (this._activeBuffer === this._normal) {
            return;
        }
        this._alt.clear();
        this._activeBuffer = this._normal;
        this.emit('activate', {
            activeBuffer: this._normal,
            inactiveBuffer: this._alt
        });
    };
    BufferSet.prototype.activateAltBuffer = function () {
        if (this._activeBuffer === this._alt) {
            return;
        }
        this._alt.fillViewportRows();
        this._activeBuffer = this._alt;
        this.emit('activate', {
            activeBuffer: this._alt,
            inactiveBuffer: this._normal
        });
    };
    BufferSet.prototype.resize = function (newCols, newRows) {
        this._normal.resize(newCols, newRows);
        this._alt.resize(newCols, newRows);
    };
    BufferSet.prototype.setupTabStops = function (i) {
        this._normal.setupTabStops(i);
        this._alt.setupTabStops(i);
    };
    return BufferSet;
}(EventEmitter_1.EventEmitter));
exports.BufferSet = BufferSet;

//# sourceMappingURL=BufferSet.js.map


/***/ }),

/***/ "9rBw":
/*!********************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/to_log_range.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var isNumeric = __webpack_require__(/*! fast-isnumeric */ "GbLo");

/**
 * convert a linear value into a logged value, folding negative numbers into
 * the given range
 */
module.exports = function toLogRange(val, range) {
    if(val > 0) return Math.log(val) / Math.LN10;

    // move a negative value reference to a log axis - just put the
    // result at the lowest range value on the plot (or if the range also went negative,
    // one millionth of the top of the range)
    var newVal = Math.log(Math.min(range[0], range[1])) / Math.LN10;
    if(!isNumeric(newVal)) newVal = Math.log(Math.max(range[0], range[1])) / Math.LN10 - 6;
    return newVal;
};


/***/ }),

/***/ "9rRi":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/gd.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var months = [
    'Am Faoilleach', 'An Gearran', 'Am Màrt', 'An Giblean', 'An Cèitean', 'An t-Ògmhios', 'An t-Iuchar', 'An Lùnastal', 'An t-Sultain', 'An Dàmhair', 'An t-Samhain', 'An Dùbhlachd'
];

var monthsShort = ['Faoi', 'Gear', 'Màrt', 'Gibl', 'Cèit', 'Ògmh', 'Iuch', 'Lùn', 'Sult', 'Dàmh', 'Samh', 'Dùbh'];

var weekdays = ['Didòmhnaich', 'Diluain', 'Dimàirt', 'Diciadain', 'Diardaoin', 'Dihaoine', 'Disathairne'];

var weekdaysShort = ['Did', 'Dil', 'Dim', 'Dic', 'Dia', 'Dih', 'Dis'];

var weekdaysMin = ['Dò', 'Lu', 'Mà', 'Ci', 'Ar', 'Ha', 'Sa'];

var gd = moment.defineLocale('gd', {
    months : months,
    monthsShort : monthsShort,
    monthsParseExact : true,
    weekdays : weekdays,
    weekdaysShort : weekdaysShort,
    weekdaysMin : weekdaysMin,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd, D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay : '[An-diugh aig] LT',
        nextDay : '[A-màireach aig] LT',
        nextWeek : 'dddd [aig] LT',
        lastDay : '[An-dè aig] LT',
        lastWeek : 'dddd [seo chaidh] [aig] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'ann an %s',
        past : 'bho chionn %s',
        s : 'beagan diogan',
        ss : '%d diogan',
        m : 'mionaid',
        mm : '%d mionaidean',
        h : 'uair',
        hh : '%d uairean',
        d : 'latha',
        dd : '%d latha',
        M : 'mìos',
        MM : '%d mìosan',
        y : 'bliadhna',
        yy : '%d bliadhna'
    },
    dayOfMonthOrdinalParse : /\d{1,2}(d|na|mh)/,
    ordinal : function (number) {
        var output = number === 1 ? 'd' : number % 10 === 2 ? 'na' : 'mh';
        return number + output;
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return gd;

})));


/***/ }),

/***/ "9tPo":
/*!***********************************************!*\
  !*** ./node_modules/style-loader/lib/urls.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports) {


/**
 * When source maps are enabled, `style-loader` uses a link element with a data-uri to
 * embed the css on the page. This breaks all relative urls because now they are relative to a
 * bundle instead of the current page.
 *
 * One solution is to only use full urls, but that may be impossible.
 *
 * Instead, this function "fixes" the relative urls to be absolute according to the current page location.
 *
 * A rudimentary test suite is located at `test/fixUrls.js` and can be run via the `npm test` command.
 *
 */

module.exports = function (css) {
  // get current location
  var location = typeof window !== "undefined" && window.location;

  if (!location) {
    throw new Error("fixUrls requires window.location");
  }

	// blank or null?
	if (!css || typeof css !== "string") {
	  return css;
  }

  var baseUrl = location.protocol + "//" + location.host;
  var currentDir = baseUrl + location.pathname.replace(/\/[^\/]*$/, "/");

	// convert each url(...)
	/*
	This regular expression is just a way to recursively match brackets within
	a string.

	 /url\s*\(  = Match on the word "url" with any whitespace after it and then a parens
	   (  = Start a capturing group
	     (?:  = Start a non-capturing group
	         [^)(]  = Match anything that isn't a parentheses
	         |  = OR
	         \(  = Match a start parentheses
	             (?:  = Start another non-capturing groups
	                 [^)(]+  = Match anything that isn't a parentheses
	                 |  = OR
	                 \(  = Match a start parentheses
	                     [^)(]*  = Match anything that isn't a parentheses
	                 \)  = Match a end parentheses
	             )  = End Group
              *\) = Match anything and then a close parens
          )  = Close non-capturing group
          *  = Match anything
       )  = Close capturing group
	 \)  = Match a close parens

	 /gi  = Get all matches, not the first.  Be case insensitive.
	 */
	var fixedCss = css.replace(/url\s*\(((?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)\)/gi, function(fullMatch, origUrl) {
		// strip quotes (if they exist)
		var unquotedOrigUrl = origUrl
			.trim()
			.replace(/^"(.*)"$/, function(o, $1){ return $1; })
			.replace(/^'(.*)'$/, function(o, $1){ return $1; });

		// already a full url? no change
		if (/^(#|data:|http:\/\/|https:\/\/|file:\/\/\/|\s*$)/i.test(unquotedOrigUrl)) {
		  return fullMatch;
		}

		// convert the url to a full url
		var newUrl;

		if (unquotedOrigUrl.indexOf("//") === 0) {
		  	//TODO: should we add protocol?
			newUrl = unquotedOrigUrl;
		} else if (unquotedOrigUrl.indexOf("/") === 0) {
			// path should be relative to the base url
			newUrl = baseUrl + unquotedOrigUrl; // already starts with '/'
		} else {
			// path should be relative to current directory
			newUrl = currentDir + unquotedOrigUrl.replace(/^\.\//, ""); // Strip leading './'
		}

		// send back the fixed url(...)
		return "url(" + JSON.stringify(newUrl) + ")";
	});

	// send back the fixed css
	return fixedCss;
};


/***/ }),

/***/ "9txC":
/*!********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/default_panels/StyleLegendPanel.js ***!
  \********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _components = __webpack_require__(/*! ../components */ "yF51");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var StyleLegendPanel = function StyleLegendPanel(props, _ref) {
  var _ = _ref.localize;
  return _react2.default.createElement(
    _components.TraceRequiredPanel,
    null,
    _react2.default.createElement(
      _components.PlotlyFold,
      { name: _('Legend') },
      _react2.default.createElement(_components.Radio, {
        attr: 'showlegend',
        options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
      }),
      _react2.default.createElement(
        _components.PlotlySection,
        { name: _('Text') },
        _react2.default.createElement(_components.FontSelector, { label: _('Typeface'), attr: 'legend.font.family' }),
        _react2.default.createElement(_components.Numeric, { label: _('Size'), attr: 'legend.font.size', units: 'px' }),
        _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'legend.font.color' })
      ),
      _react2.default.createElement(
        _components.PlotlySection,
        { name: _('Legend Box') },
        _react2.default.createElement(_components.Numeric, { label: _('Border Width'), attr: 'legend.borderwidth', units: 'px' }),
        _react2.default.createElement(_components.ColorPicker, { label: _('Border Color'), attr: 'legend.bordercolor' }),
        _react2.default.createElement(_components.ColorPicker, { label: _('Background Color'), attr: 'legend.bgcolor' })
      ),
      _react2.default.createElement(
        _components.PlotlySection,
        { name: _('Horizontal Positioning') },
        _react2.default.createElement(_components.Dropdown, {
          label: _('Anchor Point'),
          clearable: false,
          attr: 'legend.xanchor',
          options: [{ label: _('Auto'), value: 'auto' }, { label: _('Left'), value: 'left' }, { label: _('Center'), value: 'center' }, { label: _('Right'), value: 'right' }]
        }),
        _react2.default.createElement(_components.Numeric, { label: _('Position'), showSlider: true, step: 0.02, attr: 'legend.x' })
      ),
      _react2.default.createElement(
        _components.PlotlySection,
        { name: _('Vertical Positioning') },
        _react2.default.createElement(_components.Dropdown, {
          label: _('Anchor Point'),
          clearable: false,
          attr: 'legend.yanchor',
          options: [{ label: _('Auto'), value: 'auto' }, { label: _('Top'), value: 'top' }, { label: _('Middle'), value: 'middle' }, { label: _('Bottom'), value: 'bottom' }]
        }),
        _react2.default.createElement(_components.Numeric, { label: _('Position'), showSlider: true, step: 0.02, attr: 'legend.y' }),
        _react2.default.createElement(_components.Dropdown, {
          label: _('Text Alignment'),
          clearable: false,
          attr: 'legend.valign',
          options: [{ label: _('Top'), value: 'top' }, { label: _('Middle'), value: 'middle' }, { label: _('Bottom'), value: 'bottom' }]
        })
      ),
      _react2.default.createElement(
        _components.PlotlySection,
        { name: _('Orientation') },
        _react2.default.createElement(_components.Radio, {
          attr: 'legend.orientation',
          options: [{ label: _('Vertical'), value: 'v' }, { label: _('Horizontal'), value: 'h' }]
        })
      ),
      _react2.default.createElement(
        _components.PlotlySection,
        { name: _('Trace Order') },
        _react2.default.createElement(_components.Dropdown, {
          attr: 'legend.traceorder',
          options: [{ label: _('Normal'), value: 'normal' }, { label: _('Reversed'), value: 'reversed' }, { label: _('Grouped'), value: 'grouped' }, { label: _('Reversed and Grouped'), value: 'reversed+grouped' }]
        }),
        _react2.default.createElement(_components.Numeric, { label: _('Gap Between Groups'), attr: 'legend.tracegroupgap', units: 'px' })
      )
    )
  );
};

StyleLegendPanel.contextTypes = {
  localize: _propTypes2.default.func
};

exports.default = StyleLegendPanel;
//# sourceMappingURL=StyleLegendPanel.js.map

/***/ }),

/***/ "9vST":
/*!******************************************************************!*\
  !*** ./node_modules/@jupyterlab/docregistry/lib/mimedocument.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const rendermime_1 = __webpack_require__(/*! @jupyterlab/rendermime */ "Towz");
const coreutils_2 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const default_1 = __webpack_require__(/*! ./default */ "Or5M");
/**
 * A content widget for a rendered mimetype document.
 */
class MimeContent extends widgets_1.Widget {
    /**
     * Construct a new widget.
     */
    constructor(options) {
        super();
        /**
         * A bound change callback.
         */
        this._changeCallback = (options) => {
            if (!options.data || !options.data[this.mimeType]) {
                return;
            }
            let data = options.data[this.mimeType];
            if (typeof data === 'string') {
                this._context.model.fromString(data);
            }
            else {
                this._context.model.fromJSON(data);
            }
        };
        this._ready = new coreutils_2.PromiseDelegate();
        this._isRendering = false;
        this._renderRequested = false;
        this.addClass('jp-MimeDocument');
        this.mimeType = options.mimeType;
        this._dataType = options.dataType || 'string';
        this._context = options.context;
        this.renderer = options.renderer;
        const layout = (this.layout = new widgets_1.StackedLayout());
        layout.addWidget(this.renderer);
        this._context.ready
            .then(() => {
            return this._render();
        })
            .then(() => {
            // After rendering for the first time, send an activation request if we
            // are currently focused.
            if (this.node === document.activeElement) {
                // We want to synchronously send (not post) the activate message, while
                // we know this node still has focus.
                messaging_1.MessageLoop.sendMessage(this.renderer, widgets_1.Widget.Msg.ActivateRequest);
            }
            // Throttle the rendering rate of the widget.
            this._monitor = new coreutils_1.ActivityMonitor({
                signal: this._context.model.contentChanged,
                timeout: options.renderTimeout
            });
            this._monitor.activityStopped.connect(this.update, this);
            this._ready.resolve(undefined);
        })
            .catch(reason => {
            // Dispose the document if rendering fails.
            requestAnimationFrame(() => {
                this.dispose();
            });
            apputils_1.showErrorMessage(`Renderer Failure: ${this._context.path}`, reason);
        });
    }
    /**
     * A promise that resolves when the widget is ready.
     */
    get ready() {
        return this._ready.promise;
    }
    /**
     * Dispose of the resources held by the widget.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        if (this._monitor) {
            this._monitor.dispose();
        }
        this._monitor = null;
        super.dispose();
    }
    /**
     * Handle an `update-request` message to the widget.
     */
    onUpdateRequest(msg) {
        if (this._context.isReady) {
            this._render();
        }
    }
    /**
     * Render the mime content.
     */
    _render() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.isDisposed) {
                return;
            }
            // Since rendering is async, we note render requests that happen while we
            // actually are rendering for a future rendering.
            if (this._isRendering) {
                this._renderRequested = true;
                return;
            }
            // Set up for this rendering pass.
            this._renderRequested = false;
            let context = this._context;
            let model = context.model;
            let data = {};
            if (this._dataType === 'string') {
                data[this.mimeType] = model.toString();
            }
            else {
                data[this.mimeType] = model.toJSON();
            }
            let mimeModel = new rendermime_1.MimeModel({ data, callback: this._changeCallback });
            try {
                // Do the rendering asynchronously.
                this._isRendering = true;
                yield this.renderer.renderModel(mimeModel);
                this._isRendering = false;
                // If there is an outstanding request to render, go ahead and render
                if (this._renderRequested) {
                    return this._render();
                }
            }
            catch (reason) {
                // Dispose the document if rendering fails.
                requestAnimationFrame(() => {
                    this.dispose();
                });
                apputils_1.showErrorMessage(`Renderer Failure: ${context.path}`, reason);
            }
        });
    }
}
exports.MimeContent = MimeContent;
/**
 * A document widget for mime content.
 */
class MimeDocument extends default_1.DocumentWidget {
}
exports.MimeDocument = MimeDocument;
/**
 * An implementation of a widget factory for a rendered mimetype document.
 */
class MimeDocumentFactory extends default_1.ABCWidgetFactory {
    /**
     * Construct a new mimetype widget factory.
     */
    constructor(options) {
        super(Private.createRegistryOptions(options));
        this._rendermime = options.rendermime;
        this._renderTimeout = options.renderTimeout || 1000;
        this._dataType = options.dataType || 'string';
        this._fileType = options.primaryFileType;
    }
    /**
     * Create a new widget given a context.
     */
    createNewWidget(context) {
        const ft = this._fileType;
        const mimeType = ft.mimeTypes.length ? ft.mimeTypes[0] : 'text/plain';
        const rendermime = this._rendermime.clone({
            resolver: context.urlResolver
        });
        const renderer = rendermime.createRenderer(mimeType);
        const content = new MimeContent({
            context,
            renderer,
            mimeType,
            renderTimeout: this._renderTimeout,
            dataType: this._dataType
        });
        content.title.iconClass = ft.iconClass;
        content.title.iconLabel = ft.iconLabel;
        const widget = new MimeDocument({ content, context });
        return widget;
    }
}
exports.MimeDocumentFactory = MimeDocumentFactory;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * Create the document registry options.
     */
    function createRegistryOptions(options) {
        return Object.assign({}, options, { readOnly: true });
    }
    Private.createRegistryOptions = createRegistryOptions;
})(Private || (Private = {}));


/***/ }),

/***/ "A+xa":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/cv.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var cv = moment.defineLocale('cv', {
    months : 'кӑрлач_нарӑс_пуш_ака_май_ҫӗртме_утӑ_ҫурла_авӑн_юпа_чӳк_раштав'.split('_'),
    monthsShort : 'кӑр_нар_пуш_ака_май_ҫӗр_утӑ_ҫур_авн_юпа_чӳк_раш'.split('_'),
    weekdays : 'вырсарникун_тунтикун_ытларикун_юнкун_кӗҫнерникун_эрнекун_шӑматкун'.split('_'),
    weekdaysShort : 'выр_тун_ытл_юн_кӗҫ_эрн_шӑм'.split('_'),
    weekdaysMin : 'вр_тн_ыт_юн_кҫ_эр_шм'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD-MM-YYYY',
        LL : 'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ]',
        LLL : 'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm',
        LLLL : 'dddd, YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm'
    },
    calendar : {
        sameDay: '[Паян] LT [сехетре]',
        nextDay: '[Ыран] LT [сехетре]',
        lastDay: '[Ӗнер] LT [сехетре]',
        nextWeek: '[Ҫитес] dddd LT [сехетре]',
        lastWeek: '[Иртнӗ] dddd LT [сехетре]',
        sameElse: 'L'
    },
    relativeTime : {
        future : function (output) {
            var affix = /сехет$/i.exec(output) ? 'рен' : /ҫул$/i.exec(output) ? 'тан' : 'ран';
            return output + affix;
        },
        past : '%s каялла',
        s : 'пӗр-ик ҫеккунт',
        ss : '%d ҫеккунт',
        m : 'пӗр минут',
        mm : '%d минут',
        h : 'пӗр сехет',
        hh : '%d сехет',
        d : 'пӗр кун',
        dd : '%d кун',
        M : 'пӗр уйӑх',
        MM : '%d уйӑх',
        y : 'пӗр ҫул',
        yy : '%d ҫул'
    },
    dayOfMonthOrdinalParse: /\d{1,2}-мӗш/,
    ordinal : '%d-мӗш',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return cv;

})));


/***/ }),

/***/ "A1bG":
/*!**************************************************************!*\
  !*** ./node_modules/@jupyterlab/rendermime/lib/renderers.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const ansi_up_1 = __importDefault(__webpack_require__(/*! ansi_up */ "E4Z0"));
const marked_1 = __importDefault(__webpack_require__(/*! marked */ "DlQD"));
const codemirror_1 = __webpack_require__(/*! @jupyterlab/codemirror */ "ddNL");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const latex_1 = __webpack_require__(/*! ./latex */ "lOjS");
/**
 * Render HTML into a host node.
 *
 * @params options - The options for rendering.
 *
 * @returns A promise which resolves when rendering is complete.
 */
function renderHTML(options) {
    // Unpack the options.
    let { host, source, trusted, sanitizer, resolver, linkHandler, shouldTypeset, latexTypesetter } = options;
    let originalSource = source;
    // Bail early if the source is empty.
    if (!source) {
        host.textContent = '';
        return Promise.resolve(undefined);
    }
    // Sanitize the source if it is not trusted. This removes all
    // `<script>` tags as well as other potentially harmful HTML.
    if (!trusted) {
        originalSource = `${source}`;
        source = sanitizer.sanitize(source);
    }
    // Set the inner HTML of the host.
    host.innerHTML = source;
    if (host.getElementsByTagName('script').length > 0) {
        // If output it trusted, eval any script tags contained in the HTML.
        // This is not done automatically by the browser when script tags are
        // created by setting `innerHTML`.
        if (trusted) {
            Private.evalInnerHTMLScriptTags(host);
        }
        else {
            const container = document.createElement('div');
            const warning = document.createElement('pre');
            warning.textContent =
                'This HTML output contains inline scripts. Are you sure that you want to run arbitrary Javascript within your JupyterLab session?';
            const runButton = document.createElement('button');
            runButton.textContent = 'Run';
            runButton.onclick = event => {
                host.innerHTML = originalSource;
                Private.evalInnerHTMLScriptTags(host);
                host.removeChild(host.firstChild);
            };
            container.appendChild(warning);
            container.appendChild(runButton);
            host.insertBefore(container, host.firstChild);
        }
    }
    // Handle default behavior of nodes.
    Private.handleDefaults(host, resolver);
    // Patch the urls if a resolver is available.
    let promise;
    if (resolver) {
        promise = Private.handleUrls(host, resolver, linkHandler);
    }
    else {
        promise = Promise.resolve(undefined);
    }
    // Return the final rendered promise.
    return promise.then(() => {
        if (shouldTypeset && latexTypesetter) {
            latexTypesetter.typeset(host);
        }
    });
}
exports.renderHTML = renderHTML;
/**
 * Render an image into a host node.
 *
 * @params options - The options for rendering.
 *
 * @returns A promise which resolves when rendering is complete.
 */
function renderImage(options) {
    // Unpack the options.
    let { host, mimeType, source, width, height, needsBackground, unconfined } = options;
    // Clear the content in the host.
    host.textContent = '';
    // Create the image element.
    let img = document.createElement('img');
    // Set the source of the image.
    img.src = `data:${mimeType};base64,${source}`;
    // Set the size of the image if provided.
    if (typeof height === 'number') {
        img.height = height;
    }
    if (typeof width === 'number') {
        img.width = width;
    }
    if (needsBackground === 'light') {
        img.classList.add('jp-needs-light-background');
    }
    else if (needsBackground === 'dark') {
        img.classList.add('jp-needs-dark-background');
    }
    if (unconfined === true) {
        img.classList.add('jp-mod-unconfined');
    }
    // Add the image to the host.
    host.appendChild(img);
    // Return the rendered promise.
    return Promise.resolve(undefined);
}
exports.renderImage = renderImage;
/**
 * Render LaTeX into a host node.
 *
 * @params options - The options for rendering.
 *
 * @returns A promise which resolves when rendering is complete.
 */
function renderLatex(options) {
    // Unpack the options.
    let { host, source, shouldTypeset, latexTypesetter } = options;
    // Set the source on the node.
    host.textContent = source;
    // Typeset the node if needed.
    if (shouldTypeset && latexTypesetter) {
        latexTypesetter.typeset(host);
    }
    // Return the rendered promise.
    return Promise.resolve(undefined);
}
exports.renderLatex = renderLatex;
/**
 * Render Markdown into a host node.
 *
 * @params options - The options for rendering.
 *
 * @returns A promise which resolves when rendering is complete.
 */
function renderMarkdown(options) {
    // Unpack the options.
    let { host, source, trusted, sanitizer, resolver, linkHandler, latexTypesetter, shouldTypeset } = options;
    // Clear the content if there is no source.
    if (!source) {
        host.textContent = '';
        return Promise.resolve(undefined);
    }
    // Separate math from normal markdown text.
    let parts = latex_1.removeMath(source);
    // Render the markdown and handle sanitization.
    return Private.renderMarked(parts['text'])
        .then(content => {
        // Restore the math content in the rendered markdown.
        content = latex_1.replaceMath(content, parts['math']);
        let originalContent = content;
        // Sanitize the content it is not trusted.
        if (!trusted) {
            originalContent = `${content}`;
            content = sanitizer.sanitize(content);
        }
        // Set the inner HTML of the host.
        host.innerHTML = content;
        if (host.getElementsByTagName('script').length > 0) {
            // If output it trusted, eval any script tags contained in the HTML.
            // This is not done automatically by the browser when script tags are
            // created by setting `innerHTML`.
            if (trusted) {
                Private.evalInnerHTMLScriptTags(host);
            }
            else {
                const container = document.createElement('div');
                const warning = document.createElement('pre');
                warning.textContent =
                    'This HTML output contains inline scripts. Are you sure that you want to run arbitrary Javascript within your JupyterLab session?';
                const runButton = document.createElement('button');
                runButton.textContent = 'Run';
                runButton.onclick = event => {
                    host.innerHTML = originalContent;
                    Private.evalInnerHTMLScriptTags(host);
                    host.removeChild(host.firstChild);
                };
                container.appendChild(warning);
                container.appendChild(runButton);
                host.insertBefore(container, host.firstChild);
            }
        }
        // Handle default behavior of nodes.
        Private.handleDefaults(host, resolver);
        // Apply ids to the header nodes.
        Private.headerAnchors(host);
        // Patch the urls if a resolver is available.
        let promise;
        if (resolver) {
            promise = Private.handleUrls(host, resolver, linkHandler);
        }
        else {
            promise = Promise.resolve(undefined);
        }
        // Return the rendered promise.
        return promise;
    })
        .then(() => {
        if (shouldTypeset && latexTypesetter) {
            latexTypesetter.typeset(host);
        }
    });
}
exports.renderMarkdown = renderMarkdown;
/**
 * Render SVG into a host node.
 *
 * @params options - The options for rendering.
 *
 * @returns A promise which resolves when rendering is complete.
 */
function renderSVG(options) {
    // Unpack the options.
    let { host, source, trusted, unconfined } = options;
    // Clear the content if there is no source.
    if (!source) {
        host.textContent = '';
        return Promise.resolve(undefined);
    }
    // Display a message if the source is not trusted.
    if (!trusted) {
        host.textContent =
            'Cannot display an untrusted SVG. Maybe you need to run the cell?';
        return Promise.resolve(undefined);
    }
    // Render in img so that user can save it easily
    const img = new Image();
    img.src = `data:image/svg+xml,${encodeURIComponent(source)}`;
    host.appendChild(img);
    if (unconfined === true) {
        host.classList.add('jp-mod-unconfined');
    }
    return Promise.resolve();
}
exports.renderSVG = renderSVG;
/**
 * Render text into a host node.
 *
 * @params options - The options for rendering.
 *
 * @returns A promise which resolves when rendering is complete.
 */
function renderText(options) {
    // Unpack the options.
    let { host, source } = options;
    const ansiUp = new ansi_up_1.default();
    ansiUp.escape_for_html = true;
    ansiUp.use_classes = true;
    // Create the HTML content.
    let content = ansiUp.ansi_to_html(source);
    // Set the inner HTML for the host node.
    host.innerHTML = `<pre>${content}</pre>`;
    // Return the rendered promise.
    return Promise.resolve(undefined);
}
exports.renderText = renderText;
/**
 * The namespace for module implementation details.
 */
var Private;
(function (Private) {
    /**
     * Eval the script tags contained in a host populated by `innerHTML`.
     *
     * When script tags are created via `innerHTML`, the browser does not
     * evaluate them when they are added to the page. This function works
     * around that by creating new equivalent script nodes manually, and
     * replacing the originals.
     */
    function evalInnerHTMLScriptTags(host) {
        // Create a snapshot of the current script nodes.
        let scripts = algorithm_1.toArray(host.getElementsByTagName('script'));
        // Loop over each script node.
        for (let script of scripts) {
            // Skip any scripts which no longer have a parent.
            if (!script.parentNode) {
                continue;
            }
            // Create a new script node which will be clone.
            let clone = document.createElement('script');
            // Copy the attributes into the clone.
            let attrs = script.attributes;
            for (let i = 0, n = attrs.length; i < n; ++i) {
                let { name, value } = attrs[i];
                clone.setAttribute(name, value);
            }
            // Copy the text content into the clone.
            clone.textContent = script.textContent;
            // Replace the old script in the parent.
            script.parentNode.replaceChild(clone, script);
        }
    }
    Private.evalInnerHTMLScriptTags = evalInnerHTMLScriptTags;
    /**
     * Render markdown for the specified content.
     *
     * @param content - The string of markdown to render.
     *
     * @return A promise which resolves with the rendered content.
     */
    function renderMarked(content) {
        initializeMarked();
        return new Promise((resolve, reject) => {
            marked_1.default(content, (err, content) => {
                if (err) {
                    reject(err);
                }
                else {
                    resolve(content);
                }
            });
        });
    }
    Private.renderMarked = renderMarked;
    /**
     * Handle the default behavior of nodes.
     */
    function handleDefaults(node, resolver) {
        // Handle anchor elements.
        let anchors = node.getElementsByTagName('a');
        for (let i = 0; i < anchors.length; i++) {
            let path = anchors[i].href || '';
            const isLocal = resolver && resolver.isLocal
                ? resolver.isLocal(path)
                : coreutils_1.URLExt.isLocal(path);
            if (isLocal) {
                anchors[i].target = '_self';
            }
            else {
                anchors[i].target = '_blank';
            }
        }
        // Handle image elements.
        let imgs = node.getElementsByTagName('img');
        for (let i = 0; i < imgs.length; i++) {
            if (!imgs[i].alt) {
                imgs[i].alt = 'Image';
            }
        }
    }
    Private.handleDefaults = handleDefaults;
    /**
     * Resolve the relative urls in element `src` and `href` attributes.
     *
     * @param node - The head html element.
     *
     * @param resolver - A url resolver.
     *
     * @param linkHandler - An optional link handler for nodes.
     *
     * @returns a promise fulfilled when the relative urls have been resolved.
     */
    function handleUrls(node, resolver, linkHandler) {
        // Set up an array to collect promises.
        let promises = [];
        // Handle HTML Elements with src attributes.
        let nodes = node.querySelectorAll('*[src]');
        for (let i = 0; i < nodes.length; i++) {
            promises.push(handleAttr(nodes[i], 'src', resolver));
        }
        // Handle anchor elements.
        let anchors = node.getElementsByTagName('a');
        for (let i = 0; i < anchors.length; i++) {
            promises.push(handleAnchor(anchors[i], resolver, linkHandler));
        }
        // Handle link elements.
        let links = node.getElementsByTagName('link');
        for (let i = 0; i < links.length; i++) {
            promises.push(handleAttr(links[i], 'href', resolver));
        }
        // Wait on all promises.
        return Promise.all(promises).then(() => undefined);
    }
    Private.handleUrls = handleUrls;
    /**
     * Apply ids to headers.
     */
    function headerAnchors(node) {
        let headerNames = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
        for (let headerType of headerNames) {
            let headers = node.getElementsByTagName(headerType);
            for (let i = 0; i < headers.length; i++) {
                let header = headers[i];
                header.id = encodeURIComponent(header.innerHTML.replace(/ /g, '-'));
                let anchor = document.createElement('a');
                anchor.target = '_self';
                anchor.textContent = '¶';
                anchor.href = '#' + header.id;
                anchor.classList.add('jp-InternalAnchorLink');
                header.appendChild(anchor);
            }
        }
    }
    Private.headerAnchors = headerAnchors;
    /**
     * Handle a node with a `src` or `href` attribute.
     */
    function handleAttr(node, name, resolver) {
        let source = node.getAttribute(name) || '';
        const isLocal = resolver.isLocal
            ? resolver.isLocal(source)
            : coreutils_1.URLExt.isLocal(source);
        if (!source || !isLocal) {
            return Promise.resolve(undefined);
        }
        node.setAttribute(name, '');
        return resolver
            .resolveUrl(source)
            .then(urlPath => {
            return resolver.getDownloadUrl(urlPath);
        })
            .then(url => {
            // Check protocol again in case it changed:
            if (coreutils_1.URLExt.parse(url).protocol !== 'data:') {
                // Bust caching for local src attrs.
                // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Bypassing_the_cache
                url += (/\?/.test(url) ? '&' : '?') + new Date().getTime();
            }
            node.setAttribute(name, url);
        })
            .catch(err => {
            // If there was an error getting the url,
            // just make it an empty link.
            node.setAttribute(name, '');
        });
    }
    /**
     * Handle an anchor node.
     */
    function handleAnchor(anchor, resolver, linkHandler) {
        // Get the link path without the location prepended.
        // (e.g. "./foo.md#Header 1" vs "http://localhost:8888/foo.md#Header 1")
        let href = anchor.getAttribute('href') || '';
        const isLocal = resolver.isLocal
            ? resolver.isLocal(href)
            : coreutils_1.URLExt.isLocal(href);
        // Bail if it is not a file-like url.
        if (!href || !isLocal) {
            return Promise.resolve(undefined);
        }
        // Remove the hash until we can handle it.
        let hash = anchor.hash;
        if (hash) {
            // Handle internal link in the file.
            if (hash === href) {
                anchor.target = '_self';
                return Promise.resolve(undefined);
            }
            // For external links, remove the hash until we have hash handling.
            href = href.replace(hash, '');
        }
        // Get the appropriate file path.
        return resolver
            .resolveUrl(href)
            .then(urlPath => {
            // decode encoded url from url to api path
            const path = decodeURI(urlPath);
            // Handle the click override.
            if (linkHandler) {
                linkHandler.handleLink(anchor, path, hash);
            }
            // Get the appropriate file download path.
            return resolver.getDownloadUrl(urlPath);
        })
            .then(url => {
            // Set the visible anchor.
            anchor.href = url + hash;
        })
            .catch(err => {
            // If there was an error getting the url,
            // just make it an empty link.
            anchor.href = '';
        });
    }
    let markedInitialized = false;
    /**
     * Support GitHub flavored Markdown, leave sanitizing to external library.
     */
    function initializeMarked() {
        if (markedInitialized) {
            return;
        }
        markedInitialized = true;
        marked_1.default.setOptions({
            gfm: true,
            sanitize: false,
            tables: true,
            // breaks: true; We can't use GFM breaks as it causes problems with tables
            langPrefix: `cm-s-${codemirror_1.CodeMirrorEditor.defaultConfig.theme} language-`,
            highlight: (code, lang, callback) => {
                let cb = (err, code) => {
                    if (callback) {
                        callback(err, code);
                    }
                    return code;
                };
                if (!lang) {
                    // no language, no highlight
                    return cb(null, code);
                }
                codemirror_1.Mode.ensure(lang)
                    .then(spec => {
                    let el = document.createElement('div');
                    if (!spec) {
                        console.log(`No CodeMirror mode: ${lang}`);
                        return cb(null, code);
                    }
                    try {
                        codemirror_1.Mode.run(code, spec.mime, el);
                        return cb(null, el.innerHTML);
                    }
                    catch (err) {
                        console.log(`Failed to highlight ${lang} code`, err);
                        return cb(err, code);
                    }
                })
                    .catch(err => {
                    console.log(`No CodeMirror mode: ${lang}`);
                    console.log(`Require CodeMirror mode error: ${err}`);
                    return cb(null, code);
                });
                return code;
            }
        });
    }
})(Private || (Private = {}));


/***/ }),

/***/ "A1k/":
/*!***********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeLineIcon.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeLineIcon = function TraceTypeLineIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement(
            'g',
            { fill: 'none' },
            _react2.default.createElement('path', { d: 'M0 0h46v46H0z' }),
            _react2.default.createElement('path', { stroke: '#25fdfc', d: 'M5.087 39l9.391-12.913 8.218 7.043L37.957 12', strokeMiterlimit: '10', strokeWidth: '2.348' }),
            _react2.default.createElement('path', { stroke: '#1d9bfb', d: 'M12.13 37.826l11.74-15.261 8.217 7.044 8.217-11.739', strokeMiterlimit: '10', strokeWidth: '2.348' })
        )
    );
};

exports.default = TraceTypeLineIcon;

/***/ }),

/***/ "A5Xg":
/*!******************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_object-gopn-ext.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = __webpack_require__(/*! ./_to-iobject */ "NsO/");
var gOPN = __webpack_require__(/*! ./_object-gopn */ "ar/p").f;
var toString = {}.toString;

var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
  ? Object.getOwnPropertyNames(window) : [];

var getWindowNames = function (it) {
  try {
    return gOPN(it);
  } catch (e) {
    return windowNames.slice();
  }
};

module.exports.f = function getOwnPropertyNames(it) {
  return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
};


/***/ }),

/***/ "A5fR":
/*!***********************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/connectToContainer.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.containerConnectedContextTypes = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

exports.default = connectToContainer;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _unpackPlotProps = __webpack_require__(/*! ./unpackPlotProps */ "WWhV");

var _unpackPlotProps2 = _interopRequireDefault(_unpackPlotProps);

var _lib = __webpack_require__(/*! ../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var containerConnectedContextTypes = exports.containerConnectedContextTypes = {
  localize: _propTypes2.default.func,
  container: _propTypes2.default.object,
  data: _propTypes2.default.array,
  defaultContainer: _propTypes2.default.object,
  fullContainer: _propTypes2.default.object,
  fullData: _propTypes2.default.array,
  fullLayout: _propTypes2.default.object,
  getValObject: _propTypes2.default.func,
  graphDiv: _propTypes2.default.object,
  layout: _propTypes2.default.object,
  onUpdate: _propTypes2.default.func,
  plotly: _propTypes2.default.object,
  updateContainer: _propTypes2.default.func,
  traceIndexes: _propTypes2.default.array
};

function connectToContainer(WrappedComponent) {
  var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

  var ContainerConnectedComponent = function (_Component) {
    _inherits(ContainerConnectedComponent, _Component);

    _createClass(ContainerConnectedComponent, null, [{
      key: 'modifyPlotProps',

      // Run the inner modifications first and allow more recent modifyPlotProp
      // config function to modify last.
      value: function modifyPlotProps(props, context, plotProps) {
        if (WrappedComponent.modifyPlotProps) {
          WrappedComponent.modifyPlotProps(props, context, plotProps);
        }
        if (config.modifyPlotProps) {
          config.modifyPlotProps(props, context, plotProps);
        }
      }
    }]);

    function ContainerConnectedComponent(props, context) {
      _classCallCheck(this, ContainerConnectedComponent);

      var _this = _possibleConstructorReturn(this, (ContainerConnectedComponent.__proto__ || Object.getPrototypeOf(ContainerConnectedComponent)).call(this, props, context));

      _this.setLocals(props, context);
      return _this;
    }

    _createClass(ContainerConnectedComponent, [{
      key: 'componentWillReceiveProps',
      value: function componentWillReceiveProps(nextProps, nextContext) {
        this.setLocals(nextProps, nextContext);
      }
    }, {
      key: 'setLocals',
      value: function setLocals(props, context) {
        this.plotProps = (0, _unpackPlotProps2.default)(props, context);
        this.attr = props.attr;
        ContainerConnectedComponent.modifyPlotProps(props, context, this.plotProps);
      }
    }, {
      key: 'getChildContext',
      value: function getChildContext() {
        return {
          description: this.plotProps.description,
          attr: this.attr
        };
      }
    }, {
      key: 'render',
      value: function render() {
        // Merge plotprops onto props so leaf components only need worry about
        // props. However pass plotProps as a specific prop in case inner component
        // is also wrapped by a component that `unpackPlotProps`. That way inner
        // component can skip computation as it can see plotProps is already defined.
        var _Object$assign = Object.assign({}, this.plotProps, this.props),
            _Object$assign$plotPr = _Object$assign.plotProps,
            plotProps = _Object$assign$plotPr === undefined ? this.plotProps : _Object$assign$plotPr,
            props = _objectWithoutProperties(_Object$assign, ['plotProps']);

        if (props.isVisible) {
          return _react2.default.createElement(WrappedComponent, _extends({}, props, { plotProps: plotProps }));
        }

        return null;
      }
    }]);

    return ContainerConnectedComponent;
  }(_react.Component);

  ContainerConnectedComponent.displayName = 'ContainerConnected' + (0, _lib.getDisplayName)(WrappedComponent);

  ContainerConnectedComponent.contextTypes = containerConnectedContextTypes;
  ContainerConnectedComponent.childContextTypes = {
    description: _propTypes2.default.string,
    attr: _propTypes2.default.string
  };

  var plotly_editor_traits = WrappedComponent.plotly_editor_traits;

  ContainerConnectedComponent.plotly_editor_traits = plotly_editor_traits;

  return ContainerConnectedComponent;
}
//# sourceMappingURL=connectToContainer.js.map

/***/ }),

/***/ "A5vG":
/*!*************************************************!*\
  !*** ./node_modules/mdi-react/OpenInNewIcon.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var OpenInNewIcon = function OpenInNewIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M14,3V5H17.59L7.76,14.83L9.17,16.24L19,6.41V10H21V3M19,19H5V5H12V3H5C3.89,3 3,3.9 3,5V19C3,20.1 3.9,21 5,21H19C20.1,21 21,20.1 21,19V12H19V19Z' })
  );
};

module.exports = OpenInNewIcon;


/***/ }),

/***/ "A7MO":
/*!****************************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/lazy-result.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _mapGenerator = __webpack_require__(/*! ./map-generator */ "vIqA");

var _mapGenerator2 = _interopRequireDefault(_mapGenerator);

var _stringify2 = __webpack_require__(/*! ./stringify */ "3ZTG");

var _stringify3 = _interopRequireDefault(_stringify2);

var _warnOnce = __webpack_require__(/*! ./warn-once */ "thcq");

var _warnOnce2 = _interopRequireDefault(_warnOnce);

var _result = __webpack_require__(/*! ./result */ "TkTV");

var _result2 = _interopRequireDefault(_result);

var _parse = __webpack_require__(/*! ./parse */ "ao+V");

var _parse2 = _interopRequireDefault(_parse);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function isPromise(obj) {
    return (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && typeof obj.then === 'function';
}

/**
 * A Promise proxy for the result of PostCSS transformations.
 *
 * A `LazyResult` instance is returned by {@link Processor#process}.
 *
 * @example
 * const lazy = postcss([cssnext]).process(css);
 */

var LazyResult = function () {
    function LazyResult(processor, css, opts) {
        _classCallCheck(this, LazyResult);

        this.stringified = false;
        this.processed = false;

        var root = void 0;
        if ((typeof css === 'undefined' ? 'undefined' : _typeof(css)) === 'object' && css !== null && css.type === 'root') {
            root = css;
        } else if (css instanceof LazyResult || css instanceof _result2.default) {
            root = css.root;
            if (css.map) {
                if (typeof opts.map === 'undefined') opts.map = {};
                if (!opts.map.inline) opts.map.inline = false;
                opts.map.prev = css.map;
            }
        } else {
            var parser = _parse2.default;
            if (opts.syntax) parser = opts.syntax.parse;
            if (opts.parser) parser = opts.parser;
            if (parser.parse) parser = parser.parse;

            try {
                root = parser(css, opts);
            } catch (error) {
                this.error = error;
            }
        }

        this.result = new _result2.default(processor, root, opts);
    }

    /**
     * Returns a {@link Processor} instance, which will be used
     * for CSS transformations.
     * @type {Processor}
     */


    /**
     * Processes input CSS through synchronous plugins
     * and calls {@link Result#warnings()}.
     *
     * @return {Warning[]} warnings from plugins
     */
    LazyResult.prototype.warnings = function warnings() {
        return this.sync().warnings();
    };

    /**
     * Alias for the {@link LazyResult#css} property.
     *
     * @example
     * lazy + '' === lazy.css;
     *
     * @return {string} output CSS
     */


    LazyResult.prototype.toString = function toString() {
        return this.css;
    };

    /**
     * Processes input CSS through synchronous and asynchronous plugins
     * and calls `onFulfilled` with a Result instance. If a plugin throws
     * an error, the `onRejected` callback will be executed.
     *
     * It implements standard Promise API.
     *
     * @param {onFulfilled} onFulfilled - callback will be executed
     *                                    when all plugins will finish work
     * @param {onRejected}  onRejected  - callback will be executed on any error
     *
     * @return {Promise} Promise API to make queue
     *
     * @example
     * postcss([cssnext]).process(css, { from: cssPath }).then(result => {
     *   console.log(result.css);
     * });
     */


    LazyResult.prototype.then = function then(onFulfilled, onRejected) {
        if (!('from' in this.opts)) {
            (0, _warnOnce2.default)('Without `from` option PostCSS could generate wrong ' + 'source map and will not find Browserslist config. ' + 'Set it to CSS file path or to `undefined` to prevent ' + 'this warning.');
        }
        return this.async().then(onFulfilled, onRejected);
    };

    /**
     * Processes input CSS through synchronous and asynchronous plugins
     * and calls onRejected for each error thrown in any plugin.
     *
     * It implements standard Promise API.
     *
     * @param {onRejected} onRejected - callback will be executed on any error
     *
     * @return {Promise} Promise API to make queue
     *
     * @example
     * postcss([cssnext]).process(css).then(result => {
     *   console.log(result.css);
     * }).catch(error => {
     *   console.error(error);
     * });
     */


    LazyResult.prototype.catch = function _catch(onRejected) {
        return this.async().catch(onRejected);
    };

    LazyResult.prototype.handleError = function handleError(error, plugin) {
        try {
            this.error = error;
            if (error.name === 'CssSyntaxError' && !error.plugin) {
                error.plugin = plugin.postcssPlugin;
                error.setMessage();
            } else if (plugin.postcssVersion) {
                var pluginName = plugin.postcssPlugin;
                var pluginVer = plugin.postcssVersion;
                var runtimeVer = this.result.processor.version;
                var a = pluginVer.split('.');
                var b = runtimeVer.split('.');

                if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) {
                    console.error('Unknown error from PostCSS plugin. ' + 'Your current PostCSS version ' + 'is ' + runtimeVer + ', but ' + pluginName + ' ' + 'uses ' + pluginVer + '. Perhaps this is ' + 'the source of the error below.');
                }
            }
        } catch (err) {
            if (console && console.error) console.error(err);
        }
    };

    LazyResult.prototype.asyncTick = function asyncTick(resolve, reject) {
        var _this = this;

        if (this.plugin >= this.processor.plugins.length) {
            this.processed = true;
            return resolve();
        }

        try {
            var plugin = this.processor.plugins[this.plugin];
            var promise = this.run(plugin);
            this.plugin += 1;

            if (isPromise(promise)) {
                promise.then(function () {
                    _this.asyncTick(resolve, reject);
                }).catch(function (error) {
                    _this.handleError(error, plugin);
                    _this.processed = true;
                    reject(error);
                });
            } else {
                this.asyncTick(resolve, reject);
            }
        } catch (error) {
            this.processed = true;
            reject(error);
        }
    };

    LazyResult.prototype.async = function async() {
        var _this2 = this;

        if (this.processed) {
            return new Promise(function (resolve, reject) {
                if (_this2.error) {
                    reject(_this2.error);
                } else {
                    resolve(_this2.stringify());
                }
            });
        }
        if (this.processing) {
            return this.processing;
        }

        this.processing = new Promise(function (resolve, reject) {
            if (_this2.error) return reject(_this2.error);
            _this2.plugin = 0;
            _this2.asyncTick(resolve, reject);
        }).then(function () {
            _this2.processed = true;
            return _this2.stringify();
        });

        return this.processing;
    };

    LazyResult.prototype.sync = function sync() {
        if (this.processed) return this.result;
        this.processed = true;

        if (this.processing) {
            throw new Error('Use process(css).then(cb) to work with async plugins');
        }

        if (this.error) throw this.error;

        for (var _iterator = this.result.processor.plugins, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
            var _ref;

            if (_isArray) {
                if (_i >= _iterator.length) break;
                _ref = _iterator[_i++];
            } else {
                _i = _iterator.next();
                if (_i.done) break;
                _ref = _i.value;
            }

            var plugin = _ref;

            var promise = this.run(plugin);
            if (isPromise(promise)) {
                throw new Error('Use process(css).then(cb) to work with async plugins');
            }
        }

        return this.result;
    };

    LazyResult.prototype.run = function run(plugin) {
        this.result.lastPlugin = plugin;

        try {
            return plugin(this.result.root, this.result);
        } catch (error) {
            this.handleError(error, plugin);
            throw error;
        }
    };

    LazyResult.prototype.stringify = function stringify() {
        if (this.stringified) return this.result;
        this.stringified = true;

        this.sync();

        var opts = this.result.opts;
        var str = _stringify3.default;
        if (opts.syntax) str = opts.syntax.stringify;
        if (opts.stringifier) str = opts.stringifier;
        if (str.stringify) str = str.stringify;

        var map = new _mapGenerator2.default(str, this.result.root, this.result.opts);
        var data = map.generate();
        this.result.css = data[0];
        this.result.map = data[1];

        return this.result;
    };

    _createClass(LazyResult, [{
        key: 'processor',
        get: function get() {
            return this.result.processor;
        }

        /**
         * Options from the {@link Processor#process} call.
         * @type {processOptions}
         */

    }, {
        key: 'opts',
        get: function get() {
            return this.result.opts;
        }

        /**
         * Processes input CSS through synchronous plugins, converts `Root`
         * to a CSS string and returns {@link Result#css}.
         *
         * This property will only work with synchronous plugins.
         * If the processor contains any asynchronous plugins
         * it will throw an error. This is why this method is only
         * for debug purpose, you should always use {@link LazyResult#then}.
         *
         * @type {string}
         * @see Result#css
         */

    }, {
        key: 'css',
        get: function get() {
            return this.stringify().css;
        }

        /**
         * An alias for the `css` property. Use it with syntaxes
         * that generate non-CSS output.
         *
         * This property will only work with synchronous plugins.
         * If the processor contains any asynchronous plugins
         * it will throw an error. This is why this method is only
         * for debug purpose, you should always use {@link LazyResult#then}.
         *
         * @type {string}
         * @see Result#content
         */

    }, {
        key: 'content',
        get: function get() {
            return this.stringify().content;
        }

        /**
         * Processes input CSS through synchronous plugins
         * and returns {@link Result#map}.
         *
         * This property will only work with synchronous plugins.
         * If the processor contains any asynchronous plugins
         * it will throw an error. This is why this method is only
         * for debug purpose, you should always use {@link LazyResult#then}.
         *
         * @type {SourceMapGenerator}
         * @see Result#map
         */

    }, {
        key: 'map',
        get: function get() {
            return this.stringify().map;
        }

        /**
         * Processes input CSS through synchronous plugins
         * and returns {@link Result#root}.
         *
         * This property will only work with synchronous plugins. If the processor
         * contains any asynchronous plugins it will throw an error.
         *
         * This is why this method is only for debug purpose,
         * you should always use {@link LazyResult#then}.
         *
         * @type {Root}
         * @see Result#root
         */

    }, {
        key: 'root',
        get: function get() {
            return this.sync().root;
        }

        /**
         * Processes input CSS through synchronous plugins
         * and returns {@link Result#messages}.
         *
         * This property will only work with synchronous plugins. If the processor
         * contains any asynchronous plugins it will throw an error.
         *
         * This is why this method is only for debug purpose,
         * you should always use {@link LazyResult#then}.
         *
         * @type {Message[]}
         * @see Result#messages
         */

    }, {
        key: 'messages',
        get: function get() {
            return this.sync().messages;
        }
    }]);

    return LazyResult;
}();

exports.default = LazyResult;

/**
 * @callback onFulfilled
 * @param {Result} result
 */

/**
 * @callback onRejected
 * @param {Error} error
 */

module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64, 


/***/ }),

/***/ "A90E":
/*!******************************************!*\
  !*** ./node_modules/lodash/_baseKeys.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isPrototype = __webpack_require__(/*! ./_isPrototype */ "6sVZ"),
    nativeKeys = __webpack_require__(/*! ./_nativeKeys */ "V6Ve");

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * 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;
}

module.exports = baseKeys;


/***/ }),

/***/ "AGAg":
/*!*****************************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils/lib/mainareawidget.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const spinner_1 = __webpack_require__(/*! ./spinner */ "d2xu");
const toolbar_1 = __webpack_require__(/*! ./toolbar */ "yhkN");
/**
 * A widget meant to be contained in the JupyterLab main area.
 *
 * #### Notes
 * Mirrors all of the `title` attributes of the content.
 * This widget is `closable` by default.
 * This widget is automatically disposed when closed.
 * This widget ensures its own focus when activated.
 */
class MainAreaWidget extends widgets_1.Widget {
    /**
     * Construct a new main area widget.
     *
     * @param options - The options for initializing the widget.
     */
    constructor(options) {
        super(options);
        this._changeGuard = false;
        this._spinner = new spinner_1.Spinner();
        this._isRevealed = false;
        this.addClass('jp-MainAreaWidget');
        this.id = coreutils_1.UUID.uuid4();
        const content = (this._content = options.content);
        const toolbar = (this._toolbar = options.toolbar || new toolbar_1.Toolbar());
        const spinner = this._spinner;
        const layout = (this.layout = new widgets_1.BoxLayout({ spacing: 0 }));
        layout.direction = 'top-to-bottom';
        widgets_1.BoxLayout.setStretch(toolbar, 0);
        widgets_1.BoxLayout.setStretch(content, 1);
        layout.addWidget(toolbar);
        layout.addWidget(content);
        if (!content.id) {
            content.id = coreutils_1.UUID.uuid4();
        }
        content.node.tabIndex = -1;
        this._updateTitle();
        content.title.changed.connect(this._updateTitle, this);
        this.title.closable = true;
        this.title.changed.connect(this._updateContentTitle, this);
        if (options.reveal) {
            this.node.appendChild(spinner.node);
            this._revealed = options.reveal
                .then(() => {
                if (content.isDisposed) {
                    this.dispose();
                    return;
                }
                content.disposed.connect(() => this.dispose());
                const active = document.activeElement === spinner.node;
                this.node.removeChild(spinner.node);
                spinner.dispose();
                this._isRevealed = true;
                if (active) {
                    this._focusContent();
                }
            })
                .catch(e => {
                // Show a revealed promise error.
                const error = new widgets_1.Widget();
                // Show the error to the user.
                const pre = document.createElement('pre');
                pre.textContent = String(e);
                error.node.appendChild(pre);
                widgets_1.BoxLayout.setStretch(error, 1);
                this.node.removeChild(spinner.node);
                spinner.dispose();
                content.dispose();
                this._content = null;
                toolbar.dispose();
                this._toolbar = null;
                layout.addWidget(error);
                this._isRevealed = true;
                throw error;
            });
        }
        else {
            // Handle no reveal promise.
            spinner.dispose();
            content.disposed.connect(() => this.dispose());
            this._isRevealed = true;
            this._revealed = Promise.resolve(undefined);
        }
    }
    /**
     * The content hosted by the widget.
     */
    get content() {
        return this._content;
    }
    /**
     * The toolbar hosted by the widget.
     */
    get toolbar() {
        return this._toolbar;
    }
    /**
     * Whether the content widget or an error is revealed.
     */
    get isRevealed() {
        return this._isRevealed;
    }
    /**
     * A promise that resolves when the widget is revealed.
     */
    get revealed() {
        return this._revealed;
    }
    /**
     * Handle `'activate-request'` messages.
     */
    onActivateRequest(msg) {
        if (this._isRevealed) {
            if (this._content) {
                this._focusContent();
            }
        }
        else {
            this._spinner.node.focus();
        }
    }
    /**
     * Handle `'close-request'` messages.
     */
    onCloseRequest(msg) {
        this.dispose();
    }
    /**
     * Update the title based on the attributes of the child widget.
     */
    _updateTitle() {
        if (this._changeGuard) {
            return;
        }
        this._changeGuard = true;
        const content = this.content;
        this.title.label = content.title.label;
        this.title.mnemonic = content.title.mnemonic;
        this.title.iconClass = content.title.iconClass;
        this.title.iconLabel = content.title.iconLabel;
        this.title.caption = content.title.caption;
        this.title.className = content.title.className;
        this.title.dataset = content.title.dataset;
        this._changeGuard = false;
    }
    /**
     * Update the content title based on attributes of the main widget.
     */
    _updateContentTitle() {
        if (this._changeGuard) {
            return;
        }
        this._changeGuard = true;
        const content = this.content;
        content.title.label = this.title.label;
        content.title.mnemonic = this.title.mnemonic;
        content.title.iconClass = this.title.iconClass;
        content.title.iconLabel = this.title.iconLabel;
        content.title.caption = this.title.caption;
        content.title.className = this.title.className;
        content.title.dataset = this.title.dataset;
        this._changeGuard = false;
    }
    /**
     * Give focus to the content.
     */
    _focusContent() {
        // Focus the content node if we aren't already focused on it or a
        // descendent.
        if (!this.content.node.contains(document.activeElement)) {
            this.content.node.focus();
        }
        // Activate the content asynchronously (which may change the focus).
        this.content.activate();
    }
}
exports.MainAreaWidget = MainAreaWidget;


/***/ }),

/***/ "AII8":
/*!****************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/notifier.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




var d3 = __webpack_require__(/*! d3 */ "bljh");
var isNumeric = __webpack_require__(/*! fast-isnumeric */ "GbLo");

var NOTEDATA = [];

/**
 * notifier
 * @param {String} text The person's user name
 * @param {Number} [delay=1000] The delay time in milliseconds
 *          or 'long' which provides 2000 ms delay time.
 * @return {undefined} this function does not return a value
 */
module.exports = function(text, displayLength) {
    if(NOTEDATA.indexOf(text) !== -1) return;

    NOTEDATA.push(text);

    var ts = 1000;
    if(isNumeric(displayLength)) ts = displayLength;
    else if(displayLength === 'long') ts = 3000;

    var notifierContainer = d3.select('body')
        .selectAll('.plotly-notifier')
        .data([0]);
    notifierContainer.enter()
        .append('div')
        .classed('plotly-notifier', true);

    var notes = notifierContainer.selectAll('.notifier-note').data(NOTEDATA);

    function killNote(transition) {
        transition
            .duration(700)
            .style('opacity', 0)
            .each('end', function(thisText) {
                var thisIndex = NOTEDATA.indexOf(thisText);
                if(thisIndex !== -1) NOTEDATA.splice(thisIndex, 1);
                d3.select(this).remove();
            });
    }

    notes.enter().append('div')
        .classed('notifier-note', true)
        .style('opacity', 0)
        .each(function(thisText) {
            var note = d3.select(this);

            note.append('button')
                .classed('notifier-close', true)
                .html('&times;')
                .on('click', function() {
                    note.transition().call(killNote);
                });

            var p = note.append('p');
            var lines = thisText.split(/<br\s*\/?>/g);
            for(var i = 0; i < lines.length; i++) {
                if(i) p.append('br');
                p.append('span').text(lines[i]);
            }

            note.transition()
                    .duration(700)
                    .style('opacity', 1)
                .transition()
                    .delay(ts)
                    .call(killNote);
        });
};


/***/ }),

/***/ "AIml":
/*!*****************************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils/lib/windowresolver.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
/* tslint:disable */
/**
 * The default window resolver token.
 */
exports.IWindowResolver = new coreutils_1.Token('@jupyterlab/apputils:IWindowResolver');
/**
 * A concrete implementation of a window name resolver.
 */
class WindowResolver {
    constructor() {
        this._name = null;
    }
    /**
     * The resolved window name.
     */
    get name() {
        return this._name;
    }
    /**
     * Resolve a window name to use as a handle among shared resources.
     *
     * @param candidate - The potential window name being resolved.
     *
     * #### Notes
     * Typically, the name candidate should be a JupyterLab workspace name or
     * an empty string if there is no workspace.
     *
     * If the returned promise rejects, a window name cannot be resolved without
     * user intervention, which typically means navigation to a new URL.
     */
    resolve(candidate) {
        return Private.resolve(candidate).then(name => {
            this._name = name;
        });
    }
}
exports.WindowResolver = WindowResolver;
/*
 * A namespace for private module data.
 */
var Private;
(function (Private) {
    /**
     * The internal prefix for private local storage keys.
     */
    const PREFIX = '@jupyterlab/coreutils:StateDB';
    /**
     * The local storage beacon key.
     */
    const BEACON = `${PREFIX}:beacon`;
    /**
     * The timeout (in ms) to wait for beacon responders.
     *
     * #### Notes
     * This value is a whole number between 200 and 500 in order to prevent
     * perfect timeout collisions between multiple simultaneously opening windows
     * that have the same URL. This is an edge case because multiple windows
     * should not ordinarily share the same URL, but it can be contrived.
     */
    const TIMEOUT = Math.floor(200 + Math.random() * 300);
    /**
     * The local storage window key.
     */
    const WINDOW = `${PREFIX}:window`;
    /**
     * A potential preferred default window name.
     */
    let candidate = null;
    /**
     * The window name promise.
     */
    let delegate = new coreutils_1.PromiseDelegate();
    /**
     * The known window names.
     */
    let known = {};
    /**
     * The window name.
     */
    let name = null;
    /**
     * Whether the name resolution has completed.
     */
    let resolved = false;
    /**
     * Start the storage event handler.
     */
    function initialize() {
        // Listen to all storage events for beacons and window names.
        window.addEventListener('storage', (event) => {
            const { key, newValue } = event;
            // All the keys we care about have values.
            if (newValue === null) {
                return;
            }
            // If the beacon was fired, respond with a ping.
            if (key === BEACON && candidate !== null) {
                ping(resolved ? name : candidate);
                return;
            }
            // If the window name is resolved, bail.
            if (resolved || key !== WINDOW) {
                return;
            }
            const reported = newValue.replace(/\-\d+$/, '');
            // Store the reported window name.
            known[reported] = null;
            // If a reported window name and candidate collide, reject the candidate.
            if (candidate in known) {
                reject();
            }
        });
    }
    /**
     * Ping peers with payload.
     */
    function ping(payload) {
        if (payload === null) {
            return;
        }
        const { localStorage } = window;
        localStorage.setItem(WINDOW, `${payload}-${new Date().getTime()}`);
    }
    /**
     * Reject the candidate.
     */
    function reject() {
        resolved = true;
        delegate.reject(`Window name candidate "${candidate}" already exists`);
    }
    /**
     * Returns a promise that resolves with the window name used for restoration.
     */
    function resolve(potential) {
        if (resolved) {
            return delegate.promise;
        }
        // Set the local candidate.
        candidate = potential;
        if (candidate in known) {
            reject();
            return delegate.promise;
        }
        const { localStorage, setTimeout } = window;
        // Wait until other windows have reported before claiming the candidate.
        setTimeout(() => {
            if (resolved) {
                return;
            }
            // If the window name has not already been resolved, check one last time
            // to confirm it is not a duplicate before resolving.
            if (candidate in known) {
                return reject();
            }
            resolved = true;
            delegate.resolve((name = candidate));
            ping(name);
        }, TIMEOUT);
        // Fire the beacon to collect other windows' names.
        localStorage.setItem(BEACON, `${Math.random()}-${new Date().getTime()}`);
        return delegate.promise;
    }
    Private.resolve = resolve;
    // Initialize the storage listener at runtime.
    (() => {
        initialize();
    })();
})(Private || (Private = {}));


/***/ }),

/***/ "AK1u":
/*!**********************************************!*\
  !*** ./node_modules/ajv/lib/dotjs/format.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_format(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  if (it.opts.format === false) {
    if ($breakOnError) {
      out += ' if (true) { ';
    }
    return out;
  }
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $unknownFormats = it.opts.unknownFormats,
    $allowUnknown = Array.isArray($unknownFormats);
  if ($isData) {
    var $format = 'format' + $lvl,
      $isObject = 'isObject' + $lvl,
      $formatType = 'formatType' + $lvl;
    out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \'string\'; if (' + ($isObject) + ') { ';
    if (it.async) {
      out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; ';
    }
    out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if (  ';
    if ($isData) {
      out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
    }
    out += ' (';
    if ($unknownFormats != 'ignore') {
      out += ' (' + ($schemaValue) + ' && !' + ($format) + ' ';
      if ($allowUnknown) {
        out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 ';
      }
      out += ') || ';
    }
    out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? ';
    if (it.async) {
      out += ' (async' + ($lvl) + ' ? ' + (it.yieldAwait) + ' ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) ';
    } else {
      out += ' ' + ($format) + '(' + ($data) + ') ';
    }
    out += ' : ' + ($format) + '.test(' + ($data) + '))))) {';
  } else {
    var $format = it.formats[$schema];
    if (!$format) {
      if ($unknownFormats == 'ignore') {
        console.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"');
        if ($breakOnError) {
          out += ' if (true) { ';
        }
        return out;
      } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) {
        if ($breakOnError) {
          out += ' if (true) { ';
        }
        return out;
      } else {
        throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"');
      }
    }
    var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate;
    var $formatType = $isObject && $format.type || 'string';
    if ($isObject) {
      var $async = $format.async === true;
      $format = $format.validate;
    }
    if ($formatType != $ruleType) {
      if ($breakOnError) {
        out += ' if (true) { ';
      }
      return out;
    }
    if ($async) {
      if (!it.async) throw new Error('async format in sync schema');
      var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';
      out += ' if (!(' + (it.yieldAwait) + ' ' + ($formatRef) + '(' + ($data) + '))) { ';
    } else {
      out += ' if (! ';
      var $formatRef = 'formats' + it.util.getProperty($schema);
      if ($isObject) $formatRef += '.validate';
      if (typeof $format == 'function') {
        out += ' ' + ($formatRef) + '(' + ($data) + ') ';
      } else {
        out += ' ' + ($formatRef) + '.test(' + ($data) + ') ';
      }
      out += ') { ';
    }
  }
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format:  ';
    if ($isData) {
      out += '' + ($schemaValue);
    } else {
      out += '' + (it.util.toQuotedString($schema));
    }
    out += '  } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should match format "';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + (it.util.escapeQuotes($schema));
      }
      out += '"\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + (it.util.toQuotedString($schema));
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += ' } ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}


/***/ }),

/***/ "AKPT":
/*!**********************************************************************!*\
  !*** ./node_modules/draft-js/lib/adjustBlockDepthForContentState.js ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule adjustBlockDepthForContentState
 * @format
 * 
 */



function adjustBlockDepthForContentState(contentState, selectionState, adjustment, maxDepth) {
  var startKey = selectionState.getStartKey();
  var endKey = selectionState.getEndKey();
  var blockMap = contentState.getBlockMap();
  var blocks = blockMap.toSeq().skipUntil(function (_, k) {
    return k === startKey;
  }).takeUntil(function (_, k) {
    return k === endKey;
  }).concat([[endKey, blockMap.get(endKey)]]).map(function (block) {
    var depth = block.getDepth() + adjustment;
    depth = Math.max(0, Math.min(depth, maxDepth));
    return block.set('depth', depth);
  });

  blockMap = blockMap.merge(blocks);

  return contentState.merge({
    blockMap: blockMap,
    selectionBefore: selectionState,
    selectionAfter: selectionState
  });
}

module.exports = adjustBlockDepthForContentState;

/***/ }),

/***/ "AKwq":
/*!*******************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/ModalBox.js ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _classnames = __webpack_require__(/*! classnames */ "TSYQ");

var _classnames2 = _interopRequireDefault(_classnames);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var ModalBox = function (_Component) {
  _inherits(ModalBox, _Component);

  function ModalBox() {
    _classCallCheck(this, ModalBox);

    return _possibleConstructorReturn(this, (ModalBox.__proto__ || Object.getPrototypeOf(ModalBox)).apply(this, arguments));
  }

  _createClass(ModalBox, [{
    key: 'render',
    value: function render() {
      var _props = this.props,
          backgroundDark = _props.backgroundDark,
          children = _props.children,
          onClose = _props.onClose,
          relative = _props.relative;

      var modalboxClass = (0, _classnames2.default)('modalbox', {
        'modalbox--dark': backgroundDark,
        'modalbox--relative': relative
      });
      return _react2.default.createElement(
        'div',
        { className: modalboxClass },
        _react2.default.createElement('div', { className: 'modalbox__cover', onClick: onClose }),
        _react2.default.createElement(
          'div',
          { className: 'modalbox__content' },
          children
        )
      );
    }
  }]);

  return ModalBox;
}(_react.Component);

exports.default = ModalBox;


ModalBox.propTypes = {
  backgroundDark: _propTypes2.default.bool,
  relative: _propTypes2.default.bool,
  children: _propTypes2.default.node,
  onClose: _propTypes2.default.func
};
//# sourceMappingURL=ModalBox.js.map

/***/ }),

/***/ "ANZy":
/*!*******************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotHistogram2dBricksIcon.js ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotHistogram2dBricksIcon = function PlotHistogram2dBricksIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M15 7.063H6v4.625h9zm11 0h-9v4.625h9zM6 24.938h9v-4.625H6zm11 0h9v-4.625h-9zm-5.5-6.625h9v-4.625h-9zm11-4.625v4.625h9v-4.625zm-13 0h-9v4.625h9z' })
    );
};

exports.default = PlotHistogram2dBricksIcon;

/***/ }),

/***/ "ANxK":
/*!************************************************!*\
  !*** ./node_modules/diffie-hellman/browser.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(Buffer) {var generatePrime = __webpack_require__(/*! ./lib/generatePrime */ "WKKt")
var primes = __webpack_require__(/*! ./lib/primes.json */ "wk3p")

var DH = __webpack_require__(/*! ./lib/dh */ "Vh22")

function getDiffieHellman (mod) {
  var prime = new Buffer(primes[mod].prime, 'hex')
  var gen = new Buffer(primes[mod].gen, 'hex')

  return new DH(prime, gen)
}

var ENCODINGS = {
  'binary': true, 'hex': true, 'base64': true
}

function createDiffieHellman (prime, enc, generator, genc) {
  if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) {
    return createDiffieHellman(prime, 'binary', enc, generator)
  }

  enc = enc || 'binary'
  genc = genc || 'binary'
  generator = generator || new Buffer([2])

  if (!Buffer.isBuffer(generator)) {
    generator = new Buffer(generator, genc)
  }

  if (typeof prime === 'number') {
    return new DH(generatePrime(prime, generator), generator, true)
  }

  if (!Buffer.isBuffer(prime)) {
    prime = new Buffer(prime, enc)
  }

  return new DH(prime, generator, true)
}

exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman
exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../buffer/index.js */ "tjlA").Buffer))

/***/ }),

/***/ "AO6+":
/*!******************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/codemirror/theme/mdn-like.css ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*\n  MDN-LIKE Theme - Mozilla\n  Ported to CodeMirror by Peter Kroon <plakroon@gmail.com>\n  Report bugs/issues here: https://github.com/codemirror/CodeMirror/issues\n  GitHub: @peterkroon\n\n  The mdn-like theme is inspired on the displayed code examples at: https://developer.mozilla.org/en-US/docs/Web/CSS/animation\n\n*/\n.cm-s-mdn-like.CodeMirror { color: #999; background-color: #fff; }\n.cm-s-mdn-like div.CodeMirror-selected { background: #cfc; }\n.cm-s-mdn-like .CodeMirror-line::selection, .cm-s-mdn-like .CodeMirror-line > span::selection, .cm-s-mdn-like .CodeMirror-line > span > span::selection { background: #cfc; }\n.cm-s-mdn-like .CodeMirror-line::-moz-selection, .cm-s-mdn-like .CodeMirror-line > span::-moz-selection, .cm-s-mdn-like .CodeMirror-line > span > span::-moz-selection { background: #cfc; }\n\n.cm-s-mdn-like .CodeMirror-gutters { background: #f8f8f8; border-left: 6px solid rgba(0,83,159,0.65); color: #333; }\n.cm-s-mdn-like .CodeMirror-linenumber { color: #aaa; padding-left: 8px; }\n.cm-s-mdn-like .CodeMirror-cursor { border-left: 2px solid #222; }\n\n.cm-s-mdn-like .cm-keyword { color: #6262FF; }\n.cm-s-mdn-like .cm-atom { color: #F90; }\n.cm-s-mdn-like .cm-number { color:  #ca7841; }\n.cm-s-mdn-like .cm-def { color: #8DA6CE; }\n.cm-s-mdn-like span.cm-variable-2, .cm-s-mdn-like span.cm-tag { color: #690; }\n.cm-s-mdn-like span.cm-variable-3, .cm-s-mdn-like span.cm-def, .cm-s-mdn-like span.cm-type { color: #07a; }\n\n.cm-s-mdn-like .cm-variable { color: #07a; }\n.cm-s-mdn-like .cm-property { color: #905; }\n.cm-s-mdn-like .cm-qualifier { color: #690; }\n\n.cm-s-mdn-like .cm-operator { color: #cda869; }\n.cm-s-mdn-like .cm-comment { color:#777; font-weight:normal; }\n.cm-s-mdn-like .cm-string { color:#07a; font-style:italic; }\n.cm-s-mdn-like .cm-string-2 { color:#bd6b18; } /*?*/\n.cm-s-mdn-like .cm-meta { color: #000; } /*?*/\n.cm-s-mdn-like .cm-builtin { color: #9B7536; } /*?*/\n.cm-s-mdn-like .cm-tag { color: #997643; }\n.cm-s-mdn-like .cm-attribute { color: #d6bb6d; } /*?*/\n.cm-s-mdn-like .cm-header { color: #FF6400; }\n.cm-s-mdn-like .cm-hr { color: #AEAEAE; }\n.cm-s-mdn-like .cm-link { color:#ad9361; font-style:italic; text-decoration:none; }\n.cm-s-mdn-like .cm-error { border-bottom: 1px solid red; }\n\ndiv.cm-s-mdn-like .CodeMirror-activeline-background { background: #efefff; }\ndiv.cm-s-mdn-like span.CodeMirror-matchingbracket { outline:1px solid grey; color: inherit; }\n\n.cm-s-mdn-like.CodeMirror { background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFcAAAAyCAYAAAAp8UeFAAAHvklEQVR42s2b63bcNgyEQZCSHCdt2vd/0tWF7I+Q6XgMXiTtuvU5Pl57ZQKkKHzEAOtF5KeIJBGJ8uvL599FRFREZhFx8DeXv8trn68RuGaC8TRfo3SNp9dlDDHedyLyTUTeRWStXKPZrjtpZxaRw5hPqozRs1N8/enzIiQRWcCgy4MUA0f+XWliDhyL8Lfyvx7ei/Ae3iQFHyw7U/59pQVIMEEPEz0G7XiwdRjzSfC3UTtz9vchIntxvry5iMgfIhJoEflOz2CQr3F5h/HfeFe+GTdLaKcu9L8LTeQb/R/7GgbsfKedyNdoHsN31uRPWrfZ5wsj/NzzRQHuToIdU3ahwnsKPxXCjJITuOsi7XLc7SG/v5GdALs7wf8JjTFiB5+QvTEfRyGOfX3Lrx8wxyQi3sNq46O7QahQiCsRFgqddjBouVEHOKDgXAQHD9gJCr5sMKkEdjwsarG/ww3BMHBU7OBjXnzdyY7SfCxf5/z6ATccrwlKuwC/jhznnPF4CgVzhhVf4xp2EixcBActO75iZ8/fM9zAs2OMzKdslgXWJ9XG8PQoOAMA5fGcsvORgv0doBXyHrCwfLJAOwo71QLNkb8n2Pl6EWiR7OCibtkPaz4Kc/0NNAze2gju3zOwekALDaCFPI5vjPFmgGY5AZqyGEvH1x7QfIb8YtxMnA/b+QQ0aQDAwc6JMFg8CbQZ4qoYEEHbRwNojuK3EHwd7VALSgq+MNDKzfT58T8qdpADrgW0GmgcAS1lhzztJmkAzcPNOQbsWEALBDSlMKUG0Eq4CLAQWvEVQ9WU57gZJwZtgPO3r9oBTQ9WO8TjqXINx8R0EYpiZEUWOF3FxkbJkgU9B2f41YBrIj5ZfsQa0M5kTgiAAqM3ShXLgu8XMqcrQBvJ0CL5pnTsfMB13oB8athpAq2XOQmcGmoACCLydx7nToa23ATaSIY2ichfOdPTGxlasXMLaL0MLZAOwAKIM+y8CmicobGdCcbbK9DzN+yYGVoNNI5iUKTMyYOjPse4A8SM1MmcXgU0toOq1yO/v8FOxlASyc7TgeYaAMBJHcY1CcCwGI/TK4AmDbDyKYBBtFUkRwto8gygiQEaByFgJ00BH2M8JWwQS1nafDXQCidWyOI8AcjDCSjCLk8ngObuAm3JAHAdubAmOaK06V8MNEsKPJOhobSprwQa6gD7DclRQdqcwL4zxqgBrQcabUiBLclRDKAlWp+etPkBaNMA0AKlrHwTdEByZAA4GM+SNluSY6wAzcMNewxmgig5Ks0nkrSpBvSaQHMdKTBAnLojOdYyGpQ254602ZILPdTD1hdlggdIm74jbTp8vDwF5ZYUeLWGJpWsh6XNyXgcYwVoJQTEhhTYkxzZjiU5npU2TaB979TQehlaAVq4kaGpiPwwwLkYUuBbQwocyQTv1tA0+1UFWoJF3iv1oq+qoSk8EQdJmwHkziIF7oOZk14EGitibAdjLYYK78H5vZOhtWpoI0ATGHs0Q8OMb4Ey+2bU2UYztCtA0wFAs7TplGLRVQCcqaFdGSPCeTI1QNIC52iWNzof6Uib7xjEp07mNNoUYmVosVItHrHzRlLgBn9LFyRHaQCtVUMbtTNhoXWiTOO9k/V8BdAc1Oq0ArSQs6/5SU0hckNy9NnXqQY0PGYo5dWJ7nINaN6o958FWin27aBaWRka1r5myvLOAm0j30eBJqCxHLReVclxhxOEN2JfDWjxBtAC7MIH1fVaGdoOp4qJYDgKtKPSFNID2gSnGldrCqkFZ+5UeQXQBIRrSwocbdZYQT/2LwRahBPBXoHrB8nxaGROST62DKUbQOMMzZIC9abkuELfQzQALWTnDNAm8KHWFOJgJ5+SHIvTPcmx1xQyZRhNL5Qci689aXMEaN/uNIWkEwDAvFpOZmgsBaaGnbs1NPa1Jm32gBZAIh1pCtG7TSH4aE0y1uVY4uqoFPisGlpP2rSA5qTecWn5agK6BzSpgAyD+wFaqhnYoSZ1Vwr8CmlTQbrcO3ZaX0NAEyMbYaAlyquFoLKK3SPby9CeVUPThrSJmkCAE0CrKUQadi4DrdSlWhmah0YL9z9vClH59YGbHx1J8VZTyAjQepJjmXwAKTDQI3omc3p1U4gDUf6RfcdYfrUp5ClAi2J3Ba6UOXGo+K+bQrjjssitG2SJzshaLwMtXgRagUNpYYoVkMSBLM+9GGiJZMvduG6DRZ4qc04DMPtQQxOjEtACmhO7K1AbNbQDEggZyJwscFpAGwENhoBeUwh3bWolhe8BTYVKxQEWrSUn/uhcM5KhvUu/+eQu0Lzhi+VrK0PrZZNDQKs9cpYUuFYgMVpD4/NxenJTiMCNqdUEUf1qZWjppLT5qSkkUZbCwkbZMSuVnu80hfSkzRbQeqCZSAh6huR4VtoM2gHAlLf72smuWgE+VV7XpE25Ab2WFDgyhnSuKbs4GuGzCjR+tIoUuMFg3kgcWKLTwRqanJQ2W00hAsenfaApRC42hbCvK1SlE0HtE9BGgneJO+ELamitD1YjjOYnNYVcraGhtKkW0EqVVeDx733I2NH581k1NNxNLG0i0IJ8/NjVaOZ0tYZ2Vtr0Xv7tPV3hkWp9EFkgS/J0vosngTaSoaG06WHi+xObQkaAdlbanP8B2+2l0f90LmUAAAAASUVORK5CYII=); }\n", ""]);

// exports


/***/ }),

/***/ "AP2z":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_getRawTag.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Symbol = __webpack_require__(/*! ./_Symbol */ "nmnc");

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var nativeObjectToString = objectProto.toString;

/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : 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;
}

module.exports = getRawTag;


/***/ }),

/***/ "APKd":
/*!***************************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils/lib/thememanager.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const coreutils_2 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const disposable_1 = __webpack_require__(/*! @phosphor/disposable */ "uNUc");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const dialog_1 = __webpack_require__(/*! ./dialog */ "DZkP");
/* tslint:disable */
/**
 * The theme manager token.
 */
exports.IThemeManager = new coreutils_2.Token('@jupyterlab/apputils:IThemeManager');
/**
 * The number of milliseconds between theme loading attempts.
 */
const REQUEST_INTERVAL = 75;
/**
 * The number of times to attempt to load a theme before giving up.
 */
const REQUEST_THRESHOLD = 20;
/**
 * A class that provides theme management.
 */
class ThemeManager {
    /**
     * Construct a new theme manager.
     */
    constructor(options) {
        this._current = null;
        this._links = [];
        this._outstanding = null;
        this._pending = 0;
        this._requests = {};
        this._themes = {};
        this._themeChanged = new signaling_1.Signal(this);
        const { host, key, splash, url } = options;
        const registry = options.settings;
        this._base = url;
        this._host = host;
        this._splash = splash;
        registry.load(key).then(settings => {
            this._settings = settings;
            this._settings.changed.connect(this._loadSettings, this);
            this._loadSettings();
        });
    }
    /**
     * Get the name of the current theme.
     */
    get theme() {
        return this._current;
    }
    /**
     * The names of the registered themes.
     */
    get themes() {
        return Object.keys(this._themes);
    }
    /**
     * A signal fired when the application theme changes.
     */
    get themeChanged() {
        return this._themeChanged;
    }
    /**
     * Load a theme CSS file by path.
     *
     * @param path - The path of the file to load.
     */
    loadCSS(path) {
        const base = this._base;
        const href = coreutils_1.URLExt.isLocal(path) ? coreutils_1.URLExt.join(base, path) : path;
        const links = this._links;
        return new Promise((resolve, reject) => {
            const link = document.createElement('link');
            link.setAttribute('rel', 'stylesheet');
            link.setAttribute('type', 'text/css');
            link.setAttribute('href', href);
            link.addEventListener('load', () => {
                resolve(undefined);
            });
            link.addEventListener('error', () => {
                reject(`Stylesheet failed to load: ${href}`);
            });
            document.body.appendChild(link);
            links.push(link);
        });
    }
    /**
     * Register a theme with the theme manager.
     *
     * @param theme - The theme to register.
     *
     * @returns A disposable that can be used to unregister the theme.
     */
    register(theme) {
        const { name } = theme;
        const themes = this._themes;
        if (themes[name]) {
            throw new Error(`Theme already registered for ${name}`);
        }
        themes[name] = theme;
        return new disposable_1.DisposableDelegate(() => {
            delete themes[name];
        });
    }
    /**
     * Set the current theme.
     */
    setTheme(name) {
        return this._settings.set('theme', name);
    }
    /**
     * Test whether a given theme is light.
     */
    isLight(name) {
        return this._themes[name].isLight;
    }
    /**
     * Handle the current settings.
     */
    _loadSettings() {
        const outstanding = this._outstanding;
        const pending = this._pending;
        const requests = this._requests;
        // If another request is pending, cancel it.
        if (pending) {
            window.clearTimeout(pending);
            this._pending = 0;
        }
        const settings = this._settings;
        const themes = this._themes;
        const theme = settings.composite['theme'];
        // If another promise is outstanding, wait until it finishes before
        // attempting to load the settings. Because outstanding promises cannot
        // be aborted, the order in which they occur must be enforced.
        if (outstanding) {
            outstanding
                .then(() => {
                this._loadSettings();
            })
                .catch(() => {
                this._loadSettings();
            });
            this._outstanding = null;
            return;
        }
        // Increment the request counter.
        requests[theme] = requests[theme] ? requests[theme] + 1 : 1;
        // If the theme exists, load it right away.
        if (themes[theme]) {
            this._outstanding = this._loadTheme(theme);
            delete requests[theme];
            return;
        }
        // If the request has taken too long, give up.
        if (requests[theme] > REQUEST_THRESHOLD) {
            const fallback = settings.default('theme');
            // Stop tracking the requests for this theme.
            delete requests[theme];
            if (!themes[fallback]) {
                this._onError(`Neither theme ${theme} nor default ${fallback} loaded.`);
                return;
            }
            console.warn(`Could not load theme ${theme}, using default ${fallback}.`);
            this._outstanding = this._loadTheme(fallback);
            return;
        }
        // If the theme does not yet exist, attempt to wait for it.
        this._pending = window.setTimeout(() => {
            this._loadSettings();
        }, REQUEST_INTERVAL);
    }
    /**
     * Load the theme.
     *
     * #### Notes
     * This method assumes that the `theme` exists.
     */
    _loadTheme(theme) {
        const current = this._current;
        const links = this._links;
        const themes = this._themes;
        const splash = this._splash.show(themes[theme].isLight);
        // Unload any CSS files that have been loaded.
        links.forEach(link => {
            if (link.parentElement) {
                link.parentElement.removeChild(link);
            }
        });
        links.length = 0;
        // Unload the previously loaded theme.
        const old = current ? themes[current].unload() : Promise.resolve();
        return Promise.all([old, themes[theme].load()])
            .then(() => {
            this._current = theme;
            Private.fitAll(this._host);
            splash.dispose();
            this._themeChanged.emit({
                name: 'theme',
                oldValue: current,
                newValue: theme
            });
        })
            .catch(reason => {
            this._onError(reason);
            splash.dispose();
        });
    }
    /**
     * Handle a theme error.
     */
    _onError(reason) {
        dialog_1.showDialog({
            title: 'Error Loading Theme',
            body: String(reason),
            buttons: [dialog_1.Dialog.okButton({ label: 'OK' })]
        });
    }
}
exports.ThemeManager = ThemeManager;
/**
 * A namespace for module private data.
 */
var Private;
(function (Private) {
    /**
     * Fit a widget and all of its children, recursively.
     */
    function fitAll(widget) {
        algorithm_1.each(widget.children(), fitAll);
        widget.fit();
    }
    Private.fitAll = fitAll;
})(Private || (Private = {}));


/***/ }),

/***/ "APWh":
/*!*******************************************!*\
  !*** ./node_modules/ajv/lib/dotjs/not.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_not(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  if (it.util.schemaHasRules($schema, it.RULES.all)) {
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    out += ' var ' + ($errs) + ' = errors;  ';
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    $it.createErrors = false;
    var $allErrorsOption;
    if ($it.opts.allErrors) {
      $allErrorsOption = $it.opts.allErrors;
      $it.opts.allErrors = false;
    }
    out += ' ' + (it.validate($it)) + ' ';
    $it.createErrors = true;
    if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption;
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += ' if (' + ($nextValid) + ') {   ';
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = ''; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should NOT be valid\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError([' + (__err) + ']); ';
      } else {
        out += ' validate.errors = [' + (__err) + ']; return false; ';
      }
    } else {
      out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    }
    out += ' } else {  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
    if (it.opts.allErrors) {
      out += ' } ';
    }
  } else {
    out += '  var err =   '; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should NOT be valid\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    if ($breakOnError) {
      out += ' if (false) { ';
    }
  }
  return out;
}


/***/ }),

/***/ "APuC":
/*!******************************************************!*\
  !*** ./node_modules/xterm/lib/handlers/Clipboard.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function prepareTextForTerminal(text) {
    return text.replace(/\r?\n/g, '\r');
}
exports.prepareTextForTerminal = prepareTextForTerminal;
function bracketTextForPaste(text, bracketedPasteMode) {
    if (bracketedPasteMode) {
        return '\x1b[200~' + text + '\x1b[201~';
    }
    return text;
}
exports.bracketTextForPaste = bracketTextForPaste;
function copyHandler(ev, term, selectionManager) {
    if (term.browser.isMSIE) {
        window.clipboardData.setData('Text', selectionManager.selectionText);
    }
    else {
        ev.clipboardData.setData('text/plain', selectionManager.selectionText);
    }
    ev.preventDefault();
}
exports.copyHandler = copyHandler;
function pasteHandler(ev, term) {
    ev.stopPropagation();
    var text;
    var dispatchPaste = function (text) {
        text = prepareTextForTerminal(text);
        text = bracketTextForPaste(text, term.bracketedPasteMode);
        term.handler(text);
        term.textarea.value = '';
        term.emit('paste', text);
        term.cancel(ev);
    };
    if (term.browser.isMSIE) {
        if (window.clipboardData) {
            text = window.clipboardData.getData('Text');
            dispatchPaste(text);
        }
    }
    else {
        if (ev.clipboardData) {
            text = ev.clipboardData.getData('text/plain');
            dispatchPaste(text);
        }
    }
}
exports.pasteHandler = pasteHandler;
function moveTextAreaUnderMouseCursor(ev, textarea) {
    textarea.style.position = 'fixed';
    textarea.style.width = '20px';
    textarea.style.height = '20px';
    textarea.style.left = (ev.clientX - 10) + 'px';
    textarea.style.top = (ev.clientY - 10) + 'px';
    textarea.style.zIndex = '1000';
    textarea.focus();
    setTimeout(function () {
        textarea.style.position = null;
        textarea.style.width = null;
        textarea.style.height = null;
        textarea.style.left = null;
        textarea.style.top = null;
        textarea.style.zIndex = null;
    }, 200);
}
exports.moveTextAreaUnderMouseCursor = moveTextAreaUnderMouseCursor;
function rightClickHandler(ev, textarea, selectionManager, shouldSelectWord) {
    moveTextAreaUnderMouseCursor(ev, textarea);
    if (shouldSelectWord && !selectionManager.isClickInSelection(ev)) {
        selectionManager.selectWordAtCursor(ev);
    }
    textarea.value = selectionManager.selectionText;
    textarea.select();
}
exports.rightClickHandler = rightClickHandler;

//# sourceMappingURL=Clipboard.js.map


/***/ }),

/***/ "AQ68":
/*!***********************************************!*\
  !*** ./node_modules/moment/locale/uz-latn.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var uzLatn = moment.defineLocale('uz-latn', {
    months : 'Yanvar_Fevral_Mart_Aprel_May_Iyun_Iyul_Avgust_Sentabr_Oktabr_Noyabr_Dekabr'.split('_'),
    monthsShort : 'Yan_Fev_Mar_Apr_May_Iyun_Iyul_Avg_Sen_Okt_Noy_Dek'.split('_'),
    weekdays : 'Yakshanba_Dushanba_Seshanba_Chorshanba_Payshanba_Juma_Shanba'.split('_'),
    weekdaysShort : 'Yak_Dush_Sesh_Chor_Pay_Jum_Shan'.split('_'),
    weekdaysMin : 'Ya_Du_Se_Cho_Pa_Ju_Sha'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'D MMMM YYYY, dddd HH:mm'
    },
    calendar : {
        sameDay : '[Bugun soat] LT [da]',
        nextDay : '[Ertaga] LT [da]',
        nextWeek : 'dddd [kuni soat] LT [da]',
        lastDay : '[Kecha soat] LT [da]',
        lastWeek : '[O\'tgan] dddd [kuni soat] LT [da]',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'Yaqin %s ichida',
        past : 'Bir necha %s oldin',
        s : 'soniya',
        ss : '%d soniya',
        m : 'bir daqiqa',
        mm : '%d daqiqa',
        h : 'bir soat',
        hh : '%d soat',
        d : 'bir kun',
        dd : '%d kun',
        M : 'bir oy',
        MM : '%d oy',
        y : 'bir yil',
        yy : '%d yil'
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return uzLatn;

})));


/***/ }),

/***/ "AQjG":
/*!********************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils/lib/index.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__webpack_require__(/*! ../style/index.css */ "mBDu");
__export(__webpack_require__(/*! ./clientsession */ "z/AG"));
__export(__webpack_require__(/*! ./clipboard */ "5cFW"));
__export(__webpack_require__(/*! ./commandlinker */ "8n7X"));
__export(__webpack_require__(/*! ./commandpalette */ "U2CZ"));
__export(__webpack_require__(/*! ./dialog */ "DZkP"));
__export(__webpack_require__(/*! ./domutils */ "4yqh"));
__export(__webpack_require__(/*! ./hoverbox */ "jjzf"));
__export(__webpack_require__(/*! ./iframe */ "8+Fv"));
__export(__webpack_require__(/*! ./instancetracker */ "/aXk"));
__export(__webpack_require__(/*! ./mainareawidget */ "AGAg"));
__export(__webpack_require__(/*! ./sanitizer */ "/w2Y"));
__export(__webpack_require__(/*! ./spinner */ "d2xu"));
__export(__webpack_require__(/*! ./splash */ "OUGg"));
__export(__webpack_require__(/*! ./styling */ "3g5F"));
__export(__webpack_require__(/*! ./thememanager */ "APKd"));
__export(__webpack_require__(/*! ./toolbar */ "yhkN"));
__export(__webpack_require__(/*! ./vdom */ "PbVF"));
__export(__webpack_require__(/*! ./windowresolver */ "AIml"));


/***/ }),

/***/ "AS1u":
/*!***********************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/cells/style/widget.css ***!
  \***********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n/*-----------------------------------------------------------------------------\n| Private CSS variables\n|----------------------------------------------------------------------------*/\n\n:root {\n  --jp-private-cell-scrolling-output-offset: 5px;\n}\n\n/*-----------------------------------------------------------------------------\n| Cell\n|----------------------------------------------------------------------------*/\n\n.jp-Cell {\n  padding: var(--jp-cell-padding);\n  margin: 0px;\n  border: none;\n  outline: none;\n  background: transparent;\n}\n\n/*-----------------------------------------------------------------------------\n| Common input/output\n|----------------------------------------------------------------------------*/\n\n.jp-Cell-inputWrapper,\n.jp-Cell-outputWrapper {\n  display: flex;\n  flex-direction: row;\n  padding: 0px;\n  margin: 0px;\n  /* Added to reveal the box-shadow on the input and output collapsers. */\n  overflow: visible;\n}\n\n/* Only input/output areas inside cells */\n.jp-Cell-inputArea,\n.jp-Cell-outputArea {\n  flex: 1 1 auto;\n}\n\n/*-----------------------------------------------------------------------------\n| Collapser\n|----------------------------------------------------------------------------*/\n\n/* Make the output collapser disappear when there is not output, but do so\n * in a manner that leaves it in the layout and preserves its width.\n */\n.jp-Cell.jp-mod-noOutputs .jp-Cell-outputCollapser {\n  border: none !important;\n  background: transparent !important;\n}\n\n.jp-Cell:not(.jp-mod-noOutputs) .jp-Cell-outputCollapser {\n  min-height: var(--jp-cell-collapser-min-height);\n}\n\n/*-----------------------------------------------------------------------------\n| Output\n|----------------------------------------------------------------------------*/\n\n/* Put a space between input and output when there IS output */\n.jp-Cell:not(.jp-mod-noOutputs) .jp-Cell-outputWrapper {\n  margin-top: 5px;\n}\n\n/* Text output with the Out[] prompt needs a top padding to match the\n * alignment of the Out[] prompt itself.\n */\n.jp-OutputArea-executeResult .jp-RenderedText.jp-OutputArea-output {\n  padding-top: var(--jp-code-padding);\n}\n\n.jp-CodeCell.jp-mod-outputsScrolled .jp-Cell-outputArea {\n  overflow-y: auto;\n  max-height: 200px;\n  box-shadow: inset 0 0 6px 2px rgba(0, 0, 0, 0.3);\n  margin-left: var(--jp-private-cell-scrolling-output-offset);\n}\n\n.jp-CodeCell.jp-mod-outputsScrolled .jp-OutputArea-prompt {\n  flex: 0 0\n    calc(\n      var(--jp-cell-prompt-width) -\n        var(--jp-private-cell-scrolling-output-offset)\n    );\n}\n\n/*-----------------------------------------------------------------------------\n| CodeCell\n|----------------------------------------------------------------------------*/\n\n/*-----------------------------------------------------------------------------\n| MarkdownCell\n|----------------------------------------------------------------------------*/\n\n.jp-MarkdownOutput {\n  flex: 1 1 auto;\n  margin-top: 0;\n  margin-bottom: 0;\n  padding-left: var(--jp-code-padding);\n}\n\n.jp-MarkdownOutput.jp-RenderedHTMLCommon {\n  overflow: visible;\n}\n", ""]);

// exports


/***/ }),

/***/ "AUX7":
/*!**************************************************!*\
  !*** ./node_modules/browserify-aes/modes/ecb.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

exports.encrypt = function (self, block) {
  return self._cipher.encryptBlock(block)
}

exports.decrypt = function (self, block) {
  return self._cipher.decryptBlock(block)
}


/***/ }),

/***/ "AUvm":
/*!************************************************************!*\
  !*** ./node_modules/core-js/library/modules/es6.symbol.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// ECMAScript 6 symbols shim
var global = __webpack_require__(/*! ./_global */ "5T2Y");
var has = __webpack_require__(/*! ./_has */ "B+OT");
var DESCRIPTORS = __webpack_require__(/*! ./_descriptors */ "jmDH");
var $export = __webpack_require__(/*! ./_export */ "Y7ZC");
var redefine = __webpack_require__(/*! ./_redefine */ "kTiW");
var META = __webpack_require__(/*! ./_meta */ "6/1s").KEY;
var $fails = __webpack_require__(/*! ./_fails */ "KUxP");
var shared = __webpack_require__(/*! ./_shared */ "29s/");
var setToStringTag = __webpack_require__(/*! ./_set-to-string-tag */ "RfKB");
var uid = __webpack_require__(/*! ./_uid */ "YqAc");
var wks = __webpack_require__(/*! ./_wks */ "UWiX");
var wksExt = __webpack_require__(/*! ./_wks-ext */ "zLkG");
var wksDefine = __webpack_require__(/*! ./_wks-define */ "Zxgi");
var enumKeys = __webpack_require__(/*! ./_enum-keys */ "R+7+");
var isArray = __webpack_require__(/*! ./_is-array */ "kAMH");
var anObject = __webpack_require__(/*! ./_an-object */ "5K7Z");
var isObject = __webpack_require__(/*! ./_is-object */ "93I4");
var toIObject = __webpack_require__(/*! ./_to-iobject */ "NsO/");
var toPrimitive = __webpack_require__(/*! ./_to-primitive */ "G8Mo");
var createDesc = __webpack_require__(/*! ./_property-desc */ "rr1i");
var _create = __webpack_require__(/*! ./_object-create */ "oVml");
var gOPNExt = __webpack_require__(/*! ./_object-gopn-ext */ "A5Xg");
var $GOPD = __webpack_require__(/*! ./_object-gopd */ "vwuL");
var $DP = __webpack_require__(/*! ./_object-dp */ "2faE");
var $keys = __webpack_require__(/*! ./_object-keys */ "w6GO");
var gOPD = $GOPD.f;
var dP = $DP.f;
var gOPN = gOPNExt.f;
var $Symbol = global.Symbol;
var $JSON = global.JSON;
var _stringify = $JSON && $JSON.stringify;
var PROTOTYPE = 'prototype';
var HIDDEN = wks('_hidden');
var TO_PRIMITIVE = wks('toPrimitive');
var isEnum = {}.propertyIsEnumerable;
var SymbolRegistry = shared('symbol-registry');
var AllSymbols = shared('symbols');
var OPSymbols = shared('op-symbols');
var ObjectProto = Object[PROTOTYPE];
var USE_NATIVE = typeof $Symbol == 'function';
var QObject = global.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;

// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function () {
  return _create(dP({}, 'a', {
    get: function () { return dP(this, 'a', { value: 7 }).a; }
  })).a != 7;
}) ? function (it, key, D) {
  var protoDesc = gOPD(ObjectProto, key);
  if (protoDesc) delete ObjectProto[key];
  dP(it, key, D);
  if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc);
} : dP;

var wrap = function (tag) {
  var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
  sym._k = tag;
  return sym;
};

var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) {
  return typeof it == 'symbol';
} : function (it) {
  return it instanceof $Symbol;
};

var $defineProperty = function defineProperty(it, key, D) {
  if (it === ObjectProto) $defineProperty(OPSymbols, key, D);
  anObject(it);
  key = toPrimitive(key, true);
  anObject(D);
  if (has(AllSymbols, key)) {
    if (!D.enumerable) {
      if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {}));
      it[HIDDEN][key] = true;
    } else {
      if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false;
      D = _create(D, { enumerable: createDesc(0, false) });
    } return setSymbolDesc(it, key, D);
  } return dP(it, key, D);
};
var $defineProperties = function defineProperties(it, P) {
  anObject(it);
  var keys = enumKeys(P = toIObject(P));
  var i = 0;
  var l = keys.length;
  var key;
  while (l > i) $defineProperty(it, key = keys[i++], P[key]);
  return it;
};
var $create = function create(it, P) {
  return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key) {
  var E = isEnum.call(this, key = toPrimitive(key, true));
  if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false;
  return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) {
  it = toIObject(it);
  key = toPrimitive(key, true);
  if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return;
  var D = gOPD(it, key);
  if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true;
  return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it) {
  var names = gOPN(toIObject(it));
  var result = [];
  var i = 0;
  var key;
  while (names.length > i) {
    if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key);
  } return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it) {
  var IS_OP = it === ObjectProto;
  var names = gOPN(IS_OP ? OPSymbols : toIObject(it));
  var result = [];
  var i = 0;
  var key;
  while (names.length > i) {
    if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]);
  } return result;
};

// 19.4.1.1 Symbol([description])
if (!USE_NATIVE) {
  $Symbol = function Symbol() {
    if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!');
    var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
    var $set = function (value) {
      if (this === ObjectProto) $set.call(OPSymbols, value);
      if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
      setSymbolDesc(this, tag, createDesc(1, value));
    };
    if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set });
    return wrap(tag);
  };
  redefine($Symbol[PROTOTYPE], 'toString', function toString() {
    return this._k;
  });

  $GOPD.f = $getOwnPropertyDescriptor;
  $DP.f = $defineProperty;
  __webpack_require__(/*! ./_object-gopn */ "ar/p").f = gOPNExt.f = $getOwnPropertyNames;
  __webpack_require__(/*! ./_object-pie */ "NV0k").f = $propertyIsEnumerable;
  __webpack_require__(/*! ./_object-gops */ "mqlF").f = $getOwnPropertySymbols;

  if (DESCRIPTORS && !__webpack_require__(/*! ./_library */ "uOPS")) {
    redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
  }

  wksExt.f = function (name) {
    return wrap(wks(name));
  };
}

$export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol });

for (var es6Symbols = (
  // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
  'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]);

for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]);

$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
  // 19.4.2.1 Symbol.for(key)
  'for': function (key) {
    return has(SymbolRegistry, key += '')
      ? SymbolRegistry[key]
      : SymbolRegistry[key] = $Symbol(key);
  },
  // 19.4.2.5 Symbol.keyFor(sym)
  keyFor: function keyFor(sym) {
    if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!');
    for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key;
  },
  useSetter: function () { setter = true; },
  useSimple: function () { setter = false; }
});

$export($export.S + $export.F * !USE_NATIVE, 'Object', {
  // 19.1.2.2 Object.create(O [, Properties])
  create: $create,
  // 19.1.2.4 Object.defineProperty(O, P, Attributes)
  defineProperty: $defineProperty,
  // 19.1.2.3 Object.defineProperties(O, Properties)
  defineProperties: $defineProperties,
  // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
  getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
  // 19.1.2.7 Object.getOwnPropertyNames(O)
  getOwnPropertyNames: $getOwnPropertyNames,
  // 19.1.2.8 Object.getOwnPropertySymbols(O)
  getOwnPropertySymbols: $getOwnPropertySymbols
});

// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () {
  var S = $Symbol();
  // MS Edge converts symbol values to JSON as {}
  // WebKit converts symbol values to JSON as null
  // V8 throws on boxed symbols
  return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
  stringify: function stringify(it) {
    var args = [it];
    var i = 1;
    var replacer, $replacer;
    while (arguments.length > i) args.push(arguments[i++]);
    $replacer = replacer = args[1];
    if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined
    if (!isArray(replacer)) replacer = function (key, value) {
      if (typeof $replacer == 'function') value = $replacer.call(this, key, value);
      if (!isSymbol(value)) return value;
    };
    args[1] = replacer;
    return _stringify.apply($JSON, args);
  }
});

// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(/*! ./_hide */ "NegM")($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);


/***/ }),

/***/ "AV7D":
/*!**********************************************************!*\
  !*** ./node_modules/react-day-picker/lib/src/Caption.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _LocaleUtils = __webpack_require__(/*! ./LocaleUtils */ "ze2x");

var _LocaleUtils2 = _interopRequireDefault(_LocaleUtils);

var _keys = __webpack_require__(/*! ./keys */ "VBVY");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Caption = function (_Component) {
  _inherits(Caption, _Component);

  function Caption(props) {
    _classCallCheck(this, Caption);

    var _this = _possibleConstructorReturn(this, (Caption.__proto__ || Object.getPrototypeOf(Caption)).call(this, props));

    _this.handleKeyUp = _this.handleKeyUp.bind(_this);
    return _this;
  }

  _createClass(Caption, [{
    key: 'shouldComponentUpdate',
    value: function shouldComponentUpdate(nextProps) {
      return nextProps.locale !== this.props.locale || nextProps.classNames !== this.props.classNames || nextProps.date.getMonth() !== this.props.date.getMonth() || nextProps.date.getFullYear() !== this.props.date.getFullYear();
    }
  }, {
    key: 'handleKeyUp',
    value: function handleKeyUp(e) {
      if (e.keyCode === _keys.ENTER) {
        this.props.onClick(e);
      }
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          classNames = _props.classNames,
          date = _props.date,
          months = _props.months,
          locale = _props.locale,
          localeUtils = _props.localeUtils,
          onClick = _props.onClick;

      return _react2.default.createElement(
        'div',
        { className: classNames.caption, role: 'heading' },
        _react2.default.createElement(
          'div',
          { onClick: onClick, onKeyUp: this.handleKeyUp },
          months ? months[date.getMonth()] + ' ' + date.getFullYear() : localeUtils.formatMonthTitle(date, locale)
        )
      );
    }
  }]);

  return Caption;
}(_react.Component);

Caption.defaultProps = {
  localeUtils: _LocaleUtils2.default
};
exports.default = Caption;
Caption.propTypes =  true ? {
  date: _propTypes2.default.instanceOf(Date),
  months: _propTypes2.default.arrayOf(_propTypes2.default.string),
  locale: _propTypes2.default.string,
  localeUtils: _propTypes2.default.object,
  onClick: _propTypes2.default.func,
  classNames: _propTypes2.default.shape({
    caption: _propTypes2.default.string.isRequired
  }).isRequired
} : undefined;
//# sourceMappingURL=Caption.js.map

/***/ }),

/***/ "AYSA":
/*!***********************************************!*\
  !*** ./node_modules/des.js/lib/des/cipher.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var assert = __webpack_require__(/*! minimalistic-assert */ "2j6C");

function Cipher(options) {
  this.options = options;

  this.type = this.options.type;
  this.blockSize = 8;
  this._init();

  this.buffer = new Array(this.blockSize);
  this.bufferOff = 0;
}
module.exports = Cipher;

Cipher.prototype._init = function _init() {
  // Might be overrided
};

Cipher.prototype.update = function update(data) {
  if (data.length === 0)
    return [];

  if (this.type === 'decrypt')
    return this._updateDecrypt(data);
  else
    return this._updateEncrypt(data);
};

Cipher.prototype._buffer = function _buffer(data, off) {
  // Append data to buffer
  var min = Math.min(this.buffer.length - this.bufferOff, data.length - off);
  for (var i = 0; i < min; i++)
    this.buffer[this.bufferOff + i] = data[off + i];
  this.bufferOff += min;

  // Shift next
  return min;
};

Cipher.prototype._flushBuffer = function _flushBuffer(out, off) {
  this._update(this.buffer, 0, out, off);
  this.bufferOff = 0;
  return this.blockSize;
};

Cipher.prototype._updateEncrypt = function _updateEncrypt(data) {
  var inputOff = 0;
  var outputOff = 0;

  var count = ((this.bufferOff + data.length) / this.blockSize) | 0;
  var out = new Array(count * this.blockSize);

  if (this.bufferOff !== 0) {
    inputOff += this._buffer(data, inputOff);

    if (this.bufferOff === this.buffer.length)
      outputOff += this._flushBuffer(out, outputOff);
  }

  // Write blocks
  var max = data.length - ((data.length - inputOff) % this.blockSize);
  for (; inputOff < max; inputOff += this.blockSize) {
    this._update(data, inputOff, out, outputOff);
    outputOff += this.blockSize;
  }

  // Queue rest
  for (; inputOff < data.length; inputOff++, this.bufferOff++)
    this.buffer[this.bufferOff] = data[inputOff];

  return out;
};

Cipher.prototype._updateDecrypt = function _updateDecrypt(data) {
  var inputOff = 0;
  var outputOff = 0;

  var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1;
  var out = new Array(count * this.blockSize);

  // TODO(indutny): optimize it, this is far from optimal
  for (; count > 0; count--) {
    inputOff += this._buffer(data, inputOff);
    outputOff += this._flushBuffer(out, outputOff);
  }

  // Buffer rest of the input
  inputOff += this._buffer(data, inputOff);

  return out;
};

Cipher.prototype.final = function final(buffer) {
  var first;
  if (buffer)
    first = this.update(buffer);

  var last;
  if (this.type === 'encrypt')
    last = this._finalEncrypt();
  else
    last = this._finalDecrypt();

  if (first)
    return first.concat(last);
  else
    return last;
};

Cipher.prototype._pad = function _pad(buffer, off) {
  if (off === 0)
    return false;

  while (off < buffer.length)
    buffer[off++] = 0;

  return true;
};

Cipher.prototype._finalEncrypt = function _finalEncrypt() {
  if (!this._pad(this.buffer, this.bufferOff))
    return [];

  var out = new Array(this.blockSize);
  this._update(this.buffer, 0, out, 0);
  return out;
};

Cipher.prototype._unpad = function _unpad(buffer) {
  return buffer;
};

Cipher.prototype._finalDecrypt = function _finalDecrypt() {
  assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt');
  var out = new Array(this.blockSize);
  this._flushBuffer(out, 0);

  return this._unpad(out);
};


/***/ }),

/***/ "AaHf":
/*!*********************************************!*\
  !*** ./node_modules/mdi-react/InboxIcon.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var InboxIcon = function InboxIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M19,15H15C15,16.66 13.66,18 12,18C10.34,18 9,16.66 9,15H5V5H19M19,3H5C3.89,3 3,3.9 3,5V19C3,20.1 3.9,21 5,21H19C20.1,21 21,20.1 21,19V5C21,3.9 20.1,3 19,3Z' })
  );
};

module.exports = InboxIcon;


/***/ }),

/***/ "AdCt":
/*!*********************************************!*\
  !*** ./node_modules/domhandler/lib/node.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

// This object will be used as the prototype for Nodes when creating a
// DOM-Level-1-compliant structure.
var NodePrototype = module.exports = {
	get firstChild() {
		var children = this.children;
		return children && children[0] || null;
	},
	get lastChild() {
		var children = this.children;
		return children && children[children.length - 1] || null;
	},
	get nodeType() {
		return nodeTypes[this.type] || nodeTypes.element;
	}
};

var domLvl1 = {
	tagName: "name",
	childNodes: "children",
	parentNode: "parent",
	previousSibling: "prev",
	nextSibling: "next",
	nodeValue: "data"
};

var nodeTypes = {
	element: 1,
	text: 3,
	cdata: 4,
	comment: 8
};

Object.keys(domLvl1).forEach(function(key) {
	var shorthand = domLvl1[key];
	Object.defineProperty(NodePrototype, key, {
		get: function() {
			return this[shorthand] || null;
		},
		set: function(val) {
			this[shorthand] = val;
			return val;
		}
	});
});


/***/ }),

/***/ "Ag8Z":
/*!***************************************!*\
  !*** ./node_modules/lodash/forOwn.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseForOwn = __webpack_require__(/*! ./_baseForOwn */ "JC6p"),
    castFunction = __webpack_require__(/*! ./_castFunction */ "EwQA");

/**
 * 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, castFunction(iteratee));
}

module.exports = forOwn;


/***/ }),

/***/ "AhHn":
/*!**********************************************************!*\
  !*** ./node_modules/asn1.js/lib/asn1/constants/index.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var constants = exports;

// Helper
constants._reverse = function reverse(map) {
  var res = {};

  Object.keys(map).forEach(function(key) {
    // Convert key to integer if it is stringified
    if ((key | 0) == key)
      key = key | 0;

    var value = map[key];
    res[value] = key;
  });

  return res;
};

constants.der = __webpack_require__(/*! ./der */ "i3FT");


/***/ }),

/***/ "AiYS":
/*!*********************************************!*\
  !*** ./node_modules/mdi-react/PhoneIcon.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var PhoneIcon = function PhoneIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M6.62,10.79C8.06,13.62 10.38,15.94 13.21,17.38L15.41,15.18C15.69,14.9 16.08,14.82 16.43,14.93C17.55,15.3 18.75,15.5 20,15.5C20.55,15.5 21,15.95 21,16.5V20C21,20.55 20.55,21 20,21C10.61,21 3,13.39 3,4C3,3.45 3.45,3 4,3H7.5C8.05,3 8.5,3.45 8.5,4C8.5,5.25 8.7,6.45 9.07,7.57C9.18,7.92 9.1,8.31 8.82,8.59L6.62,10.79Z' })
  );
};

module.exports = PhoneIcon;


/***/ }),

/***/ "AnK5":
/*!*************************************************************************!*\
  !*** ./node_modules/react-color/lib/components/common/EditableInput.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.EditableInput = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var EditableInput = exports.EditableInput = function (_ref) {
  _inherits(EditableInput, _ref);

  function EditableInput(props) {
    _classCallCheck(this, EditableInput);

    var _this = _possibleConstructorReturn(this, (EditableInput.__proto__ || Object.getPrototypeOf(EditableInput)).call(this));

    _this.handleBlur = function () {
      if (_this.state.blurValue) {
        _this.setState({ value: _this.state.blurValue, blurValue: null });
      }
    };

    _this.handleChange = function (e) {
      if (_this.props.label) {
        _this.props.onChange && _this.props.onChange(_defineProperty({}, _this.props.label, e.target.value), e);
      } else {
        _this.props.onChange && _this.props.onChange(e.target.value, e);
      }

      _this.setState({ value: e.target.value });
    };

    _this.handleKeyDown = function (e) {
      // In case `e.target.value` is a percentage remove the `%` character
      // and update accordingly with a percentage
      // https://github.com/casesandberg/react-color/issues/383
      var stringValue = String(e.target.value);
      var isPercentage = stringValue.indexOf('%') > -1;
      var number = Number(stringValue.replace(/%/g, ''));
      if (!isNaN(number)) {
        var amount = _this.props.arrowOffset || 1;

        // Up
        if (e.keyCode === 38) {
          if (_this.props.label !== null) {
            _this.props.onChange && _this.props.onChange(_defineProperty({}, _this.props.label, number + amount), e);
          } else {
            _this.props.onChange && _this.props.onChange(number + amount, e);
          }

          if (isPercentage) {
            _this.setState({ value: number + amount + '%' });
          } else {
            _this.setState({ value: number + amount });
          }
        }

        // Down
        if (e.keyCode === 40) {
          if (_this.props.label !== null) {
            _this.props.onChange && _this.props.onChange(_defineProperty({}, _this.props.label, number - amount), e);
          } else {
            _this.props.onChange && _this.props.onChange(number - amount, e);
          }

          if (isPercentage) {
            _this.setState({ value: number - amount + '%' });
          } else {
            _this.setState({ value: number - amount });
          }
        }
      }
    };

    _this.handleDrag = function (e) {
      if (_this.props.dragLabel) {
        var newValue = Math.round(_this.props.value + e.movementX);
        if (newValue >= 0 && newValue <= _this.props.dragMax) {
          _this.props.onChange && _this.props.onChange(_defineProperty({}, _this.props.label, newValue), e);
        }
      }
    };

    _this.handleMouseDown = function (e) {
      if (_this.props.dragLabel) {
        e.preventDefault();
        _this.handleDrag(e);
        window.addEventListener('mousemove', _this.handleDrag);
        window.addEventListener('mouseup', _this.handleMouseUp);
      }
    };

    _this.handleMouseUp = function () {
      _this.unbindEventListeners();
    };

    _this.unbindEventListeners = function () {
      window.removeEventListener('mousemove', _this.handleDrag);
      window.removeEventListener('mouseup', _this.handleMouseUp);
    };

    _this.state = {
      value: String(props.value).toUpperCase(),
      blurValue: String(props.value).toUpperCase()
    };
    return _this;
  }

  _createClass(EditableInput, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      var input = this.input;
      if (nextProps.value !== this.state.value) {
        if (input === document.activeElement) {
          this.setState({ blurValue: String(nextProps.value).toUpperCase() });
        } else {
          this.setState({ value: String(nextProps.value).toUpperCase(), blurValue: !this.state.blurValue && String(nextProps.value).toUpperCase() });
        }
      }
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      this.unbindEventListeners();
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var styles = (0, _reactcss2.default)({
        'default': {
          wrap: {
            position: 'relative'
          }
        },
        'user-override': {
          wrap: this.props.style && this.props.style.wrap ? this.props.style.wrap : {},
          input: this.props.style && this.props.style.input ? this.props.style.input : {},
          label: this.props.style && this.props.style.label ? this.props.style.label : {}
        },
        'dragLabel-true': {
          label: {
            cursor: 'ew-resize'
          }
        }
      }, {
        'user-override': true
      }, this.props);

      return _react2.default.createElement(
        'div',
        { style: styles.wrap },
        _react2.default.createElement('input', {
          style: styles.input,
          ref: function ref(input) {
            return _this2.input = input;
          },
          value: this.state.value,
          onKeyDown: this.handleKeyDown,
          onChange: this.handleChange,
          onBlur: this.handleBlur,
          placeholder: this.props.placeholder,
          spellCheck: 'false'
        }),
        this.props.label && !this.props.hideLabel ? _react2.default.createElement(
          'span',
          { style: styles.label, onMouseDown: this.handleMouseDown },
          this.props.label
        ) : null
      );
    }
  }]);

  return EditableInput;
}(_react.PureComponent || _react.Component);

exports.default = EditableInput;

/***/ }),

/***/ "AvDN":
/*!************************************************************!*\
  !*** ./node_modules/react-day-picker/lib/src/PropTypes.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ModifierPropType = undefined;

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PrimitiveTypes = {
  localeUtils: _propTypes2.default.shape({
    formatMonthTitle: _propTypes2.default.func,
    formatWeekdayShort: _propTypes2.default.func,
    formatWeekdayLong: _propTypes2.default.func,
    getFirstDayOfWeek: _propTypes2.default.func
  }),
  range: _propTypes2.default.shape({
    from: _propTypes2.default.instanceOf(Date),
    to: _propTypes2.default.instanceOf(Date)
  }),
  after: _propTypes2.default.shape({
    after: _propTypes2.default.instanceOf(Date)
  }),
  before: _propTypes2.default.shape({
    before: _propTypes2.default.instanceOf(Date)
  })
};

var ModifierPropType = exports.ModifierPropType = _propTypes2.default.oneOfType([PrimitiveTypes.after, PrimitiveTypes.before, PrimitiveTypes.range, _propTypes2.default.func, _propTypes2.default.array]);

exports.default = PrimitiveTypes;
//# sourceMappingURL=PropTypes.js.map

/***/ }),

/***/ "AvDn":
/*!*****************************************************!*\
  !*** ./node_modules/codemirror/mode/shell/shell.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"));
  else {}
})(function(CodeMirror) {
"use strict";

CodeMirror.defineMode('shell', function() {

  var words = {};
  function define(style, string) {
    var split = string.split(' ');
    for(var i = 0; i < split.length; i++) {
      words[split[i]] = style;
    }
  };

  // Atoms
  define('atom', 'true false');

  // Keywords
  define('keyword', 'if then do else elif while until for in esac fi fin ' +
    'fil done exit set unset export function');

  // Commands
  define('builtin', 'ab awk bash beep cat cc cd chown chmod chroot clear cp ' +
    'curl cut diff echo find gawk gcc get git grep hg kill killall ln ls make ' +
    'mkdir openssl mv nc node npm ping ps restart rm rmdir sed service sh ' +
    'shopt shred source sort sleep ssh start stop su sudo svn tee telnet top ' +
    'touch vi vim wall wc wget who write yes zsh');

  function tokenBase(stream, state) {
    if (stream.eatSpace()) return null;

    var sol = stream.sol();
    var ch = stream.next();

    if (ch === '\\') {
      stream.next();
      return null;
    }
    if (ch === '\'' || ch === '"' || ch === '`') {
      state.tokens.unshift(tokenString(ch, ch === "`" ? "quote" : "string"));
      return tokenize(stream, state);
    }
    if (ch === '#') {
      if (sol && stream.eat('!')) {
        stream.skipToEnd();
        return 'meta'; // 'comment'?
      }
      stream.skipToEnd();
      return 'comment';
    }
    if (ch === '$') {
      state.tokens.unshift(tokenDollar);
      return tokenize(stream, state);
    }
    if (ch === '+' || ch === '=') {
      return 'operator';
    }
    if (ch === '-') {
      stream.eat('-');
      stream.eatWhile(/\w/);
      return 'attribute';
    }
    if (/\d/.test(ch)) {
      stream.eatWhile(/\d/);
      if(stream.eol() || !/\w/.test(stream.peek())) {
        return 'number';
      }
    }
    stream.eatWhile(/[\w-]/);
    var cur = stream.current();
    if (stream.peek() === '=' && /\w+/.test(cur)) return 'def';
    return words.hasOwnProperty(cur) ? words[cur] : null;
  }

  function tokenString(quote, style) {
    var close = quote == "(" ? ")" : quote == "{" ? "}" : quote
    return function(stream, state) {
      var next, escaped = false;
      while ((next = stream.next()) != null) {
        if (next === close && !escaped) {
          state.tokens.shift();
          break;
        } else if (next === '$' && !escaped && quote !== "'" && stream.peek() != close) {
          escaped = true;
          stream.backUp(1);
          state.tokens.unshift(tokenDollar);
          break;
        } else if (!escaped && quote !== close && next === quote) {
          state.tokens.unshift(tokenString(quote, style))
          return tokenize(stream, state)
        } else if (!escaped && /['"]/.test(next) && !/['"]/.test(quote)) {
          state.tokens.unshift(tokenStringStart(next, "string"));
          stream.backUp(1);
          break;
        }
        escaped = !escaped && next === '\\';
      }
      return style;
    };
  };

  function tokenStringStart(quote, style) {
    return function(stream, state) {
      state.tokens[0] = tokenString(quote, style)
      stream.next()
      return tokenize(stream, state)
    }
  }

  var tokenDollar = function(stream, state) {
    if (state.tokens.length > 1) stream.eat('$');
    var ch = stream.next()
    if (/['"({]/.test(ch)) {
      state.tokens[0] = tokenString(ch, ch == "(" ? "quote" : ch == "{" ? "def" : "string");
      return tokenize(stream, state);
    }
    if (!/\d/.test(ch)) stream.eatWhile(/\w/);
    state.tokens.shift();
    return 'def';
  };

  function tokenize(stream, state) {
    return (state.tokens[0] || tokenBase) (stream, state);
  };

  return {
    startState: function() {return {tokens:[]};},
    token: function(stream, state) {
      return tokenize(stream, state);
    },
    closeBrackets: "()[]{}''\"\"``",
    lineComment: '#',
    fold: "brace"
  };
});

CodeMirror.defineMIME('text/x-sh', 'shell');
// Apache uses a slightly different Media Type for Shell scripts
// http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types
CodeMirror.defineMIME('application/x-sh', 'shell');

});


/***/ }),

/***/ "AvKE":
/*!***************************************************!*\
  !*** ./node_modules/lodash.escaperegexp/index.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global) {/**
 * lodash (Custom Build) <https://lodash.com/>
 * Build: `lodash modularize exports="npm" -o ./`
 * Copyright jQuery Foundation and other contributors <https://jquery.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
 */

/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;

/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';

/**
 * Used to match `RegExp`
 * [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns).
 */
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g,
    reHasRegExpChar = RegExp(reRegExpChar.source);

/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;

/** 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')();

/** Used for built-in method references. */
var objectProto = Object.prototype;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
 * of values.
 */
var objectToString = objectProto.toString;

/** Built-in value references. */
var Symbol = root.Symbol;

/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
    symbolToString = symbolProto ? symbolProto.toString : undefined;

/**
 * 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 (isSymbol(value)) {
    return symbolToString ? symbolToString.call(value) : '';
  }
  var result = (value + '');
  return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}

/**
 * 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 && typeof value == 'object';
}

/**
 * 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) && objectToString.call(value) == symbolTag);
}

/**
 * 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 process.
 * @returns {string} Returns the string.
 * @example
 *
 * _.toString(null);
 * // => ''
 *
 * _.toString(-0);
 * // => '-0'
 *
 * _.toString([1, 2, 3]);
 * // => '1,2,3'
 */
function toString(value) {
  return value == null ? '' : baseToString(value);
}

/**
 * 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;
}

module.exports = escapeRegExp;

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "AvvY":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/ml.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var ml = moment.defineLocale('ml', {
    months : 'ജനുവരി_ഫെബ്രുവരി_മാർച്ച്_ഏപ്രിൽ_മേയ്_ജൂൺ_ജൂലൈ_ഓഗസ്റ്റ്_സെപ്റ്റംബർ_ഒക്ടോബർ_നവംബർ_ഡിസംബർ'.split('_'),
    monthsShort : 'ജനു._ഫെബ്രു._മാർ._ഏപ്രി._മേയ്_ജൂൺ_ജൂലൈ._ഓഗ._സെപ്റ്റ._ഒക്ടോ._നവം._ഡിസം.'.split('_'),
    monthsParseExact : true,
    weekdays : 'ഞായറാഴ്ച_തിങ്കളാഴ്ച_ചൊവ്വാഴ്ച_ബുധനാഴ്ച_വ്യാഴാഴ്ച_വെള്ളിയാഴ്ച_ശനിയാഴ്ച'.split('_'),
    weekdaysShort : 'ഞായർ_തിങ്കൾ_ചൊവ്വ_ബുധൻ_വ്യാഴം_വെള്ളി_ശനി'.split('_'),
    weekdaysMin : 'ഞാ_തി_ചൊ_ബു_വ്യാ_വെ_ശ'.split('_'),
    longDateFormat : {
        LT : 'A h:mm -നു',
        LTS : 'A h:mm:ss -നു',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY, A h:mm -നു',
        LLLL : 'dddd, D MMMM YYYY, A h:mm -നു'
    },
    calendar : {
        sameDay : '[ഇന്ന്] LT',
        nextDay : '[നാളെ] LT',
        nextWeek : 'dddd, LT',
        lastDay : '[ഇന്നലെ] LT',
        lastWeek : '[കഴിഞ്ഞ] dddd, LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : '%s കഴിഞ്ഞ്',
        past : '%s മുൻപ്',
        s : 'അൽപ നിമിഷങ്ങൾ',
        ss : '%d സെക്കൻഡ്',
        m : 'ഒരു മിനിറ്റ്',
        mm : '%d മിനിറ്റ്',
        h : 'ഒരു മണിക്കൂർ',
        hh : '%d മണിക്കൂർ',
        d : 'ഒരു ദിവസം',
        dd : '%d ദിവസം',
        M : 'ഒരു മാസം',
        MM : '%d മാസം',
        y : 'ഒരു വർഷം',
        yy : '%d വർഷം'
    },
    meridiemParse: /രാത്രി|രാവിലെ|ഉച്ച കഴിഞ്ഞ്|വൈകുന്നേരം|രാത്രി/i,
    meridiemHour : function (hour, meridiem) {
        if (hour === 12) {
            hour = 0;
        }
        if ((meridiem === 'രാത്രി' && hour >= 4) ||
                meridiem === 'ഉച്ച കഴിഞ്ഞ്' ||
                meridiem === 'വൈകുന്നേരം') {
            return hour + 12;
        } else {
            return hour;
        }
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 4) {
            return 'രാത്രി';
        } else if (hour < 12) {
            return 'രാവിലെ';
        } else if (hour < 17) {
            return 'ഉച്ച കഴിഞ്ഞ്';
        } else if (hour < 20) {
            return 'വൈകുന്നേരം';
        } else {
            return 'രാത്രി';
        }
    }
});

return ml;

})));


/***/ }),

/***/ "AwJw":
/*!*********************************************!*\
  !*** ./node_modules/ajv/lib/dotjs/const.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_const(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  if (!$isData) {
    out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';';
  }
  out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') {   ';
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should be equal to constant\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += ' }';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}


/***/ }),

/***/ "AyB5":
/*!***********************************************************!*\
  !*** ./node_modules/draft-js/lib/getDefaultKeyBinding.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule getDefaultKeyBinding
 * @format
 * 
 */



var KeyBindingUtil = __webpack_require__(/*! ./KeyBindingUtil */ "s8ra");
var Keys = __webpack_require__(/*! fbjs/lib/Keys */ "7wDu");
var UserAgent = __webpack_require__(/*! fbjs/lib/UserAgent */ "CYTE");

var isOSX = UserAgent.isPlatform('Mac OS X');
var isWindows = UserAgent.isPlatform('Windows');

// Firefox on OSX had a bug resulting in navigation instead of cursor movement.
// This bug was fixed in Firefox 29. Feature detection is virtually impossible
// so we just check the version number. See #342765.
var shouldFixFirefoxMovement = isOSX && UserAgent.isBrowser('Firefox < 29');

var hasCommandModifier = KeyBindingUtil.hasCommandModifier,
    isCtrlKeyCommand = KeyBindingUtil.isCtrlKeyCommand;


function shouldRemoveWord(e) {
  return isOSX && e.altKey || isCtrlKeyCommand(e);
}

/**
 * Get the appropriate undo/redo command for a Z key command.
 */
function getZCommand(e) {
  if (!hasCommandModifier(e)) {
    return null;
  }
  return e.shiftKey ? 'redo' : 'undo';
}

function getDeleteCommand(e) {
  // Allow default "cut" behavior for Windows on Shift + Delete.
  if (isWindows && e.shiftKey) {
    return null;
  }
  return shouldRemoveWord(e) ? 'delete-word' : 'delete';
}

function getBackspaceCommand(e) {
  if (hasCommandModifier(e) && isOSX) {
    return 'backspace-to-start-of-line';
  }
  return shouldRemoveWord(e) ? 'backspace-word' : 'backspace';
}

/**
 * Retrieve a bound key command for the given event.
 */
function getDefaultKeyBinding(e) {
  switch (e.keyCode) {
    case 66:
      // B
      return hasCommandModifier(e) ? 'bold' : null;
    case 68:
      // D
      return isCtrlKeyCommand(e) ? 'delete' : null;
    case 72:
      // H
      return isCtrlKeyCommand(e) ? 'backspace' : null;
    case 73:
      // I
      return hasCommandModifier(e) ? 'italic' : null;
    case 74:
      // J
      return hasCommandModifier(e) ? 'code' : null;
    case 75:
      // K
      return !isWindows && isCtrlKeyCommand(e) ? 'secondary-cut' : null;
    case 77:
      // M
      return isCtrlKeyCommand(e) ? 'split-block' : null;
    case 79:
      // O
      return isCtrlKeyCommand(e) ? 'split-block' : null;
    case 84:
      // T
      return isOSX && isCtrlKeyCommand(e) ? 'transpose-characters' : null;
    case 85:
      // U
      return hasCommandModifier(e) ? 'underline' : null;
    case 87:
      // W
      return isOSX && isCtrlKeyCommand(e) ? 'backspace-word' : null;
    case 89:
      // Y
      if (isCtrlKeyCommand(e)) {
        return isWindows ? 'redo' : 'secondary-paste';
      }
      return null;
    case 90:
      // Z
      return getZCommand(e) || null;
    case Keys.RETURN:
      return 'split-block';
    case Keys.DELETE:
      return getDeleteCommand(e);
    case Keys.BACKSPACE:
      return getBackspaceCommand(e);
    // LEFT/RIGHT handlers serve as a workaround for a Firefox bug.
    case Keys.LEFT:
      return shouldFixFirefoxMovement && hasCommandModifier(e) ? 'move-selection-to-start-of-block' : null;
    case Keys.RIGHT:
      return shouldFixFirefoxMovement && hasCommandModifier(e) ? 'move-selection-to-end-of-block' : null;
    default:
      return null;
  }
}

module.exports = getDefaultKeyBinding;

/***/ }),

/***/ "AyUB":
/*!*************************************************************!*\
  !*** ./node_modules/babel-runtime/core-js/object/create.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = { "default": __webpack_require__(/*! core-js/library/fn/object/create */ "3GJH"), __esModule: true };

/***/ }),

/***/ "B+OT":
/*!******************************************************!*\
  !*** ./node_modules/core-js/library/modules/_has.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

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


/***/ }),

/***/ "B+Rx":
/*!*****************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/loggers.js ***!
  \*****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



/* eslint-disable no-console */

var dfltConfig = __webpack_require__(/*! ../plot_api/plot_config */ "2va9").dfltConfig;

var loggers = module.exports = {};

/**
 * ------------------------------------------
 * debugging tools
 * ------------------------------------------
 */

loggers.log = function() {
    if(dfltConfig.logging > 1) {
        var messages = ['LOG:'];

        for(var i = 0; i < arguments.length; i++) {
            messages.push(arguments[i]);
        }

        apply(console.trace || console.log, messages);
    }
};

loggers.warn = function() {
    if(dfltConfig.logging > 0) {
        var messages = ['WARN:'];

        for(var i = 0; i < arguments.length; i++) {
            messages.push(arguments[i]);
        }

        apply(console.trace || console.log, messages);
    }
};

loggers.error = function() {
    if(dfltConfig.logging > 0) {
        var messages = ['ERROR:'];

        for(var i = 0; i < arguments.length; i++) {
            messages.push(arguments[i]);
        }

        apply(console.error, messages);
    }
};

/*
 * Robust apply, for IE9 where console.log doesn't support
 * apply like other functions do
 */
function apply(f, args) {
    if(f && f.apply) {
        try {
            // `this` should always be console, since here we're always
            // applying a method of the console object.
            f.apply(console, args);
            return;
        }
        catch(e) { /* in case apply failed, fall back on the code below */ }
    }

    // no apply - just try calling the function on each arg independently
    for(var i = 0; i < args.length; i++) {
        try {
            f(args[i]);
        }
        catch(e) {
            // still fails - last resort simple console.log
            console.log(args[i]);
        }
    }
}


/***/ }),

/***/ "B/J0":
/*!**************************************************!*\
  !*** ./node_modules/hash.js/lib/hash/sha/224.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var utils = __webpack_require__(/*! ../utils */ "w8CP");
var SHA256 = __webpack_require__(/*! ./256 */ "bu2F");

function SHA224() {
  if (!(this instanceof SHA224))
    return new SHA224();

  SHA256.call(this);
  this.h = [
    0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
    0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
}
utils.inherits(SHA224, SHA256);
module.exports = SHA224;

SHA224.blockSize = 512;
SHA224.outSize = 224;
SHA224.hmacStrength = 192;
SHA224.padLength = 64;

SHA224.prototype._digest = function digest(enc) {
  // Just truncate output
  if (enc === 'hex')
    return utils.toHex32(this.h.slice(0, 7), 'big');
  else
    return utils.split32(this.h.slice(0, 7), 'big');
};



/***/ }),

/***/ "B0ab":
/*!***************************************************************!*\
  !*** ./node_modules/draft-js/lib/splitBlockInContentState.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule splitBlockInContentState
 * @format
 * 
 */



var ContentBlockNode = __webpack_require__(/*! ./ContentBlockNode */ "JL7T");
var Immutable = __webpack_require__(/*! immutable */ "JPcv");

var generateRandomKey = __webpack_require__(/*! ./generateRandomKey */ "rJY1");
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");

var List = Immutable.List,
    Map = Immutable.Map;


var transformBlock = function transformBlock(key, blockMap, func) {
  if (!key) {
    return;
  }

  var block = blockMap.get(key);

  if (!block) {
    return;
  }

  blockMap.set(key, func(block));
};

var updateBlockMapLinks = function updateBlockMapLinks(blockMap, originalBlock, belowBlock) {
  return blockMap.withMutations(function (blocks) {
    var originalBlockKey = originalBlock.getKey();
    var belowBlockKey = belowBlock.getKey();

    // update block parent
    transformBlock(originalBlock.getParentKey(), blocks, function (block) {
      var parentChildrenList = block.getChildKeys();
      var insertionIndex = parentChildrenList.indexOf(originalBlockKey) + 1;
      var newChildrenArray = parentChildrenList.toArray();

      newChildrenArray.splice(insertionIndex, 0, belowBlockKey);

      return block.merge({
        children: List(newChildrenArray)
      });
    });

    // update original next block
    transformBlock(originalBlock.getNextSiblingKey(), blocks, function (block) {
      return block.merge({
        prevSibling: belowBlockKey
      });
    });

    // update original block
    transformBlock(originalBlockKey, blocks, function (block) {
      return block.merge({
        nextSibling: belowBlockKey
      });
    });

    // update below block
    transformBlock(belowBlockKey, blocks, function (block) {
      return block.merge({
        prevSibling: originalBlockKey
      });
    });
  });
};

var splitBlockInContentState = function splitBlockInContentState(contentState, selectionState) {
  !selectionState.isCollapsed() ?  true ? invariant(false, 'Selection range must be collapsed.') : undefined : void 0;

  var key = selectionState.getAnchorKey();
  var offset = selectionState.getAnchorOffset();
  var blockMap = contentState.getBlockMap();
  var blockToSplit = blockMap.get(key);
  var text = blockToSplit.getText();
  var chars = blockToSplit.getCharacterList();
  var keyBelow = generateRandomKey();
  var isExperimentalTreeBlock = blockToSplit instanceof ContentBlockNode;

  var blockAbove = blockToSplit.merge({
    text: text.slice(0, offset),
    characterList: chars.slice(0, offset)
  });
  var blockBelow = blockAbove.merge({
    key: keyBelow,
    text: text.slice(offset),
    characterList: chars.slice(offset),
    data: Map()
  });

  var blocksBefore = blockMap.toSeq().takeUntil(function (v) {
    return v === blockToSplit;
  });
  var blocksAfter = blockMap.toSeq().skipUntil(function (v) {
    return v === blockToSplit;
  }).rest();
  var newBlocks = blocksBefore.concat([[key, blockAbove], [keyBelow, blockBelow]], blocksAfter).toOrderedMap();

  if (isExperimentalTreeBlock) {
    !blockToSplit.getChildKeys().isEmpty() ?  true ? invariant(false, 'ContentBlockNode must not have children') : undefined : void 0;

    newBlocks = updateBlockMapLinks(newBlocks, blockAbove, blockBelow);
  }

  return contentState.merge({
    blockMap: newBlocks,
    selectionBefore: selectionState,
    selectionAfter: selectionState.merge({
      anchorKey: keyBelow,
      anchorOffset: 0,
      focusKey: keyBelow,
      focusOffset: 0,
      isBackward: false
    })
  });
};

module.exports = splitBlockInContentState;

/***/ }),

/***/ "B4uZ":
/*!********************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/xterm/src/xterm.css ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/**\n * Copyright (c) 2014 The xterm.js authors. All rights reserved.\n * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)\n * https://github.com/chjj/term.js\n * @license MIT\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * Originally forked from (with the author's permission):\n *   Fabrice Bellard's javascript vt100 for jslinux:\n *   http://bellard.org/jslinux/\n *   Copyright (c) 2011 Fabrice Bellard\n *   The original design remains. The terminal itself\n *   has been extended to include xterm CSI codes, among\n *   other features.\n */\n\n/**\n *  Default styles for xterm.js\n */\n\n.xterm {\n    font-family: courier-new, courier, monospace;\n    font-feature-settings: \"liga\" 0;\n    position: relative;\n    user-select: none;\n    -ms-user-select: none;\n    -webkit-user-select: none;\n}\n\n.xterm.focus,\n.xterm:focus {\n    outline: none;\n}\n\n.xterm .xterm-helpers {\n    position: absolute;\n    top: 0;\n    /**\n     * The z-index of the helpers must be higher than the canvases in order for\n     * IMEs to appear on top.\n     */\n    z-index: 10;\n}\n\n.xterm .xterm-helper-textarea {\n    /*\n     * HACK: to fix IE's blinking cursor\n     * Move textarea out of the screen to the far left, so that the cursor is not visible.\n     */\n    position: absolute;\n    opacity: 0;\n    left: -9999em;\n    top: 0;\n    width: 0;\n    height: 0;\n    z-index: -10;\n    /** Prevent wrapping so the IME appears against the textarea at the correct position */\n    white-space: nowrap;\n    overflow: hidden;\n    resize: none;\n}\n\n.xterm .composition-view {\n    /* TODO: Composition position got messed up somewhere */\n    background: #000;\n    color: #FFF;\n    display: none;\n    position: absolute;\n    white-space: nowrap;\n    z-index: 1;\n}\n\n.xterm .composition-view.active {\n    display: block;\n}\n\n.xterm .xterm-viewport {\n    /* On OS X this is required in order for the scroll bar to appear fully opaque */\n    background-color: #000;\n    overflow-y: scroll;\n    cursor: default;\n    position: absolute;\n    right: 0;\n    left: 0;\n    top: 0;\n    bottom: 0;\n}\n\n.xterm .xterm-screen {\n    position: relative;\n}\n\n.xterm .xterm-screen canvas {\n    position: absolute;\n    left: 0;\n    top: 0;\n}\n\n.xterm .xterm-scroll-area {\n    visibility: hidden;\n}\n\n.xterm-char-measure-element {\n    display: inline-block;\n    visibility: hidden;\n    position: absolute;\n    top: 0;\n    left: -9999em;\n    line-height: normal;\n}\n\n.xterm.enable-mouse-events {\n    /* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */\n    cursor: default;\n}\n\n.xterm:not(.enable-mouse-events) {\n    cursor: text;\n}\n\n.xterm .xterm-accessibility,\n.xterm .xterm-message {\n    position: absolute;\n    left: 0;\n    top: 0;\n    bottom: 0;\n    right: 0;\n    z-index: 100;\n    color: transparent;\n}\n\n.xterm .live-region {\n    position: absolute;\n    left: -9999px;\n    width: 1px;\n    height: 1px;\n    overflow: hidden;\n}\n\n.xterm-cursor-pointer {\n    cursor: pointer;\n}\n", ""]);

// exports


/***/ }),

/***/ "B55N":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/ja.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var ja = moment.defineLocale('ja', {
    months : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
    monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
    weekdays : '日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日'.split('_'),
    weekdaysShort : '日_月_火_水_木_金_土'.split('_'),
    weekdaysMin : '日_月_火_水_木_金_土'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'YYYY/MM/DD',
        LL : 'YYYY年M月D日',
        LLL : 'YYYY年M月D日 HH:mm',
        LLLL : 'YYYY年M月D日 HH:mm dddd',
        l : 'YYYY/MM/DD',
        ll : 'YYYY年M月D日',
        lll : 'YYYY年M月D日 HH:mm',
        llll : 'YYYY年M月D日 HH:mm dddd'
    },
    meridiemParse: /午前|午後/i,
    isPM : function (input) {
        return input === '午後';
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 12) {
            return '午前';
        } else {
            return '午後';
        }
    },
    calendar : {
        sameDay : '[今日] LT',
        nextDay : '[明日] LT',
        nextWeek : '[来週]dddd LT',
        lastDay : '[昨日] LT',
        lastWeek : '[前週]dddd LT',
        sameElse : 'L'
    },
    dayOfMonthOrdinalParse : /\d{1,2}日/,
    ordinal : function (number, period) {
        switch (period) {
            case 'd':
            case 'D':
            case 'DDD':
                return number + '日';
            default:
                return number;
        }
    },
    relativeTime : {
        future : '%s後',
        past : '%s前',
        s : '数秒',
        ss : '%d秒',
        m : '1分',
        mm : '%d分',
        h : '1時間',
        hh : '%d時間',
        d : '1日',
        dd : '%d日',
        M : '1ヶ月',
        MM : '%dヶ月',
        y : '1年',
        yy : '%d年'
    }
});

return ja;

})));


/***/ }),

/***/ "B5Mt":
/*!*******************************************!*\
  !*** ./node_modules/reactcss/lib/loop.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var loopable = function loopable(i, length) {
  var props = {};
  var setProp = function setProp(name) {
    var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;

    props[name] = value;
  };

  i === 0 && setProp('first-child');
  i === length - 1 && setProp('last-child');
  (i === 0 || i % 2 === 0) && setProp('even');
  Math.abs(i % 2) === 1 && setProp('odd');
  setProp('nth-child', i);

  return props;
};

exports.default = loopable;

/***/ }),

/***/ "B8du":
/*!******************************************!*\
  !*** ./node_modules/lodash/stubFalse.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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;
}

module.exports = stubFalse;


/***/ }),

/***/ "BFJn":
/*!***********************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/text_editors/RichText/index.js ***!
  \***********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _draftJs = __webpack_require__(/*! draft-js */ "v83y");

var _draftJsExportHtml = __webpack_require__(/*! @plotly/draft-js-export-html */ "1YrB");

var _draftJsImportHtml = __webpack_require__(/*! draft-js-import-html */ "wTZr");

var _configuration = __webpack_require__(/*! ./configuration */ "3Mxs");

var _LinkDecorator = __webpack_require__(/*! ./LinkDecorator */ "a3Vw");

var _LinkDecorator2 = _interopRequireDefault(_LinkDecorator);

var _LinkEditor = __webpack_require__(/*! ./LinkEditor */ "fegh");

var _LinkEditor2 = _interopRequireDefault(_LinkEditor);

var _StyleButtonGroup = __webpack_require__(/*! ./StyleButtonGroup */ "s/Uv");

var _StyleButtonGroup2 = _interopRequireDefault(_StyleButtonGroup);

var _debounce = __webpack_require__(/*! ./debounce */ "Z7lC");

var _debounce2 = _interopRequireDefault(_debounce);

var _DraftCommands = __webpack_require__(/*! ./DraftCommands */ "tP0r");

var _decoratorStrategies = __webpack_require__(/*! ./decoratorStrategies */ "F43Q");

var _getSelectionCoordinates = __webpack_require__(/*! ./getSelectionCoordinates */ "sBIJ");

var _getSelectionCoordinates2 = _interopRequireDefault(_getSelectionCoordinates);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

// Constants


// Components


// Libraries


var RichText = function (_Component) {
  _inherits(RichText, _Component);

  function RichText(props, context) {
    _classCallCheck(this, RichText);

    /*
         * Initially set state based on the plotly.js annotation content.
         * After this, as long as this component is mounted, it owns the source
         * of truth for the annotation value via `this.state.editorState`.
         * This state may be updated externally via a prop update.
         * See `componentWillReceiveProps`.
         */
    var _this = _possibleConstructorReturn(this, (RichText.__proto__ || Object.getPrototypeOf(RichText)).call(this, props, context));

    _this.state = {
      editorState: props.value.toString().trim().length ? _this.createEditorStateFromHTML(props.value) : _draftJs.EditorState.createEmpty(_this.getDecorator())
    };

    _this.getDecorator = _this.getDecorator.bind(_this);
    _this.createEditorStateFromHTML = _this.createEditorStateFromHTML.bind(_this);
    _this.getEditorStateAsHTML = _this.getEditorStateAsHTML.bind(_this);
    _this.focus = _this.focus.bind(_this);
    _this.getParentContainerVerticalOffset = _this.getParentContainerVerticalOffset.bind(_this);
    _this.onChange = _this.onChange.bind(_this);
    _this.onBlur = _this.onBlur.bind(_this);
    _this.onFocus = _this.onFocus.bind(_this);
    _this.onLinkEditorBlur = _this.onLinkEditorBlur.bind(_this);
    _this.onLinkEditorFocus = _this.onLinkEditorFocus.bind(_this);
    _this.onLinkEditorChange = _this.onLinkEditorChange.bind(_this);
    _this.onLinkEditorClose = _this.onLinkEditorClose.bind(_this);
    _this.onKeyCommand = _this.onKeyCommand.bind(_this);
    _this.onReturnPressed = _this.onReturnPressed.bind(_this);
    _this.onStyleButtonToggle = _this.onStyleButtonToggle.bind(_this);
    _this.renderLinkEditor = _this.renderLinkEditor.bind(_this);
    return _this;
  }

  _createClass(RichText, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      var _state = this.state,
          linkEditorFocus = _state.linkEditorFocus,
          editorFocus = _state.editorFocus;

      /*
           * Don't worry about what plotly.js thinks the annotation value
           * should be while we're using our editor, for these reasons:
           *
           * 1. The editor should be considered the source of truth, unless the
           *    user is actually editing the annotation inline, in the chart.
           * 2. Sometimes we get updates with stale values.
           */

      if (linkEditorFocus || editorFocus) {
        return;
      }

      // Sync editor state with plotly annotation value.
      var editorState = this.createEditorStateFromHTML(nextProps.value);

      this.setState({ editorState: editorState });
    }
  }, {
    key: 'shouldComponentUpdate',
    value: function shouldComponentUpdate(nextProps, nextState) {
      var _props = this.props,
          placeholder = _props.placeholder,
          value = _props.value;
      var _state2 = this.state,
          editorState = _state2.editorState,
          linkEditorFocus = _state2.linkEditorFocus;

      // If relevant props or state changed, return true.

      if (
      // Always update when user is editing link
      linkEditorFocus || placeholder !== nextProps.placeholder || value !== nextProps.value || editorState !== nextState.editorState) {
        return true;
      }

      // Compare incoming value with HTML representation of state.
      return nextProps.value !== this.getEditorStateAsHTML(editorState);
    }
  }, {
    key: 'getDecorator',
    value: function getDecorator() {
      return new _draftJs.CompositeDecorator([{
        strategy: _decoratorStrategies.findLinkEntities,
        component: _LinkDecorator2.default,

        // Props for the LinkDecorator component
        props: {
          style: _configuration.STYLE_MAP[_configuration.LINK]
        }
      }]);
    }
  }, {
    key: 'createEditorStateFromHTML',
    value: function createEditorStateFromHTML(html) {
      var _inlineStyles;

      var contentState = (0, _draftJsImportHtml.stateFromHTML)(html, {
        inlineStyles: (_inlineStyles = {}, _defineProperty(_inlineStyles, _configuration.SUPERSCRIPT, { element: 'sup' }), _defineProperty(_inlineStyles, _configuration.SUBSCRIPT, { element: 'sub' }), _inlineStyles),
        defaultBlockTag: null
      });

      var decorator = this.getDecorator();

      /*
       * Work around issue described here:
       * https://github.com/facebook/draft-js/issues/185
       * #issuecomment-217207612
       */

      // Parse once to generate entity instances
      _draftJs.EditorState.createWithContent(contentState);

      // Now we can add our decorator
      return _draftJs.EditorState.createWithContent(contentState, decorator);
    }
  }, {
    key: 'getEditorStateAsHTML',
    value: function getEditorStateAsHTML(editorState) {
      var contentState = editorState.getCurrentContent();

      return (0, _draftJsExportHtml.stateToHTML)(contentState, {
        defaultBlockTag: null,
        inlineStyles: _configuration.STYLES_TO_HTML_TAGS
      });
    }
  }, {
    key: 'focus',
    value: function focus() {
      this.editorInput.focus();
    }

    // Used to properly calculate user selection coordinates.

  }, {
    key: 'getParentContainerVerticalOffset',
    value: function getParentContainerVerticalOffset() {
      return document.querySelector('.panel').scrollTop;
    }
  }, {
    key: 'onChange',
    value: function onChange(editorState) {
      var selectedLinkID = this.state.selectedLinkID;

      var selection = editorState.getSelection();
      var entityKey = (0, _DraftCommands.getEntityKeyAt)(editorState, selection);

      var newState = { editorState: editorState };

      // Update selected link ID
      if (!(0, _DraftCommands.cursorHasLink)(editorState, selection)) {
        // If a link is no longer selected, clear selected link ID state
        Object.assign(newState, {
          selectedLinkID: null
        });
      } else if (selectedLinkID !== entityKey) {
        // If link selection is new / different link selected, update it
        Object.assign(newState, {
          selectedLinkID: entityKey
        });
      }

      // Update internal state
      this.setState(newState);

      // Dispatch changes to plotly.js
      // TODO consider moving to render (plotly.js is a render target)
      var htmlContent = this.getEditorStateAsHTML(editorState).replace(/<br>\n*/, '<br>');
      if (this.props.value !== htmlContent) {
        (0, _debounce2.default)(this.props.onChange, [htmlContent]);
      }
    }
  }, {
    key: 'onBlur',
    value: function onBlur() {
      this.setState({
        editorFocus: false
      });
    }
  }, {
    key: 'onFocus',
    value: function onFocus() {
      this.setState({
        editorFocus: true
      });
    }
  }, {
    key: 'onLinkEditorBlur',
    value: function onLinkEditorBlur() {
      this.setState({
        linkEditorFocus: false
      });
    }
  }, {
    key: 'onLinkEditorFocus',
    value: function onLinkEditorFocus() {
      this.setState({
        linkEditorFocus: true
      });
    }
  }, {
    key: 'onLinkEditorChange',
    value: function onLinkEditorChange(linkID, urlValue) {
      var editorState = this.state.editorState;

      var selectionState = editorState.getSelection();

      // Update link URL
      _draftJs.Entity.replaceData(linkID, { url: urlValue });

      // Trigger an editor state update
      var updatedEditorState = _draftJs.RichUtils.toggleLink(editorState, selectionState, linkID);

      this.onChange(updatedEditorState);
    }

    /**
     * Will be called by LinkEditor when the user confirms or cancels new URL.
     * Will not be called if LinkEditor is closed by moving the cursor off of
     * the selected LINK entity.
     *
     * @param   {String} linkID The link entity key related to this LinkEditor
     * @returns {undefined}
     */

  }, {
    key: 'onLinkEditorClose',
    value: function onLinkEditorClose() {
      /*
           * Focus on editor immediately to avoid error that occurs when
           * `selection.extend` is called and another element has focus.
           * https://bugzilla.mozilla.org/show_bug.cgi?id=921444
           * https://github.com/facebook/draft-js/blob/342576bf7186d07c82a41d9ca8169130669747d6/src/component/selection/setDraftEditorSelection.js#L128-L134
           */
      this.focus();

      // Hide the editor.
      this.setState({
        linkEditorFocus: false,
        selectedLinkID: null
      });
    }
  }, {
    key: 'onKeyCommand',
    value: function onKeyCommand(command) {
      var newEditorState = (0, _DraftCommands.handleKeyCommand)(this.state.editorState, command);

      if (newEditorState) {
        this.onChange(newEditorState);

        // Let draft-js know that keyboard command is handled.
        return true;
      }

      // Default draft-js implementation
      return false;
    }
  }, {
    key: 'onReturnPressed',
    value: function onReturnPressed() {
      var newEditorState = (0, _DraftCommands.insertSoftNewline)(this.state.editorState);

      // Update internal and external state
      this.onChange(newEditorState);

      // Cancel draft-js implementation
      return true;
    }
  }, {
    key: 'onStyleButtonToggle',
    value: function onStyleButtonToggle(inlineStyle) {
      var newEditorState = (0, _DraftCommands.toggleInlineStyle)(this.state.editorState, inlineStyle);

      if (newEditorState) {
        this.onChange(newEditorState);
      }
    }
  }, {
    key: 'renderLinkEditor',
    value: function renderLinkEditor(selectedLinkID) {
      if (!selectedLinkID) {
        return null;
      }

      // All entities are link entities.
      var linkEntity = (0, _DraftCommands.getEntityByKey)(selectedLinkID);
      var linkURL = linkEntity.getData().url;

      var coordinates = (0, _getSelectionCoordinates2.default)();

      return _react2.default.createElement(_LinkEditor2.default, {
        onFocus: this.onLinkEditorFocus,
        onURLChange: this.onLinkEditorChange,
        onBlur: this.onLinkEditorBlur,
        onClose: this.onLinkEditorClose,
        coordinates: coordinates,
        linkID: selectedLinkID,
        linkURL: linkURL
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _state3 = this.state,
          editorState = _state3.editorState,
          selectedLinkID = _state3.selectedLinkID;

      var linkIsSelected = Boolean(selectedLinkID);

      return _react2.default.createElement(
        'div',
        { className: 'rich-text-editor__root' },
        _react2.default.createElement(_StyleButtonGroup2.default, {
          styles: _configuration.INLINE_STYLES,
          currentStyle: editorState.getCurrentInlineStyle(),
          linkIsSelected: linkIsSelected,
          onToggle: this.onStyleButtonToggle
        }),
        _react2.default.createElement(
          'div',
          { className: 'rich-text-editor__editor', onClick: this.focus },
          _react2.default.createElement(_draftJs.Editor, {
            customStyleMap: _configuration.STYLE_MAP,
            editorState: editorState,
            handleReturn: this.onReturnPressed,
            handleKeyCommand: this.onKeyCommand,
            onChange: this.onChange,
            onBlur: this.onBlur,
            onFocus: this.onFocus,
            placeholder: this.props.placeholder,
            spellCheck: false,
            ref: function ref(input) {
              return _this2.editorInput = input;
            }
          })
        ),
        this.renderLinkEditor(selectedLinkID)
      );
    }
  }]);

  return RichText;
}(_react.Component);

RichText.propTypes = {
  onChange: _propTypes2.default.func.isRequired,
  placeholder: _propTypes2.default.string,
  value: _propTypes2.default.any
};

RichText.defaultProps = {
  placeholder: '',
  value: ''
};

exports.default = RichText;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ "BFWj":
/*!****************************************************!*\
  !*** ./node_modules/react-day-picker/DayPicker.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/*
  Used as main file in package.json
*/

/* eslint-disable no-var */
/* eslint-env node */

var DayPicker = __webpack_require__(/*! ./lib/src/DayPicker */ "42BV");
var DateUtils = __webpack_require__(/*! ./lib/src/DateUtils */ "mHnu");
var LocaleUtils = __webpack_require__(/*! ./lib/src/LocaleUtils */ "ze2x");
var ModifiersUtils = __webpack_require__(/*! ./lib/src/ModifiersUtils */ "KFnn");
var Weekday = __webpack_require__(/*! ./lib/src/Weekday */ "jsC2");
var Navbar = __webpack_require__(/*! ./lib/src/Navbar */ "l//F");
var PropTypes = __webpack_require__(/*! ./lib/src/PropTypes */ "AvDN");

module.exports = DayPicker;
module.exports.DateUtils = DateUtils;
module.exports.LocaleUtils = LocaleUtils;
module.exports.ModifiersUtils = ModifiersUtils;
module.exports.WeekdayPropTypes = Weekday.propTypes;
module.exports.NavbarPropTypes = Navbar.propTypes;
module.exports.PropTypes = PropTypes;


/***/ }),

/***/ "BGip":
/*!***********************************************!*\
  !*** ./node_modules/mdi-react/MessageIcon.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var MessageIcon = function MessageIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M20,2H4C2.9,2 2,2.9 2,4V22L6,18H20C21.1,18 22,17.1 22,16V4C22,2.89 21.1,2 20,2Z' })
  );
};

module.exports = MessageIcon;


/***/ }),

/***/ "BIsW":
/*!***********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotPieShadedIcon.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotPieShadedIcon = function PlotPieShadedIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M17.5 19c-.188.375-.625.5-1 .313a.856.856 0 0 1-.25-.188l.813-1.188c.063 0 .125.063.188.063.375.188.438.688.25 1zm2 5.75c-.375-.188-.813-.063-1.063.313-.188.313-.063.813.313 1 .313.188.813.063 1-.25a.867.867 0 0 0-.25-1.063zM17.25 27c-.375-.188-.875-.063-1.063.313-.188.313-.063.813.313 1 .313.188.813.063 1-.25A.867.867 0 0 0 17.25 27zm0-4.5c-.375-.188-.813-.063-1.063.313-.188.313-.063.813.313 1s.813.063 1-.25c.188-.375.125-.813-.25-1.063zm2.25-11.312c-.313-.188-.813-.063-1 .313-.188.313-.063.813.25 1a.867.867 0 0 0 1.063-.25c.188-.375.063-.813-.313-1.063zm0 4.562c-.313-.25-.813-.125-1 .25s-.063.813.25 1c.375.25.813.125 1.063-.25.188-.375.063-.813-.313-1zm0 4.5c-.375-.188-.813-.063-1 .313-.25.313-.125.813.25 1s.813.063 1-.25c.25-.375.125-.875-.25-1.063zm-6.812 6.813c-.313-.25-.813-.125-1 .25s-.063.813.25 1c.375.25.875.125 1.063-.25s.063-.813-.313-1zM15 24.75c-.375-.188-.813-.063-1.063.313-.188.375-.063.813.313 1 .313.25.813.125 1-.25S15.313 25 15 24.75zM18.75 8c.375.188.813.063 1-.313.25-.375.125-.813-.25-1-.375-.25-.813-.125-1 .25-.25.375-.125.813.25 1.063zm-4.312 13.625a.814.814 0 0 0 .813-.313.928.928 0 0 0 0-.813zM21.75 27c-.375-.188-.813-.063-1.063.313-.188.313-.063.75.25 1 .438-.188.813-.375 1.188-.563a.976.976 0 0 0-.375-.75zm6.063-14.5a.758.758 0 0 0 .938-.125c-.125-.438-.25-.875-.438-1.25-.313-.063-.625.063-.813.375s-.063.813.313 1zM18.75 3.438c.313.188.75.125.938-.188-.438-.125-.875-.188-1.313-.313.063.25.188.438.375.5zM21 5.688c.375.25.813.125 1.063-.25.188-.375.063-.813-.313-1-.375-.25-.813-.125-1 .25-.25.375-.125.813.25 1zM27.5 20.5c-.188.375-.063.813.313 1 .063.063.125.063.188.125.188-.438.375-.938.563-1.375-.375-.25-.813-.125-1.063.25zm-1.25 2c-.313-.25-.813-.125-1 .25s-.063.813.25 1.063c.375.188.875.063 1.063-.313s.063-.813-.313-1zM24.063 6.688c-.375-.188-.875-.063-1.063.25-.188.375-.063.813.313 1.063.313.188.813.063 1-.313.188-.313.063-.813-.25-1zm2.187 11.25c-.313-.188-.813-.063-1 .313s-.063.813.25 1c.375.25.875.125 1.063-.25s.063-.813-.313-1.063zm2.313-2.25c-.375-.188-.813-.063-1.063.313-.188.313-.063.813.313 1 .313.188.813.063 1-.25a.867.867 0 0 0-.25-1.063zm-4.5-4.5c-.375-.188-.875-.063-1.063.313-.188.313-.063.813.313 1 .313.188.813.063 1-.25a.867.867 0 0 0-.25-1.063zm2.25 2.25c-.375-.188-.813-.063-1.063.313-.188.375-.063.813.313 1 .313.188.813.125 1-.25s.063-.813-.25-1.063zM21.75 22.5a.867.867 0 0 0-1.063.25c-.188.375-.063.875.313 1.063s.813.063 1-.313c.25-.313.125-.813-.25-1zm4.563-13.562c-.375-.188-.813-.063-1.063.313-.188.313-.063.813.313 1 .313.188.813.063 1-.25.188-.375.063-.875-.25-1.063zm-2.25 6.812c-.375-.25-.875-.125-1.063.25s-.063.813.313 1c.313.25.813.125 1-.25s.063-.813-.25-1zm-2.313-2.312c-.313-.188-.813-.063-1 .313s-.063.813.25 1c.375.188.813.125 1.063-.25.188-.375.063-.813-.313-1.063zm0 4.562c-.313-.25-.813-.125-1 .25s-.063.813.25 1c.375.25.813.125 1.063-.25.188-.375.063-.813-.313-1zm0-9.062c-.313-.188-.813-.063-1 .313-.188.313-.063.813.25 1a.867.867 0 0 0 1.063-.25c.188-.375.063-.875-.313-1.063zM24 20.25c-.313-.25-.813-.125-1 .25s-.063.813.25 1c.375.25.813.125 1.063-.25.188-.375.063-.813-.313-1zm0 4.5c-.375-.188-.813-.063-1 .313-.25.313-.125.813.25 1s.813.063 1-.25c.25-.375.125-.813-.25-1.063zM32 16c0 8.813-7.188 16-16 16S0 24.812 0 16C0 7.187 7.188 0 16 0s16 7.188 16 16zM7 27.375L14.75 16.5l-13.063-3a16.224 16.224 0 0 0-.188 2.5c0 4 1.625 7.625 4.25 10.25a7 7 0 0 0 1.25 1.125zM30.5 16c0-4-1.625-7.625-4.25-10.25-2.438-2.438-5.813-4.063-9.5-4.25V16l-.125.438L8.25 28.251a14.245 14.245 0 0 0 7.75 2.25c4 0 7.625-1.625 10.25-4.25s4.25-6.25 4.25-10.25z' })
    );
};

exports.default = PlotPieShadedIcon;

/***/ }),

/***/ "BKMn":
/*!*************************************************************************************!*\
  !*** ./node_modules/react-color/lib/components/photoshop/PhotoshopPointerCircle.js ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.PhotoshopPointerCircle = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PhotoshopPointerCircle = exports.PhotoshopPointerCircle = function PhotoshopPointerCircle(_ref) {
  var hsl = _ref.hsl;

  var styles = (0, _reactcss2.default)({
    'default': {
      picker: {
        width: '12px',
        height: '12px',
        borderRadius: '6px',
        boxShadow: 'inset 0 0 0 1px #fff',
        transform: 'translate(-6px, -6px)'
      }
    },
    'black-outline': {
      picker: {
        boxShadow: 'inset 0 0 0 1px #000'
      }
    }
  }, { 'black-outline': hsl.l > 0.5 });

  return _react2.default.createElement('div', { style: styles.picker });
};

exports.default = PhotoshopPointerCircle;

/***/ }),

/***/ "BOmv":
/*!*************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/TraceTypeSelector.js ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.TraceTypeSelectorButton = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _plotlyIcons = __webpack_require__(/*! plotly-icons */ "hwSx");

var _Modal = __webpack_require__(/*! ../containers/Modal */ "caab");

var _Modal2 = _interopRequireDefault(_Modal);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _constants = __webpack_require__(/*! ../../lib/constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var renderActionItems = function renderActionItems(actionItems, item) {
  return actionItems ? actionItems(item).map(function (action, i) {
    return !action.onClick ? null : _react2.default.createElement(
      'a',
      {
        className: 'trace-item__actions__item',
        key: i,
        'aria-label': action.label,
        'data-microtip-position': 'top-left',
        role: 'tooltip',
        onClick: action.onClick,
        target: '_blank'
      },
      action.icon
    );
  }) : null;
};

var Item = function Item(_ref) {
  var item = _ref.item,
      active = _ref.active,
      handleClick = _ref.handleClick,
      actions = _ref.actions,
      showActions = _ref.showActions,
      complex = _ref.complex;
  var label = item.label,
      value = item.value,
      icon = item.icon;

  var SimpleIcon = (0, _lib.renderTraceIcon)(icon ? icon : value);
  var ComplexIcon = (0, _lib.renderTraceIcon)(icon ? icon : value, 'TraceType');

  return _react2.default.createElement(
    'div',
    { className: 'trace-item' + (active ? ' trace-item--active' : ''), onClick: handleClick },
    _react2.default.createElement(
      'div',
      { className: 'trace-item__actions' },
      actions && showActions ? renderActionItems(actions, item) : null
    ),
    _react2.default.createElement(
      'div',
      { className: 'trace-item__image' },
      !complex && _react2.default.createElement(
        'div',
        { className: 'trace-item__image__svg' },
        _react2.default.createElement(SimpleIcon, null)
      ),
      complex && _react2.default.createElement(
        'div',
        { className: 'trace-item__image__wrapper' },
        _react2.default.createElement(ComplexIcon, null)
      )
    ),
    _react2.default.createElement(
      'div',
      { className: 'trace-item__label' },
      label
    )
  );
};

Item.propTypes = {
  item: _propTypes2.default.object,
  active: _propTypes2.default.bool,
  complex: _propTypes2.default.bool,
  handleClick: _propTypes2.default.func,
  actions: _propTypes2.default.func,
  showActions: _propTypes2.default.bool
};
Item.contextTypes = {
  localize: _propTypes2.default.func
};

var TraceTypeSelector = function (_Component) {
  _inherits(TraceTypeSelector, _Component);

  function TraceTypeSelector(props) {
    _classCallCheck(this, TraceTypeSelector);

    var _this = _possibleConstructorReturn(this, (TraceTypeSelector.__proto__ || Object.getPrototypeOf(TraceTypeSelector)).call(this, props));

    _this.selectAndClose = _this.selectAndClose.bind(_this);
    _this.actions = _this.actions.bind(_this);
    _this.renderCategories = _this.renderCategories.bind(_this);
    _this.renderGrid = _this.renderGrid.bind(_this);
    _this.renderSingleBlock = _this.renderSingleBlock.bind(_this);
    return _this;
  }

  _createClass(TraceTypeSelector, [{
    key: 'selectAndClose',
    value: function selectAndClose(value) {
      var _props = this.props,
          updateContainer = _props.updateContainer,
          glByDefault = _props.glByDefault,
          type = _props.fullContainer.type;

      var computedValue = (0, _lib.traceTypeToPlotlyInitFigure)(value);
      if ((type && type.endsWith('gl') || !_constants.TRACES_WITH_GL.includes(type) && glByDefault) && _constants.TRACES_WITH_GL.includes(computedValue.type) && !computedValue.type.endsWith('gl')) {
        computedValue.type += 'gl';
      }
      updateContainer(computedValue);
      this.context.handleClose();
    }
  }, {
    key: 'actions',
    value: function actions(_ref2) {
      var _this2 = this;

      var value = _ref2.value;
      var _context = this.context,
          _ = _context.localize,
          chartHelp = _context.chartHelp;


      var onClick = function onClick(e, func) {
        e.stopPropagation();
        func();
        _this2.context.handleClose();
      };

      return [{
        label: _('Charts like this by Plotly users.'),
        onClick: chartHelp[value] && chartHelp[value].feedQuery && function (e) {
          return onClick(e, function () {
            return window.open('https://plot.ly/feed/?q=' + (chartHelp[value] ? chartHelp[value].feedQuery : value), '_blank');
          });
        },
        icon: _react2.default.createElement(_plotlyIcons.SearchIcon, null)
      }, {
        label: _('View tutorials on this chart type.'),
        onClick: chartHelp[value] && chartHelp[value].helpDoc && function (e) {
          return onClick(e, function () {
            return window.open(chartHelp[value].helpDoc, '_blank');
          });
        },
        icon: _react2.default.createElement(_plotlyIcons.ThumnailViewIcon, null)
      }, {
        label: _('See a basic example.'),
        onClick: chartHelp[value] && chartHelp[value].examplePlot && function (e) {
          return onClick(e, chartHelp[value].examplePlot);
        },
        icon: _react2.default.createElement(_plotlyIcons.GraphIcon, null)
      }];
    }
  }, {
    key: 'renderCategories',
    value: function renderCategories() {
      var _this3 = this;

      var fullValue = this.props.fullValue;
      var _context2 = this.context,
          mapBoxAccess = _context2.mapBoxAccess,
          _ = _context2.localize,
          chartHelp = _context2.chartHelp;
      var _props$traceTypesConf = this.props.traceTypesConfig,
          traces = _props$traceTypesConf.traces,
          categories = _props$traceTypesConf.categories,
          complex = _props$traceTypesConf.complex;


      return categories(_).map(function (category, i) {
        var items = traces(_).filter(function (_ref3) {
          var value = _ref3.category.value;
          return value === category.value;
        }).filter(function (i) {
          return i.value !== 'scattergl' && i.value !== 'scatterpolargl';
        });

        if (!mapBoxAccess) {
          items = items.filter(function (i) {
            return i.value !== 'scattermapbox';
          });
        }

        var MAX_ITEMS = 4;

        var columnClasses = items.length > MAX_ITEMS && !category.maxColumns || category.maxColumns && category.maxColumns > 1 ? 'trace-grid__column trace-grid__column--double' : 'trace-grid__column';

        return _react2.default.createElement(
          'div',
          { className: columnClasses, key: i },
          _react2.default.createElement(
            'div',
            { className: 'trace-grid__column__header' },
            category.label
          ),
          _react2.default.createElement(
            'div',
            { className: 'trace-grid__column__items' },
            items.map(function (item) {
              return _react2.default.createElement(Item, {
                complex: complex,
                key: item.value,
                active: fullValue === item.value,
                item: item,
                actions: _this3.actions,
                handleClick: function handleClick() {
                  return _this3.selectAndClose(item.value);
                },
                showActions: Boolean(chartHelp)
              });
            })
          )
        );
      });
    }
  }, {
    key: 'renderGrid',
    value: function renderGrid() {
      return _react2.default.createElement(
        'div',
        { className: 'trace-grid' },
        this.renderCategories()
      );
    }
  }, {
    key: 'renderSingleBlock',
    value: function renderSingleBlock() {
      var _this4 = this;

      var fullValue = this.props.fullValue;
      var _ = this.context.localize;
      var _props$traceTypesConf2 = this.props.traceTypesConfig,
          traces = _props$traceTypesConf2.traces,
          complex = _props$traceTypesConf2.complex;


      return _react2.default.createElement(
        'div',
        { className: 'trace-grid-single-block' },
        traces(_).map(function (item) {
          return _react2.default.createElement(Item, {
            key: item.value,
            complex: complex,
            active: fullValue === item.value,
            item: item,
            actions: _this4.actions,
            showActions: false,
            handleClick: function handleClick() {
              return _this4.selectAndClose(item.value);
            },
            style: { display: 'inline-block' }
          });
        })
      );
    }
  }, {
    key: 'render',
    value: function render() {
      var _ = this.context.localize;
      var categories = this.props.traceTypesConfig.categories;


      return _react2.default.createElement(
        _Modal2.default,
        { title: _('Select Trace Type') },
        categories ? this.renderGrid() : this.renderSingleBlock()
      );
    }
  }]);

  return TraceTypeSelector;
}(_react.Component);

TraceTypeSelector.propTypes = {
  updateContainer: _propTypes2.default.func,
  fullValue: _propTypes2.default.string,
  fullContainer: _propTypes2.default.object,
  glByDefault: _propTypes2.default.bool,
  traceTypesConfig: _propTypes2.default.object
};
TraceTypeSelector.contextTypes = {
  handleClose: _propTypes2.default.func,
  localize: _propTypes2.default.func,
  mapBoxAccess: _propTypes2.default.bool,
  chartHelp: _propTypes2.default.object
};

var TraceTypeSelectorButton = exports.TraceTypeSelectorButton = function (_Component2) {
  _inherits(TraceTypeSelectorButton, _Component2);

  function TraceTypeSelectorButton() {
    _classCallCheck(this, TraceTypeSelectorButton);

    return _possibleConstructorReturn(this, (TraceTypeSelectorButton.__proto__ || Object.getPrototypeOf(TraceTypeSelectorButton)).apply(this, arguments));
  }

  _createClass(TraceTypeSelectorButton, [{
    key: 'render',
    value: function render() {
      var _props2 = this.props,
          handleClick = _props2.handleClick,
          container = _props2.container,
          traces = _props2.traceTypesConfig.traces;
      var _ = this.context.localize;


      var inferredType = (0, _lib.plotlyTraceToCustomTrace)(container);

      var _traces$find = traces(_).find(function (type) {
        return type.value === inferredType;
      }),
          label = _traces$find.label,
          icon = _traces$find.icon,
          value = _traces$find.value;

      var Icon = (0, _lib.renderTraceIcon)(icon ? icon : value);

      return _react2.default.createElement(
        'div',
        { className: 'trace-type-select-button', onClick: handleClick ? handleClick : null },
        _react2.default.createElement(
          'div',
          { className: 'trace-type-select-button__icon' },
          _react2.default.createElement(Icon, null)
        ),
        label
      );
    }
  }]);

  return TraceTypeSelectorButton;
}(_react.Component);

TraceTypeSelectorButton.propTypes = {
  handleClick: _propTypes2.default.func.isRequired,
  container: _propTypes2.default.object,
  traceTypesConfig: _propTypes2.default.object.isRequired
};
TraceTypeSelectorButton.contextTypes = {
  localize: _propTypes2.default.func
};

exports.default = TraceTypeSelector;
//# sourceMappingURL=TraceTypeSelector.js.map

/***/ }),

/***/ "BQpX":
/*!**********************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/apputils/style/mainareawidget.css ***!
  \**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2016, Jupyter Development Team.\n|\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.jp-MainAreaWidget > :focus {\n  outline: none;\n}\n", ""]);

// exports


/***/ }),

/***/ "BRr/":
/*!*********************************************!*\
  !*** ./node_modules/entities/lib/encode.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var inverseXML = getInverseObj(__webpack_require__(/*! ../maps/xml.json */ "ZLJe")),
    xmlReplacer = getInverseReplacer(inverseXML);

exports.XML = getInverse(inverseXML, xmlReplacer);

var inverseHTML = getInverseObj(__webpack_require__(/*! ../maps/entities.json */ "8PLQ")),
    htmlReplacer = getInverseReplacer(inverseHTML);

exports.HTML = getInverse(inverseHTML, htmlReplacer);

function getInverseObj(obj) {
    return Object.keys(obj)
        .sort()
        .reduce(function(inverse, name) {
            inverse[obj[name]] = "&" + name + ";";
            return inverse;
        }, {});
}

function getInverseReplacer(inverse) {
    var single = [],
        multiple = [];

    Object.keys(inverse).forEach(function(k) {
        if (k.length === 1) {
            single.push("\\" + k);
        } else {
            multiple.push(k);
        }
    });

    //TODO add ranges
    multiple.unshift("[" + single.join("") + "]");

    return new RegExp(multiple.join("|"), "g");
}

var re_nonASCII = /[^\0-\x7F]/g,
    re_astralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;

function singleCharReplacer(c) {
    return (
        "&#x" +
        c
            .charCodeAt(0)
            .toString(16)
            .toUpperCase() +
        ";"
    );
}

function astralReplacer(c) {
    // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
    var high = c.charCodeAt(0);
    var low = c.charCodeAt(1);
    var codePoint = (high - 0xd800) * 0x400 + low - 0xdc00 + 0x10000;
    return "&#x" + codePoint.toString(16).toUpperCase() + ";";
}

function getInverse(inverse, re) {
    function func(name) {
        return inverse[name];
    }

    return function(data) {
        return data
            .replace(re, func)
            .replace(re_astralSymbols, astralReplacer)
            .replace(re_nonASCII, singleCharReplacer);
    };
}

var re_xmlChars = getInverseReplacer(inverseXML);

function escapeXML(data) {
    return data
        .replace(re_xmlChars, singleCharReplacer)
        .replace(re_astralSymbols, astralReplacer)
        .replace(re_nonASCII, singleCharReplacer);
}

exports.escape = escapeXML;


/***/ }),

/***/ "BVg3":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/is.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


function plural(n) {
    if (n % 100 === 11) {
        return true;
    } else if (n % 10 === 1) {
        return false;
    }
    return true;
}
function translate(number, withoutSuffix, key, isFuture) {
    var result = number + ' ';
    switch (key) {
        case 's':
            return withoutSuffix || isFuture ? 'nokkrar sekúndur' : 'nokkrum sekúndum';
        case 'ss':
            if (plural(number)) {
                return result + (withoutSuffix || isFuture ? 'sekúndur' : 'sekúndum');
            }
            return result + 'sekúnda';
        case 'm':
            return withoutSuffix ? 'mínúta' : 'mínútu';
        case 'mm':
            if (plural(number)) {
                return result + (withoutSuffix || isFuture ? 'mínútur' : 'mínútum');
            } else if (withoutSuffix) {
                return result + 'mínúta';
            }
            return result + 'mínútu';
        case 'hh':
            if (plural(number)) {
                return result + (withoutSuffix || isFuture ? 'klukkustundir' : 'klukkustundum');
            }
            return result + 'klukkustund';
        case 'd':
            if (withoutSuffix) {
                return 'dagur';
            }
            return isFuture ? 'dag' : 'degi';
        case 'dd':
            if (plural(number)) {
                if (withoutSuffix) {
                    return result + 'dagar';
                }
                return result + (isFuture ? 'daga' : 'dögum');
            } else if (withoutSuffix) {
                return result + 'dagur';
            }
            return result + (isFuture ? 'dag' : 'degi');
        case 'M':
            if (withoutSuffix) {
                return 'mánuður';
            }
            return isFuture ? 'mánuð' : 'mánuði';
        case 'MM':
            if (plural(number)) {
                if (withoutSuffix) {
                    return result + 'mánuðir';
                }
                return result + (isFuture ? 'mánuði' : 'mánuðum');
            } else if (withoutSuffix) {
                return result + 'mánuður';
            }
            return result + (isFuture ? 'mánuð' : 'mánuði');
        case 'y':
            return withoutSuffix || isFuture ? 'ár' : 'ári';
        case 'yy':
            if (plural(number)) {
                return result + (withoutSuffix || isFuture ? 'ár' : 'árum');
            }
            return result + (withoutSuffix || isFuture ? 'ár' : 'ári');
    }
}

var is = moment.defineLocale('is', {
    months : 'janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember'.split('_'),
    monthsShort : 'jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des'.split('_'),
    weekdays : 'sunnudagur_mánudagur_þriðjudagur_miðvikudagur_fimmtudagur_föstudagur_laugardagur'.split('_'),
    weekdaysShort : 'sun_mán_þri_mið_fim_fös_lau'.split('_'),
    weekdaysMin : 'Su_Má_Þr_Mi_Fi_Fö_La'.split('_'),
    longDateFormat : {
        LT : 'H:mm',
        LTS : 'H:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D. MMMM YYYY',
        LLL : 'D. MMMM YYYY [kl.] H:mm',
        LLLL : 'dddd, D. MMMM YYYY [kl.] H:mm'
    },
    calendar : {
        sameDay : '[í dag kl.] LT',
        nextDay : '[á morgun kl.] LT',
        nextWeek : 'dddd [kl.] LT',
        lastDay : '[í gær kl.] LT',
        lastWeek : '[síðasta] dddd [kl.] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'eftir %s',
        past : 'fyrir %s síðan',
        s : translate,
        ss : translate,
        m : translate,
        mm : translate,
        h : 'klukkustund',
        hh : translate,
        d : translate,
        dd : translate,
        M : translate,
        MM : translate,
        y : translate,
        yy : translate
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return is;

})));


/***/ }),

/***/ "BVrX":
/*!*************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/regex.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



/*
 * make a regex for matching counter ids/names ie xaxis, xaxis2, xaxis10...
 *
 * @param {string} head: the head of the pattern, eg 'x' matches 'x', 'x2', 'x10' etc.
 *      'xy' is a special case for cartesian subplots: it matches 'x2y3' etc
 * @param {Optional(string)} tail: a fixed piece after the id
 *      eg counterRegex('scene', '.annotations') for scene2.annotations etc.
 * @param {boolean} openEnded: if true, the string may continue past the match.
 * @param {boolean} matchBeginning: if false, the string may start before the match.
 */
exports.counter = function(head, tail, openEnded, matchBeginning) {
    var fullTail = (tail || '') + (openEnded ? '' : '$');
    var startWithPrefix = matchBeginning === false ? '' : '^';
    if(head === 'xy') {
        return new RegExp(startWithPrefix + 'x([2-9]|[1-9][0-9]+)?y([2-9]|[1-9][0-9]+)?' + fullTail);
    }
    return new RegExp(startWithPrefix + head + '([2-9]|[1-9][0-9]+)?' + fullTail);
};


/***/ }),

/***/ "BWSO":
/*!*************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/connectImageToLayout.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

exports.default = connectImageToLayout;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _lib = __webpack_require__(/*! ../lib */ "RXjw");

var _constants = __webpack_require__(/*! ./constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function connectImageToLayout(WrappedComponent) {
  var ImageConnectedComponent = function (_Component) {
    _inherits(ImageConnectedComponent, _Component);

    function ImageConnectedComponent(props, context) {
      _classCallCheck(this, ImageConnectedComponent);

      var _this = _possibleConstructorReturn(this, (ImageConnectedComponent.__proto__ || Object.getPrototypeOf(ImageConnectedComponent)).call(this, props, context));

      _this.deleteImage = _this.deleteImage.bind(_this);
      _this.updateImage = _this.updateImage.bind(_this);
      _this.setLocals(props, context);
      return _this;
    }

    _createClass(ImageConnectedComponent, [{
      key: 'componentWillReceiveProps',
      value: function componentWillReceiveProps(nextProps, nextContext) {
        this.setLocals(nextProps, nextContext);
      }
    }, {
      key: 'setLocals',
      value: function setLocals(props, context) {
        var imageIndex = props.imageIndex;
        var container = context.container,
            fullContainer = context.fullContainer;


        var images = container.images || [];
        var fullImages = fullContainer.images || [];
        this.container = images[imageIndex];
        this.fullContainer = fullImages[imageIndex];
      }
    }, {
      key: 'getChildContext',
      value: function getChildContext() {
        var _this2 = this;

        return {
          getValObject: function getValObject(attr) {
            return !_this2.context.getValObject ? null : _this2.context.getValObject('images[].' + attr);
          },
          updateContainer: this.updateImage,
          deleteContainer: this.deleteImage,
          container: this.container,
          fullContainer: this.fullContainer
        };
      }
    }, {
      key: 'updateImage',
      value: function updateImage(update) {
        var newUpdate = {};
        var imageIndex = this.props.imageIndex;

        for (var key in update) {
          var newkey = 'images[' + imageIndex + '].' + key;
          newUpdate[newkey] = update[key];
        }
        this.context.updateContainer(newUpdate);
      }
    }, {
      key: 'deleteImage',
      value: function deleteImage() {
        if (this.context.onUpdate) {
          this.context.onUpdate({
            type: _constants.EDITOR_ACTIONS.DELETE_IMAGE,
            payload: { imageIndex: this.props.imageIndex }
          });
        }
      }
    }, {
      key: 'render',
      value: function render() {
        return _react2.default.createElement(WrappedComponent, this.props);
      }
    }]);

    return ImageConnectedComponent;
  }(_react.Component);

  ImageConnectedComponent.displayName = 'ImageConnected' + (0, _lib.getDisplayName)(WrappedComponent);

  ImageConnectedComponent.propTypes = {
    imageIndex: _propTypes2.default.number.isRequired
  };

  ImageConnectedComponent.contextTypes = {
    container: _propTypes2.default.object,
    fullContainer: _propTypes2.default.object,
    data: _propTypes2.default.array,
    onUpdate: _propTypes2.default.func,
    updateContainer: _propTypes2.default.func,
    getValObject: _propTypes2.default.func
  };

  ImageConnectedComponent.childContextTypes = {
    updateContainer: _propTypes2.default.func,
    deleteContainer: _propTypes2.default.func,
    container: _propTypes2.default.object,
    fullContainer: _propTypes2.default.object,
    getValObject: _propTypes2.default.func
  };

  var plotly_editor_traits = WrappedComponent.plotly_editor_traits;

  ImageConnectedComponent.plotly_editor_traits = plotly_editor_traits;

  return ImageConnectedComponent;
}
//# sourceMappingURL=connectImageToLayout.js.map

/***/ }),

/***/ "BWnT":
/*!*************************************************************!*\
  !*** ./node_modules/@jupyterlab/outputarea/style/index.css ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "3GB9");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "Ba7A":
/*!******************************************************************!*\
  !*** ./node_modules/react-color/lib/components/common/Swatch.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Swatch = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _interaction = __webpack_require__(/*! ../../helpers/interaction */ "japM");

var _Checkboard = __webpack_require__(/*! ./Checkboard */ "Nq3d");

var _Checkboard2 = _interopRequireDefault(_Checkboard);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var ENTER = 13;

var Swatch = exports.Swatch = function Swatch(_ref) {
  var color = _ref.color,
      style = _ref.style,
      _ref$onClick = _ref.onClick,
      onClick = _ref$onClick === undefined ? function () {} : _ref$onClick,
      onHover = _ref.onHover,
      _ref$title = _ref.title,
      title = _ref$title === undefined ? color : _ref$title,
      children = _ref.children,
      focus = _ref.focus,
      _ref$focusStyle = _ref.focusStyle,
      focusStyle = _ref$focusStyle === undefined ? {} : _ref$focusStyle;

  var transparent = color === 'transparent';
  var styles = (0, _reactcss2.default)({
    default: {
      swatch: _extends({
        background: color,
        height: '100%',
        width: '100%',
        cursor: 'pointer',
        position: 'relative',
        outline: 'none'
      }, style, focus ? focusStyle : {})
    }
  });

  var handleClick = function handleClick(e) {
    return onClick(color, e);
  };
  var handleKeyDown = function handleKeyDown(e) {
    return e.keyCode === ENTER && onClick(color, e);
  };
  var handleHover = function handleHover(e) {
    return onHover(color, e);
  };

  var optionalEvents = {};
  if (onHover) {
    optionalEvents.onMouseOver = handleHover;
  }

  return _react2.default.createElement(
    'div',
    _extends({
      style: styles.swatch,
      onClick: handleClick,
      title: title,
      tabIndex: 0,
      onKeyDown: handleKeyDown
    }, optionalEvents),
    children,
    transparent && _react2.default.createElement(_Checkboard2.default, {
      borderRadius: styles.swatch.borderRadius,
      boxShadow: 'inset 0 0 0 1px rgba(0,0,0,0.1)'
    })
  );
};

exports.default = (0, _interaction.handleFocus)(Swatch);

/***/ }),

/***/ "BbDm":
/*!*********************************************************!*\
  !*** ./node_modules/@phosphor/domutils/lib/selector.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * The namespace for selector related utilities.
 */
var Selector;
(function (Selector) {
    /**
     * Calculate the specificity of a single CSS selector.
     *
     * @param selector - The CSS selector of interest.
     *
     * @returns The specificity of the selector.
     *
     * #### Undefined Behavior
     * The selector is invalid.
     *
     * #### Notes
     * This is based on https://www.w3.org/TR/css3-selectors/#specificity
     *
     * A larger number represents a more specific selector.
     *
     * The smallest possible specificity is `0`.
     *
     * The result is represented as a hex number `0x<aa><bb><cc>` where
     * each component is the count of the respective selector clause.
     *
     * If the selector contains commas, only the first clause is used.
     *
     * The computed result is cached, so subsequent calculations for the
     * same selector are extremely fast.
     */
    function calculateSpecificity(selector) {
        if (selector in Private.specificityCache) {
            return Private.specificityCache[selector];
        }
        var result = Private.calculateSingle(selector);
        return Private.specificityCache[selector] = result;
    }
    Selector.calculateSpecificity = calculateSpecificity;
    /**
     * Test whether a selector is a valid CSS selector.
     *
     * @param selector - The CSS selector of interest.
     *
     * @returns `true` if the selector is valid, `false` otherwise.
     *
     * #### Notes
     * The computed result is cached, so subsequent tests for the same
     * selector are extremely fast.
     */
    function isValid(selector) {
        if (selector in Private.validityCache) {
            return Private.validityCache[selector];
        }
        var result = true;
        try {
            Private.testElem.querySelector(selector);
        }
        catch (err) {
            result = false;
        }
        return Private.validityCache[selector] = result;
    }
    Selector.isValid = isValid;
    /**
     * Test whether an element matches a CSS selector.
     *
     * @param element - The element of interest.
     *
     * @param selector - The valid CSS selector of interest.
     *
     * @returns `true` if the element is a match, `false` otherwise.
     *
     * #### Notes
     * This function uses the builtin browser capabilities when possible,
     * falling back onto a document query otherwise.
     */
    function matches(element, selector) {
        return Private.protoMatchFunc.call(element, selector);
    }
    Selector.matches = matches;
})(Selector = exports.Selector || (exports.Selector = {}));
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * A cache of computed selector specificity values.
     */
    Private.specificityCache = Object.create(null);
    /**
     * A cache of computed selector validity.
     */
    Private.validityCache = Object.create(null);
    /**
     * An empty element for testing selector validity.
     */
    Private.testElem = document.createElement('div');
    /**
     * A cross-browser CSS selector matching prototype function.
     */
    Private.protoMatchFunc = (function () {
        var proto = Element.prototype;
        return (proto.matches ||
            proto.matchesSelector ||
            proto.mozMatchesSelector ||
            proto.msMatchesSelector ||
            proto.oMatchesSelector ||
            proto.webkitMatchesSelector ||
            (function (selector) {
                var elem = this;
                var matches = elem.ownerDocument.querySelectorAll(selector);
                return Array.prototype.indexOf.call(matches, elem) !== -1;
            }));
    })();
    /**
     * Calculate the specificity of a single selector.
     *
     * The behavior is undefined if the selector is invalid.
     */
    function calculateSingle(selector) {
        // Ignore anything after the first comma.
        selector = selector.split(',', 1)[0];
        // Setup the aggregate counters.
        var a = 0;
        var b = 0;
        var c = 0;
        // Apply a regex to the front of the selector. If it succeeds, that
        // portion of the selector is removed. Returns a success/fail flag.
        function match(re) {
            var match = selector.match(re);
            if (match === null) {
                return false;
            }
            selector = selector.slice(match[0].length);
            return true;
        }
        // Replace the negation pseudo-class (which is ignored),
        // but keep its inner content (which is not ignored).
        selector = selector.replace(NEGATION_RE, ' $1 ');
        // Continue matching until the selector is consumed.
        while (selector.length > 0) {
            // Match an ID selector.
            if (match(ID_RE)) {
                a++;
                continue;
            }
            // Match a class selector.
            if (match(CLASS_RE)) {
                b++;
                continue;
            }
            // Match an attribute selector.
            if (match(ATTR_RE)) {
                b++;
                continue;
            }
            // Match a pseudo-element selector. This is done before matching
            // a pseudo-class since this regex overlaps with that regex.
            if (match(PSEUDO_ELEM_RE)) {
                c++;
                continue;
            }
            // Match a pseudo-class selector.
            if (match(PSEDUO_CLASS_RE)) {
                b++;
                continue;
            }
            // Match a plain type selector.
            if (match(TYPE_RE)) {
                c++;
                continue;
            }
            // Finally, match any ignored characters.
            if (match(IGNORE_RE)) {
                continue;
            }
            // At this point, the selector is assumed to be invalid.
            return 0;
        }
        // Clamp each component to a reasonable base.
        a = Math.min(a, 0xFF);
        b = Math.min(b, 0xFF);
        c = Math.min(c, 0xFF);
        // Combine the components into a single result.
        return (a << 16) | (b << 8) | c;
    }
    Private.calculateSingle = calculateSingle;
    /**
     * A regex which matches an ID selector at string start.
     */
    var ID_RE = /^#[^\s\+>~#\.\[:]+/;
    /**
     * A regex which matches a class selector at string start.
     */
    var CLASS_RE = /^\.[^\s\+>~#\.\[:]+/;
    /**
     * A regex which matches an attribute selector at string start.
     */
    var ATTR_RE = /^\[[^\]]+\]/;
    /**
     * A regex which matches a type selector at string start.
     */
    var TYPE_RE = /^[^\s\+>~#\.\[:]+/;
    /**
     * A regex which matches a pseudo-element selector at string start.
     */
    var PSEUDO_ELEM_RE = /^(::[^\s\+>~#\.\[:]+|:first-line|:first-letter|:before|:after)/;
    /**
     * A regex which matches a pseudo-class selector at string start.
     */
    var PSEDUO_CLASS_RE = /^:[^\s\+>~#\.\[:]+/;
    /**
     * A regex which matches ignored characters at string start.
     */
    var IGNORE_RE = /^[\s\+>~\*]+/;
    /**
     * A regex which matches the negation pseudo-class globally.
     */
    var NEGATION_RE = /:not\(([^\)]+)\)/g;
})(Private || (Private = {}));


/***/ }),

/***/ "BkRI":
/*!******************************************!*\
  !*** ./node_modules/lodash/cloneDeep.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseClone = __webpack_require__(/*! ./_baseClone */ "OBhP");

/** 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;


/***/ }),

/***/ "Bm3m":
/*!*******************************************************!*\
  !*** ./node_modules/@phosphor/algorithm/lib/empty.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/**
 * Create an empty iterator.
 *
 * @returns A new iterator which yields nothing.
 *
 * #### Example
 * ```typescript
 * import { empty, toArray } from '@phosphor/algorithm';
 *
 * let stream = empty<number>();
 *
 * toArray(stream);  // []
 * ```
 */
function empty() {
    return new EmptyIterator();
}
exports.empty = empty;
/**
 * An iterator which is always empty.
 */
var EmptyIterator = (function () {
    /**
     * Construct a new empty iterator.
     */
    function EmptyIterator() {
    }
    /**
     * Get an iterator over the object's values.
     *
     * @returns An iterator which yields the object's values.
     */
    EmptyIterator.prototype.iter = function () {
        return this;
    };
    /**
     * Create an independent clone of the iterator.
     *
     * @returns A new independent clone of the iterator.
     */
    EmptyIterator.prototype.clone = function () {
        return new EmptyIterator();
    };
    /**
     * Get the next value from the iterator.
     *
     * @returns The next value from the iterator, or `undefined`.
     */
    EmptyIterator.prototype.next = function () {
        return undefined;
    };
    return EmptyIterator;
}());
exports.EmptyIterator = EmptyIterator;


/***/ }),

/***/ "BmQL":
/*!***************************************************************************!*\
  !*** ./node_modules/react-color/lib/components/swatches/SwatchesColor.js ***!
  \***************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SwatchesColor = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _color = __webpack_require__(/*! ../../helpers/color */ "p8yl");

var _color2 = _interopRequireDefault(_color);

var _common = __webpack_require__(/*! ../common */ "TM95");

var _CheckIcon = __webpack_require__(/*! @icons/material/CheckIcon */ "ql/k");

var _CheckIcon2 = _interopRequireDefault(_CheckIcon);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var SwatchesColor = exports.SwatchesColor = function SwatchesColor(_ref) {
  var color = _ref.color,
      _ref$onClick = _ref.onClick,
      onClick = _ref$onClick === undefined ? function () {} : _ref$onClick,
      onSwatchHover = _ref.onSwatchHover,
      first = _ref.first,
      last = _ref.last,
      active = _ref.active;

  var styles = (0, _reactcss2.default)({
    'default': {
      color: {
        width: '40px',
        height: '24px',
        cursor: 'pointer',
        background: color,
        marginBottom: '1px'
      },
      check: {
        color: _color2.default.getContrastingColor(color),
        marginLeft: '8px',
        display: 'none'
      }
    },
    'first': {
      color: {
        overflow: 'hidden',
        borderRadius: '2px 2px 0 0'
      }
    },
    'last': {
      color: {
        overflow: 'hidden',
        borderRadius: '0 0 2px 2px'
      }
    },
    'active': {
      check: {
        display: 'block'
      }
    },
    'color-#FFFFFF': {
      color: {
        boxShadow: 'inset 0 0 0 1px #ddd'
      },
      check: {
        color: '#333'
      }
    },
    'transparent': {
      check: {
        color: '#333'
      }
    }
  }, {
    first: first,
    last: last,
    active: active,
    'color-#FFFFFF': color === '#FFFFFF',
    'transparent': color === 'transparent'
  });

  return _react2.default.createElement(
    _common.Swatch,
    {
      color: color,
      style: styles.color,
      onClick: onClick,
      onHover: onSwatchHover,
      focusStyle: { boxShadow: '0 0 4px ' + color }
    },
    _react2.default.createElement(
      'div',
      { style: styles.check },
      _react2.default.createElement(_CheckIcon2.default, null)
    )
  );
};

exports.default = SwatchesColor;

/***/ }),

/***/ "BnSx":
/*!***************************************************************************!*\
  !*** ./node_modules/@jupyterlab/markdownviewer-extension/style/index.css ***!
  \***************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "Y6Sv");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "BwZh":
/*!*********************************************!*\
  !*** ./node_modules/vm-browserify/index.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var indexOf = __webpack_require__(/*! indexof */ "7jRU");

var Object_keys = function (obj) {
    if (Object.keys) return Object.keys(obj)
    else {
        var res = [];
        for (var key in obj) res.push(key)
        return res;
    }
};

var forEach = function (xs, fn) {
    if (xs.forEach) return xs.forEach(fn)
    else for (var i = 0; i < xs.length; i++) {
        fn(xs[i], i, xs);
    }
};

var defineProp = (function() {
    try {
        Object.defineProperty({}, '_', {});
        return function(obj, name, value) {
            Object.defineProperty(obj, name, {
                writable: true,
                enumerable: false,
                configurable: true,
                value: value
            })
        };
    } catch(e) {
        return function(obj, name, value) {
            obj[name] = value;
        };
    }
}());

var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function',
'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError',
'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError',
'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape',
'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape'];

function Context() {}
Context.prototype = {};

var Script = exports.Script = function NodeScript (code) {
    if (!(this instanceof Script)) return new Script(code);
    this.code = code;
};

Script.prototype.runInContext = function (context) {
    if (!(context instanceof Context)) {
        throw new TypeError("needs a 'context' argument.");
    }
    
    var iframe = document.createElement('iframe');
    if (!iframe.style) iframe.style = {};
    iframe.style.display = 'none';
    
    document.body.appendChild(iframe);
    
    var win = iframe.contentWindow;
    var wEval = win.eval, wExecScript = win.execScript;

    if (!wEval && wExecScript) {
        // win.eval() magically appears when this is called in IE:
        wExecScript.call(win, 'null');
        wEval = win.eval;
    }
    
    forEach(Object_keys(context), function (key) {
        win[key] = context[key];
    });
    forEach(globals, function (key) {
        if (context[key]) {
            win[key] = context[key];
        }
    });
    
    var winKeys = Object_keys(win);

    var res = wEval.call(win, this.code);
    
    forEach(Object_keys(win), function (key) {
        // Avoid copying circular objects like `top` and `window` by only
        // updating existing context properties or new properties in the `win`
        // that was only introduced after the eval.
        if (key in context || indexOf(winKeys, key) === -1) {
            context[key] = win[key];
        }
    });

    forEach(globals, function (key) {
        if (!(key in context)) {
            defineProp(context, key, win[key]);
        }
    });
    
    document.body.removeChild(iframe);
    
    return res;
};

Script.prototype.runInThisContext = function () {
    return eval(this.code); // maybe...
};

Script.prototype.runInNewContext = function (context) {
    var ctx = Script.createContext(context);
    var res = this.runInContext(ctx);

    forEach(Object_keys(ctx), function (key) {
        context[key] = ctx[key];
    });

    return res;
};

forEach(Object_keys(Script.prototype), function (name) {
    exports[name] = Script[name] = function (code) {
        var s = Script(code);
        return s[name].apply(s, [].slice.call(arguments, 1));
    };
});

exports.createScript = function (code) {
    return exports.Script(code);
};

exports.createContext = Script.createContext = function (context) {
    var copy = new Context();
    if(typeof context === 'object') {
        forEach(Object_keys(context), function (key) {
            copy[key] = context[key];
        });
    }
    return copy;
};


/***/ }),

/***/ "Bx99":
/*!*****************************************************************!*\
  !*** ./node_modules/@jupyterlab/extensionmanager/lib/dialog.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const React = __importStar(__webpack_require__(/*! react */ "q1tI"));
/**
 * Show a dialog box reporting an error during installation of an extension.
 *
 * @param name The name of the extension
 * @param errorMessage Any error message giving details about the failure.
 */
function reportInstallError(name, errorMessage) {
    let entries = [];
    entries.push(React.createElement("p", null,
        "An error occurred installing ",
        React.createElement("code", null, name),
        "."));
    if (errorMessage) {
        entries.push(React.createElement("p", null,
            React.createElement("span", { className: "jp-extensionmanager-dialog-subheader" }, "Error message:")), React.createElement("pre", null, errorMessage.trim()));
    }
    let body = React.createElement("div", { className: "jp-extensionmanager-dialog" }, entries);
    apputils_1.showDialog({
        title: 'Extension Installation Error',
        body,
        buttons: [apputils_1.Dialog.warnButton({ label: 'OK' })]
    });
}
exports.reportInstallError = reportInstallError;


/***/ }),

/***/ "BxQ/":
/*!**********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/FilterOperation.js ***!
  \**********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.FilterValue = exports.FilterOperation = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _Dropdown = __webpack_require__(/*! ../widgets/Dropdown */ "9Rtb");

var _Dropdown2 = _interopRequireDefault(_Dropdown);

var _TextInput = __webpack_require__(/*! ../widgets/TextInput */ "CVbq");

var _TextInput2 = _interopRequireDefault(_TextInput);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var operations = function operations(_) {
  return {
    inequality: [{ value: '!=', label: _('Target ≠ Reference') }, { value: '<', label: _('Target < Reference') }, { value: '<=', label: _('Target ≤ Reference') }, { value: '=', label: _('Target = Reference') }, { value: '>', label: _('Target > Reference') }, { value: '>=', label: _('Target ≥ Reference') }],
    inrange: [{ value: '[]', label: _('Lower ≤ Target ≤ Upper') }, { value: '()', label: _('Lower < Target < Upper') }, { value: '[)', label: _('Lower ≤ Target < Upper') }, { value: '(]', label: _('Lower < Target ≤ Upper') }],
    exrange: [{ value: ')(', label: _('Lower ≤ Target ≤ Upper') }, { value: '][', label: _('Lower < Target < Upper') }, { value: ')[', label: _('Lower ≤ Target < Upper') }, { value: '](', label: _('Lower < Target ≤ Upper') }],
    inset: [{ value: '{}', label: _('Include') }],
    exset: [{ value: '}{', label: _('Exclude') }]
  };
};

var findOperation = function findOperation(operator, _) {
  var op = 'inequality';
  var ops = operations(_);
  for (var key in ops) {
    if (ops.hasOwnProperty(key) && ops[key].map(function (o) {
      return o.value;
    }).indexOf(operator) !== -1) {
      op = key;
      break;
    }
  }
  return op;
};

var UnconnectedFilterOperation = function (_Component) {
  _inherits(UnconnectedFilterOperation, _Component);

  function UnconnectedFilterOperation(props, context) {
    _classCallCheck(this, UnconnectedFilterOperation);

    var _this = _possibleConstructorReturn(this, (UnconnectedFilterOperation.__proto__ || Object.getPrototypeOf(UnconnectedFilterOperation)).call(this, props, context));

    var _ = context.localize;


    _this.state = {
      operation: findOperation(_this.props.fullValue, _),
      operator: operations(_).inequality[0].value
    };

    _this.setOperation = _this.setOperation.bind(_this);
    return _this;
  }

  _createClass(UnconnectedFilterOperation, [{
    key: 'setOperation',
    value: function setOperation(value) {
      var _ = this.context.localize;

      var operator = operations(_)[value][0].value;
      this.setState({ operation: value, operator: operator });
      this.props.updatePlot(operator);
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          fullValue = _props.fullValue,
          updatePlot = _props.updatePlot,
          optionRenderer = _props.optionRenderer,
          valueRenderer = _props.valueRenderer,
          backgroundDark = _props.backgroundDark,
          attr = _props.attr;
      var _ = this.context.localize;


      var operators = [{
        label: _('Inequality'),
        value: 'inequality'
      }, {
        label: _('Include Range'),
        value: 'inrange'
      }, {
        label: _('Exclude Range'),
        value: 'exrange'
      }, {
        label: _('Include Values'),
        value: 'inset'
      }, {
        label: _('Exclude Values'),
        value: 'exset'
      }];

      var opValue = fullValue && fullValue.length > 0 ? fullValue : this.state.operator;
      return _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(
          _Field2.default,
          _extends({}, this.props, { attr: attr }),
          _react2.default.createElement(_Dropdown2.default, {
            backgroundDark: backgroundDark,
            options: operators,
            value: findOperation(opValue, _),
            onChange: this.setOperation,
            clearable: false,
            optionRenderer: optionRenderer,
            valueRenderer: valueRenderer
          }),
          this.state.operation === 'inset' || this.state.operation === 'exset' ? null : _react2.default.createElement(_Dropdown2.default, {
            backgroundDark: backgroundDark,
            options: operations(_)[this.state.operation],
            value: opValue,
            onChange: updatePlot,
            clearable: false,
            optionRenderer: optionRenderer,
            valueRenderer: valueRenderer
          })
        )
      );
    }
  }]);

  return UnconnectedFilterOperation;
}(_react.Component);

UnconnectedFilterOperation.propTypes = _extends({
  fullValue: _propTypes2.default.any,
  updatePlot: _propTypes2.default.func
}, _Field2.default.propTypes);
UnconnectedFilterOperation.contextTypes = {
  localize: _propTypes2.default.func
};

var UnconnectedFilterValue = function (_Component2) {
  _inherits(UnconnectedFilterValue, _Component2);

  function UnconnectedFilterValue(props, context) {
    _classCallCheck(this, UnconnectedFilterValue);

    var _this2 = _possibleConstructorReturn(this, (UnconnectedFilterValue.__proto__ || Object.getPrototypeOf(UnconnectedFilterValue)).call(this, props, context));

    _this2.state = { value: '', valueMax: '' };

    _this2.setValue = _this2.setValue.bind(_this2);
    _this2.setValueMax = _this2.setValueMax.bind(_this2);
    return _this2;
  }

  _createClass(UnconnectedFilterValue, [{
    key: 'setValue',
    value: function setValue(v) {
      var _context = this.context,
          _ = _context.localize,
          container = _context.container;

      var op = findOperation(container.operation, _);
      this.setState({ value: v });
      var val = void 0;
      val = op === 'inrange' || op === 'exrange' ? [v, this.state.valueMax] : v;
      if (op === 'inset' || op === 'exset') {
        val = val.split(',');
        val = val.map(function (v) {
          return v.trim();
        });
      }
      this.props.updatePlot(val);
    }
  }, {
    key: 'setValueMax',
    value: function setValueMax(v) {
      this.setState({ valueMax: v });
      this.props.updatePlot([this.state.value, v]);
    }
  }, {
    key: 'render',
    value: function render() {
      var _context2 = this.context,
          _ = _context2.localize,
          container = _context2.container;


      var operation = container && container.operation ? container.operation : '=';

      var _props2 = this.props,
          fullValue = _props2.fullValue,
          attr = _props2.attr,
          defaultValue = _props2.defaultValue;

      var op = findOperation(operation, _);

      var label1 = _('Reference');
      if (op === 'inrange' || op === 'exrange') {
        label1 = _('Lower Bound');
      } else if (op === 'inset' || op === 'exset') {
        label1 = _('Values');
      }

      var val1 = fullValue;
      if ((op === 'inset' || op === 'exset') && Array.isArray(fullValue)) {
        val1 = fullValue.join(', ');
      } else if (Array.isArray(fullValue)) {
        val1 = fullValue[0];
      }

      return _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(
          _Field2.default,
          _extends({}, this.props, { label: label1 }),
          _react2.default.createElement(_TextInput2.default, { value: val1, defaultValue: val1, onUpdate: this.setValue })
        ),
        !(op === 'inrange' || op === 'exrange') ? null : _react2.default.createElement(
          _Field2.default,
          _extends({}, this.props, { label: _('Upper Bound'), attr: attr }),
          _react2.default.createElement(_TextInput2.default, {
            value: Array.isArray(fullValue) ? fullValue[1] : fullValue,
            defaultValue: defaultValue,
            onUpdate: this.setValueMax
          })
        )
      );
    }
  }]);

  return UnconnectedFilterValue;
}(_react.Component);

UnconnectedFilterValue.propTypes = _extends({
  defaultValue: _propTypes2.default.string,
  fullValue: _propTypes2.default.any,
  updatePlot: _propTypes2.default.func
}, _Field2.default.propTypes);
UnconnectedFilterValue.contextTypes = {
  localize: _propTypes2.default.func,
  container: _propTypes2.default.object
};

var FilterOperation = exports.FilterOperation = (0, _lib.connectToContainer)(UnconnectedFilterOperation);
var FilterValue = exports.FilterValue = (0, _lib.connectToContainer)(UnconnectedFilterValue);
//# sourceMappingURL=FilterOperation.js.map

/***/ }),

/***/ "ByF4":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/fo.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var fo = moment.defineLocale('fo', {
    months : 'januar_februar_mars_apríl_mai_juni_juli_august_september_oktober_november_desember'.split('_'),
    monthsShort : 'jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'),
    weekdays : 'sunnudagur_mánadagur_týsdagur_mikudagur_hósdagur_fríggjadagur_leygardagur'.split('_'),
    weekdaysShort : 'sun_mán_týs_mik_hós_frí_ley'.split('_'),
    weekdaysMin : 'su_má_tý_mi_hó_fr_le'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd D. MMMM, YYYY HH:mm'
    },
    calendar : {
        sameDay : '[Í dag kl.] LT',
        nextDay : '[Í morgin kl.] LT',
        nextWeek : 'dddd [kl.] LT',
        lastDay : '[Í gjár kl.] LT',
        lastWeek : '[síðstu] dddd [kl] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'um %s',
        past : '%s síðani',
        s : 'fá sekund',
        ss : '%d sekundir',
        m : 'ein minutt',
        mm : '%d minuttir',
        h : 'ein tími',
        hh : '%d tímar',
        d : 'ein dagur',
        dd : '%d dagar',
        M : 'ein mánaði',
        MM : '%d mánaðir',
        y : 'eitt ár',
        yy : '%d ár'
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return fo;

})));


/***/ }),

/***/ "BzXa":
/*!**************************************************************!*\
  !*** ./node_modules/jupyterlab-chart-editor/style/index.css ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../css-loader!./index.css */ "p0j+");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "C+gy":
/*!**********************************************!*\
  !*** ./node_modules/browserify-des/modes.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

exports['des-ecb'] = {
  key: 8,
  iv: 0
}
exports['des-cbc'] = exports.des = {
  key: 8,
  iv: 8
}
exports['des-ede3-cbc'] = exports.des3 = {
  key: 24,
  iv: 8
}
exports['des-ede3'] = {
  key: 24,
  iv: 0
}
exports['des-ede-cbc'] = {
  key: 16,
  iv: 8
}
exports['des-ede'] = {
  key: 16,
  iv: 0
}


/***/ }),

/***/ "C26z":
/*!********************************************!*\
  !*** ./node_modules/base16/lib/paraiso.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'paraiso',
  author: 'jan t. sott',
  base00: '#2f1e2e',
  base01: '#41323f',
  base02: '#4f424c',
  base03: '#776e71',
  base04: '#8d8687',
  base05: '#a39e9b',
  base06: '#b9b6b0',
  base07: '#e7e9db',
  base08: '#ef6155',
  base09: '#f99b15',
  base0A: '#fec418',
  base0B: '#48b685',
  base0C: '#5bc4bf',
  base0D: '#06b6ef',
  base0E: '#815ba4',
  base0F: '#e96ba8'
};
module.exports = exports['default'];

/***/ }),

/***/ "C2zF":
/*!********************************************************!*\
  !*** ./node_modules/codemirror/addon/search/search.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

// Define search commands. Depends on dialog.js or another
// implementation of the openDialog method.

// Replace works a little oddly -- it will do the replace on the next
// Ctrl-G (or whatever is bound to findNext) press. You prevent a
// replace by making sure the match is no longer selected when hitting
// Ctrl-G.

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"), __webpack_require__(/*! ./searchcursor */ "uTOq"), __webpack_require__(/*! ../dialog/dialog */ "Ku0u"));
  else {}
})(function(CodeMirror) {
  "use strict";

  function searchOverlay(query, caseInsensitive) {
    if (typeof query == "string")
      query = new RegExp(query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), caseInsensitive ? "gi" : "g");
    else if (!query.global)
      query = new RegExp(query.source, query.ignoreCase ? "gi" : "g");

    return {token: function(stream) {
      query.lastIndex = stream.pos;
      var match = query.exec(stream.string);
      if (match && match.index == stream.pos) {
        stream.pos += match[0].length || 1;
        return "searching";
      } else if (match) {
        stream.pos = match.index;
      } else {
        stream.skipToEnd();
      }
    }};
  }

  function SearchState() {
    this.posFrom = this.posTo = this.lastQuery = this.query = null;
    this.overlay = null;
  }

  function getSearchState(cm) {
    return cm.state.search || (cm.state.search = new SearchState());
  }

  function queryCaseInsensitive(query) {
    return typeof query == "string" && query == query.toLowerCase();
  }

  function getSearchCursor(cm, query, pos) {
    // Heuristic: if the query string is all lowercase, do a case insensitive search.
    return cm.getSearchCursor(query, pos, {caseFold: queryCaseInsensitive(query), multiline: true});
  }

  function persistentDialog(cm, text, deflt, onEnter, onKeyDown) {
    cm.openDialog(text, onEnter, {
      value: deflt,
      selectValueOnOpen: true,
      closeOnEnter: false,
      onClose: function() { clearSearch(cm); },
      onKeyDown: onKeyDown
    });
  }

  function dialog(cm, text, shortText, deflt, f) {
    if (cm.openDialog) cm.openDialog(text, f, {value: deflt, selectValueOnOpen: true});
    else f(prompt(shortText, deflt));
  }

  function confirmDialog(cm, text, shortText, fs) {
    if (cm.openConfirm) cm.openConfirm(text, fs);
    else if (confirm(shortText)) fs[0]();
  }

  function parseString(string) {
    return string.replace(/\\(.)/g, function(_, ch) {
      if (ch == "n") return "\n"
      if (ch == "r") return "\r"
      return ch
    })
  }

  function parseQuery(query) {
    var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
    if (isRE) {
      try { query = new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i"); }
      catch(e) {} // Not a regular expression after all, do a string search
    } else {
      query = parseString(query)
    }
    if (typeof query == "string" ? query == "" : query.test(""))
      query = /x^/;
    return query;
  }

  var queryDialog =
    '<span class="CodeMirror-search-label">Search:</span> <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">(Use /re/ syntax for regexp search)</span>';

  function startSearch(cm, state, query) {
    state.queryText = query;
    state.query = parseQuery(query);
    cm.removeOverlay(state.overlay, queryCaseInsensitive(state.query));
    state.overlay = searchOverlay(state.query, queryCaseInsensitive(state.query));
    cm.addOverlay(state.overlay);
    if (cm.showMatchesOnScrollbar) {
      if (state.annotate) { state.annotate.clear(); state.annotate = null; }
      state.annotate = cm.showMatchesOnScrollbar(state.query, queryCaseInsensitive(state.query));
    }
  }

  function doSearch(cm, rev, persistent, immediate) {
    var state = getSearchState(cm);
    if (state.query) return findNext(cm, rev);
    var q = cm.getSelection() || state.lastQuery;
    if (q instanceof RegExp && q.source == "x^") q = null
    if (persistent && cm.openDialog) {
      var hiding = null
      var searchNext = function(query, event) {
        CodeMirror.e_stop(event);
        if (!query) return;
        if (query != state.queryText) {
          startSearch(cm, state, query);
          state.posFrom = state.posTo = cm.getCursor();
        }
        if (hiding) hiding.style.opacity = 1
        findNext(cm, event.shiftKey, function(_, to) {
          var dialog
          if (to.line < 3 && document.querySelector &&
              (dialog = cm.display.wrapper.querySelector(".CodeMirror-dialog")) &&
              dialog.getBoundingClientRect().bottom - 4 > cm.cursorCoords(to, "window").top)
            (hiding = dialog).style.opacity = .4
        })
      };
      persistentDialog(cm, queryDialog, q, searchNext, function(event, query) {
        var keyName = CodeMirror.keyName(event)
        var extra = cm.getOption('extraKeys'), cmd = (extra && extra[keyName]) || CodeMirror.keyMap[cm.getOption("keyMap")][keyName]
        if (cmd == "findNext" || cmd == "findPrev" ||
          cmd == "findPersistentNext" || cmd == "findPersistentPrev") {
          CodeMirror.e_stop(event);
          startSearch(cm, getSearchState(cm), query);
          cm.execCommand(cmd);
        } else if (cmd == "find" || cmd == "findPersistent") {
          CodeMirror.e_stop(event);
          searchNext(query, event);
        }
      });
      if (immediate && q) {
        startSearch(cm, state, q);
        findNext(cm, rev);
      }
    } else {
      dialog(cm, queryDialog, "Search for:", q, function(query) {
        if (query && !state.query) cm.operation(function() {
          startSearch(cm, state, query);
          state.posFrom = state.posTo = cm.getCursor();
          findNext(cm, rev);
        });
      });
    }
  }

  function findNext(cm, rev, callback) {cm.operation(function() {
    var state = getSearchState(cm);
    var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo);
    if (!cursor.find(rev)) {
      cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0));
      if (!cursor.find(rev)) return;
    }
    cm.setSelection(cursor.from(), cursor.to());
    cm.scrollIntoView({from: cursor.from(), to: cursor.to()}, 20);
    state.posFrom = cursor.from(); state.posTo = cursor.to();
    if (callback) callback(cursor.from(), cursor.to())
  });}

  function clearSearch(cm) {cm.operation(function() {
    var state = getSearchState(cm);
    state.lastQuery = state.query;
    if (!state.query) return;
    state.query = state.queryText = null;
    cm.removeOverlay(state.overlay);
    if (state.annotate) { state.annotate.clear(); state.annotate = null; }
  });}

  var replaceQueryDialog =
    ' <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">(Use /re/ syntax for regexp search)</span>';
  var replacementQueryDialog = '<span class="CodeMirror-search-label">With:</span> <input type="text" style="width: 10em" class="CodeMirror-search-field"/>';
  var doReplaceConfirm = '<span class="CodeMirror-search-label">Replace?</span> <button>Yes</button> <button>No</button> <button>All</button> <button>Stop</button>';

  function replaceAll(cm, query, text) {
    cm.operation(function() {
      for (var cursor = getSearchCursor(cm, query); cursor.findNext();) {
        if (typeof query != "string") {
          var match = cm.getRange(cursor.from(), cursor.to()).match(query);
          cursor.replace(text.replace(/\$(\d)/g, function(_, i) {return match[i];}));
        } else cursor.replace(text);
      }
    });
  }

  function replace(cm, all) {
    if (cm.getOption("readOnly")) return;
    var query = cm.getSelection() || getSearchState(cm).lastQuery;
    var dialogText = '<span class="CodeMirror-search-label">' + (all ? 'Replace all:' : 'Replace:') + '</span>';
    dialog(cm, dialogText + replaceQueryDialog, dialogText, query, function(query) {
      if (!query) return;
      query = parseQuery(query);
      dialog(cm, replacementQueryDialog, "Replace with:", "", function(text) {
        text = parseString(text)
        if (all) {
          replaceAll(cm, query, text)
        } else {
          clearSearch(cm);
          var cursor = getSearchCursor(cm, query, cm.getCursor("from"));
          var advance = function() {
            var start = cursor.from(), match;
            if (!(match = cursor.findNext())) {
              cursor = getSearchCursor(cm, query);
              if (!(match = cursor.findNext()) ||
                  (start && cursor.from().line == start.line && cursor.from().ch == start.ch)) return;
            }
            cm.setSelection(cursor.from(), cursor.to());
            cm.scrollIntoView({from: cursor.from(), to: cursor.to()});
            confirmDialog(cm, doReplaceConfirm, "Replace?",
                          [function() {doReplace(match);}, advance,
                           function() {replaceAll(cm, query, text)}]);
          };
          var doReplace = function(match) {
            cursor.replace(typeof query == "string" ? text :
                           text.replace(/\$(\d)/g, function(_, i) {return match[i];}));
            advance();
          };
          advance();
        }
      });
    });
  }

  CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);};
  CodeMirror.commands.findPersistent = function(cm) {clearSearch(cm); doSearch(cm, false, true);};
  CodeMirror.commands.findPersistentNext = function(cm) {doSearch(cm, false, true, true);};
  CodeMirror.commands.findPersistentPrev = function(cm) {doSearch(cm, true, true, true);};
  CodeMirror.commands.findNext = doSearch;
  CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);};
  CodeMirror.commands.clearSearch = clearSearch;
  CodeMirror.commands.replace = replace;
  CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);};
});


/***/ }),

/***/ "C6sy":
/*!***********************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/text_editors/convertFormats.js ***!
  \***********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var getTextBlockRegExp = function getTextBlockRegExp() {
  return (/\\text\{([^}]*)}/g
  );
};

/**
 * To match any character including newline whitespace, use `[\s\S]*`
 * instead of `.*`. http://stackoverflow.com/a/1068308
 *
 * @returns {RegExp} the regular expression
 */
var getLaTeXWrappedRegExp = function getLaTeXWrappedRegExp() {
  return (/^\$[\s\S]*\$$/
  );
};

var stripHTMLTags = function stripHTMLTags(html) {
  return html.replace(/<[^>]*>/g, '').trim();
};

var extractTextBlocks = function extractTextBlocks(laTeX) {
  var matchObj = void 0;
  var matchStr = void 0;
  var matches = [];

  // Need to stringify to match literally on `\t`.
  var stringifiedLaTeX = JSON.stringify(laTeX);
  var regExp = getTextBlockRegExp();

  /**
   * Find multiple matches with the ``//g` flag.
   * The `RegExp.prototype.exec` API mutates the RegExp object.
   * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec#Finding_successive_matches
   */
  while ((matchObj = regExp.exec(stringifiedLaTeX)) !== null) {
    matchStr = matchObj[1].trim().replace('\\n', '');
    matches.push(matchStr);
  }

  return matches.join('<br>');
};

var wrapLaTeX = function wrapLaTeX(value) {
  return value ? '$' + value + '$' : '$$';
};

var wrapText = function wrapText(value) {
  return value ? '\\text{' + value + '}' : '\\text{}';
};

// Exports
// -------

var isLaTeXExpr = exports.isLaTeXExpr = function isLaTeXExpr(value) {
  return getLaTeXWrappedRegExp().test(value);
};

var hasTextExpression = exports.hasTextExpression = function hasTextExpression(laTeX) {
  var regExp = getTextBlockRegExp();
  var stringifiedLaTeX = JSON.stringify(laTeX);

  return regExp.test(stringifiedLaTeX);
};

var htmlToLaTeX = exports.htmlToLaTeX = function htmlToLaTeX(html) {
  var breakTag = '<br>';
  var trimmedHTML = html.trim();

  // Handle empty input
  if (trimmedHTML === '') {
    return wrapLaTeX(wrapText());
  }

  // Handle input with only linebreaks
  if (trimmedHTML.replace(breakTag, '') === '') {
    return wrapLaTeX(wrapText());
  }

  return wrapLaTeX(trimmedHTML.split(breakTag)

  // Ignore empty linebreaks
  .map(function (para) {
    return para.length ? wrapText(stripHTMLTags(para)) : '';
  }).join('\n'));
};

var laTeXToHTML = exports.laTeXToHTML = function laTeXToHTML(laTeX) {
  var trimmedLaTeX = laTeX.trim();

  return extractTextBlocks(trimmedLaTeX);
};
//# sourceMappingURL=convertFormats.js.map

/***/ }),

/***/ "C9ER":
/*!****************************************************!*\
  !*** ./node_modules/draft-js/lib/editOnKeyDown.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule editOnKeyDown
 * @format
 * 
 */



var DraftModifier = __webpack_require__(/*! ./DraftModifier */ "fyOY");
var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");
var KeyBindingUtil = __webpack_require__(/*! ./KeyBindingUtil */ "s8ra");
var Keys = __webpack_require__(/*! fbjs/lib/Keys */ "7wDu");
var SecondaryClipboard = __webpack_require__(/*! ./SecondaryClipboard */ "Wkzk");
var UserAgent = __webpack_require__(/*! fbjs/lib/UserAgent */ "CYTE");

var isEventHandled = __webpack_require__(/*! ./isEventHandled */ "T401");
var keyCommandBackspaceToStartOfLine = __webpack_require__(/*! ./keyCommandBackspaceToStartOfLine */ "HEBY");
var keyCommandBackspaceWord = __webpack_require__(/*! ./keyCommandBackspaceWord */ "vcNX");
var keyCommandDeleteWord = __webpack_require__(/*! ./keyCommandDeleteWord */ "YUem");
var keyCommandInsertNewline = __webpack_require__(/*! ./keyCommandInsertNewline */ "MPKC");
var keyCommandMoveSelectionToEndOfBlock = __webpack_require__(/*! ./keyCommandMoveSelectionToEndOfBlock */ "0RQb");
var keyCommandMoveSelectionToStartOfBlock = __webpack_require__(/*! ./keyCommandMoveSelectionToStartOfBlock */ "ujuU");
var keyCommandPlainBackspace = __webpack_require__(/*! ./keyCommandPlainBackspace */ "3Br+");
var keyCommandPlainDelete = __webpack_require__(/*! ./keyCommandPlainDelete */ "tuJh");
var keyCommandTransposeCharacters = __webpack_require__(/*! ./keyCommandTransposeCharacters */ "ocgx");
var keyCommandUndo = __webpack_require__(/*! ./keyCommandUndo */ "SYhp");

var isOptionKeyCommand = KeyBindingUtil.isOptionKeyCommand;

var isChrome = UserAgent.isBrowser('Chrome');

/**
 * Map a `DraftEditorCommand` command value to a corresponding function.
 */
function onKeyCommand(command, editorState) {
  switch (command) {
    case 'redo':
      return EditorState.redo(editorState);
    case 'delete':
      return keyCommandPlainDelete(editorState);
    case 'delete-word':
      return keyCommandDeleteWord(editorState);
    case 'backspace':
      return keyCommandPlainBackspace(editorState);
    case 'backspace-word':
      return keyCommandBackspaceWord(editorState);
    case 'backspace-to-start-of-line':
      return keyCommandBackspaceToStartOfLine(editorState);
    case 'split-block':
      return keyCommandInsertNewline(editorState);
    case 'transpose-characters':
      return keyCommandTransposeCharacters(editorState);
    case 'move-selection-to-start-of-block':
      return keyCommandMoveSelectionToStartOfBlock(editorState);
    case 'move-selection-to-end-of-block':
      return keyCommandMoveSelectionToEndOfBlock(editorState);
    case 'secondary-cut':
      return SecondaryClipboard.cut(editorState);
    case 'secondary-paste':
      return SecondaryClipboard.paste(editorState);
    default:
      return editorState;
  }
}

/**
 * Intercept keydown behavior to handle keys and commands manually, if desired.
 *
 * Keydown combinations may be mapped to `DraftCommand` values, which may
 * correspond to command functions that modify the editor or its contents.
 *
 * See `getDefaultKeyBinding` for defaults. Alternatively, the top-level
 * component may provide a custom mapping via the `keyBindingFn` prop.
 */
function editOnKeyDown(editor, e) {
  var keyCode = e.which;
  var editorState = editor._latestEditorState;

  switch (keyCode) {
    case Keys.RETURN:
      e.preventDefault();
      // The top-level component may manually handle newline insertion. If
      // no special handling is performed, fall through to command handling.
      if (editor.props.handleReturn && isEventHandled(editor.props.handleReturn(e, editorState))) {
        return;
      }
      break;
    case Keys.ESC:
      e.preventDefault();
      editor.props.onEscape && editor.props.onEscape(e);
      return;
    case Keys.TAB:
      editor.props.onTab && editor.props.onTab(e);
      return;
    case Keys.UP:
      editor.props.onUpArrow && editor.props.onUpArrow(e);
      return;
    case Keys.RIGHT:
      editor.props.onRightArrow && editor.props.onRightArrow(e);
      return;
    case Keys.DOWN:
      editor.props.onDownArrow && editor.props.onDownArrow(e);
      return;
    case Keys.LEFT:
      editor.props.onLeftArrow && editor.props.onLeftArrow(e);
      return;
    case Keys.SPACE:
      // Handling for OSX where option + space scrolls.
      if (isChrome && isOptionKeyCommand(e)) {
        e.preventDefault();
        // Insert a nbsp into the editor.
        var contentState = DraftModifier.replaceText(editorState.getCurrentContent(), editorState.getSelection(), '\xA0');
        editor.update(EditorState.push(editorState, contentState, 'insert-characters'));
        return;
      }
  }

  var command = editor.props.keyBindingFn(e);

  // If no command is specified, allow keydown event to continue.
  if (!command) {
    return;
  }

  if (command === 'undo') {
    // Since undo requires some special updating behavior to keep the editor
    // in sync, handle it separately.
    keyCommandUndo(e, editorState, editor.update);
    return;
  }

  // At this point, we know that we're handling a command of some kind, so
  // we don't want to insert a character following the keydown.
  e.preventDefault();

  // Allow components higher up the tree to handle the command first.
  if (editor.props.handleKeyCommand && isEventHandled(editor.props.handleKeyCommand(command, editorState))) {
    return;
  }

  var newState = onKeyCommand(command, editorState);
  if (newState !== editorState) {
    editor.update(newState);
  }
}

module.exports = editOnKeyDown;

/***/ }),

/***/ "CH3K":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_arrayPush.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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;
}

module.exports = arrayPush;


/***/ }),

/***/ "CH9F":
/*!************************************!*\
  !*** ./node_modules/sha.js/sha.js ***!
  \************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/*
 * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
 * in FIPS PUB 180-1
 * This source code is derived from sha1.js of the same repository.
 * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
 * operation was added.
 */

var inherits = __webpack_require__(/*! inherits */ "P7XM")
var Hash = __webpack_require__(/*! ./hash */ "tnIz")
var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer

var K = [
  0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
]

var W = new Array(80)

function Sha () {
  this.init()
  this._w = W

  Hash.call(this, 64, 56)
}

inherits(Sha, Hash)

Sha.prototype.init = function () {
  this._a = 0x67452301
  this._b = 0xefcdab89
  this._c = 0x98badcfe
  this._d = 0x10325476
  this._e = 0xc3d2e1f0

  return this
}

function rotl5 (num) {
  return (num << 5) | (num >>> 27)
}

function rotl30 (num) {
  return (num << 30) | (num >>> 2)
}

function ft (s, b, c, d) {
  if (s === 0) return (b & c) | ((~b) & d)
  if (s === 2) return (b & c) | (b & d) | (c & d)
  return b ^ c ^ d
}

Sha.prototype._update = function (M) {
  var W = this._w

  var a = this._a | 0
  var b = this._b | 0
  var c = this._c | 0
  var d = this._d | 0
  var e = this._e | 0

  for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
  for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]

  for (var j = 0; j < 80; ++j) {
    var s = ~~(j / 20)
    var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0

    e = d
    d = c
    c = rotl30(b)
    b = a
    a = t
  }

  this._a = (a + this._a) | 0
  this._b = (b + this._b) | 0
  this._c = (c + this._c) | 0
  this._d = (d + this._d) | 0
  this._e = (e + this._e) | 0
}

Sha.prototype._hash = function () {
  var H = Buffer.allocUnsafe(20)

  H.writeInt32BE(this._a | 0, 0)
  H.writeInt32BE(this._b | 0, 4)
  H.writeInt32BE(this._c | 0, 8)
  H.writeInt32BE(this._d | 0, 12)
  H.writeInt32BE(this._e | 0, 16)

  return H
}

module.exports = Sha


/***/ }),

/***/ "CJXx":
/*!************************************************************!*\
  !*** ./node_modules/draft-js/lib/DraftEditorLeaf.react.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DraftEditorLeaf.react
 * @format
 * 
 */



var _assign = __webpack_require__(/*! object-assign */ "MgzW");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var DraftEditorTextNode = __webpack_require__(/*! ./DraftEditorTextNode.react */ "WLG0");
var React = __webpack_require__(/*! react */ "q1tI");
var ReactDOM = __webpack_require__(/*! react-dom */ "i8i4");

var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");
var setDraftEditorSelection = __webpack_require__(/*! ./setDraftEditorSelection */ "O4zn");

/**
 * All leaf nodes in the editor are spans with single text nodes. Leaf
 * elements are styled based on the merging of an optional custom style map
 * and a default style map.
 *
 * `DraftEditorLeaf` also provides a wrapper for calling into the imperative
 * DOM Selection API. In this way, top-level components can declaratively
 * maintain the selection state.
 */
var DraftEditorLeaf = function (_React$Component) {
  _inherits(DraftEditorLeaf, _React$Component);

  function DraftEditorLeaf() {
    _classCallCheck(this, DraftEditorLeaf);

    return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
  }

  DraftEditorLeaf.prototype._setSelection = function _setSelection() {
    var selection = this.props.selection;

    // If selection state is irrelevant to the parent block, no-op.

    if (selection == null || !selection.getHasFocus()) {
      return;
    }

    var _props = this.props,
        block = _props.block,
        start = _props.start,
        text = _props.text;

    var blockKey = block.getKey();
    var end = start + text.length;
    if (!selection.hasEdgeWithin(blockKey, start, end)) {
      return;
    }

    // Determine the appropriate target node for selection. If the child
    // is not a text node, it is a <br /> spacer. In this case, use the
    // <span> itself as the selection target.
    var node = ReactDOM.findDOMNode(this);
    !node ?  true ? invariant(false, 'Missing node') : undefined : void 0;
    var child = node.firstChild;
    !child ?  true ? invariant(false, 'Missing child') : undefined : void 0;
    var targetNode = void 0;

    if (child.nodeType === Node.TEXT_NODE) {
      targetNode = child;
    } else if (child.tagName === 'BR') {
      targetNode = node;
    } else {
      targetNode = child.firstChild;
      !targetNode ?  true ? invariant(false, 'Missing targetNode') : undefined : void 0;
    }

    setDraftEditorSelection(selection, targetNode, blockKey, start, end);
  };
  /**
   * By making individual leaf instances aware of their context within
   * the text of the editor, we can set our selection range more
   * easily than we could in the non-React world.
   *
   * Note that this depends on our maintaining tight control over the
   * DOM structure of the DraftEditor component. If leaves had multiple
   * text nodes, this would be harder.
   */

  DraftEditorLeaf.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
    var leafNode = ReactDOM.findDOMNode(this.leaf);
    !leafNode ?  true ? invariant(false, 'Missing leafNode') : undefined : void 0;
    return leafNode.textContent !== nextProps.text || nextProps.styleSet !== this.props.styleSet || nextProps.forceSelection;
  };

  DraftEditorLeaf.prototype.componentDidUpdate = function componentDidUpdate() {
    this._setSelection();
  };

  DraftEditorLeaf.prototype.componentDidMount = function componentDidMount() {
    this._setSelection();
  };

  DraftEditorLeaf.prototype.render = function render() {
    var _this2 = this;

    var block = this.props.block;
    var text = this.props.text;

    // If the leaf is at the end of its block and ends in a soft newline, append
    // an extra line feed character. Browsers collapse trailing newline
    // characters, which leaves the cursor in the wrong place after a
    // shift+enter. The extra character repairs this.

    if (text.endsWith('\n') && this.props.isLast) {
      text += '\n';
    }

    var _props2 = this.props,
        customStyleMap = _props2.customStyleMap,
        customStyleFn = _props2.customStyleFn,
        offsetKey = _props2.offsetKey,
        styleSet = _props2.styleSet;

    var styleObj = styleSet.reduce(function (map, styleName) {
      var mergedStyles = {};
      var style = customStyleMap[styleName];

      if (style !== undefined && map.textDecoration !== style.textDecoration) {
        // .trim() is necessary for IE9/10/11 and Edge
        mergedStyles.textDecoration = [map.textDecoration, style.textDecoration].join(' ').trim();
      }

      return _assign(map, style, mergedStyles);
    }, {});

    if (customStyleFn) {
      var newStyles = customStyleFn(styleSet, block);
      styleObj = _assign(styleObj, newStyles);
    }

    return React.createElement(
      'span',
      {
        'data-offset-key': offsetKey,
        ref: function ref(_ref) {
          return _this2.leaf = _ref;
        },
        style: styleObj },
      React.createElement(
        DraftEditorTextNode,
        null,
        text
      )
    );
  };

  return DraftEditorLeaf;
}(React.Component);

module.exports = DraftEditorLeaf;

/***/ }),

/***/ "CMye":
/*!****************************************************!*\
  !*** ./node_modules/lodash/_isStrictComparable.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isObject = __webpack_require__(/*! ./isObject */ "GoyQ");

/**
 * 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);
}

module.exports = isStrictComparable;


/***/ }),

/***/ "CPRm":
/*!***********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotScatter3dIcon.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotScatter3dIcon = function PlotScatter3dIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M17.313 5.313h-2.625v8L0 18.688l16 8 16-8-14.688-5.375zM9 20a1.68 1.68 0 0 1-1.688-1.688c0-.875.75-1.625 1.688-1.625s1.688.75 1.688 1.625A1.68 1.68 0 0 1 9 20zm6.688 4.688C14.75 24.688 14 23.938 14 23s.75-1.688 1.688-1.688c.875 0 1.625.75 1.625 1.688s-.75 1.688-1.625 1.688zm8-7.375c.875 0 1.625.75 1.625 1.688s-.75 1.688-1.625 1.688c-.938 0-1.688-.75-1.688-1.688s.75-1.688 1.688-1.688zm-5-1c0 .938-.75 1.688-1.688 1.688s-1.688-.75-1.688-1.688c0-.875.75-1.625 1.688-1.625s1.688.75 1.688 1.625zM5.313 7c0 .938-.75 1.688-1.625 1.688C2.75 8.688 2 7.938 2 7s.75-1.688 1.688-1.688c.875 0 1.625.75 1.625 1.688zM12 11.688c0 .875-.75 1.625-1.688 1.625-.875 0-1.625-.75-1.625-1.625 0-.938.75-1.688 1.625-1.688.938 0 1.688.75 1.688 1.688zm-8.687 2c0 .875-.75 1.625-1.625 1.625-.938 0-1.688-.75-1.688-1.625C0 12.75.75 12 1.688 12c.875 0 1.625.75 1.625 1.688zm26.687 0c0 .875-.75 1.625-1.688 1.625-.875 0-1.625-.75-1.625-1.625 0-.938.75-1.688 1.625-1.688.938 0 1.688.75 1.688 1.688zM23.313 9c0 .938-.75 1.688-1.625 1.688C20.75 10.688 20 9.938 20 9s.75-1.688 1.688-1.688c.875 0 1.625.75 1.625 1.688zM32 7a1.68 1.68 0 0 1-1.688 1.688c-.875 0-1.625-.75-1.625-1.688s.75-1.688 1.625-1.688C31.25 5.312 32 6.062 32 7z' })
    );
};

exports.default = PlotScatter3dIcon;

/***/ }),

/***/ "CQ7X":
/*!***********************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/Text.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UnconnectedText = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _TextInput = __webpack_require__(/*! ../widgets/TextInput */ "CVbq");

var _TextInput2 = _interopRequireDefault(_TextInput);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UnconnectedText = exports.UnconnectedText = function (_Component) {
  _inherits(UnconnectedText, _Component);

  function UnconnectedText() {
    _classCallCheck(this, UnconnectedText);

    return _possibleConstructorReturn(this, (UnconnectedText.__proto__ || Object.getPrototypeOf(UnconnectedText)).apply(this, arguments));
  }

  _createClass(UnconnectedText, [{
    key: 'render',
    value: function render() {
      var fullValue = this.props.fullValue;
      var placeholder = void 0;
      if (this.props.multiValued) {
        placeholder = fullValue;
        fullValue = '';
      }

      return _react2.default.createElement(
        _Field2.default,
        this.props,
        _react2.default.createElement(_TextInput2.default, {
          value: fullValue,
          defaultValue: this.props.defaultValue,
          placeholder: placeholder,
          onUpdate: this.props.updatePlot,
          onChange: this.props.onChange
        })
      );
    }
  }]);

  return UnconnectedText;
}(_react.Component);

UnconnectedText.propTypes = _extends({
  defaultValue: _propTypes2.default.any,
  fullValue: _propTypes2.default.any,
  multiValued: _propTypes2.default.bool,
  updatePlot: _propTypes2.default.func,
  onChange: _propTypes2.default.func
}, _Field2.default.propTypes);

exports.default = (0, _lib.connectToContainer)(UnconnectedText);
//# sourceMappingURL=Text.js.map

/***/ }),

/***/ "CUWc":
/*!*********************************************!*\
  !*** ./node_modules/mdi-react/CloudIcon.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var CloudIcon = function CloudIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M19.35,10.03C18.67,6.59 15.64,4 12,4C9.11,4 6.6,5.64 5.35,8.03C2.34,8.36 0,10.9 0,14C0,17.31 2.69,20 6,20H19C21.76,20 24,17.76 24,15C24,12.36 21.95,10.22 19.35,10.03Z' })
  );
};

module.exports = CloudIcon;


/***/ }),

/***/ "CVbq":
/*!*****************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/TextInput.js ***!
  \*****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _EditableText = __webpack_require__(/*! ./EditableText */ "Q/qy");

var _EditableText2 = _interopRequireDefault(_EditableText);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var TextInput = function (_Component) {
  _inherits(TextInput, _Component);

  function TextInput(props) {
    _classCallCheck(this, TextInput);

    var _this = _possibleConstructorReturn(this, (TextInput.__proto__ || Object.getPrototypeOf(TextInput)).call(this, props));

    _this.state = { value: props.value };
    return _this;
  }

  _createClass(TextInput, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      if (nextProps.value !== this.state.value) {
        this.setState({ value: nextProps.value });
      }
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      return _react2.default.createElement(_EditableText2.default, {
        className: 'text-input ' + (this.props.editableClassName ? this.props.editableClassName : ''),
        placeholder: this.props.placeholder,
        text: this.state.value,
        type: 'text',
        onChange: function onChange(value) {
          if (_this2.props.onChange) {
            _this2.props.onChange(value);
          }
          _this2.setState({ value: value });
        },
        onUpdate: this.props.onUpdate
      });
    }
  }]);

  return TextInput;
}(_react.Component);

exports.default = TextInput;


TextInput.propTypes = {
  defaultValue: _propTypes2.default.any,
  editableClassName: _propTypes2.default.string,
  onUpdate: _propTypes2.default.func.isRequired,
  onChange: _propTypes2.default.func,
  placeholder: _propTypes2.default.string,
  value: _propTypes2.default.any
};
//# sourceMappingURL=TextInput.js.map

/***/ }),

/***/ "CVh7":
/*!********************************************************!*\
  !*** ./node_modules/@phosphor/algorithm/lib/repeat.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/**
 * Create an iterator which repeats a value a number of times.
 *
 * @param value - The value to repeat.
 *
 * @param count - The number of times to repeat the value.
 *
 * @returns A new iterator which repeats the specified value.
 *
 * #### Example
 * ```typescript
 * import { repeat, toArray } from '@phosphor/algorithm';
 *
 * let stream = repeat(7, 3);
 *
 * toArray(stream);  // [7, 7, 7]
 * ```
 */
function repeat(value, count) {
    return new RepeatIterator(value, count);
}
exports.repeat = repeat;
/**
 * Create an iterator which yields a value a single time.
 *
 * @param value - The value to wrap in an iterator.
 *
 * @returns A new iterator which yields the value a single time.
 *
 * #### Example
 * ```typescript
 * import { once, toArray } from '@phosphor/algorithm';
 *
 * let stream = once(7);
 *
 * toArray(stream);  // [7]
 * ```
 */
function once(value) {
    return new RepeatIterator(value, 1);
}
exports.once = once;
/**
 * An iterator which repeats a value a specified number of times.
 */
var RepeatIterator = (function () {
    /**
     * Construct a new repeat iterator.
     *
     * @param value - The value to repeat.
     *
     * @param count - The number of times to repeat the value.
     */
    function RepeatIterator(value, count) {
        this._value = value;
        this._count = count;
    }
    /**
     * Get an iterator over the object's values.
     *
     * @returns An iterator which yields the object's values.
     */
    RepeatIterator.prototype.iter = function () {
        return this;
    };
    /**
     * Create an independent clone of the iterator.
     *
     * @returns A new independent clone of the iterator.
     */
    RepeatIterator.prototype.clone = function () {
        return new RepeatIterator(this._value, this._count);
    };
    /**
     * Get the next value from the iterator.
     *
     * @returns The next value from the iterator, or `undefined`.
     */
    RepeatIterator.prototype.next = function () {
        if (this._count <= 0) {
            return undefined;
        }
        this._count--;
        return this._value;
    };
    return RepeatIterator;
}());
exports.RepeatIterator = RepeatIterator;


/***/ }),

/***/ "CWBI":
/*!********************************************************!*\
  !*** ./node_modules/readable-stream/duplex-browser.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(/*! ./lib/_stream_duplex.js */ "sZro");


/***/ }),

/***/ "CYTE":
/*!********************************************!*\
  !*** ./node_modules/fbjs/lib/UserAgent.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */



var UserAgentData = __webpack_require__(/*! ./UserAgentData */ "KL9H");
var VersionRange = __webpack_require__(/*! ./VersionRange */ "QfTi");

var mapObject = __webpack_require__(/*! ./mapObject */ "bd9B");
var memoizeStringOnly = __webpack_require__(/*! ./memoizeStringOnly */ "rWXM");

/**
 * Checks to see whether `name` and `version` satisfy `query`.
 *
 * @param {string} name Name of the browser, device, engine or platform
 * @param {?string} version Version of the browser, engine or platform
 * @param {string} query Query of form "Name [range expression]"
 * @param {?function} normalizer Optional pre-processor for range expression
 * @return {boolean}
 */
function compare(name, version, query, normalizer) {
  // check for exact match with no version
  if (name === query) {
    return true;
  }

  // check for non-matching names
  if (!query.startsWith(name)) {
    return false;
  }

  // full comparison with version
  var range = query.slice(name.length);
  if (version) {
    range = normalizer ? normalizer(range) : range;
    return VersionRange.contains(range, version);
  }

  return false;
}

/**
 * Normalizes `version` by stripping any "NT" prefix, but only on the Windows
 * platform.
 *
 * Mimics the stripping performed by the `UserAgentWindowsPlatform` PHP class.
 *
 * @param {string} version
 * @return {string}
 */
function normalizePlatformVersion(version) {
  if (UserAgentData.platformName === 'Windows') {
    return version.replace(/^\s*NT/, '');
  }

  return version;
}

/**
 * Provides client-side access to the authoritative PHP-generated User Agent
 * information supplied by the server.
 */
var UserAgent = {
  /**
   * Check if the User Agent browser matches `query`.
   *
   * `query` should be a string like "Chrome" or "Chrome > 33".
   *
   * Valid browser names include:
   *
   * - ACCESS NetFront
   * - AOL
   * - Amazon Silk
   * - Android
   * - BlackBerry
   * - BlackBerry PlayBook
   * - Chrome
   * - Chrome for iOS
   * - Chrome frame
   * - Facebook PHP SDK
   * - Facebook for iOS
   * - Firefox
   * - IE
   * - IE Mobile
   * - Mobile Safari
   * - Motorola Internet Browser
   * - Nokia
   * - Openwave Mobile Browser
   * - Opera
   * - Opera Mini
   * - Opera Mobile
   * - Safari
   * - UIWebView
   * - Unknown
   * - webOS
   * - etc...
   *
   * An authoritative list can be found in the PHP `BrowserDetector` class and
   * related classes in the same file (see calls to `new UserAgentBrowser` here:
   * https://fburl.com/50728104).
   *
   * @note Function results are memoized
   *
   * @param {string} query Query of the form "Name [range expression]"
   * @return {boolean}
   */
  isBrowser: function isBrowser(query) {
    return compare(UserAgentData.browserName, UserAgentData.browserFullVersion, query);
  },


  /**
   * Check if the User Agent browser uses a 32 or 64 bit architecture.
   *
   * @note Function results are memoized
   *
   * @param {string} query Query of the form "32" or "64".
   * @return {boolean}
   */
  isBrowserArchitecture: function isBrowserArchitecture(query) {
    return compare(UserAgentData.browserArchitecture, null, query);
  },


  /**
   * Check if the User Agent device matches `query`.
   *
   * `query` should be a string like "iPhone" or "iPad".
   *
   * Valid device names include:
   *
   * - Kindle
   * - Kindle Fire
   * - Unknown
   * - iPad
   * - iPhone
   * - iPod
   * - etc...
   *
   * An authoritative list can be found in the PHP `DeviceDetector` class and
   * related classes in the same file (see calls to `new UserAgentDevice` here:
   * https://fburl.com/50728332).
   *
   * @note Function results are memoized
   *
   * @param {string} query Query of the form "Name"
   * @return {boolean}
   */
  isDevice: function isDevice(query) {
    return compare(UserAgentData.deviceName, null, query);
  },


  /**
   * Check if the User Agent rendering engine matches `query`.
   *
   * `query` should be a string like "WebKit" or "WebKit >= 537".
   *
   * Valid engine names include:
   *
   * - Gecko
   * - Presto
   * - Trident
   * - WebKit
   * - etc...
   *
   * An authoritative list can be found in the PHP `RenderingEngineDetector`
   * class related classes in the same file (see calls to `new
   * UserAgentRenderingEngine` here: https://fburl.com/50728617).
   *
   * @note Function results are memoized
   *
   * @param {string} query Query of the form "Name [range expression]"
   * @return {boolean}
   */
  isEngine: function isEngine(query) {
    return compare(UserAgentData.engineName, UserAgentData.engineVersion, query);
  },


  /**
   * Check if the User Agent platform matches `query`.
   *
   * `query` should be a string like "Windows" or "iOS 5 - 6".
   *
   * Valid platform names include:
   *
   * - Android
   * - BlackBerry OS
   * - Java ME
   * - Linux
   * - Mac OS X
   * - Mac OS X Calendar
   * - Mac OS X Internet Account
   * - Symbian
   * - SymbianOS
   * - Windows
   * - Windows Mobile
   * - Windows Phone
   * - iOS
   * - iOS Facebook Integration Account
   * - iOS Facebook Social Sharing UI
   * - webOS
   * - Chrome OS
   * - etc...
   *
   * An authoritative list can be found in the PHP `PlatformDetector` class and
   * related classes in the same file (see calls to `new UserAgentPlatform`
   * here: https://fburl.com/50729226).
   *
   * @note Function results are memoized
   *
   * @param {string} query Query of the form "Name [range expression]"
   * @return {boolean}
   */
  isPlatform: function isPlatform(query) {
    return compare(UserAgentData.platformName, UserAgentData.platformFullVersion, query, normalizePlatformVersion);
  },


  /**
   * Check if the User Agent platform is a 32 or 64 bit architecture.
   *
   * @note Function results are memoized
   *
   * @param {string} query Query of the form "32" or "64".
   * @return {boolean}
   */
  isPlatformArchitecture: function isPlatformArchitecture(query) {
    return compare(UserAgentData.platformArchitecture, null, query);
  }
};

module.exports = mapObject(UserAgent, memoizeStringOnly);

/***/ }),

/***/ "Cbry":
/*!*********************************************!*\
  !*** ./node_modules/source-map/lib/util.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/* -*- Mode: js; js-indent-level: 2; -*- */
/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

/**
 * This is a helper function for getting values from parameter/options
 * objects.
 *
 * @param args The object we are extracting values from
 * @param name The name of the property we are getting.
 * @param defaultValue An optional value to return if the property is missing
 * from the object. If this is not specified and the property is missing, an
 * error will be thrown.
 */
function getArg(aArgs, aName, aDefaultValue) {
  if (aName in aArgs) {
    return aArgs[aName];
  } else if (arguments.length === 3) {
    return aDefaultValue;
  } else {
    throw new Error('"' + aName + '" is a required argument.');
  }
}
exports.getArg = getArg;

var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
var dataUrlRegexp = /^data:.+\,.+$/;

function urlParse(aUrl) {
  var match = aUrl.match(urlRegexp);
  if (!match) {
    return null;
  }
  return {
    scheme: match[1],
    auth: match[2],
    host: match[3],
    port: match[4],
    path: match[5]
  };
}
exports.urlParse = urlParse;

function urlGenerate(aParsedUrl) {
  var url = '';
  if (aParsedUrl.scheme) {
    url += aParsedUrl.scheme + ':';
  }
  url += '//';
  if (aParsedUrl.auth) {
    url += aParsedUrl.auth + '@';
  }
  if (aParsedUrl.host) {
    url += aParsedUrl.host;
  }
  if (aParsedUrl.port) {
    url += ":" + aParsedUrl.port
  }
  if (aParsedUrl.path) {
    url += aParsedUrl.path;
  }
  return url;
}
exports.urlGenerate = urlGenerate;

/**
 * Normalizes a path, or the path portion of a URL:
 *
 * - Replaces consecutive slashes with one slash.
 * - Removes unnecessary '.' parts.
 * - Removes unnecessary '<dir>/..' parts.
 *
 * Based on code in the Node.js 'path' core module.
 *
 * @param aPath The path or url to normalize.
 */
function normalize(aPath) {
  var path = aPath;
  var url = urlParse(aPath);
  if (url) {
    if (!url.path) {
      return aPath;
    }
    path = url.path;
  }
  var isAbsolute = exports.isAbsolute(path);

  var parts = path.split(/\/+/);
  for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
    part = parts[i];
    if (part === '.') {
      parts.splice(i, 1);
    } else if (part === '..') {
      up++;
    } else if (up > 0) {
      if (part === '') {
        // The first part is blank if the path is absolute. Trying to go
        // above the root is a no-op. Therefore we can remove all '..' parts
        // directly after the root.
        parts.splice(i + 1, up);
        up = 0;
      } else {
        parts.splice(i, 2);
        up--;
      }
    }
  }
  path = parts.join('/');

  if (path === '') {
    path = isAbsolute ? '/' : '.';
  }

  if (url) {
    url.path = path;
    return urlGenerate(url);
  }
  return path;
}
exports.normalize = normalize;

/**
 * Joins two paths/URLs.
 *
 * @param aRoot The root path or URL.
 * @param aPath The path or URL to be joined with the root.
 *
 * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
 *   scheme-relative URL: Then the scheme of aRoot, if any, is prepended
 *   first.
 * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
 *   is updated with the result and aRoot is returned. Otherwise the result
 *   is returned.
 *   - If aPath is absolute, the result is aPath.
 *   - Otherwise the two paths are joined with a slash.
 * - Joining for example 'http://' and 'www.example.com' is also supported.
 */
function join(aRoot, aPath) {
  if (aRoot === "") {
    aRoot = ".";
  }
  if (aPath === "") {
    aPath = ".";
  }
  var aPathUrl = urlParse(aPath);
  var aRootUrl = urlParse(aRoot);
  if (aRootUrl) {
    aRoot = aRootUrl.path || '/';
  }

  // `join(foo, '//www.example.org')`
  if (aPathUrl && !aPathUrl.scheme) {
    if (aRootUrl) {
      aPathUrl.scheme = aRootUrl.scheme;
    }
    return urlGenerate(aPathUrl);
  }

  if (aPathUrl || aPath.match(dataUrlRegexp)) {
    return aPath;
  }

  // `join('http://', 'www.example.com')`
  if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
    aRootUrl.host = aPath;
    return urlGenerate(aRootUrl);
  }

  var joined = aPath.charAt(0) === '/'
    ? aPath
    : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);

  if (aRootUrl) {
    aRootUrl.path = joined;
    return urlGenerate(aRootUrl);
  }
  return joined;
}
exports.join = join;

exports.isAbsolute = function (aPath) {
  return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
};

/**
 * Make a path relative to a URL or another path.
 *
 * @param aRoot The root path or URL.
 * @param aPath The path or URL to be made relative to aRoot.
 */
function relative(aRoot, aPath) {
  if (aRoot === "") {
    aRoot = ".";
  }

  aRoot = aRoot.replace(/\/$/, '');

  // It is possible for the path to be above the root. In this case, simply
  // checking whether the root is a prefix of the path won't work. Instead, we
  // need to remove components from the root one by one, until either we find
  // a prefix that fits, or we run out of components to remove.
  var level = 0;
  while (aPath.indexOf(aRoot + '/') !== 0) {
    var index = aRoot.lastIndexOf("/");
    if (index < 0) {
      return aPath;
    }

    // If the only part of the root that is left is the scheme (i.e. http://,
    // file:///, etc.), one or more slashes (/), or simply nothing at all, we
    // have exhausted all components, so the path is not relative to the root.
    aRoot = aRoot.slice(0, index);
    if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
      return aPath;
    }

    ++level;
  }

  // Make sure we add a "../" for each component we removed from the root.
  return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
}
exports.relative = relative;

var supportsNullProto = (function () {
  var obj = Object.create(null);
  return !('__proto__' in obj);
}());

function identity (s) {
  return s;
}

/**
 * Because behavior goes wacky when you set `__proto__` on objects, we
 * have to prefix all the strings in our set with an arbitrary character.
 *
 * See https://github.com/mozilla/source-map/pull/31 and
 * https://github.com/mozilla/source-map/issues/30
 *
 * @param String aStr
 */
function toSetString(aStr) {
  if (isProtoString(aStr)) {
    return '$' + aStr;
  }

  return aStr;
}
exports.toSetString = supportsNullProto ? identity : toSetString;

function fromSetString(aStr) {
  if (isProtoString(aStr)) {
    return aStr.slice(1);
  }

  return aStr;
}
exports.fromSetString = supportsNullProto ? identity : fromSetString;

function isProtoString(s) {
  if (!s) {
    return false;
  }

  var length = s.length;

  if (length < 9 /* "__proto__".length */) {
    return false;
  }

  if (s.charCodeAt(length - 1) !== 95  /* '_' */ ||
      s.charCodeAt(length - 2) !== 95  /* '_' */ ||
      s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
      s.charCodeAt(length - 4) !== 116 /* 't' */ ||
      s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
      s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
      s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
      s.charCodeAt(length - 8) !== 95  /* '_' */ ||
      s.charCodeAt(length - 9) !== 95  /* '_' */) {
    return false;
  }

  for (var i = length - 10; i >= 0; i--) {
    if (s.charCodeAt(i) !== 36 /* '$' */) {
      return false;
    }
  }

  return true;
}

/**
 * Comparator between two mappings where the original positions are compared.
 *
 * Optionally pass in `true` as `onlyCompareGenerated` to consider two
 * mappings with the same original source/line/column, but different generated
 * line and column the same. Useful when searching for a mapping with a
 * stubbed out mapping.
 */
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  var cmp = strcmp(mappingA.source, mappingB.source);
  if (cmp !== 0) {
    return cmp;
  }

  cmp = mappingA.originalLine - mappingB.originalLine;
  if (cmp !== 0) {
    return cmp;
  }

  cmp = mappingA.originalColumn - mappingB.originalColumn;
  if (cmp !== 0 || onlyCompareOriginal) {
    return cmp;
  }

  cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  if (cmp !== 0) {
    return cmp;
  }

  cmp = mappingA.generatedLine - mappingB.generatedLine;
  if (cmp !== 0) {
    return cmp;
  }

  return strcmp(mappingA.name, mappingB.name);
}
exports.compareByOriginalPositions = compareByOriginalPositions;

/**
 * Comparator between two mappings with deflated source and name indices where
 * the generated positions are compared.
 *
 * Optionally pass in `true` as `onlyCompareGenerated` to consider two
 * mappings with the same generated line and column, but different
 * source/name/original line and column the same. Useful when searching for a
 * mapping with a stubbed out mapping.
 */
function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  var cmp = mappingA.generatedLine - mappingB.generatedLine;
  if (cmp !== 0) {
    return cmp;
  }

  cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  if (cmp !== 0 || onlyCompareGenerated) {
    return cmp;
  }

  cmp = strcmp(mappingA.source, mappingB.source);
  if (cmp !== 0) {
    return cmp;
  }

  cmp = mappingA.originalLine - mappingB.originalLine;
  if (cmp !== 0) {
    return cmp;
  }

  cmp = mappingA.originalColumn - mappingB.originalColumn;
  if (cmp !== 0) {
    return cmp;
  }

  return strcmp(mappingA.name, mappingB.name);
}
exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;

function strcmp(aStr1, aStr2) {
  if (aStr1 === aStr2) {
    return 0;
  }

  if (aStr1 === null) {
    return 1; // aStr2 !== null
  }

  if (aStr2 === null) {
    return -1; // aStr1 !== null
  }

  if (aStr1 > aStr2) {
    return 1;
  }

  return -1;
}

/**
 * Comparator between two mappings with inflated source and name strings where
 * the generated positions are compared.
 */
function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  var cmp = mappingA.generatedLine - mappingB.generatedLine;
  if (cmp !== 0) {
    return cmp;
  }

  cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  if (cmp !== 0) {
    return cmp;
  }

  cmp = strcmp(mappingA.source, mappingB.source);
  if (cmp !== 0) {
    return cmp;
  }

  cmp = mappingA.originalLine - mappingB.originalLine;
  if (cmp !== 0) {
    return cmp;
  }

  cmp = mappingA.originalColumn - mappingB.originalColumn;
  if (cmp !== 0) {
    return cmp;
  }

  return strcmp(mappingA.name, mappingB.name);
}
exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;

/**
 * Strip any JSON XSSI avoidance prefix from the string (as documented
 * in the source maps specification), and then parse the string as
 * JSON.
 */
function parseSourceMapInput(str) {
  return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
}
exports.parseSourceMapInput = parseSourceMapInput;

/**
 * Compute the URL of a source given the the source root, the source's
 * URL, and the source map's URL.
 */
function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  sourceURL = sourceURL || '';

  if (sourceRoot) {
    // This follows what Chrome does.
    if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
      sourceRoot += '/';
    }
    // The spec says:
    //   Line 4: An optional source root, useful for relocating source
    //   files on a server or removing repeated values in the
    //   “sources” entry.  This value is prepended to the individual
    //   entries in the “source” field.
    sourceURL = sourceRoot + sourceURL;
  }

  // Historically, SourceMapConsumer did not take the sourceMapURL as
  // a parameter.  This mode is still somewhat supported, which is why
  // this code block is conditional.  However, it's preferable to pass
  // the source map URL to SourceMapConsumer, so that this function
  // can implement the source URL resolution algorithm as outlined in
  // the spec.  This block is basically the equivalent of:
  //    new URL(sourceURL, sourceMapURL).toString()
  // ... except it avoids using URL, which wasn't available in the
  // older releases of node still supported by this library.
  //
  // The spec says:
  //   If the sources are not absolute URLs after prepending of the
  //   “sourceRoot”, the sources are resolved relative to the
  //   SourceMap (like resolving script src in a html document).
  if (sourceMapURL) {
    var parsed = urlParse(sourceMapURL);
    if (!parsed) {
      throw new Error("sourceMapURL could not be parsed");
    }
    if (parsed.path) {
      // Strip the last path component, but keep the "/".
      var index = parsed.path.lastIndexOf('/');
      if (index >= 0) {
        parsed.path = parsed.path.substring(0, index + 1);
      }
    }
    sourceURL = join(urlGenerate(parsed), sourceURL);
  }

  return normalize(sourceURL);
}
exports.computeSourceURL = computeSourceURL;


/***/ }),

/***/ "Cdfm":
/*!********************************************************!*\
  !*** ./node_modules/@phosphor/algorithm/lib/filter.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var iter_1 = __webpack_require__(/*! ./iter */ "DMSk");
/**
 * Filter an iterable for values which pass a test.
 *
 * @param object - The iterable or array-like object of interest.
 *
 * @param fn - The predicate function to invoke for each value.
 *
 * @returns An iterator which yields the values which pass the test.
 *
 * #### Example
 * ```typescript
 * import { filter, toArray } from '@phosphor/algorithm';
 *
 * let data = [1, 2, 3, 4, 5, 6];
 *
 * let stream = filter(data, value => value % 2 === 0);
 *
 * toArray(stream);  // [2, 4, 6]
 * ```
 */
function filter(object, fn) {
    return new FilterIterator(iter_1.iter(object), fn);
}
exports.filter = filter;
/**
 * An iterator which yields values which pass a test.
 */
var FilterIterator = (function () {
    /**
     * Construct a new filter iterator.
     *
     * @param source - The iterator of values of interest.
     *
     * @param fn - The predicate function to invoke for each value.
     */
    function FilterIterator(source, fn) {
        this._index = 0;
        this._source = source;
        this._fn = fn;
    }
    /**
     * Get an iterator over the object's values.
     *
     * @returns An iterator which yields the object's values.
     */
    FilterIterator.prototype.iter = function () {
        return this;
    };
    /**
     * Create an independent clone of the iterator.
     *
     * @returns A new independent clone of the iterator.
     */
    FilterIterator.prototype.clone = function () {
        var result = new FilterIterator(this._source.clone(), this._fn);
        result._index = this._index;
        return result;
    };
    /**
     * Get the next value from the iterator.
     *
     * @returns The next value from the iterator, or `undefined`.
     */
    FilterIterator.prototype.next = function () {
        var fn = this._fn;
        var it = this._source;
        var value;
        while ((value = it.next()) !== undefined) {
            if (fn(value, this._index++)) {
                return value;
            }
        }
        return undefined;
    };
    return FilterIterator;
}());
exports.FilterIterator = FilterIterator;


/***/ }),

/***/ "CfXC":
/*!*****************************************************!*\
  !*** ./node_modules/browserify-aes/streamCipher.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var aes = __webpack_require__(/*! ./aes */ "OfWw")
var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer
var Transform = __webpack_require__(/*! cipher-base */ "ZDAU")
var inherits = __webpack_require__(/*! inherits */ "P7XM")

function StreamCipher (mode, key, iv, decrypt) {
  Transform.call(this)

  this._cipher = new aes.AES(key)
  this._prev = Buffer.from(iv)
  this._cache = Buffer.allocUnsafe(0)
  this._secCache = Buffer.allocUnsafe(0)
  this._decrypt = decrypt
  this._mode = mode
}

inherits(StreamCipher, Transform)

StreamCipher.prototype._update = function (chunk) {
  return this._mode.encrypt(this, chunk, this._decrypt)
}

StreamCipher.prototype._final = function () {
  this._cipher.scrub()
}

module.exports = StreamCipher


/***/ }),

/***/ "Cj/q":
/*!******************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/codemirror/theme/material.css ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*\n\n    Name:       material\n    Author:     Michael Kaminsky (http://github.com/mkaminsky11)\n\n    Original material color scheme by Mattia Astorino (https://github.com/equinusocio/material-theme)\n\n*/\n\n.cm-s-material.CodeMirror {\n  background-color: #263238;\n  color: rgba(233, 237, 237, 1);\n}\n.cm-s-material .CodeMirror-gutters {\n  background: #263238;\n  color: rgb(83,127,126);\n  border: none;\n}\n.cm-s-material .CodeMirror-guttermarker, .cm-s-material .CodeMirror-guttermarker-subtle, .cm-s-material .CodeMirror-linenumber { color: rgb(83,127,126); }\n.cm-s-material .CodeMirror-cursor { border-left: 1px solid #f8f8f0; }\n.cm-s-material div.CodeMirror-selected { background: rgba(255, 255, 255, 0.15); }\n.cm-s-material.CodeMirror-focused div.CodeMirror-selected { background: rgba(255, 255, 255, 0.10); }\n.cm-s-material .CodeMirror-line::selection, .cm-s-material .CodeMirror-line > span::selection, .cm-s-material .CodeMirror-line > span > span::selection { background: rgba(255, 255, 255, 0.10); }\n.cm-s-material .CodeMirror-line::-moz-selection, .cm-s-material .CodeMirror-line > span::-moz-selection, .cm-s-material .CodeMirror-line > span > span::-moz-selection { background: rgba(255, 255, 255, 0.10); }\n\n.cm-s-material .CodeMirror-activeline-background { background: rgba(0, 0, 0, 0); }\n.cm-s-material .cm-keyword { color: rgba(199, 146, 234, 1); }\n.cm-s-material .cm-operator { color: rgba(233, 237, 237, 1); }\n.cm-s-material .cm-variable-2 { color: #80CBC4; }\n.cm-s-material .cm-variable-3, .cm-s-material .cm-type { color: #82B1FF; }\n.cm-s-material .cm-builtin { color: #DECB6B; }\n.cm-s-material .cm-atom { color: #F77669; }\n.cm-s-material .cm-number { color: #F77669; }\n.cm-s-material .cm-def { color: rgba(233, 237, 237, 1); }\n.cm-s-material .cm-string { color: #C3E88D; }\n.cm-s-material .cm-string-2 { color: #80CBC4; }\n.cm-s-material .cm-comment { color: #546E7A; }\n.cm-s-material .cm-variable { color: #82B1FF; }\n.cm-s-material .cm-tag { color: #80CBC4; }\n.cm-s-material .cm-meta { color: #80CBC4; }\n.cm-s-material .cm-attribute { color: #FFCB6B; }\n.cm-s-material .cm-property { color: #80CBAE; }\n.cm-s-material .cm-qualifier { color: #DECB6B; }\n.cm-s-material .cm-variable-3, .cm-s-material .cm-type { color: #DECB6B; }\n.cm-s-material .cm-tag { color: rgba(255, 83, 112, 1); }\n.cm-s-material .cm-error {\n  color: rgba(255, 255, 255, 1.0);\n  background-color: #EC5F67;\n}\n.cm-s-material .CodeMirror-matchingbracket {\n  text-decoration: underline;\n  color: white !important;\n}\n", ""]);

// exports


/***/ }),

/***/ "CjjH":
/*!*******************************************!*\
  !*** ./node_modules/base16/lib/bright.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'bright',
  author: 'chris kempson (http://chriskempson.com)',
  base00: '#000000',
  base01: '#303030',
  base02: '#505050',
  base03: '#b0b0b0',
  base04: '#d0d0d0',
  base05: '#e0e0e0',
  base06: '#f5f5f5',
  base07: '#ffffff',
  base08: '#fb0120',
  base09: '#fc6d24',
  base0A: '#fda331',
  base0B: '#a1c659',
  base0C: '#76c7b7',
  base0D: '#6fb3d2',
  base0E: '#d381c3',
  base0F: '#be643c'
};
module.exports = exports['default'];

/***/ }),

/***/ "CjzT":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/es-do.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'),
    monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_');

var monthsParse = [/^ene/i, /^feb/i, /^mar/i, /^abr/i, /^may/i, /^jun/i, /^jul/i, /^ago/i, /^sep/i, /^oct/i, /^nov/i, /^dic/i];
var monthsRegex = /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i;

var esDo = moment.defineLocale('es-do', {
    months : 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'),
    monthsShort : function (m, format) {
        if (!m) {
            return monthsShortDot;
        } else if (/-MMM-/.test(format)) {
            return monthsShort[m.month()];
        } else {
            return monthsShortDot[m.month()];
        }
    },
    monthsRegex: monthsRegex,
    monthsShortRegex: monthsRegex,
    monthsStrictRegex: /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i,
    monthsShortStrictRegex: /^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i,
    monthsParse: monthsParse,
    longMonthsParse: monthsParse,
    shortMonthsParse: monthsParse,
    weekdays : 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'),
    weekdaysShort : 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'),
    weekdaysMin : 'do_lu_ma_mi_ju_vi_sá'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'h:mm A',
        LTS : 'h:mm:ss A',
        L : 'DD/MM/YYYY',
        LL : 'D [de] MMMM [de] YYYY',
        LLL : 'D [de] MMMM [de] YYYY h:mm A',
        LLLL : 'dddd, D [de] MMMM [de] YYYY h:mm A'
    },
    calendar : {
        sameDay : function () {
            return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
        },
        nextDay : function () {
            return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
        },
        nextWeek : function () {
            return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
        },
        lastDay : function () {
            return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
        },
        lastWeek : function () {
            return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
        },
        sameElse : 'L'
    },
    relativeTime : {
        future : 'en %s',
        past : 'hace %s',
        s : 'unos segundos',
        ss : '%d segundos',
        m : 'un minuto',
        mm : '%d minutos',
        h : 'una hora',
        hh : '%d horas',
        d : 'un día',
        dd : '%d días',
        M : 'un mes',
        MM : '%d meses',
        y : 'un año',
        yy : '%d años'
    },
    dayOfMonthOrdinalParse : /\d{1,2}º/,
    ordinal : '%dº',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return esDo;

})));


/***/ }),

/***/ "Cn7X":
/*!**********************************************************************!*\
  !*** ./node_modules/@jupyterlab/coreutils/lib/markdowncodeblocks.js ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * The namespace for code block functions which help
 * in extract code from markdown text
 */
var MarkdownCodeBlocks;
(function (MarkdownCodeBlocks) {
    MarkdownCodeBlocks.CODE_BLOCK_MARKER = '```';
    const markdownExtensions = [
        '.markdown',
        '.mdown',
        '.mkdn',
        '.md',
        '.mkd',
        '.mdwn',
        '.mdtxt',
        '.mdtext',
        '.text',
        '.txt',
        '.Rmd'
    ];
    class MarkdownCodeBlock {
        constructor(startLine) {
            this.startLine = startLine;
            this.code = '';
            this.endLine = -1;
        }
    }
    MarkdownCodeBlocks.MarkdownCodeBlock = MarkdownCodeBlock;
    /**
     * Check whether the given file extension is a markdown extension
     * @param extension - A file extension
     *
     * @returns true/false depending on whether this is a supported markdown extension
     */
    function isMarkdown(extension) {
        return markdownExtensions.indexOf(extension) > -1;
    }
    MarkdownCodeBlocks.isMarkdown = isMarkdown;
    /**
     * Construct all code snippets from current text
     * (this could be potentially optimized if we can cache and detect differences)
     * @param text - A string to parse codeblocks from
     *
     * @returns An array of MarkdownCodeBlocks.
     */
    function findMarkdownCodeBlocks(text) {
        if (!text || text === '') {
            return [];
        }
        const lines = text.split('\n');
        const codeBlocks = [];
        let currentBlock = null;
        for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
            const line = lines[lineIndex];
            const lineContainsMarker = line.indexOf(MarkdownCodeBlocks.CODE_BLOCK_MARKER) === 0;
            const constructingBlock = currentBlock != null;
            // Skip this line if it is not part of any code block and doesn't contain a marker.
            if (!lineContainsMarker && !constructingBlock) {
                continue;
            }
            // Check if we are already constructing a code block.
            if (!constructingBlock) {
                // Start constructing a new code block.
                currentBlock = new MarkdownCodeBlock(lineIndex);
                // Check whether this is a single line code block of the form ```a = 10```.
                const firstIndex = line.indexOf(MarkdownCodeBlocks.CODE_BLOCK_MARKER);
                const lastIndex = line.lastIndexOf(MarkdownCodeBlocks.CODE_BLOCK_MARKER);
                const isSingleLine = firstIndex !== lastIndex;
                if (isSingleLine) {
                    currentBlock.code = line.substring(firstIndex + MarkdownCodeBlocks.CODE_BLOCK_MARKER.length, lastIndex);
                    currentBlock.endLine = lineIndex;
                    codeBlocks.push(currentBlock);
                    currentBlock = null;
                }
            }
            else if (currentBlock) {
                if (lineContainsMarker) {
                    // End of block, finish it up.
                    currentBlock.endLine = lineIndex - 1;
                    codeBlocks.push(currentBlock);
                    currentBlock = null;
                }
                else {
                    // Append the current line.
                    currentBlock.code += line + '\n';
                }
            }
        }
        return codeBlocks;
    }
    MarkdownCodeBlocks.findMarkdownCodeBlocks = findMarkdownCodeBlocks;
})(MarkdownCodeBlocks = exports.MarkdownCodeBlocks || (exports.MarkdownCodeBlocks = {}));


/***/ }),

/***/ "Cnx3":
/*!*************************************************************!*\
  !*** ./node_modules/@phosphor/datagrid/lib/cellrenderer.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/**
 * An object which renders the cells of a data grid.
 *
 * #### Notes
 * If the predefined cell renderers are insufficient for a particular
 * use case, a custom cell renderer can be defined which derives from
 * this class.
 *
 * The data grid renders cells in column-major order, by region. The
 * region order is: body, row header, column header, corner header.
 */
var CellRenderer = (function () {
    function CellRenderer() {
    }
    /**
     * Prepare the graphics context for drawing a column of cells.
     *
     * @param gc - The graphics context to prepare.
     *
     * @param config - The configuration data for the column.
     *
     * #### Notes
     * This method is called just before the grid renders the cells in
     * a column. It allows the renderer an opportunity to set defaults
     * on the `gc` or pre-compute column render state. This can reduce
     * the need for costly `gc` state changes when painting each cell.
     *
     * The renderer **must not** draw to the `gc` in this method.
     *
     * The default implementation is a no-op.
     */
    CellRenderer.prototype.prepare = function (gc, config) { };
    return CellRenderer;
}());
exports.CellRenderer = CellRenderer;
/**
 * The namespace for the `CellRenderer` class statics.
 */
(function (CellRenderer) {
    /**
     * Resolve a config option for a cell renderer.
     *
     * @param option - The config option to resolve.
     *
     * @param config - The cell config object.
     *
     * @returns The resolved value for the option.
     */
    function resolveOption(option, config) {
        return typeof option === 'function' ? option(config) : option;
    }
    CellRenderer.resolveOption = resolveOption;
})(CellRenderer = exports.CellRenderer || (exports.CellRenderer = {}));
exports.CellRenderer = CellRenderer;


/***/ }),

/***/ "CoRJ":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/ar-ma.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var arMa = moment.defineLocale('ar-ma', {
    months : 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'),
    monthsShort : 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'),
    weekdays : 'الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
    weekdaysShort : 'احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'),
    weekdaysMin : 'ح_ن_ث_ر_خ_ج_س'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay: '[اليوم على الساعة] LT',
        nextDay: '[غدا على الساعة] LT',
        nextWeek: 'dddd [على الساعة] LT',
        lastDay: '[أمس على الساعة] LT',
        lastWeek: 'dddd [على الساعة] LT',
        sameElse: 'L'
    },
    relativeTime : {
        future : 'في %s',
        past : 'منذ %s',
        s : 'ثوان',
        ss : '%d ثانية',
        m : 'دقيقة',
        mm : '%d دقائق',
        h : 'ساعة',
        hh : '%d ساعات',
        d : 'يوم',
        dd : '%d أيام',
        M : 'شهر',
        MM : '%d أشهر',
        y : 'سنة',
        yy : '%d سنوات'
    },
    week : {
        dow : 6, // Saturday is the first day of the week.
        doy : 12  // The week that contains Jan 1st is the first week of the year.
    }
});

return arMa;

})));


/***/ }),

/***/ "CsZw":
/*!***********************************************!*\
  !*** ./node_modules/mdi-react/AccountIcon.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var AccountIcon = function AccountIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M12,4C14.21,4 16,5.79 16,8C16,10.21 14.21,12 12,12C9.79,12 8,10.21 8,8C8,5.79 9.79,4 12,4M12,14C16.42,14 20,15.79 20,18V20H4V18C4,15.79 7.58,14 12,14Z' })
  );
};

module.exports = AccountIcon;


/***/ }),

/***/ "Cwc5":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_getNative.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseIsNative = __webpack_require__(/*! ./_baseIsNative */ "NKxu"),
    getValue = __webpack_require__(/*! ./_getValue */ "Npjl");

/**
 * 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;
}

module.exports = getNative;


/***/ }),

/***/ "Cwia":
/*!************************************************************!*\
  !*** ./node_modules/react-dropzone/dist/es/utils/index.js ***!
  \************************************************************/
/*! exports provided: supportMultiple, getDataTransferItems, fileAccepted, fileMatchSize, allFilesAccepted, onDocumentDragOver, isIeOrEdge */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "supportMultiple", function() { return supportMultiple; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDataTransferItems", function() { return getDataTransferItems; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fileAccepted", function() { return fileAccepted; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fileMatchSize", function() { return fileMatchSize; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "allFilesAccepted", function() { return allFilesAccepted; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "onDocumentDragOver", function() { return onDocumentDragOver; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isIeOrEdge", function() { return isIeOrEdge; });
/* harmony import */ var attr_accept__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! attr-accept */ "eMbh");
/* harmony import */ var attr_accept__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(attr_accept__WEBPACK_IMPORTED_MODULE_0__);


var supportMultiple = typeof document !== 'undefined' && document && document.createElement ? 'multiple' in document.createElement('input') : true;

function getDataTransferItems(event) {
  var dataTransferItemsList = [];
  if (event.dataTransfer) {
    var dt = event.dataTransfer;

    if (dt.files && dt.files.length) {
      dataTransferItemsList = dt.files;
    } else if (dt.items && dt.items.length) {
      // During the drag even the dataTransfer.files is null
      // but Chrome implements some drag store, which is accesible via dataTransfer.items
      dataTransferItemsList = dt.items;
    }
  } else if (event.target && event.target.files) {
    dataTransferItemsList = event.target.files;
  }

  // Convert from DataTransferItemsList to the native Array
  return Array.prototype.slice.call(dataTransferItemsList);
}

// Firefox versions prior to 53 return a bogus MIME type for every file drag, so dragovers with
// that MIME type will always be accepted
function fileAccepted(file, accept) {
  return file.type === 'application/x-moz-file' || attr_accept__WEBPACK_IMPORTED_MODULE_0___default()(file, accept);
}

function fileMatchSize(file, maxSize, minSize) {
  return file.size <= maxSize && file.size >= minSize;
}

function allFilesAccepted(files, accept) {
  return files.every(function (file) {
    return fileAccepted(file, accept);
  });
}

// allow the entire document to be a drag target
function onDocumentDragOver(evt) {
  evt.preventDefault();
}

function isIe(userAgent) {
  return userAgent.indexOf('MSIE') !== -1 || userAgent.indexOf('Trident/') !== -1;
}

function isEdge(userAgent) {
  return userAgent.indexOf('Edge/') !== -1;
}

function isIeOrEdge() {
  var userAgent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window.navigator.userAgent;

  return isIe(userAgent) || isEdge(userAgent);
}

/***/ }),

/***/ "Cx5C":
/*!*********************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/rule.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _container = __webpack_require__(/*! ./container */ "+9U2");

var _container2 = _interopRequireDefault(_container);

var _list = __webpack_require__(/*! ./list */ "TIjV");

var _list2 = _interopRequireDefault(_list);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * Represents a CSS rule: a selector followed by a declaration block.
 *
 * @extends Container
 *
 * @example
 * const root = postcss.parse('a{}');
 * const rule = root.first;
 * rule.type       //=> 'rule'
 * rule.toString() //=> 'a{}'
 */
var Rule = function (_Container) {
  _inherits(Rule, _Container);

  function Rule(defaults) {
    _classCallCheck(this, Rule);

    var _this = _possibleConstructorReturn(this, _Container.call(this, defaults));

    _this.type = 'rule';
    if (!_this.nodes) _this.nodes = [];
    return _this;
  }

  /**
   * An array containing the rule’s individual selectors.
   * Groups of selectors are split at commas.
   *
   * @type {string[]}
   *
   * @example
   * const root = postcss.parse('a, b { }');
   * const rule = root.first;
   *
   * rule.selector  //=> 'a, b'
   * rule.selectors //=> ['a', 'b']
   *
   * rule.selectors = ['a', 'strong'];
   * rule.selector //=> 'a, strong'
   */


  _createClass(Rule, [{
    key: 'selectors',
    get: function get() {
      return _list2.default.comma(this.selector);
    },
    set: function set(values) {
      var match = this.selector ? this.selector.match(/,\s*/) : null;
      var sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen');
      this.selector = values.join(sep);
    }

    /**
     * @memberof Rule#
     * @member {string} selector - the rule’s full selector represented
     *                             as a string
     *
     * @example
     * const root = postcss.parse('a, b { }');
     * const rule = root.first;
     * rule.selector //=> 'a, b'
     */

    /**
     * @memberof Rule#
     * @member {object} raws - Information to generate byte-to-byte equal
     *                         node string as it was in the origin input.
     *
     * Every parser saves its own properties,
     * but the default CSS parser uses:
     *
     * * `before`: the space symbols before the node. It also stores `*`
     *   and `_` symbols before the declaration (IE hack).
     * * `after`: the space symbols after the last child of the node
     *   to the end of the node.
     * * `between`: the symbols between the property and value
     *   for declarations, selector and `{` for rules, or last parameter
     *   and `{` for at-rules.
     * * `semicolon`: contains `true` if the last child has
     *   an (optional) semicolon.
     * * `ownSemicolon`: contains `true` if there is semicolon after rule.
     *
     * PostCSS cleans selectors from comments and extra spaces,
     * but it stores origin content in raws properties.
     * As such, if you don’t change a declaration’s value,
     * PostCSS will use the raw value with comments.
     *
     * @example
     * const root = postcss.parse('a {\n  color:black\n}')
     * root.first.first.raws //=> { before: '', between: ' ', after: '\n' }
     */

  }]);

  return Rule;
}(_container2.default);

exports.default = Rule;
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64, 


/***/ }),

/***/ "CxY0":
/*!*********************************!*\
  !*** ./node_modules/url/url.js ***!
  \*********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.



var punycode = __webpack_require__(/*! punycode */ "nYho");
var util = __webpack_require__(/*! ./util */ "Nehr");

exports.parse = urlParse;
exports.resolve = urlResolve;
exports.resolveObject = urlResolveObject;
exports.format = urlFormat;

exports.Url = Url;

function Url() {
  this.protocol = null;
  this.slashes = null;
  this.auth = null;
  this.host = null;
  this.port = null;
  this.hostname = null;
  this.hash = null;
  this.search = null;
  this.query = null;
  this.pathname = null;
  this.path = null;
  this.href = null;
}

// Reference: RFC 3986, RFC 1808, RFC 2396

// define these here so at least they only have to be
// compiled once on the first module load.
var protocolPattern = /^([a-z0-9.+-]+:)/i,
    portPattern = /:[0-9]*$/,

    // Special case for a simple path URL
    simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,

    // RFC 2396: characters reserved for delimiting URLs.
    // We actually just auto-escape these.
    delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],

    // RFC 2396: characters not allowed for various reasons.
    unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),

    // Allowed by RFCs, but cause of XSS attacks.  Always escape these.
    autoEscape = ['\''].concat(unwise),
    // Characters that are never ever allowed in a hostname.
    // Note that any invalid chars are also handled, but these
    // are the ones that are *expected* to be seen, so we fast-path
    // them.
    nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
    hostEndingChars = ['/', '?', '#'],
    hostnameMaxLen = 255,
    hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
    hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
    // protocols that can allow "unsafe" and "unwise" chars.
    unsafeProtocol = {
      'javascript': true,
      'javascript:': true
    },
    // protocols that never have a hostname.
    hostlessProtocol = {
      'javascript': true,
      'javascript:': true
    },
    // protocols that always contain a // bit.
    slashedProtocol = {
      'http': true,
      'https': true,
      'ftp': true,
      'gopher': true,
      'file': true,
      'http:': true,
      'https:': true,
      'ftp:': true,
      'gopher:': true,
      'file:': true
    },
    querystring = __webpack_require__(/*! querystring */ "s4NR");

function urlParse(url, parseQueryString, slashesDenoteHost) {
  if (url && util.isObject(url) && url instanceof Url) return url;

  var u = new Url;
  u.parse(url, parseQueryString, slashesDenoteHost);
  return u;
}

Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  if (!util.isString(url)) {
    throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  }

  // Copy chrome, IE, opera backslash-handling behavior.
  // Back slashes before the query string get converted to forward slashes
  // See: https://code.google.com/p/chromium/issues/detail?id=25916
  var queryIndex = url.indexOf('?'),
      splitter =
          (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
      uSplit = url.split(splitter),
      slashRegex = /\\/g;
  uSplit[0] = uSplit[0].replace(slashRegex, '/');
  url = uSplit.join(splitter);

  var rest = url;

  // trim before proceeding.
  // This is to support parse stuff like "  http://foo.com  \n"
  rest = rest.trim();

  if (!slashesDenoteHost && url.split('#').length === 1) {
    // Try fast path regexp
    var simplePath = simplePathPattern.exec(rest);
    if (simplePath) {
      this.path = rest;
      this.href = rest;
      this.pathname = simplePath[1];
      if (simplePath[2]) {
        this.search = simplePath[2];
        if (parseQueryString) {
          this.query = querystring.parse(this.search.substr(1));
        } else {
          this.query = this.search.substr(1);
        }
      } else if (parseQueryString) {
        this.search = '';
        this.query = {};
      }
      return this;
    }
  }

  var proto = protocolPattern.exec(rest);
  if (proto) {
    proto = proto[0];
    var lowerProto = proto.toLowerCase();
    this.protocol = lowerProto;
    rest = rest.substr(proto.length);
  }

  // figure out if it's got a host
  // user@server is *always* interpreted as a hostname, and url
  // resolution will treat //foo/bar as host=foo,path=bar because that's
  // how the browser resolves relative URLs.
  if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
    var slashes = rest.substr(0, 2) === '//';
    if (slashes && !(proto && hostlessProtocol[proto])) {
      rest = rest.substr(2);
      this.slashes = true;
    }
  }

  if (!hostlessProtocol[proto] &&
      (slashes || (proto && !slashedProtocol[proto]))) {

    // there's a hostname.
    // the first instance of /, ?, ;, or # ends the host.
    //
    // If there is an @ in the hostname, then non-host chars *are* allowed
    // to the left of the last @ sign, unless some host-ending character
    // comes *before* the @-sign.
    // URLs are obnoxious.
    //
    // ex:
    // http://a@b@c/ => user:a@b host:c
    // http://a@b?@c => user:a host:c path:/?@c

    // v0.12 TODO(isaacs): This is not quite how Chrome does things.
    // Review our test case against browsers more comprehensively.

    // find the first instance of any hostEndingChars
    var hostEnd = -1;
    for (var i = 0; i < hostEndingChars.length; i++) {
      var hec = rest.indexOf(hostEndingChars[i]);
      if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
        hostEnd = hec;
    }

    // at this point, either we have an explicit point where the
    // auth portion cannot go past, or the last @ char is the decider.
    var auth, atSign;
    if (hostEnd === -1) {
      // atSign can be anywhere.
      atSign = rest.lastIndexOf('@');
    } else {
      // atSign must be in auth portion.
      // http://a@b/c@d => host:b auth:a path:/c@d
      atSign = rest.lastIndexOf('@', hostEnd);
    }

    // Now we have a portion which is definitely the auth.
    // Pull that off.
    if (atSign !== -1) {
      auth = rest.slice(0, atSign);
      rest = rest.slice(atSign + 1);
      this.auth = decodeURIComponent(auth);
    }

    // the host is the remaining to the left of the first non-host char
    hostEnd = -1;
    for (var i = 0; i < nonHostChars.length; i++) {
      var hec = rest.indexOf(nonHostChars[i]);
      if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
        hostEnd = hec;
    }
    // if we still have not hit it, then the entire thing is a host.
    if (hostEnd === -1)
      hostEnd = rest.length;

    this.host = rest.slice(0, hostEnd);
    rest = rest.slice(hostEnd);

    // pull out port.
    this.parseHost();

    // we've indicated that there is a hostname,
    // so even if it's empty, it has to be present.
    this.hostname = this.hostname || '';

    // if hostname begins with [ and ends with ]
    // assume that it's an IPv6 address.
    var ipv6Hostname = this.hostname[0] === '[' &&
        this.hostname[this.hostname.length - 1] === ']';

    // validate a little.
    if (!ipv6Hostname) {
      var hostparts = this.hostname.split(/\./);
      for (var i = 0, l = hostparts.length; i < l; i++) {
        var part = hostparts[i];
        if (!part) continue;
        if (!part.match(hostnamePartPattern)) {
          var newpart = '';
          for (var j = 0, k = part.length; j < k; j++) {
            if (part.charCodeAt(j) > 127) {
              // we replace non-ASCII char with a temporary placeholder
              // we need this to make sure size of hostname is not
              // broken by replacing non-ASCII by nothing
              newpart += 'x';
            } else {
              newpart += part[j];
            }
          }
          // we test again with ASCII char only
          if (!newpart.match(hostnamePartPattern)) {
            var validParts = hostparts.slice(0, i);
            var notHost = hostparts.slice(i + 1);
            var bit = part.match(hostnamePartStart);
            if (bit) {
              validParts.push(bit[1]);
              notHost.unshift(bit[2]);
            }
            if (notHost.length) {
              rest = '/' + notHost.join('.') + rest;
            }
            this.hostname = validParts.join('.');
            break;
          }
        }
      }
    }

    if (this.hostname.length > hostnameMaxLen) {
      this.hostname = '';
    } else {
      // hostnames are always lower case.
      this.hostname = this.hostname.toLowerCase();
    }

    if (!ipv6Hostname) {
      // IDNA Support: Returns a punycoded representation of "domain".
      // It only converts parts of the domain name that
      // have non-ASCII characters, i.e. it doesn't matter if
      // you call it with a domain that already is ASCII-only.
      this.hostname = punycode.toASCII(this.hostname);
    }

    var p = this.port ? ':' + this.port : '';
    var h = this.hostname || '';
    this.host = h + p;
    this.href += this.host;

    // strip [ and ] from the hostname
    // the host field still retains them, though
    if (ipv6Hostname) {
      this.hostname = this.hostname.substr(1, this.hostname.length - 2);
      if (rest[0] !== '/') {
        rest = '/' + rest;
      }
    }
  }

  // now rest is set to the post-host stuff.
  // chop off any delim chars.
  if (!unsafeProtocol[lowerProto]) {

    // First, make 100% sure that any "autoEscape" chars get
    // escaped, even if encodeURIComponent doesn't think they
    // need to be.
    for (var i = 0, l = autoEscape.length; i < l; i++) {
      var ae = autoEscape[i];
      if (rest.indexOf(ae) === -1)
        continue;
      var esc = encodeURIComponent(ae);
      if (esc === ae) {
        esc = escape(ae);
      }
      rest = rest.split(ae).join(esc);
    }
  }


  // chop off from the tail first.
  var hash = rest.indexOf('#');
  if (hash !== -1) {
    // got a fragment string.
    this.hash = rest.substr(hash);
    rest = rest.slice(0, hash);
  }
  var qm = rest.indexOf('?');
  if (qm !== -1) {
    this.search = rest.substr(qm);
    this.query = rest.substr(qm + 1);
    if (parseQueryString) {
      this.query = querystring.parse(this.query);
    }
    rest = rest.slice(0, qm);
  } else if (parseQueryString) {
    // no query string, but parseQueryString still requested
    this.search = '';
    this.query = {};
  }
  if (rest) this.pathname = rest;
  if (slashedProtocol[lowerProto] &&
      this.hostname && !this.pathname) {
    this.pathname = '/';
  }

  //to support http.request
  if (this.pathname || this.search) {
    var p = this.pathname || '';
    var s = this.search || '';
    this.path = p + s;
  }

  // finally, reconstruct the href based on what has been validated.
  this.href = this.format();
  return this;
};

// format a parsed object into a url string
function urlFormat(obj) {
  // ensure it's an object, and not a string url.
  // If it's an obj, this is a no-op.
  // this way, you can call url_format() on strings
  // to clean up potentially wonky urls.
  if (util.isString(obj)) obj = urlParse(obj);
  if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
  return obj.format();
}

Url.prototype.format = function() {
  var auth = this.auth || '';
  if (auth) {
    auth = encodeURIComponent(auth);
    auth = auth.replace(/%3A/i, ':');
    auth += '@';
  }

  var protocol = this.protocol || '',
      pathname = this.pathname || '',
      hash = this.hash || '',
      host = false,
      query = '';

  if (this.host) {
    host = auth + this.host;
  } else if (this.hostname) {
    host = auth + (this.hostname.indexOf(':') === -1 ?
        this.hostname :
        '[' + this.hostname + ']');
    if (this.port) {
      host += ':' + this.port;
    }
  }

  if (this.query &&
      util.isObject(this.query) &&
      Object.keys(this.query).length) {
    query = querystring.stringify(this.query);
  }

  var search = this.search || (query && ('?' + query)) || '';

  if (protocol && protocol.substr(-1) !== ':') protocol += ':';

  // only the slashedProtocols get the //.  Not mailto:, xmpp:, etc.
  // unless they had them to begin with.
  if (this.slashes ||
      (!protocol || slashedProtocol[protocol]) && host !== false) {
    host = '//' + (host || '');
    if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  } else if (!host) {
    host = '';
  }

  if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  if (search && search.charAt(0) !== '?') search = '?' + search;

  pathname = pathname.replace(/[?#]/g, function(match) {
    return encodeURIComponent(match);
  });
  search = search.replace('#', '%23');

  return protocol + host + pathname + search + hash;
};

function urlResolve(source, relative) {
  return urlParse(source, false, true).resolve(relative);
}

Url.prototype.resolve = function(relative) {
  return this.resolveObject(urlParse(relative, false, true)).format();
};

function urlResolveObject(source, relative) {
  if (!source) return relative;
  return urlParse(source, false, true).resolveObject(relative);
}

Url.prototype.resolveObject = function(relative) {
  if (util.isString(relative)) {
    var rel = new Url();
    rel.parse(relative, false, true);
    relative = rel;
  }

  var result = new Url();
  var tkeys = Object.keys(this);
  for (var tk = 0; tk < tkeys.length; tk++) {
    var tkey = tkeys[tk];
    result[tkey] = this[tkey];
  }

  // hash is always overridden, no matter what.
  // even href="" will remove it.
  result.hash = relative.hash;

  // if the relative url is empty, then there's nothing left to do here.
  if (relative.href === '') {
    result.href = result.format();
    return result;
  }

  // hrefs like //foo/bar always cut to the protocol.
  if (relative.slashes && !relative.protocol) {
    // take everything except the protocol from relative
    var rkeys = Object.keys(relative);
    for (var rk = 0; rk < rkeys.length; rk++) {
      var rkey = rkeys[rk];
      if (rkey !== 'protocol')
        result[rkey] = relative[rkey];
    }

    //urlParse appends trailing / to urls like http://www.example.com
    if (slashedProtocol[result.protocol] &&
        result.hostname && !result.pathname) {
      result.path = result.pathname = '/';
    }

    result.href = result.format();
    return result;
  }

  if (relative.protocol && relative.protocol !== result.protocol) {
    // if it's a known url protocol, then changing
    // the protocol does weird things
    // first, if it's not file:, then we MUST have a host,
    // and if there was a path
    // to begin with, then we MUST have a path.
    // if it is file:, then the host is dropped,
    // because that's known to be hostless.
    // anything else is assumed to be absolute.
    if (!slashedProtocol[relative.protocol]) {
      var keys = Object.keys(relative);
      for (var v = 0; v < keys.length; v++) {
        var k = keys[v];
        result[k] = relative[k];
      }
      result.href = result.format();
      return result;
    }

    result.protocol = relative.protocol;
    if (!relative.host && !hostlessProtocol[relative.protocol]) {
      var relPath = (relative.pathname || '').split('/');
      while (relPath.length && !(relative.host = relPath.shift()));
      if (!relative.host) relative.host = '';
      if (!relative.hostname) relative.hostname = '';
      if (relPath[0] !== '') relPath.unshift('');
      if (relPath.length < 2) relPath.unshift('');
      result.pathname = relPath.join('/');
    } else {
      result.pathname = relative.pathname;
    }
    result.search = relative.search;
    result.query = relative.query;
    result.host = relative.host || '';
    result.auth = relative.auth;
    result.hostname = relative.hostname || relative.host;
    result.port = relative.port;
    // to support http.request
    if (result.pathname || result.search) {
      var p = result.pathname || '';
      var s = result.search || '';
      result.path = p + s;
    }
    result.slashes = result.slashes || relative.slashes;
    result.href = result.format();
    return result;
  }

  var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
      isRelAbs = (
          relative.host ||
          relative.pathname && relative.pathname.charAt(0) === '/'
      ),
      mustEndAbs = (isRelAbs || isSourceAbs ||
                    (result.host && relative.pathname)),
      removeAllDots = mustEndAbs,
      srcPath = result.pathname && result.pathname.split('/') || [],
      relPath = relative.pathname && relative.pathname.split('/') || [],
      psychotic = result.protocol && !slashedProtocol[result.protocol];

  // if the url is a non-slashed url, then relative
  // links like ../.. should be able
  // to crawl up to the hostname, as well.  This is strange.
  // result.protocol has already been set by now.
  // Later on, put the first path part into the host field.
  if (psychotic) {
    result.hostname = '';
    result.port = null;
    if (result.host) {
      if (srcPath[0] === '') srcPath[0] = result.host;
      else srcPath.unshift(result.host);
    }
    result.host = '';
    if (relative.protocol) {
      relative.hostname = null;
      relative.port = null;
      if (relative.host) {
        if (relPath[0] === '') relPath[0] = relative.host;
        else relPath.unshift(relative.host);
      }
      relative.host = null;
    }
    mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  }

  if (isRelAbs) {
    // it's absolute.
    result.host = (relative.host || relative.host === '') ?
                  relative.host : result.host;
    result.hostname = (relative.hostname || relative.hostname === '') ?
                      relative.hostname : result.hostname;
    result.search = relative.search;
    result.query = relative.query;
    srcPath = relPath;
    // fall through to the dot-handling below.
  } else if (relPath.length) {
    // it's relative
    // throw away the existing file, and take the new path instead.
    if (!srcPath) srcPath = [];
    srcPath.pop();
    srcPath = srcPath.concat(relPath);
    result.search = relative.search;
    result.query = relative.query;
  } else if (!util.isNullOrUndefined(relative.search)) {
    // just pull out the search.
    // like href='?foo'.
    // Put this after the other two cases because it simplifies the booleans
    if (psychotic) {
      result.hostname = result.host = srcPath.shift();
      //occationaly the auth can get stuck only in host
      //this especially happens in cases like
      //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
      var authInHost = result.host && result.host.indexOf('@') > 0 ?
                       result.host.split('@') : false;
      if (authInHost) {
        result.auth = authInHost.shift();
        result.host = result.hostname = authInHost.shift();
      }
    }
    result.search = relative.search;
    result.query = relative.query;
    //to support http.request
    if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
      result.path = (result.pathname ? result.pathname : '') +
                    (result.search ? result.search : '');
    }
    result.href = result.format();
    return result;
  }

  if (!srcPath.length) {
    // no path at all.  easy.
    // we've already handled the other stuff above.
    result.pathname = null;
    //to support http.request
    if (result.search) {
      result.path = '/' + result.search;
    } else {
      result.path = null;
    }
    result.href = result.format();
    return result;
  }

  // if a url ENDs in . or .., then it must get a trailing slash.
  // however, if it ends in anything else non-slashy,
  // then it must NOT get a trailing slash.
  var last = srcPath.slice(-1)[0];
  var hasTrailingSlash = (
      (result.host || relative.host || srcPath.length > 1) &&
      (last === '.' || last === '..') || last === '');

  // strip single dots, resolve double dots to parent dir
  // if the path tries to go above the root, `up` ends up > 0
  var up = 0;
  for (var i = srcPath.length; i >= 0; i--) {
    last = srcPath[i];
    if (last === '.') {
      srcPath.splice(i, 1);
    } else if (last === '..') {
      srcPath.splice(i, 1);
      up++;
    } else if (up) {
      srcPath.splice(i, 1);
      up--;
    }
  }

  // if the path is allowed to go above the root, restore leading ..s
  if (!mustEndAbs && !removeAllDots) {
    for (; up--; up) {
      srcPath.unshift('..');
    }
  }

  if (mustEndAbs && srcPath[0] !== '' &&
      (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
    srcPath.unshift('');
  }

  if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
    srcPath.push('');
  }

  var isAbsolute = srcPath[0] === '' ||
      (srcPath[0] && srcPath[0].charAt(0) === '/');

  // put the host back
  if (psychotic) {
    result.hostname = result.host = isAbsolute ? '' :
                                    srcPath.length ? srcPath.shift() : '';
    //occationaly the auth can get stuck only in host
    //this especially happens in cases like
    //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
    var authInHost = result.host && result.host.indexOf('@') > 0 ?
                     result.host.split('@') : false;
    if (authInHost) {
      result.auth = authInHost.shift();
      result.host = result.hostname = authInHost.shift();
    }
  }

  mustEndAbs = mustEndAbs || (result.host && srcPath.length);

  if (mustEndAbs && !isAbsolute) {
    srcPath.unshift('');
  }

  if (!srcPath.length) {
    result.pathname = null;
    result.path = null;
  } else {
    result.pathname = srcPath.join('/');
  }

  //to support request.http
  if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
    result.path = (result.pathname ? result.pathname : '') +
                  (result.search ? result.search : '');
  }
  result.auth = relative.auth || result.auth;
  result.slashes = result.slashes || relative.slashes;
  result.href = result.format();
  return result;
};

Url.prototype.parseHost = function() {
  var host = this.host;
  var port = portPattern.exec(host);
  if (port) {
    port = port[0];
    if (port !== ':') {
      this.port = port.substr(1);
    }
    host = host.substr(0, host.length - port.length);
  }
  if (host) this.hostname = host;
};


/***/ }),

/***/ "D+M8":
/*!*********************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/codemirror/theme/base16-dark.css ***!
  \*********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*\n\n    Name:       Base16 Default Dark\n    Author:     Chris Kempson (http://chriskempson.com)\n\n    CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror)\n    Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16)\n\n*/\n\n.cm-s-base16-dark.CodeMirror { background: #151515; color: #e0e0e0; }\n.cm-s-base16-dark div.CodeMirror-selected { background: #303030; }\n.cm-s-base16-dark .CodeMirror-line::selection, .cm-s-base16-dark .CodeMirror-line > span::selection, .cm-s-base16-dark .CodeMirror-line > span > span::selection { background: rgba(48, 48, 48, .99); }\n.cm-s-base16-dark .CodeMirror-line::-moz-selection, .cm-s-base16-dark .CodeMirror-line > span::-moz-selection, .cm-s-base16-dark .CodeMirror-line > span > span::-moz-selection { background: rgba(48, 48, 48, .99); }\n.cm-s-base16-dark .CodeMirror-gutters { background: #151515; border-right: 0px; }\n.cm-s-base16-dark .CodeMirror-guttermarker { color: #ac4142; }\n.cm-s-base16-dark .CodeMirror-guttermarker-subtle { color: #505050; }\n.cm-s-base16-dark .CodeMirror-linenumber { color: #505050; }\n.cm-s-base16-dark .CodeMirror-cursor { border-left: 1px solid #b0b0b0; }\n\n.cm-s-base16-dark span.cm-comment { color: #8f5536; }\n.cm-s-base16-dark span.cm-atom { color: #aa759f; }\n.cm-s-base16-dark span.cm-number { color: #aa759f; }\n\n.cm-s-base16-dark span.cm-property, .cm-s-base16-dark span.cm-attribute { color: #90a959; }\n.cm-s-base16-dark span.cm-keyword { color: #ac4142; }\n.cm-s-base16-dark span.cm-string { color: #f4bf75; }\n\n.cm-s-base16-dark span.cm-variable { color: #90a959; }\n.cm-s-base16-dark span.cm-variable-2 { color: #6a9fb5; }\n.cm-s-base16-dark span.cm-def { color: #d28445; }\n.cm-s-base16-dark span.cm-bracket { color: #e0e0e0; }\n.cm-s-base16-dark span.cm-tag { color: #ac4142; }\n.cm-s-base16-dark span.cm-link { color: #aa759f; }\n.cm-s-base16-dark span.cm-error { background: #ac4142; color: #b0b0b0; }\n\n.cm-s-base16-dark .CodeMirror-activeline-background { background: #202020; }\n.cm-s-base16-dark .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; }\n", ""]);

// exports


/***/ }),

/***/ "D/JM":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/eu.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var eu = moment.defineLocale('eu', {
    months : 'urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua'.split('_'),
    monthsShort : 'urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.'.split('_'),
    monthsParseExact : true,
    weekdays : 'igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata'.split('_'),
    weekdaysShort : 'ig._al._ar._az._og._ol._lr.'.split('_'),
    weekdaysMin : 'ig_al_ar_az_og_ol_lr'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'YYYY-MM-DD',
        LL : 'YYYY[ko] MMMM[ren] D[a]',
        LLL : 'YYYY[ko] MMMM[ren] D[a] HH:mm',
        LLLL : 'dddd, YYYY[ko] MMMM[ren] D[a] HH:mm',
        l : 'YYYY-M-D',
        ll : 'YYYY[ko] MMM D[a]',
        lll : 'YYYY[ko] MMM D[a] HH:mm',
        llll : 'ddd, YYYY[ko] MMM D[a] HH:mm'
    },
    calendar : {
        sameDay : '[gaur] LT[etan]',
        nextDay : '[bihar] LT[etan]',
        nextWeek : 'dddd LT[etan]',
        lastDay : '[atzo] LT[etan]',
        lastWeek : '[aurreko] dddd LT[etan]',
        sameElse : 'L'
    },
    relativeTime : {
        future : '%s barru',
        past : 'duela %s',
        s : 'segundo batzuk',
        ss : '%d segundo',
        m : 'minutu bat',
        mm : '%d minutu',
        h : 'ordu bat',
        hh : '%d ordu',
        d : 'egun bat',
        dd : '%d egun',
        M : 'hilabete bat',
        MM : '%d hilabete',
        y : 'urte bat',
        yy : '%d urte'
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return eu;

})));


/***/ }),

/***/ "D1qR":
/*!*************************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/keyed_container.js ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var nestedProperty = __webpack_require__(/*! ./nested_property */ "oz8K");

var SIMPLE_PROPERTY_REGEX = /^\w*$/;

// bitmask for deciding what's updated. Sometimes the name needs to be updated,
// sometimes the value needs to be updated, and sometimes both do. This is just
// a simple way to track what's updated such that it's a simple OR operation to
// assimilate new updates.
//
// The only exception is the UNSET bit that tracks when we need to explicitly
// unset and remove the property. This concrn arises because of the special
// way in which nestedProperty handles null/undefined. When you specify `null`,
// it prunes any unused items in the tree. I ran into some issues with it getting
// null vs undefined confused, so UNSET is just a bit that forces the property
// update to send `null`, removing the property explicitly rather than setting
// it to undefined.
var NONE = 0;
var NAME = 1;
var VALUE = 2;
var BOTH = 3;
var UNSET = 4;

module.exports = function keyedContainer(baseObj, path, keyName, valueName) {
    keyName = keyName || 'name';
    valueName = valueName || 'value';
    var i, arr, baseProp;
    var changeTypes = {};

    if(path && path.length) {
        baseProp = nestedProperty(baseObj, path);
        arr = baseProp.get();
    } else {
        arr = baseObj;
    }

    path = path || '';

    // Construct an index:
    var indexLookup = {};
    if(arr) {
        for(i = 0; i < arr.length; i++) {
            indexLookup[arr[i][keyName]] = i;
        }
    }

    var isSimpleValueProp = SIMPLE_PROPERTY_REGEX.test(valueName);

    var obj = {
        set: function(name, value) {
            var changeType = value === null ? UNSET : NONE;

            // create the base array if necessary
            if(!arr) {
                if(!baseProp || changeType === UNSET) return;

                arr = [];
                baseProp.set(arr);
            }

            var idx = indexLookup[name];
            if(idx === undefined) {
                if(changeType === UNSET) return;

                changeType = changeType | BOTH;
                idx = arr.length;
                indexLookup[name] = idx;
            } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : nestedProperty(arr[idx], valueName).get())) {
                changeType = changeType | VALUE;
            }

            var newValue = arr[idx] = arr[idx] || {};
            newValue[keyName] = name;

            if(isSimpleValueProp) {
                newValue[valueName] = value;
            } else {
                nestedProperty(newValue, valueName).set(value);
            }

            // If it's not an unset, force that bit to be unset. This is all related to the fact
            // that undefined and null are a bit specially implemented in nestedProperties.
            if(value !== null) {
                changeType = changeType & ~UNSET;
            }

            changeTypes[idx] = changeTypes[idx] | changeType;

            return obj;
        },
        get: function(name) {
            if(!arr) return;

            var idx = indexLookup[name];

            if(idx === undefined) {
                return undefined;
            } else if(isSimpleValueProp) {
                return arr[idx][valueName];
            } else {
                return nestedProperty(arr[idx], valueName).get();
            }
        },
        rename: function(name, newName) {
            var idx = indexLookup[name];

            if(idx === undefined) return obj;
            changeTypes[idx] = changeTypes[idx] | NAME;

            indexLookup[newName] = idx;
            delete indexLookup[name];

            arr[idx][keyName] = newName;

            return obj;
        },
        remove: function(name) {
            var idx = indexLookup[name];

            if(idx === undefined) return obj;

            var object = arr[idx];
            if(Object.keys(object).length > 2) {
                // This object contains more than just the key/value, so unset
                // the value without modifying the entry otherwise:
                changeTypes[idx] = changeTypes[idx] | VALUE;
                return obj.set(name, null);
            }

            if(isSimpleValueProp) {
                for(i = idx; i < arr.length; i++) {
                    changeTypes[i] = changeTypes[i] | BOTH;
                }
                for(i = idx; i < arr.length; i++) {
                    indexLookup[arr[i][keyName]]--;
                }
                arr.splice(idx, 1);
                delete(indexLookup[name]);
            } else {
                // Perform this update *strictly* so we can check whether the result's
                // been pruned. If so, it's a removal. If not, it's a value unset only.
                nestedProperty(object, valueName).set(null);

                // Now check if the top level nested property has any keys left. If so,
                // the object still has values so we only want to unset the key. If not,
                // the entire object can be removed since there's no other data.
                // var topLevelKeys = Object.keys(object[valueName.split('.')[0]] || []);

                changeTypes[idx] = changeTypes[idx] | VALUE | UNSET;
            }

            return obj;
        },
        constructUpdate: function() {
            var astr, idx;
            var update = {};
            var changed = Object.keys(changeTypes);
            for(var i = 0; i < changed.length; i++) {
                idx = changed[i];
                astr = path + '[' + idx + ']';
                if(arr[idx]) {
                    if(changeTypes[idx] & NAME) {
                        update[astr + '.' + keyName] = arr[idx][keyName];
                    }
                    if(changeTypes[idx] & VALUE) {
                        if(isSimpleValueProp) {
                            update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : arr[idx][valueName];
                        } else {
                            update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : nestedProperty(arr[idx], valueName).get();
                        }
                    }
                } else {
                    update[astr] = null;
                }
            }

            return update;
        }
    };

    return obj;
};


/***/ }),

/***/ "D5Sy":
/*!****************************************!*\
  !*** ./node_modules/domutils/index.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var DomUtils = module.exports;

[
	__webpack_require__(/*! ./lib/stringify */ "aLRh"),
	__webpack_require__(/*! ./lib/traversal */ "JvmS"),
	__webpack_require__(/*! ./lib/manipulation */ "ejln"),
	__webpack_require__(/*! ./lib/querying */ "czxZ"),
	__webpack_require__(/*! ./lib/legacy */ "nyAU"),
	__webpack_require__(/*! ./lib/helpers */ "9n51")
].forEach(function(ext){
	Object.keys(ext).forEach(function(key){
		DomUtils[key] = ext[key].bind(DomUtils);
	});
});


/***/ }),

/***/ "D5hx":
/*!*******************************************!*\
  !*** ./node_modules/base16/lib/apathy.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'apathy',
  author: 'jannik siebert (https://github.com/janniks)',
  base00: '#031A16',
  base01: '#0B342D',
  base02: '#184E45',
  base03: '#2B685E',
  base04: '#5F9C92',
  base05: '#81B5AC',
  base06: '#A7CEC8',
  base07: '#D2E7E4',
  base08: '#3E9688',
  base09: '#3E7996',
  base0A: '#3E4C96',
  base0B: '#883E96',
  base0C: '#963E4C',
  base0D: '#96883E',
  base0E: '#4C963E',
  base0F: '#3E965B'
};
module.exports = exports['default'];

/***/ }),

/***/ "D8kY":
/*!********************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_to-absolute-index.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var toInteger = __webpack_require__(/*! ./_to-integer */ "Ojgd");
var max = Math.max;
var min = Math.min;
module.exports = function (index, length) {
  index = toInteger(index);
  return index < 0 ? max(index + length, 0) : min(index, length);
};


/***/ }),

/***/ "D9OR":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/launcher/style/index.css ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "nEUT");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "DE1x":
/*!****************************************************!*\
  !*** ./node_modules/mdi-react/GithubCircleIcon.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var GithubCircleIcon = function GithubCircleIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M12,2C6.48,2 2,6.48 2,12C2,16.42 4.87,20.17 8.84,21.5C9.34,21.58 9.5,21.27 9.5,21C9.5,20.77 9.5,20.14 9.5,19.31C6.73,19.91 6.14,17.97 6.14,17.97C5.68,16.81 5.03,16.5 5.03,16.5C4.12,15.88 5.1,15.9 5.1,15.9C6.1,15.97 6.63,16.93 6.63,16.93C7.5,18.45 8.97,18 9.54,17.76C9.63,17.11 9.89,16.67 10.17,16.42C7.95,16.17 5.62,15.31 5.62,11.5C5.62,10.39 6,9.5 6.65,8.79C6.55,8.54 6.2,7.5 6.75,6.15C6.75,6.15 7.59,5.88 9.5,7.17C10.29,6.95 11.15,6.84 12,6.84C12.85,6.84 13.71,6.95 14.5,7.17C16.41,5.88 17.25,6.15 17.25,6.15C17.8,7.5 17.45,8.54 17.35,8.79C18,9.5 18.38,10.39 18.38,11.5C18.38,15.32 16.04,16.16 13.81,16.41C14.17,16.72 14.5,17.33 14.5,18.26C14.5,19.6 14.5,20.68 14.5,21C14.5,21.27 14.66,21.59 15.17,21.5C19.14,20.16 22,16.42 22,12C22,6.48 17.52,2 12,2Z' })
  );
};

module.exports = GithubCircleIcon;


/***/ }),

/***/ "DEWG":
/*!***********************************************************!*\
  !*** ./node_modules/draft-js/lib/moveSelectionForward.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule moveSelectionForward
 * @format
 * 
 */



/**
 * Given a collapsed selection, move the focus `maxDistance` forward within
 * the selected block. If the selection will go beyond the end of the block,
 * move focus to the start of the next block, but no further.
 *
 * This function is not Unicode-aware, so surrogate pairs will be treated
 * as having length 2.
 */
function moveSelectionForward(editorState, maxDistance) {
  var selection = editorState.getSelection();
  var key = selection.getStartKey();
  var offset = selection.getStartOffset();
  var content = editorState.getCurrentContent();

  var focusKey = key;
  var focusOffset;

  var block = content.getBlockForKey(key);

  if (maxDistance > block.getText().length - offset) {
    focusKey = content.getKeyAfter(key);
    focusOffset = 0;
  } else {
    focusOffset = offset + maxDistance;
  }

  return selection.merge({ focusKey: focusKey, focusOffset: focusOffset });
}

module.exports = moveSelectionForward;

/***/ }),

/***/ "DKr+":
/*!************************************************!*\
  !*** ./node_modules/moment/locale/gom-latn.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


function processRelativeTime(number, withoutSuffix, key, isFuture) {
    var format = {
        's': ['thodde secondanim', 'thodde second'],
        'ss': [number + ' secondanim', number + ' second'],
        'm': ['eka mintan', 'ek minute'],
        'mm': [number + ' mintanim', number + ' mintam'],
        'h': ['eka horan', 'ek hor'],
        'hh': [number + ' horanim', number + ' hor'],
        'd': ['eka disan', 'ek dis'],
        'dd': [number + ' disanim', number + ' dis'],
        'M': ['eka mhoinean', 'ek mhoino'],
        'MM': [number + ' mhoineanim', number + ' mhoine'],
        'y': ['eka vorsan', 'ek voros'],
        'yy': [number + ' vorsanim', number + ' vorsam']
    };
    return withoutSuffix ? format[key][0] : format[key][1];
}

var gomLatn = moment.defineLocale('gom-latn', {
    months : 'Janer_Febrer_Mars_Abril_Mai_Jun_Julai_Agost_Setembr_Otubr_Novembr_Dezembr'.split('_'),
    monthsShort : 'Jan._Feb._Mars_Abr._Mai_Jun_Jul._Ago._Set._Otu._Nov._Dez.'.split('_'),
    monthsParseExact : true,
    weekdays : 'Aitar_Somar_Mongllar_Budvar_Brestar_Sukrar_Son\'var'.split('_'),
    weekdaysShort : 'Ait._Som._Mon._Bud._Bre._Suk._Son.'.split('_'),
    weekdaysMin : 'Ai_Sm_Mo_Bu_Br_Su_Sn'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'A h:mm [vazta]',
        LTS : 'A h:mm:ss [vazta]',
        L : 'DD-MM-YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY A h:mm [vazta]',
        LLLL : 'dddd, MMMM[achea] Do, YYYY, A h:mm [vazta]',
        llll: 'ddd, D MMM YYYY, A h:mm [vazta]'
    },
    calendar : {
        sameDay: '[Aiz] LT',
        nextDay: '[Faleam] LT',
        nextWeek: '[Ieta to] dddd[,] LT',
        lastDay: '[Kal] LT',
        lastWeek: '[Fatlo] dddd[,] LT',
        sameElse: 'L'
    },
    relativeTime : {
        future : '%s',
        past : '%s adim',
        s : processRelativeTime,
        ss : processRelativeTime,
        m : processRelativeTime,
        mm : processRelativeTime,
        h : processRelativeTime,
        hh : processRelativeTime,
        d : processRelativeTime,
        dd : processRelativeTime,
        M : processRelativeTime,
        MM : processRelativeTime,
        y : processRelativeTime,
        yy : processRelativeTime
    },
    dayOfMonthOrdinalParse : /\d{1,2}(er)/,
    ordinal : function (number, period) {
        switch (period) {
            // the ordinal 'er' only applies to day of the month
            case 'D':
                return number + 'er';
            default:
            case 'M':
            case 'Q':
            case 'DDD':
            case 'd':
            case 'w':
            case 'W':
                return number;
        }
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    },
    meridiemParse: /rati|sokalli|donparam|sanje/,
    meridiemHour : function (hour, meridiem) {
        if (hour === 12) {
            hour = 0;
        }
        if (meridiem === 'rati') {
            return hour < 4 ? hour : hour + 12;
        } else if (meridiem === 'sokalli') {
            return hour;
        } else if (meridiem === 'donparam') {
            return hour > 12 ? hour : hour + 12;
        } else if (meridiem === 'sanje') {
            return hour + 12;
        }
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 4) {
            return 'rati';
        } else if (hour < 12) {
            return 'sokalli';
        } else if (hour < 16) {
            return 'donparam';
        } else if (hour < 20) {
            return 'sanje';
        } else {
            return 'rati';
        }
    }
});

return gomLatn;

})));


/***/ }),

/***/ "DLvh":
/*!******************************************************!*\
  !*** ./node_modules/elliptic/lib/elliptic/curves.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var curves = exports;

var hash = __webpack_require__(/*! hash.js */ "fZJM");
var elliptic = __webpack_require__(/*! ../elliptic */ "MzeL");

var assert = elliptic.utils.assert;

function PresetCurve(options) {
  if (options.type === 'short')
    this.curve = new elliptic.curve.short(options);
  else if (options.type === 'edwards')
    this.curve = new elliptic.curve.edwards(options);
  else
    this.curve = new elliptic.curve.mont(options);
  this.g = this.curve.g;
  this.n = this.curve.n;
  this.hash = options.hash;

  assert(this.g.validate(), 'Invalid curve');
  assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');
}
curves.PresetCurve = PresetCurve;

function defineCurve(name, options) {
  Object.defineProperty(curves, name, {
    configurable: true,
    enumerable: true,
    get: function() {
      var curve = new PresetCurve(options);
      Object.defineProperty(curves, name, {
        configurable: true,
        enumerable: true,
        value: curve
      });
      return curve;
    }
  });
}

defineCurve('p192', {
  type: 'short',
  prime: 'p192',
  p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
  a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
  b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
  n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
  hash: hash.sha256,
  gRed: false,
  g: [
    '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
    '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'
  ]
});

defineCurve('p224', {
  type: 'short',
  prime: 'p224',
  p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
  a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
  b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
  n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
  hash: hash.sha256,
  gRed: false,
  g: [
    'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
    'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'
  ]
});

defineCurve('p256', {
  type: 'short',
  prime: null,
  p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
  a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
  b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
  n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
  hash: hash.sha256,
  gRed: false,
  g: [
    '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
    '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'
  ]
});

defineCurve('p384', {
  type: 'short',
  prime: null,
  p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
     'fffffffe ffffffff 00000000 00000000 ffffffff',
  a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
     'fffffffe ffffffff 00000000 00000000 fffffffc',
  b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +
     '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
  n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +
     'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
  hash: hash.sha384,
  gRed: false,
  g: [
    'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +
    '5502f25d bf55296c 3a545e38 72760ab7',
    '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +
    '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'
  ]
});

defineCurve('p521', {
  type: 'short',
  prime: null,
  p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
     'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
     'ffffffff ffffffff ffffffff ffffffff ffffffff',
  a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
     'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
     'ffffffff ffffffff ffffffff ffffffff fffffffc',
  b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +
     '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +
     '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
  n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
     'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +
     'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
  hash: hash.sha512,
  gRed: false,
  g: [
    '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +
    '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +
    'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',
    '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +
    '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +
    '3fad0761 353c7086 a272c240 88be9476 9fd16650'
  ]
});

defineCurve('curve25519', {
  type: 'mont',
  prime: 'p25519',
  p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
  a: '76d06',
  b: '1',
  n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
  hash: hash.sha256,
  gRed: false,
  g: [
    '9'
  ]
});

defineCurve('ed25519', {
  type: 'edwards',
  prime: 'p25519',
  p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
  a: '-1',
  c: '1',
  // -121665 * (121666^(-1)) (mod P)
  d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
  n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
  hash: hash.sha256,
  gRed: false,
  g: [
    '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',

    // 4/5
    '6666666666666666666666666666666666666666666666666666666666666658'
  ]
});

var pre;
try {
  pre = __webpack_require__(/*! ./precomputed/secp256k1 */ "QJsb");
} catch (e) {
  pre = undefined;
}

defineCurve('secp256k1', {
  type: 'short',
  prime: 'k256',
  p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
  a: '0',
  b: '7',
  n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
  h: '1',
  hash: hash.sha256,

  // Precomputed endomorphism
  beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
  lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
  basis: [
    {
      a: '3086d221a7d46bcde86c90e49284eb15',
      b: '-e4437ed6010e88286f547fa90abfe4c3'
    },
    {
      a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
      b: '3086d221a7d46bcde86c90e49284eb15'
    }
  ],

  gRed: false,
  g: [
    '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
    '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
    pre
  ]
});


/***/ }),

/***/ "DMSk":
/*!******************************************************!*\
  !*** ./node_modules/@phosphor/algorithm/lib/iter.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * Create an iterator for an iterable object.
 *
 * @param object - The iterable or array-like object of interest.
 *
 * @returns A new iterator for the given object.
 *
 * #### Notes
 * This function allows iteration algorithms to operate on user-defined
 * iterable types and builtin array-like objects in a uniform fashion.
 */
function iter(object) {
    var it;
    if (typeof object.iter === 'function') {
        it = object.iter();
    }
    else {
        it = new ArrayIterator(object);
    }
    return it;
}
exports.iter = iter;
/**
 * Invoke a function for each value in an iterable.
 *
 * @param object - The iterable or array-like object of interest.
 *
 * @param fn - The callback function to invoke for each value.
 *
 * #### Notes
 * Iteration can be terminated early by returning `false` from the
 * callback function.
 *
 * #### Complexity
 * Linear.
 *
 * #### Example
 * ```typescript
 * import { each } from '@phosphor/algorithm';
 *
 * let data = [5, 7, 0, -2, 9];
 *
 * each(data, value => { console.log(value); });
 * ```
 */
function each(object, fn) {
    var index = 0;
    var it = iter(object);
    var value;
    while ((value = it.next()) !== undefined) {
        if (fn(value, index++) === false) {
            return;
        }
    }
}
exports.each = each;
/**
 * Test whether all values in an iterable satisfy a predicate.
 *
 * @param object - The iterable or array-like object of interest.
 *
 * @param fn - The predicate function to invoke for each value.
 *
 * @returns `true` if all values pass the test, `false` otherwise.
 *
 * #### Notes
 * Iteration terminates on the first `false` predicate result.
 *
 * #### Complexity
 * Linear.
 *
 * #### Example
 * ```typescript
 * import { every } from '@phosphor/algorithm';
 *
 * let data = [5, 7, 1];
 *
 * every(data, value => value % 2 === 0);  // false
 * every(data, value => value % 2 === 1);  // true
 * ```
 */
function every(object, fn) {
    var index = 0;
    var it = iter(object);
    var value;
    while ((value = it.next()) !== undefined) {
        if (!fn(value, index++)) {
            return false;
        }
    }
    return true;
}
exports.every = every;
/**
 * Test whether any value in an iterable satisfies a predicate.
 *
 * @param object - The iterable or array-like object of interest.
 *
 * @param fn - The predicate function to invoke for each value.
 *
 * @returns `true` if any value passes the test, `false` otherwise.
 *
 * #### Notes
 * Iteration terminates on the first `true` predicate result.
 *
 * #### Complexity
 * Linear.
 *
 * #### Example
 * ```typescript
 * import { some } from '@phosphor/algorithm';
 *
 * let data = [5, 7, 1];
 *
 * some(data, value => value === 7);  // true
 * some(data, value => value === 3);  // false
 * ```
 */
function some(object, fn) {
    var index = 0;
    var it = iter(object);
    var value;
    while ((value = it.next()) !== undefined) {
        if (fn(value, index++)) {
            return true;
        }
    }
    return false;
}
exports.some = some;
/**
 * Create an array from an iterable of values.
 *
 * @param object - The iterable or array-like object of interest.
 *
 * @returns A new array of values from the given object.
 *
 * #### Example
 * ```typescript
 * import { iter, toArray } from '@phosphor/algorithm';
 *
 * let data = [1, 2, 3, 4, 5, 6];
 *
 * let stream = iter(data);
 *
 * toArray(stream);  // [1, 2, 3, 4, 5, 6];
 * ```
 */
function toArray(object) {
    var index = 0;
    var result = [];
    var it = iter(object);
    var value;
    while ((value = it.next()) !== undefined) {
        result[index++] = value;
    }
    return result;
}
exports.toArray = toArray;
/**
 * An iterator for an array-like object.
 *
 * #### Notes
 * This iterator can be used for any builtin JS array-like object.
 */
var ArrayIterator = (function () {
    /**
     * Construct a new array iterator.
     *
     * @param source - The array-like object of interest.
     */
    function ArrayIterator(source) {
        this._index = 0;
        this._source = source;
    }
    /**
     * Get an iterator over the object's values.
     *
     * @returns An iterator which yields the object's values.
     */
    ArrayIterator.prototype.iter = function () {
        return this;
    };
    /**
     * Create an independent clone of the iterator.
     *
     * @returns A new independent clone of the iterator.
     */
    ArrayIterator.prototype.clone = function () {
        var result = new ArrayIterator(this._source);
        result._index = this._index;
        return result;
    };
    /**
     * Get the next value from the iterator.
     *
     * @returns The next value from the iterator, or `undefined`.
     */
    ArrayIterator.prototype.next = function () {
        if (this._index >= this._source.length) {
            return undefined;
        }
        return this._source[this._index++];
    };
    return ArrayIterator;
}());
exports.ArrayIterator = ArrayIterator;


/***/ }),

/***/ "DNkW":
/*!*************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_is-integer.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// 20.1.2.3 Number.isInteger(number)
var isObject = __webpack_require__(/*! ./_is-object */ "93I4");
var floor = Math.floor;
module.exports = function isInteger(it) {
  return !isObject(it) && isFinite(it) && floor(it) === it;
};


/***/ }),

/***/ "DQoj":
/*!*****************************************************************!*\
  !*** ./node_modules/@jupyterlab/help-extension/style/index.css ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "YkW1");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "DRdP":
/*!******************************************************************************!*\
  !*** ./node_modules/react-color/lib/components/photoshop/PhotoshopButton.js ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.PhotoshopBotton = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PhotoshopBotton = exports.PhotoshopBotton = function PhotoshopBotton(_ref) {
  var onClick = _ref.onClick,
      label = _ref.label,
      children = _ref.children,
      active = _ref.active;

  var styles = (0, _reactcss2.default)({
    'default': {
      button: {
        backgroundImage: 'linear-gradient(-180deg, #FFFFFF 0%, #E6E6E6 100%)',
        border: '1px solid #878787',
        borderRadius: '2px',
        height: '20px',
        boxShadow: '0 1px 0 0 #EAEAEA',
        fontSize: '14px',
        color: '#000',
        lineHeight: '20px',
        textAlign: 'center',
        marginBottom: '10px',
        cursor: 'pointer'
      }
    },
    'active': {
      button: {
        boxShadow: '0 0 0 1px #878787'
      }
    }
  }, { active: active });

  return _react2.default.createElement(
    'div',
    { style: styles.button, onClick: onClick },
    label || children
  );
};

exports.default = PhotoshopBotton;

/***/ }),

/***/ "DSRE":
/*!*****************************************!*\
  !*** ./node_modules/lodash/isBuffer.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(/*! ./_root */ "Kz5y"),
    stubFalse = __webpack_require__(/*! ./stubFalse */ "B8du");

/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;

/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;

/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;

/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;

/**
 * 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;

module.exports = isBuffer;

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/module.js */ "YuTi")(module)))

/***/ }),

/***/ "DYKh":
/*!**************************************************************!*\
  !*** ./node_modules/draft-js/lib/getContentStateFragment.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule getContentStateFragment
 * @format
 * 
 */



var randomizeBlockMapKeys = __webpack_require__(/*! ./randomizeBlockMapKeys */ "V8dp");
var removeEntitiesAtEdges = __webpack_require__(/*! ./removeEntitiesAtEdges */ "bu5B");

var getContentStateFragment = function getContentStateFragment(contentState, selectionState) {
  var startKey = selectionState.getStartKey();
  var startOffset = selectionState.getStartOffset();
  var endKey = selectionState.getEndKey();
  var endOffset = selectionState.getEndOffset();

  // Edge entities should be stripped to ensure that we don't preserve
  // invalid partial entities when the fragment is reused. We do, however,
  // preserve entities that are entirely within the selection range.
  var contentWithoutEdgeEntities = removeEntitiesAtEdges(contentState, selectionState);

  var blockMap = contentWithoutEdgeEntities.getBlockMap();
  var blockKeys = blockMap.keySeq();
  var startIndex = blockKeys.indexOf(startKey);
  var endIndex = blockKeys.indexOf(endKey) + 1;

  return randomizeBlockMapKeys(blockMap.slice(startIndex, endIndex).map(function (block, blockKey) {
    var text = block.getText();
    var chars = block.getCharacterList();

    if (startKey === endKey) {
      return block.merge({
        text: text.slice(startOffset, endOffset),
        characterList: chars.slice(startOffset, endOffset)
      });
    }

    if (blockKey === startKey) {
      return block.merge({
        text: text.slice(startOffset),
        characterList: chars.slice(startOffset)
      });
    }

    if (blockKey === endKey) {
      return block.merge({
        text: text.slice(0, endOffset),
        characterList: chars.slice(0, endOffset)
      });
    }

    return block;
  }));
};

module.exports = getContentStateFragment;

/***/ }),

/***/ "DZkP":
/*!*********************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils/lib/dialog.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const vdom_1 = __webpack_require__(/*! ./vdom */ "PbVF");
const styling_1 = __webpack_require__(/*! ./styling */ "3g5F");
/**
 * Create and show a dialog.
 *
 * @param options - The dialog setup options.
 *
 * @returns A promise that resolves with whether the dialog was accepted.
 */
function showDialog(options = {}) {
    let dialog = new Dialog(options);
    return dialog.launch();
}
exports.showDialog = showDialog;
/**
 * Show an error message dialog.
 *
 * @param title - The title of the dialog box.
 *
 * @param error - the error to show in the dialog body (either a string
 *   or an object with a string `message` property).
 */
function showErrorMessage(title, error) {
    console.warn('Showing error:', error);
    return showDialog({
        title: title,
        body: error.message || title,
        buttons: [Dialog.okButton({ label: 'DISMISS' })]
    }).then(() => {
        /* no-op */
    });
}
exports.showErrorMessage = showErrorMessage;
/**
 * A modal dialog widget.
 */
class Dialog extends widgets_1.Widget {
    /**
     * Create a dialog panel instance.
     *
     * @param options - The dialog setup options.
     */
    constructor(options = {}) {
        super();
        this._focusNodeSelector = '';
        this.addClass('jp-Dialog');
        let normalized = Private.handleOptions(options);
        let renderer = normalized.renderer;
        this._host = normalized.host;
        this._defaultButton = normalized.defaultButton;
        this._buttons = normalized.buttons;
        this._buttonNodes = algorithm_1.toArray(algorithm_1.map(this._buttons, button => {
            return renderer.createButtonNode(button);
        }));
        let layout = (this.layout = new widgets_1.PanelLayout());
        let content = new widgets_1.Panel();
        content.addClass('jp-Dialog-content');
        layout.addWidget(content);
        this._body = normalized.body;
        let header = renderer.createHeader(normalized.title);
        let body = renderer.createBody(normalized.body);
        let footer = renderer.createFooter(this._buttonNodes);
        content.addWidget(header);
        content.addWidget(body);
        content.addWidget(footer);
        this._primary = this._buttonNodes[this._defaultButton];
        this._focusNodeSelector = options.focusNodeSelector;
    }
    /**
     * Dispose of the resources used by the dialog.
     */
    dispose() {
        const promise = this._promise;
        if (promise) {
            this._promise = null;
            promise.reject(void 0);
            algorithm_1.ArrayExt.removeFirstOf(Private.launchQueue, promise.promise);
        }
        super.dispose();
    }
    /**
     * Launch the dialog as a modal window.
     *
     * @returns a promise that resolves with the result of the dialog.
     */
    launch() {
        // Return the existing dialog if already open.
        if (this._promise) {
            return this._promise.promise;
        }
        const promise = (this._promise = new coreutils_1.PromiseDelegate());
        let promises = Promise.all(Private.launchQueue);
        Private.launchQueue.push(this._promise.promise);
        return promises.then(() => {
            widgets_1.Widget.attach(this, this._host);
            return promise.promise;
        });
    }
    /**
     * Resolve the current dialog.
     *
     * @param index - An optional index to the button to resolve.
     *
     * #### Notes
     * Will default to the defaultIndex.
     * Will resolve the current `show()` with the button value.
     * Will be a no-op if the dialog is not shown.
     */
    resolve(index) {
        if (!this._promise) {
            return;
        }
        if (index === undefined) {
            index = this._defaultButton;
        }
        this._resolve(this._buttons[index]);
    }
    /**
     * Reject the current dialog with a default reject value.
     *
     * #### Notes
     * Will be a no-op if the dialog is not shown.
     */
    reject() {
        if (!this._promise) {
            return;
        }
        this._resolve(Dialog.cancelButton());
    }
    /**
     * Handle the DOM events for the directory listing.
     *
     * @param event - The DOM event sent to the widget.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the panel's DOM node. It should
     * not be called directly by user code.
     */
    handleEvent(event) {
        switch (event.type) {
            case 'keydown':
                this._evtKeydown(event);
                break;
            case 'click':
                this._evtClick(event);
                break;
            case 'focus':
                this._evtFocus(event);
                break;
            case 'contextmenu':
                event.preventDefault();
                event.stopPropagation();
                break;
            default:
                break;
        }
    }
    /**
     *  A message handler invoked on an `'after-attach'` message.
     */
    onAfterAttach(msg) {
        let node = this.node;
        node.addEventListener('keydown', this, true);
        node.addEventListener('contextmenu', this, true);
        node.addEventListener('click', this, true);
        document.addEventListener('focus', this, true);
        this._first = Private.findFirstFocusable(this.node);
        this._original = document.activeElement;
        if (this._focusNodeSelector) {
            let body = this.node.querySelector('.jp-Dialog-body');
            let el = body.querySelector(this._focusNodeSelector);
            if (el) {
                this._primary = el;
            }
        }
        this._primary.focus();
    }
    /**
     *  A message handler invoked on an `'after-detach'` message.
     */
    onAfterDetach(msg) {
        let node = this.node;
        node.removeEventListener('keydown', this, true);
        node.removeEventListener('contextmenu', this, true);
        node.removeEventListener('click', this, true);
        document.removeEventListener('focus', this, true);
        this._original.focus();
    }
    /**
     * A message handler invoked on a `'close-request'` message.
     */
    onCloseRequest(msg) {
        if (this._promise) {
            this.reject();
        }
        super.onCloseRequest(msg);
    }
    /**
     * Handle the `'click'` event for a dialog button.
     *
     * @param event - The DOM event sent to the widget
     */
    _evtClick(event) {
        let content = this.node.getElementsByClassName('jp-Dialog-content')[0];
        if (!content.contains(event.target)) {
            event.stopPropagation();
            event.preventDefault();
            return;
        }
        for (let buttonNode of this._buttonNodes) {
            if (buttonNode.contains(event.target)) {
                let index = this._buttonNodes.indexOf(buttonNode);
                this.resolve(index);
            }
        }
    }
    /**
     * Handle the `'keydown'` event for the widget.
     *
     * @param event - The DOM event sent to the widget
     */
    _evtKeydown(event) {
        // Check for escape key
        switch (event.keyCode) {
            case 27: // Escape.
                event.stopPropagation();
                event.preventDefault();
                this.reject();
                break;
            case 9: // Tab.
                // Handle a tab on the last button.
                let node = this._buttonNodes[this._buttons.length - 1];
                if (document.activeElement === node && !event.shiftKey) {
                    event.stopPropagation();
                    event.preventDefault();
                    this._first.focus();
                }
                break;
            case 13: // Enter.
                event.stopPropagation();
                event.preventDefault();
                this.resolve();
                break;
            default:
                break;
        }
    }
    /**
     * Handle the `'focus'` event for the widget.
     *
     * @param event - The DOM event sent to the widget
     */
    _evtFocus(event) {
        let target = event.target;
        if (!this.node.contains(target)) {
            event.stopPropagation();
            this._buttonNodes[this._defaultButton].focus();
        }
    }
    /**
     * Resolve a button item.
     */
    _resolve(button) {
        // Prevent loopback.
        const promise = this._promise;
        if (!promise) {
            this.dispose();
            return;
        }
        this._promise = null;
        algorithm_1.ArrayExt.removeFirstOf(Private.launchQueue, promise.promise);
        let body = this._body;
        let value = null;
        if (button.accept &&
            body instanceof widgets_1.Widget &&
            typeof body.getValue === 'function') {
            value = body.getValue();
        }
        this.dispose();
        promise.resolve({ button, value });
    }
}
exports.Dialog = Dialog;
/**
 * The namespace for Dialog class statics.
 */
(function (Dialog) {
    /**
     * Create an accept button.
     */
    function okButton(options = {}) {
        options.accept = true;
        return createButton(options);
    }
    Dialog.okButton = okButton;
    /**
     * Create a reject button.
     */
    function cancelButton(options = {}) {
        options.accept = false;
        return createButton(options);
    }
    Dialog.cancelButton = cancelButton;
    /**
     * Create a warn button.
     */
    function warnButton(options = {}) {
        options.displayType = 'warn';
        return createButton(options);
    }
    Dialog.warnButton = warnButton;
    /**
     * Create a button item.
     */
    function createButton(value) {
        value.accept = value.accept !== false;
        let defaultLabel = value.accept ? 'OK' : 'CANCEL';
        return {
            label: value.label || defaultLabel,
            iconClass: value.iconClass || '',
            iconLabel: value.iconLabel || '',
            caption: value.caption || '',
            className: value.className || '',
            accept: value.accept,
            displayType: value.displayType || 'default'
        };
    }
    Dialog.createButton = createButton;
    /**
     * The default implementation of a dialog renderer.
     */
    class Renderer {
        /**
         * Create the header of the dialog.
         *
         * @param title - The title of the dialog.
         *
         * @returns A widget for the dialog header.
         */
        createHeader(title) {
            let header;
            if (typeof title === 'string') {
                header = new widgets_1.Widget({ node: document.createElement('span') });
                header.node.textContent = title;
            }
            else {
                header = new vdom_1.ReactElementWidget(title);
            }
            header.addClass('jp-Dialog-header');
            styling_1.Styling.styleNode(header.node);
            return header;
        }
        /**
         * Create the body of the dialog.
         *
         * @param value - The input value for the body.
         *
         * @returns A widget for the body.
         */
        createBody(value) {
            let body;
            if (typeof value === 'string') {
                body = new widgets_1.Widget({ node: document.createElement('span') });
                body.node.textContent = value;
            }
            else if (value instanceof widgets_1.Widget) {
                body = value;
            }
            else {
                body = new vdom_1.ReactElementWidget(value);
                // Immediately update the body even though it has not yet attached in
                // order to trigger a render of the DOM nodes from the React element.
                messaging_1.MessageLoop.sendMessage(body, widgets_1.Widget.Msg.UpdateRequest);
            }
            body.addClass('jp-Dialog-body');
            styling_1.Styling.styleNode(body.node);
            return body;
        }
        /**
         * Create the footer of the dialog.
         *
         * @param buttonNodes - The buttons nodes to add to the footer.
         *
         * @returns A widget for the footer.
         */
        createFooter(buttons) {
            let footer = new widgets_1.Widget();
            footer.addClass('jp-Dialog-footer');
            algorithm_1.each(buttons, button => {
                footer.node.appendChild(button);
            });
            styling_1.Styling.styleNode(footer.node);
            return footer;
        }
        /**
         * Create a button node for the dialog.
         *
         * @param button - The button data.
         *
         * @returns A node for the button.
         */
        createButtonNode(button) {
            const e = document.createElement('button');
            e.className = this.createItemClass(button);
            e.appendChild(this.renderIcon(button));
            e.appendChild(this.renderLabel(button));
            return e;
        }
        /**
         * Create the class name for the button.
         *
         * @param data - The data to use for the class name.
         *
         * @returns The full class name for the button.
         */
        createItemClass(data) {
            // Setup the initial class name.
            let name = 'jp-Dialog-button';
            // Add the other state classes.
            if (data.accept) {
                name += ' jp-mod-accept';
            }
            else {
                name += ' jp-mod-reject';
            }
            if (data.displayType === 'warn') {
                name += ' jp-mod-warn';
            }
            // Add the extra class.
            let extra = data.className;
            if (extra) {
                name += ` ${extra}`;
            }
            // Return the complete class name.
            return name;
        }
        /**
         * Render an icon element for a dialog item.
         *
         * @param data - The data to use for rendering the icon.
         *
         * @returns An HTML element representing the icon.
         */
        renderIcon(data) {
            const e = document.createElement('div');
            e.className = this.createIconClass(data);
            e.appendChild(document.createTextNode(data.iconLabel));
            return e;
        }
        /**
         * Create the class name for the button icon.
         *
         * @param data - The data to use for the class name.
         *
         * @returns The full class name for the item icon.
         */
        createIconClass(data) {
            let name = 'jp-Dialog-buttonIcon';
            let extra = data.iconClass;
            return extra ? `${name} ${extra}` : name;
        }
        /**
         * Render the label element for a button.
         *
         * @param data - The data to use for rendering the label.
         *
         * @returns An HTML element representing the item label.
         */
        renderLabel(data) {
            const e = document.createElement('div');
            e.className = 'jp-Dialog-buttonLabel';
            e.title = data.caption;
            e.appendChild(document.createTextNode(data.label));
            return e;
        }
    }
    Dialog.Renderer = Renderer;
    /**
     * The default renderer instance.
     */
    Dialog.defaultRenderer = new Renderer();
})(Dialog = exports.Dialog || (exports.Dialog = {}));
/**
 * The namespace for module private data.
 */
var Private;
(function (Private) {
    /**
     * The queue for launching dialogs.
     */
    Private.launchQueue = [];
    /**
     * Handle the input options for a dialog.
     *
     * @param options - The input options.
     *
     * @returns A new options object with defaults applied.
     */
    function handleOptions(options = {}) {
        let buttons = options.buttons || [Dialog.cancelButton(), Dialog.okButton()];
        let defaultButton = buttons.length - 1;
        if (options.defaultButton !== undefined) {
            defaultButton = options.defaultButton;
        }
        return {
            title: options.title || '',
            body: options.body || '',
            host: options.host || document.body,
            buttons,
            defaultButton,
            renderer: options.renderer || Dialog.defaultRenderer,
            focusNodeSelector: options.focusNodeSelector || ''
        };
    }
    Private.handleOptions = handleOptions;
    /**
     *  Find the first focusable item in the dialog.
     */
    function findFirstFocusable(node) {
        let candidateSelectors = [
            'input',
            'select',
            'a[href]',
            'textarea',
            'button',
            '[tabindex]'
        ].join(',');
        return node.querySelectorAll(candidateSelectors)[0];
    }
    Private.findFirstFocusable = findFirstFocusable;
})(Private || (Private = {}));


/***/ }),

/***/ "DaRl":
/*!********************************************!*\
  !*** ./node_modules/des.js/lib/des/cbc.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var assert = __webpack_require__(/*! minimalistic-assert */ "2j6C");
var inherits = __webpack_require__(/*! inherits */ "P7XM");

var proto = {};

function CBCState(iv) {
  assert.equal(iv.length, 8, 'Invalid IV length');

  this.iv = new Array(8);
  for (var i = 0; i < this.iv.length; i++)
    this.iv[i] = iv[i];
}

function instantiate(Base) {
  function CBC(options) {
    Base.call(this, options);
    this._cbcInit();
  }
  inherits(CBC, Base);

  var keys = Object.keys(proto);
  for (var i = 0; i < keys.length; i++) {
    var key = keys[i];
    CBC.prototype[key] = proto[key];
  }

  CBC.create = function create(options) {
    return new CBC(options);
  };

  return CBC;
}

exports.instantiate = instantiate;

proto._cbcInit = function _cbcInit() {
  var state = new CBCState(this.options.iv);
  this._cbcState = state;
};

proto._update = function _update(inp, inOff, out, outOff) {
  var state = this._cbcState;
  var superProto = this.constructor.super_.prototype;

  var iv = state.iv;
  if (this.type === 'encrypt') {
    for (var i = 0; i < this.blockSize; i++)
      iv[i] ^= inp[inOff + i];

    superProto._update.call(this, iv, 0, out, outOff);

    for (var i = 0; i < this.blockSize; i++)
      iv[i] = out[outOff + i];
  } else {
    superProto._update.call(this, inp, inOff, out, outOff);

    for (var i = 0; i < this.blockSize; i++)
      out[outOff + i] ^= iv[i];

    for (var i = 0; i < this.blockSize; i++)
      iv[i] = inp[inOff + i];
  }
};


/***/ }),

/***/ "Dblc":
/*!******************************************************!*\
  !*** ./node_modules/@phosphor/datagrid/lib/index.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
__export(__webpack_require__(/*! ./cellrenderer */ "Cnx3"));
__export(__webpack_require__(/*! ./datagrid */ "nGDH"));
__export(__webpack_require__(/*! ./datamodel */ "y5KU"));
__export(__webpack_require__(/*! ./graphicscontext */ "8n10"));
__export(__webpack_require__(/*! ./jsonmodel */ "RFJM"));
__export(__webpack_require__(/*! ./renderermap */ "gAjT"));
__export(__webpack_require__(/*! ./textrenderer */ "XoP6"));


/***/ }),

/***/ "DdeV":
/*!*******************************************************************************!*\
  !*** ./node_modules/plotly.js/src/components/colorscale/layout_attributes.js ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var scales = __webpack_require__(/*! ./scales */ "SFLx").scales;

var msg = 'Note that `autocolorscale` must be true for this attribute to work.';

module.exports = {
    editType: 'calc',
    sequential: {
        valType: 'colorscale',
        dflt: scales.Reds,
        role: 'style',
        editType: 'calc',
        description: [
            'Sets the default sequential colorscale for positive values.',
            msg
        ].join(' ')
    },
    sequentialminus: {
        valType: 'colorscale',
        dflt: scales.Blues,
        role: 'style',
        editType: 'calc',
        description: [
            'Sets the default sequential colorscale for negative values.',
            msg
        ].join(' ')
    },
    diverging: {
        valType: 'colorscale',
        dflt: scales.RdBu,
        role: 'style',
        editType: 'calc',
        description: [
            'Sets the default diverging colorscale.',
            msg
        ].join(' ')
    }
};


/***/ }),

/***/ "DeIs":
/*!****************************************************!*\
  !*** ./node_modules/fbjs/lib/getScrollPosition.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks
 */



var getDocumentScrollElement = __webpack_require__(/*! ./getDocumentScrollElement */ "83KV");
var getUnboundedScrollPosition = __webpack_require__(/*! ./getUnboundedScrollPosition */ "MxAa");

/**
 * Gets the scroll position of the supplied element or window.
 *
 * The return values are bounded. This means that if the scroll position is
 * negative or exceeds the element boundaries (which is possible using inertial
 * scrolling), you will get zero or the maximum scroll position, respectively.
 *
 * If you need the unbound scroll position, use `getUnboundedScrollPosition`.
 *
 * @param {DOMWindow|DOMElement} scrollable
 * @return {object} Map with `x` and `y` keys.
 */
function getScrollPosition(scrollable) {
  var documentScrollElement = getDocumentScrollElement(scrollable.ownerDocument || scrollable.document);
  if (scrollable.Window && scrollable instanceof scrollable.Window) {
    scrollable = documentScrollElement;
  }
  var scrollPosition = getUnboundedScrollPosition(scrollable);

  var viewport = scrollable === documentScrollElement ? scrollable.ownerDocument.documentElement : scrollable;

  var xMax = scrollable.scrollWidth - viewport.clientWidth;
  var yMax = scrollable.scrollHeight - viewport.clientHeight;

  scrollPosition.x = Math.max(0, Math.min(scrollPosition.x, xMax));
  scrollPosition.y = Math.max(0, Math.min(scrollPosition.y, yMax));

  return scrollPosition;
}

module.exports = getScrollPosition;

/***/ }),

/***/ "DfxN":
/*!******************************************!*\
  !*** ./node_modules/base16/lib/mocha.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'mocha',
  author: 'chris kempson (http://chriskempson.com)',
  base00: '#3B3228',
  base01: '#534636',
  base02: '#645240',
  base03: '#7e705a',
  base04: '#b8afad',
  base05: '#d0c8c6',
  base06: '#e9e1dd',
  base07: '#f5eeeb',
  base08: '#cb6077',
  base09: '#d28b71',
  base0A: '#f4bc87',
  base0B: '#beb55b',
  base0C: '#7bbda4',
  base0D: '#8ab3b5',
  base0E: '#a89bb9',
  base0F: '#bb9584'
};
module.exports = exports['default'];

/***/ }),

/***/ "Dg32":
/*!*************************************************************!*\
  !*** ./node_modules/ajv/lib/refs/json-schema-draft-06.json ***!
  \*************************************************************/
/*! exports provided: $schema, $id, title, definitions, type, properties, default */
/***/ (function(module) {

module.exports = {"$schema":"http://json-schema.org/draft-06/schema#","$id":"http://json-schema.org/draft-06/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"title":{"type":"string"},"description":{"type":"string"},"default":{},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":{}},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":{},"enum":{"type":"array","minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":{}};

/***/ }),

/***/ "Dkky":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/fr-ch.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var frCh = moment.defineLocale('fr-ch', {
    months : 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'),
    monthsShort : 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'),
    monthsParseExact : true,
    weekdays : 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),
    weekdaysShort : 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'),
    weekdaysMin : 'di_lu_ma_me_je_ve_sa'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay : '[Aujourd’hui à] LT',
        nextDay : '[Demain à] LT',
        nextWeek : 'dddd [à] LT',
        lastDay : '[Hier à] LT',
        lastWeek : 'dddd [dernier à] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'dans %s',
        past : 'il y a %s',
        s : 'quelques secondes',
        ss : '%d secondes',
        m : 'une minute',
        mm : '%d minutes',
        h : 'une heure',
        hh : '%d heures',
        d : 'un jour',
        dd : '%d jours',
        M : 'un mois',
        MM : '%d mois',
        y : 'un an',
        yy : '%d ans'
    },
    dayOfMonthOrdinalParse: /\d{1,2}(er|e)/,
    ordinal : function (number, period) {
        switch (period) {
            // Words with masculine grammatical gender: mois, trimestre, jour
            default:
            case 'M':
            case 'Q':
            case 'D':
            case 'DDD':
            case 'd':
                return number + (number === 1 ? 'er' : 'e');

            // Words with feminine grammatical gender: semaine
            case 'w':
            case 'W':
                return number + (number === 1 ? 're' : 'e');
        }
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return frCh;

})));


/***/ }),

/***/ "DlQD":
/*!*******************************************!*\
  !*** ./node_modules/marked/lib/marked.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global) {/**
 * marked - a markdown parser
 * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
 * https://github.com/markedjs/marked
 */

;(function(root) {
'use strict';

/**
 * Block-Level Grammar
 */

var block = {
  newline: /^\n+/,
  code: /^( {4}[^\n]+\n*)+/,
  fences: noop,
  hr: /^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/,
  heading: /^ *(#{1,6}) *([^\n]+?) *(?:#+ *)?(?:\n+|$)/,
  nptable: noop,
  blockquote: /^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,
  list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
  html: '^ {0,3}(?:' // optional indentation
    + '<(script|pre|style)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)' // (1)
    + '|comment[^\\n]*(\\n+|$)' // (2)
    + '|<\\?[\\s\\S]*?\\?>\\n*' // (3)
    + '|<![A-Z][\\s\\S]*?>\\n*' // (4)
    + '|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>\\n*' // (5)
    + '|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:\\n{2,}|$)' // (6)
    + '|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=\\h*\\n)[\\s\\S]*?(?:\\n{2,}|$)' // (7) open tag
    + '|</(?!script|pre|style)[a-z][\\w-]*\\s*>(?=\\h*\\n)[\\s\\S]*?(?:\\n{2,}|$)' // (7) closing tag
    + ')',
  def: /^ {0,3}\[(label)\]: *\n? *<?([^\s>]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/,
  table: noop,
  lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
  paragraph: /^([^\n]+(?:\n(?!hr|heading|lheading| {0,3}>|<\/?(?:tag)(?: +|\n|\/?>)|<(?:script|pre|style|!--))[^\n]+)*)/,
  text: /^[^\n]+/
};

block._label = /(?!\s*\])(?:\\[\[\]]|[^\[\]])+/;
block._title = /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/;
block.def = edit(block.def)
  .replace('label', block._label)
  .replace('title', block._title)
  .getRegex();

block.bullet = /(?:[*+-]|\d+\.)/;
block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
block.item = edit(block.item, 'gm')
  .replace(/bull/g, block.bullet)
  .getRegex();

block.list = edit(block.list)
  .replace(/bull/g, block.bullet)
  .replace('hr', '\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))')
  .replace('def', '\\n+(?=' + block.def.source + ')')
  .getRegex();

block._tag = 'address|article|aside|base|basefont|blockquote|body|caption'
  + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption'
  + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe'
  + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option'
  + '|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr'
  + '|track|ul';
block._comment = /<!--(?!-?>)[\s\S]*?-->/;
block.html = edit(block.html, 'i')
  .replace('comment', block._comment)
  .replace('tag', block._tag)
  .replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/)
  .getRegex();

block.paragraph = edit(block.paragraph)
  .replace('hr', block.hr)
  .replace('heading', block.heading)
  .replace('lheading', block.lheading)
  .replace('tag', block._tag) // pars can be interrupted by type (6) html blocks
  .getRegex();

block.blockquote = edit(block.blockquote)
  .replace('paragraph', block.paragraph)
  .getRegex();

/**
 * Normal Block Grammar
 */

block.normal = merge({}, block);

/**
 * GFM Block Grammar
 */

block.gfm = merge({}, block.normal, {
  fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\n? *\1 *(?:\n+|$)/,
  paragraph: /^/,
  heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
});

block.gfm.paragraph = edit(block.paragraph)
  .replace('(?!', '(?!'
    + block.gfm.fences.source.replace('\\1', '\\2') + '|'
    + block.list.source.replace('\\1', '\\3') + '|')
  .getRegex();

/**
 * GFM + Tables Block Grammar
 */

block.tables = merge({}, block.gfm, {
  nptable: /^ *([^|\n ].*\|.*)\n *([-:]+ *\|[-| :]*)(?:\n((?:.*[^>\n ].*(?:\n|$))*)\n*|$)/,
  table: /^ *\|(.+)\n *\|?( *[-:]+[-| :]*)(?:\n((?: *[^>\n ].*(?:\n|$))*)\n*|$)/
});

/**
 * Pedantic grammar
 */

block.pedantic = merge({}, block.normal, {
  html: edit(
    '^ *(?:comment *(?:\\n|\\s*$)'
    + '|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)' // closed tag
    + '|<tag(?:"[^"]*"|\'[^\']*\'|\\s[^\'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))')
    .replace('comment', block._comment)
    .replace(/tag/g, '(?!(?:'
      + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub'
      + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)'
      + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b')
    .getRegex(),
  def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/
});

/**
 * Block Lexer
 */

function Lexer(options) {
  this.tokens = [];
  this.tokens.links = {};
  this.options = options || marked.defaults;
  this.rules = block.normal;

  if (this.options.pedantic) {
    this.rules = block.pedantic;
  } else if (this.options.gfm) {
    if (this.options.tables) {
      this.rules = block.tables;
    } else {
      this.rules = block.gfm;
    }
  }
}

/**
 * Expose Block Rules
 */

Lexer.rules = block;

/**
 * Static Lex Method
 */

Lexer.lex = function(src, options) {
  var lexer = new Lexer(options);
  return lexer.lex(src);
};

/**
 * Preprocessing
 */

Lexer.prototype.lex = function(src) {
  src = src
    .replace(/\r\n|\r/g, '\n')
    .replace(/\t/g, '    ')
    .replace(/\u00a0/g, ' ')
    .replace(/\u2424/g, '\n');

  return this.token(src, true);
};

/**
 * Lexing
 */

Lexer.prototype.token = function(src, top) {
  src = src.replace(/^ +$/gm, '');
  var next,
      loose,
      cap,
      bull,
      b,
      item,
      space,
      i,
      tag,
      l,
      isordered,
      istask,
      ischecked;

  while (src) {
    // newline
    if (cap = this.rules.newline.exec(src)) {
      src = src.substring(cap[0].length);
      if (cap[0].length > 1) {
        this.tokens.push({
          type: 'space'
        });
      }
    }

    // code
    if (cap = this.rules.code.exec(src)) {
      src = src.substring(cap[0].length);
      cap = cap[0].replace(/^ {4}/gm, '');
      this.tokens.push({
        type: 'code',
        text: !this.options.pedantic
          ? cap.replace(/\n+$/, '')
          : cap
      });
      continue;
    }

    // fences (gfm)
    if (cap = this.rules.fences.exec(src)) {
      src = src.substring(cap[0].length);
      this.tokens.push({
        type: 'code',
        lang: cap[2],
        text: cap[3] || ''
      });
      continue;
    }

    // heading
    if (cap = this.rules.heading.exec(src)) {
      src = src.substring(cap[0].length);
      this.tokens.push({
        type: 'heading',
        depth: cap[1].length,
        text: cap[2]
      });
      continue;
    }

    // table no leading pipe (gfm)
    if (top && (cap = this.rules.nptable.exec(src))) {
      item = {
        type: 'table',
        header: splitCells(cap[1].replace(/^ *| *\| *$/g, '')),
        align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
        cells: cap[3] ? cap[3].replace(/\n$/, '').split('\n') : []
      };

      if (item.header.length === item.align.length) {
        src = src.substring(cap[0].length);

        for (i = 0; i < item.align.length; i++) {
          if (/^ *-+: *$/.test(item.align[i])) {
            item.align[i] = 'right';
          } else if (/^ *:-+: *$/.test(item.align[i])) {
            item.align[i] = 'center';
          } else if (/^ *:-+ *$/.test(item.align[i])) {
            item.align[i] = 'left';
          } else {
            item.align[i] = null;
          }
        }

        for (i = 0; i < item.cells.length; i++) {
          item.cells[i] = splitCells(item.cells[i], item.header.length);
        }

        this.tokens.push(item);

        continue;
      }
    }

    // hr
    if (cap = this.rules.hr.exec(src)) {
      src = src.substring(cap[0].length);
      this.tokens.push({
        type: 'hr'
      });
      continue;
    }

    // blockquote
    if (cap = this.rules.blockquote.exec(src)) {
      src = src.substring(cap[0].length);

      this.tokens.push({
        type: 'blockquote_start'
      });

      cap = cap[0].replace(/^ *> ?/gm, '');

      // Pass `top` to keep the current
      // "toplevel" state. This is exactly
      // how markdown.pl works.
      this.token(cap, top);

      this.tokens.push({
        type: 'blockquote_end'
      });

      continue;
    }

    // list
    if (cap = this.rules.list.exec(src)) {
      src = src.substring(cap[0].length);
      bull = cap[2];
      isordered = bull.length > 1;

      this.tokens.push({
        type: 'list_start',
        ordered: isordered,
        start: isordered ? +bull : ''
      });

      // Get each top-level item.
      cap = cap[0].match(this.rules.item);

      next = false;
      l = cap.length;
      i = 0;

      for (; i < l; i++) {
        item = cap[i];

        // Remove the list item's bullet
        // so it is seen as the next token.
        space = item.length;
        item = item.replace(/^ *([*+-]|\d+\.) +/, '');

        // Outdent whatever the
        // list item contains. Hacky.
        if (~item.indexOf('\n ')) {
          space -= item.length;
          item = !this.options.pedantic
            ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
            : item.replace(/^ {1,4}/gm, '');
        }

        // Determine whether the next list item belongs here.
        // Backpedal if it does not belong in this list.
        if (this.options.smartLists && i !== l - 1) {
          b = block.bullet.exec(cap[i + 1])[0];
          if (bull !== b && !(bull.length > 1 && b.length > 1)) {
            src = cap.slice(i + 1).join('\n') + src;
            i = l - 1;
          }
        }

        // Determine whether item is loose or not.
        // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
        // for discount behavior.
        loose = next || /\n\n(?!\s*$)/.test(item);
        if (i !== l - 1) {
          next = item.charAt(item.length - 1) === '\n';
          if (!loose) loose = next;
        }

        // Check for task list items
        istask = /^\[[ xX]\] /.test(item);
        ischecked = undefined;
        if (istask) {
          ischecked = item[1] !== ' ';
          item = item.replace(/^\[[ xX]\] +/, '');
        }

        this.tokens.push({
          type: loose
            ? 'loose_item_start'
            : 'list_item_start',
          task: istask,
          checked: ischecked
        });

        // Recurse.
        this.token(item, false);

        this.tokens.push({
          type: 'list_item_end'
        });
      }

      this.tokens.push({
        type: 'list_end'
      });

      continue;
    }

    // html
    if (cap = this.rules.html.exec(src)) {
      src = src.substring(cap[0].length);
      this.tokens.push({
        type: this.options.sanitize
          ? 'paragraph'
          : 'html',
        pre: !this.options.sanitizer
          && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
        text: cap[0]
      });
      continue;
    }

    // def
    if (top && (cap = this.rules.def.exec(src))) {
      src = src.substring(cap[0].length);
      if (cap[3]) cap[3] = cap[3].substring(1, cap[3].length - 1);
      tag = cap[1].toLowerCase().replace(/\s+/g, ' ');
      if (!this.tokens.links[tag]) {
        this.tokens.links[tag] = {
          href: cap[2],
          title: cap[3]
        };
      }
      continue;
    }

    // table (gfm)
    if (top && (cap = this.rules.table.exec(src))) {
      item = {
        type: 'table',
        header: splitCells(cap[1].replace(/^ *| *\| *$/g, '')),
        align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
        cells: cap[3] ? cap[3].replace(/(?: *\| *)?\n$/, '').split('\n') : []
      };

      if (item.header.length === item.align.length) {
        src = src.substring(cap[0].length);

        for (i = 0; i < item.align.length; i++) {
          if (/^ *-+: *$/.test(item.align[i])) {
            item.align[i] = 'right';
          } else if (/^ *:-+: *$/.test(item.align[i])) {
            item.align[i] = 'center';
          } else if (/^ *:-+ *$/.test(item.align[i])) {
            item.align[i] = 'left';
          } else {
            item.align[i] = null;
          }
        }

        for (i = 0; i < item.cells.length; i++) {
          item.cells[i] = splitCells(
            item.cells[i].replace(/^ *\| *| *\| *$/g, ''),
            item.header.length);
        }

        this.tokens.push(item);

        continue;
      }
    }

    // lheading
    if (cap = this.rules.lheading.exec(src)) {
      src = src.substring(cap[0].length);
      this.tokens.push({
        type: 'heading',
        depth: cap[2] === '=' ? 1 : 2,
        text: cap[1]
      });
      continue;
    }

    // top-level paragraph
    if (top && (cap = this.rules.paragraph.exec(src))) {
      src = src.substring(cap[0].length);
      this.tokens.push({
        type: 'paragraph',
        text: cap[1].charAt(cap[1].length - 1) === '\n'
          ? cap[1].slice(0, -1)
          : cap[1]
      });
      continue;
    }

    // text
    if (cap = this.rules.text.exec(src)) {
      // Top-level should never reach here.
      src = src.substring(cap[0].length);
      this.tokens.push({
        type: 'text',
        text: cap[0]
      });
      continue;
    }

    if (src) {
      throw new Error('Infinite loop on byte: ' + src.charCodeAt(0));
    }
  }

  return this.tokens;
};

/**
 * Inline-Level Grammar
 */

var inline = {
  escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,
  autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/,
  url: noop,
  tag: '^comment'
    + '|^</[a-zA-Z][\\w:-]*\\s*>' // self-closing tag
    + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag
    + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. <?php ?>
    + '|^<![a-zA-Z]+\\s[\\s\\S]*?>' // declaration, e.g. <!DOCTYPE html>
    + '|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>', // CDATA section
  link: /^!?\[(label)\]\(href(?:\s+(title))?\s*\)/,
  reflink: /^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/,
  nolink: /^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/,
  strong: /^__([^\s][\s\S]*?[^\s])__(?!_)|^\*\*([^\s][\s\S]*?[^\s])\*\*(?!\*)|^__([^\s])__(?!_)|^\*\*([^\s])\*\*(?!\*)/,
  em: /^_([^\s][\s\S]*?[^\s_])_(?!_)|^_([^\s_][\s\S]*?[^\s])_(?!_)|^\*([^\s][\s\S]*?[^\s*])\*(?!\*)|^\*([^\s*][\s\S]*?[^\s])\*(?!\*)|^_([^\s_])_(?!_)|^\*([^\s*])\*(?!\*)/,
  code: /^(`+)\s*([\s\S]*?[^`]?)\s*\1(?!`)/,
  br: /^ {2,}\n(?!\s*$)/,
  del: noop,
  text: /^[\s\S]+?(?=[\\<!\[`*]|\b_| {2,}\n|$)/
};

inline._escapes = /\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g;

inline._scheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/;
inline._email = /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/;
inline.autolink = edit(inline.autolink)
  .replace('scheme', inline._scheme)
  .replace('email', inline._email)
  .getRegex();

inline._attribute = /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/;

inline.tag = edit(inline.tag)
  .replace('comment', block._comment)
  .replace('attribute', inline._attribute)
  .getRegex();

inline._label = /(?:\[[^\[\]]*\]|\\[\[\]]?|`[^`]*`|[^\[\]\\])*?/;
inline._href = /\s*(<(?:\\[<>]?|[^\s<>\\])*>|(?:\\[()]?|\([^\s\x00-\x1f()\\]*\)|[^\s\x00-\x1f()\\])*?)/;
inline._title = /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/;

inline.link = edit(inline.link)
  .replace('label', inline._label)
  .replace('href', inline._href)
  .replace('title', inline._title)
  .getRegex();

inline.reflink = edit(inline.reflink)
  .replace('label', inline._label)
  .getRegex();

/**
 * Normal Inline Grammar
 */

inline.normal = merge({}, inline);

/**
 * Pedantic Inline Grammar
 */

inline.pedantic = merge({}, inline.normal, {
  strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
  em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/,
  link: edit(/^!?\[(label)\]\((.*?)\)/)
    .replace('label', inline._label)
    .getRegex(),
  reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/)
    .replace('label', inline._label)
    .getRegex()
});

/**
 * GFM Inline Grammar
 */

inline.gfm = merge({}, inline.normal, {
  escape: edit(inline.escape).replace('])', '~|])').getRegex(),
  url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/)
    .replace('email', inline._email)
    .getRegex(),
  _backpedal: /(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/,
  del: /^~~(?=\S)([\s\S]*?\S)~~/,
  text: edit(inline.text)
    .replace(']|', '~]|')
    .replace('|', '|https?://|ftp://|www\\.|[a-zA-Z0-9.!#$%&\'*+/=?^_`{\\|}~-]+@|')
    .getRegex()
});

/**
 * GFM + Line Breaks Inline Grammar
 */

inline.breaks = merge({}, inline.gfm, {
  br: edit(inline.br).replace('{2,}', '*').getRegex(),
  text: edit(inline.gfm.text).replace('{2,}', '*').getRegex()
});

/**
 * Inline Lexer & Compiler
 */

function InlineLexer(links, options) {
  this.options = options || marked.defaults;
  this.links = links;
  this.rules = inline.normal;
  this.renderer = this.options.renderer || new Renderer();
  this.renderer.options = this.options;

  if (!this.links) {
    throw new Error('Tokens array requires a `links` property.');
  }

  if (this.options.pedantic) {
    this.rules = inline.pedantic;
  } else if (this.options.gfm) {
    if (this.options.breaks) {
      this.rules = inline.breaks;
    } else {
      this.rules = inline.gfm;
    }
  }
}

/**
 * Expose Inline Rules
 */

InlineLexer.rules = inline;

/**
 * Static Lexing/Compiling Method
 */

InlineLexer.output = function(src, links, options) {
  var inline = new InlineLexer(links, options);
  return inline.output(src);
};

/**
 * Lexing/Compiling
 */

InlineLexer.prototype.output = function(src) {
  var out = '',
      link,
      text,
      href,
      title,
      cap;

  while (src) {
    // escape
    if (cap = this.rules.escape.exec(src)) {
      src = src.substring(cap[0].length);
      out += cap[1];
      continue;
    }

    // autolink
    if (cap = this.rules.autolink.exec(src)) {
      src = src.substring(cap[0].length);
      if (cap[2] === '@') {
        text = escape(this.mangle(cap[1]));
        href = 'mailto:' + text;
      } else {
        text = escape(cap[1]);
        href = text;
      }
      out += this.renderer.link(href, null, text);
      continue;
    }

    // url (gfm)
    if (!this.inLink && (cap = this.rules.url.exec(src))) {
      cap[0] = this.rules._backpedal.exec(cap[0])[0];
      src = src.substring(cap[0].length);
      if (cap[2] === '@') {
        text = escape(cap[0]);
        href = 'mailto:' + text;
      } else {
        text = escape(cap[0]);
        if (cap[1] === 'www.') {
          href = 'http://' + text;
        } else {
          href = text;
        }
      }
      out += this.renderer.link(href, null, text);
      continue;
    }

    // tag
    if (cap = this.rules.tag.exec(src)) {
      if (!this.inLink && /^<a /i.test(cap[0])) {
        this.inLink = true;
      } else if (this.inLink && /^<\/a>/i.test(cap[0])) {
        this.inLink = false;
      }
      src = src.substring(cap[0].length);
      out += this.options.sanitize
        ? this.options.sanitizer
          ? this.options.sanitizer(cap[0])
          : escape(cap[0])
        : cap[0]
      continue;
    }

    // link
    if (cap = this.rules.link.exec(src)) {
      src = src.substring(cap[0].length);
      this.inLink = true;
      href = cap[2];
      if (this.options.pedantic) {
        link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href);

        if (link) {
          href = link[1];
          title = link[3];
        } else {
          title = '';
        }
      } else {
        title = cap[3] ? cap[3].slice(1, -1) : '';
      }
      href = href.trim().replace(/^<([\s\S]*)>$/, '$1');
      out += this.outputLink(cap, {
        href: InlineLexer.escapes(href),
        title: InlineLexer.escapes(title)
      });
      this.inLink = false;
      continue;
    }

    // reflink, nolink
    if ((cap = this.rules.reflink.exec(src))
        || (cap = this.rules.nolink.exec(src))) {
      src = src.substring(cap[0].length);
      link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
      link = this.links[link.toLowerCase()];
      if (!link || !link.href) {
        out += cap[0].charAt(0);
        src = cap[0].substring(1) + src;
        continue;
      }
      this.inLink = true;
      out += this.outputLink(cap, link);
      this.inLink = false;
      continue;
    }

    // strong
    if (cap = this.rules.strong.exec(src)) {
      src = src.substring(cap[0].length);
      out += this.renderer.strong(this.output(cap[4] || cap[3] || cap[2] || cap[1]));
      continue;
    }

    // em
    if (cap = this.rules.em.exec(src)) {
      src = src.substring(cap[0].length);
      out += this.renderer.em(this.output(cap[6] || cap[5] || cap[4] || cap[3] || cap[2] || cap[1]));
      continue;
    }

    // code
    if (cap = this.rules.code.exec(src)) {
      src = src.substring(cap[0].length);
      out += this.renderer.codespan(escape(cap[2].trim(), true));
      continue;
    }

    // br
    if (cap = this.rules.br.exec(src)) {
      src = src.substring(cap[0].length);
      out += this.renderer.br();
      continue;
    }

    // del (gfm)
    if (cap = this.rules.del.exec(src)) {
      src = src.substring(cap[0].length);
      out += this.renderer.del(this.output(cap[1]));
      continue;
    }

    // text
    if (cap = this.rules.text.exec(src)) {
      src = src.substring(cap[0].length);
      out += this.renderer.text(escape(this.smartypants(cap[0])));
      continue;
    }

    if (src) {
      throw new Error('Infinite loop on byte: ' + src.charCodeAt(0));
    }
  }

  return out;
};

InlineLexer.escapes = function(text) {
  return text ? text.replace(InlineLexer.rules._escapes, '$1') : text;
}

/**
 * Compile Link
 */

InlineLexer.prototype.outputLink = function(cap, link) {
  var href = link.href,
      title = link.title ? escape(link.title) : null;

  return cap[0].charAt(0) !== '!'
    ? this.renderer.link(href, title, this.output(cap[1]))
    : this.renderer.image(href, title, escape(cap[1]));
};

/**
 * Smartypants Transformations
 */

InlineLexer.prototype.smartypants = function(text) {
  if (!this.options.smartypants) return text;
  return text
    // em-dashes
    .replace(/---/g, '\u2014')
    // en-dashes
    .replace(/--/g, '\u2013')
    // opening singles
    .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
    // closing singles & apostrophes
    .replace(/'/g, '\u2019')
    // opening doubles
    .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
    // closing doubles
    .replace(/"/g, '\u201d')
    // ellipses
    .replace(/\.{3}/g, '\u2026');
};

/**
 * Mangle Links
 */

InlineLexer.prototype.mangle = function(text) {
  if (!this.options.mangle) return text;
  var out = '',
      l = text.length,
      i = 0,
      ch;

  for (; i < l; i++) {
    ch = text.charCodeAt(i);
    if (Math.random() > 0.5) {
      ch = 'x' + ch.toString(16);
    }
    out += '&#' + ch + ';';
  }

  return out;
};

/**
 * Renderer
 */

function Renderer(options) {
  this.options = options || marked.defaults;
}

Renderer.prototype.code = function(code, lang, escaped) {
  if (this.options.highlight) {
    var out = this.options.highlight(code, lang);
    if (out != null && out !== code) {
      escaped = true;
      code = out;
    }
  }

  if (!lang) {
    return '<pre><code>'
      + (escaped ? code : escape(code, true))
      + '</code></pre>';
  }

  return '<pre><code class="'
    + this.options.langPrefix
    + escape(lang, true)
    + '">'
    + (escaped ? code : escape(code, true))
    + '</code></pre>\n';
};

Renderer.prototype.blockquote = function(quote) {
  return '<blockquote>\n' + quote + '</blockquote>\n';
};

Renderer.prototype.html = function(html) {
  return html;
};

Renderer.prototype.heading = function(text, level, raw) {
  if (this.options.headerIds) {
    return '<h'
      + level
      + ' id="'
      + this.options.headerPrefix
      + raw.toLowerCase().replace(/[^\w]+/g, '-')
      + '">'
      + text
      + '</h'
      + level
      + '>\n';
  }
  // ignore IDs
  return '<h' + level + '>' + text + '</h' + level + '>\n';
};

Renderer.prototype.hr = function() {
  return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
};

Renderer.prototype.list = function(body, ordered, start) {
  var type = ordered ? 'ol' : 'ul',
      startatt = (ordered && start !== 1) ? (' start="' + start + '"') : '';
  return '<' + type + startatt + '>\n' + body + '</' + type + '>\n';
};

Renderer.prototype.listitem = function(text) {
  return '<li>' + text + '</li>\n';
};

Renderer.prototype.checkbox = function(checked) {
  return '<input '
    + (checked ? 'checked="" ' : '')
    + 'disabled="" type="checkbox"'
    + (this.options.xhtml ? ' /' : '')
    + '> ';
}

Renderer.prototype.paragraph = function(text) {
  return '<p>' + text + '</p>\n';
};

Renderer.prototype.table = function(header, body) {
  if (body) body = '<tbody>' + body + '</tbody>';

  return '<table>\n'
    + '<thead>\n'
    + header
    + '</thead>\n'
    + body
    + '</table>\n';
};

Renderer.prototype.tablerow = function(content) {
  return '<tr>\n' + content + '</tr>\n';
};

Renderer.prototype.tablecell = function(content, flags) {
  var type = flags.header ? 'th' : 'td';
  var tag = flags.align
    ? '<' + type + ' align="' + flags.align + '">'
    : '<' + type + '>';
  return tag + content + '</' + type + '>\n';
};

// span level renderer
Renderer.prototype.strong = function(text) {
  return '<strong>' + text + '</strong>';
};

Renderer.prototype.em = function(text) {
  return '<em>' + text + '</em>';
};

Renderer.prototype.codespan = function(text) {
  return '<code>' + text + '</code>';
};

Renderer.prototype.br = function() {
  return this.options.xhtml ? '<br/>' : '<br>';
};

Renderer.prototype.del = function(text) {
  return '<del>' + text + '</del>';
};

Renderer.prototype.link = function(href, title, text) {
  if (this.options.sanitize) {
    try {
      var prot = decodeURIComponent(unescape(href))
        .replace(/[^\w:]/g, '')
        .toLowerCase();
    } catch (e) {
      return text;
    }
    if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) {
      return text;
    }
  }
  if (this.options.baseUrl && !originIndependentUrl.test(href)) {
    href = resolveUrl(this.options.baseUrl, href);
  }
  try {
    href = encodeURI(href).replace(/%25/g, '%');
  } catch (e) {
    return text;
  }
  var out = '<a href="' + escape(href) + '"';
  if (title) {
    out += ' title="' + title + '"';
  }
  out += '>' + text + '</a>';
  return out;
};

Renderer.prototype.image = function(href, title, text) {
  if (this.options.baseUrl && !originIndependentUrl.test(href)) {
    href = resolveUrl(this.options.baseUrl, href);
  }
  var out = '<img src="' + href + '" alt="' + text + '"';
  if (title) {
    out += ' title="' + title + '"';
  }
  out += this.options.xhtml ? '/>' : '>';
  return out;
};

Renderer.prototype.text = function(text) {
  return text;
};

/**
 * TextRenderer
 * returns only the textual part of the token
 */

function TextRenderer() {}

// no need for block level renderers

TextRenderer.prototype.strong =
TextRenderer.prototype.em =
TextRenderer.prototype.codespan =
TextRenderer.prototype.del =
TextRenderer.prototype.text = function (text) {
  return text;
}

TextRenderer.prototype.link =
TextRenderer.prototype.image = function(href, title, text) {
  return '' + text;
}

TextRenderer.prototype.br = function() {
  return '';
}

/**
 * Parsing & Compiling
 */

function Parser(options) {
  this.tokens = [];
  this.token = null;
  this.options = options || marked.defaults;
  this.options.renderer = this.options.renderer || new Renderer();
  this.renderer = this.options.renderer;
  this.renderer.options = this.options;
}

/**
 * Static Parse Method
 */

Parser.parse = function(src, options) {
  var parser = new Parser(options);
  return parser.parse(src);
};

/**
 * Parse Loop
 */

Parser.prototype.parse = function(src) {
  this.inline = new InlineLexer(src.links, this.options);
  // use an InlineLexer with a TextRenderer to extract pure text
  this.inlineText = new InlineLexer(
    src.links,
    merge({}, this.options, {renderer: new TextRenderer()})
  );
  this.tokens = src.reverse();

  var out = '';
  while (this.next()) {
    out += this.tok();
  }

  return out;
};

/**
 * Next Token
 */

Parser.prototype.next = function() {
  return this.token = this.tokens.pop();
};

/**
 * Preview Next Token
 */

Parser.prototype.peek = function() {
  return this.tokens[this.tokens.length - 1] || 0;
};

/**
 * Parse Text Tokens
 */

Parser.prototype.parseText = function() {
  var body = this.token.text;

  while (this.peek().type === 'text') {
    body += '\n' + this.next().text;
  }

  return this.inline.output(body);
};

/**
 * Parse Current Token
 */

Parser.prototype.tok = function() {
  switch (this.token.type) {
    case 'space': {
      return '';
    }
    case 'hr': {
      return this.renderer.hr();
    }
    case 'heading': {
      return this.renderer.heading(
        this.inline.output(this.token.text),
        this.token.depth,
        unescape(this.inlineText.output(this.token.text)));
    }
    case 'code': {
      return this.renderer.code(this.token.text,
        this.token.lang,
        this.token.escaped);
    }
    case 'table': {
      var header = '',
          body = '',
          i,
          row,
          cell,
          j;

      // header
      cell = '';
      for (i = 0; i < this.token.header.length; i++) {
        cell += this.renderer.tablecell(
          this.inline.output(this.token.header[i]),
          { header: true, align: this.token.align[i] }
        );
      }
      header += this.renderer.tablerow(cell);

      for (i = 0; i < this.token.cells.length; i++) {
        row = this.token.cells[i];

        cell = '';
        for (j = 0; j < row.length; j++) {
          cell += this.renderer.tablecell(
            this.inline.output(row[j]),
            { header: false, align: this.token.align[j] }
          );
        }

        body += this.renderer.tablerow(cell);
      }
      return this.renderer.table(header, body);
    }
    case 'blockquote_start': {
      body = '';

      while (this.next().type !== 'blockquote_end') {
        body += this.tok();
      }

      return this.renderer.blockquote(body);
    }
    case 'list_start': {
      body = '';
      var ordered = this.token.ordered,
          start = this.token.start;

      while (this.next().type !== 'list_end') {
        body += this.tok();
      }

      return this.renderer.list(body, ordered, start);
    }
    case 'list_item_start': {
      body = '';

      if (this.token.task) {
        body += this.renderer.checkbox(this.token.checked);
      }

      while (this.next().type !== 'list_item_end') {
        body += this.token.type === 'text'
          ? this.parseText()
          : this.tok();
      }

      return this.renderer.listitem(body);
    }
    case 'loose_item_start': {
      body = '';

      while (this.next().type !== 'list_item_end') {
        body += this.tok();
      }

      return this.renderer.listitem(body);
    }
    case 'html': {
      // TODO parse inline content if parameter markdown=1
      return this.renderer.html(this.token.text);
    }
    case 'paragraph': {
      return this.renderer.paragraph(this.inline.output(this.token.text));
    }
    case 'text': {
      return this.renderer.paragraph(this.parseText());
    }
  }
};

/**
 * Helpers
 */

function escape(html, encode) {
  return html
    .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}

function unescape(html) {
  // explicitly match decimal, hex, and named HTML entities
  return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig, function(_, n) {
    n = n.toLowerCase();
    if (n === 'colon') return ':';
    if (n.charAt(0) === '#') {
      return n.charAt(1) === 'x'
        ? String.fromCharCode(parseInt(n.substring(2), 16))
        : String.fromCharCode(+n.substring(1));
    }
    return '';
  });
}

function edit(regex, opt) {
  regex = regex.source || regex;
  opt = opt || '';
  return {
    replace: function(name, val) {
      val = val.source || val;
      val = val.replace(/(^|[^\[])\^/g, '$1');
      regex = regex.replace(name, val);
      return this;
    },
    getRegex: function() {
      return new RegExp(regex, opt);
    }
  };
}

function resolveUrl(base, href) {
  if (!baseUrls[' ' + base]) {
    // we can ignore everything in base after the last slash of its path component,
    // but we might need to add _that_
    // https://tools.ietf.org/html/rfc3986#section-3
    if (/^[^:]+:\/*[^/]*$/.test(base)) {
      baseUrls[' ' + base] = base + '/';
    } else {
      baseUrls[' ' + base] = base.replace(/[^/]*$/, '');
    }
  }
  base = baseUrls[' ' + base];

  if (href.slice(0, 2) === '//') {
    return base.replace(/:[\s\S]*/, ':') + href;
  } else if (href.charAt(0) === '/') {
    return base.replace(/(:\/*[^/]*)[\s\S]*/, '$1') + href;
  } else {
    return base + href;
  }
}
var baseUrls = {};
var originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;

function noop() {}
noop.exec = noop;

function merge(obj) {
  var i = 1,
      target,
      key;

  for (; i < arguments.length; i++) {
    target = arguments[i];
    for (key in target) {
      if (Object.prototype.hasOwnProperty.call(target, key)) {
        obj[key] = target[key];
      }
    }
  }

  return obj;
}

function splitCells(tableRow, count) {
  var cells = tableRow.replace(/([^\\])\|/g, '$1 |').split(/ +\| */),
      i = 0;

  if (cells.length > count) {
    cells.splice(count);
  } else {
    while (cells.length < count) cells.push('');
  }

  for (; i < cells.length; i++) {
    cells[i] = cells[i].replace(/\\\|/g, '|');
  }
  return cells;
}

/**
 * Marked
 */

function marked(src, opt, callback) {
  // throw error in case of non string input
  if (typeof src === 'undefined' || src === null) {
    throw new Error('marked(): input parameter is undefined or null');
  }
  if (typeof src !== 'string') {
    throw new Error('marked(): input parameter is of type '
      + Object.prototype.toString.call(src) + ', string expected');
  }

  if (callback || typeof opt === 'function') {
    if (!callback) {
      callback = opt;
      opt = null;
    }

    opt = merge({}, marked.defaults, opt || {});

    var highlight = opt.highlight,
        tokens,
        pending,
        i = 0;

    try {
      tokens = Lexer.lex(src, opt)
    } catch (e) {
      return callback(e);
    }

    pending = tokens.length;

    var done = function(err) {
      if (err) {
        opt.highlight = highlight;
        return callback(err);
      }

      var out;

      try {
        out = Parser.parse(tokens, opt);
      } catch (e) {
        err = e;
      }

      opt.highlight = highlight;

      return err
        ? callback(err)
        : callback(null, out);
    };

    if (!highlight || highlight.length < 3) {
      return done();
    }

    delete opt.highlight;

    if (!pending) return done();

    for (; i < tokens.length; i++) {
      (function(token) {
        if (token.type !== 'code') {
          return --pending || done();
        }
        return highlight(token.text, token.lang, function(err, code) {
          if (err) return done(err);
          if (code == null || code === token.text) {
            return --pending || done();
          }
          token.text = code;
          token.escaped = true;
          --pending || done();
        });
      })(tokens[i]);
    }

    return;
  }
  try {
    if (opt) opt = merge({}, marked.defaults, opt);
    return Parser.parse(Lexer.lex(src, opt), opt);
  } catch (e) {
    e.message += '\nPlease report this to https://github.com/markedjs/marked.';
    if ((opt || marked.defaults).silent) {
      return '<p>An error occurred:</p><pre>'
        + escape(e.message + '', true)
        + '</pre>';
    }
    throw e;
  }
}

/**
 * Options
 */

marked.options =
marked.setOptions = function(opt) {
  merge(marked.defaults, opt);
  return marked;
};

marked.getDefaults = function () {
  return {
    baseUrl: null,
    breaks: false,
    gfm: true,
    headerIds: true,
    headerPrefix: '',
    highlight: null,
    langPrefix: 'language-',
    mangle: true,
    pedantic: false,
    renderer: new Renderer(),
    sanitize: false,
    sanitizer: null,
    silent: false,
    smartLists: false,
    smartypants: false,
    tables: true,
    xhtml: false
  };
}

marked.defaults = marked.getDefaults();

/**
 * Expose
 */

marked.Parser = Parser;
marked.parser = Parser.parse;

marked.Renderer = Renderer;
marked.TextRenderer = TextRenderer;

marked.Lexer = Lexer;
marked.lexer = Lexer.lex;

marked.InlineLexer = InlineLexer;
marked.inlineLexer = InlineLexer.output;

marked.parse = marked;

if (true) {
  module.exports = marked;
} else {}
})(this || (typeof window !== 'undefined' ? window : global));

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "Dmvi":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/en-au.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var enAu = moment.defineLocale('en-au', {
    months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
    monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
    weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
    weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
    weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
    longDateFormat : {
        LT : 'h:mm A',
        LTS : 'h:mm:ss A',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY h:mm A',
        LLLL : 'dddd, D MMMM YYYY h:mm A'
    },
    calendar : {
        sameDay : '[Today at] LT',
        nextDay : '[Tomorrow at] LT',
        nextWeek : 'dddd [at] LT',
        lastDay : '[Yesterday at] LT',
        lastWeek : '[Last] dddd [at] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'in %s',
        past : '%s ago',
        s : 'a few seconds',
        ss : '%d seconds',
        m : 'a minute',
        mm : '%d minutes',
        h : 'an hour',
        hh : '%d hours',
        d : 'a day',
        dd : '%d days',
        M : 'a month',
        MM : '%d months',
        y : 'a year',
        yy : '%d years'
    },
    dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/,
    ordinal : function (number) {
        var b = number % 10,
            output = (~~(number % 100 / 10) === 1) ? 'th' :
            (b === 1) ? 'st' :
            (b === 2) ? 'nd' :
            (b === 3) ? 'rd' : 'th';
        return number + output;
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return enAu;

})));


/***/ }),

/***/ "DnSU":
/*!***************************************************************************************!*\
  !*** ./node_modules/react-resizable-rotatable-draggable/lib/components/Rect/index.js ***!
  \***************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _propTypes = _interopRequireDefault(__webpack_require__(/*! prop-types */ "17x9"));

var _react = _interopRequireWildcard(__webpack_require__(/*! react */ "q1tI"));

var _utils = __webpack_require__(/*! ../../utils */ "Pkh7");

var _StyledRect = _interopRequireDefault(__webpack_require__(/*! ./StyledRect */ "q+TC"));

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } _setPrototypeOf(subClass.prototype, superClass && superClass.prototype); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) { return o.__proto__; }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var zoomableMap = {
  'n': 't',
  's': 'b',
  'e': 'r',
  'w': 'l',
  'ne': 'tr',
  'nw': 'tl',
  'se': 'br',
  'sw': 'bl'
};

var Rect = function (_PureComponent) {
  function Rect() {
    var _getPrototypeOf2;

    var _temp, _this;

    _classCallCheck(this, Rect);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _possibleConstructorReturn(_this, (_temp = _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Rect)).call.apply(_getPrototypeOf2, [this].concat(args))), _defineProperty(_defineProperty(_defineProperty(_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "setElementRef", function (ref) {
      return _this.$element = ref;
    }), "startDrag", function (e) {
      var startX = e.clientX,
          startY = e.clientY;
      _this.props.onDragStart && _this.props.onDragStart();
      _this._isMouseDown = true;

      var onMove = function onMove(e) {
        if (!_this._isMouseDown) return;
        e.stopImmediatePropagation();
        var clientX = e.clientX,
            clientY = e.clientY;
        var deltaX = clientX - startX;
        var deltaY = clientY - startY;

        _this.props.onDrag(deltaX, deltaY);

        startX = clientX;
        startY = clientY;
      };

      var onUp = function onUp() {
        document.removeEventListener('mousemove', onMove);
        document.removeEventListener('mouseup', onUp);
        if (!_this._isMouseDown) return;
        _this._isMouseDown = false;
        _this.props.onDragEnd && _this.props.onDragEnd();
      };

      document.addEventListener('mousemove', onMove);
      document.addEventListener('mouseup', onUp);
    }), "startRotate", function (e) {
      if (e.button !== 0) return;
      var clientX = e.clientX,
          clientY = e.clientY;
      var startAngle = _this.props.styles.transform.rotateAngle;

      var rect = _this.$element.getBoundingClientRect();

      var center = {
        x: rect.left + rect.width / 2,
        y: rect.top + rect.height / 2
      };
      var startVector = {
        x: clientX - center.x,
        y: clientY - center.y
      };
      _this.props.onRotateStart && _this.props.onRotateStart();
      _this._isMouseDown = true;

      var onMove = function onMove(e) {
        if (!_this._isMouseDown) return;
        e.stopImmediatePropagation();
        var clientX = e.clientX,
            clientY = e.clientY;
        var rotateVector = {
          x: clientX - center.x,
          y: clientY - center.y
        };
        var angle = (0, _utils.getAngle)(startVector, rotateVector);

        _this.props.onRotate(angle, startAngle);
      };

      var onUp = function onUp() {
        document.removeEventListener('mousemove', onMove);
        document.removeEventListener('mouseup', onUp);
        if (!_this._isMouseDown) return;
        _this._isMouseDown = false;
        _this.props.onRotateEnd && _this.props.onRotateEnd();
      };

      document.addEventListener('mousemove', onMove);
      document.addEventListener('mouseup', onUp);
    }), "startResize", function (e, cursor) {
      if (e.button !== 0) return;
      document.body.style.cursor = cursor;
      var _this$props$styles = _this.props.styles,
          _this$props$styles$po = _this$props$styles.position,
          centerX = _this$props$styles$po.centerX,
          centerY = _this$props$styles$po.centerY,
          _this$props$styles$si = _this$props$styles.size,
          width = _this$props$styles$si.width,
          height = _this$props$styles$si.height,
          rotateAngle = _this$props$styles.transform.rotateAngle;
      var startX = e.clientX,
          startY = e.clientY;
      var rect = {
        width: width,
        height: height,
        centerX: centerX,
        centerY: centerY,
        rotateAngle: rotateAngle
      };
      var type = e.target.getAttribute('class').split(' ')[0];
      _this.props.onResizeStart && _this.props.onResizeStart();
      _this._isMouseDown = true;

      var onMove = function onMove(e) {
        if (!_this._isMouseDown) return;
        e.stopImmediatePropagation();
        var clientX = e.clientX,
            clientY = e.clientY;
        var deltaX = clientX - startX;
        var deltaY = clientY - startY;
        var alpha = Math.atan2(deltaY, deltaX);
        var deltaL = (0, _utils.getLength)(deltaX, deltaY);
        var isShiftKey = e.shiftKey;

        _this.props.onResize(deltaL, alpha, rect, type, isShiftKey);
      };

      var onUp = function onUp() {
        document.body.style.cursor = 'auto';
        document.removeEventListener('mousemove', onMove);
        document.removeEventListener('mouseup', onUp);
        if (!_this._isMouseDown) return;
        _this._isMouseDown = false;
        _this.props.onResizeEnd && _this.props.onResizeEnd();
      };

      document.addEventListener('mousemove', onMove);
      document.addEventListener('mouseup', onUp);
    }), _temp));
  }

  _createClass(Rect, [{
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props = this.props,
          _this$props$styles2 = _this$props.styles,
          _this$props$styles2$p = _this$props$styles2.position,
          centerX = _this$props$styles2$p.centerX,
          centerY = _this$props$styles2$p.centerY,
          _this$props$styles2$s = _this$props$styles2.size,
          width = _this$props$styles2$s.width,
          height = _this$props$styles2$s.height,
          rotateAngle = _this$props$styles2.transform.rotateAngle,
          zoomable = _this$props.zoomable,
          rotatable = _this$props.rotatable,
          parentRotateAngle = _this$props.parentRotateAngle;
      var style = {
        width: Math.abs(width),
        height: Math.abs(height),
        transform: "rotate(".concat(rotateAngle, "deg)"),
        left: centerX - Math.abs(width) / 2,
        top: centerY - Math.abs(height) / 2
      };
      var direction = zoomable.split(',').map(function (d) {
        return d.trim();
      }).filter(function (d) {
        return d;
      });
      return _react.default.createElement(_StyledRect.default, {
        innerRef: this.setElementRef,
        onMouseDown: this.startDrag,
        className: "rect single-resizer",
        style: style
      }, rotatable && _react.default.createElement("div", {
        className: "rotate",
        onMouseDown: this.startRotate
      }, _react.default.createElement("i", null)), direction.map(function (d) {
        var cursor = "".concat((0, _utils.getCursor)(rotateAngle + parentRotateAngle, d), "-resize");
        return _react.default.createElement("div", {
          key: d,
          style: {
            cursor: cursor
          },
          className: "".concat(zoomableMap[d], " resizable-handler"),
          onMouseDown: function onMouseDown(e) {
            return _this2.startResize(e, cursor);
          }
        });
      }), direction.map(function (d) {
        return _react.default.createElement("div", {
          key: d,
          className: "".concat(zoomableMap[d], " square")
        });
      }));
    }
  }]);

  _inherits(Rect, _PureComponent);

  return Rect;
}(_react.PureComponent);

exports.default = Rect;

_defineProperty(Rect, "propTypes", {
  styles: _propTypes.default.object,
  zoomable: _propTypes.default.string,
  rotatable: _propTypes.default.bool,
  onResizeStart: _propTypes.default.func,
  onResize: _propTypes.default.func,
  onResizeEnd: _propTypes.default.func,
  onRotateStart: _propTypes.default.func,
  onRotate: _propTypes.default.func,
  onRotateEnd: _propTypes.default.func,
  onDragStart: _propTypes.default.func,
  onDrag: _propTypes.default.func,
  onDragEnd: _propTypes.default.func,
  parentRotateAngle: _propTypes.default.number
});

/***/ }),

/***/ "DoHr":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/tr.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';

var suffixes = {
    1: '\'inci',
    5: '\'inci',
    8: '\'inci',
    70: '\'inci',
    80: '\'inci',
    2: '\'nci',
    7: '\'nci',
    20: '\'nci',
    50: '\'nci',
    3: '\'üncü',
    4: '\'üncü',
    100: '\'üncü',
    6: '\'ncı',
    9: '\'uncu',
    10: '\'uncu',
    30: '\'uncu',
    60: '\'ıncı',
    90: '\'ıncı'
};

var tr = moment.defineLocale('tr', {
    months : 'Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık'.split('_'),
    monthsShort : 'Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara'.split('_'),
    weekdays : 'Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi'.split('_'),
    weekdaysShort : 'Paz_Pts_Sal_Çar_Per_Cum_Cts'.split('_'),
    weekdaysMin : 'Pz_Pt_Sa_Ça_Pe_Cu_Ct'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd, D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay : '[bugün saat] LT',
        nextDay : '[yarın saat] LT',
        nextWeek : '[gelecek] dddd [saat] LT',
        lastDay : '[dün] LT',
        lastWeek : '[geçen] dddd [saat] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : '%s sonra',
        past : '%s önce',
        s : 'birkaç saniye',
        ss : '%d saniye',
        m : 'bir dakika',
        mm : '%d dakika',
        h : 'bir saat',
        hh : '%d saat',
        d : 'bir gün',
        dd : '%d gün',
        M : 'bir ay',
        MM : '%d ay',
        y : 'bir yıl',
        yy : '%d yıl'
    },
    ordinal: function (number, period) {
        switch (period) {
            case 'd':
            case 'D':
            case 'Do':
            case 'DD':
                return number;
            default:
                if (number === 0) {  // special case for zero
                    return number + '\'ıncı';
                }
                var a = number % 10,
                    b = number % 100 - a,
                    c = number >= 100 ? 100 : null;
                return number + (suffixes[a] || suffixes[b] || suffixes[c]);
        }
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return tr;

})));


/***/ }),

/***/ "DrOJ":
/*!*******************************************************!*\
  !*** ./node_modules/@jupyterlab/console/lib/index.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__webpack_require__(/*! ../style/index.css */ "RZIX");
__export(__webpack_require__(/*! ./foreign */ "wplO"));
__export(__webpack_require__(/*! ./history */ "vz/y"));
__export(__webpack_require__(/*! ./panel */ "1iyU"));
__export(__webpack_require__(/*! ./tracker */ "9DXq"));
__export(__webpack_require__(/*! ./widget */ "wK5+"));


/***/ }),

/***/ "Dt/b":
/*!********************************************************!*\
  !*** ./node_modules/@jupyterlab/coreutils/lib/path.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const posix = __importStar(__webpack_require__(/*! path-posix */ "y7cq"));
/**
 * The namespace for path-related functions.
 *
 * Note that Jupyter server paths do not start with a leading slash.
 */
var PathExt;
(function (PathExt) {
    /**
     * Join all arguments together and normalize the resulting path.
     * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.
     *
     * @param paths - The string paths to join.
     */
    function join(...paths) {
        const path = posix.join(...paths);
        return path === '.' ? '' : removeSlash(posix.join(...paths));
    }
    PathExt.join = join;
    /**
     * Return the last portion of a path. Similar to the Unix basename command.
     * Often used to extract the file name from a fully qualified path.
     *
     * @param path - The path to evaluate.
     *
     * @param ext - An extension to remove from the result.
     */
    function basename(path, ext) {
        return posix.basename(path, ext);
    }
    PathExt.basename = basename;
    /**
     * Get the directory name of a path, similar to the Unix dirname command.
     * When an empty path is given, returns the root path.
     *
     * @param path - The file path.
     */
    function dirname(path) {
        let dir = removeSlash(posix.dirname(path));
        return dir === '.' ? '' : dir;
    }
    PathExt.dirname = dirname;
    /**
     * Get the extension of the path.
     *
     * @param path - The file path.
     *
     * @returns the extension of the file.
     *
     * #### Notes
     * The extension is the string from the last occurrence of the `.`
     * character to end of string in the last portion of the path, inclusive.
     * If there is no `.` in the last portion of the path, or if the first
     * character of the basename of path [[basename]] is `.`, then an
     * empty string is returned.
     */
    function extname(path) {
        return posix.extname(path);
    }
    PathExt.extname = extname;
    /**
     * Normalize a string path, reducing '..' and '.' parts.
     * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used.
     * When an empty path is given, returns the root path.
     *
     * @param path - The string path to normalize.
     */
    function normalize(path) {
        if (path === '') {
            return '';
        }
        return removeSlash(posix.normalize(path));
    }
    PathExt.normalize = normalize;
    /**
     * Resolve a sequence of paths or path segments into an absolute path.
     * The root path in the application has no leading slash, so it is removed.
     *
     * @param parts - The paths to join.
     *
     * #### Notes
     * The right-most parameter is considered {to}.  Other parameters are considered an array of {from}.
     *
     * Starting from leftmost {from} parameter, resolves {to} to an absolute path.
     *
     * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory.
     */
    function resolve(...parts) {
        return removeSlash(posix.resolve(...parts));
    }
    PathExt.resolve = resolve;
    /**
     * Solve the relative path from {from} to {to}.
     *
     * @param from - The source path.
     *
     * @param to - The target path.
     *
     * #### Notes
     * If from and to each resolve to the same path (after calling
     * path.resolve() on each), a zero-length string is returned.
     * If a zero-length string is passed as from or to, `/`
     * will be used instead of the zero-length strings.
     */
    function relative(from, to) {
        return removeSlash(posix.relative(from, to));
    }
    PathExt.relative = relative;
    /**
     * Normalize a file extension to be of the type `'.foo'`.
     *
     * @param extension - the file extension.
     *
     * #### Notes
     * Adds a leading dot if not present and converts to lower case.
     */
    function normalizeExtension(extension) {
        if (extension.length > 0 && extension.indexOf('.') !== 0) {
            extension = `.${extension}`;
        }
        return extension;
    }
    PathExt.normalizeExtension = normalizeExtension;
    /**
     * Remove the leading slash from a path.
     *
     * @param path: the path from which to remove a leading slash.
     */
    function removeSlash(path) {
        if (path.indexOf('/') === 0) {
            path = path.slice(1);
        }
        return path;
    }
    PathExt.removeSlash = removeSlash;
})(PathExt = exports.PathExt || (exports.PathExt = {}));


/***/ }),

/***/ "DtRd":
/*!************************************************!*\
  !*** ./node_modules/pure-color/parse/index.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var hsl = __webpack_require__(/*! ./hsl */ "07l2");
var hex = __webpack_require__(/*! ./hex */ "6jo/");
var rgb = __webpack_require__(/*! ./rgb */ "U6ii");
var hsl2rgb = __webpack_require__(/*! ../convert/hsl2rgb */ "5Luj");

function hsl2rgbParse(color) {
  var h = hsl(color);
  var r = hsl2rgb(h);

  // handle alpha since hsl2rgb doesn't know (or care!) about it
  if(h.length === 4) {
    r.push(h[3]);
  }

  return r;
}

var space2parser = {
  "#" : hex,
  "hsl" : hsl2rgbParse,
  "rgb" : rgb
};

function parse(color) {
  for(var scheme in space2parser) {
    if(color.indexOf(scheme) === 0) {
      return space2parser[scheme](color);
    }
  }
}

parse.rgb = rgb;
parse.hsl = hsl;
parse.hex = hex;

module.exports = parse;

/***/ }),

/***/ "DthY":
/*!*************************************************************!*\
  !*** ./node_modules/draft-js/lib/DraftEditorBlock.react.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DraftEditorBlock.react
 * @format
 * 
 */



var _assign = __webpack_require__(/*! object-assign */ "MgzW");

var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var DraftEditorLeaf = __webpack_require__(/*! ./DraftEditorLeaf.react */ "CJXx");
var DraftOffsetKey = __webpack_require__(/*! ./DraftOffsetKey */ "Iq8E");
var React = __webpack_require__(/*! react */ "q1tI");
var ReactDOM = __webpack_require__(/*! react-dom */ "i8i4");
var Scroll = __webpack_require__(/*! fbjs/lib/Scroll */ "prOm");
var Style = __webpack_require__(/*! fbjs/lib/Style */ "6Xrj");
var UnicodeBidi = __webpack_require__(/*! fbjs/lib/UnicodeBidi */ "fZAc");
var UnicodeBidiDirection = __webpack_require__(/*! fbjs/lib/UnicodeBidiDirection */ "mjHj");

var cx = __webpack_require__(/*! fbjs/lib/cx */ "YVIB");
var getElementPosition = __webpack_require__(/*! fbjs/lib/getElementPosition */ "p1kU");
var getScrollPosition = __webpack_require__(/*! fbjs/lib/getScrollPosition */ "DeIs");
var getViewportDimensions = __webpack_require__(/*! fbjs/lib/getViewportDimensions */ "tKWh");
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");
var nullthrows = __webpack_require__(/*! fbjs/lib/nullthrows */ "gWRK");

var SCROLL_BUFFER = 10;

/**
 * Return whether a block overlaps with either edge of the `SelectionState`.
 */
var isBlockOnSelectionEdge = function isBlockOnSelectionEdge(selection, key) {
  return selection.getAnchorKey() === key || selection.getFocusKey() === key;
};

/**
 * The default block renderer for a `DraftEditor` component.
 *
 * A `DraftEditorBlock` is able to render a given `ContentBlock` to its
 * appropriate decorator and inline style components.
 */

var DraftEditorBlock = function (_React$Component) {
  _inherits(DraftEditorBlock, _React$Component);

  function DraftEditorBlock() {
    _classCallCheck(this, DraftEditorBlock);

    return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
  }

  DraftEditorBlock.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
    return this.props.block !== nextProps.block || this.props.tree !== nextProps.tree || this.props.direction !== nextProps.direction || isBlockOnSelectionEdge(nextProps.selection, nextProps.block.getKey()) && nextProps.forceSelection;
  };

  /**
   * When a block is mounted and overlaps the selection state, we need to make
   * sure that the cursor is visible to match native behavior. This may not
   * be the case if the user has pressed `RETURN` or pasted some content, since
   * programatically creating these new blocks and setting the DOM selection
   * will miss out on the browser natively scrolling to that position.
   *
   * To replicate native behavior, if the block overlaps the selection state
   * on mount, force the scroll position. Check the scroll state of the scroll
   * parent, and adjust it to align the entire block to the bottom of the
   * scroll parent.
   */


  DraftEditorBlock.prototype.componentDidMount = function componentDidMount() {
    var selection = this.props.selection;
    var endKey = selection.getEndKey();
    if (!selection.getHasFocus() || endKey !== this.props.block.getKey()) {
      return;
    }

    var blockNode = ReactDOM.findDOMNode(this);
    var scrollParent = Style.getScrollParent(blockNode);
    var scrollPosition = getScrollPosition(scrollParent);
    var scrollDelta = void 0;

    if (scrollParent === window) {
      var nodePosition = getElementPosition(blockNode);
      var nodeBottom = nodePosition.y + nodePosition.height;
      var viewportHeight = getViewportDimensions().height;
      scrollDelta = nodeBottom - viewportHeight;
      if (scrollDelta > 0) {
        window.scrollTo(scrollPosition.x, scrollPosition.y + scrollDelta + SCROLL_BUFFER);
      }
    } else {
      !(blockNode instanceof HTMLElement) ?  true ? invariant(false, 'blockNode is not an HTMLElement') : undefined : void 0;
      var blockBottom = blockNode.offsetHeight + blockNode.offsetTop;
      var scrollBottom = scrollParent.offsetHeight + scrollPosition.y;
      scrollDelta = blockBottom - scrollBottom;
      if (scrollDelta > 0) {
        Scroll.setTop(scrollParent, Scroll.getTop(scrollParent) + scrollDelta + SCROLL_BUFFER);
      }
    }
  };

  DraftEditorBlock.prototype._renderChildren = function _renderChildren() {
    var _this2 = this;

    var block = this.props.block;
    var blockKey = block.getKey();
    var text = block.getText();
    var lastLeafSet = this.props.tree.size - 1;
    var hasSelection = isBlockOnSelectionEdge(this.props.selection, blockKey);

    return this.props.tree.map(function (leafSet, ii) {
      var leavesForLeafSet = leafSet.get('leaves');
      var lastLeaf = leavesForLeafSet.size - 1;
      var leaves = leavesForLeafSet.map(function (leaf, jj) {
        var offsetKey = DraftOffsetKey.encode(blockKey, ii, jj);
        var start = leaf.get('start');
        var end = leaf.get('end');
        return React.createElement(DraftEditorLeaf, {
          key: offsetKey,
          offsetKey: offsetKey,
          block: block,
          start: start,
          selection: hasSelection ? _this2.props.selection : null,
          forceSelection: _this2.props.forceSelection,
          text: text.slice(start, end),
          styleSet: block.getInlineStyleAt(start),
          customStyleMap: _this2.props.customStyleMap,
          customStyleFn: _this2.props.customStyleFn,
          isLast: ii === lastLeafSet && jj === lastLeaf
        });
      }).toArray();

      var decoratorKey = leafSet.get('decoratorKey');
      if (decoratorKey == null) {
        return leaves;
      }

      if (!_this2.props.decorator) {
        return leaves;
      }

      var decorator = nullthrows(_this2.props.decorator);

      var DecoratorComponent = decorator.getComponentForKey(decoratorKey);
      if (!DecoratorComponent) {
        return leaves;
      }

      var decoratorProps = decorator.getPropsForKey(decoratorKey);
      var decoratorOffsetKey = DraftOffsetKey.encode(blockKey, ii, 0);
      var decoratedText = text.slice(leavesForLeafSet.first().get('start'), leavesForLeafSet.last().get('end'));

      // Resetting dir to the same value on a child node makes Chrome/Firefox
      // confused on cursor movement. See http://jsfiddle.net/d157kLck/3/
      var dir = UnicodeBidiDirection.getHTMLDirIfDifferent(UnicodeBidi.getDirection(decoratedText), _this2.props.direction);

      return React.createElement(
        DecoratorComponent,
        _extends({}, decoratorProps, {
          contentState: _this2.props.contentState,
          decoratedText: decoratedText,
          dir: dir,
          key: decoratorOffsetKey,
          entityKey: block.getEntityAt(leafSet.get('start')),
          offsetKey: decoratorOffsetKey }),
        leaves
      );
    }).toArray();
  };

  DraftEditorBlock.prototype.render = function render() {
    var _props = this.props,
        direction = _props.direction,
        offsetKey = _props.offsetKey;

    var className = cx({
      'public/DraftStyleDefault/block': true,
      'public/DraftStyleDefault/ltr': direction === 'LTR',
      'public/DraftStyleDefault/rtl': direction === 'RTL'
    });

    return React.createElement(
      'div',
      { 'data-offset-key': offsetKey, className: className },
      this._renderChildren()
    );
  };

  return DraftEditorBlock;
}(React.Component);

module.exports = DraftEditorBlock;

/***/ }),

/***/ "Dw+G":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_baseAssignIn.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var copyObject = __webpack_require__(/*! ./_copyObject */ "juv8"),
    keysIn = __webpack_require__(/*! ./keysIn */ "mTTR");

/**
 * 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);
}

module.exports = baseAssignIn;


/***/ }),

/***/ "DxQv":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/da.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var da = moment.defineLocale('da', {
    months : 'januar_februar_marts_april_maj_juni_juli_august_september_oktober_november_december'.split('_'),
    monthsShort : 'jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec'.split('_'),
    weekdays : 'søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag'.split('_'),
    weekdaysShort : 'søn_man_tir_ons_tor_fre_lør'.split('_'),
    weekdaysMin : 'sø_ma_ti_on_to_fr_lø'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D. MMMM YYYY',
        LLL : 'D. MMMM YYYY HH:mm',
        LLLL : 'dddd [d.] D. MMMM YYYY [kl.] HH:mm'
    },
    calendar : {
        sameDay : '[i dag kl.] LT',
        nextDay : '[i morgen kl.] LT',
        nextWeek : 'på dddd [kl.] LT',
        lastDay : '[i går kl.] LT',
        lastWeek : '[i] dddd[s kl.] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'om %s',
        past : '%s siden',
        s : 'få sekunder',
        ss : '%d sekunder',
        m : 'et minut',
        mm : '%d minutter',
        h : 'en time',
        hh : '%d timer',
        d : 'en dag',
        dd : '%d dage',
        M : 'en måned',
        MM : '%d måneder',
        y : 'et år',
        yy : '%d år'
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return da;

})));


/***/ }),

/***/ "Dy5G":
/*!********************************************!*\
  !*** ./node_modules/mdi-react/MenuIcon.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var MenuIcon = function MenuIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M3,6H21V8H3V6M3,11H21V13H3V11M3,16H21V18H3V16Z' })
  );
};

module.exports = MenuIcon;


/***/ }),

/***/ "DypV":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyter-widgets/output/lib/index.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(__webpack_require__(/*! ./output */ "qiq3"));


/***/ }),

/***/ "DyzK":
/*!*******************************************************!*\
  !*** ./node_modules/public-encrypt/privateDecrypt.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var parseKeys = __webpack_require__(/*! parse-asn1 */ "Ku4m")
var mgf = __webpack_require__(/*! ./mgf */ "9GDS")
var xor = __webpack_require__(/*! ./xor */ "g9U9")
var BN = __webpack_require__(/*! bn.js */ "OZ/i")
var crt = __webpack_require__(/*! browserify-rsa */ "qVij")
var createHash = __webpack_require__(/*! create-hash */ "mObS")
var withPublic = __webpack_require__(/*! ./withPublic */ "UpF+")
var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer

module.exports = function privateDecrypt (privateKey, enc, reverse) {
  var padding
  if (privateKey.padding) {
    padding = privateKey.padding
  } else if (reverse) {
    padding = 1
  } else {
    padding = 4
  }

  var key = parseKeys(privateKey)
  var k = key.modulus.byteLength()
  if (enc.length > k || new BN(enc).cmp(key.modulus) >= 0) {
    throw new Error('decryption error')
  }
  var msg
  if (reverse) {
    msg = withPublic(new BN(enc), key)
  } else {
    msg = crt(enc, key)
  }
  var zBuffer = Buffer.alloc(k - msg.length)
  msg = Buffer.concat([zBuffer, msg], k)
  if (padding === 4) {
    return oaep(key, msg)
  } else if (padding === 1) {
    return pkcs1(key, msg, reverse)
  } else if (padding === 3) {
    return msg
  } else {
    throw new Error('unknown padding')
  }
}

function oaep (key, msg) {
  var k = key.modulus.byteLength()
  var iHash = createHash('sha1').update(Buffer.alloc(0)).digest()
  var hLen = iHash.length
  if (msg[0] !== 0) {
    throw new Error('decryption error')
  }
  var maskedSeed = msg.slice(1, hLen + 1)
  var maskedDb = msg.slice(hLen + 1)
  var seed = xor(maskedSeed, mgf(maskedDb, hLen))
  var db = xor(maskedDb, mgf(seed, k - hLen - 1))
  if (compare(iHash, db.slice(0, hLen))) {
    throw new Error('decryption error')
  }
  var i = hLen
  while (db[i] === 0) {
    i++
  }
  if (db[i++] !== 1) {
    throw new Error('decryption error')
  }
  return db.slice(i)
}

function pkcs1 (key, msg, reverse) {
  var p1 = msg.slice(0, 2)
  var i = 2
  var status = 0
  while (msg[i++] !== 0) {
    if (i >= msg.length) {
      status++
      break
    }
  }
  var ps = msg.slice(2, i - 1)

  if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)) {
    status++
  }
  if (ps.length < 8) {
    status++
  }
  if (status) {
    throw new Error('decryption error')
  }
  return msg.slice(i)
}
function compare (a, b) {
  a = Buffer.from(a)
  b = Buffer.from(b)
  var dif = 0
  var len = a.length
  if (a.length !== b.length) {
    dif++
    len = Math.min(a.length, b.length)
  }
  var i = -1
  while (++i < len) {
    dif += (a[i] ^ b[i])
  }
  return dif
}


/***/ }),

/***/ "DzJC":
/*!*****************************************!*\
  !*** ./node_modules/lodash/throttle.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var debounce = __webpack_require__(/*! ./debounce */ "sEfC"),
    isObject = __webpack_require__(/*! ./isObject */ "GoyQ");

/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';

/**
 * 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
  });
}

module.exports = throttle;


/***/ }),

/***/ "Dzi0":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/tl-ph.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var tlPh = moment.defineLocale('tl-ph', {
    months : 'Enero_Pebrero_Marso_Abril_Mayo_Hunyo_Hulyo_Agosto_Setyembre_Oktubre_Nobyembre_Disyembre'.split('_'),
    monthsShort : 'Ene_Peb_Mar_Abr_May_Hun_Hul_Ago_Set_Okt_Nob_Dis'.split('_'),
    weekdays : 'Linggo_Lunes_Martes_Miyerkules_Huwebes_Biyernes_Sabado'.split('_'),
    weekdaysShort : 'Lin_Lun_Mar_Miy_Huw_Biy_Sab'.split('_'),
    weekdaysMin : 'Li_Lu_Ma_Mi_Hu_Bi_Sab'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'MM/D/YYYY',
        LL : 'MMMM D, YYYY',
        LLL : 'MMMM D, YYYY HH:mm',
        LLLL : 'dddd, MMMM DD, YYYY HH:mm'
    },
    calendar : {
        sameDay: 'LT [ngayong araw]',
        nextDay: '[Bukas ng] LT',
        nextWeek: 'LT [sa susunod na] dddd',
        lastDay: 'LT [kahapon]',
        lastWeek: 'LT [noong nakaraang] dddd',
        sameElse: 'L'
    },
    relativeTime : {
        future : 'sa loob ng %s',
        past : '%s ang nakalipas',
        s : 'ilang segundo',
        ss : '%d segundo',
        m : 'isang minuto',
        mm : '%d minuto',
        h : 'isang oras',
        hh : '%d oras',
        d : 'isang araw',
        dd : '%d araw',
        M : 'isang buwan',
        MM : '%d buwan',
        y : 'isang taon',
        yy : '%d taon'
    },
    dayOfMonthOrdinalParse: /\d{1,2}/,
    ordinal : function (number) {
        return number;
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return tlPh;

})));


/***/ }),

/***/ "E+IA":
/*!************************************************!*\
  !*** ./node_modules/hash.js/lib/hash/sha/1.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var utils = __webpack_require__(/*! ../utils */ "w8CP");
var common = __webpack_require__(/*! ../common */ "7ckf");
var shaCommon = __webpack_require__(/*! ./common */ "qlaj");

var rotl32 = utils.rotl32;
var sum32 = utils.sum32;
var sum32_5 = utils.sum32_5;
var ft_1 = shaCommon.ft_1;
var BlockHash = common.BlockHash;

var sha1_K = [
  0x5A827999, 0x6ED9EBA1,
  0x8F1BBCDC, 0xCA62C1D6
];

function SHA1() {
  if (!(this instanceof SHA1))
    return new SHA1();

  BlockHash.call(this);
  this.h = [
    0x67452301, 0xefcdab89, 0x98badcfe,
    0x10325476, 0xc3d2e1f0 ];
  this.W = new Array(80);
}

utils.inherits(SHA1, BlockHash);
module.exports = SHA1;

SHA1.blockSize = 512;
SHA1.outSize = 160;
SHA1.hmacStrength = 80;
SHA1.padLength = 64;

SHA1.prototype._update = function _update(msg, start) {
  var W = this.W;

  for (var i = 0; i < 16; i++)
    W[i] = msg[start + i];

  for(; i < W.length; i++)
    W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);

  var a = this.h[0];
  var b = this.h[1];
  var c = this.h[2];
  var d = this.h[3];
  var e = this.h[4];

  for (i = 0; i < W.length; i++) {
    var s = ~~(i / 20);
    var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);
    e = d;
    d = c;
    c = rotl32(b, 30);
    b = a;
    a = t;
  }

  this.h[0] = sum32(this.h[0], a);
  this.h[1] = sum32(this.h[1], b);
  this.h[2] = sum32(this.h[2], c);
  this.h[3] = sum32(this.h[3], d);
  this.h[4] = sum32(this.h[4], e);
};

SHA1.prototype._digest = function digest(enc) {
  if (enc === 'hex')
    return utils.toHex32(this.h, 'big');
  else
    return utils.split32(this.h, 'big');
};


/***/ }),

/***/ "E+lV":
/*!***********************************************!*\
  !*** ./node_modules/moment/locale/sr-cyrl.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var translator = {
    words: { //Different grammatical cases
        ss: ['секунда', 'секунде', 'секунди'],
        m: ['један минут', 'једне минуте'],
        mm: ['минут', 'минуте', 'минута'],
        h: ['један сат', 'једног сата'],
        hh: ['сат', 'сата', 'сати'],
        dd: ['дан', 'дана', 'дана'],
        MM: ['месец', 'месеца', 'месеци'],
        yy: ['година', 'године', 'година']
    },
    correctGrammaticalCase: function (number, wordKey) {
        return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]);
    },
    translate: function (number, withoutSuffix, key) {
        var wordKey = translator.words[key];
        if (key.length === 1) {
            return withoutSuffix ? wordKey[0] : wordKey[1];
        } else {
            return number + ' ' + translator.correctGrammaticalCase(number, wordKey);
        }
    }
};

var srCyrl = moment.defineLocale('sr-cyrl', {
    months: 'јануар_фебруар_март_април_мај_јун_јул_август_септембар_октобар_новембар_децембар'.split('_'),
    monthsShort: 'јан._феб._мар._апр._мај_јун_јул_авг._сеп._окт._нов._дец.'.split('_'),
    monthsParseExact: true,
    weekdays: 'недеља_понедељак_уторак_среда_четвртак_петак_субота'.split('_'),
    weekdaysShort: 'нед._пон._уто._сре._чет._пет._суб.'.split('_'),
    weekdaysMin: 'не_по_ут_ср_че_пе_су'.split('_'),
    weekdaysParseExact : true,
    longDateFormat: {
        LT: 'H:mm',
        LTS : 'H:mm:ss',
        L: 'DD.MM.YYYY',
        LL: 'D. MMMM YYYY',
        LLL: 'D. MMMM YYYY H:mm',
        LLLL: 'dddd, D. MMMM YYYY H:mm'
    },
    calendar: {
        sameDay: '[данас у] LT',
        nextDay: '[сутра у] LT',
        nextWeek: function () {
            switch (this.day()) {
                case 0:
                    return '[у] [недељу] [у] LT';
                case 3:
                    return '[у] [среду] [у] LT';
                case 6:
                    return '[у] [суботу] [у] LT';
                case 1:
                case 2:
                case 4:
                case 5:
                    return '[у] dddd [у] LT';
            }
        },
        lastDay  : '[јуче у] LT',
        lastWeek : function () {
            var lastWeekDays = [
                '[прошле] [недеље] [у] LT',
                '[прошлог] [понедељка] [у] LT',
                '[прошлог] [уторка] [у] LT',
                '[прошле] [среде] [у] LT',
                '[прошлог] [четвртка] [у] LT',
                '[прошлог] [петка] [у] LT',
                '[прошле] [суботе] [у] LT'
            ];
            return lastWeekDays[this.day()];
        },
        sameElse : 'L'
    },
    relativeTime : {
        future : 'за %s',
        past   : 'пре %s',
        s      : 'неколико секунди',
        ss     : translator.translate,
        m      : translator.translate,
        mm     : translator.translate,
        h      : translator.translate,
        hh     : translator.translate,
        d      : 'дан',
        dd     : translator.translate,
        M      : 'месец',
        MM     : translator.translate,
        y      : 'годину',
        yy     : translator.translate
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return srCyrl;

})));


/***/ }),

/***/ "E01D":
/*!**************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/Numeric.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UnconnectedNumeric = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _NumericInput = __webpack_require__(/*! ../widgets/NumericInput */ "2NAh");

var _NumericInput2 = _interopRequireDefault(_NumericInput);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UnconnectedNumeric = exports.UnconnectedNumeric = function (_Component) {
  _inherits(UnconnectedNumeric, _Component);

  function UnconnectedNumeric() {
    _classCallCheck(this, UnconnectedNumeric);

    return _possibleConstructorReturn(this, (UnconnectedNumeric.__proto__ || Object.getPrototypeOf(UnconnectedNumeric)).apply(this, arguments));
  }

  _createClass(UnconnectedNumeric, [{
    key: 'render',
    value: function render() {
      var fullValue = this.props.fullValue;
      var placeholder = void 0;
      if (this.props.multiValued) {
        placeholder = fullValue;
        fullValue = '';
      }

      return _react2.default.createElement(
        _Field2.default,
        this.props,
        _react2.default.createElement(_NumericInput2.default, {
          value: fullValue,
          defaultValue: this.props.defaultValue,
          placeholder: placeholder,
          step: this.props.step,
          stepmode: this.props.stepmode,
          min: this.props.min,
          max: this.props.max,
          onChange: this.props.updatePlot,
          onUpdate: this.props.updatePlot,
          showArrows: !this.props.hideArrows,
          showSlider: this.props.showSlider
        })
      );
    }
  }]);

  return UnconnectedNumeric;
}(_react.Component);

UnconnectedNumeric.propTypes = _extends({
  defaultValue: _propTypes2.default.any,
  fullValue: _propTypes2.default.any,
  min: _propTypes2.default.number,
  max: _propTypes2.default.number,
  multiValued: _propTypes2.default.bool,
  hideArrows: _propTypes2.default.bool,
  showSlider: _propTypes2.default.bool,
  step: _propTypes2.default.number,
  stepmode: _propTypes2.default.string,
  updatePlot: _propTypes2.default.func
}, _Field2.default.propTypes);

exports.default = (0, _lib.connectToContainer)(UnconnectedNumeric);
//# sourceMappingURL=Numeric.js.map

/***/ }),

/***/ "E1lr":
/*!*********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/default_panels/StyleSlidersPanel.js ***!
  \*********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _components = __webpack_require__(/*! ../components */ "yF51");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var StyleSlidersPanel = function StyleSlidersPanel(props, _ref) {
  var _ = _ref.localize;
  return _react2.default.createElement(
    _components.SliderAccordion,
    null,
    _react2.default.createElement(_components.Radio, {
      attr: 'visible',
      options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
    }),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Background') },
      _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'bgcolor' }),
      _react2.default.createElement(_components.ColorPicker, { label: _('Active Color'), attr: 'activebgcolor' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Border') },
      _react2.default.createElement(_components.Numeric, { label: _('Width'), attr: 'borderwidth' }),
      _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'bordercolor' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Font') },
      _react2.default.createElement(_components.FontSelector, { label: _('Typeface'), attr: 'font.family' }),
      _react2.default.createElement(_components.Numeric, { label: _('Size'), attr: 'font.size' }),
      _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'font.color' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Length'), attr: 'len' },
      _react2.default.createElement(_components.Numeric, { label: _('Length'), attr: 'len', step: 0.02 }),
      _react2.default.createElement(_components.Dropdown, {
        label: _('Length Mode'),
        attr: 'lenmode',
        options: [{ label: _('Fraction of canvas'), value: 'fraction' }, { label: _('Pixels'), value: 'pixels' }]
      })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Horizontal Positioning'), attr: 'x' },
      _react2.default.createElement(_components.Numeric, { label: _('Position'), attr: 'x', showSlider: true, step: 0.02 }),
      _react2.default.createElement(_components.Radio, {
        label: _('Anchor'),
        attr: 'xanchor',
        options: [{ label: _('Left'), value: 'left' }, { label: _('Center'), value: 'center' }, { label: _('Right'), value: 'right' }]
      })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Vertical Positioning'), attr: 'y' },
      _react2.default.createElement(_components.Numeric, { label: _('Position'), attr: 'y', showSlider: true, step: 0.02 }),
      _react2.default.createElement(_components.Radio, {
        label: _('Anchor'),
        attr: 'yanchor',
        options: [{ label: _('Top'), value: 'top' }, { label: _('Middle'), value: 'middle' }, { label: _('Bottom'), value: 'bottom' }]
      })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Padding') },
      _react2.default.createElement(_components.Numeric, { label: _('Top'), attr: 'pad.t', units: 'px' }),
      _react2.default.createElement(_components.Numeric, { label: _('Bottom'), attr: 'pad.b', units: 'px' }),
      _react2.default.createElement(_components.Numeric, { label: _('Left'), attr: 'pad.l', units: 'px' }),
      _react2.default.createElement(_components.Numeric, { label: _('Right'), attr: 'pad.r', units: 'px' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Ticks') },
      _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'tickcolor' }),
      _react2.default.createElement(_components.Numeric, { label: _('Length'), attr: 'ticklen' }),
      _react2.default.createElement(_components.Numeric, { label: _('Width'), attr: 'tickwidth' })
    )
  );
};

StyleSlidersPanel.contextTypes = {
  localize: _propTypes2.default.func
};

exports.default = StyleSlidersPanel;
//# sourceMappingURL=StyleSlidersPanel.js.map

/***/ }),

/***/ "E2g8":
/*!******************************************************!*\
  !*** ./node_modules/es6-promise/dist/es6-promise.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(process, global) {var require;/*!
 * @overview es6-promise - a tiny implementation of Promises/A+.
 * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
 * @license   Licensed under MIT license
 *            See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
 * @version   4.1.1
 */

(function (global, factory) {
	 true ? module.exports = factory() :
	undefined;
}(this, (function () { 'use strict';

function objectOrFunction(x) {
  var type = typeof x;
  return x !== null && (type === 'object' || type === 'function');
}

function isFunction(x) {
  return typeof x === 'function';
}

var _isArray = undefined;
if (Array.isArray) {
  _isArray = Array.isArray;
} else {
  _isArray = function (x) {
    return Object.prototype.toString.call(x) === '[object Array]';
  };
}

var isArray = _isArray;

var len = 0;
var vertxNext = undefined;
var customSchedulerFn = undefined;

var asap = function asap(callback, arg) {
  queue[len] = callback;
  queue[len + 1] = arg;
  len += 2;
  if (len === 2) {
    // If len is 2, that means that we need to schedule an async flush.
    // If additional callbacks are queued before the queue is flushed, they
    // will be processed by this flush that we are scheduling.
    if (customSchedulerFn) {
      customSchedulerFn(flush);
    } else {
      scheduleFlush();
    }
  }
};

function setScheduler(scheduleFn) {
  customSchedulerFn = scheduleFn;
}

function setAsap(asapFn) {
  asap = asapFn;
}

var browserWindow = typeof window !== 'undefined' ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';

// test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';

// node
function useNextTick() {
  // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  // see https://github.com/cujojs/when/issues/410 for details
  return function () {
    return process.nextTick(flush);
  };
}

// vertx
function useVertxTimer() {
  if (typeof vertxNext !== 'undefined') {
    return function () {
      vertxNext(flush);
    };
  }

  return useSetTimeout();
}

function useMutationObserver() {
  var iterations = 0;
  var observer = new BrowserMutationObserver(flush);
  var node = document.createTextNode('');
  observer.observe(node, { characterData: true });

  return function () {
    node.data = iterations = ++iterations % 2;
  };
}

// web worker
function useMessageChannel() {
  var channel = new MessageChannel();
  channel.port1.onmessage = flush;
  return function () {
    return channel.port2.postMessage(0);
  };
}

function useSetTimeout() {
  // Store setTimeout reference so es6-promise will be unaffected by
  // other code modifying setTimeout (like sinon.useFakeTimers())
  var globalSetTimeout = setTimeout;
  return function () {
    return globalSetTimeout(flush, 1);
  };
}

var queue = new Array(1000);
function flush() {
  for (var i = 0; i < len; i += 2) {
    var callback = queue[i];
    var arg = queue[i + 1];

    callback(arg);

    queue[i] = undefined;
    queue[i + 1] = undefined;
  }

  len = 0;
}

function attemptVertx() {
  try {
    var r = require;
    var vertx = __webpack_require__(/*! vertx */ 1);
    vertxNext = vertx.runOnLoop || vertx.runOnContext;
    return useVertxTimer();
  } catch (e) {
    return useSetTimeout();
  }
}

var scheduleFlush = undefined;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
  scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
  scheduleFlush = useMutationObserver();
} else if (isWorker) {
  scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && "function" === 'function') {
  scheduleFlush = attemptVertx();
} else {
  scheduleFlush = useSetTimeout();
}

function then(onFulfillment, onRejection) {
  var _arguments = arguments;

  var parent = this;

  var child = new this.constructor(noop);

  if (child[PROMISE_ID] === undefined) {
    makePromise(child);
  }

  var _state = parent._state;

  if (_state) {
    (function () {
      var callback = _arguments[_state - 1];
      asap(function () {
        return invokeCallback(_state, child, callback, parent._result);
      });
    })();
  } else {
    subscribe(parent, child, onFulfillment, onRejection);
  }

  return child;
}

/**
  `Promise.resolve` returns a promise that will become resolved with the
  passed `value`. It is shorthand for the following:

  ```javascript
  let promise = new Promise(function(resolve, reject){
    resolve(1);
  });

  promise.then(function(value){
    // value === 1
  });
  ```

  Instead of writing the above, your code now simply becomes the following:

  ```javascript
  let promise = Promise.resolve(1);

  promise.then(function(value){
    // value === 1
  });
  ```

  @method resolve
  @static
  @param {Any} value value that the returned promise will be resolved with
  Useful for tooling.
  @return {Promise} a promise that will become fulfilled with the given
  `value`
*/
function resolve$1(object) {
  /*jshint validthis:true */
  var Constructor = this;

  if (object && typeof object === 'object' && object.constructor === Constructor) {
    return object;
  }

  var promise = new Constructor(noop);
  resolve(promise, object);
  return promise;
}

var PROMISE_ID = Math.random().toString(36).substring(16);

function noop() {}

var PENDING = void 0;
var FULFILLED = 1;
var REJECTED = 2;

var GET_THEN_ERROR = new ErrorObject();

function selfFulfillment() {
  return new TypeError("You cannot resolve a promise with itself");
}

function cannotReturnOwn() {
  return new TypeError('A promises callback cannot return that same promise.');
}

function getThen(promise) {
  try {
    return promise.then;
  } catch (error) {
    GET_THEN_ERROR.error = error;
    return GET_THEN_ERROR;
  }
}

function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
  try {
    then$$1.call(value, fulfillmentHandler, rejectionHandler);
  } catch (e) {
    return e;
  }
}

function handleForeignThenable(promise, thenable, then$$1) {
  asap(function (promise) {
    var sealed = false;
    var error = tryThen(then$$1, thenable, function (value) {
      if (sealed) {
        return;
      }
      sealed = true;
      if (thenable !== value) {
        resolve(promise, value);
      } else {
        fulfill(promise, value);
      }
    }, function (reason) {
      if (sealed) {
        return;
      }
      sealed = true;

      reject(promise, reason);
    }, 'Settle: ' + (promise._label || ' unknown promise'));

    if (!sealed && error) {
      sealed = true;
      reject(promise, error);
    }
  }, promise);
}

function handleOwnThenable(promise, thenable) {
  if (thenable._state === FULFILLED) {
    fulfill(promise, thenable._result);
  } else if (thenable._state === REJECTED) {
    reject(promise, thenable._result);
  } else {
    subscribe(thenable, undefined, function (value) {
      return resolve(promise, value);
    }, function (reason) {
      return reject(promise, reason);
    });
  }
}

function handleMaybeThenable(promise, maybeThenable, then$$1) {
  if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
    handleOwnThenable(promise, maybeThenable);
  } else {
    if (then$$1 === GET_THEN_ERROR) {
      reject(promise, GET_THEN_ERROR.error);
      GET_THEN_ERROR.error = null;
    } else if (then$$1 === undefined) {
      fulfill(promise, maybeThenable);
    } else if (isFunction(then$$1)) {
      handleForeignThenable(promise, maybeThenable, then$$1);
    } else {
      fulfill(promise, maybeThenable);
    }
  }
}

function resolve(promise, value) {
  if (promise === value) {
    reject(promise, selfFulfillment());
  } else if (objectOrFunction(value)) {
    handleMaybeThenable(promise, value, getThen(value));
  } else {
    fulfill(promise, value);
  }
}

function publishRejection(promise) {
  if (promise._onerror) {
    promise._onerror(promise._result);
  }

  publish(promise);
}

function fulfill(promise, value) {
  if (promise._state !== PENDING) {
    return;
  }

  promise._result = value;
  promise._state = FULFILLED;

  if (promise._subscribers.length !== 0) {
    asap(publish, promise);
  }
}

function reject(promise, reason) {
  if (promise._state !== PENDING) {
    return;
  }
  promise._state = REJECTED;
  promise._result = reason;

  asap(publishRejection, promise);
}

function subscribe(parent, child, onFulfillment, onRejection) {
  var _subscribers = parent._subscribers;
  var length = _subscribers.length;

  parent._onerror = null;

  _subscribers[length] = child;
  _subscribers[length + FULFILLED] = onFulfillment;
  _subscribers[length + REJECTED] = onRejection;

  if (length === 0 && parent._state) {
    asap(publish, parent);
  }
}

function publish(promise) {
  var subscribers = promise._subscribers;
  var settled = promise._state;

  if (subscribers.length === 0) {
    return;
  }

  var child = undefined,
      callback = undefined,
      detail = promise._result;

  for (var i = 0; i < subscribers.length; i += 3) {
    child = subscribers[i];
    callback = subscribers[i + settled];

    if (child) {
      invokeCallback(settled, child, callback, detail);
    } else {
      callback(detail);
    }
  }

  promise._subscribers.length = 0;
}

function ErrorObject() {
  this.error = null;
}

var TRY_CATCH_ERROR = new ErrorObject();

function tryCatch(callback, detail) {
  try {
    return callback(detail);
  } catch (e) {
    TRY_CATCH_ERROR.error = e;
    return TRY_CATCH_ERROR;
  }
}

function invokeCallback(settled, promise, callback, detail) {
  var hasCallback = isFunction(callback),
      value = undefined,
      error = undefined,
      succeeded = undefined,
      failed = undefined;

  if (hasCallback) {
    value = tryCatch(callback, detail);

    if (value === TRY_CATCH_ERROR) {
      failed = true;
      error = value.error;
      value.error = null;
    } else {
      succeeded = true;
    }

    if (promise === value) {
      reject(promise, cannotReturnOwn());
      return;
    }
  } else {
    value = detail;
    succeeded = true;
  }

  if (promise._state !== PENDING) {
    // noop
  } else if (hasCallback && succeeded) {
      resolve(promise, value);
    } else if (failed) {
      reject(promise, error);
    } else if (settled === FULFILLED) {
      fulfill(promise, value);
    } else if (settled === REJECTED) {
      reject(promise, value);
    }
}

function initializePromise(promise, resolver) {
  try {
    resolver(function resolvePromise(value) {
      resolve(promise, value);
    }, function rejectPromise(reason) {
      reject(promise, reason);
    });
  } catch (e) {
    reject(promise, e);
  }
}

var id = 0;
function nextId() {
  return id++;
}

function makePromise(promise) {
  promise[PROMISE_ID] = id++;
  promise._state = undefined;
  promise._result = undefined;
  promise._subscribers = [];
}

function Enumerator$1(Constructor, input) {
  this._instanceConstructor = Constructor;
  this.promise = new Constructor(noop);

  if (!this.promise[PROMISE_ID]) {
    makePromise(this.promise);
  }

  if (isArray(input)) {
    this.length = input.length;
    this._remaining = input.length;

    this._result = new Array(this.length);

    if (this.length === 0) {
      fulfill(this.promise, this._result);
    } else {
      this.length = this.length || 0;
      this._enumerate(input);
      if (this._remaining === 0) {
        fulfill(this.promise, this._result);
      }
    }
  } else {
    reject(this.promise, validationError());
  }
}

function validationError() {
  return new Error('Array Methods must be provided an Array');
}

Enumerator$1.prototype._enumerate = function (input) {
  for (var i = 0; this._state === PENDING && i < input.length; i++) {
    this._eachEntry(input[i], i);
  }
};

Enumerator$1.prototype._eachEntry = function (entry, i) {
  var c = this._instanceConstructor;
  var resolve$$1 = c.resolve;

  if (resolve$$1 === resolve$1) {
    var _then = getThen(entry);

    if (_then === then && entry._state !== PENDING) {
      this._settledAt(entry._state, i, entry._result);
    } else if (typeof _then !== 'function') {
      this._remaining--;
      this._result[i] = entry;
    } else if (c === Promise$2) {
      var promise = new c(noop);
      handleMaybeThenable(promise, entry, _then);
      this._willSettleAt(promise, i);
    } else {
      this._willSettleAt(new c(function (resolve$$1) {
        return resolve$$1(entry);
      }), i);
    }
  } else {
    this._willSettleAt(resolve$$1(entry), i);
  }
};

Enumerator$1.prototype._settledAt = function (state, i, value) {
  var promise = this.promise;

  if (promise._state === PENDING) {
    this._remaining--;

    if (state === REJECTED) {
      reject(promise, value);
    } else {
      this._result[i] = value;
    }
  }

  if (this._remaining === 0) {
    fulfill(promise, this._result);
  }
};

Enumerator$1.prototype._willSettleAt = function (promise, i) {
  var enumerator = this;

  subscribe(promise, undefined, function (value) {
    return enumerator._settledAt(FULFILLED, i, value);
  }, function (reason) {
    return enumerator._settledAt(REJECTED, i, reason);
  });
};

/**
  `Promise.all` accepts an array of promises, and returns a new promise which
  is fulfilled with an array of fulfillment values for the passed promises, or
  rejected with the reason of the first passed promise to be rejected. It casts all
  elements of the passed iterable to promises as it runs this algorithm.

  Example:

  ```javascript
  let promise1 = resolve(1);
  let promise2 = resolve(2);
  let promise3 = resolve(3);
  let promises = [ promise1, promise2, promise3 ];

  Promise.all(promises).then(function(array){
    // The array here would be [ 1, 2, 3 ];
  });
  ```

  If any of the `promises` given to `all` are rejected, the first promise
  that is rejected will be given as an argument to the returned promises's
  rejection handler. For example:

  Example:

  ```javascript
  let promise1 = resolve(1);
  let promise2 = reject(new Error("2"));
  let promise3 = reject(new Error("3"));
  let promises = [ promise1, promise2, promise3 ];

  Promise.all(promises).then(function(array){
    // Code here never runs because there are rejected promises!
  }, function(error) {
    // error.message === "2"
  });
  ```

  @method all
  @static
  @param {Array} entries array of promises
  @param {String} label optional string for labeling the promise.
  Useful for tooling.
  @return {Promise} promise that is fulfilled when all `promises` have been
  fulfilled, or rejected if any of them become rejected.
  @static
*/
function all$1(entries) {
  return new Enumerator$1(this, entries).promise;
}

/**
  `Promise.race` returns a new promise which is settled in the same way as the
  first passed promise to settle.

  Example:

  ```javascript
  let promise1 = new Promise(function(resolve, reject){
    setTimeout(function(){
      resolve('promise 1');
    }, 200);
  });

  let promise2 = new Promise(function(resolve, reject){
    setTimeout(function(){
      resolve('promise 2');
    }, 100);
  });

  Promise.race([promise1, promise2]).then(function(result){
    // result === 'promise 2' because it was resolved before promise1
    // was resolved.
  });
  ```

  `Promise.race` is deterministic in that only the state of the first
  settled promise matters. For example, even if other promises given to the
  `promises` array argument are resolved, but the first settled promise has
  become rejected before the other promises became fulfilled, the returned
  promise will become rejected:

  ```javascript
  let promise1 = new Promise(function(resolve, reject){
    setTimeout(function(){
      resolve('promise 1');
    }, 200);
  });

  let promise2 = new Promise(function(resolve, reject){
    setTimeout(function(){
      reject(new Error('promise 2'));
    }, 100);
  });

  Promise.race([promise1, promise2]).then(function(result){
    // Code here never runs
  }, function(reason){
    // reason.message === 'promise 2' because promise 2 became rejected before
    // promise 1 became fulfilled
  });
  ```

  An example real-world use case is implementing timeouts:

  ```javascript
  Promise.race([ajax('foo.json'), timeout(5000)])
  ```

  @method race
  @static
  @param {Array} promises array of promises to observe
  Useful for tooling.
  @return {Promise} a promise which settles in the same way as the first passed
  promise to settle.
*/
function race$1(entries) {
  /*jshint validthis:true */
  var Constructor = this;

  if (!isArray(entries)) {
    return new Constructor(function (_, reject) {
      return reject(new TypeError('You must pass an array to race.'));
    });
  } else {
    return new Constructor(function (resolve, reject) {
      var length = entries.length;
      for (var i = 0; i < length; i++) {
        Constructor.resolve(entries[i]).then(resolve, reject);
      }
    });
  }
}

/**
  `Promise.reject` returns a promise rejected with the passed `reason`.
  It is shorthand for the following:

  ```javascript
  let promise = new Promise(function(resolve, reject){
    reject(new Error('WHOOPS'));
  });

  promise.then(function(value){
    // Code here doesn't run because the promise is rejected!
  }, function(reason){
    // reason.message === 'WHOOPS'
  });
  ```

  Instead of writing the above, your code now simply becomes the following:

  ```javascript
  let promise = Promise.reject(new Error('WHOOPS'));

  promise.then(function(value){
    // Code here doesn't run because the promise is rejected!
  }, function(reason){
    // reason.message === 'WHOOPS'
  });
  ```

  @method reject
  @static
  @param {Any} reason value that the returned promise will be rejected with.
  Useful for tooling.
  @return {Promise} a promise rejected with the given `reason`.
*/
function reject$1(reason) {
  /*jshint validthis:true */
  var Constructor = this;
  var promise = new Constructor(noop);
  reject(promise, reason);
  return promise;
}

function needsResolver() {
  throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}

function needsNew() {
  throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}

/**
  Promise objects represent the eventual result of an asynchronous operation. The
  primary way of interacting with a promise is through its `then` method, which
  registers callbacks to receive either a promise's eventual value or the reason
  why the promise cannot be fulfilled.

  Terminology
  -----------

  - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  - `thenable` is an object or function that defines a `then` method.
  - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  - `exception` is a value that is thrown using the throw statement.
  - `reason` is a value that indicates why a promise was rejected.
  - `settled` the final resting state of a promise, fulfilled or rejected.

  A promise can be in one of three states: pending, fulfilled, or rejected.

  Promises that are fulfilled have a fulfillment value and are in the fulfilled
  state.  Promises that are rejected have a rejection reason and are in the
  rejected state.  A fulfillment value is never a thenable.

  Promises can also be said to *resolve* a value.  If this value is also a
  promise, then the original promise's settled state will match the value's
  settled state.  So a promise that *resolves* a promise that rejects will
  itself reject, and a promise that *resolves* a promise that fulfills will
  itself fulfill.


  Basic Usage:
  ------------

  ```js
  let promise = new Promise(function(resolve, reject) {
    // on success
    resolve(value);

    // on failure
    reject(reason);
  });

  promise.then(function(value) {
    // on fulfillment
  }, function(reason) {
    // on rejection
  });
  ```

  Advanced Usage:
  ---------------

  Promises shine when abstracting away asynchronous interactions such as
  `XMLHttpRequest`s.

  ```js
  function getJSON(url) {
    return new Promise(function(resolve, reject){
      let xhr = new XMLHttpRequest();

      xhr.open('GET', url);
      xhr.onreadystatechange = handler;
      xhr.responseType = 'json';
      xhr.setRequestHeader('Accept', 'application/json');
      xhr.send();

      function handler() {
        if (this.readyState === this.DONE) {
          if (this.status === 200) {
            resolve(this.response);
          } else {
            reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
          }
        }
      };
    });
  }

  getJSON('/posts.json').then(function(json) {
    // on fulfillment
  }, function(reason) {
    // on rejection
  });
  ```

  Unlike callbacks, promises are great composable primitives.

  ```js
  Promise.all([
    getJSON('/posts'),
    getJSON('/comments')
  ]).then(function(values){
    values[0] // => postsJSON
    values[1] // => commentsJSON

    return values;
  });
  ```

  @class Promise
  @param {function} resolver
  Useful for tooling.
  @constructor
*/
function Promise$2(resolver) {
  this[PROMISE_ID] = nextId();
  this._result = this._state = undefined;
  this._subscribers = [];

  if (noop !== resolver) {
    typeof resolver !== 'function' && needsResolver();
    this instanceof Promise$2 ? initializePromise(this, resolver) : needsNew();
  }
}

Promise$2.all = all$1;
Promise$2.race = race$1;
Promise$2.resolve = resolve$1;
Promise$2.reject = reject$1;
Promise$2._setScheduler = setScheduler;
Promise$2._setAsap = setAsap;
Promise$2._asap = asap;

Promise$2.prototype = {
  constructor: Promise$2,

  /**
    The primary way of interacting with a promise is through its `then` method,
    which registers callbacks to receive either a promise's eventual value or the
    reason why the promise cannot be fulfilled.
  
    ```js
    findUser().then(function(user){
      // user is available
    }, function(reason){
      // user is unavailable, and you are given the reason why
    });
    ```
  
    Chaining
    --------
  
    The return value of `then` is itself a promise.  This second, 'downstream'
    promise is resolved with the return value of the first promise's fulfillment
    or rejection handler, or rejected if the handler throws an exception.
  
    ```js
    findUser().then(function (user) {
      return user.name;
    }, function (reason) {
      return 'default name';
    }).then(function (userName) {
      // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
      // will be `'default name'`
    });
  
    findUser().then(function (user) {
      throw new Error('Found user, but still unhappy');
    }, function (reason) {
      throw new Error('`findUser` rejected and we're unhappy');
    }).then(function (value) {
      // never reached
    }, function (reason) {
      // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
      // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
    });
    ```
    If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  
    ```js
    findUser().then(function (user) {
      throw new PedagogicalException('Upstream error');
    }).then(function (value) {
      // never reached
    }).then(function (value) {
      // never reached
    }, function (reason) {
      // The `PedgagocialException` is propagated all the way down to here
    });
    ```
  
    Assimilation
    ------------
  
    Sometimes the value you want to propagate to a downstream promise can only be
    retrieved asynchronously. This can be achieved by returning a promise in the
    fulfillment or rejection handler. The downstream promise will then be pending
    until the returned promise is settled. This is called *assimilation*.
  
    ```js
    findUser().then(function (user) {
      return findCommentsByAuthor(user);
    }).then(function (comments) {
      // The user's comments are now available
    });
    ```
  
    If the assimliated promise rejects, then the downstream promise will also reject.
  
    ```js
    findUser().then(function (user) {
      return findCommentsByAuthor(user);
    }).then(function (comments) {
      // If `findCommentsByAuthor` fulfills, we'll have the value here
    }, function (reason) {
      // If `findCommentsByAuthor` rejects, we'll have the reason here
    });
    ```
  
    Simple Example
    --------------
  
    Synchronous Example
  
    ```javascript
    let result;
  
    try {
      result = findResult();
      // success
    } catch(reason) {
      // failure
    }
    ```
  
    Errback Example
  
    ```js
    findResult(function(result, err){
      if (err) {
        // failure
      } else {
        // success
      }
    });
    ```
  
    Promise Example;
  
    ```javascript
    findResult().then(function(result){
      // success
    }, function(reason){
      // failure
    });
    ```
  
    Advanced Example
    --------------
  
    Synchronous Example
  
    ```javascript
    let author, books;
  
    try {
      author = findAuthor();
      books  = findBooksByAuthor(author);
      // success
    } catch(reason) {
      // failure
    }
    ```
  
    Errback Example
  
    ```js
  
    function foundBooks(books) {
  
    }
  
    function failure(reason) {
  
    }
  
    findAuthor(function(author, err){
      if (err) {
        failure(err);
        // failure
      } else {
        try {
          findBoooksByAuthor(author, function(books, err) {
            if (err) {
              failure(err);
            } else {
              try {
                foundBooks(books);
              } catch(reason) {
                failure(reason);
              }
            }
          });
        } catch(error) {
          failure(err);
        }
        // success
      }
    });
    ```
  
    Promise Example;
  
    ```javascript
    findAuthor().
      then(findBooksByAuthor).
      then(function(books){
        // found books
    }).catch(function(reason){
      // something went wrong
    });
    ```
  
    @method then
    @param {Function} onFulfilled
    @param {Function} onRejected
    Useful for tooling.
    @return {Promise}
  */
  then: then,

  /**
    `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
    as the catch block of a try/catch statement.
  
    ```js
    function findAuthor(){
      throw new Error('couldn't find that author');
    }
  
    // synchronous
    try {
      findAuthor();
    } catch(reason) {
      // something went wrong
    }
  
    // async with promises
    findAuthor().catch(function(reason){
      // something went wrong
    });
    ```
  
    @method catch
    @param {Function} onRejection
    Useful for tooling.
    @return {Promise}
  */
  'catch': function _catch(onRejection) {
    return this.then(null, onRejection);
  }
};

/*global self*/
function polyfill$1() {
    var local = undefined;

    if (typeof global !== 'undefined') {
        local = global;
    } else if (typeof self !== 'undefined') {
        local = self;
    } else {
        try {
            local = Function('return this')();
        } catch (e) {
            throw new Error('polyfill failed because global object is unavailable in this environment');
        }
    }

    var P = local.Promise;

    if (P) {
        var promiseToString = null;
        try {
            promiseToString = Object.prototype.toString.call(P.resolve());
        } catch (e) {
            // silently ignored
        }

        if (promiseToString === '[object Promise]' && !P.cast) {
            return;
        }
    }

    local.Promise = Promise$2;
}

// Strange compat..
Promise$2.polyfill = polyfill$1;
Promise$2.Promise = Promise$2;

return Promise$2;

})));

//# sourceMappingURL=es6-promise.map

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ "8oxB"), __webpack_require__(/*! ./../../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "E2jh":
/*!******************************************!*\
  !*** ./node_modules/lodash/_isMasked.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var coreJsData = __webpack_require__(/*! ./_coreJsData */ "2gN3");

/** 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) : '';
}());

/**
 * 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);
}

module.exports = isMasked;


/***/ }),

/***/ "E4V0":
/*!***********************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/is_plain_object.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




// more info: http://stackoverflow.com/questions/18531624/isplainobject-thing
module.exports = function isPlainObject(obj) {

    // We need to be a little less strict in the `imagetest` container because
    // of how async image requests are handled.
    //
    // N.B. isPlainObject(new Constructor()) will return true in `imagetest`
    if(window && window.process && window.process.versions) {
        return Object.prototype.toString.call(obj) === '[object Object]';
    }

    return (
        Object.prototype.toString.call(obj) === '[object Object]' &&
        Object.getPrototypeOf(obj) === Object.prototype
    );
};


/***/ }),

/***/ "E4Z0":
/*!*****************************************!*\
  !*** ./node_modules/ansi_up/ansi_up.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*  ansi_up.js
 *  author : Dru Nelson
 *  license : MIT
 *  http://github.com/drudru/ansi_up
 */
(function (root, factory) {
    if (true) {
        // AMD. Register as an anonymous module.
        !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
    } else { var exp; }
}(this, function (exports) {
"use strict";
function rgx(tmplObj) {
    var subst = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        subst[_i - 1] = arguments[_i];
    }
    var regexText = tmplObj.raw[0];
    var wsrgx = /^\s+|\s+\n|\s+#[\s\S]+?\n/gm;
    var txt2 = regexText.replace(wsrgx, '');
    return new RegExp(txt2, 'm');
}
var AnsiUp = (function () {
    function AnsiUp() {
        this.VERSION = "3.0.0";
        this.ansi_colors = [
            [
                { rgb: [0, 0, 0], class_name: "ansi-black" },
                { rgb: [187, 0, 0], class_name: "ansi-red" },
                { rgb: [0, 187, 0], class_name: "ansi-green" },
                { rgb: [187, 187, 0], class_name: "ansi-yellow" },
                { rgb: [0, 0, 187], class_name: "ansi-blue" },
                { rgb: [187, 0, 187], class_name: "ansi-magenta" },
                { rgb: [0, 187, 187], class_name: "ansi-cyan" },
                { rgb: [255, 255, 255], class_name: "ansi-white" }
            ],
            [
                { rgb: [85, 85, 85], class_name: "ansi-bright-black" },
                { rgb: [255, 85, 85], class_name: "ansi-bright-red" },
                { rgb: [0, 255, 0], class_name: "ansi-bright-green" },
                { rgb: [255, 255, 85], class_name: "ansi-bright-yellow" },
                { rgb: [85, 85, 255], class_name: "ansi-bright-blue" },
                { rgb: [255, 85, 255], class_name: "ansi-bright-magenta" },
                { rgb: [85, 255, 255], class_name: "ansi-bright-cyan" },
                { rgb: [255, 255, 255], class_name: "ansi-bright-white" }
            ]
        ];
        this.htmlFormatter = {
            transform: function (fragment, instance) {
                var txt = fragment.text;
                if (txt.length === 0)
                    return txt;
                if (instance._escape_for_html)
                    txt = instance.old_escape_for_html(txt);
                if (!fragment.bold && fragment.fg === null && fragment.bg === null)
                    return txt;
                var styles = [];
                var classes = [];
                var fg = fragment.fg;
                var bg = fragment.bg;
                if (fragment.bold)
                    styles.push('font-weight:bold');
                if (!instance._use_classes) {
                    if (fg)
                        styles.push("color:rgb(" + fg.rgb.join(',') + ")");
                    if (bg)
                        styles.push("background-color:rgb(" + bg.rgb + ")");
                }
                else {
                    if (fg) {
                        if (fg.class_name !== 'truecolor') {
                            classes.push(fg.class_name + "-fg");
                        }
                        else {
                            styles.push("color:rgb(" + fg.rgb.join(',') + ")");
                        }
                    }
                    if (bg) {
                        if (bg.class_name !== 'truecolor') {
                            classes.push(bg.class_name + "-bg");
                        }
                        else {
                            styles.push("background-color:rgb(" + bg.rgb.join(',') + ")");
                        }
                    }
                }
                var class_string = '';
                var style_string = '';
                if (classes.length)
                    class_string = " class=\"" + classes.join(' ') + "\"";
                if (styles.length)
                    style_string = " style=\"" + styles.join(';') + "\"";
                return "<span" + style_string + class_string + ">" + txt + "</span>";
            },
            compose: function (segments, instance) {
                return segments.join("");
            }
        };
        this.textFormatter = {
            transform: function (fragment, instance) {
                return fragment.text;
            },
            compose: function (segments, instance) {
                return segments.join("");
            }
        };
        this.setup_256_palette();
        this._use_classes = false;
        this._escape_for_html = true;
        this.bold = false;
        this.fg = this.bg = null;
        this._buffer = '';
    }
    Object.defineProperty(AnsiUp.prototype, "use_classes", {
        get: function () {
            return this._use_classes;
        },
        set: function (arg) {
            this._use_classes = arg;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(AnsiUp.prototype, "escape_for_html", {
        get: function () {
            return this._escape_for_html;
        },
        set: function (arg) {
            this._escape_for_html = arg;
        },
        enumerable: true,
        configurable: true
    });
    AnsiUp.prototype.setup_256_palette = function () {
        var _this = this;
        this.palette_256 = [];
        this.ansi_colors.forEach(function (palette) {
            palette.forEach(function (rec) {
                _this.palette_256.push(rec);
            });
        });
        var levels = [0, 95, 135, 175, 215, 255];
        for (var r = 0; r < 6; ++r) {
            for (var g = 0; g < 6; ++g) {
                for (var b = 0; b < 6; ++b) {
                    var col = { rgb: [levels[r], levels[g], levels[b]], class_name: 'truecolor' };
                    this.palette_256.push(col);
                }
            }
        }
        var grey_level = 8;
        for (var i = 0; i < 24; ++i, grey_level += 10) {
            var gry = { rgb: [grey_level, grey_level, grey_level], class_name: 'truecolor' };
            this.palette_256.push(gry);
        }
    };
    AnsiUp.prototype.old_escape_for_html = function (txt) {
        return txt.replace(/[&<>]/gm, function (str) {
            if (str === "&")
                return "&amp;";
            if (str === "<")
                return "&lt;";
            if (str === ">")
                return "&gt;";
        });
    };
    AnsiUp.prototype.old_linkify = function (txt) {
        return txt.replace(/(https?:\/\/[^\s]+)/gm, function (str) {
            return "<a href=\"" + str + "\">" + str + "</a>";
        });
    };
    AnsiUp.prototype.detect_incomplete_ansi = function (txt) {
        return !(/.*?[\x40-\x7e]/.test(txt));
    };
    AnsiUp.prototype.detect_incomplete_link = function (txt) {
        var found = false;
        for (var i = txt.length - 1; i > 0; i--) {
            if (/\s|\x1B/.test(txt[i])) {
                found = true;
                break;
            }
        }
        if (!found) {
            if (/(https?:\/\/[^\s]+)/.test(txt))
                return 0;
            else
                return -1;
        }
        var prefix = txt.substr(i + 1, 4);
        if (prefix.length === 0)
            return -1;
        if ("http".indexOf(prefix) === 0)
            return (i + 1);
    };
    AnsiUp.prototype.ansi_to = function (txt, formatter) {
        var pkt = this._buffer + txt;
        this._buffer = '';
        var raw_text_pkts = pkt.split(/\x1B\[/);
        if (raw_text_pkts.length === 1)
            raw_text_pkts.push('');
        this.handle_incomplete_sequences(raw_text_pkts);
        var first_chunk = this.with_state(raw_text_pkts.shift());
        var blocks = new Array(raw_text_pkts.length);
        for (var i = 0, len = raw_text_pkts.length; i < len; ++i) {
            blocks[i] = (formatter.transform(this.process_ansi(raw_text_pkts[i]), this));
        }
        if (first_chunk.text.length > 0)
            blocks.unshift(formatter.transform(first_chunk, this));
        return formatter.compose(blocks, this);
    };
    AnsiUp.prototype.ansi_to_html = function (txt) {
        return this.ansi_to(txt, this.htmlFormatter);
    };
    AnsiUp.prototype.ansi_to_text = function (txt) {
        return this.ansi_to(txt, this.textFormatter);
    };
    AnsiUp.prototype.with_state = function (text) {
        return { bold: this.bold, fg: this.fg, bg: this.bg, text: text };
    };
    AnsiUp.prototype.handle_incomplete_sequences = function (chunks) {
        var last_chunk = chunks[chunks.length - 1];
        if ((last_chunk.length > 0) && this.detect_incomplete_ansi(last_chunk)) {
            this._buffer = "\x1B[" + last_chunk;
            chunks.pop();
            chunks.push('');
        }
        else {
            if (last_chunk.slice(-1) === "\x1B") {
                this._buffer = "\x1B";
                console.log("raw", chunks);
                chunks.pop();
                chunks.push(last_chunk.substr(0, last_chunk.length - 1));
                console.log(chunks);
                console.log(last_chunk);
            }
            if (chunks.length === 2 &&
                chunks[1] === "" &&
                chunks[0].slice(-1) === "\x1B") {
                this._buffer = "\x1B";
                last_chunk = chunks.shift();
                chunks.unshift(last_chunk.substr(0, last_chunk.length - 1));
            }
        }
    };
    AnsiUp.prototype.process_ansi = function (block) {
        if (!this._sgr_regex) {
            this._sgr_regex = (_a = ["\n            ^                           # beginning of line\n            ([!<-?]?)             # a private-mode char (!, <, =, >, ?)\n            ([d;]*)                    # any digits or semicolons\n            ([ -/]?               # an intermediate modifier\n            [@-~])                # the command\n            ([sS]*)                   # any text following this CSI sequence\n          "], _a.raw = ["\n            ^                           # beginning of line\n            ([!\\x3c-\\x3f]?)             # a private-mode char (!, <, =, >, ?)\n            ([\\d;]*)                    # any digits or semicolons\n            ([\\x20-\\x2f]?               # an intermediate modifier\n            [\\x40-\\x7e])                # the command\n            ([\\s\\S]*)                   # any text following this CSI sequence\n          "], rgx(_a));
        }
        var matches = block.match(this._sgr_regex);
        if (!matches) {
            return this.with_state(block);
        }
        var orig_txt = matches[4];
        if (matches[1] !== '' || matches[3] !== 'm') {
            return this.with_state(orig_txt);
        }
        var sgr_cmds = matches[2].split(';');
        while (sgr_cmds.length > 0) {
            var sgr_cmd_str = sgr_cmds.shift();
            var num = parseInt(sgr_cmd_str, 10);
            if (isNaN(num) || num === 0) {
                this.fg = this.bg = null;
                this.bold = false;
            }
            else if (num === 1) {
                this.bold = true;
            }
            else if (num === 22) {
                this.bold = false;
            }
            else if (num === 39) {
                this.fg = null;
            }
            else if (num === 49) {
                this.bg = null;
            }
            else if ((num >= 30) && (num < 38)) {
                this.fg = this.ansi_colors[0][(num - 30)];
            }
            else if ((num >= 40) && (num < 48)) {
                this.bg = this.ansi_colors[0][(num - 40)];
            }
            else if ((num >= 90) && (num < 98)) {
                this.fg = this.ansi_colors[1][(num - 90)];
            }
            else if ((num >= 100) && (num < 108)) {
                this.bg = this.ansi_colors[1][(num - 100)];
            }
            else if (num === 38 || num === 48) {
                if (sgr_cmds.length > 0) {
                    var is_foreground = (num === 38);
                    var mode_cmd = sgr_cmds.shift();
                    if (mode_cmd === '5' && sgr_cmds.length > 0) {
                        var palette_index = parseInt(sgr_cmds.shift(), 10);
                        if (palette_index >= 0 && palette_index <= 255) {
                            if (is_foreground)
                                this.fg = this.palette_256[palette_index];
                            else
                                this.bg = this.palette_256[palette_index];
                        }
                    }
                    if (mode_cmd === '2' && sgr_cmds.length > 2) {
                        var r = parseInt(sgr_cmds.shift(), 10);
                        var g = parseInt(sgr_cmds.shift(), 10);
                        var b = parseInt(sgr_cmds.shift(), 10);
                        if ((r >= 0 && r <= 255) && (g >= 0 && g <= 255) && (b >= 0 && b <= 255)) {
                            var c = { rgb: [r, g, b], class_name: 'truecolor' };
                            if (is_foreground)
                                this.fg = c;
                            else
                                this.bg = c;
                        }
                    }
                }
            }
        }
        return this.with_state(orig_txt);
        var _a;
    };
    return AnsiUp;
}());
//# sourceMappingURL=ansi_up.js.map
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.default = AnsiUp;
}));


/***/ }),

/***/ "E5mV":
/*!*************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/codemirror/theme/mbo.css ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/****************************************************************/\n/*   Based on mbonaci's Brackets mbo theme                      */\n/*   https://github.com/mbonaci/global/blob/master/Mbo.tmTheme  */\n/*   Create your own: http://tmtheme-editor.herokuapp.com       */\n/****************************************************************/\n\n.cm-s-mbo.CodeMirror { background: #2c2c2c; color: #ffffec; }\n.cm-s-mbo div.CodeMirror-selected { background: #716C62; }\n.cm-s-mbo .CodeMirror-line::selection, .cm-s-mbo .CodeMirror-line > span::selection, .cm-s-mbo .CodeMirror-line > span > span::selection { background: rgba(113, 108, 98, .99); }\n.cm-s-mbo .CodeMirror-line::-moz-selection, .cm-s-mbo .CodeMirror-line > span::-moz-selection, .cm-s-mbo .CodeMirror-line > span > span::-moz-selection { background: rgba(113, 108, 98, .99); }\n.cm-s-mbo .CodeMirror-gutters { background: #4e4e4e; border-right: 0px; }\n.cm-s-mbo .CodeMirror-guttermarker { color: white; }\n.cm-s-mbo .CodeMirror-guttermarker-subtle { color: grey; }\n.cm-s-mbo .CodeMirror-linenumber { color: #dadada; }\n.cm-s-mbo .CodeMirror-cursor { border-left: 1px solid #ffffec; }\n\n.cm-s-mbo span.cm-comment { color: #95958a; }\n.cm-s-mbo span.cm-atom { color: #00a8c6; }\n.cm-s-mbo span.cm-number { color: #00a8c6; }\n\n.cm-s-mbo span.cm-property, .cm-s-mbo span.cm-attribute { color: #9ddfe9; }\n.cm-s-mbo span.cm-keyword { color: #ffb928; }\n.cm-s-mbo span.cm-string { color: #ffcf6c; }\n.cm-s-mbo span.cm-string.cm-property { color: #ffffec; }\n\n.cm-s-mbo span.cm-variable { color: #ffffec; }\n.cm-s-mbo span.cm-variable-2 { color: #00a8c6; }\n.cm-s-mbo span.cm-def { color: #ffffec; }\n.cm-s-mbo span.cm-bracket { color: #fffffc; font-weight: bold; }\n.cm-s-mbo span.cm-tag { color: #9ddfe9; }\n.cm-s-mbo span.cm-link { color: #f54b07; }\n.cm-s-mbo span.cm-error { border-bottom: #636363; color: #ffffec; }\n.cm-s-mbo span.cm-qualifier { color: #ffffec; }\n\n.cm-s-mbo .CodeMirror-activeline-background { background: #494b41; }\n.cm-s-mbo .CodeMirror-matchingbracket { color: #ffb928 !important; }\n.cm-s-mbo .CodeMirror-matchingtag { background: rgba(255, 255, 255, .37); }\n", ""]);

// exports


/***/ }),

/***/ "E6GL":
/*!*************************************************************!*\
  !*** ./node_modules/@jupyterlab/pdf-extension/lib/index.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
__webpack_require__(/*! ../style/index.css */ "FZZk");
/**
 * The MIME type for PDF.
 */
exports.MIME_TYPE = 'application/pdf';
exports.PDF_CLASS = 'jp-PDFViewer';
exports.PDF_CONTAINER_CLASS = 'jp-PDFContainer';
/**
 * A class for rendering a PDF document.
 */
class RenderedPDF extends widgets_1.Widget {
    constructor() {
        super({ node: Private.createNode() });
        this._objectUrl = '';
    }
    /**
     * Render PDF into this widget's node.
     */
    renderModel(model) {
        let data = model.data[exports.MIME_TYPE];
        // If there is no data, do nothing.
        if (!data) {
            return Promise.resolve(void 0);
        }
        const blob = Private.b64toBlob(data, exports.MIME_TYPE);
        let oldUrl = this._objectUrl;
        this._objectUrl = URL.createObjectURL(blob);
        this.node.querySelector('embed').setAttribute('src', this._objectUrl);
        // Release reference to any previous object url.
        if (oldUrl) {
            try {
                URL.revokeObjectURL(oldUrl);
            }
            catch (error) {
                /* no-op */
            }
        }
        return Promise.resolve(void 0);
    }
    /**
     * Dispose of the resources held by the pdf widget.
     */
    dispose() {
        try {
            URL.revokeObjectURL(this._objectUrl);
        }
        catch (error) {
            /* no-op */
        }
        super.dispose();
    }
}
exports.RenderedPDF = RenderedPDF;
/**
 * A mime renderer factory for PDF data.
 */
exports.rendererFactory = {
    safe: false,
    mimeTypes: [exports.MIME_TYPE],
    defaultRank: 75,
    createRenderer: options => new RenderedPDF()
};
const extensions = [
    {
        id: '@jupyterlab/pdf-extension:factory',
        rendererFactory: exports.rendererFactory,
        dataType: 'string',
        fileTypes: [
            {
                name: 'PDF',
                displayName: 'PDF',
                fileFormat: 'base64',
                mimeTypes: [exports.MIME_TYPE],
                extensions: ['.pdf']
            }
        ],
        documentWidgetFactoryOptions: {
            name: 'PDF',
            modelName: 'base64',
            primaryFileType: 'PDF',
            fileTypes: ['PDF'],
            defaultFor: ['PDF']
        }
    }
];
exports.default = extensions;
/**
 * A namespace for PDF widget private data.
 */
var Private;
(function (Private) {
    /**
     * Create the node for the PDF widget.
     */
    function createNode() {
        let node = document.createElement('div');
        node.className = exports.PDF_CONTAINER_CLASS;
        let pdf = document.createElement('embed');
        pdf.className = exports.PDF_CLASS;
        pdf.setAttribute('type', exports.MIME_TYPE);
        node.appendChild(pdf);
        return node;
    }
    Private.createNode = createNode;
    /**
     * Convert a base64 encoded string to a Blob object.
     * Modified from a snippet found here:
     * https://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript
     *
     * @param b64Data - The base64 encoded data.
     *
     * @param contentType - The mime type of the data.
     *
     * @param sliceSize - The size to chunk the data into for processing.
     *
     * @returns a Blob for the data.
     */
    function b64toBlob(b64Data, contentType = '', sliceSize = 512) {
        const byteCharacters = atob(b64Data);
        let byteArrays = [];
        for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
            let slice = byteCharacters.slice(offset, offset + sliceSize);
            let byteNumbers = new Array(slice.length);
            for (let i = 0; i < slice.length; i++) {
                byteNumbers[i] = slice.charCodeAt(i);
            }
            let byteArray = new Uint8Array(byteNumbers);
            byteArrays.push(byteArray);
        }
        return new Blob(byteArrays, { type: contentType });
    }
    Private.b64toBlob = b64toBlob;
})(Private || (Private = {}));


/***/ }),

/***/ "EA7m":
/*!******************************************!*\
  !*** ./node_modules/lodash/_baseRest.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var identity = __webpack_require__(/*! ./identity */ "zZ0H"),
    overRest = __webpack_require__(/*! ./_overRest */ "Ioao"),
    setToString = __webpack_require__(/*! ./_setToString */ "wclG");

/**
 * 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 + '');
}

module.exports = baseRest;


/***/ }),

/***/ "EC7n":
/*!*********************************************************!*\
  !*** ./node_modules/@jupyterlab/csvviewer/lib/model.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const datagrid_1 = __webpack_require__(/*! @phosphor/datagrid */ "Dblc");
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const parse_1 = __webpack_require__(/*! ./parse */ "0gkL");
/*
Possible ideas for further implementation:

- Show a spinner or something visible when we are doing delayed parsing.
- The cache right now handles scrolling down great - it gets the next several hundred rows. However, scrolling up causes lots of cache misses - each new row causes a flush of the cache. When invalidating an entire cache, we should put the requested row in middle of the cache (adjusting for rows at the beginning or end). When populating a cache, we should retrieve rows both above and below the requested row.
- When we have a header, and we are guessing the parser to use, try checking just the part of the file *after* the header row for quotes. I think often a first header row is quoted, but the rest of the file is not and can be parsed much faster.
- autdetect the delimiter (look for comma, tab, semicolon in first line. If more than one found, parse first row with comma, tab, semicolon delimiters. One with most fields wins).
- Toolbar buttons to control the row delimiter, the parsing engine (quoted/not quoted), the quote character, etc.
- Investigate incremental loading strategies in the parseAsync function. In initial investigations, setting the chunk size to 100k in parseAsync seems cause instability with large files in Chrome (such as 8-million row files). Perhaps this is because we are recycling the row offset and column offset arrays quickly? It doesn't seem that there is a memory leak. On this theory, perhaps we just need to keep the offsets list an actual list, and pass it into the parsing function to extend without copying, and finalize it into an array buffer only when we are done parsing. Or perhaps we double the size of the array buffer each time, which may be wasteful, but at the end we trim it down if it's too wasteful (perhaps we have our own object that is backed by an array buffer, but has a push method that will automatically double the array buffer size as needed, and a trim function to finalize the array to exactly the size needed)? Or perhaps we don't use array buffers at all - compare the memory cost and speed of keeping the offsets as lists instead of memory buffers.
- Investigate a time-based incremental parsing strategy, rather than a row-based one. The parser could take a maximum time to parse (say 300ms), and will parse up to that duration, in which case the parser probably also needs a way to notify when it has reached the end of a file.
- For very large files, where we are only storing a small cache, scrolling is very laggy in Safari. It would be good to profile it.
*/
/**
 * Possible delimiter-separated data parsers.
 */
const PARSERS = {
    quotes: parse_1.parseDSV,
    noquotes: parse_1.parseDSVNoQuotes
};
/**
 * A data model implementation for in-memory delimiter-separated data.
 *
 * #### Notes
 * This model handles data with up to 2**32 characters.
 */
class DSVModel extends datagrid_1.DataModel {
    /**
     * Create a data model with static CSV data.
     *
     * @param options - The options for initializing the data model.
     */
    constructor(options) {
        super();
        this._rowCount = 1;
        // Cache information
        /**
         * The header strings.
         */
        this._header = [];
        /**
         * The column offset cache, starting with row _columnOffsetsStartingRow
         *
         * #### Notes
         * The index of the first character in the data string for row r, column c is
         * _columnOffsets[(r-this._columnOffsetsStartingRow)*numColumns+c]
         */
        this._columnOffsets = new Uint32Array(0);
        /**
         * The row that _columnOffsets[0] represents.
         */
        this._columnOffsetsStartingRow = 0;
        /**
         * The maximum number of rows to parse when there is a cache miss.
         */
        this._maxCacheGet = 1000;
        /**
         * The index for the start of each row.
         */
        this._rowOffsets = new Uint32Array(1);
        // Bookkeeping variables.
        this._delayedParse = null;
        this._startedParsing = false;
        this._doneParsing = false;
        this._isDisposed = false;
        this._ready = new coreutils_1.PromiseDelegate();
        let { data, delimiter = ',', rowDelimiter = undefined, quote = '"', quoteParser = undefined, header = true, initialRows = 500 } = options;
        this._data = data;
        this._delimiter = delimiter;
        this._quote = quote;
        this._quoteEscaped = new RegExp(quote + quote, 'g');
        this._initialRows = initialRows;
        // Guess the row delimiter if it was not supplied. This will be fooled if a
        // different line delimiter possibility appears in the first row.
        if (rowDelimiter === undefined) {
            let i = data.slice(0, 5000).indexOf('\r');
            if (i === -1) {
                rowDelimiter = '\n';
            }
            else if (data[i + 1] === '\n') {
                rowDelimiter = '\r\n';
            }
            else {
                rowDelimiter = '\r';
            }
        }
        this._rowDelimiter = rowDelimiter;
        if (quoteParser === undefined) {
            // Check for the existence of quotes if the quoteParser is not set.
            quoteParser = data.indexOf(quote) >= 0;
        }
        this._parser = quoteParser ? 'quotes' : 'noquotes';
        // Parse the data.
        this._parseAsync();
        // Cache the header row.
        if (header === true && this._columnCount > 0) {
            let h = [];
            for (let c = 0; c < this._columnCount; c++) {
                h.push(this._getField(0, c));
            }
            this._header = h;
        }
    }
    /**
     * Whether this model has been disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * A promise that resolves when the model has parsed all of its data.
     */
    get ready() {
        return this._ready.promise;
    }
    /**
     * Get the row count for a region in the data model.
     *
     * @param region - The row region of interest.
     *
     * @returns - The row count for the region.
     */
    rowCount(region) {
        if (region === 'body') {
            if (this._header.length === 0) {
                return this._rowCount;
            }
            else {
                return this._rowCount - 1;
            }
        }
        return 1;
    }
    /**
     * Get the column count for a region in the data model.
     *
     * @param region - The column region of interest.
     *
     * @returns - The column count for the region.
     */
    columnCount(region) {
        if (region === 'body') {
            return this._columnCount;
        }
        return 1;
    }
    /**
     * Get the data value for a cell in the data model.
     *
     * @param region - The cell region of interest.
     *
     * @param row - The row index of the cell of interest.
     *
     * @param column - The column index of the cell of interest.
     *
     * @param returns - The data value for the specified cell.
     */
    data(region, row, column) {
        let value;
        // Look up the field and value for the region.
        switch (region) {
            case 'body':
                if (this._header.length === 0) {
                    value = this._getField(row, column);
                }
                else {
                    value = this._getField(row + 1, column);
                }
                break;
            case 'column-header':
                if (this._header.length === 0) {
                    value = (column + 1).toString();
                }
                else {
                    value = this._header[column];
                }
                break;
            case 'row-header':
                value = (row + 1).toString();
                break;
            case 'corner-header':
                value = '';
                break;
            default:
                throw 'unreachable';
        }
        // Return the final value.
        return value;
    }
    /**
     * Dispose the resources held by this model.
     */
    dispose() {
        if (this._isDisposed) {
            return;
        }
        this._columnCount = undefined;
        this._rowCount = undefined;
        this._rowOffsets = null;
        this._columnOffsets = null;
        this._data = null;
        // Clear out state associated with the asynchronous parsing.
        if (this._doneParsing === false) {
            // Explicitly catch this rejection at least once so an error is not thrown
            // to the console.
            this.ready.catch(() => {
                return;
            });
            this._ready.reject(undefined);
        }
        if (this._delayedParse !== null) {
            window.clearTimeout(this._delayedParse);
        }
    }
    /**
     * Compute the row offsets and initialize the column offset cache.
     *
     * @param endRow - The last row to parse, from the start of the data (first
     * row is row 1).
     *
     * #### Notes
     * This method supports parsing the data incrementally by calling it with
     * incrementally higher endRow. Rows that have already been parsed will not be
     * parsed again.
     */
    _computeRowOffsets(endRow = 4294967295) {
        // If we've already parsed up to endRow, or if we've already parsed the
        // entire data set, return early.
        if (this._rowCount >= endRow || this._doneParsing === true) {
            return;
        }
        // Compute the column count if we don't already have it.
        if (this._columnCount === undefined) {
            // Get number of columns in first row
            this._columnCount = PARSERS[this._parser]({
                data: this._data,
                delimiter: this._delimiter,
                rowDelimiter: this._rowDelimiter,
                quote: this._quote,
                columnOffsets: true,
                maxRows: 1
            }).ncols;
        }
        // Parse the data up to and including the requested row, starting from the
        // last row offset we have.
        let { nrows, offsets } = PARSERS[this._parser]({
            data: this._data,
            startIndex: this._rowOffsets[this._rowCount - 1],
            delimiter: this._delimiter,
            rowDelimiter: this._rowDelimiter,
            quote: this._quote,
            columnOffsets: false,
            maxRows: endRow - this._rowCount + 1
        });
        // Return if we didn't actually get any new rows beyond the one we've
        // already parsed.
        if (this._startedParsing && nrows <= 1) {
            this._doneParsing = true;
            this._ready.resolve(undefined);
            return;
        }
        this._startedParsing = true;
        // Update the row count.
        let oldRowCount = this._rowCount;
        this._rowCount = oldRowCount + nrows - 1;
        // If we didn't reach the requested row, we must be done.
        if (this._rowCount < endRow) {
            this._doneParsing = true;
            this._ready.resolve(undefined);
        }
        // Copy the new offsets into a new row offset array.
        let oldRowOffsets = this._rowOffsets;
        this._rowOffsets = new Uint32Array(this._rowCount);
        this._rowOffsets.set(oldRowOffsets);
        this._rowOffsets.set(offsets, oldRowCount - 1);
        // Expand the column offsets array if needed
        // If the full column offsets array is small enough, build a cache big
        // enough for all column offsets. We allocate up to 128 megabytes:
        // 128*(2**20 bytes/M)/(4 bytes/entry) = 33554432 entries.
        let maxColumnOffsetsRows = Math.floor(33554432 / this._columnCount);
        // We need to expand the column offset array if we were storing all column
        // offsets before. Check to see if the previous size was small enough that
        // we stored all column offsets.
        if (oldRowCount <= maxColumnOffsetsRows) {
            // Check to see if the new column offsets array is small enough to still
            // store, or if we should cut over to a small cache.
            if (this._rowCount <= maxColumnOffsetsRows) {
                // Expand the existing column offset array for new column offsets.
                let oldColumnOffsets = this._columnOffsets;
                this._columnOffsets = new Uint32Array(this._rowCount * this._columnCount);
                this._columnOffsets.set(oldColumnOffsets);
                this._columnOffsets.fill(0xffffffff, oldColumnOffsets.length);
            }
            else {
                // If not, then our cache size is at most the maximum number of rows we
                // fill in the cache at a time.
                let oldColumnOffsets = this._columnOffsets;
                this._columnOffsets = new Uint32Array(Math.min(this._maxCacheGet, maxColumnOffsetsRows) * this._columnCount);
                // Fill in the entries we already have.
                this._columnOffsets.set(oldColumnOffsets.subarray(0, this._columnOffsets.length));
                // Invalidate the rest of the entries.
                this._columnOffsets.fill(0xffffffff, oldColumnOffsets.length);
                this._columnOffsetsStartingRow = 0;
            }
        }
        // We have more rows than before, so emit the rows-inserted change signal.
        let firstIndex = oldRowCount;
        if (this._header.length > 0) {
            firstIndex -= 1;
        }
        this.emitChanged({
            type: 'rows-inserted',
            region: 'body',
            index: firstIndex,
            span: this._rowCount - oldRowCount
        });
    }
    /**
     * Get the parsed string field for a row and column.
     *
     * @param row - The row number of the data item.
     * @param column - The column number of the data item.
     * @returns The parsed string for the data item.
     */
    _getField(row, column) {
        // Declare local variables.
        let value;
        let nextIndex;
        // Find the index for the first character in the field.
        let index = this._getOffsetIndex(row, column);
        // Initialize the trim adjustments.
        let trimRight = 0;
        let trimLeft = 0;
        // Find the end of the slice (the start of the next field), and how much we
        // should adjust to trim off a trailing field or row delimiter. First check
        // if we are getting the last column.
        if (column === this._columnCount - 1) {
            // Check if we are getting any row but the last.
            if (row < this._rowCount - 1) {
                // Set the next offset to the next row, column 0.
                nextIndex = this._getOffsetIndex(row + 1, 0);
                // Since we are not at the last row, we need to trim off the row
                // delimiter.
                trimRight += this._rowDelimiter.length;
            }
            else {
                // We are getting the last data item, so the slice end is the end of the
                // data string.
                nextIndex = this._data.length;
                // The string may or may not end in a row delimiter (RFC 4180 2.2), so
                // we explicitly check if we should trim off a row delimiter.
                if (this._data[nextIndex - 1] ===
                    this._rowDelimiter[this._rowDelimiter.length - 1]) {
                    trimRight += this._rowDelimiter.length;
                }
            }
        }
        else {
            // The next field starts at the next column offset.
            nextIndex = this._getOffsetIndex(row, column + 1);
            // Trim off the delimiter if it exists at the end of the field
            if (index < nextIndex && this._data[nextIndex - 1] === this._delimiter) {
                trimRight += 1;
            }
        }
        // Check to see if the field begins with a quote. If it does, trim a quote on either side.
        if (this._data[index] === this._quote) {
            trimLeft += 1;
            trimRight += 1;
        }
        // Slice the actual value out of the data string.
        value = this._data.slice(index + trimLeft, nextIndex - trimRight);
        // If we have a quoted field and we have an escaped quote inside it, unescape it.
        if (trimLeft === 1 && value.indexOf(this._quote) !== -1) {
            value = value.replace(this._quoteEscaped, this._quote);
        }
        // Return the value.
        return value;
    }
    /**
     * Get the index in the data string for the first character of a row and
     * column.
     *
     * @param row - The row of the data item.
     * @param column - The column of the data item.
     * @returns - The index into the data string where the data item starts.
     */
    _getOffsetIndex(row, column) {
        // Declare local variables.
        const ncols = this._columnCount;
        // Check to see if row *should* be in the cache, based on the cache size.
        let rowIndex = (row - this._columnOffsetsStartingRow) * ncols;
        if (rowIndex < 0 || rowIndex > this._columnOffsets.length) {
            // Row isn't in the cache, so we invalidate the entire cache and set up
            // the cache to hold the requested row.
            this._columnOffsets.fill(0xffffffff);
            this._columnOffsetsStartingRow = row;
            rowIndex = 0;
        }
        // Check to see if we need to fetch the row data into the cache.
        if (this._columnOffsets[rowIndex] === 0xffffffff) {
            // Figure out how many rows below us also need to be fetched.
            let maxRows = 1;
            while (maxRows <= this._maxCacheGet &&
                this._columnOffsets[rowIndex + maxRows * ncols] === 0xffffff) {
                maxRows++;
            }
            // Parse the data to get the column offsets.
            let { offsets } = PARSERS[this._parser]({
                data: this._data,
                delimiter: this._delimiter,
                rowDelimiter: this._rowDelimiter,
                quote: this._quote,
                columnOffsets: true,
                maxRows: maxRows,
                ncols: ncols,
                startIndex: this._rowOffsets[row]
            });
            // Copy results to the cache.
            for (let i = 0; i < offsets.length; i++) {
                this._columnOffsets[rowIndex + i] = offsets[i];
            }
        }
        // Return the offset index from cache.
        return this._columnOffsets[rowIndex + column];
    }
    /**
     * Parse the data string asynchronously.
     *
     * #### Notes
     * It can take several seconds to parse a several hundred megabyte string, so
     * we parse the first 500 rows to get something up on the screen, then we
     * parse the full data string asynchronously.
     */
    _parseAsync() {
        // Number of rows to get initially.
        let currentRows = this._initialRows;
        // Number of rows to get in each chunk thereafter. We set this high to just
        // get the rest of the rows for now.
        let chunkRows = Math.pow(2, 32) - 1;
        // We give the UI a chance to draw by delaying the chunk parsing.
        let delay = 30; // milliseconds
        // Define a function to parse a chunk up to and including endRow.
        let parseChunk = (endRow) => {
            try {
                this._computeRowOffsets(endRow);
            }
            catch (e) {
                // Sometimes the data string cannot be parsed with the full parser (for
                // example, we may have the wrong delimiter). In these cases, fall back to
                // the simpler parser so we can show something.
                if (this._parser === 'quotes') {
                    console.warn(e);
                    this._parser = 'noquotes';
                    this._resetParser();
                    this._computeRowOffsets(endRow);
                }
                else {
                    throw e;
                }
            }
            return this._doneParsing;
        };
        // Reset the parser to its initial state.
        this._resetParser();
        // Parse the first rows to give us the start of the data right away.
        let done = parseChunk(currentRows);
        // If we are done, return early.
        if (done) {
            return;
        }
        // Define a function to recursively parse the next chunk after a delay.
        let delayedParse = () => {
            // Parse up to the new end row.
            let done = parseChunk(currentRows + chunkRows);
            currentRows += chunkRows;
            // Gradually double the chunk size until we reach a million rows, if we
            // start below a million-row chunk size.
            if (chunkRows < 1000000) {
                chunkRows *= 2;
            }
            // If we aren't done, the schedule another parse.
            if (done) {
                this._delayedParse = null;
            }
            else {
                this._delayedParse = window.setTimeout(delayedParse, delay);
            }
        };
        // Parse full data string in chunks, delayed by a few milliseconds to give the UI a chance to draw.
        this._delayedParse = window.setTimeout(delayedParse, delay);
    }
    /**
     * Reset the parser state.
     */
    _resetParser() {
        this._columnCount = undefined;
        // First row offset is *always* 0, so we always have the first row offset.
        this._rowOffsets = new Uint32Array(1);
        this._rowCount = 1;
        this._startedParsing = false;
        this._columnOffsets = new Uint32Array(0);
        // Clear out state associated with the asynchronous parsing.
        if (this._doneParsing === false) {
            // Explicitly catch this rejection at least once so an error is not thrown
            // to the console.
            this.ready.catch(() => {
                return;
            });
            this._ready.reject(undefined);
        }
        this._doneParsing = false;
        this._ready = new coreutils_1.PromiseDelegate();
        if (this._delayedParse !== null) {
            window.clearTimeout(this._delayedParse);
            this._delayedParse = null;
        }
        this.emitChanged({ type: 'model-reset' });
    }
}
exports.DSVModel = DSVModel;


/***/ }),

/***/ "EEGq":
/*!***********************************************!*\
  !*** ./node_modules/lodash/_copySymbolsIn.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var copyObject = __webpack_require__(/*! ./_copyObject */ "juv8"),
    getSymbolsIn = __webpack_require__(/*! ./_getSymbolsIn */ "oCl/");

/**
 * 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);
}

module.exports = copySymbolsIn;


/***/ }),

/***/ "EHQm":
/*!***********************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/get_graph_div.js ***!
  \***********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



/**
 * Allow referencing a graph DOM element either directly
 * or by its id string
 *
 * @param {HTMLDivElement|string} gd: a graph element or its id
 *
 * @returns {HTMLDivElement} the DOM element of the graph
 */
module.exports = function(gd) {
    var gdElement;

    if(typeof gd === 'string') {
        gdElement = document.getElementById(gd);

        if(gdElement === null) {
            throw new Error('No DOM element with id \'' + gd + '\' exists on the page.');
        }

        return gdElement;
    }
    else if(gd === null || gd === undefined) {
        throw new Error('DOM element provided is null or undefined');
    }

    return gd;  // otherwise assume that gd is a DOM element
};


/***/ }),

/***/ "EJhI":
/*!*****************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/codemirror/theme/dracula.css ***!
  \*****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*\n\n    Name:       dracula\n    Author:     Michael Kaminsky (http://github.com/mkaminsky11)\n\n    Original dracula color scheme by Zeno Rocha (https://github.com/zenorocha/dracula-theme)\n\n*/\n\n\n.cm-s-dracula.CodeMirror, .cm-s-dracula .CodeMirror-gutters {\n  background-color: #282a36 !important;\n  color: #f8f8f2 !important;\n  border: none;\n}\n.cm-s-dracula .CodeMirror-gutters { color: #282a36; }\n.cm-s-dracula .CodeMirror-cursor { border-left: solid thin #f8f8f0; }\n.cm-s-dracula .CodeMirror-linenumber { color: #6D8A88; }\n.cm-s-dracula .CodeMirror-selected { background: rgba(255, 255, 255, 0.10); }\n.cm-s-dracula .CodeMirror-line::selection, .cm-s-dracula .CodeMirror-line > span::selection, .cm-s-dracula .CodeMirror-line > span > span::selection { background: rgba(255, 255, 255, 0.10); }\n.cm-s-dracula .CodeMirror-line::-moz-selection, .cm-s-dracula .CodeMirror-line > span::-moz-selection, .cm-s-dracula .CodeMirror-line > span > span::-moz-selection { background: rgba(255, 255, 255, 0.10); }\n.cm-s-dracula span.cm-comment { color: #6272a4; }\n.cm-s-dracula span.cm-string, .cm-s-dracula span.cm-string-2 { color: #f1fa8c; }\n.cm-s-dracula span.cm-number { color: #bd93f9; }\n.cm-s-dracula span.cm-variable { color: #50fa7b; }\n.cm-s-dracula span.cm-variable-2 { color: white; }\n.cm-s-dracula span.cm-def { color: #50fa7b; }\n.cm-s-dracula span.cm-operator { color: #ff79c6; }\n.cm-s-dracula span.cm-keyword { color: #ff79c6; }\n.cm-s-dracula span.cm-atom { color: #bd93f9; }\n.cm-s-dracula span.cm-meta { color: #f8f8f2; }\n.cm-s-dracula span.cm-tag { color: #ff79c6; }\n.cm-s-dracula span.cm-attribute { color: #50fa7b; }\n.cm-s-dracula span.cm-qualifier { color: #50fa7b; }\n.cm-s-dracula span.cm-property { color: #66d9ef; }\n.cm-s-dracula span.cm-builtin { color: #50fa7b; }\n.cm-s-dracula span.cm-variable-3, .cm-s-dracula span.cm-type { color: #ffb86c; }\n\n.cm-s-dracula .CodeMirror-activeline-background { background: rgba(255,255,255,0.1); }\n.cm-s-dracula .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; }\n", ""]);

// exports


/***/ }),

/***/ "EJiy":
/*!******************************************************!*\
  !*** ./node_modules/babel-runtime/helpers/typeof.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _iterator = __webpack_require__(/*! ../core-js/symbol/iterator */ "F+2o");

var _iterator2 = _interopRequireDefault(_iterator);

var _symbol = __webpack_require__(/*! ../core-js/symbol */ "+JPL");

var _symbol2 = _interopRequireDefault(_symbol);

var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; };

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) {
  return typeof obj === "undefined" ? "undefined" : _typeof(obj);
} : function (obj) {
  return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj);
};

/***/ }),

/***/ "ELLl":
/*!*************************************************************!*\
  !*** ./node_modules/codemirror/addon/edit/closebrackets.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"));
  else {}
})(function(CodeMirror) {
  var defaults = {
    pairs: "()[]{}''\"\"",
    triples: "",
    explode: "[]{}"
  };

  var Pos = CodeMirror.Pos;

  CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) {
    if (old && old != CodeMirror.Init) {
      cm.removeKeyMap(keyMap);
      cm.state.closeBrackets = null;
    }
    if (val) {
      ensureBound(getOption(val, "pairs"))
      cm.state.closeBrackets = val;
      cm.addKeyMap(keyMap);
    }
  });

  function getOption(conf, name) {
    if (name == "pairs" && typeof conf == "string") return conf;
    if (typeof conf == "object" && conf[name] != null) return conf[name];
    return defaults[name];
  }

  var keyMap = {Backspace: handleBackspace, Enter: handleEnter};
  function ensureBound(chars) {
    for (var i = 0; i < chars.length; i++) {
      var ch = chars.charAt(i), key = "'" + ch + "'"
      if (!keyMap[key]) keyMap[key] = handler(ch)
    }
  }
  ensureBound(defaults.pairs + "`")

  function handler(ch) {
    return function(cm) { return handleChar(cm, ch); };
  }

  function getConfig(cm) {
    var deflt = cm.state.closeBrackets;
    if (!deflt || deflt.override) return deflt;
    var mode = cm.getModeAt(cm.getCursor());
    return mode.closeBrackets || deflt;
  }

  function handleBackspace(cm) {
    var conf = getConfig(cm);
    if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;

    var pairs = getOption(conf, "pairs");
    var ranges = cm.listSelections();
    for (var i = 0; i < ranges.length; i++) {
      if (!ranges[i].empty()) return CodeMirror.Pass;
      var around = charsAround(cm, ranges[i].head);
      if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass;
    }
    for (var i = ranges.length - 1; i >= 0; i--) {
      var cur = ranges[i].head;
      cm.replaceRange("", Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1), "+delete");
    }
  }

  function handleEnter(cm) {
    var conf = getConfig(cm);
    var explode = conf && getOption(conf, "explode");
    if (!explode || cm.getOption("disableInput")) return CodeMirror.Pass;

    var ranges = cm.listSelections();
    for (var i = 0; i < ranges.length; i++) {
      if (!ranges[i].empty()) return CodeMirror.Pass;
      var around = charsAround(cm, ranges[i].head);
      if (!around || explode.indexOf(around) % 2 != 0) return CodeMirror.Pass;
    }
    cm.operation(function() {
      var linesep = cm.lineSeparator() || "\n";
      cm.replaceSelection(linesep + linesep, null);
      cm.execCommand("goCharLeft");
      ranges = cm.listSelections();
      for (var i = 0; i < ranges.length; i++) {
        var line = ranges[i].head.line;
        cm.indentLine(line, null, true);
        cm.indentLine(line + 1, null, true);
      }
    });
  }

  function contractSelection(sel) {
    var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) > 0;
    return {anchor: new Pos(sel.anchor.line, sel.anchor.ch + (inverted ? -1 : 1)),
            head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1))};
  }

  function handleChar(cm, ch) {
    var conf = getConfig(cm);
    if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;

    var pairs = getOption(conf, "pairs");
    var pos = pairs.indexOf(ch);
    if (pos == -1) return CodeMirror.Pass;
    var triples = getOption(conf, "triples");

    var identical = pairs.charAt(pos + 1) == ch;
    var ranges = cm.listSelections();
    var opening = pos % 2 == 0;

    var type;
    for (var i = 0; i < ranges.length; i++) {
      var range = ranges[i], cur = range.head, curType;
      var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1));
      if (opening && !range.empty()) {
        curType = "surround";
      } else if ((identical || !opening) && next == ch) {
        if (identical && stringStartsAfter(cm, cur))
          curType = "both";
        else if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch)
          curType = "skipThree";
        else
          curType = "skip";
      } else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 &&
                 cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch) {
        if (cur.ch > 2 && /\bstring/.test(cm.getTokenTypeAt(Pos(cur.line, cur.ch - 2)))) return CodeMirror.Pass;
        curType = "addFour";
      } else if (identical) {
        var prev = cur.ch == 0 ? " " : cm.getRange(Pos(cur.line, cur.ch - 1), cur)
        if (!CodeMirror.isWordChar(next) && prev != ch && !CodeMirror.isWordChar(prev)) curType = "both";
        else return CodeMirror.Pass;
      } else if (opening && (cm.getLine(cur.line).length == cur.ch ||
                             isClosingBracket(next, pairs) ||
                             /\s/.test(next))) {
        curType = "both";
      } else {
        return CodeMirror.Pass;
      }
      if (!type) type = curType;
      else if (type != curType) return CodeMirror.Pass;
    }

    var left = pos % 2 ? pairs.charAt(pos - 1) : ch;
    var right = pos % 2 ? ch : pairs.charAt(pos + 1);
    cm.operation(function() {
      if (type == "skip") {
        cm.execCommand("goCharRight");
      } else if (type == "skipThree") {
        for (var i = 0; i < 3; i++)
          cm.execCommand("goCharRight");
      } else if (type == "surround") {
        var sels = cm.getSelections();
        for (var i = 0; i < sels.length; i++)
          sels[i] = left + sels[i] + right;
        cm.replaceSelections(sels, "around");
        sels = cm.listSelections().slice();
        for (var i = 0; i < sels.length; i++)
          sels[i] = contractSelection(sels[i]);
        cm.setSelections(sels);
      } else if (type == "both") {
        cm.replaceSelection(left + right, null);
        cm.triggerElectric(left + right);
        cm.execCommand("goCharLeft");
      } else if (type == "addFour") {
        cm.replaceSelection(left + left + left + left, "before");
        cm.execCommand("goCharRight");
      }
    });
  }

  function isClosingBracket(ch, pairs) {
    var pos = pairs.lastIndexOf(ch);
    return pos > -1 && pos % 2 == 1;
  }

  function charsAround(cm, pos) {
    var str = cm.getRange(Pos(pos.line, pos.ch - 1),
                          Pos(pos.line, pos.ch + 1));
    return str.length == 2 ? str : null;
  }

  function stringStartsAfter(cm, pos) {
    var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1))
    return /\bstring/.test(token.type) && token.start == pos.ch &&
      (pos.ch == 0 || !/\bstring/.test(cm.getTokenTypeAt(pos)))
  }
});


/***/ }),

/***/ "EOgW":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/th.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var th = moment.defineLocale('th', {
    months : 'มกราคม_กุมภาพันธ์_มีนาคม_เมษายน_พฤษภาคม_มิถุนายน_กรกฎาคม_สิงหาคม_กันยายน_ตุลาคม_พฤศจิกายน_ธันวาคม'.split('_'),
    monthsShort : 'ม.ค._ก.พ._มี.ค._เม.ย._พ.ค._มิ.ย._ก.ค._ส.ค._ก.ย._ต.ค._พ.ย._ธ.ค.'.split('_'),
    monthsParseExact: true,
    weekdays : 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัสบดี_ศุกร์_เสาร์'.split('_'),
    weekdaysShort : 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัส_ศุกร์_เสาร์'.split('_'), // yes, three characters difference
    weekdaysMin : 'อา._จ._อ._พ._พฤ._ศ._ส.'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'H:mm',
        LTS : 'H:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY เวลา H:mm',
        LLLL : 'วันddddที่ D MMMM YYYY เวลา H:mm'
    },
    meridiemParse: /ก่อนเที่ยง|หลังเที่ยง/,
    isPM: function (input) {
        return input === 'หลังเที่ยง';
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 12) {
            return 'ก่อนเที่ยง';
        } else {
            return 'หลังเที่ยง';
        }
    },
    calendar : {
        sameDay : '[วันนี้ เวลา] LT',
        nextDay : '[พรุ่งนี้ เวลา] LT',
        nextWeek : 'dddd[หน้า เวลา] LT',
        lastDay : '[เมื่อวานนี้ เวลา] LT',
        lastWeek : '[วัน]dddd[ที่แล้ว เวลา] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'อีก %s',
        past : '%sที่แล้ว',
        s : 'ไม่กี่วินาที',
        ss : '%d วินาที',
        m : '1 นาที',
        mm : '%d นาที',
        h : '1 ชั่วโมง',
        hh : '%d ชั่วโมง',
        d : '1 วัน',
        dd : '%d วัน',
        M : '1 เดือน',
        MM : '%d เดือน',
        y : '1 ปี',
        yy : '%d ปี'
    }
});

return th;

})));


/***/ }),

/***/ "EQzv":
/*!********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotCarpetIcon.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotCarpetIcon = function PlotCarpetIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M9 4.063h22.25c.375.125.625.563.438.938-2.5 7.313-5 14.625-7.563 21.938-.125.5-.563.875-1.063 1H.812c-.438-.063-.688-.563-.5-.938 2.5-7.313 5.063-14.625 7.563-21.938.125-.5.625-.875 1.125-1m.375 1.875a83.164 83.164 0 0 1-1.25 3.625h3.688c.438-1.188.813-2.438 1.25-3.625H9.375m5.5 0a83.164 83.164 0 0 1-1.25 3.625c1.25 0 2.438.063 3.688 0a83.164 83.164 0 0 1 1.25-3.625h-3.688m5.5 0a83.164 83.164 0 0 1-1.25 3.625h3.688a83.164 83.164 0 0 1 1.25-3.625h-3.688m5.5 0a83.164 83.164 0 0 1-1.25 3.625h3.563c.125.063.125-.063.188-.188.375-1.125.813-2.313 1.188-3.438h-3.688M7.5 11.438c-.438 1.188-.813 2.438-1.25 3.625h3.688a83.164 83.164 0 0 1 1.25-3.625H7.5m4.25 3.625h3.625c.438-1.188.875-2.438 1.313-3.625H13c-.438 1.188-.813 2.438-1.25 3.625m6.75-3.625c-.438 1.188-.813 2.438-1.25 3.625h3.625c.438-1.188.875-2.438 1.313-3.625H18.5m5.5 0a82.752 82.752 0 0 0-1.25 3.625h3.625c.438-1.188.875-2.438 1.313-3.625H24M4.375 20.563H8a82.752 82.752 0 0 0 1.25-3.625H5.625a82.752 82.752 0 0 0-1.25 3.625m6.75-3.625a82.752 82.752 0 0 0-1.25 3.625H13.5a82.752 82.752 0 0 0 1.25-3.625h-3.625m5.5 0a82.752 82.752 0 0 0-1.25 3.625H19a82.752 82.752 0 0 0 1.25-3.625h-3.625m5.5 0a82.752 82.752 0 0 0-1.25 3.625H24.5a82.752 82.752 0 0 0 1.25-3.625h-3.625m-18.375 5.5c-.438 1.188-.875 2.438-1.313 3.625h3.688c.438-1.188.813-2.438 1.25-3.625-1.188 0-2.438-.063-3.625 0m5.438 0a83.164 83.164 0 0 1-1.25 3.625h3.688c.438-1.188.813-2.438 1.25-3.625-1.188 0-2.438-.063-3.688 0m5.5 0a83.164 83.164 0 0 1-1.25 3.625h3.688c.438-1.188.813-2.438 1.25-3.625-1.25 0-2.438-.063-3.688 0m5.5.125c-.438 1.188-.813 2.313-1.25 3.5h3.688a82.752 82.752 0 0 0 1.25-3.625h-3.625c-.063-.063-.063.063-.063.125z' })
    );
};

exports.default = PlotCarpetIcon;

/***/ }),

/***/ "ESK+":
/*!************************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/postcss.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _declaration = __webpack_require__(/*! ./declaration */ "dUwI");

var _declaration2 = _interopRequireDefault(_declaration);

var _processor = __webpack_require__(/*! ./processor */ "jTUL");

var _processor2 = _interopRequireDefault(_processor);

var _stringify = __webpack_require__(/*! ./stringify */ "3ZTG");

var _stringify2 = _interopRequireDefault(_stringify);

var _comment = __webpack_require__(/*! ./comment */ "aOxJ");

var _comment2 = _interopRequireDefault(_comment);

var _atRule = __webpack_require__(/*! ./at-rule */ "6z8e");

var _atRule2 = _interopRequireDefault(_atRule);

var _vendor = __webpack_require__(/*! ./vendor */ "euxk");

var _vendor2 = _interopRequireDefault(_vendor);

var _parse = __webpack_require__(/*! ./parse */ "ao+V");

var _parse2 = _interopRequireDefault(_parse);

var _list = __webpack_require__(/*! ./list */ "TIjV");

var _list2 = _interopRequireDefault(_list);

var _rule = __webpack_require__(/*! ./rule */ "Cx5C");

var _rule2 = _interopRequireDefault(_rule);

var _root = __webpack_require__(/*! ./root */ "sYGr");

var _root2 = _interopRequireDefault(_root);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Create a new {@link Processor} instance that will apply `plugins`
 * as CSS processors.
 *
 * @param {Array.<Plugin|pluginFunction>|Processor} plugins - PostCSS
 *        plugins. See {@link Processor#use} for plugin format.
 *
 * @return {Processor} Processor to process multiple CSS
 *
 * @example
 * import postcss from 'postcss';
 *
 * postcss(plugins).process(css, { from, to }).then(result => {
 *   console.log(result.css);
 * });
 *
 * @namespace postcss
 */
function postcss() {
  for (var _len = arguments.length, plugins = Array(_len), _key = 0; _key < _len; _key++) {
    plugins[_key] = arguments[_key];
  }

  if (plugins.length === 1 && Array.isArray(plugins[0])) {
    plugins = plugins[0];
  }
  return new _processor2.default(plugins);
}

/**
 * Creates a PostCSS plugin with a standard API.
 *
 * The newly-wrapped function will provide both the name and PostCSS
 * version of the plugin.
 *
 * ```js
 *  const processor = postcss([replace]);
 *  processor.plugins[0].postcssPlugin  //=> 'postcss-replace'
 *  processor.plugins[0].postcssVersion //=> '5.1.0'
 * ```
 *
 * The plugin function receives 2 arguments: {@link Root}
 * and {@link Result} instance. The function should mutate the provided
 * `Root` node. Alternatively, you can create a new `Root` node
 * and override the `result.root` property.
 *
 * ```js
 * const cleaner = postcss.plugin('postcss-cleaner', () => {
 *   return (root, result) => {
 *     result.root = postcss.root();
 *   };
 * });
 * ```
 *
 * As a convenience, plugins also expose a `process` method so that you can use
 * them as standalone tools.
 *
 * ```js
 * cleaner.process(css, processOpts, pluginOpts);
 * // This is equivalent to:
 * postcss([ cleaner(pluginOpts) ]).process(css, processOpts);
 * ```
 *
 * Asynchronous plugins should return a `Promise` instance.
 *
 * ```js
 * postcss.plugin('postcss-import', () => {
 *   return (root, result) => {
 *     return new Promise( (resolve, reject) => {
 *       fs.readFile('base.css', (base) => {
 *         root.prepend(base);
 *         resolve();
 *       });
 *     });
 *   };
 * });
 * ```
 *
 * Add warnings using the {@link Node#warn} method.
 * Send data to other plugins using the {@link Result#messages} array.
 *
 * ```js
 * postcss.plugin('postcss-caniuse-test', () => {
 *   return (root, result) => {
 *     root.walkDecls(decl => {
 *       if ( !caniuse.support(decl.prop) ) {
 *         decl.warn(result, 'Some browsers do not support ' + decl.prop);
 *       }
 *     });
 *   };
 * });
 * ```
 *
 * @param {string} name          - PostCSS plugin name. Same as in `name`
 *                                 property in `package.json`. It will be saved
 *                                 in `plugin.postcssPlugin` property.
 * @param {function} initializer - will receive plugin options
 *                                 and should return {@link pluginFunction}
 *
 * @return {Plugin} PostCSS plugin
 */
postcss.plugin = function plugin(name, initializer) {
  var creator = function creator() {
    var transformer = initializer.apply(undefined, arguments);
    transformer.postcssPlugin = name;
    transformer.postcssVersion = new _processor2.default().version;
    return transformer;
  };

  var cache = void 0;
  Object.defineProperty(creator, 'postcss', {
    get: function get() {
      if (!cache) cache = creator();
      return cache;
    }
  });

  creator.process = function (css, processOpts, pluginOpts) {
    return postcss([creator(pluginOpts)]).process(css, processOpts);
  };

  return creator;
};

/**
 * Default function to convert a node tree into a CSS string.
 *
 * @param {Node} node       - start node for stringifing. Usually {@link Root}.
 * @param {builder} builder - function to concatenate CSS from node’s parts
 *                            or generate string and source map
 *
 * @return {void}
 *
 * @function
 */
postcss.stringify = _stringify2.default;

/**
 * Parses source css and returns a new {@link Root} node,
 * which contains the source CSS nodes.
 *
 * @param {string|toString} css   - string with input CSS or any object
 *                                  with toString() method, like a Buffer
 * @param {processOptions} [opts] - options with only `from` and `map` keys
 *
 * @return {Root} PostCSS AST
 *
 * @example
 * // Simple CSS concatenation with source map support
 * const root1 = postcss.parse(css1, { from: file1 });
 * const root2 = postcss.parse(css2, { from: file2 });
 * root1.append(root2).toResult().css;
 *
 * @function
 */
postcss.parse = _parse2.default;

/**
 * @member {vendor} - Contains the {@link vendor} module.
 *
 * @example
 * postcss.vendor.unprefixed('-moz-tab') //=> ['tab']
 */
postcss.vendor = _vendor2.default;

/**
 * @member {list} - Contains the {@link list} module.
 *
 * @example
 * postcss.list.space('5px calc(10% + 5px)') //=> ['5px', 'calc(10% + 5px)']
 */
postcss.list = _list2.default;

/**
 * Creates a new {@link Comment} node.
 *
 * @param {object} [defaults] - properties for the new node.
 *
 * @return {Comment} new Comment node
 *
 * @example
 * postcss.comment({ text: 'test' })
 */
postcss.comment = function (defaults) {
  return new _comment2.default(defaults);
};

/**
 * Creates a new {@link AtRule} node.
 *
 * @param {object} [defaults] - properties for the new node.
 *
 * @return {AtRule} new AtRule node
 *
 * @example
 * postcss.atRule({ name: 'charset' }).toString() //=> "@charset"
 */
postcss.atRule = function (defaults) {
  return new _atRule2.default(defaults);
};

/**
 * Creates a new {@link Declaration} node.
 *
 * @param {object} [defaults] - properties for the new node.
 *
 * @return {Declaration} new Declaration node
 *
 * @example
 * postcss.decl({ prop: 'color', value: 'red' }).toString() //=> "color: red"
 */
postcss.decl = function (defaults) {
  return new _declaration2.default(defaults);
};

/**
 * Creates a new {@link Rule} node.
 *
 * @param {object} [defaults] - properties for the new node.
 *
 * @return {Rule} new Rule node
 *
 * @example
 * postcss.rule({ selector: 'a' }).toString() //=> "a {\n}"
 */
postcss.rule = function (defaults) {
  return new _rule2.default(defaults);
};

/**
 * Creates a new {@link Root} node.
 *
 * @param {object} [defaults] - properties for the new node.
 *
 * @return {Root} new Root node
 *
 * @example
 * postcss.root({ after: '\n' }).toString() //=> "\n"
 */
postcss.root = function (defaults) {
  return new _root2.default(defaults);
};

exports.default = postcss;
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64, 


/***/ }),

/***/ "EVUy":
/*!************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/LogoMastercardIcon.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var LogoMastercardIcon = function LogoMastercardIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M29.375 16a8.377 8.377 0 0 0-1.063-4.063c-.75-1.188-1.75-2.125-2.938-2.875-1.313-.688-2.625-1.063-4-1.063-1.813 0-3.438.563-4.875 1.625a8.428 8.428 0 0 1 2.563 4.188h-.75a7.712 7.712 0 0 0-2.313-3.75 7.717 7.717 0 0 0-2.313 3.75h-.75c.438-1.625 1.25-3 2.563-4.188-1.438-1.063-3.063-1.625-4.875-1.625-1.375 0-2.688.375-4 1.063-1.188.75-2.188 1.688-2.938 2.875-.688 1.25-1.063 2.625-1.063 4.063s.375 2.813 1.063 4.063c.75 1.188 1.75 2.125 2.938 2.875 1.313.688 2.625 1.063 4 1.063 1.813 0 3.438-.563 4.875-1.625-1.188-1.063-2-2.313-2.5-3.875h.75a7.872 7.872 0 0 0 2.25 3.438 7.854 7.854 0 0 0 2.25-3.438h.75c-.5 1.563-1.313 2.813-2.5 3.875 1.438 1.063 3.063 1.625 4.875 1.625 1.375 0 2.688-.375 4-1.063 1.188-.75 2.188-1.688 2.938-2.875A8.377 8.377 0 0 0 29.375 16zm-23.25-1.937h1.25l-.625 3.875h-.813l.5-2.938-1.063 2.938h-.625V15l-.5 2.938h-.813l.688-3.875h1.188v2.375zm3.75 1.625c0 .188-.063.375-.063.563-.063.313-.125.625-.188.875 0 .25-.063.438-.125.625v.188h-.625v-.375c-.188.313-.5.438-.875.438-.25 0-.375-.063-.5-.188-.188-.188-.25-.438-.25-.688 0-.375.125-.688.375-.875a2.157 2.157 0 0 1 1.125-.313h.313v-.188c0-.188-.188-.25-.563-.25-.188 0-.5 0-.813.125 0-.188.063-.438.125-.688.313-.125.625-.188.938-.188.75 0 1.125.313 1.125.938zm-.937.812H8.75c-.438 0-.688.188-.688.5 0 .188.063.313.25.313s.313-.063.438-.188.188-.313.188-.625zm3.25-1.687l-.125.75c-.188-.063-.375-.063-.625-.063s-.375.063-.375.25c0 .063 0 .125.063.188l.25.125c.375.25.563.5.563.875 0 .688-.375 1.063-1.25 1.063-.375 0-.688-.063-.813-.063 0-.188.063-.438.125-.75.313.063.563.125.688.125.313 0 .5-.063.5-.25 0-.063-.063-.188-.063-.188-.125-.125-.188-.188-.375-.188-.375-.188-.563-.5-.563-.875 0-.688.375-1.063 1.188-1.063.375 0 .688 0 .813.063zm1.25 0h.375l-.063.813h-.438c0 .188-.063.375-.063.563 0 .063-.063.125-.063.25 0 .188-.063.25-.125.313v.25c0 .188.125.25.313.25.063 0 .125 0 .25-.063l-.125.75c-.125 0-.313.063-.625.063-.438 0-.625-.25-.625-.688 0-.25 0-.563.125-.875l.313-2.063h.813zm2.937 1.062c0 .313 0 .563-.063.813h-1.625c0 .188.063.375.125.438.125.125.313.188.563.188.313 0 .563-.063.875-.25l-.125.813c-.188.063-.5.125-.875.125-.875 0-1.375-.5-1.375-1.375 0-.625.125-1.063.438-1.375.25-.313.563-.5.938-.5s.688.125.875.313c.188.188.25.438.25.813zM14.75 16h.938v-.188l-.063-.125c0-.063-.063-.125-.063-.125-.063 0-.125-.063-.188-.063h-.125c-.25 0-.438.125-.5.5zm3.688-1.187c-.063.063-.125.375-.313.938-.188-.063-.313.063-.5.313-.125.5-.188 1.125-.313 1.875h-.875l.063-.188c.188-1.25.313-2.25.438-2.938h.813l-.125.438c.188-.188.313-.313.438-.375.125-.125.25-.125.375-.063zm2.812-.625l-.188.813c-.25-.125-.5-.188-.688-.188-.375 0-.625.125-.813.375s-.25.563-.25 1.063c0 .313.063.563.188.688.125.188.313.25.563.25.188 0 .438-.063.688-.188l-.125.875a2.322 2.322 0 0 1-.75.125c-.438 0-.75-.188-1.063-.5-.25-.25-.375-.625-.375-1.188 0-.625.188-1.188.563-1.625.313-.438.75-.688 1.313-.688.188 0 .5.063.938.188zm2.375 1.5s-.063.125-.063.25v.313c-.063.25-.125.563-.188.938 0 .375-.063.625-.125.75h-.625v-.375c-.188.313-.5.438-.875.438-.25 0-.375-.063-.5-.188-.188-.188-.25-.438-.25-.688 0-.375.125-.688.375-.875.313-.188.625-.313 1.063-.313h.313c.063-.063.063-.125.063-.188 0-.188-.188-.25-.5-.25-.25 0-.563 0-.875.125 0-.188 0-.438.125-.688.375-.125.625-.188.938-.188.75 0 1.125.313 1.125.938zm-.937.812H22.5c-.438 0-.688.188-.688.5 0 .188.125.313.25.313.188 0 .313-.063.438-.188s.188-.313.188-.625zm2.937-1.687c-.125.188-.25.5-.313.938-.188-.063-.313.063-.438.313s-.188.875-.375 1.875h-.813l.063-.188c.188-1 .313-2 .375-2.938h.813c0 .188-.063.313-.063.438.125-.188.25-.313.375-.375.188-.063.313-.125.375-.063zm2.063-.75h.875l-.688 3.875h-.75l.063-.313a.892.892 0 0 1-.75.375c-.375 0-.563-.125-.688-.375a1.235 1.235 0 0 1-.375-.875c0-.625.188-1.063.5-1.438.188-.313.5-.5.875-.5.313 0 .563.125.813.375zm-.313 2.062c0-.375-.188-.563-.438-.563a.515.515 0 0 0-.5.313c-.063.125-.125.375-.125.75s.125.563.375.563c.188 0 .375-.063.5-.25s.188-.438.188-.813z' })
    );
};

exports.default = LogoMastercardIcon;

/***/ }),

/***/ "EVdn":
/*!********************************************!*\
  !*** ./node_modules/jquery/dist/jquery.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * jQuery JavaScript Library v3.3.1
 * https://jquery.com/
 *
 * Includes Sizzle.js
 * https://sizzlejs.com/
 *
 * Copyright JS Foundation and other contributors
 * Released under the MIT license
 * https://jquery.org/license
 *
 * Date: 2018-01-20T17:24Z
 */
( function( global, factory ) {

	"use strict";

	if ( typeof module === "object" && 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 document = window.document;

var getProto = Object.getPrototypeOf;

var slice = arr.slice;

var concat = arr.concat;

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.
      return typeof obj === "function" && typeof obj.nodeType !== "number";
  };


var isWindow = function isWindow( obj ) {
		return obj != null && obj === obj.window;
	};




	var preservedScriptAttributes = {
		type: true,
		src: true,
		noModule: true
	};

	function DOMEval( code, doc, node ) {
		doc = doc || document;

		var i,
			script = doc.createElement( "script" );

		script.text = code;
		if ( node ) {
			for ( i in preservedScriptAttributes ) {
				if ( node[ i ] ) {
					script[ i ] = node[ i ];
				}
			}
		}
		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.3.1",

	// 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 );
	},

	// Support: Android <=4.0 only
	// Make sure we trim BOM and NBSP
	rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;

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 );
	},

	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 ) {
				src = target[ name ];
				copy = options[ name ];

				// Prevent never-ending loop
				if ( target === copy ) {
					continue;
				}

				// Recurse if we're merging plain objects or arrays
				if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
					( copyIsArray = Array.isArray( copy ) ) ) ) {

					if ( copyIsArray ) {
						copyIsArray = false;
						clone = src && Array.isArray( src ) ? src : [];

					} else {
						clone = src && jQuery.isPlainObject( src ) ? src : {};
					}

					// 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 ) {

		/* eslint-disable no-unused-vars */
		// See https://github.com/eslint/eslint/issues/6125
		var name;

		for ( name in obj ) {
			return false;
		}
		return true;
	},

	// Evaluates a script in a global context
	globalEval: function( code ) {
		DOMEval( code );
	},

	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;
	},

	// Support: Android <=4.0 only
	trim: function( text ) {
		return text == null ?
			"" :
			( text + "" ).replace( rtrim, "" );
	},

	// 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 concat.apply( [], 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.3
 * https://sizzlejs.com/
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license
 * http://jquery.org/license
 *
 * Date: 2016-08-08
 */
(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(),
	sortOrder = function( a, b ) {
		if ( a === b ) {
			hasDuplicate = true;
		}
		return 0;
	},

	// Instance methods
	hasOwn = ({}).hasOwnProperty,
	arr = [],
	pop = arr.pop,
	push_native = 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]",

	// http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
	identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+",

	// 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 + "*" ),

	rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),

	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" )
	},

	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-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
	funescape = function( _, escaped, escapedWhitespace ) {
		var high = "0x" + escaped - 0x10000;
		// NaN means non-codepoint
		// Support: Firefox<24
		// Workaround erroneous numeric interpretation of +"0x"
		return high !== high || escapedWhitespace ?
			escaped :
			high < 0 ?
				// BMP codepoint
				String.fromCharCode( high + 0x10000 ) :
				// Supplemental Plane codepoint (surrogate pair)
				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();
	},

	disabledAncestor = addCombinator(
		function( elem ) {
			return elem.disabled === true && ("form" in elem || "label" in elem);
		},
		{ 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
	arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
	push = { apply: arr.length ?

		// Leverage slice if possible
		function( target, els ) {
			push_native.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 ) {

		if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
			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 &&
				!compilerCache[ selector + " " ] &&
				(!rbuggyQSA || !rbuggyQSA.test( selector )) ) {

				if ( nodeType !== 1 ) {
					newContext = context;
					newSelector = selector;

				// qSA looks outside Element context, which is not what we want
				// Thanks to Andrew Dupont for this workaround technique
				// Support: IE <=8
				// Exclude object elements
				} else if ( context.nodeName.toLowerCase() !== "object" ) {

					// 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 + " " + toSelector( groups[i] );
					}
					newSelector = groups.join( "," );

					// Expand context for sibling selectors
					newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
						context;
				}

				if ( newSelector ) {
					try {
						push.apply( results,
							newContext.querySelectorAll( newSelector )
						);
						return results;
					} catch ( qsaError ) {
					} 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 &&
						disabledAncestor( 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 ) {
	// documentElement is verified for cases where it doesn't yet exist
	// (such as loading iframes in IE - #4833)
	var documentElement = elem && (elem.ownerDocument || elem).documentElement;
	return documentElement ? documentElement.nodeName !== "HTML" : false;
};

/**
 * 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
	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
	// Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
	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 );
		}
	}

	/* 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 ) {
			// 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("~=");
			}

			// 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(".#.+[+~]");
			}
		});

		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" );
			}

			// 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
		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
			if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
				return -1;
			}
			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 ) {
			return a === document ? -1 :
				b === document ? 1 :
				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
			ap[i] === preferredDoc ? -1 :
			bp[i] === preferredDoc ? 1 :
			0;
	};

	return document;
};

Sizzle.matches = function( expr, elements ) {
	return Sizzle( expr, null, null, elements );
};

Sizzle.matchesSelector = function( elem, expr ) {
	// Set document vars if needed
	if ( ( elem.ownerDocument || elem ) !== document ) {
		setDocument( elem );
	}

	// Make sure that attribute selectors are quoted
	expr = expr.replace( rattributeQuotes, "='$1']" );

	if ( support.matchesSelector && documentIsHTML &&
		!compilerCache[ 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) {}
	}

	return Sizzle( expr, document, null, [ elem ] ).length > 0;
};

Sizzle.contains = function( context, elem ) {
	// Set document vars if needed
	if ( ( context.ownerDocument || context ) !== document ) {
		setDocument( context );
	}
	return contains( context, elem );
};

Sizzle.attr = function( elem, name ) {
	// Set document vars if needed
	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 += "";

				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;
			};
		},

		"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 || elem.innerText || 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 ) {
				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;
			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 ) {
				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;
					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 ( nodeName( elem, "iframe" ) ) {
            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 master Deferred
			master = 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 ) ) {
						master.resolveWith( resolveContexts, resolveValues );
					}
				};
			};

		// Single- and empty arguments are adopted like Promise.resolve
		if ( remaining <= 1 ) {
			adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject,
				!remaining );

			// Use .then() to unwrap secondary thenables (cf. gh-3000)
			if ( master.state() === "pending" ||
				isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) {

				return master.then();
			}
		}

		// Multiple arguments are aggregated like Promise.all array elements
		while ( i-- ) {
			adoptValue( resolveValues[ i ], updateFunc( i ), master.reject );
		}

		return master.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 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.
			jQuery.contains( elem.ownerDocument, elem ) &&

			jQuery.css( elem, "display" ) === "none";
	};

var swap = function( elem, options, callback, args ) {
	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.apply( elem, args || [] );

	// Revert the old values
	for ( name in options ) {
		elem.style[ name ] = old[ name ];
	}

	return ret;
};




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 = ( 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 );



// We have to close these tags to support XHTML (#13200)
var wrapMap = {

	// Support: IE <=9 only
	option: [ 1, "<select multiple='multiple'>", "</select>" ],

	// 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, "", "" ]
};

// Support: IE <=9 only
wrapMap.optgroup = wrapMap.option;

wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;


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, contains, 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;
		}

		contains = jQuery.contains( elem.ownerDocument, elem );

		// Append to fragment
		tmp = getAll( fragment.appendChild( elem ), "script" );

		// Preserve script evaluation history
		if ( contains ) {
			setGlobalEval( tmp );
		}

		// Capture executables
		if ( scripts ) {
			j = 0;
			while ( ( elem = tmp[ j++ ] ) ) {
				if ( rscriptType.test( elem.type || "" ) ) {
					scripts.push( elem );
				}
			}
		}
	}

	return fragment;
}


( 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;
} )();
var documentElement = document.documentElement;



var
	rkeyEvent = /^key/,
	rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,
	rtypenamespace = /^([^.]*)(?:\.(.+)|)/;

function returnTrue() {
	return true;
}

function returnFalse() {
	return false;
}

// Support: IE <=9 only
// See #13393 for more info
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 );

		// Don't attach events to noData or text/comment nodes (but allow plain objects)
		if ( !elemData ) {
			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 = {};
		}
		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 ) {

		// Make a writable jQuery.Event from the native event object
		var event = jQuery.event.fix( nativeEvent );

		var i, j, ret, matched, handleObj, handlerQueue,
			args = new Array( arguments.length ),
			handlers = ( dataPriv.get( this, "events" ) || {} )[ 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() ) {

				// Triggered event must either 1) have no namespace, or 2) have namespace(s)
				// a subset or equal to those in the bound event (both can have no namespace).
				if ( !event.rnamespace || 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
		},
		focus: {

			// Fire native event if possible so blur/focus sequence is correct
			trigger: function() {
				if ( this !== safeActiveElement() && this.focus ) {
					this.focus();
					return false;
				}
			},
			delegateType: "focusin"
		},
		blur: {
			trigger: function() {
				if ( this === safeActiveElement() && this.blur ) {
					this.blur();
					return false;
				}
			},
			delegateType: "focusout"
		},
		click: {

			// For checkbox, fire native event so checked state will be right
			trigger: function() {
				if ( this.type === "checkbox" && this.click && nodeName( this, "input" ) ) {
					this.click();
					return false;
				}
			},

			// For cross-browser consistency, don't fire native .click() on links
			_default: function( event ) {
				return nodeName( event.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;
				}
			}
		}
	}
};

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,
	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: function( event ) {
		var button = event.button;

		// Add which for key events
		if ( event.which == null && rkeyEvent.test( event.type ) ) {
			return event.charCode != null ? event.charCode : event.keyCode;
		}

		// Add which for click: 1 === left; 2 === middle; 3 === right
		if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) {
			if ( button & 1 ) {
				return 1;
			}

			if ( button & 2 ) {
				return 3;
			}

			if ( button & 4 ) {
				return 2;
			}

			return 0;
		}

		return event.which;
	}
}, jQuery.event.addProp );

// 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

	/* eslint-disable max-len */

	// See https://github.com/eslint/eslint/issues/3229
	rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,

	/* eslint-enable */

	// 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, pdataCur, udataOld, udataCur, events;

	if ( dest.nodeType !== 1 ) {
		return;
	}

	// 1. Copy private data: events, handlers, etc.
	if ( dataPriv.hasData( src ) ) {
		pdataOld = dataPriv.access( src );
		pdataCur = dataPriv.set( dest, pdataOld );
		events = pdataOld.events;

		if ( events ) {
			delete pdataCur.handle;
			pdataCur.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 = concat.apply( [], 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 ) {
								jQuery._evalUrl( node.src );
							}
						} else {
							DOMEval( node.textContent.replace( rcleanScript, "" ), doc, node );
						}
					}
				}
			}
		}
	}

	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 && jQuery.contains( node.ownerDocument, node ) ) {
				setGlobalEval( getAll( node, "script" ) );
			}
			node.parentNode.removeChild( node );
		}
	}

	return elem;
}

jQuery.extend( {
	htmlPrefilter: function( html ) {
		return html.replace( rxhtmlTag, "<$1></$2>" );
	},

	clone: function( elem, dataAndEvents, deepDataAndEvents ) {
		var i, l, srcElements, destElements,
			clone = elem.cloneNode( true ),
			inPage = jQuery.contains( elem.ownerDocument, 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 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)
		div.style.position = "absolute";
		scrollboxSizeVal = div.offsetWidth === 36 || "absolute";

		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,
		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;
		}
	} );
} )();


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 === "" && !jQuery.contains( elem.ownerDocument, 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

	// 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"
	},

	cssPrefixes = [ "Webkit", "Moz", "ms" ],
	emptyStyle = document.createElement( "div" ).style;

// Return a css property mapped to a potentially vendor prefixed property
function vendorPropName( name ) {

	// Shortcut for names that are not vendor prefixed
	if ( name in emptyStyle ) {
		return 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 property mapped along what jQuery.cssProps suggests or to
// a vendor prefixed property.
function finalPropName( name ) {
	var ret = jQuery.cssProps[ name ];
	if ( !ret ) {
		ret = jQuery.cssProps[ name ] = vendorPropName( name ) || name;
	}
	return ret;
}

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
		) );
	}

	return delta;
}

function getWidthOrHeight( elem, dimension, extra ) {

	// Start with computed style
	var styles = getStyles( elem ),
		val = curCSS( elem, dimension, styles ),
		isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
		valueIsBorderBox = isBorderBox;

	// Support: Firefox <=54
	// Return a confounding non-pixel value or feign ignorance, as appropriate.
	if ( rnumnonpx.test( val ) ) {
		if ( !extra ) {
			return val;
		}
		val = "auto";
	}

	// Check for style in case a browser which returns unreliable values
	// for getComputedStyle silently falls back to the reliable elem.style
	valueIsBorderBox = valueIsBorderBox &&
		( support.boxSizingReliable() || val === elem.style[ dimension ] );

	// Fall back to offsetWidth/offsetHeight when value is "auto"
	// This happens for inline elements with no explicit setting (gh-3571)
	// Support: Android <=4.1 - 4.3 only
	// Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602)
	if ( val === "auto" ||
		!parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) {

		val = elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ];

		// offsetWidth/offsetHeight provide border-box values
		valueIsBorderBox = true;
	}

	// 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,
		"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)
			if ( type === "number" ) {
				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 ),
				isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
				subtract = extra && boxModelAdjustment(
					elem,
					dimension,
					extra,
					isBorderBox,
					styles
				);

			// 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 && support.scrollboxSize() === styles.position ) {
				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 &&
				( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null ||
					jQuery.cssHooks[ tween.prop ] ) ) {
				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 && type !== false ) {
			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" ) || {} )[ 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() {
				var doc = this.ownerDocument || 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,
					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 = Date.now();

var rquery = ( /\?/ );



// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
	var xml;
	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 ) {
		xml = undefined;
	}

	if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
		jQuery.error( "Invalid XML: " + 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 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() ] = match[ 2 ];
							}
						}
						match = responseHeaders[ key.toLowerCase() ];
					}
					return match == null ? null : match;
				},

				// 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++ ) + 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 );
			}

			// 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._evalUrl = function( url ) {
	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,
		"throws": true
	} );
};


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 requests
	if ( s.crossDomain ) {
		var script, callback;
		return {
			send: function( _, complete ) {
				script = jQuery( "<script>" ).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++ ) );
		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;
};




// Attach a bunch of functions for handling common AJAX events
jQuery.each( [
	"ajaxStart",
	"ajaxStop",
	"ajaxComplete",
	"ajaxError",
	"ajaxSuccess",
	"ajaxSend"
], function( i, type ) {
	jQuery.fn[ type ] = function( fn ) {
		return this.on( type, fn );
	};
} );




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( ( "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 );
	};
} );

jQuery.fn.extend( {
	hover: function( fnOver, fnOut ) {
		return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
	}
} );




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 );
	}
} );

// 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 ) );
};




// 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 ( !noGlobal ) {
	window.jQuery = window.$ = jQuery;
}




return jQuery;
} );


/***/ }),

/***/ "EW/T":
/*!**************************************************************!*\
  !*** ./node_modules/@jupyterlab/docregistry/lib/registry.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const disposable_1 = __webpack_require__(/*! @phosphor/disposable */ "uNUc");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const default_1 = __webpack_require__(/*! ./default */ "Or5M");
/**
 * The document registry.
 */
class DocumentRegistry {
    /**
     * Construct a new document registry.
     */
    constructor(options = {}) {
        this._modelFactories = Object.create(null);
        this._widgetFactories = Object.create(null);
        this._defaultWidgetFactory = '';
        this._defaultWidgetFactories = Object.create(null);
        this._defaultRenderedWidgetFactories = Object.create(null);
        this._widgetFactoryExtensions = Object.create(null);
        this._fileTypes = [];
        this._extenders = Object.create(null);
        this._changed = new signaling_1.Signal(this);
        this._isDisposed = false;
        let factory = options.textModelFactory;
        if (factory && factory.name !== 'text') {
            throw new Error('Text model factory must have the name `text`');
        }
        this._modelFactories['text'] = factory || new default_1.TextModelFactory();
        let fts = options.initialFileTypes || DocumentRegistry.defaultFileTypes;
        fts.forEach(ft => {
            let value = Object.assign({}, DocumentRegistry.fileTypeDefaults, ft);
            this._fileTypes.push(value);
        });
    }
    /**
     * A signal emitted when the registry has changed.
     */
    get changed() {
        return this._changed;
    }
    /**
     * Get whether the document registry has been disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources held by the document registery.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        for (let modelName in this._modelFactories) {
            this._modelFactories[modelName].dispose();
        }
        for (let widgetName in this._widgetFactories) {
            this._widgetFactories[widgetName].dispose();
        }
        for (let widgetName in this._extenders) {
            this._extenders[widgetName].length = 0;
        }
        this._fileTypes.length = 0;
        signaling_1.Signal.clearData(this);
    }
    /**
     * Add a widget factory to the registry.
     *
     * @param factory - The factory instance to register.
     *
     * @returns A disposable which will unregister the factory.
     *
     * #### Notes
     * If a factory with the given `'displayName'` is already registered,
     * a warning will be logged, and this will be a no-op.
     * If `'*'` is given as a default extension, the factory will be registered
     * as the global default.
     * If an extension or global default is already registered, this factory
     * will override the existing default.
     */
    addWidgetFactory(factory) {
        let name = factory.name.toLowerCase();
        if (this._widgetFactories[name]) {
            console.warn(`Duplicate registered factory ${name}`);
            return new disposable_1.DisposableDelegate(Private.noOp);
        }
        this._widgetFactories[name] = factory;
        for (let ft of factory.defaultFor || []) {
            if (factory.fileTypes.indexOf(ft) === -1) {
                continue;
            }
            if (ft === '*') {
                this._defaultWidgetFactory = name;
            }
            else {
                this._defaultWidgetFactories[ft] = name;
            }
        }
        for (let ft of factory.defaultRendered || []) {
            if (factory.fileTypes.indexOf(ft) === -1) {
                continue;
            }
            this._defaultRenderedWidgetFactories[ft] = name;
        }
        // For convenience, store a mapping of file type name -> name
        for (let ft of factory.fileTypes) {
            if (!this._widgetFactoryExtensions[ft]) {
                this._widgetFactoryExtensions[ft] = [];
            }
            this._widgetFactoryExtensions[ft].push(name);
        }
        this._changed.emit({
            type: 'widgetFactory',
            name,
            change: 'added'
        });
        return new disposable_1.DisposableDelegate(() => {
            delete this._widgetFactories[name];
            if (this._defaultWidgetFactory === name) {
                this._defaultWidgetFactory = '';
            }
            for (let ext of Object.keys(this._defaultWidgetFactories)) {
                if (this._defaultWidgetFactories[ext] === name) {
                    delete this._defaultWidgetFactories[ext];
                }
            }
            for (let ext of Object.keys(this._defaultRenderedWidgetFactories)) {
                if (this._defaultRenderedWidgetFactories[ext] === name) {
                    delete this._defaultRenderedWidgetFactories[ext];
                }
            }
            for (let ext of Object.keys(this._widgetFactoryExtensions)) {
                algorithm_1.ArrayExt.removeFirstOf(this._widgetFactoryExtensions[ext], name);
                if (this._widgetFactoryExtensions[ext].length === 0) {
                    delete this._widgetFactoryExtensions[ext];
                }
            }
            this._changed.emit({
                type: 'widgetFactory',
                name,
                change: 'removed'
            });
        });
    }
    /**
     * Add a model factory to the registry.
     *
     * @param factory - The factory instance.
     *
     * @returns A disposable which will unregister the factory.
     *
     * #### Notes
     * If a factory with the given `name` is already registered, or
     * the given factory is already registered, a warning will be logged
     * and this will be a no-op.
     */
    addModelFactory(factory) {
        let name = factory.name.toLowerCase();
        if (this._modelFactories[name]) {
            console.warn(`Duplicate registered factory ${name}`);
            return new disposable_1.DisposableDelegate(Private.noOp);
        }
        this._modelFactories[name] = factory;
        this._changed.emit({
            type: 'modelFactory',
            name,
            change: 'added'
        });
        return new disposable_1.DisposableDelegate(() => {
            delete this._modelFactories[name];
            this._changed.emit({
                type: 'modelFactory',
                name,
                change: 'removed'
            });
        });
    }
    /**
     * Add a widget extension to the registry.
     *
     * @param widgetName - The name of the widget factory.
     *
     * @param extension - A widget extension.
     *
     * @returns A disposable which will unregister the extension.
     *
     * #### Notes
     * If the extension is already registered for the given
     * widget name, a warning will be logged and this will be a no-op.
     */
    addWidgetExtension(widgetName, extension) {
        widgetName = widgetName.toLowerCase();
        if (!(widgetName in this._extenders)) {
            this._extenders[widgetName] = [];
        }
        let extenders = this._extenders[widgetName];
        let index = algorithm_1.ArrayExt.firstIndexOf(extenders, extension);
        if (index !== -1) {
            console.warn(`Duplicate registered extension for ${widgetName}`);
            return new disposable_1.DisposableDelegate(Private.noOp);
        }
        this._extenders[widgetName].push(extension);
        this._changed.emit({
            type: 'widgetExtension',
            name: widgetName,
            change: 'added'
        });
        return new disposable_1.DisposableDelegate(() => {
            algorithm_1.ArrayExt.removeFirstOf(this._extenders[widgetName], extension);
            this._changed.emit({
                type: 'widgetExtension',
                name: widgetName,
                change: 'removed'
            });
        });
    }
    /**
     * Add a file type to the document registry.
     *
     * @params fileType - The file type object to register.
     *
     * @returns A disposable which will unregister the command.
     *
     * #### Notes
     * These are used to populate the "Create New" dialog.
     */
    addFileType(fileType) {
        let value = Object.assign({}, DocumentRegistry.fileTypeDefaults, fileType);
        this._fileTypes.push(value);
        this._changed.emit({
            type: 'fileType',
            name: value.name,
            change: 'added'
        });
        return new disposable_1.DisposableDelegate(() => {
            algorithm_1.ArrayExt.removeFirstOf(this._fileTypes, value);
            this._changed.emit({
                type: 'fileType',
                name: fileType.name,
                change: 'removed'
            });
        });
    }
    /**
     * Get a list of the preferred widget factories.
     *
     * @param path - The file path to filter the results.
     *
     * @returns A new array of widget factories.
     *
     * #### Notes
     * Only the widget factories whose associated model factory have
     * been registered will be returned.
     * The first item is considered the default. The returned array
     * has widget factories in the following order:
     * - path-specific default factory
     * - path-specific default rendered factory
     * - global default factory
     * - all other path-specific factories
     * - all other global factories
     */
    preferredWidgetFactories(path) {
        let factories = new Set();
        // Get the ordered matching file types.
        let fts = this.getFileTypesForPath(coreutils_1.PathExt.basename(path));
        // Start with the file type default factories.
        fts.forEach(ft => {
            if (ft.name in this._defaultWidgetFactories) {
                factories.add(this._defaultWidgetFactories[ft.name]);
            }
        });
        // Add the file type default rendered factories.
        fts.forEach(ft => {
            if (ft.name in this._defaultRenderedWidgetFactories) {
                factories.add(this._defaultRenderedWidgetFactories[ft.name]);
            }
        });
        // Add the global default factory.
        if (this._defaultWidgetFactory) {
            factories.add(this._defaultWidgetFactory);
        }
        // Add the file type factories in registration order.
        fts.forEach(ft => {
            if (ft.name in this._widgetFactoryExtensions) {
                algorithm_1.each(this._widgetFactoryExtensions[ft.name], n => {
                    factories.add(n);
                });
            }
        });
        // Add the rest of the global factories, in registration order.
        if ('*' in this._widgetFactoryExtensions) {
            algorithm_1.each(this._widgetFactoryExtensions['*'], n => {
                factories.add(n);
            });
        }
        // Construct the return list, checking to make sure the corresponding
        // model factories are registered.
        let factoryList = [];
        factories.forEach(name => {
            let factory = this._widgetFactories[name];
            if (!factory) {
                return;
            }
            let modelName = factory.modelName || 'text';
            if (modelName in this._modelFactories) {
                factoryList.push(factory);
            }
        });
        return factoryList;
    }
    /**
     * Get the default rendered widget factory for a path.
     *
     * @param path - The path to for which to find a widget factory.
     *
     * @returns The default rendered widget factory for the path.
     *
     * ### Notes
     * If the widget factory has registered a separate set of `defaultRendered`
     * file types and there is a match in that set, this returns that.
     * Otherwise, this returns the same widget factory as
     * [[defaultWidgetFactory]].
     */
    defaultRenderedWidgetFactory(path) {
        // Get the matching file types.
        let fts = this.getFileTypesForPath(coreutils_1.PathExt.basename(path));
        let factory = undefined;
        // Find if a there is a default rendered factory for this type.
        for (let ft of fts) {
            if (ft.name in this._defaultRenderedWidgetFactories) {
                factory = this._widgetFactories[this._defaultRenderedWidgetFactories[ft.name]];
                break;
            }
        }
        return factory || this.defaultWidgetFactory(path);
    }
    /**
     * Get the default widget factory for a path.
     *
     * @param path - An optional file path to filter the results.
     *
     * @returns The default widget factory for an path.
     *
     * #### Notes
     * This is equivalent to the first value in [[preferredWidgetFactories]].
     */
    defaultWidgetFactory(path) {
        if (!path) {
            return this._widgetFactories[this._defaultWidgetFactory];
        }
        return this.preferredWidgetFactories(path)[0];
    }
    /**
     * Create an iterator over the widget factories that have been registered.
     *
     * @returns A new iterator of widget factories.
     */
    widgetFactories() {
        return algorithm_1.map(Object.keys(this._widgetFactories), name => {
            return this._widgetFactories[name];
        });
    }
    /**
     * Create an iterator over the model factories that have been registered.
     *
     * @returns A new iterator of model factories.
     */
    modelFactories() {
        return algorithm_1.map(Object.keys(this._modelFactories), name => {
            return this._modelFactories[name];
        });
    }
    /**
     * Create an iterator over the registered extensions for a given widget.
     *
     * @param widgetName - The name of the widget factory.
     *
     * @returns A new iterator over the widget extensions.
     */
    widgetExtensions(widgetName) {
        widgetName = widgetName.toLowerCase();
        if (!(widgetName in this._extenders)) {
            return algorithm_1.empty();
        }
        return new algorithm_1.ArrayIterator(this._extenders[widgetName]);
    }
    /**
     * Create an iterator over the file types that have been registered.
     *
     * @returns A new iterator of file types.
     */
    fileTypes() {
        return new algorithm_1.ArrayIterator(this._fileTypes);
    }
    /**
     * Get a widget factory by name.
     *
     * @param widgetName - The name of the widget factory.
     *
     * @returns A widget factory instance.
     */
    getWidgetFactory(widgetName) {
        return this._widgetFactories[widgetName.toLowerCase()];
    }
    /**
     * Get a model factory by name.
     *
     * @param name - The name of the model factory.
     *
     * @returns A model factory instance.
     */
    getModelFactory(name) {
        return this._modelFactories[name.toLowerCase()];
    }
    /**
     * Get a file type by name.
     */
    getFileType(name) {
        name = name.toLowerCase();
        return algorithm_1.find(this._fileTypes, fileType => {
            return fileType.name.toLowerCase() === name;
        });
    }
    /**
     * Get a kernel preference.
     *
     * @param path - The file path.
     *
     * @param widgetName - The name of the widget factory.
     *
     * @param kernel - An optional existing kernel model.
     *
     * @returns A kernel preference.
     */
    getKernelPreference(path, widgetName, kernel) {
        widgetName = widgetName.toLowerCase();
        let widgetFactory = this._widgetFactories[widgetName];
        if (!widgetFactory) {
            return void 0;
        }
        let modelFactory = this.getModelFactory(widgetFactory.modelName || 'text');
        if (!modelFactory) {
            return void 0;
        }
        let language = modelFactory.preferredLanguage(coreutils_1.PathExt.basename(path));
        let name = kernel && kernel.name;
        let id = kernel && kernel.id;
        return {
            id,
            name,
            language,
            shouldStart: widgetFactory.preferKernel,
            canStart: widgetFactory.canStartKernel
        };
    }
    /**
     * Get the best file type given a contents model.
     *
     * @param model - The contents model of interest.
     *
     * @returns The best matching file type.
     */
    getFileTypeForModel(model) {
        switch (model.type) {
            case 'directory':
                return (algorithm_1.find(this._fileTypes, ft => ft.contentType === 'directory') ||
                    DocumentRegistry.defaultDirectoryFileType);
            case 'notebook':
                return (algorithm_1.find(this._fileTypes, ft => ft.contentType === 'notebook') ||
                    DocumentRegistry.defaultNotebookFileType);
            default:
                // Find the best matching extension.
                if (model.name || model.path) {
                    let name = model.name || coreutils_1.PathExt.basename(model.path);
                    let fts = this.getFileTypesForPath(name);
                    if (fts.length > 0) {
                        return fts[0];
                    }
                }
                return this.getFileType('text') || DocumentRegistry.defaultTextFileType;
        }
    }
    /**
     * Get the file types that match a file name.
     *
     * @param path - The path of the file.
     *
     * @returns An ordered list of matching file types.
     */
    getFileTypesForPath(path) {
        let fts = [];
        let name = coreutils_1.PathExt.basename(path);
        // Look for a pattern match first.
        let ft = algorithm_1.find(this._fileTypes, ft => {
            return ft.pattern && ft.pattern.match(name) !== null;
        });
        if (ft) {
            fts.push(ft);
        }
        // Then look by extension name, starting with the longest
        let ext = Private.extname(name);
        while (ext.length > 1) {
            ft = algorithm_1.find(this._fileTypes, ft => ft.extensions.indexOf(ext) !== -1);
            if (ft) {
                fts.push(ft);
            }
            ext =
                '.' +
                    ext
                        .split('.')
                        .slice(2)
                        .join('.');
        }
        return fts;
    }
}
exports.DocumentRegistry = DocumentRegistry;
/**
 * The namespace for the `DocumentRegistry` class statics.
 */
(function (DocumentRegistry) {
    /**
     * The defaults used for a file type.
     */
    DocumentRegistry.fileTypeDefaults = {
        name: 'default',
        extensions: [],
        mimeTypes: [],
        iconClass: 'jp-MaterialIcon jp-FileIcon',
        iconLabel: '',
        contentType: 'file',
        fileFormat: 'text'
    };
    /**
     * The default text file type used by the document registry.
     */
    DocumentRegistry.defaultTextFileType = Object.assign({}, DocumentRegistry.fileTypeDefaults, { name: 'text', mimeTypes: ['text/plain'], extensions: ['.txt'] });
    /**
     * The default notebook file type used by the document registry.
     */
    DocumentRegistry.defaultNotebookFileType = Object.assign({}, DocumentRegistry.fileTypeDefaults, { name: 'notebook', displayName: 'Notebook', mimeTypes: ['application/x-ipynb+json'], extensions: ['.ipynb'], contentType: 'notebook', fileFormat: 'json', iconClass: 'jp-MaterialIcon jp-NotebookIcon' });
    /**
     * The default directory file type used by the document registry.
     */
    DocumentRegistry.defaultDirectoryFileType = Object.assign({}, DocumentRegistry.fileTypeDefaults, { name: 'directory', extensions: [], mimeTypes: ['text/directory'], contentType: 'directory', iconClass: 'jp-MaterialIcon jp-OpenFolderIcon' });
    /**
     * The default file types used by the document registry.
     */
    DocumentRegistry.defaultFileTypes = [
        DocumentRegistry.defaultTextFileType,
        DocumentRegistry.defaultNotebookFileType,
        DocumentRegistry.defaultDirectoryFileType,
        {
            name: 'markdown',
            displayName: 'Markdown File',
            extensions: ['.md'],
            mimeTypes: ['text/markdown'],
            iconClass: 'jp-MaterialIcon jp-MarkdownIcon'
        },
        {
            name: 'python',
            displayName: 'Python File',
            extensions: ['.py'],
            mimeTypes: ['text/x-python'],
            iconClass: 'jp-MaterialIcon jp-PythonIcon'
        },
        {
            name: 'json',
            displayName: 'JSON File',
            extensions: ['.json'],
            mimeTypes: ['application/json'],
            iconClass: 'jp-MaterialIcon jp-JSONIcon'
        },
        {
            name: 'csv',
            displayName: 'CSV File',
            extensions: ['.csv'],
            mimeTypes: ['text/csv'],
            iconClass: 'jp-MaterialIcon jp-SpreadsheetIcon'
        },
        {
            name: 'tsv',
            displayName: 'TSV File',
            extensions: ['.tsv'],
            mimeTypes: ['text/csv'],
            iconClass: 'jp-MaterialIcon jp-SpreadsheetIcon'
        },
        {
            name: 'r',
            displayName: 'R File',
            mimeTypes: ['text/x-rsrc'],
            extensions: ['.r'],
            iconClass: 'jp-MaterialIcon jp-RKernelIcon'
        },
        {
            name: 'yaml',
            displayName: 'YAML File',
            mimeTypes: ['text/x-yaml', 'text/yaml'],
            extensions: ['.yaml', '.yml'],
            iconClass: 'jp-MaterialIcon jp-YamlIcon'
        },
        {
            name: 'svg',
            displayName: 'Image',
            mimeTypes: ['image/svg+xml'],
            extensions: ['.svg'],
            iconClass: 'jp-MaterialIcon jp-ImageIcon',
            fileFormat: 'base64'
        },
        {
            name: 'tiff',
            displayName: 'Image',
            mimeTypes: ['image/tiff'],
            extensions: ['.tif', '.tiff'],
            iconClass: 'jp-MaterialIcon jp-ImageIcon',
            fileFormat: 'base64'
        },
        {
            name: 'jpeg',
            displayName: 'Image',
            mimeTypes: ['image/jpeg'],
            extensions: ['.jpg', '.jpeg'],
            iconClass: 'jp-MaterialIcon jp-ImageIcon',
            fileFormat: 'base64'
        },
        {
            name: 'gif',
            displayName: 'Image',
            mimeTypes: ['image/gif'],
            extensions: ['.gif'],
            iconClass: 'jp-MaterialIcon jp-ImageIcon',
            fileFormat: 'base64'
        },
        {
            name: 'png',
            displayName: 'Image',
            mimeTypes: ['image/png'],
            extensions: ['.png'],
            iconClass: 'jp-MaterialIcon jp-ImageIcon',
            fileFormat: 'base64'
        },
        {
            name: 'bmp',
            displayName: 'Image',
            mimeTypes: ['image/bmp'],
            extensions: ['.bmp'],
            iconClass: 'jp-MaterialIcon jp-ImageIcon',
            fileFormat: 'base64'
        }
    ];
})(DocumentRegistry = exports.DocumentRegistry || (exports.DocumentRegistry = {}));
/**
 * A private namespace for DocumentRegistry data.
 */
var Private;
(function (Private) {
    /**
     * Get the extension name of a path.
     *
     * @param file - string.
     *
     * #### Notes
     * Dotted filenames (e.g. `".table.json"` are allowed).
     */
    function extname(path) {
        let parts = coreutils_1.PathExt.basename(path).split('.');
        parts.shift();
        let ext = '.' + parts.join('.');
        return ext.toLowerCase();
    }
    Private.extname = extname;
    /**
     * A no-op function.
     */
    function noOp() {
        /* no-op */
    }
    Private.noOp = noOp;
})(Private || (Private = {}));


/***/ }),

/***/ "EW15":
/*!****************************************************************!*\
  !*** ./node_modules/@jupyter-widgets/base/lib/widget_style.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = __webpack_require__(/*! ./utils */ "o9P/");
var widget_1 = __webpack_require__(/*! ./widget */ "rynU");
var StyleModel = /** @class */ (function (_super) {
    __extends(StyleModel, _super);
    function StyleModel() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    StyleModel.prototype.defaults = function () {
        var Derived = this.constructor;
        return utils_1.assign(_super.prototype.defaults.call(this), {
            _model_name: 'StyleModel',
            _view_name: 'StyleView',
        }, Object.keys(Derived.styleProperties).reduce(function (obj, key) {
            obj[key] = Derived.styleProperties[key].default;
            return obj;
        }, {}));
    };
    StyleModel.styleProperties = {};
    return StyleModel;
}(widget_1.WidgetModel));
exports.StyleModel = StyleModel;
var StyleView = /** @class */ (function (_super) {
    __extends(StyleView, _super);
    function StyleView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    /**
     * Public constructor
     */
    StyleView.prototype.initialize = function (parameters) {
        this._traitNames = [];
        _super.prototype.initialize.call(this, parameters);
        // Register the traits that live on the Python side
        var ModelType = this.model.constructor;
        for (var _i = 0, _a = Object.keys(ModelType.styleProperties); _i < _a.length; _i++) {
            var key = _a[_i];
            this.registerTrait(key);
        }
        // Set the initial styles
        this.style();
    };
    /**
     * Register a CSS trait that is known by the model
     * @param trait
     */
    StyleView.prototype.registerTrait = function (trait) {
        var _this = this;
        this._traitNames.push(trait);
        // Listen to changes, and set the value on change.
        this.listenTo(this.model, 'change:' + trait, function (model, value) {
            _this.handleChange(trait, value);
        });
    };
    /**
     * Handles when a trait value changes
     */
    StyleView.prototype.handleChange = function (trait, value) {
        // should be synchronous so that we can measure later.
        var parent = this.options.parent;
        if (parent) {
            var ModelType = this.model.constructor;
            var styleProperties = ModelType.styleProperties;
            var attribute = styleProperties[trait].attribute;
            var selector = styleProperties[trait].selector;
            var elements = selector ? parent.el.querySelectorAll(selector) : [parent.el];
            if (value === null) {
                for (var i = 0; i !== elements.length; ++i) {
                    elements[i].style.removeProperty(attribute);
                }
            }
            else {
                for (var i = 0; i !== elements.length; ++i) {
                    elements[i].style[attribute] = value;
                }
            }
        }
        else {
            console.warn('Style not applied because a parent view does not exist');
        }
    };
    /**
     * Apply styles for all registered traits
     */
    StyleView.prototype.style = function () {
        for (var _i = 0, _a = this._traitNames; _i < _a.length; _i++) {
            var trait = _a[_i];
            this.handleChange(trait, this.model.get(trait));
        }
    };
    /**
     * Remove the styling from the parent view.
     */
    StyleView.prototype.unstyle = function () {
        var parent = this.options.parent;
        var ModelType = this.model.constructor;
        var styleProperties = ModelType.styleProperties;
        this._traitNames.forEach(function (trait) {
            if (parent) {
                var attribute = styleProperties[trait].attribute;
                var selector = styleProperties[trait].selector;
                var elements = selector ? parent.el.querySelectorAll(selector) : [parent.el];
                for (var i = 0; i !== elements.length; ++i) {
                    elements[i].style.removeProperty(attribute);
                }
            }
            else {
                console.warn('Style not removed because a parent view does not exist');
            }
        }, this);
    };
    return StyleView;
}(widget_1.WidgetView));
exports.StyleView = StyleView;


/***/ }),

/***/ "EW2V":
/*!***********************************************!*\
  !*** ./node_modules/browserify-sign/algos.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(/*! ./browser/algorithms.json */ "tOiH")


/***/ }),

/***/ "Eb04":
/*!******************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/localize.js ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




var Registry = __webpack_require__(/*! ../registry */ "GF7H");

/**
 * localize: translate a string for the current locale
 *
 * @param {object} gd: the graphDiv for context
 *  gd._context.locale determines the language (& optional region/country)
 *  the dictionary for each locale may either be supplied in
 *  gd._context.locales or globally via Plotly.register
 * @param {string} s: the string to translate
 */
module.exports = function localize(gd, s) {
    var locale = gd._context.locale;

    /*
     * Priority of lookup:
     *     contextDicts[locale],
     *     registeredDicts[locale],
     *     contextDicts[baseLocale], (if baseLocale is distinct)
     *     registeredDicts[baseLocale]
     * Return the first translation we find.
     * This way if you have a regionalization you are allowed to specify
     * only what's different from the base locale, everything else will
     * fall back on the base.
     */
    for(var i = 0; i < 2; i++) {
        var locales = gd._context.locales;
        for(var j = 0; j < 2; j++) {
            var dict = (locales[locale] || {}).dictionary;
            if(dict) {
                var out = dict[s];
                if(out) return out;
            }
            locales = Registry.localeRegistry;
        }

        var baseLocale = locale.split('-')[0];
        if(baseLocale === locale) break;
        locale = baseLocale;
    }

    return s;
};


/***/ }),

/***/ "Edxu":
/*!*********************************************!*\
  !*** ./node_modules/randombytes/browser.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global, process) {

// limit of Crypto.getRandomValues()
// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
var MAX_BYTES = 65536

// Node supports requesting up to this number of bytes
// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48
var MAX_UINT32 = 4294967295

function oldBrowser () {
  throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11')
}

var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer
var crypto = global.crypto || global.msCrypto

if (crypto && crypto.getRandomValues) {
  module.exports = randomBytes
} else {
  module.exports = oldBrowser
}

function randomBytes (size, cb) {
  // phantomjs needs to throw
  if (size > MAX_UINT32) throw new RangeError('requested too many random bytes')

  var bytes = Buffer.allocUnsafe(size)

  if (size > 0) {  // getRandomValues fails on IE if size == 0
    if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues
      // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
      for (var generated = 0; generated < size; generated += MAX_BYTES) {
        // buffer.slice automatically checks if the end is past the end of
        // the buffer so we don't have to here
        crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES))
      }
    } else {
      crypto.getRandomValues(bytes)
    }
  }

  if (typeof cb === 'function') {
    return process.nextTick(function () {
      cb(null, bytes)
    })
  }

  return bytes
}

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "yLpj"), __webpack_require__(/*! ./../process/browser.js */ "8oxB")))

/***/ }),

/***/ "Efrf":
/*!***************************************************************************!*\
  !*** ./node_modules/react-color/lib/components/swatches/SwatchesGroup.js ***!
  \***************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SwatchesGroup = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _map = __webpack_require__(/*! lodash/map */ "3WF5");

var _map2 = _interopRequireDefault(_map);

var _SwatchesColor = __webpack_require__(/*! ./SwatchesColor */ "BmQL");

var _SwatchesColor2 = _interopRequireDefault(_SwatchesColor);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var SwatchesGroup = exports.SwatchesGroup = function SwatchesGroup(_ref) {
  var onClick = _ref.onClick,
      onSwatchHover = _ref.onSwatchHover,
      group = _ref.group,
      active = _ref.active;

  var styles = (0, _reactcss2.default)({
    'default': {
      group: {
        paddingBottom: '10px',
        width: '40px',
        float: 'left',
        marginRight: '10px'
      }
    }
  });

  return _react2.default.createElement(
    'div',
    { style: styles.group },
    (0, _map2.default)(group, function (color, i) {
      return _react2.default.createElement(_SwatchesColor2.default, {
        key: color,
        color: color,
        active: color.toLowerCase() === active,
        first: i === 0,
        last: i === group.length - 1,
        onClick: onClick,
        onSwatchHover: onSwatchHover
      });
    })
  );
};

exports.default = SwatchesGroup;

/***/ }),

/***/ "EnHN":
/*!***********************************************************************************!*\
  !*** ./node_modules/core-js/library/modules/es6.object.get-own-property-names.js ***!
  \***********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.7 Object.getOwnPropertyNames(O)
__webpack_require__(/*! ./_object-sap */ "zn7N")('getOwnPropertyNames', function () {
  return __webpack_require__(/*! ./_object-gopn-ext */ "A5Xg").f;
});


/***/ }),

/***/ "EpBk":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_isKeyable.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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);
}

module.exports = isKeyable;


/***/ }),

/***/ "EqA/":
/*!*******************************************************!*\
  !*** ./node_modules/@jupyterlab/mainmenu/lib/file.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const labmenu_1 = __webpack_require__(/*! ./labmenu */ "e7FE");
/**
 * An extensible FileMenu for the application.
 */
class FileMenu extends labmenu_1.JupyterLabMenu {
    constructor(options) {
        super(options);
        this.menu.title.label = 'File';
        this.quitEntry = false;
        // Create the "New" submenu.
        this.newMenu = new labmenu_1.JupyterLabMenu(options, false);
        this.newMenu.menu.title.label = 'New';
        this.closeAndCleaners = new Set();
        this.persistAndSavers = new Set();
        this.consoleCreators = new Set();
    }
    /**
     * Dispose of the resources held by the file menu.
     */
    dispose() {
        this.newMenu.dispose();
        this.consoleCreators.clear();
        super.dispose();
    }
}
exports.FileMenu = FileMenu;


/***/ }),

/***/ "Et+i":
/*!***********************************************************!*\
  !*** ./node_modules/react-day-picker/lib/src/Weekdays.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Weekdays = function (_Component) {
  _inherits(Weekdays, _Component);

  function Weekdays() {
    _classCallCheck(this, Weekdays);

    return _possibleConstructorReturn(this, (Weekdays.__proto__ || Object.getPrototypeOf(Weekdays)).apply(this, arguments));
  }

  _createClass(Weekdays, [{
    key: 'shouldComponentUpdate',
    value: function shouldComponentUpdate(nextProps) {
      return this.props !== nextProps;
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          classNames = _props.classNames,
          firstDayOfWeek = _props.firstDayOfWeek,
          showWeekNumbers = _props.showWeekNumbers,
          weekdaysLong = _props.weekdaysLong,
          weekdaysShort = _props.weekdaysShort,
          locale = _props.locale,
          localeUtils = _props.localeUtils,
          weekdayElement = _props.weekdayElement;

      var days = [];
      for (var i = 0; i < 7; i += 1) {
        var weekday = (i + firstDayOfWeek) % 7;
        var elementProps = {
          key: i,
          className: classNames.weekday,
          weekday: weekday,
          weekdaysLong: weekdaysLong,
          weekdaysShort: weekdaysShort,
          localeUtils: localeUtils,
          locale: locale
        };
        var element = _react2.default.isValidElement(weekdayElement) ? _react2.default.cloneElement(weekdayElement, elementProps) : _react2.default.createElement(weekdayElement, elementProps);
        days.push(element);
      }

      return _react2.default.createElement(
        'div',
        { className: classNames.weekdays, role: 'rowgroup' },
        _react2.default.createElement(
          'div',
          { className: classNames.weekdaysRow, role: 'row' },
          showWeekNumbers && _react2.default.createElement('div', { className: classNames.weekday }),
          days
        )
      );
    }
  }]);

  return Weekdays;
}(_react.Component);

exports.default = Weekdays;
Weekdays.propTypes =  true ? {
  classNames: _propTypes2.default.shape({
    weekday: _propTypes2.default.string.isRequired,
    weekdays: _propTypes2.default.string.isRequired,
    weekdaysRow: _propTypes2.default.string.isRequired
  }).isRequired,

  firstDayOfWeek: _propTypes2.default.number.isRequired,
  weekdaysLong: _propTypes2.default.arrayOf(_propTypes2.default.string),
  weekdaysShort: _propTypes2.default.arrayOf(_propTypes2.default.string),
  showWeekNumbers: _propTypes2.default.bool,
  locale: _propTypes2.default.string.isRequired,
  localeUtils: _propTypes2.default.object.isRequired,
  weekdayElement: _propTypes2.default.oneOfType([_propTypes2.default.element, _propTypes2.default.func, _propTypes2.default.instanceOf(_react2.default.Component)])
} : undefined;
//# sourceMappingURL=Weekdays.js.map

/***/ }),

/***/ "EugZ":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/fileeditor/lib/widget.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const docregistry_1 = __webpack_require__(/*! @jupyterlab/docregistry */ "jTF0");
const codeeditor_1 = __webpack_require__(/*! @jupyterlab/codeeditor */ "sLCx");
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
/**
 * The data attribute added to a widget that can run code.
 */
const CODE_RUNNER = 'jpCodeRunner';
/**
 * The data attribute added to a widget that can undo.
 */
const UNDOER = 'jpUndoer';
/**
 * A code editor wrapper for the file editor.
 */
class FileEditorCodeWrapper extends codeeditor_1.CodeEditorWrapper {
    /**
     * Construct a new editor widget.
     */
    constructor(options) {
        super({
            factory: options.factory,
            model: options.context.model
        });
        this._ready = new coreutils_1.PromiseDelegate();
        const context = (this._context = options.context);
        const editor = this.editor;
        this.addClass('jp-FileEditorCodeWrapper');
        this.node.dataset[CODE_RUNNER] = 'true';
        this.node.dataset[UNDOER] = 'true';
        editor.model.value.text = context.model.toString();
        context.ready.then(() => {
            this._onContextReady();
        });
        if (context.model.modelDB.isCollaborative) {
            let modelDB = context.model.modelDB;
            modelDB.connected.then(() => {
                let collaborators = modelDB.collaborators;
                if (!collaborators) {
                    return;
                }
                // Setup the selection style for collaborators
                let localCollaborator = collaborators.localCollaborator;
                this.editor.uuid = localCollaborator.sessionId;
                this.editor.selectionStyle = Object.assign({}, codeeditor_1.CodeEditor.defaultSelectionStyle, { color: localCollaborator.color });
                collaborators.changed.connect(this._onCollaboratorsChanged, this);
                // Trigger an initial onCollaboratorsChanged event.
                this._onCollaboratorsChanged();
            });
        }
    }
    /**
     * Get the context for the editor widget.
     */
    get context() {
        return this._context;
    }
    /**
     * A promise that resolves when the file editor is ready.
     */
    get ready() {
        return this._ready.promise;
    }
    /**
     * Handle actions that should be taken when the context is ready.
     */
    _onContextReady() {
        if (this.isDisposed) {
            return;
        }
        const contextModel = this._context.model;
        const editor = this.editor;
        const editorModel = editor.model;
        // Set the editor model value.
        editorModel.value.text = contextModel.toString();
        // Prevent the initial loading from disk from being in the editor history.
        editor.clearHistory();
        // Wire signal connections.
        contextModel.contentChanged.connect(this._onContentChanged, this);
        // Resolve the ready promise.
        this._ready.resolve(undefined);
    }
    /**
     * Handle a change in context model content.
     */
    _onContentChanged() {
        const editorModel = this.editor.model;
        const oldValue = editorModel.value.text;
        const newValue = this._context.model.toString();
        if (oldValue !== newValue) {
            editorModel.value.text = newValue;
        }
    }
    /**
     * Handle a change to the collaborators on the model
     * by updating UI elements associated with them.
     */
    _onCollaboratorsChanged() {
        // If there are selections corresponding to non-collaborators,
        // they are stale and should be removed.
        let collaborators = this._context.model.modelDB.collaborators;
        if (!collaborators) {
            return;
        }
        for (let key of this.editor.model.selections.keys()) {
            if (!collaborators.has(key)) {
                this.editor.model.selections.delete(key);
            }
        }
    }
}
exports.FileEditorCodeWrapper = FileEditorCodeWrapper;
/**
 * A widget for editors.
 */
class FileEditor extends widgets_1.Widget {
    /**
     * Construct a new editor widget.
     */
    constructor(options) {
        super();
        this.addClass('jp-FileEditor');
        const context = (this._context = options.context);
        this._mimeTypeService = options.mimeTypeService;
        let editorWidget = (this.editorWidget = new FileEditorCodeWrapper(options));
        this.editor = editorWidget.editor;
        this.model = editorWidget.model;
        // Listen for changes to the path.
        context.pathChanged.connect(this._onPathChanged, this);
        this._onPathChanged();
        let layout = (this.layout = new widgets_1.StackedLayout());
        layout.addWidget(editorWidget);
    }
    /**
     * Get the context for the editor widget.
     */
    get context() {
        return this.editorWidget.context;
    }
    /**
     * A promise that resolves when the file editor is ready.
     */
    get ready() {
        return this.editorWidget.ready;
    }
    /**
     * Handle the DOM events for the widget.
     *
     * @param event - The DOM event sent to the widget.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the widget's node. It should
     * not be called directly by user code.
     */
    handleEvent(event) {
        if (!this.model) {
            return;
        }
        switch (event.type) {
            case 'mousedown':
                this._ensureFocus();
                break;
            default:
                break;
        }
    }
    /**
     * Handle `after-attach` messages for the widget.
     */
    onAfterAttach(msg) {
        super.onAfterAttach(msg);
        let node = this.node;
        node.addEventListener('mousedown', this);
    }
    /**
     * Handle `before-detach` messages for the widget.
     */
    onBeforeDetach(msg) {
        let node = this.node;
        node.removeEventListener('mousedown', this);
    }
    /**
     * Handle `'activate-request'` messages.
     */
    onActivateRequest(msg) {
        this._ensureFocus();
    }
    /**
     * Ensure that the widget has focus.
     */
    _ensureFocus() {
        if (!this.editor.hasFocus()) {
            this.editor.focus();
        }
    }
    /**
     * Handle a change to the path.
     */
    _onPathChanged() {
        const editor = this.editor;
        const localPath = this._context.localPath;
        editor.model.mimeType = this._mimeTypeService.getMimeTypeByFilePath(localPath);
    }
}
exports.FileEditor = FileEditor;
/**
 * A widget factory for editors.
 */
class FileEditorFactory extends docregistry_1.ABCWidgetFactory {
    /**
     * Construct a new editor widget factory.
     */
    constructor(options) {
        super(options.factoryOptions);
        this._services = options.editorServices;
    }
    /**
     * Create a new widget given a context.
     */
    createNewWidget(context) {
        let func = this._services.factoryService.newDocumentEditor;
        let factory = options => {
            return func(options);
        };
        const content = new FileEditor({
            factory,
            context,
            mimeTypeService: this._services.mimeTypeService
        });
        const widget = new docregistry_1.DocumentWidget({ content, context });
        return widget;
    }
}
exports.FileEditorFactory = FileEditorFactory;


/***/ }),

/***/ "EwQA":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_castFunction.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var identity = __webpack_require__(/*! ./identity */ "zZ0H");

/**
 * 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;
}

module.exports = castFunction;


/***/ }),

/***/ "ExA7":
/*!*********************************************!*\
  !*** ./node_modules/lodash/isObjectLike.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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';
}

module.exports = isObjectLike;


/***/ }),

/***/ "ExqO":
/*!********************************************************!*\
  !*** ./node_modules/@phosphor/algorithm/lib/reduce.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var iter_1 = __webpack_require__(/*! ./iter */ "DMSk");
function reduce(object, fn, initial) {
    // Setup the iterator and fetch the first value.
    var index = 0;
    var it = iter_1.iter(object);
    var first = it.next();
    // An empty iterator and no initial value is an error.
    if (first === undefined && initial === undefined) {
        throw new TypeError('Reduce of empty iterable with no initial value.');
    }
    // If the iterator is empty, return the initial value.
    if (first === undefined) {
        return initial;
    }
    // If the iterator has a single item and no initial value, the
    // reducer is not invoked and the first item is the return value.
    var second = it.next();
    if (second === undefined && initial === undefined) {
        return first;
    }
    // If iterator has a single item and an initial value is provided,
    // the reducer is invoked and that result is the return value.
    if (second === undefined) {
        return fn(initial, first, index++);
    }
    // Setup the initial accumlated value.
    var accumulator;
    if (initial === undefined) {
        accumulator = fn(first, second, index++);
    }
    else {
        accumulator = fn(fn(initial, first, index++), second, index++);
    }
    // Iterate the rest of the values, updating the accumulator.
    var next;
    while ((next = it.next()) !== undefined) {
        accumulator = fn(accumulator, next, index++);
    }
    // Return the final accumulated value.
    return accumulator;
}
exports.reduce = reduce;


/***/ }),

/***/ "EzAi":
/*!**************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/kernel/comm.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const disposable_1 = __webpack_require__(/*! @phosphor/disposable */ "uNUc");
const messages_1 = __webpack_require__(/*! ./messages */ "Wg3t");
/**
 * Comm channel handler.
 */
class CommHandler extends disposable_1.DisposableDelegate {
    /**
     * Construct a new comm channel.
     */
    constructor(target, id, kernel, disposeCb) {
        super(disposeCb);
        this._target = '';
        this._id = '';
        this._id = id;
        this._target = target;
        this._kernel = kernel;
    }
    /**
     * The unique id for the comm channel.
     */
    get commId() {
        return this._id;
    }
    /**
     * The target name for the comm channel.
     */
    get targetName() {
        return this._target;
    }
    /**
     * Get the callback for a comm close event.
     *
     * #### Notes
     * This is called when the comm is closed from either the server or client.
     *
     * **See also:** [[ICommClose]], [[close]]
     */
    get onClose() {
        return this._onClose;
    }
    /**
     * Set the callback for a comm close event.
     *
     * #### Notes
     * This is called when the comm is closed from either the server or client. If
     * the function returns a promise, and the kernel was closed from the server,
     * kernel message processing will pause until the returned promise is
     * fulfilled.
     *
     * **See also:** [[close]]
     */
    set onClose(cb) {
        this._onClose = cb;
    }
    /**
     * Get the callback for a comm message received event.
     */
    get onMsg() {
        return this._onMsg;
    }
    /**
     * Set the callback for a comm message received event.
     *
     * #### Notes
     * This is called when a comm message is received. If the function returns a
     * promise, kernel message processing will pause until it is fulfilled.
     */
    set onMsg(cb) {
        this._onMsg = cb;
    }
    /**
     * Open a comm with optional data and metadata.
     *
     * #### Notes
     * This sends a `comm_open` message to the server.
     *
     * **See also:** [[ICommOpen]]
     */
    open(data, metadata, buffers = []) {
        if (this.isDisposed || this._kernel.isDisposed) {
            throw new Error('Cannot open');
        }
        let options = {
            msgType: 'comm_open',
            channel: 'shell',
            username: this._kernel.username,
            session: this._kernel.clientId
        };
        let content = {
            comm_id: this._id,
            target_name: this._target,
            data: data || {}
        };
        let msg = messages_1.KernelMessage.createShellMessage(options, content, metadata, buffers);
        return this._kernel.sendShellMessage(msg, false, true);
    }
    /**
     * Send a `comm_msg` message to the kernel.
     *
     * #### Notes
     * This is a no-op if the comm has been closed.
     *
     * **See also:** [[ICommMsg]]
     */
    send(data, metadata, buffers = [], disposeOnDone = true) {
        if (this.isDisposed || this._kernel.isDisposed) {
            throw new Error('Cannot send');
        }
        let options = {
            msgType: 'comm_msg',
            channel: 'shell',
            username: this._kernel.username,
            session: this._kernel.clientId
        };
        let content = {
            comm_id: this._id,
            data: data
        };
        let msg = messages_1.KernelMessage.createShellMessage(options, content, metadata, buffers);
        return this._kernel.sendShellMessage(msg, false, true);
    }
    /**
     * Close the comm.
     *
     * #### Notes
     * This will send a `comm_close` message to the kernel, and call the
     * `onClose` callback if set.
     *
     * This is a no-op if the comm is already closed.
     *
     * **See also:** [[ICommClose]], [[onClose]]
     */
    close(data, metadata, buffers = []) {
        if (this.isDisposed || this._kernel.isDisposed) {
            throw new Error('Cannot close');
        }
        let options = {
            msgType: 'comm_msg',
            channel: 'shell',
            username: this._kernel.username,
            session: this._kernel.clientId
        };
        let content = {
            comm_id: this._id,
            data: data || {}
        };
        let msg = messages_1.KernelMessage.createShellMessage(options, content, metadata, buffers);
        let future = this._kernel.sendShellMessage(msg, false, true);
        options.channel = 'iopub';
        let onClose = this._onClose;
        if (onClose) {
            let ioMsg = messages_1.KernelMessage.createMessage(options, content, metadata, buffers);
            // In the future, we may want to communicate back to the user the possible
            // promise returned from onClose.
            onClose(ioMsg);
        }
        this.dispose();
        return future;
    }
}
exports.CommHandler = CommHandler;


/***/ }),

/***/ "EzBX":
/*!**************************************************************!*\
  !*** ./node_modules/mdi-react/AccountMultipleOutlineIcon.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var AccountMultipleOutlineIcon = function AccountMultipleOutlineIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M9,4C11.21,4 13,5.79 13,8C13,10.21 11.21,12 9,12C6.79,12 5,10.21 5,8C5,5.79 6.79,4 9,4M9,6C7.9,6 7,6.9 7,8C7,9.1 7.9,10 9,10C10.1,10 11,9.1 11,8C11,6.9 10.1,6 9,6M9,13C11.67,13 17,14.34 17,17V20H1V17C1,14.34 6.33,13 9,13M9,14.9C6.03,14.9 2.9,16.36 2.9,17V18.1H15.1V17C15.1,16.36 11.97,14.9 9,14.9M15,4C17.21,4 19,5.79 19,8C19,10.21 17.21,12 15,12C14.53,12 14.08,11.92 13.67,11.77C14.5,10.74 15,9.43 15,8C15,6.57 14.5,5.26 13.67,4.23C14.08,4.08 14.53,4 15,4M23,17V20H19V16.5C19,15.25 18.24,14.1 16.97,13.18C19.68,13.62 23,14.9 23,17Z' })
  );
};

module.exports = AccountMultipleOutlineIcon;


/***/ }),

/***/ "Ezr3":
/*!*************************************************!*\
  !*** ./node_modules/base16/lib/shapeshifter.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'shapeshifter',
  author: 'tyler benziger (http://tybenz.com)',
  base00: '#000000',
  base01: '#040404',
  base02: '#102015',
  base03: '#343434',
  base04: '#555555',
  base05: '#ababab',
  base06: '#e0e0e0',
  base07: '#f9f9f9',
  base08: '#e92f2f',
  base09: '#e09448',
  base0A: '#dddd13',
  base0B: '#0ed839',
  base0C: '#23edda',
  base0D: '#3b48e3',
  base0E: '#f996e2',
  base0F: '#69542d'
};
module.exports = exports['default'];

/***/ }),

/***/ "F+2o":
/*!***************************************************************!*\
  !*** ./node_modules/babel-runtime/core-js/symbol/iterator.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = { "default": __webpack_require__(/*! core-js/library/fn/symbol/iterator */ "2Nb0"), __esModule: true };

/***/ }),

/***/ "F/Rj":
/*!************************************************************!*\
  !*** ./node_modules/@jupyterlab/coreutils/lib/nbformat.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
// Notebook format interfaces
// https://nbformat.readthedocs.io/en/latest/format_description.html
// https://github.com/jupyter/nbformat/blob/master/nbformat/v4/nbformat.v4.schema.json
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
/**
 * A namespace for nbformat interfaces.
 */
var nbformat;
(function (nbformat) {
    /**
     * The major version of the notebook format.
     */
    nbformat.MAJOR_VERSION = 4;
    /**
     * The minor version of the notebook format.
     */
    nbformat.MINOR_VERSION = 2;
    /**
     * Validate a mime type/value pair.
     *
     * @param type - The mimetype name.
     *
     * @param value - The value associated with the type.
     *
     * @returns Whether the type/value pair are valid.
     */
    function validateMimeValue(type, value) {
        // Check if "application/json" or "application/foo+json"
        const jsonTest = /^application\/(.*?)+\+json$/;
        const isJSONType = type === 'application/json' || jsonTest.test(type);
        let isString = (x) => {
            return Object.prototype.toString.call(x) === '[object String]';
        };
        // If it is an array, make sure if is not a JSON type and it is an
        // array of strings.
        if (Array.isArray(value)) {
            if (isJSONType) {
                return false;
            }
            let valid = true;
            value.forEach(v => {
                if (!isString(v)) {
                    valid = false;
                }
            });
            return valid;
        }
        // If it is a string, make sure we are not a JSON type.
        if (isString(value)) {
            return !isJSONType;
        }
        // It is not a string, make sure it is a JSON type.
        if (!isJSONType) {
            return false;
        }
        // It is a JSON type, make sure it is a valid JSON object.
        return coreutils_1.JSONExt.isObject(value);
    }
    nbformat.validateMimeValue = validateMimeValue;
    /**
     * Test whether a cell is a raw cell.
     */
    function isRaw(cell) {
        return cell.cell_type === 'raw';
    }
    nbformat.isRaw = isRaw;
    /**
     * Test whether a cell is a markdown cell.
     */
    function isMarkdown(cell) {
        return cell.cell_type === 'markdown';
    }
    nbformat.isMarkdown = isMarkdown;
    /**
     * Test whether a cell is a code cell.
     */
    function isCode(cell) {
        return cell.cell_type === 'code';
    }
    nbformat.isCode = isCode;
    /**
     * Test whether an output is an execute result.
     */
    function isExecuteResult(output) {
        return output.output_type === 'execute_result';
    }
    nbformat.isExecuteResult = isExecuteResult;
    /**
     * Test whether an output is from display data.
     */
    function isDisplayData(output) {
        return output.output_type === 'display_data';
    }
    nbformat.isDisplayData = isDisplayData;
    /**
     * Test whether an output is from updated display data.
     */
    function isDisplayUpdate(output) {
        return output.output_type === 'update_display_data';
    }
    nbformat.isDisplayUpdate = isDisplayUpdate;
    /**
     * Test whether an output is from a stream.
     */
    function isStream(output) {
        return output.output_type === 'stream';
    }
    nbformat.isStream = isStream;
    /**
     * Test whether an output is from a stream.
     */
    function isError(output) {
        return output.output_type === 'error';
    }
    nbformat.isError = isError;
})(nbformat = exports.nbformat || (exports.nbformat = {}));


/***/ }),

/***/ "F/us":
/*!***********************************************!*\
  !*** ./node_modules/underscore/underscore.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global, module) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;//     Underscore.js 1.9.1
//     http://underscorejs.org
//     (c) 2009-2018 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
//     Underscore may be freely distributed under the MIT license.

(function() {

  // Baseline setup
  // --------------

  // 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 global == 'object' && global.global === global && global ||
            this ||
            {};

  // Save the previous value of the `_` variable.
  var previousUnderscore = root._;

  // 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;

  // All **ECMAScript 5** native function implementations that we hope to use
  // are declared here.
  var nativeIsArray = Array.isArray,
      nativeKeys = Object.keys,
      nativeCreate = Object.create;

  // Naked function reference for surrogate-prototype-swapping.
  var Ctor = function(){};

  // Create a safe reference to the Underscore object for use below.
  var _ = function(obj) {
    if (obj instanceof _) return obj;
    if (!(this instanceof _)) return new _(obj);
    this._wrapped = obj;
  };

  // Export the Underscore object for **Node.js**, with
  // backwards-compatibility for their old module API. If we're in
  // the browser, add `_` as a global object.
  // (`nodeType` is checked to ensure that `module`
  // and `exports` are not HTML elements.)
  if (typeof exports != 'undefined' && !exports.nodeType) {
    if (typeof module != 'undefined' && !module.nodeType && module.exports) {
      exports = module.exports = _;
    }
    exports._ = _;
  } else {
    root._ = _;
  }

  // Current version.
  _.VERSION = '1.9.1';

  // Internal function that returns an efficient (for current engines) version
  // of the passed-in callback, to be repeatedly applied in other Underscore
  // functions.
  var optimizeCb = function(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);
    };
  };

  var builtinIteratee;

  // 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.
  var cb = function(value, context, argCount) {
    if (_.iteratee !== builtinIteratee) return _.iteratee(value, context);
    if (value == null) return _.identity;
    if (_.isFunction(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.
  _.iteratee = builtinIteratee = function(value, context) {
    return cb(value, context, Infinity);
  };

  // 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".
  var restArguments = function(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);
    };
  };

  // An internal function for creating a new object that inherits from another.
  var baseCreate = function(prototype) {
    if (!_.isObject(prototype)) return {};
    if (nativeCreate) return nativeCreate(prototype);
    Ctor.prototype = prototype;
    var result = new Ctor;
    Ctor.prototype = null;
    return result;
  };

  var shallowProperty = function(key) {
    return function(obj) {
      return obj == null ? void 0 : obj[key];
    };
  };

  var has = function(obj, path) {
    return obj != null && hasOwnProperty.call(obj, path);
  }

  var deepGet = function(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;
  };

  // Helper for collection methods to determine whether a collection
  // should be iterated as an array or as an object.
  // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
  // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
  var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
  var getLength = shallowProperty('length');
  var isArrayLike = function(collection) {
    var length = getLength(collection);
    return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
  };

  // Collection Functions
  // --------------------

  // The cornerstone, an `each` implementation, aka `forEach`.
  // Handles raw objects in addition to array-likes. Treats all
  // sparse array-likes as if they were dense.
  _.each = _.forEach = function(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.
  _.map = _.collect = function(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;
  };

  // Create a reducing function iterating left or right.
  var createReduce = function(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`.
  _.reduce = _.foldl = _.inject = createReduce(1);

  // The right-associative version of reduce, also known as `foldr`.
  _.reduceRight = _.foldr = createReduce(-1);

  // Return the first value which passes a truth test. Aliased as `detect`.
  _.find = _.detect = function(obj, predicate, context) {
    var keyFinder = isArrayLike(obj) ? _.findIndex : _.findKey;
    var key = keyFinder(obj, predicate, context);
    if (key !== void 0 && key !== -1) return obj[key];
  };

  // Return all the elements that pass a truth test.
  // Aliased as `select`.
  _.filter = _.select = function(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.
  _.reject = function(obj, predicate, context) {
    return _.filter(obj, _.negate(cb(predicate)), context);
  };

  // Determine whether all of the elements match a truth test.
  // Aliased as `all`.
  _.every = _.all = function(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 matches a truth test.
  // Aliased as `any`.
  _.some = _.any = function(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 `===`).
  // Aliased as `includes` and `include`.
  _.contains = _.includes = _.include = function(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.
  _.invoke = restArguments(function(obj, path, args) {
    var contextPath, func;
    if (_.isFunction(path)) {
      func = path;
    } else if (_.isArray(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.
  _.pluck = function(obj, key) {
    return _.map(obj, _.property(key));
  };

  // Convenience version of a common use case of `filter`: selecting only objects
  // containing specific `key:value` pairs.
  _.where = function(obj, attrs) {
    return _.filter(obj, _.matcher(attrs));
  };

  // Convenience version of a common use case of `find`: getting the first object
  // containing specific `key:value` pairs.
  _.findWhere = function(obj, attrs) {
    return _.find(obj, _.matcher(attrs));
  };

  // Return the maximum element (or element-based computation).
  _.max = function(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).
  _.min = function(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;
  };

  // Shuffle a collection.
  _.shuffle = function(obj) {
    return _.sample(obj, Infinity);
  };

  // Sample **n** random values from a collection using the modern version of the
  // [Fisher-Yates shuffle](http://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`.
  _.sample = function(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);
  };

  // Sort the object's values by a criterion produced by an iteratee.
  _.sortBy = function(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.
  var group = function(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.
  _.groupBy = group(function(result, value, key) {
    if (has(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.
  _.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.
  _.countBy = group(function(result, value, key) {
    if (has(result, key)) result[key]++; else result[key] = 1;
  });

  var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;
  // Safely create a real, live array from anything iterable.
  _.toArray = function(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 an object.
  _.size = function(obj) {
    if (obj == null) return 0;
    return isArrayLike(obj) ? obj.length : _.keys(obj).length;
  };

  // Split a collection into two arrays: one whose elements all satisfy the given
  // predicate, and one whose elements all do not satisfy the predicate.
  _.partition = group(function(result, value, pass) {
    result[pass ? 0 : 1].push(value);
  }, true);

  // Array Functions
  // ---------------

  // Get the first element of an array. Passing **n** will return the first N
  // values in the array. Aliased as `head` and `take`. The **guard** check
  // allows it to work with `_.map`.
  _.first = _.head = _.take = function(array, n, guard) {
    if (array == null || array.length < 1) return n == null ? void 0 : [];
    if (n == null || guard) return array[0];
    return _.initial(array, array.length - n);
  };

  // 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.
  _.initial = function(array, n, guard) {
    return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
  };

  // Get the last element of an array. Passing **n** will return the last N
  // values in the array.
  _.last = function(array, n, guard) {
    if (array == null || array.length < 1) return n == null ? void 0 : [];
    if (n == null || guard) return array[array.length - 1];
    return _.rest(array, Math.max(0, array.length - n));
  };

  // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
  // Especially useful on the arguments object. Passing an **n** will return
  // the rest N values in the array.
  _.rest = _.tail = _.drop = function(array, n, guard) {
    return slice.call(array, n == null || guard ? 1 : n);
  };

  // Trim out all falsy values from an array.
  _.compact = function(array) {
    return _.filter(array, Boolean);
  };

  // Internal implementation of a recursive `flatten` function.
  var flatten = function(input, shallow, strict, output) {
    output = output || [];
    var idx = output.length;
    for (var i = 0, length = getLength(input); i < length; i++) {
      var value = input[i];
      if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
        // Flatten current level of array or arguments object.
        if (shallow) {
          var j = 0, len = value.length;
          while (j < len) output[idx++] = value[j++];
        } else {
          flatten(value, shallow, strict, output);
          idx = output.length;
        }
      } else if (!strict) {
        output[idx++] = value;
      }
    }
    return output;
  };

  // Flatten out an array, either recursively (by default), or just one level.
  _.flatten = function(array, shallow) {
    return flatten(array, shallow, false);
  };

  // Return a version of the array that does not contain the specified value(s).
  _.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.
  // Aliased as `unique`.
  _.uniq = _.unique = function(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.
  _.union = restArguments(function(arrays) {
    return _.uniq(flatten(arrays, true, true));
  });

  // Produce an array that contains every item shared between all the
  // passed-in arrays.
  _.intersection = function(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;
  };

  // Take the difference between one array and a number of other arrays.
  // Only the elements present in just the first array will remain.
  _.difference = restArguments(function(array, rest) {
    rest = flatten(rest, true, true);
    return _.filter(array, function(value){
      return !_.contains(rest, value);
    });
  });

  // Complement of _.zip. Unzip accepts an array of arrays and groups
  // each array's elements on shared indices.
  _.unzip = function(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.
  _.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.
  _.object = function(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;
  };

  // Generator function to create the findIndex and findLastIndex functions.
  var createPredicateIndexFinder = function(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 predicate test.
  _.findIndex = createPredicateIndexFinder(1);
  _.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.
  _.sortedIndex = function(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;
  };

  // Generator function to create the indexOf and lastIndexOf functions.
  var createIndexFinder = function(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);
        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.
  _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
  _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);

  // Generate an integer Array containing an arithmetic progression. A port of
  // the native Python `range()` function. See
  // [the Python documentation](http://docs.python.org/library/functions.html#range).
  _.range = function(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.
  _.chunk = function(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;
  };

  // Function (ahem) Functions
  // ------------------

  // Determines whether to execute a function as a constructor
  // or a normal function with the provided arguments.
  var executeBound = function(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;
  };

  // Create a function bound to a given object (assigning `this`, and arguments,
  // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
  // available.
  _.bind = restArguments(function(func, context, args) {
    if (!_.isFunction(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;
  });

  // 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.
  _.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 = _;

  // 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.
  _.bindAll = restArguments(function(obj, keys) {
    keys = flatten(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);
    }
  });

  // Memoize an expensive function by storing its results.
  _.memoize = function(func, hasher) {
    var memoize = function(key) {
      var cache = memoize.cache;
      var address = '' + (hasher ? hasher.apply(this, arguments) : key);
      if (!has(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.
  _.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.
  _.defer = _.partial(_.delay, _, 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.
  _.throttle = function(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;
  };

  // Returns a function, that, as long as it continues to be invoked, will not
  // be triggered. The function will be called after it stops being called for
  // N milliseconds. If `immediate` is passed, trigger the function on the
  // leading edge, instead of the trailing.
  _.debounce = function(func, wait, immediate) {
    var timeout, result;

    var later = function(context, args) {
      timeout = null;
      if (args) result = func.apply(context, args);
    };

    var debounced = restArguments(function(args) {
      if (timeout) clearTimeout(timeout);
      if (immediate) {
        var callNow = !timeout;
        timeout = setTimeout(later, wait);
        if (callNow) result = func.apply(this, args);
      } else {
        timeout = _.delay(later, wait, this, args);
      }

      return result;
    });

    debounced.cancel = function() {
      clearTimeout(timeout);
      timeout = 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.
  _.wrap = function(func, wrapper) {
    return _.partial(wrapper, func);
  };

  // Returns a negated version of the passed-in predicate.
  _.negate = function(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.
  _.compose = function() {
    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.
  _.after = function(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.
  _.before = function(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.
  _.once = _.partial(_.before, 2);

  _.restArguments = restArguments;

  // Object Functions
  // ----------------

  // 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'];

  var collectNonEnumProps = function(obj, keys) {
    var nonEnumIdx = nonEnumerableProps.length;
    var constructor = obj.constructor;
    var proto = _.isFunction(constructor) && constructor.prototype || ObjProto;

    // Constructor is a special case.
    var prop = 'constructor';
    if (has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);

    while (nonEnumIdx--) {
      prop = nonEnumerableProps[nonEnumIdx];
      if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
        keys.push(prop);
      }
    }
  };

  // Retrieve the names of an object's own properties.
  // Delegates to **ECMAScript 5**'s native `Object.keys`.
  _.keys = function(obj) {
    if (!_.isObject(obj)) return [];
    if (nativeKeys) return nativeKeys(obj);
    var keys = [];
    for (var key in obj) if (has(obj, key)) keys.push(key);
    // Ahem, IE < 9.
    if (hasEnumBug) collectNonEnumProps(obj, keys);
    return keys;
  };

  // Retrieve all the property names of an object.
  _.allKeys = function(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;
  };

  // Retrieve the values of an object's properties.
  _.values = function(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;
  };

  // Returns the results of applying the iteratee to each element of the object.
  // In contrast to _.map it returns an object.
  _.mapObject = function(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;
  };

  // Convert an object into a list of `[key, value]` pairs.
  // The opposite of _.object.
  _.pairs = function(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.
  _.invert = function(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.
  // Aliased as `methods`.
  _.functions = _.methods = function(obj) {
    var names = [];
    for (var key in obj) {
      if (_.isFunction(obj[key])) names.push(key);
    }
    return names.sort();
  };

  // An internal function for creating assigner functions.
  var createAssigner = function(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).
  _.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)
  _.extendOwn = _.assign = createAssigner(_.keys);

  // Returns the first key on an object that passes a predicate test.
  _.findKey = function(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 pick helper function to determine if `obj` has key `key`.
  var keyInObj = function(value, key, obj) {
    return key in obj;
  };

  // Return a copy of the object only containing the whitelisted properties.
  _.pick = restArguments(function(obj, keys) {
    var result = {}, iteratee = keys[0];
    if (obj == null) return result;
    if (_.isFunction(iteratee)) {
      if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]);
      keys = _.allKeys(obj);
    } else {
      iteratee = keyInObj;
      keys = flatten(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 blacklisted properties.
  _.omit = restArguments(function(obj, keys) {
    var iteratee = keys[0], context;
    if (_.isFunction(iteratee)) {
      iteratee = _.negate(iteratee);
      if (keys.length > 1) context = keys[1];
    } else {
      keys = _.map(flatten(keys, false, false), String);
      iteratee = function(value, key) {
        return !_.contains(keys, key);
      };
    }
    return _.pick(obj, iteratee, context);
  });

  // Fill in a given object with default properties.
  _.defaults = createAssigner(_.allKeys, true);

  // Creates an object that inherits from the given prototype object.
  // If additional properties are provided then they will be added to the
  // created object.
  _.create = function(prototype, props) {
    var result = baseCreate(prototype);
    if (props) _.extendOwn(result, props);
    return result;
  };

  // Create a (shallow-cloned) duplicate of an object.
  _.clone = function(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.
  _.tap = function(obj, interceptor) {
    interceptor(obj);
    return obj;
  };

  // Returns whether an object has a given set of `key:value` pairs.
  _.isMatch = function(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;
  };


  // Internal recursive comparison function for `isEqual`.
  var eq, deepEq;
  eq = function(a, b, aStack, bStack) {
    // Identical objects are equal. `0 === -0`, but they aren't identical.
    // See the [Harmony `egal` proposal](http://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`.
  deepEq = function(a, b, aStack, bStack) {
    // Unwrap any wrapped objects.
    if (a instanceof _) a = a._wrapped;
    if (b instanceof _) b = b._wrapped;
    // Compare `[[Class]]` names.
    var className = toString.call(a);
    if (className !== toString.call(b)) return false;
    switch (className) {
      // Strings, numbers, regular expressions, dates, and booleans 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);
    }

    var areArrays = className === '[object Array]';
    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(aCtor) && aCtor instanceof aCtor &&
                               _.isFunction(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(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.
  _.isEqual = function(a, b) {
    return eq(a, b);
  };

  // Is a given array, string, or object empty?
  // An "empty" object has no enumerable own-properties.
  _.isEmpty = function(obj) {
    if (obj == null) return true;
    if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
    return _.keys(obj).length === 0;
  };

  // Is a given value a DOM element?
  _.isElement = function(obj) {
    return !!(obj && obj.nodeType === 1);
  };

  // Is a given value an array?
  // Delegates to ECMA5's native Array.isArray
  _.isArray = nativeIsArray || function(obj) {
    return toString.call(obj) === '[object Array]';
  };

  // Is a given variable an object?
  _.isObject = function(obj) {
    var type = typeof obj;
    return type === 'function' || type === 'object' && !!obj;
  };

  // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError, isMap, isWeakMap, isSet, isWeakSet.
  _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error', 'Symbol', 'Map', 'WeakMap', 'Set', 'WeakSet'], function(name) {
    _['is' + name] = function(obj) {
      return toString.call(obj) === '[object ' + name + ']';
    };
  });

  // Define a fallback version of the method in browsers (ahem, IE < 9), where
  // there isn't any inspectable "Arguments" type.
  if (!_.isArguments(arguments)) {
    _.isArguments = function(obj) {
      return has(obj, 'callee');
    };
  }

  // 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 (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') {
    _.isFunction = function(obj) {
      return typeof obj == 'function' || false;
    };
  }

  // Is a given object a finite number?
  _.isFinite = function(obj) {
    return !_.isSymbol(obj) && isFinite(obj) && !isNaN(parseFloat(obj));
  };

  // Is the given value `NaN`?
  _.isNaN = function(obj) {
    return _.isNumber(obj) && isNaN(obj);
  };

  // Is a given value a boolean?
  _.isBoolean = function(obj) {
    return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
  };

  // Is a given value equal to null?
  _.isNull = function(obj) {
    return obj === null;
  };

  // Is a given variable undefined?
  _.isUndefined = function(obj) {
    return obj === void 0;
  };

  // Shortcut function for checking if an object has a given property directly
  // on itself (in other words, not on a prototype).
  _.has = function(obj, path) {
    if (!_.isArray(path)) {
      return has(obj, path);
    }
    var length = path.length;
    for (var i = 0; i < length; i++) {
      var key = path[i];
      if (obj == null || !hasOwnProperty.call(obj, key)) {
        return false;
      }
      obj = obj[key];
    }
    return !!length;
  };

  // Utility Functions
  // -----------------

  // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
  // previous owner. Returns a reference to the Underscore object.
  _.noConflict = function() {
    root._ = previousUnderscore;
    return this;
  };

  // Keep the identity function around for default iteratees.
  _.identity = function(value) {
    return value;
  };

  // Predicate-generating functions. Often useful outside of Underscore.
  _.constant = function(value) {
    return function() {
      return value;
    };
  };

  _.noop = function(){};

  // 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 indexes.
  _.property = function(path) {
    if (!_.isArray(path)) {
      return shallowProperty(path);
    }
    return function(obj) {
      return deepGet(obj, path);
    };
  };

  // Generates a function for a given object that returns a given property.
  _.propertyOf = function(obj) {
    if (obj == null) {
      return function(){};
    }
    return function(path) {
      return !_.isArray(path) ? obj[path] : deepGet(obj, path);
    };
  };

  // Returns a predicate for checking whether an object has a given set of
  // `key:value` pairs.
  _.matcher = _.matches = function(attrs) {
    attrs = _.extendOwn({}, attrs);
    return function(obj) {
      return _.isMatch(obj, attrs);
    };
  };

  // Run a function **n** times.
  _.times = function(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).
  _.random = function(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.
  _.now = Date.now || function() {
    return new Date().getTime();
  };

  // List of HTML entities for escaping.
  var escapeMap = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#x27;',
    '`': '&#x60;'
  };
  var unescapeMap = _.invert(escapeMap);

  // Functions for escaping and unescaping strings to/from HTML interpolation.
  var createEscaper = function(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;
    };
  };
  _.escape = createEscaper(escapeMap);
  _.unescape = createEscaper(unescapeMap);

  // 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.
  _.result = function(obj, path, fallback) {
    if (!_.isArray(path)) path = [path];
    var length = path.length;
    if (!length) {
      return _.isFunction(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(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;
  _.uniqueId = function(prefix) {
    var id = ++idCounter + '';
    return prefix ? prefix + id : id;
  };

  // By default, Underscore uses ERB-style template delimiters, change the
  // following template settings to use alternative delimiters.
  _.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;

  var escapeChar = function(match) {
    return '\\' + escapes[match];
  };

  // 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.
  _.template = function(text, settings, oldSettings) {
    if (!settings && oldSettings) settings = oldSettings;
    settings = _.defaults({}, settings, _.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";

    // If a variable is not specified, place data values in local scope.
    if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';

    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(settings.variable || 'obj', '_', source);
    } catch (e) {
      e.source = source;
      throw e;
    }

    var template = function(data) {
      return render.call(this, data, _);
    };

    // Provide the compiled source as a convenience for precompilation.
    var argument = settings.variable || 'obj';
    template.source = 'function(' + argument + '){\n' + source + '}';

    return template;
  };

  // Add a "chain" function. Start chaining a wrapped Underscore object.
  _.chain = function(obj) {
    var instance = _(obj);
    instance._chain = true;
    return instance;
  };

  // OOP
  // ---------------
  // 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 the
  // underscore functions. Wrapped objects may be chained.

  // Helper function to continue chaining intermediate results.
  var chainResult = function(instance, obj) {
    return instance._chain ? _(obj).chain() : obj;
  };

  // Add your own custom functions to the Underscore object.
  _.mixin = function(obj) {
    _.each(_.functions(obj), function(name) {
      var func = _[name] = obj[name];
      _.prototype[name] = function() {
        var args = [this._wrapped];
        push.apply(args, arguments);
        return chainResult(this, func.apply(_, args));
      };
    });
    return _;
  };

  // Add all of the Underscore functions to the wrapper object.
  _.mixin(_);

  // Add all mutator Array functions to the wrapper.
  _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
    var method = ArrayProto[name];
    _.prototype[name] = function() {
      var obj = this._wrapped;
      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];
    _.prototype[name] = function() {
      return chainResult(this, method.apply(this._wrapped, arguments));
    };
  });

  // Extracts the result from a wrapped and chained object.
  _.prototype.value = function() {
    return this._wrapped;
  };

  // Provide unwrapping proxy for some methods used in engine operations
  // such as arithmetic and JSON stringification.
  _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;

  _.prototype.toString = function() {
    return String(this._wrapped);
  };

  // AMD registration happens at the end for compatibility with AMD loaders
  // that may not enforce next-turn semantics on modules. Even though general
  // practice for AMD registration is to be anonymous, underscore registers
  // as a named module because, like jQuery, it is a base library that is
  // popular enough to be bundled in a third party lib, but not be part of
  // an AMD load request. Those cases could generate an error when an
  // anonymous define() is called outside of a loader request.
  if (true) {
    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() {
      return _;
    }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  }
}());

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "yLpj"), __webpack_require__(/*! ./../webpack/buildin/module.js */ "YuTi")(module)))

/***/ }),

/***/ "F3q3":
/*!**********************************************************************!*\
  !*** ./node_modules/draft-js-import-element/lib/stateFromElement.js ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

exports.stateFromElement = stateFromElement;

var _replaceTextWithMeta3 = __webpack_require__(/*! ./lib/replaceTextWithMeta */ "v6Iv");

var _replaceTextWithMeta4 = _interopRequireDefault(_replaceTextWithMeta3);

var _draftJs = __webpack_require__(/*! draft-js */ "v83y");

var _immutable = __webpack_require__(/*! immutable */ "JPcv");

var _draftJsUtils = __webpack_require__(/*! draft-js-utils */ "24WU");

var _syntheticDom = __webpack_require__(/*! synthetic-dom */ "4X8Z");

var _Constants = __webpack_require__(/*! ./lib/Constants */ "buUt");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

// A ParsedBlock has two purposes:
//   1) to keep data about the block (textFragments, type)
//   2) to act as some context for storing parser state as we parse its contents
var DATA_URL = /^data:/i;
var NO_STYLE = (0, _immutable.OrderedSet)();
var NO_ENTITY = null;

var EMPTY_BLOCK = new _draftJs.ContentBlock({
  key: (0, _draftJs.genKey)(),
  text: '',
  type: _draftJsUtils.BLOCK_TYPE.UNSTYLED,
  characterList: (0, _immutable.List)(),
  depth: 0
});

var LINE_BREAKS = /(\r\n|\r|\n)/g;
// We use `\r` because that character is always stripped from source (normalized
// to `\n`), so it's safe to assume it will only appear in the text content when
// we put it there as a placeholder.
var SOFT_BREAK_PLACEHOLDER = '\r';
var ZERO_WIDTH_SPACE = '\u200B';
var DATA_ATTRIBUTE = /^data-([a-z0-9-]+)$/;

// Map element attributes to entity data.
var ELEM_ATTR_MAP = {
  a: { href: 'url', rel: 'rel', target: 'target', title: 'title' },
  img: { src: 'src', alt: 'alt' }
};

var getEntityData = function getEntityData(tagName, element) {
  var data = {};
  if (ELEM_ATTR_MAP.hasOwnProperty(tagName)) {
    var attrMap = ELEM_ATTR_MAP[tagName];
    for (var i = 0; i < element.attributes.length; i++) {
      var _element$attributes$i = element.attributes[i],
          name = _element$attributes$i.name,
          value = _element$attributes$i.value;

      if (typeof value === 'string') {
        var strVal = value;
        if (attrMap.hasOwnProperty(name)) {
          var newName = attrMap[name];
          data[newName] = strVal;
        } else if (DATA_ATTRIBUTE.test(name)) {
          data[name] = strVal;
        }
      }
    }
  }
  return data;
};

// Functions to create entities from elements.
var ElementToEntity = {
  a: function a(generator, tagName, element) {
    var data = getEntityData(tagName, element);
    // Don't add `<a>` elements with invalid href.
    if (isAllowedHref(data.url)) {
      return generator.createEntity(_draftJsUtils.ENTITY_TYPE.LINK, data);
    }
  },
  img: function img(generator, tagName, element) {
    var data = getEntityData(tagName, element);
    // Don't add `<img>` elements with no src.
    if (data.src != null) {
      return generator.createEntity(_draftJsUtils.ENTITY_TYPE.IMAGE, data);
    }
  }
};

var ContentGenerator = function () {
  function ContentGenerator() {
    var _this = this;

    var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

    _classCallCheck(this, ContentGenerator);

    this.inlineCreators = {
      Style: function Style(style) {
        return { type: 'STYLE', style: style };
      },
      Entity: function Entity(type, data) {
        var mutability = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'MUTABLE';
        return {
          type: 'ENTITY',
          entityKey: _this.createEntity(type, toStringMap(data), mutability)
        };
      }
    };

    this.options = options;
    this.contentStateForEntities = _draftJs.ContentState.createFromBlockArray([]);
    // This represents the hierarchy as we traverse nested elements; for
    // example [body, ul, li] where we must know li's parent type (ul or ol).
    this.blockStack = [];
    // This is a linear list of blocks that will form the output; for example
    // [p, li, li, blockquote].
    this.blockList = [];
    this.depth = 0;
  }
  // This will be passed to the customInlineFn to allow it
  // to return a Style() or Entity().


  _createClass(ContentGenerator, [{
    key: 'process',
    value: function process(element) {
      this.processBlockElement(element);
      var contentBlocks = [];
      this.blockList.forEach(function (block) {
        var _concatFragments = concatFragments(block.textFragments),
            text = _concatFragments.text,
            characterMeta = _concatFragments.characterMeta;

        var includeEmptyBlock = false;
        // If the block contains only a soft break then don't discard the block,
        // but discard the soft break.
        if (text === SOFT_BREAK_PLACEHOLDER) {
          includeEmptyBlock = true;
          text = '';
        }
        if (block.tagName === 'pre') {
          var _trimLeadingNewline = trimLeadingNewline(text, characterMeta);

          text = _trimLeadingNewline.text;
          characterMeta = _trimLeadingNewline.characterMeta;
        } else {
          var _collapseWhiteSpace = collapseWhiteSpace(text, characterMeta);

          text = _collapseWhiteSpace.text;
          characterMeta = _collapseWhiteSpace.characterMeta;
        }
        // Previously we were using a placeholder for soft breaks. Now that we
        // have collapsed whitespace we can change it back to normal line breaks.
        text = text.split(SOFT_BREAK_PLACEHOLDER).join('\n');
        // Discard empty blocks (unless otherwise specified).
        if (text.length || includeEmptyBlock) {
          contentBlocks.push(new _draftJs.ContentBlock({
            key: (0, _draftJs.genKey)(),
            text: text,
            type: block.type,
            characterList: characterMeta.toList(),
            depth: block.depth,
            data: block.data ? (0, _immutable.Map)(block.data) : (0, _immutable.Map)()
          }));
        }
      });
      if (!contentBlocks.length) {
        contentBlocks = [EMPTY_BLOCK];
      }
      return _draftJs.ContentState.createFromBlockArray(contentBlocks, this.contentStateForEntities.getEntityMap());
    }
  }, {
    key: 'getBlockTypeFromTagName',
    value: function getBlockTypeFromTagName(tagName) {
      var blockTypes = this.options.blockTypes;

      if (blockTypes && blockTypes[tagName]) {
        return blockTypes[tagName];
      }
      switch (tagName) {
        case 'li':
          {
            var parent = this.blockStack.slice(-1)[0];
            return parent.tagName === 'ol' ? _draftJsUtils.BLOCK_TYPE.ORDERED_LIST_ITEM : _draftJsUtils.BLOCK_TYPE.UNORDERED_LIST_ITEM;
          }
        case 'blockquote':
          {
            return _draftJsUtils.BLOCK_TYPE.BLOCKQUOTE;
          }
        case 'h1':
          {
            return _draftJsUtils.BLOCK_TYPE.HEADER_ONE;
          }
        case 'h2':
          {
            return _draftJsUtils.BLOCK_TYPE.HEADER_TWO;
          }
        case 'h3':
          {
            return _draftJsUtils.BLOCK_TYPE.HEADER_THREE;
          }
        case 'h4':
          {
            return _draftJsUtils.BLOCK_TYPE.HEADER_FOUR;
          }
        case 'h5':
          {
            return _draftJsUtils.BLOCK_TYPE.HEADER_FIVE;
          }
        case 'h6':
          {
            return _draftJsUtils.BLOCK_TYPE.HEADER_SIX;
          }
        case 'pre':
          {
            return _draftJsUtils.BLOCK_TYPE.CODE;
          }
        case 'figure':
          {
            return _draftJsUtils.BLOCK_TYPE.ATOMIC;
          }
        default:
          {
            return _draftJsUtils.BLOCK_TYPE.UNSTYLED;
          }
      }
    }
  }, {
    key: 'processBlockElement',
    value: function processBlockElement(element) {
      if (!element) {
        return;
      }
      var customBlockFn = this.options.customBlockFn;

      var tagName = element.nodeName.toLowerCase();
      var type = void 0;
      var data = void 0;
      if (customBlockFn) {
        var customBlock = customBlockFn(element);
        if (customBlock != null) {
          type = customBlock.type;
          data = customBlock.data;
        }
      }
      var isCustomType = true;
      if (type == null) {
        isCustomType = false;
        type = this.getBlockTypeFromTagName(tagName);
      }
      if (type === _draftJsUtils.BLOCK_TYPE.CODE) {
        var language = element.getAttribute('data-language');
        if (language) {
          data = _extends({}, data, { language: language });
        }
      }
      var hasDepth = canHaveDepth(type);
      var allowRender = !_Constants.SPECIAL_ELEMENTS.hasOwnProperty(tagName);
      if (!isCustomType && !hasSemanticMeaning(type)) {
        var parent = this.blockStack.slice(-1)[0];
        if (parent) {
          type = parent.type;
        }
      }
      var block = {
        tagName: tagName,
        textFragments: [],
        type: type,
        styleStack: [NO_STYLE],
        entityStack: [NO_ENTITY],
        depth: hasDepth ? this.depth : 0,
        data: data
      };
      if (allowRender) {
        this.blockList.push(block);
        if (hasDepth) {
          this.depth += 1;
        }
      }
      this.blockStack.push(block);
      if (element.childNodes != null) {
        Array.from(element.childNodes).forEach(this.processNode, this);
      }
      this.blockStack.pop();
      if (allowRender && hasDepth) {
        this.depth -= 1;
      }
    }
  }, {
    key: 'processInlineElement',
    value: function processInlineElement(element) {
      var tagName = element.nodeName.toLowerCase();
      if (tagName === 'br') {
        this.processText(SOFT_BREAK_PLACEHOLDER);
        return;
      }
      var block = this.blockStack.slice(-1)[0];
      var style = block.styleStack.slice(-1)[0];
      var entityKey = block.entityStack.slice(-1)[0];
      var customInlineFn = this.options.customInlineFn;

      var customInline = customInlineFn ? customInlineFn(element, this.inlineCreators) : null;
      if (customInline != null) {
        switch (customInline.type) {
          case 'STYLE':
            {
              style = style.add(customInline.style);
              break;
            }
          case 'ENTITY':
            {
              entityKey = customInline.entityKey;
              break;
            }
        }
      } else {
        style = addStyleFromTagName(style, tagName, this.options.elementStyles);
        if (ElementToEntity.hasOwnProperty(tagName)) {
          // If the to-entity function returns nothing, use the existing entity.
          entityKey = ElementToEntity[tagName](this, tagName, element) || entityKey;
        }
      }
      block.styleStack.push(style);
      block.entityStack.push(entityKey);
      if (element.childNodes != null) {
        Array.from(element.childNodes).forEach(this.processNode, this);
      }
      if (_Constants.SELF_CLOSING_ELEMENTS.hasOwnProperty(tagName)) {
        this.processText('\xA0');
      }
      block.entityStack.pop();
      block.styleStack.pop();
    }
  }, {
    key: 'processTextNode',
    value: function processTextNode(node) {
      var text = node.nodeValue;
      // This is important because we will use \r as a placeholder for a soft break.
      text = text.replace(LINE_BREAKS, '\n');
      // Replace zero-width space (we use it as a placeholder in markdown) with a
      // soft break.
      // TODO: The import-markdown package should correctly turn breaks into <br>
      // elements so we don't need to include this hack.
      text = text.split(ZERO_WIDTH_SPACE).join(SOFT_BREAK_PLACEHOLDER);
      this.processText(text);
    }
  }, {
    key: 'processText',
    value: function processText(text) {
      var block = this.blockStack.slice(-1)[0];
      var style = block.styleStack.slice(-1)[0];
      var entity = block.entityStack.slice(-1)[0];
      var charMetadata = _draftJs.CharacterMetadata.create({
        style: style,
        entity: entity
      });
      var seq = (0, _immutable.Repeat)(charMetadata, text.length);
      block.textFragments.push({
        text: text,
        characterMeta: seq
      });
    }
  }, {
    key: 'processNode',
    value: function processNode(node) {
      if (node.nodeType === _syntheticDom.NODE_TYPE_ELEMENT) {
        // $FlowIssue
        var _element = node;
        var _tagName = _element.nodeName.toLowerCase();
        if (_Constants.INLINE_ELEMENTS.hasOwnProperty(_tagName)) {
          this.processInlineElement(_element);
        } else {
          this.processBlockElement(_element);
        }
      } else if (node.nodeType === _syntheticDom.NODE_TYPE_TEXT) {
        this.processTextNode(node);
      }
    }
  }, {
    key: 'createEntity',
    value: function createEntity(type, data) {
      var mutability = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'MUTABLE';

      this.contentStateForEntities = this.contentStateForEntities.createEntity(type, mutability, data);
      return this.contentStateForEntities.getLastCreatedEntityKey();
    }
  }]);

  return ContentGenerator;
}();

function trimLeadingNewline(text, characterMeta) {
  if (text.charAt(0) === '\n') {
    text = text.slice(1);
    characterMeta = characterMeta.slice(1);
  }
  return { text: text, characterMeta: characterMeta };
}

function trimLeadingSpace(text, characterMeta) {
  while (text.charAt(0) === ' ') {
    text = text.slice(1);
    characterMeta = characterMeta.slice(1);
  }
  return { text: text, characterMeta: characterMeta };
}

function trimTrailingSpace(text, characterMeta) {
  while (text.slice(-1) === ' ') {
    text = text.slice(0, -1);
    characterMeta = characterMeta.slice(0, -1);
  }
  return { text: text, characterMeta: characterMeta };
}

function collapseWhiteSpace(text, characterMeta) {
  text = text.replace(/[ \t\n]/g, ' ');

  var _trimLeadingSpace = trimLeadingSpace(text, characterMeta);

  text = _trimLeadingSpace.text;
  characterMeta = _trimLeadingSpace.characterMeta;

  var _trimTrailingSpace = trimTrailingSpace(text, characterMeta);

  text = _trimTrailingSpace.text;
  characterMeta = _trimTrailingSpace.characterMeta;

  var i = text.length;
  while (i--) {
    if (text.charAt(i) === ' ' && text.charAt(i - 1) === ' ') {
      text = text.slice(0, i) + text.slice(i + 1);
      characterMeta = characterMeta.slice(0, i).concat(characterMeta.slice(i + 1));
    }
  }
  // There could still be one space on either side of a softbreak.

  var _replaceTextWithMeta = (0, _replaceTextWithMeta4.default)({ text: text, characterMeta: characterMeta }, SOFT_BREAK_PLACEHOLDER + ' ', SOFT_BREAK_PLACEHOLDER);

  text = _replaceTextWithMeta.text;
  characterMeta = _replaceTextWithMeta.characterMeta;

  var _replaceTextWithMeta2 = (0, _replaceTextWithMeta4.default)({ text: text, characterMeta: characterMeta }, ' ' + SOFT_BREAK_PLACEHOLDER, SOFT_BREAK_PLACEHOLDER);

  text = _replaceTextWithMeta2.text;
  characterMeta = _replaceTextWithMeta2.characterMeta;

  return { text: text, characterMeta: characterMeta };
}

function canHaveDepth(blockType) {
  switch (blockType) {
    case _draftJsUtils.BLOCK_TYPE.UNORDERED_LIST_ITEM:
    case _draftJsUtils.BLOCK_TYPE.ORDERED_LIST_ITEM:
      {
        return true;
      }
    default:
      {
        return false;
      }
  }
}

function concatFragments(fragments) {
  var text = '';
  var characterMeta = (0, _immutable.Seq)();
  fragments.forEach(function (textFragment) {
    text = text + textFragment.text;
    characterMeta = characterMeta.concat(textFragment.characterMeta);
  });
  return { text: text, characterMeta: characterMeta };
}

function addStyleFromTagName(styleSet, tagName, elementStyles) {
  switch (tagName) {
    case 'b':
    case 'strong':
      {
        return styleSet.add(_draftJsUtils.INLINE_STYLE.BOLD);
      }
    case 'i':
    case 'em':
      {
        return styleSet.add(_draftJsUtils.INLINE_STYLE.ITALIC);
      }
    case 'u':
    case 'ins':
      {
        return styleSet.add(_draftJsUtils.INLINE_STYLE.UNDERLINE);
      }
    case 'code':
      {
        return styleSet.add(_draftJsUtils.INLINE_STYLE.CODE);
      }
    case 's':
    case 'del':
      {
        return styleSet.add(_draftJsUtils.INLINE_STYLE.STRIKETHROUGH);
      }
    default:
      {
        // Allow custom styles to be provided.
        if (elementStyles && elementStyles[tagName]) {
          return styleSet.add(elementStyles[tagName]);
        }

        return styleSet;
      }
  }
}

function hasSemanticMeaning(blockType) {
  return blockType !== _draftJsUtils.BLOCK_TYPE.UNSTYLED;
}

function toStringMap(input) {
  var result = {};
  if (input !== null && (typeof input === 'undefined' ? 'undefined' : _typeof(input)) === 'object' && !Array.isArray(input)) {
    var obj = input;
    var _iteratorNormalCompletion = true;
    var _didIteratorError = false;
    var _iteratorError = undefined;

    try {
      for (var _iterator = Object.keys(obj)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
        var _key = _step.value;

        var value = obj[_key];
        if (typeof value === 'string') {
          result[_key] = value;
        }
      }
    } catch (err) {
      _didIteratorError = true;
      _iteratorError = err;
    } finally {
      try {
        if (!_iteratorNormalCompletion && _iterator.return) {
          _iterator.return();
        }
      } finally {
        if (_didIteratorError) {
          throw _iteratorError;
        }
      }
    }
  }
  return result;
}

function isAllowedHref(input) {
  if (input == null || input.match(DATA_URL)) {
    return false;
  } else {
    return true;
  }
}

function stateFromElement(element, options) {
  return new ContentGenerator(options).process(element);
}

exports.default = stateFromElement;

/***/ }),

/***/ "F43Q":
/*!*************************************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/text_editors/RichText/decoratorStrategies.js ***!
  \*************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.findLinkEntities = undefined;

var _draftJs = __webpack_require__(/*! draft-js */ "v83y");

var characterIsLinkEntity = function characterIsLinkEntity(character) {
  var entityKey = character.getEntity();

  if (entityKey === null) {
    return false;
  }

  var entity = _draftJs.Entity.get(entityKey);

  return entity.getType() === 'LINK';
}; /*
    * A decoratorStrategy is used by `draft-js` to determine how to render
    * content beyond inline styles. We use them to render LINK entities.
    *
    * See https://facebook.github.io/draft-js/docs/advanced-topics-decorators.html#content
    * and
    * https://facebook.github.io/draft-js/docs/advanced-topics-entities.html#content
    */
var findLinkEntities = exports.findLinkEntities = function findLinkEntities(contentBlock, callback) {
  contentBlock.findEntityRanges(characterIsLinkEntity, callback);
};
//# sourceMappingURL=decoratorStrategies.js.map

/***/ }),

/***/ "FCiD":
/*!**********************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/manager.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const builder_1 = __webpack_require__(/*! ./builder */ "0LMu");
const nbconvert_1 = __webpack_require__(/*! ./nbconvert */ "hBxh");
const contents_1 = __webpack_require__(/*! ./contents */ "/Hsf");
const session_1 = __webpack_require__(/*! ./session */ "Gm2Q");
const setting_1 = __webpack_require__(/*! ./setting */ "ai3f");
const terminal_1 = __webpack_require__(/*! ./terminal */ "JSoe");
const serverconnection_1 = __webpack_require__(/*! ./serverconnection */ "ZWV2");
const workspace_1 = __webpack_require__(/*! ./workspace */ "yjZJ");
/**
 * A Jupyter services manager.
 */
class ServiceManager {
    /**
     * Construct a new services provider.
     */
    constructor(options = {}) {
        this._isDisposed = false;
        this._specsChanged = new signaling_1.Signal(this);
        this._isReady = false;
        this.serverSettings =
            options.serverSettings || serverconnection_1.ServerConnection.makeSettings();
        this.contents = new contents_1.ContentsManager(options);
        this.sessions = new session_1.SessionManager(options);
        this.settings = new setting_1.SettingManager(options);
        this.terminals = new terminal_1.TerminalManager(options);
        this.builder = new builder_1.BuildManager(options);
        this.workspaces = new workspace_1.WorkspaceManager(options);
        this.nbconvert = new nbconvert_1.NbConvertManager(options);
        this.sessions.specsChanged.connect((sender, specs) => {
            this._specsChanged.emit(specs);
        });
        this._readyPromise = this.sessions.ready.then(() => {
            if (this.terminals.isAvailable()) {
                return this.terminals.ready;
            }
        });
        this._readyPromise.then(() => {
            this._isReady = true;
        });
    }
    /**
     * A signal emitted when the kernel specs change.
     */
    get specsChanged() {
        return this._specsChanged;
    }
    /**
     * Test whether the service manager is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources used by the manager.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        signaling_1.Signal.clearData(this);
        this.contents.dispose();
        this.sessions.dispose();
        this.terminals.dispose();
    }
    /**
     * The kernel spec models.
     */
    get specs() {
        return this.sessions.specs;
    }
    /**
     * Test whether the manager is ready.
     */
    get isReady() {
        return this._isReady;
    }
    /**
     * A promise that fulfills when the manager is ready.
     */
    get ready() {
        return this._readyPromise;
    }
}
exports.ServiceManager = ServiceManager;


/***/ }),

/***/ "FExI":
/*!******************************************************!*\
  !*** ./node_modules/mdi-react/MessageOutlineIcon.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var MessageOutlineIcon = function MessageOutlineIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M20,2H4C2.9,2 2,2.9 2,4V22L6,18H20C21.1,18 22,17.1 22,16V4C22,2.9 21.1,2 20,2M20,16H6L4,18V4H20' })
  );
};

module.exports = MessageOutlineIcon;


/***/ }),

/***/ "FMM9":
/*!*****************************************************!*\
  !*** ./node_modules/base16/lib/threezerotwofour.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'threezerotwofour',
  author: 'jan t. sott (http://github.com/idleberg)',
  base00: '#090300',
  base01: '#3a3432',
  base02: '#4a4543',
  base03: '#5c5855',
  base04: '#807d7c',
  base05: '#a5a2a2',
  base06: '#d6d5d4',
  base07: '#f7f7f7',
  base08: '#db2d20',
  base09: '#e8bbd0',
  base0A: '#fded02',
  base0B: '#01a252',
  base0C: '#b5e4f4',
  base0D: '#01a0e4',
  base0E: '#a16a94',
  base0F: '#cdab53'
};
module.exports = exports['default'];

/***/ }),

/***/ "FOBs":
/*!*******************************************************!*\
  !*** ./node_modules/react-colorscales/build/index.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

!function(e,t){if(true)module.exports=t(__webpack_require__(/*! react */ "q1tI"),__webpack_require__(/*! react-dom */ "i8i4"));else { var o, n; }}(this,function(e,t){return function(e){function t(o){if(n[o])return n[o].exports;var r=n[o]={i:o,l:!1,exports:{}};return e[o].call(r.exports,r,r.exports,t),r.l=!0,r.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,o){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:o})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=82)}([function(t,n){t.exports=e},function(e,t,n){(function(t){if("production"!==t.env.NODE_ENV){var o="function"===typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103,r=function(e){return"object"===typeof e&&null!==e&&e.$$typeof===o};e.exports=n(120)(r,!0)}else e.exports=n(122)()}).call(t,n(26))},function(e,t,n){"use strict";t.__esModule=!0,t.default=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}},function(e,t,n){"use strict";t.__esModule=!0;var o=n(43),r=function(e){return e&&e.__esModule?e:{default:e}}(o);t.default=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==("undefined"===typeof t?"undefined":(0,r.default)(t))&&"function"!==typeof t?e:t}},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var r=n(113),i=o(r),a=n(117),s=o(a),u=n(43),l=o(u);t.default=function(e,t){if("function"!==typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+("undefined"===typeof t?"undefined":(0,l.default)(t)));e.prototype=(0,s.default)(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(i.default?(0,i.default)(e,t):e.__proto__=t)}},function(e,t,n){"use strict";t.__esModule=!0;var o=n(86),r=function(e){return e&&e.__esModule?e:{default:e}}(o);t.default=r.default||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e}},function(e,t){var n=e.exports={version:"2.6.2"};"number"==typeof __e&&(__e=n)},function(e,t,n){var o=n(40)("wks"),r=n(29),i=n(11).Symbol,a="function"==typeof i;(e.exports=function(e){return o[e]||(o[e]=a&&i[e]||(a?i:r)("Symbol."+e))}).store=o},function(e,n){e.exports=t},function(e,t,n){"use strict";t.__esModule=!0;var o=n(69),r=function(e){return e&&e.__esModule?e:{default:e}}(o);t.default=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),(0,r.default)(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}()},function(e,t,n){var o=n(11),r=n(6),i=n(34),a=n(19),s=n(14),u=function(e,t,n){var l,c,p,f=e&u.F,d=e&u.G,h=e&u.S,b=e&u.P,v=e&u.B,g=e&u.W,m=d?r:r[t]||(r[t]={}),y=m.prototype,E=d?o:h?o[t]:(o[t]||{}).prototype;d&&(n=t);for(l in n)(c=!f&&E&&void 0!==E[l])&&s(m,l)||(p=c?E[l]:n[l],m[l]=d&&"function"!=typeof E[l]?n[l]:v&&c?i(p,o):g&&E[l]==p?function(e){var t=function(t,n,o){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,n)}return new e(t,n,o)}return e.apply(this,arguments)};return t.prototype=e.prototype,t}(p):b&&"function"==typeof p?i(Function.call,p):p,b&&((m.virtual||(m.virtual={}))[l]=p,e&u.R&&y&&!y[l]&&a(y,l,p)))};u.F=1,u.G=2,u.S=4,u.P=8,u.B=16,u.W=32,u.U=64,u.R=128,e.exports=u},function(e,t){var n=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(e,t,n){var o=n(20),r=n(58),i=n(35),a=Object.defineProperty;t.f=n(13)?Object.defineProperty:function(e,t,n){if(o(e),t=i(t,!0),o(n),r)try{return a(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e}},function(e,t,n){e.exports=!n(22)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},function(e,t,n){var o=n(61),r=n(37);e.exports=function(e){return o(r(e))}},function(e,t,n){var o,r;!function(){"use strict";function n(){for(var e=[],t=0;t<arguments.length;t++){var o=arguments[t];if(o){var r=typeof o;if("string"===r||"number"===r)e.push(o);else if(Array.isArray(o)&&o.length){var a=n.apply(null,o);a&&e.push(a)}else if("object"===r)for(var s in o)i.call(o,s)&&o[s]&&e.push(s)}}return e.join(" ")}var i={}.hasOwnProperty;"undefined"!==typeof e&&e.exports?(n.default=n,e.exports=n):(o=[],void 0!==(r=function(){return n}.apply(t,o))&&(e.exports=r))}()},function(e,t,n){"use strict";function o(e){var t=e.style.display;e.style.display="none",e.offsetHeight,e.style.display=t}function r(e,t,n){var o=n;{if("object"!==("undefined"===typeof t?"undefined":T(t)))return"undefined"!==typeof o?("number"===typeof o&&(o+="px"),void(e.style[t]=o)):_(e,t);for(var i in t)t.hasOwnProperty(i)&&r(e,i,t[i])}}function i(e){var t=void 0,n=void 0,o=void 0,r=e.ownerDocument,i=r.body,a=r&&r.documentElement;return t=e.getBoundingClientRect(),n=t.left,o=t.top,n-=a.clientLeft||i.clientLeft||0,o-=a.clientTop||i.clientTop||0,{left:n,top:o}}function a(e,t){var n=e["page"+(t?"Y":"X")+"Offset"],o="scroll"+(t?"Top":"Left");if("number"!==typeof n){var r=e.document;n=r.documentElement[o],"number"!==typeof n&&(n=r.body[o])}return n}function s(e){return a(e)}function u(e){return a(e,!0)}function l(e){var t=i(e),n=e.ownerDocument,o=n.defaultView||n.parentWindow;return t.left+=s(o),t.top+=u(o),t}function c(e){return null!==e&&void 0!==e&&e==e.window}function p(e){return c(e)?e.document:9===e.nodeType?e:e.ownerDocument}function f(e,t,n){var o=n,r="",i=p(e);return o=o||i.defaultView.getComputedStyle(e,null),o&&(r=o.getPropertyValue(t)||o[t]),r}function d(e,t){var n=e[D]&&e[D][t];if(P.test(n)&&!M.test(t)){var o=e.style,r=o[N],i=e[F][N];e[F][N]=e[D][N],o[N]="fontSize"===t?"1em":n||0,n=o.pixelLeft+j,o[N]=r,e[F][N]=i}return""===n?"auto":n}function h(e,t){return"left"===e?t.useCssRight?"right":e:t.useCssBottom?"bottom":e}function b(e){return"left"===e?"right":"right"===e?"left":"top"===e?"bottom":"bottom"===e?"top":void 0}function v(e,t,n){"static"===r(e,"position")&&(e.style.position="relative");var i=-999,a=-999,s=h("left",n),u=h("top",n),c=b(s),p=b(u);"left"!==s&&(i=999),"top"!==u&&(a=999);var f="",d=l(e);("left"in t||"top"in t)&&(f=Object(k.c)(e)||"",Object(k.e)(e,"none")),"left"in t&&(e.style[c]="",e.style[s]=i+"px"),"top"in t&&(e.style[p]="",e.style[u]=a+"px"),o(e);var v=l(e),g={};for(var m in t)if(t.hasOwnProperty(m)){var y=h(m,n),E="left"===m?i:a,w=d[m]-v[m];g[y]=y===m?E+w:E-w}r(e,g),o(e),("left"in t||"top"in t)&&Object(k.e)(e,f);var O={};for(var x in t)if(t.hasOwnProperty(x)){var C=h(x,n),S=t[x]-d[x];O[C]=x===C?g[C]+S:g[C]-S}r(e,O)}function g(e,t){var n=l(e),o=Object(k.b)(e),r={x:o.x,y:o.y};"left"in t&&(r.x=o.x+t.left-n.left),"top"in t&&(r.y=o.y+t.top-n.top),Object(k.d)(e,r)}function m(e,t,n){if(n.ignoreShake){var o=l(e),r=o.left.toFixed(0),i=o.top.toFixed(0),a=t.left.toFixed(0),s=t.top.toFixed(0);if(r===a&&i===s)return}n.useCssRight||n.useCssBottom?v(e,t,n):n.useCssTransform&&Object(k.a)()in document.body.style?g(e,t,n):v(e,t,n)}function y(e,t){for(var n=0;n<e.length;n++)t(e[n])}function E(e){return"border-box"===_(e,"boxSizing")}function w(e,t,n){var o={},r=e.style,i=void 0;for(i in t)t.hasOwnProperty(i)&&(o[i]=r[i],r[i]=t[i]);n.call(e);for(i in t)t.hasOwnProperty(i)&&(r[i]=o[i])}function O(e,t,n){var o=0,r=void 0,i=void 0,a=void 0;for(i=0;i<t.length;i++)if(r=t[i])for(a=0;a<n.length;a++){var s=void 0;s="border"===r?""+r+n[a]+"Width":r+n[a],o+=parseFloat(_(e,s))||0}return o}function x(e,t,n){var o=n;if(c(e))return"width"===t?B.viewportWidth(e):B.viewportHeight(e);if(9===e.nodeType)return"width"===t?B.docWidth(e):B.docHeight(e);var r="width"===t?["Left","Right"]:["Top","Bottom"],i="width"===t?e.getBoundingClientRect().width:e.getBoundingClientRect().height,a=_(e),s=E(e,a),u=0;(null===i||void 0===i||i<=0)&&(i=void 0,u=_(e,t),(null===u||void 0===u||Number(u)<0)&&(u=e.style[t]||0),u=parseFloat(u)||0),void 0===o&&(o=s?V:L);var l=void 0!==i||s,p=i||u;return o===L?l?p-O(e,["border","padding"],r,a):u:l?o===V?p:p+(o===I?-O(e,["border"],r,a):O(e,["margin"],r,a)):u+O(e,R.slice(o),r,a)}function C(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var o=void 0,r=t[0];return 0!==r.offsetWidth?o=x.apply(void 0,t):w(r,U,function(){o=x.apply(void 0,t)}),o}function S(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}var k=n(137),T="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"===typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},A=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,_=void 0,P=new RegExp("^("+A+")(?!px)[a-z%]+$","i"),M=/^(top|right|bottom|left)$/,D="currentStyle",F="runtimeStyle",N="left",j="px";"undefined"!==typeof window&&(_=window.getComputedStyle?f:d);var R=["margin","border","padding"],L=-1,I=2,V=1,B={};y(["Width","Height"],function(e){B["doc"+e]=function(t){var n=t.document;return Math.max(n.documentElement["scroll"+e],n.body["scroll"+e],B["viewport"+e](n))},B["viewport"+e]=function(t){var n="client"+e,o=t.document,r=o.body,i=o.documentElement,a=i[n];return"CSS1Compat"===o.compatMode&&a||r&&r[n]||a}});var U={position:"absolute",visibility:"hidden",display:"block"};y(["width","height"],function(e){var t=e.charAt(0).toUpperCase()+e.slice(1);B["outer"+t]=function(t,n){return t&&C(t,e,n?0:V)};var n="width"===e?["Left","Right"]:["Top","Bottom"];B[e]=function(t,o){var i=o;if(void 0===i)return t&&C(t,e,L);if(t){var a=_(t);return E(t)&&(i+=O(t,["padding","border"],n,a)),r(t,e,i)}}});var W={getWindow:function(e){if(e&&e.document&&e.setTimeout)return e;var t=e.ownerDocument||e;return t.defaultView||t.parentWindow},getDocument:p,offset:function(e,t,n){if("undefined"===typeof t)return l(e);m(e,t,n||{})},isWindow:c,each:y,css:r,clone:function(e){var t=void 0,n={};for(t in e)e.hasOwnProperty(t)&&(n[t]=e[t]);if(e.overflow)for(t in e)e.hasOwnProperty(t)&&(n.overflow[t]=e.overflow[t]);return n},mix:S,getWindowScrollLeft:function(e){return s(e)},getWindowScrollTop:function(e){return u(e)},merge:function(){for(var e={},t=arguments.length,n=Array(t),o=0;o<t;o++)n[o]=arguments[o];for(var r=0;r<n.length;r++)W.mix(e,n[r]);return e},viewportWidth:0,viewportHeight:0};S(W,B),t.a=W},function(e,t,n){"use strict";t.__esModule=!0;var o=n(69),r=function(e){return e&&e.__esModule?e:{default:e}}(o);t.default=function(e,t,n){return t in e?(0,r.default)(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}},function(e,t,n){var o=n(12),r=n(23);e.exports=n(13)?function(e,t,n){return o.f(e,t,r(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t,n){var o=n(21);e.exports=function(e){if(!o(e))throw TypeError(e+" is not an object!");return e}},function(e,t){e.exports=function(e){return"object"===typeof e?null!==e:"function"===typeof e}},function(e,t){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t,n){"use strict";t.__esModule=!0,t.default=function(e,t){var n={};for(var o in e)t.indexOf(o)>=0||Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=e[o]);return n}},function(e,t){e.exports={}},function(e,t){function n(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function r(e){if(c===setTimeout)return setTimeout(e,0);if((c===n||!c)&&setTimeout)return c=setTimeout,setTimeout(e,0);try{return c(e,0)}catch(t){try{return c.call(null,e,0)}catch(t){return c.call(this,e,0)}}}function i(e){if(p===clearTimeout)return clearTimeout(e);if((p===o||!p)&&clearTimeout)return p=clearTimeout,clearTimeout(e);try{return p(e)}catch(t){try{return p.call(null,e)}catch(t){return p.call(this,e)}}}function a(){b&&d&&(b=!1,d.length?h=d.concat(h):v=-1,h.length&&s())}function s(){if(!b){var e=r(a);b=!0;for(var t=h.length;t;){for(d=h,h=[];++v<t;)d&&d[v].run();v=-1,t=h.length}d=null,b=!1,i(e)}}function u(e,t){this.fun=e,this.array=t}function l(){}var c,p,f=e.exports={};!function(){try{c="function"===typeof setTimeout?setTimeout:n}catch(e){c=n}try{p="function"===typeof clearTimeout?clearTimeout:o}catch(e){p=o}}();var d,h=[],b=!1,v=-1;f.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];h.push(new u(e,t)),1!==h.length||b||r(s)},u.prototype.run=function(){this.fun.apply(null,this.array)},f.title="browser",f.browser=!0,f.env={},f.argv=[],f.version="",f.versions={},f.on=l,f.addListener=l,f.once=l,f.off=l,f.removeListener=l,f.removeAllListeners=l,f.emit=l,f.prependListener=l,f.prependOnceListener=l,f.listeners=function(e){return[]},f.binding=function(e){throw new Error("process.binding is not supported")},f.cwd=function(){return"/"},f.chdir=function(e){throw new Error("process.chdir is not supported")},f.umask=function(){return 0}},function(e,t,n){var o=n(60),r=n(41);e.exports=Object.keys||function(e){return o(e,r)}},function(e,t){e.exports=!0},function(e,t){var n=0,o=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+o).toString(36))}},function(e,t){t.f={}.propertyIsEnumerable},function(e,t,n){var o=n(37);e.exports=function(e){return Object(o(e))}},function(e,t,n){"use strict";function o(e,t,n,o){var r=s.a.unstable_batchedUpdates?function(e){s.a.unstable_batchedUpdates(n,e)}:n;return i()(e,t,r,o)}t.a=o;var r=n(125),i=n.n(r),a=n(8),s=n.n(a)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_NPREVIEWCOLORS=t.DEFAULT_SWATCH_WIDTH=t.DEFAULT_BREAKPOINTS=t.DEFAULT_LOG_BREAKPOINTS=t.DEFAULT_SCALE=t.DEFAULT_SWATCHES=t.DEFAULT_NCOLORS=t.DEFAULT_LIGHTNESS=t.DEFAULT_GAMMA=t.DEFAULT_HUE=t.DEFAULT_ROTATIONS=t.DEFAULT_START=t.CUBEHELIX=t.CMOCEAN=t.BUILTINS=t.BREWER=t.COLORSCALE_DESCRIPTIONS=t.SCALES_WITHOUT_LOG=t.COLORSCALE_TYPES=void 0;var o=n(56),r=function(e){return e&&e.__esModule?e:{default:e}}(o),i=(t.COLORSCALE_TYPES=["sequential","divergent","categorical","cyclical","cubehelix","cmocean","custom"],t.SCALES_WITHOUT_LOG=["divergent","categorical","custom"],t.COLORSCALE_DESCRIPTIONS={sequential:"Use sequential colorscales for data that smoothly changes value and has meaningful order.",divergent:"Use divergent colorscales for data that smoothly changes around a centerpoint (such as zero).",categorical:"Use categorical colorscales for data that has distinct groups and a non-meaningful order.",cyclical:"Use cyclical colorscales for data that has a natural cycle, such as angular, diurnal or seasonal data.",cubehelix:'Cubehelix colorscales are like sequential scales, but have the added benefit of printing clearly in black & white. Adjust the "start" slider to change the scale\'s base color. A cubehelix scale with 0 rotation transitions through a single base color. A scale with non-zero rotation "rotates" through other colors. Change the rotation slightly to add a touch of another color, change it more to create a scale with multiple colors.',cmocean:"cmocean colorscales are a mix of sequential and diverging scales. They were originally developed for oceanography data, but can be applied beautifully to any other type of data as well.",custom:"Select a sequential or categorical colorscale, then set customized breakpoints for it in the text box above. The breakpoints should have meaning to your data. For example, you could color data related to human age by groups in between the years 0, 5, 13, 20, 40, and 70. Click the preview colorscale below when you are satisfied with your breakpoints."},t.BREWER={sequential:["Purples","Blues","Greens","Oranges","Reds","YlOrBr","YlOrRd","OrRd","PuRd","RdPu","BuPu","PuBu","PuBuGn","GnBu","BuGn","YlGnBu","YlGn","Greys"],divergent:["Spectral","RdYlGn","RdBu","PiYG","PRGn","RdYlBu","BrBG","RdGy"],categorical:["Set1","Pastel1","Dark2","Set2","Pastel2","Set3"]},t.BUILTINS={sequential:{Viridis:["#440154","#482878","#3e4989","#31688e","#26828e","#1f9e89","#35b779","#6ece58","#b5de2b","#fde725"],Cividis:["#00224e","#123570","#3b496c","#575d6d","#707173","#8a8678","#a59c74","#c3b369","#e1cc55","#fee838"],Inferno:["#000004","#1b0c41","#4a0c6b","#781c6d","#a52c60","#cf4446","#ed6925","#fb9b06","#f7d13d","#fcffa4"],Magma:["#000004","#180f3d","#440f76","#721f81","#9e2f7f","#cd4071","#f1605d","#fd9668","#feca8d","#fcfdbf"],Plasma:["#0d0887","#46039f","#7201a8","#9c179e","#bd3786","#d8576b","#ed7953","#fb9f3a","#fdca26","#f0f921"]},categorical:{D3:["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],G10:["#3366cc","#dc3912","#ff9900","#109618","#990099","#0099c6","#dd4477","#66aa00","#b82e2e","#316395"],T10:["#4c78a8","#f58518","#e45756","#72b7b2","#54a24b","#eeca3b","#b279a2","#ff9da6","#9d755d","#bab0ac"],Alphabet:["#AA0DFE","#3283FE","#85660D","#782AB6","#565656","#1C8356","#16FF32","#F7E1A0","#E2E2E2","#1CBE4F","#C4451C","#DEA0FD","#FE00FA","#325A9B","#FEAF16","#F8A19F","#90AD1C","#F6222E","#1CFFCE","#2ED9FF","#B10DA1","#C075A6","#FC1CBF","#B00068","#FBE426","#FA0087"],Dark24:["#2E91E5","#E15F99","#1CA71C","#FB0D0D","#DA16FF","#222A2A","#B68100","#750D86","#EB663B","#511CFB","#00A08B","#FB00D1","#FC0080","#B2828D","#6C7C32","#778AAE","#862A16","#A777F1","#620042","#1616A7","#DA60CA","#6C4516","#0D2A63","#AF0038"],Light24:["#FD3216","#00FE35","#6A76FC","#FED4C4","#FE00CE","#0DF9FF","#F6F926","#FF9616","#479B55","#EEA6FB","#DC587D","#D626FF","#6E899C","#00B5F7","#B68E00","#C9FBE5","#FF0092","#22FFA7","#E3EE9E","#86CE00","#BC7196","#7E7DCD","#FC6955","#E48F72"]},cyclical:{Twilight:["#e2d9e2","#9ebbc9","#6785be","#5e43a5","#421257","#471340","#8e2c50","#ba6657","#ceac94","#e2d9e2"],IceFire:["#000000","#001f4d","#003786","#0e58a8","#217eb8","#30a4ca","#54c8df","#9be4ef","#e1e9d1","#f3d573","#e7b000","#da8200","#c65400","#ac2301","#820000","#4c0000","#040100"],Edge:["#313131","#3d019d","#3810dc","#2d47f9","#2593ff","#2adef6","#60fdfa","#aefdff","#f3f3f1","#fffda9","#fafd5b","#f7da29","#ff8e25","#f8432d","#d90d39","#97023d","#313131"],Phase:["rgb(167, 119, 12)","rgb(197, 96, 51)","rgb(217, 67, 96)","rgb(221, 38, 163)","rgb(196, 59, 224)","rgb(153, 97, 244)","rgb(95, 127, 228)","rgb(40, 144, 183)","rgb(15, 151, 136)","rgb(39, 153, 79)","rgb(119, 141, 17)","rgb(167, 119, 12)"],HSV:["#ff0000","#ffa700","#afff00","#08ff00","#00ff9f","#00b7ff","#0010ff","#9700ff","#ff00bf","#ff0018"],mrybm:["#f884f7","#f968c4","#ea4388","#cf244b","#b51a15","#bd4304","#cc6904","#d58f04","#cfaa27","#a19f62","#588a93","#2269c4","#3e3ef0","#6b4ef9","#956bfa","#cd7dfe"],mygbm:["#ef55f1","#fb84ce","#fbafa1","#fcd471","#f0ed35","#c6e516","#96d310","#61c10b","#31ac28","#439064","#3d719a","#284ec8","#2e21ea","#6324f5","#9139fa","#c543fa"]}},t.CMOCEAN={turbid:["rgb(232, 245, 171)","rgb(220, 219, 137)","rgb(209, 193, 107)","rgb(199, 168, 83)","rgb(186, 143, 66)","rgb(170, 121, 60)","rgb(151, 103, 58)","rgb(129, 87, 56)","rgb(104, 72, 53)","rgb(80, 59, 46)","rgb(57, 45, 37)","rgb(34, 30, 27)"],thermal:["rgb(3, 35, 51)","rgb(13, 48, 100)","rgb(53, 50, 155)","rgb(93, 62, 153)","rgb(126, 77, 143)","rgb(158, 89, 135)","rgb(193, 100, 121)","rgb(225, 113, 97)","rgb(246, 139, 69)","rgb(251, 173, 60)","rgb(246, 211, 70)","rgb(231, 250, 90)"],haline:["rgb(41, 24, 107)","rgb(42, 35, 160)","rgb(15, 71, 153)","rgb(18, 95, 142)","rgb(38, 116, 137)","rgb(53, 136, 136)","rgb(65, 157, 133)","rgb(81, 178, 124)","rgb(111, 198, 107)","rgb(160, 214, 91)","rgb(212, 225, 112)","rgb(253, 238, 153)"],solar:["rgb(51, 19, 23)","rgb(79, 28, 33)","rgb(108, 36, 36)","rgb(135, 47, 32)","rgb(157, 66, 25)","rgb(174, 88, 20)","rgb(188, 111, 19)","rgb(199, 137, 22)","rgb(209, 164, 32)","rgb(217, 192, 44)","rgb(222, 222, 59)","rgb(224, 253, 74)"],ice:["rgb(3, 5, 18)","rgb(25, 25, 51)","rgb(44, 42, 87)","rgb(58, 60, 125)","rgb(62, 83, 160)","rgb(62, 109, 178)","rgb(72, 134, 187)","rgb(89, 159, 196)","rgb(114, 184, 205)","rgb(149, 207, 216)","rgb(192, 229, 232)","rgb(234, 252, 253)"],gray:["rgb(0, 0, 0)","rgb(16, 16, 16)","rgb(38, 38, 38)","rgb(59, 59, 59)","rgb(81, 80, 80)","rgb(102, 101, 101)","rgb(124, 123, 122)","rgb(146, 146, 145)","rgb(171, 171, 170)","rgb(197, 197, 195)","rgb(224, 224, 223)","rgb(254, 254, 253)"],oxy:["rgb(63, 5, 5)","rgb(101, 6, 13)","rgb(138, 17, 9)","rgb(96, 95, 95)","rgb(119, 118, 118)","rgb(142, 141, 141)","rgb(166, 166, 165)","rgb(193, 192, 191)","rgb(222, 222, 220)","rgb(239, 248, 90)","rgb(230, 210, 41)","rgb(220, 174, 25)"],deep:["rgb(253, 253, 204)","rgb(206, 236, 179)","rgb(156, 219, 165)","rgb(111, 201, 163)","rgb(86, 177, 163)","rgb(76, 153, 160)","rgb(68, 130, 155)","rgb(62, 108, 150)","rgb(62, 82, 143)","rgb(64, 60, 115)","rgb(54, 43, 77)","rgb(39, 26, 44)"],dense:["rgb(230, 240, 240)","rgb(191, 221, 229)","rgb(156, 201, 226)","rgb(129, 180, 227)","rgb(115, 154, 228)","rgb(117, 127, 221)","rgb(120, 100, 202)","rgb(119, 74, 175)","rgb(113, 50, 141)","rgb(100, 31, 104)","rgb(80, 20, 66)","rgb(54, 14, 36)"],algae:["rgb(214, 249, 207)","rgb(186, 228, 174)","rgb(156, 209, 143)","rgb(124, 191, 115)","rgb(85, 174, 91)","rgb(37, 157, 81)","rgb(7, 138, 78)","rgb(13, 117, 71)","rgb(23, 95, 61)","rgb(25, 75, 49)","rgb(23, 55, 35)","rgb(17, 36, 20)"],matter:["rgb(253, 237, 176)","rgb(250, 205, 145)","rgb(246, 173, 119)","rgb(240, 142, 98)","rgb(231, 109, 84)","rgb(216, 80, 83)","rgb(195, 56, 90)","rgb(168, 40, 96)","rgb(138, 29, 99)","rgb(107, 24, 93)","rgb(76, 21, 80)","rgb(47, 15, 61)"],speed:["rgb(254, 252, 205)","rgb(239, 225, 156)","rgb(221, 201, 106)","rgb(194, 182, 59)","rgb(157, 167, 21)","rgb(116, 153, 5)","rgb(75, 138, 20)","rgb(35, 121, 36)","rgb(11, 100, 44)","rgb(18, 78, 43)","rgb(25, 56, 34)","rgb(23, 35, 18)"],amp:["rgb(241, 236, 236)","rgb(230, 209, 203)","rgb(221, 182, 170)","rgb(213, 156, 137)","rgb(205, 129, 103)","rgb(196, 102, 73)","rgb(186, 74, 47)","rgb(172, 44, 36)","rgb(149, 19, 39)","rgb(120, 14, 40)","rgb(89, 13, 31)","rgb(60, 9, 17)"],tempo:["rgb(254, 245, 244)","rgb(222, 224, 210)","rgb(189, 206, 181)","rgb(153, 189, 156)","rgb(110, 173, 138)","rgb(65, 157, 129)","rgb(25, 137, 125)","rgb(18, 116, 117)","rgb(25, 94, 106)","rgb(28, 72, 93)","rgb(25, 51, 80)","rgb(20, 29, 67)"],phase:["rgb(167, 119, 12)","rgb(197, 96, 51)","rgb(217, 67, 96)","rgb(221, 38, 163)","rgb(196, 59, 224)","rgb(153, 97, 244)","rgb(95, 127, 228)","rgb(40, 144, 183)","rgb(15, 151, 136)","rgb(39, 153, 79)","rgb(119, 141, 17)","rgb(167, 119, 12)"],balance:["rgb(23, 28, 66)","rgb(41, 58, 143)","rgb(11, 102, 189)","rgb(69, 144, 185)","rgb(142, 181, 194)","rgb(210, 216, 219)","rgb(230, 210, 204)","rgb(213, 157, 137)","rgb(196, 101, 72)","rgb(172, 43, 36)","rgb(120, 14, 40)","rgb(60, 9, 17)"],delta:["rgb(16, 31, 63)","rgb(38, 62, 144)","rgb(30, 110, 161)","rgb(60, 154, 171)","rgb(140, 193, 186)","rgb(217, 229, 218)","rgb(239, 226, 156)","rgb(195, 182, 59)","rgb(115, 152, 5)","rgb(34, 120, 36)","rgb(18, 78, 43)","rgb(23, 35, 18)"],curl:["rgb(20, 29, 67)","rgb(28, 72, 93)","rgb(18, 115, 117)","rgb(63, 156, 129)","rgb(153, 189, 156)","rgb(223, 225, 211)","rgb(241, 218, 206)","rgb(224, 160, 137)","rgb(203, 101, 99)","rgb(164, 54, 96)","rgb(111, 23, 91)","rgb(51, 13, 53)"]},t.CUBEHELIX=[{start:300,rotations:-1.5},{start:0,rotations:-.4},{start:0,rotations:-.1},{start:100,rotations:.4},{start:200,rotations:-.1},{start:200,rotations:-.4},{start:200,rotations:.4},{start:300,rotations:-.1}],t.DEFAULT_START=300,t.DEFAULT_ROTATIONS=-1.5,t.DEFAULT_HUE=1,t.DEFAULT_GAMMA=1,t.DEFAULT_LIGHTNESS=[.85,.15],t.DEFAULT_NCOLORS=10,t.DEFAULT_SWATCHES=9);t.DEFAULT_SCALE=r.default.scale(["#fafa6e","#2A4858"]).mode("lch").colors(i),t.DEFAULT_LOG_BREAKPOINTS=4,t.DEFAULT_BREAKPOINTS=[0,1],t.DEFAULT_SWATCH_WIDTH=20,t.DEFAULT_NPREVIEWCOLORS=10},function(e,t,n){var o=n(89);e.exports=function(e,t,n){if(o(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,o){return e.call(t,n,o)};case 3:return function(n,o,r){return e.call(t,n,o,r)}}return function(){return e.apply(t,arguments)}}},function(e,t,n){var o=n(21);e.exports=function(e,t){if(!o(e))return e;var n,r;if(t&&"function"==typeof(n=e.toString)&&!o(r=n.call(e)))return r;if("function"==typeof(n=e.valueOf)&&!o(r=n.call(e)))return r;if(!t&&"function"==typeof(n=e.toString)&&!o(r=n.call(e)))return r;throw TypeError("Can't convert object to primitive value")}},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on  "+e);return e}},function(e,t){var n=Math.ceil,o=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?o:n)(e)}},function(e,t,n){var o=n(40)("keys"),r=n(29);e.exports=function(e){return o[e]||(o[e]=r(e))}},function(e,t,n){var o=n(6),r=n(11),i=r["__core-js_shared__"]||(r["__core-js_shared__"]={});(e.exports=function(e,t){return i[e]||(i[e]=void 0!==t?t:{})})("versions",[]).push({version:o.version,mode:n(28)?"pure":"global",copyright:"\xa9 2019 Denis Pushkarev (zloirock.ru)"})},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var r=n(93),i=o(r),a=n(103),s=o(a),u="function"===typeof s.default&&"symbol"===typeof i.default?function(e){return typeof e}:function(e){return e&&"function"===typeof s.default&&e.constructor===s.default&&e!==s.default.prototype?"symbol":typeof e};t.default="function"===typeof s.default&&"symbol"===u(i.default)?function(e){return"undefined"===typeof e?"undefined":u(e)}:function(e){return e&&"function"===typeof s.default&&e.constructor===s.default&&e!==s.default.prototype?"symbol":"undefined"===typeof e?"undefined":u(e)}},function(e,t,n){var o=n(20),r=n(97),i=n(41),a=n(39)("IE_PROTO"),s=function(){},u=function(){var e,t=n(59)("iframe"),o=i.length;for(t.style.display="none",n(98).appendChild(t),t.src="javascript:",e=t.contentWindow.document,e.open(),e.write("<script>document.F=Object<\/script>"),e.close(),u=e.F;o--;)delete u.prototype[i[o]];return u()};e.exports=Object.create||function(e,t){var n;return null!==e?(s.prototype=o(e),n=new s,s.prototype=null,n[a]=e):n=u(),void 0===t?n:r(n,t)}},function(e,t,n){var o=n(12).f,r=n(14),i=n(7)("toStringTag");e.exports=function(e,t,n){e&&!r(e=n?e:e.prototype,i)&&o(e,i,{configurable:!0,value:t})}},function(e,t,n){t.f=n(7)},function(e,t,n){var o=n(11),r=n(6),i=n(28),a=n(46),s=n(12).f;e.exports=function(e){var t=r.Symbol||(r.Symbol=i?{}:o.Symbol||{});"_"==e.charAt(0)||e in t||s(t,e,{value:a.f(e)})}},function(e,t,n){var o=n(30),r=n(23),i=n(15),a=n(35),s=n(14),u=n(58),l=Object.getOwnPropertyDescriptor;t.f=n(13)?l:function(e,t){if(e=i(e),t=a(t,!0),u)try{return l(e,t)}catch(e){}if(s(e,t))return r(!o.f.call(e,t),e[t])}},function(e,t,n){"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},function(e,t,n){"use strict";(function(t){var n=function(){};"production"!==t.env.NODE_ENV&&(n=function(e,t,n){var o=arguments.length;n=new Array(o>2?o-2:0);for(var r=2;r<o;r++)n[r-2]=arguments[r];if(void 0===t)throw new Error("`warning(condition, format, ...args)` requires a warning message argument");if(t.length<10||/^[s\W]*$/.test(t))throw new Error("The warning format should be able to uniquely identify this warning. Please, use a more descriptive format than: "+t);if(!e){var i=0,a="Warning: "+t.replace(/%s/g,function(){return n[i++]});"undefined"!==typeof console&&console.error(a);try{throw new Error(a)}catch(e){}}}),e.exports=n}).call(t,n(26))},function(e,t,n){"use strict";var o=n(5),r=n.n(o),i=n(18),a=n.n(i),s=n(24),u=n.n(s),l=n(2),c=n.n(l),p=n(9),f=n.n(p),d=n(3),h=n.n(d),b=n(4),v=n.n(b),g=n(0),m=n.n(g),y=n(1),E=n.n(y),w=n(16),O=n.n(w),x=n(32),C=function(e){function t(){var e,n,o,r;c()(this,t);for(var i=arguments.length,a=Array(i),s=0;s<i;s++)a[s]=arguments[s];return n=o=h()(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(a))),o.state={clickFocused:!1},o.setHandleRef=function(e){o.handle=e},o.handleMouseUp=function(){document.activeElement===o.handle&&o.setClickFocus(!0)},o.handleBlur=function(){o.setClickFocus(!1)},o.handleKeyDown=function(){o.setClickFocus(!1)},r=n,h()(o,r)}return v()(t,e),f()(t,[{key:"componentDidMount",value:function(){this.onMouseUpListener=Object(x.a)(document,"mouseup",this.handleMouseUp)}},{key:"componentWillUnmount",value:function(){this.onMouseUpListener&&this.onMouseUpListener.remove()}},{key:"setClickFocus",value:function(e){this.setState({clickFocused:e})}},{key:"clickFocus",value:function(){this.setClickFocus(!0),this.focus()}},{key:"focus",value:function(){this.handle.focus()}},{key:"blur",value:function(){this.handle.blur()}},{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.vertical,o=e.offset,i=e.style,s=e.disabled,l=e.min,c=e.max,p=e.value,f=e.tabIndex,d=u()(e,["prefixCls","vertical","offset","style","disabled","min","max","value","tabIndex"]),h=O()(this.props.className,a()({},t+"-handle-click-focused",this.state.clickFocused)),b=n?{bottom:o+"%"}:{left:o+"%"},v=r()({},i,b);return m.a.createElement("div",r()({ref:this.setHandleRef,tabIndex:s?null:f||0},d,{className:h,style:v,onBlur:this.handleBlur,onKeyDown:this.handleKeyDown,role:"slider","aria-valuemin":l,"aria-valuemax":c,"aria-valuenow":p,"aria-disabled":!!s}))}}]),t}(m.a.Component);t.a=C,C.propTypes={prefixCls:E.a.string,className:E.a.string,vertical:E.a.bool,offset:E.a.number,style:E.a.object,disabled:E.a.bool,min:E.a.number,max:E.a.number,value:E.a.number,tabIndex:E.a.number}},function(e,t,n){"use strict";(function(e){function o(){return"production"!==e.env.NODE_ENV}function r(e,t){try{return Object.keys(t).some(function(n){return e.target===Object(y.findDOMNode)(t[n])})}catch(e){return!1}}function i(e,t){var n=t.min,o=t.max;return e<n||e>o}function a(e){return e.touches.length>1||"touchend"===e.type.toLowerCase()&&e.touches.length>0}function s(e,t){var n=t.marks,o=t.step,r=t.min,i=Object.keys(n).map(parseFloat);if(null!==o){var a=Math.round((e-r)/o)*o+r;i.push(a)}var s=i.map(function(t){return Math.abs(e-t)});return i[s.indexOf(Math.min.apply(Math,m()(s)))]}function u(e){var t=e.toString(),n=0;return t.indexOf(".")>=0&&(n=t.length-t.indexOf(".")-1),n}function l(e,t){return e?t.clientY:t.pageX}function c(e,t){return e?t.touches[0].clientY:t.touches[0].pageX}function p(e,t){var n=t.getBoundingClientRect();return e?n.top+.5*n.height:window.pageXOffset+n.left+.5*n.width}function f(e,t){var n=t.max,o=t.min;return e<=o?o:e>=n?n:e}function d(e,t){var n=t.step,o=isFinite(s(e,t))?s(e,t):0;return null===n?o:parseFloat(o.toFixed(u(n)))}function h(e){e.stopPropagation(),e.preventDefault()}function b(e,t,n){var o={increase:function(e,t){return e+t},decrease:function(e,t){return e-t}},r=o[e](Object.keys(n.marks).indexOf(JSON.stringify(t)),1),i=Object.keys(n.marks)[r];return n.step?o[e](t,n.step):Object.keys(n.marks).length&&n.marks[i]?n.marks[i]:t}function v(e){switch(e.keyCode){case E.a.UP:case E.a.RIGHT:return function(e,t){return b("increase",e,t)};case E.a.DOWN:case E.a.LEFT:return function(e,t){return b("decrease",e,t)};case E.a.END:return function(e,t){return t.max};case E.a.HOME:return function(e,t){return t.min};case E.a.PAGE_UP:return function(e,t){return e+2*t.step};case E.a.PAGE_DOWN:return function(e,t){return e-2*t.step};default:return}}t.g=o,t.h=r,t.j=i,t.i=a,t.e=l,t.f=c,t.c=p,t.a=f,t.b=d,t.k=h,t.d=v;var g=n(81),m=n.n(g),y=n(8),E=(n.n(y),n(173))}).call(t,n(26))},function(e,t){function n(e,t){var n=e[1]||"",r=e[3];if(!r)return n;if(t&&"function"===typeof btoa){var i=o(r);return[n].concat(r.sources.map(function(e){return"/*# sourceURL="+r.sourceRoot+e+" */"})).concat([i]).join("\n")}return[n].join("\n")}function o(e){return"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(e))))+" */"}e.exports=function(e){var t=[];return t.toString=function(){return this.map(function(t){var o=n(t,e);return t[2]?"@media "+t[2]+"{"+o+"}":o}).join("")},t.i=function(e,n){"string"===typeof e&&(e=[[null,e,""]]);for(var o={},r=0;r<this.length;r++){var i=this[r][0];"number"===typeof i&&(o[i]=!0)}for(r=0;r<e.length;r++){var a=e[r];"number"===typeof a[0]&&o[a[0]]||(n&&!a[2]?a[2]=n:n&&(a[2]="("+a[2]+") and ("+n+")"),t.push(a))}},t}},function(e,t,n){function o(e,t){for(var n=0;n<e.length;n++){var o=e[n],r=h[o.id];if(r){r.refs++;for(var i=0;i<r.parts.length;i++)r.parts[i](o.parts[i]);for(;i<o.parts.length;i++)r.parts.push(c(o.parts[i],t))}else{for(var a=[],i=0;i<o.parts.length;i++)a.push(c(o.parts[i],t));h[o.id]={id:o.id,refs:1,parts:a}}}}function r(e,t){for(var n=[],o={},r=0;r<e.length;r++){var i=e[r],a=t.base?i[0]+t.base:i[0],s=i[1],u=i[2],l=i[3],c={css:s,media:u,sourceMap:l};o[a]?o[a].parts.push(c):n.push(o[a]={id:a,parts:[c]})}return n}function i(e,t){var n=v(e.insertInto);if(!n)throw new Error("Couldn't find a style target. This probably means that the value for the 'insertInto' parameter is invalid.");var o=y[y.length-1];if("top"===e.insertAt)o?o.nextSibling?n.insertBefore(t,o.nextSibling):n.appendChild(t):n.insertBefore(t,n.firstChild),y.push(t);else{if("bottom"!==e.insertAt)throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");n.appendChild(t)}}function a(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e);var t=y.indexOf(e);t>=0&&y.splice(t,1)}function s(e){var t=document.createElement("style");return e.attrs.type="text/css",l(t,e.attrs),i(e,t),t}function u(e){var t=document.createElement("link");return e.attrs.type="text/css",e.attrs.rel="stylesheet",l(t,e.attrs),i(e,t),t}function l(e,t){Object.keys(t).forEach(function(n){e.setAttribute(n,t[n])})}function c(e,t){var n,o,r,i;if(t.transform&&e.css){if(!(i=t.transform(e.css)))return function(){};e.css=i}if(t.singleton){var l=m++;n=g||(g=s(t)),o=p.bind(null,n,l,!1),r=p.bind(null,n,l,!0)}else e.sourceMap&&"function"===typeof URL&&"function"===typeof URL.createObjectURL&&"function"===typeof URL.revokeObjectURL&&"function"===typeof Blob&&"function"===typeof btoa?(n=u(t),o=d.bind(null,n,t),r=function(){a(n),n.href&&URL.revokeObjectURL(n.href)}):(n=s(t),o=f.bind(null,n),r=function(){a(n)});return o(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap)return;o(e=t)}else r()}}function p(e,t,n,o){var r=n?"":o.css;if(e.styleSheet)e.styleSheet.cssText=w(t,r);else{var i=document.createTextNode(r),a=e.childNodes;a[t]&&e.removeChild(a[t]),a.length?e.insertBefore(i,a[t]):e.appendChild(i)}}function f(e,t){var n=t.css,o=t.media;if(o&&e.setAttribute("media",o),e.styleSheet)e.styleSheet.cssText=n;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(n))}}function d(e,t,n){var o=n.css,r=n.sourceMap,i=void 0===t.convertToAbsoluteUrls&&r;(t.convertToAbsoluteUrls||i)&&(o=E(o)),r&&(o+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(r))))+" */");var a=new Blob([o],{type:"text/css"}),s=e.href;e.href=URL.createObjectURL(a),s&&URL.revokeObjectURL(s)}var h={},b=function(e){var t;return function(){return"undefined"===typeof t&&(t=e.apply(this,arguments)),t}}(function(){return window&&document&&document.all&&!window.atob}),v=function(e){var t={};return function(n){return"undefined"===typeof t[n]&&(t[n]=e.call(this,n)),t[n]}}(function(e){return document.querySelector(e)}),g=null,m=0,y=[],E=n(181);e.exports=function(e,t){if("undefined"!==typeof DEBUG&&DEBUG&&"object"!==typeof document)throw new Error("The style-loader cannot be used in a non-browser environment");t=t||{},t.attrs="object"===typeof t.attrs?t.attrs:{},t.singleton||(t.singleton=b()),t.insertInto||(t.insertInto="head"),t.insertAt||(t.insertAt="bottom");var n=r(e,t);return o(n,t),function(e){for(var i=[],a=0;a<n.length;a++){var s=n[a],u=h[s.id];u.refs--,i.push(u)}if(e){o(r(e,t),t)}for(var a=0;a<i.length;a++){var u=i[a];if(0===u.refs){for(var l=0;l<u.parts.length;l++)u.parts[l]();delete h[u.id]}}}};var w=function(){var e=[];return function(t,n){return e[t]=n,e.filter(Boolean).join("\n")}}()},function(e,t,n){"use strict";function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function r(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==typeof t&&"function"!==typeof t?e:t}function i(e,t){if("function"!==typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),s=n(0),u=function(e){return e&&e.__esModule?e:{default:e}}(s),l=n(33),c=function(e){function t(){return o(this,t),r(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return i(t,e),a(t,[{key:"render",value:function(){var e=this,t=this.props.colorscale?this.props.colorscale:l.DEFAULT_SCALE;return u.default.createElement("div",{style:{width:"100%"},className:"colorscale-container"},this.props.label?u.default.createElement("div",{className:"colorscale-label",style:{fontWeight:600,fontSize:"12px",color:"#2a3f5f",display:"inline-block",width:"25%",textAlign:"start"}},this.props.label):null,u.default.createElement("div",{className:"colorscale-palette-container",style:{display:"inline-block",textAlign:"start",width:this.props.label?"75%":"100%"}},u.default.createElement("div",{className:"colorscale-block",style:{fontSize:"0px",display:"inline-block",width:"100%"},onClick:function(){return e.props.onClick(t,e.props.start,e.props.rot)}},t.map(function(e,n){return u.default.createElement("div",{key:n,className:"colorscale-swatch",style:{backgroundColor:e,width:100/t.length+"%",height:"20px",margin:"0 auto",display:"inline-block",cursor:"pointer"}})}))))}}]),t}(s.Component);t.default=c},function(e,t,n){(function(e){var n,o;(function(){var r,i,a,s,u,l,c,p,f,d,h,b,v,g,m,y,E,w,O,x,C,S,k,T,A,_,P,M,D,F,N,j,R,L,I,V,B,U,W,H,z,K,q,Y,G,X,Z,J,$,Q,ee,te,ne,oe,re,ie,ae,se,ue,le,ce,pe,fe,de,he,be,ve,ge,me,ye,Ee,we,Oe,xe,Ce,Se,ke,Te,Ae,_e,Pe,Me=[].slice;ke=function(){var e,t,n,o,r;for(e={},r="Boolean Number String Function Array Date RegExp Undefined Null".split(" "),o=0,t=r.length;o<t;o++)n=r[o],e["[object "+n+"]"]=n.toLowerCase();return function(t){var n;return n=Object.prototype.toString.call(t),e[n]||"object"}}(),Z=function(e,t,n){return null==t&&(t=0),null==n&&(n=1),e<t&&(e=t),e>n&&(e=n),e},Te=function(e){return e.length>=3?Array.prototype.slice.call(e):e[0]},C=function(e){var t,n;for(e._clipped=!1,e._unclipped=e.slice(0),t=n=0;n<3;t=++n)t<3?((e[t]<0||e[t]>255)&&(e._clipped=!0),e[t]<0&&(e[t]=0),e[t]>255&&(e[t]=255)):3===t&&(e[t]<0&&(e[t]=0),e[t]>1&&(e[t]=1));return e._clipped||delete e._unclipped,e},s=Math.PI,we=Math.round,k=Math.cos,M=Math.floor,ie=Math.pow,J=Math.log,xe=Math.sin,Ce=Math.sqrt,g=Math.atan2,ee=Math.max,v=Math.abs,c=2*s,u=s/3,i=s/180,l=180/s,x=function(){return arguments[0]instanceof r?arguments[0]:function(e,t,n){n.prototype=e.prototype;var o=new n,r=e.apply(o,t);return Object(r)===r?r:o}(r,arguments,function(){})},x.default=x,b=[],"undefined"!==typeof e&&null!==e&&null!=e.exports&&(e.exports=x),n=[],void 0!==(o=function(){return x}.apply(t,n))&&(e.exports=o),x.version="1.4.1",h={},f=[],d=!1,r=function(){function e(){var e,t,n,o,r,i,a,s,u;for(i=this,t=[],s=0,o=arguments.length;s<o;s++)null!=(e=arguments[s])&&t.push(e);if(t.length>1&&(a=t[t.length-1]),null!=h[a])i._rgb=C(h[a](Te(t.slice(0,-1))));else{for(d||(f=f.sort(function(e,t){return t.p-e.p}),d=!0),u=0,r=f.length;u<r&&(n=f[u],!(a=n.test.apply(n,t)));u++);a&&(i._rgb=C(h[a].apply(h,t)))}null==i._rgb&&console.warn("unknown format: "+t),null==i._rgb&&(i._rgb=[0,0,0]),3===i._rgb.length&&i._rgb.push(1)}return e.prototype.toString=function(){return this.hex()},e}(),x._input=h,x.brewer=w={OrRd:["#fff7ec","#fee8c8","#fdd49e","#fdbb84","#fc8d59","#ef6548","#d7301f","#b30000","#7f0000"],PuBu:["#fff7fb","#ece7f2","#d0d1e6","#a6bddb","#74a9cf","#3690c0","#0570b0","#045a8d","#023858"],BuPu:["#f7fcfd","#e0ecf4","#bfd3e6","#9ebcda","#8c96c6","#8c6bb1","#88419d","#810f7c","#4d004b"],Oranges:["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#a63603","#7f2704"],BuGn:["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#006d2c","#00441b"],YlOrBr:["#ffffe5","#fff7bc","#fee391","#fec44f","#fe9929","#ec7014","#cc4c02","#993404","#662506"],YlGn:["#ffffe5","#f7fcb9","#d9f0a3","#addd8e","#78c679","#41ab5d","#238443","#006837","#004529"],Reds:["#fff5f0","#fee0d2","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#a50f15","#67000d"],RdPu:["#fff7f3","#fde0dd","#fcc5c0","#fa9fb5","#f768a1","#dd3497","#ae017e","#7a0177","#49006a"],Greens:["#f7fcf5","#e5f5e0","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#006d2c","#00441b"],YlGnBu:["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"],Purples:["#fcfbfd","#efedf5","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#54278f","#3f007d"],GnBu:["#f7fcf0","#e0f3db","#ccebc5","#a8ddb5","#7bccc4","#4eb3d3","#2b8cbe","#0868ac","#084081"],Greys:["#ffffff","#f0f0f0","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525","#000000"],YlOrRd:["#ffffcc","#ffeda0","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#bd0026","#800026"],PuRd:["#f7f4f9","#e7e1ef","#d4b9da","#c994c7","#df65b0","#e7298a","#ce1256","#980043","#67001f"],Blues:["#f7fbff","#deebf7","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#08519c","#08306b"],PuBuGn:["#fff7fb","#ece2f0","#d0d1e6","#a6bddb","#67a9cf","#3690c0","#02818a","#016c59","#014636"],Viridis:["#440154","#482777","#3f4a8a","#31678e","#26838f","#1f9d8a","#6cce5a","#b6de2b","#fee825"],Spectral:["#9e0142","#d53e4f","#f46d43","#fdae61","#fee08b","#ffffbf","#e6f598","#abdda4","#66c2a5","#3288bd","#5e4fa2"],RdYlGn:["#a50026","#d73027","#f46d43","#fdae61","#fee08b","#ffffbf","#d9ef8b","#a6d96a","#66bd63","#1a9850","#006837"],RdBu:["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#f7f7f7","#d1e5f0","#92c5de","#4393c3","#2166ac","#053061"],PiYG:["#8e0152","#c51b7d","#de77ae","#f1b6da","#fde0ef","#f7f7f7","#e6f5d0","#b8e186","#7fbc41","#4d9221","#276419"],PRGn:["#40004b","#762a83","#9970ab","#c2a5cf","#e7d4e8","#f7f7f7","#d9f0d3","#a6dba0","#5aae61","#1b7837","#00441b"],RdYlBu:["#a50026","#d73027","#f46d43","#fdae61","#fee090","#ffffbf","#e0f3f8","#abd9e9","#74add1","#4575b4","#313695"],BrBG:["#543005","#8c510a","#bf812d","#dfc27d","#f6e8c3","#f5f5f5","#c7eae5","#80cdc1","#35978f","#01665e","#003c30"],RdGy:["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#ffffff","#e0e0e0","#bababa","#878787","#4d4d4d","#1a1a1a"],PuOr:["#7f3b08","#b35806","#e08214","#fdb863","#fee0b6","#f7f7f7","#d8daeb","#b2abd2","#8073ac","#542788","#2d004b"],Set2:["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f","#e5c494","#b3b3b3"],Accent:["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0","#f0027f","#bf5b17","#666666"],Set1:["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628","#f781bf","#999999"],Set3:["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd","#ccebc5","#ffed6f"],Dark2:["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e","#e6ab02","#a6761d","#666666"],Paired:["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6","#6a3d9a","#ffff99","#b15928"],Pastel2:["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9","#fff2ae","#f1e2cc","#cccccc"],Pastel1:["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc","#e5d8bd","#fddaec","#f2f2f2"]},function(){var e,t;t=[];for(e in w)t.push(w[e.toLowerCase()]=w[e])}(),Ae={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflower:"#6495ed",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",laserlemon:"#ffff54",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrod:"#fafad2",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",maroon2:"#7f0000",maroon3:"#b03060",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",purple2:"#7f007f",purple3:"#a020f0",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},x.colors=Ae,K=function(){var e,t,n,o,r,i,s,u,l;return t=Te(arguments),r=t[0],e=t[1],n=t[2],u=(r+16)/116,s=isNaN(e)?u:u+e/500,l=isNaN(n)?u:u-n/200,u=a.Yn*q(u),s=a.Xn*q(s),l=a.Zn*q(l),i=Pe(3.2404542*s-1.5371385*u-.4985314*l),o=Pe(-.969266*s+1.8760108*u+.041556*l),n=Pe(.0556434*s-.2040259*u+1.0572252*l),[i,o,n,t.length>3?t[3]:1]},Pe=function(e){return 255*(e<=.00304?12.92*e:1.055*ie(e,1/2.4)-.055)},q=function(e){return e>a.t1?e*e*e:a.t2*(e-a.t0)},a={Kn:18,Xn:.95047,Yn:1,Zn:1.08883,t0:.137931034,t1:.206896552,t2:.12841855,t3:.008856452},de=function(){var e,t,n,o,r,i,a,s;return o=Te(arguments),n=o[0],t=o[1],e=o[2],r=me(n,t,e),i=r[0],a=r[1],s=r[2],[116*a-16,500*(i-a),200*(a-s)]},ye=function(e){return(e/=255)<=.04045?e/12.92:ie((e+.055)/1.055,2.4)},_e=function(e){return e>a.t3?ie(e,1/3):e/a.t2+a.t0},me=function(){var e,t,n,o,r,i,s;return o=Te(arguments),n=o[0],t=o[1],e=o[2],n=ye(n),t=ye(t),e=ye(e),r=_e((.4124564*n+.3575761*t+.1804375*e)/a.Xn),i=_e((.2126729*n+.7151522*t+.072175*e)/a.Yn),s=_e((.0193339*n+.119192*t+.9503041*e)/a.Zn),[r,i,s]},x.lab=function(){return function(e,t,n){n.prototype=e.prototype;var o=new n,r=e.apply(o,t);return Object(r)===r?r:o}(r,Me.call(arguments).concat(["lab"]),function(){})},h.lab=K,r.prototype.lab=function(){return de(this._rgb)},m=function(e){var t,n,o,r,i,a,s,u,l,c,p;return e=function(){var t,n,o;for(o=[],n=0,t=e.length;n<t;n++)r=e[n],o.push(x(r));return o}(),2===e.length?(l=function(){var t,n,o;for(o=[],n=0,t=e.length;n<t;n++)r=e[n],o.push(r.lab());return o}(),i=l[0],a=l[1],t=function(e){var t,n;return n=function(){var n,o;for(o=[],t=n=0;n<=2;t=++n)o.push(i[t]+e*(a[t]-i[t]));return o}(),x.lab.apply(x,n)}):3===e.length?(c=function(){var t,n,o;for(o=[],n=0,t=e.length;n<t;n++)r=e[n],o.push(r.lab());return o}(),i=c[0],a=c[1],s=c[2],t=function(e){var t,n;return n=function(){var n,o;for(o=[],t=n=0;n<=2;t=++n)o.push((1-e)*(1-e)*i[t]+2*(1-e)*e*a[t]+e*e*s[t]);return o}(),x.lab.apply(x,n)}):4===e.length?(p=function(){var t,n,o;for(o=[],n=0,t=e.length;n<t;n++)r=e[n],o.push(r.lab());return o}(),i=p[0],a=p[1],s=p[2],u=p[3],t=function(e){var t,n;return n=function(){var n,o;for(o=[],t=n=0;n<=2;t=++n)o.push((1-e)*(1-e)*(1-e)*i[t]+3*(1-e)*(1-e)*e*a[t]+3*(1-e)*e*e*s[t]+e*e*e*u[t]);return o}(),x.lab.apply(x,n)}):5===e.length&&(n=m(e.slice(0,3)),o=m(e.slice(2,5)),t=function(e){return e<.5?n(2*e):o(2*(e-.5))}),t},x.bezier=function(e){var t;return t=m(e),t.scale=function(){return x.scale(t)},t},x.cubehelix=function(e,t,n,o,r){var i,a,s;return null==e&&(e=300),null==t&&(t=-1.5),null==n&&(n=1),null==o&&(o=1),null==r&&(r=[0,1]),i=0,"array"===ke(r)?a=r[1]-r[0]:(a=0,r=[r,r]),s=function(s){var u,l,p,f,d,h,b,v,g;return u=c*((e+120)/360+t*s),b=ie(r[0]+a*s,o),h=0!==i?n[0]+s*i:n,l=h*b*(1-b)/2,f=k(u),g=xe(u),v=b+l*(-.14861*f+1.78277*g),d=b+l*(-.29227*f-.90649*g),p=b+l*(1.97294*f),x(C([255*v,255*d,255*p,1]))},s.start=function(t){return null==t?e:(e=t,s)},s.rotations=function(e){return null==e?t:(t=e,s)},s.gamma=function(e){return null==e?o:(o=e,s)},s.hue=function(e){return null==e?n:(n=e,"array"===ke(n)?0===(i=n[1]-n[0])&&(n=n[1]):i=0,s)},s.lightness=function(e){return null==e?r:("array"===ke(e)?(r=e,a=e[1]-e[0]):(r=[e,e],a=0),s)},s.scale=function(){return x.scale(s)},s.hue(n),s},x.random=function(){var e,t,n;for(t="0123456789abcdef",e="#",n=0;n<6;++n)e+=t.charAt(M(16*Math.random()));return new r(e)},b=[],I=function(e,t,n,o){var r,i,a,s;for(null==n&&(n=.5),null==o&&(o="rgb"),"object"!==ke(e)&&(e=x(e)),"object"!==ke(t)&&(t=x(t)),a=0,i=b.length;a<i;a++)if(r=b[a],o===r[0]){s=r[1](e,t,n,o);break}if(null==s)throw"color mode "+o+" is not supported";return s.alpha(e.alpha()+n*(t.alpha()-e.alpha()))},x.interpolate=I,r.prototype.interpolate=function(e,t,n){return I(this,e,t,n)},x.mix=I,r.prototype.mix=r.prototype.interpolate,h.rgb=function(){var e,t,n,o;t=Te(arguments),n=[];for(e in t)o=t[e],n.push(o);return n},x.rgb=function(){return function(e,t,n){n.prototype=e.prototype;var o=new n,r=e.apply(o,t);return Object(r)===r?r:o}(r,Me.call(arguments).concat(["rgb"]),function(){})},r.prototype.rgb=function(e){return null==e&&(e=!0),e?this._rgb.map(Math.round).slice(0,3):this._rgb.slice(0,3)},r.prototype.rgba=function(e){return null==e&&(e=!0),e?[Math.round(this._rgb[0]),Math.round(this._rgb[1]),Math.round(this._rgb[2]),this._rgb[3]]:this._rgb.slice(0)},f.push({p:3,test:function(e){var t;return t=Te(arguments),"array"===ke(t)&&3===t.length?"rgb":4===t.length&&"number"===ke(t[3])&&t[3]>=0&&t[3]<=1?"rgb":void 0}}),h.lrgb=h.rgb,U=function(e,t,n,o){var i,a;return i=e._rgb,a=t._rgb,new r(Ce(ie(i[0],2)*(1-n)+ie(a[0],2)*n),Ce(ie(i[1],2)*(1-n)+ie(a[1],2)*n),Ce(ie(i[2],2)*(1-n)+ie(a[2],2)*n),o)},p=function(e){var t,n,o,i,a,s;for(n=1/e.length,s=[0,0,0,0],i=0,o=e.length;i<o;i++)t=e[i],a=t._rgb,s[0]+=ie(a[0],2)*n,s[1]+=ie(a[1],2)*n,s[2]+=ie(a[2],2)*n,s[3]+=a[3]*n;return s[0]=Ce(s[0]),s[1]=Ce(s[1]),s[2]=Ce(s[2]),s[3]>1&&(s[3]=1),new r(C(s))},b.push(["lrgb",U]),x.average=function(e,t){var n,o,r,i,a,u,l,c,f,d,h,b,v;if(null==t&&(t="rgb"),f=e.length,e=e.map(function(e){return x(e)}),l=e.splice(0,1)[0],"lrgb"===t)return p(e);b=l.get(t),i=[],a=0,u=0;for(c in b)b[c]=b[c]||0,i.push(isNaN(b[c])?0:1),"h"!==t.charAt(c)||isNaN(b[c])||(n=b[c]/180*s,a+=k(n),u+=xe(n));for(o=l.alpha(),h=0,d=e.length;h<d;h++){r=e[h],v=r.get(t),o+=r.alpha();for(c in b)isNaN(v[c])||(i[c]+=1,"h"===t.charAt(c)?(n=v[c]/180*s,a+=k(n),u+=xe(n)):b[c]+=v[c])}for(c in b)if("h"===t.charAt(c)){for(n=g(u/i[c],a/i[c])/s*180;n<0;)n+=360;for(;n>=360;)n-=360;b[c]=n}else b[c]=b[c]/i[c];return x(b,t).alpha(o/f)},F=function(e){var t,n,o,r,i,a;if(e.match(/^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/))return 4!==e.length&&7!==e.length||(e=e.substr(1)),3===e.length&&(e=e.split(""),e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]),a=parseInt(e,16),r=a>>16,o=a>>8&255,n=255&a,[r,o,n,1];if(e.match(/^#?([A-Fa-f0-9]{8})$/))return 9===e.length&&(e=e.substr(1)),a=parseInt(e,16),r=a>>24&255,o=a>>16&255,n=a>>8&255,t=we((255&a)/255*100)/100,[r,o,n,t];if(null!=h.css&&(i=h.css(e)))return i;throw"unknown color: "+e},le=function(e,t){var n,o,r,i,a,s,u;return null==t&&(t="auto"),a=e[0],r=e[1],o=e[2],n=e[3],"auto"===t&&(t=n<1?"rgba":"rgb"),a=Math.round(a),r=Math.round(r),o=Math.round(o),u=a<<16|r<<8|o,s="000000"+u.toString(16),s=s.substr(s.length-6),i="0"+we(255*n).toString(16),i=i.substr(i.length-2),"#"+function(){switch(t.toLowerCase()){case"rgba":return s+i;case"argb":return i+s;default:return s}}()},h.hex=function(e){return F(e)},x.hex=function(){return function(e,t,n){n.prototype=e.prototype;var o=new n,r=e.apply(o,t);return Object(r)===r?r:o}(r,Me.call(arguments).concat(["hex"]),function(){})},r.prototype.hex=function(e){return null==e&&(e="auto"),le(this._rgb,e)},f.push({p:4,test:function(e){if(1===arguments.length&&"string"===ke(e))return"hex"}}),R=function(){var e,t,n,o,r,i,a,s,u,l,c,p,f,d;if(e=Te(arguments),r=e[0],c=e[1],a=e[2],0===c)u=o=t=255*a;else{for(d=[0,0,0],n=[0,0,0],f=a<.5?a*(1+c):a+c-a*c,p=2*a-f,r/=360,d[0]=r+1/3,d[1]=r,d[2]=r-1/3,i=s=0;s<=2;i=++s)d[i]<0&&(d[i]+=1),d[i]>1&&(d[i]-=1),6*d[i]<1?n[i]=p+6*(f-p)*d[i]:2*d[i]<1?n[i]=f:3*d[i]<2?n[i]=p+(f-p)*(2/3-d[i])*6:n[i]=p;l=[we(255*n[0]),we(255*n[1]),we(255*n[2])],u=l[0],o=l[1],t=l[2]}return e.length>3?[u,o,t,e[3]]:[u,o,t]},pe=function(e,t,n){var o,r,i,a,s;return void 0!==e&&e.length>=3&&(a=e,e=a[0],t=a[1],n=a[2]),e/=255,t/=255,n/=255,i=Math.min(e,t,n),ee=Math.max(e,t,n),r=(ee+i)/2,ee===i?(s=0,o=Number.NaN):s=r<.5?(ee-i)/(ee+i):(ee-i)/(2-ee-i),e===ee?o=(t-n)/(ee-i):t===ee?o=2+(n-e)/(ee-i):n===ee&&(o=4+(e-t)/(ee-i)),o*=60,o<0&&(o+=360),[o,s,r]},x.hsl=function(){return function(e,t,n){n.prototype=e.prototype;var o=new n,r=e.apply(o,t);return Object(r)===r?r:o}(r,Me.call(arguments).concat(["hsl"]),function(){})},h.hsl=R,r.prototype.hsl=function(){return pe(this._rgb)},L=function(){var e,t,n,o,r,i,a,s,u,l,c,p,f,d,h,b,v,g;if(e=Te(arguments),r=e[0],b=e[1],g=e[2],g*=255,0===b)u=o=t=g;else switch(360===r&&(r=0),r>360&&(r-=360),r<0&&(r+=360),r/=60,i=M(r),n=r-i,a=g*(1-b),s=g*(1-b*n),v=g*(1-b*(1-n)),i){case 0:l=[g,v,a],u=l[0],o=l[1],t=l[2];break;case 1:c=[s,g,a],u=c[0],o=c[1],t=c[2];break;case 2:p=[a,g,v],u=p[0],o=p[1],t=p[2];break;case 3:f=[a,s,g],u=f[0],o=f[1],t=f[2];break;case 4:d=[v,a,g],u=d[0],o=d[1],t=d[2];break;case 5:h=[g,a,s],u=h[0],o=h[1],t=h[2]}return[u,o,t,e.length>3?e[3]:1]},fe=function(){var e,t,n,o,r,i,a,s,u;return a=Te(arguments),i=a[0],n=a[1],e=a[2],r=Math.min(i,n,e),ee=Math.max(i,n,e),t=ee-r,u=ee/255,0===ee?(o=Number.NaN,s=0):(s=t/ee,i===ee&&(o=(n-e)/t),n===ee&&(o=2+(e-i)/t),e===ee&&(o=4+(i-n)/t),(o*=60)<0&&(o+=360)),[o,s,u]},x.hsv=function(){return function(e,t,n){n.prototype=e.prototype;var o=new n,r=e.apply(o,t);return Object(r)===r?r:o}(r,Me.call(arguments).concat(["hsv"]),function(){})},h.hsv=L,r.prototype.hsv=function(){return fe(this._rgb)},oe=function(e){var t,n,o;return"number"===ke(e)&&e>=0&&e<=16777215?(o=e>>16,n=e>>8&255,t=255&e,[o,n,t,1]):(console.warn("unknown num color: "+e),[0,0,0,1])},ve=function(){var e,t,n,o;return o=Te(arguments),n=o[0],t=o[1],e=o[2],(n<<16)+(t<<8)+e},x.num=function(e){return new r(e,"num")},r.prototype.num=function(e){return null==e&&(e="rgb"),ve(this._rgb,e)},h.num=oe,f.push({p:1,test:function(e){if(1===arguments.length&&"number"===ke(e)&&e>=0&&e<=16777215)return"num"}}),D=function(){var e,t,n,o,r,i,a,s,u,l,c,p,f,d,h,b,v,g,m,y;if(n=Te(arguments),s=n[0],r=n[1],t=n[2],r/=100,a=a/100*255,e=255*r,0===r)p=a=o=t;else switch(360===s&&(s=0),s>360&&(s-=360),s<0&&(s+=360),s/=60,u=M(s),i=s-u,l=t*(1-r),c=l+e*(1-i),m=l+e*i,y=l+e,u){case 0:f=[y,m,l],p=f[0],a=f[1],o=f[2];break;case 1:d=[c,y,l],p=d[0],a=d[1],o=d[2];break;case 2:h=[l,y,m],p=h[0],a=h[1],o=h[2];break;case 3:b=[l,c,y],p=b[0],a=b[1],o=b[2];break;case 4:v=[m,l,y],p=v[0],a=v[1],o=v[2];break;case 5:g=[y,l,c],p=g[0],a=g[1],o=g[2]}return[p,a,o,n.length>3?n[3]:1]},ue=function(){var e,t,n,o,r,i,a,s,u;return u=Te(arguments),s=u[0],r=u[1],t=u[2],a=Math.min(s,r,t),ee=Math.max(s,r,t),o=ee-a,n=100*o/255,e=a/(255-o)*100,0===o?i=Number.NaN:(s===ee&&(i=(r-t)/o),r===ee&&(i=2+(t-s)/o),t===ee&&(i=4+(s-r)/o),(i*=60)<0&&(i+=360)),[i,n,e]},x.hcg=function(){return function(e,t,n){n.prototype=e.prototype;var o=new n,r=e.apply(o,t);return Object(r)===r?r:o}(r,Me.call(arguments).concat(["hcg"]),function(){})},h.hcg=D,r.prototype.hcg=function(){return ue(this._rgb)},T=function(e){var t,n,o,r,i,a,s,u;if(e=e.toLowerCase(),null!=x.colors&&x.colors[e])return F(x.colors[e]);if(i=e.match(/rgb\(\s*(\-?\d+),\s*(\-?\d+)\s*,\s*(\-?\d+)\s*\)/)){for(s=i.slice(1,4),r=a=0;a<=2;r=++a)s[r]=+s[r];s[3]=1}else if(i=e.match(/rgba\(\s*(\-?\d+),\s*(\-?\d+)\s*,\s*(\-?\d+)\s*,\s*([01]|[01]?\.\d+)\)/))for(s=i.slice(1,5),r=u=0;u<=3;r=++u)s[r]=+s[r];else if(i=e.match(/rgb\(\s*(\-?\d+(?:\.\d+)?)%,\s*(\-?\d+(?:\.\d+)?)%\s*,\s*(\-?\d+(?:\.\d+)?)%\s*\)/)){for(s=i.slice(1,4),r=t=0;t<=2;r=++t)s[r]=we(2.55*s[r]);s[3]=1}else if(i=e.match(/rgba\(\s*(\-?\d+(?:\.\d+)?)%,\s*(\-?\d+(?:\.\d+)?)%\s*,\s*(\-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)/)){for(s=i.slice(1,5),r=n=0;n<=2;r=++n)s[r]=we(2.55*s[r]);s[3]=+s[3]}else(i=e.match(/hsl\(\s*(\-?\d+(?:\.\d+)?),\s*(\-?\d+(?:\.\d+)?)%\s*,\s*(\-?\d+(?:\.\d+)?)%\s*\)/))?(o=i.slice(1,4),o[1]*=.01,o[2]*=.01,s=R(o),s[3]=1):(i=e.match(/hsla\(\s*(\-?\d+(?:\.\d+)?),\s*(\-?\d+(?:\.\d+)?)%\s*,\s*(\-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)/))&&(o=i.slice(1,4),o[1]*=.01,o[2]*=.01,s=R(o),s[3]=+i[4]);return s},se=function(e){var t;return t=e[3]<1?"rgba":"rgb","rgb"===t?t+"("+e.slice(0,3).map(we).join(",")+")":"rgba"===t?t+"("+e.slice(0,3).map(we).join(",")+","+e[3]+")":void 0},Ee=function(e){return we(100*e)/100},j=function(e,t){var n;return n=t<1?"hsla":"hsl",e[0]=Ee(e[0]||0),e[1]=Ee(100*e[1])+"%",e[2]=Ee(100*e[2])+"%","hsla"===n&&(e[3]=t),n+"("+e.join(",")+")"},h.css=function(e){return T(e)},x.css=function(){return function(e,t,n){n.prototype=e.prototype;var o=new n,r=e.apply(o,t);return Object(r)===r?r:o}(r,Me.call(arguments).concat(["css"]),function(){})},r.prototype.css=function(e){return null==e&&(e="rgb"),"rgb"===e.slice(0,3)?se(this._rgb):"hsl"===e.slice(0,3)?j(this.hsl(),this.alpha()):void 0},h.named=function(e){return F(Ae[e])},f.push({p:5,test:function(e){if(1===arguments.length&&null!=Ae[e])return"named"}}),r.prototype.name=function(e){var t,n;arguments.length&&(Ae[e]&&(this._rgb=F(Ae[e])),this._rgb[3]=1),t=this.hex("rgb");for(n in Ae)if(t===Ae[n])return n;return t},Y=function(){var e,t,n,o;return o=Te(arguments),n=o[0],e=o[1],t=o[2],t*=i,[n,k(t)*e,xe(t)*e]},G=function(){var e,t,n,o,r,i,a,s,u,l,c;return n=Te(arguments),s=n[0],r=n[1],a=n[2],l=Y(s,r,a),e=l[0],t=l[1],o=l[2],c=K(e,t,o),u=c[0],i=c[1],o=c[2],[u,i,o,n.length>3?n[3]:1]},z=function(){var e,t,n,o,r,i;return i=Te(arguments),r=i[0],e=i[1],t=i[2],n=Ce(e*e+t*t),o=(g(t,e)*l+360)%360,0===we(1e4*n)&&(o=Number.NaN),[r,n,o]},he=function(){var e,t,n,o,r,i,a;return i=Te(arguments),r=i[0],n=i[1],t=i[2],a=de(r,n,t),o=a[0],e=a[1],t=a[2],z(o,e,t)},x.lch=function(){var e;return e=Te(arguments),new r(e,"lch")},x.hcl=function(){var e;return e=Te(arguments),new r(e,"hcl")},h.lch=G,h.hcl=function(){var e,t,n,o;return o=Te(arguments),t=o[0],e=o[1],n=o[2],G([n,e,t])},r.prototype.lch=function(){return he(this._rgb)},r.prototype.hcl=function(){return he(this._rgb).reverse()},ae=function(e){var t,n,o,r,i,a,s,u,l;return null==e&&(e="rgb"),u=Te(arguments),s=u[0],r=u[1],t=u[2],s/=255,r/=255,t/=255,i=1-Math.max(s,Math.max(r,t)),o=i<1?1/(1-i):0,n=(1-s-i)*o,a=(1-r-i)*o,l=(1-t-i)*o,[n,a,l,i]},S=function(){var e,t,n,o,r,i,a,s,u;return t=Te(arguments),o=t[0],a=t[1],u=t[2],i=t[3],e=t.length>4?t[4]:1,1===i?[0,0,0,e]:(s=o>=1?0:255*(1-o)*(1-i),r=a>=1?0:255*(1-a)*(1-i),n=u>=1?0:255*(1-u)*(1-i),[s,r,n,e])},h.cmyk=function(){return S(Te(arguments))},x.cmyk=function(){return function(e,t,n){n.prototype=e.prototype;var o=new n,r=e.apply(o,t);return Object(r)===r?r:o}(r,Me.call(arguments).concat(["cmyk"]),function(){})},r.prototype.cmyk=function(){return ae(this._rgb)},h.gl=function(){var e,t,n,o,r;for(o=function(){var e,n;e=Te(arguments),n=[];for(t in e)r=e[t],n.push(r);return n}.apply(this,arguments),e=n=0;n<=2;e=++n)o[e]*=255;return o},x.gl=function(){return function(e,t,n){n.prototype=e.prototype;var o=new n,r=e.apply(o,t);return Object(r)===r?r:o}(r,Me.call(arguments).concat(["gl"]),function(){})},r.prototype.gl=function(){var e;return e=this._rgb,[e[0]/255,e[1]/255,e[2]/255,e[3]]},be=function(e,t,n){var o;return o=Te(arguments),e=o[0],t=o[1],n=o[2],e=$(e),t=$(t),n=$(n),.2126*e+.7152*t+.0722*n},$=function(e){return e/=255,e<=.03928?e/12.92:ie((e+.055)/1.055,2.4)},H=function(e,t,n,o){var i,a;return i=e._rgb,a=t._rgb,new r(i[0]+n*(a[0]-i[0]),i[1]+n*(a[1]-i[1]),i[2]+n*(a[2]-i[2]),o)},b.push(["rgb",H]),r.prototype.luminance=function(e,t){var n,o,r,i,a;return null==t&&(t="rgb"),arguments.length?(i=this._rgb,0===e?i=[0,0,0,this._rgb[3]]:1===e?i=[255,255,255,this[3]]:(n=be(this._rgb),o=1e-7,r=20,a=function(n,i){var s,u;return u=n.interpolate(i,.5,t),s=u.luminance(),Math.abs(e-s)<o||!r--?u:s>e?a(n,u):a(u,i)},i=n>e?a(x("black"),this).rgba():a(this,x("white")).rgba()),x(i).alpha(this.alpha())):be(this._rgb)},Se=function(e){var t,n,o,r;return r=e/100,r<66?(o=255,n=-155.25485562709179-.44596950469579133*(n=r-2)+104.49216199393888*J(n),t=r<20?0:.8274096064007395*(t=r-10)-254.76935184120902+115.67994401066147*J(t)):(o=351.97690566805693+.114206453784165*(o=r-55)-40.25366309332127*J(o),n=325.4494125711974+.07943456536662342*(n=r-50)-28.0852963507957*J(n),t=255),[o,n,t]},ge=function(){var e,t,n,o,r,i,a,s;for(i=Te(arguments),r=i[0],i[1],e=i[2],o=1e3,n=4e4,t=.4;n-o>t;)s=.5*(n+o),a=Se(s),a[2]/a[0]>=e/r?n=s:o=s;return we(s)},x.temperature=x.kelvin=function(){return function(e,t,n){n.prototype=e.prototype;var o=new n,r=e.apply(o,t);return Object(r)===r?r:o}(r,Me.call(arguments).concat(["temperature"]),function(){})},h.temperature=h.kelvin=h.K=Se,r.prototype.temperature=function(){return ge(this._rgb)},r.prototype.kelvin=r.prototype.temperature,x.contrast=function(e,t){var n,o,i,a;return"string"!==(i=ke(e))&&"number"!==i||(e=new r(e)),"string"!==(a=ke(t))&&"number"!==a||(t=new r(t)),n=e.luminance(),o=t.luminance(),n>o?(n+.05)/(o+.05):(o+.05)/(n+.05)},x.distance=function(e,t,n){var o,i,a,s,u,l,c;null==n&&(n="lab"),"string"!==(u=ke(e))&&"number"!==u||(e=new r(e)),"string"!==(l=ke(t))&&"number"!==l||(t=new r(t)),a=e.get(n),s=t.get(n),c=0;for(i in a)o=(a[i]||0)-(s[i]||0),c+=o*o;return Math.sqrt(c)},x.deltaE=function(e,t,n,o){var i,a,u,l,c,p,f,d,h,b,m,y,E,w,O,x,C,S,T,A,_,P,M,D,F,N,j;for(null==n&&(n=1),null==o&&(o=1),"string"!==(C=ke(e))&&"number"!==C||(e=new r(e)),"string"!==(S=ke(t))&&"number"!==S||(t=new r(t)),T=e.lab(),i=T[0],u=T[1],c=T[2],A=t.lab(),a=A[0],l=A[1],p=A[2],f=Ce(u*u+c*c),d=Ce(l*l+p*p),M=i<16?.511:.040975*i/(1+.01765*i),_=.0638*f/(1+.0131*f)+.638,x=f<1e-6?0:180*g(c,u)/s;x<0;)x+=360;for(;x>=360;)x-=360;return D=x>=164&&x<=345?.56+v(.2*k(s*(x+168)/180)):.36+v(.4*k(s*(x+35)/180)),h=f*f*f*f,O=Ce(h/(h+1900)),P=_*(O*D+1-O),w=i-a,E=f-d,m=u-l,y=c-p,b=m*m+y*y-E*E,F=w/(n*M),N=E/(o*_),j=P,Ce(F*F+N*N+b/(j*j))},r.prototype.get=function(e){var t,n,o,r,i,a;return o=this,i=e.split("."),r=i[0],t=i[1],a=o[r](),t?(n=r.indexOf(t),n>-1?a[n]:console.warn("unknown channel "+t+" in mode "+r)):a},r.prototype.set=function(e,t){var n,o,r,i,a,s;if(r=this,a=e.split("."),i=a[0],n=a[1],n)if(s=r[i](),(o=i.indexOf(n))>-1)if("string"===ke(t))switch(t.charAt(0)){case"+":case"-":s[o]+=+t;break;case"*":s[o]*=+t.substr(1);break;case"/":s[o]/=+t.substr(1);break;default:s[o]=+t}else s[o]=t;else console.warn("unknown channel "+n+" in mode "+i);else s=t;return x(s,i).alpha(r.alpha())},r.prototype.clipped=function(){return this._rgb._clipped||!1},r.prototype.alpha=function(e){return arguments.length?x.rgb([this._rgb[0],this._rgb[1],this._rgb[2],e]):this._rgb[3]},r.prototype.darken=function(e){var t,n;return null==e&&(e=1),n=this,t=n.lab(),t[0]-=a.Kn*e,x.lab(t).alpha(n.alpha())},r.prototype.brighten=function(e){return null==e&&(e=1),this.darken(-e)},r.prototype.darker=r.prototype.darken,r.prototype.brighter=r.prototype.brighten,r.prototype.saturate=function(e){var t,n;return null==e&&(e=1),n=this,t=n.lch(),t[1]+=e*a.Kn,t[1]<0&&(t[1]=0),x.lch(t).alpha(n.alpha())},r.prototype.desaturate=function(e){return null==e&&(e=1),this.saturate(-e)},r.prototype.premultiply=function(){var e,t;return t=this.rgb(),e=this.alpha(),x(t[0]*e,t[1]*e,t[2]*e,e)},y=function(e,t,n){if(!y[n])throw"unknown blend mode "+n;return y[n](e,t)},E=function(e){return function(t,n){var o,r;return o=x(n).rgb(),r=x(t).rgb(),x(e(o,r),"rgb")}},P=function(e){return function(t,n){var o,r,i;for(i=[],o=r=0;r<=3;o=++r)i[o]=e(t[o],n[o]);return i}},ne=function(e,t){return e},te=function(e,t){return e*t/255},A=function(e,t){return e>t?t:e},X=function(e,t){return e>t?e:t},Oe=function(e,t){return 255*(1-(1-e/255)*(1-t/255))},re=function(e,t){return t<128?2*e*t/255:255*(1-2*(1-e/255)*(1-t/255))},O=function(e,t){return 255*(1-(1-t/255)/(e/255))},_=function(e,t){return 255===e?255:(e=t/255*255/(1-e/255),e>255?255:e)},y.normal=E(P(ne)),y.multiply=E(P(te)),y.screen=E(P(Oe)),y.overlay=E(P(re)),y.darken=E(P(A)),y.lighten=E(P(X)),y.dodge=E(P(_)),y.burn=E(P(O)),x.blend=y,x.analyze=function(e){var t,n,o,r;for(o={min:Number.MAX_VALUE,max:-1*Number.MAX_VALUE,sum:0,values:[],count:0},n=0,t=e.length;n<t;n++)null==(r=e[n])||isNaN(r)||(o.values.push(r),o.sum+=r,r<o.min&&(o.min=r),r>o.max&&(o.max=r),o.count+=1);return o.domain=[o.min,o.max],o.limits=function(e,t){return x.limits(o,e,t)},o},x.scale=function(e,t){var n,o,r,i,a,s,u,l,c,p,f,d,h,b,v,g,m,y,E,w,O;return c="rgb",p=x("#ccc"),b=0,!1,a=[0,1],h=[],d=[0,0],n=!1,r=[],f=!1,l=0,u=1,i=!1,o={},v=!0,s=1,w=function(e){var t,n,o,i,a,s;if(null==e&&(e=["#fff","#000"]),null!=e&&"string"===ke(e)&&null!=x.brewer&&(e=x.brewer[e]||x.brewer[e.toLowerCase()]||e),"array"===ke(e)){for(1===e.length&&(e=[e[0],e[0]]),e=e.slice(0),t=o=0,i=e.length-1;0<=i?o<=i:o>=i;t=0<=i?++o:--o)n=e[t],"string"===ke(n)&&(e[t]=x(n));for(h.length=0,t=s=0,a=e.length-1;0<=a?s<=a:s>=a;t=0<=a?++s:--s)h.push(t/(e.length-1))}return E(),r=e},m=function(e){var t,o;if(null!=n){for(o=n.length-1,t=0;t<o&&e>=n[t];)t++;return t-1}return 0},O=function(e){return e},function(e){var t,o,r,i,a;return a=e,n.length>2&&(i=n.length-1,t=m(e),r=n[0]+(n[1]-n[0])*(0+.5*b),o=n[i-1]+(n[i]-n[i-1])*(1-.5*b),a=l+(n[t]+.5*(n[t+1]-n[t])-r)/(o-r)*(u-l)),a},y=function(e,t){var i,a,f,b,g,y,E,w;if(null==t&&(t=!1),isNaN(e)||null===e)return p;if(t?w=e:n&&n.length>2?(i=m(e),w=i/(n.length-2)):w=u!==l?(e-l)/(u-l):1,t||(w=O(w)),1!==s&&(w=ie(w,s)),w=d[0]+w*(1-d[0]-d[1]),w=Math.min(1,Math.max(0,w)),b=Math.floor(1e4*w),v&&o[b])a=o[b];else{if("array"===ke(r))for(f=g=0,E=h.length-1;0<=E?g<=E:g>=E;f=0<=E?++g:--g){if(y=h[f],w<=y){a=r[f];break}if(w>=y&&f===h.length-1){a=r[f];break}if(w>y&&w<h[f+1]){w=(w-y)/(h[f+1]-y),a=x.interpolate(r[f],r[f+1],w,c);break}}else"function"===ke(r)&&(a=r(w));v&&(o[b]=a)}return a},E=function(){return o={}},w(e),g=function(e){var t;return t=x(y(e)),f&&t[f]?t[f]():t},g.classes=function(e){var t;return null!=e?("array"===ke(e)?(n=e,a=[e[0],e[e.length-1]]):(t=x.analyze(a),n=0===e?[t.min,t.max]:x.limits(t,"e",e)),g):n},g.domain=function(e){var t,n,o,i,s,c,p;if(!arguments.length)return a;if(l=e[0],u=e[e.length-1],h=[],o=r.length,e.length===o&&l!==u)for(s=0,i=e.length;s<i;s++)n=e[s],h.push((n-l)/(u-l));else for(t=p=0,c=o-1;0<=c?p<=c:p>=c;t=0<=c?++p:--p)h.push(t/(o-1));return a=[l,u],g},g.mode=function(e){return arguments.length?(c=e,E(),g):c},g.range=function(e,t){return w(e,t),g},g.out=function(e){return f=e,g},g.spread=function(e){return arguments.length?(b=e,g):b},g.correctLightness=function(e){return null==e&&(e=!0),i=e,E(),O=i?function(e){var t,n,o,r,i,a,s,u,l;for(t=y(0,!0).lab()[0],n=y(1,!0).lab()[0],s=t>n,o=y(e,!0).lab()[0],i=t+(n-t)*e,r=o-i,u=0,l=1,a=20;Math.abs(r)>.01&&a-- >0;)!function(){s&&(r*=-1),r<0?(u=e,e+=.5*(l-e)):(l=e,e+=.5*(u-e)),o=y(e,!0).lab()[0],r=o-i}();return e}:function(e){return e},g},g.padding=function(e){return null!=e?("number"===ke(e)&&(e=[e,e]),d=e,g):d},g.colors=function(t,o){var i,s,u,l,c,p,f,d;if(arguments.length<2&&(o="hex"),c=[],0===arguments.length)c=r.slice(0);else if(1===t)c=[g(.5)];else if(t>1)s=a[0],i=a[1]-s,c=function(){p=[];for(var e=0;0<=t?e<t:e>t;0<=t?e++:e--)p.push(e);return p}.apply(this).map(function(e){return g(s+e/(t-1)*i)});else{if(e=[],f=[],n&&n.length>2)for(u=d=1,l=n.length;1<=l?d<l:d>l;u=1<=l?++d:--d)f.push(.5*(n[u-1]+n[u]));else f=a;c=f.map(function(e){return g(e)})}return x[o]&&(c=c.map(function(e){return e[o]()})),c},g.cache=function(e){return null!=e?(v=e,g):v},g.gamma=function(e){return null!=e?(s=e,g):s},g.nodata=function(e){return null!=e?(p=x(e),g):p},g},null==x.scales&&(x.scales={}),x.scales.cool=function(){return x.scale([x.hsl(180,1,.9),x.hsl(250,.7,.4)])},x.scales.hot=function(){return x.scale(["#000","#f00","#ff0","#fff"],[0,.25,.75,1]).mode("rgb")},x.analyze=function(e,t,n){var o,r,i,a,s,u,l;if(s={min:Number.MAX_VALUE,max:-1*Number.MAX_VALUE,sum:0,values:[],count:0},null==n&&(n=function(){return!0}),o=function(e){null==e||isNaN(e)||(s.values.push(e),s.sum+=e,e<s.min&&(s.min=e),e>s.max&&(s.max=e),s.count+=1)},l=function(e,r){if(n(e,r))return o(null!=t&&"function"===ke(t)?t(e):null!=t&&"string"===ke(t)||"number"===ke(t)?e[t]:e)},"array"===ke(e))for(a=0,i=e.length;a<i;a++)u=e[a],l(u);else for(r in e)u=e[r],l(u,r);return s.domain=[s.min,s.max],s.limits=function(e,t){return x.limits(s,e,t)},s},x.limits=function(e,t,n){var o,r,i,a,s,u,l,c,p,f,d,h,b,g,m,y,E,w,O,C,S,k,T,A,_,P,D,F,N,j,R,L,I,V,B,U,W,H,z,K,q,Y,G,X,Z,$,Q,te,ne,oe,re,ae,se,ue,le;if(null==t&&(t="equal"),null==n&&(n=7),"array"===ke(e)&&(e=x.analyze(e)),_=e.min,ee=e.max,e.sum,ue=e.values.sort(function(e,t){return e-t}),1===n)return[_,ee];if(T=[],"c"===t.substr(0,1)&&(T.push(_),T.push(ee)),"e"===t.substr(0,1)){for(T.push(_),C=R=1,B=n-1;1<=B?R<=B:R>=B;C=1<=B?++R:--R)T.push(_+C/n*(ee-_));T.push(ee)}else if("l"===t.substr(0,1)){if(_<=0)throw"Logarithmic scales are only possible for values > 0";for(P=Math.LOG10E*J(_),A=Math.LOG10E*J(ee),T.push(_),C=le=1,U=n-1;1<=U?le<=U:le>=U;C=1<=U?++le:--le)T.push(ie(10,P+C/n*(A-P)));T.push(ee)}else if("q"===t.substr(0,1)){for(T.push(_),C=o=1,Y=n-1;1<=Y?o<=Y:o>=Y;C=1<=Y?++o:--o)L=(ue.length-1)*C/n,I=M(L),I===L?T.push(ue[I]):(V=L-I,T.push(ue[I]*(1-V)+ue[I+1]*V));T.push(ee)}else if("k"===t.substr(0,1)){for(F=ue.length,g=new Array(F),w=new Array(n),oe=!0,N=0,y=null,y=[],y.push(_),C=r=1,G=n-1;1<=G?r<=G:r>=G;C=1<=G?++r:--r)y.push(_+C/n*(ee-_));for(y.push(ee);oe;){for(S=i=0,X=n-1;0<=X?i<=X:i>=X;S=0<=X?++i:--i)w[S]=0;for(C=a=0,Z=F-1;0<=Z?a<=Z:a>=Z;C=0<=Z?++a:--a){for(se=ue[C],D=Number.MAX_VALUE,S=s=0,$=n-1;0<=$?s<=$:s>=$;S=0<=$?++s:--s)(O=v(y[S]-se))<D&&(D=O,m=S);w[m]++,g[C]=m}for(j=new Array(n),S=u=0,Q=n-1;0<=Q?u<=Q:u>=Q;S=0<=Q?++u:--u)j[S]=null;for(C=l=0,te=F-1;0<=te?l<=te:l>=te;C=0<=te?++l:--l)E=g[C],null===j[E]?j[E]=ue[C]:j[E]+=ue[C];for(S=c=0,ne=n-1;0<=ne?c<=ne:c>=ne;S=0<=ne?++c:--c)j[S]*=1/w[S];for(oe=!1,S=p=0,W=n-1;0<=W?p<=W:p>=W;S=0<=W?++p:--p)if(j[S]!==y[C]){oe=!0;break}y=j,N++,N>200&&(oe=!1)}for(k={},S=f=0,H=n-1;0<=H?f<=H:f>=H;S=0<=H?++f:--f)k[S]=[];for(C=d=0,z=F-1;0<=z?d<=z:d>=z;C=0<=z?++d:--d)E=g[C],k[E].push(ue[C]);for(re=[],S=h=0,K=n-1;0<=K?h<=K:h>=K;S=0<=K?++h:--h)re.push(k[S][0]),re.push(k[S][k[S].length-1]);for(re=re.sort(function(e,t){return e-t}),T.push(re[0]),C=b=1,q=re.length-1;b<=q;C=b+=2)ae=re[C],isNaN(ae)||-1!==T.indexOf(ae)||T.push(ae)}return T},N=function(e,t,n){var o,r,i,a;return o=Te(arguments),e=o[0],t=o[1],n=o[2],isNaN(e)&&(e=0),e/=360,e<1/3?(r=(1-t)/3,a=(1+t*k(c*e)/k(u-c*e))/3,i=1-(r+a)):e<2/3?(e-=1/3,a=(1-t)/3,i=(1+t*k(c*e)/k(u-c*e))/3,r=1-(a+i)):(e-=2/3,i=(1-t)/3,r=(1+t*k(c*e)/k(u-c*e))/3,a=1-(i+r)),a=Z(n*a*3),i=Z(n*i*3),r=Z(n*r*3),[255*a,255*i,255*r,o.length>3?o[3]:1]},ce=function(){var e,t,n,o,r,i,a,s;return a=Te(arguments),i=a[0],t=a[1],e=a[2],c=2*Math.PI,i/=255,t/=255,e/=255,r=Math.min(i,t,e),o=(i+t+e)/3,s=1-r/o,0===s?n=0:(n=(i-t+(i-e))/2,n/=Math.sqrt((i-t)*(i-t)+(i-e)*(t-e)),n=Math.acos(n),e>t&&(n=c-n),n/=c),[360*n,s,o]},x.hsi=function(){return function(e,t,n){n.prototype=e.prototype;var o=new n,r=e.apply(o,t);return Object(r)===r?r:o}(r,Me.call(arguments).concat(["hsi"]),function(){})},h.hsi=N,r.prototype.hsi=function(){return ce(this._rgb)},V=function(e,t,n,o){var r,i,a,s,u,l,c,p,f,d,h,b;return"hsl"===o?(h=e.hsl(),b=t.hsl()):"hsv"===o?(h=e.hsv(),b=t.hsv()):"hcg"===o?(h=e.hcg(),b=t.hcg()):"hsi"===o?(h=e.hsi(),b=t.hsi()):"lch"!==o&&"hcl"!==o||(o="hcl",h=e.hcl(),b=t.hcl()),"h"===o.substr(0,1)&&(a=h[0],f=h[1],l=h[2],s=b[0],d=b[1],c=b[2]),isNaN(a)||isNaN(s)?isNaN(a)?isNaN(s)?i=Number.NaN:(i=s,1!==l&&0!==l||"hsv"===o||(p=d)):(i=a,1!==c&&0!==c||"hsv"===o||(p=f)):(r=s>a&&s-a>180?s-(a+360):s<a&&a-s>180?s+360-a:s-a,i=a+n*r),null==p&&(p=f+n*(d-f)),u=l+n*(c-l),x[o](i,p,u)},b=b.concat(function(){var e,t,n,o;for(n=["hsv","hsl","hsi","hcl","lch","hcg"],o=[],t=0,e=n.length;t<e;t++)Q=n[t],o.push([Q,V]);return o}()),W=function(e,t,n,o){var r,i;return r=e.num(),i=t.num(),x.num(r+(i-r)*n,"num")},b.push(["num",W]),B=function(e,t,n,o){var i,a;return i=e.lab(),a=t.lab(),new r(i[0]+n*(a[0]-i[0]),i[1]+n*(a[1]-i[1]),i[2]+n*(a[2]-i[2]),o)},b.push(["lab",B])}).call(this)}).call(t,n(83)(e))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=n(85);t.default=o.a},function(e,t,n){e.exports=!n(13)&&!n(22)(function(){return 7!=Object.defineProperty(n(59)("div"),"a",{get:function(){return 7}}).a})},function(e,t,n){var o=n(21),r=n(11).document,i=o(r)&&o(r.createElement);e.exports=function(e){return i?r.createElement(e):{}}},function(e,t,n){var o=n(14),r=n(15),i=n(91)(!1),a=n(39)("IE_PROTO");e.exports=function(e,t){var n,s=r(e),u=0,l=[];for(n in s)n!=a&&o(s,n)&&l.push(n);for(;t.length>u;)o(s,n=t[u++])&&(~i(l,n)||l.push(n));return l}},function(e,t,n){var o=n(36);e.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==o(e)?e.split(""):Object(e)}},function(e,t,n){var o=n(38),r=Math.min;e.exports=function(e){return e>0?r(o(e),9007199254740991):0}},function(e,t,n){"use strict";var o=n(95)(!0);n(64)(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,n=this._i;return n>=t.length?{value:void 0,done:!0}:(e=o(t,n),this._i+=e.length,{value:e,done:!1})})},function(e,t,n){"use strict";var o=n(28),r=n(10),i=n(65),a=n(19),s=n(25),u=n(96),l=n(45),c=n(66),p=n(7)("iterator"),f=!([].keys&&"next"in[].keys()),d=function(){return this};e.exports=function(e,t,n,h,b,v,g){u(n,t,h);var m,y,E,w=function(e){if(!f&&e in S)return S[e];switch(e){case"keys":case"values":return function(){return new n(this,e)}}return function(){return new n(this,e)}},O=t+" Iterator",x="values"==b,C=!1,S=e.prototype,k=S[p]||S["@@iterator"]||b&&S[b],T=k||w(b),A=b?x?w("entries"):T:void 0,_="Array"==t?S.entries||k:k;if(_&&(E=c(_.call(new e)))!==Object.prototype&&E.next&&(l(E,O,!0),o||"function"==typeof E[p]||a(E,p,d)),x&&k&&"values"!==k.name&&(C=!0,T=function(){return k.call(this)}),o&&!g||!f&&!C&&S[p]||a(S,p,T),s[t]=T,s[O]=d,b)if(m={values:x?T:w("values"),keys:v?T:w("keys"),entries:A},g)for(y in m)y in S||i(S,y,m[y]);else r(r.P+r.F*(f||C),t,m);return m}},function(e,t,n){e.exports=n(19)},function(e,t,n){var o=n(14),r=n(31),i=n(39)("IE_PROTO"),a=Object.prototype;e.exports=Object.getPrototypeOf||function(e){return e=r(e),o(e,i)?e[i]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?a:null}},function(e,t,n){var o=n(60),r=n(41).concat("length","prototype");t.f=Object.getOwnPropertyNames||function(e){return o(e,r)}},function(e,t,n){"use strict";function o(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}var r=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable;e.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(""))return!1;var o={};return"abcdefghijklmnopqrst".split("").forEach(function(e){o[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},o)).join("")}catch(e){return!1}}()?Object.assign:function(e,t){for(var n,s,u=o(e),l=1;l<arguments.length;l++){n=Object(arguments[l]);for(var c in n)i.call(n,c)&&(u[c]=n[c]);if(r){s=r(n);for(var p=0;p<s.length;p++)a.call(n,s[p])&&(u[s[p]]=n[s[p]])}}return u}},function(e,t,n){e.exports={default:n(129),__esModule:!0}},function(e,t,n){"use strict";function o(e,t,n){return n?e[0]===t[0]:e[0]===t[0]&&e[1]===t[1]}function r(e,t,n){var o=e[t]||{};return u()({},o,n)}function i(e,t,n,r){var i=n.points;for(var a in e)if(e.hasOwnProperty(a)&&o(e[a].points,i,r))return t+"-placement-"+a;return""}function a(e,t){this[e]=t}t.a=r,t.b=i,t.c=a;var s=n(5),u=n.n(s)},function(e,t,n){"use strict";function o(e,t,n){return e.left<n.left||e.left+t.width>n.right}function r(e,t,n){return e.top<n.top||e.top+t.height>n.bottom}function i(e,t,n){return e.left>n.right||e.left+t.width<n.left}function a(e,t,n){return e.top>n.bottom||e.top+t.height<n.top}function s(e,t,n){var o=[];return f.a.each(e,function(e){o.push(e.replace(t,function(e){return n[e]}))}),o}function u(e,t){return e[t]=-e[t],e}function l(e,t){return(/%$/.test(e)?parseInt(e.substring(0,e.length-1),10)/100*t:parseInt(e,10))||0}function c(e,t){e[0]=l(e[0],t.width),e[1]=l(e[1],t.height)}function p(e,t,n,l){var p=n.points,g=n.offset||[0,0],m=n.targetOffset||[0,0],y=n.overflow,E=n.source||e;g=[].concat(g),m=[].concat(m),y=y||{};var w={},O=0,x=Object(d.a)(E),C=Object(b.a)(E);c(g,C),c(m,t);var S=Object(v.a)(C,t,p,g,m),k=f.a.merge(C,S);if(x&&(y.adjustX||y.adjustY)&&l){if(y.adjustX&&o(S,C,x)){var T=s(p,/[lr]/gi,{l:"r",r:"l"}),A=u(g,0),_=u(m,0);i(Object(v.a)(C,t,T,A,_),C,x)||(O=1,p=T,g=A,m=_)}if(y.adjustY&&r(S,C,x)){var P=s(p,/[tb]/gi,{t:"b",b:"t"}),M=u(g,1),D=u(m,1);a(Object(v.a)(C,t,P,M,D),C,x)||(O=1,p=P,g=M,m=D)}O&&(S=Object(v.a)(C,t,p,g,m),f.a.mix(k,S));var F=o(S,C,x),N=r(S,C,x);(F||N)&&(p=n.points,g=n.offset||[0,0],m=n.targetOffset||[0,0]),w.adjustX=y.adjustX&&F,w.adjustY=y.adjustY&&N,(w.adjustX||w.adjustY)&&(k=Object(h.a)(S,C,x,w))}return k.width!==C.width&&f.a.css(E,"width",f.a.width(E)+k.width-C.width),k.height!==C.height&&f.a.css(E,"height",f.a.height(E)+k.height-C.height),f.a.offset(E,{left:k.left,top:k.top},{useCssRight:n.useCssRight,useCssBottom:n.useCssBottom,useCssTransform:n.useCssTransform,ignoreShake:n.ignoreShake}),{points:p,offset:g,targetOffset:m,overflow:w}}var f=n(17),d=n(72),h=n(139),b=n(74),v=n(140);t.a=p},function(e,t,n){"use strict";function o(e){for(var t={left:0,right:1/0,top:0,bottom:1/0},n=Object(i.a)(e),o=r.a.getDocument(e),s=o.defaultView||o.parentWindow,u=o.body,l=o.documentElement;n;){if(-1!==navigator.userAgent.indexOf("MSIE")&&0===n.clientWidth||n===u||n===l||"visible"===r.a.css(n,"overflow")){if(n===u||n===l)break}else{var c=r.a.offset(n);c.left+=n.clientLeft,c.top+=n.clientTop,t.top=Math.max(t.top,c.top),t.right=Math.min(t.right,c.left+n.clientWidth),t.bottom=Math.min(t.bottom,c.top+n.clientHeight),t.left=Math.max(t.left,c.left)}n=Object(i.a)(n)}var p=null;if(!r.a.isWindow(e)&&9!==e.nodeType){p=e.style.position;"absolute"===r.a.css(e,"position")&&(e.style.position="fixed")}var f=r.a.getWindowScrollLeft(s),d=r.a.getWindowScrollTop(s),h=r.a.viewportWidth(s),b=r.a.viewportHeight(s),v=l.scrollWidth,g=l.scrollHeight;if(e.style&&(e.style.position=p),Object(a.a)(e))t.left=Math.max(t.left,f),t.top=Math.max(t.top,d),t.right=Math.min(t.right,f+h),t.bottom=Math.min(t.bottom,d+b);else{var m=Math.max(v,f+h);t.right=Math.min(t.right,m);var y=Math.max(g,d+b);t.bottom=Math.min(t.bottom,y)}return t.top>=0&&t.left>=0&&t.bottom>t.top&&t.right>t.left?t:null}var r=n(17),i=n(73),a=n(138);t.a=o},function(e,t,n){"use strict";function o(e){if(r.a.isWindow(e)||9===e.nodeType)return null;var t=r.a.getDocument(e),n=t.body,o=void 0,i=r.a.css(e,"position");if("fixed"!==i&&"absolute"!==i)return"html"===e.nodeName.toLowerCase()?null:e.parentNode;for(o=e.parentNode;o&&o!==n;o=o.parentNode)if("static"!==(i=r.a.css(o,"position")))return o;return null}var r=n(17);t.a=o},function(e,t,n){"use strict";function o(e){var t=void 0,n=void 0,o=void 0;if(r.a.isWindow(e)||9===e.nodeType){var i=r.a.getWindow(e);t={left:r.a.getWindowScrollLeft(i),top:r.a.getWindowScrollTop(i)},n=r.a.viewportWidth(i),o=r.a.viewportHeight(i)}else t=r.a.offset(e),n=r.a.outerWidth(e),o=r.a.outerHeight(e);return t.width=n,t.height=o,t}var r=n(17);t.a=o},function(e,t){e.exports=function(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0;n<e.length;++n)if(e[n]===t)return n;return-1}},function(e,t,n){"use strict";var o={isAppearSupported:function(e){return e.transitionName&&e.transitionAppear||e.animation.appear},isEnterSupported:function(e){return e.transitionName&&e.transitionEnter||e.animation.enter},isLeaveSupported:function(e){return e.transitionName&&e.transitionLeave||e.animation.leave},allowAppearCallback:function(e){return e.transitionAppear||e.animation.appear},allowEnterCallback:function(e){return e.transitionEnter||e.animation.enter},allowLeaveCallback:function(e){return e.transitionLeave||e.animation.leave}};t.a=o},function(e,t,n){"use strict";var o=n(24),r=n.n(o),i=n(2),a=n.n(i),s=n(3),u=n.n(s),l=n(4),c=n.n(l),p=n(0),f=n.n(p),d=n(1),h=n.n(d),b=function(e){function t(){return a()(this,t),u()(this,e.apply(this,arguments))}return c()(t,e),t.prototype.shouldComponentUpdate=function(e){return e.hiddenClassName||e.visible},t.prototype.render=function(){var e=this.props,t=e.hiddenClassName,n=e.visible,o=r()(e,["hiddenClassName","visible"]);return t||f.a.Children.count(o.children)>1?(!n&&t&&(o.className+=" "+t),f.a.createElement("div",o)):f.a.Children.only(o.children)},t}(p.Component);b.propTypes={children:h.a.any,className:h.a.string,visible:h.a.bool,hiddenClassName:h.a.string},t.a=b},function(e,t,n){"use strict";var o=n(5),r=n.n(o),i=n(0),a=n.n(i),s=function(e){var t=e.className,n=e.included,o=e.vertical,i=e.offset,s=e.length,u=e.style,l=o?{bottom:i+"%",height:s+"%"}:{left:i+"%",width:s+"%"},c=r()({},u,l);return n?a.a.createElement("div",{className:t,style:c}):null};t.a=s},function(e,t,n){"use strict";function o(){}function r(e){var t,n;return n=t=function(e){function t(e){f()(this,t);var n=v()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));if(n.onMouseDown=function(e){if(0===e.button){var t=n.props.vertical,o=F.e(t,e);if(F.h(e,n.handlesRefs)){var r=F.c(t,e.target);n.dragOffset=o-r,o=r}else n.dragOffset=0;n.removeDocumentEvents(),n.onStart(o),n.addDocumentMouseEvents()}},n.onTouchStart=function(e){if(!F.i(e)){var t=n.props.vertical,o=F.f(t,e);if(F.h(e,n.handlesRefs)){var r=F.c(t,e.target);n.dragOffset=o-r,o=r}else n.dragOffset=0;n.onStart(o),n.addDocumentTouchEvents(),F.k(e)}},n.onFocus=function(e){var t=n.props,o=t.onFocus,r=t.vertical;if(F.h(e,n.handlesRefs)){var i=F.c(r,e.target);n.dragOffset=0,n.onStart(i),F.k(e),o&&o(e)}},n.onBlur=function(e){var t=n.props.onBlur;n.onEnd(e),t&&t(e)},n.onMouseUp=function(){n.handlesRefs[n.prevMovedHandleIndex]&&n.handlesRefs[n.prevMovedHandleIndex].clickFocus()},n.onMouseMove=function(e){if(!n.sliderRef)return void n.onEnd();var t=F.e(n.props.vertical,e);n.onMove(e,t-n.dragOffset)},n.onTouchMove=function(e){if(F.i(e)||!n.sliderRef)return void n.onEnd();var t=F.f(n.props.vertical,e);n.onMove(e,t-n.dragOffset)},n.onKeyDown=function(e){n.sliderRef&&F.h(e,n.handlesRefs)&&n.onKeyboard(e)},n.onClickMarkLabel=function(e,t){e.stopPropagation(),n.onChange({value:t}),n.onEnd()},n.saveSlider=function(e){n.sliderRef=e},F.g()){var o=e.step,r=e.max,i=e.min,a=!isFinite(r-i)||(r-i)%o===0;_()(!o||Math.floor(o)!==o||a,"Slider[max] - Slider[min] (%s) should be a multiple of Slider[step] (%s)",r-i,o)}return n.handlesRefs={},n}return E()(t,e),h()(t,[{key:"componentDidMount",value:function(){this.document=this.sliderRef&&this.sliderRef.ownerDocument}},{key:"componentWillUnmount",value:function(){m()(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"componentWillUnmount",this)&&m()(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"componentWillUnmount",this).call(this),this.removeDocumentEvents()}},{key:"getSliderStart",value:function(){var e=this.sliderRef,t=e.getBoundingClientRect();return this.props.vertical?t.top:t.left+window.pageXOffset}},{key:"getSliderLength",value:function(){var e=this.sliderRef;if(!e)return 0;var t=e.getBoundingClientRect();return this.props.vertical?t.height:t.width}},{key:"addDocumentTouchEvents",value:function(){this.onTouchMoveListener=Object(S.a)(this.document,"touchmove",this.onTouchMove),this.onTouchUpListener=Object(S.a)(this.document,"touchend",this.onEnd)}},{key:"addDocumentMouseEvents",value:function(){this.onMouseMoveListener=Object(S.a)(this.document,"mousemove",this.onMouseMove),this.onMouseUpListener=Object(S.a)(this.document,"mouseup",this.onEnd)}},{key:"removeDocumentEvents",value:function(){this.onTouchMoveListener&&this.onTouchMoveListener.remove(),this.onTouchUpListener&&this.onTouchUpListener.remove(),this.onMouseMoveListener&&this.onMouseMoveListener.remove(),this.onMouseUpListener&&this.onMouseUpListener.remove()}},{key:"focus",value:function(){this.props.disabled||this.handlesRefs[0].focus()}},{key:"blur",value:function(){var e=this;this.props.disabled||Object.keys(this.handlesRefs).forEach(function(t){e.handlesRefs[t]&&e.handlesRefs[t].blur&&e.handlesRefs[t].blur()})}},{key:"calcValue",value:function(e){var t=this.props,n=t.vertical,o=t.min,r=t.max,i=Math.abs(Math.max(e,0)/this.getSliderLength());return n?(1-i)*(r-o)+o:i*(r-o)+o}},{key:"calcValueByPos",value:function(e){var t=e-this.getSliderStart();return this.trimAlignValue(this.calcValue(t))}},{key:"calcOffset",value:function(e){var t=this.props,n=t.min;return(e-n)/(t.max-n)*100}},{key:"saveHandle",value:function(e,t){this.handlesRefs[e]=t}},{key:"render",value:function(){var e,n=this.props,r=n.prefixCls,i=n.className,a=n.marks,s=n.dots,l=n.step,p=n.included,f=n.disabled,d=n.vertical,h=n.min,b=n.max,v=n.children,g=n.maximumTrackStyle,y=n.style,E=n.railStyle,w=n.dotStyle,x=n.activeDotStyle,C=m()(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"render",this).call(this),S=C.tracks,k=C.handles,A=T()(r,(e={},c()(e,r+"-with-marks",Object.keys(a).length),c()(e,r+"-disabled",f),c()(e,r+"-vertical",d),c()(e,i,i),e));return O.a.createElement("div",{ref:this.saveSlider,className:A,onTouchStart:f?o:this.onTouchStart,onMouseDown:f?o:this.onMouseDown,onMouseUp:f?o:this.onMouseUp,onKeyDown:f?o:this.onKeyDown,onFocus:f?o:this.onFocus,onBlur:f?o:this.onBlur,style:y},O.a.createElement("div",{className:r+"-rail",style:u()({},g,E)}),S,O.a.createElement(P.a,{prefixCls:r,vertical:d,marks:a,dots:s,step:l,included:p,lowerBound:this.getLowerBound(),upperBound:this.getUpperBound(),max:b,min:h,dotStyle:w,activeDotStyle:x}),k,O.a.createElement(M.a,{className:r+"-mark",onClickLabel:f?o:this.onClickMarkLabel,vertical:d,marks:a,included:p,lowerBound:this.getLowerBound(),upperBound:this.getUpperBound(),max:b,min:h}),v)}}]),t}(e),t.displayName="ComponentEnhancer("+e.displayName+")",t.propTypes=u()({},e.propTypes,{min:C.a.number,max:C.a.number,step:C.a.number,marks:C.a.object,included:C.a.bool,className:C.a.string,prefixCls:C.a.string,disabled:C.a.bool,children:C.a.any,onBeforeChange:C.a.func,onChange:C.a.func,onAfterChange:C.a.func,handle:C.a.func,dots:C.a.bool,vertical:C.a.bool,style:C.a.object,minimumTrackStyle:C.a.object,maximumTrackStyle:C.a.object,handleStyle:C.a.oneOfType([C.a.object,C.a.arrayOf(C.a.object)]),trackStyle:C.a.oneOfType([C.a.object,C.a.arrayOf(C.a.object)]),railStyle:C.a.object,dotStyle:C.a.object,activeDotStyle:C.a.object,autoFocus:C.a.bool,onFocus:C.a.func,onBlur:C.a.func}),t.defaultProps=u()({},e.defaultProps,{prefixCls:"rc-slider",className:"",min:0,max:100,step:1,marks:{},handle:function(e){var t=e.index,n=a()(e,["index"]);return delete n.dragging,null===n.value?null:O.a.createElement(D.a,u()({},n,{key:t}))},onBeforeChange:o,onChange:o,onAfterChange:o,included:!0,disabled:!1,dots:!1,vertical:!1,trackStyle:[{}],handleStyle:[{}],railStyle:{},dotStyle:{},activeDotStyle:{}}),n}t.a=r;var i=n(24),a=n.n(i),s=n(5),u=n.n(s),l=n(18),c=n.n(l),p=n(2),f=n.n(p),d=n(9),h=n.n(d),b=n(3),v=n.n(b),g=n(155),m=n.n(g),y=n(4),E=n.n(y),w=n(0),O=n.n(w),x=n(1),C=n.n(x),S=n(32),k=n(16),T=n.n(k),A=n(50),_=n.n(A),P=n(162),M=n(163),D=n(51),F=n(52)},function(e,t,n){var o=n(10),r=n(6),i=n(22);e.exports=function(e,t){var n=(r.Object||{})[e]||Object[e],a={};a[e]=t(n),o(o.S+o.F*i(function(){n(1)}),"Object",a)}},function(e,t,n){"use strict";t.__esModule=!0;var o=n(164),r=function(e){return e&&e.__esModule?e:{default:e}}(o);t.default=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return(0,r.default)(e)}},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getColorscale=t.COLOR_PICKER_CONSTANTS=t.Colorscale=void 0;var r=n(55),i=o(r),a=n(84),s=o(a),u=n(33),l=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}(u);t.default=s.default,t.Colorscale=i.default,t.COLOR_PICKER_CONSTANTS=l,t.getColorscale=a.getColorscale},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}function r(e,t){var n={};for(var o in e)t.indexOf(o)>=0||Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=e[o]);return n}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==typeof t&&"function"!==typeof t?e:t}function s(e,t){if("function"!==typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function u(e,t,n,o,r){var i=v.default.scale(e).mode("lch");if(o){var a=Array(t).fill().map(function(e,t){return t+1});i=i.classes(v.default.limits(a,"l",n))}var s=i.colors(t);return o||"categorical"!==r||(s=function(e,t){var n=Array.apply(null,new Array(t));return n=n.map(function(){return e}),[].concat.apply([],n)}(e,t).slice(0,t)),s}Object.defineProperty(t,"__esModule",{value:!0}),t.ColorscalePaletteSelector=void 0;var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},c=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}();t.getColorscale=u;var p=n(0),f=o(p),d=n(55),h=o(d),b=n(56),v=o(b),g=n(57),m=o(g),y=n(153),E=o(y),w=n(177),O=o(w);n(179),n(182);var x=n(33);n(184);var C=E.default.Handle,S=function(e){function t(e){i(this,t);var n=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return k.call(n),n.state={colorscale:n.props.colorscale||x.DEFAULT_SCALE,nSwatches:(n.props.colorscale||x.DEFAULT_SCALE).length,previousColorscale:n.props.colorscale||x.DEFAULT_SCALE,colorscaleType:n.props.colorscaleType||n.props.initialColorscaleType,log:!1,logBreakpoints:x.DEFAULT_LOG_BREAKPOINTS,customBreakpoints:x.DEFAULT_BREAKPOINTS,previousCustomBreakpoints:null,cubehelix:{start:x.DEFAULT_START,rotations:x.DEFAULT_ROTATIONS}},n.onClick=n.onClick.bind(n),n.setColorscaleType=n.setColorscaleType.bind(n),n.updateCubehelixStart=n.updateCubehelixStart.bind(n),n.updateCubehelixRotations=n.updateCubehelixRotations.bind(n),n.updateCubehelix=n.updateCubehelix.bind(n),n.toggleLog=n.toggleLog.bind(n),n.handle=n.handle.bind(n),n}return s(t,e),c(t,[{key:"componentDidMount",value:function(){this.setState({colorscaleOnMount:this.props.colorscale})}},{key:"setColorscaleType",value:function(e){var t=e.value;if(t!==this.state.colorscaleType){var n=this.state.log;x.SCALES_WITHOUT_LOG.indexOf(t)>=0&&(n=!1),this.setState({colorscaleType:t,log:n})}}},{key:"renderSwatchControls",value:function(){var e=null,t=null;return this.props.fixSwatches||(e=f.default.createElement("div",{className:"noWrap inlineBlock"},f.default.createElement("span",{className:"textLabel spaceRight"},"Swatches:"),f.default.createElement("span",{className:"textLabel spaceRight"},this.state.nSwatches)),t=f.default.createElement(E.default,{min:1,max:100,defaultValue:this.state.nSwatches,handle:this.handle,onAfterChange:this.updateSwatchNumber})),f.default.createElement("div",null,e,x.SCALES_WITHOUT_LOG.indexOf(this.state.colorscaleType)<0&&f.default.createElement("div",{className:"noWrap inlineBlock alignTop"},f.default.createElement("span",{className:"textLabel spaceRight spaceLeft"},"Log scale"),f.default.createElement("input",{type:"checkbox",name:"log",value:"log",onChange:this.toggleLog,defaultChecked:this.state.log,className:"spaceRightZeroTop alignMiddle"}),this.state.log&&f.default.createElement("span",null,f.default.createElement("span",{className:"textLabel spaceRight spaceLeft"},"Breakpoints:"," "),f.default.createElement("input",{type:"number",step:"1",min:"1",max:"10",value:""+this.state.logBreakpoints,onChange:this.updateBreakpoints}))),t)}},{key:"render",value:function(){var e=x.COLORSCALE_TYPES.map(function(e){return{label:e+" scales",value:e}}),t="colorscalePickerContainer"+(this.props.className?" "+this.props.className:"");return f.default.createElement("div",{className:t,style:{width:this.props.width||"300px"}},f.default.createElement("div",{className:"colorscalePickerTopContainer"},f.default.createElement(O.default,{options:e,value:this.state.colorscaleType,onChange:this.setColorscaleType,placeholder:"Select colorscale",noResultsText:"Colorscale not found",clearable:!1,searchable:!1})),f.default.createElement(T,{colorscaleType:this.props.colorscaleType||this.state.colorscaleType,colorscaleOnMount:this.state.colorscaleOnMount,onClick:this.onClick,previousColorscale:this.state.previousColorscale,customBreakpoints:this.state.customBreakpoints,nSwatches:this.state.nSwatches,cubehelix:this.state.cubehelix,updateCubehelixStartState:this.updateCubehelixStartState,updateCubehelixStart:this.updateCubehelixStart,handle:this.handle,updateCubehelixRotState:this.updateCubehelixRotState,updateCubehelixRotations:this.updateCubehelixRotations,updateBreakpointArray:this.updateBreakpointArray,scaleLength:this.props.scaleLength}),this.props.disableSwatchControls?null:this.renderSwatchControls())}}]),t}(p.Component),k=function(){var e=this;this.handle=function(e){var t=e.value,n=e.dragging,o=e.index,i=r(e,["value","dragging","index"]);return f.default.createElement(m.default,{prefixCls:"rc-slider-tooltip",overlay:t,visible:n,placement:"top",key:o},f.default.createElement(C,l({value:t},i)))},this.toggleLog=function(){var t=u(e.state.previousColorscale,e.state.nSwatches,e.state.logBreakpoints,!e.state.log,e.state.colorscaleType);e.setState({log:!e.state.log,colorscale:t}),e.props.onChange(t)},this.onClick=function(t,n,o){if(e.state.customBreakpoints!==e.state.previousCustomBreakpoints||"custom"!==e.state.colorscaleType){var r=u(t,t.length,e.state.logBreakpoints,e.state.log,e.state.colorscaleType),i=t;"custom"===e.state.colorscaleType&&(i=e.state.previousColorscale),n||o?e.setState({previousColorscale:i,colorscale:r,nSwatches:t.length,previousCustomBreakpoints:null,cubehelix:{start:n,rotations:o}}):e.setState({previousColorscale:i,colorscale:r,nSwatches:t.length,previousCustomBreakpoints:"custom"===e.state.colorscaleType?e.state.customBreakpoints:null}),e.props.onChange(r,e.state.colorscaleType)}},this.updateSwatchNumber=function(t){var n=u(e.state.previousColorscale,t,e.state.logBreakpoints,e.state.log,e.state.colorscaleType);e.setState({nSwatches:t,colorscale:n,customBreakpoints:x.DEFAULT_BREAKPOINTS}),e.props.onChange(n)},this.updateBreakpoints=function(t){var n=t.currentTarget.valueAsNumber,o=u(e.state.previousColorscale,e.state.nSwatches,n,e.state.log,e.state.colorscaleType);e.setState({logBreakpoints:n,colorscale:o}),e.props.onChange(o)},this.updateBreakpointArray=function(t){var n=t.currentTarget.value.replace(/,\s*$/,"").split(",").map(Number);e.setState({customBreakpoints:n})},this.updateCubehelixStart=function(t){var n=e.state.cubehelix.rotations;e.updateCubehelix(t,n)},this.updateCubehelixRotations=function(t){var n=e.state.cubehelix.start;e.updateCubehelix(n,t)},this.updateCubehelixStartState=function(t){var n=e.state.cubehelix;n.start=t,e.setState({cubehelix:n})},this.updateCubehelixRotState=function(t){var n=e.state.cubehelix;n.rotations=t,e.setState({cubehelix:n})},this.updateCubehelix=function(t,n){var o=v.default.cubehelix().start(t).rotations(e.state.cubehelix.rotations).gamma(x.DEFAULT_GAMMA).lightness(x.DEFAULT_LIGHTNESS).scale().correctLightness().colors(x.DEFAULT_NCOLORS);e.onClick(o,t,n)}};t.default=S,S.defaultProps={initialColorscaleType:"sequential"};var T=t.ColorscalePaletteSelector=function(e){function t(){return i(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return s(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.colorscaleType,n=e.colorscaleOnMount,o=e.onClick,r=e.previousColorscale,i=e.customBreakpoints,a=e.nSwatches,s=e.cubehelix,u=e.updateCubehelixStartState,l=e.updateCubehelixStart,c=e.handle,p=e.updateCubehelixRotState,d=e.updateCubehelixRotations,b=e.updateBreakpointArray,g=e.scaleLength;return f.default.createElement("div",{className:"colorscalePickerBottomContainer"},f.default.createElement("div",{style:{margin:"0 auto"}},f.default.createElement(h.default,{key:"reset",colorscale:n,onClick:o,label:"RESET",scaleLength:g||x.DEFAULT_NPREVIEWCOLORS}),x.BUILTINS.hasOwnProperty(t)&&Object.keys(x.BUILTINS[t]).map(function(e,n){return f.default.createElement(h.default,{key:n,onClick:o,colorscale:x.BUILTINS[t][e],label:e,scaleLength:x.BUILTINS[t][e].length})}),x.BREWER.hasOwnProperty(t)&&x.BREWER[t].map(function(e,t){return f.default.createElement(h.default,{key:t,onClick:o,colorscale:v.default.brewer[e],label:e,scaleLength:v.default.brewer[e].length})}),"cubehelix"===t&&x.CUBEHELIX.map(function(e,t){return f.default.createElement(h.default,{key:t,onClick:o,colorscale:v.default.cubehelix().start(e.start).rotations(e.rotations).gamma(x.DEFAULT_GAMMA).lightness(x.DEFAULT_LIGHTNESS).scale().correctLightness().colors(g||x.DEFAULT_NPREVIEWCOLORS),start:e.start,rot:e.rotations,label:"s"+e.start+" r"+e.rotations,scaleLength:g})}),"cmocean"===t&&Object.keys(x.CMOCEAN).map(function(e,t){return f.default.createElement(h.default,{key:t,onClick:o,colorscale:x.CMOCEAN[e],label:e,scaleLength:x.CMOCEAN[e].length})}),"custom"===t&&f.default.createElement(h.default,{onClick:o,colorscale:v.default.scale(r).classes(i).mode("lch").colors(g||a),maxWidth:200,label:"Preview",scaleLength:g}),f.default.createElement("p",{className:"colorscaleDescription"},x.COLORSCALE_DESCRIPTIONS[t]),["custom","cubehelix"].includes(t)?f.default.createElement("div",{className:"colorscaleControlPanel"},"cubehelix"===t&&f.default.createElement("div",null,f.default.createElement("div",{className:"noWrap"},f.default.createElement("span",{className:"textLabel"},"Start: "),f.default.createElement("span",{className:"textLabel"},s.start),f.default.createElement(E.default,{min:0,max:300,step:1,value:s.start,onChange:u,onAfterChange:l,handle:c})),f.default.createElement("div",{className:"noWrap"},f.default.createElement("span",{className:"textLabel"},"Rotations: "),f.default.createElement("span",{className:"textLabel"},s.rotations),f.default.createElement(E.default,{min:-1.5,max:1.5,step:.1,value:s.rotations,onChange:p,onAfterChange:d,handle:c}))),f.default.createElement("div",null,"custom"===t&&f.default.createElement("div",{className:"colorscaleControlsRow"},f.default.createElement("p",{className:"textLabel zeroSpace"},"Decimals between 0 and 1, or numbers between MIN and MAX of your data, separated by commas:"),f.default.createElement("input",{type:"text",defaultValue:i.join(", "),onChange:b}),f.default.createElement("p",{className:"textLabel spaceTop"},i.length-1," breakpoints:"," ",i.join(" | "))))):null))}}]),t}(p.Component)},function(e,t,n){"use strict";var o=n(5),r=n.n(o),i=n(24),a=n.n(i),s=n(2),u=n.n(s),l=n(3),c=n.n(l),p=n(4),f=n.n(p),d=n(0),h=n.n(d),b=n(1),v=n.n(b),g=n(123),m=n(151),y=n(152),E=function(e){function t(){var n,o,r;u()(this,t);for(var i=arguments.length,a=Array(i),s=0;s<i;s++)a[s]=arguments[s];return n=o=c()(this,e.call.apply(e,[this].concat(a))),o.getPopupElement=function(){var e=o.props,t=e.arrowContent,n=e.overlay,r=e.prefixCls,i=e.id;return[h.a.createElement("div",{className:r+"-arrow",key:"arrow"},t),h.a.createElement(y.a,{key:"content",trigger:o.trigger,prefixCls:r,id:i,overlay:n})]},o.saveTrigger=function(e){o.trigger=e},r=n,c()(o,r)}return f()(t,e),t.prototype.getPopupDomNode=function(){return this.trigger.getPopupDomNode()},t.prototype.render=function(){var e=this.props,t=e.overlayClassName,n=e.trigger,o=e.mouseEnterDelay,i=e.mouseLeaveDelay,s=e.overlayStyle,u=e.prefixCls,l=e.children,c=e.onVisibleChange,p=e.afterVisibleChange,f=e.transitionName,d=e.animation,b=e.placement,v=e.align,y=e.destroyTooltipOnHide,E=e.defaultVisible,w=e.getTooltipContainer,O=a()(e,["overlayClassName","trigger","mouseEnterDelay","mouseLeaveDelay","overlayStyle","prefixCls","children","onVisibleChange","afterVisibleChange","transitionName","animation","placement","align","destroyTooltipOnHide","defaultVisible","getTooltipContainer"]),x=r()({},O);return"visible"in this.props&&(x.popupVisible=this.props.visible),h.a.createElement(g.a,r()({popupClassName:t,ref:this.saveTrigger,prefixCls:u,popup:this.getPopupElement,action:n,builtinPlacements:m.a,popupPlacement:b,popupAlign:v,getPopupContainer:w,onPopupVisibleChange:c,afterPopupVisibleChange:p,popupTransitionName:f,popupAnimation:d,defaultPopupVisible:E,destroyPopupOnHide:y,mouseLeaveDelay:i,popupStyle:s,mouseEnterDelay:o},x),l)},t}(d.Component);E.propTypes={trigger:v.a.any,children:v.a.any,defaultVisible:v.a.bool,visible:v.a.bool,placement:v.a.string,transitionName:v.a.oneOfType([v.a.string,v.a.object]),animation:v.a.any,onVisibleChange:v.a.func,afterVisibleChange:v.a.func,overlay:v.a.oneOfType([v.a.node,v.a.func]).isRequired,overlayStyle:v.a.object,overlayClassName:v.a.string,prefixCls:v.a.string,mouseEnterDelay:v.a.number,mouseLeaveDelay:v.a.number,getTooltipContainer:v.a.func,destroyTooltipOnHide:v.a.bool,align:v.a.object,arrowContent:v.a.any,id:v.a.string},E.defaultProps={prefixCls:"rc-tooltip",mouseEnterDelay:0,destroyTooltipOnHide:!1,mouseLeaveDelay:.1,align:{},placement:"right",trigger:["hover"],arrowContent:null},t.a=E},function(e,t,n){e.exports={default:n(87),__esModule:!0}},function(e,t,n){n(88),e.exports=n(6).Object.assign},function(e,t,n){var o=n(10);o(o.S+o.F,"Object",{assign:n(90)})},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},function(e,t,n){"use strict";var o=n(27),r=n(42),i=n(30),a=n(31),s=n(61),u=Object.assign;e.exports=!u||n(22)(function(){var e={},t={},n=Symbol(),o="abcdefghijklmnopqrst";return e[n]=7,o.split("").forEach(function(e){t[e]=e}),7!=u({},e)[n]||Object.keys(u({},t)).join("")!=o})?function(e,t){for(var n=a(e),u=arguments.length,l=1,c=r.f,p=i.f;u>l;)for(var f,d=s(arguments[l++]),h=c?o(d).concat(c(d)):o(d),b=h.length,v=0;b>v;)p.call(d,f=h[v++])&&(n[f]=d[f]);return n}:u},function(e,t,n){var o=n(15),r=n(62),i=n(92);e.exports=function(e){return function(t,n,a){var s,u=o(t),l=r(u.length),c=i(a,l);if(e&&n!=n){for(;l>c;)if((s=u[c++])!=s)return!0}else for(;l>c;c++)if((e||c in u)&&u[c]===n)return e||c||0;return!e&&-1}}},function(e,t,n){var o=n(38),r=Math.max,i=Math.min;e.exports=function(e,t){return e=o(e),e<0?r(e+t,0):i(e,t)}},function(e,t,n){e.exports={default:n(94),__esModule:!0}},function(e,t,n){n(63),n(99),e.exports=n(46).f("iterator")},function(e,t,n){var o=n(38),r=n(37);e.exports=function(e){return function(t,n){var i,a,s=String(r(t)),u=o(n),l=s.length;return u<0||u>=l?e?"":void 0:(i=s.charCodeAt(u),i<55296||i>56319||u+1===l||(a=s.charCodeAt(u+1))<56320||a>57343?e?s.charAt(u):i:e?s.slice(u,u+2):a-56320+(i-55296<<10)+65536)}}},function(e,t,n){"use strict";var o=n(44),r=n(23),i=n(45),a={};n(19)(a,n(7)("iterator"),function(){return this}),e.exports=function(e,t,n){e.prototype=o(a,{next:r(1,n)}),i(e,t+" Iterator")}},function(e,t,n){var o=n(12),r=n(20),i=n(27);e.exports=n(13)?Object.defineProperties:function(e,t){r(e);for(var n,a=i(t),s=a.length,u=0;s>u;)o.f(e,n=a[u++],t[n]);return e}},function(e,t,n){var o=n(11).document;e.exports=o&&o.documentElement},function(e,t,n){n(100);for(var o=n(11),r=n(19),i=n(25),a=n(7)("toStringTag"),s="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),u=0;u<s.length;u++){var l=s[u],c=o[l],p=c&&c.prototype;p&&!p[a]&&r(p,a,l),i[l]=i.Array}},function(e,t,n){"use strict";var o=n(101),r=n(102),i=n(25),a=n(15);e.exports=n(64)(Array,"Array",function(e,t){this._t=a(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,n=this._i++;return!e||n>=e.length?(this._t=void 0,r(1)):"keys"==t?r(0,n):"values"==t?r(0,e[n]):r(0,[n,e[n]])},"values"),i.Arguments=i.Array,o("keys"),o("values"),o("entries")},function(e,t){e.exports=function(){}},function(e,t){e.exports=function(e,t){return{value:t,done:!!e}}},function(e,t,n){e.exports={default:n(104),__esModule:!0}},function(e,t,n){n(105),n(110),n(111),n(112),e.exports=n(6).Symbol},function(e,t,n){"use strict";var o=n(11),r=n(14),i=n(13),a=n(10),s=n(65),u=n(106).KEY,l=n(22),c=n(40),p=n(45),f=n(29),d=n(7),h=n(46),b=n(47),v=n(107),g=n(108),m=n(20),y=n(21),E=n(15),w=n(35),O=n(23),x=n(44),C=n(109),S=n(48),k=n(12),T=n(27),A=S.f,_=k.f,P=C.f,M=o.Symbol,D=o.JSON,F=D&&D.stringify,N=d("_hidden"),j=d("toPrimitive"),R={}.propertyIsEnumerable,L=c("symbol-registry"),I=c("symbols"),V=c("op-symbols"),B=Object.prototype,U="function"==typeof M,W=o.QObject,H=!W||!W.prototype||!W.prototype.findChild,z=i&&l(function(){return 7!=x(_({},"a",{get:function(){return _(this,"a",{value:7}).a}})).a})?function(e,t,n){var o=A(B,t);o&&delete B[t],_(e,t,n),o&&e!==B&&_(B,t,o)}:_,K=function(e){var t=I[e]=x(M.prototype);return t._k=e,t},q=U&&"symbol"==typeof M.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof M},Y=function(e,t,n){return e===B&&Y(V,t,n),m(e),t=w(t,!0),m(n),r(I,t)?(n.enumerable?(r(e,N)&&e[N][t]&&(e[N][t]=!1),n=x(n,{enumerable:O(0,!1)})):(r(e,N)||_(e,N,O(1,{})),e[N][t]=!0),z(e,t,n)):_(e,t,n)},G=function(e,t){m(e);for(var n,o=v(t=E(t)),r=0,i=o.length;i>r;)Y(e,n=o[r++],t[n]);return e},X=function(e,t){return void 0===t?x(e):G(x(e),t)},Z=function(e){var t=R.call(this,e=w(e,!0));return!(this===B&&r(I,e)&&!r(V,e))&&(!(t||!r(this,e)||!r(I,e)||r(this,N)&&this[N][e])||t)},J=function(e,t){if(e=E(e),t=w(t,!0),e!==B||!r(I,t)||r(V,t)){var n=A(e,t);return!n||!r(I,t)||r(e,N)&&e[N][t]||(n.enumerable=!0),n}},$=function(e){for(var t,n=P(E(e)),o=[],i=0;n.length>i;)r(I,t=n[i++])||t==N||t==u||o.push(t);return o},Q=function(e){for(var t,n=e===B,o=P(n?V:E(e)),i=[],a=0;o.length>a;)!r(I,t=o[a++])||n&&!r(B,t)||i.push(I[t]);return i};U||(M=function(){if(this instanceof M)throw TypeError("Symbol is not a constructor!");var e=f(arguments.length>0?arguments[0]:void 0),t=function(n){this===B&&t.call(V,n),r(this,N)&&r(this[N],e)&&(this[N][e]=!1),z(this,e,O(1,n))};return i&&H&&z(B,e,{configurable:!0,set:t}),K(e)},s(M.prototype,"toString",function(){return this._k}),S.f=J,k.f=Y,n(67).f=C.f=$,n(30).f=Z,n(42).f=Q,i&&!n(28)&&s(B,"propertyIsEnumerable",Z,!0),h.f=function(e){return K(d(e))}),a(a.G+a.W+a.F*!U,{Symbol:M});for(var ee="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),te=0;ee.length>te;)d(ee[te++]);for(var ne=T(d.store),oe=0;ne.length>oe;)b(ne[oe++]);a(a.S+a.F*!U,"Symbol",{for:function(e){return r(L,e+="")?L[e]:L[e]=M(e)},keyFor:function(e){if(!q(e))throw TypeError(e+" is not a symbol!");for(var t in L)if(L[t]===e)return t},useSetter:function(){H=!0},useSimple:function(){H=!1}}),a(a.S+a.F*!U,"Object",{create:X,defineProperty:Y,defineProperties:G,getOwnPropertyDescriptor:J,getOwnPropertyNames:$,getOwnPropertySymbols:Q}),D&&a(a.S+a.F*(!U||l(function(){var e=M();return"[null]"!=F([e])||"{}"!=F({a:e})||"{}"!=F(Object(e))})),"JSON",{stringify:function(e){for(var t,n,o=[e],r=1;arguments.length>r;)o.push(arguments[r++]);if(n=t=o[1],(y(t)||void 0!==e)&&!q(e))return g(t)||(t=function(e,t){if("function"==typeof n&&(t=n.call(this,e,t)),!q(t))return t}),o[1]=t,F.apply(D,o)}}),M.prototype[j]||n(19)(M.prototype,j,M.prototype.valueOf),p(M,"Symbol"),p(Math,"Math",!0),p(o.JSON,"JSON",!0)},function(e,t,n){var o=n(29)("meta"),r=n(21),i=n(14),a=n(12).f,s=0,u=Object.isExtensible||function(){return!0},l=!n(22)(function(){return u(Object.preventExtensions({}))}),c=function(e){a(e,o,{value:{i:"O"+ ++s,w:{}}})},p=function(e,t){if(!r(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!i(e,o)){if(!u(e))return"F";if(!t)return"E";c(e)}return e[o].i},f=function(e,t){if(!i(e,o)){if(!u(e))return!0;if(!t)return!1;c(e)}return e[o].w},d=function(e){return l&&h.NEED&&u(e)&&!i(e,o)&&c(e),e},h=e.exports={KEY:o,NEED:!1,fastKey:p,getWeak:f,onFreeze:d}},function(e,t,n){var o=n(27),r=n(42),i=n(30);e.exports=function(e){var t=o(e),n=r.f;if(n)for(var a,s=n(e),u=i.f,l=0;s.length>l;)u.call(e,a=s[l++])&&t.push(a);return t}},function(e,t,n){var o=n(36);e.exports=Array.isArray||function(e){return"Array"==o(e)}},function(e,t,n){var o=n(15),r=n(67).f,i={}.toString,a="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],s=function(e){try{return r(e)}catch(e){return a.slice()}};e.exports.f=function(e){return a&&"[object Window]"==i.call(e)?s(e):r(o(e))}},function(e,t){},function(e,t,n){n(47)("asyncIterator")},function(e,t,n){n(47)("observable")},function(e,t,n){e.exports={default:n(114),__esModule:!0}},function(e,t,n){n(115),e.exports=n(6).Object.setPrototypeOf},function(e,t,n){var o=n(10);o(o.S,"Object",{setPrototypeOf:n(116).set})},function(e,t,n){var o=n(21),r=n(20),i=function(e,t){if(r(e),!o(t)&&null!==t)throw TypeError(t+": can't set as prototype!")};e.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(e,t,o){try{o=n(34)(Function.call,n(48).f(Object.prototype,"__proto__").set,2),o(e,[]),t=!(e instanceof Array)}catch(e){t=!0}return function(e,n){return i(e,n),t?e.__proto__=n:o(e,n),e}}({},!1):void 0),check:i}},function(e,t,n){e.exports={default:n(118),__esModule:!0}},function(e,t,n){n(119);var o=n(6).Object;e.exports=function(e,t){return o.create(e,t)}},function(e,t,n){var o=n(10);o(o.S,"Object",{create:n(44)})},function(e,t,n){"use strict";(function(t){function o(){return null}var r=n(68),i=n(49),a=n(121),s=function(){};"production"!==t.env.NODE_ENV&&(s=function(e){var t="Warning: "+e;"undefined"!==typeof console&&console.error(t);try{throw new Error(t)}catch(e){}}),e.exports=function(e,n){function u(e){var t=e&&(k&&e[k]||e[T]);if("function"===typeof t)return t}function l(e,t){return e===t?0!==e||1/e===1/t:e!==e&&t!==t}function c(e){this.message=e,this.stack=""}function p(e){function o(o,u,l,p,f,d,h){if(p=p||A,d=d||l,h!==i){if(n){var b=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types");throw b.name="Invariant Violation",b}if("production"!==t.env.NODE_ENV&&"undefined"!==typeof console){var v=p+":"+l;!r[v]&&a<3&&(s("You are manually calling a React.PropTypes validation function for the `"+d+"` prop on `"+p+"`. This is deprecated and will throw in the standalone `prop-types` package. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details."),r[v]=!0,a++)}}return null==u[l]?o?new c(null===u[l]?"The "+f+" `"+d+"` is marked as required in `"+p+"`, but its value is `null`.":"The "+f+" `"+d+"` is marked as required in `"+p+"`, but its value is `undefined`."):null:e(u,l,p,f,d)}if("production"!==t.env.NODE_ENV)var r={},a=0;var u=o.bind(null,!1);return u.isRequired=o.bind(null,!0),u}function f(e){function t(t,n,o,r,i,a){var s=t[n];if(O(s)!==e)return new c("Invalid "+r+" `"+i+"` of type `"+x(s)+"` supplied to `"+o+"`, expected `"+e+"`.");return null}return p(t)}function d(e){function t(t,n,o,r,a){if("function"!==typeof e)return new c("Property `"+a+"` of component `"+o+"` has invalid PropType notation inside arrayOf.");var s=t[n];if(!Array.isArray(s)){return new c("Invalid "+r+" `"+a+"` of type `"+O(s)+"` supplied to `"+o+"`, expected an array.")}for(var u=0;u<s.length;u++){var l=e(s,u,o,r,a+"["+u+"]",i);if(l instanceof Error)return l}return null}return p(t)}function h(e){function t(t,n,o,r,i){if(!(t[n]instanceof e)){var a=e.name||A;return new c("Invalid "+r+" `"+i+"` of type `"+S(t[n])+"` supplied to `"+o+"`, expected instance of `"+a+"`.")}return null}return p(t)}function b(e){function n(t,n,o,r,i){for(var a=t[n],s=0;s<e.length;s++)if(l(a,e[s]))return null;return new c("Invalid "+r+" `"+i+"` of value `"+a+"` supplied to `"+o+"`, expected one of "+JSON.stringify(e)+".")}return Array.isArray(e)?p(n):("production"!==t.env.NODE_ENV&&s("Invalid argument supplied to oneOf, expected an instance of array."),o)}function v(e){function t(t,n,o,r,a){if("function"!==typeof e)return new c("Property `"+a+"` of component `"+o+"` has invalid PropType notation inside objectOf.");var s=t[n],u=O(s);if("object"!==u)return new c("Invalid "+r+" `"+a+"` of type `"+u+"` supplied to `"+o+"`, expected an object.");for(var l in s)if(s.hasOwnProperty(l)){var p=e(s,l,o,r,a+"."+l,i);if(p instanceof Error)return p}return null}return p(t)}function g(e){function n(t,n,o,r,a){for(var s=0;s<e.length;s++){if(null==(0,e[s])(t,n,o,r,a,i))return null}return new c("Invalid "+r+" `"+a+"` supplied to `"+o+"`.")}if(!Array.isArray(e))return"production"!==t.env.NODE_ENV&&s("Invalid argument supplied to oneOfType, expected an instance of array."),o;for(var r=0;r<e.length;r++){var a=e[r];if("function"!==typeof a)return s("Invalid argument supplied to oneOfType. Expected an array of check functions, but received "+C(a)+" at index "+r+"."),o}return p(n)}function m(e){function t(t,n,o,r,a){var s=t[n],u=O(s);if("object"!==u)return new c("Invalid "+r+" `"+a+"` of type `"+u+"` supplied to `"+o+"`, expected `object`.");for(var l in e){var p=e[l];if(p){var f=p(s,l,o,r,a+"."+l,i);if(f)return f}}return null}return p(t)}function y(e){function t(t,n,o,a,s){var u=t[n],l=O(u);if("object"!==l)return new c("Invalid "+a+" `"+s+"` of type `"+l+"` supplied to `"+o+"`, expected `object`.");var p=r({},t[n],e);for(var f in p){var d=e[f];if(!d)return new c("Invalid "+a+" `"+s+"` key `"+f+"` supplied to `"+o+"`.\nBad object: "+JSON.stringify(t[n],null,"  ")+"\nValid keys: "+JSON.stringify(Object.keys(e),null,"  "));var h=d(u,f,o,a,s+"."+f,i);if(h)return h}return null}return p(t)}function E(t){switch(typeof t){case"number":case"string":case"undefined":return!0;case"boolean":return!t;case"object":if(Array.isArray(t))return t.every(E);if(null===t||e(t))return!0;var n=u(t);if(!n)return!1;var o,r=n.call(t);if(n!==t.entries){for(;!(o=r.next()).done;)if(!E(o.value))return!1}else for(;!(o=r.next()).done;){var i=o.value;if(i&&!E(i[1]))return!1}return!0;default:return!1}}function w(e,t){return"symbol"===e||("Symbol"===t["@@toStringTag"]||"function"===typeof Symbol&&t instanceof Symbol)}function O(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":w(t,e)?"symbol":t}function x(e){if("undefined"===typeof e||null===e)return""+e;var t=O(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}function C(e){var t=x(e);switch(t){case"array":case"object":return"an "+t;case"boolean":case"date":case"regexp":return"a "+t;default:return t}}function S(e){return e.constructor&&e.constructor.name?e.constructor.name:A}var k="function"===typeof Symbol&&Symbol.iterator,T="@@iterator",A="<<anonymous>>",_={array:f("array"),bool:f("boolean"),func:f("function"),number:f("number"),object:f("object"),string:f("string"),symbol:f("symbol"),any:function(){return p(o)}(),arrayOf:d,element:function(){function t(t,n,o,r,i){var a=t[n];if(!e(a)){return new c("Invalid "+r+" `"+i+"` of type `"+O(a)+"` supplied to `"+o+"`, expected a single ReactElement.")}return null}return p(t)}(),instanceOf:h,node:function(){function e(e,t,n,o,r){return E(e[t])?null:new c("Invalid "+o+" `"+r+"` supplied to `"+n+"`, expected a ReactNode.")}return p(e)}(),objectOf:v,oneOf:b,oneOfType:g,shape:m,exact:y};return c.prototype=Error.prototype,_.checkPropTypes=a,_.PropTypes=_,_}}).call(t,n(26))},function(e,t,n){"use strict";(function(t){function o(e,n,o,s,u){if("production"!==t.env.NODE_ENV)for(var l in e)if(e.hasOwnProperty(l)){var c;try{if("function"!==typeof e[l]){var p=Error((s||"React class")+": "+o+" type `"+l+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[l]+"`.");throw p.name="Invariant Violation",p}c=e[l](n,l,s,o,null,i)}catch(e){c=e}if(!c||c instanceof Error||r((s||"React class")+": type specification of "+o+" `"+l+"` is invalid; the type checker function must return `null` or an `Error` but returned a "+typeof c+". You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument)."),c instanceof Error&&!(c.message in a)){a[c.message]=!0;var f=u?u():"";r("Failed "+o+" type: "+c.message+(null!=f?f:""))}}}var r=function(){};if("production"!==t.env.NODE_ENV){var i=n(49),a={};r=function(e){var t="Warning: "+e;"undefined"!==typeof console&&console.error(t);try{throw new Error(t)}catch(e){}}}e.exports=o}).call(t,n(26))},function(e,t,n){"use strict";function o(){}var r=n(49);e.exports=function(){function e(e,t,n,o,i,a){if(a!==r){var s=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw s.name="Invariant Violation",s}}function t(){return e}e.isRequired=e;var n={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t};return n.checkPropTypes=o,n.PropTypes=n,n}},function(e,t,n){"use strict";function o(){}function r(){return""}function i(){return window.document}var a=n(5),s=n.n(a),u=n(2),l=n.n(u),c=n(3),p=n.n(c),f=n(4),d=n.n(f),h=n(0),b=n.n(h),v=n(1),g=n.n(v),m=n(8),y=(n.n(m),n(124)),E=n(32),w=n(128),O=n(131),x=n(16),C=n.n(x),S=n(70),k=n(132),T=["onClick","onMouseDown","onTouchStart","onMouseEnter","onMouseLeave","onFocus","onBlur","onContextMenu"],A=!!m.createPortal,_={rcTrigger:g.a.shape({onPopupMouseDown:g.a.func})},P=function(e){function t(n){l()(this,t);var o=p()(this,e.call(this,n));M.call(o);var r=void 0;return r="popupVisible"in n?!!n.popupVisible:!!n.defaultPopupVisible,o.prevPopupVisible=r,o.state={popupVisible:r},o}return d()(t,e),t.prototype.getChildContext=function(){return{rcTrigger:{onPopupMouseDown:this.onPopupMouseDown}}},t.prototype.componentWillMount=function(){var e=this;T.forEach(function(t){e["fire"+t]=function(n){e.fireEvents(t,n)}})},t.prototype.componentDidMount=function(){this.componentDidUpdate({},{popupVisible:this.state.popupVisible})},t.prototype.componentWillReceiveProps=function(e){var t=e.popupVisible;void 0!==t&&this.setState({popupVisible:t})},t.prototype.componentDidUpdate=function(e,t){var n=this.props,o=this.state,r=function(){t.popupVisible!==o.popupVisible&&n.afterPopupVisibleChange(o.popupVisible)};if(A||this.renderComponent(null,r),this.prevPopupVisible=t.popupVisible,o.popupVisible){var i=void 0;return this.clickOutsideHandler||!this.isClickToHide()&&!this.isContextMenuToShow()||(i=n.getDocument(),this.clickOutsideHandler=Object(E.a)(i,"mousedown",this.onDocumentClick)),this.touchOutsideHandler||(i=i||n.getDocument(),this.touchOutsideHandler=Object(E.a)(i,"touchstart",this.onDocumentClick)),!this.contextMenuOutsideHandler1&&this.isContextMenuToShow()&&(i=i||n.getDocument(),this.contextMenuOutsideHandler1=Object(E.a)(i,"scroll",this.onContextMenuClose)),void(!this.contextMenuOutsideHandler2&&this.isContextMenuToShow()&&(this.contextMenuOutsideHandler2=Object(E.a)(window,"blur",this.onContextMenuClose)))}this.clearOutsideHandler()},t.prototype.componentWillUnmount=function(){this.clearDelayTimer(),this.clearOutsideHandler(),clearTimeout(this.mouseDownTimeout)},t.prototype.getPopupDomNode=function(){return this._component&&this._component.getPopupDomNode?this._component.getPopupDomNode():null},t.prototype.getPopupAlign=function(){var e=this.props,t=e.popupPlacement,n=e.popupAlign,o=e.builtinPlacements;return t&&o?Object(S.a)(o,t,n):n},t.prototype.setPopupVisible=function(e,t){var n=this.props.alignPoint;this.clearDelayTimer(),this.state.popupVisible!==e&&("popupVisible"in this.props||this.setState({popupVisible:e}),this.props.onPopupVisibleChange(e)),n&&t&&this.setPoint(t)},t.prototype.delaySetPopupVisible=function(e,t,n){var o=this,r=1e3*t;if(this.clearDelayTimer(),r){var i=n?{pageX:n.pageX,pageY:n.pageY}:null;this.delayTimer=setTimeout(function(){o.setPopupVisible(e,i),o.clearDelayTimer()},r)}else this.setPopupVisible(e,n)},t.prototype.clearDelayTimer=function(){this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null)},t.prototype.clearOutsideHandler=function(){this.clickOutsideHandler&&(this.clickOutsideHandler.remove(),this.clickOutsideHandler=null),this.contextMenuOutsideHandler1&&(this.contextMenuOutsideHandler1.remove(),this.contextMenuOutsideHandler1=null),this.contextMenuOutsideHandler2&&(this.contextMenuOutsideHandler2.remove(),this.contextMenuOutsideHandler2=null),this.touchOutsideHandler&&(this.touchOutsideHandler.remove(),this.touchOutsideHandler=null)},t.prototype.createTwoChains=function(e){var t=this.props.children.props,n=this.props;return t[e]&&n[e]?this["fire"+e]:t[e]||n[e]},t.prototype.isClickToShow=function(){var e=this.props,t=e.action,n=e.showAction;return-1!==t.indexOf("click")||-1!==n.indexOf("click")},t.prototype.isContextMenuToShow=function(){var e=this.props,t=e.action,n=e.showAction;return-1!==t.indexOf("contextMenu")||-1!==n.indexOf("contextMenu")},t.prototype.isClickToHide=function(){var e=this.props,t=e.action,n=e.hideAction;return-1!==t.indexOf("click")||-1!==n.indexOf("click")},t.prototype.isMouseEnterToShow=function(){var e=this.props,t=e.action,n=e.showAction;return-1!==t.indexOf("hover")||-1!==n.indexOf("mouseEnter")},t.prototype.isMouseLeaveToHide=function(){var e=this.props,t=e.action,n=e.hideAction;return-1!==t.indexOf("hover")||-1!==n.indexOf("mouseLeave")},t.prototype.isFocusToShow=function(){var e=this.props,t=e.action,n=e.showAction;return-1!==t.indexOf("focus")||-1!==n.indexOf("focus")},t.prototype.isBlurToHide=function(){var e=this.props,t=e.action,n=e.hideAction;return-1!==t.indexOf("focus")||-1!==n.indexOf("blur")},t.prototype.forcePopupAlign=function(){this.state.popupVisible&&this._component&&this._component.alignInstance&&this._component.alignInstance.forceAlign()},t.prototype.fireEvents=function(e,t){var n=this.props.children.props[e];n&&n(t);var o=this.props[e];o&&o(t)},t.prototype.close=function(){this.setPopupVisible(!1)},t.prototype.render=function(){var e=this,t=this.state.popupVisible,n=this.props,o=n.children,r=n.forceRender,i=n.alignPoint,a=n.className,s=b.a.Children.only(o),u={key:"trigger"};this.isContextMenuToShow()?u.onContextMenu=this.onContextMenu:u.onContextMenu=this.createTwoChains("onContextMenu"),this.isClickToHide()||this.isClickToShow()?(u.onClick=this.onClick,u.onMouseDown=this.onMouseDown,u.onTouchStart=this.onTouchStart):(u.onClick=this.createTwoChains("onClick"),u.onMouseDown=this.createTwoChains("onMouseDown"),u.onTouchStart=this.createTwoChains("onTouchStart")),this.isMouseEnterToShow()?(u.onMouseEnter=this.onMouseEnter,i&&(u.onMouseMove=this.onMouseMove)):u.onMouseEnter=this.createTwoChains("onMouseEnter"),this.isMouseLeaveToHide()?u.onMouseLeave=this.onMouseLeave:u.onMouseLeave=this.createTwoChains("onMouseLeave"),this.isFocusToShow()||this.isBlurToHide()?(u.onFocus=this.onFocus,u.onBlur=this.onBlur):(u.onFocus=this.createTwoChains("onFocus"),u.onBlur=this.createTwoChains("onBlur"));var l=C()(s&&s.props&&s.props.className,a);l&&(u.className=l);var c=b.a.cloneElement(s,u);if(!A)return b.a.createElement(w.a,{parent:this,visible:t,autoMount:!1,forceRender:r,getComponent:this.getComponent,getContainer:this.getContainer},function(t){var n=t.renderComponent;return e.renderComponent=n,c});var p=void 0;return(t||this._component||r)&&(p=b.a.createElement(O.a,{key:"portal",getContainer:this.getContainer,didUpdate:this.handlePortalUpdate},this.getComponent())),[c,p]},t}(b.a.Component);P.propTypes={children:g.a.any,action:g.a.oneOfType([g.a.string,g.a.arrayOf(g.a.string)]),showAction:g.a.any,hideAction:g.a.any,getPopupClassNameFromAlign:g.a.any,onPopupVisibleChange:g.a.func,afterPopupVisibleChange:g.a.func,popup:g.a.oneOfType([g.a.node,g.a.func]).isRequired,popupStyle:g.a.object,prefixCls:g.a.string,popupClassName:g.a.string,className:g.a.string,popupPlacement:g.a.string,builtinPlacements:g.a.object,popupTransitionName:g.a.oneOfType([g.a.string,g.a.object]),popupAnimation:g.a.any,mouseEnterDelay:g.a.number,mouseLeaveDelay:g.a.number,zIndex:g.a.number,focusDelay:g.a.number,blurDelay:g.a.number,getPopupContainer:g.a.func,getDocument:g.a.func,forceRender:g.a.bool,destroyPopupOnHide:g.a.bool,mask:g.a.bool,maskClosable:g.a.bool,onPopupAlign:g.a.func,popupAlign:g.a.object,popupVisible:g.a.bool,defaultPopupVisible:g.a.bool,maskTransitionName:g.a.oneOfType([g.a.string,g.a.object]),maskAnimation:g.a.string,stretch:g.a.string,alignPoint:g.a.bool},P.contextTypes=_,P.childContextTypes=_,P.defaultProps={prefixCls:"rc-trigger-popup",getPopupClassNameFromAlign:r,getDocument:i,onPopupVisibleChange:o,afterPopupVisibleChange:o,onPopupAlign:o,popupClassName:"",mouseEnterDelay:0,mouseLeaveDelay:.1,focusDelay:0,blurDelay:.15,popupStyle:{},destroyPopupOnHide:!1,popupAlign:{},defaultPopupVisible:!1,mask:!1,maskClosable:!0,action:[],showAction:[],hideAction:[]};var M=function(){var e=this;this.onMouseEnter=function(t){var n=e.props.mouseEnterDelay;e.fireEvents("onMouseEnter",t),e.delaySetPopupVisible(!0,n,n?null:t)},this.onMouseMove=function(t){e.fireEvents("onMouseMove",t),e.setPoint(t)},this.onMouseLeave=function(t){e.fireEvents("onMouseLeave",t),e.delaySetPopupVisible(!1,e.props.mouseLeaveDelay)},this.onPopupMouseEnter=function(){e.clearDelayTimer()},this.onPopupMouseLeave=function(t){t.relatedTarget&&!t.relatedTarget.setTimeout&&e._component&&e._component.getPopupDomNode&&Object(y.a)(e._component.getPopupDomNode(),t.relatedTarget)||e.delaySetPopupVisible(!1,e.props.mouseLeaveDelay)},this.onFocus=function(t){e.fireEvents("onFocus",t),e.clearDelayTimer(),e.isFocusToShow()&&(e.focusTime=Date.now(),e.delaySetPopupVisible(!0,e.props.focusDelay))},this.onMouseDown=function(t){e.fireEvents("onMouseDown",t),e.preClickTime=Date.now()},this.onTouchStart=function(t){e.fireEvents("onTouchStart",t),e.preTouchTime=Date.now()},this.onBlur=function(t){e.fireEvents("onBlur",t),e.clearDelayTimer(),e.isBlurToHide()&&e.delaySetPopupVisible(!1,e.props.blurDelay)},this.onContextMenu=function(t){t.preventDefault(),e.fireEvents("onContextMenu",t),e.setPopupVisible(!0,t)},this.onContextMenuClose=function(){e.isContextMenuToShow()&&e.close()},this.onClick=function(t){if(e.fireEvents("onClick",t),e.focusTime){var n=void 0;if(e.preClickTime&&e.preTouchTime?n=Math.min(e.preClickTime,e.preTouchTime):e.preClickTime?n=e.preClickTime:e.preTouchTime&&(n=e.preTouchTime),Math.abs(n-e.focusTime)<20)return;e.focusTime=0}e.preClickTime=0,e.preTouchTime=0,t&&t.preventDefault&&t.preventDefault();var o=!e.state.popupVisible;(e.isClickToHide()&&!o||o&&e.isClickToShow())&&e.setPopupVisible(!e.state.popupVisible,t)},this.onPopupMouseDown=function(){var t=e.context.rcTrigger,n=void 0===t?{}:t;e.hasPopupMouseDown=!0,clearTimeout(e.mouseDownTimeout),e.mouseDownTimeout=setTimeout(function(){e.hasPopupMouseDown=!1},0),n.onPopupMouseDown&&n.onPopupMouseDown.apply(n,arguments)},this.onDocumentClick=function(t){if(!e.props.mask||e.props.maskClosable){var n=t.target,o=Object(m.findDOMNode)(e);Object(y.a)(o,n)||e.hasPopupMouseDown||e.close()}},this.getRootDomNode=function(){return Object(m.findDOMNode)(e)},this.getPopupClassNameFromAlign=function(t){var n=[],o=e.props,r=o.popupPlacement,i=o.builtinPlacements,a=o.prefixCls,s=o.alignPoint,u=o.getPopupClassNameFromAlign;return r&&i&&n.push(Object(S.b)(i,a,t,s)),u&&n.push(u(t)),n.join(" ")},this.getComponent=function(){var t=e.props,n=t.prefixCls,o=t.destroyPopupOnHide,r=t.popupClassName,i=t.action,a=t.onPopupAlign,u=t.popupAnimation,l=t.popupTransitionName,c=t.popupStyle,p=t.mask,f=t.maskAnimation,d=t.maskTransitionName,h=t.zIndex,v=t.popup,g=t.stretch,m=t.alignPoint,y=e.state,E=y.popupVisible,w=y.point,O=e.getPopupAlign(),x={};return e.isMouseEnterToShow()&&(x.onMouseEnter=e.onPopupMouseEnter),e.isMouseLeaveToHide()&&(x.onMouseLeave=e.onPopupMouseLeave),x.onMouseDown=e.onPopupMouseDown,x.onTouchStart=e.onPopupMouseDown,b.a.createElement(k.a,s()({prefixCls:n,destroyPopupOnHide:o,visible:E,point:m&&w,className:r,action:i,align:O,onAlign:a,animation:u,getClassNameFromAlign:e.getPopupClassNameFromAlign},x,{stretch:g,getRootDomNode:e.getRootDomNode,style:c,mask:p,zIndex:h,transitionName:l,maskAnimation:f,maskTransitionName:d,ref:e.savePopup}),"function"===typeof v?v():v)},this.getContainer=function(){var t=e.props,n=document.createElement("div");return n.style.position="absolute",n.style.top="0",n.style.left="0",n.style.width="100%",(t.getPopupContainer?t.getPopupContainer(Object(m.findDOMNode)(e)):t.getDocument().body).appendChild(n),n},this.setPoint=function(t){e.props.alignPoint&&t&&e.setState({point:{pageX:t.pageX,pageY:t.pageY}})},this.handlePortalUpdate=function(){e.prevPopupVisible!==e.state.popupVisible&&e.props.afterPopupVisibleChange(e.state.popupVisible)},this.savePopup=function(t){e._component=t}};t.a=P},function(e,t,n){"use strict";function o(e,t){for(var n=t;n;){if(n===e)return!0;n=n.parentNode}return!1}t.a=o},function(e,t,n){"use strict";function o(e,t,n,o){function r(t){var o=new i.default(t);n.call(e,o)}if(e.addEventListener){var a=function(){var n=!1;return"object"===typeof o?n=o.capture||!1:"boolean"===typeof o&&(n=o),e.addEventListener(t,r,o||!1),{v:{remove:function(){e.removeEventListener(t,r,n)}}}}();if("object"===typeof a)return a.v}else if(e.attachEvent)return e.attachEvent("on"+t,r),{remove:function(){e.detachEvent("on"+t,r)}}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=o;var r=n(126),i=function(e){return e&&e.__esModule?e:{default:e}}(r);e.exports=t.default},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}function r(e){return null===e||void 0===e}function i(){return f}function a(){return d}function s(e){var t=e.type,n="function"===typeof e.stopPropagation||"boolean"===typeof e.cancelBubble;l.default.call(this),this.nativeEvent=e;var o=a;"defaultPrevented"in e?o=e.defaultPrevented?i:a:"getPreventDefault"in e?o=e.getPreventDefault()?i:a:"returnValue"in e&&(o=e.returnValue===d?i:a),this.isDefaultPrevented=o;var r=[],s=void 0,u=void 0,c=h.concat();for(b.forEach(function(e){t.match(e.reg)&&(c=c.concat(e.props),e.fix&&r.push(e.fix))}),s=c.length;s;)u=c[--s],this[u]=e[u];for(!this.target&&n&&(this.target=e.srcElement||document),this.target&&3===this.target.nodeType&&(this.target=this.target.parentNode),s=r.length;s;)(0,r[--s])(this,e);this.timeStamp=e.timeStamp||Date.now()}Object.defineProperty(t,"__esModule",{value:!0});var u=n(127),l=o(u),c=n(68),p=o(c),f=!0,d=!1,h=["altKey","bubbles","cancelable","ctrlKey","currentTarget","eventPhase","metaKey","shiftKey","target","timeStamp","view","type"],b=[{reg:/^key/,props:["char","charCode","key","keyCode","which"],fix:function(e,t){r(e.which)&&(e.which=r(t.charCode)?t.keyCode:t.charCode),void 0===e.metaKey&&(e.metaKey=e.ctrlKey)}},{reg:/^touch/,props:["touches","changedTouches","targetTouches"]},{reg:/^hashchange$/,props:["newURL","oldURL"]},{reg:/^gesturechange$/i,props:["rotation","scale"]},{reg:/^(mousewheel|DOMMouseScroll)$/,props:[],fix:function(e,t){var n=void 0,o=void 0,r=void 0,i=t.wheelDelta,a=t.axis,s=t.wheelDeltaY,u=t.wheelDeltaX,l=t.detail;i&&(r=i/120),l&&(r=0-(l%3===0?l/3:l)),void 0!==a&&(a===e.HORIZONTAL_AXIS?(o=0,n=0-r):a===e.VERTICAL_AXIS&&(n=0,o=r)),void 0!==s&&(o=s/120),void 0!==u&&(n=-1*u/120),n||o||(o=r),void 0!==n&&(e.deltaX=n),void 0!==o&&(e.deltaY=o),void 0!==r&&(e.delta=r)}},{reg:/^mouse|contextmenu|click|mspointer|(^DOMMouseScroll$)/i,props:["buttons","clientX","clientY","button","offsetX","relatedTarget","which","fromElement","toElement","offsetY","pageX","pageY","screenX","screenY"],fix:function(e,t){var n=void 0,o=void 0,i=void 0,a=e.target,s=t.button;return a&&r(e.pageX)&&!r(t.clientX)&&(n=a.ownerDocument||document,o=n.documentElement,i=n.body,e.pageX=t.clientX+(o&&o.scrollLeft||i&&i.scrollLeft||0)-(o&&o.clientLeft||i&&i.clientLeft||0),e.pageY=t.clientY+(o&&o.scrollTop||i&&i.scrollTop||0)-(o&&o.clientTop||i&&i.clientTop||0)),e.which||void 0===s||(e.which=1&s?1:2&s?3:4&s?2:0),!e.relatedTarget&&e.fromElement&&(e.relatedTarget=e.fromElement===a?e.toElement:e.fromElement),e}}],v=l.default.prototype;(0,p.default)(s.prototype,v,{constructor:s,preventDefault:function(){var e=this.nativeEvent;e.preventDefault?e.preventDefault():e.returnValue=d,v.preventDefault.call(this)},stopPropagation:function(){var e=this.nativeEvent;e.stopPropagation?e.stopPropagation():e.cancelBubble=f,v.stopPropagation.call(this)}}),t.default=s,e.exports=t.default},function(e,t,n){"use strict";function o(){return!1}function r(){return!0}function i(){this.timeStamp=Date.now(),this.target=void 0,this.currentTarget=void 0}Object.defineProperty(t,"__esModule",{value:!0}),i.prototype={isEventObject:1,constructor:i,isDefaultPrevented:o,isPropagationStopped:o,isImmediatePropagationStopped:o,preventDefault:function(){this.isDefaultPrevented=r},stopPropagation:function(){this.isPropagationStopped=r},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=r,this.stopPropagation()},halt:function(e){e?this.stopImmediatePropagation():this.stopPropagation(),this.preventDefault()}},t.default=i,e.exports=t.default},function(e,t,n){"use strict";var o=n(2),r=n.n(o),i=n(9),a=n.n(i),s=n(3),u=n.n(s),l=n(4),c=n.n(l),p=n(0),f=n.n(p),d=n(8),h=n.n(d),b=n(1),v=n.n(b),g=function(e){function t(){var e,n,o,i;r()(this,t);for(var a=arguments.length,s=Array(a),l=0;l<a;l++)s[l]=arguments[l];return n=o=u()(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),o.removeContainer=function(){o.container&&(h.a.unmountComponentAtNode(o.container),o.container.parentNode.removeChild(o.container),o.container=null)},o.renderComponent=function(e,t){var n=o.props,r=n.visible,i=n.getComponent,a=n.forceRender,s=n.getContainer,u=n.parent;(r||u._component||a)&&(o.container||(o.container=s()),h.a.unstable_renderSubtreeIntoContainer(u,i(e),o.container,function(){t&&t.call(this)}))},i=n,u()(o,i)}return c()(t,e),a()(t,[{key:"componentDidMount",value:function(){this.props.autoMount&&this.renderComponent()}},{key:"componentDidUpdate",value:function(){this.props.autoMount&&this.renderComponent()}},{key:"componentWillUnmount",value:function(){this.props.autoDestroy&&this.removeContainer()}},{key:"render",value:function(){return this.props.children({renderComponent:this.renderComponent,removeContainer:this.removeContainer})}}]),t}(f.a.Component);g.propTypes={autoMount:v.a.bool,autoDestroy:v.a.bool,visible:v.a.bool,forceRender:v.a.bool,parent:v.a.any,getComponent:v.a.func.isRequired,getContainer:v.a.func.isRequired,children:v.a.func.isRequired},g.defaultProps={autoMount:!0,autoDestroy:!0,forceRender:!1},t.a=g},function(e,t,n){n(130);var o=n(6).Object;e.exports=function(e,t,n){return o.defineProperty(e,t,n)}},function(e,t,n){var o=n(10);o(o.S+o.F*!n(13),"Object",{defineProperty:n(12).f})},function(e,t,n){"use strict";var o=n(2),r=n.n(o),i=n(9),a=n.n(i),s=n(3),u=n.n(s),l=n(4),c=n.n(l),p=n(0),f=n.n(p),d=n(8),h=n.n(d),b=n(1),v=n.n(b),g=function(e){function t(){return r()(this,t),u()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return c()(t,e),a()(t,[{key:"componentDidMount",value:function(){this.createContainer()}},{key:"componentDidUpdate",value:function(e){var t=this.props.didUpdate;t&&t(e)}},{key:"componentWillUnmount",value:function(){this.removeContainer()}},{key:"createContainer",value:function(){this._container=this.props.getContainer(),this.forceUpdate()}},{key:"removeContainer",value:function(){this._container&&this._container.parentNode.removeChild(this._container)}},{key:"render",value:function(){return this._container?h.a.createPortal(this.props.children,this._container):null}}]),t}(f.a.Component);g.propTypes={getContainer:v.a.func.isRequired,children:v.a.node.isRequired,didUpdate:v.a.func},t.a=g},function(e,t,n){"use strict";var o=n(5),r=n.n(o),i=n(2),a=n.n(i),s=n(3),u=n.n(s),l=n(4),c=n.n(l),p=n(0),f=n.n(p),d=n(1),h=n.n(d),b=n(8),v=n.n(b),g=n(133),m=n(144),y=n(150),E=n(77),w=n(70),O=function(e){function t(n){a()(this,t);var o=u()(this,e.call(this,n));return x.call(o),o.state={stretchChecked:!1,targetWidth:void 0,targetHeight:void 0},o.savePopupRef=w.c.bind(o,"popupInstance"),o.saveAlignRef=w.c.bind(o,"alignInstance"),o}return c()(t,e),t.prototype.componentDidMount=function(){this.rootNode=this.getPopupDomNode(),this.setStretchSize()},t.prototype.componentDidUpdate=function(){this.setStretchSize()},t.prototype.getPopupDomNode=function(){return v.a.findDOMNode(this.popupInstance)},t.prototype.getMaskTransitionName=function(){var e=this.props,t=e.maskTransitionName,n=e.maskAnimation;return!t&&n&&(t=e.prefixCls+"-"+n),t},t.prototype.getTransitionName=function(){var e=this.props,t=e.transitionName;return!t&&e.animation&&(t=e.prefixCls+"-"+e.animation),t},t.prototype.getClassName=function(e){return this.props.prefixCls+" "+this.props.className+" "+e},t.prototype.getPopupElement=function(){var e=this,t=this.savePopupRef,n=this.state,o=n.stretchChecked,i=n.targetHeight,a=n.targetWidth,s=this.props,u=s.align,l=s.visible,c=s.prefixCls,p=s.style,d=s.getClassNameFromAlign,h=s.destroyPopupOnHide,b=s.stretch,v=s.children,E=s.onMouseEnter,w=s.onMouseLeave,O=s.onMouseDown,x=s.onTouchStart,C=this.getClassName(this.currentAlignClassName||d(u)),S=c+"-hidden";l||(this.currentAlignClassName=null);var k={};b&&(-1!==b.indexOf("height")?k.height=i:-1!==b.indexOf("minHeight")&&(k.minHeight=i),-1!==b.indexOf("width")?k.width=a:-1!==b.indexOf("minWidth")&&(k.minWidth=a),o||(k.visibility="hidden",setTimeout(function(){e.alignInstance&&e.alignInstance.forceAlign()},0)));var T=r()({},k,p,this.getZIndexStyle()),A={className:C,prefixCls:c,ref:t,onMouseEnter:E,onMouseLeave:w,onMouseDown:O,onTouchStart:x,style:T};return h?f.a.createElement(m.a,{component:"",exclusive:!0,transitionAppear:!0,transitionName:this.getTransitionName()},l?f.a.createElement(g.a,{target:this.getAlignTarget(),key:"popup",ref:this.saveAlignRef,monitorWindowResize:!0,align:u,onAlign:this.onAlign},f.a.createElement(y.a,r()({visible:!0},A),v)):null):f.a.createElement(m.a,{component:"",exclusive:!0,transitionAppear:!0,transitionName:this.getTransitionName(),showProp:"xVisible"},f.a.createElement(g.a,{target:this.getAlignTarget(),key:"popup",ref:this.saveAlignRef,monitorWindowResize:!0,xVisible:l,childrenProps:{visible:"xVisible"},disabled:!l,align:u,onAlign:this.onAlign},f.a.createElement(y.a,r()({hiddenClassName:S},A),v)))},t.prototype.getZIndexStyle=function(){var e={},t=this.props;return void 0!==t.zIndex&&(e.zIndex=t.zIndex),e},t.prototype.getMaskElement=function(){var e=this.props,t=void 0;if(e.mask){var n=this.getMaskTransitionName();t=f.a.createElement(E.a,{style:this.getZIndexStyle(),key:"mask",className:e.prefixCls+"-mask",hiddenClassName:e.prefixCls+"-mask-hidden",visible:e.visible}),n&&(t=f.a.createElement(m.a,{key:"mask",showProp:"visible",transitionAppear:!0,component:"",transitionName:n},t))}return t},t.prototype.render=function(){return f.a.createElement("div",null,this.getMaskElement(),this.getPopupElement())},t}(p.Component);O.propTypes={visible:h.a.bool,style:h.a.object,getClassNameFromAlign:h.a.func,onAlign:h.a.func,getRootDomNode:h.a.func,align:h.a.any,destroyPopupOnHide:h.a.bool,className:h.a.string,prefixCls:h.a.string,onMouseEnter:h.a.func,onMouseLeave:h.a.func,onMouseDown:h.a.func,onTouchStart:h.a.func,stretch:h.a.string,children:h.a.node,point:h.a.shape({pageX:h.a.number,pageY:h.a.number})};var x=function(){var e=this;this.onAlign=function(t,n){var o=e.props,r=o.getClassNameFromAlign(n);e.currentAlignClassName!==r&&(e.currentAlignClassName=r,t.className=e.getClassName(r)),o.onAlign(t,n)},this.setStretchSize=function(){var t=e.props,n=t.stretch,o=t.getRootDomNode,r=t.visible,i=e.state,a=i.stretchChecked,s=i.targetHeight,u=i.targetWidth;if(!n||!r)return void(a&&e.setState({stretchChecked:!1}));var l=o();if(l){var c=l.offsetHeight,p=l.offsetWidth;s===c&&u===p&&a||e.setState({stretchChecked:!0,targetHeight:c,targetWidth:p})}},this.getTargetElement=function(){return e.props.getRootDomNode()},this.getAlignTarget=function(){var t=e.props.point;return t||e.getTargetElement}};t.a=O},function(e,t,n){"use strict";var o=n(134);t.a=o.a},function(e,t,n){"use strict";function o(e){return"function"===typeof e&&e?e():null}function r(e){return"object"===typeof e&&e?e:null}var i=n(2),a=n.n(i),s=n(3),u=n.n(s),l=n(4),c=n.n(l),p=n(0),f=n.n(p),d=n(1),h=n.n(d),b=n(8),v=n.n(b),g=n(135),m=n(32),y=n(143),E=function(e){function t(){var n,i,s;a()(this,t);for(var l=arguments.length,c=Array(l),p=0;p<l;p++)c[p]=arguments[p];return n=i=u()(this,e.call.apply(e,[this].concat(c))),i.forceAlign=function(){var e=i.props,t=e.disabled,n=e.target,a=e.align,s=e.onAlign;if(!t&&n){var u=v.a.findDOMNode(i),l=void 0,c=o(n),p=r(n);c?l=Object(g.a)(u,c,a):p&&(l=Object(g.b)(u,p,a)),s&&s(u,l)}},s=n,u()(i,s)}return c()(t,e),t.prototype.componentDidMount=function(){var e=this.props;this.forceAlign(),!e.disabled&&e.monitorWindowResize&&this.startMonitorWindowResize()},t.prototype.componentDidUpdate=function(e){var t=!1,n=this.props;if(!n.disabled){var i=v.a.findDOMNode(this),a=i?i.getBoundingClientRect():null;if(e.disabled)t=!0;else{var s=o(e.target),u=o(n.target),l=r(e.target),c=r(n.target);Object(y.c)(s)&&Object(y.c)(u)?t=!1:(s!==u||s&&!u&&c||l&&c&&u||c&&!Object(y.b)(l,c))&&(t=!0);var p=this.sourceRect||{};t||!i||p.width===a.width&&p.height===a.height||(t=!0)}this.sourceRect=a}t&&this.forceAlign(),n.monitorWindowResize&&!n.disabled?this.startMonitorWindowResize():this.stopMonitorWindowResize()},t.prototype.componentWillUnmount=function(){this.stopMonitorWindowResize()},t.prototype.startMonitorWindowResize=function(){this.resizeHandler||(this.bufferMonitor=Object(y.a)(this.forceAlign,this.props.monitorBufferTime),this.resizeHandler=Object(m.a)(window,"resize",this.bufferMonitor))},t.prototype.stopMonitorWindowResize=function(){this.resizeHandler&&(this.bufferMonitor.clear(),this.resizeHandler.remove(),this.resizeHandler=null)},t.prototype.render=function(){var e=this,t=this.props,n=t.childrenProps,o=t.children,r=f.a.Children.only(o);if(n){var i={};return Object.keys(n).forEach(function(t){i[t]=e.props[n[t]]}),f.a.cloneElement(r,i)}return r},t}(p.Component);E.propTypes={childrenProps:h.a.object,align:h.a.object.isRequired,target:h.a.oneOfType([h.a.func,h.a.shape({clientX:h.a.number,clientY:h.a.number,pageX:h.a.number,pageY:h.a.number})]),onAlign:h.a.func,monitorBufferTime:h.a.number,monitorWindowResize:h.a.bool,disabled:h.a.bool,children:h.a.any},E.defaultProps={target:function(){return window},monitorBufferTime:50,monitorWindowResize:!1,disabled:!1},t.a=E},function(e,t,n){"use strict";var o=n(136),r=n(142);n.d(t,"a",function(){return o.a}),n.d(t,"b",function(){return r.a});o.a},function(e,t,n){"use strict";function o(e){var t=Object(s.a)(e),n=Object(u.a)(e);return!t||n.left+n.width<=t.left||n.top+n.height<=t.top||n.left>=t.right||n.top>=t.bottom}function r(e,t,n){var r=n.target||t,a=Object(u.a)(r),s=!o(r);return Object(i.a)(e,a,n,s)}var i=n(71),a=n(73),s=n(72),u=n(74);r.__getOffsetParent=a.a,r.__getVisibleRectForElement=s.a,t.a=r},function(e,t,n){"use strict";function o(){if(void 0!==p)return p;p="";var e=document.createElement("p").style;for(var t in f)t+"Transform"in e&&(p=t);return p}function r(){return o()?o()+"TransitionProperty":"transitionProperty"}function i(){return o()?o()+"Transform":"transform"}function a(e,t){var n=r();n&&(e.style[n]=t,"transitionProperty"!==n&&(e.style.transitionProperty=t))}function s(e,t){var n=i();n&&(e.style[n]=t,"transform"!==n&&(e.style.transform=t))}function u(e){return e.style.transitionProperty||e.style[r()]}function l(e){var t=window.getComputedStyle(e,null),n=t.getPropertyValue("transform")||t.getPropertyValue(i());if(n&&"none"!==n){var o=n.replace(/[^0-9\-.,]/g,"").split(",");return{x:parseFloat(o[12]||o[4],0),y:parseFloat(o[13]||o[5],0)}}return{x:0,y:0}}function c(e,t){var n=window.getComputedStyle(e,null),o=n.getPropertyValue("transform")||n.getPropertyValue(i());if(o&&"none"!==o){var r=void 0,a=o.match(d);if(a)a=a[1],r=a.split(",").map(function(e){return parseFloat(e,10)}),r[4]=t.x,r[5]=t.y,s(e,"matrix("+r.join(",")+")");else{r=o.match(h)[1].split(",").map(function(e){return parseFloat(e,10)}),r[12]=t.x,r[13]=t.y,s(e,"matrix3d("+r.join(",")+")")}}else s(e,"translateX("+t.x+"px) translateY("+t.y+"px) translateZ(0)")}t.a=i,t.e=a,t.c=u,t.b=l,t.d=c;var p=void 0,f={Webkit:"-webkit-",Moz:"-moz-",ms:"-ms-",O:"-o-"},d=/matrix\((.*)\)/,h=/matrix3d\((.*)\)/},function(e,t,n){"use strict";function o(e){if(r.a.isWindow(e)||9===e.nodeType)return!1;var t=r.a.getDocument(e),n=t.body,o=null;for(o=e.parentNode;o&&o!==n;o=o.parentNode){if("fixed"===r.a.css(o,"position"))return!0}return!1}t.a=o;var r=n(17)},function(e,t,n){"use strict";function o(e,t,n,o){var i=r.a.clone(e),a={width:t.width,height:t.height};return o.adjustX&&i.left<n.left&&(i.left=n.left),o.resizeWidth&&i.left>=n.left&&i.left+a.width>n.right&&(a.width-=i.left+a.width-n.right),o.adjustX&&i.left+a.width>n.right&&(i.left=Math.max(n.right-a.width,n.left)),o.adjustY&&i.top<n.top&&(i.top=n.top),o.resizeHeight&&i.top>=n.top&&i.top+a.height>n.bottom&&(a.height-=i.top+a.height-n.bottom),o.adjustY&&i.top+a.height>n.bottom&&(i.top=Math.max(n.bottom-a.height,n.top)),r.a.mix(i,a)}var r=n(17);t.a=o},function(e,t,n){"use strict";function o(e,t,n,o,i){var a=Object(r.a)(t,n[1]),s=Object(r.a)(e,n[0]),u=[s.left-a.left,s.top-a.top];return{left:e.left-u[0]+o[0]-i[0],top:e.top-u[1]+o[1]-i[1]}}var r=n(141);t.a=o},function(e,t,n){"use strict";function o(e,t){var n=t.charAt(0),o=t.charAt(1),r=e.width,i=e.height,a=e.left,s=e.top;return"c"===n?s+=i/2:"b"===n&&(s+=i),"c"===o?a+=r/2:"r"===o&&(a+=r),{left:a,top:s}}t.a=o},function(e,t,n){"use strict";function o(e,t,n){var o=void 0,s=void 0,u=r.a.getDocument(e),l=u.defaultView||u.parentWindow,c=r.a.getWindowScrollLeft(l),p=r.a.getWindowScrollTop(l),f=r.a.viewportWidth(l),d=r.a.viewportHeight(l);o="pageX"in t?t.pageX:c+t.clientX,s="pageY"in t?t.pageY:p+t.clientY;var h={left:o,top:s,width:0,height:0},b=o>=0&&o<=c+f&&s>=0&&s<=p+d,v=[n.points[0],"cc"];return Object(i.a)(e,h,a({},n,{points:v}),b)}var r=n(17),i=n(71),a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e};t.a=o},function(e,t,n){"use strict";function o(e,t){function n(){r&&(clearTimeout(r),r=null)}function o(){n(),r=setTimeout(e,t)}var r=void 0;return o.clear=n,o}function r(e,t){return e===t||!(!e||!t)&&("pageX"in t&&"pageY"in t?e.pageX===t.pageX&&e.pageY===t.pageY:"clientX"in t&&"clientY"in t&&(e.clientX===t.clientX&&e.clientY===t.clientY))}function i(e){return e&&"object"===typeof e&&e.window===e}t.a=o,t.b=r,t.c=i},function(e,t,n){"use strict";function o(e){var t=e.children;return m.a.isValidElement(t)&&!t.key?m.a.cloneElement(t,{key:C}):t}function r(){}var i=n(5),a=n.n(i),s=n(18),u=n.n(s),l=n(2),c=n.n(l),p=n(9),f=n.n(p),d=n(3),h=n.n(d),b=n(4),v=n.n(b),g=n(0),m=n.n(g),y=n(1),E=n.n(y),w=n(145),O=n(146),x=n(76),C="rc_animate_"+Date.now(),S=function(e){function t(e){c()(this,t);var n=h()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return k.call(n),n.currentlyAnimatingKeys={},n.keysToEnter=[],n.keysToLeave=[],n.state={children:Object(w.e)(o(e))},n.childrenRefs={},n}return v()(t,e),f()(t,[{key:"componentDidMount",value:function(){var e=this,t=this.props.showProp,n=this.state.children;t&&(n=n.filter(function(e){return!!e.props[t]})),n.forEach(function(t){t&&e.performAppear(t.key)})}},{key:"componentWillReceiveProps",value:function(e){var t=this;this.nextProps=e;var n=Object(w.e)(o(e)),r=this.props;r.exclusive&&Object.keys(this.currentlyAnimatingKeys).forEach(function(e){t.stop(e)});var i=r.showProp,a=this.currentlyAnimatingKeys,s=r.exclusive?Object(w.e)(o(r)):this.state.children,l=[];i?(s.forEach(function(e){var t=e&&Object(w.a)(n,e.key),o=void 0;(o=t&&t.props[i]||!e.props[i]?t:m.a.cloneElement(t||e,u()({},i,!0)))&&l.push(o)}),n.forEach(function(e){e&&Object(w.a)(s,e.key)||l.push(e)})):l=Object(w.d)(s,n),this.setState({children:l}),n.forEach(function(e){var n=e&&e.key;if(!e||!a[n]){var o=e&&Object(w.a)(s,n);if(i){var r=e.props[i];if(o){!Object(w.b)(s,n,i)&&r&&t.keysToEnter.push(n)}else r&&t.keysToEnter.push(n)}else o||t.keysToEnter.push(n)}}),s.forEach(function(e){var o=e&&e.key;if(!e||!a[o]){var r=e&&Object(w.a)(n,o);if(i){var s=e.props[i];if(r){!Object(w.b)(n,o,i)&&s&&t.keysToLeave.push(o)}else s&&t.keysToLeave.push(o)}else r||t.keysToLeave.push(o)}})}},{key:"componentDidUpdate",value:function(){var e=this.keysToEnter;this.keysToEnter=[],e.forEach(this.performEnter);var t=this.keysToLeave;this.keysToLeave=[],t.forEach(this.performLeave)}},{key:"isValidChildByKey",value:function(e,t){var n=this.props.showProp;return n?Object(w.b)(e,t,n):Object(w.a)(e,t)}},{key:"stop",value:function(e){delete this.currentlyAnimatingKeys[e];var t=this.childrenRefs[e];t&&t.stop()}},{key:"render",value:function(){var e=this,t=this.props;this.nextProps=t;var n=this.state.children,o=null;n&&(o=n.map(function(n){if(null===n||void 0===n)return n;if(!n.key)throw new Error("must set key for <rc-animate> children");return m.a.createElement(O.a,{key:n.key,ref:function(t){e.childrenRefs[n.key]=t},animation:t.animation,transitionName:t.transitionName,transitionEnter:t.transitionEnter,transitionAppear:t.transitionAppear,transitionLeave:t.transitionLeave},n)}));var r=t.component;if(r){var i=t;return"string"===typeof r&&(i=a()({className:t.className,style:t.style},t.componentProps)),m.a.createElement(r,i,o)}return o[0]||null}}]),t}(m.a.Component);S.isAnimate=!0,S.propTypes={component:E.a.any,componentProps:E.a.object,animation:E.a.object,transitionName:E.a.oneOfType([E.a.string,E.a.object]),transitionEnter:E.a.bool,transitionAppear:E.a.bool,exclusive:E.a.bool,transitionLeave:E.a.bool,onEnd:E.a.func,onEnter:E.a.func,onLeave:E.a.func,onAppear:E.a.func,showProp:E.a.string,children:E.a.node},S.defaultProps={animation:{},component:"span",componentProps:{},transitionEnter:!0,transitionLeave:!0,transitionAppear:!1,onEnd:r,onEnter:r,onLeave:r,onAppear:r};var k=function(){var e=this;this.performEnter=function(t){e.childrenRefs[t]&&(e.currentlyAnimatingKeys[t]=!0,e.childrenRefs[t].componentWillEnter(e.handleDoneAdding.bind(e,t,"enter")))},this.performAppear=function(t){e.childrenRefs[t]&&(e.currentlyAnimatingKeys[t]=!0,e.childrenRefs[t].componentWillAppear(e.handleDoneAdding.bind(e,t,"appear")))},this.handleDoneAdding=function(t,n){var r=e.props;if(delete e.currentlyAnimatingKeys[t],!r.exclusive||r===e.nextProps){var i=Object(w.e)(o(r));e.isValidChildByKey(i,t)?"appear"===n?x.a.allowAppearCallback(r)&&(r.onAppear(t),r.onEnd(t,!0)):x.a.allowEnterCallback(r)&&(r.onEnter(t),r.onEnd(t,!0)):e.performLeave(t)}},this.performLeave=function(t){e.childrenRefs[t]&&(e.currentlyAnimatingKeys[t]=!0,e.childrenRefs[t].componentWillLeave(e.handleDoneLeaving.bind(e,t)))},this.handleDoneLeaving=function(t){var n=e.props;if(delete e.currentlyAnimatingKeys[t],!n.exclusive||n===e.nextProps){var r=Object(w.e)(o(n));if(e.isValidChildByKey(r,t))e.performEnter(t);else{var i=function(){x.a.allowLeaveCallback(n)&&(n.onLeave(t),n.onEnd(t,!1))};Object(w.c)(e.state.children,r,n.showProp)?i():e.setState({children:r},i)}}}};t.a=S},function(e,t,n){"use strict";function o(e){var t=[];return l.a.Children.forEach(e,function(e){t.push(e)}),t}function r(e,t){var n=null;return e&&e.forEach(function(e){n||e&&e.key===t&&(n=e)}),n}function i(e,t,n){var o=null;return e&&e.forEach(function(e){if(e&&e.key===t&&e.props[n]){if(o)throw new Error("two child with same key for <rc-animate> children");o=e}}),o}function a(e,t,n){var o=e.length===t.length;return o&&e.forEach(function(e,r){var i=t[r];e&&i&&(e&&!i||!e&&i?o=!1:e.key!==i.key?o=!1:n&&e.props[n]!==i.props[n]&&(o=!1))}),o}function s(e,t){var n=[],o={},i=[];return e.forEach(function(e){e&&r(t,e.key)?i.length&&(o[e.key]=i,i=[]):i.push(e)}),t.forEach(function(e){e&&Object.prototype.hasOwnProperty.call(o,e.key)&&(n=n.concat(o[e.key])),n.push(e)}),n=n.concat(i)}t.e=o,t.a=r,t.b=i,t.c=a,t.d=s;var u=n(0),l=n.n(u)},function(e,t,n){"use strict";var o=n(2),r=n.n(o),i=n(9),a=n.n(i),s=n(3),u=n.n(s),l=n(4),c=n.n(l),p=n(0),f=n.n(p),d=n(8),h=n.n(d),b=n(1),v=n.n(b),g=n(147),m=n(76),y={enter:"transitionEnter",appear:"transitionAppear",leave:"transitionLeave"},E=function(e){function t(){return r()(this,t),u()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return c()(t,e),a()(t,[{key:"componentWillUnmount",value:function(){this.stop()}},{key:"componentWillEnter",value:function(e){m.a.isEnterSupported(this.props)?this.transition("enter",e):e()}},{key:"componentWillAppear",value:function(e){m.a.isAppearSupported(this.props)?this.transition("appear",e):e()}},{key:"componentWillLeave",value:function(e){m.a.isLeaveSupported(this.props)?this.transition("leave",e):e()}},{key:"transition",value:function(e,t){var n=this,o=h.a.findDOMNode(this),r=this.props,i=r.transitionName,a="object"===typeof i;this.stop();var s=function(){n.stopper=null,t()};if((g.b||!r.animation[e])&&i&&r[y[e]]){var u=a?i[e]:i+"-"+e,l=u+"-active";a&&i[e+"Active"]&&(l=i[e+"Active"]),this.stopper=Object(g.a)(o,{name:u,active:l},s)}else this.stopper=r.animation[e](o,s)}},{key:"stop",value:function(){var e=this.stopper;e&&(this.stopper=null,e.stop())}},{key:"render",value:function(){return this.props.children}}]),t}(f.a.Component);E.propTypes={children:v.a.any},t.a=E},function(e,t,n){"use strict";function o(e,t){for(var n=window.getComputedStyle(e,null),o="",r=0;r<d.length&&!(o=n.getPropertyValue(d[r]+t));r++);return o}function r(e){if(p){var t=parseFloat(o(e,"transition-delay"))||0,n=parseFloat(o(e,"transition-duration"))||0,r=parseFloat(o(e,"animation-delay"))||0,i=parseFloat(o(e,"animation-duration"))||0,a=Math.max(n+t,i+r);e.rcEndAnimTimeout=setTimeout(function(){e.rcEndAnimTimeout=null,e.rcEndListener&&e.rcEndListener()},1e3*a+200)}}function i(e){e.rcEndAnimTimeout&&(clearTimeout(e.rcEndAnimTimeout),e.rcEndAnimTimeout=null)}n.d(t,"b",function(){return p});var a=n(43),s=n.n(a),u=n(148),l=n(149),c=n.n(l),p=0!==u.a.endEvents.length,f=["Webkit","Moz","O","ms"],d=["-webkit-","-moz-","-o-","ms-",""],h=function(e,t,n){var o="object"===("undefined"===typeof t?"undefined":s()(t)),a=o?t.name:t,l=o?t.active:t+"-active",p=n,f=void 0,d=void 0,h=c()(e);return n&&"[object Object]"===Object.prototype.toString.call(n)&&(p=n.end,f=n.start,d=n.active),e.rcEndListener&&e.rcEndListener(),e.rcEndListener=function(t){t&&t.target!==e||(e.rcAnimTimeout&&(clearTimeout(e.rcAnimTimeout),e.rcAnimTimeout=null),i(e),h.remove(a),h.remove(l),u.a.removeEndEventListener(e,e.rcEndListener),e.rcEndListener=null,p&&p())},u.a.addEndEventListener(e,e.rcEndListener),f&&f(),h.add(a),e.rcAnimTimeout=setTimeout(function(){e.rcAnimTimeout=null,h.add(l),d&&setTimeout(d,0),r(e)},30),{stop:function(){e.rcEndListener&&e.rcEndListener()}}};h.style=function(e,t,n){e.rcEndListener&&e.rcEndListener(),e.rcEndListener=function(t){t&&t.target!==e||(e.rcAnimTimeout&&(clearTimeout(e.rcAnimTimeout),e.rcAnimTimeout=null),i(e),u.a.removeEndEventListener(e,e.rcEndListener),e.rcEndListener=null,n&&n())},u.a.addEndEventListener(e,e.rcEndListener),e.rcAnimTimeout=setTimeout(function(){for(var n in t)t.hasOwnProperty(n)&&(e.style[n]=t[n]);e.rcAnimTimeout=null,r(e)},0)},h.setTransition=function(e,t,n){var o=t,r=n;void 0===n&&(r=o,o=""),o=o||"",f.forEach(function(t){e.style[t+"Transition"+o]=r})},h.isCssAnimationSupported=p,t.a=h},function(e,t,n){"use strict";function o(e,t,n){e.addEventListener(t,n,!1)}function r(e,t,n){e.removeEventListener(t,n,!1)}var i={transitionstart:{transition:"transitionstart",WebkitTransition:"webkitTransitionStart",MozTransition:"mozTransitionStart",OTransition:"oTransitionStart",msTransition:"MSTransitionStart"},animationstart:{animation:"animationstart",WebkitAnimation:"webkitAnimationStart",MozAnimation:"mozAnimationStart",OAnimation:"oAnimationStart",msAnimation:"MSAnimationStart"}},a={transitionend:{transition:"transitionend",WebkitTransition:"webkitTransitionEnd",MozTransition:"mozTransitionEnd",OTransition:"oTransitionEnd",msTransition:"MSTransitionEnd"},animationend:{animation:"animationend",WebkitAnimation:"webkitAnimationEnd",MozAnimation:"mozAnimationEnd",OAnimation:"oAnimationEnd",msAnimation:"MSAnimationEnd"}},s=[],u=[];"undefined"!==typeof window&&"undefined"!==typeof document&&function(){function e(e,t){for(var o in e)if(e.hasOwnProperty(o)){var r=e[o];for(var i in r)if(i in n){t.push(r[i]);break}}}var t=document.createElement("div"),n=t.style;"AnimationEvent"in window||(delete i.animationstart.animation,delete a.animationend.animation),"TransitionEvent"in window||(delete i.transitionstart.transition,delete a.transitionend.transition),e(i,s),e(a,u)}();var l={startEvents:s,addStartEventListener:function(e,t){if(0===s.length)return void window.setTimeout(t,0);s.forEach(function(n){o(e,n,t)})},removeStartEventListener:function(e,t){0!==s.length&&s.forEach(function(n){r(e,n,t)})},endEvents:u,addEndEventListener:function(e,t){if(0===u.length)return void window.setTimeout(t,0);u.forEach(function(n){o(e,n,t)})},removeEndEventListener:function(e,t){0!==u.length&&u.forEach(function(n){r(e,n,t)})}};t.a=l},function(e,t,n){function o(e){if(!e||!e.nodeType)throw new Error("A DOM element reference is required");this.el=e,this.list=e.classList}try{var r=n(75)}catch(e){var r=n(75)}var i=/\s+/,a=Object.prototype.toString;e.exports=function(e){return new o(e)},o.prototype.add=function(e){if(this.list)return this.list.add(e),this;var t=this.array();return~r(t,e)||t.push(e),this.el.className=t.join(" "),this},o.prototype.remove=function(e){if("[object RegExp]"==a.call(e))return this.removeMatching(e);if(this.list)return this.list.remove(e),this;var t=this.array(),n=r(t,e);return~n&&t.splice(n,1),this.el.className=t.join(" "),this},o.prototype.removeMatching=function(e){for(var t=this.array(),n=0;n<t.length;n++)e.test(t[n])&&this.remove(t[n]);return this},o.prototype.toggle=function(e,t){return this.list?("undefined"!==typeof t?t!==this.list.toggle(e,t)&&this.list.toggle(e):this.list.toggle(e),this):("undefined"!==typeof t?t?this.add(e):this.remove(e):this.has(e)?this.remove(e):this.add(e),this)},o.prototype.array=function(){var e=this.el.getAttribute("class")||"",t=e.replace(/^\s+|\s+$/g,""),n=t.split(i);return""===n[0]&&n.shift(),n},o.prototype.has=o.prototype.contains=function(e){return this.list?this.list.contains(e):!!~r(this.array(),e)}},function(e,t,n){"use strict";var o=n(2),r=n.n(o),i=n(3),a=n.n(i),s=n(4),u=n.n(s),l=n(0),c=n.n(l),p=n(1),f=n.n(p),d=n(77),h=function(e){function t(){return r()(this,t),a()(this,e.apply(this,arguments))}return u()(t,e),t.prototype.render=function(){var e=this.props,t=e.className;return e.visible||(t+=" "+e.hiddenClassName),c.a.createElement("div",{className:t,onMouseEnter:e.onMouseEnter,onMouseLeave:e.onMouseLeave,onMouseDown:e.onMouseDown,onTouchStart:e.onTouchStart,style:e.style},c.a.createElement(d.a,{className:e.prefixCls+"-content",visible:e.visible},e.children))},t}(l.Component);h.propTypes={hiddenClassName:f.a.string,className:f.a.string,prefixCls:f.a.string,onMouseEnter:f.a.func,onMouseLeave:f.a.func,onMouseDown:f.a.func,onTouchStart:f.a.func,children:f.a.any},t.a=h},function(e,t,n){"use strict";n.d(t,"a",function(){return i});var o={adjustX:1,adjustY:1},r=[0,0],i={left:{points:["cr","cl"],overflow:o,offset:[-4,0],targetOffset:r},right:{points:["cl","cr"],overflow:o,offset:[4,0],targetOffset:r},top:{points:["bc","tc"],overflow:o,offset:[0,-4],targetOffset:r},bottom:{points:["tc","bc"],overflow:o,offset:[0,4],targetOffset:r},topLeft:{points:["bl","tl"],overflow:o,offset:[0,-4],targetOffset:r},leftTop:{points:["tr","tl"],overflow:o,offset:[-4,0],targetOffset:r},topRight:{points:["br","tr"],overflow:o,offset:[0,-4],targetOffset:r},rightTop:{points:["tl","tr"],overflow:o,offset:[4,0],targetOffset:r},bottomRight:{points:["tr","br"],overflow:o,offset:[0,4],targetOffset:r},rightBottom:{points:["bl","br"],overflow:o,offset:[4,0],targetOffset:r},bottomLeft:{points:["tl","bl"],overflow:o,offset:[0,4],targetOffset:r},leftBottom:{points:["br","bl"],overflow:o,offset:[-4,0],targetOffset:r}}},function(e,t,n){"use strict";var o=n(2),r=n.n(o),i=n(3),a=n.n(i),s=n(4),u=n.n(s),l=n(0),c=n.n(l),p=n(1),f=n.n(p),d=function(e){function t(){return r()(this,t),a()(this,e.apply(this,arguments))}return u()(t,e),t.prototype.componentDidUpdate=function(){var e=this.props.trigger;e&&e.forcePopupAlign()},t.prototype.render=function(){var e=this.props,t=e.overlay,n=e.prefixCls,o=e.id;return c.a.createElement("div",{className:n+"-inner",id:o,role:"tooltip"},"function"===typeof t?t():t)},t}(c.a.Component);d.propTypes={prefixCls:f.a.string,overlay:f.a.oneOfType([f.a.node,f.a.func]).isRequired,id:f.a.string,trigger:f.a.any},t.a=d},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=n(154),r=n(174),i=n(51),a=n(176);n.d(t,"Range",function(){return r.a}),n.d(t,"Handle",function(){return i.a}),n.d(t,"createSliderWithTooltip",function(){return a.a}),o.a.Range=r.a,o.a.Handle=i.a,o.a.createSliderWithTooltip=a.a,t.default=o.a},function(e,t,n){"use strict";var o=n(5),r=n.n(o),i=n(2),a=n.n(i),s=n(9),u=n.n(s),l=n(3),c=n.n(l),p=n(4),f=n.n(p),d=n(0),h=n.n(d),b=n(1),v=n.n(b),g=n(50),m=n.n(g),y=n(78),E=n(79),w=n(52),O=function(e){function t(e){a()(this,t);var n=c()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));n.onEnd=function(){n.setState({dragging:!1}),n.removeDocumentEvents(),n.props.onAfterChange(n.getValue())};var o=void 0!==e.defaultValue?e.defaultValue:e.min,r=void 0!==e.value?e.value:o;return n.state={value:n.trimAlignValue(r),dragging:!1},w.g()&&(m()(!("minimumTrackStyle"in e),"minimumTrackStyle will be deprecate, please use trackStyle instead."),m()(!("maximumTrackStyle"in e),"maximumTrackStyle will be deprecate, please use railStyle instead.")),n}return f()(t,e),u()(t,[{key:"componentDidMount",value:function(){var e=this.props,t=e.autoFocus,n=e.disabled;t&&!n&&this.focus()}},{key:"componentWillReceiveProps",value:function(e){if("value"in e||"min"in e||"max"in e){var t=this.state.value,n=void 0!==e.value?e.value:t,o=this.trimAlignValue(n,e);o!==t&&(this.setState({value:o}),w.j(n,e)&&this.props.onChange(o))}}},{key:"onChange",value:function(e){var t=this.props;!("value"in t)&&this.setState(e);var n=e.value;t.onChange(n)}},{key:"onStart",value:function(e){this.setState({dragging:!0});var t=this.props,n=this.getValue();t.onBeforeChange(n);var o=this.calcValueByPos(e);this.startValue=o,this.startPosition=e,o!==n&&(this.prevMovedHandleIndex=0,this.onChange({value:o}))}},{key:"onMove",value:function(e,t){w.k(e);var n=this.state.value,o=this.calcValueByPos(t);o!==n&&this.onChange({value:o})}},{key:"onKeyboard",value:function(e){var t=w.d(e);if(t){w.k(e);var n=this.state,o=n.value,r=t(o,this.props),i=this.trimAlignValue(r);if(i===o)return;this.onChange({value:i})}}},{key:"getValue",value:function(){return this.state.value}},{key:"getLowerBound",value:function(){return this.props.min}},{key:"getUpperBound",value:function(){return this.state.value}},{key:"trimAlignValue",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null===e)return null;var n=r()({},this.props,t),o=w.a(e,n);return w.b(o,n)}},{key:"render",value:function(){var e=this,t=this.props,n=t.prefixCls,o=t.vertical,i=t.included,a=t.disabled,s=t.minimumTrackStyle,u=t.trackStyle,l=t.handleStyle,c=t.tabIndex,p=t.min,f=t.max,d=t.handle,b=this.state,v=b.value,g=b.dragging,m=this.calcOffset(v),E=d({className:n+"-handle",prefixCls:n,vertical:o,offset:m,value:v,dragging:g,disabled:a,min:p,max:f,index:0,tabIndex:c,style:l[0]||l,ref:function(t){return e.saveHandle(0,t)}}),w=u[0]||u;return{tracks:h.a.createElement(y.a,{className:n+"-track",vertical:o,included:i,offset:0,length:m,style:r()({},s,w)}),handles:E}}}]),t}(h.a.Component);O.propTypes={defaultValue:v.a.number,value:v.a.number,disabled:v.a.bool,autoFocus:v.a.bool,tabIndex:v.a.number,min:v.a.number,max:v.a.number},t.a=Object(E.a)(O)},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var r=n(156),i=o(r),a=n(159),s=o(a);t.default=function e(t,n,o){null===t&&(t=Function.prototype);var r=(0,s.default)(t,n);if(void 0===r){var a=(0,i.default)(t);return null===a?void 0:e(a,n,o)}if("value"in r)return r.value;var u=r.get;if(void 0!==u)return u.call(o)}},function(e,t,n){e.exports={default:n(157),__esModule:!0}},function(e,t,n){n(158),e.exports=n(6).Object.getPrototypeOf},function(e,t,n){var o=n(31),r=n(66);n(80)("getPrototypeOf",function(){return function(e){return r(o(e))}})},function(e,t,n){e.exports={default:n(160),__esModule:!0}},function(e,t,n){n(161);var o=n(6).Object;e.exports=function(e,t){return o.getOwnPropertyDescriptor(e,t)}},function(e,t,n){var o=n(15),r=n(48).f;n(80)("getOwnPropertyDescriptor",function(){return function(e,t){return r(o(e),t)}})},function(e,t,n){"use strict";var o=n(18),r=n.n(o),i=n(5),a=n.n(i),s=n(0),u=n.n(s),l=n(1),c=n.n(l),p=n(16),f=n.n(p),d=n(50),h=n.n(d),b=function(e,t,n,o,r,i){h()(!n||o>0,"`Slider[step]` should be a positive number in order to make Slider[dots] work.");var a=Object.keys(t).map(parseFloat).sort(function(e,t){return e-t});if(n)for(var s=r;s<=i;s+=o)-1===a.indexOf(s)&&a.push(s);return a},v=function(e){var t=e.prefixCls,n=e.vertical,o=e.marks,i=e.dots,s=e.step,l=e.included,c=e.lowerBound,p=e.upperBound,d=e.max,h=e.min,v=e.dotStyle,g=e.activeDotStyle,m=d-h,y=b(0,o,i,s,h,d).map(function(e){var o,i=Math.abs(e-h)/m*100+"%",s=!l&&e===p||l&&e<=p&&e>=c,d=n?a()({bottom:i},v):a()({left:i},v);s&&(d=a()({},d,g));var b=f()((o={},r()(o,t+"-dot",!0),r()(o,t+"-dot-active",s),o));return u.a.createElement("span",{className:b,style:d,key:e})});return u.a.createElement("div",{className:t+"-step"},y)};v.propTypes={prefixCls:c.a.string,activeDotStyle:c.a.object,dotStyle:c.a.object,min:c.a.number,max:c.a.number,upperBound:c.a.number,lowerBound:c.a.number,included:c.a.bool,dots:c.a.bool,step:c.a.number,marks:c.a.object,vertical:c.a.bool},t.a=v},function(e,t,n){"use strict";var o=n(5),r=n.n(o),i=n(18),a=n.n(i),s=n(0),u=n.n(s),l=n(1),c=n.n(l),p=n(16),f=n.n(p),d=function(e){var t=e.className,n=e.vertical,o=e.marks,i=e.included,s=e.upperBound,l=e.lowerBound,c=e.max,p=e.min,d=e.onClickLabel,h=Object.keys(o),b=h.length,v=b>1?100/(b-1):100,g=.9*v,m=c-p,y=h.map(parseFloat).sort(function(e,t){return e-t}).map(function(e){var c,h=o[e],b="object"===typeof h&&!u.a.isValidElement(h),v=b?h.label:h;if(!v&&0!==v)return null;var y=!i&&e===s||i&&e<=s&&e>=l,E=f()((c={},a()(c,t+"-text",!0),a()(c,t+"-text-active",y),c)),w={marginBottom:"-50%",bottom:(e-p)/m*100+"%"},O={width:g+"%",marginLeft:-g/2+"%",left:(e-p)/m*100+"%"},x=n?w:O,C=b?r()({},x,h.style):x;return u.a.createElement("span",{className:E,style:C,key:e,onMouseDown:function(t){return d(t,e)},onTouchStart:function(t){return d(t,e)}},v)});return u.a.createElement("div",{className:t},y)};d.propTypes={className:c.a.string,vertical:c.a.bool,marks:c.a.object,included:c.a.bool,upperBound:c.a.number,lowerBound:c.a.number,max:c.a.number,min:c.a.number,onClickLabel:c.a.func},t.a=d},function(e,t,n){e.exports={default:n(165),__esModule:!0}},function(e,t,n){n(63),n(166),e.exports=n(6).Array.from},function(e,t,n){"use strict";var o=n(34),r=n(10),i=n(31),a=n(167),s=n(168),u=n(62),l=n(169),c=n(170);r(r.S+r.F*!n(172)(function(e){Array.from(e)}),"Array",{from:function(e){var t,n,r,p,f=i(e),d="function"==typeof this?this:Array,h=arguments.length,b=h>1?arguments[1]:void 0,v=void 0!==b,g=0,m=c(f);if(v&&(b=o(b,h>2?arguments[2]:void 0,2)),void 0==m||d==Array&&s(m))for(t=u(f.length),n=new d(t);t>g;g++)l(n,g,v?b(f[g],g):f[g]);else for(p=m.call(f),n=new d;!(r=p.next()).done;g++)l(n,g,v?a(p,b,[r.value,g],!0):r.value);return n.length=g,n}})},function(e,t,n){var o=n(20);e.exports=function(e,t,n,r){try{return r?t(o(n)[0],n[1]):t(n)}catch(t){var i=e.return;throw void 0!==i&&o(i.call(e)),t}}},function(e,t,n){var o=n(25),r=n(7)("iterator"),i=Array.prototype;e.exports=function(e){return void 0!==e&&(o.Array===e||i[r]===e)}},function(e,t,n){"use strict";var o=n(12),r=n(23);e.exports=function(e,t,n){t in e?o.f(e,t,r(0,n)):e[t]=n}},function(e,t,n){var o=n(171),r=n(7)("iterator"),i=n(25);e.exports=n(6).getIteratorMethod=function(e){if(void 0!=e)return e[r]||e["@@iterator"]||i[o(e)]}},function(e,t,n){var o=n(36),r=n(7)("toStringTag"),i="Arguments"==o(function(){return arguments}()),a=function(e,t){try{return e[t]}catch(e){}};e.exports=function(e){var t,n,s;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=a(t=Object(e),r))?n:i?o(t):"Object"==(s=o(t))&&"function"==typeof t.callee?"Arguments":s}},function(e,t,n){var o=n(7)("iterator"),r=!1;try{var i=[7][o]();i.return=function(){r=!0},Array.from(i,function(){throw 2})}catch(e){}e.exports=function(e,t){if(!t&&!r)return!1;var n=!1;try{var i=[7],a=i[o]();a.next=function(){return{done:n=!0}},i[o]=function(){return a},e(i)}catch(e){}return n}},function(e,t,n){"use strict";var o={MAC_ENTER:3,BACKSPACE:8,TAB:9,NUM_CENTER:12,ENTER:13,SHIFT:16,CTRL:17,ALT:18,PAUSE:19,CAPS_LOCK:20,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,PRINT_SCREEN:44,INSERT:45,DELETE:46,ZERO:48,ONE:49,TWO:50,THREE:51,FOUR:52,FIVE:53,SIX:54,SEVEN:55,EIGHT:56,NINE:57,QUESTION_MARK:63,A:65,B:66,C:67,D:68,E:69,F:70,G:71,H:72,I:73,J:74,K:75,L:76,M:77,N:78,O:79,P:80,Q:81,R:82,S:83,T:84,U:85,V:86,W:87,X:88,Y:89,Z:90,META:91,WIN_KEY_RIGHT:92,CONTEXT_MENU:93,NUM_ZERO:96,NUM_ONE:97,NUM_TWO:98,NUM_THREE:99,NUM_FOUR:100,NUM_FIVE:101,NUM_SIX:102,NUM_SEVEN:103,NUM_EIGHT:104,NUM_NINE:105,NUM_MULTIPLY:106,NUM_PLUS:107,NUM_MINUS:109,NUM_PERIOD:110,NUM_DIVISION:111,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,NUMLOCK:144,SEMICOLON:186,DASH:189,EQUALS:187,COMMA:188,PERIOD:190,SLASH:191,APOSTROPHE:192,SINGLE_QUOTE:222,OPEN_SQUARE_BRACKET:219,BACKSLASH:220,CLOSE_SQUARE_BRACKET:221,WIN_KEY:224,MAC_FF_META:224,WIN_IME:229};o.isTextModifyingKeyEvent=function(e){var t=e.keyCode;if(e.altKey&&!e.ctrlKey||e.metaKey||t>=o.F1&&t<=o.F12)return!1;switch(t){case o.ALT:case o.CAPS_LOCK:case o.CONTEXT_MENU:case o.CTRL:case o.DOWN:case o.END:case o.ESC:case o.HOME:case o.INSERT:case o.LEFT:case o.MAC_FF_META:case o.META:case o.NUMLOCK:case o.NUM_CENTER:case o.PAGE_DOWN:case o.PAGE_UP:case o.PAUSE:case o.PRINT_SCREEN:case o.RIGHT:case o.SHIFT:case o.UP:case o.WIN_KEY:case o.WIN_KEY_RIGHT:return!1;default:return!0}},o.isCharacterKey=function(e){if(e>=o.ZERO&&e<=o.NINE)return!0;if(e>=o.NUM_ZERO&&e<=o.NUM_MULTIPLY)return!0;if(e>=o.A&&e<=o.Z)return!0;if(-1!==window.navigation.userAgent.indexOf("WebKit")&&0===e)return!0;switch(e){case o.SPACE:case o.QUESTION_MARK:case o.NUM_PLUS:case o.NUM_MINUS:case o.NUM_PERIOD:case o.NUM_DIVISION:case o.SEMICOLON:case o.DASH:case o.EQUALS:case o.COMMA:case o.PERIOD:case o.SLASH:case o.APOSTROPHE:case o.SINGLE_QUOTE:case o.OPEN_SQUARE_BRACKET:case o.BACKSLASH:case o.CLOSE_SQUARE_BRACKET:return!0;default:return!1}},t.a=o},function(e,t,n){"use strict";var o=n(18),r=n.n(o),i=n(5),a=n.n(i),s=n(81),u=n.n(s),l=n(2),c=n.n(l),p=n(9),f=n.n(p),d=n(3),h=n.n(d),b=n(4),v=n.n(b),g=n(0),m=n.n(g),y=n(1),E=n.n(y),w=n(16),O=n.n(w),x=n(175),C=n.n(x),S=n(78),k=n(79),T=n(52),A=function(e){function t(e){c()(this,t);var n=h()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));n.onEnd=function(){n.setState({handle:null}),n.removeDocumentEvents(),n.props.onAfterChange(n.getValue())};var o=e.count,r=e.min,i=e.max,a=Array.apply(void 0,u()(Array(o+1))).map(function(){return r}),s="defaultValue"in e?e.defaultValue:a,l=void 0!==e.value?e.value:s,p=l.map(function(e,t){return n.trimAlignValue(e,t)}),f=p[0]===i?0:p.length-1;return n.state={handle:null,recent:f,bounds:p},n}return v()(t,e),f()(t,[{key:"componentWillReceiveProps",value:function(e){var t=this;if(("value"in e||"min"in e||"max"in e)&&(this.props.min!==e.min||this.props.max!==e.max||!C()(this.props.value,e.value))){var n=this.state.bounds,o=e.value||n,r=o.map(function(n,o){return t.trimAlignValue(n,o,e)});if((r.length!==n.length||!r.every(function(e,t){return e===n[t]}))&&(this.setState({bounds:r}),o.some(function(t){return T.j(t,e)}))){var i=o.map(function(t){return T.a(t,e)});this.props.onChange(i)}}}},{key:"onChange",value:function(e){var t=this.props;"value"in t?void 0!==e.handle&&this.setState({handle:e.handle}):this.setState(e);var n=a()({},this.state,e),o=n.bounds;t.onChange(o)}},{key:"onStart",value:function(e){var t=this.props,n=this.state,o=this.getValue();t.onBeforeChange(o);var r=this.calcValueByPos(e);this.startValue=r,this.startPosition=e;var i=this.getClosestBound(r);if(this.prevMovedHandleIndex=this.getBoundNeedMoving(r,i),this.setState({handle:this.prevMovedHandleIndex,recent:this.prevMovedHandleIndex}),r!==o[this.prevMovedHandleIndex]){var a=[].concat(u()(n.bounds));a[this.prevMovedHandleIndex]=r,this.onChange({bounds:a})}}},{key:"onMove",value:function(e,t){T.k(e);var n=this.state,o=this.calcValueByPos(t);o!==n.bounds[n.handle]&&this.moveTo(o)}},{key:"onKeyboard",value:function(e){var t=T.d(e);if(t){T.k(e);var n=this.state,o=this.props,r=n.bounds,i=n.handle,a=r[i],s=t(a,o),u=this.trimAlignValue(s);if(u===a)return;this.moveTo(u,!0)}}},{key:"getValue",value:function(){return this.state.bounds}},{key:"getClosestBound",value:function(e){for(var t=this.state.bounds,n=0,o=1;o<t.length-1;++o)e>t[o]&&(n=o);return Math.abs(t[n+1]-e)<Math.abs(t[n]-e)&&(n+=1),n}},{key:"getBoundNeedMoving",value:function(e,t){var n=this.state,o=n.bounds,r=n.recent,i=t,a=o[t+1]===o[t];return a&&o[r]===o[t]&&(i=r),a&&e!==o[t+1]&&(i=e<o[t+1]?t:t+1),i}},{key:"getLowerBound",value:function(){return this.state.bounds[0]}},{key:"getUpperBound",value:function(){var e=this.state.bounds;return e[e.length-1]}},{key:"getPoints",value:function(){var e=this.props,t=e.marks,n=e.step,o=e.min,r=e.max,i=this._getPointsCache;if(!i||i.marks!==t||i.step!==n){var s=a()({},t);if(null!==n)for(var u=o;u<=r;u+=n)s[u]=u;var l=Object.keys(s).map(parseFloat);l.sort(function(e,t){return e-t}),this._getPointsCache={marks:t,step:n,points:l}}return this._getPointsCache.points}},{key:"moveTo",value:function(e,t){var n=this,o=this.state,r=this.props,i=[].concat(u()(o.bounds));i[o.handle]=e;var a=o.handle;!1!==r.pushable?this.pushSurroundingHandles(i,a):r.allowCross&&(i.sort(function(e,t){return e-t}),a=i.indexOf(e)),this.onChange({handle:a,bounds:i}),t&&this.setState({},function(){n.handlesRefs[a].focus()})}},{key:"pushSurroundingHandles",value:function(e,t){var n=e[t],o=this.props.pushable;o=Number(o);var r=0;if(e[t+1]-n<o&&(r=1),n-e[t-1]<o&&(r=-1),0!==r){var i=t+r,a=r*(e[i]-n);this.pushHandle(e,i,r,o-a)||(e[t]=e[i]-r*o)}}},{key:"pushHandle",value:function(e,t,n,o){for(var r=e[t],i=e[t];n*(i-r)<o;){if(!this.pushHandleOnePoint(e,t,n))return e[t]=r,!1;i=e[t]}return!0}},{key:"pushHandleOnePoint",value:function(e,t,n){var o=this.getPoints(),r=o.indexOf(e[t]),i=r+n;if(i>=o.length||i<0)return!1;var a=t+n,s=o[i],u=this.props.pushable,l=n*(e[a]-s);return!!this.pushHandle(e,a,n,u-l)&&(e[t]=s,!0)}},{key:"trimAlignValue",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=a()({},this.props,n),r=T.a(e,o),i=this.ensureValueNotConflict(t,r,o);return T.b(i,o)}},{key:"ensureValueNotConflict",value:function(e,t,n){var o=n.allowCross,r=n.pushable,i=this.state||{},a=i.bounds;if(e=void 0===e?i.handle:e,r=Number(r),!o&&null!=e&&void 0!==a){if(e>0&&t<=a[e-1]+r)return a[e-1]+r;if(e<a.length-1&&t>=a[e+1]-r)return a[e+1]-r}return t}},{key:"render",value:function(){var e=this,t=this.state,n=t.handle,o=t.bounds,i=this.props,a=i.prefixCls,s=i.vertical,u=i.included,l=i.disabled,c=i.min,p=i.max,f=i.handle,d=i.trackStyle,h=i.handleStyle,b=i.tabIndex,v=o.map(function(t){return e.calcOffset(t)}),g=a+"-handle",y=o.map(function(t,o){var i;return f({className:O()((i={},r()(i,g,!0),r()(i,g+"-"+(o+1),!0),i)),prefixCls:a,vertical:s,offset:v[o],value:t,dragging:n===o,index:o,tabIndex:b[o]||0,min:c,max:p,disabled:l,style:h[o],ref:function(t){return e.saveHandle(o,t)}})});return{tracks:o.slice(0,-1).map(function(e,t){var n,o=t+1,i=O()((n={},r()(n,a+"-track",!0),r()(n,a+"-track-"+o,!0),n));return m.a.createElement(S.a,{className:i,vertical:s,included:u,offset:v[o-1],length:v[o]-v[o-1],style:d[t],key:o})}),handles:y}}}]),t}(m.a.Component);A.displayName="Range",A.propTypes={defaultValue:E.a.arrayOf(E.a.number),value:E.a.arrayOf(E.a.number),count:E.a.number,pushable:E.a.oneOfType([E.a.bool,E.a.number]),allowCross:E.a.bool,disabled:E.a.bool,tabIndex:E.a.arrayOf(E.a.number),min:E.a.number,max:E.a.number},A.defaultProps={count:1,allowCross:!0,pushable:!1,tabIndex:[]},t.a=Object(k.a)(A)},function(e,t){e.exports=function(e,t,n,o){var r=n?n.call(o,e,t):void 0;if(void 0!==r)return!!r;if(e===t)return!0;if("object"!==typeof e||!e||"object"!==typeof t||!t)return!1;var i=Object.keys(e),a=Object.keys(t);if(i.length!==a.length)return!1;for(var s=Object.prototype.hasOwnProperty.bind(t),u=0;u<i.length;u++){var l=i[u];if(!s(l))return!1;var c=e[l],p=t[l];if(!1===(r=n?n.call(o,c,p,l):void 0)||void 0===r&&c!==p)return!1}return!0}},function(e,t,n){"use strict";function o(e){var t,n;return n=t=function(t){function n(e){p()(this,n);var t=b()(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,e));return t.handleTooltipVisibleChange=function(e,n){t.setState(function(t){return{visibles:l()({},t.visibles,s()({},e,n))}})},t.handleWithTooltip=function(e){var n=e.value,o=e.dragging,r=e.index,a=e.disabled,s=i()(e,["value","dragging","index","disabled"]),u=t.props,c=u.tipFormatter,p=u.tipProps,f=u.handleStyle,d=p.prefixCls,h=void 0===d?"rc-slider-tooltip":d,b=p.overlay,v=void 0===b?c(n):b,g=p.placement,m=void 0===g?"top":g,E=p.visible,w=void 0!==E&&E,C=i()(p,["prefixCls","overlay","placement","visible"]),S=void 0;return S=Array.isArray(f)?f[r]||f[0]:f,y.a.createElement(O.default,l()({},C,{prefixCls:h,overlay:v,placement:m,visible:!a&&(t.state.visibles[r]||o)||w,key:r}),y.a.createElement(x.a,l()({},s,{style:l()({},S),value:n,onMouseEnter:function(){return t.handleTooltipVisibleChange(r,!0)},onMouseLeave:function(){return t.handleTooltipVisibleChange(r,!1)}})))},t.state={visibles:{}},t}return g()(n,t),d()(n,[{key:"render",value:function(){return y.a.createElement(e,l()({},this.props,{handle:this.handleWithTooltip}))}}]),n}(y.a.Component),t.propTypes={tipFormatter:w.a.func,handleStyle:w.a.oneOfType([w.a.object,w.a.arrayOf(w.a.object)]),tipProps:w.a.object},t.defaultProps={tipFormatter:function(e){return e},handleStyle:[{}],tipProps:{}},n}t.a=o;var r=n(24),i=n.n(r),a=n(18),s=n.n(a),u=n(5),l=n.n(u),c=n(2),p=n.n(c),f=n(9),d=n.n(f),h=n(3),b=n.n(h),v=n(4),g=n.n(v),m=n(0),y=n.n(m),E=n(1),w=n.n(E),O=n(57),x=n(51)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"Async",function(){return z}),n.d(t,"AsyncCreatable",function(){return $}),n.d(t,"Creatable",function(){return K}),n.d(t,"Value",function(){return P}),n.d(t,"Option",function(){return _}),n.d(t,"defaultMenuRenderer",function(){return y}),n.d(t,"defaultArrowRenderer",function(){return f}),n.d(t,"defaultClearRenderer",function(){return d}),n.d(t,"defaultFilterOptions",function(){return m});var o=n(178),r=n.n(o),i=n(16),a=n.n(i),s=n(1),u=n.n(s),l=n(0),c=n.n(l),p=n(8),f=(n.n(p),function(e){var t=e.onMouseDown;return c.a.createElement("span",{className:"Select-arrow",onMouseDown:t})});f.propTypes={onMouseDown:u.a.func};var d=function(){return c.a.createElement("span",{className:"Select-clear",dangerouslySetInnerHTML:{__html:"&times;"}})},h=[{base:"A",letters:/[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g},{base:"AA",letters:/[\uA732]/g},{base:"AE",letters:/[\u00C6\u01FC\u01E2]/g},{base:"AO",letters:/[\uA734]/g},{base:"AU",letters:/[\uA736]/g},{base:"AV",letters:/[\uA738\uA73A]/g},{base:"AY",letters:/[\uA73C]/g},{base:"B",letters:/[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g},{base:"C",letters:/[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g},{base:"D",letters:/[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g},{base:"DZ",letters:/[\u01F1\u01C4]/g},{base:"Dz",letters:/[\u01F2\u01C5]/g},{base:"E",letters:/[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g},{base:"F",letters:/[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g},{base:"G",letters:/[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g},{base:"H",letters:/[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g},{base:"I",letters:/[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g},{base:"J",letters:/[\u004A\u24BF\uFF2A\u0134\u0248]/g},{base:"K",letters:/[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g},{base:"L",letters:/[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g},{base:"LJ",letters:/[\u01C7]/g},{base:"Lj",letters:/[\u01C8]/g},{base:"M",letters:/[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g},{base:"N",letters:/[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g},{base:"NJ",letters:/[\u01CA]/g},{base:"Nj",letters:/[\u01CB]/g},{base:"O",letters:/[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g},{base:"OI",letters:/[\u01A2]/g},{base:"OO",letters:/[\uA74E]/g},{base:"OU",letters:/[\u0222]/g},{base:"P",letters:/[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g},{base:"Q",letters:/[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g},{base:"R",letters:/[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g},{base:"S",letters:/[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g},{base:"T",letters:/[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g},{base:"TZ",letters:/[\uA728]/g},{base:"U",letters:/[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g},{base:"V",letters:/[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g},{base:"VY",letters:/[\uA760]/g},{base:"W",letters:/[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g},{base:"X",letters:/[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g},{base:"Y",letters:/[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g},{base:"Z",letters:/[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g},{base:"a",letters:/[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g},{base:"aa",letters:/[\uA733]/g},{base:"ae",letters:/[\u00E6\u01FD\u01E3]/g},{base:"ao",letters:/[\uA735]/g},{base:"au",letters:/[\uA737]/g},{base:"av",letters:/[\uA739\uA73B]/g},{base:"ay",letters:/[\uA73D]/g},{base:"b",letters:/[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g},{base:"c",letters:/[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g},{base:"d",letters:/[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g},{base:"dz",letters:/[\u01F3\u01C6]/g},{base:"e",letters:/[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g},{base:"f",letters:/[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g},{base:"g",letters:/[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g},{base:"h",letters:/[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g},{base:"hv",letters:/[\u0195]/g},{base:"i",letters:/[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g},{base:"j",letters:/[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g},{base:"k",letters:/[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g},{base:"l",letters:/[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g},{base:"lj",letters:/[\u01C9]/g},{base:"m",letters:/[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g},{base:"n",letters:/[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g},{base:"nj",letters:/[\u01CC]/g},{base:"o",letters:/[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g},{base:"oi",letters:/[\u01A3]/g},{base:"ou",letters:/[\u0223]/g},{base:"oo",letters:/[\uA74F]/g},{base:"p",letters:/[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g},{base:"q",letters:/[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g},{base:"r",letters:/[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g},{base:"s",letters:/[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g},{base:"t",letters:/[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g},{base:"tz",letters:/[\uA729]/g},{base:"u",letters:/[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g},{base:"v",letters:/[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g},{base:"vy",letters:/[\uA761]/g},{base:"w",letters:/[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g},{base:"x",letters:/[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g},{base:"y",letters:/[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g},{base:"z",letters:/[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g}],b=function(e){for(var t=0;t<h.length;t++)e=e.replace(h[t].letters,h[t].base);return e},v=function(e){return e.replace(/^\s+|\s+$/g,"")},g=function(e){return"undefined"!==typeof e&&null!==e&&""!==e},m=function(e,t,n,o){return o.ignoreAccents&&(t=b(t)),o.ignoreCase&&(t=t.toLowerCase()),o.trimFilter&&(t=v(t)),n&&(n=n.map(function(e){return e[o.valueKey]})),e.filter(function(e){if(n&&n.indexOf(e[o.valueKey])>-1)return!1;if(o.filterOption)return o.filterOption.call(void 0,e,t);if(!t)return!0;var r=e[o.valueKey],i=e[o.labelKey],a=g(r),s=g(i);if(!a&&!s)return!1;var u=a?String(r):null,l=s?String(i):null;return o.ignoreAccents&&(u&&"label"!==o.matchProp&&(u=b(u)),l&&"value"!==o.matchProp&&(l=b(l))),o.ignoreCase&&(u&&"label"!==o.matchProp&&(u=u.toLowerCase()),l&&"value"!==o.matchProp&&(l=l.toLowerCase())),"start"===o.matchPos?u&&"label"!==o.matchProp&&u.substr(0,t.length)===t||l&&"value"!==o.matchProp&&l.substr(0,t.length)===t:u&&"label"!==o.matchProp&&u.indexOf(t)>=0||l&&"value"!==o.matchProp&&l.indexOf(t)>=0})},y=function(e){var t=e.focusedOption,n=e.focusOption,o=e.inputValue,r=e.instancePrefix,i=e.onFocus,s=e.onOptionRef,u=e.onSelect,l=e.optionClassName,p=e.optionComponent,f=e.optionRenderer,d=e.options,h=e.removeValue,b=e.selectValue,v=e.valueArray,g=e.valueKey,m=p;return d.map(function(e,p){var d=v&&v.some(function(t){return t[g]===e[g]}),y=e===t,E=a()(l,{"Select-option":!0,"is-selected":d,"is-focused":y,"is-disabled":e.disabled});return c.a.createElement(m,{className:E,focusOption:n,inputValue:o,instancePrefix:r,isDisabled:e.disabled,isFocused:y,isSelected:d,key:"option-"+p+"-"+e[g],onFocus:i,onSelect:u,option:e,optionIndex:p,ref:function(e){s(e,y)},removeValue:h,selectValue:b},f(e,p,o))})};y.propTypes={focusOption:u.a.func,focusedOption:u.a.object,inputValue:u.a.string,instancePrefix:u.a.string,onFocus:u.a.func,onOptionRef:u.a.func,onSelect:u.a.func,optionClassName:u.a.string,optionComponent:u.a.func,optionRenderer:u.a.func,options:u.a.array,removeValue:u.a.func,selectValue:u.a.func,valueArray:u.a.array,valueKey:u.a.string};var E=function(e){e.preventDefault(),e.stopPropagation(),"A"===e.target.tagName&&"href"in e.target&&(e.target.target?window.open(e.target.href,e.target.target):window.location.href=e.target.href)},w="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"===typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},O=(function(){function e(e){this.value=e}function t(t){function n(e,t){return new Promise(function(n,r){var s={key:e,arg:t,resolve:n,reject:r,next:null};a?a=a.next=s:(i=a=s,o(e,t))})}function o(n,i){try{var a=t[n](i),s=a.value;s instanceof e?Promise.resolve(s.value).then(function(e){o("next",e)},function(e){o("throw",e)}):r(a.done?"return":"normal",a.value)}catch(e){r("throw",e)}}function r(e,t){switch(e){case"return":i.resolve({value:t,done:!0});break;case"throw":i.reject(t);break;default:i.resolve({value:t,done:!1})}i=i.next,i?o(i.key,i.arg):a=null}var i,a;this._invoke=n,"function"!==typeof t.return&&(this.return=void 0)}"function"===typeof Symbol&&Symbol.asyncIterator&&(t.prototype[Symbol.asyncIterator]=function(){return this}),t.prototype.next=function(e){return this._invoke("next",e)},t.prototype.throw=function(e){return this._invoke("throw",e)},t.prototype.return=function(e){return this._invoke("return",e)}}(),function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}),x=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),C=function(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e},S=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},k=function(e,t){if("function"!==typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},T=function(e,t){var n={};for(var o in e)t.indexOf(o)>=0||Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=e[o]);return n},A=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==typeof t&&"function"!==typeof t?e:t},_=function(e){function t(e){O(this,t);var n=A(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.handleMouseDown=n.handleMouseDown.bind(n),n.handleMouseEnter=n.handleMouseEnter.bind(n),n.handleMouseMove=n.handleMouseMove.bind(n),n.handleTouchStart=n.handleTouchStart.bind(n),n.handleTouchEnd=n.handleTouchEnd.bind(n),n.handleTouchMove=n.handleTouchMove.bind(n),n.onFocus=n.onFocus.bind(n),n}return k(t,e),x(t,[{key:"handleMouseDown",value:function(e){e.preventDefault(),e.stopPropagation(),this.props.onSelect(this.props.option,e)}},{key:"handleMouseEnter",value:function(e){this.onFocus(e)}},{key:"handleMouseMove",value:function(e){this.onFocus(e)}},{key:"handleTouchEnd",value:function(e){this.dragging||this.handleMouseDown(e)}},{key:"handleTouchMove",value:function(){this.dragging=!0}},{key:"handleTouchStart",value:function(){this.dragging=!1}},{key:"onFocus",value:function(e){this.props.isFocused||this.props.onFocus(this.props.option,e)}},{key:"render",value:function(){var e=this.props,t=e.option,n=e.instancePrefix,o=e.optionIndex,r=a()(this.props.className,t.className);return t.disabled?c.a.createElement("div",{className:r,onMouseDown:E,onClick:E},this.props.children):c.a.createElement("div",{className:r,style:t.style,role:"option","aria-label":t.label,onMouseDown:this.handleMouseDown,onMouseEnter:this.handleMouseEnter,onMouseMove:this.handleMouseMove,onTouchStart:this.handleTouchStart,onTouchMove:this.handleTouchMove,onTouchEnd:this.handleTouchEnd,id:n+"-option-"+o,title:t.title},this.props.children)}}]),t}(c.a.Component);_.propTypes={children:u.a.node,className:u.a.string,instancePrefix:u.a.string.isRequired,isDisabled:u.a.bool,isFocused:u.a.bool,isSelected:u.a.bool,onFocus:u.a.func,onSelect:u.a.func,onUnfocus:u.a.func,option:u.a.object.isRequired,optionIndex:u.a.number};var P=function(e){function t(e){O(this,t);var n=A(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.handleMouseDown=n.handleMouseDown.bind(n),n.onRemove=n.onRemove.bind(n),n.handleTouchEndRemove=n.handleTouchEndRemove.bind(n),n.handleTouchMove=n.handleTouchMove.bind(n),n.handleTouchStart=n.handleTouchStart.bind(n),n}return k(t,e),x(t,[{key:"handleMouseDown",value:function(e){if("mousedown"!==e.type||0===e.button)return this.props.onClick?(e.stopPropagation(),void this.props.onClick(this.props.value,e)):void(this.props.value.href&&e.stopPropagation())}},{key:"onRemove",value:function(e){e.preventDefault(),e.stopPropagation(),this.props.onRemove(this.props.value)}},{key:"handleTouchEndRemove",value:function(e){this.dragging||this.onRemove(e)}},{key:"handleTouchMove",value:function(){this.dragging=!0}},{key:"handleTouchStart",value:function(){this.dragging=!1}},{key:"renderRemoveIcon",value:function(){if(!this.props.disabled&&this.props.onRemove)return c.a.createElement("span",{className:"Select-value-icon","aria-hidden":"true",onMouseDown:this.onRemove,onTouchEnd:this.handleTouchEndRemove,onTouchStart:this.handleTouchStart,onTouchMove:this.handleTouchMove},"\xd7")}},{key:"renderLabel",value:function(){return this.props.onClick||this.props.value.href?c.a.createElement("a",{className:"Select-value-label",href:this.props.value.href,target:this.props.value.target,onMouseDown:this.handleMouseDown,onTouchEnd:this.handleMouseDown},this.props.children):c.a.createElement("span",{className:"Select-value-label",role:"option","aria-selected":"true",id:this.props.id},this.props.children)}},{key:"render",value:function(){return c.a.createElement("div",{className:a()("Select-value",this.props.value.disabled?"Select-value-disabled":"",this.props.value.className),style:this.props.value.style,title:this.props.value.title},this.renderRemoveIcon(),this.renderLabel())}}]),t}(c.a.Component);P.propTypes={children:u.a.node,disabled:u.a.bool,id:u.a.string,onClick:u.a.func,onRemove:u.a.func,value:u.a.object.isRequired};var M=function(e){return"string"===typeof e?e:null!==e&&JSON.stringify(e)||""},D=u.a.oneOfType([u.a.string,u.a.node]),F=u.a.oneOfType([u.a.string,u.a.number]),N=1,j=function(e,t){var n=e.inputValue,o=e.isPseudoFocused,r=e.isFocused,i=t.onSelectResetsInput;return!n||!i&&!(!r&&o||r&&!o)},R=function(e,t,n){var o=e.inputValue,r=e.isPseudoFocused,i=e.isFocused,a=t.onSelectResetsInput;return!o||!a&&!n&&!r&&!i},L=function(e,t){var n="undefined"===typeof e?"undefined":w(e);if("string"!==n&&"number"!==n&&"boolean"!==n)return e;var o=t.options,r=t.valueKey;if(o)for(var i=0;i<o.length;i++)if(String(o[i][r])===String(e))return o[i]},I=function(e,t){return!e||(t?0===e.length:0===Object.keys(e).length)},V=function(e){function t(e){O(this,t);var n=A(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return["clearValue","focusOption","getOptionLabel","handleInputBlur","handleInputChange","handleInputFocus","handleInputValueChange","handleKeyDown","handleMenuScroll","handleMouseDown","handleMouseDownOnArrow","handleMouseDownOnMenu","handleTouchEnd","handleTouchEndClearValue","handleTouchMove","handleTouchOutside","handleTouchStart","handleValueClick","onOptionRef","removeValue","selectValue"].forEach(function(e){return n[e]=n[e].bind(n)}),n.state={inputValue:"",isFocused:!1,isOpen:!1,isPseudoFocused:!1,required:!1},n}return k(t,e),x(t,[{key:"componentWillMount",value:function(){this._instancePrefix="react-select-"+(this.props.instanceId||++N)+"-";var e=this.getValueArray(this.props.value);this.props.required&&this.setState({required:I(e[0],this.props.multi)})}},{key:"componentDidMount",value:function(){"undefined"!==typeof this.props.autofocus&&"undefined"!==typeof console&&console.warn("Warning: The autofocus prop has changed to autoFocus, support will be removed after react-select@1.0"),(this.props.autoFocus||this.props.autofocus)&&this.focus()}},{key:"componentWillReceiveProps",value:function(e){var t=this.getValueArray(e.value,e);e.required?this.setState({required:I(t[0],e.multi)}):this.props.required&&this.setState({required:!1}),this.state.inputValue&&this.props.value!==e.value&&e.onSelectResetsInput&&this.setState({inputValue:this.handleInputValueChange("")})}},{key:"componentDidUpdate",value:function(e,t){if(this.menu&&this.focused&&this.state.isOpen&&!this.hasScrolledToOption){var n=Object(p.findDOMNode)(this.focused),o=Object(p.findDOMNode)(this.menu),r=o.scrollTop,i=r+o.offsetHeight,a=n.offsetTop,s=a+n.offsetHeight;(r>a||i<s)&&(o.scrollTop=n.offsetTop),this.hasScrolledToOption=!0}else this.state.isOpen||(this.hasScrolledToOption=!1);if(this._scrollToFocusedOptionOnUpdate&&this.focused&&this.menu){this._scrollToFocusedOptionOnUpdate=!1;var u=Object(p.findDOMNode)(this.focused),l=Object(p.findDOMNode)(this.menu),c=u.getBoundingClientRect(),f=l.getBoundingClientRect();c.bottom>f.bottom?l.scrollTop=u.offsetTop+u.clientHeight-l.offsetHeight:c.top<f.top&&(l.scrollTop=u.offsetTop)}if(this.props.scrollMenuIntoView&&this.menuContainer){var d=this.menuContainer.getBoundingClientRect();window.innerHeight<d.bottom+this.props.menuBuffer&&window.scrollBy(0,d.bottom+this.props.menuBuffer-window.innerHeight)}if(e.disabled!==this.props.disabled&&(this.setState({isFocused:!1}),this.closeMenu()),t.isOpen!==this.state.isOpen){this.toggleTouchOutsideEvent(this.state.isOpen);var h=this.state.isOpen?this.props.onOpen:this.props.onClose;h&&h()}}},{key:"componentWillUnmount",value:function(){this.toggleTouchOutsideEvent(!1)}},{key:"toggleTouchOutsideEvent",value:function(e){var t=e?document.addEventListener?"addEventListener":"attachEvent":document.removeEventListener?"removeEventListener":"detachEvent",n=document.addEventListener?"":"on";document[t](n+"touchstart",this.handleTouchOutside),document[t](n+"mousedown",this.handleTouchOutside)}},{key:"handleTouchOutside",value:function(e){this.wrapper&&!this.wrapper.contains(e.target)&&this.closeMenu()}},{key:"focus",value:function(){this.input&&this.input.focus()}},{key:"blurInput",value:function(){this.input&&this.input.blur()}},{key:"handleTouchMove",value:function(){this.dragging=!0}},{key:"handleTouchStart",value:function(){this.dragging=!1}},{key:"handleTouchEnd",value:function(e){this.dragging||this.handleMouseDown(e)}},{key:"handleTouchEndClearValue",value:function(e){this.dragging||this.clearValue(e)}},{key:"handleMouseDown",value:function(e){if(!(this.props.disabled||"mousedown"===e.type&&0!==e.button)){if("INPUT"===e.target.tagName)return void(this.state.isFocused?this.state.isOpen||this.setState({isOpen:!0,isPseudoFocused:!1,focusedOption:null}):(this._openAfterFocus=this.props.openOnClick,this.focus()));if(e.preventDefault(),!this.props.searchable)return this.focus(),this.setState({isOpen:!this.state.isOpen,focusedOption:null});if(this.state.isFocused){this.focus();var t=this.input,n=!0;"function"===typeof t.getInput&&(t=t.getInput()),t.value="",this._focusAfterClear&&(n=!1,this._focusAfterClear=!1),this.setState({isOpen:n,isPseudoFocused:!1,focusedOption:null})}else this._openAfterFocus=this.props.openOnClick,this.focus(),this.setState({focusedOption:null})}}},{key:"handleMouseDownOnArrow",value:function(e){this.props.disabled||"mousedown"===e.type&&0!==e.button||(this.state.isOpen?(e.stopPropagation(),e.preventDefault(),this.closeMenu()):this.setState({isOpen:!0}))}},{key:"handleMouseDownOnMenu",value:function(e){this.props.disabled||"mousedown"===e.type&&0!==e.button||(e.stopPropagation(),e.preventDefault(),this._openAfterFocus=!0,this.focus())}},{key:"closeMenu",value:function(){this.props.onCloseResetsInput?this.setState({inputValue:this.handleInputValueChange(""),isOpen:!1,isPseudoFocused:this.state.isFocused&&!this.props.multi}):this.setState({isOpen:!1,isPseudoFocused:this.state.isFocused&&!this.props.multi}),this.hasScrolledToOption=!1}},{key:"handleInputFocus",value:function(e){if(!this.props.disabled){var t=this.state.isOpen||this._openAfterFocus||this.props.openOnFocus;t=!this._focusAfterClear&&t,this.props.onFocus&&this.props.onFocus(e),this.setState({isFocused:!0,isOpen:!!t}),this._focusAfterClear=!1,this._openAfterFocus=!1}}},{key:"handleInputBlur",value:function(e){if(this.menu&&(this.menu===document.activeElement||this.menu.contains(document.activeElement)))return void this.focus();this.props.onBlur&&this.props.onBlur(e);var t={isFocused:!1,isOpen:!1,isPseudoFocused:!1};this.props.onBlurResetsInput&&(t.inputValue=this.handleInputValueChange("")),this.setState(t)}},{key:"handleInputChange",value:function(e){var t=e.target.value;this.state.inputValue!==e.target.value&&(t=this.handleInputValueChange(t)),this.setState({inputValue:t,isOpen:!0,isPseudoFocused:!1})}},{key:"setInputValue",value:function(e){if(this.props.onInputChange){var t=this.props.onInputChange(e);null!=t&&"object"!==("undefined"===typeof t?"undefined":w(t))&&(e=""+t)}this.setState({inputValue:e})}},{key:"handleInputValueChange",value:function(e){if(this.props.onInputChange){var t=this.props.onInputChange(e);null!=t&&"object"!==("undefined"===typeof t?"undefined":w(t))&&(e=""+t)}return e}},{key:"handleKeyDown",value:function(e){if(!this.props.disabled&&("function"!==typeof this.props.onInputKeyDown||(this.props.onInputKeyDown(e),!e.defaultPrevented)))switch(e.keyCode){case 8:!this.state.inputValue&&this.props.backspaceRemoves&&(e.preventDefault(),this.popValue());break;case 9:if(e.shiftKey||!this.state.isOpen||!this.props.tabSelectsValue)break;e.preventDefault(),this.selectFocusedOption();break;case 13:e.preventDefault(),e.stopPropagation(),this.state.isOpen?this.selectFocusedOption():this.focusNextOption();break;case 27:e.preventDefault(),this.state.isOpen?(this.closeMenu(),e.stopPropagation()):this.props.clearable&&this.props.escapeClearsValue&&(this.clearValue(e),e.stopPropagation());break;case 32:if(this.props.searchable)break;if(e.preventDefault(),!this.state.isOpen){this.focusNextOption();break}e.stopPropagation(),this.selectFocusedOption();break;case 38:e.preventDefault(),this.focusPreviousOption();break;case 40:e.preventDefault(),this.focusNextOption();break;case 33:e.preventDefault(),this.focusPageUpOption();break;case 34:e.preventDefault(),this.focusPageDownOption();break;case 35:if(e.shiftKey)break;e.preventDefault(),this.focusEndOption();break;case 36:if(e.shiftKey)break;e.preventDefault(),this.focusStartOption();break;case 46:!this.state.inputValue&&this.props.deleteRemoves&&(e.preventDefault(),this.popValue())}}},{key:"handleValueClick",value:function(e,t){this.props.onValueClick&&this.props.onValueClick(e,t)}},{key:"handleMenuScroll",value:function(e){if(this.props.onMenuScrollToBottom){var t=e.target;t.scrollHeight>t.offsetHeight&&t.scrollHeight-t.offsetHeight-t.scrollTop<=0&&this.props.onMenuScrollToBottom()}}},{key:"getOptionLabel",value:function(e){return e[this.props.labelKey]}},{key:"getValueArray",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0,n="object"===("undefined"===typeof t?"undefined":w(t))?t:this.props;if(n.multi){if("string"===typeof e&&(e=e.split(n.delimiter)),!Array.isArray(e)){if(null===e||void 0===e)return[];e=[e]}return e.map(function(e){return L(e,n)}).filter(function(e){return e})}var o=L(e,n);return o?[o]:[]}},{key:"setValue",value:function(e){var t=this;if(this.props.autoBlur&&this.blurInput(),this.props.required){var n=I(e,this.props.multi);this.setState({required:n})}this.props.simpleValue&&e&&(e=this.props.multi?e.map(function(e){return e[t.props.valueKey]}).join(this.props.delimiter):e[this.props.valueKey]),this.props.onChange&&this.props.onChange(e)}},{key:"selectValue",value:function(e){var t=this;this.props.closeOnSelect&&(this.hasScrolledToOption=!1);var n=this.props.onSelectResetsInput?"":this.state.inputValue;this.props.multi?this.setState({focusedIndex:null,inputValue:this.handleInputValueChange(n),isOpen:!this.props.closeOnSelect},function(){t.getValueArray(t.props.value).some(function(n){return n[t.props.valueKey]===e[t.props.valueKey]})?t.removeValue(e):t.addValue(e)}):this.setState({inputValue:this.handleInputValueChange(n),isOpen:!this.props.closeOnSelect,isPseudoFocused:this.state.isFocused},function(){t.setValue(e)})}},{key:"addValue",value:function(e){var t=this.getValueArray(this.props.value),n=this._visibleOptions.filter(function(e){return!e.disabled}),o=n.indexOf(e);this.setValue(t.concat(e)),this.props.closeOnSelect&&(n.length-1===o?this.focusOption(n[o-1]):n.length>o&&this.focusOption(n[o+1]))}},{key:"popValue",value:function(){var e=this.getValueArray(this.props.value);e.length&&!1!==e[e.length-1].clearableValue&&this.setValue(this.props.multi?e.slice(0,e.length-1):null)}},{key:"removeValue",value:function(e){var t=this,n=this.getValueArray(this.props.value);this.setValue(n.filter(function(n){return n[t.props.valueKey]!==e[t.props.valueKey]})),this.focus()}},{key:"clearValue",value:function(e){e&&"mousedown"===e.type&&0!==e.button||(e.preventDefault(),this.setValue(this.getResetValue()),this.setState({inputValue:this.handleInputValueChange(""),isOpen:!1},this.focus),this._focusAfterClear=!0)}},{key:"getResetValue",value:function(){return void 0!==this.props.resetValue?this.props.resetValue:this.props.multi?[]:null}},{key:"focusOption",value:function(e){this.setState({focusedOption:e})}},{key:"focusNextOption",value:function(){this.focusAdjacentOption("next")}},{key:"focusPreviousOption",value:function(){this.focusAdjacentOption("previous")}},{key:"focusPageUpOption",value:function(){this.focusAdjacentOption("page_up")}},{key:"focusPageDownOption",value:function(){this.focusAdjacentOption("page_down")}},{key:"focusStartOption",value:function(){this.focusAdjacentOption("start")}},{key:"focusEndOption",value:function(){this.focusAdjacentOption("end")}},{key:"focusAdjacentOption",value:function(e){var t=this._visibleOptions.map(function(e,t){return{option:e,index:t}}).filter(function(e){return!e.option.disabled});if(this._scrollToFocusedOptionOnUpdate=!0,!this.state.isOpen){var n={focusedOption:this._focusedOption||(t.length?t["next"===e?0:t.length-1].option:null),isOpen:!0};return this.props.onSelectResetsInput&&(n.inputValue=""),void this.setState(n)}if(t.length){for(var o=-1,r=0;r<t.length;r++)if(this._focusedOption===t[r].option){o=r;break}if("next"===e&&-1!==o)o=(o+1)%t.length;else if("previous"===e)o>0?o-=1:o=t.length-1;else if("start"===e)o=0;else if("end"===e)o=t.length-1;else if("page_up"===e){var i=o-this.props.pageSize;o=i<0?0:i}else if("page_down"===e){var a=o+this.props.pageSize;o=a>t.length-1?t.length-1:a}-1===o&&(o=0),this.setState({focusedIndex:t[o].index,focusedOption:t[o].option})}}},{key:"getFocusedOption",value:function(){return this._focusedOption}},{key:"selectFocusedOption",value:function(){if(this._focusedOption)return this.selectValue(this._focusedOption)}},{key:"renderLoading",value:function(){if(this.props.isLoading)return c.a.createElement("span",{className:"Select-loading-zone","aria-hidden":"true"},c.a.createElement("span",{className:"Select-loading"}))}},{key:"renderValue",value:function(e,t){var n=this,o=this.props.valueRenderer||this.getOptionLabel,r=this.props.valueComponent;if(!e.length){return R(this.state,this.props,t)?c.a.createElement("div",{className:"Select-placeholder"},this.props.placeholder):null}var i=this.props.onValueClick?this.handleValueClick:null;return this.props.multi?e.map(function(t,a){return c.a.createElement(r,{disabled:n.props.disabled||!1===t.clearableValue,id:n._instancePrefix+"-value-"+a,instancePrefix:n._instancePrefix,key:"value-"+a+"-"+t[n.props.valueKey],onClick:i,onRemove:n.removeValue,placeholder:n.props.placeholder,value:t,values:e},o(t,a),c.a.createElement("span",{className:"Select-aria-only"},"\xa0"))}):j(this.state,this.props)?(t&&(i=null),c.a.createElement(r,{disabled:this.props.disabled,id:this._instancePrefix+"-value-item",instancePrefix:this._instancePrefix,onClick:i,placeholder:this.props.placeholder,value:e[0]},o(e[0]))):void 0}},{key:"renderInput",value:function(e,t){var n,o=this,i=a()("Select-input",this.props.inputProps.className),s=this.state.isOpen,u=a()((n={},C(n,this._instancePrefix+"-list",s),C(n,this._instancePrefix+"-backspace-remove-message",this.props.multi&&!this.props.disabled&&this.state.isFocused&&!this.state.inputValue),n)),l=this.state.inputValue;!l||this.props.onSelectResetsInput||this.state.isFocused||(l="");var p=S({},this.props.inputProps,{"aria-activedescendant":s?this._instancePrefix+"-option-"+t:this._instancePrefix+"-value","aria-describedby":this.props["aria-describedby"],"aria-expanded":""+s,"aria-haspopup":""+s,"aria-label":this.props["aria-label"],"aria-labelledby":this.props["aria-labelledby"],"aria-owns":u,onBlur:this.handleInputBlur,onChange:this.handleInputChange,onFocus:this.handleInputFocus,ref:function(e){return o.input=e},role:"combobox",required:this.state.required,tabIndex:this.props.tabIndex,value:l});if(this.props.inputRenderer)return this.props.inputRenderer(p);if(this.props.disabled||!this.props.searchable){var f=T(this.props.inputProps,[]),d=a()(C({},this._instancePrefix+"-list",s));return c.a.createElement("div",S({},f,{"aria-expanded":s,"aria-owns":d,"aria-activedescendant":s?this._instancePrefix+"-option-"+t:this._instancePrefix+"-value","aria-disabled":""+this.props.disabled,"aria-label":this.props["aria-label"],"aria-labelledby":this.props["aria-labelledby"],className:i,onBlur:this.handleInputBlur,onFocus:this.handleInputFocus,ref:function(e){return o.input=e},role:"combobox",style:{border:0,width:1,display:"inline-block"},tabIndex:this.props.tabIndex||0}))}return this.props.autosize?c.a.createElement(r.a,S({id:this.props.id},p,{className:i,minWidth:"5"})):c.a.createElement("div",{className:i,key:"input-wrap",style:{display:"inline-block"}},c.a.createElement("input",S({id:this.props.id},p)))}},{key:"renderClear",value:function(){var e=this.getValueArray(this.props.value);if(this.props.clearable&&e.length&&!this.props.disabled&&!this.props.isLoading){var t=this.props.multi?this.props.clearAllText:this.props.clearValueText,n=this.props.clearRenderer();return c.a.createElement("span",{"aria-label":t,className:"Select-clear-zone",onMouseDown:this.clearValue,onTouchEnd:this.handleTouchEndClearValue,onTouchMove:this.handleTouchMove,onTouchStart:this.handleTouchStart,title:t},n)}}},{key:"renderArrow",value:function(){if(this.props.arrowRenderer){var e=this.handleMouseDownOnArrow,t=this.state.isOpen,n=this.props.arrowRenderer({onMouseDown:e,isOpen:t});return n?c.a.createElement("span",{className:"Select-arrow-zone",onMouseDown:e},n):null}}},{key:"filterOptions",value:function(e){var t=this.state.inputValue,n=this.props.options||[];if(this.props.filterOptions){return("function"===typeof this.props.filterOptions?this.props.filterOptions:m)(n,t,e,{filterOption:this.props.filterOption,ignoreAccents:this.props.ignoreAccents,ignoreCase:this.props.ignoreCase,labelKey:this.props.labelKey,matchPos:this.props.matchPos,matchProp:this.props.matchProp,trimFilter:this.props.trimFilter,valueKey:this.props.valueKey})}return n}},{key:"onOptionRef",value:function(e,t){t&&(this.focused=e)}},{key:"renderMenu",value:function(e,t,n){return e&&e.length?this.props.menuRenderer({focusedOption:n,focusOption:this.focusOption,inputValue:this.state.inputValue,instancePrefix:this._instancePrefix,labelKey:this.props.labelKey,onFocus:this.focusOption,onOptionRef:this.onOptionRef,onSelect:this.selectValue,optionClassName:this.props.optionClassName,optionComponent:this.props.optionComponent,optionRenderer:this.props.optionRenderer||this.getOptionLabel,options:e,removeValue:this.removeValue,selectValue:this.selectValue,valueArray:t,valueKey:this.props.valueKey}):this.props.noResultsText?c.a.createElement("div",{className:"Select-noresults"},this.props.noResultsText):null}},{key:"renderHiddenField",value:function(e){var t=this;if(this.props.name){if(this.props.joinValues){var n=e.map(function(e){return M(e[t.props.valueKey])}).join(this.props.delimiter);return c.a.createElement("input",{disabled:this.props.disabled,name:this.props.name,ref:function(e){return t.value=e},type:"hidden",value:n})}return e.map(function(e,n){return c.a.createElement("input",{disabled:t.props.disabled,key:"hidden."+n,name:t.props.name,ref:"value"+n,type:"hidden",value:M(e[t.props.valueKey])})})}}},{key:"getFocusableOptionIndex",value:function(e){var t=this._visibleOptions;if(!t.length)return null;var n=this.props.valueKey,o=this.state.focusedOption||e;if(o&&!o.disabled){var r=-1;if(t.some(function(e,t){var i=e[n]===o[n];return i&&(r=t),i}),-1!==r)return r}for(var i=0;i<t.length;i++)if(!t[i].disabled)return i;return null}},{key:"renderOuter",value:function(e,t,n){var o=this,r=this.renderMenu(e,t,n);return r?c.a.createElement("div",{ref:function(e){return o.menuContainer=e},className:"Select-menu-outer",style:this.props.menuContainerStyle},c.a.createElement("div",{className:"Select-menu",id:this._instancePrefix+"-list",onMouseDown:this.handleMouseDownOnMenu,onScroll:this.handleMenuScroll,ref:function(e){return o.menu=e},role:"listbox",style:this.props.menuStyle,tabIndex:-1},r)):null}},{key:"render",value:function(){var e=this,t=this.getValueArray(this.props.value),n=this._visibleOptions=this.filterOptions(this.props.multi&&this.props.removeSelected?t:null),o=this.state.isOpen;this.props.multi&&!n.length&&t.length&&!this.state.inputValue&&(o=!1);var r=this.getFocusableOptionIndex(t[0]),i=null;i=this._focusedOption=null!==r?n[r]:null;var s=a()("Select",this.props.className,{"has-value":t.length,"is-clearable":this.props.clearable,"is-disabled":this.props.disabled,"is-focused":this.state.isFocused,"is-loading":this.props.isLoading,"is-open":o,"is-pseudo-focused":this.state.isPseudoFocused,"is-searchable":this.props.searchable,"Select--multi":this.props.multi,"Select--rtl":this.props.rtl,"Select--single":!this.props.multi}),u=null;return this.props.multi&&!this.props.disabled&&t.length&&!this.state.inputValue&&this.state.isFocused&&this.props.backspaceRemoves&&(u=c.a.createElement("span",{id:this._instancePrefix+"-backspace-remove-message",className:"Select-aria-only","aria-live":"assertive"},this.props.backspaceToRemoveMessage.replace("{label}",t[t.length-1][this.props.labelKey]))),c.a.createElement("div",{ref:function(t){return e.wrapper=t},className:s,style:this.props.wrapperStyle},this.renderHiddenField(t),c.a.createElement("div",{ref:function(t){return e.control=t},className:"Select-control",onKeyDown:this.handleKeyDown,onMouseDown:this.handleMouseDown,onTouchEnd:this.handleTouchEnd,onTouchMove:this.handleTouchMove,onTouchStart:this.handleTouchStart,style:this.props.style},c.a.createElement("div",{className:"Select-multi-value-wrapper",id:this._instancePrefix+"-value"},this.renderValue(t,o),this.renderInput(t,r)),u,this.renderLoading(),this.renderClear(),this.renderArrow()),o?this.renderOuter(n,t,i):null)}}]),t}(c.a.Component);V.propTypes={"aria-describedby":u.a.string,"aria-label":u.a.string,"aria-labelledby":u.a.string,arrowRenderer:u.a.func,autoBlur:u.a.bool,autoFocus:u.a.bool,autofocus:u.a.bool,autosize:u.a.bool,backspaceRemoves:u.a.bool,backspaceToRemoveMessage:u.a.string,className:u.a.string,clearAllText:D,clearRenderer:u.a.func,clearValueText:D,clearable:u.a.bool,closeOnSelect:u.a.bool,deleteRemoves:u.a.bool,delimiter:u.a.string,disabled:u.a.bool,escapeClearsValue:u.a.bool,filterOption:u.a.func,filterOptions:u.a.any,id:u.a.string,ignoreAccents:u.a.bool,ignoreCase:u.a.bool,inputProps:u.a.object,inputRenderer:u.a.func,instanceId:u.a.string,isLoading:u.a.bool,joinValues:u.a.bool,labelKey:u.a.string,matchPos:u.a.string,matchProp:u.a.string,menuBuffer:u.a.number,menuContainerStyle:u.a.object,menuRenderer:u.a.func,menuStyle:u.a.object,multi:u.a.bool,name:u.a.string,noResultsText:D,onBlur:u.a.func,onBlurResetsInput:u.a.bool,onChange:u.a.func,onClose:u.a.func,onCloseResetsInput:u.a.bool,onFocus:u.a.func,onInputChange:u.a.func,onInputKeyDown:u.a.func,onMenuScrollToBottom:u.a.func,onOpen:u.a.func,onSelectResetsInput:u.a.bool,onValueClick:u.a.func,openOnClick:u.a.bool,openOnFocus:u.a.bool,optionClassName:u.a.string,optionComponent:u.a.func,optionRenderer:u.a.func,options:u.a.array,pageSize:u.a.number,placeholder:D,removeSelected:u.a.bool,required:u.a.bool,resetValue:u.a.any,rtl:u.a.bool,scrollMenuIntoView:u.a.bool,searchable:u.a.bool,simpleValue:u.a.bool,style:u.a.object,tabIndex:F,tabSelectsValue:u.a.bool,trimFilter:u.a.bool,value:u.a.any,valueComponent:u.a.func,valueKey:u.a.string,valueRenderer:u.a.func,wrapperStyle:u.a.object},V.defaultProps={arrowRenderer:f,autosize:!0,backspaceRemoves:!0,backspaceToRemoveMessage:"Press backspace to remove {label}",clearable:!0,clearAllText:"Clear all",clearRenderer:d,clearValueText:"Clear value",closeOnSelect:!0,deleteRemoves:!0,delimiter:",",disabled:!1,escapeClearsValue:!0,filterOptions:m,ignoreAccents:!0,ignoreCase:!0,inputProps:{},isLoading:!1,joinValues:!1,labelKey:"label",matchPos:"any",matchProp:"any",menuBuffer:0,menuRenderer:y,multi:!1,noResultsText:"No results found",onBlurResetsInput:!0,onCloseResetsInput:!0,onSelectResetsInput:!0,openOnClick:!0,optionComponent:_,pageSize:5,placeholder:"Select...",removeSelected:!0,required:!1,rtl:!1,scrollMenuIntoView:!0,searchable:!0,simpleValue:!1,tabSelectsValue:!0,trimFilter:!0,valueComponent:P,valueKey:"value"};var B={autoload:u.a.bool.isRequired,cache:u.a.any,children:u.a.func.isRequired,ignoreAccents:u.a.bool,ignoreCase:u.a.bool,loadOptions:u.a.func.isRequired,loadingPlaceholder:u.a.oneOfType([u.a.string,u.a.node]),multi:u.a.bool,noResultsText:u.a.oneOfType([u.a.string,u.a.node]),onChange:u.a.func,onInputChange:u.a.func,options:u.a.array.isRequired,placeholder:u.a.oneOfType([u.a.string,u.a.node]),searchPromptText:u.a.oneOfType([u.a.string,u.a.node]),value:u.a.any},U={},W=function(e){return c.a.createElement(V,e)},H={autoload:!0,cache:U,children:W,ignoreAccents:!0,ignoreCase:!0,loadingPlaceholder:"Loading...",options:[],searchPromptText:"Type to search"},z=function(e){function t(e,n){O(this,t);var o=A(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n));return o._cache=e.cache===U?{}:e.cache,o.state={inputValue:"",isLoading:!1,options:e.options},o.onInputChange=o.onInputChange.bind(o),o}return k(t,e),x(t,[{key:"componentDidMount",value:function(){this.props.autoload&&this.loadOptions("")}},{key:"componentWillReceiveProps",value:function(e){e.options!==this.props.options&&this.setState({options:e.options})}},{key:"componentWillUnmount",value:function(){this._callback=null}},{key:"loadOptions",value:function(e){var t=this,n=this.props.loadOptions,o=this._cache;if(o&&Object.prototype.hasOwnProperty.call(o,e))return this._callback=null,void this.setState({isLoading:!1,options:o[e]});var r=function n(r,i){var a=i&&i.options||[];o&&(o[e]=a),n===t._callback&&(t._callback=null,t.setState({isLoading:!1,options:a}))};this._callback=r;var i=n(e,r);i&&i.then(function(e){return r(0,e)},function(e){return r()}),this._callback&&!this.state.isLoading&&this.setState({isLoading:!0})}},{key:"onInputChange",value:function(e){var t=this.props,n=t.ignoreAccents,o=t.ignoreCase,r=t.onInputChange,i=e;if(r){var a=r(i);null!=a&&"object"!==("undefined"===typeof a?"undefined":w(a))&&(i=""+a)}var s=i;return n&&(s=b(s)),o&&(s=s.toLowerCase()),this.setState({inputValue:i}),this.loadOptions(s),i}},{key:"noResultsText",value:function(){var e=this.props,t=e.loadingPlaceholder,n=e.noResultsText,o=e.searchPromptText,r=this.state,i=r.inputValue;return r.isLoading?t:i&&n?n:o}},{key:"focus",value:function(){this.select.focus()}},{key:"render",value:function(){var e=this,t=this.props,n=t.children,o=t.loadingPlaceholder,r=t.placeholder,i=this.state,a=i.isLoading,s=i.options,u={noResultsText:this.noResultsText(),placeholder:a?o:r,options:a&&o?[]:s,ref:function(t){return e.select=t}};return n(S({},this.props,u,{isLoading:a,onInputChange:this.onInputChange}))}}]),t}(l.Component);z.propTypes=B,z.defaultProps=H;var K=function(e){function t(e,n){O(this,t);var o=A(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n));return o.filterOptions=o.filterOptions.bind(o),o.menuRenderer=o.menuRenderer.bind(o),o.onInputKeyDown=o.onInputKeyDown.bind(o),o.onInputChange=o.onInputChange.bind(o),o.onOptionSelect=o.onOptionSelect.bind(o),o}return k(t,e),x(t,[{key:"createNewOption",value:function(){var e=this.props,t=e.isValidNewOption,n=e.newOptionCreator,o=e.onNewOptionClick,r=e.options,i=void 0===r?[]:r;if(t({label:this.inputValue})){var a=n({label:this.inputValue,labelKey:this.labelKey,valueKey:this.valueKey});this.isOptionUnique({option:a,options:i})&&(o?o(a):(i.unshift(a),this.select.selectValue(a)))}}},{key:"filterOptions",value:function(){var e=this.props,t=e.filterOptions,n=e.isValidNewOption,o=e.promptTextCreator,r=e.showNewOptionAtTop,i=(arguments.length<=2?void 0:arguments[2])||[],a=t.apply(void 0,arguments)||[];if(n({label:this.inputValue})){var s=this.props.newOptionCreator,u=s({label:this.inputValue,labelKey:this.labelKey,valueKey:this.valueKey});if(this.isOptionUnique({option:u,options:i.concat(a)})){var l=o(this.inputValue);this._createPlaceholderOption=s({label:l,labelKey:this.labelKey,valueKey:this.valueKey}),r?a.unshift(this._createPlaceholderOption):a.push(this._createPlaceholderOption)}}return a}},{key:"isOptionUnique",value:function(e){var t=e.option,n=e.options,o=this.props.isOptionUnique;return n=n||this.props.options,o({labelKey:this.labelKey,option:t,options:n,valueKey:this.valueKey})}},{key:"menuRenderer",value:function(e){return(0,this.props.menuRenderer)(S({},e,{onSelect:this.onOptionSelect,selectValue:this.onOptionSelect}))}},{key:"onInputChange",value:function(e){var t=this.props.onInputChange;return this.inputValue=e,t&&(this.inputValue=t(e)),this.inputValue}},{key:"onInputKeyDown",value:function(e){var t=this.props,n=t.shouldKeyDownEventCreateNewOption,o=t.onInputKeyDown,r=this.select.getFocusedOption();r&&r===this._createPlaceholderOption&&n(e)?(this.createNewOption(),e.preventDefault()):o&&o(e)}},{key:"onOptionSelect",value:function(e){e===this._createPlaceholderOption?this.createNewOption():this.select.selectValue(e)}},{key:"focus",value:function(){this.select.focus()}},{key:"render",value:function(){var e=this,t=this.props,n=t.ref,o=T(t,["ref"]),r=this.props.children;return r||(r=q),r(S({},o,{allowCreate:!0,filterOptions:this.filterOptions,menuRenderer:this.menuRenderer,onInputChange:this.onInputChange,onInputKeyDown:this.onInputKeyDown,ref:function(t){e.select=t,t&&(e.labelKey=t.props.labelKey,e.valueKey=t.props.valueKey),n&&n(t)}}))}}]),t}(c.a.Component),q=function(e){return c.a.createElement(V,e)},Y=function(e){var t=e.option,n=e.options,o=e.labelKey,r=e.valueKey;return!n||!n.length||0===n.filter(function(e){return e[o]===t[o]||e[r]===t[r]}).length},G=function(e){return!!e.label},X=function(e){var t=e.label,n=e.labelKey,o=e.valueKey,r={};return r[o]=t,r[n]=t,r.className="Select-create-option-placeholder",r},Z=function(e){return'Create option "'+e+'"'},J=function(e){switch(e.keyCode){case 9:case 13:case 188:return!0;default:return!1}};K.isOptionUnique=Y,K.isValidNewOption=G,K.newOptionCreator=X,K.promptTextCreator=Z,K.shouldKeyDownEventCreateNewOption=J,K.defaultProps={filterOptions:m,isOptionUnique:Y,isValidNewOption:G,menuRenderer:y,newOptionCreator:X,promptTextCreator:Z,shouldKeyDownEventCreateNewOption:J,showNewOptionAtTop:!0},K.propTypes={children:u.a.func,filterOptions:u.a.any,isOptionUnique:u.a.func,isValidNewOption:u.a.func,menuRenderer:u.a.any,newOptionCreator:u.a.func,onInputChange:u.a.func,onInputKeyDown:u.a.func,onNewOptionClick:u.a.func,options:u.a.array,promptTextCreator:u.a.func,ref:u.a.func,shouldKeyDownEventCreateNewOption:u.a.func,showNewOptionAtTop:u.a.bool};var $=function(e){function t(){return O(this,t),A(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return k(t,e),x(t,[{key:"focus",value:function(){this.select.focus()}},{key:"render",value:function(){var e=this;return c.a.createElement(z,this.props,function(t){var n=t.ref,o=T(t,["ref"]),r=n;return c.a.createElement(K,o,function(t){var n=t.ref,o=T(t,["ref"]),i=n;return e.props.children(S({},o,{ref:function(t){i(t),r(t),e.select=t}}))})})}}]),t}(c.a.Component),Q=function(e){return c.a.createElement(V,e)};$.propTypes={children:u.a.func.isRequired},$.defaultProps={children:Q},V.Async=z,V.AsyncCreatable=$,V.Creatable=K,V.Value=P,V.Option=_,t.default=V},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}function r(e,t){var n={};for(var o in e)t.indexOf(o)>=0||Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=e[o]);return n}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==typeof t&&"function"!==typeof t?e:t}function s(e,t){if("function"!==typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},l=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),c=n(0),p=o(c),f=n(1),d=o(f),h={position:"absolute",top:0,left:0,visibility:"hidden",height:0,overflow:"scroll",whiteSpace:"pre"},b=["extraWidth","injectStyles","inputClassName","inputRef","inputStyle","minWidth","onAutosize","placeholderIsMinWidth"],v=function(e){return b.forEach(function(t){return delete e[t]}),e},g=function(e,t){t.style.fontSize=e.fontSize,t.style.fontFamily=e.fontFamily,t.style.fontWeight=e.fontWeight,t.style.fontStyle=e.fontStyle,t.style.letterSpacing=e.letterSpacing,t.style.textTransform=e.textTransform},m=!("undefined"===typeof window||!window.navigator)&&/MSIE |Trident\/|Edge\//.test(window.navigator.userAgent),y=function(){return m?"_"+Math.random().toString(36).substr(2,12):void 0},E=function(e){function t(e){i(this,t);var n=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.inputRef=function(e){n.input=e,"function"===typeof n.props.inputRef&&n.props.inputRef(e)},n.placeHolderSizerRef=function(e){n.placeHolderSizer=e},n.sizerRef=function(e){n.sizer=e},n.state={inputWidth:e.minWidth,inputId:e.id||y()},n}return s(t,e),l(t,[{key:"componentDidMount",value:function(){this.mounted=!0,this.copyInputStyles(),this.updateInputWidth()}},{key:"componentWillReceiveProps",value:function(e){var t=e.id;t!==this.props.id&&this.setState({inputId:t||y()})}},{key:"componentDidUpdate",value:function(e,t){t.inputWidth!==this.state.inputWidth&&"function"===typeof this.props.onAutosize&&this.props.onAutosize(this.state.inputWidth),this.updateInputWidth()}},{key:"componentWillUnmount",value:function(){this.mounted=!1}},{key:"copyInputStyles",value:function(){if(this.mounted&&window.getComputedStyle){var e=this.input&&window.getComputedStyle(this.input);e&&(g(e,this.sizer),this.placeHolderSizer&&g(e,this.placeHolderSizer))}}},{key:"updateInputWidth",value:function(){if(this.mounted&&this.sizer&&"undefined"!==typeof this.sizer.scrollWidth){var e=void 0;e=this.props.placeholder&&(!this.props.value||this.props.value&&this.props.placeholderIsMinWidth)?Math.max(this.sizer.scrollWidth,this.placeHolderSizer.scrollWidth)+2:this.sizer.scrollWidth+2;e+="number"===this.props.type&&void 0===this.props.extraWidth?16:parseInt(this.props.extraWidth)||0,e<this.props.minWidth&&(e=this.props.minWidth),e!==this.state.inputWidth&&this.setState({inputWidth:e})}}},{key:"getInput",value:function(){return this.input}},{key:"focus",value:function(){this.input.focus()}},{key:"blur",value:function(){this.input.blur()}},{key:"select",value:function(){this.input.select()}},{key:"renderStyles",value:function(){var e=this.props.injectStyles;return m&&e?p.default.createElement("style",{dangerouslySetInnerHTML:{__html:"input#"+this.state.inputId+"::-ms-clear {display: none;}"}}):null}},{key:"render",value:function(){var e=[this.props.defaultValue,this.props.value,""].reduce(function(e,t){return null!==e&&void 0!==e?e:t}),t=u({},this.props.style);t.display||(t.display="inline-block");var n=u({boxSizing:"content-box",width:this.state.inputWidth+"px"},this.props.inputStyle),o=r(this.props,[]);return v(o),o.className=this.props.inputClassName,o.id=this.state.inputId,o.style=n,p.default.createElement("div",{className:this.props.className,style:t},this.renderStyles(),p.default.createElement("input",u({},o,{ref:this.inputRef})),p.default.createElement("div",{ref:this.sizerRef,style:h},e),this.props.placeholder?p.default.createElement("div",{ref:this.placeHolderSizerRef,style:h},this.props.placeholder):null)}}]),t}(c.Component);E.propTypes={className:d.default.string,defaultValue:d.default.any,extraWidth:d.default.oneOfType([d.default.number,d.default.string]),id:d.default.string,injectStyles:d.default.bool,inputClassName:d.default.string,inputRef:d.default.func,inputStyle:d.default.object,minWidth:d.default.oneOfType([d.default.number,d.default.string]),onAutosize:d.default.func,onChange:d.default.func,placeholder:d.default.string,placeholderIsMinWidth:d.default.bool,style:d.default.object,value:d.default.any},E.defaultProps={minWidth:1,injectStyles:!0},t.default=E},function(e,t,n){var o=n(180);"string"===typeof o&&(o=[[e.i,o,""]]);var r={};r.transform=void 0;n(54)(o,r);o.locals&&(e.exports=o.locals)},function(e,t,n){t=e.exports=n(53)(void 0),t.push([e.i,"/**\n * React Select\n * ============\n * Created by Jed Watson and Joss Mackison for KeystoneJS, http://www.keystonejs.com/\n * https://twitter.com/jedwatson https://twitter.com/jossmackison https://twitter.com/keystonejs\n * MIT License: https://github.com/JedWatson/react-select\n*/\n.Select {\n  position: relative;\n}\n.Select input::-webkit-contacts-auto-fill-button,\n.Select input::-webkit-credentials-auto-fill-button {\n  display: none !important;\n}\n.Select input::-ms-clear {\n  display: none !important;\n}\n.Select input::-ms-reveal {\n  display: none !important;\n}\n.Select,\n.Select div,\n.Select input,\n.Select span {\n  -webkit-box-sizing: border-box;\n  box-sizing: border-box;\n}\n.Select.is-disabled .Select-arrow-zone {\n  cursor: default;\n  pointer-events: none;\n  opacity: 0.35;\n}\n.Select.is-disabled > .Select-control {\n  background-color: #f9f9f9;\n}\n.Select.is-disabled > .Select-control:hover {\n  -webkit-box-shadow: none;\n          box-shadow: none;\n}\n.Select.is-open > .Select-control {\n  border-bottom-right-radius: 0;\n  border-bottom-left-radius: 0;\n  background: #fff;\n  border-color: #b3b3b3 #ccc #d9d9d9;\n}\n.Select.is-open > .Select-control .Select-arrow {\n  top: -2px;\n  border-color: transparent transparent #999;\n  border-width: 0 5px 5px;\n}\n.Select.is-searchable.is-open > .Select-control {\n  cursor: text;\n}\n.Select.is-searchable.is-focused:not(.is-open) > .Select-control {\n  cursor: text;\n}\n.Select.is-focused > .Select-control {\n  background: #fff;\n}\n.Select.is-focused:not(.is-open) > .Select-control {\n  border-color: #007eff;\n  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 0 3px rgba(0, 126, 255, 0.1);\n          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 0 3px rgba(0, 126, 255, 0.1);\n  background: #fff;\n}\n.Select.has-value.is-clearable.Select--single > .Select-control .Select-value {\n  padding-right: 42px;\n}\n.Select.has-value.Select--single > .Select-control .Select-value .Select-value-label,\n.Select.has-value.is-pseudo-focused.Select--single > .Select-control .Select-value .Select-value-label {\n  color: #333;\n}\n.Select.has-value.Select--single > .Select-control .Select-value a.Select-value-label,\n.Select.has-value.is-pseudo-focused.Select--single > .Select-control .Select-value a.Select-value-label {\n  cursor: pointer;\n  text-decoration: none;\n}\n.Select.has-value.Select--single > .Select-control .Select-value a.Select-value-label:hover,\n.Select.has-value.is-pseudo-focused.Select--single > .Select-control .Select-value a.Select-value-label:hover,\n.Select.has-value.Select--single > .Select-control .Select-value a.Select-value-label:focus,\n.Select.has-value.is-pseudo-focused.Select--single > .Select-control .Select-value a.Select-value-label:focus {\n  color: #007eff;\n  outline: none;\n  text-decoration: underline;\n}\n.Select.has-value.Select--single > .Select-control .Select-value a.Select-value-label:focus,\n.Select.has-value.is-pseudo-focused.Select--single > .Select-control .Select-value a.Select-value-label:focus {\n  background: #fff;\n}\n.Select.has-value.is-pseudo-focused .Select-input {\n  opacity: 0;\n}\n.Select.is-open .Select-arrow,\n.Select .Select-arrow-zone:hover > .Select-arrow {\n  border-top-color: #666;\n}\n.Select.Select--rtl {\n  direction: rtl;\n  text-align: right;\n}\n.Select-control {\n  background-color: #fff;\n  border-color: #d9d9d9 #ccc #b3b3b3;\n  border-radius: 4px;\n  border: 1px solid #ccc;\n  color: #333;\n  cursor: default;\n  display: table;\n  border-spacing: 0;\n  border-collapse: separate;\n  height: 36px;\n  outline: none;\n  overflow: hidden;\n  position: relative;\n  width: 100%;\n}\n.Select-control:hover {\n  -webkit-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.06);\n          box-shadow: 0 1px 0 rgba(0, 0, 0, 0.06);\n}\n.Select-control .Select-input:focus {\n  outline: none;\n  background: #fff;\n}\n.Select-placeholder,\n.Select--single > .Select-control .Select-value {\n  bottom: 0;\n  color: #aaa;\n  left: 0;\n  line-height: 34px;\n  padding-left: 10px;\n  padding-right: 10px;\n  position: absolute;\n  right: 0;\n  top: 0;\n  max-width: 100%;\n  overflow: hidden;\n  -o-text-overflow: ellipsis;\n     text-overflow: ellipsis;\n  white-space: nowrap;\n}\n.Select-input {\n  height: 34px;\n  padding-left: 10px;\n  padding-right: 10px;\n  vertical-align: middle;\n}\n.Select-input > input {\n  width: 100%;\n  background: none transparent;\n  border: 0 none;\n  -webkit-box-shadow: none;\n          box-shadow: none;\n  cursor: default;\n  display: inline-block;\n  font-family: inherit;\n  font-size: inherit;\n  margin: 0;\n  outline: none;\n  line-height: 17px;\n  /* For IE 8 compatibility */\n  padding: 8px 0 12px;\n  /* For IE 8 compatibility */\n  -webkit-appearance: none;\n}\n.is-focused .Select-input > input {\n  cursor: text;\n}\n.has-value.is-pseudo-focused .Select-input {\n  opacity: 0;\n}\n.Select-control:not(.is-searchable) > .Select-input {\n  outline: none;\n}\n.Select-loading-zone {\n  cursor: pointer;\n  display: table-cell;\n  position: relative;\n  text-align: center;\n  vertical-align: middle;\n  width: 16px;\n}\n.Select-loading {\n  -webkit-animation: Select-animation-spin 400ms infinite linear;\n  animation: Select-animation-spin 400ms infinite linear;\n  width: 16px;\n  height: 16px;\n  -webkit-box-sizing: border-box;\n          box-sizing: border-box;\n  border-radius: 50%;\n  border: 2px solid #ccc;\n  border-right-color: #333;\n  display: inline-block;\n  position: relative;\n  vertical-align: middle;\n}\n.Select-clear-zone {\n  -webkit-animation: Select-animation-fadeIn 200ms;\n  animation: Select-animation-fadeIn 200ms;\n  color: #999;\n  cursor: pointer;\n  display: table-cell;\n  position: relative;\n  text-align: center;\n  vertical-align: middle;\n  width: 17px;\n}\n.Select-clear-zone:hover {\n  color: #D0021B;\n}\n.Select-clear {\n  display: inline-block;\n  font-size: 18px;\n  line-height: 1;\n}\n.Select--multi .Select-clear-zone {\n  width: 17px;\n}\n.Select-arrow-zone {\n  cursor: pointer;\n  display: table-cell;\n  position: relative;\n  text-align: center;\n  vertical-align: middle;\n  width: 25px;\n  padding-right: 5px;\n}\n.Select--rtl .Select-arrow-zone {\n  padding-right: 0;\n  padding-left: 5px;\n}\n.Select-arrow {\n  border-color: #999 transparent transparent;\n  border-style: solid;\n  border-width: 5px 5px 2.5px;\n  display: inline-block;\n  height: 0;\n  width: 0;\n  position: relative;\n}\n.Select-control > *:last-child {\n  padding-right: 5px;\n}\n.Select--multi .Select-multi-value-wrapper {\n  display: inline-block;\n}\n.Select .Select-aria-only {\n  position: absolute;\n  display: inline-block;\n  height: 1px;\n  width: 1px;\n  margin: -1px;\n  clip: rect(0, 0, 0, 0);\n  overflow: hidden;\n  float: left;\n}\n@-webkit-keyframes Select-animation-fadeIn {\n  from {\n    opacity: 0;\n  }\n  to {\n    opacity: 1;\n  }\n}\n@keyframes Select-animation-fadeIn {\n  from {\n    opacity: 0;\n  }\n  to {\n    opacity: 1;\n  }\n}\n.Select-menu-outer {\n  border-bottom-right-radius: 4px;\n  border-bottom-left-radius: 4px;\n  background-color: #fff;\n  border: 1px solid #ccc;\n  border-top-color: #e6e6e6;\n  -webkit-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.06);\n          box-shadow: 0 1px 0 rgba(0, 0, 0, 0.06);\n  -webkit-box-sizing: border-box;\n          box-sizing: border-box;\n  margin-top: -1px;\n  max-height: 200px;\n  position: absolute;\n  left: 0;\n  top: 100%;\n  width: 100%;\n  z-index: 1;\n  -webkit-overflow-scrolling: touch;\n}\n.Select-menu {\n  max-height: 198px;\n  overflow-y: auto;\n}\n.Select-option {\n  -webkit-box-sizing: border-box;\n          box-sizing: border-box;\n  background-color: #fff;\n  color: #666666;\n  cursor: pointer;\n  display: block;\n  padding: 8px 10px;\n}\n.Select-option:last-child {\n  border-bottom-right-radius: 4px;\n  border-bottom-left-radius: 4px;\n}\n.Select-option.is-selected {\n  background-color: #f5faff;\n  /* Fallback color for IE 8 */\n  background-color: rgba(0, 126, 255, 0.04);\n  color: #333;\n}\n.Select-option.is-focused {\n  background-color: #ebf5ff;\n  /* Fallback color for IE 8 */\n  background-color: rgba(0, 126, 255, 0.08);\n  color: #333;\n}\n.Select-option.is-disabled {\n  color: #cccccc;\n  cursor: default;\n}\n.Select-noresults {\n  -webkit-box-sizing: border-box;\n          box-sizing: border-box;\n  color: #999999;\n  cursor: default;\n  display: block;\n  padding: 8px 10px;\n}\n.Select--multi .Select-input {\n  vertical-align: middle;\n  margin-left: 10px;\n  padding: 0;\n}\n.Select--multi.Select--rtl .Select-input {\n  margin-left: 0;\n  margin-right: 10px;\n}\n.Select--multi.has-value .Select-input {\n  margin-left: 5px;\n}\n.Select--multi .Select-value {\n  background-color: #ebf5ff;\n  /* Fallback color for IE 8 */\n  background-color: rgba(0, 126, 255, 0.08);\n  border-radius: 2px;\n  border: 1px solid #c2e0ff;\n  /* Fallback color for IE 8 */\n  border: 1px solid rgba(0, 126, 255, 0.24);\n  color: #007eff;\n  display: inline-block;\n  font-size: 0.9em;\n  line-height: 1.4;\n  margin-left: 5px;\n  margin-top: 5px;\n  vertical-align: top;\n}\n.Select--multi .Select-value-icon,\n.Select--multi .Select-value-label {\n  display: inline-block;\n  vertical-align: middle;\n}\n.Select--multi .Select-value-label {\n  border-bottom-right-radius: 2px;\n  border-top-right-radius: 2px;\n  cursor: default;\n  padding: 2px 5px;\n}\n.Select--multi a.Select-value-label {\n  color: #007eff;\n  cursor: pointer;\n  text-decoration: none;\n}\n.Select--multi a.Select-value-label:hover {\n  text-decoration: underline;\n}\n.Select--multi .Select-value-icon {\n  cursor: pointer;\n  border-bottom-left-radius: 2px;\n  border-top-left-radius: 2px;\n  border-right: 1px solid #c2e0ff;\n  /* Fallback color for IE 8 */\n  border-right: 1px solid rgba(0, 126, 255, 0.24);\n  padding: 1px 5px 3px;\n}\n.Select--multi .Select-value-icon:hover,\n.Select--multi .Select-value-icon:focus {\n  background-color: #d8eafd;\n  /* Fallback color for IE 8 */\n  background-color: rgba(0, 113, 230, 0.08);\n  color: #0071e6;\n}\n.Select--multi .Select-value-icon:active {\n  background-color: #c2e0ff;\n  /* Fallback color for IE 8 */\n  background-color: rgba(0, 126, 255, 0.24);\n}\n.Select--multi.Select--rtl .Select-value {\n  margin-left: 0;\n  margin-right: 5px;\n}\n.Select--multi.Select--rtl .Select-value-icon {\n  border-right: none;\n  border-left: 1px solid #c2e0ff;\n  /* Fallback color for IE 8 */\n  border-left: 1px solid rgba(0, 126, 255, 0.24);\n}\n.Select--multi.is-disabled .Select-value {\n  background-color: #fcfcfc;\n  border: 1px solid #e3e3e3;\n  color: #333;\n}\n.Select--multi.is-disabled .Select-value-icon {\n  cursor: not-allowed;\n  border-right: 1px solid #e3e3e3;\n}\n.Select--multi.is-disabled .Select-value-icon:hover,\n.Select--multi.is-disabled .Select-value-icon:focus,\n.Select--multi.is-disabled .Select-value-icon:active {\n  background-color: #fcfcfc;\n}\n@keyframes Select-animation-spin {\n  to {\n    -webkit-transform: rotate(1turn);\n            transform: rotate(1turn);\n  }\n}\n@-webkit-keyframes Select-animation-spin {\n  to {\n    -webkit-transform: rotate(1turn);\n  }\n}\n",""])},function(e,t){e.exports=function(e){var t="undefined"!==typeof window&&window.location;if(!t)throw new Error("fixUrls requires window.location");if(!e||"string"!==typeof e)return e;var n=t.protocol+"//"+t.host,o=n+t.pathname.replace(/\/[^\/]*$/,"/");return e.replace(/url\s*\(((?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)\)/gi,function(e,t){var r=t.trim().replace(/^"(.*)"$/,function(e,t){return t}).replace(/^'(.*)'$/,function(e,t){return t});if(/^(#|data:|http:\/\/|https:\/\/|file:\/\/\/)/i.test(r))return e;var i;return i=0===r.indexOf("//")?r:0===r.indexOf("/")?n+r:o+r.replace(/^\.\//,""),"url("+JSON.stringify(i)+")"})}},function(e,t,n){var o=n(183);"string"===typeof o&&(o=[[e.i,o,""]]);var r={};r.transform=void 0;n(54)(o,r);o.locals&&(e.exports=o.locals)},function(e,t,n){t=e.exports=n(53)(void 0),t.push([e.i,".rc-slider {\n  position: relative;\n  height: 14px;\n  padding: 5px 0;\n  width: 100%;\n  border-radius: 6px;\n  -ms-touch-action: none;\n      touch-action: none;\n  -webkit-box-sizing: border-box;\n          box-sizing: border-box;\n  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);\n}\n.rc-slider * {\n  -webkit-box-sizing: border-box;\n          box-sizing: border-box;\n  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);\n}\n.rc-slider-rail {\n  position: absolute;\n  width: 100%;\n  background-color: #e9e9e9;\n  height: 4px;\n  border-radius: 6px;\n}\n.rc-slider-track {\n  position: absolute;\n  left: 0;\n  height: 4px;\n  border-radius: 6px;\n  background-color: #abe2fb;\n}\n.rc-slider-handle {\n  position: absolute;\n  margin-left: -7px;\n  margin-top: -5px;\n  width: 14px;\n  height: 14px;\n  cursor: pointer;\n  cursor: -webkit-grab;\n  cursor: grab;\n  border-radius: 50%;\n  border: solid 2px #96dbfa;\n  background-color: #fff;\n  -ms-touch-action: pan-x;\n      touch-action: pan-x;\n}\n.rc-slider-handle:focus {\n  border-color: #57c5f7;\n  -webkit-box-shadow: 0 0 0 5px #96dbfa;\n          box-shadow: 0 0 0 5px #96dbfa;\n  outline: none;\n}\n.rc-slider-handle-click-focused:focus {\n  border-color: #96dbfa;\n  -webkit-box-shadow: unset;\n          box-shadow: unset;\n}\n.rc-slider-handle:hover {\n  border-color: #57c5f7;\n}\n.rc-slider-handle:active {\n  border-color: #57c5f7;\n  -webkit-box-shadow: 0 0 5px #57c5f7;\n          box-shadow: 0 0 5px #57c5f7;\n  cursor: -webkit-grabbing;\n  cursor: grabbing;\n}\n.rc-slider-mark {\n  position: absolute;\n  top: 18px;\n  left: 0;\n  width: 100%;\n  font-size: 12px;\n}\n.rc-slider-mark-text {\n  position: absolute;\n  display: inline-block;\n  vertical-align: middle;\n  text-align: center;\n  cursor: pointer;\n  color: #999;\n}\n.rc-slider-mark-text-active {\n  color: #666;\n}\n.rc-slider-step {\n  position: absolute;\n  width: 100%;\n  height: 4px;\n  background: transparent;\n}\n.rc-slider-dot {\n  position: absolute;\n  bottom: -2px;\n  margin-left: -4px;\n  width: 8px;\n  height: 8px;\n  border: 2px solid #e9e9e9;\n  background-color: #fff;\n  cursor: pointer;\n  border-radius: 50%;\n  vertical-align: middle;\n}\n.rc-slider-dot-active {\n  border-color: #96dbfa;\n}\n.rc-slider-disabled {\n  background-color: #e9e9e9;\n}\n.rc-slider-disabled .rc-slider-track {\n  background-color: #ccc;\n}\n.rc-slider-disabled .rc-slider-handle,\n.rc-slider-disabled .rc-slider-dot {\n  border-color: #ccc;\n  -webkit-box-shadow: none;\n          box-shadow: none;\n  background-color: #fff;\n  cursor: not-allowed;\n}\n.rc-slider-disabled .rc-slider-mark-text,\n.rc-slider-disabled .rc-slider-dot {\n  cursor: not-allowed !important;\n}\n.rc-slider-vertical {\n  width: 14px;\n  height: 100%;\n  padding: 0 5px;\n}\n.rc-slider-vertical .rc-slider-rail {\n  height: 100%;\n  width: 4px;\n}\n.rc-slider-vertical .rc-slider-track {\n  left: 5px;\n  bottom: 0;\n  width: 4px;\n}\n.rc-slider-vertical .rc-slider-handle {\n  margin-left: -5px;\n  margin-bottom: -7px;\n  -ms-touch-action: pan-y;\n      touch-action: pan-y;\n}\n.rc-slider-vertical .rc-slider-mark {\n  top: 0;\n  left: 18px;\n  height: 100%;\n}\n.rc-slider-vertical .rc-slider-step {\n  height: 100%;\n  width: 4px;\n}\n.rc-slider-vertical .rc-slider-dot {\n  left: 2px;\n  margin-bottom: -4px;\n}\n.rc-slider-vertical .rc-slider-dot:first-child {\n  margin-bottom: -4px;\n}\n.rc-slider-vertical .rc-slider-dot:last-child {\n  margin-bottom: -4px;\n}\n.rc-slider-tooltip-zoom-down-enter,\n.rc-slider-tooltip-zoom-down-appear {\n  -webkit-animation-duration: .3s;\n          animation-duration: .3s;\n  -webkit-animation-fill-mode: both;\n          animation-fill-mode: both;\n  display: block !important;\n  -webkit-animation-play-state: paused;\n          animation-play-state: paused;\n}\n.rc-slider-tooltip-zoom-down-leave {\n  -webkit-animation-duration: .3s;\n          animation-duration: .3s;\n  -webkit-animation-fill-mode: both;\n          animation-fill-mode: both;\n  display: block !important;\n  -webkit-animation-play-state: paused;\n          animation-play-state: paused;\n}\n.rc-slider-tooltip-zoom-down-enter.rc-slider-tooltip-zoom-down-enter-active,\n.rc-slider-tooltip-zoom-down-appear.rc-slider-tooltip-zoom-down-appear-active {\n  -webkit-animation-name: rcSliderTooltipZoomDownIn;\n          animation-name: rcSliderTooltipZoomDownIn;\n  -webkit-animation-play-state: running;\n          animation-play-state: running;\n}\n.rc-slider-tooltip-zoom-down-leave.rc-slider-tooltip-zoom-down-leave-active {\n  -webkit-animation-name: rcSliderTooltipZoomDownOut;\n          animation-name: rcSliderTooltipZoomDownOut;\n  -webkit-animation-play-state: running;\n          animation-play-state: running;\n}\n.rc-slider-tooltip-zoom-down-enter,\n.rc-slider-tooltip-zoom-down-appear {\n  -webkit-transform: scale(0, 0);\n      -ms-transform: scale(0, 0);\n          transform: scale(0, 0);\n  -webkit-animation-timing-function: cubic-bezier(0.23, 1, 0.32, 1);\n          animation-timing-function: cubic-bezier(0.23, 1, 0.32, 1);\n}\n.rc-slider-tooltip-zoom-down-leave {\n  -webkit-animation-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);\n          animation-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);\n}\n@-webkit-keyframes rcSliderTooltipZoomDownIn {\n  0% {\n    opacity: 0;\n    -webkit-transform-origin: 50% 100%;\n            transform-origin: 50% 100%;\n    -webkit-transform: scale(0, 0);\n            transform: scale(0, 0);\n  }\n  100% {\n    -webkit-transform-origin: 50% 100%;\n            transform-origin: 50% 100%;\n    -webkit-transform: scale(1, 1);\n            transform: scale(1, 1);\n  }\n}\n@keyframes rcSliderTooltipZoomDownIn {\n  0% {\n    opacity: 0;\n    -webkit-transform-origin: 50% 100%;\n            transform-origin: 50% 100%;\n    -webkit-transform: scale(0, 0);\n            transform: scale(0, 0);\n  }\n  100% {\n    -webkit-transform-origin: 50% 100%;\n            transform-origin: 50% 100%;\n    -webkit-transform: scale(1, 1);\n            transform: scale(1, 1);\n  }\n}\n@-webkit-keyframes rcSliderTooltipZoomDownOut {\n  0% {\n    -webkit-transform-origin: 50% 100%;\n            transform-origin: 50% 100%;\n    -webkit-transform: scale(1, 1);\n            transform: scale(1, 1);\n  }\n  100% {\n    opacity: 0;\n    -webkit-transform-origin: 50% 100%;\n            transform-origin: 50% 100%;\n    -webkit-transform: scale(0, 0);\n            transform: scale(0, 0);\n  }\n}\n@keyframes rcSliderTooltipZoomDownOut {\n  0% {\n    -webkit-transform-origin: 50% 100%;\n            transform-origin: 50% 100%;\n    -webkit-transform: scale(1, 1);\n            transform: scale(1, 1);\n  }\n  100% {\n    opacity: 0;\n    -webkit-transform-origin: 50% 100%;\n            transform-origin: 50% 100%;\n    -webkit-transform: scale(0, 0);\n            transform: scale(0, 0);\n  }\n}\n.rc-slider-tooltip {\n  position: absolute;\n  left: -9999px;\n  top: -9999px;\n  visibility: visible;\n  -webkit-box-sizing: border-box;\n          box-sizing: border-box;\n  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);\n}\n.rc-slider-tooltip * {\n  -webkit-box-sizing: border-box;\n          box-sizing: border-box;\n  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);\n}\n.rc-slider-tooltip-hidden {\n  display: none;\n}\n.rc-slider-tooltip-placement-top {\n  padding: 4px 0 8px 0;\n}\n.rc-slider-tooltip-inner {\n  padding: 6px 2px;\n  min-width: 24px;\n  height: 24px;\n  font-size: 12px;\n  line-height: 1;\n  color: #fff;\n  text-align: center;\n  text-decoration: none;\n  background-color: #6c6c6c;\n  border-radius: 6px;\n  -webkit-box-shadow: 0 0 4px #d9d9d9;\n          box-shadow: 0 0 4px #d9d9d9;\n}\n.rc-slider-tooltip-arrow {\n  position: absolute;\n  width: 0;\n  height: 0;\n  border-color: transparent;\n  border-style: solid;\n}\n.rc-slider-tooltip-placement-top .rc-slider-tooltip-arrow {\n  bottom: 4px;\n  left: 50%;\n  margin-left: -4px;\n  border-width: 4px 4px 0;\n  border-top-color: #6c6c6c;\n}\n",""])},function(e,t,n){var o=n(185);"string"===typeof o&&(o=[[e.i,o,""]]);var r={};r.transform=void 0;n(54)(o,r);o.locals&&(e.exports=o.locals)},function(e,t,n){t=e.exports=n(53)(void 0),t.push([e.i,'.colorscalePickerContainer {\n  max-height: 550px;\n  max-width: 700px;\n  min-width: 295px;\n  overflow-y: auto;\n  overflow-x: hidden;\n  background: rgba(242, 245, 250, 0.9);\n  border: 1px solid #c8d4e3;\n  position: absolute;\n  z-index: 99;\n  font-family: Helvetica, sans-serif;\n  padding: 10px;\n  resize: horizontal;\n  text-align: left;\n}\n\n.colorscalePickerContainer::-webkit-scrollbar {\n  width: 5px;\n  background-color: #dfe8f3;\n}\n\n.colorscalePickerContainer::-webkit-scrollbar-thumb {\n  background-color: #a2b1c6;\n}\n\n.colorscalePickerContainer::-webkit-scrollbar-track {\n  -webkit-box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.3);\n  background-color: #dfe8f3;\n}\n\n.colorscalePickerContainer .textLabel {\n  color: rgb(80, 103, 132);\n  font-size: 12px;\n  vertical-align: top;\n  font-weight: 600;\n  text-transform: uppercase;\n}\n\n.colorscalePickerContainer .spaceRight {\n  margin-right: 5px;\n}\n.colorscalePickerContainer .spaceRightZeroTop {\n  margin-right: 5px;\n  margin-top: 0;\n}\n.colorscalePickerContainer .spaceLeft {\n  margin-left: 5px;\n}\n.colorscalePickerContainer .spaceTop {\n  margin-top: 5px;\n}\n.colorscalePickerContainer .alignMiddle {\n  vertical-align: middle;\n}\n.colorscalePickerContainer .alignTop {\n  vertical-align: top;\n}\n.colorscalePickerContainer .zeroSpace {\n  margin: 0;\n}\n.colorscalePickerContainer .noWrap {\n  white-space: nowrap;\n}\n.colorscalePickerContainer .inlineBlock {\n  display: inline-block;\n}\n\n.colorscalePickerBottomContainer {\n  padding: 10px 0;\n}\n\n.colorscaleDescription {\n  font-size: 13px;\n  color: #506784;\n  border: 1px solid #c8d4e3;\n  padding: 10px;\n  border-radius: 2px;\n  text-align: left;\n  line-height: 1.4em;\n}\n\n.colorscaleControlPanel {\n  display: block;\n  padding: 10px;\n  width: 80%;\n  margin: 0 auto;\n}\n\n.colorscalePickerContainer input[type="range"] {\n  width: 200px;\n}\n\n.colorscalePickerContainer input[type="number"] {\n  vertical-align: top;\n  margin-top: -4px;\n  margin-right: 5px;\n}\n\n.colorscalePickerContainer input[type="text"] {\n  text-align: center;\n  font-size: 12px;\n  width: 90%;\n  margin-top: 5px;\n  padding: 5px;\n  border: 1px solid #dfe8f3;\n}\n\n.colorscaleControlsRow {\n  margin-top: 20px;\n}\n\n.colorscaleControlsRow div {\n  display: inline;\n}\n\n.colorscaleControlPanel .rc-slider-tooltip {\n  opacity: 1;\n  z-index: 999;\n  font-family: Helvetica, sans-serif;\n}\n\n.colorscaleControlPanel .rc-slider-rail {\n  background-color: #a2b1c6;\n}\n\n.Select.is-focused:not(.is-open) > .Select-control {\n  border-color: #c8d4e3 !important;\n  -webkit-box-shadow: none;\n          box-shadow: none;\n}\n',""])}])});

/***/ }),

/***/ "FSmo":
/*!**************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotScatterpolarIcon.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotScatterpolarIcon = function PlotScatterpolarIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M28.438 15.188l-.563-6.938c1.063-1.063 1.313-2.75.625-4.125-.625-1.375-2.063-2.188-3.625-2.063-1.5.125-2.813 1.188-3.188 2.688l-3.438.125c-.938-1.5-2.75-2.188-4.438-1.563-1.688.563-2.688 2.313-2.375 4.063l-4.375 1.75C5.873 8 4.123 7.75 2.748 8.5a3.647 3.647 0 0 0-1.875 3.938c.25 1.563 1.563 2.75 3.125 3l2 6.938c-1 .938-1.313 2.313-.938 3.625s1.438 2.25 2.75 2.563c1.313.25 2.688-.188 3.563-1.188l5.125.875c.938 1.438 2.688 2.063 4.313 1.5s2.688-2.188 2.438-3.938l3.625-3.438c1.938.375 3.875-.938 4.25-2.875.438-1.938-.75-3.875-2.688-4.313zm-3.375 6.25l-2.625 2.5c-.938-1.188-2.563-1.625-4-1.125-1.5.5-2.5 1.813-2.5 3.375l-3.75-.625a3.65 3.65 0 0 0-1.125-3.25c-.938-.875-2.188-1.188-3.375-.875l-1.75-6.313c1.688-.688 2.563-2.563 2.063-4.313l4.25-1.688a3.725 3.725 0 0 0 4.063 1.125c1.5-.563 2.438-1.938 2.438-3.5l2.875-.063c.5 1.875 2.438 3.063 4.375 2.625l.5 5.875c-1.313.375-2.25 1.438-2.563 2.75-.313 1.25.125 2.625 1.125 3.5z' })
    );
};

exports.default = PlotScatterpolarIcon;

/***/ }),

/***/ "FUBA":
/*!****************************************************************!*\
  !*** ./node_modules/react-input-autosize/lib/AutosizeInput.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var sizerStyle = {
	position: 'absolute',
	top: 0,
	left: 0,
	visibility: 'hidden',
	height: 0,
	overflow: 'scroll',
	whiteSpace: 'pre'
};

var INPUT_PROPS_BLACKLIST = ['extraWidth', 'injectStyles', 'inputClassName', 'inputRef', 'inputStyle', 'minWidth', 'onAutosize', 'placeholderIsMinWidth'];

var cleanInputProps = function cleanInputProps(inputProps) {
	INPUT_PROPS_BLACKLIST.forEach(function (field) {
		return delete inputProps[field];
	});
	return inputProps;
};

var copyStyles = function copyStyles(styles, node) {
	node.style.fontSize = styles.fontSize;
	node.style.fontFamily = styles.fontFamily;
	node.style.fontWeight = styles.fontWeight;
	node.style.fontStyle = styles.fontStyle;
	node.style.letterSpacing = styles.letterSpacing;
	node.style.textTransform = styles.textTransform;
};

var isIE = typeof window !== 'undefined' && window.navigator ? /MSIE |Trident\/|Edge\//.test(window.navigator.userAgent) : false;

var generateId = function generateId() {
	// we only need an auto-generated ID for stylesheet injection, which is only
	// used for IE. so if the browser is not IE, this should return undefined.
	return isIE ? '_' + Math.random().toString(36).substr(2, 12) : undefined;
};

var AutosizeInput = function (_Component) {
	_inherits(AutosizeInput, _Component);

	function AutosizeInput(props) {
		_classCallCheck(this, AutosizeInput);

		var _this = _possibleConstructorReturn(this, (AutosizeInput.__proto__ || Object.getPrototypeOf(AutosizeInput)).call(this, props));

		_this.inputRef = function (el) {
			_this.input = el;
			if (typeof _this.props.inputRef === 'function') {
				_this.props.inputRef(el);
			}
		};

		_this.placeHolderSizerRef = function (el) {
			_this.placeHolderSizer = el;
		};

		_this.sizerRef = function (el) {
			_this.sizer = el;
		};

		_this.state = {
			inputWidth: props.minWidth,
			inputId: props.id || generateId()
		};
		return _this;
	}

	_createClass(AutosizeInput, [{
		key: 'componentDidMount',
		value: function componentDidMount() {
			this.mounted = true;
			this.copyInputStyles();
			this.updateInputWidth();
		}
	}, {
		key: 'componentWillReceiveProps',
		value: function componentWillReceiveProps(nextProps) {
			var id = nextProps.id;

			if (id !== this.props.id) {
				this.setState({ inputId: id || generateId() });
			}
		}
	}, {
		key: 'componentDidUpdate',
		value: function componentDidUpdate(prevProps, prevState) {
			if (prevState.inputWidth !== this.state.inputWidth) {
				if (typeof this.props.onAutosize === 'function') {
					this.props.onAutosize(this.state.inputWidth);
				}
			}
			this.updateInputWidth();
		}
	}, {
		key: 'componentWillUnmount',
		value: function componentWillUnmount() {
			this.mounted = false;
		}
	}, {
		key: 'copyInputStyles',
		value: function copyInputStyles() {
			if (!this.mounted || !window.getComputedStyle) {
				return;
			}
			var inputStyles = this.input && window.getComputedStyle(this.input);
			if (!inputStyles) {
				return;
			}
			copyStyles(inputStyles, this.sizer);
			if (this.placeHolderSizer) {
				copyStyles(inputStyles, this.placeHolderSizer);
			}
		}
	}, {
		key: 'updateInputWidth',
		value: function updateInputWidth() {
			if (!this.mounted || !this.sizer || typeof this.sizer.scrollWidth === 'undefined') {
				return;
			}
			var newInputWidth = void 0;
			if (this.props.placeholder && (!this.props.value || this.props.value && this.props.placeholderIsMinWidth)) {
				newInputWidth = Math.max(this.sizer.scrollWidth, this.placeHolderSizer.scrollWidth) + 2;
			} else {
				newInputWidth = this.sizer.scrollWidth + 2;
			}
			// add extraWidth to the detected width. for number types, this defaults to 16 to allow for the stepper UI
			var extraWidth = this.props.type === 'number' && this.props.extraWidth === undefined ? 16 : parseInt(this.props.extraWidth) || 0;
			newInputWidth += extraWidth;
			if (newInputWidth < this.props.minWidth) {
				newInputWidth = this.props.minWidth;
			}
			if (newInputWidth !== this.state.inputWidth) {
				this.setState({
					inputWidth: newInputWidth
				});
			}
		}
	}, {
		key: 'getInput',
		value: function getInput() {
			return this.input;
		}
	}, {
		key: 'focus',
		value: function focus() {
			this.input.focus();
		}
	}, {
		key: 'blur',
		value: function blur() {
			this.input.blur();
		}
	}, {
		key: 'select',
		value: function select() {
			this.input.select();
		}
	}, {
		key: 'renderStyles',
		value: function renderStyles() {
			// this method injects styles to hide IE's clear indicator, which messes
			// with input size detection. the stylesheet is only injected when the
			// browser is IE, and can also be disabled by the `injectStyles` prop.
			var injectStyles = this.props.injectStyles;

			return isIE && injectStyles ? _react2.default.createElement('style', { dangerouslySetInnerHTML: {
					__html: 'input#' + this.state.inputId + '::-ms-clear {display: none;}'
				} }) : null;
		}
	}, {
		key: 'render',
		value: function render() {
			var sizerValue = [this.props.defaultValue, this.props.value, ''].reduce(function (previousValue, currentValue) {
				if (previousValue !== null && previousValue !== undefined) {
					return previousValue;
				}
				return currentValue;
			});

			var wrapperStyle = _extends({}, this.props.style);
			if (!wrapperStyle.display) wrapperStyle.display = 'inline-block';

			var inputStyle = _extends({
				boxSizing: 'content-box',
				width: this.state.inputWidth + 'px'
			}, this.props.inputStyle);

			var inputProps = _objectWithoutProperties(this.props, []);

			cleanInputProps(inputProps);
			inputProps.className = this.props.inputClassName;
			inputProps.id = this.state.inputId;
			inputProps.style = inputStyle;

			return _react2.default.createElement(
				'div',
				{ className: this.props.className, style: wrapperStyle },
				this.renderStyles(),
				_react2.default.createElement('input', _extends({}, inputProps, { ref: this.inputRef })),
				_react2.default.createElement(
					'div',
					{ ref: this.sizerRef, style: sizerStyle },
					sizerValue
				),
				this.props.placeholder ? _react2.default.createElement(
					'div',
					{ ref: this.placeHolderSizerRef, style: sizerStyle },
					this.props.placeholder
				) : null
			);
		}
	}]);

	return AutosizeInput;
}(_react.Component);

AutosizeInput.propTypes = {
	className: _propTypes2.default.string, // className for the outer element
	defaultValue: _propTypes2.default.any, // default field value
	extraWidth: _propTypes2.default.oneOfType([// additional width for input element
	_propTypes2.default.number, _propTypes2.default.string]),
	id: _propTypes2.default.string, // id to use for the input, can be set for consistent snapshots
	injectStyles: _propTypes2.default.bool, // inject the custom stylesheet to hide clear UI, defaults to true
	inputClassName: _propTypes2.default.string, // className for the input element
	inputRef: _propTypes2.default.func, // ref callback for the input element
	inputStyle: _propTypes2.default.object, // css styles for the input element
	minWidth: _propTypes2.default.oneOfType([// minimum width for input element
	_propTypes2.default.number, _propTypes2.default.string]),
	onAutosize: _propTypes2.default.func, // onAutosize handler: function(newWidth) {}
	onChange: _propTypes2.default.func, // onChange handler: function(event) {}
	placeholder: _propTypes2.default.string, // placeholder text
	placeholderIsMinWidth: _propTypes2.default.bool, // don't collapse size to less than the placeholder
	style: _propTypes2.default.object, // css styles for the outer element
	value: _propTypes2.default.any // field value
};
AutosizeInput.defaultProps = {
	minWidth: 1,
	injectStyles: true
};

exports.default = AutosizeInput;

/***/ }),

/***/ "FUXG":
/*!****************************************!*\
  !*** ./node_modules/des.js/lib/des.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.utils = __webpack_require__(/*! ./des/utils */ "Xudb");
exports.Cipher = __webpack_require__(/*! ./des/cipher */ "AYSA");
exports.DES = __webpack_require__(/*! ./des/des */ "Titl");
exports.CBC = __webpack_require__(/*! ./des/cbc */ "DaRl");
exports.EDE = __webpack_require__(/*! ./des/ede */ "H+yo");


/***/ }),

/***/ "FYw3":
/*!*************************************************************************!*\
  !*** ./node_modules/babel-runtime/helpers/possibleConstructorReturn.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _typeof2 = __webpack_require__(/*! ../helpers/typeof */ "EJiy");

var _typeof3 = _interopRequireDefault(_typeof2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = function (self, call) {
  if (!self) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }

  return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self;
};

/***/ }),

/***/ "FZZk":
/*!****************************************************************!*\
  !*** ./node_modules/@jupyterlab/pdf-extension/style/index.css ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "dwfJ");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "FbP/":
/*!************************************************************************!*\
  !*** ./node_modules/react-color/lib/components/photoshop/Photoshop.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Photoshop = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _merge = __webpack_require__(/*! lodash/merge */ "QkVN");

var _merge2 = _interopRequireDefault(_merge);

var _common = __webpack_require__(/*! ../common */ "TM95");

var _PhotoshopFields = __webpack_require__(/*! ./PhotoshopFields */ "81by");

var _PhotoshopFields2 = _interopRequireDefault(_PhotoshopFields);

var _PhotoshopPointerCircle = __webpack_require__(/*! ./PhotoshopPointerCircle */ "BKMn");

var _PhotoshopPointerCircle2 = _interopRequireDefault(_PhotoshopPointerCircle);

var _PhotoshopPointer = __webpack_require__(/*! ./PhotoshopPointer */ "sVjb");

var _PhotoshopPointer2 = _interopRequireDefault(_PhotoshopPointer);

var _PhotoshopButton = __webpack_require__(/*! ./PhotoshopButton */ "DRdP");

var _PhotoshopButton2 = _interopRequireDefault(_PhotoshopButton);

var _PhotoshopPreviews = __webpack_require__(/*! ./PhotoshopPreviews */ "2zpl");

var _PhotoshopPreviews2 = _interopRequireDefault(_PhotoshopPreviews);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Photoshop = exports.Photoshop = function (_React$Component) {
  _inherits(Photoshop, _React$Component);

  function Photoshop(props) {
    _classCallCheck(this, Photoshop);

    var _this = _possibleConstructorReturn(this, (Photoshop.__proto__ || Object.getPrototypeOf(Photoshop)).call(this));

    _this.state = {
      currentColor: props.hex
    };
    return _this;
  }

  _createClass(Photoshop, [{
    key: 'render',
    value: function render() {
      var _props = this.props,
          _props$styles = _props.styles,
          passedStyles = _props$styles === undefined ? {} : _props$styles,
          _props$className = _props.className,
          className = _props$className === undefined ? '' : _props$className;

      var styles = (0, _reactcss2.default)((0, _merge2.default)({
        'default': {
          picker: {
            background: '#DCDCDC',
            borderRadius: '4px',
            boxShadow: '0 0 0 1px rgba(0,0,0,.25), 0 8px 16px rgba(0,0,0,.15)',
            boxSizing: 'initial',
            width: '513px'
          },
          head: {
            backgroundImage: 'linear-gradient(-180deg, #F0F0F0 0%, #D4D4D4 100%)',
            borderBottom: '1px solid #B1B1B1',
            boxShadow: 'inset 0 1px 0 0 rgba(255,255,255,.2), inset 0 -1px 0 0 rgba(0,0,0,.02)',
            height: '23px',
            lineHeight: '24px',
            borderRadius: '4px 4px 0 0',
            fontSize: '13px',
            color: '#4D4D4D',
            textAlign: 'center'
          },
          body: {
            padding: '15px 15px 0',
            display: 'flex'
          },
          saturation: {
            width: '256px',
            height: '256px',
            position: 'relative',
            border: '2px solid #B3B3B3',
            borderBottom: '2px solid #F0F0F0',
            overflow: 'hidden'
          },
          hue: {
            position: 'relative',
            height: '256px',
            width: '19px',
            marginLeft: '10px',
            border: '2px solid #B3B3B3',
            borderBottom: '2px solid #F0F0F0'
          },
          controls: {
            width: '180px',
            marginLeft: '10px'
          },
          top: {
            display: 'flex'
          },
          previews: {
            width: '60px'
          },
          actions: {
            flex: '1',
            marginLeft: '20px'
          }
        }
      }, passedStyles));

      return _react2.default.createElement(
        'div',
        { style: styles.picker, className: 'photoshop-picker ' + className },
        _react2.default.createElement(
          'div',
          { style: styles.head },
          this.props.header
        ),
        _react2.default.createElement(
          'div',
          { style: styles.body, className: 'flexbox-fix' },
          _react2.default.createElement(
            'div',
            { style: styles.saturation },
            _react2.default.createElement(_common.Saturation, {
              hsl: this.props.hsl,
              hsv: this.props.hsv,
              pointer: _PhotoshopPointerCircle2.default,
              onChange: this.props.onChange
            })
          ),
          _react2.default.createElement(
            'div',
            { style: styles.hue },
            _react2.default.createElement(_common.Hue, {
              direction: 'vertical',
              hsl: this.props.hsl,
              pointer: _PhotoshopPointer2.default,
              onChange: this.props.onChange
            })
          ),
          _react2.default.createElement(
            'div',
            { style: styles.controls },
            _react2.default.createElement(
              'div',
              { style: styles.top, className: 'flexbox-fix' },
              _react2.default.createElement(
                'div',
                { style: styles.previews },
                _react2.default.createElement(_PhotoshopPreviews2.default, {
                  rgb: this.props.rgb,
                  currentColor: this.state.currentColor
                })
              ),
              _react2.default.createElement(
                'div',
                { style: styles.actions },
                _react2.default.createElement(_PhotoshopButton2.default, { label: 'OK', onClick: this.props.onAccept, active: true }),
                _react2.default.createElement(_PhotoshopButton2.default, { label: 'Cancel', onClick: this.props.onCancel }),
                _react2.default.createElement(_PhotoshopFields2.default, {
                  onChange: this.props.onChange,
                  rgb: this.props.rgb,
                  hsv: this.props.hsv,
                  hex: this.props.hex
                })
              )
            )
          )
        )
      );
    }
  }]);

  return Photoshop;
}(_react2.default.Component);

Photoshop.propTypes = {
  header: _propTypes2.default.string,
  styles: _propTypes2.default.object
};

Photoshop.defaultProps = {
  header: 'Color Picker',
  styles: {}
};

exports.default = (0, _common.ColorWrap)(Photoshop);

/***/ }),

/***/ "FcJ0":
/*!**************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotIsosurface3dIcon.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotIsosurface3dIcon = function PlotIsosurface3dIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M30.313 18.375l-2.375-2.188-4.438-11.5 1.063-1.375 4.063 7.563zm-12.5 5.188l-10.25-7L11.001 5h11.875l4.375 11.25zM24 2.938l-1.063 1.375H10.812l-3-1.625 7.75-.938zm-17.125 0l3.438 1.875-3.375 11.688-5.313 2.875v-7.813zM1.75 20.063l5.438-2.938 10.313 7-.938 6.125-9.313-2.563zm22.75 7l-7.25 3.063.875-5.938 9.5-7.375 2.75 2.563z' })
    );
};

exports.default = PlotIsosurface3dIcon;

/***/ }),

/***/ "FcOR":
/*!**********************************************************!*\
  !*** ./node_modules/draft-js/lib/DraftJsDebugLogging.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DraftJsDebugLogging
 */



module.exports = {
  logSelectionStateFailure: function logSelectionStateFailure() {
    return null;
  }
};

/***/ }),

/***/ "FdJ0":
/*!********************************************!*\
  !*** ./node_modules/lodash.curry/index.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global) {/**
 * lodash (Custom Build) <https://lodash.com/>
 * Build: `lodash modularize exports="npm" -o ./`
 * Copyright jQuery Foundation and other contributors <https://jquery.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
 */

/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';

/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';

/** Used to compose bitmasks for function metadata. */
var BIND_FLAG = 1,
    BIND_KEY_FLAG = 2,
    CURRY_BOUND_FLAG = 4,
    CURRY_FLAG = 8,
    CURRY_RIGHT_FLAG = 16,
    PARTIAL_FLAG = 32,
    PARTIAL_RIGHT_FLAG = 64,
    ARY_FLAG = 128,
    REARG_FLAG = 256,
    FLIP_FLAG = 512;

/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
    MAX_SAFE_INTEGER = 9007199254740991,
    MAX_INTEGER = 1.7976931348623157e+308,
    NAN = 0 / 0;

/** Used to associate wrap methods with their bit flags. */
var wrapFlags = [
  ['ary', ARY_FLAG],
  ['bind', BIND_FLAG],
  ['bindKey', BIND_KEY_FLAG],
  ['curry', CURRY_FLAG],
  ['curryRight', CURRY_RIGHT_FLAG],
  ['flip', FLIP_FLAG],
  ['partial', PARTIAL_FLAG],
  ['partialRight', PARTIAL_RIGHT_FLAG],
  ['rearg', REARG_FLAG]
];

/** `Object#toString` result references. */
var funcTag = '[object Function]',
    genTag = '[object GeneratorFunction]',
    symbolTag = '[object Symbol]';

/**
 * Used to match `RegExp`
 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
 */
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;

/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;

/** Used to match wrap detail comments. */
var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,
    reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
    reSplitDetails = /,? & /;

/** 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*)$/;

/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;

/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;

/** 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')();

/**
 * 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 `_.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 ? array.length : 0;

  while (++index < length) {
    if (iteratee(array[index], index, array) === false) {
      break;
    }
  }
  return array;
}

/**
 * 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 ? array.length : 0;
  return !!length && baseIndexOf(array, value, 0) > -1;
}

/**
 * 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) {
  if (value !== value) {
    return baseFindIndex(array, baseIsNaN, fromIndex);
  }
  var index = fromIndex - 1,
      length = array.length;

  while (++index < length) {
    if (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;
}

/**
 * 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;
}

/**
 * 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 `value` is a host object in IE < 9.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
 */
function isHostObject(value) {
  // Many host objects are `Object` objects that can coerce to strings
  // despite having improperly defined `toString` methods.
  var result = false;
  if (value != null && typeof value.toString != 'function') {
    try {
      result = !!(value + '');
    } catch (e) {}
  }
  return result;
}

/**
 * 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;
}

/** Used for built-in method references. */
var funcProto = Function.prototype,
    objectProto = Object.prototype;

/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];

/** 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 decompiled source of functions. */
var funcToString = funcProto.toString;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var objectToString = objectProto.toString;

/** 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 objectCreate = Object.create;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max,
    nativeMin = Math.min;

/* Used to set `toString` methods. */
var defineProperty = (function() {
  var func = getNative(Object, 'defineProperty'),
      name = getNative.name;

  return (name && name.length > 2) ? func : undefined;
}());

/**
 * The base implementation of `_.create` without support for assigning
 * properties to the created object.
 *
 * @private
 * @param {Object} prototype The object to inherit from.
 * @returns {Object} Returns the new object.
 */
function baseCreate(proto) {
  return isObject(proto) ? objectCreate(proto) : {};
}

/**
 * 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) || isHostObject(value)) ? reIsNative : reIsHostCtor;
  return pattern.test(toSource(value));
}

/**
 * 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;
}

/**
 * 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 & 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 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 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 & ARY_FLAG,
      isBind = bitmask & BIND_FLAG,
      isBindKey = bitmask & BIND_KEY_FLAG,
      isCurried = bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG),
      isFlip = bitmask & 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 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 & 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 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 & CURRY_FLAG,
      newHolders = isCurry ? holders : undefined,
      newHoldersRight = isCurry ? undefined : holders,
      newPartials = isCurry ? partials : undefined,
      newPartialsRight = isCurry ? undefined : partials;

  bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG);
  bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG);

  if (!(bitmask & CURRY_BOUND_FLAG)) {
    bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG);
  }

  var result = wrapFunc(func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity);
  result.placeholder = placeholder;
  return setWrapToString(result, func, bitmask);
}

/**
 * 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.
 *  The bitmask may be composed of the following 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 & BIND_KEY_FLAG;
  if (!isBindKey && typeof func != 'function') {
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  var length = partials ? partials.length : 0;
  if (!length) {
    bitmask &= ~(PARTIAL_FLAG | 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 & PARTIAL_RIGHT_FLAG) {
    var partialsRight = partials,
        holdersRight = holders;

    partials = holders = undefined;
  }

  var newData = [
    func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
    argPos, ary, arity
  ];

  func = newData[0];
  bitmask = newData[1];
  thisArg = newData[2];
  partials = newData[3];
  holders = newData[4];
  arity = newData[9] = newData[9] == null
    ? (isBindKey ? 0 : func.length)
    : nativeMax(newData[9] - length, 0);

  if (!arity && bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG)) {
    bitmask &= ~(CURRY_FLAG | CURRY_RIGHT_FLAG);
  }
  if (!bitmask || bitmask == BIND_FLAG) {
    var result = createBind(func, bitmask, thisArg);
  } else if (bitmask == CURRY_FLAG || bitmask == CURRY_RIGHT_FLAG) {
    result = createCurry(func, bitmask, arity);
  } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !holders.length) {
    result = createPartial(func, bitmask, thisArg, partials);
  } else {
    result = createHybrid.apply(undefined, newData);
  }
  return setWrapToString(result, func, bitmask);
}

/**
 * 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 = func;
  return object.placeholder;
}

/**
 * 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;
}

/**
 * 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) : [];
}

/**
 * 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,
      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 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) {
  length = length == null ? MAX_SAFE_INTEGER : length;
  return !!length &&
    (typeof value == 'number' || reIsUint.test(value)) &&
    (value > -1 && value % 1 == 0 && value < length);
}

/**
 * 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);
}

/**
 * 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;
}

/**
 * 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`.
 */
var setWrapToString = !defineProperty ? identity : function(wrapper, reference, bitmask) {
  var source = (reference + '');
  return defineProperty(wrapper, 'toString', {
    'configurable': true,
    'enumerable': false,
    'value': constant(insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)))
  });
};

/**
 * Converts `func` to its source code.
 *
 * @private
 * @param {Function} func The function to process.
 * @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 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, CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
  result.placeholder = curry.placeholder;
  return result;
}

/**
 * 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) {
  // The use of `Object#toString` avoids issues with the `typeof` operator
  // in Safari 8-9 which returns 'object' for typed array and other constructors.
  var tag = isObject(value) ? objectToString.call(value) : '';
  return tag == funcTag || tag == genTag;
}

/**
 * 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 && (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 && typeof value == 'object';
}

/**
 * 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) && objectToString.call(value) == symbolTag);
}

/**
 * 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 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 = value.replace(reTrim, '');
  var isBinary = reIsBinary.test(value);
  return (isBinary || reIsOctal.test(value))
    ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
    : (reIsBadHex.test(value) ? NAN : +value);
}

/**
 * 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;
  };
}

/**
 * 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;
}

// Assign default placeholders.
curry.placeholder = {};

module.exports = curry;

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "FkFl":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/application/lib/index.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
// Local CSS must be loaded prior to loading other libs.
__webpack_require__(/*! ../style/index.css */ "KItQ");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const docregistry_1 = __webpack_require__(/*! @jupyterlab/docregistry */ "jTF0");
const services_1 = __webpack_require__(/*! @jupyterlab/services */ "S9up");
const application_1 = __webpack_require__(/*! @phosphor/application */ "2R+v");
const disposable_1 = __webpack_require__(/*! @phosphor/disposable */ "uNUc");
const mimerenderers_1 = __webpack_require__(/*! ./mimerenderers */ "Oq9H");
const shell_1 = __webpack_require__(/*! ./shell */ "ldDC");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
var layoutrestorer_1 = __webpack_require__(/*! ./layoutrestorer */ "2F0p");
exports.ILayoutRestorer = layoutrestorer_1.ILayoutRestorer;
exports.LayoutRestorer = layoutrestorer_1.LayoutRestorer;
var mimerenderers_2 = __webpack_require__(/*! ./mimerenderers */ "Oq9H");
exports.IMimeDocumentTracker = mimerenderers_2.IMimeDocumentTracker;
var router_1 = __webpack_require__(/*! ./router */ "I9Sh");
exports.IRouter = router_1.IRouter;
exports.Router = router_1.Router;
var shell_2 = __webpack_require__(/*! ./shell */ "ldDC");
exports.ApplicationShell = shell_2.ApplicationShell;
/**
 * JupyterLab is the main application class. It is instantiated once and shared.
 */
class JupyterLab extends application_1.Application {
    /**
     * Construct a new JupyterLab object.
     */
    constructor(options = {}) {
        super({ shell: new shell_1.ApplicationShell() });
        /**
         * A list of all errors encountered when registering plugins.
         */
        this.registerPluginErrors = [];
        this._dirtyCount = 0;
        this._busyCount = 0;
        this._busySignal = new signaling_1.Signal(this);
        this._dirtySignal = new signaling_1.Signal(this);
        // Construct the default workspace name.
        const defaultWorkspace = coreutils_1.URLExt.join(coreutils_1.PageConfig.getOption('baseUrl'), coreutils_1.PageConfig.getOption('pageUrl'));
        // Set default workspace in page config.
        coreutils_1.PageConfig.setOption('defaultWorkspace', defaultWorkspace);
        // Instantiate public resources.
        this.serviceManager = options.serviceManager || new services_1.ServiceManager();
        this.commandLinker =
            options.commandLinker || new apputils_1.CommandLinker({ commands: this.commands });
        this.docRegistry = options.docRegistry || new docregistry_1.DocumentRegistry();
        // Remove extra resources (non-IInfo) from options object.
        delete options.serviceManager;
        delete options.commandLinker;
        delete options.docRegistry;
        // Populate application info.
        this._info = Object.assign({}, JupyterLab.defaultInfo, options, { defaultWorkspace });
        if (this._info.devMode) {
            this.shell.addClass('jp-mod-devMode');
        }
        // Make workspace accessible via a getter because it is set at runtime.
        Object.defineProperty(this._info, 'workspace', {
            get: () => coreutils_1.PageConfig.getOption('workspace') || ''
        });
        // Add initial model factory.
        this.docRegistry.addModelFactory(new docregistry_1.Base64ModelFactory());
        if (options.mimeExtensions) {
            for (let plugin of mimerenderers_1.createRendermimePlugins(options.mimeExtensions)) {
                this.registerPlugin(plugin);
            }
        }
    }
    /**
     * A method invoked on a document `'contextmenu'` event.
     *
     * #### Notes
     * The default implementation of this method opens the application
     * `contextMenu` at the current mouse position.
     *
     * If the application context menu has no matching content *or* if
     * the shift key is pressed, the default browser context menu will
     * be opened instead.
     *
     * A subclass may reimplement this method as needed.
     */
    evtContextMenu(event) {
        if (event.shiftKey) {
            return;
        }
        this._contextMenuEvent = event;
        if (this.contextMenu.open(event)) {
            event.preventDefault();
            event.stopPropagation();
        }
    }
    /**
     * Whether the application is dirty.
     */
    get isDirty() {
        return this._dirtyCount > 0;
    }
    /**
     * Whether the application is busy.
     */
    get isBusy() {
        return this._busyCount > 0;
    }
    /**
     * Returns a signal for when application changes its busy status.
     */
    get busySignal() {
        return this._busySignal;
    }
    /**
     * Returns a signal for when application changes its dirty status.
     */
    get dirtySignal() {
        return this._dirtySignal;
    }
    /**
     * The information about the application.
     */
    get info() {
        return this._info;
    }
    /**
     * Promise that resolves when state is first restored, returning layout description.
     *
     * #### Notes
     * This is just a reference to `shell.restored`.
     */
    get restored() {
        return this.shell.restored;
    }
    /**
     * Walks up the DOM hierarchy of the target of the active `contextmenu`
     * event, testing the nodes for a user-supplied funcion. This can
     * be used to find a node on which to operate, given a context menu click.
     *
     * @param test - a function that takes an `HTMLElement` and returns a
     *   boolean for whether it is the element the requester is seeking.
     *
     * @returns an HTMLElement or undefined, if none is found.
     */
    contextMenuFirst(test) {
        for (let node of this._getContextMenuNodes()) {
            if (test(node)) {
                return node;
            }
        }
        return undefined;
    }
    /**
     * Set the application state to dirty.
     *
     * @returns A disposable used to clear the dirty state for the caller.
     */
    setDirty() {
        const oldDirty = this.isDirty;
        this._dirtyCount++;
        if (this.isDirty !== oldDirty) {
            this._dirtySignal.emit(this.isDirty);
        }
        return new disposable_1.DisposableDelegate(() => {
            const oldDirty = this.isDirty;
            this._dirtyCount = Math.max(0, this._dirtyCount - 1);
            if (this.isDirty !== oldDirty) {
                this._dirtySignal.emit(this.isDirty);
            }
        });
    }
    /**
     * Set the application state to busy.
     *
     * @returns A disposable used to clear the busy state for the caller.
     */
    setBusy() {
        const oldBusy = this.isBusy;
        this._busyCount++;
        if (this.isBusy !== oldBusy) {
            this._busySignal.emit(this.isBusy);
        }
        return new disposable_1.DisposableDelegate(() => {
            const oldBusy = this.isBusy;
            this._busyCount--;
            if (this.isBusy !== oldBusy) {
                this._busySignal.emit(this.isBusy);
            }
        });
    }
    /**
     * Register plugins from a plugin module.
     *
     * @param mod - The plugin module to register.
     */
    registerPluginModule(mod) {
        let data = mod.default;
        // Handle commonjs exports.
        if (!mod.hasOwnProperty('__esModule')) {
            data = mod;
        }
        if (!Array.isArray(data)) {
            data = [data];
        }
        data.forEach(item => {
            try {
                this.registerPlugin(item);
            }
            catch (error) {
                this.registerPluginErrors.push(error);
            }
        });
    }
    /**
     * Register the plugins from multiple plugin modules.
     *
     * @param mods - The plugin modules to register.
     */
    registerPluginModules(mods) {
        mods.forEach(mod => {
            this.registerPluginModule(mod);
        });
    }
    /**
     * Gets the hierarchy of html nodes that was under the cursor
     * when the most recent contextmenu event was issued
     */
    _getContextMenuNodes() {
        if (!this._contextMenuEvent) {
            return [];
        }
        // this one-liner doesn't work, but should at some point
        // in the future (https://developer.mozilla.org/en-US/docs/Web/API/Event)
        // return this._contextMenuEvent.composedPath() as HTMLElement[];
        let nodes = [this._contextMenuEvent.target];
        while ('parentNode' in nodes[nodes.length - 1] &&
            nodes[nodes.length - 1].parentNode &&
            nodes[nodes.length - 1] !== nodes[nodes.length - 1].parentNode) {
            nodes.push(nodes[nodes.length - 1].parentNode);
        }
        return nodes;
    }
}
exports.JupyterLab = JupyterLab;
/**
 * The namespace for `JupyterLab` class statics.
 */
(function (JupyterLab) {
    /**
     * The default application info.
     */
    JupyterLab.defaultInfo = {
        name: coreutils_1.PageConfig.getOption('appName') || 'JupyterLab',
        namespace: coreutils_1.PageConfig.getOption('appNamespace'),
        version: coreutils_1.PageConfig.getOption('appVersion') || 'unknown',
        devMode: coreutils_1.PageConfig.getOption('devMode').toLowerCase() === 'true',
        deferred: { patterns: [], matches: [] },
        disabled: { patterns: [], matches: [] },
        mimeExtensions: [],
        urls: {
            base: coreutils_1.PageConfig.getOption('baseUrl'),
            page: coreutils_1.PageConfig.getOption('pageUrl'),
            public: coreutils_1.PageConfig.getOption('publicUrl'),
            settings: coreutils_1.PageConfig.getOption('settingsUrl'),
            themes: coreutils_1.PageConfig.getOption('themesUrl'),
            tree: coreutils_1.PageConfig.getOption('treeUrl'),
            workspaces: coreutils_1.PageConfig.getOption('workspacesUrl')
        },
        directories: {
            appSettings: coreutils_1.PageConfig.getOption('appSettingsDir'),
            schemas: coreutils_1.PageConfig.getOption('schemasDir'),
            static: coreutils_1.PageConfig.getOption('staticDir'),
            templates: coreutils_1.PageConfig.getOption('templatesDir'),
            themes: coreutils_1.PageConfig.getOption('themesDir'),
            userSettings: coreutils_1.PageConfig.getOption('userSettingsDir'),
            serverRoot: coreutils_1.PageConfig.getOption('serverRoot'),
            workspaces: coreutils_1.PageConfig.getOption('workspacesDir')
        },
        filesCached: coreutils_1.PageConfig.getOption('cacheFiles').toLowerCase() === 'true',
        workspace: '',
        defaultWorkspace: ''
    };
})(JupyterLab = exports.JupyterLab || (exports.JupyterLab = {}));


/***/ }),

/***/ "FlQf":
/*!*********************************************************************!*\
  !*** ./node_modules/core-js/library/modules/es6.string.iterator.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var $at = __webpack_require__(/*! ./_string-at */ "ccE7")(true);

// 21.1.3.27 String.prototype[@@iterator]()
__webpack_require__(/*! ./_iter-define */ "MPFp")(String, 'String', function (iterated) {
  this._t = String(iterated); // target
  this._i = 0;                // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function () {
  var O = this._t;
  var index = this._i;
  var point;
  if (index >= O.length) return { value: undefined, done: true };
  point = $at(O, index);
  this._i += point.length;
  return { value: point, done: false };
});


/***/ }),

/***/ "FmDU":
/*!******************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/widget.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
var messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
var properties_1 = __webpack_require__(/*! @phosphor/properties */ "3kwb");
var signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
var title_1 = __webpack_require__(/*! ./title */ "0jI2");
/**
 * The base class of the Phosphor widget hierarchy.
 *
 * #### Notes
 * This class will typically be subclassed in order to create a useful
 * widget. However, it can be used directly to host externally created
 * content.
 */
var Widget = (function () {
    /**
     * Construct a new widget.
     *
     * @param options - The options for initializing the widget.
     */
    function Widget(options) {
        if (options === void 0) { options = {}; }
        this._flags = 0;
        this._layout = null;
        this._parent = null;
        this._disposed = new signaling_1.Signal(this);
        this.node = Private.createNode(options);
        this.addClass('p-Widget');
    }
    /**
     * Dispose of the widget and its descendant widgets.
     *
     * #### Notes
     * It is unsafe to use the widget after it has been disposed.
     *
     * All calls made to this method after the first are a no-op.
     */
    Widget.prototype.dispose = function () {
        // Do nothing if the widget is already disposed.
        if (this.isDisposed) {
            return;
        }
        // Set the disposed flag and emit the disposed signal.
        this.setFlag(Widget.Flag.IsDisposed);
        this._disposed.emit(undefined);
        // Remove or detach the widget if necessary.
        if (this.parent) {
            this.parent = null;
        }
        else if (this.isAttached) {
            Widget.detach(this);
        }
        // Dispose of the widget layout.
        if (this._layout) {
            this._layout.dispose();
            this._layout = null;
        }
        // Clear the extra data associated with the widget.
        signaling_1.Signal.clearData(this);
        messaging_1.MessageLoop.clearData(this);
        properties_1.AttachedProperty.clearData(this);
    };
    Object.defineProperty(Widget.prototype, "disposed", {
        /**
         * A signal emitted when the widget is disposed.
         */
        get: function () {
            return this._disposed;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Widget.prototype, "isDisposed", {
        /**
         * Test whether the widget has been disposed.
         */
        get: function () {
            return this.testFlag(Widget.Flag.IsDisposed);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Widget.prototype, "isAttached", {
        /**
         * Test whether the widget's node is attached to the DOM.
         */
        get: function () {
            return this.testFlag(Widget.Flag.IsAttached);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Widget.prototype, "isHidden", {
        /**
         * Test whether the widget is explicitly hidden.
         */
        get: function () {
            return this.testFlag(Widget.Flag.IsHidden);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Widget.prototype, "isVisible", {
        /**
         * Test whether the widget is visible.
         *
         * #### Notes
         * A widget is visible when it is attached to the DOM, is not
         * explicitly hidden, and has no explicitly hidden ancestors.
         */
        get: function () {
            return this.testFlag(Widget.Flag.IsVisible);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Widget.prototype, "title", {
        /**
         * The title object for the widget.
         *
         * #### Notes
         * The title object is used by some container widgets when displaying
         * the widget alongside some title, such as a tab panel or side bar.
         *
         * Since not all widgets will use the title, it is created on demand.
         *
         * The `owner` property of the title is set to this widget.
         */
        get: function () {
            return Private.titleProperty.get(this);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Widget.prototype, "id", {
        /**
         * Get the id of the widget's DOM node.
         */
        get: function () {
            return this.node.id;
        },
        /**
         * Set the id of the widget's DOM node.
         */
        set: function (value) {
            this.node.id = value;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Widget.prototype, "dataset", {
        /**
         * The dataset for the widget's DOM node.
         */
        get: function () {
            return this.node.dataset;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Widget.prototype, "parent", {
        /**
         * Get the parent of the widget.
         */
        get: function () {
            return this._parent;
        },
        /**
         * Set the parent of the widget.
         *
         * #### Notes
         * Children are typically added to a widget by using a layout, which
         * means user code will not normally set the parent widget directly.
         *
         * The widget will be automatically removed from its old parent.
         *
         * This is a no-op if there is no effective parent change.
         */
        set: function (value) {
            if (this._parent === value) {
                return;
            }
            if (value && this.contains(value)) {
                throw new Error('Invalid parent widget.');
            }
            if (this._parent && !this._parent.isDisposed) {
                var msg = new Widget.ChildMessage('child-removed', this);
                messaging_1.MessageLoop.sendMessage(this._parent, msg);
            }
            this._parent = value;
            if (this._parent && !this._parent.isDisposed) {
                var msg = new Widget.ChildMessage('child-added', this);
                messaging_1.MessageLoop.sendMessage(this._parent, msg);
            }
            if (!this.isDisposed) {
                messaging_1.MessageLoop.sendMessage(this, Widget.Msg.ParentChanged);
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Widget.prototype, "layout", {
        /**
         * Get the layout for the widget.
         */
        get: function () {
            return this._layout;
        },
        /**
         * Set the layout for the widget.
         *
         * #### Notes
         * The layout is single-use only. It cannot be changed after the
         * first assignment.
         *
         * The layout is disposed automatically when the widget is disposed.
         */
        set: function (value) {
            if (this._layout === value) {
                return;
            }
            if (this.testFlag(Widget.Flag.DisallowLayout)) {
                throw new Error('Cannot set widget layout.');
            }
            if (this._layout) {
                throw new Error('Cannot change widget layout.');
            }
            if (value.parent) {
                throw new Error('Cannot change layout parent.');
            }
            this._layout = value;
            value.parent = this;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Create an iterator over the widget's children.
     *
     * @returns A new iterator over the children of the widget.
     *
     * #### Notes
     * The widget must have a populated layout in order to have children.
     *
     * If a layout is not installed, the returned iterator will be empty.
     */
    Widget.prototype.children = function () {
        return this._layout ? this._layout.iter() : algorithm_1.empty();
    };
    /**
     * Test whether a widget is a descendant of this widget.
     *
     * @param widget - The descendant widget of interest.
     *
     * @returns `true` if the widget is a descendant, `false` otherwise.
     */
    Widget.prototype.contains = function (widget) {
        for (var value = widget; value; value = value._parent) {
            if (value === this) {
                return true;
            }
        }
        return false;
    };
    /**
     * Test whether the widget's DOM node has the given class name.
     *
     * @param name - The class name of interest.
     *
     * @returns `true` if the node has the class, `false` otherwise.
     */
    Widget.prototype.hasClass = function (name) {
        return this.node.classList.contains(name);
    };
    /**
     * Add a class name to the widget's DOM node.
     *
     * @param name - The class name to add to the node.
     *
     * #### Notes
     * If the class name is already added to the node, this is a no-op.
     *
     * The class name must not contain whitespace.
     */
    Widget.prototype.addClass = function (name) {
        this.node.classList.add(name);
    };
    /**
     * Remove a class name from the widget's DOM node.
     *
     * @param name - The class name to remove from the node.
     *
     * #### Notes
     * If the class name is not yet added to the node, this is a no-op.
     *
     * The class name must not contain whitespace.
     */
    Widget.prototype.removeClass = function (name) {
        this.node.classList.remove(name);
    };
    /**
     * Toggle a class name on the widget's DOM node.
     *
     * @param name - The class name to toggle on the node.
     *
     * @param force - Whether to force add the class (`true`) or force
     *   remove the class (`false`). If not provided, the presence of
     *   the class will be toggled from its current state.
     *
     * @returns `true` if the class is now present, `false` otherwise.
     *
     * #### Notes
     * The class name must not contain whitespace.
     */
    Widget.prototype.toggleClass = function (name, force) {
        if (force === true) {
            this.node.classList.add(name);
            return true;
        }
        if (force === false) {
            this.node.classList.remove(name);
            return false;
        }
        return this.node.classList.toggle(name);
    };
    /**
     * Post an `'update-request'` message to the widget.
     *
     * #### Notes
     * This is a simple convenience method for posting the message.
     */
    Widget.prototype.update = function () {
        messaging_1.MessageLoop.postMessage(this, Widget.Msg.UpdateRequest);
    };
    /**
     * Post a `'fit-request'` message to the widget.
     *
     * #### Notes
     * This is a simple convenience method for posting the message.
     */
    Widget.prototype.fit = function () {
        messaging_1.MessageLoop.postMessage(this, Widget.Msg.FitRequest);
    };
    /**
     * Post an `'activate-request'` message to the widget.
     *
     * #### Notes
     * This is a simple convenience method for posting the message.
     */
    Widget.prototype.activate = function () {
        messaging_1.MessageLoop.postMessage(this, Widget.Msg.ActivateRequest);
    };
    /**
     * Send a `'close-request'` message to the widget.
     *
     * #### Notes
     * This is a simple convenience method for sending the message.
     */
    Widget.prototype.close = function () {
        messaging_1.MessageLoop.sendMessage(this, Widget.Msg.CloseRequest);
    };
    /**
     * Show the widget and make it visible to its parent widget.
     *
     * #### Notes
     * This causes the [[isHidden]] property to be `false`.
     *
     * If the widget is not explicitly hidden, this is a no-op.
     */
    Widget.prototype.show = function () {
        if (!this.testFlag(Widget.Flag.IsHidden)) {
            return;
        }
        if (this.isAttached && (!this.parent || this.parent.isVisible)) {
            messaging_1.MessageLoop.sendMessage(this, Widget.Msg.BeforeShow);
        }
        this.clearFlag(Widget.Flag.IsHidden);
        this.removeClass('p-mod-hidden');
        if (this.isAttached && (!this.parent || this.parent.isVisible)) {
            messaging_1.MessageLoop.sendMessage(this, Widget.Msg.AfterShow);
        }
        if (this.parent) {
            var msg = new Widget.ChildMessage('child-shown', this);
            messaging_1.MessageLoop.sendMessage(this.parent, msg);
        }
    };
    /**
     * Hide the widget and make it hidden to its parent widget.
     *
     * #### Notes
     * This causes the [[isHidden]] property to be `true`.
     *
     * If the widget is explicitly hidden, this is a no-op.
     */
    Widget.prototype.hide = function () {
        if (this.testFlag(Widget.Flag.IsHidden)) {
            return;
        }
        if (this.isAttached && (!this.parent || this.parent.isVisible)) {
            messaging_1.MessageLoop.sendMessage(this, Widget.Msg.BeforeHide);
        }
        this.setFlag(Widget.Flag.IsHidden);
        this.addClass('p-mod-hidden');
        if (this.isAttached && (!this.parent || this.parent.isVisible)) {
            messaging_1.MessageLoop.sendMessage(this, Widget.Msg.AfterHide);
        }
        if (this.parent) {
            var msg = new Widget.ChildMessage('child-hidden', this);
            messaging_1.MessageLoop.sendMessage(this.parent, msg);
        }
    };
    /**
     * Show or hide the widget according to a boolean value.
     *
     * @param hidden - `true` to hide the widget, or `false` to show it.
     *
     * #### Notes
     * This is a convenience method for `hide()` and `show()`.
     */
    Widget.prototype.setHidden = function (hidden) {
        if (hidden) {
            this.hide();
        }
        else {
            this.show();
        }
    };
    /**
     * Test whether the given widget flag is set.
     *
     * #### Notes
     * This will not typically be called directly by user code.
     */
    Widget.prototype.testFlag = function (flag) {
        return (this._flags & flag) !== 0;
    };
    /**
     * Set the given widget flag.
     *
     * #### Notes
     * This will not typically be called directly by user code.
     */
    Widget.prototype.setFlag = function (flag) {
        this._flags |= flag;
    };
    /**
     * Clear the given widget flag.
     *
     * #### Notes
     * This will not typically be called directly by user code.
     */
    Widget.prototype.clearFlag = function (flag) {
        this._flags &= ~flag;
    };
    /**
     * Process a message sent to the widget.
     *
     * @param msg - The message sent to the widget.
     *
     * #### Notes
     * Subclasses may reimplement this method as needed.
     */
    Widget.prototype.processMessage = function (msg) {
        switch (msg.type) {
            case 'resize':
                this.notifyLayout(msg);
                this.onResize(msg);
                break;
            case 'update-request':
                this.notifyLayout(msg);
                this.onUpdateRequest(msg);
                break;
            case 'fit-request':
                this.notifyLayout(msg);
                this.onFitRequest(msg);
                break;
            case 'before-show':
                this.notifyLayout(msg);
                this.onBeforeShow(msg);
                break;
            case 'after-show':
                this.setFlag(Widget.Flag.IsVisible);
                this.notifyLayout(msg);
                this.onAfterShow(msg);
                break;
            case 'before-hide':
                this.notifyLayout(msg);
                this.onBeforeHide(msg);
                break;
            case 'after-hide':
                this.clearFlag(Widget.Flag.IsVisible);
                this.notifyLayout(msg);
                this.onAfterHide(msg);
                break;
            case 'before-attach':
                this.notifyLayout(msg);
                this.onBeforeAttach(msg);
                break;
            case 'after-attach':
                if (!this.isHidden && (!this.parent || this.parent.isVisible)) {
                    this.setFlag(Widget.Flag.IsVisible);
                }
                this.setFlag(Widget.Flag.IsAttached);
                this.notifyLayout(msg);
                this.onAfterAttach(msg);
                break;
            case 'before-detach':
                this.notifyLayout(msg);
                this.onBeforeDetach(msg);
                break;
            case 'after-detach':
                this.clearFlag(Widget.Flag.IsVisible);
                this.clearFlag(Widget.Flag.IsAttached);
                this.notifyLayout(msg);
                this.onAfterDetach(msg);
                break;
            case 'activate-request':
                this.notifyLayout(msg);
                this.onActivateRequest(msg);
                break;
            case 'close-request':
                this.notifyLayout(msg);
                this.onCloseRequest(msg);
                break;
            case 'child-added':
                this.notifyLayout(msg);
                this.onChildAdded(msg);
                break;
            case 'child-removed':
                this.notifyLayout(msg);
                this.onChildRemoved(msg);
                break;
            default:
                this.notifyLayout(msg);
                break;
        }
    };
    /**
     * Invoke the message processing routine of the widget's layout.
     *
     * @param msg - The message to dispatch to the layout.
     *
     * #### Notes
     * This is a no-op if the widget does not have a layout.
     *
     * This will not typically be called directly by user code.
     */
    Widget.prototype.notifyLayout = function (msg) {
        if (this._layout) {
            this._layout.processParentMessage(msg);
        }
    };
    /**
     * A message handler invoked on a `'close-request'` message.
     *
     * #### Notes
     * The default implementation unparents or detaches the widget.
     */
    Widget.prototype.onCloseRequest = function (msg) {
        if (this.parent) {
            this.parent = null;
        }
        else if (this.isAttached) {
            Widget.detach(this);
        }
    };
    /**
     * A message handler invoked on a `'resize'` message.
     *
     * #### Notes
     * The default implementation of this handler is a no-op.
     */
    Widget.prototype.onResize = function (msg) { };
    /**
     * A message handler invoked on an `'update-request'` message.
     *
     * #### Notes
     * The default implementation of this handler is a no-op.
     */
    Widget.prototype.onUpdateRequest = function (msg) { };
    /**
     * A message handler invoked on a `'fit-request'` message.
     *
     * #### Notes
     * The default implementation of this handler is a no-op.
     */
    Widget.prototype.onFitRequest = function (msg) { };
    /**
     * A message handler invoked on an `'activate-request'` message.
     *
     * #### Notes
     * The default implementation of this handler is a no-op.
     */
    Widget.prototype.onActivateRequest = function (msg) { };
    /**
     * A message handler invoked on a `'before-show'` message.
     *
     * #### Notes
     * The default implementation of this handler is a no-op.
     */
    Widget.prototype.onBeforeShow = function (msg) { };
    /**
     * A message handler invoked on an `'after-show'` message.
     *
     * #### Notes
     * The default implementation of this handler is a no-op.
     */
    Widget.prototype.onAfterShow = function (msg) { };
    /**
     * A message handler invoked on a `'before-hide'` message.
     *
     * #### Notes
     * The default implementation of this handler is a no-op.
     */
    Widget.prototype.onBeforeHide = function (msg) { };
    /**
     * A message handler invoked on an `'after-hide'` message.
     *
     * #### Notes
     * The default implementation of this handler is a no-op.
     */
    Widget.prototype.onAfterHide = function (msg) { };
    /**
     * A message handler invoked on a `'before-attach'` message.
     *
     * #### Notes
     * The default implementation of this handler is a no-op.
     */
    Widget.prototype.onBeforeAttach = function (msg) { };
    /**
     * A message handler invoked on an `'after-attach'` message.
     *
     * #### Notes
     * The default implementation of this handler is a no-op.
     */
    Widget.prototype.onAfterAttach = function (msg) { };
    /**
     * A message handler invoked on a `'before-detach'` message.
     *
     * #### Notes
     * The default implementation of this handler is a no-op.
     */
    Widget.prototype.onBeforeDetach = function (msg) { };
    /**
     * A message handler invoked on an `'after-detach'` message.
     *
     * #### Notes
     * The default implementation of this handler is a no-op.
     */
    Widget.prototype.onAfterDetach = function (msg) { };
    /**
     * A message handler invoked on a `'child-added'` message.
     *
     * #### Notes
     * The default implementation of this handler is a no-op.
     */
    Widget.prototype.onChildAdded = function (msg) { };
    /**
     * A message handler invoked on a `'child-removed'` message.
     *
     * #### Notes
     * The default implementation of this handler is a no-op.
     */
    Widget.prototype.onChildRemoved = function (msg) { };
    return Widget;
}());
exports.Widget = Widget;
/**
 * The namespace for the `Widget` class statics.
 */
(function (Widget) {
    /**
     * An enum of widget bit flags.
     */
    var Flag;
    (function (Flag) {
        /**
         * The widget has been disposed.
         */
        Flag[Flag["IsDisposed"] = 1] = "IsDisposed";
        /**
         * The widget is attached to the DOM.
         */
        Flag[Flag["IsAttached"] = 2] = "IsAttached";
        /**
         * The widget is hidden.
         */
        Flag[Flag["IsHidden"] = 4] = "IsHidden";
        /**
         * The widget is visible.
         */
        Flag[Flag["IsVisible"] = 8] = "IsVisible";
        /**
         * A layout cannot be set on the widget.
         */
        Flag[Flag["DisallowLayout"] = 16] = "DisallowLayout";
    })(Flag = Widget.Flag || (Widget.Flag = {}));
    /**
     * A collection of stateless messages related to widgets.
     */
    var Msg;
    (function (Msg) {
        /**
         * A singleton `'before-show'` message.
         *
         * #### Notes
         * This message is sent to a widget before it becomes visible.
         *
         * This message is **not** sent when the widget is being attached.
         */
        Msg.BeforeShow = new messaging_1.Message('before-show');
        /**
         * A singleton `'after-show'` message.
         *
         * #### Notes
         * This message is sent to a widget after it becomes visible.
         *
         * This message is **not** sent when the widget is being attached.
         */
        Msg.AfterShow = new messaging_1.Message('after-show');
        /**
         * A singleton `'before-hide'` message.
         *
         * #### Notes
         * This message is sent to a widget before it becomes not-visible.
         *
         * This message is **not** sent when the widget is being detached.
         */
        Msg.BeforeHide = new messaging_1.Message('before-hide');
        /**
         * A singleton `'after-hide'` message.
         *
         * #### Notes
         * This message is sent to a widget after it becomes not-visible.
         *
         * This message is **not** sent when the widget is being detached.
         */
        Msg.AfterHide = new messaging_1.Message('after-hide');
        /**
         * A singleton `'before-attach'` message.
         *
         * #### Notes
         * This message is sent to a widget before it is attached.
         */
        Msg.BeforeAttach = new messaging_1.Message('before-attach');
        /**
         * A singleton `'after-attach'` message.
         *
         * #### Notes
         * This message is sent to a widget after it is attached.
         */
        Msg.AfterAttach = new messaging_1.Message('after-attach');
        /**
         * A singleton `'before-detach'` message.
         *
         * #### Notes
         * This message is sent to a widget before it is detached.
         */
        Msg.BeforeDetach = new messaging_1.Message('before-detach');
        /**
         * A singleton `'after-detach'` message.
         *
         * #### Notes
         * This message is sent to a widget after it is detached.
         */
        Msg.AfterDetach = new messaging_1.Message('after-detach');
        /**
         * A singleton `'parent-changed'` message.
         *
         * #### Notes
         * This message is sent to a widget when its parent has changed.
         */
        Msg.ParentChanged = new messaging_1.Message('parent-changed');
        /**
         * A singleton conflatable `'update-request'` message.
         *
         * #### Notes
         * This message can be dispatched to supporting widgets in order to
         * update their content based on the current widget state. Not all
         * widgets will respond to messages of this type.
         *
         * For widgets with a layout, this message will inform the layout to
         * update the position and size of its child widgets.
         */
        Msg.UpdateRequest = new messaging_1.ConflatableMessage('update-request');
        /**
         * A singleton conflatable `'fit-request'` message.
         *
         * #### Notes
         * For widgets with a layout, this message will inform the layout to
         * recalculate its size constraints to fit the space requirements of
         * its child widgets, and to update their position and size. Not all
         * layouts will respond to messages of this type.
         */
        Msg.FitRequest = new messaging_1.ConflatableMessage('fit-request');
        /**
         * A singleton conflatable `'activate-request'` message.
         *
         * #### Notes
         * This message should be dispatched to a widget when it should
         * perform the actions necessary to activate the widget, which
         * may include focusing its node or descendant node.
         */
        Msg.ActivateRequest = new messaging_1.ConflatableMessage('activate-request');
        /**
         * A singleton conflatable `'close-request'` message.
         *
         * #### Notes
         * This message should be dispatched to a widget when it should close
         * and remove itself from the widget hierarchy.
         */
        Msg.CloseRequest = new messaging_1.ConflatableMessage('close-request');
    })(Msg = Widget.Msg || (Widget.Msg = {}));
    /**
     * A message class for child related messages.
     */
    var ChildMessage = (function (_super) {
        __extends(ChildMessage, _super);
        /**
         * Construct a new child message.
         *
         * @param type - The message type.
         *
         * @param child - The child widget for the message.
         */
        function ChildMessage(type, child) {
            var _this = _super.call(this, type) || this;
            _this.child = child;
            return _this;
        }
        return ChildMessage;
    }(messaging_1.Message));
    Widget.ChildMessage = ChildMessage;
    /**
     * A message class for `'resize'` messages.
     */
    var ResizeMessage = (function (_super) {
        __extends(ResizeMessage, _super);
        /**
         * Construct a new resize message.
         *
         * @param width - The **offset width** of the widget, or `-1` if
         *   the width is not known.
         *
         * @param height - The **offset height** of the widget, or `-1` if
         *   the height is not known.
         */
        function ResizeMessage(width, height) {
            var _this = _super.call(this, 'resize') || this;
            _this.width = width;
            _this.height = height;
            return _this;
        }
        return ResizeMessage;
    }(messaging_1.Message));
    Widget.ResizeMessage = ResizeMessage;
    /**
     * The namespace for the `ResizeMessage` class statics.
     */
    (function (ResizeMessage) {
        /**
         * A singleton `'resize'` message with an unknown size.
         */
        ResizeMessage.UnknownSize = new ResizeMessage(-1, -1);
    })(ResizeMessage = Widget.ResizeMessage || (Widget.ResizeMessage = {}));
    /**
     * Attach a widget to a host DOM node.
     *
     * @param widget - The widget of interest.
     *
     * @param host - The DOM node to use as the widget's host.
     *
     * @param ref - The child of `host` to use as the reference element.
     *   If this is provided, the widget will be inserted before this
     *   node in the host. The default is `null`, which will cause the
     *   widget to be added as the last child of the host.
     *
     * #### Notes
     * This will throw an error if the widget is not a root widget, if
     * the widget is already attached, or if the host is not attached
     * to the DOM.
     */
    function attach(widget, host, ref) {
        if (ref === void 0) { ref = null; }
        if (widget.parent) {
            throw new Error('Cannot attach a child widget.');
        }
        if (widget.isAttached || document.body.contains(widget.node)) {
            throw new Error('Widget is already attached.');
        }
        if (!document.body.contains(host)) {
            throw new Error('Host is not attached.');
        }
        messaging_1.MessageLoop.sendMessage(widget, Widget.Msg.BeforeAttach);
        host.insertBefore(widget.node, ref);
        messaging_1.MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach);
    }
    Widget.attach = attach;
    /**
     * Detach the widget from its host DOM node.
     *
     * @param widget - The widget of interest.
     *
     * #### Notes
     * This will throw an error if the widget is not a root widget,
     * or if the widget is not attached to the DOM.
     */
    function detach(widget) {
        if (widget.parent) {
            throw new Error('Cannot detach a child widget.');
        }
        if (!widget.isAttached || !document.body.contains(widget.node)) {
            throw new Error('Widget is not attached.');
        }
        messaging_1.MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);
        widget.node.parentNode.removeChild(widget.node);
        messaging_1.MessageLoop.sendMessage(widget, Widget.Msg.AfterDetach);
    }
    Widget.detach = detach;
})(Widget = exports.Widget || (exports.Widget = {}));
exports.Widget = Widget;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * An attached property for the widget title object.
     */
    Private.titleProperty = new properties_1.AttachedProperty({
        name: 'title',
        create: function (owner) { return new title_1.Title({ owner: owner }); },
    });
    /**
     * Create a DOM node for the given widget options.
     */
    function createNode(options) {
        return options.node || document.createElement('div');
    }
    Private.createNode = createNode;
})(Private || (Private = {}));


/***/ }),

/***/ "FpHa":
/*!****************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_enum-bug-keys.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

// IE 8- don't enum bug keys
module.exports = (
  'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');


/***/ }),

/***/ "FvI0":
/*!*******************************************************!*\
  !*** ./node_modules/@phosphor/algorithm/lib/chain.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var iter_1 = __webpack_require__(/*! ./iter */ "DMSk");
/**
 * Chain together several iterables.
 *
 * @param objects - The iterable or array-like objects of interest.
 *
 * @returns An iterator which yields the values of the iterables
 *   in the order in which they are supplied.
 *
 * #### Example
 * ```typescript
 * import { chain, toArray } from '@phosphor/algorithm';
 *
 * let data1 = [1, 2, 3];
 * let data2 = [4, 5, 6];
 *
 * let stream = chain(data1, data2);
 *
 * toArray(stream);  // [1, 2, 3, 4, 5, 6]
 * ```
 */
function chain() {
    var objects = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        objects[_i] = arguments[_i];
    }
    return new ChainIterator(iter_1.iter(objects.map(iter_1.iter)));
}
exports.chain = chain;
/**
 * An iterator which chains together several iterators.
 */
var ChainIterator = (function () {
    /**
     * Construct a new chain iterator.
     *
     * @param source - The iterator of iterators of interest.
     */
    function ChainIterator(source) {
        this._cloned = false;
        this._source = source;
        this._active = undefined;
    }
    /**
     * Get an iterator over the object's values.
     *
     * @returns An iterator which yields the object's values.
     */
    ChainIterator.prototype.iter = function () {
        return this;
    };
    /**
     * Create an independent clone of the iterator.
     *
     * @returns A new independent clone of the iterator.
     */
    ChainIterator.prototype.clone = function () {
        var result = new ChainIterator(this._source.clone());
        result._active = this._active && this._active.clone();
        result._cloned = true;
        this._cloned = true;
        return result;
    };
    /**
     * Get the next value from the iterator.
     *
     * @returns The next value from the iterator, or `undefined`.
     */
    ChainIterator.prototype.next = function () {
        if (this._active === undefined) {
            var active = this._source.next();
            if (active === undefined) {
                return undefined;
            }
            this._active = this._cloned ? active.clone() : active;
        }
        var value = this._active.next();
        if (value !== undefined) {
            return value;
        }
        this._active = undefined;
        return this.next();
    };
    return ChainIterator;
}());
exports.ChainIterator = ChainIterator;


/***/ }),

/***/ "FwNs":
/*!********************************************************!*\
  !*** ./node_modules/react-tabs/esm/components/Tabs.js ***!
  \********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Tabs; });
/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! prop-types */ "17x9");
/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(prop_types__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "q1tI");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _helpers_propTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../helpers/propTypes */ "6ak3");
/* harmony import */ var _UncontrolledTabs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./UncontrolledTabs */ "guEx");
/* harmony import */ var _helpers_count__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../helpers/count */ "Oive");
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }







var Tabs =
/*#__PURE__*/
function (_Component) {
  _inheritsLoose(Tabs, _Component);

  function Tabs(props) {
    var _this;

    _this = _Component.call(this, props) || this;

    _this.handleSelected = function (index, last, event) {
      var onSelect = _this.props.onSelect; // Call change event handler

      if (typeof onSelect === 'function') {
        // Check if the change event handler cancels the tab change
        if (onSelect(index, last, event) === false) return;
      }

      var state = {
        // Set focus if the change was triggered from the keyboard
        focus: event.type === 'keydown'
      };

      if (Tabs.inUncontrolledMode(_this.props)) {
        // Update selected index
        state.selectedIndex = index;
      }

      _this.setState(state);
    };

    _this.state = Tabs.copyPropsToState(_this.props, {}, props.defaultFocus);
    return _this;
  }

  var _proto = Tabs.prototype;

  _proto.componentWillReceiveProps = function componentWillReceiveProps(newProps) {
    if ("development" !== 'production' && Tabs.inUncontrolledMode(newProps) !== Tabs.inUncontrolledMode(this.props)) {
      throw new Error("Switching between controlled mode (by using `selectedIndex`) and uncontrolled mode is not supported in `Tabs`.\nFor more information about controlled and uncontrolled mode of react-tabs see the README.");
    } // Use a transactional update to prevent race conditions
    // when reading the state in copyPropsToState
    // See https://github.com/reactjs/react-tabs/issues/51


    this.setState(function (state) {
      return Tabs.copyPropsToState(newProps, state);
    });
  };

  Tabs.inUncontrolledMode = function inUncontrolledMode(props) {
    return props.selectedIndex === null;
  };

  // preserve the existing selectedIndex from state.
  // If the state has not selectedIndex, default to the defaultIndex or 0
  Tabs.copyPropsToState = function copyPropsToState(props, state, focus) {
    if (focus === void 0) {
      focus = false;
    }

    var newState = {
      focus: focus
    };

    if (Tabs.inUncontrolledMode(props)) {
      var maxTabIndex = Object(_helpers_count__WEBPACK_IMPORTED_MODULE_4__["getTabsCount"])(props.children) - 1;
      var selectedIndex = null;

      if (state.selectedIndex != null) {
        selectedIndex = Math.min(state.selectedIndex, maxTabIndex);
      } else {
        selectedIndex = props.defaultIndex || 0;
      }

      newState.selectedIndex = selectedIndex;
    }

    return newState;
  };

  _proto.render = function render() {
    var _this$props = this.props,
        children = _this$props.children,
        defaultIndex = _this$props.defaultIndex,
        defaultFocus = _this$props.defaultFocus,
        props = _objectWithoutPropertiesLoose(_this$props, ["children", "defaultIndex", "defaultFocus"]);

    var _this$state = this.state,
        focus = _this$state.focus,
        selectedIndex = _this$state.selectedIndex;
    props.focus = focus;
    props.onSelect = this.handleSelected;

    if (selectedIndex != null) {
      props.selectedIndex = selectedIndex;
    }

    return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_UncontrolledTabs__WEBPACK_IMPORTED_MODULE_3__["default"], props, children);
  };

  return Tabs;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]);

Tabs.defaultProps = {
  defaultFocus: false,
  forceRenderTabPanel: false,
  selectedIndex: null,
  defaultIndex: null
};

Tabs.propTypes =  true ? {
  children: _helpers_propTypes__WEBPACK_IMPORTED_MODULE_2__["childrenPropType"],
  className: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.array, prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.object]),
  defaultFocus: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.bool,
  defaultIndex: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.number,
  disabledTabClassName: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.string,
  domRef: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.func,
  forceRenderTabPanel: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.bool,
  onSelect: _helpers_propTypes__WEBPACK_IMPORTED_MODULE_2__["onSelectPropType"],
  selectedIndex: _helpers_propTypes__WEBPACK_IMPORTED_MODULE_2__["selectedIndexPropType"],
  selectedTabClassName: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.string,
  selectedTabPanelClassName: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.string
} : undefined;
Tabs.tabsRole = 'Tabs';

/***/ }),

/***/ "FyfS":
/*!************************************************************!*\
  !*** ./node_modules/babel-runtime/core-js/get-iterator.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = { "default": __webpack_require__(/*! core-js/library/fn/get-iterator */ "Rp86"), __esModule: true };

/***/ }),

/***/ "Fzdc":
/*!*******************************************!*\
  !*** ./node_modules/base16/lib/bespin.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'bespin',
  author: 'jan t. sott',
  base00: '#28211c',
  base01: '#36312e',
  base02: '#5e5d5c',
  base03: '#666666',
  base04: '#797977',
  base05: '#8a8986',
  base06: '#9d9b97',
  base07: '#baae9e',
  base08: '#cf6a4c',
  base09: '#cf7d34',
  base0A: '#f9ee98',
  base0B: '#54be0d',
  base0C: '#afc4db',
  base0D: '#5ea6ea',
  base0E: '#9b859d',
  base0F: '#937121'
};
module.exports = exports['default'];

/***/ }),

/***/ "G+QD":
/*!***********************************************!*\
  !*** ./node_modules/xterm/lib/utils/Clone.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.clone = function (val, depth) {
    if (depth === void 0) { depth = 5; }
    if (typeof val !== 'object') {
        return val;
    }
    if (val === null) {
        return null;
    }
    var clonedObject = Array.isArray(val) ? [] : {};
    for (var key in val) {
        clonedObject[key] = depth <= 1 ? val[key] : exports.clone(val[key], depth - 1);
    }
    return clonedObject;
};

//# sourceMappingURL=Clone.js.map


/***/ }),

/***/ "G0Uy":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/mt.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var mt = moment.defineLocale('mt', {
    months : 'Jannar_Frar_Marzu_April_Mejju_Ġunju_Lulju_Awwissu_Settembru_Ottubru_Novembru_Diċembru'.split('_'),
    monthsShort : 'Jan_Fra_Mar_Apr_Mej_Ġun_Lul_Aww_Set_Ott_Nov_Diċ'.split('_'),
    weekdays : 'Il-Ħadd_It-Tnejn_It-Tlieta_L-Erbgħa_Il-Ħamis_Il-Ġimgħa_Is-Sibt'.split('_'),
    weekdaysShort : 'Ħad_Tne_Tli_Erb_Ħam_Ġim_Sib'.split('_'),
    weekdaysMin : 'Ħa_Tn_Tl_Er_Ħa_Ġi_Si'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd, D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay : '[Illum fil-]LT',
        nextDay : '[Għada fil-]LT',
        nextWeek : 'dddd [fil-]LT',
        lastDay : '[Il-bieraħ fil-]LT',
        lastWeek : 'dddd [li għadda] [fil-]LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'f’ %s',
        past : '%s ilu',
        s : 'ftit sekondi',
        ss : '%d sekondi',
        m : 'minuta',
        mm : '%d minuti',
        h : 'siegħa',
        hh : '%d siegħat',
        d : 'ġurnata',
        dd : '%d ġranet',
        M : 'xahar',
        MM : '%d xhur',
        y : 'sena',
        yy : '%d sni'
    },
    dayOfMonthOrdinalParse : /\d{1,2}º/,
    ordinal: '%dº',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return mt;

})));


/***/ }),

/***/ "G6z8":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_getAllKeysIn.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseGetAllKeys = __webpack_require__(/*! ./_baseGetAllKeys */ "fR/l"),
    getSymbolsIn = __webpack_require__(/*! ./_getSymbolsIn */ "oCl/"),
    keysIn = __webpack_require__(/*! ./keysIn */ "mTTR");

/**
 * 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);
}

module.exports = getAllKeysIn;


/***/ }),

/***/ "G7cy":
/*!****************************************************!*\
  !*** ./node_modules/pure-color/convert/rgb2hex.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var clamp = __webpack_require__(/*! ../util/clamp */ "I0N7");

function componentToHex(c) {
  var value = Math.round(clamp(c, 0, 255));
  var hex   = value.toString(16);

  return hex.length == 1 ? "0" + hex : hex;
}

function rgb2hex(rgb) {
  var alpha = rgb.length === 4 ? componentToHex(rgb[3] * 255) : "";

  return "#" + componentToHex(rgb[0]) + componentToHex(rgb[1]) + componentToHex(rgb[2]) + alpha;
}

module.exports = rgb2hex;

/***/ }),

/***/ "G8Mo":
/*!***************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_to-primitive.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = __webpack_require__(/*! ./_is-object */ "93I4");
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function (it, S) {
  if (!isObject(it)) return it;
  var fn, val;
  if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
  if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;
  if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
  throw TypeError("Can't convert object to primitive value");
};


/***/ }),

/***/ "GBY4":
/*!*****************************************!*\
  !*** ./node_modules/url-parse/index.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {

var required = __webpack_require__(/*! requires-port */ "RA0T")
  , qs = __webpack_require__(/*! querystringify */ "nFlj")
  , protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\S\s]*)/i
  , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\//;

/**
 * These are the parse rules for the URL parser, it informs the parser
 * about:
 *
 * 0. The char it Needs to parse, if it's a string it should be done using
 *    indexOf, RegExp using exec and NaN means set as current value.
 * 1. The property we should set when parsing this value.
 * 2. Indication if it's backwards or forward parsing, when set as number it's
 *    the value of extra chars that should be split off.
 * 3. Inherit from location if non existing in the parser.
 * 4. `toLowerCase` the resulting value.
 */
var rules = [
  ['#', 'hash'],                        // Extract from the back.
  ['?', 'query'],                       // Extract from the back.
  function sanitize(address) {          // Sanitize what is left of the address
    return address.replace('\\', '/');
  },
  ['/', 'pathname'],                    // Extract from the back.
  ['@', 'auth', 1],                     // Extract from the front.
  [NaN, 'host', undefined, 1, 1],       // Set left over value.
  [/:(\d+)$/, 'port', undefined, 1],    // RegExp the back.
  [NaN, 'hostname', undefined, 1, 1]    // Set left over.
];

/**
 * These properties should not be copied or inherited from. This is only needed
 * for all non blob URL's as a blob URL does not include a hash, only the
 * origin.
 *
 * @type {Object}
 * @private
 */
var ignore = { hash: 1, query: 1 };

/**
 * The location object differs when your code is loaded through a normal page,
 * Worker or through a worker using a blob. And with the blobble begins the
 * trouble as the location object will contain the URL of the blob, not the
 * location of the page where our code is loaded in. The actual origin is
 * encoded in the `pathname` so we can thankfully generate a good "default"
 * location from it so we can generate proper relative URL's again.
 *
 * @param {Object|String} loc Optional default location object.
 * @returns {Object} lolcation object.
 * @public
 */
function lolcation(loc) {
  var globalVar;

  if (typeof window !== 'undefined') globalVar = window;
  else if (typeof global !== 'undefined') globalVar = global;
  else if (typeof self !== 'undefined') globalVar = self;
  else globalVar = {};

  var location = globalVar.location || {};
  loc = loc || location;

  var finaldestination = {}
    , type = typeof loc
    , key;

  if ('blob:' === loc.protocol) {
    finaldestination = new Url(unescape(loc.pathname), {});
  } else if ('string' === type) {
    finaldestination = new Url(loc, {});
    for (key in ignore) delete finaldestination[key];
  } else if ('object' === type) {
    for (key in loc) {
      if (key in ignore) continue;
      finaldestination[key] = loc[key];
    }

    if (finaldestination.slashes === undefined) {
      finaldestination.slashes = slashes.test(loc.href);
    }
  }

  return finaldestination;
}

/**
 * @typedef ProtocolExtract
 * @type Object
 * @property {String} protocol Protocol matched in the URL, in lowercase.
 * @property {Boolean} slashes `true` if protocol is followed by "//", else `false`.
 * @property {String} rest Rest of the URL that is not part of the protocol.
 */

/**
 * Extract protocol information from a URL with/without double slash ("//").
 *
 * @param {String} address URL we want to extract from.
 * @return {ProtocolExtract} Extracted information.
 * @private
 */
function extractProtocol(address) {
  var match = protocolre.exec(address);

  return {
    protocol: match[1] ? match[1].toLowerCase() : '',
    slashes: !!match[2],
    rest: match[3]
  };
}

/**
 * Resolve a relative URL pathname against a base URL pathname.
 *
 * @param {String} relative Pathname of the relative URL.
 * @param {String} base Pathname of the base URL.
 * @return {String} Resolved pathname.
 * @private
 */
function resolve(relative, base) {
  var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))
    , i = path.length
    , last = path[i - 1]
    , unshift = false
    , up = 0;

  while (i--) {
    if (path[i] === '.') {
      path.splice(i, 1);
    } else if (path[i] === '..') {
      path.splice(i, 1);
      up++;
    } else if (up) {
      if (i === 0) unshift = true;
      path.splice(i, 1);
      up--;
    }
  }

  if (unshift) path.unshift('');
  if (last === '.' || last === '..') path.push('');

  return path.join('/');
}

/**
 * The actual URL instance. Instead of returning an object we've opted-in to
 * create an actual constructor as it's much more memory efficient and
 * faster and it pleases my OCD.
 *
 * It is worth noting that we should not use `URL` as class name to prevent
 * clashes with the global URL instance that got introduced in browsers.
 *
 * @constructor
 * @param {String} address URL we want to parse.
 * @param {Object|String} [location] Location defaults for relative paths.
 * @param {Boolean|Function} [parser] Parser for the query string.
 * @private
 */
function Url(address, location, parser) {
  if (!(this instanceof Url)) {
    return new Url(address, location, parser);
  }

  var relative, extracted, parse, instruction, index, key
    , instructions = rules.slice()
    , type = typeof location
    , url = this
    , i = 0;

  //
  // The following if statements allows this module two have compatibility with
  // 2 different API:
  //
  // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments
  //    where the boolean indicates that the query string should also be parsed.
  //
  // 2. The `URL` interface of the browser which accepts a URL, object as
  //    arguments. The supplied object will be used as default values / fall-back
  //    for relative paths.
  //
  if ('object' !== type && 'string' !== type) {
    parser = location;
    location = null;
  }

  if (parser && 'function' !== typeof parser) parser = qs.parse;

  location = lolcation(location);

  //
  // Extract protocol information before running the instructions.
  //
  extracted = extractProtocol(address || '');
  relative = !extracted.protocol && !extracted.slashes;
  url.slashes = extracted.slashes || relative && location.slashes;
  url.protocol = extracted.protocol || location.protocol || '';
  address = extracted.rest;

  //
  // When the authority component is absent the URL starts with a path
  // component.
  //
  if (!extracted.slashes) instructions[3] = [/(.*)/, 'pathname'];

  for (; i < instructions.length; i++) {
    instruction = instructions[i];

    if (typeof instruction === 'function') {
      address = instruction(address);
      continue;
    }

    parse = instruction[0];
    key = instruction[1];

    if (parse !== parse) {
      url[key] = address;
    } else if ('string' === typeof parse) {
      if (~(index = address.indexOf(parse))) {
        if ('number' === typeof instruction[2]) {
          url[key] = address.slice(0, index);
          address = address.slice(index + instruction[2]);
        } else {
          url[key] = address.slice(index);
          address = address.slice(0, index);
        }
      }
    } else if ((index = parse.exec(address))) {
      url[key] = index[1];
      address = address.slice(0, index.index);
    }

    url[key] = url[key] || (
      relative && instruction[3] ? location[key] || '' : ''
    );

    //
    // Hostname, host and protocol should be lowercased so they can be used to
    // create a proper `origin`.
    //
    if (instruction[4]) url[key] = url[key].toLowerCase();
  }

  //
  // Also parse the supplied query string in to an object. If we're supplied
  // with a custom parser as function use that instead of the default build-in
  // parser.
  //
  if (parser) url.query = parser(url.query);

  //
  // If the URL is relative, resolve the pathname against the base URL.
  //
  if (
      relative
    && location.slashes
    && url.pathname.charAt(0) !== '/'
    && (url.pathname !== '' || location.pathname !== '')
  ) {
    url.pathname = resolve(url.pathname, location.pathname);
  }

  //
  // We should not add port numbers if they are already the default port number
  // for a given protocol. As the host also contains the port number we're going
  // override it with the hostname which contains no port number.
  //
  if (!required(url.port, url.protocol)) {
    url.host = url.hostname;
    url.port = '';
  }

  //
  // Parse down the `auth` for the username and password.
  //
  url.username = url.password = '';
  if (url.auth) {
    instruction = url.auth.split(':');
    url.username = instruction[0] || '';
    url.password = instruction[1] || '';
  }

  url.origin = url.protocol && url.host && url.protocol !== 'file:'
    ? url.protocol +'//'+ url.host
    : 'null';

  //
  // The href is just the compiled result.
  //
  url.href = url.toString();
}

/**
 * This is convenience method for changing properties in the URL instance to
 * insure that they all propagate correctly.
 *
 * @param {String} part          Property we need to adjust.
 * @param {Mixed} value          The newly assigned value.
 * @param {Boolean|Function} fn  When setting the query, it will be the function
 *                               used to parse the query.
 *                               When setting the protocol, double slash will be
 *                               removed from the final url if it is true.
 * @returns {URL} URL instance for chaining.
 * @public
 */
function set(part, value, fn) {
  var url = this;

  switch (part) {
    case 'query':
      if ('string' === typeof value && value.length) {
        value = (fn || qs.parse)(value);
      }

      url[part] = value;
      break;

    case 'port':
      url[part] = value;

      if (!required(value, url.protocol)) {
        url.host = url.hostname;
        url[part] = '';
      } else if (value) {
        url.host = url.hostname +':'+ value;
      }

      break;

    case 'hostname':
      url[part] = value;

      if (url.port) value += ':'+ url.port;
      url.host = value;
      break;

    case 'host':
      url[part] = value;

      if (/:\d+$/.test(value)) {
        value = value.split(':');
        url.port = value.pop();
        url.hostname = value.join(':');
      } else {
        url.hostname = value;
        url.port = '';
      }

      break;

    case 'protocol':
      url.protocol = value.toLowerCase();
      url.slashes = !fn;
      break;

    case 'pathname':
    case 'hash':
      if (value) {
        var char = part === 'pathname' ? '/' : '#';
        url[part] = value.charAt(0) !== char ? char + value : value;
      } else {
        url[part] = value;
      }
      break;

    default:
      url[part] = value;
  }

  for (var i = 0; i < rules.length; i++) {
    var ins = rules[i];

    if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();
  }

  url.origin = url.protocol && url.host && url.protocol !== 'file:'
    ? url.protocol +'//'+ url.host
    : 'null';

  url.href = url.toString();

  return url;
}

/**
 * Transform the properties back in to a valid and full URL string.
 *
 * @param {Function} stringify Optional query stringify function.
 * @returns {String} Compiled version of the URL.
 * @public
 */
function toString(stringify) {
  if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;

  var query
    , url = this
    , protocol = url.protocol;

  if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';

  var result = protocol + (url.slashes ? '//' : '');

  if (url.username) {
    result += url.username;
    if (url.password) result += ':'+ url.password;
    result += '@';
  }

  result += url.host + url.pathname;

  query = 'object' === typeof url.query ? stringify(url.query) : url.query;
  if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;

  if (url.hash) result += url.hash;

  return result;
}

Url.prototype = { set: set, toString: toString };

//
// Expose the URL parser and some additional properties that might be useful for
// others or testing.
//
Url.extractProtocol = extractProtocol;
Url.location = lolcation;
Url.qs = qs;

module.exports = Url;

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "GDhZ":
/*!*****************************************************!*\
  !*** ./node_modules/lodash/_baseMatchesProperty.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseIsEqual = __webpack_require__(/*! ./_baseIsEqual */ "wF/u"),
    get = __webpack_require__(/*! ./get */ "mwIZ"),
    hasIn = __webpack_require__(/*! ./hasIn */ "hgQt"),
    isKey = __webpack_require__(/*! ./_isKey */ "9ggG"),
    isStrictComparable = __webpack_require__(/*! ./_isStrictComparable */ "CMye"),
    matchesStrictComparable = __webpack_require__(/*! ./_matchesStrictComparable */ "IOzZ"),
    toKey = __webpack_require__(/*! ./_toKey */ "9Nap");

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
    COMPARE_UNORDERED_FLAG = 2;

/**
 * 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);
  };
}

module.exports = baseMatchesProperty;


/***/ }),

/***/ "GF7H":
/*!**************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/registry.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var Loggers = __webpack_require__(/*! ./lib/loggers */ "B+Rx");
var noop = __webpack_require__(/*! ./lib/noop */ "lKy8");
var pushUnique = __webpack_require__(/*! ./lib/push_unique */ "/nst");
var isPlainObject = __webpack_require__(/*! ./lib/is_plain_object */ "SWc2");
var ExtendModule = __webpack_require__(/*! ./lib/extend */ "dnr1");

var basePlotAttributes = __webpack_require__(/*! ./plots/attributes */ "2yMk");
var baseLayoutAttributes = __webpack_require__(/*! ./plots/layout_attributes */ "mfZb");

var extendFlat = ExtendModule.extendFlat;
var extendDeepAll = ExtendModule.extendDeepAll;

exports.modules = {};
exports.allCategories = {};
exports.allTypes = [];
exports.subplotsRegistry = {};
exports.transformsRegistry = {};
exports.componentsRegistry = {};
exports.layoutArrayContainers = [];
exports.layoutArrayRegexes = [];
exports.traceLayoutAttributes = {};
exports.localeRegistry = {};
exports.apiMethodRegistry = {};
exports.collectableSubplotTypes = null;

/**
 * Top-level register routine, exported as Plotly.register
 *
 * @param {object array or array of objects} _modules :
 *  module object or list of module object to register.
 *
 *  A valid `moduleType: 'trace'` module has fields:
 *  - name {string} : the trace type
 *  - categories {array} : categories associated with this trace type,
 *                         tested with Register.traceIs()
 *  - meta {object} : meta info (mostly for plot-schema)
 *
 *  A valid `moduleType: 'locale'` module has fields:
 *  - name {string} : the locale name. Should be a 2-digit language string ('en', 'de')
 *                    optionally with a country/region code ('en-GB', 'de-CH'). If a country
 *                    code is used but the base language locale has not yet been supplied,
 *                    we will use this locale for the base as well.
 *  - dictionary {object} : the dictionary mapping input strings to localized strings
 *                          generally the keys should be the literal input strings, but
 *                          if default translations are provided you can use any string as a key.
 *  - format {object} : a `d3.locale` format specifier for this locale
 *                      any omitted keys we'll fall back on en-US.
 *
 *  A valid `moduleType: 'transform'` module has fields:
 *  - name {string} : transform name
 *  - transform {function} : default-level transform function
 *  - calcTransform {function} : calc-level transform function
 *  - attributes {object} : transform attributes declarations
 *  - supplyDefaults {function} : attributes default-supply function
 *
 *  A valid `moduleType: 'component'` module has fields:
 *  - name {string} : the component name, used it with Register.getComponentMethod()
 *                    to employ component method.
 *
 *  A valid `moduleType: 'apiMethod'` module has fields:
 *  - name {string} : the api method name.
 *  - fn {function} : the api method called with Register.call();
 *
 */
exports.register = function register(_modules) {
    exports.collectableSubplotTypes = null;

    if(!_modules) {
        throw new Error('No argument passed to Plotly.register.');
    } else if(_modules && !Array.isArray(_modules)) {
        _modules = [_modules];
    }

    for(var i = 0; i < _modules.length; i++) {
        var newModule = _modules[i];

        if(!newModule) {
            throw new Error('Invalid module was attempted to be registered!');
        }

        switch(newModule.moduleType) {
            case 'trace':
                registerTraceModule(newModule);
                break;
            case 'transform':
                registerTransformModule(newModule);
                break;
            case 'component':
                registerComponentModule(newModule);
                break;
            case 'locale':
                registerLocale(newModule);
                break;
            case 'apiMethod':
                var name = newModule.name;
                exports.apiMethodRegistry[name] = newModule.fn;
                break;
            default:
                throw new Error('Invalid module was attempted to be registered!');
        }
    }
};

/**
 * Get registered module using trace object or trace type
 *
 * @param {object||string} trace
 *  trace object with prop 'type' or trace type as a string
 * @return {object}
 *  module object corresponding to trace type
 */
exports.getModule = function(trace) {
    var _module = exports.modules[getTraceType(trace)];
    if(!_module) return false;
    return _module._module;
};

/**
 * Determine if this trace type is in a given category
 *
 * @param {object||string} traceType
 *  a trace (object) or trace type (string)
 * @param {string} category
 *  category in question
 * @return {boolean}
 */
exports.traceIs = function(traceType, category) {
    traceType = getTraceType(traceType);

    // old plot.ly workspace hack, nothing to see here
    if(traceType === 'various') return false;

    var _module = exports.modules[traceType];

    if(!_module) {
        if(traceType && traceType !== 'area') {
            Loggers.log('Unrecognized trace type ' + traceType + '.');
        }

        _module = exports.modules[basePlotAttributes.type.dflt];
    }

    return !!_module.categories[category];
};

/**
 * Determine if this trace has a transform of the given type and return
 * array of matching indices.
 *
 * @param {object} data
 *  a trace object (member of data or fullData)
 * @param {string} type
 *  type of trace to test
 * @return {array}
 *  array of matching indices. If none found, returns []
 */
exports.getTransformIndices = function(data, type) {
    var indices = [];
    var transforms = data.transforms || [];
    for(var i = 0; i < transforms.length; i++) {
        if(transforms[i].type === type) {
            indices.push(i);
        }
    }
    return indices;
};

/**
 * Determine if this trace has a transform of the given type
 *
 * @param {object} data
 *  a trace object (member of data or fullData)
 * @param {string} type
 *  type of trace to test
 * @return {boolean}
 */
exports.hasTransform = function(data, type) {
    var transforms = data.transforms || [];
    for(var i = 0; i < transforms.length; i++) {
        if(transforms[i].type === type) {
            return true;
        }
    }
    return false;
};

/**
 * Retrieve component module method. Falls back on noop if either the
 * module or the method is missing, so the result can always be safely called
 *
 * @param {string} name
 *  name of component (as declared in component module)
 * @param {string} method
 *  name of component module method
 * @return {function}
 */
exports.getComponentMethod = function(name, method) {
    var _module = exports.componentsRegistry[name];

    if(!_module) return noop;
    return _module[method] || noop;
};

/**
 * Call registered api method.
 *
 * @param {string} name : api method name
 * @param {...array} args : arguments passed to api method
 * @return {any} : returns api method output
 */
exports.call = function() {
    var name = arguments[0];
    var args = [].slice.call(arguments, 1);
    return exports.apiMethodRegistry[name].apply(null, args);
};

function registerTraceModule(_module) {
    var thisType = _module.name;
    var categoriesIn = _module.categories;
    var meta = _module.meta;

    if(exports.modules[thisType]) {
        Loggers.log('Type ' + thisType + ' already registered');
        return;
    }

    if(!exports.subplotsRegistry[_module.basePlotModule.name]) {
        registerSubplot(_module.basePlotModule);
    }

    var categoryObj = {};
    for(var i = 0; i < categoriesIn.length; i++) {
        categoryObj[categoriesIn[i]] = true;
        exports.allCategories[categoriesIn[i]] = true;
    }

    exports.modules[thisType] = {
        _module: _module,
        categories: categoryObj
    };

    if(meta && Object.keys(meta).length) {
        exports.modules[thisType].meta = meta;
    }

    exports.allTypes.push(thisType);

    for(var componentName in exports.componentsRegistry) {
        mergeComponentAttrsToTrace(componentName, thisType);
    }

    /*
     * Collect all trace layout attributes in one place for easier lookup later
     * but don't merge them into the base schema as it would confuse the docs
     * (at least after https://github.com/plotly/documentation/issues/202 gets done!)
     */
    if(_module.layoutAttributes) {
        extendFlat(exports.traceLayoutAttributes, _module.layoutAttributes);
    }
}

function registerSubplot(_module) {
    var plotType = _module.name;

    if(exports.subplotsRegistry[plotType]) {
        Loggers.log('Plot type ' + plotType + ' already registered.');
        return;
    }

    // relayout array handling will look for component module methods with this
    // name and won't find them because this is a subplot module... but that
    // should be fine, it will just fall back on redrawing the plot.
    findArrayRegexps(_module);

    // not sure what's best for the 'cartesian' type at this point
    exports.subplotsRegistry[plotType] = _module;

    for(var componentName in exports.componentsRegistry) {
        mergeComponentAttrsToSubplot(componentName, _module.name);
    }
}

function registerComponentModule(_module) {
    if(typeof _module.name !== 'string') {
        throw new Error('Component module *name* must be a string.');
    }

    var name = _module.name;
    exports.componentsRegistry[name] = _module;

    if(_module.layoutAttributes) {
        if(_module.layoutAttributes._isLinkedToArray) {
            pushUnique(exports.layoutArrayContainers, name);
        }
        findArrayRegexps(_module);
    }

    for(var traceType in exports.modules) {
        mergeComponentAttrsToTrace(name, traceType);
    }

    for(var subplotName in exports.subplotsRegistry) {
        mergeComponentAttrsToSubplot(name, subplotName);
    }

    for(var transformType in exports.transformsRegistry) {
        mergeComponentAttrsToTransform(name, transformType);
    }

    if(_module.schema && _module.schema.layout) {
        extendDeepAll(baseLayoutAttributes, _module.schema.layout);
    }
}

function registerTransformModule(_module) {
    if(typeof _module.name !== 'string') {
        throw new Error('Transform module *name* must be a string.');
    }

    var prefix = 'Transform module ' + _module.name;
    var hasTransform = typeof _module.transform === 'function';
    var hasCalcTransform = typeof _module.calcTransform === 'function';

    if(!hasTransform && !hasCalcTransform) {
        throw new Error(prefix + ' is missing a *transform* or *calcTransform* method.');
    }
    if(hasTransform && hasCalcTransform) {
        Loggers.log([
            prefix + ' has both a *transform* and *calcTransform* methods.',
            'Please note that all *transform* methods are executed',
            'before all *calcTransform* methods.'
        ].join(' '));
    }
    if(!isPlainObject(_module.attributes)) {
        Loggers.log(prefix + ' registered without an *attributes* object.');
    }
    if(typeof _module.supplyDefaults !== 'function') {
        Loggers.log(prefix + ' registered without a *supplyDefaults* method.');
    }

    exports.transformsRegistry[_module.name] = _module;

    for(var componentName in exports.componentsRegistry) {
        mergeComponentAttrsToTransform(componentName, _module.name);
    }
}

function registerLocale(_module) {
    var locale = _module.name;
    var baseLocale = locale.split('-')[0];

    var newDict = _module.dictionary;
    var newFormat = _module.format;
    var hasDict = newDict && Object.keys(newDict).length;
    var hasFormat = newFormat && Object.keys(newFormat).length;

    var locales = exports.localeRegistry;

    var localeObj = locales[locale];
    if(!localeObj) locales[locale] = localeObj = {};

    // Should we use this dict for the base locale?
    // In case we're overwriting a previous dict for this locale, check
    // whether the base matches the full locale dict now. If we're not
    // overwriting, locales[locale] is undefined so this just checks if
    // baseLocale already had a dict or not.
    // Same logic for dateFormats
    if(baseLocale !== locale) {
        var baseLocaleObj = locales[baseLocale];
        if(!baseLocaleObj) locales[baseLocale] = baseLocaleObj = {};

        if(hasDict && baseLocaleObj.dictionary === localeObj.dictionary) {
            baseLocaleObj.dictionary = newDict;
        }
        if(hasFormat && baseLocaleObj.format === localeObj.format) {
            baseLocaleObj.format = newFormat;
        }
    }

    if(hasDict) localeObj.dictionary = newDict;
    if(hasFormat) localeObj.format = newFormat;
}

function findArrayRegexps(_module) {
    if(_module.layoutAttributes) {
        var arrayAttrRegexps = _module.layoutAttributes._arrayAttrRegexps;
        if(arrayAttrRegexps) {
            for(var i = 0; i < arrayAttrRegexps.length; i++) {
                pushUnique(exports.layoutArrayRegexes, arrayAttrRegexps[i]);
            }
        }
    }
}

function mergeComponentAttrsToTrace(componentName, traceType) {
    var componentSchema = exports.componentsRegistry[componentName].schema;
    if(!componentSchema || !componentSchema.traces) return;

    var traceAttrs = componentSchema.traces[traceType];
    if(traceAttrs) {
        extendDeepAll(exports.modules[traceType]._module.attributes, traceAttrs);
    }
}

function mergeComponentAttrsToTransform(componentName, transformType) {
    var componentSchema = exports.componentsRegistry[componentName].schema;
    if(!componentSchema || !componentSchema.transforms) return;

    var transformAttrs = componentSchema.transforms[transformType];
    if(transformAttrs) {
        extendDeepAll(exports.transformsRegistry[transformType].attributes, transformAttrs);
    }
}

function mergeComponentAttrsToSubplot(componentName, subplotName) {
    var componentSchema = exports.componentsRegistry[componentName].schema;
    if(!componentSchema || !componentSchema.subplots) return;

    var subplotModule = exports.subplotsRegistry[subplotName];
    var subplotAttrs = subplotModule.layoutAttributes;
    var subplotAttr = subplotModule.attr === 'subplot' ? subplotModule.name : subplotModule.attr;
    if(Array.isArray(subplotAttr)) subplotAttr = subplotAttr[0];

    var componentLayoutAttrs = componentSchema.subplots[subplotAttr];
    if(subplotAttrs && componentLayoutAttrs) {
        extendDeepAll(subplotAttrs, componentLayoutAttrs);
    }
}

function getTraceType(traceType) {
    if(typeof traceType === 'object') traceType = traceType.type;
    return traceType;
}


/***/ }),

/***/ "GH25":
/*!**********************************!*\
  !*** ./node_modules/co/index.js ***!
  \**********************************/
/*! no static exports found */
/***/ (function(module, exports) {


/**
 * slice() reference.
 */

var slice = Array.prototype.slice;

/**
 * Expose `co`.
 */

module.exports = co['default'] = co.co = co;

/**
 * Wrap the given generator `fn` into a
 * function that returns a promise.
 * This is a separate function so that
 * every `co()` call doesn't create a new,
 * unnecessary closure.
 *
 * @param {GeneratorFunction} fn
 * @return {Function}
 * @api public
 */

co.wrap = function (fn) {
  createPromise.__generatorFunction__ = fn;
  return createPromise;
  function createPromise() {
    return co.call(this, fn.apply(this, arguments));
  }
};

/**
 * Execute the generator function or a generator
 * and return a promise.
 *
 * @param {Function} fn
 * @return {Promise}
 * @api public
 */

function co(gen) {
  var ctx = this;
  var args = slice.call(arguments, 1)

  // we wrap everything in a promise to avoid promise chaining,
  // which leads to memory leak errors.
  // see https://github.com/tj/co/issues/180
  return new Promise(function(resolve, reject) {
    if (typeof gen === 'function') gen = gen.apply(ctx, args);
    if (!gen || typeof gen.next !== 'function') return resolve(gen);

    onFulfilled();

    /**
     * @param {Mixed} res
     * @return {Promise}
     * @api private
     */

    function onFulfilled(res) {
      var ret;
      try {
        ret = gen.next(res);
      } catch (e) {
        return reject(e);
      }
      next(ret);
    }

    /**
     * @param {Error} err
     * @return {Promise}
     * @api private
     */

    function onRejected(err) {
      var ret;
      try {
        ret = gen.throw(err);
      } catch (e) {
        return reject(e);
      }
      next(ret);
    }

    /**
     * Get the next value in the generator,
     * return a promise.
     *
     * @param {Object} ret
     * @return {Promise}
     * @api private
     */

    function next(ret) {
      if (ret.done) return resolve(ret.value);
      var value = toPromise.call(ctx, ret.value);
      if (value && isPromise(value)) return value.then(onFulfilled, onRejected);
      return onRejected(new TypeError('You may only yield a function, promise, generator, array, or object, '
        + 'but the following object was passed: "' + String(ret.value) + '"'));
    }
  });
}

/**
 * Convert a `yield`ed value into a promise.
 *
 * @param {Mixed} obj
 * @return {Promise}
 * @api private
 */

function toPromise(obj) {
  if (!obj) return obj;
  if (isPromise(obj)) return obj;
  if (isGeneratorFunction(obj) || isGenerator(obj)) return co.call(this, obj);
  if ('function' == typeof obj) return thunkToPromise.call(this, obj);
  if (Array.isArray(obj)) return arrayToPromise.call(this, obj);
  if (isObject(obj)) return objectToPromise.call(this, obj);
  return obj;
}

/**
 * Convert a thunk to a promise.
 *
 * @param {Function}
 * @return {Promise}
 * @api private
 */

function thunkToPromise(fn) {
  var ctx = this;
  return new Promise(function (resolve, reject) {
    fn.call(ctx, function (err, res) {
      if (err) return reject(err);
      if (arguments.length > 2) res = slice.call(arguments, 1);
      resolve(res);
    });
  });
}

/**
 * Convert an array of "yieldables" to a promise.
 * Uses `Promise.all()` internally.
 *
 * @param {Array} obj
 * @return {Promise}
 * @api private
 */

function arrayToPromise(obj) {
  return Promise.all(obj.map(toPromise, this));
}

/**
 * Convert an object of "yieldables" to a promise.
 * Uses `Promise.all()` internally.
 *
 * @param {Object} obj
 * @return {Promise}
 * @api private
 */

function objectToPromise(obj){
  var results = new obj.constructor();
  var keys = Object.keys(obj);
  var promises = [];
  for (var i = 0; i < keys.length; i++) {
    var key = keys[i];
    var promise = toPromise.call(this, obj[key]);
    if (promise && isPromise(promise)) defer(promise, key);
    else results[key] = obj[key];
  }
  return Promise.all(promises).then(function () {
    return results;
  });

  function defer(promise, key) {
    // predefine the key in the result
    results[key] = undefined;
    promises.push(promise.then(function (res) {
      results[key] = res;
    }));
  }
}

/**
 * Check if `obj` is a promise.
 *
 * @param {Object} obj
 * @return {Boolean}
 * @api private
 */

function isPromise(obj) {
  return 'function' == typeof obj.then;
}

/**
 * Check if `obj` is a generator.
 *
 * @param {Mixed} obj
 * @return {Boolean}
 * @api private
 */

function isGenerator(obj) {
  return 'function' == typeof obj.next && 'function' == typeof obj.throw;
}

/**
 * Check if `obj` is a generator function.
 *
 * @param {Mixed} obj
 * @return {Boolean}
 * @api private
 */
function isGeneratorFunction(obj) {
  var constructor = obj.constructor;
  if (!constructor) return false;
  if ('GeneratorFunction' === constructor.name || 'GeneratorFunction' === constructor.displayName) return true;
  return isGenerator(constructor.prototype);
}

/**
 * Check for plain object.
 *
 * @param {Mixed} val
 * @return {Boolean}
 * @api private
 */

function isObject(val) {
  return Object == val.constructor;
}


/***/ }),

/***/ "GIBT":
/*!**********************************************!*\
  !*** ./node_modules/dom-serializer/index.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/*
  Module dependencies
*/
var ElementType = __webpack_require__(/*! domelementtype */ "TR4g");
var entities = __webpack_require__(/*! entities */ "4oK2");

var unencodedElements = {
  __proto__: null,
  style: true,
  script: true,
  xmp: true,
  iframe: true,
  noembed: true,
  noframes: true,
  plaintext: true,
  noscript: true
};

/*
  Format attributes
*/
function formatAttrs(attributes, opts) {
  if (!attributes) return;

  var output = '',
      value;

  // Loop through the attributes
  for (var key in attributes) {
    value = attributes[key];
    if (output) {
      output += ' ';
    }

    output += key;
    if ((value !== null && value !== '') || opts.xmlMode) {
        output += '="' + (opts.decodeEntities ? entities.encodeXML(value) : value) + '"';
    }
  }

  return output;
}

/*
  Self-enclosing tags (stolen from node-htmlparser)
*/
var singleTag = {
  __proto__: null,
  area: true,
  base: true,
  basefont: true,
  br: true,
  col: true,
  command: true,
  embed: true,
  frame: true,
  hr: true,
  img: true,
  input: true,
  isindex: true,
  keygen: true,
  link: true,
  meta: true,
  param: true,
  source: true,
  track: true,
  wbr: true,
};


var render = module.exports = function(dom, opts) {
  if (!Array.isArray(dom) && !dom.cheerio) dom = [dom];
  opts = opts || {};

  var output = '';

  for(var i = 0; i < dom.length; i++){
    var elem = dom[i];

    if (elem.type === 'root')
      output += render(elem.children, opts);
    else if (ElementType.isTag(elem))
      output += renderTag(elem, opts);
    else if (elem.type === ElementType.Directive)
      output += renderDirective(elem);
    else if (elem.type === ElementType.Comment)
      output += renderComment(elem);
    else if (elem.type === ElementType.CDATA)
      output += renderCdata(elem);
    else
      output += renderText(elem, opts);
  }

  return output;
};

function renderTag(elem, opts) {
  // Handle SVG
  if (elem.name === "svg") opts = {decodeEntities: opts.decodeEntities, xmlMode: true};

  var tag = '<' + elem.name,
      attribs = formatAttrs(elem.attribs, opts);

  if (attribs) {
    tag += ' ' + attribs;
  }

  if (
    opts.xmlMode
    && (!elem.children || elem.children.length === 0)
  ) {
    tag += '/>';
  } else {
    tag += '>';
    if (elem.children) {
      tag += render(elem.children, opts);
    }

    if (!singleTag[elem.name] || opts.xmlMode) {
      tag += '</' + elem.name + '>';
    }
  }

  return tag;
}

function renderDirective(elem) {
  return '<' + elem.data + '>';
}

function renderText(elem, opts) {
  var data = elem.data || '';

  // if entities weren't decoded, no need to encode them back
  if (opts.decodeEntities && !(elem.parent && elem.parent.name in unencodedElements)) {
    data = entities.encodeXML(data);
  }

  return data;
}

function renderCdata(elem) {
  return '<![CDATA[' + elem.children[0].data + ']]>';
}

function renderComment(elem) {
  return '<!--' + elem.data + '-->';
}


/***/ }),

/***/ "GMnZ":
/*!************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotTimeSeriesIcon.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotTimeSeriesIcon = function PlotTimeSeriesIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M1.938 16.188c.125-.438.25-.938.438-1.438.5-1.5 1.063-3 1.75-4.438 1.75-3.875 3.625-6.188 5.375-6.188 1.625 0 3.063 1.625 6 6.25 3.25 5.125 4.75 6.813 7 6.813 2.438 0 4.563-2.563 6.5-6.875.625-1.438 1.25-3 1.75-4.563.188-.5.313-1 .5-1.438.063-.313.125-.5.125-.625l-1.125-.313c-.063.125-.063.313-.188.563-.125.438-.25.938-.438 1.438-.5 1.563-1.063 3.063-1.75 4.438C26.125 13.687 24.25 16 22.5 16c-1.625 0-3.063-1.563-6-6.25-3.25-5.125-4.75-6.813-7-6.813-2.438 0-4.563 2.625-6.5 6.875-.625 1.438-1.25 3-1.75 4.563-.188.563-.313 1.063-.5 1.5-.063.25-.125.438-.125.563l1.125.313c.063-.125.063-.313.188-.563zM.75 4.313c.188.438.313.938.5 1.438.5 1.563 1.125 3.125 1.75 4.563 1.938 4.313 4.063 6.875 6.5 6.875 2.25 0 3.75-1.688 7-6.813 2.938-4.625 4.375-6.25 6-6.25 1.75 0 3.625 2.313 5.375 6.188.688 1.438 1.25 2.938 1.75 4.438.188.5.313 1 .438 1.438.125.25.125.438.188.563l1.125-.313c0-.125-.063-.313-.125-.563-.188-.438-.313-.938-.5-1.5-.5-1.563-1.125-3.125-1.75-4.563-1.938-4.25-4.063-6.875-6.5-6.875-2.25 0-3.75 1.688-7 6.813-2.938 4.688-4.375 6.25-6 6.25-1.75 0-3.625-2.313-5.375-6.188-.688-1.375-1.25-2.875-1.75-4.438-.188-.5-.313-1-.438-1.438-.125-.25-.125-.438-.188-.563l-1.125.313c0 .125.063.313.125.625zM0 23.688h7.125v5.938H0zm22.5 0H32v5.938h-9.5zm-15.375 0H22.5v1.188H7.125zm0 4.75H22.5v1.188H7.125z' })
    );
};

exports.default = PlotTimeSeriesIcon;

/***/ }),

/***/ "GNWD":
/*!**************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/font-awesome/css/font-awesome.min.css ***!
  \**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var escape = __webpack_require__(/*! ../../css-loader/lib/url/escape.js */ "sEG9");
exports = module.exports = __webpack_require__(/*! ../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*!\n *  Font Awesome 4.7.0 by @davegandy - http://fontawesome.io - @fontawesome\n *  License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License)\n */@font-face{font-family:'FontAwesome';src:url(" + escape(__webpack_require__(/*! ../fonts/fontawesome-webfont.eot?v=4.7.0 */ "/MSg")) + ");src:url(" + escape(__webpack_require__(/*! ../fonts/fontawesome-webfont.eot */ "xYL2")) + "?#iefix&v=4.7.0) format('embedded-opentype'),url(" + escape(__webpack_require__(/*! ../fonts/fontawesome-webfont.woff2?v=4.7.0 */ "82c5")) + ") format('woff2'),url(" + escape(__webpack_require__(/*! ../fonts/fontawesome-webfont.woff?v=4.7.0 */ "W/R5")) + ") format('woff'),url(" + escape(__webpack_require__(/*! ../fonts/fontawesome-webfont.ttf?v=4.7.0 */ "im7S")) + ") format('truetype'),url(" + escape(__webpack_require__(/*! ../fonts/fontawesome-webfont.svg?v=4.7.0 */ "NZGY")) + "#fontawesomeregular) format('svg');font-weight:normal;font-style:normal}.fa{display:inline-block;font:normal normal normal 14px/1 FontAwesome;font-size:inherit;text-rendering:auto;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.fa-lg{font-size:1.33333333em;line-height:.75em;vertical-align:-15%}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-fw{width:1.28571429em;text-align:center}.fa-ul{padding-left:0;margin-left:2.14285714em;list-style-type:none}.fa-ul>li{position:relative}.fa-li{position:absolute;left:-2.14285714em;width:2.14285714em;top:.14285714em;text-align:center}.fa-li.fa-lg{left:-1.85714286em}.fa-border{padding:.2em .25em .15em;border:solid .08em #eee;border-radius:.1em}.fa-pull-left{float:left}.fa-pull-right{float:right}.fa.fa-pull-left{margin-right:.3em}.fa.fa-pull-right{margin-left:.3em}.pull-right{float:right}.pull-left{float:left}.fa.pull-left{margin-right:.3em}.fa.pull-right{margin-left:.3em}.fa-spin{-webkit-animation:fa-spin 2s infinite linear;animation:fa-spin 2s infinite linear}.fa-pulse{-webkit-animation:fa-spin 1s infinite steps(8);animation:fa-spin 1s infinite steps(8)}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}.fa-rotate-90{-ms-filter:\"progid:DXImageTransform.Microsoft.BasicImage(rotation=1)\";-webkit-transform:rotate(90deg);-ms-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{-ms-filter:\"progid:DXImageTransform.Microsoft.BasicImage(rotation=2)\";-webkit-transform:rotate(180deg);-ms-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{-ms-filter:\"progid:DXImageTransform.Microsoft.BasicImage(rotation=3)\";-webkit-transform:rotate(270deg);-ms-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{-ms-filter:\"progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1)\";-webkit-transform:scale(-1, 1);-ms-transform:scale(-1, 1);transform:scale(-1, 1)}.fa-flip-vertical{-ms-filter:\"progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)\";-webkit-transform:scale(1, -1);-ms-transform:scale(1, -1);transform:scale(1, -1)}:root .fa-rotate-90,:root .fa-rotate-180,:root .fa-rotate-270,:root .fa-flip-horizontal,:root .fa-flip-vertical{filter:none}.fa-stack{position:relative;display:inline-block;width:2em;height:2em;line-height:2em;vertical-align:middle}.fa-stack-1x,.fa-stack-2x{position:absolute;left:0;width:100%;text-align:center}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:#fff}.fa-glass:before{content:\"\\F000\"}.fa-music:before{content:\"\\F001\"}.fa-search:before{content:\"\\F002\"}.fa-envelope-o:before{content:\"\\F003\"}.fa-heart:before{content:\"\\F004\"}.fa-star:before{content:\"\\F005\"}.fa-star-o:before{content:\"\\F006\"}.fa-user:before{content:\"\\F007\"}.fa-film:before{content:\"\\F008\"}.fa-th-large:before{content:\"\\F009\"}.fa-th:before{content:\"\\F00A\"}.fa-th-list:before{content:\"\\F00B\"}.fa-check:before{content:\"\\F00C\"}.fa-remove:before,.fa-close:before,.fa-times:before{content:\"\\F00D\"}.fa-search-plus:before{content:\"\\F00E\"}.fa-search-minus:before{content:\"\\F010\"}.fa-power-off:before{content:\"\\F011\"}.fa-signal:before{content:\"\\F012\"}.fa-gear:before,.fa-cog:before{content:\"\\F013\"}.fa-trash-o:before{content:\"\\F014\"}.fa-home:before{content:\"\\F015\"}.fa-file-o:before{content:\"\\F016\"}.fa-clock-o:before{content:\"\\F017\"}.fa-road:before{content:\"\\F018\"}.fa-download:before{content:\"\\F019\"}.fa-arrow-circle-o-down:before{content:\"\\F01A\"}.fa-arrow-circle-o-up:before{content:\"\\F01B\"}.fa-inbox:before{content:\"\\F01C\"}.fa-play-circle-o:before{content:\"\\F01D\"}.fa-rotate-right:before,.fa-repeat:before{content:\"\\F01E\"}.fa-refresh:before{content:\"\\F021\"}.fa-list-alt:before{content:\"\\F022\"}.fa-lock:before{content:\"\\F023\"}.fa-flag:before{content:\"\\F024\"}.fa-headphones:before{content:\"\\F025\"}.fa-volume-off:before{content:\"\\F026\"}.fa-volume-down:before{content:\"\\F027\"}.fa-volume-up:before{content:\"\\F028\"}.fa-qrcode:before{content:\"\\F029\"}.fa-barcode:before{content:\"\\F02A\"}.fa-tag:before{content:\"\\F02B\"}.fa-tags:before{content:\"\\F02C\"}.fa-book:before{content:\"\\F02D\"}.fa-bookmark:before{content:\"\\F02E\"}.fa-print:before{content:\"\\F02F\"}.fa-camera:before{content:\"\\F030\"}.fa-font:before{content:\"\\F031\"}.fa-bold:before{content:\"\\F032\"}.fa-italic:before{content:\"\\F033\"}.fa-text-height:before{content:\"\\F034\"}.fa-text-width:before{content:\"\\F035\"}.fa-align-left:before{content:\"\\F036\"}.fa-align-center:before{content:\"\\F037\"}.fa-align-right:before{content:\"\\F038\"}.fa-align-justify:before{content:\"\\F039\"}.fa-list:before{content:\"\\F03A\"}.fa-dedent:before,.fa-outdent:before{content:\"\\F03B\"}.fa-indent:before{content:\"\\F03C\"}.fa-video-camera:before{content:\"\\F03D\"}.fa-photo:before,.fa-image:before,.fa-picture-o:before{content:\"\\F03E\"}.fa-pencil:before{content:\"\\F040\"}.fa-map-marker:before{content:\"\\F041\"}.fa-adjust:before{content:\"\\F042\"}.fa-tint:before{content:\"\\F043\"}.fa-edit:before,.fa-pencil-square-o:before{content:\"\\F044\"}.fa-share-square-o:before{content:\"\\F045\"}.fa-check-square-o:before{content:\"\\F046\"}.fa-arrows:before{content:\"\\F047\"}.fa-step-backward:before{content:\"\\F048\"}.fa-fast-backward:before{content:\"\\F049\"}.fa-backward:before{content:\"\\F04A\"}.fa-play:before{content:\"\\F04B\"}.fa-pause:before{content:\"\\F04C\"}.fa-stop:before{content:\"\\F04D\"}.fa-forward:before{content:\"\\F04E\"}.fa-fast-forward:before{content:\"\\F050\"}.fa-step-forward:before{content:\"\\F051\"}.fa-eject:before{content:\"\\F052\"}.fa-chevron-left:before{content:\"\\F053\"}.fa-chevron-right:before{content:\"\\F054\"}.fa-plus-circle:before{content:\"\\F055\"}.fa-minus-circle:before{content:\"\\F056\"}.fa-times-circle:before{content:\"\\F057\"}.fa-check-circle:before{content:\"\\F058\"}.fa-question-circle:before{content:\"\\F059\"}.fa-info-circle:before{content:\"\\F05A\"}.fa-crosshairs:before{content:\"\\F05B\"}.fa-times-circle-o:before{content:\"\\F05C\"}.fa-check-circle-o:before{content:\"\\F05D\"}.fa-ban:before{content:\"\\F05E\"}.fa-arrow-left:before{content:\"\\F060\"}.fa-arrow-right:before{content:\"\\F061\"}.fa-arrow-up:before{content:\"\\F062\"}.fa-arrow-down:before{content:\"\\F063\"}.fa-mail-forward:before,.fa-share:before{content:\"\\F064\"}.fa-expand:before{content:\"\\F065\"}.fa-compress:before{content:\"\\F066\"}.fa-plus:before{content:\"\\F067\"}.fa-minus:before{content:\"\\F068\"}.fa-asterisk:before{content:\"\\F069\"}.fa-exclamation-circle:before{content:\"\\F06A\"}.fa-gift:before{content:\"\\F06B\"}.fa-leaf:before{content:\"\\F06C\"}.fa-fire:before{content:\"\\F06D\"}.fa-eye:before{content:\"\\F06E\"}.fa-eye-slash:before{content:\"\\F070\"}.fa-warning:before,.fa-exclamation-triangle:before{content:\"\\F071\"}.fa-plane:before{content:\"\\F072\"}.fa-calendar:before{content:\"\\F073\"}.fa-random:before{content:\"\\F074\"}.fa-comment:before{content:\"\\F075\"}.fa-magnet:before{content:\"\\F076\"}.fa-chevron-up:before{content:\"\\F077\"}.fa-chevron-down:before{content:\"\\F078\"}.fa-retweet:before{content:\"\\F079\"}.fa-shopping-cart:before{content:\"\\F07A\"}.fa-folder:before{content:\"\\F07B\"}.fa-folder-open:before{content:\"\\F07C\"}.fa-arrows-v:before{content:\"\\F07D\"}.fa-arrows-h:before{content:\"\\F07E\"}.fa-bar-chart-o:before,.fa-bar-chart:before{content:\"\\F080\"}.fa-twitter-square:before{content:\"\\F081\"}.fa-facebook-square:before{content:\"\\F082\"}.fa-camera-retro:before{content:\"\\F083\"}.fa-key:before{content:\"\\F084\"}.fa-gears:before,.fa-cogs:before{content:\"\\F085\"}.fa-comments:before{content:\"\\F086\"}.fa-thumbs-o-up:before{content:\"\\F087\"}.fa-thumbs-o-down:before{content:\"\\F088\"}.fa-star-half:before{content:\"\\F089\"}.fa-heart-o:before{content:\"\\F08A\"}.fa-sign-out:before{content:\"\\F08B\"}.fa-linkedin-square:before{content:\"\\F08C\"}.fa-thumb-tack:before{content:\"\\F08D\"}.fa-external-link:before{content:\"\\F08E\"}.fa-sign-in:before{content:\"\\F090\"}.fa-trophy:before{content:\"\\F091\"}.fa-github-square:before{content:\"\\F092\"}.fa-upload:before{content:\"\\F093\"}.fa-lemon-o:before{content:\"\\F094\"}.fa-phone:before{content:\"\\F095\"}.fa-square-o:before{content:\"\\F096\"}.fa-bookmark-o:before{content:\"\\F097\"}.fa-phone-square:before{content:\"\\F098\"}.fa-twitter:before{content:\"\\F099\"}.fa-facebook-f:before,.fa-facebook:before{content:\"\\F09A\"}.fa-github:before{content:\"\\F09B\"}.fa-unlock:before{content:\"\\F09C\"}.fa-credit-card:before{content:\"\\F09D\"}.fa-feed:before,.fa-rss:before{content:\"\\F09E\"}.fa-hdd-o:before{content:\"\\F0A0\"}.fa-bullhorn:before{content:\"\\F0A1\"}.fa-bell:before{content:\"\\F0F3\"}.fa-certificate:before{content:\"\\F0A3\"}.fa-hand-o-right:before{content:\"\\F0A4\"}.fa-hand-o-left:before{content:\"\\F0A5\"}.fa-hand-o-up:before{content:\"\\F0A6\"}.fa-hand-o-down:before{content:\"\\F0A7\"}.fa-arrow-circle-left:before{content:\"\\F0A8\"}.fa-arrow-circle-right:before{content:\"\\F0A9\"}.fa-arrow-circle-up:before{content:\"\\F0AA\"}.fa-arrow-circle-down:before{content:\"\\F0AB\"}.fa-globe:before{content:\"\\F0AC\"}.fa-wrench:before{content:\"\\F0AD\"}.fa-tasks:before{content:\"\\F0AE\"}.fa-filter:before{content:\"\\F0B0\"}.fa-briefcase:before{content:\"\\F0B1\"}.fa-arrows-alt:before{content:\"\\F0B2\"}.fa-group:before,.fa-users:before{content:\"\\F0C0\"}.fa-chain:before,.fa-link:before{content:\"\\F0C1\"}.fa-cloud:before{content:\"\\F0C2\"}.fa-flask:before{content:\"\\F0C3\"}.fa-cut:before,.fa-scissors:before{content:\"\\F0C4\"}.fa-copy:before,.fa-files-o:before{content:\"\\F0C5\"}.fa-paperclip:before{content:\"\\F0C6\"}.fa-save:before,.fa-floppy-o:before{content:\"\\F0C7\"}.fa-square:before{content:\"\\F0C8\"}.fa-navicon:before,.fa-reorder:before,.fa-bars:before{content:\"\\F0C9\"}.fa-list-ul:before{content:\"\\F0CA\"}.fa-list-ol:before{content:\"\\F0CB\"}.fa-strikethrough:before{content:\"\\F0CC\"}.fa-underline:before{content:\"\\F0CD\"}.fa-table:before{content:\"\\F0CE\"}.fa-magic:before{content:\"\\F0D0\"}.fa-truck:before{content:\"\\F0D1\"}.fa-pinterest:before{content:\"\\F0D2\"}.fa-pinterest-square:before{content:\"\\F0D3\"}.fa-google-plus-square:before{content:\"\\F0D4\"}.fa-google-plus:before{content:\"\\F0D5\"}.fa-money:before{content:\"\\F0D6\"}.fa-caret-down:before{content:\"\\F0D7\"}.fa-caret-up:before{content:\"\\F0D8\"}.fa-caret-left:before{content:\"\\F0D9\"}.fa-caret-right:before{content:\"\\F0DA\"}.fa-columns:before{content:\"\\F0DB\"}.fa-unsorted:before,.fa-sort:before{content:\"\\F0DC\"}.fa-sort-down:before,.fa-sort-desc:before{content:\"\\F0DD\"}.fa-sort-up:before,.fa-sort-asc:before{content:\"\\F0DE\"}.fa-envelope:before{content:\"\\F0E0\"}.fa-linkedin:before{content:\"\\F0E1\"}.fa-rotate-left:before,.fa-undo:before{content:\"\\F0E2\"}.fa-legal:before,.fa-gavel:before{content:\"\\F0E3\"}.fa-dashboard:before,.fa-tachometer:before{content:\"\\F0E4\"}.fa-comment-o:before{content:\"\\F0E5\"}.fa-comments-o:before{content:\"\\F0E6\"}.fa-flash:before,.fa-bolt:before{content:\"\\F0E7\"}.fa-sitemap:before{content:\"\\F0E8\"}.fa-umbrella:before{content:\"\\F0E9\"}.fa-paste:before,.fa-clipboard:before{content:\"\\F0EA\"}.fa-lightbulb-o:before{content:\"\\F0EB\"}.fa-exchange:before{content:\"\\F0EC\"}.fa-cloud-download:before{content:\"\\F0ED\"}.fa-cloud-upload:before{content:\"\\F0EE\"}.fa-user-md:before{content:\"\\F0F0\"}.fa-stethoscope:before{content:\"\\F0F1\"}.fa-suitcase:before{content:\"\\F0F2\"}.fa-bell-o:before{content:\"\\F0A2\"}.fa-coffee:before{content:\"\\F0F4\"}.fa-cutlery:before{content:\"\\F0F5\"}.fa-file-text-o:before{content:\"\\F0F6\"}.fa-building-o:before{content:\"\\F0F7\"}.fa-hospital-o:before{content:\"\\F0F8\"}.fa-ambulance:before{content:\"\\F0F9\"}.fa-medkit:before{content:\"\\F0FA\"}.fa-fighter-jet:before{content:\"\\F0FB\"}.fa-beer:before{content:\"\\F0FC\"}.fa-h-square:before{content:\"\\F0FD\"}.fa-plus-square:before{content:\"\\F0FE\"}.fa-angle-double-left:before{content:\"\\F100\"}.fa-angle-double-right:before{content:\"\\F101\"}.fa-angle-double-up:before{content:\"\\F102\"}.fa-angle-double-down:before{content:\"\\F103\"}.fa-angle-left:before{content:\"\\F104\"}.fa-angle-right:before{content:\"\\F105\"}.fa-angle-up:before{content:\"\\F106\"}.fa-angle-down:before{content:\"\\F107\"}.fa-desktop:before{content:\"\\F108\"}.fa-laptop:before{content:\"\\F109\"}.fa-tablet:before{content:\"\\F10A\"}.fa-mobile-phone:before,.fa-mobile:before{content:\"\\F10B\"}.fa-circle-o:before{content:\"\\F10C\"}.fa-quote-left:before{content:\"\\F10D\"}.fa-quote-right:before{content:\"\\F10E\"}.fa-spinner:before{content:\"\\F110\"}.fa-circle:before{content:\"\\F111\"}.fa-mail-reply:before,.fa-reply:before{content:\"\\F112\"}.fa-github-alt:before{content:\"\\F113\"}.fa-folder-o:before{content:\"\\F114\"}.fa-folder-open-o:before{content:\"\\F115\"}.fa-smile-o:before{content:\"\\F118\"}.fa-frown-o:before{content:\"\\F119\"}.fa-meh-o:before{content:\"\\F11A\"}.fa-gamepad:before{content:\"\\F11B\"}.fa-keyboard-o:before{content:\"\\F11C\"}.fa-flag-o:before{content:\"\\F11D\"}.fa-flag-checkered:before{content:\"\\F11E\"}.fa-terminal:before{content:\"\\F120\"}.fa-code:before{content:\"\\F121\"}.fa-mail-reply-all:before,.fa-reply-all:before{content:\"\\F122\"}.fa-star-half-empty:before,.fa-star-half-full:before,.fa-star-half-o:before{content:\"\\F123\"}.fa-location-arrow:before{content:\"\\F124\"}.fa-crop:before{content:\"\\F125\"}.fa-code-fork:before{content:\"\\F126\"}.fa-unlink:before,.fa-chain-broken:before{content:\"\\F127\"}.fa-question:before{content:\"\\F128\"}.fa-info:before{content:\"\\F129\"}.fa-exclamation:before{content:\"\\F12A\"}.fa-superscript:before{content:\"\\F12B\"}.fa-subscript:before{content:\"\\F12C\"}.fa-eraser:before{content:\"\\F12D\"}.fa-puzzle-piece:before{content:\"\\F12E\"}.fa-microphone:before{content:\"\\F130\"}.fa-microphone-slash:before{content:\"\\F131\"}.fa-shield:before{content:\"\\F132\"}.fa-calendar-o:before{content:\"\\F133\"}.fa-fire-extinguisher:before{content:\"\\F134\"}.fa-rocket:before{content:\"\\F135\"}.fa-maxcdn:before{content:\"\\F136\"}.fa-chevron-circle-left:before{content:\"\\F137\"}.fa-chevron-circle-right:before{content:\"\\F138\"}.fa-chevron-circle-up:before{content:\"\\F139\"}.fa-chevron-circle-down:before{content:\"\\F13A\"}.fa-html5:before{content:\"\\F13B\"}.fa-css3:before{content:\"\\F13C\"}.fa-anchor:before{content:\"\\F13D\"}.fa-unlock-alt:before{content:\"\\F13E\"}.fa-bullseye:before{content:\"\\F140\"}.fa-ellipsis-h:before{content:\"\\F141\"}.fa-ellipsis-v:before{content:\"\\F142\"}.fa-rss-square:before{content:\"\\F143\"}.fa-play-circle:before{content:\"\\F144\"}.fa-ticket:before{content:\"\\F145\"}.fa-minus-square:before{content:\"\\F146\"}.fa-minus-square-o:before{content:\"\\F147\"}.fa-level-up:before{content:\"\\F148\"}.fa-level-down:before{content:\"\\F149\"}.fa-check-square:before{content:\"\\F14A\"}.fa-pencil-square:before{content:\"\\F14B\"}.fa-external-link-square:before{content:\"\\F14C\"}.fa-share-square:before{content:\"\\F14D\"}.fa-compass:before{content:\"\\F14E\"}.fa-toggle-down:before,.fa-caret-square-o-down:before{content:\"\\F150\"}.fa-toggle-up:before,.fa-caret-square-o-up:before{content:\"\\F151\"}.fa-toggle-right:before,.fa-caret-square-o-right:before{content:\"\\F152\"}.fa-euro:before,.fa-eur:before{content:\"\\F153\"}.fa-gbp:before{content:\"\\F154\"}.fa-dollar:before,.fa-usd:before{content:\"\\F155\"}.fa-rupee:before,.fa-inr:before{content:\"\\F156\"}.fa-cny:before,.fa-rmb:before,.fa-yen:before,.fa-jpy:before{content:\"\\F157\"}.fa-ruble:before,.fa-rouble:before,.fa-rub:before{content:\"\\F158\"}.fa-won:before,.fa-krw:before{content:\"\\F159\"}.fa-bitcoin:before,.fa-btc:before{content:\"\\F15A\"}.fa-file:before{content:\"\\F15B\"}.fa-file-text:before{content:\"\\F15C\"}.fa-sort-alpha-asc:before{content:\"\\F15D\"}.fa-sort-alpha-desc:before{content:\"\\F15E\"}.fa-sort-amount-asc:before{content:\"\\F160\"}.fa-sort-amount-desc:before{content:\"\\F161\"}.fa-sort-numeric-asc:before{content:\"\\F162\"}.fa-sort-numeric-desc:before{content:\"\\F163\"}.fa-thumbs-up:before{content:\"\\F164\"}.fa-thumbs-down:before{content:\"\\F165\"}.fa-youtube-square:before{content:\"\\F166\"}.fa-youtube:before{content:\"\\F167\"}.fa-xing:before{content:\"\\F168\"}.fa-xing-square:before{content:\"\\F169\"}.fa-youtube-play:before{content:\"\\F16A\"}.fa-dropbox:before{content:\"\\F16B\"}.fa-stack-overflow:before{content:\"\\F16C\"}.fa-instagram:before{content:\"\\F16D\"}.fa-flickr:before{content:\"\\F16E\"}.fa-adn:before{content:\"\\F170\"}.fa-bitbucket:before{content:\"\\F171\"}.fa-bitbucket-square:before{content:\"\\F172\"}.fa-tumblr:before{content:\"\\F173\"}.fa-tumblr-square:before{content:\"\\F174\"}.fa-long-arrow-down:before{content:\"\\F175\"}.fa-long-arrow-up:before{content:\"\\F176\"}.fa-long-arrow-left:before{content:\"\\F177\"}.fa-long-arrow-right:before{content:\"\\F178\"}.fa-apple:before{content:\"\\F179\"}.fa-windows:before{content:\"\\F17A\"}.fa-android:before{content:\"\\F17B\"}.fa-linux:before{content:\"\\F17C\"}.fa-dribbble:before{content:\"\\F17D\"}.fa-skype:before{content:\"\\F17E\"}.fa-foursquare:before{content:\"\\F180\"}.fa-trello:before{content:\"\\F181\"}.fa-female:before{content:\"\\F182\"}.fa-male:before{content:\"\\F183\"}.fa-gittip:before,.fa-gratipay:before{content:\"\\F184\"}.fa-sun-o:before{content:\"\\F185\"}.fa-moon-o:before{content:\"\\F186\"}.fa-archive:before{content:\"\\F187\"}.fa-bug:before{content:\"\\F188\"}.fa-vk:before{content:\"\\F189\"}.fa-weibo:before{content:\"\\F18A\"}.fa-renren:before{content:\"\\F18B\"}.fa-pagelines:before{content:\"\\F18C\"}.fa-stack-exchange:before{content:\"\\F18D\"}.fa-arrow-circle-o-right:before{content:\"\\F18E\"}.fa-arrow-circle-o-left:before{content:\"\\F190\"}.fa-toggle-left:before,.fa-caret-square-o-left:before{content:\"\\F191\"}.fa-dot-circle-o:before{content:\"\\F192\"}.fa-wheelchair:before{content:\"\\F193\"}.fa-vimeo-square:before{content:\"\\F194\"}.fa-turkish-lira:before,.fa-try:before{content:\"\\F195\"}.fa-plus-square-o:before{content:\"\\F196\"}.fa-space-shuttle:before{content:\"\\F197\"}.fa-slack:before{content:\"\\F198\"}.fa-envelope-square:before{content:\"\\F199\"}.fa-wordpress:before{content:\"\\F19A\"}.fa-openid:before{content:\"\\F19B\"}.fa-institution:before,.fa-bank:before,.fa-university:before{content:\"\\F19C\"}.fa-mortar-board:before,.fa-graduation-cap:before{content:\"\\F19D\"}.fa-yahoo:before{content:\"\\F19E\"}.fa-google:before{content:\"\\F1A0\"}.fa-reddit:before{content:\"\\F1A1\"}.fa-reddit-square:before{content:\"\\F1A2\"}.fa-stumbleupon-circle:before{content:\"\\F1A3\"}.fa-stumbleupon:before{content:\"\\F1A4\"}.fa-delicious:before{content:\"\\F1A5\"}.fa-digg:before{content:\"\\F1A6\"}.fa-pied-piper-pp:before{content:\"\\F1A7\"}.fa-pied-piper-alt:before{content:\"\\F1A8\"}.fa-drupal:before{content:\"\\F1A9\"}.fa-joomla:before{content:\"\\F1AA\"}.fa-language:before{content:\"\\F1AB\"}.fa-fax:before{content:\"\\F1AC\"}.fa-building:before{content:\"\\F1AD\"}.fa-child:before{content:\"\\F1AE\"}.fa-paw:before{content:\"\\F1B0\"}.fa-spoon:before{content:\"\\F1B1\"}.fa-cube:before{content:\"\\F1B2\"}.fa-cubes:before{content:\"\\F1B3\"}.fa-behance:before{content:\"\\F1B4\"}.fa-behance-square:before{content:\"\\F1B5\"}.fa-steam:before{content:\"\\F1B6\"}.fa-steam-square:before{content:\"\\F1B7\"}.fa-recycle:before{content:\"\\F1B8\"}.fa-automobile:before,.fa-car:before{content:\"\\F1B9\"}.fa-cab:before,.fa-taxi:before{content:\"\\F1BA\"}.fa-tree:before{content:\"\\F1BB\"}.fa-spotify:before{content:\"\\F1BC\"}.fa-deviantart:before{content:\"\\F1BD\"}.fa-soundcloud:before{content:\"\\F1BE\"}.fa-database:before{content:\"\\F1C0\"}.fa-file-pdf-o:before{content:\"\\F1C1\"}.fa-file-word-o:before{content:\"\\F1C2\"}.fa-file-excel-o:before{content:\"\\F1C3\"}.fa-file-powerpoint-o:before{content:\"\\F1C4\"}.fa-file-photo-o:before,.fa-file-picture-o:before,.fa-file-image-o:before{content:\"\\F1C5\"}.fa-file-zip-o:before,.fa-file-archive-o:before{content:\"\\F1C6\"}.fa-file-sound-o:before,.fa-file-audio-o:before{content:\"\\F1C7\"}.fa-file-movie-o:before,.fa-file-video-o:before{content:\"\\F1C8\"}.fa-file-code-o:before{content:\"\\F1C9\"}.fa-vine:before{content:\"\\F1CA\"}.fa-codepen:before{content:\"\\F1CB\"}.fa-jsfiddle:before{content:\"\\F1CC\"}.fa-life-bouy:before,.fa-life-buoy:before,.fa-life-saver:before,.fa-support:before,.fa-life-ring:before{content:\"\\F1CD\"}.fa-circle-o-notch:before{content:\"\\F1CE\"}.fa-ra:before,.fa-resistance:before,.fa-rebel:before{content:\"\\F1D0\"}.fa-ge:before,.fa-empire:before{content:\"\\F1D1\"}.fa-git-square:before{content:\"\\F1D2\"}.fa-git:before{content:\"\\F1D3\"}.fa-y-combinator-square:before,.fa-yc-square:before,.fa-hacker-news:before{content:\"\\F1D4\"}.fa-tencent-weibo:before{content:\"\\F1D5\"}.fa-qq:before{content:\"\\F1D6\"}.fa-wechat:before,.fa-weixin:before{content:\"\\F1D7\"}.fa-send:before,.fa-paper-plane:before{content:\"\\F1D8\"}.fa-send-o:before,.fa-paper-plane-o:before{content:\"\\F1D9\"}.fa-history:before{content:\"\\F1DA\"}.fa-circle-thin:before{content:\"\\F1DB\"}.fa-header:before{content:\"\\F1DC\"}.fa-paragraph:before{content:\"\\F1DD\"}.fa-sliders:before{content:\"\\F1DE\"}.fa-share-alt:before{content:\"\\F1E0\"}.fa-share-alt-square:before{content:\"\\F1E1\"}.fa-bomb:before{content:\"\\F1E2\"}.fa-soccer-ball-o:before,.fa-futbol-o:before{content:\"\\F1E3\"}.fa-tty:before{content:\"\\F1E4\"}.fa-binoculars:before{content:\"\\F1E5\"}.fa-plug:before{content:\"\\F1E6\"}.fa-slideshare:before{content:\"\\F1E7\"}.fa-twitch:before{content:\"\\F1E8\"}.fa-yelp:before{content:\"\\F1E9\"}.fa-newspaper-o:before{content:\"\\F1EA\"}.fa-wifi:before{content:\"\\F1EB\"}.fa-calculator:before{content:\"\\F1EC\"}.fa-paypal:before{content:\"\\F1ED\"}.fa-google-wallet:before{content:\"\\F1EE\"}.fa-cc-visa:before{content:\"\\F1F0\"}.fa-cc-mastercard:before{content:\"\\F1F1\"}.fa-cc-discover:before{content:\"\\F1F2\"}.fa-cc-amex:before{content:\"\\F1F3\"}.fa-cc-paypal:before{content:\"\\F1F4\"}.fa-cc-stripe:before{content:\"\\F1F5\"}.fa-bell-slash:before{content:\"\\F1F6\"}.fa-bell-slash-o:before{content:\"\\F1F7\"}.fa-trash:before{content:\"\\F1F8\"}.fa-copyright:before{content:\"\\F1F9\"}.fa-at:before{content:\"\\F1FA\"}.fa-eyedropper:before{content:\"\\F1FB\"}.fa-paint-brush:before{content:\"\\F1FC\"}.fa-birthday-cake:before{content:\"\\F1FD\"}.fa-area-chart:before{content:\"\\F1FE\"}.fa-pie-chart:before{content:\"\\F200\"}.fa-line-chart:before{content:\"\\F201\"}.fa-lastfm:before{content:\"\\F202\"}.fa-lastfm-square:before{content:\"\\F203\"}.fa-toggle-off:before{content:\"\\F204\"}.fa-toggle-on:before{content:\"\\F205\"}.fa-bicycle:before{content:\"\\F206\"}.fa-bus:before{content:\"\\F207\"}.fa-ioxhost:before{content:\"\\F208\"}.fa-angellist:before{content:\"\\F209\"}.fa-cc:before{content:\"\\F20A\"}.fa-shekel:before,.fa-sheqel:before,.fa-ils:before{content:\"\\F20B\"}.fa-meanpath:before{content:\"\\F20C\"}.fa-buysellads:before{content:\"\\F20D\"}.fa-connectdevelop:before{content:\"\\F20E\"}.fa-dashcube:before{content:\"\\F210\"}.fa-forumbee:before{content:\"\\F211\"}.fa-leanpub:before{content:\"\\F212\"}.fa-sellsy:before{content:\"\\F213\"}.fa-shirtsinbulk:before{content:\"\\F214\"}.fa-simplybuilt:before{content:\"\\F215\"}.fa-skyatlas:before{content:\"\\F216\"}.fa-cart-plus:before{content:\"\\F217\"}.fa-cart-arrow-down:before{content:\"\\F218\"}.fa-diamond:before{content:\"\\F219\"}.fa-ship:before{content:\"\\F21A\"}.fa-user-secret:before{content:\"\\F21B\"}.fa-motorcycle:before{content:\"\\F21C\"}.fa-street-view:before{content:\"\\F21D\"}.fa-heartbeat:before{content:\"\\F21E\"}.fa-venus:before{content:\"\\F221\"}.fa-mars:before{content:\"\\F222\"}.fa-mercury:before{content:\"\\F223\"}.fa-intersex:before,.fa-transgender:before{content:\"\\F224\"}.fa-transgender-alt:before{content:\"\\F225\"}.fa-venus-double:before{content:\"\\F226\"}.fa-mars-double:before{content:\"\\F227\"}.fa-venus-mars:before{content:\"\\F228\"}.fa-mars-stroke:before{content:\"\\F229\"}.fa-mars-stroke-v:before{content:\"\\F22A\"}.fa-mars-stroke-h:before{content:\"\\F22B\"}.fa-neuter:before{content:\"\\F22C\"}.fa-genderless:before{content:\"\\F22D\"}.fa-facebook-official:before{content:\"\\F230\"}.fa-pinterest-p:before{content:\"\\F231\"}.fa-whatsapp:before{content:\"\\F232\"}.fa-server:before{content:\"\\F233\"}.fa-user-plus:before{content:\"\\F234\"}.fa-user-times:before{content:\"\\F235\"}.fa-hotel:before,.fa-bed:before{content:\"\\F236\"}.fa-viacoin:before{content:\"\\F237\"}.fa-train:before{content:\"\\F238\"}.fa-subway:before{content:\"\\F239\"}.fa-medium:before{content:\"\\F23A\"}.fa-yc:before,.fa-y-combinator:before{content:\"\\F23B\"}.fa-optin-monster:before{content:\"\\F23C\"}.fa-opencart:before{content:\"\\F23D\"}.fa-expeditedssl:before{content:\"\\F23E\"}.fa-battery-4:before,.fa-battery:before,.fa-battery-full:before{content:\"\\F240\"}.fa-battery-3:before,.fa-battery-three-quarters:before{content:\"\\F241\"}.fa-battery-2:before,.fa-battery-half:before{content:\"\\F242\"}.fa-battery-1:before,.fa-battery-quarter:before{content:\"\\F243\"}.fa-battery-0:before,.fa-battery-empty:before{content:\"\\F244\"}.fa-mouse-pointer:before{content:\"\\F245\"}.fa-i-cursor:before{content:\"\\F246\"}.fa-object-group:before{content:\"\\F247\"}.fa-object-ungroup:before{content:\"\\F248\"}.fa-sticky-note:before{content:\"\\F249\"}.fa-sticky-note-o:before{content:\"\\F24A\"}.fa-cc-jcb:before{content:\"\\F24B\"}.fa-cc-diners-club:before{content:\"\\F24C\"}.fa-clone:before{content:\"\\F24D\"}.fa-balance-scale:before{content:\"\\F24E\"}.fa-hourglass-o:before{content:\"\\F250\"}.fa-hourglass-1:before,.fa-hourglass-start:before{content:\"\\F251\"}.fa-hourglass-2:before,.fa-hourglass-half:before{content:\"\\F252\"}.fa-hourglass-3:before,.fa-hourglass-end:before{content:\"\\F253\"}.fa-hourglass:before{content:\"\\F254\"}.fa-hand-grab-o:before,.fa-hand-rock-o:before{content:\"\\F255\"}.fa-hand-stop-o:before,.fa-hand-paper-o:before{content:\"\\F256\"}.fa-hand-scissors-o:before{content:\"\\F257\"}.fa-hand-lizard-o:before{content:\"\\F258\"}.fa-hand-spock-o:before{content:\"\\F259\"}.fa-hand-pointer-o:before{content:\"\\F25A\"}.fa-hand-peace-o:before{content:\"\\F25B\"}.fa-trademark:before{content:\"\\F25C\"}.fa-registered:before{content:\"\\F25D\"}.fa-creative-commons:before{content:\"\\F25E\"}.fa-gg:before{content:\"\\F260\"}.fa-gg-circle:before{content:\"\\F261\"}.fa-tripadvisor:before{content:\"\\F262\"}.fa-odnoklassniki:before{content:\"\\F263\"}.fa-odnoklassniki-square:before{content:\"\\F264\"}.fa-get-pocket:before{content:\"\\F265\"}.fa-wikipedia-w:before{content:\"\\F266\"}.fa-safari:before{content:\"\\F267\"}.fa-chrome:before{content:\"\\F268\"}.fa-firefox:before{content:\"\\F269\"}.fa-opera:before{content:\"\\F26A\"}.fa-internet-explorer:before{content:\"\\F26B\"}.fa-tv:before,.fa-television:before{content:\"\\F26C\"}.fa-contao:before{content:\"\\F26D\"}.fa-500px:before{content:\"\\F26E\"}.fa-amazon:before{content:\"\\F270\"}.fa-calendar-plus-o:before{content:\"\\F271\"}.fa-calendar-minus-o:before{content:\"\\F272\"}.fa-calendar-times-o:before{content:\"\\F273\"}.fa-calendar-check-o:before{content:\"\\F274\"}.fa-industry:before{content:\"\\F275\"}.fa-map-pin:before{content:\"\\F276\"}.fa-map-signs:before{content:\"\\F277\"}.fa-map-o:before{content:\"\\F278\"}.fa-map:before{content:\"\\F279\"}.fa-commenting:before{content:\"\\F27A\"}.fa-commenting-o:before{content:\"\\F27B\"}.fa-houzz:before{content:\"\\F27C\"}.fa-vimeo:before{content:\"\\F27D\"}.fa-black-tie:before{content:\"\\F27E\"}.fa-fonticons:before{content:\"\\F280\"}.fa-reddit-alien:before{content:\"\\F281\"}.fa-edge:before{content:\"\\F282\"}.fa-credit-card-alt:before{content:\"\\F283\"}.fa-codiepie:before{content:\"\\F284\"}.fa-modx:before{content:\"\\F285\"}.fa-fort-awesome:before{content:\"\\F286\"}.fa-usb:before{content:\"\\F287\"}.fa-product-hunt:before{content:\"\\F288\"}.fa-mixcloud:before{content:\"\\F289\"}.fa-scribd:before{content:\"\\F28A\"}.fa-pause-circle:before{content:\"\\F28B\"}.fa-pause-circle-o:before{content:\"\\F28C\"}.fa-stop-circle:before{content:\"\\F28D\"}.fa-stop-circle-o:before{content:\"\\F28E\"}.fa-shopping-bag:before{content:\"\\F290\"}.fa-shopping-basket:before{content:\"\\F291\"}.fa-hashtag:before{content:\"\\F292\"}.fa-bluetooth:before{content:\"\\F293\"}.fa-bluetooth-b:before{content:\"\\F294\"}.fa-percent:before{content:\"\\F295\"}.fa-gitlab:before{content:\"\\F296\"}.fa-wpbeginner:before{content:\"\\F297\"}.fa-wpforms:before{content:\"\\F298\"}.fa-envira:before{content:\"\\F299\"}.fa-universal-access:before{content:\"\\F29A\"}.fa-wheelchair-alt:before{content:\"\\F29B\"}.fa-question-circle-o:before{content:\"\\F29C\"}.fa-blind:before{content:\"\\F29D\"}.fa-audio-description:before{content:\"\\F29E\"}.fa-volume-control-phone:before{content:\"\\F2A0\"}.fa-braille:before{content:\"\\F2A1\"}.fa-assistive-listening-systems:before{content:\"\\F2A2\"}.fa-asl-interpreting:before,.fa-american-sign-language-interpreting:before{content:\"\\F2A3\"}.fa-deafness:before,.fa-hard-of-hearing:before,.fa-deaf:before{content:\"\\F2A4\"}.fa-glide:before{content:\"\\F2A5\"}.fa-glide-g:before{content:\"\\F2A6\"}.fa-signing:before,.fa-sign-language:before{content:\"\\F2A7\"}.fa-low-vision:before{content:\"\\F2A8\"}.fa-viadeo:before{content:\"\\F2A9\"}.fa-viadeo-square:before{content:\"\\F2AA\"}.fa-snapchat:before{content:\"\\F2AB\"}.fa-snapchat-ghost:before{content:\"\\F2AC\"}.fa-snapchat-square:before{content:\"\\F2AD\"}.fa-pied-piper:before{content:\"\\F2AE\"}.fa-first-order:before{content:\"\\F2B0\"}.fa-yoast:before{content:\"\\F2B1\"}.fa-themeisle:before{content:\"\\F2B2\"}.fa-google-plus-circle:before,.fa-google-plus-official:before{content:\"\\F2B3\"}.fa-fa:before,.fa-font-awesome:before{content:\"\\F2B4\"}.fa-handshake-o:before{content:\"\\F2B5\"}.fa-envelope-open:before{content:\"\\F2B6\"}.fa-envelope-open-o:before{content:\"\\F2B7\"}.fa-linode:before{content:\"\\F2B8\"}.fa-address-book:before{content:\"\\F2B9\"}.fa-address-book-o:before{content:\"\\F2BA\"}.fa-vcard:before,.fa-address-card:before{content:\"\\F2BB\"}.fa-vcard-o:before,.fa-address-card-o:before{content:\"\\F2BC\"}.fa-user-circle:before{content:\"\\F2BD\"}.fa-user-circle-o:before{content:\"\\F2BE\"}.fa-user-o:before{content:\"\\F2C0\"}.fa-id-badge:before{content:\"\\F2C1\"}.fa-drivers-license:before,.fa-id-card:before{content:\"\\F2C2\"}.fa-drivers-license-o:before,.fa-id-card-o:before{content:\"\\F2C3\"}.fa-quora:before{content:\"\\F2C4\"}.fa-free-code-camp:before{content:\"\\F2C5\"}.fa-telegram:before{content:\"\\F2C6\"}.fa-thermometer-4:before,.fa-thermometer:before,.fa-thermometer-full:before{content:\"\\F2C7\"}.fa-thermometer-3:before,.fa-thermometer-three-quarters:before{content:\"\\F2C8\"}.fa-thermometer-2:before,.fa-thermometer-half:before{content:\"\\F2C9\"}.fa-thermometer-1:before,.fa-thermometer-quarter:before{content:\"\\F2CA\"}.fa-thermometer-0:before,.fa-thermometer-empty:before{content:\"\\F2CB\"}.fa-shower:before{content:\"\\F2CC\"}.fa-bathtub:before,.fa-s15:before,.fa-bath:before{content:\"\\F2CD\"}.fa-podcast:before{content:\"\\F2CE\"}.fa-window-maximize:before{content:\"\\F2D0\"}.fa-window-minimize:before{content:\"\\F2D1\"}.fa-window-restore:before{content:\"\\F2D2\"}.fa-times-rectangle:before,.fa-window-close:before{content:\"\\F2D3\"}.fa-times-rectangle-o:before,.fa-window-close-o:before{content:\"\\F2D4\"}.fa-bandcamp:before{content:\"\\F2D5\"}.fa-grav:before{content:\"\\F2D6\"}.fa-etsy:before{content:\"\\F2D7\"}.fa-imdb:before{content:\"\\F2D8\"}.fa-ravelry:before{content:\"\\F2D9\"}.fa-eercast:before{content:\"\\F2DA\"}.fa-microchip:before{content:\"\\F2DB\"}.fa-snowflake-o:before{content:\"\\F2DC\"}.fa-superpowers:before{content:\"\\F2DD\"}.fa-wpexplorer:before{content:\"\\F2DE\"}.fa-meetup:before{content:\"\\F2E0\"}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto}\n", ""]);

// exports


/***/ }),

/***/ "GNiM":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_stringToPath.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var memoizeCapped = __webpack_require__(/*! ./_memoizeCapped */ "I01J");

/** Used to match property names within property paths. */
var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;

/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;

/**
 * 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;
});

module.exports = stringToPath;


/***/ }),

/***/ "GO48":
/*!*************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/notebook/style/index.css ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports
exports.i(__webpack_require__(/*! -!../../../css-loader!./toolbar.css */ "wXb+"), "");

// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n/*-----------------------------------------------------------------------------\n| Private CSS variables\n|----------------------------------------------------------------------------*/\n\n:root {\n  --jp-private-notebook-dragImage-width: 304px;\n  --jp-private-notebook-dragImage-height: 36px;\n  --jp-private-notebook-selected-color: var(--md-blue-400);\n  --jp-private-notebook-active-color: var(--md-green-400);\n}\n\n/*-----------------------------------------------------------------------------\n| Imports\n|----------------------------------------------------------------------------*/\n\n/*-----------------------------------------------------------------------------\n| Notebook\n|----------------------------------------------------------------------------*/\n\n.jp-NotebookPanel {\n  display: block;\n  height: 100%;\n}\n\n.jp-NotebookPanel.jp-Document {\n  min-width: 240px;\n  min-height: 120px;\n}\n\n.jp-Notebook {\n  padding: var(--jp-notebook-padding);\n  outline: none;\n  overflow: auto;\n  background: var(--jp-layout-color0);\n}\n\n.jp-Notebook::after {\n  display: block;\n  content: '';\n  min-height: var(--jp-notebook-scroll-padding);\n}\n\n.jp-Notebook .jp-Cell {\n  overflow: visible;\n}\n\n.jp-Notebook .jp-Cell .jp-InputPrompt {\n  cursor: move;\n}\n\n/*-----------------------------------------------------------------------------\n| Notebook state related styling\n|\n| The notebook and cells each have states, here are the possibilities:\n|\n| - Notebook\n|   - Command\n|   - Edit\n| - Cell\n|   - None\n|   - Active (only one can be active)\n|   - Selected (the cells actions are applied to)\n|   - Multiselected (when multiple selected, the cursor)\n|   - No outputs\n|----------------------------------------------------------------------------*/\n\n/* Command or edit modes */\n\n.jp-Notebook .jp-Cell:not(.jp-mod-active) .jp-InputPrompt {\n  opacity: var(--jp-cell-prompt-not-active-opacity);\n  color: var(--jp-cell-prompt-not-active-font-color);\n}\n\n.jp-Notebook .jp-Cell:not(.jp-mod-active) .jp-OutputPrompt {\n  opacity: var(--jp-cell-prompt-not-active-opacity);\n  color: var(--jp-cell-prompt-not-active-font-color);\n}\n\n/* cell is active */\n.jp-Notebook .jp-Cell.jp-mod-active .jp-Collapser {\n  background: var(--jp-brand-color1);\n}\n\n/* collapser is hovered */\n.jp-Notebook .jp-Cell .jp-Collapser:hover {\n  box-shadow: var(--jp-elevation-z2);\n  background: var(--jp-brand-color1);\n  opacity: var(--jp-cell-collapser-not-active-hover-opacity);\n}\n\n/* cell is active and collapser is hovered */\n.jp-Notebook .jp-Cell.jp-mod-active .jp-Collapser:hover {\n  background: var(--jp-brand-color0);\n  opacity: 1;\n}\n\n/* Command mode */\n\n.jp-Notebook.jp-mod-commandMode .jp-Cell.jp-mod-selected {\n  background: var(--jp-notebook-multiselected-color);\n}\n\n.jp-Notebook.jp-mod-commandMode\n  .jp-Cell.jp-mod-active.jp-mod-selected:not(.jp-mod-multiSelected) {\n  background: transparent;\n}\n\n/* Edit mode */\n\n.jp-Notebook.jp-mod-editMode .jp-Cell.jp-mod-active .jp-InputArea-editor {\n  border: var(--jp-border-width) solid var(--jp-cell-editor-active-border-color);\n  box-shadow: var(--jp-input-box-shadow);\n  background-color: var(--jp-cell-editor-active-background);\n}\n\n/*-----------------------------------------------------------------------------\n| Notebook drag and drop\n|----------------------------------------------------------------------------*/\n\n.jp-Notebook-cell.jp-mod-dropSource {\n  opacity: 0.5;\n}\n\n.jp-Notebook-cell.jp-mod-dropTarget,\n.jp-Notebook.jp-mod-commandMode\n  .jp-Notebook-cell.jp-mod-active.jp-mod-selected.jp-mod-dropTarget {\n  border-top-color: var(--jp-private-notebook-selected-color);\n  border-top-style: solid;\n  border-top-width: 2px;\n}\n\n.jp-dragImage {\n  display: flex;\n  flex-direction: row;\n  width: var(--jp-private-notebook-dragImage-width);\n  height: var(--jp-private-notebook-dragImage-height);\n  border: var(--jp-border-width) solid var(--jp-cell-editor-border-color);\n  background: var(--jp-cell-editor-background);\n  overflow: visible;\n}\n\n.jp-dragImage-singlePrompt {\n  box-shadow: 2px 2px 4px 0px rgba(0, 0, 0, 0.12);\n}\n\n.jp-dragImage .jp-dragImage-content {\n  flex: 1 1 auto;\n  z-index: 2;\n  font-size: var(--jp-code-font-size);\n  font-family: var(--jp-code-font-family);\n  line-height: var(--jp-code-line-height);\n  padding: var(--jp-code-padding);\n  border: var(--jp-border-width) solid var(--jp-cell-editor-border-color);\n  background: var(--jp-cell-editor-background-color);\n  color: var(--jp-content-font-color3);\n  text-align: left;\n  margin: 4px 4px 4px 0px;\n}\n\n.jp-dragImage .jp-dragImage-prompt {\n  flex: 0 0 auto;\n  min-width: 36px;\n  color: var(--jp-cell-inprompt-font-color);\n  padding: var(--jp-code-padding);\n  padding-left: 12px;\n  font-family: var(--jp-cell-prompt-font-family);\n  letter-spacing: var(--jp-cell-prompt-letter-spacing);\n  line-height: 1.9;\n  font-size: var(--jp-code-font-size);\n  border: var(--jp-border-width) solid transparent;\n}\n\n.jp-dragImage-multipleBack {\n  z-index: -1;\n  position: absolute;\n  height: 32px;\n  width: 300px;\n  top: 8px;\n  left: 8px;\n  background: var(--jp-layout-color2);\n  border: var(--jp-border-width) solid var(--jp-input-border-color);\n  box-shadow: 2px 2px 4px 0px rgba(0, 0, 0, 0.12);\n}\n\n/*-----------------------------------------------------------------------------\n| Cell toolbar\n|----------------------------------------------------------------------------*/\n\n.jp-CellTools {\n  display: flex;\n  flex-direction: column;\n  min-width: var(--jp-sidebar-min-width);\n  color: var(--jp-ui-font-color1);\n  background: var(--jp-layout-color1);\n  /* This is needed so that all font sizing of children done in ems is\n   * relative to this base size */\n  font-size: var(--jp-ui-font-size1);\n}\n\n.jp-ActiveCellTool {\n  padding: 12px;\n  background-color: var(--jp-layout-color1);\n  border-top: none !important;\n}\n\n.jp-ActiveCellTool .jp-InputArea-prompt {\n  flex: 0 0 auto;\n  padding-left: 0px;\n}\n\n.jp-ActiveCellTool .jp-InputArea-editor {\n  flex: 1 1 auto;\n  background: var(--jp-cell-editor-background);\n  border-color: var(--jp-cell-editor-border-color);\n}\n\n.jp-ActiveCellTool .jp-InputArea-editor .CodeMirror {\n  background: transparent;\n}\n\n.jp-CellTools-tool:not(:nth-child(2)) {\n  border-top: var(--jp-border-width) solid var(--jp-border-color2);\n}\n\n.jp-MetadataEditorTool {\n  flex-direction: column;\n}\n\n.jp-KeySelector {\n  padding: 12px;\n}\n\n.jp-KeySelector select.jp-mod-styled {\n  font-size: var(--jp-ui-font-size1);\n  color: var(--jp-ui-font-color0);\n  border: var(--jp-border-width) solid var(--jp-border-color1);\n}\n\n.jp-KeySelector label {\n  line-height: 1.4;\n}\n\n/*-----------------------------------------------------------------------------\n| Presentation Mode (.jp-mod-presentationMode)\n|----------------------------------------------------------------------------*/\n\n.jp-mod-presentationMode .jp-Notebook {\n  --jp-content-font-size1: var(--jp-content-presentation-font-size1);\n  --jp-code-font-size: var(--jp-code-presentation-font-size);\n}\n\n.jp-mod-presentationMode .jp-Notebook .jp-Cell .jp-InputPrompt,\n.jp-mod-presentationMode .jp-Notebook .jp-Cell .jp-OutputPrompt {\n  flex: 0 0 110px;\n}\n", ""]);

// exports


/***/ }),

/***/ "GOc5":
/*!*****************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotBoxIcon.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotBoxIcon = function PlotBoxIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M28 8v6h-4V5.312H8V14H4V8H0v16h4v-6h4v8.688h16V18h4v6h4V8zM12 22.688V9.313h8v13.375z' })
    );
};

exports.default = PlotBoxIcon;

/***/ }),

/***/ "GP5n":
/*!**************************************************************!*\
  !*** ./node_modules/codemirror/addon/search/jump-to-line.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

// Defines jumpToLine command. Uses dialog.js if present.

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"), __webpack_require__(/*! ../dialog/dialog */ "Ku0u"));
  else {}
})(function(CodeMirror) {
  "use strict";

  function dialog(cm, text, shortText, deflt, f) {
    if (cm.openDialog) cm.openDialog(text, f, {value: deflt, selectValueOnOpen: true});
    else f(prompt(shortText, deflt));
  }

  var jumpDialog =
      'Jump to line: <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">(Use line:column or scroll% syntax)</span>';

  function interpretLine(cm, string) {
    var num = Number(string)
    if (/^[-+]/.test(string)) return cm.getCursor().line + num
    else return num - 1
  }

  CodeMirror.commands.jumpToLine = function(cm) {
    var cur = cm.getCursor();
    dialog(cm, jumpDialog, "Jump to line:", (cur.line + 1) + ":" + cur.ch, function(posStr) {
      if (!posStr) return;

      var match;
      if (match = /^\s*([\+\-]?\d+)\s*\:\s*(\d+)\s*$/.exec(posStr)) {
        cm.setCursor(interpretLine(cm, match[1]), Number(match[2]))
      } else if (match = /^\s*([\+\-]?\d+(\.\d+)?)\%\s*/.exec(posStr)) {
        var line = Math.round(cm.lineCount() * Number(match[1]) / 100);
        if (/^[-+]/.test(match[1])) line = cur.line + line + 1;
        cm.setCursor(line - 1, cur.ch);
      } else if (match = /^\s*\:?\s*([\+\-]?\d+)\s*/.exec(posStr)) {
        cm.setCursor(interpretLine(cm, match[1]), cur.ch);
      }
    });
  };

  CodeMirror.keyMap["default"]["Alt-G"] = "jumpToLine";
});


/***/ }),

/***/ "GQeE":
/*!***********************************************************!*\
  !*** ./node_modules/babel-runtime/core-js/object/keys.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = { "default": __webpack_require__(/*! core-js/library/fn/object/keys */ "iq4v"), __esModule: true };

/***/ }),

/***/ "GRvS":
/*!*****************************************!*\
  !*** ./node_modules/blacklist/index.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = function blacklist (src) {
  var copy = {}
  var filter = arguments[1]

  if (typeof filter === 'string') {
    filter = {}
    for (var i = 1; i < arguments.length; i++) {
      filter[arguments[i]] = true
    }
  }

  for (var key in src) {
    // blacklist?
    if (filter[key]) continue

    copy[key] = src[key]
  }

  return copy
}


/***/ }),

/***/ "GTV5":
/*!**********************************************!*\
  !*** ./node_modules/react-tabs/esm/index.js ***!
  \**********************************************/
/*! exports provided: Tabs, TabList, Tab, TabPanel, resetIdCounter */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _components_Tabs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./components/Tabs */ "FwNs");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Tabs", function() { return _components_Tabs__WEBPACK_IMPORTED_MODULE_0__["default"]; });

/* harmony import */ var _components_TabList__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./components/TabList */ "ZvEP");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TabList", function() { return _components_TabList__WEBPACK_IMPORTED_MODULE_1__["default"]; });

/* harmony import */ var _components_Tab__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./components/Tab */ "4694");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Tab", function() { return _components_Tab__WEBPACK_IMPORTED_MODULE_2__["default"]; });

/* harmony import */ var _components_TabPanel__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./components/TabPanel */ "WZUU");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TabPanel", function() { return _components_TabPanel__WEBPACK_IMPORTED_MODULE_3__["default"]; });

/* harmony import */ var _helpers_uuid__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./helpers/uuid */ "gTk9");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "resetIdCounter", function() { return _helpers_uuid__WEBPACK_IMPORTED_MODULE_4__["reset"]; });







/***/ }),

/***/ "GWQT":
/*!***************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeBarpolarIcon.js ***!
  \***************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeBarpolarIcon = function TraceTypeBarpolarIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 1360 1360' }, props),
        _react2.default.createElement('path', { fill: '#119DFF', d: 'M1080.177 1084.467c.354-.322 1.108-1.021 2.555-2.404L813.893 807.359c-1.172.887-2.273 1.848-3.495 2.695-22.345 15.512-48.603 20.99-73.59 17.6l96.948 377.646c82.413-12.22 195.673-85.513 246.421-120.833zM693.09 637.132c22.891-15.186 49.64-20.216 74.876-16.01l88.415-463.555c-116.336-21.674-239.205-7.669-350.961 45.067l187.67 434.498zM1231.328 810.035c30.589-165.676-42.52-301.417-42.52-301.417l.015-.008-353.95 153.634c.577.793 1.229 1.516 1.791 2.326 31.529 45.414 21.991 106.994-20.521 141.049l332.54 197.34c32.805-47.598 68.03-113.773 82.645-192.924zM834.302 661.506l208.602-142.957c-10.164-13.462-77.007-98.029-177.018-132.644l-97.269 235.302c25.413 4.403 49.124 18.214 65.685 40.299zM648.714 702.166l-459.61-107.527c-32.188 139.755-12.253 290.923 65.154 422.035l408.846-235.822c-15.628-24.149-20.048-52.436-14.39-78.686zM329.351 480.408l319.894 219.463c5.76-24.115 19.966-46.309 41.941-61.558.467-.321.957-.57 1.424-.884l-203.702-324.95c-.032.021-119.013 88.111-159.557 167.929zM664.928 783.789c-.08-.113-.137-.23-.217-.342L501.627 970.611c45.541 79.689 180.246 104.195 180.326 104.211l49.816-247.875c-26.154-4.84-50.482-19.582-66.841-43.158z' }),
        _react2.default.createElement(
            'g',
            { fill: '#09FFFF' },
            _react2.default.createElement('path', { d: 'M834.302 661.506l208.602-142.957c-10.164-13.462-77.007-98.029-177.018-132.644l-97.269 235.302c25.413 4.403 49.124 18.214 65.685 40.299zM648.714 702.166L275.1 614.759c-27.23 118.514-10.205 246.698 55.633 357.805l332.37-191.713c-15.627-24.148-20.047-52.435-14.389-78.685zM1203.143 540.826c-.667-1.643-1.286-3.302-1.977-4.941a407.91 407.91 0 0 0-1.864-4.524 480.081 480.081 0 0 0-10.519-22.734l-353.91 153.618c.577.793 1.229 1.516 1.791 2.326 31.529 45.414 21.991 106.994-20.521 141.049l332.54 197.34c30.612-44.416 63.313-105.016 79.433-177.232.979-4.604 1.991-9.209 2.844-13.844.063-.355.145-.695.208-1.049 3.922-21.762 6.308-43.795 7.265-65.922.112-3.041.232-6.084.29-9.088.015-.855.007-1.715.031-2.576 1.052-84.013-20.474-153.912-35.611-192.423zM693.09 637.132c22.891-15.186 49.64-20.216 74.876-16.01L839.838 244.3c-99.287-18.42-204.188-6.179-299.394 39.427L693.09 637.132zM813.893 807.359c-1.172.887-2.273 1.848-3.495 2.695-22.345 15.512-48.603 20.99-73.59 17.6l96.932 377.559c68.136-11.697 134.865-38.029 195.407-80.053 19.131-13.281 36.938-27.752 53.553-43.129L813.893 807.359zM329.351 480.408l319.894 219.463c5.76-24.115 19.966-46.309 41.941-61.558.467-.321.957-.57 1.424-.884l-203.702-324.95c-.032.021-119.013 88.111-159.557 167.929zM664.928 783.789c-.08-.113-.137-.23-.217-.342L501.627 970.611c45.541 79.689 180.246 104.195 180.326 104.211l49.816-247.875c-26.154-4.84-50.482-19.582-66.841-43.158z' })
        ),
        _react2.default.createElement(
            'g',
            { fill: '#119DFF' },
            _react2.default.createElement('path', { d: 'M693.09 637.132c22.891-15.186 49.64-20.216 74.876-16.01l47.365-248.342c-74.041-13.599-152.315-3.921-222.966 31.139L693.09 637.132zM834.302 661.506l208.602-142.957c-10.107-13.39-76.34-97.101-175.474-132.053-.523-.177-1.036-.382-1.559-.559l-97.254 235.27c25.413 4.403 49.124 18.214 65.685 40.299zM648.714 702.166l-246.229-57.605c-19.871 87.053-7.16 181.197 41.556 262.656l219.063-126.365c-15.628-24.149-20.048-52.436-14.39-78.686zM1068.493 560.841l-233.62 101.403c.577.793 1.229 1.516 1.791 2.326 31.529 45.414 21.991 106.994-20.521 141.049l221.569 131.486c79.858-107.585 93.889-253.884 30.781-376.264zM436.642 554.016l212.603 145.855c5.76-24.115 19.966-46.309 41.941-61.558.467-.321.957-.57 1.424-.884L558.337 423.24c-3.784 2.422-7.576 4.841-11.298 7.429-47.605 33.046-84.598 75.627-110.397 123.347zM813.893 807.359c-1.172.887-2.273 1.848-3.495 2.695-22.345 15.512-48.603 20.99-73.59 17.6l64.246 250.262c53.496-7.561 106.092-27.311 153.497-60.221 13.017-9.039 25.158-18.85 36.591-29.223L813.893 807.359zM664.928 783.789c-.08-.113-.137-.23-.217-.342L501.627 970.611c7.223 12.639 16.704 23.879 27.519 33.867a355.976 355.976 0 0 0 107.989 58.461c.619.201 1.205.377 1.816.578 3.624 1.189 7.271 2.283 10.928 3.352 2.859.836 5.551 1.59 8.114 2.281 4.002 1.078 7.995 2.139 12.021 3.078.306.063.58.129.868.199 3.68.846 7.392 1.551 11.097 2.275l49.791-247.756c-26.155-4.839-50.483-19.581-66.842-43.157z' })
        ),
        _react2.default.createElement(
            'g',
            { fill: '#09FFFF' },
            _react2.default.createElement('path', { d: 'M664.928 783.789c-.08-.113-.137-.23-.217-.342l-72.41 83.104c31.81 35.506 73.583 58.213 118.081 66.811l21.389-106.414c-26.156-4.841-50.484-19.583-66.843-43.159zM629.277 549.13c-32.862 22.815-57.297 53.224-72.634 87.215l92.602 63.526c5.76-24.115 19.966-46.309 41.941-61.558.467-.321.957-.57 1.424-.884l-57.676-92.016c-1.896 1.226-3.792 2.423-5.657 3.717zM813.893 807.359c-1.172.887-2.273 1.848-3.495 2.695-22.345 15.512-48.603 20.99-73.59 17.6l28.024 109.162c37.33-2.428 74.508-14.703 107.475-37.588a214.348 214.348 0 0 0 17.902-13.891l-76.316-77.978zM648.714 702.166l-105.796-24.75c-11.763 52.371-3.824 108.988 26.001 157.76l94.185-54.324c-15.628-24.149-20.048-52.436-14.39-78.686zM693.09 637.132c22.891-15.186 49.64-20.216 74.876-16.01l20.353-106.699c-46.2-8.264-95.107-1.326-138.641 22.208l43.412 100.501zM834.302 661.506l89.645-61.435c-28.821-40.231-69.132-67.489-113.355-80.389l-41.974 101.525c25.412 4.403 49.123 18.214 65.684 40.299zM935.759 618.455l-100.886 43.79c.577.793 1.229 1.516 1.791 2.326 31.529 45.414 21.991 106.994-20.521 141.049l96.483 57.26c57.746-67.288 68.433-165.378 23.133-244.425z' })
        )
    );
};

exports.default = TraceTypeBarpolarIcon;

/***/ }),

/***/ "GbLo":
/*!**********************************************!*\
  !*** ./node_modules/fast-isnumeric/index.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * inspired by is-number <https://github.com/jonschlinkert/is-number>
 * but significantly simplified and sped up by ignoring number and string constructors
 * ie these return false:
 *   new Number(1)
 *   new String('1')
 */



var allBlankCharCodes = __webpack_require__(/*! is-string-blank */ "6bQy");

module.exports = function(n) {
    var type = typeof n;
    if(type === 'string') {
        var original = n;
        n = +n;
        // whitespace strings cast to zero - filter them out
        if(n===0 && allBlankCharCodes(original)) return false;
    }
    else if(type !== 'number') return false;

    return n - n < 1;
};


/***/ }),

/***/ "Gbhj":
/*!********************************************************!*\
  !*** ./node_modules/@phosphor/algorithm/lib/string.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * The namespace for string-specific algorithms.
 */
var StringExt;
(function (StringExt) {
    /**
     * Find the indices of characters in a source text.
     *
     * @param source - The source text which should be searched.
     *
     * @param query - The characters to locate in the source text.
     *
     * @param start - The index to start the search.
     *
     * @returns The matched indices, or `null` if there is no match.
     *
     * #### Complexity
     * Linear on `sourceText`.
     *
     * #### Notes
     * In order for there to be a match, all of the characters in `query`
     * **must** appear in `source` in the order given by `query`.
     *
     * Characters are matched using strict `===` equality.
     */
    function findIndices(source, query, start) {
        if (start === void 0) { start = 0; }
        var indices = new Array(query.length);
        for (var i = 0, j = start, n = query.length; i < n; ++i, ++j) {
            j = source.indexOf(query[i], j);
            if (j === -1) {
                return null;
            }
            indices[i] = j;
        }
        return indices;
    }
    StringExt.findIndices = findIndices;
    /**
     * A string matcher which uses a sum-of-squares algorithm.
     *
     * @param source - The source text which should be searched.
     *
     * @param query - The characters to locate in the source text.
     *
     * @param start - The index to start the search.
     *
     * @returns The match result, or `null` if there is no match.
     *   A lower `score` represents a stronger match.
     *
     * #### Complexity
     * Linear on `sourceText`.
     *
     * #### Notes
     * This scoring algorithm uses a sum-of-squares approach to determine
     * the score. In order for there to be a match, all of the characters
     * in `query` **must** appear in `source` in order. The index of each
     * matching character is squared and added to the score. This means
     * that early and consecutive character matches are preferred, while
     * late matches are heavily penalized.
     */
    function matchSumOfSquares(source, query, start) {
        if (start === void 0) { start = 0; }
        var indices = findIndices(source, query, start);
        if (!indices) {
            return null;
        }
        var score = 0;
        for (var i = 0, n = indices.length; i < n; ++i) {
            var j = indices[i] - start;
            score += j * j;
        }
        return { score: score, indices: indices };
    }
    StringExt.matchSumOfSquares = matchSumOfSquares;
    /**
     * A string matcher which uses a sum-of-deltas algorithm.
     *
     * @param source - The source text which should be searched.
     *
     * @param query - The characters to locate in the source text.
     *
     * @param start - The index to start the search.
     *
     * @returns The match result, or `null` if there is no match.
     *   A lower `score` represents a stronger match.
     *
     * #### Complexity
     * Linear on `sourceText`.
     *
     * #### Notes
     * This scoring algorithm uses a sum-of-deltas approach to determine
     * the score. In order for there to be a match, all of the characters
     * in `query` **must** appear in `source` in order. The delta between
     * the indices are summed to create the score. This means that groups
     * of matched characters are preferred, while fragmented matches are
     * penalized.
     */
    function matchSumOfDeltas(source, query, start) {
        if (start === void 0) { start = 0; }
        var indices = findIndices(source, query, start);
        if (!indices) {
            return null;
        }
        var score = 0;
        var last = start - 1;
        for (var i = 0, n = indices.length; i < n; ++i) {
            var j = indices[i];
            score += j - last - 1;
            last = j;
        }
        return { score: score, indices: indices };
    }
    StringExt.matchSumOfDeltas = matchSumOfDeltas;
    /**
     * Highlight the matched characters of a source text.
     *
     * @param source - The text which should be highlighted.
     *
     * @param indices - The indices of the matched characters. They must
     *   appear in increasing order and must be in bounds of the source.
     *
     * @param fn - The function to apply to the matched chunks.
     *
     * @returns An array of unmatched and highlighted chunks.
     */
    function highlight(source, indices, fn) {
        // Set up the result array.
        var result = [];
        // Set up the counter variables.
        var k = 0;
        var last = 0;
        var n = indices.length;
        // Iterator over each index.
        while (k < n) {
            // Set up the chunk indices.
            var i = indices[k];
            var j = indices[k];
            // Advance the right chunk index until it's non-contiguous.
            while (++k < n && indices[k] === j + 1) {
                j++;
            }
            // Extract the unmatched text.
            if (last < i) {
                result.push(source.slice(last, i));
            }
            // Extract and highlight the matched text.
            if (i < j + 1) {
                result.push(fn(source.slice(i, j + 1)));
            }
            // Update the last visited index.
            last = j + 1;
        }
        // Extract any remaining unmatched text.
        if (last < source.length) {
            result.push(source.slice(last));
        }
        // Return the highlighted result.
        return result;
    }
    StringExt.highlight = highlight;
})(StringExt = exports.StringExt || (exports.StringExt = {}));


/***/ }),

/***/ "GbqW":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/imageviewer/lib/index.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
__webpack_require__(/*! ../style/index.css */ "mg2g");
__export(__webpack_require__(/*! ./widget */ "/PhR"));
/* tslint:disable */
/**
 * The editor tracker token.
 */
exports.IImageTracker = new coreutils_1.Token('@jupyterlab/imageviewer:IImageTracker');
/* tslint:enable */


/***/ }),

/***/ "Gdy8":
/*!**************************************************************************!*\
  !*** ./node_modules/draft-js-utils/lib/callModifierForSelectedBlocks.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _draftJs = __webpack_require__(/*! draft-js */ "v83y");

var _getSelectedBlocks = __webpack_require__(/*! ./getSelectedBlocks */ "jb54");

var _getSelectedBlocks2 = _interopRequireDefault(_getSelectedBlocks);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Calls a provided `modifier` function with a selection for each
 * selected block in the current editor selection. Passes through additional
 * arguments to the modifier.
 *
 * Note: At the moment it will retain the original selection and override
 * possible selection changes from modifiers
 *
 * @param  {object} editorState The current draft.js editor state object
 *
 * @param  {function} modifier  A modifier function to be executed.
 *                              Must have the signature (editorState, selection, ...)
 *
 * @param  {mixed} ...args      Additional arguments to be passed through to the modifier
 *
 * @return {object} The new editor state
 */
exports.default = function (editorState, modifier) {
  for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
    args[_key - 2] = arguments[_key];
  }

  var contentState = editorState.getCurrentContent();
  var currentSelection = editorState.getSelection();

  var startKey = currentSelection.getStartKey();
  var endKey = currentSelection.getEndKey();
  var startOffset = currentSelection.getStartOffset();
  var endOffset = currentSelection.getEndOffset();

  var isSameBlock = startKey === endKey;
  var selectedBlocks = (0, _getSelectedBlocks2.default)(contentState, startKey, endKey);

  var finalEditorState = editorState;
  selectedBlocks.forEach(function (block) {
    var currentBlockKey = block.getKey();
    var selectionStart = startOffset;
    var selectionEnd = endOffset;

    if (currentBlockKey === startKey) {
      selectionStart = startOffset;
      selectionEnd = isSameBlock ? endOffset : block.getText().length;
    } else if (currentBlockKey === endKey) {
      selectionStart = isSameBlock ? startOffset : 0;
      selectionEnd = endOffset;
    } else {
      selectionStart = 0;
      selectionEnd = block.getText().length;
    }

    var selection = new _draftJs.SelectionState({
      anchorKey: currentBlockKey,
      anchorOffset: selectionStart,
      focusKey: currentBlockKey,
      focusOffset: selectionEnd
    });

    finalEditorState = modifier.apply(undefined, [finalEditorState, selection].concat(args));
  });

  return _draftJs.EditorState.forceSelection(finalEditorState, currentSelection);
};

/***/ }),

/***/ "GeF/":
/*!******************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/geometry2d.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var mod = __webpack_require__(/*! ./mod */ "09xr").mod;

/*
 * look for intersection of two line segments
 *   (1->2 and 3->4) - returns array [x,y] if they do, null if not
 */
exports.segmentsIntersect = segmentsIntersect;
function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) {
    var a = x2 - x1;
    var b = x3 - x1;
    var c = x4 - x3;
    var d = y2 - y1;
    var e = y3 - y1;
    var f = y4 - y3;
    var det = a * f - c * d;
    // parallel lines? intersection is undefined
    // ignore the case where they are colinear
    if(det === 0) return null;
    var t = (b * f - c * e) / det;
    var u = (b * d - a * e) / det;
    // segments do not intersect?
    if(u < 0 || u > 1 || t < 0 || t > 1) return null;

    return {x: x1 + a * t, y: y1 + d * t};
}

/*
 * find the minimum distance between two line segments (1->2 and 3->4)
 */
exports.segmentDistance = function segmentDistance(x1, y1, x2, y2, x3, y3, x4, y4) {
    if(segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4)) return 0;

    // the two segments and their lengths squared
    var x12 = x2 - x1;
    var y12 = y2 - y1;
    var x34 = x4 - x3;
    var y34 = y4 - y3;
    var ll12 = x12 * x12 + y12 * y12;
    var ll34 = x34 * x34 + y34 * y34;

    // calculate distance squared, then take the sqrt at the very end
    var dist2 = Math.min(
        perpDistance2(x12, y12, ll12, x3 - x1, y3 - y1),
        perpDistance2(x12, y12, ll12, x4 - x1, y4 - y1),
        perpDistance2(x34, y34, ll34, x1 - x3, y1 - y3),
        perpDistance2(x34, y34, ll34, x2 - x3, y2 - y3)
    );

    return Math.sqrt(dist2);
};

/*
 * distance squared from segment ab to point c
 * [xab, yab] is the vector b-a
 * [xac, yac] is the vector c-a
 * llab is the length squared of (b-a), just to simplify calculation
 */
function perpDistance2(xab, yab, llab, xac, yac) {
    var fcAB = (xac * xab + yac * yab);
    if(fcAB < 0) {
        // point c is closer to point a
        return xac * xac + yac * yac;
    }
    else if(fcAB > llab) {
        // point c is closer to point b
        var xbc = xac - xab;
        var ybc = yac - yab;
        return xbc * xbc + ybc * ybc;
    }
    else {
        // perpendicular distance is the shortest
        var crossProduct = xac * yab - yac * xab;
        return crossProduct * crossProduct / llab;
    }
}

// a very short-term cache for getTextLocation, just because
// we're often looping over the same locations multiple times
// invalidated as soon as we look at a different path
var locationCache, workingPath, workingTextWidth;

// turn a path and position along it into x, y, and angle for the given text
exports.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) {
    if(path !== workingPath || textWidth !== workingTextWidth) {
        locationCache = {};
        workingPath = path;
        workingTextWidth = textWidth;
    }
    if(locationCache[positionOnPath]) {
        return locationCache[positionOnPath];
    }

    // for the angle, use points on the path separated by the text width
    // even though due to curvature, the text will cover a bit more than that
    var p0 = path.getPointAtLength(mod(positionOnPath - textWidth / 2, totalPathLen));
    var p1 = path.getPointAtLength(mod(positionOnPath + textWidth / 2, totalPathLen));
    // note: atan handles 1/0 nicely
    var theta = Math.atan((p1.y - p0.y) / (p1.x - p0.x));
    // center the text at 2/3 of the center position plus 1/3 the p0/p1 midpoint
    // that's the average position of this segment, assuming it's roughly quadratic
    var pCenter = path.getPointAtLength(mod(positionOnPath, totalPathLen));
    var x = (pCenter.x * 4 + p0.x + p1.x) / 6;
    var y = (pCenter.y * 4 + p0.y + p1.y) / 6;

    var out = {x: x, y: y, theta: theta};
    locationCache[positionOnPath] = out;
    return out;
};

exports.clearLocationCache = function() {
    workingPath = null;
};

/*
 * Find the segment of `path` that's within the visible area
 * given by `bounds` {left, right, top, bottom}, to within a
 * precision of `buffer` px
 *
 * returns: undefined if nothing is visible, else object:
 * {
 *   min: position where the path first enters bounds, or 0 if it
 *        starts within bounds
 *   max: position where the path last exits bounds, or the path length
 *        if it finishes within bounds
 *   len: max - min, ie the length of visible path
 *   total: the total path length - just included so the caller doesn't
 *        need to call path.getTotalLength() again
 *   isClosed: true iff the start and end points of the path are both visible
 *        and are at the same point
 * }
 *
 * Works by starting from either end and repeatedly finding the distance from
 * that point to the plot area, and if it's outside the plot, moving along the
 * path by that distance (because the plot must be at least that far away on
 * the path). Note that if a path enters, exits, and re-enters the plot, we
 * will not capture this behavior.
 */
exports.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) {
    var left = bounds.left;
    var right = bounds.right;
    var top = bounds.top;
    var bottom = bounds.bottom;

    var pMin = 0;
    var pTotal = path.getTotalLength();
    var pMax = pTotal;

    var pt0, ptTotal;

    function getDistToPlot(len) {
        var pt = path.getPointAtLength(len);

        // hold on to the start and end points for `closed`
        if(len === 0) pt0 = pt;
        else if(len === pTotal) ptTotal = pt;

        var dx = (pt.x < left) ? left - pt.x : (pt.x > right ? pt.x - right : 0);
        var dy = (pt.y < top) ? top - pt.y : (pt.y > bottom ? pt.y - bottom : 0);
        return Math.sqrt(dx * dx + dy * dy);
    }

    var distToPlot = getDistToPlot(pMin);
    while(distToPlot) {
        pMin += distToPlot + buffer;
        if(pMin > pMax) return;
        distToPlot = getDistToPlot(pMin);
    }

    distToPlot = getDistToPlot(pMax);
    while(distToPlot) {
        pMax -= distToPlot + buffer;
        if(pMin > pMax) return;
        distToPlot = getDistToPlot(pMax);
    }

    return {
        min: pMin,
        max: pMax,
        len: pMax - pMin,
        total: pTotal,
        isClosed: pMin === 0 && pMax === pTotal &&
            Math.abs(pt0.x - ptTotal.x) < 0.1 &&
            Math.abs(pt0.y - ptTotal.y) < 0.1
    };
};

/**
 * Find point on SVG path corresponding to a given constraint coordinate
 *
 * @param {SVGPathElement} path
 * @param {Number} val : constraint coordinate value
 * @param {String} coord : 'x' or 'y' the constraint coordinate
 * @param {Object} opts :
 *  - {Number} pathLength : supply total path length before hand
 *  - {Number} tolerance
 *  - {Number} iterationLimit
 * @return {SVGPoint}
 */
exports.findPointOnPath = function findPointOnPath(path, val, coord, opts) {
    opts = opts || {};

    var pathLength = opts.pathLength || path.getTotalLength();
    var tolerance = opts.tolerance || 1e-3;
    var iterationLimit = opts.iterationLimit || 30;

    // if path starts at a val greater than the path tail (like on vertical violins),
    // we must flip the sign of the computed diff.
    var mul = path.getPointAtLength(0)[coord] > path.getPointAtLength(pathLength)[coord] ? -1 : 1;

    var i = 0;
    var b0 = 0;
    var b1 = pathLength;
    var mid;
    var pt;
    var diff;

    while(i < iterationLimit) {
        mid = (b0 + b1) / 2;
        pt = path.getPointAtLength(mid);
        diff = pt[coord] - val;

        if(Math.abs(diff) < tolerance) {
            return pt;
        } else {
            if(mul * diff > 0) {
                b1 = mid;
            } else {
                b0 = mid;
            }
            i++;
        }
    }
    return pt;
};


/***/ }),

/***/ "Gga1":
/*!*********************************************************!*\
  !*** ./node_modules/@jupyterlab/codemirror/lib/mode.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const codeeditor_1 = __webpack_require__(/*! @jupyterlab/codeeditor */ "sLCx");
const codemirror_1 = __importDefault(__webpack_require__(/*! codemirror */ "VrN/"));
__webpack_require__(/*! codemirror/mode/meta */ "8EBN");
__webpack_require__(/*! codemirror/addon/runmode/runmode */ "w/2H");
__webpack_require__(/*! ./codemirror-ipython */ "3Mkv");
__webpack_require__(/*! ./codemirror-ipythongfm */ "4a3i");
// Bundle other common modes
__webpack_require__(/*! codemirror/mode/javascript/javascript */ "+dQi");
__webpack_require__(/*! codemirror/mode/css/css */ "ewDg");
__webpack_require__(/*! codemirror/mode/julia/julia */ "NGrM");
__webpack_require__(/*! codemirror/mode/r/r */ "kD6b");
__webpack_require__(/*! codemirror/mode/markdown/markdown */ "lZu9");
__webpack_require__(/*! codemirror/mode/clike/clike */ "S6bl");
__webpack_require__(/*! codemirror/mode/shell/shell */ "AvDn");
__webpack_require__(/*! codemirror/mode/sql/sql */ "/9rB");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
/**
 * The namespace for CodeMirror Mode functionality.
 */
var Mode;
(function (Mode) {
    /**
     * Get the raw list of available modes specs.
     */
    function getModeInfo() {
        return codemirror_1.default.modeInfo;
    }
    Mode.getModeInfo = getModeInfo;
    /**
     * Running a CodeMirror mode outside of an editor.
     */
    function run(code, mode, el) {
        codemirror_1.default.runMode(code, mode, el);
    }
    Mode.run = run;
    /**
     * Ensure a codemirror mode is available by name or Codemirror spec.
     *
     * @param mode - The mode to ensure.  If it is a string, uses [findBest]
     *   to get the appropriate spec.
     *
     * @returns A promise that resolves when the mode is available.
     */
    function ensure(mode) {
        let spec = findBest(mode);
        // Simplest, cheapest check by mode name.
        if (codemirror_1.default.modes.hasOwnProperty(spec.mode)) {
            return Promise.resolve(spec);
        }
        // Fetch the mode asynchronously.
        return new Promise((resolve, reject) => {
            // An arrow function below seems to miscompile in our current webpack to
            // invalid js.
            Promise.all(/*! AMD require */[__webpack_require__.e(1), __webpack_require__.e(0)]).then(function() { var __WEBPACK_AMD_REQUIRE_ARRAY__ = [__webpack_require__("eTbV")(`./${spec.mode}/${spec.mode}.js`)]; (function () {
                resolve(spec);
            }).apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);}).catch(__webpack_require__.oe);
        });
    }
    Mode.ensure = ensure;
    /**
     * Find a codemirror mode by name or CodeMirror spec.
     */
    function findBest(mode) {
        let modename = typeof mode === 'string' ? mode : mode.mode || mode.name;
        let mimetype = typeof mode !== 'string' ? mode.mime : modename;
        let ext = typeof mode !== 'string' ? mode.ext : [];
        return (codemirror_1.default.findModeByName(modename || '') ||
            codemirror_1.default.findModeByMIME(mimetype || '') ||
            findByExtension(ext) ||
            codemirror_1.default.findModeByMIME(codeeditor_1.IEditorMimeTypeService.defaultMimeType) ||
            codemirror_1.default.findModeByMIME('text/plain'));
    }
    Mode.findBest = findBest;
    /**
     * Find a codemirror mode by MIME.
     */
    function findByMIME(mime) {
        return codemirror_1.default.findModeByMIME(mime);
    }
    Mode.findByMIME = findByMIME;
    /**
     * Find a codemirror mode by name.
     */
    function findByName(name) {
        return codemirror_1.default.findModeByName(name);
    }
    Mode.findByName = findByName;
    /**
     * Find a codemirror mode by filename.
     */
    function findByFileName(name) {
        let basename = coreutils_1.PathExt.basename(name);
        return codemirror_1.default.findModeByFileName(basename);
    }
    Mode.findByFileName = findByFileName;
    /**
     * Find a codemirror mode by extension.
     */
    function findByExtension(ext) {
        if (typeof ext === 'string') {
            return codemirror_1.default.findModeByExtension(name);
        }
        for (let i = 0; i < ext.length; i++) {
            let mode = codemirror_1.default.findModeByExtension(ext[i]);
            if (mode) {
                return mode;
            }
        }
    }
    Mode.findByExtension = findByExtension;
})(Mode = exports.Mode || (exports.Mode = {}));


/***/ }),

/***/ "Gi0A":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_baseIsMap.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getTag = __webpack_require__(/*! ./_getTag */ "QqLw"),
    isObjectLike = __webpack_require__(/*! ./isObjectLike */ "ExA7");

/** `Object#toString` result references. */
var mapTag = '[object Map]';

/**
 * 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;
}

module.exports = baseIsMap;


/***/ }),

/***/ "GiOz":
/*!************************************************************************!*\
  !*** ./node_modules/react-color/lib/components/sketch/SketchFields.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SketchFields = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _color = __webpack_require__(/*! ../../helpers/color */ "p8yl");

var _color2 = _interopRequireDefault(_color);

var _common = __webpack_require__(/*! ../common */ "TM95");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/* eslint-disable no-param-reassign */

var SketchFields = exports.SketchFields = function SketchFields(_ref) {
  var onChange = _ref.onChange,
      rgb = _ref.rgb,
      hsl = _ref.hsl,
      hex = _ref.hex,
      disableAlpha = _ref.disableAlpha;

  var styles = (0, _reactcss2.default)({
    'default': {
      fields: {
        display: 'flex',
        paddingTop: '4px'
      },
      single: {
        flex: '1',
        paddingLeft: '6px'
      },
      alpha: {
        flex: '1',
        paddingLeft: '6px'
      },
      double: {
        flex: '2'
      },
      input: {
        width: '80%',
        padding: '4px 10% 3px',
        border: 'none',
        boxShadow: 'inset 0 0 0 1px #ccc',
        fontSize: '11px'
      },
      label: {
        display: 'block',
        textAlign: 'center',
        fontSize: '11px',
        color: '#222',
        paddingTop: '3px',
        paddingBottom: '4px',
        textTransform: 'capitalize'
      }
    },
    'disableAlpha': {
      alpha: {
        display: 'none'
      }
    }
  }, { disableAlpha: disableAlpha });

  var handleChange = function handleChange(data, e) {
    if (data.hex) {
      _color2.default.isValidHex(data.hex) && onChange({
        hex: data.hex,
        source: 'hex'
      }, e);
    } else if (data.r || data.g || data.b) {
      onChange({
        r: data.r || rgb.r,
        g: data.g || rgb.g,
        b: data.b || rgb.b,
        a: rgb.a,
        source: 'rgb'
      }, e);
    } else if (data.a) {
      if (data.a < 0) {
        data.a = 0;
      } else if (data.a > 100) {
        data.a = 100;
      }

      data.a /= 100;
      onChange({
        h: hsl.h,
        s: hsl.s,
        l: hsl.l,
        a: data.a,
        source: 'rgb'
      }, e);
    }
  };

  return _react2.default.createElement(
    'div',
    { style: styles.fields, className: 'flexbox-fix' },
    _react2.default.createElement(
      'div',
      { style: styles.double },
      _react2.default.createElement(_common.EditableInput, {
        style: { input: styles.input, label: styles.label },
        label: 'hex',
        value: hex.replace('#', ''),
        onChange: handleChange
      })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.single },
      _react2.default.createElement(_common.EditableInput, {
        style: { input: styles.input, label: styles.label },
        label: 'r',
        value: rgb.r,
        onChange: handleChange,
        dragLabel: 'true',
        dragMax: '255'
      })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.single },
      _react2.default.createElement(_common.EditableInput, {
        style: { input: styles.input, label: styles.label },
        label: 'g',
        value: rgb.g,
        onChange: handleChange,
        dragLabel: 'true',
        dragMax: '255'
      })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.single },
      _react2.default.createElement(_common.EditableInput, {
        style: { input: styles.input, label: styles.label },
        label: 'b',
        value: rgb.b,
        onChange: handleChange,
        dragLabel: 'true',
        dragMax: '255'
      })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.alpha },
      _react2.default.createElement(_common.EditableInput, {
        style: { input: styles.input, label: styles.label },
        label: 'a',
        value: Math.round(rgb.a * 100),
        onChange: handleChange,
        dragLabel: 'true',
        dragMax: '100'
      })
    )
  );
};

exports.default = SketchFields;

/***/ }),

/***/ "Giow":
/*!*********************************************!*\
  !*** ./node_modules/create-hmac/browser.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var inherits = __webpack_require__(/*! inherits */ "P7XM")
var Legacy = __webpack_require__(/*! ./legacy */ "1CSz")
var Base = __webpack_require__(/*! cipher-base */ "ZDAU")
var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer
var md5 = __webpack_require__(/*! create-hash/md5 */ "WnY+")
var RIPEMD160 = __webpack_require__(/*! ripemd160 */ "tcrS")

var sha = __webpack_require__(/*! sha.js */ "afKu")

var ZEROS = Buffer.alloc(128)

function Hmac (alg, key) {
  Base.call(this, 'digest')
  if (typeof key === 'string') {
    key = Buffer.from(key)
  }

  var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64

  this._alg = alg
  this._key = key
  if (key.length > blocksize) {
    var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
    key = hash.update(key).digest()
  } else if (key.length < blocksize) {
    key = Buffer.concat([key, ZEROS], blocksize)
  }

  var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
  var opad = this._opad = Buffer.allocUnsafe(blocksize)

  for (var i = 0; i < blocksize; i++) {
    ipad[i] = key[i] ^ 0x36
    opad[i] = key[i] ^ 0x5C
  }
  this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
  this._hash.update(ipad)
}

inherits(Hmac, Base)

Hmac.prototype._update = function (data) {
  this._hash.update(data)
}

Hmac.prototype._final = function () {
  var h = this._hash.digest()
  var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg)
  return hash.update(this._opad).update(h).digest()
}

module.exports = function createHmac (alg, key) {
  alg = alg.toLowerCase()
  if (alg === 'rmd160' || alg === 'ripemd160') {
    return new Hmac('rmd160', key)
  }
  if (alg === 'md5') {
    return new Legacy(md5, key)
  }
  return new Hmac(alg, key)
}


/***/ }),

/***/ "Gm2Q":
/*!****************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/session/index.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(__webpack_require__(/*! ./manager */ "6SSc"));
__export(__webpack_require__(/*! ./session */ "MZLl"));


/***/ }),

/***/ "GoyQ":
/*!*****************************************!*\
  !*** ./node_modules/lodash/isObject.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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');
}

module.exports = isObject;


/***/ }),

/***/ "Gqu+":
/*!********************************************************!*\
  !*** ./node_modules/@phosphor/virtualdom/lib/index.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
/**
 * A virtual node which represents plain text content.
 *
 * #### Notes
 * User code will not typically create a `VirtualText` node directly.
 * Instead, the `h()` function will be used to create an element tree.
 */
var VirtualText = (function () {
    /**
     * Construct a new virtual text node.
     *
     * @param content - The text content for the node.
     */
    function VirtualText(content) {
        /**
         * The type of the node.
         *
         * This value can be used as a type guard for discriminating the
         * `VirtualNode` union type.
         */
        this.type = 'text';
        this.content = content;
    }
    return VirtualText;
}());
exports.VirtualText = VirtualText;
/**
 * A virtual node which represents an HTML element.
 *
 * #### Notes
 * User code will not typically create a `VirtualElement` node directly.
 * Instead, the `h()` function will be used to create an element tree.
 */
var VirtualElement = (function () {
    /**
     * Construct a new virtual element node.
     *
     * @param tag - The element tag name.
     *
     * @param attrs - The element attributes.
     *
     * @param children - The element children.
     */
    function VirtualElement(tag, attrs, children) {
        /**
         * The type of the node.
         *
         * This value can be used as a type guard for discriminating the
         * `VirtualNode` union type.
         */
        this.type = 'element';
        this.tag = tag;
        this.attrs = attrs;
        this.children = children;
    }
    return VirtualElement;
}());
exports.VirtualElement = VirtualElement;
function h(tag) {
    var attrs = {};
    var children = [];
    for (var i = 1, n = arguments.length; i < n; ++i) {
        var arg = arguments[i];
        if (typeof arg === 'string') {
            children.push(new VirtualText(arg));
        }
        else if (arg instanceof VirtualText) {
            children.push(arg);
        }
        else if (arg instanceof VirtualElement) {
            children.push(arg);
        }
        else if (arg instanceof Array) {
            extend(children, arg);
        }
        else if (i === 1 && arg && typeof arg === 'object') {
            attrs = arg;
        }
    }
    return new VirtualElement(tag, attrs, children);
    function extend(array, values) {
        for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
            var child = values_1[_i];
            if (typeof child === 'string') {
                array.push(new VirtualText(child));
            }
            else if (child instanceof VirtualText) {
                array.push(child);
            }
            else if (child instanceof VirtualElement) {
                array.push(child);
            }
        }
    }
}
exports.h = h;
/**
 * The namespace for the `h` function statics.
 */
(function (h) {
    h.a = h.bind(undefined, 'a');
    h.abbr = h.bind(undefined, 'abbr');
    h.address = h.bind(undefined, 'address');
    h.area = h.bind(undefined, 'area');
    h.article = h.bind(undefined, 'article');
    h.aside = h.bind(undefined, 'aside');
    h.audio = h.bind(undefined, 'audio');
    h.b = h.bind(undefined, 'b');
    h.bdi = h.bind(undefined, 'bdi');
    h.bdo = h.bind(undefined, 'bdo');
    h.blockquote = h.bind(undefined, 'blockquote');
    h.br = h.bind(undefined, 'br');
    h.button = h.bind(undefined, 'button');
    h.canvas = h.bind(undefined, 'canvas');
    h.caption = h.bind(undefined, 'caption');
    h.cite = h.bind(undefined, 'cite');
    h.code = h.bind(undefined, 'code');
    h.col = h.bind(undefined, 'col');
    h.colgroup = h.bind(undefined, 'colgroup');
    h.data = h.bind(undefined, 'data');
    h.datalist = h.bind(undefined, 'datalist');
    h.dd = h.bind(undefined, 'dd');
    h.del = h.bind(undefined, 'del');
    h.dfn = h.bind(undefined, 'dfn');
    h.div = h.bind(undefined, 'div');
    h.dl = h.bind(undefined, 'dl');
    h.dt = h.bind(undefined, 'dt');
    h.em = h.bind(undefined, 'em');
    h.embed = h.bind(undefined, 'embed');
    h.fieldset = h.bind(undefined, 'fieldset');
    h.figcaption = h.bind(undefined, 'figcaption');
    h.figure = h.bind(undefined, 'figure');
    h.footer = h.bind(undefined, 'footer');
    h.form = h.bind(undefined, 'form');
    h.h1 = h.bind(undefined, 'h1');
    h.h2 = h.bind(undefined, 'h2');
    h.h3 = h.bind(undefined, 'h3');
    h.h4 = h.bind(undefined, 'h4');
    h.h5 = h.bind(undefined, 'h5');
    h.h6 = h.bind(undefined, 'h6');
    h.header = h.bind(undefined, 'header');
    h.hr = h.bind(undefined, 'hr');
    h.i = h.bind(undefined, 'i');
    h.iframe = h.bind(undefined, 'iframe');
    h.img = h.bind(undefined, 'img');
    h.input = h.bind(undefined, 'input');
    h.ins = h.bind(undefined, 'ins');
    h.kbd = h.bind(undefined, 'kbd');
    h.label = h.bind(undefined, 'label');
    h.legend = h.bind(undefined, 'legend');
    h.li = h.bind(undefined, 'li');
    h.main = h.bind(undefined, 'main');
    h.map = h.bind(undefined, 'map');
    h.mark = h.bind(undefined, 'mark');
    h.meter = h.bind(undefined, 'meter');
    h.nav = h.bind(undefined, 'nav');
    h.noscript = h.bind(undefined, 'noscript');
    h.object = h.bind(undefined, 'object');
    h.ol = h.bind(undefined, 'ol');
    h.optgroup = h.bind(undefined, 'optgroup');
    h.option = h.bind(undefined, 'option');
    h.output = h.bind(undefined, 'output');
    h.p = h.bind(undefined, 'p');
    h.param = h.bind(undefined, 'param');
    h.pre = h.bind(undefined, 'pre');
    h.progress = h.bind(undefined, 'progress');
    h.q = h.bind(undefined, 'q');
    h.rp = h.bind(undefined, 'rp');
    h.rt = h.bind(undefined, 'rt');
    h.ruby = h.bind(undefined, 'ruby');
    h.s = h.bind(undefined, 's');
    h.samp = h.bind(undefined, 'samp');
    h.section = h.bind(undefined, 'section');
    h.select = h.bind(undefined, 'select');
    h.small = h.bind(undefined, 'small');
    h.source = h.bind(undefined, 'source');
    h.span = h.bind(undefined, 'span');
    h.strong = h.bind(undefined, 'strong');
    h.sub = h.bind(undefined, 'sub');
    h.summary = h.bind(undefined, 'summary');
    h.sup = h.bind(undefined, 'sup');
    h.table = h.bind(undefined, 'table');
    h.tbody = h.bind(undefined, 'tbody');
    h.td = h.bind(undefined, 'td');
    h.textarea = h.bind(undefined, 'textarea');
    h.tfoot = h.bind(undefined, 'tfoot');
    h.th = h.bind(undefined, 'th');
    h.thead = h.bind(undefined, 'thead');
    h.time = h.bind(undefined, 'time');
    h.title = h.bind(undefined, 'title');
    h.tr = h.bind(undefined, 'tr');
    h.track = h.bind(undefined, 'track');
    h.u = h.bind(undefined, 'u');
    h.ul = h.bind(undefined, 'ul');
    h.var_ = h.bind(undefined, 'var');
    h.video = h.bind(undefined, 'video');
    h.wbr = h.bind(undefined, 'wbr');
})(h = exports.h || (exports.h = {}));
/**
 * The namespace for the virtual DOM rendering functions.
 */
var VirtualDOM;
(function (VirtualDOM) {
    /**
     * Create a real DOM element from a virtual element node.
     *
     * @param node - The virtual element node to realize.
     *
     * @returns A new DOM element for the given virtual element node.
     *
     * #### Notes
     * This creates a brand new *real* DOM element with a structure which
     * matches the given virtual DOM node.
     *
     * If virtual diffing is desired, use the `render` function instead.
     */
    function realize(node) {
        return Private.createDOMNode(node);
    }
    VirtualDOM.realize = realize;
    /**
     * Render virtual DOM content into a host element.
     *
     * @param content - The virtual DOM content to render.
     *
     * @param host - The host element for the rendered content.
     *
     * #### Notes
     * This renders the delta from the previous rendering. It assumes that
     * the content of the host element is not manipulated by external code.
     *
     * Providing `null` content will clear the rendering.
     *
     * Externally modifying the provided content or the host element will
     * result in undefined rendering behavior.
     */
    function render(content, host) {
        var oldContent = Private.hostMap.get(host) || [];
        var newContent = Private.asContentArray(content);
        Private.hostMap.set(host, newContent);
        Private.updateContent(host, oldContent, newContent);
    }
    VirtualDOM.render = render;
})(VirtualDOM = exports.VirtualDOM || (exports.VirtualDOM = {}));
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * A weak mapping of host element to virtual DOM content.
     */
    Private.hostMap = new WeakMap();
    /**
     * Cast a content value to a content array.
     */
    function asContentArray(value) {
        if (!value) {
            return [];
        }
        if (value instanceof Array) {
            return value;
        }
        return [value];
    }
    Private.asContentArray = asContentArray;
    function createDOMNode(node) {
        // Create a text node for a virtual text node.
        if (node.type === 'text') {
            return document.createTextNode(node.content);
        }
        // Create the HTML element with the specified tag.
        var element = document.createElement(node.tag);
        // Add the attributes for the new element.
        addAttrs(element, node.attrs);
        // Recursively populate the element with child content.
        for (var i = 0, n = node.children.length; i < n; ++i) {
            element.appendChild(createDOMNode(node.children[i]));
        }
        // Return the populated element.
        return element;
    }
    Private.createDOMNode = createDOMNode;
    /**
     * Update a host element with the delta of the virtual content.
     *
     * This is the core "diff" algorithm. There is no explicit "patch"
     * phase. The host is patched at each step as the diff progresses.
     */
    function updateContent(host, oldContent, newContent) {
        // Bail early if the content is identical.
        if (oldContent === newContent) {
            return;
        }
        // Collect the old keyed elems into a mapping.
        var oldKeyed = collectKeys(host, oldContent);
        // Create a copy of the old content which can be modified in-place.
        var oldCopy = oldContent.slice();
        // Update the host with the new content. The diff always proceeds
        // forward and never modifies a previously visited index. The old
        // copy array is modified in-place to reflect the changes made to
        // the host children. This causes the stale nodes to be pushed to
        // the end of the host node and removed at the end of the loop.
        var currElem = host.firstChild;
        var newCount = newContent.length;
        for (var i = 0; i < newCount; ++i) {
            // If the old content is exhausted, create a new node.
            if (i >= oldCopy.length) {
                host.appendChild(createDOMNode(newContent[i]));
                continue;
            }
            // Lookup the old and new virtual nodes.
            var oldVNode = oldCopy[i];
            var newVNode = newContent[i];
            // If both elements are identical, there is nothing to do.
            if (oldVNode === newVNode) {
                currElem = currElem.nextSibling;
                continue;
            }
            // Handle the simplest case of in-place text update first.
            if (oldVNode.type === 'text' && newVNode.type === 'text') {
                currElem.textContent = newVNode.content;
                currElem = currElem.nextSibling;
                continue;
            }
            // If the old or new node is a text node, the other node is now
            // known to be an element node, so create and insert a new node.
            if (oldVNode.type === 'text' || newVNode.type === 'text') {
                algorithm_1.ArrayExt.insert(oldCopy, i, newVNode);
                host.insertBefore(createDOMNode(newVNode), currElem);
                continue;
            }
            // At this point, both nodes are known to be element nodes.
            // If the new elem is keyed, move an old keyed elem to the proper
            // location before proceeding with the diff. The search can start
            // at the current index, since the unmatched old keyed elems are
            // pushed forward in the old copy array.
            var newKey = newVNode.attrs.key;
            if (newKey && newKey in oldKeyed) {
                var pair = oldKeyed[newKey];
                if (pair.vNode !== oldVNode) {
                    algorithm_1.ArrayExt.move(oldCopy, oldCopy.indexOf(pair.vNode, i + 1), i);
                    host.insertBefore(pair.element, currElem);
                    oldVNode = pair.vNode;
                    currElem = pair.element;
                }
            }
            // If both elements are identical, there is nothing to do.
            if (oldVNode === newVNode) {
                currElem = currElem.nextSibling;
                continue;
            }
            // If the old elem is keyed and does not match the new elem key,
            // create a new node. This is necessary since the old keyed elem
            // may be matched at a later point in the diff.
            var oldKey = oldVNode.attrs.key;
            if (oldKey && oldKey !== newKey) {
                algorithm_1.ArrayExt.insert(oldCopy, i, newVNode);
                host.insertBefore(createDOMNode(newVNode), currElem);
                continue;
            }
            // If the tags are different, create a new node.
            if (oldVNode.tag !== newVNode.tag) {
                algorithm_1.ArrayExt.insert(oldCopy, i, newVNode);
                host.insertBefore(createDOMNode(newVNode), currElem);
                continue;
            }
            // At this point, the element can be updated in-place.
            // Update the element attributes.
            updateAttrs(currElem, oldVNode.attrs, newVNode.attrs);
            // Update the element content.
            updateContent(currElem, oldVNode.children, newVNode.children);
            // Step to the next sibling element.
            currElem = currElem.nextSibling;
        }
        // Dispose of the old nodes pushed to the end of the host.
        for (var i = oldCopy.length - newCount; i > 0; --i) {
            host.removeChild(host.lastChild);
        }
    }
    Private.updateContent = updateContent;
    /**
     * A set of special-cased attribute names.
     */
    var specialAttrs = {
        'key': true,
        'className': true,
        'htmlFor': true,
        'dataset': true,
        'style': true,
    };
    /**
     * Add element attributes to a newly created HTML element.
     */
    function addAttrs(element, attrs) {
        // Add the inline event listeners and node attributes.
        for (var name_1 in attrs) {
            if (name_1 in specialAttrs) {
                continue;
            }
            if (name_1.substr(0, 2) === 'on') {
                element[name_1] = attrs[name_1];
            }
            else {
                element.setAttribute(name_1, attrs[name_1]);
            }
        }
        // Add the element `class` attribute.
        if (attrs.className !== undefined) {
            element.setAttribute('class', attrs.className);
        }
        // Add the element `for` attribute.
        if (attrs.htmlFor !== undefined) {
            element.setAttribute('for', attrs.htmlFor);
        }
        // Add the dataset values.
        if (attrs.dataset) {
            addDataset(element, attrs.dataset);
        }
        // Add the inline styles.
        if (attrs.style) {
            addStyle(element, attrs.style);
        }
    }
    /**
     * Update the element attributes of an HTML element.
     */
    function updateAttrs(element, oldAttrs, newAttrs) {
        // Do nothing if the attrs are the same object.
        if (oldAttrs === newAttrs) {
            return;
        }
        // Setup the strongly typed loop variable.
        var name;
        // Remove attributes and listeners which no longer exist.
        for (name in oldAttrs) {
            if (name in specialAttrs || name in newAttrs) {
                continue;
            }
            if (name.substr(0, 2) === 'on') {
                element[name] = null;
            }
            else {
                element.removeAttribute(name);
            }
        }
        // Add and update new and existing attributes and listeners.
        for (name in newAttrs) {
            if (name in specialAttrs || oldAttrs[name] === newAttrs[name]) {
                continue;
            }
            if (name.substr(0, 2) === 'on') {
                element[name] = newAttrs[name];
            }
            else {
                element.setAttribute(name, newAttrs[name]);
            }
        }
        // Update the element `class` attribute.
        if (oldAttrs.className !== newAttrs.className) {
            if (newAttrs.className !== undefined) {
                element.setAttribute('class', newAttrs.className);
            }
            else {
                element.removeAttribute('class');
            }
        }
        // Add the element `for` attribute.
        if (oldAttrs.htmlFor !== newAttrs.htmlFor) {
            if (newAttrs.htmlFor !== undefined) {
                element.setAttribute('for', newAttrs.htmlFor);
            }
            else {
                element.removeAttribute('for');
            }
        }
        // Update the dataset values.
        if (oldAttrs.dataset !== newAttrs.dataset) {
            updateDataset(element, oldAttrs.dataset || {}, newAttrs.dataset || {});
        }
        // Update the inline styles.
        if (oldAttrs.style !== newAttrs.style) {
            updateStyle(element, oldAttrs.style || {}, newAttrs.style || {});
        }
    }
    /**
     * Add dataset values to a newly created HTML element.
     */
    function addDataset(element, dataset) {
        for (var name_2 in dataset) {
            element.setAttribute("data-" + name_2, dataset[name_2]);
        }
    }
    /**
     * Update the dataset values of an HTML element.
     */
    function updateDataset(element, oldDataset, newDataset) {
        for (var name_3 in oldDataset) {
            if (!(name_3 in newDataset)) {
                element.removeAttribute("data-" + name_3);
            }
        }
        for (var name_4 in newDataset) {
            if (oldDataset[name_4] !== newDataset[name_4]) {
                element.setAttribute("data-" + name_4, newDataset[name_4]);
            }
        }
    }
    /**
     * Add inline style values to a newly created HTML element.
     */
    function addStyle(element, style) {
        var elemStyle = element.style;
        var name;
        for (name in style) {
            elemStyle[name] = style[name];
        }
    }
    /**
     * Update the inline style values of an HTML element.
     */
    function updateStyle(element, oldStyle, newStyle) {
        var elemStyle = element.style;
        var name;
        for (name in oldStyle) {
            if (!(name in newStyle)) {
                elemStyle[name] = '';
            }
        }
        for (name in newStyle) {
            if (oldStyle[name] !== newStyle[name]) {
                elemStyle[name] = newStyle[name];
            }
        }
    }
    /**
     * Collect a mapping of keyed elements for the host content.
     */
    function collectKeys(host, content) {
        var node = host.firstChild;
        var keyMap = Object.create(null);
        for (var _i = 0, content_1 = content; _i < content_1.length; _i++) {
            var vNode = content_1[_i];
            if (vNode.type === 'element' && vNode.attrs.key) {
                keyMap[vNode.attrs.key] = { vNode: vNode, element: node };
            }
            node = node.nextSibling;
        }
        return keyMap;
    }
})(Private || (Private = {}));


/***/ }),

/***/ "GwDy":
/*!********************************************!*\
  !*** ./node_modules/mdi-react/StarIcon.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var StarIcon = function StarIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M12,17.27L18.18,21L16.54,13.97L22,9.24L14.81,8.62L12,2L9.19,8.62L2,9.24L7.45,13.97L5.82,21L12,17.27Z' })
  );
};

module.exports = StarIcon;


/***/ }),

/***/ "Gxzi":
/*!*******************************************************!*\
  !*** ./node_modules/@phosphor/algorithm/lib/range.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/**
 * Create an iterator of evenly spaced values.
 *
 * @param start - The starting value for the range, inclusive.
 *
 * @param stop - The stopping value for the range, exclusive.
 *
 * @param step - The distance between each value.
 *
 * @returns An iterator which produces evenly spaced values.
 *
 * #### Notes
 * In the single argument form of `range(stop)`, `start` defaults to
 * `0` and `step` defaults to `1`.
 *
 * In the two argument form of `range(start, stop)`, `step` defaults
 * to `1`.
 */
function range(start, stop, step) {
    if (stop === undefined) {
        return new RangeIterator(0, start, 1);
    }
    if (step === undefined) {
        return new RangeIterator(start, stop, 1);
    }
    return new RangeIterator(start, stop, step);
}
exports.range = range;
/**
 * An iterator which produces a range of evenly spaced values.
 */
var RangeIterator = (function () {
    /**
     * Construct a new range iterator.
     *
     * @param start - The starting value for the range, inclusive.
     *
     * @param stop - The stopping value for the range, exclusive.
     *
     * @param step - The distance between each value.
     */
    function RangeIterator(start, stop, step) {
        this._index = 0;
        this._start = start;
        this._stop = stop;
        this._step = step;
        this._length = Private.rangeLength(start, stop, step);
    }
    /**
     * Get an iterator over the object's values.
     *
     * @returns An iterator which yields the object's values.
     */
    RangeIterator.prototype.iter = function () {
        return this;
    };
    /**
     * Create an independent clone of the iterator.
     *
     * @returns A new independent clone of the iterator.
     */
    RangeIterator.prototype.clone = function () {
        var result = new RangeIterator(this._start, this._stop, this._step);
        result._index = this._index;
        return result;
    };
    /**
     * Get the next value from the iterator.
     *
     * @returns The next value from the iterator, or `undefined`.
     */
    RangeIterator.prototype.next = function () {
        if (this._index >= this._length) {
            return undefined;
        }
        return this._start + this._step * this._index++;
    };
    return RangeIterator;
}());
exports.RangeIterator = RangeIterator;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * Compute the effective length of a range.
     *
     * @param start - The starting value for the range, inclusive.
     *
     * @param stop - The stopping value for the range, exclusive.
     *
     * @param step - The distance between each value.
     *
     * @returns The number of steps need to traverse the range.
     */
    function rangeLength(start, stop, step) {
        if (step === 0) {
            return Infinity;
        }
        if (start > stop && step > 0) {
            return 0;
        }
        if (start < stop && step < 0) {
            return 0;
        }
        return Math.ceil((stop - start) / step);
    }
    Private.rangeLength = rangeLength;
})(Private || (Private = {}));


/***/ }),

/***/ "H+vO":
/*!*******************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/sidebar/SidebarItem.js ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var SidebarItem = function (_Component) {
  _inherits(SidebarItem, _Component);

  function SidebarItem() {
    _classCallCheck(this, SidebarItem);

    return _possibleConstructorReturn(this, (SidebarItem.__proto__ || Object.getPrototypeOf(SidebarItem)).apply(this, arguments));
  }

  _createClass(SidebarItem, [{
    key: 'render',
    value: function render() {
      var _props = this.props,
          onClick = _props.onClick,
          label = _props.label,
          active = _props.active;

      return _react2.default.createElement(
        'div',
        { onClick: onClick, className: (0, _lib.bem)('sidebar__item', [active ? 'is-active' : '']) },
        _react2.default.createElement(
          'div',
          { className: (0, _lib.bem)('sidebar__item', 'wrapper') },
          _react2.default.createElement(
            'div',
            { className: (0, _lib.bem)('sidebar__item', 'label') },
            label
          )
        )
      );
    }
  }]);

  return SidebarItem;
}(_react.Component);

exports.default = SidebarItem;


SidebarItem.propTypes = {
  active: _propTypes2.default.bool,
  label: _propTypes2.default.string,
  onClick: _propTypes2.default.func
};
//# sourceMappingURL=SidebarItem.js.map

/***/ }),

/***/ "H+yo":
/*!********************************************!*\
  !*** ./node_modules/des.js/lib/des/ede.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var assert = __webpack_require__(/*! minimalistic-assert */ "2j6C");
var inherits = __webpack_require__(/*! inherits */ "P7XM");

var des = __webpack_require__(/*! ../des */ "FUXG");
var Cipher = des.Cipher;
var DES = des.DES;

function EDEState(type, key) {
  assert.equal(key.length, 24, 'Invalid key length');

  var k1 = key.slice(0, 8);
  var k2 = key.slice(8, 16);
  var k3 = key.slice(16, 24);

  if (type === 'encrypt') {
    this.ciphers = [
      DES.create({ type: 'encrypt', key: k1 }),
      DES.create({ type: 'decrypt', key: k2 }),
      DES.create({ type: 'encrypt', key: k3 })
    ];
  } else {
    this.ciphers = [
      DES.create({ type: 'decrypt', key: k3 }),
      DES.create({ type: 'encrypt', key: k2 }),
      DES.create({ type: 'decrypt', key: k1 })
    ];
  }
}

function EDE(options) {
  Cipher.call(this, options);

  var state = new EDEState(this.type, this.options.key);
  this._edeState = state;
}
inherits(EDE, Cipher);

module.exports = EDE;

EDE.create = function create(options) {
  return new EDE(options);
};

EDE.prototype._update = function _update(inp, inOff, out, outOff) {
  var state = this._edeState;

  state.ciphers[0]._update(inp, inOff, out, outOff);
  state.ciphers[1]._update(out, outOff, out, outOff);
  state.ciphers[2]._update(out, outOff, out, outOff);
};

EDE.prototype._pad = DES.prototype._pad;
EDE.prototype._unpad = DES.prototype._unpad;


/***/ }),

/***/ "H1Ta":
/*!************************************************************!*\
  !*** ./node_modules/font-awesome/css/font-awesome.min.css ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../css-loader!./font-awesome.min.css */ "GNWD");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "H54+":
/*!*****************************************************!*\
  !*** ./node_modules/xterm/lib/utils/CharMeasure.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var EventEmitter_1 = __webpack_require__(/*! ../EventEmitter */ "t2YR");
var CharMeasure = (function (_super) {
    __extends(CharMeasure, _super);
    function CharMeasure(document, parentElement) {
        var _this = _super.call(this) || this;
        _this._document = document;
        _this._parentElement = parentElement;
        _this._measureElement = _this._document.createElement('span');
        _this._measureElement.classList.add('xterm-char-measure-element');
        _this._measureElement.textContent = 'W';
        _this._measureElement.setAttribute('aria-hidden', 'true');
        _this._parentElement.appendChild(_this._measureElement);
        return _this;
    }
    Object.defineProperty(CharMeasure.prototype, "width", {
        get: function () {
            return this._width;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(CharMeasure.prototype, "height", {
        get: function () {
            return this._height;
        },
        enumerable: true,
        configurable: true
    });
    CharMeasure.prototype.measure = function (options) {
        this._measureElement.style.fontFamily = options.fontFamily;
        this._measureElement.style.fontSize = options.fontSize + "px";
        var geometry = this._measureElement.getBoundingClientRect();
        if (geometry.width === 0 || geometry.height === 0) {
            return;
        }
        if (this._width !== geometry.width || this._height !== geometry.height) {
            this._width = geometry.width;
            this._height = Math.ceil(geometry.height);
            this.emit('charsizechanged');
        }
    };
    return CharMeasure;
}(EventEmitter_1.EventEmitter));
exports.CharMeasure = CharMeasure;

//# sourceMappingURL=CharMeasure.js.map


/***/ }),

/***/ "H7Er":
/*!**********************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/cells/style/index.css ***!
  \**********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports
exports.i(__webpack_require__(/*! -!../../../css-loader!./collapser.css */ "Tco+"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./headerfooter.css */ "5p9q"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./inputarea.css */ "+KPr"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./placeholder.css */ "I3K3"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./widget.css */ "AS1u"), "");

// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n/*-----------------------------------------------------------------------------\n| Imports\n|----------------------------------------------------------------------------*/\n", ""]);

// exports


/***/ }),

/***/ "H7PE":
/*!*********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/DropdownCustom.js ***!
  \*********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UnconnectedDropdownCustom = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _constants = __webpack_require__(/*! ../../lib/constants */ "5Bkx");

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _Dropdown = __webpack_require__(/*! ../widgets/Dropdown */ "9Rtb");

var _Dropdown2 = _interopRequireDefault(_Dropdown);

var _Text = __webpack_require__(/*! ./Text */ "CQ7X");

var _Text2 = _interopRequireDefault(_Text);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UnconnectedDropdownCustom = exports.UnconnectedDropdownCustom = function (_Component) {
  _inherits(UnconnectedDropdownCustom, _Component);

  function UnconnectedDropdownCustom(props, context) {
    _classCallCheck(this, UnconnectedDropdownCustom);

    var _this = _possibleConstructorReturn(this, (UnconnectedDropdownCustom.__proto__ || Object.getPrototypeOf(UnconnectedDropdownCustom)).call(this, props, context));

    _this.setValue = _this.setValue.bind(_this);
    _this.setLocals = _this.setLocals.bind(_this);

    _this.setLocals(props);

    _this.state = {
      custom: _this.value === props.customOpt || !_this.props.options.map(function (o) {
        return o.value;
      }).includes(_this.value)
    };
    return _this;
  }

  _createClass(UnconnectedDropdownCustom, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(props) {
      this.setLocals(props);
    }
  }, {
    key: 'setLocals',
    value: function setLocals(props) {
      this.value = props.fullValue === undefined || props.fullValue === _constants.MULTI_VALUED_PLACEHOLDER // eslint-disable-line no-undefined
      ? this.props.defaultOpt : props.fullValue;
    }
  }, {
    key: 'setValue',
    value: function setValue(value) {
      var custom = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

      this.value = value;
      var customOpt = this.props.customOpt;
      this.setState({
        custom: (custom || value === customOpt) && value !== ''
      });
      this.props.updateContainer(_defineProperty({}, this.props.attr, value === customOpt && !custom ? customOpt : value));
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _props = this.props,
          options = _props.options,
          attr = _props.attr,
          customOpt = _props.customOpt;

      var value = (this.value === '' || !options.map(function (o) {
        return o.value;
      }).includes(this.value)) && this.state.custom ? customOpt : this.value;

      return _react2.default.createElement(
        _Field2.default,
        this.props,
        _react2.default.createElement(_Dropdown2.default, {
          backgroundDark: this.props.backgroundDark,
          options: options,
          value: value,
          onChange: this.setValue,
          clearable: this.props.clearable,
          optionRenderer: this.props.optionRenderer,
          valueRenderer: this.props.valueRenderer,
          placeholder: this.props.placeholder
        }),
        this.state.custom && _react2.default.createElement(_Text2.default, {
          attr: attr,
          updatePlot: function updatePlot(value) {
            return _this2.setValue(value, true);
          },
          onChange: function onChange(value) {
            if (value) {
              _this2.setValue(value, true);
            }
          }
        })
      );
    }
  }]);

  return UnconnectedDropdownCustom;
}(_react.Component);

UnconnectedDropdownCustom.propTypes = _extends({
  fullValue: _propTypes2.default.any,
  updatePlot: _propTypes2.default.func,
  clearable: _propTypes2.default.bool,
  defaultOpt: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.bool, _propTypes2.default.string]),
  customOpt: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.bool, _propTypes2.default.string]),
  label: _propTypes2.default.string,
  attr: _propTypes2.default.string
}, _Field2.default.propTypes);

UnconnectedDropdownCustom.contextTypes = {
  updateContainer: _propTypes2.default.func
};

exports.default = (0, _lib.connectToContainer)(UnconnectedDropdownCustom);
//# sourceMappingURL=DropdownCustom.js.map

/***/ }),

/***/ "H7XF":
/*!*****************************************!*\
  !*** ./node_modules/base64-js/index.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray

var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array

var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
  lookup[i] = code[i]
  revLookup[code.charCodeAt(i)] = i
}

// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63

function getLens (b64) {
  var len = b64.length

  if (len % 4 > 0) {
    throw new Error('Invalid string. Length must be a multiple of 4')
  }

  // Trim off extra bytes after placeholder bytes are found
  // See: https://github.com/beatgammit/base64-js/issues/42
  var validLen = b64.indexOf('=')
  if (validLen === -1) validLen = len

  var placeHoldersLen = validLen === len
    ? 0
    : 4 - (validLen % 4)

  return [validLen, placeHoldersLen]
}

// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function _byteLength (b64, validLen, placeHoldersLen) {
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function toByteArray (b64) {
  var tmp
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]

  var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))

  var curByte = 0

  // if there are placeholders, only get up to the last complete 4 chars
  var len = placeHoldersLen > 0
    ? validLen - 4
    : validLen

  for (var i = 0; i < len; i += 4) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 18) |
      (revLookup[b64.charCodeAt(i + 1)] << 12) |
      (revLookup[b64.charCodeAt(i + 2)] << 6) |
      revLookup[b64.charCodeAt(i + 3)]
    arr[curByte++] = (tmp >> 16) & 0xFF
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 2) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 2) |
      (revLookup[b64.charCodeAt(i + 1)] >> 4)
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 1) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 10) |
      (revLookup[b64.charCodeAt(i + 1)] << 4) |
      (revLookup[b64.charCodeAt(i + 2)] >> 2)
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  return arr
}

function tripletToBase64 (num) {
  return lookup[num >> 18 & 0x3F] +
    lookup[num >> 12 & 0x3F] +
    lookup[num >> 6 & 0x3F] +
    lookup[num & 0x3F]
}

function encodeChunk (uint8, start, end) {
  var tmp
  var output = []
  for (var i = start; i < end; i += 3) {
    tmp =
      ((uint8[i] << 16) & 0xFF0000) +
      ((uint8[i + 1] << 8) & 0xFF00) +
      (uint8[i + 2] & 0xFF)
    output.push(tripletToBase64(tmp))
  }
  return output.join('')
}

function fromByteArray (uint8) {
  var tmp
  var len = uint8.length
  var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  var parts = []
  var maxChunkLength = 16383 // must be multiple of 3

  // go through the array every three bytes, we'll deal with trailing stuff later
  for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
    parts.push(encodeChunk(
      uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
    ))
  }

  // pad the end with zeros, but make sure to not forget the extra bytes
  if (extraBytes === 1) {
    tmp = uint8[len - 1]
    parts.push(
      lookup[tmp >> 2] +
      lookup[(tmp << 4) & 0x3F] +
      '=='
    )
  } else if (extraBytes === 2) {
    tmp = (uint8[len - 2] << 8) + uint8[len - 1]
    parts.push(
      lookup[tmp >> 10] +
      lookup[(tmp >> 4) & 0x3F] +
      lookup[(tmp << 2) & 0x3F] +
      '='
    )
  }

  return parts.join('')
}


/***/ }),

/***/ "H8ED":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/be.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


function plural(word, num) {
    var forms = word.split('_');
    return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]);
}
function relativeTimeWithPlural(number, withoutSuffix, key) {
    var format = {
        'ss': withoutSuffix ? 'секунда_секунды_секунд' : 'секунду_секунды_секунд',
        'mm': withoutSuffix ? 'хвіліна_хвіліны_хвілін' : 'хвіліну_хвіліны_хвілін',
        'hh': withoutSuffix ? 'гадзіна_гадзіны_гадзін' : 'гадзіну_гадзіны_гадзін',
        'dd': 'дзень_дні_дзён',
        'MM': 'месяц_месяцы_месяцаў',
        'yy': 'год_гады_гадоў'
    };
    if (key === 'm') {
        return withoutSuffix ? 'хвіліна' : 'хвіліну';
    }
    else if (key === 'h') {
        return withoutSuffix ? 'гадзіна' : 'гадзіну';
    }
    else {
        return number + ' ' + plural(format[key], +number);
    }
}

var be = moment.defineLocale('be', {
    months : {
        format: 'студзеня_лютага_сакавіка_красавіка_траўня_чэрвеня_ліпеня_жніўня_верасня_кастрычніка_лістапада_снежня'.split('_'),
        standalone: 'студзень_люты_сакавік_красавік_травень_чэрвень_ліпень_жнівень_верасень_кастрычнік_лістапад_снежань'.split('_')
    },
    monthsShort : 'студ_лют_сак_крас_трав_чэрв_ліп_жнів_вер_каст_ліст_снеж'.split('_'),
    weekdays : {
        format: 'нядзелю_панядзелак_аўторак_сераду_чацвер_пятніцу_суботу'.split('_'),
        standalone: 'нядзеля_панядзелак_аўторак_серада_чацвер_пятніца_субота'.split('_'),
        isFormat: /\[ ?[Вв] ?(?:мінулую|наступную)? ?\] ?dddd/
    },
    weekdaysShort : 'нд_пн_ат_ср_чц_пт_сб'.split('_'),
    weekdaysMin : 'нд_пн_ат_ср_чц_пт_сб'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D MMMM YYYY г.',
        LLL : 'D MMMM YYYY г., HH:mm',
        LLLL : 'dddd, D MMMM YYYY г., HH:mm'
    },
    calendar : {
        sameDay: '[Сёння ў] LT',
        nextDay: '[Заўтра ў] LT',
        lastDay: '[Учора ў] LT',
        nextWeek: function () {
            return '[У] dddd [ў] LT';
        },
        lastWeek: function () {
            switch (this.day()) {
                case 0:
                case 3:
                case 5:
                case 6:
                    return '[У мінулую] dddd [ў] LT';
                case 1:
                case 2:
                case 4:
                    return '[У мінулы] dddd [ў] LT';
            }
        },
        sameElse: 'L'
    },
    relativeTime : {
        future : 'праз %s',
        past : '%s таму',
        s : 'некалькі секунд',
        m : relativeTimeWithPlural,
        mm : relativeTimeWithPlural,
        h : relativeTimeWithPlural,
        hh : relativeTimeWithPlural,
        d : 'дзень',
        dd : relativeTimeWithPlural,
        M : 'месяц',
        MM : relativeTimeWithPlural,
        y : 'год',
        yy : relativeTimeWithPlural
    },
    meridiemParse: /ночы|раніцы|дня|вечара/,
    isPM : function (input) {
        return /^(дня|вечара)$/.test(input);
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 4) {
            return 'ночы';
        } else if (hour < 12) {
            return 'раніцы';
        } else if (hour < 17) {
            return 'дня';
        } else {
            return 'вечара';
        }
    },
    dayOfMonthOrdinalParse: /\d{1,2}-(і|ы|га)/,
    ordinal: function (number, period) {
        switch (period) {
            case 'M':
            case 'd':
            case 'DDD':
            case 'w':
            case 'W':
                return (number % 10 === 2 || number % 10 === 3) && (number % 100 !== 12 && number % 100 !== 13) ? number + '-і' : number + '-ы';
            case 'D':
                return number + '-га';
            default:
                return number;
        }
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return be;

})));


/***/ }),

/***/ "H8j4":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_mapCacheSet.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getMapData = __webpack_require__(/*! ./_getMapData */ "QkVE");

/**
 * 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;
}

module.exports = mapCacheSet;


/***/ }),

/***/ "HDyB":
/*!********************************************!*\
  !*** ./node_modules/lodash/_equalByTag.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Symbol = __webpack_require__(/*! ./_Symbol */ "nmnc"),
    Uint8Array = __webpack_require__(/*! ./_Uint8Array */ "JHRd"),
    eq = __webpack_require__(/*! ./eq */ "ljhN"),
    equalArrays = __webpack_require__(/*! ./_equalArrays */ "or5M"),
    mapToArray = __webpack_require__(/*! ./_mapToArray */ "7fqy"),
    setToArray = __webpack_require__(/*! ./_setToArray */ "rEGp");

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
    COMPARE_UNORDERED_FLAG = 2;

/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
    dateTag = '[object Date]',
    errorTag = '[object Error]',
    mapTag = '[object Map]',
    numberTag = '[object Number]',
    regexpTag = '[object RegExp]',
    setTag = '[object Set]',
    stringTag = '[object String]',
    symbolTag = '[object Symbol]';

var arrayBufferTag = '[object ArrayBuffer]',
    dataViewTag = '[object DataView]';

/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
    symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;

/**
 * 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;
}

module.exports = equalByTag;


/***/ }),

/***/ "HEBY":
/*!***********************************************************************!*\
  !*** ./node_modules/draft-js/lib/keyCommandBackspaceToStartOfLine.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule keyCommandBackspaceToStartOfLine
 * @format
 * 
 */



var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");

var expandRangeToStartOfLine = __webpack_require__(/*! ./expandRangeToStartOfLine */ "HezI");
var getDraftEditorSelectionWithNodes = __webpack_require__(/*! ./getDraftEditorSelectionWithNodes */ "ISee");
var moveSelectionBackward = __webpack_require__(/*! ./moveSelectionBackward */ "kWjT");
var removeTextWithStrategy = __webpack_require__(/*! ./removeTextWithStrategy */ "8d//");

function keyCommandBackspaceToStartOfLine(editorState) {
  var afterRemoval = removeTextWithStrategy(editorState, function (strategyState) {
    var selection = strategyState.getSelection();
    if (selection.isCollapsed() && selection.getAnchorOffset() === 0) {
      return moveSelectionBackward(strategyState, 1);
    }

    var domSelection = global.getSelection();
    var range = domSelection.getRangeAt(0);
    range = expandRangeToStartOfLine(range);

    return getDraftEditorSelectionWithNodes(strategyState, null, range.endContainer, range.endOffset, range.startContainer, range.startOffset).selectionState;
  }, 'backward');

  if (afterRemoval === editorState.getCurrentContent()) {
    return editorState;
  }

  return EditorState.push(editorState, afterRemoval, 'remove-range');
}

module.exports = keyCommandBackspaceToStartOfLine;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "HEbw":
/*!*************************************************!*\
  !*** ./node_modules/crypto-browserify/index.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = __webpack_require__(/*! randombytes */ "Edxu")
exports.createHash = exports.Hash = __webpack_require__(/*! create-hash */ "mObS")
exports.createHmac = exports.Hmac = __webpack_require__(/*! create-hmac */ "Giow")

var algos = __webpack_require__(/*! browserify-sign/algos */ "EW2V")
var algoKeys = Object.keys(algos)
var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys)
exports.getHashes = function () {
  return hashes
}

var p = __webpack_require__(/*! pbkdf2 */ "oJl4")
exports.pbkdf2 = p.pbkdf2
exports.pbkdf2Sync = p.pbkdf2Sync

var aes = __webpack_require__(/*! browserify-cipher */ "lWpZ")

exports.Cipher = aes.Cipher
exports.createCipher = aes.createCipher
exports.Cipheriv = aes.Cipheriv
exports.createCipheriv = aes.createCipheriv
exports.Decipher = aes.Decipher
exports.createDecipher = aes.createDecipher
exports.Decipheriv = aes.Decipheriv
exports.createDecipheriv = aes.createDecipheriv
exports.getCiphers = aes.getCiphers
exports.listCiphers = aes.listCiphers

var dh = __webpack_require__(/*! diffie-hellman */ "ANxK")

exports.DiffieHellmanGroup = dh.DiffieHellmanGroup
exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup
exports.getDiffieHellman = dh.getDiffieHellman
exports.createDiffieHellman = dh.createDiffieHellman
exports.DiffieHellman = dh.DiffieHellman

var sign = __webpack_require__(/*! browserify-sign */ "tpL1")

exports.createSign = sign.createSign
exports.Sign = sign.Sign
exports.createVerify = sign.createVerify
exports.Verify = sign.Verify

exports.createECDH = __webpack_require__(/*! create-ecdh */ "4dMO")

var publicEncrypt = __webpack_require__(/*! public-encrypt */ "ZEK9")

exports.publicEncrypt = publicEncrypt.publicEncrypt
exports.privateEncrypt = publicEncrypt.privateEncrypt
exports.publicDecrypt = publicEncrypt.publicDecrypt
exports.privateDecrypt = publicEncrypt.privateDecrypt

// the least I can do is make error messages for the rest of the node.js/crypto api.
// ;[
//   'createCredentials'
// ].forEach(function (name) {
//   exports[name] = function () {
//     throw new Error([
//       'sorry, ' + name + ' is not implemented yet',
//       'we accept pull requests',
//       'https://github.com/crypto-browserify/crypto-browserify'
//     ].join('\n'))
//   }
// })

var rf = __webpack_require__(/*! randomfill */ "dcwN")

exports.randomFill = rf.randomFill
exports.randomFillSync = rf.randomFillSync

exports.createCredentials = function () {
  throw new Error([
    'sorry, createCredentials is not implemented yet',
    'we accept pull requests',
    'https://github.com/crypto-browserify/crypto-browserify'
  ].join('\n'))
}

exports.constants = {
  'DH_CHECK_P_NOT_SAFE_PRIME': 2,
  'DH_CHECK_P_NOT_PRIME': 1,
  'DH_UNABLE_TO_CHECK_GENERATOR': 4,
  'DH_NOT_SUITABLE_GENERATOR': 8,
  'NPN_ENABLED': 1,
  'ALPN_ENABLED': 1,
  'RSA_PKCS1_PADDING': 1,
  'RSA_SSLV23_PADDING': 2,
  'RSA_NO_PADDING': 3,
  'RSA_PKCS1_OAEP_PADDING': 4,
  'RSA_X931_PADDING': 5,
  'RSA_PKCS1_PSS_PADDING': 6,
  'POINT_CONVERSION_COMPRESSED': 2,
  'POINT_CONVERSION_UNCOMPRESSED': 4,
  'POINT_CONVERSION_HYBRID': 6
}


/***/ }),

/***/ "HHOg":
/*!************************************************************!*\
  !*** ./node_modules/xterm/lib/renderer/BaseRenderLayer.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var Types_1 = __webpack_require__(/*! ./atlas/Types */ "2+Wn");
var Types_2 = __webpack_require__(/*! ../shared/atlas/Types */ "S8N9");
var CharAtlas_1 = __webpack_require__(/*! ./atlas/CharAtlas */ "y1AW");
var Buffer_1 = __webpack_require__(/*! ../Buffer */ "MsZC");
var BaseRenderLayer = (function () {
    function BaseRenderLayer(_container, id, zIndex, _alpha, _colors) {
        this._container = _container;
        this._alpha = _alpha;
        this._colors = _colors;
        this._scaledCharWidth = 0;
        this._scaledCharHeight = 0;
        this._scaledCellWidth = 0;
        this._scaledCellHeight = 0;
        this._scaledCharLeft = 0;
        this._scaledCharTop = 0;
        this._canvas = document.createElement('canvas');
        this._canvas.classList.add("xterm-" + id + "-layer");
        this._canvas.style.zIndex = zIndex.toString();
        this._initCanvas();
        this._container.appendChild(this._canvas);
    }
    BaseRenderLayer.prototype._initCanvas = function () {
        this._ctx = this._canvas.getContext('2d', { alpha: this._alpha });
        if (!this._alpha) {
            this.clearAll();
        }
    };
    BaseRenderLayer.prototype.onOptionsChanged = function (terminal) { };
    BaseRenderLayer.prototype.onBlur = function (terminal) { };
    BaseRenderLayer.prototype.onFocus = function (terminal) { };
    BaseRenderLayer.prototype.onCursorMove = function (terminal) { };
    BaseRenderLayer.prototype.onGridChanged = function (terminal, startRow, endRow) { };
    BaseRenderLayer.prototype.onSelectionChanged = function (terminal, start, end) { };
    BaseRenderLayer.prototype.onThemeChanged = function (terminal, colorSet) {
        this._refreshCharAtlas(terminal, colorSet);
    };
    BaseRenderLayer.prototype.setTransparency = function (terminal, alpha) {
        if (alpha === this._alpha) {
            return;
        }
        var oldCanvas = this._canvas;
        this._alpha = alpha;
        this._canvas = this._canvas.cloneNode();
        this._initCanvas();
        this._container.replaceChild(this._canvas, oldCanvas);
        this._refreshCharAtlas(terminal, this._colors);
        this.onGridChanged(terminal, 0, terminal.rows - 1);
    };
    BaseRenderLayer.prototype._refreshCharAtlas = function (terminal, colorSet) {
        var _this = this;
        if (this._scaledCharWidth <= 0 && this._scaledCharHeight <= 0) {
            return;
        }
        this._charAtlas = null;
        var result = CharAtlas_1.acquireCharAtlas(terminal, colorSet, this._scaledCharWidth, this._scaledCharHeight);
        if (result instanceof HTMLCanvasElement) {
            this._charAtlas = result;
        }
        else {
            result.then(function (bitmap) { return _this._charAtlas = bitmap; });
        }
    };
    BaseRenderLayer.prototype.resize = function (terminal, dim) {
        this._scaledCellWidth = dim.scaledCellWidth;
        this._scaledCellHeight = dim.scaledCellHeight;
        this._scaledCharWidth = dim.scaledCharWidth;
        this._scaledCharHeight = dim.scaledCharHeight;
        this._scaledCharLeft = dim.scaledCharLeft;
        this._scaledCharTop = dim.scaledCharTop;
        this._canvas.width = dim.scaledCanvasWidth;
        this._canvas.height = dim.scaledCanvasHeight;
        this._canvas.style.width = dim.canvasWidth + "px";
        this._canvas.style.height = dim.canvasHeight + "px";
        if (!this._alpha) {
            this.clearAll();
        }
        this._refreshCharAtlas(terminal, this._colors);
    };
    BaseRenderLayer.prototype.fillCells = function (x, y, width, height) {
        this._ctx.fillRect(x * this._scaledCellWidth, y * this._scaledCellHeight, width * this._scaledCellWidth, height * this._scaledCellHeight);
    };
    BaseRenderLayer.prototype.fillBottomLineAtCells = function (x, y, width) {
        if (width === void 0) { width = 1; }
        this._ctx.fillRect(x * this._scaledCellWidth, (y + 1) * this._scaledCellHeight - window.devicePixelRatio - 1, width * this._scaledCellWidth, window.devicePixelRatio);
    };
    BaseRenderLayer.prototype.fillLeftLineAtCell = function (x, y) {
        this._ctx.fillRect(x * this._scaledCellWidth, y * this._scaledCellHeight, window.devicePixelRatio, this._scaledCellHeight);
    };
    BaseRenderLayer.prototype.strokeRectAtCell = function (x, y, width, height) {
        this._ctx.lineWidth = window.devicePixelRatio;
        this._ctx.strokeRect(x * this._scaledCellWidth + window.devicePixelRatio / 2, y * this._scaledCellHeight + (window.devicePixelRatio / 2), width * this._scaledCellWidth - window.devicePixelRatio, (height * this._scaledCellHeight) - window.devicePixelRatio);
    };
    BaseRenderLayer.prototype.clearAll = function () {
        if (this._alpha) {
            this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);
        }
        else {
            this._ctx.fillStyle = this._colors.background.css;
            this._ctx.fillRect(0, 0, this._canvas.width, this._canvas.height);
        }
    };
    BaseRenderLayer.prototype.clearCells = function (x, y, width, height) {
        if (this._alpha) {
            this._ctx.clearRect(x * this._scaledCellWidth, y * this._scaledCellHeight, width * this._scaledCellWidth, height * this._scaledCellHeight);
        }
        else {
            this._ctx.fillStyle = this._colors.background.css;
            this._ctx.fillRect(x * this._scaledCellWidth, y * this._scaledCellHeight, width * this._scaledCellWidth, height * this._scaledCellHeight);
        }
    };
    BaseRenderLayer.prototype.fillCharTrueColor = function (terminal, charData, x, y) {
        this._ctx.font = this._getFont(terminal, false);
        this._ctx.textBaseline = 'top';
        this._clipRow(terminal, y);
        this._ctx.fillText(charData[Buffer_1.CHAR_DATA_CHAR_INDEX], x * this._scaledCellWidth + this._scaledCharLeft, y * this._scaledCellHeight + this._scaledCharTop);
    };
    BaseRenderLayer.prototype.drawChar = function (terminal, char, code, width, x, y, fg, bg, bold, dim) {
        var colorIndex = 0;
        if (fg < 256) {
            colorIndex = fg + 2;
        }
        else {
            if (bold && terminal.options.enableBold) {
                colorIndex = 1;
            }
        }
        var isAscii = code < 256;
        var isBasicColor = (colorIndex > 1 && fg < 16) && (fg < 8 || bold);
        var isDefaultColor = fg >= 256;
        var isDefaultBackground = bg >= 256;
        if (this._charAtlas && isAscii && (isBasicColor || isDefaultColor) && isDefaultBackground) {
            var charAtlasCellWidth = this._scaledCharWidth + Types_2.CHAR_ATLAS_CELL_SPACING;
            var charAtlasCellHeight = this._scaledCharHeight + Types_2.CHAR_ATLAS_CELL_SPACING;
            if (dim) {
                this._ctx.globalAlpha = Types_1.DIM_OPACITY;
            }
            if (bold && !terminal.options.enableBold) {
                if (colorIndex > 1) {
                    colorIndex -= 8;
                }
            }
            this._ctx.drawImage(this._charAtlas, code * charAtlasCellWidth, colorIndex * charAtlasCellHeight, charAtlasCellWidth, this._scaledCharHeight, x * this._scaledCellWidth + this._scaledCharLeft, y * this._scaledCellHeight + this._scaledCharTop, charAtlasCellWidth, this._scaledCharHeight);
        }
        else {
            this._drawUncachedChar(terminal, char, width, fg, x, y, bold && terminal.options.enableBold, dim);
        }
    };
    BaseRenderLayer.prototype._drawUncachedChar = function (terminal, char, width, fg, x, y, bold, dim) {
        this._ctx.save();
        this._ctx.font = this._getFont(terminal, bold);
        this._ctx.textBaseline = 'top';
        if (fg === Types_1.INVERTED_DEFAULT_COLOR) {
            this._ctx.fillStyle = this._colors.background.css;
        }
        else if (fg < 256) {
            this._ctx.fillStyle = this._colors.ansi[fg].css;
        }
        else {
            this._ctx.fillStyle = this._colors.foreground.css;
        }
        this._clipRow(terminal, y);
        if (dim) {
            this._ctx.globalAlpha = Types_1.DIM_OPACITY;
        }
        this._ctx.fillText(char, x * this._scaledCellWidth + this._scaledCharLeft, y * this._scaledCellHeight + this._scaledCharTop);
        this._ctx.restore();
    };
    BaseRenderLayer.prototype._clipRow = function (terminal, y) {
        this._ctx.beginPath();
        this._ctx.rect(0, y * this._scaledCellHeight, terminal.cols * this._scaledCellWidth, this._scaledCellHeight);
        this._ctx.clip();
    };
    BaseRenderLayer.prototype._getFont = function (terminal, isBold) {
        var fontWeight = isBold ? terminal.options.fontWeightBold : terminal.options.fontWeight;
        return fontWeight + " " + terminal.options.fontSize * window.devicePixelRatio + "px " + terminal.options.fontFamily;
    };
    return BaseRenderLayer;
}());
exports.BaseRenderLayer = BaseRenderLayer;

//# sourceMappingURL=BaseRenderLayer.js.map


/***/ }),

/***/ "HKS5":
/*!**************************************************************!*\
  !*** ./node_modules/draft-js/lib/getTextContentFromFiles.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule getTextContentFromFiles
 * @format
 * 
 */



var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");

var TEXT_CLIPPING_REGEX = /\.textClipping$/;

var TEXT_TYPES = {
  'text/plain': true,
  'text/html': true,
  'text/rtf': true
};

// Somewhat arbitrary upper bound on text size. Let's not lock up the browser.
var TEXT_SIZE_UPPER_BOUND = 5000;

/**
 * Extract the text content from a file list.
 */
function getTextContentFromFiles(files, callback) {
  var readCount = 0;
  var results = [];
  files.forEach(function ( /*blob*/file) {
    readFile(file, function ( /*string*/text) {
      readCount++;
      text && results.push(text.slice(0, TEXT_SIZE_UPPER_BOUND));
      if (readCount == files.length) {
        callback(results.join('\r'));
      }
    });
  });
}

/**
 * todo isaac: Do work to turn html/rtf into a content fragment.
 */
function readFile(file, callback) {
  if (!global.FileReader || file.type && !(file.type in TEXT_TYPES)) {
    callback('');
    return;
  }

  if (file.type === '') {
    var contents = '';
    // Special-case text clippings, which have an empty type but include
    // `.textClipping` in the file name. `readAsText` results in an empty
    // string for text clippings, so we force the file name to serve
    // as the text value for the file.
    if (TEXT_CLIPPING_REGEX.test(file.name)) {
      contents = file.name.replace(TEXT_CLIPPING_REGEX, '');
    }
    callback(contents);
    return;
  }

  var reader = new FileReader();
  reader.onload = function () {
    var result = reader.result;
    !(typeof result === 'string') ?  true ? invariant(false, 'We should be calling "FileReader.readAsText" which returns a string') : undefined : void 0;
    callback(result);
  };
  reader.onerror = function () {
    callback('');
  };
  reader.readAsText(file);
}

module.exports = getTextContentFromFiles;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "HOxn":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_Promise.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getNative = __webpack_require__(/*! ./_getNative */ "Cwc5"),
    root = __webpack_require__(/*! ./_root */ "Kz5y");

/* Built-in method references that are verified to be native. */
var Promise = getNative(root, 'Promise');

module.exports = Promise;


/***/ }),

/***/ "HP3h":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/ar-ly.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var symbolMap = {
    '1': '1',
    '2': '2',
    '3': '3',
    '4': '4',
    '5': '5',
    '6': '6',
    '7': '7',
    '8': '8',
    '9': '9',
    '0': '0'
}, pluralForm = function (n) {
    return n === 0 ? 0 : n === 1 ? 1 : n === 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5;
}, plurals = {
    s : ['أقل من ثانية', 'ثانية واحدة', ['ثانيتان', 'ثانيتين'], '%d ثوان', '%d ثانية', '%d ثانية'],
    m : ['أقل من دقيقة', 'دقيقة واحدة', ['دقيقتان', 'دقيقتين'], '%d دقائق', '%d دقيقة', '%d دقيقة'],
    h : ['أقل من ساعة', 'ساعة واحدة', ['ساعتان', 'ساعتين'], '%d ساعات', '%d ساعة', '%d ساعة'],
    d : ['أقل من يوم', 'يوم واحد', ['يومان', 'يومين'], '%d أيام', '%d يومًا', '%d يوم'],
    M : ['أقل من شهر', 'شهر واحد', ['شهران', 'شهرين'], '%d أشهر', '%d شهرا', '%d شهر'],
    y : ['أقل من عام', 'عام واحد', ['عامان', 'عامين'], '%d أعوام', '%d عامًا', '%d عام']
}, pluralize = function (u) {
    return function (number, withoutSuffix, string, isFuture) {
        var f = pluralForm(number),
            str = plurals[u][pluralForm(number)];
        if (f === 2) {
            str = str[withoutSuffix ? 0 : 1];
        }
        return str.replace(/%d/i, number);
    };
}, months = [
    'يناير',
    'فبراير',
    'مارس',
    'أبريل',
    'مايو',
    'يونيو',
    'يوليو',
    'أغسطس',
    'سبتمبر',
    'أكتوبر',
    'نوفمبر',
    'ديسمبر'
];

var arLy = moment.defineLocale('ar-ly', {
    months : months,
    monthsShort : months,
    weekdays : 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
    weekdaysShort : 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),
    weekdaysMin : 'ح_ن_ث_ر_خ_ج_س'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'D/\u200FM/\u200FYYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd D MMMM YYYY HH:mm'
    },
    meridiemParse: /ص|م/,
    isPM : function (input) {
        return 'م' === input;
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 12) {
            return 'ص';
        } else {
            return 'م';
        }
    },
    calendar : {
        sameDay: '[اليوم عند الساعة] LT',
        nextDay: '[غدًا عند الساعة] LT',
        nextWeek: 'dddd [عند الساعة] LT',
        lastDay: '[أمس عند الساعة] LT',
        lastWeek: 'dddd [عند الساعة] LT',
        sameElse: 'L'
    },
    relativeTime : {
        future : 'بعد %s',
        past : 'منذ %s',
        s : pluralize('s'),
        ss : pluralize('s'),
        m : pluralize('m'),
        mm : pluralize('m'),
        h : pluralize('h'),
        hh : pluralize('h'),
        d : pluralize('d'),
        dd : pluralize('d'),
        M : pluralize('M'),
        MM : pluralize('M'),
        y : pluralize('y'),
        yy : pluralize('y')
    },
    preparse: function (string) {
        return string.replace(/،/g, ',');
    },
    postformat: function (string) {
        return string.replace(/\d/g, function (match) {
            return symbolMap[match];
        }).replace(/,/g, '،');
    },
    week : {
        dow : 6, // Saturday is the first day of the week.
        doy : 12  // The week that contains Jan 1st is the first week of the year.
    }
});

return arLy;

})));


/***/ }),

/***/ "HTXX":
/*!******************************************************************!*\
  !*** ./node_modules/react-color/lib/components/sketch/Sketch.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Sketch = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _merge = __webpack_require__(/*! lodash/merge */ "QkVN");

var _merge2 = _interopRequireDefault(_merge);

var _common = __webpack_require__(/*! ../common */ "TM95");

var _SketchFields = __webpack_require__(/*! ./SketchFields */ "GiOz");

var _SketchFields2 = _interopRequireDefault(_SketchFields);

var _SketchPresetColors = __webpack_require__(/*! ./SketchPresetColors */ "eHBW");

var _SketchPresetColors2 = _interopRequireDefault(_SketchPresetColors);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var Sketch = exports.Sketch = function Sketch(_ref) {
  var width = _ref.width,
      rgb = _ref.rgb,
      hex = _ref.hex,
      hsv = _ref.hsv,
      hsl = _ref.hsl,
      onChange = _ref.onChange,
      onSwatchHover = _ref.onSwatchHover,
      disableAlpha = _ref.disableAlpha,
      presetColors = _ref.presetColors,
      renderers = _ref.renderers,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': _extends({
      picker: {
        width: width,
        padding: '10px 10px 0',
        boxSizing: 'initial',
        background: '#fff',
        borderRadius: '4px',
        boxShadow: '0 0 0 1px rgba(0,0,0,.15), 0 8px 16px rgba(0,0,0,.15)'
      },
      saturation: {
        width: '100%',
        paddingBottom: '75%',
        position: 'relative',
        overflow: 'hidden'
      },
      Saturation: {
        radius: '3px',
        shadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)'
      },
      controls: {
        display: 'flex'
      },
      sliders: {
        padding: '4px 0',
        flex: '1'
      },
      color: {
        width: '24px',
        height: '24px',
        position: 'relative',
        marginTop: '4px',
        marginLeft: '4px',
        borderRadius: '3px'
      },
      activeColor: {
        absolute: '0px 0px 0px 0px',
        borderRadius: '2px',
        background: 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + rgb.a + ')',
        boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)'
      },
      hue: {
        position: 'relative',
        height: '10px',
        overflow: 'hidden'
      },
      Hue: {
        radius: '2px',
        shadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)'
      },

      alpha: {
        position: 'relative',
        height: '10px',
        marginTop: '4px',
        overflow: 'hidden'
      },
      Alpha: {
        radius: '2px',
        shadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)'
      }
    }, passedStyles),
    'disableAlpha': {
      color: {
        height: '10px'
      },
      hue: {
        height: '10px'
      },
      alpha: {
        display: 'none'
      }
    }
  }, passedStyles), { disableAlpha: disableAlpha });

  return _react2.default.createElement(
    'div',
    { style: styles.picker, className: 'sketch-picker ' + className },
    _react2.default.createElement(
      'div',
      { style: styles.saturation },
      _react2.default.createElement(_common.Saturation, {
        style: styles.Saturation,
        hsl: hsl,
        hsv: hsv,
        onChange: onChange
      })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.controls, className: 'flexbox-fix' },
      _react2.default.createElement(
        'div',
        { style: styles.sliders },
        _react2.default.createElement(
          'div',
          { style: styles.hue },
          _react2.default.createElement(_common.Hue, {
            style: styles.Hue,
            hsl: hsl,
            onChange: onChange
          })
        ),
        _react2.default.createElement(
          'div',
          { style: styles.alpha },
          _react2.default.createElement(_common.Alpha, {
            style: styles.Alpha,
            rgb: rgb,
            hsl: hsl,
            renderers: renderers,
            onChange: onChange
          })
        )
      ),
      _react2.default.createElement(
        'div',
        { style: styles.color },
        _react2.default.createElement(_common.Checkboard, null),
        _react2.default.createElement('div', { style: styles.activeColor })
      )
    ),
    _react2.default.createElement(_SketchFields2.default, {
      rgb: rgb,
      hsl: hsl,
      hex: hex,
      onChange: onChange,
      disableAlpha: disableAlpha
    }),
    _react2.default.createElement(_SketchPresetColors2.default, {
      colors: presetColors,
      onClick: onChange,
      onSwatchHover: onSwatchHover
    })
  );
};

Sketch.propTypes = {
  disableAlpha: _propTypes2.default.bool,
  width: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]),
  styles: _propTypes2.default.object
};

Sketch.defaultProps = {
  disableAlpha: false,
  width: 200,
  styles: {},
  presetColors: ['#D0021B', '#F5A623', '#F8E71C', '#8B572A', '#7ED321', '#417505', '#BD10E0', '#9013FE', '#4A90E2', '#50E3C2', '#B8E986', '#000000', '#4A4A4A', '#9B9B9B', '#FFFFFF']
};

exports.default = (0, _common.ColorWrap)(Sketch);

/***/ }),

/***/ "HWBy":
/*!***********************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/panellayout.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
var messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
var layout_1 = __webpack_require__(/*! ./layout */ "yNaG");
var widget_1 = __webpack_require__(/*! ./widget */ "FmDU");
/**
 * A concrete layout implementation suitable for many use cases.
 *
 * #### Notes
 * This class is suitable as a base class for implementing a variety of
 * layouts, but can also be used directly with standard CSS to layout a
 * collection of widgets.
 */
var PanelLayout = (function (_super) {
    __extends(PanelLayout, _super);
    function PanelLayout() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this._widgets = [];
        return _this;
    }
    /**
     * Dispose of the resources held by the layout.
     *
     * #### Notes
     * This will clear and dispose all widgets in the layout.
     *
     * All reimplementations should call the superclass method.
     *
     * This method is called automatically when the parent is disposed.
     */
    PanelLayout.prototype.dispose = function () {
        while (this._widgets.length > 0) {
            this._widgets.pop().dispose();
        }
        _super.prototype.dispose.call(this);
    };
    Object.defineProperty(PanelLayout.prototype, "widgets", {
        /**
         * A read-only array of the widgets in the layout.
         */
        get: function () {
            return this._widgets;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Create an iterator over the widgets in the layout.
     *
     * @returns A new iterator over the widgets in the layout.
     */
    PanelLayout.prototype.iter = function () {
        return algorithm_1.iter(this._widgets);
    };
    /**
     * Add a widget to the end of the layout.
     *
     * @param widget - The widget to add to the layout.
     *
     * #### Notes
     * If the widget is already contained in the layout, it will be moved.
     */
    PanelLayout.prototype.addWidget = function (widget) {
        this.insertWidget(this._widgets.length, widget);
    };
    /**
     * Insert a widget into the layout at the specified index.
     *
     * @param index - The index at which to insert the widget.
     *
     * @param widget - The widget to insert into the layout.
     *
     * #### Notes
     * The index will be clamped to the bounds of the widgets.
     *
     * If the widget is already added to the layout, it will be moved.
     *
     * #### Undefined Behavior
     * An `index` which is non-integral.
     */
    PanelLayout.prototype.insertWidget = function (index, widget) {
        // Remove the widget from its current parent. This is a no-op
        // if the widget's parent is already the layout parent widget.
        widget.parent = this.parent;
        // Look up the current index of the widget.
        var i = this._widgets.indexOf(widget);
        // Clamp the insert index to the array bounds.
        var j = Math.max(0, Math.min(index, this._widgets.length));
        // If the widget is not in the array, insert it.
        if (i === -1) {
            // Insert the widget into the array.
            algorithm_1.ArrayExt.insert(this._widgets, j, widget);
            // If the layout is parented, attach the widget to the DOM.
            if (this.parent) {
                this.attachWidget(j, widget);
            }
            // There is nothing more to do.
            return;
        }
        // Otherwise, the widget exists in the array and should be moved.
        // Adjust the index if the location is at the end of the array.
        if (j === this._widgets.length) {
            j--;
        }
        // Bail if there is no effective move.
        if (i === j) {
            return;
        }
        // Move the widget to the new location.
        algorithm_1.ArrayExt.move(this._widgets, i, j);
        // If the layout is parented, move the widget in the DOM.
        if (this.parent) {
            this.moveWidget(i, j, widget);
        }
    };
    /**
     * Remove a widget from the layout.
     *
     * @param widget - The widget to remove from the layout.
     *
     * #### Notes
     * A widget is automatically removed from the layout when its `parent`
     * is set to `null`. This method should only be invoked directly when
     * removing a widget from a layout which has yet to be installed on a
     * parent widget.
     *
     * This method does *not* modify the widget's `parent`.
     */
    PanelLayout.prototype.removeWidget = function (widget) {
        this.removeWidgetAt(this._widgets.indexOf(widget));
    };
    /**
     * Remove the widget at a given index from the layout.
     *
     * @param index - The index of the widget to remove.
     *
     * #### Notes
     * A widget is automatically removed from the layout when its `parent`
     * is set to `null`. This method should only be invoked directly when
     * removing a widget from a layout which has yet to be installed on a
     * parent widget.
     *
     * This method does *not* modify the widget's `parent`.
     *
     * #### Undefined Behavior
     * An `index` which is non-integral.
     */
    PanelLayout.prototype.removeWidgetAt = function (index) {
        // Remove the widget from the array.
        var widget = algorithm_1.ArrayExt.removeAt(this._widgets, index);
        // If the layout is parented, detach the widget from the DOM.
        if (widget && this.parent) {
            this.detachWidget(index, widget);
        }
    };
    /**
     * Perform layout initialization which requires the parent widget.
     */
    PanelLayout.prototype.init = function () {
        var _this = this;
        _super.prototype.init.call(this);
        algorithm_1.each(this, function (widget, index) {
            _this.attachWidget(index, widget);
        });
    };
    /**
     * Attach a widget to the parent's DOM node.
     *
     * @param index - The current index of the widget in the layout.
     *
     * @param widget - The widget to attach to the parent.
     *
     * #### Notes
     * This method is called automatically by the panel layout at the
     * appropriate time. It should not be called directly by user code.
     *
     * The default implementation adds the widgets's node to the parent's
     * node at the proper location, and sends the appropriate attach
     * messages to the widget if the parent is attached to the DOM.
     *
     * Subclasses may reimplement this method to control how the widget's
     * node is added to the parent's node.
     */
    PanelLayout.prototype.attachWidget = function (index, widget) {
        // Look up the next sibling reference node.
        var ref = this.parent.node.children[index];
        // Send a `'before-attach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.BeforeAttach);
        }
        // Insert the widget's node before the sibling.
        this.parent.node.insertBefore(widget.node, ref);
        // Send an `'after-attach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.AfterAttach);
        }
    };
    /**
     * Move a widget in the parent's DOM node.
     *
     * @param fromIndex - The previous index of the widget in the layout.
     *
     * @param toIndex - The current index of the widget in the layout.
     *
     * @param widget - The widget to move in the parent.
     *
     * #### Notes
     * This method is called automatically by the panel layout at the
     * appropriate time. It should not be called directly by user code.
     *
     * The default implementation moves the widget's node to the proper
     * location in the parent's node and sends the appropriate attach and
     * detach messages to the widget if the parent is attached to the DOM.
     *
     * Subclasses may reimplement this method to control how the widget's
     * node is moved in the parent's node.
     */
    PanelLayout.prototype.moveWidget = function (fromIndex, toIndex, widget) {
        // Send a `'before-detach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.BeforeDetach);
        }
        // Remove the widget's node from the parent.
        this.parent.node.removeChild(widget.node);
        // Send an `'after-detach'` and  message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.AfterDetach);
        }
        // Look up the next sibling reference node.
        var ref = this.parent.node.children[toIndex];
        // Send a `'before-attach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.BeforeAttach);
        }
        // Insert the widget's node before the sibling.
        this.parent.node.insertBefore(widget.node, ref);
        // Send an `'after-attach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.AfterAttach);
        }
    };
    /**
     * Detach a widget from the parent's DOM node.
     *
     * @param index - The previous index of the widget in the layout.
     *
     * @param widget - The widget to detach from the parent.
     *
     * #### Notes
     * This method is called automatically by the panel layout at the
     * appropriate time. It should not be called directly by user code.
     *
     * The default implementation removes the widget's node from the
     * parent's node, and sends the appropriate detach messages to the
     * widget if the parent is attached to the DOM.
     *
     * Subclasses may reimplement this method to control how the widget's
     * node is removed from the parent's node.
     */
    PanelLayout.prototype.detachWidget = function (index, widget) {
        // Send a `'before-detach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.BeforeDetach);
        }
        // Remove the widget's node from the parent.
        this.parent.node.removeChild(widget.node);
        // Send an `'after-detach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.AfterDetach);
        }
    };
    return PanelLayout;
}(layout_1.Layout));
exports.PanelLayout = PanelLayout;


/***/ }),

/***/ "HWco":
/*!******************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/AxesCreator.js ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Dropdown = __webpack_require__(/*! ./Dropdown */ "dRXW");

var _Dropdown2 = _interopRequireDefault(_Dropdown);

var _Info = __webpack_require__(/*! ./Info */ "iOcY");

var _Info2 = _interopRequireDefault(_Info);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _constants = __webpack_require__(/*! ../../lib/constants */ "5Bkx");

var _Button = __webpack_require__(/*! ../widgets/Button */ "rZxl");

var _Button2 = _interopRequireDefault(_Button);

var _plotlyIcons = __webpack_require__(/*! plotly-icons */ "hwSx");

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _2 = __webpack_require__(/*! ./.. */ "yF51");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UnconnectedAxisCreator = function (_Component) {
  _inherits(UnconnectedAxisCreator, _Component);

  function UnconnectedAxisCreator() {
    _classCallCheck(this, UnconnectedAxisCreator);

    return _possibleConstructorReturn(this, (UnconnectedAxisCreator.__proto__ || Object.getPrototypeOf(UnconnectedAxisCreator)).apply(this, arguments));
  }

  _createClass(UnconnectedAxisCreator, [{
    key: 'canAddAxis',
    value: function canAddAxis() {
      var _this2 = this;

      var currentAxisId = this.props.fullContainer[this.props.attr];
      var currentTraceIndex = this.props.fullContainer.index;
      return this.context.fullData.some(function (d) {
        return d.index !== currentTraceIndex && d[_this2.props.attr] === currentAxisId;
      });
    }
  }, {
    key: 'addAndUpdateAxis',
    value: function addAndUpdateAxis() {
      var _update;

      var _props = this.props,
          attr = _props.attr,
          updateContainer = _props.updateContainer;
      var _context = this.context,
          onUpdate = _context.onUpdate,
          subplots = _context.fullLayout._subplots;

      var lastAxisNumber = Number(subplots[attr][subplots[attr].length - 1].charAt(1)) || 1;

      updateContainer(_defineProperty({}, attr, attr.charAt(0) + (lastAxisNumber + 1)));

      var side = null;
      if (attr === 'yaxis') {
        side = 'right';
      } else if (attr === 'xaxis') {
        side = 'top';
      }

      onUpdate({
        type: _constants.EDITOR_ACTIONS.UPDATE_LAYOUT,
        payload: {
          update: (_update = {}, _defineProperty(_update, attr + (lastAxisNumber + 1) + '.side', side), _defineProperty(_update, attr + (lastAxisNumber + 1) + '.overlaying', !(attr === 'yaxis' || attr === 'xaxis') ? null : subplots[attr][subplots[attr].length - 1]), _update)
        }
      });
    }
  }, {
    key: 'updateAxis',
    value: function updateAxis(update) {
      var _this3 = this;

      var currentAxisId = this.props.fullContainer[this.props.attr];
      var axesToBeGarbageCollected = [];

      // When we select another axis, make sure no unused axes are left
      if (currentAxisId !== update && !this.context.fullData.some(function (trace) {
        return trace[_this3.props.attr] === currentAxisId && trace.index !== _this3.props.fullContainer.index;
      })) {
        axesToBeGarbageCollected.push(currentAxisId);
      }

      this.context.onUpdate({
        type: _constants.EDITOR_ACTIONS.UPDATE_TRACES,
        payload: {
          axesToBeGarbageCollected: axesToBeGarbageCollected,
          update: _defineProperty({}, this.props.attr, update),
          traceIndexes: [this.props.fullContainer.index]
        }
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var _this4 = this;

      var icon = _react2.default.createElement(_plotlyIcons.PlusIcon, null);
      var extraComponent = this.canAddAxis() ? _react2.default.createElement(_Button2.default, { variant: 'no-text', icon: icon, onClick: function onClick() {
          return _this4.addAndUpdateAxis();
        } }) : _react2.default.createElement(_Button2.default, { variant: 'no-text--disabled', icon: icon, onClick: function onClick() {} });

      return _react2.default.createElement(_Dropdown2.default, {
        label: this.props.label,
        attr: this.props.attr,
        clearable: false,
        options: this.props.options,
        updatePlot: function updatePlot(u) {
          return _this4.updateAxis(u);
        },
        extraComponent: extraComponent
      });
    }
  }]);

  return UnconnectedAxisCreator;
}(_react.Component);

UnconnectedAxisCreator.propTypes = {
  attr: _propTypes2.default.string,
  label: _propTypes2.default.string,
  options: _propTypes2.default.array,
  container: _propTypes2.default.object,
  fullContainer: _propTypes2.default.object,
  updateContainer: _propTypes2.default.func
};

UnconnectedAxisCreator.contextTypes = {
  fullLayout: _propTypes2.default.object,
  data: _propTypes2.default.array,
  fullData: _propTypes2.default.array,
  onUpdate: _propTypes2.default.func
};

var AxisCreator = (0, _lib.connectToContainer)(UnconnectedAxisCreator);

var UnconnectedAxesCreator = function (_Component2) {
  _inherits(UnconnectedAxesCreator, _Component2);

  function UnconnectedAxesCreator() {
    _classCallCheck(this, UnconnectedAxesCreator);

    return _possibleConstructorReturn(this, (UnconnectedAxesCreator.__proto__ || Object.getPrototypeOf(UnconnectedAxesCreator)).apply(this, arguments));
  }

  _createClass(UnconnectedAxesCreator, [{
    key: 'render',
    value: function render() {
      var _this6 = this;

      var axisType = (0, _lib.traceTypeToAxisType)(this.props.container.type);
      var isFirstTraceOfAxisType = this.context.data.filter(function (d) {
        return (0, _lib.traceTypeToAxisType)(d.type) === axisType;
      }).length === 1;

      if (isFirstTraceOfAxisType) {
        return null;
      }

      var _context2 = this.context,
          fullLayout = _context2.fullLayout,
          _ = _context2.localize;

      var controls = [];

      function getOptions(axisType) {
        return fullLayout._subplots[axisType].map(function (axisId) {
          return {
            label: (0, _lib.getParsedTemplateString)((0, _lib.getAxisTitle)(fullLayout[(0, _lib.axisIdToAxisName)(axisId)]), fullLayout.meta),
            value: axisId
          };
        });
      }

      if (axisType === 'cartesian') {
        ['xaxis', 'yaxis'].forEach(function (type, index) {
          controls.push(_react2.default.createElement(AxisCreator, {
            key: index,
            attr: type,
            label: type.charAt(0).toUpperCase() + _(' Axis'),
            options: getOptions(type)
          }));
        });
      }

      return _react2.default.createElement(
        _2.PlotlySection,
        { name: _('Axes to Use') },
        controls,
        _react2.default.createElement(
          _Info2.default,
          null,
          _('You can style and position your axes in the '),
          _react2.default.createElement(
            'a',
            { onClick: function onClick() {
                return _this6.context.setPanel('Structure', 'Subplots');
              } },
            _('Subplots')
          ),
          _(' panel.')
        )
      );
    }
  }]);

  return UnconnectedAxesCreator;
}(_react.Component);

UnconnectedAxesCreator.propTypes = {
  container: _propTypes2.default.object,
  fullContainer: _propTypes2.default.object
};

UnconnectedAxesCreator.contextTypes = {
  data: _propTypes2.default.array,
  fullData: _propTypes2.default.array,
  fullLayout: _propTypes2.default.object,
  localize: _propTypes2.default.func,
  setPanel: _propTypes2.default.func
};

exports.default = (0, _lib.connectToContainer)(UnconnectedAxesCreator, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var data = context.data;
    var fullContainer = plotProps.fullContainer;


    plotProps.isVisible = data.length > 1 && data[fullContainer.index] && (0, _lib.traceTypeToAxisType)(data[fullContainer.index].type) === 'cartesian';
  }
});
//# sourceMappingURL=AxesCreator.js.map

/***/ }),

/***/ "HXUZ":
/*!************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/running/style/index.css ***!
  \************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Variables\n|----------------------------------------------------------------------------*/\n\n:root {\n  --jp-private-running-button-height: 28px;\n  --jp-private-running-button-width: 48px;\n  --jp-private-running-item-height: 24px;\n  --jp-private-running-shutdown-button-height: 24px;\n}\n\n/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.jp-RunningSessions {\n  display: flex;\n  flex-direction: column;\n  min-width: var(--jp-sidebar-min-width);\n  color: var(--jp-ui-font-color1);\n  background: var(--jp-layout-color1);\n  /* This is needed so that all font sizing of children done in ems is\n   * relative to this base size */\n  font-size: var(--jp-ui-font-size1);\n}\n\n.jp-RunningSessions-header {\n  flex: 0 0 auto;\n  display: flex;\n  flex-direction: row;\n  margin: var(--jp-toolbar-header-margin);\n  justify-content: flex-end;\n}\n\n.jp-RunningSessions-header .jp-ToolbarButtonComponent {\n  padding: 0px 16px;\n}\n\n.jp-RunningSessions-shutdownAll {\n  flex: 1 1 auto;\n  height: var(--jp-private-running-button-height);\n  width: var(--jp-private-running-button-width);\n  max-width: 100px;\n  min-width: 16px;\n  min-height: 16px;\n  padding: 4px 6px;\n  background: var(--jp-layout-color1);\n  border: none;\n  outline: 0;\n  background-image: var(--jp-icon-close);\n  background-size: 16px;\n  vertical-align: middle;\n  background-repeat: no-repeat;\n  background-position: center;\n}\n\n.jp-RunningSessions-section {\n  display: flex;\n  flex: 0 1 auto;\n  flex-direction: column;\n}\n\n.jp-RunningSessions-sectionHeader {\n  flex: 0 0 auto;\n  align-items: center;\n  height: 28px;\n  display: flex;\n  border-bottom: var(--jp-border-width) solid var(--jp-border-color2);\n  margin-top: 8px;\n}\n\n.jp-RunningSessions-sectionHeader h2 {\n  flex: 0 0 auto;\n  font-weight: 600;\n  text-transform: uppercase;\n  letter-spacing: 1px;\n  font-size: var(--jp-ui-font-size0);\n  padding: 8px 8px 8px 12px;\n  margin: 0px;\n}\n\n.jp-RunningSessions-sectionHeader .jp-ToolbarButtonComponent {\n  flex: 0 0 auto;\n}\n\n.jp-RunningSessions-sectionContainer {\n  flex: 1 1 auto;\n  margin: 0;\n  padding: 0;\n  overflow: auto;\n}\n\n.jp-RunningSessions-sectionList {\n  margin: 0;\n  padding: 0;\n  list-style-type: none;\n}\n\n.jp-RunningSessions-item {\n  display: flex;\n  flex-direction: row;\n  color: var(--jp-ui-font-color1);\n  height: var(--jp-private-running-item-height);\n  line-height: var(--jp-private-running-item-height);\n}\n\n.jp-RunningSessions-itemIcon {\n  flex: 0 0 auto;\n  padding: 0px 8px;\n  margin-right: 4px;\n  margin-left: 12px;\n  vertical-align: baseline;\n  background-size: 16px;\n  background-repeat: no-repeat;\n  background-position: center;\n}\n\n.jp-RunningSessions-itemIcon.jp-mod-notebook {\n  background-image: var(--jp-icon-book);\n}\n\n.jp-RunningSessions-itemIcon.jp-mod-console {\n  background-image: var(--jp-icon-console);\n}\n\n.jp-RunningSessions-itemIcon.jp-mod-file:before {\n  background-image: var(--jp-icon-file);\n}\n\n.jp-RunningSessions-itemIcon.jp-mod-terminal {\n  background-image: var(--jp-icon-terminal);\n}\n\n.jp-RunningSessions-itemLabel {\n  font-size: var(--jp-ui-font-size1);\n  flex: 1 1 auto;\n  margin-right: 4px;\n  padding-left: 4px;\n  text-overflow: ellipsis;\n  overflow: hidden;\n  white-space: nowrap;\n  border-radius: 2px;\n  transition: background-color 0.1s ease;\n}\n\n.jp-RunningSessions-itemLabel:hover {\n  background-color: var(--jp-layout-color2);\n}\n\n.jp-RunningSessions-itemLabel:focus {\n  background-color: rgba(153, 153, 153, 0.2);\n}\n\n.jp-RunningSessions-itemShutdown.jp-mod-styled {\n  margin: 0px 4px;\n  color: var(--jp-warn-color1);\n  font-weight: 500;\n  background-color: transparent;\n  height: var(--jp-private-running-shutdown-button-height);\n  line-height: var(--jp-private-running-shutdown-button-height);\n  transition: background-color 0.1s ease;\n  border-radius: 2px;\n}\n\n.jp-RunningSessions-itemShutdown.jp-mod-styled:hover {\n  background-color: rgba(153, 153, 153, 0.1);\n}\n\n.jp-RunningSessions-itemShutdown.jp-mod-styled:focus {\n  border: none;\n  box-shadow: none;\n  background-color: rgba(153, 153, 153, 0.2);\n}\n", ""]);

// exports


/***/ }),

/***/ "Hdlu":
/*!*******************************************************************!*\
  !*** ./node_modules/draft-js/lib/DraftEditorPlaceholder.react.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DraftEditorPlaceholder.react
 * @format
 * 
 */



function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var React = __webpack_require__(/*! react */ "q1tI");

var cx = __webpack_require__(/*! fbjs/lib/cx */ "YVIB");

/**
 * This component is responsible for rendering placeholder text for the
 * `DraftEditor` component.
 *
 * Override placeholder style via CSS.
 */
var DraftEditorPlaceholder = function (_React$Component) {
  _inherits(DraftEditorPlaceholder, _React$Component);

  function DraftEditorPlaceholder() {
    _classCallCheck(this, DraftEditorPlaceholder);

    return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
  }

  DraftEditorPlaceholder.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
    return this.props.text !== nextProps.text || this.props.editorState.getSelection().getHasFocus() !== nextProps.editorState.getSelection().getHasFocus();
  };

  DraftEditorPlaceholder.prototype.render = function render() {
    var hasFocus = this.props.editorState.getSelection().getHasFocus();

    var className = cx({
      'public/DraftEditorPlaceholder/root': true,
      'public/DraftEditorPlaceholder/hasFocus': hasFocus
    });

    var contentStyle = {
      whiteSpace: 'pre-wrap'
    };

    return React.createElement(
      'div',
      { className: className },
      React.createElement(
        'div',
        {
          className: cx('public/DraftEditorPlaceholder/inner'),
          id: this.props.accessibilityID,
          style: contentStyle },
        this.props.text
      )
    );
  };

  return DraftEditorPlaceholder;
}(React.Component);

module.exports = DraftEditorPlaceholder;

/***/ }),

/***/ "HezI":
/*!***************************************************************!*\
  !*** ./node_modules/draft-js/lib/expandRangeToStartOfLine.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule expandRangeToStartOfLine
 * @format
 * 
 */

var UnicodeUtils = __webpack_require__(/*! fbjs/lib/UnicodeUtils */ "jLRO");

var getRangeClientRects = __webpack_require__(/*! ./getRangeClientRects */ "158f");
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");

/**
 * Return the computed line height, in pixels, for the provided element.
 */
function getLineHeightPx(element) {
  var computed = getComputedStyle(element);
  var div = document.createElement('div');
  div.style.fontFamily = computed.fontFamily;
  div.style.fontSize = computed.fontSize;
  div.style.fontStyle = computed.fontStyle;
  div.style.fontWeight = computed.fontWeight;
  div.style.lineHeight = computed.lineHeight;
  div.style.position = 'absolute';
  div.textContent = 'M';

  var documentBody = document.body;
  !documentBody ?  true ? invariant(false, 'Missing document.body') : undefined : void 0;

  // forced layout here
  documentBody.appendChild(div);
  var rect = div.getBoundingClientRect();
  documentBody.removeChild(div);

  return rect.height;
}

/**
 * Return whether every ClientRect in the provided list lies on the same line.
 *
 * We assume that the rects on the same line all contain the baseline, so the
 * lowest top line needs to be above the highest bottom line (i.e., if you were
 * to project the rects onto the y-axis, their intersection would be nonempty).
 *
 * In addition, we require that no two boxes are lineHeight (or more) apart at
 * either top or bottom, which helps protect against false positives for fonts
 * with extremely large glyph heights (e.g., with a font size of 17px, Zapfino
 * produces rects of height 58px!).
 */
function areRectsOnOneLine(rects, lineHeight) {
  var minTop = Infinity;
  var minBottom = Infinity;
  var maxTop = -Infinity;
  var maxBottom = -Infinity;

  for (var ii = 0; ii < rects.length; ii++) {
    var rect = rects[ii];
    if (rect.width === 0 || rect.width === 1) {
      // When a range starts or ends a soft wrap, many browsers (Chrome, IE,
      // Safari) include an empty rect on the previous or next line. When the
      // text lies in a container whose position is not integral (e.g., from
      // margin: auto), Safari makes these empty rects have width 1 (instead of
      // 0). Having one-pixel-wide characters seems unlikely (and most browsers
      // report widths in subpixel precision anyway) so it's relatively safe to
      // skip over them.
      continue;
    }
    minTop = Math.min(minTop, rect.top);
    minBottom = Math.min(minBottom, rect.bottom);
    maxTop = Math.max(maxTop, rect.top);
    maxBottom = Math.max(maxBottom, rect.bottom);
  }

  return maxTop <= minBottom && maxTop - minTop < lineHeight && maxBottom - minBottom < lineHeight;
}

/**
 * Return the length of a node, as used by Range offsets.
 */
function getNodeLength(node) {
  // http://www.w3.org/TR/dom/#concept-node-length
  switch (node.nodeType) {
    case Node.DOCUMENT_TYPE_NODE:
      return 0;
    case Node.TEXT_NODE:
    case Node.PROCESSING_INSTRUCTION_NODE:
    case Node.COMMENT_NODE:
      return node.length;
    default:
      return node.childNodes.length;
  }
}

/**
 * Given a collapsed range, move the start position backwards as far as
 * possible while the range still spans only a single line.
 */
function expandRangeToStartOfLine(range) {
  !range.collapsed ?  true ? invariant(false, 'expandRangeToStartOfLine: Provided range is not collapsed.') : undefined : void 0;
  range = range.cloneRange();

  var containingElement = range.startContainer;
  if (containingElement.nodeType !== 1) {
    containingElement = containingElement.parentNode;
  }
  var lineHeight = getLineHeightPx(containingElement);

  // Imagine our text looks like:
  //   <div><span>once upon a time, there was a <em>boy
  //   who lived</em> </span><q><strong>under^ the
  //   stairs</strong> in a small closet.</q></div>
  // where the caret represents the cursor. First, we crawl up the tree until
  // the range spans multiple lines (setting the start point to before
  // "<strong>", then before "<div>"), then at each level we do a search to
  // find the latest point which is still on a previous line. We'll find that
  // the break point is inside the span, then inside the <em>, then in its text
  // node child, the actual break point before "who".

  var bestContainer = range.endContainer;
  var bestOffset = range.endOffset;
  range.setStart(range.startContainer, 0);

  while (areRectsOnOneLine(getRangeClientRects(range), lineHeight)) {
    bestContainer = range.startContainer;
    bestOffset = range.startOffset;
    !bestContainer.parentNode ?  true ? invariant(false, 'Found unexpected detached subtree when traversing.') : undefined : void 0;
    range.setStartBefore(bestContainer);
    if (bestContainer.nodeType === 1 && getComputedStyle(bestContainer).display !== 'inline') {
      // The start of the line is never in a different block-level container.
      break;
    }
  }

  // In the above example, range now spans from "<div>" to "under",
  // bestContainer is <div>, and bestOffset is 1 (index of <q> inside <div>)].
  // Picking out which child to recurse into here is a special case since we
  // don't want to check past <q> -- once we find that the final range starts
  // in <span>, we can look at all of its children (and all of their children)
  // to find the break point.

  // At all times, (bestContainer, bestOffset) is the latest single-line start
  // point that we know of.
  var currentContainer = bestContainer;
  var maxIndexToConsider = bestOffset - 1;

  do {
    var nodeValue = currentContainer.nodeValue;

    for (var ii = maxIndexToConsider; ii >= 0; ii--) {
      if (nodeValue != null && ii > 0 && UnicodeUtils.isSurrogatePair(nodeValue, ii - 1)) {
        // We're in the middle of a surrogate pair -- skip over so we never
        // return a range with an endpoint in the middle of a code point.
        continue;
      }

      range.setStart(currentContainer, ii);
      if (areRectsOnOneLine(getRangeClientRects(range), lineHeight)) {
        bestContainer = currentContainer;
        bestOffset = ii;
      } else {
        break;
      }
    }

    if (ii === -1 || currentContainer.childNodes.length === 0) {
      // If ii === -1, then (bestContainer, bestOffset), which is equal to
      // (currentContainer, 0), was a single-line start point but a start
      // point before currentContainer wasn't, so the line break seems to
      // have occurred immediately after currentContainer's start tag
      //
      // If currentContainer.childNodes.length === 0, we're already at a
      // terminal node (e.g., text node) and should return our current best.
      break;
    }

    currentContainer = currentContainer.childNodes[ii];
    maxIndexToConsider = getNodeLength(currentContainer);
  } while (true);

  range.setStart(bestContainer, bestOffset);
  return range;
}

module.exports = expandRangeToStartOfLine;

/***/ }),

/***/ "Hfiw":
/*!*****************************************************************************!*\
  !*** ./node_modules/core-js/library/modules/es6.object.set-prototype-of.js ***!
  \*****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = __webpack_require__(/*! ./_export */ "Y7ZC");
$export($export.S, 'Object', { setPrototypeOf: __webpack_require__(/*! ./_set-proto */ "6tYh").set });


/***/ }),

/***/ "Hjy1":
/*!**********************************************!*\
  !*** ./node_modules/browserify-des/index.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var CipherBase = __webpack_require__(/*! cipher-base */ "ZDAU")
var des = __webpack_require__(/*! des.js */ "FUXG")
var inherits = __webpack_require__(/*! inherits */ "P7XM")
var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer

var modes = {
  'des-ede3-cbc': des.CBC.instantiate(des.EDE),
  'des-ede3': des.EDE,
  'des-ede-cbc': des.CBC.instantiate(des.EDE),
  'des-ede': des.EDE,
  'des-cbc': des.CBC.instantiate(des.DES),
  'des-ecb': des.DES
}
modes.des = modes['des-cbc']
modes.des3 = modes['des-ede3-cbc']
module.exports = DES
inherits(DES, CipherBase)
function DES (opts) {
  CipherBase.call(this)
  var modeName = opts.mode.toLowerCase()
  var mode = modes[modeName]
  var type
  if (opts.decrypt) {
    type = 'decrypt'
  } else {
    type = 'encrypt'
  }
  var key = opts.key
  if (!Buffer.isBuffer(key)) {
    key = Buffer.from(key)
  }
  if (modeName === 'des-ede' || modeName === 'des-ede-cbc') {
    key = Buffer.concat([key, key.slice(0, 8)])
  }
  var iv = opts.iv
  if (!Buffer.isBuffer(iv)) {
    iv = Buffer.from(iv)
  }
  this._des = mode.create({
    key: key,
    iv: iv,
    type: type
  })
}
DES.prototype._update = function (data) {
  return Buffer.from(this._des.update(data))
}
DES.prototype._final = function () {
  return Buffer.from(this._des.final())
}


/***/ }),

/***/ "HlQe":
/*!***************************************************************!*\
  !*** ./node_modules/react-color/lib/components/common/Hue.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Hue = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _hue = __webpack_require__(/*! ../../helpers/hue */ "srvI");

var hue = _interopRequireWildcard(_hue);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Hue = exports.Hue = function (_ref) {
  _inherits(Hue, _ref);

  function Hue() {
    var _ref2;

    var _temp, _this, _ret;

    _classCallCheck(this, Hue);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref2 = Hue.__proto__ || Object.getPrototypeOf(Hue)).call.apply(_ref2, [this].concat(args))), _this), _this.handleChange = function (e, skip) {
      var change = hue.calculateChange(e, skip, _this.props, _this.container);
      change && _this.props.onChange && _this.props.onChange(change, e);
    }, _this.handleMouseDown = function (e) {
      _this.handleChange(e, true);
      window.addEventListener('mousemove', _this.handleChange);
      window.addEventListener('mouseup', _this.handleMouseUp);
    }, _this.handleMouseUp = function () {
      _this.unbindEventListeners();
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(Hue, [{
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      this.unbindEventListeners();
    }
  }, {
    key: 'unbindEventListeners',
    value: function unbindEventListeners() {
      window.removeEventListener('mousemove', this.handleChange);
      window.removeEventListener('mouseup', this.handleMouseUp);
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _props$direction = this.props.direction,
          direction = _props$direction === undefined ? 'horizontal' : _props$direction;


      var styles = (0, _reactcss2.default)({
        'default': {
          hue: {
            absolute: '0px 0px 0px 0px',
            borderRadius: this.props.radius,
            boxShadow: this.props.shadow
          },
          container: {
            padding: '0 2px',
            position: 'relative',
            height: '100%',
            borderRadius: this.props.radius
          },
          pointer: {
            position: 'absolute',
            left: this.props.hsl.h * 100 / 360 + '%'
          },
          slider: {
            marginTop: '1px',
            width: '4px',
            borderRadius: '1px',
            height: '8px',
            boxShadow: '0 0 2px rgba(0, 0, 0, .6)',
            background: '#fff',
            transform: 'translateX(-2px)'
          }
        },
        'vertical': {
          pointer: {
            left: '0px',
            top: -(this.props.hsl.h * 100 / 360) + 100 + '%'
          }
        }
      }, { vertical: direction === 'vertical' });

      return _react2.default.createElement(
        'div',
        { style: styles.hue },
        _react2.default.createElement(
          'div',
          {
            className: 'hue-' + direction,
            style: styles.container,
            ref: function ref(container) {
              return _this2.container = container;
            },
            onMouseDown: this.handleMouseDown,
            onTouchMove: this.handleChange,
            onTouchStart: this.handleChange
          },
          _react2.default.createElement(
            'style',
            null,
            '\n            .hue-horizontal {\n              background: linear-gradient(to right, #f00 0%, #ff0 17%, #0f0\n                33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%);\n              background: -webkit-linear-gradient(to right, #f00 0%, #ff0\n                17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%);\n            }\n\n            .hue-vertical {\n              background: linear-gradient(to top, #f00 0%, #ff0 17%, #0f0 33%,\n                #0ff 50%, #00f 67%, #f0f 83%, #f00 100%);\n              background: -webkit-linear-gradient(to top, #f00 0%, #ff0 17%,\n                #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%);\n            }\n          '
          ),
          _react2.default.createElement(
            'div',
            { style: styles.pointer },
            this.props.pointer ? _react2.default.createElement(this.props.pointer, this.props) : _react2.default.createElement('div', { style: styles.slider })
          )
        )
      );
    }
  }]);

  return Hue;
}(_react.PureComponent || _react.Component);

exports.default = Hue;

/***/ }),

/***/ "HriT":
/*!********************************************************!*\
  !*** ./node_modules/draft-js/lib/sanitizeDraftText.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule sanitizeDraftText
 * @format
 * 
 */



var REGEX_BLOCK_DELIMITER = new RegExp('\r', 'g');

function sanitizeDraftText(input) {
  return input.replace(REGEX_BLOCK_DELIMITER, '');
}

module.exports = sanitizeDraftText;

/***/ }),

/***/ "Hsns":
/*!*************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_dom-create.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isObject = __webpack_require__(/*! ./_is-object */ "93I4");
var document = __webpack_require__(/*! ./_global */ "5T2Y").document;
// typeof document.createElement is 'object' in old IE
var is = isObject(document) && isObject(document.createElement);
module.exports = function (it) {
  return is ? document.createElement(it) : {};
};


/***/ }),

/***/ "HtHp":
/*!****************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotCandlestickAltIcon.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotCandlestickAltIcon = function PlotCandlestickAltIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M8.688 0h1.313v32H8.688zm6.625 0h1.375v32h-1.375zm0 5.313h1.375c.75 0 1.313.563 1.313 1.375v6.625c0 .813-.563 1.375-1.313 1.375h-1.375c-.75 0-1.313-.563-1.313-1.375V6.688c0-.813.563-1.375 1.313-1.375zM8.688 20h1.313c.813 0 1.313.563 1.313 1.313v6.688c0 .813-.5 1.313-1.313 1.313H8.688c-.813 0-1.375-.5-1.375-1.313v-6.688c0-.75.563-1.313 1.375-1.313zM2 0h1.313v32H2zm0 10.688h1.313c.813 0 1.375.5 1.375 1.313v6.688c0 .75-.563 1.313-1.375 1.313H2c-.813 0-1.313-.563-1.313-1.313v-6.688c0-.813.5-1.313 1.313-1.313zM22 0h1.313v32H22zm0 14.688h1.313c.813 0 1.375.5 1.375 1.313v6.688c0 .75-.563 1.313-1.375 1.313H22c-.813 0-1.313-.563-1.313-1.313v-6.688c0-.813.5-1.313 1.313-1.313zM28.688 0h1.313v32h-1.313zm0 2.688h1.313c.813 0 1.313.5 1.313 1.313v6.688c0 .75-.5 1.313-1.313 1.313h-1.313c-.813 0-1.375-.563-1.375-1.313V4.001c0-.813.563-1.313 1.375-1.313z' })
    );
};

exports.default = PlotCandlestickAltIcon;

/***/ }),

/***/ "Hvzi":
/*!********************************************!*\
  !*** ./node_modules/lodash/_hashDelete.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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;
}

module.exports = hashDelete;


/***/ }),

/***/ "Hytk":
/*!******************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@mflevine/jupyterlab_html/style/index.css ***!
  \******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var escape = __webpack_require__(/*! ../../../css-loader/lib/url/escape.js */ "sEG9");
exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/**\r\n  Distributed under the terms of the Modified BSD License.\r\n*/\r\n\r\n/* Add CSS variables to :root */\r\n:root {\r\n  --jp-icon-html5: url(" + escape(__webpack_require__(/*! ./html5-icon.svg */ "wQXC")) + ");\r\n}\r\n\r\n/* Document styles */\r\n.jp-MimeDocument .jp-RenderedIFrame {\r\n  overflow: hidden;\r\n}\r\n\r\n/* Output styles */\r\n.jp-OutputArea .jp-RenderedIFrame {\r\n  min-height: 360px;\r\n}\r\n\r\n/* Document icon */\r\n.jp-HTMLIcon {\r\n  background-image: var(--jp-icon-html5);\r\n}\r\n\r\n.jp-RenderedIFrame {\r\n  min-width: 100px;\r\n  min-height: 100px;\r\n  width: 100%;\r\n  height: 100%;\r\n}\r\n\r\n\r\n.jp-RenderedIFrame > iframe {\r\n  border: none;\r\n}\r\n\r\n\r\n/*\r\nWhen drag events occur, `p-mod-override-cursor` is added to the body.\r\nBecause iframes steal all cursor events, the following two rules are necessary\r\nto suppress pointer events while resize drags are occuring. There may be a\r\nbetter solution to this problem.\r\n*/\r\nbody.p-mod-override-cursor .jp-RenderedIFrame {\r\n  position: relative;\r\n}\r\n\r\nbody.p-mod-override-cursor .jp-RenderedIFrame:before {\r\n  content: '';\r\n  position: absolute;\r\n  top: 0;\r\n  left: 0;\r\n  right: 0;\r\n  bottom: 0;\r\n  background: transparent;\r\n}\r\n", ""]);

// exports


/***/ }),

/***/ "I+VJ":
/*!****************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/application/style/icons.css ***!
  \****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.jp-MaterialIcon {\n  min-width: 16px;\n  min-height: 16px;\n  background-size: 16px;\n  display: inline-block;\n  vertical-align: middle;\n  background-repeat: no-repeat;\n  background-position: center;\n}\n\n.jp-Icon {\n  display: inline-block;\n  vertical-align: middle;\n  background-repeat: no-repeat;\n  background-position: center;\n  margin: auto;\n}\n\n.jp-Icon-16 {\n  min-width: 16px;\n  min-height: 16px;\n  background-size: 16px;\n}\n\n.jp-Icon-18 {\n  min-width: 18px;\n  min-height: 18px;\n  background-size: 18px;\n}\n\n.jp-Icon-20 {\n  min-width: 20px;\n  min-height: 20px;\n  background-size: 20px;\n}\n\n.jp-AddIcon {\n  background-image: var(--jp-icon-add);\n}\n\n.jp-BugIcon {\n  background-image: var(--jp-icon-bug);\n}\n\n.jp-BuildIcon {\n  background-image: var(--jp-icon-build);\n}\n\n.jp-ChatIcon {\n  background-image: var(--jp-icon-chat);\n}\n\n.jp-CircleIcon {\n  background-image: var(--jp-icon-kernel-running);\n}\n\n.jp-CloseIcon {\n  background-image: var(--jp-icon-close);\n}\n\n.jp-CodeConsoleIcon {\n  background-image: var(--jp-icon-console);\n}\n\n.jp-CopyIcon {\n  background-image: var(--jp-icon-copy);\n}\n\n.jp-CutIcon {\n  background-image: var(--jp-icon-cut);\n}\n\n.jp-DirectionsRunIcon {\n  background-image: var(--jp-icon-directions-run);\n}\n\n.jp-DownCaretIcon {\n  background-image: var(--jp-ui-select-caret);\n}\n\n.jp-DownloadIcon {\n  background-image: var(--jp-icon-download);\n}\n\n.jp-DragIcon {\n  margin-right: 4px;\n}\n\n.jp-EditIcon {\n  background-image: var(--jp-icon-edit);\n}\n\n.jp-EllipsesIcon {\n  background-image: var(--jp-icon-ellipses);\n}\n\n.jp-ExpandLessIcon {\n  background-image: var(--jp-icon-expand-less);\n}\n\n.jp-ExpandMoreIcon {\n  background-image: var(--jp-icon-expand-more);\n}\n\n.jp-ExtensionIcon {\n  background-image: var(--jp-icon-extension);\n}\n\n.jp-FileIcon {\n  background-image: var(--jp-icon-file);\n}\n\n.jp-FilledCircleIcon {\n  background-image: var(--jp-icon-circle);\n}\n\n.jp-FolderIcon {\n  background-image: var(--jp-icon-folder);\n}\n\n.jp-HomeIcon {\n  background-image: var(--jp-icon-home);\n  min-width: 16px;\n  min-height: 16px;\n  background-size: 16px;\n  vertical-align: sub;\n}\n\n.jp-ImageIcon {\n  background-image: var(--jp-icon-image);\n}\n\n.jp-JSONIcon {\n  background-image: var(--jp-icon-json);\n}\n\n.jp-JupyterIcon {\n  background-image: var(--jp-image-jupyter);\n  background-size: 16px;\n  margin: 2px;\n  margin-left: 8px;\n  margin-right: 0px;\n  padding-right: 0px;\n}\n\n.jp-LauncherIcon {\n  background-image: var(--jp-icon-launcher);\n}\n\n.jp-LinkIcon {\n  background-image: var(--jp-icon-link);\n}\n\n.jp-MainAreaLandscapeIcon {\n  background-repeat: no-repeat;\n  margin-right: 2px;\n  width: 22px;\n}\n\n.jp-MainAreaPortraitIcon {\n  background-position: 0 2px;\n  background-repeat: no-repeat;\n  margin-right: 2px;\n  width: 20px;\n}\n\n.jp-MarkdownIcon {\n  background-image: var(--jp-icon-markdown);\n}\n\n.jp-MoreHorizIcon {\n  background-image: var(--jp-icon-more);\n}\n\n.jp-NewFolderIcon {\n  background-image: var(--jp-icon-new-folder);\n}\n\n.jp-NotebookIcon {\n  background-image: var(--jp-icon-book);\n}\n\n.jp-OpenFolderIcon {\n  background-image: var(--jp-icon-directory);\n}\n\n.jp-PaletteIcon {\n  background-image: var(--jp-icon-palette);\n}\n\n.jp-PasteIcon {\n  background-image: var(--jp-icon-paste);\n}\n\n.jp-PythonIcon {\n  background-image: var(--jp-icon-python);\n}\n\n.jp-RKernelIcon {\n  background-image: var(--jp-icon-r);\n}\n\n.jp-RefreshIcon {\n  background-image: var(--jp-icon-refresh);\n}\n\n.jp-RunIcon {\n  background-image: var(--jp-icon-run);\n}\n\n.jp-SaveIcon {\n  background-image: var(--jp-icon-save);\n}\n\n.jp-SettingsIcon {\n  background-image: var(--jp-icon-settings);\n}\n\n.jp-SpreadsheetIcon {\n  background-image: var(--jp-icon-spreadsheet);\n}\n\n.jp-StopIcon {\n  background-image: var(--jp-icon-stop);\n}\n\n.jp-TabIcon {\n  background-image: var(--jp-icon-tab);\n}\n\n.jp-TerminalIcon {\n  background-image: var(--jp-icon-terminal);\n}\n\n.jp-TextEditorIcon {\n  background-image: var(--jp-icon-text-editor);\n}\n\n.jp-UndoIcon {\n  background-image: var(--jp-icon-undo);\n}\n\n.jp-FileUploadIcon {\n  background-image: var(--jp-icon-file-upload);\n}\n\n.jp-YamlIcon {\n  background-image: var(--jp-icon-yaml);\n}\n\n.jp-VegaIcon {\n  background-image: var(--jp-icon-vega);\n}\n\n.jp-QuestionMarkIcon {\n  background-image: var(--jp-icon-question-mark);\n}\n", ""]);

// exports


/***/ }),

/***/ "I01J":
/*!***********************************************!*\
  !*** ./node_modules/lodash/_memoizeCapped.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var memoize = __webpack_require__(/*! ./memoize */ "44Ds");

/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;

/**
 * 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;
}

module.exports = memoizeCapped;


/***/ }),

/***/ "I0N7":
/*!***********************************************!*\
  !*** ./node_modules/pure-color/util/clamp.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

function clamp(val, min, max) {
  return Math.min(Math.max(val, min), max);
}

module.exports = clamp;

/***/ }),

/***/ "I0Qy":
/*!*******************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/NotebookRIcon.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var NotebookRIcon = function NotebookRIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M27.625 32H5.812a.722.722 0 0 1-.75-.75V.75c0-.438.313-.75.75-.75h21.813c.438 0 .75.313.75.75v30.5c0 .438-.313.75-.75.75zM6.563 30.563h20.375V1.438H6.563zm.687-24.75H4.375c-.438 0-.75-.313-.75-.75s.313-.688.75-.688H7.25c.438 0 .75.25.75.688s-.313.75-.75.75zm0 4.375H4.375c-.438 0-.75-.313-.75-.75s.313-.688.75-.688H7.25c.438 0 .75.25.75.688s-.313.75-.75.75zm0 4.375H4.375c-.438 0-.75-.313-.75-.75s.313-.75.75-.75H7.25c.438 0 .75.313.75.75s-.313.75-.75.75zm0 4.375H4.375c-.438 0-.75-.313-.75-.75s.313-.75.75-.75H7.25c.438 0 .75.313.75.75s-.313.75-.75.75zm0 4.312H4.375c-.438 0-.75-.25-.75-.688s.313-.75.75-.75H7.25c.438 0 .75.313.75.75s-.313.688-.75.688zm0 4.375H4.375c-.438 0-.75-.25-.75-.688s.313-.75.75-.75H7.25c.438 0 .75.313.75.75s-.313.688-.75.688zm6-5.937v-10.75h4.813c1 0 1.75.125 2.125.25.438.188.875.625 1.188 1 .313.438.438 1.063.438 1.625 0 .75-.313 1.438-.75 1.875-.438.625-1.25.875-2.313 1.063.438.125.75.25.875.563.438.438.875.875 1.188 1.438l1.875 2.938h-1.75l-1.438-2.188c-.438-.563-.75-1.188-1-1.438-.313-.438-.625-.625-.75-.75s-.438-.313-.563-.313h-2.5v4.813H13.25zm1.438-6h3.063c.563 0 1.188 0 1.625-.125s.563-.313.813-.563c.188-.313.313-.625.313-1.063 0-.563-.125-.875-.563-1.313-.438-.25-1-.438-1.75-.438h-3.5z' })
    );
};

exports.default = NotebookRIcon;

/***/ }),

/***/ "I1BE":
/*!*************************************************!*\
  !*** ./node_modules/css-loader/lib/css-base.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
// css base code, injected by the css-loader
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 " + item[2] + "{" + content + "}";
			} else {
				return content;
			}
		}).join("");
	};

	// import a list of modules into the list
	list.i = function(modules, mediaQuery) {
		if(typeof modules === "string")
			modules = [[null, modules, ""]];
		var alreadyImportedModules = {};
		for(var i = 0; i < this.length; i++) {
			var id = this[i][0];
			if(typeof id === "number")
				alreadyImportedModules[id] = true;
		}
		for(i = 0; i < modules.length; i++) {
			var item = modules[i];
			// skip already imported module
			// this implementation is not 100% perfect for weird media query combinations
			//  when a module is imported multiple times with different media queries.
			//  I hope this will never occur (Hey this way we have smaller bundles)
			if(typeof item[0] !== "number" || !alreadyImportedModules[item[0]]) {
				if(mediaQuery && !item[2]) {
					item[2] = mediaQuery;
				} else if(mediaQuery) {
					item[2] = "(" + item[2] + ") and (" + mediaQuery + ")";
				}
				list.push(item);
			}
		}
	};
	return list;
};

function cssWithMappingToString(item, useSourceMap) {
	var content = item[1] || '';
	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=' + cssMapping.sourceRoot + 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,' + base64;

	return '/*# ' + data + ' */';
}


/***/ }),

/***/ "I1EO":
/*!***************************************************!*\
  !*** ./node_modules/mdi-react/ContentCopyIcon.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var ContentCopyIcon = function ContentCopyIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M19,21H8V7H19M19,5H8C6.9,5 6,5.9 6,7V21C6,22.1 6.9,23 8,23H19C20.1,23 21,22.1 21,21V7C21,5.9 20.1,5 19,5M16,1H4C2.9,1 2,1.9 2,3V17H4V3H16V1Z' })
  );
};

module.exports = ContentCopyIcon;


/***/ }),

/***/ "I2Ug":
/*!**************************************************************!*\
  !*** ./node_modules/draft-js/lib/moveBlockInContentState.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule moveBlockInContentState
 * @format
 * 
 */



var ContentBlockNode = __webpack_require__(/*! ./ContentBlockNode */ "JL7T");
var Immutable = __webpack_require__(/*! immutable */ "JPcv");

var getNextDelimiterBlockKey = __webpack_require__(/*! ./getNextDelimiterBlockKey */ "VTBg");
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");

var OrderedMap = Immutable.OrderedMap,
    List = Immutable.List;


var transformBlock = function transformBlock(key, blockMap, func) {
  if (!key) {
    return;
  }

  var block = blockMap.get(key);

  if (!block) {
    return;
  }

  blockMap.set(key, func(block));
};

var updateBlockMapLinks = function updateBlockMapLinks(blockMap, originalBlockToBeMoved, originalTargetBlock, insertionMode, isExperimentalTreeBlock) {
  if (!isExperimentalTreeBlock) {
    return blockMap;
  }
  // possible values of 'insertionMode' are: 'after', 'before'
  var isInsertedAfterTarget = insertionMode === 'after';

  var originalBlockKey = originalBlockToBeMoved.getKey();
  var originalTargetKey = originalTargetBlock.getKey();
  var originalParentKey = originalBlockToBeMoved.getParentKey();
  var originalNextSiblingKey = originalBlockToBeMoved.getNextSiblingKey();
  var originalPrevSiblingKey = originalBlockToBeMoved.getPrevSiblingKey();
  var newParentKey = originalTargetBlock.getParentKey();
  var newNextSiblingKey = isInsertedAfterTarget ? originalTargetBlock.getNextSiblingKey() : originalTargetKey;
  var newPrevSiblingKey = isInsertedAfterTarget ? originalTargetKey : originalTargetBlock.getPrevSiblingKey();

  return blockMap.withMutations(function (blocks) {
    // update old parent
    transformBlock(originalParentKey, blocks, function (block) {
      var parentChildrenList = block.getChildKeys();
      return block.merge({
        children: parentChildrenList['delete'](parentChildrenList.indexOf(originalBlockKey))
      });
    });

    // update old prev
    transformBlock(originalPrevSiblingKey, blocks, function (block) {
      return block.merge({
        nextSibling: originalNextSiblingKey
      });
    });

    // update old next
    transformBlock(originalNextSiblingKey, blocks, function (block) {
      return block.merge({
        prevSibling: originalPrevSiblingKey
      });
    });

    // update new next
    transformBlock(newNextSiblingKey, blocks, function (block) {
      return block.merge({
        prevSibling: originalBlockKey
      });
    });

    // update new prev
    transformBlock(newPrevSiblingKey, blocks, function (block) {
      return block.merge({
        nextSibling: originalBlockKey
      });
    });

    // update new parent
    transformBlock(newParentKey, blocks, function (block) {
      var newParentChildrenList = block.getChildKeys();
      var targetBlockIndex = newParentChildrenList.indexOf(originalTargetKey);

      var insertionIndex = isInsertedAfterTarget ? targetBlockIndex + 1 : targetBlockIndex !== 0 ? targetBlockIndex - 1 : 0;

      var newChildrenArray = newParentChildrenList.toArray();
      newChildrenArray.splice(insertionIndex, 0, originalBlockKey);

      return block.merge({
        children: List(newChildrenArray)
      });
    });

    // update block
    transformBlock(originalBlockKey, blocks, function (block) {
      return block.merge({
        nextSibling: newNextSiblingKey,
        prevSibling: newPrevSiblingKey,
        parent: newParentKey
      });
    });
  });
};

var moveBlockInContentState = function moveBlockInContentState(contentState, blockToBeMoved, targetBlock, insertionMode) {
  !(insertionMode !== 'replace') ?  true ? invariant(false, 'Replacing blocks is not supported.') : undefined : void 0;

  var targetKey = targetBlock.getKey();
  var blockKey = blockToBeMoved.getKey();

  !(blockKey !== targetKey) ?  true ? invariant(false, 'Block cannot be moved next to itself.') : undefined : void 0;

  var blockMap = contentState.getBlockMap();
  var isExperimentalTreeBlock = blockToBeMoved instanceof ContentBlockNode;

  var blocksToBeMoved = [blockToBeMoved];
  var blockMapWithoutBlocksToBeMoved = blockMap['delete'](blockKey);

  if (isExperimentalTreeBlock) {
    blocksToBeMoved = [];
    blockMapWithoutBlocksToBeMoved = blockMap.withMutations(function (blocks) {
      var nextSiblingKey = blockToBeMoved.getNextSiblingKey();
      var nextDelimiterBlockKey = getNextDelimiterBlockKey(blockToBeMoved, blocks);

      blocks.toSeq().skipUntil(function (block) {
        return block.getKey() === blockKey;
      }).takeWhile(function (block) {
        var key = block.getKey();
        var isBlockToBeMoved = key === blockKey;
        var hasNextSiblingAndIsNotNextSibling = nextSiblingKey && key !== nextSiblingKey;
        var doesNotHaveNextSiblingAndIsNotDelimiter = !nextSiblingKey && block.getParentKey() && (!nextDelimiterBlockKey || key !== nextDelimiterBlockKey);

        return !!(isBlockToBeMoved || hasNextSiblingAndIsNotNextSibling || doesNotHaveNextSiblingAndIsNotDelimiter);
      }).forEach(function (block) {
        blocksToBeMoved.push(block);
        blocks['delete'](block.getKey());
      });
    });
  }

  var blocksBefore = blockMapWithoutBlocksToBeMoved.toSeq().takeUntil(function (v) {
    return v === targetBlock;
  });

  var blocksAfter = blockMapWithoutBlocksToBeMoved.toSeq().skipUntil(function (v) {
    return v === targetBlock;
  }).skip(1);

  var slicedBlocks = blocksToBeMoved.map(function (block) {
    return [block.getKey(), block];
  });

  var newBlocks = OrderedMap();

  if (insertionMode === 'before') {
    var blockBefore = contentState.getBlockBefore(targetKey);

    !(!blockBefore || blockBefore.getKey() !== blockToBeMoved.getKey()) ?  true ? invariant(false, 'Block cannot be moved next to itself.') : undefined : void 0;

    newBlocks = blocksBefore.concat([].concat(slicedBlocks, [[targetKey, targetBlock]]), blocksAfter).toOrderedMap();
  } else if (insertionMode === 'after') {
    var blockAfter = contentState.getBlockAfter(targetKey);

    !(!blockAfter || blockAfter.getKey() !== blockKey) ?  true ? invariant(false, 'Block cannot be moved next to itself.') : undefined : void 0;

    newBlocks = blocksBefore.concat([[targetKey, targetBlock]].concat(slicedBlocks), blocksAfter).toOrderedMap();
  }

  return contentState.merge({
    blockMap: updateBlockMapLinks(newBlocks, blockToBeMoved, targetBlock, insertionMode, isExperimentalTreeBlock),
    selectionBefore: contentState.getSelectionAfter(),
    selectionAfter: contentState.getSelectionAfter().merge({
      anchorKey: blockKey,
      focusKey: blockKey
    })
  });
};

module.exports = moveBlockInContentState;

/***/ }),

/***/ "I3K3":
/*!****************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/cells/style/placeholder.css ***!
  \****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n/*-----------------------------------------------------------------------------\n| Placeholder\n|----------------------------------------------------------------------------*/\n\n.jp-Placeholder {\n  display: flex;\n  flex-direction: row;\n  flex: 1 1 auto;\n}\n\n.jp-Placeholder-prompt {\n  box-sizing: border-box;\n}\n\n.jp-Placeholder-content {\n  flex: 1 1 auto;\n  border: none;\n  background: transparent;\n  height: 20px;\n  box-sizing: border-box;\n}\n\n.jp-Placeholder-content .jp-MoreHorizIcon {\n  background-repeat: no-repeat;\n  background-position: center;\n  background-size: 32px;\n  width: 32px;\n  height: 16px;\n  border: 1px solid transparent;\n  border-radius: var(--jp-border-radius);\n}\n\n.jp-Placeholder-content .jp-MoreHorizIcon:hover {\n  border: 1px solid var(--jp-border-color1);\n  box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, 0.25);\n  background-color: var(--jp-layout-color0);\n}\n", ""]);

// exports


/***/ }),

/***/ "I4rr":
/*!**************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@phosphor/widgets/style/dockpanel.css ***!
  \**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\r\n| Copyright (c) 2014-2017, PhosphorJS Contributors\r\n|\r\n| Distributed under the terms of the BSD 3-Clause License.\r\n|\r\n| The full license is in the file LICENSE, distributed with this software.\r\n|----------------------------------------------------------------------------*/\r\n\r\n\r\n.p-DockPanel {\r\n  z-index: 0;\r\n}\r\n\r\n\r\n.p-DockPanel-widget {\r\n  z-index: 0;\r\n}\r\n\r\n\r\n.p-DockPanel-tabBar {\r\n  z-index: 1;\r\n}\r\n\r\n\r\n.p-DockPanel-handle {\r\n  z-index: 2;\r\n}\r\n\r\n\r\n.p-DockPanel-handle.p-mod-hidden {\r\n  display: none !important;\r\n}\r\n\r\n\r\n.p-DockPanel-handle:after {\r\n  position: absolute;\r\n  top: 0;\r\n  left: 0;\r\n  width: 100%;\r\n  height: 100%;\r\n  content: '';\r\n}\r\n\r\n\r\n.p-DockPanel-handle[data-orientation='horizontal'] {\r\n  cursor: ew-resize;\r\n}\r\n\r\n\r\n.p-DockPanel-handle[data-orientation='vertical'] {\r\n  cursor: ns-resize;\r\n}\r\n\r\n\r\n.p-DockPanel-handle[data-orientation='horizontal']:after {\r\n  left: 50%;\r\n  min-width: 8px;\r\n  transform: translateX(-50%);\r\n}\r\n\r\n\r\n.p-DockPanel-handle[data-orientation='vertical']:after {\r\n  top: 50%;\r\n  min-height: 8px;\r\n  transform: translateY(-50%);\r\n}\r\n\r\n\r\n.p-DockPanel-overlay {\r\n  z-index: 3;\r\n  box-sizing: border-box;\r\n  pointer-events: none;\r\n}\r\n\r\n\r\n.p-DockPanel-overlay.p-mod-hidden {\r\n  display: none !important;\r\n}\r\n", ""]);

// exports


/***/ }),

/***/ "I8OZ":
/*!*****************************************************!*\
  !*** ./node_modules/fbjs/lib/UnicodeBidiService.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks
 * 
 */

/**
 * Stateful API for text direction detection
 *
 * This class can be used in applications where you need to detect the
 * direction of a sequence of text blocks, where each direction shall be used
 * as the fallback direction for the next one.
 *
 * NOTE: A default direction, if not provided, is set based on the global
 *       direction, as defined by `UnicodeBidiDirection`.
 *
 * == Example ==
 * ```
 * var UnicodeBidiService = require('UnicodeBidiService');
 *
 * var bidiService = new UnicodeBidiService();
 *
 * ...
 *
 * bidiService.reset();
 * for (var para in paragraphs) {
 *   var dir = bidiService.getDirection(para);
 *   ...
 * }
 * ```
 *
 * Part of our implementation of Unicode Bidirectional Algorithm (UBA)
 * Unicode Standard Annex #9 (UAX9)
 * http://www.unicode.org/reports/tr9/
 */



function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var UnicodeBidi = __webpack_require__(/*! ./UnicodeBidi */ "fZAc");
var UnicodeBidiDirection = __webpack_require__(/*! ./UnicodeBidiDirection */ "mjHj");

var invariant = __webpack_require__(/*! ./invariant */ "2NuI");

var UnicodeBidiService = function () {

  /**
   * Stateful class for paragraph direction detection
   *
   * @param defaultDir  Default direction of the service
   */
  function UnicodeBidiService(defaultDir) {
    _classCallCheck(this, UnicodeBidiService);

    if (!defaultDir) {
      defaultDir = UnicodeBidiDirection.getGlobalDir();
    } else {
      !UnicodeBidiDirection.isStrong(defaultDir) ?  true ? invariant(false, 'Default direction must be a strong direction (LTR or RTL)') : undefined : void 0;
    }
    this._defaultDir = defaultDir;
    this.reset();
  }

  /**
   * Reset the internal state
   *
   * Instead of creating a new instance, you can just reset() your instance
   * everytime you start a new loop.
   */


  UnicodeBidiService.prototype.reset = function reset() {
    this._lastDir = this._defaultDir;
  };

  /**
   * Returns the direction of a block of text, and remembers it as the
   * fall-back direction for the next paragraph.
   *
   * @param str  A text block, e.g. paragraph, table cell, tag
   * @return     The resolved direction
   */


  UnicodeBidiService.prototype.getDirection = function getDirection(str) {
    this._lastDir = UnicodeBidi.getDirection(str, this._lastDir);
    return this._lastDir;
  };

  return UnicodeBidiService;
}();

module.exports = UnicodeBidiService;

/***/ }),

/***/ "I9Sh":
/*!************************************************************!*\
  !*** ./node_modules/@jupyterlab/application/lib/router.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const coreutils_2 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const disposable_1 = __webpack_require__(/*! @phosphor/disposable */ "uNUc");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
/* tslint:disable */
/**
 * The URL Router token.
 */
exports.IRouter = new coreutils_2.Token('@jupyterlab/application:IRouter');
/**
 * A static class that routes URLs within the application.
 */
class Router {
    /**
     * Create a URL router.
     */
    constructor(options) {
        /**
         * If a matching rule's command resolves with the `stop` token during routing,
         * no further matches will execute.
         */
        this.stop = new coreutils_2.Token('@jupyterlab/application:Router#stop');
        this._routed = new signaling_1.Signal(this);
        this._rules = new Map();
        this.base = options.base;
        this.commands = options.commands;
    }
    /**
     * Returns the parsed current URL of the application.
     */
    get current() {
        const { base } = this;
        const parsed = coreutils_1.URLExt.parse(window.location.href);
        const { search, hash } = parsed;
        const path = parsed.pathname.replace(base, '/');
        const request = path + search + hash;
        return { hash, path, request, search };
    }
    /**
     * A signal emitted when the router routes a route.
     */
    get routed() {
        return this._routed;
    }
    /**
     * Navigate to a new path within the application.
     *
     * @param path - The new path or empty string if redirecting to root.
     *
     * @param options - The navigation options.
     */
    navigate(path, options = {}) {
        const { base } = this;
        const { history } = window;
        const { hard, silent } = options;
        const url = path && path.indexOf(base) === 0 ? path : coreutils_1.URLExt.join(base, path);
        if (silent) {
            history.replaceState({}, '', url);
        }
        else {
            history.pushState({}, '', url);
        }
        if (hard) {
            return this.reload();
        }
        // Because a `route()` call may still be in the stack after having received
        // a `stop` token, wait for the next stack frame before calling `route()`.
        requestAnimationFrame(() => {
            this.route();
        });
    }
    /**
     * Register to route a path pattern to a command.
     *
     * @param options - The route registration options.
     *
     * @returns A disposable that removes the registered rule from the router.
     */
    register(options) {
        const { command, pattern } = options;
        const rank = 'rank' in options ? options.rank : 100;
        const rules = this._rules;
        rules.set(pattern, { command, rank });
        return new disposable_1.DisposableDelegate(() => {
            rules.delete(pattern);
        });
    }
    /**
     * Cause a hard reload of the document.
     */
    reload() {
        window.location.reload();
    }
    /**
     * Route a specific path to an action.
     *
     * #### Notes
     * If a pattern is matched, its command will be invoked with arguments that
     * match the `IRouter.ILocation` interface.
     */
    route() {
        const { commands, current, stop } = this;
        const { request } = current;
        const routed = this._routed;
        const rules = this._rules;
        const matches = [];
        // Collect all rules that match the URL.
        rules.forEach((rule, pattern) => {
            if (request.match(pattern)) {
                matches.push(rule);
            }
        });
        // Order the matching rules by rank and enqueue them.
        const queue = matches.sort((a, b) => b.rank - a.rank);
        // Process each enqueued command sequentially and short-circuit if a promise
        // resolves with the `stop` token.
        (function next() {
            if (!queue.length) {
                routed.emit(current);
                return;
            }
            const { command } = queue.pop();
            commands
                .execute(command, current)
                .then(result => {
                if (result === stop) {
                    queue.length = 0;
                    console.log(`Routing ${request} was short-circuited by ${command}`);
                }
                next();
            })
                .catch(reason => {
                console.warn(`Routing ${request} to ${command} failed`, reason);
                next();
            });
        })();
    }
}
exports.Router = Router;


/***/ }),

/***/ "IBtZ":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/ka.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var ka = moment.defineLocale('ka', {
    months : {
        standalone: 'იანვარი_თებერვალი_მარტი_აპრილი_მაისი_ივნისი_ივლისი_აგვისტო_სექტემბერი_ოქტომბერი_ნოემბერი_დეკემბერი'.split('_'),
        format: 'იანვარს_თებერვალს_მარტს_აპრილის_მაისს_ივნისს_ივლისს_აგვისტს_სექტემბერს_ოქტომბერს_ნოემბერს_დეკემბერს'.split('_')
    },
    monthsShort : 'იან_თებ_მარ_აპრ_მაი_ივნ_ივლ_აგვ_სექ_ოქტ_ნოე_დეკ'.split('_'),
    weekdays : {
        standalone: 'კვირა_ორშაბათი_სამშაბათი_ოთხშაბათი_ხუთშაბათი_პარასკევი_შაბათი'.split('_'),
        format: 'კვირას_ორშაბათს_სამშაბათს_ოთხშაბათს_ხუთშაბათს_პარასკევს_შაბათს'.split('_'),
        isFormat: /(წინა|შემდეგ)/
    },
    weekdaysShort : 'კვი_ორშ_სამ_ოთხ_ხუთ_პარ_შაბ'.split('_'),
    weekdaysMin : 'კვ_ორ_სა_ოთ_ხუ_პა_შა'.split('_'),
    longDateFormat : {
        LT : 'h:mm A',
        LTS : 'h:mm:ss A',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY h:mm A',
        LLLL : 'dddd, D MMMM YYYY h:mm A'
    },
    calendar : {
        sameDay : '[დღეს] LT[-ზე]',
        nextDay : '[ხვალ] LT[-ზე]',
        lastDay : '[გუშინ] LT[-ზე]',
        nextWeek : '[შემდეგ] dddd LT[-ზე]',
        lastWeek : '[წინა] dddd LT-ზე',
        sameElse : 'L'
    },
    relativeTime : {
        future : function (s) {
            return (/(წამი|წუთი|საათი|წელი)/).test(s) ?
                s.replace(/ი$/, 'ში') :
                s + 'ში';
        },
        past : function (s) {
            if ((/(წამი|წუთი|საათი|დღე|თვე)/).test(s)) {
                return s.replace(/(ი|ე)$/, 'ის უკან');
            }
            if ((/წელი/).test(s)) {
                return s.replace(/წელი$/, 'წლის უკან');
            }
        },
        s : 'რამდენიმე წამი',
        ss : '%d წამი',
        m : 'წუთი',
        mm : '%d წუთი',
        h : 'საათი',
        hh : '%d საათი',
        d : 'დღე',
        dd : '%d დღე',
        M : 'თვე',
        MM : '%d თვე',
        y : 'წელი',
        yy : '%d წელი'
    },
    dayOfMonthOrdinalParse: /0|1-ლი|მე-\d{1,2}|\d{1,2}-ე/,
    ordinal : function (number) {
        if (number === 0) {
            return number;
        }
        if (number === 1) {
            return number + '-ლი';
        }
        if ((number < 20) || (number <= 100 && (number % 20 === 0)) || (number % 100 === 0)) {
            return 'მე-' + number;
        }
        return number + '-ე';
    },
    week : {
        dow : 1,
        doy : 7
    }
});

return ka;

})));


/***/ }),

/***/ "IBvg":
/*!*****************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/TraceRequiredPanel.js ***!
  \*****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _PanelEmpty = __webpack_require__(/*! ./PanelEmpty */ "o21U");

var _PanelEmpty2 = _interopRequireDefault(_PanelEmpty);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _derived = __webpack_require__(/*! ./derived */ "ykRn");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var TraceRequiredPanel = function (_Component) {
  _inherits(TraceRequiredPanel, _Component);

  function TraceRequiredPanel() {
    _classCallCheck(this, TraceRequiredPanel);

    return _possibleConstructorReturn(this, (TraceRequiredPanel.__proto__ || Object.getPrototypeOf(TraceRequiredPanel)).apply(this, arguments));
  }

  _createClass(TraceRequiredPanel, [{
    key: 'hasTrace',
    value: function hasTrace() {
      return this.context.fullData.filter(function (trace) {
        return trace.visible;
      }).length > 0;
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _ = this.context.localize;

      var _props = this.props,
          children = _props.children,
          rest = _objectWithoutProperties(_props, ['children']);

      if (!this.props.visible) {
        return null;
      }

      return this.hasTrace() ? _react2.default.createElement(
        _derived.LayoutPanel,
        rest,
        children
      ) : _react2.default.createElement(
        _PanelEmpty2.default,
        { heading: _("Looks like there aren't any traces defined yet.") },
        _react2.default.createElement(
          'p',
          null,
          _('Go to the '),
          _react2.default.createElement(
            'a',
            { onClick: function onClick() {
                return _this2.context.setPanel('Structure', 'Traces');
              } },
            _('Traces')
          ),
          _(' panel under Structure to define traces.')
        )
      );
    }
  }]);

  return TraceRequiredPanel;
}(_react.Component);

TraceRequiredPanel.propTypes = {
  children: _propTypes2.default.node,
  visible: _propTypes2.default.bool
};

TraceRequiredPanel.defaultProps = {
  visible: true
};

TraceRequiredPanel.contextTypes = {
  fullData: _propTypes2.default.array,
  localize: _propTypes2.default.func,
  setPanel: _propTypes2.default.func
};

exports.default = TraceRequiredPanel;
//# sourceMappingURL=TraceRequiredPanel.js.map

/***/ }),

/***/ "ICOY":
/*!*****************************************************!*\
  !*** ./node_modules/react-json-tree/lib/objType.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _iterator = __webpack_require__(/*! babel-runtime/core-js/symbol/iterator */ "F+2o");

var _iterator2 = _interopRequireDefault(_iterator);

exports['default'] = objType;

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

function objType(obj) {
  var type = Object.prototype.toString.call(obj).slice(8, -1);
  if (type === 'Object' && typeof obj[_iterator2['default']] === 'function') {
    return 'Iterable';
  }

  if (type === 'Custom' && obj.constructor !== Object && obj instanceof Object) {
    // For projects implementing objects overriding `.prototype[Symbol.toStringTag]`
    return 'Object';
  }

  return type;
}

/***/ }),

/***/ "IG1u":
/*!******************************************!*\
  !*** ./node_modules/pbkdf2/lib/async.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global, process) {var checkParameters = __webpack_require__(/*! ./precondition */ "fSpj")
var defaultEncoding = __webpack_require__(/*! ./default-encoding */ "n53Y")
var sync = __webpack_require__(/*! ./sync */ "4Hv8")
var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer

var ZERO_BUF
var subtle = global.crypto && global.crypto.subtle
var toBrowser = {
  'sha': 'SHA-1',
  'sha-1': 'SHA-1',
  'sha1': 'SHA-1',
  'sha256': 'SHA-256',
  'sha-256': 'SHA-256',
  'sha384': 'SHA-384',
  'sha-384': 'SHA-384',
  'sha-512': 'SHA-512',
  'sha512': 'SHA-512'
}
var checks = []
function checkNative (algo) {
  if (global.process && !global.process.browser) {
    return Promise.resolve(false)
  }
  if (!subtle || !subtle.importKey || !subtle.deriveBits) {
    return Promise.resolve(false)
  }
  if (checks[algo] !== undefined) {
    return checks[algo]
  }
  ZERO_BUF = ZERO_BUF || Buffer.alloc(8)
  var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo)
    .then(function () {
      return true
    }).catch(function () {
      return false
    })
  checks[algo] = prom
  return prom
}

function browserPbkdf2 (password, salt, iterations, length, algo) {
  return subtle.importKey(
    'raw', password, {name: 'PBKDF2'}, false, ['deriveBits']
  ).then(function (key) {
    return subtle.deriveBits({
      name: 'PBKDF2',
      salt: salt,
      iterations: iterations,
      hash: {
        name: algo
      }
    }, key, length << 3)
  }).then(function (res) {
    return Buffer.from(res)
  })
}

function resolvePromise (promise, callback) {
  promise.then(function (out) {
    process.nextTick(function () {
      callback(null, out)
    })
  }, function (e) {
    process.nextTick(function () {
      callback(e)
    })
  })
}
module.exports = function (password, salt, iterations, keylen, digest, callback) {
  if (typeof digest === 'function') {
    callback = digest
    digest = undefined
  }

  digest = digest || 'sha1'
  var algo = toBrowser[digest.toLowerCase()]

  if (!algo || typeof global.Promise !== 'function') {
    return process.nextTick(function () {
      var out
      try {
        out = sync(password, salt, iterations, keylen, digest)
      } catch (e) {
        return callback(e)
      }
      callback(null, out)
    })
  }

  checkParameters(password, salt, iterations, keylen)
  if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2')
  if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding)
  if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding)

  resolvePromise(checkNative(algo).then(function (resp) {
    if (resp) return browserPbkdf2(password, salt, iterations, keylen, algo)

    return sync(password, salt, iterations, keylen, digest)
  }), callback)
}

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "yLpj"), __webpack_require__(/*! ./../../process/browser.js */ "8oxB")))

/***/ }),

/***/ "IHQy":
/*!*************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/mathjax2/style/index.css ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n/* Left-justify the MathJax preview in cell outputs. */\n.jp-OutputArea-output.jp-RenderedLatex .MathJax_Preview .MJXp-display {\n  text-align: left !important;\n}\n\n/* Left-justify the MathJax display equation in cell outputs. */\n.jp-OutputArea-output.jp-RenderedLatex .MathJax_Display {\n  text-align: left !important;\n}\n", ""]);

// exports


/***/ }),

/***/ "IMnP":
/*!************************************************************!*\
  !*** ./node_modules/@jupyterlab/cells/lib/headerfooter.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
/**
 * The CSS class added to the cell header.
 */
const CELL_HEADER_CLASS = 'jp-CellHeader';
/**
 * The CSS class added to the cell footer.
 */
const CELL_FOOTER_CLASS = 'jp-CellFooter';
/**
 * Default implementation of a cell header.
 */
class CellHeader extends widgets_1.Widget {
    /**
     * Construct a new cell header.
     */
    constructor() {
        super();
        this.addClass(CELL_HEADER_CLASS);
    }
}
exports.CellHeader = CellHeader;
/**
 * Default implementation of a cell footer.
 */
class CellFooter extends widgets_1.Widget {
    /**
     * Construct a new cell footer.
     */
    constructor() {
        super();
        this.addClass(CELL_FOOTER_CLASS);
    }
}
exports.CellFooter = CellFooter;


/***/ }),

/***/ "IOzZ":
/*!*********************************************************!*\
  !*** ./node_modules/lodash/_matchesStrictComparable.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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)));
  };
}

module.exports = matchesStrictComparable;


/***/ }),

/***/ "IPZY":
/*!*********************************************************!*\
  !*** ./node_modules/asn1.js/lib/asn1/decoders/index.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var decoders = exports;

decoders.der = __webpack_require__(/*! ./der */ "z71Z");
decoders.pem = __webpack_require__(/*! ./pem */ "jfd1");


/***/ }),

/***/ "ISR0":
/*!*************************************************************!*\
  !*** ./node_modules/draft-js/lib/DraftEditorDragHandler.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DraftEditorDragHandler
 * @format
 * 
 */



var DataTransfer = __webpack_require__(/*! fbjs/lib/DataTransfer */ "QvxS");
var DraftModifier = __webpack_require__(/*! ./DraftModifier */ "fyOY");
var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");

var findAncestorOffsetKey = __webpack_require__(/*! ./findAncestorOffsetKey */ "kc9Y");
var getTextContentFromFiles = __webpack_require__(/*! ./getTextContentFromFiles */ "HKS5");
var getUpdatedSelectionState = __webpack_require__(/*! ./getUpdatedSelectionState */ "5RSi");
var isEventHandled = __webpack_require__(/*! ./isEventHandled */ "T401");
var nullthrows = __webpack_require__(/*! fbjs/lib/nullthrows */ "gWRK");

/**
 * Get a SelectionState for the supplied mouse event.
 */
function getSelectionForEvent(event, editorState) {
  var node = null;
  var offset = null;

  if (typeof document.caretRangeFromPoint === 'function') {
    var dropRange = document.caretRangeFromPoint(event.x, event.y);
    node = dropRange.startContainer;
    offset = dropRange.startOffset;
  } else if (event.rangeParent) {
    node = event.rangeParent;
    offset = event.rangeOffset;
  } else {
    return null;
  }

  node = nullthrows(node);
  offset = nullthrows(offset);
  var offsetKey = nullthrows(findAncestorOffsetKey(node));

  return getUpdatedSelectionState(editorState, offsetKey, offset, offsetKey, offset);
}

var DraftEditorDragHandler = {
  /**
   * Drag originating from input terminated.
   */
  onDragEnd: function onDragEnd(editor) {
    editor.exitCurrentMode();
  },

  /**
   * Handle data being dropped.
   */
  onDrop: function onDrop(editor, e) {
    var data = new DataTransfer(e.nativeEvent.dataTransfer);

    var editorState = editor._latestEditorState;
    var dropSelection = getSelectionForEvent(e.nativeEvent, editorState);

    e.preventDefault();
    editor.exitCurrentMode();

    if (dropSelection == null) {
      return;
    }

    var files = data.getFiles();
    if (files.length > 0) {
      if (editor.props.handleDroppedFiles && isEventHandled(editor.props.handleDroppedFiles(dropSelection, files))) {
        return;
      }

      getTextContentFromFiles(files, function (fileText) {
        fileText && editor.update(insertTextAtSelection(editorState, dropSelection, fileText));
      });
      return;
    }

    var dragType = editor._internalDrag ? 'internal' : 'external';
    if (editor.props.handleDrop && isEventHandled(editor.props.handleDrop(dropSelection, data, dragType))) {
      return;
    }

    if (editor._internalDrag) {
      editor.update(moveText(editorState, dropSelection));
      return;
    }

    editor.update(insertTextAtSelection(editorState, dropSelection, data.getText()));
  }
};

function moveText(editorState, targetSelection) {
  var newContentState = DraftModifier.moveText(editorState.getCurrentContent(), editorState.getSelection(), targetSelection);
  return EditorState.push(editorState, newContentState, 'insert-fragment');
}

/**
 * Insert text at a specified selection.
 */
function insertTextAtSelection(editorState, selection, text) {
  var newContentState = DraftModifier.insertText(editorState.getCurrentContent(), selection, text, editorState.getCurrentInlineStyle());
  return EditorState.push(editorState, newContentState, 'insert-fragment');
}

module.exports = DraftEditorDragHandler;

/***/ }),

/***/ "ISee":
/*!***********************************************************************!*\
  !*** ./node_modules/draft-js/lib/getDraftEditorSelectionWithNodes.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule getDraftEditorSelectionWithNodes
 * @format
 * 
 */



var findAncestorOffsetKey = __webpack_require__(/*! ./findAncestorOffsetKey */ "kc9Y");
var getSelectionOffsetKeyForNode = __webpack_require__(/*! ./getSelectionOffsetKeyForNode */ "zORg");
var getUpdatedSelectionState = __webpack_require__(/*! ./getUpdatedSelectionState */ "5RSi");
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");
var nullthrows = __webpack_require__(/*! fbjs/lib/nullthrows */ "gWRK");

/**
 * Convert the current selection range to an anchor/focus pair of offset keys
 * and values that can be interpreted by components.
 */
function getDraftEditorSelectionWithNodes(editorState, root, anchorNode, anchorOffset, focusNode, focusOffset) {
  var anchorIsTextNode = anchorNode.nodeType === Node.TEXT_NODE;
  var focusIsTextNode = focusNode.nodeType === Node.TEXT_NODE;

  // If the selection range lies only on text nodes, the task is simple.
  // Find the nearest offset-aware elements and use the
  // offset values supplied by the selection range.
  if (anchorIsTextNode && focusIsTextNode) {
    return {
      selectionState: getUpdatedSelectionState(editorState, nullthrows(findAncestorOffsetKey(anchorNode)), anchorOffset, nullthrows(findAncestorOffsetKey(focusNode)), focusOffset),
      needsRecovery: false
    };
  }

  var anchorPoint = null;
  var focusPoint = null;
  var needsRecovery = true;

  // An element is selected. Convert this selection range into leaf offset
  // keys and offset values for consumption at the component level. This
  // is common in Firefox, where select-all and triple click behavior leads
  // to entire elements being selected.
  //
  // Note that we use the `needsRecovery` parameter in the callback here. This
  // is because when certain elements are selected, the behavior for subsequent
  // cursor movement (e.g. via arrow keys) is uncertain and may not match
  // expectations at the component level. For example, if an entire <div> is
  // selected and the user presses the right arrow, Firefox keeps the selection
  // on the <div>. If we allow subsequent keypresses to insert characters
  // natively, they will be inserted into a browser-created text node to the
  // right of that <div>. This is obviously undesirable.
  //
  // With the `needsRecovery` flag, we inform the caller that it is responsible
  // for manually setting the selection state on the rendered document to
  // ensure proper selection state maintenance.

  if (anchorIsTextNode) {
    anchorPoint = {
      key: nullthrows(findAncestorOffsetKey(anchorNode)),
      offset: anchorOffset
    };
    focusPoint = getPointForNonTextNode(root, focusNode, focusOffset);
  } else if (focusIsTextNode) {
    focusPoint = {
      key: nullthrows(findAncestorOffsetKey(focusNode)),
      offset: focusOffset
    };
    anchorPoint = getPointForNonTextNode(root, anchorNode, anchorOffset);
  } else {
    anchorPoint = getPointForNonTextNode(root, anchorNode, anchorOffset);
    focusPoint = getPointForNonTextNode(root, focusNode, focusOffset);

    // If the selection is collapsed on an empty block, don't force recovery.
    // This way, on arrow key selection changes, the browser can move the
    // cursor from a non-zero offset on one block, through empty blocks,
    // to a matching non-zero offset on other text blocks.
    if (anchorNode === focusNode && anchorOffset === focusOffset) {
      needsRecovery = !!anchorNode.firstChild && anchorNode.firstChild.nodeName !== 'BR';
    }
  }

  return {
    selectionState: getUpdatedSelectionState(editorState, anchorPoint.key, anchorPoint.offset, focusPoint.key, focusPoint.offset),
    needsRecovery: needsRecovery
  };
}

/**
 * Identify the first leaf descendant for the given node.
 */
function getFirstLeaf(node) {
  while (node.firstChild && (
  // data-blocks has no offset
  node.firstChild instanceof Element && node.firstChild.getAttribute('data-blocks') === 'true' || getSelectionOffsetKeyForNode(node.firstChild))) {
    node = node.firstChild;
  }
  return node;
}

/**
 * Identify the last leaf descendant for the given node.
 */
function getLastLeaf(node) {
  while (node.lastChild && (
  // data-blocks has no offset
  node.lastChild instanceof Element && node.lastChild.getAttribute('data-blocks') === 'true' || getSelectionOffsetKeyForNode(node.lastChild))) {
    node = node.lastChild;
  }
  return node;
}

function getPointForNonTextNode(editorRoot, startNode, childOffset) {
  var node = startNode;
  var offsetKey = findAncestorOffsetKey(node);

  !(offsetKey != null || editorRoot && (editorRoot === node || editorRoot.firstChild === node)) ?  true ? invariant(false, 'Unknown node in selection range.') : undefined : void 0;

  // If the editorRoot is the selection, step downward into the content
  // wrapper.
  if (editorRoot === node) {
    node = node.firstChild;
    !(node instanceof Element && node.getAttribute('data-contents') === 'true') ?  true ? invariant(false, 'Invalid DraftEditorContents structure.') : undefined : void 0;
    if (childOffset > 0) {
      childOffset = node.childNodes.length;
    }
  }

  // If the child offset is zero and we have an offset key, we're done.
  // If there's no offset key because the entire editor is selected,
  // find the leftmost ("first") leaf in the tree and use that as the offset
  // key.
  if (childOffset === 0) {
    var key = null;
    if (offsetKey != null) {
      key = offsetKey;
    } else {
      var firstLeaf = getFirstLeaf(node);
      key = nullthrows(getSelectionOffsetKeyForNode(firstLeaf));
    }
    return { key: key, offset: 0 };
  }

  var nodeBeforeCursor = node.childNodes[childOffset - 1];
  var leafKey = null;
  var textLength = null;

  if (!getSelectionOffsetKeyForNode(nodeBeforeCursor)) {
    // Our target node may be a leaf or a text node, in which case we're
    // already where we want to be and can just use the child's length as
    // our offset.
    leafKey = nullthrows(offsetKey);
    textLength = getTextContentLength(nodeBeforeCursor);
  } else {
    // Otherwise, we'll look at the child to the left of the cursor and find
    // the last leaf node in its subtree.
    var lastLeaf = getLastLeaf(nodeBeforeCursor);
    leafKey = nullthrows(getSelectionOffsetKeyForNode(lastLeaf));
    textLength = getTextContentLength(lastLeaf);
  }

  return {
    key: leafKey,
    offset: textLength
  };
}

/**
 * Return the length of a node's textContent, regarding single newline
 * characters as zero-length. This allows us to avoid problems with identifying
 * the correct selection offset for empty blocks in IE, in which we
 * render newlines instead of break tags.
 */
function getTextContentLength(node) {
  var textContent = node.textContent;
  return textContent === '\n' ? 0 : textContent.length;
}

module.exports = getDraftEditorSelectionWithNodes;

/***/ }),

/***/ "ITfd":
/*!***********************************************!*\
  !*** ./node_modules/hash.js/lib/hash/hmac.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var utils = __webpack_require__(/*! ./utils */ "w8CP");
var assert = __webpack_require__(/*! minimalistic-assert */ "2j6C");

function Hmac(hash, key, enc) {
  if (!(this instanceof Hmac))
    return new Hmac(hash, key, enc);
  this.Hash = hash;
  this.blockSize = hash.blockSize / 8;
  this.outSize = hash.outSize / 8;
  this.inner = null;
  this.outer = null;

  this._init(utils.toArray(key, enc));
}
module.exports = Hmac;

Hmac.prototype._init = function init(key) {
  // Shorten key, if needed
  if (key.length > this.blockSize)
    key = new this.Hash().update(key).digest();
  assert(key.length <= this.blockSize);

  // Add padding to key
  for (var i = key.length; i < this.blockSize; i++)
    key.push(0);

  for (i = 0; i < key.length; i++)
    key[i] ^= 0x36;
  this.inner = new this.Hash().update(key);

  // 0x36 ^ 0x5c = 0x6a
  for (i = 0; i < key.length; i++)
    key[i] ^= 0x6a;
  this.outer = new this.Hash().update(key);
};

Hmac.prototype.update = function update(msg, enc) {
  this.inner.update(msg, enc);
  return this;
};

Hmac.prototype.digest = function digest(enc) {
  this.outer.update(this.inner.digest());
  return this.outer.digest(enc);
};


/***/ }),

/***/ "IVJK":
/*!*********************************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils-extension/style/index.css ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "OM9w");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "IXoA":
/*!***********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotParcoordsIcon.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotParcoordsIcon = function PlotParcoordsIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M.875.25h.313c.5.125.875.5.875 1v4.938C6.251 5.125 10.501 4.063 14.688 3V1.25c0-.5.375-.875.813-1h.375c.438.125.875.5.875 1v2.188c4.375 1.688 8.813 3.313 13.188 4.938V1.251c0-.438.375-.875.875-1h.313c.438.125.75.438.875.813v29.875c-.125.375-.375.688-.75.813h-.563a1.07 1.07 0 0 1-.75-1v-3c-2.25-1.813-4.438-3.625-6.688-5.438a487.954 487.954 0 0 1-6.5 5.313v3.125c0 .438-.375.875-.75 1h-.563a1.07 1.07 0 0 1-.75-1v-2.75c-4.188-.813-8.438-1.563-12.625-2.375v5.125c0 .438-.375.875-.75 1H.75a1.18 1.18 0 0 1-.75-.875V1.127C.063.689.438.377.875.252M2.063 7.25v11.313c4.188-1.063 8.375-2.125 12.625-3.188V4.062A3664.18 3664.18 0 0 0 2.063 7.25M16.75 4.563v11.125a487.954 487.954 0 0 0 6.5 5.313c2.188-1.813 4.375-3.563 6.625-5.375 0 0 .063-.063.063-.125v-6c-4.375-1.625-8.813-3.313-13.188-4.938M2.063 19.625v4.938c4.188.813 8.375 1.563 12.625 2.375V16.5c-4.25 1-8.438 2.063-12.625 3.125m22.125 2c-.063 0-.063 0-.125.063 2 1.563 3.938 3.125 5.875 4.75v-9.5c-1.938 1.563-3.875 3.125-5.75 4.688m-7.438-4.563v9.188c1.875-1.5 3.75-3.063 5.688-4.563a366.502 366.502 0 0 0-5.688-4.625z' })
    );
};

exports.default = PlotParcoordsIcon;

/***/ }),

/***/ "Idtq":
/*!****************************************************************!*\
  !*** ./node_modules/draft-js/lib/DraftEditorContents.react.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DraftEditorContents.react
 * @format
 * 
 */



var DraftEditorContents = __webpack_require__(/*! ./DraftEditorContents-core.react */ "Y3PQ");

module.exports = DraftEditorContents;

/***/ }),

/***/ "Ihzh":
/*!******************************************!*\
  !*** ./node_modules/base16/lib/index.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

function _interopRequire(obj) { return obj && obj.__esModule ? obj['default'] : obj; }

var _threezerotwofour = __webpack_require__(/*! ./threezerotwofour */ "FMM9");

exports.threezerotwofour = _interopRequire(_threezerotwofour);

var _apathy = __webpack_require__(/*! ./apathy */ "D5hx");

exports.apathy = _interopRequire(_apathy);

var _ashes = __webpack_require__(/*! ./ashes */ "zFpJ");

exports.ashes = _interopRequire(_ashes);

var _atelierDune = __webpack_require__(/*! ./atelier-dune */ "+/up");

exports.atelierDune = _interopRequire(_atelierDune);

var _atelierForest = __webpack_require__(/*! ./atelier-forest */ "7KeA");

exports.atelierForest = _interopRequire(_atelierForest);

var _atelierHeath = __webpack_require__(/*! ./atelier-heath */ "5FFA");

exports.atelierHeath = _interopRequire(_atelierHeath);

var _atelierLakeside = __webpack_require__(/*! ./atelier-lakeside */ "99I3");

exports.atelierLakeside = _interopRequire(_atelierLakeside);

var _atelierSeaside = __webpack_require__(/*! ./atelier-seaside */ "ZMQG");

exports.atelierSeaside = _interopRequire(_atelierSeaside);

var _bespin = __webpack_require__(/*! ./bespin */ "Fzdc");

exports.bespin = _interopRequire(_bespin);

var _brewer = __webpack_require__(/*! ./brewer */ "opHZ");

exports.brewer = _interopRequire(_brewer);

var _bright = __webpack_require__(/*! ./bright */ "CjjH");

exports.bright = _interopRequire(_bright);

var _chalk = __webpack_require__(/*! ./chalk */ "ju9h");

exports.chalk = _interopRequire(_chalk);

var _codeschool = __webpack_require__(/*! ./codeschool */ "KFpz");

exports.codeschool = _interopRequire(_codeschool);

var _colors = __webpack_require__(/*! ./colors */ "pq2K");

exports.colors = _interopRequire(_colors);

var _default = __webpack_require__(/*! ./default */ "Pxmx");

exports['default'] = _interopRequire(_default);

var _eighties = __webpack_require__(/*! ./eighties */ "Vgfr");

exports.eighties = _interopRequire(_eighties);

var _embers = __webpack_require__(/*! ./embers */ "yyUu");

exports.embers = _interopRequire(_embers);

var _flat = __webpack_require__(/*! ./flat */ "Vp1n");

exports.flat = _interopRequire(_flat);

var _google = __webpack_require__(/*! ./google */ "Udc6");

exports.google = _interopRequire(_google);

var _grayscale = __webpack_require__(/*! ./grayscale */ "sBam");

exports.grayscale = _interopRequire(_grayscale);

var _greenscreen = __webpack_require__(/*! ./greenscreen */ "yZE0");

exports.greenscreen = _interopRequire(_greenscreen);

var _harmonic = __webpack_require__(/*! ./harmonic */ "lw7W");

exports.harmonic = _interopRequire(_harmonic);

var _hopscotch = __webpack_require__(/*! ./hopscotch */ "JOSh");

exports.hopscotch = _interopRequire(_hopscotch);

var _isotope = __webpack_require__(/*! ./isotope */ "V/5U");

exports.isotope = _interopRequire(_isotope);

var _marrakesh = __webpack_require__(/*! ./marrakesh */ "chXj");

exports.marrakesh = _interopRequire(_marrakesh);

var _mocha = __webpack_require__(/*! ./mocha */ "DfxN");

exports.mocha = _interopRequire(_mocha);

var _monokai = __webpack_require__(/*! ./monokai */ "aic/");

exports.monokai = _interopRequire(_monokai);

var _ocean = __webpack_require__(/*! ./ocean */ "0TAD");

exports.ocean = _interopRequire(_ocean);

var _paraiso = __webpack_require__(/*! ./paraiso */ "C26z");

exports.paraiso = _interopRequire(_paraiso);

var _pop = __webpack_require__(/*! ./pop */ "6xfF");

exports.pop = _interopRequire(_pop);

var _railscasts = __webpack_require__(/*! ./railscasts */ "LRzW");

exports.railscasts = _interopRequire(_railscasts);

var _shapeshifter = __webpack_require__(/*! ./shapeshifter */ "Ezr3");

exports.shapeshifter = _interopRequire(_shapeshifter);

var _solarized = __webpack_require__(/*! ./solarized */ "lDDf");

exports.solarized = _interopRequire(_solarized);

var _summerfruit = __webpack_require__(/*! ./summerfruit */ "R/zK");

exports.summerfruit = _interopRequire(_summerfruit);

var _tomorrow = __webpack_require__(/*! ./tomorrow */ "YAoJ");

exports.tomorrow = _interopRequire(_tomorrow);

var _tube = __webpack_require__(/*! ./tube */ "Wl7T");

exports.tube = _interopRequire(_tube);

var _twilight = __webpack_require__(/*! ./twilight */ "XW4k");

exports.twilight = _interopRequire(_twilight);

/***/ }),

/***/ "IiDj":
/*!*******************************************************!*\
  !*** ./node_modules/@phosphor/coreutils/lib/token.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * A runtime object which captures compile-time type information.
 *
 * #### Notes
 * A token captures the compile-time type of an interface or class in
 * an object which can be used at runtime in a type-safe fashion.
 */
var Token = (function () {
    /**
     * Construct a new token.
     *
     * @param name - A human readable name for the token.
     */
    function Token(name) {
        this.name = name;
        this._tokenStructuralPropertyT = null;
    }
    return Token;
}());
exports.Token = Token;


/***/ }),

/***/ "Im2J":
/*!********************************************************!*\
  !*** ./node_modules/xterm/lib/AccessibilityManager.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var Strings = __webpack_require__(/*! ./Strings */ "hqvf");
var Browser_1 = __webpack_require__(/*! ./shared/utils/Browser */ "1XL3");
var RenderDebouncer_1 = __webpack_require__(/*! ./utils/RenderDebouncer */ "zjAe");
var Dom_1 = __webpack_require__(/*! ./utils/Dom */ "4Pvz");
var MAX_ROWS_TO_READ = 20;
var BoundaryPosition;
(function (BoundaryPosition) {
    BoundaryPosition[BoundaryPosition["Top"] = 0] = "Top";
    BoundaryPosition[BoundaryPosition["Bottom"] = 1] = "Bottom";
})(BoundaryPosition || (BoundaryPosition = {}));
var AccessibilityManager = (function () {
    function AccessibilityManager(_terminal) {
        var _this = this;
        this._terminal = _terminal;
        this._liveRegionLineCount = 0;
        this._disposables = [];
        this._charsToConsume = [];
        this._accessibilityTreeRoot = document.createElement('div');
        this._accessibilityTreeRoot.classList.add('xterm-accessibility');
        this._rowContainer = document.createElement('div');
        this._rowContainer.classList.add('xterm-accessibility-tree');
        this._rowElements = [];
        for (var i = 0; i < this._terminal.rows; i++) {
            this._rowElements[i] = this._createAccessibilityTreeNode();
            this._rowContainer.appendChild(this._rowElements[i]);
        }
        this._topBoundaryFocusListener = function (e) { return _this._onBoundaryFocus(e, BoundaryPosition.Top); };
        this._bottomBoundaryFocusListener = function (e) { return _this._onBoundaryFocus(e, BoundaryPosition.Bottom); };
        this._rowElements[0].addEventListener('focus', this._topBoundaryFocusListener);
        this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener);
        this._refreshRowsDimensions();
        this._accessibilityTreeRoot.appendChild(this._rowContainer);
        this._renderRowsDebouncer = new RenderDebouncer_1.RenderDebouncer(this._terminal, this._renderRows.bind(this));
        this._refreshRows();
        this._liveRegion = document.createElement('div');
        this._liveRegion.classList.add('live-region');
        this._liveRegion.setAttribute('aria-live', 'assertive');
        this._accessibilityTreeRoot.appendChild(this._liveRegion);
        this._terminal.element.insertAdjacentElement('afterbegin', this._accessibilityTreeRoot);
        this._disposables.push(this._renderRowsDebouncer);
        this._disposables.push(this._terminal.addDisposableListener('resize', function (data) { return _this._onResize(data.cols, data.rows); }));
        this._disposables.push(this._terminal.addDisposableListener('refresh', function (data) { return _this._refreshRows(data.start, data.end); }));
        this._disposables.push(this._terminal.addDisposableListener('scroll', function (data) { return _this._refreshRows(); }));
        this._disposables.push(this._terminal.addDisposableListener('a11y.char', function (char) { return _this._onChar(char); }));
        this._disposables.push(this._terminal.addDisposableListener('linefeed', function () { return _this._onChar('\n'); }));
        this._disposables.push(this._terminal.addDisposableListener('a11y.tab', function (spaceCount) { return _this._onTab(spaceCount); }));
        this._disposables.push(this._terminal.addDisposableListener('key', function (keyChar) { return _this._onKey(keyChar); }));
        this._disposables.push(this._terminal.addDisposableListener('blur', function () { return _this._clearLiveRegion(); }));
        this._disposables.push(this._terminal.addDisposableListener('dprchange', function () { return _this._refreshRowsDimensions(); }));
        this._disposables.push(this._terminal.renderer.addDisposableListener('resize', function () { return _this._refreshRowsDimensions(); }));
        this._disposables.push(Dom_1.addDisposableListener(window, 'resize', function () { return _this._refreshRowsDimensions(); }));
    }
    AccessibilityManager.prototype.dispose = function () {
        this._disposables.forEach(function (d) { return d.dispose(); });
        this._disposables.length = 0;
        this._terminal.element.removeChild(this._accessibilityTreeRoot);
        this._rowElements.length = 0;
    };
    AccessibilityManager.prototype._onBoundaryFocus = function (e, position) {
        var boundaryElement = e.target;
        var beforeBoundaryElement = this._rowElements[position === BoundaryPosition.Top ? 1 : this._rowElements.length - 2];
        var posInSet = boundaryElement.getAttribute('aria-posinset');
        var lastRowPos = position === BoundaryPosition.Top ? '1' : "" + this._terminal.buffer.lines.length;
        if (posInSet === lastRowPos) {
            return;
        }
        if (e.relatedTarget !== beforeBoundaryElement) {
            return;
        }
        var topBoundaryElement;
        var bottomBoundaryElement;
        if (position === BoundaryPosition.Top) {
            topBoundaryElement = boundaryElement;
            bottomBoundaryElement = this._rowElements.pop();
            this._rowContainer.removeChild(bottomBoundaryElement);
        }
        else {
            topBoundaryElement = this._rowElements.shift();
            bottomBoundaryElement = boundaryElement;
            this._rowContainer.removeChild(topBoundaryElement);
        }
        topBoundaryElement.removeEventListener('focus', this._topBoundaryFocusListener);
        bottomBoundaryElement.removeEventListener('focus', this._bottomBoundaryFocusListener);
        if (position === BoundaryPosition.Top) {
            var newElement = this._createAccessibilityTreeNode();
            this._rowElements.unshift(newElement);
            this._rowContainer.insertAdjacentElement('afterbegin', newElement);
        }
        else {
            var newElement = this._createAccessibilityTreeNode();
            this._rowElements.push(newElement);
            this._rowContainer.appendChild(newElement);
        }
        this._rowElements[0].addEventListener('focus', this._topBoundaryFocusListener);
        this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener);
        this._terminal.scrollLines(position === BoundaryPosition.Top ? -1 : 1);
        this._rowElements[position === BoundaryPosition.Top ? 1 : this._rowElements.length - 2].focus();
        e.preventDefault();
        e.stopImmediatePropagation();
    };
    AccessibilityManager.prototype._onResize = function (cols, rows) {
        this._rowElements[this._rowElements.length - 1].removeEventListener('focus', this._bottomBoundaryFocusListener);
        for (var i = this._rowContainer.children.length; i < this._terminal.rows; i++) {
            this._rowElements[i] = this._createAccessibilityTreeNode();
            this._rowContainer.appendChild(this._rowElements[i]);
        }
        while (this._rowElements.length > rows) {
            this._rowContainer.removeChild(this._rowElements.pop());
        }
        this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener);
        this._refreshRowsDimensions();
    };
    AccessibilityManager.prototype._createAccessibilityTreeNode = function () {
        var element = document.createElement('div');
        element.setAttribute('role', 'listitem');
        element.tabIndex = -1;
        this._refreshRowDimensions(element);
        return element;
    };
    AccessibilityManager.prototype._onTab = function (spaceCount) {
        for (var i = 0; i < spaceCount; i++) {
            this._onChar(' ');
        }
    };
    AccessibilityManager.prototype._onChar = function (char) {
        var _this = this;
        if (this._liveRegionLineCount < MAX_ROWS_TO_READ + 1) {
            if (this._charsToConsume.length > 0) {
                var shiftedChar = this._charsToConsume.shift();
                if (shiftedChar !== char) {
                    this._announceCharacter(char);
                }
            }
            else {
                this._announceCharacter(char);
            }
            if (char === '\n') {
                this._liveRegionLineCount++;
                if (this._liveRegionLineCount === MAX_ROWS_TO_READ + 1) {
                    this._liveRegion.textContent += Strings.tooMuchOutput;
                }
            }
            if (Browser_1.isMac) {
                if (this._liveRegion.textContent && this._liveRegion.textContent.length > 0 && !this._liveRegion.parentNode) {
                    setTimeout(function () {
                        _this._accessibilityTreeRoot.appendChild(_this._liveRegion);
                    }, 0);
                }
            }
        }
    };
    AccessibilityManager.prototype._clearLiveRegion = function () {
        this._liveRegion.textContent = '';
        this._liveRegionLineCount = 0;
        if (Browser_1.isMac) {
            if (this._liveRegion.parentNode) {
                this._accessibilityTreeRoot.removeChild(this._liveRegion);
            }
        }
    };
    AccessibilityManager.prototype._onKey = function (keyChar) {
        this._clearLiveRegion();
        this._charsToConsume.push(keyChar);
    };
    AccessibilityManager.prototype._refreshRows = function (start, end) {
        this._renderRowsDebouncer.refresh(start, end);
    };
    AccessibilityManager.prototype._renderRows = function (start, end) {
        var buffer = this._terminal.buffer;
        var setSize = buffer.lines.length.toString();
        for (var i = start; i <= end; i++) {
            var lineData = buffer.translateBufferLineToString(buffer.ydisp + i, true);
            var posInSet = (buffer.ydisp + i + 1).toString();
            var element = this._rowElements[i];
            element.textContent = lineData.length === 0 ? Strings.blankLine : lineData;
            element.setAttribute('aria-posinset', posInSet);
            element.setAttribute('aria-setsize', setSize);
        }
    };
    AccessibilityManager.prototype._refreshRowsDimensions = function () {
        if (!this._terminal.renderer.dimensions.actualCellHeight) {
            return;
        }
        for (var i = 0; i < this._terminal.rows; i++) {
            this._refreshRowDimensions(this._rowElements[i]);
        }
    };
    AccessibilityManager.prototype._refreshRowDimensions = function (element) {
        element.style.height = this._terminal.renderer.dimensions.actualCellHeight + "px";
    };
    AccessibilityManager.prototype._announceCharacter = function (char) {
        if (char === ' ') {
            this._liveRegion.innerHTML += '&nbsp;';
        }
        else {
            this._liveRegion.textContent += char;
        }
    };
    return AccessibilityManager;
}());
exports.AccessibilityManager = AccessibilityManager;

//# sourceMappingURL=AccessibilityManager.js.map


/***/ }),

/***/ "Ioao":
/*!******************************************!*\
  !*** ./node_modules/lodash/_overRest.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var apply = __webpack_require__(/*! ./_apply */ "heNW");

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;

/**
 * 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);
  };
}

module.exports = overRest;


/***/ }),

/***/ "Ipkf":
/*!*****************************************************************!*\
  !*** ./node_modules/xterm/lib/renderer/SelectionRenderLayer.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var BaseRenderLayer_1 = __webpack_require__(/*! ./BaseRenderLayer */ "HHOg");
var SelectionRenderLayer = (function (_super) {
    __extends(SelectionRenderLayer, _super);
    function SelectionRenderLayer(container, zIndex, colors) {
        var _this = _super.call(this, container, 'selection', zIndex, true, colors) || this;
        _this._state = {
            start: null,
            end: null
        };
        return _this;
    }
    SelectionRenderLayer.prototype.resize = function (terminal, dim) {
        _super.prototype.resize.call(this, terminal, dim);
        this._state = {
            start: null,
            end: null
        };
    };
    SelectionRenderLayer.prototype.reset = function (terminal) {
        if (this._state.start && this._state.end) {
            this._state = {
                start: null,
                end: null
            };
            this.clearAll();
        }
    };
    SelectionRenderLayer.prototype.onSelectionChanged = function (terminal, start, end) {
        if (this._state.start === start || this._state.end === end) {
            return;
        }
        this.clearAll();
        if (!start || !end) {
            return;
        }
        var viewportStartRow = start[1] - terminal.buffer.ydisp;
        var viewportEndRow = end[1] - terminal.buffer.ydisp;
        var viewportCappedStartRow = Math.max(viewportStartRow, 0);
        var viewportCappedEndRow = Math.min(viewportEndRow, terminal.rows - 1);
        if (viewportCappedStartRow >= terminal.rows || viewportCappedEndRow < 0) {
            return;
        }
        var startCol = viewportStartRow === viewportCappedStartRow ? start[0] : 0;
        var startRowEndCol = viewportCappedStartRow === viewportCappedEndRow ? end[0] : terminal.cols;
        this._ctx.fillStyle = this._colors.selection.css;
        this.fillCells(startCol, viewportCappedStartRow, startRowEndCol - startCol, 1);
        var middleRowsCount = Math.max(viewportCappedEndRow - viewportCappedStartRow - 1, 0);
        this.fillCells(0, viewportCappedStartRow + 1, terminal.cols, middleRowsCount);
        if (viewportCappedStartRow !== viewportCappedEndRow) {
            var endCol = viewportEndRow === viewportCappedEndRow ? end[0] : terminal.cols;
            this.fillCells(0, viewportCappedEndRow, endCol, 1);
        }
        this._state.start = [start[0], start[1]];
        this._state.end = [end[0], end[1]];
    };
    return SelectionRenderLayer;
}(BaseRenderLayer_1.BaseRenderLayer));
exports.SelectionRenderLayer = SelectionRenderLayer;

//# sourceMappingURL=SelectionRenderLayer.js.map


/***/ }),

/***/ "Iq8E":
/*!*****************************************************!*\
  !*** ./node_modules/draft-js/lib/DraftOffsetKey.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DraftOffsetKey
 * @format
 * 
 */



var KEY_DELIMITER = '-';

var DraftOffsetKey = {
  encode: function encode(blockKey, decoratorKey, leafKey) {
    return blockKey + KEY_DELIMITER + decoratorKey + KEY_DELIMITER + leafKey;
  },

  decode: function decode(offsetKey) {
    var _offsetKey$split = offsetKey.split(KEY_DELIMITER),
        blockKey = _offsetKey$split[0],
        decoratorKey = _offsetKey$split[1],
        leafKey = _offsetKey$split[2];

    return {
      blockKey: blockKey,
      decoratorKey: parseInt(decoratorKey, 10),
      leafKey: parseInt(leafKey, 10)
    };
  }
};

module.exports = DraftOffsetKey;

/***/ }),

/***/ "ItQE":
/*!****************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/connectTransformToTrace.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

exports.default = connectTransformToTrace;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _lib = __webpack_require__(/*! ../lib */ "RXjw");

var _constants = __webpack_require__(/*! ./constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function connectTransformToTrace(WrappedComponent) {
  var TransformConnectedComponent = function (_Component) {
    _inherits(TransformConnectedComponent, _Component);

    function TransformConnectedComponent(props, context) {
      _classCallCheck(this, TransformConnectedComponent);

      var _this = _possibleConstructorReturn(this, (TransformConnectedComponent.__proto__ || Object.getPrototypeOf(TransformConnectedComponent)).call(this, props, context));

      _this.deleteTransform = _this.deleteTransform.bind(_this);
      _this.updateTransform = _this.updateTransform.bind(_this);
      _this.setLocals(props, context);
      return _this;
    }

    _createClass(TransformConnectedComponent, [{
      key: 'componentWillReceiveProps',
      value: function componentWillReceiveProps(nextProps, nextContext) {
        this.setLocals(nextProps, nextContext);
      }
    }, {
      key: 'setLocals',
      value: function setLocals(props, context) {
        var transformIndex = props.transformIndex;
        var container = context.container,
            fullContainer = context.fullContainer;


        var transforms = container.transforms || [];
        var fullTransforms = fullContainer.transforms || [];
        this.container = transforms[transformIndex];
        this.fullContainer = fullTransforms[transformIndex];
      }
    }, {
      key: 'getChildContext',
      value: function getChildContext() {
        var _this2 = this;

        return {
          getValObject: function getValObject(attr) {
            return !_this2.context.getValObject ? null : _this2.context.getValObject('transforms[].' + attr);
          },
          updateContainer: this.updateTransform,
          deleteContainer: this.deleteTransform,
          container: this.container,
          fullContainer: this.fullContainer
        };
      }
    }, {
      key: 'updateTransform',
      value: function updateTransform(update) {
        var newUpdate = {};
        var transformIndex = this.props.transformIndex;

        for (var key in update) {
          var newkey = 'transforms[' + transformIndex + '].' + key;
          newUpdate[newkey] = update[key];
        }
        this.context.updateContainer(newUpdate);
      }
    }, {
      key: 'deleteTransform',
      value: function deleteTransform() {
        if (this.context.onUpdate) {
          this.context.onUpdate({
            type: _constants.EDITOR_ACTIONS.DELETE_TRANSFORM,
            payload: {
              traceIndex: this.context.fullContainer.index,
              transformIndex: this.props.transformIndex
            }
          });
        }
      }
    }, {
      key: 'render',
      value: function render() {
        return _react2.default.createElement(WrappedComponent, this.props);
      }
    }]);

    return TransformConnectedComponent;
  }(_react.Component);

  TransformConnectedComponent.displayName = 'TransformConnected' + (0, _lib.getDisplayName)(WrappedComponent);

  TransformConnectedComponent.propTypes = {
    transformIndex: _propTypes2.default.number.isRequired
  };

  TransformConnectedComponent.contextTypes = {
    container: _propTypes2.default.object,
    fullContainer: _propTypes2.default.object,
    data: _propTypes2.default.array,
    onUpdate: _propTypes2.default.func,
    updateContainer: _propTypes2.default.func,
    getValObject: _propTypes2.default.func
  };

  TransformConnectedComponent.childContextTypes = {
    updateContainer: _propTypes2.default.func,
    deleteContainer: _propTypes2.default.func,
    container: _propTypes2.default.object,
    fullContainer: _propTypes2.default.object,
    getValObject: _propTypes2.default.func
  };

  var plotly_editor_traits = WrappedComponent.plotly_editor_traits;

  TransformConnectedComponent.plotly_editor_traits = plotly_editor_traits;

  return TransformConnectedComponent;
}
//# sourceMappingURL=connectTransformToTrace.js.map

/***/ }),

/***/ "Ivi+":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/ko.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var ko = moment.defineLocale('ko', {
    months : '1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월'.split('_'),
    monthsShort : '1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월'.split('_'),
    weekdays : '일요일_월요일_화요일_수요일_목요일_금요일_토요일'.split('_'),
    weekdaysShort : '일_월_화_수_목_금_토'.split('_'),
    weekdaysMin : '일_월_화_수_목_금_토'.split('_'),
    longDateFormat : {
        LT : 'A h:mm',
        LTS : 'A h:mm:ss',
        L : 'YYYY.MM.DD.',
        LL : 'YYYY년 MMMM D일',
        LLL : 'YYYY년 MMMM D일 A h:mm',
        LLLL : 'YYYY년 MMMM D일 dddd A h:mm',
        l : 'YYYY.MM.DD.',
        ll : 'YYYY년 MMMM D일',
        lll : 'YYYY년 MMMM D일 A h:mm',
        llll : 'YYYY년 MMMM D일 dddd A h:mm'
    },
    calendar : {
        sameDay : '오늘 LT',
        nextDay : '내일 LT',
        nextWeek : 'dddd LT',
        lastDay : '어제 LT',
        lastWeek : '지난주 dddd LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : '%s 후',
        past : '%s 전',
        s : '몇 초',
        ss : '%d초',
        m : '1분',
        mm : '%d분',
        h : '한 시간',
        hh : '%d시간',
        d : '하루',
        dd : '%d일',
        M : '한 달',
        MM : '%d달',
        y : '일 년',
        yy : '%d년'
    },
    dayOfMonthOrdinalParse : /\d{1,2}(일|월|주)/,
    ordinal : function (number, period) {
        switch (period) {
            case 'd':
            case 'D':
            case 'DDD':
                return number + '일';
            case 'M':
                return number + '월';
            case 'w':
            case 'W':
                return number + '주';
            default:
                return number;
        }
    },
    meridiemParse : /오전|오후/,
    isPM : function (token) {
        return token === '오후';
    },
    meridiem : function (hour, minute, isUpper) {
        return hour < 12 ? '오전' : '오후';
    }
});

return ko;

})));


/***/ }),

/***/ "IzUq":
/*!***********************************************************!*\
  !*** ./node_modules/buffer/node_modules/isarray/index.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

var toString = {}.toString;

module.exports = Array.isArray || function (arr) {
  return toString.call(arr) == '[object Array]';
};


/***/ }),

/***/ "Izdy":
/*!**************************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/apputils-extension/style/redirect.css ***!
  \**************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, Jupyter Development Team.\n|\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.jp-RedirectForm input {\n  display: block;\n  margin-top: 10px;\n  width: 100%;\n}\n\n.jp-RedirectForm-warning {\n  color: var(--jp-warn-color0);\n}\n", ""]);

// exports


/***/ }),

/***/ "J78i":
/*!***************************************************************!*\
  !*** ./node_modules/readable-stream/lib/_stream_transform.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.

// a transform stream is a readable/writable stream where you do
// something with the data.  Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored.  (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation.  For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes.  When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up.  When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer.  When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks.  If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk.  However,
// a pathological inflate type of transform can cause excessive buffering
// here.  For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output.  Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output.  In this case, you could write a very small
// amount of input, and end up with a very large amount of output.  In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform.  A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.



module.exports = Transform;

var Duplex = __webpack_require__(/*! ./_stream_duplex */ "sZro");

/*<replacement>*/
var util = __webpack_require__(/*! core-util-is */ "Onz0");
util.inherits = __webpack_require__(/*! inherits */ "P7XM");
/*</replacement>*/

util.inherits(Transform, Duplex);

function afterTransform(er, data) {
  var ts = this._transformState;
  ts.transforming = false;

  var cb = ts.writecb;

  if (!cb) {
    return this.emit('error', new Error('write callback called multiple times'));
  }

  ts.writechunk = null;
  ts.writecb = null;

  if (data != null) // single equals check for both `null` and `undefined`
    this.push(data);

  cb(er);

  var rs = this._readableState;
  rs.reading = false;
  if (rs.needReadable || rs.length < rs.highWaterMark) {
    this._read(rs.highWaterMark);
  }
}

function Transform(options) {
  if (!(this instanceof Transform)) return new Transform(options);

  Duplex.call(this, options);

  this._transformState = {
    afterTransform: afterTransform.bind(this),
    needTransform: false,
    transforming: false,
    writecb: null,
    writechunk: null,
    writeencoding: null
  };

  // start out asking for a readable event once data is transformed.
  this._readableState.needReadable = true;

  // we have implemented the _read method, and done the other things
  // that Readable wants before the first _read call, so unset the
  // sync guard flag.
  this._readableState.sync = false;

  if (options) {
    if (typeof options.transform === 'function') this._transform = options.transform;

    if (typeof options.flush === 'function') this._flush = options.flush;
  }

  // When the writable side finishes, then flush out anything remaining.
  this.on('prefinish', prefinish);
}

function prefinish() {
  var _this = this;

  if (typeof this._flush === 'function') {
    this._flush(function (er, data) {
      done(_this, er, data);
    });
  } else {
    done(this, null, null);
  }
}

Transform.prototype.push = function (chunk, encoding) {
  this._transformState.needTransform = false;
  return Duplex.prototype.push.call(this, chunk, encoding);
};

// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side.  You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk.  If you pass
// an error, then that'll put the hurt on the whole operation.  If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function (chunk, encoding, cb) {
  throw new Error('_transform() is not implemented');
};

Transform.prototype._write = function (chunk, encoding, cb) {
  var ts = this._transformState;
  ts.writecb = cb;
  ts.writechunk = chunk;
  ts.writeencoding = encoding;
  if (!ts.transforming) {
    var rs = this._readableState;
    if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  }
};

// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function (n) {
  var ts = this._transformState;

  if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
    ts.transforming = true;
    this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  } else {
    // mark that we need a transform, so that any data that comes in
    // will get processed, now that we've asked for it.
    ts.needTransform = true;
  }
};

Transform.prototype._destroy = function (err, cb) {
  var _this2 = this;

  Duplex.prototype._destroy.call(this, err, function (err2) {
    cb(err2);
    _this2.emit('close');
  });
};

function done(stream, er, data) {
  if (er) return stream.emit('error', er);

  if (data != null) // single equals check for both `null` and `undefined`
    stream.push(data);

  // if there's nothing in the write buffer, then that means
  // that nothing more will ever be provided
  if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');

  if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');

  return stream.push(null);
}

/***/ }),

/***/ "JB68":
/*!************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_to-object.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// 7.1.13 ToObject(argument)
var defined = __webpack_require__(/*! ./_defined */ "Jes0");
module.exports = function (it) {
  return Object(defined(it));
};


/***/ }),

/***/ "JC6p":
/*!********************************************!*\
  !*** ./node_modules/lodash/_baseForOwn.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseFor = __webpack_require__(/*! ./_baseFor */ "cq/+"),
    keys = __webpack_require__(/*! ./keys */ "7GkX");

/**
 * 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);
}

module.exports = baseForOwn;


/***/ }),

/***/ "JHRd":
/*!********************************************!*\
  !*** ./node_modules/lodash/_Uint8Array.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var root = __webpack_require__(/*! ./_root */ "Kz5y");

/** Built-in value references. */
var Uint8Array = root.Uint8Array;

module.exports = Uint8Array;


/***/ }),

/***/ "JHgL":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_mapCacheGet.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getMapData = __webpack_require__(/*! ./_getMapData */ "QkVE");

/**
 * 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);
}

module.exports = mapCacheGet;


/***/ }),

/***/ "JI+E":
/*!*************************************************!*\
  !*** ./node_modules/draft-js/lib/editOnBlur.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule editOnBlur
 * @format
 * 
 */



var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");

var containsNode = __webpack_require__(/*! fbjs/lib/containsNode */ "TWoB");
var getActiveElement = __webpack_require__(/*! fbjs/lib/getActiveElement */ "jl2H");

function editOnBlur(editor, e) {
  // In a contentEditable element, when you select a range and then click
  // another active element, this does trigger a `blur` event but will not
  // remove the DOM selection from the contenteditable.
  // This is consistent across all browsers, but we prefer that the editor
  // behave like a textarea, where a `blur` event clears the DOM selection.
  // We therefore force the issue to be certain, checking whether the active
  // element is `body` to force it when blurring occurs within the window (as
  // opposed to clicking to another tab or window).
  if (getActiveElement() === document.body) {
    var _selection = global.getSelection();
    var editorNode = editor.editor;
    if (_selection.rangeCount === 1 && containsNode(editorNode, _selection.anchorNode) && containsNode(editorNode, _selection.focusNode)) {
      _selection.removeAllRanges();
    }
  }

  var editorState = editor._latestEditorState;
  var currentSelection = editorState.getSelection();
  if (!currentSelection.getHasFocus()) {
    return;
  }

  var selection = currentSelection.set('hasFocus', false);
  editor.props.onBlur && editor.props.onBlur(e);
  editor.update(EditorState.acceptSelection(editorState, selection));
}

module.exports = editOnBlur;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "JI00":
/*!******************************************************************!*\
  !*** ./node_modules/react-color/lib/components/chrome/Chrome.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Chrome = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _merge = __webpack_require__(/*! lodash/merge */ "QkVN");

var _merge2 = _interopRequireDefault(_merge);

var _common = __webpack_require__(/*! ../common */ "TM95");

var _ChromeFields = __webpack_require__(/*! ./ChromeFields */ "Rkpk");

var _ChromeFields2 = _interopRequireDefault(_ChromeFields);

var _ChromePointer = __webpack_require__(/*! ./ChromePointer */ "NSvM");

var _ChromePointer2 = _interopRequireDefault(_ChromePointer);

var _ChromePointerCircle = __webpack_require__(/*! ./ChromePointerCircle */ "tu5P");

var _ChromePointerCircle2 = _interopRequireDefault(_ChromePointerCircle);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var Chrome = exports.Chrome = function Chrome(_ref) {
  var onChange = _ref.onChange,
      disableAlpha = _ref.disableAlpha,
      rgb = _ref.rgb,
      hsl = _ref.hsl,
      hsv = _ref.hsv,
      hex = _ref.hex,
      renderers = _ref.renderers,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': {
      picker: {
        background: '#fff',
        borderRadius: '2px',
        boxShadow: '0 0 2px rgba(0,0,0,.3), 0 4px 8px rgba(0,0,0,.3)',
        boxSizing: 'initial',
        width: '225px',
        fontFamily: 'Menlo'
      },
      saturation: {
        width: '100%',
        paddingBottom: '55%',
        position: 'relative',
        borderRadius: '2px 2px 0 0',
        overflow: 'hidden'
      },
      Saturation: {
        radius: '2px 2px 0 0'
      },
      body: {
        padding: '16px 16px 12px'
      },
      controls: {
        display: 'flex'
      },
      color: {
        width: '32px'
      },
      swatch: {
        marginTop: '6px',
        width: '16px',
        height: '16px',
        borderRadius: '8px',
        position: 'relative',
        overflow: 'hidden'
      },
      active: {
        absolute: '0px 0px 0px 0px',
        borderRadius: '8px',
        boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.1)',
        background: 'rgba(' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ', ' + rgb.a + ')',
        zIndex: '2'
      },
      toggles: {
        flex: '1'
      },
      hue: {
        height: '10px',
        position: 'relative',
        marginBottom: '8px'
      },
      Hue: {
        radius: '2px'
      },
      alpha: {
        height: '10px',
        position: 'relative'
      },
      Alpha: {
        radius: '2px'
      }
    },
    'disableAlpha': {
      color: {
        width: '22px'
      },
      alpha: {
        display: 'none'
      },
      hue: {
        marginBottom: '0px'
      },
      swatch: {
        width: '10px',
        height: '10px',
        marginTop: '0px'
      }
    }
  }, passedStyles), { disableAlpha: disableAlpha });

  return _react2.default.createElement(
    'div',
    { style: styles.picker, className: 'chrome-picker ' + className },
    _react2.default.createElement(
      'div',
      { style: styles.saturation },
      _react2.default.createElement(_common.Saturation, {
        style: styles.Saturation,
        hsl: hsl,
        hsv: hsv,
        pointer: _ChromePointerCircle2.default,
        onChange: onChange
      })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.body },
      _react2.default.createElement(
        'div',
        { style: styles.controls, className: 'flexbox-fix' },
        _react2.default.createElement(
          'div',
          { style: styles.color },
          _react2.default.createElement(
            'div',
            { style: styles.swatch },
            _react2.default.createElement('div', { style: styles.active }),
            _react2.default.createElement(_common.Checkboard, { renderers: renderers })
          )
        ),
        _react2.default.createElement(
          'div',
          { style: styles.toggles },
          _react2.default.createElement(
            'div',
            { style: styles.hue },
            _react2.default.createElement(_common.Hue, {
              style: styles.Hue,
              hsl: hsl,
              pointer: _ChromePointer2.default,
              onChange: onChange
            })
          ),
          _react2.default.createElement(
            'div',
            { style: styles.alpha },
            _react2.default.createElement(_common.Alpha, {
              style: styles.Alpha,
              rgb: rgb,
              hsl: hsl,
              pointer: _ChromePointer2.default,
              renderers: renderers,
              onChange: onChange
            })
          )
        )
      ),
      _react2.default.createElement(_ChromeFields2.default, {
        rgb: rgb,
        hsl: hsl,
        hex: hex,
        onChange: onChange,
        disableAlpha: disableAlpha
      })
    )
  );
};

Chrome.propTypes = {
  disableAlpha: _propTypes2.default.bool,
  styles: _propTypes2.default.object
};

Chrome.defaultProps = {
  disableAlpha: false,
  styles: {}
};

exports.default = (0, _common.ColorWrap)(Chrome);

/***/ }),

/***/ "JIKs":
/*!****************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/kernel/future.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(setImmediate) {
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const disposable_1 = __webpack_require__(/*! @phosphor/disposable */ "uNUc");
const messages_1 = __webpack_require__(/*! ./messages */ "Wg3t");
/**
 * Implementation of a kernel future.
 *
 * If a reply is expected, the Future is considered done when both a `reply`
 * message and an `idle` iopub status message have been received.  Otherwise, it
 * is considered done when the `idle` status is received.
 *
 */
class KernelFutureHandler extends disposable_1.DisposableDelegate {
    /**
     * Construct a new KernelFutureHandler.
     */
    constructor(cb, msg, expectReply, disposeOnDone, kernel) {
        super(cb);
        this._status = 0;
        this._stdin = Private.noOp;
        this._iopub = Private.noOp;
        this._reply = Private.noOp;
        this._done = new coreutils_1.PromiseDelegate();
        this._hooks = new Private.HookList();
        this._disposeOnDone = true;
        this._msg = msg;
        if (!expectReply) {
            this._setFlag(Private.KernelFutureFlag.GotReply);
        }
        this._disposeOnDone = disposeOnDone;
        this._kernel = kernel;
    }
    /**
     * Get the original outgoing message.
     */
    get msg() {
        return this._msg;
    }
    /**
     * A promise that resolves when the future is done.
     */
    get done() {
        return this._done.promise;
    }
    /**
     * Get the reply handler.
     */
    get onReply() {
        return this._reply;
    }
    /**
     * Set the reply handler.
     */
    set onReply(cb) {
        this._reply = cb;
    }
    /**
     * Get the iopub handler.
     */
    get onIOPub() {
        return this._iopub;
    }
    /**
     * Set the iopub handler.
     */
    set onIOPub(cb) {
        this._iopub = cb;
    }
    /**
     * Get the stdin handler.
     */
    get onStdin() {
        return this._stdin;
    }
    /**
     * Set the stdin handler.
     */
    set onStdin(cb) {
        this._stdin = cb;
    }
    /**
     * Register hook for IOPub messages.
     *
     * @param hook - The callback invoked for an IOPub message.
     *
     * #### Notes
     * The IOPub hook system allows you to preempt the handlers for IOPub
     * messages handled by the future.
     *
     * The most recently registered hook is run first. A hook can return a
     * boolean or a promise to a boolean, in which case all kernel message
     * processing pauses until the promise is fulfilled. If a hook return value
     * resolves to false, any later hooks will not run and the function will
     * return a promise resolving to false. If a hook throws an error, the error
     * is logged to the console and the next hook is run. If a hook is
     * registered during the hook processing, it will not run until the next
     * message. If a hook is removed during the hook processing, it will be
     * deactivated immediately.
     */
    registerMessageHook(hook) {
        if (this.isDisposed) {
            throw new Error('Kernel future is disposed');
        }
        this._hooks.add(hook);
    }
    /**
     * Remove a hook for IOPub messages.
     *
     * @param hook - The hook to remove.
     *
     * #### Notes
     * If a hook is removed during the hook processing, it will be deactivated immediately.
     */
    removeMessageHook(hook) {
        if (this.isDisposed) {
            return;
        }
        this._hooks.remove(hook);
    }
    /**
     * Send an `input_reply` message.
     */
    sendInputReply(content) {
        this._kernel.sendInputReply(content);
    }
    /**
     * Dispose and unregister the future.
     */
    dispose() {
        this._stdin = Private.noOp;
        this._iopub = Private.noOp;
        this._reply = Private.noOp;
        this._hooks = null;
        if (!this._testFlag(Private.KernelFutureFlag.IsDone)) {
            // Reject the `done` promise, but catch its error here in case no one else
            // is waiting for the promise to resolve. This prevents the error from
            // being displayed in the console, but does not prevent it from being
            // caught by a client who is waiting for it.
            this._done.reject(new Error('Canceled'));
            this._done.promise.catch(() => {
                /* no-op */
            });
            // TODO: Uncomment the following logging code, and check for any tests that trigger it.
            // let status = [];
            // if (!this._testFlag(Private.KernelFutureFlag.GotIdle)) {
            //   status.push('idle');
            // }
            // if (!this._testFlag(Private.KernelFutureFlag.GotReply)) {
            //   status.push('reply');
            // }
            // console.warn(`*************** DISPOSED BEFORE DONE: K${this._kernel.id.slice(0, 6)} M${this._msg.header.msg_id.slice(0, 6)} missing ${status.join(' ')}`);
        }
        super.dispose();
    }
    /**
     * Handle an incoming kernel message.
     */
    handleMsg(msg) {
        return __awaiter(this, void 0, void 0, function* () {
            switch (msg.channel) {
                case 'shell':
                    yield this._handleReply(msg);
                    break;
                case 'stdin':
                    yield this._handleStdin(msg);
                    break;
                case 'iopub':
                    yield this._handleIOPub(msg);
                    break;
                default:
                    break;
            }
        });
    }
    _handleReply(msg) {
        return __awaiter(this, void 0, void 0, function* () {
            let reply = this._reply;
            if (reply) {
                yield reply(msg);
            }
            this._replyMsg = msg;
            this._setFlag(Private.KernelFutureFlag.GotReply);
            if (this._testFlag(Private.KernelFutureFlag.GotIdle)) {
                this._handleDone();
            }
        });
    }
    _handleStdin(msg) {
        return __awaiter(this, void 0, void 0, function* () {
            let stdin = this._stdin;
            if (stdin) {
                yield stdin(msg);
            }
        });
    }
    _handleIOPub(msg) {
        return __awaiter(this, void 0, void 0, function* () {
            let process = yield this._hooks.process(msg);
            let iopub = this._iopub;
            if (process && iopub) {
                yield iopub(msg);
            }
            if (messages_1.KernelMessage.isStatusMsg(msg) &&
                msg.content.execution_state === 'idle') {
                this._setFlag(Private.KernelFutureFlag.GotIdle);
                if (this._testFlag(Private.KernelFutureFlag.GotReply)) {
                    this._handleDone();
                }
            }
        });
    }
    _handleDone() {
        if (this._testFlag(Private.KernelFutureFlag.IsDone)) {
            return;
        }
        this._setFlag(Private.KernelFutureFlag.IsDone);
        this._done.resolve(this._replyMsg);
        if (this._disposeOnDone) {
            this.dispose();
        }
    }
    /**
     * Test whether the given future flag is set.
     */
    _testFlag(flag) {
        // tslint:disable-next-line
        return (this._status & flag) !== 0;
    }
    /**
     * Set the given future flag.
     */
    _setFlag(flag) {
        // tslint:disable-next-line
        this._status |= flag;
    }
}
exports.KernelFutureHandler = KernelFutureHandler;
var Private;
(function (Private) {
    /**
     * A no-op function.
     */
    Private.noOp = () => {
        /* no-op */
    };
    /**
     * Defer a computation.
     *
     * #### NOTES
     * We can't just use requestAnimationFrame since it is not available in node.
     * This implementation is from Phosphor:
     * https://github.com/phosphorjs/phosphor/blob/e88e4321289bb1198f3098e7bda40736501f2ed8/tests/test-messaging/src/index.spec.ts#L63
     */
    const defer = (() => {
        let ok = typeof requestAnimationFrame === 'function';
        return ok ? requestAnimationFrame : setImmediate;
    })();
    class HookList {
        constructor() {
            this._hooks = [];
        }
        /**
         * Register a hook.
         *
         * @param hook - The callback to register.
         */
        add(hook) {
            this.remove(hook);
            this._hooks.push(hook);
        }
        /**
         * Remove a hook, if it exists in the hook list.
         *
         * @param hook - The callback to remove.
         */
        remove(hook) {
            let index = this._hooks.indexOf(hook);
            if (index >= 0) {
                this._hooks[index] = null;
                this._scheduleCompact();
            }
        }
        /**
         * Process a message through the hooks.
         *
         * @returns a promise resolving to false if any hook resolved as false,
         * otherwise true
         *
         * #### Notes
         * The most recently registered hook is run first. A hook can return a
         * boolean or a promise to a boolean, in which case processing pauses until
         * the promise is fulfilled. If a hook return value resolves to false, any
         * later hooks will not run and the function will return a promise resolving
         * to false. If a hook throws an error, the error is logged to the console
         * and the next hook is run. If a hook is registered during the hook
         * processing, it will not run until the next message. If a hook is removed
         * during the hook processing, it will be deactivated immediately.
         */
        process(msg) {
            return __awaiter(this, void 0, void 0, function* () {
                // Wait until we can start a new process run.
                yield this._processing;
                // Start the next process run.
                let processing = new coreutils_1.PromiseDelegate();
                this._processing = processing.promise;
                let continueHandling;
                // Call the end hook (most recently-added) first. Starting at the end also
                // guarantees that hooks added during the processing will not be run in
                // this process run.
                for (let i = this._hooks.length - 1; i >= 0; i--) {
                    let hook = this._hooks[i];
                    // If the hook has been removed, continue to the next one.
                    if (hook === null) {
                        continue;
                    }
                    // Execute the hook and log any errors.
                    try {
                        continueHandling = yield hook(msg);
                    }
                    catch (err) {
                        continueHandling = true;
                        console.error(err);
                    }
                    // If the hook resolved to false, stop processing and return.
                    if (continueHandling === false) {
                        processing.resolve(undefined);
                        return false;
                    }
                }
                // All hooks returned true (or errored out), so return true.
                processing.resolve(undefined);
                return true;
            });
        }
        /**
         * Schedule a cleanup of the list, removing any hooks that have been nulled out.
         */
        _scheduleCompact() {
            if (!this._compactScheduled) {
                this._compactScheduled = true;
                // Schedule a compaction in between processing runs. We do the
                // scheduling in an animation frame to rate-limit our compactions. If we
                // need to compact more frequently, we can change this to directly
                // schedule the compaction.
                defer(() => {
                    this._processing = this._processing.then(() => {
                        this._compactScheduled = false;
                        this._compact();
                    });
                });
            }
        }
        /**
         * Compact the list, removing any nulls.
         */
        _compact() {
            let numNulls = 0;
            for (let i = 0, len = this._hooks.length; i < len; i++) {
                let hook = this._hooks[i];
                if (this._hooks[i] === null) {
                    numNulls++;
                }
                else {
                    this._hooks[i - numNulls] = hook;
                }
            }
            this._hooks.length -= numNulls;
        }
    }
    Private.HookList = HookList;
    /**
     * Bit flags for the kernel future state.
     */
    let KernelFutureFlag;
    (function (KernelFutureFlag) {
        KernelFutureFlag[KernelFutureFlag["GotReply"] = 1] = "GotReply";
        KernelFutureFlag[KernelFutureFlag["GotIdle"] = 2] = "GotIdle";
        KernelFutureFlag[KernelFutureFlag["IsDone"] = 4] = "IsDone";
        KernelFutureFlag[KernelFutureFlag["DisposeOnDone"] = 8] = "DisposeOnDone";
    })(KernelFutureFlag = Private.KernelFutureFlag || (Private.KernelFutureFlag = {}));
})(Private || (Private = {}));

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../timers-browserify/main.js */ "URgk").setImmediate))

/***/ }),

/***/ "JKFw":
/*!******************************************************!*\
  !*** ./node_modules/@phosphor/algorithm/lib/find.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var iter_1 = __webpack_require__(/*! ./iter */ "DMSk");
/**
 * Find the first value in an iterable which matches a predicate.
 *
 * @param object - The iterable or array-like object to search.
 *
 * @param fn - The predicate function to apply to the values.
 *
 * @returns The first matching value, or `undefined` if no matching
 *   value is found.
 *
 * #### Complexity
 * Linear.
 *
 * #### Example
 * ```typescript
 * import { find } from '@phosphor/algorithm';
 *
 * interface IAnimal { species: string, name: string };
 *
 * function isCat(value: IAnimal): boolean {
 *   return value.species === 'cat';
 * }
 *
 * let data: IAnimal[] = [
 *   { species: 'dog', name: 'spot' },
 *   { species: 'cat', name: 'fluffy' },
 *   { species: 'alligator', name: 'pocho' }
 * ];
 *
 * find(data, isCat).name;  // 'fluffy'
 * ```
 */
function find(object, fn) {
    var index = 0;
    var it = iter_1.iter(object);
    var value;
    while ((value = it.next()) !== undefined) {
        if (fn(value, index++)) {
            return value;
        }
    }
    return undefined;
}
exports.find = find;
/**
 * Find the minimum value in an iterable.
 *
 * @param object - The iterable or array-like object to search.
 *
 * @param fn - The 3-way comparison function to apply to the values.
 *   It should return `< 0` if the first value is less than the second.
 *   `0` if the values are equivalent, or `> 0` if the first value is
 *   greater than the second.
 *
 * @returns The minimum value in the iterable. If multiple values are
 *   equivalent to the minimum, the left-most value is returned. If
 *   the iterable is empty, this returns `undefined`.
 *
 * #### Complexity
 * Linear.
 *
 * #### Example
 * ```typescript
 * import { min } from '@phosphor/algorithm';
 *
 * function numberCmp(a: number, b: number): number {
 *   return a - b;
 * }
 *
 * min([7, 4, 0, 3, 9, 4], numberCmp);  // 0
 * ```
 */
function min(object, fn) {
    var it = iter_1.iter(object);
    var value = it.next();
    if (value === undefined) {
        return undefined;
    }
    var result = value;
    while ((value = it.next()) !== undefined) {
        if (fn(value, result) < 0) {
            result = value;
        }
    }
    return result;
}
exports.min = min;
/**
 * Find the maximum value in an iterable.
 *
 * @param object - The iterable or array-like object to search.
 *
 * @param fn - The 3-way comparison function to apply to the values.
 *   It should return `< 0` if the first value is less than the second.
 *   `0` if the values are equivalent, or `> 0` if the first value is
 *   greater than the second.
 *
 * @returns The maximum value in the iterable. If multiple values are
 *   equivalent to the maximum, the left-most value is returned. If
 *   the iterable is empty, this returns `undefined`.
 *
 * #### Complexity
 * Linear.
 *
 * #### Example
 * ```typescript
 * import { max } from '@phosphor/algorithm';
 *
 * function numberCmp(a: number, b: number): number {
 *   return a - b;
 * }
 *
 * max([7, 4, 0, 3, 9, 4], numberCmp);  // 9
 * ```
 */
function max(object, fn) {
    var it = iter_1.iter(object);
    var value = it.next();
    if (value === undefined) {
        return undefined;
    }
    var result = value;
    while ((value = it.next()) !== undefined) {
        if (fn(value, result) > 0) {
            result = value;
        }
    }
    return result;
}
exports.max = max;
/**
 * Find the minimum and maximum values in an iterable.
 *
 * @param object - The iterable or array-like object to search.
 *
 * @param fn - The 3-way comparison function to apply to the values.
 *   It should return `< 0` if the first value is less than the second.
 *   `0` if the values are equivalent, or `> 0` if the first value is
 *   greater than the second.
 *
 * @returns A 2-tuple of the `[min, max]` values in the iterable. If
 *   multiple values are equivalent, the left-most values are returned.
 *   If the iterable is empty, this returns `undefined`.
 *
 * #### Complexity
 * Linear.
 *
 * #### Example
 * ```typescript
 * import { minmax } from '@phosphor/algorithm';
 *
 * function numberCmp(a: number, b: number): number {
 *   return a - b;
 * }
 *
 * minmax([7, 4, 0, 3, 9, 4], numberCmp);  // [0, 9]
 * ```
 */
function minmax(object, fn) {
    var it = iter_1.iter(object);
    var value = it.next();
    if (value === undefined) {
        return undefined;
    }
    var vmin = value;
    var vmax = value;
    while ((value = it.next()) !== undefined) {
        if (fn(value, vmin) < 0) {
            vmin = value;
        }
        else if (fn(value, vmax) > 0) {
            vmax = value;
        }
    }
    return [vmin, vmax];
}
exports.minmax = minmax;


/***/ }),

/***/ "JL7T":
/*!*******************************************************!*\
  !*** ./node_modules/draft-js/lib/ContentBlockNode.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule ContentBlockNode
 * @format
 * 
 *
 * This file is a fork of ContentBlock adding support for nesting references by
 * providing links to children, parent, prevSibling, and nextSibling.
 *
 * This is unstable and not part of the public API and should not be used by
 * production systems. This file may be update/removed without notice.
 */



function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var CharacterMetadata = __webpack_require__(/*! ./CharacterMetadata */ "lFJn");
var Immutable = __webpack_require__(/*! immutable */ "JPcv");

var findRangesImmutable = __webpack_require__(/*! ./findRangesImmutable */ "Taje");

var List = Immutable.List,
    Map = Immutable.Map,
    OrderedSet = Immutable.OrderedSet,
    Record = Immutable.Record,
    Repeat = Immutable.Repeat;


var EMPTY_SET = OrderedSet();

var defaultRecord = {
  parent: null,
  characterList: List(),
  data: Map(),
  depth: 0,
  key: '',
  text: '',
  type: 'unstyled',
  children: List(),
  prevSibling: null,
  nextSibling: null
};

var haveEqualStyle = function haveEqualStyle(charA, charB) {
  return charA.getStyle() === charB.getStyle();
};

var haveEqualEntity = function haveEqualEntity(charA, charB) {
  return charA.getEntity() === charB.getEntity();
};

var decorateCharacterList = function decorateCharacterList(config) {
  if (!config) {
    return config;
  }

  var characterList = config.characterList,
      text = config.text;


  if (text && !characterList) {
    config.characterList = List(Repeat(CharacterMetadata.EMPTY, text.length));
  }

  return config;
};

var ContentBlockNode = function (_Record) {
  _inherits(ContentBlockNode, _Record);

  function ContentBlockNode() {
    var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultRecord;

    _classCallCheck(this, ContentBlockNode);

    return _possibleConstructorReturn(this, _Record.call(this, decorateCharacterList(props)));
  }

  ContentBlockNode.prototype.getKey = function getKey() {
    return this.get('key');
  };

  ContentBlockNode.prototype.getType = function getType() {
    return this.get('type');
  };

  ContentBlockNode.prototype.getText = function getText() {
    return this.get('text');
  };

  ContentBlockNode.prototype.getCharacterList = function getCharacterList() {
    return this.get('characterList');
  };

  ContentBlockNode.prototype.getLength = function getLength() {
    return this.getText().length;
  };

  ContentBlockNode.prototype.getDepth = function getDepth() {
    return this.get('depth');
  };

  ContentBlockNode.prototype.getData = function getData() {
    return this.get('data');
  };

  ContentBlockNode.prototype.getInlineStyleAt = function getInlineStyleAt(offset) {
    var character = this.getCharacterList().get(offset);
    return character ? character.getStyle() : EMPTY_SET;
  };

  ContentBlockNode.prototype.getEntityAt = function getEntityAt(offset) {
    var character = this.getCharacterList().get(offset);
    return character ? character.getEntity() : null;
  };

  ContentBlockNode.prototype.getChildKeys = function getChildKeys() {
    return this.get('children');
  };

  ContentBlockNode.prototype.getParentKey = function getParentKey() {
    return this.get('parent');
  };

  ContentBlockNode.prototype.getPrevSiblingKey = function getPrevSiblingKey() {
    return this.get('prevSibling');
  };

  ContentBlockNode.prototype.getNextSiblingKey = function getNextSiblingKey() {
    return this.get('nextSibling');
  };

  ContentBlockNode.prototype.findStyleRanges = function findStyleRanges(filterFn, callback) {
    findRangesImmutable(this.getCharacterList(), haveEqualStyle, filterFn, callback);
  };

  ContentBlockNode.prototype.findEntityRanges = function findEntityRanges(filterFn, callback) {
    findRangesImmutable(this.getCharacterList(), haveEqualEntity, filterFn, callback);
  };

  return ContentBlockNode;
}(Record(defaultRecord));

module.exports = ContentBlockNode;

/***/ }),

/***/ "JOGU":
/*!********************************************************!*\
  !*** ./node_modules/@jupyterlab/notebook/lib/index.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__webpack_require__(/*! ../style/index.css */ "jAxu");
__export(__webpack_require__(/*! ./actions */ "qhsb"));
__export(__webpack_require__(/*! ./celltools */ "8x15"));
__export(__webpack_require__(/*! ./default-toolbar */ "jdEz"));
__export(__webpack_require__(/*! ./model */ "wGmf"));
__export(__webpack_require__(/*! ./modelfactory */ "jrUH"));
__export(__webpack_require__(/*! ./panel */ "RNiT"));
__export(__webpack_require__(/*! ./tracker */ "fMtF"));
__export(__webpack_require__(/*! ./widget */ "qZRx"));
__export(__webpack_require__(/*! ./widgetfactory */ "Kdc5"));


/***/ }),

/***/ "JOSh":
/*!**********************************************!*\
  !*** ./node_modules/base16/lib/hopscotch.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'hopscotch',
  author: 'jan t. sott',
  base00: '#322931',
  base01: '#433b42',
  base02: '#5c545b',
  base03: '#797379',
  base04: '#989498',
  base05: '#b9b5b8',
  base06: '#d5d3d5',
  base07: '#ffffff',
  base08: '#dd464c',
  base09: '#fd8b19',
  base0A: '#fdcc59',
  base0B: '#8fc13e',
  base0C: '#149b93',
  base0D: '#1290bf',
  base0E: '#c85e7c',
  base0F: '#b33508'
};
module.exports = exports['default'];

/***/ }),

/***/ "JPcv":
/*!**************************************************!*\
  !*** ./node_modules/immutable/dist/immutable.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/**
 *  Copyright (c) 2014-2015, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 */

(function (global, factory) {
   true ? module.exports = factory() :
  undefined;
}(this, function () { 'use strict';var SLICE$0 = Array.prototype.slice;

  function createClass(ctor, superClass) {
    if (superClass) {
      ctor.prototype = Object.create(superClass.prototype);
    }
    ctor.prototype.constructor = ctor;
  }

  function Iterable(value) {
      return isIterable(value) ? value : Seq(value);
    }


  createClass(KeyedIterable, Iterable);
    function KeyedIterable(value) {
      return isKeyed(value) ? value : KeyedSeq(value);
    }


  createClass(IndexedIterable, Iterable);
    function IndexedIterable(value) {
      return isIndexed(value) ? value : IndexedSeq(value);
    }


  createClass(SetIterable, Iterable);
    function SetIterable(value) {
      return isIterable(value) && !isAssociative(value) ? value : SetSeq(value);
    }



  function isIterable(maybeIterable) {
    return !!(maybeIterable && maybeIterable[IS_ITERABLE_SENTINEL]);
  }

  function isKeyed(maybeKeyed) {
    return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL]);
  }

  function isIndexed(maybeIndexed) {
    return !!(maybeIndexed && maybeIndexed[IS_INDEXED_SENTINEL]);
  }

  function isAssociative(maybeAssociative) {
    return isKeyed(maybeAssociative) || isIndexed(maybeAssociative);
  }

  function isOrdered(maybeOrdered) {
    return !!(maybeOrdered && maybeOrdered[IS_ORDERED_SENTINEL]);
  }

  Iterable.isIterable = isIterable;
  Iterable.isKeyed = isKeyed;
  Iterable.isIndexed = isIndexed;
  Iterable.isAssociative = isAssociative;
  Iterable.isOrdered = isOrdered;

  Iterable.Keyed = KeyedIterable;
  Iterable.Indexed = IndexedIterable;
  Iterable.Set = SetIterable;


  var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@';
  var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@';
  var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@';
  var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@';

  // Used for setting prototype methods that IE8 chokes on.
  var DELETE = 'delete';

  // Constants describing the size of trie nodes.
  var SHIFT = 5; // Resulted in best performance after ______?
  var SIZE = 1 << SHIFT;
  var MASK = SIZE - 1;

  // A consistent shared value representing "not set" which equals nothing other
  // than itself, and nothing that could be provided externally.
  var NOT_SET = {};

  // Boolean references, Rough equivalent of `bool &`.
  var CHANGE_LENGTH = { value: false };
  var DID_ALTER = { value: false };

  function MakeRef(ref) {
    ref.value = false;
    return ref;
  }

  function SetRef(ref) {
    ref && (ref.value = true);
  }

  // A function which returns a value representing an "owner" for transient writes
  // to tries. The return value will only ever equal itself, and will not equal
  // the return of any subsequent call of this function.
  function OwnerID() {}

  // http://jsperf.com/copy-array-inline
  function arrCopy(arr, offset) {
    offset = offset || 0;
    var len = Math.max(0, arr.length - offset);
    var newArr = new Array(len);
    for (var ii = 0; ii < len; ii++) {
      newArr[ii] = arr[ii + offset];
    }
    return newArr;
  }

  function ensureSize(iter) {
    if (iter.size === undefined) {
      iter.size = iter.__iterate(returnTrue);
    }
    return iter.size;
  }

  function wrapIndex(iter, index) {
    // This implements "is array index" which the ECMAString spec defines as:
    //
    //     A String property name P is an array index if and only if
    //     ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal
    //     to 2^32−1.
    //
    // http://www.ecma-international.org/ecma-262/6.0/#sec-array-exotic-objects
    if (typeof index !== 'number') {
      var uint32Index = index >>> 0; // N >>> 0 is shorthand for ToUint32
      if ('' + uint32Index !== index || uint32Index === 4294967295) {
        return NaN;
      }
      index = uint32Index;
    }
    return index < 0 ? ensureSize(iter) + index : index;
  }

  function returnTrue() {
    return true;
  }

  function wholeSlice(begin, end, size) {
    return (begin === 0 || (size !== undefined && begin <= -size)) &&
      (end === undefined || (size !== undefined && end >= size));
  }

  function resolveBegin(begin, size) {
    return resolveIndex(begin, size, 0);
  }

  function resolveEnd(end, size) {
    return resolveIndex(end, size, size);
  }

  function resolveIndex(index, size, defaultIndex) {
    return index === undefined ?
      defaultIndex :
      index < 0 ?
        Math.max(0, size + index) :
        size === undefined ?
          index :
          Math.min(size, index);
  }

  /* global Symbol */

  var ITERATE_KEYS = 0;
  var ITERATE_VALUES = 1;
  var ITERATE_ENTRIES = 2;

  var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
  var FAUX_ITERATOR_SYMBOL = '@@iterator';

  var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL;


  function Iterator(next) {
      this.next = next;
    }

    Iterator.prototype.toString = function() {
      return '[Iterator]';
    };


  Iterator.KEYS = ITERATE_KEYS;
  Iterator.VALUES = ITERATE_VALUES;
  Iterator.ENTRIES = ITERATE_ENTRIES;

  Iterator.prototype.inspect =
  Iterator.prototype.toSource = function () { return this.toString(); }
  Iterator.prototype[ITERATOR_SYMBOL] = function () {
    return this;
  };


  function iteratorValue(type, k, v, iteratorResult) {
    var value = type === 0 ? k : type === 1 ? v : [k, v];
    iteratorResult ? (iteratorResult.value = value) : (iteratorResult = {
      value: value, done: false
    });
    return iteratorResult;
  }

  function iteratorDone() {
    return { value: undefined, done: true };
  }

  function hasIterator(maybeIterable) {
    return !!getIteratorFn(maybeIterable);
  }

  function isIterator(maybeIterator) {
    return maybeIterator && typeof maybeIterator.next === 'function';
  }

  function getIterator(iterable) {
    var iteratorFn = getIteratorFn(iterable);
    return iteratorFn && iteratorFn.call(iterable);
  }

  function getIteratorFn(iterable) {
    var iteratorFn = iterable && (
      (REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) ||
      iterable[FAUX_ITERATOR_SYMBOL]
    );
    if (typeof iteratorFn === 'function') {
      return iteratorFn;
    }
  }

  function isArrayLike(value) {
    return value && typeof value.length === 'number';
  }

  createClass(Seq, Iterable);
    function Seq(value) {
      return value === null || value === undefined ? emptySequence() :
        isIterable(value) ? value.toSeq() : seqFromValue(value);
    }

    Seq.of = function(/*...values*/) {
      return Seq(arguments);
    };

    Seq.prototype.toSeq = function() {
      return this;
    };

    Seq.prototype.toString = function() {
      return this.__toString('Seq {', '}');
    };

    Seq.prototype.cacheResult = function() {
      if (!this._cache && this.__iterateUncached) {
        this._cache = this.entrySeq().toArray();
        this.size = this._cache.length;
      }
      return this;
    };

    // abstract __iterateUncached(fn, reverse)

    Seq.prototype.__iterate = function(fn, reverse) {
      return seqIterate(this, fn, reverse, true);
    };

    // abstract __iteratorUncached(type, reverse)

    Seq.prototype.__iterator = function(type, reverse) {
      return seqIterator(this, type, reverse, true);
    };



  createClass(KeyedSeq, Seq);
    function KeyedSeq(value) {
      return value === null || value === undefined ?
        emptySequence().toKeyedSeq() :
        isIterable(value) ?
          (isKeyed(value) ? value.toSeq() : value.fromEntrySeq()) :
          keyedSeqFromValue(value);
    }

    KeyedSeq.prototype.toKeyedSeq = function() {
      return this;
    };



  createClass(IndexedSeq, Seq);
    function IndexedSeq(value) {
      return value === null || value === undefined ? emptySequence() :
        !isIterable(value) ? indexedSeqFromValue(value) :
        isKeyed(value) ? value.entrySeq() : value.toIndexedSeq();
    }

    IndexedSeq.of = function(/*...values*/) {
      return IndexedSeq(arguments);
    };

    IndexedSeq.prototype.toIndexedSeq = function() {
      return this;
    };

    IndexedSeq.prototype.toString = function() {
      return this.__toString('Seq [', ']');
    };

    IndexedSeq.prototype.__iterate = function(fn, reverse) {
      return seqIterate(this, fn, reverse, false);
    };

    IndexedSeq.prototype.__iterator = function(type, reverse) {
      return seqIterator(this, type, reverse, false);
    };



  createClass(SetSeq, Seq);
    function SetSeq(value) {
      return (
        value === null || value === undefined ? emptySequence() :
        !isIterable(value) ? indexedSeqFromValue(value) :
        isKeyed(value) ? value.entrySeq() : value
      ).toSetSeq();
    }

    SetSeq.of = function(/*...values*/) {
      return SetSeq(arguments);
    };

    SetSeq.prototype.toSetSeq = function() {
      return this;
    };



  Seq.isSeq = isSeq;
  Seq.Keyed = KeyedSeq;
  Seq.Set = SetSeq;
  Seq.Indexed = IndexedSeq;

  var IS_SEQ_SENTINEL = '@@__IMMUTABLE_SEQ__@@';

  Seq.prototype[IS_SEQ_SENTINEL] = true;



  createClass(ArraySeq, IndexedSeq);
    function ArraySeq(array) {
      this._array = array;
      this.size = array.length;
    }

    ArraySeq.prototype.get = function(index, notSetValue) {
      return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue;
    };

    ArraySeq.prototype.__iterate = function(fn, reverse) {
      var array = this._array;
      var maxIndex = array.length - 1;
      for (var ii = 0; ii <= maxIndex; ii++) {
        if (fn(array[reverse ? maxIndex - ii : ii], ii, this) === false) {
          return ii + 1;
        }
      }
      return ii;
    };

    ArraySeq.prototype.__iterator = function(type, reverse) {
      var array = this._array;
      var maxIndex = array.length - 1;
      var ii = 0;
      return new Iterator(function() 
        {return ii > maxIndex ?
          iteratorDone() :
          iteratorValue(type, ii, array[reverse ? maxIndex - ii++ : ii++])}
      );
    };



  createClass(ObjectSeq, KeyedSeq);
    function ObjectSeq(object) {
      var keys = Object.keys(object);
      this._object = object;
      this._keys = keys;
      this.size = keys.length;
    }

    ObjectSeq.prototype.get = function(key, notSetValue) {
      if (notSetValue !== undefined && !this.has(key)) {
        return notSetValue;
      }
      return this._object[key];
    };

    ObjectSeq.prototype.has = function(key) {
      return this._object.hasOwnProperty(key);
    };

    ObjectSeq.prototype.__iterate = function(fn, reverse) {
      var object = this._object;
      var keys = this._keys;
      var maxIndex = keys.length - 1;
      for (var ii = 0; ii <= maxIndex; ii++) {
        var key = keys[reverse ? maxIndex - ii : ii];
        if (fn(object[key], key, this) === false) {
          return ii + 1;
        }
      }
      return ii;
    };

    ObjectSeq.prototype.__iterator = function(type, reverse) {
      var object = this._object;
      var keys = this._keys;
      var maxIndex = keys.length - 1;
      var ii = 0;
      return new Iterator(function()  {
        var key = keys[reverse ? maxIndex - ii : ii];
        return ii++ > maxIndex ?
          iteratorDone() :
          iteratorValue(type, key, object[key]);
      });
    };

  ObjectSeq.prototype[IS_ORDERED_SENTINEL] = true;


  createClass(IterableSeq, IndexedSeq);
    function IterableSeq(iterable) {
      this._iterable = iterable;
      this.size = iterable.length || iterable.size;
    }

    IterableSeq.prototype.__iterateUncached = function(fn, reverse) {
      if (reverse) {
        return this.cacheResult().__iterate(fn, reverse);
      }
      var iterable = this._iterable;
      var iterator = getIterator(iterable);
      var iterations = 0;
      if (isIterator(iterator)) {
        var step;
        while (!(step = iterator.next()).done) {
          if (fn(step.value, iterations++, this) === false) {
            break;
          }
        }
      }
      return iterations;
    };

    IterableSeq.prototype.__iteratorUncached = function(type, reverse) {
      if (reverse) {
        return this.cacheResult().__iterator(type, reverse);
      }
      var iterable = this._iterable;
      var iterator = getIterator(iterable);
      if (!isIterator(iterator)) {
        return new Iterator(iteratorDone);
      }
      var iterations = 0;
      return new Iterator(function()  {
        var step = iterator.next();
        return step.done ? step : iteratorValue(type, iterations++, step.value);
      });
    };



  createClass(IteratorSeq, IndexedSeq);
    function IteratorSeq(iterator) {
      this._iterator = iterator;
      this._iteratorCache = [];
    }

    IteratorSeq.prototype.__iterateUncached = function(fn, reverse) {
      if (reverse) {
        return this.cacheResult().__iterate(fn, reverse);
      }
      var iterator = this._iterator;
      var cache = this._iteratorCache;
      var iterations = 0;
      while (iterations < cache.length) {
        if (fn(cache[iterations], iterations++, this) === false) {
          return iterations;
        }
      }
      var step;
      while (!(step = iterator.next()).done) {
        var val = step.value;
        cache[iterations] = val;
        if (fn(val, iterations++, this) === false) {
          break;
        }
      }
      return iterations;
    };

    IteratorSeq.prototype.__iteratorUncached = function(type, reverse) {
      if (reverse) {
        return this.cacheResult().__iterator(type, reverse);
      }
      var iterator = this._iterator;
      var cache = this._iteratorCache;
      var iterations = 0;
      return new Iterator(function()  {
        if (iterations >= cache.length) {
          var step = iterator.next();
          if (step.done) {
            return step;
          }
          cache[iterations] = step.value;
        }
        return iteratorValue(type, iterations, cache[iterations++]);
      });
    };




  // # pragma Helper functions

  function isSeq(maybeSeq) {
    return !!(maybeSeq && maybeSeq[IS_SEQ_SENTINEL]);
  }

  var EMPTY_SEQ;

  function emptySequence() {
    return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([]));
  }

  function keyedSeqFromValue(value) {
    var seq =
      Array.isArray(value) ? new ArraySeq(value).fromEntrySeq() :
      isIterator(value) ? new IteratorSeq(value).fromEntrySeq() :
      hasIterator(value) ? new IterableSeq(value).fromEntrySeq() :
      typeof value === 'object' ? new ObjectSeq(value) :
      undefined;
    if (!seq) {
      throw new TypeError(
        'Expected Array or iterable object of [k, v] entries, '+
        'or keyed object: ' + value
      );
    }
    return seq;
  }

  function indexedSeqFromValue(value) {
    var seq = maybeIndexedSeqFromValue(value);
    if (!seq) {
      throw new TypeError(
        'Expected Array or iterable object of values: ' + value
      );
    }
    return seq;
  }

  function seqFromValue(value) {
    var seq = maybeIndexedSeqFromValue(value) ||
      (typeof value === 'object' && new ObjectSeq(value));
    if (!seq) {
      throw new TypeError(
        'Expected Array or iterable object of values, or keyed object: ' + value
      );
    }
    return seq;
  }

  function maybeIndexedSeqFromValue(value) {
    return (
      isArrayLike(value) ? new ArraySeq(value) :
      isIterator(value) ? new IteratorSeq(value) :
      hasIterator(value) ? new IterableSeq(value) :
      undefined
    );
  }

  function seqIterate(seq, fn, reverse, useKeys) {
    var cache = seq._cache;
    if (cache) {
      var maxIndex = cache.length - 1;
      for (var ii = 0; ii <= maxIndex; ii++) {
        var entry = cache[reverse ? maxIndex - ii : ii];
        if (fn(entry[1], useKeys ? entry[0] : ii, seq) === false) {
          return ii + 1;
        }
      }
      return ii;
    }
    return seq.__iterateUncached(fn, reverse);
  }

  function seqIterator(seq, type, reverse, useKeys) {
    var cache = seq._cache;
    if (cache) {
      var maxIndex = cache.length - 1;
      var ii = 0;
      return new Iterator(function()  {
        var entry = cache[reverse ? maxIndex - ii : ii];
        return ii++ > maxIndex ?
          iteratorDone() :
          iteratorValue(type, useKeys ? entry[0] : ii - 1, entry[1]);
      });
    }
    return seq.__iteratorUncached(type, reverse);
  }

  function fromJS(json, converter) {
    return converter ?
      fromJSWith(converter, json, '', {'': json}) :
      fromJSDefault(json);
  }

  function fromJSWith(converter, json, key, parentJSON) {
    if (Array.isArray(json)) {
      return converter.call(parentJSON, key, IndexedSeq(json).map(function(v, k)  {return fromJSWith(converter, v, k, json)}));
    }
    if (isPlainObj(json)) {
      return converter.call(parentJSON, key, KeyedSeq(json).map(function(v, k)  {return fromJSWith(converter, v, k, json)}));
    }
    return json;
  }

  function fromJSDefault(json) {
    if (Array.isArray(json)) {
      return IndexedSeq(json).map(fromJSDefault).toList();
    }
    if (isPlainObj(json)) {
      return KeyedSeq(json).map(fromJSDefault).toMap();
    }
    return json;
  }

  function isPlainObj(value) {
    return value && (value.constructor === Object || value.constructor === undefined);
  }

  /**
   * An extension of the "same-value" algorithm as [described for use by ES6 Map
   * and Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality)
   *
   * NaN is considered the same as NaN, however -0 and 0 are considered the same
   * value, which is different from the algorithm described by
   * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is).
   *
   * This is extended further to allow Objects to describe the values they
   * represent, by way of `valueOf` or `equals` (and `hashCode`).
   *
   * Note: because of this extension, the key equality of Immutable.Map and the
   * value equality of Immutable.Set will differ from ES6 Map and Set.
   *
   * ### Defining custom values
   *
   * The easiest way to describe the value an object represents is by implementing
   * `valueOf`. For example, `Date` represents a value by returning a unix
   * timestamp for `valueOf`:
   *
   *     var date1 = new Date(1234567890000); // Fri Feb 13 2009 ...
   *     var date2 = new Date(1234567890000);
   *     date1.valueOf(); // 1234567890000
   *     assert( date1 !== date2 );
   *     assert( Immutable.is( date1, date2 ) );
   *
   * Note: overriding `valueOf` may have other implications if you use this object
   * where JavaScript expects a primitive, such as implicit string coercion.
   *
   * For more complex types, especially collections, implementing `valueOf` may
   * not be performant. An alternative is to implement `equals` and `hashCode`.
   *
   * `equals` takes another object, presumably of similar type, and returns true
   * if the it is equal. Equality is symmetrical, so the same result should be
   * returned if this and the argument are flipped.
   *
   *     assert( a.equals(b) === b.equals(a) );
   *
   * `hashCode` returns a 32bit integer number representing the object which will
   * be used to determine how to store the value object in a Map or Set. You must
   * provide both or neither methods, one must not exist without the other.
   *
   * Also, an important relationship between these methods must be upheld: if two
   * values are equal, they *must* return the same hashCode. If the values are not
   * equal, they might have the same hashCode; this is called a hash collision,
   * and while undesirable for performance reasons, it is acceptable.
   *
   *     if (a.equals(b)) {
   *       assert( a.hashCode() === b.hashCode() );
   *     }
   *
   * All Immutable collections implement `equals` and `hashCode`.
   *
   */
  function is(valueA, valueB) {
    if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
      return true;
    }
    if (!valueA || !valueB) {
      return false;
    }
    if (typeof valueA.valueOf === 'function' &&
        typeof valueB.valueOf === 'function') {
      valueA = valueA.valueOf();
      valueB = valueB.valueOf();
      if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
        return true;
      }
      if (!valueA || !valueB) {
        return false;
      }
    }
    if (typeof valueA.equals === 'function' &&
        typeof valueB.equals === 'function' &&
        valueA.equals(valueB)) {
      return true;
    }
    return false;
  }

  function deepEqual(a, b) {
    if (a === b) {
      return true;
    }

    if (
      !isIterable(b) ||
      a.size !== undefined && b.size !== undefined && a.size !== b.size ||
      a.__hash !== undefined && b.__hash !== undefined && a.__hash !== b.__hash ||
      isKeyed(a) !== isKeyed(b) ||
      isIndexed(a) !== isIndexed(b) ||
      isOrdered(a) !== isOrdered(b)
    ) {
      return false;
    }

    if (a.size === 0 && b.size === 0) {
      return true;
    }

    var notAssociative = !isAssociative(a);

    if (isOrdered(a)) {
      var entries = a.entries();
      return b.every(function(v, k)  {
        var entry = entries.next().value;
        return entry && is(entry[1], v) && (notAssociative || is(entry[0], k));
      }) && entries.next().done;
    }

    var flipped = false;

    if (a.size === undefined) {
      if (b.size === undefined) {
        if (typeof a.cacheResult === 'function') {
          a.cacheResult();
        }
      } else {
        flipped = true;
        var _ = a;
        a = b;
        b = _;
      }
    }

    var allEqual = true;
    var bSize = b.__iterate(function(v, k)  {
      if (notAssociative ? !a.has(v) :
          flipped ? !is(v, a.get(k, NOT_SET)) : !is(a.get(k, NOT_SET), v)) {
        allEqual = false;
        return false;
      }
    });

    return allEqual && a.size === bSize;
  }

  createClass(Repeat, IndexedSeq);

    function Repeat(value, times) {
      if (!(this instanceof Repeat)) {
        return new Repeat(value, times);
      }
      this._value = value;
      this.size = times === undefined ? Infinity : Math.max(0, times);
      if (this.size === 0) {
        if (EMPTY_REPEAT) {
          return EMPTY_REPEAT;
        }
        EMPTY_REPEAT = this;
      }
    }

    Repeat.prototype.toString = function() {
      if (this.size === 0) {
        return 'Repeat []';
      }
      return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]';
    };

    Repeat.prototype.get = function(index, notSetValue) {
      return this.has(index) ? this._value : notSetValue;
    };

    Repeat.prototype.includes = function(searchValue) {
      return is(this._value, searchValue);
    };

    Repeat.prototype.slice = function(begin, end) {
      var size = this.size;
      return wholeSlice(begin, end, size) ? this :
        new Repeat(this._value, resolveEnd(end, size) - resolveBegin(begin, size));
    };

    Repeat.prototype.reverse = function() {
      return this;
    };

    Repeat.prototype.indexOf = function(searchValue) {
      if (is(this._value, searchValue)) {
        return 0;
      }
      return -1;
    };

    Repeat.prototype.lastIndexOf = function(searchValue) {
      if (is(this._value, searchValue)) {
        return this.size;
      }
      return -1;
    };

    Repeat.prototype.__iterate = function(fn, reverse) {
      for (var ii = 0; ii < this.size; ii++) {
        if (fn(this._value, ii, this) === false) {
          return ii + 1;
        }
      }
      return ii;
    };

    Repeat.prototype.__iterator = function(type, reverse) {var this$0 = this;
      var ii = 0;
      return new Iterator(function() 
        {return ii < this$0.size ? iteratorValue(type, ii++, this$0._value) : iteratorDone()}
      );
    };

    Repeat.prototype.equals = function(other) {
      return other instanceof Repeat ?
        is(this._value, other._value) :
        deepEqual(other);
    };


  var EMPTY_REPEAT;

  function invariant(condition, error) {
    if (!condition) throw new Error(error);
  }

  createClass(Range, IndexedSeq);

    function Range(start, end, step) {
      if (!(this instanceof Range)) {
        return new Range(start, end, step);
      }
      invariant(step !== 0, 'Cannot step a Range by 0');
      start = start || 0;
      if (end === undefined) {
        end = Infinity;
      }
      step = step === undefined ? 1 : Math.abs(step);
      if (end < start) {
        step = -step;
      }
      this._start = start;
      this._end = end;
      this._step = step;
      this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1);
      if (this.size === 0) {
        if (EMPTY_RANGE) {
          return EMPTY_RANGE;
        }
        EMPTY_RANGE = this;
      }
    }

    Range.prototype.toString = function() {
      if (this.size === 0) {
        return 'Range []';
      }
      return 'Range [ ' +
        this._start + '...' + this._end +
        (this._step > 1 ? ' by ' + this._step : '') +
      ' ]';
    };

    Range.prototype.get = function(index, notSetValue) {
      return this.has(index) ?
        this._start + wrapIndex(this, index) * this._step :
        notSetValue;
    };

    Range.prototype.includes = function(searchValue) {
      var possibleIndex = (searchValue - this._start) / this._step;
      return possibleIndex >= 0 &&
        possibleIndex < this.size &&
        possibleIndex === Math.floor(possibleIndex);
    };

    Range.prototype.slice = function(begin, end) {
      if (wholeSlice(begin, end, this.size)) {
        return this;
      }
      begin = resolveBegin(begin, this.size);
      end = resolveEnd(end, this.size);
      if (end <= begin) {
        return new Range(0, 0);
      }
      return new Range(this.get(begin, this._end), this.get(end, this._end), this._step);
    };

    Range.prototype.indexOf = function(searchValue) {
      var offsetValue = searchValue - this._start;
      if (offsetValue % this._step === 0) {
        var index = offsetValue / this._step;
        if (index >= 0 && index < this.size) {
          return index
        }
      }
      return -1;
    };

    Range.prototype.lastIndexOf = function(searchValue) {
      return this.indexOf(searchValue);
    };

    Range.prototype.__iterate = function(fn, reverse) {
      var maxIndex = this.size - 1;
      var step = this._step;
      var value = reverse ? this._start + maxIndex * step : this._start;
      for (var ii = 0; ii <= maxIndex; ii++) {
        if (fn(value, ii, this) === false) {
          return ii + 1;
        }
        value += reverse ? -step : step;
      }
      return ii;
    };

    Range.prototype.__iterator = function(type, reverse) {
      var maxIndex = this.size - 1;
      var step = this._step;
      var value = reverse ? this._start + maxIndex * step : this._start;
      var ii = 0;
      return new Iterator(function()  {
        var v = value;
        value += reverse ? -step : step;
        return ii > maxIndex ? iteratorDone() : iteratorValue(type, ii++, v);
      });
    };

    Range.prototype.equals = function(other) {
      return other instanceof Range ?
        this._start === other._start &&
        this._end === other._end &&
        this._step === other._step :
        deepEqual(this, other);
    };


  var EMPTY_RANGE;

  createClass(Collection, Iterable);
    function Collection() {
      throw TypeError('Abstract');
    }


  createClass(KeyedCollection, Collection);function KeyedCollection() {}

  createClass(IndexedCollection, Collection);function IndexedCollection() {}

  createClass(SetCollection, Collection);function SetCollection() {}


  Collection.Keyed = KeyedCollection;
  Collection.Indexed = IndexedCollection;
  Collection.Set = SetCollection;

  var imul =
    typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2 ?
    Math.imul :
    function imul(a, b) {
      a = a | 0; // int
      b = b | 0; // int
      var c = a & 0xffff;
      var d = b & 0xffff;
      // Shift by 0 fixes the sign on the high part.
      return (c * d) + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0) | 0; // int
    };

  // v8 has an optimization for storing 31-bit signed numbers.
  // Values which have either 00 or 11 as the high order bits qualify.
  // This function drops the highest order bit in a signed number, maintaining
  // the sign bit.
  function smi(i32) {
    return ((i32 >>> 1) & 0x40000000) | (i32 & 0xBFFFFFFF);
  }

  function hash(o) {
    if (o === false || o === null || o === undefined) {
      return 0;
    }
    if (typeof o.valueOf === 'function') {
      o = o.valueOf();
      if (o === false || o === null || o === undefined) {
        return 0;
      }
    }
    if (o === true) {
      return 1;
    }
    var type = typeof o;
    if (type === 'number') {
      var h = o | 0;
      if (h !== o) {
        h ^= o * 0xFFFFFFFF;
      }
      while (o > 0xFFFFFFFF) {
        o /= 0xFFFFFFFF;
        h ^= o;
      }
      return smi(h);
    }
    if (type === 'string') {
      return o.length > STRING_HASH_CACHE_MIN_STRLEN ? cachedHashString(o) : hashString(o);
    }
    if (typeof o.hashCode === 'function') {
      return o.hashCode();
    }
    if (type === 'object') {
      return hashJSObj(o);
    }
    if (typeof o.toString === 'function') {
      return hashString(o.toString());
    }
    throw new Error('Value type ' + type + ' cannot be hashed.');
  }

  function cachedHashString(string) {
    var hash = stringHashCache[string];
    if (hash === undefined) {
      hash = hashString(string);
      if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) {
        STRING_HASH_CACHE_SIZE = 0;
        stringHashCache = {};
      }
      STRING_HASH_CACHE_SIZE++;
      stringHashCache[string] = hash;
    }
    return hash;
  }

  // http://jsperf.com/hashing-strings
  function hashString(string) {
    // This is the hash from JVM
    // The hash code for a string is computed as
    // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],
    // where s[i] is the ith character of the string and n is the length of
    // the string. We "mod" the result to make it between 0 (inclusive) and 2^31
    // (exclusive) by dropping high bits.
    var hash = 0;
    for (var ii = 0; ii < string.length; ii++) {
      hash = 31 * hash + string.charCodeAt(ii) | 0;
    }
    return smi(hash);
  }

  function hashJSObj(obj) {
    var hash;
    if (usingWeakMap) {
      hash = weakMap.get(obj);
      if (hash !== undefined) {
        return hash;
      }
    }

    hash = obj[UID_HASH_KEY];
    if (hash !== undefined) {
      return hash;
    }

    if (!canDefineProperty) {
      hash = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY];
      if (hash !== undefined) {
        return hash;
      }

      hash = getIENodeHash(obj);
      if (hash !== undefined) {
        return hash;
      }
    }

    hash = ++objHashUID;
    if (objHashUID & 0x40000000) {
      objHashUID = 0;
    }

    if (usingWeakMap) {
      weakMap.set(obj, hash);
    } else if (isExtensible !== undefined && isExtensible(obj) === false) {
      throw new Error('Non-extensible objects are not allowed as keys.');
    } else if (canDefineProperty) {
      Object.defineProperty(obj, UID_HASH_KEY, {
        'enumerable': false,
        'configurable': false,
        'writable': false,
        'value': hash
      });
    } else if (obj.propertyIsEnumerable !== undefined &&
               obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable) {
      // Since we can't define a non-enumerable property on the object
      // we'll hijack one of the less-used non-enumerable properties to
      // save our hash on it. Since this is a function it will not show up in
      // `JSON.stringify` which is what we want.
      obj.propertyIsEnumerable = function() {
        return this.constructor.prototype.propertyIsEnumerable.apply(this, arguments);
      };
      obj.propertyIsEnumerable[UID_HASH_KEY] = hash;
    } else if (obj.nodeType !== undefined) {
      // At this point we couldn't get the IE `uniqueID` to use as a hash
      // and we couldn't use a non-enumerable property to exploit the
      // dontEnum bug so we simply add the `UID_HASH_KEY` on the node
      // itself.
      obj[UID_HASH_KEY] = hash;
    } else {
      throw new Error('Unable to set a non-enumerable property on object.');
    }

    return hash;
  }

  // Get references to ES5 object methods.
  var isExtensible = Object.isExtensible;

  // True if Object.defineProperty works as expected. IE8 fails this test.
  var canDefineProperty = (function() {
    try {
      Object.defineProperty({}, '@', {});
      return true;
    } catch (e) {
      return false;
    }
  }());

  // IE has a `uniqueID` property on DOM nodes. We can construct the hash from it
  // and avoid memory leaks from the IE cloneNode bug.
  function getIENodeHash(node) {
    if (node && node.nodeType > 0) {
      switch (node.nodeType) {
        case 1: // Element
          return node.uniqueID;
        case 9: // Document
          return node.documentElement && node.documentElement.uniqueID;
      }
    }
  }

  // If possible, use a WeakMap.
  var usingWeakMap = typeof WeakMap === 'function';
  var weakMap;
  if (usingWeakMap) {
    weakMap = new WeakMap();
  }

  var objHashUID = 0;

  var UID_HASH_KEY = '__immutablehash__';
  if (typeof Symbol === 'function') {
    UID_HASH_KEY = Symbol(UID_HASH_KEY);
  }

  var STRING_HASH_CACHE_MIN_STRLEN = 16;
  var STRING_HASH_CACHE_MAX_SIZE = 255;
  var STRING_HASH_CACHE_SIZE = 0;
  var stringHashCache = {};

  function assertNotInfinite(size) {
    invariant(
      size !== Infinity,
      'Cannot perform this action with an infinite size.'
    );
  }

  createClass(Map, KeyedCollection);

    // @pragma Construction

    function Map(value) {
      return value === null || value === undefined ? emptyMap() :
        isMap(value) && !isOrdered(value) ? value :
        emptyMap().withMutations(function(map ) {
          var iter = KeyedIterable(value);
          assertNotInfinite(iter.size);
          iter.forEach(function(v, k)  {return map.set(k, v)});
        });
    }

    Map.prototype.toString = function() {
      return this.__toString('Map {', '}');
    };

    // @pragma Access

    Map.prototype.get = function(k, notSetValue) {
      return this._root ?
        this._root.get(0, undefined, k, notSetValue) :
        notSetValue;
    };

    // @pragma Modification

    Map.prototype.set = function(k, v) {
      return updateMap(this, k, v);
    };

    Map.prototype.setIn = function(keyPath, v) {
      return this.updateIn(keyPath, NOT_SET, function()  {return v});
    };

    Map.prototype.remove = function(k) {
      return updateMap(this, k, NOT_SET);
    };

    Map.prototype.deleteIn = function(keyPath) {
      return this.updateIn(keyPath, function()  {return NOT_SET});
    };

    Map.prototype.update = function(k, notSetValue, updater) {
      return arguments.length === 1 ?
        k(this) :
        this.updateIn([k], notSetValue, updater);
    };

    Map.prototype.updateIn = function(keyPath, notSetValue, updater) {
      if (!updater) {
        updater = notSetValue;
        notSetValue = undefined;
      }
      var updatedValue = updateInDeepMap(
        this,
        forceIterator(keyPath),
        notSetValue,
        updater
      );
      return updatedValue === NOT_SET ? undefined : updatedValue;
    };

    Map.prototype.clear = function() {
      if (this.size === 0) {
        return this;
      }
      if (this.__ownerID) {
        this.size = 0;
        this._root = null;
        this.__hash = undefined;
        this.__altered = true;
        return this;
      }
      return emptyMap();
    };

    // @pragma Composition

    Map.prototype.merge = function(/*...iters*/) {
      return mergeIntoMapWith(this, undefined, arguments);
    };

    Map.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
      return mergeIntoMapWith(this, merger, iters);
    };

    Map.prototype.mergeIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1);
      return this.updateIn(
        keyPath,
        emptyMap(),
        function(m ) {return typeof m.merge === 'function' ?
          m.merge.apply(m, iters) :
          iters[iters.length - 1]}
      );
    };

    Map.prototype.mergeDeep = function(/*...iters*/) {
      return mergeIntoMapWith(this, deepMerger, arguments);
    };

    Map.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
      return mergeIntoMapWith(this, deepMergerWith(merger), iters);
    };

    Map.prototype.mergeDeepIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1);
      return this.updateIn(
        keyPath,
        emptyMap(),
        function(m ) {return typeof m.mergeDeep === 'function' ?
          m.mergeDeep.apply(m, iters) :
          iters[iters.length - 1]}
      );
    };

    Map.prototype.sort = function(comparator) {
      // Late binding
      return OrderedMap(sortFactory(this, comparator));
    };

    Map.prototype.sortBy = function(mapper, comparator) {
      // Late binding
      return OrderedMap(sortFactory(this, comparator, mapper));
    };

    // @pragma Mutability

    Map.prototype.withMutations = function(fn) {
      var mutable = this.asMutable();
      fn(mutable);
      return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this;
    };

    Map.prototype.asMutable = function() {
      return this.__ownerID ? this : this.__ensureOwner(new OwnerID());
    };

    Map.prototype.asImmutable = function() {
      return this.__ensureOwner();
    };

    Map.prototype.wasAltered = function() {
      return this.__altered;
    };

    Map.prototype.__iterator = function(type, reverse) {
      return new MapIterator(this, type, reverse);
    };

    Map.prototype.__iterate = function(fn, reverse) {var this$0 = this;
      var iterations = 0;
      this._root && this._root.iterate(function(entry ) {
        iterations++;
        return fn(entry[1], entry[0], this$0);
      }, reverse);
      return iterations;
    };

    Map.prototype.__ensureOwner = function(ownerID) {
      if (ownerID === this.__ownerID) {
        return this;
      }
      if (!ownerID) {
        this.__ownerID = ownerID;
        this.__altered = false;
        return this;
      }
      return makeMap(this.size, this._root, ownerID, this.__hash);
    };


  function isMap(maybeMap) {
    return !!(maybeMap && maybeMap[IS_MAP_SENTINEL]);
  }

  Map.isMap = isMap;

  var IS_MAP_SENTINEL = '@@__IMMUTABLE_MAP__@@';

  var MapPrototype = Map.prototype;
  MapPrototype[IS_MAP_SENTINEL] = true;
  MapPrototype[DELETE] = MapPrototype.remove;
  MapPrototype.removeIn = MapPrototype.deleteIn;


  // #pragma Trie Nodes



    function ArrayMapNode(ownerID, entries) {
      this.ownerID = ownerID;
      this.entries = entries;
    }

    ArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) {
      var entries = this.entries;
      for (var ii = 0, len = entries.length; ii < len; ii++) {
        if (is(key, entries[ii][0])) {
          return entries[ii][1];
        }
      }
      return notSetValue;
    };

    ArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
      var removed = value === NOT_SET;

      var entries = this.entries;
      var idx = 0;
      for (var len = entries.length; idx < len; idx++) {
        if (is(key, entries[idx][0])) {
          break;
        }
      }
      var exists = idx < len;

      if (exists ? entries[idx][1] === value : removed) {
        return this;
      }

      SetRef(didAlter);
      (removed || !exists) && SetRef(didChangeSize);

      if (removed && entries.length === 1) {
        return; // undefined
      }

      if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) {
        return createNodes(ownerID, entries, key, value);
      }

      var isEditable = ownerID && ownerID === this.ownerID;
      var newEntries = isEditable ? entries : arrCopy(entries);

      if (exists) {
        if (removed) {
          idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop());
        } else {
          newEntries[idx] = [key, value];
        }
      } else {
        newEntries.push([key, value]);
      }

      if (isEditable) {
        this.entries = newEntries;
        return this;
      }

      return new ArrayMapNode(ownerID, newEntries);
    };




    function BitmapIndexedNode(ownerID, bitmap, nodes) {
      this.ownerID = ownerID;
      this.bitmap = bitmap;
      this.nodes = nodes;
    }

    BitmapIndexedNode.prototype.get = function(shift, keyHash, key, notSetValue) {
      if (keyHash === undefined) {
        keyHash = hash(key);
      }
      var bit = (1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK));
      var bitmap = this.bitmap;
      return (bitmap & bit) === 0 ? notSetValue :
        this.nodes[popCount(bitmap & (bit - 1))].get(shift + SHIFT, keyHash, key, notSetValue);
    };

    BitmapIndexedNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
      if (keyHash === undefined) {
        keyHash = hash(key);
      }
      var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
      var bit = 1 << keyHashFrag;
      var bitmap = this.bitmap;
      var exists = (bitmap & bit) !== 0;

      if (!exists && value === NOT_SET) {
        return this;
      }

      var idx = popCount(bitmap & (bit - 1));
      var nodes = this.nodes;
      var node = exists ? nodes[idx] : undefined;
      var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter);

      if (newNode === node) {
        return this;
      }

      if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) {
        return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode);
      }

      if (exists && !newNode && nodes.length === 2 && isLeafNode(nodes[idx ^ 1])) {
        return nodes[idx ^ 1];
      }

      if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) {
        return newNode;
      }

      var isEditable = ownerID && ownerID === this.ownerID;
      var newBitmap = exists ? newNode ? bitmap : bitmap ^ bit : bitmap | bit;
      var newNodes = exists ? newNode ?
        setIn(nodes, idx, newNode, isEditable) :
        spliceOut(nodes, idx, isEditable) :
        spliceIn(nodes, idx, newNode, isEditable);

      if (isEditable) {
        this.bitmap = newBitmap;
        this.nodes = newNodes;
        return this;
      }

      return new BitmapIndexedNode(ownerID, newBitmap, newNodes);
    };




    function HashArrayMapNode(ownerID, count, nodes) {
      this.ownerID = ownerID;
      this.count = count;
      this.nodes = nodes;
    }

    HashArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) {
      if (keyHash === undefined) {
        keyHash = hash(key);
      }
      var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
      var node = this.nodes[idx];
      return node ? node.get(shift + SHIFT, keyHash, key, notSetValue) : notSetValue;
    };

    HashArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
      if (keyHash === undefined) {
        keyHash = hash(key);
      }
      var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
      var removed = value === NOT_SET;
      var nodes = this.nodes;
      var node = nodes[idx];

      if (removed && !node) {
        return this;
      }

      var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter);
      if (newNode === node) {
        return this;
      }

      var newCount = this.count;
      if (!node) {
        newCount++;
      } else if (!newNode) {
        newCount--;
        if (newCount < MIN_HASH_ARRAY_MAP_SIZE) {
          return packNodes(ownerID, nodes, newCount, idx);
        }
      }

      var isEditable = ownerID && ownerID === this.ownerID;
      var newNodes = setIn(nodes, idx, newNode, isEditable);

      if (isEditable) {
        this.count = newCount;
        this.nodes = newNodes;
        return this;
      }

      return new HashArrayMapNode(ownerID, newCount, newNodes);
    };




    function HashCollisionNode(ownerID, keyHash, entries) {
      this.ownerID = ownerID;
      this.keyHash = keyHash;
      this.entries = entries;
    }

    HashCollisionNode.prototype.get = function(shift, keyHash, key, notSetValue) {
      var entries = this.entries;
      for (var ii = 0, len = entries.length; ii < len; ii++) {
        if (is(key, entries[ii][0])) {
          return entries[ii][1];
        }
      }
      return notSetValue;
    };

    HashCollisionNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
      if (keyHash === undefined) {
        keyHash = hash(key);
      }

      var removed = value === NOT_SET;

      if (keyHash !== this.keyHash) {
        if (removed) {
          return this;
        }
        SetRef(didAlter);
        SetRef(didChangeSize);
        return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]);
      }

      var entries = this.entries;
      var idx = 0;
      for (var len = entries.length; idx < len; idx++) {
        if (is(key, entries[idx][0])) {
          break;
        }
      }
      var exists = idx < len;

      if (exists ? entries[idx][1] === value : removed) {
        return this;
      }

      SetRef(didAlter);
      (removed || !exists) && SetRef(didChangeSize);

      if (removed && len === 2) {
        return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]);
      }

      var isEditable = ownerID && ownerID === this.ownerID;
      var newEntries = isEditable ? entries : arrCopy(entries);

      if (exists) {
        if (removed) {
          idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop());
        } else {
          newEntries[idx] = [key, value];
        }
      } else {
        newEntries.push([key, value]);
      }

      if (isEditable) {
        this.entries = newEntries;
        return this;
      }

      return new HashCollisionNode(ownerID, this.keyHash, newEntries);
    };




    function ValueNode(ownerID, keyHash, entry) {
      this.ownerID = ownerID;
      this.keyHash = keyHash;
      this.entry = entry;
    }

    ValueNode.prototype.get = function(shift, keyHash, key, notSetValue) {
      return is(key, this.entry[0]) ? this.entry[1] : notSetValue;
    };

    ValueNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
      var removed = value === NOT_SET;
      var keyMatch = is(key, this.entry[0]);
      if (keyMatch ? value === this.entry[1] : removed) {
        return this;
      }

      SetRef(didAlter);

      if (removed) {
        SetRef(didChangeSize);
        return; // undefined
      }

      if (keyMatch) {
        if (ownerID && ownerID === this.ownerID) {
          this.entry[1] = value;
          return this;
        }
        return new ValueNode(ownerID, this.keyHash, [key, value]);
      }

      SetRef(didChangeSize);
      return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]);
    };



  // #pragma Iterators

  ArrayMapNode.prototype.iterate =
  HashCollisionNode.prototype.iterate = function (fn, reverse) {
    var entries = this.entries;
    for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) {
      if (fn(entries[reverse ? maxIndex - ii : ii]) === false) {
        return false;
      }
    }
  }

  BitmapIndexedNode.prototype.iterate =
  HashArrayMapNode.prototype.iterate = function (fn, reverse) {
    var nodes = this.nodes;
    for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) {
      var node = nodes[reverse ? maxIndex - ii : ii];
      if (node && node.iterate(fn, reverse) === false) {
        return false;
      }
    }
  }

  ValueNode.prototype.iterate = function (fn, reverse) {
    return fn(this.entry);
  }

  createClass(MapIterator, Iterator);

    function MapIterator(map, type, reverse) {
      this._type = type;
      this._reverse = reverse;
      this._stack = map._root && mapIteratorFrame(map._root);
    }

    MapIterator.prototype.next = function() {
      var type = this._type;
      var stack = this._stack;
      while (stack) {
        var node = stack.node;
        var index = stack.index++;
        var maxIndex;
        if (node.entry) {
          if (index === 0) {
            return mapIteratorValue(type, node.entry);
          }
        } else if (node.entries) {
          maxIndex = node.entries.length - 1;
          if (index <= maxIndex) {
            return mapIteratorValue(type, node.entries[this._reverse ? maxIndex - index : index]);
          }
        } else {
          maxIndex = node.nodes.length - 1;
          if (index <= maxIndex) {
            var subNode = node.nodes[this._reverse ? maxIndex - index : index];
            if (subNode) {
              if (subNode.entry) {
                return mapIteratorValue(type, subNode.entry);
              }
              stack = this._stack = mapIteratorFrame(subNode, stack);
            }
            continue;
          }
        }
        stack = this._stack = this._stack.__prev;
      }
      return iteratorDone();
    };


  function mapIteratorValue(type, entry) {
    return iteratorValue(type, entry[0], entry[1]);
  }

  function mapIteratorFrame(node, prev) {
    return {
      node: node,
      index: 0,
      __prev: prev
    };
  }

  function makeMap(size, root, ownerID, hash) {
    var map = Object.create(MapPrototype);
    map.size = size;
    map._root = root;
    map.__ownerID = ownerID;
    map.__hash = hash;
    map.__altered = false;
    return map;
  }

  var EMPTY_MAP;
  function emptyMap() {
    return EMPTY_MAP || (EMPTY_MAP = makeMap(0));
  }

  function updateMap(map, k, v) {
    var newRoot;
    var newSize;
    if (!map._root) {
      if (v === NOT_SET) {
        return map;
      }
      newSize = 1;
      newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]);
    } else {
      var didChangeSize = MakeRef(CHANGE_LENGTH);
      var didAlter = MakeRef(DID_ALTER);
      newRoot = updateNode(map._root, map.__ownerID, 0, undefined, k, v, didChangeSize, didAlter);
      if (!didAlter.value) {
        return map;
      }
      newSize = map.size + (didChangeSize.value ? v === NOT_SET ? -1 : 1 : 0);
    }
    if (map.__ownerID) {
      map.size = newSize;
      map._root = newRoot;
      map.__hash = undefined;
      map.__altered = true;
      return map;
    }
    return newRoot ? makeMap(newSize, newRoot) : emptyMap();
  }

  function updateNode(node, ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
    if (!node) {
      if (value === NOT_SET) {
        return node;
      }
      SetRef(didAlter);
      SetRef(didChangeSize);
      return new ValueNode(ownerID, keyHash, [key, value]);
    }
    return node.update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter);
  }

  function isLeafNode(node) {
    return node.constructor === ValueNode || node.constructor === HashCollisionNode;
  }

  function mergeIntoNode(node, ownerID, shift, keyHash, entry) {
    if (node.keyHash === keyHash) {
      return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]);
    }

    var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK;
    var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;

    var newNode;
    var nodes = idx1 === idx2 ?
      [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)] :
      ((newNode = new ValueNode(ownerID, keyHash, entry)), idx1 < idx2 ? [node, newNode] : [newNode, node]);

    return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes);
  }

  function createNodes(ownerID, entries, key, value) {
    if (!ownerID) {
      ownerID = new OwnerID();
    }
    var node = new ValueNode(ownerID, hash(key), [key, value]);
    for (var ii = 0; ii < entries.length; ii++) {
      var entry = entries[ii];
      node = node.update(ownerID, 0, undefined, entry[0], entry[1]);
    }
    return node;
  }

  function packNodes(ownerID, nodes, count, excluding) {
    var bitmap = 0;
    var packedII = 0;
    var packedNodes = new Array(count);
    for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) {
      var node = nodes[ii];
      if (node !== undefined && ii !== excluding) {
        bitmap |= bit;
        packedNodes[packedII++] = node;
      }
    }
    return new BitmapIndexedNode(ownerID, bitmap, packedNodes);
  }

  function expandNodes(ownerID, nodes, bitmap, including, node) {
    var count = 0;
    var expandedNodes = new Array(SIZE);
    for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) {
      expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined;
    }
    expandedNodes[including] = node;
    return new HashArrayMapNode(ownerID, count + 1, expandedNodes);
  }

  function mergeIntoMapWith(map, merger, iterables) {
    var iters = [];
    for (var ii = 0; ii < iterables.length; ii++) {
      var value = iterables[ii];
      var iter = KeyedIterable(value);
      if (!isIterable(value)) {
        iter = iter.map(function(v ) {return fromJS(v)});
      }
      iters.push(iter);
    }
    return mergeIntoCollectionWith(map, merger, iters);
  }

  function deepMerger(existing, value, key) {
    return existing && existing.mergeDeep && isIterable(value) ?
      existing.mergeDeep(value) :
      is(existing, value) ? existing : value;
  }

  function deepMergerWith(merger) {
    return function(existing, value, key)  {
      if (existing && existing.mergeDeepWith && isIterable(value)) {
        return existing.mergeDeepWith(merger, value);
      }
      var nextValue = merger(existing, value, key);
      return is(existing, nextValue) ? existing : nextValue;
    };
  }

  function mergeIntoCollectionWith(collection, merger, iters) {
    iters = iters.filter(function(x ) {return x.size !== 0});
    if (iters.length === 0) {
      return collection;
    }
    if (collection.size === 0 && !collection.__ownerID && iters.length === 1) {
      return collection.constructor(iters[0]);
    }
    return collection.withMutations(function(collection ) {
      var mergeIntoMap = merger ?
        function(value, key)  {
          collection.update(key, NOT_SET, function(existing )
            {return existing === NOT_SET ? value : merger(existing, value, key)}
          );
        } :
        function(value, key)  {
          collection.set(key, value);
        }
      for (var ii = 0; ii < iters.length; ii++) {
        iters[ii].forEach(mergeIntoMap);
      }
    });
  }

  function updateInDeepMap(existing, keyPathIter, notSetValue, updater) {
    var isNotSet = existing === NOT_SET;
    var step = keyPathIter.next();
    if (step.done) {
      var existingValue = isNotSet ? notSetValue : existing;
      var newValue = updater(existingValue);
      return newValue === existingValue ? existing : newValue;
    }
    invariant(
      isNotSet || (existing && existing.set),
      'invalid keyPath'
    );
    var key = step.value;
    var nextExisting = isNotSet ? NOT_SET : existing.get(key, NOT_SET);
    var nextUpdated = updateInDeepMap(
      nextExisting,
      keyPathIter,
      notSetValue,
      updater
    );
    return nextUpdated === nextExisting ? existing :
      nextUpdated === NOT_SET ? existing.remove(key) :
      (isNotSet ? emptyMap() : existing).set(key, nextUpdated);
  }

  function popCount(x) {
    x = x - ((x >> 1) & 0x55555555);
    x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
    x = (x + (x >> 4)) & 0x0f0f0f0f;
    x = x + (x >> 8);
    x = x + (x >> 16);
    return x & 0x7f;
  }

  function setIn(array, idx, val, canEdit) {
    var newArray = canEdit ? array : arrCopy(array);
    newArray[idx] = val;
    return newArray;
  }

  function spliceIn(array, idx, val, canEdit) {
    var newLen = array.length + 1;
    if (canEdit && idx + 1 === newLen) {
      array[idx] = val;
      return array;
    }
    var newArray = new Array(newLen);
    var after = 0;
    for (var ii = 0; ii < newLen; ii++) {
      if (ii === idx) {
        newArray[ii] = val;
        after = -1;
      } else {
        newArray[ii] = array[ii + after];
      }
    }
    return newArray;
  }

  function spliceOut(array, idx, canEdit) {
    var newLen = array.length - 1;
    if (canEdit && idx === newLen) {
      array.pop();
      return array;
    }
    var newArray = new Array(newLen);
    var after = 0;
    for (var ii = 0; ii < newLen; ii++) {
      if (ii === idx) {
        after = 1;
      }
      newArray[ii] = array[ii + after];
    }
    return newArray;
  }

  var MAX_ARRAY_MAP_SIZE = SIZE / 4;
  var MAX_BITMAP_INDEXED_SIZE = SIZE / 2;
  var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4;

  createClass(List, IndexedCollection);

    // @pragma Construction

    function List(value) {
      var empty = emptyList();
      if (value === null || value === undefined) {
        return empty;
      }
      if (isList(value)) {
        return value;
      }
      var iter = IndexedIterable(value);
      var size = iter.size;
      if (size === 0) {
        return empty;
      }
      assertNotInfinite(size);
      if (size > 0 && size < SIZE) {
        return makeList(0, size, SHIFT, null, new VNode(iter.toArray()));
      }
      return empty.withMutations(function(list ) {
        list.setSize(size);
        iter.forEach(function(v, i)  {return list.set(i, v)});
      });
    }

    List.of = function(/*...values*/) {
      return this(arguments);
    };

    List.prototype.toString = function() {
      return this.__toString('List [', ']');
    };

    // @pragma Access

    List.prototype.get = function(index, notSetValue) {
      index = wrapIndex(this, index);
      if (index >= 0 && index < this.size) {
        index += this._origin;
        var node = listNodeFor(this, index);
        return node && node.array[index & MASK];
      }
      return notSetValue;
    };

    // @pragma Modification

    List.prototype.set = function(index, value) {
      return updateList(this, index, value);
    };

    List.prototype.remove = function(index) {
      return !this.has(index) ? this :
        index === 0 ? this.shift() :
        index === this.size - 1 ? this.pop() :
        this.splice(index, 1);
    };

    List.prototype.insert = function(index, value) {
      return this.splice(index, 0, value);
    };

    List.prototype.clear = function() {
      if (this.size === 0) {
        return this;
      }
      if (this.__ownerID) {
        this.size = this._origin = this._capacity = 0;
        this._level = SHIFT;
        this._root = this._tail = null;
        this.__hash = undefined;
        this.__altered = true;
        return this;
      }
      return emptyList();
    };

    List.prototype.push = function(/*...values*/) {
      var values = arguments;
      var oldSize = this.size;
      return this.withMutations(function(list ) {
        setListBounds(list, 0, oldSize + values.length);
        for (var ii = 0; ii < values.length; ii++) {
          list.set(oldSize + ii, values[ii]);
        }
      });
    };

    List.prototype.pop = function() {
      return setListBounds(this, 0, -1);
    };

    List.prototype.unshift = function(/*...values*/) {
      var values = arguments;
      return this.withMutations(function(list ) {
        setListBounds(list, -values.length);
        for (var ii = 0; ii < values.length; ii++) {
          list.set(ii, values[ii]);
        }
      });
    };

    List.prototype.shift = function() {
      return setListBounds(this, 1);
    };

    // @pragma Composition

    List.prototype.merge = function(/*...iters*/) {
      return mergeIntoListWith(this, undefined, arguments);
    };

    List.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
      return mergeIntoListWith(this, merger, iters);
    };

    List.prototype.mergeDeep = function(/*...iters*/) {
      return mergeIntoListWith(this, deepMerger, arguments);
    };

    List.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
      return mergeIntoListWith(this, deepMergerWith(merger), iters);
    };

    List.prototype.setSize = function(size) {
      return setListBounds(this, 0, size);
    };

    // @pragma Iteration

    List.prototype.slice = function(begin, end) {
      var size = this.size;
      if (wholeSlice(begin, end, size)) {
        return this;
      }
      return setListBounds(
        this,
        resolveBegin(begin, size),
        resolveEnd(end, size)
      );
    };

    List.prototype.__iterator = function(type, reverse) {
      var index = 0;
      var values = iterateList(this, reverse);
      return new Iterator(function()  {
        var value = values();
        return value === DONE ?
          iteratorDone() :
          iteratorValue(type, index++, value);
      });
    };

    List.prototype.__iterate = function(fn, reverse) {
      var index = 0;
      var values = iterateList(this, reverse);
      var value;
      while ((value = values()) !== DONE) {
        if (fn(value, index++, this) === false) {
          break;
        }
      }
      return index;
    };

    List.prototype.__ensureOwner = function(ownerID) {
      if (ownerID === this.__ownerID) {
        return this;
      }
      if (!ownerID) {
        this.__ownerID = ownerID;
        return this;
      }
      return makeList(this._origin, this._capacity, this._level, this._root, this._tail, ownerID, this.__hash);
    };


  function isList(maybeList) {
    return !!(maybeList && maybeList[IS_LIST_SENTINEL]);
  }

  List.isList = isList;

  var IS_LIST_SENTINEL = '@@__IMMUTABLE_LIST__@@';

  var ListPrototype = List.prototype;
  ListPrototype[IS_LIST_SENTINEL] = true;
  ListPrototype[DELETE] = ListPrototype.remove;
  ListPrototype.setIn = MapPrototype.setIn;
  ListPrototype.deleteIn =
  ListPrototype.removeIn = MapPrototype.removeIn;
  ListPrototype.update = MapPrototype.update;
  ListPrototype.updateIn = MapPrototype.updateIn;
  ListPrototype.mergeIn = MapPrototype.mergeIn;
  ListPrototype.mergeDeepIn = MapPrototype.mergeDeepIn;
  ListPrototype.withMutations = MapPrototype.withMutations;
  ListPrototype.asMutable = MapPrototype.asMutable;
  ListPrototype.asImmutable = MapPrototype.asImmutable;
  ListPrototype.wasAltered = MapPrototype.wasAltered;



    function VNode(array, ownerID) {
      this.array = array;
      this.ownerID = ownerID;
    }

    // TODO: seems like these methods are very similar

    VNode.prototype.removeBefore = function(ownerID, level, index) {
      if (index === level ? 1 << level : 0 || this.array.length === 0) {
        return this;
      }
      var originIndex = (index >>> level) & MASK;
      if (originIndex >= this.array.length) {
        return new VNode([], ownerID);
      }
      var removingFirst = originIndex === 0;
      var newChild;
      if (level > 0) {
        var oldChild = this.array[originIndex];
        newChild = oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index);
        if (newChild === oldChild && removingFirst) {
          return this;
        }
      }
      if (removingFirst && !newChild) {
        return this;
      }
      var editable = editableVNode(this, ownerID);
      if (!removingFirst) {
        for (var ii = 0; ii < originIndex; ii++) {
          editable.array[ii] = undefined;
        }
      }
      if (newChild) {
        editable.array[originIndex] = newChild;
      }
      return editable;
    };

    VNode.prototype.removeAfter = function(ownerID, level, index) {
      if (index === (level ? 1 << level : 0) || this.array.length === 0) {
        return this;
      }
      var sizeIndex = ((index - 1) >>> level) & MASK;
      if (sizeIndex >= this.array.length) {
        return this;
      }

      var newChild;
      if (level > 0) {
        var oldChild = this.array[sizeIndex];
        newChild = oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index);
        if (newChild === oldChild && sizeIndex === this.array.length - 1) {
          return this;
        }
      }

      var editable = editableVNode(this, ownerID);
      editable.array.splice(sizeIndex + 1);
      if (newChild) {
        editable.array[sizeIndex] = newChild;
      }
      return editable;
    };



  var DONE = {};

  function iterateList(list, reverse) {
    var left = list._origin;
    var right = list._capacity;
    var tailPos = getTailOffset(right);
    var tail = list._tail;

    return iterateNodeOrLeaf(list._root, list._level, 0);

    function iterateNodeOrLeaf(node, level, offset) {
      return level === 0 ?
        iterateLeaf(node, offset) :
        iterateNode(node, level, offset);
    }

    function iterateLeaf(node, offset) {
      var array = offset === tailPos ? tail && tail.array : node && node.array;
      var from = offset > left ? 0 : left - offset;
      var to = right - offset;
      if (to > SIZE) {
        to = SIZE;
      }
      return function()  {
        if (from === to) {
          return DONE;
        }
        var idx = reverse ? --to : from++;
        return array && array[idx];
      };
    }

    function iterateNode(node, level, offset) {
      var values;
      var array = node && node.array;
      var from = offset > left ? 0 : (left - offset) >> level;
      var to = ((right - offset) >> level) + 1;
      if (to > SIZE) {
        to = SIZE;
      }
      return function()  {
        do {
          if (values) {
            var value = values();
            if (value !== DONE) {
              return value;
            }
            values = null;
          }
          if (from === to) {
            return DONE;
          }
          var idx = reverse ? --to : from++;
          values = iterateNodeOrLeaf(
            array && array[idx], level - SHIFT, offset + (idx << level)
          );
        } while (true);
      };
    }
  }

  function makeList(origin, capacity, level, root, tail, ownerID, hash) {
    var list = Object.create(ListPrototype);
    list.size = capacity - origin;
    list._origin = origin;
    list._capacity = capacity;
    list._level = level;
    list._root = root;
    list._tail = tail;
    list.__ownerID = ownerID;
    list.__hash = hash;
    list.__altered = false;
    return list;
  }

  var EMPTY_LIST;
  function emptyList() {
    return EMPTY_LIST || (EMPTY_LIST = makeList(0, 0, SHIFT));
  }

  function updateList(list, index, value) {
    index = wrapIndex(list, index);

    if (index !== index) {
      return list;
    }

    if (index >= list.size || index < 0) {
      return list.withMutations(function(list ) {
        index < 0 ?
          setListBounds(list, index).set(0, value) :
          setListBounds(list, 0, index + 1).set(index, value)
      });
    }

    index += list._origin;

    var newTail = list._tail;
    var newRoot = list._root;
    var didAlter = MakeRef(DID_ALTER);
    if (index >= getTailOffset(list._capacity)) {
      newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter);
    } else {
      newRoot = updateVNode(newRoot, list.__ownerID, list._level, index, value, didAlter);
    }

    if (!didAlter.value) {
      return list;
    }

    if (list.__ownerID) {
      list._root = newRoot;
      list._tail = newTail;
      list.__hash = undefined;
      list.__altered = true;
      return list;
    }
    return makeList(list._origin, list._capacity, list._level, newRoot, newTail);
  }

  function updateVNode(node, ownerID, level, index, value, didAlter) {
    var idx = (index >>> level) & MASK;
    var nodeHas = node && idx < node.array.length;
    if (!nodeHas && value === undefined) {
      return node;
    }

    var newNode;

    if (level > 0) {
      var lowerNode = node && node.array[idx];
      var newLowerNode = updateVNode(lowerNode, ownerID, level - SHIFT, index, value, didAlter);
      if (newLowerNode === lowerNode) {
        return node;
      }
      newNode = editableVNode(node, ownerID);
      newNode.array[idx] = newLowerNode;
      return newNode;
    }

    if (nodeHas && node.array[idx] === value) {
      return node;
    }

    SetRef(didAlter);

    newNode = editableVNode(node, ownerID);
    if (value === undefined && idx === newNode.array.length - 1) {
      newNode.array.pop();
    } else {
      newNode.array[idx] = value;
    }
    return newNode;
  }

  function editableVNode(node, ownerID) {
    if (ownerID && node && ownerID === node.ownerID) {
      return node;
    }
    return new VNode(node ? node.array.slice() : [], ownerID);
  }

  function listNodeFor(list, rawIndex) {
    if (rawIndex >= getTailOffset(list._capacity)) {
      return list._tail;
    }
    if (rawIndex < 1 << (list._level + SHIFT)) {
      var node = list._root;
      var level = list._level;
      while (node && level > 0) {
        node = node.array[(rawIndex >>> level) & MASK];
        level -= SHIFT;
      }
      return node;
    }
  }

  function setListBounds(list, begin, end) {
    // Sanitize begin & end using this shorthand for ToInt32(argument)
    // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32
    if (begin !== undefined) {
      begin = begin | 0;
    }
    if (end !== undefined) {
      end = end | 0;
    }
    var owner = list.__ownerID || new OwnerID();
    var oldOrigin = list._origin;
    var oldCapacity = list._capacity;
    var newOrigin = oldOrigin + begin;
    var newCapacity = end === undefined ? oldCapacity : end < 0 ? oldCapacity + end : oldOrigin + end;
    if (newOrigin === oldOrigin && newCapacity === oldCapacity) {
      return list;
    }

    // If it's going to end after it starts, it's empty.
    if (newOrigin >= newCapacity) {
      return list.clear();
    }

    var newLevel = list._level;
    var newRoot = list._root;

    // New origin might need creating a higher root.
    var offsetShift = 0;
    while (newOrigin + offsetShift < 0) {
      newRoot = new VNode(newRoot && newRoot.array.length ? [undefined, newRoot] : [], owner);
      newLevel += SHIFT;
      offsetShift += 1 << newLevel;
    }
    if (offsetShift) {
      newOrigin += offsetShift;
      oldOrigin += offsetShift;
      newCapacity += offsetShift;
      oldCapacity += offsetShift;
    }

    var oldTailOffset = getTailOffset(oldCapacity);
    var newTailOffset = getTailOffset(newCapacity);

    // New size might need creating a higher root.
    while (newTailOffset >= 1 << (newLevel + SHIFT)) {
      newRoot = new VNode(newRoot && newRoot.array.length ? [newRoot] : [], owner);
      newLevel += SHIFT;
    }

    // Locate or create the new tail.
    var oldTail = list._tail;
    var newTail = newTailOffset < oldTailOffset ?
      listNodeFor(list, newCapacity - 1) :
      newTailOffset > oldTailOffset ? new VNode([], owner) : oldTail;

    // Merge Tail into tree.
    if (oldTail && newTailOffset > oldTailOffset && newOrigin < oldCapacity && oldTail.array.length) {
      newRoot = editableVNode(newRoot, owner);
      var node = newRoot;
      for (var level = newLevel; level > SHIFT; level -= SHIFT) {
        var idx = (oldTailOffset >>> level) & MASK;
        node = node.array[idx] = editableVNode(node.array[idx], owner);
      }
      node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail;
    }

    // If the size has been reduced, there's a chance the tail needs to be trimmed.
    if (newCapacity < oldCapacity) {
      newTail = newTail && newTail.removeAfter(owner, 0, newCapacity);
    }

    // If the new origin is within the tail, then we do not need a root.
    if (newOrigin >= newTailOffset) {
      newOrigin -= newTailOffset;
      newCapacity -= newTailOffset;
      newLevel = SHIFT;
      newRoot = null;
      newTail = newTail && newTail.removeBefore(owner, 0, newOrigin);

    // Otherwise, if the root has been trimmed, garbage collect.
    } else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) {
      offsetShift = 0;

      // Identify the new top root node of the subtree of the old root.
      while (newRoot) {
        var beginIndex = (newOrigin >>> newLevel) & MASK;
        if (beginIndex !== (newTailOffset >>> newLevel) & MASK) {
          break;
        }
        if (beginIndex) {
          offsetShift += (1 << newLevel) * beginIndex;
        }
        newLevel -= SHIFT;
        newRoot = newRoot.array[beginIndex];
      }

      // Trim the new sides of the new root.
      if (newRoot && newOrigin > oldOrigin) {
        newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift);
      }
      if (newRoot && newTailOffset < oldTailOffset) {
        newRoot = newRoot.removeAfter(owner, newLevel, newTailOffset - offsetShift);
      }
      if (offsetShift) {
        newOrigin -= offsetShift;
        newCapacity -= offsetShift;
      }
    }

    if (list.__ownerID) {
      list.size = newCapacity - newOrigin;
      list._origin = newOrigin;
      list._capacity = newCapacity;
      list._level = newLevel;
      list._root = newRoot;
      list._tail = newTail;
      list.__hash = undefined;
      list.__altered = true;
      return list;
    }
    return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail);
  }

  function mergeIntoListWith(list, merger, iterables) {
    var iters = [];
    var maxSize = 0;
    for (var ii = 0; ii < iterables.length; ii++) {
      var value = iterables[ii];
      var iter = IndexedIterable(value);
      if (iter.size > maxSize) {
        maxSize = iter.size;
      }
      if (!isIterable(value)) {
        iter = iter.map(function(v ) {return fromJS(v)});
      }
      iters.push(iter);
    }
    if (maxSize > list.size) {
      list = list.setSize(maxSize);
    }
    return mergeIntoCollectionWith(list, merger, iters);
  }

  function getTailOffset(size) {
    return size < SIZE ? 0 : (((size - 1) >>> SHIFT) << SHIFT);
  }

  createClass(OrderedMap, Map);

    // @pragma Construction

    function OrderedMap(value) {
      return value === null || value === undefined ? emptyOrderedMap() :
        isOrderedMap(value) ? value :
        emptyOrderedMap().withMutations(function(map ) {
          var iter = KeyedIterable(value);
          assertNotInfinite(iter.size);
          iter.forEach(function(v, k)  {return map.set(k, v)});
        });
    }

    OrderedMap.of = function(/*...values*/) {
      return this(arguments);
    };

    OrderedMap.prototype.toString = function() {
      return this.__toString('OrderedMap {', '}');
    };

    // @pragma Access

    OrderedMap.prototype.get = function(k, notSetValue) {
      var index = this._map.get(k);
      return index !== undefined ? this._list.get(index)[1] : notSetValue;
    };

    // @pragma Modification

    OrderedMap.prototype.clear = function() {
      if (this.size === 0) {
        return this;
      }
      if (this.__ownerID) {
        this.size = 0;
        this._map.clear();
        this._list.clear();
        return this;
      }
      return emptyOrderedMap();
    };

    OrderedMap.prototype.set = function(k, v) {
      return updateOrderedMap(this, k, v);
    };

    OrderedMap.prototype.remove = function(k) {
      return updateOrderedMap(this, k, NOT_SET);
    };

    OrderedMap.prototype.wasAltered = function() {
      return this._map.wasAltered() || this._list.wasAltered();
    };

    OrderedMap.prototype.__iterate = function(fn, reverse) {var this$0 = this;
      return this._list.__iterate(
        function(entry ) {return entry && fn(entry[1], entry[0], this$0)},
        reverse
      );
    };

    OrderedMap.prototype.__iterator = function(type, reverse) {
      return this._list.fromEntrySeq().__iterator(type, reverse);
    };

    OrderedMap.prototype.__ensureOwner = function(ownerID) {
      if (ownerID === this.__ownerID) {
        return this;
      }
      var newMap = this._map.__ensureOwner(ownerID);
      var newList = this._list.__ensureOwner(ownerID);
      if (!ownerID) {
        this.__ownerID = ownerID;
        this._map = newMap;
        this._list = newList;
        return this;
      }
      return makeOrderedMap(newMap, newList, ownerID, this.__hash);
    };


  function isOrderedMap(maybeOrderedMap) {
    return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap);
  }

  OrderedMap.isOrderedMap = isOrderedMap;

  OrderedMap.prototype[IS_ORDERED_SENTINEL] = true;
  OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove;



  function makeOrderedMap(map, list, ownerID, hash) {
    var omap = Object.create(OrderedMap.prototype);
    omap.size = map ? map.size : 0;
    omap._map = map;
    omap._list = list;
    omap.__ownerID = ownerID;
    omap.__hash = hash;
    return omap;
  }

  var EMPTY_ORDERED_MAP;
  function emptyOrderedMap() {
    return EMPTY_ORDERED_MAP || (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList()));
  }

  function updateOrderedMap(omap, k, v) {
    var map = omap._map;
    var list = omap._list;
    var i = map.get(k);
    var has = i !== undefined;
    var newMap;
    var newList;
    if (v === NOT_SET) { // removed
      if (!has) {
        return omap;
      }
      if (list.size >= SIZE && list.size >= map.size * 2) {
        newList = list.filter(function(entry, idx)  {return entry !== undefined && i !== idx});
        newMap = newList.toKeyedSeq().map(function(entry ) {return entry[0]}).flip().toMap();
        if (omap.__ownerID) {
          newMap.__ownerID = newList.__ownerID = omap.__ownerID;
        }
      } else {
        newMap = map.remove(k);
        newList = i === list.size - 1 ? list.pop() : list.set(i, undefined);
      }
    } else {
      if (has) {
        if (v === list.get(i)[1]) {
          return omap;
        }
        newMap = map;
        newList = list.set(i, [k, v]);
      } else {
        newMap = map.set(k, list.size);
        newList = list.set(list.size, [k, v]);
      }
    }
    if (omap.__ownerID) {
      omap.size = newMap.size;
      omap._map = newMap;
      omap._list = newList;
      omap.__hash = undefined;
      return omap;
    }
    return makeOrderedMap(newMap, newList);
  }

  createClass(ToKeyedSequence, KeyedSeq);
    function ToKeyedSequence(indexed, useKeys) {
      this._iter = indexed;
      this._useKeys = useKeys;
      this.size = indexed.size;
    }

    ToKeyedSequence.prototype.get = function(key, notSetValue) {
      return this._iter.get(key, notSetValue);
    };

    ToKeyedSequence.prototype.has = function(key) {
      return this._iter.has(key);
    };

    ToKeyedSequence.prototype.valueSeq = function() {
      return this._iter.valueSeq();
    };

    ToKeyedSequence.prototype.reverse = function() {var this$0 = this;
      var reversedSequence = reverseFactory(this, true);
      if (!this._useKeys) {
        reversedSequence.valueSeq = function()  {return this$0._iter.toSeq().reverse()};
      }
      return reversedSequence;
    };

    ToKeyedSequence.prototype.map = function(mapper, context) {var this$0 = this;
      var mappedSequence = mapFactory(this, mapper, context);
      if (!this._useKeys) {
        mappedSequence.valueSeq = function()  {return this$0._iter.toSeq().map(mapper, context)};
      }
      return mappedSequence;
    };

    ToKeyedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
      var ii;
      return this._iter.__iterate(
        this._useKeys ?
          function(v, k)  {return fn(v, k, this$0)} :
          ((ii = reverse ? resolveSize(this) : 0),
            function(v ) {return fn(v, reverse ? --ii : ii++, this$0)}),
        reverse
      );
    };

    ToKeyedSequence.prototype.__iterator = function(type, reverse) {
      if (this._useKeys) {
        return this._iter.__iterator(type, reverse);
      }
      var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
      var ii = reverse ? resolveSize(this) : 0;
      return new Iterator(function()  {
        var step = iterator.next();
        return step.done ? step :
          iteratorValue(type, reverse ? --ii : ii++, step.value, step);
      });
    };

  ToKeyedSequence.prototype[IS_ORDERED_SENTINEL] = true;


  createClass(ToIndexedSequence, IndexedSeq);
    function ToIndexedSequence(iter) {
      this._iter = iter;
      this.size = iter.size;
    }

    ToIndexedSequence.prototype.includes = function(value) {
      return this._iter.includes(value);
    };

    ToIndexedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
      var iterations = 0;
      return this._iter.__iterate(function(v ) {return fn(v, iterations++, this$0)}, reverse);
    };

    ToIndexedSequence.prototype.__iterator = function(type, reverse) {
      var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
      var iterations = 0;
      return new Iterator(function()  {
        var step = iterator.next();
        return step.done ? step :
          iteratorValue(type, iterations++, step.value, step)
      });
    };



  createClass(ToSetSequence, SetSeq);
    function ToSetSequence(iter) {
      this._iter = iter;
      this.size = iter.size;
    }

    ToSetSequence.prototype.has = function(key) {
      return this._iter.includes(key);
    };

    ToSetSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
      return this._iter.__iterate(function(v ) {return fn(v, v, this$0)}, reverse);
    };

    ToSetSequence.prototype.__iterator = function(type, reverse) {
      var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
      return new Iterator(function()  {
        var step = iterator.next();
        return step.done ? step :
          iteratorValue(type, step.value, step.value, step);
      });
    };



  createClass(FromEntriesSequence, KeyedSeq);
    function FromEntriesSequence(entries) {
      this._iter = entries;
      this.size = entries.size;
    }

    FromEntriesSequence.prototype.entrySeq = function() {
      return this._iter.toSeq();
    };

    FromEntriesSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
      return this._iter.__iterate(function(entry ) {
        // Check if entry exists first so array access doesn't throw for holes
        // in the parent iteration.
        if (entry) {
          validateEntry(entry);
          var indexedIterable = isIterable(entry);
          return fn(
            indexedIterable ? entry.get(1) : entry[1],
            indexedIterable ? entry.get(0) : entry[0],
            this$0
          );
        }
      }, reverse);
    };

    FromEntriesSequence.prototype.__iterator = function(type, reverse) {
      var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
      return new Iterator(function()  {
        while (true) {
          var step = iterator.next();
          if (step.done) {
            return step;
          }
          var entry = step.value;
          // Check if entry exists first so array access doesn't throw for holes
          // in the parent iteration.
          if (entry) {
            validateEntry(entry);
            var indexedIterable = isIterable(entry);
            return iteratorValue(
              type,
              indexedIterable ? entry.get(0) : entry[0],
              indexedIterable ? entry.get(1) : entry[1],
              step
            );
          }
        }
      });
    };


  ToIndexedSequence.prototype.cacheResult =
  ToKeyedSequence.prototype.cacheResult =
  ToSetSequence.prototype.cacheResult =
  FromEntriesSequence.prototype.cacheResult =
    cacheResultThrough;


  function flipFactory(iterable) {
    var flipSequence = makeSequence(iterable);
    flipSequence._iter = iterable;
    flipSequence.size = iterable.size;
    flipSequence.flip = function()  {return iterable};
    flipSequence.reverse = function () {
      var reversedSequence = iterable.reverse.apply(this); // super.reverse()
      reversedSequence.flip = function()  {return iterable.reverse()};
      return reversedSequence;
    };
    flipSequence.has = function(key ) {return iterable.includes(key)};
    flipSequence.includes = function(key ) {return iterable.has(key)};
    flipSequence.cacheResult = cacheResultThrough;
    flipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
      return iterable.__iterate(function(v, k)  {return fn(k, v, this$0) !== false}, reverse);
    }
    flipSequence.__iteratorUncached = function(type, reverse) {
      if (type === ITERATE_ENTRIES) {
        var iterator = iterable.__iterator(type, reverse);
        return new Iterator(function()  {
          var step = iterator.next();
          if (!step.done) {
            var k = step.value[0];
            step.value[0] = step.value[1];
            step.value[1] = k;
          }
          return step;
        });
      }
      return iterable.__iterator(
        type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES,
        reverse
      );
    }
    return flipSequence;
  }


  function mapFactory(iterable, mapper, context) {
    var mappedSequence = makeSequence(iterable);
    mappedSequence.size = iterable.size;
    mappedSequence.has = function(key ) {return iterable.has(key)};
    mappedSequence.get = function(key, notSetValue)  {
      var v = iterable.get(key, NOT_SET);
      return v === NOT_SET ?
        notSetValue :
        mapper.call(context, v, key, iterable);
    };
    mappedSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
      return iterable.__iterate(
        function(v, k, c)  {return fn(mapper.call(context, v, k, c), k, this$0) !== false},
        reverse
      );
    }
    mappedSequence.__iteratorUncached = function (type, reverse) {
      var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
      return new Iterator(function()  {
        var step = iterator.next();
        if (step.done) {
          return step;
        }
        var entry = step.value;
        var key = entry[0];
        return iteratorValue(
          type,
          key,
          mapper.call(context, entry[1], key, iterable),
          step
        );
      });
    }
    return mappedSequence;
  }


  function reverseFactory(iterable, useKeys) {
    var reversedSequence = makeSequence(iterable);
    reversedSequence._iter = iterable;
    reversedSequence.size = iterable.size;
    reversedSequence.reverse = function()  {return iterable};
    if (iterable.flip) {
      reversedSequence.flip = function () {
        var flipSequence = flipFactory(iterable);
        flipSequence.reverse = function()  {return iterable.flip()};
        return flipSequence;
      };
    }
    reversedSequence.get = function(key, notSetValue) 
      {return iterable.get(useKeys ? key : -1 - key, notSetValue)};
    reversedSequence.has = function(key )
      {return iterable.has(useKeys ? key : -1 - key)};
    reversedSequence.includes = function(value ) {return iterable.includes(value)};
    reversedSequence.cacheResult = cacheResultThrough;
    reversedSequence.__iterate = function (fn, reverse) {var this$0 = this;
      return iterable.__iterate(function(v, k)  {return fn(v, k, this$0)}, !reverse);
    };
    reversedSequence.__iterator =
      function(type, reverse)  {return iterable.__iterator(type, !reverse)};
    return reversedSequence;
  }


  function filterFactory(iterable, predicate, context, useKeys) {
    var filterSequence = makeSequence(iterable);
    if (useKeys) {
      filterSequence.has = function(key ) {
        var v = iterable.get(key, NOT_SET);
        return v !== NOT_SET && !!predicate.call(context, v, key, iterable);
      };
      filterSequence.get = function(key, notSetValue)  {
        var v = iterable.get(key, NOT_SET);
        return v !== NOT_SET && predicate.call(context, v, key, iterable) ?
          v : notSetValue;
      };
    }
    filterSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
      var iterations = 0;
      iterable.__iterate(function(v, k, c)  {
        if (predicate.call(context, v, k, c)) {
          iterations++;
          return fn(v, useKeys ? k : iterations - 1, this$0);
        }
      }, reverse);
      return iterations;
    };
    filterSequence.__iteratorUncached = function (type, reverse) {
      var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
      var iterations = 0;
      return new Iterator(function()  {
        while (true) {
          var step = iterator.next();
          if (step.done) {
            return step;
          }
          var entry = step.value;
          var key = entry[0];
          var value = entry[1];
          if (predicate.call(context, value, key, iterable)) {
            return iteratorValue(type, useKeys ? key : iterations++, value, step);
          }
        }
      });
    }
    return filterSequence;
  }


  function countByFactory(iterable, grouper, context) {
    var groups = Map().asMutable();
    iterable.__iterate(function(v, k)  {
      groups.update(
        grouper.call(context, v, k, iterable),
        0,
        function(a ) {return a + 1}
      );
    });
    return groups.asImmutable();
  }


  function groupByFactory(iterable, grouper, context) {
    var isKeyedIter = isKeyed(iterable);
    var groups = (isOrdered(iterable) ? OrderedMap() : Map()).asMutable();
    iterable.__iterate(function(v, k)  {
      groups.update(
        grouper.call(context, v, k, iterable),
        function(a ) {return (a = a || [], a.push(isKeyedIter ? [k, v] : v), a)}
      );
    });
    var coerce = iterableClass(iterable);
    return groups.map(function(arr ) {return reify(iterable, coerce(arr))});
  }


  function sliceFactory(iterable, begin, end, useKeys) {
    var originalSize = iterable.size;

    // Sanitize begin & end using this shorthand for ToInt32(argument)
    // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32
    if (begin !== undefined) {
      begin = begin | 0;
    }
    if (end !== undefined) {
      end = end | 0;
    }

    if (wholeSlice(begin, end, originalSize)) {
      return iterable;
    }

    var resolvedBegin = resolveBegin(begin, originalSize);
    var resolvedEnd = resolveEnd(end, originalSize);

    // begin or end will be NaN if they were provided as negative numbers and
    // this iterable's size is unknown. In that case, cache first so there is
    // a known size and these do not resolve to NaN.
    if (resolvedBegin !== resolvedBegin || resolvedEnd !== resolvedEnd) {
      return sliceFactory(iterable.toSeq().cacheResult(), begin, end, useKeys);
    }

    // Note: resolvedEnd is undefined when the original sequence's length is
    // unknown and this slice did not supply an end and should contain all
    // elements after resolvedBegin.
    // In that case, resolvedSize will be NaN and sliceSize will remain undefined.
    var resolvedSize = resolvedEnd - resolvedBegin;
    var sliceSize;
    if (resolvedSize === resolvedSize) {
      sliceSize = resolvedSize < 0 ? 0 : resolvedSize;
    }

    var sliceSeq = makeSequence(iterable);

    // If iterable.size is undefined, the size of the realized sliceSeq is
    // unknown at this point unless the number of items to slice is 0
    sliceSeq.size = sliceSize === 0 ? sliceSize : iterable.size && sliceSize || undefined;

    if (!useKeys && isSeq(iterable) && sliceSize >= 0) {
      sliceSeq.get = function (index, notSetValue) {
        index = wrapIndex(this, index);
        return index >= 0 && index < sliceSize ?
          iterable.get(index + resolvedBegin, notSetValue) :
          notSetValue;
      }
    }

    sliceSeq.__iterateUncached = function(fn, reverse) {var this$0 = this;
      if (sliceSize === 0) {
        return 0;
      }
      if (reverse) {
        return this.cacheResult().__iterate(fn, reverse);
      }
      var skipped = 0;
      var isSkipping = true;
      var iterations = 0;
      iterable.__iterate(function(v, k)  {
        if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) {
          iterations++;
          return fn(v, useKeys ? k : iterations - 1, this$0) !== false &&
                 iterations !== sliceSize;
        }
      });
      return iterations;
    };

    sliceSeq.__iteratorUncached = function(type, reverse) {
      if (sliceSize !== 0 && reverse) {
        return this.cacheResult().__iterator(type, reverse);
      }
      // Don't bother instantiating parent iterator if taking 0.
      var iterator = sliceSize !== 0 && iterable.__iterator(type, reverse);
      var skipped = 0;
      var iterations = 0;
      return new Iterator(function()  {
        while (skipped++ < resolvedBegin) {
          iterator.next();
        }
        if (++iterations > sliceSize) {
          return iteratorDone();
        }
        var step = iterator.next();
        if (useKeys || type === ITERATE_VALUES) {
          return step;
        } else if (type === ITERATE_KEYS) {
          return iteratorValue(type, iterations - 1, undefined, step);
        } else {
          return iteratorValue(type, iterations - 1, step.value[1], step);
        }
      });
    }

    return sliceSeq;
  }


  function takeWhileFactory(iterable, predicate, context) {
    var takeSequence = makeSequence(iterable);
    takeSequence.__iterateUncached = function(fn, reverse) {var this$0 = this;
      if (reverse) {
        return this.cacheResult().__iterate(fn, reverse);
      }
      var iterations = 0;
      iterable.__iterate(function(v, k, c) 
        {return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$0)}
      );
      return iterations;
    };
    takeSequence.__iteratorUncached = function(type, reverse) {var this$0 = this;
      if (reverse) {
        return this.cacheResult().__iterator(type, reverse);
      }
      var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
      var iterating = true;
      return new Iterator(function()  {
        if (!iterating) {
          return iteratorDone();
        }
        var step = iterator.next();
        if (step.done) {
          return step;
        }
        var entry = step.value;
        var k = entry[0];
        var v = entry[1];
        if (!predicate.call(context, v, k, this$0)) {
          iterating = false;
          return iteratorDone();
        }
        return type === ITERATE_ENTRIES ? step :
          iteratorValue(type, k, v, step);
      });
    };
    return takeSequence;
  }


  function skipWhileFactory(iterable, predicate, context, useKeys) {
    var skipSequence = makeSequence(iterable);
    skipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
      if (reverse) {
        return this.cacheResult().__iterate(fn, reverse);
      }
      var isSkipping = true;
      var iterations = 0;
      iterable.__iterate(function(v, k, c)  {
        if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) {
          iterations++;
          return fn(v, useKeys ? k : iterations - 1, this$0);
        }
      });
      return iterations;
    };
    skipSequence.__iteratorUncached = function(type, reverse) {var this$0 = this;
      if (reverse) {
        return this.cacheResult().__iterator(type, reverse);
      }
      var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
      var skipping = true;
      var iterations = 0;
      return new Iterator(function()  {
        var step, k, v;
        do {
          step = iterator.next();
          if (step.done) {
            if (useKeys || type === ITERATE_VALUES) {
              return step;
            } else if (type === ITERATE_KEYS) {
              return iteratorValue(type, iterations++, undefined, step);
            } else {
              return iteratorValue(type, iterations++, step.value[1], step);
            }
          }
          var entry = step.value;
          k = entry[0];
          v = entry[1];
          skipping && (skipping = predicate.call(context, v, k, this$0));
        } while (skipping);
        return type === ITERATE_ENTRIES ? step :
          iteratorValue(type, k, v, step);
      });
    };
    return skipSequence;
  }


  function concatFactory(iterable, values) {
    var isKeyedIterable = isKeyed(iterable);
    var iters = [iterable].concat(values).map(function(v ) {
      if (!isIterable(v)) {
        v = isKeyedIterable ?
          keyedSeqFromValue(v) :
          indexedSeqFromValue(Array.isArray(v) ? v : [v]);
      } else if (isKeyedIterable) {
        v = KeyedIterable(v);
      }
      return v;
    }).filter(function(v ) {return v.size !== 0});

    if (iters.length === 0) {
      return iterable;
    }

    if (iters.length === 1) {
      var singleton = iters[0];
      if (singleton === iterable ||
          isKeyedIterable && isKeyed(singleton) ||
          isIndexed(iterable) && isIndexed(singleton)) {
        return singleton;
      }
    }

    var concatSeq = new ArraySeq(iters);
    if (isKeyedIterable) {
      concatSeq = concatSeq.toKeyedSeq();
    } else if (!isIndexed(iterable)) {
      concatSeq = concatSeq.toSetSeq();
    }
    concatSeq = concatSeq.flatten(true);
    concatSeq.size = iters.reduce(
      function(sum, seq)  {
        if (sum !== undefined) {
          var size = seq.size;
          if (size !== undefined) {
            return sum + size;
          }
        }
      },
      0
    );
    return concatSeq;
  }


  function flattenFactory(iterable, depth, useKeys) {
    var flatSequence = makeSequence(iterable);
    flatSequence.__iterateUncached = function(fn, reverse) {
      var iterations = 0;
      var stopped = false;
      function flatDeep(iter, currentDepth) {var this$0 = this;
        iter.__iterate(function(v, k)  {
          if ((!depth || currentDepth < depth) && isIterable(v)) {
            flatDeep(v, currentDepth + 1);
          } else if (fn(v, useKeys ? k : iterations++, this$0) === false) {
            stopped = true;
          }
          return !stopped;
        }, reverse);
      }
      flatDeep(iterable, 0);
      return iterations;
    }
    flatSequence.__iteratorUncached = function(type, reverse) {
      var iterator = iterable.__iterator(type, reverse);
      var stack = [];
      var iterations = 0;
      return new Iterator(function()  {
        while (iterator) {
          var step = iterator.next();
          if (step.done !== false) {
            iterator = stack.pop();
            continue;
          }
          var v = step.value;
          if (type === ITERATE_ENTRIES) {
            v = v[1];
          }
          if ((!depth || stack.length < depth) && isIterable(v)) {
            stack.push(iterator);
            iterator = v.__iterator(type, reverse);
          } else {
            return useKeys ? step : iteratorValue(type, iterations++, v, step);
          }
        }
        return iteratorDone();
      });
    }
    return flatSequence;
  }


  function flatMapFactory(iterable, mapper, context) {
    var coerce = iterableClass(iterable);
    return iterable.toSeq().map(
      function(v, k)  {return coerce(mapper.call(context, v, k, iterable))}
    ).flatten(true);
  }


  function interposeFactory(iterable, separator) {
    var interposedSequence = makeSequence(iterable);
    interposedSequence.size = iterable.size && iterable.size * 2 -1;
    interposedSequence.__iterateUncached = function(fn, reverse) {var this$0 = this;
      var iterations = 0;
      iterable.__iterate(function(v, k) 
        {return (!iterations || fn(separator, iterations++, this$0) !== false) &&
        fn(v, iterations++, this$0) !== false},
        reverse
      );
      return iterations;
    };
    interposedSequence.__iteratorUncached = function(type, reverse) {
      var iterator = iterable.__iterator(ITERATE_VALUES, reverse);
      var iterations = 0;
      var step;
      return new Iterator(function()  {
        if (!step || iterations % 2) {
          step = iterator.next();
          if (step.done) {
            return step;
          }
        }
        return iterations % 2 ?
          iteratorValue(type, iterations++, separator) :
          iteratorValue(type, iterations++, step.value, step);
      });
    };
    return interposedSequence;
  }


  function sortFactory(iterable, comparator, mapper) {
    if (!comparator) {
      comparator = defaultComparator;
    }
    var isKeyedIterable = isKeyed(iterable);
    var index = 0;
    var entries = iterable.toSeq().map(
      function(v, k)  {return [k, v, index++, mapper ? mapper(v, k, iterable) : v]}
    ).toArray();
    entries.sort(function(a, b)  {return comparator(a[3], b[3]) || a[2] - b[2]}).forEach(
      isKeyedIterable ?
      function(v, i)  { entries[i].length = 2; } :
      function(v, i)  { entries[i] = v[1]; }
    );
    return isKeyedIterable ? KeyedSeq(entries) :
      isIndexed(iterable) ? IndexedSeq(entries) :
      SetSeq(entries);
  }


  function maxFactory(iterable, comparator, mapper) {
    if (!comparator) {
      comparator = defaultComparator;
    }
    if (mapper) {
      var entry = iterable.toSeq()
        .map(function(v, k)  {return [v, mapper(v, k, iterable)]})
        .reduce(function(a, b)  {return maxCompare(comparator, a[1], b[1]) ? b : a});
      return entry && entry[0];
    } else {
      return iterable.reduce(function(a, b)  {return maxCompare(comparator, a, b) ? b : a});
    }
  }

  function maxCompare(comparator, a, b) {
    var comp = comparator(b, a);
    // b is considered the new max if the comparator declares them equal, but
    // they are not equal and b is in fact a nullish value.
    return (comp === 0 && b !== a && (b === undefined || b === null || b !== b)) || comp > 0;
  }


  function zipWithFactory(keyIter, zipper, iters) {
    var zipSequence = makeSequence(keyIter);
    zipSequence.size = new ArraySeq(iters).map(function(i ) {return i.size}).min();
    // Note: this a generic base implementation of __iterate in terms of
    // __iterator which may be more generically useful in the future.
    zipSequence.__iterate = function(fn, reverse) {
      /* generic:
      var iterator = this.__iterator(ITERATE_ENTRIES, reverse);
      var step;
      var iterations = 0;
      while (!(step = iterator.next()).done) {
        iterations++;
        if (fn(step.value[1], step.value[0], this) === false) {
          break;
        }
      }
      return iterations;
      */
      // indexed:
      var iterator = this.__iterator(ITERATE_VALUES, reverse);
      var step;
      var iterations = 0;
      while (!(step = iterator.next()).done) {
        if (fn(step.value, iterations++, this) === false) {
          break;
        }
      }
      return iterations;
    };
    zipSequence.__iteratorUncached = function(type, reverse) {
      var iterators = iters.map(function(i )
        {return (i = Iterable(i), getIterator(reverse ? i.reverse() : i))}
      );
      var iterations = 0;
      var isDone = false;
      return new Iterator(function()  {
        var steps;
        if (!isDone) {
          steps = iterators.map(function(i ) {return i.next()});
          isDone = steps.some(function(s ) {return s.done});
        }
        if (isDone) {
          return iteratorDone();
        }
        return iteratorValue(
          type,
          iterations++,
          zipper.apply(null, steps.map(function(s ) {return s.value}))
        );
      });
    };
    return zipSequence
  }


  // #pragma Helper Functions

  function reify(iter, seq) {
    return isSeq(iter) ? seq : iter.constructor(seq);
  }

  function validateEntry(entry) {
    if (entry !== Object(entry)) {
      throw new TypeError('Expected [K, V] tuple: ' + entry);
    }
  }

  function resolveSize(iter) {
    assertNotInfinite(iter.size);
    return ensureSize(iter);
  }

  function iterableClass(iterable) {
    return isKeyed(iterable) ? KeyedIterable :
      isIndexed(iterable) ? IndexedIterable :
      SetIterable;
  }

  function makeSequence(iterable) {
    return Object.create(
      (
        isKeyed(iterable) ? KeyedSeq :
        isIndexed(iterable) ? IndexedSeq :
        SetSeq
      ).prototype
    );
  }

  function cacheResultThrough() {
    if (this._iter.cacheResult) {
      this._iter.cacheResult();
      this.size = this._iter.size;
      return this;
    } else {
      return Seq.prototype.cacheResult.call(this);
    }
  }

  function defaultComparator(a, b) {
    return a > b ? 1 : a < b ? -1 : 0;
  }

  function forceIterator(keyPath) {
    var iter = getIterator(keyPath);
    if (!iter) {
      // Array might not be iterable in this environment, so we need a fallback
      // to our wrapped type.
      if (!isArrayLike(keyPath)) {
        throw new TypeError('Expected iterable or array-like: ' + keyPath);
      }
      iter = getIterator(Iterable(keyPath));
    }
    return iter;
  }

  createClass(Record, KeyedCollection);

    function Record(defaultValues, name) {
      var hasInitialized;

      var RecordType = function Record(values) {
        if (values instanceof RecordType) {
          return values;
        }
        if (!(this instanceof RecordType)) {
          return new RecordType(values);
        }
        if (!hasInitialized) {
          hasInitialized = true;
          var keys = Object.keys(defaultValues);
          setProps(RecordTypePrototype, keys);
          RecordTypePrototype.size = keys.length;
          RecordTypePrototype._name = name;
          RecordTypePrototype._keys = keys;
          RecordTypePrototype._defaultValues = defaultValues;
        }
        this._map = Map(values);
      };

      var RecordTypePrototype = RecordType.prototype = Object.create(RecordPrototype);
      RecordTypePrototype.constructor = RecordType;

      return RecordType;
    }

    Record.prototype.toString = function() {
      return this.__toString(recordName(this) + ' {', '}');
    };

    // @pragma Access

    Record.prototype.has = function(k) {
      return this._defaultValues.hasOwnProperty(k);
    };

    Record.prototype.get = function(k, notSetValue) {
      if (!this.has(k)) {
        return notSetValue;
      }
      var defaultVal = this._defaultValues[k];
      return this._map ? this._map.get(k, defaultVal) : defaultVal;
    };

    // @pragma Modification

    Record.prototype.clear = function() {
      if (this.__ownerID) {
        this._map && this._map.clear();
        return this;
      }
      var RecordType = this.constructor;
      return RecordType._empty || (RecordType._empty = makeRecord(this, emptyMap()));
    };

    Record.prototype.set = function(k, v) {
      if (!this.has(k)) {
        throw new Error('Cannot set unknown key "' + k + '" on ' + recordName(this));
      }
      var newMap = this._map && this._map.set(k, v);
      if (this.__ownerID || newMap === this._map) {
        return this;
      }
      return makeRecord(this, newMap);
    };

    Record.prototype.remove = function(k) {
      if (!this.has(k)) {
        return this;
      }
      var newMap = this._map && this._map.remove(k);
      if (this.__ownerID || newMap === this._map) {
        return this;
      }
      return makeRecord(this, newMap);
    };

    Record.prototype.wasAltered = function() {
      return this._map.wasAltered();
    };

    Record.prototype.__iterator = function(type, reverse) {var this$0 = this;
      return KeyedIterable(this._defaultValues).map(function(_, k)  {return this$0.get(k)}).__iterator(type, reverse);
    };

    Record.prototype.__iterate = function(fn, reverse) {var this$0 = this;
      return KeyedIterable(this._defaultValues).map(function(_, k)  {return this$0.get(k)}).__iterate(fn, reverse);
    };

    Record.prototype.__ensureOwner = function(ownerID) {
      if (ownerID === this.__ownerID) {
        return this;
      }
      var newMap = this._map && this._map.__ensureOwner(ownerID);
      if (!ownerID) {
        this.__ownerID = ownerID;
        this._map = newMap;
        return this;
      }
      return makeRecord(this, newMap, ownerID);
    };


  var RecordPrototype = Record.prototype;
  RecordPrototype[DELETE] = RecordPrototype.remove;
  RecordPrototype.deleteIn =
  RecordPrototype.removeIn = MapPrototype.removeIn;
  RecordPrototype.merge = MapPrototype.merge;
  RecordPrototype.mergeWith = MapPrototype.mergeWith;
  RecordPrototype.mergeIn = MapPrototype.mergeIn;
  RecordPrototype.mergeDeep = MapPrototype.mergeDeep;
  RecordPrototype.mergeDeepWith = MapPrototype.mergeDeepWith;
  RecordPrototype.mergeDeepIn = MapPrototype.mergeDeepIn;
  RecordPrototype.setIn = MapPrototype.setIn;
  RecordPrototype.update = MapPrototype.update;
  RecordPrototype.updateIn = MapPrototype.updateIn;
  RecordPrototype.withMutations = MapPrototype.withMutations;
  RecordPrototype.asMutable = MapPrototype.asMutable;
  RecordPrototype.asImmutable = MapPrototype.asImmutable;


  function makeRecord(likeRecord, map, ownerID) {
    var record = Object.create(Object.getPrototypeOf(likeRecord));
    record._map = map;
    record.__ownerID = ownerID;
    return record;
  }

  function recordName(record) {
    return record._name || record.constructor.name || 'Record';
  }

  function setProps(prototype, names) {
    try {
      names.forEach(setProp.bind(undefined, prototype));
    } catch (error) {
      // Object.defineProperty failed. Probably IE8.
    }
  }

  function setProp(prototype, name) {
    Object.defineProperty(prototype, name, {
      get: function() {
        return this.get(name);
      },
      set: function(value) {
        invariant(this.__ownerID, 'Cannot set on an immutable record.');
        this.set(name, value);
      }
    });
  }

  createClass(Set, SetCollection);

    // @pragma Construction

    function Set(value) {
      return value === null || value === undefined ? emptySet() :
        isSet(value) && !isOrdered(value) ? value :
        emptySet().withMutations(function(set ) {
          var iter = SetIterable(value);
          assertNotInfinite(iter.size);
          iter.forEach(function(v ) {return set.add(v)});
        });
    }

    Set.of = function(/*...values*/) {
      return this(arguments);
    };

    Set.fromKeys = function(value) {
      return this(KeyedIterable(value).keySeq());
    };

    Set.prototype.toString = function() {
      return this.__toString('Set {', '}');
    };

    // @pragma Access

    Set.prototype.has = function(value) {
      return this._map.has(value);
    };

    // @pragma Modification

    Set.prototype.add = function(value) {
      return updateSet(this, this._map.set(value, true));
    };

    Set.prototype.remove = function(value) {
      return updateSet(this, this._map.remove(value));
    };

    Set.prototype.clear = function() {
      return updateSet(this, this._map.clear());
    };

    // @pragma Composition

    Set.prototype.union = function() {var iters = SLICE$0.call(arguments, 0);
      iters = iters.filter(function(x ) {return x.size !== 0});
      if (iters.length === 0) {
        return this;
      }
      if (this.size === 0 && !this.__ownerID && iters.length === 1) {
        return this.constructor(iters[0]);
      }
      return this.withMutations(function(set ) {
        for (var ii = 0; ii < iters.length; ii++) {
          SetIterable(iters[ii]).forEach(function(value ) {return set.add(value)});
        }
      });
    };

    Set.prototype.intersect = function() {var iters = SLICE$0.call(arguments, 0);
      if (iters.length === 0) {
        return this;
      }
      iters = iters.map(function(iter ) {return SetIterable(iter)});
      var originalSet = this;
      return this.withMutations(function(set ) {
        originalSet.forEach(function(value ) {
          if (!iters.every(function(iter ) {return iter.includes(value)})) {
            set.remove(value);
          }
        });
      });
    };

    Set.prototype.subtract = function() {var iters = SLICE$0.call(arguments, 0);
      if (iters.length === 0) {
        return this;
      }
      iters = iters.map(function(iter ) {return SetIterable(iter)});
      var originalSet = this;
      return this.withMutations(function(set ) {
        originalSet.forEach(function(value ) {
          if (iters.some(function(iter ) {return iter.includes(value)})) {
            set.remove(value);
          }
        });
      });
    };

    Set.prototype.merge = function() {
      return this.union.apply(this, arguments);
    };

    Set.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
      return this.union.apply(this, iters);
    };

    Set.prototype.sort = function(comparator) {
      // Late binding
      return OrderedSet(sortFactory(this, comparator));
    };

    Set.prototype.sortBy = function(mapper, comparator) {
      // Late binding
      return OrderedSet(sortFactory(this, comparator, mapper));
    };

    Set.prototype.wasAltered = function() {
      return this._map.wasAltered();
    };

    Set.prototype.__iterate = function(fn, reverse) {var this$0 = this;
      return this._map.__iterate(function(_, k)  {return fn(k, k, this$0)}, reverse);
    };

    Set.prototype.__iterator = function(type, reverse) {
      return this._map.map(function(_, k)  {return k}).__iterator(type, reverse);
    };

    Set.prototype.__ensureOwner = function(ownerID) {
      if (ownerID === this.__ownerID) {
        return this;
      }
      var newMap = this._map.__ensureOwner(ownerID);
      if (!ownerID) {
        this.__ownerID = ownerID;
        this._map = newMap;
        return this;
      }
      return this.__make(newMap, ownerID);
    };


  function isSet(maybeSet) {
    return !!(maybeSet && maybeSet[IS_SET_SENTINEL]);
  }

  Set.isSet = isSet;

  var IS_SET_SENTINEL = '@@__IMMUTABLE_SET__@@';

  var SetPrototype = Set.prototype;
  SetPrototype[IS_SET_SENTINEL] = true;
  SetPrototype[DELETE] = SetPrototype.remove;
  SetPrototype.mergeDeep = SetPrototype.merge;
  SetPrototype.mergeDeepWith = SetPrototype.mergeWith;
  SetPrototype.withMutations = MapPrototype.withMutations;
  SetPrototype.asMutable = MapPrototype.asMutable;
  SetPrototype.asImmutable = MapPrototype.asImmutable;

  SetPrototype.__empty = emptySet;
  SetPrototype.__make = makeSet;

  function updateSet(set, newMap) {
    if (set.__ownerID) {
      set.size = newMap.size;
      set._map = newMap;
      return set;
    }
    return newMap === set._map ? set :
      newMap.size === 0 ? set.__empty() :
      set.__make(newMap);
  }

  function makeSet(map, ownerID) {
    var set = Object.create(SetPrototype);
    set.size = map ? map.size : 0;
    set._map = map;
    set.__ownerID = ownerID;
    return set;
  }

  var EMPTY_SET;
  function emptySet() {
    return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap()));
  }

  createClass(OrderedSet, Set);

    // @pragma Construction

    function OrderedSet(value) {
      return value === null || value === undefined ? emptyOrderedSet() :
        isOrderedSet(value) ? value :
        emptyOrderedSet().withMutations(function(set ) {
          var iter = SetIterable(value);
          assertNotInfinite(iter.size);
          iter.forEach(function(v ) {return set.add(v)});
        });
    }

    OrderedSet.of = function(/*...values*/) {
      return this(arguments);
    };

    OrderedSet.fromKeys = function(value) {
      return this(KeyedIterable(value).keySeq());
    };

    OrderedSet.prototype.toString = function() {
      return this.__toString('OrderedSet {', '}');
    };


  function isOrderedSet(maybeOrderedSet) {
    return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet);
  }

  OrderedSet.isOrderedSet = isOrderedSet;

  var OrderedSetPrototype = OrderedSet.prototype;
  OrderedSetPrototype[IS_ORDERED_SENTINEL] = true;

  OrderedSetPrototype.__empty = emptyOrderedSet;
  OrderedSetPrototype.__make = makeOrderedSet;

  function makeOrderedSet(map, ownerID) {
    var set = Object.create(OrderedSetPrototype);
    set.size = map ? map.size : 0;
    set._map = map;
    set.__ownerID = ownerID;
    return set;
  }

  var EMPTY_ORDERED_SET;
  function emptyOrderedSet() {
    return EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap()));
  }

  createClass(Stack, IndexedCollection);

    // @pragma Construction

    function Stack(value) {
      return value === null || value === undefined ? emptyStack() :
        isStack(value) ? value :
        emptyStack().unshiftAll(value);
    }

    Stack.of = function(/*...values*/) {
      return this(arguments);
    };

    Stack.prototype.toString = function() {
      return this.__toString('Stack [', ']');
    };

    // @pragma Access

    Stack.prototype.get = function(index, notSetValue) {
      var head = this._head;
      index = wrapIndex(this, index);
      while (head && index--) {
        head = head.next;
      }
      return head ? head.value : notSetValue;
    };

    Stack.prototype.peek = function() {
      return this._head && this._head.value;
    };

    // @pragma Modification

    Stack.prototype.push = function(/*...values*/) {
      if (arguments.length === 0) {
        return this;
      }
      var newSize = this.size + arguments.length;
      var head = this._head;
      for (var ii = arguments.length - 1; ii >= 0; ii--) {
        head = {
          value: arguments[ii],
          next: head
        };
      }
      if (this.__ownerID) {
        this.size = newSize;
        this._head = head;
        this.__hash = undefined;
        this.__altered = true;
        return this;
      }
      return makeStack(newSize, head);
    };

    Stack.prototype.pushAll = function(iter) {
      iter = IndexedIterable(iter);
      if (iter.size === 0) {
        return this;
      }
      assertNotInfinite(iter.size);
      var newSize = this.size;
      var head = this._head;
      iter.reverse().forEach(function(value ) {
        newSize++;
        head = {
          value: value,
          next: head
        };
      });
      if (this.__ownerID) {
        this.size = newSize;
        this._head = head;
        this.__hash = undefined;
        this.__altered = true;
        return this;
      }
      return makeStack(newSize, head);
    };

    Stack.prototype.pop = function() {
      return this.slice(1);
    };

    Stack.prototype.unshift = function(/*...values*/) {
      return this.push.apply(this, arguments);
    };

    Stack.prototype.unshiftAll = function(iter) {
      return this.pushAll(iter);
    };

    Stack.prototype.shift = function() {
      return this.pop.apply(this, arguments);
    };

    Stack.prototype.clear = function() {
      if (this.size === 0) {
        return this;
      }
      if (this.__ownerID) {
        this.size = 0;
        this._head = undefined;
        this.__hash = undefined;
        this.__altered = true;
        return this;
      }
      return emptyStack();
    };

    Stack.prototype.slice = function(begin, end) {
      if (wholeSlice(begin, end, this.size)) {
        return this;
      }
      var resolvedBegin = resolveBegin(begin, this.size);
      var resolvedEnd = resolveEnd(end, this.size);
      if (resolvedEnd !== this.size) {
        // super.slice(begin, end);
        return IndexedCollection.prototype.slice.call(this, begin, end);
      }
      var newSize = this.size - resolvedBegin;
      var head = this._head;
      while (resolvedBegin--) {
        head = head.next;
      }
      if (this.__ownerID) {
        this.size = newSize;
        this._head = head;
        this.__hash = undefined;
        this.__altered = true;
        return this;
      }
      return makeStack(newSize, head);
    };

    // @pragma Mutability

    Stack.prototype.__ensureOwner = function(ownerID) {
      if (ownerID === this.__ownerID) {
        return this;
      }
      if (!ownerID) {
        this.__ownerID = ownerID;
        this.__altered = false;
        return this;
      }
      return makeStack(this.size, this._head, ownerID, this.__hash);
    };

    // @pragma Iteration

    Stack.prototype.__iterate = function(fn, reverse) {
      if (reverse) {
        return this.reverse().__iterate(fn);
      }
      var iterations = 0;
      var node = this._head;
      while (node) {
        if (fn(node.value, iterations++, this) === false) {
          break;
        }
        node = node.next;
      }
      return iterations;
    };

    Stack.prototype.__iterator = function(type, reverse) {
      if (reverse) {
        return this.reverse().__iterator(type);
      }
      var iterations = 0;
      var node = this._head;
      return new Iterator(function()  {
        if (node) {
          var value = node.value;
          node = node.next;
          return iteratorValue(type, iterations++, value);
        }
        return iteratorDone();
      });
    };


  function isStack(maybeStack) {
    return !!(maybeStack && maybeStack[IS_STACK_SENTINEL]);
  }

  Stack.isStack = isStack;

  var IS_STACK_SENTINEL = '@@__IMMUTABLE_STACK__@@';

  var StackPrototype = Stack.prototype;
  StackPrototype[IS_STACK_SENTINEL] = true;
  StackPrototype.withMutations = MapPrototype.withMutations;
  StackPrototype.asMutable = MapPrototype.asMutable;
  StackPrototype.asImmutable = MapPrototype.asImmutable;
  StackPrototype.wasAltered = MapPrototype.wasAltered;


  function makeStack(size, head, ownerID, hash) {
    var map = Object.create(StackPrototype);
    map.size = size;
    map._head = head;
    map.__ownerID = ownerID;
    map.__hash = hash;
    map.__altered = false;
    return map;
  }

  var EMPTY_STACK;
  function emptyStack() {
    return EMPTY_STACK || (EMPTY_STACK = makeStack(0));
  }

  /**
   * Contributes additional methods to a constructor
   */
  function mixin(ctor, methods) {
    var keyCopier = function(key ) { ctor.prototype[key] = methods[key]; };
    Object.keys(methods).forEach(keyCopier);
    Object.getOwnPropertySymbols &&
      Object.getOwnPropertySymbols(methods).forEach(keyCopier);
    return ctor;
  }

  Iterable.Iterator = Iterator;

  mixin(Iterable, {

    // ### Conversion to other types

    toArray: function() {
      assertNotInfinite(this.size);
      var array = new Array(this.size || 0);
      this.valueSeq().__iterate(function(v, i)  { array[i] = v; });
      return array;
    },

    toIndexedSeq: function() {
      return new ToIndexedSequence(this);
    },

    toJS: function() {
      return this.toSeq().map(
        function(value ) {return value && typeof value.toJS === 'function' ? value.toJS() : value}
      ).__toJS();
    },

    toJSON: function() {
      return this.toSeq().map(
        function(value ) {return value && typeof value.toJSON === 'function' ? value.toJSON() : value}
      ).__toJS();
    },

    toKeyedSeq: function() {
      return new ToKeyedSequence(this, true);
    },

    toMap: function() {
      // Use Late Binding here to solve the circular dependency.
      return Map(this.toKeyedSeq());
    },

    toObject: function() {
      assertNotInfinite(this.size);
      var object = {};
      this.__iterate(function(v, k)  { object[k] = v; });
      return object;
    },

    toOrderedMap: function() {
      // Use Late Binding here to solve the circular dependency.
      return OrderedMap(this.toKeyedSeq());
    },

    toOrderedSet: function() {
      // Use Late Binding here to solve the circular dependency.
      return OrderedSet(isKeyed(this) ? this.valueSeq() : this);
    },

    toSet: function() {
      // Use Late Binding here to solve the circular dependency.
      return Set(isKeyed(this) ? this.valueSeq() : this);
    },

    toSetSeq: function() {
      return new ToSetSequence(this);
    },

    toSeq: function() {
      return isIndexed(this) ? this.toIndexedSeq() :
        isKeyed(this) ? this.toKeyedSeq() :
        this.toSetSeq();
    },

    toStack: function() {
      // Use Late Binding here to solve the circular dependency.
      return Stack(isKeyed(this) ? this.valueSeq() : this);
    },

    toList: function() {
      // Use Late Binding here to solve the circular dependency.
      return List(isKeyed(this) ? this.valueSeq() : this);
    },


    // ### Common JavaScript methods and properties

    toString: function() {
      return '[Iterable]';
    },

    __toString: function(head, tail) {
      if (this.size === 0) {
        return head + tail;
      }
      return head + ' ' + this.toSeq().map(this.__toStringMapper).join(', ') + ' ' + tail;
    },


    // ### ES6 Collection methods (ES6 Array and Map)

    concat: function() {var values = SLICE$0.call(arguments, 0);
      return reify(this, concatFactory(this, values));
    },

    includes: function(searchValue) {
      return this.some(function(value ) {return is(value, searchValue)});
    },

    entries: function() {
      return this.__iterator(ITERATE_ENTRIES);
    },

    every: function(predicate, context) {
      assertNotInfinite(this.size);
      var returnValue = true;
      this.__iterate(function(v, k, c)  {
        if (!predicate.call(context, v, k, c)) {
          returnValue = false;
          return false;
        }
      });
      return returnValue;
    },

    filter: function(predicate, context) {
      return reify(this, filterFactory(this, predicate, context, true));
    },

    find: function(predicate, context, notSetValue) {
      var entry = this.findEntry(predicate, context);
      return entry ? entry[1] : notSetValue;
    },

    findEntry: function(predicate, context) {
      var found;
      this.__iterate(function(v, k, c)  {
        if (predicate.call(context, v, k, c)) {
          found = [k, v];
          return false;
        }
      });
      return found;
    },

    findLastEntry: function(predicate, context) {
      return this.toSeq().reverse().findEntry(predicate, context);
    },

    forEach: function(sideEffect, context) {
      assertNotInfinite(this.size);
      return this.__iterate(context ? sideEffect.bind(context) : sideEffect);
    },

    join: function(separator) {
      assertNotInfinite(this.size);
      separator = separator !== undefined ? '' + separator : ',';
      var joined = '';
      var isFirst = true;
      this.__iterate(function(v ) {
        isFirst ? (isFirst = false) : (joined += separator);
        joined += v !== null && v !== undefined ? v.toString() : '';
      });
      return joined;
    },

    keys: function() {
      return this.__iterator(ITERATE_KEYS);
    },

    map: function(mapper, context) {
      return reify(this, mapFactory(this, mapper, context));
    },

    reduce: function(reducer, initialReduction, context) {
      assertNotInfinite(this.size);
      var reduction;
      var useFirst;
      if (arguments.length < 2) {
        useFirst = true;
      } else {
        reduction = initialReduction;
      }
      this.__iterate(function(v, k, c)  {
        if (useFirst) {
          useFirst = false;
          reduction = v;
        } else {
          reduction = reducer.call(context, reduction, v, k, c);
        }
      });
      return reduction;
    },

    reduceRight: function(reducer, initialReduction, context) {
      var reversed = this.toKeyedSeq().reverse();
      return reversed.reduce.apply(reversed, arguments);
    },

    reverse: function() {
      return reify(this, reverseFactory(this, true));
    },

    slice: function(begin, end) {
      return reify(this, sliceFactory(this, begin, end, true));
    },

    some: function(predicate, context) {
      return !this.every(not(predicate), context);
    },

    sort: function(comparator) {
      return reify(this, sortFactory(this, comparator));
    },

    values: function() {
      return this.__iterator(ITERATE_VALUES);
    },


    // ### More sequential methods

    butLast: function() {
      return this.slice(0, -1);
    },

    isEmpty: function() {
      return this.size !== undefined ? this.size === 0 : !this.some(function()  {return true});
    },

    count: function(predicate, context) {
      return ensureSize(
        predicate ? this.toSeq().filter(predicate, context) : this
      );
    },

    countBy: function(grouper, context) {
      return countByFactory(this, grouper, context);
    },

    equals: function(other) {
      return deepEqual(this, other);
    },

    entrySeq: function() {
      var iterable = this;
      if (iterable._cache) {
        // We cache as an entries array, so we can just return the cache!
        return new ArraySeq(iterable._cache);
      }
      var entriesSequence = iterable.toSeq().map(entryMapper).toIndexedSeq();
      entriesSequence.fromEntrySeq = function()  {return iterable.toSeq()};
      return entriesSequence;
    },

    filterNot: function(predicate, context) {
      return this.filter(not(predicate), context);
    },

    findLast: function(predicate, context, notSetValue) {
      return this.toKeyedSeq().reverse().find(predicate, context, notSetValue);
    },

    first: function() {
      return this.find(returnTrue);
    },

    flatMap: function(mapper, context) {
      return reify(this, flatMapFactory(this, mapper, context));
    },

    flatten: function(depth) {
      return reify(this, flattenFactory(this, depth, true));
    },

    fromEntrySeq: function() {
      return new FromEntriesSequence(this);
    },

    get: function(searchKey, notSetValue) {
      return this.find(function(_, key)  {return is(key, searchKey)}, undefined, notSetValue);
    },

    getIn: function(searchKeyPath, notSetValue) {
      var nested = this;
      // Note: in an ES6 environment, we would prefer:
      // for (var key of searchKeyPath) {
      var iter = forceIterator(searchKeyPath);
      var step;
      while (!(step = iter.next()).done) {
        var key = step.value;
        nested = nested && nested.get ? nested.get(key, NOT_SET) : NOT_SET;
        if (nested === NOT_SET) {
          return notSetValue;
        }
      }
      return nested;
    },

    groupBy: function(grouper, context) {
      return groupByFactory(this, grouper, context);
    },

    has: function(searchKey) {
      return this.get(searchKey, NOT_SET) !== NOT_SET;
    },

    hasIn: function(searchKeyPath) {
      return this.getIn(searchKeyPath, NOT_SET) !== NOT_SET;
    },

    isSubset: function(iter) {
      iter = typeof iter.includes === 'function' ? iter : Iterable(iter);
      return this.every(function(value ) {return iter.includes(value)});
    },

    isSuperset: function(iter) {
      iter = typeof iter.isSubset === 'function' ? iter : Iterable(iter);
      return iter.isSubset(this);
    },

    keySeq: function() {
      return this.toSeq().map(keyMapper).toIndexedSeq();
    },

    last: function() {
      return this.toSeq().reverse().first();
    },

    max: function(comparator) {
      return maxFactory(this, comparator);
    },

    maxBy: function(mapper, comparator) {
      return maxFactory(this, comparator, mapper);
    },

    min: function(comparator) {
      return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator);
    },

    minBy: function(mapper, comparator) {
      return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator, mapper);
    },

    rest: function() {
      return this.slice(1);
    },

    skip: function(amount) {
      return this.slice(Math.max(0, amount));
    },

    skipLast: function(amount) {
      return reify(this, this.toSeq().reverse().skip(amount).reverse());
    },

    skipWhile: function(predicate, context) {
      return reify(this, skipWhileFactory(this, predicate, context, true));
    },

    skipUntil: function(predicate, context) {
      return this.skipWhile(not(predicate), context);
    },

    sortBy: function(mapper, comparator) {
      return reify(this, sortFactory(this, comparator, mapper));
    },

    take: function(amount) {
      return this.slice(0, Math.max(0, amount));
    },

    takeLast: function(amount) {
      return reify(this, this.toSeq().reverse().take(amount).reverse());
    },

    takeWhile: function(predicate, context) {
      return reify(this, takeWhileFactory(this, predicate, context));
    },

    takeUntil: function(predicate, context) {
      return this.takeWhile(not(predicate), context);
    },

    valueSeq: function() {
      return this.toIndexedSeq();
    },


    // ### Hashable Object

    hashCode: function() {
      return this.__hash || (this.__hash = hashIterable(this));
    }


    // ### Internal

    // abstract __iterate(fn, reverse)

    // abstract __iterator(type, reverse)
  });

  // var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@';
  // var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@';
  // var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@';
  // var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@';

  var IterablePrototype = Iterable.prototype;
  IterablePrototype[IS_ITERABLE_SENTINEL] = true;
  IterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.values;
  IterablePrototype.__toJS = IterablePrototype.toArray;
  IterablePrototype.__toStringMapper = quoteString;
  IterablePrototype.inspect =
  IterablePrototype.toSource = function() { return this.toString(); };
  IterablePrototype.chain = IterablePrototype.flatMap;
  IterablePrototype.contains = IterablePrototype.includes;

  // Temporary warning about using length
  (function () {
    try {
      Object.defineProperty(IterablePrototype, 'length', {
        get: function () {
          if (!Iterable.noLengthWarning) {
            var stack;
            try {
              throw new Error();
            } catch (error) {
              stack = error.stack;
            }
            if (stack.indexOf('_wrapObject') === -1) {
              console && console.warn && console.warn(
                'iterable.length has been deprecated, '+
                'use iterable.size or iterable.count(). '+
                'This warning will become a silent error in a future version. ' +
                stack
              );
              return this.size;
            }
          }
        }
      });
    } catch (e) {}
  })();



  mixin(KeyedIterable, {

    // ### More sequential methods

    flip: function() {
      return reify(this, flipFactory(this));
    },

    findKey: function(predicate, context) {
      var entry = this.findEntry(predicate, context);
      return entry && entry[0];
    },

    findLastKey: function(predicate, context) {
      return this.toSeq().reverse().findKey(predicate, context);
    },

    keyOf: function(searchValue) {
      return this.findKey(function(value ) {return is(value, searchValue)});
    },

    lastKeyOf: function(searchValue) {
      return this.findLastKey(function(value ) {return is(value, searchValue)});
    },

    mapEntries: function(mapper, context) {var this$0 = this;
      var iterations = 0;
      return reify(this,
        this.toSeq().map(
          function(v, k)  {return mapper.call(context, [k, v], iterations++, this$0)}
        ).fromEntrySeq()
      );
    },

    mapKeys: function(mapper, context) {var this$0 = this;
      return reify(this,
        this.toSeq().flip().map(
          function(k, v)  {return mapper.call(context, k, v, this$0)}
        ).flip()
      );
    }

  });

  var KeyedIterablePrototype = KeyedIterable.prototype;
  KeyedIterablePrototype[IS_KEYED_SENTINEL] = true;
  KeyedIterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.entries;
  KeyedIterablePrototype.__toJS = IterablePrototype.toObject;
  KeyedIterablePrototype.__toStringMapper = function(v, k)  {return JSON.stringify(k) + ': ' + quoteString(v)};



  mixin(IndexedIterable, {

    // ### Conversion to other types

    toKeyedSeq: function() {
      return new ToKeyedSequence(this, false);
    },


    // ### ES6 Collection methods (ES6 Array and Map)

    filter: function(predicate, context) {
      return reify(this, filterFactory(this, predicate, context, false));
    },

    findIndex: function(predicate, context) {
      var entry = this.findEntry(predicate, context);
      return entry ? entry[0] : -1;
    },

    indexOf: function(searchValue) {
      var key = this.toKeyedSeq().keyOf(searchValue);
      return key === undefined ? -1 : key;
    },

    lastIndexOf: function(searchValue) {
      var key = this.toKeyedSeq().reverse().keyOf(searchValue);
      return key === undefined ? -1 : key;

      // var index =
      // return this.toSeq().reverse().indexOf(searchValue);
    },

    reverse: function() {
      return reify(this, reverseFactory(this, false));
    },

    slice: function(begin, end) {
      return reify(this, sliceFactory(this, begin, end, false));
    },

    splice: function(index, removeNum /*, ...values*/) {
      var numArgs = arguments.length;
      removeNum = Math.max(removeNum | 0, 0);
      if (numArgs === 0 || (numArgs === 2 && !removeNum)) {
        return this;
      }
      // If index is negative, it should resolve relative to the size of the
      // collection. However size may be expensive to compute if not cached, so
      // only call count() if the number is in fact negative.
      index = resolveBegin(index, index < 0 ? this.count() : this.size);
      var spliced = this.slice(0, index);
      return reify(
        this,
        numArgs === 1 ?
          spliced :
          spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum))
      );
    },


    // ### More collection methods

    findLastIndex: function(predicate, context) {
      var key = this.toKeyedSeq().findLastKey(predicate, context);
      return key === undefined ? -1 : key;
    },

    first: function() {
      return this.get(0);
    },

    flatten: function(depth) {
      return reify(this, flattenFactory(this, depth, false));
    },

    get: function(index, notSetValue) {
      index = wrapIndex(this, index);
      return (index < 0 || (this.size === Infinity ||
          (this.size !== undefined && index > this.size))) ?
        notSetValue :
        this.find(function(_, key)  {return key === index}, undefined, notSetValue);
    },

    has: function(index) {
      index = wrapIndex(this, index);
      return index >= 0 && (this.size !== undefined ?
        this.size === Infinity || index < this.size :
        this.indexOf(index) !== -1
      );
    },

    interpose: function(separator) {
      return reify(this, interposeFactory(this, separator));
    },

    interleave: function(/*...iterables*/) {
      var iterables = [this].concat(arrCopy(arguments));
      var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, iterables);
      var interleaved = zipped.flatten(true);
      if (zipped.size) {
        interleaved.size = zipped.size * iterables.length;
      }
      return reify(this, interleaved);
    },

    last: function() {
      return this.get(-1);
    },

    skipWhile: function(predicate, context) {
      return reify(this, skipWhileFactory(this, predicate, context, false));
    },

    zip: function(/*, ...iterables */) {
      var iterables = [this].concat(arrCopy(arguments));
      return reify(this, zipWithFactory(this, defaultZipper, iterables));
    },

    zipWith: function(zipper/*, ...iterables */) {
      var iterables = arrCopy(arguments);
      iterables[0] = this;
      return reify(this, zipWithFactory(this, zipper, iterables));
    }

  });

  IndexedIterable.prototype[IS_INDEXED_SENTINEL] = true;
  IndexedIterable.prototype[IS_ORDERED_SENTINEL] = true;



  mixin(SetIterable, {

    // ### ES6 Collection methods (ES6 Array and Map)

    get: function(value, notSetValue) {
      return this.has(value) ? value : notSetValue;
    },

    includes: function(value) {
      return this.has(value);
    },


    // ### More sequential methods

    keySeq: function() {
      return this.valueSeq();
    }

  });

  SetIterable.prototype.has = IterablePrototype.includes;


  // Mixin subclasses

  mixin(KeyedSeq, KeyedIterable.prototype);
  mixin(IndexedSeq, IndexedIterable.prototype);
  mixin(SetSeq, SetIterable.prototype);

  mixin(KeyedCollection, KeyedIterable.prototype);
  mixin(IndexedCollection, IndexedIterable.prototype);
  mixin(SetCollection, SetIterable.prototype);


  // #pragma Helper functions

  function keyMapper(v, k) {
    return k;
  }

  function entryMapper(v, k) {
    return [k, v];
  }

  function not(predicate) {
    return function() {
      return !predicate.apply(this, arguments);
    }
  }

  function neg(predicate) {
    return function() {
      return -predicate.apply(this, arguments);
    }
  }

  function quoteString(value) {
    return typeof value === 'string' ? JSON.stringify(value) : value;
  }

  function defaultZipper() {
    return arrCopy(arguments);
  }

  function defaultNegComparator(a, b) {
    return a < b ? 1 : a > b ? -1 : 0;
  }

  function hashIterable(iterable) {
    if (iterable.size === Infinity) {
      return 0;
    }
    var ordered = isOrdered(iterable);
    var keyed = isKeyed(iterable);
    var h = ordered ? 1 : 0;
    var size = iterable.__iterate(
      keyed ?
        ordered ?
          function(v, k)  { h = 31 * h + hashMerge(hash(v), hash(k)) | 0; } :
          function(v, k)  { h = h + hashMerge(hash(v), hash(k)) | 0; } :
        ordered ?
          function(v ) { h = 31 * h + hash(v) | 0; } :
          function(v ) { h = h + hash(v) | 0; }
    );
    return murmurHashOfSize(size, h);
  }

  function murmurHashOfSize(size, h) {
    h = imul(h, 0xCC9E2D51);
    h = imul(h << 15 | h >>> -15, 0x1B873593);
    h = imul(h << 13 | h >>> -13, 5);
    h = (h + 0xE6546B64 | 0) ^ size;
    h = imul(h ^ h >>> 16, 0x85EBCA6B);
    h = imul(h ^ h >>> 13, 0xC2B2AE35);
    h = smi(h ^ h >>> 16);
    return h;
  }

  function hashMerge(a, b) {
    return a ^ b + 0x9E3779B9 + (a << 6) + (a >> 2) | 0; // int
  }

  var Immutable = {

    Iterable: Iterable,

    Seq: Seq,
    Collection: Collection,
    Map: Map,
    OrderedMap: OrderedMap,
    List: List,
    Stack: Stack,
    Set: Set,
    OrderedSet: OrderedSet,

    Record: Record,
    Range: Range,
    Repeat: Repeat,

    is: is,
    fromJS: fromJS

  };

  return Immutable;

}));

/***/ }),

/***/ "JQOU":
/*!**************************************************************!*\
  !*** ./node_modules/@jupyterlab/coreutils/lib/pageconfig.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(process) {
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const minimist_1 = __importDefault(__webpack_require__(/*! minimist */ "8v/U"));
const path_1 = __webpack_require__(/*! ./path */ "Dt/b");
const url_1 = __webpack_require__(/*! ./url */ "huh6");
/**
 * The namespace for Page Config functions.
 */
var PageConfig;
(function (PageConfig) {
    /**
     * Get global configuration data for the Jupyter application.
     *
     * @param name - The name of the configuration option.
     *
     * @returns The config value or an empty string if not found.
     *
     * #### Notes
     * All values are treated as strings.
     * For browser based applications, it is assumed that the page HTML
     * includes a script tag with the id `jupyter-config-data` containing the
     * configuration as valid JSON.  In order to support the classic Notebook,
     * we fall back on checking for `body` data of the given `name`.
     *
     * For node applications, it is assumed that the process was launched
     * with a `--jupyter-config-data` option pointing to a JSON settings
     * file.
     */
    function getOption(name) {
        if (configData) {
            return configData[name] || Private.getBodyData(name);
        }
        configData = Object.create(null);
        let found = false;
        // Use script tag if available.
        if (typeof document !== 'undefined') {
            const el = document.getElementById('jupyter-config-data');
            if (el) {
                configData = JSON.parse(el.textContent || '');
                found = true;
            }
        }
        // Otherwise use CLI if given.
        if (!found && typeof process !== 'undefined') {
            try {
                const cli = minimist_1.default(process.argv.slice(2));
                const path = __webpack_require__(/*! path */ "33yf");
                let fullPath = '';
                if ('jupyter-config-data' in cli) {
                    fullPath = path.resolve(cli['jupyter-config-data']);
                }
                else if ('JUPYTER_CONFIG_DATA' in process.env) {
                    fullPath = path.resolve(process.env['JUPYTER_CONFIG_DATA']);
                }
                if (fullPath) {
                    /* tslint:disable */
                    // Force Webpack to ignore this require.
                    configData = eval('require')(fullPath);
                    /* tslint:enable */
                }
            }
            catch (e) {
                console.error(e);
            }
        }
        if (!coreutils_1.JSONExt.isObject(configData)) {
            configData = Object.create(null);
        }
        else {
            for (let key in configData) {
                // Quote characters are escaped, unescape them.
                configData[key] = String(configData[key])
                    .split('&#39;')
                    .join('"');
            }
        }
        return configData[name] || '';
    }
    PageConfig.getOption = getOption;
    /**
     * Set global configuration data for the Jupyter application.
     *
     * @param name - The name of the configuration option.
     * @param value - The value to set the option to.
     *
     * @returns The last config value or an empty string if it doesn't exist.
     */
    function setOption(name, value) {
        const last = getOption(name);
        configData[name] = value;
        return last;
    }
    PageConfig.setOption = setOption;
    /**
     * Get the base url for a Jupyter application, or the base url of the page.
     */
    function getBaseUrl() {
        return url_1.URLExt.normalize(getOption('baseUrl') || '/');
    }
    PageConfig.getBaseUrl = getBaseUrl;
    /**
     * Get the tree url for a JupyterLab application.
     *
     * @param options - The tree URL construction options.
     */
    function getTreeUrl(options = {}) {
        const base = getBaseUrl();
        const tree = getOption('treeUrl');
        const defaultWorkspace = getOption('defaultWorkspace');
        const workspaces = getOption('workspacesUrl');
        const workspace = getOption('workspace');
        return !!options.workspace && workspace && workspace !== defaultWorkspace
            ? url_1.URLExt.join(base, workspaces, path_1.PathExt.basename(workspace), 'tree')
            : url_1.URLExt.join(base, tree);
    }
    PageConfig.getTreeUrl = getTreeUrl;
    /**
     * Get the base websocket url for a Jupyter application, or an empty string.
     */
    function getWsUrl(baseUrl) {
        let wsUrl = getOption('wsUrl');
        if (!wsUrl) {
            baseUrl = baseUrl ? url_1.URLExt.normalize(baseUrl) : getBaseUrl();
            if (baseUrl.indexOf('http') !== 0) {
                return '';
            }
            wsUrl = 'ws' + baseUrl.slice(4);
        }
        return url_1.URLExt.normalize(wsUrl);
    }
    PageConfig.getWsUrl = getWsUrl;
    /**
     * Get the authorization token for a Jupyter application.
     */
    function getToken() {
        return getOption('token') || Private.getBodyData('jupyterApiToken');
    }
    PageConfig.getToken = getToken;
    /**
     * Get the Notebook version info [major, minor, patch].
     */
    function getNotebookVersion() {
        const notebookVersion = getOption('notebookVersion');
        if (notebookVersion === '') {
            return [0, 0, 0];
        }
        return JSON.parse(notebookVersion);
    }
    PageConfig.getNotebookVersion = getNotebookVersion;
    /**
     * Private page config data for the Jupyter application.
     */
    let configData = null;
})(PageConfig = exports.PageConfig || (exports.PageConfig = {}));
/**
 * A namespace for module private data.
 */
var Private;
(function (Private) {
    /**
     * Get a url-encoded item from `body.data` and decode it
     * We should never have any encoded URLs anywhere else in code
     * until we are building an actual request.
     */
    function getBodyData(key) {
        if (typeof document === 'undefined' || !document.body) {
            return '';
        }
        let val = document.body.dataset[key];
        if (typeof val === 'undefined') {
            return '';
        }
        return decodeURIComponent(val);
    }
    Private.getBodyData = getBodyData;
})(Private || (Private = {}));

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../process/browser.js */ "8oxB")))

/***/ }),

/***/ "JReR":
/*!***************************************************!*\
  !*** ./node_modules/mdi-react/LinkVariantIcon.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var LinkVariantIcon = function LinkVariantIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M10.59,13.41C11,13.8 11,14.44 10.59,14.83C10.2,15.22 9.56,15.22 9.17,14.83C7.22,12.88 7.22,9.71 9.17,7.76V7.76L12.71,4.22C14.66,2.27 17.83,2.27 19.78,4.22C21.73,6.17 21.73,9.34 19.78,11.29L18.29,12.78C18.3,11.96 18.17,11.14 17.89,10.36L18.36,9.88C19.54,8.71 19.54,6.81 18.36,5.64C17.19,4.46 15.29,4.46 14.12,5.64L10.59,9.17C9.41,10.34 9.41,12.24 10.59,13.41M13.41,9.17C13.8,8.78 14.44,8.78 14.83,9.17C16.78,11.12 16.78,14.29 14.83,16.24V16.24L11.29,19.78C9.34,21.73 6.17,21.73 4.22,19.78C2.27,17.83 2.27,14.66 4.22,12.71L5.71,11.22C5.7,12.04 5.83,12.86 6.11,13.65L5.64,14.12C4.46,15.29 4.46,17.19 5.64,18.36C6.81,19.54 8.71,19.54 9.88,18.36L13.41,14.83C14.59,13.66 14.59,11.76 13.41,10.59C13,10.2 13,9.56 13.41,9.17Z' })
  );
};

module.exports = LinkVariantIcon;


/***/ }),

/***/ "JSQU":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_hashSet.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var nativeCreate = __webpack_require__(/*! ./_nativeCreate */ "YESw");

/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';

/**
 * 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;
}

module.exports = hashSet;


/***/ }),

/***/ "JSoe":
/*!*****************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/terminal/index.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(__webpack_require__(/*! ./manager */ "NL6Z"));
__export(__webpack_require__(/*! ./terminal */ "lV/m"));


/***/ }),

/***/ "JTzB":
/*!*************************************************!*\
  !*** ./node_modules/lodash/_baseIsArguments.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseGetTag = __webpack_require__(/*! ./_baseGetTag */ "NykK"),
    isObjectLike = __webpack_require__(/*! ./isObjectLike */ "ExA7");

/** `Object#toString` result references. */
var argsTag = '[object Arguments]';

/**
 * 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;
}

module.exports = baseIsArguments;


/***/ }),

/***/ "JVSJ":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/bs.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


function translate(number, withoutSuffix, key) {
    var result = number + ' ';
    switch (key) {
        case 'ss':
            if (number === 1) {
                result += 'sekunda';
            } else if (number === 2 || number === 3 || number === 4) {
                result += 'sekunde';
            } else {
                result += 'sekundi';
            }
            return result;
        case 'm':
            return withoutSuffix ? 'jedna minuta' : 'jedne minute';
        case 'mm':
            if (number === 1) {
                result += 'minuta';
            } else if (number === 2 || number === 3 || number === 4) {
                result += 'minute';
            } else {
                result += 'minuta';
            }
            return result;
        case 'h':
            return withoutSuffix ? 'jedan sat' : 'jednog sata';
        case 'hh':
            if (number === 1) {
                result += 'sat';
            } else if (number === 2 || number === 3 || number === 4) {
                result += 'sata';
            } else {
                result += 'sati';
            }
            return result;
        case 'dd':
            if (number === 1) {
                result += 'dan';
            } else {
                result += 'dana';
            }
            return result;
        case 'MM':
            if (number === 1) {
                result += 'mjesec';
            } else if (number === 2 || number === 3 || number === 4) {
                result += 'mjeseca';
            } else {
                result += 'mjeseci';
            }
            return result;
        case 'yy':
            if (number === 1) {
                result += 'godina';
            } else if (number === 2 || number === 3 || number === 4) {
                result += 'godine';
            } else {
                result += 'godina';
            }
            return result;
    }
}

var bs = moment.defineLocale('bs', {
    months : 'januar_februar_mart_april_maj_juni_juli_august_septembar_oktobar_novembar_decembar'.split('_'),
    monthsShort : 'jan._feb._mar._apr._maj._jun._jul._aug._sep._okt._nov._dec.'.split('_'),
    monthsParseExact: true,
    weekdays : 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'),
    weekdaysShort : 'ned._pon._uto._sri._čet._pet._sub.'.split('_'),
    weekdaysMin : 'ne_po_ut_sr_če_pe_su'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'H:mm',
        LTS : 'H:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D. MMMM YYYY',
        LLL : 'D. MMMM YYYY H:mm',
        LLLL : 'dddd, D. MMMM YYYY H:mm'
    },
    calendar : {
        sameDay  : '[danas u] LT',
        nextDay  : '[sutra u] LT',
        nextWeek : function () {
            switch (this.day()) {
                case 0:
                    return '[u] [nedjelju] [u] LT';
                case 3:
                    return '[u] [srijedu] [u] LT';
                case 6:
                    return '[u] [subotu] [u] LT';
                case 1:
                case 2:
                case 4:
                case 5:
                    return '[u] dddd [u] LT';
            }
        },
        lastDay  : '[jučer u] LT',
        lastWeek : function () {
            switch (this.day()) {
                case 0:
                case 3:
                    return '[prošlu] dddd [u] LT';
                case 6:
                    return '[prošle] [subote] [u] LT';
                case 1:
                case 2:
                case 4:
                case 5:
                    return '[prošli] dddd [u] LT';
            }
        },
        sameElse : 'L'
    },
    relativeTime : {
        future : 'za %s',
        past   : 'prije %s',
        s      : 'par sekundi',
        ss     : translate,
        m      : translate,
        mm     : translate,
        h      : translate,
        hh     : translate,
        d      : 'dan',
        dd     : translate,
        M      : 'mjesec',
        MM     : translate,
        y      : 'godinu',
        yy     : translate
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return bs;

})));


/***/ }),

/***/ "JbBM":
/*!********************************************************************!*\
  !*** ./node_modules/core-js/library/fn/object/set-prototype-of.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(/*! ../../modules/es6.object.set-prototype-of */ "Hfiw");
module.exports = __webpack_require__(/*! ../../modules/_core */ "WEpk").Object.setPrototypeOf;


/***/ }),

/***/ "JcQb":
/*!***********************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/contextmenu.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __assign = (this && this.__assign) || Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
        s = arguments[i];
        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
            t[p] = s[p];
    }
    return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
var disposable_1 = __webpack_require__(/*! @phosphor/disposable */ "uNUc");
var domutils_1 = __webpack_require__(/*! @phosphor/domutils */ "XWTc");
var menu_1 = __webpack_require__(/*! ./menu */ "Jrp+");
/**
 * An object which implements a universal context menu.
 *
 * #### Notes
 * The items shown in the context menu are determined by CSS selector
 * matching against the DOM hierarchy at the site of the mouse click.
 * This is similar in concept to how keyboard shortcuts are matched
 * in the command registry.
 */
var ContextMenu = (function () {
    /**
     * Construct a new context menu.
     *
     * @param options - The options for initializing the menu.
     */
    function ContextMenu(options) {
        this._idTick = 0;
        this._items = [];
        this.menu = new menu_1.Menu(options);
    }
    /**
     * Add an item to the context menu.
     *
     * @param options - The options for creating the item.
     *
     * @returns A disposable which will remove the item from the menu.
     */
    ContextMenu.prototype.addItem = function (options) {
        var _this = this;
        // Create an item from the given options.
        var item = Private.createItem(options, this._idTick++);
        // Add the item to the internal array.
        this._items.push(item);
        // Return a disposable which will remove the item.
        return new disposable_1.DisposableDelegate(function () {
            algorithm_1.ArrayExt.removeFirstOf(_this._items, item);
        });
    };
    /**
     * Open the context menu in response to a `'contextmenu'` event.
     *
     * @param event - The `'contextmenu'` event of interest.
     *
     * @returns `true` if the menu was opened, or `false` if no items
     *   matched the event and the menu was not opened.
     *
     * #### Notes
     * This method will populate the context menu with items which match
     * the propagation path of the event, then open the menu at the mouse
     * position indicated by the event.
     */
    ContextMenu.prototype.open = function (event) {
        var _this = this;
        // Clear the current contents of the context menu.
        this.menu.clearItems();
        // Bail early if there are no items to match.
        if (this._items.length === 0) {
            return false;
        }
        // Find the matching items for the event.
        var items = Private.matchItems(this._items, event);
        // Bail if there are no matching items.
        if (!items || items.length === 0) {
            return false;
        }
        // Add the filtered items to the menu.
        algorithm_1.each(items, function (item) { _this.menu.addItem(item); });
        // Open the context menu at the current mouse position.
        this.menu.open(event.clientX, event.clientY);
        // Indicate success.
        return true;
    };
    return ContextMenu;
}());
exports.ContextMenu = ContextMenu;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * Create a normalized context menu item from an options object.
     */
    function createItem(options, id) {
        var selector = validateSelector(options.selector);
        var rank = options.rank !== undefined ? options.rank : Infinity;
        return __assign({}, options, { selector: selector, rank: rank, id: id });
    }
    Private.createItem = createItem;
    /**
     * Find the items which match a context menu event.
     *
     * The results are sorted by DOM level, specificity, and rank.
     */
    function matchItems(items, event) {
        // Look up the target of the event.
        var target = event.target;
        // Bail if there is no target.
        if (!target) {
            return null;
        }
        // Look up the current target of the event.
        var currentTarget = event.currentTarget;
        // Bail if there is no current target.
        if (!currentTarget) {
            return null;
        }
        // There are some third party libraries that cause the `target` to
        // be detached from the DOM before Phosphor can process the event.
        // If that happens, search for a new target node by point. If that
        // node is still dangling, bail.
        if (!currentTarget.contains(target)) {
            target = document.elementFromPoint(event.clientX, event.clientY);
            if (!target || !currentTarget.contains(target)) {
                return null;
            }
        }
        // Set up the result array.
        var result = [];
        // Copy the items array to allow in-place modification.
        var availableItems = items.slice();
        // Walk up the DOM hierarchy searching for matches.
        while (target !== null) {
            // Set up the match array for this DOM level.
            var matches = [];
            // Search the remaining items for matches.
            for (var i = 0, n = availableItems.length; i < n; ++i) {
                // Fetch the item.
                var item = availableItems[i];
                // Skip items which are already consumed.
                if (!item) {
                    continue;
                }
                // Skip items which do not match the element.
                if (!domutils_1.Selector.matches(target, item.selector)) {
                    continue;
                }
                // Add the matched item to the result for this DOM level.
                matches.push(item);
                // Mark the item as consumed.
                availableItems[i] = null;
            }
            // Sort the matches for this level and add them to the results.
            if (matches.length !== 0) {
                matches.sort(itemCmp);
                result.push.apply(result, matches);
            }
            // Stop searching at the limits of the DOM range.
            if (target === currentTarget) {
                break;
            }
            // Step to the parent DOM level.
            target = target.parentElement;
        }
        // Return the matched and sorted results.
        return result;
    }
    Private.matchItems = matchItems;
    /**
     * Validate the selector for a menu item.
     *
     * This returns the validated selector, or throws if the selector is
     * invalid or contains commas.
     */
    function validateSelector(selector) {
        if (selector.indexOf(',') !== -1) {
            throw new Error("Selector cannot contain commas: " + selector);
        }
        if (!domutils_1.Selector.isValid(selector)) {
            throw new Error("Invalid selector: " + selector);
        }
        return selector;
    }
    /**
     * A sort comparison function for a context menu item.
     */
    function itemCmp(a, b) {
        // Sort first based on selector specificity.
        var s1 = domutils_1.Selector.calculateSpecificity(a.selector);
        var s2 = domutils_1.Selector.calculateSpecificity(b.selector);
        if (s1 !== s2) {
            return s2 - s1;
        }
        // If specificities are equal, sort based on rank.
        var r1 = a.rank;
        var r2 = b.rank;
        if (r1 !== r2) {
            return r1 < r2 ? -1 : 1; // Infinity-safe
        }
        // When all else fails, sort by item id.
        return a.id - b.id;
    }
})(Private || (Private = {}));


/***/ }),

/***/ "Jcck":
/*!***********************************************!*\
  !*** ./node_modules/source-map/lib/base64.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/* -*- Mode: js; js-indent-level: 2; -*- */
/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');

/**
 * Encode an integer in the range of 0 to 63 to a single base 64 digit.
 */
exports.encode = function (number) {
  if (0 <= number && number < intToCharMap.length) {
    return intToCharMap[number];
  }
  throw new TypeError("Must be between 0 and 63: " + number);
};

/**
 * Decode a single base 64 character code digit to an integer. Returns -1 on
 * failure.
 */
exports.decode = function (charCode) {
  var bigA = 65;     // 'A'
  var bigZ = 90;     // 'Z'

  var littleA = 97;  // 'a'
  var littleZ = 122; // 'z'

  var zero = 48;     // '0'
  var nine = 57;     // '9'

  var plus = 43;     // '+'
  var slash = 47;    // '/'

  var littleOffset = 26;
  var numberOffset = 52;

  // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  if (bigA <= charCode && charCode <= bigZ) {
    return (charCode - bigA);
  }

  // 26 - 51: abcdefghijklmnopqrstuvwxyz
  if (littleA <= charCode && charCode <= littleZ) {
    return (charCode - littleA + littleOffset);
  }

  // 52 - 61: 0123456789
  if (zero <= charCode && charCode <= nine) {
    return (charCode - zero + numberOffset);
  }

  // 62: +
  if (charCode == plus) {
    return 62;
  }

  // 63: /
  if (charCode == slash) {
    return 63;
  }

  // Invalid base64 digit.
  return -1;
};


/***/ }),

/***/ "Jes0":
/*!**********************************************************!*\
  !*** ./node_modules/core-js/library/modules/_defined.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

// 7.2.1 RequireObjectCoercible(argument)
module.exports = function (it) {
  if (it == undefined) throw TypeError("Can't call method on  " + it);
  return it;
};


/***/ }),

/***/ "JmEZ":
/*!******************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeHistogram2dIcon.js ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeHistogram2dIcon = function TraceTypeHistogram2dIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement('path', { fill: 'none', d: 'M0 0h46v46H0z' }),
        _react2.default.createElement('path', { fill: '#1d9bfb', d: 'M32 20h6v6h-6zm-12-6h6v6h-6zm-6 6h6v6h-6zm0 12h6v6h-6zm6 0h6v6h-6zm12 0h6v6h-6zm-6-12h6v6h-6z' }),
        _react2.default.createElement('path', { fill: '#25fdfc', d: 'M26 14h6v6h-6zm6 0h6v6h-6zm-12 6h6v6h-6zM8 20h6v6H8z' }),
        _react2.default.createElement('path', { fill: '#1d9bfb', d: 'M14 14h6v6h-6z' }),
        _react2.default.createElement('path', { fill: '#25fdfc', d: 'M8 14h6v6H8z' }),
        _react2.default.createElement('path', { fill: '#1d9bfb', d: 'M26 26h6v6h-6zM8 26h6v6H8z' }),
        _react2.default.createElement('path', { fill: '#25fdfc', d: 'M20 26h6v6h-6zm12 0h6v6h-6zm-18 0h6v6h-6z' }),
        _react2.default.createElement('path', { fill: '#1d9bfb', d: 'M26 8h6v6h-6zM8 8h6v6H8z' }),
        _react2.default.createElement('path', { fill: '#25fdfc', d: 'M20 8h6v6h-6zm12 0h6v6h-6zM14 8h6v6h-6zM8 32h6v6H8zm18 0h6v6h-6z' }),
        _react2.default.createElement('circle', { cx: '29', cy: '29', r: '2', fill: '#fff' }),
        _react2.default.createElement('circle', { cx: '17', cy: '23', r: '2', fill: '#fff' }),
        _react2.default.createElement('circle', { cx: '17', cy: '35', r: '2', fill: '#fff' }),
        _react2.default.createElement('circle', { cx: '29', cy: '23', r: '2', fill: '#fff' }),
        _react2.default.createElement('circle', { cx: '23', cy: '17', r: '2', fill: '#fff' }),
        _react2.default.createElement('path', { fill: 'none', stroke: '#fff', d: 'M29 11l1.5-1.5M29 11l-1.5-1.5M29 11l1.5 1.5M29 11l-1.5 1.5M35 23l1.5-1.5M35 23l-1.5-1.5M35 23l1.5 1.5M35 23l-1.5 1.5M23 35l1.5-1.5M23 35l-1.5-1.5M23 35l1.5 1.5M23 35l-1.5 1.5', strokeLinecap: 'round', strokeLinejoin: 'round' })
    );
};

exports.default = TraceTypeHistogram2dIcon;

/***/ }),

/***/ "Jrif":
/*!******************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeCandlestickIcon.js ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeCandlestickIcon = function TraceTypeCandlestickIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement('path', { fill: 'none', d: 'M0 0h46v46H0z' }),
        _react2.default.createElement('path', { fill: 'none', stroke: '#1d9bfb', d: 'M23 24v16M11 12v24M35 6v29', strokeMiterlimit: '10', strokeWidth: '2' }),
        _react2.default.createElement('path', { fill: '#25fdfc', d: 'M8 19h6v10H8z' }),
        _react2.default.createElement('path', { d: 'M13 20v8H9v-8h4m2-2H7v12h8V18z', fill: '#1d9bfb' }),
        _react2.default.createElement('path', { fill: '#25fdfc', d: 'M20 27h6v4h-6z' }),
        _react2.default.createElement('path', { d: 'M25 28v2h-4v-2h4m2-2h-8v6h8v-6z', fill: '#1d9bfb' }),
        _react2.default.createElement('path', { fill: '#25fdfc', d: 'M32 15h6v14h-6z' }),
        _react2.default.createElement('path', { d: 'M37 16v12h-4V16h4m2-2h-8v16h8V14z', fill: '#1d9bfb' })
    );
};

exports.default = TraceTypeCandlestickIcon;

/***/ }),

/***/ "Jrp+":
/*!****************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/menu.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
        s = arguments[i];
        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
            t[p] = s[p];
    }
    return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
var commands_1 = __webpack_require__(/*! @phosphor/commands */ "5TpB");
var coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
var domutils_1 = __webpack_require__(/*! @phosphor/domutils */ "XWTc");
var keyboard_1 = __webpack_require__(/*! @phosphor/keyboard */ "djTv");
var messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
var signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
var virtualdom_1 = __webpack_require__(/*! @phosphor/virtualdom */ "Gqu+");
var widget_1 = __webpack_require__(/*! ./widget */ "FmDU");
/**
 * A widget which displays items as a canonical menu.
 */
var Menu = (function (_super) {
    __extends(Menu, _super);
    /**
     * Construct a new menu.
     *
     * @param options - The options for initializing the menu.
     */
    function Menu(options) {
        var _this = _super.call(this, { node: Private.createNode() }) || this;
        _this._childIndex = -1;
        _this._activeIndex = -1;
        _this._openTimerID = 0;
        _this._closeTimerID = 0;
        _this._items = [];
        _this._childMenu = null;
        _this._parentMenu = null;
        _this._aboutToClose = new signaling_1.Signal(_this);
        _this._menuRequested = new signaling_1.Signal(_this);
        _this.addClass('p-Menu');
        _this.setFlag(widget_1.Widget.Flag.DisallowLayout);
        _this.commands = options.commands;
        _this.renderer = options.renderer || Menu.defaultRenderer;
        return _this;
    }
    /**
     * Dispose of the resources held by the menu.
     */
    Menu.prototype.dispose = function () {
        this.close();
        this._items.length = 0;
        _super.prototype.dispose.call(this);
    };
    Object.defineProperty(Menu.prototype, "aboutToClose", {
        /**
         * A signal emitted just before the menu is closed.
         *
         * #### Notes
         * This signal is emitted when the menu receives a `'close-request'`
         * message, just before it removes itself from the DOM.
         *
         * This signal is not emitted if the menu is already detached from
         * the DOM when it receives the `'close-request'` message.
         */
        get: function () {
            return this._aboutToClose;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Menu.prototype, "menuRequested", {
        /**
         * A signal emitted when a new menu is requested by the user.
         *
         * #### Notes
         * This signal is emitted whenever the user presses the right or left
         * arrow keys, and a submenu cannot be opened or closed in response.
         *
         * This signal is useful when implementing menu bars in order to open
         * the next or previous menu in response to a user key press.
         *
         * This signal is only emitted for the root menu in a hierarchy.
         */
        get: function () {
            return this._menuRequested;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Menu.prototype, "parentMenu", {
        /**
         * The parent menu of the menu.
         *
         * #### Notes
         * This is `null` unless the menu is an open submenu.
         */
        get: function () {
            return this._parentMenu;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Menu.prototype, "childMenu", {
        /**
         * The child menu of the menu.
         *
         * #### Notes
         * This is `null` unless the menu has an open submenu.
         */
        get: function () {
            return this._childMenu;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Menu.prototype, "rootMenu", {
        /**
         * The root menu of the menu hierarchy.
         */
        get: function () {
            var menu = this;
            while (menu._parentMenu) {
                menu = menu._parentMenu;
            }
            return menu;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Menu.prototype, "leafMenu", {
        /**
         * The leaf menu of the menu hierarchy.
         */
        get: function () {
            var menu = this;
            while (menu._childMenu) {
                menu = menu._childMenu;
            }
            return menu;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Menu.prototype, "contentNode", {
        /**
         * The menu content node.
         *
         * #### Notes
         * This is the node which holds the menu item nodes.
         *
         * Modifying this node directly can lead to undefined behavior.
         */
        get: function () {
            return this.node.getElementsByClassName('p-Menu-content')[0];
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Menu.prototype, "activeItem", {
        /**
         * Get the currently active menu item.
         */
        get: function () {
            return this._items[this._activeIndex] || null;
        },
        /**
         * Set the currently active menu item.
         *
         * #### Notes
         * If the item cannot be activated, the item will be set to `null`.
         */
        set: function (value) {
            this.activeIndex = value ? this._items.indexOf(value) : -1;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Menu.prototype, "activeIndex", {
        /**
         * Get the index of the currently active menu item.
         *
         * #### Notes
         * This will be `-1` if no menu item is active.
         */
        get: function () {
            return this._activeIndex;
        },
        /**
         * Set the index of the currently active menu item.
         *
         * #### Notes
         * If the item cannot be activated, the index will be set to `-1`.
         */
        set: function (value) {
            // Adjust the value for an out of range index.
            if (value < 0 || value >= this._items.length) {
                value = -1;
            }
            // Ensure the item can be activated.
            if (value !== -1 && !Private.canActivate(this._items[value])) {
                value = -1;
            }
            // Bail if the index will not change.
            if (this._activeIndex === value) {
                return;
            }
            // Update the active index.
            this._activeIndex = value;
            // schedule an update of the items.
            this.update();
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Menu.prototype, "items", {
        /**
         * A read-only array of the menu items in the menu.
         */
        get: function () {
            return this._items;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Activate the next selectable item in the menu.
     *
     * #### Notes
     * If no item is selectable, the index will be set to `-1`.
     */
    Menu.prototype.activateNextItem = function () {
        var n = this._items.length;
        var ai = this._activeIndex;
        var start = ai < n - 1 ? ai + 1 : 0;
        var stop = start === 0 ? n - 1 : start - 1;
        this.activeIndex = algorithm_1.ArrayExt.findFirstIndex(this._items, Private.canActivate, start, stop);
    };
    /**
     * Activate the previous selectable item in the menu.
     *
     * #### Notes
     * If no item is selectable, the index will be set to `-1`.
     */
    Menu.prototype.activatePreviousItem = function () {
        var n = this._items.length;
        var ai = this._activeIndex;
        var start = ai <= 0 ? n - 1 : ai - 1;
        var stop = start === n - 1 ? 0 : start + 1;
        this.activeIndex = algorithm_1.ArrayExt.findLastIndex(this._items, Private.canActivate, start, stop);
    };
    /**
     * Trigger the active menu item.
     *
     * #### Notes
     * If the active item is a submenu, it will be opened and the first
     * item will be activated.
     *
     * If the active item is a command, the command will be executed.
     *
     * If the menu is not attached, this is a no-op.
     *
     * If there is no active item, this is a no-op.
     */
    Menu.prototype.triggerActiveItem = function () {
        // Bail if the menu is not attached.
        if (!this.isAttached) {
            return;
        }
        // Bail if there is no active item.
        var item = this.activeItem;
        if (!item) {
            return;
        }
        // Cancel the pending timers.
        this._cancelOpenTimer();
        this._cancelCloseTimer();
        // If the item is a submenu, open it.
        if (item.type === 'submenu') {
            this._openChildMenu(true);
            return;
        }
        // Close the root menu before executing the command.
        this.rootMenu.close();
        // Execute the command for the item.
        var command = item.command, args = item.args;
        if (this.commands.isEnabled(command, args)) {
            this.commands.execute(command, args);
        }
        else {
            console.log("Command '" + command + "' is disabled.");
        }
    };
    /**
     * Add a menu item to the end of the menu.
     *
     * @param options - The options for creating the menu item.
     *
     * @returns The menu item added to the menu.
     */
    Menu.prototype.addItem = function (options) {
        return this.insertItem(this._items.length, options);
    };
    /**
     * Insert a menu item into the menu at the specified index.
     *
     * @param index - The index at which to insert the item.
     *
     * @param options - The options for creating the menu item.
     *
     * @returns The menu item added to the menu.
     *
     * #### Notes
     * The index will be clamped to the bounds of the items.
     */
    Menu.prototype.insertItem = function (index, options) {
        // Close the menu if it's attached.
        if (this.isAttached) {
            this.close();
        }
        // Reset the active index.
        this.activeIndex = -1;
        // Clamp the insert index to the array bounds.
        var i = Math.max(0, Math.min(index, this._items.length));
        // Create the item for the options.
        var item = Private.createItem(this, options);
        // Insert the item into the array.
        algorithm_1.ArrayExt.insert(this._items, i, item);
        // Schedule an update of the items.
        this.update();
        // Return the item added to the menu.
        return item;
    };
    /**
     * Remove an item from the menu.
     *
     * @param item - The item to remove from the menu.
     *
     * #### Notes
     * This is a no-op if the item is not in the menu.
     */
    Menu.prototype.removeItem = function (item) {
        this.removeItemAt(this._items.indexOf(item));
    };
    /**
     * Remove the item at a given index from the menu.
     *
     * @param index - The index of the item to remove.
     *
     * #### Notes
     * This is a no-op if the index is out of range.
     */
    Menu.prototype.removeItemAt = function (index) {
        // Close the menu if it's attached.
        if (this.isAttached) {
            this.close();
        }
        // Reset the active index.
        this.activeIndex = -1;
        // Remove the item from the array.
        var item = algorithm_1.ArrayExt.removeAt(this._items, index);
        // Bail if the index is out of range.
        if (!item) {
            return;
        }
        // Schedule an update of the items.
        this.update();
    };
    /**
     * Remove all menu items from the menu.
     */
    Menu.prototype.clearItems = function () {
        // Close the menu if it's attached.
        if (this.isAttached) {
            this.close();
        }
        // Reset the active index.
        this.activeIndex = -1;
        // Bail if there is nothing to remove.
        if (this._items.length === 0) {
            return;
        }
        // Clear the items.
        this._items.length = 0;
        // Schedule an update of the items.
        this.update();
    };
    /**
     * Open the menu at the specified location.
     *
     * @param x - The client X coordinate of the menu location.
     *
     * @param y - The client Y coordinate of the menu location.
     *
     * @param options - The additional options for opening the menu.
     *
     * #### Notes
     * The menu will be opened at the given location unless it will not
     * fully fit on the screen. If it will not fit, it will be adjusted
     * to fit naturally on the screen.
     *
     * This is a no-op if the menu is already attached to the DOM.
     */
    Menu.prototype.open = function (x, y, options) {
        if (options === void 0) { options = {}; }
        // Bail early if the menu is already attached.
        if (this.isAttached) {
            return;
        }
        // Extract the position options.
        var forceX = options.forceX || false;
        var forceY = options.forceY || false;
        // Open the menu as a root menu.
        Private.openRootMenu(this, x, y, forceX, forceY);
        // Activate the menu to accept keyboard input.
        this.activate();
    };
    /**
     * Handle the DOM events for the menu.
     *
     * @param event - The DOM event sent to the menu.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the menu's DOM nodes. It should
     * not be called directly by user code.
     */
    Menu.prototype.handleEvent = function (event) {
        switch (event.type) {
            case 'keydown':
                this._evtKeyDown(event);
                break;
            case 'mouseup':
                this._evtMouseUp(event);
                break;
            case 'mousemove':
                this._evtMouseMove(event);
                break;
            case 'mouseenter':
                this._evtMouseEnter(event);
                break;
            case 'mouseleave':
                this._evtMouseLeave(event);
                break;
            case 'mousedown':
                this._evtMouseDown(event);
                break;
            case 'contextmenu':
                event.preventDefault();
                event.stopPropagation();
                break;
        }
    };
    /**
     * A message handler invoked on a `'before-attach'` message.
     */
    Menu.prototype.onBeforeAttach = function (msg) {
        this.node.addEventListener('keydown', this);
        this.node.addEventListener('mouseup', this);
        this.node.addEventListener('mousemove', this);
        this.node.addEventListener('mouseenter', this);
        this.node.addEventListener('mouseleave', this);
        this.node.addEventListener('contextmenu', this);
        document.addEventListener('mousedown', this, true);
    };
    /**
     * A message handler invoked on an `'after-detach'` message.
     */
    Menu.prototype.onAfterDetach = function (msg) {
        this.node.removeEventListener('keydown', this);
        this.node.removeEventListener('mouseup', this);
        this.node.removeEventListener('mousemove', this);
        this.node.removeEventListener('mouseenter', this);
        this.node.removeEventListener('mouseleave', this);
        this.node.removeEventListener('contextmenu', this);
        document.removeEventListener('mousedown', this, true);
    };
    /**
     * A message handler invoked on an `'activate-request'` message.
     */
    Menu.prototype.onActivateRequest = function (msg) {
        if (this.isAttached) {
            this.node.focus();
        }
    };
    /**
     * A message handler invoked on an `'update-request'` message.
     */
    Menu.prototype.onUpdateRequest = function (msg) {
        var items = this._items;
        var renderer = this.renderer;
        var activeIndex = this._activeIndex;
        var collapsedFlags = Private.computeCollapsed(items);
        var content = new Array(items.length);
        for (var i = 0, n = items.length; i < n; ++i) {
            var item = items[i];
            var active = i === activeIndex;
            var collapsed = collapsedFlags[i];
            content[i] = renderer.renderItem({ item: item, active: active, collapsed: collapsed });
        }
        virtualdom_1.VirtualDOM.render(content, this.contentNode);
    };
    /**
     * A message handler invoked on a `'close-request'` message.
     */
    Menu.prototype.onCloseRequest = function (msg) {
        // Cancel the pending timers.
        this._cancelOpenTimer();
        this._cancelCloseTimer();
        // Reset the active index.
        this.activeIndex = -1;
        // Close any open child menu.
        var childMenu = this._childMenu;
        if (childMenu) {
            this._childIndex = -1;
            this._childMenu = null;
            childMenu._parentMenu = null;
            childMenu.close();
        }
        // Remove this menu from its parent and activate the parent.
        var parentMenu = this._parentMenu;
        if (parentMenu) {
            this._parentMenu = null;
            parentMenu._childIndex = -1;
            parentMenu._childMenu = null;
            parentMenu.activate();
        }
        // Emit the `aboutToClose` signal if the menu is attached.
        if (this.isAttached) {
            this._aboutToClose.emit(undefined);
        }
        // Finish closing the menu.
        _super.prototype.onCloseRequest.call(this, msg);
    };
    /**
     * Handle the `'keydown'` event for the menu.
     *
     * #### Notes
     * This listener is attached to the menu node.
     */
    Menu.prototype._evtKeyDown = function (event) {
        // A menu handles all keydown events.
        event.preventDefault();
        event.stopPropagation();
        // Fetch the key code for the event.
        var kc = event.keyCode;
        // Enter
        if (kc === 13) {
            this.triggerActiveItem();
            return;
        }
        // Escape
        if (kc === 27) {
            this.close();
            return;
        }
        // Left Arrow
        if (kc === 37) {
            if (this._parentMenu) {
                this.close();
            }
            else {
                this._menuRequested.emit('previous');
            }
            return;
        }
        // Up Arrow
        if (kc === 38) {
            this.activatePreviousItem();
            return;
        }
        // Right Arrow
        if (kc === 39) {
            var item = this.activeItem;
            if (item && item.type === 'submenu') {
                this.triggerActiveItem();
            }
            else {
                this.rootMenu._menuRequested.emit('next');
            }
            return;
        }
        // Down Arrow
        if (kc === 40) {
            this.activateNextItem();
            return;
        }
        // Get the pressed key character.
        var key = keyboard_1.getKeyboardLayout().keyForKeydownEvent(event);
        // Bail if the key is not valid.
        if (!key) {
            return;
        }
        // Search for the next best matching mnemonic item.
        var start = this._activeIndex + 1;
        var result = Private.findMnemonic(this._items, key, start);
        // Handle the requested mnemonic based on the search results.
        // If exactly one mnemonic is matched, that item is triggered.
        // Otherwise, the next mnemonic is activated if available,
        // followed by the auto mnemonic if available.
        if (result.index !== -1 && !result.multiple) {
            this.activeIndex = result.index;
            this.triggerActiveItem();
        }
        else if (result.index !== -1) {
            this.activeIndex = result.index;
        }
        else if (result.auto !== -1) {
            this.activeIndex = result.auto;
        }
    };
    /**
     * Handle the `'mouseup'` event for the menu.
     *
     * #### Notes
     * This listener is attached to the menu node.
     */
    Menu.prototype._evtMouseUp = function (event) {
        if (event.button !== 0) {
            return;
        }
        event.preventDefault();
        event.stopPropagation();
        this.triggerActiveItem();
    };
    /**
     * Handle the `'mousemove'` event for the menu.
     *
     * #### Notes
     * This listener is attached to the menu node.
     */
    Menu.prototype._evtMouseMove = function (event) {
        // Hit test the item nodes for the item under the mouse.
        var index = algorithm_1.ArrayExt.findFirstIndex(this.contentNode.children, function (node) {
            return domutils_1.ElementExt.hitTest(node, event.clientX, event.clientY);
        });
        // Bail early if the mouse is already over the active index.
        if (index === this._activeIndex) {
            return;
        }
        // Update and coerce the active index.
        this.activeIndex = index;
        index = this.activeIndex;
        // If the index is the current child index, cancel the timers.
        if (index === this._childIndex) {
            this._cancelOpenTimer();
            this._cancelCloseTimer();
            return;
        }
        // If a child menu is currently open, start the close timer.
        if (this._childIndex !== -1) {
            this._startCloseTimer();
        }
        // Cancel the open timer to give a full delay for opening.
        this._cancelOpenTimer();
        // Bail if the active item is not a valid submenu item.
        var item = this.activeItem;
        if (!item || item.type !== 'submenu' || !item.submenu) {
            return;
        }
        // Start the open timer to open the active item submenu.
        this._startOpenTimer();
    };
    /**
     * Handle the `'mouseenter'` event for the menu.
     *
     * #### Notes
     * This listener is attached to the menu node.
     */
    Menu.prototype._evtMouseEnter = function (event) {
        // Synchronize the active ancestor items.
        for (var menu = this._parentMenu; menu; menu = menu._parentMenu) {
            menu._cancelOpenTimer();
            menu._cancelCloseTimer();
            menu.activeIndex = menu._childIndex;
        }
    };
    /**
     * Handle the `'mouseleave'` event for the menu.
     *
     * #### Notes
     * This listener is attached to the menu node.
     */
    Menu.prototype._evtMouseLeave = function (event) {
        // Cancel any pending submenu opening.
        this._cancelOpenTimer();
        // If there is no open child menu, just reset the active index.
        if (!this._childMenu) {
            this.activeIndex = -1;
            return;
        }
        // If the mouse is over the child menu, cancel the close timer.
        var clientX = event.clientX, clientY = event.clientY;
        if (domutils_1.ElementExt.hitTest(this._childMenu.node, clientX, clientY)) {
            this._cancelCloseTimer();
            return;
        }
        // Otherwise, reset the active index and start the close timer.
        this.activeIndex = -1;
        this._startCloseTimer();
    };
    /**
     * Handle the `'mousedown'` event for the menu.
     *
     * #### Notes
     * This listener is attached to the document node.
     */
    Menu.prototype._evtMouseDown = function (event) {
        // Bail if the menu is not a root menu.
        if (this._parentMenu) {
            return;
        }
        // The mouse button which is pressed is irrelevant. If the press
        // is not on a menu, the entire hierarchy is closed and the event
        // is allowed to propagate. This allows other code to act on the
        // event, such as focusing the clicked element.
        if (Private.hitTestMenus(this, event.clientX, event.clientY)) {
            event.preventDefault();
            event.stopPropagation();
        }
        else {
            this.close();
        }
    };
    /**
     * Open the child menu at the active index immediately.
     *
     * If a different child menu is already open, it will be closed,
     * even if the active item is not a valid submenu.
     */
    Menu.prototype._openChildMenu = function (activateFirst) {
        if (activateFirst === void 0) { activateFirst = false; }
        // If the item is not a valid submenu, close the child menu.
        var item = this.activeItem;
        if (!item || item.type !== 'submenu' || !item.submenu) {
            this._closeChildMenu();
            return;
        }
        // Do nothing if the child menu will not change.
        var submenu = item.submenu;
        if (submenu === this._childMenu) {
            return;
        }
        // Ensure the current child menu is closed.
        this._closeChildMenu();
        // Update the private child state.
        this._childMenu = submenu;
        this._childIndex = this._activeIndex;
        // Set the parent menu reference for the child.
        submenu._parentMenu = this;
        // Ensure the menu is updated and lookup the item node.
        messaging_1.MessageLoop.sendMessage(this, widget_1.Widget.Msg.UpdateRequest);
        var itemNode = this.contentNode.children[this._activeIndex];
        // Open the submenu at the active node.
        Private.openSubmenu(submenu, itemNode);
        // Activate the first item if desired.
        if (activateFirst) {
            submenu.activeIndex = -1;
            submenu.activateNextItem();
        }
        // Activate the child menu.
        submenu.activate();
    };
    /**
     * Close the child menu immediately.
     *
     * This is a no-op if a child menu is not open.
     */
    Menu.prototype._closeChildMenu = function () {
        if (this._childMenu) {
            this._childMenu.close();
        }
    };
    /**
     * Start the open timer, unless it is already pending.
     */
    Menu.prototype._startOpenTimer = function () {
        var _this = this;
        if (this._openTimerID === 0) {
            this._openTimerID = setTimeout(function () {
                _this._openTimerID = 0;
                _this._openChildMenu();
            }, Private.TIMER_DELAY);
        }
    };
    /**
     * Start the close timer, unless it is already pending.
     */
    Menu.prototype._startCloseTimer = function () {
        var _this = this;
        if (this._closeTimerID === 0) {
            this._closeTimerID = setTimeout(function () {
                _this._closeTimerID = 0;
                _this._closeChildMenu();
            }, Private.TIMER_DELAY);
        }
    };
    /**
     * Cancel the open timer, if the timer is pending.
     */
    Menu.prototype._cancelOpenTimer = function () {
        if (this._openTimerID !== 0) {
            clearTimeout(this._openTimerID);
            this._openTimerID = 0;
        }
    };
    /**
     * Cancel the close timer, if the timer is pending.
     */
    Menu.prototype._cancelCloseTimer = function () {
        if (this._closeTimerID !== 0) {
            clearTimeout(this._closeTimerID);
            this._closeTimerID = 0;
        }
    };
    return Menu;
}(widget_1.Widget));
exports.Menu = Menu;
/**
 * The namespace for the `Menu` class statics.
 */
(function (Menu) {
    /**
     * The default implementation of `IRenderer`.
     *
     * #### Notes
     * Subclasses are free to reimplement rendering methods as needed.
     */
    var Renderer = (function () {
        /**
         * Construct a new renderer.
         */
        function Renderer() {
        }
        /**
         * Render the virtual element for a menu item.
         *
         * @param data - The data to use for rendering the item.
         *
         * @returns A virtual element representing the item.
         */
        Renderer.prototype.renderItem = function (data) {
            var className = this.createItemClass(data);
            var dataset = this.createItemDataset(data);
            return (virtualdom_1.h.li({ className: className, dataset: dataset }, this.renderIcon(data), this.renderLabel(data), this.renderShortcut(data), this.renderSubmenu(data)));
        };
        /**
         * Render the icon element for a menu item.
         *
         * @param data - The data to use for rendering the icon.
         *
         * @returns A virtual element representing the item icon.
         */
        Renderer.prototype.renderIcon = function (data) {
            var className = this.createIconClass(data);
            return virtualdom_1.h.div({ className: className }, data.item.iconLabel);
        };
        /**
         * Render the label element for a menu item.
         *
         * @param data - The data to use for rendering the label.
         *
         * @returns A virtual element representing the item label.
         */
        Renderer.prototype.renderLabel = function (data) {
            var content = this.formatLabel(data);
            return virtualdom_1.h.div({ className: 'p-Menu-itemLabel' }, content);
        };
        /**
         * Render the shortcut element for a menu item.
         *
         * @param data - The data to use for rendering the shortcut.
         *
         * @returns A virtual element representing the item shortcut.
         */
        Renderer.prototype.renderShortcut = function (data) {
            var content = this.formatShortcut(data);
            return virtualdom_1.h.div({ className: 'p-Menu-itemShortcut' }, content);
        };
        /**
         * Render the submenu icon element for a menu item.
         *
         * @param data - The data to use for rendering the submenu icon.
         *
         * @returns A virtual element representing the submenu icon.
         */
        Renderer.prototype.renderSubmenu = function (data) {
            return virtualdom_1.h.div({ className: 'p-Menu-itemSubmenuIcon' });
        };
        /**
         * Create the class name for the menu item.
         *
         * @param data - The data to use for the class name.
         *
         * @returns The full class name for the menu item.
         */
        Renderer.prototype.createItemClass = function (data) {
            // Setup the initial class name.
            var name = 'p-Menu-item';
            // Add the boolean state classes.
            if (!data.item.isEnabled) {
                name += ' p-mod-disabled';
            }
            if (data.item.isToggled) {
                name += ' p-mod-toggled';
            }
            if (!data.item.isVisible) {
                name += ' p-mod-hidden';
            }
            if (data.active) {
                name += ' p-mod-active';
            }
            if (data.collapsed) {
                name += ' p-mod-collapsed';
            }
            // Add the extra class.
            var extra = data.item.className;
            if (extra) {
                name += " " + extra;
            }
            // Return the complete class name.
            return name;
        };
        /**
         * Create the dataset for the menu item.
         *
         * @param data - The data to use for creating the dataset.
         *
         * @returns The dataset for the menu item.
         */
        Renderer.prototype.createItemDataset = function (data) {
            var result;
            var _a = data.item, type = _a.type, command = _a.command, dataset = _a.dataset;
            if (type === 'command') {
                result = __assign({}, dataset, { type: type, command: command });
            }
            else {
                result = __assign({}, dataset, { type: type });
            }
            return result;
        };
        /**
         * Create the class name for the menu item icon.
         *
         * @param data - The data to use for the class name.
         *
         * @returns The full class name for the item icon.
         */
        Renderer.prototype.createIconClass = function (data) {
            var name = 'p-Menu-itemIcon';
            var extra = data.item.iconClass;
            return extra ? name + " " + extra : name;
        };
        /**
         * Create the render content for the label node.
         *
         * @param data - The data to use for the label content.
         *
         * @returns The content to add to the label node.
         */
        Renderer.prototype.formatLabel = function (data) {
            // Fetch the label text and mnemonic index.
            var _a = data.item, label = _a.label, mnemonic = _a.mnemonic;
            // If the index is out of range, do not modify the label.
            if (mnemonic < 0 || mnemonic >= label.length) {
                return label;
            }
            // Split the label into parts.
            var prefix = label.slice(0, mnemonic);
            var suffix = label.slice(mnemonic + 1);
            var char = label[mnemonic];
            // Wrap the mnemonic character in a span.
            var span = virtualdom_1.h.span({ className: 'p-Menu-itemMnemonic' }, char);
            // Return the content parts.
            return [prefix, span, suffix];
        };
        /**
         * Create the render content for the shortcut node.
         *
         * @param data - The data to use for the shortcut content.
         *
         * @returns The content to add to the shortcut node.
         */
        Renderer.prototype.formatShortcut = function (data) {
            var kb = data.item.keyBinding;
            return kb ? kb.keys.map(Private.formatKeystroke).join(', ') : null;
        };
        return Renderer;
    }());
    Menu.Renderer = Renderer;
    /**
     * The default `Renderer` instance.
     */
    Menu.defaultRenderer = new Renderer();
})(Menu = exports.Menu || (exports.Menu = {}));
exports.Menu = Menu;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * The ms delay for opening and closing a submenu.
     */
    Private.TIMER_DELAY = 300;
    /**
     * The horizontal pixel overlap for an open submenu.
     */
    Private.SUBMENU_OVERLAP = 3;
    /**
     * Create the DOM node for a menu.
     */
    function createNode() {
        var node = document.createElement('div');
        var content = document.createElement('ul');
        content.className = 'p-Menu-content';
        node.appendChild(content);
        node.tabIndex = -1;
        return node;
    }
    Private.createNode = createNode;
    /**
     * Test whether a menu item can be activated.
     */
    function canActivate(item) {
        return item.type !== 'separator' && item.isEnabled && item.isVisible;
    }
    Private.canActivate = canActivate;
    /**
     * Create a new menu item for an owner menu.
     */
    function createItem(owner, options) {
        return new MenuItem(owner.commands, options);
    }
    Private.createItem = createItem;
    /**
     * Format a keystroke for display on the local system.
     */
    function formatKeystroke(keystroke) {
        var mods = '';
        var parts = commands_1.CommandRegistry.parseKeystroke(keystroke);
        if (domutils_1.Platform.IS_MAC) {
            if (parts.ctrl) {
                mods += '\u2303 ';
            }
            if (parts.alt) {
                mods += '\u2325 ';
            }
            if (parts.shift) {
                mods += '\u21E7 ';
            }
            if (parts.cmd) {
                mods += '\u2318 ';
            }
        }
        else {
            if (parts.ctrl) {
                mods += 'Ctrl+';
            }
            if (parts.alt) {
                mods += 'Alt+';
            }
            if (parts.shift) {
                mods += 'Shift+';
            }
        }
        return mods + parts.key;
    }
    Private.formatKeystroke = formatKeystroke;
    /**
     * Hit test a menu hierarchy starting at the given root.
     */
    function hitTestMenus(menu, x, y) {
        for (var temp = menu; temp; temp = temp.childMenu) {
            if (domutils_1.ElementExt.hitTest(temp.node, x, y)) {
                return true;
            }
        }
        return false;
    }
    Private.hitTestMenus = hitTestMenus;
    /**
     * Compute which extra separator items should be collapsed.
     */
    function computeCollapsed(items) {
        // Allocate the return array and fill it with `false`.
        var result = new Array(items.length);
        algorithm_1.ArrayExt.fill(result, false);
        // Collapse the leading separators.
        var k1 = 0;
        var n = items.length;
        for (; k1 < n; ++k1) {
            var item = items[k1];
            if (!item.isVisible) {
                continue;
            }
            if (item.type !== 'separator') {
                break;
            }
            result[k1] = true;
        }
        // Hide the trailing separators.
        var k2 = n - 1;
        for (; k2 >= 0; --k2) {
            var item = items[k2];
            if (!item.isVisible) {
                continue;
            }
            if (item.type !== 'separator') {
                break;
            }
            result[k2] = true;
        }
        // Hide the remaining consecutive separators.
        var hide = false;
        while (++k1 < k2) {
            var item = items[k1];
            if (!item.isVisible) {
                continue;
            }
            if (item.type !== 'separator') {
                hide = false;
            }
            else if (hide) {
                result[k1] = true;
            }
            else {
                hide = true;
            }
        }
        // Return the resulting flags.
        return result;
    }
    Private.computeCollapsed = computeCollapsed;
    /**
     * Open a menu as a root menu at the target location.
     */
    function openRootMenu(menu, x, y, forceX, forceY) {
        // Ensure the menu is updated before attaching and measuring.
        messaging_1.MessageLoop.sendMessage(menu, widget_1.Widget.Msg.UpdateRequest);
        // Get the current position and size of the main viewport.
        var px = window.pageXOffset;
        var py = window.pageYOffset;
        var cw = document.documentElement.clientWidth;
        var ch = document.documentElement.clientHeight;
        // Compute the maximum allowed height for the menu.
        var maxHeight = ch - (forceY ? y : 0);
        // Fetch common variables.
        var node = menu.node;
        var style = node.style;
        // Clear the menu geometry and prepare it for measuring.
        style.top = '';
        style.left = '';
        style.width = '';
        style.height = '';
        style.visibility = 'hidden';
        style.maxHeight = maxHeight + "px";
        // Attach the menu to the document.
        widget_1.Widget.attach(menu, document.body);
        // Measure the size of the menu.
        var _a = node.getBoundingClientRect(), width = _a.width, height = _a.height;
        // Adjust the X position of the menu to fit on-screen.
        if (!forceX && (x + width > px + cw)) {
            x = px + cw - width;
        }
        // Adjust the Y position of the menu to fit on-screen.
        if (!forceY && (y + height > py + ch)) {
            if (y > py + ch) {
                y = py + ch - height;
            }
            else {
                y = y - height;
            }
        }
        // Update the position of the menu to the computed position.
        style.top = Math.max(0, y) + "px";
        style.left = Math.max(0, x) + "px";
        // Finally, make the menu visible on the screen.
        style.visibility = '';
    }
    Private.openRootMenu = openRootMenu;
    /**
     * Open a menu as a submenu using an item node for positioning.
     */
    function openSubmenu(submenu, itemNode) {
        // Ensure the menu is updated before opening.
        messaging_1.MessageLoop.sendMessage(submenu, widget_1.Widget.Msg.UpdateRequest);
        // Get the current position and size of the main viewport.
        var px = window.pageXOffset;
        var py = window.pageYOffset;
        var cw = document.documentElement.clientWidth;
        var ch = document.documentElement.clientHeight;
        // Compute the maximum allowed height for the menu.
        var maxHeight = ch;
        // Fetch common variables.
        var node = submenu.node;
        var style = node.style;
        // Clear the menu geometry and prepare it for measuring.
        style.top = '';
        style.left = '';
        style.width = '';
        style.height = '';
        style.visibility = 'hidden';
        style.maxHeight = maxHeight + "px";
        // Attach the menu to the document.
        widget_1.Widget.attach(submenu, document.body);
        // Measure the size of the menu.
        var _a = node.getBoundingClientRect(), width = _a.width, height = _a.height;
        // Compute the box sizing for the menu.
        var box = domutils_1.ElementExt.boxSizing(submenu.node);
        // Get the bounding rect for the target item node.
        var itemRect = itemNode.getBoundingClientRect();
        // Compute the target X position.
        var x = itemRect.right - Private.SUBMENU_OVERLAP;
        // Adjust the X position to fit on the screen.
        if (x + width > px + cw) {
            x = itemRect.left + Private.SUBMENU_OVERLAP - width;
        }
        // Compute the target Y position.
        var y = itemRect.top - box.borderTop - box.paddingTop;
        // Adjust the Y position to fit on the screen.
        if (y + height > py + ch) {
            y = itemRect.bottom + box.borderBottom + box.paddingBottom - height;
        }
        // Update the position of the menu to the computed position.
        style.top = Math.max(0, y) + "px";
        style.left = Math.max(0, x) + "px";
        // Finally, make the menu visible on the screen.
        style.visibility = '';
    }
    Private.openSubmenu = openSubmenu;
    /**
     * Find the best matching mnemonic item.
     *
     * The search starts at the given index and wraps around.
     */
    function findMnemonic(items, key, start) {
        // Setup the result variables.
        var index = -1;
        var auto = -1;
        var multiple = false;
        // Normalize the key to upper case.
        var upperKey = key.toUpperCase();
        // Search the items from the given start index.
        for (var i = 0, n = items.length; i < n; ++i) {
            // Compute the wrapped index.
            var k = (i + start) % n;
            // Lookup the item
            var item = items[k];
            // Ignore items which cannot be activated.
            if (!canActivate(item)) {
                continue;
            }
            // Ignore items with an empty label.
            var label = item.label;
            if (label.length === 0) {
                continue;
            }
            // Lookup the mnemonic index for the label.
            var mn = item.mnemonic;
            // Handle a valid mnemonic index.
            if (mn >= 0 && mn < label.length) {
                if (label[mn].toUpperCase() === upperKey) {
                    if (index === -1) {
                        index = k;
                    }
                    else {
                        multiple = true;
                    }
                }
                continue;
            }
            // Finally, handle the auto index if possible.
            if (auto === -1 && label[0].toUpperCase() === upperKey) {
                auto = k;
            }
        }
        // Return the search results.
        return { index: index, multiple: multiple, auto: auto };
    }
    Private.findMnemonic = findMnemonic;
    /**
     * A concrete implementation of `Menu.IItem`.
     */
    var MenuItem = (function () {
        /**
         * Construct a new menu item.
         */
        function MenuItem(commands, options) {
            this._commands = commands;
            this.type = options.type || 'command';
            this.command = options.command || '';
            this.args = options.args || coreutils_1.JSONExt.emptyObject;
            this.submenu = options.submenu || null;
        }
        Object.defineProperty(MenuItem.prototype, "label", {
            /**
             * The display label for the menu item.
             */
            get: function () {
                if (this.type === 'command') {
                    return this._commands.label(this.command, this.args);
                }
                if (this.type === 'submenu' && this.submenu) {
                    return this.submenu.title.label;
                }
                return '';
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MenuItem.prototype, "mnemonic", {
            /**
             * The mnemonic index for the menu item.
             */
            get: function () {
                if (this.type === 'command') {
                    return this._commands.mnemonic(this.command, this.args);
                }
                if (this.type === 'submenu' && this.submenu) {
                    return this.submenu.title.mnemonic;
                }
                return -1;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MenuItem.prototype, "icon", {
            /**
             * @deprecated Use `iconClass` instead.
             */
            get: function () {
                return this.iconClass;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MenuItem.prototype, "iconClass", {
            /**
             * The icon class for the menu item.
             */
            get: function () {
                if (this.type === 'command') {
                    return this._commands.iconClass(this.command, this.args);
                }
                if (this.type === 'submenu' && this.submenu) {
                    return this.submenu.title.iconClass;
                }
                return '';
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MenuItem.prototype, "iconLabel", {
            /**
             * The icon label for the menu item.
             */
            get: function () {
                if (this.type === 'command') {
                    return this._commands.iconLabel(this.command, this.args);
                }
                if (this.type === 'submenu' && this.submenu) {
                    return this.submenu.title.iconLabel;
                }
                return '';
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MenuItem.prototype, "caption", {
            /**
             * The display caption for the menu item.
             */
            get: function () {
                if (this.type === 'command') {
                    return this._commands.caption(this.command, this.args);
                }
                if (this.type === 'submenu' && this.submenu) {
                    return this.submenu.title.caption;
                }
                return '';
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MenuItem.prototype, "className", {
            /**
             * The extra class name for the menu item.
             */
            get: function () {
                if (this.type === 'command') {
                    return this._commands.className(this.command, this.args);
                }
                if (this.type === 'submenu' && this.submenu) {
                    return this.submenu.title.className;
                }
                return '';
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MenuItem.prototype, "dataset", {
            /**
             * The dataset for the menu item.
             */
            get: function () {
                if (this.type === 'command') {
                    return this._commands.dataset(this.command, this.args);
                }
                if (this.type === 'submenu' && this.submenu) {
                    return this.submenu.title.dataset;
                }
                return {};
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MenuItem.prototype, "isEnabled", {
            /**
             * Whether the menu item is enabled.
             */
            get: function () {
                if (this.type === 'command') {
                    return this._commands.isEnabled(this.command, this.args);
                }
                if (this.type === 'submenu') {
                    return this.submenu !== null;
                }
                return true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MenuItem.prototype, "isToggled", {
            /**
             * Whether the menu item is toggled.
             */
            get: function () {
                if (this.type === 'command') {
                    return this._commands.isToggled(this.command, this.args);
                }
                return false;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MenuItem.prototype, "isVisible", {
            /**
             * Whether the menu item is visible.
             */
            get: function () {
                if (this.type === 'command') {
                    return this._commands.isVisible(this.command, this.args);
                }
                if (this.type === 'submenu') {
                    return this.submenu !== null;
                }
                return true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MenuItem.prototype, "keyBinding", {
            /**
             * The key binding for the menu item.
             */
            get: function () {
                if (this.type === 'command') {
                    var _a = this, command_1 = _a.command, args_1 = _a.args;
                    return algorithm_1.ArrayExt.findLastValue(this._commands.keyBindings, function (kb) {
                        return kb.command === command_1 && coreutils_1.JSONExt.deepEqual(kb.args, args_1);
                    }) || null;
                }
                return null;
            },
            enumerable: true,
            configurable: true
        });
        return MenuItem;
    }());
})(Private || (Private = {}));


/***/ }),

/***/ "Juji":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_baseHasIn.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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);
}

module.exports = baseHasIn;


/***/ }),

/***/ "Jv9w":
/*!***********************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/splitlayout.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
var domutils_1 = __webpack_require__(/*! @phosphor/domutils */ "XWTc");
var messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
var properties_1 = __webpack_require__(/*! @phosphor/properties */ "3kwb");
var boxengine_1 = __webpack_require__(/*! ./boxengine */ "ovjo");
var layout_1 = __webpack_require__(/*! ./layout */ "yNaG");
var panellayout_1 = __webpack_require__(/*! ./panellayout */ "HWBy");
var widget_1 = __webpack_require__(/*! ./widget */ "FmDU");
/**
 * A layout which arranges its widgets into resizable sections.
 */
var SplitLayout = (function (_super) {
    __extends(SplitLayout, _super);
    /**
     * Construct a new split layout.
     *
     * @param options - The options for initializing the layout.
     */
    function SplitLayout(options) {
        var _this = _super.call(this) || this;
        _this._fixed = 0;
        _this._spacing = 4;
        _this._dirty = false;
        _this._hasNormedSizes = false;
        _this._sizers = [];
        _this._items = [];
        _this._handles = [];
        _this._box = null;
        _this._alignment = 'start';
        _this._orientation = 'horizontal';
        _this.renderer = options.renderer;
        if (options.orientation !== undefined) {
            _this._orientation = options.orientation;
        }
        if (options.alignment !== undefined) {
            _this._alignment = options.alignment;
        }
        if (options.spacing !== undefined) {
            _this._spacing = Private.clampSpacing(options.spacing);
        }
        return _this;
    }
    /**
     * Dispose of the resources held by the layout.
     */
    SplitLayout.prototype.dispose = function () {
        // Dispose of the layout items.
        algorithm_1.each(this._items, function (item) { item.dispose(); });
        // Clear the layout state.
        this._box = null;
        this._items.length = 0;
        this._sizers.length = 0;
        this._handles.length = 0;
        // Dispose of the rest of the layout.
        _super.prototype.dispose.call(this);
    };
    Object.defineProperty(SplitLayout.prototype, "orientation", {
        /**
         * Get the layout orientation for the split layout.
         */
        get: function () {
            return this._orientation;
        },
        /**
         * Set the layout orientation for the split layout.
         */
        set: function (value) {
            if (this._orientation === value) {
                return;
            }
            this._orientation = value;
            if (!this.parent) {
                return;
            }
            this.parent.dataset['orientation'] = value;
            this.parent.fit();
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(SplitLayout.prototype, "alignment", {
        /**
         * Get the content alignment for the split layout.
         *
         * #### Notes
         * This is the alignment of the widgets in the layout direction.
         *
         * The alignment has no effect if the widgets can expand  to fill the
         * entire split layout.
         */
        get: function () {
            return this._alignment;
        },
        /**
         * Set the content alignment for the split layout.
         *
         * #### Notes
         * This is the alignment of the widgets in the layout direction.
         *
         * The alignment has no effect if the widgets can expand  to fill the
         * entire split layout.
         */
        set: function (value) {
            if (this._alignment === value) {
                return;
            }
            this._alignment = value;
            if (!this.parent) {
                return;
            }
            this.parent.dataset['alignment'] = value;
            this.parent.update();
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(SplitLayout.prototype, "spacing", {
        /**
         * Get the inter-element spacing for the split layout.
         */
        get: function () {
            return this._spacing;
        },
        /**
         * Set the inter-element spacing for the split layout.
         */
        set: function (value) {
            value = Private.clampSpacing(value);
            if (this._spacing === value) {
                return;
            }
            this._spacing = value;
            if (!this.parent) {
                return;
            }
            this.parent.fit();
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(SplitLayout.prototype, "handles", {
        /**
         * A read-only array of the split handles in the layout.
         */
        get: function () {
            return this._handles;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Get the relative sizes of the widgets in the layout.
     *
     * @returns A new array of the relative sizes of the widgets.
     *
     * #### Notes
     * The returned sizes reflect the sizes of the widgets normalized
     * relative to their siblings.
     *
     * This method **does not** measure the DOM nodes.
     */
    SplitLayout.prototype.relativeSizes = function () {
        return Private.normalize(this._sizers.map(function (sizer) { return sizer.size; }));
    };
    /**
     * Set the relative sizes for the widgets in the layout.
     *
     * @param sizes - The relative sizes for the widgets in the panel.
     *
     * #### Notes
     * Extra values are ignored, too few will yield an undefined layout.
     *
     * The actual geometry of the DOM nodes is updated asynchronously.
     */
    SplitLayout.prototype.setRelativeSizes = function (sizes) {
        // Copy the sizes and pad with zeros as needed.
        var n = this._sizers.length;
        var temp = sizes.slice(0, n);
        while (temp.length < n) {
            temp.push(0);
        }
        // Normalize the padded sizes.
        var normed = Private.normalize(temp);
        // Apply the normalized sizes to the sizers.
        for (var i = 0; i < n; ++i) {
            var sizer = this._sizers[i];
            sizer.sizeHint = normed[i];
            sizer.size = normed[i];
        }
        // Set the flag indicating the sizes are normalized.
        this._hasNormedSizes = true;
        // Trigger an update of the parent widget.
        if (this.parent) {
            this.parent.update();
        }
    };
    /**
     * Move the offset position of a split handle.
     *
     * @param index - The index of the handle of the interest.
     *
     * @param position - The desired offset position of the handle.
     *
     * #### Notes
     * The position is relative to the offset parent.
     *
     * This will move the handle as close as possible to the desired
     * position. The sibling widgets will be adjusted as necessary.
     */
    SplitLayout.prototype.moveHandle = function (index, position) {
        // Bail if the index is invalid or the handle is hidden.
        var handle = this._handles[index];
        if (!handle || handle.classList.contains('p-mod-hidden')) {
            return;
        }
        // Compute the desired delta movement for the handle.
        var delta;
        if (this._orientation === 'horizontal') {
            delta = position - handle.offsetLeft;
        }
        else {
            delta = position - handle.offsetTop;
        }
        // Bail if there is no handle movement.
        if (delta === 0) {
            return;
        }
        // Prevent widget resizing unless needed.
        for (var _i = 0, _a = this._sizers; _i < _a.length; _i++) {
            var sizer = _a[_i];
            if (sizer.size > 0) {
                sizer.sizeHint = sizer.size;
            }
        }
        // Adjust the sizers to reflect the handle movement.
        boxengine_1.BoxEngine.adjust(this._sizers, index, delta);
        // Update the layout of the widgets.
        if (this.parent) {
            this.parent.update();
        }
    };
    /**
     * Perform layout initialization which requires the parent widget.
     */
    SplitLayout.prototype.init = function () {
        this.parent.dataset['orientation'] = this.orientation;
        this.parent.dataset['alignment'] = this.alignment;
        _super.prototype.init.call(this);
    };
    /**
     * Attach a widget to the parent's DOM node.
     *
     * @param index - The current index of the widget in the layout.
     *
     * @param widget - The widget to attach to the parent.
     *
     * #### Notes
     * This is a reimplementation of the superclass method.
     */
    SplitLayout.prototype.attachWidget = function (index, widget) {
        // Create the item, handle, and sizer for the new widget.
        var item = new layout_1.LayoutItem(widget);
        var handle = Private.createHandle(this.renderer);
        var average = Private.averageSize(this._sizers);
        var sizer = Private.createSizer(average);
        // Insert the item, handle, and sizer into the internal arrays.
        algorithm_1.ArrayExt.insert(this._items, index, item);
        algorithm_1.ArrayExt.insert(this._sizers, index, sizer);
        algorithm_1.ArrayExt.insert(this._handles, index, handle);
        // Send a `'before-attach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.BeforeAttach);
        }
        // Add the widget and handle nodes to the parent.
        this.parent.node.appendChild(widget.node);
        this.parent.node.appendChild(handle);
        // Send an `'after-attach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.AfterAttach);
        }
        // Post a fit request for the parent widget.
        this.parent.fit();
    };
    /**
     * Move a widget in the parent's DOM node.
     *
     * @param fromIndex - The previous index of the widget in the layout.
     *
     * @param toIndex - The current index of the widget in the layout.
     *
     * @param widget - The widget to move in the parent.
     *
     * #### Notes
     * This is a reimplementation of the superclass method.
     */
    SplitLayout.prototype.moveWidget = function (fromIndex, toIndex, widget) {
        // Move the item, sizer, and handle for the widget.
        algorithm_1.ArrayExt.move(this._items, fromIndex, toIndex);
        algorithm_1.ArrayExt.move(this._sizers, fromIndex, toIndex);
        algorithm_1.ArrayExt.move(this._handles, fromIndex, toIndex);
        // Post a fit request to the parent to show/hide last handle.
        this.parent.fit();
    };
    /**
     * Detach a widget from the parent's DOM node.
     *
     * @param index - The previous index of the widget in the layout.
     *
     * @param widget - The widget to detach from the parent.
     *
     * #### Notes
     * This is a reimplementation of the superclass method.
     */
    SplitLayout.prototype.detachWidget = function (index, widget) {
        // Remove the item, handle, and sizer for the widget.
        var item = algorithm_1.ArrayExt.removeAt(this._items, index);
        var handle = algorithm_1.ArrayExt.removeAt(this._handles, index);
        algorithm_1.ArrayExt.removeAt(this._sizers, index);
        // Send a `'before-detach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.BeforeDetach);
        }
        // Remove the widget and handle nodes from the parent.
        this.parent.node.removeChild(widget.node);
        this.parent.node.removeChild(handle);
        // Send an `'after-detach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.AfterDetach);
        }
        // Dispose of the layout item.
        item.dispose();
        // Post a fit request for the parent widget.
        this.parent.fit();
    };
    /**
     * A message handler invoked on a `'before-show'` message.
     */
    SplitLayout.prototype.onBeforeShow = function (msg) {
        _super.prototype.onBeforeShow.call(this, msg);
        this.parent.update();
    };
    /**
     * A message handler invoked on a `'before-attach'` message.
     */
    SplitLayout.prototype.onBeforeAttach = function (msg) {
        _super.prototype.onBeforeAttach.call(this, msg);
        this.parent.fit();
    };
    /**
     * A message handler invoked on a `'child-shown'` message.
     */
    SplitLayout.prototype.onChildShown = function (msg) {
        this.parent.fit();
    };
    /**
     * A message handler invoked on a `'child-hidden'` message.
     */
    SplitLayout.prototype.onChildHidden = function (msg) {
        this.parent.fit();
    };
    /**
     * A message handler invoked on a `'resize'` message.
     */
    SplitLayout.prototype.onResize = function (msg) {
        if (this.parent.isVisible) {
            this._update(msg.width, msg.height);
        }
    };
    /**
     * A message handler invoked on an `'update-request'` message.
     */
    SplitLayout.prototype.onUpdateRequest = function (msg) {
        if (this.parent.isVisible) {
            this._update(-1, -1);
        }
    };
    /**
     * A message handler invoked on a `'fit-request'` message.
     */
    SplitLayout.prototype.onFitRequest = function (msg) {
        if (this.parent.isAttached) {
            this._fit();
        }
    };
    /**
     * Fit the layout to the total size required by the widgets.
     */
    SplitLayout.prototype._fit = function () {
        // Update the handles and track the visible widget count.
        var nVisible = 0;
        var lastHandleIndex = -1;
        for (var i = 0, n = this._items.length; i < n; ++i) {
            if (this._items[i].isHidden) {
                this._handles[i].classList.add('p-mod-hidden');
            }
            else {
                this._handles[i].classList.remove('p-mod-hidden');
                lastHandleIndex = i;
                nVisible++;
            }
        }
        // Hide the handle for the last visible widget.
        if (lastHandleIndex !== -1) {
            this._handles[lastHandleIndex].classList.add('p-mod-hidden');
        }
        // Update the fixed space for the visible items.
        this._fixed = this._spacing * Math.max(0, nVisible - 1);
        // Setup the computed minimum size.
        var horz = this._orientation === 'horizontal';
        var minW = horz ? this._fixed : 0;
        var minH = horz ? 0 : this._fixed;
        // Update the sizers and computed size limits.
        for (var i = 0, n = this._items.length; i < n; ++i) {
            // Fetch the item and corresponding box sizer.
            var item = this._items[i];
            var sizer = this._sizers[i];
            // Prevent resizing unless necessary.
            if (sizer.size > 0) {
                sizer.sizeHint = sizer.size;
            }
            // If the item is hidden, it should consume zero size.
            if (item.isHidden) {
                sizer.minSize = 0;
                sizer.maxSize = 0;
                continue;
            }
            // Update the size limits for the item.
            item.fit();
            // Update the stretch factor.
            sizer.stretch = SplitLayout.getStretch(item.widget);
            // Update the sizer limits and computed min size.
            if (horz) {
                sizer.minSize = item.minWidth;
                sizer.maxSize = item.maxWidth;
                minW += item.minWidth;
                minH = Math.max(minH, item.minHeight);
            }
            else {
                sizer.minSize = item.minHeight;
                sizer.maxSize = item.maxHeight;
                minH += item.minHeight;
                minW = Math.max(minW, item.minWidth);
            }
        }
        // Update the box sizing and add it to the computed min size.
        var box = this._box = domutils_1.ElementExt.boxSizing(this.parent.node);
        minW += box.horizontalSum;
        minH += box.verticalSum;
        // Update the parent's min size constraints.
        var style = this.parent.node.style;
        style.minWidth = minW + "px";
        style.minHeight = minH + "px";
        // Set the dirty flag to ensure only a single update occurs.
        this._dirty = true;
        // Notify the ancestor that it should fit immediately. This may
        // cause a resize of the parent, fulfilling the required update.
        if (this.parent.parent) {
            messaging_1.MessageLoop.sendMessage(this.parent.parent, widget_1.Widget.Msg.FitRequest);
        }
        // If the dirty flag is still set, the parent was not resized.
        // Trigger the required update on the parent widget immediately.
        if (this._dirty) {
            messaging_1.MessageLoop.sendMessage(this.parent, widget_1.Widget.Msg.UpdateRequest);
        }
    };
    /**
     * Update the layout position and size of the widgets.
     *
     * The parent offset dimensions should be `-1` if unknown.
     */
    SplitLayout.prototype._update = function (offsetWidth, offsetHeight) {
        // Clear the dirty flag to indicate the update occurred.
        this._dirty = false;
        // Compute the visible item count.
        var nVisible = 0;
        for (var i = 0, n = this._items.length; i < n; ++i) {
            nVisible += +!this._items[i].isHidden;
        }
        // Bail early if there are no visible items to layout.
        if (nVisible === 0) {
            return;
        }
        // Measure the parent if the offset dimensions are unknown.
        if (offsetWidth < 0) {
            offsetWidth = this.parent.node.offsetWidth;
        }
        if (offsetHeight < 0) {
            offsetHeight = this.parent.node.offsetHeight;
        }
        // Ensure the parent box sizing data is computed.
        if (!this._box) {
            this._box = domutils_1.ElementExt.boxSizing(this.parent.node);
        }
        // Compute the actual layout bounds adjusted for border and padding.
        var top = this._box.paddingTop;
        var left = this._box.paddingLeft;
        var width = offsetWidth - this._box.horizontalSum;
        var height = offsetHeight - this._box.verticalSum;
        // Compute the adjusted layout space.
        var space;
        var horz = this._orientation === 'horizontal';
        if (horz) {
            space = Math.max(0, width - this._fixed);
        }
        else {
            space = Math.max(0, height - this._fixed);
        }
        // Scale the size hints if they are normalized.
        if (this._hasNormedSizes) {
            for (var _i = 0, _a = this._sizers; _i < _a.length; _i++) {
                var sizer = _a[_i];
                sizer.sizeHint *= space;
            }
            this._hasNormedSizes = false;
        }
        // Distribute the layout space to the box sizers.
        var delta = boxengine_1.BoxEngine.calc(this._sizers, space);
        // Set up the variables for justification and alignment offset.
        var extra = 0;
        var offset = 0;
        // Account for alignment if there is extra layout space.
        if (delta > 0) {
            switch (this._alignment) {
                case 'start':
                    break;
                case 'center':
                    extra = 0;
                    offset = delta / 2;
                    break;
                case 'end':
                    extra = 0;
                    offset = delta;
                    break;
                case 'justify':
                    extra = delta / nVisible;
                    offset = 0;
                    break;
                default:
                    throw 'unreachable';
            }
        }
        // Layout the items using the computed box sizes.
        for (var i = 0, n = this._items.length; i < n; ++i) {
            // Fetch the item.
            var item = this._items[i];
            // Ignore hidden items.
            if (item.isHidden) {
                continue;
            }
            // Fetch the computed size for the widget.
            var size = this._sizers[i].size;
            // Fetch the style for the handle.
            var handleStyle = this._handles[i].style;
            // Update the widget and handle, and advance the relevant edge.
            if (horz) {
                item.update(left + offset, top, size + extra, height);
                left += size + extra;
                handleStyle.top = top + "px";
                handleStyle.left = left + offset + "px";
                handleStyle.width = this._spacing + "px";
                handleStyle.height = height + "px";
                left += this._spacing;
            }
            else {
                item.update(left, top + offset, width, size + extra);
                top += size + extra;
                handleStyle.top = top + offset + "px";
                handleStyle.left = left + "px";
                handleStyle.width = width + "px";
                handleStyle.height = this._spacing + "px";
                top += this._spacing;
            }
        }
    };
    return SplitLayout;
}(panellayout_1.PanelLayout));
exports.SplitLayout = SplitLayout;
/**
 * The namespace for the `SplitLayout` class statics.
 */
(function (SplitLayout) {
    /**
     * Get the split layout stretch factor for the given widget.
     *
     * @param widget - The widget of interest.
     *
     * @returns The split layout stretch factor for the widget.
     */
    function getStretch(widget) {
        return Private.stretchProperty.get(widget);
    }
    SplitLayout.getStretch = getStretch;
    /**
     * Set the split layout stretch factor for the given widget.
     *
     * @param widget - The widget of interest.
     *
     * @param value - The value for the stretch factor.
     */
    function setStretch(widget, value) {
        Private.stretchProperty.set(widget, value);
    }
    SplitLayout.setStretch = setStretch;
})(SplitLayout = exports.SplitLayout || (exports.SplitLayout = {}));
exports.SplitLayout = SplitLayout;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * The property descriptor for a widget stretch factor.
     */
    Private.stretchProperty = new properties_1.AttachedProperty({
        name: 'stretch',
        create: function () { return 0; },
        coerce: function (owner, value) { return Math.max(0, Math.floor(value)); },
        changed: onChildSizingChanged
    });
    /**
     * Create a new box sizer with the given size hint.
     */
    function createSizer(size) {
        var sizer = new boxengine_1.BoxSizer();
        sizer.sizeHint = Math.floor(size);
        return sizer;
    }
    Private.createSizer = createSizer;
    /**
     * Create a new split handle node using the given renderer.
     */
    function createHandle(renderer) {
        var handle = renderer.createHandle();
        handle.style.position = 'absolute';
        return handle;
    }
    Private.createHandle = createHandle;
    /**
     * Clamp a spacing value to an integer >= 0.
     */
    function clampSpacing(value) {
        return Math.max(0, Math.floor(value));
    }
    Private.clampSpacing = clampSpacing;
    /**
     * Compute the average size of an array of box sizers.
     */
    function averageSize(sizers) {
        return sizers.reduce(function (v, s) { return v + s.size; }, 0) / sizers.length || 0;
    }
    Private.averageSize = averageSize;
    /**
     * Normalize an array of values.
     */
    function normalize(values) {
        var n = values.length;
        if (n === 0) {
            return [];
        }
        var sum = values.reduce(function (a, b) { return a + Math.abs(b); }, 0);
        return sum === 0 ? values.map(function (v) { return 1 / n; }) : values.map(function (v) { return v / sum; });
    }
    Private.normalize = normalize;
    /**
     * The change handler for the attached sizing properties.
     */
    function onChildSizingChanged(child) {
        if (child.parent && child.parent.layout instanceof SplitLayout) {
            child.parent.fit();
        }
    }
})(Private || (Private = {}));


/***/ }),

/***/ "JvlW":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/lt.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var units = {
    'ss' : 'sekundė_sekundžių_sekundes',
    'm' : 'minutė_minutės_minutę',
    'mm': 'minutės_minučių_minutes',
    'h' : 'valanda_valandos_valandą',
    'hh': 'valandos_valandų_valandas',
    'd' : 'diena_dienos_dieną',
    'dd': 'dienos_dienų_dienas',
    'M' : 'mėnuo_mėnesio_mėnesį',
    'MM': 'mėnesiai_mėnesių_mėnesius',
    'y' : 'metai_metų_metus',
    'yy': 'metai_metų_metus'
};
function translateSeconds(number, withoutSuffix, key, isFuture) {
    if (withoutSuffix) {
        return 'kelios sekundės';
    } else {
        return isFuture ? 'kelių sekundžių' : 'kelias sekundes';
    }
}
function translateSingular(number, withoutSuffix, key, isFuture) {
    return withoutSuffix ? forms(key)[0] : (isFuture ? forms(key)[1] : forms(key)[2]);
}
function special(number) {
    return number % 10 === 0 || (number > 10 && number < 20);
}
function forms(key) {
    return units[key].split('_');
}
function translate(number, withoutSuffix, key, isFuture) {
    var result = number + ' ';
    if (number === 1) {
        return result + translateSingular(number, withoutSuffix, key[0], isFuture);
    } else if (withoutSuffix) {
        return result + (special(number) ? forms(key)[1] : forms(key)[0]);
    } else {
        if (isFuture) {
            return result + forms(key)[1];
        } else {
            return result + (special(number) ? forms(key)[1] : forms(key)[2]);
        }
    }
}
var lt = moment.defineLocale('lt', {
    months : {
        format: 'sausio_vasario_kovo_balandžio_gegužės_birželio_liepos_rugpjūčio_rugsėjo_spalio_lapkričio_gruodžio'.split('_'),
        standalone: 'sausis_vasaris_kovas_balandis_gegužė_birželis_liepa_rugpjūtis_rugsėjis_spalis_lapkritis_gruodis'.split('_'),
        isFormat: /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?|MMMM?(\[[^\[\]]*\]|\s)+D[oD]?/
    },
    monthsShort : 'sau_vas_kov_bal_geg_bir_lie_rgp_rgs_spa_lap_grd'.split('_'),
    weekdays : {
        format: 'sekmadienį_pirmadienį_antradienį_trečiadienį_ketvirtadienį_penktadienį_šeštadienį'.split('_'),
        standalone: 'sekmadienis_pirmadienis_antradienis_trečiadienis_ketvirtadienis_penktadienis_šeštadienis'.split('_'),
        isFormat: /dddd HH:mm/
    },
    weekdaysShort : 'Sek_Pir_Ant_Tre_Ket_Pen_Šeš'.split('_'),
    weekdaysMin : 'S_P_A_T_K_Pn_Š'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'YYYY-MM-DD',
        LL : 'YYYY [m.] MMMM D [d.]',
        LLL : 'YYYY [m.] MMMM D [d.], HH:mm [val.]',
        LLLL : 'YYYY [m.] MMMM D [d.], dddd, HH:mm [val.]',
        l : 'YYYY-MM-DD',
        ll : 'YYYY [m.] MMMM D [d.]',
        lll : 'YYYY [m.] MMMM D [d.], HH:mm [val.]',
        llll : 'YYYY [m.] MMMM D [d.], ddd, HH:mm [val.]'
    },
    calendar : {
        sameDay : '[Šiandien] LT',
        nextDay : '[Rytoj] LT',
        nextWeek : 'dddd LT',
        lastDay : '[Vakar] LT',
        lastWeek : '[Praėjusį] dddd LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'po %s',
        past : 'prieš %s',
        s : translateSeconds,
        ss : translate,
        m : translateSingular,
        mm : translate,
        h : translateSingular,
        hh : translate,
        d : translateSingular,
        dd : translate,
        M : translateSingular,
        MM : translate,
        y : translateSingular,
        yy : translate
    },
    dayOfMonthOrdinalParse: /\d{1,2}-oji/,
    ordinal : function (number) {
        return number + '-oji';
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return lt;

})));


/***/ }),

/***/ "JvmS":
/*!************************************************!*\
  !*** ./node_modules/domutils/lib/traversal.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

var getChildren = exports.getChildren = function(elem){
	return elem.children;
};

var getParent = exports.getParent = function(elem){
	return elem.parent;
};

exports.getSiblings = function(elem){
	var parent = getParent(elem);
	return parent ? getChildren(parent) : [elem];
};

exports.getAttributeValue = function(elem, name){
	return elem.attribs && elem.attribs[name];
};

exports.hasAttrib = function(elem, name){
	return !!elem.attribs && hasOwnProperty.call(elem.attribs, name);
};

exports.getName = function(elem){
	return elem.name;
};


/***/ }),

/***/ "Jxpl":
/*!**********************************************************************!*\
  !*** ./node_modules/react-color/lib/components/material/Material.js ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Material = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _merge = __webpack_require__(/*! lodash/merge */ "QkVN");

var _merge2 = _interopRequireDefault(_merge);

var _color = __webpack_require__(/*! ../../helpers/color */ "p8yl");

var _color2 = _interopRequireDefault(_color);

var _common = __webpack_require__(/*! ../common */ "TM95");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var Material = exports.Material = function Material(_ref) {
  var onChange = _ref.onChange,
      hex = _ref.hex,
      rgb = _ref.rgb,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': {
      material: {
        width: '98px',
        height: '98px',
        padding: '16px',
        fontFamily: 'Roboto'
      },
      HEXwrap: {
        position: 'relative'
      },
      HEXinput: {
        width: '100%',
        marginTop: '12px',
        fontSize: '15px',
        color: '#333',
        padding: '0px',
        border: '0px',
        borderBottom: '2px solid ' + hex,
        outline: 'none',
        height: '30px'
      },
      HEXlabel: {
        position: 'absolute',
        top: '0px',
        left: '0px',
        fontSize: '11px',
        color: '#999999',
        textTransform: 'capitalize'
      },
      Hex: {
        style: {}
      },
      RGBwrap: {
        position: 'relative'
      },
      RGBinput: {
        width: '100%',
        marginTop: '12px',
        fontSize: '15px',
        color: '#333',
        padding: '0px',
        border: '0px',
        borderBottom: '1px solid #eee',
        outline: 'none',
        height: '30px'
      },
      RGBlabel: {
        position: 'absolute',
        top: '0px',
        left: '0px',
        fontSize: '11px',
        color: '#999999',
        textTransform: 'capitalize'
      },
      split: {
        display: 'flex',
        marginRight: '-10px',
        paddingTop: '11px'
      },
      third: {
        flex: '1',
        paddingRight: '10px'
      }
    }
  }, passedStyles));

  var handleChange = function handleChange(data, e) {
    if (data.hex) {
      _color2.default.isValidHex(data.hex) && onChange({
        hex: data.hex,
        source: 'hex'
      }, e);
    } else if (data.r || data.g || data.b) {
      onChange({
        r: data.r || rgb.r,
        g: data.g || rgb.g,
        b: data.b || rgb.b,
        source: 'rgb'
      }, e);
    }
  };

  return _react2.default.createElement(
    _common.Raised,
    { styles: passedStyles },
    _react2.default.createElement(
      'div',
      { style: styles.material, className: 'material-picker ' + className },
      _react2.default.createElement(_common.EditableInput, {
        style: { wrap: styles.HEXwrap, input: styles.HEXinput, label: styles.HEXlabel },
        label: 'hex',
        value: hex,
        onChange: handleChange
      }),
      _react2.default.createElement(
        'div',
        { style: styles.split, className: 'flexbox-fix' },
        _react2.default.createElement(
          'div',
          { style: styles.third },
          _react2.default.createElement(_common.EditableInput, {
            style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
            label: 'r', value: rgb.r,
            onChange: handleChange
          })
        ),
        _react2.default.createElement(
          'div',
          { style: styles.third },
          _react2.default.createElement(_common.EditableInput, {
            style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
            label: 'g',
            value: rgb.g,
            onChange: handleChange
          })
        ),
        _react2.default.createElement(
          'div',
          { style: styles.third },
          _react2.default.createElement(_common.EditableInput, {
            style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
            label: 'b',
            value: rgb.b,
            onChange: handleChange
          })
        )
      )
    )
  );
};

exports.default = (0, _common.ColorWrap)(Material);

/***/ }),

/***/ "K/tc":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/af.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var af = moment.defineLocale('af', {
    months : 'Januarie_Februarie_Maart_April_Mei_Junie_Julie_Augustus_September_Oktober_November_Desember'.split('_'),
    monthsShort : 'Jan_Feb_Mrt_Apr_Mei_Jun_Jul_Aug_Sep_Okt_Nov_Des'.split('_'),
    weekdays : 'Sondag_Maandag_Dinsdag_Woensdag_Donderdag_Vrydag_Saterdag'.split('_'),
    weekdaysShort : 'Son_Maa_Din_Woe_Don_Vry_Sat'.split('_'),
    weekdaysMin : 'So_Ma_Di_Wo_Do_Vr_Sa'.split('_'),
    meridiemParse: /vm|nm/i,
    isPM : function (input) {
        return /^nm$/i.test(input);
    },
    meridiem : function (hours, minutes, isLower) {
        if (hours < 12) {
            return isLower ? 'vm' : 'VM';
        } else {
            return isLower ? 'nm' : 'NM';
        }
    },
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd, D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay : '[Vandag om] LT',
        nextDay : '[Môre om] LT',
        nextWeek : 'dddd [om] LT',
        lastDay : '[Gister om] LT',
        lastWeek : '[Laas] dddd [om] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'oor %s',
        past : '%s gelede',
        s : '\'n paar sekondes',
        ss : '%d sekondes',
        m : '\'n minuut',
        mm : '%d minute',
        h : '\'n uur',
        hh : '%d ure',
        d : '\'n dag',
        dd : '%d dae',
        M : '\'n maand',
        MM : '%d maande',
        y : '\'n jaar',
        yy : '%d jaar'
    },
    dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/,
    ordinal : function (number) {
        return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de'); // Thanks to Joris Röling : https://github.com/jjupiter
    },
    week : {
        dow : 1, // Maandag is die eerste dag van die week.
        doy : 4  // Die week wat die 4de Januarie bevat is die eerste week van die jaar.
    }
});

return af;

})));


/***/ }),

/***/ "K2+N":
/*!****************************************************************!*\
  !*** ./node_modules/@mflevine/jupyterlab_html/style/index.css ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "Hytk");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "K4CH":
/*!****************************************************!*\
  !*** ./node_modules/ua-parser-js/src/ua-parser.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * UAParser.js v0.7.19
 * Lightweight JavaScript-based User-Agent string parser
 * https://github.com/faisalman/ua-parser-js
 *
 * Copyright © 2012-2016 Faisal Salman <fyzlman@gmail.com>
 * Dual licensed under GPLv2 or MIT
 */

(function (window, undefined) {

    'use strict';

    //////////////
    // Constants
    /////////////


    var LIBVERSION  = '0.7.19',
        EMPTY       = '',
        UNKNOWN     = '?',
        FUNC_TYPE   = 'function',
        UNDEF_TYPE  = 'undefined',
        OBJ_TYPE    = 'object',
        STR_TYPE    = 'string',
        MAJOR       = 'major', // deprecated
        MODEL       = 'model',
        NAME        = 'name',
        TYPE        = 'type',
        VENDOR      = 'vendor',
        VERSION     = 'version',
        ARCHITECTURE= 'architecture',
        CONSOLE     = 'console',
        MOBILE      = 'mobile',
        TABLET      = 'tablet',
        SMARTTV     = 'smarttv',
        WEARABLE    = 'wearable',
        EMBEDDED    = 'embedded';


    ///////////
    // Helper
    //////////


    var util = {
        extend : function (regexes, extensions) {
            var margedRegexes = {};
            for (var i in regexes) {
                if (extensions[i] && extensions[i].length % 2 === 0) {
                    margedRegexes[i] = extensions[i].concat(regexes[i]);
                } else {
                    margedRegexes[i] = regexes[i];
                }
            }
            return margedRegexes;
        },
        has : function (str1, str2) {
          if (typeof str1 === "string") {
            return str2.toLowerCase().indexOf(str1.toLowerCase()) !== -1;
          } else {
            return false;
          }
        },
        lowerize : function (str) {
            return str.toLowerCase();
        },
        major : function (version) {
            return typeof(version) === STR_TYPE ? version.replace(/[^\d\.]/g,'').split(".")[0] : undefined;
        },
        trim : function (str) {
          return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
        }
    };


    ///////////////
    // Map helper
    //////////////


    var mapper = {

        rgx : function (ua, arrays) {

            //var result = {},
            var i = 0, j, k, p, q, matches, match;//, args = arguments;

            /*// construct object barebones
            for (p = 0; p < args[1].length; p++) {
                q = args[1][p];
                result[typeof q === OBJ_TYPE ? q[0] : q] = undefined;
            }*/

            // loop through all regexes maps
            while (i < arrays.length && !matches) {

                var regex = arrays[i],       // even sequence (0,2,4,..)
                    props = arrays[i + 1];   // odd sequence (1,3,5,..)
                j = k = 0;

                // try matching uastring with regexes
                while (j < regex.length && !matches) {

                    matches = regex[j++].exec(ua);

                    if (!!matches) {
                        for (p = 0; p < props.length; p++) {
                            match = matches[++k];
                            q = props[p];
                            // check if given property is actually array
                            if (typeof q === OBJ_TYPE && q.length > 0) {
                                if (q.length == 2) {
                                    if (typeof q[1] == FUNC_TYPE) {
                                        // assign modified match
                                        this[q[0]] = q[1].call(this, match);
                                    } else {
                                        // assign given value, ignore regex match
                                        this[q[0]] = q[1];
                                    }
                                } else if (q.length == 3) {
                                    // check whether function or regex
                                    if (typeof q[1] === FUNC_TYPE && !(q[1].exec && q[1].test)) {
                                        // call function (usually string mapper)
                                        this[q[0]] = match ? q[1].call(this, match, q[2]) : undefined;
                                    } else {
                                        // sanitize match using given regex
                                        this[q[0]] = match ? match.replace(q[1], q[2]) : undefined;
                                    }
                                } else if (q.length == 4) {
                                        this[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined;
                                }
                            } else {
                                this[q] = match ? match : undefined;
                            }
                        }
                    }
                }
                i += 2;
            }
            // console.log(this);
            //return this;
        },

        str : function (str, map) {

            for (var i in map) {
                // check if array
                if (typeof map[i] === OBJ_TYPE && map[i].length > 0) {
                    for (var j = 0; j < map[i].length; j++) {
                        if (util.has(map[i][j], str)) {
                            return (i === UNKNOWN) ? undefined : i;
                        }
                    }
                } else if (util.has(map[i], str)) {
                    return (i === UNKNOWN) ? undefined : i;
                }
            }
            return str;
        }
    };


    ///////////////
    // String map
    //////////////


    var maps = {

        browser : {
            oldsafari : {
                version : {
                    '1.0'   : '/8',
                    '1.2'   : '/1',
                    '1.3'   : '/3',
                    '2.0'   : '/412',
                    '2.0.2' : '/416',
                    '2.0.3' : '/417',
                    '2.0.4' : '/419',
                    '?'     : '/'
                }
            }
        },

        device : {
            amazon : {
                model : {
                    'Fire Phone' : ['SD', 'KF']
                }
            },
            sprint : {
                model : {
                    'Evo Shift 4G' : '7373KT'
                },
                vendor : {
                    'HTC'       : 'APA',
                    'Sprint'    : 'Sprint'
                }
            }
        },

        os : {
            windows : {
                version : {
                    'ME'        : '4.90',
                    'NT 3.11'   : 'NT3.51',
                    'NT 4.0'    : 'NT4.0',
                    '2000'      : 'NT 5.0',
                    'XP'        : ['NT 5.1', 'NT 5.2'],
                    'Vista'     : 'NT 6.0',
                    '7'         : 'NT 6.1',
                    '8'         : 'NT 6.2',
                    '8.1'       : 'NT 6.3',
                    '10'        : ['NT 6.4', 'NT 10.0'],
                    'RT'        : 'ARM'
                }
            }
        }
    };


    //////////////
    // Regex map
    /////////////


    var regexes = {

        browser : [[

            // Presto based
            /(opera\smini)\/([\w\.-]+)/i,                                       // Opera Mini
            /(opera\s[mobiletab]+).+version\/([\w\.-]+)/i,                      // Opera Mobi/Tablet
            /(opera).+version\/([\w\.]+)/i,                                     // Opera > 9.80
            /(opera)[\/\s]+([\w\.]+)/i                                          // Opera < 9.80
            ], [NAME, VERSION], [

            /(opios)[\/\s]+([\w\.]+)/i                                          // Opera mini on iphone >= 8.0
            ], [[NAME, 'Opera Mini'], VERSION], [

            /\s(opr)\/([\w\.]+)/i                                               // Opera Webkit
            ], [[NAME, 'Opera'], VERSION], [

            // Mixed
            /(kindle)\/([\w\.]+)/i,                                             // Kindle
            /(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?([\w\.]*)/i,
                                                                                // Lunascape/Maxthon/Netfront/Jasmine/Blazer

            // Trident based
            /(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?([\w\.]*)/i,
                                                                                // Avant/IEMobile/SlimBrowser/Baidu
            /(?:ms|\()(ie)\s([\w\.]+)/i,                                        // Internet Explorer

            // Webkit/KHTML based
            /(rekonq)\/([\w\.]*)/i,                                             // Rekonq
            /(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark)\/([\w\.-]+)/i
                                                                                // Chromium/Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron/Iridium/PhantomJS/Bowser
            ], [NAME, VERSION], [

            /(trident).+rv[:\s]([\w\.]+).+like\sgecko/i                         // IE11
            ], [[NAME, 'IE'], VERSION], [

            /(edge|edgios|edga)\/((\d+)?[\w\.]+)/i                              // Microsoft Edge
            ], [[NAME, 'Edge'], VERSION], [

            /(yabrowser)\/([\w\.]+)/i                                           // Yandex
            ], [[NAME, 'Yandex'], VERSION], [

            /(puffin)\/([\w\.]+)/i                                              // Puffin
            ], [[NAME, 'Puffin'], VERSION], [

            /(focus)\/([\w\.]+)/i                                               // Firefox Focus
            ], [[NAME, 'Firefox Focus'], VERSION], [

            /(opt)\/([\w\.]+)/i                                                 // Opera Touch
            ], [[NAME, 'Opera Touch'], VERSION], [

            /((?:[\s\/])uc?\s?browser|(?:juc.+)ucweb)[\/\s]?([\w\.]+)/i         // UCBrowser
            ], [[NAME, 'UCBrowser'], VERSION], [

            /(comodo_dragon)\/([\w\.]+)/i                                       // Comodo Dragon
            ], [[NAME, /_/g, ' '], VERSION], [

            /(micromessenger)\/([\w\.]+)/i                                      // WeChat
            ], [[NAME, 'WeChat'], VERSION], [

            /(brave)\/([\w\.]+)/i                                              // Brave browser
            ], [[NAME, 'Brave'], VERSION], [

            /(qqbrowserlite)\/([\w\.]+)/i                                       // QQBrowserLite
            ], [NAME, VERSION], [

            /(QQ)\/([\d\.]+)/i                                                  // QQ, aka ShouQ
            ], [NAME, VERSION], [

            /m?(qqbrowser)[\/\s]?([\w\.]+)/i                                    // QQBrowser
            ], [NAME, VERSION], [

            /(BIDUBrowser)[\/\s]?([\w\.]+)/i                                    // Baidu Browser
            ], [NAME, VERSION], [

            /(2345Explorer)[\/\s]?([\w\.]+)/i                                   // 2345 Browser
            ], [NAME, VERSION], [

            /(MetaSr)[\/\s]?([\w\.]+)/i                                         // SouGouBrowser
            ], [NAME], [

            /(LBBROWSER)/i                                      // LieBao Browser
            ], [NAME], [

            /xiaomi\/miuibrowser\/([\w\.]+)/i                                   // MIUI Browser
            ], [VERSION, [NAME, 'MIUI Browser']], [

            /;fbav\/([\w\.]+);/i                                                // Facebook App for iOS & Android
            ], [VERSION, [NAME, 'Facebook']], [

            /safari\s(line)\/([\w\.]+)/i,                                       // Line App for iOS
            /android.+(line)\/([\w\.]+)\/iab/i                                  // Line App for Android
            ], [NAME, VERSION], [

            /headlesschrome(?:\/([\w\.]+)|\s)/i                                 // Chrome Headless
            ], [VERSION, [NAME, 'Chrome Headless']], [

            /\swv\).+(chrome)\/([\w\.]+)/i                                      // Chrome WebView
            ], [[NAME, /(.+)/, '$1 WebView'], VERSION], [

            /((?:oculus|samsung)browser)\/([\w\.]+)/i
            ], [[NAME, /(.+(?:g|us))(.+)/, '$1 $2'], VERSION], [                // Oculus / Samsung Browser

            /android.+version\/([\w\.]+)\s+(?:mobile\s?safari|safari)*/i        // Android Browser
            ], [VERSION, [NAME, 'Android Browser']], [

            /(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?([\w\.]+)/i
                                                                                // Chrome/OmniWeb/Arora/Tizen/Nokia
            ], [NAME, VERSION], [

            /(dolfin)\/([\w\.]+)/i                                              // Dolphin
            ], [[NAME, 'Dolphin'], VERSION], [

            /((?:android.+)crmo|crios)\/([\w\.]+)/i                             // Chrome for Android/iOS
            ], [[NAME, 'Chrome'], VERSION], [

            /(coast)\/([\w\.]+)/i                                               // Opera Coast
            ], [[NAME, 'Opera Coast'], VERSION], [

            /fxios\/([\w\.-]+)/i                                                // Firefox for iOS
            ], [VERSION, [NAME, 'Firefox']], [

            /version\/([\w\.]+).+?mobile\/\w+\s(safari)/i                       // Mobile Safari
            ], [VERSION, [NAME, 'Mobile Safari']], [

            /version\/([\w\.]+).+?(mobile\s?safari|safari)/i                    // Safari & Safari Mobile
            ], [VERSION, NAME], [

            /webkit.+?(gsa)\/([\w\.]+).+?(mobile\s?safari|safari)(\/[\w\.]+)/i  // Google Search Appliance on iOS
            ], [[NAME, 'GSA'], VERSION], [

            /webkit.+?(mobile\s?safari|safari)(\/[\w\.]+)/i                     // Safari < 3.0
            ], [NAME, [VERSION, mapper.str, maps.browser.oldsafari.version]], [

            /(konqueror)\/([\w\.]+)/i,                                          // Konqueror
            /(webkit|khtml)\/([\w\.]+)/i
            ], [NAME, VERSION], [

            // Gecko based
            /(navigator|netscape)\/([\w\.-]+)/i                                 // Netscape
            ], [[NAME, 'Netscape'], VERSION], [
            /(swiftfox)/i,                                                      // Swiftfox
            /(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?([\w\.\+]+)/i,
                                                                                // IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror
            /(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([\w\.-]+)$/i,

                                                                                // Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix
            /(mozilla)\/([\w\.]+).+rv\:.+gecko\/\d+/i,                          // Mozilla

            // Other
            /(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir)[\/\s]?([\w\.]+)/i,
                                                                                // Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf/Sleipnir
            /(links)\s\(([\w\.]+)/i,                                            // Links
            /(gobrowser)\/?([\w\.]*)/i,                                         // GoBrowser
            /(ice\s?browser)\/v?([\w\._]+)/i,                                   // ICE Browser
            /(mosaic)[\/\s]([\w\.]+)/i                                          // Mosaic
            ], [NAME, VERSION]

            /* /////////////////////
            // Media players BEGIN
            ////////////////////////

            , [

            /(apple(?:coremedia|))\/((\d+)[\w\._]+)/i,                          // Generic Apple CoreMedia
            /(coremedia) v((\d+)[\w\._]+)/i
            ], [NAME, VERSION], [

            /(aqualung|lyssna|bsplayer)\/((\d+)?[\w\.-]+)/i                     // Aqualung/Lyssna/BSPlayer
            ], [NAME, VERSION], [

            /(ares|ossproxy)\s((\d+)[\w\.-]+)/i                                 // Ares/OSSProxy
            ], [NAME, VERSION], [

            /(audacious|audimusicstream|amarok|bass|core|dalvik|gnomemplayer|music on console|nsplayer|psp-internetradioplayer|videos)\/((\d+)[\w\.-]+)/i,
                                                                                // Audacious/AudiMusicStream/Amarok/BASS/OpenCORE/Dalvik/GnomeMplayer/MoC
                                                                                // NSPlayer/PSP-InternetRadioPlayer/Videos
            /(clementine|music player daemon)\s((\d+)[\w\.-]+)/i,               // Clementine/MPD
            /(lg player|nexplayer)\s((\d+)[\d\.]+)/i,
            /player\/(nexplayer|lg player)\s((\d+)[\w\.-]+)/i                   // NexPlayer/LG Player
            ], [NAME, VERSION], [
            /(nexplayer)\s((\d+)[\w\.-]+)/i                                     // Nexplayer
            ], [NAME, VERSION], [

            /(flrp)\/((\d+)[\w\.-]+)/i                                          // Flip Player
            ], [[NAME, 'Flip Player'], VERSION], [

            /(fstream|nativehost|queryseekspider|ia-archiver|facebookexternalhit)/i
                                                                                // FStream/NativeHost/QuerySeekSpider/IA Archiver/facebookexternalhit
            ], [NAME], [

            /(gstreamer) souphttpsrc (?:\([^\)]+\)){0,1} libsoup\/((\d+)[\w\.-]+)/i
                                                                                // Gstreamer
            ], [NAME, VERSION], [

            /(htc streaming player)\s[\w_]+\s\/\s((\d+)[\d\.]+)/i,              // HTC Streaming Player
            /(java|python-urllib|python-requests|wget|libcurl)\/((\d+)[\w\.-_]+)/i,
                                                                                // Java/urllib/requests/wget/cURL
            /(lavf)((\d+)[\d\.]+)/i                                             // Lavf (FFMPEG)
            ], [NAME, VERSION], [

            /(htc_one_s)\/((\d+)[\d\.]+)/i                                      // HTC One S
            ], [[NAME, /_/g, ' '], VERSION], [

            /(mplayer)(?:\s|\/)(?:(?:sherpya-){0,1}svn)(?:-|\s)(r\d+(?:-\d+[\w\.-]+){0,1})/i
                                                                                // MPlayer SVN
            ], [NAME, VERSION], [

            /(mplayer)(?:\s|\/|[unkow-]+)((\d+)[\w\.-]+)/i                      // MPlayer
            ], [NAME, VERSION], [

            /(mplayer)/i,                                                       // MPlayer (no other info)
            /(yourmuze)/i,                                                      // YourMuze
            /(media player classic|nero showtime)/i                             // Media Player Classic/Nero ShowTime
            ], [NAME], [

            /(nero (?:home|scout))\/((\d+)[\w\.-]+)/i                           // Nero Home/Nero Scout
            ], [NAME, VERSION], [

            /(nokia\d+)\/((\d+)[\w\.-]+)/i                                      // Nokia
            ], [NAME, VERSION], [

            /\s(songbird)\/((\d+)[\w\.-]+)/i                                    // Songbird/Philips-Songbird
            ], [NAME, VERSION], [

            /(winamp)3 version ((\d+)[\w\.-]+)/i,                               // Winamp
            /(winamp)\s((\d+)[\w\.-]+)/i,
            /(winamp)mpeg\/((\d+)[\w\.-]+)/i
            ], [NAME, VERSION], [

            /(ocms-bot|tapinradio|tunein radio|unknown|winamp|inlight radio)/i  // OCMS-bot/tap in radio/tunein/unknown/winamp (no other info)
                                                                                // inlight radio
            ], [NAME], [

            /(quicktime|rma|radioapp|radioclientapplication|soundtap|totem|stagefright|streamium)\/((\d+)[\w\.-]+)/i
                                                                                // QuickTime/RealMedia/RadioApp/RadioClientApplication/
                                                                                // SoundTap/Totem/Stagefright/Streamium
            ], [NAME, VERSION], [

            /(smp)((\d+)[\d\.]+)/i                                              // SMP
            ], [NAME, VERSION], [

            /(vlc) media player - version ((\d+)[\w\.]+)/i,                     // VLC Videolan
            /(vlc)\/((\d+)[\w\.-]+)/i,
            /(xbmc|gvfs|xine|xmms|irapp)\/((\d+)[\w\.-]+)/i,                    // XBMC/gvfs/Xine/XMMS/irapp
            /(foobar2000)\/((\d+)[\d\.]+)/i,                                    // Foobar2000
            /(itunes)\/((\d+)[\d\.]+)/i                                         // iTunes
            ], [NAME, VERSION], [

            /(wmplayer)\/((\d+)[\w\.-]+)/i,                                     // Windows Media Player
            /(windows-media-player)\/((\d+)[\w\.-]+)/i
            ], [[NAME, /-/g, ' '], VERSION], [

            /windows\/((\d+)[\w\.-]+) upnp\/[\d\.]+ dlnadoc\/[\d\.]+ (home media server)/i
                                                                                // Windows Media Server
            ], [VERSION, [NAME, 'Windows']], [

            /(com\.riseupradioalarm)\/((\d+)[\d\.]*)/i                          // RiseUP Radio Alarm
            ], [NAME, VERSION], [

            /(rad.io)\s((\d+)[\d\.]+)/i,                                        // Rad.io
            /(radio.(?:de|at|fr))\s((\d+)[\d\.]+)/i
            ], [[NAME, 'rad.io'], VERSION]

            //////////////////////
            // Media players END
            ////////////////////*/

        ],

        cpu : [[

            /(?:(amd|x(?:(?:86|64)[_-])?|wow|win)64)[;\)]/i                     // AMD64
            ], [[ARCHITECTURE, 'amd64']], [

            /(ia32(?=;))/i                                                      // IA32 (quicktime)
            ], [[ARCHITECTURE, util.lowerize]], [

            /((?:i[346]|x)86)[;\)]/i                                            // IA32
            ], [[ARCHITECTURE, 'ia32']], [

            // PocketPC mistakenly identified as PowerPC
            /windows\s(ce|mobile);\sppc;/i
            ], [[ARCHITECTURE, 'arm']], [

            /((?:ppc|powerpc)(?:64)?)(?:\smac|;|\))/i                           // PowerPC
            ], [[ARCHITECTURE, /ower/, '', util.lowerize]], [

            /(sun4\w)[;\)]/i                                                    // SPARC
            ], [[ARCHITECTURE, 'sparc']], [

            /((?:avr32|ia64(?=;))|68k(?=\))|arm(?:64|(?=v\d+[;l]))|(?=atmel\s)avr|(?:irix|mips|sparc)(?:64)?(?=;)|pa-risc)/i
                                                                                // IA64, 68K, ARM/64, AVR/32, IRIX/64, MIPS/64, SPARC/64, PA-RISC
            ], [[ARCHITECTURE, util.lowerize]]
        ],

        device : [[

            /\((ipad|playbook);[\w\s\);-]+(rim|apple)/i                         // iPad/PlayBook
            ], [MODEL, VENDOR, [TYPE, TABLET]], [

            /applecoremedia\/[\w\.]+ \((ipad)/                                  // iPad
            ], [MODEL, [VENDOR, 'Apple'], [TYPE, TABLET]], [

            /(apple\s{0,1}tv)/i                                                 // Apple TV
            ], [[MODEL, 'Apple TV'], [VENDOR, 'Apple']], [

            /(archos)\s(gamepad2?)/i,                                           // Archos
            /(hp).+(touchpad)/i,                                                // HP TouchPad
            /(hp).+(tablet)/i,                                                  // HP Tablet
            /(kindle)\/([\w\.]+)/i,                                             // Kindle
            /\s(nook)[\w\s]+build\/(\w+)/i,                                     // Nook
            /(dell)\s(strea[kpr\s\d]*[\dko])/i                                  // Dell Streak
            ], [VENDOR, MODEL, [TYPE, TABLET]], [

            /(kf[A-z]+)\sbuild\/.+silk\//i                                      // Kindle Fire HD
            ], [MODEL, [VENDOR, 'Amazon'], [TYPE, TABLET]], [
            /(sd|kf)[0349hijorstuw]+\sbuild\/.+silk\//i                         // Fire Phone
            ], [[MODEL, mapper.str, maps.device.amazon.model], [VENDOR, 'Amazon'], [TYPE, MOBILE]], [
            /android.+aft([bms])\sbuild/i                                       // Fire TV
            ], [MODEL, [VENDOR, 'Amazon'], [TYPE, SMARTTV]], [

            /\((ip[honed|\s\w*]+);.+(apple)/i                                   // iPod/iPhone
            ], [MODEL, VENDOR, [TYPE, MOBILE]], [
            /\((ip[honed|\s\w*]+);/i                                            // iPod/iPhone
            ], [MODEL, [VENDOR, 'Apple'], [TYPE, MOBILE]], [

            /(blackberry)[\s-]?(\w+)/i,                                         // BlackBerry
            /(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[\s_-]?([\w-]*)/i,
                                                                                // BenQ/Palm/Sony-Ericsson/Acer/Asus/Dell/Meizu/Motorola/Polytron
            /(hp)\s([\w\s]+\w)/i,                                               // HP iPAQ
            /(asus)-?(\w+)/i                                                    // Asus
            ], [VENDOR, MODEL, [TYPE, MOBILE]], [
            /\(bb10;\s(\w+)/i                                                   // BlackBerry 10
            ], [MODEL, [VENDOR, 'BlackBerry'], [TYPE, MOBILE]], [
                                                                                // Asus Tablets
            /android.+(transfo[prime\s]{4,10}\s\w+|eeepc|slider\s\w+|nexus 7|padfone)/i
            ], [MODEL, [VENDOR, 'Asus'], [TYPE, TABLET]], [

            /(sony)\s(tablet\s[ps])\sbuild\//i,                                  // Sony
            /(sony)?(?:sgp.+)\sbuild\//i
            ], [[VENDOR, 'Sony'], [MODEL, 'Xperia Tablet'], [TYPE, TABLET]], [
            /android.+\s([c-g]\d{4}|so[-l]\w+)\sbuild\//i
            ], [MODEL, [VENDOR, 'Sony'], [TYPE, MOBILE]], [

            /\s(ouya)\s/i,                                                      // Ouya
            /(nintendo)\s([wids3u]+)/i                                          // Nintendo
            ], [VENDOR, MODEL, [TYPE, CONSOLE]], [

            /android.+;\s(shield)\sbuild/i                                      // Nvidia
            ], [MODEL, [VENDOR, 'Nvidia'], [TYPE, CONSOLE]], [

            /(playstation\s[34portablevi]+)/i                                   // Playstation
            ], [MODEL, [VENDOR, 'Sony'], [TYPE, CONSOLE]], [

            /(sprint\s(\w+))/i                                                  // Sprint Phones
            ], [[VENDOR, mapper.str, maps.device.sprint.vendor], [MODEL, mapper.str, maps.device.sprint.model], [TYPE, MOBILE]], [

            /(lenovo)\s?(S(?:5000|6000)+(?:[-][\w+]))/i                         // Lenovo tablets
            ], [VENDOR, MODEL, [TYPE, TABLET]], [

            /(htc)[;_\s-]+([\w\s]+(?=\))|\w+)*/i,                               // HTC
            /(zte)-(\w*)/i,                                                     // ZTE
            /(alcatel|geeksphone|lenovo|nexian|panasonic|(?=;\s)sony)[_\s-]?([\w-]*)/i
                                                                                // Alcatel/GeeksPhone/Lenovo/Nexian/Panasonic/Sony
            ], [VENDOR, [MODEL, /_/g, ' '], [TYPE, MOBILE]], [

            /(nexus\s9)/i                                                       // HTC Nexus 9
            ], [MODEL, [VENDOR, 'HTC'], [TYPE, TABLET]], [

            /d\/huawei([\w\s-]+)[;\)]/i,
            /(nexus\s6p)/i                                                      // Huawei
            ], [MODEL, [VENDOR, 'Huawei'], [TYPE, MOBILE]], [

            /(microsoft);\s(lumia[\s\w]+)/i                                     // Microsoft Lumia
            ], [VENDOR, MODEL, [TYPE, MOBILE]], [

            /[\s\(;](xbox(?:\sone)?)[\s\);]/i                                   // Microsoft Xbox
            ], [MODEL, [VENDOR, 'Microsoft'], [TYPE, CONSOLE]], [
            /(kin\.[onetw]{3})/i                                                // Microsoft Kin
            ], [[MODEL, /\./g, ' '], [VENDOR, 'Microsoft'], [TYPE, MOBILE]], [

                                                                                // Motorola
            /\s(milestone|droid(?:[2-4x]|\s(?:bionic|x2|pro|razr))?:?(\s4g)?)[\w\s]+build\//i,
            /mot[\s-]?(\w*)/i,
            /(XT\d{3,4}) build\//i,
            /(nexus\s6)/i
            ], [MODEL, [VENDOR, 'Motorola'], [TYPE, MOBILE]], [
            /android.+\s(mz60\d|xoom[\s2]{0,2})\sbuild\//i
            ], [MODEL, [VENDOR, 'Motorola'], [TYPE, TABLET]], [

            /hbbtv\/\d+\.\d+\.\d+\s+\([\w\s]*;\s*(\w[^;]*);([^;]*)/i            // HbbTV devices
            ], [[VENDOR, util.trim], [MODEL, util.trim], [TYPE, SMARTTV]], [

            /hbbtv.+maple;(\d+)/i
            ], [[MODEL, /^/, 'SmartTV'], [VENDOR, 'Samsung'], [TYPE, SMARTTV]], [

            /\(dtv[\);].+(aquos)/i                                              // Sharp
            ], [MODEL, [VENDOR, 'Sharp'], [TYPE, SMARTTV]], [

            /android.+((sch-i[89]0\d|shw-m380s|gt-p\d{4}|gt-n\d+|sgh-t8[56]9|nexus 10))/i,
            /((SM-T\w+))/i
            ], [[VENDOR, 'Samsung'], MODEL, [TYPE, TABLET]], [                  // Samsung
            /smart-tv.+(samsung)/i
            ], [VENDOR, [TYPE, SMARTTV], MODEL], [
            /((s[cgp]h-\w+|gt-\w+|galaxy\snexus|sm-\w[\w\d]+))/i,
            /(sam[sung]*)[\s-]*(\w+-?[\w-]*)/i,
            /sec-((sgh\w+))/i
            ], [[VENDOR, 'Samsung'], MODEL, [TYPE, MOBILE]], [

            /sie-(\w*)/i                                                        // Siemens
            ], [MODEL, [VENDOR, 'Siemens'], [TYPE, MOBILE]], [

            /(maemo|nokia).*(n900|lumia\s\d+)/i,                                // Nokia
            /(nokia)[\s_-]?([\w-]*)/i
            ], [[VENDOR, 'Nokia'], MODEL, [TYPE, MOBILE]], [

            /android\s3\.[\s\w;-]{10}(a\d{3})/i                                 // Acer
            ], [MODEL, [VENDOR, 'Acer'], [TYPE, TABLET]], [

            /android.+([vl]k\-?\d{3})\s+build/i                                 // LG Tablet
            ], [MODEL, [VENDOR, 'LG'], [TYPE, TABLET]], [
            /android\s3\.[\s\w;-]{10}(lg?)-([06cv9]{3,4})/i                     // LG Tablet
            ], [[VENDOR, 'LG'], MODEL, [TYPE, TABLET]], [
            /(lg) netcast\.tv/i                                                 // LG SmartTV
            ], [VENDOR, MODEL, [TYPE, SMARTTV]], [
            /(nexus\s[45])/i,                                                   // LG
            /lg[e;\s\/-]+(\w*)/i,
            /android.+lg(\-?[\d\w]+)\s+build/i
            ], [MODEL, [VENDOR, 'LG'], [TYPE, MOBILE]], [

            /android.+(ideatab[a-z0-9\-\s]+)/i                                  // Lenovo
            ], [MODEL, [VENDOR, 'Lenovo'], [TYPE, TABLET]], [

            /linux;.+((jolla));/i                                               // Jolla
            ], [VENDOR, MODEL, [TYPE, MOBILE]], [

            /((pebble))app\/[\d\.]+\s/i                                         // Pebble
            ], [VENDOR, MODEL, [TYPE, WEARABLE]], [

            /android.+;\s(oppo)\s?([\w\s]+)\sbuild/i                            // OPPO
            ], [VENDOR, MODEL, [TYPE, MOBILE]], [

            /crkey/i                                                            // Google Chromecast
            ], [[MODEL, 'Chromecast'], [VENDOR, 'Google']], [

            /android.+;\s(glass)\s\d/i                                          // Google Glass
            ], [MODEL, [VENDOR, 'Google'], [TYPE, WEARABLE]], [

            /android.+;\s(pixel c)[\s)]/i                                       // Google Pixel C
            ], [MODEL, [VENDOR, 'Google'], [TYPE, TABLET]], [

            /android.+;\s(pixel( [23])?( xl)?)\s/i                              // Google Pixel
            ], [MODEL, [VENDOR, 'Google'], [TYPE, MOBILE]], [

            /android.+;\s(\w+)\s+build\/hm\1/i,                                 // Xiaomi Hongmi 'numeric' models
            /android.+(hm[\s\-_]*note?[\s_]*(?:\d\w)?)\s+build/i,               // Xiaomi Hongmi
            /android.+(mi[\s\-_]*(?:one|one[\s_]plus|note lte)?[\s_]*(?:\d?\w?)[\s_]*(?:plus)?)\s+build/i,    // Xiaomi Mi
            /android.+(redmi[\s\-_]*(?:note)?(?:[\s_]*[\w\s]+))\s+build/i       // Redmi Phones
            ], [[MODEL, /_/g, ' '], [VENDOR, 'Xiaomi'], [TYPE, MOBILE]], [
            /android.+(mi[\s\-_]*(?:pad)(?:[\s_]*[\w\s]+))\s+build/i            // Mi Pad tablets
            ],[[MODEL, /_/g, ' '], [VENDOR, 'Xiaomi'], [TYPE, TABLET]], [
            /android.+;\s(m[1-5]\snote)\sbuild/i                                // Meizu Tablet
            ], [MODEL, [VENDOR, 'Meizu'], [TYPE, TABLET]], [
            /(mz)-([\w-]{2,})/i                                                 // Meizu Phone
            ], [[VENDOR, 'Meizu'], MODEL, [TYPE, MOBILE]], [

            /android.+a000(1)\s+build/i,                                        // OnePlus
            /android.+oneplus\s(a\d{4})\s+build/i
            ], [MODEL, [VENDOR, 'OnePlus'], [TYPE, MOBILE]], [

            /android.+[;\/]\s*(RCT[\d\w]+)\s+build/i                            // RCA Tablets
            ], [MODEL, [VENDOR, 'RCA'], [TYPE, TABLET]], [

            /android.+[;\/\s]+(Venue[\d\s]{2,7})\s+build/i                      // Dell Venue Tablets
            ], [MODEL, [VENDOR, 'Dell'], [TYPE, TABLET]], [

            /android.+[;\/]\s*(Q[T|M][\d\w]+)\s+build/i                         // Verizon Tablet
            ], [MODEL, [VENDOR, 'Verizon'], [TYPE, TABLET]], [

            /android.+[;\/]\s+(Barnes[&\s]+Noble\s+|BN[RT])(V?.*)\s+build/i     // Barnes & Noble Tablet
            ], [[VENDOR, 'Barnes & Noble'], MODEL, [TYPE, TABLET]], [

            /android.+[;\/]\s+(TM\d{3}.*\b)\s+build/i                           // Barnes & Noble Tablet
            ], [MODEL, [VENDOR, 'NuVision'], [TYPE, TABLET]], [

            /android.+;\s(k88)\sbuild/i                                         // ZTE K Series Tablet
            ], [MODEL, [VENDOR, 'ZTE'], [TYPE, TABLET]], [

            /android.+[;\/]\s*(gen\d{3})\s+build.*49h/i                         // Swiss GEN Mobile
            ], [MODEL, [VENDOR, 'Swiss'], [TYPE, MOBILE]], [

            /android.+[;\/]\s*(zur\d{3})\s+build/i                              // Swiss ZUR Tablet
            ], [MODEL, [VENDOR, 'Swiss'], [TYPE, TABLET]], [

            /android.+[;\/]\s*((Zeki)?TB.*\b)\s+build/i                         // Zeki Tablets
            ], [MODEL, [VENDOR, 'Zeki'], [TYPE, TABLET]], [

            /(android).+[;\/]\s+([YR]\d{2})\s+build/i,
            /android.+[;\/]\s+(Dragon[\-\s]+Touch\s+|DT)(\w{5})\sbuild/i        // Dragon Touch Tablet
            ], [[VENDOR, 'Dragon Touch'], MODEL, [TYPE, TABLET]], [

            /android.+[;\/]\s*(NS-?\w{0,9})\sbuild/i                            // Insignia Tablets
            ], [MODEL, [VENDOR, 'Insignia'], [TYPE, TABLET]], [

            /android.+[;\/]\s*((NX|Next)-?\w{0,9})\s+build/i                    // NextBook Tablets
            ], [MODEL, [VENDOR, 'NextBook'], [TYPE, TABLET]], [

            /android.+[;\/]\s*(Xtreme\_)?(V(1[045]|2[015]|30|40|60|7[05]|90))\s+build/i
            ], [[VENDOR, 'Voice'], MODEL, [TYPE, MOBILE]], [                    // Voice Xtreme Phones

            /android.+[;\/]\s*(LVTEL\-)?(V1[12])\s+build/i                     // LvTel Phones
            ], [[VENDOR, 'LvTel'], MODEL, [TYPE, MOBILE]], [

            /android.+;\s(PH-1)\s/i
            ], [MODEL, [VENDOR, 'Essential'], [TYPE, MOBILE]], [                // Essential PH-1

            /android.+[;\/]\s*(V(100MD|700NA|7011|917G).*\b)\s+build/i          // Envizen Tablets
            ], [MODEL, [VENDOR, 'Envizen'], [TYPE, TABLET]], [

            /android.+[;\/]\s*(Le[\s\-]+Pan)[\s\-]+(\w{1,9})\s+build/i          // Le Pan Tablets
            ], [VENDOR, MODEL, [TYPE, TABLET]], [

            /android.+[;\/]\s*(Trio[\s\-]*.*)\s+build/i                         // MachSpeed Tablets
            ], [MODEL, [VENDOR, 'MachSpeed'], [TYPE, TABLET]], [

            /android.+[;\/]\s*(Trinity)[\-\s]*(T\d{3})\s+build/i                // Trinity Tablets
            ], [VENDOR, MODEL, [TYPE, TABLET]], [

            /android.+[;\/]\s*TU_(1491)\s+build/i                               // Rotor Tablets
            ], [MODEL, [VENDOR, 'Rotor'], [TYPE, TABLET]], [

            /android.+(KS(.+))\s+build/i                                        // Amazon Kindle Tablets
            ], [MODEL, [VENDOR, 'Amazon'], [TYPE, TABLET]], [

            /android.+(Gigaset)[\s\-]+(Q\w{1,9})\s+build/i                      // Gigaset Tablets
            ], [VENDOR, MODEL, [TYPE, TABLET]], [

            /\s(tablet|tab)[;\/]/i,                                             // Unidentifiable Tablet
            /\s(mobile)(?:[;\/]|\ssafari)/i                                     // Unidentifiable Mobile
            ], [[TYPE, util.lowerize], VENDOR, MODEL], [

            /(android[\w\.\s\-]{0,9});.+build/i                                 // Generic Android Device
            ], [MODEL, [VENDOR, 'Generic']]


        /*//////////////////////////
            // TODO: move to string map
            ////////////////////////////

            /(C6603)/i                                                          // Sony Xperia Z C6603
            ], [[MODEL, 'Xperia Z C6603'], [VENDOR, 'Sony'], [TYPE, MOBILE]], [
            /(C6903)/i                                                          // Sony Xperia Z 1
            ], [[MODEL, 'Xperia Z 1'], [VENDOR, 'Sony'], [TYPE, MOBILE]], [

            /(SM-G900[F|H])/i                                                   // Samsung Galaxy S5
            ], [[MODEL, 'Galaxy S5'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [
            /(SM-G7102)/i                                                       // Samsung Galaxy Grand 2
            ], [[MODEL, 'Galaxy Grand 2'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [
            /(SM-G530H)/i                                                       // Samsung Galaxy Grand Prime
            ], [[MODEL, 'Galaxy Grand Prime'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [
            /(SM-G313HZ)/i                                                      // Samsung Galaxy V
            ], [[MODEL, 'Galaxy V'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [
            /(SM-T805)/i                                                        // Samsung Galaxy Tab S 10.5
            ], [[MODEL, 'Galaxy Tab S 10.5'], [VENDOR, 'Samsung'], [TYPE, TABLET]], [
            /(SM-G800F)/i                                                       // Samsung Galaxy S5 Mini
            ], [[MODEL, 'Galaxy S5 Mini'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [
            /(SM-T311)/i                                                        // Samsung Galaxy Tab 3 8.0
            ], [[MODEL, 'Galaxy Tab 3 8.0'], [VENDOR, 'Samsung'], [TYPE, TABLET]], [

            /(T3C)/i                                                            // Advan Vandroid T3C
            ], [MODEL, [VENDOR, 'Advan'], [TYPE, TABLET]], [
            /(ADVAN T1J\+)/i                                                    // Advan Vandroid T1J+
            ], [[MODEL, 'Vandroid T1J+'], [VENDOR, 'Advan'], [TYPE, TABLET]], [
            /(ADVAN S4A)/i                                                      // Advan Vandroid S4A
            ], [[MODEL, 'Vandroid S4A'], [VENDOR, 'Advan'], [TYPE, MOBILE]], [

            /(V972M)/i                                                          // ZTE V972M
            ], [MODEL, [VENDOR, 'ZTE'], [TYPE, MOBILE]], [

            /(i-mobile)\s(IQ\s[\d\.]+)/i                                        // i-mobile IQ
            ], [VENDOR, MODEL, [TYPE, MOBILE]], [
            /(IQ6.3)/i                                                          // i-mobile IQ IQ 6.3
            ], [[MODEL, 'IQ 6.3'], [VENDOR, 'i-mobile'], [TYPE, MOBILE]], [
            /(i-mobile)\s(i-style\s[\d\.]+)/i                                   // i-mobile i-STYLE
            ], [VENDOR, MODEL, [TYPE, MOBILE]], [
            /(i-STYLE2.1)/i                                                     // i-mobile i-STYLE 2.1
            ], [[MODEL, 'i-STYLE 2.1'], [VENDOR, 'i-mobile'], [TYPE, MOBILE]], [

            /(mobiistar touch LAI 512)/i                                        // mobiistar touch LAI 512
            ], [[MODEL, 'Touch LAI 512'], [VENDOR, 'mobiistar'], [TYPE, MOBILE]], [

            /////////////
            // END TODO
            ///////////*/

        ],

        engine : [[

            /windows.+\sedge\/([\w\.]+)/i                                       // EdgeHTML
            ], [VERSION, [NAME, 'EdgeHTML']], [

            /(presto)\/([\w\.]+)/i,                                             // Presto
            /(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i,     // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m
            /(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i,                          // KHTML/Tasman/Links
            /(icab)[\/\s]([23]\.[\d\.]+)/i                                      // iCab
            ], [NAME, VERSION], [

            /rv\:([\w\.]{1,9}).+(gecko)/i                                       // Gecko
            ], [VERSION, NAME]
        ],

        os : [[

            // Windows based
            /microsoft\s(windows)\s(vista|xp)/i                                 // Windows (iTunes)
            ], [NAME, VERSION], [
            /(windows)\snt\s6\.2;\s(arm)/i,                                     // Windows RT
            /(windows\sphone(?:\sos)*)[\s\/]?([\d\.\s\w]*)/i,                   // Windows Phone
            /(windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i
            ], [NAME, [VERSION, mapper.str, maps.os.windows.version]], [
            /(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i
            ], [[NAME, 'Windows'], [VERSION, mapper.str, maps.os.windows.version]], [

            // Mobile/Embedded OS
            /\((bb)(10);/i                                                      // BlackBerry 10
            ], [[NAME, 'BlackBerry'], VERSION], [
            /(blackberry)\w*\/?([\w\.]*)/i,                                     // Blackberry
            /(tizen)[\/\s]([\w\.]+)/i,                                          // Tizen
            /(android|webos|palm\sos|qnx|bada|rim\stablet\sos|meego|contiki)[\/\s-]?([\w\.]*)/i,
                                                                                // Android/WebOS/Palm/QNX/Bada/RIM/MeeGo/Contiki
            /linux;.+(sailfish);/i                                              // Sailfish OS
            ], [NAME, VERSION], [
            /(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]*)/i                  // Symbian
            ], [[NAME, 'Symbian'], VERSION], [
            /\((series40);/i                                                    // Series 40
            ], [NAME], [
            /mozilla.+\(mobile;.+gecko.+firefox/i                               // Firefox OS
            ], [[NAME, 'Firefox OS'], VERSION], [

            // Console
            /(nintendo|playstation)\s([wids34portablevu]+)/i,                   // Nintendo/Playstation

            // GNU/Linux based
            /(mint)[\/\s\(]?(\w*)/i,                                            // Mint
            /(mageia|vectorlinux)[;\s]/i,                                       // Mageia/VectorLinux
            /(joli|[kxln]?ubuntu|debian|suse|opensuse|gentoo|(?=\s)arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk|linpus)[\/\s-]?(?!chrom)([\w\.-]*)/i,
                                                                                // Joli/Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware
                                                                                // Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk/Linpus
            /(hurd|linux)\s?([\w\.]*)/i,                                        // Hurd/Linux
            /(gnu)\s?([\w\.]*)/i                                                // GNU
            ], [NAME, VERSION], [

            /(cros)\s[\w]+\s([\w\.]+\w)/i                                       // Chromium OS
            ], [[NAME, 'Chromium OS'], VERSION],[

            // Solaris
            /(sunos)\s?([\w\.\d]*)/i                                            // Solaris
            ], [[NAME, 'Solaris'], VERSION], [

            // BSD based
            /\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]*)/i                    // FreeBSD/NetBSD/OpenBSD/PC-BSD/DragonFly
            ], [NAME, VERSION],[

            /(haiku)\s(\w+)/i                                                   // Haiku
            ], [NAME, VERSION],[

            /cfnetwork\/.+darwin/i,
            /ip[honead]{2,4}(?:.*os\s([\w]+)\slike\smac|;\sopera)/i             // iOS
            ], [[VERSION, /_/g, '.'], [NAME, 'iOS']], [

            /(mac\sos\sx)\s?([\w\s\.]*)/i,
            /(macintosh|mac(?=_powerpc)\s)/i                                    // Mac OS
            ], [[NAME, 'Mac OS'], [VERSION, /_/g, '.']], [

            // Other
            /((?:open)?solaris)[\/\s-]?([\w\.]*)/i,                             // Solaris
            /(aix)\s((\d)(?=\.|\)|\s)[\w\.])*/i,                                // AIX
            /(plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos|openvms|fuchsia)/i,
                                                                                // Plan9/Minix/BeOS/OS2/AmigaOS/MorphOS/RISCOS/OpenVMS/Fuchsia
            /(unix)\s?([\w\.]*)/i                                               // UNIX
            ], [NAME, VERSION]
        ]
    };


    /////////////////
    // Constructor
    ////////////////
    /*
    var Browser = function (name, version) {
        this[NAME] = name;
        this[VERSION] = version;
    };
    var CPU = function (arch) {
        this[ARCHITECTURE] = arch;
    };
    var Device = function (vendor, model, type) {
        this[VENDOR] = vendor;
        this[MODEL] = model;
        this[TYPE] = type;
    };
    var Engine = Browser;
    var OS = Browser;
    */
    var UAParser = function (uastring, extensions) {

        if (typeof uastring === 'object') {
            extensions = uastring;
            uastring = undefined;
        }

        if (!(this instanceof UAParser)) {
            return new UAParser(uastring, extensions).getResult();
        }

        var ua = uastring || ((window && window.navigator && window.navigator.userAgent) ? window.navigator.userAgent : EMPTY);
        var rgxmap = extensions ? util.extend(regexes, extensions) : regexes;
        //var browser = new Browser();
        //var cpu = new CPU();
        //var device = new Device();
        //var engine = new Engine();
        //var os = new OS();

        this.getBrowser = function () {
            var browser = { name: undefined, version: undefined };
            mapper.rgx.call(browser, ua, rgxmap.browser);
            browser.major = util.major(browser.version); // deprecated
            return browser;
        };
        this.getCPU = function () {
            var cpu = { architecture: undefined };
            mapper.rgx.call(cpu, ua, rgxmap.cpu);
            return cpu;
        };
        this.getDevice = function () {
            var device = { vendor: undefined, model: undefined, type: undefined };
            mapper.rgx.call(device, ua, rgxmap.device);
            return device;
        };
        this.getEngine = function () {
            var engine = { name: undefined, version: undefined };
            mapper.rgx.call(engine, ua, rgxmap.engine);
            return engine;
        };
        this.getOS = function () {
            var os = { name: undefined, version: undefined };
            mapper.rgx.call(os, ua, rgxmap.os);
            return os;
        };
        this.getResult = function () {
            return {
                ua      : this.getUA(),
                browser : this.getBrowser(),
                engine  : this.getEngine(),
                os      : this.getOS(),
                device  : this.getDevice(),
                cpu     : this.getCPU()
            };
        };
        this.getUA = function () {
            return ua;
        };
        this.setUA = function (uastring) {
            ua = uastring;
            //browser = new Browser();
            //cpu = new CPU();
            //device = new Device();
            //engine = new Engine();
            //os = new OS();
            return this;
        };
        return this;
    };

    UAParser.VERSION = LIBVERSION;
    UAParser.BROWSER = {
        NAME    : NAME,
        MAJOR   : MAJOR, // deprecated
        VERSION : VERSION
    };
    UAParser.CPU = {
        ARCHITECTURE : ARCHITECTURE
    };
    UAParser.DEVICE = {
        MODEL   : MODEL,
        VENDOR  : VENDOR,
        TYPE    : TYPE,
        CONSOLE : CONSOLE,
        MOBILE  : MOBILE,
        SMARTTV : SMARTTV,
        TABLET  : TABLET,
        WEARABLE: WEARABLE,
        EMBEDDED: EMBEDDED
    };
    UAParser.ENGINE = {
        NAME    : NAME,
        VERSION : VERSION
    };
    UAParser.OS = {
        NAME    : NAME,
        VERSION : VERSION
    };
    //UAParser.Utils = util;

    ///////////
    // Export
    //////////


    // check js environment
    if (typeof(exports) !== UNDEF_TYPE) {
        // nodejs env
        if (typeof module !== UNDEF_TYPE && module.exports) {
            exports = module.exports = UAParser;
        }
        // TODO: test!!!!!!!!
        /*
        if (require && require.main === module && process) {
            // cli
            var jsonize = function (arr) {
                var res = [];
                for (var i in arr) {
                    res.push(new UAParser(arr[i]).getResult());
                }
                process.stdout.write(JSON.stringify(res, null, 2) + '\n');
            };
            if (process.stdin.isTTY) {
                // via args
                jsonize(process.argv.slice(2));
            } else {
                // via pipe
                var str = '';
                process.stdin.on('readable', function() {
                    var read = process.stdin.read();
                    if (read !== null) {
                        str += read;
                    }
                });
                process.stdin.on('end', function () {
                    jsonize(str.replace(/\n$/, '').split('\n'));
                });
            }
        }
        */
        exports.UAParser = UAParser;
    } else {
        // requirejs env (optional)
        if ("function" === FUNC_TYPE && __webpack_require__(/*! !webpack amd options */ "PDX0")) {
            !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {
                return UAParser;
            }).call(exports, __webpack_require__, exports, module),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
        } else if (window) {
            // browser env
            window.UAParser = UAParser;
        }
    }

    // jQuery/Zepto specific (optional)
    // Note:
    //   In AMD env the global scope should be kept clean, but jQuery is an exception.
    //   jQuery always exports to global scope, unless jQuery.noConflict(true) is used,
    //   and we should catch that.
    var $ = window && (window.jQuery || window.Zepto);
    if (typeof $ !== UNDEF_TYPE && !$.ua) {
        var parser = new UAParser();
        $.ua = parser.getResult();
        $.ua.get = function () {
            return parser.getUA();
        };
        $.ua.set = function (uastring) {
            parser.setUA(uastring);
            var result = parser.getResult();
            for (var prop in result) {
                $.ua[prop] = result[prop];
            }
        };
    }

})(typeof window === 'object' ? window : this);


/***/ }),

/***/ "K7N2":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/cells/lib/placeholder.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const React = __importStar(__webpack_require__(/*! react */ "q1tI"));
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
/**
 * The CSS class added to placeholders.
 */
const PLACEHOLDER_CLASS = 'jp-Placeholder';
/**
 * The CSS classes added to input placeholder prompts.
 */
const INPUT_PROMPT_CLASS = 'jp-Placeholder-prompt jp-InputPrompt';
/**
 * The CSS classes added to output placeholder prompts.
 */
const OUTPUT_PROMPT_CLASS = 'jp-Placeholder-prompt jp-OutputPrompt';
/**
 * The CSS class added to placeholder content.
 */
const CONTENT_CLASS = 'jp-Placeholder-content';
/**
 * The CSS class added to input placeholders.
 */
const INPUT_PLACEHOLDER_CLASS = 'jp-InputPlaceholder';
/**
 * The CSS class added to output placeholders.
 */
const OUTPUT_PLACEHOLDER_CLASS = 'jp-OutputPlaceholder';
/**
 * An abstract base class for placeholders
 *
 * ### Notes
 * A placeholder is the element that is shown when input/output
 * is hidden.
 */
class Placeholder extends apputils_1.VDomRenderer {
    /**
     * Construct a new placeholder.
     */
    constructor(callback) {
        super();
        this.addClass(PLACEHOLDER_CLASS);
        this._callback = callback;
    }
    /**
     * Handle the click event.
     */
    handleClick(e) {
        let callback = this._callback;
        callback(e);
    }
}
exports.Placeholder = Placeholder;
/**
 * The input placeholder class.
 */
class InputPlaceholder extends Placeholder {
    /**
     * Construct a new input placeholder.
     */
    constructor(callback) {
        super(callback);
        this.addClass(INPUT_PLACEHOLDER_CLASS);
    }
    /**
     * Render the input placeholder using the virtual DOM.
     */
    render() {
        return [
            React.createElement("div", { className: INPUT_PROMPT_CLASS, key: "input" }),
            React.createElement("div", { className: CONTENT_CLASS, onClick: e => this.handleClick(e), key: "content" },
                React.createElement("div", { className: "jp-MoreHorizIcon" }))
        ];
    }
}
exports.InputPlaceholder = InputPlaceholder;
/**
 * The output placeholder class.
 */
class OutputPlaceholder extends Placeholder {
    /**
     * Construct a new output placeholder.
     */
    constructor(callback) {
        super(callback);
        this.addClass(OUTPUT_PLACEHOLDER_CLASS);
    }
    /**
     * Render the output placeholder using the virtual DOM.
     */
    render() {
        return [
            React.createElement("div", { className: OUTPUT_PROMPT_CLASS, key: "output" }),
            React.createElement("div", { className: CONTENT_CLASS, onClick: e => this.handleClick(e), key: "content" },
                React.createElement("div", { className: "jp-MoreHorizIcon" }))
        ];
    }
}
exports.OutputPlaceholder = OutputPlaceholder;


/***/ }),

/***/ "K8RU":
/*!****************************************************!*\
  !*** ./node_modules/mdi-react/FileMultipleIcon.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var FileMultipleIcon = function FileMultipleIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M15,7H20.5L15,1.5V7M8,0H16L22,6V18C22,19.1 21.1,20 20,20H8C6.89,20 6,19.1 6,18V2C6,0.9 6.9,0 8,0M4,4V22H20V24H4C2.9,24 2,23.1 2,22V4H4Z' })
  );
};

module.exports = FileMultipleIcon;


/***/ }),

/***/ "KAEN":
/*!********************************************!*\
  !*** ./node_modules/elliptic/package.json ***!
  \********************************************/
/*! exports provided: name, version, description, main, files, scripts, repository, keywords, author, license, bugs, homepage, devDependencies, dependencies, default */
/***/ (function(module) {

module.exports = {"name":"elliptic","version":"6.4.1","description":"EC cryptography","main":"lib/elliptic.js","files":["lib"],"scripts":{"jscs":"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js","jshint":"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js","lint":"npm run jscs && npm run jshint","unit":"istanbul test _mocha --reporter=spec test/index.js","test":"npm run lint && npm run unit","version":"grunt dist && git add dist/"},"repository":{"type":"git","url":"git@github.com:indutny/elliptic"},"keywords":["EC","Elliptic","curve","Cryptography"],"author":"Fedor Indutny <fedor@indutny.com>","license":"MIT","bugs":{"url":"https://github.com/indutny/elliptic/issues"},"homepage":"https://github.com/indutny/elliptic","devDependencies":{"brfs":"^1.4.3","coveralls":"^2.11.3","grunt":"^0.4.5","grunt-browserify":"^5.0.0","grunt-cli":"^1.2.0","grunt-contrib-connect":"^1.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^1.0.1","grunt-mocha-istanbul":"^3.0.1","grunt-saucelabs":"^8.6.2","istanbul":"^0.4.2","jscs":"^2.9.0","jshint":"^2.6.0","mocha":"^2.1.0"},"dependencies":{"bn.js":"^4.4.0","brorand":"^1.0.1","hash.js":"^1.0.0","hmac-drbg":"^1.0.0","inherits":"^2.0.1","minimalistic-assert":"^1.0.0","minimalistic-crypto-utils":"^1.0.0"}};

/***/ }),

/***/ "KEyW":
/*!***********************************************!*\
  !*** ./node_modules/mdi-react/ArrowUpIcon.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var ArrowUpIcon = function ArrowUpIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M13,20H11V8L5.5,13.5L4.08,12.08L12,4.16L19.92,12.08L18.5,13.5L13,8V20Z' })
  );
};

module.exports = ArrowUpIcon;


/***/ }),

/***/ "KFnn":
/*!*****************************************************************!*\
  !*** ./node_modules/react-day-picker/lib/src/ModifiersUtils.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.dayMatchesModifier = dayMatchesModifier;
exports.getModifiersForDay = getModifiersForDay;

var _DateUtils = __webpack_require__(/*! ./DateUtils */ "mHnu");

var _Helpers = __webpack_require__(/*! ./Helpers */ "VJCR");

/**
 * Return `true` if a date matches the specified modifier.
 *
 * @export
 * @param {Date} day
 * @param {Any} modifier
 * @return {Boolean}
 */
function dayMatchesModifier(day, modifier) {
  if (!modifier) {
    return false;
  }
  var arr = Array.isArray(modifier) ? modifier : [modifier];
  return arr.some(function (mod) {
    if (!mod) {
      return false;
    }
    if (mod instanceof Date) {
      return (0, _DateUtils.isSameDay)(day, mod);
    }
    if ((0, _Helpers.isRangeOfDates)(mod)) {
      return (0, _DateUtils.isDayInRange)(day, mod);
    }
    if (mod.after && mod.before && (0, _DateUtils.isDayAfter)(mod.before, mod.after)) {
      return (0, _DateUtils.isDayAfter)(day, mod.after) && (0, _DateUtils.isDayBefore)(day, mod.before);
    }
    if (mod.after && mod.before && ((0, _DateUtils.isDayAfter)(mod.after, mod.before) || (0, _DateUtils.isSameDay)(mod.after, mod.before))) {
      return (0, _DateUtils.isDayAfter)(day, mod.after) || (0, _DateUtils.isDayBefore)(day, mod.before);
    }
    if (mod.after) {
      return (0, _DateUtils.isDayAfter)(day, mod.after);
    }
    if (mod.before) {
      return (0, _DateUtils.isDayBefore)(day, mod.before);
    }
    if (mod.daysOfWeek) {
      return mod.daysOfWeek.some(function (dayOfWeek) {
        return day.getDay() === dayOfWeek;
      });
    }
    if (typeof mod === 'function') {
      return mod(day);
    }
    return false;
  });
}

/**
 * Return the modifiers matching the given day for the given
 * object of modifiers.
 *
 * @export
 * @param {Date} day
 * @param {Object} [modifiersObj={}]
 * @return {Array}
 */
function getModifiersForDay(day) {
  var modifiersObj = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

  return Object.keys(modifiersObj).reduce(function (modifiers, modifierName) {
    var value = modifiersObj[modifierName];
    if (dayMatchesModifier(day, value)) {
      modifiers.push(modifierName);
    }
    return modifiers;
  }, []);
}

exports.default = { dayMatchesModifier: dayMatchesModifier, getModifiersForDay: getModifiersForDay };
//# sourceMappingURL=ModifiersUtils.js.map

/***/ }),

/***/ "KFpz":
/*!***********************************************!*\
  !*** ./node_modules/base16/lib/codeschool.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'codeschool',
  author: 'brettof86',
  base00: '#232c31',
  base01: '#1c3657',
  base02: '#2a343a',
  base03: '#3f4944',
  base04: '#84898c',
  base05: '#9ea7a6',
  base06: '#a7cfa3',
  base07: '#b5d8f6',
  base08: '#2a5491',
  base09: '#43820d',
  base0A: '#a03b1e',
  base0B: '#237986',
  base0C: '#b02f30',
  base0D: '#484d79',
  base0E: '#c59820',
  base0F: '#c98344'
};
module.exports = exports['default'];

/***/ }),

/***/ "KItQ":
/*!**************************************************************!*\
  !*** ./node_modules/@jupyterlab/application/style/index.css ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "aQ04");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "KKbn":
/*!***********************************************************************!*\
  !*** ./node_modules/@jupyter-widgets/jupyterlab-manager/lib/index.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const plugin_1 = __importDefault(__webpack_require__(/*! ./plugin */ "tn3U"));
exports.default = plugin_1.default;


/***/ }),

/***/ "KL9H":
/*!************************************************!*\
  !*** ./node_modules/fbjs/lib/UserAgentData.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

/**
 * Usage note:
 * This module makes a best effort to export the same data we would internally.
 * At Facebook we use a server-generated module that does the parsing and
 * exports the data for the client to use. We can't rely on a server-side
 * implementation in open source so instead we make use of an open source
 * library to do the heavy lifting and then make some adjustments as necessary.
 * It's likely there will be some differences. Some we can smooth over.
 * Others are going to be harder.
 */



var UAParser = __webpack_require__(/*! ua-parser-js */ "K4CH");

var UNKNOWN = 'Unknown';

var PLATFORM_MAP = {
  'Mac OS': 'Mac OS X'
};

/**
 * Convert from UAParser platform name to what we expect.
 */
function convertPlatformName(name) {
  return PLATFORM_MAP[name] || name;
}

/**
 * Get the version number in parts. This is very naive. We actually get major
 * version as a part of UAParser already, which is generally good enough, but
 * let's get the minor just in case.
 */
function getBrowserVersion(version) {
  if (!version) {
    return {
      major: '',
      minor: ''
    };
  }
  var parts = version.split('.');
  return {
    major: parts[0],
    minor: parts[1]
  };
}

/**
 * Get the UA data fom UAParser and then convert it to the format we're
 * expecting for our APIS.
 */
var parser = new UAParser();
var results = parser.getResult();

// Do some conversion first.
var browserVersionData = getBrowserVersion(results.browser.version);
var uaData = {
  browserArchitecture: results.cpu.architecture || UNKNOWN,
  browserFullVersion: results.browser.version || UNKNOWN,
  browserMinorVersion: browserVersionData.minor || UNKNOWN,
  browserName: results.browser.name || UNKNOWN,
  browserVersion: results.browser.major || UNKNOWN,
  deviceName: results.device.model || UNKNOWN,
  engineName: results.engine.name || UNKNOWN,
  engineVersion: results.engine.version || UNKNOWN,
  platformArchitecture: results.cpu.architecture || UNKNOWN,
  platformName: convertPlatformName(results.os.name) || UNKNOWN,
  platformVersion: results.os.version || UNKNOWN,
  platformFullVersion: results.os.version || UNKNOWN
};

module.exports = uaData;

/***/ }),

/***/ "KMkd":
/*!************************************************!*\
  !*** ./node_modules/lodash/_listCacheClear.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * Removes all key-value entries from the list cache.
 *
 * @private
 * @name clear
 * @memberOf ListCache
 */
function listCacheClear() {
  this.__data__ = [];
  this.size = 0;
}

module.exports = listCacheClear;


/***/ }),

/***/ "KQs1":
/*!*****************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeScattergeoIcon.js ***!
  \*****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeScattergeoIcon = function TraceTypeScattergeoIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement('path', { fill: 'none', d: 'M0 0h46v46H0z' }),
        _react2.default.createElement('path', { fill: '#25fdfc', stroke: '#fff', d: 'M32.05 26.375l-2.3 3.45-4.6 1.15-2.3-2.3H19.4l-6.15 1.15-3.45-2.3 3.85-4.6v-3.45h5.163l4.187 3 4.45-3 9.2 6.9h-4.6z', strokeMiterlimit: '10' }),
        _react2.default.createElement('path', { fill: '#25fdfc', stroke: '#fff', d: 'M36.65 26.375l-9.2-6.9-4.45 3-4.187-3H13.65l-2.875-1.725v-2.3l-1.15-1.15-1.15 1.15-1.15-1.15V9.7h2.3l2.3-1.15h2.3l3.45 2.3h3.45l4.6-2.3 3.45 3.45-3.45 3.45h5.75v-2.3h3.45v1.15l1.15 1.15 1.15-1.15 3.45 3.45v3.45H36.65v5.175zm-9.775 7.475L25.725 35h-1.15l.575-4.025-2.3-2.3H19.4l-6.15 1.15 7.875 4.025v2.3l3.45 2.3h2.3l1.15-1.15V35l-1.15-1.15z', strokeMiterlimit: '10' }),
        _react2.default.createElement('circle', { cx: '37.5', cy: '18.5', r: '1', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '23', cy: '18.5', r: '2', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '11.5', cy: '12.5', r: '1', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '16.5', cy: '22.5', r: '1', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '14.5', cy: '26.5', r: '1', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '26.5', cy: '25.5', r: '3', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '14.5', cy: '15.5', r: '1', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '21.5', cy: '24.5', r: '1', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '24.5', cy: '12.5', r: '1.5', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '31.5', cy: '18.5', r: '1', fill: '#1d9bfb' })
    );
};

exports.default = TraceTypeScattergeoIcon;

/***/ }),

/***/ "KSF8":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/vi.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var vi = moment.defineLocale('vi', {
    months : 'tháng 1_tháng 2_tháng 3_tháng 4_tháng 5_tháng 6_tháng 7_tháng 8_tháng 9_tháng 10_tháng 11_tháng 12'.split('_'),
    monthsShort : 'Th01_Th02_Th03_Th04_Th05_Th06_Th07_Th08_Th09_Th10_Th11_Th12'.split('_'),
    monthsParseExact : true,
    weekdays : 'chủ nhật_thứ hai_thứ ba_thứ tư_thứ năm_thứ sáu_thứ bảy'.split('_'),
    weekdaysShort : 'CN_T2_T3_T4_T5_T6_T7'.split('_'),
    weekdaysMin : 'CN_T2_T3_T4_T5_T6_T7'.split('_'),
    weekdaysParseExact : true,
    meridiemParse: /sa|ch/i,
    isPM : function (input) {
        return /^ch$/i.test(input);
    },
    meridiem : function (hours, minutes, isLower) {
        if (hours < 12) {
            return isLower ? 'sa' : 'SA';
        } else {
            return isLower ? 'ch' : 'CH';
        }
    },
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM [năm] YYYY',
        LLL : 'D MMMM [năm] YYYY HH:mm',
        LLLL : 'dddd, D MMMM [năm] YYYY HH:mm',
        l : 'DD/M/YYYY',
        ll : 'D MMM YYYY',
        lll : 'D MMM YYYY HH:mm',
        llll : 'ddd, D MMM YYYY HH:mm'
    },
    calendar : {
        sameDay: '[Hôm nay lúc] LT',
        nextDay: '[Ngày mai lúc] LT',
        nextWeek: 'dddd [tuần tới lúc] LT',
        lastDay: '[Hôm qua lúc] LT',
        lastWeek: 'dddd [tuần rồi lúc] LT',
        sameElse: 'L'
    },
    relativeTime : {
        future : '%s tới',
        past : '%s trước',
        s : 'vài giây',
        ss : '%d giây' ,
        m : 'một phút',
        mm : '%d phút',
        h : 'một giờ',
        hh : '%d giờ',
        d : 'một ngày',
        dd : '%d ngày',
        M : 'một tháng',
        MM : '%d tháng',
        y : 'một năm',
        yy : '%d năm'
    },
    dayOfMonthOrdinalParse: /\d{1,2}/,
    ordinal : function (number) {
        return number;
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return vi;

})));


/***/ }),

/***/ "KTz0":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/me.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var translator = {
    words: { //Different grammatical cases
        ss: ['sekund', 'sekunda', 'sekundi'],
        m: ['jedan minut', 'jednog minuta'],
        mm: ['minut', 'minuta', 'minuta'],
        h: ['jedan sat', 'jednog sata'],
        hh: ['sat', 'sata', 'sati'],
        dd: ['dan', 'dana', 'dana'],
        MM: ['mjesec', 'mjeseca', 'mjeseci'],
        yy: ['godina', 'godine', 'godina']
    },
    correctGrammaticalCase: function (number, wordKey) {
        return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]);
    },
    translate: function (number, withoutSuffix, key) {
        var wordKey = translator.words[key];
        if (key.length === 1) {
            return withoutSuffix ? wordKey[0] : wordKey[1];
        } else {
            return number + ' ' + translator.correctGrammaticalCase(number, wordKey);
        }
    }
};

var me = moment.defineLocale('me', {
    months: 'januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar'.split('_'),
    monthsShort: 'jan._feb._mar._apr._maj_jun_jul_avg._sep._okt._nov._dec.'.split('_'),
    monthsParseExact : true,
    weekdays: 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'),
    weekdaysShort: 'ned._pon._uto._sri._čet._pet._sub.'.split('_'),
    weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'),
    weekdaysParseExact : true,
    longDateFormat: {
        LT: 'H:mm',
        LTS : 'H:mm:ss',
        L: 'DD.MM.YYYY',
        LL: 'D. MMMM YYYY',
        LLL: 'D. MMMM YYYY H:mm',
        LLLL: 'dddd, D. MMMM YYYY H:mm'
    },
    calendar: {
        sameDay: '[danas u] LT',
        nextDay: '[sjutra u] LT',

        nextWeek: function () {
            switch (this.day()) {
                case 0:
                    return '[u] [nedjelju] [u] LT';
                case 3:
                    return '[u] [srijedu] [u] LT';
                case 6:
                    return '[u] [subotu] [u] LT';
                case 1:
                case 2:
                case 4:
                case 5:
                    return '[u] dddd [u] LT';
            }
        },
        lastDay  : '[juče u] LT',
        lastWeek : function () {
            var lastWeekDays = [
                '[prošle] [nedjelje] [u] LT',
                '[prošlog] [ponedjeljka] [u] LT',
                '[prošlog] [utorka] [u] LT',
                '[prošle] [srijede] [u] LT',
                '[prošlog] [četvrtka] [u] LT',
                '[prošlog] [petka] [u] LT',
                '[prošle] [subote] [u] LT'
            ];
            return lastWeekDays[this.day()];
        },
        sameElse : 'L'
    },
    relativeTime : {
        future : 'za %s',
        past   : 'prije %s',
        s      : 'nekoliko sekundi',
        ss     : translator.translate,
        m      : translator.translate,
        mm     : translator.translate,
        h      : translator.translate,
        hh     : translator.translate,
        d      : 'dan',
        dd     : translator.translate,
        M      : 'mjesec',
        MM     : translator.translate,
        y      : 'godinu',
        yy     : translator.translate
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return me;

})));


/***/ }),

/***/ "KUxP":
/*!********************************************************!*\
  !*** ./node_modules/core-js/library/modules/_fails.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = function (exec) {
  try {
    return !!exec();
  } catch (e) {
    return true;
  }
};


/***/ }),

/***/ "Ka7v":
/*!*********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotContourIcon.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotContourIcon = function PlotContourIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M11.188 4c4.938 0 10.688 1.625 13.063 3.75 2.938 2.5 4.813 6 5.063 9.875.313 2.375-.625 4.75-2.25 6.625-3.188 2.813-7.313 4.313-11.625 4.313-2.875.125-5.688-.938-7.813-2.938-5.75-5.75-6.688-16.313-3.25-19.75C5.626 4.687 8.001 4 11.189 4m-.001-1.312c-3.188 0-6.125.625-7.75 2.25-4.125 4-2.75 15.438 3.25 21.438a11.902 11.902 0 0 0 8.75 3.375c4.563 0 9.125-1.625 12.563-4.688 4.125-4.125 3.75-12.938-2.813-18.5-2.625-2.313-8.813-3.875-14-3.875zm1.75 6.375c3.875 0 7.188 1.063 8.125 2 1.625 1.5 2.375 3.5 2.375 5.625.188 1.875-.5 3.688-1.813 5.063-1.25 1.063-2.813 1.688-4.563 1.563-2.25 0-4.375-.938-6-2.5-3.75-3.75-5.438-8.688-3.625-10.563.813-.5 2.438-1.188 5.5-1.188m.001-1.313c-2.688 0-5.063.5-6.25 1.563C4 12.001 6.25 17.876 10.251 21.751c1.875 1.875 4.313 2.938 6.938 2.938 2 0 4-.688 5.5-2.125 3.188-3.75 2.938-9.25-.688-12.688-1.438-1.188-5.438-2.125-9.063-2.125zm2 4.625c.5 0 1.063.313 1.438.563 1.875 1.875 2.813 4.5 2.563 4.938a2.002 2.002 0 0 1-1.75 1.063c-1.063-.125-2.125-.688-2.938-1.313-2.25-1.875-2.375-3.063-2.25-3.875 0-.125.125-.313.125-.313.688-.625 1.75-1.063 2.813-1.063m-.001-1.312c-1.875 0-4 1.063-4.25 2.125-.688 2 .625 3.75 2.625 5.375a7.121 7.121 0 0 0 3.875 1.563c1.188 0 2.25-.5 2.813-1.438.938-1.5-.813-4.813-2.688-6.688-.625-.563-1.438-1.063-2.375-.938' })
    );
};

exports.default = PlotContourIcon;

/***/ }),

/***/ "KavO":
/*!**************************************************!*\
  !*** ./node_modules/source-map/lib/array-set.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* -*- Mode: js; js-indent-level: 2; -*- */
/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var util = __webpack_require__(/*! ./util */ "Cbry");
var has = Object.prototype.hasOwnProperty;
var hasNativeMap = typeof Map !== "undefined";

/**
 * A data structure which is a combination of an array and a set. Adding a new
 * member is O(1), testing for membership is O(1), and finding the index of an
 * element is O(1). Removing elements from the set is not supported. Only
 * strings are supported for membership.
 */
function ArraySet() {
  this._array = [];
  this._set = hasNativeMap ? new Map() : Object.create(null);
}

/**
 * Static method for creating ArraySet instances from an existing array.
 */
ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  var set = new ArraySet();
  for (var i = 0, len = aArray.length; i < len; i++) {
    set.add(aArray[i], aAllowDuplicates);
  }
  return set;
};

/**
 * Return how many unique items are in this ArraySet. If duplicates have been
 * added, than those do not count towards the size.
 *
 * @returns Number
 */
ArraySet.prototype.size = function ArraySet_size() {
  return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
};

/**
 * Add the given string to this set.
 *
 * @param String aStr
 */
ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
  var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  var idx = this._array.length;
  if (!isDuplicate || aAllowDuplicates) {
    this._array.push(aStr);
  }
  if (!isDuplicate) {
    if (hasNativeMap) {
      this._set.set(aStr, idx);
    } else {
      this._set[sStr] = idx;
    }
  }
};

/**
 * Is the given string a member of this set?
 *
 * @param String aStr
 */
ArraySet.prototype.has = function ArraySet_has(aStr) {
  if (hasNativeMap) {
    return this._set.has(aStr);
  } else {
    var sStr = util.toSetString(aStr);
    return has.call(this._set, sStr);
  }
};

/**
 * What is the index of the given string in the array?
 *
 * @param String aStr
 */
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  if (hasNativeMap) {
    var idx = this._set.get(aStr);
    if (idx >= 0) {
        return idx;
    }
  } else {
    var sStr = util.toSetString(aStr);
    if (has.call(this._set, sStr)) {
      return this._set[sStr];
    }
  }

  throw new Error('"' + aStr + '" is not in the set.');
};

/**
 * What is the element at the given index?
 *
 * @param Number aIdx
 */
ArraySet.prototype.at = function ArraySet_at(aIdx) {
  if (aIdx >= 0 && aIdx < this._array.length) {
    return this._array[aIdx];
  }
  throw new Error('No element indexed by ' + aIdx);
};

/**
 * Returns the array representation of this set (which has the proper indices
 * indicated by indexOf). Note that this is a copy of the internal array used
 * for storing the members so that no one can mess with internal state.
 */
ArraySet.prototype.toArray = function ArraySet_toArray() {
  return this._array.slice();
};

exports.ArraySet = ArraySet;


/***/ }),

/***/ "Kdc5":
/*!****************************************************************!*\
  !*** ./node_modules/@jupyterlab/notebook/lib/widgetfactory.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const docregistry_1 = __webpack_require__(/*! @jupyterlab/docregistry */ "jTF0");
const default_toolbar_1 = __webpack_require__(/*! ./default-toolbar */ "jdEz");
const panel_1 = __webpack_require__(/*! ./panel */ "RNiT");
const widget_1 = __webpack_require__(/*! ./widget */ "qZRx");
/**
 * A widget factory for notebook panels.
 */
class NotebookWidgetFactory extends docregistry_1.ABCWidgetFactory {
    /**
     * Construct a new notebook widget factory.
     *
     * @param options - The options used to construct the factory.
     */
    constructor(options) {
        super(options);
        this.rendermime = options.rendermime;
        this.contentFactory =
            options.contentFactory || panel_1.NotebookPanel.defaultContentFactory;
        this.mimeTypeService = options.mimeTypeService;
        this._editorConfig =
            options.editorConfig || widget_1.StaticNotebook.defaultEditorConfig;
    }
    /**
     * A configuration object for cell editor settings.
     */
    get editorConfig() {
        return this._editorConfig;
    }
    set editorConfig(value) {
        this._editorConfig = value;
    }
    /**
     * Create a new widget.
     *
     * #### Notes
     * The factory will start the appropriate kernel and populate
     * the default toolbar items using `ToolbarItems.populateDefaults`.
     */
    createNewWidget(context) {
        let rendermime = this.rendermime.clone({ resolver: context.urlResolver });
        let nbOptions = {
            rendermime,
            contentFactory: this.contentFactory,
            mimeTypeService: this.mimeTypeService,
            editorConfig: this._editorConfig
        };
        let content = this.contentFactory.createNotebook(nbOptions);
        return new panel_1.NotebookPanel({ context, content });
    }
    /**
     * Default factory for toolbar items to be added after the widget is created.
     */
    defaultToolbarFactory(widget) {
        return default_toolbar_1.ToolbarItems.getDefaultItems(widget);
    }
}
exports.NotebookWidgetFactory = NotebookWidgetFactory;


/***/ }),

/***/ "KfNM":
/*!************************************************!*\
  !*** ./node_modules/lodash/_objectToString.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/** Used for built-in method references. */
var objectProto = Object.prototype;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var nativeObjectToString = objectProto.toString;

/**
 * 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);
}

module.exports = objectToString;


/***/ }),

/***/ "KfSR":
/*!*************************************************!*\
  !*** ./node_modules/reactcss/lib/autoprefix.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.autoprefix = undefined;

var _forOwn2 = __webpack_require__(/*! lodash/forOwn */ "Ag8Z");

var _forOwn3 = _interopRequireDefault(_forOwn2);

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var transforms = {
  borderRadius: function borderRadius(value) {
    return {
      msBorderRadius: value,
      MozBorderRadius: value,
      OBorderRadius: value,
      WebkitBorderRadius: value,
      borderRadius: value
    };
  },
  boxShadow: function boxShadow(value) {
    return {
      msBoxShadow: value,
      MozBoxShadow: value,
      OBoxShadow: value,
      WebkitBoxShadow: value,
      boxShadow: value
    };
  },
  userSelect: function userSelect(value) {
    return {
      WebkitTouchCallout: value,
      KhtmlUserSelect: value,
      MozUserSelect: value,
      msUserSelect: value,
      WebkitUserSelect: value,
      userSelect: value
    };
  },

  flex: function flex(value) {
    return {
      WebkitBoxFlex: value,
      MozBoxFlex: value,
      WebkitFlex: value,
      msFlex: value,
      flex: value
    };
  },
  flexBasis: function flexBasis(value) {
    return {
      WebkitFlexBasis: value,
      flexBasis: value
    };
  },
  justifyContent: function justifyContent(value) {
    return {
      WebkitJustifyContent: value,
      justifyContent: value
    };
  },

  transition: function transition(value) {
    return {
      msTransition: value,
      MozTransition: value,
      OTransition: value,
      WebkitTransition: value,
      transition: value
    };
  },

  transform: function transform(value) {
    return {
      msTransform: value,
      MozTransform: value,
      OTransform: value,
      WebkitTransform: value,
      transform: value
    };
  },
  absolute: function absolute(value) {
    var direction = value && value.split(' ');
    return {
      position: 'absolute',
      top: direction && direction[0],
      right: direction && direction[1],
      bottom: direction && direction[2],
      left: direction && direction[3]
    };
  },
  extend: function extend(name, otherElementStyles) {
    var otherStyle = otherElementStyles[name];
    if (otherStyle) {
      return otherStyle;
    }
    return {
      'extend': name
    };
  }
};

var autoprefix = exports.autoprefix = function autoprefix(elements) {
  var prefixed = {};
  (0, _forOwn3.default)(elements, function (styles, element) {
    var expanded = {};
    (0, _forOwn3.default)(styles, function (value, key) {
      var transform = transforms[key];
      if (transform) {
        expanded = _extends({}, expanded, transform(value));
      } else {
        expanded[key] = value;
      }
    });
    prefixed[element] = expanded;
  });
  return prefixed;
};

exports.default = autoprefix;

/***/ }),

/***/ "Ki94":
/*!***************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/fileeditor/style/index.css ***!
  \***************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.jp-FileEditor {\n}\n\n/*-----------------------------------------------------------------------------\n| Presentation Mode (.jp-mod-presentationMode)\n|----------------------------------------------------------------------------*/\n\n.jp-mod-presentationMode .jp-FileEditor {\n  --jp-code-font-size: var(--jp-code-presentation-font-size);\n}\n", ""]);

// exports


/***/ }),

/***/ "Kta1":
/*!***********************************************************************!*\
  !*** ./node_modules/@jupyterlab/tabmanager-extension/style/index.css ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "n/bZ");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "Ku0u":
/*!********************************************************!*\
  !*** ./node_modules/codemirror/addon/dialog/dialog.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

// Open simple dialogs on top of an editor. Relies on dialog.css.

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"));
  else {}
})(function(CodeMirror) {
  function dialogDiv(cm, template, bottom) {
    var wrap = cm.getWrapperElement();
    var dialog;
    dialog = wrap.appendChild(document.createElement("div"));
    if (bottom)
      dialog.className = "CodeMirror-dialog CodeMirror-dialog-bottom";
    else
      dialog.className = "CodeMirror-dialog CodeMirror-dialog-top";

    if (typeof template == "string") {
      dialog.innerHTML = template;
    } else { // Assuming it's a detached DOM element.
      dialog.appendChild(template);
    }
    CodeMirror.addClass(wrap, 'dialog-opened');
    return dialog;
  }

  function closeNotification(cm, newVal) {
    if (cm.state.currentNotificationClose)
      cm.state.currentNotificationClose();
    cm.state.currentNotificationClose = newVal;
  }

  CodeMirror.defineExtension("openDialog", function(template, callback, options) {
    if (!options) options = {};

    closeNotification(this, null);

    var dialog = dialogDiv(this, template, options.bottom);
    var closed = false, me = this;
    function close(newVal) {
      if (typeof newVal == 'string') {
        inp.value = newVal;
      } else {
        if (closed) return;
        closed = true;
        CodeMirror.rmClass(dialog.parentNode, 'dialog-opened');
        dialog.parentNode.removeChild(dialog);
        me.focus();

        if (options.onClose) options.onClose(dialog);
      }
    }

    var inp = dialog.getElementsByTagName("input")[0], button;
    if (inp) {
      inp.focus();

      if (options.value) {
        inp.value = options.value;
        if (options.selectValueOnOpen !== false) {
          inp.select();
        }
      }

      if (options.onInput)
        CodeMirror.on(inp, "input", function(e) { options.onInput(e, inp.value, close);});
      if (options.onKeyUp)
        CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);});

      CodeMirror.on(inp, "keydown", function(e) {
        if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; }
        if (e.keyCode == 27 || (options.closeOnEnter !== false && e.keyCode == 13)) {
          inp.blur();
          CodeMirror.e_stop(e);
          close();
        }
        if (e.keyCode == 13) callback(inp.value, e);
      });

      if (options.closeOnBlur !== false) CodeMirror.on(inp, "blur", close);
    } else if (button = dialog.getElementsByTagName("button")[0]) {
      CodeMirror.on(button, "click", function() {
        close();
        me.focus();
      });

      if (options.closeOnBlur !== false) CodeMirror.on(button, "blur", close);

      button.focus();
    }
    return close;
  });

  CodeMirror.defineExtension("openConfirm", function(template, callbacks, options) {
    closeNotification(this, null);
    var dialog = dialogDiv(this, template, options && options.bottom);
    var buttons = dialog.getElementsByTagName("button");
    var closed = false, me = this, blurring = 1;
    function close() {
      if (closed) return;
      closed = true;
      CodeMirror.rmClass(dialog.parentNode, 'dialog-opened');
      dialog.parentNode.removeChild(dialog);
      me.focus();
    }
    buttons[0].focus();
    for (var i = 0; i < buttons.length; ++i) {
      var b = buttons[i];
      (function(callback) {
        CodeMirror.on(b, "click", function(e) {
          CodeMirror.e_preventDefault(e);
          close();
          if (callback) callback(me);
        });
      })(callbacks[i]);
      CodeMirror.on(b, "blur", function() {
        --blurring;
        setTimeout(function() { if (blurring <= 0) close(); }, 200);
      });
      CodeMirror.on(b, "focus", function() { ++blurring; });
    }
  });

  /*
   * openNotification
   * Opens a notification, that can be closed with an optional timer
   * (default 5000ms timer) and always closes on click.
   *
   * If a notification is opened while another is opened, it will close the
   * currently opened one and open the new one immediately.
   */
  CodeMirror.defineExtension("openNotification", function(template, options) {
    closeNotification(this, close);
    var dialog = dialogDiv(this, template, options && options.bottom);
    var closed = false, doneTimer;
    var duration = options && typeof options.duration !== "undefined" ? options.duration : 5000;

    function close() {
      if (closed) return;
      closed = true;
      clearTimeout(doneTimer);
      CodeMirror.rmClass(dialog.parentNode, 'dialog-opened');
      dialog.parentNode.removeChild(dialog);
    }

    CodeMirror.on(dialog, 'click', function(e) {
      CodeMirror.e_preventDefault(e);
      close();
    });

    if (duration)
      doneTimer = setTimeout(close, duration);

    return close;
  });
});


/***/ }),

/***/ "Ku4m":
/*!******************************************!*\
  !*** ./node_modules/parse-asn1/index.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var asn1 = __webpack_require__(/*! ./asn1 */ "QRH4")
var aesid = __webpack_require__(/*! ./aesid.json */ "1w4i")
var fixProc = __webpack_require__(/*! ./fixProc */ "TdD3")
var ciphers = __webpack_require__(/*! browserify-aes */ "/ab2")
var compat = __webpack_require__(/*! pbkdf2 */ "oJl4")
var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer
module.exports = parseKeys

function parseKeys (buffer) {
  var password
  if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) {
    password = buffer.passphrase
    buffer = buffer.key
  }
  if (typeof buffer === 'string') {
    buffer = Buffer.from(buffer)
  }

  var stripped = fixProc(buffer, password)

  var type = stripped.tag
  var data = stripped.data
  var subtype, ndata
  switch (type) {
    case 'CERTIFICATE':
      ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo
      // falls through
    case 'PUBLIC KEY':
      if (!ndata) {
        ndata = asn1.PublicKey.decode(data, 'der')
      }
      subtype = ndata.algorithm.algorithm.join('.')
      switch (subtype) {
        case '1.2.840.113549.1.1.1':
          return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der')
        case '1.2.840.10045.2.1':
          ndata.subjectPrivateKey = ndata.subjectPublicKey
          return {
            type: 'ec',
            data: ndata
          }
        case '1.2.840.10040.4.1':
          ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der')
          return {
            type: 'dsa',
            data: ndata.algorithm.params
          }
        default: throw new Error('unknown key id ' + subtype)
      }
      throw new Error('unknown key type ' + type)
    case 'ENCRYPTED PRIVATE KEY':
      data = asn1.EncryptedPrivateKey.decode(data, 'der')
      data = decrypt(data, password)
      // falls through
    case 'PRIVATE KEY':
      ndata = asn1.PrivateKey.decode(data, 'der')
      subtype = ndata.algorithm.algorithm.join('.')
      switch (subtype) {
        case '1.2.840.113549.1.1.1':
          return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der')
        case '1.2.840.10045.2.1':
          return {
            curve: ndata.algorithm.curve,
            privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey
          }
        case '1.2.840.10040.4.1':
          ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der')
          return {
            type: 'dsa',
            params: ndata.algorithm.params
          }
        default: throw new Error('unknown key id ' + subtype)
      }
      throw new Error('unknown key type ' + type)
    case 'RSA PUBLIC KEY':
      return asn1.RSAPublicKey.decode(data, 'der')
    case 'RSA PRIVATE KEY':
      return asn1.RSAPrivateKey.decode(data, 'der')
    case 'DSA PRIVATE KEY':
      return {
        type: 'dsa',
        params: asn1.DSAPrivateKey.decode(data, 'der')
      }
    case 'EC PRIVATE KEY':
      data = asn1.ECPrivateKey.decode(data, 'der')
      return {
        curve: data.parameters.value,
        privateKey: data.privateKey
      }
    default: throw new Error('unknown key type ' + type)
  }
}
parseKeys.signature = asn1.signature
function decrypt (data, password) {
  var salt = data.algorithm.decrypt.kde.kdeparams.salt
  var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10)
  var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')]
  var iv = data.algorithm.decrypt.cipher.iv
  var cipherText = data.subjectPrivateKey
  var keylen = parseInt(algo.split('-')[1], 10) / 8
  var key = compat.pbkdf2Sync(password, salt, iters, keylen, 'sha1')
  var cipher = ciphers.createDecipheriv(algo, key, iv)
  var out = []
  out.push(cipher.update(cipherText))
  out.push(cipher.final())
  return Buffer.concat(out)
}


/***/ }),

/***/ "Kuxr":
/*!***************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/regex.js ***!
  \***************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



/*
 * make a regex for matching counter ids/names ie xaxis, xaxis2, xaxis10...
 *
 * @param {string} head: the head of the pattern, eg 'x' matches 'x', 'x2', 'x10' etc.
 *      'xy' is a special case for cartesian subplots: it matches 'x2y3' etc
 * @param {Optional(string)} tail: a fixed piece after the id
 *      eg counterRegex('scene', '.annotations') for scene2.annotations etc.
 * @param {boolean} openEnded: if true, the string may continue past the match.
 * @param {boolean} matchBeginning: if false, the string may start before the match.
 */
exports.counter = function(head, tail, openEnded, matchBeginning) {
    var fullTail = (tail || '') + (openEnded ? '' : '$');
    var startWithPrefix = matchBeginning === false ? '' : '^';
    if(head === 'xy') {
        return new RegExp(startWithPrefix + 'x([2-9]|[1-9][0-9]+)?y([2-9]|[1-9][0-9]+)?' + fullTail);
    }
    return new RegExp(startWithPrefix + head + '([2-9]|[1-9][0-9]+)?' + fullTail);
};


/***/ }),

/***/ "Kz5y":
/*!**************************************!*\
  !*** ./node_modules/lodash/_root.js ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var freeGlobal = __webpack_require__(/*! ./_freeGlobal */ "WFqU");

/** 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')();

module.exports = root;


/***/ }),

/***/ "L/Ch":
/*!***********************************************************!*\
  !*** ./node_modules/react-json-tree/lib/JSONArrayNode.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "QbLZ");

var _extends3 = _interopRequireDefault(_extends2);

var _objectWithoutProperties2 = __webpack_require__(/*! babel-runtime/helpers/objectWithoutProperties */ "jo6Y");

var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _JSONNestedNode = __webpack_require__(/*! ./JSONNestedNode */ "X834");

var _JSONNestedNode2 = _interopRequireDefault(_JSONNestedNode);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

// Returns the "n Items" string for this node,
// generating and caching it if it hasn't been created yet.
function createItemString(data) {
  return data.length + ' ' + (data.length !== 1 ? 'items' : 'item');
}

// Configures <JSONNestedNode> to render an Array
var JSONArrayNode = function JSONArrayNode(_ref) {
  var data = _ref.data,
      props = (0, _objectWithoutProperties3['default'])(_ref, ['data']);
  return _react2['default'].createElement(_JSONNestedNode2['default'], (0, _extends3['default'])({}, props, {
    data: data,
    nodeType: 'Array',
    nodeTypeIndicator: '[]',
    createItemString: createItemString,
    expandable: data.length > 0
  }));
};

JSONArrayNode.propTypes = {
  data: _propTypes2['default'].array
};

exports['default'] = JSONArrayNode;

/***/ }),

/***/ "L0q3":
/*!************************************************!*\
  !*** ./node_modules/draft-js/lib/BlockTree.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule BlockTree
 * @format
 * 
 */



var Immutable = __webpack_require__(/*! immutable */ "JPcv");

var emptyFunction = __webpack_require__(/*! fbjs/lib/emptyFunction */ "ohE5");
var findRangesImmutable = __webpack_require__(/*! ./findRangesImmutable */ "Taje");

var List = Immutable.List,
    Repeat = Immutable.Repeat,
    Record = Immutable.Record;


var returnTrue = emptyFunction.thatReturnsTrue;

var FINGERPRINT_DELIMITER = '-';

var defaultLeafRange = {
  start: null,
  end: null
};

var LeafRange = Record(defaultLeafRange);

var defaultDecoratorRange = {
  start: null,
  end: null,
  decoratorKey: null,
  leaves: null
};

var DecoratorRange = Record(defaultDecoratorRange);

var BlockTree = {
  /**
   * Generate a block tree for a given ContentBlock/decorator pair.
   */
  generate: function generate(contentState, block, decorator) {
    var textLength = block.getLength();
    if (!textLength) {
      return List.of(new DecoratorRange({
        start: 0,
        end: 0,
        decoratorKey: null,
        leaves: List.of(new LeafRange({ start: 0, end: 0 }))
      }));
    }

    var leafSets = [];
    var decorations = decorator ? decorator.getDecorations(block, contentState) : List(Repeat(null, textLength));

    var chars = block.getCharacterList();

    findRangesImmutable(decorations, areEqual, returnTrue, function (start, end) {
      leafSets.push(new DecoratorRange({
        start: start,
        end: end,
        decoratorKey: decorations.get(start),
        leaves: generateLeaves(chars.slice(start, end).toList(), start)
      }));
    });

    return List(leafSets);
  },

  /**
   * Create a string representation of the given tree map. This allows us
   * to rapidly determine whether a tree has undergone a significant
   * structural change.
   */
  getFingerprint: function getFingerprint(tree) {
    return tree.map(function (leafSet) {
      var decoratorKey = leafSet.get('decoratorKey');
      var fingerprintString = decoratorKey !== null ? decoratorKey + '.' + (leafSet.get('end') - leafSet.get('start')) : '';
      return '' + fingerprintString + '.' + leafSet.get('leaves').size;
    }).join(FINGERPRINT_DELIMITER);
  }
};

/**
 * Generate LeafRange records for a given character list.
 */
function generateLeaves(characters, offset) {
  var leaves = [];
  var inlineStyles = characters.map(function (c) {
    return c.getStyle();
  }).toList();
  findRangesImmutable(inlineStyles, areEqual, returnTrue, function (start, end) {
    leaves.push(new LeafRange({
      start: start + offset,
      end: end + offset
    }));
  });
  return List(leaves);
}

function areEqual(a, b) {
  return a === b;
}

module.exports = BlockTree;

/***/ }),

/***/ "L2EA":
/*!*********************************************************************!*\
  !*** ./node_modules/draft-js/lib/insertFragmentIntoContentState.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule insertFragmentIntoContentState
 * @format
 * 
 */



var BlockMapBuilder = __webpack_require__(/*! ./BlockMapBuilder */ "YeVe");
var ContentBlockNode = __webpack_require__(/*! ./ContentBlockNode */ "JL7T");
var Immutable = __webpack_require__(/*! immutable */ "JPcv");

var insertIntoList = __webpack_require__(/*! ./insertIntoList */ "Zf/v");
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");
var randomizeBlockMapKeys = __webpack_require__(/*! ./randomizeBlockMapKeys */ "V8dp");

var List = Immutable.List;


var updateExistingBlock = function updateExistingBlock(contentState, selectionState, blockMap, fragmentBlock, targetKey, targetOffset) {
  var targetBlock = blockMap.get(targetKey);
  var text = targetBlock.getText();
  var chars = targetBlock.getCharacterList();
  var finalKey = targetKey;
  var finalOffset = targetOffset + fragmentBlock.getText().length;

  var newBlock = targetBlock.merge({
    text: text.slice(0, targetOffset) + fragmentBlock.getText() + text.slice(targetOffset),
    characterList: insertIntoList(chars, fragmentBlock.getCharacterList(), targetOffset),
    data: fragmentBlock.getData()
  });

  return contentState.merge({
    blockMap: blockMap.set(targetKey, newBlock),
    selectionBefore: selectionState,
    selectionAfter: selectionState.merge({
      anchorKey: finalKey,
      anchorOffset: finalOffset,
      focusKey: finalKey,
      focusOffset: finalOffset,
      isBackward: false
    })
  });
};

/**
 * Appends text/characterList from the fragment first block to
 * target block.
 */
var updateHead = function updateHead(block, targetOffset, fragment) {
  var text = block.getText();
  var chars = block.getCharacterList();

  // Modify head portion of block.
  var headText = text.slice(0, targetOffset);
  var headCharacters = chars.slice(0, targetOffset);
  var appendToHead = fragment.first();

  return block.merge({
    text: headText + appendToHead.getText(),
    characterList: headCharacters.concat(appendToHead.getCharacterList()),
    type: headText ? block.getType() : appendToHead.getType(),
    data: appendToHead.getData()
  });
};

/**
 * Appends offset text/characterList from the target block to the last
 * fragment block.
 */
var updateTail = function updateTail(block, targetOffset, fragment) {
  // Modify tail portion of block.
  var text = block.getText();
  var chars = block.getCharacterList();

  // Modify head portion of block.
  var blockSize = text.length;
  var tailText = text.slice(targetOffset, blockSize);
  var tailCharacters = chars.slice(targetOffset, blockSize);
  var prependToTail = fragment.last();

  return prependToTail.merge({
    text: prependToTail.getText() + tailText,
    characterList: prependToTail.getCharacterList().concat(tailCharacters),
    data: prependToTail.getData()
  });
};

var getRootBlocks = function getRootBlocks(block, blockMap) {
  var headKey = block.getKey();
  var rootBlock = block;
  var rootBlocks = [];

  // sometimes the fragment head block will not be part of the blockMap itself this can happen when
  // the fragment head is used to update the target block, however when this does not happen we need
  // to make sure that we include it on the rootBlocks since the first block of a fragment is always a
  // fragment root block
  if (blockMap.get(headKey)) {
    rootBlocks.push(headKey);
  }

  while (rootBlock && rootBlock.getNextSiblingKey()) {
    var lastSiblingKey = rootBlock.getNextSiblingKey();

    if (!lastSiblingKey) {
      break;
    }

    rootBlocks.push(lastSiblingKey);
    rootBlock = blockMap.get(lastSiblingKey);
  }

  return rootBlocks;
};

var updateBlockMapLinks = function updateBlockMapLinks(blockMap, originalBlockMap, targetBlock, fragmentHeadBlock) {
  return blockMap.withMutations(function (blockMapState) {
    var targetKey = targetBlock.getKey();
    var headKey = fragmentHeadBlock.getKey();
    var targetNextKey = targetBlock.getNextSiblingKey();
    var targetParentKey = targetBlock.getParentKey();
    var fragmentRootBlocks = getRootBlocks(fragmentHeadBlock, blockMap);
    var lastRootFragmentBlockKey = fragmentRootBlocks[fragmentRootBlocks.length - 1];

    if (blockMapState.get(headKey)) {
      // update the fragment head when it is part of the blockMap otherwise
      blockMapState.setIn([targetKey, 'nextSibling'], headKey);
      blockMapState.setIn([headKey, 'prevSibling'], targetKey);
    } else {
      // update the target block that had the fragment head contents merged into it
      blockMapState.setIn([targetKey, 'nextSibling'], fragmentHeadBlock.getNextSiblingKey());
      blockMapState.setIn([fragmentHeadBlock.getNextSiblingKey(), 'prevSibling'], targetKey);
    }

    // update the last root block fragment
    blockMapState.setIn([lastRootFragmentBlockKey, 'nextSibling'], targetNextKey);

    // update the original target next block
    if (targetNextKey) {
      blockMapState.setIn([targetNextKey, 'prevSibling'], lastRootFragmentBlockKey);
    }

    // update fragment parent links
    fragmentRootBlocks.forEach(function (blockKey) {
      return blockMapState.setIn([blockKey, 'parent'], targetParentKey);
    });

    // update targetBlock parent child links
    if (targetParentKey) {
      var targetParent = blockMap.get(targetParentKey);
      var originalTargetParentChildKeys = targetParent.getChildKeys();

      var targetBlockIndex = originalTargetParentChildKeys.indexOf(targetKey);
      var insertionIndex = targetBlockIndex + 1;

      var newChildrenKeysArray = originalTargetParentChildKeys.toArray();

      // insert fragment children
      newChildrenKeysArray.splice.apply(newChildrenKeysArray, [insertionIndex, 0].concat(fragmentRootBlocks));

      blockMapState.setIn([targetParentKey, 'children'], List(newChildrenKeysArray));
    }
  });
};

var insertFragment = function insertFragment(contentState, selectionState, blockMap, fragment, targetKey, targetOffset) {
  var isTreeBasedBlockMap = blockMap.first() instanceof ContentBlockNode;
  var newBlockArr = [];
  var fragmentSize = fragment.size;
  var target = blockMap.get(targetKey);
  var head = fragment.first();
  var tail = fragment.last();
  var finalOffset = tail.getLength();
  var finalKey = tail.getKey();
  var shouldNotUpdateFromFragmentBlock = isTreeBasedBlockMap && (!target.getChildKeys().isEmpty() || !head.getChildKeys().isEmpty());

  blockMap.forEach(function (block, blockKey) {
    if (blockKey !== targetKey) {
      newBlockArr.push(block);
      return;
    }

    if (shouldNotUpdateFromFragmentBlock) {
      newBlockArr.push(block);
    } else {
      newBlockArr.push(updateHead(block, targetOffset, fragment));
    }

    // Insert fragment blocks after the head and before the tail.
    fragment
    // when we are updating the target block with the head fragment block we skip the first fragment
    // head since its contents have already been merged with the target block otherwise we include
    // the whole fragment
    .slice(shouldNotUpdateFromFragmentBlock ? 0 : 1, fragmentSize - 1).forEach(function (fragmentBlock) {
      return newBlockArr.push(fragmentBlock);
    });

    // update tail
    newBlockArr.push(updateTail(block, targetOffset, fragment));
  });

  var updatedBlockMap = BlockMapBuilder.createFromArray(newBlockArr);

  if (isTreeBasedBlockMap) {
    updatedBlockMap = updateBlockMapLinks(updatedBlockMap, blockMap, target, head);
  }

  return contentState.merge({
    blockMap: updatedBlockMap,
    selectionBefore: selectionState,
    selectionAfter: selectionState.merge({
      anchorKey: finalKey,
      anchorOffset: finalOffset,
      focusKey: finalKey,
      focusOffset: finalOffset,
      isBackward: false
    })
  });
};

var insertFragmentIntoContentState = function insertFragmentIntoContentState(contentState, selectionState, fragmentBlockMap) {
  !selectionState.isCollapsed() ?  true ? invariant(false, '`insertFragment` should only be called with a collapsed selection state.') : undefined : void 0;

  var blockMap = contentState.getBlockMap();
  var fragment = randomizeBlockMapKeys(fragmentBlockMap);
  var targetKey = selectionState.getStartKey();
  var targetOffset = selectionState.getStartOffset();

  var targetBlock = blockMap.get(targetKey);

  if (targetBlock instanceof ContentBlockNode) {
    !targetBlock.getChildKeys().isEmpty() ?  true ? invariant(false, '`insertFragment` should not be called when a container node is selected.') : undefined : void 0;
  }

  // When we insert a fragment with a single block we simply update the target block
  // with the contents of the inserted fragment block
  if (fragment.size === 1) {
    return updateExistingBlock(contentState, selectionState, blockMap, fragment.first(), targetKey, targetOffset);
  }

  return insertFragment(contentState, selectionState, blockMap, fragment, targetKey, targetOffset);
};

module.exports = insertFragmentIntoContentState;

/***/ }),

/***/ "L3zP":
/*!**********************************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/components/colorscale/scales.js ***!
  \**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var tinycolor = __webpack_require__(/*! tinycolor2 */ "Zss7");

var scales = {
    'Greys': [
        [0, 'rgb(0,0,0)'], [1, 'rgb(255,255,255)']
    ],

    'YlGnBu': [
        [0, 'rgb(8,29,88)'], [0.125, 'rgb(37,52,148)'],
        [0.25, 'rgb(34,94,168)'], [0.375, 'rgb(29,145,192)'],
        [0.5, 'rgb(65,182,196)'], [0.625, 'rgb(127,205,187)'],
        [0.75, 'rgb(199,233,180)'], [0.875, 'rgb(237,248,217)'],
        [1, 'rgb(255,255,217)']
    ],

    'Greens': [
        [0, 'rgb(0,68,27)'], [0.125, 'rgb(0,109,44)'],
        [0.25, 'rgb(35,139,69)'], [0.375, 'rgb(65,171,93)'],
        [0.5, 'rgb(116,196,118)'], [0.625, 'rgb(161,217,155)'],
        [0.75, 'rgb(199,233,192)'], [0.875, 'rgb(229,245,224)'],
        [1, 'rgb(247,252,245)']
    ],

    'YlOrRd': [
        [0, 'rgb(128,0,38)'], [0.125, 'rgb(189,0,38)'],
        [0.25, 'rgb(227,26,28)'], [0.375, 'rgb(252,78,42)'],
        [0.5, 'rgb(253,141,60)'], [0.625, 'rgb(254,178,76)'],
        [0.75, 'rgb(254,217,118)'], [0.875, 'rgb(255,237,160)'],
        [1, 'rgb(255,255,204)']
    ],

    'Bluered': [
        [0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']
    ],

    // modified RdBu based on
    // www.sandia.gov/~kmorel/documents/ColorMaps/ColorMapsExpanded.pdf
    'RdBu': [
        [0, 'rgb(5,10,172)'], [0.35, 'rgb(106,137,247)'],
        [0.5, 'rgb(190,190,190)'], [0.6, 'rgb(220,170,132)'],
        [0.7, 'rgb(230,145,90)'], [1, 'rgb(178,10,28)']
    ],

    // Scale for non-negative numeric values
    'Reds': [
        [0, 'rgb(220,220,220)'], [0.2, 'rgb(245,195,157)'],
        [0.4, 'rgb(245,160,105)'], [1, 'rgb(178,10,28)']
    ],

    // Scale for non-positive numeric values
    'Blues': [
        [0, 'rgb(5,10,172)'], [0.35, 'rgb(40,60,190)'],
        [0.5, 'rgb(70,100,245)'], [0.6, 'rgb(90,120,245)'],
        [0.7, 'rgb(106,137,247)'], [1, 'rgb(220,220,220)']
    ],

    'Picnic': [
        [0, 'rgb(0,0,255)'], [0.1, 'rgb(51,153,255)'],
        [0.2, 'rgb(102,204,255)'], [0.3, 'rgb(153,204,255)'],
        [0.4, 'rgb(204,204,255)'], [0.5, 'rgb(255,255,255)'],
        [0.6, 'rgb(255,204,255)'], [0.7, 'rgb(255,153,255)'],
        [0.8, 'rgb(255,102,204)'], [0.9, 'rgb(255,102,102)'],
        [1, 'rgb(255,0,0)']
    ],

    'Rainbow': [
        [0, 'rgb(150,0,90)'], [0.125, 'rgb(0,0,200)'],
        [0.25, 'rgb(0,25,255)'], [0.375, 'rgb(0,152,255)'],
        [0.5, 'rgb(44,255,150)'], [0.625, 'rgb(151,255,0)'],
        [0.75, 'rgb(255,234,0)'], [0.875, 'rgb(255,111,0)'],
        [1, 'rgb(255,0,0)']
    ],

    'Portland': [
        [0, 'rgb(12,51,131)'], [0.25, 'rgb(10,136,186)'],
        [0.5, 'rgb(242,211,56)'], [0.75, 'rgb(242,143,56)'],
        [1, 'rgb(217,30,30)']
    ],

    'Jet': [
        [0, 'rgb(0,0,131)'], [0.125, 'rgb(0,60,170)'],
        [0.375, 'rgb(5,255,255)'], [0.625, 'rgb(255,255,0)'],
        [0.875, 'rgb(250,0,0)'], [1, 'rgb(128,0,0)']
    ],

    'Hot': [
        [0, 'rgb(0,0,0)'], [0.3, 'rgb(230,0,0)'],
        [0.6, 'rgb(255,210,0)'], [1, 'rgb(255,255,255)']
    ],

    'Blackbody': [
        [0, 'rgb(0,0,0)'], [0.2, 'rgb(230,0,0)'],
        [0.4, 'rgb(230,210,0)'], [0.7, 'rgb(255,255,255)'],
        [1, 'rgb(160,200,255)']
    ],

    'Earth': [
        [0, 'rgb(0,0,130)'], [0.1, 'rgb(0,180,180)'],
        [0.2, 'rgb(40,210,40)'], [0.4, 'rgb(230,230,50)'],
        [0.6, 'rgb(120,70,20)'], [1, 'rgb(255,255,255)']
    ],

    'Electric': [
        [0, 'rgb(0,0,0)'], [0.15, 'rgb(30,0,100)'],
        [0.4, 'rgb(120,0,100)'], [0.6, 'rgb(160,90,0)'],
        [0.8, 'rgb(230,200,0)'], [1, 'rgb(255,250,220)']
    ],

    'Viridis': [
        [0, '#440154'], [0.06274509803921569, '#48186a'],
        [0.12549019607843137, '#472d7b'], [0.18823529411764706, '#424086'],
        [0.25098039215686274, '#3b528b'], [0.3137254901960784, '#33638d'],
        [0.3764705882352941, '#2c728e'], [0.4392156862745098, '#26828e'],
        [0.5019607843137255, '#21918c'], [0.5647058823529412, '#1fa088'],
        [0.6274509803921569, '#28ae80'], [0.6901960784313725, '#3fbc73'],
        [0.7529411764705882, '#5ec962'], [0.8156862745098039, '#84d44b'],
        [0.8784313725490196, '#addc30'], [0.9411764705882353, '#d8e219'],
        [1, '#fde725']
    ],

    'Cividis': [
        [0.000000, 'rgb(0,32,76)'], [0.058824, 'rgb(0,42,102)'],
        [0.117647, 'rgb(0,52,110)'], [0.176471, 'rgb(39,63,108)'],
        [0.235294, 'rgb(60,74,107)'], [0.294118, 'rgb(76,85,107)'],
        [0.352941, 'rgb(91,95,109)'], [0.411765, 'rgb(104,106,112)'],
        [0.470588, 'rgb(117,117,117)'], [0.529412, 'rgb(131,129,120)'],
        [0.588235, 'rgb(146,140,120)'], [0.647059, 'rgb(161,152,118)'],
        [0.705882, 'rgb(176,165,114)'], [0.764706, 'rgb(192,177,109)'],
        [0.823529, 'rgb(209,191,102)'], [0.882353, 'rgb(225,204,92)'],
        [0.941176, 'rgb(243,219,79)'], [1.000000, 'rgb(255,233,69)']
    ]
};

var defaultScale = scales.RdBu;

function getScale(scl, dflt) {
    if(!dflt) dflt = defaultScale;
    if(!scl) return dflt;

    function parseScale() {
        try {
            scl = scales[scl] || JSON.parse(scl);
        } catch(e) {
            scl = dflt;
        }
    }

    if(typeof scl === 'string') {
        parseScale();
        // occasionally scl is double-JSON encoded...
        if(typeof scl === 'string') parseScale();
    }

    if(!isValidScaleArray(scl)) return dflt;
    return scl;
}


function isValidScaleArray(scl) {
    var highestVal = 0;

    if(!Array.isArray(scl) || scl.length < 2) return false;

    if(!scl[0] || !scl[scl.length - 1]) return false;

    if(+scl[0][0] !== 0 || +scl[scl.length - 1][0] !== 1) return false;

    for(var i = 0; i < scl.length; i++) {
        var si = scl[i];

        if(si.length !== 2 || +si[0] < highestVal || !tinycolor(si[1]).isValid()) {
            return false;
        }

        highestVal = +si[0];
    }

    return true;
}

function isValidScale(scl) {
    if(scales[scl] !== undefined) return true;
    else return isValidScaleArray(scl);
}

module.exports = {
    scales: scales,
    defaultScale: defaultScale,

    get: getScale,
    isValid: isValidScale
};


/***/ }),

/***/ "L8xA":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_stackDelete.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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;
}

module.exports = stackDelete;


/***/ }),

/***/ "LGOv":
/*!**********************************************************!*\
  !*** ./node_modules/readable-stream/writable-browser.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(/*! ./lib/_stream_writable.js */ "3BRs");


/***/ }),

/***/ "LPzJ":
/*!********************************************************!*\
  !*** ./node_modules/react-day-picker/lib/src/Month.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _Weekdays = __webpack_require__(/*! ./Weekdays */ "Et+i");

var _Weekdays2 = _interopRequireDefault(_Weekdays);

var _Day = __webpack_require__(/*! ./Day */ "xSJi");

var _Day2 = _interopRequireDefault(_Day);

var _keys = __webpack_require__(/*! ./keys */ "VBVY");

var _ModifiersUtils = __webpack_require__(/*! ./ModifiersUtils */ "KFnn");

var ModifiersUtils = _interopRequireWildcard(_ModifiersUtils);

var _Helpers = __webpack_require__(/*! ./Helpers */ "VJCR");

var Helpers = _interopRequireWildcard(_Helpers);

var _DateUtils = __webpack_require__(/*! ./DateUtils */ "mHnu");

var DateUtils = _interopRequireWildcard(_DateUtils);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Month = function (_Component) {
  _inherits(Month, _Component);

  function Month() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, Month);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Month.__proto__ || Object.getPrototypeOf(Month)).call.apply(_ref, [this].concat(args))), _this), _this.renderDay = function (day) {
      var monthNumber = _this.props.month.getMonth();
      var propModifiers = Helpers.getModifiersFromProps(_this.props);
      var dayModifiers = ModifiersUtils.getModifiersForDay(day, propModifiers);
      if (DateUtils.isSameDay(day, new Date()) && !Object.prototype.hasOwnProperty.call(propModifiers, _this.props.classNames.today)) {
        dayModifiers.push(_this.props.classNames.today);
      }
      if (day.getMonth() !== monthNumber) {
        dayModifiers.push(_this.props.classNames.outside);
      }

      var isOutside = day.getMonth() !== monthNumber;
      var tabIndex = -1;
      // Focus on the first day of the month
      if (_this.props.onDayClick && !isOutside && day.getDate() === 1) {
        tabIndex = _this.props.tabIndex; // eslint-disable-line prefer-destructuring
      }
      var key = '' + day.getFullYear() + day.getMonth() + day.getDate();
      var modifiers = {};
      dayModifiers.forEach(function (modifier) {
        modifiers[modifier] = true;
      });

      return _react2.default.createElement(
        _Day2.default,
        {
          key: '' + (isOutside ? 'outside-' : '') + key,
          classNames: _this.props.classNames,
          day: day,
          modifiers: modifiers,
          modifiersStyles: _this.props.modifiersStyles,
          empty: isOutside && !_this.props.showOutsideDays && !_this.props.fixedWeeks,
          tabIndex: tabIndex,
          ariaLabel: _this.props.localeUtils.formatDay(day, _this.props.locale),
          ariaDisabled: isOutside || dayModifiers.indexOf('disabled') > -1,
          ariaSelected: dayModifiers.indexOf('selected') > -1,
          onClick: _this.props.onDayClick,
          onFocus: _this.props.onDayFocus,
          onKeyDown: _this.props.onDayKeyDown,
          onMouseEnter: _this.props.onDayMouseEnter,
          onMouseLeave: _this.props.onDayMouseLeave,
          onMouseDown: _this.props.onDayMouseDown,
          onMouseUp: _this.props.onDayMouseUp,
          onTouchEnd: _this.props.onDayTouchEnd,
          onTouchStart: _this.props.onDayTouchStart
        },
        _this.props.renderDay(day, modifiers)
      );
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(Month, [{
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _props = this.props,
          classNames = _props.classNames,
          month = _props.month,
          months = _props.months,
          fixedWeeks = _props.fixedWeeks,
          captionElement = _props.captionElement,
          weekdayElement = _props.weekdayElement,
          locale = _props.locale,
          localeUtils = _props.localeUtils,
          weekdaysLong = _props.weekdaysLong,
          weekdaysShort = _props.weekdaysShort,
          firstDayOfWeek = _props.firstDayOfWeek,
          onCaptionClick = _props.onCaptionClick,
          showWeekNumbers = _props.showWeekNumbers,
          showWeekDays = _props.showWeekDays,
          onWeekClick = _props.onWeekClick;


      var captionProps = {
        date: month,
        classNames: classNames,
        months: months,
        localeUtils: localeUtils,
        locale: locale,
        onClick: onCaptionClick ? function (e) {
          return onCaptionClick(month, e);
        } : undefined
      };
      var caption = _react2.default.isValidElement(captionElement) ? _react2.default.cloneElement(captionElement, captionProps) : _react2.default.createElement(captionElement, captionProps);

      var weeks = Helpers.getWeekArray(month, firstDayOfWeek, fixedWeeks);
      return _react2.default.createElement(
        'div',
        { className: classNames.month, role: 'grid' },
        caption,
        showWeekDays && _react2.default.createElement(_Weekdays2.default, {
          classNames: classNames,
          weekdaysShort: weekdaysShort,
          weekdaysLong: weekdaysLong,
          firstDayOfWeek: firstDayOfWeek,
          showWeekNumbers: showWeekNumbers,
          locale: locale,
          localeUtils: localeUtils,
          weekdayElement: weekdayElement
        }),
        _react2.default.createElement(
          'div',
          { className: classNames.body, role: 'rowgroup' },
          weeks.map(function (week) {
            var weekNumber = void 0;
            if (showWeekNumbers) {
              weekNumber = DateUtils.getWeekNumber(week[6]);
            }
            return _react2.default.createElement(
              'div',
              {
                key: week[0].getTime(),
                className: classNames.week,
                role: 'row'
              },
              showWeekNumbers && _react2.default.createElement(
                'div',
                {
                  className: classNames.weekNumber,
                  tabIndex: onWeekClick ? 0 : -1,
                  role: 'gridcell',
                  onClick: onWeekClick ? function (e) {
                    return onWeekClick(weekNumber, week, e);
                  } : undefined,
                  onKeyUp: onWeekClick ? function (e) {
                    return e.keyCode === _keys.ENTER && onWeekClick(weekNumber, week, e);
                  } : undefined
                },
                _this2.props.renderWeek(weekNumber, week, month)
              ),
              week.map(_this2.renderDay)
            );
          })
        )
      );
    }
  }]);

  return Month;
}(_react.Component);

exports.default = Month;
Month.propTypes =  true ? {
  classNames: _propTypes2.default.shape({
    body: _propTypes2.default.string.isRequired,
    month: _propTypes2.default.string.isRequired,
    outside: _propTypes2.default.string.isRequired,
    today: _propTypes2.default.string.isRequired,
    week: _propTypes2.default.string.isRequired
  }).isRequired,
  tabIndex: _propTypes2.default.number,

  month: _propTypes2.default.instanceOf(Date).isRequired,
  months: _propTypes2.default.arrayOf(_propTypes2.default.string),

  modifiersStyles: _propTypes2.default.object,

  showWeekDays: _propTypes2.default.bool,
  showOutsideDays: _propTypes2.default.bool,

  renderDay: _propTypes2.default.func.isRequired,
  renderWeek: _propTypes2.default.func.isRequired,

  captionElement: _propTypes2.default.oneOfType([_propTypes2.default.element, _propTypes2.default.func, _propTypes2.default.instanceOf(_react2.default.Component)]).isRequired,
  weekdayElement: _propTypes2.default.oneOfType([_propTypes2.default.element, _propTypes2.default.func, _propTypes2.default.instanceOf(_react2.default.Component)]),

  fixedWeeks: _propTypes2.default.bool,
  showWeekNumbers: _propTypes2.default.bool,

  locale: _propTypes2.default.string.isRequired,
  localeUtils: _propTypes2.default.object.isRequired,
  weekdaysLong: _propTypes2.default.arrayOf(_propTypes2.default.string),
  weekdaysShort: _propTypes2.default.arrayOf(_propTypes2.default.string),
  firstDayOfWeek: _propTypes2.default.number.isRequired,

  onCaptionClick: _propTypes2.default.func,
  onDayClick: _propTypes2.default.func,
  onDayFocus: _propTypes2.default.func,
  onDayKeyDown: _propTypes2.default.func,
  onDayMouseEnter: _propTypes2.default.func,
  onDayMouseLeave: _propTypes2.default.func,
  onDayMouseDown: _propTypes2.default.func,
  onDayMouseUp: _propTypes2.default.func,
  onDayTouchEnd: _propTypes2.default.func,
  onDayTouchStart: _propTypes2.default.func,
  onWeekClick: _propTypes2.default.func
} : undefined;
//# sourceMappingURL=Month.js.map

/***/ }),

/***/ "LRzW":
/*!***********************************************!*\
  !*** ./node_modules/base16/lib/railscasts.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'railscasts',
  author: 'ryan bates (http://railscasts.com)',
  base00: '#2b2b2b',
  base01: '#272935',
  base02: '#3a4055',
  base03: '#5a647e',
  base04: '#d4cfc9',
  base05: '#e6e1dc',
  base06: '#f4f1ed',
  base07: '#f9f7f3',
  base08: '#da4939',
  base09: '#cc7833',
  base0A: '#ffc66d',
  base0B: '#a5c261',
  base0C: '#519f50',
  base0D: '#6d9cbe',
  base0E: '#b6b3eb',
  base0F: '#bc9458'
};
module.exports = exports['default'];

/***/ }),

/***/ "LSGn":
/*!******************************************************!*\
  !*** ./node_modules/jupyterlab-dash/style/index.css ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../css-loader!./index.css */ "Rsun");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "LUd0":
/*!*********************************************************!*\
  !*** ./node_modules/mdi-react/FormatAlignCenterIcon.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var FormatAlignCenterIcon = function FormatAlignCenterIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M3,3H21V5H3V3M7,7H17V9H7V7M3,11H21V13H3V11M7,15H17V17H7V15M3,19H21V21H3V19Z' })
  );
};

module.exports = FormatAlignCenterIcon;


/***/ }),

/***/ "LXxW":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_arrayFilter.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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;
}

module.exports = arrayFilter;


/***/ }),

/***/ "LY7c":
/*!********************************************************************!*\
  !*** ./node_modules/@jupyterlab/observables/lib/observablejson.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
const observablemap_1 = __webpack_require__(/*! ./observablemap */ "14pl");
/**
 * A concrete Observable map for JSON data.
 */
class ObservableJSON extends observablemap_1.ObservableMap {
    /**
     * Construct a new observable JSON object.
     */
    constructor(options = {}) {
        super({
            itemCmp: coreutils_1.JSONExt.deepEqual,
            values: options.values
        });
    }
    /**
     * Serialize the model to JSON.
     */
    toJSON() {
        const out = Object.create(null);
        const keys = this.keys();
        for (let key of keys) {
            const value = this.get(key);
            if (value !== undefined) {
                out[key] = coreutils_1.JSONExt.deepCopy(value);
            }
        }
        return out;
    }
}
exports.ObservableJSON = ObservableJSON;
/**
 * The namespace for ObservableJSON static data.
 */
(function (ObservableJSON) {
    /**
     * An observable JSON change message.
     */
    class ChangeMessage extends messaging_1.Message {
        /**
         * Create a new metadata changed message.
         */
        constructor(args) {
            super('jsonvalue-changed');
            this.args = args;
        }
    }
    ObservableJSON.ChangeMessage = ChangeMessage;
})(ObservableJSON = exports.ObservableJSON || (exports.ObservableJSON = {}));


/***/ }),

/***/ "LYgx":
/*!********************************************************************!*\
  !*** ./node_modules/@jupyterlab/docmanager-extension/lib/index.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const docmanager_1 = __webpack_require__(/*! @jupyterlab/docmanager */ "kL29");
const mainmenu_1 = __webpack_require__(/*! @jupyterlab/mainmenu */ "N4Qf");
/**
 * The name of the factory that creates markdown widgets.
 */
const MARKDOWN_FACTORY = 'Markdown Preview';
/**
 * The command IDs used by the document manager plugin.
 */
var CommandIDs;
(function (CommandIDs) {
    CommandIDs.clone = 'docmanager:clone';
    CommandIDs.close = 'docmanager:close';
    CommandIDs.closeAllFiles = 'docmanager:close-all-files';
    CommandIDs.closeOtherTabs = 'docmanager:close-other-tabs';
    CommandIDs.closeRightTabs = 'docmanager:close-right-tabs';
    CommandIDs.deleteFile = 'docmanager:delete-file';
    CommandIDs.newUntitled = 'docmanager:new-untitled';
    CommandIDs.open = 'docmanager:open';
    CommandIDs.openBrowserTab = 'docmanager:open-browser-tab';
    CommandIDs.openDirect = 'docmanager:open-direct';
    CommandIDs.reload = 'docmanager:reload';
    CommandIDs.rename = 'docmanager:rename';
    CommandIDs.restoreCheckpoint = 'docmanager:restore-checkpoint';
    CommandIDs.save = 'docmanager:save';
    CommandIDs.saveAll = 'docmanager:save-all';
    CommandIDs.saveAs = 'docmanager:save-as';
    CommandIDs.toggleAutosave = 'docmanager:toggle-autosave';
    CommandIDs.showInFileBrowser = 'docmanager:show-in-file-browser';
    CommandIDs.markdownPreview = 'markdownviewer:open';
})(CommandIDs || (CommandIDs = {}));
const pluginId = '@jupyterlab/docmanager-extension:plugin';
/**
 * The default document manager provider.
 */
const plugin = {
    id: pluginId,
    provides: docmanager_1.IDocumentManager,
    requires: [apputils_1.ICommandPalette, mainmenu_1.IMainMenu, coreutils_1.ISettingRegistry],
    activate: (app, palette, menu, settingRegistry) => {
        const manager = app.serviceManager;
        const contexts = new WeakSet();
        const opener = {
            open: (widget, options) => {
                const shell = app.shell;
                if (!widget.id) {
                    widget.id = `document-manager-${++Private.id}`;
                }
                widget.title.dataset = Object.assign({ type: 'document-title' }, widget.title.dataset);
                if (!widget.isAttached) {
                    app.shell.addToMainArea(widget, options || {});
                }
                shell.activateById(widget.id);
                // Handle dirty state for open documents.
                let context = docManager.contextForWidget(widget);
                if (!contexts.has(context)) {
                    handleContext(app, context);
                    contexts.add(context);
                }
            }
        };
        const registry = app.docRegistry;
        const when = app.restored.then(() => void 0);
        const docManager = new docmanager_1.DocumentManager({
            registry,
            manager,
            opener,
            when,
            setBusy: app.setBusy.bind(app)
        });
        // Register the file operations commands.
        addCommands(app, docManager, palette, opener, settingRegistry);
        // Keep up to date with the settings registry.
        const onSettingsUpdated = (settings) => {
            const autosave = settings.get('autosave').composite;
            docManager.autosave =
                autosave === true || autosave === false ? autosave : true;
            app.commands.notifyCommandChanged(CommandIDs.toggleAutosave);
        };
        // Fetch the initial state of the settings.
        Promise.all([settingRegistry.load(pluginId), app.restored])
            .then(([settings]) => {
            settings.changed.connect(onSettingsUpdated);
            onSettingsUpdated(settings);
        })
            .catch((reason) => {
            console.error(reason.message);
        });
        menu.settingsMenu.addGroup([{ command: CommandIDs.toggleAutosave }], 5);
        return docManager;
    }
};
/**
 * Export the plugin as default.
 */
exports.default = plugin;
/* Widget to display the revert to checkpoint confirmation. */
class RevertConfirmWidget extends widgets_1.Widget {
    /**
     * Construct a new revert confirmation widget.
     */
    constructor(checkpoint) {
        super({ node: Private.createRevertConfirmNode(checkpoint) });
    }
}
/**
 * Add the file operations commands to the application's command registry.
 */
function addCommands(app, docManager, palette, opener, settingRegistry) {
    const { commands, docRegistry, shell } = app;
    const category = 'File Operations';
    const isEnabled = () => {
        const { currentWidget } = shell;
        return !!(currentWidget && docManager.contextForWidget(currentWidget));
    };
    const isWritable = () => {
        const { currentWidget } = shell;
        if (!currentWidget) {
            return false;
        }
        const context = docManager.contextForWidget(currentWidget);
        return !!(context &&
            context.contentsModel &&
            context.contentsModel.writable);
    };
    // fetches the doc widget associated with the most recent contextmenu event
    const contextMenuWidget = () => {
        const pathRe = /[Pp]ath:\s?(.*)\n?/;
        const test = (node) => node['title'] && !!node['title'].match(pathRe);
        const node = app.contextMenuFirst(test);
        if (!node) {
            // fall back to active doc widget if path cannot be obtained from event
            return app.shell.currentWidget;
        }
        const pathMatch = node['title'].match(pathRe);
        return docManager.findWidget(pathMatch[1]);
    };
    // operates on active widget by default
    const fileType = (widget = shell.currentWidget) => {
        if (!widget) {
            return 'File';
        }
        const context = docManager.contextForWidget(widget);
        if (!context) {
            return '';
        }
        const fts = docRegistry.getFileTypesForPath(context.path);
        return fts.length && fts[0].displayName ? fts[0].displayName : 'File';
    };
    const closeWidgets = (widgets) => {
        widgets.forEach(widget => widget.close());
    };
    const findTab = (area, widget) => {
        switch (area.type) {
            case 'split-area':
                const iterator = algorithm_1.iter(area.children);
                let tab = null;
                let value = null;
                do {
                    value = iterator.next();
                    if (value) {
                        tab = findTab(value, widget);
                    }
                } while (!tab && value);
                return tab;
            case 'tab-area':
                const { id } = widget;
                return area.widgets.some(widget => widget.id === id) ? area : null;
            default:
                return null;
        }
    };
    const tabAreaFor = (widget) => {
        const { mainArea } = shell.saveLayout();
        if (mainArea.mode !== 'multiple-document') {
            return null;
        }
        let area = mainArea.dock.main;
        if (!area) {
            return null;
        }
        return findTab(area, widget);
    };
    const widgetsRightOf = (widget) => {
        const { id } = widget;
        const tabArea = tabAreaFor(widget);
        const widgets = tabArea ? tabArea.widgets || [] : [];
        const index = widgets.findIndex(widget => widget.id === id);
        if (index < 0) {
            return [];
        }
        return widgets.slice(index + 1);
    };
    commands.addCommand(CommandIDs.close, {
        label: () => {
            const widget = shell.currentWidget;
            let name = 'File';
            if (widget) {
                const typeName = fileType();
                name = typeName || widget.title.label;
            }
            return `Close ${name}`;
        },
        isEnabled: () => !!shell.currentWidget && !!shell.currentWidget.title.closable,
        execute: () => {
            if (shell.currentWidget) {
                shell.currentWidget.close();
            }
        }
    });
    commands.addCommand(CommandIDs.closeAllFiles, {
        label: 'Close All',
        execute: () => {
            shell.closeAll();
        }
    });
    commands.addCommand(CommandIDs.closeOtherTabs, {
        label: () => `Close Other Tabs`,
        isEnabled: () => {
            // Ensure there are at least two widgets.
            const iterator = shell.widgets('main');
            return !!iterator.next() && !!iterator.next();
        },
        execute: () => {
            const widget = contextMenuWidget();
            if (!widget) {
                return;
            }
            const { id } = widget;
            const otherWidgets = algorithm_1.toArray(shell.widgets('main')).filter(widget => widget.id !== id);
            closeWidgets(otherWidgets);
        }
    });
    commands.addCommand(CommandIDs.closeRightTabs, {
        label: () => `Close Tabs to Right`,
        isEnabled: () => contextMenuWidget() && widgetsRightOf(contextMenuWidget()).length > 0,
        execute: () => {
            const widget = contextMenuWidget();
            if (!widget) {
                return;
            }
            closeWidgets(widgetsRightOf(widget));
        }
    });
    commands.addCommand(CommandIDs.deleteFile, {
        label: () => `Delete ${fileType()}`,
        execute: args => {
            const path = typeof args['path'] === 'undefined' ? '' : args['path'];
            if (!path) {
                const command = CommandIDs.deleteFile;
                throw new Error(`A non-empty path is required for ${command}.`);
            }
            return docManager.deleteFile(path);
        }
    });
    commands.addCommand(CommandIDs.newUntitled, {
        execute: args => {
            const errorTitle = args['error'] || 'Error';
            const path = typeof args['path'] === 'undefined' ? '' : args['path'];
            let options = {
                type: args['type'],
                path
            };
            if (args['type'] === 'file') {
                options.ext = args['ext'] || '.txt';
            }
            return docManager.services.contents
                .newUntitled(options)
                .catch(error => apputils_1.showErrorMessage(errorTitle, error));
        },
        label: args => args['label'] || `New ${args['type']}`
    });
    commands.addCommand(CommandIDs.open, {
        execute: args => {
            const path = typeof args['path'] === 'undefined' ? '' : args['path'];
            const factory = args['factory'] || void 0;
            const kernel = args['kernel'] || void 0;
            const options = args['options'] || void 0;
            return docManager.services.contents
                .get(path, { content: false })
                .then(() => docManager.openOrReveal(path, factory, kernel, options));
        },
        icon: args => args['icon'] || '',
        label: args => (args['label'] || args['factory']),
        mnemonic: args => args['mnemonic'] || -1
    });
    commands.addCommand(CommandIDs.openBrowserTab, {
        execute: args => {
            const path = typeof args['path'] === 'undefined' ? '' : args['path'];
            if (!path) {
                return;
            }
            return docManager.services.contents.getDownloadUrl(path).then(url => {
                window.open(url, '_blank');
            });
        },
        icon: args => args['icon'] || '',
        label: () => 'Open in New Browser Tab'
    });
    commands.addCommand(CommandIDs.openDirect, {
        label: () => 'Open From Path...',
        caption: 'Open from path',
        isEnabled: () => true,
        execute: () => {
            return docmanager_1.getOpenPath(docManager.services.contents).then(path => {
                if (!path) {
                    return;
                }
                docManager.services.contents.get(path, { content: false }).then(args => {
                    // exists
                    return commands.execute(CommandIDs.open, { path: path });
                }, () => {
                    // does not exist
                    return apputils_1.showDialog({
                        title: 'Cannot open',
                        body: 'File not found',
                        buttons: [apputils_1.Dialog.okButton()]
                    });
                });
                return;
            });
        }
    });
    commands.addCommand(CommandIDs.reload, {
        label: () => `Reload ${fileType()} from Disk`,
        caption: 'Reload contents from disk',
        isEnabled,
        execute: () => {
            if (!isEnabled()) {
                return;
            }
            const context = docManager.contextForWidget(shell.currentWidget);
            return apputils_1.showDialog({
                title: 'Reload Notebook from Disk',
                body: `Are you sure you want to reload
          the notebook from the disk?`,
                buttons: [apputils_1.Dialog.cancelButton(), apputils_1.Dialog.warnButton({ label: 'Reload' })]
            }).then(result => {
                if (result.button.accept && !context.isDisposed) {
                    return context.revert();
                }
            });
        }
    });
    commands.addCommand(CommandIDs.restoreCheckpoint, {
        label: () => `Revert ${fileType()} to Checkpoint`,
        caption: 'Revert contents to previous checkpoint',
        isEnabled,
        execute: () => {
            if (!isEnabled()) {
                return;
            }
            const context = docManager.contextForWidget(shell.currentWidget);
            return context.listCheckpoints().then(checkpoints => {
                if (checkpoints.length < 1) {
                    return;
                }
                const lastCheckpoint = checkpoints[checkpoints.length - 1];
                if (!lastCheckpoint) {
                    return;
                }
                return apputils_1.showDialog({
                    title: 'Revert notebook to checkpoint',
                    body: new RevertConfirmWidget(lastCheckpoint),
                    buttons: [
                        apputils_1.Dialog.cancelButton(),
                        apputils_1.Dialog.warnButton({ label: 'Revert' })
                    ]
                }).then(result => {
                    if (context.isDisposed) {
                        return;
                    }
                    if (result.button.accept) {
                        if (context.model.readOnly) {
                            return context.revert();
                        }
                        return context.restoreCheckpoint().then(() => context.revert());
                    }
                });
            });
        }
    });
    commands.addCommand(CommandIDs.save, {
        label: () => `Save ${fileType()}`,
        caption: 'Save and create checkpoint',
        isEnabled: isWritable,
        execute: () => {
            if (isEnabled()) {
                let context = docManager.contextForWidget(shell.currentWidget);
                if (context.model.readOnly) {
                    return apputils_1.showDialog({
                        title: 'Cannot Save',
                        body: 'Document is read-only',
                        buttons: [apputils_1.Dialog.okButton()]
                    });
                }
                return context
                    .save()
                    .then(() => context.createCheckpoint())
                    .catch(err => {
                    // If the save was canceled by user-action, do nothing.
                    if (err.message === 'Cancel') {
                        return;
                    }
                    throw err;
                });
            }
        }
    });
    commands.addCommand(CommandIDs.saveAll, {
        label: () => 'Save All',
        caption: 'Save all open documents',
        isEnabled: () => {
            const iterator = shell.widgets('main');
            let widget = iterator.next();
            while (widget) {
                let context = docManager.contextForWidget(widget);
                if (context &&
                    context.contentsModel &&
                    context.contentsModel.writable) {
                    return true;
                }
                widget = iterator.next();
            }
            // disable saveAll if all of the widgets models
            // have writable === false
            return false;
        },
        execute: () => {
            const iterator = shell.widgets('main');
            const promises = [];
            const paths = new Set(); // Cache so we don't double save files.
            let widget = iterator.next();
            while (widget) {
                const context = docManager.contextForWidget(widget);
                if (context && !context.model.readOnly && !paths.has(context.path)) {
                    paths.add(context.path);
                    promises.push(context.save());
                }
                widget = iterator.next();
            }
            return Promise.all(promises);
        }
    });
    commands.addCommand(CommandIDs.saveAs, {
        label: () => `Save ${fileType()} As…`,
        caption: 'Save with new path',
        isEnabled,
        execute: () => {
            if (isEnabled()) {
                let context = docManager.contextForWidget(shell.currentWidget);
                return context.saveAs();
            }
        }
    });
    commands.addCommand(CommandIDs.rename, {
        label: () => `Rename ${fileType(contextMenuWidget())}…`,
        isEnabled,
        execute: () => {
            if (isEnabled()) {
                let context = docManager.contextForWidget(contextMenuWidget());
                return docmanager_1.renameDialog(docManager, context.path);
            }
        }
    });
    commands.addCommand(CommandIDs.clone, {
        label: () => `New View for ${fileType(contextMenuWidget())}`,
        isEnabled,
        execute: args => {
            const widget = contextMenuWidget();
            const options = args['options'] || {
                mode: 'split-right'
            };
            if (!widget) {
                return;
            }
            // Clone the widget.
            let child = docManager.cloneWidget(widget);
            if (child) {
                opener.open(child, options);
            }
        }
    });
    commands.addCommand(CommandIDs.toggleAutosave, {
        label: 'Autosave Documents',
        isToggled: () => docManager.autosave,
        execute: () => {
            const value = !docManager.autosave;
            const key = 'autosave';
            return settingRegistry
                .set(pluginId, key, value)
                .catch((reason) => {
                console.error(`Failed to set ${pluginId}:${key} - ${reason.message}`);
            });
        }
    });
    commands.addCommand(CommandIDs.showInFileBrowser, {
        label: () => `Show in File Browser`,
        isEnabled,
        execute: () => {
            let context = docManager.contextForWidget(contextMenuWidget());
            if (!context) {
                return;
            }
            // 'activate' is needed if this command is selected in the "open tabs" sidebar
            commands.execute('filebrowser:activate', { path: context.path });
            commands.execute('filebrowser:navigate', { path: context.path });
        }
    });
    commands.addCommand(CommandIDs.markdownPreview, {
        label: 'Markdown Preview',
        execute: args => {
            let path = args['path'];
            if (typeof path !== 'string') {
                return;
            }
            return commands.execute('docmanager:open', {
                path,
                factory: MARKDOWN_FACTORY,
                options: args['options']
            });
        }
    });
    app.contextMenu.addItem({
        command: CommandIDs.rename,
        selector: '[data-type="document-title"]',
        rank: 1
    });
    app.contextMenu.addItem({
        command: CommandIDs.clone,
        selector: '[data-type="document-title"]',
        rank: 2
    });
    app.contextMenu.addItem({
        command: CommandIDs.showInFileBrowser,
        selector: '[data-type="document-title"]',
        rank: 3
    });
    app.contextMenu.addItem({
        command: CommandIDs.closeOtherTabs,
        selector: '[data-type="document-title"]',
        rank: 4
    });
    app.contextMenu.addItem({
        command: CommandIDs.closeRightTabs,
        selector: '[data-type="document-title"]',
        rank: 5
    });
    [
        CommandIDs.openDirect,
        CommandIDs.save,
        CommandIDs.reload,
        CommandIDs.restoreCheckpoint,
        CommandIDs.saveAs,
        CommandIDs.clone,
        CommandIDs.close,
        CommandIDs.closeAllFiles,
        CommandIDs.closeOtherTabs,
        CommandIDs.closeRightTabs,
        CommandIDs.toggleAutosave
    ].forEach(command => {
        palette.addItem({ command, category });
    });
}
/**
 * Handle dirty state for a context.
 */
function handleContext(app, context) {
    let disposable = null;
    let onStateChanged = (sender, args) => {
        if (args.name === 'dirty') {
            if (args.newValue === true) {
                if (!disposable) {
                    disposable = app.setDirty();
                }
            }
            else if (disposable) {
                disposable.dispose();
                disposable = null;
            }
        }
    };
    context.ready.then(() => {
        context.model.stateChanged.connect(onStateChanged);
        if (context.model.dirty) {
            disposable = app.setDirty();
        }
    });
    context.disposed.connect(() => {
        if (disposable) {
            disposable.dispose();
        }
    });
}
/**
 * A namespace for private module data.
 */
var Private;
(function (Private) {
    /**
     * A counter for unique IDs.
     */
    Private.id = 0;
    function createRevertConfirmNode(checkpoint) {
        let body = document.createElement('div');
        let confirmMessage = document.createElement('p');
        let confirmText = document.createTextNode(`Are you sure you want to revert
      the notebook to the latest checkpoint? `);
        let cannotUndoText = document.createElement('strong');
        cannotUndoText.textContent = 'This cannot be undone.';
        confirmMessage.appendChild(confirmText);
        confirmMessage.appendChild(cannotUndoText);
        let lastCheckpointMessage = document.createElement('p');
        let lastCheckpointText = document.createTextNode('The checkpoint was last updated at: ');
        let lastCheckpointDate = document.createElement('p');
        let date = new Date(checkpoint.last_modified);
        lastCheckpointDate.style.textAlign = 'center';
        lastCheckpointDate.textContent =
            coreutils_1.Time.format(date, 'dddd, MMMM Do YYYY, h:mm:ss a') +
                ' (' +
                coreutils_1.Time.formatHuman(date) +
                ')';
        lastCheckpointMessage.appendChild(lastCheckpointText);
        lastCheckpointMessage.appendChild(lastCheckpointDate);
        body.appendChild(confirmMessage);
        body.appendChild(lastCheckpointMessage);
        return body;
    }
    Private.createRevertConfirmNode = createRevertConfirmNode;
})(Private || (Private = {}));


/***/ }),

/***/ "LcsW":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_getPrototype.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var overArg = __webpack_require__(/*! ./_overArg */ "kekF");

/** Built-in value references. */
var getPrototype = overArg(Object.getPrototypeOf, Object);

module.exports = getPrototype;


/***/ }),

/***/ "LiaU":
/*!*********************************************************************!*\
  !*** ./node_modules/@jupyter-widgets/controls/css/widgets-base.css ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./widgets-base.css */ "hmv/");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "Lj1h":
/*!*********************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/relative_attr.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




// ASCEND: chop off the last nesting level - either [<n>] or .<key> - to ascend
// the attribute tree. the remaining attrString is in match[1]
var ASCEND = /^(.*)(\.[^\.\[\]]+|\[\d\])$/;

// SIMPLEATTR: is this an un-nested attribute? (no dots or brackets)
var SIMPLEATTR = /^[^\.\[\]]+$/;

/*
 * calculate a relative attribute string, similar to a relative path
 *
 * @param {string} baseAttr:
 *   an attribute string, such as 'annotations[3].x'. The "current location"
 *   is the attribute string minus the last component ('annotations[3]')
 * @param {string} relativeAttr:
 *   a route to the desired attribute string, using '^' to ascend
 *
 * @return {string} attrString:
 *   for example:
 *     relativeAttr('annotations[3].x', 'y') = 'annotations[3].y'
 *     relativeAttr('annotations[3].x', '^[2].z') = 'annotations[2].z'
 *     relativeAttr('annotations[3].x', '^^margin') = 'margin'
 *     relativeAttr('annotations[3].x', '^^margin.r') = 'margin.r'
 */
module.exports = function(baseAttr, relativeAttr) {
    while(relativeAttr) {
        var match = baseAttr.match(ASCEND);

        if(match) baseAttr = match[1];
        else if(baseAttr.match(SIMPLEATTR)) baseAttr = '';
        else throw new Error('bad relativeAttr call:' + [baseAttr, relativeAttr]);

        if(relativeAttr.charAt(0) === '^') relativeAttr = relativeAttr.slice(1);
        else break;
    }

    if(baseAttr && relativeAttr.charAt(0) !== '[') {
        return baseAttr + '.' + relativeAttr;
    }
    return baseAttr + relativeAttr;
};


/***/ }),

/***/ "LjMy":
/*!**************************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/clear_responsive.js ***!
  \**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



/**
 * Clear responsive handlers (if any).
 *
 * @param {DOM node or object} gd : graph div object
 */
module.exports = function clearResponsive(gd) {
    if(gd._responsiveChartHandler) {
        window.removeEventListener('resize', gd._responsiveChartHandler);
        delete gd._responsiveChartHandler;
    }
};


/***/ }),

/***/ "Lm6R":
/*!*************************************************!*\
  !*** ./node_modules/codemirror/keymap/emacs.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../lib/codemirror */ "VrN/"));
  else {}
})(function(CodeMirror) {
  "use strict";

  var Pos = CodeMirror.Pos;
  function posEq(a, b) { return a.line == b.line && a.ch == b.ch; }

  // Kill 'ring'

  var killRing = [];
  function addToRing(str) {
    killRing.push(str);
    if (killRing.length > 50) killRing.shift();
  }
  function growRingTop(str) {
    if (!killRing.length) return addToRing(str);
    killRing[killRing.length - 1] += str;
  }
  function getFromRing(n) { return killRing[killRing.length - (n ? Math.min(n, 1) : 1)] || ""; }
  function popFromRing() { if (killRing.length > 1) killRing.pop(); return getFromRing(); }

  var lastKill = null;

  function kill(cm, from, to, ring, text) {
    if (text == null) text = cm.getRange(from, to);

    if (ring == "grow" && lastKill && lastKill.cm == cm && posEq(from, lastKill.pos) && cm.isClean(lastKill.gen))
      growRingTop(text);
    else if (ring !== false)
      addToRing(text);
    cm.replaceRange("", from, to, "+delete");

    if (ring == "grow") lastKill = {cm: cm, pos: from, gen: cm.changeGeneration()};
    else lastKill = null;
  }

  // Boundaries of various units

  function byChar(cm, pos, dir) {
    return cm.findPosH(pos, dir, "char", true);
  }

  function byWord(cm, pos, dir) {
    return cm.findPosH(pos, dir, "word", true);
  }

  function byLine(cm, pos, dir) {
    return cm.findPosV(pos, dir, "line", cm.doc.sel.goalColumn);
  }

  function byPage(cm, pos, dir) {
    return cm.findPosV(pos, dir, "page", cm.doc.sel.goalColumn);
  }

  function byParagraph(cm, pos, dir) {
    var no = pos.line, line = cm.getLine(no);
    var sawText = /\S/.test(dir < 0 ? line.slice(0, pos.ch) : line.slice(pos.ch));
    var fst = cm.firstLine(), lst = cm.lastLine();
    for (;;) {
      no += dir;
      if (no < fst || no > lst)
        return cm.clipPos(Pos(no - dir, dir < 0 ? 0 : null));
      line = cm.getLine(no);
      var hasText = /\S/.test(line);
      if (hasText) sawText = true;
      else if (sawText) return Pos(no, 0);
    }
  }

  function bySentence(cm, pos, dir) {
    var line = pos.line, ch = pos.ch;
    var text = cm.getLine(pos.line), sawWord = false;
    for (;;) {
      var next = text.charAt(ch + (dir < 0 ? -1 : 0));
      if (!next) { // End/beginning of line reached
        if (line == (dir < 0 ? cm.firstLine() : cm.lastLine())) return Pos(line, ch);
        text = cm.getLine(line + dir);
        if (!/\S/.test(text)) return Pos(line, ch);
        line += dir;
        ch = dir < 0 ? text.length : 0;
        continue;
      }
      if (sawWord && /[!?.]/.test(next)) return Pos(line, ch + (dir > 0 ? 1 : 0));
      if (!sawWord) sawWord = /\w/.test(next);
      ch += dir;
    }
  }

  function byExpr(cm, pos, dir) {
    var wrap;
    if (cm.findMatchingBracket && (wrap = cm.findMatchingBracket(pos, {strict: true}))
        && wrap.match && (wrap.forward ? 1 : -1) == dir)
      return dir > 0 ? Pos(wrap.to.line, wrap.to.ch + 1) : wrap.to;

    for (var first = true;; first = false) {
      var token = cm.getTokenAt(pos);
      var after = Pos(pos.line, dir < 0 ? token.start : token.end);
      if (first && dir > 0 && token.end == pos.ch || !/\w/.test(token.string)) {
        var newPos = cm.findPosH(after, dir, "char");
        if (posEq(after, newPos)) return pos;
        else pos = newPos;
      } else {
        return after;
      }
    }
  }

  // Prefixes (only crudely supported)

  function getPrefix(cm, precise) {
    var digits = cm.state.emacsPrefix;
    if (!digits) return precise ? null : 1;
    clearPrefix(cm);
    return digits == "-" ? -1 : Number(digits);
  }

  function repeated(cmd) {
    var f = typeof cmd == "string" ? function(cm) { cm.execCommand(cmd); } : cmd;
    return function(cm) {
      var prefix = getPrefix(cm);
      f(cm);
      for (var i = 1; i < prefix; ++i) f(cm);
    };
  }

  function findEnd(cm, pos, by, dir) {
    var prefix = getPrefix(cm);
    if (prefix < 0) { dir = -dir; prefix = -prefix; }
    for (var i = 0; i < prefix; ++i) {
      var newPos = by(cm, pos, dir);
      if (posEq(newPos, pos)) break;
      pos = newPos;
    }
    return pos;
  }

  function move(by, dir) {
    var f = function(cm) {
      cm.extendSelection(findEnd(cm, cm.getCursor(), by, dir));
    };
    f.motion = true;
    return f;
  }

  function killTo(cm, by, dir, ring) {
    var selections = cm.listSelections(), cursor;
    var i = selections.length;
    while (i--) {
      cursor = selections[i].head;
      kill(cm, cursor, findEnd(cm, cursor, by, dir), ring);
    }
  }

  function killRegion(cm, ring) {
    if (cm.somethingSelected()) {
      var selections = cm.listSelections(), selection;
      var i = selections.length;
      while (i--) {
        selection = selections[i];
        kill(cm, selection.anchor, selection.head, ring);
      }
      return true;
    }
  }

  function addPrefix(cm, digit) {
    if (cm.state.emacsPrefix) {
      if (digit != "-") cm.state.emacsPrefix += digit;
      return;
    }
    // Not active yet
    cm.state.emacsPrefix = digit;
    cm.on("keyHandled", maybeClearPrefix);
    cm.on("inputRead", maybeDuplicateInput);
  }

  var prefixPreservingKeys = {"Alt-G": true, "Ctrl-X": true, "Ctrl-Q": true, "Ctrl-U": true};

  function maybeClearPrefix(cm, arg) {
    if (!cm.state.emacsPrefixMap && !prefixPreservingKeys.hasOwnProperty(arg))
      clearPrefix(cm);
  }

  function clearPrefix(cm) {
    cm.state.emacsPrefix = null;
    cm.off("keyHandled", maybeClearPrefix);
    cm.off("inputRead", maybeDuplicateInput);
  }

  function maybeDuplicateInput(cm, event) {
    var dup = getPrefix(cm);
    if (dup > 1 && event.origin == "+input") {
      var one = event.text.join("\n"), txt = "";
      for (var i = 1; i < dup; ++i) txt += one;
      cm.replaceSelection(txt);
    }
  }

  function addPrefixMap(cm) {
    cm.state.emacsPrefixMap = true;
    cm.addKeyMap(prefixMap);
    cm.on("keyHandled", maybeRemovePrefixMap);
    cm.on("inputRead", maybeRemovePrefixMap);
  }

  function maybeRemovePrefixMap(cm, arg) {
    if (typeof arg == "string" && (/^\d$/.test(arg) || arg == "Ctrl-U")) return;
    cm.removeKeyMap(prefixMap);
    cm.state.emacsPrefixMap = false;
    cm.off("keyHandled", maybeRemovePrefixMap);
    cm.off("inputRead", maybeRemovePrefixMap);
  }

  // Utilities

  function setMark(cm) {
    cm.setCursor(cm.getCursor());
    cm.setExtending(!cm.getExtending());
    cm.on("change", function() { cm.setExtending(false); });
  }

  function clearMark(cm) {
    cm.setExtending(false);
    cm.setCursor(cm.getCursor());
  }

  function getInput(cm, msg, f) {
    if (cm.openDialog)
      cm.openDialog(msg + ": <input type=\"text\" style=\"width: 10em\"/>", f, {bottom: true});
    else
      f(prompt(msg, ""));
  }

  function operateOnWord(cm, op) {
    var start = cm.getCursor(), end = cm.findPosH(start, 1, "word");
    cm.replaceRange(op(cm.getRange(start, end)), start, end);
    cm.setCursor(end);
  }

  function toEnclosingExpr(cm) {
    var pos = cm.getCursor(), line = pos.line, ch = pos.ch;
    var stack = [];
    while (line >= cm.firstLine()) {
      var text = cm.getLine(line);
      for (var i = ch == null ? text.length : ch; i > 0;) {
        var ch = text.charAt(--i);
        if (ch == ")")
          stack.push("(");
        else if (ch == "]")
          stack.push("[");
        else if (ch == "}")
          stack.push("{");
        else if (/[\(\{\[]/.test(ch) && (!stack.length || stack.pop() != ch))
          return cm.extendSelection(Pos(line, i));
      }
      --line; ch = null;
    }
  }

  function quit(cm) {
    cm.execCommand("clearSearch");
    clearMark(cm);
  }

  CodeMirror.emacs = {kill: kill, killRegion: killRegion, repeated: repeated};

  // Actual keymap

  var keyMap = CodeMirror.keyMap.emacs = CodeMirror.normalizeKeyMap({
    "Ctrl-W": function(cm) {kill(cm, cm.getCursor("start"), cm.getCursor("end"), true);},
    "Ctrl-K": repeated(function(cm) {
      var start = cm.getCursor(), end = cm.clipPos(Pos(start.line));
      var text = cm.getRange(start, end);
      if (!/\S/.test(text)) {
        text += "\n";
        end = Pos(start.line + 1, 0);
      }
      kill(cm, start, end, "grow", text);
    }),
    "Alt-W": function(cm) {
      addToRing(cm.getSelection());
      clearMark(cm);
    },
    "Ctrl-Y": function(cm) {
      var start = cm.getCursor();
      cm.replaceRange(getFromRing(getPrefix(cm)), start, start, "paste");
      cm.setSelection(start, cm.getCursor());
    },
    "Alt-Y": function(cm) {cm.replaceSelection(popFromRing(), "around", "paste");},

    "Ctrl-Space": setMark, "Ctrl-Shift-2": setMark,

    "Ctrl-F": move(byChar, 1), "Ctrl-B": move(byChar, -1),
    "Right": move(byChar, 1), "Left": move(byChar, -1),
    "Ctrl-D": function(cm) { killTo(cm, byChar, 1, false); },
    "Delete": function(cm) { killRegion(cm, false) || killTo(cm, byChar, 1, false); },
    "Ctrl-H": function(cm) { killTo(cm, byChar, -1, false); },
    "Backspace": function(cm) { killRegion(cm, false) || killTo(cm, byChar, -1, false); },

    "Alt-F": move(byWord, 1), "Alt-B": move(byWord, -1),
    "Alt-Right": move(byWord, 1), "Alt-Left": move(byWord, -1),
    "Alt-D": function(cm) { killTo(cm, byWord, 1, "grow"); },
    "Alt-Backspace": function(cm) { killTo(cm, byWord, -1, "grow"); },

    "Ctrl-N": move(byLine, 1), "Ctrl-P": move(byLine, -1),
    "Down": move(byLine, 1), "Up": move(byLine, -1),
    "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
    "End": "goLineEnd", "Home": "goLineStart",

    "Alt-V": move(byPage, -1), "Ctrl-V": move(byPage, 1),
    "PageUp": move(byPage, -1), "PageDown": move(byPage, 1),

    "Ctrl-Up": move(byParagraph, -1), "Ctrl-Down": move(byParagraph, 1),

    "Alt-A": move(bySentence, -1), "Alt-E": move(bySentence, 1),
    "Alt-K": function(cm) { killTo(cm, bySentence, 1, "grow"); },

    "Ctrl-Alt-K": function(cm) { killTo(cm, byExpr, 1, "grow"); },
    "Ctrl-Alt-Backspace": function(cm) { killTo(cm, byExpr, -1, "grow"); },
    "Ctrl-Alt-F": move(byExpr, 1), "Ctrl-Alt-B": move(byExpr, -1, "grow"),

    "Shift-Ctrl-Alt-2": function(cm) {
      var cursor = cm.getCursor();
      cm.setSelection(findEnd(cm, cursor, byExpr, 1), cursor);
    },
    "Ctrl-Alt-T": function(cm) {
      var leftStart = byExpr(cm, cm.getCursor(), -1), leftEnd = byExpr(cm, leftStart, 1);
      var rightEnd = byExpr(cm, leftEnd, 1), rightStart = byExpr(cm, rightEnd, -1);
      cm.replaceRange(cm.getRange(rightStart, rightEnd) + cm.getRange(leftEnd, rightStart) +
                      cm.getRange(leftStart, leftEnd), leftStart, rightEnd);
    },
    "Ctrl-Alt-U": repeated(toEnclosingExpr),

    "Alt-Space": function(cm) {
      var pos = cm.getCursor(), from = pos.ch, to = pos.ch, text = cm.getLine(pos.line);
      while (from && /\s/.test(text.charAt(from - 1))) --from;
      while (to < text.length && /\s/.test(text.charAt(to))) ++to;
      cm.replaceRange(" ", Pos(pos.line, from), Pos(pos.line, to));
    },
    "Ctrl-O": repeated(function(cm) { cm.replaceSelection("\n", "start"); }),
    "Ctrl-T": repeated(function(cm) {
      cm.execCommand("transposeChars");
    }),

    "Alt-C": repeated(function(cm) {
      operateOnWord(cm, function(w) {
        var letter = w.search(/\w/);
        if (letter == -1) return w;
        return w.slice(0, letter) + w.charAt(letter).toUpperCase() + w.slice(letter + 1).toLowerCase();
      });
    }),
    "Alt-U": repeated(function(cm) {
      operateOnWord(cm, function(w) { return w.toUpperCase(); });
    }),
    "Alt-L": repeated(function(cm) {
      operateOnWord(cm, function(w) { return w.toLowerCase(); });
    }),

    "Alt-;": "toggleComment",

    "Ctrl-/": repeated("undo"), "Shift-Ctrl--": repeated("undo"),
    "Ctrl-Z": repeated("undo"), "Cmd-Z": repeated("undo"),
    "Shift-Alt-,": "goDocStart", "Shift-Alt-.": "goDocEnd",
    "Ctrl-S": "findPersistentNext", "Ctrl-R": "findPersistentPrev", "Ctrl-G": quit, "Shift-Alt-5": "replace",
    "Alt-/": "autocomplete",
    "Enter": "newlineAndIndent",
    "Ctrl-J": repeated(function(cm) { cm.replaceSelection("\n", "end"); }),
    "Tab": "indentAuto",

    "Alt-G G": function(cm) {
      var prefix = getPrefix(cm, true);
      if (prefix != null && prefix > 0) return cm.setCursor(prefix - 1);

      getInput(cm, "Goto line", function(str) {
        var num;
        if (str && !isNaN(num = Number(str)) && num == (num|0) && num > 0)
          cm.setCursor(num - 1);
      });
    },

    "Ctrl-X Tab": function(cm) {
      cm.indentSelection(getPrefix(cm, true) || cm.getOption("indentUnit"));
    },
    "Ctrl-X Ctrl-X": function(cm) {
      cm.setSelection(cm.getCursor("head"), cm.getCursor("anchor"));
    },
    "Ctrl-X Ctrl-S": "save",
    "Ctrl-X Ctrl-W": "save",
    "Ctrl-X S": "saveAll",
    "Ctrl-X F": "open",
    "Ctrl-X U": repeated("undo"),
    "Ctrl-X K": "close",
    "Ctrl-X Delete": function(cm) { kill(cm, cm.getCursor(), bySentence(cm, cm.getCursor(), 1), "grow"); },
    "Ctrl-X H": "selectAll",

    "Ctrl-Q Tab": repeated("insertTab"),
    "Ctrl-U": addPrefixMap
  });

  var prefixMap = {"Ctrl-G": clearPrefix};
  function regPrefix(d) {
    prefixMap[d] = function(cm) { addPrefix(cm, d); };
    keyMap["Ctrl-" + d] = function(cm) { addPrefix(cm, d); };
    prefixPreservingKeys["Ctrl-" + d] = true;
  }
  for (var i = 0; i < 10; ++i) regPrefix(String(i));
  regPrefix("-");
});


/***/ }),

/***/ "Loxo":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/uz.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var uz = moment.defineLocale('uz', {
    months : 'январ_феврал_март_апрел_май_июн_июл_август_сентябр_октябр_ноябр_декабр'.split('_'),
    monthsShort : 'янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек'.split('_'),
    weekdays : 'Якшанба_Душанба_Сешанба_Чоршанба_Пайшанба_Жума_Шанба'.split('_'),
    weekdaysShort : 'Якш_Душ_Сеш_Чор_Пай_Жум_Шан'.split('_'),
    weekdaysMin : 'Як_Ду_Се_Чо_Па_Жу_Ша'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'D MMMM YYYY, dddd HH:mm'
    },
    calendar : {
        sameDay : '[Бугун соат] LT [да]',
        nextDay : '[Эртага] LT [да]',
        nextWeek : 'dddd [куни соат] LT [да]',
        lastDay : '[Кеча соат] LT [да]',
        lastWeek : '[Утган] dddd [куни соат] LT [да]',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'Якин %s ичида',
        past : 'Бир неча %s олдин',
        s : 'фурсат',
        ss : '%d фурсат',
        m : 'бир дакика',
        mm : '%d дакика',
        h : 'бир соат',
        hh : '%d соат',
        d : 'бир кун',
        dd : '%d кун',
        M : 'бир ой',
        MM : '%d ой',
        y : 'бир йил',
        yy : '%d йил'
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 4th is the first week of the year.
    }
});

return uz;

})));


/***/ }),

/***/ "LpQA":
/*!***************************************************!*\
  !*** ./node_modules/draft-js/lib/ContentState.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule ContentState
 * @format
 * 
 */



function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var BlockMapBuilder = __webpack_require__(/*! ./BlockMapBuilder */ "YeVe");
var CharacterMetadata = __webpack_require__(/*! ./CharacterMetadata */ "lFJn");
var ContentBlock = __webpack_require__(/*! ./ContentBlock */ "8uQm");
var ContentBlockNode = __webpack_require__(/*! ./ContentBlockNode */ "JL7T");
var DraftEntity = __webpack_require__(/*! ./DraftEntity */ "TzU/");
var DraftFeatureFlags = __webpack_require__(/*! ./DraftFeatureFlags */ "cX45");
var Immutable = __webpack_require__(/*! immutable */ "JPcv");
var SelectionState = __webpack_require__(/*! ./SelectionState */ "hMpd");

var generateRandomKey = __webpack_require__(/*! ./generateRandomKey */ "rJY1");
var sanitizeDraftText = __webpack_require__(/*! ./sanitizeDraftText */ "HriT");

var List = Immutable.List,
    Record = Immutable.Record,
    Repeat = Immutable.Repeat;


var experimentalTreeDataSupport = DraftFeatureFlags.draft_tree_data_support;

var defaultRecord = {
  entityMap: null,
  blockMap: null,
  selectionBefore: null,
  selectionAfter: null
};

var ContentBlockNodeRecord = experimentalTreeDataSupport ? ContentBlockNode : ContentBlock;

var ContentStateRecord = Record(defaultRecord);

var ContentState = function (_ContentStateRecord) {
  _inherits(ContentState, _ContentStateRecord);

  function ContentState() {
    _classCallCheck(this, ContentState);

    return _possibleConstructorReturn(this, _ContentStateRecord.apply(this, arguments));
  }

  ContentState.prototype.getEntityMap = function getEntityMap() {
    // TODO: update this when we fully remove DraftEntity
    return DraftEntity;
  };

  ContentState.prototype.getBlockMap = function getBlockMap() {
    return this.get('blockMap');
  };

  ContentState.prototype.getSelectionBefore = function getSelectionBefore() {
    return this.get('selectionBefore');
  };

  ContentState.prototype.getSelectionAfter = function getSelectionAfter() {
    return this.get('selectionAfter');
  };

  ContentState.prototype.getBlockForKey = function getBlockForKey(key) {
    var block = this.getBlockMap().get(key);
    return block;
  };

  ContentState.prototype.getKeyBefore = function getKeyBefore(key) {
    return this.getBlockMap().reverse().keySeq().skipUntil(function (v) {
      return v === key;
    }).skip(1).first();
  };

  ContentState.prototype.getKeyAfter = function getKeyAfter(key) {
    return this.getBlockMap().keySeq().skipUntil(function (v) {
      return v === key;
    }).skip(1).first();
  };

  ContentState.prototype.getBlockAfter = function getBlockAfter(key) {
    return this.getBlockMap().skipUntil(function (_, k) {
      return k === key;
    }).skip(1).first();
  };

  ContentState.prototype.getBlockBefore = function getBlockBefore(key) {
    return this.getBlockMap().reverse().skipUntil(function (_, k) {
      return k === key;
    }).skip(1).first();
  };

  ContentState.prototype.getBlocksAsArray = function getBlocksAsArray() {
    return this.getBlockMap().toArray();
  };

  ContentState.prototype.getFirstBlock = function getFirstBlock() {
    return this.getBlockMap().first();
  };

  ContentState.prototype.getLastBlock = function getLastBlock() {
    return this.getBlockMap().last();
  };

  ContentState.prototype.getPlainText = function getPlainText(delimiter) {
    return this.getBlockMap().map(function (block) {
      return block ? block.getText() : '';
    }).join(delimiter || '\n');
  };

  ContentState.prototype.getLastCreatedEntityKey = function getLastCreatedEntityKey() {
    // TODO: update this when we fully remove DraftEntity
    return DraftEntity.__getLastCreatedEntityKey();
  };

  ContentState.prototype.hasText = function hasText() {
    var blockMap = this.getBlockMap();
    return blockMap.size > 1 || blockMap.first().getLength() > 0;
  };

  ContentState.prototype.createEntity = function createEntity(type, mutability, data) {
    // TODO: update this when we fully remove DraftEntity
    DraftEntity.__create(type, mutability, data);
    return this;
  };

  ContentState.prototype.mergeEntityData = function mergeEntityData(key, toMerge) {
    // TODO: update this when we fully remove DraftEntity
    DraftEntity.__mergeData(key, toMerge);
    return this;
  };

  ContentState.prototype.replaceEntityData = function replaceEntityData(key, newData) {
    // TODO: update this when we fully remove DraftEntity
    DraftEntity.__replaceData(key, newData);
    return this;
  };

  ContentState.prototype.addEntity = function addEntity(instance) {
    // TODO: update this when we fully remove DraftEntity
    DraftEntity.__add(instance);
    return this;
  };

  ContentState.prototype.getEntity = function getEntity(key) {
    // TODO: update this when we fully remove DraftEntity
    return DraftEntity.__get(key);
  };

  ContentState.createFromBlockArray = function createFromBlockArray(
  // TODO: update flow type when we completely deprecate the old entity API
  blocks, entityMap) {
    // TODO: remove this when we completely deprecate the old entity API
    var theBlocks = Array.isArray(blocks) ? blocks : blocks.contentBlocks;
    var blockMap = BlockMapBuilder.createFromArray(theBlocks);
    var selectionState = blockMap.isEmpty() ? new SelectionState() : SelectionState.createEmpty(blockMap.first().getKey());
    return new ContentState({
      blockMap: blockMap,
      entityMap: entityMap || DraftEntity,
      selectionBefore: selectionState,
      selectionAfter: selectionState
    });
  };

  ContentState.createFromText = function createFromText(text) {
    var delimiter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : /\r\n?|\n/g;

    var strings = text.split(delimiter);
    var blocks = strings.map(function (block) {
      block = sanitizeDraftText(block);
      return new ContentBlockNodeRecord({
        key: generateRandomKey(),
        text: block,
        type: 'unstyled',
        characterList: List(Repeat(CharacterMetadata.EMPTY, block.length))
      });
    });
    return ContentState.createFromBlockArray(blocks);
  };

  return ContentState;
}(ContentStateRecord);

module.exports = ContentState;

/***/ }),

/***/ "LsHQ":
/*!************************************************!*\
  !*** ./node_modules/lodash/_createAssigner.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseRest = __webpack_require__(/*! ./_baseRest */ "EA7m"),
    isIterateeCall = __webpack_require__(/*! ./_isIterateeCall */ "mv/X");

/**
 * 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;


/***/ }),

/***/ "Ltj7":
/*!*****************************************!*\
  !*** ./node_modules/xterm/lib/Types.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var LinkHoverEventTypes;
(function (LinkHoverEventTypes) {
    LinkHoverEventTypes["HOVER"] = "linkhover";
    LinkHoverEventTypes["TOOLTIP"] = "linktooltip";
    LinkHoverEventTypes["LEAVE"] = "linkleave";
})(LinkHoverEventTypes = exports.LinkHoverEventTypes || (exports.LinkHoverEventTypes = {}));

//# sourceMappingURL=Types.js.map


/***/ }),

/***/ "LvDl":
/*!***************************************!*\
  !*** ./node_modules/lodash/lodash.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global, module) {var __WEBPACK_AMD_DEFINE_RESULT__;/**
 * @license
 * Lodash <https://lodash.com/>
 * Copyright JS Foundation and other contributors <https://js.foundation/>
 * 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.11';

  /** 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';

  /** 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 and trailing whitespace. */
  var reTrim = /^\s+|\s+$/g,
      reTrimStart = /^\s+/,
      reTrimEnd = /\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 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 global == 'object' && global && global.Object === Object && global;

  /** 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 = typeof exports == 'object' && exports && !exports.nodeType && exports;

  /** Detect free variable `module`. */
  var freeModule = freeExports && typeof module == '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 `_.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 `_.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));
        });

        return result;
      }

      if (isMap(value)) {
        value.forEach(function(subValue, key) {
          result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
        });

        return result;
      }

      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) {
        if (isObject(srcValue)) {
          stack || (stack = new Stack);
          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) {
      var index = -1;
      iteratees = arrayMap(iteratees.length ? iteratees : [identity], 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 (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) {
      value = iteratee(value);

      var low = 0,
          high = array == null ? 0 : array.length,
          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) {
          // 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;
      }
      // Assume cyclic values are equal.
      var stacked = stack.get(array);
      if (stacked && stack.get(other)) {
        return stacked == other;
      }
      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;
        }
      }
      // Assume cyclic values are equal.
      var stacked = stack.get(object);
      if (stacked && stack.get(other)) {
        return stacked == other;
      }
      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__".
     *
     * @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 == '__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']
     */
    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': 40 },
     *   { 'user': 'barney', 'age': 34 }
     * ];
     *
     * _.sortBy(users, [function(o) { return o.user; }]);
     * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
     *
     * _.sortBy(users, ['user', 'age']);
     * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['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.
            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 = value.replace(reTrim, '');
      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.
      var sourceURL = '//# sourceURL=' +
        ('sourceURL' in options
          ? options.sourceURL
          : ('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 = options.variable;
      if (!variable) {
        source = 'with (obj) {\n' + source + '\n}\n';
      }
      // 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 string.replace(reTrim, '');
      }
      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.replace(reTrimEnd, '');
      }
      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.
     *
     * @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 }]
     */
    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.
     *
     * @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 }
     */
    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.
     *
     * @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.
     *
     * @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 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 + ''),
            names = realNames[key] || (realNames[key] = []);

        names.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));

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "yLpj"), __webpack_require__(/*! ./../webpack/buildin/module.js */ "YuTi")(module)))

/***/ }),

/***/ "Lwbf":
/*!************************************************************!*\
  !*** ./node_modules/react-color/lib/helpers/checkboard.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var checkboardCache = {};

var render = exports.render = function render(c1, c2, size, serverCanvas) {
  if (typeof document === 'undefined' && !serverCanvas) {
    return null;
  }
  var canvas = serverCanvas ? new serverCanvas() : document.createElement('canvas');
  canvas.width = size * 2;
  canvas.height = size * 2;
  var ctx = canvas.getContext('2d');
  if (!ctx) {
    return null;
  } // If no context can be found, return early.
  ctx.fillStyle = c1;
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = c2;
  ctx.fillRect(0, 0, size, size);
  ctx.translate(size, size);
  ctx.fillRect(0, 0, size, size);
  return canvas.toDataURL();
};

var get = exports.get = function get(c1, c2, size, serverCanvas) {
  var key = c1 + '-' + c2 + '-' + size + (serverCanvas ? '-server' : '');
  var checkboard = render(c1, c2, size, serverCanvas);

  if (checkboardCache[key]) {
    return checkboardCache[key];
  }
  checkboardCache[key] = checkboard;
  return checkboard;
};

/***/ }),

/***/ "Lx/H":
/*!******************************************************************!*\
  !*** ./node_modules/react-color/lib/components/github/Github.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Github = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _map = __webpack_require__(/*! lodash/map */ "3WF5");

var _map2 = _interopRequireDefault(_map);

var _merge = __webpack_require__(/*! lodash/merge */ "QkVN");

var _merge2 = _interopRequireDefault(_merge);

var _common = __webpack_require__(/*! ../common */ "TM95");

var _GithubSwatch = __webpack_require__(/*! ./GithubSwatch */ "iGDq");

var _GithubSwatch2 = _interopRequireDefault(_GithubSwatch);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var Github = exports.Github = function Github(_ref) {
  var width = _ref.width,
      colors = _ref.colors,
      onChange = _ref.onChange,
      onSwatchHover = _ref.onSwatchHover,
      triangle = _ref.triangle,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': {
      card: {
        width: width,
        background: '#fff',
        border: '1px solid rgba(0,0,0,0.2)',
        boxShadow: '0 3px 12px rgba(0,0,0,0.15)',
        borderRadius: '4px',
        position: 'relative',
        padding: '5px',
        display: 'flex',
        flexWrap: 'wrap'
      },
      triangle: {
        position: 'absolute',
        border: '7px solid transparent',
        borderBottomColor: '#fff'
      },
      triangleShadow: {
        position: 'absolute',
        border: '8px solid transparent',
        borderBottomColor: 'rgba(0,0,0,0.15)'
      }
    },
    'hide-triangle': {
      triangle: {
        display: 'none'
      },
      triangleShadow: {
        display: 'none'
      }
    },
    'top-left-triangle': {
      triangle: {
        top: '-14px',
        left: '10px'
      },
      triangleShadow: {
        top: '-16px',
        left: '9px'
      }
    },
    'top-right-triangle': {
      triangle: {
        top: '-14px',
        right: '10px'
      },
      triangleShadow: {
        top: '-16px',
        right: '9px'
      }
    },
    'bottom-left-triangle': {
      triangle: {
        top: '35px',
        left: '10px',
        transform: 'rotate(180deg)'
      },
      triangleShadow: {
        top: '37px',
        left: '9px',
        transform: 'rotate(180deg)'
      }
    },
    'bottom-right-triangle': {
      triangle: {
        top: '35px',
        right: '10px',
        transform: 'rotate(180deg)'
      },
      triangleShadow: {
        top: '37px',
        right: '9px',
        transform: 'rotate(180deg)'
      }
    }
  }, passedStyles), {
    'hide-triangle': triangle === 'hide',
    'top-left-triangle': triangle === 'top-left',
    'top-right-triangle': triangle === 'top-right',
    'bottom-left-triangle': triangle == 'bottom-left',
    'bottom-right-triangle': triangle === 'bottom-right'
  });

  var handleChange = function handleChange(hex, e) {
    return onChange({ hex: hex, source: 'hex' }, e);
  };

  return _react2.default.createElement(
    'div',
    { style: styles.card, className: 'github-picker ' + className },
    _react2.default.createElement('div', { style: styles.triangleShadow }),
    _react2.default.createElement('div', { style: styles.triangle }),
    (0, _map2.default)(colors, function (c) {
      return _react2.default.createElement(_GithubSwatch2.default, {
        color: c,
        key: c,
        onClick: handleChange,
        onSwatchHover: onSwatchHover
      });
    })
  );
};

Github.propTypes = {
  width: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]),
  colors: _propTypes2.default.arrayOf(_propTypes2.default.string),
  triangle: _propTypes2.default.oneOf(['hide', 'top-left', 'top-right', 'bottom-left', 'bottom-right']),
  styles: _propTypes2.default.object
};

Github.defaultProps = {
  width: 200,
  colors: ['#B80000', '#DB3E00', '#FCCB00', '#008B02', '#006B76', '#1273DE', '#004DCF', '#5300EB', '#EB9694', '#FAD0C3', '#FEF3BD', '#C1E1C5', '#BEDADC', '#C4DEF6', '#BED3F3', '#D4C4FB'],
  triangle: 'top-left',
  styles: {}
};

exports.default = (0, _common.ColorWrap)(Github);

/***/ }),

/***/ "LxhV":
/*!*********************************************************!*\
  !*** ./node_modules/@phosphor/collections/lib/index.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
__export(__webpack_require__(/*! ./linkedlist */ "pHe9"));


/***/ }),

/***/ "M1xp":
/*!**********************************************************!*\
  !*** ./node_modules/core-js/library/modules/_iobject.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__(/*! ./_cof */ "a0xu");
// eslint-disable-next-line no-prototype-builtins
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {
  return cof(it) == 'String' ? it.split('') : Object(it);
};


/***/ }),

/***/ "M2ap":
/*!***************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/traceTypes.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Trace type constants
 */

var chartCategory = exports.chartCategory = function chartCategory(_) {
  return {
    SIMPLE: {
      value: 'SIMPLE',
      label: _('Simple')
    },
    FINANCIAL: {
      value: 'FINANCIAL',
      label: _('Finance')
    },
    DISTRIBUTIONS: {
      value: 'DISTRIBUTIONS',
      label: _('Distributions')
    },
    MAPS: {
      value: 'MAPS',
      label: _('Maps')
    },
    SPECIALIZED: {
      value: 'SPECIALIZED',
      label: _('Specialized')
    },
    THREE_D: {
      value: '3D',
      label: _('3D'),
      maxColumns: 1
    },
    HIDDEN: {
      value: 'HIDDEN',
      label: ''
    }
  };
};

// Layout specification for TraceTypeSelector.js
var categoryLayout = exports.categoryLayout = function categoryLayout(_) {
  return [chartCategory(_).SIMPLE, chartCategory(_).DISTRIBUTIONS, chartCategory(_).THREE_D, chartCategory(_).MAPS, chartCategory(_).FINANCIAL, chartCategory(_).SPECIALIZED];
};

var traceTypes = exports.traceTypes = function traceTypes(_) {
  return [{
    value: 'scatter',
    label: _('Scatter'),
    category: chartCategory(_).SIMPLE
  }, {
    value: 'bar',
    label: _('Bar'),
    category: chartCategory(_).SIMPLE
  }, {
    value: 'line',
    label: _('Line'),
    category: chartCategory(_).SIMPLE
  }, {
    value: 'area',
    label: _('Area'),
    category: chartCategory(_).SIMPLE
  }, {
    value: 'heatmap',
    label: _('Heatmap'),
    category: chartCategory(_).SIMPLE
  }, {
    value: 'table',
    label: _('Table'),
    category: chartCategory(_).SIMPLE
  }, {
    value: 'contour',
    label: _('Contour'),
    category: chartCategory(_).SIMPLE
  }, {
    value: 'pie',
    label: _('Pie'),
    category: chartCategory(_).SIMPLE
  }, {
    value: 'scatter3d',
    label: _('3D Scatter'),
    category: chartCategory(_).THREE_D
  }, {
    value: 'line3d',
    label: _('3D Line'),
    category: chartCategory(_).THREE_D
  }, {
    value: 'surface',
    label: _('3D Surface'),
    category: chartCategory(_).THREE_D
  }, {
    value: 'mesh3d',
    label: _('3D Mesh'),
    category: chartCategory(_).THREE_D
  }, {
    value: 'cone',
    label: _('Cone'),
    category: chartCategory(_).THREE_D
  }, {
    value: 'streamtube',
    label: _('Streamtube'),
    category: chartCategory(_).THREE_D
  }, {
    value: 'box',
    label: _('Box'),
    category: chartCategory(_).DISTRIBUTIONS
  }, {
    value: 'violin',
    label: _('Violin'),
    category: chartCategory(_).DISTRIBUTIONS
  }, {
    value: 'histogram',
    label: _('Histogram'),
    category: chartCategory(_).DISTRIBUTIONS
  }, {
    value: 'histogram2d',
    label: _('2D Histogram'),
    category: chartCategory(_).DISTRIBUTIONS
  }, {
    value: 'histogram2dcontour',
    label: _('2D Contour Histogram'),
    category: chartCategory(_).DISTRIBUTIONS
  }, {
    value: 'choropleth',
    label: _('Choropleth'),
    category: chartCategory(_).MAPS
  }, {
    value: 'scattermapbox',
    label: _('Satellite Map'),
    category: chartCategory(_).MAPS
  }, {
    value: 'scattergeo',
    label: _('Atlas Map'),
    category: chartCategory(_).MAPS
  }, {
    value: 'scatterpolar',
    label: _('Polar Scatter'),
    category: chartCategory(_).SPECIALIZED
  }, {
    value: 'barpolar',
    label: _('Polar Bar'),
    category: chartCategory(_).SPECIALIZED
  }, {
    value: 'scatterternary',
    label: _('Ternary Scatter'),
    category: chartCategory(_).SPECIALIZED
  }, {
    value: 'candlestick',
    label: _('Candlestick'),
    category: chartCategory(_).FINANCIAL
  }, {
    value: 'ohlc',
    label: _('OHLC'),
    category: chartCategory(_).FINANCIAL
  }, {
    value: 'scattergl',
    icon: 'scatter',
    label: _('Scatter'),
    category: chartCategory(_).THREE_D
  }, {
    value: 'scatterpolargl',
    icon: 'scatterpolar',
    label: _('Polar Scatter'),
    category: chartCategory(_).THREE_D
  }, {
    value: 'heatmapgl',
    icon: 'heatmap',
    label: _('Heatmap GL'),
    category: chartCategory(_).HIDDEN
  }, {
    value: 'pointcloud',
    label: _('Point Cloud'),
    category: chartCategory(_).HIDDEN
  }, {
    value: 'parcoords',
    label: _('Parallel Coordinates'),
    category: chartCategory(_).HIDDEN
  }, {
    value: 'parcats',
    label: _('Parallel Categories'),
    category: chartCategory(_).HIDDEN
  }, {
    value: 'splom',
    label: _('Scatterplot Matrix'),
    category: chartCategory(_).HIDDEN
  }, {
    value: 'sankey',
    label: _('Sankey'),
    category: chartCategory(_).HIDDEN
  }, {
    value: 'scattercarpet',
    label: _('Scatter Carpet'),
    category: chartCategory(_).HIDDEN
  }, {
    value: 'contourcarpet',
    label: _('Contour Carpet'),
    category: chartCategory(_).HIDDEN
  }, {
    value: 'carpet',
    label: _('Carpet'),
    category: chartCategory(_).HIDDEN
  }, {
    value: 'isosurface',
    label: _('Isosurface'),
    category: chartCategory(_).HIDDEN
  }];
};
//# sourceMappingURL=traceTypes.js.map

/***/ }),

/***/ "M4OJ":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/mainmenu/lib/mainmenu.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const file_1 = __webpack_require__(/*! ./file */ "EqA/");
const edit_1 = __webpack_require__(/*! ./edit */ "qeiu");
const help_1 = __webpack_require__(/*! ./help */ "PuQA");
const kernel_1 = __webpack_require__(/*! ./kernel */ "T2Ng");
const run_1 = __webpack_require__(/*! ./run */ "tNxU");
const settings_1 = __webpack_require__(/*! ./settings */ "YrNz");
const view_1 = __webpack_require__(/*! ./view */ "gqd8");
const tabs_1 = __webpack_require__(/*! ./tabs */ "3C5O");
/* tslint:disable */
/**
 * The main menu token.
 */
exports.IMainMenu = new coreutils_1.Token('@jupyterlab/mainmenu:IMainMenu');
/**
 * The main menu class.  It is intended to be used as a singleton.
 */
class MainMenu extends widgets_1.MenuBar {
    /**
     * Construct the main menu bar.
     */
    constructor(commands) {
        super();
        this._items = [];
        this.editMenu = new edit_1.EditMenu({ commands });
        this.fileMenu = new file_1.FileMenu({ commands });
        this.helpMenu = new help_1.HelpMenu({ commands });
        this.kernelMenu = new kernel_1.KernelMenu({ commands });
        this.runMenu = new run_1.RunMenu({ commands });
        this.settingsMenu = new settings_1.SettingsMenu({ commands });
        this.viewMenu = new view_1.ViewMenu({ commands });
        this.tabsMenu = new tabs_1.TabsMenu({ commands });
        this.addMenu(this.fileMenu.menu, { rank: 0 });
        this.addMenu(this.editMenu.menu, { rank: 1 });
        this.addMenu(this.viewMenu.menu, { rank: 2 });
        this.addMenu(this.runMenu.menu, { rank: 3 });
        this.addMenu(this.kernelMenu.menu, { rank: 4 });
        this.addMenu(this.tabsMenu.menu, { rank: 500 });
        this.addMenu(this.settingsMenu.menu, { rank: 999 });
        this.addMenu(this.helpMenu.menu, { rank: 1000 });
    }
    /**
     * Add a new menu to the main menu bar.
     */
    addMenu(menu, options = {}) {
        if (algorithm_1.ArrayExt.firstIndexOf(this.menus, menu) > -1) {
            return;
        }
        let rank = 'rank' in options ? options.rank : 100;
        let rankItem = { menu, rank };
        let index = algorithm_1.ArrayExt.upperBound(this._items, rankItem, Private.itemCmp);
        // Upon disposal, remove the menu and its rank reference.
        menu.disposed.connect(this._onMenuDisposed, this);
        algorithm_1.ArrayExt.insert(this._items, index, rankItem);
        /**
         * Create a new menu.
         */
        this.insertMenu(index, menu);
    }
    /**
     * Dispose of the resources held by the menu bar.
     */
    dispose() {
        this.editMenu.dispose();
        this.fileMenu.dispose();
        this.helpMenu.dispose();
        this.kernelMenu.dispose();
        this.runMenu.dispose();
        this.settingsMenu.dispose();
        this.viewMenu.dispose();
        this.tabsMenu.dispose();
        super.dispose();
    }
    /**
     * Handle the disposal of a menu.
     */
    _onMenuDisposed(menu) {
        this.removeMenu(menu);
        let index = algorithm_1.ArrayExt.findFirstIndex(this._items, item => item.menu === menu);
        if (index !== -1) {
            algorithm_1.ArrayExt.removeAt(this._items, index);
        }
    }
}
exports.MainMenu = MainMenu;
/**
 * A namespace for private data.
 */
var Private;
(function (Private) {
    /**
     * A comparator function for menu rank items.
     */
    function itemCmp(first, second) {
        return first.rank - second.rank;
    }
    Private.itemCmp = itemCmp;
})(Private || (Private = {}));


/***/ }),

/***/ "M6rc":
/*!**************************************************************!*\
  !*** ./node_modules/draft-js/lib/ContentStateInlineStyle.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule ContentStateInlineStyle
 * @format
 * 
 */



var CharacterMetadata = __webpack_require__(/*! ./CharacterMetadata */ "lFJn");

var _require = __webpack_require__(/*! immutable */ "JPcv"),
    Map = _require.Map;

var ContentStateInlineStyle = {
  add: function add(contentState, selectionState, inlineStyle) {
    return modifyInlineStyle(contentState, selectionState, inlineStyle, true);
  },

  remove: function remove(contentState, selectionState, inlineStyle) {
    return modifyInlineStyle(contentState, selectionState, inlineStyle, false);
  }
};

function modifyInlineStyle(contentState, selectionState, inlineStyle, addOrRemove) {
  var blockMap = contentState.getBlockMap();
  var startKey = selectionState.getStartKey();
  var startOffset = selectionState.getStartOffset();
  var endKey = selectionState.getEndKey();
  var endOffset = selectionState.getEndOffset();

  var newBlocks = blockMap.skipUntil(function (_, k) {
    return k === startKey;
  }).takeUntil(function (_, k) {
    return k === endKey;
  }).concat(Map([[endKey, blockMap.get(endKey)]])).map(function (block, blockKey) {
    var sliceStart;
    var sliceEnd;

    if (startKey === endKey) {
      sliceStart = startOffset;
      sliceEnd = endOffset;
    } else {
      sliceStart = blockKey === startKey ? startOffset : 0;
      sliceEnd = blockKey === endKey ? endOffset : block.getLength();
    }

    var chars = block.getCharacterList();
    var current;
    while (sliceStart < sliceEnd) {
      current = chars.get(sliceStart);
      chars = chars.set(sliceStart, addOrRemove ? CharacterMetadata.applyStyle(current, inlineStyle) : CharacterMetadata.removeStyle(current, inlineStyle));
      sliceStart++;
    }

    return block.set('characterList', chars);
  });

  return contentState.merge({
    blockMap: blockMap.merge(newBlocks),
    selectionBefore: selectionState,
    selectionAfter: selectionState
  });
}

module.exports = ContentStateInlineStyle;

/***/ }),

/***/ "MD8t":
/*!*************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/PlotlyEditor.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _factory = __webpack_require__(/*! react-plotly.js/factory */ "qT3F");

var _factory2 = _interopRequireDefault(_factory);

var _EditorControls = __webpack_require__(/*! ./EditorControls */ "i8+h");

var _EditorControls2 = _interopRequireDefault(_EditorControls);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _constants = __webpack_require__(/*! ./lib/constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var PlotlyEditor = function (_Component) {
  _inherits(PlotlyEditor, _Component);

  function PlotlyEditor(props) {
    _classCallCheck(this, PlotlyEditor);

    var _this = _possibleConstructorReturn(this, (PlotlyEditor.__proto__ || Object.getPrototypeOf(PlotlyEditor)).call(this));

    _this.state = { graphDiv: {} };
    _this.PlotComponent = (0, _factory2.default)(props.plotly);
    _this.handleRender = _this.handleRender.bind(_this);
    return _this;
  }

  _createClass(PlotlyEditor, [{
    key: 'handleRender',
    value: function handleRender(fig, graphDiv) {
      this.setState({ graphDiv: graphDiv });
      if (this.props.onRender) {
        this.props.onRender(graphDiv.data, graphDiv.layout, graphDiv._transitionData._frames);
      }
    }
  }, {
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        'div',
        { className: 'plotly_editor' },
        !this.props.hideControls && _react2.default.createElement(
          _EditorControls2.default,
          {
            graphDiv: this.state.graphDiv,
            dataSources: this.props.dataSources,
            dataSourceOptions: this.props.dataSourceOptions,
            plotly: this.props.plotly,
            onUpdate: this.props.onUpdate,
            advancedTraceTypeSelector: this.props.advancedTraceTypeSelector,
            locale: this.props.locale,
            traceTypesConfig: this.props.traceTypesConfig,
            dictionaries: this.props.dictionaries,
            showFieldTooltips: this.props.showFieldTooltips,
            srcConverters: this.props.srcConverters,
            makeDefaultTrace: this.props.makeDefaultTrace,
            glByDefault: this.props.glByDefault,
            mapBoxAccess: Boolean(this.props.config && this.props.config.mapboxAccessToken),
            fontOptions: this.props.fontOptions,
            chartHelp: this.props.chartHelp
          },
          this.props.children
        ),
        _react2.default.createElement(
          'div',
          { className: 'plotly_editor_plot', style: { width: '100%', height: '100%' } },
          _react2.default.createElement(this.PlotComponent, {
            data: this.props.data,
            layout: this.props.layout,
            frames: this.props.frames,
            config: this.props.config,
            useResizeHandler: this.props.useResizeHandler,
            debug: this.props.debug,
            onInitialized: this.handleRender,
            onUpdate: this.handleRender,
            style: { width: '100%', height: '100%' },
            divId: this.props.divId
          })
        )
      );
    }
  }]);

  return PlotlyEditor;
}(_react.Component);

PlotlyEditor.propTypes = {
  children: _propTypes2.default.any,
  layout: _propTypes2.default.object,
  data: _propTypes2.default.array,
  config: _propTypes2.default.object,
  dataSourceOptions: _propTypes2.default.array,
  dataSources: _propTypes2.default.object,
  frames: _propTypes2.default.array,
  onUpdate: _propTypes2.default.func,
  onRender: _propTypes2.default.func,
  plotly: _propTypes2.default.object,
  useResizeHandler: _propTypes2.default.bool,
  debug: _propTypes2.default.bool,
  advancedTraceTypeSelector: _propTypes2.default.bool,
  locale: _propTypes2.default.string,
  traceTypesConfig: _propTypes2.default.object,
  dictionaries: _propTypes2.default.object,
  divId: _propTypes2.default.string,
  hideControls: _propTypes2.default.bool,
  showFieldTooltips: _propTypes2.default.bool,
  srcConverters: _propTypes2.default.shape({
    toSrc: _propTypes2.default.func.isRequired,
    fromSrc: _propTypes2.default.func.isRequired
  }),
  makeDefaultTrace: _propTypes2.default.func,
  glByDefault: _propTypes2.default.bool,
  fontOptions: _propTypes2.default.array,
  chartHelp: _propTypes2.default.object
};

PlotlyEditor.defaultProps = {
  hideControls: false,
  showFieldTooltips: false,
  fontOptions: _constants.DEFAULT_FONTS
};

exports.default = PlotlyEditor;
//# sourceMappingURL=PlotlyEditor.js.map

/***/ }),

/***/ "MGuP":
/*!*************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/default_panels/StyleUpdateMenusPanel.js ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _components = __webpack_require__(/*! ../components */ "yF51");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var StyleUpdateMenusPanel = function StyleUpdateMenusPanel(props, _ref) {
  var _ = _ref.localize;
  return _react2.default.createElement(
    _components.UpdateMenuAccordion,
    null,
    _react2.default.createElement(
      _components.VisibilitySelect,
      {
        attr: 'visible',
        options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }],
        showOn: true
      },
      _react2.default.createElement(
        _components.PlotlySection,
        { name: _('Button Labels') },
        _react2.default.createElement(_components.UpdateMenuButtons, { attr: 'buttons' })
      ),
      _react2.default.createElement(
        _components.PlotlySection,
        { name: _('Background') },
        _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'bgcolor' })
      ),
      _react2.default.createElement(
        _components.PlotlySection,
        { name: _('Font') },
        _react2.default.createElement(_components.FontSelector, { label: _('Typeface'), attr: 'font.family' }),
        _react2.default.createElement(_components.Numeric, { label: _('Size'), attr: 'font.size' }),
        _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'font.color' })
      ),
      _react2.default.createElement(
        _components.PlotlySection,
        { name: _('Border') },
        _react2.default.createElement(_components.Numeric, { label: _('Width'), attr: 'borderwidth' }),
        _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'bordercolor' })
      ),
      _react2.default.createElement(
        _components.PlotlySection,
        { name: _('Horizontal Positioning'), attr: 'x' },
        _react2.default.createElement(_components.Numeric, { label: _('Position'), attr: 'x', showSlider: true, step: 0.02 }),
        _react2.default.createElement(_components.Radio, {
          label: _('Anchor'),
          attr: 'xanchor',
          options: [{ label: _('Left'), value: 'left' }, { label: _('Center'), value: 'center' }, { label: _('Right'), value: 'right' }]
        })
      ),
      _react2.default.createElement(
        _components.PlotlySection,
        { name: _('Vertical Positioning'), attr: 'y' },
        _react2.default.createElement(_components.Numeric, { label: _('Position'), attr: 'y', showSlider: true, step: 0.02 }),
        _react2.default.createElement(_components.Radio, {
          label: _('Anchor'),
          attr: 'yanchor',
          options: [{ label: _('Top'), value: 'top' }, { label: _('Middle'), value: 'middle' }, { label: _('Bottom'), value: 'bottom' }]
        })
      ),
      _react2.default.createElement(
        _components.PlotlySection,
        { name: _('Padding') },
        _react2.default.createElement(_components.Numeric, { label: _('Top'), attr: 'pad.t', units: 'px' }),
        _react2.default.createElement(_components.Numeric, { label: _('Bottom'), attr: 'pad.b', units: 'px' }),
        _react2.default.createElement(_components.Numeric, { label: _('Left'), attr: 'pad.l', units: 'px' }),
        _react2.default.createElement(_components.Numeric, { label: _('Right'), attr: 'pad.r', units: 'px' })
      )
    )
  );
};

StyleUpdateMenusPanel.contextTypes = {
  localize: _propTypes2.default.func
};

exports.default = StyleUpdateMenusPanel;
//# sourceMappingURL=StyleUpdateMenusPanel.js.map

/***/ }),

/***/ "MGx7":
/*!****************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/identity.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



// Simple helper functions
// none of these need any external deps

module.exports = function identity(d) { return d; };


/***/ }),

/***/ "MM3R":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/filebrowser/lib/model.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const docmanager_1 = __webpack_require__(/*! @jupyterlab/docmanager */ "kL29");
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const coreutils_2 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
/**
 * The default duration of the auto-refresh in ms
 */
const DEFAULT_REFRESH_INTERVAL = 10000;
/**
 * The enforced time between refreshes in ms.
 */
const MIN_REFRESH = 1000;
/**
 * The maximum upload size (in bytes) for notebook version < 5.1.0
 */
exports.LARGE_FILE_SIZE = 15 * 1024 * 1024;
/**
 * The size (in bytes) of the biggest chunk we should upload at once.
 */
exports.CHUNK_SIZE = 1024 * 1024;
/**
 * An implementation of a file browser model.
 *
 * #### Notes
 * All paths parameters without a leading `'/'` are interpreted as relative to
 * the current directory.  Supports `'../'` syntax.
 */
class FileBrowserModel {
    /**
     * Construct a new file browser model.
     */
    constructor(options) {
        this._connectionFailure = new signaling_1.Signal(this);
        this._fileChanged = new signaling_1.Signal(this);
        this._items = [];
        this._key = '';
        this._pathChanged = new signaling_1.Signal(this);
        this._paths = new Set();
        this._pending = null;
        this._pendingPath = null;
        this._refreshed = new signaling_1.Signal(this);
        this._lastRefresh = -1;
        this._requested = false;
        this._sessions = [];
        this._state = null;
        this._timeoutId = -1;
        this._isDisposed = false;
        this._restored = new coreutils_2.PromiseDelegate();
        this._uploads = [];
        this._uploadChanged = new signaling_1.Signal(this);
        this.manager = options.manager;
        this._driveName = options.driveName || '';
        let rootPath = this._driveName ? this._driveName + ':' : '';
        this._model = {
            path: rootPath,
            name: coreutils_1.PathExt.basename(rootPath),
            type: 'directory',
            content: undefined,
            writable: false,
            created: 'unknown',
            last_modified: 'unknown',
            mimetype: 'text/plain',
            format: 'text'
        };
        this._state = options.state || null;
        this._baseRefreshDuration =
            options.refreshInterval || DEFAULT_REFRESH_INTERVAL;
        const { services } = options.manager;
        services.contents.fileChanged.connect(this._onFileChanged, this);
        services.sessions.runningChanged.connect(this._onRunningChanged, this);
        this._unloadEventListener = (e) => {
            if (this._uploads.length > 0) {
                const confirmationMessage = 'Files still uploading';
                e.returnValue = confirmationMessage;
                return confirmationMessage;
            }
        };
        window.addEventListener('beforeunload', this._unloadEventListener);
        this._scheduleUpdate();
        this._startTimer();
    }
    /**
     * A signal emitted when the file browser model loses connection.
     */
    get connectionFailure() {
        return this._connectionFailure;
    }
    /**
     * The drive name that gets prepended to the path.
     */
    get driveName() {
        return this._driveName;
    }
    /**
     * A promise that resolves when the model is first restored.
     */
    get restored() {
        return this._restored.promise;
    }
    /**
     * Get the file path changed signal.
     */
    get fileChanged() {
        return this._fileChanged;
    }
    /**
     * Get the current path.
     */
    get path() {
        return this._model ? this._model.path : '';
    }
    /**
     * A signal emitted when the path changes.
     */
    get pathChanged() {
        return this._pathChanged;
    }
    /**
     * A signal emitted when the directory listing is refreshed.
     */
    get refreshed() {
        return this._refreshed;
    }
    /**
     * Get the kernel spec models.
     */
    get specs() {
        return this.manager.services.sessions.specs;
    }
    /**
     * Get whether the model is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * A signal emitted when an upload progresses.
     */
    get uploadChanged() {
        return this._uploadChanged;
    }
    /**
     * Create an iterator over the status of all in progress uploads.
     */
    uploads() {
        return new algorithm_1.ArrayIterator(this._uploads);
    }
    /**
     * Dispose of the resources held by the model.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        window.removeEventListener('beforeunload', this._unloadEventListener);
        this._isDisposed = true;
        clearTimeout(this._timeoutId);
        this._sessions.length = 0;
        this._items.length = 0;
        signaling_1.Signal.clearData(this);
    }
    /**
     * Create an iterator over the model's items.
     *
     * @returns A new iterator over the model's items.
     */
    items() {
        return new algorithm_1.ArrayIterator(this._items);
    }
    /**
     * Create an iterator over the active sessions in the directory.
     *
     * @returns A new iterator over the model's active sessions.
     */
    sessions() {
        return new algorithm_1.ArrayIterator(this._sessions);
    }
    /**
     * Force a refresh of the directory contents.
     */
    refresh() {
        this._lastRefresh = new Date().getTime();
        this._requested = false;
        return this.cd('.');
    }
    /**
     * Change directory.
     *
     * @param path - The path to the file or directory.
     *
     * @returns A promise with the contents of the directory.
     */
    cd(newValue = '.') {
        return __awaiter(this, void 0, void 0, function* () {
            if (newValue !== '.') {
                newValue = Private.normalizePath(this.manager.services.contents, this._model.path, newValue);
            }
            else {
                newValue = this._pendingPath || this._model.path;
            }
            if (this._pending) {
                // Collapse requests to the same directory.
                if (newValue === this._pendingPath) {
                    return this._pending;
                }
                // Otherwise wait for the pending request to complete before continuing.
                yield this._pending;
            }
            let oldValue = this.path;
            let options = { content: true };
            this._pendingPath = newValue;
            if (oldValue !== newValue) {
                this._sessions.length = 0;
            }
            let services = this.manager.services;
            this._pending = services.contents
                .get(newValue, options)
                .then(contents => {
                if (this.isDisposed) {
                    return;
                }
                this._refreshDuration = this._baseRefreshDuration;
                this._handleContents(contents);
                this._pendingPath = null;
                if (oldValue !== newValue) {
                    // If there is a state database and a unique key, save the new path.
                    if (this._state && this._key) {
                        this._state.save(this._key, { path: newValue });
                    }
                    this._pathChanged.emit({
                        name: 'path',
                        oldValue,
                        newValue
                    });
                }
                this._onRunningChanged(services.sessions, services.sessions.running());
                this._refreshed.emit(void 0);
            })
                .catch(error => {
                this._pendingPath = null;
                if (error.message === 'Not Found') {
                    error.message = `Directory not found: "${this._model.path}"`;
                    console.error(error);
                    this._connectionFailure.emit(error);
                    return this.cd('/');
                }
                else {
                    this._refreshDuration = this._baseRefreshDuration * 10;
                    this._connectionFailure.emit(error);
                }
            });
            return this._pending;
        });
    }
    /**
     * Download a file.
     *
     * @param path - The path of the file to be downloaded.
     *
     * @returns A promise which resolves when the file has begun
     *   downloading.
     */
    download(path) {
        return this.manager.services.contents.getDownloadUrl(path).then(url => {
            let element = document.createElement('a');
            document.body.appendChild(element);
            element.setAttribute('href', url);
            element.setAttribute('download', '');
            element.click();
            document.body.removeChild(element);
            return void 0;
        });
    }
    /**
     * Restore the state of the file browser.
     *
     * @param id - The unique ID that is used to construct a state database key.
     *
     * @returns A promise when restoration is complete.
     *
     * #### Notes
     * This function will only restore the model *once*. If it is called multiple
     * times, all subsequent invocations are no-ops.
     */
    restore(id) {
        const state = this._state;
        const restored = !!this._key;
        if (!state || restored) {
            return Promise.resolve(void 0);
        }
        const manager = this.manager;
        const key = `file-browser-${id}:cwd`;
        const ready = manager.services.ready;
        return Promise.all([state.fetch(key), ready])
            .then(([cwd]) => {
            if (!cwd) {
                this._restored.resolve(void 0);
                return;
            }
            const path = cwd['path'];
            const localPath = manager.services.contents.localPath(path);
            return manager.services.contents
                .get(path)
                .then(() => this.cd(localPath))
                .catch(() => state.remove(key));
        })
            .catch(() => state.remove(key))
            .then(() => {
            this._key = key;
            this._restored.resolve(void 0);
        }); // Set key after restoration is done.
    }
    /**
     * Upload a `File` object.
     *
     * @param file - The `File` object to upload.
     *
     * @returns A promise containing the new file contents model.
     *
     * #### Notes
     * On Notebook version < 5.1.0, this will fail to upload files that are too
     * big to be sent in one request to the server. On newer versions, it will
     * ask for confirmation then upload the file in 1 MB chunks.
     */
    upload(file) {
        return __awaiter(this, void 0, void 0, function* () {
            const supportsChunked = coreutils_1.PageConfig.getNotebookVersion() >= [5, 1, 0];
            const largeFile = file.size > exports.LARGE_FILE_SIZE;
            if (largeFile && !supportsChunked) {
                let msg = `Cannot upload file (>${exports.LARGE_FILE_SIZE / (1024 * 1024)} MB). ${file.name}`;
                console.warn(msg);
                throw msg;
            }
            const err = 'File not uploaded';
            if (largeFile && !(yield this._shouldUploadLarge(file))) {
                throw 'Cancelled large file upload';
            }
            yield this._uploadCheckDisposed();
            yield this.refresh();
            yield this._uploadCheckDisposed();
            if (algorithm_1.find(this._items, i => i.name === file.name) &&
                !(yield docmanager_1.shouldOverwrite(file.name))) {
                throw err;
            }
            yield this._uploadCheckDisposed();
            const chunkedUpload = supportsChunked && file.size > exports.CHUNK_SIZE;
            return yield this._upload(file, chunkedUpload);
        });
    }
    _shouldUploadLarge(file) {
        return __awaiter(this, void 0, void 0, function* () {
            const { button } = yield apputils_1.showDialog({
                title: 'Large file size warning',
                body: `The file size is ${Math.round(file.size / (1024 * 1024))} MB. Do you still want to upload it?`,
                buttons: [apputils_1.Dialog.cancelButton(), apputils_1.Dialog.warnButton({ label: 'UPLOAD' })]
            });
            return button.accept;
        });
    }
    /**
     * Perform the actual upload.
     */
    _upload(file, chunked) {
        return __awaiter(this, void 0, void 0, function* () {
            // Gather the file model parameters.
            let path = this._model.path;
            path = path ? path + '/' + file.name : file.name;
            let name = file.name;
            let type = 'file';
            let format = 'base64';
            const uploadInner = (blob, chunk) => __awaiter(this, void 0, void 0, function* () {
                yield this._uploadCheckDisposed();
                let reader = new FileReader();
                reader.readAsDataURL(blob);
                yield new Promise((resolve, reject) => {
                    reader.onload = resolve;
                    reader.onerror = event => reject(`Failed to upload "${file.name}":` + event);
                });
                yield this._uploadCheckDisposed();
                // remove header https://stackoverflow.com/a/24289420/907060
                const content = reader.result.split(',')[1];
                let model = {
                    type,
                    format,
                    name,
                    chunk,
                    content
                };
                return yield this.manager.services.contents.save(path, model);
            });
            if (!chunked) {
                try {
                    return yield uploadInner(file);
                }
                catch (err) {
                    algorithm_1.ArrayExt.removeFirstWhere(this._uploads, uploadIndex => {
                        return file.name === uploadIndex.path;
                    });
                    throw err;
                }
            }
            let finalModel;
            let upload = { path, progress: 0 };
            this._uploadChanged.emit({
                name: 'start',
                newValue: upload,
                oldValue: null
            });
            for (let start = 0; !finalModel; start += exports.CHUNK_SIZE) {
                const end = start + exports.CHUNK_SIZE;
                const lastChunk = end >= file.size;
                const chunk = lastChunk ? -1 : end / exports.CHUNK_SIZE;
                const newUpload = { path, progress: start / file.size };
                this._uploads.splice(this._uploads.indexOf(upload));
                this._uploads.push(newUpload);
                this._uploadChanged.emit({
                    name: 'update',
                    newValue: newUpload,
                    oldValue: upload
                });
                upload = newUpload;
                let currentModel;
                try {
                    currentModel = yield uploadInner(file.slice(start, end), chunk);
                }
                catch (err) {
                    algorithm_1.ArrayExt.removeFirstWhere(this._uploads, uploadIndex => {
                        return file.name === uploadIndex.path;
                    });
                    this._uploadChanged.emit({
                        name: 'failure',
                        newValue: upload,
                        oldValue: null
                    });
                    throw err;
                }
                if (lastChunk) {
                    finalModel = currentModel;
                }
            }
            this._uploads.splice(this._uploads.indexOf(upload));
            this._uploadChanged.emit({
                name: 'finish',
                newValue: null,
                oldValue: upload
            });
            return finalModel;
        });
    }
    _uploadCheckDisposed() {
        if (this.isDisposed) {
            return Promise.reject('Filemanager disposed. File upload canceled');
        }
        return Promise.resolve();
    }
    /**
     * Handle an updated contents model.
     */
    _handleContents(contents) {
        // Update our internal data.
        this._model = {
            name: contents.name,
            path: contents.path,
            type: contents.type,
            content: undefined,
            writable: contents.writable,
            created: contents.created,
            last_modified: contents.last_modified,
            mimetype: contents.mimetype,
            format: contents.format
        };
        this._items = contents.content;
        this._paths.clear();
        contents.content.forEach((model) => {
            this._paths.add(model.path);
        });
    }
    /**
     * Handle a change to the running sessions.
     */
    _onRunningChanged(sender, models) {
        this._populateSessions(models);
        this._refreshed.emit(void 0);
    }
    /**
     * Handle a change on the contents manager.
     */
    _onFileChanged(sender, change) {
        let path = this._model.path;
        let { sessions } = this.manager.services;
        let { oldValue, newValue } = change;
        let value = oldValue && oldValue.path && coreutils_1.PathExt.dirname(oldValue.path) === path
            ? oldValue
            : newValue && newValue.path && coreutils_1.PathExt.dirname(newValue.path) === path
                ? newValue
                : undefined;
        // If either the old value or the new value is in the current path, update.
        if (value) {
            this._scheduleUpdate();
            this._populateSessions(sessions.running());
            this._fileChanged.emit(change);
            return;
        }
    }
    /**
     * Populate the model's sessions collection.
     */
    _populateSessions(models) {
        this._sessions.length = 0;
        algorithm_1.each(models, model => {
            if (this._paths.has(model.path)) {
                this._sessions.push(model);
            }
        });
    }
    /**
     * Start the internal refresh timer.
     */
    _startTimer() {
        this._timeoutId = window.setInterval(() => {
            if (this._requested) {
                this.refresh();
                return;
            }
            if (document.hidden) {
                // Don't poll when nobody's looking.
                return;
            }
            let date = new Date().getTime();
            if (date - this._lastRefresh > this._refreshDuration) {
                this.refresh();
            }
        }, MIN_REFRESH);
    }
    /**
     * Handle internal model refresh logic.
     */
    _scheduleUpdate() {
        let date = new Date().getTime();
        if (date - this._lastRefresh > MIN_REFRESH) {
            this.refresh();
        }
        else {
            this._requested = true;
        }
    }
}
exports.FileBrowserModel = FileBrowserModel;
/**
 * The namespace for the file browser model private data.
 */
var Private;
(function (Private) {
    /**
     * Normalize a path based on a root directory, accounting for relative paths.
     */
    function normalizePath(contents, root, path) {
        const driveName = contents.driveName(root);
        const localPath = contents.localPath(root);
        const resolved = coreutils_1.PathExt.resolve(localPath, path);
        return driveName ? `${driveName}:${resolved}` : resolved;
    }
    Private.normalizePath = normalizePath;
})(Private || (Private = {}));


/***/ }),

/***/ "MMmD":
/*!********************************************!*\
  !*** ./node_modules/lodash/isArrayLike.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isFunction = __webpack_require__(/*! ./isFunction */ "lSCD"),
    isLength = __webpack_require__(/*! ./isLength */ "shjB");

/**
 * 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);
}

module.exports = isArrayLike;


/***/ }),

/***/ "MNtL":
/*!*********************************************************!*\
  !*** ./node_modules/@jupyterlab/completer/lib/model.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const algorithm_2 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
/**
 * An implementation of a completer model.
 */
class CompleterModel {
    constructor() {
        this._current = null;
        this._cursor = null;
        this._isDisposed = false;
        this._options = [];
        this._original = null;
        this._query = '';
        this._subsetMatch = false;
        this._typeMap = {};
        this._orderedTypes = [];
        this._stateChanged = new signaling_1.Signal(this);
    }
    /**
     * A signal emitted when state of the completer menu changes.
     */
    get stateChanged() {
        return this._stateChanged;
    }
    /**
     * The original completion request details.
     */
    get original() {
        return this._original;
    }
    set original(newValue) {
        let unchanged = this._original === newValue ||
            (this._original &&
                newValue &&
                coreutils_1.JSONExt.deepEqual(newValue, this._original));
        if (unchanged) {
            return;
        }
        this._reset();
        // Set both the current and original to the same value when original is set.
        this._current = this._original = newValue;
        this._stateChanged.emit(undefined);
    }
    /**
     * The current text change details.
     */
    get current() {
        return this._current;
    }
    set current(newValue) {
        const unchanged = this._current === newValue ||
            (this._current && newValue && coreutils_1.JSONExt.deepEqual(newValue, this._current));
        if (unchanged) {
            return;
        }
        const original = this._original;
        // Original request must always be set before a text change. If it isn't
        // the model fails silently.
        if (!original) {
            return;
        }
        const cursor = this._cursor;
        // Cursor must always be set before a text change. This happens
        // automatically in the completer handler, but since `current` is a public
        // attribute, this defensive check is necessary.
        if (!cursor) {
            return;
        }
        const current = (this._current = newValue);
        if (!current) {
            this._stateChanged.emit(undefined);
            return;
        }
        const originalLine = original.text.split('\n')[original.line];
        const currentLine = current.text.split('\n')[current.line];
        // If the text change means that the original start point has been preceded,
        // then the completion is no longer valid and should be reset.
        if (currentLine.length < originalLine.length) {
            this.reset(true);
            return;
        }
        const { start, end } = this._cursor;
        // Clip the front of the current line.
        let query = current.text.substring(start);
        // Clip the back of the current line by calculating the end of the original.
        const ending = original.text.substring(end);
        query = query.substring(0, query.lastIndexOf(ending));
        this._query = query;
        this._stateChanged.emit(undefined);
    }
    /**
     * The cursor details that the API has used to return matching options.
     */
    get cursor() {
        return this._cursor;
    }
    set cursor(newValue) {
        // Original request must always be set before a cursor change. If it isn't
        // the model fails silently.
        if (!this.original) {
            return;
        }
        this._cursor = newValue;
    }
    /**
     * The query against which items are filtered.
     */
    get query() {
        return this._query;
    }
    set query(newValue) {
        this._query = newValue;
    }
    /**
     * A flag that is true when the model value was modified by a subset match.
     */
    get subsetMatch() {
        return this._subsetMatch;
    }
    set subsetMatch(newValue) {
        this._subsetMatch = newValue;
    }
    /**
     * Get whether the model is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources held by the model.
     */
    dispose() {
        // Do nothing if already disposed.
        if (this._isDisposed) {
            return;
        }
        this._isDisposed = true;
        signaling_1.Signal.clearData(this);
    }
    /**
     * The list of visible items in the completer menu.
     *
     * #### Notes
     * This is a read-only property.
     */
    items() {
        return this._filter();
    }
    /**
     * The unfiltered list of all available options in a completer menu.
     */
    options() {
        return algorithm_1.iter(this._options);
    }
    /**
     * The map from identifiers (a.b) to types (function, module, class, instance,
     * etc.).
     *
     * #### Notes
     * A type map is currently only provided by the latest IPython kernel using
     * the completer reply metadata field `_jupyter_types_experimental`. The
     * values are completely up to the kernel.
     *
     */
    typeMap() {
        return this._typeMap;
    }
    /**
     * An ordered list of all the known types in the typeMap.
     *
     * #### Notes
     * To visually encode the types of the completer matches, we assemble an
     * ordered list. This list begins with:
     * ```
     * ['function', 'instance', 'class', 'module', 'keyword']
     * ```
     * and then has any remaining types listed alphebetically. This will give
     * reliable visual encoding for these known types, but allow kernels to
     * provide new types.
     */
    orderedTypes() {
        return this._orderedTypes;
    }
    /**
     * Set the available options in the completer menu.
     */
    setOptions(newValue, typeMap) {
        const values = algorithm_1.toArray(newValue || []);
        const types = typeMap || {};
        if (coreutils_1.JSONExt.deepEqual(values, this._options) &&
            coreutils_1.JSONExt.deepEqual(types, this._typeMap)) {
            return;
        }
        if (values.length) {
            this._options = values;
            this._typeMap = types;
            this._orderedTypes = Private.findOrderedTypes(types);
            this._subsetMatch = true;
        }
        else {
            this._options = [];
            this._typeMap = {};
            this._orderedTypes = [];
        }
        this._stateChanged.emit(undefined);
    }
    /**
     * Handle a cursor change.
     */
    handleCursorChange(change) {
        // If there is no active completion, return.
        if (!this._original) {
            return;
        }
        const { column, line } = change;
        const { original } = this;
        if (!original) {
            return;
        }
        // If a cursor change results in a the cursor being on a different line
        // than the original request, cancel.
        if (line !== original.line) {
            this.reset(true);
            return;
        }
        // If a cursor change results in the cursor being set to a position that
        // precedes the original request, cancel.
        if (column < original.column) {
            this.reset(true);
            return;
        }
        const { cursor, current } = this;
        if (!cursor || !current) {
            return;
        }
        // If a cursor change results in the cursor being set to a position beyond
        // the end of the area that would be affected by completion, cancel.
        const cursorDelta = cursor.end - cursor.start;
        const originalLine = original.text.split('\n')[original.line];
        const currentLine = current.text.split('\n')[current.line];
        const inputDelta = currentLine.length - originalLine.length;
        if (column > original.column + cursorDelta + inputDelta) {
            this.reset(true);
            return;
        }
    }
    /**
     * Handle a text change.
     */
    handleTextChange(change) {
        const original = this._original;
        // If there is no active completion, return.
        if (!original) {
            return;
        }
        // When the completer detects a common subset prefix for all options,
        // it updates the model and sets the model source to that value, but this
        // text change should be ignored.
        if (this._subsetMatch) {
            return;
        }
        const { text, column, line } = change;
        const last = text.split('\n')[line][column - 1];
        // If last character entered is not whitespace or if the change column is
        // greater than or equal to the original column, update completion.
        if ((last && last.match(/\S/)) || change.column >= original.column) {
            this.current = change;
            return;
        }
        // If final character is whitespace, reset completion.
        this.reset(true);
    }
    /**
     * Create a resolved patch between the original state and a patch string.
     *
     * @param patch - The patch string to apply to the original value.
     *
     * @returns A patched text change or undefined if original value did not exist.
     */
    createPatch(patch) {
        const original = this._original;
        const cursor = this._cursor;
        if (!original || !cursor) {
            return undefined;
        }
        const { start, end } = cursor;
        const { text } = original;
        const prefix = text.substring(0, start);
        const suffix = text.substring(end);
        return { offset: (prefix + patch).length, text: prefix + patch + suffix };
    }
    /**
     * Reset the state of the model and emit a state change signal.
     *
     * @param hard - Reset even if a subset match is in progress.
     */
    reset(hard = false) {
        // When the completer detects a common subset prefix for all options,
        // it updates the model and sets the model source to that value, triggering
        // a reset. Unless explicitly a hard reset, this should be ignored.
        if (!hard && this._subsetMatch) {
            return;
        }
        this._subsetMatch = false;
        this._reset();
        this._stateChanged.emit(undefined);
    }
    /**
     * Apply the query to the complete options list to return the matching subset.
     */
    _filter() {
        let options = this._options || [];
        let query = this._query;
        if (!query) {
            return algorithm_1.map(options, option => ({ raw: option, text: option }));
        }
        let results = [];
        for (let option of options) {
            let match = algorithm_2.StringExt.matchSumOfSquares(option, query);
            if (match) {
                let marked = algorithm_2.StringExt.highlight(option, match.indices, Private.mark);
                results.push({
                    raw: option,
                    score: match.score,
                    text: marked.join('')
                });
            }
        }
        return algorithm_1.map(results.sort(Private.scoreCmp), result => ({
            text: result.text,
            raw: result.raw
        }));
    }
    /**
     * Reset the state of the model.
     */
    _reset() {
        this._current = null;
        this._cursor = null;
        this._options = [];
        this._original = null;
        this._query = '';
        this._subsetMatch = false;
        this._typeMap = {};
        this._orderedTypes = [];
    }
}
exports.CompleterModel = CompleterModel;
/**
 * A namespace for completer model private data.
 */
var Private;
(function (Private) {
    /**
     * The list of known type annotations of completer matches.
     */
    const KNOWN_TYPES = ['function', 'instance', 'class', 'module', 'keyword'];
    /**
     * The map of known type annotations of completer matches.
     */
    const KNOWN_MAP = KNOWN_TYPES.reduce((acc, type) => {
        acc[type] = null;
        return acc;
    }, {});
    /**
     * Mark a highlighted chunk of text.
     */
    function mark(value) {
        return `<mark>${value}</mark>`;
    }
    Private.mark = mark;
    /**
     * A sort comparison function for item match scores.
     *
     * #### Notes
     * This orders the items first based on score (lower is better), then
     * by locale order of the item text.
     */
    function scoreCmp(a, b) {
        let delta = a.score - b.score;
        if (delta !== 0) {
            return delta;
        }
        return a.raw.localeCompare(b.raw);
    }
    Private.scoreCmp = scoreCmp;
    /**
     * Compute a reliably ordered list of types.
     *
     * #### Notes
     * The resulting list always begins with the known types:
     * ```
     * ['function', 'instance', 'class', 'module', 'keyword']
     * ```
     * followed by other types in alphabetical order.
     */
    function findOrderedTypes(typeMap) {
        const filtered = Object.keys(typeMap)
            .map(key => typeMap[key])
            .filter(value => value && !(value in KNOWN_MAP))
            .sort((a, b) => a.localeCompare(b));
        return KNOWN_TYPES.concat(filtered);
    }
    Private.findOrderedTypes = findOrderedTypes;
})(Private || (Private = {}));


/***/ }),

/***/ "MPFp":
/*!**************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_iter-define.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var LIBRARY = __webpack_require__(/*! ./_library */ "uOPS");
var $export = __webpack_require__(/*! ./_export */ "Y7ZC");
var redefine = __webpack_require__(/*! ./_redefine */ "kTiW");
var hide = __webpack_require__(/*! ./_hide */ "NegM");
var Iterators = __webpack_require__(/*! ./_iterators */ "SBuE");
var $iterCreate = __webpack_require__(/*! ./_iter-create */ "j2DC");
var setToStringTag = __webpack_require__(/*! ./_set-to-string-tag */ "RfKB");
var getPrototypeOf = __webpack_require__(/*! ./_object-gpo */ "U+KD");
var ITERATOR = __webpack_require__(/*! ./_wks */ "UWiX")('iterator');
var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next`
var FF_ITERATOR = '@@iterator';
var KEYS = 'keys';
var VALUES = 'values';

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

module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {
  $iterCreate(Constructor, NAME, next);
  var getMethod = function (kind) {
    if (!BUGGY && kind in proto) return proto[kind];
    switch (kind) {
      case KEYS: return function keys() { return new Constructor(this, kind); };
      case VALUES: return function values() { return new Constructor(this, kind); };
    } return function entries() { return new Constructor(this, kind); };
  };
  var TAG = NAME + ' Iterator';
  var DEF_VALUES = DEFAULT == VALUES;
  var VALUES_BUG = false;
  var proto = Base.prototype;
  var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];
  var $default = $native || getMethod(DEFAULT);
  var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;
  var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;
  var methods, key, IteratorPrototype;
  // Fix native
  if ($anyNative) {
    IteratorPrototype = getPrototypeOf($anyNative.call(new Base()));
    if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) {
      // Set @@toStringTag to native iterators
      setToStringTag(IteratorPrototype, TAG, true);
      // fix for some old engines
      if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis);
    }
  }
  // fix Array#{values, @@iterator}.name in V8 / FF
  if (DEF_VALUES && $native && $native.name !== VALUES) {
    VALUES_BUG = true;
    $default = function values() { return $native.call(this); };
  }
  // Define iterator
  if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) {
    hide(proto, ITERATOR, $default);
  }
  // Plug for library
  Iterators[NAME] = $default;
  Iterators[TAG] = returnThis;
  if (DEFAULT) {
    methods = {
      values: DEF_VALUES ? $default : getMethod(VALUES),
      keys: IS_SET ? $default : getMethod(KEYS),
      entries: $entries
    };
    if (FORCED) for (key in methods) {
      if (!(key in proto)) redefine(proto, key, methods[key]);
    } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
  }
  return methods;
};


/***/ }),

/***/ "MPKC":
/*!**************************************************************!*\
  !*** ./node_modules/draft-js/lib/keyCommandInsertNewline.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule keyCommandInsertNewline
 * @format
 * 
 */



var DraftModifier = __webpack_require__(/*! ./DraftModifier */ "fyOY");
var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");

function keyCommandInsertNewline(editorState) {
  var contentState = DraftModifier.splitBlock(editorState.getCurrentContent(), editorState.getSelection());
  return EditorState.push(editorState, contentState, 'split-block');
}

module.exports = keyCommandInsertNewline;

/***/ }),

/***/ "MSdE":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/csvviewer/lib/toolbar.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
/**
 * The supported parsing delimiters.
 */
const DELIMITERS = [',', ';', '\t', '|'];
/**
 * The labels for each delimiter as they appear in the dropdown menu.
 */
const LABELS = [',', ';', 'tab', 'pipe'];
/**
 * The class name added to a csv toolbar widget.
 */
const CSV_DELIMITER_CLASS = 'jp-CSVDelimiter';
const CSV_DELIMITER_LABEL_CLASS = 'jp-CSVDelimiter-label';
/**
 * The class name added to a csv toolbar's dropdown element.
 */
const CSV_DELIMITER_DROPDOWN_CLASS = 'jp-CSVDelimiter-dropdown';
/**
 * A widget for selecting a delimiter.
 */
class CSVDelimiter extends widgets_1.Widget {
    /**
     * Construct a new csv table widget.
     */
    constructor(options) {
        super({ node: Private.createNode(options.selected) });
        this._delimiterChanged = new signaling_1.Signal(this);
        this.addClass(CSV_DELIMITER_CLASS);
    }
    /**
     * A signal emitted when the delimiter selection has changed.
     */
    get delimiterChanged() {
        return this._delimiterChanged;
    }
    /**
     * The delimiter dropdown menu.
     */
    get selectNode() {
        return this.node.getElementsByTagName('select')[0];
    }
    /**
     * Handle the DOM events for the widget.
     *
     * @param event - The DOM event sent to the widget.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the dock panel's node. It should
     * not be called directly by user code.
     */
    handleEvent(event) {
        switch (event.type) {
            case 'change':
                this._delimiterChanged.emit(this.selectNode.value);
                break;
            default:
                break;
        }
    }
    /**
     * Handle `after-attach` messages for the widget.
     */
    onAfterAttach(msg) {
        this.selectNode.addEventListener('change', this);
    }
    /**
     * Handle `before-detach` messages for the widget.
     */
    onBeforeDetach(msg) {
        this.selectNode.removeEventListener('change', this);
    }
}
exports.CSVDelimiter = CSVDelimiter;
/**
 * A namespace for private toolbar methods.
 */
var Private;
(function (Private) {
    /**
     * Create the node for the delimiter switcher.
     */
    function createNode(selected) {
        let div = document.createElement('div');
        let label = document.createElement('span');
        let select = document.createElement('select');
        label.textContent = 'Delimiter: ';
        label.className = CSV_DELIMITER_LABEL_CLASS;
        algorithm_1.each(algorithm_1.zip(DELIMITERS, LABELS), ([delimiter, label]) => {
            let option = document.createElement('option');
            option.value = delimiter;
            option.textContent = label;
            if (delimiter === selected) {
                option.selected = true;
            }
            select.appendChild(option);
        });
        div.appendChild(label);
        let node = apputils_1.Styling.wrapSelect(select);
        node.classList.add(CSV_DELIMITER_DROPDOWN_CLASS);
        div.appendChild(node);
        return div;
    }
    Private.createNode = createNode;
})(Private || (Private = {}));


/***/ }),

/***/ "MZLl":
/*!******************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/session/session.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const default_1 = __webpack_require__(/*! ./default */ "q4Uc");
/**
 * A namespace for session interfaces and factory functions.
 */
var Session;
(function (Session) {
    /**
     * List the running sessions.
     *
     * @param settings - The server settings to use for the request.
     *
     * @returns A promise that resolves with the list of session models.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/sessions), and validates the response.
     *
     * All client-side sessions are updated with current information.
     *
     * The promise is fulfilled on a valid response and rejected otherwise.
     */
    function listRunning(settings) {
        return default_1.DefaultSession.listRunning(settings);
    }
    Session.listRunning = listRunning;
    /**
     * Start a new session.
     *
     * @param options - The options used to start the session.
     *
     * @returns A promise that resolves with the session instance.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/sessions), and validates the response.
     *
     * A path must be provided.  If a kernel id is given, it will
     * connect to an existing kernel.  If no kernel id or name is given,
     * the server will start the default kernel type.
     *
     * The promise is fulfilled on a valid response and rejected otherwise.
     *
     * Wrap the result in an Session object. The promise is fulfilled
     * when the session is created on the server, otherwise the promise is
     * rejected.
     */
    function startNew(options) {
        return default_1.DefaultSession.startNew(options);
    }
    Session.startNew = startNew;
    /**
     * Find a session by id.
     *
     * @param id - The id of the target session.
     *
     * @param settings - The server settings.
     *
     * @returns A promise that resolves with the session model.
     *
     * #### Notes
     * If the session was already started via `startNew`, the existing
     * Session object's information is used in the fulfillment value.
     *
     * Otherwise, we attempt to find to the existing session.
     * The promise is fulfilled when the session is found,
     * otherwise the promise is rejected.
     */
    function findById(id, settings) {
        return default_1.DefaultSession.findById(id, settings);
    }
    Session.findById = findById;
    /**
     * Find a session by path.
     *
     * @param path - The path of the target session.
     *
     * @param settings: The server settings.
     *
     * @returns A promise that resolves with the session model.
     *
     * #### Notes
     * If the session was already started via `startNewSession`, the existing
     * Session object's info is used in the fulfillment value.
     *
     * Otherwise, we attempt to find to the existing
     * session using [listRunningSessions].
     * The promise is fulfilled when the session is found,
     * otherwise the promise is rejected.
     *
     * If the session was not already started and no `options` are given,
     * the promise is rejected.
     */
    function findByPath(path, settings) {
        return default_1.DefaultSession.findByPath(path, settings);
    }
    Session.findByPath = findByPath;
    /**
     * Connect to a running session.
     *
     * @param model - The model of the target session.
     *
     * @param settigns - The server settings.
     *
     * @returns The session instance.
     *
     * #### Notes
     * If the session was already started via `startNew`, the existing
     * Session object is used as the fulfillment value.
     *
     * Otherwise, we attempt to connect to the existing session.
     */
    function connectTo(model, settings) {
        return default_1.DefaultSession.connectTo(model, settings);
    }
    Session.connectTo = connectTo;
    /**
     * Shut down a session by id.
     *
     * @param id - The id of the target session.
     *
     * @param settings - The server settings.
     *
     * @returns A promise that resolves when the session is shut down.
     *
     */
    function shutdown(id, settings) {
        return default_1.DefaultSession.shutdown(id, settings);
    }
    Session.shutdown = shutdown;
    /**
     * Shut down all sessions.
     *
     * @returns A promise that resolves when all of the sessions are shut down.
     */
    function shutdownAll(settings) {
        return default_1.DefaultSession.shutdownAll(settings);
    }
    Session.shutdownAll = shutdownAll;
})(Session = exports.Session || (exports.Session = {}));


/***/ }),

/***/ "MfJx":
/*!********************************************************!*\
  !*** ./node_modules/synthetic-dom/lib/SyntheticDOM.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var EMPTY_ATTR_LIST = [];

var NODE_TYPE_ELEMENT = exports.NODE_TYPE_ELEMENT = 1;
var NODE_TYPE_TEXT = exports.NODE_TYPE_TEXT = 3;
var NODE_TYPE_FRAGMENT = exports.NODE_TYPE_FRAGMENT = 11;
var SELF_CLOSING = exports.SELF_CLOSING = {
  area: true,
  base: true,
  br: true,
  col: true,
  embed: true,
  hr: true,
  img: true,
  input: true,
  keygen: true,
  link: true,
  meta: true,
  param: true,
  source: true,
  track: true,
  wbr: true
};

var Node = exports.Node = function () {
  function Node() {
    _classCallCheck(this, Node);
  }

  _createClass(Node, [{
    key: 'toString',
    value: function toString(isXHTML) {
      return isXHTML ? '' : '';
    }
  }]);

  return Node;
}();

var TextNode = exports.TextNode = function (_Node) {
  _inherits(TextNode, _Node);

  function TextNode(value) {
    _classCallCheck(this, TextNode);

    var _this = _possibleConstructorReturn(this, (TextNode.__proto__ || Object.getPrototypeOf(TextNode)).apply(this, arguments));

    _this.nodeType = NODE_TYPE_TEXT;
    _this.nodeName = '#text';
    _this.nodeValue = value;
    return _this;
  }

  // eslint-disable-next-line no-unused-vars


  _createClass(TextNode, [{
    key: 'toString',
    value: function toString(isXHTML) {
      return escape(this.nodeValue);
    }
  }]);

  return TextNode;
}(Node);

var ElementNode = exports.ElementNode = function (_Node2) {
  _inherits(ElementNode, _Node2);

  function ElementNode(name, attributes, childNodes) {
    _classCallCheck(this, ElementNode);

    var _this2 = _possibleConstructorReturn(this, (ElementNode.__proto__ || Object.getPrototypeOf(ElementNode)).apply(this, arguments));

    if (attributes == null) {
      attributes = EMPTY_ATTR_LIST;
    }
    var isSelfClosing = SELF_CLOSING[name] === true;
    _this2.nodeType = NODE_TYPE_ELEMENT;
    _this2._name = name.toLowerCase();
    _this2.attributes = attributes;
    _this2._attrMap = new Map(attributes.map(function (attr) {
      return [attr.name, attr];
    }));
    _this2.nodeName = name.toUpperCase();
    _this2.childNodes = [];
    _this2._isSelfClosing = isSelfClosing;
    if (!isSelfClosing && childNodes) {
      childNodes.forEach(_this2.appendChild, _this2);
    }
    return _this2;
  }

  _createClass(ElementNode, [{
    key: 'appendChild',
    value: function appendChild(node) {
      if (node.nodeType === NODE_TYPE_FRAGMENT && node.childNodes) {
        var _childNodes;

        this.childNodes && (_childNodes = this.childNodes).push.apply(_childNodes, _toConsumableArray(node.childNodes));
      } else {
        this.childNodes && this.childNodes.push(node);
      }
    }
  }, {
    key: 'getAttribute',
    value: function getAttribute(name) {
      var attr = this._attrMap.get(name);
      if (attr) {
        return attr.value;
      }
    }
  }, {
    key: 'toString',
    value: function toString(isXHTML) {
      var attributes = [];
      var _iteratorNormalCompletion = true;
      var _didIteratorError = false;
      var _iteratorError = undefined;

      try {
        for (var _iterator = this.attributes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
          var _ref2 = _step.value;
          var _name = _ref2.name,
              _value = _ref2.value;

          attributes.push(_name + (_value ? '="' + escapeAttr(_value) + '"' : ''));
        }
      } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion && _iterator.return) {
            _iterator.return();
          }
        } finally {
          if (_didIteratorError) {
            throw _iteratorError;
          }
        }
      }

      var attrString = attributes.length ? ' ' + attributes.join(' ') : '';
      if (this._isSelfClosing) {
        return '<' + this._name + attrString + (isXHTML ? '/>' : '>');
      }
      var childNodes = this.childNodes ? this.childNodes.map(function (node) {
        return node.toString(isXHTML);
      }).join('') : '';
      return '<' + this._name + attrString + '>' + childNodes + '</' + this._name + '>';
    }
  }, {
    key: 'tagName',
    get: function get() {
      return this.nodeName;
    }
  }, {
    key: 'className',
    get: function get() {
      return this.getAttribute('class') || '';
    }
  }]);

  return ElementNode;
}(Node);

var FragmentNode = exports.FragmentNode = function (_Node3) {
  _inherits(FragmentNode, _Node3);

  function FragmentNode(childNodes) {
    _classCallCheck(this, FragmentNode);

    var _this3 = _possibleConstructorReturn(this, (FragmentNode.__proto__ || Object.getPrototypeOf(FragmentNode)).apply(this, arguments));

    _this3.nodeType = NODE_TYPE_FRAGMENT;
    _this3.childNodes = [];
    if (childNodes) {
      childNodes.forEach(_this3.appendChild, _this3);
    }
    return _this3;
  }

  _createClass(FragmentNode, [{
    key: 'appendChild',
    value: function appendChild(node) {
      if (node.nodeType === NODE_TYPE_FRAGMENT && node.childNodes) {
        var _childNodes2;

        this.childNodes && (_childNodes2 = this.childNodes).push.apply(_childNodes2, _toConsumableArray(node.childNodes));
      } else {
        this.childNodes && this.childNodes.push(node);
      }
    }
  }, {
    key: 'toString',
    value: function toString(isXHTML) {
      var childNodes = this.childNodes;
      return childNodes ? childNodes.map(function (node) {
        return node.toString(isXHTML);
      }).join('') : '';
    }
  }]);

  return FragmentNode;
}(Node);

function escape(html) {
  return html.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

function escapeAttr(html) {
  return html.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
}

/***/ }),

/***/ "MgzW":
/*!*********************************************!*\
  !*** ./node_modules/object-assign/index.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/


/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;

function toObject(val) {
	if (val === null || val === undefined) {
		throw new TypeError('Object.assign cannot be called with null or undefined');
	}

	return Object(val);
}

function shouldUseNative() {
	try {
		if (!Object.assign) {
			return false;
		}

		// Detect buggy property enumeration order in older V8 versions.

		// https://bugs.chromium.org/p/v8/issues/detail?id=4118
		var test1 = new String('abc');  // eslint-disable-line no-new-wrappers
		test1[5] = 'de';
		if (Object.getOwnPropertyNames(test1)[0] === '5') {
			return false;
		}

		// https://bugs.chromium.org/p/v8/issues/detail?id=3056
		var test2 = {};
		for (var i = 0; i < 10; i++) {
			test2['_' + String.fromCharCode(i)] = i;
		}
		var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
			return test2[n];
		});
		if (order2.join('') !== '0123456789') {
			return false;
		}

		// https://bugs.chromium.org/p/v8/issues/detail?id=3056
		var test3 = {};
		'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
			test3[letter] = letter;
		});
		if (Object.keys(Object.assign({}, test3)).join('') !==
				'abcdefghijklmnopqrst') {
			return false;
		}

		return true;
	} catch (err) {
		// We don't expect any of the above to throw, but better to be safe.
		return false;
	}
}

module.exports = shouldUseNative() ? Object.assign : function (target, source) {
	var from;
	var to = toObject(target);
	var symbols;

	for (var s = 1; s < arguments.length; s++) {
		from = Object(arguments[s]);

		for (var key in from) {
			if (hasOwnProperty.call(from, key)) {
				to[key] = from[key];
			}
		}

		if (getOwnPropertySymbols) {
			symbols = getOwnPropertySymbols(from);
			for (var i = 0; i < symbols.length; i++) {
				if (propIsEnumerable.call(from, symbols[i])) {
					to[symbols[i]] = from[symbols[i]];
				}
			}
		}
	}

	return to;
};


/***/ }),

/***/ "Mh8y":
/*!*****************************************************************!*\
  !*** ./node_modules/draft-js/lib/modifyBlockForContentState.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule modifyBlockForContentState
 * @format
 * 
 */



var Immutable = __webpack_require__(/*! immutable */ "JPcv");

var Map = Immutable.Map;


function modifyBlockForContentState(contentState, selectionState, operation) {
  var startKey = selectionState.getStartKey();
  var endKey = selectionState.getEndKey();
  var blockMap = contentState.getBlockMap();
  var newBlocks = blockMap.toSeq().skipUntil(function (_, k) {
    return k === startKey;
  }).takeUntil(function (_, k) {
    return k === endKey;
  }).concat(Map([[endKey, blockMap.get(endKey)]])).map(operation);

  return contentState.merge({
    blockMap: blockMap.merge(newBlocks),
    selectionBefore: selectionState,
    selectionAfter: selectionState
  });
}

module.exports = modifyBlockForContentState;

/***/ }),

/***/ "MlIt":
/*!******************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotOhlcIcon.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotOhlcIcon = function PlotOhlcIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M6.688 2.688h2.625v26.625H6.688zm2.625 12h5.375v2.625H9.313zm-8 8h5.375v2.625H1.313zm20-20h2.688v26.625h-2.688zm-5.313 4h5.313v2.625H16zm8 10.625h5.313v2.688H24z' })
    );
};

exports.default = PlotOhlcIcon;

/***/ }),

/***/ "MlNG":
/*!*****************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/MarkerSize.js ***!
  \*****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _RadioBlocks = __webpack_require__(/*! ../widgets/RadioBlocks */ "N8y9");

var _RadioBlocks2 = _interopRequireDefault(_RadioBlocks);

var _Numeric = __webpack_require__(/*! ./Numeric */ "E01D");

var _Numeric2 = _interopRequireDefault(_Numeric);

var _DataSelector = __webpack_require__(/*! ./DataSelector */ "dv5i");

var _DataSelector2 = _interopRequireDefault(_DataSelector);

var _constants = __webpack_require__(/*! ../../lib/constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UnconnectedMarkerSize = function (_Component) {
  _inherits(UnconnectedMarkerSize, _Component);

  function UnconnectedMarkerSize(props, context) {
    _classCallCheck(this, UnconnectedMarkerSize);

    var _this = _possibleConstructorReturn(this, (UnconnectedMarkerSize.__proto__ || Object.getPrototypeOf(UnconnectedMarkerSize)).call(this, props, context));

    var type = null;
    if (!props.container.marker || props.container.marker && !props.container.marker.sizesrc) {
      type = 'constant';
    } else if (props.container.marker && Array.isArray(props.container.marker.size) && props.fullContainer.marker && Array.isArray(props.fullContainer.marker.size)) {
      type = 'variable';
    }

    _this.state = {
      type: type,
      value: {
        constant: type === 'constant' ? props.fullValue : '6',
        variable: type === 'variable' ? props.fullValue : null
      }
    };

    _this.setType = _this.setType.bind(_this);
    _this.setValue = _this.setValue.bind(_this);
    return _this;
  }

  _createClass(UnconnectedMarkerSize, [{
    key: 'setType',
    value: function setType(type) {
      this.setState({ type: type });
      this.props.updatePlot(this.state.value[type]);
      if (type === 'constant') {
        this.context.updateContainer(_defineProperty({}, 'marker.sizesrc', null));
      } else {
        var _context$updateContai2;

        this.context.updateContainer((_context$updateContai2 = {}, _defineProperty(_context$updateContai2, 'marker.size', null), _defineProperty(_context$updateContai2, 'marker.sizesrc', null), _context$updateContai2));
      }
    }
  }, {
    key: 'setValue',
    value: function setValue(inputValue) {
      var type = this.state.type;


      this.setState(type === 'constant' ? { value: { constant: inputValue } } : { value: { variable: inputValue } });
      this.props.updatePlot(inputValue);
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          attr = _props.attr,
          fullValue = _props.fullValue;
      var _ = this.context.localize;
      var _state = this.state,
          type = _state.type,
          value = _state.value;

      var options = [{ label: _('Constant'), value: 'constant' }, { label: _('Variable'), value: 'variable' }];
      var multiValued = this.props.multiValued || Array.isArray(fullValue) && fullValue.includes(_constants.MULTI_VALUED);

      return _react2.default.createElement(
        _Field2.default,
        _extends({}, this.props, { multiValued: multiValued, attr: attr }),
        _react2.default.createElement(_RadioBlocks2.default, { options: options, activeOption: type, onOptionChange: this.setType }),
        type === 'constant' ? _react2.default.createElement(_Numeric2.default, {
          suppressMultiValuedMessage: true,
          attr: 'marker.size',
          updatePlot: this.setValue,
          fullValue: value.constant
        }) : multiValued ? null : _react2.default.createElement(_DataSelector2.default, { suppressMultiValuedMessage: true, attr: 'marker.size', updatePlot: this.setValue })
      );
    }
  }]);

  return UnconnectedMarkerSize;
}(_react.Component);

UnconnectedMarkerSize.propTypes = _extends({
  fullValue: _propTypes2.default.any,
  updatePlot: _propTypes2.default.func
}, _Field2.default.propTypes);

UnconnectedMarkerSize.contextTypes = {
  localize: _propTypes2.default.func,
  updateContainer: _propTypes2.default.func
};

exports.default = (0, _lib.connectToContainer)(UnconnectedMarkerSize);
//# sourceMappingURL=MarkerSize.js.map

/***/ }),

/***/ "MnKG":
/*!****************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/imageviewer/style/index.css ***!
  \****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.jp-ImageViewer {\n  overflow: auto;\n}\n\n.jp-ImageViewer > img {\n  box-sizing: border-box;\n  transform-origin: top left;\n}\n", ""]);

// exports


/***/ }),

/***/ "Mqbl":
/*!*****************************************************************!*\
  !*** ./node_modules/core-js/library/modules/es6.object.keys.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.14 Object.keys(O)
var toObject = __webpack_require__(/*! ./_to-object */ "JB68");
var $keys = __webpack_require__(/*! ./_object-keys */ "w6GO");

__webpack_require__(/*! ./_object-sap */ "zn7N")('keys', function () {
  return function keys(it) {
    return $keys(toObject(it));
  };
});


/***/ }),

/***/ "MrPd":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_assignValue.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseAssignValue = __webpack_require__(/*! ./_baseAssignValue */ "hypo"),
    eq = __webpack_require__(/*! ./eq */ "ljhN");

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * 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);
  }
}

module.exports = assignValue;


/***/ }),

/***/ "MsZC":
/*!******************************************!*\
  !*** ./node_modules/xterm/lib/Buffer.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var CircularList_1 = __webpack_require__(/*! ./utils/CircularList */ "NaQQ");
var EventEmitter_1 = __webpack_require__(/*! ./EventEmitter */ "t2YR");
exports.CHAR_DATA_ATTR_INDEX = 0;
exports.CHAR_DATA_CHAR_INDEX = 1;
exports.CHAR_DATA_WIDTH_INDEX = 2;
exports.CHAR_DATA_CODE_INDEX = 3;
exports.MAX_BUFFER_SIZE = 4294967295;
var Buffer = (function () {
    function Buffer(_terminal, _hasScrollback) {
        this._terminal = _terminal;
        this._hasScrollback = _hasScrollback;
        this.markers = [];
        this.clear();
    }
    Object.defineProperty(Buffer.prototype, "lines", {
        get: function () {
            return this._lines;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Buffer.prototype, "hasScrollback", {
        get: function () {
            return this._hasScrollback && this.lines.maxLength > this._terminal.rows;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Buffer.prototype, "isCursorInViewport", {
        get: function () {
            var absoluteY = this.ybase + this.y;
            var relativeY = absoluteY - this.ydisp;
            return (relativeY >= 0 && relativeY < this._terminal.rows);
        },
        enumerable: true,
        configurable: true
    });
    Buffer.prototype._getCorrectBufferLength = function (rows) {
        if (!this._hasScrollback) {
            return rows;
        }
        var correctBufferLength = rows + this._terminal.options.scrollback;
        return correctBufferLength > exports.MAX_BUFFER_SIZE ? exports.MAX_BUFFER_SIZE : correctBufferLength;
    };
    Buffer.prototype.fillViewportRows = function () {
        if (this._lines.length === 0) {
            var i = this._terminal.rows;
            while (i--) {
                this.lines.push(this._terminal.blankLine());
            }
        }
    };
    Buffer.prototype.clear = function () {
        this.ydisp = 0;
        this.ybase = 0;
        this.y = 0;
        this.x = 0;
        this._lines = new CircularList_1.CircularList(this._getCorrectBufferLength(this._terminal.rows));
        this.scrollTop = 0;
        this.scrollBottom = this._terminal.rows - 1;
        this.setupTabStops();
    };
    Buffer.prototype.resize = function (newCols, newRows) {
        var newMaxLength = this._getCorrectBufferLength(newRows);
        if (newMaxLength > this._lines.maxLength) {
            this._lines.maxLength = newMaxLength;
        }
        if (this._lines.length > 0) {
            if (this._terminal.cols < newCols) {
                var ch = [this._terminal.defAttr, ' ', 1, 32];
                for (var i = 0; i < this._lines.length; i++) {
                    while (this._lines.get(i).length < newCols) {
                        this._lines.get(i).push(ch);
                    }
                }
            }
            var addToY = 0;
            if (this._terminal.rows < newRows) {
                for (var y = this._terminal.rows; y < newRows; y++) {
                    if (this._lines.length < newRows + this.ybase) {
                        if (this.ybase > 0 && this._lines.length <= this.ybase + this.y + addToY + 1) {
                            this.ybase--;
                            addToY++;
                            if (this.ydisp > 0) {
                                this.ydisp--;
                            }
                        }
                        else {
                            this._lines.push(this._terminal.blankLine(undefined, undefined, newCols));
                        }
                    }
                }
            }
            else {
                for (var y = this._terminal.rows; y > newRows; y--) {
                    if (this._lines.length > newRows + this.ybase) {
                        if (this._lines.length > this.ybase + this.y + 1) {
                            this._lines.pop();
                        }
                        else {
                            this.ybase++;
                            this.ydisp++;
                        }
                    }
                }
            }
            if (newMaxLength < this._lines.maxLength) {
                var amountToTrim = this._lines.length - newMaxLength;
                if (amountToTrim > 0) {
                    this._lines.trimStart(amountToTrim);
                    this.ybase = Math.max(this.ybase - amountToTrim, 0);
                    this.ydisp = Math.max(this.ydisp - amountToTrim, 0);
                }
                this._lines.maxLength = newMaxLength;
            }
            this.x = Math.min(this.x, newCols - 1);
            this.y = Math.min(this.y, newRows - 1);
            if (addToY) {
                this.y += addToY;
            }
            this.savedY = Math.min(this.savedY, newRows - 1);
            this.savedX = Math.min(this.savedX, newCols - 1);
            this.scrollTop = 0;
        }
        this.scrollBottom = newRows - 1;
    };
    Buffer.prototype.translateBufferLineToString = function (lineIndex, trimRight, startCol, endCol) {
        if (startCol === void 0) { startCol = 0; }
        if (endCol === void 0) { endCol = null; }
        var lineString = '';
        var line = this.lines.get(lineIndex);
        if (!line) {
            return '';
        }
        var startIndex = startCol;
        if (endCol === null) {
            endCol = line.length;
        }
        var endIndex = endCol;
        for (var i = 0; i < line.length; i++) {
            var char = line[i];
            lineString += char[exports.CHAR_DATA_CHAR_INDEX];
            if (char[exports.CHAR_DATA_WIDTH_INDEX] === 0) {
                if (startCol >= i) {
                    startIndex--;
                }
                if (endCol >= i) {
                    endIndex--;
                }
            }
            else {
                if (char[exports.CHAR_DATA_CHAR_INDEX].length > 1) {
                    if (startCol > i) {
                        startIndex += char[exports.CHAR_DATA_CHAR_INDEX].length - 1;
                    }
                    if (endCol > i) {
                        endIndex += char[exports.CHAR_DATA_CHAR_INDEX].length - 1;
                    }
                }
            }
        }
        if (trimRight) {
            var rightWhitespaceIndex = lineString.search(/\s+$/);
            if (rightWhitespaceIndex !== -1) {
                endIndex = Math.min(endIndex, rightWhitespaceIndex);
            }
            if (endIndex <= startIndex) {
                return '';
            }
        }
        return lineString.substring(startIndex, endIndex);
    };
    Buffer.prototype.setupTabStops = function (i) {
        if (i != null) {
            if (!this.tabs[i]) {
                i = this.prevStop(i);
            }
        }
        else {
            this.tabs = {};
            i = 0;
        }
        for (; i < this._terminal.cols; i += this._terminal.options.tabStopWidth) {
            this.tabs[i] = true;
        }
    };
    Buffer.prototype.prevStop = function (x) {
        if (x == null) {
            x = this.x;
        }
        while (!this.tabs[--x] && x > 0)
            ;
        return x >= this._terminal.cols ? this._terminal.cols - 1 : x < 0 ? 0 : x;
    };
    Buffer.prototype.nextStop = function (x) {
        if (x == null) {
            x = this.x;
        }
        while (!this.tabs[++x] && x < this._terminal.cols)
            ;
        return x >= this._terminal.cols ? this._terminal.cols - 1 : x < 0 ? 0 : x;
    };
    Buffer.prototype.addMarker = function (y) {
        var _this = this;
        var marker = new Marker(y);
        this.markers.push(marker);
        marker.disposables.push(this._lines.addDisposableListener('trim', function (amount) {
            marker.line -= amount;
            if (marker.line < 0) {
                marker.dispose();
            }
        }));
        marker.on('dispose', function () { return _this._removeMarker(marker); });
        return marker;
    };
    Buffer.prototype._removeMarker = function (marker) {
        this.markers.splice(this.markers.indexOf(marker), 1);
    };
    return Buffer;
}());
exports.Buffer = Buffer;
var Marker = (function (_super) {
    __extends(Marker, _super);
    function Marker(line) {
        var _this = _super.call(this) || this;
        _this.line = line;
        _this._id = Marker.NEXT_ID++;
        _this.isDisposed = false;
        _this.disposables = [];
        return _this;
    }
    Object.defineProperty(Marker.prototype, "id", {
        get: function () { return this._id; },
        enumerable: true,
        configurable: true
    });
    Marker.prototype.dispose = function () {
        if (this.isDisposed) {
            return;
        }
        this.isDisposed = true;
        this.disposables.forEach(function (d) { return d.dispose(); });
        this.disposables.length = 0;
        this.emit('dispose');
    };
    Marker.NEXT_ID = 1;
    return Marker;
}(EventEmitter_1.EventEmitter));
exports.Marker = Marker;

//# sourceMappingURL=Buffer.js.map


/***/ }),

/***/ "Mta4":
/*!*************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/terminal/style/index.css ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports
exports.i(__webpack_require__(/*! -!../../../css-loader!xterm/src/xterm.css */ "B4uZ"), "");

// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.jp-Terminal {\n  min-width: 240px;\n  min-height: 120px;\n  background: black;\n}\n\n.jp-Terminal.jp-mod-light {\n  background: white;\n}\n\n.jp-Terminal-body {\n  padding: 8px;\n}\n", ""]);

// exports


/***/ }),

/***/ "MvSz":
/*!********************************************!*\
  !*** ./node_modules/lodash/_getSymbols.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var arrayFilter = __webpack_require__(/*! ./_arrayFilter */ "LXxW"),
    stubArray = __webpack_require__(/*! ./stubArray */ "0ycA");

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;

/**
 * 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);
  });
};

module.exports = getSymbols;


/***/ }),

/***/ "MvwC":
/*!*******************************************************!*\
  !*** ./node_modules/core-js/library/modules/_html.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var document = __webpack_require__(/*! ./_global */ "5T2Y").document;
module.exports = document && document.documentElement;


/***/ }),

/***/ "MwBp":
/*!***********************************************************!*\
  !*** ./node_modules/elliptic/lib/elliptic/curve/short.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var curve = __webpack_require__(/*! ../curve */ "QTa/");
var elliptic = __webpack_require__(/*! ../../elliptic */ "MzeL");
var BN = __webpack_require__(/*! bn.js */ "OZ/i");
var inherits = __webpack_require__(/*! inherits */ "P7XM");
var Base = curve.base;

var assert = elliptic.utils.assert;

function ShortCurve(conf) {
  Base.call(this, 'short', conf);

  this.a = new BN(conf.a, 16).toRed(this.red);
  this.b = new BN(conf.b, 16).toRed(this.red);
  this.tinv = this.two.redInvm();

  this.zeroA = this.a.fromRed().cmpn(0) === 0;
  this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;

  // If the curve is endomorphic, precalculate beta and lambda
  this.endo = this._getEndomorphism(conf);
  this._endoWnafT1 = new Array(4);
  this._endoWnafT2 = new Array(4);
}
inherits(ShortCurve, Base);
module.exports = ShortCurve;

ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
  // No efficient endomorphism
  if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
    return;

  // Compute beta and lambda, that lambda * P = (beta * Px; Py)
  var beta;
  var lambda;
  if (conf.beta) {
    beta = new BN(conf.beta, 16).toRed(this.red);
  } else {
    var betas = this._getEndoRoots(this.p);
    // Choose the smallest beta
    beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
    beta = beta.toRed(this.red);
  }
  if (conf.lambda) {
    lambda = new BN(conf.lambda, 16);
  } else {
    // Choose the lambda that is matching selected beta
    var lambdas = this._getEndoRoots(this.n);
    if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
      lambda = lambdas[0];
    } else {
      lambda = lambdas[1];
      assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
    }
  }

  // Get basis vectors, used for balanced length-two representation
  var basis;
  if (conf.basis) {
    basis = conf.basis.map(function(vec) {
      return {
        a: new BN(vec.a, 16),
        b: new BN(vec.b, 16)
      };
    });
  } else {
    basis = this._getEndoBasis(lambda);
  }

  return {
    beta: beta,
    lambda: lambda,
    basis: basis
  };
};

ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
  // Find roots of for x^2 + x + 1 in F
  // Root = (-1 +- Sqrt(-3)) / 2
  //
  var red = num === this.p ? this.red : BN.mont(num);
  var tinv = new BN(2).toRed(red).redInvm();
  var ntinv = tinv.redNeg();

  var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);

  var l1 = ntinv.redAdd(s).fromRed();
  var l2 = ntinv.redSub(s).fromRed();
  return [ l1, l2 ];
};

ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
  // aprxSqrt >= sqrt(this.n)
  var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));

  // 3.74
  // Run EGCD, until r(L + 1) < aprxSqrt
  var u = lambda;
  var v = this.n.clone();
  var x1 = new BN(1);
  var y1 = new BN(0);
  var x2 = new BN(0);
  var y2 = new BN(1);

  // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
  var a0;
  var b0;
  // First vector
  var a1;
  var b1;
  // Second vector
  var a2;
  var b2;

  var prevR;
  var i = 0;
  var r;
  var x;
  while (u.cmpn(0) !== 0) {
    var q = v.div(u);
    r = v.sub(q.mul(u));
    x = x2.sub(q.mul(x1));
    var y = y2.sub(q.mul(y1));

    if (!a1 && r.cmp(aprxSqrt) < 0) {
      a0 = prevR.neg();
      b0 = x1;
      a1 = r.neg();
      b1 = x;
    } else if (a1 && ++i === 2) {
      break;
    }
    prevR = r;

    v = u;
    u = r;
    x2 = x1;
    x1 = x;
    y2 = y1;
    y1 = y;
  }
  a2 = r.neg();
  b2 = x;

  var len1 = a1.sqr().add(b1.sqr());
  var len2 = a2.sqr().add(b2.sqr());
  if (len2.cmp(len1) >= 0) {
    a2 = a0;
    b2 = b0;
  }

  // Normalize signs
  if (a1.negative) {
    a1 = a1.neg();
    b1 = b1.neg();
  }
  if (a2.negative) {
    a2 = a2.neg();
    b2 = b2.neg();
  }

  return [
    { a: a1, b: b1 },
    { a: a2, b: b2 }
  ];
};

ShortCurve.prototype._endoSplit = function _endoSplit(k) {
  var basis = this.endo.basis;
  var v1 = basis[0];
  var v2 = basis[1];

  var c1 = v2.b.mul(k).divRound(this.n);
  var c2 = v1.b.neg().mul(k).divRound(this.n);

  var p1 = c1.mul(v1.a);
  var p2 = c2.mul(v2.a);
  var q1 = c1.mul(v1.b);
  var q2 = c2.mul(v2.b);

  // Calculate answer
  var k1 = k.sub(p1).sub(p2);
  var k2 = q1.add(q2).neg();
  return { k1: k1, k2: k2 };
};

ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
  x = new BN(x, 16);
  if (!x.red)
    x = x.toRed(this.red);

  var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
  var y = y2.redSqrt();
  if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
    throw new Error('invalid point');

  // XXX Is there any way to tell if the number is odd without converting it
  // to non-red form?
  var isOdd = y.fromRed().isOdd();
  if (odd && !isOdd || !odd && isOdd)
    y = y.redNeg();

  return this.point(x, y);
};

ShortCurve.prototype.validate = function validate(point) {
  if (point.inf)
    return true;

  var x = point.x;
  var y = point.y;

  var ax = this.a.redMul(x);
  var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
  return y.redSqr().redISub(rhs).cmpn(0) === 0;
};

ShortCurve.prototype._endoWnafMulAdd =
    function _endoWnafMulAdd(points, coeffs, jacobianResult) {
  var npoints = this._endoWnafT1;
  var ncoeffs = this._endoWnafT2;
  for (var i = 0; i < points.length; i++) {
    var split = this._endoSplit(coeffs[i]);
    var p = points[i];
    var beta = p._getBeta();

    if (split.k1.negative) {
      split.k1.ineg();
      p = p.neg(true);
    }
    if (split.k2.negative) {
      split.k2.ineg();
      beta = beta.neg(true);
    }

    npoints[i * 2] = p;
    npoints[i * 2 + 1] = beta;
    ncoeffs[i * 2] = split.k1;
    ncoeffs[i * 2 + 1] = split.k2;
  }
  var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);

  // Clean-up references to points and coefficients
  for (var j = 0; j < i * 2; j++) {
    npoints[j] = null;
    ncoeffs[j] = null;
  }
  return res;
};

function Point(curve, x, y, isRed) {
  Base.BasePoint.call(this, curve, 'affine');
  if (x === null && y === null) {
    this.x = null;
    this.y = null;
    this.inf = true;
  } else {
    this.x = new BN(x, 16);
    this.y = new BN(y, 16);
    // Force redgomery representation when loading from JSON
    if (isRed) {
      this.x.forceRed(this.curve.red);
      this.y.forceRed(this.curve.red);
    }
    if (!this.x.red)
      this.x = this.x.toRed(this.curve.red);
    if (!this.y.red)
      this.y = this.y.toRed(this.curve.red);
    this.inf = false;
  }
}
inherits(Point, Base.BasePoint);

ShortCurve.prototype.point = function point(x, y, isRed) {
  return new Point(this, x, y, isRed);
};

ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
  return Point.fromJSON(this, obj, red);
};

Point.prototype._getBeta = function _getBeta() {
  if (!this.curve.endo)
    return;

  var pre = this.precomputed;
  if (pre && pre.beta)
    return pre.beta;

  var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
  if (pre) {
    var curve = this.curve;
    var endoMul = function(p) {
      return curve.point(p.x.redMul(curve.endo.beta), p.y);
    };
    pre.beta = beta;
    beta.precomputed = {
      beta: null,
      naf: pre.naf && {
        wnd: pre.naf.wnd,
        points: pre.naf.points.map(endoMul)
      },
      doubles: pre.doubles && {
        step: pre.doubles.step,
        points: pre.doubles.points.map(endoMul)
      }
    };
  }
  return beta;
};

Point.prototype.toJSON = function toJSON() {
  if (!this.precomputed)
    return [ this.x, this.y ];

  return [ this.x, this.y, this.precomputed && {
    doubles: this.precomputed.doubles && {
      step: this.precomputed.doubles.step,
      points: this.precomputed.doubles.points.slice(1)
    },
    naf: this.precomputed.naf && {
      wnd: this.precomputed.naf.wnd,
      points: this.precomputed.naf.points.slice(1)
    }
  } ];
};

Point.fromJSON = function fromJSON(curve, obj, red) {
  if (typeof obj === 'string')
    obj = JSON.parse(obj);
  var res = curve.point(obj[0], obj[1], red);
  if (!obj[2])
    return res;

  function obj2point(obj) {
    return curve.point(obj[0], obj[1], red);
  }

  var pre = obj[2];
  res.precomputed = {
    beta: null,
    doubles: pre.doubles && {
      step: pre.doubles.step,
      points: [ res ].concat(pre.doubles.points.map(obj2point))
    },
    naf: pre.naf && {
      wnd: pre.naf.wnd,
      points: [ res ].concat(pre.naf.points.map(obj2point))
    }
  };
  return res;
};

Point.prototype.inspect = function inspect() {
  if (this.isInfinity())
    return '<EC Point Infinity>';
  return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
      ' y: ' + this.y.fromRed().toString(16, 2) + '>';
};

Point.prototype.isInfinity = function isInfinity() {
  return this.inf;
};

Point.prototype.add = function add(p) {
  // O + P = P
  if (this.inf)
    return p;

  // P + O = P
  if (p.inf)
    return this;

  // P + P = 2P
  if (this.eq(p))
    return this.dbl();

  // P + (-P) = O
  if (this.neg().eq(p))
    return this.curve.point(null, null);

  // P + Q = O
  if (this.x.cmp(p.x) === 0)
    return this.curve.point(null, null);

  var c = this.y.redSub(p.y);
  if (c.cmpn(0) !== 0)
    c = c.redMul(this.x.redSub(p.x).redInvm());
  var nx = c.redSqr().redISub(this.x).redISub(p.x);
  var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
  return this.curve.point(nx, ny);
};

Point.prototype.dbl = function dbl() {
  if (this.inf)
    return this;

  // 2P = O
  var ys1 = this.y.redAdd(this.y);
  if (ys1.cmpn(0) === 0)
    return this.curve.point(null, null);

  var a = this.curve.a;

  var x2 = this.x.redSqr();
  var dyinv = ys1.redInvm();
  var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);

  var nx = c.redSqr().redISub(this.x.redAdd(this.x));
  var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
  return this.curve.point(nx, ny);
};

Point.prototype.getX = function getX() {
  return this.x.fromRed();
};

Point.prototype.getY = function getY() {
  return this.y.fromRed();
};

Point.prototype.mul = function mul(k) {
  k = new BN(k, 16);

  if (this._hasDoubles(k))
    return this.curve._fixedNafMul(this, k);
  else if (this.curve.endo)
    return this.curve._endoWnafMulAdd([ this ], [ k ]);
  else
    return this.curve._wnafMul(this, k);
};

Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
  var points = [ this, p2 ];
  var coeffs = [ k1, k2 ];
  if (this.curve.endo)
    return this.curve._endoWnafMulAdd(points, coeffs);
  else
    return this.curve._wnafMulAdd(1, points, coeffs, 2);
};

Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
  var points = [ this, p2 ];
  var coeffs = [ k1, k2 ];
  if (this.curve.endo)
    return this.curve._endoWnafMulAdd(points, coeffs, true);
  else
    return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
};

Point.prototype.eq = function eq(p) {
  return this === p ||
         this.inf === p.inf &&
             (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
};

Point.prototype.neg = function neg(_precompute) {
  if (this.inf)
    return this;

  var res = this.curve.point(this.x, this.y.redNeg());
  if (_precompute && this.precomputed) {
    var pre = this.precomputed;
    var negate = function(p) {
      return p.neg();
    };
    res.precomputed = {
      naf: pre.naf && {
        wnd: pre.naf.wnd,
        points: pre.naf.points.map(negate)
      },
      doubles: pre.doubles && {
        step: pre.doubles.step,
        points: pre.doubles.points.map(negate)
      }
    };
  }
  return res;
};

Point.prototype.toJ = function toJ() {
  if (this.inf)
    return this.curve.jpoint(null, null, null);

  var res = this.curve.jpoint(this.x, this.y, this.curve.one);
  return res;
};

function JPoint(curve, x, y, z) {
  Base.BasePoint.call(this, curve, 'jacobian');
  if (x === null && y === null && z === null) {
    this.x = this.curve.one;
    this.y = this.curve.one;
    this.z = new BN(0);
  } else {
    this.x = new BN(x, 16);
    this.y = new BN(y, 16);
    this.z = new BN(z, 16);
  }
  if (!this.x.red)
    this.x = this.x.toRed(this.curve.red);
  if (!this.y.red)
    this.y = this.y.toRed(this.curve.red);
  if (!this.z.red)
    this.z = this.z.toRed(this.curve.red);

  this.zOne = this.z === this.curve.one;
}
inherits(JPoint, Base.BasePoint);

ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
  return new JPoint(this, x, y, z);
};

JPoint.prototype.toP = function toP() {
  if (this.isInfinity())
    return this.curve.point(null, null);

  var zinv = this.z.redInvm();
  var zinv2 = zinv.redSqr();
  var ax = this.x.redMul(zinv2);
  var ay = this.y.redMul(zinv2).redMul(zinv);

  return this.curve.point(ax, ay);
};

JPoint.prototype.neg = function neg() {
  return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
};

JPoint.prototype.add = function add(p) {
  // O + P = P
  if (this.isInfinity())
    return p;

  // P + O = P
  if (p.isInfinity())
    return this;

  // 12M + 4S + 7A
  var pz2 = p.z.redSqr();
  var z2 = this.z.redSqr();
  var u1 = this.x.redMul(pz2);
  var u2 = p.x.redMul(z2);
  var s1 = this.y.redMul(pz2.redMul(p.z));
  var s2 = p.y.redMul(z2.redMul(this.z));

  var h = u1.redSub(u2);
  var r = s1.redSub(s2);
  if (h.cmpn(0) === 0) {
    if (r.cmpn(0) !== 0)
      return this.curve.jpoint(null, null, null);
    else
      return this.dbl();
  }

  var h2 = h.redSqr();
  var h3 = h2.redMul(h);
  var v = u1.redMul(h2);

  var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
  var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
  var nz = this.z.redMul(p.z).redMul(h);

  return this.curve.jpoint(nx, ny, nz);
};

JPoint.prototype.mixedAdd = function mixedAdd(p) {
  // O + P = P
  if (this.isInfinity())
    return p.toJ();

  // P + O = P
  if (p.isInfinity())
    return this;

  // 8M + 3S + 7A
  var z2 = this.z.redSqr();
  var u1 = this.x;
  var u2 = p.x.redMul(z2);
  var s1 = this.y;
  var s2 = p.y.redMul(z2).redMul(this.z);

  var h = u1.redSub(u2);
  var r = s1.redSub(s2);
  if (h.cmpn(0) === 0) {
    if (r.cmpn(0) !== 0)
      return this.curve.jpoint(null, null, null);
    else
      return this.dbl();
  }

  var h2 = h.redSqr();
  var h3 = h2.redMul(h);
  var v = u1.redMul(h2);

  var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
  var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
  var nz = this.z.redMul(h);

  return this.curve.jpoint(nx, ny, nz);
};

JPoint.prototype.dblp = function dblp(pow) {
  if (pow === 0)
    return this;
  if (this.isInfinity())
    return this;
  if (!pow)
    return this.dbl();

  if (this.curve.zeroA || this.curve.threeA) {
    var r = this;
    for (var i = 0; i < pow; i++)
      r = r.dbl();
    return r;
  }

  // 1M + 2S + 1A + N * (4S + 5M + 8A)
  // N = 1 => 6M + 6S + 9A
  var a = this.curve.a;
  var tinv = this.curve.tinv;

  var jx = this.x;
  var jy = this.y;
  var jz = this.z;
  var jz4 = jz.redSqr().redSqr();

  // Reuse results
  var jyd = jy.redAdd(jy);
  for (var i = 0; i < pow; i++) {
    var jx2 = jx.redSqr();
    var jyd2 = jyd.redSqr();
    var jyd4 = jyd2.redSqr();
    var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));

    var t1 = jx.redMul(jyd2);
    var nx = c.redSqr().redISub(t1.redAdd(t1));
    var t2 = t1.redISub(nx);
    var dny = c.redMul(t2);
    dny = dny.redIAdd(dny).redISub(jyd4);
    var nz = jyd.redMul(jz);
    if (i + 1 < pow)
      jz4 = jz4.redMul(jyd4);

    jx = nx;
    jz = nz;
    jyd = dny;
  }

  return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
};

JPoint.prototype.dbl = function dbl() {
  if (this.isInfinity())
    return this;

  if (this.curve.zeroA)
    return this._zeroDbl();
  else if (this.curve.threeA)
    return this._threeDbl();
  else
    return this._dbl();
};

JPoint.prototype._zeroDbl = function _zeroDbl() {
  var nx;
  var ny;
  var nz;
  // Z = 1
  if (this.zOne) {
    // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
    //     #doubling-mdbl-2007-bl
    // 1M + 5S + 14A

    // XX = X1^2
    var xx = this.x.redSqr();
    // YY = Y1^2
    var yy = this.y.redSqr();
    // YYYY = YY^2
    var yyyy = yy.redSqr();
    // S = 2 * ((X1 + YY)^2 - XX - YYYY)
    var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
    s = s.redIAdd(s);
    // M = 3 * XX + a; a = 0
    var m = xx.redAdd(xx).redIAdd(xx);
    // T = M ^ 2 - 2*S
    var t = m.redSqr().redISub(s).redISub(s);

    // 8 * YYYY
    var yyyy8 = yyyy.redIAdd(yyyy);
    yyyy8 = yyyy8.redIAdd(yyyy8);
    yyyy8 = yyyy8.redIAdd(yyyy8);

    // X3 = T
    nx = t;
    // Y3 = M * (S - T) - 8 * YYYY
    ny = m.redMul(s.redISub(t)).redISub(yyyy8);
    // Z3 = 2*Y1
    nz = this.y.redAdd(this.y);
  } else {
    // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
    //     #doubling-dbl-2009-l
    // 2M + 5S + 13A

    // A = X1^2
    var a = this.x.redSqr();
    // B = Y1^2
    var b = this.y.redSqr();
    // C = B^2
    var c = b.redSqr();
    // D = 2 * ((X1 + B)^2 - A - C)
    var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
    d = d.redIAdd(d);
    // E = 3 * A
    var e = a.redAdd(a).redIAdd(a);
    // F = E^2
    var f = e.redSqr();

    // 8 * C
    var c8 = c.redIAdd(c);
    c8 = c8.redIAdd(c8);
    c8 = c8.redIAdd(c8);

    // X3 = F - 2 * D
    nx = f.redISub(d).redISub(d);
    // Y3 = E * (D - X3) - 8 * C
    ny = e.redMul(d.redISub(nx)).redISub(c8);
    // Z3 = 2 * Y1 * Z1
    nz = this.y.redMul(this.z);
    nz = nz.redIAdd(nz);
  }

  return this.curve.jpoint(nx, ny, nz);
};

JPoint.prototype._threeDbl = function _threeDbl() {
  var nx;
  var ny;
  var nz;
  // Z = 1
  if (this.zOne) {
    // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
    //     #doubling-mdbl-2007-bl
    // 1M + 5S + 15A

    // XX = X1^2
    var xx = this.x.redSqr();
    // YY = Y1^2
    var yy = this.y.redSqr();
    // YYYY = YY^2
    var yyyy = yy.redSqr();
    // S = 2 * ((X1 + YY)^2 - XX - YYYY)
    var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
    s = s.redIAdd(s);
    // M = 3 * XX + a
    var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
    // T = M^2 - 2 * S
    var t = m.redSqr().redISub(s).redISub(s);
    // X3 = T
    nx = t;
    // Y3 = M * (S - T) - 8 * YYYY
    var yyyy8 = yyyy.redIAdd(yyyy);
    yyyy8 = yyyy8.redIAdd(yyyy8);
    yyyy8 = yyyy8.redIAdd(yyyy8);
    ny = m.redMul(s.redISub(t)).redISub(yyyy8);
    // Z3 = 2 * Y1
    nz = this.y.redAdd(this.y);
  } else {
    // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
    // 3M + 5S

    // delta = Z1^2
    var delta = this.z.redSqr();
    // gamma = Y1^2
    var gamma = this.y.redSqr();
    // beta = X1 * gamma
    var beta = this.x.redMul(gamma);
    // alpha = 3 * (X1 - delta) * (X1 + delta)
    var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
    alpha = alpha.redAdd(alpha).redIAdd(alpha);
    // X3 = alpha^2 - 8 * beta
    var beta4 = beta.redIAdd(beta);
    beta4 = beta4.redIAdd(beta4);
    var beta8 = beta4.redAdd(beta4);
    nx = alpha.redSqr().redISub(beta8);
    // Z3 = (Y1 + Z1)^2 - gamma - delta
    nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
    // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
    var ggamma8 = gamma.redSqr();
    ggamma8 = ggamma8.redIAdd(ggamma8);
    ggamma8 = ggamma8.redIAdd(ggamma8);
    ggamma8 = ggamma8.redIAdd(ggamma8);
    ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
  }

  return this.curve.jpoint(nx, ny, nz);
};

JPoint.prototype._dbl = function _dbl() {
  var a = this.curve.a;

  // 4M + 6S + 10A
  var jx = this.x;
  var jy = this.y;
  var jz = this.z;
  var jz4 = jz.redSqr().redSqr();

  var jx2 = jx.redSqr();
  var jy2 = jy.redSqr();

  var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));

  var jxd4 = jx.redAdd(jx);
  jxd4 = jxd4.redIAdd(jxd4);
  var t1 = jxd4.redMul(jy2);
  var nx = c.redSqr().redISub(t1.redAdd(t1));
  var t2 = t1.redISub(nx);

  var jyd8 = jy2.redSqr();
  jyd8 = jyd8.redIAdd(jyd8);
  jyd8 = jyd8.redIAdd(jyd8);
  jyd8 = jyd8.redIAdd(jyd8);
  var ny = c.redMul(t2).redISub(jyd8);
  var nz = jy.redAdd(jy).redMul(jz);

  return this.curve.jpoint(nx, ny, nz);
};

JPoint.prototype.trpl = function trpl() {
  if (!this.curve.zeroA)
    return this.dbl().add(this);

  // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
  // 5M + 10S + ...

  // XX = X1^2
  var xx = this.x.redSqr();
  // YY = Y1^2
  var yy = this.y.redSqr();
  // ZZ = Z1^2
  var zz = this.z.redSqr();
  // YYYY = YY^2
  var yyyy = yy.redSqr();
  // M = 3 * XX + a * ZZ2; a = 0
  var m = xx.redAdd(xx).redIAdd(xx);
  // MM = M^2
  var mm = m.redSqr();
  // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
  var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
  e = e.redIAdd(e);
  e = e.redAdd(e).redIAdd(e);
  e = e.redISub(mm);
  // EE = E^2
  var ee = e.redSqr();
  // T = 16*YYYY
  var t = yyyy.redIAdd(yyyy);
  t = t.redIAdd(t);
  t = t.redIAdd(t);
  t = t.redIAdd(t);
  // U = (M + E)^2 - MM - EE - T
  var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
  // X3 = 4 * (X1 * EE - 4 * YY * U)
  var yyu4 = yy.redMul(u);
  yyu4 = yyu4.redIAdd(yyu4);
  yyu4 = yyu4.redIAdd(yyu4);
  var nx = this.x.redMul(ee).redISub(yyu4);
  nx = nx.redIAdd(nx);
  nx = nx.redIAdd(nx);
  // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
  var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
  ny = ny.redIAdd(ny);
  ny = ny.redIAdd(ny);
  ny = ny.redIAdd(ny);
  // Z3 = (Z1 + E)^2 - ZZ - EE
  var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);

  return this.curve.jpoint(nx, ny, nz);
};

JPoint.prototype.mul = function mul(k, kbase) {
  k = new BN(k, kbase);

  return this.curve._wnafMul(this, k);
};

JPoint.prototype.eq = function eq(p) {
  if (p.type === 'affine')
    return this.eq(p.toJ());

  if (this === p)
    return true;

  // x1 * z2^2 == x2 * z1^2
  var z2 = this.z.redSqr();
  var pz2 = p.z.redSqr();
  if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
    return false;

  // y1 * z2^3 == y2 * z1^3
  var z3 = z2.redMul(this.z);
  var pz3 = pz2.redMul(p.z);
  return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
};

JPoint.prototype.eqXToP = function eqXToP(x) {
  var zs = this.z.redSqr();
  var rx = x.toRed(this.curve.red).redMul(zs);
  if (this.x.cmp(rx) === 0)
    return true;

  var xc = x.clone();
  var t = this.curve.redN.redMul(zs);
  for (;;) {
    xc.iadd(this.curve.n);
    if (xc.cmp(this.curve.p) >= 0)
      return false;

    rx.redIAdd(t);
    if (this.x.cmp(rx) === 0)
      return true;
  }
};

JPoint.prototype.inspect = function inspect() {
  if (this.isInfinity())
    return '<EC JPoint Infinity>';
  return '<EC JPoint x: ' + this.x.toString(16, 2) +
      ' y: ' + this.y.toString(16, 2) +
      ' z: ' + this.z.toString(16, 2) + '>';
};

JPoint.prototype.isInfinity = function isInfinity() {
  // XXX This code assumes that zero is always zero in red
  return this.z.cmpn(0) === 0;
};


/***/ }),

/***/ "MxAa":
/*!*************************************************************!*\
  !*** ./node_modules/fbjs/lib/getUnboundedScrollPosition.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks
 */



/**
 * Gets the scroll position of the supplied element or window.
 *
 * The return values are unbounded, unlike `getScrollPosition`. This means they
 * may be negative or exceed the element boundaries (which is possible using
 * inertial scrolling).
 *
 * @param {DOMWindow|DOMElement} scrollable
 * @return {object} Map with `x` and `y` keys.
 */

function getUnboundedScrollPosition(scrollable) {
  if (scrollable.Window && scrollable instanceof scrollable.Window) {
    return {
      x: scrollable.pageXOffset || scrollable.document.documentElement.scrollLeft,
      y: scrollable.pageYOffset || scrollable.document.documentElement.scrollTop
    };
  }
  return {
    x: scrollable.scrollLeft,
    y: scrollable.scrollTop
  };
}

module.exports = getUnboundedScrollPosition;

/***/ }),

/***/ "MzeL":
/*!***********************************************!*\
  !*** ./node_modules/elliptic/lib/elliptic.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var elliptic = exports;

elliptic.version = __webpack_require__(/*! ../package.json */ "KAEN").version;
elliptic.utils = __webpack_require__(/*! ./elliptic/utils */ "86MQ");
elliptic.rand = __webpack_require__(/*! brorand */ "/ayr");
elliptic.curve = __webpack_require__(/*! ./elliptic/curve */ "QTa/");
elliptic.curves = __webpack_require__(/*! ./elliptic/curves */ "DLvh");

// Protocols
elliptic.ec = __webpack_require__(/*! ./elliptic/ec */ "uagp");
elliptic.eddsa = __webpack_require__(/*! ./elliptic/eddsa */ "lF1L");


/***/ }),

/***/ "N2jm":
/*!*******************************************************!*\
  !*** ./node_modules/asn1.js/lib/asn1/encoders/der.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var inherits = __webpack_require__(/*! inherits */ "P7XM");
var Buffer = __webpack_require__(/*! buffer */ "tjlA").Buffer;

var asn1 = __webpack_require__(/*! ../../asn1 */ "f3pb");
var base = asn1.base;

// Import DER constants
var der = asn1.constants.der;

function DEREncoder(entity) {
  this.enc = 'der';
  this.name = entity.name;
  this.entity = entity;

  // Construct base tree
  this.tree = new DERNode();
  this.tree._init(entity.body);
};
module.exports = DEREncoder;

DEREncoder.prototype.encode = function encode(data, reporter) {
  return this.tree._encode(data, reporter).join();
};

// Tree methods

function DERNode(parent) {
  base.Node.call(this, 'der', parent);
}
inherits(DERNode, base.Node);

DERNode.prototype._encodeComposite = function encodeComposite(tag,
                                                              primitive,
                                                              cls,
                                                              content) {
  var encodedTag = encodeTag(tag, primitive, cls, this.reporter);

  // Short form
  if (content.length < 0x80) {
    var header = new Buffer(2);
    header[0] = encodedTag;
    header[1] = content.length;
    return this._createEncoderBuffer([ header, content ]);
  }

  // Long form
  // Count octets required to store length
  var lenOctets = 1;
  for (var i = content.length; i >= 0x100; i >>= 8)
    lenOctets++;

  var header = new Buffer(1 + 1 + lenOctets);
  header[0] = encodedTag;
  header[1] = 0x80 | lenOctets;

  for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8)
    header[i] = j & 0xff;

  return this._createEncoderBuffer([ header, content ]);
};

DERNode.prototype._encodeStr = function encodeStr(str, tag) {
  if (tag === 'bitstr') {
    return this._createEncoderBuffer([ str.unused | 0, str.data ]);
  } else if (tag === 'bmpstr') {
    var buf = new Buffer(str.length * 2);
    for (var i = 0; i < str.length; i++) {
      buf.writeUInt16BE(str.charCodeAt(i), i * 2);
    }
    return this._createEncoderBuffer(buf);
  } else if (tag === 'numstr') {
    if (!this._isNumstr(str)) {
      return this.reporter.error('Encoding of string type: numstr supports ' +
                                 'only digits and space');
    }
    return this._createEncoderBuffer(str);
  } else if (tag === 'printstr') {
    if (!this._isPrintstr(str)) {
      return this.reporter.error('Encoding of string type: printstr supports ' +
                                 'only latin upper and lower case letters, ' +
                                 'digits, space, apostrophe, left and rigth ' +
                                 'parenthesis, plus sign, comma, hyphen, ' +
                                 'dot, slash, colon, equal sign, ' +
                                 'question mark');
    }
    return this._createEncoderBuffer(str);
  } else if (/str$/.test(tag)) {
    return this._createEncoderBuffer(str);
  } else if (tag === 'objDesc') {
    return this._createEncoderBuffer(str);
  } else {
    return this.reporter.error('Encoding of string type: ' + tag +
                               ' unsupported');
  }
};

DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) {
  if (typeof id === 'string') {
    if (!values)
      return this.reporter.error('string objid given, but no values map found');
    if (!values.hasOwnProperty(id))
      return this.reporter.error('objid not found in values map');
    id = values[id].split(/[\s\.]+/g);
    for (var i = 0; i < id.length; i++)
      id[i] |= 0;
  } else if (Array.isArray(id)) {
    id = id.slice();
    for (var i = 0; i < id.length; i++)
      id[i] |= 0;
  }

  if (!Array.isArray(id)) {
    return this.reporter.error('objid() should be either array or string, ' +
                               'got: ' + JSON.stringify(id));
  }

  if (!relative) {
    if (id[1] >= 40)
      return this.reporter.error('Second objid identifier OOB');
    id.splice(0, 2, id[0] * 40 + id[1]);
  }

  // Count number of octets
  var size = 0;
  for (var i = 0; i < id.length; i++) {
    var ident = id[i];
    for (size++; ident >= 0x80; ident >>= 7)
      size++;
  }

  var objid = new Buffer(size);
  var offset = objid.length - 1;
  for (var i = id.length - 1; i >= 0; i--) {
    var ident = id[i];
    objid[offset--] = ident & 0x7f;
    while ((ident >>= 7) > 0)
      objid[offset--] = 0x80 | (ident & 0x7f);
  }

  return this._createEncoderBuffer(objid);
};

function two(num) {
  if (num < 10)
    return '0' + num;
  else
    return num;
}

DERNode.prototype._encodeTime = function encodeTime(time, tag) {
  var str;
  var date = new Date(time);

  if (tag === 'gentime') {
    str = [
      two(date.getFullYear()),
      two(date.getUTCMonth() + 1),
      two(date.getUTCDate()),
      two(date.getUTCHours()),
      two(date.getUTCMinutes()),
      two(date.getUTCSeconds()),
      'Z'
    ].join('');
  } else if (tag === 'utctime') {
    str = [
      two(date.getFullYear() % 100),
      two(date.getUTCMonth() + 1),
      two(date.getUTCDate()),
      two(date.getUTCHours()),
      two(date.getUTCMinutes()),
      two(date.getUTCSeconds()),
      'Z'
    ].join('');
  } else {
    this.reporter.error('Encoding ' + tag + ' time is not supported yet');
  }

  return this._encodeStr(str, 'octstr');
};

DERNode.prototype._encodeNull = function encodeNull() {
  return this._createEncoderBuffer('');
};

DERNode.prototype._encodeInt = function encodeInt(num, values) {
  if (typeof num === 'string') {
    if (!values)
      return this.reporter.error('String int or enum given, but no values map');
    if (!values.hasOwnProperty(num)) {
      return this.reporter.error('Values map doesn\'t contain: ' +
                                 JSON.stringify(num));
    }
    num = values[num];
  }

  // Bignum, assume big endian
  if (typeof num !== 'number' && !Buffer.isBuffer(num)) {
    var numArray = num.toArray();
    if (!num.sign && numArray[0] & 0x80) {
      numArray.unshift(0);
    }
    num = new Buffer(numArray);
  }

  if (Buffer.isBuffer(num)) {
    var size = num.length;
    if (num.length === 0)
      size++;

    var out = new Buffer(size);
    num.copy(out);
    if (num.length === 0)
      out[0] = 0
    return this._createEncoderBuffer(out);
  }

  if (num < 0x80)
    return this._createEncoderBuffer(num);

  if (num < 0x100)
    return this._createEncoderBuffer([0, num]);

  var size = 1;
  for (var i = num; i >= 0x100; i >>= 8)
    size++;

  var out = new Array(size);
  for (var i = out.length - 1; i >= 0; i--) {
    out[i] = num & 0xff;
    num >>= 8;
  }
  if(out[0] & 0x80) {
    out.unshift(0);
  }

  return this._createEncoderBuffer(new Buffer(out));
};

DERNode.prototype._encodeBool = function encodeBool(value) {
  return this._createEncoderBuffer(value ? 0xff : 0);
};

DERNode.prototype._use = function use(entity, obj) {
  if (typeof entity === 'function')
    entity = entity(obj);
  return entity._getEncoder('der').tree;
};

DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) {
  var state = this._baseState;
  var i;
  if (state['default'] === null)
    return false;

  var data = dataBuffer.join();
  if (state.defaultBuffer === undefined)
    state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join();

  if (data.length !== state.defaultBuffer.length)
    return false;

  for (i=0; i < data.length; i++)
    if (data[i] !== state.defaultBuffer[i])
      return false;

  return true;
};

// Utility methods

function encodeTag(tag, primitive, cls, reporter) {
  var res;

  if (tag === 'seqof')
    tag = 'seq';
  else if (tag === 'setof')
    tag = 'set';

  if (der.tagByName.hasOwnProperty(tag))
    res = der.tagByName[tag];
  else if (typeof tag === 'number' && (tag | 0) === tag)
    res = tag;
  else
    return reporter.error('Unknown tag: ' + tag);

  if (res >= 0x1f)
    return reporter.error('Multi-octet tag encoding unsupported');

  if (!primitive)
    res |= 0x20;

  res |= (der.tagClassByName[cls || 'universal'] << 6);

  return res;
}


/***/ }),

/***/ "N4Qf":
/*!********************************************************!*\
  !*** ./node_modules/@jupyterlab/mainmenu/lib/index.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(__webpack_require__(/*! ./mainmenu */ "M4OJ"));
__export(__webpack_require__(/*! ./labmenu */ "e7FE"));
__export(__webpack_require__(/*! ./edit */ "qeiu"));
__export(__webpack_require__(/*! ./file */ "EqA/"));
__export(__webpack_require__(/*! ./help */ "PuQA"));
__export(__webpack_require__(/*! ./kernel */ "T2Ng"));
__export(__webpack_require__(/*! ./run */ "tNxU"));
__export(__webpack_require__(/*! ./settings */ "YrNz"));
__export(__webpack_require__(/*! ./view */ "gqd8"));
__export(__webpack_require__(/*! ./tabs */ "3C5O"));


/***/ }),

/***/ "N7Mi":
/*!********************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/boxpanel.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var boxlayout_1 = __webpack_require__(/*! ./boxlayout */ "mvme");
var panel_1 = __webpack_require__(/*! ./panel */ "RlJB");
/**
 * A panel which arranges its widgets in a single row or column.
 *
 * #### Notes
 * This class provides a convenience wrapper around a [[BoxLayout]].
 */
var BoxPanel = (function (_super) {
    __extends(BoxPanel, _super);
    /**
     * Construct a new box panel.
     *
     * @param options - The options for initializing the box panel.
     */
    function BoxPanel(options) {
        if (options === void 0) { options = {}; }
        var _this = _super.call(this, { layout: Private.createLayout(options) }) || this;
        _this.addClass('p-BoxPanel');
        return _this;
    }
    Object.defineProperty(BoxPanel.prototype, "direction", {
        /**
         * Get the layout direction for the box panel.
         */
        get: function () {
            return this.layout.direction;
        },
        /**
         * Set the layout direction for the box panel.
         */
        set: function (value) {
            this.layout.direction = value;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(BoxPanel.prototype, "alignment", {
        /**
         * Get the content alignment for the box panel.
         *
         * #### Notes
         * This is the alignment of the widgets in the layout direction.
         *
         * The alignment has no effect if the widgets can expand to fill the
         * entire box layout.
         */
        get: function () {
            return this.layout.alignment;
        },
        /**
         * Set the content alignment for the box panel.
         *
         * #### Notes
         * This is the alignment of the widgets in the layout direction.
         *
         * The alignment has no effect if the widgets can expand to fill the
         * entire box layout.
         */
        set: function (value) {
            this.layout.alignment = value;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(BoxPanel.prototype, "spacing", {
        /**
         * Get the inter-element spacing for the box panel.
         */
        get: function () {
            return this.layout.spacing;
        },
        /**
         * Set the inter-element spacing for the box panel.
         */
        set: function (value) {
            this.layout.spacing = value;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * A message handler invoked on a `'child-added'` message.
     */
    BoxPanel.prototype.onChildAdded = function (msg) {
        msg.child.addClass('p-BoxPanel-child');
    };
    /**
     * A message handler invoked on a `'child-removed'` message.
     */
    BoxPanel.prototype.onChildRemoved = function (msg) {
        msg.child.removeClass('p-BoxPanel-child');
    };
    return BoxPanel;
}(panel_1.Panel));
exports.BoxPanel = BoxPanel;
/**
 * The namespace for the `BoxPanel` class statics.
 */
(function (BoxPanel) {
    /**
     * Get the box panel stretch factor for the given widget.
     *
     * @param widget - The widget of interest.
     *
     * @returns The box panel stretch factor for the widget.
     */
    function getStretch(widget) {
        return boxlayout_1.BoxLayout.getStretch(widget);
    }
    BoxPanel.getStretch = getStretch;
    /**
     * Set the box panel stretch factor for the given widget.
     *
     * @param widget - The widget of interest.
     *
     * @param value - The value for the stretch factor.
     */
    function setStretch(widget, value) {
        boxlayout_1.BoxLayout.setStretch(widget, value);
    }
    BoxPanel.setStretch = setStretch;
    /**
     * Get the box panel size basis for the given widget.
     *
     * @param widget - The widget of interest.
     *
     * @returns The box panel size basis for the widget.
     */
    function getSizeBasis(widget) {
        return boxlayout_1.BoxLayout.getSizeBasis(widget);
    }
    BoxPanel.getSizeBasis = getSizeBasis;
    /**
     * Set the box panel size basis for the given widget.
     *
     * @param widget - The widget of interest.
     *
     * @param value - The value for the size basis.
     */
    function setSizeBasis(widget, value) {
        boxlayout_1.BoxLayout.setSizeBasis(widget, value);
    }
    BoxPanel.setSizeBasis = setSizeBasis;
})(BoxPanel = exports.BoxPanel || (exports.BoxPanel = {}));
exports.BoxPanel = BoxPanel;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * Create a box layout for the given panel options.
     */
    function createLayout(options) {
        return options.layout || new boxlayout_1.BoxLayout(options);
    }
    Private.createLayout = createLayout;
})(Private || (Private = {}));


/***/ }),

/***/ "N8y9":
/*!*******************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/RadioBlocks.js ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _classnames = __webpack_require__(/*! classnames */ "TSYQ");

var _classnames2 = _interopRequireDefault(_classnames);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var RadioBlocks = function (_Component) {
  _inherits(RadioBlocks, _Component);

  function RadioBlocks(props) {
    _classCallCheck(this, RadioBlocks);

    var _this = _possibleConstructorReturn(this, (RadioBlocks.__proto__ || Object.getPrototypeOf(RadioBlocks)).call(this, props));

    _this.state = { activeOption: _this.props.activeOption };
    _this.handleChange = _this.handleChange.bind(_this);
    _this.renderOption = _this.renderOption.bind(_this);
    return _this;
  }

  _createClass(RadioBlocks, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      // Reset the value to the graph's actual value
      if (nextProps.activeOption !== this.state.activeOption) {
        this.setState({
          activeOption: nextProps.activeOption
        });
      }
    }
  }, {
    key: 'handleChange',
    value: function handleChange(newValue) {
      this.setState({ activeOption: newValue });
      this.props.onOptionChange(newValue);
    }
  }, {
    key: 'renderOption',
    value: function renderOption(optionName) {
      var _this2 = this;

      var label = optionName.label,
          value = optionName.value,
          Icon = optionName.icon;

      var defaultActive = this.state.activeOption === value;

      var optionClass = (0, _classnames2.default)('radio-block__option', {
        'radio-block__option--active': defaultActive
      });

      return _react2.default.createElement(
        'div',
        {
          className: optionClass,
          key: value,
          checked: defaultActive,
          onClick: function onClick() {
            return _this2.handleChange(value);
          }
        },
        Icon ? _react2.default.createElement(Icon, { className: 'radio-block__icon' }) : null,
        label ? _react2.default.createElement(
          'span',
          null,
          label
        ) : null
      );
    }
  }, {
    key: 'render',
    value: function render() {
      var optionList = this.props.options.map(this.renderOption);

      var groupClass = (0, _classnames2.default)('radio-block', 'radio-block__group', {
        'radio-block__group--center': this.props.alignment === 'center'
      });

      return _react2.default.createElement(
        'div',
        { className: groupClass },
        optionList
      );
    }
  }]);

  return RadioBlocks;
}(_react.Component);

RadioBlocks.propTypes = {
  options: _propTypes2.default.arrayOf(_propTypes2.default.shape({
    value: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.bool, _propTypes2.default.number]).isRequired,
    label: _propTypes2.default.string,
    icon: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]),
    disabled: _propTypes2.default.bool
  })),
  onOptionChange: _propTypes2.default.func.isRequired,
  activeOption: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.bool, _propTypes2.default.number]),
  radioClassName: _propTypes2.default.string,

  // One of right, left, center
  alignment: _propTypes2.default.string
};

exports.default = RadioBlocks;
//# sourceMappingURL=RadioBlocks.js.map

/***/ }),

/***/ "NA37":
/*!*************************************************!*\
  !*** ./node_modules/mdi-react/ArrowLeftIcon.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var ArrowLeftIcon = function ArrowLeftIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M20,11V13H8L13.5,18.5L12.08,19.92L4.16,12L12.08,4.08L13.5,5.5L8,11H20Z' })
  );
};

module.exports = ArrowLeftIcon;


/***/ }),

/***/ "NCq+":
/*!********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/ArrowSelector.js ***!
  \********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _Dropdown = __webpack_require__(/*! ./Dropdown */ "dRXW");

var _Dropdown2 = _interopRequireDefault(_Dropdown);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _arrow_paths = __webpack_require__(/*! plotly.js/src/components/annotations/arrow_paths */ "qTWP");

var _arrow_paths2 = _interopRequireDefault(_arrow_paths);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var ARROW_OPTIONS = _arrow_paths2.default.map(function (_ref, index) {
  var path = _ref.path;

  var label = _react2.default.createElement(
    'svg',
    { width: '40', height: '20', style: { position: 'relative', top: '5px' } },
    _react2.default.createElement('line', {
      stroke: 'rgb(68, 68, 68)',
      style: { fill: 'none' },
      x1: '5',
      y1: '10',
      x2: '23.8',
      y2: '10',
      strokeWidth: '2'
    }),
    _react2.default.createElement('path', {
      d: path,
      transform: 'translate(23.8,10)rotate(360)scale(2)',
      style: { fill: 'rgb(68, 68, 68)', opacity: 1, strokeWidth: 0 }
    })
  );

  return {
    label: label,
    value: index,
    key: 'arrow' + index
  };
});

var ArrowSelector = function ArrowSelector(props) {
  return _react2.default.createElement(_Dropdown2.default, _extends({}, props, { options: ARROW_OPTIONS }));
};

ArrowSelector.propTypes = _extends({}, _Dropdown2.default.propTypes);

ArrowSelector.defaultProps = {
  clearable: false
};

exports.default = ArrowSelector;
//# sourceMappingURL=ArrowSelector.js.map

/***/ }),

/***/ "ND7S":
/*!*********************************************************!*\
  !*** ./node_modules/asn1.js/lib/asn1/encoders/index.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var encoders = exports;

encoders.der = __webpack_require__(/*! ./der */ "N2jm");
encoders.pem = __webpack_require__(/*! ./pem */ "hbMA");


/***/ }),

/***/ "NGrM":
/*!*****************************************************!*\
  !*** ./node_modules/codemirror/mode/julia/julia.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"));
  else {}
})(function(CodeMirror) {
"use strict";

CodeMirror.defineMode("julia", function(config, parserConf) {
  function wordRegexp(words, end) {
    if (typeof end === "undefined") { end = "\\b"; }
    return new RegExp("^((" + words.join(")|(") + "))" + end);
  }

  var octChar = "\\\\[0-7]{1,3}";
  var hexChar = "\\\\x[A-Fa-f0-9]{1,2}";
  var sChar = "\\\\[abefnrtv0%?'\"\\\\]";
  var uChar = "([^\\u0027\\u005C\\uD800-\\uDFFF]|[\\uD800-\\uDFFF][\\uDC00-\\uDFFF])";

  var operators = parserConf.operators || wordRegexp([
      "[<>]:", "[<>=]=", "<<=?", ">>>?=?", "=>", "->", "\\/\\/",
      "[\\\\%*+\\-<>!=\\/^|&\\u00F7\\u22BB]=?", "\\?", "\\$", "~", ":",
      "\\u00D7", "\\u2208", "\\u2209", "\\u220B", "\\u220C", "\\u2218",
      "\\u221A", "\\u221B", "\\u2229", "\\u222A", "\\u2260", "\\u2264",
      "\\u2265", "\\u2286", "\\u2288", "\\u228A", "\\u22C5",
      "\\b(in|isa)\\b(?!\.?\\()"], "");
  var delimiters = parserConf.delimiters || /^[;,()[\]{}]/;
  var identifiers = parserConf.identifiers ||
      /^[_A-Za-z\u00A1-\u2217\u2219-\uFFFF][\w\u00A1-\u2217\u2219-\uFFFF]*!*/;

  var chars = wordRegexp([octChar, hexChar, sChar, uChar], "'");
  var openers = wordRegexp(["begin", "function", "type", "struct", "immutable",
      "let", "macro", "for", "while", "quote", "if", "else", "elseif", "try",
      "finally", "catch", "do"]);
  var closers = wordRegexp(["end", "else", "elseif", "catch", "finally"]);
  var keywords = wordRegexp(["if", "else", "elseif", "while", "for", "begin",
      "let", "end", "do", "try", "catch", "finally", "return", "break",
      "continue", "global", "local", "const", "export", "import", "importall",
      "using", "function", "where", "macro", "module", "baremodule", "struct",
      "type", "mutable", "immutable", "quote", "typealias", "abstract",
      "primitive", "bitstype"]);
  var builtins = wordRegexp(["true", "false", "nothing", "NaN", "Inf"]);

  var macro = /^@[_A-Za-z][\w]*/;
  var symbol = /^:[_A-Za-z\u00A1-\uFFFF][\w\u00A1-\uFFFF]*!*/;
  var stringPrefixes = /^(`|([_A-Za-z\u00A1-\uFFFF]*"("")?))/;

  function inArray(state) {
    return inGenerator(state, '[')
  }

  function inGenerator(state, bracket, depth) {
    if (typeof(bracket) === "undefined") { bracket = '('; }
    if (typeof(depth)   === "undefined") { depth   = 0;   }
    var scope = currentScope(state, depth);
    if ((depth == 0 && scope === "if" && inGenerator(state, bracket, depth + 1)) ||
        (scope === "for" && inGenerator(state, bracket, depth + 1)) ||
        (scope === bracket)) {
      return true;
    }
    return false;
  }

  function currentScope(state, n) {
    if (typeof(n) === "undefined") { n = 0; }
    if (state.scopes.length <= n) {
      return null;
    }
    return state.scopes[state.scopes.length - (n + 1)];
  }

  // tokenizers
  function tokenBase(stream, state) {
    // Handle multiline comments
    if (stream.match(/^#=/, false)) {
      state.tokenize = tokenComment;
      return state.tokenize(stream, state);
    }

    // Handle scope changes
    var leavingExpr = state.leavingExpr;
    if (stream.sol()) {
      leavingExpr = false;
    }
    state.leavingExpr = false;

    if (leavingExpr) {
      if (stream.match(/^'+/)) {
        return "operator";
      }
    }

    if (stream.match(/\.{4,}/)) {
      return "error";
    } else if (stream.match(/\.{1,3}/)) {
      return "operator";
    }

    if (stream.eatSpace()) {
      return null;
    }

    var ch = stream.peek();

    // Handle single line comments
    if (ch === '#') {
      stream.skipToEnd();
      return "comment";
    }

    if (ch === '[') {
      state.scopes.push('[');
    }

    if (ch === '(') {
      state.scopes.push('(');
    }

    if (inArray(state) && ch === ']') {
      if (currentScope(state) === "if") { state.scopes.pop(); }
      while (currentScope(state) === "for") { state.scopes.pop(); }
      state.scopes.pop();
      state.leavingExpr = true;
    }

    if (inGenerator(state) && ch === ')') {
      if (currentScope(state) === "if") { state.scopes.pop(); }
      while (currentScope(state) === "for") { state.scopes.pop(); }
      state.scopes.pop();
      state.leavingExpr = true;
    }

    if (inArray(state)) {
      if (state.lastToken == "end" && stream.match(/^:/)) {
        return "operator";
      }
      if (stream.match(/^end/)) {
        return "number";
      }
    }

    var match;
    if (match = stream.match(openers)) {
      state.scopes.push(match[0]);
      return "keyword";
    }

    if (stream.match(closers)) {
      state.scopes.pop();
      return "keyword";
    }

    // Handle type annotations
    if (stream.match(/^::(?![:\$])/)) {
      state.tokenize = tokenAnnotation;
      return state.tokenize(stream, state);
    }

    // Handle symbols
    if (!leavingExpr && stream.match(symbol) ||
        stream.match(/:([<>]:|<<=?|>>>?=?|->|\/\/|\.{2,3}|[\.\\%*+\-<>!\/^|&]=?|[~\?\$])/)) {
      return "builtin";
    }

    // Handle parametric types
    //if (stream.match(/^{[^}]*}(?=\()/)) {
    //  return "builtin";
    //}

    // Handle operators and Delimiters
    if (stream.match(operators)) {
      return "operator";
    }

    // Handle Number Literals
    if (stream.match(/^\.?\d/, false)) {
      var imMatcher = RegExp(/^im\b/);
      var numberLiteral = false;
      // Floats
      if (stream.match(/^\d*\.(?!\.)\d*([Eef][\+\-]?\d+)?/i)) { numberLiteral = true; }
      if (stream.match(/^\d+\.(?!\.)\d*/)) { numberLiteral = true; }
      if (stream.match(/^\.\d+/)) { numberLiteral = true; }
      if (stream.match(/^0x\.[0-9a-f]+p[\+\-]?\d+/i)) { numberLiteral = true; }
      // Integers
      if (stream.match(/^0x[0-9a-f]+/i)) { numberLiteral = true; } // Hex
      if (stream.match(/^0b[01]+/i)) { numberLiteral = true; } // Binary
      if (stream.match(/^0o[0-7]+/i)) { numberLiteral = true; } // Octal
      if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) { numberLiteral = true; } // Decimal
      // Zero by itself with no other piece of number.
      if (stream.match(/^0(?![\dx])/i)) { numberLiteral = true; }
      if (numberLiteral) {
          // Integer literals may be "long"
          stream.match(imMatcher);
          state.leavingExpr = true;
          return "number";
      }
    }

    // Handle Chars
    if (stream.match(/^'/)) {
      state.tokenize = tokenChar;
      return state.tokenize(stream, state);
    }

    // Handle Strings
    if (stream.match(stringPrefixes)) {
      state.tokenize = tokenStringFactory(stream.current());
      return state.tokenize(stream, state);
    }

    if (stream.match(macro)) {
      return "meta";
    }

    if (stream.match(delimiters)) {
      return null;
    }

    if (stream.match(keywords)) {
      return "keyword";
    }

    if (stream.match(builtins)) {
      return "builtin";
    }

    var isDefinition = state.isDefinition || state.lastToken == "function" ||
                       state.lastToken == "macro" || state.lastToken == "type" ||
                       state.lastToken == "struct" || state.lastToken == "immutable";

    if (stream.match(identifiers)) {
      if (isDefinition) {
        if (stream.peek() === '.') {
          state.isDefinition = true;
          return "variable";
        }
        state.isDefinition = false;
        return "def";
      }
      if (stream.match(/^({[^}]*})*\(/, false)) {
        state.tokenize = tokenCallOrDef;
        return state.tokenize(stream, state);
      }
      state.leavingExpr = true;
      return "variable";
    }

    // Handle non-detected items
    stream.next();
    return "error";
  }

  function tokenCallOrDef(stream, state) {
    var match = stream.match(/^(\(\s*)/);
    if (match) {
      if (state.firstParenPos < 0)
        state.firstParenPos = state.scopes.length;
      state.scopes.push('(');
      state.charsAdvanced += match[1].length;
    }
    if (currentScope(state) == '(' && stream.match(/^\)/)) {
      state.scopes.pop();
      state.charsAdvanced += 1;
      if (state.scopes.length <= state.firstParenPos) {
        var isDefinition = stream.match(/^(\s*where\s+[^\s=]+)*\s*?=(?!=)/, false);
        stream.backUp(state.charsAdvanced);
        state.firstParenPos = -1;
        state.charsAdvanced = 0;
        state.tokenize = tokenBase;
        if (isDefinition)
          return "def";
        return "builtin";
      }
    }
    // Unfortunately javascript does not support multiline strings, so we have
    // to undo anything done upto here if a function call or definition splits
    // over two or more lines.
    if (stream.match(/^$/g, false)) {
      stream.backUp(state.charsAdvanced);
      while (state.scopes.length > state.firstParenPos)
        state.scopes.pop();
      state.firstParenPos = -1;
      state.charsAdvanced = 0;
      state.tokenize = tokenBase;
      return "builtin";
    }
    state.charsAdvanced += stream.match(/^([^()]*)/)[1].length;
    return state.tokenize(stream, state);
  }

  function tokenAnnotation(stream, state) {
    stream.match(/.*?(?=,|;|{|}|\(|\)|=|$|\s)/);
    if (stream.match(/^{/)) {
      state.nestedLevels++;
    } else if (stream.match(/^}/)) {
      state.nestedLevels--;
    }
    if (state.nestedLevels > 0) {
      stream.match(/.*?(?={|})/) || stream.next();
    } else if (state.nestedLevels == 0) {
      state.tokenize = tokenBase;
    }
    return "builtin";
  }

  function tokenComment(stream, state) {
    if (stream.match(/^#=/)) {
      state.nestedLevels++;
    }
    if (!stream.match(/.*?(?=(#=|=#))/)) {
      stream.skipToEnd();
    }
    if (stream.match(/^=#/)) {
      state.nestedLevels--;
      if (state.nestedLevels == 0)
        state.tokenize = tokenBase;
    }
    return "comment";
  }

  function tokenChar(stream, state) {
    var isChar = false, match;
    if (stream.match(chars)) {
      isChar = true;
    } else if (match = stream.match(/\\u([a-f0-9]{1,4})(?=')/i)) {
      var value = parseInt(match[1], 16);
      if (value <= 55295 || value >= 57344) { // (U+0,U+D7FF), (U+E000,U+FFFF)
        isChar = true;
        stream.next();
      }
    } else if (match = stream.match(/\\U([A-Fa-f0-9]{5,8})(?=')/)) {
      var value = parseInt(match[1], 16);
      if (value <= 1114111) { // U+10FFFF
        isChar = true;
        stream.next();
      }
    }
    if (isChar) {
      state.leavingExpr = true;
      state.tokenize = tokenBase;
      return "string";
    }
    if (!stream.match(/^[^']+(?=')/)) { stream.skipToEnd(); }
    if (stream.match(/^'/)) { state.tokenize = tokenBase; }
    return "error";
  }

  function tokenStringFactory(delimiter) {
    if (delimiter.substr(-3) === '"""') {
      delimiter = '"""';
    } else if (delimiter.substr(-1) === '"') {
      delimiter = '"';
    }
    function tokenString(stream, state) {
      if (stream.eat('\\')) {
        stream.next();
      } else if (stream.match(delimiter)) {
        state.tokenize = tokenBase;
        state.leavingExpr = true;
        return "string";
      } else {
        stream.eat(/[`"]/);
      }
      stream.eatWhile(/[^\\`"]/);
      return "string";
    }
    return tokenString;
  }

  var external = {
    startState: function() {
      return {
        tokenize: tokenBase,
        scopes: [],
        lastToken: null,
        leavingExpr: false,
        isDefinition: false,
        nestedLevels: 0,
        charsAdvanced: 0,
        firstParenPos: -1
      };
    },

    token: function(stream, state) {
      var style = state.tokenize(stream, state);
      var current = stream.current();

      if (current && style) {
        state.lastToken = current;
      }

      return style;
    },

    indent: function(state, textAfter) {
      var delta = 0;
      if ( textAfter === ']' || textAfter === ')' || textAfter === "end" ||
           textAfter === "else" || textAfter === "catch" || textAfter === "elseif" ||
           textAfter === "finally" ) {
        delta = -1;
      }
      return (state.scopes.length + delta) * config.indentUnit;
    },

    electricInput: /\b(end|else|catch|finally)\b/,
    blockCommentStart: "#=",
    blockCommentEnd: "=#",
    lineComment: "#",
    fold: "indent"
  };
  return external;
});


CodeMirror.defineMIME("text/x-julia", "julia");

});


/***/ }),

/***/ "NHPb":
/*!*****************************************************************!*\
  !*** ./node_modules/@jupyterlab/console-extension/lib/index.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const application_1 = __webpack_require__(/*! @jupyterlab/application */ "FkFl");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const codeeditor_1 = __webpack_require__(/*! @jupyterlab/codeeditor */ "sLCx");
const console_1 = __webpack_require__(/*! @jupyterlab/console */ "DrOJ");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const filebrowser_1 = __webpack_require__(/*! @jupyterlab/filebrowser */ "my6z");
const launcher_1 = __webpack_require__(/*! @jupyterlab/launcher */ "78yt");
const mainmenu_1 = __webpack_require__(/*! @jupyterlab/mainmenu */ "N4Qf");
const rendermime_1 = __webpack_require__(/*! @jupyterlab/rendermime */ "Towz");
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const coreutils_2 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
/**
 * The command IDs used by the console plugin.
 */
var CommandIDs;
(function (CommandIDs) {
    CommandIDs.create = 'console:create';
    CommandIDs.clear = 'console:clear';
    CommandIDs.runUnforced = 'console:run-unforced';
    CommandIDs.runForced = 'console:run-forced';
    CommandIDs.linebreak = 'console:linebreak';
    CommandIDs.interrupt = 'console:interrupt-kernel';
    CommandIDs.restart = 'console:restart-kernel';
    CommandIDs.closeAndShutdown = 'console:close-and-shutdown';
    CommandIDs.open = 'console:open';
    CommandIDs.inject = 'console:inject';
    CommandIDs.changeKernel = 'console:change-kernel';
    CommandIDs.toggleShowAllActivity = 'console:toggle-show-all-kernel-activity';
    CommandIDs.enterToExecute = 'console:enter-to-execute';
    CommandIDs.shiftEnterToExecute = 'console:shift-enter-to-execute';
})(CommandIDs || (CommandIDs = {}));
/**
 * The console widget tracker provider.
 */
const tracker = {
    id: '@jupyterlab/console-extension:tracker',
    provides: console_1.IConsoleTracker,
    requires: [
        mainmenu_1.IMainMenu,
        apputils_1.ICommandPalette,
        console_1.ConsolePanel.IContentFactory,
        codeeditor_1.IEditorServices,
        application_1.ILayoutRestorer,
        filebrowser_1.IFileBrowserFactory,
        rendermime_1.IRenderMimeRegistry,
        coreutils_1.ISettingRegistry
    ],
    optional: [launcher_1.ILauncher],
    activate: activateConsole,
    autoStart: true
};
/**
 * The console widget content factory.
 */
const factory = {
    id: '@jupyterlab/console-extension:factory',
    provides: console_1.ConsolePanel.IContentFactory,
    requires: [codeeditor_1.IEditorServices],
    autoStart: true,
    activate: (app, editorServices) => {
        const editorFactory = editorServices.factoryService.newInlineEditor;
        return new console_1.ConsolePanel.ContentFactory({ editorFactory });
    }
};
/**
 * Export the plugins as the default.
 */
const plugins = [factory, tracker];
exports.default = plugins;
/**
 * Activate the console extension.
 */
function activateConsole(app, mainMenu, palette, contentFactory, editorServices, restorer, browserFactory, rendermime, settingRegistry, launcher) {
    const manager = app.serviceManager;
    const { commands, shell } = app;
    const category = 'Console';
    // Create an instance tracker for all console panels.
    const tracker = new apputils_1.InstanceTracker({ namespace: 'console' });
    // Handle state restoration.
    restorer.restore(tracker, {
        command: CommandIDs.open,
        args: panel => ({
            path: panel.console.session.path,
            name: panel.console.session.name
        }),
        name: panel => panel.console.session.path,
        when: manager.ready
    });
    // Add a launcher item if the launcher is available.
    if (launcher) {
        manager.ready.then(() => {
            const specs = manager.specs;
            if (!specs) {
                return;
            }
            let baseUrl = coreutils_1.PageConfig.getBaseUrl();
            for (let name in specs.kernelspecs) {
                let rank = name === specs.default ? 0 : Infinity;
                let kernelIconUrl = specs.kernelspecs[name].resources['logo-64x64'];
                if (kernelIconUrl) {
                    let index = kernelIconUrl.indexOf('kernelspecs');
                    kernelIconUrl = baseUrl + kernelIconUrl.slice(index);
                }
                launcher.add({
                    command: CommandIDs.create,
                    args: { isLauncher: true, kernelPreference: { name } },
                    category: 'Console',
                    rank,
                    kernelIconUrl
                });
            }
        });
    }
    /**
     * Create a console for a given path.
     */
    function createConsole(options) {
        let panel;
        return manager.ready
            .then(() => {
            panel = new console_1.ConsolePanel(Object.assign({ manager,
                contentFactory, mimeTypeService: editorServices.mimeTypeService, rendermime, setBusy: app.setBusy.bind(app) }, options));
            return panel.session.ready;
        })
            .then(() => {
            // Add the console panel to the tracker.
            tracker.add(panel);
            panel.session.propertyChanged.connect(() => tracker.save(panel));
            shell.addToMainArea(panel, {
                ref: options.ref,
                mode: options.insertMode,
                activate: options.activate
            });
            return panel;
        });
    }
    /**
     * Whether there is an active console.
     */
    function isEnabled() {
        return (tracker.currentWidget !== null &&
            tracker.currentWidget === app.shell.currentWidget);
    }
    let command = CommandIDs.open;
    commands.addCommand(command, {
        execute: (args) => {
            let path = args['path'];
            let widget = tracker.find(value => {
                return value.console.session.path === path;
            });
            if (widget) {
                if (args['activate'] !== false) {
                    shell.activateById(widget.id);
                }
                return widget;
            }
            else {
                return manager.ready.then(() => {
                    let model = algorithm_1.find(manager.sessions.running(), item => {
                        return item.path === path;
                    });
                    if (model) {
                        return createConsole(args);
                    }
                    return Promise.reject(`No running kernel session for path: ${path}`);
                });
            }
        }
    });
    command = CommandIDs.create;
    commands.addCommand(command, {
        label: args => {
            if (args['isPalette']) {
                return 'New Console';
            }
            else if (args['isLauncher'] && args['kernelPreference']) {
                const kernelPreference = args['kernelPreference'];
                return manager.specs.kernelspecs[kernelPreference.name].display_name;
            }
            return 'Console';
        },
        iconClass: args => (args['isPalette'] ? '' : 'jp-CodeConsoleIcon'),
        execute: args => {
            let basePath = args['basePath'] ||
                args['cwd'] ||
                browserFactory.defaultBrowser.model.path;
            return createConsole(Object.assign({ basePath }, args));
        }
    });
    // Get the current widget and activate unless the args specify otherwise.
    function getCurrent(args) {
        let widget = tracker.currentWidget;
        let activate = args['activate'] !== false;
        if (activate && widget) {
            shell.activateById(widget.id);
        }
        return widget;
    }
    commands.addCommand(CommandIDs.clear, {
        label: 'Clear Console Cells',
        execute: args => {
            let current = getCurrent(args);
            if (!current) {
                return;
            }
            current.console.clear();
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.runUnforced, {
        label: 'Run Cell (unforced)',
        execute: args => {
            let current = getCurrent(args);
            if (!current) {
                return;
            }
            return current.console.execute();
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.runForced, {
        label: 'Run Cell (forced)',
        execute: args => {
            let current = getCurrent(args);
            if (!current) {
                return;
            }
            current.console.execute(true);
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.linebreak, {
        label: 'Insert Line Break',
        execute: args => {
            let current = getCurrent(args);
            if (!current) {
                return;
            }
            current.console.insertLinebreak();
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.interrupt, {
        label: 'Interrupt Kernel',
        execute: args => {
            let current = getCurrent(args);
            if (!current) {
                return;
            }
            let kernel = current.console.session.kernel;
            if (kernel) {
                return kernel.interrupt();
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.restart, {
        label: 'Restart Kernel…',
        execute: args => {
            let current = getCurrent(args);
            if (!current) {
                return;
            }
            return current.console.session.restart();
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.closeAndShutdown, {
        label: 'Close and Shutdown…',
        execute: args => {
            const current = getCurrent(args);
            if (!current) {
                return;
            }
            return apputils_1.showDialog({
                title: 'Shutdown the console?',
                body: `Are you sure you want to close "${current.title.label}"?`,
                buttons: [apputils_1.Dialog.cancelButton(), apputils_1.Dialog.warnButton()]
            }).then(result => {
                if (result.button.accept) {
                    current.console.session.shutdown().then(() => {
                        current.dispose();
                    });
                }
                else {
                    return false;
                }
            });
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.inject, {
        execute: args => {
            let path = args['path'];
            tracker.find(widget => {
                if (widget.console.session.path === path) {
                    if (args['activate'] !== false) {
                        shell.activateById(widget.id);
                    }
                    widget.console.inject(args['code']);
                    return true;
                }
                return false;
            });
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.changeKernel, {
        label: 'Change Kernel…',
        execute: args => {
            let current = getCurrent(args);
            if (!current) {
                return;
            }
            return current.console.session.selectKernel();
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.toggleShowAllActivity, {
        label: args => 'Show All Kernel Activity',
        execute: args => {
            let current = getCurrent(args);
            if (!current) {
                return;
            }
            current.console.showAllActivity = !current.console.showAllActivity;
        },
        isToggled: () => tracker.currentWidget
            ? tracker.currentWidget.console.showAllActivity
            : false,
        isEnabled
    });
    // Constants for setting the shortcuts for executing console cells.
    const shortcutPlugin = '@jupyterlab/shortcuts-extension:plugin';
    const selector = '.jp-CodeConsole-promptCell';
    // Keep updated keybindings for the console commands related to execution.
    let linebreak = algorithm_1.find(commands.keyBindings, kb => kb.command === CommandIDs.linebreak);
    let runUnforced = algorithm_1.find(commands.keyBindings, kb => kb.command === CommandIDs.runUnforced);
    let runForced = algorithm_1.find(commands.keyBindings, kb => kb.command === CommandIDs.runForced);
    commands.keyBindingChanged.connect((s, args) => {
        if (args.binding.command === CommandIDs.linebreak) {
            linebreak = args.type === 'added' ? args.binding : undefined;
            return;
        }
        if (args.binding.command === CommandIDs.runUnforced) {
            runUnforced = args.type === 'added' ? args.binding : undefined;
            return;
        }
        if (args.binding.command === CommandIDs.runForced) {
            runForced = args.type === 'added' ? args.binding : undefined;
            return;
        }
    });
    commands.addCommand(CommandIDs.shiftEnterToExecute, {
        label: 'Execute with Shift+Enter',
        isToggled: () => {
            // Only show as toggled if the shortcuts are strictly
            // The Shift+Enter ones.
            return (linebreak &&
                coreutils_2.JSONExt.deepEqual(linebreak.keys, ['Enter']) &&
                runUnforced === undefined &&
                runForced &&
                coreutils_2.JSONExt.deepEqual(runForced.keys, ['Shift Enter']));
        },
        execute: () => {
            const first = settingRegistry.set(shortcutPlugin, CommandIDs.linebreak, {
                command: CommandIDs.linebreak,
                keys: ['Enter'],
                selector
            });
            const second = settingRegistry.remove(shortcutPlugin, CommandIDs.runUnforced);
            const third = settingRegistry.set(shortcutPlugin, CommandIDs.runForced, {
                command: CommandIDs.runForced,
                keys: ['Shift Enter'],
                selector
            });
            return Promise.all([first, second, third]);
        }
    });
    commands.addCommand(CommandIDs.enterToExecute, {
        label: 'Execute with Enter',
        isToggled: () => {
            // Only show as toggled if the shortcuts are strictly
            // The Enter ones.
            return (linebreak &&
                coreutils_2.JSONExt.deepEqual(linebreak.keys, ['Ctrl Enter']) &&
                runUnforced &&
                coreutils_2.JSONExt.deepEqual(runUnforced.keys, ['Enter']) &&
                runForced &&
                coreutils_2.JSONExt.deepEqual(runForced.keys, ['Shift Enter']));
        },
        execute: () => {
            const first = settingRegistry.set(shortcutPlugin, CommandIDs.linebreak, {
                command: CommandIDs.linebreak,
                keys: ['Ctrl Enter'],
                selector
            });
            const second = settingRegistry.set(shortcutPlugin, CommandIDs.runUnforced, {
                command: CommandIDs.runUnforced,
                keys: ['Enter'],
                selector
            });
            const third = settingRegistry.set(shortcutPlugin, CommandIDs.runForced, {
                command: CommandIDs.runForced,
                keys: ['Shift Enter'],
                selector
            });
            return Promise.all([first, second, third]);
        }
    });
    // Add command palette items
    [
        CommandIDs.create,
        CommandIDs.linebreak,
        CommandIDs.clear,
        CommandIDs.runUnforced,
        CommandIDs.runForced,
        CommandIDs.restart,
        CommandIDs.interrupt,
        CommandIDs.changeKernel,
        CommandIDs.closeAndShutdown,
        CommandIDs.toggleShowAllActivity
    ].forEach(command => {
        palette.addItem({ command, category, args: { isPalette: true } });
    });
    // Add a console creator to the File menu
    mainMenu.fileMenu.newMenu.addGroup([{ command: CommandIDs.create }], 0);
    // Add a close and shutdown command to the file menu.
    mainMenu.fileMenu.closeAndCleaners.add({
        tracker,
        action: 'Shutdown',
        name: 'Console',
        closeAndCleanup: (current) => {
            return apputils_1.showDialog({
                title: 'Shutdown the console?',
                body: `Are you sure you want to close "${current.title.label}"?`,
                buttons: [apputils_1.Dialog.cancelButton(), apputils_1.Dialog.warnButton()]
            }).then(result => {
                if (result.button.accept) {
                    current.console.session.shutdown().then(() => {
                        current.dispose();
                    });
                }
                else {
                    return void 0;
                }
            });
        }
    });
    // Add a kernel user to the Kernel menu
    mainMenu.kernelMenu.kernelUsers.add({
        tracker,
        interruptKernel: current => {
            let kernel = current.console.session.kernel;
            if (kernel) {
                return kernel.interrupt();
            }
            return Promise.resolve(void 0);
        },
        noun: 'Console',
        restartKernel: current => current.console.session.restart(),
        restartKernelAndClear: current => {
            return current.console.session.restart().then(restarted => {
                if (restarted) {
                    current.console.clear();
                }
                return restarted;
            });
        },
        changeKernel: current => current.console.session.selectKernel(),
        shutdownKernel: current => current.console.session.shutdown()
    });
    // Add a code runner to the Run menu.
    mainMenu.runMenu.codeRunners.add({
        tracker,
        noun: 'Cell',
        pluralNoun: 'Cells',
        run: current => current.console.execute(true)
    });
    // Add a clearer to the edit menu
    mainMenu.editMenu.clearers.add({
        tracker,
        noun: 'Console Cells',
        clearCurrent: (current) => {
            return current.console.clear();
        }
    });
    // Add the execute keystroke setting submenu.
    const executeMenu = new widgets_1.Menu({ commands });
    executeMenu.title.label = 'Console Run Keystroke';
    executeMenu.addItem({ command: CommandIDs.enterToExecute });
    executeMenu.addItem({ command: CommandIDs.shiftEnterToExecute });
    mainMenu.settingsMenu.addGroup([
        {
            type: 'submenu',
            submenu: executeMenu
        }
    ], 10);
    // Add kernel information to the application help menu.
    mainMenu.helpMenu.kernelUsers.add({
        tracker,
        getKernel: current => current.session.kernel
    });
    app.contextMenu.addItem({
        command: CommandIDs.clear,
        selector: '.jp-CodeConsole-content'
    });
    app.contextMenu.addItem({
        command: CommandIDs.restart,
        selector: '.jp-CodeConsole'
    });
    app.contextMenu.addItem({
        command: CommandIDs.toggleShowAllActivity,
        selector: '.jp-CodeConsole'
    });
    return tracker;
}


/***/ }),

/***/ "NHcn":
/*!************************************************************!*\
  !*** ./node_modules/draft-js-utils/lib/getEntityRanges.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.EMPTY_SET = undefined;
exports.default = getEntityRanges;

var _immutable = __webpack_require__(/*! immutable */ "JPcv");

var EMPTY_SET = exports.EMPTY_SET = new _immutable.OrderedSet();
function getEntityRanges(text, charMetaList) {
  var charEntity = null;
  var prevCharEntity = null;
  var ranges = [];
  var rangeStart = 0;
  for (var i = 0, len = text.length; i < len; i++) {
    prevCharEntity = charEntity;
    var meta = charMetaList.get(i);
    charEntity = meta ? meta.getEntity() : null;
    if (i > 0 && charEntity !== prevCharEntity) {
      ranges.push([prevCharEntity, getStyleRanges(text.slice(rangeStart, i), charMetaList.slice(rangeStart, i))]);
      rangeStart = i;
    }
  }
  ranges.push([charEntity, getStyleRanges(text.slice(rangeStart), charMetaList.slice(rangeStart))]);
  return ranges;
}

function getStyleRanges(text, charMetaList) {
  var charStyle = EMPTY_SET;
  var prevCharStyle = EMPTY_SET;
  var ranges = [];
  var rangeStart = 0;
  for (var i = 0, len = text.length; i < len; i++) {
    prevCharStyle = charStyle;
    var meta = charMetaList.get(i);
    charStyle = meta ? meta.getStyle() : EMPTY_SET;
    if (i > 0 && !(0, _immutable.is)(charStyle, prevCharStyle)) {
      ranges.push([text.slice(rangeStart, i), prevCharStyle]);
      rangeStart = i;
    }
  }
  ranges.push([text.slice(rangeStart), charStyle]);
  return ranges;
}

/***/ }),

/***/ "NKxu":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_baseIsNative.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isFunction = __webpack_require__(/*! ./isFunction */ "lSCD"),
    isMasked = __webpack_require__(/*! ./_isMasked */ "E2jh"),
    isObject = __webpack_require__(/*! ./isObject */ "GoyQ"),
    toSource = __webpack_require__(/*! ./_toSource */ "3Fdi");

/**
 * Used to match `RegExp`
 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
 */
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;

/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;

/** 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 detect if a method is native. */
var reIsNative = RegExp('^' +
  funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
  .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);

/**
 * 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));
}

module.exports = baseIsNative;


/***/ }),

/***/ "NL6Z":
/*!*******************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/terminal/manager.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const __1 = __webpack_require__(/*! .. */ "S9up");
const terminal_1 = __webpack_require__(/*! ./terminal */ "lV/m");
/**
 * A terminal session manager.
 */
class TerminalManager {
    /**
     * Construct a new terminal manager.
     */
    constructor(options = {}) {
        this._models = [];
        this._sessions = new Set();
        this._isDisposed = false;
        this._isReady = false;
        this._refreshTimer = -1;
        this._runningChanged = new signaling_1.Signal(this);
        this.serverSettings =
            options.serverSettings || __1.ServerConnection.makeSettings();
        // Set up state handling if terminals are available.
        if (terminal_1.TerminalSession.isAvailable()) {
            // Initialize internal data.
            this._readyPromise = this._refreshRunning();
            // Set up polling.
            this._refreshTimer = setInterval(() => {
                if (typeof document !== 'undefined' && document.hidden) {
                    // Don't poll when nobody's looking.
                    return;
                }
                this._refreshRunning();
            }, 10000);
        }
    }
    /**
     * A signal emitted when the running terminals change.
     */
    get runningChanged() {
        return this._runningChanged;
    }
    /**
     * Test whether the terminal manager is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Test whether the manager is ready.
     */
    get isReady() {
        return this._isReady;
    }
    /**
     * Dispose of the resources used by the manager.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        clearInterval(this._refreshTimer);
        signaling_1.Signal.clearData(this);
        this._models = [];
    }
    /**
     * A promise that fulfills when the manager is ready.
     */
    get ready() {
        return this._readyPromise || Promise.reject('Terminals unavailable');
    }
    /**
     * Whether the terminal service is available.
     */
    isAvailable() {
        return terminal_1.TerminalSession.isAvailable();
    }
    /**
     * Create an iterator over the most recent running terminals.
     *
     * @returns A new iterator over the running terminals.
     */
    running() {
        return algorithm_1.iter(this._models);
    }
    /**
     * Create a new terminal session.
     *
     * @param options - The options used to connect to the session.
     *
     * @returns A promise that resolves with the terminal instance.
     *
     * #### Notes
     * The manager `serverSettings` will be used unless overridden in the
     * options.
     */
    startNew(options) {
        return terminal_1.TerminalSession.startNew(this._getOptions(options)).then(session => {
            this._onStarted(session);
            return session;
        });
    }
    /*
     * Connect to a running session.
     *
     * @param name - The name of the target session.
     *
     * @param options - The options used to connect to the session.
     *
     * @returns A promise that resolves with the new session instance.
     *
     * #### Notes
     * The manager `serverSettings` will be used unless overridden in the
     * options.
     */
    connectTo(name, options) {
        return terminal_1.TerminalSession.connectTo(name, this._getOptions(options)).then(session => {
            this._onStarted(session);
            return session;
        });
    }
    /**
     * Shut down a terminal session by name.
     */
    shutdown(name) {
        let index = algorithm_1.ArrayExt.findFirstIndex(this._models, value => value.name === name);
        if (index === -1) {
            return;
        }
        // Proactively remove the model.
        this._models.splice(index, 1);
        this._runningChanged.emit(this._models.slice());
        return terminal_1.TerminalSession.shutdown(name, this.serverSettings).then(() => {
            let toRemove = [];
            this._sessions.forEach(s => {
                if (s.name === name) {
                    s.dispose();
                    toRemove.push(s);
                }
            });
            toRemove.forEach(s => {
                this._sessions.delete(s);
            });
        });
    }
    /**
     * Shut down all terminal sessions.
     *
     * @returns A promise that resolves when all of the sessions are shut down.
     */
    shutdownAll() {
        // Proactively remove all models.
        let models = this._models;
        if (models.length > 0) {
            this._models = [];
            this._runningChanged.emit([]);
        }
        return this._refreshRunning().then(() => {
            return Promise.all(models.map(model => {
                return terminal_1.TerminalSession.shutdown(model.name, this.serverSettings).then(() => {
                    let toRemove = [];
                    this._sessions.forEach(s => {
                        s.dispose();
                        toRemove.push(s);
                    });
                    toRemove.forEach(s => {
                        this._sessions.delete(s);
                    });
                });
            })).then(() => {
                return undefined;
            });
        });
    }
    /**
     * Force a refresh of the running sessions.
     *
     * @returns A promise that with the list of running sessions.
     *
     * #### Notes
     * This is not typically meant to be called by the user, since the
     * manager maintains its own internal state.
     */
    refreshRunning() {
        return this._refreshRunning();
    }
    /**
     * Handle a session terminating.
     */
    _onTerminated(name) {
        let index = algorithm_1.ArrayExt.findFirstIndex(this._models, value => value.name === name);
        if (index !== -1) {
            this._models.splice(index, 1);
            this._runningChanged.emit(this._models.slice());
        }
    }
    /**
     * Handle a session starting.
     */
    _onStarted(session) {
        let name = session.name;
        this._sessions.add(session);
        let index = algorithm_1.ArrayExt.findFirstIndex(this._models, value => value.name === name);
        if (index === -1) {
            this._models.push(session.model);
            this._runningChanged.emit(this._models.slice());
        }
        session.terminated.connect(() => {
            this._onTerminated(name);
        });
    }
    /**
     * Refresh the running sessions.
     */
    _refreshRunning() {
        return terminal_1.TerminalSession.listRunning(this.serverSettings).then(models => {
            this._isReady = true;
            if (!coreutils_1.JSONExt.deepEqual(models, this._models)) {
                let names = models.map(r => r.name);
                let toRemove = [];
                this._sessions.forEach(s => {
                    if (names.indexOf(s.name) === -1) {
                        s.dispose();
                        toRemove.push(s);
                    }
                });
                toRemove.forEach(s => {
                    this._sessions.delete(s);
                });
                this._models = models.slice();
                this._runningChanged.emit(models);
            }
        });
    }
    /**
     * Get a set of options to pass.
     */
    _getOptions(options = {}) {
        return Object.assign({}, options, { serverSettings: this.serverSettings });
    }
}
exports.TerminalManager = TerminalManager;


/***/ }),

/***/ "NLw+":
/*!***************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/index.js ***!
  \***************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




var d3 = __webpack_require__(/*! d3 */ "bljh");
var isNumeric = __webpack_require__(/*! fast-isnumeric */ "GbLo");

var numConstants = __webpack_require__(/*! ../constants/numerical */ "qrPk");
var FP_SAFE = numConstants.FP_SAFE;
var BADNUM = numConstants.BADNUM;

var lib = module.exports = {};

lib.nestedProperty = __webpack_require__(/*! ./nested_property */ "oz8K");
lib.keyedContainer = __webpack_require__(/*! ./keyed_container */ "D1qR");
lib.relativeAttr = __webpack_require__(/*! ./relative_attr */ "SNK5");
lib.isPlainObject = __webpack_require__(/*! ./is_plain_object */ "SWc2");
lib.toLogRange = __webpack_require__(/*! ./to_log_range */ "ks0Q");
lib.relinkPrivateKeys = __webpack_require__(/*! ./relink_private */ "+drS");

var arrayModule = __webpack_require__(/*! ./array */ "lCvc");
lib.isTypedArray = arrayModule.isTypedArray;
lib.isArrayOrTypedArray = arrayModule.isArrayOrTypedArray;
lib.isArray1D = arrayModule.isArray1D;
lib.ensureArray = arrayModule.ensureArray;
lib.concat = arrayModule.concat;
lib.maxRowLength = arrayModule.maxRowLength;
lib.minRowLength = arrayModule.minRowLength;

var modModule = __webpack_require__(/*! ./mod */ "74Od");
lib.mod = modModule.mod;
lib.modHalf = modModule.modHalf;

var coerceModule = __webpack_require__(/*! ./coerce */ "7pOt");
lib.valObjectMeta = coerceModule.valObjectMeta;
lib.coerce = coerceModule.coerce;
lib.coerce2 = coerceModule.coerce2;
lib.coerceFont = coerceModule.coerceFont;
lib.coerceHoverinfo = coerceModule.coerceHoverinfo;
lib.coerceSelectionMarkerOpacity = coerceModule.coerceSelectionMarkerOpacity;
lib.validate = coerceModule.validate;

var datesModule = __webpack_require__(/*! ./dates */ "7qpb");
lib.dateTime2ms = datesModule.dateTime2ms;
lib.isDateTime = datesModule.isDateTime;
lib.ms2DateTime = datesModule.ms2DateTime;
lib.ms2DateTimeLocal = datesModule.ms2DateTimeLocal;
lib.cleanDate = datesModule.cleanDate;
lib.isJSDate = datesModule.isJSDate;
lib.formatDate = datesModule.formatDate;
lib.incrementMonth = datesModule.incrementMonth;
lib.dateTick0 = datesModule.dateTick0;
lib.dfltRange = datesModule.dfltRange;
lib.findExactDates = datesModule.findExactDates;
lib.MIN_MS = datesModule.MIN_MS;
lib.MAX_MS = datesModule.MAX_MS;

var searchModule = __webpack_require__(/*! ./search */ "z6eE");
lib.findBin = searchModule.findBin;
lib.sorterAsc = searchModule.sorterAsc;
lib.sorterDes = searchModule.sorterDes;
lib.distinctVals = searchModule.distinctVals;
lib.roundUp = searchModule.roundUp;
lib.sort = searchModule.sort;
lib.findIndexOfMin = searchModule.findIndexOfMin;

var statsModule = __webpack_require__(/*! ./stats */ "4zK0");
lib.aggNums = statsModule.aggNums;
lib.len = statsModule.len;
lib.mean = statsModule.mean;
lib.midRange = statsModule.midRange;
lib.variance = statsModule.variance;
lib.stdev = statsModule.stdev;
lib.interp = statsModule.interp;

var matrixModule = __webpack_require__(/*! ./matrix */ "k/Ue");
lib.init2dArray = matrixModule.init2dArray;
lib.transposeRagged = matrixModule.transposeRagged;
lib.dot = matrixModule.dot;
lib.translationMatrix = matrixModule.translationMatrix;
lib.rotationMatrix = matrixModule.rotationMatrix;
lib.rotationXYMatrix = matrixModule.rotationXYMatrix;
lib.apply2DTransform = matrixModule.apply2DTransform;
lib.apply2DTransform2 = matrixModule.apply2DTransform2;

var anglesModule = __webpack_require__(/*! ./angles */ "1L4U");
lib.deg2rad = anglesModule.deg2rad;
lib.rad2deg = anglesModule.rad2deg;
lib.angleDelta = anglesModule.angleDelta;
lib.angleDist = anglesModule.angleDist;
lib.isFullCircle = anglesModule.isFullCircle;
lib.isAngleInsideSector = anglesModule.isAngleInsideSector;
lib.isPtInsideSector = anglesModule.isPtInsideSector;
lib.pathArc = anglesModule.pathArc;
lib.pathSector = anglesModule.pathSector;
lib.pathAnnulus = anglesModule.pathAnnulus;

var anchorUtils = __webpack_require__(/*! ./anchor_utils */ "hraO");
lib.isLeftAnchor = anchorUtils.isLeftAnchor;
lib.isCenterAnchor = anchorUtils.isCenterAnchor;
lib.isRightAnchor = anchorUtils.isRightAnchor;
lib.isTopAnchor = anchorUtils.isTopAnchor;
lib.isMiddleAnchor = anchorUtils.isMiddleAnchor;
lib.isBottomAnchor = anchorUtils.isBottomAnchor;

var geom2dModule = __webpack_require__(/*! ./geometry2d */ "lNXy");
lib.segmentsIntersect = geom2dModule.segmentsIntersect;
lib.segmentDistance = geom2dModule.segmentDistance;
lib.getTextLocation = geom2dModule.getTextLocation;
lib.clearLocationCache = geom2dModule.clearLocationCache;
lib.getVisibleSegment = geom2dModule.getVisibleSegment;
lib.findPointOnPath = geom2dModule.findPointOnPath;

var extendModule = __webpack_require__(/*! ./extend */ "dnr1");
lib.extendFlat = extendModule.extendFlat;
lib.extendDeep = extendModule.extendDeep;
lib.extendDeepAll = extendModule.extendDeepAll;
lib.extendDeepNoArrays = extendModule.extendDeepNoArrays;

var loggersModule = __webpack_require__(/*! ./loggers */ "B+Rx");
lib.log = loggersModule.log;
lib.warn = loggersModule.warn;
lib.error = loggersModule.error;

var regexModule = __webpack_require__(/*! ./regex */ "Kuxr");
lib.counterRegex = regexModule.counter;

var throttleModule = __webpack_require__(/*! ./throttle */ "w+wy");
lib.throttle = throttleModule.throttle;
lib.throttleDone = throttleModule.done;
lib.clearThrottle = throttleModule.clear;

lib.getGraphDiv = __webpack_require__(/*! ./get_graph_div */ "EHQm");

lib.clearResponsive = __webpack_require__(/*! ./clear_responsive */ "LjMy");

lib.makeTraceGroups = __webpack_require__(/*! ./make_trace_groups */ "lyJQ");

lib._ = __webpack_require__(/*! ./localize */ "Eb04");

lib.notifier = __webpack_require__(/*! ./notifier */ "qeu3");

lib.filterUnique = __webpack_require__(/*! ./filter_unique */ "psdB");
lib.filterVisible = __webpack_require__(/*! ./filter_visible */ "lTKM");
lib.pushUnique = __webpack_require__(/*! ./push_unique */ "/nst");

lib.cleanNumber = __webpack_require__(/*! ./clean_number */ "QFxM");

lib.ensureNumber = function num(v) {
    if(!isNumeric(v)) return BADNUM;
    v = Number(v);
    if(v < -FP_SAFE || v > FP_SAFE) return BADNUM;
    return isNumeric(v) ? Number(v) : BADNUM;
};

/**
 * Is v a valid array index? Accepts numeric strings as well as numbers.
 *
 * @param {any} v: the value to test
 * @param {Optional[integer]} len: the array length we are indexing
 *
 * @return {bool}: v is a valid array index
 */
lib.isIndex = function(v, len) {
    if(len !== undefined && v >= len) return false;
    return isNumeric(v) && (v >= 0) && (v % 1 === 0);
};

lib.noop = __webpack_require__(/*! ./noop */ "lKy8");
lib.identity = __webpack_require__(/*! ./identity */ "Qhhf");

/**
 * create an array of length 'cnt' filled with 'v' at all indices
 *
 * @param {any} v
 * @param {number} cnt
 * @return {array}
 */
lib.repeat = function(v, cnt) {
    var out = new Array(cnt);
    for(var i = 0; i < cnt; i++) {
        out[i] = v;
    }
    return out;
};

/**
 * swap x and y of the same attribute in container cont
 * specify attr with a ? in place of x/y
 * you can also swap other things than x/y by providing part1 and part2
 */
lib.swapAttrs = function(cont, attrList, part1, part2) {
    if(!part1) part1 = 'x';
    if(!part2) part2 = 'y';
    for(var i = 0; i < attrList.length; i++) {
        var attr = attrList[i];
        var xp = lib.nestedProperty(cont, attr.replace('?', part1));
        var yp = lib.nestedProperty(cont, attr.replace('?', part2));
        var temp = xp.get();
        xp.set(yp.get());
        yp.set(temp);
    }
};

/**
 * SVG painter's algo worked around with reinsertion
 */
lib.raiseToTop = function raiseToTop(elem) {
    elem.parentNode.appendChild(elem);
};

/**
 * cancel a possibly pending transition; returned selection may be used by caller
 */
lib.cancelTransition = function(selection) {
    return selection.transition().duration(0);
};

// constrain - restrict a number v to be between v0 and v1
lib.constrain = function(v, v0, v1) {
    if(v0 > v1) return Math.max(v1, Math.min(v0, v));
    return Math.max(v0, Math.min(v1, v));
};

/**
 * do two bounding boxes from getBoundingClientRect,
 * ie {left,right,top,bottom,width,height}, overlap?
 * takes optional padding pixels
 */
lib.bBoxIntersect = function(a, b, pad) {
    pad = pad || 0;
    return (a.left <= b.right + pad &&
            b.left <= a.right + pad &&
            a.top <= b.bottom + pad &&
            b.top <= a.bottom + pad);
};

/*
 * simpleMap: alternative to Array.map that only
 * passes on the element and up to 2 extra args you
 * provide (but not the array index or the whole array)
 *
 * array: the array to map it to
 * func: the function to apply
 * x1, x2: optional extra args
 */
lib.simpleMap = function(array, func, x1, x2) {
    var len = array.length;
    var out = new Array(len);
    for(var i = 0; i < len; i++) out[i] = func(array[i], x1, x2);
    return out;
};

/**
 * Random string generator
 *
 * @param {object} existing
 *     pass in strings to avoid as keys with truthy values
 * @param {int} bits
 *     bits of information in the output string, default 24
 * @param {int} base
 *     base of string representation, default 16. Should be a power of 2.
 */
lib.randstr = function randstr(existing, bits, base, _recursion) {
    if(!base) base = 16;
    if(bits === undefined) bits = 24;
    if(bits <= 0) return '0';

    var digits = Math.log(Math.pow(2, bits)) / Math.log(base);
    var res = '';
    var i, b, x;

    for(i = 2; digits === Infinity; i *= 2) {
        digits = Math.log(Math.pow(2, bits / i)) / Math.log(base) * i;
    }

    var rem = digits - Math.floor(digits);

    for(i = 0; i < Math.floor(digits); i++) {
        x = Math.floor(Math.random() * base).toString(base);
        res = x + res;
    }

    if(rem) {
        b = Math.pow(base, rem);
        x = Math.floor(Math.random() * b).toString(base);
        res = x + res;
    }

    var parsed = parseInt(res, base);
    if((existing && existing[res]) ||
         (parsed !== Infinity && parsed >= Math.pow(2, bits))) {
        if(_recursion > 10) {
            lib.warn('randstr failed uniqueness');
            return res;
        }
        return randstr(existing, bits, base, (_recursion || 0) + 1);
    }
    else return res;
};

lib.OptionControl = function(opt, optname) {
    /*
     * An environment to contain all option setters and
     * getters that collectively modify opts.
     *
     * You can call up opts from any function in new object
     * as this.optname || this.opt
     *
     * See FitOpts for example of usage
     */
    if(!opt) opt = {};
    if(!optname) optname = 'opt';

    var self = {};
    self.optionList = [];

    self._newoption = function(optObj) {
        optObj[optname] = opt;
        self[optObj.name] = optObj;
        self.optionList.push(optObj);
    };

    self['_' + optname] = opt;
    return self;
};

/**
 * lib.smooth: smooth arrayIn by convolving with
 * a hann window with given full width at half max
 * bounce the ends in, so the output has the same length as the input
 */
lib.smooth = function(arrayIn, FWHM) {
    FWHM = Math.round(FWHM) || 0; // only makes sense for integers
    if(FWHM < 2) return arrayIn;

    var alen = arrayIn.length;
    var alen2 = 2 * alen;
    var wlen = 2 * FWHM - 1;
    var w = new Array(wlen);
    var arrayOut = new Array(alen);
    var i;
    var j;
    var k;
    var v;

    // first make the window array
    for(i = 0; i < wlen; i++) {
        w[i] = (1 - Math.cos(Math.PI * (i + 1) / FWHM)) / (2 * FWHM);
    }

    // now do the convolution
    for(i = 0; i < alen; i++) {
        v = 0;
        for(j = 0; j < wlen; j++) {
            k = i + j + 1 - FWHM;

            // multibounce
            if(k < -alen) k -= alen2 * Math.round(k / alen2);
            else if(k >= alen2) k -= alen2 * Math.floor(k / alen2);

            // single bounce
            if(k < 0) k = - 1 - k;
            else if(k >= alen) k = alen2 - 1 - k;

            v += arrayIn[k] * w[j];
        }
        arrayOut[i] = v;
    }

    return arrayOut;
};

/**
 * syncOrAsync: run a sequence of functions synchronously
 * as long as its returns are not promises (ie have no .then)
 * includes one argument arg to send to all functions...
 * this is mainly just to prevent us having to make wrapper functions
 * when the only purpose of the wrapper is to reference gd
 * and a final step to be executed at the end
 * TODO: if there's an error and everything is sync,
 * this doesn't happen yet because we want to make sure
 * that it gets reported
 */
lib.syncOrAsync = function(sequence, arg, finalStep) {
    var ret, fni;

    function continueAsync() {
        return lib.syncOrAsync(sequence, arg, finalStep);
    }

    while(sequence.length) {
        fni = sequence.splice(0, 1)[0];
        ret = fni(arg);

        if(ret && ret.then) {
            return ret.then(continueAsync)
                .then(undefined, lib.promiseError);
        }
    }

    return finalStep && finalStep(arg);
};


/**
 * Helper to strip trailing slash, from
 * http://stackoverflow.com/questions/6680825/return-string-without-trailing-slash
 */
lib.stripTrailingSlash = function(str) {
    if(str.substr(-1) === '/') return str.substr(0, str.length - 1);
    return str;
};

lib.noneOrAll = function(containerIn, containerOut, attrList) {
    /**
     * some attributes come together, so if you have one of them
     * in the input, you should copy the default values of the others
     * to the input as well.
     */
    if(!containerIn) return;

    var hasAny = false;
    var hasAll = true;
    var i;
    var val;

    for(i = 0; i < attrList.length; i++) {
        val = containerIn[attrList[i]];
        if(val !== undefined && val !== null) hasAny = true;
        else hasAll = false;
    }

    if(hasAny && !hasAll) {
        for(i = 0; i < attrList.length; i++) {
            containerIn[attrList[i]] = containerOut[attrList[i]];
        }
    }
};

/** merges calcdata field (given by cdAttr) with traceAttr values
 *
 * N.B. Loop over minimum of cd.length and traceAttr.length
 * i.e. it does not try to fill in beyond traceAttr.length-1
 *
 * @param {array} traceAttr : trace attribute
 * @param {object} cd : calcdata trace
 * @param {string} cdAttr : calcdata key
 */
lib.mergeArray = function(traceAttr, cd, cdAttr) {
    if(lib.isArrayOrTypedArray(traceAttr)) {
        var imax = Math.min(traceAttr.length, cd.length);
        for(var i = 0; i < imax; i++) cd[i][cdAttr] = traceAttr[i];
    }
};

/** fills calcdata field (given by cdAttr) with traceAttr values
 *  or function of traceAttr values (e.g. some fallback)
 *
 * N.B. Loops over all cd items.
 *
 * @param {array} traceAttr : trace attribute
 * @param {object} cd : calcdata trace
 * @param {string} cdAttr : calcdata key
 * @param {function} [fn] : optional function to apply to each array item
 */
lib.fillArray = function(traceAttr, cd, cdAttr, fn) {
    fn = fn || lib.identity;

    if(lib.isArrayOrTypedArray(traceAttr)) {
        for(var i = 0; i < cd.length; i++) {
            cd[i][cdAttr] = fn(traceAttr[i]);
        }
    }
};

/** Handler for trace-wide vs per-point options
 *
 * @param {object} trace : (full) trace object
 * @param {number} ptNumber : index of the point in question
 * @param {string} astr : attribute string
 * @param {function} [fn] : optional function to apply to each array item
 *
 * @return {any}
 */
lib.castOption = function(trace, ptNumber, astr, fn) {
    fn = fn || lib.identity;

    var val = lib.nestedProperty(trace, astr).get();

    if(lib.isArrayOrTypedArray(val)) {
        if(Array.isArray(ptNumber) && lib.isArrayOrTypedArray(val[ptNumber[0]])) {
            return fn(val[ptNumber[0]][ptNumber[1]]);
        } else {
            return fn(val[ptNumber]);
        }
    } else {
        return val;
    }
};

/** Extract option from calcdata item, correctly falling back to
 *  trace value if not found.
 *
 *  @param {object} calcPt : calcdata[i][j] item
 *  @param {object} trace : (full) trace object
 *  @param {string} calcKey : calcdata key
 *  @param {string} traceKey : aka trace attribute string
 *  @return {any}
 */
lib.extractOption = function(calcPt, trace, calcKey, traceKey) {
    if(calcKey in calcPt) return calcPt[calcKey];

    // fallback to trace value,
    //   must check if value isn't itself an array
    //   which means the trace attribute has a corresponding
    //   calcdata key, but its value is falsy
    var traceVal = lib.nestedProperty(trace, traceKey).get();
    if(!Array.isArray(traceVal)) return traceVal;
};

function makePtIndex2PtNumber(indexToPoints) {
    var ptIndex2ptNumber = {};
    for(var k in indexToPoints) {
        var pts = indexToPoints[k];
        for(var j = 0; j < pts.length; j++) {
            ptIndex2ptNumber[pts[j]] = +k;
        }
    }
    return ptIndex2ptNumber;
}

/** Tag selected calcdata items
 *
 * N.B. note that point 'index' corresponds to input data array index
 *  whereas 'number' is its post-transform version.
 *
 * @param {array} calcTrace
 * @param {object} trace
 *  - selectedpoints {array}
 *  - _indexToPoints {object}
 * @param {ptNumber2cdIndex} ptNumber2cdIndex (optional)
 *  optional map object for trace types that do not have 1-to-1 point number to
 *  calcdata item index correspondence (e.g. histogram)
 */
lib.tagSelected = function(calcTrace, trace, ptNumber2cdIndex) {
    var selectedpoints = trace.selectedpoints;
    var indexToPoints = trace._indexToPoints;
    var ptIndex2ptNumber;

    // make pt index-to-number map object, which takes care of transformed traces
    if(indexToPoints) {
        ptIndex2ptNumber = makePtIndex2PtNumber(indexToPoints);
    }

    function isCdIndexValid(v) {
        return v !== undefined && v < calcTrace.length;
    }

    for(var i = 0; i < selectedpoints.length; i++) {
        var ptIndex = selectedpoints[i];

        if(lib.isIndex(ptIndex)) {
            var ptNumber = ptIndex2ptNumber ? ptIndex2ptNumber[ptIndex] : ptIndex;
            var cdIndex = ptNumber2cdIndex ? ptNumber2cdIndex[ptNumber] : ptNumber;

            if(isCdIndexValid(cdIndex)) {
                calcTrace[cdIndex].selected = 1;
            }
        }
    }
};

lib.selIndices2selPoints = function(trace) {
    var selectedpoints = trace.selectedpoints;
    var indexToPoints = trace._indexToPoints;

    if(indexToPoints) {
        var ptIndex2ptNumber = makePtIndex2PtNumber(indexToPoints);
        var out = [];

        for(var i = 0; i < selectedpoints.length; i++) {
            var ptIndex = selectedpoints[i];
            if(lib.isIndex(ptIndex)) {
                var ptNumber = ptIndex2ptNumber[ptIndex];
                if(lib.isIndex(ptNumber)) {
                    out.push(ptNumber);
                }
            }
        }

        return out;
    } else {
        return selectedpoints;
    }
};

/** Returns target as set by 'target' transform attribute
 *
 * @param {object} trace : full trace object
 * @param {object} transformOpts : transform option object
 *  - target (string} :
 *      either an attribute string referencing an array in the trace object, or
 *      a set array.
 *
 * @return {array or false} : the target array (NOT a copy!!) or false if invalid
 */
lib.getTargetArray = function(trace, transformOpts) {
    var target = transformOpts.target;

    if(typeof target === 'string' && target) {
        var array = lib.nestedProperty(trace, target).get();
        return Array.isArray(array) ? array : false;
    } else if(Array.isArray(target)) {
        return target;
    }

    return false;
};

/**
 * modified version of jQuery's extend to strip out private objs and functions,
 * and cut arrays down to first <arraylen> or 1 elements
 * because extend-like algorithms are hella slow
 * obj2 is assumed to already be clean of these things (including no arrays)
 */
lib.minExtend = function(obj1, obj2) {
    var objOut = {};
    if(typeof obj2 !== 'object') obj2 = {};
    var arrayLen = 3;
    var keys = Object.keys(obj1);
    var i, k, v;

    for(i = 0; i < keys.length; i++) {
        k = keys[i];
        v = obj1[k];
        if(k.charAt(0) === '_' || typeof v === 'function') continue;
        else if(k === 'module') objOut[k] = v;
        else if(Array.isArray(v)) {
            if(k === 'colorscale') {
                objOut[k] = v.slice();
            } else {
                objOut[k] = v.slice(0, arrayLen);
            }
        }
        else if(v && (typeof v === 'object')) objOut[k] = lib.minExtend(obj1[k], obj2[k]);
        else objOut[k] = v;
    }

    keys = Object.keys(obj2);
    for(i = 0; i < keys.length; i++) {
        k = keys[i];
        v = obj2[k];
        if(typeof v !== 'object' || !(k in objOut) || typeof objOut[k] !== 'object') {
            objOut[k] = v;
        }
    }

    return objOut;
};

lib.titleCase = function(s) {
    return s.charAt(0).toUpperCase() + s.substr(1);
};

lib.containsAny = function(s, fragments) {
    for(var i = 0; i < fragments.length; i++) {
        if(s.indexOf(fragments[i]) !== -1) return true;
    }
    return false;
};

lib.isPlotDiv = function(el) {
    var el3 = d3.select(el);
    return el3.node() instanceof HTMLElement &&
        el3.size() &&
        el3.classed('js-plotly-plot');
};

lib.removeElement = function(el) {
    var elParent = el && el.parentNode;
    if(elParent) elParent.removeChild(el);
};

/**
 * for dynamically adding style rules
 * makes one stylesheet that contains all rules added
 * by all calls to this function
 */
lib.addStyleRule = function(selector, styleString) {
    lib.addRelatedStyleRule('global', selector, styleString);
};

/**
 * for dynamically adding style rules
 * to a stylesheet uniquely identified by a uid
 */
lib.addRelatedStyleRule = function(uid, selector, styleString) {
    var id = 'plotly.js-style-' + uid;
    var style = document.getElementById(id);
    if(!style) {
        style = document.createElement('style');
        style.setAttribute('id', id);
        // WebKit hack :(
        style.appendChild(document.createTextNode(''));
        document.head.appendChild(style);
    }
    var styleSheet = style.sheet;

    if(styleSheet.insertRule) {
        styleSheet.insertRule(selector + '{' + styleString + '}', 0);
    }
    else if(styleSheet.addRule) {
        styleSheet.addRule(selector, styleString, 0);
    }
    else lib.warn('addStyleRule failed');
};

/**
 * to remove from the page a stylesheet identified by a given uid
 */
lib.deleteRelatedStyleRule = function(uid) {
    var id = 'plotly.js-style-' + uid;
    var style = document.getElementById(id);
    if(style) lib.removeElement(style);
};

lib.isIE = function() {
    return typeof window.navigator.msSaveBlob !== 'undefined';
};

/**
 * Duck typing to recognize a d3 selection, mostly for IE9's benefit
 * because it doesn't handle instanceof like modern browsers
 */
lib.isD3Selection = function(obj) {
    return obj && (typeof obj.classed === 'function');
};

/**
 * Append element to DOM only if not present.
 *
 * @param {d3 selection} parent : parent selection of the element in question
 * @param {string} nodeType : node type of element to append
 * @param {string} className (optional) : class name of element in question
 * @param {fn} enterFn (optional) : optional fn applied to entering elements only
 * @return {d3 selection} selection of new layer
 *
 * Previously, we were using the following pattern:
 *
 * ```
 * var sel = parent.selectAll('.' + className)
 *     .data([0]);
 *
 * sel.enter().append(nodeType)
 *     .classed(className, true);
 *
 * return sel;
 * ```
 *
 * in numerous places in our codebase to achieve the same behavior.
 *
 * The logic below performs much better, mostly as we are using
 * `.select` instead `.selectAll` that is `querySelector` instead of
 * `querySelectorAll`.
 *
 */
lib.ensureSingle = function(parent, nodeType, className, enterFn) {
    var sel = parent.select(nodeType + (className ? '.' + className : ''));
    if(sel.size()) return sel;

    var layer = parent.append(nodeType);
    if(className) layer.classed(className, true);
    if(enterFn) layer.call(enterFn);

    return layer;
};

/**
 * Same as Lib.ensureSingle, but using id as selector.
 * This version is mostly used for clipPath nodes.
 *
 * @param {d3 selection} parent : parent selection of the element in question
 * @param {string} nodeType : node type of element to append
 * @param {string} id : id of element in question
 * @param {fn} enterFn (optional) : optional fn applied to entering elements only
 * @return {d3 selection} selection of new layer
 */
lib.ensureSingleById = function(parent, nodeType, id, enterFn) {
    var sel = parent.select(nodeType + '#' + id);
    if(sel.size()) return sel;

    var layer = parent.append(nodeType).attr('id', id);
    if(enterFn) layer.call(enterFn);

    return layer;
};

/**
 * Converts a string path to an object.
 *
 * When given a string containing an array element, it will create a `null`
 * filled array of the given size.
 *
 * @example
 * lib.objectFromPath('nested.test[2].path', 'value');
 * // returns { nested: { test: [null, null, { path: 'value' }]}
 *
 * @param   {string}    path to nested value
 * @param   {*}         any value to be set
 *
 * @return {Object} the constructed object with a full nested path
 */
lib.objectFromPath = function(path, value) {
    var keys = path.split('.');
    var tmpObj;
    var obj = tmpObj = {};

    for(var i = 0; i < keys.length; i++) {
        var key = keys[i];
        var el = null;

        var parts = keys[i].match(/(.*)\[([0-9]+)\]/);

        if(parts) {
            key = parts[1];
            el = parts[2];

            tmpObj = tmpObj[key] = [];

            if(i === keys.length - 1) {
                tmpObj[el] = value;
            } else {
                tmpObj[el] = {};
            }

            tmpObj = tmpObj[el];
        } else {

            if(i === keys.length - 1) {
                tmpObj[key] = value;
            } else {
                tmpObj[key] = {};
            }

            tmpObj = tmpObj[key];
        }
    }

    return obj;
};

/**
 * Iterate through an object in-place, converting dotted properties to objects.
 *
 * Examples:
 *
 *   lib.expandObjectPaths({'nested.test.path': 'value'});
 *     => { nested: { test: {path: 'value'}}}
 *
 * It also handles array notation, e.g.:
 *
 *   lib.expandObjectPaths({'foo[1].bar': 'value'});
 *     => { foo: [null, {bar: value}] }
 *
 * It handles merges the results when two properties are specified in parallel:
 *
 *   lib.expandObjectPaths({'foo[1].bar': 10, 'foo[0].bar': 20});
 *     => { foo: [{bar: 10}, {bar: 20}] }
 *
 * It does NOT, however, merge mulitple mutliply-nested arrays::
 *
 *   lib.expandObjectPaths({'marker[1].range[1]': 5, 'marker[1].range[0]': 4})
 *     => { marker: [null, {range: 4}] }
 */

// Store this to avoid recompiling regex on *every* prop since this may happen many
// many times for animations. Could maybe be inside the function. Not sure about
// scoping vs. recompilation tradeoff, but at least it's not just inlining it into
// the inner loop.
var dottedPropertyRegex = /^([^\[\.]+)\.(.+)?/;
var indexedPropertyRegex = /^([^\.]+)\[([0-9]+)\](\.)?(.+)?/;

lib.expandObjectPaths = function(data) {
    var match, key, prop, datum, idx, dest, trailingPath;
    if(typeof data === 'object' && !Array.isArray(data)) {
        for(key in data) {
            if(data.hasOwnProperty(key)) {
                if((match = key.match(dottedPropertyRegex))) {
                    datum = data[key];
                    prop = match[1];

                    delete data[key];

                    data[prop] = lib.extendDeepNoArrays(data[prop] || {}, lib.objectFromPath(key, lib.expandObjectPaths(datum))[prop]);
                } else if((match = key.match(indexedPropertyRegex))) {
                    datum = data[key];

                    prop = match[1];
                    idx = parseInt(match[2]);

                    delete data[key];

                    data[prop] = data[prop] || [];

                    if(match[3] === '.') {
                        // This is the case where theere are subsequent properties into which
                        // we must recurse, e.g. transforms[0].value
                        trailingPath = match[4];
                        dest = data[prop][idx] = data[prop][idx] || {};

                        // NB: Extend deep no arrays prevents this from working on multiple
                        // nested properties in the same object, e.g.
                        //
                        // {
                        //   foo[0].bar[1].range
                        //   foo[0].bar[0].range
                        // }
                        //
                        // In this case, the extendDeepNoArrays will overwrite one array with
                        // the other, so that both properties *will not* be present in the
                        // result. Fixing this would require a more intelligent tracking
                        // of changes and merging than extendDeepNoArrays currently accomplishes.
                        lib.extendDeepNoArrays(dest, lib.objectFromPath(trailingPath, lib.expandObjectPaths(datum)));
                    } else {
                        // This is the case where this property is the end of the line,
                        // e.g. xaxis.range[0]
                        data[prop][idx] = lib.expandObjectPaths(datum);
                    }
                } else {
                    data[key] = lib.expandObjectPaths(data[key]);
                }
            }
        }
    }

    return data;
};

/**
 * Converts value to string separated by the provided separators.
 *
 * @example
 * lib.numSeparate(2016, '.,');
 * // returns '2016'
 *
 * @example
 * lib.numSeparate(3000, '.,', true);
 * // returns '3,000'
 *
 * @example
 * lib.numSeparate(1234.56, '|,')
 * // returns '1,234|56'
 *
 * @param   {string|number} value       the value to be converted
 * @param   {string}    separators  string of decimal, then thousands separators
 * @param   {boolean}    separatethousands  boolean, 4-digit integers are separated if true
 *
 * @return  {string}    the value that has been separated
 */
lib.numSeparate = function(value, separators, separatethousands) {
    if(!separatethousands) separatethousands = false;

    if(typeof separators !== 'string' || separators.length === 0) {
        throw new Error('Separator string required for formatting!');
    }

    if(typeof value === 'number') {
        value = String(value);
    }

    var thousandsRe = /(\d+)(\d{3})/;
    var decimalSep = separators.charAt(0);
    var thouSep = separators.charAt(1);

    var x = value.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? decimalSep + x[1] : '';

    // Years are ignored for thousands separators
    if(thouSep && (x.length > 1 || x1.length > 4 || separatethousands)) {
        while(thousandsRe.test(x1)) {
            x1 = x1.replace(thousandsRe, '$1' + thouSep + '$2');
        }
    }

    return x1 + x2;
};

lib.TEMPLATE_STRING_REGEX = /%{([^\s%{}:]*)(:[^}]*)?}/g;
var SIMPLE_PROPERTY_REGEX = /^\w*$/;

/**
 * Substitute values from an object into a string
 *
 * Examples:
 *  Lib.templateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
 *  Lib.templateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
 *
 * @param {string}  input string containing %{...} template strings
 * @param {obj}     data object containing substitution values
 *
 * @return {string} templated string
 */
lib.templateString = function(string, obj) {
    // Not all that useful, but cache nestedProperty instantiation
    // just in case it speeds things up *slightly*:
    var getterCache = {};

    return string.replace(lib.TEMPLATE_STRING_REGEX, function(dummy, key) {
        if(SIMPLE_PROPERTY_REGEX.test(key)) {
            return obj[key] || '';
        }
        getterCache[key] = getterCache[key] || lib.nestedProperty(obj, key).get;
        return getterCache[key]() || '';
    });
};

var TEMPLATE_STRING_FORMAT_SEPARATOR = /^:/;
var numberOfHoverTemplateWarnings = 0;
var maximumNumberOfHoverTemplateWarnings = 10;
/**
 * Substitute values from an object into a string and optionally formats them using d3-format,
 * or fallback to associated labels.
 *
 * Examples:
 *  Lib.hovertemplateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
 *  Lib.hovertemplateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
 *  Lib.hovertemplateString('price: %{y:$.2f}', {y: 1}) --> 'price: $1.00'
 *
 * @param {obj}     d3 locale
 * @param {string}  input string containing %{...:...} template strings
 * @param {obj}     data object containing fallback text when no formatting is specified, ex.: {yLabel: 'formattedYValue'}
 * @param {obj}     data objects containing substitution values
 *
 * @return {string} templated string
 */
lib.hovertemplateString = function(string, labels, d3locale) {
    var args = arguments;
    // Not all that useful, but cache nestedProperty instantiation
    // just in case it speeds things up *slightly*:
    var getterCache = {};

    return string.replace(lib.TEMPLATE_STRING_REGEX, function(match, key, format) {
        var obj, value, i;
        for(i = 3; i < args.length; i++) {
            obj = args[i];
            if(obj.hasOwnProperty(key)) {
                value = obj[key];
                break;
            }

            if(!SIMPLE_PROPERTY_REGEX.test(key)) {
                value = getterCache[key] || lib.nestedProperty(obj, key).get();
                if(value) getterCache[key] = value;
            }
            if(value !== undefined) break;
        }

        if(value === undefined) {
            if(numberOfHoverTemplateWarnings < maximumNumberOfHoverTemplateWarnings) {
                lib.warn('Variable \'' + key + '\' in hovertemplate could not be found!');
                value = match;
            }

            if(numberOfHoverTemplateWarnings === maximumNumberOfHoverTemplateWarnings) {
                lib.warn('Too many hovertemplate warnings - additional warnings will be suppressed');
            }
            numberOfHoverTemplateWarnings++;
        }

        if(format) {
            var fmt;
            if(d3locale) {
                fmt = d3locale.numberFormat;
            } else {
                fmt = d3.format;
            }
            value = fmt(format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ''))(value);
        } else {
            if(labels.hasOwnProperty(key + 'Label')) value = labels[key + 'Label'];
        }
        return value;
    });
};

/*
 * alphanumeric string sort, tailored for subplot IDs like scene2, scene10, x10y13 etc
 */
var char0 = 48;
var char9 = 57;
lib.subplotSort = function(a, b) {
    var l = Math.min(a.length, b.length) + 1;
    var numA = 0;
    var numB = 0;
    for(var i = 0; i < l; i++) {
        var charA = a.charCodeAt(i) || 0;
        var charB = b.charCodeAt(i) || 0;
        var isNumA = charA >= char0 && charA <= char9;
        var isNumB = charB >= char0 && charB <= char9;

        if(isNumA) numA = 10 * numA + charA - char0;
        if(isNumB) numB = 10 * numB + charB - char0;

        if(!isNumA || !isNumB) {
            if(numA !== numB) return numA - numB;
            if(charA !== charB) return charA - charB;
        }
    }
    return numB - numA;
};

// repeatable pseudorandom generator
var randSeed = 2000000000;

lib.seedPseudoRandom = function() {
    randSeed = 2000000000;
};

lib.pseudoRandom = function() {
    var lastVal = randSeed;
    randSeed = (69069 * randSeed + 1) % 4294967296;
    // don't let consecutive vals be too close together
    // gets away from really trying to be random, in favor of better local uniformity
    if(Math.abs(randSeed - lastVal) < 429496729) return lib.pseudoRandom();
    return randSeed / 4294967296;
};


/***/ }),

/***/ "NQV1":
/*!*************************************************!*\
  !*** ./node_modules/fbjs/lib/PhotosMimeType.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */
var PhotosMimeType = {
  isImage: function isImage(mimeString) {
    return getParts(mimeString)[0] === 'image';
  },
  isJpeg: function isJpeg(mimeString) {
    var parts = getParts(mimeString);
    return PhotosMimeType.isImage(mimeString) && (
    // see http://fburl.com/10972194
    parts[1] === 'jpeg' || parts[1] === 'pjpeg');
  }
};

function getParts(mimeString) {
  return mimeString.split('/');
}

module.exports = PhotosMimeType;

/***/ }),

/***/ "NQVK":
/*!**************************************************!*\
  !*** ./node_modules/browserify-aes/modes/cfb.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer
var xor = __webpack_require__(/*! buffer-xor */ "jIre")

function encryptStart (self, data, decrypt) {
  var len = data.length
  var out = xor(data, self._cache)
  self._cache = self._cache.slice(len)
  self._prev = Buffer.concat([self._prev, decrypt ? data : out])
  return out
}

exports.encrypt = function (self, data, decrypt) {
  var out = Buffer.allocUnsafe(0)
  var len

  while (data.length) {
    if (self._cache.length === 0) {
      self._cache = self._cipher.encryptBlock(self._prev)
      self._prev = Buffer.allocUnsafe(0)
    }

    if (self._cache.length <= data.length) {
      len = self._cache.length
      out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)])
      data = data.slice(len)
    } else {
      out = Buffer.concat([out, encryptStart(self, data, decrypt)])
      break
    }
  }

  return out
}


/***/ }),

/***/ "NSvM":
/*!*************************************************************************!*\
  !*** ./node_modules/react-color/lib/components/chrome/ChromePointer.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ChromePointer = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var ChromePointer = exports.ChromePointer = function ChromePointer() {
  var styles = (0, _reactcss2.default)({
    'default': {
      picker: {
        width: '12px',
        height: '12px',
        borderRadius: '6px',
        transform: 'translate(-6px, -1px)',
        backgroundColor: 'rgb(248, 248, 248)',
        boxShadow: '0 1px 4px 0 rgba(0, 0, 0, 0.37)'
      }
    }
  });

  return _react2.default.createElement('div', { style: styles.picker });
};

exports.default = ChromePointer;

/***/ }),

/***/ "NV0k":
/*!*************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_object-pie.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

exports.f = {}.propertyIsEnumerable;


/***/ }),

/***/ "NW3o":
/*!****************************************************************!*\
  !*** ./node_modules/@jupyterlab/extensionmanager/lib/query.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * An object for searching an NPM registry.
 *
 * Searches the NPM registry via web API:
 * https://github.com/npm/registry/blob/master/docs/REGISTRY-API.md
 */
class Searcher {
    /**
     * Create a Searcher object.
     *
     * @param repoUri The URI of the NPM registry to use.
     * @param cdnUri The URI of the CDN to use for fetching full package data.
     */
    constructor(repoUri = 'https://registry.npmjs.org/', cdnUri = 'https://unpkg.com') {
        this.repoUri = repoUri;
        this.cdnUri = cdnUri;
    }
    /**
     * Search for a jupyterlab extension.
     *
     * @param query The query to send. `keywords:"jupyterlab-extension"` will be appended to the query.
     * @param page The page of results to fetch.
     * @param pageination The pagination size to use. See registry API documentation for acceptable values.
     */
    searchExtensions(query, page = 0, pageination = 250) {
        const uri = new URL('/-/v1/search', this.repoUri);
        // Note: Spaces are encoded to '+' signs!
        let text = `${query} keywords:"jupyterlab-extension"`;
        uri.searchParams.append('text', text);
        uri.searchParams.append('size', pageination.toString());
        uri.searchParams.append('from', (pageination * page).toString());
        return fetch(uri.toString()).then((response) => {
            if (response.ok) {
                return response.json();
            }
            return [];
        });
    }
    /**
     * Fetch package.json of a package
     *
     * @param name The package name.
     * @param version The version of the package to fetch.
     */
    fetchPackageData(name, version) {
        const uri = new URL(`/${name}@${version}/package.json`, this.cdnUri);
        return fetch(uri.toString()).then((response) => {
            if (response.ok) {
                return response.json();
            }
            return null;
        });
    }
}
exports.Searcher = Searcher;
/**
 * Check whether the NPM org is a Jupyter one.
 */
function isJupyterOrg(name) {
    /**
     * A list of whitelisted NPM orgs.
     */
    const whitelist = ['jupyterlab', 'jupyter-widgets'];
    const parts = name.split('/');
    const first = parts[0];
    return (parts.length > 1 && // Has a first part
        first && // with a finite length
        first[0] === '@' && // corresponding to an org name
        whitelist.indexOf(first.slice(1)) !== -1 // in the org whitelist.
    );
}
exports.isJupyterOrg = isJupyterOrg;


/***/ }),

/***/ "NZGY":
/*!*************************************************************************!*\
  !*** ./node_modules/font-awesome/fonts/fontawesome-webfont.svg?v=4.7.0 ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__.p + "912ec66d7572ff821749319396470bde.svg";

/***/ }),

/***/ "NaQQ":
/*!******************************************************!*\
  !*** ./node_modules/xterm/lib/utils/CircularList.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var EventEmitter_1 = __webpack_require__(/*! ../EventEmitter */ "t2YR");
var CircularList = (function (_super) {
    __extends(CircularList, _super);
    function CircularList(_maxLength) {
        var _this = _super.call(this) || this;
        _this._maxLength = _maxLength;
        _this._array = new Array(_this._maxLength);
        _this._startIndex = 0;
        _this._length = 0;
        return _this;
    }
    Object.defineProperty(CircularList.prototype, "maxLength", {
        get: function () {
            return this._maxLength;
        },
        set: function (newMaxLength) {
            if (this._maxLength === newMaxLength) {
                return;
            }
            var newArray = new Array(newMaxLength);
            for (var i = 0; i < Math.min(newMaxLength, this.length); i++) {
                newArray[i] = this._array[this._getCyclicIndex(i)];
            }
            this._array = newArray;
            this._maxLength = newMaxLength;
            this._startIndex = 0;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(CircularList.prototype, "length", {
        get: function () {
            return this._length;
        },
        set: function (newLength) {
            if (newLength > this._length) {
                for (var i = this._length; i < newLength; i++) {
                    this._array[i] = undefined;
                }
            }
            this._length = newLength;
        },
        enumerable: true,
        configurable: true
    });
    CircularList.prototype.get = function (index) {
        return this._array[this._getCyclicIndex(index)];
    };
    CircularList.prototype.set = function (index, value) {
        this._array[this._getCyclicIndex(index)] = value;
    };
    CircularList.prototype.push = function (value) {
        this._array[this._getCyclicIndex(this._length)] = value;
        if (this._length === this._maxLength) {
            this._startIndex++;
            if (this._startIndex === this._maxLength) {
                this._startIndex = 0;
            }
            this.emit('trim', 1);
        }
        else {
            this._length++;
        }
    };
    CircularList.prototype.pop = function () {
        return this._array[this._getCyclicIndex(this._length-- - 1)];
    };
    CircularList.prototype.splice = function (start, deleteCount) {
        var items = [];
        for (var _i = 2; _i < arguments.length; _i++) {
            items[_i - 2] = arguments[_i];
        }
        if (deleteCount) {
            for (var i = start; i < this._length - deleteCount; i++) {
                this._array[this._getCyclicIndex(i)] = this._array[this._getCyclicIndex(i + deleteCount)];
            }
            this._length -= deleteCount;
        }
        if (items && items.length) {
            for (var i = this._length - 1; i >= start; i--) {
                this._array[this._getCyclicIndex(i + items.length)] = this._array[this._getCyclicIndex(i)];
            }
            for (var i = 0; i < items.length; i++) {
                this._array[this._getCyclicIndex(start + i)] = items[i];
            }
            if (this._length + items.length > this.maxLength) {
                var countToTrim = (this._length + items.length) - this.maxLength;
                this._startIndex += countToTrim;
                this._length = this.maxLength;
                this.emit('trim', countToTrim);
            }
            else {
                this._length += items.length;
            }
        }
    };
    CircularList.prototype.trimStart = function (count) {
        if (count > this._length) {
            count = this._length;
        }
        this._startIndex += count;
        this._length -= count;
        this.emit('trim', count);
    };
    CircularList.prototype.shiftElements = function (start, count, offset) {
        if (count <= 0) {
            return;
        }
        if (start < 0 || start >= this._length) {
            throw new Error('start argument out of range');
        }
        if (start + offset < 0) {
            throw new Error('Cannot shift elements in list beyond index 0');
        }
        if (offset > 0) {
            for (var i = count - 1; i >= 0; i--) {
                this.set(start + i + offset, this.get(start + i));
            }
            var expandListBy = (start + count + offset) - this._length;
            if (expandListBy > 0) {
                this._length += expandListBy;
                while (this._length > this.maxLength) {
                    this._length--;
                    this._startIndex++;
                    this.emit('trim', 1);
                }
            }
        }
        else {
            for (var i = 0; i < count; i++) {
                this.set(start + i + offset, this.get(start + i));
            }
        }
    };
    CircularList.prototype._getCyclicIndex = function (index) {
        return (this._startIndex + index) % this.maxLength;
    };
    return CircularList;
}(EventEmitter_1.EventEmitter));
exports.CircularList = CircularList;

//# sourceMappingURL=CircularList.js.map


/***/ }),

/***/ "NegM":
/*!*******************************************************!*\
  !*** ./node_modules/core-js/library/modules/_hide.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var dP = __webpack_require__(/*! ./_object-dp */ "2faE");
var createDesc = __webpack_require__(/*! ./_property-desc */ "rr1i");
module.exports = __webpack_require__(/*! ./_descriptors */ "jmDH") ? function (object, key, value) {
  return dP.f(object, key, createDesc(1, value));
} : function (object, key, value) {
  object[key] = value;
  return object;
};


/***/ }),

/***/ "Nehr":
/*!**********************************!*\
  !*** ./node_modules/url/util.js ***!
  \**********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


module.exports = {
  isString: function(arg) {
    return typeof(arg) === 'string';
  },
  isObject: function(arg) {
    return typeof(arg) === 'object' && arg !== null;
  },
  isNull: function(arg) {
    return arg === null;
  },
  isNullOrUndefined: function(arg) {
    return arg == null;
  }
};


/***/ }),

/***/ "NgHg":
/*!*******************************************!*\
  !*** ./node_modules/fbjs/lib/camelize.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks
 */

var _hyphenPattern = /-(.)/g;

/**
 * Camelcases a hyphenated string, for example:
 *
 *   > camelize('background-color')
 *   < "backgroundColor"
 *
 * @param {string} string
 * @return {string}
 */
function camelize(string) {
  return string.replace(_hyphenPattern, function (_, character) {
    return character.toUpperCase();
  });
}

module.exports = camelize;

/***/ }),

/***/ "Ngil":
/*!***********************************************************!*\
  !*** ./node_modules/react-highlighter/lib/highlighter.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var React = __webpack_require__(/*! react */ "q1tI");
var RegExpPropType = __webpack_require__(/*! ./regExpPropType */ "UXrF");
var escapeStringRegexp = __webpack_require__(/*! escape-string-regexp */ "oxjq");
var blacklist = __webpack_require__(/*! blacklist */ "GRvS");
var createReactClass = __webpack_require__(/*! create-react-class */ "fhzG");
var PropTypes = __webpack_require__(/*! prop-types */ "17x9");

function removeDiacritics(str, blacklist) {
  if (!String.prototype.normalize) {
    // Fall back to original string
    return str;
  }

  if (!blacklist) {
    // No blacklist, just remove all
    return str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
  }
  else {
    var blacklistChars = blacklist.split('');

    // Remove all diacritics that are not a part of a blacklisted character
    // First char cannot be a diacritic
    return str.normalize('NFD').replace(/.[\u0300-\u036f]+/g, function(m) {
      return blacklistChars.indexOf(m.normalize()) > -1 ? m.normalize() : m[0];
    });
  }
}

var Highlighter = createReactClass({
  displayName: 'Highlighter',
  count: 0,
  propTypes: {
    search: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number,
      PropTypes.bool,
      RegExpPropType
    ]).isRequired,
    caseSensitive: PropTypes.bool,
    ignoreDiacritics: PropTypes.bool,
    diacriticsBlacklist: PropTypes.string,
    matchElement: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
    matchClass: PropTypes.string,
    matchStyle: PropTypes.object
  },

  render: function() {
    var props = blacklist(
      this.props,
      'search',
      'caseSensitive',
      'ignoreDiacritics',
      'diacriticsBlacklist',
      'matchElement',
      'matchClass',
      'matchStyle'
    );

    return React.createElement('span', props, this.renderElement(this.props.children));
  },

  /**
   * A wrapper to the highlight method to determine when the highlighting
   * process should occur.
   *
   * @param  {string} subject
   *   The body of text that will be searched for highlighted words.
   *
   * @return {Array}
   *   An array of ReactElements
   */
  renderElement: function(subject) {
    if (this.isScalar() && this.hasSearch()) {
      var search = this.getSearch();
      return this.highlightChildren(subject, search);
    }

    return this.props.children;
  },

  /**
   * Determine if props are valid types for processing.
   *
   * @return {Boolean}
   */
  isScalar: function() {
    return (/string|number|boolean/).test(typeof this.props.children);
  },

  /**
   * Determine if required search prop is defined and valid.
   *
   * @return {Boolean}
   */
  hasSearch: function() {
    return (typeof this.props.search !== 'undefined') && this.props.search;
  },

  /**
   * Get the search prop, but always in the form of a regular expression. Use
   * this as a proxy to this.props.search for consistency.
   *
   * @return {RegExp}
   */
  getSearch: function() {
    if (this.props.search instanceof RegExp) {
      return this.props.search;
    }

    var flags = '';
    if (!this.props.caseSensitive) {
      flags +='i';
    }

    var search = this.props.search;
    if (typeof this.props.search === 'string') {
      search = escapeStringRegexp(search);
    }

    if (this.props.ignoreDiacritics) {
      search = removeDiacritics(search, this.props.diacriticsBlacklist);
    }

    return new RegExp(search, flags);
  },

  /**
   * Get the indexes of the first and last characters of the matched string.
   *
   * @param  {string} subject
   *   The string to search against.
   *
   * @param  {RegExp} search
   *   The regex search query.
   *
   * @return {Object}
   *   An object consisting of "first" and "last" properties representing the
   *   indexes of the first and last characters of a matching string.
   */
  getMatchBoundaries: function(subject, search) {
    var matches = search.exec(subject);
    if (matches) {
      return {
        first: matches.index,
        last: matches.index + matches[0].length
      };
    }
  },

  /**
   * Determines which strings of text should be highlighted or not.
   *
   * @param  {string} subject
   *   The body of text that will be searched for highlighted words.
   * @param  {string} search
   *   The search used to search for highlighted words.
   *
   * @return {Array}
   *   An array of ReactElements
   */
  highlightChildren: function(subject, search) {
    var children = [];
    var remaining = subject;

    while (remaining) {
      var remainingCleaned = (this.props.ignoreDiacritics
        ? removeDiacritics(remaining, this.props.diacriticsBlacklist)
        : remaining
      );

      if (!search.test(remainingCleaned)) {
        children.push(this.renderPlain(remaining));
        return children;
      }

      var boundaries = this.getMatchBoundaries(remainingCleaned, search);

      if (boundaries.first === 0 && boundaries.last === 0) {
        // Regex zero-width match
        return children;
      }

      // Capture the string that leads up to a match...
      var nonMatch = remaining.slice(0, boundaries.first);
      if (nonMatch) {
        children.push(this.renderPlain(nonMatch));
      }

      // Now, capture the matching string...
      var match = remaining.slice(boundaries.first, boundaries.last);
      if (match) {
        children.push(this.renderHighlight(match));
      }

      // And if there's anything left over, recursively run this method again.
      remaining = remaining.slice(boundaries.last);

    }

    return children;
  },

  /**
   * Responsible for rending a non-highlighted element.
   *
   * @param  {string} string
   *   A string value to wrap an element around.
   *
   * @return {ReactElement}
   */
  renderPlain: function(string) {
    this.count++;
    return React.createElement('span', { key: this.count, children: string });
  },

  /**
   * Responsible for rending a highlighted element.
   *
   * @param  {string} string
   *   A string value to wrap an element around.
   *
   * @return {ReactElement}
   */
  renderHighlight: function(string) {
    this.count++;
    return React.createElement(this.props.matchElement, {
      key: this.count,
      className: this.props.matchClass,
      style: this.props.matchStyle,
      children: string
    });
  }
});

Highlighter.defaultProps = {
  caseSensitive: false,
  ignoreDiacritics: false,
  diacriticsBlacklist: '',
  matchElement: 'mark',
  matchClass: 'highlight',
  matchStyle: {}
};

module.exports = Highlighter;


/***/ }),

/***/ "Npjl":
/*!******************************************!*\
  !*** ./node_modules/lodash/_getValue.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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];
}

module.exports = getValue;


/***/ }),

/***/ "Nq3d":
/*!**********************************************************************!*\
  !*** ./node_modules/react-color/lib/components/common/Checkboard.js ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Checkboard = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _checkboard = __webpack_require__(/*! ../../helpers/checkboard */ "Lwbf");

var checkboard = _interopRequireWildcard(_checkboard);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var Checkboard = exports.Checkboard = function Checkboard(_ref) {
  var white = _ref.white,
      grey = _ref.grey,
      size = _ref.size,
      renderers = _ref.renderers,
      borderRadius = _ref.borderRadius,
      boxShadow = _ref.boxShadow;

  var styles = (0, _reactcss2.default)({
    'default': {
      grid: {
        borderRadius: borderRadius,
        boxShadow: boxShadow,
        absolute: '0px 0px 0px 0px',
        background: 'url(' + checkboard.get(white, grey, size, renderers.canvas) + ') center left'
      }
    }
  });

  return _react2.default.createElement('div', { style: styles.grid });
};

Checkboard.defaultProps = {
  size: 8,
  white: 'transparent',
  grey: 'rgba(0,0,0,.08)',
  renderers: {}
};

exports.default = Checkboard;

/***/ }),

/***/ "NsO/":
/*!*************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_to-iobject.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __webpack_require__(/*! ./_iobject */ "M1xp");
var defined = __webpack_require__(/*! ./_defined */ "Jes0");
module.exports = function (it) {
  return IObject(defined(it));
};


/***/ }),

/***/ "Nsyh":
/*!**********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/SymbolSelector.js ***!
  \**********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _classnames = __webpack_require__(/*! classnames */ "TSYQ");

var _classnames2 = _interopRequireDefault(_classnames);

var _plotlyIcons = __webpack_require__(/*! plotly-icons */ "hwSx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var SymbolSelector = function (_Component) {
  _inherits(SymbolSelector, _Component);

  function SymbolSelector(props) {
    _classCallCheck(this, SymbolSelector);

    var _this = _possibleConstructorReturn(this, (SymbolSelector.__proto__ || Object.getPrototypeOf(SymbolSelector)).call(this, props));

    _this.state = {
      isOpen: false
    };
    _this.togglePanel = _this.togglePanel.bind(_this);
    return _this;
  }

  _createClass(SymbolSelector, [{
    key: 'shouldComponentUpdate',
    value: function shouldComponentUpdate(nextProps, nextState) {
      var _props = this.props,
          markerColor = _props.markerColor,
          borderColor = _props.borderColor;
      var nextMarkerColor = nextProps.markerColor,
          nextBorderColor = nextProps.borderColor;


      return this.props.value !== nextProps.value || this.state.isOpen !== nextState.isOpen || markerColor !== nextMarkerColor || borderColor !== nextBorderColor;
    }
  }, {
    key: 'togglePanel',
    value: function togglePanel() {
      this.setState({ isOpen: !this.state.isOpen });
    }
  }, {
    key: 'renderActiveOption',
    value: function renderActiveOption() {
      var _props2 = this.props,
          markerColor = _props2.markerColor,
          borderColor = _props2.borderColor,
          symbolOptions = _props2.symbolOptions,
          value = _props2.value;

      var currentSymbol = symbolOptions.find(function (symbol) {
        return symbol.value === value;
      });
      if (!currentSymbol) {
        return _react2.default.createElement(
          'span',
          {
            style: {
              paddingTop: '5px',
              paddingLeft: '15px'
            }
          },
          '-'
        );
      }

      var symbolStyle = {
        stroke: currentSymbol.fill === 'none' ? markerColor : borderColor,
        strokeOpacity: '1',
        strokeWidth: '2px',
        fill: currentSymbol.fill === 'none' ? 'none' : markerColor
      };

      return _react2.default.createElement(
        'span',
        null,
        _react2.default.createElement(
          'svg',
          { width: '18', height: '18' },
          _react2.default.createElement(
            'g',
            { transform: 'translate(8,8)' },
            _react2.default.createElement('path', { d: currentSymbol.label, style: symbolStyle })
          )
        )
      );
    }
  }, {
    key: 'renderOptions',
    value: function renderOptions() {
      var _this2 = this;

      var _props3 = this.props,
          markerColor = _props3.markerColor,
          borderColor = _props3.borderColor,
          symbolOptions = _props3.symbolOptions;

      return symbolOptions.map(function (option) {
        var fill = option.fill,
            value = option.value,
            label = option.label;


        var symbolStyle = {
          stroke: fill === 'none' ? markerColor : borderColor,
          strokeOpacity: '1',
          strokeWidth: '2px',
          fill: fill === 'none' ? 'none' : markerColor
        };
        return _react2.default.createElement(
          'div',
          {
            className: 'symbol-selector__item',
            key: value,
            onClick: function onClick() {
              return _this2.props.onChange(value);
            }
          },
          _react2.default.createElement(
            'svg',
            { width: '28', height: '28', className: 'symbol-selector__symbol', 'data-value': value },
            _react2.default.createElement(
              'g',
              { transform: 'translate(14,14)' },
              _react2.default.createElement('path', { d: label, style: symbolStyle })
            )
          )
        );
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var isOpen = this.state.isOpen;

      var toggleClass = (0, _classnames2.default)('symbol-selector__toggle', {
        'symbol-selector__toggle--dark': this.props.backgroundDark
      });

      return _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(
          'div',
          { className: toggleClass, onClick: this.togglePanel },
          _react2.default.createElement(
            'span',
            { className: 'symbol-selector__toggle_option' },
            this.renderActiveOption()
          ),
          _react2.default.createElement(
            'span',
            null,
            _react2.default.createElement(_plotlyIcons.CarretDownIcon, { className: 'symbol-selector__toggle__caret' })
          )
        ),
        isOpen && this.renderOptions()
      );
    }
  }]);

  return SymbolSelector;
}(_react.Component);

exports.default = SymbolSelector;


SymbolSelector.propTypes = {
  backgroundDark: _propTypes2.default.bool,
  markerColor: _propTypes2.default.string,
  borderColor: _propTypes2.default.string,
  value: _propTypes2.default.string,
  onChange: _propTypes2.default.func,
  symbolOptions: _propTypes2.default.array
};
//# sourceMappingURL=SymbolSelector.js.map

/***/ }),

/***/ "Nsz2":
/*!******************************************!*\
  !*** ./node_modules/domhandler/index.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var ElementType = __webpack_require__(/*! domelementtype */ "TR4g");

var re_whitespace = /\s+/g;
var NodePrototype = __webpack_require__(/*! ./lib/node */ "AdCt");
var ElementPrototype = __webpack_require__(/*! ./lib/element */ "ZuxE");

function DomHandler(callback, options, elementCB){
	if(typeof callback === "object"){
		elementCB = options;
		options = callback;
		callback = null;
	} else if(typeof options === "function"){
		elementCB = options;
		options = defaultOpts;
	}
	this._callback = callback;
	this._options = options || defaultOpts;
	this._elementCB = elementCB;
	this.dom = [];
	this._done = false;
	this._tagStack = [];
	this._parser = this._parser || null;
}

//default options
var defaultOpts = {
	normalizeWhitespace: false, //Replace all whitespace with single spaces
	withStartIndices: false, //Add startIndex properties to nodes
	withEndIndices: false, //Add endIndex properties to nodes
};

DomHandler.prototype.onparserinit = function(parser){
	this._parser = parser;
};

//Resets the handler back to starting state
DomHandler.prototype.onreset = function(){
	DomHandler.call(this, this._callback, this._options, this._elementCB);
};

//Signals the handler that parsing is done
DomHandler.prototype.onend = function(){
	if(this._done) return;
	this._done = true;
	this._parser = null;
	this._handleCallback(null);
};

DomHandler.prototype._handleCallback =
DomHandler.prototype.onerror = function(error){
	if(typeof this._callback === "function"){
		this._callback(error, this.dom);
	} else {
		if(error) throw error;
	}
};

DomHandler.prototype.onclosetag = function(){
	//if(this._tagStack.pop().name !== name) this._handleCallback(Error("Tagname didn't match!"));
	
	var elem = this._tagStack.pop();

	if(this._options.withEndIndices && elem){
		elem.endIndex = this._parser.endIndex;
	}

	if(this._elementCB) this._elementCB(elem);
};

DomHandler.prototype._createDomElement = function(properties){
	if (!this._options.withDomLvl1) return properties;

	var element;
	if (properties.type === "tag") {
		element = Object.create(ElementPrototype);
	} else {
		element = Object.create(NodePrototype);
	}

	for (var key in properties) {
		if (properties.hasOwnProperty(key)) {
			element[key] = properties[key];
		}
	}

	return element;
};

DomHandler.prototype._addDomElement = function(element){
	var parent = this._tagStack[this._tagStack.length - 1];
	var siblings = parent ? parent.children : this.dom;
	var previousSibling = siblings[siblings.length - 1];

	element.next = null;

	if(this._options.withStartIndices){
		element.startIndex = this._parser.startIndex;
	}
	if(this._options.withEndIndices){
		element.endIndex = this._parser.endIndex;
	}

	if(previousSibling){
		element.prev = previousSibling;
		previousSibling.next = element;
	} else {
		element.prev = null;
	}

	siblings.push(element);
	element.parent = parent || null;
};

DomHandler.prototype.onopentag = function(name, attribs){
	var properties = {
		type: name === "script" ? ElementType.Script : name === "style" ? ElementType.Style : ElementType.Tag,
		name: name,
		attribs: attribs,
		children: []
	};

	var element = this._createDomElement(properties);

	this._addDomElement(element);

	this._tagStack.push(element);
};

DomHandler.prototype.ontext = function(data){
	//the ignoreWhitespace is officially dropped, but for now,
	//it's an alias for normalizeWhitespace
	var normalize = this._options.normalizeWhitespace || this._options.ignoreWhitespace;

	var lastTag;

	if(!this._tagStack.length && this.dom.length && (lastTag = this.dom[this.dom.length-1]).type === ElementType.Text){
		if(normalize){
			lastTag.data = (lastTag.data + data).replace(re_whitespace, " ");
		} else {
			lastTag.data += data;
		}
	} else {
		if(
			this._tagStack.length &&
			(lastTag = this._tagStack[this._tagStack.length - 1]) &&
			(lastTag = lastTag.children[lastTag.children.length - 1]) &&
			lastTag.type === ElementType.Text
		){
			if(normalize){
				lastTag.data = (lastTag.data + data).replace(re_whitespace, " ");
			} else {
				lastTag.data += data;
			}
		} else {
			if(normalize){
				data = data.replace(re_whitespace, " ");
			}

			var element = this._createDomElement({
				data: data,
				type: ElementType.Text
			});

			this._addDomElement(element);
		}
	}
};

DomHandler.prototype.oncomment = function(data){
	var lastTag = this._tagStack[this._tagStack.length - 1];

	if(lastTag && lastTag.type === ElementType.Comment){
		lastTag.data += data;
		return;
	}

	var properties = {
		data: data,
		type: ElementType.Comment
	};

	var element = this._createDomElement(properties);

	this._addDomElement(element);
	this._tagStack.push(element);
};

DomHandler.prototype.oncdatastart = function(){
	var properties = {
		children: [{
			data: "",
			type: ElementType.Text
		}],
		type: ElementType.CDATA
	};

	var element = this._createDomElement(properties);

	this._addDomElement(element);
	this._tagStack.push(element);
};

DomHandler.prototype.oncommentend = DomHandler.prototype.oncdataend = function(){
	this._tagStack.pop();
};

DomHandler.prototype.onprocessinginstruction = function(name, data){
	var element = this._createDomElement({
		name: name,
		data: data,
		type: ElementType.Directive
	});

	this._addDomElement(element);
};

module.exports = DomHandler;


/***/ }),

/***/ "Nx4+":
/*!*********************************************************!*\
  !*** ./node_modules/draft-js/lib/RichTextEditorUtil.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule RichTextEditorUtil
 * @format
 * 
 */



var DraftModifier = __webpack_require__(/*! ./DraftModifier */ "fyOY");
var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");
var SelectionState = __webpack_require__(/*! ./SelectionState */ "hMpd");

var adjustBlockDepthForContentState = __webpack_require__(/*! ./adjustBlockDepthForContentState */ "AKPT");
var nullthrows = __webpack_require__(/*! fbjs/lib/nullthrows */ "gWRK");

var RichTextEditorUtil = {
  currentBlockContainsLink: function currentBlockContainsLink(editorState) {
    var selection = editorState.getSelection();
    var contentState = editorState.getCurrentContent();
    var entityMap = contentState.getEntityMap();
    return contentState.getBlockForKey(selection.getAnchorKey()).getCharacterList().slice(selection.getStartOffset(), selection.getEndOffset()).some(function (v) {
      var entity = v.getEntity();
      return !!entity && entityMap.__get(entity).getType() === 'LINK';
    });
  },

  getCurrentBlockType: function getCurrentBlockType(editorState) {
    var selection = editorState.getSelection();
    return editorState.getCurrentContent().getBlockForKey(selection.getStartKey()).getType();
  },

  getDataObjectForLinkURL: function getDataObjectForLinkURL(uri) {
    return { url: uri.toString() };
  },

  handleKeyCommand: function handleKeyCommand(editorState, command) {
    switch (command) {
      case 'bold':
        return RichTextEditorUtil.toggleInlineStyle(editorState, 'BOLD');
      case 'italic':
        return RichTextEditorUtil.toggleInlineStyle(editorState, 'ITALIC');
      case 'underline':
        return RichTextEditorUtil.toggleInlineStyle(editorState, 'UNDERLINE');
      case 'code':
        return RichTextEditorUtil.toggleCode(editorState);
      case 'backspace':
      case 'backspace-word':
      case 'backspace-to-start-of-line':
        return RichTextEditorUtil.onBackspace(editorState);
      case 'delete':
      case 'delete-word':
      case 'delete-to-end-of-block':
        return RichTextEditorUtil.onDelete(editorState);
      default:
        // they may have custom editor commands; ignore those
        return null;
    }
  },

  insertSoftNewline: function insertSoftNewline(editorState) {
    var contentState = DraftModifier.insertText(editorState.getCurrentContent(), editorState.getSelection(), '\n', editorState.getCurrentInlineStyle(), null);

    var newEditorState = EditorState.push(editorState, contentState, 'insert-characters');

    return EditorState.forceSelection(newEditorState, contentState.getSelectionAfter());
  },

  /**
   * For collapsed selections at the start of styled blocks, backspace should
   * just remove the existing style.
   */
  onBackspace: function onBackspace(editorState) {
    var selection = editorState.getSelection();
    if (!selection.isCollapsed() || selection.getAnchorOffset() || selection.getFocusOffset()) {
      return null;
    }

    // First, try to remove a preceding atomic block.
    var content = editorState.getCurrentContent();
    var startKey = selection.getStartKey();
    var blockBefore = content.getBlockBefore(startKey);

    if (blockBefore && blockBefore.getType() === 'atomic') {
      var blockMap = content.getBlockMap()['delete'](blockBefore.getKey());
      var withoutAtomicBlock = content.merge({
        blockMap: blockMap,
        selectionAfter: selection
      });
      if (withoutAtomicBlock !== content) {
        return EditorState.push(editorState, withoutAtomicBlock, 'remove-range');
      }
    }

    // If that doesn't succeed, try to remove the current block style.
    var withoutBlockStyle = RichTextEditorUtil.tryToRemoveBlockStyle(editorState);

    if (withoutBlockStyle) {
      return EditorState.push(editorState, withoutBlockStyle, 'change-block-type');
    }

    return null;
  },

  onDelete: function onDelete(editorState) {
    var selection = editorState.getSelection();
    if (!selection.isCollapsed()) {
      return null;
    }

    var content = editorState.getCurrentContent();
    var startKey = selection.getStartKey();
    var block = content.getBlockForKey(startKey);
    var length = block.getLength();

    // The cursor is somewhere within the text. Behave normally.
    if (selection.getStartOffset() < length) {
      return null;
    }

    var blockAfter = content.getBlockAfter(startKey);

    if (!blockAfter || blockAfter.getType() !== 'atomic') {
      return null;
    }

    var atomicBlockTarget = selection.merge({
      focusKey: blockAfter.getKey(),
      focusOffset: blockAfter.getLength()
    });

    var withoutAtomicBlock = DraftModifier.removeRange(content, atomicBlockTarget, 'forward');

    if (withoutAtomicBlock !== content) {
      return EditorState.push(editorState, withoutAtomicBlock, 'remove-range');
    }

    return null;
  },

  onTab: function onTab(event, editorState, maxDepth) {
    var selection = editorState.getSelection();
    var key = selection.getAnchorKey();
    if (key !== selection.getFocusKey()) {
      return editorState;
    }

    var content = editorState.getCurrentContent();
    var block = content.getBlockForKey(key);
    var type = block.getType();
    if (type !== 'unordered-list-item' && type !== 'ordered-list-item') {
      return editorState;
    }

    event.preventDefault();

    // Only allow indenting one level beyond the block above, and only if
    // the block above is a list item as well.
    var blockAbove = content.getBlockBefore(key);
    if (!blockAbove) {
      return editorState;
    }

    var typeAbove = blockAbove.getType();
    if (typeAbove !== 'unordered-list-item' && typeAbove !== 'ordered-list-item') {
      return editorState;
    }

    var depth = block.getDepth();
    if (!event.shiftKey && depth === maxDepth) {
      return editorState;
    }

    maxDepth = Math.min(blockAbove.getDepth() + 1, maxDepth);

    var withAdjustment = adjustBlockDepthForContentState(content, selection, event.shiftKey ? -1 : 1, maxDepth);

    return EditorState.push(editorState, withAdjustment, 'adjust-depth');
  },

  toggleBlockType: function toggleBlockType(editorState, blockType) {
    var selection = editorState.getSelection();
    var startKey = selection.getStartKey();
    var endKey = selection.getEndKey();
    var content = editorState.getCurrentContent();
    var target = selection;

    // Triple-click can lead to a selection that includes offset 0 of the
    // following block. The `SelectionState` for this case is accurate, but
    // we should avoid toggling block type for the trailing block because it
    // is a confusing interaction.
    if (startKey !== endKey && selection.getEndOffset() === 0) {
      var blockBefore = nullthrows(content.getBlockBefore(endKey));
      endKey = blockBefore.getKey();
      target = target.merge({
        anchorKey: startKey,
        anchorOffset: selection.getStartOffset(),
        focusKey: endKey,
        focusOffset: blockBefore.getLength(),
        isBackward: false
      });
    }

    var hasAtomicBlock = content.getBlockMap().skipWhile(function (_, k) {
      return k !== startKey;
    }).reverse().skipWhile(function (_, k) {
      return k !== endKey;
    }).some(function (v) {
      return v.getType() === 'atomic';
    });

    if (hasAtomicBlock) {
      return editorState;
    }

    var typeToSet = content.getBlockForKey(startKey).getType() === blockType ? 'unstyled' : blockType;

    return EditorState.push(editorState, DraftModifier.setBlockType(content, target, typeToSet), 'change-block-type');
  },

  toggleCode: function toggleCode(editorState) {
    var selection = editorState.getSelection();
    var anchorKey = selection.getAnchorKey();
    var focusKey = selection.getFocusKey();

    if (selection.isCollapsed() || anchorKey !== focusKey) {
      return RichTextEditorUtil.toggleBlockType(editorState, 'code-block');
    }

    return RichTextEditorUtil.toggleInlineStyle(editorState, 'CODE');
  },

  /**
   * Toggle the specified inline style for the selection. If the
   * user's selection is collapsed, apply or remove the style for the
   * internal state. If it is not collapsed, apply the change directly
   * to the document state.
   */
  toggleInlineStyle: function toggleInlineStyle(editorState, inlineStyle) {
    var selection = editorState.getSelection();
    var currentStyle = editorState.getCurrentInlineStyle();

    // If the selection is collapsed, toggle the specified style on or off and
    // set the result as the new inline style override. This will then be
    // used as the inline style for the next character to be inserted.
    if (selection.isCollapsed()) {
      return EditorState.setInlineStyleOverride(editorState, currentStyle.has(inlineStyle) ? currentStyle.remove(inlineStyle) : currentStyle.add(inlineStyle));
    }

    // If characters are selected, immediately apply or remove the
    // inline style on the document state itself.
    var content = editorState.getCurrentContent();
    var newContent;

    // If the style is already present for the selection range, remove it.
    // Otherwise, apply it.
    if (currentStyle.has(inlineStyle)) {
      newContent = DraftModifier.removeInlineStyle(content, selection, inlineStyle);
    } else {
      newContent = DraftModifier.applyInlineStyle(content, selection, inlineStyle);
    }

    return EditorState.push(editorState, newContent, 'change-inline-style');
  },

  toggleLink: function toggleLink(editorState, targetSelection, entityKey) {
    var withoutLink = DraftModifier.applyEntity(editorState.getCurrentContent(), targetSelection, entityKey);

    return EditorState.push(editorState, withoutLink, 'apply-entity');
  },

  /**
   * When a collapsed cursor is at the start of the first styled block, or
   * an empty styled block, changes block to 'unstyled'. Returns null if
   * block or selection does not meet that criteria.
   */
  tryToRemoveBlockStyle: function tryToRemoveBlockStyle(editorState) {
    var selection = editorState.getSelection();
    var offset = selection.getAnchorOffset();
    if (selection.isCollapsed() && offset === 0) {
      var key = selection.getAnchorKey();
      var content = editorState.getCurrentContent();
      var block = content.getBlockForKey(key);

      var firstBlock = content.getFirstBlock();
      if (block.getLength() > 0 && block !== firstBlock) {
        return null;
      }

      var type = block.getType();
      var blockBefore = content.getBlockBefore(key);
      if (type === 'code-block' && blockBefore && blockBefore.getType() === 'code-block' && blockBefore.getLength() !== 0) {
        return null;
      }

      if (type !== 'unstyled') {
        return DraftModifier.setBlockType(content, selection, 'unstyled');
      }
    }
    return null;
  }
};

module.exports = RichTextEditorUtil;

/***/ }),

/***/ "Nx4I":
/*!************************************************!*\
  !*** ./node_modules/plotly.js/src/registry.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var Loggers = __webpack_require__(/*! ./lib/loggers */ "rhNM");
var noop = __webpack_require__(/*! ./lib/noop */ "t3iM");
var pushUnique = __webpack_require__(/*! ./lib/push_unique */ "Whu6");
var isPlainObject = __webpack_require__(/*! ./lib/is_plain_object */ "E4V0");
var ExtendModule = __webpack_require__(/*! ./lib/extend */ "kJIm");

var basePlotAttributes = __webpack_require__(/*! ./plots/attributes */ "qHYo");
var baseLayoutAttributes = __webpack_require__(/*! ./plots/layout_attributes */ "poX/");

var extendFlat = ExtendModule.extendFlat;
var extendDeepAll = ExtendModule.extendDeepAll;

exports.modules = {};
exports.allCategories = {};
exports.allTypes = [];
exports.subplotsRegistry = {};
exports.transformsRegistry = {};
exports.componentsRegistry = {};
exports.layoutArrayContainers = [];
exports.layoutArrayRegexes = [];
exports.traceLayoutAttributes = {};
exports.localeRegistry = {};
exports.apiMethodRegistry = {};
exports.collectableSubplotTypes = null;

/**
 * Top-level register routine, exported as Plotly.register
 *
 * @param {object array or array of objects} _modules :
 *  module object or list of module object to register.
 *
 *  A valid `moduleType: 'trace'` module has fields:
 *  - name {string} : the trace type
 *  - categories {array} : categories associated with this trace type,
 *                         tested with Register.traceIs()
 *  - meta {object} : meta info (mostly for plot-schema)
 *
 *  A valid `moduleType: 'locale'` module has fields:
 *  - name {string} : the locale name. Should be a 2-digit language string ('en', 'de')
 *                    optionally with a country/region code ('en-GB', 'de-CH'). If a country
 *                    code is used but the base language locale has not yet been supplied,
 *                    we will use this locale for the base as well.
 *  - dictionary {object} : the dictionary mapping input strings to localized strings
 *                          generally the keys should be the literal input strings, but
 *                          if default translations are provided you can use any string as a key.
 *  - format {object} : a `d3.locale` format specifier for this locale
 *                      any omitted keys we'll fall back on en-US.
 *
 *  A valid `moduleType: 'transform'` module has fields:
 *  - name {string} : transform name
 *  - transform {function} : default-level transform function
 *  - calcTransform {function} : calc-level transform function
 *  - attributes {object} : transform attributes declarations
 *  - supplyDefaults {function} : attributes default-supply function
 *
 *  A valid `moduleType: 'component'` module has fields:
 *  - name {string} : the component name, used it with Register.getComponentMethod()
 *                    to employ component method.
 *
 *  A valid `moduleType: 'apiMethod'` module has fields:
 *  - name {string} : the api method name.
 *  - fn {function} : the api method called with Register.call();
 *
 */
exports.register = function register(_modules) {
    exports.collectableSubplotTypes = null;

    if(!_modules) {
        throw new Error('No argument passed to Plotly.register.');
    } else if(_modules && !Array.isArray(_modules)) {
        _modules = [_modules];
    }

    for(var i = 0; i < _modules.length; i++) {
        var newModule = _modules[i];

        if(!newModule) {
            throw new Error('Invalid module was attempted to be registered!');
        }

        switch(newModule.moduleType) {
            case 'trace':
                registerTraceModule(newModule);
                break;
            case 'transform':
                registerTransformModule(newModule);
                break;
            case 'component':
                registerComponentModule(newModule);
                break;
            case 'locale':
                registerLocale(newModule);
                break;
            case 'apiMethod':
                var name = newModule.name;
                exports.apiMethodRegistry[name] = newModule.fn;
                break;
            default:
                throw new Error('Invalid module was attempted to be registered!');
        }
    }
};

/**
 * Get registered module using trace object or trace type
 *
 * @param {object||string} trace
 *  trace object with prop 'type' or trace type as a string
 * @return {object}
 *  module object corresponding to trace type
 */
exports.getModule = function(trace) {
    var _module = exports.modules[getTraceType(trace)];
    if(!_module) return false;
    return _module._module;
};

/**
 * Determine if this trace type is in a given category
 *
 * @param {object||string} traceType
 *  a trace (object) or trace type (string)
 * @param {string} category
 *  category in question
 * @return {boolean}
 */
exports.traceIs = function(traceType, category) {
    traceType = getTraceType(traceType);

    // old plot.ly workspace hack, nothing to see here
    if(traceType === 'various') return false;

    var _module = exports.modules[traceType];

    if(!_module) {
        if(traceType && traceType !== 'area') {
            Loggers.log('Unrecognized trace type ' + traceType + '.');
        }

        _module = exports.modules[basePlotAttributes.type.dflt];
    }

    return !!_module.categories[category];
};

/**
 * Determine if this trace has a transform of the given type and return
 * array of matching indices.
 *
 * @param {object} data
 *  a trace object (member of data or fullData)
 * @param {string} type
 *  type of trace to test
 * @return {array}
 *  array of matching indices. If none found, returns []
 */
exports.getTransformIndices = function(data, type) {
    var indices = [];
    var transforms = data.transforms || [];
    for(var i = 0; i < transforms.length; i++) {
        if(transforms[i].type === type) {
            indices.push(i);
        }
    }
    return indices;
};

/**
 * Determine if this trace has a transform of the given type
 *
 * @param {object} data
 *  a trace object (member of data or fullData)
 * @param {string} type
 *  type of trace to test
 * @return {boolean}
 */
exports.hasTransform = function(data, type) {
    var transforms = data.transforms || [];
    for(var i = 0; i < transforms.length; i++) {
        if(transforms[i].type === type) {
            return true;
        }
    }
    return false;
};

/**
 * Retrieve component module method. Falls back on noop if either the
 * module or the method is missing, so the result can always be safely called
 *
 * @param {string} name
 *  name of component (as declared in component module)
 * @param {string} method
 *  name of component module method
 * @return {function}
 */
exports.getComponentMethod = function(name, method) {
    var _module = exports.componentsRegistry[name];

    if(!_module) return noop;
    return _module[method] || noop;
};

/**
 * Call registered api method.
 *
 * @param {string} name : api method name
 * @param {...array} args : arguments passed to api method
 * @return {any} : returns api method output
 */
exports.call = function() {
    var name = arguments[0];
    var args = [].slice.call(arguments, 1);
    return exports.apiMethodRegistry[name].apply(null, args);
};

function registerTraceModule(_module) {
    var thisType = _module.name;
    var categoriesIn = _module.categories;
    var meta = _module.meta;

    if(exports.modules[thisType]) {
        Loggers.log('Type ' + thisType + ' already registered');
        return;
    }

    if(!exports.subplotsRegistry[_module.basePlotModule.name]) {
        registerSubplot(_module.basePlotModule);
    }

    var categoryObj = {};
    for(var i = 0; i < categoriesIn.length; i++) {
        categoryObj[categoriesIn[i]] = true;
        exports.allCategories[categoriesIn[i]] = true;
    }

    exports.modules[thisType] = {
        _module: _module,
        categories: categoryObj
    };

    if(meta && Object.keys(meta).length) {
        exports.modules[thisType].meta = meta;
    }

    exports.allTypes.push(thisType);

    for(var componentName in exports.componentsRegistry) {
        mergeComponentAttrsToTrace(componentName, thisType);
    }

    /*
     * Collect all trace layout attributes in one place for easier lookup later
     * but don't merge them into the base schema as it would confuse the docs
     * (at least after https://github.com/plotly/documentation/issues/202 gets done!)
     */
    if(_module.layoutAttributes) {
        extendFlat(exports.traceLayoutAttributes, _module.layoutAttributes);
    }
}

function registerSubplot(_module) {
    var plotType = _module.name;

    if(exports.subplotsRegistry[plotType]) {
        Loggers.log('Plot type ' + plotType + ' already registered.');
        return;
    }

    // relayout array handling will look for component module methods with this
    // name and won't find them because this is a subplot module... but that
    // should be fine, it will just fall back on redrawing the plot.
    findArrayRegexps(_module);

    // not sure what's best for the 'cartesian' type at this point
    exports.subplotsRegistry[plotType] = _module;

    for(var componentName in exports.componentsRegistry) {
        mergeComponentAttrsToSubplot(componentName, _module.name);
    }
}

function registerComponentModule(_module) {
    if(typeof _module.name !== 'string') {
        throw new Error('Component module *name* must be a string.');
    }

    var name = _module.name;
    exports.componentsRegistry[name] = _module;

    if(_module.layoutAttributes) {
        if(_module.layoutAttributes._isLinkedToArray) {
            pushUnique(exports.layoutArrayContainers, name);
        }
        findArrayRegexps(_module);
    }

    for(var traceType in exports.modules) {
        mergeComponentAttrsToTrace(name, traceType);
    }

    for(var subplotName in exports.subplotsRegistry) {
        mergeComponentAttrsToSubplot(name, subplotName);
    }

    for(var transformType in exports.transformsRegistry) {
        mergeComponentAttrsToTransform(name, transformType);
    }

    if(_module.schema && _module.schema.layout) {
        extendDeepAll(baseLayoutAttributes, _module.schema.layout);
    }
}

function registerTransformModule(_module) {
    if(typeof _module.name !== 'string') {
        throw new Error('Transform module *name* must be a string.');
    }

    var prefix = 'Transform module ' + _module.name;
    var hasTransform = typeof _module.transform === 'function';
    var hasCalcTransform = typeof _module.calcTransform === 'function';

    if(!hasTransform && !hasCalcTransform) {
        throw new Error(prefix + ' is missing a *transform* or *calcTransform* method.');
    }
    if(hasTransform && hasCalcTransform) {
        Loggers.log([
            prefix + ' has both a *transform* and *calcTransform* methods.',
            'Please note that all *transform* methods are executed',
            'before all *calcTransform* methods.'
        ].join(' '));
    }
    if(!isPlainObject(_module.attributes)) {
        Loggers.log(prefix + ' registered without an *attributes* object.');
    }
    if(typeof _module.supplyDefaults !== 'function') {
        Loggers.log(prefix + ' registered without a *supplyDefaults* method.');
    }

    exports.transformsRegistry[_module.name] = _module;

    for(var componentName in exports.componentsRegistry) {
        mergeComponentAttrsToTransform(componentName, _module.name);
    }
}

function registerLocale(_module) {
    var locale = _module.name;
    var baseLocale = locale.split('-')[0];

    var newDict = _module.dictionary;
    var newFormat = _module.format;
    var hasDict = newDict && Object.keys(newDict).length;
    var hasFormat = newFormat && Object.keys(newFormat).length;

    var locales = exports.localeRegistry;

    var localeObj = locales[locale];
    if(!localeObj) locales[locale] = localeObj = {};

    // Should we use this dict for the base locale?
    // In case we're overwriting a previous dict for this locale, check
    // whether the base matches the full locale dict now. If we're not
    // overwriting, locales[locale] is undefined so this just checks if
    // baseLocale already had a dict or not.
    // Same logic for dateFormats
    if(baseLocale !== locale) {
        var baseLocaleObj = locales[baseLocale];
        if(!baseLocaleObj) locales[baseLocale] = baseLocaleObj = {};

        if(hasDict && baseLocaleObj.dictionary === localeObj.dictionary) {
            baseLocaleObj.dictionary = newDict;
        }
        if(hasFormat && baseLocaleObj.format === localeObj.format) {
            baseLocaleObj.format = newFormat;
        }
    }

    if(hasDict) localeObj.dictionary = newDict;
    if(hasFormat) localeObj.format = newFormat;
}

function findArrayRegexps(_module) {
    if(_module.layoutAttributes) {
        var arrayAttrRegexps = _module.layoutAttributes._arrayAttrRegexps;
        if(arrayAttrRegexps) {
            for(var i = 0; i < arrayAttrRegexps.length; i++) {
                pushUnique(exports.layoutArrayRegexes, arrayAttrRegexps[i]);
            }
        }
    }
}

function mergeComponentAttrsToTrace(componentName, traceType) {
    var componentSchema = exports.componentsRegistry[componentName].schema;
    if(!componentSchema || !componentSchema.traces) return;

    var traceAttrs = componentSchema.traces[traceType];
    if(traceAttrs) {
        extendDeepAll(exports.modules[traceType]._module.attributes, traceAttrs);
    }
}

function mergeComponentAttrsToTransform(componentName, transformType) {
    var componentSchema = exports.componentsRegistry[componentName].schema;
    if(!componentSchema || !componentSchema.transforms) return;

    var transformAttrs = componentSchema.transforms[transformType];
    if(transformAttrs) {
        extendDeepAll(exports.transformsRegistry[transformType].attributes, transformAttrs);
    }
}

function mergeComponentAttrsToSubplot(componentName, subplotName) {
    var componentSchema = exports.componentsRegistry[componentName].schema;
    if(!componentSchema || !componentSchema.subplots) return;

    var subplotModule = exports.subplotsRegistry[subplotName];
    var subplotAttrs = subplotModule.layoutAttributes;
    var subplotAttr = subplotModule.attr === 'subplot' ? subplotModule.name : subplotModule.attr;
    if(Array.isArray(subplotAttr)) subplotAttr = subplotAttr[0];

    var componentLayoutAttrs = componentSchema.subplots[subplotAttr];
    if(subplotAttrs && componentLayoutAttrs) {
        extendDeepAll(subplotAttrs, componentLayoutAttrs);
    }
}

function getTraceType(traceType) {
    if(typeof traceType === 'object') traceType = traceType.type;
    return traceType;
}


/***/ }),

/***/ "NykK":
/*!********************************************!*\
  !*** ./node_modules/lodash/_baseGetTag.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Symbol = __webpack_require__(/*! ./_Symbol */ "nmnc"),
    getRawTag = __webpack_require__(/*! ./_getRawTag */ "AP2z"),
    objectToString = __webpack_require__(/*! ./_objectToString */ "KfNM");

/** `Object#toString` result references. */
var nullTag = '[object Null]',
    undefinedTag = '[object Undefined]';

/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;

/**
 * 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);
}

module.exports = baseGetTag;


/***/ }),

/***/ "O0oS":
/*!************************************************!*\
  !*** ./node_modules/lodash/_defineProperty.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getNative = __webpack_require__(/*! ./_getNative */ "Cwc5");

var defineProperty = (function() {
  try {
    var func = getNative(Object, 'defineProperty');
    func({}, '', {});
    return func;
  } catch (e) {}
}());

module.exports = defineProperty;


/***/ }),

/***/ "O4+9":
/*!***********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeOhlcIcon.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeOhlcIcon = function TraceTypeOhlcIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement(
            'g',
            { fill: 'none' },
            _react2.default.createElement('path', { d: 'M0 0h46v46H0z' }),
            _react2.default.createElement('path', { stroke: '#1d9bfb', d: 'M23 24v16M11 12v24M35 6v29m-24 0H6m10-14h-5m12 18h-5m11-14h-5m11 5h-5M40 7h-5', strokeMiterlimit: '10', strokeWidth: '2' })
        )
    );
};

exports.default = TraceTypeOhlcIcon;

/***/ }),

/***/ "O4zn":
/*!**************************************************************!*\
  !*** ./node_modules/draft-js/lib/setDraftEditorSelection.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule setDraftEditorSelection
 * @format
 * 
 */



var DraftJsDebugLogging = __webpack_require__(/*! ./DraftJsDebugLogging */ "FcOR");

var containsNode = __webpack_require__(/*! fbjs/lib/containsNode */ "TWoB");
var getActiveElement = __webpack_require__(/*! fbjs/lib/getActiveElement */ "jl2H");
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");

function getAnonymizedDOM(node, getNodeLabels) {
  if (!node) {
    return '[empty]';
  }

  var anonymized = anonymizeTextWithin(node, getNodeLabels);
  if (anonymized.nodeType === Node.TEXT_NODE) {
    return anonymized.textContent;
  }

  !(anonymized instanceof Element) ?  true ? invariant(false, 'Node must be an Element if it is not a text node.') : undefined : void 0;
  return anonymized.outerHTML;
}

function anonymizeTextWithin(node, getNodeLabels) {
  var labels = getNodeLabels !== undefined ? getNodeLabels(node) : [];

  if (node.nodeType === Node.TEXT_NODE) {
    var length = node.textContent.length;
    return document.createTextNode('[text ' + length + (labels.length ? ' | ' + labels.join(', ') : '') + ']');
  }

  var clone = node.cloneNode();
  if (clone.nodeType === 1 && labels.length) {
    clone.setAttribute('data-labels', labels.join(', '));
  }
  var childNodes = node.childNodes;
  for (var ii = 0; ii < childNodes.length; ii++) {
    clone.appendChild(anonymizeTextWithin(childNodes[ii], getNodeLabels));
  }

  return clone;
}

function getAnonymizedEditorDOM(node, getNodeLabels) {
  // grabbing the DOM content of the Draft editor
  var currentNode = node;
  while (currentNode) {
    if (currentNode instanceof Element && currentNode.hasAttribute('contenteditable')) {
      // found the Draft editor container
      return getAnonymizedDOM(currentNode, getNodeLabels);
    } else {
      currentNode = currentNode.parentNode;
    }
  }
  return 'Could not find contentEditable parent of node';
}

function getNodeLength(node) {
  return node.nodeValue === null ? node.childNodes.length : node.nodeValue.length;
}

/**
 * In modern non-IE browsers, we can support both forward and backward
 * selections.
 *
 * Note: IE10+ supports the Selection object, but it does not support
 * the `extend` method, which means that even in modern IE, it's not possible
 * to programatically create a backward selection. Thus, for all IE
 * versions, we use the old IE API to create our selections.
 */
function setDraftEditorSelection(selectionState, node, blockKey, nodeStart, nodeEnd) {
  // It's possible that the editor has been removed from the DOM but
  // our selection code doesn't know it yet. Forcing selection in
  // this case may lead to errors, so just bail now.
  if (!containsNode(document.documentElement, node)) {
    return;
  }

  var selection = global.getSelection();
  var anchorKey = selectionState.getAnchorKey();
  var anchorOffset = selectionState.getAnchorOffset();
  var focusKey = selectionState.getFocusKey();
  var focusOffset = selectionState.getFocusOffset();
  var isBackward = selectionState.getIsBackward();

  // IE doesn't support backward selection. Swap key/offset pairs.
  if (!selection.extend && isBackward) {
    var tempKey = anchorKey;
    var tempOffset = anchorOffset;
    anchorKey = focusKey;
    anchorOffset = focusOffset;
    focusKey = tempKey;
    focusOffset = tempOffset;
    isBackward = false;
  }

  var hasAnchor = anchorKey === blockKey && nodeStart <= anchorOffset && nodeEnd >= anchorOffset;

  var hasFocus = focusKey === blockKey && nodeStart <= focusOffset && nodeEnd >= focusOffset;

  // If the selection is entirely bound within this node, set the selection
  // and be done.
  if (hasAnchor && hasFocus) {
    selection.removeAllRanges();
    addPointToSelection(selection, node, anchorOffset - nodeStart, selectionState);
    addFocusToSelection(selection, node, focusOffset - nodeStart, selectionState);
    return;
  }

  if (!isBackward) {
    // If the anchor is within this node, set the range start.
    if (hasAnchor) {
      selection.removeAllRanges();
      addPointToSelection(selection, node, anchorOffset - nodeStart, selectionState);
    }

    // If the focus is within this node, we can assume that we have
    // already set the appropriate start range on the selection, and
    // can simply extend the selection.
    if (hasFocus) {
      addFocusToSelection(selection, node, focusOffset - nodeStart, selectionState);
    }
  } else {
    // If this node has the focus, set the selection range to be a
    // collapsed range beginning here. Later, when we encounter the anchor,
    // we'll use this information to extend the selection.
    if (hasFocus) {
      selection.removeAllRanges();
      addPointToSelection(selection, node, focusOffset - nodeStart, selectionState);
    }

    // If this node has the anchor, we may assume that the correct
    // focus information is already stored on the selection object.
    // We keep track of it, reset the selection range, and extend it
    // back to the focus point.
    if (hasAnchor) {
      var storedFocusNode = selection.focusNode;
      var storedFocusOffset = selection.focusOffset;

      selection.removeAllRanges();
      addPointToSelection(selection, node, anchorOffset - nodeStart, selectionState);
      addFocusToSelection(selection, storedFocusNode, storedFocusOffset, selectionState);
    }
  }
}

/**
 * Extend selection towards focus point.
 */
function addFocusToSelection(selection, node, offset, selectionState) {
  var activeElement = getActiveElement();
  if (selection.extend && containsNode(activeElement, node)) {
    // If `extend` is called while another element has focus, an error is
    // thrown. We therefore disable `extend` if the active element is somewhere
    // other than the node we are selecting. This should only occur in Firefox,
    // since it is the only browser to support multiple selections.
    // See https://bugzilla.mozilla.org/show_bug.cgi?id=921444.

    // logging to catch bug that is being reported in t16250795
    if (offset > getNodeLength(node)) {
      // the call to 'selection.extend' is about to throw
      DraftJsDebugLogging.logSelectionStateFailure({
        anonymizedDom: getAnonymizedEditorDOM(node),
        extraParams: JSON.stringify({ offset: offset }),
        selectionState: JSON.stringify(selectionState.toJS())
      });
    }

    // logging to catch bug that is being reported in t18110632
    var nodeWasFocus = node === selection.focusNode;
    try {
      selection.extend(node, offset);
    } catch (e) {
      DraftJsDebugLogging.logSelectionStateFailure({
        anonymizedDom: getAnonymizedEditorDOM(node, function (n) {
          var labels = [];
          if (n === activeElement) {
            labels.push('active element');
          }
          if (n === selection.anchorNode) {
            labels.push('selection anchor node');
          }
          if (n === selection.focusNode) {
            labels.push('selection focus node');
          }
          return labels;
        }),
        extraParams: JSON.stringify({
          activeElementName: activeElement ? activeElement.nodeName : null,
          nodeIsFocus: node === selection.focusNode,
          nodeWasFocus: nodeWasFocus,
          selectionRangeCount: selection.rangeCount,
          selectionAnchorNodeName: selection.anchorNode ? selection.anchorNode.nodeName : null,
          selectionAnchorOffset: selection.anchorOffset,
          selectionFocusNodeName: selection.focusNode ? selection.focusNode.nodeName : null,
          selectionFocusOffset: selection.focusOffset,
          message: e ? '' + e : null,
          offset: offset
        }, null, 2),
        selectionState: JSON.stringify(selectionState.toJS(), null, 2)
      });
      // allow the error to be thrown -
      // better than continuing in a broken state
      throw e;
    }
  } else {
    // IE doesn't support extend. This will mean no backward selection.
    // Extract the existing selection range and add focus to it.
    // Additionally, clone the selection range. IE11 throws an
    // InvalidStateError when attempting to access selection properties
    // after the range is detached.
    var range = selection.getRangeAt(0);
    range.setEnd(node, offset);
    selection.addRange(range.cloneRange());
  }
}

function addPointToSelection(selection, node, offset, selectionState) {
  var range = document.createRange();
  // logging to catch bug that is being reported in t16250795
  if (offset > getNodeLength(node)) {
    // in this case we know that the call to 'range.setStart' is about to throw
    DraftJsDebugLogging.logSelectionStateFailure({
      anonymizedDom: getAnonymizedEditorDOM(node),
      extraParams: JSON.stringify({ offset: offset }),
      selectionState: JSON.stringify(selectionState.toJS())
    });
  }
  range.setStart(node, offset);
  selection.addRange(range);
}

module.exports = setDraftEditorSelection;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "O7RO":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_getMatchData.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isStrictComparable = __webpack_require__(/*! ./_isStrictComparable */ "CMye"),
    keys = __webpack_require__(/*! ./keys */ "7GkX");

/**
 * 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;
}

module.exports = getMatchData;


/***/ }),

/***/ "OA+I":
/*!*********************************************************!*\
  !*** ./node_modules/elliptic/lib/elliptic/eddsa/key.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var elliptic = __webpack_require__(/*! ../../elliptic */ "MzeL");
var utils = elliptic.utils;
var assert = utils.assert;
var parseBytes = utils.parseBytes;
var cachedProperty = utils.cachedProperty;

/**
* @param {EDDSA} eddsa - instance
* @param {Object} params - public/private key parameters
*
* @param {Array<Byte>} [params.secret] - secret seed bytes
* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)
* @param {Array<Byte>} [params.pub] - public key point encoded as bytes
*
*/
function KeyPair(eddsa, params) {
  this.eddsa = eddsa;
  this._secret = parseBytes(params.secret);
  if (eddsa.isPoint(params.pub))
    this._pub = params.pub;
  else
    this._pubBytes = parseBytes(params.pub);
}

KeyPair.fromPublic = function fromPublic(eddsa, pub) {
  if (pub instanceof KeyPair)
    return pub;
  return new KeyPair(eddsa, { pub: pub });
};

KeyPair.fromSecret = function fromSecret(eddsa, secret) {
  if (secret instanceof KeyPair)
    return secret;
  return new KeyPair(eddsa, { secret: secret });
};

KeyPair.prototype.secret = function secret() {
  return this._secret;
};

cachedProperty(KeyPair, 'pubBytes', function pubBytes() {
  return this.eddsa.encodePoint(this.pub());
});

cachedProperty(KeyPair, 'pub', function pub() {
  if (this._pubBytes)
    return this.eddsa.decodePoint(this._pubBytes);
  return this.eddsa.g.mul(this.priv());
});

cachedProperty(KeyPair, 'privBytes', function privBytes() {
  var eddsa = this.eddsa;
  var hash = this.hash();
  var lastIx = eddsa.encodingLength - 1;

  var a = hash.slice(0, eddsa.encodingLength);
  a[0] &= 248;
  a[lastIx] &= 127;
  a[lastIx] |= 64;

  return a;
});

cachedProperty(KeyPair, 'priv', function priv() {
  return this.eddsa.decodeInt(this.privBytes());
});

cachedProperty(KeyPair, 'hash', function hash() {
  return this.eddsa.hash().update(this.secret()).digest();
});

cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() {
  return this.hash().slice(this.eddsa.encodingLength);
});

KeyPair.prototype.sign = function sign(message) {
  assert(this._secret, 'KeyPair can only verify');
  return this.eddsa.sign(message, this);
};

KeyPair.prototype.verify = function verify(message, sig) {
  return this.eddsa.verify(message, sig, this);
};

KeyPair.prototype.getSecret = function getSecret(enc) {
  assert(this._secret, 'KeyPair is public only');
  return utils.encode(this.secret(), enc);
};

KeyPair.prototype.getPublic = function getPublic(enc) {
  return utils.encode(this.pubBytes(), enc);
};

module.exports = KeyPair;


/***/ }),

/***/ "OBhP":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_baseClone.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Stack = __webpack_require__(/*! ./_Stack */ "fmRc"),
    arrayEach = __webpack_require__(/*! ./_arrayEach */ "gFfm"),
    assignValue = __webpack_require__(/*! ./_assignValue */ "MrPd"),
    baseAssign = __webpack_require__(/*! ./_baseAssign */ "WwFo"),
    baseAssignIn = __webpack_require__(/*! ./_baseAssignIn */ "Dw+G"),
    cloneBuffer = __webpack_require__(/*! ./_cloneBuffer */ "5Tg0"),
    copyArray = __webpack_require__(/*! ./_copyArray */ "Q1l4"),
    copySymbols = __webpack_require__(/*! ./_copySymbols */ "VOtZ"),
    copySymbolsIn = __webpack_require__(/*! ./_copySymbolsIn */ "EEGq"),
    getAllKeys = __webpack_require__(/*! ./_getAllKeys */ "qZTm"),
    getAllKeysIn = __webpack_require__(/*! ./_getAllKeysIn */ "G6z8"),
    getTag = __webpack_require__(/*! ./_getTag */ "QqLw"),
    initCloneArray = __webpack_require__(/*! ./_initCloneArray */ "yHx3"),
    initCloneByTag = __webpack_require__(/*! ./_initCloneByTag */ "wrZu"),
    initCloneObject = __webpack_require__(/*! ./_initCloneObject */ "+iFO"),
    isArray = __webpack_require__(/*! ./isArray */ "Z0cm"),
    isBuffer = __webpack_require__(/*! ./isBuffer */ "DSRE"),
    isMap = __webpack_require__(/*! ./isMap */ "zEVN"),
    isObject = __webpack_require__(/*! ./isObject */ "GoyQ"),
    isSet = __webpack_require__(/*! ./isSet */ "1+5i"),
    keys = __webpack_require__(/*! ./keys */ "7GkX");

/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
    CLONE_FLAT_FLAG = 2,
    CLONE_SYMBOLS_FLAG = 4;

/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
    arrayTag = '[object Array]',
    boolTag = '[object Boolean]',
    dateTag = '[object Date]',
    errorTag = '[object Error]',
    funcTag = '[object Function]',
    genTag = '[object GeneratorFunction]',
    mapTag = '[object Map]',
    numberTag = '[object Number]',
    objectTag = '[object Object]',
    regexpTag = '[object RegExp]',
    setTag = '[object Set]',
    stringTag = '[object String]',
    symbolTag = '[object Symbol]',
    weakMapTag = '[object WeakMap]';

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 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;

/**
 * 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));
    });

    return result;
  }

  if (isMap(value)) {
    value.forEach(function(subValue, key) {
      result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
    });

    return result;
  }

  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;
}

module.exports = baseClone;


/***/ }),

/***/ "OIYi":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/en-ca.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var enCa = moment.defineLocale('en-ca', {
    months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
    monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
    weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
    weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
    weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
    longDateFormat : {
        LT : 'h:mm A',
        LTS : 'h:mm:ss A',
        L : 'YYYY-MM-DD',
        LL : 'MMMM D, YYYY',
        LLL : 'MMMM D, YYYY h:mm A',
        LLLL : 'dddd, MMMM D, YYYY h:mm A'
    },
    calendar : {
        sameDay : '[Today at] LT',
        nextDay : '[Tomorrow at] LT',
        nextWeek : 'dddd [at] LT',
        lastDay : '[Yesterday at] LT',
        lastWeek : '[Last] dddd [at] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'in %s',
        past : '%s ago',
        s : 'a few seconds',
        ss : '%d seconds',
        m : 'a minute',
        mm : '%d minutes',
        h : 'an hour',
        hh : '%d hours',
        d : 'a day',
        dd : '%d days',
        M : 'a month',
        MM : '%d months',
        y : 'a year',
        yy : '%d years'
    },
    dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/,
    ordinal : function (number) {
        var b = number % 10,
            output = (~~(number % 100 / 10) === 1) ? 'th' :
            (b === 1) ? 'st' :
            (b === 2) ? 'nd' :
            (b === 3) ? 'rd' : 'th';
        return number + output;
    }
});

return enCa;

})));


/***/ }),

/***/ "OM9w":
/*!***********************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/apputils-extension/style/index.css ***!
  \***********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports
exports.i(__webpack_require__(/*! -!../../../css-loader!./redirect.css */ "Izdy"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./splash.css */ "hcLw"), "");

// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, Jupyter Development Team.\n|\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n", ""]);

// exports


/***/ }),

/***/ "ONRs":
/*!*****************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotFitIcon.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotFitIcon = function PlotFitIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M1.313 19.313c0 1.5 1.188 2.688 2.688 2.688s2.688-1.188 2.688-2.688c0-1.438-1.188-2.625-2.688-2.625s-2.688 1.188-2.688 2.625zM9.313 8c0 1.5 1.188 2.688 2.688 2.688S14.689 9.5 14.689 8c0-1.5-1.188-2.688-2.688-2.688S9.313 6.5 9.313 8zm16 4.688c0 1.438 1.188 2.625 2.688 2.625s2.688-1.188 2.688-2.625c0-1.5-1.188-2.688-2.688-2.688s-2.688 1.188-2.688 2.688zm-8 11.312c0 1.5 1.188 2.688 2.688 2.688S22.689 25.5 22.689 24c0-1.5-1.188-2.688-2.688-2.688S17.313 22.5 17.313 24zM32 22.688L0 13.313v-4l32 9.375z' })
    );
};

exports.default = PlotFitIcon;

/***/ }),

/***/ "OREO":
/*!*****************************************************************!*\
  !*** ./node_modules/@jupyterlab/extensionmanager/lib/widget.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const React = __importStar(__webpack_require__(/*! react */ "q1tI"));
const react_paginate_1 = __importDefault(__webpack_require__(/*! react-paginate */ "werx"));
const model_1 = __webpack_require__(/*! ./model */ "mT+/");
const query_1 = __webpack_require__(/*! ./query */ "NW3o");
// TODO: Replace pagination with lazy loading of lower search results
/**
 * Search bar VDOM component.
 */
class SearchBar extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: ''
        };
    }
    /**
     * Render the list view using the virtual DOM.
     */
    render() {
        return (React.createElement("div", { className: "jp-extensionmanager-search-bar" },
            React.createElement("div", { className: "jp-extensionmanager-search-wrapper" },
                React.createElement("input", { type: "text", className: "jp-extensionmanager-input", placeholder: this.props.placeholder, onChange: this.handleChange.bind(this), value: this.state.value }))));
    }
    /**
     * Handler for search input changes.
     */
    handleChange(e) {
        let target = e.target;
        this.setState({
            value: target.value
        });
    }
}
exports.SearchBar = SearchBar;
/**
 * Create a build prompt as a react element.
 *
 * @param props Configuration of the build prompt.
 */
function BuildPrompt(props) {
    return (React.createElement("div", { className: "jp-extensionmanager-buildprompt" },
        React.createElement("div", { className: "jp-extensionmanager-buildmessage" }, "A build is needed to include the latest changes"),
        React.createElement("button", { className: "jp-extensionmanager-rebuild", onClick: props.performBuild }, "Rebuild"),
        React.createElement("button", { className: "jp-extensionmanager-ignorebuild", onClick: props.ignoreBuild }, "Ignore")));
}
/**
 * VDOM for visualizing an extension entry.
 */
function ListEntry(props) {
    const { entry } = props;
    const flagClasses = [];
    if (entry.installed) {
        flagClasses.push('jp-extensionmanager-entry-installed');
    }
    if (entry.enabled) {
        flagClasses.push('jp-extensionmanager-entry-enabled');
    }
    if (model_1.ListModel.entryHasUpdate(entry)) {
        flagClasses.push('jp-extensionmanager-entry-update');
    }
    if (entry.status && ['ok', 'warning', 'error'].indexOf(entry.status) !== -1) {
        flagClasses.push(`jp-extensionmanager-entry-${entry.status}`);
    }
    let title = entry.name;
    if (query_1.isJupyterOrg(entry.name)) {
        flagClasses.push(`jp-extensionmanager-entry-mod-whitelisted`);
        title = `${entry.name} (Developed by Project Jupyter)`;
    }
    return (React.createElement("li", { className: `jp-extensionmanager-entry ${flagClasses.join(' ')}`, title: title },
        React.createElement("div", { className: "jp-extensionmanager-entry-title" },
            React.createElement("div", { className: "jp-extensionmanager-entry-name" },
                React.createElement("a", { href: entry.url, target: "_blank" }, entry.name)),
            React.createElement("div", { className: "jp-extensionmanager-entry-jupyter-org" })),
        React.createElement("div", { className: "jp-extensionmanager-entry-content" },
            React.createElement("div", { className: "jp-extensionmanager-entry-description" }, entry.description),
            React.createElement("div", { className: "jp-extensionmanager-entry-buttons" },
                React.createElement("button", { className: "jp-extensionmanager-install", onClick: () => props.performAction('install', entry) }, "Install"),
                React.createElement("button", { className: "jp-extensionmanager-update", 
                    // An install action will update the extension:
                    onClick: () => props.performAction('install', entry) }, "Update"),
                React.createElement("button", { className: "jp-extensionmanager-uninstall", onClick: () => props.performAction('uninstall', entry) }, "Uninstall"),
                React.createElement("button", { className: "jp-extensionmanager-enable", onClick: () => props.performAction('enable', entry) }, "Enable"),
                React.createElement("button", { className: "jp-extensionmanager-disable", onClick: () => props.performAction('disable', entry) }, "Disable")))));
}
/**
 * List view widget for extensions
 */
function ListView(props) {
    const entryViews = [];
    for (let entry of props.entries) {
        entryViews.push(React.createElement(ListEntry, { entry: entry, key: entry.name, performAction: props.performAction }));
    }
    let pagination;
    if (props.numPages > 1) {
        pagination = (React.createElement("div", { className: "jp-extensionmanager-pagination" },
            React.createElement(react_paginate_1.default, { previousLabel: '<', nextLabel: '>', breakLabel: React.createElement("a", { href: "" }, "..."), breakClassName: 'break-me', pageCount: props.numPages, marginPagesDisplayed: 2, pageRangeDisplayed: 5, onPageChange: (data) => props.onPage(data.selected), containerClassName: 'pagination', activeClassName: 'active' })));
    }
    const listview = (React.createElement("ul", { className: "jp-extensionmanager-listview" }, entryViews));
    return (React.createElement("div", { className: "jp-extensionmanager-listview-wrapper" },
        entryViews.length > 0 ? (listview) : (React.createElement("div", { key: "message", className: "jp-extensionmanager-listview-message" }, "No entries")),
        pagination));
}
exports.ListView = ListView;
/**
 *
 *
 * @param {RefreshButton.IProperties} props
 * @returns {React.ReactElement<any>}
 */
function RefreshButton(props) {
    return (React.createElement(apputils_1.ToolbarButtonComponent, { key: "refreshButton", className: "jp-extensionmanager-refresh", iconClassName: "jp-RefreshIcon jp-Icon jp-Icon-16", onClick: props.onClick, tooltip: "Refresh extension list" }));
}
function ErrorMessage(props) {
    return (React.createElement("div", { key: "error-msg", className: "jp-extensionmanager-error" }, props.children));
}
/**
 *
 */
class CollapsibleSection extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            collapsed: props.startCollapsed
        };
    }
    /**
     * Render the collapsible section using the virtual DOM.
     */
    render() {
        const elements = [
            React.createElement("header", { key: "header" },
                React.createElement(apputils_1.ToolbarButtonComponent, { key: "collapser", iconClassName: 'jp-Icon jp-Icon-16 ' +
                        (this.state.collapsed
                            ? 'jp-extensionmanager-collapseIcon'
                            : 'jp-extensionmanager-expandIcon'), className: 'jp-collapser-button', onClick: () => {
                        this.onCollapse();
                    } }),
                React.createElement("span", { className: "jp-extensionmanager-headerText" }, this.props.header),
                this.props.headerElements)
        ];
        if (!this.state.collapsed) {
            if (Array.isArray(this.props.children)) {
                elements.push(...this.props.children);
            }
            else {
                elements.push(this.props.children);
            }
        }
        return elements;
    }
    /**
     * Handler for search input changes.
     */
    onCollapse() {
        if (this.props.onCollapse !== undefined) {
            this.props.onCollapse(!this.state.collapsed);
        }
        this.setState({
            collapsed: !this.state.collapsed
        });
    }
}
exports.CollapsibleSection = CollapsibleSection;
/**
 * The main view for the discovery extension.
 */
class ExtensionView extends apputils_1.VDomRenderer {
    constructor(serviceManager) {
        super();
        this.model = new model_1.ListModel(serviceManager);
        this.addClass('jp-extensionmanager-view');
    }
    /**
     * The search input node.
     */
    get inputNode() {
        return this.node.getElementsByClassName('jp-extensionmanager-input')[0];
    }
    /**
     * Render the extension view using the virtual DOM.
     */
    render() {
        const model = this.model;
        let pages = Math.ceil(model.totalEntries / model.pagination);
        let elements = [React.createElement(SearchBar, { key: "searchbar", placeholder: "SEARCH" })];
        if (model.promptBuild) {
            elements.push(React.createElement(BuildPrompt, { key: "buildpromt", performBuild: () => {
                    model.performBuild();
                }, ignoreBuild: () => {
                    model.ignoreBuildRecommendation();
                } }));
        }
        // Indicator element for pending actions:
        elements.push(React.createElement("div", { key: "pending", className: `jp-extensionmanager-pending ${model.hasPendingActions() ? 'jp-mod-hasPending' : ''}` }));
        const content = [];
        if (!model.initialized) {
            model.initialize();
            content.push(React.createElement("div", { key: "loading-placeholder", className: "jp-extensionmanager-loader" }, "Updating extensions list"));
        }
        else if (model.serverConnectionError !== null) {
            content.push(React.createElement(ErrorMessage, { key: "error-msg" },
                React.createElement("p", null, "Error communicating with server extension. Consult the documentation for how to ensure that it is enabled."),
                React.createElement("p", null, "Reason given:"),
                React.createElement("pre", null, model.serverConnectionError)));
        }
        else if (model.serverRequirementsError !== null) {
            content.push(React.createElement(ErrorMessage, { key: "error-msg" },
                React.createElement("p", null, "The server has some missing requirements for installing extensions."),
                React.createElement("p", null, "Details:"),
                React.createElement("pre", null, model.serverRequirementsError)));
        }
        else {
            // List installed and discovery sections
            let installedContent = [];
            if (model.installedError !== null) {
                installedContent.push(React.createElement(ErrorMessage, null, `Error querying installed extensions${model.installedError ? `: ${model.installedError}` : '.'}`));
            }
            else {
                installedContent.push(React.createElement(ListView, { entries: model.installed, numPages: 1, onPage: value => {
                        /* no-op */
                    }, performAction: this.onAction.bind(this) }));
            }
            content.push(React.createElement(CollapsibleSection, { header: "Installed", key: "installed-section", startCollapsed: false, headerElements: React.createElement(RefreshButton, { onClick: () => {
                        model.refreshInstalled();
                    } }) }, installedContent));
            let searchContent = [];
            if (model.searchError !== null) {
                searchContent.push(React.createElement(ErrorMessage, null, `Error searching for extensions${model.searchError ? `: ${model.searchError}` : '.'}`));
            }
            else {
                searchContent.push(React.createElement(ListView
                // Filter out installed extensions:
                , { 
                    // Filter out installed extensions:
                    entries: model.searchResult.filter(entry => model.installed.indexOf(entry) === -1), numPages: pages, onPage: value => {
                        this.onPage(value);
                    }, performAction: this.onAction.bind(this) }));
            }
            content.push(React.createElement(CollapsibleSection, { header: model.query ? 'Search Results' : 'Discover', key: "search-section", startCollapsed: true, onCollapse: (collapsed) => {
                    if (!collapsed && model.query === null) {
                        model.query = '';
                    }
                } }, searchContent));
        }
        elements.push(React.createElement("div", { key: "content", className: "jp-extensionmanager-content" }, content));
        return elements;
    }
    /**
     * Callback handler for the user specifies a new search query.
     *
     * @param value The new query.
     */
    onSearch(value) {
        this.model.query = value;
    }
    /**
     * Callback handler for the user changes the page of the search result pagination.
     *
     * @param value The pagination page number.
     */
    onPage(value) {
        this.model.page = value;
    }
    /**
     * Callback handler for when the user wants to perform an action on an extension.
     *
     * @param action The action to perform.
     * @param entry The entry to perform the action on.
     */
    onAction(action, entry) {
        switch (action) {
            case 'install':
                return this.model.install(entry);
            case 'uninstall':
                return this.model.uninstall(entry);
            case 'enable':
                return this.model.enable(entry);
            case 'disable':
                return this.model.disable(entry);
            default:
                throw new Error(`Invalid action: ${action}`);
        }
    }
    /**
     * Handle the DOM events for the command palette.
     *
     * @param event - The DOM event sent to the command palette.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the command palette's DOM node.
     * It should not be called directly by user code.
     */
    handleEvent(event) {
        switch (event.type) {
            case 'input':
                this.onSearch(this.inputNode.value);
                break;
            case 'focus':
            case 'blur':
                this._toggleFocused();
                break;
            default:
                break;
        }
    }
    /**
     * A message handler invoked on a `'before-attach'` message.
     */
    onBeforeAttach(msg) {
        this.node.addEventListener('input', this);
        this.node.addEventListener('focus', this, true);
        this.node.addEventListener('blur', this, true);
    }
    /**
     * A message handler invoked on an `'after-detach'` message.
     */
    onAfterDetach(msg) {
        this.node.removeEventListener('input', this);
        this.node.removeEventListener('focus', this, true);
        this.node.removeEventListener('blur', this, true);
    }
    /**
     * A message handler invoked on an `'activate-request'` message.
     */
    onActivateRequest(msg) {
        if (this.isAttached) {
            let input = this.inputNode;
            input.focus();
            input.select();
        }
    }
    /**
     * Toggle the focused modifier based on the input node focus state.
     */
    _toggleFocused() {
        let focused = document.activeElement === this.inputNode;
        this.toggleClass('p-mod-focused', focused);
    }
}
exports.ExtensionView = ExtensionView;


/***/ }),

/***/ "OTJG":
/*!**********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeBoxIcon.js ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeBoxIcon = function TraceTypeBoxIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement('path', { fill: 'none', d: 'M0 0h46v46H0z' }),
        _react2.default.createElement('path', { fill: 'none', stroke: '#1d9bfb', d: 'M23 23v16m4 0h-8m8-16h-8m-8-12v24m4 0H7m8-24H7m28-2v24m4 0h-8m8-24h-8', strokeMiterlimit: '10', strokeWidth: '2' }),
        _react2.default.createElement('path', { fill: '#25fdfc', d: 'M8 18h6v10H8z' }),
        _react2.default.createElement('path', { d: 'M13 19v8H9v-8h4m2-2H7v12h8V17z', fill: '#1d9bfb' }),
        _react2.default.createElement('path', { fill: '#25fdfc', d: 'M20 29h6v4h-6z' }),
        _react2.default.createElement('path', { d: 'M25 30v2h-4v-2h4m2-2h-8v6h8v-6z', fill: '#1d9bfb' }),
        _react2.default.createElement('path', { fill: '#25fdfc', d: 'M32 14h6v14h-6z' }),
        _react2.default.createElement('path', { d: 'M37 15v12h-4V15h4m2-2h-8v16h8V13z', fill: '#1d9bfb' }),
        _react2.default.createElement('path', { fill: 'none', stroke: '#1d9bfb', d: 'M38 21h-6m-18 1H8', strokeMiterlimit: '10', strokeWidth: '2' })
    );
};

exports.default = TraceTypeBoxIcon;

/***/ }),

/***/ "OUGg":
/*!*********************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils/lib/splash.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
/* tslint:disable */
/**
 * The main menu token.
 */
exports.ISplashScreen = new coreutils_1.Token('@jupyterlab/apputils:ISplashScreen');


/***/ }),

/***/ "OYk8":
/*!**************************************************************************!*\
  !*** ./node_modules/react-color/lib/components/slider/SliderSwatches.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SliderSwatches = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _SliderSwatch = __webpack_require__(/*! ./SliderSwatch */ "PGcv");

var _SliderSwatch2 = _interopRequireDefault(_SliderSwatch);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var SliderSwatches = exports.SliderSwatches = function SliderSwatches(_ref) {
  var onClick = _ref.onClick,
      hsl = _ref.hsl;

  var styles = (0, _reactcss2.default)({
    'default': {
      swatches: {
        marginTop: '20px'
      },
      swatch: {
        boxSizing: 'border-box',
        width: '20%',
        paddingRight: '1px',
        float: 'left'
      },
      clear: {
        clear: 'both'
      }
    }
  });

  return _react2.default.createElement(
    'div',
    { style: styles.swatches },
    _react2.default.createElement(
      'div',
      { style: styles.swatch },
      _react2.default.createElement(_SliderSwatch2.default, {
        hsl: hsl,
        offset: '.80',
        active: Math.round(hsl.l * 100) / 100 === 0.80 && Math.round(hsl.s * 100) / 100 === 0.50,
        onClick: onClick,
        first: true
      })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.swatch },
      _react2.default.createElement(_SliderSwatch2.default, {
        hsl: hsl,
        offset: '.65',
        active: Math.round(hsl.l * 100) / 100 === 0.65 && Math.round(hsl.s * 100) / 100 === 0.50,
        onClick: onClick
      })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.swatch },
      _react2.default.createElement(_SliderSwatch2.default, {
        hsl: hsl,
        offset: '.50',
        active: Math.round(hsl.l * 100) / 100 === 0.50 && Math.round(hsl.s * 100) / 100 === 0.50,
        onClick: onClick
      })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.swatch },
      _react2.default.createElement(_SliderSwatch2.default, {
        hsl: hsl,
        offset: '.35',
        active: Math.round(hsl.l * 100) / 100 === 0.35 && Math.round(hsl.s * 100) / 100 === 0.50,
        onClick: onClick
      })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.swatch },
      _react2.default.createElement(_SliderSwatch2.default, {
        hsl: hsl,
        offset: '.20',
        active: Math.round(hsl.l * 100) / 100 === 0.20 && Math.round(hsl.s * 100) / 100 === 0.50,
        onClick: onClick,
        last: true
      })
    ),
    _react2.default.createElement('div', { style: styles.clear })
  );
};

exports.default = SliderSwatches;

/***/ }),

/***/ "OZ/i":
/*!**************************************!*\
  !*** ./node_modules/bn.js/lib/bn.js ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(module) {(function (module, exports) {
  'use strict';

  // Utils
  function assert (val, msg) {
    if (!val) throw new Error(msg || 'Assertion failed');
  }

  // Could use `inherits` module, but don't want to move from single file
  // architecture yet.
  function inherits (ctor, superCtor) {
    ctor.super_ = superCtor;
    var TempCtor = function () {};
    TempCtor.prototype = superCtor.prototype;
    ctor.prototype = new TempCtor();
    ctor.prototype.constructor = ctor;
  }

  // BN

  function BN (number, base, endian) {
    if (BN.isBN(number)) {
      return number;
    }

    this.negative = 0;
    this.words = null;
    this.length = 0;

    // Reduction context
    this.red = null;

    if (number !== null) {
      if (base === 'le' || base === 'be') {
        endian = base;
        base = 10;
      }

      this._init(number || 0, base || 10, endian || 'be');
    }
  }
  if (typeof module === 'object') {
    module.exports = BN;
  } else {
    exports.BN = BN;
  }

  BN.BN = BN;
  BN.wordSize = 26;

  var Buffer;
  try {
    Buffer = __webpack_require__(/*! buffer */ 4).Buffer;
  } catch (e) {
  }

  BN.isBN = function isBN (num) {
    if (num instanceof BN) {
      return true;
    }

    return num !== null && typeof num === 'object' &&
      num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
  };

  BN.max = function max (left, right) {
    if (left.cmp(right) > 0) return left;
    return right;
  };

  BN.min = function min (left, right) {
    if (left.cmp(right) < 0) return left;
    return right;
  };

  BN.prototype._init = function init (number, base, endian) {
    if (typeof number === 'number') {
      return this._initNumber(number, base, endian);
    }

    if (typeof number === 'object') {
      return this._initArray(number, base, endian);
    }

    if (base === 'hex') {
      base = 16;
    }
    assert(base === (base | 0) && base >= 2 && base <= 36);

    number = number.toString().replace(/\s+/g, '');
    var start = 0;
    if (number[0] === '-') {
      start++;
    }

    if (base === 16) {
      this._parseHex(number, start);
    } else {
      this._parseBase(number, base, start);
    }

    if (number[0] === '-') {
      this.negative = 1;
    }

    this.strip();

    if (endian !== 'le') return;

    this._initArray(this.toArray(), base, endian);
  };

  BN.prototype._initNumber = function _initNumber (number, base, endian) {
    if (number < 0) {
      this.negative = 1;
      number = -number;
    }
    if (number < 0x4000000) {
      this.words = [ number & 0x3ffffff ];
      this.length = 1;
    } else if (number < 0x10000000000000) {
      this.words = [
        number & 0x3ffffff,
        (number / 0x4000000) & 0x3ffffff
      ];
      this.length = 2;
    } else {
      assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
      this.words = [
        number & 0x3ffffff,
        (number / 0x4000000) & 0x3ffffff,
        1
      ];
      this.length = 3;
    }

    if (endian !== 'le') return;

    // Reverse the bytes
    this._initArray(this.toArray(), base, endian);
  };

  BN.prototype._initArray = function _initArray (number, base, endian) {
    // Perhaps a Uint8Array
    assert(typeof number.length === 'number');
    if (number.length <= 0) {
      this.words = [ 0 ];
      this.length = 1;
      return this;
    }

    this.length = Math.ceil(number.length / 3);
    this.words = new Array(this.length);
    for (var i = 0; i < this.length; i++) {
      this.words[i] = 0;
    }

    var j, w;
    var off = 0;
    if (endian === 'be') {
      for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
        w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
        this.words[j] |= (w << off) & 0x3ffffff;
        this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
        off += 24;
        if (off >= 26) {
          off -= 26;
          j++;
        }
      }
    } else if (endian === 'le') {
      for (i = 0, j = 0; i < number.length; i += 3) {
        w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
        this.words[j] |= (w << off) & 0x3ffffff;
        this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
        off += 24;
        if (off >= 26) {
          off -= 26;
          j++;
        }
      }
    }
    return this.strip();
  };

  function parseHex (str, start, end) {
    var r = 0;
    var len = Math.min(str.length, end);
    for (var i = start; i < len; i++) {
      var c = str.charCodeAt(i) - 48;

      r <<= 4;

      // 'a' - 'f'
      if (c >= 49 && c <= 54) {
        r |= c - 49 + 0xa;

      // 'A' - 'F'
      } else if (c >= 17 && c <= 22) {
        r |= c - 17 + 0xa;

      // '0' - '9'
      } else {
        r |= c & 0xf;
      }
    }
    return r;
  }

  BN.prototype._parseHex = function _parseHex (number, start) {
    // Create possibly bigger array to ensure that it fits the number
    this.length = Math.ceil((number.length - start) / 6);
    this.words = new Array(this.length);
    for (var i = 0; i < this.length; i++) {
      this.words[i] = 0;
    }

    var j, w;
    // Scan 24-bit chunks and add them to the number
    var off = 0;
    for (i = number.length - 6, j = 0; i >= start; i -= 6) {
      w = parseHex(number, i, i + 6);
      this.words[j] |= (w << off) & 0x3ffffff;
      // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
      this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
      off += 24;
      if (off >= 26) {
        off -= 26;
        j++;
      }
    }
    if (i + 6 !== start) {
      w = parseHex(number, start, i + 6);
      this.words[j] |= (w << off) & 0x3ffffff;
      this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
    }
    this.strip();
  };

  function parseBase (str, start, end, mul) {
    var r = 0;
    var len = Math.min(str.length, end);
    for (var i = start; i < len; i++) {
      var c = str.charCodeAt(i) - 48;

      r *= mul;

      // 'a'
      if (c >= 49) {
        r += c - 49 + 0xa;

      // 'A'
      } else if (c >= 17) {
        r += c - 17 + 0xa;

      // '0' - '9'
      } else {
        r += c;
      }
    }
    return r;
  }

  BN.prototype._parseBase = function _parseBase (number, base, start) {
    // Initialize as zero
    this.words = [ 0 ];
    this.length = 1;

    // Find length of limb in base
    for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
      limbLen++;
    }
    limbLen--;
    limbPow = (limbPow / base) | 0;

    var total = number.length - start;
    var mod = total % limbLen;
    var end = Math.min(total, total - mod) + start;

    var word = 0;
    for (var i = start; i < end; i += limbLen) {
      word = parseBase(number, i, i + limbLen, base);

      this.imuln(limbPow);
      if (this.words[0] + word < 0x4000000) {
        this.words[0] += word;
      } else {
        this._iaddn(word);
      }
    }

    if (mod !== 0) {
      var pow = 1;
      word = parseBase(number, i, number.length, base);

      for (i = 0; i < mod; i++) {
        pow *= base;
      }

      this.imuln(pow);
      if (this.words[0] + word < 0x4000000) {
        this.words[0] += word;
      } else {
        this._iaddn(word);
      }
    }
  };

  BN.prototype.copy = function copy (dest) {
    dest.words = new Array(this.length);
    for (var i = 0; i < this.length; i++) {
      dest.words[i] = this.words[i];
    }
    dest.length = this.length;
    dest.negative = this.negative;
    dest.red = this.red;
  };

  BN.prototype.clone = function clone () {
    var r = new BN(null);
    this.copy(r);
    return r;
  };

  BN.prototype._expand = function _expand (size) {
    while (this.length < size) {
      this.words[this.length++] = 0;
    }
    return this;
  };

  // Remove leading `0` from `this`
  BN.prototype.strip = function strip () {
    while (this.length > 1 && this.words[this.length - 1] === 0) {
      this.length--;
    }
    return this._normSign();
  };

  BN.prototype._normSign = function _normSign () {
    // -0 = 0
    if (this.length === 1 && this.words[0] === 0) {
      this.negative = 0;
    }
    return this;
  };

  BN.prototype.inspect = function inspect () {
    return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
  };

  /*

  var zeros = [];
  var groupSizes = [];
  var groupBases = [];

  var s = '';
  var i = -1;
  while (++i < BN.wordSize) {
    zeros[i] = s;
    s += '0';
  }
  groupSizes[0] = 0;
  groupSizes[1] = 0;
  groupBases[0] = 0;
  groupBases[1] = 0;
  var base = 2 - 1;
  while (++base < 36 + 1) {
    var groupSize = 0;
    var groupBase = 1;
    while (groupBase < (1 << BN.wordSize) / base) {
      groupBase *= base;
      groupSize += 1;
    }
    groupSizes[base] = groupSize;
    groupBases[base] = groupBase;
  }

  */

  var zeros = [
    '',
    '0',
    '00',
    '000',
    '0000',
    '00000',
    '000000',
    '0000000',
    '00000000',
    '000000000',
    '0000000000',
    '00000000000',
    '000000000000',
    '0000000000000',
    '00000000000000',
    '000000000000000',
    '0000000000000000',
    '00000000000000000',
    '000000000000000000',
    '0000000000000000000',
    '00000000000000000000',
    '000000000000000000000',
    '0000000000000000000000',
    '00000000000000000000000',
    '000000000000000000000000',
    '0000000000000000000000000'
  ];

  var groupSizes = [
    0, 0,
    25, 16, 12, 11, 10, 9, 8,
    8, 7, 7, 7, 7, 6, 6,
    6, 6, 6, 6, 6, 5, 5,
    5, 5, 5, 5, 5, 5, 5,
    5, 5, 5, 5, 5, 5, 5
  ];

  var groupBases = [
    0, 0,
    33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
    43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
    16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
    6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
    24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
  ];

  BN.prototype.toString = function toString (base, padding) {
    base = base || 10;
    padding = padding | 0 || 1;

    var out;
    if (base === 16 || base === 'hex') {
      out = '';
      var off = 0;
      var carry = 0;
      for (var i = 0; i < this.length; i++) {
        var w = this.words[i];
        var word = (((w << off) | carry) & 0xffffff).toString(16);
        carry = (w >>> (24 - off)) & 0xffffff;
        if (carry !== 0 || i !== this.length - 1) {
          out = zeros[6 - word.length] + word + out;
        } else {
          out = word + out;
        }
        off += 2;
        if (off >= 26) {
          off -= 26;
          i--;
        }
      }
      if (carry !== 0) {
        out = carry.toString(16) + out;
      }
      while (out.length % padding !== 0) {
        out = '0' + out;
      }
      if (this.negative !== 0) {
        out = '-' + out;
      }
      return out;
    }

    if (base === (base | 0) && base >= 2 && base <= 36) {
      // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
      var groupSize = groupSizes[base];
      // var groupBase = Math.pow(base, groupSize);
      var groupBase = groupBases[base];
      out = '';
      var c = this.clone();
      c.negative = 0;
      while (!c.isZero()) {
        var r = c.modn(groupBase).toString(base);
        c = c.idivn(groupBase);

        if (!c.isZero()) {
          out = zeros[groupSize - r.length] + r + out;
        } else {
          out = r + out;
        }
      }
      if (this.isZero()) {
        out = '0' + out;
      }
      while (out.length % padding !== 0) {
        out = '0' + out;
      }
      if (this.negative !== 0) {
        out = '-' + out;
      }
      return out;
    }

    assert(false, 'Base should be between 2 and 36');
  };

  BN.prototype.toNumber = function toNumber () {
    var ret = this.words[0];
    if (this.length === 2) {
      ret += this.words[1] * 0x4000000;
    } else if (this.length === 3 && this.words[2] === 0x01) {
      // NOTE: at this stage it is known that the top bit is set
      ret += 0x10000000000000 + (this.words[1] * 0x4000000);
    } else if (this.length > 2) {
      assert(false, 'Number can only safely store up to 53 bits');
    }
    return (this.negative !== 0) ? -ret : ret;
  };

  BN.prototype.toJSON = function toJSON () {
    return this.toString(16);
  };

  BN.prototype.toBuffer = function toBuffer (endian, length) {
    assert(typeof Buffer !== 'undefined');
    return this.toArrayLike(Buffer, endian, length);
  };

  BN.prototype.toArray = function toArray (endian, length) {
    return this.toArrayLike(Array, endian, length);
  };

  BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
    var byteLength = this.byteLength();
    var reqLength = length || Math.max(1, byteLength);
    assert(byteLength <= reqLength, 'byte array longer than desired length');
    assert(reqLength > 0, 'Requested array length <= 0');

    this.strip();
    var littleEndian = endian === 'le';
    var res = new ArrayType(reqLength);

    var b, i;
    var q = this.clone();
    if (!littleEndian) {
      // Assume big-endian
      for (i = 0; i < reqLength - byteLength; i++) {
        res[i] = 0;
      }

      for (i = 0; !q.isZero(); i++) {
        b = q.andln(0xff);
        q.iushrn(8);

        res[reqLength - i - 1] = b;
      }
    } else {
      for (i = 0; !q.isZero(); i++) {
        b = q.andln(0xff);
        q.iushrn(8);

        res[i] = b;
      }

      for (; i < reqLength; i++) {
        res[i] = 0;
      }
    }

    return res;
  };

  if (Math.clz32) {
    BN.prototype._countBits = function _countBits (w) {
      return 32 - Math.clz32(w);
    };
  } else {
    BN.prototype._countBits = function _countBits (w) {
      var t = w;
      var r = 0;
      if (t >= 0x1000) {
        r += 13;
        t >>>= 13;
      }
      if (t >= 0x40) {
        r += 7;
        t >>>= 7;
      }
      if (t >= 0x8) {
        r += 4;
        t >>>= 4;
      }
      if (t >= 0x02) {
        r += 2;
        t >>>= 2;
      }
      return r + t;
    };
  }

  BN.prototype._zeroBits = function _zeroBits (w) {
    // Short-cut
    if (w === 0) return 26;

    var t = w;
    var r = 0;
    if ((t & 0x1fff) === 0) {
      r += 13;
      t >>>= 13;
    }
    if ((t & 0x7f) === 0) {
      r += 7;
      t >>>= 7;
    }
    if ((t & 0xf) === 0) {
      r += 4;
      t >>>= 4;
    }
    if ((t & 0x3) === 0) {
      r += 2;
      t >>>= 2;
    }
    if ((t & 0x1) === 0) {
      r++;
    }
    return r;
  };

  // Return number of used bits in a BN
  BN.prototype.bitLength = function bitLength () {
    var w = this.words[this.length - 1];
    var hi = this._countBits(w);
    return (this.length - 1) * 26 + hi;
  };

  function toBitArray (num) {
    var w = new Array(num.bitLength());

    for (var bit = 0; bit < w.length; bit++) {
      var off = (bit / 26) | 0;
      var wbit = bit % 26;

      w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
    }

    return w;
  }

  // Number of trailing zero bits
  BN.prototype.zeroBits = function zeroBits () {
    if (this.isZero()) return 0;

    var r = 0;
    for (var i = 0; i < this.length; i++) {
      var b = this._zeroBits(this.words[i]);
      r += b;
      if (b !== 26) break;
    }
    return r;
  };

  BN.prototype.byteLength = function byteLength () {
    return Math.ceil(this.bitLength() / 8);
  };

  BN.prototype.toTwos = function toTwos (width) {
    if (this.negative !== 0) {
      return this.abs().inotn(width).iaddn(1);
    }
    return this.clone();
  };

  BN.prototype.fromTwos = function fromTwos (width) {
    if (this.testn(width - 1)) {
      return this.notn(width).iaddn(1).ineg();
    }
    return this.clone();
  };

  BN.prototype.isNeg = function isNeg () {
    return this.negative !== 0;
  };

  // Return negative clone of `this`
  BN.prototype.neg = function neg () {
    return this.clone().ineg();
  };

  BN.prototype.ineg = function ineg () {
    if (!this.isZero()) {
      this.negative ^= 1;
    }

    return this;
  };

  // Or `num` with `this` in-place
  BN.prototype.iuor = function iuor (num) {
    while (this.length < num.length) {
      this.words[this.length++] = 0;
    }

    for (var i = 0; i < num.length; i++) {
      this.words[i] = this.words[i] | num.words[i];
    }

    return this.strip();
  };

  BN.prototype.ior = function ior (num) {
    assert((this.negative | num.negative) === 0);
    return this.iuor(num);
  };

  // Or `num` with `this`
  BN.prototype.or = function or (num) {
    if (this.length > num.length) return this.clone().ior(num);
    return num.clone().ior(this);
  };

  BN.prototype.uor = function uor (num) {
    if (this.length > num.length) return this.clone().iuor(num);
    return num.clone().iuor(this);
  };

  // And `num` with `this` in-place
  BN.prototype.iuand = function iuand (num) {
    // b = min-length(num, this)
    var b;
    if (this.length > num.length) {
      b = num;
    } else {
      b = this;
    }

    for (var i = 0; i < b.length; i++) {
      this.words[i] = this.words[i] & num.words[i];
    }

    this.length = b.length;

    return this.strip();
  };

  BN.prototype.iand = function iand (num) {
    assert((this.negative | num.negative) === 0);
    return this.iuand(num);
  };

  // And `num` with `this`
  BN.prototype.and = function and (num) {
    if (this.length > num.length) return this.clone().iand(num);
    return num.clone().iand(this);
  };

  BN.prototype.uand = function uand (num) {
    if (this.length > num.length) return this.clone().iuand(num);
    return num.clone().iuand(this);
  };

  // Xor `num` with `this` in-place
  BN.prototype.iuxor = function iuxor (num) {
    // a.length > b.length
    var a;
    var b;
    if (this.length > num.length) {
      a = this;
      b = num;
    } else {
      a = num;
      b = this;
    }

    for (var i = 0; i < b.length; i++) {
      this.words[i] = a.words[i] ^ b.words[i];
    }

    if (this !== a) {
      for (; i < a.length; i++) {
        this.words[i] = a.words[i];
      }
    }

    this.length = a.length;

    return this.strip();
  };

  BN.prototype.ixor = function ixor (num) {
    assert((this.negative | num.negative) === 0);
    return this.iuxor(num);
  };

  // Xor `num` with `this`
  BN.prototype.xor = function xor (num) {
    if (this.length > num.length) return this.clone().ixor(num);
    return num.clone().ixor(this);
  };

  BN.prototype.uxor = function uxor (num) {
    if (this.length > num.length) return this.clone().iuxor(num);
    return num.clone().iuxor(this);
  };

  // Not ``this`` with ``width`` bitwidth
  BN.prototype.inotn = function inotn (width) {
    assert(typeof width === 'number' && width >= 0);

    var bytesNeeded = Math.ceil(width / 26) | 0;
    var bitsLeft = width % 26;

    // Extend the buffer with leading zeroes
    this._expand(bytesNeeded);

    if (bitsLeft > 0) {
      bytesNeeded--;
    }

    // Handle complete words
    for (var i = 0; i < bytesNeeded; i++) {
      this.words[i] = ~this.words[i] & 0x3ffffff;
    }

    // Handle the residue
    if (bitsLeft > 0) {
      this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
    }

    // And remove leading zeroes
    return this.strip();
  };

  BN.prototype.notn = function notn (width) {
    return this.clone().inotn(width);
  };

  // Set `bit` of `this`
  BN.prototype.setn = function setn (bit, val) {
    assert(typeof bit === 'number' && bit >= 0);

    var off = (bit / 26) | 0;
    var wbit = bit % 26;

    this._expand(off + 1);

    if (val) {
      this.words[off] = this.words[off] | (1 << wbit);
    } else {
      this.words[off] = this.words[off] & ~(1 << wbit);
    }

    return this.strip();
  };

  // Add `num` to `this` in-place
  BN.prototype.iadd = function iadd (num) {
    var r;

    // negative + positive
    if (this.negative !== 0 && num.negative === 0) {
      this.negative = 0;
      r = this.isub(num);
      this.negative ^= 1;
      return this._normSign();

    // positive + negative
    } else if (this.negative === 0 && num.negative !== 0) {
      num.negative = 0;
      r = this.isub(num);
      num.negative = 1;
      return r._normSign();
    }

    // a.length > b.length
    var a, b;
    if (this.length > num.length) {
      a = this;
      b = num;
    } else {
      a = num;
      b = this;
    }

    var carry = 0;
    for (var i = 0; i < b.length; i++) {
      r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
      this.words[i] = r & 0x3ffffff;
      carry = r >>> 26;
    }
    for (; carry !== 0 && i < a.length; i++) {
      r = (a.words[i] | 0) + carry;
      this.words[i] = r & 0x3ffffff;
      carry = r >>> 26;
    }

    this.length = a.length;
    if (carry !== 0) {
      this.words[this.length] = carry;
      this.length++;
    // Copy the rest of the words
    } else if (a !== this) {
      for (; i < a.length; i++) {
        this.words[i] = a.words[i];
      }
    }

    return this;
  };

  // Add `num` to `this`
  BN.prototype.add = function add (num) {
    var res;
    if (num.negative !== 0 && this.negative === 0) {
      num.negative = 0;
      res = this.sub(num);
      num.negative ^= 1;
      return res;
    } else if (num.negative === 0 && this.negative !== 0) {
      this.negative = 0;
      res = num.sub(this);
      this.negative = 1;
      return res;
    }

    if (this.length > num.length) return this.clone().iadd(num);

    return num.clone().iadd(this);
  };

  // Subtract `num` from `this` in-place
  BN.prototype.isub = function isub (num) {
    // this - (-num) = this + num
    if (num.negative !== 0) {
      num.negative = 0;
      var r = this.iadd(num);
      num.negative = 1;
      return r._normSign();

    // -this - num = -(this + num)
    } else if (this.negative !== 0) {
      this.negative = 0;
      this.iadd(num);
      this.negative = 1;
      return this._normSign();
    }

    // At this point both numbers are positive
    var cmp = this.cmp(num);

    // Optimization - zeroify
    if (cmp === 0) {
      this.negative = 0;
      this.length = 1;
      this.words[0] = 0;
      return this;
    }

    // a > b
    var a, b;
    if (cmp > 0) {
      a = this;
      b = num;
    } else {
      a = num;
      b = this;
    }

    var carry = 0;
    for (var i = 0; i < b.length; i++) {
      r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
      carry = r >> 26;
      this.words[i] = r & 0x3ffffff;
    }
    for (; carry !== 0 && i < a.length; i++) {
      r = (a.words[i] | 0) + carry;
      carry = r >> 26;
      this.words[i] = r & 0x3ffffff;
    }

    // Copy rest of the words
    if (carry === 0 && i < a.length && a !== this) {
      for (; i < a.length; i++) {
        this.words[i] = a.words[i];
      }
    }

    this.length = Math.max(this.length, i);

    if (a !== this) {
      this.negative = 1;
    }

    return this.strip();
  };

  // Subtract `num` from `this`
  BN.prototype.sub = function sub (num) {
    return this.clone().isub(num);
  };

  function smallMulTo (self, num, out) {
    out.negative = num.negative ^ self.negative;
    var len = (self.length + num.length) | 0;
    out.length = len;
    len = (len - 1) | 0;

    // Peel one iteration (compiler can't do it, because of code complexity)
    var a = self.words[0] | 0;
    var b = num.words[0] | 0;
    var r = a * b;

    var lo = r & 0x3ffffff;
    var carry = (r / 0x4000000) | 0;
    out.words[0] = lo;

    for (var k = 1; k < len; k++) {
      // Sum all words with the same `i + j = k` and accumulate `ncarry`,
      // note that ncarry could be >= 0x3ffffff
      var ncarry = carry >>> 26;
      var rword = carry & 0x3ffffff;
      var maxJ = Math.min(k, num.length - 1);
      for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
        var i = (k - j) | 0;
        a = self.words[i] | 0;
        b = num.words[j] | 0;
        r = a * b + rword;
        ncarry += (r / 0x4000000) | 0;
        rword = r & 0x3ffffff;
      }
      out.words[k] = rword | 0;
      carry = ncarry | 0;
    }
    if (carry !== 0) {
      out.words[k] = carry | 0;
    } else {
      out.length--;
    }

    return out.strip();
  }

  // TODO(indutny): it may be reasonable to omit it for users who don't need
  // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
  // multiplication (like elliptic secp256k1).
  var comb10MulTo = function comb10MulTo (self, num, out) {
    var a = self.words;
    var b = num.words;
    var o = out.words;
    var c = 0;
    var lo;
    var mid;
    var hi;
    var a0 = a[0] | 0;
    var al0 = a0 & 0x1fff;
    var ah0 = a0 >>> 13;
    var a1 = a[1] | 0;
    var al1 = a1 & 0x1fff;
    var ah1 = a1 >>> 13;
    var a2 = a[2] | 0;
    var al2 = a2 & 0x1fff;
    var ah2 = a2 >>> 13;
    var a3 = a[3] | 0;
    var al3 = a3 & 0x1fff;
    var ah3 = a3 >>> 13;
    var a4 = a[4] | 0;
    var al4 = a4 & 0x1fff;
    var ah4 = a4 >>> 13;
    var a5 = a[5] | 0;
    var al5 = a5 & 0x1fff;
    var ah5 = a5 >>> 13;
    var a6 = a[6] | 0;
    var al6 = a6 & 0x1fff;
    var ah6 = a6 >>> 13;
    var a7 = a[7] | 0;
    var al7 = a7 & 0x1fff;
    var ah7 = a7 >>> 13;
    var a8 = a[8] | 0;
    var al8 = a8 & 0x1fff;
    var ah8 = a8 >>> 13;
    var a9 = a[9] | 0;
    var al9 = a9 & 0x1fff;
    var ah9 = a9 >>> 13;
    var b0 = b[0] | 0;
    var bl0 = b0 & 0x1fff;
    var bh0 = b0 >>> 13;
    var b1 = b[1] | 0;
    var bl1 = b1 & 0x1fff;
    var bh1 = b1 >>> 13;
    var b2 = b[2] | 0;
    var bl2 = b2 & 0x1fff;
    var bh2 = b2 >>> 13;
    var b3 = b[3] | 0;
    var bl3 = b3 & 0x1fff;
    var bh3 = b3 >>> 13;
    var b4 = b[4] | 0;
    var bl4 = b4 & 0x1fff;
    var bh4 = b4 >>> 13;
    var b5 = b[5] | 0;
    var bl5 = b5 & 0x1fff;
    var bh5 = b5 >>> 13;
    var b6 = b[6] | 0;
    var bl6 = b6 & 0x1fff;
    var bh6 = b6 >>> 13;
    var b7 = b[7] | 0;
    var bl7 = b7 & 0x1fff;
    var bh7 = b7 >>> 13;
    var b8 = b[8] | 0;
    var bl8 = b8 & 0x1fff;
    var bh8 = b8 >>> 13;
    var b9 = b[9] | 0;
    var bl9 = b9 & 0x1fff;
    var bh9 = b9 >>> 13;

    out.negative = self.negative ^ num.negative;
    out.length = 19;
    /* k = 0 */
    lo = Math.imul(al0, bl0);
    mid = Math.imul(al0, bh0);
    mid = (mid + Math.imul(ah0, bl0)) | 0;
    hi = Math.imul(ah0, bh0);
    var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
    w0 &= 0x3ffffff;
    /* k = 1 */
    lo = Math.imul(al1, bl0);
    mid = Math.imul(al1, bh0);
    mid = (mid + Math.imul(ah1, bl0)) | 0;
    hi = Math.imul(ah1, bh0);
    lo = (lo + Math.imul(al0, bl1)) | 0;
    mid = (mid + Math.imul(al0, bh1)) | 0;
    mid = (mid + Math.imul(ah0, bl1)) | 0;
    hi = (hi + Math.imul(ah0, bh1)) | 0;
    var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
    w1 &= 0x3ffffff;
    /* k = 2 */
    lo = Math.imul(al2, bl0);
    mid = Math.imul(al2, bh0);
    mid = (mid + Math.imul(ah2, bl0)) | 0;
    hi = Math.imul(ah2, bh0);
    lo = (lo + Math.imul(al1, bl1)) | 0;
    mid = (mid + Math.imul(al1, bh1)) | 0;
    mid = (mid + Math.imul(ah1, bl1)) | 0;
    hi = (hi + Math.imul(ah1, bh1)) | 0;
    lo = (lo + Math.imul(al0, bl2)) | 0;
    mid = (mid + Math.imul(al0, bh2)) | 0;
    mid = (mid + Math.imul(ah0, bl2)) | 0;
    hi = (hi + Math.imul(ah0, bh2)) | 0;
    var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
    w2 &= 0x3ffffff;
    /* k = 3 */
    lo = Math.imul(al3, bl0);
    mid = Math.imul(al3, bh0);
    mid = (mid + Math.imul(ah3, bl0)) | 0;
    hi = Math.imul(ah3, bh0);
    lo = (lo + Math.imul(al2, bl1)) | 0;
    mid = (mid + Math.imul(al2, bh1)) | 0;
    mid = (mid + Math.imul(ah2, bl1)) | 0;
    hi = (hi + Math.imul(ah2, bh1)) | 0;
    lo = (lo + Math.imul(al1, bl2)) | 0;
    mid = (mid + Math.imul(al1, bh2)) | 0;
    mid = (mid + Math.imul(ah1, bl2)) | 0;
    hi = (hi + Math.imul(ah1, bh2)) | 0;
    lo = (lo + Math.imul(al0, bl3)) | 0;
    mid = (mid + Math.imul(al0, bh3)) | 0;
    mid = (mid + Math.imul(ah0, bl3)) | 0;
    hi = (hi + Math.imul(ah0, bh3)) | 0;
    var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
    w3 &= 0x3ffffff;
    /* k = 4 */
    lo = Math.imul(al4, bl0);
    mid = Math.imul(al4, bh0);
    mid = (mid + Math.imul(ah4, bl0)) | 0;
    hi = Math.imul(ah4, bh0);
    lo = (lo + Math.imul(al3, bl1)) | 0;
    mid = (mid + Math.imul(al3, bh1)) | 0;
    mid = (mid + Math.imul(ah3, bl1)) | 0;
    hi = (hi + Math.imul(ah3, bh1)) | 0;
    lo = (lo + Math.imul(al2, bl2)) | 0;
    mid = (mid + Math.imul(al2, bh2)) | 0;
    mid = (mid + Math.imul(ah2, bl2)) | 0;
    hi = (hi + Math.imul(ah2, bh2)) | 0;
    lo = (lo + Math.imul(al1, bl3)) | 0;
    mid = (mid + Math.imul(al1, bh3)) | 0;
    mid = (mid + Math.imul(ah1, bl3)) | 0;
    hi = (hi + Math.imul(ah1, bh3)) | 0;
    lo = (lo + Math.imul(al0, bl4)) | 0;
    mid = (mid + Math.imul(al0, bh4)) | 0;
    mid = (mid + Math.imul(ah0, bl4)) | 0;
    hi = (hi + Math.imul(ah0, bh4)) | 0;
    var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
    w4 &= 0x3ffffff;
    /* k = 5 */
    lo = Math.imul(al5, bl0);
    mid = Math.imul(al5, bh0);
    mid = (mid + Math.imul(ah5, bl0)) | 0;
    hi = Math.imul(ah5, bh0);
    lo = (lo + Math.imul(al4, bl1)) | 0;
    mid = (mid + Math.imul(al4, bh1)) | 0;
    mid = (mid + Math.imul(ah4, bl1)) | 0;
    hi = (hi + Math.imul(ah4, bh1)) | 0;
    lo = (lo + Math.imul(al3, bl2)) | 0;
    mid = (mid + Math.imul(al3, bh2)) | 0;
    mid = (mid + Math.imul(ah3, bl2)) | 0;
    hi = (hi + Math.imul(ah3, bh2)) | 0;
    lo = (lo + Math.imul(al2, bl3)) | 0;
    mid = (mid + Math.imul(al2, bh3)) | 0;
    mid = (mid + Math.imul(ah2, bl3)) | 0;
    hi = (hi + Math.imul(ah2, bh3)) | 0;
    lo = (lo + Math.imul(al1, bl4)) | 0;
    mid = (mid + Math.imul(al1, bh4)) | 0;
    mid = (mid + Math.imul(ah1, bl4)) | 0;
    hi = (hi + Math.imul(ah1, bh4)) | 0;
    lo = (lo + Math.imul(al0, bl5)) | 0;
    mid = (mid + Math.imul(al0, bh5)) | 0;
    mid = (mid + Math.imul(ah0, bl5)) | 0;
    hi = (hi + Math.imul(ah0, bh5)) | 0;
    var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
    w5 &= 0x3ffffff;
    /* k = 6 */
    lo = Math.imul(al6, bl0);
    mid = Math.imul(al6, bh0);
    mid = (mid + Math.imul(ah6, bl0)) | 0;
    hi = Math.imul(ah6, bh0);
    lo = (lo + Math.imul(al5, bl1)) | 0;
    mid = (mid + Math.imul(al5, bh1)) | 0;
    mid = (mid + Math.imul(ah5, bl1)) | 0;
    hi = (hi + Math.imul(ah5, bh1)) | 0;
    lo = (lo + Math.imul(al4, bl2)) | 0;
    mid = (mid + Math.imul(al4, bh2)) | 0;
    mid = (mid + Math.imul(ah4, bl2)) | 0;
    hi = (hi + Math.imul(ah4, bh2)) | 0;
    lo = (lo + Math.imul(al3, bl3)) | 0;
    mid = (mid + Math.imul(al3, bh3)) | 0;
    mid = (mid + Math.imul(ah3, bl3)) | 0;
    hi = (hi + Math.imul(ah3, bh3)) | 0;
    lo = (lo + Math.imul(al2, bl4)) | 0;
    mid = (mid + Math.imul(al2, bh4)) | 0;
    mid = (mid + Math.imul(ah2, bl4)) | 0;
    hi = (hi + Math.imul(ah2, bh4)) | 0;
    lo = (lo + Math.imul(al1, bl5)) | 0;
    mid = (mid + Math.imul(al1, bh5)) | 0;
    mid = (mid + Math.imul(ah1, bl5)) | 0;
    hi = (hi + Math.imul(ah1, bh5)) | 0;
    lo = (lo + Math.imul(al0, bl6)) | 0;
    mid = (mid + Math.imul(al0, bh6)) | 0;
    mid = (mid + Math.imul(ah0, bl6)) | 0;
    hi = (hi + Math.imul(ah0, bh6)) | 0;
    var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
    w6 &= 0x3ffffff;
    /* k = 7 */
    lo = Math.imul(al7, bl0);
    mid = Math.imul(al7, bh0);
    mid = (mid + Math.imul(ah7, bl0)) | 0;
    hi = Math.imul(ah7, bh0);
    lo = (lo + Math.imul(al6, bl1)) | 0;
    mid = (mid + Math.imul(al6, bh1)) | 0;
    mid = (mid + Math.imul(ah6, bl1)) | 0;
    hi = (hi + Math.imul(ah6, bh1)) | 0;
    lo = (lo + Math.imul(al5, bl2)) | 0;
    mid = (mid + Math.imul(al5, bh2)) | 0;
    mid = (mid + Math.imul(ah5, bl2)) | 0;
    hi = (hi + Math.imul(ah5, bh2)) | 0;
    lo = (lo + Math.imul(al4, bl3)) | 0;
    mid = (mid + Math.imul(al4, bh3)) | 0;
    mid = (mid + Math.imul(ah4, bl3)) | 0;
    hi = (hi + Math.imul(ah4, bh3)) | 0;
    lo = (lo + Math.imul(al3, bl4)) | 0;
    mid = (mid + Math.imul(al3, bh4)) | 0;
    mid = (mid + Math.imul(ah3, bl4)) | 0;
    hi = (hi + Math.imul(ah3, bh4)) | 0;
    lo = (lo + Math.imul(al2, bl5)) | 0;
    mid = (mid + Math.imul(al2, bh5)) | 0;
    mid = (mid + Math.imul(ah2, bl5)) | 0;
    hi = (hi + Math.imul(ah2, bh5)) | 0;
    lo = (lo + Math.imul(al1, bl6)) | 0;
    mid = (mid + Math.imul(al1, bh6)) | 0;
    mid = (mid + Math.imul(ah1, bl6)) | 0;
    hi = (hi + Math.imul(ah1, bh6)) | 0;
    lo = (lo + Math.imul(al0, bl7)) | 0;
    mid = (mid + Math.imul(al0, bh7)) | 0;
    mid = (mid + Math.imul(ah0, bl7)) | 0;
    hi = (hi + Math.imul(ah0, bh7)) | 0;
    var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
    w7 &= 0x3ffffff;
    /* k = 8 */
    lo = Math.imul(al8, bl0);
    mid = Math.imul(al8, bh0);
    mid = (mid + Math.imul(ah8, bl0)) | 0;
    hi = Math.imul(ah8, bh0);
    lo = (lo + Math.imul(al7, bl1)) | 0;
    mid = (mid + Math.imul(al7, bh1)) | 0;
    mid = (mid + Math.imul(ah7, bl1)) | 0;
    hi = (hi + Math.imul(ah7, bh1)) | 0;
    lo = (lo + Math.imul(al6, bl2)) | 0;
    mid = (mid + Math.imul(al6, bh2)) | 0;
    mid = (mid + Math.imul(ah6, bl2)) | 0;
    hi = (hi + Math.imul(ah6, bh2)) | 0;
    lo = (lo + Math.imul(al5, bl3)) | 0;
    mid = (mid + Math.imul(al5, bh3)) | 0;
    mid = (mid + Math.imul(ah5, bl3)) | 0;
    hi = (hi + Math.imul(ah5, bh3)) | 0;
    lo = (lo + Math.imul(al4, bl4)) | 0;
    mid = (mid + Math.imul(al4, bh4)) | 0;
    mid = (mid + Math.imul(ah4, bl4)) | 0;
    hi = (hi + Math.imul(ah4, bh4)) | 0;
    lo = (lo + Math.imul(al3, bl5)) | 0;
    mid = (mid + Math.imul(al3, bh5)) | 0;
    mid = (mid + Math.imul(ah3, bl5)) | 0;
    hi = (hi + Math.imul(ah3, bh5)) | 0;
    lo = (lo + Math.imul(al2, bl6)) | 0;
    mid = (mid + Math.imul(al2, bh6)) | 0;
    mid = (mid + Math.imul(ah2, bl6)) | 0;
    hi = (hi + Math.imul(ah2, bh6)) | 0;
    lo = (lo + Math.imul(al1, bl7)) | 0;
    mid = (mid + Math.imul(al1, bh7)) | 0;
    mid = (mid + Math.imul(ah1, bl7)) | 0;
    hi = (hi + Math.imul(ah1, bh7)) | 0;
    lo = (lo + Math.imul(al0, bl8)) | 0;
    mid = (mid + Math.imul(al0, bh8)) | 0;
    mid = (mid + Math.imul(ah0, bl8)) | 0;
    hi = (hi + Math.imul(ah0, bh8)) | 0;
    var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
    w8 &= 0x3ffffff;
    /* k = 9 */
    lo = Math.imul(al9, bl0);
    mid = Math.imul(al9, bh0);
    mid = (mid + Math.imul(ah9, bl0)) | 0;
    hi = Math.imul(ah9, bh0);
    lo = (lo + Math.imul(al8, bl1)) | 0;
    mid = (mid + Math.imul(al8, bh1)) | 0;
    mid = (mid + Math.imul(ah8, bl1)) | 0;
    hi = (hi + Math.imul(ah8, bh1)) | 0;
    lo = (lo + Math.imul(al7, bl2)) | 0;
    mid = (mid + Math.imul(al7, bh2)) | 0;
    mid = (mid + Math.imul(ah7, bl2)) | 0;
    hi = (hi + Math.imul(ah7, bh2)) | 0;
    lo = (lo + Math.imul(al6, bl3)) | 0;
    mid = (mid + Math.imul(al6, bh3)) | 0;
    mid = (mid + Math.imul(ah6, bl3)) | 0;
    hi = (hi + Math.imul(ah6, bh3)) | 0;
    lo = (lo + Math.imul(al5, bl4)) | 0;
    mid = (mid + Math.imul(al5, bh4)) | 0;
    mid = (mid + Math.imul(ah5, bl4)) | 0;
    hi = (hi + Math.imul(ah5, bh4)) | 0;
    lo = (lo + Math.imul(al4, bl5)) | 0;
    mid = (mid + Math.imul(al4, bh5)) | 0;
    mid = (mid + Math.imul(ah4, bl5)) | 0;
    hi = (hi + Math.imul(ah4, bh5)) | 0;
    lo = (lo + Math.imul(al3, bl6)) | 0;
    mid = (mid + Math.imul(al3, bh6)) | 0;
    mid = (mid + Math.imul(ah3, bl6)) | 0;
    hi = (hi + Math.imul(ah3, bh6)) | 0;
    lo = (lo + Math.imul(al2, bl7)) | 0;
    mid = (mid + Math.imul(al2, bh7)) | 0;
    mid = (mid + Math.imul(ah2, bl7)) | 0;
    hi = (hi + Math.imul(ah2, bh7)) | 0;
    lo = (lo + Math.imul(al1, bl8)) | 0;
    mid = (mid + Math.imul(al1, bh8)) | 0;
    mid = (mid + Math.imul(ah1, bl8)) | 0;
    hi = (hi + Math.imul(ah1, bh8)) | 0;
    lo = (lo + Math.imul(al0, bl9)) | 0;
    mid = (mid + Math.imul(al0, bh9)) | 0;
    mid = (mid + Math.imul(ah0, bl9)) | 0;
    hi = (hi + Math.imul(ah0, bh9)) | 0;
    var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
    w9 &= 0x3ffffff;
    /* k = 10 */
    lo = Math.imul(al9, bl1);
    mid = Math.imul(al9, bh1);
    mid = (mid + Math.imul(ah9, bl1)) | 0;
    hi = Math.imul(ah9, bh1);
    lo = (lo + Math.imul(al8, bl2)) | 0;
    mid = (mid + Math.imul(al8, bh2)) | 0;
    mid = (mid + Math.imul(ah8, bl2)) | 0;
    hi = (hi + Math.imul(ah8, bh2)) | 0;
    lo = (lo + Math.imul(al7, bl3)) | 0;
    mid = (mid + Math.imul(al7, bh3)) | 0;
    mid = (mid + Math.imul(ah7, bl3)) | 0;
    hi = (hi + Math.imul(ah7, bh3)) | 0;
    lo = (lo + Math.imul(al6, bl4)) | 0;
    mid = (mid + Math.imul(al6, bh4)) | 0;
    mid = (mid + Math.imul(ah6, bl4)) | 0;
    hi = (hi + Math.imul(ah6, bh4)) | 0;
    lo = (lo + Math.imul(al5, bl5)) | 0;
    mid = (mid + Math.imul(al5, bh5)) | 0;
    mid = (mid + Math.imul(ah5, bl5)) | 0;
    hi = (hi + Math.imul(ah5, bh5)) | 0;
    lo = (lo + Math.imul(al4, bl6)) | 0;
    mid = (mid + Math.imul(al4, bh6)) | 0;
    mid = (mid + Math.imul(ah4, bl6)) | 0;
    hi = (hi + Math.imul(ah4, bh6)) | 0;
    lo = (lo + Math.imul(al3, bl7)) | 0;
    mid = (mid + Math.imul(al3, bh7)) | 0;
    mid = (mid + Math.imul(ah3, bl7)) | 0;
    hi = (hi + Math.imul(ah3, bh7)) | 0;
    lo = (lo + Math.imul(al2, bl8)) | 0;
    mid = (mid + Math.imul(al2, bh8)) | 0;
    mid = (mid + Math.imul(ah2, bl8)) | 0;
    hi = (hi + Math.imul(ah2, bh8)) | 0;
    lo = (lo + Math.imul(al1, bl9)) | 0;
    mid = (mid + Math.imul(al1, bh9)) | 0;
    mid = (mid + Math.imul(ah1, bl9)) | 0;
    hi = (hi + Math.imul(ah1, bh9)) | 0;
    var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
    w10 &= 0x3ffffff;
    /* k = 11 */
    lo = Math.imul(al9, bl2);
    mid = Math.imul(al9, bh2);
    mid = (mid + Math.imul(ah9, bl2)) | 0;
    hi = Math.imul(ah9, bh2);
    lo = (lo + Math.imul(al8, bl3)) | 0;
    mid = (mid + Math.imul(al8, bh3)) | 0;
    mid = (mid + Math.imul(ah8, bl3)) | 0;
    hi = (hi + Math.imul(ah8, bh3)) | 0;
    lo = (lo + Math.imul(al7, bl4)) | 0;
    mid = (mid + Math.imul(al7, bh4)) | 0;
    mid = (mid + Math.imul(ah7, bl4)) | 0;
    hi = (hi + Math.imul(ah7, bh4)) | 0;
    lo = (lo + Math.imul(al6, bl5)) | 0;
    mid = (mid + Math.imul(al6, bh5)) | 0;
    mid = (mid + Math.imul(ah6, bl5)) | 0;
    hi = (hi + Math.imul(ah6, bh5)) | 0;
    lo = (lo + Math.imul(al5, bl6)) | 0;
    mid = (mid + Math.imul(al5, bh6)) | 0;
    mid = (mid + Math.imul(ah5, bl6)) | 0;
    hi = (hi + Math.imul(ah5, bh6)) | 0;
    lo = (lo + Math.imul(al4, bl7)) | 0;
    mid = (mid + Math.imul(al4, bh7)) | 0;
    mid = (mid + Math.imul(ah4, bl7)) | 0;
    hi = (hi + Math.imul(ah4, bh7)) | 0;
    lo = (lo + Math.imul(al3, bl8)) | 0;
    mid = (mid + Math.imul(al3, bh8)) | 0;
    mid = (mid + Math.imul(ah3, bl8)) | 0;
    hi = (hi + Math.imul(ah3, bh8)) | 0;
    lo = (lo + Math.imul(al2, bl9)) | 0;
    mid = (mid + Math.imul(al2, bh9)) | 0;
    mid = (mid + Math.imul(ah2, bl9)) | 0;
    hi = (hi + Math.imul(ah2, bh9)) | 0;
    var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
    w11 &= 0x3ffffff;
    /* k = 12 */
    lo = Math.imul(al9, bl3);
    mid = Math.imul(al9, bh3);
    mid = (mid + Math.imul(ah9, bl3)) | 0;
    hi = Math.imul(ah9, bh3);
    lo = (lo + Math.imul(al8, bl4)) | 0;
    mid = (mid + Math.imul(al8, bh4)) | 0;
    mid = (mid + Math.imul(ah8, bl4)) | 0;
    hi = (hi + Math.imul(ah8, bh4)) | 0;
    lo = (lo + Math.imul(al7, bl5)) | 0;
    mid = (mid + Math.imul(al7, bh5)) | 0;
    mid = (mid + Math.imul(ah7, bl5)) | 0;
    hi = (hi + Math.imul(ah7, bh5)) | 0;
    lo = (lo + Math.imul(al6, bl6)) | 0;
    mid = (mid + Math.imul(al6, bh6)) | 0;
    mid = (mid + Math.imul(ah6, bl6)) | 0;
    hi = (hi + Math.imul(ah6, bh6)) | 0;
    lo = (lo + Math.imul(al5, bl7)) | 0;
    mid = (mid + Math.imul(al5, bh7)) | 0;
    mid = (mid + Math.imul(ah5, bl7)) | 0;
    hi = (hi + Math.imul(ah5, bh7)) | 0;
    lo = (lo + Math.imul(al4, bl8)) | 0;
    mid = (mid + Math.imul(al4, bh8)) | 0;
    mid = (mid + Math.imul(ah4, bl8)) | 0;
    hi = (hi + Math.imul(ah4, bh8)) | 0;
    lo = (lo + Math.imul(al3, bl9)) | 0;
    mid = (mid + Math.imul(al3, bh9)) | 0;
    mid = (mid + Math.imul(ah3, bl9)) | 0;
    hi = (hi + Math.imul(ah3, bh9)) | 0;
    var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
    w12 &= 0x3ffffff;
    /* k = 13 */
    lo = Math.imul(al9, bl4);
    mid = Math.imul(al9, bh4);
    mid = (mid + Math.imul(ah9, bl4)) | 0;
    hi = Math.imul(ah9, bh4);
    lo = (lo + Math.imul(al8, bl5)) | 0;
    mid = (mid + Math.imul(al8, bh5)) | 0;
    mid = (mid + Math.imul(ah8, bl5)) | 0;
    hi = (hi + Math.imul(ah8, bh5)) | 0;
    lo = (lo + Math.imul(al7, bl6)) | 0;
    mid = (mid + Math.imul(al7, bh6)) | 0;
    mid = (mid + Math.imul(ah7, bl6)) | 0;
    hi = (hi + Math.imul(ah7, bh6)) | 0;
    lo = (lo + Math.imul(al6, bl7)) | 0;
    mid = (mid + Math.imul(al6, bh7)) | 0;
    mid = (mid + Math.imul(ah6, bl7)) | 0;
    hi = (hi + Math.imul(ah6, bh7)) | 0;
    lo = (lo + Math.imul(al5, bl8)) | 0;
    mid = (mid + Math.imul(al5, bh8)) | 0;
    mid = (mid + Math.imul(ah5, bl8)) | 0;
    hi = (hi + Math.imul(ah5, bh8)) | 0;
    lo = (lo + Math.imul(al4, bl9)) | 0;
    mid = (mid + Math.imul(al4, bh9)) | 0;
    mid = (mid + Math.imul(ah4, bl9)) | 0;
    hi = (hi + Math.imul(ah4, bh9)) | 0;
    var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
    w13 &= 0x3ffffff;
    /* k = 14 */
    lo = Math.imul(al9, bl5);
    mid = Math.imul(al9, bh5);
    mid = (mid + Math.imul(ah9, bl5)) | 0;
    hi = Math.imul(ah9, bh5);
    lo = (lo + Math.imul(al8, bl6)) | 0;
    mid = (mid + Math.imul(al8, bh6)) | 0;
    mid = (mid + Math.imul(ah8, bl6)) | 0;
    hi = (hi + Math.imul(ah8, bh6)) | 0;
    lo = (lo + Math.imul(al7, bl7)) | 0;
    mid = (mid + Math.imul(al7, bh7)) | 0;
    mid = (mid + Math.imul(ah7, bl7)) | 0;
    hi = (hi + Math.imul(ah7, bh7)) | 0;
    lo = (lo + Math.imul(al6, bl8)) | 0;
    mid = (mid + Math.imul(al6, bh8)) | 0;
    mid = (mid + Math.imul(ah6, bl8)) | 0;
    hi = (hi + Math.imul(ah6, bh8)) | 0;
    lo = (lo + Math.imul(al5, bl9)) | 0;
    mid = (mid + Math.imul(al5, bh9)) | 0;
    mid = (mid + Math.imul(ah5, bl9)) | 0;
    hi = (hi + Math.imul(ah5, bh9)) | 0;
    var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
    w14 &= 0x3ffffff;
    /* k = 15 */
    lo = Math.imul(al9, bl6);
    mid = Math.imul(al9, bh6);
    mid = (mid + Math.imul(ah9, bl6)) | 0;
    hi = Math.imul(ah9, bh6);
    lo = (lo + Math.imul(al8, bl7)) | 0;
    mid = (mid + Math.imul(al8, bh7)) | 0;
    mid = (mid + Math.imul(ah8, bl7)) | 0;
    hi = (hi + Math.imul(ah8, bh7)) | 0;
    lo = (lo + Math.imul(al7, bl8)) | 0;
    mid = (mid + Math.imul(al7, bh8)) | 0;
    mid = (mid + Math.imul(ah7, bl8)) | 0;
    hi = (hi + Math.imul(ah7, bh8)) | 0;
    lo = (lo + Math.imul(al6, bl9)) | 0;
    mid = (mid + Math.imul(al6, bh9)) | 0;
    mid = (mid + Math.imul(ah6, bl9)) | 0;
    hi = (hi + Math.imul(ah6, bh9)) | 0;
    var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
    w15 &= 0x3ffffff;
    /* k = 16 */
    lo = Math.imul(al9, bl7);
    mid = Math.imul(al9, bh7);
    mid = (mid + Math.imul(ah9, bl7)) | 0;
    hi = Math.imul(ah9, bh7);
    lo = (lo + Math.imul(al8, bl8)) | 0;
    mid = (mid + Math.imul(al8, bh8)) | 0;
    mid = (mid + Math.imul(ah8, bl8)) | 0;
    hi = (hi + Math.imul(ah8, bh8)) | 0;
    lo = (lo + Math.imul(al7, bl9)) | 0;
    mid = (mid + Math.imul(al7, bh9)) | 0;
    mid = (mid + Math.imul(ah7, bl9)) | 0;
    hi = (hi + Math.imul(ah7, bh9)) | 0;
    var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
    w16 &= 0x3ffffff;
    /* k = 17 */
    lo = Math.imul(al9, bl8);
    mid = Math.imul(al9, bh8);
    mid = (mid + Math.imul(ah9, bl8)) | 0;
    hi = Math.imul(ah9, bh8);
    lo = (lo + Math.imul(al8, bl9)) | 0;
    mid = (mid + Math.imul(al8, bh9)) | 0;
    mid = (mid + Math.imul(ah8, bl9)) | 0;
    hi = (hi + Math.imul(ah8, bh9)) | 0;
    var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
    w17 &= 0x3ffffff;
    /* k = 18 */
    lo = Math.imul(al9, bl9);
    mid = Math.imul(al9, bh9);
    mid = (mid + Math.imul(ah9, bl9)) | 0;
    hi = Math.imul(ah9, bh9);
    var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
    c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
    w18 &= 0x3ffffff;
    o[0] = w0;
    o[1] = w1;
    o[2] = w2;
    o[3] = w3;
    o[4] = w4;
    o[5] = w5;
    o[6] = w6;
    o[7] = w7;
    o[8] = w8;
    o[9] = w9;
    o[10] = w10;
    o[11] = w11;
    o[12] = w12;
    o[13] = w13;
    o[14] = w14;
    o[15] = w15;
    o[16] = w16;
    o[17] = w17;
    o[18] = w18;
    if (c !== 0) {
      o[19] = c;
      out.length++;
    }
    return out;
  };

  // Polyfill comb
  if (!Math.imul) {
    comb10MulTo = smallMulTo;
  }

  function bigMulTo (self, num, out) {
    out.negative = num.negative ^ self.negative;
    out.length = self.length + num.length;

    var carry = 0;
    var hncarry = 0;
    for (var k = 0; k < out.length - 1; k++) {
      // Sum all words with the same `i + j = k` and accumulate `ncarry`,
      // note that ncarry could be >= 0x3ffffff
      var ncarry = hncarry;
      hncarry = 0;
      var rword = carry & 0x3ffffff;
      var maxJ = Math.min(k, num.length - 1);
      for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
        var i = k - j;
        var a = self.words[i] | 0;
        var b = num.words[j] | 0;
        var r = a * b;

        var lo = r & 0x3ffffff;
        ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
        lo = (lo + rword) | 0;
        rword = lo & 0x3ffffff;
        ncarry = (ncarry + (lo >>> 26)) | 0;

        hncarry += ncarry >>> 26;
        ncarry &= 0x3ffffff;
      }
      out.words[k] = rword;
      carry = ncarry;
      ncarry = hncarry;
    }
    if (carry !== 0) {
      out.words[k] = carry;
    } else {
      out.length--;
    }

    return out.strip();
  }

  function jumboMulTo (self, num, out) {
    var fftm = new FFTM();
    return fftm.mulp(self, num, out);
  }

  BN.prototype.mulTo = function mulTo (num, out) {
    var res;
    var len = this.length + num.length;
    if (this.length === 10 && num.length === 10) {
      res = comb10MulTo(this, num, out);
    } else if (len < 63) {
      res = smallMulTo(this, num, out);
    } else if (len < 1024) {
      res = bigMulTo(this, num, out);
    } else {
      res = jumboMulTo(this, num, out);
    }

    return res;
  };

  // Cooley-Tukey algorithm for FFT
  // slightly revisited to rely on looping instead of recursion

  function FFTM (x, y) {
    this.x = x;
    this.y = y;
  }

  FFTM.prototype.makeRBT = function makeRBT (N) {
    var t = new Array(N);
    var l = BN.prototype._countBits(N) - 1;
    for (var i = 0; i < N; i++) {
      t[i] = this.revBin(i, l, N);
    }

    return t;
  };

  // Returns binary-reversed representation of `x`
  FFTM.prototype.revBin = function revBin (x, l, N) {
    if (x === 0 || x === N - 1) return x;

    var rb = 0;
    for (var i = 0; i < l; i++) {
      rb |= (x & 1) << (l - i - 1);
      x >>= 1;
    }

    return rb;
  };

  // Performs "tweedling" phase, therefore 'emulating'
  // behaviour of the recursive algorithm
  FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
    for (var i = 0; i < N; i++) {
      rtws[i] = rws[rbt[i]];
      itws[i] = iws[rbt[i]];
    }
  };

  FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
    this.permute(rbt, rws, iws, rtws, itws, N);

    for (var s = 1; s < N; s <<= 1) {
      var l = s << 1;

      var rtwdf = Math.cos(2 * Math.PI / l);
      var itwdf = Math.sin(2 * Math.PI / l);

      for (var p = 0; p < N; p += l) {
        var rtwdf_ = rtwdf;
        var itwdf_ = itwdf;

        for (var j = 0; j < s; j++) {
          var re = rtws[p + j];
          var ie = itws[p + j];

          var ro = rtws[p + j + s];
          var io = itws[p + j + s];

          var rx = rtwdf_ * ro - itwdf_ * io;

          io = rtwdf_ * io + itwdf_ * ro;
          ro = rx;

          rtws[p + j] = re + ro;
          itws[p + j] = ie + io;

          rtws[p + j + s] = re - ro;
          itws[p + j + s] = ie - io;

          /* jshint maxdepth : false */
          if (j !== l) {
            rx = rtwdf * rtwdf_ - itwdf * itwdf_;

            itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
            rtwdf_ = rx;
          }
        }
      }
    }
  };

  FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
    var N = Math.max(m, n) | 1;
    var odd = N & 1;
    var i = 0;
    for (N = N / 2 | 0; N; N = N >>> 1) {
      i++;
    }

    return 1 << i + 1 + odd;
  };

  FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
    if (N <= 1) return;

    for (var i = 0; i < N / 2; i++) {
      var t = rws[i];

      rws[i] = rws[N - i - 1];
      rws[N - i - 1] = t;

      t = iws[i];

      iws[i] = -iws[N - i - 1];
      iws[N - i - 1] = -t;
    }
  };

  FFTM.prototype.normalize13b = function normalize13b (ws, N) {
    var carry = 0;
    for (var i = 0; i < N / 2; i++) {
      var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
        Math.round(ws[2 * i] / N) +
        carry;

      ws[i] = w & 0x3ffffff;

      if (w < 0x4000000) {
        carry = 0;
      } else {
        carry = w / 0x4000000 | 0;
      }
    }

    return ws;
  };

  FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
    var carry = 0;
    for (var i = 0; i < len; i++) {
      carry = carry + (ws[i] | 0);

      rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
      rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
    }

    // Pad with zeroes
    for (i = 2 * len; i < N; ++i) {
      rws[i] = 0;
    }

    assert(carry === 0);
    assert((carry & ~0x1fff) === 0);
  };

  FFTM.prototype.stub = function stub (N) {
    var ph = new Array(N);
    for (var i = 0; i < N; i++) {
      ph[i] = 0;
    }

    return ph;
  };

  FFTM.prototype.mulp = function mulp (x, y, out) {
    var N = 2 * this.guessLen13b(x.length, y.length);

    var rbt = this.makeRBT(N);

    var _ = this.stub(N);

    var rws = new Array(N);
    var rwst = new Array(N);
    var iwst = new Array(N);

    var nrws = new Array(N);
    var nrwst = new Array(N);
    var niwst = new Array(N);

    var rmws = out.words;
    rmws.length = N;

    this.convert13b(x.words, x.length, rws, N);
    this.convert13b(y.words, y.length, nrws, N);

    this.transform(rws, _, rwst, iwst, N, rbt);
    this.transform(nrws, _, nrwst, niwst, N, rbt);

    for (var i = 0; i < N; i++) {
      var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
      iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
      rwst[i] = rx;
    }

    this.conjugate(rwst, iwst, N);
    this.transform(rwst, iwst, rmws, _, N, rbt);
    this.conjugate(rmws, _, N);
    this.normalize13b(rmws, N);

    out.negative = x.negative ^ y.negative;
    out.length = x.length + y.length;
    return out.strip();
  };

  // Multiply `this` by `num`
  BN.prototype.mul = function mul (num) {
    var out = new BN(null);
    out.words = new Array(this.length + num.length);
    return this.mulTo(num, out);
  };

  // Multiply employing FFT
  BN.prototype.mulf = function mulf (num) {
    var out = new BN(null);
    out.words = new Array(this.length + num.length);
    return jumboMulTo(this, num, out);
  };

  // In-place Multiplication
  BN.prototype.imul = function imul (num) {
    return this.clone().mulTo(num, this);
  };

  BN.prototype.imuln = function imuln (num) {
    assert(typeof num === 'number');
    assert(num < 0x4000000);

    // Carry
    var carry = 0;
    for (var i = 0; i < this.length; i++) {
      var w = (this.words[i] | 0) * num;
      var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
      carry >>= 26;
      carry += (w / 0x4000000) | 0;
      // NOTE: lo is 27bit maximum
      carry += lo >>> 26;
      this.words[i] = lo & 0x3ffffff;
    }

    if (carry !== 0) {
      this.words[i] = carry;
      this.length++;
    }

    return this;
  };

  BN.prototype.muln = function muln (num) {
    return this.clone().imuln(num);
  };

  // `this` * `this`
  BN.prototype.sqr = function sqr () {
    return this.mul(this);
  };

  // `this` * `this` in-place
  BN.prototype.isqr = function isqr () {
    return this.imul(this.clone());
  };

  // Math.pow(`this`, `num`)
  BN.prototype.pow = function pow (num) {
    var w = toBitArray(num);
    if (w.length === 0) return new BN(1);

    // Skip leading zeroes
    var res = this;
    for (var i = 0; i < w.length; i++, res = res.sqr()) {
      if (w[i] !== 0) break;
    }

    if (++i < w.length) {
      for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
        if (w[i] === 0) continue;

        res = res.mul(q);
      }
    }

    return res;
  };

  // Shift-left in-place
  BN.prototype.iushln = function iushln (bits) {
    assert(typeof bits === 'number' && bits >= 0);
    var r = bits % 26;
    var s = (bits - r) / 26;
    var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
    var i;

    if (r !== 0) {
      var carry = 0;

      for (i = 0; i < this.length; i++) {
        var newCarry = this.words[i] & carryMask;
        var c = ((this.words[i] | 0) - newCarry) << r;
        this.words[i] = c | carry;
        carry = newCarry >>> (26 - r);
      }

      if (carry) {
        this.words[i] = carry;
        this.length++;
      }
    }

    if (s !== 0) {
      for (i = this.length - 1; i >= 0; i--) {
        this.words[i + s] = this.words[i];
      }

      for (i = 0; i < s; i++) {
        this.words[i] = 0;
      }

      this.length += s;
    }

    return this.strip();
  };

  BN.prototype.ishln = function ishln (bits) {
    // TODO(indutny): implement me
    assert(this.negative === 0);
    return this.iushln(bits);
  };

  // Shift-right in-place
  // NOTE: `hint` is a lowest bit before trailing zeroes
  // NOTE: if `extended` is present - it will be filled with destroyed bits
  BN.prototype.iushrn = function iushrn (bits, hint, extended) {
    assert(typeof bits === 'number' && bits >= 0);
    var h;
    if (hint) {
      h = (hint - (hint % 26)) / 26;
    } else {
      h = 0;
    }

    var r = bits % 26;
    var s = Math.min((bits - r) / 26, this.length);
    var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
    var maskedWords = extended;

    h -= s;
    h = Math.max(0, h);

    // Extended mode, copy masked part
    if (maskedWords) {
      for (var i = 0; i < s; i++) {
        maskedWords.words[i] = this.words[i];
      }
      maskedWords.length = s;
    }

    if (s === 0) {
      // No-op, we should not move anything at all
    } else if (this.length > s) {
      this.length -= s;
      for (i = 0; i < this.length; i++) {
        this.words[i] = this.words[i + s];
      }
    } else {
      this.words[0] = 0;
      this.length = 1;
    }

    var carry = 0;
    for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
      var word = this.words[i] | 0;
      this.words[i] = (carry << (26 - r)) | (word >>> r);
      carry = word & mask;
    }

    // Push carried bits as a mask
    if (maskedWords && carry !== 0) {
      maskedWords.words[maskedWords.length++] = carry;
    }

    if (this.length === 0) {
      this.words[0] = 0;
      this.length = 1;
    }

    return this.strip();
  };

  BN.prototype.ishrn = function ishrn (bits, hint, extended) {
    // TODO(indutny): implement me
    assert(this.negative === 0);
    return this.iushrn(bits, hint, extended);
  };

  // Shift-left
  BN.prototype.shln = function shln (bits) {
    return this.clone().ishln(bits);
  };

  BN.prototype.ushln = function ushln (bits) {
    return this.clone().iushln(bits);
  };

  // Shift-right
  BN.prototype.shrn = function shrn (bits) {
    return this.clone().ishrn(bits);
  };

  BN.prototype.ushrn = function ushrn (bits) {
    return this.clone().iushrn(bits);
  };

  // Test if n bit is set
  BN.prototype.testn = function testn (bit) {
    assert(typeof bit === 'number' && bit >= 0);
    var r = bit % 26;
    var s = (bit - r) / 26;
    var q = 1 << r;

    // Fast case: bit is much higher than all existing words
    if (this.length <= s) return false;

    // Check bit and return
    var w = this.words[s];

    return !!(w & q);
  };

  // Return only lowers bits of number (in-place)
  BN.prototype.imaskn = function imaskn (bits) {
    assert(typeof bits === 'number' && bits >= 0);
    var r = bits % 26;
    var s = (bits - r) / 26;

    assert(this.negative === 0, 'imaskn works only with positive numbers');

    if (this.length <= s) {
      return this;
    }

    if (r !== 0) {
      s++;
    }
    this.length = Math.min(s, this.length);

    if (r !== 0) {
      var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
      this.words[this.length - 1] &= mask;
    }

    return this.strip();
  };

  // Return only lowers bits of number
  BN.prototype.maskn = function maskn (bits) {
    return this.clone().imaskn(bits);
  };

  // Add plain number `num` to `this`
  BN.prototype.iaddn = function iaddn (num) {
    assert(typeof num === 'number');
    assert(num < 0x4000000);
    if (num < 0) return this.isubn(-num);

    // Possible sign change
    if (this.negative !== 0) {
      if (this.length === 1 && (this.words[0] | 0) < num) {
        this.words[0] = num - (this.words[0] | 0);
        this.negative = 0;
        return this;
      }

      this.negative = 0;
      this.isubn(num);
      this.negative = 1;
      return this;
    }

    // Add without checks
    return this._iaddn(num);
  };

  BN.prototype._iaddn = function _iaddn (num) {
    this.words[0] += num;

    // Carry
    for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
      this.words[i] -= 0x4000000;
      if (i === this.length - 1) {
        this.words[i + 1] = 1;
      } else {
        this.words[i + 1]++;
      }
    }
    this.length = Math.max(this.length, i + 1);

    return this;
  };

  // Subtract plain number `num` from `this`
  BN.prototype.isubn = function isubn (num) {
    assert(typeof num === 'number');
    assert(num < 0x4000000);
    if (num < 0) return this.iaddn(-num);

    if (this.negative !== 0) {
      this.negative = 0;
      this.iaddn(num);
      this.negative = 1;
      return this;
    }

    this.words[0] -= num;

    if (this.length === 1 && this.words[0] < 0) {
      this.words[0] = -this.words[0];
      this.negative = 1;
    } else {
      // Carry
      for (var i = 0; i < this.length && this.words[i] < 0; i++) {
        this.words[i] += 0x4000000;
        this.words[i + 1] -= 1;
      }
    }

    return this.strip();
  };

  BN.prototype.addn = function addn (num) {
    return this.clone().iaddn(num);
  };

  BN.prototype.subn = function subn (num) {
    return this.clone().isubn(num);
  };

  BN.prototype.iabs = function iabs () {
    this.negative = 0;

    return this;
  };

  BN.prototype.abs = function abs () {
    return this.clone().iabs();
  };

  BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
    var len = num.length + shift;
    var i;

    this._expand(len);

    var w;
    var carry = 0;
    for (i = 0; i < num.length; i++) {
      w = (this.words[i + shift] | 0) + carry;
      var right = (num.words[i] | 0) * mul;
      w -= right & 0x3ffffff;
      carry = (w >> 26) - ((right / 0x4000000) | 0);
      this.words[i + shift] = w & 0x3ffffff;
    }
    for (; i < this.length - shift; i++) {
      w = (this.words[i + shift] | 0) + carry;
      carry = w >> 26;
      this.words[i + shift] = w & 0x3ffffff;
    }

    if (carry === 0) return this.strip();

    // Subtraction overflow
    assert(carry === -1);
    carry = 0;
    for (i = 0; i < this.length; i++) {
      w = -(this.words[i] | 0) + carry;
      carry = w >> 26;
      this.words[i] = w & 0x3ffffff;
    }
    this.negative = 1;

    return this.strip();
  };

  BN.prototype._wordDiv = function _wordDiv (num, mode) {
    var shift = this.length - num.length;

    var a = this.clone();
    var b = num;

    // Normalize
    var bhi = b.words[b.length - 1] | 0;
    var bhiBits = this._countBits(bhi);
    shift = 26 - bhiBits;
    if (shift !== 0) {
      b = b.ushln(shift);
      a.iushln(shift);
      bhi = b.words[b.length - 1] | 0;
    }

    // Initialize quotient
    var m = a.length - b.length;
    var q;

    if (mode !== 'mod') {
      q = new BN(null);
      q.length = m + 1;
      q.words = new Array(q.length);
      for (var i = 0; i < q.length; i++) {
        q.words[i] = 0;
      }
    }

    var diff = a.clone()._ishlnsubmul(b, 1, m);
    if (diff.negative === 0) {
      a = diff;
      if (q) {
        q.words[m] = 1;
      }
    }

    for (var j = m - 1; j >= 0; j--) {
      var qj = (a.words[b.length + j] | 0) * 0x4000000 +
        (a.words[b.length + j - 1] | 0);

      // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
      // (0x7ffffff)
      qj = Math.min((qj / bhi) | 0, 0x3ffffff);

      a._ishlnsubmul(b, qj, j);
      while (a.negative !== 0) {
        qj--;
        a.negative = 0;
        a._ishlnsubmul(b, 1, j);
        if (!a.isZero()) {
          a.negative ^= 1;
        }
      }
      if (q) {
        q.words[j] = qj;
      }
    }
    if (q) {
      q.strip();
    }
    a.strip();

    // Denormalize
    if (mode !== 'div' && shift !== 0) {
      a.iushrn(shift);
    }

    return {
      div: q || null,
      mod: a
    };
  };

  // NOTE: 1) `mode` can be set to `mod` to request mod only,
  //       to `div` to request div only, or be absent to
  //       request both div & mod
  //       2) `positive` is true if unsigned mod is requested
  BN.prototype.divmod = function divmod (num, mode, positive) {
    assert(!num.isZero());

    if (this.isZero()) {
      return {
        div: new BN(0),
        mod: new BN(0)
      };
    }

    var div, mod, res;
    if (this.negative !== 0 && num.negative === 0) {
      res = this.neg().divmod(num, mode);

      if (mode !== 'mod') {
        div = res.div.neg();
      }

      if (mode !== 'div') {
        mod = res.mod.neg();
        if (positive && mod.negative !== 0) {
          mod.iadd(num);
        }
      }

      return {
        div: div,
        mod: mod
      };
    }

    if (this.negative === 0 && num.negative !== 0) {
      res = this.divmod(num.neg(), mode);

      if (mode !== 'mod') {
        div = res.div.neg();
      }

      return {
        div: div,
        mod: res.mod
      };
    }

    if ((this.negative & num.negative) !== 0) {
      res = this.neg().divmod(num.neg(), mode);

      if (mode !== 'div') {
        mod = res.mod.neg();
        if (positive && mod.negative !== 0) {
          mod.isub(num);
        }
      }

      return {
        div: res.div,
        mod: mod
      };
    }

    // Both numbers are positive at this point

    // Strip both numbers to approximate shift value
    if (num.length > this.length || this.cmp(num) < 0) {
      return {
        div: new BN(0),
        mod: this
      };
    }

    // Very short reduction
    if (num.length === 1) {
      if (mode === 'div') {
        return {
          div: this.divn(num.words[0]),
          mod: null
        };
      }

      if (mode === 'mod') {
        return {
          div: null,
          mod: new BN(this.modn(num.words[0]))
        };
      }

      return {
        div: this.divn(num.words[0]),
        mod: new BN(this.modn(num.words[0]))
      };
    }

    return this._wordDiv(num, mode);
  };

  // Find `this` / `num`
  BN.prototype.div = function div (num) {
    return this.divmod(num, 'div', false).div;
  };

  // Find `this` % `num`
  BN.prototype.mod = function mod (num) {
    return this.divmod(num, 'mod', false).mod;
  };

  BN.prototype.umod = function umod (num) {
    return this.divmod(num, 'mod', true).mod;
  };

  // Find Round(`this` / `num`)
  BN.prototype.divRound = function divRound (num) {
    var dm = this.divmod(num);

    // Fast case - exact division
    if (dm.mod.isZero()) return dm.div;

    var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;

    var half = num.ushrn(1);
    var r2 = num.andln(1);
    var cmp = mod.cmp(half);

    // Round down
    if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;

    // Round up
    return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
  };

  BN.prototype.modn = function modn (num) {
    assert(num <= 0x3ffffff);
    var p = (1 << 26) % num;

    var acc = 0;
    for (var i = this.length - 1; i >= 0; i--) {
      acc = (p * acc + (this.words[i] | 0)) % num;
    }

    return acc;
  };

  // In-place division by number
  BN.prototype.idivn = function idivn (num) {
    assert(num <= 0x3ffffff);

    var carry = 0;
    for (var i = this.length - 1; i >= 0; i--) {
      var w = (this.words[i] | 0) + carry * 0x4000000;
      this.words[i] = (w / num) | 0;
      carry = w % num;
    }

    return this.strip();
  };

  BN.prototype.divn = function divn (num) {
    return this.clone().idivn(num);
  };

  BN.prototype.egcd = function egcd (p) {
    assert(p.negative === 0);
    assert(!p.isZero());

    var x = this;
    var y = p.clone();

    if (x.negative !== 0) {
      x = x.umod(p);
    } else {
      x = x.clone();
    }

    // A * x + B * y = x
    var A = new BN(1);
    var B = new BN(0);

    // C * x + D * y = y
    var C = new BN(0);
    var D = new BN(1);

    var g = 0;

    while (x.isEven() && y.isEven()) {
      x.iushrn(1);
      y.iushrn(1);
      ++g;
    }

    var yp = y.clone();
    var xp = x.clone();

    while (!x.isZero()) {
      for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
      if (i > 0) {
        x.iushrn(i);
        while (i-- > 0) {
          if (A.isOdd() || B.isOdd()) {
            A.iadd(yp);
            B.isub(xp);
          }

          A.iushrn(1);
          B.iushrn(1);
        }
      }

      for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
      if (j > 0) {
        y.iushrn(j);
        while (j-- > 0) {
          if (C.isOdd() || D.isOdd()) {
            C.iadd(yp);
            D.isub(xp);
          }

          C.iushrn(1);
          D.iushrn(1);
        }
      }

      if (x.cmp(y) >= 0) {
        x.isub(y);
        A.isub(C);
        B.isub(D);
      } else {
        y.isub(x);
        C.isub(A);
        D.isub(B);
      }
    }

    return {
      a: C,
      b: D,
      gcd: y.iushln(g)
    };
  };

  // This is reduced incarnation of the binary EEA
  // above, designated to invert members of the
  // _prime_ fields F(p) at a maximal speed
  BN.prototype._invmp = function _invmp (p) {
    assert(p.negative === 0);
    assert(!p.isZero());

    var a = this;
    var b = p.clone();

    if (a.negative !== 0) {
      a = a.umod(p);
    } else {
      a = a.clone();
    }

    var x1 = new BN(1);
    var x2 = new BN(0);

    var delta = b.clone();

    while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
      for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
      if (i > 0) {
        a.iushrn(i);
        while (i-- > 0) {
          if (x1.isOdd()) {
            x1.iadd(delta);
          }

          x1.iushrn(1);
        }
      }

      for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
      if (j > 0) {
        b.iushrn(j);
        while (j-- > 0) {
          if (x2.isOdd()) {
            x2.iadd(delta);
          }

          x2.iushrn(1);
        }
      }

      if (a.cmp(b) >= 0) {
        a.isub(b);
        x1.isub(x2);
      } else {
        b.isub(a);
        x2.isub(x1);
      }
    }

    var res;
    if (a.cmpn(1) === 0) {
      res = x1;
    } else {
      res = x2;
    }

    if (res.cmpn(0) < 0) {
      res.iadd(p);
    }

    return res;
  };

  BN.prototype.gcd = function gcd (num) {
    if (this.isZero()) return num.abs();
    if (num.isZero()) return this.abs();

    var a = this.clone();
    var b = num.clone();
    a.negative = 0;
    b.negative = 0;

    // Remove common factor of two
    for (var shift = 0; a.isEven() && b.isEven(); shift++) {
      a.iushrn(1);
      b.iushrn(1);
    }

    do {
      while (a.isEven()) {
        a.iushrn(1);
      }
      while (b.isEven()) {
        b.iushrn(1);
      }

      var r = a.cmp(b);
      if (r < 0) {
        // Swap `a` and `b` to make `a` always bigger than `b`
        var t = a;
        a = b;
        b = t;
      } else if (r === 0 || b.cmpn(1) === 0) {
        break;
      }

      a.isub(b);
    } while (true);

    return b.iushln(shift);
  };

  // Invert number in the field F(num)
  BN.prototype.invm = function invm (num) {
    return this.egcd(num).a.umod(num);
  };

  BN.prototype.isEven = function isEven () {
    return (this.words[0] & 1) === 0;
  };

  BN.prototype.isOdd = function isOdd () {
    return (this.words[0] & 1) === 1;
  };

  // And first word and num
  BN.prototype.andln = function andln (num) {
    return this.words[0] & num;
  };

  // Increment at the bit position in-line
  BN.prototype.bincn = function bincn (bit) {
    assert(typeof bit === 'number');
    var r = bit % 26;
    var s = (bit - r) / 26;
    var q = 1 << r;

    // Fast case: bit is much higher than all existing words
    if (this.length <= s) {
      this._expand(s + 1);
      this.words[s] |= q;
      return this;
    }

    // Add bit and propagate, if needed
    var carry = q;
    for (var i = s; carry !== 0 && i < this.length; i++) {
      var w = this.words[i] | 0;
      w += carry;
      carry = w >>> 26;
      w &= 0x3ffffff;
      this.words[i] = w;
    }
    if (carry !== 0) {
      this.words[i] = carry;
      this.length++;
    }
    return this;
  };

  BN.prototype.isZero = function isZero () {
    return this.length === 1 && this.words[0] === 0;
  };

  BN.prototype.cmpn = function cmpn (num) {
    var negative = num < 0;

    if (this.negative !== 0 && !negative) return -1;
    if (this.negative === 0 && negative) return 1;

    this.strip();

    var res;
    if (this.length > 1) {
      res = 1;
    } else {
      if (negative) {
        num = -num;
      }

      assert(num <= 0x3ffffff, 'Number is too big');

      var w = this.words[0] | 0;
      res = w === num ? 0 : w < num ? -1 : 1;
    }
    if (this.negative !== 0) return -res | 0;
    return res;
  };

  // Compare two numbers and return:
  // 1 - if `this` > `num`
  // 0 - if `this` == `num`
  // -1 - if `this` < `num`
  BN.prototype.cmp = function cmp (num) {
    if (this.negative !== 0 && num.negative === 0) return -1;
    if (this.negative === 0 && num.negative !== 0) return 1;

    var res = this.ucmp(num);
    if (this.negative !== 0) return -res | 0;
    return res;
  };

  // Unsigned comparison
  BN.prototype.ucmp = function ucmp (num) {
    // At this point both numbers have the same sign
    if (this.length > num.length) return 1;
    if (this.length < num.length) return -1;

    var res = 0;
    for (var i = this.length - 1; i >= 0; i--) {
      var a = this.words[i] | 0;
      var b = num.words[i] | 0;

      if (a === b) continue;
      if (a < b) {
        res = -1;
      } else if (a > b) {
        res = 1;
      }
      break;
    }
    return res;
  };

  BN.prototype.gtn = function gtn (num) {
    return this.cmpn(num) === 1;
  };

  BN.prototype.gt = function gt (num) {
    return this.cmp(num) === 1;
  };

  BN.prototype.gten = function gten (num) {
    return this.cmpn(num) >= 0;
  };

  BN.prototype.gte = function gte (num) {
    return this.cmp(num) >= 0;
  };

  BN.prototype.ltn = function ltn (num) {
    return this.cmpn(num) === -1;
  };

  BN.prototype.lt = function lt (num) {
    return this.cmp(num) === -1;
  };

  BN.prototype.lten = function lten (num) {
    return this.cmpn(num) <= 0;
  };

  BN.prototype.lte = function lte (num) {
    return this.cmp(num) <= 0;
  };

  BN.prototype.eqn = function eqn (num) {
    return this.cmpn(num) === 0;
  };

  BN.prototype.eq = function eq (num) {
    return this.cmp(num) === 0;
  };

  //
  // A reduce context, could be using montgomery or something better, depending
  // on the `m` itself.
  //
  BN.red = function red (num) {
    return new Red(num);
  };

  BN.prototype.toRed = function toRed (ctx) {
    assert(!this.red, 'Already a number in reduction context');
    assert(this.negative === 0, 'red works only with positives');
    return ctx.convertTo(this)._forceRed(ctx);
  };

  BN.prototype.fromRed = function fromRed () {
    assert(this.red, 'fromRed works only with numbers in reduction context');
    return this.red.convertFrom(this);
  };

  BN.prototype._forceRed = function _forceRed (ctx) {
    this.red = ctx;
    return this;
  };

  BN.prototype.forceRed = function forceRed (ctx) {
    assert(!this.red, 'Already a number in reduction context');
    return this._forceRed(ctx);
  };

  BN.prototype.redAdd = function redAdd (num) {
    assert(this.red, 'redAdd works only with red numbers');
    return this.red.add(this, num);
  };

  BN.prototype.redIAdd = function redIAdd (num) {
    assert(this.red, 'redIAdd works only with red numbers');
    return this.red.iadd(this, num);
  };

  BN.prototype.redSub = function redSub (num) {
    assert(this.red, 'redSub works only with red numbers');
    return this.red.sub(this, num);
  };

  BN.prototype.redISub = function redISub (num) {
    assert(this.red, 'redISub works only with red numbers');
    return this.red.isub(this, num);
  };

  BN.prototype.redShl = function redShl (num) {
    assert(this.red, 'redShl works only with red numbers');
    return this.red.shl(this, num);
  };

  BN.prototype.redMul = function redMul (num) {
    assert(this.red, 'redMul works only with red numbers');
    this.red._verify2(this, num);
    return this.red.mul(this, num);
  };

  BN.prototype.redIMul = function redIMul (num) {
    assert(this.red, 'redMul works only with red numbers');
    this.red._verify2(this, num);
    return this.red.imul(this, num);
  };

  BN.prototype.redSqr = function redSqr () {
    assert(this.red, 'redSqr works only with red numbers');
    this.red._verify1(this);
    return this.red.sqr(this);
  };

  BN.prototype.redISqr = function redISqr () {
    assert(this.red, 'redISqr works only with red numbers');
    this.red._verify1(this);
    return this.red.isqr(this);
  };

  // Square root over p
  BN.prototype.redSqrt = function redSqrt () {
    assert(this.red, 'redSqrt works only with red numbers');
    this.red._verify1(this);
    return this.red.sqrt(this);
  };

  BN.prototype.redInvm = function redInvm () {
    assert(this.red, 'redInvm works only with red numbers');
    this.red._verify1(this);
    return this.red.invm(this);
  };

  // Return negative clone of `this` % `red modulo`
  BN.prototype.redNeg = function redNeg () {
    assert(this.red, 'redNeg works only with red numbers');
    this.red._verify1(this);
    return this.red.neg(this);
  };

  BN.prototype.redPow = function redPow (num) {
    assert(this.red && !num.red, 'redPow(normalNum)');
    this.red._verify1(this);
    return this.red.pow(this, num);
  };

  // Prime numbers with efficient reduction
  var primes = {
    k256: null,
    p224: null,
    p192: null,
    p25519: null
  };

  // Pseudo-Mersenne prime
  function MPrime (name, p) {
    // P = 2 ^ N - K
    this.name = name;
    this.p = new BN(p, 16);
    this.n = this.p.bitLength();
    this.k = new BN(1).iushln(this.n).isub(this.p);

    this.tmp = this._tmp();
  }

  MPrime.prototype._tmp = function _tmp () {
    var tmp = new BN(null);
    tmp.words = new Array(Math.ceil(this.n / 13));
    return tmp;
  };

  MPrime.prototype.ireduce = function ireduce (num) {
    // Assumes that `num` is less than `P^2`
    // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
    var r = num;
    var rlen;

    do {
      this.split(r, this.tmp);
      r = this.imulK(r);
      r = r.iadd(this.tmp);
      rlen = r.bitLength();
    } while (rlen > this.n);

    var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
    if (cmp === 0) {
      r.words[0] = 0;
      r.length = 1;
    } else if (cmp > 0) {
      r.isub(this.p);
    } else {
      r.strip();
    }

    return r;
  };

  MPrime.prototype.split = function split (input, out) {
    input.iushrn(this.n, 0, out);
  };

  MPrime.prototype.imulK = function imulK (num) {
    return num.imul(this.k);
  };

  function K256 () {
    MPrime.call(
      this,
      'k256',
      'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
  }
  inherits(K256, MPrime);

  K256.prototype.split = function split (input, output) {
    // 256 = 9 * 26 + 22
    var mask = 0x3fffff;

    var outLen = Math.min(input.length, 9);
    for (var i = 0; i < outLen; i++) {
      output.words[i] = input.words[i];
    }
    output.length = outLen;

    if (input.length <= 9) {
      input.words[0] = 0;
      input.length = 1;
      return;
    }

    // Shift by 9 limbs
    var prev = input.words[9];
    output.words[output.length++] = prev & mask;

    for (i = 10; i < input.length; i++) {
      var next = input.words[i] | 0;
      input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
      prev = next;
    }
    prev >>>= 22;
    input.words[i - 10] = prev;
    if (prev === 0 && input.length > 10) {
      input.length -= 10;
    } else {
      input.length -= 9;
    }
  };

  K256.prototype.imulK = function imulK (num) {
    // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
    num.words[num.length] = 0;
    num.words[num.length + 1] = 0;
    num.length += 2;

    // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
    var lo = 0;
    for (var i = 0; i < num.length; i++) {
      var w = num.words[i] | 0;
      lo += w * 0x3d1;
      num.words[i] = lo & 0x3ffffff;
      lo = w * 0x40 + ((lo / 0x4000000) | 0);
    }

    // Fast length reduction
    if (num.words[num.length - 1] === 0) {
      num.length--;
      if (num.words[num.length - 1] === 0) {
        num.length--;
      }
    }
    return num;
  };

  function P224 () {
    MPrime.call(
      this,
      'p224',
      'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
  }
  inherits(P224, MPrime);

  function P192 () {
    MPrime.call(
      this,
      'p192',
      'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
  }
  inherits(P192, MPrime);

  function P25519 () {
    // 2 ^ 255 - 19
    MPrime.call(
      this,
      '25519',
      '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
  }
  inherits(P25519, MPrime);

  P25519.prototype.imulK = function imulK (num) {
    // K = 0x13
    var carry = 0;
    for (var i = 0; i < num.length; i++) {
      var hi = (num.words[i] | 0) * 0x13 + carry;
      var lo = hi & 0x3ffffff;
      hi >>>= 26;

      num.words[i] = lo;
      carry = hi;
    }
    if (carry !== 0) {
      num.words[num.length++] = carry;
    }
    return num;
  };

  // Exported mostly for testing purposes, use plain name instead
  BN._prime = function prime (name) {
    // Cached version of prime
    if (primes[name]) return primes[name];

    var prime;
    if (name === 'k256') {
      prime = new K256();
    } else if (name === 'p224') {
      prime = new P224();
    } else if (name === 'p192') {
      prime = new P192();
    } else if (name === 'p25519') {
      prime = new P25519();
    } else {
      throw new Error('Unknown prime ' + name);
    }
    primes[name] = prime;

    return prime;
  };

  //
  // Base reduction engine
  //
  function Red (m) {
    if (typeof m === 'string') {
      var prime = BN._prime(m);
      this.m = prime.p;
      this.prime = prime;
    } else {
      assert(m.gtn(1), 'modulus must be greater than 1');
      this.m = m;
      this.prime = null;
    }
  }

  Red.prototype._verify1 = function _verify1 (a) {
    assert(a.negative === 0, 'red works only with positives');
    assert(a.red, 'red works only with red numbers');
  };

  Red.prototype._verify2 = function _verify2 (a, b) {
    assert((a.negative | b.negative) === 0, 'red works only with positives');
    assert(a.red && a.red === b.red,
      'red works only with red numbers');
  };

  Red.prototype.imod = function imod (a) {
    if (this.prime) return this.prime.ireduce(a)._forceRed(this);
    return a.umod(this.m)._forceRed(this);
  };

  Red.prototype.neg = function neg (a) {
    if (a.isZero()) {
      return a.clone();
    }

    return this.m.sub(a)._forceRed(this);
  };

  Red.prototype.add = function add (a, b) {
    this._verify2(a, b);

    var res = a.add(b);
    if (res.cmp(this.m) >= 0) {
      res.isub(this.m);
    }
    return res._forceRed(this);
  };

  Red.prototype.iadd = function iadd (a, b) {
    this._verify2(a, b);

    var res = a.iadd(b);
    if (res.cmp(this.m) >= 0) {
      res.isub(this.m);
    }
    return res;
  };

  Red.prototype.sub = function sub (a, b) {
    this._verify2(a, b);

    var res = a.sub(b);
    if (res.cmpn(0) < 0) {
      res.iadd(this.m);
    }
    return res._forceRed(this);
  };

  Red.prototype.isub = function isub (a, b) {
    this._verify2(a, b);

    var res = a.isub(b);
    if (res.cmpn(0) < 0) {
      res.iadd(this.m);
    }
    return res;
  };

  Red.prototype.shl = function shl (a, num) {
    this._verify1(a);
    return this.imod(a.ushln(num));
  };

  Red.prototype.imul = function imul (a, b) {
    this._verify2(a, b);
    return this.imod(a.imul(b));
  };

  Red.prototype.mul = function mul (a, b) {
    this._verify2(a, b);
    return this.imod(a.mul(b));
  };

  Red.prototype.isqr = function isqr (a) {
    return this.imul(a, a.clone());
  };

  Red.prototype.sqr = function sqr (a) {
    return this.mul(a, a);
  };

  Red.prototype.sqrt = function sqrt (a) {
    if (a.isZero()) return a.clone();

    var mod3 = this.m.andln(3);
    assert(mod3 % 2 === 1);

    // Fast case
    if (mod3 === 3) {
      var pow = this.m.add(new BN(1)).iushrn(2);
      return this.pow(a, pow);
    }

    // Tonelli-Shanks algorithm (Totally unoptimized and slow)
    //
    // Find Q and S, that Q * 2 ^ S = (P - 1)
    var q = this.m.subn(1);
    var s = 0;
    while (!q.isZero() && q.andln(1) === 0) {
      s++;
      q.iushrn(1);
    }
    assert(!q.isZero());

    var one = new BN(1).toRed(this);
    var nOne = one.redNeg();

    // Find quadratic non-residue
    // NOTE: Max is such because of generalized Riemann hypothesis.
    var lpow = this.m.subn(1).iushrn(1);
    var z = this.m.bitLength();
    z = new BN(2 * z * z).toRed(this);

    while (this.pow(z, lpow).cmp(nOne) !== 0) {
      z.redIAdd(nOne);
    }

    var c = this.pow(z, q);
    var r = this.pow(a, q.addn(1).iushrn(1));
    var t = this.pow(a, q);
    var m = s;
    while (t.cmp(one) !== 0) {
      var tmp = t;
      for (var i = 0; tmp.cmp(one) !== 0; i++) {
        tmp = tmp.redSqr();
      }
      assert(i < m);
      var b = this.pow(c, new BN(1).iushln(m - i - 1));

      r = r.redMul(b);
      c = b.redSqr();
      t = t.redMul(c);
      m = i;
    }

    return r;
  };

  Red.prototype.invm = function invm (a) {
    var inv = a._invmp(this.m);
    if (inv.negative !== 0) {
      inv.negative = 0;
      return this.imod(inv).redNeg();
    } else {
      return this.imod(inv);
    }
  };

  Red.prototype.pow = function pow (a, num) {
    if (num.isZero()) return new BN(1).toRed(this);
    if (num.cmpn(1) === 0) return a.clone();

    var windowSize = 4;
    var wnd = new Array(1 << windowSize);
    wnd[0] = new BN(1).toRed(this);
    wnd[1] = a;
    for (var i = 2; i < wnd.length; i++) {
      wnd[i] = this.mul(wnd[i - 1], a);
    }

    var res = wnd[0];
    var current = 0;
    var currentLen = 0;
    var start = num.bitLength() % 26;
    if (start === 0) {
      start = 26;
    }

    for (i = num.length - 1; i >= 0; i--) {
      var word = num.words[i];
      for (var j = start - 1; j >= 0; j--) {
        var bit = (word >> j) & 1;
        if (res !== wnd[0]) {
          res = this.sqr(res);
        }

        if (bit === 0 && current === 0) {
          currentLen = 0;
          continue;
        }

        current <<= 1;
        current |= bit;
        currentLen++;
        if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;

        res = this.mul(res, wnd[current]);
        currentLen = 0;
        current = 0;
      }
      start = 26;
    }

    return res;
  };

  Red.prototype.convertTo = function convertTo (num) {
    var r = num.umod(this.m);

    return r === num ? r.clone() : r;
  };

  Red.prototype.convertFrom = function convertFrom (num) {
    var res = num.clone();
    res.red = null;
    return res;
  };

  //
  // Montgomery method engine
  //

  BN.mont = function mont (num) {
    return new Mont(num);
  };

  function Mont (m) {
    Red.call(this, m);

    this.shift = this.m.bitLength();
    if (this.shift % 26 !== 0) {
      this.shift += 26 - (this.shift % 26);
    }

    this.r = new BN(1).iushln(this.shift);
    this.r2 = this.imod(this.r.sqr());
    this.rinv = this.r._invmp(this.m);

    this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
    this.minv = this.minv.umod(this.r);
    this.minv = this.r.sub(this.minv);
  }
  inherits(Mont, Red);

  Mont.prototype.convertTo = function convertTo (num) {
    return this.imod(num.ushln(this.shift));
  };

  Mont.prototype.convertFrom = function convertFrom (num) {
    var r = this.imod(num.mul(this.rinv));
    r.red = null;
    return r;
  };

  Mont.prototype.imul = function imul (a, b) {
    if (a.isZero() || b.isZero()) {
      a.words[0] = 0;
      a.length = 1;
      return a;
    }

    var t = a.imul(b);
    var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
    var u = t.isub(c).iushrn(this.shift);
    var res = u;

    if (u.cmp(this.m) >= 0) {
      res = u.isub(this.m);
    } else if (u.cmpn(0) < 0) {
      res = u.iadd(this.m);
    }

    return res._forceRed(this);
  };

  Mont.prototype.mul = function mul (a, b) {
    if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);

    var t = a.mul(b);
    var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
    var u = t.isub(c).iushrn(this.shift);
    var res = u;
    if (u.cmp(this.m) >= 0) {
      res = u.isub(this.m);
    } else if (u.cmpn(0) < 0) {
      res = u.iadd(this.m);
    }

    return res._forceRed(this);
  };

  Mont.prototype.invm = function invm (a) {
    // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
    var res = this.imod(a._invmp(this.m).mul(this.r2));
    return res._forceRed(this);
  };
})(typeof module === 'undefined' || module, this);

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/module.js */ "YuTi")(module)))

/***/ }),

/***/ "Oaa7":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/en-gb.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var enGb = moment.defineLocale('en-gb', {
    months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
    monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
    weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
    weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
    weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd, D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay : '[Today at] LT',
        nextDay : '[Tomorrow at] LT',
        nextWeek : 'dddd [at] LT',
        lastDay : '[Yesterday at] LT',
        lastWeek : '[Last] dddd [at] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'in %s',
        past : '%s ago',
        s : 'a few seconds',
        ss : '%d seconds',
        m : 'a minute',
        mm : '%d minutes',
        h : 'an hour',
        hh : '%d hours',
        d : 'a day',
        dd : '%d days',
        M : 'a month',
        MM : '%d months',
        y : 'a year',
        yy : '%d years'
    },
    dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/,
    ordinal : function (number) {
        var b = number % 10,
            output = (~~(number % 100 / 10) === 1) ? 'th' :
            (b === 1) ? 'st' :
            (b === 2) ? 'nd' :
            (b === 3) ? 'rd' : 'th';
        return number + output;
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return enGb;

})));


/***/ }),

/***/ "Oau+":
/*!***********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/FilingCabinetIcon.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var FilingCabinetIcon = function FilingCabinetIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M28 11H4c-1 0-2 1-2 2v14c0 1 1 2 2 2h24c1 0 2-1 2-2V13c0-1-1-2-2-2zm-6.375 6.625c0 1-1 2-2 2H12c-1 0-2-1-2-2V17c0-1 1-2 2-2h7.625c1 0 2 1 2 2zM30 3H2C1 3 0 4 0 5v4h32V5c0-1-1-2-2-2z' })
    );
};

exports.default = FilingCabinetIcon;

/***/ }),

/***/ "Ob0Z":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/mr.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var symbolMap = {
    '1': '१',
    '2': '२',
    '3': '३',
    '4': '४',
    '5': '५',
    '6': '६',
    '7': '७',
    '8': '८',
    '9': '९',
    '0': '०'
},
numberMap = {
    '१': '1',
    '२': '2',
    '३': '3',
    '४': '4',
    '५': '5',
    '६': '6',
    '७': '7',
    '८': '8',
    '९': '9',
    '०': '0'
};

function relativeTimeMr(number, withoutSuffix, string, isFuture)
{
    var output = '';
    if (withoutSuffix) {
        switch (string) {
            case 's': output = 'काही सेकंद'; break;
            case 'ss': output = '%d सेकंद'; break;
            case 'm': output = 'एक मिनिट'; break;
            case 'mm': output = '%d मिनिटे'; break;
            case 'h': output = 'एक तास'; break;
            case 'hh': output = '%d तास'; break;
            case 'd': output = 'एक दिवस'; break;
            case 'dd': output = '%d दिवस'; break;
            case 'M': output = 'एक महिना'; break;
            case 'MM': output = '%d महिने'; break;
            case 'y': output = 'एक वर्ष'; break;
            case 'yy': output = '%d वर्षे'; break;
        }
    }
    else {
        switch (string) {
            case 's': output = 'काही सेकंदां'; break;
            case 'ss': output = '%d सेकंदां'; break;
            case 'm': output = 'एका मिनिटा'; break;
            case 'mm': output = '%d मिनिटां'; break;
            case 'h': output = 'एका तासा'; break;
            case 'hh': output = '%d तासां'; break;
            case 'd': output = 'एका दिवसा'; break;
            case 'dd': output = '%d दिवसां'; break;
            case 'M': output = 'एका महिन्या'; break;
            case 'MM': output = '%d महिन्यां'; break;
            case 'y': output = 'एका वर्षा'; break;
            case 'yy': output = '%d वर्षां'; break;
        }
    }
    return output.replace(/%d/i, number);
}

var mr = moment.defineLocale('mr', {
    months : 'जानेवारी_फेब्रुवारी_मार्च_एप्रिल_मे_जून_जुलै_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर'.split('_'),
    monthsShort: 'जाने._फेब्रु._मार्च._एप्रि._मे._जून._जुलै._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.'.split('_'),
    monthsParseExact : true,
    weekdays : 'रविवार_सोमवार_मंगळवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'),
    weekdaysShort : 'रवि_सोम_मंगळ_बुध_गुरू_शुक्र_शनि'.split('_'),
    weekdaysMin : 'र_सो_मं_बु_गु_शु_श'.split('_'),
    longDateFormat : {
        LT : 'A h:mm वाजता',
        LTS : 'A h:mm:ss वाजता',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY, A h:mm वाजता',
        LLLL : 'dddd, D MMMM YYYY, A h:mm वाजता'
    },
    calendar : {
        sameDay : '[आज] LT',
        nextDay : '[उद्या] LT',
        nextWeek : 'dddd, LT',
        lastDay : '[काल] LT',
        lastWeek: '[मागील] dddd, LT',
        sameElse : 'L'
    },
    relativeTime : {
        future: '%sमध्ये',
        past: '%sपूर्वी',
        s: relativeTimeMr,
        ss: relativeTimeMr,
        m: relativeTimeMr,
        mm: relativeTimeMr,
        h: relativeTimeMr,
        hh: relativeTimeMr,
        d: relativeTimeMr,
        dd: relativeTimeMr,
        M: relativeTimeMr,
        MM: relativeTimeMr,
        y: relativeTimeMr,
        yy: relativeTimeMr
    },
    preparse: function (string) {
        return string.replace(/[१२३४५६७८९०]/g, function (match) {
            return numberMap[match];
        });
    },
    postformat: function (string) {
        return string.replace(/\d/g, function (match) {
            return symbolMap[match];
        });
    },
    meridiemParse: /रात्री|सकाळी|दुपारी|सायंकाळी/,
    meridiemHour : function (hour, meridiem) {
        if (hour === 12) {
            hour = 0;
        }
        if (meridiem === 'रात्री') {
            return hour < 4 ? hour : hour + 12;
        } else if (meridiem === 'सकाळी') {
            return hour;
        } else if (meridiem === 'दुपारी') {
            return hour >= 10 ? hour : hour + 12;
        } else if (meridiem === 'सायंकाळी') {
            return hour + 12;
        }
    },
    meridiem: function (hour, minute, isLower) {
        if (hour < 4) {
            return 'रात्री';
        } else if (hour < 10) {
            return 'सकाळी';
        } else if (hour < 17) {
            return 'दुपारी';
        } else if (hour < 20) {
            return 'सायंकाळी';
        } else {
            return 'रात्री';
        }
    },
    week : {
        dow : 0, // Sunday is the first day of the week.
        doy : 6  // The week that contains Jan 1st is the first week of the year.
    }
});

return mr;

})));


/***/ }),

/***/ "Of+w":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_WeakMap.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getNative = __webpack_require__(/*! ./_getNative */ "Cwc5"),
    root = __webpack_require__(/*! ./_root */ "Kz5y");

/* Built-in method references that are verified to be native. */
var WeakMap = getNative(root, 'WeakMap');

module.exports = WeakMap;


/***/ }),

/***/ "OfDz":
/*!************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/index.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DateTimePicker = exports.NumericOrDate = exports.AxisInterval = exports.HovermodeDropdown = exports.HoveronDropdown = exports.LocationSelector = exports.RectanglePositioner = exports.DropdownCustom = exports.VisibilitySelect = exports.MultiColorPicker = exports.MarkerColor = exports.MarkerSize = exports.TextPosition = exports.Dropzone = exports.UpdateMenuButtons = exports.AxisSide = exports.AxisOverlayDropdown = exports.GroupCreator = exports.SubplotCreator = exports.AxesCreator = exports.TraceSelector = exports.TraceOrientation = exports.TextEditor = exports.RangesliderVisible = exports.SymbolSelector = exports.Radio = exports.TickFormat = exports.Text = exports.AxisRangeValue = exports.DualNumeric = exports.Numeric = exports.LineShapeSelector = exports.LineDashSelector = exports.PositioningNumeric = exports.NumericFractionInverse = exports.NumericFractionDomain = exports.NumericFraction = exports.Info = exports.HoverTemplateSwitch = exports.HoverTemplateText = exports.HoverInfo = exports.FontSelector = exports.Flaglist = exports.FilterValue = exports.FilterOperation = exports.PieColorscalePicker = exports.FillDropdown = exports.ErrorBars = exports.Dropdown = exports.DataSelector = exports.ContourNumeric = exports.ColorwayPicker = exports.ColorscalePicker = exports.ColorPicker = exports.AxesSelector = exports.DTicksInterval = exports.DTicks = exports.NTicks = exports.AxesRange = exports.ArrowSelector = exports.PositioningRef = exports.AxisAnchorDropdown = exports.AnnotationRef = exports.AnnotationArrowRef = exports.ShowInLegend = undefined;

var _ArrowSelector = __webpack_require__(/*! ./ArrowSelector */ "NCq+");

var _ArrowSelector2 = _interopRequireDefault(_ArrowSelector);

var _AxesSelector = __webpack_require__(/*! ./AxesSelector */ "rVQt");

var _AxesSelector2 = _interopRequireDefault(_AxesSelector);

var _ColorPicker = __webpack_require__(/*! ./ColorPicker */ "u/dz");

var _ColorPicker2 = _interopRequireDefault(_ColorPicker);

var _ColorscalePicker = __webpack_require__(/*! ./ColorscalePicker */ "t0w/");

var _ColorscalePicker2 = _interopRequireDefault(_ColorscalePicker);

var _PieColorscalePicker = __webpack_require__(/*! ./PieColorscalePicker */ "vn1i");

var _PieColorscalePicker2 = _interopRequireDefault(_PieColorscalePicker);

var _ColorwayPicker = __webpack_require__(/*! ./ColorwayPicker */ "Yixa");

var _ColorwayPicker2 = _interopRequireDefault(_ColorwayPicker);

var _Dropdown = __webpack_require__(/*! ./Dropdown */ "dRXW");

var _Dropdown2 = _interopRequireDefault(_Dropdown);

var _Dropzone = __webpack_require__(/*! ./Dropzone */ "YDq3");

var _Dropzone2 = _interopRequireDefault(_Dropzone);

var _FontSelector = __webpack_require__(/*! ./FontSelector */ "tkb2");

var _FontSelector2 = _interopRequireDefault(_FontSelector);

var _Flaglist = __webpack_require__(/*! ./Flaglist */ "fS+6");

var _Flaglist2 = _interopRequireDefault(_Flaglist);

var _Info = __webpack_require__(/*! ./Info */ "iOcY");

var _Info2 = _interopRequireDefault(_Info);

var _Radio = __webpack_require__(/*! ./Radio */ "5Riz");

var _Radio2 = _interopRequireDefault(_Radio);

var _TextEditor = __webpack_require__(/*! ./TextEditor */ "0b9Q");

var _TextEditor2 = _interopRequireDefault(_TextEditor);

var _DataSelector = __webpack_require__(/*! ./DataSelector */ "dv5i");

var _DataSelector2 = _interopRequireDefault(_DataSelector);

var _Numeric = __webpack_require__(/*! ./Numeric */ "E01D");

var _Numeric2 = _interopRequireDefault(_Numeric);

var _NumericOrDate = __webpack_require__(/*! ./NumericOrDate */ "dZIv");

var _NumericOrDate2 = _interopRequireDefault(_NumericOrDate);

var _DualNumeric = __webpack_require__(/*! ./DualNumeric */ "x9uK");

var _DualNumeric2 = _interopRequireDefault(_DualNumeric);

var _AxisRangeValue = __webpack_require__(/*! ./AxisRangeValue */ "eRYw");

var _AxisRangeValue2 = _interopRequireDefault(_AxisRangeValue);

var _Text = __webpack_require__(/*! ./Text */ "CQ7X");

var _Text2 = _interopRequireDefault(_Text);

var _SymbolSelector = __webpack_require__(/*! ./SymbolSelector */ "g3A5");

var _SymbolSelector2 = _interopRequireDefault(_SymbolSelector);

var _TraceSelector = __webpack_require__(/*! ./TraceSelector */ "eDmQ");

var _TraceSelector2 = _interopRequireDefault(_TraceSelector);

var _ErrorBars = __webpack_require__(/*! ./ErrorBars */ "iw4z");

var _ErrorBars2 = _interopRequireDefault(_ErrorBars);

var _AxesCreator = __webpack_require__(/*! ./AxesCreator */ "HWco");

var _AxesCreator2 = _interopRequireDefault(_AxesCreator);

var _SubplotCreator = __webpack_require__(/*! ./SubplotCreator */ "y4qi");

var _SubplotCreator2 = _interopRequireDefault(_SubplotCreator);

var _GroupCreator = __webpack_require__(/*! ./GroupCreator */ "k3sf");

var _GroupCreator2 = _interopRequireDefault(_GroupCreator);

var _UpdateMenuButtons = __webpack_require__(/*! ./UpdateMenuButtons */ "Qx43");

var _UpdateMenuButtons2 = _interopRequireDefault(_UpdateMenuButtons);

var _FilterOperation = __webpack_require__(/*! ./FilterOperation */ "BxQ/");

var _MarkerSize = __webpack_require__(/*! ./MarkerSize */ "MlNG");

var _MarkerSize2 = _interopRequireDefault(_MarkerSize);

var _MarkerColor = __webpack_require__(/*! ./MarkerColor */ "zBqG");

var _MarkerColor2 = _interopRequireDefault(_MarkerColor);

var _VisibilitySelect = __webpack_require__(/*! ./VisibilitySelect */ "a9J7");

var _VisibilitySelect2 = _interopRequireDefault(_VisibilitySelect);

var _DropdownCustom = __webpack_require__(/*! ./DropdownCustom */ "H7PE");

var _DropdownCustom2 = _interopRequireDefault(_DropdownCustom);

var _MultiColorPicker = __webpack_require__(/*! ./MultiColorPicker */ "/lhS");

var _MultiColorPicker2 = _interopRequireDefault(_MultiColorPicker);

var _RectanglePositioner = __webpack_require__(/*! ./RectanglePositioner */ "WLfm");

var _RectanglePositioner2 = _interopRequireDefault(_RectanglePositioner);

var _LocationSelector = __webpack_require__(/*! ./LocationSelector */ "sJIH");

var _LocationSelector2 = _interopRequireDefault(_LocationSelector);

var _AxisInterval = __webpack_require__(/*! ./AxisInterval */ "eeV2");

var _AxisInterval2 = _interopRequireDefault(_AxisInterval);

var _DateTimePicker = __webpack_require__(/*! ./DateTimePicker */ "PLYX");

var _DateTimePicker2 = _interopRequireDefault(_DateTimePicker);

var _TextPosition = __webpack_require__(/*! ./TextPosition */ "4cd8");

var _TextPosition2 = _interopRequireDefault(_TextPosition);

var _derived = __webpack_require__(/*! ./derived */ "5og8");

var _LineSelectors = __webpack_require__(/*! ./LineSelectors */ "6ugs");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.ShowInLegend = _derived.ShowInLegend;
exports.AnnotationArrowRef = _derived.AnnotationArrowRef;
exports.AnnotationRef = _derived.AnnotationRef;
exports.AxisAnchorDropdown = _derived.AxisAnchorDropdown;
exports.PositioningRef = _derived.PositioningRef;
exports.ArrowSelector = _ArrowSelector2.default;
exports.AxesRange = _derived.AxesRange;
exports.NTicks = _derived.NTicks;
exports.DTicks = _derived.DTicks;
exports.DTicksInterval = _derived.DTicksInterval;
exports.AxesSelector = _AxesSelector2.default;
exports.ColorPicker = _ColorPicker2.default;
exports.ColorscalePicker = _ColorscalePicker2.default;
exports.ColorwayPicker = _ColorwayPicker2.default;
exports.ContourNumeric = _derived.ContourNumeric;
exports.DataSelector = _DataSelector2.default;
exports.Dropdown = _Dropdown2.default;
exports.ErrorBars = _ErrorBars2.default;
exports.FillDropdown = _derived.FillDropdown;
exports.PieColorscalePicker = _PieColorscalePicker2.default;
exports.FilterOperation = _FilterOperation.FilterOperation;
exports.FilterValue = _FilterOperation.FilterValue;
exports.Flaglist = _Flaglist2.default;
exports.FontSelector = _FontSelector2.default;
exports.HoverInfo = _derived.HoverInfo;
exports.HoverTemplateText = _derived.HoverTemplateText;
exports.HoverTemplateSwitch = _derived.HoverTemplateSwitch;
exports.Info = _Info2.default;
exports.NumericFraction = _derived.NumericFraction;
exports.NumericFractionDomain = _derived.NumericFractionDomain;
exports.NumericFractionInverse = _derived.NumericFractionInverse;
exports.PositioningNumeric = _derived.PositioningNumeric;
exports.LineDashSelector = _LineSelectors.LineDashSelector;
exports.LineShapeSelector = _LineSelectors.LineShapeSelector;
exports.Numeric = _Numeric2.default;
exports.DualNumeric = _DualNumeric2.default;
exports.AxisRangeValue = _AxisRangeValue2.default;
exports.Text = _Text2.default;
exports.TickFormat = _derived.TickFormat;
exports.Radio = _Radio2.default;
exports.SymbolSelector = _SymbolSelector2.default;
exports.RangesliderVisible = _derived.RangesliderVisible;
exports.TextEditor = _TextEditor2.default;
exports.TraceOrientation = _derived.TraceOrientation;
exports.TraceSelector = _TraceSelector2.default;
exports.AxesCreator = _AxesCreator2.default;
exports.SubplotCreator = _SubplotCreator2.default;
exports.GroupCreator = _GroupCreator2.default;
exports.AxisOverlayDropdown = _derived.AxisOverlayDropdown;
exports.AxisSide = _derived.AxisSide;
exports.UpdateMenuButtons = _UpdateMenuButtons2.default;
exports.Dropzone = _Dropzone2.default;
exports.TextPosition = _TextPosition2.default;
exports.MarkerSize = _MarkerSize2.default;
exports.MarkerColor = _MarkerColor2.default;
exports.MultiColorPicker = _MultiColorPicker2.default;
exports.VisibilitySelect = _VisibilitySelect2.default;
exports.DropdownCustom = _DropdownCustom2.default;
exports.RectanglePositioner = _RectanglePositioner2.default;
exports.LocationSelector = _LocationSelector2.default;
exports.HoveronDropdown = _derived.HoveronDropdown;
exports.HovermodeDropdown = _derived.HovermodeDropdown;
exports.AxisInterval = _AxisInterval2.default;
exports.NumericOrDate = _NumericOrDate2.default;
exports.DateTimePicker = _DateTimePicker2.default;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ "OfWw":
/*!********************************************!*\
  !*** ./node_modules/browserify-aes/aes.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// based on the aes implimentation in triple sec
// https://github.com/keybase/triplesec
// which is in turn based on the one from crypto-js
// https://code.google.com/p/crypto-js/

var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer

function asUInt32Array (buf) {
  if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)

  var len = (buf.length / 4) | 0
  var out = new Array(len)

  for (var i = 0; i < len; i++) {
    out[i] = buf.readUInt32BE(i * 4)
  }

  return out
}

function scrubVec (v) {
  for (var i = 0; i < v.length; v++) {
    v[i] = 0
  }
}

function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) {
  var SUB_MIX0 = SUB_MIX[0]
  var SUB_MIX1 = SUB_MIX[1]
  var SUB_MIX2 = SUB_MIX[2]
  var SUB_MIX3 = SUB_MIX[3]

  var s0 = M[0] ^ keySchedule[0]
  var s1 = M[1] ^ keySchedule[1]
  var s2 = M[2] ^ keySchedule[2]
  var s3 = M[3] ^ keySchedule[3]
  var t0, t1, t2, t3
  var ksRow = 4

  for (var round = 1; round < nRounds; round++) {
    t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++]
    t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++]
    t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++]
    t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++]
    s0 = t0
    s1 = t1
    s2 = t2
    s3 = t3
  }

  t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]
  t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]
  t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]
  t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]
  t0 = t0 >>> 0
  t1 = t1 >>> 0
  t2 = t2 >>> 0
  t3 = t3 >>> 0

  return [t0, t1, t2, t3]
}

// AES constants
var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
var G = (function () {
  // Compute double table
  var d = new Array(256)
  for (var j = 0; j < 256; j++) {
    if (j < 128) {
      d[j] = j << 1
    } else {
      d[j] = (j << 1) ^ 0x11b
    }
  }

  var SBOX = []
  var INV_SBOX = []
  var SUB_MIX = [[], [], [], []]
  var INV_SUB_MIX = [[], [], [], []]

  // Walk GF(2^8)
  var x = 0
  var xi = 0
  for (var i = 0; i < 256; ++i) {
    // Compute sbox
    var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)
    sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63
    SBOX[x] = sx
    INV_SBOX[sx] = x

    // Compute multiplication
    var x2 = d[x]
    var x4 = d[x2]
    var x8 = d[x4]

    // Compute sub bytes, mix columns tables
    var t = (d[sx] * 0x101) ^ (sx * 0x1010100)
    SUB_MIX[0][x] = (t << 24) | (t >>> 8)
    SUB_MIX[1][x] = (t << 16) | (t >>> 16)
    SUB_MIX[2][x] = (t << 8) | (t >>> 24)
    SUB_MIX[3][x] = t

    // Compute inv sub bytes, inv mix columns tables
    t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)
    INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)
    INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)
    INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)
    INV_SUB_MIX[3][sx] = t

    if (x === 0) {
      x = xi = 1
    } else {
      x = x2 ^ d[d[d[x8 ^ x2]]]
      xi ^= d[d[xi]]
    }
  }

  return {
    SBOX: SBOX,
    INV_SBOX: INV_SBOX,
    SUB_MIX: SUB_MIX,
    INV_SUB_MIX: INV_SUB_MIX
  }
})()

function AES (key) {
  this._key = asUInt32Array(key)
  this._reset()
}

AES.blockSize = 4 * 4
AES.keySize = 256 / 8
AES.prototype.blockSize = AES.blockSize
AES.prototype.keySize = AES.keySize
AES.prototype._reset = function () {
  var keyWords = this._key
  var keySize = keyWords.length
  var nRounds = keySize + 6
  var ksRows = (nRounds + 1) * 4

  var keySchedule = []
  for (var k = 0; k < keySize; k++) {
    keySchedule[k] = keyWords[k]
  }

  for (k = keySize; k < ksRows; k++) {
    var t = keySchedule[k - 1]

    if (k % keySize === 0) {
      t = (t << 8) | (t >>> 24)
      t =
        (G.SBOX[t >>> 24] << 24) |
        (G.SBOX[(t >>> 16) & 0xff] << 16) |
        (G.SBOX[(t >>> 8) & 0xff] << 8) |
        (G.SBOX[t & 0xff])

      t ^= RCON[(k / keySize) | 0] << 24
    } else if (keySize > 6 && k % keySize === 4) {
      t =
        (G.SBOX[t >>> 24] << 24) |
        (G.SBOX[(t >>> 16) & 0xff] << 16) |
        (G.SBOX[(t >>> 8) & 0xff] << 8) |
        (G.SBOX[t & 0xff])
    }

    keySchedule[k] = keySchedule[k - keySize] ^ t
  }

  var invKeySchedule = []
  for (var ik = 0; ik < ksRows; ik++) {
    var ksR = ksRows - ik
    var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)]

    if (ik < 4 || ksR <= 4) {
      invKeySchedule[ik] = tt
    } else {
      invKeySchedule[ik] =
        G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^
        G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^
        G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^
        G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]]
    }
  }

  this._nRounds = nRounds
  this._keySchedule = keySchedule
  this._invKeySchedule = invKeySchedule
}

AES.prototype.encryptBlockRaw = function (M) {
  M = asUInt32Array(M)
  return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds)
}

AES.prototype.encryptBlock = function (M) {
  var out = this.encryptBlockRaw(M)
  var buf = Buffer.allocUnsafe(16)
  buf.writeUInt32BE(out[0], 0)
  buf.writeUInt32BE(out[1], 4)
  buf.writeUInt32BE(out[2], 8)
  buf.writeUInt32BE(out[3], 12)
  return buf
}

AES.prototype.decryptBlock = function (M) {
  M = asUInt32Array(M)

  // swap
  var m1 = M[1]
  M[1] = M[3]
  M[3] = m1

  var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds)
  var buf = Buffer.allocUnsafe(16)
  buf.writeUInt32BE(out[0], 0)
  buf.writeUInt32BE(out[3], 4)
  buf.writeUInt32BE(out[2], 8)
  buf.writeUInt32BE(out[1], 12)
  return buf
}

AES.prototype.scrub = function () {
  scrubVec(this._keySchedule)
  scrubVec(this._invKeySchedule)
  scrubVec(this._key)
}

module.exports.AES = AES


/***/ }),

/***/ "Oive":
/*!******************************************************!*\
  !*** ./node_modules/react-tabs/esm/helpers/count.js ***!
  \******************************************************/
/*! exports provided: getTabsCount, getPanelsCount */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTabsCount", function() { return getTabsCount; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPanelsCount", function() { return getPanelsCount; });
/* harmony import */ var _childrenDeepMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./childrenDeepMap */ "pMj9");
/* harmony import */ var _elementTypes__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./elementTypes */ "fxcN");


function getTabsCount(children) {
  var tabCount = 0;
  Object(_childrenDeepMap__WEBPACK_IMPORTED_MODULE_0__["deepForEach"])(children, function (child) {
    if (Object(_elementTypes__WEBPACK_IMPORTED_MODULE_1__["isTab"])(child)) tabCount++;
  });
  return tabCount;
}
function getPanelsCount(children) {
  var panelCount = 0;
  Object(_childrenDeepMap__WEBPACK_IMPORTED_MODULE_0__["deepForEach"])(children, function (child) {
    if (Object(_elementTypes__WEBPACK_IMPORTED_MODULE_1__["isTabPanel"])(child)) panelCount++;
  });
  return panelCount;
}

/***/ }),

/***/ "Ojgd":
/*!*************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_to-integer.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

// 7.1.4 ToInteger
var ceil = Math.ceil;
var floor = Math.floor;
module.exports = function (it) {
  return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};


/***/ }),

/***/ "OjkT":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/ne.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var symbolMap = {
    '1': '१',
    '2': '२',
    '3': '३',
    '4': '४',
    '5': '५',
    '6': '६',
    '7': '७',
    '8': '८',
    '9': '९',
    '0': '०'
},
numberMap = {
    '१': '1',
    '२': '2',
    '३': '3',
    '४': '4',
    '५': '5',
    '६': '6',
    '७': '7',
    '८': '8',
    '९': '9',
    '०': '0'
};

var ne = moment.defineLocale('ne', {
    months : 'जनवरी_फेब्रुवरी_मार्च_अप्रिल_मई_जुन_जुलाई_अगष्ट_सेप्टेम्बर_अक्टोबर_नोभेम्बर_डिसेम्बर'.split('_'),
    monthsShort : 'जन._फेब्रु._मार्च_अप्रि._मई_जुन_जुलाई._अग._सेप्ट._अक्टो._नोभे._डिसे.'.split('_'),
    monthsParseExact : true,
    weekdays : 'आइतबार_सोमबार_मङ्गलबार_बुधबार_बिहिबार_शुक्रबार_शनिबार'.split('_'),
    weekdaysShort : 'आइत._सोम._मङ्गल._बुध._बिहि._शुक्र._शनि.'.split('_'),
    weekdaysMin : 'आ._सो._मं._बु._बि._शु._श.'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'Aको h:mm बजे',
        LTS : 'Aको h:mm:ss बजे',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY, Aको h:mm बजे',
        LLLL : 'dddd, D MMMM YYYY, Aको h:mm बजे'
    },
    preparse: function (string) {
        return string.replace(/[१२३४५६७८९०]/g, function (match) {
            return numberMap[match];
        });
    },
    postformat: function (string) {
        return string.replace(/\d/g, function (match) {
            return symbolMap[match];
        });
    },
    meridiemParse: /राति|बिहान|दिउँसो|साँझ/,
    meridiemHour : function (hour, meridiem) {
        if (hour === 12) {
            hour = 0;
        }
        if (meridiem === 'राति') {
            return hour < 4 ? hour : hour + 12;
        } else if (meridiem === 'बिहान') {
            return hour;
        } else if (meridiem === 'दिउँसो') {
            return hour >= 10 ? hour : hour + 12;
        } else if (meridiem === 'साँझ') {
            return hour + 12;
        }
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 3) {
            return 'राति';
        } else if (hour < 12) {
            return 'बिहान';
        } else if (hour < 16) {
            return 'दिउँसो';
        } else if (hour < 20) {
            return 'साँझ';
        } else {
            return 'राति';
        }
    },
    calendar : {
        sameDay : '[आज] LT',
        nextDay : '[भोलि] LT',
        nextWeek : '[आउँदो] dddd[,] LT',
        lastDay : '[हिजो] LT',
        lastWeek : '[गएको] dddd[,] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : '%sमा',
        past : '%s अगाडि',
        s : 'केही क्षण',
        ss : '%d सेकेण्ड',
        m : 'एक मिनेट',
        mm : '%d मिनेट',
        h : 'एक घण्टा',
        hh : '%d घण्टा',
        d : 'एक दिन',
        dd : '%d दिन',
        M : 'एक महिना',
        MM : '%d महिना',
        y : 'एक बर्ष',
        yy : '%d बर्ष'
    },
    week : {
        dow : 0, // Sunday is the first day of the week.
        doy : 6  // The week that contains Jan 1st is the first week of the year.
    }
});

return ne;

})));


/***/ }),

/***/ "Ojt5":
/*!******************************************************************!*\
  !*** ./node_modules/react-color/lib/components/common/Raised.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Raised = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _merge = __webpack_require__(/*! lodash/merge */ "QkVN");

var _merge2 = _interopRequireDefault(_merge);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var Raised = exports.Raised = function Raised(_ref) {
  var zDepth = _ref.zDepth,
      radius = _ref.radius,
      background = _ref.background,
      children = _ref.children,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles;

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': {
      wrap: {
        position: 'relative',
        display: 'inline-block'
      },
      content: {
        position: 'relative'
      },
      bg: {
        absolute: '0px 0px 0px 0px',
        boxShadow: '0 ' + zDepth + 'px ' + zDepth * 4 + 'px rgba(0,0,0,.24)',
        borderRadius: radius,
        background: background
      }
    },
    'zDepth-0': {
      bg: {
        boxShadow: 'none'
      }
    },

    'zDepth-1': {
      bg: {
        boxShadow: '0 2px 10px rgba(0,0,0,.12), 0 2px 5px rgba(0,0,0,.16)'
      }
    },
    'zDepth-2': {
      bg: {
        boxShadow: '0 6px 20px rgba(0,0,0,.19), 0 8px 17px rgba(0,0,0,.2)'
      }
    },
    'zDepth-3': {
      bg: {
        boxShadow: '0 17px 50px rgba(0,0,0,.19), 0 12px 15px rgba(0,0,0,.24)'
      }
    },
    'zDepth-4': {
      bg: {
        boxShadow: '0 25px 55px rgba(0,0,0,.21), 0 16px 28px rgba(0,0,0,.22)'
      }
    },
    'zDepth-5': {
      bg: {
        boxShadow: '0 40px 77px rgba(0,0,0,.22), 0 27px 24px rgba(0,0,0,.2)'
      }
    },
    'square': {
      bg: {
        borderRadius: '0'
      }
    },
    'circle': {
      bg: {
        borderRadius: '50%'
      }
    }
  }, passedStyles), { 'zDepth-1': zDepth === 1 });

  return _react2.default.createElement(
    'div',
    { style: styles.wrap },
    _react2.default.createElement('div', { style: styles.bg }),
    _react2.default.createElement(
      'div',
      { style: styles.content },
      children
    )
  );
};

Raised.propTypes = {
  background: _propTypes2.default.string,
  zDepth: _propTypes2.default.oneOf([0, 1, 2, 3, 4, 5]),
  radius: _propTypes2.default.number,
  styles: _propTypes2.default.object
};

Raised.defaultProps = {
  background: '#fff',
  zDepth: 1,
  radius: 2,
  styles: {}
};

exports.default = Raised;

/***/ }),

/***/ "Onz0":
/*!***********************************************!*\
  !*** ./node_modules/core-util-is/lib/util.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(Buffer) {// Copyright Joyent, Inc. and other Node contributors.
//
// 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.

// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.

function isArray(arg) {
  if (Array.isArray) {
    return Array.isArray(arg);
  }
  return objectToString(arg) === '[object Array]';
}
exports.isArray = isArray;

function isBoolean(arg) {
  return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;

function isNull(arg) {
  return arg === null;
}
exports.isNull = isNull;

function isNullOrUndefined(arg) {
  return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;

function isNumber(arg) {
  return typeof arg === 'number';
}
exports.isNumber = isNumber;

function isString(arg) {
  return typeof arg === 'string';
}
exports.isString = isString;

function isSymbol(arg) {
  return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;

function isUndefined(arg) {
  return arg === void 0;
}
exports.isUndefined = isUndefined;

function isRegExp(re) {
  return objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;

function isObject(arg) {
  return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;

function isDate(d) {
  return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;

function isError(e) {
  return (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;

function isFunction(arg) {
  return typeof arg === 'function';
}
exports.isFunction = isFunction;

function isPrimitive(arg) {
  return arg === null ||
         typeof arg === 'boolean' ||
         typeof arg === 'number' ||
         typeof arg === 'string' ||
         typeof arg === 'symbol' ||  // ES6 symbol
         typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;

exports.isBuffer = Buffer.isBuffer;

function objectToString(o) {
  return Object.prototype.toString.call(o);
}

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../buffer/index.js */ "tjlA").Buffer))

/***/ }),

/***/ "Oq9H":
/*!*******************************************************************!*\
  !*** ./node_modules/@jupyterlab/application/lib/mimerenderers.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const docregistry_1 = __webpack_require__(/*! @jupyterlab/docregistry */ "jTF0");
const rendermime_1 = __webpack_require__(/*! @jupyterlab/rendermime */ "Towz");
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const properties_1 = __webpack_require__(/*! @phosphor/properties */ "3kwb");
const layoutrestorer_1 = __webpack_require__(/*! ./layoutrestorer */ "2F0p");
/* tslint:disable */
/**
 * The mime document tracker token.
 */
exports.IMimeDocumentTracker = new coreutils_1.Token('@jupyterlab/application:IMimeDocumentTracker');
/* tslint:enable */
/**
 * Create rendermime plugins for rendermime extension modules.
 */
function createRendermimePlugins(extensions) {
    const plugins = [];
    const namespace = 'application-mimedocuments';
    const tracker = new apputils_1.InstanceTracker({ namespace });
    extensions.forEach(mod => {
        let data = mod.default;
        // Handle CommonJS exports.
        if (!mod.hasOwnProperty('__esModule')) {
            data = mod;
        }
        if (!Array.isArray(data)) {
            data = [data];
        }
        data.forEach(item => {
            plugins.push(createRendermimePlugin(tracker, item));
        });
    });
    // Also add a meta-plugin handling state restoration
    // and exposing the mime document instance tracker.
    plugins.push({
        id: '@jupyterlab/application:mimedocument',
        requires: [layoutrestorer_1.ILayoutRestorer],
        provides: exports.IMimeDocumentTracker,
        autoStart: true,
        activate: (app, restorer) => {
            restorer.restore(tracker, {
                command: 'docmanager:open',
                args: widget => ({
                    path: widget.context.path,
                    factory: Private.factoryNameProperty.get(widget)
                }),
                name: widget => `${widget.context.path}:${Private.factoryNameProperty.get(widget)}`
            });
            return tracker;
        }
    });
    return plugins;
}
exports.createRendermimePlugins = createRendermimePlugins;
/**
 * Create rendermime plugins for rendermime extension modules.
 */
function createRendermimePlugin(tracker, item) {
    return {
        id: item.id,
        requires: [layoutrestorer_1.ILayoutRestorer, rendermime_1.IRenderMimeRegistry],
        autoStart: true,
        activate: (app, restorer, rendermime) => {
            // Add the mime renderer.
            if (item.rank !== undefined) {
                rendermime.addFactory(item.rendererFactory, item.rank);
            }
            else {
                rendermime.addFactory(item.rendererFactory);
            }
            // Handle the widget factory.
            if (!item.documentWidgetFactoryOptions) {
                return;
            }
            let registry = app.docRegistry;
            let options = [];
            if (Array.isArray(item.documentWidgetFactoryOptions)) {
                options = item.documentWidgetFactoryOptions;
            }
            else {
                options = [
                    item.documentWidgetFactoryOptions
                ];
            }
            if (item.fileTypes) {
                item.fileTypes.forEach(ft => {
                    app.docRegistry.addFileType(ft);
                });
            }
            options.forEach(option => {
                const toolbarFactory = option.toolbarFactory
                    ? (w) => option.toolbarFactory(w.content.renderer)
                    : undefined;
                let factory = new docregistry_1.MimeDocumentFactory({
                    renderTimeout: item.renderTimeout,
                    dataType: item.dataType,
                    rendermime,
                    modelName: option.modelName,
                    name: option.name,
                    primaryFileType: registry.getFileType(option.primaryFileType),
                    fileTypes: option.fileTypes,
                    defaultFor: option.defaultFor,
                    defaultRendered: option.defaultRendered,
                    toolbarFactory
                });
                registry.addWidgetFactory(factory);
                factory.widgetCreated.connect((sender, widget) => {
                    Private.factoryNameProperty.set(widget, factory.name);
                    // Notify the instance tracker if restore data needs to update.
                    widget.context.pathChanged.connect(() => {
                        tracker.save(widget);
                    });
                    tracker.add(widget);
                });
            });
        }
    };
}
exports.createRendermimePlugin = createRendermimePlugin;
/**
 * Private namespace for the module.
 */
var Private;
(function (Private) {
    /**
     * An attached property for keeping the factory name
     * that was used to create a mimedocument.
     */
    Private.factoryNameProperty = new properties_1.AttachedProperty({
        name: 'factoryName',
        create: () => undefined
    });
})(Private || (Private = {}));


/***/ }),

/***/ "Or5M":
/*!*************************************************************!*\
  !*** ./node_modules/@jupyterlab/docregistry/lib/default.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const codemirror_1 = __webpack_require__(/*! @jupyterlab/codemirror */ "ddNL");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const codeeditor_1 = __webpack_require__(/*! @jupyterlab/codeeditor */ "sLCx");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
/**
 * The default implementation of a document model.
 */
class DocumentModel extends codeeditor_1.CodeEditor.Model {
    /**
     * Construct a new document model.
     */
    constructor(languagePreference, modelDB) {
        super({ modelDB });
        this._defaultLang = '';
        this._dirty = false;
        this._readOnly = false;
        this._contentChanged = new signaling_1.Signal(this);
        this._stateChanged = new signaling_1.Signal(this);
        this._defaultLang = languagePreference || '';
        this.value.changed.connect(this.triggerContentChange, this);
    }
    /**
     * A signal emitted when the document content changes.
     */
    get contentChanged() {
        return this._contentChanged;
    }
    /**
     * A signal emitted when the document state changes.
     */
    get stateChanged() {
        return this._stateChanged;
    }
    /**
     * The dirty state of the document.
     */
    get dirty() {
        return this._dirty;
    }
    set dirty(newValue) {
        if (newValue === this._dirty) {
            return;
        }
        let oldValue = this._dirty;
        this._dirty = newValue;
        this.triggerStateChange({ name: 'dirty', oldValue, newValue });
    }
    /**
     * The read only state of the document.
     */
    get readOnly() {
        return this._readOnly;
    }
    set readOnly(newValue) {
        if (newValue === this._readOnly) {
            return;
        }
        let oldValue = this._readOnly;
        this._readOnly = newValue;
        this.triggerStateChange({ name: 'readOnly', oldValue, newValue });
    }
    /**
     * The default kernel name of the document.
     *
     * #### Notes
     * This is a read-only property.
     */
    get defaultKernelName() {
        return '';
    }
    /**
     * The default kernel language of the document.
     *
     * #### Notes
     * This is a read-only property.
     */
    get defaultKernelLanguage() {
        return this._defaultLang;
    }
    /**
     * Serialize the model to a string.
     */
    toString() {
        return this.value.text;
    }
    /**
     * Deserialize the model from a string.
     *
     * #### Notes
     * Should emit a [contentChanged] signal.
     */
    fromString(value) {
        this.value.text = value;
    }
    /**
     * Serialize the model to JSON.
     */
    toJSON() {
        return JSON.parse(this.value.text || 'null');
    }
    /**
     * Deserialize the model from JSON.
     *
     * #### Notes
     * Should emit a [contentChanged] signal.
     */
    fromJSON(value) {
        this.fromString(JSON.stringify(value));
    }
    /**
     * Initialize the model with its current state.
     */
    initialize() {
        return;
    }
    /**
     * Trigger a state change signal.
     */
    triggerStateChange(args) {
        this._stateChanged.emit(args);
    }
    /**
     * Trigger a content changed signal.
     */
    triggerContentChange() {
        this._contentChanged.emit(void 0);
        this.dirty = true;
    }
}
exports.DocumentModel = DocumentModel;
/**
 * An implementation of a model factory for text files.
 */
class TextModelFactory {
    constructor() {
        this._isDisposed = false;
    }
    /**
     * The name of the model type.
     *
     * #### Notes
     * This is a read-only property.
     */
    get name() {
        return 'text';
    }
    /**
     * The type of the file.
     *
     * #### Notes
     * This is a read-only property.
     */
    get contentType() {
        return 'file';
    }
    /**
     * The format of the file.
     *
     * This is a read-only property.
     */
    get fileFormat() {
        return 'text';
    }
    /**
     * Get whether the model factory has been disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources held by the model factory.
     */
    dispose() {
        this._isDisposed = true;
    }
    /**
     * Create a new model.
     *
     * @param languagePreference - An optional kernel language preference.
     *
     * @returns A new document model.
     */
    createNew(languagePreference, modelDB) {
        return new DocumentModel(languagePreference, modelDB);
    }
    /**
     * Get the preferred kernel language given a file path.
     */
    preferredLanguage(path) {
        let mode = codemirror_1.Mode.findByFileName(path);
        return mode && mode.mode;
    }
}
exports.TextModelFactory = TextModelFactory;
/**
 * An implementation of a model factory for base64 files.
 */
class Base64ModelFactory extends TextModelFactory {
    /**
     * The name of the model type.
     *
     * #### Notes
     * This is a read-only property.
     */
    get name() {
        return 'base64';
    }
    /**
     * The type of the file.
     *
     * #### Notes
     * This is a read-only property.
     */
    get contentType() {
        return 'file';
    }
    /**
     * The format of the file.
     *
     * This is a read-only property.
     */
    get fileFormat() {
        return 'base64';
    }
}
exports.Base64ModelFactory = Base64ModelFactory;
/**
 * The default implementation of a widget factory.
 */
class ABCWidgetFactory {
    /**
     * Construct a new `ABCWidgetFactory`.
     */
    constructor(options) {
        this._isDisposed = false;
        this._widgetCreated = new signaling_1.Signal(this);
        this._name = options.name;
        this._readOnly = options.readOnly === undefined ? false : options.readOnly;
        this._defaultFor = options.defaultFor ? options.defaultFor.slice() : [];
        this._defaultRendered = (options.defaultRendered || []).slice();
        this._fileTypes = options.fileTypes.slice();
        this._modelName = options.modelName || 'text';
        this._preferKernel = !!options.preferKernel;
        this._canStartKernel = !!options.canStartKernel;
        this._toolbarFactory = options.toolbarFactory;
    }
    /**
     * A signal emitted when a widget is created.
     */
    get widgetCreated() {
        return this._widgetCreated;
    }
    /**
     * Get whether the model factory has been disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources held by the document manager.
     */
    dispose() {
        this._isDisposed = true;
    }
    /**
     * Whether the widget factory is read only.
     */
    get readOnly() {
        return this._readOnly;
    }
    /**
     * The name of the widget to display in dialogs.
     */
    get name() {
        return this._name;
    }
    /**
     * The file types the widget can view.
     */
    get fileTypes() {
        return this._fileTypes.slice();
    }
    /**
     * The registered name of the model type used to create the widgets.
     */
    get modelName() {
        return this._modelName;
    }
    /**
     * The file types for which the factory should be the default.
     */
    get defaultFor() {
        return this._defaultFor.slice();
    }
    /**
     * The file types for which the factory should be the default for
     * rendering a document model, if different from editing.
     */
    get defaultRendered() {
        return this._defaultRendered.slice();
    }
    /**
     * Whether the widgets prefer having a kernel started.
     */
    get preferKernel() {
        return this._preferKernel;
    }
    /**
     * Whether the widgets can start a kernel when opened.
     */
    get canStartKernel() {
        return this._canStartKernel;
    }
    /**
     * Create a new widget given a document model and a context.
     *
     * #### Notes
     * It should emit the [widgetCreated] signal with the new widget.
     */
    createNew(context) {
        // Create the new widget
        const widget = this.createNewWidget(context);
        // Add toolbar items
        let items;
        if (this._toolbarFactory) {
            items = this._toolbarFactory(widget);
        }
        else {
            items = this.defaultToolbarFactory(widget);
        }
        items.forEach(({ name, widget: item }) => {
            widget.toolbar.addItem(name, item);
        });
        // Emit widget created signal
        this._widgetCreated.emit(widget);
        return widget;
    }
    /**
     * Default factory for toolbar items to be added after the widget is created.
     */
    defaultToolbarFactory(widget) {
        return [];
    }
}
exports.ABCWidgetFactory = ABCWidgetFactory;
/**
 * The class name added to a dirty widget.
 */
const DIRTY_CLASS = 'jp-mod-dirty';
/**
 * A document widget implementation.
 */
class DocumentWidget extends apputils_1.MainAreaWidget {
    constructor(options) {
        // Include the context ready promise in the widget reveal promise
        options.reveal = Promise.all([options.reveal, options.context.ready]);
        super(options);
        this.context = options.context;
        // Handle context path changes
        this.context.pathChanged.connect(this._onPathChanged, this);
        this._onPathChanged(this.context, this.context.path);
        // Listen for changes in the dirty state.
        this.context.model.stateChanged.connect(this._onModelStateChanged, this);
        this.context.ready.then(() => {
            this._handleDirtyState();
        });
    }
    /**
     * Handle a path change.
     */
    _onPathChanged(sender, path) {
        this.title.label = coreutils_1.PathExt.basename(sender.localPath);
    }
    /**
     * Handle a change to the context model state.
     */
    _onModelStateChanged(sender, args) {
        if (args.name === 'dirty') {
            this._handleDirtyState();
        }
    }
    /**
     * Handle the dirty state of the context model.
     */
    _handleDirtyState() {
        if (this.context.model.dirty) {
            this.title.className += ` ${DIRTY_CLASS}`;
        }
        else {
            this.title.className = this.title.className.replace(DIRTY_CLASS, '');
        }
    }
}
exports.DocumentWidget = DocumentWidget;


/***/ }),

/***/ "Oxv6":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/tg.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var suffixes = {
    0: '-ум',
    1: '-ум',
    2: '-юм',
    3: '-юм',
    4: '-ум',
    5: '-ум',
    6: '-ум',
    7: '-ум',
    8: '-ум',
    9: '-ум',
    10: '-ум',
    12: '-ум',
    13: '-ум',
    20: '-ум',
    30: '-юм',
    40: '-ум',
    50: '-ум',
    60: '-ум',
    70: '-ум',
    80: '-ум',
    90: '-ум',
    100: '-ум'
};

var tg = moment.defineLocale('tg', {
    months : 'январ_феврал_март_апрел_май_июн_июл_август_сентябр_октябр_ноябр_декабр'.split('_'),
    monthsShort : 'янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек'.split('_'),
    weekdays : 'якшанбе_душанбе_сешанбе_чоршанбе_панҷшанбе_ҷумъа_шанбе'.split('_'),
    weekdaysShort : 'яшб_дшб_сшб_чшб_пшб_ҷум_шнб'.split('_'),
    weekdaysMin : 'яш_дш_сш_чш_пш_ҷм_шб'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd, D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay : '[Имрӯз соати] LT',
        nextDay : '[Пагоҳ соати] LT',
        lastDay : '[Дирӯз соати] LT',
        nextWeek : 'dddd[и] [ҳафтаи оянда соати] LT',
        lastWeek : 'dddd[и] [ҳафтаи гузашта соати] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'баъди %s',
        past : '%s пеш',
        s : 'якчанд сония',
        m : 'як дақиқа',
        mm : '%d дақиқа',
        h : 'як соат',
        hh : '%d соат',
        d : 'як рӯз',
        dd : '%d рӯз',
        M : 'як моҳ',
        MM : '%d моҳ',
        y : 'як сол',
        yy : '%d сол'
    },
    meridiemParse: /шаб|субҳ|рӯз|бегоҳ/,
    meridiemHour: function (hour, meridiem) {
        if (hour === 12) {
            hour = 0;
        }
        if (meridiem === 'шаб') {
            return hour < 4 ? hour : hour + 12;
        } else if (meridiem === 'субҳ') {
            return hour;
        } else if (meridiem === 'рӯз') {
            return hour >= 11 ? hour : hour + 12;
        } else if (meridiem === 'бегоҳ') {
            return hour + 12;
        }
    },
    meridiem: function (hour, minute, isLower) {
        if (hour < 4) {
            return 'шаб';
        } else if (hour < 11) {
            return 'субҳ';
        } else if (hour < 16) {
            return 'рӯз';
        } else if (hour < 19) {
            return 'бегоҳ';
        } else {
            return 'шаб';
        }
    },
    dayOfMonthOrdinalParse: /\d{1,2}-(ум|юм)/,
    ordinal: function (number) {
        var a = number % 10,
            b = number >= 100 ? 100 : null;
        return number + (suffixes[number] || suffixes[a] || suffixes[b]);
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1th is the first week of the year.
    }
});

return tg;

})));


/***/ }),

/***/ "OyzN":
/*!*****************************************************************************!*\
  !*** ./node_modules/babel-runtime/core-js/object/get-own-property-names.js ***!
  \*****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = { "default": __webpack_require__(/*! core-js/library/fn/object/get-own-property-names */ "5biZ"), __esModule: true };

/***/ }),

/***/ "OyzV":
/*!**************************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/settingeditor/style/settingeditor.css ***!
  \**************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n:root {\n  --jp-private-settingeditor-debug-height: 28px;\n  --jp-private-settingeditor-key-width: 150px;\n  --jp-private-settingeditor-legend-height: 16px;\n  --jp-private-settingeditor-row-height: 16px;\n  --jp-private-settingeditor-switcher-height: 32px;\n  --jp-private-settingeditor-toolbar-height: 28px;\n  --jp-private-settingeditor-type-width: 75px;\n}\n\n#setting-editor {\n  min-width: 360px;\n  min-height: 240px;\n  background-color: var(--jp-layout-color0);\n  margin-top: -1px;\n  outline: none;\n  /* This is needed so that all font sizing of children done in ems is\n   * relative to this base size */\n  font-size: var(--jp-ui-font-size1);\n}\n\n#setting-editor > .p-Widget {\n  position: absolute;\n  top: 0;\n  bottom: 0;\n  left: 0;\n  right: 0;\n}\n\n#setting-editor .p-SplitPanel-handle {\n  background-color: var(--jp-border-color2);\n}\n\n#setting-editor .jp-SettingEditorInstructions {\n  text-align: center;\n}\n\n#setting-editor .jp-SettingEditorInstructions-icon {\n  display: inline-block;\n  background-size: 60px;\n  width: 60px;\n  height: 78px;\n  margin-right: 5px;\n}\n\n#setting-editor .jp-SettingEditorInstructions-title {\n  color: var(--jp-ui-font-color0);\n  font-size: 32px;\n  font-weight: 200;\n  line-height: 78px;\n  vertical-align: top;\n}\n\n#setting-editor .jp-SettingEditorInstructions-text {\n  color: var(--jp-ui-font-color0);\n  font-size: var(--jp-ui-font-size2);\n}\n\n#setting-editor .jp-PluginList {\n  min-width: 175px;\n  width: 175px;\n}\n\n#setting-editor .jp-PluginList-switcher {\n  height: var(--jp-private-settingeditor-switcher-height);\n  position: absolute;\n  top: 1px;\n  left: 0;\n  right: 0;\n}\n\n#setting-editor .jp-PluginList-switcher button {\n  background: var(--jp-layout-color2);\n  color: var(--jp-ui-font-color2);\n  border: 0;\n  border-bottom: 1px solid var(--jp-ui-font-color3);\n  margin: 0;\n  padding: 0;\n  height: var(--jp-private-settingeditor-switcher-height);\n  width: 50%;\n}\n\n#setting-editor .jp-PluginList-switcher button:first-child {\n  border-right: 1px solid var(--jp-ui-font-color3);\n}\n\n#setting-editor .jp-PluginList-switcher button:disabled {\n  background: var(--jp-layout-color1);\n  color: var(--jp-ui-font-color0);\n}\n\n#setting-editor .jp-PluginList ul {\n  background-color: var(--jp-layout-color1);\n  color: var(--jp-ui-font-color1);\n  font-size: var(--jp-ui-font-size1);\n  list-style-type: none;\n  margin: 0;\n  padding: 0;\n  overflow-y: auto;\n  position: absolute;\n  top: var(--jp-private-settingeditor-switcher-height);\n  bottom: 0;\n  left: 0;\n  right: 0;\n}\n\n#setting-editor .jp-PluginList li {\n  border: 1px solid transparent;\n  overflow: hidden;\n  padding: 2px 0 5px 5px;\n  text-overflow: ellipsis;\n  white-space: nowrap;\n}\n\n#setting-editor .jp-PluginList li:hover {\n  background-color: var(--jp-layout-color2);\n  border: 1px solid var(--jp-border-color2);\n}\n\n#setting-editor .jp-PluginList li.jp-mod-selected {\n  background-color: var(--jp-brand-color1);\n  color: white;\n  border: 1px solid var(--jp-brand-color1);\n}\n\n#setting-editor\n  ul.jp-PluginList\n  li.jp-mod-selected\n  span.jp-PluginList-icon.jp-FileIcon {\n  background-image: var(--jp-icon-file-selected);\n}\n\n#setting-editor .jp-PluginList-icon {\n  display: inline-block;\n  height: 20px;\n  width: 20px;\n  margin-right: 3px;\n  position: relative;\n  top: 3px;\n}\n\n#setting-editor .jp-SettingsRawEditor .jp-Toolbar {\n  color: var(--jp-ui-font-color0);\n  font-size: var(--jp-ui-font-size1);\n  height: var(--jp-private-settingeditor-toolbar-height);\n  max-height: var(--jp-private-settingeditor-toolbar-height);\n}\n\n#setting-editor .jp-SettingsRawEditor .jp-Toolbar-item {\n  margin-top: 2px;\n}\n\n#setting-editor\n  .jp-SettingsRawEditor.jp-mod-error\n  .jp-Toolbar-item.jp-BugIcon::after {\n  color: red;\n  content: '\\25CF'; /* Unicode circle character (error dot) */\n  font-size: 7px;\n  width: 100%;\n  height: 100%;\n  position: absolute;\n  top: 4px;\n  left: 6px;\n}\n\n#setting-editor .jp-SettingsRawEditor .jp-Inspector {\n  border-top: 2px solid var(--jp-layout-color2);\n  max-height: var(--jp-private-settingeditor-debug-height);\n}\n\n#setting-editor\n  .jp-SettingsRawEditor\n  .jp-InspectorItem.jp-SettingsDebug\n  .jp-RenderedHTMLCommon {\n  padding: 2px 5px 2px 0;\n  width: 100%;\n}\n\n#setting-editor\n  .jp-SettingsRawEditor\n  .jp-InspectorItem.jp-SettingsDebug\n  .jp-RenderedHTMLCommon\n  p {\n  text-align: right;\n}\n\n#setting-editor .jp-SettingsTableEditor {\n  border: 1px solid var(--jp-brand-color1);\n  margin: 0;\n  padding: 0;\n}\n\n#setting-editor .jp-SettingsTableEditor legend {\n  color: var(--jp-brand-color1);\n  font-size: 70%;\n  font-weight: bold;\n  margin-left: 15px;\n  height: var(--jp-private-settingeditor-legend-height);\n}\n\n#setting-editor .jp-SettingsTableEditor-wrapper {\n  position: absolute;\n  top: var(--jp-private-settingeditor-legend-height);\n  bottom: 0;\n  overflow-y: auto;\n}\n\n#setting-editor .jp-SettingsTableEditor table {\n  table-layout: fixed;\n  color: var(--jp-ui-font-color1);\n  font-size: var(--jp-ui-font-size1);\n  padding: 2px;\n  width: calc(100% - 4px);\n  overflow: hidden;\n}\n\n#setting-editor .jp-SettingsTableEditor tr {\n  color: var(--jp-ui-font-color2);\n  height: var(--jp-private-settingeditor-row-height);\n  overflow: hidden;\n}\n\n#setting-editor .jp-SettingsTableEditor th {\n  background-color: var(--jp-layout-color3);\n  border: 1px solid transparent;\n  font-weight: bold;\n  height: var(--jp-private-settingeditor-row-height);\n}\n\n#setting-editor .jp-SettingsTableEditor td {\n  border: 1px solid transparent;\n  height: var(--jp-private-settingeditor-row-height);\n}\n\n#setting-editor .jp-SettingsTableEditor th.jp-SettingsTableEditor-key {\n  width: var(--jp-private-settingeditor-key-width);\n}\n\n#setting-editor .jp-SettingsTableEditor th.jp-SettingsTableEditor-type {\n  width: var(--jp-private-settingeditor-type-width);\n}\n\n#setting-editor .jp-SettingsTableEditor td.jp-SettingsTableEditor-key {\n  overflow: hidden;\n  white-space: nowrap;\n  text-overflow: ellipsis;\n}\n\n#setting-editor .jp-SettingsTableEditor td.jp-SettingsTableEditor-value {\n  overflow: hidden;\n  white-space: nowrap;\n  text-overflow: ellipsis;\n}\n\n#setting-editor .jp-SettingsTableEditor td.jp-SettingsTableEditor-type {\n  text-align: right;\n}\n", ""]);

// exports


/***/ }),

/***/ "Oz5i":
/*!*******************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/connectRangeSelectorToAxis.js ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

exports.default = connectRangeSelectorToAxis;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _lib = __webpack_require__(/*! ../lib */ "RXjw");

var _constants = __webpack_require__(/*! ./constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function connectRangeSelectorToAxis(WrappedComponent) {
  var RangeSelectorConnectedComponent = function (_Component) {
    _inherits(RangeSelectorConnectedComponent, _Component);

    function RangeSelectorConnectedComponent(props, context) {
      _classCallCheck(this, RangeSelectorConnectedComponent);

      var _this = _possibleConstructorReturn(this, (RangeSelectorConnectedComponent.__proto__ || Object.getPrototypeOf(RangeSelectorConnectedComponent)).call(this, props, context));

      _this.deleteRangeselector = _this.deleteRangeselector.bind(_this);
      _this.updateRangeselector = _this.updateRangeselector.bind(_this);
      _this.setLocals(props, context);
      return _this;
    }

    _createClass(RangeSelectorConnectedComponent, [{
      key: 'componentWillReceiveProps',
      value: function componentWillReceiveProps(nextProps, nextContext) {
        this.setLocals(nextProps, nextContext);
      }
    }, {
      key: 'setLocals',
      value: function setLocals(props, context) {
        var rangeselectorIndex = props.rangeselectorIndex;
        var container = context.container,
            fullContainer = context.fullContainer;


        var rangeselectors = container.rangeselector ? container.rangeselector.buttons || [] : [];
        var fullRangeselectors = fullContainer.rangeselector ? fullContainer.rangeselector.buttons || [] : [];
        this.container = rangeselectors[rangeselectorIndex];
        this.fullContainer = fullRangeselectors[rangeselectorIndex];
      }
    }, {
      key: 'getChildContext',
      value: function getChildContext() {
        var _this2 = this;

        return {
          getValObject: function getValObject(attr) {
            return !_this2.context.getValObject ? null : _this2.context.getValObject('rangeselector.buttons[].' + attr);
          },
          updateContainer: this.updateRangeselector,
          deleteContainer: this.deleteRangeselector,
          container: this.container,
          fullContainer: this.fullContainer
        };
      }
    }, {
      key: 'updateRangeselector',
      value: function updateRangeselector(update) {
        var newUpdate = {};
        var rangeselectorIndex = this.props.rangeselectorIndex;

        for (var key in update) {
          var newkey = 'rangeselector.buttons[' + rangeselectorIndex + '].' + key;
          newUpdate[newkey] = update[key];
        }
        this.context.updateContainer(newUpdate);
      }
    }, {
      key: 'deleteRangeselector',
      value: function deleteRangeselector() {
        if (this.context.onUpdate) {
          this.context.onUpdate({
            type: _constants.EDITOR_ACTIONS.DELETE_RANGESELECTOR,
            payload: {
              axisId: this.context.fullContainer._name,
              rangeselectorIndex: this.props.rangeselectorIndex
            }
          });
        }
      }
    }, {
      key: 'render',
      value: function render() {
        return _react2.default.createElement(WrappedComponent, this.props);
      }
    }]);

    return RangeSelectorConnectedComponent;
  }(_react.Component);

  RangeSelectorConnectedComponent.displayName = 'RangeSelectorConnected' + (0, _lib.getDisplayName)(WrappedComponent);

  RangeSelectorConnectedComponent.propTypes = {
    rangeselectorIndex: _propTypes2.default.number.isRequired
  };

  RangeSelectorConnectedComponent.contextTypes = {
    container: _propTypes2.default.object,
    fullContainer: _propTypes2.default.object,
    data: _propTypes2.default.array,
    onUpdate: _propTypes2.default.func,
    updateContainer: _propTypes2.default.func,
    getValObject: _propTypes2.default.func
  };

  RangeSelectorConnectedComponent.childContextTypes = {
    updateContainer: _propTypes2.default.func,
    deleteContainer: _propTypes2.default.func,
    container: _propTypes2.default.object,
    fullContainer: _propTypes2.default.object,
    getValObject: _propTypes2.default.func
  };

  var plotly_editor_traits = WrappedComponent.plotly_editor_traits;

  RangeSelectorConnectedComponent.plotly_editor_traits = plotly_editor_traits;

  return RangeSelectorConnectedComponent;
}
//# sourceMappingURL=connectRangeSelectorToAxis.js.map

/***/ }),

/***/ "P/XJ":
/*!************************************************************!*\
  !*** ./node_modules/plotly.js/src/plot_api/plot_config.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



/**
 * This will be transferred over to gd and overridden by
 * config args to Plotly.plot.
 *
 * The defaults are the appropriate settings for plotly.js,
 * so we get the right experience without any config argument.
 *
 * N.B. the config options are not coerced using Lib.coerce so keys
 * like `valType` and `values` are only set for documentation purposes
 * at the moment.
 */

var configAttributes = {
    staticPlot: {
        valType: 'boolean',
        dflt: false,
        description: [
            'Determines whether the graphs are interactive or not.',
            'If *false*, no interactivity, for export or image generation.'
        ].join(' ')
    },

    plotlyServerURL: {
        valType: 'string',
        dflt: 'https://plot.ly',
        description: [
            'Sets base URL for the \'Edit in Chart Studio\' (aka sendDataToCloud) mode bar button',
            'and the showLink/sendData on-graph link'
        ].join(' ')
    },

    editable: {
        valType: 'boolean',
        dflt: false,
        description: [
            'Determines whether the graph is editable or not.',
            'Sets all pieces of `edits`',
            'unless a separate `edits` config item overrides individual parts.'
        ].join(' ')
    },
    edits: {
        annotationPosition: {
            valType: 'boolean',
            dflt: false,
            description: [
                'Determines if the main anchor of the annotation is editable.',
                'The main anchor corresponds to the',
                'text (if no arrow) or the arrow (which drags the whole thing leaving',
                'the arrow length & direction unchanged).'
            ].join(' ')
        },
        annotationTail: {
            valType: 'boolean',
            dflt: false,
            description: [
                'Has only an effect for annotations with arrows.',
                'Enables changing the length and direction of the arrow.'
            ].join(' ')
        },
        annotationText: {
            valType: 'boolean',
            dflt: false,
            description: 'Enables editing annotation text.'
        },
        axisTitleText: {
            valType: 'boolean',
            dflt: false,
            description: 'Enables editing axis title text.'
        },
        colorbarPosition: {
            valType: 'boolean',
            dflt: false,
            description: 'Enables moving colorbars.'
        },
        colorbarTitleText: {
            valType: 'boolean',
            dflt: false,
            description: 'Enables editing colorbar title text.'
        },
        legendPosition: {
            valType: 'boolean',
            dflt: false,
            description: 'Enables moving the legend.'
        },
        legendText: {
            valType: 'boolean',
            dflt: false,
            description: 'Enables editing the trace name fields from the legend'
        },
        shapePosition: {
            valType: 'boolean',
            dflt: false,
            description: 'Enables moving shapes.'
        },
        titleText: {
            valType: 'boolean',
            dflt: false,
            description: 'Enables editing the global layout title.'
        }
    },

    autosizable: {
        valType: 'boolean',
        dflt: false,
        description: [
            'Determines whether the graphs are plotted with respect to',
            'layout.autosize:true and infer its container size.'
        ].join(' ')
    },
    responsive: {
        valType: 'boolean',
        dflt: false,
        description: [
            'Determines whether to change the layout size when window is resized.',
            'In v2, this option will be removed and will always be true.'
        ].join(' ')
    },
    fillFrame: {
        valType: 'boolean',
        dflt: false,
        description: [
            'When `layout.autosize` is turned on, determines whether the graph',
            'fills the container (the default) or the screen (if set to *true*).'
        ].join(' ')
    },
    frameMargins: {
        valType: 'number',
        dflt: 0,
        min: 0,
        max: 0.5,
        description: [
            'When `layout.autosize` is turned on, set the frame margins',
            'in fraction of the graph size.'
        ].join(' ')
    },

    scrollZoom: {
        valType: 'flaglist',
        flags: ['cartesian', 'gl3d', 'geo', 'mapbox'],
        extras: [true, false],
        dflt: 'gl3d+geo+mapbox',
        description: [
            'Determines whether mouse wheel or two-finger scroll zooms is enable.',
            'Turned on by default for gl3d, geo and mapbox subplots',
            '(as these subplot types do not have zoombox via pan),',
            'but turned off by default for cartesian subplots.',
            'Set `scrollZoom` to *false* to disable scrolling for all subplots.'
        ].join(' ')
    },
    doubleClick: {
        valType: 'enumerated',
        values: [false, 'reset', 'autosize', 'reset+autosize'],
        dflt: 'reset+autosize',
        description: [
            'Sets the double click interaction mode.',
            'Has an effect only in cartesian plots.',
            'If *false*, double click is disable.',
            'If *reset*, double click resets the axis ranges to their initial values.',
            'If *autosize*, double click set the axis ranges to their autorange values.',
            'If *reset+autosize*, the odd double clicks resets the axis ranges',
            'to their initial values and even double clicks set the axis ranges',
            'to their autorange values.'
        ].join(' ')
    },

    showAxisDragHandles: {
        valType: 'boolean',
        dflt: true,
        description: [
            'Set to *false* to omit cartesian axis pan/zoom drag handles.'
        ].join(' ')
    },
    showAxisRangeEntryBoxes: {
        valType: 'boolean',
        dflt: true,
        description: [
            'Set to *false* to omit direct range entry at the pan/zoom drag points,',
            'note that `showAxisDragHandles` must be enabled to have an effect.'
        ].join(' ')
    },

    showTips: {
        valType: 'boolean',
        dflt: true,
        description: [
            'Determines whether or not tips are shown while interacting',
            'with the resulting graphs.'
        ].join(' ')
    },

    showLink: {
        valType: 'boolean',
        dflt: false,
        description: [
            'Determines whether a link to plot.ly is displayed',
            'at the bottom right corner of resulting graphs.',
            'Use with `sendData` and `linkText`.'
        ].join(' ')
    },
    linkText: {
        valType: 'string',
        dflt: 'Edit chart',
        noBlank: true,
        description: [
            'Sets the text appearing in the `showLink` link.'
        ].join(' ')
    },
    sendData: {
        valType: 'boolean',
        dflt: true,
        description: [
            'If *showLink* is true, does it contain data',
            'just link to a plot.ly file?'
        ].join(' ')
    },
    showSources: {
        valType: 'any',
        dflt: false,
        description: [
            'Adds a source-displaying function to show sources on',
            'the resulting graphs.'
        ].join(' ')
    },

    displayModeBar: {
        valType: 'enumerated',
        values: ['hover', true, false],
        dflt: 'hover',
        description: [
            'Determines the mode bar display mode.',
            'If *true*, the mode bar is always visible.',
            'If *false*, the mode bar is always hidden.',
            'If *hover*, the mode bar is visible while the mouse cursor',
            'is on the graph container.'
        ].join(' ')
    },
    showSendToCloud: {
        valType: 'boolean',
        dflt: false,
        description: [
            'Should we include a ModeBar button, labeled "Edit in Chart Studio",',
            'that sends this chart to plot.ly or another plotly server as specified',
            'by `plotlyServerURL` for editing, export, etc? Prior to version 1.43.0',
            'this button was included by default, now it is opt-in using this flag.',
            'Note that this button can (depending on `plotlyServerURL`) send your data',
            'to an external server. However that server does not persist your data',
            'until you arrive at the Chart Studio and explicitly click "Save".'
        ].join(' ')
    },
    modeBarButtonsToRemove: {
        valType: 'any',
        dflt: [],
        description: [
            'Remove mode bar buttons by name.',
            'See ./components/modebar/buttons.js for the list of names.'
        ].join(' ')
    },
    modeBarButtonsToAdd: {
        valType: 'any',
        dflt: [],
        description: [
            'Add mode bar button using config objects',
            'See ./components/modebar/buttons.js for list of arguments.'
        ].join(' ')
    },
    modeBarButtons: {
        valType: 'any',
        dflt: false,
        description: [
            'Define fully custom mode bar buttons as nested array,',
            'where the outer arrays represents button groups, and',
            'the inner arrays have buttons config objects or names of default buttons',
            'See ./components/modebar/buttons.js for more info.'
        ].join(' ')
    },
    toImageButtonOptions: {
        valType: 'any',
        dflt: {},
        description: [
            'Statically override options for toImage modebar button',
            'allowed keys are format, filename, width, height, scale',
            'see ../components/modebar/buttons.js'
        ].join(' ')
    },
    displaylogo: {
        valType: 'boolean',
        dflt: true,
        description: [
            'Determines whether or not the plotly logo is displayed',
            'on the end of the mode bar.'
        ].join(' ')
    },
    watermark: {
        valType: 'boolean',
        dflt: false,
        description: 'watermark the images with the company\'s logo'
    },

    plotGlPixelRatio: {
        valType: 'number',
        dflt: 2,
        min: 1,
        max: 4,
        description: [
            'Set the pixel ratio during WebGL image export.',
            'This config option was formerly named `plot3dPixelRatio`',
            'which is now deprecated.'
        ].join(' ')
    },

    setBackground: {
        valType: 'any',
        dflt: 'transparent',
        description: [
            'Set function to add the background color (i.e. `layout.paper_color`)',
            'to a different container.',
            'This function take the graph div as first argument and the current background',
            'color as second argument.',
            'Alternatively, set to string *opaque* to ensure there is white behind it.'
        ].join(' ')
    },

    topojsonURL: {
        valType: 'string',
        noBlank: true,
        dflt: 'https://cdn.plot.ly/',
        description: [
            'Set the URL to topojson used in geo charts.',
            'By default, the topojson files are fetched from cdn.plot.ly.',
            'For example, set this option to:',
            '<path-to-plotly.js>/dist/topojson/',
            'to render geographical feature using the topojson files',
            'that ship with the plotly.js module.'
        ].join(' ')
    },

    mapboxAccessToken: {
        valType: 'string',
        dflt: null,
        description: [
            'Mapbox access token (required to plot mapbox trace types)',
            'If using an Mapbox Atlas server, set this option to \'\'',
            'so that plotly.js won\'t attempt to authenticate to the public Mapbox server.'
        ].join(' ')
    },

    logging: {
        valType: 'boolean',
        dflt: 1,
        description: [
            'Turn all console logging on or off (errors will be thrown)',
            'This should ONLY be set via Plotly.setPlotConfig',
            'Available levels:',
            '0: no logs',
            '1: warnings and errors, but not informational messages',
            '2: verbose logs'
        ].join(' ')
    },

    queueLength: {
        valType: 'integer',
        min: 0,
        dflt: 0,
        description: 'Sets the length of the undo/redo queue.'
    },

    globalTransforms: {
        valType: 'any',
        dflt: [],
        description: [
            'Set global transform to be applied to all traces with no',
            'specification needed'
        ].join(' ')
    },

    locale: {
        valType: 'string',
        dflt: 'en-US',
        description: [
            'Which localization should we use?',
            'Should be a string like \'en\' or \'en-US\'.'
        ].join(' ')
    },

    locales: {
        valType: 'any',
        dflt: {},
        description: [
            'Localization definitions',
            'Locales can be provided either here (specific to one chart) or globally',
            'by registering them as modules.',
            'Should be an object of objects {locale: {dictionary: {...}, format: {...}}}',
            '{',
            '  da: {',
            '      dictionary: {\'Reset axes\': \'Nulstil aksler\', ...},',
            '      format: {months: [...], shortMonths: [...]}',
            '  },',
            '  ...',
            '}',
            'All parts are optional. When looking for translation or format fields, we',
            'look first for an exact match in a config locale, then in a registered',
            'module. If those fail, we strip off any regionalization (\'en-US\' -> \'en\')',
            'and try each (config, registry) again. The final fallback for translation',
            'is untranslated (which is US English) and for formats is the base English',
            '(the only consequence being the last fallback date format %x is DD/MM/YYYY',
            'instead of MM/DD/YYYY). Currently `grouping` and `currency` are ignored',
            'for our automatic number formatting, but can be used in custom formats.'
        ].join(' ')
    }
};

var dfltConfig = {};

function crawl(src, target) {
    for(var k in src) {
        var obj = src[k];
        if(obj.valType) {
            target[k] = obj.dflt;
        } else {
            if(!target[k]) {
                target[k] = {};
            }
            crawl(obj, target[k]);
        }
    }
}

crawl(configAttributes, dfltConfig);

module.exports = {
    configAttributes: configAttributes,
    dfltConfig: dfltConfig
};


/***/ }),

/***/ "P2KE":
/*!**********************************************!*\
  !*** ./node_modules/browserify-aes/ghash.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer
var ZEROES = Buffer.alloc(16, 0)

function toArray (buf) {
  return [
    buf.readUInt32BE(0),
    buf.readUInt32BE(4),
    buf.readUInt32BE(8),
    buf.readUInt32BE(12)
  ]
}

function fromArray (out) {
  var buf = Buffer.allocUnsafe(16)
  buf.writeUInt32BE(out[0] >>> 0, 0)
  buf.writeUInt32BE(out[1] >>> 0, 4)
  buf.writeUInt32BE(out[2] >>> 0, 8)
  buf.writeUInt32BE(out[3] >>> 0, 12)
  return buf
}

function GHASH (key) {
  this.h = key
  this.state = Buffer.alloc(16, 0)
  this.cache = Buffer.allocUnsafe(0)
}

// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html
// by Juho Vähä-Herttua
GHASH.prototype.ghash = function (block) {
  var i = -1
  while (++i < block.length) {
    this.state[i] ^= block[i]
  }
  this._multiply()
}

GHASH.prototype._multiply = function () {
  var Vi = toArray(this.h)
  var Zi = [0, 0, 0, 0]
  var j, xi, lsbVi
  var i = -1
  while (++i < 128) {
    xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0
    if (xi) {
      // Z_i+1 = Z_i ^ V_i
      Zi[0] ^= Vi[0]
      Zi[1] ^= Vi[1]
      Zi[2] ^= Vi[2]
      Zi[3] ^= Vi[3]
    }

    // Store the value of LSB(V_i)
    lsbVi = (Vi[3] & 1) !== 0

    // V_i+1 = V_i >> 1
    for (j = 3; j > 0; j--) {
      Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31)
    }
    Vi[0] = Vi[0] >>> 1

    // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
    if (lsbVi) {
      Vi[0] = Vi[0] ^ (0xe1 << 24)
    }
  }
  this.state = fromArray(Zi)
}

GHASH.prototype.update = function (buf) {
  this.cache = Buffer.concat([this.cache, buf])
  var chunk
  while (this.cache.length >= 16) {
    chunk = this.cache.slice(0, 16)
    this.cache = this.cache.slice(16)
    this.ghash(chunk)
  }
}

GHASH.prototype.final = function (abl, bl) {
  if (this.cache.length) {
    this.ghash(Buffer.concat([this.cache, ZEROES], 16))
  }

  this.ghash(fromArray([0, abl, 0, bl]))
  return this.state
}

module.exports = GHASH


/***/ }),

/***/ "P2i7":
/*!************************************************!*\
  !*** ./node_modules/plotlywidget/src/index.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// Export widget models and views, and the npm package version number.
module.exports = __webpack_require__(/*! ./Figure.js */ "siaY");
module.exports['version'] = __webpack_require__(/*! ../package.json */ "Ri4F").version;


/***/ }),

/***/ "P2sY":
/*!*************************************************************!*\
  !*** ./node_modules/babel-runtime/core-js/object/assign.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = { "default": __webpack_require__(/*! core-js/library/fn/object/assign */ "UbbE"), __esModule: true };

/***/ }),

/***/ "P7XM":
/*!***************************************************!*\
  !*** ./node_modules/inherits/inherits_browser.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

if (typeof Object.create === 'function') {
  // implementation from standard node.js 'util' module
  module.exports = function inherits(ctor, superCtor) {
    ctor.super_ = superCtor
    ctor.prototype = Object.create(superCtor.prototype, {
      constructor: {
        value: ctor,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
  };
} else {
  // old school shim for old browsers
  module.exports = function inherits(ctor, superCtor) {
    ctor.super_ = superCtor
    var TempCtor = function () {}
    TempCtor.prototype = superCtor.prototype
    ctor.prototype = new TempCtor()
    ctor.prototype.constructor = ctor
  }
}


/***/ }),

/***/ "PA2r":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/cs.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var months = 'leden_únor_březen_duben_květen_červen_červenec_srpen_září_říjen_listopad_prosinec'.split('_'),
    monthsShort = 'led_úno_bře_dub_kvě_čvn_čvc_srp_zář_říj_lis_pro'.split('_');
function plural(n) {
    return (n > 1) && (n < 5) && (~~(n / 10) !== 1);
}
function translate(number, withoutSuffix, key, isFuture) {
    var result = number + ' ';
    switch (key) {
        case 's':  // a few seconds / in a few seconds / a few seconds ago
            return (withoutSuffix || isFuture) ? 'pár sekund' : 'pár sekundami';
        case 'ss': // 9 seconds / in 9 seconds / 9 seconds ago
            if (withoutSuffix || isFuture) {
                return result + (plural(number) ? 'sekundy' : 'sekund');
            } else {
                return result + 'sekundami';
            }
            break;
        case 'm':  // a minute / in a minute / a minute ago
            return withoutSuffix ? 'minuta' : (isFuture ? 'minutu' : 'minutou');
        case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago
            if (withoutSuffix || isFuture) {
                return result + (plural(number) ? 'minuty' : 'minut');
            } else {
                return result + 'minutami';
            }
            break;
        case 'h':  // an hour / in an hour / an hour ago
            return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou');
        case 'hh': // 9 hours / in 9 hours / 9 hours ago
            if (withoutSuffix || isFuture) {
                return result + (plural(number) ? 'hodiny' : 'hodin');
            } else {
                return result + 'hodinami';
            }
            break;
        case 'd':  // a day / in a day / a day ago
            return (withoutSuffix || isFuture) ? 'den' : 'dnem';
        case 'dd': // 9 days / in 9 days / 9 days ago
            if (withoutSuffix || isFuture) {
                return result + (plural(number) ? 'dny' : 'dní');
            } else {
                return result + 'dny';
            }
            break;
        case 'M':  // a month / in a month / a month ago
            return (withoutSuffix || isFuture) ? 'měsíc' : 'měsícem';
        case 'MM': // 9 months / in 9 months / 9 months ago
            if (withoutSuffix || isFuture) {
                return result + (plural(number) ? 'měsíce' : 'měsíců');
            } else {
                return result + 'měsíci';
            }
            break;
        case 'y':  // a year / in a year / a year ago
            return (withoutSuffix || isFuture) ? 'rok' : 'rokem';
        case 'yy': // 9 years / in 9 years / 9 years ago
            if (withoutSuffix || isFuture) {
                return result + (plural(number) ? 'roky' : 'let');
            } else {
                return result + 'lety';
            }
            break;
    }
}

var cs = moment.defineLocale('cs', {
    months : months,
    monthsShort : monthsShort,
    monthsParse : (function (months, monthsShort) {
        var i, _monthsParse = [];
        for (i = 0; i < 12; i++) {
            // use custom parser to solve problem with July (červenec)
            _monthsParse[i] = new RegExp('^' + months[i] + '$|^' + monthsShort[i] + '$', 'i');
        }
        return _monthsParse;
    }(months, monthsShort)),
    shortMonthsParse : (function (monthsShort) {
        var i, _shortMonthsParse = [];
        for (i = 0; i < 12; i++) {
            _shortMonthsParse[i] = new RegExp('^' + monthsShort[i] + '$', 'i');
        }
        return _shortMonthsParse;
    }(monthsShort)),
    longMonthsParse : (function (months) {
        var i, _longMonthsParse = [];
        for (i = 0; i < 12; i++) {
            _longMonthsParse[i] = new RegExp('^' + months[i] + '$', 'i');
        }
        return _longMonthsParse;
    }(months)),
    weekdays : 'neděle_pondělí_úterý_středa_čtvrtek_pátek_sobota'.split('_'),
    weekdaysShort : 'ne_po_út_st_čt_pá_so'.split('_'),
    weekdaysMin : 'ne_po_út_st_čt_pá_so'.split('_'),
    longDateFormat : {
        LT: 'H:mm',
        LTS : 'H:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D. MMMM YYYY',
        LLL : 'D. MMMM YYYY H:mm',
        LLLL : 'dddd D. MMMM YYYY H:mm',
        l : 'D. M. YYYY'
    },
    calendar : {
        sameDay: '[dnes v] LT',
        nextDay: '[zítra v] LT',
        nextWeek: function () {
            switch (this.day()) {
                case 0:
                    return '[v neděli v] LT';
                case 1:
                case 2:
                    return '[v] dddd [v] LT';
                case 3:
                    return '[ve středu v] LT';
                case 4:
                    return '[ve čtvrtek v] LT';
                case 5:
                    return '[v pátek v] LT';
                case 6:
                    return '[v sobotu v] LT';
            }
        },
        lastDay: '[včera v] LT',
        lastWeek: function () {
            switch (this.day()) {
                case 0:
                    return '[minulou neděli v] LT';
                case 1:
                case 2:
                    return '[minulé] dddd [v] LT';
                case 3:
                    return '[minulou středu v] LT';
                case 4:
                case 5:
                    return '[minulý] dddd [v] LT';
                case 6:
                    return '[minulou sobotu v] LT';
            }
        },
        sameElse: 'L'
    },
    relativeTime : {
        future : 'za %s',
        past : 'před %s',
        s : translate,
        ss : translate,
        m : translate,
        mm : translate,
        h : translate,
        hh : translate,
        d : translate,
        dd : translate,
        M : translate,
        MM : translate,
        y : translate,
        yy : translate
    },
    dayOfMonthOrdinalParse : /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return cs;

})));


/***/ }),

/***/ "PB3p":
/*!*******************************************************!*\
  !*** ./node_modules/@phosphor/algorithm/lib/array.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * The namespace for array-specific algorithms.
 */
var ArrayExt;
(function (ArrayExt) {
    /**
     * Find the index of the first occurrence of a value in an array.
     *
     * @param array - The array-like object to search.
     *
     * @param value - The value to locate in the array. Values are
     *   compared using strict `===` equality.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The index of the first occurrence of the value, or `-1`
     *   if the value is not found.
     *
     * #### Notes
     * If `stop < start` the search will wrap at the end of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * A `start` or `stop` which is non-integral.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@phosphor/algorithm';
     *
     * let data = ['one', 'two', 'three', 'four', 'one'];
     * ArrayExt.firstIndexOf(data, 'red');        // -1
     * ArrayExt.firstIndexOf(data, 'one');        // 0
     * ArrayExt.firstIndexOf(data, 'one', 1);     // 4
     * ArrayExt.firstIndexOf(data, 'two', 2);     // -1
     * ArrayExt.firstIndexOf(data, 'two', 2, 1);  // 1
     * ```
     */
    function firstIndexOf(array, value, start, stop) {
        if (start === void 0) { start = 0; }
        if (stop === void 0) { stop = -1; }
        var n = array.length;
        if (n === 0) {
            return -1;
        }
        if (start < 0) {
            start = Math.max(0, start + n);
        }
        else {
            start = Math.min(start, n - 1);
        }
        if (stop < 0) {
            stop = Math.max(0, stop + n);
        }
        else {
            stop = Math.min(stop, n - 1);
        }
        var span;
        if (stop < start) {
            span = (stop + 1) + (n - start);
        }
        else {
            span = stop - start + 1;
        }
        for (var i = 0; i < span; ++i) {
            var j = (start + i) % n;
            if (array[j] === value) {
                return j;
            }
        }
        return -1;
    }
    ArrayExt.firstIndexOf = firstIndexOf;
    /**
     * Find the index of the last occurrence of a value in an array.
     *
     * @param array - The array-like object to search.
     *
     * @param value - The value to locate in the array. Values are
     *   compared using strict `===` equality.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The index of the last occurrence of the value, or `-1`
     *   if the value is not found.
     *
     * #### Notes
     * If `start < stop` the search will wrap at the front of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * A `start` or `stop` which is non-integral.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@phosphor/algorithm';
     *
     * let data = ['one', 'two', 'three', 'four', 'one'];
     * ArrayExt.lastIndexOf(data, 'red');        // -1
     * ArrayExt.lastIndexOf(data, 'one');        // 4
     * ArrayExt.lastIndexOf(data, 'one', 1);     // 0
     * ArrayExt.lastIndexOf(data, 'two', 0);     // -1
     * ArrayExt.lastIndexOf(data, 'two', 0, 1);  // 1
     * ```
     */
    function lastIndexOf(array, value, start, stop) {
        if (start === void 0) { start = -1; }
        if (stop === void 0) { stop = 0; }
        var n = array.length;
        if (n === 0) {
            return -1;
        }
        if (start < 0) {
            start = Math.max(0, start + n);
        }
        else {
            start = Math.min(start, n - 1);
        }
        if (stop < 0) {
            stop = Math.max(0, stop + n);
        }
        else {
            stop = Math.min(stop, n - 1);
        }
        var span;
        if (start < stop) {
            span = (start + 1) + (n - stop);
        }
        else {
            span = start - stop + 1;
        }
        for (var i = 0; i < span; ++i) {
            var j = (start - i + n) % n;
            if (array[j] === value) {
                return j;
            }
        }
        return -1;
    }
    ArrayExt.lastIndexOf = lastIndexOf;
    /**
     * Find the index of the first value which matches a predicate.
     *
     * @param array - The array-like object to search.
     *
     * @param fn - The predicate function to apply to the values.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The index of the first matching value, or `-1` if no
     *   matching value is found.
     *
     * #### Notes
     * If `stop < start` the search will wrap at the end of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * A `start` or `stop` which is non-integral.
     *
     * Modifying the length of the array while searching.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@phosphor/algorithm';
     *
     * function isEven(value: number): boolean {
     *   return value % 2 === 0;
     * }
     *
     * let data = [1, 2, 3, 4, 3, 2, 1];
     * ArrayExt.findFirstIndex(data, isEven);       // 1
     * ArrayExt.findFirstIndex(data, isEven, 4);    // 5
     * ArrayExt.findFirstIndex(data, isEven, 6);    // -1
     * ArrayExt.findFirstIndex(data, isEven, 6, 5); // 1
     * ```
     */
    function findFirstIndex(array, fn, start, stop) {
        if (start === void 0) { start = 0; }
        if (stop === void 0) { stop = -1; }
        var n = array.length;
        if (n === 0) {
            return -1;
        }
        if (start < 0) {
            start = Math.max(0, start + n);
        }
        else {
            start = Math.min(start, n - 1);
        }
        if (stop < 0) {
            stop = Math.max(0, stop + n);
        }
        else {
            stop = Math.min(stop, n - 1);
        }
        var span;
        if (stop < start) {
            span = (stop + 1) + (n - start);
        }
        else {
            span = stop - start + 1;
        }
        for (var i = 0; i < span; ++i) {
            var j = (start + i) % n;
            if (fn(array[j], j)) {
                return j;
            }
        }
        return -1;
    }
    ArrayExt.findFirstIndex = findFirstIndex;
    /**
     * Find the index of the last value which matches a predicate.
     *
     * @param object - The array-like object to search.
     *
     * @param fn - The predicate function to apply to the values.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The index of the last matching value, or `-1` if no
     *   matching value is found.
     *
     * #### Notes
     * If `start < stop` the search will wrap at the front of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * A `start` or `stop` which is non-integral.
     *
     * Modifying the length of the array while searching.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@phosphor/algorithm';
     *
     * function isEven(value: number): boolean {
     *   return value % 2 === 0;
     * }
     *
     * let data = [1, 2, 3, 4, 3, 2, 1];
     * ArrayExt.findLastIndex(data, isEven);        // 5
     * ArrayExt.findLastIndex(data, isEven, 4);     // 3
     * ArrayExt.findLastIndex(data, isEven, 0);     // -1
     * ArrayExt.findLastIndex(data, isEven, 0, 1);  // 5
     * ```
     */
    function findLastIndex(array, fn, start, stop) {
        if (start === void 0) { start = -1; }
        if (stop === void 0) { stop = 0; }
        var n = array.length;
        if (n === 0) {
            return -1;
        }
        if (start < 0) {
            start = Math.max(0, start + n);
        }
        else {
            start = Math.min(start, n - 1);
        }
        if (stop < 0) {
            stop = Math.max(0, stop + n);
        }
        else {
            stop = Math.min(stop, n - 1);
        }
        var d;
        if (start < stop) {
            d = (start + 1) + (n - stop);
        }
        else {
            d = start - stop + 1;
        }
        for (var i = 0; i < d; ++i) {
            var j = (start - i + n) % n;
            if (fn(array[j], j)) {
                return j;
            }
        }
        return -1;
    }
    ArrayExt.findLastIndex = findLastIndex;
    /**
     * Find the first value which matches a predicate.
     *
     * @param array - The array-like object to search.
     *
     * @param fn - The predicate function to apply to the values.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The first matching value, or `undefined` if no matching
     *   value is found.
     *
     * #### Notes
     * If `stop < start` the search will wrap at the end of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * A `start` or `stop` which is non-integral.
     *
     * Modifying the length of the array while searching.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@phosphor/algorithm';
     *
     * function isEven(value: number): boolean {
     *   return value % 2 === 0;
     * }
     *
     * let data = [1, 2, 3, 4, 3, 2, 1];
     * ArrayExt.findFirstValue(data, isEven);       // 2
     * ArrayExt.findFirstValue(data, isEven, 2);    // 4
     * ArrayExt.findFirstValue(data, isEven, 6);    // undefined
     * ArrayExt.findFirstValue(data, isEven, 6, 5); // 2
     * ```
     */
    function findFirstValue(array, fn, start, stop) {
        if (start === void 0) { start = 0; }
        if (stop === void 0) { stop = -1; }
        var index = findFirstIndex(array, fn, start, stop);
        return index !== -1 ? array[index] : undefined;
    }
    ArrayExt.findFirstValue = findFirstValue;
    /**
     * Find the last value which matches a predicate.
     *
     * @param object - The array-like object to search.
     *
     * @param fn - The predicate function to apply to the values.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The last matching value, or `undefined` if no matching
     *   value is found.
     *
     * #### Notes
     * If `start < stop` the search will wrap at the front of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * A `start` or `stop` which is non-integral.
     *
     * Modifying the length of the array while searching.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@phosphor/algorithm';
     *
     * function isEven(value: number): boolean {
     *   return value % 2 === 0;
     * }
     *
     * let data = [1, 2, 3, 4, 3, 2, 1];
     * ArrayExt.findLastValue(data, isEven);        // 2
     * ArrayExt.findLastValue(data, isEven, 4);     // 4
     * ArrayExt.findLastValue(data, isEven, 0);     // undefined
     * ArrayExt.findLastValue(data, isEven, 0, 1);  // 2
     * ```
     */
    function findLastValue(array, fn, start, stop) {
        if (start === void 0) { start = -1; }
        if (stop === void 0) { stop = 0; }
        var index = findLastIndex(array, fn, start, stop);
        return index !== -1 ? array[index] : undefined;
    }
    ArrayExt.findLastValue = findLastValue;
    /**
     * Find the index of the first element which compares `>=` to a value.
     *
     * @param array - The sorted array-like object to search.
     *
     * @param value - The value to locate in the array.
     *
     * @param fn - The 3-way comparison function to apply to the values.
     *   It should return `< 0` if an element is less than a value, `0` if
     *   an element is equal to a value, or `> 0` if an element is greater
     *   than a value.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The index of the first element which compares `>=` to the
     *   value, or `length` if there is no such element. If the computed
     *   index for `stop` is less than `start`, then the computed index
     *   for `start` is returned.
     *
     * #### Notes
     * The array must already be sorted in ascending order according to
     * the comparison function.
     *
     * #### Complexity
     * Logarithmic.
     *
     * #### Undefined Behavior
     * Searching a range which is not sorted in ascending order.
     *
     * A `start` or `stop` which is non-integral.
     *
     * Modifying the length of the array while searching.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@phosphor/algorithm';
     *
     * function numberCmp(a: number, b: number): number {
     *   return a - b;
     * }
     *
     * let data = [0, 3, 4, 7, 7, 9];
     * ArrayExt.lowerBound(data, 0, numberCmp);   // 0
     * ArrayExt.lowerBound(data, 6, numberCmp);   // 3
     * ArrayExt.lowerBound(data, 7, numberCmp);   // 3
     * ArrayExt.lowerBound(data, -1, numberCmp);  // 0
     * ArrayExt.lowerBound(data, 10, numberCmp);  // 6
     * ```
     */
    function lowerBound(array, value, fn, start, stop) {
        if (start === void 0) { start = 0; }
        if (stop === void 0) { stop = -1; }
        var n = array.length;
        if (n === 0) {
            return 0;
        }
        if (start < 0) {
            start = Math.max(0, start + n);
        }
        else {
            start = Math.min(start, n - 1);
        }
        if (stop < 0) {
            stop = Math.max(0, stop + n);
        }
        else {
            stop = Math.min(stop, n - 1);
        }
        var begin = start;
        var span = stop - start + 1;
        while (span > 0) {
            var half = span >> 1;
            var middle = begin + half;
            if (fn(array[middle], value) < 0) {
                begin = middle + 1;
                span -= half + 1;
            }
            else {
                span = half;
            }
        }
        return begin;
    }
    ArrayExt.lowerBound = lowerBound;
    /**
     * Find the index of the first element which compares `>` than a value.
     *
     * @param array - The sorted array-like object to search.
     *
     * @param value - The value to locate in the array.
     *
     * @param fn - The 3-way comparison function to apply to the values.
     *   It should return `< 0` if an element is less than a value, `0` if
     *   an element is equal to a value, or `> 0` if an element is greater
     *   than a value.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The index of the first element which compares `>` than the
     *   value, or `length` if there is no such element. If the computed
     *   index for `stop` is less than `start`, then the computed index
     *   for `start` is returned.
     *
     * #### Notes
     * The array must already be sorted in ascending order according to
     * the comparison function.
     *
     * #### Complexity
     * Logarithmic.
     *
     * #### Undefined Behavior
     * Searching a range which is not sorted in ascending order.
     *
     * A `start` or `stop` which is non-integral.
     *
     * Modifying the length of the array while searching.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@phosphor/algorithm';
     *
     * function numberCmp(a: number, b: number): number {
     *   return a - b;
     * }
     *
     * let data = [0, 3, 4, 7, 7, 9];
     * ArrayExt.upperBound(data, 0, numberCmp);   // 1
     * ArrayExt.upperBound(data, 6, numberCmp);   // 3
     * ArrayExt.upperBound(data, 7, numberCmp);   // 5
     * ArrayExt.upperBound(data, -1, numberCmp);  // 0
     * ArrayExt.upperBound(data, 10, numberCmp);  // 6
     * ```
     */
    function upperBound(array, value, fn, start, stop) {
        if (start === void 0) { start = 0; }
        if (stop === void 0) { stop = -1; }
        var n = array.length;
        if (n === 0) {
            return 0;
        }
        if (start < 0) {
            start = Math.max(0, start + n);
        }
        else {
            start = Math.min(start, n - 1);
        }
        if (stop < 0) {
            stop = Math.max(0, stop + n);
        }
        else {
            stop = Math.min(stop, n - 1);
        }
        var begin = start;
        var span = stop - start + 1;
        while (span > 0) {
            var half = span >> 1;
            var middle = begin + half;
            if (fn(array[middle], value) > 0) {
                span = half;
            }
            else {
                begin = middle + 1;
                span -= half + 1;
            }
        }
        return begin;
    }
    ArrayExt.upperBound = upperBound;
    /**
     * Move an element in an array from one index to another.
     *
     * @param array - The mutable array-like object of interest.
     *
     * @param fromIndex - The index of the element to move. Negative
     *   values are taken as an offset from the end of the array.
     *
     * @param toIndex - The target index of the element. Negative
     *   values are taken as an offset from the end of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * A `fromIndex` or `toIndex` which is non-integral.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from from '@phosphor/algorithm';
     *
     * let data = [0, 1, 2, 3, 4];
     * ArrayExt.move(data, 1, 2);  // [0, 2, 1, 3, 4]
     * ArrayExt.move(data, 4, 2);  // [0, 2, 4, 1, 3]
     * ```
     */
    function move(array, fromIndex, toIndex) {
        var n = array.length;
        if (n <= 1) {
            return;
        }
        if (fromIndex < 0) {
            fromIndex = Math.max(0, fromIndex + n);
        }
        else {
            fromIndex = Math.min(fromIndex, n - 1);
        }
        if (toIndex < 0) {
            toIndex = Math.max(0, toIndex + n);
        }
        else {
            toIndex = Math.min(toIndex, n - 1);
        }
        if (fromIndex === toIndex) {
            return;
        }
        var value = array[fromIndex];
        var d = fromIndex < toIndex ? 1 : -1;
        for (var i = fromIndex; i !== toIndex; i += d) {
            array[i] = array[i + d];
        }
        array[toIndex] = value;
    }
    ArrayExt.move = move;
    /**
     * Reverse an array in-place.
     *
     * @param array - The mutable array-like object of interest.
     *
     * @param start - The index of the first element in the range to be
     *   reversed, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   reversed, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * A `start` or  `stop` index which is non-integral.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@phosphor/algorithm';
     *
     * let data = [0, 1, 2, 3, 4];
     * ArrayExt.reverse(data, 1, 3);  // [0, 3, 2, 1, 4]
     * ArrayExt.reverse(data, 3);     // [0, 3, 2, 4, 1]
     * ArrayExt.reverse(data);        // [1, 4, 2, 3, 0]
     * ```
     */
    function reverse(array, start, stop) {
        if (start === void 0) { start = 0; }
        if (stop === void 0) { stop = -1; }
        var n = array.length;
        if (n <= 1) {
            return;
        }
        if (start < 0) {
            start = Math.max(0, start + n);
        }
        else {
            start = Math.min(start, n - 1);
        }
        if (stop < 0) {
            stop = Math.max(0, stop + n);
        }
        else {
            stop = Math.min(stop, n - 1);
        }
        while (start < stop) {
            var a = array[start];
            var b = array[stop];
            array[start++] = b;
            array[stop--] = a;
        }
    }
    ArrayExt.reverse = reverse;
    /**
     * Rotate the elements of an array in-place.
     *
     * @param array - The mutable array-like object of interest.
     *
     * @param delta - The amount of rotation to apply to the elements. A
     *   positive value will rotate the elements to the left. A negative
     *   value will rotate the elements to the right.
     *
     * @param start - The index of the first element in the range to be
     *   rotated, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   rotated, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * A `delta`, `start`, or `stop` which is non-integral.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@phosphor/algorithm';
     *
     * let data = [0, 1, 2, 3, 4];
     * ArrayExt.rotate(data, 2);        // [2, 3, 4, 0, 1]
     * ArrayExt.rotate(data, -2);       // [0, 1, 2, 3, 4]
     * ArrayExt.rotate(data, 10);       // [0, 1, 2, 3, 4]
     * ArrayExt.rotate(data, 9);        // [4, 0, 1, 2, 3]
     * ArrayExt.rotate(data, 2, 1, 3);  // [4, 2, 0, 1, 3]
     * ```
     */
    function rotate(array, delta, start, stop) {
        if (start === void 0) { start = 0; }
        if (stop === void 0) { stop = -1; }
        var n = array.length;
        if (n <= 1) {
            return;
        }
        if (start < 0) {
            start = Math.max(0, start + n);
        }
        else {
            start = Math.min(start, n - 1);
        }
        if (stop < 0) {
            stop = Math.max(0, stop + n);
        }
        else {
            stop = Math.min(stop, n - 1);
        }
        if (start >= stop) {
            return;
        }
        var length = stop - start + 1;
        if (delta > 0) {
            delta = delta % length;
        }
        else if (delta < 0) {
            delta = ((delta % length) + length) % length;
        }
        if (delta === 0) {
            return;
        }
        var pivot = start + delta;
        reverse(array, start, pivot - 1);
        reverse(array, pivot, stop);
        reverse(array, start, stop);
    }
    ArrayExt.rotate = rotate;
    /**
     * Fill an array with a static value.
     *
     * @param array - The mutable array-like object to fill.
     *
     * @param value - The static value to use to fill the array.
     *
     * @param start - The index of the first element in the range to be
     *   filled, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   filled, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * #### Notes
     * If `stop < start` the fill will wrap at the end of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * A `start` or `stop` which is non-integral.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@phosphor/algorithm';
     *
     * let data = ['one', 'two', 'three', 'four'];
     * ArrayExt.fill(data, 'r');        // ['r', 'r', 'r', 'r']
     * ArrayExt.fill(data, 'g', 1);     // ['r', 'g', 'g', 'g']
     * ArrayExt.fill(data, 'b', 2, 3);  // ['r', 'g', 'b', 'b']
     * ArrayExt.fill(data, 'z', 3, 1);  // ['z', 'z', 'b', 'z']
     * ```
     */
    function fill(array, value, start, stop) {
        if (start === void 0) { start = 0; }
        if (stop === void 0) { stop = -1; }
        var n = array.length;
        if (n === 0) {
            return;
        }
        if (start < 0) {
            start = Math.max(0, start + n);
        }
        else {
            start = Math.min(start, n - 1);
        }
        if (stop < 0) {
            stop = Math.max(0, stop + n);
        }
        else {
            stop = Math.min(stop, n - 1);
        }
        var span;
        if (stop < start) {
            span = (stop + 1) + (n - start);
        }
        else {
            span = stop - start + 1;
        }
        for (var i = 0; i < span; ++i) {
            array[(start + i) % n] = value;
        }
    }
    ArrayExt.fill = fill;
    /**
     * Insert a value into an array at a specific index.
     *
     * @param array - The array of interest.
     *
     * @param index - The index at which to insert the value. Negative
     *   values are taken as an offset from the end of the array.
     *
     * @param value - The value to set at the specified index.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * An `index` which is non-integral.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@phosphor/algorithm';
     *
     * let data = [0, 1, 2];
     * ArrayExt.insert(data, 0, -1);  // [-1, 0, 1, 2]
     * ArrayExt.insert(data, 2, 12);  // [-1, 0, 12, 1, 2]
     * ArrayExt.insert(data, -1, 7);  // [-1, 0, 12, 1, 7, 2]
     * ArrayExt.insert(data, 6, 19);  // [-1, 0, 12, 1, 7, 2, 19]
     * ```
     */
    function insert(array, index, value) {
        var n = array.length;
        if (index < 0) {
            index = Math.max(0, index + n);
        }
        else {
            index = Math.min(index, n);
        }
        for (var i = n; i > index; --i) {
            array[i] = array[i - 1];
        }
        array[index] = value;
    }
    ArrayExt.insert = insert;
    /**
     * Remove and return a value at a specific index in an array.
     *
     * @param array - The array of interest.
     *
     * @param index - The index of the value to remove. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The value at the specified index, or `undefined` if the
     *   index is out of range.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * An `index` which is non-integral.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@phosphor/algorithm';
     *
     * let data = [0, 12, 23, 39, 14, 12, 75];
     * ArrayExt.removeAt(data, 2);   // 23
     * ArrayExt.removeAt(data, -2);  // 12
     * ArrayExt.removeAt(data, 10);  // undefined;
     * ```
     */
    function removeAt(array, index) {
        var n = array.length;
        if (index < 0) {
            index += n;
        }
        if (index < 0 || index >= n) {
            return undefined;
        }
        var value = array[index];
        for (var i = index + 1; i < n; ++i) {
            array[i - 1] = array[i];
        }
        array.length = n - 1;
        return value;
    }
    ArrayExt.removeAt = removeAt;
    /**
     * Remove the first occurrence of a value from an array.
     *
     * @param array - The array of interest.
     *
     * @param value - The value to remove from the array. Values are
     *   compared using strict `===` equality.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The index of the removed value, or `-1` if the value
     *   is not contained in the array.
     *
     * #### Notes
     * If `stop < start` the search will wrap at the end of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@phosphor/algorithm';
     *
     * let data = [0, 12, 23, 39, 14, 12, 75];
     * ArrayExt.removeFirstOf(data, 12);        // 1
     * ArrayExt.removeFirstOf(data, 17);        // -1
     * ArrayExt.removeFirstOf(data, 39, 3);     // -1
     * ArrayExt.removeFirstOf(data, 39, 3, 2);  // 2
     * ```
     */
    function removeFirstOf(array, value, start, stop) {
        if (start === void 0) { start = 0; }
        if (stop === void 0) { stop = -1; }
        var index = firstIndexOf(array, value, start, stop);
        if (index !== -1) {
            removeAt(array, index);
        }
        return index;
    }
    ArrayExt.removeFirstOf = removeFirstOf;
    /**
     * Remove the last occurrence of a value from an array.
     *
     * @param array - The array of interest.
     *
     * @param value - The value to remove from the array. Values are
     *   compared using strict `===` equality.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The index of the removed value, or `-1` if the value
     *   is not contained in the array.
     *
     * #### Notes
     * If `start < stop` the search will wrap at the end of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@phosphor/algorithm';
     *
     * let data = [0, 12, 23, 39, 14, 12, 75];
     * ArrayExt.removeLastOf(data, 12);        // 5
     * ArrayExt.removeLastOf(data, 17);        // -1
     * ArrayExt.removeLastOf(data, 39, 2);     // -1
     * ArrayExt.removeLastOf(data, 39, 2, 3);  // 3
     * ```
     */
    function removeLastOf(array, value, start, stop) {
        if (start === void 0) { start = -1; }
        if (stop === void 0) { stop = 0; }
        var index = lastIndexOf(array, value, start, stop);
        if (index !== -1) {
            removeAt(array, index);
        }
        return index;
    }
    ArrayExt.removeLastOf = removeLastOf;
    /**
     * Remove all occurrences of a value from an array.
     *
     * @param array - The array of interest.
     *
     * @param value - The value to remove from the array. Values are
     *   compared using strict `===` equality.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The number of elements removed from the array.
     *
     * #### Notes
     * If `stop < start` the search will conceptually wrap at the end of
     * the array, however the array will be traversed front-to-back.
     *
     * #### Complexity
     * Linear.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@phosphor/algorithm';
     *
     * let data = [14, 12, 23, 39, 14, 12, 19, 14];
     * ArrayExt.removeAllOf(data, 12);        // 2
     * ArrayExt.removeAllOf(data, 17);        // 0
     * ArrayExt.removeAllOf(data, 14, 1, 4);  // 1
     * ```
     */
    function removeAllOf(array, value, start, stop) {
        if (start === void 0) { start = 0; }
        if (stop === void 0) { stop = -1; }
        var n = array.length;
        if (n === 0) {
            return 0;
        }
        if (start < 0) {
            start = Math.max(0, start + n);
        }
        else {
            start = Math.min(start, n - 1);
        }
        if (stop < 0) {
            stop = Math.max(0, stop + n);
        }
        else {
            stop = Math.min(stop, n - 1);
        }
        var count = 0;
        for (var i = 0; i < n; ++i) {
            if (start <= stop && (i >= start && i <= stop) && array[i] === value) {
                count++;
            }
            else if (stop < start && (i <= stop || i >= start) && array[i] === value) {
                count++;
            }
            else if (count > 0) {
                array[i - count] = array[i];
            }
        }
        if (count > 0) {
            array.length = n - count;
        }
        return count;
    }
    ArrayExt.removeAllOf = removeAllOf;
    /**
     * Remove the first occurrence of a value which matches a predicate.
     *
     * @param array - The array of interest.
     *
     * @param fn - The predicate function to apply to the values.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The removed `{ index, value }`, which will be `-1` and
     *   `undefined` if the value is not contained in the array.
     *
     * #### Notes
     * If `stop < start` the search will wrap at the end of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@phosphor/algorithm';
     *
     * function isEven(value: number): boolean {
     *   return value % 2 === 0;
     * }
     *
     * let data = [0, 12, 23, 39, 14, 12, 75];
     * ArrayExt.removeFirstWhere(data, isEven);     // { index: 0, value: 0 }
     * ArrayExt.removeFirstWhere(data, isEven, 2);  // { index: 3, value: 14 }
     * ArrayExt.removeFirstWhere(data, isEven, 4);  // { index: -1, value: undefined }
     * ```
     */
    function removeFirstWhere(array, fn, start, stop) {
        if (start === void 0) { start = 0; }
        if (stop === void 0) { stop = -1; }
        var value;
        var index = findFirstIndex(array, fn, start, stop);
        if (index !== -1) {
            value = removeAt(array, index);
        }
        return { index: index, value: value };
    }
    ArrayExt.removeFirstWhere = removeFirstWhere;
    /**
     * Remove the last occurrence of a value which matches a predicate.
     *
     * @param array - The array of interest.
     *
     * @param fn - The predicate function to apply to the values.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The removed `{ index, value }`, which will be `-1` and
     *   `undefined` if the value is not contained in the array.
     *
     * #### Notes
     * If `start < stop` the search will wrap at the end of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@phosphor/algorithm';
     *
     * function isEven(value: number): boolean {
     *   return value % 2 === 0;
     * }
     *
     * let data = [0, 12, 23, 39, 14, 12, 75];
     * ArrayExt.removeLastWhere(data, isEven);        // { index: 5, value: 12 }
     * ArrayExt.removeLastWhere(data, isEven, 2);     // { index: 1, value: 12 }
     * ArrayExt.removeLastWhere(data, isEven, 2, 1);  // { index: -1, value: undefined }
     * ```
     */
    function removeLastWhere(array, fn, start, stop) {
        if (start === void 0) { start = -1; }
        if (stop === void 0) { stop = 0; }
        var value;
        var index = findLastIndex(array, fn, start, stop);
        if (index !== -1) {
            value = removeAt(array, index);
        }
        return { index: index, value: value };
    }
    ArrayExt.removeLastWhere = removeLastWhere;
    /**
     * Remove all occurrences of values which match a predicate.
     *
     * @param array - The array of interest.
     *
     * @param fn - The predicate function to apply to the values.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The number of elements removed from the array.
     *
     * #### Notes
     * If `stop < start` the search will conceptually wrap at the end of
     * the array, however the array will be traversed front-to-back.
     *
     * #### Complexity
     * Linear.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@phosphor/algorithm';
     *
     * function isEven(value: number): boolean {
     *   return value % 2 === 0;
     * }
     *
     * function isNegative(value: number): boolean {
     *   return value < 0;
     * }
     *
     * let data = [0, 12, -13, -9, 23, 39, 14, -15, 12, 75];
     * ArrayExt.removeAllWhere(data, isEven);            // 4
     * ArrayExt.removeAllWhere(data, isNegative, 0, 3);  // 2
     * ```
     */
    function removeAllWhere(array, fn, start, stop) {
        if (start === void 0) { start = 0; }
        if (stop === void 0) { stop = -1; }
        var n = array.length;
        if (n === 0) {
            return 0;
        }
        if (start < 0) {
            start = Math.max(0, start + n);
        }
        else {
            start = Math.min(start, n - 1);
        }
        if (stop < 0) {
            stop = Math.max(0, stop + n);
        }
        else {
            stop = Math.min(stop, n - 1);
        }
        var count = 0;
        for (var i = 0; i < n; ++i) {
            if (start <= stop && (i >= start && i <= stop) && fn(array[i], i)) {
                count++;
            }
            else if (stop < start && (i <= stop || i >= start) && fn(array[i], i)) {
                count++;
            }
            else if (count > 0) {
                array[i - count] = array[i];
            }
        }
        if (count > 0) {
            array.length = n - count;
        }
        return count;
    }
    ArrayExt.removeAllWhere = removeAllWhere;
})(ArrayExt = exports.ArrayExt || (exports.ArrayExt = {}));


/***/ }),

/***/ "PBw4":
/*!****************************************************************!*\
  !*** ./node_modules/plotly.js/src/plots/cartesian/axis_ids.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var Registry = __webpack_require__(/*! ../../registry */ "Nx4I");

var constants = __webpack_require__(/*! ./constants */ "0wH6");


// convert between axis names (xaxis, xaxis2, etc, elements of gd.layout)
// and axis id's (x, x2, etc). Would probably have ditched 'xaxis'
// completely in favor of just 'x' if it weren't ingrained in the API etc.
exports.id2name = function id2name(id) {
    if(typeof id !== 'string' || !id.match(constants.AX_ID_PATTERN)) return;
    var axNum = id.substr(1);
    if(axNum === '1') axNum = '';
    return id.charAt(0) + 'axis' + axNum;
};

exports.name2id = function name2id(name) {
    if(!name.match(constants.AX_NAME_PATTERN)) return;
    var axNum = name.substr(5);
    if(axNum === '1') axNum = '';
    return name.charAt(0) + axNum;
};

exports.cleanId = function cleanId(id, axLetter) {
    if(!id.match(constants.AX_ID_PATTERN)) return;
    if(axLetter && id.charAt(0) !== axLetter) return;

    var axNum = id.substr(1).replace(/^0+/, '');
    if(axNum === '1') axNum = '';
    return id.charAt(0) + axNum;
};

// get all axis objects, as restricted in listNames
exports.list = function(gd, axLetter, only2d) {
    var fullLayout = gd._fullLayout;
    if(!fullLayout) return [];

    var idList = exports.listIds(gd, axLetter);
    var out = new Array(idList.length);
    var i;

    for(i = 0; i < idList.length; i++) {
        var idi = idList[i];
        out[i] = fullLayout[idi.charAt(0) + 'axis' + idi.substr(1)];
    }

    if(!only2d) {
        var sceneIds3D = fullLayout._subplots.gl3d || [];

        for(i = 0; i < sceneIds3D.length; i++) {
            var scene = fullLayout[sceneIds3D[i]];

            if(axLetter) out.push(scene[axLetter + 'axis']);
            else out.push(scene.xaxis, scene.yaxis, scene.zaxis);
        }
    }

    return out;
};

// get all axis ids, optionally restricted by letter
// this only makes sense for 2d axes
exports.listIds = function(gd, axLetter) {
    var fullLayout = gd._fullLayout;
    if(!fullLayout) return [];

    var subplotLists = fullLayout._subplots;
    if(axLetter) return subplotLists[axLetter + 'axis'];
    return subplotLists.xaxis.concat(subplotLists.yaxis);
};

// get an axis object from its id 'x','x2' etc
// optionally, id can be a subplot (ie 'x2y3') and type gets x or y from it
exports.getFromId = function(gd, id, type) {
    var fullLayout = gd._fullLayout;

    if(type === 'x') id = id.replace(/y[0-9]*/, '');
    else if(type === 'y') id = id.replace(/x[0-9]*/, '');

    return fullLayout[exports.id2name(id)];
};

// get an axis object of specified type from the containing trace
exports.getFromTrace = function(gd, fullTrace, type) {
    var fullLayout = gd._fullLayout;
    var ax = null;

    if(Registry.traceIs(fullTrace, 'gl3d')) {
        var scene = fullTrace.scene;
        if(scene.substr(0, 5) === 'scene') {
            ax = fullLayout[scene][type + 'axis'];
        }
    }
    else {
        ax = exports.getFromId(gd, fullTrace[type + 'axis'] || type);
    }

    return ax;
};

// sort x, x2, x10, y, y2, y10...
exports.idSort = function(id1, id2) {
    var letter1 = id1.charAt(0);
    var letter2 = id2.charAt(0);
    if(letter1 !== letter2) return letter1 > letter2 ? 1 : -1;
    return +(id1.substr(1) || 1) - +(id2.substr(1) || 1);
};


/***/ }),

/***/ "PDX0":
/*!****************************************!*\
  !*** (webpack)/buildin/amd-options.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {/* globals __webpack_amd_options__ */
module.exports = __webpack_amd_options__;

/* WEBPACK VAR INJECTION */}.call(this, {}))

/***/ }),

/***/ "PFU8":
/*!*******************************************************!*\
  !*** ./node_modules/draft-js/lib/DraftTreeAdapter.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _assign = __webpack_require__(/*! object-assign */ "MgzW");

var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DraftTreeAdapter
 * @format
 * 
 *
 * This is unstable and not part of the public API and should not be used by
 * production systems. This file may be update/removed without notice.
 */

var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");

var traverseInDepthOrder = function traverseInDepthOrder(blocks, fn) {
  var stack = [].concat(blocks).reverse();
  while (stack.length) {
    var _block = stack.pop();

    fn(_block);

    var children = _block.children;

    !Array.isArray(children) ?  true ? invariant(false, 'Invalid tree raw block') : undefined : void 0;

    stack = stack.concat([].concat(children.reverse()));
  }
};

var isListBlock = function isListBlock(block) {
  if (!(block && block.type)) {
    return false;
  }
  var type = block.type;

  return type === 'unordered-list-item' || type === 'ordered-list-item';
};

var addDepthToChildren = function addDepthToChildren(block) {
  if (Array.isArray(block.children)) {
    block.children = block.children.map(function (child) {
      return child.type === block.type ? _extends({}, child, { depth: (block.depth || 0) + 1 }) : child;
    });
  }
};

/**
 * This adapter is intended to be be used as an adapter to draft tree data
 *
 * draft state <=====> draft tree state
 */
var DraftTreeAdapter = {
  /**
   * Converts from a tree raw state back to  draft raw state
   */
  fromRawTreeStateToRawState: function fromRawTreeStateToRawState(draftTreeState) {
    var blocks = draftTreeState.blocks;

    var transformedBlocks = [];

    !Array.isArray(blocks) ?  true ? invariant(false, 'Invalid raw state') : undefined : void 0;

    if (!Array.isArray(blocks) || !blocks.length) {
      return draftTreeState;
    }

    traverseInDepthOrder(blocks, function (block) {
      var newBlock = _extends({}, block);

      if (isListBlock(block)) {
        newBlock.depth = newBlock.depth || 0;
        addDepthToChildren(block);
      }

      delete newBlock.children;

      transformedBlocks.push(newBlock);
    });

    draftTreeState.blocks = transformedBlocks;

    return _extends({}, draftTreeState, {
      blocks: transformedBlocks
    });
  },


  /**
   * Converts from draft raw state to tree draft state
   */
  fromRawStateToRawTreeState: function fromRawStateToRawTreeState(draftState) {
    var lastListDepthCacheRef = {};
    var transformedBlocks = [];

    draftState.blocks.forEach(function (block) {
      var isList = isListBlock(block);
      var depth = block.depth || 0;
      var treeBlock = _extends({}, block, {
        children: []
      });

      if (!isList) {
        // reset the cache path
        lastListDepthCacheRef = {};
        transformedBlocks.push(treeBlock);
        return;
      }

      // update our depth cache reference path
      lastListDepthCacheRef[depth] = treeBlock;

      // if we are greater than zero we must have seen a parent already
      if (depth > 0) {
        var parent = lastListDepthCacheRef[depth - 1];

        !parent ?  true ? invariant(false, 'Invalid depth for RawDraftContentBlock') : undefined : void 0;

        // push nested list blocks
        parent.children.push(treeBlock);
        return;
      }

      // push root list blocks
      transformedBlocks.push(treeBlock);
    });

    return _extends({}, draftState, {
      blocks: transformedBlocks
    });
  }
};

module.exports = DraftTreeAdapter;

/***/ }),

/***/ "PGcv":
/*!************************************************************************!*\
  !*** ./node_modules/react-color/lib/components/slider/SliderSwatch.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SliderSwatch = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var SliderSwatch = exports.SliderSwatch = function SliderSwatch(_ref) {
  var hsl = _ref.hsl,
      offset = _ref.offset,
      _ref$onClick = _ref.onClick,
      onClick = _ref$onClick === undefined ? function () {} : _ref$onClick,
      active = _ref.active,
      first = _ref.first,
      last = _ref.last;

  var styles = (0, _reactcss2.default)({
    'default': {
      swatch: {
        height: '12px',
        background: 'hsl(' + hsl.h + ', 50%, ' + offset * 100 + '%)',
        cursor: 'pointer'
      }
    },
    'first': {
      swatch: {
        borderRadius: '2px 0 0 2px'
      }
    },
    'last': {
      swatch: {
        borderRadius: '0 2px 2px 0'
      }
    },
    'active': {
      swatch: {
        transform: 'scaleY(1.8)',
        borderRadius: '3.6px/2px'
      }
    }
  }, { active: active, first: first, last: last });

  var handleClick = function handleClick(e) {
    return onClick({
      h: hsl.h,
      s: 0.5,
      l: offset,
      source: 'hsl'
    }, e);
  };

  return _react2.default.createElement('div', { style: styles.swatch, onClick: handleClick });
};

exports.default = SliderSwatch;

/***/ }),

/***/ "PL31":
/*!*********************************************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/components/colorscale/layout_attributes.js ***!
  \*********************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var scales = __webpack_require__(/*! ./scales */ "L3zP").scales;

var msg = 'Note that `autocolorscale` must be true for this attribute to work.';

module.exports = {
    editType: 'calc',
    sequential: {
        valType: 'colorscale',
        dflt: scales.Reds,
        role: 'style',
        editType: 'calc',
        description: [
            'Sets the default sequential colorscale for positive values.',
            msg
        ].join(' ')
    },
    sequentialminus: {
        valType: 'colorscale',
        dflt: scales.Blues,
        role: 'style',
        editType: 'calc',
        description: [
            'Sets the default sequential colorscale for negative values.',
            msg
        ].join(' ')
    },
    diverging: {
        valType: 'colorscale',
        dflt: scales.RdBu,
        role: 'style',
        editType: 'calc',
        description: [
            'Sets the default diverging colorscale.',
            msg
        ].join(' ')
    }
};


/***/ }),

/***/ "PLYX":
/*!*********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/DateTimePicker.js ***!
  \*********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UnconnectedDateTimePicker = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _DateTimePicker = __webpack_require__(/*! ../widgets/DateTimePicker */ "5DOW");

var _DateTimePicker2 = _interopRequireDefault(_DateTimePicker);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UnconnectedDateTimePicker = exports.UnconnectedDateTimePicker = function (_Component) {
  _inherits(UnconnectedDateTimePicker, _Component);

  function UnconnectedDateTimePicker() {
    _classCallCheck(this, UnconnectedDateTimePicker);

    return _possibleConstructorReturn(this, (UnconnectedDateTimePicker.__proto__ || Object.getPrototypeOf(UnconnectedDateTimePicker)).apply(this, arguments));
  }

  _createClass(UnconnectedDateTimePicker, [{
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        _Field2.default,
        this.props,
        _react2.default.createElement(_DateTimePicker2.default, {
          value: this.props.fullValue,
          placeholder: this.props.placeholder,
          onChange: this.props.updatePlot
        })
      );
    }
  }]);

  return UnconnectedDateTimePicker;
}(_react.Component);

UnconnectedDateTimePicker.propTypes = _extends({
  fullValue: _propTypes2.default.string,
  updatePlot: _propTypes2.default.func,
  placeholder: _propTypes2.default.string
}, _Field2.default.propTypes);

exports.default = (0, _lib.connectToContainer)(UnconnectedDateTimePicker);
//# sourceMappingURL=DateTimePicker.js.map

/***/ }),

/***/ "PQhE":
/*!**********************************************************!*\
  !*** ./node_modules/draft-js/lib/DraftPasteProcessor.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DraftPasteProcessor
 * @format
 * 
 */



var _assign = __webpack_require__(/*! object-assign */ "MgzW");

var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var CharacterMetadata = __webpack_require__(/*! ./CharacterMetadata */ "lFJn");
var ContentBlock = __webpack_require__(/*! ./ContentBlock */ "8uQm");
var ContentBlockNode = __webpack_require__(/*! ./ContentBlockNode */ "JL7T");
var DraftFeatureFlags = __webpack_require__(/*! ./DraftFeatureFlags */ "cX45");
var Immutable = __webpack_require__(/*! immutable */ "JPcv");

var convertFromHTMLtoContentBlocks = __webpack_require__(/*! ./convertFromHTMLToContentBlocks */ "1qq2");
var generateRandomKey = __webpack_require__(/*! ./generateRandomKey */ "rJY1");
var getSafeBodyFromHTML = __webpack_require__(/*! ./getSafeBodyFromHTML */ "xocI");
var sanitizeDraftText = __webpack_require__(/*! ./sanitizeDraftText */ "HriT");

var List = Immutable.List,
    Repeat = Immutable.Repeat;


var experimentalTreeDataSupport = DraftFeatureFlags.draft_tree_data_support;
var ContentBlockRecord = experimentalTreeDataSupport ? ContentBlockNode : ContentBlock;

var DraftPasteProcessor = {
  processHTML: function processHTML(html, blockRenderMap) {
    return convertFromHTMLtoContentBlocks(html, getSafeBodyFromHTML, blockRenderMap);
  },
  processText: function processText(textBlocks, character, type) {
    return textBlocks.reduce(function (acc, textLine, index) {
      textLine = sanitizeDraftText(textLine);
      var key = generateRandomKey();

      var blockNodeConfig = {
        key: key,
        type: type,
        text: textLine,
        characterList: List(Repeat(character, textLine.length))
      };

      // next block updates previous block
      if (experimentalTreeDataSupport && index !== 0) {
        var prevSiblingIndex = index - 1;
        // update previous block
        var previousBlock = acc[prevSiblingIndex] = acc[prevSiblingIndex].merge({
          nextSibling: key
        });
        blockNodeConfig = _extends({}, blockNodeConfig, {
          prevSibling: previousBlock.getKey()
        });
      }

      acc.push(new ContentBlockRecord(blockNodeConfig));

      return acc;
    }, []);
  }
};

module.exports = DraftPasteProcessor;

/***/ }),

/***/ "PShT":
/*!*********************************************************!*\
  !*** ./node_modules/mdi-react/ReorderHorizontalIcon.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var ReorderHorizontalIcon = function ReorderHorizontalIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M3,15H21V13H3V15M3,19H21V17H3V19M3,11H21V9H3V11M3,5V7H21V5H3Z' })
  );
};

module.exports = ReorderHorizontalIcon;


/***/ }),

/***/ "PZa4":
/*!*******************************************************************!*\
  !*** ./node_modules/@jupyterlab/coreutils/lib/activitymonitor.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
/**
 * A class that monitors activity on a signal.
 */
class ActivityMonitor {
    /**
     * Construct a new activity monitor.
     */
    constructor(options) {
        this._timer = -1;
        this._timeout = -1;
        this._isDisposed = false;
        this._activityStopped = new signaling_1.Signal(this);
        options.signal.connect(this._onSignalFired, this);
        this._timeout = options.timeout || 1000;
    }
    /**
     * A signal emitted when activity has ceased.
     */
    get activityStopped() {
        return this._activityStopped;
    }
    /**
     * The timeout associated with the monitor, in milliseconds.
     */
    get timeout() {
        return this._timeout;
    }
    set timeout(value) {
        this._timeout = value;
    }
    /**
     * Test whether the monitor has been disposed.
     *
     * #### Notes
     * This is a read-only property.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources used by the activity monitor.
     */
    dispose() {
        if (this._isDisposed) {
            return;
        }
        this._isDisposed = true;
        signaling_1.Signal.clearData(this);
    }
    /**
     * A signal handler for the monitored signal.
     */
    _onSignalFired(sender, args) {
        clearTimeout(this._timer);
        this._sender = sender;
        this._args = args;
        this._timer = window.setTimeout(() => {
            this._activityStopped.emit({
                sender: this._sender,
                args: this._args
            });
        }, this._timeout);
    }
}
exports.ActivityMonitor = ActivityMonitor;


/***/ }),

/***/ "Pa+m":
/*!*************************************************************!*\
  !*** ./node_modules/elliptic/lib/elliptic/curve/edwards.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var curve = __webpack_require__(/*! ../curve */ "QTa/");
var elliptic = __webpack_require__(/*! ../../elliptic */ "MzeL");
var BN = __webpack_require__(/*! bn.js */ "OZ/i");
var inherits = __webpack_require__(/*! inherits */ "P7XM");
var Base = curve.base;

var assert = elliptic.utils.assert;

function EdwardsCurve(conf) {
  // NOTE: Important as we are creating point in Base.call()
  this.twisted = (conf.a | 0) !== 1;
  this.mOneA = this.twisted && (conf.a | 0) === -1;
  this.extended = this.mOneA;

  Base.call(this, 'edwards', conf);

  this.a = new BN(conf.a, 16).umod(this.red.m);
  this.a = this.a.toRed(this.red);
  this.c = new BN(conf.c, 16).toRed(this.red);
  this.c2 = this.c.redSqr();
  this.d = new BN(conf.d, 16).toRed(this.red);
  this.dd = this.d.redAdd(this.d);

  assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);
  this.oneC = (conf.c | 0) === 1;
}
inherits(EdwardsCurve, Base);
module.exports = EdwardsCurve;

EdwardsCurve.prototype._mulA = function _mulA(num) {
  if (this.mOneA)
    return num.redNeg();
  else
    return this.a.redMul(num);
};

EdwardsCurve.prototype._mulC = function _mulC(num) {
  if (this.oneC)
    return num;
  else
    return this.c.redMul(num);
};

// Just for compatibility with Short curve
EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {
  return this.point(x, y, z, t);
};

EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {
  x = new BN(x, 16);
  if (!x.red)
    x = x.toRed(this.red);

  var x2 = x.redSqr();
  var rhs = this.c2.redSub(this.a.redMul(x2));
  var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));

  var y2 = rhs.redMul(lhs.redInvm());
  var y = y2.redSqrt();
  if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
    throw new Error('invalid point');

  var isOdd = y.fromRed().isOdd();
  if (odd && !isOdd || !odd && isOdd)
    y = y.redNeg();

  return this.point(x, y);
};

EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {
  y = new BN(y, 16);
  if (!y.red)
    y = y.toRed(this.red);

  // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)
  var y2 = y.redSqr();
  var lhs = y2.redSub(this.c2);
  var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);
  var x2 = lhs.redMul(rhs.redInvm());

  if (x2.cmp(this.zero) === 0) {
    if (odd)
      throw new Error('invalid point');
    else
      return this.point(this.zero, y);
  }

  var x = x2.redSqrt();
  if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)
    throw new Error('invalid point');

  if (x.fromRed().isOdd() !== odd)
    x = x.redNeg();

  return this.point(x, y);
};

EdwardsCurve.prototype.validate = function validate(point) {
  if (point.isInfinity())
    return true;

  // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
  point.normalize();

  var x2 = point.x.redSqr();
  var y2 = point.y.redSqr();
  var lhs = x2.redMul(this.a).redAdd(y2);
  var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));

  return lhs.cmp(rhs) === 0;
};

function Point(curve, x, y, z, t) {
  Base.BasePoint.call(this, curve, 'projective');
  if (x === null && y === null && z === null) {
    this.x = this.curve.zero;
    this.y = this.curve.one;
    this.z = this.curve.one;
    this.t = this.curve.zero;
    this.zOne = true;
  } else {
    this.x = new BN(x, 16);
    this.y = new BN(y, 16);
    this.z = z ? new BN(z, 16) : this.curve.one;
    this.t = t && new BN(t, 16);
    if (!this.x.red)
      this.x = this.x.toRed(this.curve.red);
    if (!this.y.red)
      this.y = this.y.toRed(this.curve.red);
    if (!this.z.red)
      this.z = this.z.toRed(this.curve.red);
    if (this.t && !this.t.red)
      this.t = this.t.toRed(this.curve.red);
    this.zOne = this.z === this.curve.one;

    // Use extended coordinates
    if (this.curve.extended && !this.t) {
      this.t = this.x.redMul(this.y);
      if (!this.zOne)
        this.t = this.t.redMul(this.z.redInvm());
    }
  }
}
inherits(Point, Base.BasePoint);

EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
  return Point.fromJSON(this, obj);
};

EdwardsCurve.prototype.point = function point(x, y, z, t) {
  return new Point(this, x, y, z, t);
};

Point.fromJSON = function fromJSON(curve, obj) {
  return new Point(curve, obj[0], obj[1], obj[2]);
};

Point.prototype.inspect = function inspect() {
  if (this.isInfinity())
    return '<EC Point Infinity>';
  return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
      ' y: ' + this.y.fromRed().toString(16, 2) +
      ' z: ' + this.z.fromRed().toString(16, 2) + '>';
};

Point.prototype.isInfinity = function isInfinity() {
  // XXX This code assumes that zero is always zero in red
  return this.x.cmpn(0) === 0 &&
    (this.y.cmp(this.z) === 0 ||
    (this.zOne && this.y.cmp(this.curve.c) === 0));
};

Point.prototype._extDbl = function _extDbl() {
  // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
  //     #doubling-dbl-2008-hwcd
  // 4M + 4S

  // A = X1^2
  var a = this.x.redSqr();
  // B = Y1^2
  var b = this.y.redSqr();
  // C = 2 * Z1^2
  var c = this.z.redSqr();
  c = c.redIAdd(c);
  // D = a * A
  var d = this.curve._mulA(a);
  // E = (X1 + Y1)^2 - A - B
  var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);
  // G = D + B
  var g = d.redAdd(b);
  // F = G - C
  var f = g.redSub(c);
  // H = D - B
  var h = d.redSub(b);
  // X3 = E * F
  var nx = e.redMul(f);
  // Y3 = G * H
  var ny = g.redMul(h);
  // T3 = E * H
  var nt = e.redMul(h);
  // Z3 = F * G
  var nz = f.redMul(g);
  return this.curve.point(nx, ny, nz, nt);
};

Point.prototype._projDbl = function _projDbl() {
  // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
  //     #doubling-dbl-2008-bbjlp
  //     #doubling-dbl-2007-bl
  // and others
  // Generally 3M + 4S or 2M + 4S

  // B = (X1 + Y1)^2
  var b = this.x.redAdd(this.y).redSqr();
  // C = X1^2
  var c = this.x.redSqr();
  // D = Y1^2
  var d = this.y.redSqr();

  var nx;
  var ny;
  var nz;
  if (this.curve.twisted) {
    // E = a * C
    var e = this.curve._mulA(c);
    // F = E + D
    var f = e.redAdd(d);
    if (this.zOne) {
      // X3 = (B - C - D) * (F - 2)
      nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));
      // Y3 = F * (E - D)
      ny = f.redMul(e.redSub(d));
      // Z3 = F^2 - 2 * F
      nz = f.redSqr().redSub(f).redSub(f);
    } else {
      // H = Z1^2
      var h = this.z.redSqr();
      // J = F - 2 * H
      var j = f.redSub(h).redISub(h);
      // X3 = (B-C-D)*J
      nx = b.redSub(c).redISub(d).redMul(j);
      // Y3 = F * (E - D)
      ny = f.redMul(e.redSub(d));
      // Z3 = F * J
      nz = f.redMul(j);
    }
  } else {
    // E = C + D
    var e = c.redAdd(d);
    // H = (c * Z1)^2
    var h = this.curve._mulC(this.z).redSqr();
    // J = E - 2 * H
    var j = e.redSub(h).redSub(h);
    // X3 = c * (B - E) * J
    nx = this.curve._mulC(b.redISub(e)).redMul(j);
    // Y3 = c * E * (C - D)
    ny = this.curve._mulC(e).redMul(c.redISub(d));
    // Z3 = E * J
    nz = e.redMul(j);
  }
  return this.curve.point(nx, ny, nz);
};

Point.prototype.dbl = function dbl() {
  if (this.isInfinity())
    return this;

  // Double in extended coordinates
  if (this.curve.extended)
    return this._extDbl();
  else
    return this._projDbl();
};

Point.prototype._extAdd = function _extAdd(p) {
  // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
  //     #addition-add-2008-hwcd-3
  // 8M

  // A = (Y1 - X1) * (Y2 - X2)
  var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));
  // B = (Y1 + X1) * (Y2 + X2)
  var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));
  // C = T1 * k * T2
  var c = this.t.redMul(this.curve.dd).redMul(p.t);
  // D = Z1 * 2 * Z2
  var d = this.z.redMul(p.z.redAdd(p.z));
  // E = B - A
  var e = b.redSub(a);
  // F = D - C
  var f = d.redSub(c);
  // G = D + C
  var g = d.redAdd(c);
  // H = B + A
  var h = b.redAdd(a);
  // X3 = E * F
  var nx = e.redMul(f);
  // Y3 = G * H
  var ny = g.redMul(h);
  // T3 = E * H
  var nt = e.redMul(h);
  // Z3 = F * G
  var nz = f.redMul(g);
  return this.curve.point(nx, ny, nz, nt);
};

Point.prototype._projAdd = function _projAdd(p) {
  // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
  //     #addition-add-2008-bbjlp
  //     #addition-add-2007-bl
  // 10M + 1S

  // A = Z1 * Z2
  var a = this.z.redMul(p.z);
  // B = A^2
  var b = a.redSqr();
  // C = X1 * X2
  var c = this.x.redMul(p.x);
  // D = Y1 * Y2
  var d = this.y.redMul(p.y);
  // E = d * C * D
  var e = this.curve.d.redMul(c).redMul(d);
  // F = B - E
  var f = b.redSub(e);
  // G = B + E
  var g = b.redAdd(e);
  // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)
  var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);
  var nx = a.redMul(f).redMul(tmp);
  var ny;
  var nz;
  if (this.curve.twisted) {
    // Y3 = A * G * (D - a * C)
    ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));
    // Z3 = F * G
    nz = f.redMul(g);
  } else {
    // Y3 = A * G * (D - C)
    ny = a.redMul(g).redMul(d.redSub(c));
    // Z3 = c * F * G
    nz = this.curve._mulC(f).redMul(g);
  }
  return this.curve.point(nx, ny, nz);
};

Point.prototype.add = function add(p) {
  if (this.isInfinity())
    return p;
  if (p.isInfinity())
    return this;

  if (this.curve.extended)
    return this._extAdd(p);
  else
    return this._projAdd(p);
};

Point.prototype.mul = function mul(k) {
  if (this._hasDoubles(k))
    return this.curve._fixedNafMul(this, k);
  else
    return this.curve._wnafMul(this, k);
};

Point.prototype.mulAdd = function mulAdd(k1, p, k2) {
  return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);
};

Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) {
  return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);
};

Point.prototype.normalize = function normalize() {
  if (this.zOne)
    return this;

  // Normalize coordinates
  var zi = this.z.redInvm();
  this.x = this.x.redMul(zi);
  this.y = this.y.redMul(zi);
  if (this.t)
    this.t = this.t.redMul(zi);
  this.z = this.curve.one;
  this.zOne = true;
  return this;
};

Point.prototype.neg = function neg() {
  return this.curve.point(this.x.redNeg(),
                          this.y,
                          this.z,
                          this.t && this.t.redNeg());
};

Point.prototype.getX = function getX() {
  this.normalize();
  return this.x.fromRed();
};

Point.prototype.getY = function getY() {
  this.normalize();
  return this.y.fromRed();
};

Point.prototype.eq = function eq(other) {
  return this === other ||
         this.getX().cmp(other.getX()) === 0 &&
         this.getY().cmp(other.getY()) === 0;
};

Point.prototype.eqXToP = function eqXToP(x) {
  var rx = x.toRed(this.curve.red).redMul(this.z);
  if (this.x.cmp(rx) === 0)
    return true;

  var xc = x.clone();
  var t = this.curve.redN.redMul(this.z);
  for (;;) {
    xc.iadd(this.curve.n);
    if (xc.cmp(this.curve.p) >= 0)
      return false;

    rx.redIAdd(t);
    if (this.x.cmp(rx) === 0)
      return true;
  }
};

// Compatibility with BaseCurve
Point.prototype.toP = Point.prototype.normalize;
Point.prototype.mixedAdd = Point.prototype.add;


/***/ }),

/***/ "PbVF":
/*!*******************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils/lib/vdom.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const ReactDOM = __importStar(__webpack_require__(/*! react-dom */ "i8i4"));
/**
 * Phosphor widget that encodes best practices for VDOM based rendering.
 */
class VDomRenderer extends widgets_1.Widget {
    constructor() {
        super(...arguments);
        this._modelChanged = new signaling_1.Signal(this);
    }
    /**
     * A signal emitted when the model changes.
     */
    get modelChanged() {
        return this._modelChanged;
    }
    /**
     * Set the model and fire changed signals.
     */
    set model(newValue) {
        if (this._model === newValue) {
            return;
        }
        if (this._model) {
            this._model.stateChanged.disconnect(this.update, this);
        }
        this._model = newValue;
        if (newValue) {
            newValue.stateChanged.connect(this.update, this);
        }
        this.update();
        this._modelChanged.emit(void 0);
    }
    /**
     * Get the current model.
     */
    get model() {
        return this._model;
    }
    /**
     * Dispose this widget.
     */
    dispose() {
        this._model = null;
        super.dispose();
    }
    /**
     * Called to update the state of the widget.
     *
     * The default implementation of this method triggers
     * VDOM based rendering by calling the this.render() method.
     */
    onUpdateRequest(msg) {
        let vnode = this.render();
        if (Array.isArray(vnode)) {
            ReactDOM.render(vnode, this.node);
        }
        else {
            ReactDOM.render(vnode, this.node);
        }
    }
    /* Called after the widget is attached to the DOM
     *
     * Make sure the widget is rendered, even if the model has not changed.
     */
    onAfterAttach(msg) {
        messaging_1.MessageLoop.sendMessage(this, widgets_1.Widget.Msg.UpdateRequest);
    }
}
exports.VDomRenderer = VDomRenderer;
/**
 * Phosphor widget that renders React Element(s).
 *
 * All messages will re-render the element.
 */
class ReactElementWidget extends VDomRenderer {
    /**
     * Creates a Phosphor widget that renders the element(s) `es`.
     */
    constructor(es) {
        super();
        this._es = es;
    }
    render() {
        return this._es;
    }
}
exports.ReactElementWidget = ReactElementWidget;
/**
 * Concrete implementation of VDomRenderer model.
 */
class VDomModel {
    constructor() {
        /**
         * A signal emitted when any model state changes.
         */
        this.stateChanged = new signaling_1.Signal(this);
        this._isDisposed = false;
    }
    /**
     * Test whether the model is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose the model.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        signaling_1.Signal.clearData(this);
    }
}
exports.VDomModel = VDomModel;


/***/ }),

/***/ "PeUW":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/ta.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var symbolMap = {
    '1': '௧',
    '2': '௨',
    '3': '௩',
    '4': '௪',
    '5': '௫',
    '6': '௬',
    '7': '௭',
    '8': '௮',
    '9': '௯',
    '0': '௦'
}, numberMap = {
    '௧': '1',
    '௨': '2',
    '௩': '3',
    '௪': '4',
    '௫': '5',
    '௬': '6',
    '௭': '7',
    '௮': '8',
    '௯': '9',
    '௦': '0'
};

var ta = moment.defineLocale('ta', {
    months : 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split('_'),
    monthsShort : 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split('_'),
    weekdays : 'ஞாயிற்றுக்கிழமை_திங்கட்கிழமை_செவ்வாய்கிழமை_புதன்கிழமை_வியாழக்கிழமை_வெள்ளிக்கிழமை_சனிக்கிழமை'.split('_'),
    weekdaysShort : 'ஞாயிறு_திங்கள்_செவ்வாய்_புதன்_வியாழன்_வெள்ளி_சனி'.split('_'),
    weekdaysMin : 'ஞா_தி_செ_பு_வி_வெ_ச'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY, HH:mm',
        LLLL : 'dddd, D MMMM YYYY, HH:mm'
    },
    calendar : {
        sameDay : '[இன்று] LT',
        nextDay : '[நாளை] LT',
        nextWeek : 'dddd, LT',
        lastDay : '[நேற்று] LT',
        lastWeek : '[கடந்த வாரம்] dddd, LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : '%s இல்',
        past : '%s முன்',
        s : 'ஒரு சில விநாடிகள்',
        ss : '%d விநாடிகள்',
        m : 'ஒரு நிமிடம்',
        mm : '%d நிமிடங்கள்',
        h : 'ஒரு மணி நேரம்',
        hh : '%d மணி நேரம்',
        d : 'ஒரு நாள்',
        dd : '%d நாட்கள்',
        M : 'ஒரு மாதம்',
        MM : '%d மாதங்கள்',
        y : 'ஒரு வருடம்',
        yy : '%d ஆண்டுகள்'
    },
    dayOfMonthOrdinalParse: /\d{1,2}வது/,
    ordinal : function (number) {
        return number + 'வது';
    },
    preparse: function (string) {
        return string.replace(/[௧௨௩௪௫௬௭௮௯௦]/g, function (match) {
            return numberMap[match];
        });
    },
    postformat: function (string) {
        return string.replace(/\d/g, function (match) {
            return symbolMap[match];
        });
    },
    // refer http://ta.wikipedia.org/s/1er1
    meridiemParse: /யாமம்|வைகறை|காலை|நண்பகல்|எற்பாடு|மாலை/,
    meridiem : function (hour, minute, isLower) {
        if (hour < 2) {
            return ' யாமம்';
        } else if (hour < 6) {
            return ' வைகறை';  // வைகறை
        } else if (hour < 10) {
            return ' காலை'; // காலை
        } else if (hour < 14) {
            return ' நண்பகல்'; // நண்பகல்
        } else if (hour < 18) {
            return ' எற்பாடு'; // எற்பாடு
        } else if (hour < 22) {
            return ' மாலை'; // மாலை
        } else {
            return ' யாமம்';
        }
    },
    meridiemHour : function (hour, meridiem) {
        if (hour === 12) {
            hour = 0;
        }
        if (meridiem === 'யாமம்') {
            return hour < 2 ? hour : hour + 12;
        } else if (meridiem === 'வைகறை' || meridiem === 'காலை') {
            return hour;
        } else if (meridiem === 'நண்பகல்') {
            return hour >= 10 ? hour : hour + 12;
        } else {
            return hour + 12;
        }
    },
    week : {
        dow : 0, // Sunday is the first day of the week.
        doy : 6  // The week that contains Jan 1st is the first week of the year.
    }
});

return ta;

})));


/***/ }),

/***/ "PhsB":
/*!******************************************!*\
  !*** ./node_modules/xterm/lib/Parser.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var EscapeSequences_1 = __webpack_require__(/*! ./EscapeSequences */ "XYdm");
var Charsets_1 = __webpack_require__(/*! ./Charsets */ "rlhY");
var normalStateHandler = {};
normalStateHandler[EscapeSequences_1.C0.BEL] = function (parser, handler) { return handler.bell(); };
normalStateHandler[EscapeSequences_1.C0.LF] = function (parser, handler) { return handler.lineFeed(); };
normalStateHandler[EscapeSequences_1.C0.VT] = normalStateHandler[EscapeSequences_1.C0.LF];
normalStateHandler[EscapeSequences_1.C0.FF] = normalStateHandler[EscapeSequences_1.C0.LF];
normalStateHandler[EscapeSequences_1.C0.CR] = function (parser, handler) { return handler.carriageReturn(); };
normalStateHandler[EscapeSequences_1.C0.BS] = function (parser, handler) { return handler.backspace(); };
normalStateHandler[EscapeSequences_1.C0.HT] = function (parser, handler) { return handler.tab(); };
normalStateHandler[EscapeSequences_1.C0.SO] = function (parser, handler) { return handler.shiftOut(); };
normalStateHandler[EscapeSequences_1.C0.SI] = function (parser, handler) { return handler.shiftIn(); };
normalStateHandler[EscapeSequences_1.C0.ESC] = function (parser, handler) { return parser.setState(ParserState.ESCAPED); };
var escapedStateHandler = {};
escapedStateHandler['['] = function (parser, terminal) {
    terminal.params = [];
    terminal.currentParam = 0;
    parser.setState(ParserState.CSI_PARAM);
};
escapedStateHandler[']'] = function (parser, terminal) {
    terminal.params = [];
    terminal.currentParam = 0;
    parser.setState(ParserState.OSC);
};
escapedStateHandler['P'] = function (parser, terminal) {
    terminal.params = [];
    terminal.currentParam = 0;
    parser.setState(ParserState.DCS);
};
escapedStateHandler['_'] = function (parser, terminal) {
    parser.setState(ParserState.IGNORE);
};
escapedStateHandler['^'] = function (parser, terminal) {
    parser.setState(ParserState.IGNORE);
};
escapedStateHandler['c'] = function (parser, terminal) {
    terminal.reset();
};
escapedStateHandler['E'] = function (parser, terminal) {
    terminal.buffer.x = 0;
    terminal.index();
    parser.setState(ParserState.NORMAL);
};
escapedStateHandler['D'] = function (parser, terminal) {
    terminal.index();
    parser.setState(ParserState.NORMAL);
};
escapedStateHandler['M'] = function (parser, terminal) {
    terminal.reverseIndex();
    parser.setState(ParserState.NORMAL);
};
escapedStateHandler['%'] = function (parser, terminal) {
    terminal.setgLevel(0);
    terminal.setgCharset(0, Charsets_1.DEFAULT_CHARSET);
    parser.setState(ParserState.NORMAL);
    parser.skipNextChar();
};
escapedStateHandler[EscapeSequences_1.C0.CAN] = function (parser) { return parser.setState(ParserState.NORMAL); };
var csiParamStateHandler = {};
csiParamStateHandler['?'] = function (parser) { return parser.setPrefix('?'); };
csiParamStateHandler['>'] = function (parser) { return parser.setPrefix('>'); };
csiParamStateHandler['!'] = function (parser) { return parser.setPrefix('!'); };
csiParamStateHandler['0'] = function (parser) { return parser.setParam(parser.getParam() * 10); };
csiParamStateHandler['1'] = function (parser) { return parser.setParam(parser.getParam() * 10 + 1); };
csiParamStateHandler['2'] = function (parser) { return parser.setParam(parser.getParam() * 10 + 2); };
csiParamStateHandler['3'] = function (parser) { return parser.setParam(parser.getParam() * 10 + 3); };
csiParamStateHandler['4'] = function (parser) { return parser.setParam(parser.getParam() * 10 + 4); };
csiParamStateHandler['5'] = function (parser) { return parser.setParam(parser.getParam() * 10 + 5); };
csiParamStateHandler['6'] = function (parser) { return parser.setParam(parser.getParam() * 10 + 6); };
csiParamStateHandler['7'] = function (parser) { return parser.setParam(parser.getParam() * 10 + 7); };
csiParamStateHandler['8'] = function (parser) { return parser.setParam(parser.getParam() * 10 + 8); };
csiParamStateHandler['9'] = function (parser) { return parser.setParam(parser.getParam() * 10 + 9); };
csiParamStateHandler['$'] = function (parser) { return parser.setPostfix('$'); };
csiParamStateHandler['"'] = function (parser) { return parser.setPostfix('"'); };
csiParamStateHandler[' '] = function (parser) { return parser.setPostfix(' '); };
csiParamStateHandler['\''] = function (parser) { return parser.setPostfix('\''); };
csiParamStateHandler[';'] = function (parser) { return parser.finalizeParam(); };
csiParamStateHandler[EscapeSequences_1.C0.CAN] = function (parser) { return parser.setState(ParserState.NORMAL); };
var csiStateHandler = {};
csiStateHandler['@'] = function (handler, params, prefix) { return handler.insertChars(params); };
csiStateHandler['A'] = function (handler, params, prefix) { return handler.cursorUp(params); };
csiStateHandler['B'] = function (handler, params, prefix) { return handler.cursorDown(params); };
csiStateHandler['C'] = function (handler, params, prefix) { return handler.cursorForward(params); };
csiStateHandler['D'] = function (handler, params, prefix) { return handler.cursorBackward(params); };
csiStateHandler['E'] = function (handler, params, prefix) { return handler.cursorNextLine(params); };
csiStateHandler['F'] = function (handler, params, prefix) { return handler.cursorPrecedingLine(params); };
csiStateHandler['G'] = function (handler, params, prefix) { return handler.cursorCharAbsolute(params); };
csiStateHandler['H'] = function (handler, params, prefix) { return handler.cursorPosition(params); };
csiStateHandler['I'] = function (handler, params, prefix) { return handler.cursorForwardTab(params); };
csiStateHandler['J'] = function (handler, params, prefix) { return handler.eraseInDisplay(params); };
csiStateHandler['K'] = function (handler, params, prefix) { return handler.eraseInLine(params); };
csiStateHandler['L'] = function (handler, params, prefix) { return handler.insertLines(params); };
csiStateHandler['M'] = function (handler, params, prefix) { return handler.deleteLines(params); };
csiStateHandler['P'] = function (handler, params, prefix) { return handler.deleteChars(params); };
csiStateHandler['S'] = function (handler, params, prefix) { return handler.scrollUp(params); };
csiStateHandler['T'] = function (handler, params, prefix) {
    if (params.length < 2 && !prefix) {
        handler.scrollDown(params);
    }
};
csiStateHandler['X'] = function (handler, params, prefix) { return handler.eraseChars(params); };
csiStateHandler['Z'] = function (handler, params, prefix) { return handler.cursorBackwardTab(params); };
csiStateHandler['`'] = function (handler, params, prefix) { return handler.charPosAbsolute(params); };
csiStateHandler['a'] = function (handler, params, prefix) { return handler.HPositionRelative(params); };
csiStateHandler['b'] = function (handler, params, prefix) { return handler.repeatPrecedingCharacter(params); };
csiStateHandler['c'] = function (handler, params, prefix) { return handler.sendDeviceAttributes(params); };
csiStateHandler['d'] = function (handler, params, prefix) { return handler.linePosAbsolute(params); };
csiStateHandler['e'] = function (handler, params, prefix) { return handler.VPositionRelative(params); };
csiStateHandler['f'] = function (handler, params, prefix) { return handler.HVPosition(params); };
csiStateHandler['g'] = function (handler, params, prefix) { return handler.tabClear(params); };
csiStateHandler['h'] = function (handler, params, prefix) { return handler.setMode(params); };
csiStateHandler['l'] = function (handler, params, prefix) { return handler.resetMode(params); };
csiStateHandler['m'] = function (handler, params, prefix) { return handler.charAttributes(params); };
csiStateHandler['n'] = function (handler, params, prefix) { return handler.deviceStatus(params); };
csiStateHandler['p'] = function (handler, params, prefix) {
    switch (prefix) {
        case '!':
            handler.softReset(params);
            break;
    }
};
csiStateHandler['q'] = function (handler, params, prefix, postfix) {
    if (postfix === ' ') {
        handler.setCursorStyle(params);
    }
};
csiStateHandler['r'] = function (handler, params) { return handler.setScrollRegion(params); };
csiStateHandler['s'] = function (handler, params) { return handler.saveCursor(params); };
csiStateHandler['u'] = function (handler, params) { return handler.restoreCursor(params); };
csiStateHandler[EscapeSequences_1.C0.CAN] = function (handler, params, prefix, postfix, parser) { return parser.setState(ParserState.NORMAL); };
var ParserState;
(function (ParserState) {
    ParserState[ParserState["NORMAL"] = 0] = "NORMAL";
    ParserState[ParserState["ESCAPED"] = 1] = "ESCAPED";
    ParserState[ParserState["CSI_PARAM"] = 2] = "CSI_PARAM";
    ParserState[ParserState["CSI"] = 3] = "CSI";
    ParserState[ParserState["OSC"] = 4] = "OSC";
    ParserState[ParserState["CHARSET"] = 5] = "CHARSET";
    ParserState[ParserState["DCS"] = 6] = "DCS";
    ParserState[ParserState["IGNORE"] = 7] = "IGNORE";
})(ParserState = exports.ParserState || (exports.ParserState = {}));
var Parser = (function () {
    function Parser(_inputHandler, _terminal) {
        this._inputHandler = _inputHandler;
        this._terminal = _terminal;
        this._state = ParserState.NORMAL;
    }
    Parser.prototype.parse = function (data) {
        var l = data.length;
        var cs;
        var ch;
        var code;
        var low;
        var cursorStartX = this._terminal.buffer.x;
        var cursorStartY = this._terminal.buffer.y;
        if (this._terminal.debug) {
            this._terminal.log('data: ' + data);
        }
        this._position = 0;
        if (this._terminal.surrogate_high) {
            data = this._terminal.surrogate_high + data;
            this._terminal.surrogate_high = '';
        }
        for (; this._position < l; this._position++) {
            ch = data[this._position];
            code = data.charCodeAt(this._position);
            if (0xD800 <= code && code <= 0xDBFF) {
                low = data.charCodeAt(this._position + 1);
                if (isNaN(low)) {
                    this._terminal.surrogate_high = ch;
                    continue;
                }
                code = ((code - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
                ch += data.charAt(this._position + 1);
            }
            if (0xDC00 <= code && code <= 0xDFFF) {
                continue;
            }
            switch (this._state) {
                case ParserState.NORMAL:
                    if (ch in normalStateHandler) {
                        normalStateHandler[ch](this, this._inputHandler);
                    }
                    else {
                        this._inputHandler.addChar(ch, code);
                    }
                    break;
                case ParserState.ESCAPED:
                    if (ch in escapedStateHandler) {
                        escapedStateHandler[ch](this, this._terminal);
                        break;
                    }
                    switch (ch) {
                        case '(':
                        case ')':
                        case '*':
                        case '+':
                        case '-':
                        case '.':
                            switch (ch) {
                                case '(':
                                    this._terminal.gcharset = 0;
                                    break;
                                case ')':
                                    this._terminal.gcharset = 1;
                                    break;
                                case '*':
                                    this._terminal.gcharset = 2;
                                    break;
                                case '+':
                                    this._terminal.gcharset = 3;
                                    break;
                                case '-':
                                    this._terminal.gcharset = 1;
                                    break;
                                case '.':
                                    this._terminal.gcharset = 2;
                                    break;
                            }
                            this._state = ParserState.CHARSET;
                            break;
                        case '/':
                            this._terminal.gcharset = 3;
                            this._state = ParserState.CHARSET;
                            this._position--;
                            break;
                        case 'N':
                            this._state = ParserState.NORMAL;
                            break;
                        case 'O':
                            this._state = ParserState.NORMAL;
                            break;
                        case 'n':
                            this._terminal.setgLevel(2);
                            this._state = ParserState.NORMAL;
                            break;
                        case 'o':
                            this._terminal.setgLevel(3);
                            this._state = ParserState.NORMAL;
                            break;
                        case '|':
                            this._terminal.setgLevel(3);
                            this._state = ParserState.NORMAL;
                            break;
                        case '}':
                            this._terminal.setgLevel(2);
                            this._state = ParserState.NORMAL;
                            break;
                        case '~':
                            this._terminal.setgLevel(1);
                            this._state = ParserState.NORMAL;
                            break;
                        case '7':
                            this._inputHandler.saveCursor();
                            this._state = ParserState.NORMAL;
                            break;
                        case '8':
                            this._inputHandler.restoreCursor();
                            this._state = ParserState.NORMAL;
                            break;
                        case '#':
                            this._state = ParserState.NORMAL;
                            this._position++;
                            break;
                        case 'H':
                            this._terminal.tabSet();
                            this._state = ParserState.NORMAL;
                            break;
                        case '=':
                            this._terminal.log('Serial port requested application keypad.');
                            this._terminal.applicationKeypad = true;
                            if (this._terminal.viewport) {
                                this._terminal.viewport.syncScrollArea();
                            }
                            this._state = ParserState.NORMAL;
                            break;
                        case '>':
                            this._terminal.log('Switching back to normal keypad.');
                            this._terminal.applicationKeypad = false;
                            if (this._terminal.viewport) {
                                this._terminal.viewport.syncScrollArea();
                            }
                            this._state = ParserState.NORMAL;
                            break;
                        default:
                            this._state = ParserState.NORMAL;
                            this._terminal.error('Unknown ESC control: %s.', ch);
                            break;
                    }
                    break;
                case ParserState.CHARSET:
                    if (ch in Charsets_1.CHARSETS) {
                        cs = Charsets_1.CHARSETS[ch];
                        if (ch === '/') {
                            this.skipNextChar();
                        }
                    }
                    else {
                        cs = Charsets_1.DEFAULT_CHARSET;
                    }
                    this._terminal.setgCharset(this._terminal.gcharset, cs);
                    this._terminal.gcharset = null;
                    this._state = ParserState.NORMAL;
                    break;
                case ParserState.OSC:
                    if (ch === EscapeSequences_1.C0.ESC || ch === EscapeSequences_1.C0.BEL) {
                        if (ch === EscapeSequences_1.C0.ESC)
                            this._position++;
                        this._terminal.params.push(this._terminal.currentParam);
                        switch (this._terminal.params[0]) {
                            case 0:
                            case 1:
                            case 2:
                                if (this._terminal.params[1]) {
                                    this._terminal.title = this._terminal.params[1];
                                    this._terminal.handleTitle(this._terminal.title);
                                }
                                break;
                            case 3:
                                break;
                            case 4:
                            case 5:
                                break;
                            case 10:
                            case 11:
                            case 12:
                            case 13:
                            case 14:
                            case 15:
                            case 16:
                            case 17:
                            case 18:
                            case 19:
                                break;
                            case 46:
                                break;
                            case 50:
                                break;
                            case 51:
                                break;
                            case 52:
                                break;
                            case 104:
                            case 105:
                            case 110:
                            case 111:
                            case 112:
                            case 113:
                            case 114:
                            case 115:
                            case 116:
                            case 117:
                            case 118:
                                break;
                        }
                        this._terminal.params = [];
                        this._terminal.currentParam = 0;
                        this._state = ParserState.NORMAL;
                    }
                    else {
                        if (!this._terminal.params.length) {
                            if (ch >= '0' && ch <= '9') {
                                this._terminal.currentParam =
                                    this._terminal.currentParam * 10 + ch.charCodeAt(0) - 48;
                            }
                            else if (ch === ';') {
                                this._terminal.params.push(this._terminal.currentParam);
                                this._terminal.currentParam = '';
                            }
                        }
                        else {
                            this._terminal.currentParam += ch;
                        }
                    }
                    break;
                case ParserState.CSI_PARAM:
                    if (ch in csiParamStateHandler) {
                        csiParamStateHandler[ch](this);
                        break;
                    }
                    this.finalizeParam();
                    this._state = ParserState.CSI;
                case ParserState.CSI:
                    if (ch in csiStateHandler) {
                        if (this._terminal.debug) {
                            this._terminal.log("CSI " + (this._terminal.prefix ? this._terminal.prefix : '') + " " + (this._terminal.params ? this._terminal.params.join(';') : '') + " " + (this._terminal.postfix ? this._terminal.postfix : '') + " " + ch);
                        }
                        csiStateHandler[ch](this._inputHandler, this._terminal.params, this._terminal.prefix, this._terminal.postfix, this);
                    }
                    else {
                        this._terminal.error('Unknown CSI code: %s.', ch);
                    }
                    this._state = ParserState.NORMAL;
                    this._terminal.prefix = '';
                    this._terminal.postfix = '';
                    break;
                case ParserState.DCS:
                    if (ch === EscapeSequences_1.C0.ESC || ch === EscapeSequences_1.C0.BEL) {
                        if (ch === EscapeSequences_1.C0.ESC)
                            this._position++;
                        var pt = void 0;
                        var valid = void 0;
                        switch (this._terminal.prefix) {
                            case '':
                                break;
                            case '$q':
                                pt = this._terminal.currentParam;
                                valid = false;
                                switch (pt) {
                                    case '"q':
                                        pt = '0"q';
                                        break;
                                    case '"p':
                                        pt = '61"p';
                                        break;
                                    case 'r':
                                        pt = ''
                                            + (this._terminal.buffer.scrollTop + 1)
                                            + ';'
                                            + (this._terminal.buffer.scrollBottom + 1)
                                            + 'r';
                                        break;
                                    case 'm':
                                        pt = '0m';
                                        break;
                                    default:
                                        this._terminal.error('Unknown DCS Pt: %s.', pt);
                                        pt = '';
                                        break;
                                }
                                this._terminal.send(EscapeSequences_1.C0.ESC + 'P' + +valid + '$r' + pt + EscapeSequences_1.C0.ESC + '\\');
                                break;
                            case '+p':
                                break;
                            case '+q':
                                pt = this._terminal.currentParam;
                                valid = false;
                                this._terminal.send(EscapeSequences_1.C0.ESC + 'P' + +valid + '+r' + pt + EscapeSequences_1.C0.ESC + '\\');
                                break;
                            default:
                                this._terminal.error('Unknown DCS prefix: %s.', this._terminal.prefix);
                                break;
                        }
                        this._terminal.currentParam = 0;
                        this._terminal.prefix = '';
                        this._state = ParserState.NORMAL;
                    }
                    else if (!this._terminal.currentParam) {
                        if (!this._terminal.prefix && ch !== '$' && ch !== '+') {
                            this._terminal.currentParam = ch;
                        }
                        else if (this._terminal.prefix.length === 2) {
                            this._terminal.currentParam = ch;
                        }
                        else {
                            this._terminal.prefix += ch;
                        }
                    }
                    else {
                        this._terminal.currentParam += ch;
                    }
                    break;
                case ParserState.IGNORE:
                    if (ch === EscapeSequences_1.C0.ESC || ch === EscapeSequences_1.C0.BEL) {
                        if (ch === EscapeSequences_1.C0.ESC)
                            this._position++;
                        this._state = ParserState.NORMAL;
                    }
                    break;
            }
        }
        if (this._terminal.buffer.x !== cursorStartX || this._terminal.buffer.y !== cursorStartY) {
            this._terminal.emit('cursormove');
        }
        return this._state;
    };
    Parser.prototype.setState = function (state) {
        this._state = state;
    };
    Parser.prototype.setPrefix = function (prefix) {
        this._terminal.prefix = prefix;
    };
    Parser.prototype.setPostfix = function (postfix) {
        this._terminal.postfix = postfix;
    };
    Parser.prototype.setParam = function (param) {
        this._terminal.currentParam = param;
    };
    Parser.prototype.getParam = function () {
        return this._terminal.currentParam;
    };
    Parser.prototype.finalizeParam = function () {
        this._terminal.params.push(this._terminal.currentParam);
        this._terminal.currentParam = 0;
    };
    Parser.prototype.skipNextChar = function () {
        this._position++;
    };
    return Parser;
}());
exports.Parser = Parser;

//# sourceMappingURL=Parser.js.map


/***/ }),

/***/ "Pkh7":
/*!***********************************************************************!*\
  !*** ./node_modules/react-resizable-rotatable-draggable/lib/utils.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getCursor = exports.getNewStyle = exports.degToRadian = exports.getAngle = exports.getLength = void 0;

var getLength = function getLength(x, y) {
  return Math.sqrt(x * x + y * y);
};

exports.getLength = getLength;

var getAngle = function getAngle(_ref, _ref2) {
  var x1 = _ref.x,
      y1 = _ref.y;
  var x2 = _ref2.x,
      y2 = _ref2.y;
  var dot = x1 * x2 + y1 * y2;
  var det = x1 * y2 - y1 * x2;
  var angle = Math.atan2(det, dot) / Math.PI * 180;
  return (angle + 360) % 360;
};

exports.getAngle = getAngle;

var degToRadian = function degToRadian(deg) {
  return deg * Math.PI / 180;
};

exports.degToRadian = degToRadian;

var cos = function cos(deg) {
  return Math.cos(degToRadian(deg));
};

var sin = function sin(deg) {
  return Math.sin(degToRadian(deg));
};

var setWidthAndDeltaW = function setWidthAndDeltaW(width, deltaW, minWidth) {
  var expectedWidth = width + deltaW;

  if (expectedWidth > minWidth) {
    width = expectedWidth;
  } else {
    deltaW = minWidth - width;
    width = minWidth;
  }

  return {
    width: width,
    deltaW: deltaW
  };
};

var setHeightAndDeltaH = function setHeightAndDeltaH(height, deltaH, minHeight) {
  var expectedHeight = height + deltaH;

  if (expectedHeight > minHeight) {
    height = expectedHeight;
  } else {
    deltaH = minHeight - height;
    height = minHeight;
  }

  return {
    height: height,
    deltaH: deltaH
  };
};

var getNewStyle = function getNewStyle(type, rect, deltaW, deltaH, ratio, minWidth, minHeight) {
  var width = rect.width,
      height = rect.height,
      centerX = rect.centerX,
      centerY = rect.centerY,
      rotateAngle = rect.rotateAngle;
  var widthFlag = width < 0 ? -1 : 1;
  var heightFlag = height < 0 ? -1 : 1;
  width = Math.abs(width);
  height = Math.abs(height);

  switch (type) {
    case 'r':
      {
        var widthAndDeltaW = setWidthAndDeltaW(width, deltaW, minWidth);
        width = widthAndDeltaW.width;
        deltaW = widthAndDeltaW.deltaW;

        if (ratio) {
          deltaH = deltaW / ratio;
          height = width / ratio;
          centerX += deltaW / 2 * cos(rotateAngle) - deltaH / 2 * sin(rotateAngle);
          centerY += deltaW / 2 * sin(rotateAngle) + deltaH / 2 * cos(rotateAngle);
        } else {
          centerX += deltaW / 2 * cos(rotateAngle);
          centerY += deltaW / 2 * sin(rotateAngle);
        }

        break;
      }

    case 'tr':
      {
        deltaH = -deltaH;

        var _widthAndDeltaW = setWidthAndDeltaW(width, deltaW, minWidth);

        width = _widthAndDeltaW.width;
        deltaW = _widthAndDeltaW.deltaW;
        var heightAndDeltaH = setHeightAndDeltaH(height, deltaH, minHeight);
        height = heightAndDeltaH.height;
        deltaH = heightAndDeltaH.deltaH;

        if (ratio) {
          deltaW = deltaH * ratio;
          width = height * ratio;
        }

        centerX += deltaW / 2 * cos(rotateAngle) + deltaH / 2 * sin(rotateAngle);
        centerY += deltaW / 2 * sin(rotateAngle) - deltaH / 2 * cos(rotateAngle);
        break;
      }

    case 'br':
      {
        var _widthAndDeltaW2 = setWidthAndDeltaW(width, deltaW, minWidth);

        width = _widthAndDeltaW2.width;
        deltaW = _widthAndDeltaW2.deltaW;

        var _heightAndDeltaH = setHeightAndDeltaH(height, deltaH, minHeight);

        height = _heightAndDeltaH.height;
        deltaH = _heightAndDeltaH.deltaH;

        if (ratio) {
          deltaW = deltaH * ratio;
          width = height * ratio;
        }

        centerX += deltaW / 2 * cos(rotateAngle) - deltaH / 2 * sin(rotateAngle);
        centerY += deltaW / 2 * sin(rotateAngle) + deltaH / 2 * cos(rotateAngle);
        break;
      }

    case 'b':
      {
        var _heightAndDeltaH2 = setHeightAndDeltaH(height, deltaH, minHeight);

        height = _heightAndDeltaH2.height;
        deltaH = _heightAndDeltaH2.deltaH;

        if (ratio) {
          deltaW = deltaH * ratio;
          width = height * ratio;
          centerX += deltaW / 2 * cos(rotateAngle) - deltaH / 2 * sin(rotateAngle);
          centerY += deltaW / 2 * sin(rotateAngle) + deltaH / 2 * cos(rotateAngle);
        } else {
          centerX -= deltaH / 2 * sin(rotateAngle);
          centerY += deltaH / 2 * cos(rotateAngle);
        }

        break;
      }

    case 'bl':
      {
        deltaW = -deltaW;

        var _widthAndDeltaW3 = setWidthAndDeltaW(width, deltaW, minWidth);

        width = _widthAndDeltaW3.width;
        deltaW = _widthAndDeltaW3.deltaW;

        var _heightAndDeltaH3 = setHeightAndDeltaH(height, deltaH, minHeight);

        height = _heightAndDeltaH3.height;
        deltaH = _heightAndDeltaH3.deltaH;

        if (ratio) {
          height = width / ratio;
          deltaH = deltaW / ratio;
        }

        centerX -= deltaW / 2 * cos(rotateAngle) + deltaH / 2 * sin(rotateAngle);
        centerY -= deltaW / 2 * sin(rotateAngle) - deltaH / 2 * cos(rotateAngle);
        break;
      }

    case 'l':
      {
        deltaW = -deltaW;

        var _widthAndDeltaW4 = setWidthAndDeltaW(width, deltaW, minWidth);

        width = _widthAndDeltaW4.width;
        deltaW = _widthAndDeltaW4.deltaW;

        if (ratio) {
          height = width / ratio;
          deltaH = deltaW / ratio;
          centerX -= deltaW / 2 * cos(rotateAngle) + deltaH / 2 * sin(rotateAngle);
          centerY -= deltaW / 2 * sin(rotateAngle) - deltaH / 2 * cos(rotateAngle);
        } else {
          centerX -= deltaW / 2 * cos(rotateAngle);
          centerY -= deltaW / 2 * sin(rotateAngle);
        }

        break;
      }

    case 'tl':
      {
        deltaW = -deltaW;
        deltaH = -deltaH;

        var _widthAndDeltaW5 = setWidthAndDeltaW(width, deltaW, minWidth);

        width = _widthAndDeltaW5.width;
        deltaW = _widthAndDeltaW5.deltaW;

        var _heightAndDeltaH4 = setHeightAndDeltaH(height, deltaH, minHeight);

        height = _heightAndDeltaH4.height;
        deltaH = _heightAndDeltaH4.deltaH;

        if (ratio) {
          width = height * ratio;
          deltaW = deltaH * ratio;
        }

        centerX -= deltaW / 2 * cos(rotateAngle) - deltaH / 2 * sin(rotateAngle);
        centerY -= deltaW / 2 * sin(rotateAngle) + deltaH / 2 * cos(rotateAngle);
        break;
      }

    case 't':
      {
        deltaH = -deltaH;

        var _heightAndDeltaH5 = setHeightAndDeltaH(height, deltaH, minHeight);

        height = _heightAndDeltaH5.height;
        deltaH = _heightAndDeltaH5.deltaH;

        if (ratio) {
          width = height * ratio;
          deltaW = deltaH * ratio;
          centerX += deltaW / 2 * cos(rotateAngle) + deltaH / 2 * sin(rotateAngle);
          centerY += deltaW / 2 * sin(rotateAngle) - deltaH / 2 * cos(rotateAngle);
        } else {
          centerX += deltaH / 2 * sin(rotateAngle);
          centerY -= deltaH / 2 * cos(rotateAngle);
        }

        break;
      }
  }

  return {
    position: {
      centerX: centerX,
      centerY: centerY
    },
    size: {
      width: width * widthFlag,
      height: height * heightFlag
    }
  };
};

exports.getNewStyle = getNewStyle;

var getCursor = function getCursor(rotateAngle, d) {
  var startMap = {
    n: 0,
    ne: 1,
    e: 2,
    se: 3,
    s: 4,
    sw: 5,
    w: 6,
    nw: 7
  };
  var directionArray = ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'];
  var map = {
    0: 0,
    1: 1,
    2: 2,
    3: 2,
    4: 3,
    5: 4,
    6: 4,
    7: 5,
    8: 6,
    9: 6,
    10: 7,
    11: 8
  };
  var increment = map[Math.floor(rotateAngle / 30)];
  var index = startMap[d];
  var newIndex = (index + increment) % 8;
  return directionArray[newIndex];
};

exports.getCursor = getCursor;

/***/ }),

/***/ "PpIw":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/kn.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var symbolMap = {
    '1': '೧',
    '2': '೨',
    '3': '೩',
    '4': '೪',
    '5': '೫',
    '6': '೬',
    '7': '೭',
    '8': '೮',
    '9': '೯',
    '0': '೦'
},
numberMap = {
    '೧': '1',
    '೨': '2',
    '೩': '3',
    '೪': '4',
    '೫': '5',
    '೬': '6',
    '೭': '7',
    '೮': '8',
    '೯': '9',
    '೦': '0'
};

var kn = moment.defineLocale('kn', {
    months : 'ಜನವರಿ_ಫೆಬ್ರವರಿ_ಮಾರ್ಚ್_ಏಪ್ರಿಲ್_ಮೇ_ಜೂನ್_ಜುಲೈ_ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂಬರ್_ಅಕ್ಟೋಬರ್_ನವೆಂಬರ್_ಡಿಸೆಂಬರ್'.split('_'),
    monthsShort : 'ಜನ_ಫೆಬ್ರ_ಮಾರ್ಚ್_ಏಪ್ರಿಲ್_ಮೇ_ಜೂನ್_ಜುಲೈ_ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂ_ಅಕ್ಟೋ_ನವೆಂ_ಡಿಸೆಂ'.split('_'),
    monthsParseExact: true,
    weekdays : 'ಭಾನುವಾರ_ಸೋಮವಾರ_ಮಂಗಳವಾರ_ಬುಧವಾರ_ಗುರುವಾರ_ಶುಕ್ರವಾರ_ಶನಿವಾರ'.split('_'),
    weekdaysShort : 'ಭಾನು_ಸೋಮ_ಮಂಗಳ_ಬುಧ_ಗುರು_ಶುಕ್ರ_ಶನಿ'.split('_'),
    weekdaysMin : 'ಭಾ_ಸೋ_ಮಂ_ಬು_ಗು_ಶು_ಶ'.split('_'),
    longDateFormat : {
        LT : 'A h:mm',
        LTS : 'A h:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY, A h:mm',
        LLLL : 'dddd, D MMMM YYYY, A h:mm'
    },
    calendar : {
        sameDay : '[ಇಂದು] LT',
        nextDay : '[ನಾಳೆ] LT',
        nextWeek : 'dddd, LT',
        lastDay : '[ನಿನ್ನೆ] LT',
        lastWeek : '[ಕೊನೆಯ] dddd, LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : '%s ನಂತರ',
        past : '%s ಹಿಂದೆ',
        s : 'ಕೆಲವು ಕ್ಷಣಗಳು',
        ss : '%d ಸೆಕೆಂಡುಗಳು',
        m : 'ಒಂದು ನಿಮಿಷ',
        mm : '%d ನಿಮಿಷ',
        h : 'ಒಂದು ಗಂಟೆ',
        hh : '%d ಗಂಟೆ',
        d : 'ಒಂದು ದಿನ',
        dd : '%d ದಿನ',
        M : 'ಒಂದು ತಿಂಗಳು',
        MM : '%d ತಿಂಗಳು',
        y : 'ಒಂದು ವರ್ಷ',
        yy : '%d ವರ್ಷ'
    },
    preparse: function (string) {
        return string.replace(/[೧೨೩೪೫೬೭೮೯೦]/g, function (match) {
            return numberMap[match];
        });
    },
    postformat: function (string) {
        return string.replace(/\d/g, function (match) {
            return symbolMap[match];
        });
    },
    meridiemParse: /ರಾತ್ರಿ|ಬೆಳಿಗ್ಗೆ|ಮಧ್ಯಾಹ್ನ|ಸಂಜೆ/,
    meridiemHour : function (hour, meridiem) {
        if (hour === 12) {
            hour = 0;
        }
        if (meridiem === 'ರಾತ್ರಿ') {
            return hour < 4 ? hour : hour + 12;
        } else if (meridiem === 'ಬೆಳಿಗ್ಗೆ') {
            return hour;
        } else if (meridiem === 'ಮಧ್ಯಾಹ್ನ') {
            return hour >= 10 ? hour : hour + 12;
        } else if (meridiem === 'ಸಂಜೆ') {
            return hour + 12;
        }
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 4) {
            return 'ರಾತ್ರಿ';
        } else if (hour < 10) {
            return 'ಬೆಳಿಗ್ಗೆ';
        } else if (hour < 17) {
            return 'ಮಧ್ಯಾಹ್ನ';
        } else if (hour < 20) {
            return 'ಸಂಜೆ';
        } else {
            return 'ರಾತ್ರಿ';
        }
    },
    dayOfMonthOrdinalParse: /\d{1,2}(ನೇ)/,
    ordinal : function (number) {
        return number + 'ನೇ';
    },
    week : {
        dow : 0, // Sunday is the first day of the week.
        doy : 6  // The week that contains Jan 1st is the first week of the year.
    }
});

return kn;

})));


/***/ }),

/***/ "PrNZ":
/*!******************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/faq-extension/style/index.css ***!
  \******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.jp-FAQ {\n  font-family: var(--jp-content-font-family);\n  line-height: var(--jp-content-line-height);\n  font-size: var(--jp-content-font-size1);\n  color: var(--jp-content-font-color1);\n  outline: none;\n  display: flex;\n  flex-direction: column;\n  min-width: 240px;\n  min-height: 120px;\n}\n\n.jp-FAQ-content {\n  overflow-y: auto;\n  padding: 32px;\n}\n", ""]);

// exports


/***/ }),

/***/ "PtnK":
/*!*****************************************************!*\
  !*** ./node_modules/xterm/lib/renderer/Renderer.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var TextRenderLayer_1 = __webpack_require__(/*! ./TextRenderLayer */ "i/Fu");
var SelectionRenderLayer_1 = __webpack_require__(/*! ./SelectionRenderLayer */ "Ipkf");
var CursorRenderLayer_1 = __webpack_require__(/*! ./CursorRenderLayer */ "makB");
var ColorManager_1 = __webpack_require__(/*! ./ColorManager */ "3ujF");
var LinkRenderLayer_1 = __webpack_require__(/*! ./LinkRenderLayer */ "3+mF");
var EventEmitter_1 = __webpack_require__(/*! ../EventEmitter */ "t2YR");
var RenderDebouncer_1 = __webpack_require__(/*! ../utils/RenderDebouncer */ "zjAe");
var ScreenDprMonitor_1 = __webpack_require__(/*! ../utils/ScreenDprMonitor */ "/qo6");
var Renderer = (function (_super) {
    __extends(Renderer, _super);
    function Renderer(_terminal, theme) {
        var _this = _super.call(this) || this;
        _this._terminal = _terminal;
        _this._isPaused = false;
        _this._needsFullRefresh = false;
        var allowTransparency = _this._terminal.options.allowTransparency;
        _this.colorManager = new ColorManager_1.ColorManager(document, allowTransparency);
        if (theme) {
            _this.colorManager.setTheme(theme);
        }
        _this._renderLayers = [
            new TextRenderLayer_1.TextRenderLayer(_this._terminal.screenElement, 0, _this.colorManager.colors, allowTransparency),
            new SelectionRenderLayer_1.SelectionRenderLayer(_this._terminal.screenElement, 1, _this.colorManager.colors),
            new LinkRenderLayer_1.LinkRenderLayer(_this._terminal.screenElement, 2, _this.colorManager.colors, _this._terminal),
            new CursorRenderLayer_1.CursorRenderLayer(_this._terminal.screenElement, 3, _this.colorManager.colors)
        ];
        _this.dimensions = {
            scaledCharWidth: null,
            scaledCharHeight: null,
            scaledCellWidth: null,
            scaledCellHeight: null,
            scaledCharLeft: null,
            scaledCharTop: null,
            scaledCanvasWidth: null,
            scaledCanvasHeight: null,
            canvasWidth: null,
            canvasHeight: null,
            actualCellWidth: null,
            actualCellHeight: null
        };
        _this._devicePixelRatio = window.devicePixelRatio;
        _this._updateDimensions();
        _this.onOptionsChanged();
        _this._renderDebouncer = new RenderDebouncer_1.RenderDebouncer(_this._terminal, _this._renderRows.bind(_this));
        _this._screenDprMonitor = new ScreenDprMonitor_1.ScreenDprMonitor();
        _this._screenDprMonitor.setListener(function () { return _this.onWindowResize(window.devicePixelRatio); });
        if ('IntersectionObserver' in window) {
            var observer = new IntersectionObserver(function (e) { return _this.onIntersectionChange(e[0]); }, { threshold: 0 });
            observer.observe(_this._terminal.element);
        }
        return _this;
    }
    Renderer.prototype.onIntersectionChange = function (entry) {
        this._isPaused = entry.intersectionRatio === 0;
        if (!this._isPaused && this._needsFullRefresh) {
            this._terminal.refresh(0, this._terminal.rows - 1);
        }
    };
    Renderer.prototype.onWindowResize = function (devicePixelRatio) {
        if (this._devicePixelRatio !== devicePixelRatio) {
            this._devicePixelRatio = devicePixelRatio;
            this.onResize(this._terminal.cols, this._terminal.rows);
        }
    };
    Renderer.prototype.setTheme = function (theme) {
        var _this = this;
        this.colorManager.setTheme(theme);
        this._renderLayers.forEach(function (l) {
            l.onThemeChanged(_this._terminal, _this.colorManager.colors);
            l.reset(_this._terminal);
        });
        if (this._isPaused) {
            this._needsFullRefresh = true;
        }
        else {
            this._terminal.refresh(0, this._terminal.rows - 1);
        }
        return this.colorManager.colors;
    };
    Renderer.prototype.onResize = function (cols, rows) {
        var _this = this;
        this._updateDimensions();
        this._renderLayers.forEach(function (l) { return l.resize(_this._terminal, _this.dimensions); });
        if (this._isPaused) {
            this._needsFullRefresh = true;
        }
        else {
            this._terminal.refresh(0, this._terminal.rows - 1);
        }
        this._terminal.screenElement.style.width = this.dimensions.canvasWidth + "px";
        this._terminal.screenElement.style.height = this.dimensions.canvasHeight + "px";
        this.emit('resize', {
            width: this.dimensions.canvasWidth,
            height: this.dimensions.canvasHeight
        });
    };
    Renderer.prototype.onCharSizeChanged = function () {
        this.onResize(this._terminal.cols, this._terminal.rows);
    };
    Renderer.prototype.onBlur = function () {
        var _this = this;
        this._runOperation(function (l) { return l.onBlur(_this._terminal); });
    };
    Renderer.prototype.onFocus = function () {
        var _this = this;
        this._runOperation(function (l) { return l.onFocus(_this._terminal); });
    };
    Renderer.prototype.onSelectionChanged = function (start, end) {
        var _this = this;
        this._runOperation(function (l) { return l.onSelectionChanged(_this._terminal, start, end); });
    };
    Renderer.prototype.onCursorMove = function () {
        var _this = this;
        this._runOperation(function (l) { return l.onCursorMove(_this._terminal); });
    };
    Renderer.prototype.onOptionsChanged = function () {
        var _this = this;
        this._runOperation(function (l) { return l.onOptionsChanged(_this._terminal); });
    };
    Renderer.prototype.clear = function () {
        var _this = this;
        this._runOperation(function (l) { return l.reset(_this._terminal); });
    };
    Renderer.prototype._runOperation = function (operation) {
        if (this._isPaused) {
            this._needsFullRefresh = true;
        }
        else {
            this._renderLayers.forEach(function (l) { return operation(l); });
        }
    };
    Renderer.prototype.refreshRows = function (start, end) {
        if (this._isPaused) {
            this._needsFullRefresh = true;
            return;
        }
        this._renderDebouncer.refresh(start, end);
    };
    Renderer.prototype._renderRows = function (start, end) {
        var _this = this;
        this._renderLayers.forEach(function (l) { return l.onGridChanged(_this._terminal, start, end); });
        this._terminal.emit('refresh', { start: start, end: end });
    };
    Renderer.prototype._updateDimensions = function () {
        if (!this._terminal.charMeasure.width || !this._terminal.charMeasure.height) {
            return;
        }
        this.dimensions.scaledCharWidth = Math.floor(this._terminal.charMeasure.width * window.devicePixelRatio);
        this.dimensions.scaledCharHeight = Math.ceil(this._terminal.charMeasure.height * window.devicePixelRatio);
        this.dimensions.scaledCellHeight = Math.floor(this.dimensions.scaledCharHeight * this._terminal.options.lineHeight);
        this.dimensions.scaledCharTop = this._terminal.options.lineHeight === 1 ? 0 : Math.round((this.dimensions.scaledCellHeight - this.dimensions.scaledCharHeight) / 2);
        this.dimensions.scaledCellWidth = this.dimensions.scaledCharWidth + Math.round(this._terminal.options.letterSpacing);
        this.dimensions.scaledCharLeft = Math.floor(this._terminal.options.letterSpacing / 2);
        this.dimensions.scaledCanvasHeight = this._terminal.rows * this.dimensions.scaledCellHeight;
        this.dimensions.scaledCanvasWidth = this._terminal.cols * this.dimensions.scaledCellWidth;
        this.dimensions.canvasHeight = Math.round(this.dimensions.scaledCanvasHeight / window.devicePixelRatio);
        this.dimensions.canvasWidth = Math.round(this.dimensions.scaledCanvasWidth / window.devicePixelRatio);
        this.dimensions.actualCellHeight = this.dimensions.canvasHeight / this._terminal.rows;
        this.dimensions.actualCellWidth = this.dimensions.canvasWidth / this._terminal.cols;
    };
    return Renderer;
}(EventEmitter_1.EventEmitter));
exports.Renderer = Renderer;

//# sourceMappingURL=Renderer.js.map


/***/ }),

/***/ "PuQA":
/*!*******************************************************!*\
  !*** ./node_modules/@jupyterlab/mainmenu/lib/help.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const labmenu_1 = __webpack_require__(/*! ./labmenu */ "e7FE");
/**
 * An extensible Help menu for the application.
 */
class HelpMenu extends labmenu_1.JupyterLabMenu {
    /**
     * Construct the help menu.
     */
    constructor(options) {
        super(options);
        this.menu.title.label = 'Help';
        this.kernelUsers = new Set();
    }
}
exports.HelpMenu = HelpMenu;


/***/ }),

/***/ "Pxmx":
/*!********************************************!*\
  !*** ./node_modules/base16/lib/default.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'default',
  author: 'chris kempson (http://chriskempson.com)',
  base00: '#181818',
  base01: '#282828',
  base02: '#383838',
  base03: '#585858',
  base04: '#b8b8b8',
  base05: '#d8d8d8',
  base06: '#e8e8e8',
  base07: '#f8f8f8',
  base08: '#ab4642',
  base09: '#dc9656',
  base0A: '#f7ca88',
  base0B: '#a1b56c',
  base0C: '#86c1b9',
  base0D: '#7cafc2',
  base0E: '#ba8baf',
  base0F: '#a16946'
};
module.exports = exports['default'];

/***/ }),

/***/ "Pzom":
/*!******************************************************************!*\
  !*** ./node_modules/react-color/lib/components/slider/Slider.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Slider = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _merge = __webpack_require__(/*! lodash/merge */ "QkVN");

var _merge2 = _interopRequireDefault(_merge);

var _common = __webpack_require__(/*! ../common */ "TM95");

var _SliderSwatches = __webpack_require__(/*! ./SliderSwatches */ "OYk8");

var _SliderSwatches2 = _interopRequireDefault(_SliderSwatches);

var _SliderPointer = __webpack_require__(/*! ./SliderPointer */ "dATH");

var _SliderPointer2 = _interopRequireDefault(_SliderPointer);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var Slider = exports.Slider = function Slider(_ref) {
  var hsl = _ref.hsl,
      onChange = _ref.onChange,
      pointer = _ref.pointer,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': {
      hue: {
        height: '12px',
        position: 'relative'
      },
      Hue: {
        radius: '2px'
      }
    }
  }, passedStyles));

  return _react2.default.createElement(
    'div',
    { style: styles.wrap || '', className: 'slider-picker ' + className },
    _react2.default.createElement(
      'div',
      { style: styles.hue },
      _react2.default.createElement(_common.Hue, {
        style: styles.Hue,
        hsl: hsl,
        pointer: pointer,
        onChange: onChange
      })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.swatches },
      _react2.default.createElement(_SliderSwatches2.default, { hsl: hsl, onClick: onChange })
    )
  );
};

Slider.propTypes = {
  styles: _propTypes2.default.object
};
Slider.defaultProps = {
  pointer: _SliderPointer2.default,
  styles: {}
};

exports.default = (0, _common.ColorWrap)(Slider);

/***/ }),

/***/ "Q/qy":
/*!********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/EditableText.js ***!
  \********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var ENTER_KEYCODE = 13;

// A generic component to handle text that can be edited when the user
// clicks on it.

var EditableText = function (_Component) {
  _inherits(EditableText, _Component);

  function EditableText(props) {
    _classCallCheck(this, EditableText);

    var _this = _possibleConstructorReturn(this, (EditableText.__proto__ || Object.getPrototypeOf(EditableText)).call(this, props));

    _this.handleFocus = _this.handleFocus.bind(_this);
    _this.handleChange = _this.handleChange.bind(_this);
    _this.handleUpdate = _this.handleUpdate.bind(_this);
    _this.handleKeyPress = _this.handleKeyPress.bind(_this);
    _this.handleWheel = _this.handleWheel.bind(_this);
    _this.getRef = _this.getRef.bind(_this);
    return _this;
  }

  _createClass(EditableText, [{
    key: 'getRef',
    value: function getRef(c) {
      this._ref = c;
    }

    // Selects/highlights all of the text in the filename input

  }, {
    key: 'handleFocus',
    value: function handleFocus(event) {
      event.target.select();
    }
  }, {
    key: 'handleChange',
    value: function handleChange(event) {
      var onChange = this.props.onChange;


      if (onChange) {
        onChange(event.target.value);
      }
    }
  }, {
    key: 'handleUpdate',
    value: function handleUpdate(event) {
      var onUpdate = this.props.onUpdate;


      if (onUpdate) {
        onUpdate(event.target.value);
      }
    }
  }, {
    key: 'handleKeyPress',
    value: function handleKeyPress(event) {
      // This will force handleUpdate to be called via the input's onBlur
      if ((event.keyCode || event.which) === ENTER_KEYCODE) {
        this._ref.blur();
      }
    }
  }, {
    key: 'handleWheel',
    value: function handleWheel(event) {
      if (this.props.onWheel && document.activeElement === this._ref) {
        this.props.onWheel(event);
      }
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          type = _props.type,
          className = _props.className,
          text = _props.text,
          disable = _props.disable,
          autoFocus = _props.autoFocus,
          onKeyDown = _props.onKeyDown,
          placeholder = _props.placeholder,
          readOnly = _props.readOnly,
          size = _props.size;

      return _react2.default.createElement('input', {
        ref: this.getRef,
        type: type,
        className: className || '',
        value: text,
        onFocus: this.handleFocus,
        onChange: this.handleChange,
        onBlur: this.handleUpdate,
        disabled: disable,
        autoFocus: autoFocus,
        onKeyPress: this.handleKeyPress,
        onKeyDown: onKeyDown,
        onWheel: this.handleWheel,
        placeholder: placeholder,
        readOnly: readOnly,
        size: size
      });
    }
  }]);

  return EditableText;
}(_react.Component);

EditableText.propTypes = {
  // Called with input value on changes (as the user types)
  onChange: _propTypes2.default.func,

  // Called with input value on blur (and enter if no onEnter is given)
  onUpdate: _propTypes2.default.func,

  // Called on input keyDown events
  onKeyDown: _propTypes2.default.func,

  onWheel: _propTypes2.default.func,
  // Input value property ...
  text: _propTypes2.default.any,

  // Input properties
  placeholder: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]),
  className: _propTypes2.default.string,
  disable: _propTypes2.default.bool,
  autoFocus: _propTypes2.default.bool,
  readOnly: _propTypes2.default.bool,
  type: _propTypes2.default.oneOf(['text', 'password']),
  size: _propTypes2.default.number
};

EditableText.defaultProps = {
  readOnly: false,
  type: 'text'
};

exports.default = EditableText;
//# sourceMappingURL=EditableText.js.map

/***/ }),

/***/ "Q1hF":
/*!**********************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/relink_private.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




var isArrayOrTypedArray = __webpack_require__(/*! ./array */ "avjU").isArrayOrTypedArray;
var isPlainObject = __webpack_require__(/*! ./is_plain_object */ "E4V0");

/**
 * Relink private _keys and keys with a function value from one container
 * to the new container.
 * Relink means copying if object is pass-by-value and adding a reference
 * if object is pass-by-ref.
 * This prevents deepCopying massive structures like a webgl context.
 */
module.exports = function relinkPrivateKeys(toContainer, fromContainer) {
    for(var k in fromContainer) {
        var fromVal = fromContainer[k];
        var toVal = toContainer[k];

        if(toVal === fromVal) {
            continue;
        }
        if(k.charAt(0) === '_' || typeof fromVal === 'function') {

            // if it already exists at this point, it's something
            // that we recreate each time around, so ignore it
            if(k in toContainer) continue;

            toContainer[k] = fromVal;
        }
        else if(isArrayOrTypedArray(fromVal) && isArrayOrTypedArray(toVal) && isPlainObject(fromVal[0])) {

            // filter out data_array items that can contain user objects
            // most of the time the toVal === fromVal check will catch these early
            // but if the user makes new ones we also don't want to recurse in.
            if(k === 'customdata' || k === 'ids') continue;

            // recurse into arrays containers
            var minLen = Math.min(fromVal.length, toVal.length);
            for(var j = 0; j < minLen; j++) {
                if((toVal[j] !== fromVal[j]) && isPlainObject(fromVal[j]) && isPlainObject(toVal[j])) {
                    relinkPrivateKeys(toVal[j], fromVal[j]);
                }
            }
        }
        else if(isPlainObject(fromVal) && isPlainObject(toVal)) {

            // recurse into objects, but only if they still exist
            relinkPrivateKeys(toVal, fromVal);

            if(!Object.keys(toVal).length) delete toContainer[k];
        }
    }
};


/***/ }),

/***/ "Q1l4":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_copyArray.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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;
}

module.exports = copyArray;


/***/ }),

/***/ "QFxM":
/*!**********************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/clean_number.js ***!
  \**********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




var isNumeric = __webpack_require__(/*! fast-isnumeric */ "GbLo");

var BADNUM = __webpack_require__(/*! ../constants/numerical */ "qrPk").BADNUM;

// precompile for speed
var JUNK = /^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g;

/**
 * cleanNumber: remove common leading and trailing cruft
 * Always returns either a number or BADNUM.
 */
module.exports = function cleanNumber(v) {
    if(typeof v === 'string') {
        v = v.replace(JUNK, '');
    }

    if(isNumeric(v)) return Number(v);

    return BADNUM;
};


/***/ }),

/***/ "QIyF":
/*!************************************!*\
  !*** ./node_modules/lodash/now.js ***!
  \************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var root = __webpack_require__(/*! ./_root */ "Kz5y");

/**
 * 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;


/***/ }),

/***/ "QJsb":
/*!*********************************************************************!*\
  !*** ./node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = {
  doubles: {
    step: 4,
    points: [
      [
        'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',
        'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'
      ],
      [
        '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',
        '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'
      ],
      [
        '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',
        'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'
      ],
      [
        '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',
        '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'
      ],
      [
        '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',
        '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'
      ],
      [
        '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',
        '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'
      ],
      [
        'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',
        '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'
      ],
      [
        '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',
        'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'
      ],
      [
        'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',
        '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'
      ],
      [
        'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',
        'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'
      ],
      [
        'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',
        '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'
      ],
      [
        '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',
        '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'
      ],
      [
        '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',
        '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'
      ],
      [
        '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',
        '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'
      ],
      [
        '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',
        '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'
      ],
      [
        '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',
        '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'
      ],
      [
        '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',
        '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'
      ],
      [
        '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',
        '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'
      ],
      [
        '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',
        'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'
      ],
      [
        'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',
        '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'
      ],
      [
        'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',
        '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'
      ],
      [
        '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',
        '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'
      ],
      [
        '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',
        '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'
      ],
      [
        'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',
        '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'
      ],
      [
        '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',
        'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'
      ],
      [
        'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',
        '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'
      ],
      [
        'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',
        'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'
      ],
      [
        'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',
        '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'
      ],
      [
        'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',
        'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'
      ],
      [
        'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',
        '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'
      ],
      [
        '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',
        'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'
      ],
      [
        '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',
        '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'
      ],
      [
        'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',
        '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'
      ],
      [
        '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',
        'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'
      ],
      [
        'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',
        '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'
      ],
      [
        'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',
        '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'
      ],
      [
        'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',
        'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'
      ],
      [
        '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',
        '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'
      ],
      [
        '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',
        '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'
      ],
      [
        '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',
        'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'
      ],
      [
        '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',
        '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'
      ],
      [
        'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',
        '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'
      ],
      [
        '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',
        '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'
      ],
      [
        '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',
        'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'
      ],
      [
        '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',
        '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'
      ],
      [
        'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',
        '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'
      ],
      [
        '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',
        'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'
      ],
      [
        'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',
        'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'
      ],
      [
        'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',
        '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'
      ],
      [
        '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',
        'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'
      ],
      [
        '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',
        'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'
      ],
      [
        'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',
        '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'
      ],
      [
        'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',
        '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'
      ],
      [
        'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',
        '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'
      ],
      [
        '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',
        'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'
      ],
      [
        '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',
        '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'
      ],
      [
        'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',
        'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'
      ],
      [
        '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',
        'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'
      ],
      [
        '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',
        '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'
      ],
      [
        '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',
        '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'
      ],
      [
        'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',
        'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'
      ],
      [
        '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',
        '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'
      ],
      [
        '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',
        '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'
      ],
      [
        'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',
        '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'
      ],
      [
        'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',
        'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'
      ]
    ]
  },
  naf: {
    wnd: 7,
    points: [
      [
        'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',
        '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'
      ],
      [
        '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',
        'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'
      ],
      [
        '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',
        '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'
      ],
      [
        'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',
        'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'
      ],
      [
        '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',
        'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'
      ],
      [
        'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',
        'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'
      ],
      [
        'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',
        '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'
      ],
      [
        'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',
        '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'
      ],
      [
        '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',
        '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'
      ],
      [
        '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',
        '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'
      ],
      [
        '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',
        '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'
      ],
      [
        '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',
        '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'
      ],
      [
        'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',
        'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'
      ],
      [
        'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',
        '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'
      ],
      [
        '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',
        'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'
      ],
      [
        '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',
        'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'
      ],
      [
        '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',
        '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'
      ],
      [
        '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',
        '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'
      ],
      [
        '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',
        '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'
      ],
      [
        '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',
        'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'
      ],
      [
        'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',
        'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'
      ],
      [
        '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',
        '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'
      ],
      [
        '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',
        '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'
      ],
      [
        'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',
        'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'
      ],
      [
        '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',
        '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'
      ],
      [
        'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',
        'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'
      ],
      [
        'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',
        'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'
      ],
      [
        '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',
        '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'
      ],
      [
        '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',
        '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'
      ],
      [
        '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',
        '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'
      ],
      [
        'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',
        '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'
      ],
      [
        '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',
        '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'
      ],
      [
        'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',
        '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'
      ],
      [
        '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',
        'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'
      ],
      [
        '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',
        'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'
      ],
      [
        'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',
        'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'
      ],
      [
        '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',
        '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'
      ],
      [
        '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',
        'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'
      ],
      [
        'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',
        'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'
      ],
      [
        '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',
        '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'
      ],
      [
        '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',
        'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'
      ],
      [
        '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',
        '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'
      ],
      [
        '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',
        'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'
      ],
      [
        'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',
        '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'
      ],
      [
        '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',
        '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'
      ],
      [
        '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',
        'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'
      ],
      [
        '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',
        'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'
      ],
      [
        'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',
        'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'
      ],
      [
        'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',
        'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'
      ],
      [
        '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',
        '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'
      ],
      [
        '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',
        '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'
      ],
      [
        'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',
        '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'
      ],
      [
        'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',
        'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'
      ],
      [
        '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',
        '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'
      ],
      [
        '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',
        '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'
      ],
      [
        'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',
        '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'
      ],
      [
        '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',
        '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'
      ],
      [
        'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',
        'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'
      ],
      [
        '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',
        'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'
      ],
      [
        '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',
        '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'
      ],
      [
        'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',
        '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'
      ],
      [
        'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',
        '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'
      ],
      [
        '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',
        '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'
      ],
      [
        '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',
        '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'
      ],
      [
        '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',
        'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'
      ],
      [
        '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',
        'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'
      ],
      [
        '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',
        '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'
      ],
      [
        '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',
        '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'
      ],
      [
        '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',
        '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'
      ],
      [
        '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',
        'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'
      ],
      [
        'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',
        'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'
      ],
      [
        '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',
        'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'
      ],
      [
        'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',
        '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'
      ],
      [
        'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',
        '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'
      ],
      [
        'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',
        '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'
      ],
      [
        'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',
        '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'
      ],
      [
        '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',
        'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'
      ],
      [
        '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',
        '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'
      ],
      [
        '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',
        'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'
      ],
      [
        'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',
        'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'
      ],
      [
        'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',
        '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'
      ],
      [
        'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',
        'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'
      ],
      [
        'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',
        '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'
      ],
      [
        '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',
        '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'
      ],
      [
        'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',
        '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'
      ],
      [
        'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',
        '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'
      ],
      [
        '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',
        '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'
      ],
      [
        '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',
        'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'
      ],
      [
        'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',
        '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'
      ],
      [
        'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',
        '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'
      ],
      [
        'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',
        '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'
      ],
      [
        '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',
        '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'
      ],
      [
        'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',
        'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'
      ],
      [
        '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',
        'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'
      ],
      [
        'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',
        'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'
      ],
      [
        'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',
        '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'
      ],
      [
        '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',
        'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'
      ],
      [
        'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',
        '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'
      ],
      [
        'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',
        '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'
      ],
      [
        'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',
        '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'
      ],
      [
        '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',
        'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'
      ],
      [
        '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',
        'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'
      ],
      [
        'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',
        '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'
      ],
      [
        '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',
        'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'
      ],
      [
        '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',
        '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'
      ],
      [
        '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',
        'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'
      ],
      [
        'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',
        'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'
      ],
      [
        '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',
        'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'
      ],
      [
        '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',
        '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'
      ],
      [
        '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',
        'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'
      ],
      [
        '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',
        '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'
      ],
      [
        'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',
        'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'
      ],
      [
        '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',
        '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'
      ],
      [
        'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',
        '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'
      ],
      [
        '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',
        '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'
      ],
      [
        'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',
        'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'
      ],
      [
        'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',
        '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'
      ],
      [
        'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',
        'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'
      ],
      [
        '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',
        'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'
      ],
      [
        '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',
        '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'
      ],
      [
        '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',
        'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'
      ],
      [
        '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',
        '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'
      ],
      [
        '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',
        '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'
      ],
      [
        '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',
        'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'
      ],
      [
        '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',
        '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'
      ],
      [
        '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',
        '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'
      ],
      [
        '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',
        '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'
      ]
    ]
  }
};


/***/ }),

/***/ "QKod":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/inspector/lib/handler.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const rendermime_1 = __webpack_require__(/*! @jupyterlab/rendermime */ "Towz");
/**
 * An object that handles code inspection.
 */
class InspectionHandler {
    /**
     * Construct a new inspection handler for a widget.
     */
    constructor(options) {
        this._disposed = new signaling_1.Signal(this);
        this._editor = null;
        this._ephemeralCleared = new signaling_1.Signal(this);
        this._inspected = new signaling_1.Signal(this);
        this._isDisposed = false;
        this._pending = 0;
        this._standby = true;
        this._connector = options.connector;
        this._rendermime = options.rendermime;
    }
    /**
     * A signal emitted when the handler is disposed.
     */
    get disposed() {
        return this._disposed;
    }
    /**
     * A signal emitted when inspector should clear all items with no history.
     */
    get ephemeralCleared() {
        return this._ephemeralCleared;
    }
    /**
     * A signal emitted when an inspector value is generated.
     */
    get inspected() {
        return this._inspected;
    }
    /**
     * The editor widget used by the inspection handler.
     */
    get editor() {
        return this._editor;
    }
    set editor(newValue) {
        if (newValue === this._editor) {
            return;
        }
        if (this._editor && !this._editor.isDisposed) {
            this._editor.model.value.changed.disconnect(this.onTextChanged, this);
        }
        let editor = (this._editor = newValue);
        if (editor) {
            // Clear ephemeral inspectors in preparation for a new editor.
            this._ephemeralCleared.emit(void 0);
            editor.model.value.changed.connect(this.onTextChanged, this);
        }
    }
    /**
     * Indicates whether the handler makes API inspection requests or stands by.
     *
     * #### Notes
     * The use case for this attribute is to limit the API traffic when no
     * inspector is visible.
     */
    get standby() {
        return this._standby;
    }
    set standby(value) {
        this._standby = value;
    }
    /**
     * Get whether the inspection handler is disposed.
     *
     * #### Notes
     * This is a read-only property.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources used by the handler.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        this._disposed.emit(void 0);
        signaling_1.Signal.clearData(this);
    }
    /**
     * Handle a text changed signal from an editor.
     *
     * #### Notes
     * Update the hints inspector based on a text change.
     */
    onTextChanged() {
        // If the handler is in standby mode, bail.
        if (this._standby) {
            return;
        }
        const editor = this.editor;
        if (!editor) {
            return;
        }
        const text = editor.model.value.text;
        const position = editor.getCursorPosition();
        const offset = coreutils_1.Text.jsIndexToCharIndex(editor.getOffsetAt(position), text);
        const update = {
            content: null,
            type: 'hints'
        };
        const pending = ++this._pending;
        this._connector
            .fetch({ offset, text })
            .then(reply => {
            // If handler has been disposed or a newer request is pending, bail.
            if (this.isDisposed || pending !== this._pending) {
                this._inspected.emit(update);
                return;
            }
            const { data } = reply;
            const mimeType = this._rendermime.preferredMimeType(data);
            if (mimeType) {
                const widget = this._rendermime.createRenderer(mimeType);
                const model = new rendermime_1.MimeModel({ data });
                widget.renderModel(model);
                update.content = widget;
            }
            this._inspected.emit(update);
        })
            .catch(reason => {
            // Since almost all failures are benign, fail silently.
            this._inspected.emit(update);
        });
    }
}
exports.InspectionHandler = InspectionHandler;


/***/ }),

/***/ "QLaP":
/*!*******************************************!*\
  !*** ./node_modules/invariant/browser.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */



/**
 * Use invariant() to assert state which your program assumes to be true.
 *
 * Provide sprintf-style format (only %s is supported) and arguments
 * to provide information about what broke and what you were
 * expecting.
 *
 * The invariant message will be stripped in production, but the invariant
 * will remain to ensure logic does not differ in production.
 */

var invariant = function(condition, format, a, b, c, d, e, f) {
  if (true) {
    if (format === undefined) {
      throw new Error('invariant requires an error message argument');
    }
  }

  if (!condition) {
    var error;
    if (format === undefined) {
      error = new Error(
        'Minified exception occurred; use the non-minified dev environment ' +
        'for the full error message and additional helpful warnings.'
      );
    } else {
      var args = [a, b, c, d, e, f];
      var argIndex = 0;
      error = new Error(
        format.replace(/%s/g, function() { return args[argIndex++]; })
      );
      error.name = 'Invariant Violation';
    }

    error.framesToPop = 1; // we don't care about invariant's own frame
    throw error;
  }
};

module.exports = invariant;


/***/ }),

/***/ "QMMT":
/*!**********************************************************!*\
  !*** ./node_modules/core-js/library/modules/_classof.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = __webpack_require__(/*! ./_cof */ "a0xu");
var TAG = __webpack_require__(/*! ./_wks */ "UWiX")('toStringTag');
// ES3 wrong here
var ARG = cof(function () { return arguments; }()) == 'Arguments';

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

module.exports = function (it) {
  var O, T, B;
  return it === undefined ? 'Undefined' : it === null ? 'Null'
    // @@toStringTag case
    : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
    // builtinTag case
    : ARG ? cof(O)
    // ES3 arguments fallback
    : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};


/***/ }),

/***/ "QN1r":
/*!********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/default_panels/StyleImagesPanel.js ***!
  \********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _components = __webpack_require__(/*! ../components */ "yF51");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var StyleImagesPanel = function StyleImagesPanel(props, _ref) {
  var _ = _ref.localize;
  return _react2.default.createElement(
    _components.ImageAccordion,
    { canAdd: true },
    _react2.default.createElement(_components.Radio, {
      attr: 'visible',
      options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
    }),
    _react2.default.createElement(_components.Dropzone, { attr: 'source', fileType: _('image'), show: true }),
    _react2.default.createElement(_components.Dropdown, {
      label: _('Aspect Ratio'),
      attr: 'sizing',
      options: [{ label: _('Contain'), value: 'contain' }, { label: _('Fill'), value: 'fill' }, { label: _('Stretch'), value: 'stretch' }],
      clearable: false
    }),
    _react2.default.createElement(_components.Radio, {
      label: _('Relative to Grid'),
      attr: 'layer',
      options: [{ label: _('Below'), value: 'below' }, { label: _('Above'), value: 'above' }]
    }),
    _react2.default.createElement(_components.PositioningNumeric, { attr: 'sizex', label: _('Width') }),
    _react2.default.createElement(_components.PositioningNumeric, { attr: 'sizey', label: _('Height') }),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Horizontal Positioning') },
      _react2.default.createElement(_components.Dropdown, {
        label: _('Anchor Point'),
        clearable: false,
        attr: 'xanchor',
        options: [{ label: _('Left'), value: 'left' }, { label: _('Center'), value: 'center' }, { label: _('Right'), value: 'right' }]
      }),
      _react2.default.createElement(_components.PositioningNumeric, { label: _('Position'), attr: 'x' }),
      _react2.default.createElement(_components.PositioningRef, { label: _('Relative To'), attr: 'xref' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Vertical Positioning') },
      _react2.default.createElement(_components.Dropdown, {
        label: _('Anchor Point'),
        clearable: false,
        attr: 'yanchor',
        options: [{ label: _('Top'), value: 'top' }, { label: _('Middle'), value: 'middle' }, { label: _('Bottom'), value: 'bottom' }]
      }),
      _react2.default.createElement(_components.PositioningNumeric, { label: _('Position'), attr: 'y' }),
      _react2.default.createElement(_components.PositioningRef, { label: _('Relative To'), attr: 'yref' })
    )
  );
};

StyleImagesPanel.contextTypes = {
  localize: _propTypes2.default.func
};

exports.default = StyleImagesPanel;
//# sourceMappingURL=StyleImagesPanel.js.map

/***/ }),

/***/ "QP8U":
/*!********************************************************************!*\
  !*** ./node_modules/@jupyterlab/fileeditor-extension/lib/index.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const application_1 = __webpack_require__(/*! @jupyterlab/application */ "FkFl");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const codeeditor_1 = __webpack_require__(/*! @jupyterlab/codeeditor */ "sLCx");
const console_1 = __webpack_require__(/*! @jupyterlab/console */ "DrOJ");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const filebrowser_1 = __webpack_require__(/*! @jupyterlab/filebrowser */ "my6z");
const fileeditor_1 = __webpack_require__(/*! @jupyterlab/fileeditor */ "RHTn");
const launcher_1 = __webpack_require__(/*! @jupyterlab/launcher */ "78yt");
const mainmenu_1 = __webpack_require__(/*! @jupyterlab/mainmenu */ "N4Qf");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
/**
 * The class name for the text editor icon from the default theme.
 */
const EDITOR_ICON_CLASS = 'jp-TextEditorIcon';
/**
 * The name of the factory that creates editor widgets.
 */
const FACTORY = 'Editor';
/**
 * The command IDs used by the fileeditor plugin.
 */
var CommandIDs;
(function (CommandIDs) {
    CommandIDs.createNew = 'fileeditor:create-new';
    CommandIDs.changeFontSize = 'fileeditor:change-font-size';
    CommandIDs.lineNumbers = 'fileeditor:toggle-line-numbers';
    CommandIDs.lineWrap = 'fileeditor:toggle-line-wrap';
    CommandIDs.changeTabs = 'fileeditor:change-tabs';
    CommandIDs.matchBrackets = 'fileeditor:toggle-match-brackets';
    CommandIDs.autoClosingBrackets = 'fileeditor:toggle-autoclosing-brackets';
    CommandIDs.createConsole = 'fileeditor:create-console';
    CommandIDs.runCode = 'fileeditor:run-code';
    CommandIDs.markdownPreview = 'fileeditor:markdown-preview';
})(CommandIDs || (CommandIDs = {}));
/**
 * The editor tracker extension.
 */
const plugin = {
    activate,
    id: '@jupyterlab/fileeditor-extension:plugin',
    requires: [
        console_1.IConsoleTracker,
        codeeditor_1.IEditorServices,
        filebrowser_1.IFileBrowserFactory,
        application_1.ILayoutRestorer,
        coreutils_1.ISettingRegistry
    ],
    optional: [apputils_1.ICommandPalette, launcher_1.ILauncher, mainmenu_1.IMainMenu],
    provides: fileeditor_1.IEditorTracker,
    autoStart: true
};
/**
 * Export the plugins as default.
 */
exports.default = plugin;
/**
 * Activate the editor tracker plugin.
 */
function activate(app, consoleTracker, editorServices, browserFactory, restorer, settingRegistry, palette, launcher, menu) {
    const id = plugin.id;
    const namespace = 'editor';
    const factory = new fileeditor_1.FileEditorFactory({
        editorServices,
        factoryOptions: {
            name: FACTORY,
            fileTypes: ['markdown', '*'],
            defaultFor: ['markdown', '*'] // it outranks the defaultRendered viewer.
        }
    });
    const { commands, restored } = app;
    const tracker = new apputils_1.InstanceTracker({
        namespace
    });
    const isEnabled = () => tracker.currentWidget !== null &&
        tracker.currentWidget === app.shell.currentWidget;
    let config = Object.assign({}, codeeditor_1.CodeEditor.defaultConfig);
    // Handle state restoration.
    restorer.restore(tracker, {
        command: 'docmanager:open',
        args: widget => ({ path: widget.context.path, factory: FACTORY }),
        name: widget => widget.context.path
    });
    /**
     * Update the setting values.
     */
    function updateSettings(settings) {
        let cached = settings.get('editorConfig').composite;
        Object.keys(config).forEach((key) => {
            config[key] =
                cached[key] === null || cached[key] === undefined
                    ? codeeditor_1.CodeEditor.defaultConfig[key]
                    : cached[key];
        });
        // Trigger a refresh of the rendered commands
        app.commands.notifyCommandChanged();
    }
    /**
     * Update the settings of the current tracker instances.
     */
    function updateTracker() {
        tracker.forEach(widget => {
            updateWidget(widget.content);
        });
    }
    /**
     * Update the settings of a widget.
     */
    function updateWidget(widget) {
        const editor = widget.editor;
        Object.keys(config).forEach((key) => {
            editor.setOption(key, config[key]);
        });
    }
    // Add a console creator to the File menu
    // Fetch the initial state of the settings.
    Promise.all([settingRegistry.load(id), restored])
        .then(([settings]) => {
        updateSettings(settings);
        updateTracker();
        settings.changed.connect(() => {
            updateSettings(settings);
            updateTracker();
        });
    })
        .catch((reason) => {
        console.error(reason.message);
        updateTracker();
    });
    factory.widgetCreated.connect((sender, widget) => {
        widget.title.icon = EDITOR_ICON_CLASS;
        // Notify the instance tracker if restore data needs to update.
        widget.context.pathChanged.connect(() => {
            tracker.save(widget);
        });
        tracker.add(widget);
        updateWidget(widget.content);
    });
    app.docRegistry.addWidgetFactory(factory);
    // Handle the settings of new widgets.
    tracker.widgetAdded.connect((sender, widget) => {
        updateWidget(widget.content);
    });
    // Add a command to change font size.
    commands.addCommand(CommandIDs.changeFontSize, {
        execute: args => {
            const delta = Number(args['delta']);
            if (Number.isNaN(delta)) {
                console.error(`${CommandIDs.changeFontSize}: delta arg must be a number`);
                return;
            }
            const style = window.getComputedStyle(document.documentElement);
            const cssSize = parseInt(style.getPropertyValue('--jp-code-font-size'), 10);
            const currentSize = config.fontSize || cssSize;
            config.fontSize = currentSize + delta;
            return settingRegistry
                .set(id, 'editorConfig', config)
                .catch((reason) => {
                console.error(`Failed to set ${id}: ${reason.message}`);
            });
        },
        isEnabled,
        label: args => args['name']
    });
    commands.addCommand(CommandIDs.lineNumbers, {
        execute: () => {
            config.lineNumbers = !config.lineNumbers;
            return settingRegistry
                .set(id, 'editorConfig', config)
                .catch((reason) => {
                console.error(`Failed to set ${id}: ${reason.message}`);
            });
        },
        isEnabled,
        isToggled: () => config.lineNumbers,
        label: 'Line Numbers'
    });
    commands.addCommand(CommandIDs.lineWrap, {
        execute: args => {
            const lineWrap = args['mode'] || 'off';
            config.lineWrap = lineWrap;
            return settingRegistry
                .set(id, 'editorConfig', config)
                .catch((reason) => {
                console.error(`Failed to set ${id}: ${reason.message}`);
            });
        },
        isEnabled,
        isToggled: args => {
            const lineWrap = args['mode'] || 'off';
            return config.lineWrap === lineWrap;
        },
        label: 'Word Wrap'
    });
    commands.addCommand(CommandIDs.changeTabs, {
        label: args => args['name'],
        execute: args => {
            config.tabSize = args['size'] || 4;
            config.insertSpaces = !!args['insertSpaces'];
            return settingRegistry
                .set(id, 'editorConfig', config)
                .catch((reason) => {
                console.error(`Failed to set ${id}: ${reason.message}`);
            });
        },
        isEnabled,
        isToggled: args => {
            const insertSpaces = !!args['insertSpaces'];
            const size = args['size'] || 4;
            return config.insertSpaces === insertSpaces && config.tabSize === size;
        }
    });
    commands.addCommand(CommandIDs.matchBrackets, {
        execute: () => {
            config.matchBrackets = !config.matchBrackets;
            return settingRegistry
                .set(id, 'editorConfig', config)
                .catch((reason) => {
                console.error(`Failed to set ${id}: ${reason.message}`);
            });
        },
        label: 'Match Brackets',
        isEnabled,
        isToggled: () => config.matchBrackets
    });
    commands.addCommand(CommandIDs.autoClosingBrackets, {
        execute: () => {
            config.autoClosingBrackets = !config.autoClosingBrackets;
            return settingRegistry
                .set(id, 'editorConfig', config)
                .catch((reason) => {
                console.error(`Failed to set ${id}: ${reason.message}`);
            });
        },
        label: 'Auto Close Brackets for Text Editor',
        isEnabled,
        isToggled: () => config.autoClosingBrackets
    });
    commands.addCommand(CommandIDs.createConsole, {
        execute: args => {
            const widget = tracker.currentWidget;
            if (!widget) {
                return;
            }
            return commands
                .execute('console:create', {
                activate: args['activate'],
                name: widget.context.contentsModel.name,
                path: widget.context.path,
                preferredLanguage: widget.context.model.defaultKernelLanguage,
                ref: widget.id,
                insertMode: 'split-bottom'
            })
                .then(console => {
                widget.context.pathChanged.connect((sender, value) => {
                    console.session.setPath(value);
                    console.session.setName(widget.context.contentsModel.name);
                });
            });
        },
        isEnabled,
        label: 'Create Console for Editor'
    });
    commands.addCommand(CommandIDs.runCode, {
        execute: () => {
            // Run the appropriate code, taking into account a ```fenced``` code block.
            const widget = tracker.currentWidget.content;
            if (!widget) {
                return;
            }
            let code = '';
            const editor = widget.editor;
            const path = widget.context.path;
            const extension = coreutils_1.PathExt.extname(path);
            const selection = editor.getSelection();
            const { start, end } = selection;
            let selected = start.column !== end.column || start.line !== end.line;
            if (selected) {
                // Get the selected code from the editor.
                const start = editor.getOffsetAt(selection.start);
                const end = editor.getOffsetAt(selection.end);
                code = editor.model.value.text.substring(start, end);
            }
            else if (coreutils_1.MarkdownCodeBlocks.isMarkdown(extension)) {
                const { text } = editor.model.value;
                const blocks = coreutils_1.MarkdownCodeBlocks.findMarkdownCodeBlocks(text);
                for (let block of blocks) {
                    if (block.startLine <= start.line && start.line <= block.endLine) {
                        code = block.code;
                        selected = true;
                        break;
                    }
                }
            }
            if (!selected) {
                // no selection, submit whole line and advance
                code = editor.getLine(selection.start.line);
                const cursor = editor.getCursorPosition();
                if (cursor.line + 1 === editor.lineCount) {
                    let text = editor.model.value.text;
                    editor.model.value.text = text + '\n';
                }
                editor.setCursorPosition({
                    line: cursor.line + 1,
                    column: cursor.column
                });
            }
            const activate = false;
            if (code) {
                return commands.execute('console:inject', { activate, code, path });
            }
            else {
                return Promise.resolve(void 0);
            }
        },
        isEnabled,
        label: 'Run Code'
    });
    commands.addCommand(CommandIDs.markdownPreview, {
        execute: () => {
            let widget = tracker.currentWidget;
            if (!widget) {
                return;
            }
            let path = widget.context.path;
            return commands.execute('markdownviewer:open', {
                path,
                options: {
                    mode: 'split-right'
                }
            });
        },
        isVisible: () => {
            let widget = tracker.currentWidget;
            return ((widget && coreutils_1.PathExt.extname(widget.context.path) === '.md') || false);
        },
        label: 'Show Markdown Preview'
    });
    // Function to create a new untitled text file, given
    // the current working directory.
    const createNew = (cwd) => {
        return commands
            .execute('docmanager:new-untitled', {
            path: cwd,
            type: 'file'
        })
            .then(model => {
            return commands.execute('docmanager:open', {
                path: model.path,
                factory: FACTORY
            });
        });
    };
    // Add a command for creating a new text file.
    commands.addCommand(CommandIDs.createNew, {
        label: 'Text File',
        caption: 'Create a new text file',
        iconClass: EDITOR_ICON_CLASS,
        execute: args => {
            let cwd = args['cwd'] || browserFactory.defaultBrowser.model.path;
            return createNew(cwd);
        }
    });
    // Add a launcher item if the launcher is available.
    if (launcher) {
        launcher.add({
            command: CommandIDs.createNew,
            category: 'Other',
            rank: 1
        });
    }
    if (palette) {
        let args = {
            insertSpaces: false,
            size: 4,
            name: 'Indent with Tab'
        };
        let command = 'fileeditor:change-tabs';
        palette.addItem({ command, args, category: 'Text Editor' });
        for (let size of [1, 2, 4, 8]) {
            let args = {
                insertSpaces: true,
                size,
                name: `Spaces: ${size} `
            };
            palette.addItem({ command, args, category: 'Text Editor' });
        }
        args = { name: 'Increase Font Size', delta: 1 };
        command = CommandIDs.changeFontSize;
        palette.addItem({ command, args, category: 'Text Editor' });
        args = { name: 'Decrease Font Size', delta: -1 };
        command = CommandIDs.changeFontSize;
        palette.addItem({ command, args, category: 'Text Editor' });
    }
    if (menu) {
        // Add the editing commands to the settings menu.
        const tabMenu = new widgets_1.Menu({ commands });
        tabMenu.title.label = 'Text Editor Indentation';
        let args = {
            insertSpaces: false,
            size: 4,
            name: 'Indent with Tab'
        };
        let command = 'fileeditor:change-tabs';
        tabMenu.addItem({ command, args });
        for (let size of [1, 2, 4, 8]) {
            let args = {
                insertSpaces: true,
                size,
                name: `Spaces: ${size} `
            };
            tabMenu.addItem({ command, args });
        }
        menu.settingsMenu.addGroup([
            {
                command: CommandIDs.changeFontSize,
                args: { name: 'Increase Text Editor Font Size', delta: +1 }
            },
            {
                command: CommandIDs.changeFontSize,
                args: { name: 'Decrease Text Editor Font Size', delta: -1 }
            },
            { type: 'submenu', submenu: tabMenu },
            { command: CommandIDs.autoClosingBrackets }
        ], 30);
        // Add new text file creation to the file menu.
        menu.fileMenu.newMenu.addGroup([{ command: CommandIDs.createNew }], 30);
        // Add undo/redo hooks to the edit menu.
        menu.editMenu.undoers.add({
            tracker,
            undo: widget => {
                widget.content.editor.undo();
            },
            redo: widget => {
                widget.content.editor.redo();
            }
        });
        // Add editor view options.
        menu.viewMenu.editorViewers.add({
            tracker,
            toggleLineNumbers: widget => {
                const lineNumbers = !widget.content.editor.getOption('lineNumbers');
                widget.content.editor.setOption('lineNumbers', lineNumbers);
            },
            toggleWordWrap: widget => {
                const oldValue = widget.content.editor.getOption('lineWrap');
                const newValue = oldValue === 'off' ? 'on' : 'off';
                widget.content.editor.setOption('lineWrap', newValue);
            },
            toggleMatchBrackets: widget => {
                const matchBrackets = !widget.content.editor.getOption('matchBrackets');
                widget.content.editor.setOption('matchBrackets', matchBrackets);
            },
            lineNumbersToggled: widget => widget.content.editor.getOption('lineNumbers'),
            wordWrapToggled: widget => widget.content.editor.getOption('lineWrap') !== 'off',
            matchBracketsToggled: widget => widget.content.editor.getOption('matchBrackets')
        });
        // Add a console creator the the Kernel menu.
        menu.fileMenu.consoleCreators.add({
            tracker,
            name: 'Editor',
            createConsole: current => {
                const options = {
                    path: current.context.path,
                    preferredLanguage: current.context.model.defaultKernelLanguage
                };
                return commands.execute('console:create', options);
            }
        });
        // Add a code runner to the Run menu.
        menu.runMenu.codeRunners.add({
            tracker,
            noun: 'Code',
            isEnabled: current => {
                let found = false;
                consoleTracker.forEach(console => {
                    if (console.console.session.path === current.context.path) {
                        found = true;
                    }
                });
                return found;
            },
            run: () => commands.execute(CommandIDs.runCode)
        });
    }
    app.contextMenu.addItem({
        command: CommandIDs.createConsole,
        selector: '.jp-FileEditor'
    });
    app.contextMenu.addItem({
        command: CommandIDs.markdownPreview,
        selector: '.jp-FileEditor'
    });
    return tracker;
}


/***/ }),

/***/ "QRH4":
/*!*****************************************!*\
  !*** ./node_modules/parse-asn1/asn1.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
// from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js
// Fedor, you are amazing.


var asn1 = __webpack_require__(/*! asn1.js */ "f3pb")

exports.certificate = __webpack_require__(/*! ./certificate */ "VrUr")

var RSAPrivateKey = asn1.define('RSAPrivateKey', function () {
  this.seq().obj(
    this.key('version').int(),
    this.key('modulus').int(),
    this.key('publicExponent').int(),
    this.key('privateExponent').int(),
    this.key('prime1').int(),
    this.key('prime2').int(),
    this.key('exponent1').int(),
    this.key('exponent2').int(),
    this.key('coefficient').int()
  )
})
exports.RSAPrivateKey = RSAPrivateKey

var RSAPublicKey = asn1.define('RSAPublicKey', function () {
  this.seq().obj(
    this.key('modulus').int(),
    this.key('publicExponent').int()
  )
})
exports.RSAPublicKey = RSAPublicKey

var PublicKey = asn1.define('SubjectPublicKeyInfo', function () {
  this.seq().obj(
    this.key('algorithm').use(AlgorithmIdentifier),
    this.key('subjectPublicKey').bitstr()
  )
})
exports.PublicKey = PublicKey

var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () {
  this.seq().obj(
    this.key('algorithm').objid(),
    this.key('none').null_().optional(),
    this.key('curve').objid().optional(),
    this.key('params').seq().obj(
      this.key('p').int(),
      this.key('q').int(),
      this.key('g').int()
    ).optional()
  )
})

var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () {
  this.seq().obj(
    this.key('version').int(),
    this.key('algorithm').use(AlgorithmIdentifier),
    this.key('subjectPrivateKey').octstr()
  )
})
exports.PrivateKey = PrivateKeyInfo
var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () {
  this.seq().obj(
    this.key('algorithm').seq().obj(
      this.key('id').objid(),
      this.key('decrypt').seq().obj(
        this.key('kde').seq().obj(
          this.key('id').objid(),
          this.key('kdeparams').seq().obj(
            this.key('salt').octstr(),
            this.key('iters').int()
          )
        ),
        this.key('cipher').seq().obj(
          this.key('algo').objid(),
          this.key('iv').octstr()
        )
      )
    ),
    this.key('subjectPrivateKey').octstr()
  )
})

exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo

var DSAPrivateKey = asn1.define('DSAPrivateKey', function () {
  this.seq().obj(
    this.key('version').int(),
    this.key('p').int(),
    this.key('q').int(),
    this.key('g').int(),
    this.key('pub_key').int(),
    this.key('priv_key').int()
  )
})
exports.DSAPrivateKey = DSAPrivateKey

exports.DSAparam = asn1.define('DSAparam', function () {
  this.int()
})

var ECPrivateKey = asn1.define('ECPrivateKey', function () {
  this.seq().obj(
    this.key('version').int(),
    this.key('privateKey').octstr(),
    this.key('parameters').optional().explicit(0).use(ECParameters),
    this.key('publicKey').optional().explicit(1).bitstr()
  )
})
exports.ECPrivateKey = ECPrivateKey

var ECParameters = asn1.define('ECParameters', function () {
  this.choice({
    namedCurve: this.objid()
  })
})

exports.signature = asn1.define('signature', function () {
  this.seq().obj(
    this.key('r').int(),
    this.key('s').int()
  )
})


/***/ }),

/***/ "QTZ7":
/*!***************************************************************!*\
  !*** ./node_modules/jupyterlab-chart-editor/lib/component.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var React = __webpack_require__(/*! react */ "q1tI");
var react_chart_editor_1 = __webpack_require__(/*! react-chart-editor */ "sca4");
__webpack_require__(/*! react-chart-editor/lib/react-chart-editor.css */ "5+Ew");
var ChartEditor = /** @class */ (function (_super) {
    __extends(ChartEditor, _super);
    function ChartEditor(props) {
        var _this = _super.call(this, props) || this;
        _this.handleUpdate = function (data, layout, frames) {
            _this.setState(function () { return ({
                data: data,
                layout: layout,
                frames: frames
            }); });
            _this.props.handleUpdate({ data: data, layout: layout, frames: frames });
        };
        _this.handleRender = function (data, layout, frames) {
            _this.props.handleUpdate({ data: data, layout: layout, frames: frames });
        };
        _this.handleResize = function () {
            if (_this.ref.state.graphDiv instanceof HTMLElement)
                _this.props.plotly.Plots.resize(_this.ref.state.graphDiv);
        };
        var initialState = {
            data: props.state ? props.state.data || [] : [],
            layout: props.state ? props.state.layout || {} : {},
            frames: props.state ? props.state.frames || [] : []
        };
        // TODO: Remove after upgrading to React 16.3
        _this.state = initialState;
        return _this;
    }
    ChartEditor.getDerivedStateFromProps = function (nextProps, prevState) {
        return prevState;
    };
    ChartEditor.prototype.render = function () {
        var _this = this;
        var plotly = this.props.plotly;
        var _a = this.state, data = _a.data, layout = _a.layout, frames = _a.frames;
        var config = { editable: true };
        return (React.createElement("div", { className: "container" },
            React.createElement(react_chart_editor_1.default, { ref: function (ref) {
                    _this.ref = ref;
                }, className: "plotly-editor", data: data, layout: layout, config: config, frames: frames, plotly: plotly, onUpdate: this.handleUpdate, onRender: this.handleRender, useResizeHandler: true, debug: true, advancedTraceTypeSelector: true })));
    };
    return ChartEditor;
}(React.Component));
exports.default = ChartEditor;


/***/ }),

/***/ "QTa/":
/*!***********************************************************!*\
  !*** ./node_modules/elliptic/lib/elliptic/curve/index.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var curve = exports;

curve.base = __webpack_require__(/*! ./base */ "6lN/");
curve.short = __webpack_require__(/*! ./short */ "MwBp");
curve.mont = __webpack_require__(/*! ./mont */ "Z2+3");
curve.edwards = __webpack_require__(/*! ./edwards */ "Pa+m");


/***/ }),

/***/ "QXkm":
/*!********************************************!*\
  !*** ./node_modules/mdi-react/PlusIcon.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var PlusIcon = function PlusIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M19,13H13V19H11V13H5V11H11V5H13V11H19V13Z' })
  );
};

module.exports = PlusIcon;


/***/ }),

/***/ "QbIU":
/*!*****************************************************************!*\
  !*** ./node_modules/@jupyterlab/running-extension/lib/index.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const application_1 = __webpack_require__(/*! @jupyterlab/application */ "FkFl");
const running_1 = __webpack_require__(/*! @jupyterlab/running */ "qSDV");
/**
 * The default running sessions extension.
 */
const plugin = {
    activate,
    id: '@jupyterlab/running-extension:plugin',
    requires: [application_1.ILayoutRestorer],
    autoStart: true
};
/**
 * Export the plugin as default.
 */
exports.default = plugin;
/**
 * Activate the running plugin.
 */
function activate(app, restorer) {
    let running = new running_1.RunningSessions({ manager: app.serviceManager });
    running.id = 'jp-running-sessions';
    running.title.iconClass = 'jp-DirectionsRunIcon jp-SideBar-tabIcon';
    running.title.caption = 'Running Terminals and Kernels';
    // Let the application restorer track the running panel for restoration of
    // application state (e.g. setting the running panel as the current side bar
    // widget).
    restorer.add(running, 'running-sessions');
    running.sessionOpenRequested.connect((sender, model) => {
        let path = model.path;
        if (model.type.toLowerCase() === 'console') {
            app.commands.execute('console:open', { path });
        }
        else {
            app.commands.execute('docmanager:open', { path });
        }
    });
    running.terminalOpenRequested.connect((sender, model) => {
        app.commands.execute('terminal:open', { name: model.name });
    });
    // Rank has been chosen somewhat arbitrarily to give priority to the running
    // sessions widget in the sidebar.
    app.shell.addToLeftArea(running, { rank: 200 });
}


/***/ }),

/***/ "QbLZ":
/*!*******************************************************!*\
  !*** ./node_modules/babel-runtime/helpers/extends.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _assign = __webpack_require__(/*! ../core-js/object/assign */ "P2sY");

var _assign2 = _interopRequireDefault(_assign);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = _assign2.default || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

/***/ }),

/***/ "QcOe":
/*!********************************************!*\
  !*** ./node_modules/lodash/_baseKeysIn.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isObject = __webpack_require__(/*! ./isObject */ "GoyQ"),
    isPrototype = __webpack_require__(/*! ./_isPrototype */ "6sVZ"),
    nativeKeysIn = __webpack_require__(/*! ./_nativeKeysIn */ "7Ix3");

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * 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;
}

module.exports = baseKeysIn;


/***/ }),

/***/ "Qd/k":
/*!*****************************************************!*\
  !*** ./node_modules/asn1.js/lib/asn1/base/index.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var base = exports;

base.Reporter = __webpack_require__(/*! ./reporter */ "0cit").Reporter;
base.DecoderBuffer = __webpack_require__(/*! ./buffer */ "YoN+").DecoderBuffer;
base.EncoderBuffer = __webpack_require__(/*! ./buffer */ "YoN+").EncoderBuffer;
base.Node = __webpack_require__(/*! ./node */ "g2Dh");


/***/ }),

/***/ "QfTi":
/*!***********************************************!*\
  !*** ./node_modules/fbjs/lib/VersionRange.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */



var invariant = __webpack_require__(/*! ./invariant */ "2NuI");

var componentRegex = /\./;
var orRegex = /\|\|/;
var rangeRegex = /\s+\-\s+/;
var modifierRegex = /^(<=|<|=|>=|~>|~|>|)?\s*(.+)/;
var numericRegex = /^(\d*)(.*)/;

/**
 * Splits input `range` on "||" and returns true if any subrange matches
 * `version`.
 *
 * @param {string} range
 * @param {string} version
 * @returns {boolean}
 */
function checkOrExpression(range, version) {
  var expressions = range.split(orRegex);

  if (expressions.length > 1) {
    return expressions.some(function (range) {
      return VersionRange.contains(range, version);
    });
  } else {
    range = expressions[0].trim();
    return checkRangeExpression(range, version);
  }
}

/**
 * Splits input `range` on " - " (the surrounding whitespace is required) and
 * returns true if version falls between the two operands.
 *
 * @param {string} range
 * @param {string} version
 * @returns {boolean}
 */
function checkRangeExpression(range, version) {
  var expressions = range.split(rangeRegex);

  !(expressions.length > 0 && expressions.length <= 2) ?  true ? invariant(false, 'the "-" operator expects exactly 2 operands') : undefined : void 0;

  if (expressions.length === 1) {
    return checkSimpleExpression(expressions[0], version);
  } else {
    var startVersion = expressions[0],
        endVersion = expressions[1];

    !(isSimpleVersion(startVersion) && isSimpleVersion(endVersion)) ?  true ? invariant(false, 'operands to the "-" operator must be simple (no modifiers)') : undefined : void 0;

    return checkSimpleExpression('>=' + startVersion, version) && checkSimpleExpression('<=' + endVersion, version);
  }
}

/**
 * Checks if `range` matches `version`. `range` should be a "simple" range (ie.
 * not a compound range using the " - " or "||" operators).
 *
 * @param {string} range
 * @param {string} version
 * @returns {boolean}
 */
function checkSimpleExpression(range, version) {
  range = range.trim();
  if (range === '') {
    return true;
  }

  var versionComponents = version.split(componentRegex);

  var _getModifierAndCompon = getModifierAndComponents(range),
      modifier = _getModifierAndCompon.modifier,
      rangeComponents = _getModifierAndCompon.rangeComponents;

  switch (modifier) {
    case '<':
      return checkLessThan(versionComponents, rangeComponents);
    case '<=':
      return checkLessThanOrEqual(versionComponents, rangeComponents);
    case '>=':
      return checkGreaterThanOrEqual(versionComponents, rangeComponents);
    case '>':
      return checkGreaterThan(versionComponents, rangeComponents);
    case '~':
    case '~>':
      return checkApproximateVersion(versionComponents, rangeComponents);
    default:
      return checkEqual(versionComponents, rangeComponents);
  }
}

/**
 * Checks whether `a` is less than `b`.
 *
 * @param {array<string>} a
 * @param {array<string>} b
 * @returns {boolean}
 */
function checkLessThan(a, b) {
  return compareComponents(a, b) === -1;
}

/**
 * Checks whether `a` is less than or equal to `b`.
 *
 * @param {array<string>} a
 * @param {array<string>} b
 * @returns {boolean}
 */
function checkLessThanOrEqual(a, b) {
  var result = compareComponents(a, b);
  return result === -1 || result === 0;
}

/**
 * Checks whether `a` is equal to `b`.
 *
 * @param {array<string>} a
 * @param {array<string>} b
 * @returns {boolean}
 */
function checkEqual(a, b) {
  return compareComponents(a, b) === 0;
}

/**
 * Checks whether `a` is greater than or equal to `b`.
 *
 * @param {array<string>} a
 * @param {array<string>} b
 * @returns {boolean}
 */
function checkGreaterThanOrEqual(a, b) {
  var result = compareComponents(a, b);
  return result === 1 || result === 0;
}

/**
 * Checks whether `a` is greater than `b`.
 *
 * @param {array<string>} a
 * @param {array<string>} b
 * @returns {boolean}
 */
function checkGreaterThan(a, b) {
  return compareComponents(a, b) === 1;
}

/**
 * Checks whether `a` is "reasonably close" to `b` (as described in
 * https://www.npmjs.org/doc/misc/semver.html). For example, if `b` is "1.3.1"
 * then "reasonably close" is defined as ">= 1.3.1 and < 1.4".
 *
 * @param {array<string>} a
 * @param {array<string>} b
 * @returns {boolean}
 */
function checkApproximateVersion(a, b) {
  var lowerBound = b.slice();
  var upperBound = b.slice();

  if (upperBound.length > 1) {
    upperBound.pop();
  }
  var lastIndex = upperBound.length - 1;
  var numeric = parseInt(upperBound[lastIndex], 10);
  if (isNumber(numeric)) {
    upperBound[lastIndex] = numeric + 1 + '';
  }

  return checkGreaterThanOrEqual(a, lowerBound) && checkLessThan(a, upperBound);
}

/**
 * Extracts the optional modifier (<, <=, =, >=, >, ~, ~>) and version
 * components from `range`.
 *
 * For example, given `range` ">= 1.2.3" returns an object with a `modifier` of
 * `">="` and `components` of `[1, 2, 3]`.
 *
 * @param {string} range
 * @returns {object}
 */
function getModifierAndComponents(range) {
  var rangeComponents = range.split(componentRegex);
  var matches = rangeComponents[0].match(modifierRegex);
  !matches ?  true ? invariant(false, 'expected regex to match but it did not') : undefined : void 0;

  return {
    modifier: matches[1],
    rangeComponents: [matches[2]].concat(rangeComponents.slice(1))
  };
}

/**
 * Determines if `number` is a number.
 *
 * @param {mixed} number
 * @returns {boolean}
 */
function isNumber(number) {
  return !isNaN(number) && isFinite(number);
}

/**
 * Tests whether `range` is a "simple" version number without any modifiers
 * (">", "~" etc).
 *
 * @param {string} range
 * @returns {boolean}
 */
function isSimpleVersion(range) {
  return !getModifierAndComponents(range).modifier;
}

/**
 * Zero-pads array `array` until it is at least `length` long.
 *
 * @param {array} array
 * @param {number} length
 */
function zeroPad(array, length) {
  for (var i = array.length; i < length; i++) {
    array[i] = '0';
  }
}

/**
 * Normalizes `a` and `b` in preparation for comparison by doing the following:
 *
 * - zero-pads `a` and `b`
 * - marks any "x", "X" or "*" component in `b` as equivalent by zero-ing it out
 *   in both `a` and `b`
 * - marks any final "*" component in `b` as a greedy wildcard by zero-ing it
 *   and all of its successors in `a`
 *
 * @param {array<string>} a
 * @param {array<string>} b
 * @returns {array<array<string>>}
 */
function normalizeVersions(a, b) {
  a = a.slice();
  b = b.slice();

  zeroPad(a, b.length);

  // mark "x" and "*" components as equal
  for (var i = 0; i < b.length; i++) {
    var matches = b[i].match(/^[x*]$/i);
    if (matches) {
      b[i] = a[i] = '0';

      // final "*" greedily zeros all remaining components
      if (matches[0] === '*' && i === b.length - 1) {
        for (var j = i; j < a.length; j++) {
          a[j] = '0';
        }
      }
    }
  }

  zeroPad(b, a.length);

  return [a, b];
}

/**
 * Returns the numerical -- not the lexicographical -- ordering of `a` and `b`.
 *
 * For example, `10-alpha` is greater than `2-beta`.
 *
 * @param {string} a
 * @param {string} b
 * @returns {number} -1, 0 or 1 to indicate whether `a` is less than, equal to,
 * or greater than `b`, respectively
 */
function compareNumeric(a, b) {
  var aPrefix = a.match(numericRegex)[1];
  var bPrefix = b.match(numericRegex)[1];
  var aNumeric = parseInt(aPrefix, 10);
  var bNumeric = parseInt(bPrefix, 10);

  if (isNumber(aNumeric) && isNumber(bNumeric) && aNumeric !== bNumeric) {
    return compare(aNumeric, bNumeric);
  } else {
    return compare(a, b);
  }
}

/**
 * Returns the ordering of `a` and `b`.
 *
 * @param {string|number} a
 * @param {string|number} b
 * @returns {number} -1, 0 or 1 to indicate whether `a` is less than, equal to,
 * or greater than `b`, respectively
 */
function compare(a, b) {
  !(typeof a === typeof b) ?  true ? invariant(false, '"a" and "b" must be of the same type') : undefined : void 0;

  if (a > b) {
    return 1;
  } else if (a < b) {
    return -1;
  } else {
    return 0;
  }
}

/**
 * Compares arrays of version components.
 *
 * @param {array<string>} a
 * @param {array<string>} b
 * @returns {number} -1, 0 or 1 to indicate whether `a` is less than, equal to,
 * or greater than `b`, respectively
 */
function compareComponents(a, b) {
  var _normalizeVersions = normalizeVersions(a, b),
      aNormalized = _normalizeVersions[0],
      bNormalized = _normalizeVersions[1];

  for (var i = 0; i < bNormalized.length; i++) {
    var result = compareNumeric(aNormalized[i], bNormalized[i]);
    if (result) {
      return result;
    }
  }

  return 0;
}

var VersionRange = {
  /**
   * Checks whether `version` satisfies the `range` specification.
   *
   * We support a subset of the expressions defined in
   * https://www.npmjs.org/doc/misc/semver.html:
   *
   *    version   Must match version exactly
   *    =version  Same as just version
   *    >version  Must be greater than version
   *    >=version Must be greater than or equal to version
   *    <version  Must be less than version
   *    <=version Must be less than or equal to version
   *    ~version  Must be at least version, but less than the next significant
   *              revision above version:
   *              "~1.2.3" is equivalent to ">= 1.2.3 and < 1.3"
   *    ~>version Equivalent to ~version
   *    1.2.x     Must match "1.2.x", where "x" is a wildcard that matches
   *              anything
   *    1.2.*     Similar to "1.2.x", but "*" in the trailing position is a
   *              "greedy" wildcard, so will match any number of additional
   *              components:
   *              "1.2.*" will match "1.2.1", "1.2.1.1", "1.2.1.1.1" etc
   *    *         Any version
   *    ""        (Empty string) Same as *
   *    v1 - v2   Equivalent to ">= v1 and <= v2"
   *    r1 || r2  Passes if either r1 or r2 are satisfied
   *
   * @param {string} range
   * @param {string} version
   * @returns {boolean}
   */
  contains: function contains(range, version) {
    return checkOrExpression(range.trim(), version.trim());
  }
};

module.exports = VersionRange;

/***/ }),

/***/ "Qhhf":
/*!******************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/identity.js ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



// Simple helper functions
// none of these need any external deps

module.exports = function identity(d) { return d; };


/***/ }),

/***/ "QihY":
/*!**************************************************!*\
  !*** ./node_modules/browserify-aes/decrypter.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var AuthCipher = __webpack_require__(/*! ./authCipher */ "gvAe")
var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer
var MODES = __webpack_require__(/*! ./modes */ "usKN")
var StreamCipher = __webpack_require__(/*! ./streamCipher */ "CfXC")
var Transform = __webpack_require__(/*! cipher-base */ "ZDAU")
var aes = __webpack_require__(/*! ./aes */ "OfWw")
var ebtk = __webpack_require__(/*! evp_bytestokey */ "roQf")
var inherits = __webpack_require__(/*! inherits */ "P7XM")

function Decipher (mode, key, iv) {
  Transform.call(this)

  this._cache = new Splitter()
  this._last = void 0
  this._cipher = new aes.AES(key)
  this._prev = Buffer.from(iv)
  this._mode = mode
  this._autopadding = true
}

inherits(Decipher, Transform)

Decipher.prototype._update = function (data) {
  this._cache.add(data)
  var chunk
  var thing
  var out = []
  while ((chunk = this._cache.get(this._autopadding))) {
    thing = this._mode.decrypt(this, chunk)
    out.push(thing)
  }
  return Buffer.concat(out)
}

Decipher.prototype._final = function () {
  var chunk = this._cache.flush()
  if (this._autopadding) {
    return unpad(this._mode.decrypt(this, chunk))
  } else if (chunk) {
    throw new Error('data not multiple of block length')
  }
}

Decipher.prototype.setAutoPadding = function (setTo) {
  this._autopadding = !!setTo
  return this
}

function Splitter () {
  this.cache = Buffer.allocUnsafe(0)
}

Splitter.prototype.add = function (data) {
  this.cache = Buffer.concat([this.cache, data])
}

Splitter.prototype.get = function (autoPadding) {
  var out
  if (autoPadding) {
    if (this.cache.length > 16) {
      out = this.cache.slice(0, 16)
      this.cache = this.cache.slice(16)
      return out
    }
  } else {
    if (this.cache.length >= 16) {
      out = this.cache.slice(0, 16)
      this.cache = this.cache.slice(16)
      return out
    }
  }

  return null
}

Splitter.prototype.flush = function () {
  if (this.cache.length) return this.cache
}

function unpad (last) {
  var padded = last[15]
  if (padded < 1 || padded > 16) {
    throw new Error('unable to decrypt data')
  }
  var i = -1
  while (++i < padded) {
    if (last[(i + (16 - padded))] !== padded) {
      throw new Error('unable to decrypt data')
    }
  }
  if (padded === 16) return

  return last.slice(0, 16 - padded)
}

function createDecipheriv (suite, password, iv) {
  var config = MODES[suite.toLowerCase()]
  if (!config) throw new TypeError('invalid suite type')

  if (typeof iv === 'string') iv = Buffer.from(iv)
  if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)

  if (typeof password === 'string') password = Buffer.from(password)
  if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)

  if (config.type === 'stream') {
    return new StreamCipher(config.module, password, iv, true)
  } else if (config.type === 'auth') {
    return new AuthCipher(config.module, password, iv, true)
  }

  return new Decipher(config.module, password, iv)
}

function createDecipher (suite, password) {
  var config = MODES[suite.toLowerCase()]
  if (!config) throw new TypeError('invalid suite type')

  var keys = ebtk(password, false, config.key, config.iv)
  return createDecipheriv(suite, keys.key, keys.iv)
}

exports.createDecipher = createDecipher
exports.createDecipheriv = createDecipheriv


/***/ }),

/***/ "Qj4J":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/ar-kw.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var arKw = moment.defineLocale('ar-kw', {
    months : 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'),
    monthsShort : 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'),
    weekdays : 'الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
    weekdaysShort : 'احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'),
    weekdaysMin : 'ح_ن_ث_ر_خ_ج_س'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay: '[اليوم على الساعة] LT',
        nextDay: '[غدا على الساعة] LT',
        nextWeek: 'dddd [على الساعة] LT',
        lastDay: '[أمس على الساعة] LT',
        lastWeek: 'dddd [على الساعة] LT',
        sameElse: 'L'
    },
    relativeTime : {
        future : 'في %s',
        past : 'منذ %s',
        s : 'ثوان',
        ss : '%d ثانية',
        m : 'دقيقة',
        mm : '%d دقائق',
        h : 'ساعة',
        hh : '%d ساعات',
        d : 'يوم',
        dd : '%d أيام',
        M : 'شهر',
        MM : '%d أشهر',
        y : 'سنة',
        yy : '%d سنوات'
    },
    week : {
        dow : 0, // Sunday is the first day of the week.
        doy : 12  // The week that contains Jan 1st is the first week of the year.
    }
});

return arKw;

})));


/***/ }),

/***/ "QkKW":
/*!**************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/connectSliderToLayout.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

exports.default = connectSliderToLayout;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _lib = __webpack_require__(/*! ../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function connectSliderToLayout(WrappedComponent) {
  var SliderConnectedComponent = function (_Component) {
    _inherits(SliderConnectedComponent, _Component);

    function SliderConnectedComponent(props, context) {
      _classCallCheck(this, SliderConnectedComponent);

      var _this = _possibleConstructorReturn(this, (SliderConnectedComponent.__proto__ || Object.getPrototypeOf(SliderConnectedComponent)).call(this, props, context));

      _this.updateSlider = _this.updateSlider.bind(_this);
      _this.setLocals(props, context);
      return _this;
    }

    _createClass(SliderConnectedComponent, [{
      key: 'componentWillReceiveProps',
      value: function componentWillReceiveProps(nextProps, nextContext) {
        this.setLocals(nextProps, nextContext);
      }
    }, {
      key: 'setLocals',
      value: function setLocals(props, context) {
        var sliderIndex = props.sliderIndex;
        var container = context.container,
            fullContainer = context.fullContainer;


        var sliders = container.sliders || [];
        var fullSliders = fullContainer.sliders || [];
        this.container = sliders[sliderIndex];
        this.fullContainer = fullSliders[sliderIndex];
      }
    }, {
      key: 'getChildContext',
      value: function getChildContext() {
        var _this2 = this;

        return {
          getValObject: function getValObject(attr) {
            return !_this2.context.getValObject ? null : _this2.context.getValObject('sliders[].' + attr);
          },
          updateContainer: this.updateSlider,
          container: this.container,
          fullContainer: this.fullContainer
        };
      }
    }, {
      key: 'updateSlider',
      value: function updateSlider(update) {
        var newUpdate = {};
        var sliderIndex = this.props.sliderIndex;

        for (var key in update) {
          var newkey = 'sliders[' + sliderIndex + '].' + key;
          newUpdate[newkey] = update[key];
        }
        this.context.updateContainer(newUpdate);
      }
    }, {
      key: 'render',
      value: function render() {
        return _react2.default.createElement(WrappedComponent, this.props);
      }
    }]);

    return SliderConnectedComponent;
  }(_react.Component);

  SliderConnectedComponent.displayName = 'SliderConnected' + (0, _lib.getDisplayName)(WrappedComponent);

  SliderConnectedComponent.propTypes = {
    sliderIndex: _propTypes2.default.number.isRequired
  };

  SliderConnectedComponent.contextTypes = {
    container: _propTypes2.default.object,
    fullContainer: _propTypes2.default.object,
    onUpdate: _propTypes2.default.func,
    updateContainer: _propTypes2.default.func,
    getValObject: _propTypes2.default.func
  };

  SliderConnectedComponent.childContextTypes = {
    updateContainer: _propTypes2.default.func,
    container: _propTypes2.default.object,
    fullContainer: _propTypes2.default.object,
    getValObject: _propTypes2.default.func
  };

  var plotly_editor_traits = WrappedComponent.plotly_editor_traits;

  SliderConnectedComponent.plotly_editor_traits = plotly_editor_traits;

  return SliderConnectedComponent;
}
//# sourceMappingURL=connectSliderToLayout.js.map

/***/ }),

/***/ "QkVE":
/*!********************************************!*\
  !*** ./node_modules/lodash/_getMapData.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isKeyable = __webpack_require__(/*! ./_isKeyable */ "EpBk");

/**
 * 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;
}

module.exports = getMapData;


/***/ }),

/***/ "QkVN":
/*!**************************************!*\
  !*** ./node_modules/lodash/merge.js ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseMerge = __webpack_require__(/*! ./_baseMerge */ "+Qka"),
    createAssigner = __webpack_require__(/*! ./_createAssigner */ "LsHQ");

/**
 * 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;


/***/ }),

/***/ "Qna6":
/*!*************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeViolinIcon.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeViolinIcon = function TraceTypeViolinIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement('path', { fill: 'none', d: 'M0 0h46v46H0z' }),
        _react2.default.createElement('path', { d: 'M7 21.733c0-6.22 4.412-8.674 4.412-13.968 0 5.294 4.411 7.749 4.411 13.968 0 4.756-4.411 7.267-4.411 17.561C11.412 29 7 26.49 7 21.734zm17.039 14.679s.434-5.754 1.856-8.467-.924-6.533.427-9.879a11.606 11.606 0 0 0 0-7.816C25.468 7.862 24.039 3 24.039 3s-1.43 4.862-2.283 7.25a11.606 11.606 0 0 0 0 7.816c1.351 3.346-.995 7.165.427 9.878s1.856 8.468 1.856 8.468zm12.991 3.882a11.821 11.821 0 0 0-2.344-6.03c-1.065-1.507-1.704-6.346-.639-8.549S37.03 12 37.03 12h-.058s1.917 11.512 2.982 13.715.426 7.042-.64 8.55a11.821 11.821 0 0 0-2.342 6.03zM24 36v6M37 3v9', fill: '#25fdfc', stroke: '#1d9bfb', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2' })
    );
};

exports.default = TraceTypeViolinIcon;

/***/ }),

/***/ "QoRX":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_arraySome.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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;
}

module.exports = arraySome;


/***/ }),

/***/ "QpuX":
/*!*****************************************************************************!*\
  !*** ./node_modules/readable-stream/lib/internal/streams/stream-browser.js ***!
  \*****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(/*! events */ "+qE3").EventEmitter;


/***/ }),

/***/ "QqEw":
/*!*********************************************!*\
  !*** ./node_modules/mdi-react/VideoIcon.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var VideoIcon = function VideoIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M17,10.5V7C17,6.45 16.55,6 16,6H4C3.45,6 3,6.45 3,7V17C3,17.55 3.45,18 4,18H16C16.55,18 17,17.55 17,17V13.5L21,17.5V6.5L17,10.5Z' })
  );
};

module.exports = VideoIcon;


/***/ }),

/***/ "QqLw":
/*!****************************************!*\
  !*** ./node_modules/lodash/_getTag.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var DataView = __webpack_require__(/*! ./_DataView */ "tadb"),
    Map = __webpack_require__(/*! ./_Map */ "ebwN"),
    Promise = __webpack_require__(/*! ./_Promise */ "HOxn"),
    Set = __webpack_require__(/*! ./_Set */ "yGk4"),
    WeakMap = __webpack_require__(/*! ./_WeakMap */ "Of+w"),
    baseGetTag = __webpack_require__(/*! ./_baseGetTag */ "NykK"),
    toSource = __webpack_require__(/*! ./_toSource */ "3Fdi");

/** `Object#toString` result references. */
var mapTag = '[object Map]',
    objectTag = '[object Object]',
    promiseTag = '[object Promise]',
    setTag = '[object Set]',
    weakMapTag = '[object WeakMap]';

var dataViewTag = '[object DataView]';

/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
    mapCtorString = toSource(Map),
    promiseCtorString = toSource(Promise),
    setCtorString = toSource(Set),
    weakMapCtorString = toSource(WeakMap);

/**
 * 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;
  };
}

module.exports = getTag;


/***/ }),

/***/ "QtI6":
/*!***********************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@phosphor/widgets/style/widget.css ***!
  \***********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\r\n| Copyright (c) 2014-2017, PhosphorJS Contributors\r\n|\r\n| Distributed under the terms of the BSD 3-Clause License.\r\n|\r\n| The full license is in the file LICENSE, distributed with this software.\r\n|----------------------------------------------------------------------------*/\r\n\r\n\r\n.p-Widget {\r\n  box-sizing: border-box;\r\n  position: relative;\r\n  overflow: hidden;\r\n  cursor: default;\r\n}\r\n\r\n\r\n.p-Widget.p-mod-hidden {\r\n  display: none !important;\r\n}\r\n", ""]);

// exports


/***/ }),

/***/ "Qv8M":
/*!*********************************************************************!*\
  !*** ./node_modules/@jupyterlab/inspector-extension/lib/manager.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * A class that manages inspector widget instances and offers persistent
 * `IInspector` instance that other plugins can communicate with.
 */
class InspectorManager {
    constructor() {
        this._inspector = null;
        this._source = null;
    }
    /**
     * The current inspector widget.
     */
    get inspector() {
        return this._inspector;
    }
    set inspector(inspector) {
        if (this._inspector === inspector) {
            return;
        }
        this._inspector = inspector;
        // If an inspector was added and it has no source
        if (inspector && !inspector.source) {
            inspector.source = this._source;
        }
    }
    /**
     * The source of events the inspector panel listens for.
     */
    get source() {
        return this._source;
    }
    set source(source) {
        if (this._source === source) {
            return;
        }
        if (this._source) {
            this._source.disposed.disconnect(this._onSourceDisposed, this);
        }
        this._source = source;
        if (this._inspector && !this._inspector.isDisposed) {
            this._inspector.source = this._source;
        }
        if (this._source) {
            this._source.disposed.connect(this._onSourceDisposed, this);
        }
    }
    /**
     * Create an inspector child item and return a disposable to remove it.
     *
     * @param item - The inspector child item being added to the inspector.
     *
     * @returns A disposable that removes the child item from the inspector.
     */
    add(item) {
        if (!this._inspector) {
            throw new Error('Cannot add child item before creating an inspector.');
        }
        return this._inspector.add(item);
    }
    /**
     * Handle the source disposed signal.
     */
    _onSourceDisposed() {
        this._source = null;
    }
}
exports.InspectorManager = InspectorManager;


/***/ }),

/***/ "QvxS":
/*!***********************************************!*\
  !*** ./node_modules/fbjs/lib/DataTransfer.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks
 */

var PhotosMimeType = __webpack_require__(/*! ./PhotosMimeType */ "NQV1");

var createArrayFromMixed = __webpack_require__(/*! ./createArrayFromMixed */ "qy1W");
var emptyFunction = __webpack_require__(/*! ./emptyFunction */ "ohE5");

var CR_LF_REGEX = new RegExp('\r\n', 'g');
var LF_ONLY = '\n';

var RICH_TEXT_TYPES = {
  'text/rtf': 1,
  'text/html': 1
};

/**
 * If DataTransferItem is a file then return the Blob of data.
 *
 * @param {object} item
 * @return {?blob}
 */
function getFileFromDataTransfer(item) {
  if (item.kind == 'file') {
    return item.getAsFile();
  }
}

var DataTransfer = function () {
  /**
   * @param {object} data
   */
  function DataTransfer(data) {
    _classCallCheck(this, DataTransfer);

    this.data = data;

    // Types could be DOMStringList or array
    this.types = data.types ? createArrayFromMixed(data.types) : [];
  }

  /**
   * Is this likely to be a rich text data transfer?
   *
   * @return {boolean}
   */


  DataTransfer.prototype.isRichText = function isRichText() {
    // If HTML is available, treat this data as rich text. This way, we avoid
    // using a pasted image if it is packaged with HTML -- this may occur with
    // pastes from MS Word, for example.  However this is only rich text if
    // there's accompanying text.
    if (this.getHTML() && this.getText()) {
      return true;
    }

    // When an image is copied from a preview window, you end up with two
    // DataTransferItems one of which is a file's metadata as text.  Skip those.
    if (this.isImage()) {
      return false;
    }

    return this.types.some(function (type) {
      return RICH_TEXT_TYPES[type];
    });
  };

  /**
   * Get raw text.
   *
   * @return {?string}
   */


  DataTransfer.prototype.getText = function getText() {
    var text;
    if (this.data.getData) {
      if (!this.types.length) {
        text = this.data.getData('Text');
      } else if (this.types.indexOf('text/plain') != -1) {
        text = this.data.getData('text/plain');
      }
    }
    return text ? text.replace(CR_LF_REGEX, LF_ONLY) : null;
  };

  /**
   * Get HTML paste data
   *
   * @return {?string}
   */


  DataTransfer.prototype.getHTML = function getHTML() {
    if (this.data.getData) {
      if (!this.types.length) {
        return this.data.getData('Text');
      } else if (this.types.indexOf('text/html') != -1) {
        return this.data.getData('text/html');
      }
    }
  };

  /**
   * Is this a link data transfer?
   *
   * @return {boolean}
   */


  DataTransfer.prototype.isLink = function isLink() {
    return this.types.some(function (type) {
      return type.indexOf('Url') != -1 || type.indexOf('text/uri-list') != -1 || type.indexOf('text/x-moz-url');
    });
  };

  /**
   * Get a link url.
   *
   * @return {?string}
   */


  DataTransfer.prototype.getLink = function getLink() {
    if (this.data.getData) {
      if (this.types.indexOf('text/x-moz-url') != -1) {
        var url = this.data.getData('text/x-moz-url').split('\n');
        return url[0];
      }
      return this.types.indexOf('text/uri-list') != -1 ? this.data.getData('text/uri-list') : this.data.getData('url');
    }

    return null;
  };

  /**
   * Is this an image data transfer?
   *
   * @return {boolean}
   */


  DataTransfer.prototype.isImage = function isImage() {
    var isImage = this.types.some(function (type) {
      // Firefox will have a type of application/x-moz-file for images during
      // dragging
      return type.indexOf('application/x-moz-file') != -1;
    });

    if (isImage) {
      return true;
    }

    var items = this.getFiles();
    for (var i = 0; i < items.length; i++) {
      var type = items[i].type;
      if (!PhotosMimeType.isImage(type)) {
        return false;
      }
    }

    return true;
  };

  DataTransfer.prototype.getCount = function getCount() {
    if (this.data.hasOwnProperty('items')) {
      return this.data.items.length;
    } else if (this.data.hasOwnProperty('mozItemCount')) {
      return this.data.mozItemCount;
    } else if (this.data.files) {
      return this.data.files.length;
    }
    return null;
  };

  /**
   * Get files.
   *
   * @return {array}
   */


  DataTransfer.prototype.getFiles = function getFiles() {
    if (this.data.items) {
      // createArrayFromMixed doesn't properly handle DataTransferItemLists.
      return Array.prototype.slice.call(this.data.items).map(getFileFromDataTransfer).filter(emptyFunction.thatReturnsArgument);
    } else if (this.data.files) {
      return Array.prototype.slice.call(this.data.files);
    } else {
      return [];
    }
  };

  /**
   * Are there any files to fetch?
   *
   * @return {boolean}
   */


  DataTransfer.prototype.hasFiles = function hasFiles() {
    return this.getFiles().length > 0;
  };

  return DataTransfer;
}();

module.exports = DataTransfer;

/***/ }),

/***/ "Qx43":
/*!************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/UpdateMenuButtons.js ***!
  \************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _index = __webpack_require__(/*! ../index */ "yF51");

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UpdateMenuButtons = function (_Component) {
  _inherits(UpdateMenuButtons, _Component);

  function UpdateMenuButtons(props, context) {
    _classCallCheck(this, UpdateMenuButtons);

    var _this = _possibleConstructorReturn(this, (UpdateMenuButtons.__proto__ || Object.getPrototypeOf(UpdateMenuButtons)).call(this, props, context));

    _this.state = {
      currentButtonIndex: 0
    };
    return _this;
  }

  _createClass(UpdateMenuButtons, [{
    key: 'renderDropdown',
    value: function renderDropdown() {
      var _this2 = this;

      var _ = this.context.localize;
      var options = this.props.fullValue.map(function (button, index) {
        return { label: _('Button') + (' ' + (index + 1)), value: index };
      });
      return _react2.default.createElement(_index.Dropdown, {
        attr: 'buttons',
        label: _('Button'),
        options: options,
        updatePlot: function updatePlot(index) {
          return _this2.setState({ currentButtonIndex: index });
        },
        clearable: false,
        fullValue: this.state.currentButtonIndex
      });
    }
  }, {
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        _Field2.default,
        null,
        this.renderDropdown(),
        _react2.default.createElement(_index.TextEditor, { attr: 'buttons[' + this.state.currentButtonIndex + '].label', richTextOnly: true })
      );
    }
  }]);

  return UpdateMenuButtons;
}(_react.Component);

UpdateMenuButtons.propTypes = {
  attr: _propTypes2.default.string,
  fullValue: _propTypes2.default.array,
  updatePlot: _propTypes2.default.func
};

UpdateMenuButtons.contextTypes = {
  localize: _propTypes2.default.func
};

exports.default = (0, _lib.connectToContainer)(UpdateMenuButtons);
//# sourceMappingURL=UpdateMenuButtons.js.map

/***/ }),

/***/ "R+7+":
/*!************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_enum-keys.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// all enumerable object keys, includes symbols
var getKeys = __webpack_require__(/*! ./_object-keys */ "w6GO");
var gOPS = __webpack_require__(/*! ./_object-gops */ "mqlF");
var pIE = __webpack_require__(/*! ./_object-pie */ "NV0k");
module.exports = function (it) {
  var result = getKeys(it);
  var getSymbols = gOPS.f;
  if (getSymbols) {
    var symbols = getSymbols(it);
    var isEnum = pIE.f;
    var i = 0;
    var key;
    while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key);
  } return result;
};


/***/ }),

/***/ "R/zK":
/*!************************************************!*\
  !*** ./node_modules/base16/lib/summerfruit.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'summerfruit',
  author: 'christopher corley (http://cscorley.github.io/)',
  base00: '#151515',
  base01: '#202020',
  base02: '#303030',
  base03: '#505050',
  base04: '#B0B0B0',
  base05: '#D0D0D0',
  base06: '#E0E0E0',
  base07: '#FFFFFF',
  base08: '#FF0086',
  base09: '#FD8900',
  base0A: '#ABA800',
  base0B: '#00C918',
  base0C: '#1faaaa',
  base0D: '#3777E6',
  base0E: '#AD00A1',
  base0F: '#cc6633'
};
module.exports = exports['default'];

/***/ }),

/***/ "R1z+":
/*!*******************************************!*\
  !*** ./node_modules/lodash.flow/index.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global) {/**
 * lodash (Custom Build) <https://lodash.com/>
 * Build: `lodash modularize exports="npm" -o ./`
 * Copyright jQuery Foundation and other contributors <https://jquery.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
 */

/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';

/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;

/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
    funcTag = '[object Function]',
    genTag = '[object GeneratorFunction]';

/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;

/** 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')();

/**
 * 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);
}

/**
 * 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;
}

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var objectToString = objectProto.toString;

/** Built-in value references. */
var Symbol = root.Symbol,
    propertyIsEnumerable = objectProto.propertyIsEnumerable,
    spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;

/**
 * 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 `_.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) {
  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] = array;
    return apply(func, this, otherArgs);
  };
}

/**
 * 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 baseRest(function(funcs) {
    funcs = baseFlatten(funcs, 1);

    var length = funcs.length,
        index = length;

    if (fromRight) {
      funcs.reverse();
    }
    while (index--) {
      if (typeof funcs[index] != 'function') {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
    }
    return function() {
      var index = 0,
          result = length ? funcs[index].apply(this, arguments) : arguments[0];

      while (++index < length) {
        result = funcs[index].call(this, result);
      }
      return result;
    };
  });
}

/**
 * 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 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
 */
function isArguments(value) {
  // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
  return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
    (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
}

/**
 * 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 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 `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) {
  // The use of `Object#toString` avoids issues with the `typeof` operator
  // in Safari 8-9 which returns 'object' for typed array and other constructors.
  var tag = isObject(value) ? objectToString.call(value) : '';
  return tag == funcTag || tag == genTag;
}

/**
 * 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 && (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 && typeof value == 'object';
}

/**
 * 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();

module.exports = flow;

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "R4GQ":
/*!************************************************************!*\
  !*** ./node_modules/@jupyterlab/filebrowser/lib/crumbs.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const domutils_1 = __webpack_require__(/*! @phosphor/domutils */ "XWTc");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const docmanager_1 = __webpack_require__(/*! @jupyterlab/docmanager */ "kL29");
/**
 * The class name added to material icons
 */
const MATERIAL_CLASS = 'jp-MaterialIcon';
/**
 * The class name added to the breadcrumb node.
 */
const BREADCRUMB_CLASS = 'jp-BreadCrumbs';
/**
 * The class name added to add the home icon for the breadcrumbs
 */
const BREADCRUMB_HOME = 'jp-HomeIcon';
/**
 * The class named associated to the ellipses icon
 */
const BREADCRUMB_ELLIPSES = 'jp-EllipsesIcon';
/**
 * The class name added to the breadcrumb node.
 */
const BREADCRUMB_ITEM_CLASS = 'jp-BreadCrumbs-item';
/**
 * Bread crumb paths.
 */
const BREAD_CRUMB_PATHS = ['/', '../../', '../', ''];
/**
 * The mime type for a contents drag object.
 */
const CONTENTS_MIME = 'application/x-jupyter-icontents';
/**
 * The class name added to drop targets.
 */
const DROP_TARGET_CLASS = 'jp-mod-dropTarget';
/**
 * A class which hosts folder breadcrumbs.
 */
class BreadCrumbs extends widgets_1.Widget {
    /**
     * Construct a new file browser crumb widget.
     *
     * @param model - The file browser view model.
     */
    constructor(options) {
        super();
        this._model = options.model;
        this.addClass(BREADCRUMB_CLASS);
        this._crumbs = Private.createCrumbs();
        this._crumbSeps = Private.createCrumbSeparators();
        this.node.appendChild(this._crumbs[Private.Crumb.Home]);
        this._model.refreshed.connect(this.update, this);
    }
    /**
     * Handle the DOM events for the bread crumbs.
     *
     * @param event - The DOM event sent to the widget.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the panel's DOM node. It should
     * not be called directly by user code.
     */
    handleEvent(event) {
        switch (event.type) {
            case 'click':
                this._evtClick(event);
                break;
            case 'p-dragenter':
                this._evtDragEnter(event);
                break;
            case 'p-dragleave':
                this._evtDragLeave(event);
                break;
            case 'p-dragover':
                this._evtDragOver(event);
                break;
            case 'p-drop':
                this._evtDrop(event);
                break;
            default:
                return;
        }
    }
    /**
     * A message handler invoked on an `'after-attach'` message.
     */
    onAfterAttach(msg) {
        super.onAfterAttach(msg);
        this.update();
        let node = this.node;
        node.addEventListener('click', this);
        node.addEventListener('p-dragenter', this);
        node.addEventListener('p-dragleave', this);
        node.addEventListener('p-dragover', this);
        node.addEventListener('p-drop', this);
    }
    /**
     * A message handler invoked on a `'before-detach'` message.
     */
    onBeforeDetach(msg) {
        super.onBeforeDetach(msg);
        let node = this.node;
        node.removeEventListener('click', this);
        node.removeEventListener('p-dragenter', this);
        node.removeEventListener('p-dragleave', this);
        node.removeEventListener('p-dragover', this);
        node.removeEventListener('p-drop', this);
    }
    /**
     * A handler invoked on an `'update-request'` message.
     */
    onUpdateRequest(msg) {
        // Update the breadcrumb list.
        const contents = this._model.manager.services.contents;
        const localPath = contents.localPath(this._model.path);
        Private.updateCrumbs(this._crumbs, this._crumbSeps, localPath);
    }
    /**
     * Handle the `'click'` event for the widget.
     */
    _evtClick(event) {
        // Do nothing if it's not a left mouse press.
        if (event.button !== 0) {
            return;
        }
        // Find a valid click target.
        let node = event.target;
        while (node && node !== this.node) {
            if (node.classList.contains(BREADCRUMB_ITEM_CLASS)) {
                let index = algorithm_1.ArrayExt.findFirstIndex(this._crumbs, value => value === node);
                this._model
                    .cd(BREAD_CRUMB_PATHS[index])
                    .catch(error => apputils_1.showErrorMessage('Open Error', error));
                // Stop the event propagation.
                event.preventDefault();
                event.stopPropagation();
                return;
            }
            node = node.parentElement;
        }
    }
    /**
     * Handle the `'p-dragenter'` event for the widget.
     */
    _evtDragEnter(event) {
        if (event.mimeData.hasData(CONTENTS_MIME)) {
            let index = algorithm_1.ArrayExt.findFirstIndex(this._crumbs, node => domutils_1.ElementExt.hitTest(node, event.clientX, event.clientY));
            if (index !== -1) {
                if (index !== Private.Crumb.Current) {
                    this._crumbs[index].classList.add(DROP_TARGET_CLASS);
                    event.preventDefault();
                    event.stopPropagation();
                }
            }
        }
    }
    /**
     * Handle the `'p-dragleave'` event for the widget.
     */
    _evtDragLeave(event) {
        event.preventDefault();
        event.stopPropagation();
        let dropTarget = apputils_1.DOMUtils.findElement(this.node, DROP_TARGET_CLASS);
        if (dropTarget) {
            dropTarget.classList.remove(DROP_TARGET_CLASS);
        }
    }
    /**
     * Handle the `'p-dragover'` event for the widget.
     */
    _evtDragOver(event) {
        event.preventDefault();
        event.stopPropagation();
        event.dropAction = event.proposedAction;
        let dropTarget = apputils_1.DOMUtils.findElement(this.node, DROP_TARGET_CLASS);
        if (dropTarget) {
            dropTarget.classList.remove(DROP_TARGET_CLASS);
        }
        let index = algorithm_1.ArrayExt.findFirstIndex(this._crumbs, node => domutils_1.ElementExt.hitTest(node, event.clientX, event.clientY));
        if (index !== -1) {
            this._crumbs[index].classList.add(DROP_TARGET_CLASS);
        }
    }
    /**
     * Handle the `'p-drop'` event for the widget.
     */
    _evtDrop(event) {
        event.preventDefault();
        event.stopPropagation();
        if (event.proposedAction === 'none') {
            event.dropAction = 'none';
            return;
        }
        if (!event.mimeData.hasData(CONTENTS_MIME)) {
            return;
        }
        event.dropAction = event.proposedAction;
        let target = event.target;
        while (target && target.parentElement) {
            if (target.classList.contains(DROP_TARGET_CLASS)) {
                target.classList.remove(DROP_TARGET_CLASS);
                break;
            }
            target = target.parentElement;
        }
        // Get the path based on the target node.
        let index = algorithm_1.ArrayExt.findFirstIndex(this._crumbs, node => node === target);
        if (index === -1) {
            return;
        }
        const model = this._model;
        const path = coreutils_1.PathExt.resolve(model.path, BREAD_CRUMB_PATHS[index]);
        const manager = model.manager;
        // Move all of the items.
        let promises = [];
        let oldPaths = event.mimeData.getData(CONTENTS_MIME);
        for (let oldPath of oldPaths) {
            let localOldPath = manager.services.contents.localPath(oldPath);
            let name = coreutils_1.PathExt.basename(localOldPath);
            let newPath = coreutils_1.PathExt.join(path, name);
            promises.push(docmanager_1.renameFile(manager, oldPath, newPath));
        }
        Promise.all(promises).catch(err => {
            apputils_1.showErrorMessage('Move Error', err);
        });
    }
}
exports.BreadCrumbs = BreadCrumbs;
/**
 * The namespace for the crumbs private data.
 */
var Private;
(function (Private) {
    /**
     * Breadcrumb item list enum.
     */
    let Crumb;
    (function (Crumb) {
        Crumb[Crumb["Home"] = 0] = "Home";
        Crumb[Crumb["Ellipsis"] = 1] = "Ellipsis";
        Crumb[Crumb["Parent"] = 2] = "Parent";
        Crumb[Crumb["Current"] = 3] = "Current";
    })(Crumb = Private.Crumb || (Private.Crumb = {}));
    /**
     * Populate the breadcrumb node.
     */
    function updateCrumbs(breadcrumbs, separators, path) {
        let node = breadcrumbs[0].parentNode;
        // Remove all but the home node.
        let firstChild = node.firstChild;
        while (firstChild && firstChild.nextSibling) {
            node.removeChild(firstChild.nextSibling);
        }
        let parts = path.split('/');
        if (parts.length > 2) {
            node.appendChild(separators[0]);
            node.appendChild(breadcrumbs[Crumb.Ellipsis]);
            let grandParent = parts.slice(0, parts.length - 2).join('/');
            breadcrumbs[Crumb.Ellipsis].title = grandParent;
        }
        if (path) {
            if (parts.length >= 2) {
                node.appendChild(separators[1]);
                breadcrumbs[Crumb.Parent].textContent = parts[parts.length - 2];
                node.appendChild(breadcrumbs[Crumb.Parent]);
                let parent = parts.slice(0, parts.length - 1).join('/');
                breadcrumbs[Crumb.Parent].title = parent;
            }
            node.appendChild(separators[2]);
            breadcrumbs[Crumb.Current].textContent = parts[parts.length - 1];
            node.appendChild(breadcrumbs[Crumb.Current]);
            breadcrumbs[Crumb.Current].title = path;
        }
    }
    Private.updateCrumbs = updateCrumbs;
    /**
     * Create the breadcrumb nodes.
     */
    function createCrumbs() {
        let home = document.createElement('span');
        home.className =
            MATERIAL_CLASS + ' ' + BREADCRUMB_HOME + ' ' + BREADCRUMB_ITEM_CLASS;
        home.title = 'Home';
        let ellipsis = document.createElement('span');
        ellipsis.className =
            MATERIAL_CLASS + ' ' + BREADCRUMB_ELLIPSES + ' ' + BREADCRUMB_ITEM_CLASS;
        let parent = document.createElement('span');
        parent.className = BREADCRUMB_ITEM_CLASS;
        let current = document.createElement('span');
        current.className = BREADCRUMB_ITEM_CLASS;
        return [home, ellipsis, parent, current];
    }
    Private.createCrumbs = createCrumbs;
    /**
     * Create the breadcrumb separator nodes.
     */
    function createCrumbSeparators() {
        let items = [];
        for (let i = 0; i < 3; i++) {
            let item = document.createElement('i');
            item.className = 'fa fa-angle-right';
            items.push(item);
        }
        return items;
    }
    Private.createCrumbSeparators = createCrumbSeparators;
})(Private || (Private = {}));


/***/ }),

/***/ "RA0T":
/*!*********************************************!*\
  !*** ./node_modules/requires-port/index.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Check if we're required to add a port number.
 *
 * @see https://url.spec.whatwg.org/#default-port
 * @param {Number|String} port Port number we need to check
 * @param {String} protocol Protocol we need to check against.
 * @returns {Boolean} Is it a default port for the given protocol
 * @api private
 */
module.exports = function required(port, protocol) {
  protocol = protocol.split(':')[0];
  port = +port;

  if (!port) return false;

  switch (protocol) {
    case 'http':
    case 'ws':
    return port !== 80;

    case 'https':
    case 'wss':
    return port !== 443;

    case 'ftp':
    return port !== 21;

    case 'gopher':
    return port !== 70;

    case 'file':
    return false;
  }

  return port !== 0;
};


/***/ }),

/***/ "RAar":
/*!**********************************************!*\
  !*** ./node_modules/mdi-react/ImportIcon.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var ImportIcon = function ImportIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M14,12L10,8V11H2V13H10V16M20,18V6C20,4.89 19.1,4 18,4H6C4.9,4 4,4.9 4,6V9H6V6H18V18H6V15H4V18C4,19.1 4.9,20 6,20H18C19.1,20 20,19.1 20,18Z' })
  );
};

module.exports = ImportIcon;


/***/ }),

/***/ "RAwQ":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/lb.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


function processRelativeTime(number, withoutSuffix, key, isFuture) {
    var format = {
        'm': ['eng Minutt', 'enger Minutt'],
        'h': ['eng Stonn', 'enger Stonn'],
        'd': ['een Dag', 'engem Dag'],
        'M': ['ee Mount', 'engem Mount'],
        'y': ['ee Joer', 'engem Joer']
    };
    return withoutSuffix ? format[key][0] : format[key][1];
}
function processFutureTime(string) {
    var number = string.substr(0, string.indexOf(' '));
    if (eifelerRegelAppliesToNumber(number)) {
        return 'a ' + string;
    }
    return 'an ' + string;
}
function processPastTime(string) {
    var number = string.substr(0, string.indexOf(' '));
    if (eifelerRegelAppliesToNumber(number)) {
        return 'viru ' + string;
    }
    return 'virun ' + string;
}
/**
 * Returns true if the word before the given number loses the '-n' ending.
 * e.g. 'an 10 Deeg' but 'a 5 Deeg'
 *
 * @param number {integer}
 * @returns {boolean}
 */
function eifelerRegelAppliesToNumber(number) {
    number = parseInt(number, 10);
    if (isNaN(number)) {
        return false;
    }
    if (number < 0) {
        // Negative Number --> always true
        return true;
    } else if (number < 10) {
        // Only 1 digit
        if (4 <= number && number <= 7) {
            return true;
        }
        return false;
    } else if (number < 100) {
        // 2 digits
        var lastDigit = number % 10, firstDigit = number / 10;
        if (lastDigit === 0) {
            return eifelerRegelAppliesToNumber(firstDigit);
        }
        return eifelerRegelAppliesToNumber(lastDigit);
    } else if (number < 10000) {
        // 3 or 4 digits --> recursively check first digit
        while (number >= 10) {
            number = number / 10;
        }
        return eifelerRegelAppliesToNumber(number);
    } else {
        // Anything larger than 4 digits: recursively check first n-3 digits
        number = number / 1000;
        return eifelerRegelAppliesToNumber(number);
    }
}

var lb = moment.defineLocale('lb', {
    months: 'Januar_Februar_Mäerz_Abrëll_Mee_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'),
    monthsShort: 'Jan._Febr._Mrz._Abr._Mee_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'),
    monthsParseExact : true,
    weekdays: 'Sonndeg_Méindeg_Dënschdeg_Mëttwoch_Donneschdeg_Freideg_Samschdeg'.split('_'),
    weekdaysShort: 'So._Mé._Dë._Më._Do._Fr._Sa.'.split('_'),
    weekdaysMin: 'So_Mé_Dë_Më_Do_Fr_Sa'.split('_'),
    weekdaysParseExact : true,
    longDateFormat: {
        LT: 'H:mm [Auer]',
        LTS: 'H:mm:ss [Auer]',
        L: 'DD.MM.YYYY',
        LL: 'D. MMMM YYYY',
        LLL: 'D. MMMM YYYY H:mm [Auer]',
        LLLL: 'dddd, D. MMMM YYYY H:mm [Auer]'
    },
    calendar: {
        sameDay: '[Haut um] LT',
        sameElse: 'L',
        nextDay: '[Muer um] LT',
        nextWeek: 'dddd [um] LT',
        lastDay: '[Gëschter um] LT',
        lastWeek: function () {
            // Different date string for 'Dënschdeg' (Tuesday) and 'Donneschdeg' (Thursday) due to phonological rule
            switch (this.day()) {
                case 2:
                case 4:
                    return '[Leschten] dddd [um] LT';
                default:
                    return '[Leschte] dddd [um] LT';
            }
        }
    },
    relativeTime : {
        future : processFutureTime,
        past : processPastTime,
        s : 'e puer Sekonnen',
        ss : '%d Sekonnen',
        m : processRelativeTime,
        mm : '%d Minutten',
        h : processRelativeTime,
        hh : '%d Stonnen',
        d : processRelativeTime,
        dd : '%d Deeg',
        M : processRelativeTime,
        MM : '%d Méint',
        y : processRelativeTime,
        yy : '%d Joer'
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal: '%d.',
    week: {
        dow: 1, // Monday is the first day of the week.
        doy: 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return lb;

})));


/***/ }),

/***/ "RBQu":
/*!******************************************************!*\
  !*** ./node_modules/@phosphor/coreutils/lib/uuid.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var random_1 = __webpack_require__(/*! ./random */ "cN6I");
/**
 * The namespace for UUID related functionality.
 */
var UUID;
(function (UUID) {
    /**
     * A function which generates UUID v4 identifiers.
     *
     * @returns A new UUID v4 string.
     *
     * #### Notes
     * This implementation complies with RFC 4122.
     *
     * This uses `Random.getRandomValues()` for random bytes, which in
     * turn will use the underlying `crypto` module of the platform if
     * it is available. The fallback for randomness is `Math.random`.
     */
    UUID.uuid4 = (function () {
        // Create a 16 byte array to hold the random values.
        var bytes = new Uint8Array(16);
        // Create a look up table from bytes to hex strings.
        var lut = new Array(256);
        // Pad the single character hex digits with a leading zero.
        for (var i = 0; i < 16; ++i) {
            lut[i] = '0' + i.toString(16);
        }
        // Populate the rest of the hex digits.
        for (var i = 16; i < 256; ++i) {
            lut[i] = i.toString(16);
        }
        // Return a function which generates the UUID.
        return function uuid4() {
            // Get a new batch of random values.
            random_1.Random.getRandomValues(bytes);
            // Set the UUID version number to 4.
            bytes[6] = 0x40 | (bytes[6] & 0x0F);
            // Set the clock sequence bit to the RFC spec.
            bytes[8] = 0x80 | (bytes[8] & 0x3F);
            // Assemble the UUID string.
            return (lut[bytes[0]] +
                lut[bytes[1]] +
                lut[bytes[2]] +
                lut[bytes[3]] +
                '-' +
                lut[bytes[4]] +
                lut[bytes[5]] +
                '-' +
                lut[bytes[6]] +
                lut[bytes[7]] +
                '-' +
                lut[bytes[8]] +
                lut[bytes[9]] +
                '-' +
                lut[bytes[10]] +
                lut[bytes[11]] +
                lut[bytes[12]] +
                lut[bytes[13]] +
                lut[bytes[14]] +
                lut[bytes[15]]);
        };
    })();
})(UUID = exports.UUID || (exports.UUID = {}));


/***/ }),

/***/ "RCR6":
/*!**************************************************************!*\
  !*** ./node_modules/draft-js/lib/decodeInlineStyleRanges.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule decodeInlineStyleRanges
 * @format
 * 
 */



var _require = __webpack_require__(/*! immutable */ "JPcv"),
    OrderedSet = _require.OrderedSet;

var UnicodeUtils = __webpack_require__(/*! fbjs/lib/UnicodeUtils */ "jLRO");

var substr = UnicodeUtils.substr;


var EMPTY_SET = OrderedSet();

/**
 * Convert to native JavaScript string lengths to determine ranges.
 */
function decodeInlineStyleRanges(text, ranges) {
  var styles = Array(text.length).fill(EMPTY_SET);
  if (ranges) {
    ranges.forEach(function ( /*object*/range) {
      var cursor = substr(text, 0, range.offset).length;
      var end = cursor + substr(text, range.offset, range.length).length;
      while (cursor < end) {
        styles[cursor] = styles[cursor].add(range.style);
        cursor++;
      }
    });
  }
  return styles;
}

module.exports = decodeInlineStyleRanges;

/***/ }),

/***/ "RFJM":
/*!**********************************************************!*\
  !*** ./node_modules/@phosphor/datagrid/lib/jsonmodel.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var datamodel_1 = __webpack_require__(/*! ./datamodel */ "y5KU");
/**
 * A data model implementation for in-memory JSON data.
 */
var JSONModel = (function (_super) {
    __extends(JSONModel, _super);
    /**
     * Create a data model with static JSON data.
     *
     * @param options - The options for initializing the data model.
     */
    function JSONModel(options) {
        var _this = _super.call(this) || this;
        var split = Private.splitFields(options.schema);
        _this._data = options.data;
        _this._bodyFields = split.bodyFields;
        _this._headerFields = split.headerFields;
        _this._missingValues = Private.createMissingMap(options.schema);
        return _this;
    }
    /**
     * Get the row count for a region in the data model.
     *
     * @param region - The row region of interest.
     *
     * @returns - The row count for the region.
     */
    JSONModel.prototype.rowCount = function (region) {
        if (region === 'body') {
            return this._data.length;
        }
        return 1; // TODO multiple column-header rows?
    };
    /**
     * Get the column count for a region in the data model.
     *
     * @param region - The column region of interest.
     *
     * @returns - The column count for the region.
     */
    JSONModel.prototype.columnCount = function (region) {
        if (region === 'body') {
            return this._bodyFields.length;
        }
        return this._headerFields.length;
    };
    /**
     * Get the metadata for a column in the data model.
     *
     * @param region - The cell region of interest.
     *
     * @param column - The index of the column of interest.
     *
     * @returns The metadata for the column.
     */
    JSONModel.prototype.metadata = function (region, column) {
        if (region === 'body' || region === 'column-header') {
            return this._bodyFields[column];
        }
        return this._headerFields[column];
    };
    /**
     * Get the data value for a cell in the data model.
     *
     * @param region - The cell region of interest.
     *
     * @param row - The row index of the cell of interest.
     *
     * @param column - The column index of the cell of interest.
     *
     * @param returns - The data value for the specified cell.
     *
     * #### Notes
     * A `missingValue` as defined by the schema is converted to `null`.
     */
    JSONModel.prototype.data = function (region, row, column) {
        // Set up the field and value variables.
        var field;
        var value;
        // Look up the field and value for the region.
        switch (region) {
            case 'body':
                field = this._bodyFields[column];
                value = this._data[row][field.name];
                break;
            case 'column-header':
                field = this._bodyFields[column];
                value = field.title || field.name;
                break;
            case 'row-header':
                field = this._headerFields[column];
                value = this._data[row][field.name];
                break;
            case 'corner-header':
                field = this._headerFields[column];
                value = field.title || field.name;
                break;
            default:
                throw 'unreachable';
        }
        // Test whether the value is a missing value.
        var missing = (this._missingValues !== null &&
            typeof value === 'string' &&
            this._missingValues[value] === true);
        // Return the final value.
        return missing ? null : value;
    };
    return JSONModel;
}(datamodel_1.DataModel));
exports.JSONModel = JSONModel;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * Split the schema fields into header and body fields.
     */
    function splitFields(schema) {
        // Normalize the primary keys.
        var primaryKeys;
        if (schema.primaryKey === undefined) {
            primaryKeys = [];
        }
        else if (typeof schema.primaryKey === 'string') {
            primaryKeys = [schema.primaryKey];
        }
        else {
            primaryKeys = schema.primaryKey;
        }
        // Separate the fields for the body and header.
        var bodyFields = [];
        var headerFields = [];
        for (var _i = 0, _a = schema.fields; _i < _a.length; _i++) {
            var field = _a[_i];
            if (primaryKeys.indexOf(field.name) === -1) {
                bodyFields.push(field);
            }
            else {
                headerFields.push(field);
            }
        }
        // Return the separated fields.
        return { bodyFields: bodyFields, headerFields: headerFields };
    }
    Private.splitFields = splitFields;
    /**
     * Create a missing values map for a schema.
     *
     * This returns `null` if there are no missing values.
     */
    function createMissingMap(schema) {
        // Bail early if there are no missing values.
        if (!schema.missingValues || schema.missingValues.length === 0) {
            return null;
        }
        // Collect the missing values into a map.
        var result = Object.create(null);
        for (var _i = 0, _a = schema.missingValues; _i < _a.length; _i++) {
            var value = _a[_i];
            result[value] = true;
        }
        // Return the populated map.
        return result;
    }
    Private.createMissingMap = createMissingMap;
})(Private || (Private = {}));


/***/ }),

/***/ "RGXH":
/*!*******************************************!*\
  !*** ./node_modules/jsonify/lib/parse.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

var at, // The index of the current character
    ch, // The current character
    escapee = {
        '"':  '"',
        '\\': '\\',
        '/':  '/',
        b:    '\b',
        f:    '\f',
        n:    '\n',
        r:    '\r',
        t:    '\t'
    },
    text,

    error = function (m) {
        // Call error when something is wrong.
        throw {
            name:    'SyntaxError',
            message: m,
            at:      at,
            text:    text
        };
    },
    
    next = function (c) {
        // If a c parameter is provided, verify that it matches the current character.
        if (c && c !== ch) {
            error("Expected '" + c + "' instead of '" + ch + "'");
        }
        
        // Get the next character. When there are no more characters,
        // return the empty string.
        
        ch = text.charAt(at);
        at += 1;
        return ch;
    },
    
    number = function () {
        // Parse a number value.
        var number,
            string = '';
        
        if (ch === '-') {
            string = '-';
            next('-');
        }
        while (ch >= '0' && ch <= '9') {
            string += ch;
            next();
        }
        if (ch === '.') {
            string += '.';
            while (next() && ch >= '0' && ch <= '9') {
                string += ch;
            }
        }
        if (ch === 'e' || ch === 'E') {
            string += ch;
            next();
            if (ch === '-' || ch === '+') {
                string += ch;
                next();
            }
            while (ch >= '0' && ch <= '9') {
                string += ch;
                next();
            }
        }
        number = +string;
        if (!isFinite(number)) {
            error("Bad number");
        } else {
            return number;
        }
    },
    
    string = function () {
        // Parse a string value.
        var hex,
            i,
            string = '',
            uffff;
        
        // When parsing for string values, we must look for " and \ characters.
        if (ch === '"') {
            while (next()) {
                if (ch === '"') {
                    next();
                    return string;
                } else if (ch === '\\') {
                    next();
                    if (ch === 'u') {
                        uffff = 0;
                        for (i = 0; i < 4; i += 1) {
                            hex = parseInt(next(), 16);
                            if (!isFinite(hex)) {
                                break;
                            }
                            uffff = uffff * 16 + hex;
                        }
                        string += String.fromCharCode(uffff);
                    } else if (typeof escapee[ch] === 'string') {
                        string += escapee[ch];
                    } else {
                        break;
                    }
                } else {
                    string += ch;
                }
            }
        }
        error("Bad string");
    },

    white = function () {

// Skip whitespace.

        while (ch && ch <= ' ') {
            next();
        }
    },

    word = function () {

// true, false, or null.

        switch (ch) {
        case 't':
            next('t');
            next('r');
            next('u');
            next('e');
            return true;
        case 'f':
            next('f');
            next('a');
            next('l');
            next('s');
            next('e');
            return false;
        case 'n':
            next('n');
            next('u');
            next('l');
            next('l');
            return null;
        }
        error("Unexpected '" + ch + "'");
    },

    value,  // Place holder for the value function.

    array = function () {

// Parse an array value.

        var array = [];

        if (ch === '[') {
            next('[');
            white();
            if (ch === ']') {
                next(']');
                return array;   // empty array
            }
            while (ch) {
                array.push(value());
                white();
                if (ch === ']') {
                    next(']');
                    return array;
                }
                next(',');
                white();
            }
        }
        error("Bad array");
    },

    object = function () {

// Parse an object value.

        var key,
            object = {};

        if (ch === '{') {
            next('{');
            white();
            if (ch === '}') {
                next('}');
                return object;   // empty object
            }
            while (ch) {
                key = string();
                white();
                next(':');
                if (Object.hasOwnProperty.call(object, key)) {
                    error('Duplicate key "' + key + '"');
                }
                object[key] = value();
                white();
                if (ch === '}') {
                    next('}');
                    return object;
                }
                next(',');
                white();
            }
        }
        error("Bad object");
    };

value = function () {

// Parse a JSON value. It could be an object, an array, a string, a number,
// or a word.

    white();
    switch (ch) {
    case '{':
        return object();
    case '[':
        return array();
    case '"':
        return string();
    case '-':
        return number();
    default:
        return ch >= '0' && ch <= '9' ? number() : word();
    }
};

// Return the json_parse function. It will have access to all of the above
// functions and variables.

module.exports = function (source, reviver) {
    var result;
    
    text = source;
    at = 0;
    ch = ' ';
    result = value();
    white();
    if (ch) {
        error("Syntax error");
    }

    // If there is a reviver function, we recursively walk the new structure,
    // passing each name/value pair to the reviver function for possible
    // transformation, starting with a temporary root object that holds the result
    // in an empty key. If there is not a reviver function, we simply return the
    // result.

    return typeof reviver === 'function' ? (function walk(holder, key) {
        var k, v, value = holder[key];
        if (value && typeof value === 'object') {
            for (k in value) {
                if (Object.prototype.hasOwnProperty.call(value, k)) {
                    v = walk(value, k);
                    if (v !== undefined) {
                        value[k] = v;
                    } else {
                        delete value[k];
                    }
                }
            }
        }
        return reviver.call(holder, key, value);
    }({'': result}, '')) : result;
};


/***/ }),

/***/ "RHTn":
/*!**********************************************************!*\
  !*** ./node_modules/@jupyterlab/fileeditor/lib/index.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
__webpack_require__(/*! ../style/index.css */ "nVxC");
__export(__webpack_require__(/*! ./widget */ "EugZ"));
/* tslint:disable */
/**
 * The editor tracker token.
 */
exports.IEditorTracker = new coreutils_1.Token('@jupyterlab/fileeditor:IEditorTracker');
/* tslint:enable */


/***/ }),

/***/ "RHWC":
/*!************************************************************!*\
  !*** ./node_modules/@jupyter-widgets/base/lib/registry.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
var coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
/**
 * A runtime interface token for a widget registry.
 */
exports.IJupyterWidgetRegistry = new coreutils_1.Token('jupyter.extensions.jupyterWidgetRegistry');


/***/ }),

/***/ "RIFs":
/*!*********************************************!*\
  !*** ./node_modules/mdi-react/ClockIcon.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var ClockIcon = function ClockIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M12,2C6.48,2 2,6.48 2,12C2,17.52 6.48,22 12,22C17.52,22 22,17.52 22,12C22,6.48 17.52,2 12,2M16.2,16.2L11,13V7H12.5V12.2L17,14.9L16.2,16.2Z' })
  );
};

module.exports = ClockIcon;


/***/ }),

/***/ "RK+W":
/*!**************************************************************!*\
  !*** ./node_modules/draft-js/lib/splitTextIntoTextBlocks.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule splitTextIntoTextBlocks
 * @format
 * 
 */



var NEWLINE_REGEX = /\r\n?|\n/g;

function splitTextIntoTextBlocks(text) {
  return text.split(NEWLINE_REGEX);
}

module.exports = splitTextIntoTextBlocks;

/***/ }),

/***/ "RKCW":
/*!*************************************************!*\
  !*** ./node_modules/codemirror/mode/gfm/gfm.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"), __webpack_require__(/*! ../markdown/markdown */ "lZu9"), __webpack_require__(/*! ../../addon/mode/overlay */ "nrkQ"));
  else {}
})(function(CodeMirror) {
"use strict";

var urlRE = /^((?:(?:aaas?|about|acap|adiumxtra|af[ps]|aim|apt|attachment|aw|beshare|bitcoin|bolo|callto|cap|chrome(?:-extension)?|cid|coap|com-eventbrite-attendee|content|crid|cvs|data|dav|dict|dlna-(?:playcontainer|playsingle)|dns|doi|dtn|dvb|ed2k|facetime|feed|file|finger|fish|ftp|geo|gg|git|gizmoproject|go|gopher|gtalk|h323|hcp|https?|iax|icap|icon|im|imap|info|ipn|ipp|irc[6s]?|iris(?:\.beep|\.lwz|\.xpc|\.xpcs)?|itms|jar|javascript|jms|keyparc|lastfm|ldaps?|magnet|mailto|maps|market|message|mid|mms|ms-help|msnim|msrps?|mtqp|mumble|mupdate|mvn|news|nfs|nih?|nntp|notes|oid|opaquelocktoken|palm|paparazzi|platform|pop|pres|proxy|psyc|query|res(?:ource)?|rmi|rsync|rtmp|rtsp|secondlife|service|session|sftp|sgn|shttp|sieve|sips?|skype|sm[bs]|snmp|soap\.beeps?|soldat|spotify|ssh|steam|svn|tag|teamspeak|tel(?:net)?|tftp|things|thismessage|tip|tn3270|tv|udp|unreal|urn|ut2004|vemmi|ventrilo|view-source|webcal|wss?|wtai|wyciwyg|xcon(?:-userid)?|xfire|xmlrpc\.beeps?|xmpp|xri|ymsgr|z39\.50[rs]?):(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]|\([^\s()<>]*\))+(?:\([^\s()<>]*\)|[^\s`*!()\[\]{};:'".,<>?«»“”‘’]))/i

CodeMirror.defineMode("gfm", function(config, modeConfig) {
  var codeDepth = 0;
  function blankLine(state) {
    state.code = false;
    return null;
  }
  var gfmOverlay = {
    startState: function() {
      return {
        code: false,
        codeBlock: false,
        ateSpace: false
      };
    },
    copyState: function(s) {
      return {
        code: s.code,
        codeBlock: s.codeBlock,
        ateSpace: s.ateSpace
      };
    },
    token: function(stream, state) {
      state.combineTokens = null;

      // Hack to prevent formatting override inside code blocks (block and inline)
      if (state.codeBlock) {
        if (stream.match(/^```+/)) {
          state.codeBlock = false;
          return null;
        }
        stream.skipToEnd();
        return null;
      }
      if (stream.sol()) {
        state.code = false;
      }
      if (stream.sol() && stream.match(/^```+/)) {
        stream.skipToEnd();
        state.codeBlock = true;
        return null;
      }
      // If this block is changed, it may need to be updated in Markdown mode
      if (stream.peek() === '`') {
        stream.next();
        var before = stream.pos;
        stream.eatWhile('`');
        var difference = 1 + stream.pos - before;
        if (!state.code) {
          codeDepth = difference;
          state.code = true;
        } else {
          if (difference === codeDepth) { // Must be exact
            state.code = false;
          }
        }
        return null;
      } else if (state.code) {
        stream.next();
        return null;
      }
      // Check if space. If so, links can be formatted later on
      if (stream.eatSpace()) {
        state.ateSpace = true;
        return null;
      }
      if (stream.sol() || state.ateSpace) {
        state.ateSpace = false;
        if (modeConfig.gitHubSpice !== false) {
          if(stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+@)?(?=.{0,6}\d)(?:[a-f0-9]{7,40}\b)/)) {
            // User/Project@SHA
            // User@SHA
            // SHA
            state.combineTokens = true;
            return "link";
          } else if (stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+)?#[0-9]+\b/)) {
            // User/Project#Num
            // User#Num
            // #Num
            state.combineTokens = true;
            return "link";
          }
        }
      }
      if (stream.match(urlRE) &&
          stream.string.slice(stream.start - 2, stream.start) != "](" &&
          (stream.start == 0 || /\W/.test(stream.string.charAt(stream.start - 1)))) {
        // URLs
        // Taken from http://daringfireball.net/2010/07/improved_regex_for_matching_urls
        // And then (issue #1160) simplified to make it not crash the Chrome Regexp engine
        // And then limited url schemes to the CommonMark list, so foo:bar isn't matched as a URL
        state.combineTokens = true;
        return "link";
      }
      stream.next();
      return null;
    },
    blankLine: blankLine
  };

  var markdownConfig = {
    taskLists: true,
    strikethrough: true,
    emoji: true
  };
  for (var attr in modeConfig) {
    markdownConfig[attr] = modeConfig[attr];
  }
  markdownConfig.name = "markdown";
  return CodeMirror.overlayMode(CodeMirror.getMode(config, markdownConfig), gfmOverlay);

}, "markdown");

  CodeMirror.defineMIME("text/x-gfm", "gfm");
});


/***/ }),

/***/ "RKMU":
/*!***************************************************************!*\
  !*** ./node_modules/elliptic/lib/elliptic/eddsa/signature.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var BN = __webpack_require__(/*! bn.js */ "OZ/i");
var elliptic = __webpack_require__(/*! ../../elliptic */ "MzeL");
var utils = elliptic.utils;
var assert = utils.assert;
var cachedProperty = utils.cachedProperty;
var parseBytes = utils.parseBytes;

/**
* @param {EDDSA} eddsa - eddsa instance
* @param {Array<Bytes>|Object} sig -
* @param {Array<Bytes>|Point} [sig.R] - R point as Point or bytes
* @param {Array<Bytes>|bn} [sig.S] - S scalar as bn or bytes
* @param {Array<Bytes>} [sig.Rencoded] - R point encoded
* @param {Array<Bytes>} [sig.Sencoded] - S scalar encoded
*/
function Signature(eddsa, sig) {
  this.eddsa = eddsa;

  if (typeof sig !== 'object')
    sig = parseBytes(sig);

  if (Array.isArray(sig)) {
    sig = {
      R: sig.slice(0, eddsa.encodingLength),
      S: sig.slice(eddsa.encodingLength)
    };
  }

  assert(sig.R && sig.S, 'Signature without R or S');

  if (eddsa.isPoint(sig.R))
    this._R = sig.R;
  if (sig.S instanceof BN)
    this._S = sig.S;

  this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;
  this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
}

cachedProperty(Signature, 'S', function S() {
  return this.eddsa.decodeInt(this.Sencoded());
});

cachedProperty(Signature, 'R', function R() {
  return this.eddsa.decodePoint(this.Rencoded());
});

cachedProperty(Signature, 'Rencoded', function Rencoded() {
  return this.eddsa.encodePoint(this.R());
});

cachedProperty(Signature, 'Sencoded', function Sencoded() {
  return this.eddsa.encodeInt(this.S());
});

Signature.prototype.toBytes = function toBytes() {
  return this.Rencoded().concat(this.Sencoded());
};

Signature.prototype.toHex = function toHex() {
  return utils.encode(this.toBytes(), 'hex').toUpperCase();
};

module.exports = Signature;


/***/ }),

/***/ "RMrj":
/*!*******************************************************************!*\
  !*** ./node_modules/@jupyterlab/inspector-extension/lib/index.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const application_1 = __webpack_require__(/*! @jupyterlab/application */ "FkFl");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const console_1 = __webpack_require__(/*! @jupyterlab/console */ "DrOJ");
const inspector_1 = __webpack_require__(/*! @jupyterlab/inspector */ "vy9w");
const notebook_1 = __webpack_require__(/*! @jupyterlab/notebook */ "JOGU");
const manager_1 = __webpack_require__(/*! ./manager */ "Qv8M");
/**
 * The command IDs used by the inspector plugin.
 */
var CommandIDs;
(function (CommandIDs) {
    CommandIDs.open = 'inspector:open';
})(CommandIDs || (CommandIDs = {}));
/**
 * A service providing code introspection.
 */
const inspector = {
    id: '@jupyterlab/inspector-extension:inspector',
    requires: [apputils_1.ICommandPalette, application_1.ILayoutRestorer],
    provides: inspector_1.IInspector,
    autoStart: true,
    activate: (app, palette, restorer) => {
        const { commands, shell } = app;
        const manager = new manager_1.InspectorManager();
        const category = 'Inspector';
        const command = CommandIDs.open;
        const label = 'Open Inspector';
        const namespace = 'inspector';
        const tracker = new apputils_1.InstanceTracker({
            namespace
        });
        /**
         * Create and track a new inspector.
         */
        function newInspectorPanel() {
            const inspector = new inspector_1.InspectorPanel();
            inspector.id = 'jp-inspector';
            inspector.title.label = 'Inspector';
            inspector.disposed.connect(() => {
                if (manager.inspector === inspector) {
                    manager.inspector = null;
                }
            });
            // Track the inspector.
            let widget = new apputils_1.MainAreaWidget({ content: inspector });
            tracker.add(widget);
            // Add the default inspector child items.
            Private.defaultInspectorItems.forEach(item => {
                inspector.add(item);
            });
            return inspector;
        }
        // Handle state restoration.
        restorer.restore(tracker, {
            command,
            args: () => null,
            name: () => 'inspector'
        });
        // Add command to registry and palette.
        commands.addCommand(command, {
            label,
            execute: () => {
                if (!manager.inspector || manager.inspector.isDisposed) {
                    manager.inspector = newInspectorPanel();
                }
                if (!manager.inspector.isAttached) {
                    shell.addToMainArea(manager.inspector.parent, { activate: false });
                }
                shell.activateById(manager.inspector.parent.id);
            }
        });
        palette.addItem({ command, category });
        return manager;
    }
};
/**
 * An extension that registers consoles for inspection.
 */
const consoles = {
    id: '@jupyterlab/inspector-extension:consoles',
    requires: [inspector_1.IInspector, console_1.IConsoleTracker],
    autoStart: true,
    activate: (app, manager, consoles) => {
        // Maintain association of new consoles with their respective handlers.
        const handlers = {};
        // Create a handler for each console that is created.
        consoles.widgetAdded.connect((sender, parent) => {
            const session = parent.console.session;
            const rendermime = parent.console.rendermime;
            const connector = new inspector_1.KernelConnector({ session });
            const handler = new inspector_1.InspectionHandler({ connector, rendermime });
            // Associate the handler to the widget.
            handlers[parent.id] = handler;
            // Set the initial editor.
            let cell = parent.console.promptCell;
            handler.editor = cell && cell.editor;
            // Listen for prompt creation.
            parent.console.promptCellCreated.connect((sender, cell) => {
                handler.editor = cell && cell.editor;
            });
            // Listen for parent disposal.
            parent.disposed.connect(() => {
                delete handlers[parent.id];
                handler.dispose();
            });
        });
        // Keep track of console instances and set inspector source.
        app.shell.currentChanged.connect((sender, args) => {
            let widget = args.newValue;
            if (!widget || !consoles.has(widget)) {
                return;
            }
            let source = handlers[widget.id];
            if (source) {
                manager.source = source;
            }
        });
        app.contextMenu.addItem({
            command: CommandIDs.open,
            selector: '.jp-CodeConsole-promptCell'
        });
    }
};
/**
 * An extension that registers notebooks for inspection.
 */
const notebooks = {
    id: '@jupyterlab/inspector-extension:notebooks',
    requires: [inspector_1.IInspector, notebook_1.INotebookTracker],
    autoStart: true,
    activate: (app, manager, notebooks) => {
        // Maintain association of new notebooks with their respective handlers.
        const handlers = {};
        // Create a handler for each notebook that is created.
        notebooks.widgetAdded.connect((sender, parent) => {
            const session = parent.session;
            const rendermime = parent.rendermime;
            const connector = new inspector_1.KernelConnector({ session });
            const handler = new inspector_1.InspectionHandler({ connector, rendermime });
            // Associate the handler to the widget.
            handlers[parent.id] = handler;
            // Set the initial editor.
            let cell = parent.content.activeCell;
            handler.editor = cell && cell.editor;
            // Listen for active cell changes.
            parent.content.activeCellChanged.connect((sender, cell) => {
                handler.editor = cell && cell.editor;
            });
            // Listen for parent disposal.
            parent.disposed.connect(() => {
                delete handlers[parent.id];
                handler.dispose();
            });
        });
        // Keep track of notebook instances and set inspector source.
        app.shell.currentChanged.connect((sender, args) => {
            let widget = args.newValue;
            if (!widget || !notebooks.has(widget)) {
                return;
            }
            let source = handlers[widget.id];
            if (source) {
                manager.source = source;
            }
        });
        app.contextMenu.addItem({
            command: CommandIDs.open,
            selector: '.jp-Notebook'
        });
    }
};
/**
 * Export the plugins as default.
 */
const plugins = [inspector, consoles, notebooks];
exports.default = plugins;
/**
 * A namespace for private data.
 */
var Private;
(function (Private) {
    /**
     * The default set of inspector items added to the inspector panel.
     */
    Private.defaultInspectorItems = [
        {
            className: 'jp-HintsInspectorItem',
            name: 'Hints',
            rank: 20,
            type: 'hints'
        }
    ];
})(Private || (Private = {}));


/***/ }),

/***/ "RNiT":
/*!********************************************************!*\
  !*** ./node_modules/@jupyterlab/notebook/lib/panel.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const docregistry_1 = __webpack_require__(/*! @jupyterlab/docregistry */ "jTF0");
const widget_1 = __webpack_require__(/*! ./widget */ "qZRx");
/**
 * The class name added to notebook panels.
 */
const NOTEBOOK_PANEL_CLASS = 'jp-NotebookPanel';
const NOTEBOOK_PANEL_TOOLBAR_CLASS = 'jp-NotebookPanel-toolbar';
const NOTEBOOK_PANEL_NOTEBOOK_CLASS = 'jp-NotebookPanel-notebook';
/**
 * A widget that hosts a notebook toolbar and content area.
 *
 * #### Notes
 * The widget keeps the document metadata in sync with the current
 * kernel on the context.
 */
class NotebookPanel extends docregistry_1.DocumentWidget {
    /**
     * Construct a new notebook panel.
     */
    constructor(options) {
        super(options);
        this._activated = new signaling_1.Signal(this);
        // Set up CSS classes
        this.addClass(NOTEBOOK_PANEL_CLASS);
        this.toolbar.addClass(NOTEBOOK_PANEL_TOOLBAR_CLASS);
        this.content.addClass(NOTEBOOK_PANEL_NOTEBOOK_CLASS);
        // Set up things related to the context
        this.content.model = this.context.model;
        this.context.session.kernelChanged.connect(this._onKernelChanged, this);
        this.revealed.then(() => {
            // Set the document edit mode on initial open if it looks like a new document.
            if (this.content.widgets.length === 1) {
                let cellModel = this.content.widgets[0].model;
                if (cellModel.type === 'code' && cellModel.value.text === '') {
                    this.content.mode = 'edit';
                }
            }
        });
    }
    /**
     * A signal emitted when the panel has been activated.
     */
    get activated() {
        return this._activated;
    }
    /**
     * The client session used by the panel.
     */
    get session() {
        return this.context.session;
    }
    /**
     * The content factory for the notebook.
     *
     * TODO: deprecate this in favor of the .content attribute
     *
     */
    get contentFactory() {
        return this.content.contentFactory;
    }
    /**
     * The rendermime instance for the notebook.
     *
     * TODO: deprecate this in favor of the .content attribute
     *
     */
    get rendermime() {
        return this.content.rendermime;
    }
    /**
     * The model for the widget.
     */
    get model() {
        return this.content ? this.content.model : null;
    }
    /**
     * Dispose of the resources used by the widget.
     */
    dispose() {
        this.content.dispose();
        super.dispose();
    }
    /**
     * Handle `'activate-request'` messages.
     */
    onActivateRequest(msg) {
        super.onActivateRequest(msg);
        // TODO: do we still need to emit this signal? Who is using it?
        this._activated.emit(void 0);
    }
    /**
     * Handle a change in the kernel by updating the document metadata.
     */
    _onKernelChanged(sender, args) {
        if (!this.model || !args.newValue) {
            return;
        }
        let { newValue } = args;
        newValue.ready.then(() => {
            if (this.model) {
                this._updateLanguage(newValue.info.language_info);
            }
        });
        this._updateSpec(newValue);
    }
    /**
     * Update the kernel language.
     */
    _updateLanguage(language) {
        this.model.metadata.set('language_info', language);
    }
    /**
     * Update the kernel spec.
     */
    _updateSpec(kernel) {
        kernel.getSpec().then(spec => {
            if (this.isDisposed) {
                return;
            }
            this.model.metadata.set('kernelspec', {
                name: kernel.name,
                display_name: spec.display_name,
                language: spec.language
            });
        });
    }
}
exports.NotebookPanel = NotebookPanel;
/**
 * A namespace for `NotebookPanel` statics.
 */
(function (NotebookPanel) {
    /**
     * The default implementation of an `IContentFactory`.
     */
    class ContentFactory extends widget_1.Notebook.ContentFactory {
        /**
         * Create a new content area for the panel.
         */
        createNotebook(options) {
            return new widget_1.Notebook(options);
        }
    }
    NotebookPanel.ContentFactory = ContentFactory;
    /**
     * Default content factory for the notebook panel.
     */
    NotebookPanel.defaultContentFactory = new ContentFactory();
    /* tslint:disable */
    /**
     * The notebook renderer token.
     */
    NotebookPanel.IContentFactory = new coreutils_1.Token('@jupyterlab/notebook:IContentFactory');
    /* tslint:enable */
})(NotebookPanel = exports.NotebookPanel || (exports.NotebookPanel = {}));


/***/ }),

/***/ "RQux":
/*!***********************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/codemirror/addon/dialog/dialog.css ***!
  \***********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, ".CodeMirror-dialog {\n  position: absolute;\n  left: 0; right: 0;\n  background: inherit;\n  z-index: 15;\n  padding: .1em .8em;\n  overflow: hidden;\n  color: inherit;\n}\n\n.CodeMirror-dialog-top {\n  border-bottom: 1px solid #eee;\n  top: 0;\n}\n\n.CodeMirror-dialog-bottom {\n  border-top: 1px solid #eee;\n  bottom: 0;\n}\n\n.CodeMirror-dialog input {\n  border: none;\n  outline: none;\n  background: transparent;\n  width: 20em;\n  color: inherit;\n  font-family: monospace;\n}\n\n.CodeMirror-dialog button {\n  font-size: 70%;\n}\n", ""]);

// exports


/***/ }),

/***/ "RTLL":
/*!*********************************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/css-syntax-error.js ***!
  \*********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _supportsColor = __webpack_require__(/*! supports-color */ 7);

var _supportsColor2 = _interopRequireDefault(_supportsColor);

var _chalk = __webpack_require__(/*! chalk */ 8);

var _chalk2 = _interopRequireDefault(_chalk);

var _terminalHighlight = __webpack_require__(/*! ./terminal-highlight */ "+Kq5");

var _terminalHighlight2 = _interopRequireDefault(_terminalHighlight);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * The CSS parser throws this error for broken CSS.
 *
 * Custom parsers can throw this error for broken custom syntax using
 * the {@link Node#error} method.
 *
 * PostCSS will use the input source map to detect the original error location.
 * If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS,
 * PostCSS will show the original position in the Sass file.
 *
 * If you need the position in the PostCSS input
 * (e.g., to debug the previous compiler), use `error.input.file`.
 *
 * @example
 * // Catching and checking syntax error
 * try {
 *   postcss.parse('a{')
 * } catch (error) {
 *   if ( error.name === 'CssSyntaxError' ) {
 *     error //=> CssSyntaxError
 *   }
 * }
 *
 * @example
 * // Raising error from plugin
 * throw node.error('Unknown variable', { plugin: 'postcss-vars' });
 */
var CssSyntaxError = function () {

    /**
     * @param {string} message  - error message
     * @param {number} [line]   - source line of the error
     * @param {number} [column] - source column of the error
     * @param {string} [source] - source code of the broken file
     * @param {string} [file]   - absolute path to the broken file
     * @param {string} [plugin] - PostCSS plugin name, if error came from plugin
     */
    function CssSyntaxError(message, line, column, source, file, plugin) {
        _classCallCheck(this, CssSyntaxError);

        /**
         * @member {string} - Always equal to `'CssSyntaxError'`. You should
         *                    always check error type
         *                    by `error.name === 'CssSyntaxError'` instead of
         *                    `error instanceof CssSyntaxError`, because
         *                    npm could have several PostCSS versions.
         *
         * @example
         * if ( error.name === 'CssSyntaxError' ) {
         *   error //=> CssSyntaxError
         * }
         */
        this.name = 'CssSyntaxError';
        /**
         * @member {string} - Error message.
         *
         * @example
         * error.message //=> 'Unclosed block'
         */
        this.reason = message;

        if (file) {
            /**
             * @member {string} - Absolute path to the broken file.
             *
             * @example
             * error.file       //=> 'a.sass'
             * error.input.file //=> 'a.css'
             */
            this.file = file;
        }
        if (source) {
            /**
             * @member {string} - Source code of the broken file.
             *
             * @example
             * error.source       //=> 'a { b {} }'
             * error.input.column //=> 'a b { }'
             */
            this.source = source;
        }
        if (plugin) {
            /**
             * @member {string} - Plugin name, if error came from plugin.
             *
             * @example
             * error.plugin //=> 'postcss-vars'
             */
            this.plugin = plugin;
        }
        if (typeof line !== 'undefined' && typeof column !== 'undefined') {
            /**
             * @member {number} - Source line of the error.
             *
             * @example
             * error.line       //=> 2
             * error.input.line //=> 4
             */
            this.line = line;
            /**
             * @member {number} - Source column of the error.
             *
             * @example
             * error.column       //=> 1
             * error.input.column //=> 4
             */
            this.column = column;
        }

        this.setMessage();

        if (Error.captureStackTrace) {
            Error.captureStackTrace(this, CssSyntaxError);
        }
    }

    CssSyntaxError.prototype.setMessage = function setMessage() {
        /**
         * @member {string} - Full error text in the GNU error format
         *                    with plugin, file, line and column.
         *
         * @example
         * error.message //=> 'a.css:1:1: Unclosed block'
         */
        this.message = this.plugin ? this.plugin + ': ' : '';
        this.message += this.file ? this.file : '<css input>';
        if (typeof this.line !== 'undefined') {
            this.message += ':' + this.line + ':' + this.column;
        }
        this.message += ': ' + this.reason;
    };

    /**
     * Returns a few lines of CSS source that caused the error.
     *
     * If the CSS has an input source map without `sourceContent`,
     * this method will return an empty string.
     *
     * @param {boolean} [color] whether arrow will be colored red by terminal
     *                          color codes. By default, PostCSS will detect
     *                          color support by `process.stdout.isTTY`
     *                          and `process.env.NODE_DISABLE_COLORS`.
     *
     * @example
     * error.showSourceCode() //=> "  4 | }
     *                        //      5 | a {
     *                        //    > 6 |   bad
     *                        //        |   ^
     *                        //      7 | }
     *                        //      8 | b {"
     *
     * @return {string} few lines of CSS source that caused the error
     */


    CssSyntaxError.prototype.showSourceCode = function showSourceCode(color) {
        var _this = this;

        if (!this.source) return '';

        var css = this.source;
        if (typeof color === 'undefined') color = _supportsColor2.default.stdout;
        if (color) css = (0, _terminalHighlight2.default)(css);

        var lines = css.split(/\r?\n/);
        var start = Math.max(this.line - 3, 0);
        var end = Math.min(this.line + 2, lines.length);

        var maxWidth = String(end).length;

        function mark(text) {
            if (color && _chalk2.default.red) {
                return _chalk2.default.red.bold(text);
            } else {
                return text;
            }
        }
        function aside(text) {
            if (color && _chalk2.default.gray) {
                return _chalk2.default.gray(text);
            } else {
                return text;
            }
        }

        return lines.slice(start, end).map(function (line, index) {
            var number = start + 1 + index;
            var gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | ';
            if (number === _this.line) {
                var spacing = aside(gutter.replace(/\d/g, ' ')) + line.slice(0, _this.column - 1).replace(/[^\t]/g, ' ');
                return mark('>') + aside(gutter) + line + '\n ' + spacing + mark('^');
            } else {
                return ' ' + aside(gutter) + line;
            }
        }).join('\n');
    };

    /**
     * Returns error position, message and source code of the broken part.
     *
     * @example
     * error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block
     *                  //    > 1 | a {
     *                  //        | ^"
     *
     * @return {string} error position, message and source code
     */


    CssSyntaxError.prototype.toString = function toString() {
        var code = this.showSourceCode();
        if (code) {
            code = '\n\n' + code + '\n';
        }
        return this.name + ': ' + this.message + code;
    };

    /**
     * @memberof CssSyntaxError#
     * @member {Input} input - Input object with PostCSS internal information
     *                         about input file. If input has source map
     *                         from previous tool, PostCSS will use origin
     *                         (for example, Sass) source. You can use this
     *                         object to get PostCSS input source.
     *
     * @example
     * error.input.file //=> 'a.css'
     * error.file       //=> 'a.sass'
     */

    return CssSyntaxError;
}();

exports.default = CssSyntaxError;
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64, 


/***/ }),

/***/ "RXjw":
/*!**********************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/index.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.walkObject = exports.upperCase = exports.unpackPlotProps = exports.transpose = exports.traceTypeToPlotlyInitFigure = exports.traceTypeToAxisType = exports.tooLight = exports.striptags = exports.renderTraceIcon = exports.removeNonWord = exports.plotlyTraceToCustomTrace = exports.pascalCase = exports.getParsedTemplateString = exports.maybeTransposeData = exports.maybeAdjustSrc = exports.lowerCase = exports.localizeString = exports.localize = exports.isPlainObject = exports.getSubplotTitle = exports.getFullTrace = exports.getDisplayName = exports.getAxisTitle = exports.getAllAxes = exports.dereference = exports.containerConnectedContextTypes = exports.connectUpdateMenuToLayout = exports.connectTransformToTrace = exports.connectTraceToPlot = exports.connectToContainer = exports.connectSliderToLayout = exports.connectShapeToLayout = exports.connectRangeSelectorToAxis = exports.connectNonCartesianSubplotToLayout = exports.connectLayoutToPlot = exports.connectImageToLayout = exports.connectCartesianSubplotToLayout = exports.connectAxesToLayout = exports.connectAnnotationToLayout = exports.connectAggregationToTransform = exports.computeTraceOptionsFromSchema = exports.clamp = exports.capitalize = exports.camelCase = exports.bem = exports.axisIdToAxisName = exports.adjustColorscale = undefined;

var _bem = __webpack_require__(/*! ./bem */ "6VdM");

var _bem2 = _interopRequireDefault(_bem);

var _connectCartesianSubplotToLayout = __webpack_require__(/*! ./connectCartesianSubplotToLayout */ "ucVw");

var _connectCartesianSubplotToLayout2 = _interopRequireDefault(_connectCartesianSubplotToLayout);

var _connectNonCartesianSubplotToLayout = __webpack_require__(/*! ./connectNonCartesianSubplotToLayout */ "XpWx");

var _connectNonCartesianSubplotToLayout2 = _interopRequireDefault(_connectNonCartesianSubplotToLayout);

var _connectAnnotationToLayout = __webpack_require__(/*! ./connectAnnotationToLayout */ "ihYd");

var _connectAnnotationToLayout2 = _interopRequireDefault(_connectAnnotationToLayout);

var _connectShapeToLayout = __webpack_require__(/*! ./connectShapeToLayout */ "k3G+");

var _connectShapeToLayout2 = _interopRequireDefault(_connectShapeToLayout);

var _connectSliderToLayout = __webpack_require__(/*! ./connectSliderToLayout */ "QkKW");

var _connectSliderToLayout2 = _interopRequireDefault(_connectSliderToLayout);

var _connectImageToLayout = __webpack_require__(/*! ./connectImageToLayout */ "BWSO");

var _connectImageToLayout2 = _interopRequireDefault(_connectImageToLayout);

var _connectUpdateMenuToLayout = __webpack_require__(/*! ./connectUpdateMenuToLayout */ "i0cE");

var _connectUpdateMenuToLayout2 = _interopRequireDefault(_connectUpdateMenuToLayout);

var _connectRangeSelectorToAxis = __webpack_require__(/*! ./connectRangeSelectorToAxis */ "Oz5i");

var _connectRangeSelectorToAxis2 = _interopRequireDefault(_connectRangeSelectorToAxis);

var _connectTransformToTrace = __webpack_require__(/*! ./connectTransformToTrace */ "ItQE");

var _connectTransformToTrace2 = _interopRequireDefault(_connectTransformToTrace);

var _connectAggregationToTransform = __webpack_require__(/*! ./connectAggregationToTransform */ "g5w3");

var _connectAggregationToTransform2 = _interopRequireDefault(_connectAggregationToTransform);

var _connectAxesToLayout = __webpack_require__(/*! ./connectAxesToLayout */ "xhLm");

var _connectAxesToLayout2 = _interopRequireDefault(_connectAxesToLayout);

var _connectLayoutToPlot = __webpack_require__(/*! ./connectLayoutToPlot */ "XAgW");

var _connectLayoutToPlot2 = _interopRequireDefault(_connectLayoutToPlot);

var _connectToContainer = __webpack_require__(/*! ./connectToContainer */ "A5fR");

var _connectToContainer2 = _interopRequireDefault(_connectToContainer);

var _computeTraceOptionsFromSchema = __webpack_require__(/*! ./computeTraceOptionsFromSchema */ "TkbC");

var _connectTraceToPlot = __webpack_require__(/*! ./connectTraceToPlot */ "5Bud");

var _connectTraceToPlot2 = _interopRequireDefault(_connectTraceToPlot);

var _dereference = __webpack_require__(/*! ./dereference */ "Zi9O");

var _dereference2 = _interopRequireDefault(_dereference);

var _getAllAxes = __webpack_require__(/*! ./getAllAxes */ "uMpD");

var _getAllAxes2 = _interopRequireDefault(_getAllAxes);

var _localize = __webpack_require__(/*! ./localize */ "rIs4");

var _localize2 = _interopRequireDefault(_localize);

var _tinycolor = __webpack_require__(/*! tinycolor2 */ "Zss7");

var _tinycolor2 = _interopRequireDefault(_tinycolor);

var _unpackPlotProps = __webpack_require__(/*! ./unpackPlotProps */ "WWhV");

var _unpackPlotProps2 = _interopRequireDefault(_unpackPlotProps);

var _walkObject = __webpack_require__(/*! ./walkObject */ "/0O1");

var _walkObject2 = _interopRequireDefault(_walkObject);

var _customTraceType = __webpack_require__(/*! ./customTraceType */ "W+VA");

var _plotlyIcons = __webpack_require__(/*! plotly-icons */ "hwSx");

var PlotlyIcons = _interopRequireWildcard(_plotlyIcons);

var _striptags = __webpack_require__(/*! ./striptags */ "qw1u");

var _striptags2 = _interopRequireDefault(_striptags);

var _strings = __webpack_require__(/*! ./strings */ "Tv0l");

var _reactColorscales = __webpack_require__(/*! react-colorscales */ "FOBs");

var _lib = __webpack_require__(/*! plotly.js/src/lib */ "/CZE");

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TOO_LIGHT_FACTOR = 0.8;

function clamp(value, min, max) {
  return Math.max(min, Math.min(max, value));
}

function getDisplayName(WrappedComponent) {
  return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}

function tooLight(color) {
  var hslColor = (0, _tinycolor2.default)(color).toHsl();
  return hslColor.l > TOO_LIGHT_FACTOR;
}

function renderTraceIcon(trace) {
  var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'Plot';

  if (!trace) {
    return null;
  }
  var gl = 'gl';
  var componentName = '' + prefix + (0, _strings.pascalCase)(trace.endsWith(gl) ? trace.slice(0, -gl.length) : trace) + 'Icon';

  return PlotlyIcons[componentName] ? PlotlyIcons[componentName] : PlotlyIcons.PlotLineIcon;
}

function transpose(originalArray) {
  // if we want to transpose a uni dimensional array
  if (originalArray.every(function (a) {
    return !Array.isArray(a);
  })) {
    return originalArray.map(function (a) {
      return [a];
    });
  }

  var longestArrayItem = Array.isArray(originalArray[0]) ? originalArray[0].length : 1;

  originalArray.forEach(function (a) {
    // if it's not an array, it's a string
    var length = Array.isArray(a) ? a.length : 1;
    if (length > longestArrayItem) {
      longestArrayItem = length;
    }
  });

  var newArray = new Array(longestArrayItem);

  for (var outerIndex = 0; outerIndex < originalArray.length; outerIndex++) {
    if (!Array.isArray(originalArray[outerIndex])) {
      originalArray[outerIndex] = [originalArray[outerIndex]];
    }

    for (var innerIndex = 0; innerIndex < longestArrayItem; innerIndex++) {
      // ensure we have an array to push to
      if (!Array.isArray(newArray[innerIndex])) {
        newArray[innerIndex] = [];
      }

      var value = typeof originalArray[outerIndex][innerIndex] !== 'undefined' ? originalArray[outerIndex][innerIndex] : null;
      newArray[innerIndex].push(value);
    }
  }

  return newArray;
}

var specialTableCase = function specialTableCase(traceType, srcAttributePath) {
  /* Just more user friendly
   * Table traces have many configuration options,
   * The below attributes can be 2d or 1d and will affect the plot differently
   * EX:
   * header.values = ['Jan', 'Feb', 'Mar'] => will put data in a row
   * header.values = [['Jan', 1], ['Feb', 2], ['Mar', 3]] => will create 3 columns
   * 1d arrays affect columns
   * 2d arrays affect rows within each column
   */
  return traceType === 'table' && ['header.valuessrc', 'header.font.colorsrc', 'header.font.sizesrc', 'header.fill.colorsrc', 'columnwidthsrc'].some(function (a) {
    return srcAttributePath.endsWith(a);
  });
};

function maybeTransposeData(data, srcAttributePath, traceType) {
  if (!data || Array.isArray(data) && data.length === 0) {
    return null;
  }

  var isTransposable2DArray = srcAttributePath.endsWith('zsrc') && ['contour', 'contourgl', 'heatmap', 'heatmapgl', 'surface', 'carpet', 'contourcarpet'].includes(traceType);

  if (isTransposable2DArray) {
    return transpose(data);
  }

  if (specialTableCase(traceType, srcAttributePath) && Array.isArray(data[0]) && data.length === 1) {
    return data[0];
  }

  return data;
}

function maybeAdjustSrc(src, srcAttributePath, traceType, config) {
  if (!src || Array.isArray(src) && src.length === 0) {
    return null;
  }

  if (specialTableCase(traceType, srcAttributePath) && src.length === 1) {
    return src[0];
  }

  return config && config.fromSrc ? config.fromSrc(src, traceType, srcAttributePath) : src;
}

function adjustColorscale(colorscale, numberOfNeededColors, colorscaleType, config) {
  if (config && config.repeat) {
    if (numberOfNeededColors < colorscale.length) {
      return colorscale.slice(0, numberOfNeededColors);
    }

    var repetitions = Math.ceil(numberOfNeededColors / colorscale.length);
    var newArray = new Array(repetitions).fill(colorscale);
    return newArray.reduce(function (a, b) {
      return a.concat(b);
    }, []).slice(0, numberOfNeededColors);
  }

  return (0, _reactColorscales.getColorscale)(colorscale, numberOfNeededColors, null, null, colorscaleType);
}

function getFullTrace(props, context) {
  var fullTrace = {};
  if (context.fullData && context.data) {
    if (props.fullDataArrayPosition) {
      // fullDataArrayPosition will be supplied in panels that have the canGroup prop
      fullTrace = context.fullData[props.fullDataArrayPosition[0]];
    } else {
      // for all other panels, we'll find fullTrace with the data index
      fullTrace = context.fullData.filter(function (t) {
        return t && props.traceIndexes[0] === t.index;
      })[0];
    }

    // For transformed traces, we actually want to read in _fullInput because
    // there's original parent information that's more useful to the user there
    // This is true except for fit transforms, where reading in fullData is
    // what we want
    if (fullTrace.transforms && !fullTrace.transforms.some(function (t) {
      return ['moving-average', 'fits'].includes(t.type);
    }) && !props.fullDataArrayPosition) {
      fullTrace = fullTrace._fullInput;
    }
  }
  return fullTrace;
}

function getParsedTemplateString(originalString, meta) {
  var text = originalString;

  if (originalString && meta && meta.length) {
    text = (0, _lib.templateString)(originalString, { meta: meta });
  }

  return text === '' && originalString ? originalString : text;
}

exports.adjustColorscale = adjustColorscale;
exports.axisIdToAxisName = _getAllAxes.axisIdToAxisName;
exports.bem = _bem2.default;
exports.camelCase = _strings.camelCase;
exports.capitalize = _strings.capitalize;
exports.clamp = clamp;
exports.computeTraceOptionsFromSchema = _computeTraceOptionsFromSchema.computeTraceOptionsFromSchema;
exports.connectAggregationToTransform = _connectAggregationToTransform2.default;
exports.connectAnnotationToLayout = _connectAnnotationToLayout2.default;
exports.connectAxesToLayout = _connectAxesToLayout2.default;
exports.connectCartesianSubplotToLayout = _connectCartesianSubplotToLayout2.default;
exports.connectImageToLayout = _connectImageToLayout2.default;
exports.connectLayoutToPlot = _connectLayoutToPlot2.default;
exports.connectNonCartesianSubplotToLayout = _connectNonCartesianSubplotToLayout2.default;
exports.connectRangeSelectorToAxis = _connectRangeSelectorToAxis2.default;
exports.connectShapeToLayout = _connectShapeToLayout2.default;
exports.connectSliderToLayout = _connectSliderToLayout2.default;
exports.connectToContainer = _connectToContainer2.default;
exports.connectTraceToPlot = _connectTraceToPlot2.default;
exports.connectTransformToTrace = _connectTransformToTrace2.default;
exports.connectUpdateMenuToLayout = _connectUpdateMenuToLayout2.default;
exports.containerConnectedContextTypes = _connectToContainer.containerConnectedContextTypes;
exports.dereference = _dereference2.default;
exports.getAllAxes = _getAllAxes2.default;
exports.getAxisTitle = _getAllAxes.getAxisTitle;
exports.getDisplayName = getDisplayName;
exports.getFullTrace = getFullTrace;
exports.getSubplotTitle = _getAllAxes.getSubplotTitle;
exports.isPlainObject = _walkObject.isPlainObject;
exports.localize = _localize2.default;
exports.localizeString = _localize.localizeString;
exports.lowerCase = _strings.lowerCase;
exports.maybeAdjustSrc = maybeAdjustSrc;
exports.maybeTransposeData = maybeTransposeData;
exports.getParsedTemplateString = getParsedTemplateString;
exports.pascalCase = _strings.pascalCase;
exports.plotlyTraceToCustomTrace = _customTraceType.plotlyTraceToCustomTrace;
exports.removeNonWord = _strings.removeNonWord;
exports.renderTraceIcon = renderTraceIcon;
exports.striptags = _striptags2.default;
exports.tooLight = tooLight;
exports.traceTypeToAxisType = _getAllAxes.traceTypeToAxisType;
exports.traceTypeToPlotlyInitFigure = _customTraceType.traceTypeToPlotlyInitFigure;
exports.transpose = transpose;
exports.unpackPlotProps = _unpackPlotProps2.default;
exports.upperCase = _strings.upperCase;
exports.walkObject = _walkObject2.default;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ "RZIX":
/*!**********************************************************!*\
  !*** ./node_modules/@jupyterlab/console/style/index.css ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "6Wb8");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "RcvF":
/*!***************************************************!*\
  !*** ./node_modules/mdi-react/RotateRightIcon.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var RotateRightIcon = function RotateRightIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M16.89,15.5L18.31,16.89C19.21,15.73 19.76,14.39 19.93,13H17.91C17.77,13.87 17.43,14.72 16.89,15.5M13,17.9V19.92C14.39,19.75 15.74,19.21 16.9,18.31L15.46,16.87C14.71,17.41 13.87,17.76 13,17.9M19.93,11C19.76,9.61 19.21,8.27 18.31,7.11L16.89,8.53C17.43,9.28 17.77,10.13 17.91,11M15.55,5.55L11,1V4.07C7.06,4.56 4,7.92 4,12C4,16.08 7.05,19.44 11,19.93V17.91C8.16,17.43 6,14.97 6,12C6,9.03 8.16,6.57 11,6.09V10L15.55,5.55Z' })
  );
};

module.exports = RotateRightIcon;


/***/ }),

/***/ "RfKB":
/*!********************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_set-to-string-tag.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var def = __webpack_require__(/*! ./_object-dp */ "2faE").f;
var has = __webpack_require__(/*! ./_has */ "B+OT");
var TAG = __webpack_require__(/*! ./_wks */ "UWiX")('toStringTag');

module.exports = function (it, tag, stat) {
  if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag });
};


/***/ }),

/***/ "Rfbk":
/*!*******************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/json-extension/style/index.css ***!
  \*******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/**\n  Copyright (c) Jupyter Development Team.\n  Distributed under the terms of the Modified BSD License.\n*/\n\n/* Add CSS variables to :root */\n:root {\n  /*--jp-private-json-variable: 16px;*/\n}\n\n/* Base styles */\n.jp-RenderedJSON {\n  width: 100%;\n  height: 100%;\n  padding: 0;\n  overflow: hidden;\n}\n\n/* Patch for default ul.CodeMirror styles */\n.jp-RenderedJSON ul.CodeMirror {\n  list-style: none;\n  padding-left: 0;\n  margin: 0;\n}\n\n/* Document styles */\n.jp-MimeDocument .jp-RenderedJSON {\n  padding: 5px;\n  padding-top: 0;\n  overflow-y: auto;\n}\n\n/* Output styles */\n.jp-OutputArea .jp-RenderedJSON {\n}\n", ""]);

// exports


/***/ }),

/***/ "RhoE":
/*!**********************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/codemirror/theme/base16-light.css ***!
  \**********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*\n\n    Name:       Base16 Default Light\n    Author:     Chris Kempson (http://chriskempson.com)\n\n    CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror)\n    Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16)\n\n*/\n\n.cm-s-base16-light.CodeMirror { background: #f5f5f5; color: #202020; }\n.cm-s-base16-light div.CodeMirror-selected { background: #e0e0e0; }\n.cm-s-base16-light .CodeMirror-line::selection, .cm-s-base16-light .CodeMirror-line > span::selection, .cm-s-base16-light .CodeMirror-line > span > span::selection { background: #e0e0e0; }\n.cm-s-base16-light .CodeMirror-line::-moz-selection, .cm-s-base16-light .CodeMirror-line > span::-moz-selection, .cm-s-base16-light .CodeMirror-line > span > span::-moz-selection { background: #e0e0e0; }\n.cm-s-base16-light .CodeMirror-gutters { background: #f5f5f5; border-right: 0px; }\n.cm-s-base16-light .CodeMirror-guttermarker { color: #ac4142; }\n.cm-s-base16-light .CodeMirror-guttermarker-subtle { color: #b0b0b0; }\n.cm-s-base16-light .CodeMirror-linenumber { color: #b0b0b0; }\n.cm-s-base16-light .CodeMirror-cursor { border-left: 1px solid #505050; }\n\n.cm-s-base16-light span.cm-comment { color: #8f5536; }\n.cm-s-base16-light span.cm-atom { color: #aa759f; }\n.cm-s-base16-light span.cm-number { color: #aa759f; }\n\n.cm-s-base16-light span.cm-property, .cm-s-base16-light span.cm-attribute { color: #90a959; }\n.cm-s-base16-light span.cm-keyword { color: #ac4142; }\n.cm-s-base16-light span.cm-string { color: #f4bf75; }\n\n.cm-s-base16-light span.cm-variable { color: #90a959; }\n.cm-s-base16-light span.cm-variable-2 { color: #6a9fb5; }\n.cm-s-base16-light span.cm-def { color: #d28445; }\n.cm-s-base16-light span.cm-bracket { color: #202020; }\n.cm-s-base16-light span.cm-tag { color: #ac4142; }\n.cm-s-base16-light span.cm-link { color: #aa759f; }\n.cm-s-base16-light span.cm-error { background: #ac4142; color: #505050; }\n\n.cm-s-base16-light .CodeMirror-activeline-background { background: #DDDCDC; }\n.cm-s-base16-light .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; }\n", ""]);

// exports


/***/ }),

/***/ "Ri4F":
/*!************************************************!*\
  !*** ./node_modules/plotlywidget/package.json ***!
  \************************************************/
/*! exports provided: name, version, description, author, license, main, repository, keywords, files, scripts, devDependencies, dependencies, jupyterlab, default */
/***/ (function(module) {

module.exports = {"name":"plotlywidget","version":"0.8.0","description":"The plotly.py ipywidgets library","author":"The plotly.py team","license":"MIT","main":"src/index.js","repository":{"type":"git","url":"https://github.com/plotly/plotly.py"},"keywords":["jupyter","widgets","ipython","ipywidgets","plotly"],"files":["src/**/*.js","dist/*.js"],"scripts":{"clean":"rimraf dist/ && rimraf ../plotlywidget/static","prepublish":"webpack","test":"echo \"Error: no test specified\" && exit 1"},"devDependencies":{"webpack":"^3.10.0","rimraf":"^2.6.1","ify-loader":"^1.1.0"},"dependencies":{"plotly.js":"1.45.2","@jupyter-widgets/base":"^1.0.0","lodash":"^4.17.4"},"jupyterlab":{"extension":"src/jupyterlab-plugin"}};

/***/ }),

/***/ "RjN7":
/*!*********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotBubblesIcon.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotBubblesIcon = function PlotBubblesIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M0 0h1.625v32H0zm32 30.375V32H0v-1.625zM9.625 19.188c0 .875-.75 1.625-1.625 1.625s-1.625-.75-1.625-1.625.75-1.563 1.625-1.563 1.625.688 1.625 1.563zM30.375 4a2.374 2.374 0 1 1-4.75 0 2.374 2.374 0 1 1 4.75 0zm-1.562 7.188a3.202 3.202 0 0 1-3.188 3.188c-1.813 0-3.25-1.438-3.25-3.188S23.813 8 25.625 8a3.202 3.202 0 0 1 3.188 3.188zm-6.438-5.563c0 2.188-1.75 4-4 4-2.188 0-4-1.813-4-4 0-2.25 1.813-4 4-4 2.25 0 4 1.75 4 4zM20.75 16c0 2.625-2.188 4.813-4.813 4.813-2.688 0-4.813-2.188-4.813-4.813s2.125-4.813 4.813-4.813c2.625 0 4.813 2.188 4.813 4.813zM9.5 12.813c0 1.75-1.438 3.188-3.188 3.188s-3.188-1.438-3.188-3.188c0-1.75 1.438-3.188 3.188-3.188S9.5 11.063 9.5 12.813zm.125 12c0 1.313-1.125 2.375-2.438 2.375s-2.375-1.063-2.375-2.375c0-1.313 1.063-2.438 2.375-2.438s2.438 1.125 2.438 2.438zM16 24c0 .875-.688 1.625-1.625 1.625-.875 0-1.563-.75-1.563-1.625s.688-1.625 1.563-1.625c.938 0 1.625.75 1.625 1.625zm11.188-5.625c0 1.375-1.063 2.438-2.375 2.438s-2.438-1.063-2.438-2.438c0-1.313 1.125-2.375 2.438-2.375s2.375 1.063 2.375 2.375zm-6.375 4.813c0 .438-.375.813-.813.813s-.813-.375-.813-.813c0-.438.375-.813.813-.813s.813.375.813.813zm-8-16c0 .438-.375.813-.813.813s-.813-.375-.813-.813c0-.438.375-.813.813-.813s.813.375.813.813z' })
    );
};

exports.default = PlotBubblesIcon;

/***/ }),

/***/ "Rkpk":
/*!************************************************************************!*\
  !*** ./node_modules/react-color/lib/components/chrome/ChromeFields.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ChromeFields = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _color = __webpack_require__(/*! ../../helpers/color */ "p8yl");

var _color2 = _interopRequireDefault(_color);

var _common = __webpack_require__(/*! ../common */ "TM95");

var _UnfoldMoreHorizontalIcon = __webpack_require__(/*! @icons/material/UnfoldMoreHorizontalIcon */ "9F0J");

var _UnfoldMoreHorizontalIcon2 = _interopRequireDefault(_UnfoldMoreHorizontalIcon);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint-disable react/no-did-mount-set-state, no-param-reassign */

var ChromeFields = exports.ChromeFields = function (_React$Component) {
  _inherits(ChromeFields, _React$Component);

  function ChromeFields() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, ChromeFields);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = ChromeFields.__proto__ || Object.getPrototypeOf(ChromeFields)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
      view: ''
    }, _this.toggleViews = function () {
      if (_this.state.view === 'hex') {
        _this.setState({ view: 'rgb' });
      } else if (_this.state.view === 'rgb') {
        _this.setState({ view: 'hsl' });
      } else if (_this.state.view === 'hsl') {
        if (_this.props.hsl.a === 1) {
          _this.setState({ view: 'hex' });
        } else {
          _this.setState({ view: 'rgb' });
        }
      }
    }, _this.handleChange = function (data, e) {
      if (data.hex) {
        _color2.default.isValidHex(data.hex) && _this.props.onChange({
          hex: data.hex,
          source: 'hex'
        }, e);
      } else if (data.r || data.g || data.b) {
        _this.props.onChange({
          r: data.r || _this.props.rgb.r,
          g: data.g || _this.props.rgb.g,
          b: data.b || _this.props.rgb.b,
          source: 'rgb'
        }, e);
      } else if (data.a) {
        if (data.a < 0) {
          data.a = 0;
        } else if (data.a > 1) {
          data.a = 1;
        }

        _this.props.onChange({
          h: _this.props.hsl.h,
          s: _this.props.hsl.s,
          l: _this.props.hsl.l,
          a: Math.round(data.a * 100) / 100,
          source: 'rgb'
        }, e);
      } else if (data.h || data.s || data.l) {
        // Remove any occurances of '%'.
        if (typeof data.s === 'string' && data.s.includes('%')) {
          data.s = data.s.replace('%', '');
        }
        if (typeof data.l === 'string' && data.l.includes('%')) {
          data.l = data.l.replace('%', '');
        }

        _this.props.onChange({
          h: data.h || _this.props.hsl.h,
          s: Number(data.s && data.s || _this.props.hsl.s),
          l: Number(data.l && data.l || _this.props.hsl.l),
          source: 'hsl'
        }, e);
      }
    }, _this.showHighlight = function (e) {
      e.currentTarget.style.background = '#eee';
    }, _this.hideHighlight = function (e) {
      e.currentTarget.style.background = 'transparent';
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(ChromeFields, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      if (this.props.hsl.a === 1 && this.state.view !== 'hex') {
        this.setState({ view: 'hex' });
      } else if (this.state.view !== 'rgb' && this.state.view !== 'hsl') {
        this.setState({ view: 'rgb' });
      }
    }
  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      if (nextProps.hsl.a !== 1 && this.state.view === 'hex') {
        this.setState({ view: 'rgb' });
      }
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var styles = (0, _reactcss2.default)({
        'default': {
          wrap: {
            paddingTop: '16px',
            display: 'flex'
          },
          fields: {
            flex: '1',
            display: 'flex',
            marginLeft: '-6px'
          },
          field: {
            paddingLeft: '6px',
            width: '100%'
          },
          alpha: {
            paddingLeft: '6px',
            width: '100%'
          },
          toggle: {
            width: '32px',
            textAlign: 'right',
            position: 'relative'
          },
          icon: {
            marginRight: '-4px',
            marginTop: '12px',
            cursor: 'pointer',
            position: 'relative'
          },
          iconHighlight: {
            position: 'absolute',
            width: '24px',
            height: '28px',
            background: '#eee',
            borderRadius: '4px',
            top: '10px',
            left: '12px',
            display: 'none'
          },
          input: {
            fontSize: '11px',
            color: '#333',
            width: '100%',
            borderRadius: '2px',
            border: 'none',
            boxShadow: 'inset 0 0 0 1px #dadada',
            height: '21px',
            textAlign: 'center'
          },
          label: {
            textTransform: 'uppercase',
            fontSize: '11px',
            lineHeight: '11px',
            color: '#969696',
            textAlign: 'center',
            display: 'block',
            marginTop: '12px'
          },
          svg: {
            fill: '#333',
            width: '24px',
            height: '24px',
            border: '1px transparent solid',
            borderRadius: '5px'
          }
        },
        'disableAlpha': {
          alpha: {
            display: 'none'
          }
        }
      }, this.props, this.state);

      var fields = void 0;
      if (this.state.view === 'hex') {
        fields = _react2.default.createElement(
          'div',
          { style: styles.fields, className: 'flexbox-fix' },
          _react2.default.createElement(
            'div',
            { style: styles.field },
            _react2.default.createElement(_common.EditableInput, {
              style: { input: styles.input, label: styles.label },
              label: 'hex', value: this.props.hex,
              onChange: this.handleChange
            })
          )
        );
      } else if (this.state.view === 'rgb') {
        fields = _react2.default.createElement(
          'div',
          { style: styles.fields, className: 'flexbox-fix' },
          _react2.default.createElement(
            'div',
            { style: styles.field },
            _react2.default.createElement(_common.EditableInput, {
              style: { input: styles.input, label: styles.label },
              label: 'r',
              value: this.props.rgb.r,
              onChange: this.handleChange
            })
          ),
          _react2.default.createElement(
            'div',
            { style: styles.field },
            _react2.default.createElement(_common.EditableInput, {
              style: { input: styles.input, label: styles.label },
              label: 'g',
              value: this.props.rgb.g,
              onChange: this.handleChange
            })
          ),
          _react2.default.createElement(
            'div',
            { style: styles.field },
            _react2.default.createElement(_common.EditableInput, {
              style: { input: styles.input, label: styles.label },
              label: 'b',
              value: this.props.rgb.b,
              onChange: this.handleChange
            })
          ),
          _react2.default.createElement(
            'div',
            { style: styles.alpha },
            _react2.default.createElement(_common.EditableInput, {
              style: { input: styles.input, label: styles.label },
              label: 'a',
              value: this.props.rgb.a,
              arrowOffset: 0.01,
              onChange: this.handleChange
            })
          )
        );
      } else if (this.state.view === 'hsl') {
        fields = _react2.default.createElement(
          'div',
          { style: styles.fields, className: 'flexbox-fix' },
          _react2.default.createElement(
            'div',
            { style: styles.field },
            _react2.default.createElement(_common.EditableInput, {
              style: { input: styles.input, label: styles.label },
              label: 'h',
              value: Math.round(this.props.hsl.h),
              onChange: this.handleChange
            })
          ),
          _react2.default.createElement(
            'div',
            { style: styles.field },
            _react2.default.createElement(_common.EditableInput, {
              style: { input: styles.input, label: styles.label },
              label: 's',
              value: Math.round(this.props.hsl.s * 100) + '%',
              onChange: this.handleChange
            })
          ),
          _react2.default.createElement(
            'div',
            { style: styles.field },
            _react2.default.createElement(_common.EditableInput, {
              style: { input: styles.input, label: styles.label },
              label: 'l',
              value: Math.round(this.props.hsl.l * 100) + '%',
              onChange: this.handleChange
            })
          ),
          _react2.default.createElement(
            'div',
            { style: styles.alpha },
            _react2.default.createElement(_common.EditableInput, {
              style: { input: styles.input, label: styles.label },
              label: 'a',
              value: this.props.hsl.a,
              arrowOffset: 0.01,
              onChange: this.handleChange
            })
          )
        );
      }

      return _react2.default.createElement(
        'div',
        { style: styles.wrap, className: 'flexbox-fix' },
        fields,
        _react2.default.createElement(
          'div',
          { style: styles.toggle },
          _react2.default.createElement(
            'div',
            { style: styles.icon, onClick: this.toggleViews, ref: function ref(icon) {
                return _this2.icon = icon;
              } },
            _react2.default.createElement(_UnfoldMoreHorizontalIcon2.default, {
              style: styles.svg,
              onMouseOver: this.showHighlight,
              onMouseEnter: this.showHighlight,
              onMouseOut: this.hideHighlight
            })
          )
        )
      );
    }
  }]);

  return ChromeFields;
}(_react2.default.Component);

exports.default = ChromeFields;

/***/ }),

/***/ "RlJB":
/*!*****************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/panel.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var panellayout_1 = __webpack_require__(/*! ./panellayout */ "HWBy");
var widget_1 = __webpack_require__(/*! ./widget */ "FmDU");
/**
 * A simple and convenient panel widget class.
 *
 * #### Notes
 * This class is suitable as a base class for implementing a variety of
 * convenience panel widgets, but can also be used directly with CSS to
 * arrange a collection of widgets.
 *
 * This class provides a convenience wrapper around a [[PanelLayout]].
 */
var Panel = (function (_super) {
    __extends(Panel, _super);
    /**
     * Construct a new panel.
     *
     * @param options - The options for initializing the panel.
     */
    function Panel(options) {
        if (options === void 0) { options = {}; }
        var _this = _super.call(this) || this;
        _this.addClass('p-Panel');
        _this.layout = Private.createLayout(options);
        return _this;
    }
    Object.defineProperty(Panel.prototype, "widgets", {
        /**
         * A read-only array of the widgets in the panel.
         */
        get: function () {
            return this.layout.widgets;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Add a widget to the end of the panel.
     *
     * @param widget - The widget to add to the panel.
     *
     * #### Notes
     * If the widget is already contained in the panel, it will be moved.
     */
    Panel.prototype.addWidget = function (widget) {
        this.layout.addWidget(widget);
    };
    /**
     * Insert a widget at the specified index.
     *
     * @param index - The index at which to insert the widget.
     *
     * @param widget - The widget to insert into to the panel.
     *
     * #### Notes
     * If the widget is already contained in the panel, it will be moved.
     */
    Panel.prototype.insertWidget = function (index, widget) {
        this.layout.insertWidget(index, widget);
    };
    return Panel;
}(widget_1.Widget));
exports.Panel = Panel;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * Create a panel layout for the given panel options.
     */
    function createLayout(options) {
        return options.layout || new panellayout_1.PanelLayout();
    }
    Private.createLayout = createLayout;
})(Private || (Private = {}));


/***/ }),

/***/ "RoA7":
/*!***********************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/parser.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _declaration = __webpack_require__(/*! ./declaration */ "dUwI");

var _declaration2 = _interopRequireDefault(_declaration);

var _tokenize = __webpack_require__(/*! ./tokenize */ "r2ia");

var _tokenize2 = _interopRequireDefault(_tokenize);

var _comment = __webpack_require__(/*! ./comment */ "aOxJ");

var _comment2 = _interopRequireDefault(_comment);

var _atRule = __webpack_require__(/*! ./at-rule */ "6z8e");

var _atRule2 = _interopRequireDefault(_atRule);

var _root = __webpack_require__(/*! ./root */ "sYGr");

var _root2 = _interopRequireDefault(_root);

var _rule = __webpack_require__(/*! ./rule */ "Cx5C");

var _rule2 = _interopRequireDefault(_rule);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Parser = function () {
    function Parser(input) {
        _classCallCheck(this, Parser);

        this.input = input;

        this.root = new _root2.default();
        this.current = this.root;
        this.spaces = '';
        this.semicolon = false;

        this.createTokenizer();
        this.root.source = { input: input, start: { line: 1, column: 1 } };
    }

    Parser.prototype.createTokenizer = function createTokenizer() {
        this.tokenizer = (0, _tokenize2.default)(this.input);
    };

    Parser.prototype.parse = function parse() {
        var token = void 0;
        while (!this.tokenizer.endOfFile()) {
            token = this.tokenizer.nextToken();

            switch (token[0]) {

                case 'space':
                    this.spaces += token[1];
                    break;

                case ';':
                    this.freeSemicolon(token);
                    break;

                case '}':
                    this.end(token);
                    break;

                case 'comment':
                    this.comment(token);
                    break;

                case 'at-word':
                    this.atrule(token);
                    break;

                case '{':
                    this.emptyRule(token);
                    break;

                default:
                    this.other(token);
                    break;
            }
        }
        this.endFile();
    };

    Parser.prototype.comment = function comment(token) {
        var node = new _comment2.default();
        this.init(node, token[2], token[3]);
        node.source.end = { line: token[4], column: token[5] };

        var text = token[1].slice(2, -2);
        if (/^\s*$/.test(text)) {
            node.text = '';
            node.raws.left = text;
            node.raws.right = '';
        } else {
            var match = text.match(/^(\s*)([^]*[^\s])(\s*)$/);
            node.text = match[2];
            node.raws.left = match[1];
            node.raws.right = match[3];
        }
    };

    Parser.prototype.emptyRule = function emptyRule(token) {
        var node = new _rule2.default();
        this.init(node, token[2], token[3]);
        node.selector = '';
        node.raws.between = '';
        this.current = node;
    };

    Parser.prototype.other = function other(start) {
        var end = false;
        var type = null;
        var colon = false;
        var bracket = null;
        var brackets = [];

        var tokens = [];
        var token = start;
        while (token) {
            type = token[0];
            tokens.push(token);

            if (type === '(' || type === '[') {
                if (!bracket) bracket = token;
                brackets.push(type === '(' ? ')' : ']');
            } else if (brackets.length === 0) {
                if (type === ';') {
                    if (colon) {
                        this.decl(tokens);
                        return;
                    } else {
                        break;
                    }
                } else if (type === '{') {
                    this.rule(tokens);
                    return;
                } else if (type === '}') {
                    this.tokenizer.back(tokens.pop());
                    end = true;
                    break;
                } else if (type === ':') {
                    colon = true;
                }
            } else if (type === brackets[brackets.length - 1]) {
                brackets.pop();
                if (brackets.length === 0) bracket = null;
            }

            token = this.tokenizer.nextToken();
        }

        if (this.tokenizer.endOfFile()) end = true;
        if (brackets.length > 0) this.unclosedBracket(bracket);

        if (end && colon) {
            while (tokens.length) {
                token = tokens[tokens.length - 1][0];
                if (token !== 'space' && token !== 'comment') break;
                this.tokenizer.back(tokens.pop());
            }
            this.decl(tokens);
            return;
        } else {
            this.unknownWord(tokens);
        }
    };

    Parser.prototype.rule = function rule(tokens) {
        tokens.pop();

        var node = new _rule2.default();
        this.init(node, tokens[0][2], tokens[0][3]);

        node.raws.between = this.spacesAndCommentsFromEnd(tokens);
        this.raw(node, 'selector', tokens);
        this.current = node;
    };

    Parser.prototype.decl = function decl(tokens) {
        var node = new _declaration2.default();
        this.init(node);

        var last = tokens[tokens.length - 1];
        if (last[0] === ';') {
            this.semicolon = true;
            tokens.pop();
        }
        if (last[4]) {
            node.source.end = { line: last[4], column: last[5] };
        } else {
            node.source.end = { line: last[2], column: last[3] };
        }

        while (tokens[0][0] !== 'word') {
            if (tokens.length === 1) this.unknownWord(tokens);
            node.raws.before += tokens.shift()[1];
        }
        node.source.start = { line: tokens[0][2], column: tokens[0][3] };

        node.prop = '';
        while (tokens.length) {
            var type = tokens[0][0];
            if (type === ':' || type === 'space' || type === 'comment') {
                break;
            }
            node.prop += tokens.shift()[1];
        }

        node.raws.between = '';

        var token = void 0;
        while (tokens.length) {
            token = tokens.shift();

            if (token[0] === ':') {
                node.raws.between += token[1];
                break;
            } else {
                node.raws.between += token[1];
            }
        }

        if (node.prop[0] === '_' || node.prop[0] === '*') {
            node.raws.before += node.prop[0];
            node.prop = node.prop.slice(1);
        }
        node.raws.between += this.spacesAndCommentsFromStart(tokens);
        this.precheckMissedSemicolon(tokens);

        for (var i = tokens.length - 1; i > 0; i--) {
            token = tokens[i];
            if (token[1].toLowerCase() === '!important') {
                node.important = true;
                var string = this.stringFrom(tokens, i);
                string = this.spacesFromEnd(tokens) + string;
                if (string !== ' !important') node.raws.important = string;
                break;
            } else if (token[1].toLowerCase() === 'important') {
                var cache = tokens.slice(0);
                var str = '';
                for (var j = i; j > 0; j--) {
                    var _type = cache[j][0];
                    if (str.trim().indexOf('!') === 0 && _type !== 'space') {
                        break;
                    }
                    str = cache.pop()[1] + str;
                }
                if (str.trim().indexOf('!') === 0) {
                    node.important = true;
                    node.raws.important = str;
                    tokens = cache;
                }
            }

            if (token[0] !== 'space' && token[0] !== 'comment') {
                break;
            }
        }

        this.raw(node, 'value', tokens);

        if (node.value.indexOf(':') !== -1) this.checkMissedSemicolon(tokens);
    };

    Parser.prototype.atrule = function atrule(token) {
        var node = new _atRule2.default();
        node.name = token[1].slice(1);
        if (node.name === '') {
            this.unnamedAtrule(node, token);
        }
        this.init(node, token[2], token[3]);

        var prev = void 0;
        var shift = void 0;
        var last = false;
        var open = false;
        var params = [];

        while (!this.tokenizer.endOfFile()) {
            token = this.tokenizer.nextToken();

            if (token[0] === ';') {
                node.source.end = { line: token[2], column: token[3] };
                this.semicolon = true;
                break;
            } else if (token[0] === '{') {
                open = true;
                break;
            } else if (token[0] === '}') {
                if (params.length > 0) {
                    shift = params.length - 1;
                    prev = params[shift];
                    while (prev && prev[0] === 'space') {
                        prev = params[--shift];
                    }
                    if (prev) {
                        node.source.end = { line: prev[4], column: prev[5] };
                    }
                }
                this.end(token);
                break;
            } else {
                params.push(token);
            }

            if (this.tokenizer.endOfFile()) {
                last = true;
                break;
            }
        }

        node.raws.between = this.spacesAndCommentsFromEnd(params);
        if (params.length) {
            node.raws.afterName = this.spacesAndCommentsFromStart(params);
            this.raw(node, 'params', params);
            if (last) {
                token = params[params.length - 1];
                node.source.end = { line: token[4], column: token[5] };
                this.spaces = node.raws.between;
                node.raws.between = '';
            }
        } else {
            node.raws.afterName = '';
            node.params = '';
        }

        if (open) {
            node.nodes = [];
            this.current = node;
        }
    };

    Parser.prototype.end = function end(token) {
        if (this.current.nodes && this.current.nodes.length) {
            this.current.raws.semicolon = this.semicolon;
        }
        this.semicolon = false;

        this.current.raws.after = (this.current.raws.after || '') + this.spaces;
        this.spaces = '';

        if (this.current.parent) {
            this.current.source.end = { line: token[2], column: token[3] };
            this.current = this.current.parent;
        } else {
            this.unexpectedClose(token);
        }
    };

    Parser.prototype.endFile = function endFile() {
        if (this.current.parent) this.unclosedBlock();
        if (this.current.nodes && this.current.nodes.length) {
            this.current.raws.semicolon = this.semicolon;
        }
        this.current.raws.after = (this.current.raws.after || '') + this.spaces;
    };

    Parser.prototype.freeSemicolon = function freeSemicolon(token) {
        this.spaces += token[1];
        if (this.current.nodes) {
            var prev = this.current.nodes[this.current.nodes.length - 1];
            if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) {
                prev.raws.ownSemicolon = this.spaces;
                this.spaces = '';
            }
        }
    };

    // Helpers

    Parser.prototype.init = function init(node, line, column) {
        this.current.push(node);

        node.source = { start: { line: line, column: column }, input: this.input };
        node.raws.before = this.spaces;
        this.spaces = '';
        if (node.type !== 'comment') this.semicolon = false;
    };

    Parser.prototype.raw = function raw(node, prop, tokens) {
        var token = void 0,
            type = void 0;
        var length = tokens.length;
        var value = '';
        var clean = true;
        var next = void 0,
            prev = void 0;
        var pattern = /^([.|#])?([\w])+/i;

        for (var i = 0; i < length; i += 1) {
            token = tokens[i];
            type = token[0];

            if (type === 'comment' && node.type === 'rule') {
                prev = tokens[i - 1];
                next = tokens[i + 1];

                if (prev[0] !== 'space' && next[0] !== 'space' && pattern.test(prev[1]) && pattern.test(next[1])) {
                    value += token[1];
                } else {
                    clean = false;
                }

                continue;
            }

            if (type === 'comment' || type === 'space' && i === length - 1) {
                clean = false;
            } else {
                value += token[1];
            }
        }
        if (!clean) {
            var raw = tokens.reduce(function (all, i) {
                return all + i[1];
            }, '');
            node.raws[prop] = { value: value, raw: raw };
        }
        node[prop] = value;
    };

    Parser.prototype.spacesAndCommentsFromEnd = function spacesAndCommentsFromEnd(tokens) {
        var lastTokenType = void 0;
        var spaces = '';
        while (tokens.length) {
            lastTokenType = tokens[tokens.length - 1][0];
            if (lastTokenType !== 'space' && lastTokenType !== 'comment') break;
            spaces = tokens.pop()[1] + spaces;
        }
        return spaces;
    };

    Parser.prototype.spacesAndCommentsFromStart = function spacesAndCommentsFromStart(tokens) {
        var next = void 0;
        var spaces = '';
        while (tokens.length) {
            next = tokens[0][0];
            if (next !== 'space' && next !== 'comment') break;
            spaces += tokens.shift()[1];
        }
        return spaces;
    };

    Parser.prototype.spacesFromEnd = function spacesFromEnd(tokens) {
        var lastTokenType = void 0;
        var spaces = '';
        while (tokens.length) {
            lastTokenType = tokens[tokens.length - 1][0];
            if (lastTokenType !== 'space') break;
            spaces = tokens.pop()[1] + spaces;
        }
        return spaces;
    };

    Parser.prototype.stringFrom = function stringFrom(tokens, from) {
        var result = '';
        for (var i = from; i < tokens.length; i++) {
            result += tokens[i][1];
        }
        tokens.splice(from, tokens.length - from);
        return result;
    };

    Parser.prototype.colon = function colon(tokens) {
        var brackets = 0;
        var token = void 0,
            type = void 0,
            prev = void 0;
        for (var i = 0; i < tokens.length; i++) {
            token = tokens[i];
            type = token[0];

            if (type === '(') {
                brackets += 1;
            } else if (type === ')') {
                brackets -= 1;
            } else if (brackets === 0 && type === ':') {
                if (!prev) {
                    this.doubleColon(token);
                } else if (prev[0] === 'word' && prev[1] === 'progid') {
                    continue;
                } else {
                    return i;
                }
            }

            prev = token;
        }
        return false;
    };

    // Errors

    Parser.prototype.unclosedBracket = function unclosedBracket(bracket) {
        throw this.input.error('Unclosed bracket', bracket[2], bracket[3]);
    };

    Parser.prototype.unknownWord = function unknownWord(tokens) {
        throw this.input.error('Unknown word', tokens[0][2], tokens[0][3]);
    };

    Parser.prototype.unexpectedClose = function unexpectedClose(token) {
        throw this.input.error('Unexpected }', token[2], token[3]);
    };

    Parser.prototype.unclosedBlock = function unclosedBlock() {
        var pos = this.current.source.start;
        throw this.input.error('Unclosed block', pos.line, pos.column);
    };

    Parser.prototype.doubleColon = function doubleColon(token) {
        throw this.input.error('Double colon', token[2], token[3]);
    };

    Parser.prototype.unnamedAtrule = function unnamedAtrule(node, token) {
        throw this.input.error('At-rule without name', token[2], token[3]);
    };

    Parser.prototype.precheckMissedSemicolon = function precheckMissedSemicolon(tokens) {
        // Hook for Safe Parser
        tokens;
    };

    Parser.prototype.checkMissedSemicolon = function checkMissedSemicolon(tokens) {
        var colon = this.colon(tokens);
        if (colon === false) return;

        var founded = 0;
        var token = void 0;
        for (var j = colon - 1; j >= 0; j--) {
            token = tokens[j];
            if (token[0] !== 'space') {
                founded += 1;
                if (founded === 2) break;
            }
        }
        throw this.input.error('Missed semicolon', token[2], token[3]);
    };

    return Parser;
}();

exports.default = Parser;
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64, 


/***/ }),

/***/ "RoFp":
/*!**********************************************************************!*\
  !*** ./node_modules/readable-stream/lib/internal/streams/destroy.js ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/*<replacement>*/

var pna = __webpack_require__(/*! process-nextick-args */ "lm0R");
/*</replacement>*/

// undocumented cb() API, needed for core, not for public API
function destroy(err, cb) {
  var _this = this;

  var readableDestroyed = this._readableState && this._readableState.destroyed;
  var writableDestroyed = this._writableState && this._writableState.destroyed;

  if (readableDestroyed || writableDestroyed) {
    if (cb) {
      cb(err);
    } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
      pna.nextTick(emitErrorNT, this, err);
    }
    return this;
  }

  // we set destroyed to true before firing error callbacks in order
  // to make it re-entrance safe in case destroy() is called within callbacks

  if (this._readableState) {
    this._readableState.destroyed = true;
  }

  // if this is a duplex stream mark the writable part as destroyed as well
  if (this._writableState) {
    this._writableState.destroyed = true;
  }

  this._destroy(err || null, function (err) {
    if (!cb && err) {
      pna.nextTick(emitErrorNT, _this, err);
      if (_this._writableState) {
        _this._writableState.errorEmitted = true;
      }
    } else if (cb) {
      cb(err);
    }
  });

  return this;
}

function undestroy() {
  if (this._readableState) {
    this._readableState.destroyed = false;
    this._readableState.reading = false;
    this._readableState.ended = false;
    this._readableState.endEmitted = false;
  }

  if (this._writableState) {
    this._writableState.destroyed = false;
    this._writableState.ended = false;
    this._writableState.ending = false;
    this._writableState.finished = false;
    this._writableState.errorEmitted = false;
  }
}

function emitErrorNT(self, err) {
  self.emit('error', err);
}

module.exports = {
  destroy: destroy,
  undestroy: undestroy
};

/***/ }),

/***/ "Rp86":
/*!*********************************************************!*\
  !*** ./node_modules/core-js/library/fn/get-iterator.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(/*! ../modules/web.dom.iterable */ "bBy9");
__webpack_require__(/*! ../modules/es6.string.iterator */ "FlQf");
module.exports = __webpack_require__(/*! ../modules/core.get-iterator */ "fXsU");


/***/ }),

/***/ "RsOY":
/*!***************************************************!*\
  !*** ./node_modules/immutability-helper/index.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var invariant = __webpack_require__(/*! invariant */ "QLaP");

var hasOwnProperty = Object.prototype.hasOwnProperty;
var splice = Array.prototype.splice;

var toString = Object.prototype.toString
var type = function(obj) {
  return toString.call(obj).slice(8, -1);
}

var assign = Object.assign || /* istanbul ignore next */ function assign(target, source) {
  getAllKeys(source).forEach(function(key) {
    if (hasOwnProperty.call(source, key)) {
      target[key] = source[key];
    }
  });
  return target;
};

var getAllKeys = typeof Object.getOwnPropertySymbols === 'function' ?
  function(obj) { return Object.keys(obj).concat(Object.getOwnPropertySymbols(obj)) } :
  /* istanbul ignore next */ function(obj) { return Object.keys(obj) };

/* istanbul ignore next */
function copy(object) {
  if (Array.isArray(object)) {
    return assign(object.constructor(object.length), object)
  } else if (type(object) === 'Map') {
    return new Map(object)
  } else if (type(object) === 'Set') {
    return new Set(object)
  } else if (object && typeof object === 'object') {
    var prototype = Object.getPrototypeOf(object);
    return assign(Object.create(prototype), object);
  } else {
    return object;
  }
}

function newContext() {
  var commands = assign({}, defaultCommands);
  update.extend = function(directive, fn) {
    commands[directive] = fn;
  };
  update.isEquals = function(a, b) { return a === b; };

  return update;

  function update(object, spec) {
    if (typeof spec === 'function') {
      spec = { $apply: spec };
    }

    if (!(Array.isArray(object) && Array.isArray(spec))) {
      invariant(
        !Array.isArray(spec),
        'update(): You provided an invalid spec to update(). The spec may ' +
        'not contain an array except as the value of $set, $push, $unshift, ' +
        '$splice or any custom command allowing an array value.'
      );
    }

    invariant(
      typeof spec === 'object' && spec !== null,
      'update(): You provided an invalid spec to update(). The spec and ' +
      'every included key path must be plain objects containing one of the ' +
      'following commands: %s.',
      Object.keys(commands).join(', ')
    );

    var nextObject = object;
    var index, key;
    getAllKeys(spec).forEach(function(key) {
      if (hasOwnProperty.call(commands, key)) {
        var objectWasNextObject = object === nextObject;
        nextObject = commands[key](spec[key], nextObject, spec, object);
        if (objectWasNextObject && update.isEquals(nextObject, object)) {
          nextObject = object;
        }
      } else {
        var nextValueForKey =
          type(object) === 'Map'
            ? update(object.get(key), spec[key])
            : update(object[key], spec[key]);
        var nextObjectValue =
          type(nextObject) === 'Map'
              ? nextObject.get(key)
              : nextObject[key];
        if (!update.isEquals(nextValueForKey, nextObjectValue) || typeof nextValueForKey === 'undefined' && !hasOwnProperty.call(object, key)) {
          if (nextObject === object) {
            nextObject = copy(object);
          }
          if (type(nextObject) === 'Map') {
            nextObject.set(key, nextValueForKey);
          } else {
            nextObject[key] = nextValueForKey;
          }
        }
      }
    })
    return nextObject;
  }

}

var defaultCommands = {
  $push: function(value, nextObject, spec) {
    invariantPushAndUnshift(nextObject, spec, '$push');
    return value.length ? nextObject.concat(value) : nextObject;
  },
  $unshift: function(value, nextObject, spec) {
    invariantPushAndUnshift(nextObject, spec, '$unshift');
    return value.length ? value.concat(nextObject) : nextObject;
  },
  $splice: function(value, nextObject, spec, originalObject) {
    invariantSplices(nextObject, spec);
    value.forEach(function(args) {
      invariantSplice(args);
      if (nextObject === originalObject && args.length) nextObject = copy(originalObject);
      splice.apply(nextObject, args);
    });
    return nextObject;
  },
  $set: function(value, nextObject, spec) {
    invariantSet(spec);
    return value;
  },
  $toggle: function(targets, nextObject) {
    invariantSpecArray(targets, '$toggle');
    var nextObjectCopy = targets.length ? copy(nextObject) : nextObject;

    targets.forEach(function(target) {
      nextObjectCopy[target] = !nextObject[target];
    });

    return nextObjectCopy;
  },
  $unset: function(value, nextObject, spec, originalObject) {
    invariantSpecArray(value, '$unset');
    value.forEach(function(key) {
      if (Object.hasOwnProperty.call(nextObject, key)) {
        if (nextObject === originalObject) nextObject = copy(originalObject);
        delete nextObject[key];
      }
    });
    return nextObject;
  },
  $add: function(value, nextObject, spec, originalObject) {
    invariantMapOrSet(nextObject, '$add');
    invariantSpecArray(value, '$add');
    if (type(nextObject) === 'Map') {
      value.forEach(function(pair) {
        var key = pair[0];
        var value = pair[1];
        if (nextObject === originalObject && nextObject.get(key) !== value) nextObject = copy(originalObject);
        nextObject.set(key, value);
      });
    } else {
      value.forEach(function(value) {
        if (nextObject === originalObject && !nextObject.has(value)) nextObject = copy(originalObject);
        nextObject.add(value);
      });
    }
    return nextObject;
  },
  $remove: function(value, nextObject, spec, originalObject) {
    invariantMapOrSet(nextObject, '$remove');
    invariantSpecArray(value, '$remove');
    value.forEach(function(key) {
      if (nextObject === originalObject && nextObject.has(key)) nextObject = copy(originalObject);
      nextObject.delete(key);
    });
    return nextObject;
  },
  $merge: function(value, nextObject, spec, originalObject) {
    invariantMerge(nextObject, value);
    getAllKeys(value).forEach(function(key) {
      if (value[key] !== nextObject[key]) {
        if (nextObject === originalObject) nextObject = copy(originalObject);
        nextObject[key] = value[key];
      }
    });
    return nextObject;
  },
  $apply: function(value, original) {
    invariantApply(value);
    return value(original);
  }
};

var contextForExport = newContext();

module.exports = contextForExport;
module.exports.default = contextForExport;
module.exports.newContext = newContext;

// invariants

function invariantPushAndUnshift(value, spec, command) {
  invariant(
    Array.isArray(value),
    'update(): expected target of %s to be an array; got %s.',
    command,
    value
  );
  invariantSpecArray(spec[command], command)
}

function invariantSpecArray(spec, command) {
  invariant(
    Array.isArray(spec),
    'update(): expected spec of %s to be an array; got %s. ' +
    'Did you forget to wrap your parameter in an array?',
    command,
    spec
  );
}

function invariantSplices(value, spec) {
  invariant(
    Array.isArray(value),
    'Expected $splice target to be an array; got %s',
    value
  );
  invariantSplice(spec['$splice']);
}

function invariantSplice(value) {
  invariant(
    Array.isArray(value),
    'update(): expected spec of $splice to be an array of arrays; got %s. ' +
    'Did you forget to wrap your parameters in an array?',
    value
  );
}

function invariantApply(fn) {
  invariant(
    typeof fn === 'function',
    'update(): expected spec of $apply to be a function; got %s.',
    fn
  );
}

function invariantSet(spec) {
  invariant(
    Object.keys(spec).length === 1,
    'Cannot have more than one key in an object with $set'
  );
}

function invariantMerge(target, specValue) {
  invariant(
    specValue && typeof specValue === 'object',
    'update(): $merge expects a spec of type \'object\'; got %s',
    specValue
  );
  invariant(
    target && typeof target === 'object',
    'update(): $merge expects a target of type \'object\'; got %s',
    target
  );
}

function invariantMapOrSet(target, command) {
  var typeOfTarget = type(target);
  invariant(
    typeOfTarget === 'Map' || typeOfTarget === 'Set',
    'update(): %s expects a target of type Set or Map; got %s',
    command,
    typeOfTarget
  );
}


/***/ }),

/***/ "Rsun":
/*!********************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/jupyterlab-dash/style/index.css ***!
  \********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, ".jp-dashWidget iframe {\n  height: 100%;\n  width: 100%;\n  padding: 20px;\n  box-sizing: border-box;\n}\n", ""]);

// exports


/***/ }),

/***/ "Rtm6":
/*!*********************************************************!*\
  !*** ./node_modules/@jupyter-widgets/base/lib/index.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(__webpack_require__(/*! ./manager-base */ "hs2k"));
__export(__webpack_require__(/*! ./widget */ "rynU"));
__export(__webpack_require__(/*! ./widget_layout */ "qcc5"));
__export(__webpack_require__(/*! ./widget_style */ "EW15"));
__export(__webpack_require__(/*! ./services-shim */ "ZD1G"));
__export(__webpack_require__(/*! ./viewlist */ "bU+Y"));
__export(__webpack_require__(/*! ./version */ "tLa0"));
__export(__webpack_require__(/*! ./utils */ "o9P/"));
__export(__webpack_require__(/*! ./registry */ "RHWC"));


/***/ }),

/***/ "Ruvy":
/*!********************************************************************!*\
  !*** ./node_modules/@jupyterlab/theme-dark-extension/lib/index.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
/**
 * A plugin for the Jupyter Dark Theme.
 */
const plugin = {
    id: '@jupyterlab/theme-dark-extension:plugin',
    requires: [apputils_1.IThemeManager],
    activate: (app, manager) => {
        const style = '@jupyterlab/theme-dark-extension/index.css';
        manager.register({
            name: 'JupyterLab Dark',
            isLight: false,
            load: () => manager.loadCSS(style),
            unload: () => Promise.resolve(undefined)
        });
    },
    autoStart: true
};
exports.default = plugin;


/***/ }),

/***/ "RvMh":
/*!*********************************************************!*\
  !*** ./node_modules/@jupyterlab/completer/lib/index.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
__webpack_require__(/*! ../style/index.css */ "zzB/");
__export(__webpack_require__(/*! ./handler */ "zgGE"));
__export(__webpack_require__(/*! ./kernelconnector */ "k8wc"));
__export(__webpack_require__(/*! ./contextconnector */ "wLZx"));
__export(__webpack_require__(/*! ./connector */ "2ObX"));
__export(__webpack_require__(/*! ./model */ "MNtL"));
__export(__webpack_require__(/*! ./widget */ "7VUJ"));
/* tslint:disable */
/**
 * The completion manager token.
 */
exports.ICompletionManager = new coreutils_1.Token('@jupyterlab/completer:ICompletionManager');


/***/ }),

/***/ "Rva2":
/*!*************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@phosphor/widgets/style/tabpanel.css ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\r\n| Copyright (c) 2014-2017, PhosphorJS Contributors\r\n|\r\n| Distributed under the terms of the BSD 3-Clause License.\r\n|\r\n| The full license is in the file LICENSE, distributed with this software.\r\n|----------------------------------------------------------------------------*/\r\n\r\n\r\n.p-TabPanel-tabBar {\r\n  z-index: 1;\r\n}\r\n\r\n\r\n.p-TabPanel-stackedPanel {\r\n  z-index: 0;\r\n}\r\n", ""]);

// exports


/***/ }),

/***/ "S/4p":
/*!*********************************************************************!*\
  !*** ./node_modules/@jupyterlab/launcher-extension/style/index.css ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "sYhS");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "S09q":
/*!********************************************************************!*\
  !*** ./node_modules/@jupyterlab/codemirror-extension/lib/index.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const codemirror_1 = __importDefault(__webpack_require__(/*! codemirror */ "VrN/"));
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const mainmenu_1 = __webpack_require__(/*! @jupyterlab/mainmenu */ "N4Qf");
const codeeditor_1 = __webpack_require__(/*! @jupyterlab/codeeditor */ "sLCx");
const codemirror_2 = __webpack_require__(/*! @jupyterlab/codemirror */ "ddNL");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const fileeditor_1 = __webpack_require__(/*! @jupyterlab/fileeditor */ "RHTn");
/**
 * The command IDs used by the codemirror plugin.
 */
var CommandIDs;
(function (CommandIDs) {
    CommandIDs.changeKeyMap = 'codemirror:change-keymap';
    CommandIDs.changeTheme = 'codemirror:change-theme';
    CommandIDs.changeMode = 'codemirror:change-mode';
    CommandIDs.find = 'codemirror:find';
    CommandIDs.findAndReplace = 'codemirror:find-and-replace';
    CommandIDs.goToLine = 'codemirror:go-to-line';
})(CommandIDs || (CommandIDs = {}));
/**
 * The editor services.
 */
const services = {
    id: '@jupyterlab/codemirror-extension:services',
    provides: codeeditor_1.IEditorServices,
    activate: activateEditorServices
};
/**
 * The editor commands.
 */
const commands = {
    id: '@jupyterlab/codemirror-extension:commands',
    requires: [fileeditor_1.IEditorTracker, mainmenu_1.IMainMenu, coreutils_1.IStateDB, coreutils_1.ISettingRegistry],
    activate: activateEditorCommands,
    autoStart: true
};
/**
 * Export the plugins as default.
 */
const plugins = [commands, services];
exports.default = plugins;
/**
 * The plugin ID used as the key in the setting registry.
 */
const id = commands.id;
/**
 * Set up the editor services.
 */
function activateEditorServices(app) {
    codemirror_1.default.prototype.save = () => {
        app.commands.execute('docmanager:save');
    };
    return codemirror_2.editorServices;
}
/**
 * Set up the editor widget menu and commands.
 */
function activateEditorCommands(app, tracker, mainMenu, state, settingRegistry) {
    const { commands, restored } = app;
    let { theme, keyMap } = codemirror_2.CodeMirrorEditor.defaultConfig;
    /**
     * Update the setting values.
     */
    function updateSettings(settings) {
        keyMap = settings.get('keyMap').composite || keyMap;
        theme = settings.get('theme').composite || theme;
    }
    /**
     * Update the settings of the current tracker instances.
     */
    function updateTracker() {
        tracker.forEach(widget => {
            if (widget.content.editor instanceof codemirror_2.CodeMirrorEditor) {
                let cm = widget.content.editor.editor;
                cm.setOption('keyMap', keyMap);
                cm.setOption('theme', theme);
            }
        });
    }
    // Fetch the initial state of the settings.
    Promise.all([settingRegistry.load(id), restored])
        .then(([settings]) => {
        updateSettings(settings);
        updateTracker();
        settings.changed.connect(() => {
            updateSettings(settings);
            updateTracker();
        });
    })
        .catch((reason) => {
        console.error(reason.message);
        updateTracker();
    });
    /**
     * Handle the settings of new widgets.
     */
    tracker.widgetAdded.connect((sender, widget) => {
        if (widget.content.editor instanceof codemirror_2.CodeMirrorEditor) {
            let cm = widget.content.editor.editor;
            cm.setOption('keyMap', keyMap);
            cm.setOption('theme', theme);
        }
    });
    /**
     * A test for whether the tracker has an active widget.
     */
    function isEnabled() {
        return (tracker.currentWidget !== null &&
            tracker.currentWidget === app.shell.currentWidget);
    }
    /**
     * Create a menu for the editor.
     */
    const themeMenu = new widgets_1.Menu({ commands });
    const keyMapMenu = new widgets_1.Menu({ commands });
    const modeMenu = new widgets_1.Menu({ commands });
    themeMenu.title.label = 'Text Editor Theme';
    keyMapMenu.title.label = 'Text Editor Key Map';
    modeMenu.title.label = 'Text Editor Syntax Highlighting';
    commands.addCommand(CommandIDs.changeTheme, {
        label: args => args['theme'],
        execute: args => {
            const key = 'theme';
            const value = (theme = args['theme'] || theme);
            updateTracker();
            return settingRegistry.set(id, key, value).catch((reason) => {
                console.error(`Failed to set ${id}:${key} - ${reason.message}`);
            });
        },
        isToggled: args => args['theme'] === theme
    });
    commands.addCommand(CommandIDs.changeKeyMap, {
        label: args => {
            let title = args['keyMap'];
            return title === 'sublime' ? 'Sublime Text' : title;
        },
        execute: args => {
            const key = 'keyMap';
            const value = (keyMap = args['keyMap'] || keyMap);
            updateTracker();
            return settingRegistry.set(id, key, value).catch((reason) => {
                console.error(`Failed to set ${id}:${key} - ${reason.message}`);
            });
        },
        isToggled: args => args['keyMap'] === keyMap
    });
    commands.addCommand(CommandIDs.find, {
        label: 'Find...',
        execute: () => {
            let widget = tracker.currentWidget;
            if (!widget) {
                return;
            }
            let editor = widget.content.editor;
            editor.execCommand('find');
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.findAndReplace, {
        label: 'Find and Replace...',
        execute: () => {
            let widget = tracker.currentWidget;
            if (!widget) {
                return;
            }
            let editor = widget.content.editor;
            editor.execCommand('replace');
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.goToLine, {
        label: 'Go to Line...',
        execute: () => {
            let widget = tracker.currentWidget;
            if (!widget) {
                return;
            }
            let editor = widget.content.editor;
            editor.execCommand('jumpToLine');
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.changeMode, {
        label: args => args['name'],
        execute: args => {
            let name = args['name'];
            let widget = tracker.currentWidget;
            if (name && widget) {
                let spec = codemirror_2.Mode.findByName(name);
                if (spec) {
                    widget.content.model.mimeType = spec.mime;
                }
            }
        },
        isEnabled,
        isToggled: args => {
            let widget = tracker.currentWidget;
            if (!widget) {
                return false;
            }
            let mime = widget.content.model.mimeType;
            let spec = codemirror_2.Mode.findByMIME(mime);
            let name = spec && spec.name;
            return args['name'] === name;
        }
    });
    codemirror_2.Mode.getModeInfo()
        .sort((a, b) => {
        let aName = a.name || '';
        let bName = b.name || '';
        return aName.localeCompare(bName);
    })
        .forEach(spec => {
        // Avoid mode name with a curse word.
        if (spec.mode.indexOf('brainf') === 0) {
            return;
        }
        modeMenu.addItem({
            command: CommandIDs.changeMode,
            args: Object.assign({}, spec)
        });
    });
    [
        'jupyter',
        'default',
        'abcdef',
        'base16-dark',
        'base16-light',
        'hopscotch',
        'material',
        'mbo',
        'mdn-like',
        'seti',
        'solarized dark',
        'solarized light',
        'the-matrix',
        'xq-light',
        'zenburn'
    ].forEach(name => themeMenu.addItem({
        command: CommandIDs.changeTheme,
        args: { theme: name }
    }));
    ['default', 'sublime', 'vim', 'emacs'].forEach(name => {
        keyMapMenu.addItem({
            command: CommandIDs.changeKeyMap,
            args: { keyMap: name }
        });
    });
    // Add some of the editor settings to the settings menu.
    mainMenu.settingsMenu.addGroup([
        { type: 'submenu', submenu: keyMapMenu },
        { type: 'submenu', submenu: themeMenu }
    ], 10);
    // Add the syntax highlighting submenu to the `View` menu.
    mainMenu.viewMenu.addGroup([{ type: 'submenu', submenu: modeMenu }], 40);
    // Add find-replace capabilities to the edit menu.
    mainMenu.editMenu.findReplacers.add({
        tracker,
        find: (widget) => {
            let editor = widget.content.editor;
            editor.execCommand('find');
        },
        findAndReplace: (widget) => {
            let editor = widget.content.editor;
            editor.execCommand('replace');
        }
    });
    // Add go to line capabilities to the edit menu.
    mainMenu.editMenu.goToLiners.add({
        tracker,
        find: (widget) => {
            let editor = widget.content.editor;
            editor.execCommand('jumpToLine');
        },
        goToLine: (widget) => {
            let editor = widget.content.editor;
            editor.execCommand('jumpToLine');
        }
    });
}


/***/ }),

/***/ "S5bm":
/*!***************************************************!*\
  !*** ./node_modules/fbjs/lib/getStyleProperty.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks
 */

var camelize = __webpack_require__(/*! ./camelize */ "NgHg");
var hyphenate = __webpack_require__(/*! ./hyphenate */ "+aGp");

function asString(value) /*?string*/{
  return value == null ? value : String(value);
}

function getStyleProperty( /*DOMNode*/node, /*string*/name) /*?string*/{
  var computedStyle = void 0;

  // W3C Standard
  if (window.getComputedStyle) {
    // In certain cases such as within an iframe in FF3, this returns null.
    computedStyle = window.getComputedStyle(node, null);
    if (computedStyle) {
      return asString(computedStyle.getPropertyValue(hyphenate(name)));
    }
  }
  // Safari
  if (document.defaultView && document.defaultView.getComputedStyle) {
    computedStyle = document.defaultView.getComputedStyle(node, null);
    // A Safari bug causes this to return null for `display: none` elements.
    if (computedStyle) {
      return asString(computedStyle.getPropertyValue(hyphenate(name)));
    }
    if (name === 'display') {
      return 'none';
    }
  }
  // Internet Explorer
  if (node.currentStyle) {
    if (name === 'float') {
      return asString(node.currentStyle.cssFloat || node.currentStyle.styleFloat);
    }
    return asString(node.currentStyle[camelize(name)]);
  }
  return asString(node.style && node.style[camelize(name)]);
}

module.exports = getStyleProperty;

/***/ }),

/***/ "S6bl":
/*!*****************************************************!*\
  !*** ./node_modules/codemirror/mode/clike/clike.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"));
  else {}
})(function(CodeMirror) {
"use strict";

function Context(indented, column, type, info, align, prev) {
  this.indented = indented;
  this.column = column;
  this.type = type;
  this.info = info;
  this.align = align;
  this.prev = prev;
}
function pushContext(state, col, type, info) {
  var indent = state.indented;
  if (state.context && state.context.type == "statement" && type != "statement")
    indent = state.context.indented;
  return state.context = new Context(indent, col, type, info, null, state.context);
}
function popContext(state) {
  var t = state.context.type;
  if (t == ")" || t == "]" || t == "}")
    state.indented = state.context.indented;
  return state.context = state.context.prev;
}

function typeBefore(stream, state, pos) {
  if (state.prevToken == "variable" || state.prevToken == "type") return true;
  if (/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(stream.string.slice(0, pos))) return true;
  if (state.typeAtEndOfLine && stream.column() == stream.indentation()) return true;
}

function isTopScope(context) {
  for (;;) {
    if (!context || context.type == "top") return true;
    if (context.type == "}" && context.prev.info != "namespace") return false;
    context = context.prev;
  }
}

CodeMirror.defineMode("clike", function(config, parserConfig) {
  var indentUnit = config.indentUnit,
      statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,
      dontAlignCalls = parserConfig.dontAlignCalls,
      keywords = parserConfig.keywords || {},
      types = parserConfig.types || {},
      builtin = parserConfig.builtin || {},
      blockKeywords = parserConfig.blockKeywords || {},
      defKeywords = parserConfig.defKeywords || {},
      atoms = parserConfig.atoms || {},
      hooks = parserConfig.hooks || {},
      multiLineStrings = parserConfig.multiLineStrings,
      indentStatements = parserConfig.indentStatements !== false,
      indentSwitch = parserConfig.indentSwitch !== false,
      namespaceSeparator = parserConfig.namespaceSeparator,
      isPunctuationChar = parserConfig.isPunctuationChar || /[\[\]{}\(\),;\:\.]/,
      numberStart = parserConfig.numberStart || /[\d\.]/,
      number = parserConfig.number || /^(?:0x[a-f\d]+|0b[01]+|(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)(u|ll?|l|f)?/i,
      isOperatorChar = parserConfig.isOperatorChar || /[+\-*&%=<>!?|\/]/,
      isIdentifierChar = parserConfig.isIdentifierChar || /[\w\$_\xa1-\uffff]/;

  var curPunc, isDefKeyword;

  function tokenBase(stream, state) {
    var ch = stream.next();
    if (hooks[ch]) {
      var result = hooks[ch](stream, state);
      if (result !== false) return result;
    }
    if (ch == '"' || ch == "'") {
      state.tokenize = tokenString(ch);
      return state.tokenize(stream, state);
    }
    if (isPunctuationChar.test(ch)) {
      curPunc = ch;
      return null;
    }
    if (numberStart.test(ch)) {
      stream.backUp(1)
      if (stream.match(number)) return "number"
      stream.next()
    }
    if (ch == "/") {
      if (stream.eat("*")) {
        state.tokenize = tokenComment;
        return tokenComment(stream, state);
      }
      if (stream.eat("/")) {
        stream.skipToEnd();
        return "comment";
      }
    }
    if (isOperatorChar.test(ch)) {
      while (!stream.match(/^\/[\/*]/, false) && stream.eat(isOperatorChar)) {}
      return "operator";
    }
    stream.eatWhile(isIdentifierChar);
    if (namespaceSeparator) while (stream.match(namespaceSeparator))
      stream.eatWhile(isIdentifierChar);

    var cur = stream.current();
    if (contains(keywords, cur)) {
      if (contains(blockKeywords, cur)) curPunc = "newstatement";
      if (contains(defKeywords, cur)) isDefKeyword = true;
      return "keyword";
    }
    if (contains(types, cur)) return "type";
    if (contains(builtin, cur)) {
      if (contains(blockKeywords, cur)) curPunc = "newstatement";
      return "builtin";
    }
    if (contains(atoms, cur)) return "atom";
    return "variable";
  }

  function tokenString(quote) {
    return function(stream, state) {
      var escaped = false, next, end = false;
      while ((next = stream.next()) != null) {
        if (next == quote && !escaped) {end = true; break;}
        escaped = !escaped && next == "\\";
      }
      if (end || !(escaped || multiLineStrings))
        state.tokenize = null;
      return "string";
    };
  }

  function tokenComment(stream, state) {
    var maybeEnd = false, ch;
    while (ch = stream.next()) {
      if (ch == "/" && maybeEnd) {
        state.tokenize = null;
        break;
      }
      maybeEnd = (ch == "*");
    }
    return "comment";
  }

  function maybeEOL(stream, state) {
    if (parserConfig.typeFirstDefinitions && stream.eol() && isTopScope(state.context))
      state.typeAtEndOfLine = typeBefore(stream, state, stream.pos)
  }

  // Interface

  return {
    startState: function(basecolumn) {
      return {
        tokenize: null,
        context: new Context((basecolumn || 0) - indentUnit, 0, "top", null, false),
        indented: 0,
        startOfLine: true,
        prevToken: null
      };
    },

    token: function(stream, state) {
      var ctx = state.context;
      if (stream.sol()) {
        if (ctx.align == null) ctx.align = false;
        state.indented = stream.indentation();
        state.startOfLine = true;
      }
      if (stream.eatSpace()) { maybeEOL(stream, state); return null; }
      curPunc = isDefKeyword = null;
      var style = (state.tokenize || tokenBase)(stream, state);
      if (style == "comment" || style == "meta") return style;
      if (ctx.align == null) ctx.align = true;

      if (curPunc == ";" || curPunc == ":" || (curPunc == "," && stream.match(/^\s*(?:\/\/.*)?$/, false)))
        while (state.context.type == "statement") popContext(state);
      else if (curPunc == "{") pushContext(state, stream.column(), "}");
      else if (curPunc == "[") pushContext(state, stream.column(), "]");
      else if (curPunc == "(") pushContext(state, stream.column(), ")");
      else if (curPunc == "}") {
        while (ctx.type == "statement") ctx = popContext(state);
        if (ctx.type == "}") ctx = popContext(state);
        while (ctx.type == "statement") ctx = popContext(state);
      }
      else if (curPunc == ctx.type) popContext(state);
      else if (indentStatements &&
               (((ctx.type == "}" || ctx.type == "top") && curPunc != ";") ||
                (ctx.type == "statement" && curPunc == "newstatement"))) {
        pushContext(state, stream.column(), "statement", stream.current());
      }

      if (style == "variable" &&
          ((state.prevToken == "def" ||
            (parserConfig.typeFirstDefinitions && typeBefore(stream, state, stream.start) &&
             isTopScope(state.context) && stream.match(/^\s*\(/, false)))))
        style = "def";

      if (hooks.token) {
        var result = hooks.token(stream, state, style);
        if (result !== undefined) style = result;
      }

      if (style == "def" && parserConfig.styleDefs === false) style = "variable";

      state.startOfLine = false;
      state.prevToken = isDefKeyword ? "def" : style || curPunc;
      maybeEOL(stream, state);
      return style;
    },

    indent: function(state, textAfter) {
      if (state.tokenize != tokenBase && state.tokenize != null || state.typeAtEndOfLine) return CodeMirror.Pass;
      var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
      var closing = firstChar == ctx.type;
      if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
      if (parserConfig.dontIndentStatements)
        while (ctx.type == "statement" && parserConfig.dontIndentStatements.test(ctx.info))
          ctx = ctx.prev
      if (hooks.indent) {
        var hook = hooks.indent(state, ctx, textAfter, indentUnit);
        if (typeof hook == "number") return hook
      }
      var switchBlock = ctx.prev && ctx.prev.info == "switch";
      if (parserConfig.allmanIndentation && /[{(]/.test(firstChar)) {
        while (ctx.type != "top" && ctx.type != "}") ctx = ctx.prev
        return ctx.indented
      }
      if (ctx.type == "statement")
        return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
      if (ctx.align && (!dontAlignCalls || ctx.type != ")"))
        return ctx.column + (closing ? 0 : 1);
      if (ctx.type == ")" && !closing)
        return ctx.indented + statementIndentUnit;

      return ctx.indented + (closing ? 0 : indentUnit) +
        (!closing && switchBlock && !/^(?:case|default)\b/.test(textAfter) ? indentUnit : 0);
    },

    electricInput: indentSwitch ? /^\s*(?:case .*?:|default:|\{\}?|\})$/ : /^\s*[{}]$/,
    blockCommentStart: "/*",
    blockCommentEnd: "*/",
    blockCommentContinue: " * ",
    lineComment: "//",
    fold: "brace"
  };
});

  function words(str) {
    var obj = {}, words = str.split(" ");
    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
    return obj;
  }
  function contains(words, word) {
    if (typeof words === "function") {
      return words(word);
    } else {
      return words.propertyIsEnumerable(word);
    }
  }
  var cKeywords = "auto if break case register continue return default do sizeof " +
    "static else struct switch extern typedef union for goto while enum const volatile";
  var cTypes = "int long char short double float unsigned signed void size_t ptrdiff_t";

  function cppHook(stream, state) {
    if (!state.startOfLine) return false
    for (var ch, next = null; ch = stream.peek();) {
      if (ch == "\\" && stream.match(/^.$/)) {
        next = cppHook
        break
      } else if (ch == "/" && stream.match(/^\/[\/\*]/, false)) {
        break
      }
      stream.next()
    }
    state.tokenize = next
    return "meta"
  }

  function pointerHook(_stream, state) {
    if (state.prevToken == "type") return "type";
    return false;
  }

  function cpp14Literal(stream) {
    stream.eatWhile(/[\w\.']/);
    return "number";
  }

  function cpp11StringHook(stream, state) {
    stream.backUp(1);
    // Raw strings.
    if (stream.match(/(R|u8R|uR|UR|LR)/)) {
      var match = stream.match(/"([^\s\\()]{0,16})\(/);
      if (!match) {
        return false;
      }
      state.cpp11RawStringDelim = match[1];
      state.tokenize = tokenRawString;
      return tokenRawString(stream, state);
    }
    // Unicode strings/chars.
    if (stream.match(/(u8|u|U|L)/)) {
      if (stream.match(/["']/, /* eat */ false)) {
        return "string";
      }
      return false;
    }
    // Ignore this hook.
    stream.next();
    return false;
  }

  function cppLooksLikeConstructor(word) {
    var lastTwo = /(\w+)::~?(\w+)$/.exec(word);
    return lastTwo && lastTwo[1] == lastTwo[2];
  }

  // C#-style strings where "" escapes a quote.
  function tokenAtString(stream, state) {
    var next;
    while ((next = stream.next()) != null) {
      if (next == '"' && !stream.eat('"')) {
        state.tokenize = null;
        break;
      }
    }
    return "string";
  }

  // C++11 raw string literal is <prefix>"<delim>( anything )<delim>", where
  // <delim> can be a string up to 16 characters long.
  function tokenRawString(stream, state) {
    // Escape characters that have special regex meanings.
    var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, '\\$&');
    var match = stream.match(new RegExp(".*?\\)" + delim + '"'));
    if (match)
      state.tokenize = null;
    else
      stream.skipToEnd();
    return "string";
  }

  function def(mimes, mode) {
    if (typeof mimes == "string") mimes = [mimes];
    var words = [];
    function add(obj) {
      if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop))
        words.push(prop);
    }
    add(mode.keywords);
    add(mode.types);
    add(mode.builtin);
    add(mode.atoms);
    if (words.length) {
      mode.helperType = mimes[0];
      CodeMirror.registerHelper("hintWords", mimes[0], words);
    }

    for (var i = 0; i < mimes.length; ++i)
      CodeMirror.defineMIME(mimes[i], mode);
  }

  def(["text/x-csrc", "text/x-c", "text/x-chdr"], {
    name: "clike",
    keywords: words(cKeywords),
    types: words(cTypes + " bool _Complex _Bool float_t double_t intptr_t intmax_t " +
                 "int8_t int16_t int32_t int64_t uintptr_t uintmax_t uint8_t uint16_t " +
                 "uint32_t uint64_t"),
    blockKeywords: words("case do else for if switch while struct"),
    defKeywords: words("struct"),
    typeFirstDefinitions: true,
    atoms: words("NULL true false"),
    hooks: {"#": cppHook, "*": pointerHook},
    modeProps: {fold: ["brace", "include"]}
  });

  def(["text/x-c++src", "text/x-c++hdr"], {
    name: "clike",
    keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try explicit new " +
                    "static_cast typeid catch operator template typename class friend private " +
                    "this using const_cast inline public throw virtual delete mutable protected " +
                    "alignas alignof constexpr decltype nullptr noexcept thread_local final " +
                    "static_assert override"),
    types: words(cTypes + " bool wchar_t"),
    blockKeywords: words("catch class do else finally for if struct switch try while"),
    defKeywords: words("class namespace struct enum union"),
    typeFirstDefinitions: true,
    atoms: words("true false NULL"),
    dontIndentStatements: /^template$/,
    isIdentifierChar: /[\w\$_~\xa1-\uffff]/,
    hooks: {
      "#": cppHook,
      "*": pointerHook,
      "u": cpp11StringHook,
      "U": cpp11StringHook,
      "L": cpp11StringHook,
      "R": cpp11StringHook,
      "0": cpp14Literal,
      "1": cpp14Literal,
      "2": cpp14Literal,
      "3": cpp14Literal,
      "4": cpp14Literal,
      "5": cpp14Literal,
      "6": cpp14Literal,
      "7": cpp14Literal,
      "8": cpp14Literal,
      "9": cpp14Literal,
      token: function(stream, state, style) {
        if (style == "variable" && stream.peek() == "(" &&
            (state.prevToken == ";" || state.prevToken == null ||
             state.prevToken == "}") &&
            cppLooksLikeConstructor(stream.current()))
          return "def";
      }
    },
    namespaceSeparator: "::",
    modeProps: {fold: ["brace", "include"]}
  });

  def("text/x-java", {
    name: "clike",
    keywords: words("abstract assert break case catch class const continue default " +
                    "do else enum extends final finally float for goto if implements import " +
                    "instanceof interface native new package private protected public " +
                    "return static strictfp super switch synchronized this throw throws transient " +
                    "try volatile while @interface"),
    types: words("byte short int long float double boolean char void Boolean Byte Character Double Float " +
                 "Integer Long Number Object Short String StringBuffer StringBuilder Void"),
    blockKeywords: words("catch class do else finally for if switch try while"),
    defKeywords: words("class interface enum @interface"),
    typeFirstDefinitions: true,
    atoms: words("true false null"),
    number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i,
    hooks: {
      "@": function(stream) {
        // Don't match the @interface keyword.
        if (stream.match('interface', false)) return false;

        stream.eatWhile(/[\w\$_]/);
        return "meta";
      }
    },
    modeProps: {fold: ["brace", "import"]}
  });

  def("text/x-csharp", {
    name: "clike",
    keywords: words("abstract as async await base break case catch checked class const continue" +
                    " default delegate do else enum event explicit extern finally fixed for" +
                    " foreach goto if implicit in interface internal is lock namespace new" +
                    " operator out override params private protected public readonly ref return sealed" +
                    " sizeof stackalloc static struct switch this throw try typeof unchecked" +
                    " unsafe using virtual void volatile while add alias ascending descending dynamic from get" +
                    " global group into join let orderby partial remove select set value var yield"),
    types: words("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func" +
                 " Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32" +
                 " UInt64 bool byte char decimal double short int long object"  +
                 " sbyte float string ushort uint ulong"),
    blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
    defKeywords: words("class interface namespace struct var"),
    typeFirstDefinitions: true,
    atoms: words("true false null"),
    hooks: {
      "@": function(stream, state) {
        if (stream.eat('"')) {
          state.tokenize = tokenAtString;
          return tokenAtString(stream, state);
        }
        stream.eatWhile(/[\w\$_]/);
        return "meta";
      }
    }
  });

  function tokenTripleString(stream, state) {
    var escaped = false;
    while (!stream.eol()) {
      if (!escaped && stream.match('"""')) {
        state.tokenize = null;
        break;
      }
      escaped = stream.next() == "\\" && !escaped;
    }
    return "string";
  }

  function tokenNestedComment(depth) {
    return function (stream, state) {
      var ch
      while (ch = stream.next()) {
        if (ch == "*" && stream.eat("/")) {
          if (depth == 1) {
            state.tokenize = null
            break
          } else {
            state.tokenize = tokenNestedComment(depth - 1)
            return state.tokenize(stream, state)
          }
        } else if (ch == "/" && stream.eat("*")) {
          state.tokenize = tokenNestedComment(depth + 1)
          return state.tokenize(stream, state)
        }
      }
      return "comment"
    }
  }

  def("text/x-scala", {
    name: "clike",
    keywords: words(

      /* scala */
      "abstract case catch class def do else extends final finally for forSome if " +
      "implicit import lazy match new null object override package private protected return " +
      "sealed super this throw trait try type val var while with yield _ " +

      /* package scala */
      "assert assume require print println printf readLine readBoolean readByte readShort " +
      "readChar readInt readLong readFloat readDouble"
    ),
    types: words(
      "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " +
      "Enumeration Equiv Error Exception Fractional Function IndexedSeq Int Integral Iterable " +
      "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " +
      "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " +
      "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector " +

      /* package java.lang */
      "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
      "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
      "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
      "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
    ),
    multiLineStrings: true,
    blockKeywords: words("catch class enum do else finally for forSome if match switch try while"),
    defKeywords: words("class enum def object package trait type val var"),
    atoms: words("true false null"),
    indentStatements: false,
    indentSwitch: false,
    isOperatorChar: /[+\-*&%=<>!?|\/#:@]/,
    hooks: {
      "@": function(stream) {
        stream.eatWhile(/[\w\$_]/);
        return "meta";
      },
      '"': function(stream, state) {
        if (!stream.match('""')) return false;
        state.tokenize = tokenTripleString;
        return state.tokenize(stream, state);
      },
      "'": function(stream) {
        stream.eatWhile(/[\w\$_\xa1-\uffff]/);
        return "atom";
      },
      "=": function(stream, state) {
        var cx = state.context
        if (cx.type == "}" && cx.align && stream.eat(">")) {
          state.context = new Context(cx.indented, cx.column, cx.type, cx.info, null, cx.prev)
          return "operator"
        } else {
          return false
        }
      },

      "/": function(stream, state) {
        if (!stream.eat("*")) return false
        state.tokenize = tokenNestedComment(1)
        return state.tokenize(stream, state)
      }
    },
    modeProps: {closeBrackets: {triples: '"'}}
  });

  function tokenKotlinString(tripleString){
    return function (stream, state) {
      var escaped = false, next, end = false;
      while (!stream.eol()) {
        if (!tripleString && !escaped && stream.match('"') ) {end = true; break;}
        if (tripleString && stream.match('"""')) {end = true; break;}
        next = stream.next();
        if(!escaped && next == "$" && stream.match('{'))
          stream.skipTo("}");
        escaped = !escaped && next == "\\" && !tripleString;
      }
      if (end || !tripleString)
        state.tokenize = null;
      return "string";
    }
  }

  def("text/x-kotlin", {
    name: "clike",
    keywords: words(
      /*keywords*/
      "package as typealias class interface this super val operator " +
      "var fun for is in This throw return annotation " +
      "break continue object if else while do try when !in !is as? " +

      /*soft keywords*/
      "file import where by get set abstract enum open inner override private public internal " +
      "protected catch finally out final vararg reified dynamic companion constructor init " +
      "sealed field property receiver param sparam lateinit data inline noinline tailrec " +
      "external annotation crossinline const operator infix suspend actual expect setparam"
    ),
    types: words(
      /* package java.lang */
      "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
      "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
      "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
      "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void Annotation Any BooleanArray " +
      "ByteArray Char CharArray DeprecationLevel DoubleArray Enum FloatArray Function Int IntArray Lazy " +
      "LazyThreadSafetyMode LongArray Nothing ShortArray Unit"
    ),
    intendSwitch: false,
    indentStatements: false,
    multiLineStrings: true,
    number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+(\.\d+)?|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i,
    blockKeywords: words("catch class do else finally for if where try while enum"),
    defKeywords: words("class val var object interface fun"),
    atoms: words("true false null this"),
    hooks: {
      "@": function(stream) {
        stream.eatWhile(/[\w\$_]/);
        return "meta";
      },
      '"': function(stream, state) {
        state.tokenize = tokenKotlinString(stream.match('""'));
        return state.tokenize(stream, state);
      },
      indent: function(state, ctx, textAfter, indentUnit) {
        var firstChar = textAfter && textAfter.charAt(0);
        if ((state.prevToken == "}" || state.prevToken == ")") && textAfter == "")
          return state.indented;
        if (state.prevToken == "operator" && textAfter != "}" ||
          state.prevToken == "variable" && firstChar == "." ||
          (state.prevToken == "}" || state.prevToken == ")") && firstChar == ".")
          return indentUnit * 2 + ctx.indented;
        if (ctx.align && ctx.type == "}")
          return ctx.indented + (state.context.type == (textAfter || "").charAt(0) ? 0 : indentUnit);
      }
    },
    modeProps: {closeBrackets: {triples: '"'}}
  });

  def(["x-shader/x-vertex", "x-shader/x-fragment"], {
    name: "clike",
    keywords: words("sampler1D sampler2D sampler3D samplerCube " +
                    "sampler1DShadow sampler2DShadow " +
                    "const attribute uniform varying " +
                    "break continue discard return " +
                    "for while do if else struct " +
                    "in out inout"),
    types: words("float int bool void " +
                 "vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " +
                 "mat2 mat3 mat4"),
    blockKeywords: words("for while do if else struct"),
    builtin: words("radians degrees sin cos tan asin acos atan " +
                    "pow exp log exp2 sqrt inversesqrt " +
                    "abs sign floor ceil fract mod min max clamp mix step smoothstep " +
                    "length distance dot cross normalize ftransform faceforward " +
                    "reflect refract matrixCompMult " +
                    "lessThan lessThanEqual greaterThan greaterThanEqual " +
                    "equal notEqual any all not " +
                    "texture1D texture1DProj texture1DLod texture1DProjLod " +
                    "texture2D texture2DProj texture2DLod texture2DProjLod " +
                    "texture3D texture3DProj texture3DLod texture3DProjLod " +
                    "textureCube textureCubeLod " +
                    "shadow1D shadow2D shadow1DProj shadow2DProj " +
                    "shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " +
                    "dFdx dFdy fwidth " +
                    "noise1 noise2 noise3 noise4"),
    atoms: words("true false " +
                "gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " +
                "gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " +
                "gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " +
                "gl_FogCoord gl_PointCoord " +
                "gl_Position gl_PointSize gl_ClipVertex " +
                "gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " +
                "gl_TexCoord gl_FogFragCoord " +
                "gl_FragCoord gl_FrontFacing " +
                "gl_FragData gl_FragDepth " +
                "gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " +
                "gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " +
                "gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " +
                "gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose " +
                "gl_ProjectionMatrixInverseTranspose " +
                "gl_ModelViewProjectionMatrixInverseTranspose " +
                "gl_TextureMatrixInverseTranspose " +
                "gl_NormalScale gl_DepthRange gl_ClipPlane " +
                "gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " +
                "gl_FrontLightModelProduct gl_BackLightModelProduct " +
                "gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " +
                "gl_FogParameters " +
                "gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " +
                "gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " +
                "gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " +
                "gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " +
                "gl_MaxDrawBuffers"),
    indentSwitch: false,
    hooks: {"#": cppHook},
    modeProps: {fold: ["brace", "include"]}
  });

  def("text/x-nesc", {
    name: "clike",
    keywords: words(cKeywords + "as atomic async call command component components configuration event generic " +
                    "implementation includes interface module new norace nx_struct nx_union post provides " +
                    "signal task uses abstract extends"),
    types: words(cTypes),
    blockKeywords: words("case do else for if switch while struct"),
    atoms: words("null true false"),
    hooks: {"#": cppHook},
    modeProps: {fold: ["brace", "include"]}
  });

  def("text/x-objectivec", {
    name: "clike",
    keywords: words(cKeywords + "inline restrict _Bool _Complex _Imaginary BOOL Class bycopy byref id IMP in " +
                    "inout nil oneway out Protocol SEL self super atomic nonatomic retain copy readwrite readonly"),
    types: words(cTypes),
    atoms: words("YES NO NULL NILL ON OFF true false"),
    hooks: {
      "@": function(stream) {
        stream.eatWhile(/[\w\$]/);
        return "keyword";
      },
      "#": cppHook,
      indent: function(_state, ctx, textAfter) {
        if (ctx.type == "statement" && /^@\w/.test(textAfter)) return ctx.indented
      }
    },
    modeProps: {fold: "brace"}
  });

  def("text/x-squirrel", {
    name: "clike",
    keywords: words("base break clone continue const default delete enum extends function in class" +
                    " foreach local resume return this throw typeof yield constructor instanceof static"),
    types: words(cTypes),
    blockKeywords: words("case catch class else for foreach if switch try while"),
    defKeywords: words("function local class"),
    typeFirstDefinitions: true,
    atoms: words("true false null"),
    hooks: {"#": cppHook},
    modeProps: {fold: ["brace", "include"]}
  });

  // Ceylon Strings need to deal with interpolation
  var stringTokenizer = null;
  function tokenCeylonString(type) {
    return function(stream, state) {
      var escaped = false, next, end = false;
      while (!stream.eol()) {
        if (!escaped && stream.match('"') &&
              (type == "single" || stream.match('""'))) {
          end = true;
          break;
        }
        if (!escaped && stream.match('``')) {
          stringTokenizer = tokenCeylonString(type);
          end = true;
          break;
        }
        next = stream.next();
        escaped = type == "single" && !escaped && next == "\\";
      }
      if (end)
          state.tokenize = null;
      return "string";
    }
  }

  def("text/x-ceylon", {
    name: "clike",
    keywords: words("abstracts alias assembly assert assign break case catch class continue dynamic else" +
                    " exists extends finally for function given if import in interface is let module new" +
                    " nonempty object of out outer package return satisfies super switch then this throw" +
                    " try value void while"),
    types: function(word) {
        // In Ceylon all identifiers that start with an uppercase are types
        var first = word.charAt(0);
        return (first === first.toUpperCase() && first !== first.toLowerCase());
    },
    blockKeywords: words("case catch class dynamic else finally for function if interface module new object switch try while"),
    defKeywords: words("class dynamic function interface module object package value"),
    builtin: words("abstract actual aliased annotation by default deprecated doc final formal late license" +
                   " native optional sealed see serializable shared suppressWarnings tagged throws variable"),
    isPunctuationChar: /[\[\]{}\(\),;\:\.`]/,
    isOperatorChar: /[+\-*&%=<>!?|^~:\/]/,
    numberStart: /[\d#$]/,
    number: /^(?:#[\da-fA-F_]+|\$[01_]+|[\d_]+[kMGTPmunpf]?|[\d_]+\.[\d_]+(?:[eE][-+]?\d+|[kMGTPmunpf]|)|)/i,
    multiLineStrings: true,
    typeFirstDefinitions: true,
    atoms: words("true false null larger smaller equal empty finished"),
    indentSwitch: false,
    styleDefs: false,
    hooks: {
      "@": function(stream) {
        stream.eatWhile(/[\w\$_]/);
        return "meta";
      },
      '"': function(stream, state) {
          state.tokenize = tokenCeylonString(stream.match('""') ? "triple" : "single");
          return state.tokenize(stream, state);
        },
      '`': function(stream, state) {
          if (!stringTokenizer || !stream.match('`')) return false;
          state.tokenize = stringTokenizer;
          stringTokenizer = null;
          return state.tokenize(stream, state);
        },
      "'": function(stream) {
        stream.eatWhile(/[\w\$_\xa1-\uffff]/);
        return "atom";
      },
      token: function(_stream, state, style) {
          if ((style == "variable" || style == "type") &&
              state.prevToken == ".") {
            return "variable-2";
          }
        }
    },
    modeProps: {
        fold: ["brace", "import"],
        closeBrackets: {triples: '"'}
    }
  });

});


/***/ }),

/***/ "S6ln":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/hr.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


function translate(number, withoutSuffix, key) {
    var result = number + ' ';
    switch (key) {
        case 'ss':
            if (number === 1) {
                result += 'sekunda';
            } else if (number === 2 || number === 3 || number === 4) {
                result += 'sekunde';
            } else {
                result += 'sekundi';
            }
            return result;
        case 'm':
            return withoutSuffix ? 'jedna minuta' : 'jedne minute';
        case 'mm':
            if (number === 1) {
                result += 'minuta';
            } else if (number === 2 || number === 3 || number === 4) {
                result += 'minute';
            } else {
                result += 'minuta';
            }
            return result;
        case 'h':
            return withoutSuffix ? 'jedan sat' : 'jednog sata';
        case 'hh':
            if (number === 1) {
                result += 'sat';
            } else if (number === 2 || number === 3 || number === 4) {
                result += 'sata';
            } else {
                result += 'sati';
            }
            return result;
        case 'dd':
            if (number === 1) {
                result += 'dan';
            } else {
                result += 'dana';
            }
            return result;
        case 'MM':
            if (number === 1) {
                result += 'mjesec';
            } else if (number === 2 || number === 3 || number === 4) {
                result += 'mjeseca';
            } else {
                result += 'mjeseci';
            }
            return result;
        case 'yy':
            if (number === 1) {
                result += 'godina';
            } else if (number === 2 || number === 3 || number === 4) {
                result += 'godine';
            } else {
                result += 'godina';
            }
            return result;
    }
}

var hr = moment.defineLocale('hr', {
    months : {
        format: 'siječnja_veljače_ožujka_travnja_svibnja_lipnja_srpnja_kolovoza_rujna_listopada_studenoga_prosinca'.split('_'),
        standalone: 'siječanj_veljača_ožujak_travanj_svibanj_lipanj_srpanj_kolovoz_rujan_listopad_studeni_prosinac'.split('_')
    },
    monthsShort : 'sij._velj._ožu._tra._svi._lip._srp._kol._ruj._lis._stu._pro.'.split('_'),
    monthsParseExact: true,
    weekdays : 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'),
    weekdaysShort : 'ned._pon._uto._sri._čet._pet._sub.'.split('_'),
    weekdaysMin : 'ne_po_ut_sr_če_pe_su'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'H:mm',
        LTS : 'H:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D. MMMM YYYY',
        LLL : 'D. MMMM YYYY H:mm',
        LLLL : 'dddd, D. MMMM YYYY H:mm'
    },
    calendar : {
        sameDay  : '[danas u] LT',
        nextDay  : '[sutra u] LT',
        nextWeek : function () {
            switch (this.day()) {
                case 0:
                    return '[u] [nedjelju] [u] LT';
                case 3:
                    return '[u] [srijedu] [u] LT';
                case 6:
                    return '[u] [subotu] [u] LT';
                case 1:
                case 2:
                case 4:
                case 5:
                    return '[u] dddd [u] LT';
            }
        },
        lastDay  : '[jučer u] LT',
        lastWeek : function () {
            switch (this.day()) {
                case 0:
                case 3:
                    return '[prošlu] dddd [u] LT';
                case 6:
                    return '[prošle] [subote] [u] LT';
                case 1:
                case 2:
                case 4:
                case 5:
                    return '[prošli] dddd [u] LT';
            }
        },
        sameElse : 'L'
    },
    relativeTime : {
        future : 'za %s',
        past   : 'prije %s',
        s      : 'par sekundi',
        ss     : translate,
        m      : translate,
        mm     : translate,
        h      : translate,
        hh     : translate,
        d      : 'dan',
        dd     : translate,
        M      : 'mjesec',
        MM     : translate,
        y      : 'godinu',
        yy     : translate
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return hr;

})));


/***/ }),

/***/ "S8N9":
/*!******************************************************!*\
  !*** ./node_modules/xterm/lib/shared/atlas/Types.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.CHAR_ATLAS_CELL_SPACING = 1;

//# sourceMappingURL=Types.js.map


/***/ }),

/***/ "S8Va":
/*!*******************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/ColorPicker.js ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _SketchFields = __webpack_require__(/*! react-color/lib/components/sketch/SketchFields */ "GiOz");

var _SketchFields2 = _interopRequireDefault(_SketchFields);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _tinycolor = __webpack_require__(/*! tinycolor2 */ "Zss7");

var _tinycolor2 = _interopRequireDefault(_tinycolor);

var _common = __webpack_require__(/*! react-color/lib/components/common */ "TM95");

var _reactColor = __webpack_require__(/*! react-color */ "WFjJ");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

// Utility functions for converting ColorPicker color objects or raw strings
// into TinyColor objects.
var extractRGB = function extractRGB(c) {
  return c.rgb || c;
};
var getColorSource = function getColorSource(c) {
  return c.source === 'hex' ? c.hex : extractRGB(c);
};
var toTinyColor = function toTinyColor(c) {
  return (0, _tinycolor2.default)(getColorSource(c));
};

var Custom = function (_Component) {
  _inherits(Custom, _Component);

  function Custom() {
    _classCallCheck(this, Custom);

    return _possibleConstructorReturn(this, (Custom.__proto__ || Object.getPrototypeOf(Custom)).apply(this, arguments));
  }

  _createClass(Custom, [{
    key: 'render',
    value: function render() {
      var onChangeComplete = this.props.onChangeComplete;


      return _react2.default.createElement(
        'div',
        { className: 'colorpicker__outer' },
        _react2.default.createElement(
          'div',
          { className: 'colorpicker__controls +flex' },
          _react2.default.createElement(
            'div',
            { className: 'colorpicker__sliders' },
            _react2.default.createElement(
              'div',
              { className: 'colorpicker__slider' },
              _react2.default.createElement(_common.Hue, this.props)
            )
          )
        ),
        _react2.default.createElement(
          'div',
          { className: 'colorpicker__saturation' },
          _react2.default.createElement(_common.Saturation, this.props)
        ),
        _react2.default.createElement(
          'div',
          { className: 'colorpicker__custom-input' },
          _react2.default.createElement(_SketchFields2.default, _extends({}, this.props, { onChange: onChangeComplete }))
        )
      );
    }
  }]);

  return Custom;
}(_react.Component);

Custom.propTypes = {
  rgb: _propTypes2.default.object,
  onChangeComplete: _propTypes2.default.func
};

var CustomColorPicker = (0, _reactColor.CustomPicker)(Custom);

var ColorPicker = function (_Component2) {
  _inherits(ColorPicker, _Component2);

  function ColorPicker(props) {
    _classCallCheck(this, ColorPicker);

    var _this2 = _possibleConstructorReturn(this, (ColorPicker.__proto__ || Object.getPrototypeOf(ColorPicker)).call(this, props));

    _this2.state = {
      isVisible: false
    };

    _this2.onSelectedColorChange = _this2.onSelectedColorChange.bind(_this2);
    _this2.toggleVisible = _this2.toggleVisible.bind(_this2);
    return _this2;
  }

  _createClass(ColorPicker, [{
    key: 'onSelectedColorChange',
    value: function onSelectedColorChange(newColor) {
      // We use our own toTinyColor because this value is a ColorPicker
      // color value which is an object that needs unpacking. We also handle
      // the case where a color string is passed in (just in case).
      var color = toTinyColor(newColor);

      // relayout call only wants a RGB String
      this.props.onColorChange(color.toRgbString());
    }
  }, {
    key: 'toggleVisible',
    value: function toggleVisible() {
      this.setState({ isVisible: !this.state.isVisible });
    }
  }, {
    key: 'render',
    value: function render() {
      // We use tinycolor here instead of our own toTinyColor as
      // tinycolor handles `null` values and other weirdness we may
      // expect from user data.
      var selectedColor = (0, _tinycolor2.default)(this.props.selectedColor);
      var colorText = selectedColor.toHexString();

      // Convert rgba to rgb if necessary
      var rgbString = selectedColor._a !== 0 ? selectedColor.toRgbString() : 'rgb(' + selectedColor._r + ',' + selectedColor._g + ',' + selectedColor._b + ')';

      // We need inline style here to assign the background color
      // dynamically.
      var swatchStyle = { backgroundColor: rgbString };

      return _react2.default.createElement(
        _react.Fragment,
        null,
        _react2.default.createElement(
          'div',
          { className: 'colorpicker__container' },
          _react2.default.createElement(
            'div',
            { className: 'colorpicker' },
            _react2.default.createElement('div', {
              className: 'colorpicker__swatch +cursor-clickable',
              style: swatchStyle,
              onClick: this.toggleVisible
            })
          ),
          _react2.default.createElement(
            'div',
            { className: 'colorpicker__selected-color +hover-grey', onClick: this.toggleVisible },
            colorText
          )
        ),
        this.state.isVisible && _react2.default.createElement(CustomColorPicker, { color: rgbString, onChangeComplete: this.onSelectedColorChange })
      );
    }
  }]);

  return ColorPicker;
}(_react.Component);

ColorPicker.propTypes = {
  onColorChange: _propTypes2.default.func.isRequired,
  selectedColor: _propTypes2.default.string
};

exports.default = ColorPicker;
//# sourceMappingURL=ColorPicker.js.map

/***/ }),

/***/ "S9up":
/*!********************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/index.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(__webpack_require__(/*! ./config */ "e3Tu"));
__export(__webpack_require__(/*! ./contents */ "/Hsf"));
__export(__webpack_require__(/*! ./kernel */ "uxQ0"));
__export(__webpack_require__(/*! ./manager */ "FCiD"));
__export(__webpack_require__(/*! ./serverconnection */ "ZWV2"));
__export(__webpack_require__(/*! ./session */ "Gm2Q"));
__export(__webpack_require__(/*! ./setting */ "ai3f"));
__export(__webpack_require__(/*! ./terminal */ "JSoe"));
__export(__webpack_require__(/*! ./workspace */ "yjZJ"));
__export(__webpack_require__(/*! ./nbconvert */ "hBxh"));


/***/ }),

/***/ "SBuE":
/*!************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_iterators.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = {};


/***/ }),

/***/ "SF5q":
/*!*********************************************************!*\
  !*** ./node_modules/draft-js/lib/DraftRemovableWord.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DraftRemovableWord
 * @format
 * 
 */



var TokenizeUtil = __webpack_require__(/*! fbjs/lib/TokenizeUtil */ "evZB");

var punctuation = TokenizeUtil.getPunctuation();

// The apostrophe and curly single quotes behave in a curious way: when
// surrounded on both sides by word characters, they behave as word chars; when
// either neighbor is punctuation or an end of the string, they behave as
// punctuation.
var CHAMELEON_CHARS = '[\'\u2018\u2019]';

// Remove the underscore, which should count as part of the removable word. The
// "chameleon chars" also count as punctuation in this regex.
var WHITESPACE_AND_PUNCTUATION = '\\s|(?![_])' + punctuation;

var DELETE_STRING = '^' + '(?:' + WHITESPACE_AND_PUNCTUATION + ')*' + '(?:' + CHAMELEON_CHARS + '|(?!' + WHITESPACE_AND_PUNCTUATION + ').)*' + '(?:(?!' + WHITESPACE_AND_PUNCTUATION + ').)';
var DELETE_REGEX = new RegExp(DELETE_STRING);

var BACKSPACE_STRING = '(?:(?!' + WHITESPACE_AND_PUNCTUATION + ').)' + '(?:' + CHAMELEON_CHARS + '|(?!' + WHITESPACE_AND_PUNCTUATION + ').)*' + '(?:' + WHITESPACE_AND_PUNCTUATION + ')*' + '$';
var BACKSPACE_REGEX = new RegExp(BACKSPACE_STRING);

function getRemovableWord(text, isBackward) {
  var matches = isBackward ? BACKSPACE_REGEX.exec(text) : DELETE_REGEX.exec(text);
  return matches ? matches[0] : text;
}

var DraftRemovableWord = {
  getBackward: function getBackward(text) {
    return getRemovableWord(text, true);
  },

  getForward: function getForward(text) {
    return getRemovableWord(text, false);
  }
};

module.exports = DraftRemovableWord;

/***/ }),

/***/ "SFLx":
/*!********************************************************************!*\
  !*** ./node_modules/plotly.js/src/components/colorscale/scales.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var tinycolor = __webpack_require__(/*! tinycolor2 */ "Zss7");

var scales = {
    'Greys': [
        [0, 'rgb(0,0,0)'], [1, 'rgb(255,255,255)']
    ],

    'YlGnBu': [
        [0, 'rgb(8,29,88)'], [0.125, 'rgb(37,52,148)'],
        [0.25, 'rgb(34,94,168)'], [0.375, 'rgb(29,145,192)'],
        [0.5, 'rgb(65,182,196)'], [0.625, 'rgb(127,205,187)'],
        [0.75, 'rgb(199,233,180)'], [0.875, 'rgb(237,248,217)'],
        [1, 'rgb(255,255,217)']
    ],

    'Greens': [
        [0, 'rgb(0,68,27)'], [0.125, 'rgb(0,109,44)'],
        [0.25, 'rgb(35,139,69)'], [0.375, 'rgb(65,171,93)'],
        [0.5, 'rgb(116,196,118)'], [0.625, 'rgb(161,217,155)'],
        [0.75, 'rgb(199,233,192)'], [0.875, 'rgb(229,245,224)'],
        [1, 'rgb(247,252,245)']
    ],

    'YlOrRd': [
        [0, 'rgb(128,0,38)'], [0.125, 'rgb(189,0,38)'],
        [0.25, 'rgb(227,26,28)'], [0.375, 'rgb(252,78,42)'],
        [0.5, 'rgb(253,141,60)'], [0.625, 'rgb(254,178,76)'],
        [0.75, 'rgb(254,217,118)'], [0.875, 'rgb(255,237,160)'],
        [1, 'rgb(255,255,204)']
    ],

    'Bluered': [
        [0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']
    ],

    // modified RdBu based on
    // www.sandia.gov/~kmorel/documents/ColorMaps/ColorMapsExpanded.pdf
    'RdBu': [
        [0, 'rgb(5,10,172)'], [0.35, 'rgb(106,137,247)'],
        [0.5, 'rgb(190,190,190)'], [0.6, 'rgb(220,170,132)'],
        [0.7, 'rgb(230,145,90)'], [1, 'rgb(178,10,28)']
    ],

    // Scale for non-negative numeric values
    'Reds': [
        [0, 'rgb(220,220,220)'], [0.2, 'rgb(245,195,157)'],
        [0.4, 'rgb(245,160,105)'], [1, 'rgb(178,10,28)']
    ],

    // Scale for non-positive numeric values
    'Blues': [
        [0, 'rgb(5,10,172)'], [0.35, 'rgb(40,60,190)'],
        [0.5, 'rgb(70,100,245)'], [0.6, 'rgb(90,120,245)'],
        [0.7, 'rgb(106,137,247)'], [1, 'rgb(220,220,220)']
    ],

    'Picnic': [
        [0, 'rgb(0,0,255)'], [0.1, 'rgb(51,153,255)'],
        [0.2, 'rgb(102,204,255)'], [0.3, 'rgb(153,204,255)'],
        [0.4, 'rgb(204,204,255)'], [0.5, 'rgb(255,255,255)'],
        [0.6, 'rgb(255,204,255)'], [0.7, 'rgb(255,153,255)'],
        [0.8, 'rgb(255,102,204)'], [0.9, 'rgb(255,102,102)'],
        [1, 'rgb(255,0,0)']
    ],

    'Rainbow': [
        [0, 'rgb(150,0,90)'], [0.125, 'rgb(0,0,200)'],
        [0.25, 'rgb(0,25,255)'], [0.375, 'rgb(0,152,255)'],
        [0.5, 'rgb(44,255,150)'], [0.625, 'rgb(151,255,0)'],
        [0.75, 'rgb(255,234,0)'], [0.875, 'rgb(255,111,0)'],
        [1, 'rgb(255,0,0)']
    ],

    'Portland': [
        [0, 'rgb(12,51,131)'], [0.25, 'rgb(10,136,186)'],
        [0.5, 'rgb(242,211,56)'], [0.75, 'rgb(242,143,56)'],
        [1, 'rgb(217,30,30)']
    ],

    'Jet': [
        [0, 'rgb(0,0,131)'], [0.125, 'rgb(0,60,170)'],
        [0.375, 'rgb(5,255,255)'], [0.625, 'rgb(255,255,0)'],
        [0.875, 'rgb(250,0,0)'], [1, 'rgb(128,0,0)']
    ],

    'Hot': [
        [0, 'rgb(0,0,0)'], [0.3, 'rgb(230,0,0)'],
        [0.6, 'rgb(255,210,0)'], [1, 'rgb(255,255,255)']
    ],

    'Blackbody': [
        [0, 'rgb(0,0,0)'], [0.2, 'rgb(230,0,0)'],
        [0.4, 'rgb(230,210,0)'], [0.7, 'rgb(255,255,255)'],
        [1, 'rgb(160,200,255)']
    ],

    'Earth': [
        [0, 'rgb(0,0,130)'], [0.1, 'rgb(0,180,180)'],
        [0.2, 'rgb(40,210,40)'], [0.4, 'rgb(230,230,50)'],
        [0.6, 'rgb(120,70,20)'], [1, 'rgb(255,255,255)']
    ],

    'Electric': [
        [0, 'rgb(0,0,0)'], [0.15, 'rgb(30,0,100)'],
        [0.4, 'rgb(120,0,100)'], [0.6, 'rgb(160,90,0)'],
        [0.8, 'rgb(230,200,0)'], [1, 'rgb(255,250,220)']
    ],

    'Viridis': [
        [0, '#440154'], [0.06274509803921569, '#48186a'],
        [0.12549019607843137, '#472d7b'], [0.18823529411764706, '#424086'],
        [0.25098039215686274, '#3b528b'], [0.3137254901960784, '#33638d'],
        [0.3764705882352941, '#2c728e'], [0.4392156862745098, '#26828e'],
        [0.5019607843137255, '#21918c'], [0.5647058823529412, '#1fa088'],
        [0.6274509803921569, '#28ae80'], [0.6901960784313725, '#3fbc73'],
        [0.7529411764705882, '#5ec962'], [0.8156862745098039, '#84d44b'],
        [0.8784313725490196, '#addc30'], [0.9411764705882353, '#d8e219'],
        [1, '#fde725']
    ],

    'Cividis': [
        [0.000000, 'rgb(0,32,76)'], [0.058824, 'rgb(0,42,102)'],
        [0.117647, 'rgb(0,52,110)'], [0.176471, 'rgb(39,63,108)'],
        [0.235294, 'rgb(60,74,107)'], [0.294118, 'rgb(76,85,107)'],
        [0.352941, 'rgb(91,95,109)'], [0.411765, 'rgb(104,106,112)'],
        [0.470588, 'rgb(117,117,117)'], [0.529412, 'rgb(131,129,120)'],
        [0.588235, 'rgb(146,140,120)'], [0.647059, 'rgb(161,152,118)'],
        [0.705882, 'rgb(176,165,114)'], [0.764706, 'rgb(192,177,109)'],
        [0.823529, 'rgb(209,191,102)'], [0.882353, 'rgb(225,204,92)'],
        [0.941176, 'rgb(243,219,79)'], [1.000000, 'rgb(255,233,69)']
    ]
};

var defaultScale = scales.RdBu;

function getScale(scl, dflt) {
    if(!dflt) dflt = defaultScale;
    if(!scl) return dflt;

    function parseScale() {
        try {
            scl = scales[scl] || JSON.parse(scl);
        } catch(e) {
            scl = dflt;
        }
    }

    if(typeof scl === 'string') {
        parseScale();
        // occasionally scl is double-JSON encoded...
        if(typeof scl === 'string') parseScale();
    }

    if(!isValidScaleArray(scl)) return dflt;
    return scl;
}


function isValidScaleArray(scl) {
    var highestVal = 0;

    if(!Array.isArray(scl) || scl.length < 2) return false;

    if(!scl[0] || !scl[scl.length - 1]) return false;

    if(+scl[0][0] !== 0 || +scl[scl.length - 1][0] !== 1) return false;

    for(var i = 0; i < scl.length; i++) {
        var si = scl[i];

        if(si.length !== 2 || +si[0] < highestVal || !tinycolor(si[1]).isValid()) {
            return false;
        }

        highestVal = +si[0];
    }

    return true;
}

function isValidScale(scl) {
    if(scales[scl] !== undefined) return true;
    else return isValidScaleArray(scl);
}

module.exports = {
    scales: scales,
    defaultScale: defaultScale,

    get: getScale,
    isValid: isValidScale
};


/***/ }),

/***/ "SFxW":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/az.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var suffixes = {
    1: '-inci',
    5: '-inci',
    8: '-inci',
    70: '-inci',
    80: '-inci',
    2: '-nci',
    7: '-nci',
    20: '-nci',
    50: '-nci',
    3: '-üncü',
    4: '-üncü',
    100: '-üncü',
    6: '-ncı',
    9: '-uncu',
    10: '-uncu',
    30: '-uncu',
    60: '-ıncı',
    90: '-ıncı'
};

var az = moment.defineLocale('az', {
    months : 'yanvar_fevral_mart_aprel_may_iyun_iyul_avqust_sentyabr_oktyabr_noyabr_dekabr'.split('_'),
    monthsShort : 'yan_fev_mar_apr_may_iyn_iyl_avq_sen_okt_noy_dek'.split('_'),
    weekdays : 'Bazar_Bazar ertəsi_Çərşənbə axşamı_Çərşənbə_Cümə axşamı_Cümə_Şənbə'.split('_'),
    weekdaysShort : 'Baz_BzE_ÇAx_Çər_CAx_Cüm_Şən'.split('_'),
    weekdaysMin : 'Bz_BE_ÇA_Çə_CA_Cü_Şə'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd, D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay : '[bugün saat] LT',
        nextDay : '[sabah saat] LT',
        nextWeek : '[gələn həftə] dddd [saat] LT',
        lastDay : '[dünən] LT',
        lastWeek : '[keçən həftə] dddd [saat] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : '%s sonra',
        past : '%s əvvəl',
        s : 'birneçə saniyyə',
        ss : '%d saniyə',
        m : 'bir dəqiqə',
        mm : '%d dəqiqə',
        h : 'bir saat',
        hh : '%d saat',
        d : 'bir gün',
        dd : '%d gün',
        M : 'bir ay',
        MM : '%d ay',
        y : 'bir il',
        yy : '%d il'
    },
    meridiemParse: /gecə|səhər|gündüz|axşam/,
    isPM : function (input) {
        return /^(gündüz|axşam)$/.test(input);
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 4) {
            return 'gecə';
        } else if (hour < 12) {
            return 'səhər';
        } else if (hour < 17) {
            return 'gündüz';
        } else {
            return 'axşam';
        }
    },
    dayOfMonthOrdinalParse: /\d{1,2}-(ıncı|inci|nci|üncü|ncı|uncu)/,
    ordinal : function (number) {
        if (number === 0) {  // special case for zero
            return number + '-ıncı';
        }
        var a = number % 10,
            b = number % 100 - a,
            c = number >= 100 ? 100 : null;
        return number + (suffixes[a] || suffixes[b] || suffixes[c]);
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return az;

})));


/***/ }),

/***/ "SKAX":
/*!******************************************!*\
  !*** ./node_modules/lodash/_baseEach.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseForOwn = __webpack_require__(/*! ./_baseForOwn */ "JC6p"),
    createBaseEach = __webpack_require__(/*! ./_createBaseEach */ "lQqw");

/**
 * 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);

module.exports = baseEach;


/***/ }),

/***/ "SNK5":
/*!***********************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/relative_attr.js ***!
  \***********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




// ASCEND: chop off the last nesting level - either [<n>] or .<key> - to ascend
// the attribute tree. the remaining attrString is in match[1]
var ASCEND = /^(.*)(\.[^\.\[\]]+|\[\d\])$/;

// SIMPLEATTR: is this an un-nested attribute? (no dots or brackets)
var SIMPLEATTR = /^[^\.\[\]]+$/;

/*
 * calculate a relative attribute string, similar to a relative path
 *
 * @param {string} baseAttr:
 *   an attribute string, such as 'annotations[3].x'. The "current location"
 *   is the attribute string minus the last component ('annotations[3]')
 * @param {string} relativeAttr:
 *   a route to the desired attribute string, using '^' to ascend
 *
 * @return {string} attrString:
 *   for example:
 *     relativeAttr('annotations[3].x', 'y') = 'annotations[3].y'
 *     relativeAttr('annotations[3].x', '^[2].z') = 'annotations[2].z'
 *     relativeAttr('annotations[3].x', '^^margin') = 'margin'
 *     relativeAttr('annotations[3].x', '^^margin.r') = 'margin.r'
 */
module.exports = function(baseAttr, relativeAttr) {
    while(relativeAttr) {
        var match = baseAttr.match(ASCEND);

        if(match) baseAttr = match[1];
        else if(baseAttr.match(SIMPLEATTR)) baseAttr = '';
        else throw new Error('bad relativeAttr call:' + [baseAttr, relativeAttr]);

        if(relativeAttr.charAt(0) === '^') relativeAttr = relativeAttr.slice(1);
        else break;
    }

    if(baseAttr && relativeAttr.charAt(0) !== '[') {
        return baseAttr + '.' + relativeAttr;
    }
    return baseAttr + relativeAttr;
};


/***/ }),

/***/ "SQ0G":
/*!*********************************************!*\
  !*** ./node_modules/fbjs/lib/isTextNode.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks
 */

var isNode = __webpack_require__(/*! ./isNode */ "94Z+");

/**
 * @param {*} object The object to check.
 * @return {boolean} Whether or not the object is a DOM text node.
 */
function isTextNode(object) {
  return isNode(object) && object.nodeType == 3;
}

module.exports = isTextNode;

/***/ }),

/***/ "STJr":
/*!*******************************************************!*\
  !*** ./node_modules/@jupyterlab/faq-extension/faq.md ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = "# Frequently Asked Questions (FAQ)\n\nBelow are some frequently asked questions.\nClick on a question to be directed to relevant information in our documentation or our GitHub repo.\n\n## General\n\n- [What is JupyterLab?](https://jupyterlab.readthedocs.io/en/stable/getting_started/overview.html)\n- [How stable is JupyterLab?](https://jupyterlab.readthedocs.io/en/stable/getting_started/overview.html)\n- [What will happen to the classic Jupyter Notebook?](https://jupyterlab.readthedocs.io/en/stable/getting_started/overview.html#releases)\n- [Where is the documentation for JupyterLab?](https://jupyterlab.readthedocs.io/en/stable/)\n\n## Development\n\n- [How can you report a bug or provide feedback?](https://github.com/jupyterlab/jupyterlab/issues)\n- [How can you contribute?](https://github.com/jupyterlab/jupyterlab/blob/master/CONTRIBUTING.md)\n- [How can you extend or customize JupyterLab?](https://jupyterlab.readthedocs.io/en/stable/user/extensions.html)\n"

/***/ }),

/***/ "SWc2":
/*!*************************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/is_plain_object.js ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




// more info: http://stackoverflow.com/questions/18531624/isplainobject-thing
module.exports = function isPlainObject(obj) {

    // We need to be a little less strict in the `imagetest` container because
    // of how async image requests are handled.
    //
    // N.B. isPlainObject(new Constructor()) will return true in `imagetest`
    if(window && window.process && window.process.versions) {
        return Object.prototype.toString.call(obj) === '[object Object]';
    }

    return (
        Object.prototype.toString.call(obj) === '[object Object]' &&
        Object.getPrototypeOf(obj) === Object.prototype
    );
};


/***/ }),

/***/ "SXi3":
/*!*******************************************************!*\
  !*** ./node_modules/mdi-react/AccountMultipleIcon.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var AccountMultipleIcon = function AccountMultipleIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M16,13C15.71,13 15.38,13 15.03,13.05C16.19,13.89 17,15 17,16.5V19H23V16.5C23,14.17 18.33,13 16,13M8,13C5.67,13 1,14.17 1,16.5V19H15V16.5C15,14.17 10.33,13 8,13M8,11C9.66,11 11,9.66 11,8C11,6.34 9.66,5 8,5C6.34,5 5,6.34 5,8C5,9.66 6.34,11 8,11M16,11C17.66,11 19,9.66 19,8C19,6.34 17.66,5 16,5C14.34,5 13,6.34 13,8C13,9.66 14.34,11 16,11Z' })
  );
};

module.exports = AccountMultipleIcon;


/***/ }),

/***/ "SYhp":
/*!*****************************************************!*\
  !*** ./node_modules/draft-js/lib/keyCommandUndo.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule keyCommandUndo
 * @format
 * 
 */



var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");

function keyCommandUndo(e, editorState, updateFn) {
  var undoneState = EditorState.undo(editorState);

  // If the last change to occur was a spellcheck change, allow the undo
  // event to fall through to the browser. This allows the browser to record
  // the unwanted change, which should soon lead it to learn not to suggest
  // the correction again.
  if (editorState.getLastChangeType() === 'spellcheck-change') {
    var nativelyRenderedContent = undoneState.getCurrentContent();
    updateFn(EditorState.set(undoneState, { nativelyRenderedContent: nativelyRenderedContent }));
    return;
  }

  // Otheriwse, manage the undo behavior manually.
  e.preventDefault();
  if (!editorState.getNativelyRenderedContent()) {
    updateFn(undoneState);
    return;
  }

  // Trigger a re-render with the current content state to ensure that the
  // component tree has up-to-date props for comparison.
  updateFn(EditorState.set(editorState, { nativelyRenderedContent: null }));

  // Wait to ensure that the re-render has occurred before performing
  // the undo action.
  setTimeout(function () {
    updateFn(undoneState);
  }, 0);
}

module.exports = keyCommandUndo;

/***/ }),

/***/ "SatO":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/zh-hk.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var zhHk = moment.defineLocale('zh-hk', {
    months : '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
    monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
    weekdays : '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
    weekdaysShort : '週日_週一_週二_週三_週四_週五_週六'.split('_'),
    weekdaysMin : '日_一_二_三_四_五_六'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'YYYY/MM/DD',
        LL : 'YYYY年M月D日',
        LLL : 'YYYY年M月D日 HH:mm',
        LLLL : 'YYYY年M月D日dddd HH:mm',
        l : 'YYYY/M/D',
        ll : 'YYYY年M月D日',
        lll : 'YYYY年M月D日 HH:mm',
        llll : 'YYYY年M月D日dddd HH:mm'
    },
    meridiemParse: /凌晨|早上|上午|中午|下午|晚上/,
    meridiemHour : function (hour, meridiem) {
        if (hour === 12) {
            hour = 0;
        }
        if (meridiem === '凌晨' || meridiem === '早上' || meridiem === '上午') {
            return hour;
        } else if (meridiem === '中午') {
            return hour >= 11 ? hour : hour + 12;
        } else if (meridiem === '下午' || meridiem === '晚上') {
            return hour + 12;
        }
    },
    meridiem : function (hour, minute, isLower) {
        var hm = hour * 100 + minute;
        if (hm < 600) {
            return '凌晨';
        } else if (hm < 900) {
            return '早上';
        } else if (hm < 1130) {
            return '上午';
        } else if (hm < 1230) {
            return '中午';
        } else if (hm < 1800) {
            return '下午';
        } else {
            return '晚上';
        }
    },
    calendar : {
        sameDay : '[今天]LT',
        nextDay : '[明天]LT',
        nextWeek : '[下]ddddLT',
        lastDay : '[昨天]LT',
        lastWeek : '[上]ddddLT',
        sameElse : 'L'
    },
    dayOfMonthOrdinalParse: /\d{1,2}(日|月|週)/,
    ordinal : function (number, period) {
        switch (period) {
            case 'd' :
            case 'D' :
            case 'DDD' :
                return number + '日';
            case 'M' :
                return number + '月';
            case 'w' :
            case 'W' :
                return number + '週';
            default :
                return number;
        }
    },
    relativeTime : {
        future : '%s內',
        past : '%s前',
        s : '幾秒',
        ss : '%d 秒',
        m : '1 分鐘',
        mm : '%d 分鐘',
        h : '1 小時',
        hh : '%d 小時',
        d : '1 天',
        dd : '%d 天',
        M : '1 個月',
        MM : '%d 個月',
        y : '1 年',
        yy : '%d 年'
    }
});

return zhHk;

})));


/***/ }),

/***/ "SfRM":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_hashClear.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var nativeCreate = __webpack_require__(/*! ./_nativeCreate */ "YESw");

/**
 * Removes all key-value entries from the hash.
 *
 * @private
 * @name clear
 * @memberOf Hash
 */
function hashClear() {
  this.__data__ = nativeCreate ? nativeCreate(null) : {};
  this.size = 0;
}

module.exports = hashClear;


/***/ }),

/***/ "SlFw":
/*!**********************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/apputils/style/materialcolors.css ***!
  \**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/**\n * google-material-color v1.2.6\n * https://github.com/danlevan/google-material-color\n */\n:root {\n  --md-red-50: #ffebee;\n  --md-red-100: #ffcdd2;\n  --md-red-200: #ef9a9a;\n  --md-red-300: #e57373;\n  --md-red-400: #ef5350;\n  --md-red-500: #f44336;\n  --md-red-600: #e53935;\n  --md-red-700: #d32f2f;\n  --md-red-800: #c62828;\n  --md-red-900: #b71c1c;\n  --md-red-A100: #ff8a80;\n  --md-red-A200: #ff5252;\n  --md-red-A400: #ff1744;\n  --md-red-A700: #d50000;\n\n  --md-pink-50: #fce4ec;\n  --md-pink-100: #f8bbd0;\n  --md-pink-200: #f48fb1;\n  --md-pink-300: #f06292;\n  --md-pink-400: #ec407a;\n  --md-pink-500: #e91e63;\n  --md-pink-600: #d81b60;\n  --md-pink-700: #c2185b;\n  --md-pink-800: #ad1457;\n  --md-pink-900: #880e4f;\n  --md-pink-A100: #ff80ab;\n  --md-pink-A200: #ff4081;\n  --md-pink-A400: #f50057;\n  --md-pink-A700: #c51162;\n\n  --md-purple-50: #f3e5f5;\n  --md-purple-100: #e1bee7;\n  --md-purple-200: #ce93d8;\n  --md-purple-300: #ba68c8;\n  --md-purple-400: #ab47bc;\n  --md-purple-500: #9c27b0;\n  --md-purple-600: #8e24aa;\n  --md-purple-700: #7b1fa2;\n  --md-purple-800: #6a1b9a;\n  --md-purple-900: #4a148c;\n  --md-purple-A100: #ea80fc;\n  --md-purple-A200: #e040fb;\n  --md-purple-A400: #d500f9;\n  --md-purple-A700: #aa00ff;\n\n  --md-deep-purple-50: #ede7f6;\n  --md-deep-purple-100: #d1c4e9;\n  --md-deep-purple-200: #b39ddb;\n  --md-deep-purple-300: #9575cd;\n  --md-deep-purple-400: #7e57c2;\n  --md-deep-purple-500: #673ab7;\n  --md-deep-purple-600: #5e35b1;\n  --md-deep-purple-700: #512da8;\n  --md-deep-purple-800: #4527a0;\n  --md-deep-purple-900: #311b92;\n  --md-deep-purple-A100: #b388ff;\n  --md-deep-purple-A200: #7c4dff;\n  --md-deep-purple-A400: #651fff;\n  --md-deep-purple-A700: #6200ea;\n\n  --md-indigo-50: #e8eaf6;\n  --md-indigo-100: #c5cae9;\n  --md-indigo-200: #9fa8da;\n  --md-indigo-300: #7986cb;\n  --md-indigo-400: #5c6bc0;\n  --md-indigo-500: #3f51b5;\n  --md-indigo-600: #3949ab;\n  --md-indigo-700: #303f9f;\n  --md-indigo-800: #283593;\n  --md-indigo-900: #1a237e;\n  --md-indigo-A100: #8c9eff;\n  --md-indigo-A200: #536dfe;\n  --md-indigo-A400: #3d5afe;\n  --md-indigo-A700: #304ffe;\n\n  --md-blue-50: #e3f2fd;\n  --md-blue-100: #bbdefb;\n  --md-blue-200: #90caf9;\n  --md-blue-300: #64b5f6;\n  --md-blue-400: #42a5f5;\n  --md-blue-500: #2196f3;\n  --md-blue-600: #1e88e5;\n  --md-blue-700: #1976d2;\n  --md-blue-800: #1565c0;\n  --md-blue-900: #0d47a1;\n  --md-blue-A100: #82b1ff;\n  --md-blue-A200: #448aff;\n  --md-blue-A400: #2979ff;\n  --md-blue-A700: #2962ff;\n\n  --md-light-blue-50: #e1f5fe;\n  --md-light-blue-100: #b3e5fc;\n  --md-light-blue-200: #81d4fa;\n  --md-light-blue-300: #4fc3f7;\n  --md-light-blue-400: #29b6f6;\n  --md-light-blue-500: #03a9f4;\n  --md-light-blue-600: #039be5;\n  --md-light-blue-700: #0288d1;\n  --md-light-blue-800: #0277bd;\n  --md-light-blue-900: #01579b;\n  --md-light-blue-A100: #80d8ff;\n  --md-light-blue-A200: #40c4ff;\n  --md-light-blue-A400: #00b0ff;\n  --md-light-blue-A700: #0091ea;\n\n  --md-cyan-50: #e0f7fa;\n  --md-cyan-100: #b2ebf2;\n  --md-cyan-200: #80deea;\n  --md-cyan-300: #4dd0e1;\n  --md-cyan-400: #26c6da;\n  --md-cyan-500: #00bcd4;\n  --md-cyan-600: #00acc1;\n  --md-cyan-700: #0097a7;\n  --md-cyan-800: #00838f;\n  --md-cyan-900: #006064;\n  --md-cyan-A100: #84ffff;\n  --md-cyan-A200: #18ffff;\n  --md-cyan-A400: #00e5ff;\n  --md-cyan-A700: #00b8d4;\n\n  --md-teal-50: #e0f2f1;\n  --md-teal-100: #b2dfdb;\n  --md-teal-200: #80cbc4;\n  --md-teal-300: #4db6ac;\n  --md-teal-400: #26a69a;\n  --md-teal-500: #009688;\n  --md-teal-600: #00897b;\n  --md-teal-700: #00796b;\n  --md-teal-800: #00695c;\n  --md-teal-900: #004d40;\n  --md-teal-A100: #a7ffeb;\n  --md-teal-A200: #64ffda;\n  --md-teal-A400: #1de9b6;\n  --md-teal-A700: #00bfa5;\n\n  --md-green-50: #e8f5e9;\n  --md-green-100: #c8e6c9;\n  --md-green-200: #a5d6a7;\n  --md-green-300: #81c784;\n  --md-green-400: #66bb6a;\n  --md-green-500: #4caf50;\n  --md-green-600: #43a047;\n  --md-green-700: #388e3c;\n  --md-green-800: #2e7d32;\n  --md-green-900: #1b5e20;\n  --md-green-A100: #b9f6ca;\n  --md-green-A200: #69f0ae;\n  --md-green-A400: #00e676;\n  --md-green-A700: #00c853;\n\n  --md-light-green-50: #f1f8e9;\n  --md-light-green-100: #dcedc8;\n  --md-light-green-200: #c5e1a5;\n  --md-light-green-300: #aed581;\n  --md-light-green-400: #9ccc65;\n  --md-light-green-500: #8bc34a;\n  --md-light-green-600: #7cb342;\n  --md-light-green-700: #689f38;\n  --md-light-green-800: #558b2f;\n  --md-light-green-900: #33691e;\n  --md-light-green-A100: #ccff90;\n  --md-light-green-A200: #b2ff59;\n  --md-light-green-A400: #76ff03;\n  --md-light-green-A700: #64dd17;\n\n  --md-lime-50: #f9fbe7;\n  --md-lime-100: #f0f4c3;\n  --md-lime-200: #e6ee9c;\n  --md-lime-300: #dce775;\n  --md-lime-400: #d4e157;\n  --md-lime-500: #cddc39;\n  --md-lime-600: #c0ca33;\n  --md-lime-700: #afb42b;\n  --md-lime-800: #9e9d24;\n  --md-lime-900: #827717;\n  --md-lime-A100: #f4ff81;\n  --md-lime-A200: #eeff41;\n  --md-lime-A400: #c6ff00;\n  --md-lime-A700: #aeea00;\n\n  --md-yellow-50: #fffde7;\n  --md-yellow-100: #fff9c4;\n  --md-yellow-200: #fff59d;\n  --md-yellow-300: #fff176;\n  --md-yellow-400: #ffee58;\n  --md-yellow-500: #ffeb3b;\n  --md-yellow-600: #fdd835;\n  --md-yellow-700: #fbc02d;\n  --md-yellow-800: #f9a825;\n  --md-yellow-900: #f57f17;\n  --md-yellow-A100: #ffff8d;\n  --md-yellow-A200: #ffff00;\n  --md-yellow-A400: #ffea00;\n  --md-yellow-A700: #ffd600;\n\n  --md-amber-50: #fff8e1;\n  --md-amber-100: #ffecb3;\n  --md-amber-200: #ffe082;\n  --md-amber-300: #ffd54f;\n  --md-amber-400: #ffca28;\n  --md-amber-500: #ffc107;\n  --md-amber-600: #ffb300;\n  --md-amber-700: #ffa000;\n  --md-amber-800: #ff8f00;\n  --md-amber-900: #ff6f00;\n  --md-amber-A100: #ffe57f;\n  --md-amber-A200: #ffd740;\n  --md-amber-A400: #ffc400;\n  --md-amber-A700: #ffab00;\n\n  --md-orange-50: #fff3e0;\n  --md-orange-100: #ffe0b2;\n  --md-orange-200: #ffcc80;\n  --md-orange-300: #ffb74d;\n  --md-orange-400: #ffa726;\n  --md-orange-500: #ff9800;\n  --md-orange-600: #fb8c00;\n  --md-orange-700: #f57c00;\n  --md-orange-800: #ef6c00;\n  --md-orange-900: #e65100;\n  --md-orange-A100: #ffd180;\n  --md-orange-A200: #ffab40;\n  --md-orange-A400: #ff9100;\n  --md-orange-A700: #ff6d00;\n\n  --md-deep-orange-50: #fbe9e7;\n  --md-deep-orange-100: #ffccbc;\n  --md-deep-orange-200: #ffab91;\n  --md-deep-orange-300: #ff8a65;\n  --md-deep-orange-400: #ff7043;\n  --md-deep-orange-500: #ff5722;\n  --md-deep-orange-600: #f4511e;\n  --md-deep-orange-700: #e64a19;\n  --md-deep-orange-800: #d84315;\n  --md-deep-orange-900: #bf360c;\n  --md-deep-orange-A100: #ff9e80;\n  --md-deep-orange-A200: #ff6e40;\n  --md-deep-orange-A400: #ff3d00;\n  --md-deep-orange-A700: #dd2c00;\n\n  --md-brown-50: #efebe9;\n  --md-brown-100: #d7ccc8;\n  --md-brown-200: #bcaaa4;\n  --md-brown-300: #a1887f;\n  --md-brown-400: #8d6e63;\n  --md-brown-500: #795548;\n  --md-brown-600: #6d4c41;\n  --md-brown-700: #5d4037;\n  --md-brown-800: #4e342e;\n  --md-brown-900: #3e2723;\n\n  --md-grey-50: #fafafa;\n  --md-grey-100: #f5f5f5;\n  --md-grey-200: #eeeeee;\n  --md-grey-300: #e0e0e0;\n  --md-grey-400: #bdbdbd;\n  --md-grey-500: #9e9e9e;\n  --md-grey-600: #757575;\n  --md-grey-700: #616161;\n  --md-grey-800: #424242;\n  --md-grey-900: #212121;\n\n  --md-blue-grey-50: #eceff1;\n  --md-blue-grey-100: #cfd8dc;\n  --md-blue-grey-200: #b0bec5;\n  --md-blue-grey-300: #90a4ae;\n  --md-blue-grey-400: #78909c;\n  --md-blue-grey-500: #607d8b;\n  --md-blue-grey-600: #546e7a;\n  --md-blue-grey-700: #455a64;\n  --md-blue-grey-800: #37474f;\n  --md-blue-grey-900: #263238;\n}\n", ""]);

// exports


/***/ }),

/***/ "Sqtn":
/*!********************************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils-extension/lib/palette.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const commands_1 = __webpack_require__(/*! @phosphor/commands */ "5TpB");
const disposable_1 = __webpack_require__(/*! @phosphor/disposable */ "uNUc");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
/**
 * The command IDs used by the apputils extension.
 */
var CommandIDs;
(function (CommandIDs) {
    CommandIDs.activate = 'apputils:activate-command-palette';
})(CommandIDs || (CommandIDs = {}));
/**
 * A thin wrapper around the `CommandPalette` class to conform with the
 * JupyterLab interface for the application-wide command palette.
 */
class Palette {
    /**
     * Create a palette instance.
     */
    constructor(palette) {
        this._palette = palette;
        this._palette.title.iconClass = 'jp-PaletteIcon jp-SideBar-tabIcon';
        this._palette.title.label = '';
        this._palette.title.caption = 'Command Palette';
    }
    /**
     * The placeholder text of the command palette's search input.
     */
    set placeholder(placeholder) {
        this._palette.inputNode.placeholder = placeholder;
    }
    get placeholder() {
        return this._palette.inputNode.placeholder;
    }
    /**
     * Activate the command palette for user input.
     */
    activate() {
        this._palette.activate();
    }
    /**
     * Add a command item to the command palette.
     *
     * @param options - The options for creating the command item.
     *
     * @returns A disposable that will remove the item from the palette.
     */
    addItem(options) {
        let item = this._palette.addItem(options);
        return new disposable_1.DisposableDelegate(() => {
            this._palette.removeItem(item);
        });
    }
}
/**
 * Activate the command palette.
 */
function activatePalette(app) {
    const { commands, shell } = app;
    const palette = Private.createPalette(app);
    // Show the current palette shortcut in its title.
    const updatePaletteTitle = () => {
        const binding = algorithm_1.find(app.commands.keyBindings, b => b.command === CommandIDs.activate);
        if (binding) {
            const ks = commands_1.CommandRegistry.formatKeystroke(binding.keys.join(' '));
            palette.title.caption = `Commands (${ks})`;
        }
        else {
            palette.title.caption = 'Commands';
        }
    };
    updatePaletteTitle();
    app.commands.keyBindingChanged.connect(() => {
        updatePaletteTitle();
    });
    commands.addCommand(CommandIDs.activate, {
        execute: () => {
            shell.activateById(palette.id);
        },
        label: 'Activate Command Palette'
    });
    palette.inputNode.placeholder = 'SEARCH';
    shell.addToLeftArea(palette, { rank: 300 });
    return new Palette(palette);
}
exports.activatePalette = activatePalette;
/**
 * Restore the command palette.
 */
function restorePalette(app, restorer) {
    const palette = Private.createPalette(app);
    // Let the application restorer track the command palette for restoration of
    // application state (e.g. setting the command palette as the current side bar
    // widget).
    restorer.add(palette, 'command-palette');
}
exports.restorePalette = restorePalette;
/**
 * The namespace for module private data.
 */
var Private;
(function (Private) {
    /**
     * The private command palette instance.
     */
    let palette;
    /**
     * Create the application-wide command palette.
     */
    function createPalette(app) {
        if (!palette) {
            palette = new widgets_1.CommandPalette({ commands: app.commands });
            palette.id = 'command-palette';
            palette.title.label = 'Commands';
        }
        return palette;
    }
    Private.createPalette = createPalette;
})(Private || (Private = {}));


/***/ }),

/***/ "Syy6":
/*!***********************************************************************!*\
  !*** ./node_modules/react-color/lib/components/alpha/AlphaPointer.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.AlphaPointer = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var AlphaPointer = exports.AlphaPointer = function AlphaPointer(_ref) {
  var direction = _ref.direction;

  var styles = (0, _reactcss2.default)({
    'default': {
      picker: {
        width: '18px',
        height: '18px',
        borderRadius: '50%',
        transform: 'translate(-9px, -1px)',
        backgroundColor: 'rgb(248, 248, 248)',
        boxShadow: '0 1px 4px 0 rgba(0, 0, 0, 0.37)'
      }
    },
    'vertical': {
      picker: {
        transform: 'translate(-3px, -9px)'
      }
    }
  }, { vertical: direction === 'vertical' });

  return _react2.default.createElement('div', { style: styles.picker });
};

exports.default = AlphaPointer;

/***/ }),

/***/ "T/NO":
/*!************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/tooltip/style/index.css ***!
  \************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.jp-Tooltip {\n  background: var(--jp-layout-color1);\n  border: var(--jp-border-width) solid var(--jp-border-color1);\n  font-size: var(--jp-ui-font-size0);\n  box-shadow: var(--jp-elevation-z6);\n  max-width: 650px;\n  z-index: 10001;\n  padding: 4px;\n  display: flex;\n}\n\n.jp-Tooltip-content {\n  overflow: auto;\n}\n\n.jp-Tooltip:focus {\n  outline: 0;\n}\n\n.jp-Tooltip pre {\n  white-space: pre-wrap;\n  margin: 0;\n}\n", ""]);

// exports


/***/ }),

/***/ "T1AV":
/*!***********************************************!*\
  !*** ./node_modules/lodash/_baseMergeDeep.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var assignMergeValue = __webpack_require__(/*! ./_assignMergeValue */ "t2Dn"),
    cloneBuffer = __webpack_require__(/*! ./_cloneBuffer */ "5Tg0"),
    cloneTypedArray = __webpack_require__(/*! ./_cloneTypedArray */ "yP5f"),
    copyArray = __webpack_require__(/*! ./_copyArray */ "Q1l4"),
    initCloneObject = __webpack_require__(/*! ./_initCloneObject */ "+iFO"),
    isArguments = __webpack_require__(/*! ./isArguments */ "03A+"),
    isArray = __webpack_require__(/*! ./isArray */ "Z0cm"),
    isArrayLikeObject = __webpack_require__(/*! ./isArrayLikeObject */ "3L66"),
    isBuffer = __webpack_require__(/*! ./isBuffer */ "DSRE"),
    isFunction = __webpack_require__(/*! ./isFunction */ "lSCD"),
    isObject = __webpack_require__(/*! ./isObject */ "GoyQ"),
    isPlainObject = __webpack_require__(/*! ./isPlainObject */ "YO3V"),
    isTypedArray = __webpack_require__(/*! ./isTypedArray */ "c6wG"),
    safeGet = __webpack_require__(/*! ./_safeGet */ "itsj"),
    toPlainObject = __webpack_require__(/*! ./toPlainObject */ "jeLo");

/**
 * 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;


/***/ }),

/***/ "T2Ng":
/*!*********************************************************!*\
  !*** ./node_modules/@jupyterlab/mainmenu/lib/kernel.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const labmenu_1 = __webpack_require__(/*! ./labmenu */ "e7FE");
/**
 * An extensible Kernel menu for the application.
 */
class KernelMenu extends labmenu_1.JupyterLabMenu {
    /**
     * Construct the kernel menu.
     */
    constructor(options) {
        super(options);
        this.menu.title.label = 'Kernel';
        this.kernelUsers = new Set();
    }
    /**
     * Dispose of the resources held by the kernel menu.
     */
    dispose() {
        this.kernelUsers.clear();
        super.dispose();
    }
}
exports.KernelMenu = KernelMenu;


/***/ }),

/***/ "T3Nk":
/*!************************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/focustracker.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
var signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
/**
 * A class which tracks focus among a set of widgets.
 *
 * This class is useful when code needs to keep track of the most
 * recently focused widget(s) among a set of related widgets.
 */
var FocusTracker = (function () {
    /**
     * Construct a new focus tracker.
     */
    function FocusTracker() {
        this._counter = 0;
        this._widgets = [];
        this._activeWidget = null;
        this._currentWidget = null;
        this._numbers = new Map();
        this._nodes = new Map();
        this._activeChanged = new signaling_1.Signal(this);
        this._currentChanged = new signaling_1.Signal(this);
    }
    /**
     * Dispose of the resources held by the tracker.
     */
    FocusTracker.prototype.dispose = function () {
        var _this = this;
        // Do nothing if the tracker is already disposed.
        if (this._counter < 0) {
            return;
        }
        // Mark the tracker as disposed.
        this._counter = -1;
        // Clear the connections for the tracker.
        signaling_1.Signal.clearData(this);
        // Remove all event listeners.
        algorithm_1.each(this._widgets, function (w) {
            w.node.removeEventListener('focus', _this, true);
            w.node.removeEventListener('blur', _this, true);
        });
        // Clear the internal data structures.
        this._activeWidget = null;
        this._currentWidget = null;
        this._nodes.clear();
        this._numbers.clear();
        this._widgets.length = 0;
    };
    Object.defineProperty(FocusTracker.prototype, "currentChanged", {
        /**
         * A signal emitted when the current widget has changed.
         */
        get: function () {
            return this._currentChanged;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(FocusTracker.prototype, "activeChanged", {
        /**
         * A signal emitted when the active widget has changed.
         */
        get: function () {
            return this._activeChanged;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(FocusTracker.prototype, "isDisposed", {
        /**
         * A flag indicating whether the tracker is disposed.
         */
        get: function () {
            return this._counter < 0;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(FocusTracker.prototype, "currentWidget", {
        /**
         * The current widget in the tracker.
         *
         * #### Notes
         * The current widget is the widget among the tracked widgets which
         * has the *descendant node* which has most recently been focused.
         *
         * The current widget will not be updated if the node loses focus. It
         * will only be updated when a different tracked widget gains focus.
         *
         * If the current widget is removed from the tracker, the previous
         * current widget will be restored.
         *
         * This behavior is intended to follow a user's conceptual model of
         * a semantically "current" widget, where the "last thing of type X"
         * to be interacted with is the "current instance of X", regardless
         * of whether that instance still has focus.
         */
        get: function () {
            return this._currentWidget;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(FocusTracker.prototype, "activeWidget", {
        /**
         * The active widget in the tracker.
         *
         * #### Notes
         * The active widget is the widget among the tracked widgets which
         * has the *descendant node* which is currently focused.
         */
        get: function () {
            return this._activeWidget;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(FocusTracker.prototype, "widgets", {
        /**
         * A read only array of the widgets being tracked.
         */
        get: function () {
            return this._widgets;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Get the focus number for a particular widget in the tracker.
     *
     * @param widget - The widget of interest.
     *
     * @returns The focus number for the given widget, or `-1` if the
     *   widget has not had focus since being added to the tracker, or
     *   is not contained by the tracker.
     *
     * #### Notes
     * The focus number indicates the relative order in which the widgets
     * have gained focus. A widget with a larger number has gained focus
     * more recently than a widget with a smaller number.
     *
     * The `currentWidget` will always have the largest focus number.
     *
     * All widgets start with a focus number of `-1`, which indicates that
     * the widget has not been focused since being added to the tracker.
     */
    FocusTracker.prototype.focusNumber = function (widget) {
        var n = this._numbers.get(widget);
        return n === undefined ? -1 : n;
    };
    /**
     * Test whether the focus tracker contains a given widget.
     *
     * @param widget - The widget of interest.
     *
     * @returns `true` if the widget is tracked, `false` otherwise.
     */
    FocusTracker.prototype.has = function (widget) {
        return this._numbers.has(widget);
    };
    /**
     * Add a widget to the focus tracker.
     *
     * @param widget - The widget of interest.
     *
     * #### Notes
     * A widget will be automatically removed from the tracker if it
     * is disposed after being added.
     *
     * If the widget is already tracked, this is a no-op.
     */
    FocusTracker.prototype.add = function (widget) {
        // Do nothing if the widget is already tracked.
        if (this._numbers.has(widget)) {
            return;
        }
        // Test whether the widget has focus.
        var focused = widget.node.contains(document.activeElement);
        // Set up the initial focus number.
        var n = focused ? this._counter++ : -1;
        // Add the widget to the internal data structures.
        this._widgets.push(widget);
        this._numbers.set(widget, n);
        this._nodes.set(widget.node, widget);
        // Set up the event listeners. The capturing phase must be used
        // since the 'focus' and 'blur' events don't bubble and Firefox
        // doesn't support the 'focusin' or 'focusout' events.
        widget.node.addEventListener('focus', this, true);
        widget.node.addEventListener('blur', this, true);
        // Connect the disposed signal handler.
        widget.disposed.connect(this._onWidgetDisposed, this);
        // Set the current and active widgets if needed.
        if (focused) {
            this._setWidgets(widget, widget);
        }
    };
    /**
     * Remove a widget from the focus tracker.
     *
     * #### Notes
     * If the widget is the `currentWidget`, the previous current widget
     * will become the new `currentWidget`.
     *
     * A widget will be automatically removed from the tracker if it
     * is disposed after being added.
     *
     * If the widget is not tracked, this is a no-op.
     */
    FocusTracker.prototype.remove = function (widget) {
        var _this = this;
        // Bail early if the widget is not tracked.
        if (!this._numbers.has(widget)) {
            return;
        }
        // Disconnect the disposed signal handler.
        widget.disposed.disconnect(this._onWidgetDisposed, this);
        // Remove the event listeners.
        widget.node.removeEventListener('focus', this, true);
        widget.node.removeEventListener('blur', this, true);
        // Remove the widget from the internal data structures.
        algorithm_1.ArrayExt.removeFirstOf(this._widgets, widget);
        this._nodes.delete(widget.node);
        this._numbers.delete(widget);
        // Bail early if the widget is not the current widget.
        if (this._currentWidget !== widget) {
            return;
        }
        // Filter the widgets for those which have had focus.
        var valid = algorithm_1.filter(this._widgets, function (w) { return _this._numbers.get(w) !== -1; });
        // Get the valid widget with the max focus number.
        var previous = algorithm_1.max(valid, function (first, second) {
            var a = _this._numbers.get(first);
            var b = _this._numbers.get(second);
            return a - b;
        }) || null;
        // Set the current and active widgets.
        this._setWidgets(previous, null);
    };
    /**
     * Handle the DOM events for the focus tracker.
     *
     * @param event - The DOM event sent to the panel.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the tracked nodes. It should
     * not be called directly by user code.
     */
    FocusTracker.prototype.handleEvent = function (event) {
        switch (event.type) {
            case 'focus':
                this._evtFocus(event);
                break;
            case 'blur':
                this._evtBlur(event);
                break;
        }
    };
    /**
     * Set the current and active widgets for the tracker.
     */
    FocusTracker.prototype._setWidgets = function (current, active) {
        // Swap the current widget.
        var oldCurrent = this._currentWidget;
        this._currentWidget = current;
        // Swap the active widget.
        var oldActive = this._activeWidget;
        this._activeWidget = active;
        // Emit the `currentChanged` signal if needed.
        if (oldCurrent !== current) {
            this._currentChanged.emit({ oldValue: oldCurrent, newValue: current });
        }
        // Emit the `activeChanged` signal if needed.
        if (oldActive !== active) {
            this._activeChanged.emit({ oldValue: oldActive, newValue: active });
        }
    };
    /**
     * Handle the `'focus'` event for a tracked widget.
     */
    FocusTracker.prototype._evtFocus = function (event) {
        // Find the widget which gained focus, which is known to exist.
        var widget = this._nodes.get(event.currentTarget);
        // Update the focus number if necessary.
        if (widget !== this._currentWidget) {
            this._numbers.set(widget, this._counter++);
        }
        // Set the current and active widgets.
        this._setWidgets(widget, widget);
    };
    /**
     * Handle the `'blur'` event for a tracked widget.
     */
    FocusTracker.prototype._evtBlur = function (event) {
        // Find the widget which lost focus, which is known to exist.
        var widget = this._nodes.get(event.currentTarget);
        // Get the node which being focused after this blur.
        var focusTarget = event.relatedTarget;
        // If no other node is being focused, clear the active widget.
        if (!focusTarget) {
            this._setWidgets(this._currentWidget, null);
            return;
        }
        // Bail if the focus widget is not changing.
        if (widget.node.contains(focusTarget)) {
            return;
        }
        // If no tracked widget is being focused, clear the active widget.
        if (!algorithm_1.find(this._widgets, function (w) { return w.node.contains(focusTarget); })) {
            this._setWidgets(this._currentWidget, null);
            return;
        }
    };
    /**
     * Handle the `disposed` signal for a tracked widget.
     */
    FocusTracker.prototype._onWidgetDisposed = function (sender) {
        this.remove(sender);
    };
    return FocusTracker;
}());
exports.FocusTracker = FocusTracker;


/***/ }),

/***/ "T401":
/*!*****************************************************!*\
  !*** ./node_modules/draft-js/lib/isEventHandled.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule isEventHandled
 * @format
 * 
 */



/**
 * Utility method for determining whether or not the value returned
 * from a handler indicates that it was handled.
 */
function isEventHandled(value) {
  return value === 'handled' || value === true;
}

module.exports = isEventHandled;

/***/ }),

/***/ "T9HO":
/*!***************************************!*\
  !*** ./node_modules/sha.js/sha512.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var inherits = __webpack_require__(/*! inherits */ "P7XM")
var Hash = __webpack_require__(/*! ./hash */ "tnIz")
var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer

var K = [
  0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
  0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
  0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
  0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
  0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
  0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
  0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
  0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
  0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
  0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
  0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
  0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
  0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
  0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
  0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
  0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
  0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
  0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
  0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
  0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
  0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
  0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
  0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
  0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
  0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
  0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
  0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
  0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
  0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
  0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
  0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
  0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
  0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
  0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
  0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
  0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
  0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
  0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
  0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
  0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
]

var W = new Array(160)

function Sha512 () {
  this.init()
  this._w = W

  Hash.call(this, 128, 112)
}

inherits(Sha512, Hash)

Sha512.prototype.init = function () {
  this._ah = 0x6a09e667
  this._bh = 0xbb67ae85
  this._ch = 0x3c6ef372
  this._dh = 0xa54ff53a
  this._eh = 0x510e527f
  this._fh = 0x9b05688c
  this._gh = 0x1f83d9ab
  this._hh = 0x5be0cd19

  this._al = 0xf3bcc908
  this._bl = 0x84caa73b
  this._cl = 0xfe94f82b
  this._dl = 0x5f1d36f1
  this._el = 0xade682d1
  this._fl = 0x2b3e6c1f
  this._gl = 0xfb41bd6b
  this._hl = 0x137e2179

  return this
}

function Ch (x, y, z) {
  return z ^ (x & (y ^ z))
}

function maj (x, y, z) {
  return (x & y) | (z & (x | y))
}

function sigma0 (x, xl) {
  return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)
}

function sigma1 (x, xl) {
  return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)
}

function Gamma0 (x, xl) {
  return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)
}

function Gamma0l (x, xl) {
  return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)
}

function Gamma1 (x, xl) {
  return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)
}

function Gamma1l (x, xl) {
  return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)
}

function getCarry (a, b) {
  return (a >>> 0) < (b >>> 0) ? 1 : 0
}

Sha512.prototype._update = function (M) {
  var W = this._w

  var ah = this._ah | 0
  var bh = this._bh | 0
  var ch = this._ch | 0
  var dh = this._dh | 0
  var eh = this._eh | 0
  var fh = this._fh | 0
  var gh = this._gh | 0
  var hh = this._hh | 0

  var al = this._al | 0
  var bl = this._bl | 0
  var cl = this._cl | 0
  var dl = this._dl | 0
  var el = this._el | 0
  var fl = this._fl | 0
  var gl = this._gl | 0
  var hl = this._hl | 0

  for (var i = 0; i < 32; i += 2) {
    W[i] = M.readInt32BE(i * 4)
    W[i + 1] = M.readInt32BE(i * 4 + 4)
  }
  for (; i < 160; i += 2) {
    var xh = W[i - 15 * 2]
    var xl = W[i - 15 * 2 + 1]
    var gamma0 = Gamma0(xh, xl)
    var gamma0l = Gamma0l(xl, xh)

    xh = W[i - 2 * 2]
    xl = W[i - 2 * 2 + 1]
    var gamma1 = Gamma1(xh, xl)
    var gamma1l = Gamma1l(xl, xh)

    // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
    var Wi7h = W[i - 7 * 2]
    var Wi7l = W[i - 7 * 2 + 1]

    var Wi16h = W[i - 16 * 2]
    var Wi16l = W[i - 16 * 2 + 1]

    var Wil = (gamma0l + Wi7l) | 0
    var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0
    Wil = (Wil + gamma1l) | 0
    Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0
    Wil = (Wil + Wi16l) | 0
    Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0

    W[i] = Wih
    W[i + 1] = Wil
  }

  for (var j = 0; j < 160; j += 2) {
    Wih = W[j]
    Wil = W[j + 1]

    var majh = maj(ah, bh, ch)
    var majl = maj(al, bl, cl)

    var sigma0h = sigma0(ah, al)
    var sigma0l = sigma0(al, ah)
    var sigma1h = sigma1(eh, el)
    var sigma1l = sigma1(el, eh)

    // t1 = h + sigma1 + ch + K[j] + W[j]
    var Kih = K[j]
    var Kil = K[j + 1]

    var chh = Ch(eh, fh, gh)
    var chl = Ch(el, fl, gl)

    var t1l = (hl + sigma1l) | 0
    var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0
    t1l = (t1l + chl) | 0
    t1h = (t1h + chh + getCarry(t1l, chl)) | 0
    t1l = (t1l + Kil) | 0
    t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0
    t1l = (t1l + Wil) | 0
    t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0

    // t2 = sigma0 + maj
    var t2l = (sigma0l + majl) | 0
    var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0

    hh = gh
    hl = gl
    gh = fh
    gl = fl
    fh = eh
    fl = el
    el = (dl + t1l) | 0
    eh = (dh + t1h + getCarry(el, dl)) | 0
    dh = ch
    dl = cl
    ch = bh
    cl = bl
    bh = ah
    bl = al
    al = (t1l + t2l) | 0
    ah = (t1h + t2h + getCarry(al, t1l)) | 0
  }

  this._al = (this._al + al) | 0
  this._bl = (this._bl + bl) | 0
  this._cl = (this._cl + cl) | 0
  this._dl = (this._dl + dl) | 0
  this._el = (this._el + el) | 0
  this._fl = (this._fl + fl) | 0
  this._gl = (this._gl + gl) | 0
  this._hl = (this._hl + hl) | 0

  this._ah = (this._ah + ah + getCarry(this._al, al)) | 0
  this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0
  this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0
  this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0
  this._eh = (this._eh + eh + getCarry(this._el, el)) | 0
  this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0
  this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0
  this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0
}

Sha512.prototype._hash = function () {
  var H = Buffer.allocUnsafe(64)

  function writeInt64BE (h, l, offset) {
    H.writeInt32BE(h, offset)
    H.writeInt32BE(l, offset + 4)
  }

  writeInt64BE(this._ah, this._al, 0)
  writeInt64BE(this._bh, this._bl, 8)
  writeInt64BE(this._ch, this._cl, 16)
  writeInt64BE(this._dh, this._dl, 24)
  writeInt64BE(this._eh, this._el, 32)
  writeInt64BE(this._fh, this._fl, 40)
  writeInt64BE(this._gh, this._gl, 48)
  writeInt64BE(this._hh, this._hl, 56)

  return H
}

module.exports = Sha512


/***/ }),

/***/ "TAZq":
/*!*************************************************!*\
  !*** ./node_modules/stylis-rule-sheet/index.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

(function (factory) {
	 true ? (module['exports'] = factory()) :
		undefined
}(function () {

	'use strict'

	return function (insertRule) {
		var delimiter = '/*|*/'
		var needle = delimiter+'}'

		function toSheet (block) {
			if (block)
				try {
					insertRule(block + '}')
				} catch (e) {}
		}

		return function ruleSheet (context, content, selectors, parents, line, column, length, ns, depth, at) {
			switch (context) {
				// property
				case 1:
					// @import
					if (depth === 0 && content.charCodeAt(0) === 64)
						return insertRule(content+';'), ''
					break
				// selector
				case 2:
					if (ns === 0)
						return content + delimiter
					break
				// at-rule
				case 3:
					switch (ns) {
						// @font-face, @page
						case 102:
						case 112:
							return insertRule(selectors[0]+content), ''
						default:
							return content + (at === 0 ? delimiter : '')
					}
				case -2:
					content.split(needle).forEach(toSheet)
			}
		}
	}
}))


/***/ }),

/***/ "TEEm":
/*!********************************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/plots/animation_attributes.js ***!
  \********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



module.exports = {
    mode: {
        valType: 'enumerated',
        dflt: 'afterall',
        role: 'info',
        values: ['immediate', 'next', 'afterall'],
        description: [
            'Describes how a new animate call interacts with currently-running',
            'animations. If `immediate`, current animations are interrupted and',
            'the new animation is started. If `next`, the current frame is allowed',
            'to complete, after which the new animation is started. If `afterall`',
            'all existing frames are animated to completion before the new animation',
            'is started.'
        ].join(' ')
    },
    direction: {
        valType: 'enumerated',
        role: 'info',
        values: ['forward', 'reverse'],
        dflt: 'forward',
        description: [
            'The direction in which to play the frames triggered by the animation call'
        ].join(' ')
    },
    fromcurrent: {
        valType: 'boolean',
        dflt: false,
        role: 'info',
        description: [
            'Play frames starting at the current frame instead of the beginning.'
        ].join(' ')
    },
    frame: {
        duration: {
            valType: 'number',
            role: 'info',
            min: 0,
            dflt: 500,
            description: [
                'The duration in milliseconds of each frame. If greater than the frame',
                'duration, it will be limited to the frame duration.'
            ].join(' ')
        },
        redraw: {
            valType: 'boolean',
            role: 'info',
            dflt: true,
            description: [
                'Redraw the plot at completion of the transition. This is desirable',
                'for transitions that include properties that cannot be transitioned,',
                'but may significantly slow down updates that do not require a full',
                'redraw of the plot'
            ].join(' ')
        },
    },
    transition: {
        duration: {
            valType: 'number',
            role: 'info',
            min: 0,
            dflt: 500,
            editType: 'none',
            description: [
                'The duration of the transition, in milliseconds. If equal to zero,',
                'updates are synchronous.'
            ].join(' ')
        },
        easing: {
            valType: 'enumerated',
            dflt: 'cubic-in-out',
            values: [
                'linear',
                'quad',
                'cubic',
                'sin',
                'exp',
                'circle',
                'elastic',
                'back',
                'bounce',
                'linear-in',
                'quad-in',
                'cubic-in',
                'sin-in',
                'exp-in',
                'circle-in',
                'elastic-in',
                'back-in',
                'bounce-in',
                'linear-out',
                'quad-out',
                'cubic-out',
                'sin-out',
                'exp-out',
                'circle-out',
                'elastic-out',
                'back-out',
                'bounce-out',
                'linear-in-out',
                'quad-in-out',
                'cubic-in-out',
                'sin-in-out',
                'exp-in-out',
                'circle-in-out',
                'elastic-in-out',
                'back-in-out',
                'bounce-in-out'
            ],
            role: 'info',
            editType: 'none',
            description: 'The easing function used for the transition'
        },
        ordering: {
            valType: 'enumerated',
            values: ['layout first', 'traces first'],
            dflt: 'layout first',
            role: 'info',
            editType: 'none',
            description: [
                'Determines whether the figure\'s layout or traces smoothly transitions',
                'during updates that make both traces and layout change.'
            ].join(' ')
        }
    }
};


/***/ }),

/***/ "THLb":
/*!*******************************************************!*\
  !*** ./node_modules/react-color/lib/helpers/alpha.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var calculateChange = exports.calculateChange = function calculateChange(e, skip, props, container) {
  e.preventDefault();
  var containerWidth = container.clientWidth;
  var containerHeight = container.clientHeight;
  var x = typeof e.pageX === 'number' ? e.pageX : e.touches[0].pageX;
  var y = typeof e.pageY === 'number' ? e.pageY : e.touches[0].pageY;
  var left = x - (container.getBoundingClientRect().left + window.pageXOffset);
  var top = y - (container.getBoundingClientRect().top + window.pageYOffset);

  if (props.direction === 'vertical') {
    var a = void 0;
    if (top < 0) {
      a = 0;
    } else if (top > containerHeight) {
      a = 1;
    } else {
      a = Math.round(top * 100 / containerHeight) / 100;
    }

    if (props.hsl.a !== a) {
      return {
        h: props.hsl.h,
        s: props.hsl.s,
        l: props.hsl.l,
        a: a,
        source: 'rgb'
      };
    }
  } else {
    var _a = void 0;
    if (left < 0) {
      _a = 0;
    } else if (left > containerWidth) {
      _a = 1;
    } else {
      _a = Math.round(left * 100 / containerWidth) / 100;
    }

    if (props.a !== _a) {
      return {
        h: props.hsl.h,
        s: props.hsl.s,
        l: props.hsl.l,
        a: _a,
        source: 'rgb'
      };
    }
  }
  return null;
};

/***/ }),

/***/ "TIjV":
/*!*********************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/list.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
/**
 * Contains helpers for safely splitting lists of CSS values,
 * preserving parentheses and quotes.
 *
 * @example
 * const list = postcss.list;
 *
 * @namespace list
 */
var list = {
    split: function split(string, separators, last) {
        var array = [];
        var current = '';
        var split = false;

        var func = 0;
        var quote = false;
        var escape = false;

        for (var i = 0; i < string.length; i++) {
            var letter = string[i];

            if (quote) {
                if (escape) {
                    escape = false;
                } else if (letter === '\\') {
                    escape = true;
                } else if (letter === quote) {
                    quote = false;
                }
            } else if (letter === '"' || letter === '\'') {
                quote = letter;
            } else if (letter === '(') {
                func += 1;
            } else if (letter === ')') {
                if (func > 0) func -= 1;
            } else if (func === 0) {
                if (separators.indexOf(letter) !== -1) split = true;
            }

            if (split) {
                if (current !== '') array.push(current.trim());
                current = '';
                split = false;
            } else {
                current += letter;
            }
        }

        if (last || current !== '') array.push(current.trim());
        return array;
    },


    /**
     * Safely splits space-separated values (such as those for `background`,
     * `border-radius`, and other shorthand properties).
     *
     * @param {string} string - space-separated values
     *
     * @return {string[]} split values
     *
     * @example
     * postcss.list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)']
     */
    space: function space(string) {
        var spaces = [' ', '\n', '\t'];
        return list.split(string, spaces);
    },


    /**
     * Safely splits comma-separated values (such as those for `transition-*`
     * and `background` properties).
     *
     * @param {string} string - comma-separated values
     *
     * @return {string[]} split values
     *
     * @example
     * postcss.list.comma('black, linear-gradient(white, black)')
     * //=> ['black', 'linear-gradient(white, black)']
     */
    comma: function comma(string) {
        var comma = ',';
        return list.split(string, [comma], true);
    }
};

exports.default = list;
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64, 


/***/ }),

/***/ "TM95":
/*!*****************************************************************!*\
  !*** ./node_modules/react-color/lib/components/common/index.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _Alpha = __webpack_require__(/*! ./Alpha */ "yOY4");

Object.defineProperty(exports, 'Alpha', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Alpha).default;
  }
});

var _Checkboard = __webpack_require__(/*! ./Checkboard */ "Nq3d");

Object.defineProperty(exports, 'Checkboard', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Checkboard).default;
  }
});

var _EditableInput = __webpack_require__(/*! ./EditableInput */ "AnK5");

Object.defineProperty(exports, 'EditableInput', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_EditableInput).default;
  }
});

var _Hue = __webpack_require__(/*! ./Hue */ "HlQe");

Object.defineProperty(exports, 'Hue', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Hue).default;
  }
});

var _Raised = __webpack_require__(/*! ./Raised */ "Ojt5");

Object.defineProperty(exports, 'Raised', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Raised).default;
  }
});

var _Saturation = __webpack_require__(/*! ./Saturation */ "ccyi");

Object.defineProperty(exports, 'Saturation', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Saturation).default;
  }
});

var _ColorWrap = __webpack_require__(/*! ./ColorWrap */ "UGzO");

Object.defineProperty(exports, 'ColorWrap', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_ColorWrap).default;
  }
});

var _Swatch = __webpack_require__(/*! ./Swatch */ "Ba7A");

Object.defineProperty(exports, 'Swatch', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Swatch).default;
  }
});

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/***/ }),

/***/ "TOwV":
/*!****************************************!*\
  !*** ./node_modules/react-is/index.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


if (false) {} else {
  module.exports = __webpack_require__(/*! ./cjs/react-is.development.js */ "qPUD");
}


/***/ }),

/***/ "TPoW":
/*!************************************************************************!*\
  !*** ./node_modules/@jupyterlab/settingeditor/style/settingeditor.css ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./settingeditor.css */ "OyzV");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "TR4g":
/*!**********************************************!*\
  !*** ./node_modules/domelementtype/index.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

//Types of elements found in the DOM
module.exports = {
	Text: "text", //Text
	Directive: "directive", //<? ... ?>
	Comment: "comment", //<!-- ... -->
	Script: "script", //<script> tags
	Style: "style", //<style> tags
	Tag: "tag", //Any tag
	CDATA: "cdata", //<![CDATA[ ... ]]>
	Doctype: "doctype",

	isTag: function(elem){
		return elem.type === "tag" || elem.type === "script" || elem.type === "style";
	}
};


/***/ }),

/***/ "TSYQ":
/*!******************************************!*\
  !*** ./node_modules/classnames/index.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
  Copyright (c) 2017 Jed Watson.
  Licensed under the MIT License (MIT), see
  http://jedwatson.github.io/classnames
*/
/* global define */

(function () {
	'use strict';

	var hasOwn = {}.hasOwnProperty;

	function classNames () {
		var classes = [];

		for (var i = 0; i < arguments.length; i++) {
			var arg = arguments[i];
			if (!arg) continue;

			var argType = typeof arg;

			if (argType === 'string' || argType === 'number') {
				classes.push(arg);
			} else if (Array.isArray(arg) && arg.length) {
				var inner = classNames.apply(null, arg);
				if (inner) {
					classes.push(inner);
				}
			} else if (argType === 'object') {
				for (var key in arg) {
					if (hasOwn.call(arg, key) && arg[key]) {
						classes.push(key);
					}
				}
			}
		}

		return classes.join(' ');
	}

	if (typeof module !== 'undefined' && module.exports) {
		classNames.default = classNames;
		module.exports = classNames;
	} else if (true) {
		// register as 'classnames', consistent with npm package name
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () {
			return classNames;
		}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {}
}());


/***/ }),

/***/ "TT7y":
/*!**********************************************************************!*\
  !*** ./node_modules/@plotly/draft-js-export-html/lib/stateToHTML.js ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _DEFAULT_STYLE_MAP, _ENTITY_ATTR_MAP, _DATA_TO_ATTR;

exports.default = stateToHTML;

var _combineOrderedStyles3 = __webpack_require__(/*! ./helpers/combineOrderedStyles */ "yVpg");

var _combineOrderedStyles4 = _interopRequireDefault(_combineOrderedStyles3);

var _normalizeAttributes = __webpack_require__(/*! ./helpers/normalizeAttributes */ "k2Qq");

var _normalizeAttributes2 = _interopRequireDefault(_normalizeAttributes);

var _styleToCSS = __webpack_require__(/*! ./helpers/styleToCSS */ "dMc4");

var _styleToCSS2 = _interopRequireDefault(_styleToCSS);

var _draftJsUtils = __webpack_require__(/*! draft-js-utils */ "24WU");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var BOLD = _draftJsUtils.INLINE_STYLE.BOLD,
    CODE = _draftJsUtils.INLINE_STYLE.CODE,
    ITALIC = _draftJsUtils.INLINE_STYLE.ITALIC,
    STRIKETHROUGH = _draftJsUtils.INLINE_STYLE.STRIKETHROUGH,
    UNDERLINE = _draftJsUtils.INLINE_STYLE.UNDERLINE;


var INDENT = '  ';
var BREAK = '<br>';
var DATA_ATTRIBUTE = /^data-([a-z0-9-]+)$/;

var DEFAULT_STYLE_MAP = (_DEFAULT_STYLE_MAP = {}, _defineProperty(_DEFAULT_STYLE_MAP, BOLD, { element: 'strong' }), _defineProperty(_DEFAULT_STYLE_MAP, CODE, { element: 'code' }), _defineProperty(_DEFAULT_STYLE_MAP, ITALIC, { element: 'em' }), _defineProperty(_DEFAULT_STYLE_MAP, STRIKETHROUGH, { element: 'del' }), _defineProperty(_DEFAULT_STYLE_MAP, UNDERLINE, { element: 'u' }), _DEFAULT_STYLE_MAP);

// Order: inner-most style to outer-most.
// Examle: <em><strong>foo</strong></em>
var DEFAULT_STYLE_ORDER = [BOLD, ITALIC, UNDERLINE, STRIKETHROUGH, CODE];

// Map entity data to element attributes.
var ENTITY_ATTR_MAP = (_ENTITY_ATTR_MAP = {}, _defineProperty(_ENTITY_ATTR_MAP, _draftJsUtils.ENTITY_TYPE.LINK, {
  url: 'href',
  href: 'href',
  rel: 'rel',
  target: 'target',
  title: 'title',
  className: 'class'
}), _defineProperty(_ENTITY_ATTR_MAP, _draftJsUtils.ENTITY_TYPE.IMAGE, {
  src: 'src',
  height: 'height',
  width: 'width',
  alt: 'alt',
  className: 'class'
}), _ENTITY_ATTR_MAP);

// Map entity data to element attributes.
var DATA_TO_ATTR = (_DATA_TO_ATTR = {}, _defineProperty(_DATA_TO_ATTR, _draftJsUtils.ENTITY_TYPE.LINK, function (entityType, entity) {
  var attrMap = ENTITY_ATTR_MAP.hasOwnProperty(entityType) ? ENTITY_ATTR_MAP[entityType] : {};
  var data = entity.getData();
  var attrs = {};
  var _iteratorNormalCompletion = true;
  var _didIteratorError = false;
  var _iteratorError = undefined;

  try {
    for (var _iterator = Object.keys(data)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
      var dataKey = _step.value;

      var dataValue = data[dataKey];
      if (attrMap.hasOwnProperty(dataKey)) {
        var attrKey = attrMap[dataKey];
        attrs[attrKey] = dataValue;
      } else if (DATA_ATTRIBUTE.test(dataKey)) {
        attrs[dataKey] = dataValue;
      }
    }
  } catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion && _iterator.return) {
        _iterator.return();
      }
    } finally {
      if (_didIteratorError) {
        throw _iteratorError;
      }
    }
  }

  return attrs;
}), _defineProperty(_DATA_TO_ATTR, _draftJsUtils.ENTITY_TYPE.IMAGE, function (entityType, entity) {
  var attrMap = ENTITY_ATTR_MAP.hasOwnProperty(entityType) ? ENTITY_ATTR_MAP[entityType] : {};
  var data = entity.getData();
  var attrs = {};
  var _iteratorNormalCompletion2 = true;
  var _didIteratorError2 = false;
  var _iteratorError2 = undefined;

  try {
    for (var _iterator2 = Object.keys(data)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
      var dataKey = _step2.value;

      var dataValue = data[dataKey];
      if (attrMap.hasOwnProperty(dataKey)) {
        var attrKey = attrMap[dataKey];
        attrs[attrKey] = dataValue;
      } else if (DATA_ATTRIBUTE.test(dataKey)) {
        attrs[dataKey] = dataValue;
      }
    }
  } catch (err) {
    _didIteratorError2 = true;
    _iteratorError2 = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion2 && _iterator2.return) {
        _iterator2.return();
      }
    } finally {
      if (_didIteratorError2) {
        throw _iteratorError2;
      }
    }
  }

  return attrs;
}), _DATA_TO_ATTR);

// The reason this returns an array is because a single block might get wrapped
// in two tags.
function getTags(blockType, defaultBlockTag) {
  switch (blockType) {
    case _draftJsUtils.BLOCK_TYPE.HEADER_ONE:
      return ['h1'];
    case _draftJsUtils.BLOCK_TYPE.HEADER_TWO:
      return ['h2'];
    case _draftJsUtils.BLOCK_TYPE.HEADER_THREE:
      return ['h3'];
    case _draftJsUtils.BLOCK_TYPE.HEADER_FOUR:
      return ['h4'];
    case _draftJsUtils.BLOCK_TYPE.HEADER_FIVE:
      return ['h5'];
    case _draftJsUtils.BLOCK_TYPE.HEADER_SIX:
      return ['h6'];
    case _draftJsUtils.BLOCK_TYPE.UNORDERED_LIST_ITEM:
    case _draftJsUtils.BLOCK_TYPE.ORDERED_LIST_ITEM:
      return ['li'];
    case _draftJsUtils.BLOCK_TYPE.BLOCKQUOTE:
      return ['blockquote'];
    case _draftJsUtils.BLOCK_TYPE.CODE:
      return ['pre', 'code'];
    case _draftJsUtils.BLOCK_TYPE.ATOMIC:
      return ['figure'];
    default:
      if (defaultBlockTag === null) {
        return [];
      }
      return [defaultBlockTag || 'p'];
  }
}

function getWrapperTag(blockType) {
  switch (blockType) {
    case _draftJsUtils.BLOCK_TYPE.UNORDERED_LIST_ITEM:
      return 'ul';
    case _draftJsUtils.BLOCK_TYPE.ORDERED_LIST_ITEM:
      return 'ol';
    default:
      return null;
  }
}

var MarkupGenerator = function () {
  // These are related to state.
  function MarkupGenerator(contentState, options) {
    _classCallCheck(this, MarkupGenerator);

    if (options == null) {
      options = {};
    }
    this.contentState = contentState;
    this.options = options;

    var _combineOrderedStyles = (0, _combineOrderedStyles4.default)(options.inlineStyles, [DEFAULT_STYLE_MAP, DEFAULT_STYLE_ORDER]),
        _combineOrderedStyles2 = _slicedToArray(_combineOrderedStyles, 2),
        inlineStyles = _combineOrderedStyles2[0],
        styleOrder = _combineOrderedStyles2[1];

    this.inlineStyles = inlineStyles;
    this.styleOrder = styleOrder;
  }
  // These are related to user-defined options.


  _createClass(MarkupGenerator, [{
    key: 'generate',
    value: function generate() {
      this.output = [];
      this.blocks = this.contentState.getBlocksAsArray();
      this.totalBlocks = this.blocks.length;
      this.currentBlock = 0;
      this.indentLevel = 0;
      this.wrapperTag = null;
      while (this.currentBlock < this.totalBlocks) {
        this.processBlock();
      }
      this.closeWrapperTag();
      return this.output.join('').trim();
    }
  }, {
    key: 'processBlock',
    value: function processBlock() {
      var _options = this.options,
          blockRenderers = _options.blockRenderers,
          defaultBlockTag = _options.defaultBlockTag;

      var block = this.blocks[this.currentBlock];
      var blockType = block.getType();
      var newWrapperTag = getWrapperTag(blockType);
      if (this.wrapperTag !== newWrapperTag) {
        if (this.wrapperTag) {
          this.closeWrapperTag();
        }
        if (newWrapperTag) {
          this.openWrapperTag(newWrapperTag);
        }
      }
      this.indent();
      // Allow blocks to be rendered using a custom renderer.
      var customRenderer = blockRenderers != null && blockRenderers.hasOwnProperty(blockType) ? blockRenderers[blockType] : null;
      var customRendererOutput = customRenderer ? customRenderer(block) : null;
      // Renderer can return null, which will cause processing to continue as normal.
      if (customRendererOutput != null) {
        this.output.push(customRendererOutput);
        this.output.push('\n');
        this.currentBlock += 1;
        return;
      }
      this.writeStartTag(block, defaultBlockTag);
      this.output.push(this.renderBlockContent(block));
      // Look ahead and see if we will nest list.
      var nextBlock = this.getNextBlock();
      if (canHaveDepth(blockType) && nextBlock && nextBlock.getDepth() === block.getDepth() + 1) {
        this.output.push('\n');
        // This is a litle hacky: temporarily stash our current wrapperTag and
        // render child list(s).
        var thisWrapperTag = this.wrapperTag;
        this.wrapperTag = null;
        this.indentLevel += 1;
        this.currentBlock += 1;
        this.processBlocksAtDepth(nextBlock.getDepth());
        this.wrapperTag = thisWrapperTag;
        this.indentLevel -= 1;
        this.indent();
      } else {
        this.currentBlock += 1;
      }
      this.writeEndTag(block, defaultBlockTag);
    }
  }, {
    key: 'processBlocksAtDepth',
    value: function processBlocksAtDepth(depth) {
      var block = this.blocks[this.currentBlock];
      while (block && block.getDepth() === depth) {
        this.processBlock();
        block = this.blocks[this.currentBlock];
      }
      this.closeWrapperTag();
    }
  }, {
    key: 'getNextBlock',
    value: function getNextBlock() {
      return this.blocks[this.currentBlock + 1];
    }
  }, {
    key: 'writeStartTag',
    value: function writeStartTag(block, defaultBlockTag) {
      var tags = getTags(block.getType(), defaultBlockTag);

      var attrString = void 0;
      if (this.options.blockStyleFn) {
        var _ref = this.options.blockStyleFn(block) || {},
            _attributes = _ref.attributes,
            _style = _ref.style;
        // Normalize `className` -> `class`, etc.


        _attributes = (0, _normalizeAttributes2.default)(_attributes);
        if (_style != null) {
          var styleAttr = (0, _styleToCSS2.default)(_style);
          _attributes = _attributes == null ? { style: styleAttr } : _extends({}, _attributes, { style: styleAttr });
        }
        attrString = stringifyAttrs(_attributes);
      } else {
        attrString = '';
      }

      var _iteratorNormalCompletion3 = true;
      var _didIteratorError3 = false;
      var _iteratorError3 = undefined;

      try {
        for (var _iterator3 = tags[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
          var tag = _step3.value;

          this.output.push('<' + tag + attrString + '>');
        }
      } catch (err) {
        _didIteratorError3 = true;
        _iteratorError3 = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion3 && _iterator3.return) {
            _iterator3.return();
          }
        } finally {
          if (_didIteratorError3) {
            throw _iteratorError3;
          }
        }
      }
    }
  }, {
    key: 'writeEndTag',
    value: function writeEndTag(block, defaultBlockTag) {
      var tags = getTags(block.getType(), defaultBlockTag);
      if (tags.length === 1) {
        this.output.push('</' + tags[0] + '>\n');
      } else {
        var output = [];
        var _iteratorNormalCompletion4 = true;
        var _didIteratorError4 = false;
        var _iteratorError4 = undefined;

        try {
          for (var _iterator4 = tags[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
            var tag = _step4.value;

            output.unshift('</' + tag + '>');
          }
        } catch (err) {
          _didIteratorError4 = true;
          _iteratorError4 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion4 && _iterator4.return) {
              _iterator4.return();
            }
          } finally {
            if (_didIteratorError4) {
              throw _iteratorError4;
            }
          }
        }

        this.output.push(output.join('') + '\n');
      }
    }
  }, {
    key: 'openWrapperTag',
    value: function openWrapperTag(wrapperTag) {
      this.wrapperTag = wrapperTag;
      this.indent();
      this.output.push('<' + wrapperTag + '>\n');
      this.indentLevel += 1;
    }
  }, {
    key: 'closeWrapperTag',
    value: function closeWrapperTag() {
      var wrapperTag = this.wrapperTag;

      if (wrapperTag) {
        this.indentLevel -= 1;
        this.indent();
        this.output.push('</' + wrapperTag + '>\n');
        this.wrapperTag = null;
      }
    }
  }, {
    key: 'indent',
    value: function indent() {
      this.output.push(INDENT.repeat(this.indentLevel));
    }
  }, {
    key: 'renderBlockContent',
    value: function renderBlockContent(block) {
      var _this = this;

      var blockType = block.getType();
      var text = block.getText();
      if (text === '') {
        // Prevent element collapse if completely empty.
        return BREAK;
      }
      text = this.preserveWhitespace(text);
      var charMetaList = block.getCharacterList();
      var entityPieces = (0, _draftJsUtils.getEntityRanges)(text, charMetaList);
      return entityPieces.map(function (_ref2) {
        var _ref3 = _slicedToArray(_ref2, 2),
            entityKey = _ref3[0],
            stylePieces = _ref3[1];

        var content = stylePieces.map(function (_ref4) {
          var _ref5 = _slicedToArray(_ref4, 2),
              text = _ref5[0],
              styleSet = _ref5[1];

          var content = encodeContent(text);
          var _iteratorNormalCompletion5 = true;
          var _didIteratorError5 = false;
          var _iteratorError5 = undefined;

          try {
            for (var _iterator5 = _this.styleOrder[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
              var _styleName = _step5.value;

              // If our block type is CODE then don't wrap inline code elements.
              if (_styleName === CODE && blockType === _draftJsUtils.BLOCK_TYPE.CODE) {
                continue;
              }
              if (styleSet.has(_styleName)) {
                var _inlineStyles$_styleN = _this.inlineStyles[_styleName],
                    _element = _inlineStyles$_styleN.element,
                    _attributes2 = _inlineStyles$_styleN.attributes,
                    _style2 = _inlineStyles$_styleN.style;

                if (_element == null) {
                  _element = 'span';
                }
                // Normalize `className` -> `class`, etc.
                _attributes2 = (0, _normalizeAttributes2.default)(_attributes2);
                if (_style2 != null) {
                  var styleAttr = (0, _styleToCSS2.default)(_style2);
                  _attributes2 = _attributes2 == null ? { style: styleAttr } : _extends({}, _attributes2, { style: styleAttr });
                }
                var attrString = stringifyAttrs(_attributes2);
                content = '<' + _element + attrString + '>' + content + '</' + _element + '>';
              }
            }
          } catch (err) {
            _didIteratorError5 = true;
            _iteratorError5 = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion5 && _iterator5.return) {
                _iterator5.return();
              }
            } finally {
              if (_didIteratorError5) {
                throw _iteratorError5;
              }
            }
          }

          return content;
        }).join('');
        var entity = entityKey ? _this.contentState.getEntity(entityKey) : null;
        // Note: The `toUpperCase` below is for compatability with some libraries that use lower-case for image blocks.
        var entityType = entity == null ? null : entity.getType().toUpperCase();
        var entityStyle = void 0;
        if (entity != null && _this.options.entityStyleFn && (entityStyle = _this.options.entityStyleFn(entity))) {
          var _entityStyle = entityStyle,
              _element2 = _entityStyle.element,
              _attributes3 = _entityStyle.attributes,
              _style3 = _entityStyle.style;

          if (_element2 == null) {
            _element2 = 'span';
          }
          // Normalize `className` -> `class`, etc.
          _attributes3 = (0, _normalizeAttributes2.default)(_attributes3);
          if (_style3 != null) {
            var styleAttr = (0, _styleToCSS2.default)(_style3);
            _attributes3 = _attributes3 == null ? { style: styleAttr } : _extends({}, _attributes3, { style: styleAttr });
          }
          var attrString = stringifyAttrs(_attributes3);
          return '<' + _element2 + attrString + '>' + content + '</' + _element2 + '>';
        } else if (entityType != null && entityType === _draftJsUtils.ENTITY_TYPE.LINK) {
          var attrs = DATA_TO_ATTR.hasOwnProperty(entityType) ? DATA_TO_ATTR[entityType](entityType, entity) : null;
          var _attrString = stringifyAttrs(attrs);
          return '<a' + _attrString + '>' + content + '</a>';
        } else if (entityType != null && entityType === _draftJsUtils.ENTITY_TYPE.IMAGE) {
          var _attrs = DATA_TO_ATTR.hasOwnProperty(entityType) ? DATA_TO_ATTR[entityType](entityType, entity) : null;
          var _attrString2 = stringifyAttrs(_attrs);
          return '<img' + _attrString2 + '/>';
        } else {
          return content;
        }
      }).join('');
    }
  }, {
    key: 'preserveWhitespace',
    value: function preserveWhitespace(text) {
      var length = text.length;
      // Prevent leading/trailing/consecutive whitespace collapse.
      var newText = new Array(length);
      for (var i = 0; i < length; i++) {
        if (text[i] === ' ' && (i === 0 || i === length - 1 || text[i - 1] === ' ')) {
          newText[i] = '\xA0';
        } else {
          newText[i] = text[i];
        }
      }
      return newText.join('');
    }
  }]);

  return MarkupGenerator;
}();

function stringifyAttrs(attrs) {
  if (attrs == null) {
    return '';
  }
  var parts = [];
  var _iteratorNormalCompletion6 = true;
  var _didIteratorError6 = false;
  var _iteratorError6 = undefined;

  try {
    for (var _iterator6 = Object.keys(attrs)[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
      var name = _step6.value;

      var value = attrs[name];
      if (value != null) {
        parts.push(' ' + name + '="' + encodeAttr(value + '') + '"');
      }
    }
  } catch (err) {
    _didIteratorError6 = true;
    _iteratorError6 = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion6 && _iterator6.return) {
        _iterator6.return();
      }
    } finally {
      if (_didIteratorError6) {
        throw _iteratorError6;
      }
    }
  }

  return parts.join('');
}

function canHaveDepth(blockType) {
  switch (blockType) {
    case _draftJsUtils.BLOCK_TYPE.UNORDERED_LIST_ITEM:
    case _draftJsUtils.BLOCK_TYPE.ORDERED_LIST_ITEM:
      return true;
    default:
      return false;
  }
}

function encodeContent(text) {
  return text.split('&').join('&amp;').split('<').join('&lt;').split('>').join('&gt;').split('\xA0').join('&nbsp;').split('\n').join(BREAK + '\n');
}

function encodeAttr(text) {
  return text.split('&').join('&amp;').split('<').join('&lt;').split('>').join('&gt;').split('"').join('&quot;');
}

function stateToHTML(content, options) {
  return new MarkupGenerator(content, options).generate();
}

/***/ }),

/***/ "TWoB":
/*!***********************************************!*\
  !*** ./node_modules/fbjs/lib/containsNode.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * 
 */

var isTextNode = __webpack_require__(/*! ./isTextNode */ "SQ0G");

/*eslint-disable no-bitwise */

/**
 * Checks if a given DOM node contains or is another DOM node.
 */
function containsNode(outerNode, innerNode) {
  if (!outerNode || !innerNode) {
    return false;
  } else if (outerNode === innerNode) {
    return true;
  } else if (isTextNode(outerNode)) {
    return false;
  } else if (isTextNode(innerNode)) {
    return containsNode(outerNode, innerNode.parentNode);
  } else if ('contains' in outerNode) {
    return outerNode.contains(innerNode);
  } else if (outerNode.compareDocumentPosition) {
    return !!(outerNode.compareDocumentPosition(innerNode) & 16);
  } else {
    return false;
  }
}

module.exports = containsNode;

/***/ }),

/***/ "TYdR":
/*!**************************************************!*\
  !*** ./node_modules/mdi-react/TagOutlineIcon.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var TagOutlineIcon = function TagOutlineIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M5.5,7C6.33,7 7,6.33 7,5.5C7,4.67 6.33,4 5.5,4C4.67,4 4,4.67 4,5.5C4,6.33 4.67,7 5.5,7M21.41,11.58C21.77,11.94 22,12.44 22,13C22,13.55 21.78,14.05 21.41,14.41L14.41,21.41C14.05,21.77 13.55,22 13,22C12.45,22 11.95,21.77 11.58,21.41L2.59,12.41C2.22,12.05 2,11.55 2,11V4C2,2.89 2.89,2 4,2H11C11.55,2 12.05,2.22 12.41,2.58L21.41,11.58M13,20L20,13L11.5,4.5L4.5,11.5L13,20Z' })
  );
};

module.exports = TagOutlineIcon;


/***/ }),

/***/ "Taje":
/*!**********************************************************!*\
  !*** ./node_modules/draft-js/lib/findRangesImmutable.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule findRangesImmutable
 * @format
 * 
 */



/**
 * Search through an array to find contiguous stretches of elements that
 * match a specified filter function.
 *
 * When ranges are found, execute a specified `found` function to supply
 * the values to the caller.
 */
function findRangesImmutable(haystack, areEqualFn, filterFn, foundFn) {
  if (!haystack.size) {
    return;
  }

  var cursor = 0;

  haystack.reduce(function (value, nextValue, nextIndex) {
    if (!areEqualFn(value, nextValue)) {
      if (filterFn(value)) {
        foundFn(cursor, nextIndex);
      }
      cursor = nextIndex;
    }
    return nextValue;
  });

  filterFn(haystack.last()) && foundFn(cursor, haystack.count());
}

module.exports = findRangesImmutable;

/***/ }),

/***/ "TbEC":
/*!*********************************************!*\
  !*** ./node_modules/ajv/lib/dotjs/oneOf.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_oneOf(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  out += 'var ' + ($errs) + ' = errors;var prevValid' + ($lvl) + ' = false;var ' + ($valid) + ' = false;';
  var $currentBaseId = $it.baseId;
  var $wasComposite = it.compositeRule;
  it.compositeRule = $it.compositeRule = true;
  var arr1 = $schema;
  if (arr1) {
    var $sch, $i = -1,
      l1 = arr1.length - 1;
    while ($i < l1) {
      $sch = arr1[$i += 1];
      if (it.util.schemaHasRules($sch, it.RULES.all)) {
        $it.schema = $sch;
        $it.schemaPath = $schemaPath + '[' + $i + ']';
        $it.errSchemaPath = $errSchemaPath + '/' + $i;
        out += '  ' + (it.validate($it)) + ' ';
        $it.baseId = $currentBaseId;
      } else {
        out += ' var ' + ($nextValid) + ' = true; ';
      }
      if ($i) {
        out += ' if (' + ($nextValid) + ' && prevValid' + ($lvl) + ') ' + ($valid) + ' = false; else { ';
        $closingBraces += '}';
      }
      out += ' if (' + ($nextValid) + ') ' + ($valid) + ' = prevValid' + ($lvl) + ' = true;';
    }
  }
  it.compositeRule = $it.compositeRule = $wasComposite;
  out += '' + ($closingBraces) + 'if (!' + ($valid) + ') {   var err =   '; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should match exactly one schema in oneOf\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError(vErrors); ';
    } else {
      out += ' validate.errors = vErrors; return false; ';
    }
  }
  out += '} else {  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }';
  if (it.opts.allErrors) {
    out += ' } ';
  }
  return out;
}


/***/ }),

/***/ "Tco+":
/*!**************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/cells/style/collapser.css ***!
  \**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.jp-Collapser {\n  flex: 0 0 var(--jp-cell-collapser-width);\n  padding: 0px;\n  margin: 0px;\n  border: none;\n  outline: none;\n  background: transparent;\n  border-radius: var(--jp-border-radius);\n  opacity: 1;\n}\n\n.jp-Collapser-child {\n  display: block;\n  width: 100%;\n  box-sizing: border-box;\n  /* height: 100% doesn't work because the height of its parent is computed from content */\n  position: absolute;\n  top: 0px;\n  bottom: 0px;\n}\n", ""]);

// exports


/***/ }),

/***/ "TdD3":
/*!********************************************!*\
  !*** ./node_modules/parse-asn1/fixProc.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// adapted from https://github.com/apatil/pemstrip
var findProc = /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r\+\/\=]+)[\n\r]+/m
var startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m
var fullRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r\+\/\=]+)-----END \1-----$/m
var evp = __webpack_require__(/*! evp_bytestokey */ "roQf")
var ciphers = __webpack_require__(/*! browserify-aes */ "/ab2")
var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer
module.exports = function (okey, password) {
  var key = okey.toString()
  var match = key.match(findProc)
  var decrypted
  if (!match) {
    var match2 = key.match(fullRegex)
    decrypted = new Buffer(match2[2].replace(/[\r\n]/g, ''), 'base64')
  } else {
    var suite = 'aes' + match[1]
    var iv = Buffer.from(match[2], 'hex')
    var cipherText = Buffer.from(match[3].replace(/[\r\n]/g, ''), 'base64')
    var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key
    var out = []
    var cipher = ciphers.createDecipheriv(suite, cipherKey, iv)
    out.push(cipher.update(cipherText))
    out.push(cipher.final())
    decrypted = Buffer.concat(out)
  }
  var tag = key.match(startRegex)[1]
  return {
    tag: tag,
    data: decrypted
  }
}


/***/ }),

/***/ "Te0A":
/*!****************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/index.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.PanelMessage = exports.ModalProvider = exports.Modal = exports.TraceTypeSection = exports.SingleSidebarItem = exports.AxesFold = exports.LayoutSection = exports.LayoutPanel = exports.TraceRequiredPanel = exports.TraceMarkerSection = exports.TransformAccordion = exports.TraceAccordion = exports.SubplotAccordion = exports.Section = exports.PlotlySection = exports.PanelEmpty = exports.Panel = exports.PlotlyPanel = exports.Fold = exports.PlotlyFold = exports.MenuPanel = exports.RangeSelectorAccordion = exports.UpdateMenuAccordion = exports.ImageAccordion = exports.SliderAccordion = exports.ShapeAccordion = exports.AnnotationAccordion = undefined;

var _AnnotationAccordion = __webpack_require__(/*! ./AnnotationAccordion */ "weFL");

var _AnnotationAccordion2 = _interopRequireDefault(_AnnotationAccordion);

var _ShapeAccordion = __webpack_require__(/*! ./ShapeAccordion */ "cexl");

var _ShapeAccordion2 = _interopRequireDefault(_ShapeAccordion);

var _SliderAccordion = __webpack_require__(/*! ./SliderAccordion */ "uR0c");

var _SliderAccordion2 = _interopRequireDefault(_SliderAccordion);

var _ImageAccordion = __webpack_require__(/*! ./ImageAccordion */ "fNzb");

var _ImageAccordion2 = _interopRequireDefault(_ImageAccordion);

var _UpdateMenuAccordion = __webpack_require__(/*! ./UpdateMenuAccordion */ "3cnA");

var _UpdateMenuAccordion2 = _interopRequireDefault(_UpdateMenuAccordion);

var _RangeSelectorAccordion = __webpack_require__(/*! ./RangeSelectorAccordion */ "gB9I");

var _RangeSelectorAccordion2 = _interopRequireDefault(_RangeSelectorAccordion);

var _AxesFold = __webpack_require__(/*! ./AxesFold */ "vS4K");

var _AxesFold2 = _interopRequireDefault(_AxesFold);

var _PlotlyFold = __webpack_require__(/*! ./PlotlyFold */ "mQPs");

var _PlotlyFold2 = _interopRequireDefault(_PlotlyFold);

var _MenuPanel = __webpack_require__(/*! ./MenuPanel */ "WS6A");

var _MenuPanel2 = _interopRequireDefault(_MenuPanel);

var _PlotlyPanel = __webpack_require__(/*! ./PlotlyPanel */ "54u7");

var _PlotlyPanel2 = _interopRequireDefault(_PlotlyPanel);

var _PlotlySection = __webpack_require__(/*! ./PlotlySection */ "aR6p");

var _PlotlySection2 = _interopRequireDefault(_PlotlySection);

var _PanelEmpty = __webpack_require__(/*! ./PanelEmpty */ "o21U");

var _PanelEmpty2 = _interopRequireDefault(_PanelEmpty);

var _SubplotAccordion = __webpack_require__(/*! ./SubplotAccordion */ "94vc");

var _SubplotAccordion2 = _interopRequireDefault(_SubplotAccordion);

var _TraceAccordion = __webpack_require__(/*! ./TraceAccordion */ "vmI6");

var _TraceAccordion2 = _interopRequireDefault(_TraceAccordion);

var _TransformAccordion = __webpack_require__(/*! ./TransformAccordion */ "zcT5");

var _TransformAccordion2 = _interopRequireDefault(_TransformAccordion);

var _TraceMarkerSection = __webpack_require__(/*! ./TraceMarkerSection */ "1hgy");

var _TraceMarkerSection2 = _interopRequireDefault(_TraceMarkerSection);

var _derived = __webpack_require__(/*! ./derived */ "ykRn");

var _TraceRequiredPanel = __webpack_require__(/*! ./TraceRequiredPanel */ "IBvg");

var _TraceRequiredPanel2 = _interopRequireDefault(_TraceRequiredPanel);

var _SingleSidebarItem = __webpack_require__(/*! ./SingleSidebarItem */ "djUo");

var _SingleSidebarItem2 = _interopRequireDefault(_SingleSidebarItem);

var _ModalProvider = __webpack_require__(/*! ./ModalProvider */ "e0n3");

var _ModalProvider2 = _interopRequireDefault(_ModalProvider);

var _Modal = __webpack_require__(/*! ./Modal */ "caab");

var _Modal2 = _interopRequireDefault(_Modal);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.AnnotationAccordion = _AnnotationAccordion2.default;
exports.ShapeAccordion = _ShapeAccordion2.default;
exports.SliderAccordion = _SliderAccordion2.default;
exports.ImageAccordion = _ImageAccordion2.default;
exports.UpdateMenuAccordion = _UpdateMenuAccordion2.default;
exports.RangeSelectorAccordion = _RangeSelectorAccordion2.default;
exports.MenuPanel = _MenuPanel2.default;
exports.PlotlyFold = _PlotlyFold2.default;
exports.Fold = _PlotlyFold.Fold;
exports.PlotlyPanel = _PlotlyPanel2.default;
exports.Panel = _PlotlyPanel.Panel;
exports.PanelEmpty = _PanelEmpty2.default;
exports.PlotlySection = _PlotlySection2.default;
exports.Section = _PlotlySection.Section;
exports.SubplotAccordion = _SubplotAccordion2.default;
exports.TraceAccordion = _TraceAccordion2.default;
exports.TransformAccordion = _TransformAccordion2.default;
exports.TraceMarkerSection = _TraceMarkerSection2.default;
exports.TraceRequiredPanel = _TraceRequiredPanel2.default;
exports.LayoutPanel = _derived.LayoutPanel;
exports.LayoutSection = _derived.LayoutSection;
exports.AxesFold = _AxesFold2.default;
exports.SingleSidebarItem = _SingleSidebarItem2.default;
exports.TraceTypeSection = _derived.TraceTypeSection;
exports.Modal = _Modal2.default;
exports.ModalProvider = _ModalProvider2.default;
exports.PanelMessage = _PanelEmpty.PanelMessage;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ "Titl":
/*!********************************************!*\
  !*** ./node_modules/des.js/lib/des/des.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var assert = __webpack_require__(/*! minimalistic-assert */ "2j6C");
var inherits = __webpack_require__(/*! inherits */ "P7XM");

var des = __webpack_require__(/*! ../des */ "FUXG");
var utils = des.utils;
var Cipher = des.Cipher;

function DESState() {
  this.tmp = new Array(2);
  this.keys = null;
}

function DES(options) {
  Cipher.call(this, options);

  var state = new DESState();
  this._desState = state;

  this.deriveKeys(state, options.key);
}
inherits(DES, Cipher);
module.exports = DES;

DES.create = function create(options) {
  return new DES(options);
};

var shiftTable = [
  1, 1, 2, 2, 2, 2, 2, 2,
  1, 2, 2, 2, 2, 2, 2, 1
];

DES.prototype.deriveKeys = function deriveKeys(state, key) {
  state.keys = new Array(16 * 2);

  assert.equal(key.length, this.blockSize, 'Invalid key length');

  var kL = utils.readUInt32BE(key, 0);
  var kR = utils.readUInt32BE(key, 4);

  utils.pc1(kL, kR, state.tmp, 0);
  kL = state.tmp[0];
  kR = state.tmp[1];
  for (var i = 0; i < state.keys.length; i += 2) {
    var shift = shiftTable[i >>> 1];
    kL = utils.r28shl(kL, shift);
    kR = utils.r28shl(kR, shift);
    utils.pc2(kL, kR, state.keys, i);
  }
};

DES.prototype._update = function _update(inp, inOff, out, outOff) {
  var state = this._desState;

  var l = utils.readUInt32BE(inp, inOff);
  var r = utils.readUInt32BE(inp, inOff + 4);

  // Initial Permutation
  utils.ip(l, r, state.tmp, 0);
  l = state.tmp[0];
  r = state.tmp[1];

  if (this.type === 'encrypt')
    this._encrypt(state, l, r, state.tmp, 0);
  else
    this._decrypt(state, l, r, state.tmp, 0);

  l = state.tmp[0];
  r = state.tmp[1];

  utils.writeUInt32BE(out, l, outOff);
  utils.writeUInt32BE(out, r, outOff + 4);
};

DES.prototype._pad = function _pad(buffer, off) {
  var value = buffer.length - off;
  for (var i = off; i < buffer.length; i++)
    buffer[i] = value;

  return true;
};

DES.prototype._unpad = function _unpad(buffer) {
  var pad = buffer[buffer.length - 1];
  for (var i = buffer.length - pad; i < buffer.length; i++)
    assert.equal(buffer[i], pad);

  return buffer.slice(0, buffer.length - pad);
};

DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) {
  var l = lStart;
  var r = rStart;

  // Apply f() x16 times
  for (var i = 0; i < state.keys.length; i += 2) {
    var keyL = state.keys[i];
    var keyR = state.keys[i + 1];

    // f(r, k)
    utils.expand(r, state.tmp, 0);

    keyL ^= state.tmp[0];
    keyR ^= state.tmp[1];
    var s = utils.substitute(keyL, keyR);
    var f = utils.permute(s);

    var t = r;
    r = (l ^ f) >>> 0;
    l = t;
  }

  // Reverse Initial Permutation
  utils.rip(r, l, out, off);
};

DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) {
  var l = rStart;
  var r = lStart;

  // Apply f() x16 times
  for (var i = state.keys.length - 2; i >= 0; i -= 2) {
    var keyL = state.keys[i];
    var keyR = state.keys[i + 1];

    // f(r, k)
    utils.expand(l, state.tmp, 0);

    keyL ^= state.tmp[0];
    keyR ^= state.tmp[1];
    var s = utils.substitute(keyL, keyR);
    var f = utils.permute(s);

    var t = l;
    l = (r ^ f) >>> 0;
    r = t;
  }

  // Reverse Initial Permutation
  utils.rip(l, r, out, off);
};


/***/ }),

/***/ "TkTV":
/*!***********************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/result.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _warning = __webpack_require__(/*! ./warning */ "bTsU");

var _warning2 = _interopRequireDefault(_warning);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Provides the result of the PostCSS transformations.
 *
 * A Result instance is returned by {@link LazyResult#then}
 * or {@link Root#toResult} methods.
 *
 * @example
 * postcss([cssnext]).process(css).then(function (result) {
 *    console.log(result.css);
 * });
 *
 * @example
 * var result2 = postcss.parse(css).toResult();
 */
var Result = function () {

  /**
   * @param {Processor} processor - processor used for this transformation.
   * @param {Root}      root      - Root node after all transformations.
   * @param {processOptions} opts - options from the {@link Processor#process}
   *                                or {@link Root#toResult}
   */
  function Result(processor, root, opts) {
    _classCallCheck(this, Result);

    /**
     * @member {Processor} - The Processor instance used
     *                       for this transformation.
     *
     * @example
     * for ( let plugin of result.processor.plugins) {
     *   if ( plugin.postcssPlugin === 'postcss-bad' ) {
     *     throw 'postcss-good is incompatible with postcss-bad';
     *   }
     * });
     */
    this.processor = processor;
    /**
     * @member {Message[]} - Contains messages from plugins
     *                       (e.g., warnings or custom messages).
     *                       Each message should have type
     *                       and plugin properties.
     *
     * @example
     * postcss.plugin('postcss-min-browser', () => {
     *   return (root, result) => {
     *     var browsers = detectMinBrowsersByCanIUse(root);
     *     result.messages.push({
     *       type:    'min-browser',
     *       plugin:  'postcss-min-browser',
     *       browsers: browsers
     *     });
     *   };
     * });
     */
    this.messages = [];
    /**
     * @member {Root} - Root node after all transformations.
     *
     * @example
     * root.toResult().root == root;
     */
    this.root = root;
    /**
     * @member {processOptions} - Options from the {@link Processor#process}
     *                            or {@link Root#toResult} call
     *                            that produced this Result instance.
     *
     * @example
     * root.toResult(opts).opts == opts;
     */
    this.opts = opts;
    /**
     * @member {string} - A CSS string representing of {@link Result#root}.
     *
     * @example
     * postcss.parse('a{}').toResult().css //=> "a{}"
     */
    this.css = undefined;
    /**
     * @member {SourceMapGenerator} - An instance of `SourceMapGenerator`
     *                                class from the `source-map` library,
     *                                representing changes
     *                                to the {@link Result#root} instance.
     *
     * @example
     * result.map.toJSON() //=> { version: 3, file: 'a.css', … }
     *
     * @example
     * if ( result.map ) {
     *   fs.writeFileSync(result.opts.to + '.map', result.map.toString());
     * }
     */
    this.map = undefined;
  }

  /**
   * Returns for @{link Result#css} content.
   *
   * @example
   * result + '' === result.css
   *
   * @return {string} string representing of {@link Result#root}
   */


  Result.prototype.toString = function toString() {
    return this.css;
  };

  /**
   * Creates an instance of {@link Warning} and adds it
   * to {@link Result#messages}.
   *
   * @param {string} text        - warning message
   * @param {Object} [opts]      - warning options
   * @param {Node}   opts.node   - CSS node that caused the warning
   * @param {string} opts.word   - word in CSS source that caused the warning
   * @param {number} opts.index  - index in CSS node string that caused
   *                               the warning
   * @param {string} opts.plugin - name of the plugin that created
   *                               this warning. {@link Result#warn} fills
   *                               this property automatically.
   *
   * @return {Warning} created warning
   */


  Result.prototype.warn = function warn(text) {
    var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

    if (!opts.plugin) {
      if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
        opts.plugin = this.lastPlugin.postcssPlugin;
      }
    }

    var warning = new _warning2.default(text, opts);
    this.messages.push(warning);

    return warning;
  };

  /**
   * Returns warnings from plugins. Filters {@link Warning} instances
   * from {@link Result#messages}.
   *
   * @example
   * result.warnings().forEach(warn => {
   *   console.warn(warn.toString());
   * });
   *
   * @return {Warning[]} warnings from plugins
   */


  Result.prototype.warnings = function warnings() {
    return this.messages.filter(function (i) {
      return i.type === 'warning';
    });
  };

  /**
   * An alias for the {@link Result#css} property.
   * Use it with syntaxes that generate non-CSS output.
   * @type {string}
   *
   * @example
   * result.css === result.content;
   */


  _createClass(Result, [{
    key: 'content',
    get: function get() {
      return this.css;
    }
  }]);

  return Result;
}();

exports.default = Result;

/**
 * @typedef  {object} Message
 * @property {string} type   - message type
 * @property {string} plugin - source PostCSS plugin name
 */

module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64, 


/***/ }),

/***/ "TkbC":
/*!**********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/computeTraceOptionsFromSchema.js ***!
  \**********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
function computeTraceOptionsFromSchema(schema, _, context) {
  // Filter out Polar "area" type as it is fairly broken and we want to present
  // scatter with fill as an "area" chart type for convenience.
  var traceTypes = Object.keys(schema.traces).filter(function (t) {
    return !['area', 'scattermapbox'].includes(t);
  });

  var traceOptions = [{
    value: 'scatter',
    label: _('Scatter')
  }, {
    value: 'box',
    label: _('Box')
  }, {
    value: 'bar',
    label: _('Bar')
  }, {
    value: 'heatmap',
    label: _('Heatmap')
  }, {
    value: 'histogram',
    label: _('Histogram')
  }, {
    value: 'histogram2d',
    label: _('2D Histogram')
  }, {
    value: 'histogram2dcontour',
    label: _('2D Contour Histogram')
  }, {
    value: 'pie',
    label: _('Pie')
  }, {
    value: 'contour',
    label: _('Contour')
  }, {
    value: 'scatterternary',
    label: _('Ternary Scatter')
  }, {
    value: 'violin',
    label: _('Violin')
  }, {
    value: 'scatter3d',
    label: _('3D Scatter')
  }, {
    value: 'surface',
    label: _('Surface')
  }, {
    value: 'mesh3d',
    label: _('3D Mesh')
  }, {
    value: 'cone',
    label: _('Cone')
  }, {
    value: 'streamtube',
    label: _('Streamtube')
  }, {
    value: 'scattergeo',
    label: _('Atlas Map')
  }, {
    value: 'choropleth',
    label: _('Choropleth')
  }, {
    value: 'scattergl',
    label: _('Scatter GL')
  }, {
    value: 'pointcloud',
    label: _('Point Cloud')
  }, {
    value: 'heatmapgl',
    label: _('Heatmap GL')
  }, {
    value: 'parcoords',
    label: _('Parallel Coordinates')
  }, {
    value: 'sankey',
    label: _('Sankey')
  }, {
    value: 'table',
    label: _('Table')
  }, {
    value: 'carpet',
    label: _('Carpet')
  }, {
    value: 'scattercarpet',
    label: _('Carpet Scatter')
  }, {
    value: 'contourcarpet',
    label: _('Carpet Contour')
  }, {
    value: 'ohlc',
    label: _('OHLC')
  }, {
    value: 'candlestick',
    label: _('Candlestick')
  }, {
    value: 'scatterpolar',
    label: _('Polar Scatter')
  }, {
    value: 'scatterpolargl',
    label: _('Polar Scatter GL')
  }, {
    value: 'barpolar',
    label: _('Polar Bar')
  }, {
    value: 'isosurface',
    label: _('Isosurface')
  }].filter(function (obj) {
    return traceTypes.indexOf(obj.value) !== -1;
  });

  var traceIndex = function traceIndex(traceType) {
    return traceOptions.findIndex(function (opt) {
      return opt.value === traceType;
    });
  };

  traceOptions.splice(traceIndex('scatter') + 1, 0, { label: _('Line'), value: 'line' }, { label: _('Area'), value: 'area' }, { label: _('Timeseries'), value: 'timeseries' });

  traceOptions.splice(traceIndex('scatter3d') + 1, 0, {
    label: _('3D Line'),
    value: 'line3d'
  });

  if (context.config && context.config.mapboxAccessToken) {
    traceOptions.push({
      value: 'scattermapbox',
      label: _('Satellite Map')
    });
  }

  return traceOptions;
}

exports.computeTraceOptionsFromSchema = computeTraceOptionsFromSchema;
//# sourceMappingURL=computeTraceOptionsFromSchema.js.map

/***/ }),

/***/ "TlXQ":
/*!**********************************************************!*\
  !*** ./node_modules/draft-js/lib/createCharacterList.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule createCharacterList
 * @format
 * 
 */



var CharacterMetadata = __webpack_require__(/*! ./CharacterMetadata */ "lFJn");
var Immutable = __webpack_require__(/*! immutable */ "JPcv");

var List = Immutable.List;


function createCharacterList(inlineStyles, entities) {
  var characterArray = inlineStyles.map(function (style, ii) {
    var entity = entities[ii];
    return CharacterMetadata.create({ style: style, entity: entity });
  });
  return List(characterArray);
}

module.exports = createCharacterList;

/***/ }),

/***/ "Towz":
/*!**********************************************************!*\
  !*** ./node_modules/@jupyterlab/rendermime/lib/index.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
__webpack_require__(/*! ../style/index.css */ "eTKl"); // Why is this first?
__export(__webpack_require__(/*! ./attachmentmodel */ "53Ql"));
__export(__webpack_require__(/*! ./factories */ "gfI5"));
__export(__webpack_require__(/*! ./latex */ "lOjS"));
__export(__webpack_require__(/*! ./mimemodel */ "qXhn"));
__export(__webpack_require__(/*! ./outputmodel */ "7WuX"));
__export(__webpack_require__(/*! ./registry */ "/VUM"));
__export(__webpack_require__(/*! ./renderers */ "A1bG"));
__export(__webpack_require__(/*! ./widgets */ "75di"));


/***/ }),

/***/ "TpJo":
/*!************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeTableIcon.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeTableIcon = function TraceTypeTableIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement('path', { fill: 'none', d: 'M0 0h46v46H0z' }),
        _react2.default.createElement('path', { fill: '#1d9bfb', d: 'M8 8h16v6H8z' }),
        _react2.default.createElement('path', { fill: '#fff', d: 'M8 14h16v6H8z' }),
        _react2.default.createElement('path', { fill: '#1d9bfb', d: 'M8 20h16v6H8z' }),
        _react2.default.createElement('path', { fill: '#fff', d: 'M8 26h16v6H8z' }),
        _react2.default.createElement('path', { fill: '#1d9bfb', d: 'M8 32h16v6H8zM26 8h12v6H26z' }),
        _react2.default.createElement('path', { fill: '#fff', d: 'M26 14h12v6H26z' }),
        _react2.default.createElement('path', { fill: '#1d9bfb', d: 'M26 20h12v6H26z' }),
        _react2.default.createElement('path', { fill: '#fff', d: 'M26 26h12v6H26z' }),
        _react2.default.createElement('path', { fill: '#1d9bfb', d: 'M26 32h12v6H26z' }),
        _react2.default.createElement('path', { fill: 'none', stroke: '#25fdfc', d: 'M21 11H11m10 12H11', strokeMiterlimit: '10', strokeWidth: '2' }),
        _react2.default.createElement('path', { fill: 'none', stroke: '#1d9bfb', d: 'M21 17H11m10 12H11', strokeMiterlimit: '10', strokeWidth: '2' }),
        _react2.default.createElement('path', { fill: 'none', stroke: '#25fdfc', d: 'M21 35H11m24-24h-6m6 12h-6', strokeMiterlimit: '10', strokeWidth: '2' }),
        _react2.default.createElement('path', { fill: 'none', stroke: '#1d9bfb', d: 'M35 17h-6m6 12h-6', strokeMiterlimit: '10', strokeWidth: '2' }),
        _react2.default.createElement('path', { fill: 'none', stroke: '#25fdfc', d: 'M35 35h-6', strokeMiterlimit: '10', strokeWidth: '2' }),
        _react2.default.createElement('path', { fill: '#1d9bfb', d: 'M24 8h2v30h-2z' }),
        _react2.default.createElement('path', { fill: '#25fdfc', d: 'M24 8h2v6h-2zm0 12h2v6h-2zm0 12h2v6h-2z' })
    );
};

exports.default = TraceTypeTableIcon;

/***/ }),

/***/ "Tv0l":
/*!************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/strings.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/*eslint-disable */

/**
 * Capitalize string
 */
function capitalize(s) {
  return !s ? '' : s.charAt(0).toUpperCase() + s.substring(1);
}

/**
 * "Safer" String.toLowerCase()
 */
function lowerCase(str) {
  return str.toLowerCase();
}

/**
 * "Safer" String.toUpperCase()
 */
function upperCase(str) {
  return str.toUpperCase();
}

/**
 * Remove non-word chars.
 */
function removeNonWord(str) {
  return str.replace(/[^0-9a-zA-Z\xC0-\xFF \-]/g, '');
}

/**
 * Convert string to camelCase text.
 */
function camelCase(string) {
  return string.replace(/\-/g, ' ').replace(/(\d)(?=(\d{1})+$)/g, '$1 ').replace(/\s[a-z]/g, upperCase).replace(/\s+/g, '').replace(/^[A-Z]/g, lowerCase);
}

function pascalCase(str) {
  return camelCase(str).replace(/^[a-z]/, upperCase);
}

exports.capitalize = capitalize;
exports.lowerCase = lowerCase;
exports.upperCase = upperCase;
exports.removeNonWord = removeNonWord;
exports.camelCase = camelCase;
exports.pascalCase = pascalCase;

/* eslint-enable */
//# sourceMappingURL=strings.js.map

/***/ }),

/***/ "TzU/":
/*!**************************************************!*\
  !*** ./node_modules/draft-js/lib/DraftEntity.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _assign = __webpack_require__(/*! object-assign */ "MgzW");

var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DraftEntity
 * @format
 * 
 */

var DraftEntityInstance = __webpack_require__(/*! ./DraftEntityInstance */ "qnky");
var Immutable = __webpack_require__(/*! immutable */ "JPcv");

var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");

var Map = Immutable.Map;


var instances = Map();
var instanceKey = 0;

/**
 * Temporary utility for generating the warnings
 */
function logWarning(oldMethodCall, newMethodCall) {
  console.warn('WARNING: ' + oldMethodCall + ' will be deprecated soon!\nPlease use "' + newMethodCall + '" instead.');
}

/**
 * A "document entity" is an object containing metadata associated with a
 * piece of text in a ContentBlock.
 *
 * For example, a `link` entity might include a `uri` property. When a
 * ContentBlock is rendered in the browser, text that refers to that link
 * entity may be rendered as an anchor, with the `uri` as the href value.
 *
 * In a ContentBlock, every position in the text may correspond to zero
 * or one entities. This correspondence is tracked using a key string,
 * generated via DraftEntity.create() and used to obtain entity metadata
 * via DraftEntity.get().
 */
var DraftEntity = {
  /**
   * WARNING: This method will be deprecated soon!
   * Please use 'contentState.getLastCreatedEntityKey' instead.
   * ---
   * Get the random key string from whatever entity was last created.
   * We need this to support the new API, as part of transitioning to put Entity
   * storage in contentState.
   */
  getLastCreatedEntityKey: function getLastCreatedEntityKey() {
    logWarning('DraftEntity.getLastCreatedEntityKey', 'contentState.getLastCreatedEntityKey');
    return DraftEntity.__getLastCreatedEntityKey();
  },

  /**
   * WARNING: This method will be deprecated soon!
   * Please use 'contentState.createEntity' instead.
   * ---
   * Create a DraftEntityInstance and store it for later retrieval.
   *
   * A random key string will be generated and returned. This key may
   * be used to track the entity's usage in a ContentBlock, and for
   * retrieving data about the entity at render time.
   */
  create: function create(type, mutability, data) {
    logWarning('DraftEntity.create', 'contentState.createEntity');
    return DraftEntity.__create(type, mutability, data);
  },

  /**
   * WARNING: This method will be deprecated soon!
   * Please use 'contentState.addEntity' instead.
   * ---
   * Add an existing DraftEntityInstance to the DraftEntity map. This is
   * useful when restoring instances from the server.
   */
  add: function add(instance) {
    logWarning('DraftEntity.add', 'contentState.addEntity');
    return DraftEntity.__add(instance);
  },

  /**
   * WARNING: This method will be deprecated soon!
   * Please use 'contentState.getEntity' instead.
   * ---
   * Retrieve the entity corresponding to the supplied key string.
   */
  get: function get(key) {
    logWarning('DraftEntity.get', 'contentState.getEntity');
    return DraftEntity.__get(key);
  },

  /**
   * WARNING: This method will be deprecated soon!
   * Please use 'contentState.mergeEntityData' instead.
   * ---
   * Entity instances are immutable. If you need to update the data for an
   * instance, this method will merge your data updates and return a new
   * instance.
   */
  mergeData: function mergeData(key, toMerge) {
    logWarning('DraftEntity.mergeData', 'contentState.mergeEntityData');
    return DraftEntity.__mergeData(key, toMerge);
  },

  /**
   * WARNING: This method will be deprecated soon!
   * Please use 'contentState.replaceEntityData' instead.
   * ---
   * Completely replace the data for a given instance.
   */
  replaceData: function replaceData(key, newData) {
    logWarning('DraftEntity.replaceData', 'contentState.replaceEntityData');
    return DraftEntity.__replaceData(key, newData);
  },

  // ***********************************WARNING******************************
  // --- the above public API will be deprecated in the next version of Draft!
  // The methods below this line are private - don't call them directly.

  /**
   * Get the random key string from whatever entity was last created.
   * We need this to support the new API, as part of transitioning to put Entity
   * storage in contentState.
   */
  __getLastCreatedEntityKey: function __getLastCreatedEntityKey() {
    return '' + instanceKey;
  },

  /**
   * Create a DraftEntityInstance and store it for later retrieval.
   *
   * A random key string will be generated and returned. This key may
   * be used to track the entity's usage in a ContentBlock, and for
   * retrieving data about the entity at render time.
   */
  __create: function __create(type, mutability, data) {
    return DraftEntity.__add(new DraftEntityInstance({ type: type, mutability: mutability, data: data || {} }));
  },

  /**
   * Add an existing DraftEntityInstance to the DraftEntity map. This is
   * useful when restoring instances from the server.
   */
  __add: function __add(instance) {
    var key = '' + ++instanceKey;
    instances = instances.set(key, instance);
    return key;
  },

  /**
   * Retrieve the entity corresponding to the supplied key string.
   */
  __get: function __get(key) {
    var instance = instances.get(key);
    !!!instance ?  true ? invariant(false, 'Unknown DraftEntity key: %s.', key) : undefined : void 0;
    return instance;
  },

  /**
   * Entity instances are immutable. If you need to update the data for an
   * instance, this method will merge your data updates and return a new
   * instance.
   */
  __mergeData: function __mergeData(key, toMerge) {
    var instance = DraftEntity.__get(key);
    var newData = _extends({}, instance.getData(), toMerge);
    var newInstance = instance.set('data', newData);
    instances = instances.set(key, newInstance);
    return newInstance;
  },

  /**
   * Completely replace the data for a given instance.
   */
  __replaceData: function __replaceData(key, newData) {
    var instance = DraftEntity.__get(key);
    var newInstance = instance.set('data', newData);
    instances = instances.set(key, newInstance);
    return newInstance;
  }
};

module.exports = DraftEntity;

/***/ }),

/***/ "U+KD":
/*!*************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_object-gpo.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = __webpack_require__(/*! ./_has */ "B+OT");
var toObject = __webpack_require__(/*! ./_to-object */ "JB68");
var IE_PROTO = __webpack_require__(/*! ./_shared-key */ "VVlx")('IE_PROTO');
var ObjectProto = Object.prototype;

module.exports = Object.getPrototypeOf || function (O) {
  O = toObject(O);
  if (has(O, IE_PROTO)) return O[IE_PROTO];
  if (typeof O.constructor == 'function' && O instanceof O.constructor) {
    return O.constructor.prototype;
  } return O instanceof Object ? ObjectProto : null;
};


/***/ }),

/***/ "U2CZ":
/*!*****************************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils/lib/commandpalette.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
/* tslint:disable */
/**
 * The command palette token.
 */
exports.ICommandPalette = new coreutils_1.Token('@jupyterlab/apputils:ICommandPalette');


/***/ }),

/***/ "U45Y":
/*!*******************************************************************!*\
  !*** ./node_modules/@jupyterlab/settingeditor/lib/tableeditor.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const React = __importStar(__webpack_require__(/*! react */ "q1tI"));
const ReactDOM = __importStar(__webpack_require__(/*! react-dom */ "i8i4"));
/**
 * A tabular editor for plugin settings.
 */
class TableEditor extends widgets_1.Widget {
    /**
     * Create a new table editor for settings.
     */
    constructor(options) {
        super({ node: document.createElement('fieldset') });
        this._settings = null;
        this.addClass('jp-SettingsTableEditor');
    }
    /**
     * Tests whether the settings have been modified and need saving.
     */
    get isDirty() {
        return false; // TODO: remove placeholder.
    }
    /**
     * The plugin settings.
     */
    get settings() {
        return this._settings;
    }
    set settings(settings) {
        if (this._settings) {
            this._settings.changed.disconnect(this._onSettingsChanged, this);
        }
        this._settings = settings;
        if (this._settings) {
            this._settings.changed.connect(this._onSettingsChanged, this);
        }
        this.update();
    }
    /**
     * Handle `'update-request'` messages.
     */
    onUpdateRequest(msg) {
        const settings = this._settings;
        // Populate if possible.
        if (settings) {
            Private.populateTable(this.node, settings);
        }
    }
    /**
     * Handle setting changes.
     */
    _onSettingsChanged() {
        this.update();
    }
}
exports.TableEditor = TableEditor;
/**
 * A namespace for private module data.
 */
var Private;
(function (Private) {
    /**
     * Populate the fieldset with a specific plugin's metadata.
     */
    function populateTable(node, settings) {
        const { plugin, schema } = settings;
        const fields = {};
        const properties = schema.properties || {};
        const title = `(${plugin}) ${schema.description}`;
        const label = `Fields - ${schema.title || plugin}`;
        Object.keys(properties).forEach(property => {
            const field = properties[property];
            const { type } = field;
            const defaultValue = settings.default(property);
            const title = field.title || property;
            const value = JSON.stringify(defaultValue) || '';
            const valueTitle = JSON.stringify(defaultValue, null, 4);
            fields[property] = (React.createElement("tr", { key: property },
                React.createElement("td", { className: "jp-SettingsTableEditor-key", title: title },
                    React.createElement("code", { title: title }, property)),
                React.createElement("td", { className: "jp-SettingsTableEditor-value", title: valueTitle },
                    React.createElement("code", { title: valueTitle }, value)),
                React.createElement("td", { className: "jp-SettingsTableEditor-type" }, type)));
        });
        const rows = Object.keys(fields)
            .sort((a, b) => a.localeCompare(b))
            .map(property => fields[property]);
        const fragment = (React.createElement(React.Fragment, null,
            React.createElement("legend", { title: title }, label),
            React.createElement("div", { className: "jp-SettingsTableEditor-wrapper" },
                React.createElement("table", null,
                    React.createElement("thead", null,
                        React.createElement("tr", null,
                            React.createElement("th", { className: "jp-SettingsTableEditor-key" }, "Key"),
                            React.createElement("th", { className: "jp-SettingsTableEditor-value" }, "Default"),
                            React.createElement("th", { className: "jp-SettingsTableEditor-type" }, "Type"))),
                    React.createElement("tbody", null, rows)))));
        ReactDOM.unmountComponentAtNode(node);
        ReactDOM.render(fragment, node);
    }
    Private.populateTable = populateTable;
})(Private || (Private = {}));


/***/ }),

/***/ "U534":
/*!*********************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/plotly-extension/style/index.css ***!
  \*********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var escape = __webpack_require__(/*! ../../../css-loader/lib/url/escape.js */ "sEG9");
exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/**\n  Copyright (c) Jupyter Development Team.\n  Distributed under the terms of the Modified BSD License.\n*/\n\n/* Add CSS variables to :root */\n:root {\n  --jp-icon-plotly: url(" + escape(__webpack_require__(/*! ./plotly.svg */ "/l3u")) + ");\n}\n\n/* Base styles */\n.jp-RenderedPlotly {\n  width: 100%;\n  height: 100%;\n  padding: 0;\n  overflow: hidden;\n}\n\n/* Document styles */\n.jp-MimeDocument .jp-RenderedPlotly {\n  overflow: hidden;\n}\n\n/* Output styles */\n.jp-OutputArea .jp-RenderedPlotly {\n  min-height: 360px;\n}\n\n/* Document icon */\n.jp-PlotlyIcon {\n  background-image: var(--jp-icon-plotly);\n}\n", ""]);

// exports


/***/ }),

/***/ "U6ii":
/*!**********************************************!*\
  !*** ./node_modules/pure-color/parse/rgb.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var extractComponents = __webpack_require__(/*! ./extractComponents */ "wQnj");
var clamp = __webpack_require__(/*! ../util/clamp */ "I0N7");

function parseRgbComponent(component, i) {
  if (i < 3) {
    if (component.indexOf('%') != -1) {
      return Math.round(255 * clamp(parseInt(component, 10), 0, 100)/100);
    } else {
      return clamp(parseInt(component, 10), 0, 255);
    }
  } else {
    return clamp(parseFloat(component), 0, 1);
  } 
}

function rgb(color) {
  return extractComponents(color).map(parseRgbComponent);
}

module.exports = rgb;

/***/ }),

/***/ "U6jy":
/*!*****************************************!*\
  !*** ./node_modules/xtend/immutable.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = extend

var hasOwnProperty = Object.prototype.hasOwnProperty;

function extend() {
    var target = {}

    for (var i = 0; i < arguments.length; i++) {
        var source = arguments[i]

        for (var key in source) {
            if (hasOwnProperty.call(source, key)) {
                target[key] = source[key]
            }
        }
    }

    return target
}


/***/ }),

/***/ "U84a":
/*!*********************************************************!*\
  !*** ./node_modules/draft-js/lib/encodeEntityRanges.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule encodeEntityRanges
 * @format
 * 
 */



var DraftStringKey = __webpack_require__(/*! ./DraftStringKey */ "dyxW");
var UnicodeUtils = __webpack_require__(/*! fbjs/lib/UnicodeUtils */ "jLRO");

var strlen = UnicodeUtils.strlen;

/**
 * Convert to UTF-8 character counts for storage.
 */

function encodeEntityRanges(block, storageMap) {
  var encoded = [];
  block.findEntityRanges(function (character) {
    return !!character.getEntity();
  }, function ( /*number*/start, /*number*/end) {
    var text = block.getText();
    var key = block.getEntityAt(start);
    encoded.push({
      offset: strlen(text.slice(0, start)),
      length: strlen(text.slice(start, end)),
      // Encode the key as a number for range storage.
      key: Number(storageMap[DraftStringKey.stringify(key)])
    });
  });
  return encoded;
}

module.exports = encodeEntityRanges;

/***/ }),

/***/ "UCR5":
/*!*************************************************************!*\
  !*** ./node_modules/source-map/lib/source-map-generator.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* -*- Mode: js; js-indent-level: 2; -*- */
/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var base64VLQ = __webpack_require__(/*! ./base64-vlq */ "Vywy");
var util = __webpack_require__(/*! ./util */ "Cbry");
var ArraySet = __webpack_require__(/*! ./array-set */ "KavO").ArraySet;
var MappingList = __webpack_require__(/*! ./mapping-list */ "sQiz").MappingList;

/**
 * An instance of the SourceMapGenerator represents a source map which is
 * being built incrementally. You may pass an object with the following
 * properties:
 *
 *   - file: The filename of the generated source.
 *   - sourceRoot: A root for all relative URLs in this source map.
 */
function SourceMapGenerator(aArgs) {
  if (!aArgs) {
    aArgs = {};
  }
  this._file = util.getArg(aArgs, 'file', null);
  this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  this._sources = new ArraySet();
  this._names = new ArraySet();
  this._mappings = new MappingList();
  this._sourcesContents = null;
}

SourceMapGenerator.prototype._version = 3;

/**
 * Creates a new SourceMapGenerator based on a SourceMapConsumer
 *
 * @param aSourceMapConsumer The SourceMap.
 */
SourceMapGenerator.fromSourceMap =
  function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
    var sourceRoot = aSourceMapConsumer.sourceRoot;
    var generator = new SourceMapGenerator({
      file: aSourceMapConsumer.file,
      sourceRoot: sourceRoot
    });
    aSourceMapConsumer.eachMapping(function (mapping) {
      var newMapping = {
        generated: {
          line: mapping.generatedLine,
          column: mapping.generatedColumn
        }
      };

      if (mapping.source != null) {
        newMapping.source = mapping.source;
        if (sourceRoot != null) {
          newMapping.source = util.relative(sourceRoot, newMapping.source);
        }

        newMapping.original = {
          line: mapping.originalLine,
          column: mapping.originalColumn
        };

        if (mapping.name != null) {
          newMapping.name = mapping.name;
        }
      }

      generator.addMapping(newMapping);
    });
    aSourceMapConsumer.sources.forEach(function (sourceFile) {
      var sourceRelative = sourceFile;
      if (sourceRoot !== null) {
        sourceRelative = util.relative(sourceRoot, sourceFile);
      }

      if (!generator._sources.has(sourceRelative)) {
        generator._sources.add(sourceRelative);
      }

      var content = aSourceMapConsumer.sourceContentFor(sourceFile);
      if (content != null) {
        generator.setSourceContent(sourceFile, content);
      }
    });
    return generator;
  };

/**
 * Add a single mapping from original source line and column to the generated
 * source's line and column for this source map being created. The mapping
 * object should have the following properties:
 *
 *   - generated: An object with the generated line and column positions.
 *   - original: An object with the original line and column positions.
 *   - source: The original source file (relative to the sourceRoot).
 *   - name: An optional original token name for this mapping.
 */
SourceMapGenerator.prototype.addMapping =
  function SourceMapGenerator_addMapping(aArgs) {
    var generated = util.getArg(aArgs, 'generated');
    var original = util.getArg(aArgs, 'original', null);
    var source = util.getArg(aArgs, 'source', null);
    var name = util.getArg(aArgs, 'name', null);

    if (!this._skipValidation) {
      this._validateMapping(generated, original, source, name);
    }

    if (source != null) {
      source = String(source);
      if (!this._sources.has(source)) {
        this._sources.add(source);
      }
    }

    if (name != null) {
      name = String(name);
      if (!this._names.has(name)) {
        this._names.add(name);
      }
    }

    this._mappings.add({
      generatedLine: generated.line,
      generatedColumn: generated.column,
      originalLine: original != null && original.line,
      originalColumn: original != null && original.column,
      source: source,
      name: name
    });
  };

/**
 * Set the source content for a source file.
 */
SourceMapGenerator.prototype.setSourceContent =
  function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
    var source = aSourceFile;
    if (this._sourceRoot != null) {
      source = util.relative(this._sourceRoot, source);
    }

    if (aSourceContent != null) {
      // Add the source content to the _sourcesContents map.
      // Create a new _sourcesContents map if the property is null.
      if (!this._sourcesContents) {
        this._sourcesContents = Object.create(null);
      }
      this._sourcesContents[util.toSetString(source)] = aSourceContent;
    } else if (this._sourcesContents) {
      // Remove the source file from the _sourcesContents map.
      // If the _sourcesContents map is empty, set the property to null.
      delete this._sourcesContents[util.toSetString(source)];
      if (Object.keys(this._sourcesContents).length === 0) {
        this._sourcesContents = null;
      }
    }
  };

/**
 * Applies the mappings of a sub-source-map for a specific source file to the
 * source map being generated. Each mapping to the supplied source file is
 * rewritten using the supplied source map. Note: The resolution for the
 * resulting mappings is the minimium of this map and the supplied map.
 *
 * @param aSourceMapConsumer The source map to be applied.
 * @param aSourceFile Optional. The filename of the source file.
 *        If omitted, SourceMapConsumer's file property will be used.
 * @param aSourceMapPath Optional. The dirname of the path to the source map
 *        to be applied. If relative, it is relative to the SourceMapConsumer.
 *        This parameter is needed when the two source maps aren't in the same
 *        directory, and the source map to be applied contains relative source
 *        paths. If so, those relative source paths need to be rewritten
 *        relative to the SourceMapGenerator.
 */
SourceMapGenerator.prototype.applySourceMap =
  function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
    var sourceFile = aSourceFile;
    // If aSourceFile is omitted, we will use the file property of the SourceMap
    if (aSourceFile == null) {
      if (aSourceMapConsumer.file == null) {
        throw new Error(
          'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
          'or the source map\'s "file" property. Both were omitted.'
        );
      }
      sourceFile = aSourceMapConsumer.file;
    }
    var sourceRoot = this._sourceRoot;
    // Make "sourceFile" relative if an absolute Url is passed.
    if (sourceRoot != null) {
      sourceFile = util.relative(sourceRoot, sourceFile);
    }
    // Applying the SourceMap can add and remove items from the sources and
    // the names array.
    var newSources = new ArraySet();
    var newNames = new ArraySet();

    // Find mappings for the "sourceFile"
    this._mappings.unsortedForEach(function (mapping) {
      if (mapping.source === sourceFile && mapping.originalLine != null) {
        // Check if it can be mapped by the source map, then update the mapping.
        var original = aSourceMapConsumer.originalPositionFor({
          line: mapping.originalLine,
          column: mapping.originalColumn
        });
        if (original.source != null) {
          // Copy mapping
          mapping.source = original.source;
          if (aSourceMapPath != null) {
            mapping.source = util.join(aSourceMapPath, mapping.source)
          }
          if (sourceRoot != null) {
            mapping.source = util.relative(sourceRoot, mapping.source);
          }
          mapping.originalLine = original.line;
          mapping.originalColumn = original.column;
          if (original.name != null) {
            mapping.name = original.name;
          }
        }
      }

      var source = mapping.source;
      if (source != null && !newSources.has(source)) {
        newSources.add(source);
      }

      var name = mapping.name;
      if (name != null && !newNames.has(name)) {
        newNames.add(name);
      }

    }, this);
    this._sources = newSources;
    this._names = newNames;

    // Copy sourcesContents of applied map.
    aSourceMapConsumer.sources.forEach(function (sourceFile) {
      var content = aSourceMapConsumer.sourceContentFor(sourceFile);
      if (content != null) {
        if (aSourceMapPath != null) {
          sourceFile = util.join(aSourceMapPath, sourceFile);
        }
        if (sourceRoot != null) {
          sourceFile = util.relative(sourceRoot, sourceFile);
        }
        this.setSourceContent(sourceFile, content);
      }
    }, this);
  };

/**
 * A mapping can have one of the three levels of data:
 *
 *   1. Just the generated position.
 *   2. The Generated position, original position, and original source.
 *   3. Generated and original position, original source, as well as a name
 *      token.
 *
 * To maintain consistency, we validate that any new mapping being added falls
 * in to one of these categories.
 */
SourceMapGenerator.prototype._validateMapping =
  function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
                                              aName) {
    // When aOriginal is truthy but has empty values for .line and .column,
    // it is most likely a programmer error. In this case we throw a very
    // specific error message to try to guide them the right way.
    // For example: https://github.com/Polymer/polymer-bundler/pull/519
    if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
        throw new Error(
            'original.line and original.column are not numbers -- you probably meant to omit ' +
            'the original mapping entirely and only map the generated position. If so, pass ' +
            'null for the original mapping instead of an object with empty or null values.'
        );
    }

    if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
        && aGenerated.line > 0 && aGenerated.column >= 0
        && !aOriginal && !aSource && !aName) {
      // Case 1.
      return;
    }
    else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
             && aOriginal && 'line' in aOriginal && 'column' in aOriginal
             && aGenerated.line > 0 && aGenerated.column >= 0
             && aOriginal.line > 0 && aOriginal.column >= 0
             && aSource) {
      // Cases 2 and 3.
      return;
    }
    else {
      throw new Error('Invalid mapping: ' + JSON.stringify({
        generated: aGenerated,
        source: aSource,
        original: aOriginal,
        name: aName
      }));
    }
  };

/**
 * Serialize the accumulated mappings in to the stream of base 64 VLQs
 * specified by the source map format.
 */
SourceMapGenerator.prototype._serializeMappings =
  function SourceMapGenerator_serializeMappings() {
    var previousGeneratedColumn = 0;
    var previousGeneratedLine = 1;
    var previousOriginalColumn = 0;
    var previousOriginalLine = 0;
    var previousName = 0;
    var previousSource = 0;
    var result = '';
    var next;
    var mapping;
    var nameIdx;
    var sourceIdx;

    var mappings = this._mappings.toArray();
    for (var i = 0, len = mappings.length; i < len; i++) {
      mapping = mappings[i];
      next = ''

      if (mapping.generatedLine !== previousGeneratedLine) {
        previousGeneratedColumn = 0;
        while (mapping.generatedLine !== previousGeneratedLine) {
          next += ';';
          previousGeneratedLine++;
        }
      }
      else {
        if (i > 0) {
          if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
            continue;
          }
          next += ',';
        }
      }

      next += base64VLQ.encode(mapping.generatedColumn
                                 - previousGeneratedColumn);
      previousGeneratedColumn = mapping.generatedColumn;

      if (mapping.source != null) {
        sourceIdx = this._sources.indexOf(mapping.source);
        next += base64VLQ.encode(sourceIdx - previousSource);
        previousSource = sourceIdx;

        // lines are stored 0-based in SourceMap spec version 3
        next += base64VLQ.encode(mapping.originalLine - 1
                                   - previousOriginalLine);
        previousOriginalLine = mapping.originalLine - 1;

        next += base64VLQ.encode(mapping.originalColumn
                                   - previousOriginalColumn);
        previousOriginalColumn = mapping.originalColumn;

        if (mapping.name != null) {
          nameIdx = this._names.indexOf(mapping.name);
          next += base64VLQ.encode(nameIdx - previousName);
          previousName = nameIdx;
        }
      }

      result += next;
    }

    return result;
  };

SourceMapGenerator.prototype._generateSourcesContent =
  function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
    return aSources.map(function (source) {
      if (!this._sourcesContents) {
        return null;
      }
      if (aSourceRoot != null) {
        source = util.relative(aSourceRoot, source);
      }
      var key = util.toSetString(source);
      return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
        ? this._sourcesContents[key]
        : null;
    }, this);
  };

/**
 * Externalize the source map.
 */
SourceMapGenerator.prototype.toJSON =
  function SourceMapGenerator_toJSON() {
    var map = {
      version: this._version,
      sources: this._sources.toArray(),
      names: this._names.toArray(),
      mappings: this._serializeMappings()
    };
    if (this._file != null) {
      map.file = this._file;
    }
    if (this._sourceRoot != null) {
      map.sourceRoot = this._sourceRoot;
    }
    if (this._sourcesContents) {
      map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
    }

    return map;
  };

/**
 * Render the source map being generated to a string.
 */
SourceMapGenerator.prototype.toString =
  function SourceMapGenerator_toString() {
    return JSON.stringify(this.toJSON());
  };

exports.SourceMapGenerator = SourceMapGenerator;


/***/ }),

/***/ "UDhR":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/id.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var id = moment.defineLocale('id', {
    months : 'Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_November_Desember'.split('_'),
    monthsShort : 'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Agt_Sep_Okt_Nov_Des'.split('_'),
    weekdays : 'Minggu_Senin_Selasa_Rabu_Kamis_Jumat_Sabtu'.split('_'),
    weekdaysShort : 'Min_Sen_Sel_Rab_Kam_Jum_Sab'.split('_'),
    weekdaysMin : 'Mg_Sn_Sl_Rb_Km_Jm_Sb'.split('_'),
    longDateFormat : {
        LT : 'HH.mm',
        LTS : 'HH.mm.ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY [pukul] HH.mm',
        LLLL : 'dddd, D MMMM YYYY [pukul] HH.mm'
    },
    meridiemParse: /pagi|siang|sore|malam/,
    meridiemHour : function (hour, meridiem) {
        if (hour === 12) {
            hour = 0;
        }
        if (meridiem === 'pagi') {
            return hour;
        } else if (meridiem === 'siang') {
            return hour >= 11 ? hour : hour + 12;
        } else if (meridiem === 'sore' || meridiem === 'malam') {
            return hour + 12;
        }
    },
    meridiem : function (hours, minutes, isLower) {
        if (hours < 11) {
            return 'pagi';
        } else if (hours < 15) {
            return 'siang';
        } else if (hours < 19) {
            return 'sore';
        } else {
            return 'malam';
        }
    },
    calendar : {
        sameDay : '[Hari ini pukul] LT',
        nextDay : '[Besok pukul] LT',
        nextWeek : 'dddd [pukul] LT',
        lastDay : '[Kemarin pukul] LT',
        lastWeek : 'dddd [lalu pukul] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'dalam %s',
        past : '%s yang lalu',
        s : 'beberapa detik',
        ss : '%d detik',
        m : 'semenit',
        mm : '%d menit',
        h : 'sejam',
        hh : '%d jam',
        d : 'sehari',
        dd : '%d hari',
        M : 'sebulan',
        MM : '%d bulan',
        y : 'setahun',
        yy : '%d tahun'
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return id;

})));


/***/ }),

/***/ "UGzO":
/*!*********************************************************************!*\
  !*** ./node_modules/react-color/lib/components/common/ColorWrap.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ColorWrap = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _debounce = __webpack_require__(/*! lodash/debounce */ "sEfC");

var _debounce2 = _interopRequireDefault(_debounce);

var _color = __webpack_require__(/*! ../../helpers/color */ "p8yl");

var _color2 = _interopRequireDefault(_color);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var ColorWrap = exports.ColorWrap = function ColorWrap(Picker) {
  var ColorPicker = function (_ref) {
    _inherits(ColorPicker, _ref);

    function ColorPicker(props) {
      _classCallCheck(this, ColorPicker);

      var _this = _possibleConstructorReturn(this, (ColorPicker.__proto__ || Object.getPrototypeOf(ColorPicker)).call(this));

      _this.handleChange = function (data, event) {
        var isValidColor = _color2.default.simpleCheckForValidColor(data);
        if (isValidColor) {
          var colors = _color2.default.toState(data, data.h || _this.state.oldHue);
          _this.setState(colors);
          _this.props.onChangeComplete && _this.debounce(_this.props.onChangeComplete, colors, event);
          _this.props.onChange && _this.props.onChange(colors, event);
        }
      };

      _this.handleSwatchHover = function (data, event) {
        var isValidColor = _color2.default.simpleCheckForValidColor(data);
        if (isValidColor) {
          var colors = _color2.default.toState(data, data.h || _this.state.oldHue);
          _this.setState(colors);
          _this.props.onSwatchHover && _this.props.onSwatchHover(colors, event);
        }
      };

      _this.state = _extends({}, _color2.default.toState(props.color, 0));

      _this.debounce = (0, _debounce2.default)(function (fn, data, event) {
        fn(data, event);
      }, 100);
      return _this;
    }

    _createClass(ColorPicker, [{
      key: 'componentWillReceiveProps',
      value: function componentWillReceiveProps(nextProps) {
        this.setState(_extends({}, _color2.default.toState(nextProps.color, this.state.oldHue)));
      }
    }, {
      key: 'render',
      value: function render() {
        var optionalEvents = {};
        if (this.props.onSwatchHover) {
          optionalEvents.onSwatchHover = this.handleSwatchHover;
        }

        return _react2.default.createElement(Picker, _extends({}, this.props, this.state, {
          onChange: this.handleChange
        }, optionalEvents));
      }
    }]);

    return ColorPicker;
  }(_react.PureComponent || _react.Component);

  ColorPicker.propTypes = _extends({}, Picker.propTypes);

  ColorPicker.defaultProps = _extends({}, Picker.defaultProps, {
    color: {
      h: 250,
      s: 0.50,
      l: 0.20,
      a: 1
    }
  });

  return ColorPicker;
};

exports.default = ColorWrap;

/***/ }),

/***/ "UNSI":
/*!*****************************************************!*\
  !*** ./node_modules/react-day-picker/lib/style.css ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../css-loader!./style.css */ "4xXw");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "UNi/":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_baseTimes.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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;
}

module.exports = baseTimes;


/***/ }),

/***/ "UO39":
/*!************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_iter-step.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = function (done, value) {
  return { value: value, done: !!done };
};


/***/ }),

/***/ "URgk":
/*!************************************************!*\
  !*** ./node_modules/timers-browserify/main.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) ||
            (typeof self !== "undefined" && self) ||
            window;
var apply = Function.prototype.apply;

// DOM APIs, for completeness

exports.setTimeout = function() {
  return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);
};
exports.setInterval = function() {
  return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);
};
exports.clearTimeout =
exports.clearInterval = function(timeout) {
  if (timeout) {
    timeout.close();
  }
};

function Timeout(id, clearFn) {
  this._id = id;
  this._clearFn = clearFn;
}
Timeout.prototype.unref = Timeout.prototype.ref = function() {};
Timeout.prototype.close = function() {
  this._clearFn.call(scope, this._id);
};

// Does not start the time, just sets up the members needed.
exports.enroll = function(item, msecs) {
  clearTimeout(item._idleTimeoutId);
  item._idleTimeout = msecs;
};

exports.unenroll = function(item) {
  clearTimeout(item._idleTimeoutId);
  item._idleTimeout = -1;
};

exports._unrefActive = exports.active = function(item) {
  clearTimeout(item._idleTimeoutId);

  var msecs = item._idleTimeout;
  if (msecs >= 0) {
    item._idleTimeoutId = setTimeout(function onTimeout() {
      if (item._onTimeout)
        item._onTimeout();
    }, msecs);
  }
};

// setimmediate attaches itself to the global object
__webpack_require__(/*! setimmediate */ "YBdB");
// On some exotic environments, it's not clear which object `setimmediate` was
// able to install onto.  Search each possibility in the same order as the
// `setimmediate` library.
exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) ||
                       (typeof global !== "undefined" && global.setImmediate) ||
                       (this && this.setImmediate);
exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) ||
                         (typeof global !== "undefined" && global.clearImmediate) ||
                         (this && this.clearImmediate);

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "USP6":
/*!*****************************************************!*\
  !*** ./node_modules/@jupyterlab/cells/lib/index.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__webpack_require__(/*! ../style/index.css */ "utho");
__export(__webpack_require__(/*! ./collapser */ "ca2I"));
__export(__webpack_require__(/*! ./headerfooter */ "IMnP"));
__export(__webpack_require__(/*! ./inputarea */ "exNP"));
__export(__webpack_require__(/*! ./model */ "r+t4"));
__export(__webpack_require__(/*! ./placeholder */ "K7N2"));
__export(__webpack_require__(/*! ./widget */ "bQVC"));


/***/ }),

/***/ "UV20":
/*!*********************************************!*\
  !*** ./node_modules/mdi-react/ForumIcon.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var ForumIcon = function ForumIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M17,12V3C17,2.45 16.55,2 16,2H3C2.45,2 2,2.45 2,3V17L6,13H16C16.55,13 17,12.55 17,12M21,6H19V15H6V17C6,17.55 6.45,18 7,18H18L22,22V7C22,6.45 21.55,6 21,6Z' })
  );
};

module.exports = ForumIcon;


/***/ }),

/***/ "UWVS":
/*!**************************************************!*\
  !*** ./node_modules/browserify-aes/modes/ofb.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(Buffer) {var xor = __webpack_require__(/*! buffer-xor */ "jIre")

function getBlock (self) {
  self._prev = self._cipher.encryptBlock(self._prev)
  return self._prev
}

exports.encrypt = function (self, chunk) {
  while (self._cache.length < chunk.length) {
    self._cache = Buffer.concat([self._cache, getBlock(self)])
  }

  var pad = self._cache.slice(0, chunk.length)
  self._cache = self._cache.slice(chunk.length)
  return xor(chunk, pad)
}

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../buffer/index.js */ "tjlA").Buffer))

/***/ }),

/***/ "UWiX":
/*!******************************************************!*\
  !*** ./node_modules/core-js/library/modules/_wks.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var store = __webpack_require__(/*! ./_shared */ "29s/")('wks');
var uid = __webpack_require__(/*! ./_uid */ "YqAc");
var Symbol = __webpack_require__(/*! ./_global */ "5T2Y").Symbol;
var USE_SYMBOL = typeof Symbol == 'function';

var $exports = module.exports = function (name) {
  return store[name] || (store[name] =
    USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};

$exports.store = store;


/***/ }),

/***/ "UXQq":
/*!************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/Field.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.FieldDelete = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _MenuPanel = __webpack_require__(/*! ../containers/MenuPanel */ "WS6A");

var _MenuPanel2 = _interopRequireDefault(_MenuPanel);

var _classnames2 = __webpack_require__(/*! classnames */ "TSYQ");

var _classnames3 = _interopRequireDefault(_classnames2);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _constants = __webpack_require__(/*! ../../lib/constants */ "5Bkx");

var _plotlyIcons = __webpack_require__(/*! plotly-icons */ "hwSx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var FieldDelete = exports.FieldDelete = function (_Component) {
  _inherits(FieldDelete, _Component);

  function FieldDelete() {
    _classCallCheck(this, FieldDelete);

    return _possibleConstructorReturn(this, (FieldDelete.__proto__ || Object.getPrototypeOf(FieldDelete)).apply(this, arguments));
  }

  _createClass(FieldDelete, [{
    key: 'render',
    value: function render() {
      var onClick = this.props.onClick;

      return _react2.default.createElement(
        'div',
        { className: 'field__delete', onClick: onClick },
        _react2.default.createElement(_plotlyIcons.CloseIcon, null)
      );
    }
  }]);

  return FieldDelete;
}(_react.Component);

var Field = function (_Component2) {
  _inherits(Field, _Component2);

  function Field() {
    _classCallCheck(this, Field);

    return _possibleConstructorReturn(this, (Field.__proto__ || Object.getPrototypeOf(Field)).apply(this, arguments));
  }

  _createClass(Field, [{
    key: 'render',
    value: function render() {
      var _props = this.props,
          center = _props.center,
          children = _props.children,
          label = _props.label,
          multiValued = _props.multiValued,
          suppressMultiValuedMessage = _props.suppressMultiValuedMessage,
          units = _props.units,
          extraComponent = _props.extraComponent,
          fieldContainerClassName = _props.fieldContainerClassName,
          labelWidth = _props.labelWidth;
      var _ = this.context.localize;


      var fieldClass = void 0;
      if (!label) {
        fieldClass = (0, _classnames3.default)('field__no-title', {
          'field__no-title--center': center
        });
      } else {
        fieldClass = (0, _classnames3.default)('field__widget', {
          'field__widget--units': Boolean(units)
        });
      }

      var tooltip = this.context.attr;
      if (this.context.description) {
        tooltip += ' – ' + this.context.description.replace(/`/g, '"').replace(/\*/g, '"');
      }

      var containerClassName = (0, _classnames3.default)((0, _lib.bem)('field'), _defineProperty({}, fieldContainerClassName, Boolean(fieldContainerClassName)));

      return _react2.default.createElement(
        'div',
        { className: containerClassName },
        label ? _react2.default.createElement(
          'div',
          {
            className: (0, _lib.bem)('field', 'title'),
            style: labelWidth ? { minWidth: labelWidth + 'px' } : {}
          },
          this.context.showFieldTooltips ? _react2.default.createElement(
            'div',
            {
              className: (0, _lib.bem)('field', 'title-text'),
              'aria-label': tooltip,
              'data-microtip-position': 'bottom-right',
              'data-microtip-size': 'large',
              role: 'tooltip'
            },
            label
          ) : _react2.default.createElement(
            'div',
            { className: (0, _lib.bem)('field', 'title-text') },
            label
          )
        ) : null,
        _react2.default.createElement(
          'div',
          { className: fieldClass },
          children,
          extraComponent ? extraComponent : null,
          multiValued && !suppressMultiValuedMessage ? _react2.default.createElement(
            _MenuPanel2.default,
            { label: (0, _constants.getMultiValueText)('title', _), ownline: true, question: true },
            _react2.default.createElement(
              'div',
              { className: 'info__title' },
              (0, _constants.getMultiValueText)('title', _)
            ),
            _react2.default.createElement(
              'div',
              { className: 'info__text' },
              (0, _constants.getMultiValueText)('text', _)
            ),
            _react2.default.createElement(
              'div',
              { className: 'info__sub-text' },
              (0, _constants.getMultiValueText)('subText', _)
            )
          ) : null
        ),
        units ? _react2.default.createElement(
          'div',
          { className: (0, _lib.bem)('field', 'units') },
          _react2.default.createElement(
            'div',
            { className: (0, _lib.bem)('field', 'units-text') },
            units
          )
        ) : null
      );
    }
  }]);

  return Field;
}(_react.Component);

Field.propTypes = {
  labelWidth: _propTypes2.default.number,
  center: _propTypes2.default.bool,
  label: _propTypes2.default.any,
  units: _propTypes2.default.string,
  multiValued: _propTypes2.default.bool,
  suppressMultiValuedMessage: _propTypes2.default.bool,
  children: _propTypes2.default.node,
  extraComponent: _propTypes2.default.any,
  fieldContainerClassName: _propTypes2.default.string
};

Field.contextTypes = {
  localize: _propTypes2.default.func,
  description: _propTypes2.default.string,
  attr: _propTypes2.default.string,
  showFieldTooltips: _propTypes2.default.bool
};

Field.defaultProps = {
  center: false,
  multiValued: false
};

FieldDelete.propTypes = {
  onClick: _propTypes2.default.func
};
exports.default = Field;
//# sourceMappingURL=Field.js.map

/***/ }),

/***/ "UXrF":
/*!**************************************************************!*\
  !*** ./node_modules/react-highlighter/lib/regExpPropType.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

var regExpPropType = function (props, propName, componentName, location) {
  if (!(props[propName] instanceof RegExp)) {
    var propType = typeof props[propName];

    return new Error(
      ("Invalid " + location + " `" + propName + "` of type `" + propType + "` ") +
        ("supplied to `" + componentName + "`, expected `RegExp`.")
    );
  }
};

module.exports = regExpPropType;


/***/ }),

/***/ "UbbE":
/*!**********************************************************!*\
  !*** ./node_modules/core-js/library/fn/object/assign.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(/*! ../../modules/es6.object.assign */ "o8NH");
module.exports = __webpack_require__(/*! ../../modules/_core */ "WEpk").Object.assign;


/***/ }),

/***/ "Udc6":
/*!*******************************************!*\
  !*** ./node_modules/base16/lib/google.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'google',
  author: 'seth wright (http://sethawright.com)',
  base00: '#1d1f21',
  base01: '#282a2e',
  base02: '#373b41',
  base03: '#969896',
  base04: '#b4b7b4',
  base05: '#c5c8c6',
  base06: '#e0e0e0',
  base07: '#ffffff',
  base08: '#CC342B',
  base09: '#F96A38',
  base0A: '#FBA922',
  base0B: '#198844',
  base0C: '#3971ED',
  base0D: '#3971ED',
  base0E: '#A36AC7',
  base0F: '#3971ED'
};
module.exports = exports['default'];

/***/ }),

/***/ "Uggb":
/*!********************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/vega4-extension/style/index.css ***!
  \********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.jp-RenderedVegaCommon4 {\n  margin-left: 8px;\n  margin-top: 8px;\n}\n\n.jp-MimeDocument .jp-RenderedVegaCommon4 {\n  padding: 16px;\n}\n\n.vega canvas {\n  background: var(--jp-vega-background);\n}\n", ""]);

// exports


/***/ }),

/***/ "Uia9":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/notebook/lib/celllist.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const observables_1 = __webpack_require__(/*! @jupyterlab/observables */ "V4vH");
/**
 * A cell list object that supports undo/redo.
 */
class CellList {
    /**
     * Construct the cell list.
     */
    constructor(modelDB, factory) {
        this._isDisposed = false;
        this._cellOrder = null;
        this._cellMap = null;
        this._changed = new signaling_1.Signal(this);
        this._factory = null;
        this._factory = factory;
        this._cellOrder = modelDB.createList('cellOrder');
        this._cellMap = new observables_1.ObservableMap();
        this._cellOrder.changed.connect(this._onOrderChanged, this);
    }
    /**
     * A signal emitted when the cell list has changed.
     */
    get changed() {
        return this._changed;
    }
    /**
     * Test whether the cell list has been disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Test whether the list is empty.
     *
     * @returns `true` if the cell list is empty, `false` otherwise.
     *
     * #### Notes
     * This is a read-only property.
     *
     * #### Complexity
     * Constant.
     *
     * #### Iterator Validity
     * No changes.
     */
    get isEmpty() {
        return this._cellOrder.length === 0;
    }
    /**
     * Get the length of the cell list.
     *
     * @return The number of cells in the cell list.
     *
     * #### Notes
     * This is a read-only property.
     *
     * #### Complexity
     * Constant.
     *
     * #### Iterator Validity
     * No changes.
     */
    get length() {
        return this._cellOrder.length;
    }
    /**
     * Create an iterator over the cells in the cell list.
     *
     * @returns A new iterator starting at the front of the cell list.
     *
     * #### Complexity
     * Constant.
     *
     * #### Iterator Validity
     * No changes.
     */
    iter() {
        let arr = [];
        for (let id of algorithm_1.toArray(this._cellOrder)) {
            arr.push(this._cellMap.get(id));
        }
        return new algorithm_1.ArrayIterator(arr);
    }
    /**
     * Dispose of the resources held by the cell list.
     */
    dispose() {
        if (this._isDisposed) {
            return;
        }
        this._isDisposed = true;
        signaling_1.Signal.clearData(this);
        // Clean up the cell map and cell order objects.
        for (let cell of this._cellMap.values()) {
            cell.dispose();
        }
        this._cellMap.dispose();
        this._cellOrder.dispose();
    }
    /**
     * Get the cell at the specified index.
     *
     * @param index - The positive integer index of interest.
     *
     * @returns The cell at the specified index.
     *
     * #### Complexity
     * Constant.
     *
     * #### Iterator Validity
     * No changes.
     *
     * #### Undefined Behavior
     * An `index` which is non-integral or out of range.
     */
    get(index) {
        return this._cellMap.get(this._cellOrder.get(index));
    }
    /**
     * Set the cell at the specified index.
     *
     * @param index - The positive integer index of interest.
     *
     * @param cell - The cell to set at the specified index.
     *
     * #### Complexity
     * Constant.
     *
     * #### Iterator Validity
     * No changes.
     *
     * #### Undefined Behavior
     * An `index` which is non-integral or out of range.
     *
     * #### Notes
     * This should be considered to transfer ownership of the
     * cell to the `CellList`. As such, `cell.dispose()` should
     * not be called by other actors.
     */
    set(index, cell) {
        // Set the internal data structures.
        this._cellMap.set(cell.id, cell);
        this._cellOrder.set(index, cell.id);
    }
    /**
     * Add a cell to the back of the cell list.
     *
     * @param cell - The cell to add to the back of the cell list.
     *
     * @returns The new length of the cell list.
     *
     * #### Complexity
     * Constant.
     *
     * #### Iterator Validity
     * No changes.
     *
     * #### Notes
     * This should be considered to transfer ownership of the
     * cell to the `CellList`. As such, `cell.dispose()` should
     * not be called by other actors.
     */
    push(cell) {
        // Set the internal data structures.
        this._cellMap.set(cell.id, cell);
        let num = this._cellOrder.push(cell.id);
        return num;
    }
    /**
     * Insert a cell into the cell list at a specific index.
     *
     * @param index - The index at which to insert the cell.
     *
     * @param cell - The cell to set at the specified index.
     *
     * @returns The new length of the cell list.
     *
     * #### Complexity
     * Linear.
     *
     * #### Iterator Validity
     * No changes.
     *
     * #### Notes
     * The `index` will be clamped to the bounds of the cell list.
     *
     * #### Undefined Behavior
     * An `index` which is non-integral.
     *
     * #### Notes
     * This should be considered to transfer ownership of the
     * cell to the `CellList`. As such, `cell.dispose()` should
     * not be called by other actors.
     */
    insert(index, cell) {
        // Set the internal data structures.
        this._cellMap.set(cell.id, cell);
        this._cellOrder.insert(index, cell.id);
    }
    /**
     * Remove the first occurrence of a cell from the cell list.
     *
     * @param cell - The cell of interest.
     *
     * @returns The index of the removed cell, or `-1` if the cell
     *   is not contained in the cell list.
     *
     * #### Complexity
     * Linear.
     *
     * #### Iterator Validity
     * Iterators pointing at the removed cell and beyond are invalidated.
     */
    removeValue(cell) {
        let index = algorithm_1.ArrayExt.findFirstIndex(algorithm_1.toArray(this._cellOrder), id => this._cellMap.get(id) === cell);
        this.remove(index);
        return index;
    }
    /**
     * Remove and return the cell at a specific index.
     *
     * @param index - The index of the cell of interest.
     *
     * @returns The cell at the specified index, or `undefined` if the
     *   index is out of range.
     *
     * #### Complexity
     * Constant.
     *
     * #### Iterator Validity
     * Iterators pointing at the removed cell and beyond are invalidated.
     *
     * #### Undefined Behavior
     * An `index` which is non-integral.
     */
    remove(index) {
        let id = this._cellOrder.get(index);
        this._cellOrder.remove(index);
        let cell = this._cellMap.get(id);
        return cell;
    }
    /**
     * Remove all cells from the cell list.
     *
     * #### Complexity
     * Linear.
     *
     * #### Iterator Validity
     * All current iterators are invalidated.
     */
    clear() {
        this._cellOrder.clear();
    }
    /**
     * Move a cell from one index to another.
     *
     * @parm fromIndex - The index of the element to move.
     *
     * @param toIndex - The index to move the element to.
     *
     * #### Complexity
     * Constant.
     *
     * #### Iterator Validity
     * Iterators pointing at the lesser of the `fromIndex` and the `toIndex`
     * and beyond are invalidated.
     *
     * #### Undefined Behavior
     * A `fromIndex` or a `toIndex` which is non-integral.
     */
    move(fromIndex, toIndex) {
        this._cellOrder.move(fromIndex, toIndex);
    }
    /**
     * Push a set of cells to the back of the cell list.
     *
     * @param cells - An iterable or array-like set of cells to add.
     *
     * @returns The new length of the cell list.
     *
     * #### Complexity
     * Linear.
     *
     * #### Iterator Validity
     * No changes.
     *
     * #### Notes
     * This should be considered to transfer ownership of the
     * cells to the `CellList`. As such, `cell.dispose()` should
     * not be called by other actors.
     */
    pushAll(cells) {
        let newValues = algorithm_1.toArray(cells);
        algorithm_1.each(newValues, cell => {
            // Set the internal data structures.
            this._cellMap.set(cell.id, cell);
            this._cellOrder.push(cell.id);
        });
        return this.length;
    }
    /**
     * Insert a set of items into the cell list at the specified index.
     *
     * @param index - The index at which to insert the cells.
     *
     * @param cells - The cells to insert at the specified index.
     *
     * @returns The new length of the cell list.
     *
     * #### Complexity.
     * Linear.
     *
     * #### Iterator Validity
     * No changes.
     *
     * #### Notes
     * The `index` will be clamped to the bounds of the cell list.
     *
     * #### Undefined Behavior.
     * An `index` which is non-integral.
     *
     * #### Notes
     * This should be considered to transfer ownership of the
     * cells to the `CellList`. As such, `cell.dispose()` should
     * not be called by other actors.
     */
    insertAll(index, cells) {
        let newValues = algorithm_1.toArray(cells);
        algorithm_1.each(newValues, cell => {
            this._cellMap.set(cell.id, cell);
            this._cellOrder.beginCompoundOperation();
            this._cellOrder.insert(index++, cell.id);
            this._cellOrder.endCompoundOperation();
        });
        return this.length;
    }
    /**
     * Remove a range of items from the cell list.
     *
     * @param startIndex - The start index of the range to remove (inclusive).
     *
     * @param endIndex - The end index of the range to remove (exclusive).
     *
     * @returns The new length of the cell list.
     *
     * #### Complexity
     * Linear.
     *
     * #### Iterator Validity
     * Iterators pointing to the first removed cell and beyond are invalid.
     *
     * #### Undefined Behavior
     * A `startIndex` or `endIndex` which is non-integral.
     */
    removeRange(startIndex, endIndex) {
        this._cellOrder.removeRange(startIndex, endIndex);
        return this.length;
    }
    /**
     * Whether the object can redo changes.
     */
    get canRedo() {
        return this._cellOrder.canRedo;
    }
    /**
     * Whether the object can undo changes.
     */
    get canUndo() {
        return this._cellOrder.canUndo;
    }
    /**
     * Begin a compound operation.
     *
     * @param isUndoAble - Whether the operation is undoable.
     *   The default is `true`.
     */
    beginCompoundOperation(isUndoAble) {
        this._cellOrder.beginCompoundOperation(isUndoAble);
    }
    /**
     * End a compound operation.
     */
    endCompoundOperation() {
        this._cellOrder.endCompoundOperation();
    }
    /**
     * Undo an operation.
     */
    undo() {
        this._cellOrder.undo();
    }
    /**
     * Redo an operation.
     */
    redo() {
        this._cellOrder.redo();
    }
    /**
     * Clear the change stack.
     */
    clearUndo() {
        // Dispose of cells not in the current
        // cell order.
        for (let key of this._cellMap.keys()) {
            if (algorithm_1.ArrayExt.findFirstIndex(algorithm_1.toArray(this._cellOrder), id => id === key) ===
                -1) {
                let cell = this._cellMap.get(key);
                cell.dispose();
                this._cellMap.delete(key);
            }
        }
        this._cellOrder.clearUndo();
    }
    _onOrderChanged(order, change) {
        if (change.type === 'add' || change.type === 'set') {
            algorithm_1.each(change.newValues, id => {
                if (!this._cellMap.has(id)) {
                    let cellDB = this._factory.modelDB;
                    let cellType = cellDB.createValue(id + '.type');
                    let cell;
                    switch (cellType.get()) {
                        case 'code':
                            cell = this._factory.createCodeCell({ id: id });
                            break;
                        case 'markdown':
                            cell = this._factory.createMarkdownCell({ id: id });
                            break;
                        default:
                            cell = this._factory.createRawCell({ id: id });
                            break;
                    }
                    this._cellMap.set(id, cell);
                }
            });
        }
        let newValues = [];
        let oldValues = [];
        algorithm_1.each(change.newValues, id => {
            newValues.push(this._cellMap.get(id));
        });
        algorithm_1.each(change.oldValues, id => {
            oldValues.push(this._cellMap.get(id));
        });
        this._changed.emit({
            type: change.type,
            oldIndex: change.oldIndex,
            newIndex: change.newIndex,
            oldValues,
            newValues
        });
    }
}
exports.CellList = CellList;


/***/ }),

/***/ "Ujlg":
/*!***************************************************!*\
  !*** ./node_modules/browserify-aes/modes/cfb1.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer

function encryptByte (self, byteParam, decrypt) {
  var pad
  var i = -1
  var len = 8
  var out = 0
  var bit, value
  while (++i < len) {
    pad = self._cipher.encryptBlock(self._prev)
    bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0
    value = pad[0] ^ bit
    out += ((value & 0x80) >> (i % 8))
    self._prev = shiftIn(self._prev, decrypt ? bit : value)
  }
  return out
}

function shiftIn (buffer, value) {
  var len = buffer.length
  var i = -1
  var out = Buffer.allocUnsafe(buffer.length)
  buffer = Buffer.concat([buffer, Buffer.from([value])])

  while (++i < len) {
    out[i] = buffer[i] << 1 | buffer[i + 1] >> (7)
  }

  return out
}

exports.encrypt = function (self, chunk, decrypt) {
  var len = chunk.length
  var out = Buffer.allocUnsafe(len)
  var i = -1

  while (++i < len) {
    out[i] = encryptByte(self, chunk[i], decrypt)
  }

  return out
}


/***/ }),

/***/ "UlQ5":
/*!********************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/application/style/sidepanel.css ***!
  \********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n/*-----------------------------------------------------------------------------\n| Variables\n|----------------------------------------------------------------------------*/\n\n:root {\n  --jp-private-sidebar-tab-width: 32px;\n}\n\n/*-----------------------------------------------------------------------------\n| SideBar\n|----------------------------------------------------------------------------*/\n\n.jp-SideBar {\n  /* This is needed so that all font sizing of children done in ems is\n   * relative to this base size */\n  font-size: var(--jp-ui-font-size1);\n}\n\n.jp-SideBar.p-TabBar {\n  color: var(--jp-ui-font-color1);\n  background: var(--jp-layout-color2);\n  font-size: var(--jp-ui-font-size1);\n  min-width: calc(var(--jp-private-sidebar-tab-width) + var(--jp-border-width));\n  max-width: calc(var(--jp-private-sidebar-tab-width) + var(--jp-border-width));\n  overflow: visible;\n  display: block;\n}\n\n.jp-SideBar .p-TabBar-content,\n.jp-SideBar .p-TabBar-content {\n  margin: 0;\n  padding: 0;\n  display: flex;\n  align-items: stretch;\n  list-style-type: none;\n  height: var(--jp-private-sidebar-tab-width);\n  transform-origin: 0 0 0;\n}\n\n.jp-SideBar .p-TabBar-tab {\n  padding: 0 16px;\n  border: none;\n  overflow: visible;\n}\n\n.jp-SideBar .p-TabBar-tab.p-mod-current {\n  min-height: calc(\n    var(--jp-private-sidebar-tab-width) + var(--jp-border-width)\n  );\n  max-height: calc(\n    var(--jp-private-sidebar-tab-width) + var(--jp-border-width)\n  );\n  /* transform: translateY(var(--jp-border-width)); */\n}\n\n.jp-SideBar .p-TabBar-tab:not(.p-mod-current) {\n  background: var(--jp-layout-color2);\n}\n\n.jp-SideBar .p-TabBar-tabIcon.jp-SideBar-tabIcon {\n  min-width: 20px;\n  min-height: 20px;\n  background-size: 20px;\n  display: inline-block;\n  vertical-align: middle;\n  background-repeat: no-repeat;\n  background-position: center;\n}\n\n.jp-SideBar .p-TabBar-tabLabel {\n  line-height: var(--jp-private-sidebar-tab-width);\n}\n\n.jp-SideBar .p-TabBar-tab:hover:not(.p-mod-current) {\n  background: var(--jp-layout-color1);\n}\n\n/* Left */\n\n/* Borders */\n\n.jp-SideBar.p-TabBar.jp-mod-left {\n  border-right: var(--jp-border-width) solid var(--jp-border-color0);\n}\n\n.jp-SideBar.p-TabBar.jp-mod-left .p-TabBar-tab + .p-TabBar-tab {\n  border-right: var(--jp-border-width) solid var(--jp-layout-color2);\n}\n\n.jp-SideBar.p-TabBar.jp-mod-left .p-TabBar-tab.p-mod-current + .p-TabBar-tab {\n  border-right: var(--jp-border-width) solid var(--jp-border-color0);\n}\n\n.jp-SideBar.p-TabBar.jp-mod-left .p-TabBar-tab + .p-TabBar-tab.p-mod-current {\n  border-right: var(--jp-border-width) solid var(--jp-border-color0);\n}\n\n.jp-SideBar.p-TabBar.jp-mod-left .p-TabBar-tab.p-mod-current:last-child {\n  border-left: var(--jp-border-width) solid var(--jp-border-color0);\n}\n\n/* Transforms */\n\n.jp-SideBar.p-TabBar.jp-mod-left .p-TabBar-content {\n  flex-direction: row-reverse;\n  transform: rotate(-90deg) translateX(-100%);\n}\n\n.jp-SideBar.p-TabBar.jp-mod-left\n  .p-TabBar-tab:not(.p-mod-current)\n  .p-TabBar-tabIcon {\n  transform: rotate(90deg);\n}\n\n.jp-SideBar.p-TabBar.jp-mod-left .p-TabBar-tab.p-mod-current .p-TabBar-tabIcon {\n  transform: rotate(90deg)\n    translate(\n      calc(-0.5 * var(--jp-border-width)),\n      calc(-0.5 * var(--jp-border-width))\n    );\n}\n\n/* Right */\n\n/* Borders */\n\n.jp-SideBar.p-TabBar.jp-mod-right {\n  border-left: var(--jp-border-width) solid var(--jp-border-color0);\n}\n\n.jp-SideBar.p-TabBar.jp-mod-right .p-TabBar-tab + .p-TabBar-tab {\n  border-left: var(--jp-border-width) solid var(--jp-layout-color2);\n}\n\n.jp-SideBar.p-TabBar.jp-mod-right .p-TabBar-tab.p-mod-current + .p-TabBar-tab {\n  border-left: var(--jp-border-width) solid var(--jp-border-color0);\n}\n\n.jp-SideBar.p-TabBar.jp-mod-right .p-TabBar-tab + .p-TabBar-tab.p-mod-current {\n  border-left: var(--jp-border-width) solid var(--jp-border-color0);\n}\n\n.jp-SideBar.p-TabBar.jp-mod-right .p-TabBar-tab.p-mod-current:last-child {\n  border-right: var(--jp-border-width) solid var(--jp-border-color0);\n}\n\n/* Transforms */\n\n.jp-SideBar.p-TabBar.jp-mod-right .p-TabBar-content {\n  flex-direction: row;\n  transform: rotate(90deg) translateY(-100%);\n}\n\n.jp-SideBar.p-TabBar.jp-mod-right\n  .p-TabBar-tab:not(.p-mod-current)\n  .p-TabBar-tabIcon {\n  transform: rotate(-90deg);\n}\n\n.jp-SideBar.p-TabBar.jp-mod-right\n  .p-TabBar-tab.p-mod-current\n  .p-TabBar-tabIcon {\n  transform: rotate(-90deg)\n    translate(\n      calc(0.5 * var(--jp-border-width)),\n      calc(-0.5 * var(--jp-border-width))\n    );\n}\n\n/* Stack panels */\n\n#jp-left-stack > .p-Widget,\n#jp-right-stack > .p-Widget {\n  min-width: var(--jp-sidebar-min-width);\n}\n\n#jp-right-stack {\n  border-left: var(--jp-border-width) solid var(--jp-border-color1);\n}\n\n#jp-left-stack {\n  border-right: var(--jp-border-width) solid var(--jp-border-color1);\n}\n", ""]);

// exports


/***/ }),

/***/ "UpF+":
/*!***************************************************!*\
  !*** ./node_modules/public-encrypt/withPublic.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var BN = __webpack_require__(/*! bn.js */ "OZ/i")
var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer

function withPublic (paddedMsg, key) {
  return Buffer.from(paddedMsg
    .toRed(BN.mont(key.modulus))
    .redPow(new BN(key.publicExponent))
    .fromRed()
    .toArray())
}

module.exports = withPublic


/***/ }),

/***/ "UpQW":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/ur.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var months = [
    'جنوری',
    'فروری',
    'مارچ',
    'اپریل',
    'مئی',
    'جون',
    'جولائی',
    'اگست',
    'ستمبر',
    'اکتوبر',
    'نومبر',
    'دسمبر'
];
var days = [
    'اتوار',
    'پیر',
    'منگل',
    'بدھ',
    'جمعرات',
    'جمعہ',
    'ہفتہ'
];

var ur = moment.defineLocale('ur', {
    months : months,
    monthsShort : months,
    weekdays : days,
    weekdaysShort : days,
    weekdaysMin : days,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd، D MMMM YYYY HH:mm'
    },
    meridiemParse: /صبح|شام/,
    isPM : function (input) {
        return 'شام' === input;
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 12) {
            return 'صبح';
        }
        return 'شام';
    },
    calendar : {
        sameDay : '[آج بوقت] LT',
        nextDay : '[کل بوقت] LT',
        nextWeek : 'dddd [بوقت] LT',
        lastDay : '[گذشتہ روز بوقت] LT',
        lastWeek : '[گذشتہ] dddd [بوقت] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : '%s بعد',
        past : '%s قبل',
        s : 'چند سیکنڈ',
        ss : '%d سیکنڈ',
        m : 'ایک منٹ',
        mm : '%d منٹ',
        h : 'ایک گھنٹہ',
        hh : '%d گھنٹے',
        d : 'ایک دن',
        dd : '%d دن',
        M : 'ایک ماہ',
        MM : '%d ماہ',
        y : 'ایک سال',
        yy : '%d سال'
    },
    preparse: function (string) {
        return string.replace(/،/g, ',');
    },
    postformat: function (string) {
        return string.replace(/,/g, '،');
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return ur;

})));


/***/ }),

/***/ "UpXw":
/*!******************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/default_panels/StyleAxesPanel.js ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _components = __webpack_require__(/*! ../components */ "yF51");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var StyleAxesPanel = function (_Component) {
  _inherits(StyleAxesPanel, _Component);

  function StyleAxesPanel() {
    _classCallCheck(this, StyleAxesPanel);

    return _possibleConstructorReturn(this, (StyleAxesPanel.__proto__ || Object.getPrototypeOf(StyleAxesPanel)).apply(this, arguments));
  }

  _createClass(StyleAxesPanel, [{
    key: 'render',
    value: function render() {
      var _ = this.context.localize;

      return _react2.default.createElement(
        _components.LayoutPanel,
        null,
        _react2.default.createElement(
          _components.AxesFold,
          {
            name: _('Titles'),
            axisFilter: function axisFilter(axis) {
              return !(axis._name.includes('angular') || axis._subplot.includes('geo'));
            }
          },
          _react2.default.createElement(_components.TextEditor, { attr: 'title.text' }),
          _react2.default.createElement(_components.FontSelector, { label: _('Typeface'), attr: 'title.font.family' }),
          _react2.default.createElement(_components.Numeric, { label: _('Font Size'), attr: 'title.font.size', units: 'px' }),
          _react2.default.createElement(_components.ColorPicker, { label: _('Font Color'), attr: 'title.font.color' })
        ),
        _react2.default.createElement(
          _components.AxesFold,
          { name: _('Range') },
          _react2.default.createElement(
            _components.PlotlySection,
            { name: _('Range'), attr: 'autorange' },
            _react2.default.createElement(_components.Dropdown, {
              attr: 'type',
              label: _('Type'),
              clearable: false,
              options: [{ label: _('Linear'), value: 'linear' }, { label: _('Log'), value: 'log' }, { label: _('Date'), value: 'date' }, { label: _('Categorical'), value: 'category' }, { label: _('Multicategorical'), value: 'multicategory' }]
            }),
            _react2.default.createElement(_components.Radio, {
              attr: 'autorange',
              label: _('Range'),
              options: [{ label: _('Auto'), value: true }, { label: _('Custom'), value: false }]
            }),
            _react2.default.createElement(_components.AxesRange, { label: _('Min'), attr: 'range[0]' }),
            _react2.default.createElement(_components.AxesRange, { label: _('Max'), attr: 'range[1]' }),
            _react2.default.createElement(_components.Numeric, { label: _('Min'), attr: 'min' })
          ),
          _react2.default.createElement(
            _components.PlotlySection,
            { name: _('Zoom Interactivity'), attr: 'fixedrange' },
            _react2.default.createElement(_components.Radio, {
              attr: 'fixedrange',
              options: [{ label: _('Enable'), value: false }, { label: _('Disable'), value: true }]
            })
          ),
          _react2.default.createElement(_components.Dropdown, {
            label: _('Direction'),
            attr: 'direction',
            options: [{ label: _('Clockwise'), value: 'clockwise' }, { label: _('Counter Clockwise'), value: 'counterclockwise' }],
            clearable: false
          })
        ),
        _react2.default.createElement(
          _components.AxesFold,
          { name: _('Lines') },
          _react2.default.createElement(
            _components.PlotlySection,
            { name: _('Axis Line'), attr: 'showline' },
            _react2.default.createElement(
              _components.VisibilitySelect,
              {
                attr: 'showline',
                options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }],
                showOn: true,
                defaultOpt: true
              },
              _react2.default.createElement(_components.Numeric, { label: _('Thickness'), attr: 'linewidth', units: 'px' }),
              _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'linecolor' }),
              _react2.default.createElement(_components.AxisSide, { label: _('Position'), attr: 'side' }),
              _react2.default.createElement(_components.Radio, {
                label: _('Mirror Axis'),
                attr: 'mirror',
                options: [{ label: _('On'), value: 'ticks' }, { label: _('Off'), value: false }]
              })
            )
          ),
          _react2.default.createElement(
            _components.PlotlySection,
            { name: _('Grid Lines'), attr: 'showgrid' },
            _react2.default.createElement(
              _components.VisibilitySelect,
              {
                attr: 'showgrid',
                options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }],
                showOn: true,
                defaultOpt: true
              },
              _react2.default.createElement(_components.Numeric, { label: _('Thickness'), attr: 'gridwidth', units: 'px' }),
              _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'gridcolor' }),
              _react2.default.createElement(_components.Radio, {
                label: _('Position On'),
                attr: 'tickson',
                options: [{ label: _('Labels'), value: 'labels' }, { label: _('Boundaries'), value: 'boundaries' }]
              }),
              _react2.default.createElement(_components.Radio, {
                label: _('Grid Spacing'),
                attr: 'tickmode',
                options: [{ label: _('Auto'), value: 'auto' }, { label: _('Custom'), value: 'linear' }]
              }),
              _react2.default.createElement(_components.DTicks, { label: _('Step Offset'), attr: 'tick0' }),
              _react2.default.createElement(_components.DTicksInterval, { label: _('Step Size'), attr: 'dtick' }),
              _react2.default.createElement(_components.NTicks, { label: _('Max Number of Lines'), attr: 'nticks' })
            )
          ),
          _react2.default.createElement(
            _components.PlotlySection,
            { name: _('Zero Line'), attr: 'zeroline' },
            _react2.default.createElement(_components.Radio, {
              attr: 'zeroline',
              options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
            }),
            _react2.default.createElement(_components.Numeric, { label: _('Thickness'), attr: 'zerolinewidth', units: 'px' }),
            _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'zerolinecolor' })
          ),
          _react2.default.createElement(
            _components.PlotlySection,
            { name: _('Axis Background'), attr: 'showbackground' },
            _react2.default.createElement(_components.Radio, {
              attr: 'showbackground',
              options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
            }),
            _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'backgroundcolor' })
          )
        ),
        _react2.default.createElement(
          _components.AxesFold,
          { name: _('Tick Labels'), axisFilter: function axisFilter(axis) {
              return !axis._subplot.includes('geo');
            } },
          _react2.default.createElement(
            _components.PlotlySection,
            { name: _('Tick Labels'), attr: 'showticklabels' },
            _react2.default.createElement(
              _components.VisibilitySelect,
              {
                attr: 'showticklabels',
                options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }],
                showOn: true,
                defaultOpt: true
              },
              _react2.default.createElement(_components.AxisSide, { label: _('Position'), attr: 'side' }),
              _react2.default.createElement(_components.Radio, {
                label: _('Auto margins'),
                attr: 'automargin',
                options: [{ label: _('True'), value: true }, { label: _('False'), value: false }]
              }),
              _react2.default.createElement(_components.Radio, {
                label: _('Position on'),
                attr: 'tickson',
                options: [{ label: _('Labels'), value: 'labels' }, { label: _('Boundaries'), value: 'boundaries' }]
              }),
              _react2.default.createElement(_components.FontSelector, { label: _('Typeface'), attr: 'tickfont.family' }),
              _react2.default.createElement(_components.Numeric, { label: _('Font Size'), attr: 'tickfont.size', units: 'px' }),
              _react2.default.createElement(_components.ColorPicker, { label: _('Font Color'), attr: 'tickfont.color' }),
              _react2.default.createElement(_components.Dropdown, {
                label: _('Angle'),
                attr: 'tickangle',
                clearable: false,
                options: [{ label: _('Auto'), value: 'auto' }, { label: _('45'), value: 45 }, { label: _('90'), value: 90 }, { label: _('135'), value: 135 }, { label: _('180'), value: 180 }]
              }),
              _react2.default.createElement(_components.TickFormat, {
                label: _('Label Format'),
                attr: 'tickformat',
                dafaultOpt: '',
                clearable: false
              }),
              _react2.default.createElement(_components.Radio, {
                label: _('Separate Thousands'),
                attr: 'separatethousands',
                options: [{ label: _('True'), value: true }, { label: _('False'), value: false }]
              }),
              _react2.default.createElement(_components.Dropdown, {
                label: _('Exponents'),
                attr: 'exponentformat',
                clearable: false,
                options: [{ label: _('None'), value: 'none' }, { label: _('e+6'), value: 'e' }, { label: _('E+6'), value: 'E' }, { label: _('x10^6'), value: 'power' }, { label: _('k/M/G'), value: 'SI' }, { label: _('k/M/B'), value: 'B' }]
              }),
              _react2.default.createElement(_components.Dropdown, {
                label: _('Show Exponents'),
                attr: 'showexponent',
                clearable: false,
                options: [{ label: _('All'), value: 'all' }, { label: _('First'), value: 'first' }, { label: _('Last'), value: 'last' }, { label: _('None'), value: 'none' }]
              }),
              _react2.default.createElement(_components.DropdownCustom, {
                label: _('Prefix'),
                attr: 'tickprefix',
                options: [{ label: _('None'), value: '' }, { label: _('x'), value: 'x' }, { label: _('$'), value: '$' }, { label: _('#'), value: '#' }, { label: _('@'), value: '@' }, { label: _('Custom'), value: 'custom' }],
                customOpt: 'custom',
                dafaultOpt: '',
                clearable: false
              }),
              _react2.default.createElement(_components.Dropdown, {
                label: _('Show Prefix'),
                attr: 'showtickprefix',
                options: [{ label: _('Every label'), value: 'all' }, { label: _('First label'), value: 'first' }, { label: _('Last label'), value: 'last' }, { label: _('None'), value: 'none' }]
              }),
              _react2.default.createElement(_components.DropdownCustom, {
                label: _('Suffix'),
                attr: 'ticksuffix',
                options: [{ label: _('None'), value: '' }, { label: _('C'), value: 'C' }, { label: _('%'), value: '%' }, { label: _('^'), value: '^' }, { label: _('Custom'), value: 'custom' }],
                customOpt: 'custom',
                dafaultOpt: '',
                clearable: false
              }),
              _react2.default.createElement(_components.Dropdown, {
                label: _('Show Suffix'),
                attr: 'showticksuffix',
                options: [{ label: _('Every label'), value: 'all' }, { label: _('First label'), value: 'first' }, { label: _('Last label'), value: 'last' }, { label: _('None'), value: 'none' }]
              }),
              _react2.default.createElement(_components.Radio, {
                label: _('Tick Spacing'),
                attr: 'tickmode',
                options: [{ label: _('Auto'), value: 'auto' }, { label: _('Custom'), value: 'linear' }]
              }),
              _react2.default.createElement(_components.DTicks, { label: _('Step Offset'), attr: 'tick0' }),
              _react2.default.createElement(_components.DTicksInterval, { label: _('Step Size'), attr: 'dtick' }),
              _react2.default.createElement(_components.NTicks, { label: _('Max Number of Labels'), attr: 'nticks' })
            )
          )
        ),
        _react2.default.createElement(
          _components.AxesFold,
          { name: _('Tick Markers'), axisFilter: function axisFilter(axis) {
              return !axis._subplot.includes('geo');
            } },
          _react2.default.createElement(
            _components.PlotlySection,
            { name: _('Tick Markers'), attr: 'ticks' },
            _react2.default.createElement(
              _components.VisibilitySelect,
              {
                attr: 'ticks',
                options: [{ label: _('Inside'), value: 'inside' }, { label: _('Outside'), value: 'outside' }, { label: _('Hide'), value: '' }],
                showOn: ['inside', 'outside'],
                defaultOpt: 'Outside'
              },
              _react2.default.createElement(_components.AxisSide, { label: _('Position'), attr: 'side' }),
              _react2.default.createElement(_components.Radio, {
                label: _('Position on'),
                attr: 'tickson',
                options: [{ label: _('Labels'), value: 'labels' }, { label: _('Boundaries'), value: 'boundaries' }]
              }),
              _react2.default.createElement(_components.Numeric, { label: _('Length'), attr: 'ticklen', units: 'px' }),
              _react2.default.createElement(_components.Numeric, { label: _('Width'), attr: 'tickwidth', units: 'px' }),
              _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'tickcolor' }),
              _react2.default.createElement(_components.Radio, {
                label: _('Tick Spacing'),
                attr: 'tickmode',
                options: [{ label: _('Auto'), value: 'auto' }, { label: _('Custom'), value: 'linear' }]
              }),
              _react2.default.createElement(_components.DTicks, { label: _('Step Offset'), attr: 'tick0' }),
              _react2.default.createElement(_components.DTicksInterval, { label: _('Step Size'), attr: 'dtick' }),
              _react2.default.createElement(_components.NTicks, { label: _('Max Number of Markers'), attr: 'nticks' })
            )
          ),
          _react2.default.createElement(
            _components.PlotlySection,
            { name: _('Multicategory Dividers'), attr: 'showdividers' },
            _react2.default.createElement(
              _components.VisibilitySelect,
              {
                attr: 'showdividers',
                options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }],
                showOn: true
              },
              _react2.default.createElement(_components.Numeric, { label: _('Width'), attr: 'dividerwidth', units: 'px' }),
              _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'dividercolor' })
            )
          )
        ),
        _react2.default.createElement(
          _components.AxesFold,
          { name: _('Range Slider'), axisFilter: function axisFilter(axis) {
              return axis._subplot.includes('xaxis');
            } },
          _react2.default.createElement(_components.RangesliderVisible, {
            attr: 'rangeslider.visible',
            options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
          }),
          _react2.default.createElement(_components.NumericFraction, { label: _('Height'), attr: 'rangeslider.thickness' }),
          _react2.default.createElement(_components.ColorPicker, { label: _('Background Color'), attr: 'rangeslider.bgcolor' }),
          _react2.default.createElement(_components.Numeric, { label: _('Border Width'), attr: 'rangeslider.borderwidth', units: 'px' }),
          _react2.default.createElement(_components.ColorPicker, { label: _('Border Color'), attr: 'rangeslider.bordercolor' })
        ),
        _react2.default.createElement(
          _components.AxesFold,
          {
            name: _('Timescale Buttons'),
            axisFilter: function axisFilter(axis) {
              return axis._subplot.includes('xaxis') && axis.type === 'date';
            }
          },
          _react2.default.createElement(_components.Radio, {
            attr: 'rangeselector.visible',
            options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
          }),
          _react2.default.createElement(
            _components.RangeSelectorAccordion,
            null,
            _react2.default.createElement(_components.TextEditor, { attr: 'label', label: _('Label'), show: true }),
            _react2.default.createElement(_components.Numeric, { label: _('Count'), attr: 'count' }),
            _react2.default.createElement(_components.Dropdown, {
              label: _('Step'),
              attr: 'step',
              clearable: false,
              options: [{ label: _('Year'), value: 'year' }, { label: _('Month'), value: 'month' }, { label: _('Day'), value: 'day' }, { label: _('Hour'), value: 'hour' }, { label: _('Minute'), value: 'minute' }, { label: _('Second'), value: 'second' }, { label: _('All'), value: 'all' }]
            }),
            _react2.default.createElement(_components.Dropdown, {
              label: _('Stepmode'),
              attr: 'stepmode',
              clearable: false,
              options: [{ label: _('To Date'), value: 'todate' }, { label: _('Backward'), value: 'backward' }]
            })
          ),
          _react2.default.createElement(
            _components.PlotlySection,
            { name: _('Text') },
            _react2.default.createElement(_components.FontSelector, { label: _('Typeface'), attr: 'rangeselector.font.family' }),
            _react2.default.createElement(_components.Numeric, { label: _('Font Size'), attr: 'rangeselector.font.size', units: 'px' }),
            _react2.default.createElement(_components.ColorPicker, { label: _('Font Color'), attr: 'rangeselector.font.color' })
          ),
          _react2.default.createElement(
            _components.PlotlySection,
            { name: _('Style') },
            _react2.default.createElement(_components.ColorPicker, { label: _('Background Color'), attr: 'rangeselector.bgcolor' }),
            _react2.default.createElement(_components.ColorPicker, { label: _('Active Color'), attr: 'rangeselector.activecolor' }),
            _react2.default.createElement(_components.Numeric, { label: _('Border Width'), attr: 'rangeselector.borderwidth', units: 'px' }),
            _react2.default.createElement(_components.ColorPicker, { label: _('Border Color'), attr: 'rangeselector.bordercolor' })
          ),
          _react2.default.createElement(
            _components.PlotlySection,
            { name: _('Horizontal Positioning') },
            _react2.default.createElement(_components.Dropdown, {
              label: _('Anchor Point'),
              clearable: false,
              attr: 'rangeselector.xanchor',
              options: [{ label: _('Auto'), value: 'auto' }, { label: _('Left'), value: 'left' }, { label: _('Center'), value: 'center' }, { label: _('Right'), value: 'right' }]
            }),
            _react2.default.createElement(_components.Numeric, { label: _('Position'), step: 0.02, attr: 'rangeselector.x' })
          ),
          _react2.default.createElement(
            _components.PlotlySection,
            { name: _('Vertical Positioning') },
            _react2.default.createElement(_components.Dropdown, {
              label: _('Anchor Point'),
              clearable: false,
              attr: 'rangeselector.yanchor',
              options: [{ label: _('Auto'), value: 'auto' }, { label: _('Top'), value: 'top' }, { label: _('Middle'), value: 'middle' }, { label: _('Bottom'), value: 'bottom' }]
            }),
            _react2.default.createElement(_components.Numeric, { label: _('Position'), step: 0.02, attr: 'rangeselector.y' })
          )
        ),
        _react2.default.createElement(
          _components.AxesFold,
          {
            name: _('Spike Lines'),
            axisFilter: function axisFilter(axis) {
              return !(axis._subplot.includes('ternary') || axis._subplot.includes('polar') || axis._subplot.includes('geo'));
            }
          },
          _react2.default.createElement(_components.Radio, {
            attr: 'showspikes',
            options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
          }),
          _react2.default.createElement(_components.Radio, {
            attr: 'spikesides',
            label: _('Show Sides'),
            options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
          }),
          _react2.default.createElement(_components.Numeric, { label: _('Thickness'), attr: 'spikethickness', units: 'px' }),
          _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'spikecolor' })
        )
      );
    }
  }]);

  return StyleAxesPanel;
}(_react.Component);

StyleAxesPanel.contextTypes = {
  fullLayout: _propTypes2.default.object,
  localize: _propTypes2.default.func
};

exports.default = StyleAxesPanel;
//# sourceMappingURL=StyleAxesPanel.js.map

/***/ }),

/***/ "Ur1D":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/ss.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var ss = moment.defineLocale('ss', {
    months : "Bhimbidvwane_Indlovana_Indlov'lenkhulu_Mabasa_Inkhwekhweti_Inhlaba_Kholwane_Ingci_Inyoni_Imphala_Lweti_Ingongoni".split('_'),
    monthsShort : 'Bhi_Ina_Inu_Mab_Ink_Inh_Kho_Igc_Iny_Imp_Lwe_Igo'.split('_'),
    weekdays : 'Lisontfo_Umsombuluko_Lesibili_Lesitsatfu_Lesine_Lesihlanu_Umgcibelo'.split('_'),
    weekdaysShort : 'Lis_Umb_Lsb_Les_Lsi_Lsh_Umg'.split('_'),
    weekdaysMin : 'Li_Us_Lb_Lt_Ls_Lh_Ug'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'h:mm A',
        LTS : 'h:mm:ss A',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY h:mm A',
        LLLL : 'dddd, D MMMM YYYY h:mm A'
    },
    calendar : {
        sameDay : '[Namuhla nga] LT',
        nextDay : '[Kusasa nga] LT',
        nextWeek : 'dddd [nga] LT',
        lastDay : '[Itolo nga] LT',
        lastWeek : 'dddd [leliphelile] [nga] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'nga %s',
        past : 'wenteka nga %s',
        s : 'emizuzwana lomcane',
        ss : '%d mzuzwana',
        m : 'umzuzu',
        mm : '%d emizuzu',
        h : 'lihora',
        hh : '%d emahora',
        d : 'lilanga',
        dd : '%d emalanga',
        M : 'inyanga',
        MM : '%d tinyanga',
        y : 'umnyaka',
        yy : '%d iminyaka'
    },
    meridiemParse: /ekuseni|emini|entsambama|ebusuku/,
    meridiem : function (hours, minutes, isLower) {
        if (hours < 11) {
            return 'ekuseni';
        } else if (hours < 15) {
            return 'emini';
        } else if (hours < 19) {
            return 'entsambama';
        } else {
            return 'ebusuku';
        }
    },
    meridiemHour : function (hour, meridiem) {
        if (hour === 12) {
            hour = 0;
        }
        if (meridiem === 'ekuseni') {
            return hour;
        } else if (meridiem === 'emini') {
            return hour >= 11 ? hour : hour + 12;
        } else if (meridiem === 'entsambama' || meridiem === 'ebusuku') {
            if (hour === 0) {
                return 0;
            }
            return hour + 12;
        }
    },
    dayOfMonthOrdinalParse: /\d{1,2}/,
    ordinal : '%d',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return ss;

})));


/***/ }),

/***/ "Uwf0":
/*!*****************************************************!*\
  !*** ./node_modules/htmlparser2/lib/FeedHandler.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var DomHandler = __webpack_require__(/*! domhandler */ "Nsz2");
var DomUtils = __webpack_require__(/*! domutils */ "D5Sy");

//TODO: make this a streamable handler
function FeedHandler(callback, options) {
    this.init(callback, options);
}

__webpack_require__(/*! inherits */ "P7XM")(FeedHandler, DomHandler);

FeedHandler.prototype.init = DomHandler;

function getElements(what, where) {
    return DomUtils.getElementsByTagName(what, where, true);
}
function getOneElement(what, where) {
    return DomUtils.getElementsByTagName(what, where, true, 1)[0];
}
function fetch(what, where, recurse) {
    return DomUtils.getText(
        DomUtils.getElementsByTagName(what, where, recurse, 1)
    ).trim();
}

function addConditionally(obj, prop, what, where, recurse) {
    var tmp = fetch(what, where, recurse);
    if (tmp) obj[prop] = tmp;
}

var isValidFeed = function(value) {
    return value === "rss" || value === "feed" || value === "rdf:RDF";
};

FeedHandler.prototype.onend = function() {
    var feed = {},
        feedRoot = getOneElement(isValidFeed, this.dom),
        tmp,
        childs;

    if (feedRoot) {
        if (feedRoot.name === "feed") {
            childs = feedRoot.children;

            feed.type = "atom";
            addConditionally(feed, "id", "id", childs);
            addConditionally(feed, "title", "title", childs);
            if (
                (tmp = getOneElement("link", childs)) &&
                (tmp = tmp.attribs) &&
                (tmp = tmp.href)
            )
                feed.link = tmp;
            addConditionally(feed, "description", "subtitle", childs);
            if ((tmp = fetch("updated", childs))) feed.updated = new Date(tmp);
            addConditionally(feed, "author", "email", childs, true);

            feed.items = getElements("entry", childs).map(function(item) {
                var entry = {},
                    tmp;

                item = item.children;

                addConditionally(entry, "id", "id", item);
                addConditionally(entry, "title", "title", item);
                if (
                    (tmp = getOneElement("link", item)) &&
                    (tmp = tmp.attribs) &&
                    (tmp = tmp.href)
                )
                    entry.link = tmp;
                if ((tmp = fetch("summary", item) || fetch("content", item)))
                    entry.description = tmp;
                if ((tmp = fetch("updated", item)))
                    entry.pubDate = new Date(tmp);
                return entry;
            });
        } else {
            childs = getOneElement("channel", feedRoot.children).children;

            feed.type = feedRoot.name.substr(0, 3);
            feed.id = "";
            addConditionally(feed, "title", "title", childs);
            addConditionally(feed, "link", "link", childs);
            addConditionally(feed, "description", "description", childs);
            if ((tmp = fetch("lastBuildDate", childs)))
                feed.updated = new Date(tmp);
            addConditionally(feed, "author", "managingEditor", childs, true);

            feed.items = getElements("item", feedRoot.children).map(function(
                item
            ) {
                var entry = {},
                    tmp;

                item = item.children;

                addConditionally(entry, "id", "guid", item);
                addConditionally(entry, "title", "title", item);
                addConditionally(entry, "link", "link", item);
                addConditionally(entry, "description", "description", item);
                if ((tmp = fetch("pubDate", item)))
                    entry.pubDate = new Date(tmp);
                return entry;
            });
        }
    }
    this.dom = feed;
    DomHandler.prototype._handleCallback.call(
        this,
        feedRoot ? null : Error("couldn't find root of feed")
    );
};

module.exports = FeedHandler;


/***/ }),

/***/ "V/5U":
/*!********************************************!*\
  !*** ./node_modules/base16/lib/isotope.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'isotope',
  author: 'jan t. sott',
  base00: '#000000',
  base01: '#404040',
  base02: '#606060',
  base03: '#808080',
  base04: '#c0c0c0',
  base05: '#d0d0d0',
  base06: '#e0e0e0',
  base07: '#ffffff',
  base08: '#ff0000',
  base09: '#ff9900',
  base0A: '#ff0099',
  base0B: '#33ff00',
  base0C: '#00ffff',
  base0D: '#0066ff',
  base0E: '#cc00ff',
  base0F: '#3300ff'
};
module.exports = exports['default'];

/***/ }),

/***/ "V2x9":
/*!*******************************************!*\
  !*** ./node_modules/moment/locale/tet.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var tet = moment.defineLocale('tet', {
    months : 'Janeiru_Fevereiru_Marsu_Abril_Maiu_Juñu_Jullu_Agustu_Setembru_Outubru_Novembru_Dezembru'.split('_'),
    monthsShort : 'Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez'.split('_'),
    weekdays : 'Domingu_Segunda_Tersa_Kuarta_Kinta_Sesta_Sabadu'.split('_'),
    weekdaysShort : 'Dom_Seg_Ters_Kua_Kint_Sest_Sab'.split('_'),
    weekdaysMin : 'Do_Seg_Te_Ku_Ki_Ses_Sa'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd, D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay: '[Ohin iha] LT',
        nextDay: '[Aban iha] LT',
        nextWeek: 'dddd [iha] LT',
        lastDay: '[Horiseik iha] LT',
        lastWeek: 'dddd [semana kotuk] [iha] LT',
        sameElse: 'L'
    },
    relativeTime : {
        future : 'iha %s',
        past : '%s liuba',
        s : 'minutu balun',
        ss : 'minutu %d',
        m : 'minutu ida',
        mm : 'minutu %d',
        h : 'oras ida',
        hh : 'oras %d',
        d : 'loron ida',
        dd : 'loron %d',
        M : 'fulan ida',
        MM : 'fulan %d',
        y : 'tinan ida',
        yy : 'tinan %d'
    },
    dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/,
    ordinal : function (number) {
        var b = number % 10,
            output = (~~(number % 100 / 10) === 1) ? 'th' :
            (b === 1) ? 'st' :
            (b === 2) ? 'nd' :
            (b === 3) ? 'rd' : 'th';
        return number + output;
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return tet;

})));


/***/ }),

/***/ "V4vH":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/observables/lib/index.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(__webpack_require__(/*! ./modeldb */ "q9eo"));
__export(__webpack_require__(/*! ./observablejson */ "LY7c"));
__export(__webpack_require__(/*! ./observablelist */ "eXBS"));
__export(__webpack_require__(/*! ./observablemap */ "14pl"));
__export(__webpack_require__(/*! ./observablestring */ "eiat"));
__export(__webpack_require__(/*! ./undoablelist */ "VmqU"));


/***/ }),

/***/ "V5+5":
/*!***************************************************!*\
  !*** ./node_modules/mdi-react/ChevronLeftIcon.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var ChevronLeftIcon = function ChevronLeftIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M15.41,16.58L10.83,12L15.41,7.41L14,6L8,12L14,18L15.41,16.58Z' })
  );
};

module.exports = ChevronLeftIcon;


/***/ }),

/***/ "V6Tf":
/*!********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/default_panels/GraphCreatePanel.js ***!
  \********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _components = __webpack_require__(/*! ../components */ "yF51");

var _derived = __webpack_require__(/*! ../components/fields/derived */ "5og8");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var GraphCreatePanel = function GraphCreatePanel(props, _ref) {
  var _ = _ref.localize,
      setPanel = _ref.setPanel;

  return _react2.default.createElement(
    _components.TraceAccordion,
    {
      canAdd: true,
      traceFilterCondition: function traceFilterCondition(t) {
        return !(t.transforms && t.transforms.some(function (tr) {
          return ['fit', 'moving-average'].includes(tr.type);
        }));
      }
    },
    _react2.default.createElement(_components.TraceSelector, { label: _('Type'), attr: 'type', show: true }),
    _react2.default.createElement(_components.LocationSelector, { attr: 'type' }),
    _react2.default.createElement(_components.DataSelector, { label: _('Values'), attr: 'values' }),
    _react2.default.createElement(_components.DataSelector, { label: _('Labels'), attr: 'labels' }),
    _react2.default.createElement(_components.DataSelector, {
      label: {
        histogram2d: _('X Values'),
        histogram: _('X Values'),
        '*': _('X')
      },
      attr: 'x'
    }),
    _react2.default.createElement(_components.DataSelector, {
      label: {
        histogram2d: _('Y Values'),
        histogram: _('Y Values'),
        '*': _('Y')
      },
      attr: 'y'
    }),
    _react2.default.createElement(_components.DataSelector, {
      label: {
        choropleth: _('Values'),
        histogram2d: _('Z Values'),
        '*': _('Z')
      },
      attr: 'z'
    }),
    _react2.default.createElement(_components.Radio, {
      label: _('Orientation'),
      attr: 'orientation',
      options: [{ label: _('Vertical'), value: 'v' }, { label: _('Horizontal'), value: 'h' }]
    }),
    _react2.default.createElement(
      _derived.HistogramInfoVertical,
      null,
      _('Note: in vertical orientation, X values are used for binning. If Y values are provided, they are used as inputs to the histogram function which you can configure in the '),
      _react2.default.createElement(
        'a',
        { onClick: function onClick() {
            return setPanel('Style', 'Traces');
          } },
        _('Traces')
      ),
      _(' panel under Style. If Y values are omitted, the histogram function defaults to Count.')
    ),
    _react2.default.createElement(
      _derived.HistogramInfoHorizontal,
      null,
      _('Note: in horizontal orientation, Y values are used for binning. If X values are provided, they are used as inputs to the histogram function which you can configure in the '),
      _react2.default.createElement(
        'a',
        { onClick: function onClick() {
            return setPanel('Style', 'Traces');
          } },
        _('Traces')
      ),
      _(' under Style panel. If X values are omitted, the histogram function defaults to Count.')
    ),
    _react2.default.createElement(
      _derived.Histogram2d,
      null,
      _('Note: X and Y Values are used for binning. If Z values are provided, they are used as inputs to the histogram function which you can configure in the '),
      _react2.default.createElement(
        'a',
        { onClick: function onClick() {
            return setPanel('Style', 'Traces');
          } },
        _('Traces')
      ),
      _(' under Style panel. If Z values are omitted, the histogram function defaults to Count.')
    ),
    _react2.default.createElement(_components.DataSelector, { label: _('I (Optional)'), attr: 'i' }),
    _react2.default.createElement(_components.DataSelector, { label: _('J (Optional)'), attr: 'j' }),
    _react2.default.createElement(_components.DataSelector, { label: _('K (Optional)'), attr: 'k' }),
    _react2.default.createElement(_components.DataSelector, { label: _('Open'), attr: 'open' }),
    _react2.default.createElement(_components.DataSelector, { label: _('High'), attr: 'high' }),
    _react2.default.createElement(_components.DataSelector, { label: _('Low'), attr: 'low' }),
    _react2.default.createElement(_components.DataSelector, { label: _('Close'), attr: 'close' }),
    _react2.default.createElement(_components.DataSelector, { label: _('A'), attr: 'a' }),
    _react2.default.createElement(_components.DataSelector, { label: _('B'), attr: 'b' }),
    _react2.default.createElement(_components.DataSelector, { label: _('C'), attr: 'c' }),
    _react2.default.createElement(_components.DataSelector, { label: _('U'), attr: 'u' }),
    _react2.default.createElement(_components.DataSelector, { label: _('V'), attr: 'v' }),
    _react2.default.createElement(_components.DataSelector, { label: _('W'), attr: 'w' }),
    _react2.default.createElement(_components.DataSelector, { label: _('X start'), attr: 'starts.x' }),
    _react2.default.createElement(_components.DataSelector, { label: _('Y start'), attr: 'starts.y' }),
    _react2.default.createElement(_components.DataSelector, { label: _('Z start'), attr: 'starts.z' }),
    _react2.default.createElement(_components.DataSelector, { label: _('Headers'), attr: 'header.values' }),
    _react2.default.createElement(_components.DataSelector, { label: _('Columns'), attr: 'cells.values' }),
    _react2.default.createElement(
      _components.TraceTypeSection,
      { traceTypes: ['scatterpolar', 'scatterpolargl', 'barpolar'], mode: 'trace' },
      _react2.default.createElement(_components.DataSelector, { label: _('Radius'), attr: 'r' }),
      _react2.default.createElement(_components.DataSelector, { label: _('Theta'), attr: 'theta' }),
      _react2.default.createElement(_components.Dropdown, {
        label: _('Theta Unit'),
        options: [{ label: _('Radians'), value: 'radians' }, { label: _('Degrees'), value: 'degrees' }, { label: _('Gradians'), value: 'gradians' }],
        attr: 'thetaunit',
        clearable: false
      })
    ),
    _react2.default.createElement(_components.AxesCreator, { attr: 'fake_attr' }),
    _react2.default.createElement(_components.SubplotCreator, { attr: 'fake_attr' }),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Header Options') },
      _react2.default.createElement(_components.DataSelector, { label: _('Fill Color'), attr: 'header.fill.color' }),
      _react2.default.createElement(_components.DataSelector, { label: _('Font Color'), attr: 'header.font.color' }),
      _react2.default.createElement(_components.DataSelector, { label: _('Font Size'), attr: 'header.font.size' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Cell Options') },
      _react2.default.createElement(_components.DataSelector, { label: _('Fill Color'), attr: 'cells.fill.color' }),
      _react2.default.createElement(_components.DataSelector, { label: _('Font Color'), attr: 'cells.font.color' }),
      _react2.default.createElement(_components.DataSelector, { label: _('Font Size'), attr: 'cells.font.size' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Column Options') },
      _react2.default.createElement(_components.DataSelector, { label: _('Width'), attr: 'columnwidth' }),
      _react2.default.createElement(_components.DataSelector, { label: _('Order'), attr: 'columnorder' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Options') },
      _react2.default.createElement(_components.DataSelector, { label: _('Intensity'), attr: 'intensity' }),
      _react2.default.createElement(_components.DataSelector, { label: _('Facecolor'), attr: 'facecolor' }),
      _react2.default.createElement(_components.DataSelector, { label: _('Vertexcolor'), attr: 'vertexcolor' }),
      _react2.default.createElement(_components.Radio, {
        label: _('Transpose'),
        attr: 'transpose',
        options: [{ label: _('No'), value: false }, { label: _('Yes'), value: true }]
      })
    )
  );
};

exports.default = GraphCreatePanel;

GraphCreatePanel.contextTypes = {
  localize: _propTypes2.default.func,
  setPanel: _propTypes2.default.func
};
//# sourceMappingURL=GraphCreatePanel.js.map

/***/ }),

/***/ "V6Ve":
/*!********************************************!*\
  !*** ./node_modules/lodash/_nativeKeys.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var overArg = __webpack_require__(/*! ./_overArg */ "kekF");

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = overArg(Object.keys, Object);

module.exports = nativeKeys;


/***/ }),

/***/ "V8dp":
/*!************************************************************!*\
  !*** ./node_modules/draft-js/lib/randomizeBlockMapKeys.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule randomizeBlockMapKeys
 * @format
 * 
 */



var ContentBlockNode = __webpack_require__(/*! ./ContentBlockNode */ "JL7T");
var Immutable = __webpack_require__(/*! immutable */ "JPcv");

var generateRandomKey = __webpack_require__(/*! ./generateRandomKey */ "rJY1");

var OrderedMap = Immutable.OrderedMap;


var randomizeContentBlockNodeKeys = function randomizeContentBlockNodeKeys(blockMap) {
  var newKeysRef = {};

  // we keep track of root blocks in order to update subsequent sibling links
  var lastRootBlock = void 0;

  return OrderedMap(blockMap.withMutations(function (blockMapState) {
    blockMapState.forEach(function (block, index) {
      var oldKey = block.getKey();
      var nextKey = block.getNextSiblingKey();
      var prevKey = block.getPrevSiblingKey();
      var childrenKeys = block.getChildKeys();
      var parentKey = block.getParentKey();

      // new key that we will use to build linking
      var key = generateRandomKey();

      // we will add it here to re-use it later
      newKeysRef[oldKey] = key;

      if (nextKey) {
        var nextBlock = blockMapState.get(nextKey);
        if (nextBlock) {
          blockMapState.setIn([nextKey, 'prevSibling'], key);
        } else {
          // this can happen when generating random keys for fragments
          blockMapState.setIn([oldKey, 'nextSibling'], null);
        }
      }

      if (prevKey) {
        var prevBlock = blockMapState.get(prevKey);
        if (prevBlock) {
          blockMapState.setIn([prevKey, 'nextSibling'], key);
        } else {
          // this can happen when generating random keys for fragments
          blockMapState.setIn([oldKey, 'prevSibling'], null);
        }
      }

      if (parentKey && blockMapState.get(parentKey)) {
        var parentBlock = blockMapState.get(parentKey);
        var parentChildrenList = parentBlock.getChildKeys();
        blockMapState.setIn([parentKey, 'children'], parentChildrenList.set(parentChildrenList.indexOf(block.getKey()), key));
      } else {
        // blocks will then be treated as root block nodes
        blockMapState.setIn([oldKey, 'parent'], null);

        if (lastRootBlock) {
          blockMapState.setIn([lastRootBlock.getKey(), 'nextSibling'], key);
          blockMapState.setIn([oldKey, 'prevSibling'], newKeysRef[lastRootBlock.getKey()]);
        }

        lastRootBlock = blockMapState.get(oldKey);
      }

      childrenKeys.forEach(function (childKey) {
        var childBlock = blockMapState.get(childKey);
        if (childBlock) {
          blockMapState.setIn([childKey, 'parent'], key);
        } else {
          blockMapState.setIn([oldKey, 'children'], block.getChildKeys().filter(function (child) {
            return child !== childKey;
          }));
        }
      });
    });
  }).toArray().map(function (block) {
    return [newKeysRef[block.getKey()], block.set('key', newKeysRef[block.getKey()])];
  }));
};

var randomizeContentBlockKeys = function randomizeContentBlockKeys(blockMap) {
  return OrderedMap(blockMap.toArray().map(function (block) {
    var key = generateRandomKey();
    return [key, block.set('key', key)];
  }));
};

var randomizeBlockMapKeys = function randomizeBlockMapKeys(blockMap) {
  var isTreeBasedBlockMap = blockMap.first() instanceof ContentBlockNode;

  if (!isTreeBasedBlockMap) {
    return randomizeContentBlockKeys(blockMap);
  }

  return randomizeContentBlockNodeKeys(blockMap);
};

module.exports = randomizeBlockMapKeys;

/***/ }),

/***/ "V9si":
/*!*******************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/menubar.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
var domutils_1 = __webpack_require__(/*! @phosphor/domutils */ "XWTc");
var keyboard_1 = __webpack_require__(/*! @phosphor/keyboard */ "djTv");
var messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
var virtualdom_1 = __webpack_require__(/*! @phosphor/virtualdom */ "Gqu+");
var widget_1 = __webpack_require__(/*! ./widget */ "FmDU");
/**
 * A widget which displays menus as a canonical menu bar.
 */
var MenuBar = (function (_super) {
    __extends(MenuBar, _super);
    /**
     * Construct a new menu bar.
     *
     * @param options - The options for initializing the menu bar.
     */
    function MenuBar(options) {
        if (options === void 0) { options = {}; }
        var _this = _super.call(this, { node: Private.createNode() }) || this;
        _this._activeIndex = -1;
        _this._menus = [];
        _this._childMenu = null;
        _this.addClass('p-MenuBar');
        _this.setFlag(widget_1.Widget.Flag.DisallowLayout);
        _this.renderer = options.renderer || MenuBar.defaultRenderer;
        return _this;
    }
    /**
     * Dispose of the resources held by the widget.
     */
    MenuBar.prototype.dispose = function () {
        this._closeChildMenu();
        this._menus.length = 0;
        _super.prototype.dispose.call(this);
    };
    Object.defineProperty(MenuBar.prototype, "childMenu", {
        /**
         * The child menu of the menu bar.
         *
         * #### Notes
         * This will be `null` if the menu bar does not have an open menu.
         */
        get: function () {
            return this._childMenu;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(MenuBar.prototype, "contentNode", {
        /**
         * Get the menu bar content node.
         *
         * #### Notes
         * This is the node which holds the menu title nodes.
         *
         * Modifying this node directly can lead to undefined behavior.
         */
        get: function () {
            return this.node.getElementsByClassName('p-MenuBar-content')[0];
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(MenuBar.prototype, "activeMenu", {
        /**
         * Get the currently active menu.
         */
        get: function () {
            return this._menus[this._activeIndex] || null;
        },
        /**
         * Set the currently active menu.
         *
         * #### Notes
         * If the menu does not exist, the menu will be set to `null`.
         */
        set: function (value) {
            this.activeIndex = value ? this._menus.indexOf(value) : -1;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(MenuBar.prototype, "activeIndex", {
        /**
         * Get the index of the currently active menu.
         *
         * #### Notes
         * This will be `-1` if no menu is active.
         */
        get: function () {
            return this._activeIndex;
        },
        /**
         * Set the index of the currently active menu.
         *
         * #### Notes
         * If the menu cannot be activated, the index will be set to `-1`.
         */
        set: function (value) {
            // Adjust the value for an out of range index.
            if (value < 0 || value >= this._menus.length) {
                value = -1;
            }
            // Bail early if the index will not change.
            if (this._activeIndex === value) {
                return;
            }
            // Update the active index.
            this._activeIndex = value;
            // Schedule an update of the items.
            this.update();
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(MenuBar.prototype, "menus", {
        /**
         * A read-only array of the menus in the menu bar.
         */
        get: function () {
            return this._menus;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Open the active menu and activate its first menu item.
     *
     * #### Notes
     * If there is no active menu, this is a no-op.
     */
    MenuBar.prototype.openActiveMenu = function () {
        // Bail early if there is no active item.
        if (this._activeIndex === -1) {
            return;
        }
        // Open the child menu.
        this._openChildMenu();
        // Activate the first item in the child menu.
        if (this._childMenu) {
            this._childMenu.activeIndex = -1;
            this._childMenu.activateNextItem();
        }
    };
    /**
     * Add a menu to the end of the menu bar.
     *
     * @param menu - The menu to add to the menu bar.
     *
     * #### Notes
     * If the menu is already added to the menu bar, it will be moved.
     */
    MenuBar.prototype.addMenu = function (menu) {
        this.insertMenu(this._menus.length, menu);
    };
    /**
     * Insert a menu into the menu bar at the specified index.
     *
     * @param index - The index at which to insert the menu.
     *
     * @param menu - The menu to insert into the menu bar.
     *
     * #### Notes
     * The index will be clamped to the bounds of the menus.
     *
     * If the menu is already added to the menu bar, it will be moved.
     */
    MenuBar.prototype.insertMenu = function (index, menu) {
        // Close the child menu before making changes.
        this._closeChildMenu();
        // Look up the index of the menu.
        var i = this._menus.indexOf(menu);
        // Clamp the insert index to the array bounds.
        var j = Math.max(0, Math.min(index, this._menus.length));
        // If the menu is not in the array, insert it.
        if (i === -1) {
            // Insert the menu into the array.
            algorithm_1.ArrayExt.insert(this._menus, j, menu);
            // Add the styling class to the menu.
            menu.addClass('p-MenuBar-menu');
            // Connect to the menu signals.
            menu.aboutToClose.connect(this._onMenuAboutToClose, this);
            menu.menuRequested.connect(this._onMenuMenuRequested, this);
            menu.title.changed.connect(this._onTitleChanged, this);
            // Schedule an update of the items.
            this.update();
            // There is nothing more to do.
            return;
        }
        // Otherwise, the menu exists in the array and should be moved.
        // Adjust the index if the location is at the end of the array.
        if (j === this._menus.length) {
            j--;
        }
        // Bail if there is no effective move.
        if (i === j) {
            return;
        }
        // Move the menu to the new locations.
        algorithm_1.ArrayExt.move(this._menus, i, j);
        // Schedule an update of the items.
        this.update();
    };
    /**
     * Remove a menu from the menu bar.
     *
     * @param menu - The menu to remove from the menu bar.
     *
     * #### Notes
     * This is a no-op if the menu is not in the menu bar.
     */
    MenuBar.prototype.removeMenu = function (menu) {
        this.removeMenuAt(this._menus.indexOf(menu));
    };
    /**
     * Remove the menu at a given index from the menu bar.
     *
     * @param index - The index of the menu to remove.
     *
     * #### Notes
     * This is a no-op if the index is out of range.
     */
    MenuBar.prototype.removeMenuAt = function (index) {
        // Close the child menu before making changes.
        this._closeChildMenu();
        // Remove the menu from the array.
        var menu = algorithm_1.ArrayExt.removeAt(this._menus, index);
        // Bail if the index is out of range.
        if (!menu) {
            return;
        }
        // Disconnect from the menu signals.
        menu.aboutToClose.disconnect(this._onMenuAboutToClose, this);
        menu.menuRequested.disconnect(this._onMenuMenuRequested, this);
        menu.title.changed.disconnect(this._onTitleChanged, this);
        // Remove the styling class from the menu.
        menu.removeClass('p-MenuBar-menu');
        // Schedule an update of the items.
        this.update();
    };
    /**
     * Remove all menus from the menu bar.
     */
    MenuBar.prototype.clearMenus = function () {
        // Bail if there is nothing to remove.
        if (this._menus.length === 0) {
            return;
        }
        // Close the child menu before making changes.
        this._closeChildMenu();
        // Disconnect from the menu signals and remove the styling class.
        for (var _i = 0, _a = this._menus; _i < _a.length; _i++) {
            var menu = _a[_i];
            menu.aboutToClose.disconnect(this._onMenuAboutToClose, this);
            menu.menuRequested.disconnect(this._onMenuMenuRequested, this);
            menu.title.changed.disconnect(this._onTitleChanged, this);
            menu.removeClass('p-MenuBar-menu');
        }
        // Clear the menus array.
        this._menus.length = 0;
        // Schedule an update of the items.
        this.update();
    };
    /**
     * Handle the DOM events for the menu bar.
     *
     * @param event - The DOM event sent to the menu bar.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the menu bar's DOM nodes. It
     * should not be called directly by user code.
     */
    MenuBar.prototype.handleEvent = function (event) {
        switch (event.type) {
            case 'keydown':
                this._evtKeyDown(event);
                break;
            case 'mousedown':
                this._evtMouseDown(event);
                break;
            case 'mousemove':
                this._evtMouseMove(event);
                break;
            case 'mouseleave':
                this._evtMouseLeave(event);
                break;
            case 'contextmenu':
                event.preventDefault();
                event.stopPropagation();
                break;
        }
    };
    /**
     * A message handler invoked on a `'before-attach'` message.
     */
    MenuBar.prototype.onBeforeAttach = function (msg) {
        this.node.addEventListener('keydown', this);
        this.node.addEventListener('mousedown', this);
        this.node.addEventListener('mousemove', this);
        this.node.addEventListener('mouseleave', this);
        this.node.addEventListener('contextmenu', this);
    };
    /**
     * A message handler invoked on an `'after-detach'` message.
     */
    MenuBar.prototype.onAfterDetach = function (msg) {
        this.node.removeEventListener('keydown', this);
        this.node.removeEventListener('mousedown', this);
        this.node.removeEventListener('mousemove', this);
        this.node.removeEventListener('mouseleave', this);
        this.node.removeEventListener('contextmenu', this);
        this._closeChildMenu();
    };
    /**
     * A message handler invoked on an `'activate-request'` message.
     */
    MenuBar.prototype.onActivateRequest = function (msg) {
        if (this.isAttached) {
            this.node.focus();
        }
    };
    /**
     * A message handler invoked on an `'update-request'` message.
     */
    MenuBar.prototype.onUpdateRequest = function (msg) {
        var menus = this._menus;
        var renderer = this.renderer;
        var activeIndex = this._activeIndex;
        var content = new Array(menus.length);
        for (var i = 0, n = menus.length; i < n; ++i) {
            var title = menus[i].title;
            var active = i === activeIndex;
            content[i] = renderer.renderItem({ title: title, active: active });
        }
        virtualdom_1.VirtualDOM.render(content, this.contentNode);
    };
    /**
     * Handle the `'keydown'` event for the menu bar.
     */
    MenuBar.prototype._evtKeyDown = function (event) {
        // A menu bar handles all keydown events.
        event.preventDefault();
        event.stopPropagation();
        // Fetch the key code for the event.
        var kc = event.keyCode;
        // Enter, Up Arrow, Down Arrow
        if (kc === 13 || kc === 38 || kc === 40) {
            this.openActiveMenu();
            return;
        }
        // Escape
        if (kc === 27) {
            this._closeChildMenu();
            this.activeIndex = -1;
            this.node.blur();
            return;
        }
        // Left Arrow
        if (kc === 37) {
            var i = this._activeIndex;
            var n = this._menus.length;
            this.activeIndex = i === 0 ? n - 1 : i - 1;
            return;
        }
        // Right Arrow
        if (kc === 39) {
            var i = this._activeIndex;
            var n = this._menus.length;
            this.activeIndex = i === n - 1 ? 0 : i + 1;
            return;
        }
        // Get the pressed key character.
        var key = keyboard_1.getKeyboardLayout().keyForKeydownEvent(event);
        // Bail if the key is not valid.
        if (!key) {
            return;
        }
        // Search for the next best matching mnemonic item.
        var start = this._activeIndex + 1;
        var result = Private.findMnemonic(this._menus, key, start);
        // Handle the requested mnemonic based on the search results.
        // If exactly one mnemonic is matched, that menu is opened.
        // Otherwise, the next mnemonic is activated if available,
        // followed by the auto mnemonic if available.
        if (result.index !== -1 && !result.multiple) {
            this.activeIndex = result.index;
            this.openActiveMenu();
        }
        else if (result.index !== -1) {
            this.activeIndex = result.index;
        }
        else if (result.auto !== -1) {
            this.activeIndex = result.auto;
        }
    };
    /**
     * Handle the `'mousedown'` event for the menu bar.
     */
    MenuBar.prototype._evtMouseDown = function (event) {
        // Bail if the mouse press was not on the menu bar. This can occur
        // when the document listener is installed for an active menu bar.
        if (!domutils_1.ElementExt.hitTest(this.node, event.clientX, event.clientY)) {
            return;
        }
        // Stop the propagation of the event. Immediate propagation is
        // also stopped so that an open menu does not handle the event.
        event.preventDefault();
        event.stopPropagation();
        event.stopImmediatePropagation();
        // Check if the mouse is over one of the menu items.
        var index = algorithm_1.ArrayExt.findFirstIndex(this.contentNode.children, function (node) {
            return domutils_1.ElementExt.hitTest(node, event.clientX, event.clientY);
        });
        // If the press was not on an item, close the child menu.
        if (index === -1) {
            this._closeChildMenu();
            return;
        }
        // If the press was not the left mouse button, do nothing further.
        if (event.button !== 0) {
            return;
        }
        // Otherwise, toggle the open state of the child menu.
        if (this._childMenu) {
            this._closeChildMenu();
            this.activeIndex = index;
        }
        else {
            this.activeIndex = index;
            this._openChildMenu();
        }
    };
    /**
     * Handle the `'mousemove'` event for the menu bar.
     */
    MenuBar.prototype._evtMouseMove = function (event) {
        // Check if the mouse is over one of the menu items.
        var index = algorithm_1.ArrayExt.findFirstIndex(this.contentNode.children, function (node) {
            return domutils_1.ElementExt.hitTest(node, event.clientX, event.clientY);
        });
        // Bail early if the active index will not change.
        if (index === this._activeIndex) {
            return;
        }
        // Bail early if a child menu is open and the mouse is not over
        // an item. This allows the child menu to be kept open when the
        // mouse is over the empty part of the menu bar.
        if (index === -1 && this._childMenu) {
            return;
        }
        // Update the active index to the hovered item.
        this.activeIndex = index;
        // Open the new menu if a menu is already open.
        if (this._childMenu) {
            this._openChildMenu();
        }
    };
    /**
     * Handle the `'mouseleave'` event for the menu bar.
     */
    MenuBar.prototype._evtMouseLeave = function (event) {
        // Reset the active index if there is no open menu.
        if (!this._childMenu) {
            this.activeIndex = -1;
        }
    };
    /**
     * Open the child menu at the active index immediately.
     *
     * If a different child menu is already open, it will be closed,
     * even if there is no active menu.
     */
    MenuBar.prototype._openChildMenu = function () {
        // If there is no active menu, close the current menu.
        var newMenu = this.activeMenu;
        if (!newMenu) {
            this._closeChildMenu();
            return;
        }
        // Bail if there is no effective menu change.
        var oldMenu = this._childMenu;
        if (oldMenu === newMenu) {
            return;
        }
        // Swap the internal menu reference.
        this._childMenu = newMenu;
        // Close the current menu, or setup for the new menu.
        if (oldMenu) {
            oldMenu.close();
        }
        else {
            this.addClass('p-mod-active');
            document.addEventListener('mousedown', this, true);
        }
        // Ensure the menu bar is updated and look up the item node.
        messaging_1.MessageLoop.sendMessage(this, widget_1.Widget.Msg.UpdateRequest);
        var itemNode = this.contentNode.children[this._activeIndex];
        // Get the positioning data for the new menu.
        var _a = itemNode.getBoundingClientRect(), left = _a.left, bottom = _a.bottom;
        // Open the new menu at the computed location.
        newMenu.open(left, bottom, { forceX: true, forceY: true });
    };
    /**
     * Close the child menu immediately.
     *
     * This is a no-op if a child menu is not open.
     */
    MenuBar.prototype._closeChildMenu = function () {
        // Bail if no child menu is open.
        if (!this._childMenu) {
            return;
        }
        // Remove the active class from the menu bar.
        this.removeClass('p-mod-active');
        // Remove the document listeners.
        document.removeEventListener('mousedown', this, true);
        // Clear the internal menu reference.
        var menu = this._childMenu;
        this._childMenu = null;
        // Close the menu.
        menu.close();
        // Reset the active index.
        this.activeIndex = -1;
    };
    /**
     * Handle the `aboutToClose` signal of a menu.
     */
    MenuBar.prototype._onMenuAboutToClose = function (sender) {
        // Bail if the sender is not the child menu.
        if (sender !== this._childMenu) {
            return;
        }
        // Remove the active class from the menu bar.
        this.removeClass('p-mod-active');
        // Remove the document listeners.
        document.removeEventListener('mousedown', this, true);
        // Clear the internal menu reference.
        this._childMenu = null;
        // Reset the active index.
        this.activeIndex = -1;
    };
    /**
     * Handle the `menuRequested` signal of a child menu.
     */
    MenuBar.prototype._onMenuMenuRequested = function (sender, args) {
        // Bail if the sender is not the child menu.
        if (sender !== this._childMenu) {
            return;
        }
        // Look up the active index and menu count.
        var i = this._activeIndex;
        var n = this._menus.length;
        // Active the next requested index.
        switch (args) {
            case 'next':
                this.activeIndex = i === n - 1 ? 0 : i + 1;
                break;
            case 'previous':
                this.activeIndex = i === 0 ? n - 1 : i - 1;
                break;
        }
        // Open the active menu.
        this.openActiveMenu();
    };
    /**
     * Handle the `changed` signal of a title object.
     */
    MenuBar.prototype._onTitleChanged = function () {
        this.update();
    };
    return MenuBar;
}(widget_1.Widget));
exports.MenuBar = MenuBar;
/**
 * The namespace for the `MenuBar` class statics.
 */
(function (MenuBar) {
    /**
     * The default implementation of `IRenderer`.
     *
     * #### Notes
     * Subclasses are free to reimplement rendering methods as needed.
     */
    var Renderer = (function () {
        /**
         * Construct a new renderer.
         */
        function Renderer() {
        }
        /**
         * Render the virtual element for a menu bar item.
         *
         * @param data - The data to use for rendering the item.
         *
         * @returns A virtual element representing the item.
         */
        Renderer.prototype.renderItem = function (data) {
            var className = this.createItemClass(data);
            var dataset = this.createItemDataset(data);
            return (virtualdom_1.h.li({ className: className, dataset: dataset }, this.renderIcon(data), this.renderLabel(data)));
        };
        /**
         * Render the icon element for a menu bar item.
         *
         * @param data - The data to use for rendering the icon.
         *
         * @returns A virtual element representing the item icon.
         */
        Renderer.prototype.renderIcon = function (data) {
            var className = this.createIconClass(data);
            return virtualdom_1.h.div({ className: className }, data.title.iconLabel);
        };
        /**
         * Render the label element for a menu item.
         *
         * @param data - The data to use for rendering the label.
         *
         * @returns A virtual element representing the item label.
         */
        Renderer.prototype.renderLabel = function (data) {
            var content = this.formatLabel(data);
            return virtualdom_1.h.div({ className: 'p-MenuBar-itemLabel' }, content);
        };
        /**
         * Create the class name for the menu bar item.
         *
         * @param data - The data to use for the class name.
         *
         * @returns The full class name for the menu item.
         */
        Renderer.prototype.createItemClass = function (data) {
            var name = 'p-MenuBar-item';
            if (data.title.className) {
                name += " " + data.title.className;
            }
            if (data.active) {
                name += ' p-mod-active';
            }
            return name;
        };
        /**
         * Create the dataset for a menu bar item.
         *
         * @param data - The data to use for the item.
         *
         * @returns The dataset for the menu bar item.
         */
        Renderer.prototype.createItemDataset = function (data) {
            return data.title.dataset;
        };
        /**
         * Create the class name for the menu bar item icon.
         *
         * @param data - The data to use for the class name.
         *
         * @returns The full class name for the item icon.
         */
        Renderer.prototype.createIconClass = function (data) {
            var name = 'p-MenuBar-itemIcon';
            var extra = data.title.iconClass;
            return extra ? name + " " + extra : name;
        };
        /**
         * Create the render content for the label node.
         *
         * @param data - The data to use for the label content.
         *
         * @returns The content to add to the label node.
         */
        Renderer.prototype.formatLabel = function (data) {
            // Fetch the label text and mnemonic index.
            var _a = data.title, label = _a.label, mnemonic = _a.mnemonic;
            // If the index is out of range, do not modify the label.
            if (mnemonic < 0 || mnemonic >= label.length) {
                return label;
            }
            // Split the label into parts.
            var prefix = label.slice(0, mnemonic);
            var suffix = label.slice(mnemonic + 1);
            var char = label[mnemonic];
            // Wrap the mnemonic character in a span.
            var span = virtualdom_1.h.span({ className: 'p-MenuBar-itemMnemonic' }, char);
            // Return the content parts.
            return [prefix, span, suffix];
        };
        return Renderer;
    }());
    MenuBar.Renderer = Renderer;
    /**
     * The default `Renderer` instance.
     */
    MenuBar.defaultRenderer = new Renderer();
})(MenuBar = exports.MenuBar || (exports.MenuBar = {}));
exports.MenuBar = MenuBar;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * Create the DOM node for a menu bar.
     */
    function createNode() {
        var node = document.createElement('div');
        var content = document.createElement('ul');
        content.className = 'p-MenuBar-content';
        node.appendChild(content);
        node.tabIndex = -1;
        return node;
    }
    Private.createNode = createNode;
    /**
     * Find the best matching mnemonic item.
     *
     * The search starts at the given index and wraps around.
     */
    function findMnemonic(menus, key, start) {
        // Setup the result variables.
        var index = -1;
        var auto = -1;
        var multiple = false;
        // Normalize the key to upper case.
        var upperKey = key.toUpperCase();
        // Search the items from the given start index.
        for (var i = 0, n = menus.length; i < n; ++i) {
            // Compute the wrapped index.
            var k = (i + start) % n;
            // Look up the menu title.
            var title = menus[k].title;
            // Ignore titles with an empty label.
            if (title.label.length === 0) {
                continue;
            }
            // Look up the mnemonic index for the label.
            var mn = title.mnemonic;
            // Handle a valid mnemonic index.
            if (mn >= 0 && mn < title.label.length) {
                if (title.label[mn].toUpperCase() === upperKey) {
                    if (index === -1) {
                        index = k;
                    }
                    else {
                        multiple = true;
                    }
                }
                continue;
            }
            // Finally, handle the auto index if possible.
            if (auto === -1 && title.label[0].toUpperCase() === upperKey) {
                auto = k;
            }
        }
        // Return the search results.
        return { index: index, multiple: multiple, auto: auto };
    }
    Private.findMnemonic = findMnemonic;
})(Private || (Private = {}));


/***/ }),

/***/ "VAzd":
/*!************************************************!*\
  !*** ./node_modules/xterm/lib/SoundManager.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.DEFAULT_BELL_SOUND = 'data:audio/wav;base64,UklGRigBAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQQBAADpAFgCwAMlBZoG/wdmCcoKRAypDQ8PbRDBEQQTOxRtFYcWlBePGIUZXhoiG88bcBz7HHIdzh0WHlMeZx51HmkeUx4WHs8dah0AHXwc3hs9G4saxRnyGBIYGBcQFv8U4RPAEoYRQBACD70NWwwHC6gJOwjWBloF7gOBAhABkf8b/qv8R/ve+Xf4Ife79W/0JfPZ8Z/wde9N7ijtE+wU6xvqM+lb6H7nw+YX5mrlxuQz5Mzje+Ma49fioeKD4nXiYeJy4pHitOL04j/jn+MN5IPkFOWs5U3mDefM55/ogOl36m7rdOyE7abuyu8D8Unyj/Pg9D/2qfcb+Yn6/vuK/Qj/lAAlAg==';
var SoundManager = (function () {
    function SoundManager(_terminal) {
        this._terminal = _terminal;
    }
    SoundManager.prototype.playBellSound = function () {
        var audioContextCtor = window.AudioContext || window.webkitAudioContext;
        if (!this._audioContext && audioContextCtor) {
            this._audioContext = new audioContextCtor();
        }
        if (this._audioContext) {
            var bellAudioSource_1 = this._audioContext.createBufferSource();
            var context_1 = this._audioContext;
            this._audioContext.decodeAudioData(this._base64ToArrayBuffer(this._removeMimeType(this._terminal.options.bellSound)), function (buffer) {
                bellAudioSource_1.buffer = buffer;
                bellAudioSource_1.connect(context_1.destination);
                bellAudioSource_1.start(0);
            });
        }
        else {
            console.warn('Sorry, but the Web Audio API is not supported by your browser. Please, consider upgrading to the latest version');
        }
    };
    SoundManager.prototype._base64ToArrayBuffer = function (base64) {
        var binaryString = window.atob(base64);
        var len = binaryString.length;
        var bytes = new Uint8Array(len);
        for (var i = 0; i < len; i++) {
            bytes[i] = binaryString.charCodeAt(i);
        }
        return bytes.buffer;
    };
    SoundManager.prototype._removeMimeType = function (dataURI) {
        var splitUri = dataURI.split(',');
        return splitUri[1];
    };
    return SoundManager;
}());
exports.SoundManager = SoundManager;

//# sourceMappingURL=SoundManager.js.map


/***/ }),

/***/ "VBVY":
/*!*******************************************************!*\
  !*** ./node_modules/react-day-picker/lib/src/keys.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var LEFT = exports.LEFT = 37;
var UP = exports.UP = 38;
var RIGHT = exports.RIGHT = 39;
var DOWN = exports.DOWN = 40;
var ENTER = exports.ENTER = 13;
var SPACE = exports.SPACE = 32;
var ESC = exports.ESC = 27;
var TAB = exports.TAB = 9;
//# sourceMappingURL=keys.js.map

/***/ }),

/***/ "VI8P":
/*!**************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@phosphor/widgets/style/scrollbar.css ***!
  \**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\r\n| Copyright (c) 2014-2017, PhosphorJS Contributors\r\n|\r\n| Distributed under the terms of the BSD 3-Clause License.\r\n|\r\n| The full license is in the file LICENSE, distributed with this software.\r\n|----------------------------------------------------------------------------*/\r\n\r\n\r\n.p-ScrollBar {\r\n  display: flex;\r\n  -webkit-user-select: none;\r\n  -moz-user-select: none;\r\n  -ms-user-select: none;\r\n  user-select: none;\r\n}\r\n\r\n\r\n.p-ScrollBar[data-orientation='horizontal'] {\r\n  flex-direction: row;\r\n}\r\n\r\n\r\n.p-ScrollBar[data-orientation='vertical'] {\r\n  flex-direction: column;\r\n}\r\n\r\n\r\n.p-ScrollBar-button {\r\n  box-sizing: border-box;\r\n  flex: 0 0 auto;\r\n}\r\n\r\n\r\n.p-ScrollBar-track {\r\n  box-sizing: border-box;\r\n  position: relative;\r\n  overflow: hidden;\r\n  flex: 1 1 auto;\r\n}\r\n\r\n\r\n.p-ScrollBar-thumb {\r\n  box-sizing: border-box;\r\n  position: absolute;\r\n}\r\n", ""]);

// exports


/***/ }),

/***/ "VJCR":
/*!**********************************************************!*\
  !*** ./node_modules/react-day-picker/lib/src/Helpers.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

exports.cancelEvent = cancelEvent;
exports.getFirstDayOfMonth = getFirstDayOfMonth;
exports.getDaysInMonth = getDaysInMonth;
exports.getModifiersFromProps = getModifiersFromProps;
exports.getFirstDayOfWeekFromProps = getFirstDayOfWeekFromProps;
exports.isRangeOfDates = isRangeOfDates;
exports.getMonthsDiff = getMonthsDiff;
exports.getWeekArray = getWeekArray;
exports.startOfMonth = startOfMonth;
exports.getDayNodes = getDayNodes;
exports.nodeListToArray = nodeListToArray;
exports.hasOwnProp = hasOwnProp;

var _DateUtils = __webpack_require__(/*! ./DateUtils */ "mHnu");

var _LocaleUtils = __webpack_require__(/*! ./LocaleUtils */ "ze2x");

var _classNames = __webpack_require__(/*! ./classNames */ "ZE44");

var _classNames2 = _interopRequireDefault(_classNames);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function cancelEvent(e) {
  e.preventDefault();
  e.stopPropagation();
}

function getFirstDayOfMonth(d) {
  return new Date(d.getFullYear(), d.getMonth(), 1, 12);
}

function getDaysInMonth(d) {
  var resultDate = getFirstDayOfMonth(d);

  resultDate.setMonth(resultDate.getMonth() + 1);
  resultDate.setDate(resultDate.getDate() - 1);

  return resultDate.getDate();
}

function getModifiersFromProps(props) {
  var modifiers = _extends({}, props.modifiers);
  if (props.selectedDays) {
    modifiers[props.classNames.selected] = props.selectedDays;
  }
  if (props.disabledDays) {
    modifiers[props.classNames.disabled] = props.disabledDays;
  }
  return modifiers;
}

function getFirstDayOfWeekFromProps(props) {
  var firstDayOfWeek = props.firstDayOfWeek,
      _props$locale = props.locale,
      locale = _props$locale === undefined ? 'en' : _props$locale,
      _props$localeUtils = props.localeUtils,
      localeUtils = _props$localeUtils === undefined ? {} : _props$localeUtils;

  if (!isNaN(firstDayOfWeek)) {
    return firstDayOfWeek;
  }
  if (localeUtils.getFirstDayOfWeek) {
    return localeUtils.getFirstDayOfWeek(locale);
  }
  return 0;
}

function isRangeOfDates(value) {
  return !!(value && value.from && value.to);
}

function getMonthsDiff(d1, d2) {
  return d2.getMonth() - d1.getMonth() + 12 * (d2.getFullYear() - d1.getFullYear());
}

function getWeekArray(d) {
  var firstDayOfWeek = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (0, _LocaleUtils.getFirstDayOfWeek)();
  var fixedWeeks = arguments[2];

  var daysInMonth = getDaysInMonth(d);
  var dayArray = [];

  var week = [];
  var weekArray = [];

  for (var i = 1; i <= daysInMonth; i += 1) {
    dayArray.push(new Date(d.getFullYear(), d.getMonth(), i, 12));
  }

  dayArray.forEach(function (day) {
    if (week.length > 0 && day.getDay() === firstDayOfWeek) {
      weekArray.push(week);
      week = [];
    }
    week.push(day);
    if (dayArray.indexOf(day) === dayArray.length - 1) {
      weekArray.push(week);
    }
  });

  // unshift days to start the first week
  var firstWeek = weekArray[0];
  for (var _i = 7 - firstWeek.length; _i > 0; _i -= 1) {
    var outsideDate = (0, _DateUtils.clone)(firstWeek[0]);
    outsideDate.setDate(firstWeek[0].getDate() - 1);
    firstWeek.unshift(outsideDate);
  }

  // push days until the end of the last week
  var lastWeek = weekArray[weekArray.length - 1];
  for (var _i2 = lastWeek.length; _i2 < 7; _i2 += 1) {
    var _outsideDate = (0, _DateUtils.clone)(lastWeek[lastWeek.length - 1]);
    _outsideDate.setDate(lastWeek[lastWeek.length - 1].getDate() + 1);
    lastWeek.push(_outsideDate);
  }

  // add extra weeks to reach 6 weeks
  if (fixedWeeks && weekArray.length < 6) {
    var lastExtraWeek = void 0;

    for (var _i3 = weekArray.length; _i3 < 6; _i3 += 1) {
      lastExtraWeek = weekArray[weekArray.length - 1];
      var lastDay = lastExtraWeek[lastExtraWeek.length - 1];
      var extraWeek = [];

      for (var j = 0; j < 7; j += 1) {
        var _outsideDate2 = (0, _DateUtils.clone)(lastDay);
        _outsideDate2.setDate(lastDay.getDate() + j + 1);
        extraWeek.push(_outsideDate2);
      }

      weekArray.push(extraWeek);
    }
  }

  return weekArray;
}

function startOfMonth(d) {
  var newDate = (0, _DateUtils.clone)(d);
  newDate.setDate(1);
  newDate.setHours(12, 0, 0, 0); // always set noon to avoid time zone issues
  return newDate;
}

function getDayNodes(node, classNames) {
  var outsideClassName = void 0;
  if (classNames === _classNames2.default) {
    // When using CSS modules prefix the modifier as required by the BEM syntax
    outsideClassName = classNames.day + '--' + classNames.outside;
  } else {
    outsideClassName = '' + classNames.outside;
  }
  var dayQuery = classNames.day.replace(/ /g, '.');
  var outsideDayQuery = outsideClassName.replace(/ /g, '.');
  var selector = '.' + dayQuery + ':not(.' + outsideDayQuery + ')';
  return node.querySelectorAll(selector);
}

function nodeListToArray(nodeList) {
  return Array.prototype.slice.call(nodeList, 0);
}

function hasOwnProp(obj, prop) {
  return Object.prototype.hasOwnProperty.call(obj, prop);
}
//# sourceMappingURL=Helpers.js.map

/***/ }),

/***/ "VKFn":
/*!********************************************************!*\
  !*** ./node_modules/core-js/library/fn/is-iterable.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(/*! ../modules/web.dom.iterable */ "bBy9");
__webpack_require__(/*! ../modules/es6.string.iterator */ "FlQf");
module.exports = __webpack_require__(/*! ../modules/core.is-iterable */ "ldVq");


/***/ }),

/***/ "VKie":
/*!***************************************************************!*\
  !*** ./node_modules/@jupyter-widgets/controls/lib/version.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * The version of the Jupyter controls widget attribute spec that this package
 * implements.
 */
exports.JUPYTER_CONTROLS_VERSION = '1.4.0';


/***/ }),

/***/ "VLFu":
/*!**********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/default_panels/GraphSubplotsPanel.js ***!
  \**********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _components = __webpack_require__(/*! ../components */ "yF51");

var _constants = __webpack_require__(/*! ../lib/constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var GraphSubplotsPanel = function GraphSubplotsPanel(props, _ref) {
  var _ = _ref.localize;
  return _react2.default.createElement(
    _components.SubplotAccordion,
    null,
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Boundaries'), attr: 'xaxis.domain[0]' },
      _react2.default.createElement(_components.AxisOverlayDropdown, { label: _('X Overlay'), attr: 'xaxis.overlaying' }),
      _react2.default.createElement(_components.AxisOverlayDropdown, { label: _('Y Overlay'), attr: 'yaxis.overlaying' })
    ),
    _react2.default.createElement(_components.RectanglePositioner, { attr: 'domain.x[0]' }),
    _react2.default.createElement(_components.RectanglePositioner, { attr: 'xaxis.domain[0]', cartesian: true }),
    _react2.default.createElement(
      _components.TraceTypeSection,
      { name: _('X Anchor'), traceTypes: _constants.TRACE_TO_AXIS.cartesian },
      _react2.default.createElement(_components.AxisAnchorDropdown, { label: _('Anchor to'), attr: 'xaxis.anchor', clearable: false }),
      _react2.default.createElement(_components.AxisSide, { label: _('Side'), attr: 'xaxis.side' })
    ),
    _react2.default.createElement(
      _components.TraceTypeSection,
      { name: _('Y Anchor'), traceTypes: _constants.TRACE_TO_AXIS.cartesian },
      _react2.default.createElement(_components.AxisAnchorDropdown, { label: _('Anchor to'), attr: 'yaxis.anchor', clearable: false }),
      _react2.default.createElement(_components.AxisSide, { label: _('Side'), attr: 'yaxis.side' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Aspect Ratio') },
      _react2.default.createElement(
        _components.VisibilitySelect,
        {
          attr: 'aspectmode',
          options: [{ label: _('Auto'), value: 'mode' }, { label: _('Cube'), value: 'cube' }, { label: _('Data'), value: 'data' }, { label: _('Manual'), value: 'manual' }],
          dropdown: true,
          clearable: false,
          showOn: 'manual',
          defaultOpt: 'mode'
        },
        _react2.default.createElement(_components.Numeric, { label: _('X'), attr: 'aspectratio.x', step: 0.1 }),
        _react2.default.createElement(_components.Numeric, { label: _('Y'), attr: 'aspectratio.y', step: 0.1 }),
        _react2.default.createElement(_components.Numeric, { label: _('Z'), attr: 'aspectratio.z', step: 0.1 })
      )
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Canvas') },
      _react2.default.createElement(_components.ColorPicker, { label: _('Plot Background'), attr: 'bgcolor' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Bar Options') },
      _react2.default.createElement(_components.Radio, {
        label: _('Bar Mode'),
        attr: 'barmode',
        options: [{ label: _('Stack'), value: 'stack' }, { label: _('Overlay'), value: 'overlay' }]
      }),
      _react2.default.createElement(_components.NumericFraction, { label: _('Bar Padding'), attr: 'bargap', showSlider: true })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Map Style') },
      _react2.default.createElement(_components.Dropdown, {
        label: _('Mapbox Style'),
        attr: 'style',
        options: [{ label: _('Basic'), value: 'basic' }, { label: _('Outdoors'), value: 'outdoors' }, { label: _('Light'), value: 'light' }, { label: _('Dark'), value: 'dark' }, { label: _('Satellite'), value: 'satellite' }, { label: _('Satellite with Streets'), value: 'satellite-streets' }],
        clearable: false
      })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Map Positioning') },
      _react2.default.createElement(_components.Numeric, { label: _('Center Latitude'), attr: 'center.lat' }),
      _react2.default.createElement(_components.Numeric, { label: _('Center Longitude'), attr: 'center.lon' }),
      _react2.default.createElement(_components.Numeric, { label: _('Zoom Level'), attr: 'zoom', min: 0 }),
      _react2.default.createElement(_components.Numeric, { label: _('Bearing'), attr: 'bearing' }),
      _react2.default.createElement(_components.Numeric, { label: _('Pitch'), attr: 'pitch', min: 0 })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Map Projection') },
      _react2.default.createElement(_components.Dropdown, {
        label: _('Region'),
        attr: 'scope',
        options: [{ label: _('World'), value: 'world' }, { label: _('USA'), value: 'usa' }, { label: _('Europe'), value: 'europe' }, { label: _('Asia'), value: 'asia' }, { label: _('Africa'), value: 'africa' }, { label: _('North America'), value: 'north america' }, { label: _('South America'), value: 'south america' }],
        clearable: false
      }),
      _react2.default.createElement(_components.Dropdown, {
        label: _('Projection'),
        attr: 'projection.type',
        clearable: false,
        options: [{ label: _('Equirectangular'), value: 'equirectangular' }, { label: _('Mercator'), value: 'mercator' }, { label: _('Orthographic'), value: 'orthographic' }, { label: _('Natural Earth'), value: 'natural earth' }, { label: _('Albers USA'), value: 'albers usa' }, { label: _('Winkel Tripel'), value: 'winkel tripel' }, { label: _('Robinson'), value: 'robinson' }, { label: _('Miller'), value: 'miller' }, { label: _('Kavrayskiy 7'), value: 'kavrayskiy7' }, { label: _('Eckert 4'), value: 'eckert4' }, { label: _('Azimuthal Equal Area'), value: 'azimuthal equal area' }, {
          label: _('Azimuthal Equidistant'),
          value: 'azimuthal equidistant'
        }, { label: _('Conic Equal Area'), value: 'conic equal area' }, { label: _('Conic Conformal'), value: 'conic conformal' }, { label: _('Conic Equidistant'), value: 'conic equidistant' }, { label: _('Gnomonic'), value: 'gnomonic' }, { label: _('Stereographic'), value: 'stereographic' }, { label: _('Mollweide'), value: 'mollweide' }, { label: _('Hammer'), value: 'hammer' }, { label: _('Transverse Mercator'), value: 'transverse mercator' }, { label: _('Aitoff'), value: 'aitoff' }, { label: _('Sinusoidal'), value: 'sinusoidal' }]
      })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Country Borders'), attr: 'showcountries' },
      _react2.default.createElement(_components.Radio, {
        attr: 'showcountries',
        options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
      }),
      _react2.default.createElement(_components.Numeric, { label: _('Border Width'), attr: 'countrywidth', units: 'px' }),
      _react2.default.createElement(_components.ColorPicker, { label: _('Border Color'), attr: 'countrycolor' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Sub-Country Unit Borders'), attr: 'showsubunits' },
      _react2.default.createElement(_components.Radio, {
        attr: 'showsubunits',
        options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
      }),
      _react2.default.createElement(_components.Numeric, { label: _('Border Width'), attr: 'subunitwidth', units: 'px' }),
      _react2.default.createElement(_components.ColorPicker, { label: _('Border Color'), attr: 'subunitcolor' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Coastlines'), attr: 'showcoastlines' },
      _react2.default.createElement(_components.Radio, {
        attr: 'showcoastlines',
        options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
      }),
      _react2.default.createElement(_components.Numeric, { label: _('Width'), attr: 'coastlinewidth', units: 'px' }),
      _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'coastlinecolor' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Oceans'), attr: 'showocean' },
      _react2.default.createElement(_components.Radio, {
        attr: 'showocean',
        options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
      }),
      _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'oceancolor' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Land'), attr: 'showland' },
      _react2.default.createElement(_components.Radio, {
        attr: 'showland',
        options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
      }),
      _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'landcolor' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Lakes'), attr: 'showlakes' },
      _react2.default.createElement(_components.Radio, {
        attr: 'showlakes',
        options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
      }),
      _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'lakecolor' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Rivers'), attr: 'showrivers' },
      _react2.default.createElement(_components.Radio, {
        attr: 'showrivers',
        options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
      }),
      _react2.default.createElement(_components.Numeric, { label: _('Width'), attr: 'riverwidth', units: 'px' }),
      _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'rivercolor' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Map Frame'), attr: 'showframe' },
      _react2.default.createElement(_components.Radio, {
        attr: 'showframe',
        options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
      }),
      _react2.default.createElement(_components.Numeric, { label: _('Width'), attr: 'framewidth', units: 'px' }),
      _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'framecolor' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Map Options') },
      _react2.default.createElement(_components.Radio, {
        label: _('Resolution'),
        attr: 'resolution',
        options: [{ label: _('1:110,000,000'), value: 110 }, { label: _('1:50,000,000'), value: 50 }]
      }),
      _react2.default.createElement(_components.Numeric, { label: _('Scale'), attr: 'projection.scale', min: 0 }),
      _react2.default.createElement(_components.Numeric, { label: _('Latitude'), attr: 'projection.rotation.lon', min: 0 }),
      _react2.default.createElement(_components.Numeric, { label: _('Longitude'), attr: 'projection.rotation.lat', min: 0 }),
      _react2.default.createElement(_components.Numeric, { label: _('Roll'), attr: 'projection.rotation.roll', min: 0 })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Ternary') },
      _react2.default.createElement(_components.Numeric, { label: _('Sum'), attr: 'sum' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Polar Sector') },
      _react2.default.createElement(_components.Numeric, { label: _('Min'), attr: 'sector[0]', min: -360, max: 360, showSlider: true }),
      _react2.default.createElement(_components.Numeric, { label: _('Max'), attr: 'sector[1]', min: -360, max: 360, showSlider: true }),
      _react2.default.createElement(_components.NumericFraction, { label: _('Hole'), attr: 'hole', min: 0, max: 100, showSlider: true })
    )
  );
};

GraphSubplotsPanel.contextTypes = {
  localize: _propTypes2.default.func
};

exports.default = GraphSubplotsPanel;
//# sourceMappingURL=GraphSubplotsPanel.js.map

/***/ }),

/***/ "VLrD":
/*!******************************************!*\
  !*** ./node_modules/es6-promise/auto.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
// This file can be required in Browserify and Node.js for automatic polyfill
// To use it:  require('es6-promise/auto');

module.exports = __webpack_require__(/*! ./ */ "E2g8").polyfill();


/***/ }),

/***/ "VOtZ":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_copySymbols.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var copyObject = __webpack_require__(/*! ./_copyObject */ "juv8"),
    getSymbols = __webpack_require__(/*! ./_getSymbols */ "MvSz");

/**
 * 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);
}

module.exports = copySymbols;


/***/ }),

/***/ "VSmT":
/*!********************************************************!*\
  !*** ./node_modules/draft-js/lib/EditorBidiService.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule EditorBidiService
 * @format
 * 
 */



var Immutable = __webpack_require__(/*! immutable */ "JPcv");
var UnicodeBidiService = __webpack_require__(/*! fbjs/lib/UnicodeBidiService */ "I8OZ");

var nullthrows = __webpack_require__(/*! fbjs/lib/nullthrows */ "gWRK");

var OrderedMap = Immutable.OrderedMap;


var bidiService;

var EditorBidiService = {
  getDirectionMap: function getDirectionMap(content, prevBidiMap) {
    if (!bidiService) {
      bidiService = new UnicodeBidiService();
    } else {
      bidiService.reset();
    }

    var blockMap = content.getBlockMap();
    var nextBidi = blockMap.valueSeq().map(function (block) {
      return nullthrows(bidiService).getDirection(block.getText());
    });
    var bidiMap = OrderedMap(blockMap.keySeq().zip(nextBidi));

    if (prevBidiMap != null && Immutable.is(prevBidiMap, bidiMap)) {
      return prevBidiMap;
    }

    return bidiMap;
  }
};

module.exports = EditorBidiService;

/***/ }),

/***/ "VTBg":
/*!***************************************************************!*\
  !*** ./node_modules/draft-js/lib/getNextDelimiterBlockKey.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule getNextDelimiterBlockKey
 * @format
 * 
 *
 * This is unstable and not part of the public API and should not be used by
 * production systems. This file may be update/removed without notice.
 */

var ContentBlockNode = __webpack_require__(/*! ./ContentBlockNode */ "JL7T");

var getNextDelimiterBlockKey = function getNextDelimiterBlockKey(block, blockMap) {
  var isExperimentalTreeBlock = block instanceof ContentBlockNode;

  if (!isExperimentalTreeBlock) {
    return null;
  }

  var nextSiblingKey = block.getNextSiblingKey();

  if (nextSiblingKey) {
    return nextSiblingKey;
  }

  var parent = block.getParentKey();

  if (!parent) {
    return null;
  }

  var nextNonDescendantBlock = blockMap.get(parent);
  while (nextNonDescendantBlock && !nextNonDescendantBlock.getNextSiblingKey()) {
    var parentKey = nextNonDescendantBlock.getParentKey();
    nextNonDescendantBlock = parentKey ? blockMap.get(parentKey) : null;
  }

  if (!nextNonDescendantBlock) {
    return null;
  }

  return nextNonDescendantBlock.getNextSiblingKey();
};

module.exports = getNextDelimiterBlockKey;

/***/ }),

/***/ "VVlx":
/*!*************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_shared-key.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var shared = __webpack_require__(/*! ./_shared */ "29s/")('keys');
var uid = __webpack_require__(/*! ./_uid */ "YqAc");
module.exports = function (key) {
  return shared[key] || (shared[key] = uid(key));
};


/***/ }),

/***/ "VVms":
/*!************************************************************!*\
  !*** ./node_modules/react-color/lib/helpers/saturation.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var calculateChange = exports.calculateChange = function calculateChange(e, skip, props, container) {
  e.preventDefault();

  var _container$getBoundin = container.getBoundingClientRect(),
      containerWidth = _container$getBoundin.width,
      containerHeight = _container$getBoundin.height;

  var x = typeof e.pageX === 'number' ? e.pageX : e.touches[0].pageX;
  var y = typeof e.pageY === 'number' ? e.pageY : e.touches[0].pageY;
  var left = x - (container.getBoundingClientRect().left + window.pageXOffset);
  var top = y - (container.getBoundingClientRect().top + window.pageYOffset);

  if (left < 0) {
    left = 0;
  } else if (left > containerWidth) {
    left = containerWidth;
  } else if (top < 0) {
    top = 0;
  } else if (top > containerHeight) {
    top = containerHeight;
  }

  var saturation = left * 100 / containerWidth;
  var bright = -(top * 100 / containerHeight) + 100;

  return {
    h: props.hsl.h,
    s: saturation,
    v: bright,
    a: props.hsl.a,
    source: 'rgb'
  };
};

/***/ }),

/***/ "VWeM":
/*!*********************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/filter_unique.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/





/**
 * Return news array containing only the unique items
 * found in input array.
 *
 * IMPORTANT: Note that items are considered unique
 * if `String({})` is unique. For example;
 *
 *  Lib.filterUnique([ { a: 1 }, { b: 2 } ])
 *
 *  returns [{ a: 1 }]
 *
 * and
 *
 *  Lib.filterUnique([ '1', 1 ])
 *
 *  returns ['1']
 *
 *
 * @param {array} array base array
 * @return {array} new filtered array
 */
module.exports = function filterUnique(array) {
    var seen = {};
    var out = [];
    var j = 0;

    for(var i = 0; i < array.length; i++) {
        var item = array[i];

        if(seen[item] !== 1) {
            seen[item] = 1;
            out[j++] = item;
        }
    }

    return out;
};


/***/ }),

/***/ "VYmV":
/*!*******************************************************************!*\
  !*** ./node_modules/@jupyterlab/completer-extension/lib/index.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const completer_1 = __webpack_require__(/*! @jupyterlab/completer */ "RvMh");
const console_1 = __webpack_require__(/*! @jupyterlab/console */ "DrOJ");
const fileeditor_1 = __webpack_require__(/*! @jupyterlab/fileeditor */ "RHTn");
const notebook_1 = __webpack_require__(/*! @jupyterlab/notebook */ "JOGU");
const services_1 = __webpack_require__(/*! @jupyterlab/services */ "S9up");
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
/**
 * The command IDs used by the completer plugin.
 */
var CommandIDs;
(function (CommandIDs) {
    CommandIDs.invoke = 'completer:invoke';
    CommandIDs.invokeConsole = 'completer:invoke-console';
    CommandIDs.invokeNotebook = 'completer:invoke-notebook';
    CommandIDs.invokeFile = 'completer:invoke-file';
    CommandIDs.select = 'completer:select';
    CommandIDs.selectConsole = 'completer:select-console';
    CommandIDs.selectNotebook = 'completer:select-notebook';
    CommandIDs.selectFile = 'completer:select-file';
})(CommandIDs || (CommandIDs = {}));
/**
 * A plugin providing code completion for editors.
 */
const manager = {
    id: '@jupyterlab/completer-extension:manager',
    autoStart: true,
    provides: completer_1.ICompletionManager,
    activate: (app) => {
        const handlers = {};
        app.commands.addCommand(CommandIDs.invoke, {
            execute: args => {
                let id = args && args['id'];
                if (!id) {
                    return;
                }
                const handler = handlers[id];
                if (handler) {
                    handler.invoke();
                }
            }
        });
        app.commands.addCommand(CommandIDs.select, {
            execute: args => {
                let id = args && args['id'];
                if (!id) {
                    return;
                }
                const handler = handlers[id];
                if (handler) {
                    handler.completer.selectActive();
                }
            }
        });
        return {
            register: (completable) => {
                const { connector, editor, parent } = completable;
                const model = new completer_1.CompleterModel();
                const completer = new completer_1.Completer({ editor, model });
                const handler = new completer_1.CompletionHandler({ completer, connector });
                const id = parent.id;
                // Hide the widget when it first loads.
                completer.hide();
                // Associate the handler with the parent widget.
                handlers[id] = handler;
                // Set the handler's editor.
                handler.editor = editor;
                // Attach the completer widget.
                widgets_1.Widget.attach(completer, document.body);
                // Listen for parent disposal.
                parent.disposed.connect(() => {
                    delete handlers[id];
                    model.dispose();
                    completer.dispose();
                    handler.dispose();
                });
                return handler;
            }
        };
    }
};
/**
 * An extension that registers consoles for code completion.
 */
const consoles = {
    id: '@jupyterlab/completer-extension:consoles',
    requires: [completer_1.ICompletionManager, console_1.IConsoleTracker],
    autoStart: true,
    activate: (app, manager, consoles) => {
        // Create a handler for each console that is created.
        consoles.widgetAdded.connect((sender, panel) => {
            const anchor = panel.console;
            const cell = anchor.promptCell;
            const editor = cell && cell.editor;
            const session = anchor.session;
            const parent = panel;
            const connector = new completer_1.CompletionConnector({ session, editor });
            const handler = manager.register({ connector, editor, parent });
            // Listen for prompt creation.
            anchor.promptCellCreated.connect((sender, cell) => {
                const editor = cell && cell.editor;
                handler.editor = editor;
                handler.connector = new completer_1.CompletionConnector({ session, editor });
            });
        });
        // Add console completer invoke command.
        app.commands.addCommand(CommandIDs.invokeConsole, {
            execute: () => {
                const id = consoles.currentWidget && consoles.currentWidget.id;
                if (id) {
                    return app.commands.execute(CommandIDs.invoke, { id });
                }
            }
        });
        // Add console completer select command.
        app.commands.addCommand(CommandIDs.selectConsole, {
            execute: () => {
                const id = consoles.currentWidget && consoles.currentWidget.id;
                if (id) {
                    return app.commands.execute(CommandIDs.select, { id });
                }
            }
        });
        // Set enter key for console completer select command.
        app.commands.addKeyBinding({
            command: CommandIDs.selectConsole,
            keys: ['Enter'],
            selector: `.jp-ConsolePanel .jp-mod-completer-active`
        });
    }
};
/**
 * An extension that registers notebooks for code completion.
 */
const notebooks = {
    id: '@jupyterlab/completer-extension:notebooks',
    requires: [completer_1.ICompletionManager, notebook_1.INotebookTracker],
    autoStart: true,
    activate: (app, manager, notebooks) => {
        // Create a handler for each notebook that is created.
        notebooks.widgetAdded.connect((sender, panel) => {
            const cell = panel.content.activeCell;
            const editor = cell && cell.editor;
            const session = panel.session;
            const parent = panel;
            const connector = new completer_1.CompletionConnector({ session, editor });
            const handler = manager.register({ connector, editor, parent });
            // Listen for active cell changes.
            panel.content.activeCellChanged.connect((sender, cell) => {
                const editor = cell && cell.editor;
                handler.editor = editor;
                handler.connector = new completer_1.CompletionConnector({ session, editor });
            });
        });
        // Add notebook completer command.
        app.commands.addCommand(CommandIDs.invokeNotebook, {
            execute: () => {
                const panel = notebooks.currentWidget;
                if (panel && panel.content.activeCell.model.type === 'code') {
                    return app.commands.execute(CommandIDs.invoke, { id: panel.id });
                }
            }
        });
        // Add notebook completer select command.
        app.commands.addCommand(CommandIDs.selectNotebook, {
            execute: () => {
                const id = notebooks.currentWidget && notebooks.currentWidget.id;
                if (id) {
                    return app.commands.execute(CommandIDs.select, { id });
                }
            }
        });
        // Set enter key for notebook completer select command.
        app.commands.addKeyBinding({
            command: CommandIDs.selectNotebook,
            keys: ['Enter'],
            selector: `.jp-Notebook .jp-mod-completer-active`
        });
    }
};
/**
 * An extension that registers file editors for completion.
 */
const files = {
    id: '@jupyterlab/completer-extension:files',
    requires: [completer_1.ICompletionManager, fileeditor_1.IEditorTracker],
    autoStart: true,
    activate: (app, manager, editorTracker) => {
        // Keep a list of active ISessions so that we can
        // clean them up when they are no longer needed.
        const activeSessions = {};
        // When a new file editor is created, make the completer for it.
        editorTracker.widgetAdded.connect((sender, widget) => {
            const sessions = app.serviceManager.sessions;
            const editor = widget.content.editor;
            const contextConnector = new completer_1.ContextConnector({ editor });
            // When the list of running sessions changes,
            // check to see if there are any kernels with a
            // matching path for this file editor.
            const onRunningChanged = (sender, models) => {
                const oldSession = activeSessions[widget.id];
                // Search for a matching path.
                const model = algorithm_1.find(models, m => m.path === widget.context.path);
                if (model) {
                    // If there is a matching path, but it is the same
                    // session as we previously had, do nothing.
                    if (oldSession && oldSession.id === model.id) {
                        return;
                    }
                    // Otherwise, dispose of the old session and reset to
                    // a new CompletionConnector.
                    if (oldSession) {
                        delete activeSessions[widget.id];
                        oldSession.dispose();
                    }
                    const session = sessions.connectTo(model);
                    handler.connector = new completer_1.CompletionConnector({ session, editor });
                    activeSessions[widget.id] = session;
                }
                else {
                    // If we didn't find a match, make sure
                    // the connector is the contextConnector and
                    // dispose of any previous connection.
                    handler.connector = contextConnector;
                    if (oldSession) {
                        delete activeSessions[widget.id];
                        oldSession.dispose();
                    }
                }
            };
            services_1.Session.listRunning().then(models => {
                onRunningChanged(sessions, models);
            });
            sessions.runningChanged.connect(onRunningChanged);
            // Initially create the handler with the contextConnector.
            // If a kernel session is found matching this file editor,
            // it will be replaced in onRunningChanged().
            const handler = manager.register({
                connector: contextConnector,
                editor,
                parent: widget
            });
            // When the widget is disposed, do some cleanup.
            widget.disposed.connect(() => {
                sessions.runningChanged.disconnect(onRunningChanged);
                const session = activeSessions[widget.id];
                if (session) {
                    delete activeSessions[widget.id];
                    session.dispose();
                }
            });
        });
        // Add console completer invoke command.
        app.commands.addCommand(CommandIDs.invokeFile, {
            execute: () => {
                const id = editorTracker.currentWidget && editorTracker.currentWidget.id;
                if (id) {
                    return app.commands.execute(CommandIDs.invoke, { id });
                }
            }
        });
        // Add console completer select command.
        app.commands.addCommand(CommandIDs.selectFile, {
            execute: () => {
                const id = editorTracker.currentWidget && editorTracker.currentWidget.id;
                if (id) {
                    return app.commands.execute(CommandIDs.select, { id });
                }
            }
        });
        // Set enter key for console completer select command.
        app.commands.addKeyBinding({
            command: CommandIDs.selectFile,
            keys: ['Enter'],
            selector: `.jp-FileEditor .jp-mod-completer-active`
        });
    }
};
/**
 * Export the plugins as default.
 */
const plugins = [manager, consoles, notebooks, files];
exports.default = plugins;


/***/ }),

/***/ "VYtm":
/*!*******************************************************!*\
  !*** ./node_modules/reactcss/lib/components/hover.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.hover = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var hover = exports.hover = function hover(Component) {
  var Span = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'span';

  return function (_React$Component) {
    _inherits(Hover, _React$Component);

    function Hover() {
      var _ref;

      var _temp, _this, _ret;

      _classCallCheck(this, Hover);

      for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Hover.__proto__ || Object.getPrototypeOf(Hover)).call.apply(_ref, [this].concat(args))), _this), _this.state = { hover: false }, _this.handleMouseOver = function () {
        return _this.setState({ hover: true });
      }, _this.handleMouseOut = function () {
        return _this.setState({ hover: false });
      }, _this.render = function () {
        return _react2.default.createElement(
          Span,
          { onMouseOver: _this.handleMouseOver, onMouseOut: _this.handleMouseOut },
          _react2.default.createElement(Component, _extends({}, _this.props, _this.state))
        );
      }, _temp), _possibleConstructorReturn(_this, _ret);
    }

    return Hover;
  }(_react2.default.Component);
};

exports.default = hover;

/***/ }),

/***/ "VaNO":
/*!******************************************!*\
  !*** ./node_modules/lodash/_stackHas.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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);
}

module.exports = stackHas;


/***/ }),

/***/ "Vclq":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/es-us.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'),
    monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_');

var esUs = moment.defineLocale('es-us', {
    months : 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'),
    monthsShort : function (m, format) {
        if (!m) {
            return monthsShortDot;
        } else if (/-MMM-/.test(format)) {
            return monthsShort[m.month()];
        } else {
            return monthsShortDot[m.month()];
        }
    },
    monthsParseExact : true,
    weekdays : 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'),
    weekdaysShort : 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'),
    weekdaysMin : 'do_lu_ma_mi_ju_vi_sá'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'h:mm A',
        LTS : 'h:mm:ss A',
        L : 'MM/DD/YYYY',
        LL : 'MMMM [de] D [de] YYYY',
        LLL : 'MMMM [de] D [de] YYYY h:mm A',
        LLLL : 'dddd, MMMM [de] D [de] YYYY h:mm A'
    },
    calendar : {
        sameDay : function () {
            return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
        },
        nextDay : function () {
            return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
        },
        nextWeek : function () {
            return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
        },
        lastDay : function () {
            return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
        },
        lastWeek : function () {
            return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
        },
        sameElse : 'L'
    },
    relativeTime : {
        future : 'en %s',
        past : 'hace %s',
        s : 'unos segundos',
        ss : '%d segundos',
        m : 'un minuto',
        mm : '%d minutos',
        h : 'una hora',
        hh : '%d horas',
        d : 'un día',
        dd : '%d días',
        M : 'un mes',
        MM : '%d meses',
        y : 'un año',
        yy : '%d años'
    },
    dayOfMonthOrdinalParse : /\d{1,2}º/,
    ordinal : '%dº',
    week : {
        dow : 0, // Sunday is the first day of the week.
        doy : 6  // The week that contains Jan 1st is the first week of the year.
    }
});

return esUs;

})));


/***/ }),

/***/ "Vgfr":
/*!*********************************************!*\
  !*** ./node_modules/base16/lib/eighties.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'eighties',
  author: 'chris kempson (http://chriskempson.com)',
  base00: '#2d2d2d',
  base01: '#393939',
  base02: '#515151',
  base03: '#747369',
  base04: '#a09f93',
  base05: '#d3d0c8',
  base06: '#e8e6df',
  base07: '#f2f0ec',
  base08: '#f2777a',
  base09: '#f99157',
  base0A: '#ffcc66',
  base0B: '#99cc99',
  base0C: '#66cccc',
  base0D: '#6699cc',
  base0E: '#cc99cc',
  base0F: '#d27b53'
};
module.exports = exports['default'];

/***/ }),

/***/ "Vh22":
/*!***********************************************!*\
  !*** ./node_modules/diffie-hellman/lib/dh.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(Buffer) {var BN = __webpack_require__(/*! bn.js */ "OZ/i");
var MillerRabin = __webpack_require__(/*! miller-rabin */ "ehAg");
var millerRabin = new MillerRabin();
var TWENTYFOUR = new BN(24);
var ELEVEN = new BN(11);
var TEN = new BN(10);
var THREE = new BN(3);
var SEVEN = new BN(7);
var primes = __webpack_require__(/*! ./generatePrime */ "WKKt");
var randomBytes = __webpack_require__(/*! randombytes */ "Edxu");
module.exports = DH;

function setPublicKey(pub, enc) {
  enc = enc || 'utf8';
  if (!Buffer.isBuffer(pub)) {
    pub = new Buffer(pub, enc);
  }
  this._pub = new BN(pub);
  return this;
}

function setPrivateKey(priv, enc) {
  enc = enc || 'utf8';
  if (!Buffer.isBuffer(priv)) {
    priv = new Buffer(priv, enc);
  }
  this._priv = new BN(priv);
  return this;
}

var primeCache = {};
function checkPrime(prime, generator) {
  var gen = generator.toString('hex');
  var hex = [gen, prime.toString(16)].join('_');
  if (hex in primeCache) {
    return primeCache[hex];
  }
  var error = 0;

  if (prime.isEven() ||
    !primes.simpleSieve ||
    !primes.fermatTest(prime) ||
    !millerRabin.test(prime)) {
    //not a prime so +1
    error += 1;

    if (gen === '02' || gen === '05') {
      // we'd be able to check the generator
      // it would fail so +8
      error += 8;
    } else {
      //we wouldn't be able to test the generator
      // so +4
      error += 4;
    }
    primeCache[hex] = error;
    return error;
  }
  if (!millerRabin.test(prime.shrn(1))) {
    //not a safe prime
    error += 2;
  }
  var rem;
  switch (gen) {
    case '02':
      if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) {
        // unsuidable generator
        error += 8;
      }
      break;
    case '05':
      rem = prime.mod(TEN);
      if (rem.cmp(THREE) && rem.cmp(SEVEN)) {
        // prime mod 10 needs to equal 3 or 7
        error += 8;
      }
      break;
    default:
      error += 4;
  }
  primeCache[hex] = error;
  return error;
}

function DH(prime, generator, malleable) {
  this.setGenerator(generator);
  this.__prime = new BN(prime);
  this._prime = BN.mont(this.__prime);
  this._primeLen = prime.length;
  this._pub = undefined;
  this._priv = undefined;
  this._primeCode = undefined;
  if (malleable) {
    this.setPublicKey = setPublicKey;
    this.setPrivateKey = setPrivateKey;
  } else {
    this._primeCode = 8;
  }
}
Object.defineProperty(DH.prototype, 'verifyError', {
  enumerable: true,
  get: function () {
    if (typeof this._primeCode !== 'number') {
      this._primeCode = checkPrime(this.__prime, this.__gen);
    }
    return this._primeCode;
  }
});
DH.prototype.generateKeys = function () {
  if (!this._priv) {
    this._priv = new BN(randomBytes(this._primeLen));
  }
  this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed();
  return this.getPublicKey();
};

DH.prototype.computeSecret = function (other) {
  other = new BN(other);
  other = other.toRed(this._prime);
  var secret = other.redPow(this._priv).fromRed();
  var out = new Buffer(secret.toArray());
  var prime = this.getPrime();
  if (out.length < prime.length) {
    var front = new Buffer(prime.length - out.length);
    front.fill(0);
    out = Buffer.concat([front, out]);
  }
  return out;
};

DH.prototype.getPublicKey = function getPublicKey(enc) {
  return formatReturnValue(this._pub, enc);
};

DH.prototype.getPrivateKey = function getPrivateKey(enc) {
  return formatReturnValue(this._priv, enc);
};

DH.prototype.getPrime = function (enc) {
  return formatReturnValue(this.__prime, enc);
};

DH.prototype.getGenerator = function (enc) {
  return formatReturnValue(this._gen, enc);
};

DH.prototype.setGenerator = function (gen, enc) {
  enc = enc || 'utf8';
  if (!Buffer.isBuffer(gen)) {
    gen = new Buffer(gen, enc);
  }
  this.__gen = gen;
  this._gen = new BN(gen);
  return this;
};

function formatReturnValue(bn, enc) {
  var buf = new Buffer(bn.toArray());
  if (!enc) {
    return buf;
  } else {
    return buf.toString(enc);
  }
}

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../buffer/index.js */ "tjlA").Buffer))

/***/ }),

/***/ "VizT":
/*!*************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/index.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DateTimePicker = exports.TraceTypeSelectorButton = exports.TraceTypeSelector = exports.RadioBlocks = exports.Button = undefined;

var _Button = __webpack_require__(/*! ./Button */ "rZxl");

var _Button2 = _interopRequireDefault(_Button);

var _RadioBlocks = __webpack_require__(/*! ./RadioBlocks */ "N8y9");

var _RadioBlocks2 = _interopRequireDefault(_RadioBlocks);

var _DateTimePicker = __webpack_require__(/*! ./DateTimePicker */ "5DOW");

var _DateTimePicker2 = _interopRequireDefault(_DateTimePicker);

var _TraceTypeSelector = __webpack_require__(/*! ./TraceTypeSelector */ "BOmv");

var _TraceTypeSelector2 = _interopRequireDefault(_TraceTypeSelector);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.Button = _Button2.default;
exports.RadioBlocks = _RadioBlocks2.default;
exports.TraceTypeSelector = _TraceTypeSelector2.default;
exports.TraceTypeSelectorButton = _TraceTypeSelector.TraceTypeSelectorButton;
exports.DateTimePicker = _DateTimePicker2.default;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ "VjLE":
/*!**********************************************************!*\
  !*** ./node_modules/@jupyterlab/running/style/index.css ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "HXUZ");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "VmqU":
/*!******************************************************************!*\
  !*** ./node_modules/@jupyterlab/observables/lib/undoablelist.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const observablelist_1 = __webpack_require__(/*! ./observablelist */ "eXBS");
/**
 * A concrete implementation of an observable undoable list.
 */
class ObservableUndoableList extends observablelist_1.ObservableList {
    /**
     * Construct a new undoable observable list.
     */
    constructor(serializer) {
        super();
        this._inCompound = false;
        this._isUndoable = true;
        this._madeCompoundChange = false;
        this._index = -1;
        this._stack = [];
        this._serializer = serializer;
        this.changed.connect(this._onListChanged, this);
    }
    /**
     * Whether the object can redo changes.
     */
    get canRedo() {
        return this._index < this._stack.length - 1;
    }
    /**
     * Whether the object can undo changes.
     */
    get canUndo() {
        return this._index >= 0;
    }
    /**
     * Begin a compound operation.
     *
     * @param isUndoAble - Whether the operation is undoable.
     *   The default is `true`.
     */
    beginCompoundOperation(isUndoAble) {
        this._inCompound = true;
        this._isUndoable = isUndoAble !== false;
        this._madeCompoundChange = false;
    }
    /**
     * End a compound operation.
     */
    endCompoundOperation() {
        this._inCompound = false;
        this._isUndoable = true;
        if (this._madeCompoundChange) {
            this._index++;
        }
    }
    /**
     * Undo an operation.
     */
    undo() {
        if (!this.canUndo) {
            return;
        }
        let changes = this._stack[this._index];
        this._isUndoable = false;
        for (let change of changes.reverse()) {
            this._undoChange(change);
        }
        this._isUndoable = true;
        this._index--;
    }
    /**
     * Redo an operation.
     */
    redo() {
        if (!this.canRedo) {
            return;
        }
        this._index++;
        let changes = this._stack[this._index];
        this._isUndoable = false;
        for (let change of changes) {
            this._redoChange(change);
        }
        this._isUndoable = true;
    }
    /**
     * Clear the change stack.
     */
    clearUndo() {
        this._index = -1;
        this._stack = [];
    }
    /**
     * Handle a change in the list.
     */
    _onListChanged(list, change) {
        if (this.isDisposed || !this._isUndoable) {
            return;
        }
        // Clear everything after this position if necessary.
        if (!this._inCompound || !this._madeCompoundChange) {
            this._stack = this._stack.slice(0, this._index + 1);
        }
        // Copy the change.
        let evt = this._copyChange(change);
        // Put the change in the stack.
        if (this._stack[this._index + 1]) {
            this._stack[this._index + 1].push(evt);
        }
        else {
            this._stack.push([evt]);
        }
        // If not in a compound operation, increase index.
        if (!this._inCompound) {
            this._index++;
        }
        else {
            this._madeCompoundChange = true;
        }
    }
    /**
     * Undo a change event.
     */
    _undoChange(change) {
        let index = 0;
        let serializer = this._serializer;
        switch (change.type) {
            case 'add':
                algorithm_1.each(change.newValues, () => {
                    this.remove(change.newIndex);
                });
                break;
            case 'set':
                index = change.oldIndex;
                algorithm_1.each(change.oldValues, value => {
                    this.set(index++, serializer.fromJSON(value));
                });
                break;
            case 'remove':
                index = change.oldIndex;
                algorithm_1.each(change.oldValues, value => {
                    this.insert(index++, serializer.fromJSON(value));
                });
                break;
            case 'move':
                this.move(change.newIndex, change.oldIndex);
                break;
            default:
                return;
        }
    }
    /**
     * Redo a change event.
     */
    _redoChange(change) {
        let index = 0;
        let serializer = this._serializer;
        switch (change.type) {
            case 'add':
                index = change.newIndex;
                algorithm_1.each(change.newValues, value => {
                    this.insert(index++, serializer.fromJSON(value));
                });
                break;
            case 'set':
                index = change.newIndex;
                algorithm_1.each(change.newValues, value => {
                    this.set(change.newIndex++, serializer.fromJSON(value));
                });
                break;
            case 'remove':
                algorithm_1.each(change.oldValues, () => {
                    this.remove(change.oldIndex);
                });
                break;
            case 'move':
                this.move(change.oldIndex, change.newIndex);
                break;
            default:
                return;
        }
    }
    /**
     * Copy a change as JSON.
     */
    _copyChange(change) {
        let oldValues = [];
        algorithm_1.each(change.oldValues, value => {
            oldValues.push(this._serializer.toJSON(value));
        });
        let newValues = [];
        algorithm_1.each(change.newValues, value => {
            newValues.push(this._serializer.toJSON(value));
        });
        return {
            type: change.type,
            oldIndex: change.oldIndex,
            newIndex: change.newIndex,
            oldValues,
            newValues
        };
    }
}
exports.ObservableUndoableList = ObservableUndoableList;
/**
 * Namespace for ObservableUndoableList utilities.
 */
(function (ObservableUndoableList) {
    /**
     * A default, identity serializer.
     */
    class IdentitySerializer {
        /**
         * Identity serialize.
         */
        toJSON(value) {
            return value;
        }
        /**
         * Identity deserialize.
         */
        fromJSON(value) {
            return value;
        }
    }
    ObservableUndoableList.IdentitySerializer = IdentitySerializer;
})(ObservableUndoableList = exports.ObservableUndoableList || (exports.ObservableUndoableList = {}));


/***/ }),

/***/ "VnmM":
/*!***********************************************!*\
  !*** ./node_modules/mdi-react/HistoryIcon.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var HistoryIcon = function HistoryIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M13.5,8H12V13L16.28,15.54L17,14.33L13.5,12.25V8M13,3C8.03,3 4,7.03 4,12H1L4.96,16.03L9,12H6C6,8.13 9.13,5 13,5C16.87,5 20,8.13 20,12C20,15.87 16.87,19 13,19C11.07,19 9.32,18.21 8.06,16.94L6.64,18.36C8.27,20 10.5,21 13,21C17.97,21 22,16.97 22,12C22,7.03 17.97,3 13,3' })
  );
};

module.exports = HistoryIcon;


/***/ }),

/***/ "Vp1n":
/*!*****************************************!*\
  !*** ./node_modules/base16/lib/flat.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'flat',
  author: 'chris kempson (http://chriskempson.com)',
  base00: '#2C3E50',
  base01: '#34495E',
  base02: '#7F8C8D',
  base03: '#95A5A6',
  base04: '#BDC3C7',
  base05: '#e0e0e0',
  base06: '#f5f5f5',
  base07: '#ECF0F1',
  base08: '#E74C3C',
  base09: '#E67E22',
  base0A: '#F1C40F',
  base0B: '#2ECC71',
  base0C: '#1ABC9C',
  base0D: '#3498DB',
  base0E: '#9B59B6',
  base0F: '#be643c'
};
module.exports = exports['default'];

/***/ }),

/***/ "VrN/":
/*!***************************************************!*\
  !*** ./node_modules/codemirror/lib/codemirror.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

// This is CodeMirror (http://codemirror.net), a code editor
// implemented in JavaScript on top of the browser's DOM.
//
// You can find some technical background for some of the code below
// at http://marijnhaverbeke.nl/blog/#cm-internals .

(function (global, factory) {
	 true ? module.exports = factory() :
	undefined;
}(this, (function () { 'use strict';

// Kludges for bugs and behavior differences that can't be feature
// detected are enabled based on userAgent etc sniffing.
var userAgent = navigator.userAgent;
var platform = navigator.platform;

var gecko = /gecko\/\d/i.test(userAgent);
var ie_upto10 = /MSIE \d/.test(userAgent);
var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
var edge = /Edge\/(\d+)/.exec(userAgent);
var ie = ie_upto10 || ie_11up || edge;
var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
var webkit = !edge && /WebKit\//.test(userAgent);
var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
var chrome = !edge && /Chrome\//.test(userAgent);
var presto = /Opera\//.test(userAgent);
var safari = /Apple Computer/.test(navigator.vendor);
var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
var phantom = /PhantomJS/.test(userAgent);

var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
var android = /Android/.test(userAgent);
// This is woefully incomplete. Suggestions for alternative methods welcome.
var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
var mac = ios || /Mac/.test(platform);
var chromeOS = /\bCrOS\b/.test(userAgent);
var windows = /win/i.test(platform);

var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
if (presto_version) { presto_version = Number(presto_version[1]); }
if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
// Some browsers use the wrong event properties to signal cmd/ctrl on OS X
var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
var captureRightClick = gecko || (ie && ie_version >= 9);

function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }

var rmClass = function(node, cls) {
  var current = node.className;
  var match = classTest(cls).exec(current);
  if (match) {
    var after = current.slice(match.index + match[0].length);
    node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  }
};

function removeChildren(e) {
  for (var count = e.childNodes.length; count > 0; --count)
    { e.removeChild(e.firstChild); }
  return e
}

function removeChildrenAndAdd(parent, e) {
  return removeChildren(parent).appendChild(e)
}

function elt(tag, content, className, style) {
  var e = document.createElement(tag);
  if (className) { e.className = className; }
  if (style) { e.style.cssText = style; }
  if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
  else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
  return e
}
// wrapper for elt, which removes the elt from the accessibility tree
function eltP(tag, content, className, style) {
  var e = elt(tag, content, className, style);
  e.setAttribute("role", "presentation");
  return e
}

var range;
if (document.createRange) { range = function(node, start, end, endNode) {
  var r = document.createRange();
  r.setEnd(endNode || node, end);
  r.setStart(node, start);
  return r
}; }
else { range = function(node, start, end) {
  var r = document.body.createTextRange();
  try { r.moveToElementText(node.parentNode); }
  catch(e) { return r }
  r.collapse(true);
  r.moveEnd("character", end);
  r.moveStart("character", start);
  return r
}; }

function contains(parent, child) {
  if (child.nodeType == 3) // Android browser always returns false when child is a textnode
    { child = child.parentNode; }
  if (parent.contains)
    { return parent.contains(child) }
  do {
    if (child.nodeType == 11) { child = child.host; }
    if (child == parent) { return true }
  } while (child = child.parentNode)
}

function activeElt() {
  // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
  // IE < 10 will throw when accessed while the page is loading or in an iframe.
  // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
  var activeElement;
  try {
    activeElement = document.activeElement;
  } catch(e) {
    activeElement = document.body || null;
  }
  while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
    { activeElement = activeElement.shadowRoot.activeElement; }
  return activeElement
}

function addClass(node, cls) {
  var current = node.className;
  if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
}
function joinClasses(a, b) {
  var as = a.split(" ");
  for (var i = 0; i < as.length; i++)
    { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
  return b
}

var selectInput = function(node) { node.select(); };
if (ios) // Mobile Safari apparently has a bug where select() is broken.
  { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
else if (ie) // Suppress mysterious IE10 errors
  { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }

function bind(f) {
  var args = Array.prototype.slice.call(arguments, 1);
  return function(){return f.apply(null, args)}
}

function copyObj(obj, target, overwrite) {
  if (!target) { target = {}; }
  for (var prop in obj)
    { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
      { target[prop] = obj[prop]; } }
  return target
}

// Counts the column offset in a string, taking tabs into account.
// Used mostly to find indentation.
function countColumn(string, end, tabSize, startIndex, startValue) {
  if (end == null) {
    end = string.search(/[^\s\u00a0]/);
    if (end == -1) { end = string.length; }
  }
  for (var i = startIndex || 0, n = startValue || 0;;) {
    var nextTab = string.indexOf("\t", i);
    if (nextTab < 0 || nextTab >= end)
      { return n + (end - i) }
    n += nextTab - i;
    n += tabSize - (n % tabSize);
    i = nextTab + 1;
  }
}

var Delayed = function() {this.id = null;};
Delayed.prototype.set = function (ms, f) {
  clearTimeout(this.id);
  this.id = setTimeout(f, ms);
};

function indexOf(array, elt) {
  for (var i = 0; i < array.length; ++i)
    { if (array[i] == elt) { return i } }
  return -1
}

// Number of pixels added to scroller and sizer to hide scrollbar
var scrollerGap = 30;

// Returned or thrown by various protocols to signal 'I'm not
// handling this'.
var Pass = {toString: function(){return "CodeMirror.Pass"}};

// Reused option objects for setSelection & friends
var sel_dontScroll = {scroll: false};
var sel_mouse = {origin: "*mouse"};
var sel_move = {origin: "+move"};

// The inverse of countColumn -- find the offset that corresponds to
// a particular column.
function findColumn(string, goal, tabSize) {
  for (var pos = 0, col = 0;;) {
    var nextTab = string.indexOf("\t", pos);
    if (nextTab == -1) { nextTab = string.length; }
    var skipped = nextTab - pos;
    if (nextTab == string.length || col + skipped >= goal)
      { return pos + Math.min(skipped, goal - col) }
    col += nextTab - pos;
    col += tabSize - (col % tabSize);
    pos = nextTab + 1;
    if (col >= goal) { return pos }
  }
}

var spaceStrs = [""];
function spaceStr(n) {
  while (spaceStrs.length <= n)
    { spaceStrs.push(lst(spaceStrs) + " "); }
  return spaceStrs[n]
}

function lst(arr) { return arr[arr.length-1] }

function map(array, f) {
  var out = [];
  for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
  return out
}

function insertSorted(array, value, score) {
  var pos = 0, priority = score(value);
  while (pos < array.length && score(array[pos]) <= priority) { pos++; }
  array.splice(pos, 0, value);
}

function nothing() {}

function createObj(base, props) {
  var inst;
  if (Object.create) {
    inst = Object.create(base);
  } else {
    nothing.prototype = base;
    inst = new nothing();
  }
  if (props) { copyObj(props, inst); }
  return inst
}

var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
function isWordCharBasic(ch) {
  return /\w/.test(ch) || ch > "\x80" &&
    (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
}
function isWordChar(ch, helper) {
  if (!helper) { return isWordCharBasic(ch) }
  if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  return helper.test(ch)
}

function isEmpty(obj) {
  for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  return true
}

// Extending unicode characters. A series of a non-extending char +
// any number of extending chars is treated as a single unit as far
// as editing and measuring is concerned. This is not fully correct,
// since some scripts/fonts/browsers also treat other configurations
// of code points as a group.
var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }

// Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
function skipExtendingChars(str, pos, dir) {
  while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
  return pos
}

// Returns the value from the range [`from`; `to`] that satisfies
// `pred` and is closest to `from`. Assumes that at least `to`
// satisfies `pred`. Supports `from` being greater than `to`.
function findFirst(pred, from, to) {
  // At any point we are certain `to` satisfies `pred`, don't know
  // whether `from` does.
  var dir = from > to ? -1 : 1;
  for (;;) {
    if (from == to) { return from }
    var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
    if (mid == from) { return pred(mid) ? from : to }
    if (pred(mid)) { to = mid; }
    else { from = mid + dir; }
  }
}

// The display handles the DOM integration, both for input reading
// and content drawing. It holds references to DOM nodes and
// display-related state.

function Display(place, doc, input) {
  var d = this;
  this.input = input;

  // Covers bottom-right square when both scrollbars are present.
  d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  d.scrollbarFiller.setAttribute("cm-not-content", "true");
  // Covers bottom of gutter when coverGutterNextToScrollbar is on
  // and h scrollbar is present.
  d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  d.gutterFiller.setAttribute("cm-not-content", "true");
  // Will contain the actual code, positioned to cover the viewport.
  d.lineDiv = eltP("div", null, "CodeMirror-code");
  // Elements are added to these to represent selection and cursors.
  d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  // A visibility: hidden element used to find the size of things.
  d.measure = elt("div", null, "CodeMirror-measure");
  // When lines outside of the viewport are measured, they are drawn in this.
  d.lineMeasure = elt("div", null, "CodeMirror-measure");
  // Wraps everything that needs to exist inside the vertically-padded coordinate system
  d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
                    null, "position: relative; outline: none");
  var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
  // Moved around its parent to cover visible view.
  d.mover = elt("div", [lines], null, "position: relative");
  // Set to the height of the document, allowing scrolling.
  d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  d.sizerWidth = null;
  // Behavior of elts with overflow: auto and padding is
  // inconsistent across browsers. This is used to ensure the
  // scrollable area is big enough.
  d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  // Will contain the gutters, if any.
  d.gutters = elt("div", null, "CodeMirror-gutters");
  d.lineGutter = null;
  // Actual scrollable element.
  d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  d.scroller.setAttribute("tabIndex", "-1");
  // The element in which the editor lives.
  d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");

  // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }

  if (place) {
    if (place.appendChild) { place.appendChild(d.wrapper); }
    else { place(d.wrapper); }
  }

  // Current rendered range (may be bigger than the view window).
  d.viewFrom = d.viewTo = doc.first;
  d.reportedViewFrom = d.reportedViewTo = doc.first;
  // Information about the rendered lines.
  d.view = [];
  d.renderedView = null;
  // Holds info about a single rendered line when it was rendered
  // for measurement, while not in view.
  d.externalMeasured = null;
  // Empty space (in pixels) above the view
  d.viewOffset = 0;
  d.lastWrapHeight = d.lastWrapWidth = 0;
  d.updateLineNumbers = null;

  d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  d.scrollbarsClipped = false;

  // Used to only resize the line number gutter when necessary (when
  // the amount of lines crosses a boundary that makes its width change)
  d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  // Set to true when a non-horizontal-scrolling line widget is
  // added. As an optimization, line widget aligning is skipped when
  // this is false.
  d.alignWidgets = false;

  d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;

  // Tracks the maximum line length so that the horizontal scrollbar
  // can be kept static when scrolling.
  d.maxLine = null;
  d.maxLineLength = 0;
  d.maxLineChanged = false;

  // Used for measuring wheel scrolling granularity
  d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;

  // True when shift is held down.
  d.shift = false;

  // Used to track whether anything happened since the context menu
  // was opened.
  d.selForContextMenu = null;

  d.activeTouch = null;

  input.init(d);
}

// Find the line object corresponding to the given line number.
function getLine(doc, n) {
  n -= doc.first;
  if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  var chunk = doc;
  while (!chunk.lines) {
    for (var i = 0;; ++i) {
      var child = chunk.children[i], sz = child.chunkSize();
      if (n < sz) { chunk = child; break }
      n -= sz;
    }
  }
  return chunk.lines[n]
}

// Get the part of a document between two positions, as an array of
// strings.
function getBetween(doc, start, end) {
  var out = [], n = start.line;
  doc.iter(start.line, end.line + 1, function (line) {
    var text = line.text;
    if (n == end.line) { text = text.slice(0, end.ch); }
    if (n == start.line) { text = text.slice(start.ch); }
    out.push(text);
    ++n;
  });
  return out
}
// Get the lines between from and to, as array of strings.
function getLines(doc, from, to) {
  var out = [];
  doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
  return out
}

// Update the height of a line, propagating the height change
// upwards to parent nodes.
function updateLineHeight(line, height) {
  var diff = height - line.height;
  if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
}

// Given a line object, find its line number by walking up through
// its parent links.
function lineNo(line) {
  if (line.parent == null) { return null }
  var cur = line.parent, no = indexOf(cur.lines, line);
  for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
    for (var i = 0;; ++i) {
      if (chunk.children[i] == cur) { break }
      no += chunk.children[i].chunkSize();
    }
  }
  return no + cur.first
}

// Find the line at the given vertical position, using the height
// information in the document tree.
function lineAtHeight(chunk, h) {
  var n = chunk.first;
  outer: do {
    for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
      var child = chunk.children[i$1], ch = child.height;
      if (h < ch) { chunk = child; continue outer }
      h -= ch;
      n += child.chunkSize();
    }
    return n
  } while (!chunk.lines)
  var i = 0;
  for (; i < chunk.lines.length; ++i) {
    var line = chunk.lines[i], lh = line.height;
    if (h < lh) { break }
    h -= lh;
  }
  return n + i
}

function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}

function lineNumberFor(options, i) {
  return String(options.lineNumberFormatter(i + options.firstLineNumber))
}

// A Pos instance represents a position within the text.
function Pos(line, ch, sticky) {
  if ( sticky === void 0 ) sticky = null;

  if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  this.line = line;
  this.ch = ch;
  this.sticky = sticky;
}

// Compare two positions, return 0 if they are the same, a negative
// number when a is less, and a positive number otherwise.
function cmp(a, b) { return a.line - b.line || a.ch - b.ch }

function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }

function copyPos(x) {return Pos(x.line, x.ch)}
function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
function minPos(a, b) { return cmp(a, b) < 0 ? a : b }

// Most of the external API clips given positions to make sure they
// actually exist within the document.
function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
function clipPos(doc, pos) {
  if (pos.line < doc.first) { return Pos(doc.first, 0) }
  var last = doc.first + doc.size - 1;
  if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  return clipToLen(pos, getLine(doc, pos.line).text.length)
}
function clipToLen(pos, linelen) {
  var ch = pos.ch;
  if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  else if (ch < 0) { return Pos(pos.line, 0) }
  else { return pos }
}
function clipPosArray(doc, array) {
  var out = [];
  for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
  return out
}

// Optimize some code when these features are not used.
var sawReadOnlySpans = false;
var sawCollapsedSpans = false;

function seeReadOnlySpans() {
  sawReadOnlySpans = true;
}

function seeCollapsedSpans() {
  sawCollapsedSpans = true;
}

// TEXTMARKER SPANS

function MarkedSpan(marker, from, to) {
  this.marker = marker;
  this.from = from; this.to = to;
}

// Search an array of spans for a span matching the given marker.
function getMarkedSpanFor(spans, marker) {
  if (spans) { for (var i = 0; i < spans.length; ++i) {
    var span = spans[i];
    if (span.marker == marker) { return span }
  } }
}
// Remove a span from an array, returning undefined if no spans are
// left (we don't store arrays for lines without spans).
function removeMarkedSpan(spans, span) {
  var r;
  for (var i = 0; i < spans.length; ++i)
    { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
  return r
}
// Add a span to a line.
function addMarkedSpan(line, span) {
  line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  span.marker.attachLine(line);
}

// Used for the algorithm that adjusts markers for a change in the
// document. These functions cut an array of spans at a given
// character position, returning an array of remaining chunks (or
// undefined if nothing remains).
function markedSpansBefore(old, startCh, isInsert) {
  var nw;
  if (old) { for (var i = 0; i < old.length; ++i) {
    var span = old[i], marker = span.marker;
    var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
    if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
      var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
    }
  } }
  return nw
}
function markedSpansAfter(old, endCh, isInsert) {
  var nw;
  if (old) { for (var i = 0; i < old.length; ++i) {
    var span = old[i], marker = span.marker;
    var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
    if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
      var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
                                            span.to == null ? null : span.to - endCh));
    }
  } }
  return nw
}

// Given a change object, compute the new set of marker spans that
// cover the line in which the change took place. Removes spans
// entirely within the change, reconnects spans belonging to the
// same marker that appear on both sides of the change, and cuts off
// spans partially within the change. Returns an array of span
// arrays with one element for each line in (after) the change.
function stretchSpansOverChange(doc, change) {
  if (change.full) { return null }
  var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  if (!oldFirst && !oldLast) { return null }

  var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  // Get the spans that 'stick out' on both sides
  var first = markedSpansBefore(oldFirst, startCh, isInsert);
  var last = markedSpansAfter(oldLast, endCh, isInsert);

  // Next, merge those two ends
  var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  if (first) {
    // Fix up .to properties of first
    for (var i = 0; i < first.length; ++i) {
      var span = first[i];
      if (span.to == null) {
        var found = getMarkedSpanFor(last, span.marker);
        if (!found) { span.to = startCh; }
        else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
      }
    }
  }
  if (last) {
    // Fix up .from in last (or move them into first in case of sameLine)
    for (var i$1 = 0; i$1 < last.length; ++i$1) {
      var span$1 = last[i$1];
      if (span$1.to != null) { span$1.to += offset; }
      if (span$1.from == null) {
        var found$1 = getMarkedSpanFor(first, span$1.marker);
        if (!found$1) {
          span$1.from = offset;
          if (sameLine) { (first || (first = [])).push(span$1); }
        }
      } else {
        span$1.from += offset;
        if (sameLine) { (first || (first = [])).push(span$1); }
      }
    }
  }
  // Make sure we didn't create any zero-length spans
  if (first) { first = clearEmptySpans(first); }
  if (last && last != first) { last = clearEmptySpans(last); }

  var newMarkers = [first];
  if (!sameLine) {
    // Fill gap with whole-line-spans
    var gap = change.text.length - 2, gapMarkers;
    if (gap > 0 && first)
      { for (var i$2 = 0; i$2 < first.length; ++i$2)
        { if (first[i$2].to == null)
          { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
    for (var i$3 = 0; i$3 < gap; ++i$3)
      { newMarkers.push(gapMarkers); }
    newMarkers.push(last);
  }
  return newMarkers
}

// Remove spans that are empty and don't have a clearWhenEmpty
// option of false.
function clearEmptySpans(spans) {
  for (var i = 0; i < spans.length; ++i) {
    var span = spans[i];
    if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
      { spans.splice(i--, 1); }
  }
  if (!spans.length) { return null }
  return spans
}

// Used to 'clip' out readOnly ranges when making a change.
function removeReadOnlyRanges(doc, from, to) {
  var markers = null;
  doc.iter(from.line, to.line + 1, function (line) {
    if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
      var mark = line.markedSpans[i].marker;
      if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
        { (markers || (markers = [])).push(mark); }
    } }
  });
  if (!markers) { return null }
  var parts = [{from: from, to: to}];
  for (var i = 0; i < markers.length; ++i) {
    var mk = markers[i], m = mk.find(0);
    for (var j = 0; j < parts.length; ++j) {
      var p = parts[j];
      if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
      var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
      if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
        { newParts.push({from: p.from, to: m.from}); }
      if (dto > 0 || !mk.inclusiveRight && !dto)
        { newParts.push({from: m.to, to: p.to}); }
      parts.splice.apply(parts, newParts);
      j += newParts.length - 3;
    }
  }
  return parts
}

// Connect or disconnect spans from a line.
function detachMarkedSpans(line) {
  var spans = line.markedSpans;
  if (!spans) { return }
  for (var i = 0; i < spans.length; ++i)
    { spans[i].marker.detachLine(line); }
  line.markedSpans = null;
}
function attachMarkedSpans(line, spans) {
  if (!spans) { return }
  for (var i = 0; i < spans.length; ++i)
    { spans[i].marker.attachLine(line); }
  line.markedSpans = spans;
}

// Helpers used when computing which overlapping collapsed span
// counts as the larger one.
function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }

// Returns a number indicating which of two overlapping collapsed
// spans is larger (and thus includes the other). Falls back to
// comparing ids when the spans cover exactly the same range.
function compareCollapsedMarkers(a, b) {
  var lenDiff = a.lines.length - b.lines.length;
  if (lenDiff != 0) { return lenDiff }
  var aPos = a.find(), bPos = b.find();
  var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  if (fromCmp) { return -fromCmp }
  var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  if (toCmp) { return toCmp }
  return b.id - a.id
}

// Find out whether a line ends or starts in a collapsed span. If
// so, return the marker for that span.
function collapsedSpanAtSide(line, start) {
  var sps = sawCollapsedSpans && line.markedSpans, found;
  if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
    sp = sps[i];
    if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
        (!found || compareCollapsedMarkers(found, sp.marker) < 0))
      { found = sp.marker; }
  } }
  return found
}
function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }

function collapsedSpanAround(line, ch) {
  var sps = sawCollapsedSpans && line.markedSpans, found;
  if (sps) { for (var i = 0; i < sps.length; ++i) {
    var sp = sps[i];
    if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
        (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
  } }
  return found
}

// Test whether there exists a collapsed span that partially
// overlaps (covers the start or end, but not both) of a new span.
// Such overlap is not allowed.
function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) {
  var line = getLine(doc, lineNo$$1);
  var sps = sawCollapsedSpans && line.markedSpans;
  if (sps) { for (var i = 0; i < sps.length; ++i) {
    var sp = sps[i];
    if (!sp.marker.collapsed) { continue }
    var found = sp.marker.find(0);
    var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
    var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
    if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
    if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
        fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
      { return true }
  } }
}

// A visual line is a line as drawn on the screen. Folding, for
// example, can cause multiple logical lines to appear on the same
// visual line. This finds the start of the visual line that the
// given line is part of (usually that is the line itself).
function visualLine(line) {
  var merged;
  while (merged = collapsedSpanAtStart(line))
    { line = merged.find(-1, true).line; }
  return line
}

function visualLineEnd(line) {
  var merged;
  while (merged = collapsedSpanAtEnd(line))
    { line = merged.find(1, true).line; }
  return line
}

// Returns an array of logical lines that continue the visual line
// started by the argument, or undefined if there are no such lines.
function visualLineContinued(line) {
  var merged, lines;
  while (merged = collapsedSpanAtEnd(line)) {
    line = merged.find(1, true).line
    ;(lines || (lines = [])).push(line);
  }
  return lines
}

// Get the line number of the start of the visual line that the
// given line number is part of.
function visualLineNo(doc, lineN) {
  var line = getLine(doc, lineN), vis = visualLine(line);
  if (line == vis) { return lineN }
  return lineNo(vis)
}

// Get the line number of the start of the next visual line after
// the given line.
function visualLineEndNo(doc, lineN) {
  if (lineN > doc.lastLine()) { return lineN }
  var line = getLine(doc, lineN), merged;
  if (!lineIsHidden(doc, line)) { return lineN }
  while (merged = collapsedSpanAtEnd(line))
    { line = merged.find(1, true).line; }
  return lineNo(line) + 1
}

// Compute whether a line is hidden. Lines count as hidden when they
// are part of a visual line that starts with another line, or when
// they are entirely covered by collapsed, non-widget span.
function lineIsHidden(doc, line) {
  var sps = sawCollapsedSpans && line.markedSpans;
  if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
    sp = sps[i];
    if (!sp.marker.collapsed) { continue }
    if (sp.from == null) { return true }
    if (sp.marker.widgetNode) { continue }
    if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
      { return true }
  } }
}
function lineIsHiddenInner(doc, line, span) {
  if (span.to == null) {
    var end = span.marker.find(1, true);
    return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  }
  if (span.marker.inclusiveRight && span.to == line.text.length)
    { return true }
  for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
    sp = line.markedSpans[i];
    if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
        (sp.to == null || sp.to != span.from) &&
        (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
        lineIsHiddenInner(doc, line, sp)) { return true }
  }
}

// Find the height above the given line.
function heightAtLine(lineObj) {
  lineObj = visualLine(lineObj);

  var h = 0, chunk = lineObj.parent;
  for (var i = 0; i < chunk.lines.length; ++i) {
    var line = chunk.lines[i];
    if (line == lineObj) { break }
    else { h += line.height; }
  }
  for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
    for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
      var cur = p.children[i$1];
      if (cur == chunk) { break }
      else { h += cur.height; }
    }
  }
  return h
}

// Compute the character length of a line, taking into account
// collapsed ranges (see markText) that might hide parts, and join
// other lines onto it.
function lineLength(line) {
  if (line.height == 0) { return 0 }
  var len = line.text.length, merged, cur = line;
  while (merged = collapsedSpanAtStart(cur)) {
    var found = merged.find(0, true);
    cur = found.from.line;
    len += found.from.ch - found.to.ch;
  }
  cur = line;
  while (merged = collapsedSpanAtEnd(cur)) {
    var found$1 = merged.find(0, true);
    len -= cur.text.length - found$1.from.ch;
    cur = found$1.to.line;
    len += cur.text.length - found$1.to.ch;
  }
  return len
}

// Find the longest line in the document.
function findMaxLine(cm) {
  var d = cm.display, doc = cm.doc;
  d.maxLine = getLine(doc, doc.first);
  d.maxLineLength = lineLength(d.maxLine);
  d.maxLineChanged = true;
  doc.iter(function (line) {
    var len = lineLength(line);
    if (len > d.maxLineLength) {
      d.maxLineLength = len;
      d.maxLine = line;
    }
  });
}

// BIDI HELPERS

function iterateBidiSections(order, from, to, f) {
  if (!order) { return f(from, to, "ltr", 0) }
  var found = false;
  for (var i = 0; i < order.length; ++i) {
    var part = order[i];
    if (part.from < to && part.to > from || from == to && part.to == from) {
      f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
      found = true;
    }
  }
  if (!found) { f(from, to, "ltr"); }
}

var bidiOther = null;
function getBidiPartAt(order, ch, sticky) {
  var found;
  bidiOther = null;
  for (var i = 0; i < order.length; ++i) {
    var cur = order[i];
    if (cur.from < ch && cur.to > ch) { return i }
    if (cur.to == ch) {
      if (cur.from != cur.to && sticky == "before") { found = i; }
      else { bidiOther = i; }
    }
    if (cur.from == ch) {
      if (cur.from != cur.to && sticky != "before") { found = i; }
      else { bidiOther = i; }
    }
  }
  return found != null ? found : bidiOther
}

// Bidirectional ordering algorithm
// See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
// that this (partially) implements.

// One-char codes used for character types:
// L (L):   Left-to-Right
// R (R):   Right-to-Left
// r (AL):  Right-to-Left Arabic
// 1 (EN):  European Number
// + (ES):  European Number Separator
// % (ET):  European Number Terminator
// n (AN):  Arabic Number
// , (CS):  Common Number Separator
// m (NSM): Non-Spacing Mark
// b (BN):  Boundary Neutral
// s (B):   Paragraph Separator
// t (S):   Segment Separator
// w (WS):  Whitespace
// N (ON):  Other Neutrals

// Returns null if characters are ordered as they appear
// (left-to-right), or an array of sections ({from, to, level}
// objects) in the order in which they occur visually.
var bidiOrdering = (function() {
  // Character types for codepoints 0 to 0xff
  var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  // Character types for codepoints 0x600 to 0x6f9
  var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
  function charType(code) {
    if (code <= 0xf7) { return lowTypes.charAt(code) }
    else if (0x590 <= code && code <= 0x5f4) { return "R" }
    else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
    else if (0x6ee <= code && code <= 0x8ac) { return "r" }
    else if (0x2000 <= code && code <= 0x200b) { return "w" }
    else if (code == 0x200c) { return "b" }
    else { return "L" }
  }

  var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;

  function BidiSpan(level, from, to) {
    this.level = level;
    this.from = from; this.to = to;
  }

  return function(str, direction) {
    var outerType = direction == "ltr" ? "L" : "R";

    if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
    var len = str.length, types = [];
    for (var i = 0; i < len; ++i)
      { types.push(charType(str.charCodeAt(i))); }

    // W1. Examine each non-spacing mark (NSM) in the level run, and
    // change the type of the NSM to the type of the previous
    // character. If the NSM is at the start of the level run, it will
    // get the type of sor.
    for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
      var type = types[i$1];
      if (type == "m") { types[i$1] = prev; }
      else { prev = type; }
    }

    // W2. Search backwards from each instance of a European number
    // until the first strong type (R, L, AL, or sor) is found. If an
    // AL is found, change the type of the European number to Arabic
    // number.
    // W3. Change all ALs to R.
    for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
      var type$1 = types[i$2];
      if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
      else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
    }

    // W4. A single European separator between two European numbers
    // changes to a European number. A single common separator between
    // two numbers of the same type changes to that type.
    for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
      var type$2 = types[i$3];
      if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
      else if (type$2 == "," && prev$1 == types[i$3+1] &&
               (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
      prev$1 = type$2;
    }

    // W5. A sequence of European terminators adjacent to European
    // numbers changes to all European numbers.
    // W6. Otherwise, separators and terminators change to Other
    // Neutral.
    for (var i$4 = 0; i$4 < len; ++i$4) {
      var type$3 = types[i$4];
      if (type$3 == ",") { types[i$4] = "N"; }
      else if (type$3 == "%") {
        var end = (void 0);
        for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
        var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
        for (var j = i$4; j < end; ++j) { types[j] = replace; }
        i$4 = end - 1;
      }
    }

    // W7. Search backwards from each instance of a European number
    // until the first strong type (R, L, or sor) is found. If an L is
    // found, then change the type of the European number to L.
    for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
      var type$4 = types[i$5];
      if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
      else if (isStrong.test(type$4)) { cur$1 = type$4; }
    }

    // N1. A sequence of neutrals takes the direction of the
    // surrounding strong text if the text on both sides has the same
    // direction. European and Arabic numbers act as if they were R in
    // terms of their influence on neutrals. Start-of-level-run (sor)
    // and end-of-level-run (eor) are used at level run boundaries.
    // N2. Any remaining neutrals take the embedding direction.
    for (var i$6 = 0; i$6 < len; ++i$6) {
      if (isNeutral.test(types[i$6])) {
        var end$1 = (void 0);
        for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
        var before = (i$6 ? types[i$6-1] : outerType) == "L";
        var after = (end$1 < len ? types[end$1] : outerType) == "L";
        var replace$1 = before == after ? (before ? "L" : "R") : outerType;
        for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
        i$6 = end$1 - 1;
      }
    }

    // Here we depart from the documented algorithm, in order to avoid
    // building up an actual levels array. Since there are only three
    // levels (0, 1, 2) in an implementation that doesn't take
    // explicit embedding into account, we can build up the order on
    // the fly, without following the level-based algorithm.
    var order = [], m;
    for (var i$7 = 0; i$7 < len;) {
      if (countsAsLeft.test(types[i$7])) {
        var start = i$7;
        for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
        order.push(new BidiSpan(0, start, i$7));
      } else {
        var pos = i$7, at = order.length;
        for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
        for (var j$2 = pos; j$2 < i$7;) {
          if (countsAsNum.test(types[j$2])) {
            if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); }
            var nstart = j$2;
            for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
            order.splice(at, 0, new BidiSpan(2, nstart, j$2));
            pos = j$2;
          } else { ++j$2; }
        }
        if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
      }
    }
    if (direction == "ltr") {
      if (order[0].level == 1 && (m = str.match(/^\s+/))) {
        order[0].from = m[0].length;
        order.unshift(new BidiSpan(0, 0, m[0].length));
      }
      if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
        lst(order).to -= m[0].length;
        order.push(new BidiSpan(0, len - m[0].length, len));
      }
    }

    return direction == "rtl" ? order.reverse() : order
  }
})();

// Get the bidi ordering for the given line (and cache it). Returns
// false for lines that are fully left-to-right, and an array of
// BidiSpan objects otherwise.
function getOrder(line, direction) {
  var order = line.order;
  if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
  return order
}

// EVENT HANDLING

// Lightweight event framework. on/off also work on DOM nodes,
// registering native DOM handlers.

var noHandlers = [];

var on = function(emitter, type, f) {
  if (emitter.addEventListener) {
    emitter.addEventListener(type, f, false);
  } else if (emitter.attachEvent) {
    emitter.attachEvent("on" + type, f);
  } else {
    var map$$1 = emitter._handlers || (emitter._handlers = {});
    map$$1[type] = (map$$1[type] || noHandlers).concat(f);
  }
};

function getHandlers(emitter, type) {
  return emitter._handlers && emitter._handlers[type] || noHandlers
}

function off(emitter, type, f) {
  if (emitter.removeEventListener) {
    emitter.removeEventListener(type, f, false);
  } else if (emitter.detachEvent) {
    emitter.detachEvent("on" + type, f);
  } else {
    var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type];
    if (arr) {
      var index = indexOf(arr, f);
      if (index > -1)
        { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
    }
  }
}

function signal(emitter, type /*, values...*/) {
  var handlers = getHandlers(emitter, type);
  if (!handlers.length) { return }
  var args = Array.prototype.slice.call(arguments, 2);
  for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
}

// The DOM events that CodeMirror handles can be overridden by
// registering a (non-DOM) handler on the editor for the event name,
// and preventDefault-ing the event in that handler.
function signalDOMEvent(cm, e, override) {
  if (typeof e == "string")
    { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
  signal(cm, override || e.type, cm, e);
  return e_defaultPrevented(e) || e.codemirrorIgnore
}

function signalCursorActivity(cm) {
  var arr = cm._handlers && cm._handlers.cursorActivity;
  if (!arr) { return }
  var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
    { set.push(arr[i]); } }
}

function hasHandler(emitter, type) {
  return getHandlers(emitter, type).length > 0
}

// Add on and off methods to a constructor's prototype, to make
// registering events on such objects more convenient.
function eventMixin(ctor) {
  ctor.prototype.on = function(type, f) {on(this, type, f);};
  ctor.prototype.off = function(type, f) {off(this, type, f);};
}

// Due to the fact that we still support jurassic IE versions, some
// compatibility wrappers are needed.

function e_preventDefault(e) {
  if (e.preventDefault) { e.preventDefault(); }
  else { e.returnValue = false; }
}
function e_stopPropagation(e) {
  if (e.stopPropagation) { e.stopPropagation(); }
  else { e.cancelBubble = true; }
}
function e_defaultPrevented(e) {
  return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
}
function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}

function e_target(e) {return e.target || e.srcElement}
function e_button(e) {
  var b = e.which;
  if (b == null) {
    if (e.button & 1) { b = 1; }
    else if (e.button & 2) { b = 3; }
    else if (e.button & 4) { b = 2; }
  }
  if (mac && e.ctrlKey && b == 1) { b = 3; }
  return b
}

// Detect drag-and-drop
var dragAndDrop = function() {
  // There is *some* kind of drag-and-drop support in IE6-8, but I
  // couldn't get it to work yet.
  if (ie && ie_version < 9) { return false }
  var div = elt('div');
  return "draggable" in div || "dragDrop" in div
}();

var zwspSupported;
function zeroWidthElement(measure) {
  if (zwspSupported == null) {
    var test = elt("span", "\u200b");
    removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
    if (measure.firstChild.offsetHeight != 0)
      { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
  }
  var node = zwspSupported ? elt("span", "\u200b") :
    elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  node.setAttribute("cm-text", "");
  return node
}

// Feature-detect IE's crummy client rect reporting for bidi text
var badBidiRects;
function hasBadBidiRects(measure) {
  if (badBidiRects != null) { return badBidiRects }
  var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  var r0 = range(txt, 0, 1).getBoundingClientRect();
  var r1 = range(txt, 1, 2).getBoundingClientRect();
  removeChildren(measure);
  if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  return badBidiRects = (r1.right - r0.right < 3)
}

// See if "".split is the broken IE version, if so, provide an
// alternative way to split lines.
var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  var pos = 0, result = [], l = string.length;
  while (pos <= l) {
    var nl = string.indexOf("\n", pos);
    if (nl == -1) { nl = string.length; }
    var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
    var rt = line.indexOf("\r");
    if (rt != -1) {
      result.push(line.slice(0, rt));
      pos += rt + 1;
    } else {
      result.push(line);
      pos = nl + 1;
    }
  }
  return result
} : function (string) { return string.split(/\r\n?|\n/); };

var hasSelection = window.getSelection ? function (te) {
  try { return te.selectionStart != te.selectionEnd }
  catch(e) { return false }
} : function (te) {
  var range$$1;
  try {range$$1 = te.ownerDocument.selection.createRange();}
  catch(e) {}
  if (!range$$1 || range$$1.parentElement() != te) { return false }
  return range$$1.compareEndPoints("StartToEnd", range$$1) != 0
};

var hasCopyEvent = (function () {
  var e = elt("div");
  if ("oncopy" in e) { return true }
  e.setAttribute("oncopy", "return;");
  return typeof e.oncopy == "function"
})();

var badZoomedRects = null;
function hasBadZoomedRects(measure) {
  if (badZoomedRects != null) { return badZoomedRects }
  var node = removeChildrenAndAdd(measure, elt("span", "x"));
  var normal = node.getBoundingClientRect();
  var fromRange = range(node, 0, 1).getBoundingClientRect();
  return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
}

// Known modes, by name and by MIME
var modes = {};
var mimeModes = {};

// Extra arguments are stored as the mode's dependencies, which is
// used by (legacy) mechanisms like loadmode.js to automatically
// load a mode. (Preferred mechanism is the require/define calls.)
function defineMode(name, mode) {
  if (arguments.length > 2)
    { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
  modes[name] = mode;
}

function defineMIME(mime, spec) {
  mimeModes[mime] = spec;
}

// Given a MIME type, a {name, ...options} config object, or a name
// string, return a mode config object.
function resolveMode(spec) {
  if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
    spec = mimeModes[spec];
  } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
    var found = mimeModes[spec.name];
    if (typeof found == "string") { found = {name: found}; }
    spec = createObj(found, spec);
    spec.name = found.name;
  } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
    return resolveMode("application/xml")
  } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
    return resolveMode("application/json")
  }
  if (typeof spec == "string") { return {name: spec} }
  else { return spec || {name: "null"} }
}

// Given a mode spec (anything that resolveMode accepts), find and
// initialize an actual mode object.
function getMode(options, spec) {
  spec = resolveMode(spec);
  var mfactory = modes[spec.name];
  if (!mfactory) { return getMode(options, "text/plain") }
  var modeObj = mfactory(options, spec);
  if (modeExtensions.hasOwnProperty(spec.name)) {
    var exts = modeExtensions[spec.name];
    for (var prop in exts) {
      if (!exts.hasOwnProperty(prop)) { continue }
      if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
      modeObj[prop] = exts[prop];
    }
  }
  modeObj.name = spec.name;
  if (spec.helperType) { modeObj.helperType = spec.helperType; }
  if (spec.modeProps) { for (var prop$1 in spec.modeProps)
    { modeObj[prop$1] = spec.modeProps[prop$1]; } }

  return modeObj
}

// This can be used to attach properties to mode objects from
// outside the actual mode definition.
var modeExtensions = {};
function extendMode(mode, properties) {
  var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  copyObj(properties, exts);
}

function copyState(mode, state) {
  if (state === true) { return state }
  if (mode.copyState) { return mode.copyState(state) }
  var nstate = {};
  for (var n in state) {
    var val = state[n];
    if (val instanceof Array) { val = val.concat([]); }
    nstate[n] = val;
  }
  return nstate
}

// Given a mode and a state (for that mode), find the inner mode and
// state at the position that the state refers to.
function innerMode(mode, state) {
  var info;
  while (mode.innerMode) {
    info = mode.innerMode(state);
    if (!info || info.mode == mode) { break }
    state = info.state;
    mode = info.mode;
  }
  return info || {mode: mode, state: state}
}

function startState(mode, a1, a2) {
  return mode.startState ? mode.startState(a1, a2) : true
}

// STRING STREAM

// Fed to the mode parsers, provides helper functions to make
// parsers more succinct.

var StringStream = function(string, tabSize, lineOracle) {
  this.pos = this.start = 0;
  this.string = string;
  this.tabSize = tabSize || 8;
  this.lastColumnPos = this.lastColumnValue = 0;
  this.lineStart = 0;
  this.lineOracle = lineOracle;
};

StringStream.prototype.eol = function () {return this.pos >= this.string.length};
StringStream.prototype.sol = function () {return this.pos == this.lineStart};
StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
StringStream.prototype.next = function () {
  if (this.pos < this.string.length)
    { return this.string.charAt(this.pos++) }
};
StringStream.prototype.eat = function (match) {
  var ch = this.string.charAt(this.pos);
  var ok;
  if (typeof match == "string") { ok = ch == match; }
  else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
  if (ok) {++this.pos; return ch}
};
StringStream.prototype.eatWhile = function (match) {
  var start = this.pos;
  while (this.eat(match)){}
  return this.pos > start
};
StringStream.prototype.eatSpace = function () {
    var this$1 = this;

  var start = this.pos;
  while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; }
  return this.pos > start
};
StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
StringStream.prototype.skipTo = function (ch) {
  var found = this.string.indexOf(ch, this.pos);
  if (found > -1) {this.pos = found; return true}
};
StringStream.prototype.backUp = function (n) {this.pos -= n;};
StringStream.prototype.column = function () {
  if (this.lastColumnPos < this.start) {
    this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
    this.lastColumnPos = this.start;
  }
  return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
};
StringStream.prototype.indentation = function () {
  return countColumn(this.string, null, this.tabSize) -
    (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
};
StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  if (typeof pattern == "string") {
    var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
    var substr = this.string.substr(this.pos, pattern.length);
    if (cased(substr) == cased(pattern)) {
      if (consume !== false) { this.pos += pattern.length; }
      return true
    }
  } else {
    var match = this.string.slice(this.pos).match(pattern);
    if (match && match.index > 0) { return null }
    if (match && consume !== false) { this.pos += match[0].length; }
    return match
  }
};
StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
StringStream.prototype.hideFirstChars = function (n, inner) {
  this.lineStart += n;
  try { return inner() }
  finally { this.lineStart -= n; }
};
StringStream.prototype.lookAhead = function (n) {
  var oracle = this.lineOracle;
  return oracle && oracle.lookAhead(n)
};
StringStream.prototype.baseToken = function () {
  var oracle = this.lineOracle;
  return oracle && oracle.baseToken(this.pos)
};

var SavedContext = function(state, lookAhead) {
  this.state = state;
  this.lookAhead = lookAhead;
};

var Context = function(doc, state, line, lookAhead) {
  this.state = state;
  this.doc = doc;
  this.line = line;
  this.maxLookAhead = lookAhead || 0;
  this.baseTokens = null;
  this.baseTokenPos = 1;
};

Context.prototype.lookAhead = function (n) {
  var line = this.doc.getLine(this.line + n);
  if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
  return line
};

Context.prototype.baseToken = function (n) {
    var this$1 = this;

  if (!this.baseTokens) { return null }
  while (this.baseTokens[this.baseTokenPos] <= n)
    { this$1.baseTokenPos += 2; }
  var type = this.baseTokens[this.baseTokenPos + 1];
  return {type: type && type.replace(/( |^)overlay .*/, ""),
          size: this.baseTokens[this.baseTokenPos] - n}
};

Context.prototype.nextLine = function () {
  this.line++;
  if (this.maxLookAhead > 0) { this.maxLookAhead--; }
};

Context.fromSaved = function (doc, saved, line) {
  if (saved instanceof SavedContext)
    { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
  else
    { return new Context(doc, copyState(doc.mode, saved), line) }
};

Context.prototype.save = function (copy) {
  var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
  return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
};


// Compute a style array (an array starting with a mode generation
// -- for invalidation -- followed by pairs of end positions and
// style strings), which is used to highlight the tokens on the
// line.
function highlightLine(cm, line, context, forceToEnd) {
  // A styles array always starts with a number identifying the
  // mode/overlays that it is based on (for easy invalidation).
  var st = [cm.state.modeGen], lineClasses = {};
  // Compute the base array of styles
  runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
          lineClasses, forceToEnd);
  var state = context.state;

  // Run overlays, adjust style array.
  var loop = function ( o ) {
    context.baseTokens = st;
    var overlay = cm.state.overlays[o], i = 1, at = 0;
    context.state = true;
    runMode(cm, line.text, overlay.mode, context, function (end, style) {
      var start = i;
      // Ensure there's a token end at the current position, and that i points at it
      while (at < end) {
        var i_end = st[i];
        if (i_end > end)
          { st.splice(i, 1, end, st[i+1], i_end); }
        i += 2;
        at = Math.min(end, i_end);
      }
      if (!style) { return }
      if (overlay.opaque) {
        st.splice(start, i - start, end, "overlay " + style);
        i = start + 2;
      } else {
        for (; start < i; start += 2) {
          var cur = st[start+1];
          st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
        }
      }
    }, lineClasses);
    context.state = state;
    context.baseTokens = null;
    context.baseTokenPos = 1;
  };

  for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );

  return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
}

function getLineStyles(cm, line, updateFrontier) {
  if (!line.styles || line.styles[0] != cm.state.modeGen) {
    var context = getContextBefore(cm, lineNo(line));
    var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
    var result = highlightLine(cm, line, context);
    if (resetState) { context.state = resetState; }
    line.stateAfter = context.save(!resetState);
    line.styles = result.styles;
    if (result.classes) { line.styleClasses = result.classes; }
    else if (line.styleClasses) { line.styleClasses = null; }
    if (updateFrontier === cm.doc.highlightFrontier)
      { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
  }
  return line.styles
}

function getContextBefore(cm, n, precise) {
  var doc = cm.doc, display = cm.display;
  if (!doc.mode.startState) { return new Context(doc, true, n) }
  var start = findStartLine(cm, n, precise);
  var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
  var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);

  doc.iter(start, n, function (line) {
    processLine(cm, line.text, context);
    var pos = context.line;
    line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
    context.nextLine();
  });
  if (precise) { doc.modeFrontier = context.line; }
  return context
}

// Lightweight form of highlight -- proceed over this line and
// update state, but don't save a style array. Used for lines that
// aren't currently visible.
function processLine(cm, text, context, startAt) {
  var mode = cm.doc.mode;
  var stream = new StringStream(text, cm.options.tabSize, context);
  stream.start = stream.pos = startAt || 0;
  if (text == "") { callBlankLine(mode, context.state); }
  while (!stream.eol()) {
    readToken(mode, stream, context.state);
    stream.start = stream.pos;
  }
}

function callBlankLine(mode, state) {
  if (mode.blankLine) { return mode.blankLine(state) }
  if (!mode.innerMode) { return }
  var inner = innerMode(mode, state);
  if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
}

function readToken(mode, stream, state, inner) {
  for (var i = 0; i < 10; i++) {
    if (inner) { inner[0] = innerMode(mode, state).mode; }
    var style = mode.token(stream, state);
    if (stream.pos > stream.start) { return style }
  }
  throw new Error("Mode " + mode.name + " failed to advance stream.")
}

var Token = function(stream, type, state) {
  this.start = stream.start; this.end = stream.pos;
  this.string = stream.current();
  this.type = type || null;
  this.state = state;
};

// Utility for getTokenAt and getLineTokens
function takeToken(cm, pos, precise, asArray) {
  var doc = cm.doc, mode = doc.mode, style;
  pos = clipPos(doc, pos);
  var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
  var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
  if (asArray) { tokens = []; }
  while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
    stream.start = stream.pos;
    style = readToken(mode, stream, context.state);
    if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
  }
  return asArray ? tokens : new Token(stream, style, context.state)
}

function extractLineClasses(type, output) {
  if (type) { for (;;) {
    var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
    if (!lineClass) { break }
    type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
    var prop = lineClass[1] ? "bgClass" : "textClass";
    if (output[prop] == null)
      { output[prop] = lineClass[2]; }
    else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
      { output[prop] += " " + lineClass[2]; }
  } }
  return type
}

// Run the given mode's parser over a line, calling f for each token.
function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  var flattenSpans = mode.flattenSpans;
  if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
  var curStart = 0, curStyle = null;
  var stream = new StringStream(text, cm.options.tabSize, context), style;
  var inner = cm.options.addModeClass && [null];
  if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
  while (!stream.eol()) {
    if (stream.pos > cm.options.maxHighlightLength) {
      flattenSpans = false;
      if (forceToEnd) { processLine(cm, text, context, stream.pos); }
      stream.pos = text.length;
      style = null;
    } else {
      style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
    }
    if (inner) {
      var mName = inner[0].name;
      if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
    }
    if (!flattenSpans || curStyle != style) {
      while (curStart < stream.start) {
        curStart = Math.min(stream.start, curStart + 5000);
        f(curStart, curStyle);
      }
      curStyle = style;
    }
    stream.start = stream.pos;
  }
  while (curStart < stream.pos) {
    // Webkit seems to refuse to render text nodes longer than 57444
    // characters, and returns inaccurate measurements in nodes
    // starting around 5000 chars.
    var pos = Math.min(stream.pos, curStart + 5000);
    f(pos, curStyle);
    curStart = pos;
  }
}

// Finds the line to start with when starting a parse. Tries to
// find a line with a stateAfter, so that it can start with a
// valid state. If that fails, it returns the line with the
// smallest indentation, which tends to need the least context to
// parse correctly.
function findStartLine(cm, n, precise) {
  var minindent, minline, doc = cm.doc;
  var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  for (var search = n; search > lim; --search) {
    if (search <= doc.first) { return doc.first }
    var line = getLine(doc, search - 1), after = line.stateAfter;
    if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
      { return search }
    var indented = countColumn(line.text, null, cm.options.tabSize);
    if (minline == null || minindent > indented) {
      minline = search - 1;
      minindent = indented;
    }
  }
  return minline
}

function retreatFrontier(doc, n) {
  doc.modeFrontier = Math.min(doc.modeFrontier, n);
  if (doc.highlightFrontier < n - 10) { return }
  var start = doc.first;
  for (var line = n - 1; line > start; line--) {
    var saved = getLine(doc, line).stateAfter;
    // change is on 3
    // state on line 1 looked ahead 2 -- so saw 3
    // test 1 + 2 < 3 should cover this
    if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
      start = line + 1;
      break
    }
  }
  doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
}

// LINE DATA STRUCTURE

// Line objects. These hold state related to a line, including
// highlighting info (the styles array).
var Line = function(text, markedSpans, estimateHeight) {
  this.text = text;
  attachMarkedSpans(this, markedSpans);
  this.height = estimateHeight ? estimateHeight(this) : 1;
};

Line.prototype.lineNo = function () { return lineNo(this) };
eventMixin(Line);

// Change the content (text, markers) of a line. Automatically
// invalidates cached information and tries to re-estimate the
// line's height.
function updateLine(line, text, markedSpans, estimateHeight) {
  line.text = text;
  if (line.stateAfter) { line.stateAfter = null; }
  if (line.styles) { line.styles = null; }
  if (line.order != null) { line.order = null; }
  detachMarkedSpans(line);
  attachMarkedSpans(line, markedSpans);
  var estHeight = estimateHeight ? estimateHeight(line) : 1;
  if (estHeight != line.height) { updateLineHeight(line, estHeight); }
}

// Detach a line from the document tree and its markers.
function cleanUpLine(line) {
  line.parent = null;
  detachMarkedSpans(line);
}

// Convert a style as returned by a mode (either null, or a string
// containing one or more styles) to a CSS style. This is cached,
// and also looks for line-wide styles.
var styleToClassCache = {};
var styleToClassCacheWithMode = {};
function interpretTokenStyle(style, options) {
  if (!style || /^\s*$/.test(style)) { return null }
  var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  return cache[style] ||
    (cache[style] = style.replace(/\S+/g, "cm-$&"))
}

// Render the DOM representation of the text of a line. Also builds
// up a 'line map', which points at the DOM nodes that represent
// specific stretches of text, and is used by the measuring code.
// The returned object contains the DOM node, this map, and
// information about line-wide styles that were set by the mode.
function buildLineContent(cm, lineView) {
  // The padding-right forces the element to have a 'border', which
  // is needed on Webkit to be able to get line-level bounding
  // rectangles for it (in measureChar).
  var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
  var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
                 col: 0, pos: 0, cm: cm,
                 trailingSpace: false,
                 splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
  lineView.measure = {};

  // Iterate over the logical lines that make up this visual line.
  for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
    var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
    builder.pos = 0;
    builder.addToken = buildToken;
    // Optionally wire in some hacks into the token-rendering
    // algorithm, to deal with browser quirks.
    if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
      { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
    builder.map = [];
    var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
    insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
    if (line.styleClasses) {
      if (line.styleClasses.bgClass)
        { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
      if (line.styleClasses.textClass)
        { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
    }

    // Ensure at least a single node is present, for measuring.
    if (builder.map.length == 0)
      { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }

    // Store the map and a cache object for the current logical line
    if (i == 0) {
      lineView.measure.map = builder.map;
      lineView.measure.cache = {};
    } else {
      (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
      ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
    }
  }

  // See issue #2901
  if (webkit) {
    var last = builder.content.lastChild;
    if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
      { builder.content.className = "cm-tab-wrap-hack"; }
  }

  signal(cm, "renderLine", cm, lineView.line, builder.pre);
  if (builder.pre.className)
    { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }

  return builder
}

function defaultSpecialCharPlaceholder(ch) {
  var token = elt("span", "\u2022", "cm-invalidchar");
  token.title = "\\u" + ch.charCodeAt(0).toString(16);
  token.setAttribute("aria-label", token.title);
  return token
}

// Build up the DOM representation for a single token, and add it to
// the line map. Takes care to render special characters separately.
function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  if (!text) { return }
  var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
  var special = builder.cm.state.specialChars, mustWrap = false;
  var content;
  if (!special.test(text)) {
    builder.col += text.length;
    content = document.createTextNode(displayText);
    builder.map.push(builder.pos, builder.pos + text.length, content);
    if (ie && ie_version < 9) { mustWrap = true; }
    builder.pos += text.length;
  } else {
    content = document.createDocumentFragment();
    var pos = 0;
    while (true) {
      special.lastIndex = pos;
      var m = special.exec(text);
      var skipped = m ? m.index - pos : text.length - pos;
      if (skipped) {
        var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
        if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
        else { content.appendChild(txt); }
        builder.map.push(builder.pos, builder.pos + skipped, txt);
        builder.col += skipped;
        builder.pos += skipped;
      }
      if (!m) { break }
      pos += skipped + 1;
      var txt$1 = (void 0);
      if (m[0] == "\t") {
        var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
        txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
        txt$1.setAttribute("role", "presentation");
        txt$1.setAttribute("cm-text", "\t");
        builder.col += tabWidth;
      } else if (m[0] == "\r" || m[0] == "\n") {
        txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
        txt$1.setAttribute("cm-text", m[0]);
        builder.col += 1;
      } else {
        txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
        txt$1.setAttribute("cm-text", m[0]);
        if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
        else { content.appendChild(txt$1); }
        builder.col += 1;
      }
      builder.map.push(builder.pos, builder.pos + 1, txt$1);
      builder.pos++;
    }
  }
  builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
  if (style || startStyle || endStyle || mustWrap || css) {
    var fullStyle = style || "";
    if (startStyle) { fullStyle += startStyle; }
    if (endStyle) { fullStyle += endStyle; }
    var token = elt("span", [content], fullStyle, css);
    if (title) { token.title = title; }
    return builder.content.appendChild(token)
  }
  builder.content.appendChild(content);
}

function splitSpaces(text, trailingBefore) {
  if (text.length > 1 && !/  /.test(text)) { return text }
  var spaceBefore = trailingBefore, result = "";
  for (var i = 0; i < text.length; i++) {
    var ch = text.charAt(i);
    if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
      { ch = "\u00a0"; }
    result += ch;
    spaceBefore = ch == " ";
  }
  return result
}

// Work around nonsense dimensions being reported for stretches of
// right-to-left text.
function buildTokenBadBidi(inner, order) {
  return function (builder, text, style, startStyle, endStyle, title, css) {
    style = style ? style + " cm-force-border" : "cm-force-border";
    var start = builder.pos, end = start + text.length;
    for (;;) {
      // Find the part that overlaps with the start of this text
      var part = (void 0);
      for (var i = 0; i < order.length; i++) {
        part = order[i];
        if (part.to > start && part.from <= start) { break }
      }
      if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) }
      inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
      startStyle = null;
      text = text.slice(part.to - start);
      start = part.to;
    }
  }
}

function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  var widget = !ignoreWidget && marker.widgetNode;
  if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
  if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
    if (!widget)
      { widget = builder.content.appendChild(document.createElement("span")); }
    widget.setAttribute("cm-marker", marker.id);
  }
  if (widget) {
    builder.cm.display.input.setUneditable(widget);
    builder.content.appendChild(widget);
  }
  builder.pos += size;
  builder.trailingSpace = false;
}

// Outputs a number of spans to make up a line, taking highlighting
// and marked text into account.
function insertLineContent(line, builder, styles) {
  var spans = line.markedSpans, allText = line.text, at = 0;
  if (!spans) {
    for (var i$1 = 1; i$1 < styles.length; i$1+=2)
      { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
    return
  }

  var len = allText.length, pos = 0, i = 1, text = "", style, css;
  var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
  for (;;) {
    if (nextChange == pos) { // Update current marker set
      spanStyle = spanEndStyle = spanStartStyle = title = css = "";
      collapsed = null; nextChange = Infinity;
      var foundBookmarks = [], endStyles = (void 0);
      for (var j = 0; j < spans.length; ++j) {
        var sp = spans[j], m = sp.marker;
        if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
          foundBookmarks.push(m);
        } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
          if (sp.to != null && sp.to != pos && nextChange > sp.to) {
            nextChange = sp.to;
            spanEndStyle = "";
          }
          if (m.className) { spanStyle += " " + m.className; }
          if (m.css) { css = (css ? css + ";" : "") + m.css; }
          if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
          if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
          if (m.title && !title) { title = m.title; }
          if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
            { collapsed = sp; }
        } else if (sp.from > pos && nextChange > sp.from) {
          nextChange = sp.from;
        }
      }
      if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
        { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }

      if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
        { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
      if (collapsed && (collapsed.from || 0) == pos) {
        buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
                           collapsed.marker, collapsed.from == null);
        if (collapsed.to == null) { return }
        if (collapsed.to == pos) { collapsed = false; }
      }
    }
    if (pos >= len) { break }

    var upto = Math.min(len, nextChange);
    while (true) {
      if (text) {
        var end = pos + text.length;
        if (!collapsed) {
          var tokenText = end > upto ? text.slice(0, upto - pos) : text;
          builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
                           spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
        }
        if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
        pos = end;
        spanStartStyle = "";
      }
      text = allText.slice(at, at = styles[i++]);
      style = interpretTokenStyle(styles[i++], builder.cm.options);
    }
  }
}


// These objects are used to represent the visible (currently drawn)
// part of the document. A LineView may correspond to multiple
// logical lines, if those are connected by collapsed ranges.
function LineView(doc, line, lineN) {
  // The starting line
  this.line = line;
  // Continuing lines, if any
  this.rest = visualLineContinued(line);
  // Number of logical lines in this visual line
  this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  this.node = this.text = null;
  this.hidden = lineIsHidden(doc, line);
}

// Create a range of LineView objects for the given lines.
function buildViewArray(cm, from, to) {
  var array = [], nextPos;
  for (var pos = from; pos < to; pos = nextPos) {
    var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
    nextPos = pos + view.size;
    array.push(view);
  }
  return array
}

var operationGroup = null;

function pushOperation(op) {
  if (operationGroup) {
    operationGroup.ops.push(op);
  } else {
    op.ownsGroup = operationGroup = {
      ops: [op],
      delayedCallbacks: []
    };
  }
}

function fireCallbacksForOps(group) {
  // Calls delayed callbacks and cursorActivity handlers until no
  // new ones appear
  var callbacks = group.delayedCallbacks, i = 0;
  do {
    for (; i < callbacks.length; i++)
      { callbacks[i].call(null); }
    for (var j = 0; j < group.ops.length; j++) {
      var op = group.ops[j];
      if (op.cursorActivityHandlers)
        { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
          { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
    }
  } while (i < callbacks.length)
}

function finishOperation(op, endCb) {
  var group = op.ownsGroup;
  if (!group) { return }

  try { fireCallbacksForOps(group); }
  finally {
    operationGroup = null;
    endCb(group);
  }
}

var orphanDelayedCallbacks = null;

// Often, we want to signal events at a point where we are in the
// middle of some work, but don't want the handler to start calling
// other methods on the editor, which might be in an inconsistent
// state or simply not expect any other events to happen.
// signalLater looks whether there are any handlers, and schedules
// them to be executed when the last operation ends, or, if no
// operation is active, when a timeout fires.
function signalLater(emitter, type /*, values...*/) {
  var arr = getHandlers(emitter, type);
  if (!arr.length) { return }
  var args = Array.prototype.slice.call(arguments, 2), list;
  if (operationGroup) {
    list = operationGroup.delayedCallbacks;
  } else if (orphanDelayedCallbacks) {
    list = orphanDelayedCallbacks;
  } else {
    list = orphanDelayedCallbacks = [];
    setTimeout(fireOrphanDelayed, 0);
  }
  var loop = function ( i ) {
    list.push(function () { return arr[i].apply(null, args); });
  };

  for (var i = 0; i < arr.length; ++i)
    loop( i );
}

function fireOrphanDelayed() {
  var delayed = orphanDelayedCallbacks;
  orphanDelayedCallbacks = null;
  for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
}

// When an aspect of a line changes, a string is added to
// lineView.changes. This updates the relevant part of the line's
// DOM structure.
function updateLineForChanges(cm, lineView, lineN, dims) {
  for (var j = 0; j < lineView.changes.length; j++) {
    var type = lineView.changes[j];
    if (type == "text") { updateLineText(cm, lineView); }
    else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
    else if (type == "class") { updateLineClasses(cm, lineView); }
    else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
  }
  lineView.changes = null;
}

// Lines with gutter elements, widgets or a background class need to
// be wrapped, and have the extra elements added to the wrapper div
function ensureLineWrapped(lineView) {
  if (lineView.node == lineView.text) {
    lineView.node = elt("div", null, null, "position: relative");
    if (lineView.text.parentNode)
      { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
    lineView.node.appendChild(lineView.text);
    if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
  }
  return lineView.node
}

function updateLineBackground(cm, lineView) {
  var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  if (cls) { cls += " CodeMirror-linebackground"; }
  if (lineView.background) {
    if (cls) { lineView.background.className = cls; }
    else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  } else if (cls) {
    var wrap = ensureLineWrapped(lineView);
    lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
    cm.display.input.setUneditable(lineView.background);
  }
}

// Wrapper around buildLineContent which will reuse the structure
// in display.externalMeasured when possible.
function getLineContent(cm, lineView) {
  var ext = cm.display.externalMeasured;
  if (ext && ext.line == lineView.line) {
    cm.display.externalMeasured = null;
    lineView.measure = ext.measure;
    return ext.built
  }
  return buildLineContent(cm, lineView)
}

// Redraw the line's text. Interacts with the background and text
// classes because the mode may output tokens that influence these
// classes.
function updateLineText(cm, lineView) {
  var cls = lineView.text.className;
  var built = getLineContent(cm, lineView);
  if (lineView.text == lineView.node) { lineView.node = built.pre; }
  lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  lineView.text = built.pre;
  if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
    lineView.bgClass = built.bgClass;
    lineView.textClass = built.textClass;
    updateLineClasses(cm, lineView);
  } else if (cls) {
    lineView.text.className = cls;
  }
}

function updateLineClasses(cm, lineView) {
  updateLineBackground(cm, lineView);
  if (lineView.line.wrapClass)
    { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
  else if (lineView.node != lineView.text)
    { lineView.node.className = ""; }
  var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  lineView.text.className = textClass || "";
}

function updateLineGutter(cm, lineView, lineN, dims) {
  if (lineView.gutter) {
    lineView.node.removeChild(lineView.gutter);
    lineView.gutter = null;
  }
  if (lineView.gutterBackground) {
    lineView.node.removeChild(lineView.gutterBackground);
    lineView.gutterBackground = null;
  }
  if (lineView.line.gutterClass) {
    var wrap = ensureLineWrapped(lineView);
    lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
                                    ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
    cm.display.input.setUneditable(lineView.gutterBackground);
    wrap.insertBefore(lineView.gutterBackground, lineView.text);
  }
  var markers = lineView.line.gutterMarkers;
  if (cm.options.lineNumbers || markers) {
    var wrap$1 = ensureLineWrapped(lineView);
    var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
    cm.display.input.setUneditable(gutterWrap);
    wrap$1.insertBefore(gutterWrap, lineView.text);
    if (lineView.line.gutterClass)
      { gutterWrap.className += " " + lineView.line.gutterClass; }
    if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
      { lineView.lineNumber = gutterWrap.appendChild(
        elt("div", lineNumberFor(cm.options, lineN),
            "CodeMirror-linenumber CodeMirror-gutter-elt",
            ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
    if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) {
      var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
      if (found)
        { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
                                   ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
    } }
  }
}

function updateLineWidgets(cm, lineView, dims) {
  if (lineView.alignable) { lineView.alignable = null; }
  for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
    next = node.nextSibling;
    if (node.className == "CodeMirror-linewidget")
      { lineView.node.removeChild(node); }
  }
  insertLineWidgets(cm, lineView, dims);
}

// Build a line's DOM representation from scratch
function buildLineElement(cm, lineView, lineN, dims) {
  var built = getLineContent(cm, lineView);
  lineView.text = lineView.node = built.pre;
  if (built.bgClass) { lineView.bgClass = built.bgClass; }
  if (built.textClass) { lineView.textClass = built.textClass; }

  updateLineClasses(cm, lineView);
  updateLineGutter(cm, lineView, lineN, dims);
  insertLineWidgets(cm, lineView, dims);
  return lineView.node
}

// A lineView may contain multiple logical lines (when merged by
// collapsed spans). The widgets for all of them need to be drawn.
function insertLineWidgets(cm, lineView, dims) {
  insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
    { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
}

function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  if (!line.widgets) { return }
  var wrap = ensureLineWrapped(lineView);
  for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
    var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
    if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
    positionLineWidget(widget, node, lineView, dims);
    cm.display.input.setUneditable(node);
    if (allowAbove && widget.above)
      { wrap.insertBefore(node, lineView.gutter || lineView.text); }
    else
      { wrap.appendChild(node); }
    signalLater(widget, "redraw");
  }
}

function positionLineWidget(widget, node, lineView, dims) {
  if (widget.noHScroll) {
    (lineView.alignable || (lineView.alignable = [])).push(node);
    var width = dims.wrapperWidth;
    node.style.left = dims.fixedPos + "px";
    if (!widget.coverGutter) {
      width -= dims.gutterTotalWidth;
      node.style.paddingLeft = dims.gutterTotalWidth + "px";
    }
    node.style.width = width + "px";
  }
  if (widget.coverGutter) {
    node.style.zIndex = 5;
    node.style.position = "relative";
    if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
  }
}

function widgetHeight(widget) {
  if (widget.height != null) { return widget.height }
  var cm = widget.doc.cm;
  if (!cm) { return 0 }
  if (!contains(document.body, widget.node)) {
    var parentStyle = "position: relative;";
    if (widget.coverGutter)
      { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
    if (widget.noHScroll)
      { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
    removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  }
  return widget.height = widget.node.parentNode.offsetHeight
}

// Return true when the given mouse event happened in a widget
function eventInWidget(display, e) {
  for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
    if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
        (n.parentNode == display.sizer && n != display.mover))
      { return true }
  }
}

// POSITION MEASUREMENT

function paddingTop(display) {return display.lineSpace.offsetTop}
function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
function paddingH(display) {
  if (display.cachedPaddingH) { return display.cachedPaddingH }
  var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
  var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
  return data
}

function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
function displayWidth(cm) {
  return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
}
function displayHeight(cm) {
  return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
}

// Ensure the lineView.wrapping.heights array is populated. This is
// an array of bottom offsets for the lines that make up a drawn
// line. When lineWrapping is on, there might be more than one
// height.
function ensureLineHeights(cm, lineView, rect) {
  var wrapping = cm.options.lineWrapping;
  var curWidth = wrapping && displayWidth(cm);
  if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
    var heights = lineView.measure.heights = [];
    if (wrapping) {
      lineView.measure.width = curWidth;
      var rects = lineView.text.firstChild.getClientRects();
      for (var i = 0; i < rects.length - 1; i++) {
        var cur = rects[i], next = rects[i + 1];
        if (Math.abs(cur.bottom - next.bottom) > 2)
          { heights.push((cur.bottom + next.top) / 2 - rect.top); }
      }
    }
    heights.push(rect.bottom - rect.top);
  }
}

// Find a line map (mapping character offsets to text nodes) and a
// measurement cache for the given line number. (A line view might
// contain multiple lines when collapsed ranges are present.)
function mapFromLineView(lineView, line, lineN) {
  if (lineView.line == line)
    { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  for (var i = 0; i < lineView.rest.length; i++)
    { if (lineView.rest[i] == line)
      { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
    { if (lineNo(lineView.rest[i$1]) > lineN)
      { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
}

// Render a line into the hidden node display.externalMeasured. Used
// when measurement is needed for a line that's not in the viewport.
function updateExternalMeasurement(cm, line) {
  line = visualLine(line);
  var lineN = lineNo(line);
  var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  view.lineN = lineN;
  var built = view.built = buildLineContent(cm, view);
  view.text = built.pre;
  removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  return view
}

// Get a {top, bottom, left, right} box (in line-local coordinates)
// for a given character.
function measureChar(cm, line, ch, bias) {
  return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
}

// Find a line view that corresponds to the given line number.
function findViewForLine(cm, lineN) {
  if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
    { return cm.display.view[findViewIndex(cm, lineN)] }
  var ext = cm.display.externalMeasured;
  if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
    { return ext }
}

// Measurement can be split in two steps, the set-up work that
// applies to the whole line, and the measurement of the actual
// character. Functions like coordsChar, that need to do a lot of
// measurements in a row, can thus ensure that the set-up work is
// only done once.
function prepareMeasureForLine(cm, line) {
  var lineN = lineNo(line);
  var view = findViewForLine(cm, lineN);
  if (view && !view.text) {
    view = null;
  } else if (view && view.changes) {
    updateLineForChanges(cm, view, lineN, getDimensions(cm));
    cm.curOp.forceUpdate = true;
  }
  if (!view)
    { view = updateExternalMeasurement(cm, line); }

  var info = mapFromLineView(view, line, lineN);
  return {
    line: line, view: view, rect: null,
    map: info.map, cache: info.cache, before: info.before,
    hasHeights: false
  }
}

// Given a prepared measurement object, measures the position of an
// actual character (or fetches it from the cache).
function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  if (prepared.before) { ch = -1; }
  var key = ch + (bias || ""), found;
  if (prepared.cache.hasOwnProperty(key)) {
    found = prepared.cache[key];
  } else {
    if (!prepared.rect)
      { prepared.rect = prepared.view.text.getBoundingClientRect(); }
    if (!prepared.hasHeights) {
      ensureLineHeights(cm, prepared.view, prepared.rect);
      prepared.hasHeights = true;
    }
    found = measureCharInner(cm, prepared, ch, bias);
    if (!found.bogus) { prepared.cache[key] = found; }
  }
  return {left: found.left, right: found.right,
          top: varHeight ? found.rtop : found.top,
          bottom: varHeight ? found.rbottom : found.bottom}
}

var nullRect = {left: 0, right: 0, top: 0, bottom: 0};

function nodeAndOffsetInLineMap(map$$1, ch, bias) {
  var node, start, end, collapse, mStart, mEnd;
  // First, search the line map for the text node corresponding to,
  // or closest to, the target character.
  for (var i = 0; i < map$$1.length; i += 3) {
    mStart = map$$1[i];
    mEnd = map$$1[i + 1];
    if (ch < mStart) {
      start = 0; end = 1;
      collapse = "left";
    } else if (ch < mEnd) {
      start = ch - mStart;
      end = start + 1;
    } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) {
      end = mEnd - mStart;
      start = end - 1;
      if (ch >= mEnd) { collapse = "right"; }
    }
    if (start != null) {
      node = map$$1[i + 2];
      if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
        { collapse = bias; }
      if (bias == "left" && start == 0)
        { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) {
          node = map$$1[(i -= 3) + 2];
          collapse = "left";
        } }
      if (bias == "right" && start == mEnd - mStart)
        { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) {
          node = map$$1[(i += 3) + 2];
          collapse = "right";
        } }
      break
    }
  }
  return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
}

function getUsefulRect(rects, bias) {
  var rect = nullRect;
  if (bias == "left") { for (var i = 0; i < rects.length; i++) {
    if ((rect = rects[i]).left != rect.right) { break }
  } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
    if ((rect = rects[i$1]).left != rect.right) { break }
  } }
  return rect
}

function measureCharInner(cm, prepared, ch, bias) {
  var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  var node = place.node, start = place.start, end = place.end, collapse = place.collapse;

  var rect;
  if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
    for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
      while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
      while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
      if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
        { rect = node.parentNode.getBoundingClientRect(); }
      else
        { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
      if (rect.left || rect.right || start == 0) { break }
      end = start;
      start = start - 1;
      collapse = "right";
    }
    if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
  } else { // If it is a widget, simply get the box for the whole widget.
    if (start > 0) { collapse = bias = "right"; }
    var rects;
    if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
      { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
    else
      { rect = node.getBoundingClientRect(); }
  }
  if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
    var rSpan = node.parentNode.getClientRects()[0];
    if (rSpan)
      { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
    else
      { rect = nullRect; }
  }

  var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  var mid = (rtop + rbot) / 2;
  var heights = prepared.view.measure.heights;
  var i = 0;
  for (; i < heights.length - 1; i++)
    { if (mid < heights[i]) { break } }
  var top = i ? heights[i - 1] : 0, bot = heights[i];
  var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
                right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
                top: top, bottom: bot};
  if (!rect.left && !rect.right) { result.bogus = true; }
  if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }

  return result
}

// Work around problem with bounding client rects on ranges being
// returned incorrectly when zoomed on IE10 and below.
function maybeUpdateRectForZooming(measure, rect) {
  if (!window.screen || screen.logicalXDPI == null ||
      screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
    { return rect }
  var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  return {left: rect.left * scaleX, right: rect.right * scaleX,
          top: rect.top * scaleY, bottom: rect.bottom * scaleY}
}

function clearLineMeasurementCacheFor(lineView) {
  if (lineView.measure) {
    lineView.measure.cache = {};
    lineView.measure.heights = null;
    if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
      { lineView.measure.caches[i] = {}; } }
  }
}

function clearLineMeasurementCache(cm) {
  cm.display.externalMeasure = null;
  removeChildren(cm.display.lineMeasure);
  for (var i = 0; i < cm.display.view.length; i++)
    { clearLineMeasurementCacheFor(cm.display.view[i]); }
}

function clearCaches(cm) {
  clearLineMeasurementCache(cm);
  cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
  cm.display.lineNumChars = null;
}

function pageScrollX() {
  // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  // which causes page_Offset and bounding client rects to use
  // different reference viewports and invalidate our calculations.
  if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
  return window.pageXOffset || (document.documentElement || document.body).scrollLeft
}
function pageScrollY() {
  if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
  return window.pageYOffset || (document.documentElement || document.body).scrollTop
}

function widgetTopHeight(lineObj) {
  var height = 0;
  if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
    { height += widgetHeight(lineObj.widgets[i]); } } }
  return height
}

// Converts a {top, bottom, left, right} box from line-local
// coordinates into another coordinate system. Context may be one of
// "line", "div" (display.lineDiv), "local"./null (editor), "window",
// or "page".
function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  if (!includeWidgets) {
    var height = widgetTopHeight(lineObj);
    rect.top += height; rect.bottom += height;
  }
  if (context == "line") { return rect }
  if (!context) { context = "local"; }
  var yOff = heightAtLine(lineObj);
  if (context == "local") { yOff += paddingTop(cm.display); }
  else { yOff -= cm.display.viewOffset; }
  if (context == "page" || context == "window") {
    var lOff = cm.display.lineSpace.getBoundingClientRect();
    yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
    var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
    rect.left += xOff; rect.right += xOff;
  }
  rect.top += yOff; rect.bottom += yOff;
  return rect
}

// Coverts a box from "div" coords to another coordinate system.
// Context may be "window", "page", "div", or "local"./null.
function fromCoordSystem(cm, coords, context) {
  if (context == "div") { return coords }
  var left = coords.left, top = coords.top;
  // First move into "page" coordinate system
  if (context == "page") {
    left -= pageScrollX();
    top -= pageScrollY();
  } else if (context == "local" || !context) {
    var localBox = cm.display.sizer.getBoundingClientRect();
    left += localBox.left;
    top += localBox.top;
  }

  var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
}

function charCoords(cm, pos, context, lineObj, bias) {
  if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
  return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
}

// Returns a box for a given cursor position, which may have an
// 'other' property containing the position of the secondary cursor
// on a bidi boundary.
// A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
// and after `char - 1` in writing order of `char - 1`
// A cursor Pos(line, char, "after") is on the same visual line as `char`
// and before `char` in writing order of `char`
// Examples (upper-case letters are RTL, lower-case are LTR):
//     Pos(0, 1, ...)
//     before   after
// ab     a|b     a|b
// aB     a|B     aB|
// Ab     |Ab     A|b
// AB     B|A     B|A
// Every position after the last character on a line is considered to stick
// to the last character on the line.
function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  lineObj = lineObj || getLine(cm.doc, pos.line);
  if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  function get(ch, right) {
    var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
    if (right) { m.left = m.right; } else { m.right = m.left; }
    return intoCoordSystem(cm, lineObj, m, context)
  }
  var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
  if (ch >= lineObj.text.length) {
    ch = lineObj.text.length;
    sticky = "before";
  } else if (ch <= 0) {
    ch = 0;
    sticky = "after";
  }
  if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }

  function getBidi(ch, partPos, invert) {
    var part = order[partPos], right = part.level == 1;
    return get(invert ? ch - 1 : ch, right != invert)
  }
  var partPos = getBidiPartAt(order, ch, sticky);
  var other = bidiOther;
  var val = getBidi(ch, partPos, sticky == "before");
  if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
  return val
}

// Used to cheaply estimate the coordinates for a position. Used for
// intermediate scroll updates.
function estimateCoords(cm, pos) {
  var left = 0;
  pos = clipPos(cm.doc, pos);
  if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
  var lineObj = getLine(cm.doc, pos.line);
  var top = heightAtLine(lineObj) + paddingTop(cm.display);
  return {left: left, right: left, top: top, bottom: top + lineObj.height}
}

// Positions returned by coordsChar contain some extra information.
// xRel is the relative x position of the input coordinates compared
// to the found position (so xRel > 0 means the coordinates are to
// the right of the character position, for example). When outside
// is true, that means the coordinates lie outside the line's
// vertical range.
function PosWithInfo(line, ch, sticky, outside, xRel) {
  var pos = Pos(line, ch, sticky);
  pos.xRel = xRel;
  if (outside) { pos.outside = true; }
  return pos
}

// Compute the character position closest to the given coordinates.
// Input must be lineSpace-local ("div" coordinate system).
function coordsChar(cm, x, y) {
  var doc = cm.doc;
  y += cm.display.viewOffset;
  if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }
  var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  if (lineN > last)
    { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }
  if (x < 0) { x = 0; }

  var lineObj = getLine(doc, lineN);
  for (;;) {
    var found = coordsCharInner(cm, lineObj, lineN, x, y);
    var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 ? 1 : 0));
    if (!collapsed) { return found }
    var rangeEnd = collapsed.find(1);
    if (rangeEnd.line == lineN) { return rangeEnd }
    lineObj = getLine(doc, lineN = rangeEnd.line);
  }
}

function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  y -= widgetTopHeight(lineObj);
  var end = lineObj.text.length;
  var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
  end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
  return {begin: begin, end: end}
}

function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
  return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
}

// Returns true if the given side of a box is after the given
// coordinates, in top-to-bottom, left-to-right order.
function boxIsAfter(box, x, y, left) {
  return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
}

function coordsCharInner(cm, lineObj, lineNo$$1, x, y) {
  // Move y into line-local coordinate space
  y -= heightAtLine(lineObj);
  var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  // When directly calling `measureCharPrepared`, we have to adjust
  // for the widgets at this line.
  var widgetHeight$$1 = widgetTopHeight(lineObj);
  var begin = 0, end = lineObj.text.length, ltr = true;

  var order = getOrder(lineObj, cm.doc.direction);
  // If the line isn't plain left-to-right text, first figure out
  // which bidi section the coordinates fall into.
  if (order) {
    var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
                 (cm, lineObj, lineNo$$1, preparedMeasure, order, x, y);
    ltr = part.level != 1;
    // The awkward -1 offsets are needed because findFirst (called
    // on these below) will treat its first bound as inclusive,
    // second as exclusive, but we want to actually address the
    // characters in the part's range
    begin = ltr ? part.from : part.to - 1;
    end = ltr ? part.to : part.from - 1;
  }

  // A binary search to find the first character whose bounding box
  // starts after the coordinates. If we run across any whose box wrap
  // the coordinates, store that.
  var chAround = null, boxAround = null;
  var ch = findFirst(function (ch) {
    var box = measureCharPrepared(cm, preparedMeasure, ch);
    box.top += widgetHeight$$1; box.bottom += widgetHeight$$1;
    if (!boxIsAfter(box, x, y, false)) { return false }
    if (box.top <= y && box.left <= x) {
      chAround = ch;
      boxAround = box;
    }
    return true
  }, begin, end);

  var baseX, sticky, outside = false;
  // If a box around the coordinates was found, use that
  if (boxAround) {
    // Distinguish coordinates nearer to the left or right side of the box
    var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
    ch = chAround + (atStart ? 0 : 1);
    sticky = atStart ? "after" : "before";
    baseX = atLeft ? boxAround.left : boxAround.right;
  } else {
    // (Adjust for extended bound, if necessary.)
    if (!ltr && (ch == end || ch == begin)) { ch++; }
    // To determine which side to associate with, get the box to the
    // left of the character and compare it's vertical position to the
    // coordinates
    sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
      (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight$$1 <= y) == ltr ?
      "after" : "before";
    // Now get accurate coordinates for this place, in order to get a
    // base X position
    var coords = cursorCoords(cm, Pos(lineNo$$1, ch, sticky), "line", lineObj, preparedMeasure);
    baseX = coords.left;
    outside = y < coords.top || y >= coords.bottom;
  }

  ch = skipExtendingChars(lineObj.text, ch, 1);
  return PosWithInfo(lineNo$$1, ch, sticky, outside, x - baseX)
}

function coordsBidiPart(cm, lineObj, lineNo$$1, preparedMeasure, order, x, y) {
  // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  // situation, we can take this ordering to correspond to the visual
  // ordering. This finds the first part whose end is after the given
  // coordinates.
  var index = findFirst(function (i) {
    var part = order[i], ltr = part.level != 1;
    return boxIsAfter(cursorCoords(cm, Pos(lineNo$$1, ltr ? part.to : part.from, ltr ? "before" : "after"),
                                   "line", lineObj, preparedMeasure), x, y, true)
  }, 0, order.length - 1);
  var part = order[index];
  // If this isn't the first part, the part's start is also after
  // the coordinates, and the coordinates aren't on the same line as
  // that start, move one part back.
  if (index > 0) {
    var ltr = part.level != 1;
    var start = cursorCoords(cm, Pos(lineNo$$1, ltr ? part.from : part.to, ltr ? "after" : "before"),
                             "line", lineObj, preparedMeasure);
    if (boxIsAfter(start, x, y, true) && start.top > y)
      { part = order[index - 1]; }
  }
  return part
}

function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  // In a wrapped line, rtl text on wrapping boundaries can do things
  // that don't correspond to the ordering in our `order` array at
  // all, so a binary search doesn't work, and we want to return a
  // part that only spans one line so that the binary search in
  // coordsCharInner is safe. As such, we first find the extent of the
  // wrapped line, and then do a flat search in which we discard any
  // spans that aren't on the line.
  var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
  var begin = ref.begin;
  var end = ref.end;
  if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
  var part = null, closestDist = null;
  for (var i = 0; i < order.length; i++) {
    var p = order[i];
    if (p.from >= end || p.to <= begin) { continue }
    var ltr = p.level != 1;
    var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
    // Weigh against spans ending before this, so that they are only
    // picked if nothing ends after
    var dist = endX < x ? x - endX + 1e9 : endX - x;
    if (!part || closestDist > dist) {
      part = p;
      closestDist = dist;
    }
  }
  if (!part) { part = order[order.length - 1]; }
  // Clip the part to the wrapped line.
  if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
  if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
  return part
}

var measureText;
// Compute the default text height.
function textHeight(display) {
  if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  if (measureText == null) {
    measureText = elt("pre");
    // Measure a bunch of lines, for browsers that compute
    // fractional heights.
    for (var i = 0; i < 49; ++i) {
      measureText.appendChild(document.createTextNode("x"));
      measureText.appendChild(elt("br"));
    }
    measureText.appendChild(document.createTextNode("x"));
  }
  removeChildrenAndAdd(display.measure, measureText);
  var height = measureText.offsetHeight / 50;
  if (height > 3) { display.cachedTextHeight = height; }
  removeChildren(display.measure);
  return height || 1
}

// Compute the default character width.
function charWidth(display) {
  if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  var anchor = elt("span", "xxxxxxxxxx");
  var pre = elt("pre", [anchor]);
  removeChildrenAndAdd(display.measure, pre);
  var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  if (width > 2) { display.cachedCharWidth = width; }
  return width || 10
}

// Do a bulk-read of the DOM positions and sizes needed to draw the
// view, so that we don't interleave reading and writing to the DOM.
function getDimensions(cm) {
  var d = cm.display, left = {}, width = {};
  var gutterLeft = d.gutters.clientLeft;
  for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
    left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
    width[cm.options.gutters[i]] = n.clientWidth;
  }
  return {fixedPos: compensateForHScroll(d),
          gutterTotalWidth: d.gutters.offsetWidth,
          gutterLeft: left,
          gutterWidth: width,
          wrapperWidth: d.wrapper.clientWidth}
}

// Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
// but using getBoundingClientRect to get a sub-pixel-accurate
// result.
function compensateForHScroll(display) {
  return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
}

// Returns a function that estimates the height of a line, to use as
// first approximation until the line becomes visible (and is thus
// properly measurable).
function estimateHeight(cm) {
  var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  return function (line) {
    if (lineIsHidden(cm.doc, line)) { return 0 }

    var widgetsHeight = 0;
    if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
      if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
    } }

    if (wrapping)
      { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
    else
      { return widgetsHeight + th }
  }
}

function estimateLineHeights(cm) {
  var doc = cm.doc, est = estimateHeight(cm);
  doc.iter(function (line) {
    var estHeight = est(line);
    if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  });
}

// Given a mouse event, find the corresponding position. If liberal
// is false, it checks whether a gutter or scrollbar was clicked,
// and returns null if it was. forRect is used by rectangular
// selections, and tries to estimate a character position even for
// coordinates beyond the right of the text.
function posFromMouse(cm, e, liberal, forRect) {
  var display = cm.display;
  if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }

  var x, y, space = display.lineSpace.getBoundingClientRect();
  // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  try { x = e.clientX - space.left; y = e.clientY - space.top; }
  catch (e) { return null }
  var coords = coordsChar(cm, x, y), line;
  if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
    var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
    coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  }
  return coords
}

// Find the view element corresponding to a given line. Return null
// when the line isn't visible.
function findViewIndex(cm, n) {
  if (n >= cm.display.viewTo) { return null }
  n -= cm.display.viewFrom;
  if (n < 0) { return null }
  var view = cm.display.view;
  for (var i = 0; i < view.length; i++) {
    n -= view[i].size;
    if (n < 0) { return i }
  }
}

function updateSelection(cm) {
  cm.display.input.showSelection(cm.display.input.prepareSelection());
}

function prepareSelection(cm, primary) {
  if ( primary === void 0 ) primary = true;

  var doc = cm.doc, result = {};
  var curFragment = result.cursors = document.createDocumentFragment();
  var selFragment = result.selection = document.createDocumentFragment();

  for (var i = 0; i < doc.sel.ranges.length; i++) {
    if (!primary && i == doc.sel.primIndex) { continue }
    var range$$1 = doc.sel.ranges[i];
    if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue }
    var collapsed = range$$1.empty();
    if (collapsed || cm.options.showCursorWhenSelecting)
      { drawSelectionCursor(cm, range$$1.head, curFragment); }
    if (!collapsed)
      { drawSelectionRange(cm, range$$1, selFragment); }
  }
  return result
}

// Draws a cursor for the given range
function drawSelectionCursor(cm, head, output) {
  var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);

  var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  cursor.style.left = pos.left + "px";
  cursor.style.top = pos.top + "px";
  cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";

  if (pos.other) {
    // Secondary cursor, shown when on a 'jump' in bi-directional text
    var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
    otherCursor.style.display = "";
    otherCursor.style.left = pos.other.left + "px";
    otherCursor.style.top = pos.other.top + "px";
    otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  }
}

function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }

// Draws the given range as a highlighted selection
function drawSelectionRange(cm, range$$1, output) {
  var display = cm.display, doc = cm.doc;
  var fragment = document.createDocumentFragment();
  var padding = paddingH(cm.display), leftSide = padding.left;
  var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  var docLTR = doc.direction == "ltr";

  function add(left, top, width, bottom) {
    if (top < 0) { top = 0; }
    top = Math.round(top);
    bottom = Math.round(bottom);
    fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n                             top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n                             height: " + (bottom - top) + "px")));
  }

  function drawForLine(line, fromArg, toArg) {
    var lineObj = getLine(doc, line);
    var lineLen = lineObj.text.length;
    var start, end;
    function coords(ch, bias) {
      return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
    }

    function wrapX(pos, dir, side) {
      var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
      var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
      var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
      return coords(ch, prop)[prop]
    }

    var order = getOrder(lineObj, doc.direction);
    iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
      var ltr = dir == "ltr";
      var fromPos = coords(from, ltr ? "left" : "right");
      var toPos = coords(to - 1, ltr ? "right" : "left");

      var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
      var first = i == 0, last = !order || i == order.length - 1;
      if (toPos.top - fromPos.top <= 3) { // Single line
        var openLeft = (docLTR ? openStart : openEnd) && first;
        var openRight = (docLTR ? openEnd : openStart) && last;
        var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
        var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
        add(left, fromPos.top, right - left, fromPos.bottom);
      } else { // Multiple lines
        var topLeft, topRight, botLeft, botRight;
        if (ltr) {
          topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
          topRight = docLTR ? rightSide : wrapX(from, dir, "before");
          botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
          botRight = docLTR && openEnd && last ? rightSide : toPos.right;
        } else {
          topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
          topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
          botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
          botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
        }
        add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
        if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
        add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
      }

      if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
      if (cmpCoords(toPos, start) < 0) { start = toPos; }
      if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
      if (cmpCoords(toPos, end) < 0) { end = toPos; }
    });
    return {start: start, end: end}
  }

  var sFrom = range$$1.from(), sTo = range$$1.to();
  if (sFrom.line == sTo.line) {
    drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  } else {
    var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
    var singleVLine = visualLine(fromLine) == visualLine(toLine);
    var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
    var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
    if (singleVLine) {
      if (leftEnd.top < rightStart.top - 2) {
        add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
        add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
      } else {
        add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
      }
    }
    if (leftEnd.bottom < rightStart.top)
      { add(leftSide, leftEnd.bottom, null, rightStart.top); }
  }

  output.appendChild(fragment);
}

// Cursor-blinking
function restartBlink(cm) {
  if (!cm.state.focused) { return }
  var display = cm.display;
  clearInterval(display.blinker);
  var on = true;
  display.cursorDiv.style.visibility = "";
  if (cm.options.cursorBlinkRate > 0)
    { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
      cm.options.cursorBlinkRate); }
  else if (cm.options.cursorBlinkRate < 0)
    { display.cursorDiv.style.visibility = "hidden"; }
}

function ensureFocus(cm) {
  if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
}

function delayBlurEvent(cm) {
  cm.state.delayingBlurEvent = true;
  setTimeout(function () { if (cm.state.delayingBlurEvent) {
    cm.state.delayingBlurEvent = false;
    onBlur(cm);
  } }, 100);
}

function onFocus(cm, e) {
  if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }

  if (cm.options.readOnly == "nocursor") { return }
  if (!cm.state.focused) {
    signal(cm, "focus", cm, e);
    cm.state.focused = true;
    addClass(cm.display.wrapper, "CodeMirror-focused");
    // This test prevents this from firing when a context
    // menu is closed (since the input reset would kill the
    // select-all detection hack)
    if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
      cm.display.input.reset();
      if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
    }
    cm.display.input.receivedFocus();
  }
  restartBlink(cm);
}
function onBlur(cm, e) {
  if (cm.state.delayingBlurEvent) { return }

  if (cm.state.focused) {
    signal(cm, "blur", cm, e);
    cm.state.focused = false;
    rmClass(cm.display.wrapper, "CodeMirror-focused");
  }
  clearInterval(cm.display.blinker);
  setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
}

// Read the actual heights of the rendered lines, and update their
// stored heights to match.
function updateHeightsInViewport(cm) {
  var display = cm.display;
  var prevBottom = display.lineDiv.offsetTop;
  for (var i = 0; i < display.view.length; i++) {
    var cur = display.view[i], height = (void 0);
    if (cur.hidden) { continue }
    if (ie && ie_version < 8) {
      var bot = cur.node.offsetTop + cur.node.offsetHeight;
      height = bot - prevBottom;
      prevBottom = bot;
    } else {
      var box = cur.node.getBoundingClientRect();
      height = box.bottom - box.top;
    }
    var diff = cur.line.height - height;
    if (height < 2) { height = textHeight(display); }
    if (diff > .005 || diff < -.005) {
      updateLineHeight(cur.line, height);
      updateWidgetHeight(cur.line);
      if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
        { updateWidgetHeight(cur.rest[j]); } }
    }
  }
}

// Read and store the height of line widgets associated with the
// given line.
function updateWidgetHeight(line) {
  if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
    var w = line.widgets[i], parent = w.node.parentNode;
    if (parent) { w.height = parent.offsetHeight; }
  } }
}

// Compute the lines that are visible in a given viewport (defaults
// the the current scroll position). viewport may contain top,
// height, and ensure (see op.scrollToPos) properties.
function visibleLines(display, doc, viewport) {
  var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  top = Math.floor(top - paddingTop(display));
  var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;

  var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  // forces those lines into the viewport (if possible).
  if (viewport && viewport.ensure) {
    var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
    if (ensureFrom < from) {
      from = ensureFrom;
      to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
    } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
      from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
      to = ensureTo;
    }
  }
  return {from: from, to: Math.max(to, from + 1)}
}

// Re-align line numbers and gutter marks to compensate for
// horizontal scrolling.
function alignHorizontally(cm) {
  var display = cm.display, view = display.view;
  if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  var gutterW = display.gutters.offsetWidth, left = comp + "px";
  for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
    if (cm.options.fixedGutter) {
      if (view[i].gutter)
        { view[i].gutter.style.left = left; }
      if (view[i].gutterBackground)
        { view[i].gutterBackground.style.left = left; }
    }
    var align = view[i].alignable;
    if (align) { for (var j = 0; j < align.length; j++)
      { align[j].style.left = left; } }
  } }
  if (cm.options.fixedGutter)
    { display.gutters.style.left = (comp + gutterW) + "px"; }
}

// Used to ensure that the line number gutter is still the right
// size for the current document size. Returns true when an update
// is needed.
function maybeUpdateLineNumberWidth(cm) {
  if (!cm.options.lineNumbers) { return false }
  var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  if (last.length != display.lineNumChars) {
    var test = display.measure.appendChild(elt("div", [elt("div", last)],
                                               "CodeMirror-linenumber CodeMirror-gutter-elt"));
    var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
    display.lineGutter.style.width = "";
    display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
    display.lineNumWidth = display.lineNumInnerWidth + padding;
    display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
    display.lineGutter.style.width = display.lineNumWidth + "px";
    updateGutterSpace(cm);
    return true
  }
  return false
}

// SCROLLING THINGS INTO VIEW

// If an editor sits on the top or bottom of the window, partially
// scrolled out of view, this ensures that the cursor is visible.
function maybeScrollWindow(cm, rect) {
  if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }

  var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  if (rect.top + box.top < 0) { doScroll = true; }
  else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
  if (doScroll != null && !phantom) {
    var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n                         top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n                         height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n                         left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;"));
    cm.display.lineSpace.appendChild(scrollNode);
    scrollNode.scrollIntoView(doScroll);
    cm.display.lineSpace.removeChild(scrollNode);
  }
}

// Scroll a given position into view (immediately), verifying that
// it actually became visible (as line heights are accurately
// measured, the position of something may 'drift' during drawing).
function scrollPosIntoView(cm, pos, end, margin) {
  if (margin == null) { margin = 0; }
  var rect;
  if (!cm.options.lineWrapping && pos == end) {
    // Set pos and end to the cursor positions around the character pos sticks to
    // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
    // If pos == Pos(_, 0, "before"), pos and end are unchanged
    pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
    end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
  }
  for (var limit = 0; limit < 5; limit++) {
    var changed = false;
    var coords = cursorCoords(cm, pos);
    var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
    rect = {left: Math.min(coords.left, endCoords.left),
            top: Math.min(coords.top, endCoords.top) - margin,
            right: Math.max(coords.left, endCoords.left),
            bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
    var scrollPos = calculateScrollPos(cm, rect);
    var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
    if (scrollPos.scrollTop != null) {
      updateScrollTop(cm, scrollPos.scrollTop);
      if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
    }
    if (scrollPos.scrollLeft != null) {
      setScrollLeft(cm, scrollPos.scrollLeft);
      if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
    }
    if (!changed) { break }
  }
  return rect
}

// Scroll a given set of coordinates into view (immediately).
function scrollIntoView(cm, rect) {
  var scrollPos = calculateScrollPos(cm, rect);
  if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
  if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
}

// Calculate a new scroll position needed to scroll the given
// rectangle into view. Returns an object with scrollTop and
// scrollLeft properties. When these are undefined, the
// vertical/horizontal position does not need to be adjusted.
function calculateScrollPos(cm, rect) {
  var display = cm.display, snapMargin = textHeight(cm.display);
  if (rect.top < 0) { rect.top = 0; }
  var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  var screen = displayHeight(cm), result = {};
  if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
  var docBottom = cm.doc.height + paddingVert(display);
  var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
  if (rect.top < screentop) {
    result.scrollTop = atTop ? 0 : rect.top;
  } else if (rect.bottom > screentop + screen) {
    var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
    if (newTop != screentop) { result.scrollTop = newTop; }
  }

  var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
  var tooWide = rect.right - rect.left > screenw;
  if (tooWide) { rect.right = rect.left + screenw; }
  if (rect.left < 10)
    { result.scrollLeft = 0; }
  else if (rect.left < screenleft)
    { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); }
  else if (rect.right > screenw + screenleft - 3)
    { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
  return result
}

// Store a relative adjustment to the scroll position in the current
// operation (to be applied when the operation finishes).
function addToScrollTop(cm, top) {
  if (top == null) { return }
  resolveScrollToPos(cm);
  cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
}

// Make sure that at the end of the operation the current cursor is
// shown.
function ensureCursorVisible(cm) {
  resolveScrollToPos(cm);
  var cur = cm.getCursor();
  cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
}

function scrollToCoords(cm, x, y) {
  if (x != null || y != null) { resolveScrollToPos(cm); }
  if (x != null) { cm.curOp.scrollLeft = x; }
  if (y != null) { cm.curOp.scrollTop = y; }
}

function scrollToRange(cm, range$$1) {
  resolveScrollToPos(cm);
  cm.curOp.scrollToPos = range$$1;
}

// When an operation has its scrollToPos property set, and another
// scroll action is applied before the end of the operation, this
// 'simulates' scrolling that position into view in a cheap way, so
// that the effect of intermediate scroll commands is not ignored.
function resolveScrollToPos(cm) {
  var range$$1 = cm.curOp.scrollToPos;
  if (range$$1) {
    cm.curOp.scrollToPos = null;
    var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to);
    scrollToCoordsRange(cm, from, to, range$$1.margin);
  }
}

function scrollToCoordsRange(cm, from, to, margin) {
  var sPos = calculateScrollPos(cm, {
    left: Math.min(from.left, to.left),
    top: Math.min(from.top, to.top) - margin,
    right: Math.max(from.right, to.right),
    bottom: Math.max(from.bottom, to.bottom) + margin
  });
  scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
}

// Sync the scrollable area and scrollbars, ensure the viewport
// covers the visible area.
function updateScrollTop(cm, val) {
  if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  if (!gecko) { updateDisplaySimple(cm, {top: val}); }
  setScrollTop(cm, val, true);
  if (gecko) { updateDisplaySimple(cm); }
  startWorker(cm, 100);
}

function setScrollTop(cm, val, forceScroll) {
  val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val);
  if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
  cm.doc.scrollTop = val;
  cm.display.scrollbars.setScrollTop(val);
  if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
}

// Sync scroller and scrollbar, ensure the gutter elements are
// aligned.
function setScrollLeft(cm, val, isScroller, forceScroll) {
  val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
  cm.doc.scrollLeft = val;
  alignHorizontally(cm);
  if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
  cm.display.scrollbars.setScrollLeft(val);
}

// SCROLLBARS

// Prepare DOM reads needed to update the scrollbars. Done in one
// shot to minimize update/measure roundtrips.
function measureForScrollbars(cm) {
  var d = cm.display, gutterW = d.gutters.offsetWidth;
  var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  return {
    clientHeight: d.scroller.clientHeight,
    viewHeight: d.wrapper.clientHeight,
    scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
    viewWidth: d.wrapper.clientWidth,
    barLeft: cm.options.fixedGutter ? gutterW : 0,
    docHeight: docH,
    scrollHeight: docH + scrollGap(cm) + d.barHeight,
    nativeBarWidth: d.nativeBarWidth,
    gutterWidth: gutterW
  }
}

var NativeScrollbars = function(place, scroll, cm) {
  this.cm = cm;
  var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  vert.tabIndex = horiz.tabIndex = -1;
  place(vert); place(horiz);

  on(vert, "scroll", function () {
    if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
  });
  on(horiz, "scroll", function () {
    if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
  });

  this.checkedZeroWidth = false;
  // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
};

NativeScrollbars.prototype.update = function (measure) {
  var needsH = measure.scrollWidth > measure.clientWidth + 1;
  var needsV = measure.scrollHeight > measure.clientHeight + 1;
  var sWidth = measure.nativeBarWidth;

  if (needsV) {
    this.vert.style.display = "block";
    this.vert.style.bottom = needsH ? sWidth + "px" : "0";
    var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
    // A bug in IE8 can cause this value to be negative, so guard it.
    this.vert.firstChild.style.height =
      Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  } else {
    this.vert.style.display = "";
    this.vert.firstChild.style.height = "0";
  }

  if (needsH) {
    this.horiz.style.display = "block";
    this.horiz.style.right = needsV ? sWidth + "px" : "0";
    this.horiz.style.left = measure.barLeft + "px";
    var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
    this.horiz.firstChild.style.width =
      Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  } else {
    this.horiz.style.display = "";
    this.horiz.firstChild.style.width = "0";
  }

  if (!this.checkedZeroWidth && measure.clientHeight > 0) {
    if (sWidth == 0) { this.zeroWidthHack(); }
    this.checkedZeroWidth = true;
  }

  return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
};

NativeScrollbars.prototype.setScrollLeft = function (pos) {
  if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
  if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
};

NativeScrollbars.prototype.setScrollTop = function (pos) {
  if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
  if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
};

NativeScrollbars.prototype.zeroWidthHack = function () {
  var w = mac && !mac_geMountainLion ? "12px" : "18px";
  this.horiz.style.height = this.vert.style.width = w;
  this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
  this.disableHoriz = new Delayed;
  this.disableVert = new Delayed;
};

NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  bar.style.pointerEvents = "auto";
  function maybeDisable() {
    // To find out whether the scrollbar is still visible, we
    // check whether the element under the pixel in the bottom
    // right corner of the scrollbar box is the scrollbar box
    // itself (when the bar is still visible) or its filler child
    // (when the bar is hidden). If it is still visible, we keep
    // it enabled, if it's hidden, we disable pointer events.
    var box = bar.getBoundingClientRect();
    var elt$$1 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
        : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
    if (elt$$1 != bar) { bar.style.pointerEvents = "none"; }
    else { delay.set(1000, maybeDisable); }
  }
  delay.set(1000, maybeDisable);
};

NativeScrollbars.prototype.clear = function () {
  var parent = this.horiz.parentNode;
  parent.removeChild(this.horiz);
  parent.removeChild(this.vert);
};

var NullScrollbars = function () {};

NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
NullScrollbars.prototype.setScrollLeft = function () {};
NullScrollbars.prototype.setScrollTop = function () {};
NullScrollbars.prototype.clear = function () {};

function updateScrollbars(cm, measure) {
  if (!measure) { measure = measureForScrollbars(cm); }
  var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  updateScrollbarsInner(cm, measure);
  for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
    if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
      { updateHeightsInViewport(cm); }
    updateScrollbarsInner(cm, measureForScrollbars(cm));
    startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  }
}

// Re-synchronize the fake scrollbars with the actual size of the
// content.
function updateScrollbarsInner(cm, measure) {
  var d = cm.display;
  var sizes = d.scrollbars.update(measure);

  d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";

  if (sizes.right && sizes.bottom) {
    d.scrollbarFiller.style.display = "block";
    d.scrollbarFiller.style.height = sizes.bottom + "px";
    d.scrollbarFiller.style.width = sizes.right + "px";
  } else { d.scrollbarFiller.style.display = ""; }
  if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
    d.gutterFiller.style.display = "block";
    d.gutterFiller.style.height = sizes.bottom + "px";
    d.gutterFiller.style.width = measure.gutterWidth + "px";
  } else { d.gutterFiller.style.display = ""; }
}

var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};

function initScrollbars(cm) {
  if (cm.display.scrollbars) {
    cm.display.scrollbars.clear();
    if (cm.display.scrollbars.addClass)
      { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  }

  cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
    cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
    // Prevent clicks in the scrollbars from killing focus
    on(node, "mousedown", function () {
      if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
    });
    node.setAttribute("cm-not-content", "true");
  }, function (pos, axis) {
    if (axis == "horizontal") { setScrollLeft(cm, pos); }
    else { updateScrollTop(cm, pos); }
  }, cm);
  if (cm.display.scrollbars.addClass)
    { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
}

// Operations are used to wrap a series of changes to the editor
// state in such a way that each change won't have to update the
// cursor and display (which would be awkward, slow, and
// error-prone). Instead, display updates are batched and then all
// combined and executed at once.

var nextOpId = 0;
// Start a new operation.
function startOperation(cm) {
  cm.curOp = {
    cm: cm,
    viewChanged: false,      // Flag that indicates that lines might need to be redrawn
    startHeight: cm.doc.height, // Used to detect need to update scrollbar
    forceUpdate: false,      // Used to force a redraw
    updateInput: null,       // Whether to reset the input textarea
    typing: false,           // Whether this reset should be careful to leave existing text (for compositing)
    changeObjs: null,        // Accumulated changes, for firing change events
    cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
    cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
    selectionChanged: false, // Whether the selection needs to be redrawn
    updateMaxLine: false,    // Set when the widest line needs to be determined anew
    scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
    scrollToPos: null,       // Used to scroll to a specific position
    focus: false,
    id: ++nextOpId           // Unique ID
  };
  pushOperation(cm.curOp);
}

// Finish an operation, updating the display and signalling delayed events
function endOperation(cm) {
  var op = cm.curOp;
  finishOperation(op, function (group) {
    for (var i = 0; i < group.ops.length; i++)
      { group.ops[i].cm.curOp = null; }
    endOperations(group);
  });
}

// The DOM updates done when an operation finishes are batched so
// that the minimum number of relayouts are required.
function endOperations(group) {
  var ops = group.ops;
  for (var i = 0; i < ops.length; i++) // Read DOM
    { endOperation_R1(ops[i]); }
  for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
    { endOperation_W1(ops[i$1]); }
  for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
    { endOperation_R2(ops[i$2]); }
  for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
    { endOperation_W2(ops[i$3]); }
  for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
    { endOperation_finish(ops[i$4]); }
}

function endOperation_R1(op) {
  var cm = op.cm, display = cm.display;
  maybeClipScrollbars(cm);
  if (op.updateMaxLine) { findMaxLine(cm); }

  op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
    op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
                       op.scrollToPos.to.line >= display.viewTo) ||
    display.maxLineChanged && cm.options.lineWrapping;
  op.update = op.mustUpdate &&
    new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
}

function endOperation_W1(op) {
  op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
}

function endOperation_R2(op) {
  var cm = op.cm, display = cm.display;
  if (op.updatedDisplay) { updateHeightsInViewport(cm); }

  op.barMeasure = measureForScrollbars(cm);

  // If the max line changed since it was last measured, measure it,
  // and ensure the document's width matches it.
  // updateDisplay_W2 will use these properties to do the actual resizing
  if (display.maxLineChanged && !cm.options.lineWrapping) {
    op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
    cm.display.sizerWidth = op.adjustWidthTo;
    op.barMeasure.scrollWidth =
      Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
    op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  }

  if (op.updatedDisplay || op.selectionChanged)
    { op.preparedSelection = display.input.prepareSelection(); }
}

function endOperation_W2(op) {
  var cm = op.cm;

  if (op.adjustWidthTo != null) {
    cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
    if (op.maxScrollLeft < cm.doc.scrollLeft)
      { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
    cm.display.maxLineChanged = false;
  }

  var takeFocus = op.focus && op.focus == activeElt();
  if (op.preparedSelection)
    { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
  if (op.updatedDisplay || op.startHeight != cm.doc.height)
    { updateScrollbars(cm, op.barMeasure); }
  if (op.updatedDisplay)
    { setDocumentHeight(cm, op.barMeasure); }

  if (op.selectionChanged) { restartBlink(cm); }

  if (cm.state.focused && op.updateInput)
    { cm.display.input.reset(op.typing); }
  if (takeFocus) { ensureFocus(op.cm); }
}

function endOperation_finish(op) {
  var cm = op.cm, display = cm.display, doc = cm.doc;

  if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }

  // Abort mouse wheel delta measurement, when scrolling explicitly
  if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
    { display.wheelStartX = display.wheelStartY = null; }

  // Propagate the scroll position to the actual DOM scroller
  if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }

  if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
  // If we need to scroll a specific position into view, do so.
  if (op.scrollToPos) {
    var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
                                 clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
    maybeScrollWindow(cm, rect);
  }

  // Fire events for markers that are hidden/unidden by editing or
  // undoing
  var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  if (hidden) { for (var i = 0; i < hidden.length; ++i)
    { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
  if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
    { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }

  if (display.wrapper.offsetHeight)
    { doc.scrollTop = cm.display.scroller.scrollTop; }

  // Fire change events, and delayed event handlers
  if (op.changeObjs)
    { signal(cm, "changes", cm, op.changeObjs); }
  if (op.update)
    { op.update.finish(); }
}

// Run the given function in an operation
function runInOp(cm, f) {
  if (cm.curOp) { return f() }
  startOperation(cm);
  try { return f() }
  finally { endOperation(cm); }
}
// Wraps a function in an operation. Returns the wrapped function.
function operation(cm, f) {
  return function() {
    if (cm.curOp) { return f.apply(cm, arguments) }
    startOperation(cm);
    try { return f.apply(cm, arguments) }
    finally { endOperation(cm); }
  }
}
// Used to add methods to editor and doc instances, wrapping them in
// operations.
function methodOp(f) {
  return function() {
    if (this.curOp) { return f.apply(this, arguments) }
    startOperation(this);
    try { return f.apply(this, arguments) }
    finally { endOperation(this); }
  }
}
function docMethodOp(f) {
  return function() {
    var cm = this.cm;
    if (!cm || cm.curOp) { return f.apply(this, arguments) }
    startOperation(cm);
    try { return f.apply(this, arguments) }
    finally { endOperation(cm); }
  }
}

// Updates the display.view data structure for a given change to the
// document. From and to are in pre-change coordinates. Lendiff is
// the amount of lines added or subtracted by the change. This is
// used for changes that span multiple lines, or change the way
// lines are divided into visual lines. regLineChange (below)
// registers single-line changes.
function regChange(cm, from, to, lendiff) {
  if (from == null) { from = cm.doc.first; }
  if (to == null) { to = cm.doc.first + cm.doc.size; }
  if (!lendiff) { lendiff = 0; }

  var display = cm.display;
  if (lendiff && to < display.viewTo &&
      (display.updateLineNumbers == null || display.updateLineNumbers > from))
    { display.updateLineNumbers = from; }

  cm.curOp.viewChanged = true;

  if (from >= display.viewTo) { // Change after
    if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
      { resetView(cm); }
  } else if (to <= display.viewFrom) { // Change before
    if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
      resetView(cm);
    } else {
      display.viewFrom += lendiff;
      display.viewTo += lendiff;
    }
  } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
    resetView(cm);
  } else if (from <= display.viewFrom) { // Top overlap
    var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
    if (cut) {
      display.view = display.view.slice(cut.index);
      display.viewFrom = cut.lineN;
      display.viewTo += lendiff;
    } else {
      resetView(cm);
    }
  } else if (to >= display.viewTo) { // Bottom overlap
    var cut$1 = viewCuttingPoint(cm, from, from, -1);
    if (cut$1) {
      display.view = display.view.slice(0, cut$1.index);
      display.viewTo = cut$1.lineN;
    } else {
      resetView(cm);
    }
  } else { // Gap in the middle
    var cutTop = viewCuttingPoint(cm, from, from, -1);
    var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
    if (cutTop && cutBot) {
      display.view = display.view.slice(0, cutTop.index)
        .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
        .concat(display.view.slice(cutBot.index));
      display.viewTo += lendiff;
    } else {
      resetView(cm);
    }
  }

  var ext = display.externalMeasured;
  if (ext) {
    if (to < ext.lineN)
      { ext.lineN += lendiff; }
    else if (from < ext.lineN + ext.size)
      { display.externalMeasured = null; }
  }
}

// Register a change to a single line. Type must be one of "text",
// "gutter", "class", "widget"
function regLineChange(cm, line, type) {
  cm.curOp.viewChanged = true;
  var display = cm.display, ext = cm.display.externalMeasured;
  if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
    { display.externalMeasured = null; }

  if (line < display.viewFrom || line >= display.viewTo) { return }
  var lineView = display.view[findViewIndex(cm, line)];
  if (lineView.node == null) { return }
  var arr = lineView.changes || (lineView.changes = []);
  if (indexOf(arr, type) == -1) { arr.push(type); }
}

// Clear the view.
function resetView(cm) {
  cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  cm.display.view = [];
  cm.display.viewOffset = 0;
}

function viewCuttingPoint(cm, oldN, newN, dir) {
  var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
    { return {index: index, lineN: newN} }
  var n = cm.display.viewFrom;
  for (var i = 0; i < index; i++)
    { n += view[i].size; }
  if (n != oldN) {
    if (dir > 0) {
      if (index == view.length - 1) { return null }
      diff = (n + view[index].size) - oldN;
      index++;
    } else {
      diff = n - oldN;
    }
    oldN += diff; newN += diff;
  }
  while (visualLineNo(cm.doc, newN) != newN) {
    if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
    newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
    index += dir;
  }
  return {index: index, lineN: newN}
}

// Force the view to cover a given range, adding empty view element
// or clipping off existing ones as needed.
function adjustView(cm, from, to) {
  var display = cm.display, view = display.view;
  if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
    display.view = buildViewArray(cm, from, to);
    display.viewFrom = from;
  } else {
    if (display.viewFrom > from)
      { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
    else if (display.viewFrom < from)
      { display.view = display.view.slice(findViewIndex(cm, from)); }
    display.viewFrom = from;
    if (display.viewTo < to)
      { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
    else if (display.viewTo > to)
      { display.view = display.view.slice(0, findViewIndex(cm, to)); }
  }
  display.viewTo = to;
}

// Count the number of lines in the view whose DOM representation is
// out of date (or nonexistent).
function countDirtyView(cm) {
  var view = cm.display.view, dirty = 0;
  for (var i = 0; i < view.length; i++) {
    var lineView = view[i];
    if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
  }
  return dirty
}

// HIGHLIGHT WORKER

function startWorker(cm, time) {
  if (cm.doc.highlightFrontier < cm.display.viewTo)
    { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
}

function highlightWorker(cm) {
  var doc = cm.doc;
  if (doc.highlightFrontier >= cm.display.viewTo) { return }
  var end = +new Date + cm.options.workTime;
  var context = getContextBefore(cm, doc.highlightFrontier);
  var changedLines = [];

  doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
    if (context.line >= cm.display.viewFrom) { // Visible
      var oldStyles = line.styles;
      var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
      var highlighted = highlightLine(cm, line, context, true);
      if (resetState) { context.state = resetState; }
      line.styles = highlighted.styles;
      var oldCls = line.styleClasses, newCls = highlighted.classes;
      if (newCls) { line.styleClasses = newCls; }
      else if (oldCls) { line.styleClasses = null; }
      var ischange = !oldStyles || oldStyles.length != line.styles.length ||
        oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
      for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
      if (ischange) { changedLines.push(context.line); }
      line.stateAfter = context.save();
      context.nextLine();
    } else {
      if (line.text.length <= cm.options.maxHighlightLength)
        { processLine(cm, line.text, context); }
      line.stateAfter = context.line % 5 == 0 ? context.save() : null;
      context.nextLine();
    }
    if (+new Date > end) {
      startWorker(cm, cm.options.workDelay);
      return true
    }
  });
  doc.highlightFrontier = context.line;
  doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
  if (changedLines.length) { runInOp(cm, function () {
    for (var i = 0; i < changedLines.length; i++)
      { regLineChange(cm, changedLines[i], "text"); }
  }); }
}

// DISPLAY DRAWING

var DisplayUpdate = function(cm, viewport, force) {
  var display = cm.display;

  this.viewport = viewport;
  // Store some values that we'll need later (but don't want to force a relayout for)
  this.visible = visibleLines(display, cm.doc, viewport);
  this.editorIsHidden = !display.wrapper.offsetWidth;
  this.wrapperHeight = display.wrapper.clientHeight;
  this.wrapperWidth = display.wrapper.clientWidth;
  this.oldDisplayWidth = displayWidth(cm);
  this.force = force;
  this.dims = getDimensions(cm);
  this.events = [];
};

DisplayUpdate.prototype.signal = function (emitter, type) {
  if (hasHandler(emitter, type))
    { this.events.push(arguments); }
};
DisplayUpdate.prototype.finish = function () {
    var this$1 = this;

  for (var i = 0; i < this.events.length; i++)
    { signal.apply(null, this$1.events[i]); }
};

function maybeClipScrollbars(cm) {
  var display = cm.display;
  if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
    display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
    display.heightForcer.style.height = scrollGap(cm) + "px";
    display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
    display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
    display.scrollbarsClipped = true;
  }
}

function selectionSnapshot(cm) {
  if (cm.hasFocus()) { return null }
  var active = activeElt();
  if (!active || !contains(cm.display.lineDiv, active)) { return null }
  var result = {activeElt: active};
  if (window.getSelection) {
    var sel = window.getSelection();
    if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
      result.anchorNode = sel.anchorNode;
      result.anchorOffset = sel.anchorOffset;
      result.focusNode = sel.focusNode;
      result.focusOffset = sel.focusOffset;
    }
  }
  return result
}

function restoreSelection(snapshot) {
  if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
  snapshot.activeElt.focus();
  if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
    var sel = window.getSelection(), range$$1 = document.createRange();
    range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
    range$$1.collapse(false);
    sel.removeAllRanges();
    sel.addRange(range$$1);
    sel.extend(snapshot.focusNode, snapshot.focusOffset);
  }
}

// Does the actual updating of the line display. Bails out
// (returning false) when there is nothing to be done and forced is
// false.
function updateDisplayIfNeeded(cm, update) {
  var display = cm.display, doc = cm.doc;

  if (update.editorIsHidden) {
    resetView(cm);
    return false
  }

  // Bail out if the visible area is already rendered and nothing changed.
  if (!update.force &&
      update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
      (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
      display.renderedView == display.view && countDirtyView(cm) == 0)
    { return false }

  if (maybeUpdateLineNumberWidth(cm)) {
    resetView(cm);
    update.dims = getDimensions(cm);
  }

  // Compute a suitable new viewport (from & to)
  var end = doc.first + doc.size;
  var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
  if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
  if (sawCollapsedSpans) {
    from = visualLineNo(cm.doc, from);
    to = visualLineEndNo(cm.doc, to);
  }

  var different = from != display.viewFrom || to != display.viewTo ||
    display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  adjustView(cm, from, to);

  display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  // Position the mover div to align with the current scroll position
  cm.display.mover.style.top = display.viewOffset + "px";

  var toUpdate = countDirtyView(cm);
  if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
      (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
    { return false }

  // For big changes, we hide the enclosing element during the
  // update, since that speeds up the operations on most browsers.
  var selSnapshot = selectionSnapshot(cm);
  if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
  patchDisplay(cm, display.updateLineNumbers, update.dims);
  if (toUpdate > 4) { display.lineDiv.style.display = ""; }
  display.renderedView = display.view;
  // There might have been a widget with a focused element that got
  // hidden or updated, if so re-focus it.
  restoreSelection(selSnapshot);

  // Prevent selection and cursors from interfering with the scroll
  // width and height.
  removeChildren(display.cursorDiv);
  removeChildren(display.selectionDiv);
  display.gutters.style.height = display.sizer.style.minHeight = 0;

  if (different) {
    display.lastWrapHeight = update.wrapperHeight;
    display.lastWrapWidth = update.wrapperWidth;
    startWorker(cm, 400);
  }

  display.updateLineNumbers = null;

  return true
}

function postUpdateDisplay(cm, update) {
  var viewport = update.viewport;

  for (var first = true;; first = false) {
    if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
      // Clip forced viewport to actual scrollable area.
      if (viewport && viewport.top != null)
        { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
      // Updated line heights might result in the drawn area not
      // actually covering the viewport. Keep looping until it does.
      update.visible = visibleLines(cm.display, cm.doc, viewport);
      if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
        { break }
    }
    if (!updateDisplayIfNeeded(cm, update)) { break }
    updateHeightsInViewport(cm);
    var barMeasure = measureForScrollbars(cm);
    updateSelection(cm);
    updateScrollbars(cm, barMeasure);
    setDocumentHeight(cm, barMeasure);
    update.force = false;
  }

  update.signal(cm, "update", cm);
  if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
    update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
    cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  }
}

function updateDisplaySimple(cm, viewport) {
  var update = new DisplayUpdate(cm, viewport);
  if (updateDisplayIfNeeded(cm, update)) {
    updateHeightsInViewport(cm);
    postUpdateDisplay(cm, update);
    var barMeasure = measureForScrollbars(cm);
    updateSelection(cm);
    updateScrollbars(cm, barMeasure);
    setDocumentHeight(cm, barMeasure);
    update.finish();
  }
}

// Sync the actual display DOM structure with display.view, removing
// nodes for lines that are no longer in view, and creating the ones
// that are not there yet, and updating the ones that are out of
// date.
function patchDisplay(cm, updateNumbersFrom, dims) {
  var display = cm.display, lineNumbers = cm.options.lineNumbers;
  var container = display.lineDiv, cur = container.firstChild;

  function rm(node) {
    var next = node.nextSibling;
    // Works around a throw-scroll bug in OS X Webkit
    if (webkit && mac && cm.display.currentWheelTarget == node)
      { node.style.display = "none"; }
    else
      { node.parentNode.removeChild(node); }
    return next
  }

  var view = display.view, lineN = display.viewFrom;
  // Loop over the elements in the view, syncing cur (the DOM nodes
  // in display.lineDiv) with the view as we go.
  for (var i = 0; i < view.length; i++) {
    var lineView = view[i];
    if (lineView.hidden) {
    } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
      var node = buildLineElement(cm, lineView, lineN, dims);
      container.insertBefore(node, cur);
    } else { // Already drawn
      while (cur != lineView.node) { cur = rm(cur); }
      var updateNumber = lineNumbers && updateNumbersFrom != null &&
        updateNumbersFrom <= lineN && lineView.lineNumber;
      if (lineView.changes) {
        if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
        updateLineForChanges(cm, lineView, lineN, dims);
      }
      if (updateNumber) {
        removeChildren(lineView.lineNumber);
        lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
      }
      cur = lineView.node.nextSibling;
    }
    lineN += lineView.size;
  }
  while (cur) { cur = rm(cur); }
}

function updateGutterSpace(cm) {
  var width = cm.display.gutters.offsetWidth;
  cm.display.sizer.style.marginLeft = width + "px";
}

function setDocumentHeight(cm, measure) {
  cm.display.sizer.style.minHeight = measure.docHeight + "px";
  cm.display.heightForcer.style.top = measure.docHeight + "px";
  cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
}

// Rebuild the gutter elements, ensure the margin to the left of the
// code matches their width.
function updateGutters(cm) {
  var gutters = cm.display.gutters, specs = cm.options.gutters;
  removeChildren(gutters);
  var i = 0;
  for (; i < specs.length; ++i) {
    var gutterClass = specs[i];
    var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
    if (gutterClass == "CodeMirror-linenumbers") {
      cm.display.lineGutter = gElt;
      gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
    }
  }
  gutters.style.display = i ? "" : "none";
  updateGutterSpace(cm);
}

// Make sure the gutters options contains the element
// "CodeMirror-linenumbers" when the lineNumbers option is true.
function setGuttersForLineNumbers(options) {
  var found = indexOf(options.gutters, "CodeMirror-linenumbers");
  if (found == -1 && options.lineNumbers) {
    options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
  } else if (found > -1 && !options.lineNumbers) {
    options.gutters = options.gutters.slice(0);
    options.gutters.splice(found, 1);
  }
}

// Since the delta values reported on mouse wheel events are
// unstandardized between browsers and even browser versions, and
// generally horribly unpredictable, this code starts by measuring
// the scroll effect that the first few mouse wheel events have,
// and, from that, detects the way it can convert deltas to pixel
// offsets afterwards.
//
// The reason we want to know the amount a wheel event will scroll
// is that it gives us a chance to update the display before the
// actual scrolling happens, reducing flickering.

var wheelSamples = 0;
var wheelPixelsPerUnit = null;
// Fill in a browser-detected starting value on browsers where we
// know one. These don't have to be accurate -- the result of them
// being wrong would just be a slight flicker on the first wheel
// scroll (if it is large enough).
if (ie) { wheelPixelsPerUnit = -.53; }
else if (gecko) { wheelPixelsPerUnit = 15; }
else if (chrome) { wheelPixelsPerUnit = -.7; }
else if (safari) { wheelPixelsPerUnit = -1/3; }

function wheelEventDelta(e) {
  var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
  if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
  else if (dy == null) { dy = e.wheelDelta; }
  return {x: dx, y: dy}
}
function wheelEventPixels(e) {
  var delta = wheelEventDelta(e);
  delta.x *= wheelPixelsPerUnit;
  delta.y *= wheelPixelsPerUnit;
  return delta
}

function onScrollWheel(cm, e) {
  var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;

  var display = cm.display, scroll = display.scroller;
  // Quit if there's nothing to scroll here
  var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  if (!(dx && canScrollX || dy && canScrollY)) { return }

  // Webkit browsers on OS X abort momentum scrolls when the target
  // of the scroll event is removed from the scrollable element.
  // This hack (see related code in patchDisplay) makes sure the
  // element is kept around.
  if (dy && mac && webkit) {
    outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
      for (var i = 0; i < view.length; i++) {
        if (view[i].node == cur) {
          cm.display.currentWheelTarget = cur;
          break outer
        }
      }
    }
  }

  // On some browsers, horizontal scrolling will cause redraws to
  // happen before the gutter has been realigned, causing it to
  // wriggle around in a most unseemly way. When we have an
  // estimated pixels/delta value, we just handle horizontal
  // scrolling entirely here. It'll be slightly off from native, but
  // better than glitching out.
  if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
    if (dy && canScrollY)
      { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }
    setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));
    // Only prevent default scrolling if vertical scrolling is
    // actually possible. Otherwise, it causes vertical scroll
    // jitter on OSX trackpads when deltaX is small and deltaY
    // is large (issue #3579)
    if (!dy || (dy && canScrollY))
      { e_preventDefault(e); }
    display.wheelStartX = null; // Abort measurement, if in progress
    return
  }

  // 'Project' the visible viewport to cover the area that is being
  // scrolled into view (if we know enough to estimate it).
  if (dy && wheelPixelsPerUnit != null) {
    var pixels = dy * wheelPixelsPerUnit;
    var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
    if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
    else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
    updateDisplaySimple(cm, {top: top, bottom: bot});
  }

  if (wheelSamples < 20) {
    if (display.wheelStartX == null) {
      display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
      display.wheelDX = dx; display.wheelDY = dy;
      setTimeout(function () {
        if (display.wheelStartX == null) { return }
        var movedX = scroll.scrollLeft - display.wheelStartX;
        var movedY = scroll.scrollTop - display.wheelStartY;
        var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
          (movedX && display.wheelDX && movedX / display.wheelDX);
        display.wheelStartX = display.wheelStartY = null;
        if (!sample) { return }
        wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
        ++wheelSamples;
      }, 200);
    } else {
      display.wheelDX += dx; display.wheelDY += dy;
    }
  }
}

// Selection objects are immutable. A new one is created every time
// the selection changes. A selection is one or more non-overlapping
// (and non-touching) ranges, sorted, and an integer that indicates
// which one is the primary selection (the one that's scrolled into
// view, that getCursor returns, etc).
var Selection = function(ranges, primIndex) {
  this.ranges = ranges;
  this.primIndex = primIndex;
};

Selection.prototype.primary = function () { return this.ranges[this.primIndex] };

Selection.prototype.equals = function (other) {
    var this$1 = this;

  if (other == this) { return true }
  if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  for (var i = 0; i < this.ranges.length; i++) {
    var here = this$1.ranges[i], there = other.ranges[i];
    if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  }
  return true
};

Selection.prototype.deepCopy = function () {
    var this$1 = this;

  var out = [];
  for (var i = 0; i < this.ranges.length; i++)
    { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); }
  return new Selection(out, this.primIndex)
};

Selection.prototype.somethingSelected = function () {
    var this$1 = this;

  for (var i = 0; i < this.ranges.length; i++)
    { if (!this$1.ranges[i].empty()) { return true } }
  return false
};

Selection.prototype.contains = function (pos, end) {
    var this$1 = this;

  if (!end) { end = pos; }
  for (var i = 0; i < this.ranges.length; i++) {
    var range = this$1.ranges[i];
    if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
      { return i }
  }
  return -1
};

var Range = function(anchor, head) {
  this.anchor = anchor; this.head = head;
};

Range.prototype.from = function () { return minPos(this.anchor, this.head) };
Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };

// Take an unsorted, potentially overlapping set of ranges, and
// build a selection out of it. 'Consumes' ranges array (modifying
// it).
function normalizeSelection(ranges, primIndex) {
  var prim = ranges[primIndex];
  ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
  primIndex = indexOf(ranges, prim);
  for (var i = 1; i < ranges.length; i++) {
    var cur = ranges[i], prev = ranges[i - 1];
    if (cmp(prev.to(), cur.from()) >= 0) {
      var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
      var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
      if (i <= primIndex) { --primIndex; }
      ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
    }
  }
  return new Selection(ranges, primIndex)
}

function simpleSelection(anchor, head) {
  return new Selection([new Range(anchor, head || anchor)], 0)
}

// Compute the position of the end of a change (its 'to' property
// refers to the pre-change end).
function changeEnd(change) {
  if (!change.text) { return change.to }
  return Pos(change.from.line + change.text.length - 1,
             lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
}

// Adjust a position to refer to the post-change position of the
// same text, or the end of the change if the change covers it.
function adjustForChange(pos, change) {
  if (cmp(pos, change.from) < 0) { return pos }
  if (cmp(pos, change.to) <= 0) { return changeEnd(change) }

  var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
  return Pos(line, ch)
}

function computeSelAfterChange(doc, change) {
  var out = [];
  for (var i = 0; i < doc.sel.ranges.length; i++) {
    var range = doc.sel.ranges[i];
    out.push(new Range(adjustForChange(range.anchor, change),
                       adjustForChange(range.head, change)));
  }
  return normalizeSelection(out, doc.sel.primIndex)
}

function offsetPos(pos, old, nw) {
  if (pos.line == old.line)
    { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  else
    { return Pos(nw.line + (pos.line - old.line), pos.ch) }
}

// Used by replaceSelections to allow moving the selection to the
// start or around the replaced test. Hint may be "start" or "around".
function computeReplacedSel(doc, changes, hint) {
  var out = [];
  var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  for (var i = 0; i < changes.length; i++) {
    var change = changes[i];
    var from = offsetPos(change.from, oldPrev, newPrev);
    var to = offsetPos(changeEnd(change), oldPrev, newPrev);
    oldPrev = change.to;
    newPrev = to;
    if (hint == "around") {
      var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
      out[i] = new Range(inv ? to : from, inv ? from : to);
    } else {
      out[i] = new Range(from, from);
    }
  }
  return new Selection(out, doc.sel.primIndex)
}

// Used to get the editor into a consistent state again when options change.

function loadMode(cm) {
  cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
  resetModeState(cm);
}

function resetModeState(cm) {
  cm.doc.iter(function (line) {
    if (line.stateAfter) { line.stateAfter = null; }
    if (line.styles) { line.styles = null; }
  });
  cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
  startWorker(cm, 100);
  cm.state.modeGen++;
  if (cm.curOp) { regChange(cm); }
}

// DOCUMENT DATA STRUCTURE

// By default, updates that start and end at the beginning of a line
// are treated specially, in order to make the association of line
// widgets and marker elements with the text behave more intuitive.
function isWholeLineUpdate(doc, change) {
  return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
    (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
}

// Perform a change on the document data structure.
function updateDoc(doc, change, markedSpans, estimateHeight$$1) {
  function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  function update(line, text, spans) {
    updateLine(line, text, spans, estimateHeight$$1);
    signalLater(line, "change", line, change);
  }
  function linesFor(start, end) {
    var result = [];
    for (var i = start; i < end; ++i)
      { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); }
    return result
  }

  var from = change.from, to = change.to, text = change.text;
  var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;

  // Adjust the line structure
  if (change.full) {
    doc.insert(0, linesFor(0, text.length));
    doc.remove(text.length, doc.size - text.length);
  } else if (isWholeLineUpdate(doc, change)) {
    // This is a whole-line replace. Treated specially to make
    // sure line objects move the way they are supposed to.
    var added = linesFor(0, text.length - 1);
    update(lastLine, lastLine.text, lastSpans);
    if (nlines) { doc.remove(from.line, nlines); }
    if (added.length) { doc.insert(from.line, added); }
  } else if (firstLine == lastLine) {
    if (text.length == 1) {
      update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
    } else {
      var added$1 = linesFor(1, text.length - 1);
      added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1));
      update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
      doc.insert(from.line + 1, added$1);
    }
  } else if (text.length == 1) {
    update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
    doc.remove(from.line + 1, nlines);
  } else {
    update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
    update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
    var added$2 = linesFor(1, text.length - 1);
    if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
    doc.insert(from.line + 1, added$2);
  }

  signalLater(doc, "change", doc, change);
}

// Call f for all linked documents.
function linkedDocs(doc, f, sharedHistOnly) {
  function propagate(doc, skip, sharedHist) {
    if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
      var rel = doc.linked[i];
      if (rel.doc == skip) { continue }
      var shared = sharedHist && rel.sharedHist;
      if (sharedHistOnly && !shared) { continue }
      f(rel.doc, shared);
      propagate(rel.doc, doc, shared);
    } }
  }
  propagate(doc, null, true);
}

// Attach a document to an editor.
function attachDoc(cm, doc) {
  if (doc.cm) { throw new Error("This document is already in use.") }
  cm.doc = doc;
  doc.cm = cm;
  estimateLineHeights(cm);
  loadMode(cm);
  setDirectionClass(cm);
  if (!cm.options.lineWrapping) { findMaxLine(cm); }
  cm.options.mode = doc.modeOption;
  regChange(cm);
}

function setDirectionClass(cm) {
  (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
}

function directionChanged(cm) {
  runInOp(cm, function () {
    setDirectionClass(cm);
    regChange(cm);
  });
}

function History(startGen) {
  // Arrays of change events and selections. Doing something adds an
  // event to done and clears undo. Undoing moves events from done
  // to undone, redoing moves them in the other direction.
  this.done = []; this.undone = [];
  this.undoDepth = Infinity;
  // Used to track when changes can be merged into a single undo
  // event
  this.lastModTime = this.lastSelTime = 0;
  this.lastOp = this.lastSelOp = null;
  this.lastOrigin = this.lastSelOrigin = null;
  // Used by the isClean() method
  this.generation = this.maxGeneration = startGen || 1;
}

// Create a history change event from an updateDoc-style change
// object.
function historyChangeFromChange(doc, change) {
  var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
  return histChange
}

// Pop all selection events off the end of a history array. Stop at
// a change event.
function clearSelectionEvents(array) {
  while (array.length) {
    var last = lst(array);
    if (last.ranges) { array.pop(); }
    else { break }
  }
}

// Find the top change event in the history. Pop off selection
// events that are in the way.
function lastChangeEvent(hist, force) {
  if (force) {
    clearSelectionEvents(hist.done);
    return lst(hist.done)
  } else if (hist.done.length && !lst(hist.done).ranges) {
    return lst(hist.done)
  } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
    hist.done.pop();
    return lst(hist.done)
  }
}

// Register a change in the history. Merges changes that are within
// a single operation, or are close together with an origin that
// allows merging (starting with "+") into a single event.
function addChangeToHistory(doc, change, selAfter, opId) {
  var hist = doc.history;
  hist.undone.length = 0;
  var time = +new Date, cur;
  var last;

  if ((hist.lastOp == opId ||
       hist.lastOrigin == change.origin && change.origin &&
       ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
        change.origin.charAt(0) == "*")) &&
      (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
    // Merge this change into the last event
    last = lst(cur.changes);
    if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
      // Optimized case for simple insertion -- don't want to add
      // new changesets for every character typed
      last.to = changeEnd(change);
    } else {
      // Add new sub-event
      cur.changes.push(historyChangeFromChange(doc, change));
    }
  } else {
    // Can not be merged, start a new event.
    var before = lst(hist.done);
    if (!before || !before.ranges)
      { pushSelectionToHistory(doc.sel, hist.done); }
    cur = {changes: [historyChangeFromChange(doc, change)],
           generation: hist.generation};
    hist.done.push(cur);
    while (hist.done.length > hist.undoDepth) {
      hist.done.shift();
      if (!hist.done[0].ranges) { hist.done.shift(); }
    }
  }
  hist.done.push(selAfter);
  hist.generation = ++hist.maxGeneration;
  hist.lastModTime = hist.lastSelTime = time;
  hist.lastOp = hist.lastSelOp = opId;
  hist.lastOrigin = hist.lastSelOrigin = change.origin;

  if (!last) { signal(doc, "historyAdded"); }
}

function selectionEventCanBeMerged(doc, origin, prev, sel) {
  var ch = origin.charAt(0);
  return ch == "*" ||
    ch == "+" &&
    prev.ranges.length == sel.ranges.length &&
    prev.somethingSelected() == sel.somethingSelected() &&
    new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
}

// Called whenever the selection changes, sets the new selection as
// the pending selection in the history, and pushes the old pending
// selection into the 'done' array when it was significantly
// different (in number of selected ranges, emptiness, or time).
function addSelectionToHistory(doc, sel, opId, options) {
  var hist = doc.history, origin = options && options.origin;

  // A new event is started when the previous origin does not match
  // the current, or the origins don't allow matching. Origins
  // starting with * are always merged, those starting with + are
  // merged when similar and close together in time.
  if (opId == hist.lastSelOp ||
      (origin && hist.lastSelOrigin == origin &&
       (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
        selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
    { hist.done[hist.done.length - 1] = sel; }
  else
    { pushSelectionToHistory(sel, hist.done); }

  hist.lastSelTime = +new Date;
  hist.lastSelOrigin = origin;
  hist.lastSelOp = opId;
  if (options && options.clearRedo !== false)
    { clearSelectionEvents(hist.undone); }
}

function pushSelectionToHistory(sel, dest) {
  var top = lst(dest);
  if (!(top && top.ranges && top.equals(sel)))
    { dest.push(sel); }
}

// Used to store marked span information in the history.
function attachLocalSpans(doc, change, from, to) {
  var existing = change["spans_" + doc.id], n = 0;
  doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
    if (line.markedSpans)
      { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
    ++n;
  });
}

// When un/re-doing restores text containing marked spans, those
// that have been explicitly cleared should not be restored.
function removeClearedSpans(spans) {
  if (!spans) { return null }
  var out;
  for (var i = 0; i < spans.length; ++i) {
    if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
    else if (out) { out.push(spans[i]); }
  }
  return !out ? spans : out.length ? out : null
}

// Retrieve and filter the old marked spans stored in a change event.
function getOldSpans(doc, change) {
  var found = change["spans_" + doc.id];
  if (!found) { return null }
  var nw = [];
  for (var i = 0; i < change.text.length; ++i)
    { nw.push(removeClearedSpans(found[i])); }
  return nw
}

// Used for un/re-doing changes from the history. Combines the
// result of computing the existing spans with the set of spans that
// existed in the history (so that deleting around a span and then
// undoing brings back the span).
function mergeOldSpans(doc, change) {
  var old = getOldSpans(doc, change);
  var stretched = stretchSpansOverChange(doc, change);
  if (!old) { return stretched }
  if (!stretched) { return old }

  for (var i = 0; i < old.length; ++i) {
    var oldCur = old[i], stretchCur = stretched[i];
    if (oldCur && stretchCur) {
      spans: for (var j = 0; j < stretchCur.length; ++j) {
        var span = stretchCur[j];
        for (var k = 0; k < oldCur.length; ++k)
          { if (oldCur[k].marker == span.marker) { continue spans } }
        oldCur.push(span);
      }
    } else if (stretchCur) {
      old[i] = stretchCur;
    }
  }
  return old
}

// Used both to provide a JSON-safe object in .getHistory, and, when
// detaching a document, to split the history in two
function copyHistoryArray(events, newGroup, instantiateSel) {
  var copy = [];
  for (var i = 0; i < events.length; ++i) {
    var event = events[i];
    if (event.ranges) {
      copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
      continue
    }
    var changes = event.changes, newChanges = [];
    copy.push({changes: newChanges});
    for (var j = 0; j < changes.length; ++j) {
      var change = changes[j], m = (void 0);
      newChanges.push({from: change.from, to: change.to, text: change.text});
      if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
        if (indexOf(newGroup, Number(m[1])) > -1) {
          lst(newChanges)[prop] = change[prop];
          delete change[prop];
        }
      } } }
    }
  }
  return copy
}

// The 'scroll' parameter given to many of these indicated whether
// the new cursor position should be scrolled into view after
// modifying the selection.

// If shift is held or the extend flag is set, extends a range to
// include a given position (and optionally a second position).
// Otherwise, simply returns the range between the given positions.
// Used for cursor motion and such.
function extendRange(range, head, other, extend) {
  if (extend) {
    var anchor = range.anchor;
    if (other) {
      var posBefore = cmp(head, anchor) < 0;
      if (posBefore != (cmp(other, anchor) < 0)) {
        anchor = head;
        head = other;
      } else if (posBefore != (cmp(head, other) < 0)) {
        head = other;
      }
    }
    return new Range(anchor, head)
  } else {
    return new Range(other || head, head)
  }
}

// Extend the primary selection range, discard the rest.
function extendSelection(doc, head, other, options, extend) {
  if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
  setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
}

// Extend all selections (pos is an array of selections with length
// equal the number of selections)
function extendSelections(doc, heads, options) {
  var out = [];
  var extend = doc.cm && (doc.cm.display.shift || doc.extend);
  for (var i = 0; i < doc.sel.ranges.length; i++)
    { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
  var newSel = normalizeSelection(out, doc.sel.primIndex);
  setSelection(doc, newSel, options);
}

// Updates a single range in the selection.
function replaceOneSelection(doc, i, range, options) {
  var ranges = doc.sel.ranges.slice(0);
  ranges[i] = range;
  setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
}

// Reset the selection to a single range.
function setSimpleSelection(doc, anchor, head, options) {
  setSelection(doc, simpleSelection(anchor, head), options);
}

// Give beforeSelectionChange handlers a change to influence a
// selection update.
function filterSelectionChange(doc, sel, options) {
  var obj = {
    ranges: sel.ranges,
    update: function(ranges) {
      var this$1 = this;

      this.ranges = [];
      for (var i = 0; i < ranges.length; i++)
        { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
                                   clipPos(doc, ranges[i].head)); }
    },
    origin: options && options.origin
  };
  signal(doc, "beforeSelectionChange", doc, obj);
  if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
  if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) }
  else { return sel }
}

function setSelectionReplaceHistory(doc, sel, options) {
  var done = doc.history.done, last = lst(done);
  if (last && last.ranges) {
    done[done.length - 1] = sel;
    setSelectionNoUndo(doc, sel, options);
  } else {
    setSelection(doc, sel, options);
  }
}

// Set a new selection.
function setSelection(doc, sel, options) {
  setSelectionNoUndo(doc, sel, options);
  addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
}

function setSelectionNoUndo(doc, sel, options) {
  if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
    { sel = filterSelectionChange(doc, sel, options); }

  var bias = options && options.bias ||
    (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));

  if (!(options && options.scroll === false) && doc.cm)
    { ensureCursorVisible(doc.cm); }
}

function setSelectionInner(doc, sel) {
  if (sel.equals(doc.sel)) { return }

  doc.sel = sel;

  if (doc.cm) {
    doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
    signalCursorActivity(doc.cm);
  }
  signalLater(doc, "cursorActivity", doc);
}

// Verify that the selection does not partially select any atomic
// marked ranges.
function reCheckSelection(doc) {
  setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
}

// Return a selection that does not partially select any atomic
// ranges.
function skipAtomicInSelection(doc, sel, bias, mayClear) {
  var out;
  for (var i = 0; i < sel.ranges.length; i++) {
    var range = sel.ranges[i];
    var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
    var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
    var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
    if (out || newAnchor != range.anchor || newHead != range.head) {
      if (!out) { out = sel.ranges.slice(0, i); }
      out[i] = new Range(newAnchor, newHead);
    }
  }
  return out ? normalizeSelection(out, sel.primIndex) : sel
}

function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  var line = getLine(doc, pos.line);
  if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
    var sp = line.markedSpans[i], m = sp.marker;
    if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
        (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
      if (mayClear) {
        signal(m, "beforeCursorEnter");
        if (m.explicitlyCleared) {
          if (!line.markedSpans) { break }
          else {--i; continue}
        }
      }
      if (!m.atomic) { continue }

      if (oldPos) {
        var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
        if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
          { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
        if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
          { return skipAtomicInner(doc, near, pos, dir, mayClear) }
      }

      var far = m.find(dir < 0 ? -1 : 1);
      if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
        { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
      return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
    }
  } }
  return pos
}

// Ensure a given position is not inside an atomic range.
function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  var dir = bias || 1;
  var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
      (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
      skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
      (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  if (!found) {
    doc.cantEdit = true;
    return Pos(doc.first, 0)
  }
  return found
}

function movePos(doc, pos, dir, line) {
  if (dir < 0 && pos.ch == 0) {
    if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
    else { return null }
  } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
    if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
    else { return null }
  } else {
    return new Pos(pos.line, pos.ch + dir)
  }
}

function selectAll(cm) {
  cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
}

// UPDATING

// Allow "beforeChange" event handlers to influence a change
function filterChange(doc, change, update) {
  var obj = {
    canceled: false,
    from: change.from,
    to: change.to,
    text: change.text,
    origin: change.origin,
    cancel: function () { return obj.canceled = true; }
  };
  if (update) { obj.update = function (from, to, text, origin) {
    if (from) { obj.from = clipPos(doc, from); }
    if (to) { obj.to = clipPos(doc, to); }
    if (text) { obj.text = text; }
    if (origin !== undefined) { obj.origin = origin; }
  }; }
  signal(doc, "beforeChange", doc, obj);
  if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }

  if (obj.canceled) { return null }
  return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
}

// Apply a change to a document, and add it to the document's
// history, and propagating it to all linked documents.
function makeChange(doc, change, ignoreReadOnly) {
  if (doc.cm) {
    if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
    if (doc.cm.state.suppressEdits) { return }
  }

  if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
    change = filterChange(doc, change, true);
    if (!change) { return }
  }

  // Possibly split or suppress the update based on the presence
  // of read-only spans in its range.
  var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  if (split) {
    for (var i = split.length - 1; i >= 0; --i)
      { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
  } else {
    makeChangeInner(doc, change);
  }
}

function makeChangeInner(doc, change) {
  if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  var selAfter = computeSelAfterChange(doc, change);
  addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);

  makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  var rebased = [];

  linkedDocs(doc, function (doc, sharedHist) {
    if (!sharedHist && indexOf(rebased, doc.history) == -1) {
      rebaseHist(doc.history, change);
      rebased.push(doc.history);
    }
    makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  });
}

// Revert a change stored in a document's history.
function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  var suppress = doc.cm && doc.cm.state.suppressEdits;
  if (suppress && !allowSelectionOnly) { return }

  var hist = doc.history, event, selAfter = doc.sel;
  var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;

  // Verify that there is a useable event (so that ctrl-z won't
  // needlessly clear selection events)
  var i = 0;
  for (; i < source.length; i++) {
    event = source[i];
    if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
      { break }
  }
  if (i == source.length) { return }
  hist.lastOrigin = hist.lastSelOrigin = null;

  for (;;) {
    event = source.pop();
    if (event.ranges) {
      pushSelectionToHistory(event, dest);
      if (allowSelectionOnly && !event.equals(doc.sel)) {
        setSelection(doc, event, {clearRedo: false});
        return
      }
      selAfter = event;
    } else if (suppress) {
      source.push(event);
      return
    } else { break }
  }

  // Build up a reverse change object to add to the opposite history
  // stack (redo when undoing, and vice versa).
  var antiChanges = [];
  pushSelectionToHistory(selAfter, dest);
  dest.push({changes: antiChanges, generation: hist.generation});
  hist.generation = event.generation || ++hist.maxGeneration;

  var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");

  var loop = function ( i ) {
    var change = event.changes[i];
    change.origin = type;
    if (filter && !filterChange(doc, change, false)) {
      source.length = 0;
      return {}
    }

    antiChanges.push(historyChangeFromChange(doc, change));

    var after = i ? computeSelAfterChange(doc, change) : lst(source);
    makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
    if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
    var rebased = [];

    // Propagate to the linked documents
    linkedDocs(doc, function (doc, sharedHist) {
      if (!sharedHist && indexOf(rebased, doc.history) == -1) {
        rebaseHist(doc.history, change);
        rebased.push(doc.history);
      }
      makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
    });
  };

  for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
    var returned = loop( i$1 );

    if ( returned ) return returned.v;
  }
}

// Sub-views need their line numbers shifted when text is added
// above or below them in the parent document.
function shiftDoc(doc, distance) {
  if (distance == 0) { return }
  doc.first += distance;
  doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
    Pos(range.anchor.line + distance, range.anchor.ch),
    Pos(range.head.line + distance, range.head.ch)
  ); }), doc.sel.primIndex);
  if (doc.cm) {
    regChange(doc.cm, doc.first, doc.first - distance, distance);
    for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
      { regLineChange(doc.cm, l, "gutter"); }
  }
}

// More lower-level change function, handling only a single document
// (not linked ones).
function makeChangeSingleDoc(doc, change, selAfter, spans) {
  if (doc.cm && !doc.cm.curOp)
    { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }

  if (change.to.line < doc.first) {
    shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
    return
  }
  if (change.from.line > doc.lastLine()) { return }

  // Clip the change to the size of this doc
  if (change.from.line < doc.first) {
    var shift = change.text.length - 1 - (doc.first - change.from.line);
    shiftDoc(doc, shift);
    change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
              text: [lst(change.text)], origin: change.origin};
  }
  var last = doc.lastLine();
  if (change.to.line > last) {
    change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
              text: [change.text[0]], origin: change.origin};
  }

  change.removed = getBetween(doc, change.from, change.to);

  if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
  if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
  else { updateDoc(doc, change, spans); }
  setSelectionNoUndo(doc, selAfter, sel_dontScroll);
}

// Handle the interaction of a change to a document with the editor
// that this document is part of.
function makeChangeSingleDocInEditor(cm, change, spans) {
  var doc = cm.doc, display = cm.display, from = change.from, to = change.to;

  var recomputeMaxLength = false, checkWidthStart = from.line;
  if (!cm.options.lineWrapping) {
    checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
    doc.iter(checkWidthStart, to.line + 1, function (line) {
      if (line == display.maxLine) {
        recomputeMaxLength = true;
        return true
      }
    });
  }

  if (doc.sel.contains(change.from, change.to) > -1)
    { signalCursorActivity(cm); }

  updateDoc(doc, change, spans, estimateHeight(cm));

  if (!cm.options.lineWrapping) {
    doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
      var len = lineLength(line);
      if (len > display.maxLineLength) {
        display.maxLine = line;
        display.maxLineLength = len;
        display.maxLineChanged = true;
        recomputeMaxLength = false;
      }
    });
    if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
  }

  retreatFrontier(doc, from.line);
  startWorker(cm, 400);

  var lendiff = change.text.length - (to.line - from.line) - 1;
  // Remember that these lines changed, for updating the display
  if (change.full)
    { regChange(cm); }
  else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
    { regLineChange(cm, from.line, "text"); }
  else
    { regChange(cm, from.line, to.line + 1, lendiff); }

  var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  if (changeHandler || changesHandler) {
    var obj = {
      from: from, to: to,
      text: change.text,
      removed: change.removed,
      origin: change.origin
    };
    if (changeHandler) { signalLater(cm, "change", cm, obj); }
    if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
  }
  cm.display.selForContextMenu = null;
}

function replaceRange(doc, code, from, to, origin) {
  if (!to) { to = from; }
  if (cmp(to, from) < 0) { var assign;
    (assign = [to, from], from = assign[0], to = assign[1]); }
  if (typeof code == "string") { code = doc.splitLines(code); }
  makeChange(doc, {from: from, to: to, text: code, origin: origin});
}

// Rebasing/resetting history to deal with externally-sourced changes

function rebaseHistSelSingle(pos, from, to, diff) {
  if (to < pos.line) {
    pos.line += diff;
  } else if (from < pos.line) {
    pos.line = from;
    pos.ch = 0;
  }
}

// Tries to rebase an array of history events given a change in the
// document. If the change touches the same lines as the event, the
// event, and everything 'behind' it, is discarded. If the change is
// before the event, the event's positions are updated. Uses a
// copy-on-write scheme for the positions, to avoid having to
// reallocate them all on every rebase, but also avoid problems with
// shared position objects being unsafely updated.
function rebaseHistArray(array, from, to, diff) {
  for (var i = 0; i < array.length; ++i) {
    var sub = array[i], ok = true;
    if (sub.ranges) {
      if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
      for (var j = 0; j < sub.ranges.length; j++) {
        rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
        rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
      }
      continue
    }
    for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
      var cur = sub.changes[j$1];
      if (to < cur.from.line) {
        cur.from = Pos(cur.from.line + diff, cur.from.ch);
        cur.to = Pos(cur.to.line + diff, cur.to.ch);
      } else if (from <= cur.to.line) {
        ok = false;
        break
      }
    }
    if (!ok) {
      array.splice(0, i + 1);
      i = 0;
    }
  }
}

function rebaseHist(hist, change) {
  var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  rebaseHistArray(hist.done, from, to, diff);
  rebaseHistArray(hist.undone, from, to, diff);
}

// Utility for applying a change to a line by handle or number,
// returning the number and optionally registering the line as
// changed.
function changeLine(doc, handle, changeType, op) {
  var no = handle, line = handle;
  if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
  else { no = lineNo(handle); }
  if (no == null) { return null }
  if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
  return line
}

// The document is represented as a BTree consisting of leaves, with
// chunk of lines in them, and branches, with up to ten leaves or
// other branch nodes below them. The top node is always a branch
// node, and is the document object itself (meaning it has
// additional methods and properties).
//
// All nodes have parent links. The tree is used both to go from
// line numbers to line objects, and to go from objects to numbers.
// It also indexes by height, and is used to convert between height
// and line object, and to find the total height of the document.
//
// See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html

function LeafChunk(lines) {
  var this$1 = this;

  this.lines = lines;
  this.parent = null;
  var height = 0;
  for (var i = 0; i < lines.length; ++i) {
    lines[i].parent = this$1;
    height += lines[i].height;
  }
  this.height = height;
}

LeafChunk.prototype = {
  chunkSize: function() { return this.lines.length },

  // Remove the n lines at offset 'at'.
  removeInner: function(at, n) {
    var this$1 = this;

    for (var i = at, e = at + n; i < e; ++i) {
      var line = this$1.lines[i];
      this$1.height -= line.height;
      cleanUpLine(line);
      signalLater(line, "delete");
    }
    this.lines.splice(at, n);
  },

  // Helper used to collapse a small branch into a single leaf.
  collapse: function(lines) {
    lines.push.apply(lines, this.lines);
  },

  // Insert the given array of lines at offset 'at', count them as
  // having the given height.
  insertInner: function(at, lines, height) {
    var this$1 = this;

    this.height += height;
    this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
    for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; }
  },

  // Used to iterate over a part of the tree.
  iterN: function(at, n, op) {
    var this$1 = this;

    for (var e = at + n; at < e; ++at)
      { if (op(this$1.lines[at])) { return true } }
  }
};

function BranchChunk(children) {
  var this$1 = this;

  this.children = children;
  var size = 0, height = 0;
  for (var i = 0; i < children.length; ++i) {
    var ch = children[i];
    size += ch.chunkSize(); height += ch.height;
    ch.parent = this$1;
  }
  this.size = size;
  this.height = height;
  this.parent = null;
}

BranchChunk.prototype = {
  chunkSize: function() { return this.size },

  removeInner: function(at, n) {
    var this$1 = this;

    this.size -= n;
    for (var i = 0; i < this.children.length; ++i) {
      var child = this$1.children[i], sz = child.chunkSize();
      if (at < sz) {
        var rm = Math.min(n, sz - at), oldHeight = child.height;
        child.removeInner(at, rm);
        this$1.height -= oldHeight - child.height;
        if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; }
        if ((n -= rm) == 0) { break }
        at = 0;
      } else { at -= sz; }
    }
    // If the result is smaller than 25 lines, ensure that it is a
    // single leaf node.
    if (this.size - n < 25 &&
        (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
      var lines = [];
      this.collapse(lines);
      this.children = [new LeafChunk(lines)];
      this.children[0].parent = this;
    }
  },

  collapse: function(lines) {
    var this$1 = this;

    for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); }
  },

  insertInner: function(at, lines, height) {
    var this$1 = this;

    this.size += lines.length;
    this.height += height;
    for (var i = 0; i < this.children.length; ++i) {
      var child = this$1.children[i], sz = child.chunkSize();
      if (at <= sz) {
        child.insertInner(at, lines, height);
        if (child.lines && child.lines.length > 50) {
          // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
          // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
          var remaining = child.lines.length % 25 + 25;
          for (var pos = remaining; pos < child.lines.length;) {
            var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
            child.height -= leaf.height;
            this$1.children.splice(++i, 0, leaf);
            leaf.parent = this$1;
          }
          child.lines = child.lines.slice(0, remaining);
          this$1.maybeSpill();
        }
        break
      }
      at -= sz;
    }
  },

  // When a node has grown, check whether it should be split.
  maybeSpill: function() {
    if (this.children.length <= 10) { return }
    var me = this;
    do {
      var spilled = me.children.splice(me.children.length - 5, 5);
      var sibling = new BranchChunk(spilled);
      if (!me.parent) { // Become the parent node
        var copy = new BranchChunk(me.children);
        copy.parent = me;
        me.children = [copy, sibling];
        me = copy;
     } else {
        me.size -= sibling.size;
        me.height -= sibling.height;
        var myIndex = indexOf(me.parent.children, me);
        me.parent.children.splice(myIndex + 1, 0, sibling);
      }
      sibling.parent = me.parent;
    } while (me.children.length > 10)
    me.parent.maybeSpill();
  },

  iterN: function(at, n, op) {
    var this$1 = this;

    for (var i = 0; i < this.children.length; ++i) {
      var child = this$1.children[i], sz = child.chunkSize();
      if (at < sz) {
        var used = Math.min(n, sz - at);
        if (child.iterN(at, used, op)) { return true }
        if ((n -= used) == 0) { break }
        at = 0;
      } else { at -= sz; }
    }
  }
};

// Line widgets are block elements displayed above or below a line.

var LineWidget = function(doc, node, options) {
  var this$1 = this;

  if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
    { this$1[opt] = options[opt]; } } }
  this.doc = doc;
  this.node = node;
};

LineWidget.prototype.clear = function () {
    var this$1 = this;

  var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  if (no == null || !ws) { return }
  for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } }
  if (!ws.length) { line.widgets = null; }
  var height = widgetHeight(this);
  updateLineHeight(line, Math.max(0, line.height - height));
  if (cm) {
    runInOp(cm, function () {
      adjustScrollWhenAboveVisible(cm, line, -height);
      regLineChange(cm, no, "widget");
    });
    signalLater(cm, "lineWidgetCleared", cm, this, no);
  }
};

LineWidget.prototype.changed = function () {
    var this$1 = this;

  var oldH = this.height, cm = this.doc.cm, line = this.line;
  this.height = null;
  var diff = widgetHeight(this) - oldH;
  if (!diff) { return }
  if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
  if (cm) {
    runInOp(cm, function () {
      cm.curOp.forceUpdate = true;
      adjustScrollWhenAboveVisible(cm, line, diff);
      signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
    });
  }
};
eventMixin(LineWidget);

function adjustScrollWhenAboveVisible(cm, line, diff) {
  if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
    { addToScrollTop(cm, diff); }
}

function addLineWidget(doc, handle, node, options) {
  var widget = new LineWidget(doc, node, options);
  var cm = doc.cm;
  if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
  changeLine(doc, handle, "widget", function (line) {
    var widgets = line.widgets || (line.widgets = []);
    if (widget.insertAt == null) { widgets.push(widget); }
    else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); }
    widget.line = line;
    if (cm && !lineIsHidden(doc, line)) {
      var aboveVisible = heightAtLine(line) < doc.scrollTop;
      updateLineHeight(line, line.height + widgetHeight(widget));
      if (aboveVisible) { addToScrollTop(cm, widget.height); }
      cm.curOp.forceUpdate = true;
    }
    return true
  });
  if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
  return widget
}

// TEXTMARKERS

// Created with markText and setBookmark methods. A TextMarker is a
// handle that can be used to clear or find a marked position in the
// document. Line objects hold arrays (markedSpans) containing
// {from, to, marker} object pointing to such marker objects, and
// indicating that such a marker is present on that line. Multiple
// lines may point to the same marker when it spans across lines.
// The spans will have null for their from/to properties when the
// marker continues beyond the start/end of the line. Markers have
// links back to the lines they currently touch.

// Collapsed markers have unique ids, in order to be able to order
// them, which is needed for uniquely determining an outer marker
// when they overlap (they may nest, but not partially overlap).
var nextMarkerId = 0;

var TextMarker = function(doc, type) {
  this.lines = [];
  this.type = type;
  this.doc = doc;
  this.id = ++nextMarkerId;
};

// Clear the marker.
TextMarker.prototype.clear = function () {
    var this$1 = this;

  if (this.explicitlyCleared) { return }
  var cm = this.doc.cm, withOp = cm && !cm.curOp;
  if (withOp) { startOperation(cm); }
  if (hasHandler(this, "clear")) {
    var found = this.find();
    if (found) { signalLater(this, "clear", found.from, found.to); }
  }
  var min = null, max = null;
  for (var i = 0; i < this.lines.length; ++i) {
    var line = this$1.lines[i];
    var span = getMarkedSpanFor(line.markedSpans, this$1);
    if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text"); }
    else if (cm) {
      if (span.to != null) { max = lineNo(line); }
      if (span.from != null) { min = lineNo(line); }
    }
    line.markedSpans = removeMarkedSpan(line.markedSpans, span);
    if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)
      { updateLineHeight(line, textHeight(cm.display)); }
  }
  if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
    var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual);
    if (len > cm.display.maxLineLength) {
      cm.display.maxLine = visual;
      cm.display.maxLineLength = len;
      cm.display.maxLineChanged = true;
    }
  } }

  if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
  this.lines.length = 0;
  this.explicitlyCleared = true;
  if (this.atomic && this.doc.cantEdit) {
    this.doc.cantEdit = false;
    if (cm) { reCheckSelection(cm.doc); }
  }
  if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
  if (withOp) { endOperation(cm); }
  if (this.parent) { this.parent.clear(); }
};

// Find the position of the marker in the document. Returns a {from,
// to} object by default. Side can be passed to get a specific side
// -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
// Pos objects returned contain a line object, rather than a line
// number (used to prevent looking up the same line twice).
TextMarker.prototype.find = function (side, lineObj) {
    var this$1 = this;

  if (side == null && this.type == "bookmark") { side = 1; }
  var from, to;
  for (var i = 0; i < this.lines.length; ++i) {
    var line = this$1.lines[i];
    var span = getMarkedSpanFor(line.markedSpans, this$1);
    if (span.from != null) {
      from = Pos(lineObj ? line : lineNo(line), span.from);
      if (side == -1) { return from }
    }
    if (span.to != null) {
      to = Pos(lineObj ? line : lineNo(line), span.to);
      if (side == 1) { return to }
    }
  }
  return from && {from: from, to: to}
};

// Signals that the marker's widget changed, and surrounding layout
// should be recomputed.
TextMarker.prototype.changed = function () {
    var this$1 = this;

  var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  if (!pos || !cm) { return }
  runInOp(cm, function () {
    var line = pos.line, lineN = lineNo(pos.line);
    var view = findViewForLine(cm, lineN);
    if (view) {
      clearLineMeasurementCacheFor(view);
      cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
    }
    cm.curOp.updateMaxLine = true;
    if (!lineIsHidden(widget.doc, line) && widget.height != null) {
      var oldHeight = widget.height;
      widget.height = null;
      var dHeight = widgetHeight(widget) - oldHeight;
      if (dHeight)
        { updateLineHeight(line, line.height + dHeight); }
    }
    signalLater(cm, "markerChanged", cm, this$1);
  });
};

TextMarker.prototype.attachLine = function (line) {
  if (!this.lines.length && this.doc.cm) {
    var op = this.doc.cm.curOp;
    if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
      { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
  }
  this.lines.push(line);
};

TextMarker.prototype.detachLine = function (line) {
  this.lines.splice(indexOf(this.lines, line), 1);
  if (!this.lines.length && this.doc.cm) {
    var op = this.doc.cm.curOp;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  }
};
eventMixin(TextMarker);

// Create a marker, wire it up to the right lines, and
function markText(doc, from, to, options, type) {
  // Shared markers (across linked documents) are handled separately
  // (markTextShared will call out to this again, once per
  // document).
  if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  // Ensure we are in an operation.
  if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }

  var marker = new TextMarker(doc, type), diff = cmp(from, to);
  if (options) { copyObj(options, marker, false); }
  // Don't connect empty markers unless clearWhenEmpty is false
  if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
    { return marker }
  if (marker.replacedWith) {
    // Showing up as a widget implies collapsed (widget replaces text)
    marker.collapsed = true;
    marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
    if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
    if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
  }
  if (marker.collapsed) {
    if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
        from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
      { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
    seeCollapsedSpans();
  }

  if (marker.addToHistory)
    { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }

  var curLine = from.line, cm = doc.cm, updateMaxLine;
  doc.iter(curLine, to.line + 1, function (line) {
    if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
      { updateMaxLine = true; }
    if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
    addMarkedSpan(line, new MarkedSpan(marker,
                                       curLine == from.line ? from.ch : null,
                                       curLine == to.line ? to.ch : null));
    ++curLine;
  });
  // lineIsHidden depends on the presence of the spans, so needs a second pass
  if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
    if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
  }); }

  if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }

  if (marker.readOnly) {
    seeReadOnlySpans();
    if (doc.history.done.length || doc.history.undone.length)
      { doc.clearHistory(); }
  }
  if (marker.collapsed) {
    marker.id = ++nextMarkerId;
    marker.atomic = true;
  }
  if (cm) {
    // Sync editor state
    if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
    if (marker.collapsed)
      { regChange(cm, from.line, to.line + 1); }
    else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
      { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
    if (marker.atomic) { reCheckSelection(cm.doc); }
    signalLater(cm, "markerAdded", cm, marker);
  }
  return marker
}

// SHARED TEXTMARKERS

// A shared marker spans multiple linked documents. It is
// implemented as a meta-marker-object controlling multiple normal
// markers.
var SharedTextMarker = function(markers, primary) {
  var this$1 = this;

  this.markers = markers;
  this.primary = primary;
  for (var i = 0; i < markers.length; ++i)
    { markers[i].parent = this$1; }
};

SharedTextMarker.prototype.clear = function () {
    var this$1 = this;

  if (this.explicitlyCleared) { return }
  this.explicitlyCleared = true;
  for (var i = 0; i < this.markers.length; ++i)
    { this$1.markers[i].clear(); }
  signalLater(this, "clear");
};

SharedTextMarker.prototype.find = function (side, lineObj) {
  return this.primary.find(side, lineObj)
};
eventMixin(SharedTextMarker);

function markTextShared(doc, from, to, options, type) {
  options = copyObj(options);
  options.shared = false;
  var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  var widget = options.widgetNode;
  linkedDocs(doc, function (doc) {
    if (widget) { options.widgetNode = widget.cloneNode(true); }
    markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
    for (var i = 0; i < doc.linked.length; ++i)
      { if (doc.linked[i].isParent) { return } }
    primary = lst(markers);
  });
  return new SharedTextMarker(markers, primary)
}

function findSharedMarkers(doc) {
  return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
}

function copySharedMarkers(doc, markers) {
  for (var i = 0; i < markers.length; i++) {
    var marker = markers[i], pos = marker.find();
    var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
    if (cmp(mFrom, mTo)) {
      var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
      marker.markers.push(subMark);
      subMark.parent = marker;
    }
  }
}

function detachSharedMarkers(markers) {
  var loop = function ( i ) {
    var marker = markers[i], linked = [marker.primary.doc];
    linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
    for (var j = 0; j < marker.markers.length; j++) {
      var subMarker = marker.markers[j];
      if (indexOf(linked, subMarker.doc) == -1) {
        subMarker.parent = null;
        marker.markers.splice(j--, 1);
      }
    }
  };

  for (var i = 0; i < markers.length; i++) loop( i );
}

var nextDocId = 0;
var Doc = function(text, mode, firstLine, lineSep, direction) {
  if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
  if (firstLine == null) { firstLine = 0; }

  BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  this.first = firstLine;
  this.scrollTop = this.scrollLeft = 0;
  this.cantEdit = false;
  this.cleanGeneration = 1;
  this.modeFrontier = this.highlightFrontier = firstLine;
  var start = Pos(firstLine, 0);
  this.sel = simpleSelection(start);
  this.history = new History(null);
  this.id = ++nextDocId;
  this.modeOption = mode;
  this.lineSep = lineSep;
  this.direction = (direction == "rtl") ? "rtl" : "ltr";
  this.extend = false;

  if (typeof text == "string") { text = this.splitLines(text); }
  updateDoc(this, {from: start, to: start, text: text});
  setSelection(this, simpleSelection(start), sel_dontScroll);
};

Doc.prototype = createObj(BranchChunk.prototype, {
  constructor: Doc,
  // Iterate over the document. Supports two forms -- with only one
  // argument, it calls that for each line in the document. With
  // three, it iterates over the range given by the first two (with
  // the second being non-inclusive).
  iter: function(from, to, op) {
    if (op) { this.iterN(from - this.first, to - from, op); }
    else { this.iterN(this.first, this.first + this.size, from); }
  },

  // Non-public interface for adding and removing lines.
  insert: function(at, lines) {
    var height = 0;
    for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
    this.insertInner(at - this.first, lines, height);
  },
  remove: function(at, n) { this.removeInner(at - this.first, n); },

  // From here, the methods are part of the public interface. Most
  // are also available from CodeMirror (editor) instances.

  getValue: function(lineSep) {
    var lines = getLines(this, this.first, this.first + this.size);
    if (lineSep === false) { return lines }
    return lines.join(lineSep || this.lineSeparator())
  },
  setValue: docMethodOp(function(code) {
    var top = Pos(this.first, 0), last = this.first + this.size - 1;
    makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
                      text: this.splitLines(code), origin: "setValue", full: true}, true);
    if (this.cm) { scrollToCoords(this.cm, 0, 0); }
    setSelection(this, simpleSelection(top), sel_dontScroll);
  }),
  replaceRange: function(code, from, to, origin) {
    from = clipPos(this, from);
    to = to ? clipPos(this, to) : from;
    replaceRange(this, code, from, to, origin);
  },
  getRange: function(from, to, lineSep) {
    var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
    if (lineSep === false) { return lines }
    return lines.join(lineSep || this.lineSeparator())
  },

  getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},

  getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  getLineNumber: function(line) {return lineNo(line)},

  getLineHandleVisualStart: function(line) {
    if (typeof line == "number") { line = getLine(this, line); }
    return visualLine(line)
  },

  lineCount: function() {return this.size},
  firstLine: function() {return this.first},
  lastLine: function() {return this.first + this.size - 1},

  clipPos: function(pos) {return clipPos(this, pos)},

  getCursor: function(start) {
    var range$$1 = this.sel.primary(), pos;
    if (start == null || start == "head") { pos = range$$1.head; }
    else if (start == "anchor") { pos = range$$1.anchor; }
    else if (start == "end" || start == "to" || start === false) { pos = range$$1.to(); }
    else { pos = range$$1.from(); }
    return pos
  },
  listSelections: function() { return this.sel.ranges },
  somethingSelected: function() {return this.sel.somethingSelected()},

  setCursor: docMethodOp(function(line, ch, options) {
    setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  }),
  setSelection: docMethodOp(function(anchor, head, options) {
    setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  }),
  extendSelection: docMethodOp(function(head, other, options) {
    extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  }),
  extendSelections: docMethodOp(function(heads, options) {
    extendSelections(this, clipPosArray(this, heads), options);
  }),
  extendSelectionsBy: docMethodOp(function(f, options) {
    var heads = map(this.sel.ranges, f);
    extendSelections(this, clipPosArray(this, heads), options);
  }),
  setSelections: docMethodOp(function(ranges, primary, options) {
    var this$1 = this;

    if (!ranges.length) { return }
    var out = [];
    for (var i = 0; i < ranges.length; i++)
      { out[i] = new Range(clipPos(this$1, ranges[i].anchor),
                         clipPos(this$1, ranges[i].head)); }
    if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
    setSelection(this, normalizeSelection(out, primary), options);
  }),
  addSelection: docMethodOp(function(anchor, head, options) {
    var ranges = this.sel.ranges.slice(0);
    ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
    setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
  }),

  getSelection: function(lineSep) {
    var this$1 = this;

    var ranges = this.sel.ranges, lines;
    for (var i = 0; i < ranges.length; i++) {
      var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
      lines = lines ? lines.concat(sel) : sel;
    }
    if (lineSep === false) { return lines }
    else { return lines.join(lineSep || this.lineSeparator()) }
  },
  getSelections: function(lineSep) {
    var this$1 = this;

    var parts = [], ranges = this.sel.ranges;
    for (var i = 0; i < ranges.length; i++) {
      var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
      if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); }
      parts[i] = sel;
    }
    return parts
  },
  replaceSelection: function(code, collapse, origin) {
    var dup = [];
    for (var i = 0; i < this.sel.ranges.length; i++)
      { dup[i] = code; }
    this.replaceSelections(dup, collapse, origin || "+input");
  },
  replaceSelections: docMethodOp(function(code, collapse, origin) {
    var this$1 = this;

    var changes = [], sel = this.sel;
    for (var i = 0; i < sel.ranges.length; i++) {
      var range$$1 = sel.ranges[i];
      changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin};
    }
    var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
    for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
      { makeChange(this$1, changes[i$1]); }
    if (newSel) { setSelectionReplaceHistory(this, newSel); }
    else if (this.cm) { ensureCursorVisible(this.cm); }
  }),
  undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),

  setExtending: function(val) {this.extend = val;},
  getExtending: function() {return this.extend},

  historySize: function() {
    var hist = this.history, done = 0, undone = 0;
    for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
    for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
    return {undo: done, redo: undone}
  },
  clearHistory: function() {this.history = new History(this.history.maxGeneration);},

  markClean: function() {
    this.cleanGeneration = this.changeGeneration(true);
  },
  changeGeneration: function(forceSplit) {
    if (forceSplit)
      { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
    return this.history.generation
  },
  isClean: function (gen) {
    return this.history.generation == (gen || this.cleanGeneration)
  },

  getHistory: function() {
    return {done: copyHistoryArray(this.history.done),
            undone: copyHistoryArray(this.history.undone)}
  },
  setHistory: function(histData) {
    var hist = this.history = new History(this.history.maxGeneration);
    hist.done = copyHistoryArray(histData.done.slice(0), null, true);
    hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  },

  setGutterMarker: docMethodOp(function(line, gutterID, value) {
    return changeLine(this, line, "gutter", function (line) {
      var markers = line.gutterMarkers || (line.gutterMarkers = {});
      markers[gutterID] = value;
      if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
      return true
    })
  }),

  clearGutter: docMethodOp(function(gutterID) {
    var this$1 = this;

    this.iter(function (line) {
      if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
        changeLine(this$1, line, "gutter", function () {
          line.gutterMarkers[gutterID] = null;
          if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
          return true
        });
      }
    });
  }),

  lineInfo: function(line) {
    var n;
    if (typeof line == "number") {
      if (!isLine(this, line)) { return null }
      n = line;
      line = getLine(this, line);
      if (!line) { return null }
    } else {
      n = lineNo(line);
      if (n == null) { return null }
    }
    return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
            textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
            widgets: line.widgets}
  },

  addLineClass: docMethodOp(function(handle, where, cls) {
    return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
      var prop = where == "text" ? "textClass"
               : where == "background" ? "bgClass"
               : where == "gutter" ? "gutterClass" : "wrapClass";
      if (!line[prop]) { line[prop] = cls; }
      else if (classTest(cls).test(line[prop])) { return false }
      else { line[prop] += " " + cls; }
      return true
    })
  }),
  removeLineClass: docMethodOp(function(handle, where, cls) {
    return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
      var prop = where == "text" ? "textClass"
               : where == "background" ? "bgClass"
               : where == "gutter" ? "gutterClass" : "wrapClass";
      var cur = line[prop];
      if (!cur) { return false }
      else if (cls == null) { line[prop] = null; }
      else {
        var found = cur.match(classTest(cls));
        if (!found) { return false }
        var end = found.index + found[0].length;
        line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
      }
      return true
    })
  }),

  addLineWidget: docMethodOp(function(handle, node, options) {
    return addLineWidget(this, handle, node, options)
  }),
  removeLineWidget: function(widget) { widget.clear(); },

  markText: function(from, to, options) {
    return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  },
  setBookmark: function(pos, options) {
    var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
                    insertLeft: options && options.insertLeft,
                    clearWhenEmpty: false, shared: options && options.shared,
                    handleMouseEvents: options && options.handleMouseEvents};
    pos = clipPos(this, pos);
    return markText(this, pos, pos, realOpts, "bookmark")
  },
  findMarksAt: function(pos) {
    pos = clipPos(this, pos);
    var markers = [], spans = getLine(this, pos.line).markedSpans;
    if (spans) { for (var i = 0; i < spans.length; ++i) {
      var span = spans[i];
      if ((span.from == null || span.from <= pos.ch) &&
          (span.to == null || span.to >= pos.ch))
        { markers.push(span.marker.parent || span.marker); }
    } }
    return markers
  },
  findMarks: function(from, to, filter) {
    from = clipPos(this, from); to = clipPos(this, to);
    var found = [], lineNo$$1 = from.line;
    this.iter(from.line, to.line + 1, function (line) {
      var spans = line.markedSpans;
      if (spans) { for (var i = 0; i < spans.length; i++) {
        var span = spans[i];
        if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to ||
              span.from == null && lineNo$$1 != from.line ||
              span.from != null && lineNo$$1 == to.line && span.from >= to.ch) &&
            (!filter || filter(span.marker)))
          { found.push(span.marker.parent || span.marker); }
      } }
      ++lineNo$$1;
    });
    return found
  },
  getAllMarks: function() {
    var markers = [];
    this.iter(function (line) {
      var sps = line.markedSpans;
      if (sps) { for (var i = 0; i < sps.length; ++i)
        { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
    });
    return markers
  },

  posFromIndex: function(off) {
    var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length;
    this.iter(function (line) {
      var sz = line.text.length + sepSize;
      if (sz > off) { ch = off; return true }
      off -= sz;
      ++lineNo$$1;
    });
    return clipPos(this, Pos(lineNo$$1, ch))
  },
  indexFromPos: function (coords) {
    coords = clipPos(this, coords);
    var index = coords.ch;
    if (coords.line < this.first || coords.ch < 0) { return 0 }
    var sepSize = this.lineSeparator().length;
    this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
      index += line.text.length + sepSize;
    });
    return index
  },

  copy: function(copyHistory) {
    var doc = new Doc(getLines(this, this.first, this.first + this.size),
                      this.modeOption, this.first, this.lineSep, this.direction);
    doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
    doc.sel = this.sel;
    doc.extend = false;
    if (copyHistory) {
      doc.history.undoDepth = this.history.undoDepth;
      doc.setHistory(this.getHistory());
    }
    return doc
  },

  linkedDoc: function(options) {
    if (!options) { options = {}; }
    var from = this.first, to = this.first + this.size;
    if (options.from != null && options.from > from) { from = options.from; }
    if (options.to != null && options.to < to) { to = options.to; }
    var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
    if (options.sharedHist) { copy.history = this.history
    ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
    copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
    copySharedMarkers(copy, findSharedMarkers(this));
    return copy
  },
  unlinkDoc: function(other) {
    var this$1 = this;

    if (other instanceof CodeMirror$1) { other = other.doc; }
    if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
      var link = this$1.linked[i];
      if (link.doc != other) { continue }
      this$1.linked.splice(i, 1);
      other.unlinkDoc(this$1);
      detachSharedMarkers(findSharedMarkers(this$1));
      break
    } }
    // If the histories were shared, split them again
    if (other.history == this.history) {
      var splitIds = [other.id];
      linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
      other.history = new History(null);
      other.history.done = copyHistoryArray(this.history.done, splitIds);
      other.history.undone = copyHistoryArray(this.history.undone, splitIds);
    }
  },
  iterLinkedDocs: function(f) {linkedDocs(this, f);},

  getMode: function() {return this.mode},
  getEditor: function() {return this.cm},

  splitLines: function(str) {
    if (this.lineSep) { return str.split(this.lineSep) }
    return splitLinesAuto(str)
  },
  lineSeparator: function() { return this.lineSep || "\n" },

  setDirection: docMethodOp(function (dir) {
    if (dir != "rtl") { dir = "ltr"; }
    if (dir == this.direction) { return }
    this.direction = dir;
    this.iter(function (line) { return line.order = null; });
    if (this.cm) { directionChanged(this.cm); }
  })
});

// Public alias.
Doc.prototype.eachLine = Doc.prototype.iter;

// Kludge to work around strange IE behavior where it'll sometimes
// re-fire a series of drag-related events right after the drop (#1551)
var lastDrop = 0;

function onDrop(e) {
  var cm = this;
  clearDragCursor(cm);
  if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
    { return }
  e_preventDefault(e);
  if (ie) { lastDrop = +new Date; }
  var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  if (!pos || cm.isReadOnly()) { return }
  // Might be a file drop, in which case we simply extract the text
  // and insert it.
  if (files && files.length && window.FileReader && window.File) {
    var n = files.length, text = Array(n), read = 0;
    var loadFile = function (file, i) {
      if (cm.options.allowDropFileTypes &&
          indexOf(cm.options.allowDropFileTypes, file.type) == -1)
        { return }

      var reader = new FileReader;
      reader.onload = operation(cm, function () {
        var content = reader.result;
        if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = ""; }
        text[i] = content;
        if (++read == n) {
          pos = clipPos(cm.doc, pos);
          var change = {from: pos, to: pos,
                        text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
                        origin: "paste"};
          makeChange(cm.doc, change);
          setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
        }
      });
      reader.readAsText(file);
    };
    for (var i = 0; i < n; ++i) { loadFile(files[i], i); }
  } else { // Normal drop
    // Don't do a replace if the drop happened inside of the selected text.
    if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
      cm.state.draggingText(e);
      // Ensure the editor is re-focused
      setTimeout(function () { return cm.display.input.focus(); }, 20);
      return
    }
    try {
      var text$1 = e.dataTransfer.getData("Text");
      if (text$1) {
        var selected;
        if (cm.state.draggingText && !cm.state.draggingText.copy)
          { selected = cm.listSelections(); }
        setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
        if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
          { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
        cm.replaceSelection(text$1, "around", "paste");
        cm.display.input.focus();
      }
    }
    catch(e){}
  }
}

function onDragStart(cm, e) {
  if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }

  e.dataTransfer.setData("Text", cm.getSelection());
  e.dataTransfer.effectAllowed = "copyMove";

  // Use dummy image instead of default browsers image.
  // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  if (e.dataTransfer.setDragImage && !safari) {
    var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
    img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
    if (presto) {
      img.width = img.height = 1;
      cm.display.wrapper.appendChild(img);
      // Force a relayout, or Opera won't use our image for some obscure reason
      img._top = img.offsetTop;
    }
    e.dataTransfer.setDragImage(img, 0, 0);
    if (presto) { img.parentNode.removeChild(img); }
  }
}

function onDragOver(cm, e) {
  var pos = posFromMouse(cm, e);
  if (!pos) { return }
  var frag = document.createDocumentFragment();
  drawSelectionCursor(cm, pos, frag);
  if (!cm.display.dragCursor) {
    cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
    cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  }
  removeChildrenAndAdd(cm.display.dragCursor, frag);
}

function clearDragCursor(cm) {
  if (cm.display.dragCursor) {
    cm.display.lineSpace.removeChild(cm.display.dragCursor);
    cm.display.dragCursor = null;
  }
}

// These must be handled carefully, because naively registering a
// handler for each editor will cause the editors to never be
// garbage collected.

function forEachCodeMirror(f) {
  if (!document.getElementsByClassName) { return }
  var byClass = document.getElementsByClassName("CodeMirror");
  for (var i = 0; i < byClass.length; i++) {
    var cm = byClass[i].CodeMirror;
    if (cm) { f(cm); }
  }
}

var globalsRegistered = false;
function ensureGlobalHandlers() {
  if (globalsRegistered) { return }
  registerGlobalHandlers();
  globalsRegistered = true;
}
function registerGlobalHandlers() {
  // When the window resizes, we need to refresh active editors.
  var resizeTimer;
  on(window, "resize", function () {
    if (resizeTimer == null) { resizeTimer = setTimeout(function () {
      resizeTimer = null;
      forEachCodeMirror(onResize);
    }, 100); }
  });
  // When the window loses focus, we want to show the editor as blurred
  on(window, "blur", function () { return forEachCodeMirror(onBlur); });
}
// Called when the window resizes
function onResize(cm) {
  var d = cm.display;
  // Might be a text scaling operation, clear size caches.
  d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  d.scrollbarsClipped = false;
  cm.setSize();
}

var keyNames = {
  3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete", 145: "ScrollLock",
  173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
};

// Number keys
for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
// Alphabetic keys
for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
// Function keys
for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }

var keyMap = {};

keyMap.basic = {
  "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  "Esc": "singleSelection"
};
// Note that the save and find-related commands aren't defined by
// default. User code or addons can define them. Unknown commands
// are simply ignored.
keyMap.pcDefault = {
  "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  "fallthrough": "basic"
};
// Very basic readline/emacs-style bindings, which are standard on Mac.
keyMap.emacsy = {
  "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  "Ctrl-O": "openLine"
};
keyMap.macDefault = {
  "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  "fallthrough": ["basic", "emacsy"]
};
keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;

// KEYMAP DISPATCH

function normalizeKeyName(name) {
  var parts = name.split(/-(?!$)/);
  name = parts[parts.length - 1];
  var alt, ctrl, shift, cmd;
  for (var i = 0; i < parts.length - 1; i++) {
    var mod = parts[i];
    if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
    else if (/^a(lt)?$/i.test(mod)) { alt = true; }
    else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
    else if (/^s(hift)?$/i.test(mod)) { shift = true; }
    else { throw new Error("Unrecognized modifier name: " + mod) }
  }
  if (alt) { name = "Alt-" + name; }
  if (ctrl) { name = "Ctrl-" + name; }
  if (cmd) { name = "Cmd-" + name; }
  if (shift) { name = "Shift-" + name; }
  return name
}

// This is a kludge to keep keymaps mostly working as raw objects
// (backwards compatibility) while at the same time support features
// like normalization and multi-stroke key bindings. It compiles a
// new normalized keymap, and then updates the old object to reflect
// this.
function normalizeKeyMap(keymap) {
  var copy = {};
  for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
    var value = keymap[keyname];
    if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
    if (value == "...") { delete keymap[keyname]; continue }

    var keys = map(keyname.split(" "), normalizeKeyName);
    for (var i = 0; i < keys.length; i++) {
      var val = (void 0), name = (void 0);
      if (i == keys.length - 1) {
        name = keys.join(" ");
        val = value;
      } else {
        name = keys.slice(0, i + 1).join(" ");
        val = "...";
      }
      var prev = copy[name];
      if (!prev) { copy[name] = val; }
      else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
    }
    delete keymap[keyname];
  } }
  for (var prop in copy) { keymap[prop] = copy[prop]; }
  return keymap
}

function lookupKey(key, map$$1, handle, context) {
  map$$1 = getKeyMap(map$$1);
  var found = map$$1.call ? map$$1.call(key, context) : map$$1[key];
  if (found === false) { return "nothing" }
  if (found === "...") { return "multi" }
  if (found != null && handle(found)) { return "handled" }

  if (map$$1.fallthrough) {
    if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]")
      { return lookupKey(key, map$$1.fallthrough, handle, context) }
    for (var i = 0; i < map$$1.fallthrough.length; i++) {
      var result = lookupKey(key, map$$1.fallthrough[i], handle, context);
      if (result) { return result }
    }
  }
}

// Modifier key presses don't count as 'real' key presses for the
// purpose of keymap fallthrough.
function isModifierKey(value) {
  var name = typeof value == "string" ? value : keyNames[value.keyCode];
  return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
}

function addModifierNames(name, event, noShift) {
  var base = name;
  if (event.altKey && base != "Alt") { name = "Alt-" + name; }
  if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
  if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; }
  if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
  return name
}

// Look up the name of a key as indicated by an event object.
function keyName(event, noShift) {
  if (presto && event.keyCode == 34 && event["char"]) { return false }
  var name = keyNames[event.keyCode];
  if (name == null || event.altGraphKey) { return false }
  // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
  // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
  if (event.keyCode == 3 && event.code) { name = event.code; }
  return addModifierNames(name, event, noShift)
}

function getKeyMap(val) {
  return typeof val == "string" ? keyMap[val] : val
}

// Helper for deleting text near the selection(s), used to implement
// backspace, delete, and similar functionality.
function deleteNearSelection(cm, compute) {
  var ranges = cm.doc.sel.ranges, kill = [];
  // Build up a set of ranges to kill first, merging overlapping
  // ranges.
  for (var i = 0; i < ranges.length; i++) {
    var toKill = compute(ranges[i]);
    while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
      var replaced = kill.pop();
      if (cmp(replaced.from, toKill.from) < 0) {
        toKill.from = replaced.from;
        break
      }
    }
    kill.push(toKill);
  }
  // Next, remove those actual ranges.
  runInOp(cm, function () {
    for (var i = kill.length - 1; i >= 0; i--)
      { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
    ensureCursorVisible(cm);
  });
}

function moveCharLogically(line, ch, dir) {
  var target = skipExtendingChars(line.text, ch + dir, dir);
  return target < 0 || target > line.text.length ? null : target
}

function moveLogically(line, start, dir) {
  var ch = moveCharLogically(line, start.ch, dir);
  return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
}

function endOfLine(visually, cm, lineObj, lineNo, dir) {
  if (visually) {
    var order = getOrder(lineObj, cm.doc.direction);
    if (order) {
      var part = dir < 0 ? lst(order) : order[0];
      var moveInStorageOrder = (dir < 0) == (part.level == 1);
      var sticky = moveInStorageOrder ? "after" : "before";
      var ch;
      // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
      // it could be that the last bidi part is not on the last visual line,
      // since visual lines contain content order-consecutive chunks.
      // Thus, in rtl, we are looking for the first (content-order) character
      // in the rtl chunk that is on the last line (that is, the same line
      // as the last (content-order) character).
      if (part.level > 0 || cm.doc.direction == "rtl") {
        var prep = prepareMeasureForLine(cm, lineObj);
        ch = dir < 0 ? lineObj.text.length - 1 : 0;
        var targetTop = measureCharPrepared(cm, prep, ch).top;
        ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
        if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
      } else { ch = dir < 0 ? part.to : part.from; }
      return new Pos(lineNo, ch, sticky)
    }
  }
  return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
}

function moveVisually(cm, line, start, dir) {
  var bidi = getOrder(line, cm.doc.direction);
  if (!bidi) { return moveLogically(line, start, dir) }
  if (start.ch >= line.text.length) {
    start.ch = line.text.length;
    start.sticky = "before";
  } else if (start.ch <= 0) {
    start.ch = 0;
    start.sticky = "after";
  }
  var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
  if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
    // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
    // nothing interesting happens.
    return moveLogically(line, start, dir)
  }

  var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
  var prep;
  var getWrappedLineExtent = function (ch) {
    if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
    prep = prep || prepareMeasureForLine(cm, line);
    return wrappedLineExtentChar(cm, line, prep, ch)
  };
  var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);

  if (cm.doc.direction == "rtl" || part.level == 1) {
    var moveInStorageOrder = (part.level == 1) == (dir < 0);
    var ch = mv(start, moveInStorageOrder ? 1 : -1);
    if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
      // Case 2: We move within an rtl part or in an rtl editor on the same visual line
      var sticky = moveInStorageOrder ? "before" : "after";
      return new Pos(start.line, ch, sticky)
    }
  }

  // Case 3: Could not move within this bidi part in this visual line, so leave
  // the current bidi part

  var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
    var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
      ? new Pos(start.line, mv(ch, 1), "before")
      : new Pos(start.line, ch, "after"); };

    for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
      var part = bidi[partPos];
      var moveInStorageOrder = (dir > 0) == (part.level != 1);
      var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
      if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
      ch = moveInStorageOrder ? part.from : mv(part.to, -1);
      if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
    }
  };

  // Case 3a: Look for other bidi parts on the same visual line
  var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
  if (res) { return res }

  // Case 3b: Look for other bidi parts on the next visual line
  var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
  if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
    res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
    if (res) { return res }
  }

  // Case 4: Nowhere to move
  return null
}

// Commands are parameter-less actions that can be performed on an
// editor, mostly used for keybindings.
var commands = {
  selectAll: selectAll,
  singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  killLine: function (cm) { return deleteNearSelection(cm, function (range) {
    if (range.empty()) {
      var len = getLine(cm.doc, range.head.line).text.length;
      if (range.head.ch == len && range.head.line < cm.lastLine())
        { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
      else
        { return {from: range.head, to: Pos(range.head.line, len)} }
    } else {
      return {from: range.from(), to: range.to()}
    }
  }); },
  deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
    from: Pos(range.from().line, 0),
    to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  }); }); },
  delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
    from: Pos(range.from().line, 0), to: range.from()
  }); }); },
  delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
    var top = cm.charCoords(range.head, "div").top + 5;
    var leftPos = cm.coordsChar({left: 0, top: top}, "div");
    return {from: leftPos, to: range.from()}
  }); },
  delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
    var top = cm.charCoords(range.head, "div").top + 5;
    var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
    return {from: range.from(), to: rightPos }
  }); },
  undo: function (cm) { return cm.undo(); },
  redo: function (cm) { return cm.redo(); },
  undoSelection: function (cm) { return cm.undoSelection(); },
  redoSelection: function (cm) { return cm.redoSelection(); },
  goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
    {origin: "+move", bias: 1}
  ); },
  goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
    {origin: "+move", bias: 1}
  ); },
  goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
    {origin: "+move", bias: -1}
  ); },
  goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
    var top = cm.cursorCoords(range.head, "div").top + 5;
    return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  }, sel_move); },
  goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
    var top = cm.cursorCoords(range.head, "div").top + 5;
    return cm.coordsChar({left: 0, top: top}, "div")
  }, sel_move); },
  goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
    var top = cm.cursorCoords(range.head, "div").top + 5;
    var pos = cm.coordsChar({left: 0, top: top}, "div");
    if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
    return pos
  }, sel_move); },
  goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  goLineDown: function (cm) { return cm.moveV(1, "line"); },
  goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  goPageDown: function (cm) { return cm.moveV(1, "page"); },
  goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  goCharRight: function (cm) { return cm.moveH(1, "char"); },
  goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  goWordRight: function (cm) { return cm.moveH(1, "word"); },
  delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
  delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  indentAuto: function (cm) { return cm.indentSelection("smart"); },
  indentMore: function (cm) { return cm.indentSelection("add"); },
  indentLess: function (cm) { return cm.indentSelection("subtract"); },
  insertTab: function (cm) { return cm.replaceSelection("\t"); },
  insertSoftTab: function (cm) {
    var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
    for (var i = 0; i < ranges.length; i++) {
      var pos = ranges[i].from();
      var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
      spaces.push(spaceStr(tabSize - col % tabSize));
    }
    cm.replaceSelections(spaces);
  },
  defaultTab: function (cm) {
    if (cm.somethingSelected()) { cm.indentSelection("add"); }
    else { cm.execCommand("insertTab"); }
  },
  // Swap the two chars left and right of each selection's head.
  // Move cursor behind the two swapped characters afterwards.
  //
  // Doesn't consider line feeds a character.
  // Doesn't scan more than one line above to find a character.
  // Doesn't do anything on an empty line.
  // Doesn't do anything with non-empty selections.
  transposeChars: function (cm) { return runInOp(cm, function () {
    var ranges = cm.listSelections(), newSel = [];
    for (var i = 0; i < ranges.length; i++) {
      if (!ranges[i].empty()) { continue }
      var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
      if (line) {
        if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
        if (cur.ch > 0) {
          cur = new Pos(cur.line, cur.ch + 1);
          cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
                          Pos(cur.line, cur.ch - 2), cur, "+transpose");
        } else if (cur.line > cm.doc.first) {
          var prev = getLine(cm.doc, cur.line - 1).text;
          if (prev) {
            cur = new Pos(cur.line, 1);
            cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
                            prev.charAt(prev.length - 1),
                            Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
          }
        }
      }
      newSel.push(new Range(cur, cur));
    }
    cm.setSelections(newSel);
  }); },
  newlineAndIndent: function (cm) { return runInOp(cm, function () {
    var sels = cm.listSelections();
    for (var i = sels.length - 1; i >= 0; i--)
      { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
    sels = cm.listSelections();
    for (var i$1 = 0; i$1 < sels.length; i$1++)
      { cm.indentLine(sels[i$1].from().line, null, true); }
    ensureCursorVisible(cm);
  }); },
  openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
};


function lineStart(cm, lineN) {
  var line = getLine(cm.doc, lineN);
  var visual = visualLine(line);
  if (visual != line) { lineN = lineNo(visual); }
  return endOfLine(true, cm, visual, lineN, 1)
}
function lineEnd(cm, lineN) {
  var line = getLine(cm.doc, lineN);
  var visual = visualLineEnd(line);
  if (visual != line) { lineN = lineNo(visual); }
  return endOfLine(true, cm, line, lineN, -1)
}
function lineStartSmart(cm, pos) {
  var start = lineStart(cm, pos.line);
  var line = getLine(cm.doc, start.line);
  var order = getOrder(line, cm.doc.direction);
  if (!order || order[0].level == 0) {
    var firstNonWS = Math.max(0, line.text.search(/\S/));
    var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
    return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  }
  return start
}

// Run a handler that was bound to a key.
function doHandleBinding(cm, bound, dropShift) {
  if (typeof bound == "string") {
    bound = commands[bound];
    if (!bound) { return false }
  }
  // Ensure previous input has been read, so that the handler sees a
  // consistent view of the document
  cm.display.input.ensurePolled();
  var prevShift = cm.display.shift, done = false;
  try {
    if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
    if (dropShift) { cm.display.shift = false; }
    done = bound(cm) != Pass;
  } finally {
    cm.display.shift = prevShift;
    cm.state.suppressEdits = false;
  }
  return done
}

function lookupKeyForEditor(cm, name, handle) {
  for (var i = 0; i < cm.state.keyMaps.length; i++) {
    var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
    if (result) { return result }
  }
  return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
    || lookupKey(name, cm.options.keyMap, handle, cm)
}

// Note that, despite the name, this function is also used to check
// for bound mouse clicks.

var stopSeq = new Delayed;

function dispatchKey(cm, name, e, handle) {
  var seq = cm.state.keySeq;
  if (seq) {
    if (isModifierKey(name)) { return "handled" }
    if (/\'$/.test(name))
      { cm.state.keySeq = null; }
    else
      { stopSeq.set(50, function () {
        if (cm.state.keySeq == seq) {
          cm.state.keySeq = null;
          cm.display.input.reset();
        }
      }); }
    if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
  }
  return dispatchKeyInner(cm, name, e, handle)
}

function dispatchKeyInner(cm, name, e, handle) {
  var result = lookupKeyForEditor(cm, name, handle);

  if (result == "multi")
    { cm.state.keySeq = name; }
  if (result == "handled")
    { signalLater(cm, "keyHandled", cm, name, e); }

  if (result == "handled" || result == "multi") {
    e_preventDefault(e);
    restartBlink(cm);
  }

  return !!result
}

// Handle a key from the keydown event.
function handleKeyBinding(cm, e) {
  var name = keyName(e, true);
  if (!name) { return false }

  if (e.shiftKey && !cm.state.keySeq) {
    // First try to resolve full name (including 'Shift-'). Failing
    // that, see if there is a cursor-motion command (starting with
    // 'go') bound to the keyname without 'Shift-'.
    return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
        || dispatchKey(cm, name, e, function (b) {
             if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
               { return doHandleBinding(cm, b) }
           })
  } else {
    return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  }
}

// Handle a key from the keypress event
function handleCharBinding(cm, e, ch) {
  return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
}

var lastStoppedKey = null;
function onKeyDown(e) {
  var cm = this;
  cm.curOp.focus = activeElt();
  if (signalDOMEvent(cm, e)) { return }
  // IE does strange things with escape.
  if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
  var code = e.keyCode;
  cm.display.shift = code == 16 || e.shiftKey;
  var handled = handleKeyBinding(cm, e);
  if (presto) {
    lastStoppedKey = handled ? code : null;
    // Opera has no cut event... we try to at least catch the key combo
    if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
      { cm.replaceSelection("", null, "cut"); }
  }

  // Turn mouse into crosshair when Alt is held on Mac.
  if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
    { showCrossHair(cm); }
}

function showCrossHair(cm) {
  var lineDiv = cm.display.lineDiv;
  addClass(lineDiv, "CodeMirror-crosshair");

  function up(e) {
    if (e.keyCode == 18 || !e.altKey) {
      rmClass(lineDiv, "CodeMirror-crosshair");
      off(document, "keyup", up);
      off(document, "mouseover", up);
    }
  }
  on(document, "keyup", up);
  on(document, "mouseover", up);
}

function onKeyUp(e) {
  if (e.keyCode == 16) { this.doc.sel.shift = false; }
  signalDOMEvent(this, e);
}

function onKeyPress(e) {
  var cm = this;
  if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  var keyCode = e.keyCode, charCode = e.charCode;
  if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  // Some browsers fire keypress events for backspace
  if (ch == "\x08") { return }
  if (handleCharBinding(cm, e, ch)) { return }
  cm.display.input.onKeyPress(e);
}

var DOUBLECLICK_DELAY = 400;

var PastClick = function(time, pos, button) {
  this.time = time;
  this.pos = pos;
  this.button = button;
};

PastClick.prototype.compare = function (time, pos, button) {
  return this.time + DOUBLECLICK_DELAY > time &&
    cmp(pos, this.pos) == 0 && button == this.button
};

var lastClick;
var lastDoubleClick;
function clickRepeat(pos, button) {
  var now = +new Date;
  if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
    lastClick = lastDoubleClick = null;
    return "triple"
  } else if (lastClick && lastClick.compare(now, pos, button)) {
    lastDoubleClick = new PastClick(now, pos, button);
    lastClick = null;
    return "double"
  } else {
    lastClick = new PastClick(now, pos, button);
    lastDoubleClick = null;
    return "single"
  }
}

// A mouse down can be a single click, double click, triple click,
// start of selection drag, start of text drag, new cursor
// (ctrl-click), rectangle drag (alt-drag), or xwin
// middle-click-paste. Or it might be a click on something we should
// not interfere with, such as a scrollbar or widget.
function onMouseDown(e) {
  var cm = this, display = cm.display;
  if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  display.input.ensurePolled();
  display.shift = e.shiftKey;

  if (eventInWidget(display, e)) {
    if (!webkit) {
      // Briefly turn off draggability, to allow widgets to do
      // normal dragging things.
      display.scroller.draggable = false;
      setTimeout(function () { return display.scroller.draggable = true; }, 100);
    }
    return
  }
  if (clickInGutter(cm, e)) { return }
  var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
  window.focus();

  // #3261: make sure, that we're not starting a second selection
  if (button == 1 && cm.state.selectingText)
    { cm.state.selectingText(e); }

  if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }

  if (button == 1) {
    if (pos) { leftButtonDown(cm, pos, repeat, e); }
    else if (e_target(e) == display.scroller) { e_preventDefault(e); }
  } else if (button == 2) {
    if (pos) { extendSelection(cm.doc, pos); }
    setTimeout(function () { return display.input.focus(); }, 20);
  } else if (button == 3) {
    if (captureRightClick) { onContextMenu(cm, e); }
    else { delayBlurEvent(cm); }
  }
}

function handleMappedButton(cm, button, pos, repeat, event) {
  var name = "Click";
  if (repeat == "double") { name = "Double" + name; }
  else if (repeat == "triple") { name = "Triple" + name; }
  name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;

  return dispatchKey(cm,  addModifierNames(name, event), event, function (bound) {
    if (typeof bound == "string") { bound = commands[bound]; }
    if (!bound) { return false }
    var done = false;
    try {
      if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
      done = bound(cm, pos) != Pass;
    } finally {
      cm.state.suppressEdits = false;
    }
    return done
  })
}

function configureMouse(cm, repeat, event) {
  var option = cm.getOption("configureMouse");
  var value = option ? option(cm, repeat, event) : {};
  if (value.unit == null) {
    var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
    value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
  }
  if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
  if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
  if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
  return value
}

function leftButtonDown(cm, pos, repeat, event) {
  if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
  else { cm.curOp.focus = activeElt(); }

  var behavior = configureMouse(cm, repeat, event);

  var sel = cm.doc.sel, contained;
  if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
      repeat == "single" && (contained = sel.contains(pos)) > -1 &&
      (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
      (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
    { leftButtonStartDrag(cm, event, pos, behavior); }
  else
    { leftButtonSelect(cm, event, pos, behavior); }
}

// Start a text drag. When it ends, see if any dragging actually
// happen, and treat as a click if it didn't.
function leftButtonStartDrag(cm, event, pos, behavior) {
  var display = cm.display, moved = false;
  var dragEnd = operation(cm, function (e) {
    if (webkit) { display.scroller.draggable = false; }
    cm.state.draggingText = false;
    off(display.wrapper.ownerDocument, "mouseup", dragEnd);
    off(display.wrapper.ownerDocument, "mousemove", mouseMove);
    off(display.scroller, "dragstart", dragStart);
    off(display.scroller, "drop", dragEnd);
    if (!moved) {
      e_preventDefault(e);
      if (!behavior.addNew)
        { extendSelection(cm.doc, pos, null, null, behavior.extend); }
      // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
      if (webkit || ie && ie_version == 9)
        { setTimeout(function () {display.wrapper.ownerDocument.body.focus(); display.input.focus();}, 20); }
      else
        { display.input.focus(); }
    }
  });
  var mouseMove = function(e2) {
    moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
  };
  var dragStart = function () { return moved = true; };
  // Let the drag handler handle this.
  if (webkit) { display.scroller.draggable = true; }
  cm.state.draggingText = dragEnd;
  dragEnd.copy = !behavior.moveOnDrag;
  // IE's approach to draggable
  if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
  on(display.wrapper.ownerDocument, "mouseup", dragEnd);
  on(display.wrapper.ownerDocument, "mousemove", mouseMove);
  on(display.scroller, "dragstart", dragStart);
  on(display.scroller, "drop", dragEnd);

  delayBlurEvent(cm);
  setTimeout(function () { return display.input.focus(); }, 20);
}

function rangeForUnit(cm, pos, unit) {
  if (unit == "char") { return new Range(pos, pos) }
  if (unit == "word") { return cm.findWordAt(pos) }
  if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  var result = unit(cm, pos);
  return new Range(result.from, result.to)
}

// Normal selection, as opposed to text dragging.
function leftButtonSelect(cm, event, start, behavior) {
  var display = cm.display, doc = cm.doc;
  e_preventDefault(event);

  var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  if (behavior.addNew && !behavior.extend) {
    ourIndex = doc.sel.contains(start);
    if (ourIndex > -1)
      { ourRange = ranges[ourIndex]; }
    else
      { ourRange = new Range(start, start); }
  } else {
    ourRange = doc.sel.primary();
    ourIndex = doc.sel.primIndex;
  }

  if (behavior.unit == "rectangle") {
    if (!behavior.addNew) { ourRange = new Range(start, start); }
    start = posFromMouse(cm, event, true, true);
    ourIndex = -1;
  } else {
    var range$$1 = rangeForUnit(cm, start, behavior.unit);
    if (behavior.extend)
      { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); }
    else
      { ourRange = range$$1; }
  }

  if (!behavior.addNew) {
    ourIndex = 0;
    setSelection(doc, new Selection([ourRange], 0), sel_mouse);
    startSel = doc.sel;
  } else if (ourIndex == -1) {
    ourIndex = ranges.length;
    setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
                 {scroll: false, origin: "*mouse"});
  } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
    setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
                 {scroll: false, origin: "*mouse"});
    startSel = doc.sel;
  } else {
    replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  }

  var lastPos = start;
  function extendTo(pos) {
    if (cmp(lastPos, pos) == 0) { return }
    lastPos = pos;

    if (behavior.unit == "rectangle") {
      var ranges = [], tabSize = cm.options.tabSize;
      var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
      var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
      var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
      for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
           line <= end; line++) {
        var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
        if (left == right)
          { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
        else if (text.length > leftPos)
          { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
      }
      if (!ranges.length) { ranges.push(new Range(start, start)); }
      setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
                   {origin: "*mouse", scroll: false});
      cm.scrollIntoView(pos);
    } else {
      var oldRange = ourRange;
      var range$$1 = rangeForUnit(cm, pos, behavior.unit);
      var anchor = oldRange.anchor, head;
      if (cmp(range$$1.anchor, anchor) > 0) {
        head = range$$1.head;
        anchor = minPos(oldRange.from(), range$$1.anchor);
      } else {
        head = range$$1.anchor;
        anchor = maxPos(oldRange.to(), range$$1.head);
      }
      var ranges$1 = startSel.ranges.slice(0);
      ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
      setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse);
    }
  }

  var editorSize = display.wrapper.getBoundingClientRect();
  // Used to ensure timeout re-tries don't fire when another extend
  // happened in the meantime (clearTimeout isn't reliable -- at
  // least on Chrome, the timeouts still happen even when cleared,
  // if the clear happens after their scheduled firing time).
  var counter = 0;

  function extend(e) {
    var curCount = ++counter;
    var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
    if (!cur) { return }
    if (cmp(cur, lastPos) != 0) {
      cm.curOp.focus = activeElt();
      extendTo(cur);
      var visible = visibleLines(display, doc);
      if (cur.line >= visible.to || cur.line < visible.from)
        { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
    } else {
      var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
      if (outside) { setTimeout(operation(cm, function () {
        if (counter != curCount) { return }
        display.scroller.scrollTop += outside;
        extend(e);
      }), 50); }
    }
  }

  function done(e) {
    cm.state.selectingText = false;
    counter = Infinity;
    e_preventDefault(e);
    display.input.focus();
    off(display.wrapper.ownerDocument, "mousemove", move);
    off(display.wrapper.ownerDocument, "mouseup", up);
    doc.history.lastSelOrigin = null;
  }

  var move = operation(cm, function (e) {
    if (e.buttons === 0 || !e_button(e)) { done(e); }
    else { extend(e); }
  });
  var up = operation(cm, done);
  cm.state.selectingText = up;
  on(display.wrapper.ownerDocument, "mousemove", move);
  on(display.wrapper.ownerDocument, "mouseup", up);
}

// Used when mouse-selecting to adjust the anchor to the proper side
// of a bidi jump depending on the visual position of the head.
function bidiSimplify(cm, range$$1) {
  var anchor = range$$1.anchor;
  var head = range$$1.head;
  var anchorLine = getLine(cm.doc, anchor.line);
  if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range$$1 }
  var order = getOrder(anchorLine);
  if (!order) { return range$$1 }
  var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
  if (part.from != anchor.ch && part.to != anchor.ch) { return range$$1 }
  var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
  if (boundary == 0 || boundary == order.length) { return range$$1 }

  // Compute the relative visual position of the head compared to the
  // anchor (<0 is to the left, >0 to the right)
  var leftSide;
  if (head.line != anchor.line) {
    leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
  } else {
    var headIndex = getBidiPartAt(order, head.ch, head.sticky);
    var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
    if (headIndex == boundary - 1 || headIndex == boundary)
      { leftSide = dir < 0; }
    else
      { leftSide = dir > 0; }
  }

  var usePart = order[boundary + (leftSide ? -1 : 0)];
  var from = leftSide == (usePart.level == 1);
  var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
  return anchor.ch == ch && anchor.sticky == sticky ? range$$1 : new Range(new Pos(anchor.line, ch, sticky), head)
}


// Determines whether an event happened in the gutter, and fires the
// handlers for the corresponding event.
function gutterEvent(cm, e, type, prevent) {
  var mX, mY;
  if (e.touches) {
    mX = e.touches[0].clientX;
    mY = e.touches[0].clientY;
  } else {
    try { mX = e.clientX; mY = e.clientY; }
    catch(e) { return false }
  }
  if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  if (prevent) { e_preventDefault(e); }

  var display = cm.display;
  var lineBox = display.lineDiv.getBoundingClientRect();

  if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  mY -= lineBox.top - display.viewOffset;

  for (var i = 0; i < cm.options.gutters.length; ++i) {
    var g = display.gutters.childNodes[i];
    if (g && g.getBoundingClientRect().right >= mX) {
      var line = lineAtHeight(cm.doc, mY);
      var gutter = cm.options.gutters[i];
      signal(cm, type, cm, line, gutter, e);
      return e_defaultPrevented(e)
    }
  }
}

function clickInGutter(cm, e) {
  return gutterEvent(cm, e, "gutterClick", true)
}

// CONTEXT MENU HANDLING

// To make the context menu work, we need to briefly unhide the
// textarea (making it as unobtrusive as possible) to let the
// right-click take effect on it.
function onContextMenu(cm, e) {
  if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  if (signalDOMEvent(cm, e, "contextmenu")) { return }
  cm.display.input.onContextMenu(e);
}

function contextMenuInGutter(cm, e) {
  if (!hasHandler(cm, "gutterContextMenu")) { return false }
  return gutterEvent(cm, e, "gutterContextMenu", false)
}

function themeChanged(cm) {
  cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
    cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  clearCaches(cm);
}

var Init = {toString: function(){return "CodeMirror.Init"}};

var defaults = {};
var optionHandlers = {};

function defineOptions(CodeMirror) {
  var optionHandlers = CodeMirror.optionHandlers;

  function option(name, deflt, handle, notOnInit) {
    CodeMirror.defaults[name] = deflt;
    if (handle) { optionHandlers[name] =
      notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
  }

  CodeMirror.defineOption = option;

  // Passed to option handlers when there is no old value.
  CodeMirror.Init = Init;

  // These two are, on init, called from the constructor because they
  // have to be initialized before the editor can start at all.
  option("value", "", function (cm, val) { return cm.setValue(val); }, true);
  option("mode", null, function (cm, val) {
    cm.doc.modeOption = val;
    loadMode(cm);
  }, true);

  option("indentUnit", 2, loadMode, true);
  option("indentWithTabs", false);
  option("smartIndent", true);
  option("tabSize", 4, function (cm) {
    resetModeState(cm);
    clearCaches(cm);
    regChange(cm);
  }, true);

  option("lineSeparator", null, function (cm, val) {
    cm.doc.lineSep = val;
    if (!val) { return }
    var newBreaks = [], lineNo = cm.doc.first;
    cm.doc.iter(function (line) {
      for (var pos = 0;;) {
        var found = line.text.indexOf(val, pos);
        if (found == -1) { break }
        pos = found + val.length;
        newBreaks.push(Pos(lineNo, found));
      }
      lineNo++;
    });
    for (var i = newBreaks.length - 1; i >= 0; i--)
      { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
  });
  option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) {
    cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
    if (old != Init) { cm.refresh(); }
  });
  option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
  option("electricChars", true);
  option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
    throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  }, true);
  option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
  option("rtlMoveVisually", !windows);
  option("wholeLineUpdateBefore", true);

  option("theme", "default", function (cm) {
    themeChanged(cm);
    guttersChanged(cm);
  }, true);
  option("keyMap", "default", function (cm, val, old) {
    var next = getKeyMap(val);
    var prev = old != Init && getKeyMap(old);
    if (prev && prev.detach) { prev.detach(cm, next); }
    if (next.attach) { next.attach(cm, prev || null); }
  });
  option("extraKeys", null);
  option("configureMouse", null);

  option("lineWrapping", false, wrappingChanged, true);
  option("gutters", [], function (cm) {
    setGuttersForLineNumbers(cm.options);
    guttersChanged(cm);
  }, true);
  option("fixedGutter", true, function (cm, val) {
    cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
    cm.refresh();
  }, true);
  option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
  option("scrollbarStyle", "native", function (cm) {
    initScrollbars(cm);
    updateScrollbars(cm);
    cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
    cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  }, true);
  option("lineNumbers", false, function (cm) {
    setGuttersForLineNumbers(cm.options);
    guttersChanged(cm);
  }, true);
  option("firstLineNumber", 1, guttersChanged, true);
  option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true);
  option("showCursorWhenSelecting", false, updateSelection, true);

  option("resetSelectionOnContextMenu", true);
  option("lineWiseCopyCut", true);
  option("pasteLinesPerSelection", true);

  option("readOnly", false, function (cm, val) {
    if (val == "nocursor") {
      onBlur(cm);
      cm.display.input.blur();
    }
    cm.display.input.readOnlyChanged(val);
  });
  option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
  option("dragDrop", true, dragDropChanged);
  option("allowDropFileTypes", null);

  option("cursorBlinkRate", 530);
  option("cursorScrollMargin", 0);
  option("cursorHeight", 1, updateSelection, true);
  option("singleCursorHeightPerLine", true, updateSelection, true);
  option("workTime", 100);
  option("workDelay", 100);
  option("flattenSpans", true, resetModeState, true);
  option("addModeClass", false, resetModeState, true);
  option("pollInterval", 100);
  option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
  option("historyEventDelay", 1250);
  option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
  option("maxHighlightLength", 10000, resetModeState, true);
  option("moveInputWithCursor", true, function (cm, val) {
    if (!val) { cm.display.input.resetPosition(); }
  });

  option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
  option("autofocus", null);
  option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
}

function guttersChanged(cm) {
  updateGutters(cm);
  regChange(cm);
  alignHorizontally(cm);
}

function dragDropChanged(cm, value, old) {
  var wasOn = old && old != Init;
  if (!value != !wasOn) {
    var funcs = cm.display.dragFunctions;
    var toggle = value ? on : off;
    toggle(cm.display.scroller, "dragstart", funcs.start);
    toggle(cm.display.scroller, "dragenter", funcs.enter);
    toggle(cm.display.scroller, "dragover", funcs.over);
    toggle(cm.display.scroller, "dragleave", funcs.leave);
    toggle(cm.display.scroller, "drop", funcs.drop);
  }
}

function wrappingChanged(cm) {
  if (cm.options.lineWrapping) {
    addClass(cm.display.wrapper, "CodeMirror-wrap");
    cm.display.sizer.style.minWidth = "";
    cm.display.sizerWidth = null;
  } else {
    rmClass(cm.display.wrapper, "CodeMirror-wrap");
    findMaxLine(cm);
  }
  estimateLineHeights(cm);
  regChange(cm);
  clearCaches(cm);
  setTimeout(function () { return updateScrollbars(cm); }, 100);
}

// A CodeMirror instance represents an editor. This is the object
// that user code is usually dealing with.

function CodeMirror$1(place, options) {
  var this$1 = this;

  if (!(this instanceof CodeMirror$1)) { return new CodeMirror$1(place, options) }

  this.options = options = options ? copyObj(options) : {};
  // Determine effective options based on given values and defaults.
  copyObj(defaults, options, false);
  setGuttersForLineNumbers(options);

  var doc = options.value;
  if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
  else if (options.mode) { doc.modeOption = options.mode; }
  this.doc = doc;

  var input = new CodeMirror$1.inputStyles[options.inputStyle](this);
  var display = this.display = new Display(place, doc, input);
  display.wrapper.CodeMirror = this;
  updateGutters(this);
  themeChanged(this);
  if (options.lineWrapping)
    { this.display.wrapper.className += " CodeMirror-wrap"; }
  initScrollbars(this);

  this.state = {
    keyMaps: [],  // stores maps added by addKeyMap
    overlays: [], // highlighting overlays, as added by addOverlay
    modeGen: 0,   // bumped when mode/overlay changes, used to invalidate highlighting info
    overwrite: false,
    delayingBlurEvent: false,
    focused: false,
    suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
    pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
    selectingText: false,
    draggingText: false,
    highlight: new Delayed(), // stores highlight worker timeout
    keySeq: null,  // Unfinished key sequence
    specialChars: null
  };

  if (options.autofocus && !mobile) { display.input.focus(); }

  // Override magic textarea content restore that IE sometimes does
  // on our hidden textarea on reload
  if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }

  registerEventHandlers(this);
  ensureGlobalHandlers();

  startOperation(this);
  this.curOp.forceUpdate = true;
  attachDoc(this, doc);

  if ((options.autofocus && !mobile) || this.hasFocus())
    { setTimeout(bind(onFocus, this), 20); }
  else
    { onBlur(this); }

  for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
    { optionHandlers[opt](this$1, options[opt], Init); } }
  maybeUpdateLineNumberWidth(this);
  if (options.finishInit) { options.finishInit(this); }
  for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); }
  endOperation(this);
  // Suppress optimizelegibility in Webkit, since it breaks text
  // measuring on line wrapping boundaries.
  if (webkit && options.lineWrapping &&
      getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
    { display.lineDiv.style.textRendering = "auto"; }
}

// The default configuration options.
CodeMirror$1.defaults = defaults;
// Functions to run when options are changed.
CodeMirror$1.optionHandlers = optionHandlers;

// Attach the necessary event handlers when initializing the editor
function registerEventHandlers(cm) {
  var d = cm.display;
  on(d.scroller, "mousedown", operation(cm, onMouseDown));
  // Older IE's will not fire a second mousedown for a double click
  if (ie && ie_version < 11)
    { on(d.scroller, "dblclick", operation(cm, function (e) {
      if (signalDOMEvent(cm, e)) { return }
      var pos = posFromMouse(cm, e);
      if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
      e_preventDefault(e);
      var word = cm.findWordAt(pos);
      extendSelection(cm.doc, word.anchor, word.head);
    })); }
  else
    { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
  // Some browsers fire contextmenu *after* opening the menu, at
  // which point we can't mess with it anymore. Context menu is
  // handled in onMouseDown for these browsers.
  if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }); }

  // Used to suppress mouse event handling when a touch happens
  var touchFinished, prevTouch = {end: 0};
  function finishTouch() {
    if (d.activeTouch) {
      touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
      prevTouch = d.activeTouch;
      prevTouch.end = +new Date;
    }
  }
  function isMouseLikeTouchEvent(e) {
    if (e.touches.length != 1) { return false }
    var touch = e.touches[0];
    return touch.radiusX <= 1 && touch.radiusY <= 1
  }
  function farAway(touch, other) {
    if (other.left == null) { return true }
    var dx = other.left - touch.left, dy = other.top - touch.top;
    return dx * dx + dy * dy > 20 * 20
  }
  on(d.scroller, "touchstart", function (e) {
    if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
      d.input.ensurePolled();
      clearTimeout(touchFinished);
      var now = +new Date;
      d.activeTouch = {start: now, moved: false,
                       prev: now - prevTouch.end <= 300 ? prevTouch : null};
      if (e.touches.length == 1) {
        d.activeTouch.left = e.touches[0].pageX;
        d.activeTouch.top = e.touches[0].pageY;
      }
    }
  });
  on(d.scroller, "touchmove", function () {
    if (d.activeTouch) { d.activeTouch.moved = true; }
  });
  on(d.scroller, "touchend", function (e) {
    var touch = d.activeTouch;
    if (touch && !eventInWidget(d, e) && touch.left != null &&
        !touch.moved && new Date - touch.start < 300) {
      var pos = cm.coordsChar(d.activeTouch, "page"), range;
      if (!touch.prev || farAway(touch, touch.prev)) // Single tap
        { range = new Range(pos, pos); }
      else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
        { range = cm.findWordAt(pos); }
      else // Triple tap
        { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
      cm.setSelection(range.anchor, range.head);
      cm.focus();
      e_preventDefault(e);
    }
    finishTouch();
  });
  on(d.scroller, "touchcancel", finishTouch);

  // Sync scrolling between fake scrollbars and real scrollable
  // area, ensure viewport is updated when scrolling.
  on(d.scroller, "scroll", function () {
    if (d.scroller.clientHeight) {
      updateScrollTop(cm, d.scroller.scrollTop);
      setScrollLeft(cm, d.scroller.scrollLeft, true);
      signal(cm, "scroll", cm);
    }
  });

  // Listen to wheel events in order to try and update the viewport on time.
  on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
  on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });

  // Prevent wrapper from ever scrolling
  on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });

  d.dragFunctions = {
    enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
    over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
    start: function (e) { return onDragStart(cm, e); },
    drop: operation(cm, onDrop),
    leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  };

  var inp = d.input.getField();
  on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
  on(inp, "keydown", operation(cm, onKeyDown));
  on(inp, "keypress", operation(cm, onKeyPress));
  on(inp, "focus", function (e) { return onFocus(cm, e); });
  on(inp, "blur", function (e) { return onBlur(cm, e); });
}

var initHooks = [];
CodeMirror$1.defineInitHook = function (f) { return initHooks.push(f); };

// Indent the given line. The how parameter can be "smart",
// "add"/null, "subtract", or "prev". When aggressive is false
// (typically set to true for forced single-line indents), empty
// lines are not indented, and places where the mode returns Pass
// are left alone.
function indentLine(cm, n, how, aggressive) {
  var doc = cm.doc, state;
  if (how == null) { how = "add"; }
  if (how == "smart") {
    // Fall back to "prev" when the mode doesn't have an indentation
    // method.
    if (!doc.mode.indent) { how = "prev"; }
    else { state = getContextBefore(cm, n).state; }
  }

  var tabSize = cm.options.tabSize;
  var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  if (line.stateAfter) { line.stateAfter = null; }
  var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  if (!aggressive && !/\S/.test(line.text)) {
    indentation = 0;
    how = "not";
  } else if (how == "smart") {
    indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
    if (indentation == Pass || indentation > 150) {
      if (!aggressive) { return }
      how = "prev";
    }
  }
  if (how == "prev") {
    if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
    else { indentation = 0; }
  } else if (how == "add") {
    indentation = curSpace + cm.options.indentUnit;
  } else if (how == "subtract") {
    indentation = curSpace - cm.options.indentUnit;
  } else if (typeof how == "number") {
    indentation = curSpace + how;
  }
  indentation = Math.max(0, indentation);

  var indentString = "", pos = 0;
  if (cm.options.indentWithTabs)
    { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
  if (pos < indentation) { indentString += spaceStr(indentation - pos); }

  if (indentString != curSpaceString) {
    replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
    line.stateAfter = null;
    return true
  } else {
    // Ensure that, if the cursor was in the whitespace at the start
    // of the line, it is moved to the end of that space.
    for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
      var range = doc.sel.ranges[i$1];
      if (range.head.line == n && range.head.ch < curSpaceString.length) {
        var pos$1 = Pos(n, curSpaceString.length);
        replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
        break
      }
    }
  }
}

// This will be set to a {lineWise: bool, text: [string]} object, so
// that, when pasting, we know what kind of selections the copied
// text was made out of.
var lastCopied = null;

function setLastCopied(newLastCopied) {
  lastCopied = newLastCopied;
}

function applyTextInput(cm, inserted, deleted, sel, origin) {
  var doc = cm.doc;
  cm.display.shift = false;
  if (!sel) { sel = doc.sel; }

  var paste = cm.state.pasteIncoming || origin == "paste";
  var textLines = splitLinesAuto(inserted), multiPaste = null;
  // When pasting N lines into N selections, insert one line per selection
  if (paste && sel.ranges.length > 1) {
    if (lastCopied && lastCopied.text.join("\n") == inserted) {
      if (sel.ranges.length % lastCopied.text.length == 0) {
        multiPaste = [];
        for (var i = 0; i < lastCopied.text.length; i++)
          { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
      }
    } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
      multiPaste = map(textLines, function (l) { return [l]; });
    }
  }

  var updateInput;
  // Normal behavior is to insert the new text into every selection
  for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
    var range$$1 = sel.ranges[i$1];
    var from = range$$1.from(), to = range$$1.to();
    if (range$$1.empty()) {
      if (deleted && deleted > 0) // Handle deletion
        { from = Pos(from.line, from.ch - deleted); }
      else if (cm.state.overwrite && !paste) // Handle overwrite
        { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
      else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
        { from = to = Pos(from.line, 0); }
    }
    updateInput = cm.curOp.updateInput;
    var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
                       origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
    makeChange(cm.doc, changeEvent);
    signalLater(cm, "inputRead", cm, changeEvent);
  }
  if (inserted && !paste)
    { triggerElectric(cm, inserted); }

  ensureCursorVisible(cm);
  cm.curOp.updateInput = updateInput;
  cm.curOp.typing = true;
  cm.state.pasteIncoming = cm.state.cutIncoming = false;
}

function handlePaste(e, cm) {
  var pasted = e.clipboardData && e.clipboardData.getData("Text");
  if (pasted) {
    e.preventDefault();
    if (!cm.isReadOnly() && !cm.options.disableInput)
      { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
    return true
  }
}

function triggerElectric(cm, inserted) {
  // When an 'electric' character is inserted, immediately trigger a reindent
  if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  var sel = cm.doc.sel;

  for (var i = sel.ranges.length - 1; i >= 0; i--) {
    var range$$1 = sel.ranges[i];
    if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue }
    var mode = cm.getModeAt(range$$1.head);
    var indented = false;
    if (mode.electricChars) {
      for (var j = 0; j < mode.electricChars.length; j++)
        { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
          indented = indentLine(cm, range$$1.head.line, "smart");
          break
        } }
    } else if (mode.electricInput) {
      if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch)))
        { indented = indentLine(cm, range$$1.head.line, "smart"); }
    }
    if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); }
  }
}

function copyableRanges(cm) {
  var text = [], ranges = [];
  for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
    var line = cm.doc.sel.ranges[i].head.line;
    var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
    ranges.push(lineRange);
    text.push(cm.getRange(lineRange.anchor, lineRange.head));
  }
  return {text: text, ranges: ranges}
}

function disableBrowserMagic(field, spellcheck) {
  field.setAttribute("autocorrect", "off");
  field.setAttribute("autocapitalize", "off");
  field.setAttribute("spellcheck", !!spellcheck);
}

function hiddenTextarea() {
  var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
  var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  // The textarea is kept positioned near the cursor to prevent the
  // fact that it'll be scrolled into view on input from scrolling
  // our fake cursor out of view. On webkit, when wrap=off, paste is
  // very slow. So make the area wide instead.
  if (webkit) { te.style.width = "1000px"; }
  else { te.setAttribute("wrap", "off"); }
  // If border: 0; -- iOS fails to open keyboard (issue #1287)
  if (ios) { te.style.border = "1px solid black"; }
  disableBrowserMagic(te);
  return div
}

// The publicly visible API. Note that methodOp(f) means
// 'wrap f in an operation, performed on its `this` parameter'.

// This is not the complete set of editor methods. Most of the
// methods defined on the Doc type are also injected into
// CodeMirror.prototype, for backwards compatibility and
// convenience.

var addEditorMethods = function(CodeMirror) {
  var optionHandlers = CodeMirror.optionHandlers;

  var helpers = CodeMirror.helpers = {};

  CodeMirror.prototype = {
    constructor: CodeMirror,
    focus: function(){window.focus(); this.display.input.focus();},

    setOption: function(option, value) {
      var options = this.options, old = options[option];
      if (options[option] == value && option != "mode") { return }
      options[option] = value;
      if (optionHandlers.hasOwnProperty(option))
        { operation(this, optionHandlers[option])(this, value, old); }
      signal(this, "optionChange", this, option);
    },

    getOption: function(option) {return this.options[option]},
    getDoc: function() {return this.doc},

    addKeyMap: function(map$$1, bottom) {
      this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1));
    },
    removeKeyMap: function(map$$1) {
      var maps = this.state.keyMaps;
      for (var i = 0; i < maps.length; ++i)
        { if (maps[i] == map$$1 || maps[i].name == map$$1) {
          maps.splice(i, 1);
          return true
        } }
    },

    addOverlay: methodOp(function(spec, options) {
      var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
      if (mode.startState) { throw new Error("Overlays may not be stateful.") }
      insertSorted(this.state.overlays,
                   {mode: mode, modeSpec: spec, opaque: options && options.opaque,
                    priority: (options && options.priority) || 0},
                   function (overlay) { return overlay.priority; });
      this.state.modeGen++;
      regChange(this);
    }),
    removeOverlay: methodOp(function(spec) {
      var this$1 = this;

      var overlays = this.state.overlays;
      for (var i = 0; i < overlays.length; ++i) {
        var cur = overlays[i].modeSpec;
        if (cur == spec || typeof spec == "string" && cur.name == spec) {
          overlays.splice(i, 1);
          this$1.state.modeGen++;
          regChange(this$1);
          return
        }
      }
    }),

    indentLine: methodOp(function(n, dir, aggressive) {
      if (typeof dir != "string" && typeof dir != "number") {
        if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
        else { dir = dir ? "add" : "subtract"; }
      }
      if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
    }),
    indentSelection: methodOp(function(how) {
      var this$1 = this;

      var ranges = this.doc.sel.ranges, end = -1;
      for (var i = 0; i < ranges.length; i++) {
        var range$$1 = ranges[i];
        if (!range$$1.empty()) {
          var from = range$$1.from(), to = range$$1.to();
          var start = Math.max(end, from.line);
          end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
          for (var j = start; j < end; ++j)
            { indentLine(this$1, j, how); }
          var newRanges = this$1.doc.sel.ranges;
          if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
            { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
        } else if (range$$1.head.line > end) {
          indentLine(this$1, range$$1.head.line, how, true);
          end = range$$1.head.line;
          if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); }
        }
      }
    }),

    // Fetch the parser token for a given character. Useful for hacks
    // that want to inspect the mode state (say, for completion).
    getTokenAt: function(pos, precise) {
      return takeToken(this, pos, precise)
    },

    getLineTokens: function(line, precise) {
      return takeToken(this, Pos(line), precise, true)
    },

    getTokenTypeAt: function(pos) {
      pos = clipPos(this.doc, pos);
      var styles = getLineStyles(this, getLine(this.doc, pos.line));
      var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
      var type;
      if (ch == 0) { type = styles[2]; }
      else { for (;;) {
        var mid = (before + after) >> 1;
        if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
        else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
        else { type = styles[mid * 2 + 2]; break }
      } }
      var cut = type ? type.indexOf("overlay ") : -1;
      return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
    },

    getModeAt: function(pos) {
      var mode = this.doc.mode;
      if (!mode.innerMode) { return mode }
      return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
    },

    getHelper: function(pos, type) {
      return this.getHelpers(pos, type)[0]
    },

    getHelpers: function(pos, type) {
      var this$1 = this;

      var found = [];
      if (!helpers.hasOwnProperty(type)) { return found }
      var help = helpers[type], mode = this.getModeAt(pos);
      if (typeof mode[type] == "string") {
        if (help[mode[type]]) { found.push(help[mode[type]]); }
      } else if (mode[type]) {
        for (var i = 0; i < mode[type].length; i++) {
          var val = help[mode[type][i]];
          if (val) { found.push(val); }
        }
      } else if (mode.helperType && help[mode.helperType]) {
        found.push(help[mode.helperType]);
      } else if (help[mode.name]) {
        found.push(help[mode.name]);
      }
      for (var i$1 = 0; i$1 < help._global.length; i$1++) {
        var cur = help._global[i$1];
        if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)
          { found.push(cur.val); }
      }
      return found
    },

    getStateAfter: function(line, precise) {
      var doc = this.doc;
      line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
      return getContextBefore(this, line + 1, precise).state
    },

    cursorCoords: function(start, mode) {
      var pos, range$$1 = this.doc.sel.primary();
      if (start == null) { pos = range$$1.head; }
      else if (typeof start == "object") { pos = clipPos(this.doc, start); }
      else { pos = start ? range$$1.from() : range$$1.to(); }
      return cursorCoords(this, pos, mode || "page")
    },

    charCoords: function(pos, mode) {
      return charCoords(this, clipPos(this.doc, pos), mode || "page")
    },

    coordsChar: function(coords, mode) {
      coords = fromCoordSystem(this, coords, mode || "page");
      return coordsChar(this, coords.left, coords.top)
    },

    lineAtHeight: function(height, mode) {
      height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
      return lineAtHeight(this.doc, height + this.display.viewOffset)
    },
    heightAtLine: function(line, mode, includeWidgets) {
      var end = false, lineObj;
      if (typeof line == "number") {
        var last = this.doc.first + this.doc.size - 1;
        if (line < this.doc.first) { line = this.doc.first; }
        else if (line > last) { line = last; end = true; }
        lineObj = getLine(this.doc, line);
      } else {
        lineObj = line;
      }
      return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
        (end ? this.doc.height - heightAtLine(lineObj) : 0)
    },

    defaultTextHeight: function() { return textHeight(this.display) },
    defaultCharWidth: function() { return charWidth(this.display) },

    getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},

    addWidget: function(pos, node, scroll, vert, horiz) {
      var display = this.display;
      pos = cursorCoords(this, clipPos(this.doc, pos));
      var top = pos.bottom, left = pos.left;
      node.style.position = "absolute";
      node.setAttribute("cm-ignore-events", "true");
      this.display.input.setUneditable(node);
      display.sizer.appendChild(node);
      if (vert == "over") {
        top = pos.top;
      } else if (vert == "above" || vert == "near") {
        var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
        hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
        // Default to positioning above (if specified and possible); otherwise default to positioning below
        if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
          { top = pos.top - node.offsetHeight; }
        else if (pos.bottom + node.offsetHeight <= vspace)
          { top = pos.bottom; }
        if (left + node.offsetWidth > hspace)
          { left = hspace - node.offsetWidth; }
      }
      node.style.top = top + "px";
      node.style.left = node.style.right = "";
      if (horiz == "right") {
        left = display.sizer.clientWidth - node.offsetWidth;
        node.style.right = "0px";
      } else {
        if (horiz == "left") { left = 0; }
        else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
        node.style.left = left + "px";
      }
      if (scroll)
        { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
    },

    triggerOnKeyDown: methodOp(onKeyDown),
    triggerOnKeyPress: methodOp(onKeyPress),
    triggerOnKeyUp: onKeyUp,
    triggerOnMouseDown: methodOp(onMouseDown),

    execCommand: function(cmd) {
      if (commands.hasOwnProperty(cmd))
        { return commands[cmd].call(null, this) }
    },

    triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),

    findPosH: function(from, amount, unit, visually) {
      var this$1 = this;

      var dir = 1;
      if (amount < 0) { dir = -1; amount = -amount; }
      var cur = clipPos(this.doc, from);
      for (var i = 0; i < amount; ++i) {
        cur = findPosH(this$1.doc, cur, dir, unit, visually);
        if (cur.hitSide) { break }
      }
      return cur
    },

    moveH: methodOp(function(dir, unit) {
      var this$1 = this;

      this.extendSelectionsBy(function (range$$1) {
        if (this$1.display.shift || this$1.doc.extend || range$$1.empty())
          { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) }
        else
          { return dir < 0 ? range$$1.from() : range$$1.to() }
      }, sel_move);
    }),

    deleteH: methodOp(function(dir, unit) {
      var sel = this.doc.sel, doc = this.doc;
      if (sel.somethingSelected())
        { doc.replaceSelection("", null, "+delete"); }
      else
        { deleteNearSelection(this, function (range$$1) {
          var other = findPosH(doc, range$$1.head, dir, unit, false);
          return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other}
        }); }
    }),

    findPosV: function(from, amount, unit, goalColumn) {
      var this$1 = this;

      var dir = 1, x = goalColumn;
      if (amount < 0) { dir = -1; amount = -amount; }
      var cur = clipPos(this.doc, from);
      for (var i = 0; i < amount; ++i) {
        var coords = cursorCoords(this$1, cur, "div");
        if (x == null) { x = coords.left; }
        else { coords.left = x; }
        cur = findPosV(this$1, coords, dir, unit);
        if (cur.hitSide) { break }
      }
      return cur
    },

    moveV: methodOp(function(dir, unit) {
      var this$1 = this;

      var doc = this.doc, goals = [];
      var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
      doc.extendSelectionsBy(function (range$$1) {
        if (collapse)
          { return dir < 0 ? range$$1.from() : range$$1.to() }
        var headPos = cursorCoords(this$1, range$$1.head, "div");
        if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; }
        goals.push(headPos.left);
        var pos = findPosV(this$1, headPos, dir, unit);
        if (unit == "page" && range$$1 == doc.sel.primary())
          { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
        return pos
      }, sel_move);
      if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
        { doc.sel.ranges[i].goalColumn = goals[i]; } }
    }),

    // Find the word at the given position (as returned by coordsChar).
    findWordAt: function(pos) {
      var doc = this.doc, line = getLine(doc, pos.line).text;
      var start = pos.ch, end = pos.ch;
      if (line) {
        var helper = this.getHelper(pos, "wordChars");
        if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
        var startChar = line.charAt(start);
        var check = isWordChar(startChar, helper)
          ? function (ch) { return isWordChar(ch, helper); }
          : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
          : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
        while (start > 0 && check(line.charAt(start - 1))) { --start; }
        while (end < line.length && check(line.charAt(end))) { ++end; }
      }
      return new Range(Pos(pos.line, start), Pos(pos.line, end))
    },

    toggleOverwrite: function(value) {
      if (value != null && value == this.state.overwrite) { return }
      if (this.state.overwrite = !this.state.overwrite)
        { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
      else
        { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }

      signal(this, "overwriteToggle", this, this.state.overwrite);
    },
    hasFocus: function() { return this.display.input.getField() == activeElt() },
    isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },

    scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
    getScrollInfo: function() {
      var scroller = this.display.scroller;
      return {left: scroller.scrollLeft, top: scroller.scrollTop,
              height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
              width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
              clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
    },

    scrollIntoView: methodOp(function(range$$1, margin) {
      if (range$$1 == null) {
        range$$1 = {from: this.doc.sel.primary().head, to: null};
        if (margin == null) { margin = this.options.cursorScrollMargin; }
      } else if (typeof range$$1 == "number") {
        range$$1 = {from: Pos(range$$1, 0), to: null};
      } else if (range$$1.from == null) {
        range$$1 = {from: range$$1, to: null};
      }
      if (!range$$1.to) { range$$1.to = range$$1.from; }
      range$$1.margin = margin || 0;

      if (range$$1.from.line != null) {
        scrollToRange(this, range$$1);
      } else {
        scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin);
      }
    }),

    setSize: methodOp(function(width, height) {
      var this$1 = this;

      var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
      if (width != null) { this.display.wrapper.style.width = interpret(width); }
      if (height != null) { this.display.wrapper.style.height = interpret(height); }
      if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
      var lineNo$$1 = this.display.viewFrom;
      this.doc.iter(lineNo$$1, this.display.viewTo, function (line) {
        if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
          { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } }
        ++lineNo$$1;
      });
      this.curOp.forceUpdate = true;
      signal(this, "refresh", this);
    }),

    operation: function(f){return runInOp(this, f)},
    startOperation: function(){return startOperation(this)},
    endOperation: function(){return endOperation(this)},

    refresh: methodOp(function() {
      var oldHeight = this.display.cachedTextHeight;
      regChange(this);
      this.curOp.forceUpdate = true;
      clearCaches(this);
      scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
      updateGutterSpace(this);
      if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
        { estimateLineHeights(this); }
      signal(this, "refresh", this);
    }),

    swapDoc: methodOp(function(doc) {
      var old = this.doc;
      old.cm = null;
      attachDoc(this, doc);
      clearCaches(this);
      this.display.input.reset();
      scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
      this.curOp.forceScroll = true;
      signalLater(this, "swapDoc", this, old);
      return old
    }),

    getInputField: function(){return this.display.input.getField()},
    getWrapperElement: function(){return this.display.wrapper},
    getScrollerElement: function(){return this.display.scroller},
    getGutterElement: function(){return this.display.gutters}
  };
  eventMixin(CodeMirror);

  CodeMirror.registerHelper = function(type, name, value) {
    if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
    helpers[type][name] = value;
  };
  CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
    CodeMirror.registerHelper(type, name, value);
    helpers[type]._global.push({pred: predicate, val: value});
  };
};

// Used for horizontal relative motion. Dir is -1 or 1 (left or
// right), unit can be "char", "column" (like char, but doesn't
// cross line boundaries), "word" (across next word), or "group" (to
// the start of next group of word or non-word-non-whitespace
// chars). The visually param controls whether, in right-to-left
// text, direction 1 means to move towards the next index in the
// string, or towards the character to the right of the current
// position. The resulting position will have a hitSide=true
// property if it reached the end of the document.
function findPosH(doc, pos, dir, unit, visually) {
  var oldPos = pos;
  var origDir = dir;
  var lineObj = getLine(doc, pos.line);
  function findNextLine() {
    var l = pos.line + dir;
    if (l < doc.first || l >= doc.first + doc.size) { return false }
    pos = new Pos(l, pos.ch, pos.sticky);
    return lineObj = getLine(doc, l)
  }
  function moveOnce(boundToLine) {
    var next;
    if (visually) {
      next = moveVisually(doc.cm, lineObj, pos, dir);
    } else {
      next = moveLogically(lineObj, pos, dir);
    }
    if (next == null) {
      if (!boundToLine && findNextLine())
        { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); }
      else
        { return false }
    } else {
      pos = next;
    }
    return true
  }

  if (unit == "char") {
    moveOnce();
  } else if (unit == "column") {
    moveOnce(true);
  } else if (unit == "word" || unit == "group") {
    var sawType = null, group = unit == "group";
    var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
    for (var first = true;; first = false) {
      if (dir < 0 && !moveOnce(!first)) { break }
      var cur = lineObj.text.charAt(pos.ch) || "\n";
      var type = isWordChar(cur, helper) ? "w"
        : group && cur == "\n" ? "n"
        : !group || /\s/.test(cur) ? null
        : "p";
      if (group && !first && !type) { type = "s"; }
      if (sawType && sawType != type) {
        if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
        break
      }

      if (type) { sawType = type; }
      if (dir > 0 && !moveOnce(!first)) { break }
    }
  }
  var result = skipAtomic(doc, pos, oldPos, origDir, true);
  if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
  return result
}

// For relative vertical movement. Dir may be -1 or 1. Unit can be
// "page" or "line". The resulting position will have a hitSide=true
// property if it reached the end of the document.
function findPosV(cm, pos, dir, unit) {
  var doc = cm.doc, x = pos.left, y;
  if (unit == "page") {
    var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
    var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
    y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;

  } else if (unit == "line") {
    y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  }
  var target;
  for (;;) {
    target = coordsChar(cm, x, y);
    if (!target.outside) { break }
    if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
    y += dir * 5;
  }
  return target
}

// CONTENTEDITABLE INPUT STYLE

var ContentEditableInput = function(cm) {
  this.cm = cm;
  this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  this.polling = new Delayed();
  this.composing = null;
  this.gracePeriod = false;
  this.readDOMTimeout = null;
};

ContentEditableInput.prototype.init = function (display) {
    var this$1 = this;

  var input = this, cm = input.cm;
  var div = input.div = display.lineDiv;
  disableBrowserMagic(div, cm.options.spellcheck);

  on(div, "paste", function (e) {
    if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
    // IE doesn't fire input events, so we schedule a read for the pasted content in this way
    if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
  });

  on(div, "compositionstart", function (e) {
    this$1.composing = {data: e.data, done: false};
  });
  on(div, "compositionupdate", function (e) {
    if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
  });
  on(div, "compositionend", function (e) {
    if (this$1.composing) {
      if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
      this$1.composing.done = true;
    }
  });

  on(div, "touchstart", function () { return input.forceCompositionEnd(); });

  on(div, "input", function () {
    if (!this$1.composing) { this$1.readFromDOMSoon(); }
  });

  function onCopyCut(e) {
    if (signalDOMEvent(cm, e)) { return }
    if (cm.somethingSelected()) {
      setLastCopied({lineWise: false, text: cm.getSelections()});
      if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
    } else if (!cm.options.lineWiseCopyCut) {
      return
    } else {
      var ranges = copyableRanges(cm);
      setLastCopied({lineWise: true, text: ranges.text});
      if (e.type == "cut") {
        cm.operation(function () {
          cm.setSelections(ranges.ranges, 0, sel_dontScroll);
          cm.replaceSelection("", null, "cut");
        });
      }
    }
    if (e.clipboardData) {
      e.clipboardData.clearData();
      var content = lastCopied.text.join("\n");
      // iOS exposes the clipboard API, but seems to discard content inserted into it
      e.clipboardData.setData("Text", content);
      if (e.clipboardData.getData("Text") == content) {
        e.preventDefault();
        return
      }
    }
    // Old-fashioned briefly-focus-a-textarea hack
    var kludge = hiddenTextarea(), te = kludge.firstChild;
    cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
    te.value = lastCopied.text.join("\n");
    var hadFocus = document.activeElement;
    selectInput(te);
    setTimeout(function () {
      cm.display.lineSpace.removeChild(kludge);
      hadFocus.focus();
      if (hadFocus == div) { input.showPrimarySelection(); }
    }, 50);
  }
  on(div, "copy", onCopyCut);
  on(div, "cut", onCopyCut);
};

ContentEditableInput.prototype.prepareSelection = function () {
  var result = prepareSelection(this.cm, false);
  result.focus = this.cm.state.focused;
  return result
};

ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  if (!info || !this.cm.display.view.length) { return }
  if (info.focus || takeFocus) { this.showPrimarySelection(); }
  this.showMultipleSelections(info);
};

ContentEditableInput.prototype.getSelection = function () {
  return this.cm.display.wrapper.ownerDocument.getSelection()
};

ContentEditableInput.prototype.showPrimarySelection = function () {
  var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
  var from = prim.from(), to = prim.to();

  if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
    sel.removeAllRanges();
    return
  }

  var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
  if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
      cmp(minPos(curAnchor, curFocus), from) == 0 &&
      cmp(maxPos(curAnchor, curFocus), to) == 0)
    { return }

  var view = cm.display.view;
  var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
      {node: view[0].measure.map[2], offset: 0};
  var end = to.line < cm.display.viewTo && posToDOM(cm, to);
  if (!end) {
    var measure = view[view.length - 1].measure;
    var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
    end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]};
  }

  if (!start || !end) {
    sel.removeAllRanges();
    return
  }

  var old = sel.rangeCount && sel.getRangeAt(0), rng;
  try { rng = range(start.node, start.offset, end.offset, end.node); }
  catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  if (rng) {
    if (!gecko && cm.state.focused) {
      sel.collapse(start.node, start.offset);
      if (!rng.collapsed) {
        sel.removeAllRanges();
        sel.addRange(rng);
      }
    } else {
      sel.removeAllRanges();
      sel.addRange(rng);
    }
    if (old && sel.anchorNode == null) { sel.addRange(old); }
    else if (gecko) { this.startGracePeriod(); }
  }
  this.rememberSelection();
};

ContentEditableInput.prototype.startGracePeriod = function () {
    var this$1 = this;

  clearTimeout(this.gracePeriod);
  this.gracePeriod = setTimeout(function () {
    this$1.gracePeriod = false;
    if (this$1.selectionChanged())
      { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
  }, 20);
};

ContentEditableInput.prototype.showMultipleSelections = function (info) {
  removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
};

ContentEditableInput.prototype.rememberSelection = function () {
  var sel = this.getSelection();
  this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
};

ContentEditableInput.prototype.selectionInEditor = function () {
  var sel = this.getSelection();
  if (!sel.rangeCount) { return false }
  var node = sel.getRangeAt(0).commonAncestorContainer;
  return contains(this.div, node)
};

ContentEditableInput.prototype.focus = function () {
  if (this.cm.options.readOnly != "nocursor") {
    if (!this.selectionInEditor())
      { this.showSelection(this.prepareSelection(), true); }
    this.div.focus();
  }
};
ContentEditableInput.prototype.blur = function () { this.div.blur(); };
ContentEditableInput.prototype.getField = function () { return this.div };

ContentEditableInput.prototype.supportsTouch = function () { return true };

ContentEditableInput.prototype.receivedFocus = function () {
  var input = this;
  if (this.selectionInEditor())
    { this.pollSelection(); }
  else
    { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }

  function poll() {
    if (input.cm.state.focused) {
      input.pollSelection();
      input.polling.set(input.cm.options.pollInterval, poll);
    }
  }
  this.polling.set(this.cm.options.pollInterval, poll);
};

ContentEditableInput.prototype.selectionChanged = function () {
  var sel = this.getSelection();
  return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
    sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
};

ContentEditableInput.prototype.pollSelection = function () {
  if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
  var sel = this.getSelection(), cm = this.cm;
  // On Android Chrome (version 56, at least), backspacing into an
  // uneditable block element will put the cursor in that element,
  // and then, because it's not editable, hide the virtual keyboard.
  // Because Android doesn't allow us to actually detect backspace
  // presses in a sane way, this code checks for when that happens
  // and simulates a backspace press in this case.
  if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) {
    this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
    this.blur();
    this.focus();
    return
  }
  if (this.composing) { return }
  this.rememberSelection();
  var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  if (anchor && head) { runInOp(cm, function () {
    setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
    if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
  }); }
};

ContentEditableInput.prototype.pollContent = function () {
  if (this.readDOMTimeout != null) {
    clearTimeout(this.readDOMTimeout);
    this.readDOMTimeout = null;
  }

  var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  var from = sel.from(), to = sel.to();
  if (from.ch == 0 && from.line > cm.firstLine())
    { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
  if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
    { to = Pos(to.line + 1, 0); }
  if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }

  var fromIndex, fromLine, fromNode;
  if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
    fromLine = lineNo(display.view[0].line);
    fromNode = display.view[0].node;
  } else {
    fromLine = lineNo(display.view[fromIndex].line);
    fromNode = display.view[fromIndex - 1].node.nextSibling;
  }
  var toIndex = findViewIndex(cm, to.line);
  var toLine, toNode;
  if (toIndex == display.view.length - 1) {
    toLine = display.viewTo - 1;
    toNode = display.lineDiv.lastChild;
  } else {
    toLine = lineNo(display.view[toIndex + 1].line) - 1;
    toNode = display.view[toIndex + 1].node.previousSibling;
  }

  if (!fromNode) { return false }
  var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  while (newText.length > 1 && oldText.length > 1) {
    if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
    else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
    else { break }
  }

  var cutFront = 0, cutEnd = 0;
  var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
    { ++cutFront; }
  var newBot = lst(newText), oldBot = lst(oldText);
  var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
                           oldBot.length - (oldText.length == 1 ? cutFront : 0));
  while (cutEnd < maxCutEnd &&
         newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
    { ++cutEnd; }
  // Try to move start of change to start of selection if ambiguous
  if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
    while (cutFront && cutFront > from.ch &&
           newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
      cutFront--;
      cutEnd++;
    }
  }

  newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
  newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");

  var chFrom = Pos(fromLine, cutFront);
  var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
    replaceRange(cm.doc, newText, chFrom, chTo, "+input");
    return true
  }
};

ContentEditableInput.prototype.ensurePolled = function () {
  this.forceCompositionEnd();
};
ContentEditableInput.prototype.reset = function () {
  this.forceCompositionEnd();
};
ContentEditableInput.prototype.forceCompositionEnd = function () {
  if (!this.composing) { return }
  clearTimeout(this.readDOMTimeout);
  this.composing = null;
  this.updateFromDOM();
  this.div.blur();
  this.div.focus();
};
ContentEditableInput.prototype.readFromDOMSoon = function () {
    var this$1 = this;

  if (this.readDOMTimeout != null) { return }
  this.readDOMTimeout = setTimeout(function () {
    this$1.readDOMTimeout = null;
    if (this$1.composing) {
      if (this$1.composing.done) { this$1.composing = null; }
      else { return }
    }
    this$1.updateFromDOM();
  }, 80);
};

ContentEditableInput.prototype.updateFromDOM = function () {
    var this$1 = this;

  if (this.cm.isReadOnly() || !this.pollContent())
    { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
};

ContentEditableInput.prototype.setUneditable = function (node) {
  node.contentEditable = "false";
};

ContentEditableInput.prototype.onKeyPress = function (e) {
  if (e.charCode == 0 || this.composing) { return }
  e.preventDefault();
  if (!this.cm.isReadOnly())
    { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
};

ContentEditableInput.prototype.readOnlyChanged = function (val) {
  this.div.contentEditable = String(val != "nocursor");
};

ContentEditableInput.prototype.onContextMenu = function () {};
ContentEditableInput.prototype.resetPosition = function () {};

ContentEditableInput.prototype.needsContentAttribute = true;

function posToDOM(cm, pos) {
  var view = findViewForLine(cm, pos.line);
  if (!view || view.hidden) { return null }
  var line = getLine(cm.doc, pos.line);
  var info = mapFromLineView(view, line, pos.line);

  var order = getOrder(line, cm.doc.direction), side = "left";
  if (order) {
    var partPos = getBidiPartAt(order, pos.ch);
    side = partPos % 2 ? "right" : "left";
  }
  var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  result.offset = result.collapse == "right" ? result.end : result.start;
  return result
}

function isInGutter(node) {
  for (var scan = node; scan; scan = scan.parentNode)
    { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
  return false
}

function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }

function domTextBetween(cm, from, to, fromLine, toLine) {
  var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
  function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  function close() {
    if (closing) {
      text += lineSep;
      if (extraLinebreak) { text += lineSep; }
      closing = extraLinebreak = false;
    }
  }
  function addText(str) {
    if (str) {
      close();
      text += str;
    }
  }
  function walk(node) {
    if (node.nodeType == 1) {
      var cmText = node.getAttribute("cm-text");
      if (cmText) {
        addText(cmText);
        return
      }
      var markerID = node.getAttribute("cm-marker"), range$$1;
      if (markerID) {
        var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
        if (found.length && (range$$1 = found[0].find(0)))
          { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); }
        return
      }
      if (node.getAttribute("contenteditable") == "false") { return }
      var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
      if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }

      if (isBlock) { close(); }
      for (var i = 0; i < node.childNodes.length; i++)
        { walk(node.childNodes[i]); }

      if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
      if (isBlock) { closing = true; }
    } else if (node.nodeType == 3) {
      addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
    }
  }
  for (;;) {
    walk(from);
    if (from == to) { break }
    from = from.nextSibling;
    extraLinebreak = false;
  }
  return text
}

function domToPos(cm, node, offset) {
  var lineNode;
  if (node == cm.display.lineDiv) {
    lineNode = cm.display.lineDiv.childNodes[offset];
    if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
    node = null; offset = 0;
  } else {
    for (lineNode = node;; lineNode = lineNode.parentNode) {
      if (!lineNode || lineNode == cm.display.lineDiv) { return null }
      if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
    }
  }
  for (var i = 0; i < cm.display.view.length; i++) {
    var lineView = cm.display.view[i];
    if (lineView.node == lineNode)
      { return locateNodeInLineView(lineView, node, offset) }
  }
}

function locateNodeInLineView(lineView, node, offset) {
  var wrapper = lineView.text.firstChild, bad = false;
  if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  if (node == wrapper) {
    bad = true;
    node = wrapper.childNodes[offset];
    offset = 0;
    if (!node) {
      var line = lineView.rest ? lst(lineView.rest) : lineView.line;
      return badPos(Pos(lineNo(line), line.text.length), bad)
    }
  }

  var textNode = node.nodeType == 3 ? node : null, topNode = node;
  if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
    textNode = node.firstChild;
    if (offset) { offset = textNode.nodeValue.length; }
  }
  while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
  var measure = lineView.measure, maps = measure.maps;

  function find(textNode, topNode, offset) {
    for (var i = -1; i < (maps ? maps.length : 0); i++) {
      var map$$1 = i < 0 ? measure.map : maps[i];
      for (var j = 0; j < map$$1.length; j += 3) {
        var curNode = map$$1[j + 2];
        if (curNode == textNode || curNode == topNode) {
          var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
          var ch = map$$1[j] + offset;
          if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; }
          return Pos(line, ch)
        }
      }
    }
  }
  var found = find(textNode, topNode, offset);
  if (found) { return badPos(found, bad) }

  // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
    found = find(after, after.firstChild, 0);
    if (found)
      { return badPos(Pos(found.line, found.ch - dist), bad) }
    else
      { dist += after.textContent.length; }
  }
  for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
    found = find(before, before.firstChild, -1);
    if (found)
      { return badPos(Pos(found.line, found.ch + dist$1), bad) }
    else
      { dist$1 += before.textContent.length; }
  }
}

// TEXTAREA INPUT STYLE

var TextareaInput = function(cm) {
  this.cm = cm;
  // See input.poll and input.reset
  this.prevInput = "";

  // Flag that indicates whether we expect input to appear real soon
  // now (after some event like 'keypress' or 'input') and are
  // polling intensively.
  this.pollingFast = false;
  // Self-resetting timeout for the poller
  this.polling = new Delayed();
  // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  this.hasSelection = false;
  this.composing = null;
};

TextareaInput.prototype.init = function (display) {
    var this$1 = this;

  var input = this, cm = this.cm;
  this.createField(display);
  var te = this.textarea;

  display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);

  // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  if (ios) { te.style.width = "0px"; }

  on(te, "input", function () {
    if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
    input.poll();
  });

  on(te, "paste", function (e) {
    if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }

    cm.state.pasteIncoming = true;
    input.fastPoll();
  });

  function prepareCopyCut(e) {
    if (signalDOMEvent(cm, e)) { return }
    if (cm.somethingSelected()) {
      setLastCopied({lineWise: false, text: cm.getSelections()});
    } else if (!cm.options.lineWiseCopyCut) {
      return
    } else {
      var ranges = copyableRanges(cm);
      setLastCopied({lineWise: true, text: ranges.text});
      if (e.type == "cut") {
        cm.setSelections(ranges.ranges, null, sel_dontScroll);
      } else {
        input.prevInput = "";
        te.value = ranges.text.join("\n");
        selectInput(te);
      }
    }
    if (e.type == "cut") { cm.state.cutIncoming = true; }
  }
  on(te, "cut", prepareCopyCut);
  on(te, "copy", prepareCopyCut);

  on(display.scroller, "paste", function (e) {
    if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
    cm.state.pasteIncoming = true;
    input.focus();
  });

  // Prevent normal selection in the editor (we handle our own)
  on(display.lineSpace, "selectstart", function (e) {
    if (!eventInWidget(display, e)) { e_preventDefault(e); }
  });

  on(te, "compositionstart", function () {
    var start = cm.getCursor("from");
    if (input.composing) { input.composing.range.clear(); }
    input.composing = {
      start: start,
      range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
    };
  });
  on(te, "compositionend", function () {
    if (input.composing) {
      input.poll();
      input.composing.range.clear();
      input.composing = null;
    }
  });
};

TextareaInput.prototype.createField = function (_display) {
  // Wraps and hides input textarea
  this.wrapper = hiddenTextarea();
  // The semihidden textarea that is focused when the editor is
  // focused, and receives input.
  this.textarea = this.wrapper.firstChild;
};

TextareaInput.prototype.prepareSelection = function () {
  // Redraw the selection and/or cursor
  var cm = this.cm, display = cm.display, doc = cm.doc;
  var result = prepareSelection(cm);

  // Move the hidden textarea near the cursor to prevent scrolling artifacts
  if (cm.options.moveInputWithCursor) {
    var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
    var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
    result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
                                        headPos.top + lineOff.top - wrapOff.top));
    result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
                                         headPos.left + lineOff.left - wrapOff.left));
  }

  return result
};

TextareaInput.prototype.showSelection = function (drawn) {
  var cm = this.cm, display = cm.display;
  removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  if (drawn.teTop != null) {
    this.wrapper.style.top = drawn.teTop + "px";
    this.wrapper.style.left = drawn.teLeft + "px";
  }
};

// Reset the input to correspond to the selection (or to be empty,
// when not typing and nothing is selected)
TextareaInput.prototype.reset = function (typing) {
  if (this.contextMenuPending || this.composing) { return }
  var cm = this.cm;
  if (cm.somethingSelected()) {
    this.prevInput = "";
    var content = cm.getSelection();
    this.textarea.value = content;
    if (cm.state.focused) { selectInput(this.textarea); }
    if (ie && ie_version >= 9) { this.hasSelection = content; }
  } else if (!typing) {
    this.prevInput = this.textarea.value = "";
    if (ie && ie_version >= 9) { this.hasSelection = null; }
  }
};

TextareaInput.prototype.getField = function () { return this.textarea };

TextareaInput.prototype.supportsTouch = function () { return false };

TextareaInput.prototype.focus = function () {
  if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
    try { this.textarea.focus(); }
    catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  }
};

TextareaInput.prototype.blur = function () { this.textarea.blur(); };

TextareaInput.prototype.resetPosition = function () {
  this.wrapper.style.top = this.wrapper.style.left = 0;
};

TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };

// Poll for input changes, using the normal rate of polling. This
// runs as long as the editor is focused.
TextareaInput.prototype.slowPoll = function () {
    var this$1 = this;

  if (this.pollingFast) { return }
  this.polling.set(this.cm.options.pollInterval, function () {
    this$1.poll();
    if (this$1.cm.state.focused) { this$1.slowPoll(); }
  });
};

// When an event has just come in that is likely to add or change
// something in the input textarea, we poll faster, to ensure that
// the change appears on the screen quickly.
TextareaInput.prototype.fastPoll = function () {
  var missed = false, input = this;
  input.pollingFast = true;
  function p() {
    var changed = input.poll();
    if (!changed && !missed) {missed = true; input.polling.set(60, p);}
    else {input.pollingFast = false; input.slowPoll();}
  }
  input.polling.set(20, p);
};

// Read input from the textarea, and update the document to match.
// When something is selected, it is present in the textarea, and
// selected (unless it is huge, in which case a placeholder is
// used). When nothing is selected, the cursor sits after previously
// seen text (can be empty), which is stored in prevInput (we must
// not reset the textarea when typing, because that breaks IME).
TextareaInput.prototype.poll = function () {
    var this$1 = this;

  var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  // Since this is called a *lot*, try to bail out as cheaply as
  // possible when it is clear that nothing happened. hasSelection
  // will be the case when there is a lot of text in the textarea,
  // in which case reading its value would be expensive.
  if (this.contextMenuPending || !cm.state.focused ||
      (hasSelection(input) && !prevInput && !this.composing) ||
      cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
    { return false }

  var text = input.value;
  // If nothing changed, bail.
  if (text == prevInput && !cm.somethingSelected()) { return false }
  // Work around nonsensical selection resetting in IE9/10, and
  // inexplicable appearance of private area unicode characters on
  // some key combos in Mac (#2689).
  if (ie && ie_version >= 9 && this.hasSelection === text ||
      mac && /[\uf700-\uf7ff]/.test(text)) {
    cm.display.input.reset();
    return false
  }

  if (cm.doc.sel == cm.display.selForContextMenu) {
    var first = text.charCodeAt(0);
    if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
    if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  }
  // Find the part of the input that is actually new
  var same = 0, l = Math.min(prevInput.length, text.length);
  while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }

  runInOp(cm, function () {
    applyTextInput(cm, text.slice(same), prevInput.length - same,
                   null, this$1.composing ? "*compose" : null);

    // Don't leave long text in the textarea, since it makes further polling slow
    if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
    else { this$1.prevInput = text; }

    if (this$1.composing) {
      this$1.composing.range.clear();
      this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
                                         {className: "CodeMirror-composing"});
    }
  });
  return true
};

TextareaInput.prototype.ensurePolled = function () {
  if (this.pollingFast && this.poll()) { this.pollingFast = false; }
};

TextareaInput.prototype.onKeyPress = function () {
  if (ie && ie_version >= 9) { this.hasSelection = null; }
  this.fastPoll();
};

TextareaInput.prototype.onContextMenu = function (e) {
  var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  if (!pos || presto) { return } // Opera is difficult.

  // Reset the current text selection only if the click is done outside of the selection
  // and 'resetSelectionOnContextMenu' option is true.
  var reset = cm.options.resetSelectionOnContextMenu;
  if (reset && cm.doc.sel.contains(pos) == -1)
    { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }

  var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  input.wrapper.style.cssText = "position: absolute";
  var wrapperBox = input.wrapper.getBoundingClientRect();
  te.style.cssText = "position: absolute; width: 30px; height: 30px;\n      top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n      z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n      outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
  var oldScrollY;
  if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
  display.input.focus();
  if (webkit) { window.scrollTo(null, oldScrollY); }
  display.input.reset();
  // Adds "Select all" to context menu in FF
  if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
  input.contextMenuPending = true;
  display.selForContextMenu = cm.doc.sel;
  clearTimeout(display.detectingSelectAll);

  // Select-all will be greyed out if there's nothing to select, so
  // this adds a zero-width space so that we can later check whether
  // it got selected.
  function prepareSelectAllHack() {
    if (te.selectionStart != null) {
      var selected = cm.somethingSelected();
      var extval = "\u200b" + (selected ? te.value : "");
      te.value = "\u21da"; // Used to catch context-menu undo
      te.value = extval;
      input.prevInput = selected ? "" : "\u200b";
      te.selectionStart = 1; te.selectionEnd = extval.length;
      // Re-set this, in case some other handler touched the
      // selection in the meantime.
      display.selForContextMenu = cm.doc.sel;
    }
  }
  function rehide() {
    input.contextMenuPending = false;
    input.wrapper.style.cssText = oldWrapperCSS;
    te.style.cssText = oldCSS;
    if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }

    // Try to detect the user choosing select-all
    if (te.selectionStart != null) {
      if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
      var i = 0, poll = function () {
        if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
            te.selectionEnd > 0 && input.prevInput == "\u200b") {
          operation(cm, selectAll)(cm);
        } else if (i++ < 10) {
          display.detectingSelectAll = setTimeout(poll, 500);
        } else {
          display.selForContextMenu = null;
          display.input.reset();
        }
      };
      display.detectingSelectAll = setTimeout(poll, 200);
    }
  }

  if (ie && ie_version >= 9) { prepareSelectAllHack(); }
  if (captureRightClick) {
    e_stop(e);
    var mouseup = function () {
      off(window, "mouseup", mouseup);
      setTimeout(rehide, 20);
    };
    on(window, "mouseup", mouseup);
  } else {
    setTimeout(rehide, 50);
  }
};

TextareaInput.prototype.readOnlyChanged = function (val) {
  if (!val) { this.reset(); }
  this.textarea.disabled = val == "nocursor";
};

TextareaInput.prototype.setUneditable = function () {};

TextareaInput.prototype.needsContentAttribute = false;

function fromTextArea(textarea, options) {
  options = options ? copyObj(options) : {};
  options.value = textarea.value;
  if (!options.tabindex && textarea.tabIndex)
    { options.tabindex = textarea.tabIndex; }
  if (!options.placeholder && textarea.placeholder)
    { options.placeholder = textarea.placeholder; }
  // Set autofocus to true if this textarea is focused, or if it has
  // autofocus and no other element is focused.
  if (options.autofocus == null) {
    var hasFocus = activeElt();
    options.autofocus = hasFocus == textarea ||
      textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  }

  function save() {textarea.value = cm.getValue();}

  var realSubmit;
  if (textarea.form) {
    on(textarea.form, "submit", save);
    // Deplorable hack to make the submit method do the right thing.
    if (!options.leaveSubmitMethodAlone) {
      var form = textarea.form;
      realSubmit = form.submit;
      try {
        var wrappedSubmit = form.submit = function () {
          save();
          form.submit = realSubmit;
          form.submit();
          form.submit = wrappedSubmit;
        };
      } catch(e) {}
    }
  }

  options.finishInit = function (cm) {
    cm.save = save;
    cm.getTextArea = function () { return textarea; };
    cm.toTextArea = function () {
      cm.toTextArea = isNaN; // Prevent this from being ran twice
      save();
      textarea.parentNode.removeChild(cm.getWrapperElement());
      textarea.style.display = "";
      if (textarea.form) {
        off(textarea.form, "submit", save);
        if (typeof textarea.form.submit == "function")
          { textarea.form.submit = realSubmit; }
      }
    };
  };

  textarea.style.display = "none";
  var cm = CodeMirror$1(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
    options);
  return cm
}

function addLegacyProps(CodeMirror) {
  CodeMirror.off = off;
  CodeMirror.on = on;
  CodeMirror.wheelEventPixels = wheelEventPixels;
  CodeMirror.Doc = Doc;
  CodeMirror.splitLines = splitLinesAuto;
  CodeMirror.countColumn = countColumn;
  CodeMirror.findColumn = findColumn;
  CodeMirror.isWordChar = isWordCharBasic;
  CodeMirror.Pass = Pass;
  CodeMirror.signal = signal;
  CodeMirror.Line = Line;
  CodeMirror.changeEnd = changeEnd;
  CodeMirror.scrollbarModel = scrollbarModel;
  CodeMirror.Pos = Pos;
  CodeMirror.cmpPos = cmp;
  CodeMirror.modes = modes;
  CodeMirror.mimeModes = mimeModes;
  CodeMirror.resolveMode = resolveMode;
  CodeMirror.getMode = getMode;
  CodeMirror.modeExtensions = modeExtensions;
  CodeMirror.extendMode = extendMode;
  CodeMirror.copyState = copyState;
  CodeMirror.startState = startState;
  CodeMirror.innerMode = innerMode;
  CodeMirror.commands = commands;
  CodeMirror.keyMap = keyMap;
  CodeMirror.keyName = keyName;
  CodeMirror.isModifierKey = isModifierKey;
  CodeMirror.lookupKey = lookupKey;
  CodeMirror.normalizeKeyMap = normalizeKeyMap;
  CodeMirror.StringStream = StringStream;
  CodeMirror.SharedTextMarker = SharedTextMarker;
  CodeMirror.TextMarker = TextMarker;
  CodeMirror.LineWidget = LineWidget;
  CodeMirror.e_preventDefault = e_preventDefault;
  CodeMirror.e_stopPropagation = e_stopPropagation;
  CodeMirror.e_stop = e_stop;
  CodeMirror.addClass = addClass;
  CodeMirror.contains = contains;
  CodeMirror.rmClass = rmClass;
  CodeMirror.keyNames = keyNames;
}

// EDITOR CONSTRUCTOR

defineOptions(CodeMirror$1);

addEditorMethods(CodeMirror$1);

// Set up methods on CodeMirror's prototype to redirect to the editor's document.
var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  { CodeMirror$1.prototype[prop] = (function(method) {
    return function() {return method.apply(this.doc, arguments)}
  })(Doc.prototype[prop]); } }

eventMixin(Doc);

// INPUT HANDLING

CodeMirror$1.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};

// MODE DEFINITION AND QUERYING

// Extra arguments are stored as the mode's dependencies, which is
// used by (legacy) mechanisms like loadmode.js to automatically
// load a mode. (Preferred mechanism is the require/define calls.)
CodeMirror$1.defineMode = function(name/*, mode, …*/) {
  if (!CodeMirror$1.defaults.mode && name != "null") { CodeMirror$1.defaults.mode = name; }
  defineMode.apply(this, arguments);
};

CodeMirror$1.defineMIME = defineMIME;

// Minimal default mode.
CodeMirror$1.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
CodeMirror$1.defineMIME("text/plain", "null");

// EXTENSIONS

CodeMirror$1.defineExtension = function (name, func) {
  CodeMirror$1.prototype[name] = func;
};
CodeMirror$1.defineDocExtension = function (name, func) {
  Doc.prototype[name] = func;
};

CodeMirror$1.fromTextArea = fromTextArea;

addLegacyProps(CodeMirror$1);

CodeMirror$1.version = "5.39.2";

return CodeMirror$1;

})));


/***/ }),

/***/ "VrUr":
/*!************************************************!*\
  !*** ./node_modules/parse-asn1/certificate.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
// from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js
// thanks to @Rantanen



var asn = __webpack_require__(/*! asn1.js */ "f3pb")

var Time = asn.define('Time', function () {
  this.choice({
    utcTime: this.utctime(),
    generalTime: this.gentime()
  })
})

var AttributeTypeValue = asn.define('AttributeTypeValue', function () {
  this.seq().obj(
    this.key('type').objid(),
    this.key('value').any()
  )
})

var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () {
  this.seq().obj(
    this.key('algorithm').objid(),
    this.key('parameters').optional(),
    this.key('curve').objid().optional()
  )
})

var SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () {
  this.seq().obj(
    this.key('algorithm').use(AlgorithmIdentifier),
    this.key('subjectPublicKey').bitstr()
  )
})

var RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () {
  this.setof(AttributeTypeValue)
})

var RDNSequence = asn.define('RDNSequence', function () {
  this.seqof(RelativeDistinguishedName)
})

var Name = asn.define('Name', function () {
  this.choice({
    rdnSequence: this.use(RDNSequence)
  })
})

var Validity = asn.define('Validity', function () {
  this.seq().obj(
    this.key('notBefore').use(Time),
    this.key('notAfter').use(Time)
  )
})

var Extension = asn.define('Extension', function () {
  this.seq().obj(
    this.key('extnID').objid(),
    this.key('critical').bool().def(false),
    this.key('extnValue').octstr()
  )
})

var TBSCertificate = asn.define('TBSCertificate', function () {
  this.seq().obj(
    this.key('version').explicit(0).int().optional(),
    this.key('serialNumber').int(),
    this.key('signature').use(AlgorithmIdentifier),
    this.key('issuer').use(Name),
    this.key('validity').use(Validity),
    this.key('subject').use(Name),
    this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo),
    this.key('issuerUniqueID').implicit(1).bitstr().optional(),
    this.key('subjectUniqueID').implicit(2).bitstr().optional(),
    this.key('extensions').explicit(3).seqof(Extension).optional()
  )
})

var X509Certificate = asn.define('X509Certificate', function () {
  this.seq().obj(
    this.key('tbsCertificate').use(TBSCertificate),
    this.key('signatureAlgorithm').use(AlgorithmIdentifier),
    this.key('signatureValue').bitstr()
  )
})

module.exports = X509Certificate


/***/ }),

/***/ "Vywy":
/*!***************************************************!*\
  !*** ./node_modules/source-map/lib/base64-vlq.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* -*- Mode: js; js-indent-level: 2; -*- */
/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 *
 * Based on the Base 64 VLQ implementation in Closure Compiler:
 * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
 *
 * Copyright 2011 The Closure Compiler Authors. All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *  * Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above
 *    copyright notice, this list of conditions and the following
 *    disclaimer in the documentation and/or other materials provided
 *    with the distribution.
 *  * Neither the name of Google Inc. nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

var base64 = __webpack_require__(/*! ./base64 */ "Jcck");

// A single base 64 digit can contain 6 bits of data. For the base 64 variable
// length quantities we use in the source map spec, the first bit is the sign,
// the next four bits are the actual value, and the 6th bit is the
// continuation bit. The continuation bit tells us whether there are more
// digits in this value following this digit.
//
//   Continuation
//   |    Sign
//   |    |
//   V    V
//   101011

var VLQ_BASE_SHIFT = 5;

// binary: 100000
var VLQ_BASE = 1 << VLQ_BASE_SHIFT;

// binary: 011111
var VLQ_BASE_MASK = VLQ_BASE - 1;

// binary: 100000
var VLQ_CONTINUATION_BIT = VLQ_BASE;

/**
 * Converts from a two-complement value to a value where the sign bit is
 * placed in the least significant bit.  For example, as decimals:
 *   1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
 *   2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
 */
function toVLQSigned(aValue) {
  return aValue < 0
    ? ((-aValue) << 1) + 1
    : (aValue << 1) + 0;
}

/**
 * Converts to a two-complement value from a value where the sign bit is
 * placed in the least significant bit.  For example, as decimals:
 *   2 (10 binary) becomes 1, 3 (11 binary) becomes -1
 *   4 (100 binary) becomes 2, 5 (101 binary) becomes -2
 */
function fromVLQSigned(aValue) {
  var isNegative = (aValue & 1) === 1;
  var shifted = aValue >> 1;
  return isNegative
    ? -shifted
    : shifted;
}

/**
 * Returns the base 64 VLQ encoded value.
 */
exports.encode = function base64VLQ_encode(aValue) {
  var encoded = "";
  var digit;

  var vlq = toVLQSigned(aValue);

  do {
    digit = vlq & VLQ_BASE_MASK;
    vlq >>>= VLQ_BASE_SHIFT;
    if (vlq > 0) {
      // There are still more digits in this value, so we must make sure the
      // continuation bit is marked.
      digit |= VLQ_CONTINUATION_BIT;
    }
    encoded += base64.encode(digit);
  } while (vlq > 0);

  return encoded;
};

/**
 * Decodes the next base 64 VLQ value from the given string and returns the
 * value and the rest of the string via the out parameter.
 */
exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  var strLen = aStr.length;
  var result = 0;
  var shift = 0;
  var continuation, digit;

  do {
    if (aIndex >= strLen) {
      throw new Error("Expected more digits in base 64 VLQ value.");
    }

    digit = base64.decode(aStr.charCodeAt(aIndex++));
    if (digit === -1) {
      throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
    }

    continuation = !!(digit & VLQ_CONTINUATION_BIT);
    digit &= VLQ_BASE_MASK;
    result = result + (digit << shift);
    shift += VLQ_BASE_SHIFT;
  } while (continuation);

  aOutParam.value = fromVLQSigned(result);
  aOutParam.rest = aIndex;
};


/***/ }),

/***/ "W+VA":
/*!********************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/customTraceType.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

exports.plotlyTraceToCustomTrace = plotlyTraceToCustomTrace;
exports.traceTypeToPlotlyInitFigure = traceTypeToPlotlyInitFigure;

var _constants = __webpack_require__(/*! ./constants */ "5Bkx");

function plotlyTraceToCustomTrace(trace) {
  if ((typeof trace === 'undefined' ? 'undefined' : _typeof(trace)) !== 'object') {
    throw new Error('trace provided to plotlyTraceToCustomTrace function should be an object, received ' + (typeof trace === 'undefined' ? 'undefined' : _typeof(trace)));
  }

  var gl = 'gl';
  var type = trace.type ? trace.type.endsWith(gl) ? trace.type.slice(0, -gl.length) : trace.type : 'scatter';

  if ((type === 'scatter' || type === 'scattergl') && (![null, undefined, ''].includes(trace.stackgroup) || // eslint-disable-line no-undefined
  ['tozeroy', 'tozerox', 'tonexty', 'tonextx', 'toself', 'tonext'].includes(trace.fill))) {
    return 'area';
  } else if ((type === 'scatter' || type === 'scattergl') && (trace.mode === 'lines' || trace.mode === 'lines+markers')) {
    return 'line';
  } else if (type === 'scatter3d' && trace.mode === 'lines') {
    return 'line3d';
  }
  return type;
}

function traceTypeToPlotlyInitFigure(traceType) {
  var gl = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';

  var scatterTrace = { type: 'scatter' + gl, mode: 'markers', stackgroup: null };

  switch (traceType) {
    case 'line':
      return { type: 'scatter' + gl, mode: 'lines', stackgroup: null };
    case 'scatter':
      return scatterTrace;
    case undefined:
      // eslint-disable-line
      return scatterTrace;
    case 'area':
      return { type: 'scatter' + gl, mode: 'lines', stackgroup: 1 };
    case 'scatterpolar':
      return { type: 'scatterpolar' + gl };
    case 'ohlc':
      return {
        type: 'ohlc',
        decreasing: { line: { color: _constants.COLORS.middleGray } },
        increasing: { line: { color: _constants.COLORS.blueTeal } }
      };
    case 'candlestick':
      return {
        type: 'candlestick',
        decreasing: {
          line: { color: _constants.COLORS.middleGray },
          fillcolor: 'rgba(127, 127, 127, 0.5)'
        },
        increasing: {
          line: { color: _constants.COLORS.blueTeal },
          fillcolor: 'rgba(23, 190, 207, 0.5)'
        }
      };
    case 'box':
      return {
        type: 'box',
        boxpoints: false
      };
    case 'violin':
      return {
        type: 'violin',
        bandwidth: 0
      };
    case 'line3d':
      return {
        type: 'scatter3d',
        mode: 'lines'
      };
    case 'scatter3d':
      return {
        type: 'scatter3d',
        mode: 'markers'
      };
    case 'bar':
      return {
        orientation: 'v',
        type: 'bar'
      };
    case 'cone':
      return {
        sizeref: 1,
        type: 'cone'
      };
    case 'histogram2dcontour':
      return {
        type: 'histogram2dcontour',
        autocolorscale: true
      };
    case 'histogram2d':
      return {
        type: 'histogram2d',
        autocolorscale: true
      };
    case 'heatmap':
      return {
        type: 'heatmap',
        autocolorscale: true
      };
    case 'contour':
      return {
        type: 'contour',
        autocolorscale: true
      };
    default:
      return { type: traceType };
  }
}
//# sourceMappingURL=customTraceType.js.map

/***/ }),

/***/ "W+nl":
/*!***********************************************!*\
  !*** ./node_modules/mdi-react/MagnifyIcon.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var MagnifyIcon = function MagnifyIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M9.5,3C13.09,3 16,5.91 16,9.5C16,11.11 15.41,12.59 14.44,13.73L14.71,14H15.5L20.5,19L19,20.5L14,15.5V14.71L13.73,14.44C12.59,15.41 11.11,16 9.5,16C5.91,16 3,13.09 3,9.5C3,5.91 5.91,3 9.5,3M9.5,5C7,5 5,7 5,9.5C5,12 7,14 9.5,14C12,14 14,12 14,9.5C14,7 12,5 9.5,5Z' })
  );
};

module.exports = MagnifyIcon;


/***/ }),

/***/ "W/R5":
/*!**************************************************************************!*\
  !*** ./node_modules/font-awesome/fonts/fontawesome-webfont.woff?v=4.7.0 ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__.p + "fee66e712a8a08eef5805a46892932ad.woff";

/***/ }),

/***/ "W070":
/*!*****************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_array-includes.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// false -> Array#indexOf
// true  -> Array#includes
var toIObject = __webpack_require__(/*! ./_to-iobject */ "NsO/");
var toLength = __webpack_require__(/*! ./_to-length */ "tEej");
var toAbsoluteIndex = __webpack_require__(/*! ./_to-absolute-index */ "D8kY");
module.exports = function (IS_INCLUDES) {
  return function ($this, el, fromIndex) {
    var O = toIObject($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) {
      if (O[index] === el) return IS_INCLUDES || index || 0;
    } return !IS_INCLUDES && -1;
  };
};


/***/ }),

/***/ "W2jp":
/*!******************************************************************!*\
  !*** ./node_modules/plotly.js/src/plots/animation_attributes.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



module.exports = {
    mode: {
        valType: 'enumerated',
        dflt: 'afterall',
        role: 'info',
        values: ['immediate', 'next', 'afterall'],
        description: [
            'Describes how a new animate call interacts with currently-running',
            'animations. If `immediate`, current animations are interrupted and',
            'the new animation is started. If `next`, the current frame is allowed',
            'to complete, after which the new animation is started. If `afterall`',
            'all existing frames are animated to completion before the new animation',
            'is started.'
        ].join(' ')
    },
    direction: {
        valType: 'enumerated',
        role: 'info',
        values: ['forward', 'reverse'],
        dflt: 'forward',
        description: [
            'The direction in which to play the frames triggered by the animation call'
        ].join(' ')
    },
    fromcurrent: {
        valType: 'boolean',
        dflt: false,
        role: 'info',
        description: [
            'Play frames starting at the current frame instead of the beginning.'
        ].join(' ')
    },
    frame: {
        duration: {
            valType: 'number',
            role: 'info',
            min: 0,
            dflt: 500,
            description: [
                'The duration in milliseconds of each frame. If greater than the frame',
                'duration, it will be limited to the frame duration.'
            ].join(' ')
        },
        redraw: {
            valType: 'boolean',
            role: 'info',
            dflt: true,
            description: [
                'Redraw the plot at completion of the transition. This is desirable',
                'for transitions that include properties that cannot be transitioned,',
                'but may significantly slow down updates that do not require a full',
                'redraw of the plot'
            ].join(' ')
        },
    },
    transition: {
        duration: {
            valType: 'number',
            role: 'info',
            min: 0,
            dflt: 500,
            editType: 'none',
            description: [
                'The duration of the transition, in milliseconds. If equal to zero,',
                'updates are synchronous.'
            ].join(' ')
        },
        easing: {
            valType: 'enumerated',
            dflt: 'cubic-in-out',
            values: [
                'linear',
                'quad',
                'cubic',
                'sin',
                'exp',
                'circle',
                'elastic',
                'back',
                'bounce',
                'linear-in',
                'quad-in',
                'cubic-in',
                'sin-in',
                'exp-in',
                'circle-in',
                'elastic-in',
                'back-in',
                'bounce-in',
                'linear-out',
                'quad-out',
                'cubic-out',
                'sin-out',
                'exp-out',
                'circle-out',
                'elastic-out',
                'back-out',
                'bounce-out',
                'linear-in-out',
                'quad-in-out',
                'cubic-in-out',
                'sin-in-out',
                'exp-in-out',
                'circle-in-out',
                'elastic-in-out',
                'back-in-out',
                'bounce-in-out'
            ],
            role: 'info',
            editType: 'none',
            description: 'The easing function used for the transition'
        },
        ordering: {
            valType: 'enumerated',
            values: ['layout first', 'traces first'],
            dflt: 'layout first',
            role: 'info',
            editType: 'none',
            description: [
                'Determines whether the figure\'s layout or traces smoothly transitions',
                'during updates that make both traces and layout change.'
            ].join(' ')
        }
    }
};


/***/ }),

/***/ "W3HW":
/*!***************************************************!*\
  !*** ./node_modules/reactcss/lib/flattenNames.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.flattenNames = undefined;

var _isString2 = __webpack_require__(/*! lodash/isString */ "4qC0");

var _isString3 = _interopRequireDefault(_isString2);

var _forOwn2 = __webpack_require__(/*! lodash/forOwn */ "Ag8Z");

var _forOwn3 = _interopRequireDefault(_forOwn2);

var _isPlainObject2 = __webpack_require__(/*! lodash/isPlainObject */ "YO3V");

var _isPlainObject3 = _interopRequireDefault(_isPlainObject2);

var _map2 = __webpack_require__(/*! lodash/map */ "3WF5");

var _map3 = _interopRequireDefault(_map2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var flattenNames = exports.flattenNames = function flattenNames() {
  var things = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];

  var names = [];

  (0, _map3.default)(things, function (thing) {
    if (Array.isArray(thing)) {
      flattenNames(thing).map(function (name) {
        return names.push(name);
      });
    } else if ((0, _isPlainObject3.default)(thing)) {
      (0, _forOwn3.default)(thing, function (value, key) {
        value === true && names.push(key);
        names.push(key + '-' + value);
      });
    } else if ((0, _isString3.default)(thing)) {
      names.push(thing);
    }
  });

  return names;
};

exports.default = flattenNames;

/***/ }),

/***/ "W3a3":
/*!*******************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyter-widgets/controls/css/phosphor.css ***!
  \*******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/* This file has code derived from PhosphorJS CSS files, as noted below. The license for this PhosphorJS code is:\n\nCopyright (c) 2014-2017, PhosphorJS Contributors\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\n* Neither the name of the copyright holder nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n\n/*\n * The following section is derived from https://github.com/phosphorjs/phosphor/blob/23b9d075ebc5b73ab148b6ebfc20af97f85714c4/packages/widgets/style/tabbar.css \n * We've scoped the rules so that they are consistent with exactly our code.\n */\n\n.jupyter-widgets.widget-tab > .p-TabBar {\n  display: flex;\n  -webkit-user-select: none;\n  -moz-user-select: none;\n  -ms-user-select: none;\n  user-select: none;\n}\n\n\n.jupyter-widgets.widget-tab > .p-TabBar[data-orientation='horizontal'] {\n  flex-direction: row;\n}\n\n\n.jupyter-widgets.widget-tab > .p-TabBar[data-orientation='vertical'] {\n  flex-direction: column;\n}\n\n\n.jupyter-widgets.widget-tab > .p-TabBar > .p-TabBar-content {\n  margin: 0;\n  padding: 0;\n  display: flex;\n  flex: 1 1 auto;\n  list-style-type: none;\n}\n\n\n.jupyter-widgets.widget-tab > .p-TabBar[data-orientation='horizontal'] > .p-TabBar-content {\n  flex-direction: row;\n}\n\n\n.jupyter-widgets.widget-tab > .p-TabBar[data-orientation='vertical'] > .p-TabBar-content {\n  flex-direction: column;\n}\n\n\n.jupyter-widgets.widget-tab > .p-TabBar .p-TabBar-tab {\n  display: flex;\n  flex-direction: row;\n  box-sizing: border-box;\n  overflow: hidden;\n}\n\n\n.jupyter-widgets.widget-tab > .p-TabBar .p-TabBar-tabIcon,\n.jupyter-widgets.widget-tab > .p-TabBar .p-TabBar-tabCloseIcon {\n  flex: 0 0 auto;\n}\n\n\n.jupyter-widgets.widget-tab > .p-TabBar .p-TabBar-tabLabel {\n  flex: 1 1 auto;\n  overflow: hidden;\n  white-space: nowrap;\n}\n\n\n.jupyter-widgets.widget-tab > .p-TabBar .p-TabBar-tab.p-mod-hidden {\n  display: none !important;\n}\n\n\n.jupyter-widgets.widget-tab > .p-TabBar.p-mod-dragging .p-TabBar-tab {\n  position: relative;\n}\n\n\n.jupyter-widgets.widget-tab > .p-TabBar.p-mod-dragging[data-orientation='horizontal'] .p-TabBar-tab {\n  left: 0;\n  transition: left 150ms ease;\n}\n\n\n.jupyter-widgets.widget-tab > .p-TabBar.p-mod-dragging[data-orientation='vertical'] .p-TabBar-tab {\n  top: 0;\n  transition: top 150ms ease;\n}\n\n\n.jupyter-widgets.widget-tab > .p-TabBar.p-mod-dragging .p-TabBar-tab.p-mod-dragging {\n  transition: none;\n}\n\n/* End tabbar.css */\n", ""]);

// exports


/***/ }),

/***/ "WASD":
/*!************************************************!*\
  !*** ./node_modules/htmlparser2/lib/Parser.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Tokenizer = __webpack_require__(/*! ./Tokenizer.js */ "b70m");

/*
	Options:

	xmlMode: Disables the special behavior for script/style tags (false by default)
	lowerCaseAttributeNames: call .toLowerCase for each attribute name (true if xmlMode is `false`)
	lowerCaseTags: call .toLowerCase for each tag name (true if xmlMode is `false`)
*/

/*
	Callbacks:

	oncdataend,
	oncdatastart,
	onclosetag,
	oncomment,
	oncommentend,
	onerror,
	onopentag,
	onprocessinginstruction,
	onreset,
	ontext
*/

var formTags = {
    input: true,
    option: true,
    optgroup: true,
    select: true,
    button: true,
    datalist: true,
    textarea: true
};

var openImpliesClose = {
    tr: { tr: true, th: true, td: true },
    th: { th: true },
    td: { thead: true, th: true, td: true },
    body: { head: true, link: true, script: true },
    li: { li: true },
    p: { p: true },
    h1: { p: true },
    h2: { p: true },
    h3: { p: true },
    h4: { p: true },
    h5: { p: true },
    h6: { p: true },
    select: formTags,
    input: formTags,
    output: formTags,
    button: formTags,
    datalist: formTags,
    textarea: formTags,
    option: { option: true },
    optgroup: { optgroup: true }
};

var voidElements = {
    __proto__: null,
    area: true,
    base: true,
    basefont: true,
    br: true,
    col: true,
    command: true,
    embed: true,
    frame: true,
    hr: true,
    img: true,
    input: true,
    isindex: true,
    keygen: true,
    link: true,
    meta: true,
    param: true,
    source: true,
    track: true,
    wbr: true
};

var foreignContextElements = {
    __proto__: null,
    math: true,
    svg: true
};
var htmlIntegrationElements = {
    __proto__: null,
    mi: true,
    mo: true,
    mn: true,
    ms: true,
    mtext: true,
    "annotation-xml": true,
    foreignObject: true,
    desc: true,
    title: true
};

var re_nameEnd = /\s|\//;

function Parser(cbs, options) {
    this._options = options || {};
    this._cbs = cbs || {};

    this._tagname = "";
    this._attribname = "";
    this._attribvalue = "";
    this._attribs = null;
    this._stack = [];
    this._foreignContext = [];

    this.startIndex = 0;
    this.endIndex = null;

    this._lowerCaseTagNames =
        "lowerCaseTags" in this._options
            ? !!this._options.lowerCaseTags
            : !this._options.xmlMode;
    this._lowerCaseAttributeNames =
        "lowerCaseAttributeNames" in this._options
            ? !!this._options.lowerCaseAttributeNames
            : !this._options.xmlMode;

    if (this._options.Tokenizer) {
        Tokenizer = this._options.Tokenizer;
    }
    this._tokenizer = new Tokenizer(this._options, this);

    if (this._cbs.onparserinit) this._cbs.onparserinit(this);
}

__webpack_require__(/*! inherits */ "P7XM")(Parser, __webpack_require__(/*! events */ "+qE3").EventEmitter);

Parser.prototype._updatePosition = function(initialOffset) {
    if (this.endIndex === null) {
        if (this._tokenizer._sectionStart <= initialOffset) {
            this.startIndex = 0;
        } else {
            this.startIndex = this._tokenizer._sectionStart - initialOffset;
        }
    } else this.startIndex = this.endIndex + 1;
    this.endIndex = this._tokenizer.getAbsoluteIndex();
};

//Tokenizer event handlers
Parser.prototype.ontext = function(data) {
    this._updatePosition(1);
    this.endIndex--;

    if (this._cbs.ontext) this._cbs.ontext(data);
};

Parser.prototype.onopentagname = function(name) {
    if (this._lowerCaseTagNames) {
        name = name.toLowerCase();
    }

    this._tagname = name;

    if (!this._options.xmlMode && name in openImpliesClose) {
        for (
            var el;
            (el = this._stack[this._stack.length - 1]) in
            openImpliesClose[name];
            this.onclosetag(el)
        );
    }

    if (this._options.xmlMode || !(name in voidElements)) {
        this._stack.push(name);
        if (name in foreignContextElements) this._foreignContext.push(true);
        else if (name in htmlIntegrationElements)
            this._foreignContext.push(false);
    }

    if (this._cbs.onopentagname) this._cbs.onopentagname(name);
    if (this._cbs.onopentag) this._attribs = {};
};

Parser.prototype.onopentagend = function() {
    this._updatePosition(1);

    if (this._attribs) {
        if (this._cbs.onopentag)
            this._cbs.onopentag(this._tagname, this._attribs);
        this._attribs = null;
    }

    if (
        !this._options.xmlMode &&
        this._cbs.onclosetag &&
        this._tagname in voidElements
    ) {
        this._cbs.onclosetag(this._tagname);
    }

    this._tagname = "";
};

Parser.prototype.onclosetag = function(name) {
    this._updatePosition(1);

    if (this._lowerCaseTagNames) {
        name = name.toLowerCase();
    }
    
    if (name in foreignContextElements || name in htmlIntegrationElements) {
        this._foreignContext.pop();
    }

    if (
        this._stack.length &&
        (!(name in voidElements) || this._options.xmlMode)
    ) {
        var pos = this._stack.lastIndexOf(name);
        if (pos !== -1) {
            if (this._cbs.onclosetag) {
                pos = this._stack.length - pos;
                while (pos--) this._cbs.onclosetag(this._stack.pop());
            } else this._stack.length = pos;
        } else if (name === "p" && !this._options.xmlMode) {
            this.onopentagname(name);
            this._closeCurrentTag();
        }
    } else if (!this._options.xmlMode && (name === "br" || name === "p")) {
        this.onopentagname(name);
        this._closeCurrentTag();
    }
};

Parser.prototype.onselfclosingtag = function() {
    if (
        this._options.xmlMode ||
        this._options.recognizeSelfClosing ||
        this._foreignContext[this._foreignContext.length - 1]
    ) {
        this._closeCurrentTag();
    } else {
        this.onopentagend();
    }
};

Parser.prototype._closeCurrentTag = function() {
    var name = this._tagname;

    this.onopentagend();

    //self-closing tags will be on the top of the stack
    //(cheaper check than in onclosetag)
    if (this._stack[this._stack.length - 1] === name) {
        if (this._cbs.onclosetag) {
            this._cbs.onclosetag(name);
        }
        this._stack.pop();
        
    }
};

Parser.prototype.onattribname = function(name) {
    if (this._lowerCaseAttributeNames) {
        name = name.toLowerCase();
    }
    this._attribname = name;
};

Parser.prototype.onattribdata = function(value) {
    this._attribvalue += value;
};

Parser.prototype.onattribend = function() {
    if (this._cbs.onattribute)
        this._cbs.onattribute(this._attribname, this._attribvalue);
    if (
        this._attribs &&
        !Object.prototype.hasOwnProperty.call(this._attribs, this._attribname)
    ) {
        this._attribs[this._attribname] = this._attribvalue;
    }
    this._attribname = "";
    this._attribvalue = "";
};

Parser.prototype._getInstructionName = function(value) {
    var idx = value.search(re_nameEnd),
        name = idx < 0 ? value : value.substr(0, idx);

    if (this._lowerCaseTagNames) {
        name = name.toLowerCase();
    }

    return name;
};

Parser.prototype.ondeclaration = function(value) {
    if (this._cbs.onprocessinginstruction) {
        var name = this._getInstructionName(value);
        this._cbs.onprocessinginstruction("!" + name, "!" + value);
    }
};

Parser.prototype.onprocessinginstruction = function(value) {
    if (this._cbs.onprocessinginstruction) {
        var name = this._getInstructionName(value);
        this._cbs.onprocessinginstruction("?" + name, "?" + value);
    }
};

Parser.prototype.oncomment = function(value) {
    this._updatePosition(4);

    if (this._cbs.oncomment) this._cbs.oncomment(value);
    if (this._cbs.oncommentend) this._cbs.oncommentend();
};

Parser.prototype.oncdata = function(value) {
    this._updatePosition(1);

    if (this._options.xmlMode || this._options.recognizeCDATA) {
        if (this._cbs.oncdatastart) this._cbs.oncdatastart();
        if (this._cbs.ontext) this._cbs.ontext(value);
        if (this._cbs.oncdataend) this._cbs.oncdataend();
    } else {
        this.oncomment("[CDATA[" + value + "]]");
    }
};

Parser.prototype.onerror = function(err) {
    if (this._cbs.onerror) this._cbs.onerror(err);
};

Parser.prototype.onend = function() {
    if (this._cbs.onclosetag) {
        for (
            var i = this._stack.length;
            i > 0;
            this._cbs.onclosetag(this._stack[--i])
        );
    }
    if (this._cbs.onend) this._cbs.onend();
};

//Resets the parser to a blank state, ready to parse a new HTML document
Parser.prototype.reset = function() {
    if (this._cbs.onreset) this._cbs.onreset();
    this._tokenizer.reset();

    this._tagname = "";
    this._attribname = "";
    this._attribs = null;
    this._stack = [];

    if (this._cbs.onparserinit) this._cbs.onparserinit(this);
};

//Parses a complete HTML document and pushes it to the handler
Parser.prototype.parseComplete = function(data) {
    this.reset();
    this.end(data);
};

Parser.prototype.write = function(chunk) {
    this._tokenizer.write(chunk);
};

Parser.prototype.end = function(chunk) {
    this._tokenizer.end(chunk);
};

Parser.prototype.pause = function() {
    this._tokenizer.pause();
};

Parser.prototype.resume = function() {
    this._tokenizer.resume();
};

//alias for backwards compat
Parser.prototype.parseChunk = Parser.prototype.write;
Parser.prototype.done = Parser.prototype.end;

module.exports = Parser;


/***/ }),

/***/ "WEpk":
/*!*******************************************************!*\
  !*** ./node_modules/core-js/library/modules/_core.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

var core = module.exports = { version: '2.6.5' };
if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef


/***/ }),

/***/ "WFjJ":
/*!***********************************************!*\
  !*** ./node_modules/react-color/lib/index.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CustomPicker = exports.TwitterPicker = exports.SwatchesPicker = exports.SliderPicker = exports.SketchPicker = exports.PhotoshopPicker = exports.MaterialPicker = exports.HuePicker = exports.GithubPicker = exports.CompactPicker = exports.ChromePicker = exports.default = exports.CirclePicker = exports.BlockPicker = exports.AlphaPicker = undefined;

var _Alpha = __webpack_require__(/*! ./components/alpha/Alpha */ "qo7Q");

Object.defineProperty(exports, 'AlphaPicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Alpha).default;
  }
});

var _Block = __webpack_require__(/*! ./components/block/Block */ "rJ8t");

Object.defineProperty(exports, 'BlockPicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Block).default;
  }
});

var _Circle = __webpack_require__(/*! ./components/circle/Circle */ "7dW+");

Object.defineProperty(exports, 'CirclePicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Circle).default;
  }
});

var _Chrome = __webpack_require__(/*! ./components/chrome/Chrome */ "JI00");

Object.defineProperty(exports, 'ChromePicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Chrome).default;
  }
});

var _Compact = __webpack_require__(/*! ./components/compact/Compact */ "oPLb");

Object.defineProperty(exports, 'CompactPicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Compact).default;
  }
});

var _Github = __webpack_require__(/*! ./components/github/Github */ "Lx/H");

Object.defineProperty(exports, 'GithubPicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Github).default;
  }
});

var _Hue = __webpack_require__(/*! ./components/hue/Hue */ "wkyg");

Object.defineProperty(exports, 'HuePicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Hue).default;
  }
});

var _Material = __webpack_require__(/*! ./components/material/Material */ "Jxpl");

Object.defineProperty(exports, 'MaterialPicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Material).default;
  }
});

var _Photoshop = __webpack_require__(/*! ./components/photoshop/Photoshop */ "FbP/");

Object.defineProperty(exports, 'PhotoshopPicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Photoshop).default;
  }
});

var _Sketch = __webpack_require__(/*! ./components/sketch/Sketch */ "HTXX");

Object.defineProperty(exports, 'SketchPicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Sketch).default;
  }
});

var _Slider = __webpack_require__(/*! ./components/slider/Slider */ "Pzom");

Object.defineProperty(exports, 'SliderPicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Slider).default;
  }
});

var _Swatches = __webpack_require__(/*! ./components/swatches/Swatches */ "t8r4");

Object.defineProperty(exports, 'SwatchesPicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Swatches).default;
  }
});

var _Twitter = __webpack_require__(/*! ./components/twitter/Twitter */ "nW7/");

Object.defineProperty(exports, 'TwitterPicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Twitter).default;
  }
});

var _ColorWrap = __webpack_require__(/*! ./components/common/ColorWrap */ "UGzO");

Object.defineProperty(exports, 'CustomPicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_ColorWrap).default;
  }
});

var _Chrome2 = _interopRequireDefault(_Chrome);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = _Chrome2.default;

/***/ }),

/***/ "WFqU":
/*!********************************************!*\
  !*** ./node_modules/lodash/_freeGlobal.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;

module.exports = freeGlobal;

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "WJOU":
/*!***************************************************!*\
  !*** ./node_modules/draft-js/lib/editOnSelect.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule editOnSelect
 * @format
 * 
 */



var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");
var ReactDOM = __webpack_require__(/*! react-dom */ "i8i4");

var getDraftEditorSelection = __webpack_require__(/*! ./getDraftEditorSelection */ "Zgb7");
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");

function editOnSelect(editor) {
  if (editor._blockSelectEvents || editor._latestEditorState !== editor.props.editorState) {
    return;
  }

  var editorState = editor.props.editorState;
  var editorNode = ReactDOM.findDOMNode(editor.editorContainer);
  !editorNode ?  true ? invariant(false, 'Missing editorNode') : undefined : void 0;
  !(editorNode.firstChild instanceof HTMLElement) ?  true ? invariant(false, 'editorNode.firstChild is not an HTMLElement') : undefined : void 0;
  var documentSelection = getDraftEditorSelection(editorState, editorNode.firstChild);
  var updatedSelectionState = documentSelection.selectionState;

  if (updatedSelectionState !== editorState.getSelection()) {
    if (documentSelection.needsRecovery) {
      editorState = EditorState.forceSelection(editorState, updatedSelectionState);
    } else {
      editorState = EditorState.acceptSelection(editorState, updatedSelectionState);
    }
    editor.update(editorState);
  }
}

module.exports = editOnSelect;

/***/ }),

/***/ "WKKt":
/*!**********************************************************!*\
  !*** ./node_modules/diffie-hellman/lib/generatePrime.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var randomBytes = __webpack_require__(/*! randombytes */ "Edxu");
module.exports = findPrime;
findPrime.simpleSieve = simpleSieve;
findPrime.fermatTest = fermatTest;
var BN = __webpack_require__(/*! bn.js */ "OZ/i");
var TWENTYFOUR = new BN(24);
var MillerRabin = __webpack_require__(/*! miller-rabin */ "ehAg");
var millerRabin = new MillerRabin();
var ONE = new BN(1);
var TWO = new BN(2);
var FIVE = new BN(5);
var SIXTEEN = new BN(16);
var EIGHT = new BN(8);
var TEN = new BN(10);
var THREE = new BN(3);
var SEVEN = new BN(7);
var ELEVEN = new BN(11);
var FOUR = new BN(4);
var TWELVE = new BN(12);
var primes = null;

function _getPrimes() {
  if (primes !== null)
    return primes;

  var limit = 0x100000;
  var res = [];
  res[0] = 2;
  for (var i = 1, k = 3; k < limit; k += 2) {
    var sqrt = Math.ceil(Math.sqrt(k));
    for (var j = 0; j < i && res[j] <= sqrt; j++)
      if (k % res[j] === 0)
        break;

    if (i !== j && res[j] <= sqrt)
      continue;

    res[i++] = k;
  }
  primes = res;
  return res;
}

function simpleSieve(p) {
  var primes = _getPrimes();

  for (var i = 0; i < primes.length; i++)
    if (p.modn(primes[i]) === 0) {
      if (p.cmpn(primes[i]) === 0) {
        return true;
      } else {
        return false;
      }
    }

  return true;
}

function fermatTest(p) {
  var red = BN.mont(p);
  return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0;
}

function findPrime(bits, gen) {
  if (bits < 16) {
    // this is what openssl does
    if (gen === 2 || gen === 5) {
      return new BN([0x8c, 0x7b]);
    } else {
      return new BN([0x8c, 0x27]);
    }
  }
  gen = new BN(gen);

  var num, n2;

  while (true) {
    num = new BN(randomBytes(Math.ceil(bits / 8)));
    while (num.bitLength() > bits) {
      num.ishrn(1);
    }
    if (num.isEven()) {
      num.iadd(ONE);
    }
    if (!num.testn(1)) {
      num.iadd(TWO);
    }
    if (!gen.cmp(TWO)) {
      while (num.mod(TWENTYFOUR).cmp(ELEVEN)) {
        num.iadd(FOUR);
      }
    } else if (!gen.cmp(FIVE)) {
      while (num.mod(TEN).cmp(THREE)) {
        num.iadd(FOUR);
      }
    }
    n2 = num.shrn(1);
    if (simpleSieve(n2) && simpleSieve(num) &&
      fermatTest(n2) && fermatTest(num) &&
      millerRabin.test(n2) && millerRabin.test(num)) {
      return num;
    }
  }

}


/***/ }),

/***/ "WLG0":
/*!****************************************************************!*\
  !*** ./node_modules/draft-js/lib/DraftEditorTextNode.react.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DraftEditorTextNode.react
 * @format
 * 
 */



function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var React = __webpack_require__(/*! react */ "q1tI");
var ReactDOM = __webpack_require__(/*! react-dom */ "i8i4");
var UserAgent = __webpack_require__(/*! fbjs/lib/UserAgent */ "CYTE");

var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");

// In IE, spans with <br> tags render as two newlines. By rendering a span
// with only a newline character, we can be sure to render a single line.
var useNewlineChar = UserAgent.isBrowser('IE <= 11');

/**
 * Check whether the node should be considered a newline.
 */
function isNewline(node) {
  return useNewlineChar ? node.textContent === '\n' : node.tagName === 'BR';
}

/**
 * Placeholder elements for empty text content.
 *
 * What is this `data-text` attribute, anyway? It turns out that we need to
 * put an attribute on the lowest-level text node in order to preserve correct
 * spellcheck handling. If the <span> is naked, Chrome and Safari may do
 * bizarre things to do the DOM -- split text nodes, create extra spans, etc.
 * If the <span> has an attribute, this appears not to happen.
 * See http://jsfiddle.net/9khdavod/ for the failure case, and
 * http://jsfiddle.net/7pg143f7/ for the fixed case.
 */
var NEWLINE_A = useNewlineChar ? React.createElement(
  'span',
  { key: 'A', 'data-text': 'true' },
  '\n'
) : React.createElement('br', { key: 'A', 'data-text': 'true' });

var NEWLINE_B = useNewlineChar ? React.createElement(
  'span',
  { key: 'B', 'data-text': 'true' },
  '\n'
) : React.createElement('br', { key: 'B', 'data-text': 'true' });

/**
 * The lowest-level component in a `DraftEditor`, the text node component
 * replaces the default React text node implementation. This allows us to
 * perform custom handling of newline behavior and avoid re-rendering text
 * nodes with DOM state that already matches the expectations of our immutable
 * editor state.
 */
var DraftEditorTextNode = function (_React$Component) {
  _inherits(DraftEditorTextNode, _React$Component);

  function DraftEditorTextNode(props) {
    _classCallCheck(this, DraftEditorTextNode);

    // By flipping this flag, we also keep flipping keys which forces
    // React to remount this node every time it rerenders.
    var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));

    _this._forceFlag = false;
    return _this;
  }

  DraftEditorTextNode.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
    var node = ReactDOM.findDOMNode(this);
    var shouldBeNewline = nextProps.children === '';
    !(node instanceof Element) ?  true ? invariant(false, 'node is not an Element') : undefined : void 0;
    if (shouldBeNewline) {
      return !isNewline(node);
    }
    return node.textContent !== nextProps.children;
  };

  DraftEditorTextNode.prototype.componentDidMount = function componentDidMount() {
    this._forceFlag = !this._forceFlag;
  };

  DraftEditorTextNode.prototype.componentDidUpdate = function componentDidUpdate() {
    this._forceFlag = !this._forceFlag;
  };

  DraftEditorTextNode.prototype.render = function render() {
    if (this.props.children === '') {
      return this._forceFlag ? NEWLINE_A : NEWLINE_B;
    }
    return React.createElement(
      'span',
      { key: this._forceFlag ? 'A' : 'B', 'data-text': 'true' },
      this.props.children
    );
  };

  return DraftEditorTextNode;
}(React.Component);

module.exports = DraftEditorTextNode;

/***/ }),

/***/ "WLfm":
/*!**************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/RectanglePositioner.js ***!
  \**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _reactResizableRotatableDraggable = __webpack_require__(/*! react-resizable-rotatable-draggable */ "84Sa");

var _reactResizableRotatableDraggable2 = _interopRequireDefault(_reactResizableRotatableDraggable);

var _RadioBlocks = __webpack_require__(/*! ../widgets/RadioBlocks */ "N8y9");

var _RadioBlocks2 = _interopRequireDefault(_RadioBlocks);

var _DualNumeric = __webpack_require__(/*! ./DualNumeric */ "x9uK");

var _DualNumeric2 = _interopRequireDefault(_DualNumeric);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var maxWidth = 276;
var gridRes = 8;

var UnconnectedRectanglePositioner = function (_Component) {
  _inherits(UnconnectedRectanglePositioner, _Component);

  function UnconnectedRectanglePositioner(props, context) {
    _classCallCheck(this, UnconnectedRectanglePositioner);

    var _this = _possibleConstructorReturn(this, (UnconnectedRectanglePositioner.__proto__ || Object.getPrototypeOf(UnconnectedRectanglePositioner)).call(this, props, context));

    _this.sendUpdate = _this.sendUpdate.bind(_this);
    _this.attr = _this.props.cartesian ? {
      x: ['xaxis.domain[0]', 'xaxis.domain[1]'],
      y: ['yaxis.domain[0]', 'yaxis.domain[1]']
    } : { x: ['domain.x[0]', 'domain.x[1]'], y: ['domain.y[0]', 'domain.y[1]'] };
    _this.state = { snap: true };
    return _this;
  }

  _createClass(UnconnectedRectanglePositioner, [{
    key: 'sendUpdate',
    value: function sendUpdate(_ref) {
      var x = _ref.x,
          y = _ref.y,
          width = _ref.width,
          height = _ref.height,
          fieldWidthPx = _ref.fieldWidthPx,
          fieldHeightPx = _ref.fieldHeightPx;

      var x0 = x / fieldWidthPx;
      var x1 = (width + x) / fieldWidthPx;
      var y0 = (fieldHeightPx - (height + y)) / fieldHeightPx;
      var y1 = (fieldHeightPx - y) / fieldHeightPx;

      var snap = this.state.snap ? function (v) {
        return Math.round(v * gridRes) / gridRes;
      } : function (v) {
        return v;
      };

      var payload = {};

      if (x0 >= 0 && x1 <= 1) {
        payload[this.attr.x[0]] = snap(x0);
        payload[this.attr.x[1]] = snap(x1);
      }

      if (y0 >= 0 && y1 <= 1) {
        payload[this.attr.y[0]] = snap(y0);
        payload[this.attr.y[1]] = snap(y1);
      }

      this.context.updateContainer(payload);
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _props = this.props,
          attr = _props.attr,
          cartesian = _props.cartesian;
      var _context = this.context,
          _ = _context.localize,
          fullContainer = _context.fullContainer,
          _context$fullLayout = _context.fullLayout,
          plotWidthPx = _context$fullLayout.width,
          plotHeightPx = _context$fullLayout.height;

      var x = cartesian ? fullContainer.xaxis.domain : fullContainer.domain.x;
      var y = cartesian ? fullContainer.yaxis.domain : fullContainer.domain.y;
      var aspectRatio = plotHeightPx / plotWidthPx;
      var fieldWidthPx = Math.min(maxWidth, maxWidth / aspectRatio);
      var fieldHeightPx = Math.min(maxWidth, maxWidth * aspectRatio);

      var width = fieldWidthPx * (x[1] - x[0]);
      var height = fieldHeightPx * (y[1] - y[0]);
      var left = fieldWidthPx * x[0];
      var top = fieldHeightPx * (1 - y[1]);

      var zoomable = '';
      if (!fullContainer.xaxis || !fullContainer.yaxis || !fullContainer.xaxis.overlaying && !fullContainer.yaxis.overlaying) {
        zoomable = 'n, w, s, e, nw, ne, se, sw';
      } else if (!fullContainer.xaxis.overlaying) {
        zoomable = 'e, w';
      } else if (!fullContainer.yaxis.overlaying) {
        zoomable = 'n, s';
      }

      return _react2.default.createElement(
        'div',
        { style: { marginRight: 25 } },
        _react2.default.createElement(
          _Field2.default,
          _extends({}, this.props, { attr: attr }),
          _react2.default.createElement(
            _Field2.default,
            { label: _('Snap to Grid') },
            _react2.default.createElement(_RadioBlocks2.default, {
              alignment: 'center',
              onOptionChange: function onOptionChange(snap) {
                return _this2.setState({ snap: snap });
              },
              activeOption: this.state.snap,
              options: [{ label: _('On'), value: true }, { label: _('Off'), value: false }]
            })
          ),
          _react2.default.createElement(
            'div',
            {
              className: 'rect-container',
              style: {
                width: fieldWidthPx + 1,
                height: fieldHeightPx + 1
              }
            },
            Array(gridRes * gridRes).fill(0).map(function (v, i) {
              return _react2.default.createElement('div', {
                key: i,
                className: 'rect-grid',
                style: {
                  width: fieldWidthPx / gridRes - 1,
                  height: fieldHeightPx / gridRes - 1,
                  borderBottom: i < gridRes * (gridRes - 1) ? '0' : '1px solid ',
                  borderRight: (i + 1) % gridRes ? '0' : '1px solid'
                }
              });
            }),
            _react2.default.createElement(_reactResizableRotatableDraggable2.default, {
              bounds: 'parent',
              width: width,
              height: height,
              left: left,
              top: top,
              rotatable: false,
              draggable: !this.state.snap,
              zoomable: zoomable,
              onResize: function onResize(style) {
                _this2.sendUpdate({
                  fieldWidthPx: fieldWidthPx,
                  fieldHeightPx: fieldHeightPx,
                  width: style.width,
                  height: style.height,
                  x: style.left,
                  y: style.top
                });
              },
              onDrag: function onDrag(deltaX, deltaY) {
                _this2.sendUpdate({
                  fieldWidthPx: fieldWidthPx,
                  fieldHeightPx: fieldHeightPx,
                  width: width,
                  height: height,
                  x: left + deltaX,
                  y: top + deltaY
                });
              }
            })
          ),
          fullContainer.xaxis && fullContainer.xaxis.overlaying ? '' : _react2.default.createElement(_DualNumeric2.default, {
            label: _('X'),
            attr: this.attr.x[0],
            attr2: this.attr.x[1],
            percentage: true,
            step: 1,
            min: 0,
            max: 100
          }),
          fullContainer.yaxis && fullContainer.yaxis.overlaying ? '' : _react2.default.createElement(_DualNumeric2.default, {
            label: _('Y'),
            attr: this.attr.y[0],
            attr2: this.attr.y[1],
            percentage: true,
            step: 1,
            min: 0,
            max: 100
          })
        )
      );
    }
  }]);

  return UnconnectedRectanglePositioner;
}(_react.Component);

UnconnectedRectanglePositioner.propTypes = _extends({
  fullValue: _propTypes2.default.any,
  updatePlot: _propTypes2.default.func,
  cartesian: _propTypes2.default.bool
}, _Field2.default.propTypes);

UnconnectedRectanglePositioner.contextTypes = {
  localize: _propTypes2.default.func,
  updateContainer: _propTypes2.default.func,
  fullContainer: _propTypes2.default.object,
  fullLayout: _propTypes2.default.object
};

exports.default = (0, _lib.connectToContainer)(UnconnectedRectanglePositioner);
//# sourceMappingURL=RectanglePositioner.js.map

/***/ }),

/***/ "WMCC":
/*!********************************************************!*\
  !*** ./node_modules/@jupyterlab/coreutils/lib/time.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const moment_1 = __importDefault(__webpack_require__(/*! moment */ "wd/R"));
/**
 * The namespace for date functions.
 */
var Time;
(function (Time) {
    /**
     * Convert a timestring to a human readable string (e.g. 'two minutes ago').
     *
     * @param value - The date timestring or date object.
     *
     * @returns A formatted date.
     */
    function formatHuman(value) {
        let time = moment_1.default(value).fromNow();
        time = time === 'a few seconds ago' ? 'seconds ago' : time;
        return time;
    }
    Time.formatHuman = formatHuman;
    /**
     * Convert a timestring to a date format.
     *
     * @param value - The date timestring or date object.
     *
     * @param format - The format string.
     *
     * @returns A formatted date.
     */
    function format(value, format = 'YYYY-MM-DD HH:mm') {
        return moment_1.default(value).format(format);
    }
    Time.format = format;
})(Time = exports.Time || (exports.Time = {}));


/***/ }),

/***/ "WRkp":
/*!**********************************************!*\
  !*** ./node_modules/hash.js/lib/hash/sha.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.sha1 = __webpack_require__(/*! ./sha/1 */ "E+IA");
exports.sha224 = __webpack_require__(/*! ./sha/224 */ "B/J0");
exports.sha256 = __webpack_require__(/*! ./sha/256 */ "bu2F");
exports.sha384 = __webpack_require__(/*! ./sha/384 */ "i5UE");
exports.sha512 = __webpack_require__(/*! ./sha/512 */ "tSWc");


/***/ }),

/***/ "WS6A":
/*!********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/MenuPanel.js ***!
  \********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _ModalBox = __webpack_require__(/*! ./ModalBox */ "AKwq");

var _ModalBox2 = _interopRequireDefault(_ModalBox);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _classnames = __webpack_require__(/*! classnames */ "TSYQ");

var _classnames2 = _interopRequireDefault(_classnames);

var _plotlyIcons = __webpack_require__(/*! plotly-icons */ "hwSx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var MenuPanel = function (_Component) {
  _inherits(MenuPanel, _Component);

  function MenuPanel() {
    _classCallCheck(this, MenuPanel);

    var _this = _possibleConstructorReturn(this, (MenuPanel.__proto__ || Object.getPrototypeOf(MenuPanel)).call(this));

    _this.state = { isOpen: false };

    _this.togglePanel = _this.togglePanel.bind(_this);
    return _this;
  }

  _createClass(MenuPanel, [{
    key: 'getIcon',
    value: function getIcon() {
      var _props = this.props,
          question = _props.question,
          Icon = _props.icon;

      if (question) {
        return {
          icon: _react2.default.createElement(_plotlyIcons.QuestionIcon, { className: 'menupanel__icon' }),
          spanClass: 'menupanel__icon-span menupanel__icon-span--question'
        };
      }
      if (Icon) {
        return {
          icon: _react2.default.createElement(Icon, { className: 'menupanel__icon' }),
          spanClass: 'menupanel__icon-span'
        };
      }
      return {
        icon: _react2.default.createElement(_plotlyIcons.CogIcon, { className: 'menupanel__icon' }),
        spanClass: 'menupanel__icon-span menupanel__icon-span--cog'
      };
    }
  }, {
    key: 'togglePanel',
    value: function togglePanel() {
      this.setState({ isOpen: !this.state.isOpen });
    }
  }, {
    key: 'render',
    value: function render() {
      var _props2 = this.props,
          show = _props2.show,
          ownline = _props2.ownline,
          label = _props2.label,
          children = _props2.children;

      var isOpen = show || this.state.isOpen;

      var containerClass = (0, _classnames2.default)('menupanel', {
        'menupanel--ownline': ownline
      });

      var _getIcon = this.getIcon(),
          icon = _getIcon.icon,
          spanClass = _getIcon.spanClass;

      return _react2.default.createElement(
        'div',
        { className: containerClass },
        _react2.default.createElement(
          'div',
          { className: spanClass },
          _react2.default.createElement(
            'div',
            { className: 'menupanel__label' },
            label
          ),
          _react2.default.createElement(
            'div',
            { className: 'menupanel__icon__wrapper', onClick: this.togglePanel },
            icon
          )
        ),
        isOpen && _react2.default.createElement(
          _ModalBox2.default,
          { onClose: this.togglePanel },
          children
        )
      );
    }
  }]);

  return MenuPanel;
}(_react.Component);

exports.default = MenuPanel;


MenuPanel.propTypes = {
  children: _propTypes2.default.node,
  icon: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]),
  label: _propTypes2.default.string,
  ownline: _propTypes2.default.bool,
  question: _propTypes2.default.bool,
  show: _propTypes2.default.bool
};
//# sourceMappingURL=MenuPanel.js.map

/***/ }),

/***/ "WWhV":
/*!********************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/unpackPlotProps.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = unpackPlotProps;

var _nested_property = __webpack_require__(/*! plotly.js/src/lib/nested_property */ "dNZO");

var _nested_property2 = _interopRequireDefault(_nested_property);

var _fastIsnumeric = __webpack_require__(/*! fast-isnumeric */ "GbLo");

var _fastIsnumeric2 = _interopRequireDefault(_fastIsnumeric);

var _constants = __webpack_require__(/*! ./constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function unpackPlotProps(props, context) {
  var container = context.container,
      getValObject = context.getValObject,
      defaultContainer = context.defaultContainer,
      updateContainer = context.updateContainer;


  if (!props.attr) {
    return {};
  }

  var attrMeta = void 0;
  if (getValObject) {
    attrMeta = context.getValObject(props.attr) || {};
  }

  var fullContainer = context.fullContainer;

  var fullProperty = (0, _nested_property2.default)(fullContainer, props.attr);
  var fullValue = fullProperty.get();
  var multiValued = false;

  // MULTI_VALUED consists of a control sequence that cannot be confused with
  // user data. We must transform it into something that can be displayed as
  // the screen.
  if (fullValue === _constants.MULTI_VALUED) {
    fullValue = _constants.MULTI_VALUED_PLACEHOLDER;
    multiValued = true;
  }

  var isVisible = false;
  if (props.show || fullValue !== void 0 && fullValue !== null) {
    isVisible = true;
  }

  var defaultValue = props.defaultValue;
  if (defaultValue === void 0 && defaultContainer) {
    defaultValue = (0, _nested_property2.default)(defaultContainer, props.attr).get();
  }

  var min = void 0,
      max = void 0,
      description = void 0;
  if (attrMeta) {
    if ((0, _fastIsnumeric2.default)(attrMeta.max)) {
      max = attrMeta.max;
    }
    if ((0, _fastIsnumeric2.default)(attrMeta.min)) {
      min = attrMeta.min;
    }

    description = attrMeta.description;
  }

  var updatePlot = function updatePlot(v) {
    if (updateContainer) {
      updateContainer(_defineProperty({}, props.attr, v));
    }
  };

  return {
    attrMeta: attrMeta,
    container: container,
    defaultValue: defaultValue,
    fullContainer: fullContainer,
    fullValue: fullValue,
    getValObject: getValObject,
    isVisible: isVisible,
    max: max,
    min: min,
    description: description,
    multiValued: multiValued,
    updateContainer: updateContainer,
    updatePlot: updatePlot
  };
}
//# sourceMappingURL=unpackPlotProps.js.map

/***/ }),

/***/ "WYrj":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/dv.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var months = [
    'ޖެނުއަރީ',
    'ފެބްރުއަރީ',
    'މާރިޗު',
    'އޭޕްރީލު',
    'މޭ',
    'ޖޫން',
    'ޖުލައި',
    'އޯގަސްޓު',
    'ސެޕްޓެމްބަރު',
    'އޮކްޓޯބަރު',
    'ނޮވެމްބަރު',
    'ޑިސެމްބަރު'
], weekdays = [
    'އާދިއްތަ',
    'ހޯމަ',
    'އަންގާރަ',
    'ބުދަ',
    'ބުރާސްފަތި',
    'ހުކުރު',
    'ހޮނިހިރު'
];

var dv = moment.defineLocale('dv', {
    months : months,
    monthsShort : months,
    weekdays : weekdays,
    weekdaysShort : weekdays,
    weekdaysMin : 'އާދި_ހޯމަ_އަން_ބުދަ_ބުރާ_ހުކު_ހޮނި'.split('_'),
    longDateFormat : {

        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'D/M/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd D MMMM YYYY HH:mm'
    },
    meridiemParse: /މކ|މފ/,
    isPM : function (input) {
        return 'މފ' === input;
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 12) {
            return 'މކ';
        } else {
            return 'މފ';
        }
    },
    calendar : {
        sameDay : '[މިއަދު] LT',
        nextDay : '[މާދަމާ] LT',
        nextWeek : 'dddd LT',
        lastDay : '[އިއްޔެ] LT',
        lastWeek : '[ފާއިތުވި] dddd LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'ތެރޭގައި %s',
        past : 'ކުރިން %s',
        s : 'ސިކުންތުކޮޅެއް',
        ss : 'd% ސިކުންތު',
        m : 'މިނިޓެއް',
        mm : 'މިނިޓު %d',
        h : 'ގަޑިއިރެއް',
        hh : 'ގަޑިއިރު %d',
        d : 'ދުވަހެއް',
        dd : 'ދުވަސް %d',
        M : 'މަހެއް',
        MM : 'މަސް %d',
        y : 'އަހަރެއް',
        yy : 'އަހަރު %d'
    },
    preparse: function (string) {
        return string.replace(/،/g, ',');
    },
    postformat: function (string) {
        return string.replace(/,/g, '،');
    },
    week : {
        dow : 7,  // Sunday is the first day of the week.
        doy : 12  // The week that contains Jan 1st is the first week of the year.
    }
});

return dv;

})));


/***/ }),

/***/ "WZUU":
/*!************************************************************!*\
  !*** ./node_modules/react-tabs/esm/components/TabPanel.js ***!
  \************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TabPanel; });
/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! prop-types */ "17x9");
/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(prop_types__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "q1tI");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! classnames */ "TSYQ");
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(classnames__WEBPACK_IMPORTED_MODULE_2__);
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }




var DEFAULT_CLASS = 'react-tabs__tab-panel';

var TabPanel =
/*#__PURE__*/
function (_Component) {
  _inheritsLoose(TabPanel, _Component);

  function TabPanel() {
    return _Component.apply(this, arguments) || this;
  }

  var _proto = TabPanel.prototype;

  _proto.render = function render() {
    var _cx;

    var _this$props = this.props,
        children = _this$props.children,
        className = _this$props.className,
        forceRender = _this$props.forceRender,
        id = _this$props.id,
        selected = _this$props.selected,
        selectedClassName = _this$props.selectedClassName,
        tabId = _this$props.tabId,
        attributes = _objectWithoutPropertiesLoose(_this$props, ["children", "className", "forceRender", "id", "selected", "selectedClassName", "tabId"]);

    return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", _extends({}, attributes, {
      className: classnames__WEBPACK_IMPORTED_MODULE_2___default()(className, (_cx = {}, _cx[selectedClassName] = selected, _cx)),
      role: "tabpanel",
      id: id,
      "aria-labelledby": tabId
    }), forceRender || selected ? children : null);
  };

  return TabPanel;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]);

TabPanel.defaultProps = {
  className: DEFAULT_CLASS,
  forceRender: false,
  selectedClassName: DEFAULT_CLASS + "--selected"
};

TabPanel.propTypes =  true ? {
  children: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.node,
  className: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.array, prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.object]),
  forceRender: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.bool,
  id: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.string,
  // private
  selected: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.bool,
  // private
  selectedClassName: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.string,
  tabId: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.string // private

} : undefined;
TabPanel.tabsRole = 'TabPanel';

/***/ }),

/***/ "WbBG":
/*!*************************************************************!*\
  !*** ./node_modules/prop-types/lib/ReactPropTypesSecret.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */



var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';

module.exports = ReactPropTypesSecret;


/***/ }),

/***/ "Wd7j":
/*!*****************************************************************************!*\
  !*** ./node_modules/@jupyter-widgets/jupyterlab-manager/lib/semvercache.js ***!
  \*****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const semver_1 = __webpack_require__(/*! semver */ "jWEn");
/**
 * A cache using semver ranges to retrieve values.
 */
class SemVerCache {
    constructor() {
        this._cache = Object.create(null);
    }
    set(key, version, object) {
        if (!(key in this._cache)) {
            this._cache[key] = Object.create(null);
        }
        if (!(version in this._cache[key])) {
            this._cache[key][version] = object;
        }
        else {
            throw `Version ${version} of key ${key} already registered.`;
        }
    }
    get(key, semver) {
        if (key in this._cache) {
            let versions = this._cache[key];
            let best = semver_1.maxSatisfying(Object.keys(versions), semver);
            return versions[best];
        }
    }
}
exports.SemVerCache = SemVerCache;


/***/ }),

/***/ "Wdip":
/*!***************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/codemirror/style/index.css ***!
  \***************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports
exports.i(__webpack_require__(/*! -!../../../css-loader!codemirror/lib/codemirror.css */ "/GrO"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!codemirror/addon/dialog/dialog.css */ "RQux"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!codemirror/theme/material.css */ "Cj/q"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!codemirror/theme/zenburn.css */ "m+Ef"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!codemirror/theme/abcdef.css */ "dn6z"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!codemirror/theme/base16-light.css */ "RhoE"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!codemirror/theme/base16-dark.css */ "D+M8"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!codemirror/theme/dracula.css */ "EJhI"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!codemirror/theme/hopscotch.css */ "sK/K"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!codemirror/theme/mbo.css */ "E5mV"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!codemirror/theme/mdn-like.css */ "AO6+"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!codemirror/theme/seti.css */ "hlmY"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!codemirror/theme/solarized.css */ "jroS"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!codemirror/theme/the-matrix.css */ "6/8d"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!codemirror/theme/xq-light.css */ "uY1N"), "");

// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.CodeMirror {\n  line-height: var(--jp-code-line-height);\n  font-size: var(--jp-code-font-size);\n  font-family: var(--jp-code-font-family);\n  height: auto;\n  /* Changed to auto to autogrow */\n}\n\n.CodeMirror pre {\n  padding: 0;\n  border: 0;\n  border-radius: 0;\n}\n\n.jp-CodeMirrorEditor[data-type='inline'] .CodeMirror-dialog {\n  background-color: var(--jp-layout-color0);\n  color: var(--jp-content-font-color1);\n}\n\n/* This causes https://github.com/jupyter/jupyterlab/issues/522 */\n/* May not cause it not because we changed it! */\n.CodeMirror-lines {\n  padding: var(--jp-code-padding);\n}\n\n.CodeMirror-linenumbers {\n  padding: 0 4px 0 4px;\n}\n\n.jp-CodeMirrorEditor-static {\n  margin: var(--jp-code-padding);\n}\n\n.jp-CodeMirrorEditor,\n.jp-CodeMirrorEditor-static {\n  cursor: text;\n}\n\n.jp-CodeMirrorEditor[data-type='inline'] .CodeMirror-cursor {\n  border-left: 1.4px solid var(--jp-editor-cursor-color);\n}\n\n/* When zoomed out 67% and 33% on a screen of 1440 width x 900 height */\n@media screen and (min-width: 2138px) and (max-width: 4319px) {\n  .jp-CodeMirrorEditor[data-type='inline'] .CodeMirror-cursor {\n    border-left: 2px solid var(--jp-editor-cursor-color);\n  }\n}\n\n/* When zoomed out less than 33% */\n@media screen and (min-width: 4320px) {\n  .jp-CodeMirrorEditor[data-type='inline'] .CodeMirror-cursor {\n    border-left: 4px solid var(--jp-editor-cursor-color);\n  }\n}\n\n.CodeMirror.jp-mod-readOnly .CodeMirror-cursor {\n  display: none;\n}\n\n.CodeMirror-gutters {\n  border-right: 1px solid var(--jp-border-color2);\n  background-color: var(--jp-layout-color2);\n}\n\n.CodeMirror-gutter-wrapper {\n  margin-left: calc(-1 * var(--jp-code-padding));\n}\n\n.jp-CollaboratorCursor {\n  border-left: 5px solid transparent;\n  border-right: 5px solid transparent;\n  border-top: none;\n  border-bottom: 3px solid;\n  background-clip: content-box;\n  margin-left: -5px;\n  margin-right: -5px;\n}\n\n.CodeMirror-focused .CodeMirror-selected {\n  background-color: var(--jp-editor-selected-focused-background);\n}\n\n.CodeMirror-selected {\n  background-color: var(--jp-editor-selected-background);\n}\n\n.jp-CollaboratorCursor-hover {\n  position: absolute;\n  z-index: 1;\n  transform: translateX(-50%);\n  color: white;\n  border-radius: 3px;\n  padding-left: 4px;\n  padding-right: 4px;\n  padding-top: 1px;\n  padding-bottom: 1px;\n  text-align: center;\n  font-size: var(--jp-ui-font-size1);\n  white-space: nowrap;\n}\n\n/**\n * Here is our jupyter theme for CodeMirror syntax highlighting\n * This is used in our marked.js syntax highlighting and CodeMirror itself\n * The string \"jupyter\" is set in ../codemirror/widget.DEFAULT_CODEMIRROR_THEME\n * This came from the classic notebook, which came form highlight.js/GitHub\n */\n\n/**\n * CodeMirror themes are handling the background/color in this way. This works\n * fine for CodeMirror editors outside the notebook, but the notebook styles\n * these things differently.\n */\n.CodeMirror.cm-s-jupyter {\n  background: var(--jp-layout-color0);\n  color: var(--jp-content-font-color1);\n}\n\n/* In the notebook, we want this styling to be handled by its container */\n.jp-CodeConsole .CodeMirror.cm-s-jupyter,\n.jp-Notebook .CodeMirror.cm-s-jupyter {\n  background: transparent;\n}\n\n.cm-s-jupyter .CodeMirror-cursor {\n  border-left: 1.4px solid var(--jp-editor-cursor-color);\n}\n.cm-s-jupyter span.cm-keyword {\n  color: var(--jp-mirror-editor-keyword-color);\n  font-weight: bold;\n}\n.cm-s-jupyter span.cm-atom {\n  color: var(--jp-mirror-editor-atom-color);\n}\n.cm-s-jupyter span.cm-number {\n  color: var(--jp-mirror-editor-number-color);\n}\n.cm-s-jupyter span.cm-def {\n  color: var(--jp-mirror-editor-def-color);\n}\n.cm-s-jupyter span.cm-variable {\n  color: var(--jp-mirror-editor-variable-color);\n}\n.cm-s-jupyter span.cm-variable-2 {\n  color: var(--jp-mirror-editor-variable-2-color);\n}\n.cm-s-jupyter span.cm-variable-3 {\n  color: var(--jp-mirror-editor-variable-3-color);\n}\n.cm-s-jupyter span.cm-punctuation {\n  color: var(--jp-mirror-editor-punctuation-color);\n}\n.cm-s-jupyter span.cm-property {\n  color: var(--jp-mirror-editor-property-color);\n}\n.cm-s-jupyter span.cm-operator {\n  color: var(--jp-mirror-editor-operator-color);\n  font-weight: bold;\n}\n.cm-s-jupyter span.cm-comment {\n  color: var(--jp-mirror-editor-comment-color);\n  font-style: italic;\n}\n.cm-s-jupyter span.cm-string {\n  color: var(--jp-mirror-editor-string-color);\n}\n.cm-s-jupyter span.cm-string-2 {\n  color: var(--jp-mirror-editor-string-2-color);\n}\n.cm-s-jupyter span.cm-meta {\n  color: var(--jp-mirror-editor-meta-color);\n}\n.cm-s-jupyter span.cm-qualifier {\n  color: var(--jp-mirror-editor-qualifier-color);\n}\n.cm-s-jupyter span.cm-builtin {\n  color: var(--jp-mirror-editor-builtin-color);\n}\n.cm-s-jupyter span.cm-bracket {\n  color: var(--jp-mirror-editor-bracket-color);\n}\n.cm-s-jupyter span.cm-tag {\n  color: var(--jp-mirror-editor-tag-color);\n}\n.cm-s-jupyter span.cm-attribute {\n  color: var(--jp-mirror-editor-attribute-color);\n}\n.cm-s-jupyter span.cm-header {\n  color: var(--jp-mirror-editor-header-color);\n}\n.cm-s-jupyter span.cm-quote {\n  color: var(--jp-mirror-editor-quote-color);\n}\n.cm-s-jupyter span.cm-link {\n  color: var(--jp-mirror-editor-link-color);\n}\n.cm-s-jupyter span.cm-error {\n  color: var(--jp-mirror-editor-error-color);\n}\n.cm-s-jupyter span.cm-hr {\n  color: #999;\n}\n\n.cm-s-jupyter span.cm-tab {\n  background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAMCAYAAAAkuj5RAAAAAXNSR0IArs4c6QAAAGFJREFUSMft1LsRQFAQheHPowAKoACx3IgEKtaEHujDjORSgWTH/ZOdnZOcM/sgk/kFFWY0qV8foQwS4MKBCS3qR6ixBJvElOobYAtivseIE120FaowJPN75GMu8j/LfMwNjh4HUpwg4LUAAAAASUVORK5CYII=);\n  background-position: right;\n  background-repeat: no-repeat;\n}\n", ""]);

// exports


/***/ }),

/***/ "Wg3t":
/*!******************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/kernel/messages.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
/**
 * A namespace for kernel messages.
 */
var KernelMessage;
(function (KernelMessage) {
    /**
     * Create a well-formed kernel message.
     */
    function createMessage(options, content = {}, metadata = {}, buffers = []) {
        return {
            header: {
                username: options.username || '',
                version: '5.2',
                session: options.session,
                msg_id: options.msgId || coreutils_1.UUID.uuid4(),
                msg_type: options.msgType
            },
            parent_header: {},
            channel: options.channel,
            content,
            metadata,
            buffers
        };
    }
    KernelMessage.createMessage = createMessage;
    /**
     * Create a well-formed kernel shell message.
     */
    function createShellMessage(options, content = {}, metadata = {}, buffers = []) {
        let msg = createMessage(options, content, metadata, buffers);
        return msg;
    }
    KernelMessage.createShellMessage = createShellMessage;
    /**
     * Test whether a kernel message is a `'stream'` message.
     */
    function isStreamMsg(msg) {
        return msg.header.msg_type === 'stream';
    }
    KernelMessage.isStreamMsg = isStreamMsg;
    /**
     * Test whether a kernel message is an `'display_data'` message.
     */
    function isDisplayDataMsg(msg) {
        return msg.header.msg_type === 'display_data';
    }
    KernelMessage.isDisplayDataMsg = isDisplayDataMsg;
    /**
     * Test whether a kernel message is an `'update_display_data'` message.
     */
    function isUpdateDisplayDataMsg(msg) {
        return msg.header.msg_type === 'update_display_data';
    }
    KernelMessage.isUpdateDisplayDataMsg = isUpdateDisplayDataMsg;
    /**
     * Test whether a kernel message is an `'execute_input'` message.
     */
    function isExecuteInputMsg(msg) {
        return msg.header.msg_type === 'execute_input';
    }
    KernelMessage.isExecuteInputMsg = isExecuteInputMsg;
    /**
     * Test whether a kernel message is an `'execute_result'` message.
     */
    function isExecuteResultMsg(msg) {
        return msg.header.msg_type === 'execute_result';
    }
    KernelMessage.isExecuteResultMsg = isExecuteResultMsg;
    /**
     * Test whether a kernel message is an `'error'` message.
     */
    function isErrorMsg(msg) {
        return msg.header.msg_type === 'error';
    }
    KernelMessage.isErrorMsg = isErrorMsg;
    /**
     * Test whether a kernel message is a `'status'` message.
     */
    function isStatusMsg(msg) {
        return msg.header.msg_type === 'status';
    }
    KernelMessage.isStatusMsg = isStatusMsg;
    /**
     * Test whether a kernel message is a `'clear_output'` message.
     */
    function isClearOutputMsg(msg) {
        return msg.header.msg_type === 'clear_output';
    }
    KernelMessage.isClearOutputMsg = isClearOutputMsg;
    /**
     * Test whether a kernel message is a `'comm_open'` message.
     */
    function isCommOpenMsg(msg) {
        return msg.header.msg_type === 'comm_open';
    }
    KernelMessage.isCommOpenMsg = isCommOpenMsg;
    /**
     * Test whether a kernel message is a `'comm_close'` message.
     */
    function isCommCloseMsg(msg) {
        return msg.header.msg_type === 'comm_close';
    }
    KernelMessage.isCommCloseMsg = isCommCloseMsg;
    /**
     * Test whether a kernel message is a `'comm_msg'` message.
     */
    function isCommMsgMsg(msg) {
        return msg.header.msg_type === 'comm_msg';
    }
    KernelMessage.isCommMsgMsg = isCommMsgMsg;
    /**
     * Test whether a kernel message is an `'execute_reply'` message.
     */
    function isExecuteReplyMsg(msg) {
        return msg.header.msg_type === 'execute_reply';
    }
    KernelMessage.isExecuteReplyMsg = isExecuteReplyMsg;
    /**
     * Test whether a kernel message is an `'input_request'` message.
     */
    function isInputRequestMsg(msg) {
        return msg.header.msg_type === 'input_request';
    }
    KernelMessage.isInputRequestMsg = isInputRequestMsg;
})(KernelMessage = exports.KernelMessage || (exports.KernelMessage = {}));


/***/ }),

/***/ "WgSP":
/*!********************************************************************!*\
  !*** ./node_modules/@jupyterlab/javascript-extension/lib/index.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const rendermime_1 = __webpack_require__(/*! @jupyterlab/rendermime */ "Towz");
exports.TEXT_JAVASCRIPT_MIMETYPE = 'text/javascript';
exports.APPLICATION_JAVASCRIPT_MIMETYPE = 'application/javascript';
function evalInContext(code, element, document, window) {
    // tslint:disable-next-line
    return eval(code);
}
class ExperimentalRenderedJavascript extends rendermime_1.RenderedJavaScript {
    render(model) {
        const renderJavascript = () => {
            try {
                const data = model.data[this.mimeType];
                evalInContext(data, this.node, document, window);
                // If output is empty after evaluating, render the plain text value
                if (this.node.innerHTML === '') {
                    const text = model.data['text/plain'];
                    const output = document.createElement('pre');
                    output.textContent = text;
                    this.node.appendChild(output);
                }
                return Promise.resolve();
            }
            catch (error) {
                return Promise.reject(error);
            }
        };
        if (!model.trusted) {
            // If output is not trusted or if arbitrary Javascript execution is not enabled, render an informative error message
            this.node.innerHTML = `<pre>Are you sure that you want to run arbitrary Javascript within your JupyterLab session?</pre>
      <button>Run</button>`;
            this.node.querySelector('button').onclick = event => {
                this.node.innerHTML = '';
                renderJavascript();
            };
            return Promise.resolve();
        }
        return renderJavascript();
    }
}
exports.ExperimentalRenderedJavascript = ExperimentalRenderedJavascript;
/**
 * A mime renderer factory for text/javascript data.
 */
exports.rendererFactory = {
    safe: false,
    mimeTypes: [exports.TEXT_JAVASCRIPT_MIMETYPE, exports.APPLICATION_JAVASCRIPT_MIMETYPE],
    createRenderer: options => new ExperimentalRenderedJavascript(options)
};
const extension = {
    id: '@jupyterlab/javascript-extension:factory',
    rendererFactory: exports.rendererFactory,
    rank: 0,
    dataType: 'string'
};
exports.default = extension;


/***/ }),

/***/ "Whu6":
/*!*******************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/push_unique.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



/**
 * Push array with unique items
 *
 * Ignores falsy items, except 0 so we can use it to construct arrays of indices.
 *
 * @param {array} array
 *  array to be filled
 * @param {any} item
 *  item to be or not to be inserted
 * @return {array}
 *  ref to array (now possibly containing one more item)
 *
 */
module.exports = function pushUnique(array, item) {
    if(item instanceof RegExp) {
        var itemStr = item.toString();
        for(var i = 0; i < array.length; i++) {
            if(array[i] instanceof RegExp && array[i].toString() === itemStr) {
                return array;
            }
        }
        array.push(item);
    }
    else if((item || item === 0) && array.indexOf(item) === -1) array.push(item);

    return array;
};


/***/ }),

/***/ "Wkzk":
/*!*********************************************************!*\
  !*** ./node_modules/draft-js/lib/SecondaryClipboard.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule SecondaryClipboard
 * @format
 * 
 */



var DraftModifier = __webpack_require__(/*! ./DraftModifier */ "fyOY");
var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");

var getContentStateFragment = __webpack_require__(/*! ./getContentStateFragment */ "DYKh");
var nullthrows = __webpack_require__(/*! fbjs/lib/nullthrows */ "gWRK");

var clipboard = null;

/**
 * Some systems offer a "secondary" clipboard to allow quick internal cut
 * and paste behavior. For instance, Ctrl+K (cut) and Ctrl+Y (paste).
 */
var SecondaryClipboard = {
  cut: function cut(editorState) {
    var content = editorState.getCurrentContent();
    var selection = editorState.getSelection();
    var targetRange = null;

    if (selection.isCollapsed()) {
      var anchorKey = selection.getAnchorKey();
      var blockEnd = content.getBlockForKey(anchorKey).getLength();

      if (blockEnd === selection.getAnchorOffset()) {
        return editorState;
      }

      targetRange = selection.set('focusOffset', blockEnd);
    } else {
      targetRange = selection;
    }

    targetRange = nullthrows(targetRange);
    clipboard = getContentStateFragment(content, targetRange);

    var afterRemoval = DraftModifier.removeRange(content, targetRange, 'forward');

    if (afterRemoval === content) {
      return editorState;
    }

    return EditorState.push(editorState, afterRemoval, 'remove-range');
  },

  paste: function paste(editorState) {
    if (!clipboard) {
      return editorState;
    }

    var newContent = DraftModifier.replaceWithFragment(editorState.getCurrentContent(), editorState.getSelection(), clipboard);

    return EditorState.push(editorState, newContent, 'insert-fragment');
  }
};

module.exports = SecondaryClipboard;

/***/ }),

/***/ "Wl7T":
/*!*****************************************!*\
  !*** ./node_modules/base16/lib/tube.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'london tube',
  author: 'jan t. sott',
  base00: '#231f20',
  base01: '#1c3f95',
  base02: '#5a5758',
  base03: '#737171',
  base04: '#959ca1',
  base05: '#d9d8d8',
  base06: '#e7e7e8',
  base07: '#ffffff',
  base08: '#ee2e24',
  base09: '#f386a1',
  base0A: '#ffd204',
  base0B: '#00853e',
  base0C: '#85cebc',
  base0D: '#009ddc',
  base0E: '#98005d',
  base0F: '#b06110'
};
module.exports = exports['default'];

/***/ }),

/***/ "WnY+":
/*!*****************************************!*\
  !*** ./node_modules/create-hash/md5.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var MD5 = __webpack_require__(/*! md5.js */ "9XZ3")

module.exports = function (buffer) {
  return new MD5().update(buffer).digest()
}


/***/ }),

/***/ "WwFo":
/*!********************************************!*\
  !*** ./node_modules/lodash/_baseAssign.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var copyObject = __webpack_require__(/*! ./_copyObject */ "juv8"),
    keys = __webpack_require__(/*! ./keys */ "7GkX");

/**
 * 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);
}

module.exports = baseAssign;


/***/ }),

/***/ "WxRl":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/hu.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var weekEndings = 'vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton'.split(' ');
function translate(number, withoutSuffix, key, isFuture) {
    var num = number;
    switch (key) {
        case 's':
            return (isFuture || withoutSuffix) ? 'néhány másodperc' : 'néhány másodperce';
        case 'ss':
            return num + (isFuture || withoutSuffix) ? ' másodperc' : ' másodperce';
        case 'm':
            return 'egy' + (isFuture || withoutSuffix ? ' perc' : ' perce');
        case 'mm':
            return num + (isFuture || withoutSuffix ? ' perc' : ' perce');
        case 'h':
            return 'egy' + (isFuture || withoutSuffix ? ' óra' : ' órája');
        case 'hh':
            return num + (isFuture || withoutSuffix ? ' óra' : ' órája');
        case 'd':
            return 'egy' + (isFuture || withoutSuffix ? ' nap' : ' napja');
        case 'dd':
            return num + (isFuture || withoutSuffix ? ' nap' : ' napja');
        case 'M':
            return 'egy' + (isFuture || withoutSuffix ? ' hónap' : ' hónapja');
        case 'MM':
            return num + (isFuture || withoutSuffix ? ' hónap' : ' hónapja');
        case 'y':
            return 'egy' + (isFuture || withoutSuffix ? ' év' : ' éve');
        case 'yy':
            return num + (isFuture || withoutSuffix ? ' év' : ' éve');
    }
    return '';
}
function week(isFuture) {
    return (isFuture ? '' : '[múlt] ') + '[' + weekEndings[this.day()] + '] LT[-kor]';
}

var hu = moment.defineLocale('hu', {
    months : 'január_február_március_április_május_június_július_augusztus_szeptember_október_november_december'.split('_'),
    monthsShort : 'jan_feb_márc_ápr_máj_jún_júl_aug_szept_okt_nov_dec'.split('_'),
    weekdays : 'vasárnap_hétfő_kedd_szerda_csütörtök_péntek_szombat'.split('_'),
    weekdaysShort : 'vas_hét_kedd_sze_csüt_pén_szo'.split('_'),
    weekdaysMin : 'v_h_k_sze_cs_p_szo'.split('_'),
    longDateFormat : {
        LT : 'H:mm',
        LTS : 'H:mm:ss',
        L : 'YYYY.MM.DD.',
        LL : 'YYYY. MMMM D.',
        LLL : 'YYYY. MMMM D. H:mm',
        LLLL : 'YYYY. MMMM D., dddd H:mm'
    },
    meridiemParse: /de|du/i,
    isPM: function (input) {
        return input.charAt(1).toLowerCase() === 'u';
    },
    meridiem : function (hours, minutes, isLower) {
        if (hours < 12) {
            return isLower === true ? 'de' : 'DE';
        } else {
            return isLower === true ? 'du' : 'DU';
        }
    },
    calendar : {
        sameDay : '[ma] LT[-kor]',
        nextDay : '[holnap] LT[-kor]',
        nextWeek : function () {
            return week.call(this, true);
        },
        lastDay : '[tegnap] LT[-kor]',
        lastWeek : function () {
            return week.call(this, false);
        },
        sameElse : 'L'
    },
    relativeTime : {
        future : '%s múlva',
        past : '%s',
        s : translate,
        ss : translate,
        m : translate,
        mm : translate,
        h : translate,
        hh : translate,
        d : translate,
        dd : translate,
        M : translate,
        MM : translate,
        y : translate,
        yy : translate
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return hu;

})));


/***/ }),

/***/ "X1dy":
/*!******************************************************************!*\
  !*** ./node_modules/@jupyter-widgets/base/lib/backbone-patch.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// This file contains a modified version of the set function from the Backbone
// (see
// https://github.com/jashkenas/backbone/blob/05fde9e201f7e2137796663081105cd6dad12a98/backbone.js#L460,
// with changes below marked with an EDIT comment). This file in Backbone has the following license.
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
//     (c) 2010-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
//     Backbone may be freely distributed under the MIT license.
//     For all details and documentation:
//     http://backbonejs.org
// Backbone's full license is below (from https://github.com/jashkenas/backbone/blob/05fde9e201f7e2137796663081105cd6dad12a98/LICENSE)
/*
Copyright (c) 2010-2015 Jeremy Ashkenas, DocumentCloud

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.
*/
var utils = __webpack_require__(/*! ./utils */ "o9P/");
// 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.
// This *MUST* be called with the model as the `this` context.
function set(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) {
        // EDIT: changed to use object spread instead of _.clone
        this._previousAttributes = __assign({}, 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];
        // EDIT: the following two lines use our isEqual instead of _.isEqual
        if (!utils.isEqual(current[attr], val)) {
            changes.push(attr);
        }
        if (!utils.isEqual(prev[attr], val)) {
            changed[attr] = val;
        }
        else {
            delete changed[attr];
        }
        unset ? delete current[attr] : current[attr] = val;
    }
    // Update the `id`.
    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;
}
exports.set = set;


/***/ }),

/***/ "X4Z0":
/*!************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@phosphor/widgets/style/menubar.css ***!
  \************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\r\n| Copyright (c) 2014-2017, PhosphorJS Contributors\r\n|\r\n| Distributed under the terms of the BSD 3-Clause License.\r\n|\r\n| The full license is in the file LICENSE, distributed with this software.\r\n|----------------------------------------------------------------------------*/\r\n\r\n\r\n.p-MenuBar {\r\n  outline: none;\r\n  -webkit-user-select: none;\r\n  -moz-user-select: none;\r\n  -ms-user-select: none;\r\n  user-select: none;\r\n}\r\n\r\n\r\n.p-MenuBar-content {\r\n  margin: 0;\r\n  padding: 0;\r\n  display: flex;\r\n  flex-direction: row;\r\n  list-style-type: none;\r\n}\r\n\r\n\r\n.p-MenuBar-item {\r\n  box-sizing: border-box;\r\n}\r\n\r\n\r\n.p-MenuBar-itemIcon,\r\n.p-MenuBar-itemLabel {\r\n  display: inline-block;\r\n}\r\n", ""]);

// exports


/***/ }),

/***/ "X709":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/sv.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var sv = moment.defineLocale('sv', {
    months : 'januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december'.split('_'),
    monthsShort : 'jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec'.split('_'),
    weekdays : 'söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag'.split('_'),
    weekdaysShort : 'sön_mån_tis_ons_tor_fre_lör'.split('_'),
    weekdaysMin : 'sö_må_ti_on_to_fr_lö'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'YYYY-MM-DD',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY [kl.] HH:mm',
        LLLL : 'dddd D MMMM YYYY [kl.] HH:mm',
        lll : 'D MMM YYYY HH:mm',
        llll : 'ddd D MMM YYYY HH:mm'
    },
    calendar : {
        sameDay: '[Idag] LT',
        nextDay: '[Imorgon] LT',
        lastDay: '[Igår] LT',
        nextWeek: '[På] dddd LT',
        lastWeek: '[I] dddd[s] LT',
        sameElse: 'L'
    },
    relativeTime : {
        future : 'om %s',
        past : 'för %s sedan',
        s : 'några sekunder',
        ss : '%d sekunder',
        m : 'en minut',
        mm : '%d minuter',
        h : 'en timme',
        hh : '%d timmar',
        d : 'en dag',
        dd : '%d dagar',
        M : 'en månad',
        MM : '%d månader',
        y : 'ett år',
        yy : '%d år'
    },
    dayOfMonthOrdinalParse: /\d{1,2}(e|a)/,
    ordinal : function (number) {
        var b = number % 10,
            output = (~~(number % 100 / 10) === 1) ? 'e' :
            (b === 1) ? 'a' :
            (b === 2) ? 'a' :
            (b === 3) ? 'e' : 'e';
        return number + output;
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return sv;

})));


/***/ }),

/***/ "X834":
/*!************************************************************!*\
  !*** ./node_modules/react-json-tree/lib/JSONNestedNode.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _keys = __webpack_require__(/*! babel-runtime/core-js/object/keys */ "GQeE");

var _keys2 = _interopRequireDefault(_keys);

var _classCallCheck2 = __webpack_require__(/*! babel-runtime/helpers/classCallCheck */ "iCc5");

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _possibleConstructorReturn2 = __webpack_require__(/*! babel-runtime/helpers/possibleConstructorReturn */ "FYw3");

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __webpack_require__(/*! babel-runtime/helpers/inherits */ "mRg0");

var _inherits3 = _interopRequireDefault(_inherits2);

var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "QbLZ");

var _extends3 = _interopRequireDefault(_extends2);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _JSONArrow = __webpack_require__(/*! ./JSONArrow */ "ktrZ");

var _JSONArrow2 = _interopRequireDefault(_JSONArrow);

var _getCollectionEntries = __webpack_require__(/*! ./getCollectionEntries */ "pnsq");

var _getCollectionEntries2 = _interopRequireDefault(_getCollectionEntries);

var _JSONNode = __webpack_require__(/*! ./JSONNode */ "rTFf");

var _JSONNode2 = _interopRequireDefault(_JSONNode);

var _ItemRange = __webpack_require__(/*! ./ItemRange */ "kCS6");

var _ItemRange2 = _interopRequireDefault(_ItemRange);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

/**
 * Renders nested values (eg. objects, arrays, lists, etc.)
 */

function renderChildNodes(props, from, to) {
  var nodeType = props.nodeType,
      data = props.data,
      collectionLimit = props.collectionLimit,
      circularCache = props.circularCache,
      keyPath = props.keyPath,
      postprocessValue = props.postprocessValue,
      sortObjectKeys = props.sortObjectKeys;

  var childNodes = [];

  (0, _getCollectionEntries2['default'])(nodeType, data, sortObjectKeys, collectionLimit, from, to).forEach(function (entry) {
    if (entry.to) {
      childNodes.push(_react2['default'].createElement(_ItemRange2['default'], (0, _extends3['default'])({}, props, {
        key: 'ItemRange--' + entry.from + '-' + entry.to,
        from: entry.from,
        to: entry.to,
        renderChildNodes: renderChildNodes
      })));
    } else {
      var key = entry.key,
          value = entry.value;

      var isCircular = circularCache.indexOf(value) !== -1;

      var node = _react2['default'].createElement(_JSONNode2['default'], (0, _extends3['default'])({}, props, { postprocessValue: postprocessValue, collectionLimit: collectionLimit }, {
        key: 'Node--' + key,
        keyPath: [key].concat(keyPath),
        value: postprocessValue(value),
        circularCache: [].concat(circularCache, [value]),
        isCircular: isCircular,
        hideRoot: false
      }));

      if (node !== false) {
        childNodes.push(node);
      }
    }
  });

  return childNodes;
}

function getStateFromProps(props) {
  // calculate individual node expansion if necessary
  var expanded = props.shouldExpandNode && !props.isCircular ? props.shouldExpandNode(props.keyPath, props.data, props.level) : false;
  return {
    expanded: expanded
  };
}

var JSONNestedNode = function (_React$Component) {
  (0, _inherits3['default'])(JSONNestedNode, _React$Component);

  function JSONNestedNode(props) {
    (0, _classCallCheck3['default'])(this, JSONNestedNode);

    var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props));

    _this.handleClick = function () {
      if (_this.props.expandable) {
        _this.setState({ expanded: !_this.state.expanded });
      }
    };

    _this.state = getStateFromProps(props);
    return _this;
  }

  JSONNestedNode.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
    var nextState = getStateFromProps(nextProps);
    if (getStateFromProps(this.props).expanded !== nextState.expanded) {
      this.setState(nextState);
    }
  };

  JSONNestedNode.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) {
    var _this2 = this;

    return !!(0, _keys2['default'])(nextProps).find(function (key) {
      return key !== 'circularCache' && (key === 'keyPath' ? nextProps[key].join('/') !== _this2.props[key].join('/') : nextProps[key] !== _this2.props[key]);
    }) || nextState.expanded !== this.state.expanded;
  };

  JSONNestedNode.prototype.render = function render() {
    var _props = this.props,
        getItemString = _props.getItemString,
        nodeTypeIndicator = _props.nodeTypeIndicator,
        nodeType = _props.nodeType,
        data = _props.data,
        hideRoot = _props.hideRoot,
        createItemString = _props.createItemString,
        styling = _props.styling,
        collectionLimit = _props.collectionLimit,
        keyPath = _props.keyPath,
        labelRenderer = _props.labelRenderer,
        expandable = _props.expandable;
    var expanded = this.state.expanded;

    var renderedChildren = expanded || hideRoot && this.props.level === 0 ? renderChildNodes((0, _extends3['default'])({}, this.props, { level: this.props.level + 1 })) : null;

    var itemType = _react2['default'].createElement(
      'span',
      styling('nestedNodeItemType', expanded),
      nodeTypeIndicator
    );
    var renderedItemString = getItemString(nodeType, data, itemType, createItemString(data, collectionLimit));
    var stylingArgs = [keyPath, nodeType, expanded, expandable];

    return hideRoot ? _react2['default'].createElement(
      'li',
      styling.apply(undefined, ['rootNode'].concat(stylingArgs)),
      _react2['default'].createElement(
        'ul',
        styling.apply(undefined, ['rootNodeChildren'].concat(stylingArgs)),
        renderedChildren
      )
    ) : _react2['default'].createElement(
      'li',
      styling.apply(undefined, ['nestedNode'].concat(stylingArgs)),
      expandable && _react2['default'].createElement(_JSONArrow2['default'], {
        styling: styling,
        nodeType: nodeType,
        expanded: expanded,
        onClick: this.handleClick
      }),
      _react2['default'].createElement(
        'label',
        (0, _extends3['default'])({}, styling.apply(undefined, [['label', 'nestedNodeLabel']].concat(stylingArgs)), {
          onClick: this.handleClick
        }),
        labelRenderer.apply(undefined, stylingArgs)
      ),
      _react2['default'].createElement(
        'span',
        (0, _extends3['default'])({}, styling.apply(undefined, ['nestedNodeItemString'].concat(stylingArgs)), {
          onClick: this.handleClick
        }),
        renderedItemString
      ),
      _react2['default'].createElement(
        'ul',
        styling.apply(undefined, ['nestedNodeChildren'].concat(stylingArgs)),
        renderedChildren
      )
    );
  };

  return JSONNestedNode;
}(_react2['default'].Component);

JSONNestedNode.propTypes = {
  getItemString: _propTypes2['default'].func.isRequired,
  nodeTypeIndicator: _propTypes2['default'].any,
  nodeType: _propTypes2['default'].string.isRequired,
  data: _propTypes2['default'].any,
  hideRoot: _propTypes2['default'].bool.isRequired,
  createItemString: _propTypes2['default'].func.isRequired,
  styling: _propTypes2['default'].func.isRequired,
  collectionLimit: _propTypes2['default'].number,
  keyPath: _propTypes2['default'].arrayOf(_propTypes2['default'].oneOfType([_propTypes2['default'].string, _propTypes2['default'].number])).isRequired,
  labelRenderer: _propTypes2['default'].func.isRequired,
  shouldExpandNode: _propTypes2['default'].func,
  level: _propTypes2['default'].number.isRequired,
  sortObjectKeys: _propTypes2['default'].oneOfType([_propTypes2['default'].func, _propTypes2['default'].bool]),
  isCircular: _propTypes2['default'].bool,
  expandable: _propTypes2['default'].bool
};
JSONNestedNode.defaultProps = {
  data: [],
  circularCache: [],
  level: 0,
  expandable: true
};
exports['default'] = JSONNestedNode;

/***/ }),

/***/ "XATK":
/*!******************************************************!*\
  !*** ./node_modules/draft-js-utils/lib/Constants.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var BLOCK_TYPE = exports.BLOCK_TYPE = {
  // This is used to represent a normal text block (paragraph).
  UNSTYLED: 'unstyled',
  HEADER_ONE: 'header-one',
  HEADER_TWO: 'header-two',
  HEADER_THREE: 'header-three',
  HEADER_FOUR: 'header-four',
  HEADER_FIVE: 'header-five',
  HEADER_SIX: 'header-six',
  UNORDERED_LIST_ITEM: 'unordered-list-item',
  ORDERED_LIST_ITEM: 'ordered-list-item',
  BLOCKQUOTE: 'blockquote',
  PULLQUOTE: 'pullquote',
  CODE: 'code-block',
  ATOMIC: 'atomic'
};

var ENTITY_TYPE = exports.ENTITY_TYPE = {
  LINK: 'LINK',
  IMAGE: 'IMAGE'
};

var INLINE_STYLE = exports.INLINE_STYLE = {
  BOLD: 'BOLD',
  CODE: 'CODE',
  ITALIC: 'ITALIC',
  STRIKETHROUGH: 'STRIKETHROUGH',
  UNDERLINE: 'UNDERLINE'
};

exports.default = {
  BLOCK_TYPE: BLOCK_TYPE,
  ENTITY_TYPE: ENTITY_TYPE,
  INLINE_STYLE: INLINE_STYLE
};

/***/ }),

/***/ "XAgW":
/*!************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/connectLayoutToPlot.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

exports.default = connectLayoutToPlot;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _nested_property = __webpack_require__(/*! plotly.js/src/lib/nested_property */ "dNZO");

var _nested_property2 = _interopRequireDefault(_nested_property);

var _lib = __webpack_require__(/*! ../lib */ "RXjw");

var _constants = __webpack_require__(/*! ./constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function connectLayoutToPlot(WrappedComponent) {
  var LayoutConnectedComponent = function (_Component) {
    _inherits(LayoutConnectedComponent, _Component);

    function LayoutConnectedComponent() {
      _classCallCheck(this, LayoutConnectedComponent);

      return _possibleConstructorReturn(this, (LayoutConnectedComponent.__proto__ || Object.getPrototypeOf(LayoutConnectedComponent)).apply(this, arguments));
    }

    _createClass(LayoutConnectedComponent, [{
      key: 'getChildContext',
      value: function getChildContext() {
        var _context = this.context,
            layout = _context.layout,
            fullLayout = _context.fullLayout,
            plotly = _context.plotly,
            onUpdate = _context.onUpdate;


        var updateContainer = function updateContainer(update) {
          if (!onUpdate) {
            return;
          }
          onUpdate({
            type: _constants.EDITOR_ACTIONS.UPDATE_LAYOUT,
            payload: {
              update: update
            }
          });
        };

        return {
          getValObject: function getValObject(attr) {
            return !plotly ? null : plotly.PlotSchema.getLayoutValObject(fullLayout, (0, _nested_property2.default)({}, attr).parts);
          },
          updateContainer: updateContainer,
          container: layout,
          fullContainer: fullLayout
        };
      }
    }, {
      key: 'render',
      value: function render() {
        return _react2.default.createElement(WrappedComponent, this.props);
      }
    }]);

    return LayoutConnectedComponent;
  }(_react.Component);

  LayoutConnectedComponent.displayName = 'LayoutConnected' + (0, _lib.getDisplayName)(WrappedComponent);

  LayoutConnectedComponent.contextTypes = {
    layout: _propTypes2.default.object,
    fullLayout: _propTypes2.default.object,
    plotly: _propTypes2.default.object,
    onUpdate: _propTypes2.default.func
  };

  LayoutConnectedComponent.childContextTypes = {
    getValObject: _propTypes2.default.func,
    updateContainer: _propTypes2.default.func,
    container: _propTypes2.default.object,
    fullContainer: _propTypes2.default.object
  };

  var plotly_editor_traits = WrappedComponent.plotly_editor_traits;

  LayoutConnectedComponent.plotly_editor_traits = plotly_editor_traits;

  return LayoutConnectedComponent;
}
//# sourceMappingURL=connectLayoutToPlot.js.map

/***/ }),

/***/ "XCWL":
/*!*********************************************************!*\
  !*** ./node_modules/plotlylab-light-theme/lib/index.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
/**
 * A plugin for the PlotlyLab Light
 */
const plugin = {
    id: 'plotlylab-light-theme:plugin',
    requires: [apputils_1.IThemeManager],
    activate: function (app, manager) {
        const style = 'plotlylab-light-theme/index.css';
        manager.register({
            name: 'PlotlyLab Light',
            isLight: true,
            load: function () {
                return manager.loadCSS(style);
            },
            unload: function () {
                return Promise.resolve(void 0);
            }
        });
    },
    autoStart: true
};
exports.default = plugin;


/***/ }),

/***/ "XDpg":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/zh-cn.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var zhCn = moment.defineLocale('zh-cn', {
    months : '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
    monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
    weekdays : '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
    weekdaysShort : '周日_周一_周二_周三_周四_周五_周六'.split('_'),
    weekdaysMin : '日_一_二_三_四_五_六'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'YYYY/MM/DD',
        LL : 'YYYY年M月D日',
        LLL : 'YYYY年M月D日Ah点mm分',
        LLLL : 'YYYY年M月D日ddddAh点mm分',
        l : 'YYYY/M/D',
        ll : 'YYYY年M月D日',
        lll : 'YYYY年M月D日 HH:mm',
        llll : 'YYYY年M月D日dddd HH:mm'
    },
    meridiemParse: /凌晨|早上|上午|中午|下午|晚上/,
    meridiemHour: function (hour, meridiem) {
        if (hour === 12) {
            hour = 0;
        }
        if (meridiem === '凌晨' || meridiem === '早上' ||
                meridiem === '上午') {
            return hour;
        } else if (meridiem === '下午' || meridiem === '晚上') {
            return hour + 12;
        } else {
            // '中午'
            return hour >= 11 ? hour : hour + 12;
        }
    },
    meridiem : function (hour, minute, isLower) {
        var hm = hour * 100 + minute;
        if (hm < 600) {
            return '凌晨';
        } else if (hm < 900) {
            return '早上';
        } else if (hm < 1130) {
            return '上午';
        } else if (hm < 1230) {
            return '中午';
        } else if (hm < 1800) {
            return '下午';
        } else {
            return '晚上';
        }
    },
    calendar : {
        sameDay : '[今天]LT',
        nextDay : '[明天]LT',
        nextWeek : '[下]ddddLT',
        lastDay : '[昨天]LT',
        lastWeek : '[上]ddddLT',
        sameElse : 'L'
    },
    dayOfMonthOrdinalParse: /\d{1,2}(日|月|周)/,
    ordinal : function (number, period) {
        switch (period) {
            case 'd':
            case 'D':
            case 'DDD':
                return number + '日';
            case 'M':
                return number + '月';
            case 'w':
            case 'W':
                return number + '周';
            default:
                return number;
        }
    },
    relativeTime : {
        future : '%s内',
        past : '%s前',
        s : '几秒',
        ss : '%d 秒',
        m : '1 分钟',
        mm : '%d 分钟',
        h : '1 小时',
        hh : '%d 小时',
        d : '1 天',
        dd : '%d 天',
        M : '1 个月',
        MM : '%d 个月',
        y : '1 年',
        yy : '%d 年'
    },
    week : {
        // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return zhCn;

})));


/***/ }),

/***/ "XFcd":
/*!**************************************************************!*\
  !*** ./node_modules/@jupyter-widgets/base/lib/nativeview.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
/*
 This file contains substantial portions of https://github.com/akre54/Backbone.NativeView/blob/521188d9554b53d95d70ed34f878d8ac9fc10df2/backbone.nativeview.js, which has the following license:

(c) 2015 Adam Krebs, Jimmy Yuen Ho Wong
Backbone.NativeView may be freely distributed under the MIT license.

Copyright (c) 2014 Adam Krebs

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.

*/
var Backbone = __webpack_require__(/*! backbone */ "q1z7");
// Caches a local reference to `Element.prototype` for faster access.
var ElementProto = Element.prototype; // : typeof Element = (typeof Element !== 'undefined' && Element.prototype) || {};
// Find the right `Element#matches` for IE>=9 and modern browsers.
var matchesSelector = ElementProto.matches ||
    ElementProto['webkitMatchesSelector'] ||
    ElementProto['mozMatchesSelector'] ||
    ElementProto['msMatchesSelector'] ||
    ElementProto['oMatchesSelector'] ||
    function matches(selector) {
        var matches = (this.document || this.ownerDocument).querySelectorAll(selector);
        var i = matches.length;
        while (--i >= 0 && matches.item(i) !== this) {
            continue;
        }
        return i > -1;
    };
var NativeView = /** @class */ (function (_super) {
    __extends(NativeView, _super);
    function NativeView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    NativeView.prototype._removeElement = function () {
        this.undelegateEvents();
        if (this.el.parentNode) {
            this.el.parentNode.removeChild(this.el);
        }
    };
    // Apply the `element` to the view.
    NativeView.prototype._setElement = function (element) {
        this.el = element;
    };
    // Set a hash of attributes to the view's `el`. We use the "prop" version
    // if available, falling back to `setAttribute` for the catch-all.
    NativeView.prototype._setAttributes = function (attrs) {
        for (var attr in attrs) {
            attr in this.el ? this.el[attr] = attrs[attr] : this.el.setAttribute(attr, attrs[attr]);
        }
    };
    /**
     * Make an event delegation handler for the given `eventName` and `selector`
     * and attach it to `this.el`.
     * If selector is empty, the listener will be bound to `this.el`. If not, a
     * new handler that will recursively traverse up the event target's DOM
     * hierarchy looking for a node that matches the selector. If one is found,
     * the event's `delegateTarget` property is set to it and the return the
     * result of calling bound `listener` with the parameters given to the
     * handler.
     *
     * This does not properly handle selectors for things like focus and blur (see
     * https://github.com/jquery/jquery/blob/7d21f02b9ec9f655583e898350badf89165ed4d5/src/event.js#L442
     * for some similar exceptional cases).
     */
    NativeView.prototype.delegate = function (eventName, selector, listener) {
        if (typeof selector !== 'string') {
            listener = selector;
            selector = null;
        }
        // We have to initialize this here, instead of in the constructor, because the
        // super constructor eventually calls this method before we get a chance to initialize
        // this._domEvents to an empty list.
        if (this._domEvents === void 0) {
            this._domEvents = [];
        }
        var root = this.el;
        var handler = selector ? function (e) {
            var node = e.target || e.srcElement;
            for (; node && node !== root; node = node.parentNode) {
                if (matchesSelector.call(node, selector)) {
                    e.delegateTarget = node;
                    if (listener.handleEvent) {
                        return listener.handleEvent(e);
                    }
                    else {
                        return listener(e);
                    }
                }
            }
        } : listener;
        this.el.addEventListener(eventName, handler, false);
        this._domEvents.push({ eventName: eventName, handler: handler, listener: listener, selector: selector });
        return handler;
    };
    // Remove a single delegated event. Either `eventName` or `selector` must
    // be included, `selector` and `listener` are optional.
    NativeView.prototype.undelegate = function (eventName, selector, listener) {
        if (typeof selector === 'function') {
            listener = selector;
            selector = null;
        }
        if (this.el && this._domEvents) {
            var handlers = this._domEvents.slice();
            var i = handlers.length;
            while (i--) {
                var item = handlers[i];
                var match = item.eventName === eventName &&
                    (listener ? item.listener === listener : true) &&
                    (selector ? item.selector === selector : true);
                if (!match) {
                    continue;
                }
                this.el.removeEventListener(item.eventName, item.handler, false);
                this._domEvents.splice(i, 1);
            }
        }
        return this;
    };
    // Remove all events created with `delegate` from `el`
    NativeView.prototype.undelegateEvents = function () {
        if (this.el && this._domEvents) {
            var len = this._domEvents.length;
            for (var i = 0; i < len; i++) {
                var item = this._domEvents[i];
                this.el.removeEventListener(item.eventName, item.handler, false);
            }
            this._domEvents.length = 0;
        }
        return this;
    };
    return NativeView;
}(Backbone.View));
exports.NativeView = NativeView;


/***/ }),

/***/ "XLvN":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/te.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var te = moment.defineLocale('te', {
    months : 'జనవరి_ఫిబ్రవరి_మార్చి_ఏప్రిల్_మే_జూన్_జూలై_ఆగస్టు_సెప్టెంబర్_అక్టోబర్_నవంబర్_డిసెంబర్'.split('_'),
    monthsShort : 'జన._ఫిబ్ర._మార్చి_ఏప్రి._మే_జూన్_జూలై_ఆగ._సెప్._అక్టో._నవ._డిసె.'.split('_'),
    monthsParseExact : true,
    weekdays : 'ఆదివారం_సోమవారం_మంగళవారం_బుధవారం_గురువారం_శుక్రవారం_శనివారం'.split('_'),
    weekdaysShort : 'ఆది_సోమ_మంగళ_బుధ_గురు_శుక్ర_శని'.split('_'),
    weekdaysMin : 'ఆ_సో_మం_బు_గు_శు_శ'.split('_'),
    longDateFormat : {
        LT : 'A h:mm',
        LTS : 'A h:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY, A h:mm',
        LLLL : 'dddd, D MMMM YYYY, A h:mm'
    },
    calendar : {
        sameDay : '[నేడు] LT',
        nextDay : '[రేపు] LT',
        nextWeek : 'dddd, LT',
        lastDay : '[నిన్న] LT',
        lastWeek : '[గత] dddd, LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : '%s లో',
        past : '%s క్రితం',
        s : 'కొన్ని క్షణాలు',
        ss : '%d సెకన్లు',
        m : 'ఒక నిమిషం',
        mm : '%d నిమిషాలు',
        h : 'ఒక గంట',
        hh : '%d గంటలు',
        d : 'ఒక రోజు',
        dd : '%d రోజులు',
        M : 'ఒక నెల',
        MM : '%d నెలలు',
        y : 'ఒక సంవత్సరం',
        yy : '%d సంవత్సరాలు'
    },
    dayOfMonthOrdinalParse : /\d{1,2}వ/,
    ordinal : '%dవ',
    meridiemParse: /రాత్రి|ఉదయం|మధ్యాహ్నం|సాయంత్రం/,
    meridiemHour : function (hour, meridiem) {
        if (hour === 12) {
            hour = 0;
        }
        if (meridiem === 'రాత్రి') {
            return hour < 4 ? hour : hour + 12;
        } else if (meridiem === 'ఉదయం') {
            return hour;
        } else if (meridiem === 'మధ్యాహ్నం') {
            return hour >= 10 ? hour : hour + 12;
        } else if (meridiem === 'సాయంత్రం') {
            return hour + 12;
        }
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 4) {
            return 'రాత్రి';
        } else if (hour < 10) {
            return 'ఉదయం';
        } else if (hour < 17) {
            return 'మధ్యాహ్నం';
        } else if (hour < 20) {
            return 'సాయంత్రం';
        } else {
            return 'రాత్రి';
        }
    },
    week : {
        dow : 0, // Sunday is the first day of the week.
        doy : 6  // The week that contains Jan 1st is the first week of the year.
    }
});

return te;

})));


/***/ }),

/***/ "XPXQ":
/*!************************************************!*\
  !*** ./node_modules/ajv/lib/dotjs/contains.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_contains(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $idx = 'i' + $lvl,
    $dataNxt = $it.dataLevel = it.dataLevel + 1,
    $nextData = 'data' + $dataNxt,
    $currentBaseId = it.baseId,
    $nonEmptySchema = it.util.schemaHasRules($schema, it.RULES.all);
  out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
  if ($nonEmptySchema) {
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
    $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
    var $passData = $data + '[' + $idx + ']';
    $it.dataPathArr[$dataNxt] = $idx;
    var $code = it.validate($it);
    $it.baseId = $currentBaseId;
    if (it.util.varOccurences($code, $nextData) < 2) {
      out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
    } else {
      out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
    }
    out += ' if (' + ($nextValid) + ') break; }  ';
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {';
  } else {
    out += ' if (' + ($data) + '.length == 0) {';
  }
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should contain a valid item\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += ' } else { ';
  if ($nonEmptySchema) {
    out += '  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
  }
  if (it.opts.allErrors) {
    out += ' } ';
  }
  out = it.util.cleanUpCode(out);
  return out;
}


/***/ }),

/***/ "XQvf":
/*!********************************************************!*\
  !*** ./node_modules/reactcss/lib/components/active.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.active = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var active = exports.active = function active(Component) {
  var Span = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'span';

  return function (_React$Component) {
    _inherits(Active, _React$Component);

    function Active() {
      var _ref;

      var _temp, _this, _ret;

      _classCallCheck(this, Active);

      for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Active.__proto__ || Object.getPrototypeOf(Active)).call.apply(_ref, [this].concat(args))), _this), _this.state = { active: false }, _this.handleMouseDown = function () {
        return _this.setState({ active: true });
      }, _this.handleMouseUp = function () {
        return _this.setState({ active: false });
      }, _this.render = function () {
        return _react2.default.createElement(
          Span,
          { onMouseDown: _this.handleMouseDown, onMouseUp: _this.handleMouseUp },
          _react2.default.createElement(Component, _extends({}, _this.props, _this.state))
        );
      }, _temp), _possibleConstructorReturn(_this, _ret);
    }

    return Active;
  }(_react2.default.Component);
};

exports.default = active;

/***/ }),

/***/ "XW4k":
/*!*********************************************!*\
  !*** ./node_modules/base16/lib/twilight.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'twilight',
  author: 'david hart (http://hart-dev.com)',
  base00: '#1e1e1e',
  base01: '#323537',
  base02: '#464b50',
  base03: '#5f5a60',
  base04: '#838184',
  base05: '#a7a7a7',
  base06: '#c3c3c3',
  base07: '#ffffff',
  base08: '#cf6a4c',
  base09: '#cda869',
  base0A: '#f9ee98',
  base0B: '#8f9d6a',
  base0C: '#afc4db',
  base0D: '#7587a6',
  base0E: '#9b859d',
  base0F: '#9b703f'
};
module.exports = exports['default'];

/***/ }),

/***/ "XWTc":
/*!******************************************************!*\
  !*** ./node_modules/@phosphor/domutils/lib/index.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
__export(__webpack_require__(/*! ./element */ "/Dvf"));
__export(__webpack_require__(/*! ./platform */ "jxix"));
__export(__webpack_require__(/*! ./selector */ "BbDm"));


/***/ }),

/***/ "XXoZ":
/*!*****************************************************************!*\
  !*** ./node_modules/@jupyterlab/coreutils/lib/dataconnector.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * An abstract class that adheres to the data connector interface.
 *
 * #### Notes
 * The only abstract method in this class is the `fetch` method, which must be
 * reimplemented by all subclasses. The `remove` and `save` methods have a
 * default implementation that returns a promise that will always reject. This
 * class is a convenience superclass for connectors that only need to `fetch`.
 */
class DataConnector {
    /**
     * Remove a value using the data connector.
     *
     * @param id - The identifier for the data being removed.
     *
     * @returns A promise that is rejected if remove fails and succeeds otherwise.
     *
     * #### Notes
     * This method will always reject; subclasses should reimplement it if they
     * support a back-end that can remove resources.
     */
    remove(id) {
        return Promise.reject(new Error('Removing has not been implemented.'));
    }
    /**
     * Save a value using the data connector.
     *
     * @param id - The identifier for the data being saved.
     *
     * @param value - The data being saved.
     *
     * @returns A promise that is rejected if saving fails and succeeds otherwise.
     *
     * #### Notes
     * This method will always reject; subclasses should reimplement it if they
     * support a back-end that can save resources.
     */
    save(id, value) {
        return Promise.reject(new Error('Saving has not been implemented.'));
    }
}
exports.DataConnector = DataConnector;


/***/ }),

/***/ "XXzh":
/*!*******************************************************!*\
  !*** ./node_modules/mdi-react/ReorderVerticalIcon.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var ReorderVerticalIcon = function ReorderVerticalIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M9,3V21H11V3H9M5,3V21H7V3H5M13,3V21H15V3H13M19,3H17V21H19V3Z' })
  );
};

module.exports = ReorderVerticalIcon;


/***/ }),

/***/ "XYdm":
/*!***************************************************!*\
  !*** ./node_modules/xterm/lib/EscapeSequences.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var C0;
(function (C0) {
    C0.NUL = '\x00';
    C0.SOH = '\x01';
    C0.STX = '\x02';
    C0.ETX = '\x03';
    C0.EOT = '\x04';
    C0.ENQ = '\x05';
    C0.ACK = '\x06';
    C0.BEL = '\x07';
    C0.BS = '\x08';
    C0.HT = '\x09';
    C0.LF = '\x0a';
    C0.VT = '\x0b';
    C0.FF = '\x0c';
    C0.CR = '\x0d';
    C0.SO = '\x0e';
    C0.SI = '\x0f';
    C0.DLE = '\x10';
    C0.DC1 = '\x11';
    C0.DC2 = '\x12';
    C0.DC3 = '\x13';
    C0.DC4 = '\x14';
    C0.NAK = '\x15';
    C0.SYN = '\x16';
    C0.ETB = '\x17';
    C0.CAN = '\x18';
    C0.EM = '\x19';
    C0.SUB = '\x1a';
    C0.ESC = '\x1b';
    C0.FS = '\x1c';
    C0.GS = '\x1d';
    C0.RS = '\x1e';
    C0.US = '\x1f';
    C0.SP = '\x20';
    C0.DEL = '\x7f';
})(C0 = exports.C0 || (exports.C0 = {}));

//# sourceMappingURL=EscapeSequences.js.map


/***/ }),

/***/ "XYm9":
/*!***********************************************!*\
  !*** ./node_modules/lodash/_cloneDataView.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var cloneArrayBuffer = __webpack_require__(/*! ./_cloneArrayBuffer */ "+K+b");

/**
 * 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);
}

module.exports = cloneDataView;


/***/ }),

/***/ "XYy6":
/*!***************************************************!*\
  !*** ./node_modules/mdi-react/TooltipTextIcon.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var TooltipTextIcon = function TooltipTextIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M4,2H20C21.1,2 22,2.9 22,4V16C22,17.1 21.1,18 20,18H16L12,22L8,18H4C2.9,18 2,17.1 2,16V4C2,2.9 2.9,2 4,2M5,5V7H19V5H5M5,9V11H15V9H5M5,13V15H17V13H5Z' })
  );
};

module.exports = TooltipTextIcon;


/***/ }),

/***/ "XdQh":
/*!***********************************************!*\
  !*** ./node_modules/mdi-react/TwitterIcon.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var TwitterIcon = function TwitterIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M22.46,6C21.69,6.35 20.86,6.58 20,6.69C20.88,6.16 21.56,5.32 21.88,4.31C21.05,4.81 20.13,5.16 19.16,5.36C18.37,4.5 17.26,4 16,4C13.65,4 11.73,5.92 11.73,8.29C11.73,8.63 11.77,8.96 11.84,9.27C8.28,9.09 5.11,7.38 3,4.79C2.63,5.42 2.42,6.16 2.42,6.94C2.42,8.43 3.17,9.75 4.33,10.5C3.62,10.5 2.96,10.3 2.38,10C2.38,10 2.38,10 2.38,10.03C2.38,12.11 3.86,13.85 5.82,14.24C5.46,14.34 5.08,14.39 4.69,14.39C4.42,14.39 4.15,14.36 3.89,14.31C4.43,16 6,17.26 7.89,17.29C6.43,18.45 4.58,19.13 2.56,19.13C2.22,19.13 1.88,19.11 1.54,19.07C3.44,20.29 5.7,21 8.12,21C16,21 20.33,14.46 20.33,8.79C20.33,8.6 20.33,8.42 20.32,8.23C21.16,7.63 21.88,6.87 22.46,6Z' })
  );
};

module.exports = TwitterIcon;


/***/ }),

/***/ "Xe/Q":
/*!***********************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/keyed_container.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var nestedProperty = __webpack_require__(/*! ./nested_property */ "dNZO");

var SIMPLE_PROPERTY_REGEX = /^\w*$/;

// bitmask for deciding what's updated. Sometimes the name needs to be updated,
// sometimes the value needs to be updated, and sometimes both do. This is just
// a simple way to track what's updated such that it's a simple OR operation to
// assimilate new updates.
//
// The only exception is the UNSET bit that tracks when we need to explicitly
// unset and remove the property. This concrn arises because of the special
// way in which nestedProperty handles null/undefined. When you specify `null`,
// it prunes any unused items in the tree. I ran into some issues with it getting
// null vs undefined confused, so UNSET is just a bit that forces the property
// update to send `null`, removing the property explicitly rather than setting
// it to undefined.
var NONE = 0;
var NAME = 1;
var VALUE = 2;
var BOTH = 3;
var UNSET = 4;

module.exports = function keyedContainer(baseObj, path, keyName, valueName) {
    keyName = keyName || 'name';
    valueName = valueName || 'value';
    var i, arr, baseProp;
    var changeTypes = {};

    if(path && path.length) {
        baseProp = nestedProperty(baseObj, path);
        arr = baseProp.get();
    } else {
        arr = baseObj;
    }

    path = path || '';

    // Construct an index:
    var indexLookup = {};
    if(arr) {
        for(i = 0; i < arr.length; i++) {
            indexLookup[arr[i][keyName]] = i;
        }
    }

    var isSimpleValueProp = SIMPLE_PROPERTY_REGEX.test(valueName);

    var obj = {
        set: function(name, value) {
            var changeType = value === null ? UNSET : NONE;

            // create the base array if necessary
            if(!arr) {
                if(!baseProp || changeType === UNSET) return;

                arr = [];
                baseProp.set(arr);
            }

            var idx = indexLookup[name];
            if(idx === undefined) {
                if(changeType === UNSET) return;

                changeType = changeType | BOTH;
                idx = arr.length;
                indexLookup[name] = idx;
            } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : nestedProperty(arr[idx], valueName).get())) {
                changeType = changeType | VALUE;
            }

            var newValue = arr[idx] = arr[idx] || {};
            newValue[keyName] = name;

            if(isSimpleValueProp) {
                newValue[valueName] = value;
            } else {
                nestedProperty(newValue, valueName).set(value);
            }

            // If it's not an unset, force that bit to be unset. This is all related to the fact
            // that undefined and null are a bit specially implemented in nestedProperties.
            if(value !== null) {
                changeType = changeType & ~UNSET;
            }

            changeTypes[idx] = changeTypes[idx] | changeType;

            return obj;
        },
        get: function(name) {
            if(!arr) return;

            var idx = indexLookup[name];

            if(idx === undefined) {
                return undefined;
            } else if(isSimpleValueProp) {
                return arr[idx][valueName];
            } else {
                return nestedProperty(arr[idx], valueName).get();
            }
        },
        rename: function(name, newName) {
            var idx = indexLookup[name];

            if(idx === undefined) return obj;
            changeTypes[idx] = changeTypes[idx] | NAME;

            indexLookup[newName] = idx;
            delete indexLookup[name];

            arr[idx][keyName] = newName;

            return obj;
        },
        remove: function(name) {
            var idx = indexLookup[name];

            if(idx === undefined) return obj;

            var object = arr[idx];
            if(Object.keys(object).length > 2) {
                // This object contains more than just the key/value, so unset
                // the value without modifying the entry otherwise:
                changeTypes[idx] = changeTypes[idx] | VALUE;
                return obj.set(name, null);
            }

            if(isSimpleValueProp) {
                for(i = idx; i < arr.length; i++) {
                    changeTypes[i] = changeTypes[i] | BOTH;
                }
                for(i = idx; i < arr.length; i++) {
                    indexLookup[arr[i][keyName]]--;
                }
                arr.splice(idx, 1);
                delete(indexLookup[name]);
            } else {
                // Perform this update *strictly* so we can check whether the result's
                // been pruned. If so, it's a removal. If not, it's a value unset only.
                nestedProperty(object, valueName).set(null);

                // Now check if the top level nested property has any keys left. If so,
                // the object still has values so we only want to unset the key. If not,
                // the entire object can be removed since there's no other data.
                // var topLevelKeys = Object.keys(object[valueName.split('.')[0]] || []);

                changeTypes[idx] = changeTypes[idx] | VALUE | UNSET;
            }

            return obj;
        },
        constructUpdate: function() {
            var astr, idx;
            var update = {};
            var changed = Object.keys(changeTypes);
            for(var i = 0; i < changed.length; i++) {
                idx = changed[i];
                astr = path + '[' + idx + ']';
                if(arr[idx]) {
                    if(changeTypes[idx] & NAME) {
                        update[astr + '.' + keyName] = arr[idx][keyName];
                    }
                    if(changeTypes[idx] & VALUE) {
                        if(isSimpleValueProp) {
                            update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : arr[idx][valueName];
                        } else {
                            update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : nestedProperty(arr[idx], valueName).get();
                        }
                    }
                } else {
                    update[astr] = null;
                }
            }

            return update;
        }
    };

    return obj;
};


/***/ }),

/***/ "Xhqo":
/*!*************************************************************************!*\
  !*** ./node_modules/readable-stream/lib/internal/streams/BufferList.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer;
var util = __webpack_require__(/*! util */ 3);

function copyBuffer(src, target, offset) {
  src.copy(target, offset);
}

module.exports = function () {
  function BufferList() {
    _classCallCheck(this, BufferList);

    this.head = null;
    this.tail = null;
    this.length = 0;
  }

  BufferList.prototype.push = function push(v) {
    var entry = { data: v, next: null };
    if (this.length > 0) this.tail.next = entry;else this.head = entry;
    this.tail = entry;
    ++this.length;
  };

  BufferList.prototype.unshift = function unshift(v) {
    var entry = { data: v, next: this.head };
    if (this.length === 0) this.tail = entry;
    this.head = entry;
    ++this.length;
  };

  BufferList.prototype.shift = function shift() {
    if (this.length === 0) return;
    var ret = this.head.data;
    if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
    --this.length;
    return ret;
  };

  BufferList.prototype.clear = function clear() {
    this.head = this.tail = null;
    this.length = 0;
  };

  BufferList.prototype.join = function join(s) {
    if (this.length === 0) return '';
    var p = this.head;
    var ret = '' + p.data;
    while (p = p.next) {
      ret += s + p.data;
    }return ret;
  };

  BufferList.prototype.concat = function concat(n) {
    if (this.length === 0) return Buffer.alloc(0);
    if (this.length === 1) return this.head.data;
    var ret = Buffer.allocUnsafe(n >>> 0);
    var p = this.head;
    var i = 0;
    while (p) {
      copyBuffer(p.data, ret, i);
      i += p.data.length;
      p = p.next;
    }
    return ret;
  };

  return BufferList;
}();

if (util && util.inspect && util.inspect.custom) {
  module.exports.prototype[util.inspect.custom] = function () {
    var obj = util.inspect({ length: this.length });
    return this.constructor.name + ' ' + obj;
  };
}

/***/ }),

/***/ "Xi7e":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_ListCache.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var listCacheClear = __webpack_require__(/*! ./_listCacheClear */ "KMkd"),
    listCacheDelete = __webpack_require__(/*! ./_listCacheDelete */ "adU4"),
    listCacheGet = __webpack_require__(/*! ./_listCacheGet */ "tMB7"),
    listCacheHas = __webpack_require__(/*! ./_listCacheHas */ "+6XX"),
    listCacheSet = __webpack_require__(/*! ./_listCacheSet */ "Z8oC");

/**
 * 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]);
  }
}

// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;

module.exports = ListCache;


/***/ }),

/***/ "XoP6":
/*!*************************************************************!*\
  !*** ./node_modules/@phosphor/datagrid/lib/textrenderer.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var cellrenderer_1 = __webpack_require__(/*! ./cellrenderer */ "Cnx3");
/**
 * A cell renderer which renders data values as text.
 */
var TextRenderer = (function (_super) {
    __extends(TextRenderer, _super);
    /**
     * Construct a new text renderer.
     *
     * @param options - The options for initializing the renderer.
     */
    function TextRenderer(options) {
        if (options === void 0) { options = {}; }
        var _this = _super.call(this) || this;
        _this.font = options.font || '12px sans-serif';
        _this.textColor = options.textColor || '#000000';
        _this.backgroundColor = options.backgroundColor || '';
        _this.verticalAlignment = options.verticalAlignment || 'center';
        _this.horizontalAlignment = options.horizontalAlignment || 'left';
        _this.format = options.format || TextRenderer.formatGeneric();
        return _this;
    }
    /**
     * Paint the content for a cell.
     *
     * @param gc - The graphics context to use for drawing.
     *
     * @param config - The configuration data for the cell.
     */
    TextRenderer.prototype.paint = function (gc, config) {
        this.drawBackground(gc, config);
        this.drawText(gc, config);
    };
    /**
     * Prepare the graphics context for drawing a column of cells.
     *
     * @param gc - The graphics context to prepare.
     *
     * @param row - The index of the first row to be rendered.
     *
     * @param col - The index of the column to be rendered.
     *
     * @param field - The field descriptor for the column, or `null`.
     */
    TextRenderer.prototype.prepare = function (gc, config) {
        // Look up the default state from the renderer.
        var _a = this, font = _a.font, textColor = _a.textColor, backgroundColor = _a.backgroundColor, horizontalAlignment = _a.horizontalAlignment;
        // Set up the default font.
        if (font && typeof font === 'string') {
            gc.font = font;
        }
        // Set up the default fill style.
        if (backgroundColor && typeof backgroundColor === 'string') {
            gc.fillStyle = backgroundColor;
        }
        else if (textColor && typeof textColor === 'string') {
            gc.fillStyle = textColor;
        }
        // Set up the default text alignment.
        if (typeof horizontalAlignment === 'string') {
            gc.textAlign = horizontalAlignment;
        }
        else {
            gc.textAlign = 'left';
        }
        // Set up the default text baseline.
        gc.textBaseline = 'bottom';
    };
    /**
     * Draw the background for the cell.
     *
     * @param gc - The graphics context to use for drawing.
     *
     * @param config - The configuration data for the cell.
     */
    TextRenderer.prototype.drawBackground = function (gc, config) {
        // Resolve the background color for the cell.
        var color = cellrenderer_1.CellRenderer.resolveOption(this.backgroundColor, config);
        // Bail if there is no background color to draw.
        if (!color) {
            return;
        }
        // Fill the cell with the background color.
        gc.fillStyle = color;
        gc.fillRect(config.x, config.y, config.width, config.height);
    };
    /**
     * Draw the text for the cell.
     *
     * @param gc - The graphics context to use for drawing.
     *
     * @param config - The configuration data for the cell.
     */
    TextRenderer.prototype.drawText = function (gc, config) {
        // Resolve the font for the cell.
        var font = cellrenderer_1.CellRenderer.resolveOption(this.font, config);
        // Bail if there is no font to draw.
        if (!font) {
            return;
        }
        // Resolve the text color for the cell.
        var color = cellrenderer_1.CellRenderer.resolveOption(this.textColor, config);
        // Bail if there is no text color to draw.
        if (!color) {
            return;
        }
        // Format the cell value to text.
        var format = this.format;
        var text = format(config);
        // Bail if there is no text to draw.
        if (!text) {
            return;
        }
        // Resolve the vertical and horizontal alignment.
        var vAlign = cellrenderer_1.CellRenderer.resolveOption(this.verticalAlignment, config);
        var hAlign = cellrenderer_1.CellRenderer.resolveOption(this.horizontalAlignment, config);
        // Compute the padded text box height for the specified alignment.
        var boxHeight = config.height - (vAlign === 'center' ? 1 : 2);
        // Bail if the text box has no effective size.
        if (boxHeight <= 0) {
            return;
        }
        // Compute the text height for the gc font.
        var textHeight = TextRenderer.measureFontHeight(font);
        // Set up the text position variables.
        var textX;
        var textY;
        // Compute the Y position for the text.
        switch (vAlign) {
            case 'top':
                textY = config.y + 2 + textHeight;
                break;
            case 'center':
                textY = config.y + config.height / 2 + textHeight / 2;
                break;
            case 'bottom':
                textY = config.y + config.height - 2;
                break;
            default:
                throw 'unreachable';
        }
        // Compute the X position for the text.
        switch (hAlign) {
            case 'left':
                textX = config.x + 2;
                break;
            case 'center':
                textX = config.x + config.width / 2;
                break;
            case 'right':
                textX = config.x + config.width - 3;
                break;
            default:
                throw 'unreachable';
        }
        // Clip the cell if the text is taller than the text box height.
        if (textHeight > boxHeight) {
            gc.beginPath();
            gc.rect(config.x, config.y, config.width, config.height - 1);
            gc.clip();
        }
        // Set the gc state.
        gc.font = font;
        gc.fillStyle = color;
        gc.textAlign = hAlign;
        gc.textBaseline = 'bottom';
        // Draw the text for the cell.
        gc.fillText(text, textX, textY);
    };
    return TextRenderer;
}(cellrenderer_1.CellRenderer));
exports.TextRenderer = TextRenderer;
/**
 * The namespace for the `TextRenderer` class statics.
 */
(function (TextRenderer) {
    /**
     * Create a generic text format function.
     *
     * @param options - The options for creating the format function.
     *
     * @returns A new generic text format function.
     *
     * #### Notes
     * This formatter uses the builtin `String()` to coerce any value
     * to a string.
     */
    function formatGeneric(options) {
        if (options === void 0) { options = {}; }
        var missing = options.missing || '';
        return function (_a) {
            var value = _a.value;
            if (value === null || value === undefined) {
                return missing;
            }
            return String(value);
        };
    }
    TextRenderer.formatGeneric = formatGeneric;
    /**
     * Create a fixed decimal format function.
     *
     * @param options - The options for creating the format function.
     *
     * @returns A new fixed decimal format function.
     *
     * #### Notes
     * This formatter uses the builtin `Number()` and `toFixed()` to
     * coerce values.
     *
     * The `formatIntlNumber()` formatter is more flexible, but slower.
     */
    function formatFixed(options) {
        if (options === void 0) { options = {}; }
        var digits = options.digits;
        var missing = options.missing || '';
        return function (_a) {
            var value = _a.value;
            if (value === null || value === undefined) {
                return missing;
            }
            return Number(value).toFixed(digits);
        };
    }
    TextRenderer.formatFixed = formatFixed;
    /**
     * Create a significant figure format function.
     *
     * @param options - The options for creating the format function.
     *
     * @returns A new significant figure format function.
     *
     * #### Notes
     * This formatter uses the builtin `Number()` and `toPrecision()`
     * to coerce values.
     *
     * The `formatIntlNumber()` formatter is more flexible, but slower.
     */
    function formatPrecision(options) {
        if (options === void 0) { options = {}; }
        var digits = options.digits;
        var missing = options.missing || '';
        return function (_a) {
            var value = _a.value;
            if (value === null || value === undefined) {
                return missing;
            }
            return Number(value).toPrecision(digits);
        };
    }
    TextRenderer.formatPrecision = formatPrecision;
    /**
     * Create a scientific notation format function.
     *
     * @param options - The options for creating the format function.
     *
     * @returns A new scientific notation format function.
     *
     * #### Notes
     * This formatter uses the builtin `Number()` and `toExponential()`
     * to coerce values.
     *
     * The `formatIntlNumber()` formatter is more flexible, but slower.
     */
    function formatExponential(options) {
        if (options === void 0) { options = {}; }
        var digits = options.digits;
        var missing = options.missing || '';
        return function (_a) {
            var value = _a.value;
            if (value === null || value === undefined) {
                return missing;
            }
            return Number(value).toExponential(digits);
        };
    }
    TextRenderer.formatExponential = formatExponential;
    /**
     * Create an international number format function.
     *
     * @param options - The options for creating the format function.
     *
     * @returns A new international number format function.
     *
     * #### Notes
     * This formatter uses the builtin `Intl.NumberFormat` object to
     * coerce values.
     *
     * This is the most flexible (but slowest) number formatter.
     */
    function formatIntlNumber(options) {
        if (options === void 0) { options = {}; }
        var missing = options.missing || '';
        var nft = new Intl.NumberFormat(options.locales, options.options);
        return function (_a) {
            var value = _a.value;
            if (value === null || value === undefined) {
                return missing;
            }
            return nft.format(value);
        };
    }
    TextRenderer.formatIntlNumber = formatIntlNumber;
    /**
     * Create a date format function.
     *
     * @param options - The options for creating the format function.
     *
     * @returns A new date format function.
     *
     * #### Notes
     * This formatter uses `Date.toDateString()` to format the values.
     *
     * If a value is not a `Date` object, `new Date(value)` is used to
     * coerce the value to a date.
     *
     * The `formatIntlDateTime()` formatter is more flexible, but slower.
     */
    function formatDate(options) {
        if (options === void 0) { options = {}; }
        var missing = options.missing || '';
        return function (_a) {
            var value = _a.value;
            if (value === null || value === undefined) {
                return missing;
            }
            if (value instanceof Date) {
                return value.toDateString();
            }
            return (new Date(value)).toDateString();
        };
    }
    TextRenderer.formatDate = formatDate;
    /**
     * Create a time format function.
     *
     * @param options - The options for creating the format function.
     *
     * @returns A new time format function.
     *
     * #### Notes
     * This formatter uses `Date.toTimeString()` to format the values.
     *
     * If a value is not a `Date` object, `new Date(value)` is used to
     * coerce the value to a date.
     *
     * The `formatIntlDateTime()` formatter is more flexible, but slower.
     */
    function formatTime(options) {
        if (options === void 0) { options = {}; }
        var missing = options.missing || '';
        return function (_a) {
            var value = _a.value;
            if (value === null || value === undefined) {
                return missing;
            }
            if (value instanceof Date) {
                return value.toTimeString();
            }
            return (new Date(value)).toTimeString();
        };
    }
    TextRenderer.formatTime = formatTime;
    /**
     * Create an ISO datetime format function.
     *
     * @param options - The options for creating the format function.
     *
     * @returns A new ISO datetime format function.
     *
     * #### Notes
     * This formatter uses `Date.toISOString()` to format the values.
     *
     * If a value is not a `Date` object, `new Date(value)` is used to
     * coerce the value to a date.
     *
     * The `formatIntlDateTime()` formatter is more flexible, but slower.
     */
    function formatISODateTime(options) {
        if (options === void 0) { options = {}; }
        var missing = options.missing || '';
        return function (_a) {
            var value = _a.value;
            if (value === null || value === undefined) {
                return missing;
            }
            if (value instanceof Date) {
                return value.toISOString();
            }
            return (new Date(value)).toISOString();
        };
    }
    TextRenderer.formatISODateTime = formatISODateTime;
    /**
     * Create a UTC datetime format function.
     *
     * @param options - The options for creating the format function.
     *
     * @returns A new UTC datetime format function.
     *
     * #### Notes
     * This formatter uses `Date.toUTCString()` to format the values.
     *
     * If a value is not a `Date` object, `new Date(value)` is used to
     * coerce the value to a date.
     *
     * The `formatIntlDateTime()` formatter is more flexible, but slower.
     */
    function formatUTCDateTime(options) {
        if (options === void 0) { options = {}; }
        var missing = options.missing || '';
        return function (_a) {
            var value = _a.value;
            if (value === null || value === undefined) {
                return missing;
            }
            if (value instanceof Date) {
                return value.toUTCString();
            }
            return (new Date(value)).toUTCString();
        };
    }
    TextRenderer.formatUTCDateTime = formatUTCDateTime;
    /**
     * Create an international datetime format function.
     *
     * @param options - The options for creating the format function.
     *
     * @returns A new international datetime format function.
     *
     * #### Notes
     * This formatter uses the builtin `Intl.DateTimeFormat` object to
     * coerce values.
     *
     * This is the most flexible (but slowest) datetime formatter.
     */
    function formatIntlDateTime(options) {
        if (options === void 0) { options = {}; }
        var missing = options.missing || '';
        var dtf = new Intl.DateTimeFormat(options.locales, options.options);
        return function (_a) {
            var value = _a.value;
            if (value === null || value === undefined) {
                return missing;
            }
            return dtf.format(value);
        };
    }
    TextRenderer.formatIntlDateTime = formatIntlDateTime;
    /**
     * Measure the height of a font.
     *
     * @param font - The CSS font string of interest.
     *
     * @returns The height of the font bounding box.
     *
     * #### Notes
     * This function uses a temporary DOM node to measure the text box
     * height for the specified font. The first call for a given font
     * will incur a DOM reflow, but the return value is cached, so any
     * subsequent call for the same font will return the cached value.
     */
    function measureFontHeight(font) {
        // Look up the cached font height.
        var height = Private.fontHeightCache[font];
        // Return the cached font height if it exists.
        if (height !== undefined) {
            return height;
        }
        // Normalize the font.
        Private.fontMeasurementGC.font = font;
        var normFont = Private.fontMeasurementGC.font;
        // Set the font on the measurement node.
        Private.fontMeasurementNode.style.font = normFont;
        // Add the measurement node to the document.
        document.body.appendChild(Private.fontMeasurementNode);
        // Measure the node height.
        height = Private.fontMeasurementNode.offsetHeight;
        // Remove the measurement node from the document.
        document.body.removeChild(Private.fontMeasurementNode);
        // Cache the measured height for the font and norm font.
        Private.fontHeightCache[font] = height;
        Private.fontHeightCache[normFont] = height;
        // Return the measured height.
        return height;
    }
    TextRenderer.measureFontHeight = measureFontHeight;
})(TextRenderer = exports.TextRenderer || (exports.TextRenderer = {}));
exports.TextRenderer = TextRenderer;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * A cache of measured font heights.
     */
    Private.fontHeightCache = Object.create(null);
    /**
     * The DOM node used for font height measurement.
     */
    Private.fontMeasurementNode = (function () {
        var node = document.createElement('div');
        node.style.position = 'absolute';
        node.style.top = '-99999px';
        node.style.left = '-99999px';
        node.style.visibility = 'hidden';
        node.textContent = 'M';
        return node;
    })();
    /**
     * The GC used for font measurement.
     */
    Private.fontMeasurementGC = (function () {
        var canvas = document.createElement('canvas');
        canvas.width = 0;
        canvas.height = 0;
        return canvas.getContext('2d');
    })();
})(Private || (Private = {}));


/***/ }),

/***/ "XpWx":
/*!***************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/connectNonCartesianSubplotToLayout.js ***!
  \***************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

exports.default = connectNonCartesianSubplotToLayout;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _lib = __webpack_require__(/*! ../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function connectNonCartesianSubplotToLayout(WrappedComponent) {
  var SubplotConnectedComponent = function (_Component) {
    _inherits(SubplotConnectedComponent, _Component);

    function SubplotConnectedComponent(props, context) {
      _classCallCheck(this, SubplotConnectedComponent);

      var _this = _possibleConstructorReturn(this, (SubplotConnectedComponent.__proto__ || Object.getPrototypeOf(SubplotConnectedComponent)).call(this, props, context));

      _this.updateSubplot = _this.updateSubplot.bind(_this);
      _this.setLocals(props, context);
      return _this;
    }

    _createClass(SubplotConnectedComponent, [{
      key: 'componentWillReceiveProps',
      value: function componentWillReceiveProps(nextProps, nextContext) {
        this.setLocals(nextProps, nextContext);
      }
    }, {
      key: 'setLocals',
      value: function setLocals(props, context) {
        var subplot = props.subplot,
            traceIndexes = props.traceIndexes;
        var container = context.container,
            fullContainer = context.fullContainer,
            data = context.data;


        this.container = container[subplot] || {};
        this.fullContainer = fullContainer[subplot] || {};

        var trace = traceIndexes.length > 0 ? data[traceIndexes[0]] : {};
        var fullTrace = (0, _lib.getFullTrace)(props, context);

        if (trace && fullTrace) {
          this.icon = (0, _lib.renderTraceIcon)((0, _lib.plotlyTraceToCustomTrace)(trace));
          this.name = fullTrace.name;
        }
      }
    }, {
      key: 'getChildContext',
      value: function getChildContext() {
        var _this2 = this;

        return {
          getValObject: function getValObject(attr) {
            return !_this2.context.getValObject ? null : _this2.context.getValObject(_this2.props.subplot + '.' + attr);
          },
          updateContainer: this.updateSubplot,
          container: this.container,
          fullContainer: this.fullContainer
        };
      }
    }, {
      key: 'updateSubplot',
      value: function updateSubplot(update) {
        var newUpdate = {};
        for (var key in update) {
          newUpdate[this.props.subplot + '.' + key] = update[key];
        }
        this.context.updateContainer(newUpdate);
      }
    }, {
      key: 'render',
      value: function render() {
        return _react2.default.createElement(WrappedComponent, _extends({ name: this.name, icon: this.icon }, this.props));
      }
    }]);

    return SubplotConnectedComponent;
  }(_react.Component);

  SubplotConnectedComponent.displayName = 'SubplotConnected' + (0, _lib.getDisplayName)(WrappedComponent);

  SubplotConnectedComponent.propTypes = {
    subplot: _propTypes2.default.string.isRequired
  };

  SubplotConnectedComponent.contextTypes = {
    container: _propTypes2.default.object,
    fullContainer: _propTypes2.default.object,
    data: _propTypes2.default.array,
    fullData: _propTypes2.default.array,
    onUpdate: _propTypes2.default.func,
    updateContainer: _propTypes2.default.func,
    getValObject: _propTypes2.default.func
  };

  SubplotConnectedComponent.childContextTypes = {
    updateContainer: _propTypes2.default.func,
    deleteContainer: _propTypes2.default.func,
    container: _propTypes2.default.object,
    fullContainer: _propTypes2.default.object,
    getValObject: _propTypes2.default.func
  };

  var plotly_editor_traits = WrappedComponent.plotly_editor_traits;

  SubplotConnectedComponent.plotly_editor_traits = plotly_editor_traits;

  return SubplotConnectedComponent;
}
//# sourceMappingURL=connectNonCartesianSubplotToLayout.js.map

/***/ }),

/***/ "XtOF":
/*!************************************************************!*\
  !*** ./node_modules/@jupyterlab/filebrowser/lib/upload.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
/**
 * A widget which provides an upload button.
 */
class Uploader extends apputils_1.ToolbarButton {
    /**
     * Construct a new file browser buttons widget.
     */
    constructor(options) {
        super({
            iconClassName: 'jp-FileUploadIcon jp-Icon jp-Icon-16',
            onClick: () => {
                this._input.click();
            },
            tooltip: 'Upload Files'
        });
        /**
         * The 'change' handler for the input field.
         */
        this._onInputChanged = () => {
            let files = Array.prototype.slice.call(this._input.files);
            let pending = files.map(file => this.fileBrowserModel.upload(file));
            Promise.all(pending).catch(error => {
                apputils_1.showErrorMessage('Upload Error', error);
            });
        };
        /**
         * The 'click' handler for the input field.
         */
        this._onInputClicked = () => {
            // In order to allow repeated uploads of the same file (with delete in between),
            // we need to clear the input value to trigger a change event.
            this._input.value = '';
        };
        this._input = Private.createUploadInput();
        this.fileBrowserModel = options.model;
        this._input.onclick = this._onInputClicked;
        this._input.onchange = this._onInputChanged;
        this.addClass('jp-id-upload');
    }
}
exports.Uploader = Uploader;
/**
 * The namespace for module private data.
 */
var Private;
(function (Private) {
    /**
     * Create the upload input node for a file buttons widget.
     */
    function createUploadInput() {
        let input = document.createElement('input');
        input.type = 'file';
        input.multiple = true;
        return input;
    }
    Private.createUploadInput = createUploadInput;
})(Private || (Private = {}));


/***/ }),

/***/ "Xudb":
/*!**********************************************!*\
  !*** ./node_modules/des.js/lib/des/utils.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.readUInt32BE = function readUInt32BE(bytes, off) {
  var res =  (bytes[0 + off] << 24) |
             (bytes[1 + off] << 16) |
             (bytes[2 + off] << 8) |
             bytes[3 + off];
  return res >>> 0;
};

exports.writeUInt32BE = function writeUInt32BE(bytes, value, off) {
  bytes[0 + off] = value >>> 24;
  bytes[1 + off] = (value >>> 16) & 0xff;
  bytes[2 + off] = (value >>> 8) & 0xff;
  bytes[3 + off] = value & 0xff;
};

exports.ip = function ip(inL, inR, out, off) {
  var outL = 0;
  var outR = 0;

  for (var i = 6; i >= 0; i -= 2) {
    for (var j = 0; j <= 24; j += 8) {
      outL <<= 1;
      outL |= (inR >>> (j + i)) & 1;
    }
    for (var j = 0; j <= 24; j += 8) {
      outL <<= 1;
      outL |= (inL >>> (j + i)) & 1;
    }
  }

  for (var i = 6; i >= 0; i -= 2) {
    for (var j = 1; j <= 25; j += 8) {
      outR <<= 1;
      outR |= (inR >>> (j + i)) & 1;
    }
    for (var j = 1; j <= 25; j += 8) {
      outR <<= 1;
      outR |= (inL >>> (j + i)) & 1;
    }
  }

  out[off + 0] = outL >>> 0;
  out[off + 1] = outR >>> 0;
};

exports.rip = function rip(inL, inR, out, off) {
  var outL = 0;
  var outR = 0;

  for (var i = 0; i < 4; i++) {
    for (var j = 24; j >= 0; j -= 8) {
      outL <<= 1;
      outL |= (inR >>> (j + i)) & 1;
      outL <<= 1;
      outL |= (inL >>> (j + i)) & 1;
    }
  }
  for (var i = 4; i < 8; i++) {
    for (var j = 24; j >= 0; j -= 8) {
      outR <<= 1;
      outR |= (inR >>> (j + i)) & 1;
      outR <<= 1;
      outR |= (inL >>> (j + i)) & 1;
    }
  }

  out[off + 0] = outL >>> 0;
  out[off + 1] = outR >>> 0;
};

exports.pc1 = function pc1(inL, inR, out, off) {
  var outL = 0;
  var outR = 0;

  // 7, 15, 23, 31, 39, 47, 55, 63
  // 6, 14, 22, 30, 39, 47, 55, 63
  // 5, 13, 21, 29, 39, 47, 55, 63
  // 4, 12, 20, 28
  for (var i = 7; i >= 5; i--) {
    for (var j = 0; j <= 24; j += 8) {
      outL <<= 1;
      outL |= (inR >> (j + i)) & 1;
    }
    for (var j = 0; j <= 24; j += 8) {
      outL <<= 1;
      outL |= (inL >> (j + i)) & 1;
    }
  }
  for (var j = 0; j <= 24; j += 8) {
    outL <<= 1;
    outL |= (inR >> (j + i)) & 1;
  }

  // 1, 9, 17, 25, 33, 41, 49, 57
  // 2, 10, 18, 26, 34, 42, 50, 58
  // 3, 11, 19, 27, 35, 43, 51, 59
  // 36, 44, 52, 60
  for (var i = 1; i <= 3; i++) {
    for (var j = 0; j <= 24; j += 8) {
      outR <<= 1;
      outR |= (inR >> (j + i)) & 1;
    }
    for (var j = 0; j <= 24; j += 8) {
      outR <<= 1;
      outR |= (inL >> (j + i)) & 1;
    }
  }
  for (var j = 0; j <= 24; j += 8) {
    outR <<= 1;
    outR |= (inL >> (j + i)) & 1;
  }

  out[off + 0] = outL >>> 0;
  out[off + 1] = outR >>> 0;
};

exports.r28shl = function r28shl(num, shift) {
  return ((num << shift) & 0xfffffff) | (num >>> (28 - shift));
};

var pc2table = [
  // inL => outL
  14, 11, 17, 4, 27, 23, 25, 0,
  13, 22, 7, 18, 5, 9, 16, 24,
  2, 20, 12, 21, 1, 8, 15, 26,

  // inR => outR
  15, 4, 25, 19, 9, 1, 26, 16,
  5, 11, 23, 8, 12, 7, 17, 0,
  22, 3, 10, 14, 6, 20, 27, 24
];

exports.pc2 = function pc2(inL, inR, out, off) {
  var outL = 0;
  var outR = 0;

  var len = pc2table.length >>> 1;
  for (var i = 0; i < len; i++) {
    outL <<= 1;
    outL |= (inL >>> pc2table[i]) & 0x1;
  }
  for (var i = len; i < pc2table.length; i++) {
    outR <<= 1;
    outR |= (inR >>> pc2table[i]) & 0x1;
  }

  out[off + 0] = outL >>> 0;
  out[off + 1] = outR >>> 0;
};

exports.expand = function expand(r, out, off) {
  var outL = 0;
  var outR = 0;

  outL = ((r & 1) << 5) | (r >>> 27);
  for (var i = 23; i >= 15; i -= 4) {
    outL <<= 6;
    outL |= (r >>> i) & 0x3f;
  }
  for (var i = 11; i >= 3; i -= 4) {
    outR |= (r >>> i) & 0x3f;
    outR <<= 6;
  }
  outR |= ((r & 0x1f) << 1) | (r >>> 31);

  out[off + 0] = outL >>> 0;
  out[off + 1] = outR >>> 0;
};

var sTable = [
  14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1,
  3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8,
  4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7,
  15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13,

  15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14,
  9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5,
  0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2,
  5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9,

  10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10,
  1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1,
  13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7,
  11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12,

  7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3,
  1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9,
  10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8,
  15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14,

  2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1,
  8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6,
  4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13,
  15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3,

  12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5,
  0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8,
  9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10,
  7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13,

  4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10,
  3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6,
  1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7,
  10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12,

  13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4,
  10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2,
  7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13,
  0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11
];

exports.substitute = function substitute(inL, inR) {
  var out = 0;
  for (var i = 0; i < 4; i++) {
    var b = (inL >>> (18 - i * 6)) & 0x3f;
    var sb = sTable[i * 0x40 + b];

    out <<= 4;
    out |= sb;
  }
  for (var i = 0; i < 4; i++) {
    var b = (inR >>> (18 - i * 6)) & 0x3f;
    var sb = sTable[4 * 0x40 + i * 0x40 + b];

    out <<= 4;
    out |= sb;
  }
  return out >>> 0;
};

var permuteTable = [
  16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22,
  30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7
];

exports.permute = function permute(num) {
  var out = 0;
  for (var i = 0; i < permuteTable.length; i++) {
    out <<= 1;
    out |= (num >>> permuteTable[i]) & 0x1;
  }
  return out >>> 0;
};

exports.padSplit = function padSplit(num, size, group) {
  var str = num.toString(2);
  while (str.length < size)
    str = '0' + str;

  var out = [];
  for (var i = 0; i < size; i += group)
    out.push(str.slice(i, i + group));
  return out.join(' ');
};


/***/ }),

/***/ "XwjZ":
/*!************************************************************!*\
  !*** ./node_modules/@jupyterlab/inspector/style/index.css ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "3eV8");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "XxHi":
/*!**************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/text_editors/LaTeX.js ***!
  \**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _TextArea2 = __webpack_require__(/*! ../TextArea */ "6HQ/");

var _TextArea3 = _interopRequireDefault(_TextArea2);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _convertFormats = __webpack_require__(/*! ./convertFormats */ "C6sy");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var LaTeX = function (_TextArea) {
  _inherits(LaTeX, _TextArea);

  function LaTeX(props) {
    _classCallCheck(this, LaTeX);

    // Internally, represesent the LaTeX document without the
    // wrapping `$...$` characters.
    var _this = _possibleConstructorReturn(this, (LaTeX.__proto__ || Object.getPrototypeOf(LaTeX)).call(this, props));

    var unwrappedValue = _this.unwrap(props.value);

    _this.state = {
      value: unwrappedValue
    };
    _this.onChange = _this.onChange.bind(_this);
    _this.onBlur = _this.onBlur.bind(_this);
    return _this;
  }

  _createClass(LaTeX, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      var unwrappedNextValue = this.unwrap(nextProps.value);

      if (unwrappedNextValue !== this.state.value) {
        this.setState({
          value: unwrappedNextValue
        });
      }
    }

    // Return a new value with wrapping `$...$` removed.

  }, {
    key: 'unwrap',
    value: function unwrap(value) {
      if ((0, _convertFormats.isLaTeXExpr)(value)) {
        return value.substr(1, value.length - 2);
      }

      return value;
    }

    // Wrap value in `$...$`.

  }, {
    key: 'wrap',
    value: function wrap(value) {
      if (!(0, _convertFormats.isLaTeXExpr)(value)) {
        return '$' + value + '$';
      }

      return value;
    }
  }, {
    key: 'onChange',
    value: function onChange(e) {
      this.setState({
        value: e.target.value
      });
    }
  }, {
    key: 'onBlur',
    value: function onBlur(e) {
      var value = this.wrap(e.target.value);
      this.props.onChange(value);
    }
  }, {
    key: 'render',
    value: function render() {
      var className = this.props.className;

      var editorClassNames = className ? className : 'text-editor__latex';
      return _react2.default.createElement('textarea', {
        value: this.state.value,
        placeholder: this.props.placeholder,
        onChange: this.onChange,
        onBlur: this.onBlur,
        className: editorClassNames
      });
    }
  }]);

  return LaTeX;
}(_TextArea3.default);

exports.default = LaTeX;


LaTeX.propTypes = {
  className: _propTypes2.default.string,
  onChange: _propTypes2.default.func.isRequired,
  placeholder: _propTypes2.default.string,
  value: _propTypes2.default.string
};

LaTeX.defaultProps = {
  value: '',
  placeholder: ''
};
//# sourceMappingURL=LaTeX.js.map

/***/ }),

/***/ "Y+p1":
/*!****************************************!*\
  !*** ./node_modules/lodash/isEqual.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseIsEqual = __webpack_require__(/*! ./_baseIsEqual */ "wF/u");

/**
 * 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);
}

module.exports = isEqual;


/***/ }),

/***/ "Y/kH":
/*!******************************************************!*\
  !*** ./node_modules/draft-js/lib/editOnDragStart.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule editOnDragStart
 * @format
 * 
 */



/**
 * A `dragstart` event has begun within the text editor component.
 */
function editOnDragStart(editor) {
  editor._internalDrag = true;
  editor.setMode('drag');
}

module.exports = editOnDragStart;

/***/ }),

/***/ "Y29x":
/*!**********************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/docklayout.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
var domutils_1 = __webpack_require__(/*! @phosphor/domutils */ "XWTc");
var messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
var boxengine_1 = __webpack_require__(/*! ./boxengine */ "ovjo");
var layout_1 = __webpack_require__(/*! ./layout */ "yNaG");
var widget_1 = __webpack_require__(/*! ./widget */ "FmDU");
/**
 * A layout which provides a flexible docking arrangement.
 *
 * #### Notes
 * The consumer of this layout is repsonsible for handling all signals
 * from the generated tab bars and managing the visibility of widgets
 * and tab bars as needed.
 */
var DockLayout = (function (_super) {
    __extends(DockLayout, _super);
    /**
     * Construct a new dock layout.
     *
     * @param options - The options for initializing the layout.
     */
    function DockLayout(options) {
        var _this = _super.call(this) || this;
        _this._spacing = 4;
        _this._dirty = false;
        _this._root = null;
        _this._box = null;
        _this._items = new Map();
        _this.renderer = options.renderer;
        if (options.spacing !== undefined) {
            _this._spacing = Private.clampSpacing(options.spacing);
        }
        return _this;
    }
    /**
     * Dispose of the resources held by the layout.
     *
     * #### Notes
     * This will clear and dispose all widgets in the layout.
     */
    DockLayout.prototype.dispose = function () {
        // Get an iterator over the widgets in the layout.
        var widgets = this.iter();
        // Dispose of the layout items.
        this._items.forEach(function (item) { item.dispose(); });
        // Clear the layout state before disposing the widgets.
        this._box = null;
        this._root = null;
        this._items.clear();
        // Dispose of the widgets contained in the old layout root.
        algorithm_1.each(widgets, function (widget) { widget.dispose(); });
        // Dispose of the base class.
        _super.prototype.dispose.call(this);
    };
    Object.defineProperty(DockLayout.prototype, "spacing", {
        /**
         * Get the inter-element spacing for the dock layout.
         */
        get: function () {
            return this._spacing;
        },
        /**
         * Set the inter-element spacing for the dock layout.
         */
        set: function (value) {
            value = Private.clampSpacing(value);
            if (this._spacing === value) {
                return;
            }
            this._spacing = value;
            if (!this.parent) {
                return;
            }
            this.parent.fit();
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DockLayout.prototype, "isEmpty", {
        /**
         * Whether the dock layout is empty.
         */
        get: function () {
            return this._root === null;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Create an iterator over all widgets in the layout.
     *
     * @returns A new iterator over the widgets in the layout.
     *
     * #### Notes
     * This iterator includes the generated tab bars.
     */
    DockLayout.prototype.iter = function () {
        return this._root ? this._root.iterAllWidgets() : algorithm_1.empty();
    };
    /**
     * Create an iterator over the user widgets in the layout.
     *
     * @returns A new iterator over the user widgets in the layout.
     *
     * #### Notes
     * This iterator does not include the generated tab bars.
     */
    DockLayout.prototype.widgets = function () {
        return this._root ? this._root.iterUserWidgets() : algorithm_1.empty();
    };
    /**
     * Create an iterator over the selected widgets in the layout.
     *
     * @returns A new iterator over the selected user widgets.
     *
     * #### Notes
     * This iterator yields the widgets corresponding to the current tab
     * of each tab bar in the layout.
     */
    DockLayout.prototype.selectedWidgets = function () {
        return this._root ? this._root.iterSelectedWidgets() : algorithm_1.empty();
    };
    /**
     * Create an iterator over the tab bars in the layout.
     *
     * @returns A new iterator over the tab bars in the layout.
     *
     * #### Notes
     * This iterator does not include the user widgets.
     */
    DockLayout.prototype.tabBars = function () {
        return this._root ? this._root.iterTabBars() : algorithm_1.empty();
    };
    /**
     * Create an iterator over the handles in the layout.
     *
     * @returns A new iterator over the handles in the layout.
     */
    DockLayout.prototype.handles = function () {
        return this._root ? this._root.iterHandles() : algorithm_1.empty();
    };
    /**
     * Move a handle to the given offset position.
     *
     * @param handle - The handle to move.
     *
     * @param offsetX - The desired offset X position of the handle.
     *
     * @param offsetY - The desired offset Y position of the handle.
     *
     * #### Notes
     * If the given handle is not contained in the layout, this is no-op.
     *
     * The handle will be moved as close as possible to the desired
     * position without violating any of the layout constraints.
     *
     * Only one of the coordinates is used depending on the orientation
     * of the handle. This method accepts both coordinates to make it
     * easy to invoke from a mouse move event without needing to know
     * the handle orientation.
     */
    DockLayout.prototype.moveHandle = function (handle, offsetX, offsetY) {
        // Bail early if there is no root or if the handle is hidden.
        if (!this._root || handle.classList.contains('p-mod-hidden')) {
            return;
        }
        // Lookup the split node for the handle.
        var data = this._root.findSplitNode(handle);
        if (!data) {
            return;
        }
        // Compute the desired delta movement for the handle.
        var delta;
        if (data.node.orientation === 'horizontal') {
            delta = offsetX - handle.offsetLeft;
        }
        else {
            delta = offsetY - handle.offsetTop;
        }
        // Bail if there is no handle movement.
        if (delta === 0) {
            return;
        }
        // Prevent sibling resizing unless needed.
        data.node.holdSizes();
        // Adjust the sizers to reflect the handle movement.
        boxengine_1.BoxEngine.adjust(data.node.sizers, data.index, delta);
        // Update the layout of the widgets.
        if (this.parent) {
            this.parent.update();
        }
    };
    /**
     * Save the current configuration of the dock layout.
     *
     * @returns A new config object for the current layout state.
     *
     * #### Notes
     * The return value can be provided to the `restoreLayout` method
     * in order to restore the layout to its current configuration.
     */
    DockLayout.prototype.saveLayout = function () {
        // Bail early if there is no root.
        if (!this._root) {
            return { main: null };
        }
        // Hold the current sizes in the layout tree.
        this._root.holdAllSizes();
        // Return the layout config.
        return { main: this._root.createConfig() };
    };
    /**
     * Restore the layout to a previously saved configuration.
     *
     * @param config - The layout configuration to restore.
     *
     * #### Notes
     * Widgets which currently belong to the layout but which are not
     * contained in the config will be unparented.
     */
    DockLayout.prototype.restoreLayout = function (config) {
        var _this = this;
        // Create the widget set for validating the config.
        var widgetSet = new Set();
        // Normalize the main area config and collect the widgets.
        var mainConfig;
        if (config.main) {
            mainConfig = Private.normalizeAreaConfig(config.main, widgetSet);
        }
        else {
            mainConfig = null;
        }
        // Create iterators over the old content.
        var oldWidgets = this.widgets();
        var oldTabBars = this.tabBars();
        var oldHandles = this.handles();
        // Clear the root before removing the old content.
        this._root = null;
        // Unparent the old widgets which are not in the new config.
        algorithm_1.each(oldWidgets, function (widget) {
            if (!widgetSet.has(widget)) {
                widget.parent = null;
            }
        });
        // Dispose of the old tab bars.
        algorithm_1.each(oldTabBars, function (tabBar) {
            tabBar.dispose();
        });
        // Remove the old handles.
        algorithm_1.each(oldHandles, function (handle) {
            if (handle.parentNode) {
                handle.parentNode.removeChild(handle);
            }
        });
        // Reparent the new widgets to the current parent.
        widgetSet.forEach(function (widget) {
            widget.parent = _this.parent;
        });
        // Create the root node for the new config.
        if (mainConfig) {
            this._root = Private.realizeAreaConfig(mainConfig, {
                createTabBar: function () { return _this._createTabBar(); },
                createHandle: function () { return _this._createHandle(); }
            });
        }
        else {
            this._root = null;
        }
        // If there is no parent, there is nothing more to do.
        if (!this.parent) {
            return;
        }
        // Attach the new widgets to the parent.
        widgetSet.forEach(function (widget) {
            _this.attachWidget(widget);
        });
        // Post a fit request to the parent.
        this.parent.fit();
    };
    /**
     * Add a widget to the dock layout.
     *
     * @param widget - The widget to add to the dock layout.
     *
     * @param options - The additional options for adding the widget.
     *
     * #### Notes
     * The widget will be moved if it is already contained in the layout.
     *
     * An error will be thrown if the reference widget is invalid.
     */
    DockLayout.prototype.addWidget = function (widget, options) {
        if (options === void 0) { options = {}; }
        // Parse the options.
        var ref = options.ref || null;
        var mode = options.mode || 'tab-after';
        // Find the tab node which holds the reference widget.
        var refNode = null;
        if (this._root && ref) {
            refNode = this._root.findTabNode(ref);
        }
        // Throw an error if the reference widget is invalid.
        if (ref && !refNode) {
            throw new Error('Reference widget is not in the layout.');
        }
        // Reparent the widget to the current layout parent.
        widget.parent = this.parent;
        // Insert the widget according to the insert mode.
        switch (mode) {
            case 'tab-after':
                this._insertTab(widget, ref, refNode, true);
                break;
            case 'tab-before':
                this._insertTab(widget, ref, refNode, false);
                break;
            case 'split-top':
                this._insertSplit(widget, ref, refNode, 'vertical', false);
                break;
            case 'split-left':
                this._insertSplit(widget, ref, refNode, 'horizontal', false);
                break;
            case 'split-right':
                this._insertSplit(widget, ref, refNode, 'horizontal', true);
                break;
            case 'split-bottom':
                this._insertSplit(widget, ref, refNode, 'vertical', true);
                break;
        }
        // Do nothing else if there is no parent widget.
        if (!this.parent) {
            return;
        }
        // Ensure the widget is attached to the parent widget.
        this.attachWidget(widget);
        // Post a fit request for the parent widget.
        this.parent.fit();
    };
    /**
     * Remove a widget from the layout.
     *
     * @param widget - The widget to remove from the layout.
     *
     * #### Notes
     * A widget is automatically removed from the layout when its `parent`
     * is set to `null`. This method should only be invoked directly when
     * removing a widget from a layout which has yet to be installed on a
     * parent widget.
     *
     * This method does *not* modify the widget's `parent`.
     */
    DockLayout.prototype.removeWidget = function (widget) {
        // Remove the widget from its current layout location.
        this._removeWidget(widget);
        // Do nothing else if there is no parent widget.
        if (!this.parent) {
            return;
        }
        // Detach the widget from the parent widget.
        this.detachWidget(widget);
        // Post a fit request for the parent widget.
        this.parent.fit();
    };
    /**
     * Find the tab area which contains the given client position.
     *
     * @param clientX - The client X position of interest.
     *
     * @param clientY - The client Y position of interest.
     *
     * @returns The geometry of the tab area at the given position, or
     *   `null` if there is no tab area at the given position.
     */
    DockLayout.prototype.hitTestTabAreas = function (clientX, clientY) {
        // Bail early if hit testing cannot produce valid results.
        if (!this._root || !this.parent || !this.parent.isVisible) {
            return null;
        }
        // Ensure the parent box sizing data is computed.
        if (!this._box) {
            this._box = domutils_1.ElementExt.boxSizing(this.parent.node);
        }
        // Convert from client to local coordinates.
        var rect = this.parent.node.getBoundingClientRect();
        var x = clientX - rect.left - this._box.borderLeft;
        var y = clientY - rect.top - this._box.borderTop;
        // Find the tab layout node at the local position.
        var tabNode = this._root.hitTestTabNodes(x, y);
        // Bail if a tab layout node was not found.
        if (!tabNode) {
            return null;
        }
        // Extract the data from the tab node.
        var tabBar = tabNode.tabBar, top = tabNode.top, left = tabNode.left, width = tabNode.width, height = tabNode.height;
        // Compute the right and bottom edges of the tab area.
        var borderWidth = this._box.borderLeft + this._box.borderRight;
        var borderHeight = this._box.borderTop + this._box.borderBottom;
        var right = rect.width - borderWidth - (left + width);
        var bottom = rect.height - borderHeight - (top + height);
        // Return the hit test results.
        return { tabBar: tabBar, x: x, y: y, top: top, left: left, right: right, bottom: bottom, width: width, height: height };
    };
    /**
     * Perform layout initialization which requires the parent widget.
     */
    DockLayout.prototype.init = function () {
        var _this = this;
        // Perform superclass initialization.
        _super.prototype.init.call(this);
        // Attach each widget to the parent.
        algorithm_1.each(this, function (widget) { _this.attachWidget(widget); });
        // Attach each handle to the parent.
        algorithm_1.each(this.handles(), function (handle) { _this.parent.node.appendChild(handle); });
        // Post a fit request for the parent widget.
        this.parent.fit();
    };
    /**
     * Attach the widget to the layout parent widget.
     *
     * @param widget - The widget to attach to the parent.
     *
     * #### Notes
     * This is a no-op if the widget is already attached.
     */
    DockLayout.prototype.attachWidget = function (widget) {
        // Do nothing if the widget is already attached.
        if (this.parent.node === widget.node.parentNode) {
            return;
        }
        // Create the layout item for the widget.
        this._items.set(widget, new layout_1.LayoutItem(widget));
        // Send a `'before-attach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.BeforeAttach);
        }
        // Add the widget's node to the parent.
        this.parent.node.appendChild(widget.node);
        // Send an `'after-attach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.AfterAttach);
        }
    };
    /**
     * Detach the widget from the layout parent widget.
     *
     * @param widget - The widget to detach from the parent.
     *
     * #### Notes
     * This is a no-op if the widget is not attached.
     */
    DockLayout.prototype.detachWidget = function (widget) {
        // Do nothing if the widget is not attached.
        if (this.parent.node !== widget.node.parentNode) {
            return;
        }
        // Send a `'before-detach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.BeforeDetach);
        }
        // Remove the widget's node from the parent.
        this.parent.node.removeChild(widget.node);
        // Send an `'after-detach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.AfterDetach);
        }
        // Delete the layout item for the widget.
        var item = this._items.get(widget);
        if (item) {
            this._items.delete(widget);
            item.dispose();
        }
    };
    /**
     * A message handler invoked on a `'before-show'` message.
     */
    DockLayout.prototype.onBeforeShow = function (msg) {
        _super.prototype.onBeforeShow.call(this, msg);
        this.parent.update();
    };
    /**
     * A message handler invoked on a `'before-attach'` message.
     */
    DockLayout.prototype.onBeforeAttach = function (msg) {
        _super.prototype.onBeforeAttach.call(this, msg);
        this.parent.fit();
    };
    /**
     * A message handler invoked on a `'child-shown'` message.
     */
    DockLayout.prototype.onChildShown = function (msg) {
        this.parent.fit();
    };
    /**
     * A message handler invoked on a `'child-hidden'` message.
     */
    DockLayout.prototype.onChildHidden = function (msg) {
        this.parent.fit();
    };
    /**
     * A message handler invoked on a `'resize'` message.
     */
    DockLayout.prototype.onResize = function (msg) {
        if (this.parent.isVisible) {
            this._update(msg.width, msg.height);
        }
    };
    /**
     * A message handler invoked on an `'update-request'` message.
     */
    DockLayout.prototype.onUpdateRequest = function (msg) {
        if (this.parent.isVisible) {
            this._update(-1, -1);
        }
    };
    /**
     * A message handler invoked on a `'fit-request'` message.
     */
    DockLayout.prototype.onFitRequest = function (msg) {
        if (this.parent.isAttached) {
            this._fit();
        }
    };
    /**
     * Remove the specified widget from the layout structure.
     *
     * #### Notes
     * This is a no-op if the widget is not in the layout tree.
     *
     * This does not detach the widget from the parent node.
     */
    DockLayout.prototype._removeWidget = function (widget) {
        // Bail early if there is no layout root.
        if (!this._root) {
            return;
        }
        // Find the tab node which contains the given widget.
        var tabNode = this._root.findTabNode(widget);
        // Bail early if the tab node is not found.
        if (!tabNode) {
            return;
        }
        // If there are multiple tabs, just remove the widget's tab.
        if (tabNode.tabBar.titles.length > 1) {
            tabNode.tabBar.removeTab(widget.title);
            return;
        }
        // Otherwise, the tab node needs to be removed...
        // Dispose the tab bar.
        tabNode.tabBar.dispose();
        // Handle the case where the tab node is the root.
        if (this._root === tabNode) {
            this._root = null;
            return;
        }
        // Otherwise, remove the tab node from its parent...
        // Prevent widget resizing unless needed.
        this._root.holdAllSizes();
        // Clear the parent reference on the tab node.
        var splitNode = tabNode.parent;
        tabNode.parent = null;
        // Remove the tab node from its parent split node.
        var i = algorithm_1.ArrayExt.removeFirstOf(splitNode.children, tabNode);
        var handle = algorithm_1.ArrayExt.removeAt(splitNode.handles, i);
        algorithm_1.ArrayExt.removeAt(splitNode.sizers, i);
        // Remove the handle from its parent DOM node.
        if (handle.parentNode) {
            handle.parentNode.removeChild(handle);
        }
        // If there are multiple children, just update the handles.
        if (splitNode.children.length > 1) {
            splitNode.syncHandles();
            return;
        }
        // Otherwise, the split node also needs to be removed...
        // Clear the parent reference on the split node.
        var maybeParent = splitNode.parent;
        splitNode.parent = null;
        // Lookup the remaining child node and handle.
        var childNode = splitNode.children[0];
        var childHandle = splitNode.handles[0];
        // Clear the split node data.
        splitNode.children.length = 0;
        splitNode.handles.length = 0;
        splitNode.sizers.length = 0;
        // Remove the child handle from its parent node.
        if (childHandle.parentNode) {
            childHandle.parentNode.removeChild(childHandle);
        }
        // Handle the case where the split node is the root.
        if (this._root === splitNode) {
            childNode.parent = null;
            this._root = childNode;
            return;
        }
        // Otherwise, move the child node to the parent node...
        var parentNode = maybeParent;
        // Lookup the index of the split node.
        var j = parentNode.children.indexOf(splitNode);
        // Handle the case where the child node is a tab node.
        if (childNode instanceof Private.TabLayoutNode) {
            childNode.parent = parentNode;
            parentNode.children[j] = childNode;
            return;
        }
        // Remove the split data from the parent.
        var splitHandle = algorithm_1.ArrayExt.removeAt(parentNode.handles, j);
        algorithm_1.ArrayExt.removeAt(parentNode.children, j);
        algorithm_1.ArrayExt.removeAt(parentNode.sizers, j);
        // Remove the handle from its parent node.
        if (splitHandle.parentNode) {
            splitHandle.parentNode.removeChild(splitHandle);
        }
        // The child node and the split parent node will have the same
        // orientation. Merge the grand-children with the parent node.
        for (var i_1 = 0, n = childNode.children.length; i_1 < n; ++i_1) {
            var gChild = childNode.children[i_1];
            var gHandle = childNode.handles[i_1];
            var gSizer = childNode.sizers[i_1];
            algorithm_1.ArrayExt.insert(parentNode.children, j + i_1, gChild);
            algorithm_1.ArrayExt.insert(parentNode.handles, j + i_1, gHandle);
            algorithm_1.ArrayExt.insert(parentNode.sizers, j + i_1, gSizer);
            gChild.parent = parentNode;
        }
        // Clear the child node.
        childNode.children.length = 0;
        childNode.handles.length = 0;
        childNode.sizers.length = 0;
        childNode.parent = null;
        // Sync the handles on the parent node.
        parentNode.syncHandles();
    };
    /**
     * Insert a widget next to an existing tab.
     *
     * #### Notes
     * This does not attach the widget to the parent widget.
     */
    DockLayout.prototype._insertTab = function (widget, ref, refNode, after) {
        // Do nothing if the tab is inserted next to itself.
        if (widget === ref) {
            return;
        }
        // Create the root if it does not exist.
        if (!this._root) {
            var tabNode = new Private.TabLayoutNode(this._createTabBar());
            tabNode.tabBar.addTab(widget.title);
            this._root = tabNode;
            return;
        }
        // Use the first tab node as the ref node if needed.
        if (!refNode) {
            refNode = this._root.findFirstTabNode();
        }
        // If the widget is not contained in the ref node, ensure it is
        // removed from the layout and hidden before being added again.
        if (refNode.tabBar.titles.indexOf(widget.title) === -1) {
            this._removeWidget(widget);
            widget.hide();
        }
        // Lookup the target index for inserting the tab.
        var index;
        if (ref) {
            index = refNode.tabBar.titles.indexOf(ref.title);
        }
        else {
            index = refNode.tabBar.currentIndex;
        }
        // Insert the widget's tab relative to the target index.
        refNode.tabBar.insertTab(index + (after ? 1 : 0), widget.title);
    };
    /**
     * Insert a widget as a new split area.
     *
     * #### Notes
     * This does not attach the widget to the parent widget.
     */
    DockLayout.prototype._insertSplit = function (widget, ref, refNode, orientation, after) {
        // Do nothing if there is no effective split.
        if (widget === ref && refNode && refNode.tabBar.titles.length === 1) {
            return;
        }
        // Ensure the widget is removed from the current layout.
        this._removeWidget(widget);
        // Create the tab layout node to hold the widget.
        var tabNode = new Private.TabLayoutNode(this._createTabBar());
        tabNode.tabBar.addTab(widget.title);
        // Set the root if it does not exist.
        if (!this._root) {
            this._root = tabNode;
            return;
        }
        // If the ref node parent is null, split the root.
        if (!refNode || !refNode.parent) {
            // Ensure the root is split with the correct orientation.
            var root = this._splitRoot(orientation);
            // Determine the insert index for the new tab node.
            var i_2 = after ? root.children.length : 0;
            // Normalize the split node.
            root.normalizeSizes();
            // Create the sizer for new tab node.
            var sizer = Private.createSizer(refNode ? 1 : Private.GOLDEN_RATIO);
            // Insert the tab node sized to the golden ratio.
            algorithm_1.ArrayExt.insert(root.children, i_2, tabNode);
            algorithm_1.ArrayExt.insert(root.sizers, i_2, sizer);
            algorithm_1.ArrayExt.insert(root.handles, i_2, this._createHandle());
            tabNode.parent = root;
            // Re-normalize the split node to maintain the ratios.
            root.normalizeSizes();
            // Finally, synchronize the visibility of the handles.
            root.syncHandles();
            return;
        }
        // Lookup the split node for the ref widget.
        var splitNode = refNode.parent;
        // If the split node already had the correct orientation,
        // the widget can be inserted into the split node directly.
        if (splitNode.orientation === orientation) {
            // Find the index of the ref node.
            var i_3 = splitNode.children.indexOf(refNode);
            // Normalize the split node.
            splitNode.normalizeSizes();
            // Consume half the space for the insert location.
            var s = splitNode.sizers[i_3].sizeHint /= 2;
            // Insert the tab node sized to the other half.
            var j_1 = i_3 + (after ? 1 : 0);
            algorithm_1.ArrayExt.insert(splitNode.children, j_1, tabNode);
            algorithm_1.ArrayExt.insert(splitNode.sizers, j_1, Private.createSizer(s));
            algorithm_1.ArrayExt.insert(splitNode.handles, j_1, this._createHandle());
            tabNode.parent = splitNode;
            // Finally, synchronize the visibility of the handles.
            splitNode.syncHandles();
            return;
        }
        // Remove the ref node from the split node.
        var i = algorithm_1.ArrayExt.removeFirstOf(splitNode.children, refNode);
        // Create a new normalized split node for the children.
        var childNode = new Private.SplitLayoutNode(orientation);
        childNode.normalized = true;
        // Add the ref node sized to half the space.
        childNode.children.push(refNode);
        childNode.sizers.push(Private.createSizer(0.5));
        childNode.handles.push(this._createHandle());
        refNode.parent = childNode;
        // Add the tab node sized to the other half.
        var j = after ? 1 : 0;
        algorithm_1.ArrayExt.insert(childNode.children, j, tabNode);
        algorithm_1.ArrayExt.insert(childNode.sizers, j, Private.createSizer(0.5));
        algorithm_1.ArrayExt.insert(childNode.handles, j, this._createHandle());
        tabNode.parent = childNode;
        // Synchronize the visibility of the handles.
        childNode.syncHandles();
        // Finally, add the new child node to the original split node.
        algorithm_1.ArrayExt.insert(splitNode.children, i, childNode);
        childNode.parent = splitNode;
    };
    /**
     * Ensure the root is a split node with the given orientation.
     */
    DockLayout.prototype._splitRoot = function (orientation) {
        // Bail early if the root already meets the requirements.
        var oldRoot = this._root;
        if (oldRoot instanceof Private.SplitLayoutNode) {
            if (oldRoot.orientation === orientation) {
                return oldRoot;
            }
        }
        // Create a new root node with the specified orientation.
        var newRoot = this._root = new Private.SplitLayoutNode(orientation);
        // Add the old root to the new root.
        if (oldRoot) {
            newRoot.children.push(oldRoot);
            newRoot.sizers.push(Private.createSizer(0));
            newRoot.handles.push(this._createHandle());
            oldRoot.parent = newRoot;
        }
        // Return the new root as a convenience.
        return newRoot;
    };
    /**
     * Fit the layout to the total size required by the widgets.
     */
    DockLayout.prototype._fit = function () {
        // Set up the computed minimum size.
        var minW = 0;
        var minH = 0;
        // Update the size limits for the layout tree.
        if (this._root) {
            var limits = this._root.fit(this._spacing, this._items);
            minW = limits.minWidth;
            minH = limits.minHeight;
        }
        // Update the box sizing and add it to the computed min size.
        var box = this._box = domutils_1.ElementExt.boxSizing(this.parent.node);
        minW += box.horizontalSum;
        minH += box.verticalSum;
        // Update the parent's min size constraints.
        var style = this.parent.node.style;
        style.minWidth = minW + "px";
        style.minHeight = minH + "px";
        // Set the dirty flag to ensure only a single update occurs.
        this._dirty = true;
        // Notify the ancestor that it should fit immediately. This may
        // cause a resize of the parent, fulfilling the required update.
        if (this.parent.parent) {
            messaging_1.MessageLoop.sendMessage(this.parent.parent, widget_1.Widget.Msg.FitRequest);
        }
        // If the dirty flag is still set, the parent was not resized.
        // Trigger the required update on the parent widget immediately.
        if (this._dirty) {
            messaging_1.MessageLoop.sendMessage(this.parent, widget_1.Widget.Msg.UpdateRequest);
        }
    };
    /**
     * Update the layout position and size of the widgets.
     *
     * The parent offset dimensions should be `-1` if unknown.
     */
    DockLayout.prototype._update = function (offsetWidth, offsetHeight) {
        // Clear the dirty flag to indicate the update occurred.
        this._dirty = false;
        // Bail early if there is no root layout node.
        if (!this._root) {
            return;
        }
        // Measure the parent if the offset dimensions are unknown.
        if (offsetWidth < 0) {
            offsetWidth = this.parent.node.offsetWidth;
        }
        if (offsetHeight < 0) {
            offsetHeight = this.parent.node.offsetHeight;
        }
        // Ensure the parent box sizing data is computed.
        if (!this._box) {
            this._box = domutils_1.ElementExt.boxSizing(this.parent.node);
        }
        // Compute the actual layout bounds adjusted for border and padding.
        var x = this._box.paddingTop;
        var y = this._box.paddingLeft;
        var width = offsetWidth - this._box.horizontalSum;
        var height = offsetHeight - this._box.verticalSum;
        // Update the geometry of the layout tree.
        this._root.update(x, y, width, height, this._spacing, this._items);
    };
    /**
     * Create a new tab bar for use by the dock layout.
     *
     * #### Notes
     * The tab bar will be attached to the parent if it exists.
     */
    DockLayout.prototype._createTabBar = function () {
        // Create the tab bar using the renderer.
        var tabBar = this.renderer.createTabBar();
        // Enforce necessary tab bar behavior.
        tabBar.orientation = 'horizontal';
        // Reparent and attach the tab bar to the parent if possible.
        if (this.parent) {
            tabBar.parent = this.parent;
            this.attachWidget(tabBar);
        }
        // Return the initialized tab bar.
        return tabBar;
    };
    /**
     * Create a new handle for the dock layout.
     *
     * #### Notes
     * The handle will be attached to the parent if it exists.
     */
    DockLayout.prototype._createHandle = function () {
        // Create the handle using the renderer.
        var handle = this.renderer.createHandle();
        // Initialize the handle layout behavior.
        var style = handle.style;
        style.position = 'absolute';
        style.top = '0';
        style.left = '0';
        style.width = '0';
        style.height = '0';
        // Attach the handle to the parent if it exists.
        if (this.parent) {
            this.parent.node.appendChild(handle);
        }
        // Return the initialized handle.
        return handle;
    };
    return DockLayout;
}(layout_1.Layout));
exports.DockLayout = DockLayout;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * A fraction used for sizing root panels; ~= `1 / golden_ratio`.
     */
    Private.GOLDEN_RATIO = 0.618;
    /**
     * Clamp a spacing value to an integer >= 0.
     */
    function clampSpacing(value) {
        return Math.max(0, Math.floor(value));
    }
    Private.clampSpacing = clampSpacing;
    /**
     * Create a box sizer with an initial size hint.
     */
    function createSizer(hint) {
        var sizer = new boxengine_1.BoxSizer();
        sizer.sizeHint = hint;
        sizer.size = hint;
        return sizer;
    }
    Private.createSizer = createSizer;
    /**
     * Normalize an area config object and collect the visited widgets.
     */
    function normalizeAreaConfig(config, widgetSet) {
        var result;
        if (config.type === 'tab-area') {
            result = normalizeTabAreaConfig(config, widgetSet);
        }
        else {
            result = normalizeSplitAreaConfig(config, widgetSet);
        }
        return result;
    }
    Private.normalizeAreaConfig = normalizeAreaConfig;
    /**
     * Convert a normalized area config into a layout tree.
     */
    function realizeAreaConfig(config, renderer) {
        var node;
        if (config.type === 'tab-area') {
            node = realizeTabAreaConfig(config, renderer);
        }
        else {
            node = realizeSplitAreaConfig(config, renderer);
        }
        return node;
    }
    Private.realizeAreaConfig = realizeAreaConfig;
    /**
     * A layout node which holds the data for a tabbed area.
     */
    var TabLayoutNode = (function () {
        /**
         * Construct a new tab layout node.
         *
         * @param tabBar - The tab bar to use for the layout node.
         */
        function TabLayoutNode(tabBar) {
            /**
             * The parent of the layout node.
             */
            this.parent = null;
            this._top = 0;
            this._left = 0;
            this._width = 0;
            this._height = 0;
            var tabSizer = new boxengine_1.BoxSizer();
            var widgetSizer = new boxengine_1.BoxSizer();
            tabSizer.stretch = 0;
            widgetSizer.stretch = 1;
            this.tabBar = tabBar;
            this.sizers = [tabSizer, widgetSizer];
        }
        Object.defineProperty(TabLayoutNode.prototype, "top", {
            /**
             * The most recent value for the `top` edge of the layout box.
             */
            get: function () {
                return this._top;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TabLayoutNode.prototype, "left", {
            /**
             * The most recent value for the `left` edge of the layout box.
             */
            get: function () {
                return this._left;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TabLayoutNode.prototype, "width", {
            /**
             * The most recent value for the `width` of the layout box.
             */
            get: function () {
                return this._width;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TabLayoutNode.prototype, "height", {
            /**
             * The most recent value for the `height` of the layout box.
             */
            get: function () {
                return this._height;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Create an iterator for all widgets in the layout tree.
         */
        TabLayoutNode.prototype.iterAllWidgets = function () {
            return algorithm_1.chain(algorithm_1.once(this.tabBar), this.iterUserWidgets());
        };
        /**
         * Create an iterator for the user widgets in the layout tree.
         */
        TabLayoutNode.prototype.iterUserWidgets = function () {
            return algorithm_1.map(this.tabBar.titles, function (title) { return title.owner; });
        };
        /**
         * Create an iterator for the selected widgets in the layout tree.
         */
        TabLayoutNode.prototype.iterSelectedWidgets = function () {
            var title = this.tabBar.currentTitle;
            return title ? algorithm_1.once(title.owner) : algorithm_1.empty();
        };
        /**
         * Create an iterator for the tab bars in the layout tree.
         */
        TabLayoutNode.prototype.iterTabBars = function () {
            return algorithm_1.once(this.tabBar);
        };
        /**
         * Create an iterator for the handles in the layout tree.
         */
        TabLayoutNode.prototype.iterHandles = function () {
            return algorithm_1.empty();
        };
        /**
         * Find the tab layout node which contains the given widget.
         */
        TabLayoutNode.prototype.findTabNode = function (widget) {
            return this.tabBar.titles.indexOf(widget.title) !== -1 ? this : null;
        };
        /**
         * Find the split layout node which contains the given handle.
         */
        TabLayoutNode.prototype.findSplitNode = function (handle) {
            return null;
        };
        /**
         * Find the first tab layout node in a layout tree.
         */
        TabLayoutNode.prototype.findFirstTabNode = function () {
            return this;
        };
        /**
         * Find the tab layout node which contains the local point.
         */
        TabLayoutNode.prototype.hitTestTabNodes = function (x, y) {
            if (x < this._left || x >= this._left + this._width) {
                return null;
            }
            if (y < this._top || y >= this._top + this._height) {
                return null;
            }
            return this;
        };
        /**
         * Create a configuration object for the layout tree.
         */
        TabLayoutNode.prototype.createConfig = function () {
            var widgets = this.tabBar.titles.map(function (title) { return title.owner; });
            var currentIndex = this.tabBar.currentIndex;
            return { type: 'tab-area', widgets: widgets, currentIndex: currentIndex };
        };
        /**
         * Recursively hold all of the sizes in the layout tree.
         *
         * This ignores the sizers of tab layout nodes.
         */
        TabLayoutNode.prototype.holdAllSizes = function () {
            return;
        };
        /**
         * Fit the layout tree.
         */
        TabLayoutNode.prototype.fit = function (spacing, items) {
            // Set up the limit variables.
            var minWidth = 0;
            var minHeight = 0;
            var maxWidth = Infinity;
            var maxHeight = Infinity;
            // Lookup the tab bar layout item.
            var tabBarItem = items.get(this.tabBar);
            // Lookup the widget layout item.
            var current = this.tabBar.currentTitle;
            var widgetItem = current ? items.get(current.owner) : undefined;
            // Lookup the tab bar and widget sizers.
            var _a = this.sizers, tabBarSizer = _a[0], widgetSizer = _a[1];
            // Update the tab bar limits.
            if (tabBarItem) {
                tabBarItem.fit();
            }
            // Update the widget limits.
            if (widgetItem) {
                widgetItem.fit();
            }
            // Update the results and sizer for the tab bar.
            if (tabBarItem && !tabBarItem.isHidden) {
                minWidth = Math.max(minWidth, tabBarItem.minWidth);
                minHeight += tabBarItem.minHeight;
                tabBarSizer.minSize = tabBarItem.minHeight;
                tabBarSizer.maxSize = tabBarItem.maxHeight;
            }
            else {
                tabBarSizer.minSize = 0;
                tabBarSizer.maxSize = 0;
            }
            // Update the results and sizer for the current widget.
            if (widgetItem && !widgetItem.isHidden) {
                minWidth = Math.max(minWidth, widgetItem.minWidth);
                minHeight += widgetItem.minHeight;
                widgetSizer.minSize = widgetItem.minHeight;
                widgetSizer.maxSize = Infinity;
            }
            else {
                widgetSizer.minSize = 0;
                widgetSizer.maxSize = Infinity;
            }
            // Return the computed size limits for the layout node.
            return { minWidth: minWidth, minHeight: minHeight, maxWidth: maxWidth, maxHeight: maxHeight };
        };
        /**
         * Update the layout tree.
         */
        TabLayoutNode.prototype.update = function (left, top, width, height, spacing, items) {
            // Update the layout box values.
            this._top = top;
            this._left = left;
            this._width = width;
            this._height = height;
            // Lookup the tab bar layout item.
            var tabBarItem = items.get(this.tabBar);
            // Lookup the widget layout item.
            var current = this.tabBar.currentTitle;
            var widgetItem = current ? items.get(current.owner) : undefined;
            // Distribute the layout space to the sizers.
            boxengine_1.BoxEngine.calc(this.sizers, height);
            // Update the tab bar item using the computed size.
            if (tabBarItem && !tabBarItem.isHidden) {
                var size = this.sizers[0].size;
                tabBarItem.update(left, top, width, size);
                top += size;
            }
            // Layout the widget using the computed size.
            if (widgetItem && !widgetItem.isHidden) {
                var size = this.sizers[1].size;
                widgetItem.update(left, top, width, size);
            }
        };
        return TabLayoutNode;
    }());
    Private.TabLayoutNode = TabLayoutNode;
    /**
     * A layout node which holds the data for a split area.
     */
    var SplitLayoutNode = (function () {
        /**
         * Construct a new split layout node.
         *
         * @param orientation - The orientation of the node.
         */
        function SplitLayoutNode(orientation) {
            /**
             * The parent of the layout node.
             */
            this.parent = null;
            /**
             * Whether the sizers have been normalized.
             */
            this.normalized = false;
            /**
             * The child nodes for the split node.
             */
            this.children = [];
            /**
             * The box sizers for the layout children.
             */
            this.sizers = [];
            /**
             * The handles for the layout children.
             */
            this.handles = [];
            this.orientation = orientation;
        }
        /**
         * Create an iterator for all widgets in the layout tree.
         */
        SplitLayoutNode.prototype.iterAllWidgets = function () {
            var children = algorithm_1.map(this.children, function (child) { return child.iterAllWidgets(); });
            return new algorithm_1.ChainIterator(children);
        };
        /**
         * Create an iterator for the user widgets in the layout tree.
         */
        SplitLayoutNode.prototype.iterUserWidgets = function () {
            var children = algorithm_1.map(this.children, function (child) { return child.iterUserWidgets(); });
            return new algorithm_1.ChainIterator(children);
        };
        /**
         * Create an iterator for the selected widgets in the layout tree.
         */
        SplitLayoutNode.prototype.iterSelectedWidgets = function () {
            var children = algorithm_1.map(this.children, function (child) { return child.iterSelectedWidgets(); });
            return new algorithm_1.ChainIterator(children);
        };
        /**
         * Create an iterator for the tab bars in the layout tree.
         */
        SplitLayoutNode.prototype.iterTabBars = function () {
            var children = algorithm_1.map(this.children, function (child) { return child.iterTabBars(); });
            return new algorithm_1.ChainIterator(children);
        };
        /**
         * Create an iterator for the handles in the layout tree.
         */
        SplitLayoutNode.prototype.iterHandles = function () {
            var children = algorithm_1.map(this.children, function (child) { return child.iterHandles(); });
            return algorithm_1.chain(this.handles, new algorithm_1.ChainIterator(children));
        };
        /**
         * Find the tab layout node which contains the given widget.
         */
        SplitLayoutNode.prototype.findTabNode = function (widget) {
            for (var i = 0, n = this.children.length; i < n; ++i) {
                var result = this.children[i].findTabNode(widget);
                if (result) {
                    return result;
                }
            }
            return null;
        };
        /**
         * Find the split layout node which contains the given handle.
         */
        SplitLayoutNode.prototype.findSplitNode = function (handle) {
            var index = this.handles.indexOf(handle);
            if (index !== -1) {
                return { index: index, node: this };
            }
            for (var i = 0, n = this.children.length; i < n; ++i) {
                var result = this.children[i].findSplitNode(handle);
                if (result) {
                    return result;
                }
            }
            return null;
        };
        /**
         * Find the first tab layout node in a layout tree.
         */
        SplitLayoutNode.prototype.findFirstTabNode = function () {
            if (this.children.length === 0) {
                return null;
            }
            return this.children[0].findFirstTabNode();
        };
        /**
         * Find the tab layout node which contains the local point.
         */
        SplitLayoutNode.prototype.hitTestTabNodes = function (x, y) {
            for (var i = 0, n = this.children.length; i < n; ++i) {
                var result = this.children[i].hitTestTabNodes(x, y);
                if (result) {
                    return result;
                }
            }
            return null;
        };
        /**
         * Create a configuration object for the layout tree.
         */
        SplitLayoutNode.prototype.createConfig = function () {
            var orientation = this.orientation;
            var sizes = this.createNormalizedSizes();
            var children = this.children.map(function (child) { return child.createConfig(); });
            return { type: 'split-area', orientation: orientation, children: children, sizes: sizes };
        };
        /**
         * Sync the visibility and orientation of the handles.
         */
        SplitLayoutNode.prototype.syncHandles = function () {
            var _this = this;
            algorithm_1.each(this.handles, function (handle, i) {
                handle.setAttribute('data-orientation', _this.orientation);
                if (i === _this.handles.length - 1) {
                    handle.classList.add('p-mod-hidden');
                }
                else {
                    handle.classList.remove('p-mod-hidden');
                }
            });
        };
        /**
         * Hold the current sizes of the box sizers.
         *
         * This sets the size hint of each sizer to its current size.
         */
        SplitLayoutNode.prototype.holdSizes = function () {
            algorithm_1.each(this.sizers, function (sizer) { sizer.sizeHint = sizer.size; });
        };
        /**
         * Recursively hold all of the sizes in the layout tree.
         *
         * This ignores the sizers of tab layout nodes.
         */
        SplitLayoutNode.prototype.holdAllSizes = function () {
            algorithm_1.each(this.children, function (child) { return child.holdAllSizes(); });
            this.holdSizes();
        };
        /**
         * Normalize the sizes of the split layout node.
         */
        SplitLayoutNode.prototype.normalizeSizes = function () {
            // Bail early if the sizers are empty.
            var n = this.sizers.length;
            if (n === 0) {
                return;
            }
            // Hold the current sizes of the sizers.
            this.holdSizes();
            // Compute the sum of the sizes.
            var sum = algorithm_1.reduce(this.sizers, function (v, sizer) { return v + sizer.sizeHint; }, 0);
            // Normalize the sizes based on the sum.
            if (sum === 0) {
                algorithm_1.each(this.sizers, function (sizer) {
                    sizer.size = sizer.sizeHint = 1 / n;
                });
            }
            else {
                algorithm_1.each(this.sizers, function (sizer) {
                    sizer.size = sizer.sizeHint /= sum;
                });
            }
            // Mark the sizes as normalized.
            this.normalized = true;
        };
        /**
         * Snap the normalized sizes of the split layout node.
         */
        SplitLayoutNode.prototype.createNormalizedSizes = function () {
            // Bail early if the sizers are empty.
            var n = this.sizers.length;
            if (n === 0) {
                return [];
            }
            // Grab the current sizes of the sizers.
            var sizes = this.sizers.map(function (sizer) { return sizer.size; });
            // Compute the sum of the sizes.
            var sum = algorithm_1.reduce(sizes, function (v, size) { return v + size; }, 0);
            // Normalize the sizes based on the sum.
            if (sum === 0) {
                algorithm_1.each(sizes, function (size, i) { sizes[i] = 1 / n; });
            }
            else {
                algorithm_1.each(sizes, function (size, i) { sizes[i] = size / sum; });
            }
            // Return the normalized sizes.
            return sizes;
        };
        /**
         * Fit the layout tree.
         */
        SplitLayoutNode.prototype.fit = function (spacing, items) {
            // Compute the required fixed space.
            var horizontal = this.orientation === 'horizontal';
            var fixed = Math.max(0, this.children.length - 1) * spacing;
            // Set up the limit variables.
            var minWidth = horizontal ? fixed : 0;
            var minHeight = horizontal ? 0 : fixed;
            var maxWidth = Infinity;
            var maxHeight = Infinity;
            // Fit the children and update the limits.
            for (var i = 0, n = this.children.length; i < n; ++i) {
                var limits = this.children[i].fit(spacing, items);
                if (horizontal) {
                    minHeight = Math.max(minHeight, limits.minHeight);
                    minWidth += limits.minWidth;
                    this.sizers[i].minSize = limits.minWidth;
                }
                else {
                    minWidth = Math.max(minWidth, limits.minWidth);
                    minHeight += limits.minHeight;
                    this.sizers[i].minSize = limits.minHeight;
                }
            }
            // Return the computed limits for the layout node.
            return { minWidth: minWidth, minHeight: minHeight, maxWidth: maxWidth, maxHeight: maxHeight };
        };
        /**
         * Update the layout tree.
         */
        SplitLayoutNode.prototype.update = function (left, top, width, height, spacing, items) {
            // Compute the available layout space.
            var horizontal = this.orientation === 'horizontal';
            var fixed = Math.max(0, this.children.length - 1) * spacing;
            var space = Math.max(0, (horizontal ? width : height) - fixed);
            // De-normalize the sizes if needed.
            if (this.normalized) {
                algorithm_1.each(this.sizers, function (sizer) { sizer.sizeHint *= space; });
                this.normalized = false;
            }
            // Distribute the layout space to the sizers.
            boxengine_1.BoxEngine.calc(this.sizers, space);
            // Update the geometry of the child nodes and handles.
            for (var i = 0, n = this.children.length; i < n; ++i) {
                var child = this.children[i];
                var size = this.sizers[i].size;
                var handleStyle = this.handles[i].style;
                if (horizontal) {
                    child.update(left, top, size, height, spacing, items);
                    left += size;
                    handleStyle.top = top + "px";
                    handleStyle.left = left + "px";
                    handleStyle.width = spacing + "px";
                    handleStyle.height = height + "px";
                    left += spacing;
                }
                else {
                    child.update(left, top, width, size, spacing, items);
                    top += size;
                    handleStyle.top = top + "px";
                    handleStyle.left = left + "px";
                    handleStyle.width = width + "px";
                    handleStyle.height = spacing + "px";
                    top += spacing;
                }
            }
        };
        return SplitLayoutNode;
    }());
    Private.SplitLayoutNode = SplitLayoutNode;
    /**
     * Normalize a tab area config and collect the visited widgets.
     */
    function normalizeTabAreaConfig(config, widgetSet) {
        // Bail early if there is no content.
        if (config.widgets.length === 0) {
            return null;
        }
        // Setup the filtered widgets array.
        var widgets = [];
        // Filter the config for unique widgets.
        algorithm_1.each(config.widgets, function (widget) {
            if (!widgetSet.has(widget)) {
                widgetSet.add(widget);
                widgets.push(widget);
            }
        });
        // Bail if there are no effective widgets.
        if (widgets.length === 0) {
            return null;
        }
        // Normalize the current index.
        var index = config.currentIndex;
        if (index !== -1 && (index < 0 || index >= widgets.length)) {
            index = 0;
        }
        // Return a normalized config object.
        return { type: 'tab-area', widgets: widgets, currentIndex: index };
    }
    /**
     * Normalize a split area config and collect the visited widgets.
     */
    function normalizeSplitAreaConfig(config, widgetSet) {
        // Set up the result variables.
        var orientation = config.orientation;
        var children = [];
        var sizes = [];
        // Normalize the config children.
        for (var i = 0, n = config.children.length; i < n; ++i) {
            // Normalize the child config.
            var child = normalizeAreaConfig(config.children[i], widgetSet);
            // Ignore an empty child.
            if (!child) {
                continue;
            }
            // Add the child or hoist its content as appropriate.
            if (child.type === 'tab-area' || child.orientation !== orientation) {
                children.push(child);
                sizes.push(Math.abs(config.sizes[i] || 0));
            }
            else {
                children.push.apply(children, child.children);
                sizes.push.apply(sizes, child.sizes);
            }
        }
        // Bail if there are no effective children.
        if (children.length === 0) {
            return null;
        }
        // If there is only one effective child, return that child.
        if (children.length === 1) {
            return children[0];
        }
        // Return a normalized config object.
        return { type: 'split-area', orientation: orientation, children: children, sizes: sizes };
    }
    /**
     * Convert a normalized tab area config into a layout tree.
     */
    function realizeTabAreaConfig(config, renderer) {
        // Create the tab bar for the layout node.
        var tabBar = renderer.createTabBar();
        // Hide each widget and add it to the tab bar.
        algorithm_1.each(config.widgets, function (widget) {
            widget.hide();
            tabBar.addTab(widget.title);
        });
        // Set the current index of the tab bar.
        tabBar.currentIndex = config.currentIndex;
        // Return the new tab layout node.
        return new TabLayoutNode(tabBar);
    }
    /**
     * Convert a normalized split area config into a layout tree.
     */
    function realizeSplitAreaConfig(config, renderer) {
        // Create the split layout node.
        var node = new SplitLayoutNode(config.orientation);
        // Add each child to the layout node.
        algorithm_1.each(config.children, function (child, i) {
            // Create the child data for the layout node.
            var childNode = realizeAreaConfig(child, renderer);
            var sizer = createSizer(config.sizes[i]);
            var handle = renderer.createHandle();
            // Add the child data to the layout node.
            node.children.push(childNode);
            node.handles.push(handle);
            node.sizers.push(sizer);
            // Update the parent for the child node.
            childNode.parent = node;
        });
        // Synchronize the handle state for the layout node.
        node.syncHandles();
        // Normalize the sizes for the layout node.
        node.normalizeSizes();
        // Return the new layout node.
        return node;
    }
})(Private || (Private = {}));


/***/ }),

/***/ "Y3PQ":
/*!*********************************************************************!*\
  !*** ./node_modules/draft-js/lib/DraftEditorContents-core.react.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DraftEditorContents-core.react
 * @format
 * 
 */



var _assign = __webpack_require__(/*! object-assign */ "MgzW");

var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var DraftEditorBlock = __webpack_require__(/*! ./DraftEditorBlock.react */ "DthY");
var DraftOffsetKey = __webpack_require__(/*! ./DraftOffsetKey */ "Iq8E");
var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");
var React = __webpack_require__(/*! react */ "q1tI");

var cx = __webpack_require__(/*! fbjs/lib/cx */ "YVIB");
var joinClasses = __webpack_require__(/*! fbjs/lib/joinClasses */ "faBS");
var nullthrows = __webpack_require__(/*! fbjs/lib/nullthrows */ "gWRK");

/**
 * Provide default styling for list items. This way, lists will be styled with
 * proper counters and indentation even if the caller does not specify
 * their own styling at all. If more than five levels of nesting are needed,
 * the necessary CSS classes can be provided via `blockStyleFn` configuration.
 */
var getListItemClasses = function getListItemClasses(type, depth, shouldResetCount, direction) {
  return cx({
    'public/DraftStyleDefault/unorderedListItem': type === 'unordered-list-item',
    'public/DraftStyleDefault/orderedListItem': type === 'ordered-list-item',
    'public/DraftStyleDefault/reset': shouldResetCount,
    'public/DraftStyleDefault/depth0': depth === 0,
    'public/DraftStyleDefault/depth1': depth === 1,
    'public/DraftStyleDefault/depth2': depth === 2,
    'public/DraftStyleDefault/depth3': depth === 3,
    'public/DraftStyleDefault/depth4': depth === 4,
    'public/DraftStyleDefault/listLTR': direction === 'LTR',
    'public/DraftStyleDefault/listRTL': direction === 'RTL'
  });
};

/**
 * `DraftEditorContents` is the container component for all block components
 * rendered for a `DraftEditor`. It is optimized to aggressively avoid
 * re-rendering blocks whenever possible.
 *
 * This component is separate from `DraftEditor` because certain props
 * (for instance, ARIA props) must be allowed to update without affecting
 * the contents of the editor.
 */

var DraftEditorContents = function (_React$Component) {
  _inherits(DraftEditorContents, _React$Component);

  function DraftEditorContents() {
    _classCallCheck(this, DraftEditorContents);

    return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
  }

  DraftEditorContents.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
    var prevEditorState = this.props.editorState;
    var nextEditorState = nextProps.editorState;

    var prevDirectionMap = prevEditorState.getDirectionMap();
    var nextDirectionMap = nextEditorState.getDirectionMap();

    // Text direction has changed for one or more blocks. We must re-render.
    if (prevDirectionMap !== nextDirectionMap) {
      return true;
    }

    var didHaveFocus = prevEditorState.getSelection().getHasFocus();
    var nowHasFocus = nextEditorState.getSelection().getHasFocus();

    if (didHaveFocus !== nowHasFocus) {
      return true;
    }

    var nextNativeContent = nextEditorState.getNativelyRenderedContent();

    var wasComposing = prevEditorState.isInCompositionMode();
    var nowComposing = nextEditorState.isInCompositionMode();

    // If the state is unchanged or we're currently rendering a natively
    // rendered state, there's nothing new to be done.
    if (prevEditorState === nextEditorState || nextNativeContent !== null && nextEditorState.getCurrentContent() === nextNativeContent || wasComposing && nowComposing) {
      return false;
    }

    var prevContent = prevEditorState.getCurrentContent();
    var nextContent = nextEditorState.getCurrentContent();
    var prevDecorator = prevEditorState.getDecorator();
    var nextDecorator = nextEditorState.getDecorator();
    return wasComposing !== nowComposing || prevContent !== nextContent || prevDecorator !== nextDecorator || nextEditorState.mustForceSelection();
  };

  DraftEditorContents.prototype.render = function render() {
    var _props = this.props,
        blockRenderMap = _props.blockRenderMap,
        blockRendererFn = _props.blockRendererFn,
        blockStyleFn = _props.blockStyleFn,
        customStyleMap = _props.customStyleMap,
        customStyleFn = _props.customStyleFn,
        editorState = _props.editorState,
        editorKey = _props.editorKey,
        textDirectionality = _props.textDirectionality;


    var content = editorState.getCurrentContent();
    var selection = editorState.getSelection();
    var forceSelection = editorState.mustForceSelection();
    var decorator = editorState.getDecorator();
    var directionMap = nullthrows(editorState.getDirectionMap());

    var blocksAsArray = content.getBlocksAsArray();
    var processedBlocks = [];

    var currentDepth = null;
    var lastWrapperTemplate = null;

    for (var ii = 0; ii < blocksAsArray.length; ii++) {
      var _block = blocksAsArray[ii];
      var key = _block.getKey();
      var blockType = _block.getType();

      var customRenderer = blockRendererFn(_block);
      var CustomComponent = void 0,
          customProps = void 0,
          customEditable = void 0;
      if (customRenderer) {
        CustomComponent = customRenderer.component;
        customProps = customRenderer.props;
        customEditable = customRenderer.editable;
      }

      var direction = textDirectionality ? textDirectionality : directionMap.get(key);
      var offsetKey = DraftOffsetKey.encode(key, 0, 0);
      var componentProps = {
        contentState: content,
        block: _block,
        blockProps: customProps,
        blockStyleFn: blockStyleFn,
        customStyleMap: customStyleMap,
        customStyleFn: customStyleFn,
        decorator: decorator,
        direction: direction,
        forceSelection: forceSelection,
        key: key,
        offsetKey: offsetKey,
        selection: selection,
        tree: editorState.getBlockTree(key)
      };

      var configForType = blockRenderMap.get(blockType) || blockRenderMap.get('unstyled');
      var wrapperTemplate = configForType.wrapper;

      var Element = configForType.element || blockRenderMap.get('unstyled').element;

      var depth = _block.getDepth();
      var className = '';
      if (blockStyleFn) {
        className = blockStyleFn(_block);
      }

      // List items are special snowflakes, since we handle nesting and
      // counters manually.
      if (Element === 'li') {
        var shouldResetCount = lastWrapperTemplate !== wrapperTemplate || currentDepth === null || depth > currentDepth;
        className = joinClasses(className, getListItemClasses(blockType, depth, shouldResetCount, direction));
      }

      var Component = CustomComponent || DraftEditorBlock;
      var childProps = {
        className: className,
        'data-block': true,
        'data-editor': editorKey,
        'data-offset-key': offsetKey,
        key: key
      };
      if (customEditable !== undefined) {
        childProps = _extends({}, childProps, {
          contentEditable: customEditable,
          suppressContentEditableWarning: true
        });
      }

      var child = React.createElement(Element, childProps, React.createElement(Component, componentProps));

      processedBlocks.push({
        block: child,
        wrapperTemplate: wrapperTemplate,
        key: key,
        offsetKey: offsetKey
      });

      if (wrapperTemplate) {
        currentDepth = _block.getDepth();
      } else {
        currentDepth = null;
      }
      lastWrapperTemplate = wrapperTemplate;
    }

    // Group contiguous runs of blocks that have the same wrapperTemplate
    var outputBlocks = [];
    for (var _ii = 0; _ii < processedBlocks.length;) {
      var info = processedBlocks[_ii];
      if (info.wrapperTemplate) {
        var blocks = [];
        do {
          blocks.push(processedBlocks[_ii].block);
          _ii++;
        } while (_ii < processedBlocks.length && processedBlocks[_ii].wrapperTemplate === info.wrapperTemplate);
        var wrapperElement = React.cloneElement(info.wrapperTemplate, {
          key: info.key + '-wrap',
          'data-offset-key': info.offsetKey
        }, blocks);
        outputBlocks.push(wrapperElement);
      } else {
        outputBlocks.push(info.block);
        _ii++;
      }
    }

    return React.createElement(
      'div',
      { 'data-contents': 'true' },
      outputBlocks
    );
  };

  return DraftEditorContents;
}(React.Component);

module.exports = DraftEditorContents;

/***/ }),

/***/ "Y6Sv":
/*!*****************************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/markdownviewer-extension/style/index.css ***!
  \*****************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n:root {\n  --jp-private-markdownviewer-padding: 32px;\n}\n\n.jp-Document .jp-MimeDocument .jp-RenderedMarkdown {\n  padding-top: var(--jp-private-markdownviewer-padding);\n  padding-right: var(--jp-private-markdownviewer-padding);\n  padding-bottom: var(--jp-private-markdownviewer-padding);\n  padding-left: var(--jp-private-markdownviewer-padding);\n  overflow: auto;\n}\n\n/*-----------------------------------------------------------------------------\n| Presentation Mode (.jp-mod-presentationMode)\n|----------------------------------------------------------------------------*/\n\n.jp-mod-presentationMode .jp-MimeDocument .jp-RenderedHTMLCommon {\n  --jp-content-font-size1: var(--jp-content-presentation-font-size1);\n  --jp-code-font-size: var(--jp-code-presentation-font-size);\n}\n", ""]);

// exports


/***/ }),

/***/ "Y7ZC":
/*!*********************************************************!*\
  !*** ./node_modules/core-js/library/modules/_export.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var global = __webpack_require__(/*! ./_global */ "5T2Y");
var core = __webpack_require__(/*! ./_core */ "WEpk");
var ctx = __webpack_require__(/*! ./_ctx */ "2GTP");
var hide = __webpack_require__(/*! ./_hide */ "NegM");
var has = __webpack_require__(/*! ./_has */ "B+OT");
var PROTOTYPE = 'prototype';

var $export = function (type, name, source) {
  var IS_FORCED = type & $export.F;
  var IS_GLOBAL = type & $export.G;
  var IS_STATIC = type & $export.S;
  var IS_PROTO = type & $export.P;
  var IS_BIND = type & $export.B;
  var IS_WRAP = type & $export.W;
  var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
  var expProto = exports[PROTOTYPE];
  var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE];
  var key, own, out;
  if (IS_GLOBAL) source = name;
  for (key in source) {
    // contains in native
    own = !IS_FORCED && target && target[key] !== undefined;
    if (own && has(exports, key)) continue;
    // export native or passed
    out = own ? target[key] : source[key];
    // prevent global pollution for namespaces
    exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
    // bind timers to global for call from export context
    : IS_BIND && own ? ctx(out, global)
    // wrap global constructors for prevent change them in library
    : IS_WRAP && target[key] == out ? (function (C) {
      var F = function (a, b, c) {
        if (this instanceof C) {
          switch (arguments.length) {
            case 0: return new C();
            case 1: return new C(a);
            case 2: return new C(a, b);
          } return new C(a, b, c);
        } return C.apply(this, arguments);
      };
      F[PROTOTYPE] = C[PROTOTYPE];
      return F;
    // make static versions for prototype methods
    })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
    // export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
    if (IS_PROTO) {
      (exports.virtual || (exports.virtual = {}))[key] = out;
      // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
      if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out);
    }
  }
};
// type bitmap
$export.F = 1;   // forced
$export.G = 2;   // global
$export.S = 4;   // static
$export.P = 8;   // proto
$export.B = 16;  // bind
$export.W = 32;  // wrap
$export.U = 64;  // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;


/***/ }),

/***/ "YAoJ":
/*!*********************************************!*\
  !*** ./node_modules/base16/lib/tomorrow.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'tomorrow',
  author: 'chris kempson (http://chriskempson.com)',
  base00: '#1d1f21',
  base01: '#282a2e',
  base02: '#373b41',
  base03: '#969896',
  base04: '#b4b7b4',
  base05: '#c5c8c6',
  base06: '#e0e0e0',
  base07: '#ffffff',
  base08: '#cc6666',
  base09: '#de935f',
  base0A: '#f0c674',
  base0B: '#b5bd68',
  base0C: '#8abeb7',
  base0D: '#81a2be',
  base0E: '#b294bb',
  base0F: '#a3685a'
};
module.exports = exports['default'];

/***/ }),

/***/ "YBdB":
/*!***************************************************!*\
  !*** ./node_modules/setimmediate/setImmediate.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) {
    "use strict";

    if (global.setImmediate) {
        return;
    }

    var nextHandle = 1; // Spec says greater than zero
    var tasksByHandle = {};
    var currentlyRunningATask = false;
    var doc = global.document;
    var registerImmediate;

    function setImmediate(callback) {
      // Callback can either be a function or a string
      if (typeof callback !== "function") {
        callback = new Function("" + callback);
      }
      // Copy function arguments
      var args = new Array(arguments.length - 1);
      for (var i = 0; i < args.length; i++) {
          args[i] = arguments[i + 1];
      }
      // Store and register the task
      var task = { callback: callback, args: args };
      tasksByHandle[nextHandle] = task;
      registerImmediate(nextHandle);
      return nextHandle++;
    }

    function clearImmediate(handle) {
        delete tasksByHandle[handle];
    }

    function run(task) {
        var callback = task.callback;
        var args = task.args;
        switch (args.length) {
        case 0:
            callback();
            break;
        case 1:
            callback(args[0]);
            break;
        case 2:
            callback(args[0], args[1]);
            break;
        case 3:
            callback(args[0], args[1], args[2]);
            break;
        default:
            callback.apply(undefined, args);
            break;
        }
    }

    function runIfPresent(handle) {
        // From the spec: "Wait until any invocations of this algorithm started before this one have completed."
        // So if we're currently running a task, we'll need to delay this invocation.
        if (currentlyRunningATask) {
            // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
            // "too much recursion" error.
            setTimeout(runIfPresent, 0, handle);
        } else {
            var task = tasksByHandle[handle];
            if (task) {
                currentlyRunningATask = true;
                try {
                    run(task);
                } finally {
                    clearImmediate(handle);
                    currentlyRunningATask = false;
                }
            }
        }
    }

    function installNextTickImplementation() {
        registerImmediate = function(handle) {
            process.nextTick(function () { runIfPresent(handle); });
        };
    }

    function canUsePostMessage() {
        // The test against `importScripts` prevents this implementation from being installed inside a web worker,
        // where `global.postMessage` means something completely different and can't be used for this purpose.
        if (global.postMessage && !global.importScripts) {
            var postMessageIsAsynchronous = true;
            var oldOnMessage = global.onmessage;
            global.onmessage = function() {
                postMessageIsAsynchronous = false;
            };
            global.postMessage("", "*");
            global.onmessage = oldOnMessage;
            return postMessageIsAsynchronous;
        }
    }

    function installPostMessageImplementation() {
        // Installs an event handler on `global` for the `message` event: see
        // * https://developer.mozilla.org/en/DOM/window.postMessage
        // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages

        var messagePrefix = "setImmediate$" + Math.random() + "$";
        var onGlobalMessage = function(event) {
            if (event.source === global &&
                typeof event.data === "string" &&
                event.data.indexOf(messagePrefix) === 0) {
                runIfPresent(+event.data.slice(messagePrefix.length));
            }
        };

        if (global.addEventListener) {
            global.addEventListener("message", onGlobalMessage, false);
        } else {
            global.attachEvent("onmessage", onGlobalMessage);
        }

        registerImmediate = function(handle) {
            global.postMessage(messagePrefix + handle, "*");
        };
    }

    function installMessageChannelImplementation() {
        var channel = new MessageChannel();
        channel.port1.onmessage = function(event) {
            var handle = event.data;
            runIfPresent(handle);
        };

        registerImmediate = function(handle) {
            channel.port2.postMessage(handle);
        };
    }

    function installReadyStateChangeImplementation() {
        var html = doc.documentElement;
        registerImmediate = function(handle) {
            // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
            // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
            var script = doc.createElement("script");
            script.onreadystatechange = function () {
                runIfPresent(handle);
                script.onreadystatechange = null;
                html.removeChild(script);
                script = null;
            };
            html.appendChild(script);
        };
    }

    function installSetTimeoutImplementation() {
        registerImmediate = function(handle) {
            setTimeout(runIfPresent, 0, handle);
        };
    }

    // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
    var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
    attachTo = attachTo && attachTo.setTimeout ? attachTo : global;

    // Don't get fooled by e.g. browserify environments.
    if ({}.toString.call(global.process) === "[object process]") {
        // For Node.js before 0.9
        installNextTickImplementation();

    } else if (canUsePostMessage()) {
        // For non-IE10 modern browsers
        installPostMessageImplementation();

    } else if (global.MessageChannel) {
        // For web workers, where supported
        installMessageChannelImplementation();

    } else if (doc && "onreadystatechange" in doc.createElement("script")) {
        // For IE 6–8
        installReadyStateChangeImplementation();

    } else {
        // For older browsers
        installSetTimeoutImplementation();
    }

    attachTo.setImmediate = setImmediate;
    attachTo.clearImmediate = clearImmediate;
}(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "yLpj"), __webpack_require__(/*! ./../process/browser.js */ "8oxB")))

/***/ }),

/***/ "YC29":
/*!*****************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/kernel/default.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const coreutils_2 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const coreutils_3 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const __1 = __webpack_require__(/*! .. */ "S9up");
const comm_1 = __webpack_require__(/*! ./comm */ "EzAi");
const messages_1 = __webpack_require__(/*! ./messages */ "Wg3t");
const future_1 = __webpack_require__(/*! ./future */ "JIKs");
const serialize = __importStar(__webpack_require__(/*! ./serialize */ "om3i"));
const validate = __importStar(__webpack_require__(/*! ./validate */ "idGr"));
/**
 * The url for the kernel service.
 */
const KERNEL_SERVICE_URL = 'api/kernels';
/**
 * The url for the kernelspec service.
 */
const KERNELSPEC_SERVICE_URL = 'api/kernelspecs';
/**
 * Implementation of the Kernel object.
 *
 * #### Notes
 * Messages from the server are handled in the order they were received and
 * asynchronously. Any message handler can return a promise, and message
 * handling will pause until the promise is fulfilled.
 */
class DefaultKernel {
    /**
     * Construct a kernel object.
     */
    constructor(options, id) {
        /**
         * Create the kernel websocket connection and add socket status handlers.
         */
        this._createSocket = () => {
            if (this.isDisposed) {
                return;
            }
            let settings = this.serverSettings;
            let partialUrl = coreutils_1.URLExt.join(settings.wsUrl, KERNEL_SERVICE_URL, encodeURIComponent(this._id));
            // Strip any authentication from the display string.
            // TODO - Audit tests for extra websockets started
            let display = partialUrl.replace(/^((?:\w+:)?\/\/)(?:[^@\/]+@)/, '$1');
            console.log('Starting WebSocket:', display);
            let url = coreutils_1.URLExt.join(partialUrl, 'channels?session_id=' + encodeURIComponent(this._clientId));
            // If token authentication is in use.
            let token = settings.token;
            if (token !== '') {
                url = url + `&token=${encodeURIComponent(token)}`;
            }
            this._connectionPromise = new coreutils_3.PromiseDelegate();
            this._wsStopped = false;
            this._ws = new settings.WebSocket(url);
            // Ensure incoming binary messages are not Blobs
            this._ws.binaryType = 'arraybuffer';
            this._ws.onmessage = this._onWSMessage;
            this._ws.onopen = this._onWSOpen;
            this._ws.onclose = this._onWSClose;
            this._ws.onerror = this._onWSClose;
        };
        /**
         * Handle a websocket open event.
         */
        this._onWSOpen = (evt) => {
            this._reconnectAttempt = 0;
            // Allow the message to get through.
            this._isReady = true;
            // Update our status to connected.
            this._updateStatus('connected');
            // Get the kernel info, signaling that the kernel is ready.
            // TODO: requestKernelInfo shouldn't make a request, but should return cached info?
            this.requestKernelInfo()
                .then(() => {
                this._connectionPromise.resolve(void 0);
            })
                .catch(err => {
                this._connectionPromise.reject(err);
            });
            this._isReady = false;
        };
        /**
         * Handle a websocket message, validating and routing appropriately.
         */
        this._onWSMessage = (evt) => {
            if (this._wsStopped) {
                // If the socket is being closed, ignore any messages
                return;
            }
            // Notify immediately if there is an error with the message.
            let msg;
            try {
                msg = serialize.deserialize(evt.data);
                validate.validateMessage(msg);
            }
            catch (error) {
                error.message = `Kernel message validation error: ${error.message}`;
                // We throw the error so that it bubbles up to the top, and displays the right stack.
                throw error;
            }
            // Update the current kernel session id
            this._kernelSession = msg.header.session;
            // Handle the message asynchronously, in the order received.
            this._msgChain = this._msgChain
                .then(() => {
                // Return so that any promises from handling a message are fulfilled
                // before proceeding to the next message.
                return this._handleMessage(msg);
            })
                .catch(error => {
                // Log any errors in handling the message, thus resetting the _msgChain
                // promise so we can process more messages.
                console.error(error);
            });
            // Emit the message receive signal
            this._anyMessage.emit({ msg, direction: 'recv' });
        };
        /**
         * Handle a websocket close event.
         */
        this._onWSClose = (evt) => {
            if (this._wsStopped || !this._ws) {
                return;
            }
            // Clear the websocket event handlers and the socket itself.
            this._clearSocket();
            if (this._reconnectAttempt < this._reconnectLimit) {
                this._updateStatus('reconnecting');
                let timeout = Math.pow(2, this._reconnectAttempt);
                console.error('Connection lost, reconnecting in ' + timeout + ' seconds.');
                setTimeout(this._createSocket, 1e3 * timeout);
                this._reconnectAttempt += 1;
            }
            else {
                this._updateStatus('dead');
                this._connectionPromise.reject(new Error('Could not establish connection'));
            }
        };
        this._id = '';
        this._name = '';
        this._status = 'unknown';
        this._kernelSession = '';
        this._clientId = '';
        this._isDisposed = false;
        this._wsStopped = false;
        this._ws = null;
        this._username = '';
        this._reconnectLimit = 7;
        this._reconnectAttempt = 0;
        this._isReady = false;
        this._targetRegistry = Object.create(null);
        this._info = null;
        this._pendingMessages = [];
        this._statusChanged = new signaling_1.Signal(this);
        this._iopubMessage = new signaling_1.Signal(this);
        this._anyMessage = new signaling_1.Signal(this);
        this._unhandledMessage = new signaling_1.Signal(this);
        this._displayIdToParentIds = new Map();
        this._msgIdToDisplayIds = new Map();
        this._terminated = new signaling_1.Signal(this);
        this._msgChain = Promise.resolve();
        this._noOp = () => {
            /* no-op */
        };
        this._name = options.name;
        this._id = id;
        this.serverSettings =
            options.serverSettings || __1.ServerConnection.makeSettings();
        this._clientId = options.clientId || coreutils_2.UUID.uuid4();
        this._username = options.username || '';
        this._futures = new Map();
        this._comms = new Map();
        this._createSocket();
        Private.runningKernels.push(this);
    }
    /**
     * A signal emitted when the kernel is shut down.
     */
    get terminated() {
        return this._terminated;
    }
    /**
     * A signal emitted when the kernel status changes.
     */
    get statusChanged() {
        return this._statusChanged;
    }
    /**
     * A signal emitted for iopub kernel messages.
     *
     * #### Notes
     * This signal is emitted after the iopub message is handled asynchronously.
     */
    get iopubMessage() {
        return this._iopubMessage;
    }
    /**
     * A signal emitted for unhandled kernel message.
     *
     * #### Notes
     * This signal is emitted for a message that was not handled. It is emitted
     * during the asynchronous message handling code.
     */
    get unhandledMessage() {
        return this._unhandledMessage;
    }
    /**
     * A signal emitted for any kernel message.
     *
     * #### Notes
     * This signal is emitted when a message is received, before it is handled
     * asynchronously.
     *
     * The behavior is undefined if the message is modified during message
     * handling. As such, the message should be treated as read-only.
     */
    get anyMessage() {
        return this._anyMessage;
    }
    /**
     * The id of the server-side kernel.
     */
    get id() {
        return this._id;
    }
    /**
     * The name of the server-side kernel.
     */
    get name() {
        return this._name;
    }
    /**
     * Get the model associated with the kernel.
     */
    get model() {
        return { name: this.name, id: this.id };
    }
    /**
     * The client username.
     */
    get username() {
        return this._username;
    }
    /**
     * The client unique id.
     */
    get clientId() {
        return this._clientId;
    }
    /**
     * The current status of the kernel.
     */
    get status() {
        return this._status;
    }
    /**
     * Test whether the kernel has been disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * The cached kernel info.
     *
     * #### Notes
     * This value will be null until the kernel is ready.
     */
    get info() {
        return this._info;
    }
    /**
     * Test whether the kernel is ready.
     */
    get isReady() {
        return this._isReady;
    }
    /**
     * A promise that is fulfilled when the kernel is ready.
     */
    get ready() {
        return this._connectionPromise.promise;
    }
    /**
     * Get the kernel spec.
     *
     * @returns A promise that resolves with the kernel spec.
     */
    getSpec() {
        if (this._specPromise) {
            return this._specPromise;
        }
        this._specPromise = Private.findSpecs(this.serverSettings).then(specs => {
            return specs.kernelspecs[this._name];
        });
        return this._specPromise;
    }
    /**
     * Clone the current kernel with a new clientId.
     */
    clone() {
        return new DefaultKernel({
            name: this._name,
            username: this._username,
            serverSettings: this.serverSettings
        }, this._id);
    }
    /**
     * Dispose of the resources held by the kernel.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        this._terminated.emit(void 0);
        this._status = 'dead';
        this._clearState();
        this._clearSocket();
        this._kernelSession = '';
        this._msgChain = null;
        algorithm_1.ArrayExt.removeFirstOf(Private.runningKernels, this);
        signaling_1.Signal.clearData(this);
    }
    /**
     * Send a shell message to the kernel.
     *
     * #### Notes
     * Send a message to the kernel's shell channel, yielding a future object
     * for accepting replies.
     *
     * If `expectReply` is given and `true`, the future is disposed when both a
     * shell reply and an idle status message are received. If `expectReply`
     * is not given or is `false`, the future is resolved when an idle status
     * message is received.
     * If `disposeOnDone` is not given or is `true`, the Future is disposed at this point.
     * If `disposeOnDone` is given and `false`, it is up to the caller to dispose of the Future.
     *
     * All replies are validated as valid kernel messages.
     *
     * If the kernel status is `dead`, this will throw an error.
     */
    sendShellMessage(msg, expectReply = false, disposeOnDone = true) {
        if (this.status === 'dead') {
            throw new Error('Kernel is dead');
        }
        if (!this._isReady || !this._ws) {
            this._pendingMessages.push(msg);
        }
        else {
            this._ws.send(serialize.serialize(msg));
        }
        this._anyMessage.emit({ msg, direction: 'send' });
        let future = new future_1.KernelFutureHandler(() => {
            let msgId = msg.header.msg_id;
            this._futures.delete(msgId);
            // Remove stored display id information.
            let displayIds = this._msgIdToDisplayIds.get(msgId);
            if (!displayIds) {
                return;
            }
            displayIds.forEach(displayId => {
                let msgIds = this._displayIdToParentIds.get(displayId);
                if (msgIds) {
                    let idx = msgIds.indexOf(msgId);
                    if (idx === -1) {
                        return;
                    }
                    if (msgIds.length === 1) {
                        this._displayIdToParentIds.delete(displayId);
                    }
                    else {
                        msgIds.splice(idx, 1);
                        this._displayIdToParentIds.set(displayId, msgIds);
                    }
                }
            });
            this._msgIdToDisplayIds.delete(msgId);
        }, msg, expectReply, disposeOnDone, this);
        this._futures.set(msg.header.msg_id, future);
        return future;
    }
    /**
     * Interrupt a kernel.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels).
     *
     * The promise is fulfilled on a valid response and rejected otherwise.
     *
     * It is assumed that the API call does not mutate the kernel id or name.
     *
     * The promise will be rejected if the kernel status is `Dead` or if the
     * request fails or the response is invalid.
     */
    interrupt() {
        return Private.interruptKernel(this, this.serverSettings);
    }
    /**
     * Restart a kernel.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels) and validates the response model.
     *
     * Any existing Future or Comm objects are cleared.
     *
     * The promise is fulfilled on a valid response and rejected otherwise.
     *
     * It is assumed that the API call does not mutate the kernel id or name.
     *
     * The promise will be rejected if the request fails or the response is
     * invalid.
     */
    restart() {
        return Private.restartKernel(this, this.serverSettings);
    }
    /**
     * Handle a restart on the kernel.  This is not part of the `IKernel`
     * interface.
     */
    handleRestart() {
        this._clearState();
        this._updateStatus('restarting');
        this._clearSocket();
    }
    /**
     * Reconnect to a disconnected kernel.
     *
     * #### Notes
     * Used when the websocket connection to the kernel is lost.
     */
    reconnect() {
        this._clearSocket();
        this._updateStatus('reconnecting');
        this._createSocket();
        return this._connectionPromise.promise;
    }
    /**
     * Shutdown a kernel.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels).
     *
     * The promise is fulfilled on a valid response and rejected otherwise.
     *
     * On a valid response, closes the websocket and disposes of the kernel
     * object, and fulfills the promise.
     *
     * The promise will be rejected if the kernel status is `Dead` or if the
     * request fails or the response is invalid.
     */
    shutdown() {
        if (this.status === 'dead') {
            this._clearSocket();
            this._clearState();
            return;
        }
        return Private.shutdownKernel(this.id, this.serverSettings).then(() => {
            this._clearState();
            this._clearSocket();
        });
    }
    /**
     * Send a `kernel_info_request` message.
     *
     * #### Notes
     * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#kernel-info).
     *
     * Fulfills with the `kernel_info_response` content when the shell reply is
     * received and validated.
     *
     * TODO: this should be automatically run every time our kernel restarts,
     * before we say the kernel is ready, and cache the info and the kernel
     * session id. Further calls to this should returned the cached results.
     */
    requestKernelInfo() {
        return __awaiter(this, void 0, void 0, function* () {
            let options = {
                msgType: 'kernel_info_request',
                channel: 'shell',
                username: this._username,
                session: this._clientId
            };
            let msg = messages_1.KernelMessage.createShellMessage(options);
            let reply = (yield Private.handleShellMessage(this, msg));
            if (this.isDisposed) {
                throw new Error('Disposed kernel');
            }
            this._info = reply.content;
            return reply;
        });
    }
    /**
     * Send a `complete_request` message.
     *
     * #### Notes
     * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#completion).
     *
     * Fulfills with the `complete_reply` content when the shell reply is
     * received and validated.
     */
    requestComplete(content) {
        let options = {
            msgType: 'complete_request',
            channel: 'shell',
            username: this._username,
            session: this._clientId
        };
        let msg = messages_1.KernelMessage.createShellMessage(options, content);
        return Private.handleShellMessage(this, msg);
    }
    /**
     * Send an `inspect_request` message.
     *
     * #### Notes
     * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#introspection).
     *
     * Fulfills with the `inspect_reply` content when the shell reply is
     * received and validated.
     */
    requestInspect(content) {
        let options = {
            msgType: 'inspect_request',
            channel: 'shell',
            username: this._username,
            session: this._clientId
        };
        let msg = messages_1.KernelMessage.createShellMessage(options, content);
        return Private.handleShellMessage(this, msg);
    }
    /**
     * Send a `history_request` message.
     *
     * #### Notes
     * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#history).
     *
     * Fulfills with the `history_reply` content when the shell reply is
     * received and validated.
     */
    requestHistory(content) {
        let options = {
            msgType: 'history_request',
            channel: 'shell',
            username: this._username,
            session: this._clientId
        };
        let msg = messages_1.KernelMessage.createShellMessage(options, content);
        return Private.handleShellMessage(this, msg);
    }
    /**
     * Send an `execute_request` message.
     *
     * #### Notes
     * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#execute).
     *
     * Future `onReply` is called with the `execute_reply` content when the
     * shell reply is received and validated. The future will resolve when
     * this message is received and the `idle` iopub status is received.
     * The future will also be disposed at this point unless `disposeOnDone`
     * is specified and `false`, in which case it is up to the caller to dispose
     * of the future.
     *
     * **See also:** [[IExecuteReply]]
     */
    requestExecute(content, disposeOnDone = true, metadata) {
        let options = {
            msgType: 'execute_request',
            channel: 'shell',
            username: this._username,
            session: this._clientId
        };
        let defaults = {
            silent: false,
            store_history: true,
            user_expressions: {},
            allow_stdin: true,
            stop_on_error: false
        };
        content = Object.assign({}, defaults, content);
        let msg = messages_1.KernelMessage.createShellMessage(options, content, metadata);
        return this.sendShellMessage(msg, true, disposeOnDone);
    }
    /**
     * Send an `is_complete_request` message.
     *
     * #### Notes
     * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#code-completeness).
     *
     * Fulfills with the `is_complete_response` content when the shell reply is
     * received and validated.
     */
    requestIsComplete(content) {
        let options = {
            msgType: 'is_complete_request',
            channel: 'shell',
            username: this._username,
            session: this._clientId
        };
        let msg = messages_1.KernelMessage.createShellMessage(options, content);
        return Private.handleShellMessage(this, msg);
    }
    /**
     * Send a `comm_info_request` message.
     *
     * #### Notes
     * Fulfills with the `comm_info_reply` content when the shell reply is
     * received and validated.
     */
    requestCommInfo(content) {
        let options = {
            msgType: 'comm_info_request',
            channel: 'shell',
            username: this._username,
            session: this._clientId
        };
        let msg = messages_1.KernelMessage.createShellMessage(options, content);
        return Private.handleShellMessage(this, msg);
    }
    /**
     * Send an `input_reply` message.
     *
     * #### Notes
     * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#messages-on-the-stdin-router-dealer-sockets).
     */
    sendInputReply(content) {
        if (this.status === 'dead') {
            throw new Error('Kernel is dead');
        }
        let options = {
            msgType: 'input_reply',
            channel: 'stdin',
            username: this._username,
            session: this._clientId
        };
        let msg = messages_1.KernelMessage.createMessage(options, content);
        if (!this._isReady || !this._ws) {
            this._pendingMessages.push(msg);
        }
        else {
            this._ws.send(serialize.serialize(msg));
        }
        this._anyMessage.emit({ msg, direction: 'send' });
    }
    /**
     * Connect to a comm, or create a new one.
     *
     * #### Notes
     * If a client-side comm already exists with the given commId, it is returned.
     */
    connectToComm(targetName, commId = coreutils_2.UUID.uuid4()) {
        if (this._comms.has(commId)) {
            return this._comms.get(commId);
        }
        let comm = new comm_1.CommHandler(targetName, commId, this, () => {
            this._unregisterComm(commId);
        });
        this._comms.set(commId, comm);
        return comm;
    }
    /**
     * Register a comm target handler.
     *
     * @param targetName - The name of the comm target.
     *
     * @param callback - The callback invoked for a comm open message.
     *
     * @returns A disposable used to unregister the comm target.
     *
     * #### Notes
     * Only one comm target can be registered to a target name at a time, an
     * existing callback for the same target name will be overridden.  A registered
     * comm target handler will take precedence over a comm which specifies a
     * `target_module`.
     *
     * If the callback returns a promise, kernel message processing will pause
     * until the returned promise is fulfilled.
     */
    registerCommTarget(targetName, callback) {
        this._targetRegistry[targetName] = callback;
    }
    /**
     * Remove a comm target handler.
     *
     * @param targetName - The name of the comm target to remove.
     *
     * @param callback - The callback to remove.
     *
     * #### Notes
     * The comm target is only removed the callback argument matches.
     */
    removeCommTarget(targetName, callback) {
        if (!this.isDisposed && this._targetRegistry[targetName] === callback) {
            delete this._targetRegistry[targetName];
        }
    }
    /**
     * Register an IOPub message hook.
     *
     * @param msg_id - The parent_header message id the hook will intercept.
     *
     * @param hook - The callback invoked for the message.
     *
     * #### Notes
     * The IOPub hook system allows you to preempt the handlers for IOPub
     * messages that are responses to a given message id.
     *
     * The most recently registered hook is run first. A hook can return a
     * boolean or a promise to a boolean, in which case all kernel message
     * processing pauses until the promise is fulfilled. If a hook return value
     * resolves to false, any later hooks will not run and the function will
     * return a promise resolving to false. If a hook throws an error, the error
     * is logged to the console and the next hook is run. If a hook is
     * registered during the hook processing, it will not run until the next
     * message. If a hook is removed during the hook processing, it will be
     * deactivated immediately.
     *
     * See also [[IFuture.registerMessageHook]].
     */
    registerMessageHook(msgId, hook) {
        let future = this._futures && this._futures.get(msgId);
        if (future) {
            future.registerMessageHook(hook);
        }
    }
    /**
     * Remove an IOPub message hook.
     *
     * @param msg_id - The parent_header message id the hook intercepted.
     *
     * @param hook - The callback invoked for the message.
     *
     */
    removeMessageHook(msgId, hook) {
        let future = this._futures && this._futures.get(msgId);
        if (future) {
            future.removeMessageHook(hook);
        }
    }
    /**
     * Handle a message with a display id.
     *
     * @returns Whether the message was handled.
     */
    _handleDisplayId(displayId, msg) {
        return __awaiter(this, void 0, void 0, function* () {
            let msgId = msg.parent_header.msg_id;
            let parentIds = this._displayIdToParentIds.get(displayId);
            if (parentIds) {
                // We've seen it before, update existing outputs with same display_id
                // by handling display_data as update_display_data.
                let updateMsg = {
                    header: coreutils_3.JSONExt.deepCopy(msg.header),
                    parent_header: coreutils_3.JSONExt.deepCopy(msg.parent_header),
                    metadata: coreutils_3.JSONExt.deepCopy(msg.metadata),
                    content: coreutils_3.JSONExt.deepCopy(msg.content),
                    channel: msg.channel,
                    buffers: msg.buffers ? msg.buffers.slice() : []
                };
                updateMsg.header.msg_type = 'update_display_data';
                yield Promise.all(parentIds.map((parentId) => __awaiter(this, void 0, void 0, function* () {
                    let future = this._futures && this._futures.get(parentId);
                    if (future) {
                        yield future.handleMsg(updateMsg);
                    }
                })));
            }
            // We're done here if it's update_display.
            if (msg.header.msg_type === 'update_display_data') {
                // It's an update, don't proceed to the normal display.
                return true;
            }
            // Regular display_data with id, record it for future updating
            // in _displayIdToParentIds for future lookup.
            parentIds = this._displayIdToParentIds.get(displayId) || [];
            if (parentIds.indexOf(msgId) === -1) {
                parentIds.push(msgId);
            }
            this._displayIdToParentIds.set(displayId, parentIds);
            // Add to our map of display ids for this message.
            let displayIds = this._msgIdToDisplayIds.get(msgId) || [];
            if (displayIds.indexOf(msgId) === -1) {
                displayIds.push(msgId);
            }
            this._msgIdToDisplayIds.set(msgId, displayIds);
            // Let the message propagate to the intended recipient.
            return false;
        });
    }
    /**
     * Clear the socket state.
     */
    _clearSocket() {
        this._wsStopped = true;
        this._isReady = false;
        if (this._ws !== null) {
            // Clear the websocket event handlers and the socket itself.
            this._ws.onopen = this._noOp;
            this._ws.onclose = this._noOp;
            this._ws.onerror = this._noOp;
            this._ws.onmessage = this._noOp;
            this._ws.close();
            this._ws = null;
        }
    }
    /**
     * Handle status iopub messages from the kernel.
     */
    _updateStatus(status) {
        switch (status) {
            case 'starting':
            case 'idle':
            case 'busy':
            case 'connected':
                this._isReady = true;
                break;
            case 'restarting':
            case 'reconnecting':
            case 'dead':
                this._isReady = false;
                break;
            default:
                console.error('invalid kernel status:', status);
                return;
        }
        if (status !== this._status) {
            this._status = status;
            Private.logKernelStatus(this);
            this._statusChanged.emit(status);
            if (status === 'dead') {
                this.dispose();
            }
        }
        if (this._isReady) {
            this._sendPending();
        }
    }
    /**
     * Send pending messages to the kernel.
     */
    _sendPending() {
        // We shift the message off the queue
        // after the message is sent so that if there is an exception,
        // the message is still pending.
        while (this._ws && this._pendingMessages.length > 0) {
            let msg = serialize.serialize(this._pendingMessages[0]);
            this._ws.send(msg);
            this._pendingMessages.shift();
        }
    }
    /**
     * Clear the internal state.
     */
    _clearState() {
        this._isReady = false;
        this._pendingMessages = [];
        this._futures.forEach(future => {
            future.dispose();
        });
        this._comms.forEach(comm => {
            comm.dispose();
        });
        this._msgChain = Promise.resolve();
        this._kernelSession = '';
        this._futures = new Map();
        this._comms = new Map();
        this._displayIdToParentIds.clear();
        this._msgIdToDisplayIds.clear();
    }
    /**
     * Check to make sure it is okay to proceed to handle a message.
     *
     * #### Notes
     * Because we handle messages asynchronously, before a message is handled the
     * kernel might be disposed or restarted (and have a different session id).
     * This function throws an error in each of these cases. This is meant to be
     * called at the start of an asynchronous message handler to cancel message
     * processing if the message no longer is valid.
     */
    _assertCurrentMessage(msg) {
        if (this.isDisposed) {
            throw new Error('Kernel object is disposed');
        }
        if (msg.header.session !== this._kernelSession) {
            throw new Error(`Canceling handling of old message: ${msg.header.msg_type}`);
        }
    }
    /**
     * Handle a `comm_open` kernel message.
     */
    _handleCommOpen(msg) {
        return __awaiter(this, void 0, void 0, function* () {
            this._assertCurrentMessage(msg);
            let content = msg.content;
            let comm = new comm_1.CommHandler(content.target_name, content.comm_id, this, () => {
                this._unregisterComm(content.comm_id);
            });
            this._comms.set(content.comm_id, comm);
            try {
                let target = yield Private.loadObject(content.target_name, content.target_module, this._targetRegistry);
                yield target(comm, msg);
            }
            catch (e) {
                // Close the comm asynchronously. We cannot block message processing on
                // kernel messages to wait for another kernel message.
                comm.close();
                console.error('Exception opening new comm');
                throw e;
            }
        });
    }
    /**
     * Handle 'comm_close' kernel message.
     */
    _handleCommClose(msg) {
        return __awaiter(this, void 0, void 0, function* () {
            this._assertCurrentMessage(msg);
            let content = msg.content;
            let comm = this._comms.get(content.comm_id);
            if (!comm) {
                console.error('Comm not found for comm id ' + content.comm_id);
                return;
            }
            this._unregisterComm(comm.commId);
            let onClose = comm.onClose;
            if (onClose) {
                yield onClose(msg);
            }
            comm.dispose();
        });
    }
    /**
     * Handle a 'comm_msg' kernel message.
     */
    _handleCommMsg(msg) {
        return __awaiter(this, void 0, void 0, function* () {
            this._assertCurrentMessage(msg);
            let content = msg.content;
            let comm = this._comms.get(content.comm_id);
            if (!comm) {
                return;
            }
            let onMsg = comm.onMsg;
            if (onMsg) {
                yield onMsg(msg);
            }
        });
    }
    /**
     * Unregister a comm instance.
     */
    _unregisterComm(commId) {
        this._comms.delete(commId);
    }
    _handleMessage(msg) {
        return __awaiter(this, void 0, void 0, function* () {
            let handled = false;
            // Check to see if we have a display_id we need to reroute.
            if (msg.parent_header && msg.channel === 'iopub') {
                switch (msg.header.msg_type) {
                    case 'display_data':
                    case 'update_display_data':
                    case 'execute_result':
                        // display_data messages may re-route based on their display_id.
                        let transient = (msg.content.transient || {});
                        let displayId = transient['display_id'];
                        if (displayId) {
                            handled = yield this._handleDisplayId(displayId, msg);
                            // The await above may make this message out of date, so check again.
                            this._assertCurrentMessage(msg);
                        }
                        break;
                    default:
                        break;
                }
            }
            if (!handled && msg.parent_header) {
                let parentHeader = msg.parent_header;
                let future = this._futures && this._futures.get(parentHeader.msg_id);
                if (future) {
                    yield future.handleMsg(msg);
                    this._assertCurrentMessage(msg);
                }
                else {
                    // If the message was sent by us and was not iopub, it is orphaned.
                    let owned = parentHeader.session === this.clientId;
                    if (msg.channel !== 'iopub' && owned) {
                        this._unhandledMessage.emit(msg);
                    }
                }
            }
            if (msg.channel === 'iopub') {
                switch (msg.header.msg_type) {
                    case 'status':
                        // Updating the status is synchronous, and we call no async user code
                        this._updateStatus(msg.content.execution_state);
                        break;
                    case 'comm_open':
                        yield this._handleCommOpen(msg);
                        break;
                    case 'comm_msg':
                        yield this._handleCommMsg(msg);
                        break;
                    case 'comm_close':
                        yield this._handleCommClose(msg);
                        break;
                    default:
                        break;
                }
                // If the message was a status dead message, we might have disposed ourselves.
                if (!this.isDisposed) {
                    this._assertCurrentMessage(msg);
                    // the message wouldn't be emitted if we were disposed anyway.
                    this._iopubMessage.emit(msg);
                }
            }
        });
    }
}
exports.DefaultKernel = DefaultKernel;
/**
 * The namespace for `DefaultKernel` statics.
 */
(function (DefaultKernel) {
    /**
     * Find a kernel by id.
     *
     * @param id - The id of the kernel of interest.
     *
     * @param settings - The optional server settings.
     *
     * @returns A promise that resolves with the model for the kernel.
     *
     * #### Notes
     * If the kernel was already started via `startNewKernel`, we return its
     * `Kernel.IModel`.
     *
     * Otherwise, we attempt to find an existing kernel by connecting to the
     * server. The promise is fulfilled when the kernel is found, otherwise the
     * promise is rejected.
     */
    function findById(id, settings) {
        return Private.findById(id, settings);
    }
    DefaultKernel.findById = findById;
    /**
     * Fetch all of the kernel specs.
     *
     * @param settings - The optional server settings.
     *
     * @returns A promise that resolves with the kernel specs.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernelspecs).
     */
    function getSpecs(settings) {
        return Private.getSpecs(settings);
    }
    DefaultKernel.getSpecs = getSpecs;
    /**
     * Fetch the running kernels.
     *
     * @param settings - The optional server settings.
     *
     * @returns A promise that resolves with the list of running kernels.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels) and validates the response model.
     *
     * The promise is fulfilled on a valid response and rejected otherwise.
     */
    function listRunning(settings) {
        return Private.listRunning(settings);
    }
    DefaultKernel.listRunning = listRunning;
    /**
     * Start a new kernel.
     *
     * @param options - The options used to create the kernel.
     *
     * @returns A promise that resolves with a kernel object.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels) and validates the response model.
     *
     * If no options are given or the kernel name is not given, the
     * default kernel will by started by the server.
     *
     * Wraps the result in a Kernel object. The promise is fulfilled
     * when the kernel is started by the server, otherwise the promise is rejected.
     */
    function startNew(options) {
        return Private.startNew(options);
    }
    DefaultKernel.startNew = startNew;
    /**
     * Connect to a running kernel.
     *
     * @param model - The model of the running kernel.
     *
     * @param settings - The server settings for the request.
     *
     * @returns The kernel object.
     *
     * #### Notes
     * If the kernel was already started via `startNewKernel`, the existing
     * Kernel object info is used to create another instance.
     */
    function connectTo(model, settings) {
        return Private.connectTo(model, settings);
    }
    DefaultKernel.connectTo = connectTo;
    /**
     * Shut down a kernel by id.
     *
     * @param id - The id of the running kernel.
     *
     * @param settings - The server settings for the request.
     *
     * @returns A promise that resolves when the kernel is shut down.
     */
    function shutdown(id, settings) {
        return Private.shutdownKernel(id, settings);
    }
    DefaultKernel.shutdown = shutdown;
    /**
     * Shut down all kernels.
     *
     * @param settings - The server settings to use.
     *
     * @returns A promise that resolves when all the kernels are shut down.
     */
    function shutdownAll(settings) {
        return Private.shutdownAll(settings);
    }
    DefaultKernel.shutdownAll = shutdownAll;
})(DefaultKernel = exports.DefaultKernel || (exports.DefaultKernel = {}));
/**
 * A private namespace for the Kernel.
 */
var Private;
(function (Private) {
    /**
     * A module private store for running kernels.
     */
    Private.runningKernels = [];
    /**
     * A module private store of kernel specs by base url.
     */
    Private.specs = Object.create(null);
    /**
     * Find a kernel by id.
     *
     * Will reach out to the server if needed to find the kernel.
     */
    function findById(id, settings) {
        let kernel = algorithm_1.find(Private.runningKernels, value => {
            return value.id === id;
        });
        if (kernel) {
            return Promise.resolve(kernel.model);
        }
        return getKernelModel(id, settings).catch(() => {
            throw new Error(`No running kernel with id: ${id}`);
        });
    }
    Private.findById = findById;
    /**
     * Get the cached kernel specs or fetch them.
     */
    function findSpecs(settings) {
        settings = settings || __1.ServerConnection.makeSettings();
        let promise = Private.specs[settings.baseUrl];
        if (promise) {
            return promise;
        }
        return getSpecs(settings);
    }
    Private.findSpecs = findSpecs;
    /**
     * Fetch all of the kernel specs.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernelspecs).
     */
    function getSpecs(settings) {
        settings = settings || __1.ServerConnection.makeSettings();
        let url = coreutils_1.URLExt.join(settings.baseUrl, KERNELSPEC_SERVICE_URL);
        let promise = __1.ServerConnection.makeRequest(url, {}, settings)
            .then(response => {
            if (response.status !== 200) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            return response.json();
        })
            .then(data => {
            return validate.validateSpecModels(data);
        });
        Private.specs[settings.baseUrl] = promise;
        return promise;
    }
    Private.getSpecs = getSpecs;
    /**
     * Fetch the running kernels.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels) and validates the response model.
     *
     * The promise is fulfilled on a valid response and rejected otherwise.
     */
    function listRunning(settings) {
        settings = settings || __1.ServerConnection.makeSettings();
        let url = coreutils_1.URLExt.join(settings.baseUrl, KERNEL_SERVICE_URL);
        return __1.ServerConnection.makeRequest(url, {}, settings)
            .then(response => {
            if (response.status !== 200) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            return response.json();
        })
            .then(data => {
            if (!Array.isArray(data)) {
                throw new Error('Invalid kernel list');
            }
            for (let i = 0; i < data.length; i++) {
                validate.validateModel(data[i]);
            }
            return updateRunningKernels(data);
        });
    }
    Private.listRunning = listRunning;
    /**
     * Update the running kernels based on new data from the server.
     */
    function updateRunningKernels(kernels) {
        algorithm_1.each(Private.runningKernels.slice(), kernel => {
            let updated = algorithm_1.find(kernels, model => {
                return kernel.id === model.id;
            });
            // If kernel is no longer running on disk, emit dead signal.
            if (!updated && kernel.status !== 'dead') {
                kernel.dispose();
            }
        });
        return kernels;
    }
    Private.updateRunningKernels = updateRunningKernels;
    /**
     * Start a new kernel.
     */
    function startNew(options) {
        return __awaiter(this, void 0, void 0, function* () {
            let settings = options.serverSettings || __1.ServerConnection.makeSettings();
            let url = coreutils_1.URLExt.join(settings.baseUrl, KERNEL_SERVICE_URL);
            let init = {
                method: 'POST',
                body: JSON.stringify({ name: options.name })
            };
            let response = yield __1.ServerConnection.makeRequest(url, init, settings);
            if (response.status !== 201) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            let data = yield response.json();
            validate.validateModel(data);
            return new DefaultKernel(Object.assign({}, options, { name: data.name, serverSettings: settings }), data.id);
        });
    }
    Private.startNew = startNew;
    /**
     * Connect to a running kernel.
     */
    function connectTo(model, settings) {
        let serverSettings = settings || __1.ServerConnection.makeSettings();
        let kernel = algorithm_1.find(Private.runningKernels, value => {
            return value.id === model.id;
        });
        if (kernel) {
            return kernel.clone();
        }
        return new DefaultKernel({ name: model.name, serverSettings }, model.id);
    }
    Private.connectTo = connectTo;
    /**
     * Restart a kernel.
     */
    function restartKernel(kernel, settings) {
        return __awaiter(this, void 0, void 0, function* () {
            if (kernel.status === 'dead') {
                throw new Error('Kernel is dead');
            }
            settings = settings || __1.ServerConnection.makeSettings();
            let url = coreutils_1.URLExt.join(settings.baseUrl, KERNEL_SERVICE_URL, encodeURIComponent(kernel.id), 'restart');
            let init = { method: 'POST' };
            // TODO: If we handleRestart before making the server request, we sever the
            // communication link before the shutdown_reply message comes, so we end up
            // getting the shutdown_reply messages after we reconnect, which is weird.
            // We might want to move the handleRestart to after we get the response back
            // Handle the restart on all of the kernels with the same id.
            algorithm_1.each(Private.runningKernels, k => {
                if (k.id === kernel.id) {
                    k.handleRestart();
                }
            });
            let response = yield __1.ServerConnection.makeRequest(url, init, settings);
            if (response.status !== 200) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            let data = yield response.json();
            validate.validateModel(data);
            // Reconnect the other kernels asynchronously, but don't wait for them.
            algorithm_1.each(Private.runningKernels, k => {
                if (k !== kernel && k.id === kernel.id) {
                    k.reconnect();
                }
            });
            yield kernel.reconnect();
        });
    }
    Private.restartKernel = restartKernel;
    /**
     * Interrupt a kernel.
     */
    function interruptKernel(kernel, settings) {
        return __awaiter(this, void 0, void 0, function* () {
            if (kernel.status === 'dead') {
                throw new Error('Kernel is dead');
            }
            settings = settings || __1.ServerConnection.makeSettings();
            let url = coreutils_1.URLExt.join(settings.baseUrl, KERNEL_SERVICE_URL, encodeURIComponent(kernel.id), 'interrupt');
            let init = { method: 'POST' };
            let response = yield __1.ServerConnection.makeRequest(url, init, settings);
            if (response.status !== 204) {
                throw new __1.ServerConnection.ResponseError(response);
            }
        });
    }
    Private.interruptKernel = interruptKernel;
    /**
     * Delete a kernel.
     */
    function shutdownKernel(id, settings) {
        return __awaiter(this, void 0, void 0, function* () {
            settings = settings || __1.ServerConnection.makeSettings();
            let url = coreutils_1.URLExt.join(settings.baseUrl, KERNEL_SERVICE_URL, encodeURIComponent(id));
            let init = { method: 'DELETE' };
            let response = yield __1.ServerConnection.makeRequest(url, init, settings);
            if (response.status === 404) {
                let msg = `The kernel "${id}" does not exist on the server`;
                console.warn(msg);
            }
            else if (response.status !== 204) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            killKernels(id);
        });
    }
    Private.shutdownKernel = shutdownKernel;
    /**
     * Shut down all kernels.
     *
     * @param settings - The server settings to use.
     *
     * @returns A promise that resolves when all the kernels are shut down.
     */
    function shutdownAll(settings) {
        return __awaiter(this, void 0, void 0, function* () {
            settings = settings || __1.ServerConnection.makeSettings();
            let running = yield listRunning(settings);
            yield Promise.all(running.map(k => shutdownKernel(k.id, settings)));
        });
    }
    Private.shutdownAll = shutdownAll;
    /**
     * Kill the kernels by id.
     */
    function killKernels(id) {
        // Iterate on an array copy so disposals will not affect the iteration.
        Private.runningKernels.slice().forEach(kernel => {
            if (kernel.id === id) {
                kernel.dispose();
            }
        });
    }
    /**
     * Get a full kernel model from the server by kernel id string.
     */
    function getKernelModel(id, settings) {
        return __awaiter(this, void 0, void 0, function* () {
            settings = settings || __1.ServerConnection.makeSettings();
            let url = coreutils_1.URLExt.join(settings.baseUrl, KERNEL_SERVICE_URL, encodeURIComponent(id));
            let response = yield __1.ServerConnection.makeRequest(url, {}, settings);
            if (response.status !== 200) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            let data = yield response.json();
            validate.validateModel(data);
            return data;
        });
    }
    Private.getKernelModel = getKernelModel;
    /**
     * Log the current kernel status.
     */
    function logKernelStatus(kernel) {
        switch (kernel.status) {
            case 'idle':
            case 'busy':
            case 'unknown':
                return;
            default:
                console.log(`Kernel: ${kernel.status} (${kernel.id})`);
                break;
        }
    }
    Private.logKernelStatus = logKernelStatus;
    /**
     * Send a kernel message to the kernel and resolve the reply message.
     */
    function handleShellMessage(kernel, msg) {
        return __awaiter(this, void 0, void 0, function* () {
            let future = kernel.sendShellMessage(msg, true);
            return future.done;
        });
    }
    Private.handleShellMessage = handleShellMessage;
    /**
     * Try to load an object from a module or a registry.
     *
     * Try to load an object from a module asynchronously if a module
     * is specified, otherwise tries to load an object from the global
     * registry, if the global registry is provided.
     */
    function loadObject(name, moduleName, registry) {
        return new Promise((resolve, reject) => {
            // Try loading the view module using require.js
            if (moduleName) {
                if (typeof requirejs === 'undefined') {
                    throw new Error('requirejs not found');
                }
                requirejs([moduleName], (mod) => {
                    if (mod[name] === void 0) {
                        let msg = `Object '${name}' not found in module '${moduleName}'`;
                        reject(new Error(msg));
                    }
                    else {
                        resolve(mod[name]);
                    }
                }, reject);
            }
            else {
                if (registry && registry[name]) {
                    resolve(registry[name]);
                }
                else {
                    reject(new Error(`Object '${name}' not found in registry`));
                }
            }
        });
    }
    Private.loadObject = loadObject;
})(Private || (Private = {}));


/***/ }),

/***/ "YDMw":
/*!*************************************************!*\
  !*** ./node_modules/draft-js/lib/editOnCopy.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule editOnCopy
 * @format
 * 
 */



var getFragmentFromSelection = __webpack_require__(/*! ./getFragmentFromSelection */ "hyAj");

/**
 * If we have a selection, create a ContentState fragment and store
 * it in our internal clipboard. Subsequent paste events will use this
 * fragment if no external clipboard data is supplied.
 */
function editOnCopy(editor, e) {
  var editorState = editor._latestEditorState;
  var selection = editorState.getSelection();

  // No selection, so there's nothing to copy.
  if (selection.isCollapsed()) {
    e.preventDefault();
    return;
  }

  editor.setClipboard(getFragmentFromSelection(editor._latestEditorState));
}

module.exports = editOnCopy;

/***/ }),

/***/ "YDq3":
/*!***************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/Dropzone.js ***!
  \***************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UnconnectedDropzone = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Dropzone = __webpack_require__(/*! ../widgets/Dropzone */ "Z1RB");

var _Dropzone2 = _interopRequireDefault(_Dropzone);

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UnconnectedDropzone = exports.UnconnectedDropzone = function (_Component) {
  _inherits(UnconnectedDropzone, _Component);

  function UnconnectedDropzone() {
    _classCallCheck(this, UnconnectedDropzone);

    return _possibleConstructorReturn(this, (UnconnectedDropzone.__proto__ || Object.getPrototypeOf(UnconnectedDropzone)).apply(this, arguments));
  }

  _createClass(UnconnectedDropzone, [{
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        _Field2.default,
        this.props,
        _react2.default.createElement(_Dropzone2.default, {
          value: this.props.fullValue,
          onUpdate: this.props.updatePlot,
          fileType: this.props.fileType
        })
      );
    }
  }]);

  return UnconnectedDropzone;
}(_react.Component);

UnconnectedDropzone.propTypes = _extends({
  value: _propTypes2.default.any,
  onUpdate: _propTypes2.default.func
}, _Field2.default.propTypes);

exports.default = (0, _lib.connectToContainer)(UnconnectedDropzone);
//# sourceMappingURL=Dropzone.js.map

/***/ }),

/***/ "YESw":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_nativeCreate.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getNative = __webpack_require__(/*! ./_getNative */ "Cwc5");

/* Built-in method references that are verified to be native. */
var nativeCreate = getNative(Object, 'create');

module.exports = nativeCreate;


/***/ }),

/***/ "YJZ8":
/*!**************************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/plots/pad_attributes.js ***!
  \**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



/**
 * Creates a set of padding attributes.
 *
 * @param {object} opts
 *   @param {string} editType:
 *     the editType for all pieces of this padding definition
 *
 * @return {object} attributes object containing {t, r, b, l} as specified
 */
module.exports = function(opts) {
    var editType = opts.editType;
    return {
        t: {
            valType: 'number',
            dflt: 0,
            role: 'style',
            editType: editType,
            description: 'The amount of padding (in px) along the top of the component.'
        },
        r: {
            valType: 'number',
            dflt: 0,
            role: 'style',
            editType: editType,
            description: 'The amount of padding (in px) on the right side of the component.'
        },
        b: {
            valType: 'number',
            dflt: 0,
            role: 'style',
            editType: editType,
            description: 'The amount of padding (in px) along the bottom of the component.'
        },
        l: {
            valType: 'number',
            dflt: 0,
            role: 'style',
            editType: editType,
            description: 'The amount of padding (in px) on the left side of the component.'
        },
        editType: editType
    };
};


/***/ }),

/***/ "YJeH":
/*!***************************************************!*\
  !*** ./node_modules/mdi-react/FormatPaintIcon.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var FormatPaintIcon = function FormatPaintIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M18,4V3C18,2.45 17.55,2 17,2H5C4.45,2 4,2.45 4,3V7C4,7.55 4.45,8 5,8H17C17.55,8 18,7.55 18,7V6H19V10H9V21C9,21.55 9.45,22 10,22H12C12.55,22 13,21.55 13,21V12H21V4H18Z' })
  );
};

module.exports = FormatPaintIcon;


/***/ }),

/***/ "YO3V":
/*!**********************************************!*\
  !*** ./node_modules/lodash/isPlainObject.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseGetTag = __webpack_require__(/*! ./_baseGetTag */ "NykK"),
    getPrototype = __webpack_require__(/*! ./_getPrototype */ "LcsW"),
    isObjectLike = __webpack_require__(/*! ./isObjectLike */ "ExA7");

/** `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;


/***/ }),

/***/ "YOC8":
/*!*********************************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils-extension/lib/redirect.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
/**
 * The form label.
 */
const LABEL = `This workspace is already in use in another JupyterLab window.
  Please enter another workspace name.`;
/**
 * The form input field placeholder.
 */
const PLACEHOLDER = 'url-friendly-workspace-name';
/**
 * The form warning message if an empty value was submitted.
 */
const WARNING = 'Please enter a value.';
/**
 * The UI for the recovery option to redirect to a different workspace.
 */
class RedirectForm extends widgets_1.Widget {
    /**
     * Create a redirect form.
     */
    constructor() {
        super({ node: Private.createNode() });
    }
    /**
     * The text label of the form.
     */
    get label() {
        return this.node.querySelector('label span').textContent;
    }
    set label(label) {
        this.node.querySelector('label span').textContent = label;
    }
    /**
     * The input placeholder.
     */
    get placeholder() {
        return this.node.querySelector('input').placeholder;
    }
    set placeholder(placeholder) {
        this.node.querySelector('input').placeholder = placeholder;
    }
    /**
     * The warning message.
     */
    get warning() {
        return this.node.querySelector('.jp-RedirectForm-warning').textContent;
    }
    set warning(warning) {
        this.node.querySelector('.jp-RedirectForm-warning').textContent = warning;
    }
    /**
     * Returns the input value.
     */
    getValue() {
        return encodeURIComponent(this.node.querySelector('input').value);
    }
}
exports.RedirectForm = RedirectForm;
/**
 * Return a new redirect form, populated with default language.
 */
function createRedirectForm(warn = false) {
    const form = new RedirectForm();
    form.label = LABEL;
    form.placeholder = PLACEHOLDER;
    form.warning = warn ? WARNING : '';
    return form;
}
exports.createRedirectForm = createRedirectForm;
/**
 * A namespace for private module data.
 */
var Private;
(function (Private) {
    /**
     * Create the redirect form's content.
     */
    function createNode() {
        const node = document.createElement('div');
        const label = document.createElement('label');
        const input = document.createElement('input');
        const text = document.createElement('span');
        const warning = document.createElement('div');
        node.className = 'jp-RedirectForm';
        warning.className = 'jp-RedirectForm-warning';
        label.appendChild(text);
        label.appendChild(input);
        node.appendChild(label);
        node.appendChild(warning);
        return node;
    }
    Private.createNode = createNode;
})(Private || (Private = {}));


/***/ }),

/***/ "YPXT":
/*!*********************************************!*\
  !*** ./node_modules/ajv/lib/dotjs/anyOf.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_anyOf(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $noEmptySchema = $schema.every(function($sch) {
    return it.util.schemaHasRules($sch, it.RULES.all);
  });
  if ($noEmptySchema) {
    var $currentBaseId = $it.baseId;
    out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false;  ';
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    var arr1 = $schema;
    if (arr1) {
      var $sch, $i = -1,
        l1 = arr1.length - 1;
      while ($i < l1) {
        $sch = arr1[$i += 1];
        $it.schema = $sch;
        $it.schemaPath = $schemaPath + '[' + $i + ']';
        $it.errSchemaPath = $errSchemaPath + '/' + $i;
        out += '  ' + (it.validate($it)) + ' ';
        $it.baseId = $currentBaseId;
        out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { ';
        $closingBraces += '}';
      }
    }
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') {   var err =   '; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should match some schema in anyOf\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError(vErrors); ';
      } else {
        out += ' validate.errors = vErrors; return false; ';
      }
    }
    out += ' } else {  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
    if (it.opts.allErrors) {
      out += ' } ';
    }
    out = it.util.cleanUpCode(out);
  } else {
    if ($breakOnError) {
      out += ' if (true) { ';
    }
  }
  return out;
}


/***/ }),

/***/ "YRex":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/ug-cn.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js language configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var ugCn = moment.defineLocale('ug-cn', {
    months: 'يانۋار_فېۋرال_مارت_ئاپرېل_ماي_ئىيۇن_ئىيۇل_ئاۋغۇست_سېنتەبىر_ئۆكتەبىر_نويابىر_دېكابىر'.split(
        '_'
    ),
    monthsShort: 'يانۋار_فېۋرال_مارت_ئاپرېل_ماي_ئىيۇن_ئىيۇل_ئاۋغۇست_سېنتەبىر_ئۆكتەبىر_نويابىر_دېكابىر'.split(
        '_'
    ),
    weekdays: 'يەكشەنبە_دۈشەنبە_سەيشەنبە_چارشەنبە_پەيشەنبە_جۈمە_شەنبە'.split(
        '_'
    ),
    weekdaysShort: 'يە_دۈ_سە_چا_پە_جۈ_شە'.split('_'),
    weekdaysMin: 'يە_دۈ_سە_چا_پە_جۈ_شە'.split('_'),
    longDateFormat: {
        LT: 'HH:mm',
        LTS: 'HH:mm:ss',
        L: 'YYYY-MM-DD',
        LL: 'YYYY-يىلىM-ئاينىڭD-كۈنى',
        LLL: 'YYYY-يىلىM-ئاينىڭD-كۈنى، HH:mm',
        LLLL: 'dddd، YYYY-يىلىM-ئاينىڭD-كۈنى، HH:mm'
    },
    meridiemParse: /يېرىم كېچە|سەھەر|چۈشتىن بۇرۇن|چۈش|چۈشتىن كېيىن|كەچ/,
    meridiemHour: function (hour, meridiem) {
        if (hour === 12) {
            hour = 0;
        }
        if (
            meridiem === 'يېرىم كېچە' ||
            meridiem === 'سەھەر' ||
            meridiem === 'چۈشتىن بۇرۇن'
        ) {
            return hour;
        } else if (meridiem === 'چۈشتىن كېيىن' || meridiem === 'كەچ') {
            return hour + 12;
        } else {
            return hour >= 11 ? hour : hour + 12;
        }
    },
    meridiem: function (hour, minute, isLower) {
        var hm = hour * 100 + minute;
        if (hm < 600) {
            return 'يېرىم كېچە';
        } else if (hm < 900) {
            return 'سەھەر';
        } else if (hm < 1130) {
            return 'چۈشتىن بۇرۇن';
        } else if (hm < 1230) {
            return 'چۈش';
        } else if (hm < 1800) {
            return 'چۈشتىن كېيىن';
        } else {
            return 'كەچ';
        }
    },
    calendar: {
        sameDay: '[بۈگۈن سائەت] LT',
        nextDay: '[ئەتە سائەت] LT',
        nextWeek: '[كېلەركى] dddd [سائەت] LT',
        lastDay: '[تۆنۈگۈن] LT',
        lastWeek: '[ئالدىنقى] dddd [سائەت] LT',
        sameElse: 'L'
    },
    relativeTime: {
        future: '%s كېيىن',
        past: '%s بۇرۇن',
        s: 'نەچچە سېكونت',
        ss: '%d سېكونت',
        m: 'بىر مىنۇت',
        mm: '%d مىنۇت',
        h: 'بىر سائەت',
        hh: '%d سائەت',
        d: 'بىر كۈن',
        dd: '%d كۈن',
        M: 'بىر ئاي',
        MM: '%d ئاي',
        y: 'بىر يىل',
        yy: '%d يىل'
    },

    dayOfMonthOrdinalParse: /\d{1,2}(-كۈنى|-ئاي|-ھەپتە)/,
    ordinal: function (number, period) {
        switch (period) {
            case 'd':
            case 'D':
            case 'DDD':
                return number + '-كۈنى';
            case 'w':
            case 'W':
                return number + '-ھەپتە';
            default:
                return number;
        }
    },
    preparse: function (string) {
        return string.replace(/،/g, ',');
    },
    postformat: function (string) {
        return string.replace(/,/g, '،');
    },
    week: {
        // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效
        dow: 1, // Monday is the first day of the week.
        doy: 7 // The week that contains Jan 1st is the first week of the year.
    }
});

return ugCn;

})));


/***/ }),

/***/ "YUem":
/*!***********************************************************!*\
  !*** ./node_modules/draft-js/lib/keyCommandDeleteWord.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule keyCommandDeleteWord
 * @format
 * 
 */



var DraftRemovableWord = __webpack_require__(/*! ./DraftRemovableWord */ "SF5q");
var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");

var moveSelectionForward = __webpack_require__(/*! ./moveSelectionForward */ "DEWG");
var removeTextWithStrategy = __webpack_require__(/*! ./removeTextWithStrategy */ "8d//");

/**
 * Delete the word that is right of the cursor, as well as any spaces or
 * punctuation before the word.
 */
function keyCommandDeleteWord(editorState) {
  var afterRemoval = removeTextWithStrategy(editorState, function (strategyState) {
    var selection = strategyState.getSelection();
    var offset = selection.getStartOffset();
    var key = selection.getStartKey();
    var content = strategyState.getCurrentContent();
    var text = content.getBlockForKey(key).getText().slice(offset);
    var toRemove = DraftRemovableWord.getForward(text);

    // If there are no words in front of the cursor, remove the newline.
    return moveSelectionForward(strategyState, toRemove.length || 1);
  }, 'forward');

  if (afterRemoval === editorState.getCurrentContent()) {
    return editorState;
  }

  return EditorState.push(editorState, afterRemoval, 'remove-range');
}

module.exports = keyCommandDeleteWord;

/***/ }),

/***/ "YVIB":
/*!*************************************!*\
  !*** ./node_modules/fbjs/lib/cx.js ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

/**
 * This function is used to mark string literals representing CSS class names
 * so that they can be transformed statically. This allows for modularization
 * and minification of CSS class names.
 *
 * In static_upstream, this function is actually implemented, but it should
 * eventually be replaced with something more descriptive, and the transform
 * that is used in the main stack should be ported for use elsewhere.
 *
 * @param string|object className to modularize, or an object of key/values.
 *                      In the object case, the values are conditions that
 *                      determine if the className keys should be included.
 * @param [string ...]  Variable list of classNames in the string case.
 * @return string       Renderable space-separated CSS className.
 */
function cx(classNames) {
  if (typeof classNames == 'object') {
    return Object.keys(classNames).filter(function (className) {
      return classNames[className];
    }).map(replace).join(' ');
  }
  return Array.prototype.map.call(arguments, replace).join(' ');
}

function replace(str) {
  return str.replace(/\//g, '-');
}

module.exports = cx;

/***/ }),

/***/ "Ybq/":
/*!********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/default_panels/StyleShapesPanel.js ***!
  \********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _components = __webpack_require__(/*! ../components */ "yF51");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var StyleShapesPanel = function StyleShapesPanel(props, _ref) {
  var _ = _ref.localize;
  return _react2.default.createElement(
    _components.ShapeAccordion,
    { canAdd: true },
    _react2.default.createElement(_components.Radio, {
      attr: 'visible',
      options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
    }),
    _react2.default.createElement(_components.Radio, {
      attr: 'type',
      options: [{ label: _('Line'), value: 'line' }, { label: _('Rectangle'), value: 'rect' }, { label: _('Ellipse'), value: 'circle' }]
    }),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Horizontal Boundaries') },
      _react2.default.createElement(_components.PositioningRef, { label: _('Relative to'), attr: 'xref' }),
      _react2.default.createElement(_components.PositioningNumeric, { label: _('Start Point'), attr: 'x0' }),
      _react2.default.createElement(_components.PositioningNumeric, { label: _('End Point'), attr: 'x1' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Vertical Boundaries') },
      _react2.default.createElement(_components.PositioningRef, { label: _('Relative to'), attr: 'yref' }),
      _react2.default.createElement(_components.PositioningNumeric, { label: _('Start Point'), attr: 'y0' }),
      _react2.default.createElement(_components.PositioningNumeric, { label: _('End Point'), attr: 'y1' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Lines') },
      _react2.default.createElement(_components.Numeric, { label: _('Width'), attr: 'line.width' }),
      _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'line.color' }),
      _react2.default.createElement(_components.LineDashSelector, { label: _('Type'), attr: 'line.dash' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Fill') },
      _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'fillcolor' }),
      _react2.default.createElement(_components.NumericFraction, { label: _('Opacity'), attr: 'opacity' })
    )
  );
};

StyleShapesPanel.contextTypes = {
  localize: _propTypes2.default.func
};

exports.default = StyleShapesPanel;
//# sourceMappingURL=StyleShapesPanel.js.map

/***/ }),

/***/ "Ybsr":
/*!*************************************************************!*\
  !*** ./node_modules/react-dom/cjs/react-dom.development.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/** @license React v16.4.2
 * react-dom.development.js
 *
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */





if (true) {
  (function() {
'use strict';

var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");
var React = __webpack_require__(/*! react */ "q1tI");
var warning = __webpack_require__(/*! fbjs/lib/warning */ "2mcs");
var ExecutionEnvironment = __webpack_require__(/*! fbjs/lib/ExecutionEnvironment */ "xLLm");
var _assign = __webpack_require__(/*! object-assign */ "MgzW");
var emptyFunction = __webpack_require__(/*! fbjs/lib/emptyFunction */ "ohE5");
var checkPropTypes = __webpack_require__(/*! prop-types/checkPropTypes */ "oVyQ");
var getActiveElement = __webpack_require__(/*! fbjs/lib/getActiveElement */ "jl2H");
var shallowEqual = __webpack_require__(/*! fbjs/lib/shallowEqual */ "rzV7");
var containsNode = __webpack_require__(/*! fbjs/lib/containsNode */ "TWoB");
var emptyObject = __webpack_require__(/*! fbjs/lib/emptyObject */ "t33a");
var hyphenateStyleName = __webpack_require__(/*! fbjs/lib/hyphenateStyleName */ "+8Ar");
var camelizeStyleName = __webpack_require__(/*! fbjs/lib/camelizeStyleName */ "lZ34");

// Relying on the `invariant()` implementation lets us
// have preserve the format and params in the www builds.

!React ? invariant(false, 'ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM.') : void 0;

var invokeGuardedCallback = function (name, func, context, a, b, c, d, e, f) {
  this._hasCaughtError = false;
  this._caughtError = null;
  var funcArgs = Array.prototype.slice.call(arguments, 3);
  try {
    func.apply(context, funcArgs);
  } catch (error) {
    this._caughtError = error;
    this._hasCaughtError = true;
  }
};

{
  // In DEV mode, we swap out invokeGuardedCallback for a special version
  // that plays more nicely with the browser's DevTools. The idea is to preserve
  // "Pause on exceptions" behavior. Because React wraps all user-provided
  // functions in invokeGuardedCallback, and the production version of
  // invokeGuardedCallback uses a try-catch, all user exceptions are treated
  // like caught exceptions, and the DevTools won't pause unless the developer
  // takes the extra step of enabling pause on caught exceptions. This is
  // untintuitive, though, because even though React has caught the error, from
  // the developer's perspective, the error is uncaught.
  //
  // To preserve the expected "Pause on exceptions" behavior, we don't use a
  // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
  // DOM node, and call the user-provided callback from inside an event handler
  // for that fake event. If the callback throws, the error is "captured" using
  // a global event handler. But because the error happens in a different
  // event loop context, it does not interrupt the normal program flow.
  // Effectively, this gives us try-catch behavior without actually using
  // try-catch. Neat!

  // Check that the browser supports the APIs we need to implement our special
  // DEV version of invokeGuardedCallback
  if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
    var fakeNode = document.createElement('react');

    var invokeGuardedCallbackDev = function (name, func, context, a, b, c, d, e, f) {
      // If document doesn't exist we know for sure we will crash in this method
      // when we call document.createEvent(). However this can cause confusing
      // errors: https://github.com/facebookincubator/create-react-app/issues/3482
      // So we preemptively throw with a better message instead.
      !(typeof document !== 'undefined') ? invariant(false, 'The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous.') : void 0;
      var evt = document.createEvent('Event');

      // Keeps track of whether the user-provided callback threw an error. We
      // set this to true at the beginning, then set it to false right after
      // calling the function. If the function errors, `didError` will never be
      // set to false. This strategy works even if the browser is flaky and
      // fails to call our global error handler, because it doesn't rely on
      // the error event at all.
      var didError = true;

      // Create an event handler for our fake event. We will synchronously
      // dispatch our fake event using `dispatchEvent`. Inside the handler, we
      // call the user-provided callback.
      var funcArgs = Array.prototype.slice.call(arguments, 3);
      function callCallback() {
        // We immediately remove the callback from event listeners so that
        // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
        // nested call would trigger the fake event handlers of any call higher
        // in the stack.
        fakeNode.removeEventListener(evtType, callCallback, false);
        func.apply(context, funcArgs);
        didError = false;
      }

      // Create a global error event handler. We use this to capture the value
      // that was thrown. It's possible that this error handler will fire more
      // than once; for example, if non-React code also calls `dispatchEvent`
      // and a handler for that event throws. We should be resilient to most of
      // those cases. Even if our error event handler fires more than once, the
      // last error event is always used. If the callback actually does error,
      // we know that the last error event is the correct one, because it's not
      // possible for anything else to have happened in between our callback
      // erroring and the code that follows the `dispatchEvent` call below. If
      // the callback doesn't error, but the error event was fired, we know to
      // ignore it because `didError` will be false, as described above.
      var error = void 0;
      // Use this to track whether the error event is ever called.
      var didSetError = false;
      var isCrossOriginError = false;

      function onError(event) {
        error = event.error;
        didSetError = true;
        if (error === null && event.colno === 0 && event.lineno === 0) {
          isCrossOriginError = true;
        }
      }

      // Create a fake event type.
      var evtType = 'react-' + (name ? name : 'invokeguardedcallback');

      // Attach our event handlers
      window.addEventListener('error', onError);
      fakeNode.addEventListener(evtType, callCallback, false);

      // Synchronously dispatch our fake event. If the user-provided function
      // errors, it will trigger our global error handler.
      evt.initEvent(evtType, false, false);
      fakeNode.dispatchEvent(evt);

      if (didError) {
        if (!didSetError) {
          // The callback errored, but the error event never fired.
          error = new Error('An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.');
        } else if (isCrossOriginError) {
          error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://fb.me/react-crossorigin-error for more information.');
        }
        this._hasCaughtError = true;
        this._caughtError = error;
      } else {
        this._hasCaughtError = false;
        this._caughtError = null;
      }

      // Remove our event listeners
      window.removeEventListener('error', onError);
    };

    invokeGuardedCallback = invokeGuardedCallbackDev;
  }
}

var invokeGuardedCallback$1 = invokeGuardedCallback;

var ReactErrorUtils = {
  // Used by Fiber to simulate a try-catch.
  _caughtError: null,
  _hasCaughtError: false,

  // Used by event system to capture/rethrow the first error.
  _rethrowError: null,
  _hasRethrowError: false,

  /**
   * Call a function while guarding against errors that happens within it.
   * Returns an error if it throws, otherwise null.
   *
   * In production, this is implemented using a try-catch. The reason we don't
   * use a try-catch directly is so that we can swap out a different
   * implementation in DEV mode.
   *
   * @param {String} name of the guard to use for logging or debugging
   * @param {Function} func The function to invoke
   * @param {*} context The context to use when calling the function
   * @param {...*} args Arguments for function
   */
  invokeGuardedCallback: function (name, func, context, a, b, c, d, e, f) {
    invokeGuardedCallback$1.apply(ReactErrorUtils, arguments);
  },

  /**
   * Same as invokeGuardedCallback, but instead of returning an error, it stores
   * it in a global so it can be rethrown by `rethrowCaughtError` later.
   * TODO: See if _caughtError and _rethrowError can be unified.
   *
   * @param {String} name of the guard to use for logging or debugging
   * @param {Function} func The function to invoke
   * @param {*} context The context to use when calling the function
   * @param {...*} args Arguments for function
   */
  invokeGuardedCallbackAndCatchFirstError: function (name, func, context, a, b, c, d, e, f) {
    ReactErrorUtils.invokeGuardedCallback.apply(this, arguments);
    if (ReactErrorUtils.hasCaughtError()) {
      var error = ReactErrorUtils.clearCaughtError();
      if (!ReactErrorUtils._hasRethrowError) {
        ReactErrorUtils._hasRethrowError = true;
        ReactErrorUtils._rethrowError = error;
      }
    }
  },

  /**
   * During execution of guarded functions we will capture the first error which
   * we will rethrow to be handled by the top level error handler.
   */
  rethrowCaughtError: function () {
    return rethrowCaughtError.apply(ReactErrorUtils, arguments);
  },

  hasCaughtError: function () {
    return ReactErrorUtils._hasCaughtError;
  },

  clearCaughtError: function () {
    if (ReactErrorUtils._hasCaughtError) {
      var error = ReactErrorUtils._caughtError;
      ReactErrorUtils._caughtError = null;
      ReactErrorUtils._hasCaughtError = false;
      return error;
    } else {
      invariant(false, 'clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.');
    }
  }
};

var rethrowCaughtError = function () {
  if (ReactErrorUtils._hasRethrowError) {
    var error = ReactErrorUtils._rethrowError;
    ReactErrorUtils._rethrowError = null;
    ReactErrorUtils._hasRethrowError = false;
    throw error;
  }
};

/**
 * Injectable ordering of event plugins.
 */
var eventPluginOrder = null;

/**
 * Injectable mapping from names to event plugin modules.
 */
var namesToPlugins = {};

/**
 * Recomputes the plugin list using the injected plugins and plugin ordering.
 *
 * @private
 */
function recomputePluginOrdering() {
  if (!eventPluginOrder) {
    // Wait until an `eventPluginOrder` is injected.
    return;
  }
  for (var pluginName in namesToPlugins) {
    var pluginModule = namesToPlugins[pluginName];
    var pluginIndex = eventPluginOrder.indexOf(pluginName);
    !(pluginIndex > -1) ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.', pluginName) : void 0;
    if (plugins[pluginIndex]) {
      continue;
    }
    !pluginModule.extractEvents ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.', pluginName) : void 0;
    plugins[pluginIndex] = pluginModule;
    var publishedEvents = pluginModule.eventTypes;
    for (var eventName in publishedEvents) {
      !publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName) ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : void 0;
    }
  }
}

/**
 * Publishes an event so that it can be dispatched by the supplied plugin.
 *
 * @param {object} dispatchConfig Dispatch configuration for the event.
 * @param {object} PluginModule Plugin publishing the event.
 * @return {boolean} True if the event was successfully published.
 * @private
 */
function publishEventForPlugin(dispatchConfig, pluginModule, eventName) {
  !!eventNameDispatchConfigs.hasOwnProperty(eventName) ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.', eventName) : void 0;
  eventNameDispatchConfigs[eventName] = dispatchConfig;

  var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
  if (phasedRegistrationNames) {
    for (var phaseName in phasedRegistrationNames) {
      if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
        var phasedRegistrationName = phasedRegistrationNames[phaseName];
        publishRegistrationName(phasedRegistrationName, pluginModule, eventName);
      }
    }
    return true;
  } else if (dispatchConfig.registrationName) {
    publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName);
    return true;
  }
  return false;
}

/**
 * Publishes a registration name that is used to identify dispatched events.
 *
 * @param {string} registrationName Registration name to add.
 * @param {object} PluginModule Plugin publishing the event.
 * @private
 */
function publishRegistrationName(registrationName, pluginModule, eventName) {
  !!registrationNameModules[registrationName] ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.', registrationName) : void 0;
  registrationNameModules[registrationName] = pluginModule;
  registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies;

  {
    var lowerCasedName = registrationName.toLowerCase();
    possibleRegistrationNames[lowerCasedName] = registrationName;

    if (registrationName === 'onDoubleClick') {
      possibleRegistrationNames.ondblclick = registrationName;
    }
  }
}

/**
 * Registers plugins so that they can extract and dispatch events.
 *
 * @see {EventPluginHub}
 */

/**
 * Ordered list of injected plugins.
 */
var plugins = [];

/**
 * Mapping from event name to dispatch config
 */
var eventNameDispatchConfigs = {};

/**
 * Mapping from registration name to plugin module
 */
var registrationNameModules = {};

/**
 * Mapping from registration name to event name
 */
var registrationNameDependencies = {};

/**
 * Mapping from lowercase registration names to the properly cased version,
 * used to warn in the case of missing event handlers. Available
 * only in true.
 * @type {Object}
 */
var possibleRegistrationNames = {};
// Trust the developer to only use possibleRegistrationNames in true

/**
 * Injects an ordering of plugins (by plugin name). This allows the ordering
 * to be decoupled from injection of the actual plugins so that ordering is
 * always deterministic regardless of packaging, on-the-fly injection, etc.
 *
 * @param {array} InjectedEventPluginOrder
 * @internal
 * @see {EventPluginHub.injection.injectEventPluginOrder}
 */
function injectEventPluginOrder(injectedEventPluginOrder) {
  !!eventPluginOrder ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.') : void 0;
  // Clone the ordering so it cannot be dynamically mutated.
  eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder);
  recomputePluginOrdering();
}

/**
 * Injects plugins to be used by `EventPluginHub`. The plugin names must be
 * in the ordering injected by `injectEventPluginOrder`.
 *
 * Plugins can be injected as part of page initialization or on-the-fly.
 *
 * @param {object} injectedNamesToPlugins Map from names to plugin modules.
 * @internal
 * @see {EventPluginHub.injection.injectEventPluginsByName}
 */
function injectEventPluginsByName(injectedNamesToPlugins) {
  var isOrderingDirty = false;
  for (var pluginName in injectedNamesToPlugins) {
    if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {
      continue;
    }
    var pluginModule = injectedNamesToPlugins[pluginName];
    if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) {
      !!namesToPlugins[pluginName] ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.', pluginName) : void 0;
      namesToPlugins[pluginName] = pluginModule;
      isOrderingDirty = true;
    }
  }
  if (isOrderingDirty) {
    recomputePluginOrdering();
  }
}

var EventPluginRegistry = Object.freeze({
	plugins: plugins,
	eventNameDispatchConfigs: eventNameDispatchConfigs,
	registrationNameModules: registrationNameModules,
	registrationNameDependencies: registrationNameDependencies,
	possibleRegistrationNames: possibleRegistrationNames,
	injectEventPluginOrder: injectEventPluginOrder,
	injectEventPluginsByName: injectEventPluginsByName
});

var getFiberCurrentPropsFromNode = null;
var getInstanceFromNode = null;
var getNodeFromInstance = null;

var injection$1 = {
  injectComponentTree: function (Injected) {
    getFiberCurrentPropsFromNode = Injected.getFiberCurrentPropsFromNode;
    getInstanceFromNode = Injected.getInstanceFromNode;
    getNodeFromInstance = Injected.getNodeFromInstance;

    {
      !(getNodeFromInstance && getInstanceFromNode) ? warning(false, 'EventPluginUtils.injection.injectComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0;
    }
  }
};

var validateEventDispatches = void 0;
{
  validateEventDispatches = function (event) {
    var dispatchListeners = event._dispatchListeners;
    var dispatchInstances = event._dispatchInstances;

    var listenersIsArr = Array.isArray(dispatchListeners);
    var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0;

    var instancesIsArr = Array.isArray(dispatchInstances);
    var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0;

    !(instancesIsArr === listenersIsArr && instancesLen === listenersLen) ? warning(false, 'EventPluginUtils: Invalid `event`.') : void 0;
  };
}

/**
 * Dispatch the event to the listener.
 * @param {SyntheticEvent} event SyntheticEvent to handle
 * @param {boolean} simulated If the event is simulated (changes exn behavior)
 * @param {function} listener Application-level callback
 * @param {*} inst Internal component instance
 */
function executeDispatch(event, simulated, listener, inst) {
  var type = event.type || 'unknown-event';
  event.currentTarget = getNodeFromInstance(inst);
  ReactErrorUtils.invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
  event.currentTarget = null;
}

/**
 * Standard/simple iteration through an event's collected dispatches.
 */
function executeDispatchesInOrder(event, simulated) {
  var dispatchListeners = event._dispatchListeners;
  var dispatchInstances = event._dispatchInstances;
  {
    validateEventDispatches(event);
  }
  if (Array.isArray(dispatchListeners)) {
    for (var i = 0; i < dispatchListeners.length; i++) {
      if (event.isPropagationStopped()) {
        break;
      }
      // Listeners and Instances are two parallel arrays that are always in sync.
      executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]);
    }
  } else if (dispatchListeners) {
    executeDispatch(event, simulated, dispatchListeners, dispatchInstances);
  }
  event._dispatchListeners = null;
  event._dispatchInstances = null;
}

/**
 * @see executeDispatchesInOrderStopAtTrueImpl
 */


/**
 * Execution of a "direct" dispatch - there must be at most one dispatch
 * accumulated on the event or it is considered an error. It doesn't really make
 * sense for an event with multiple dispatches (bubbled) to keep track of the
 * return values at each dispatch execution, but it does tend to make sense when
 * dealing with "direct" dispatches.
 *
 * @return {*} The return value of executing the single dispatch.
 */


/**
 * @param {SyntheticEvent} event
 * @return {boolean} True iff number of dispatches accumulated is greater than 0.
 */

/**
 * Accumulates items that must not be null or undefined into the first one. This
 * is used to conserve memory by avoiding array allocations, and thus sacrifices
 * API cleanness. Since `current` can be null before being passed in and not
 * null after this function, make sure to assign it back to `current`:
 *
 * `a = accumulateInto(a, b);`
 *
 * This API should be sparingly used. Try `accumulate` for something cleaner.
 *
 * @return {*|array<*>} An accumulation of items.
 */

function accumulateInto(current, next) {
  !(next != null) ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : void 0;

  if (current == null) {
    return next;
  }

  // Both are not empty. Warning: Never call x.concat(y) when you are not
  // certain that x is an Array (x could be a string with concat method).
  if (Array.isArray(current)) {
    if (Array.isArray(next)) {
      current.push.apply(current, next);
      return current;
    }
    current.push(next);
    return current;
  }

  if (Array.isArray(next)) {
    // A bit too dangerous to mutate `next`.
    return [current].concat(next);
  }

  return [current, next];
}

/**
 * @param {array} arr an "accumulation" of items which is either an Array or
 * a single item. Useful when paired with the `accumulate` module. This is a
 * simple utility that allows us to reason about a collection of items, but
 * handling the case when there is exactly one item (and we do not need to
 * allocate an array).
 * @param {function} cb Callback invoked with each element or a collection.
 * @param {?} [scope] Scope used as `this` in a callback.
 */
function forEachAccumulated(arr, cb, scope) {
  if (Array.isArray(arr)) {
    arr.forEach(cb, scope);
  } else if (arr) {
    cb.call(scope, arr);
  }
}

/**
 * Internal queue of events that have accumulated their dispatches and are
 * waiting to have their dispatches executed.
 */
var eventQueue = null;

/**
 * Dispatches an event and releases it back into the pool, unless persistent.
 *
 * @param {?object} event Synthetic event to be dispatched.
 * @param {boolean} simulated If the event is simulated (changes exn behavior)
 * @private
 */
var executeDispatchesAndRelease = function (event, simulated) {
  if (event) {
    executeDispatchesInOrder(event, simulated);

    if (!event.isPersistent()) {
      event.constructor.release(event);
    }
  }
};
var executeDispatchesAndReleaseSimulated = function (e) {
  return executeDispatchesAndRelease(e, true);
};
var executeDispatchesAndReleaseTopLevel = function (e) {
  return executeDispatchesAndRelease(e, false);
};

function isInteractive(tag) {
  return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
}

function shouldPreventMouseEvent(name, type, props) {
  switch (name) {
    case 'onClick':
    case 'onClickCapture':
    case 'onDoubleClick':
    case 'onDoubleClickCapture':
    case 'onMouseDown':
    case 'onMouseDownCapture':
    case 'onMouseMove':
    case 'onMouseMoveCapture':
    case 'onMouseUp':
    case 'onMouseUpCapture':
      return !!(props.disabled && isInteractive(type));
    default:
      return false;
  }
}

/**
 * This is a unified interface for event plugins to be installed and configured.
 *
 * Event plugins can implement the following properties:
 *
 *   `extractEvents` {function(string, DOMEventTarget, string, object): *}
 *     Required. When a top-level event is fired, this method is expected to
 *     extract synthetic events that will in turn be queued and dispatched.
 *
 *   `eventTypes` {object}
 *     Optional, plugins that fire events must publish a mapping of registration
 *     names that are used to register listeners. Values of this mapping must
 *     be objects that contain `registrationName` or `phasedRegistrationNames`.
 *
 *   `executeDispatch` {function(object, function, string)}
 *     Optional, allows plugins to override how an event gets dispatched. By
 *     default, the listener is simply invoked.
 *
 * Each plugin that is injected into `EventsPluginHub` is immediately operable.
 *
 * @public
 */

/**
 * Methods for injecting dependencies.
 */
var injection = {
  /**
   * @param {array} InjectedEventPluginOrder
   * @public
   */
  injectEventPluginOrder: injectEventPluginOrder,

  /**
   * @param {object} injectedNamesToPlugins Map from names to plugin modules.
   */
  injectEventPluginsByName: injectEventPluginsByName
};

/**
 * @param {object} inst The instance, which is the source of events.
 * @param {string} registrationName Name of listener (e.g. `onClick`).
 * @return {?function} The stored callback.
 */
function getListener(inst, registrationName) {
  var listener = void 0;

  // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not
  // live here; needs to be moved to a better place soon
  var stateNode = inst.stateNode;
  if (!stateNode) {
    // Work in progress (ex: onload events in incremental mode).
    return null;
  }
  var props = getFiberCurrentPropsFromNode(stateNode);
  if (!props) {
    // Work in progress.
    return null;
  }
  listener = props[registrationName];
  if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
    return null;
  }
  !(!listener || typeof listener === 'function') ? invariant(false, 'Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener) : void 0;
  return listener;
}

/**
 * Allows registered plugins an opportunity to extract events from top-level
 * native browser events.
 *
 * @return {*} An accumulation of synthetic events.
 * @internal
 */
function extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
  var events = null;
  for (var i = 0; i < plugins.length; i++) {
    // Not every plugin in the ordering may be loaded at runtime.
    var possiblePlugin = plugins[i];
    if (possiblePlugin) {
      var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget);
      if (extractedEvents) {
        events = accumulateInto(events, extractedEvents);
      }
    }
  }
  return events;
}

function runEventsInBatch(events, simulated) {
  if (events !== null) {
    eventQueue = accumulateInto(eventQueue, events);
  }

  // Set `eventQueue` to null before processing it so that we can tell if more
  // events get enqueued while processing.
  var processingEventQueue = eventQueue;
  eventQueue = null;

  if (!processingEventQueue) {
    return;
  }

  if (simulated) {
    forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated);
  } else {
    forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel);
  }
  !!eventQueue ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.') : void 0;
  // This would be a good time to rethrow if any of the event handlers threw.
  ReactErrorUtils.rethrowCaughtError();
}

function runExtractedEventsInBatch(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
  var events = extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget);
  runEventsInBatch(events, false);
}

var EventPluginHub = Object.freeze({
	injection: injection,
	getListener: getListener,
	runEventsInBatch: runEventsInBatch,
	runExtractedEventsInBatch: runExtractedEventsInBatch
});

var IndeterminateComponent = 0; // Before we know whether it is functional or class
var FunctionalComponent = 1;
var ClassComponent = 2;
var HostRoot = 3; // Root of a host tree. Could be nested inside another node.
var HostPortal = 4; // A subtree. Could be an entry point to a different renderer.
var HostComponent = 5;
var HostText = 6;



var Fragment = 10;
var Mode = 11;
var ContextConsumer = 12;
var ContextProvider = 13;
var ForwardRef = 14;
var Profiler = 15;
var TimeoutComponent = 16;

var randomKey = Math.random().toString(36).slice(2);
var internalInstanceKey = '__reactInternalInstance$' + randomKey;
var internalEventHandlersKey = '__reactEventHandlers$' + randomKey;

function precacheFiberNode(hostInst, node) {
  node[internalInstanceKey] = hostInst;
}

/**
 * Given a DOM node, return the closest ReactDOMComponent or
 * ReactDOMTextComponent instance ancestor.
 */
function getClosestInstanceFromNode(node) {
  if (node[internalInstanceKey]) {
    return node[internalInstanceKey];
  }

  while (!node[internalInstanceKey]) {
    if (node.parentNode) {
      node = node.parentNode;
    } else {
      // Top of the tree. This node must not be part of a React tree (or is
      // unmounted, potentially).
      return null;
    }
  }

  var inst = node[internalInstanceKey];
  if (inst.tag === HostComponent || inst.tag === HostText) {
    // In Fiber, this will always be the deepest root.
    return inst;
  }

  return null;
}

/**
 * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
 * instance, or null if the node was not rendered by this React.
 */
function getInstanceFromNode$1(node) {
  var inst = node[internalInstanceKey];
  if (inst) {
    if (inst.tag === HostComponent || inst.tag === HostText) {
      return inst;
    } else {
      return null;
    }
  }
  return null;
}

/**
 * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
 * DOM node.
 */
function getNodeFromInstance$1(inst) {
  if (inst.tag === HostComponent || inst.tag === HostText) {
    // In Fiber this, is just the state node right now. We assume it will be
    // a host component or host text.
    return inst.stateNode;
  }

  // Without this first invariant, passing a non-DOM-component triggers the next
  // invariant for a missing parent, which is super confusing.
  invariant(false, 'getNodeFromInstance: Invalid argument.');
}

function getFiberCurrentPropsFromNode$1(node) {
  return node[internalEventHandlersKey] || null;
}

function updateFiberProps(node, props) {
  node[internalEventHandlersKey] = props;
}

var ReactDOMComponentTree = Object.freeze({
	precacheFiberNode: precacheFiberNode,
	getClosestInstanceFromNode: getClosestInstanceFromNode,
	getInstanceFromNode: getInstanceFromNode$1,
	getNodeFromInstance: getNodeFromInstance$1,
	getFiberCurrentPropsFromNode: getFiberCurrentPropsFromNode$1,
	updateFiberProps: updateFiberProps
});

function getParent(inst) {
  do {
    inst = inst.return;
    // TODO: If this is a HostRoot we might want to bail out.
    // That is depending on if we want nested subtrees (layers) to bubble
    // events to their parent. We could also go through parentNode on the
    // host node but that wouldn't work for React Native and doesn't let us
    // do the portal feature.
  } while (inst && inst.tag !== HostComponent);
  if (inst) {
    return inst;
  }
  return null;
}

/**
 * Return the lowest common ancestor of A and B, or null if they are in
 * different trees.
 */
function getLowestCommonAncestor(instA, instB) {
  var depthA = 0;
  for (var tempA = instA; tempA; tempA = getParent(tempA)) {
    depthA++;
  }
  var depthB = 0;
  for (var tempB = instB; tempB; tempB = getParent(tempB)) {
    depthB++;
  }

  // If A is deeper, crawl up.
  while (depthA - depthB > 0) {
    instA = getParent(instA);
    depthA--;
  }

  // If B is deeper, crawl up.
  while (depthB - depthA > 0) {
    instB = getParent(instB);
    depthB--;
  }

  // Walk in lockstep until we find a match.
  var depth = depthA;
  while (depth--) {
    if (instA === instB || instA === instB.alternate) {
      return instA;
    }
    instA = getParent(instA);
    instB = getParent(instB);
  }
  return null;
}

/**
 * Return if A is an ancestor of B.
 */


/**
 * Return the parent instance of the passed-in instance.
 */
function getParentInstance(inst) {
  return getParent(inst);
}

/**
 * Simulates the traversal of a two-phase, capture/bubble event dispatch.
 */
function traverseTwoPhase(inst, fn, arg) {
  var path = [];
  while (inst) {
    path.push(inst);
    inst = getParent(inst);
  }
  var i = void 0;
  for (i = path.length; i-- > 0;) {
    fn(path[i], 'captured', arg);
  }
  for (i = 0; i < path.length; i++) {
    fn(path[i], 'bubbled', arg);
  }
}

/**
 * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
 * should would receive a `mouseEnter` or `mouseLeave` event.
 *
 * Does not invoke the callback on the nearest common ancestor because nothing
 * "entered" or "left" that element.
 */
function traverseEnterLeave(from, to, fn, argFrom, argTo) {
  var common = from && to ? getLowestCommonAncestor(from, to) : null;
  var pathFrom = [];
  while (true) {
    if (!from) {
      break;
    }
    if (from === common) {
      break;
    }
    var alternate = from.alternate;
    if (alternate !== null && alternate === common) {
      break;
    }
    pathFrom.push(from);
    from = getParent(from);
  }
  var pathTo = [];
  while (true) {
    if (!to) {
      break;
    }
    if (to === common) {
      break;
    }
    var _alternate = to.alternate;
    if (_alternate !== null && _alternate === common) {
      break;
    }
    pathTo.push(to);
    to = getParent(to);
  }
  for (var i = 0; i < pathFrom.length; i++) {
    fn(pathFrom[i], 'bubbled', argFrom);
  }
  for (var _i = pathTo.length; _i-- > 0;) {
    fn(pathTo[_i], 'captured', argTo);
  }
}

/**
 * Some event types have a notion of different registration names for different
 * "phases" of propagation. This finds listeners by a given phase.
 */
function listenerAtPhase(inst, event, propagationPhase) {
  var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
  return getListener(inst, registrationName);
}

/**
 * A small set of propagation patterns, each of which will accept a small amount
 * of information, and generate a set of "dispatch ready event objects" - which
 * are sets of events that have already been annotated with a set of dispatched
 * listener functions/ids. The API is designed this way to discourage these
 * propagation strategies from actually executing the dispatches, since we
 * always want to collect the entire set of dispatches before executing even a
 * single one.
 */

/**
 * Tags a `SyntheticEvent` with dispatched listeners. Creating this function
 * here, allows us to not have to bind or create functions for each event.
 * Mutating the event's members allows us to not have to create a wrapping
 * "dispatch" object that pairs the event with the listener.
 */
function accumulateDirectionalDispatches(inst, phase, event) {
  {
    !inst ? warning(false, 'Dispatching inst must not be null') : void 0;
  }
  var listener = listenerAtPhase(inst, event, phase);
  if (listener) {
    event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
    event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
  }
}

/**
 * Collect dispatches (must be entirely collected before dispatching - see unit
 * tests). Lazily allocate the array to conserve memory.  We must loop through
 * each event and perform the traversal for each one. We cannot perform a
 * single traversal for the entire collection of events because each event may
 * have a different target.
 */
function accumulateTwoPhaseDispatchesSingle(event) {
  if (event && event.dispatchConfig.phasedRegistrationNames) {
    traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
  }
}

/**
 * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID.
 */
function accumulateTwoPhaseDispatchesSingleSkipTarget(event) {
  if (event && event.dispatchConfig.phasedRegistrationNames) {
    var targetInst = event._targetInst;
    var parentInst = targetInst ? getParentInstance(targetInst) : null;
    traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event);
  }
}

/**
 * Accumulates without regard to direction, does not look for phased
 * registration names. Same as `accumulateDirectDispatchesSingle` but without
 * requiring that the `dispatchMarker` be the same as the dispatched ID.
 */
function accumulateDispatches(inst, ignoredDirection, event) {
  if (inst && event && event.dispatchConfig.registrationName) {
    var registrationName = event.dispatchConfig.registrationName;
    var listener = getListener(inst, registrationName);
    if (listener) {
      event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
      event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
    }
  }
}

/**
 * Accumulates dispatches on an `SyntheticEvent`, but only for the
 * `dispatchMarker`.
 * @param {SyntheticEvent} event
 */
function accumulateDirectDispatchesSingle(event) {
  if (event && event.dispatchConfig.registrationName) {
    accumulateDispatches(event._targetInst, null, event);
  }
}

function accumulateTwoPhaseDispatches(events) {
  forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
}

function accumulateTwoPhaseDispatchesSkipTarget(events) {
  forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget);
}

function accumulateEnterLeaveDispatches(leave, enter, from, to) {
  traverseEnterLeave(from, to, accumulateDispatches, leave, enter);
}

function accumulateDirectDispatches(events) {
  forEachAccumulated(events, accumulateDirectDispatchesSingle);
}

var EventPropagators = Object.freeze({
	accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches,
	accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget,
	accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches,
	accumulateDirectDispatches: accumulateDirectDispatches
});

// Do not uses the below two methods directly!
// Instead use constants exported from DOMTopLevelEventTypes in ReactDOM.
// (It is the only module that is allowed to access these methods.)

function unsafeCastStringToDOMTopLevelType(topLevelType) {
  return topLevelType;
}

function unsafeCastDOMTopLevelTypeToString(topLevelType) {
  return topLevelType;
}

/**
 * Generate a mapping of standard vendor prefixes using the defined style property and event name.
 *
 * @param {string} styleProp
 * @param {string} eventName
 * @returns {object}
 */
function makePrefixMap(styleProp, eventName) {
  var prefixes = {};

  prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
  prefixes['Webkit' + styleProp] = 'webkit' + eventName;
  prefixes['Moz' + styleProp] = 'moz' + eventName;
  prefixes['ms' + styleProp] = 'MS' + eventName;
  prefixes['O' + styleProp] = 'o' + eventName.toLowerCase();

  return prefixes;
}

/**
 * A list of event names to a configurable list of vendor prefixes.
 */
var vendorPrefixes = {
  animationend: makePrefixMap('Animation', 'AnimationEnd'),
  animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
  animationstart: makePrefixMap('Animation', 'AnimationStart'),
  transitionend: makePrefixMap('Transition', 'TransitionEnd')
};

/**
 * Event names that have already been detected and prefixed (if applicable).
 */
var prefixedEventNames = {};

/**
 * Element to check for prefixes on.
 */
var style = {};

/**
 * Bootstrap if a DOM exists.
 */
if (ExecutionEnvironment.canUseDOM) {
  style = document.createElement('div').style;

  // On some platforms, in particular some releases of Android 4.x,
  // the un-prefixed "animation" and "transition" properties are defined on the
  // style object but the events that fire will still be prefixed, so we need
  // to check if the un-prefixed events are usable, and if not remove them from the map.
  if (!('AnimationEvent' in window)) {
    delete vendorPrefixes.animationend.animation;
    delete vendorPrefixes.animationiteration.animation;
    delete vendorPrefixes.animationstart.animation;
  }

  // Same as above
  if (!('TransitionEvent' in window)) {
    delete vendorPrefixes.transitionend.transition;
  }
}

/**
 * Attempts to determine the correct vendor prefixed event name.
 *
 * @param {string} eventName
 * @returns {string}
 */
function getVendorPrefixedEventName(eventName) {
  if (prefixedEventNames[eventName]) {
    return prefixedEventNames[eventName];
  } else if (!vendorPrefixes[eventName]) {
    return eventName;
  }

  var prefixMap = vendorPrefixes[eventName];

  for (var styleProp in prefixMap) {
    if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
      return prefixedEventNames[eventName] = prefixMap[styleProp];
    }
  }

  return eventName;
}

/**
 * To identify top level events in ReactDOM, we use constants defined by this
 * module. This is the only module that uses the unsafe* methods to express
 * that the constants actually correspond to the browser event names. This lets
 * us save some bundle size by avoiding a top level type -> event name map.
 * The rest of ReactDOM code should import top level types from this file.
 */
var TOP_ABORT = unsafeCastStringToDOMTopLevelType('abort');
var TOP_ANIMATION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationend'));
var TOP_ANIMATION_ITERATION = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationiteration'));
var TOP_ANIMATION_START = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationstart'));
var TOP_BLUR = unsafeCastStringToDOMTopLevelType('blur');
var TOP_CAN_PLAY = unsafeCastStringToDOMTopLevelType('canplay');
var TOP_CAN_PLAY_THROUGH = unsafeCastStringToDOMTopLevelType('canplaythrough');
var TOP_CANCEL = unsafeCastStringToDOMTopLevelType('cancel');
var TOP_CHANGE = unsafeCastStringToDOMTopLevelType('change');
var TOP_CLICK = unsafeCastStringToDOMTopLevelType('click');
var TOP_CLOSE = unsafeCastStringToDOMTopLevelType('close');
var TOP_COMPOSITION_END = unsafeCastStringToDOMTopLevelType('compositionend');
var TOP_COMPOSITION_START = unsafeCastStringToDOMTopLevelType('compositionstart');
var TOP_COMPOSITION_UPDATE = unsafeCastStringToDOMTopLevelType('compositionupdate');
var TOP_CONTEXT_MENU = unsafeCastStringToDOMTopLevelType('contextmenu');
var TOP_COPY = unsafeCastStringToDOMTopLevelType('copy');
var TOP_CUT = unsafeCastStringToDOMTopLevelType('cut');
var TOP_DOUBLE_CLICK = unsafeCastStringToDOMTopLevelType('dblclick');
var TOP_DRAG = unsafeCastStringToDOMTopLevelType('drag');
var TOP_DRAG_END = unsafeCastStringToDOMTopLevelType('dragend');
var TOP_DRAG_ENTER = unsafeCastStringToDOMTopLevelType('dragenter');
var TOP_DRAG_EXIT = unsafeCastStringToDOMTopLevelType('dragexit');
var TOP_DRAG_LEAVE = unsafeCastStringToDOMTopLevelType('dragleave');
var TOP_DRAG_OVER = unsafeCastStringToDOMTopLevelType('dragover');
var TOP_DRAG_START = unsafeCastStringToDOMTopLevelType('dragstart');
var TOP_DROP = unsafeCastStringToDOMTopLevelType('drop');
var TOP_DURATION_CHANGE = unsafeCastStringToDOMTopLevelType('durationchange');
var TOP_EMPTIED = unsafeCastStringToDOMTopLevelType('emptied');
var TOP_ENCRYPTED = unsafeCastStringToDOMTopLevelType('encrypted');
var TOP_ENDED = unsafeCastStringToDOMTopLevelType('ended');
var TOP_ERROR = unsafeCastStringToDOMTopLevelType('error');
var TOP_FOCUS = unsafeCastStringToDOMTopLevelType('focus');
var TOP_GOT_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('gotpointercapture');
var TOP_INPUT = unsafeCastStringToDOMTopLevelType('input');
var TOP_INVALID = unsafeCastStringToDOMTopLevelType('invalid');
var TOP_KEY_DOWN = unsafeCastStringToDOMTopLevelType('keydown');
var TOP_KEY_PRESS = unsafeCastStringToDOMTopLevelType('keypress');
var TOP_KEY_UP = unsafeCastStringToDOMTopLevelType('keyup');
var TOP_LOAD = unsafeCastStringToDOMTopLevelType('load');
var TOP_LOAD_START = unsafeCastStringToDOMTopLevelType('loadstart');
var TOP_LOADED_DATA = unsafeCastStringToDOMTopLevelType('loadeddata');
var TOP_LOADED_METADATA = unsafeCastStringToDOMTopLevelType('loadedmetadata');
var TOP_LOST_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('lostpointercapture');
var TOP_MOUSE_DOWN = unsafeCastStringToDOMTopLevelType('mousedown');
var TOP_MOUSE_MOVE = unsafeCastStringToDOMTopLevelType('mousemove');
var TOP_MOUSE_OUT = unsafeCastStringToDOMTopLevelType('mouseout');
var TOP_MOUSE_OVER = unsafeCastStringToDOMTopLevelType('mouseover');
var TOP_MOUSE_UP = unsafeCastStringToDOMTopLevelType('mouseup');
var TOP_PASTE = unsafeCastStringToDOMTopLevelType('paste');
var TOP_PAUSE = unsafeCastStringToDOMTopLevelType('pause');
var TOP_PLAY = unsafeCastStringToDOMTopLevelType('play');
var TOP_PLAYING = unsafeCastStringToDOMTopLevelType('playing');
var TOP_POINTER_CANCEL = unsafeCastStringToDOMTopLevelType('pointercancel');
var TOP_POINTER_DOWN = unsafeCastStringToDOMTopLevelType('pointerdown');


var TOP_POINTER_MOVE = unsafeCastStringToDOMTopLevelType('pointermove');
var TOP_POINTER_OUT = unsafeCastStringToDOMTopLevelType('pointerout');
var TOP_POINTER_OVER = unsafeCastStringToDOMTopLevelType('pointerover');
var TOP_POINTER_UP = unsafeCastStringToDOMTopLevelType('pointerup');
var TOP_PROGRESS = unsafeCastStringToDOMTopLevelType('progress');
var TOP_RATE_CHANGE = unsafeCastStringToDOMTopLevelType('ratechange');
var TOP_RESET = unsafeCastStringToDOMTopLevelType('reset');
var TOP_SCROLL = unsafeCastStringToDOMTopLevelType('scroll');
var TOP_SEEKED = unsafeCastStringToDOMTopLevelType('seeked');
var TOP_SEEKING = unsafeCastStringToDOMTopLevelType('seeking');
var TOP_SELECTION_CHANGE = unsafeCastStringToDOMTopLevelType('selectionchange');
var TOP_STALLED = unsafeCastStringToDOMTopLevelType('stalled');
var TOP_SUBMIT = unsafeCastStringToDOMTopLevelType('submit');
var TOP_SUSPEND = unsafeCastStringToDOMTopLevelType('suspend');
var TOP_TEXT_INPUT = unsafeCastStringToDOMTopLevelType('textInput');
var TOP_TIME_UPDATE = unsafeCastStringToDOMTopLevelType('timeupdate');
var TOP_TOGGLE = unsafeCastStringToDOMTopLevelType('toggle');
var TOP_TOUCH_CANCEL = unsafeCastStringToDOMTopLevelType('touchcancel');
var TOP_TOUCH_END = unsafeCastStringToDOMTopLevelType('touchend');
var TOP_TOUCH_MOVE = unsafeCastStringToDOMTopLevelType('touchmove');
var TOP_TOUCH_START = unsafeCastStringToDOMTopLevelType('touchstart');
var TOP_TRANSITION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('transitionend'));
var TOP_VOLUME_CHANGE = unsafeCastStringToDOMTopLevelType('volumechange');
var TOP_WAITING = unsafeCastStringToDOMTopLevelType('waiting');
var TOP_WHEEL = unsafeCastStringToDOMTopLevelType('wheel');

// List of events that need to be individually attached to media elements.
// Note that events in this list will *not* be listened to at the top level
// unless they're explicitly whitelisted in `ReactBrowserEventEmitter.listenTo`.
var mediaEventTypes = [TOP_ABORT, TOP_CAN_PLAY, TOP_CAN_PLAY_THROUGH, TOP_DURATION_CHANGE, TOP_EMPTIED, TOP_ENCRYPTED, TOP_ENDED, TOP_ERROR, TOP_LOADED_DATA, TOP_LOADED_METADATA, TOP_LOAD_START, TOP_PAUSE, TOP_PLAY, TOP_PLAYING, TOP_PROGRESS, TOP_RATE_CHANGE, TOP_SEEKED, TOP_SEEKING, TOP_STALLED, TOP_SUSPEND, TOP_TIME_UPDATE, TOP_VOLUME_CHANGE, TOP_WAITING];

function getRawEventName(topLevelType) {
  return unsafeCastDOMTopLevelTypeToString(topLevelType);
}

var contentKey = null;

/**
 * Gets the key used to access text content on a DOM node.
 *
 * @return {?string} Key used to access text content.
 * @internal
 */
function getTextContentAccessor() {
  if (!contentKey && ExecutionEnvironment.canUseDOM) {
    // Prefer textContent to innerText because many browsers support both but
    // SVG <text> elements don't support innerText even when <div> does.
    contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText';
  }
  return contentKey;
}

/**
 * This helper object stores information about text content of a target node,
 * allowing comparison of content before and after a given event.
 *
 * Identify the node where selection currently begins, then observe
 * both its text content and its current position in the DOM. Since the
 * browser may natively replace the target node during composition, we can
 * use its position to find its replacement.
 *
 *
 */
var compositionState = {
  _root: null,
  _startText: null,
  _fallbackText: null
};

function initialize(nativeEventTarget) {
  compositionState._root = nativeEventTarget;
  compositionState._startText = getText();
  return true;
}

function reset() {
  compositionState._root = null;
  compositionState._startText = null;
  compositionState._fallbackText = null;
}

function getData() {
  if (compositionState._fallbackText) {
    return compositionState._fallbackText;
  }

  var start = void 0;
  var startValue = compositionState._startText;
  var startLength = startValue.length;
  var end = void 0;
  var endValue = getText();
  var endLength = endValue.length;

  for (start = 0; start < startLength; start++) {
    if (startValue[start] !== endValue[start]) {
      break;
    }
  }

  var minEnd = startLength - start;
  for (end = 1; end <= minEnd; end++) {
    if (startValue[startLength - end] !== endValue[endLength - end]) {
      break;
    }
  }

  var sliceTail = end > 1 ? 1 - end : undefined;
  compositionState._fallbackText = endValue.slice(start, sliceTail);
  return compositionState._fallbackText;
}

function getText() {
  if ('value' in compositionState._root) {
    return compositionState._root.value;
  }
  return compositionState._root[getTextContentAccessor()];
}

/* eslint valid-typeof: 0 */

var didWarnForAddedNewProperty = false;
var EVENT_POOL_SIZE = 10;

var shouldBeReleasedProperties = ['dispatchConfig', '_targetInst', 'nativeEvent', 'isDefaultPrevented', 'isPropagationStopped', '_dispatchListeners', '_dispatchInstances'];

/**
 * @interface Event
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */
var EventInterface = {
  type: null,
  target: null,
  // currentTarget is set when dispatching; no use in copying it here
  currentTarget: emptyFunction.thatReturnsNull,
  eventPhase: null,
  bubbles: null,
  cancelable: null,
  timeStamp: function (event) {
    return event.timeStamp || Date.now();
  },
  defaultPrevented: null,
  isTrusted: null
};

/**
 * Synthetic events are dispatched by event plugins, typically in response to a
 * top-level event delegation handler.
 *
 * These systems should generally use pooling to reduce the frequency of garbage
 * collection. The system should check `isPersistent` to determine whether the
 * event should be released into the pool after being dispatched. Users that
 * need a persisted event should invoke `persist`.
 *
 * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
 * normalizing browser quirks. Subclasses do not necessarily have to implement a
 * DOM interface; custom application-specific events can also subclass this.
 *
 * @param {object} dispatchConfig Configuration used to dispatch this event.
 * @param {*} targetInst Marker identifying the event target.
 * @param {object} nativeEvent Native browser event.
 * @param {DOMEventTarget} nativeEventTarget Target node.
 */
function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
  {
    // these have a getter/setter for warnings
    delete this.nativeEvent;
    delete this.preventDefault;
    delete this.stopPropagation;
  }

  this.dispatchConfig = dispatchConfig;
  this._targetInst = targetInst;
  this.nativeEvent = nativeEvent;

  var Interface = this.constructor.Interface;
  for (var propName in Interface) {
    if (!Interface.hasOwnProperty(propName)) {
      continue;
    }
    {
      delete this[propName]; // this has a getter/setter for warnings
    }
    var normalize = Interface[propName];
    if (normalize) {
      this[propName] = normalize(nativeEvent);
    } else {
      if (propName === 'target') {
        this.target = nativeEventTarget;
      } else {
        this[propName] = nativeEvent[propName];
      }
    }
  }

  var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
  if (defaultPrevented) {
    this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
  } else {
    this.isDefaultPrevented = emptyFunction.thatReturnsFalse;
  }
  this.isPropagationStopped = emptyFunction.thatReturnsFalse;
  return this;
}

_assign(SyntheticEvent.prototype, {
  preventDefault: function () {
    this.defaultPrevented = true;
    var event = this.nativeEvent;
    if (!event) {
      return;
    }

    if (event.preventDefault) {
      event.preventDefault();
    } else if (typeof event.returnValue !== 'unknown') {
      event.returnValue = false;
    }
    this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
  },

  stopPropagation: function () {
    var event = this.nativeEvent;
    if (!event) {
      return;
    }

    if (event.stopPropagation) {
      event.stopPropagation();
    } else if (typeof event.cancelBubble !== 'unknown') {
      // The ChangeEventPlugin registers a "propertychange" event for
      // IE. This event does not support bubbling or cancelling, and
      // any references to cancelBubble throw "Member not found".  A
      // typeof check of "unknown" circumvents this issue (and is also
      // IE specific).
      event.cancelBubble = true;
    }

    this.isPropagationStopped = emptyFunction.thatReturnsTrue;
  },

  /**
   * We release all dispatched `SyntheticEvent`s after each event loop, adding
   * them back into the pool. This allows a way to hold onto a reference that
   * won't be added back into the pool.
   */
  persist: function () {
    this.isPersistent = emptyFunction.thatReturnsTrue;
  },

  /**
   * Checks if this event should be released back into the pool.
   *
   * @return {boolean} True if this should not be released, false otherwise.
   */
  isPersistent: emptyFunction.thatReturnsFalse,

  /**
   * `PooledClass` looks for `destructor` on each instance it releases.
   */
  destructor: function () {
    var Interface = this.constructor.Interface;
    for (var propName in Interface) {
      {
        Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
      }
    }
    for (var i = 0; i < shouldBeReleasedProperties.length; i++) {
      this[shouldBeReleasedProperties[i]] = null;
    }
    {
      Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
      Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', emptyFunction));
      Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', emptyFunction));
    }
  }
});

SyntheticEvent.Interface = EventInterface;

/**
 * Helper to reduce boilerplate when creating subclasses.
 */
SyntheticEvent.extend = function (Interface) {
  var Super = this;

  var E = function () {};
  E.prototype = Super.prototype;
  var prototype = new E();

  function Class() {
    return Super.apply(this, arguments);
  }
  _assign(prototype, Class.prototype);
  Class.prototype = prototype;
  Class.prototype.constructor = Class;

  Class.Interface = _assign({}, Super.Interface, Interface);
  Class.extend = Super.extend;
  addEventPoolingTo(Class);

  return Class;
};

/** Proxying after everything set on SyntheticEvent
 * to resolve Proxy issue on some WebKit browsers
 * in which some Event properties are set to undefined (GH#10010)
 */
{
  var isProxySupported = typeof Proxy === 'function' &&
  // https://github.com/facebook/react/issues/12011
  !Object.isSealed(new Proxy({}, {}));

  if (isProxySupported) {
    /*eslint-disable no-func-assign */
    SyntheticEvent = new Proxy(SyntheticEvent, {
      construct: function (target, args) {
        return this.apply(target, Object.create(target.prototype), args);
      },
      apply: function (constructor, that, args) {
        return new Proxy(constructor.apply(that, args), {
          set: function (target, prop, value) {
            if (prop !== 'isPersistent' && !target.constructor.Interface.hasOwnProperty(prop) && shouldBeReleasedProperties.indexOf(prop) === -1) {
              !(didWarnForAddedNewProperty || target.isPersistent()) ? warning(false, "This synthetic event is reused for performance reasons. If you're " + "seeing this, you're adding a new property in the synthetic event object. " + 'The property is never released. See ' + 'https://fb.me/react-event-pooling for more information.') : void 0;
              didWarnForAddedNewProperty = true;
            }
            target[prop] = value;
            return true;
          }
        });
      }
    });
    /*eslint-enable no-func-assign */
  }
}

addEventPoolingTo(SyntheticEvent);

/**
 * Helper to nullify syntheticEvent instance properties when destructing
 *
 * @param {String} propName
 * @param {?object} getVal
 * @return {object} defineProperty object
 */
function getPooledWarningPropertyDefinition(propName, getVal) {
  var isFunction = typeof getVal === 'function';
  return {
    configurable: true,
    set: set,
    get: get
  };

  function set(val) {
    var action = isFunction ? 'setting the method' : 'setting the property';
    warn(action, 'This is effectively a no-op');
    return val;
  }

  function get() {
    var action = isFunction ? 'accessing the method' : 'accessing the property';
    var result = isFunction ? 'This is a no-op function' : 'This is set to null';
    warn(action, result);
    return getVal;
  }

  function warn(action, result) {
    var warningCondition = false;
    !warningCondition ? warning(false, "This synthetic event is reused for performance reasons. If you're seeing this, " + "you're %s `%s` on a released/nullified synthetic event. %s. " + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result) : void 0;
  }
}

function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) {
  var EventConstructor = this;
  if (EventConstructor.eventPool.length) {
    var instance = EventConstructor.eventPool.pop();
    EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst);
    return instance;
  }
  return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst);
}

function releasePooledEvent(event) {
  var EventConstructor = this;
  !(event instanceof EventConstructor) ? invariant(false, 'Trying to release an event instance  into a pool of a different type.') : void 0;
  event.destructor();
  if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) {
    EventConstructor.eventPool.push(event);
  }
}

function addEventPoolingTo(EventConstructor) {
  EventConstructor.eventPool = [];
  EventConstructor.getPooled = getPooledEvent;
  EventConstructor.release = releasePooledEvent;
}

var SyntheticEvent$1 = SyntheticEvent;

/**
 * @interface Event
 * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
 */
var SyntheticCompositionEvent = SyntheticEvent$1.extend({
  data: null
});

/**
 * @interface Event
 * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
 *      /#events-inputevents
 */
var SyntheticInputEvent = SyntheticEvent$1.extend({
  data: null
});

var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
var START_KEYCODE = 229;

var canUseCompositionEvent = ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window;

var documentMode = null;
if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) {
  documentMode = document.documentMode;
}

// Webkit offers a very useful `textInput` event that can be used to
// directly represent `beforeInput`. The IE `textinput` event is not as
// useful, so we don't use it.
var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode;

// In IE9+, we have access to composition events, but the data supplied
// by the native compositionend event may be incorrect. Japanese ideographic
// spaces, for instance (\u3000) are not recorded correctly.
var useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);

var SPACEBAR_CODE = 32;
var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE);

// Events and their corresponding property names.
var eventTypes = {
  beforeInput: {
    phasedRegistrationNames: {
      bubbled: 'onBeforeInput',
      captured: 'onBeforeInputCapture'
    },
    dependencies: [TOP_COMPOSITION_END, TOP_KEY_PRESS, TOP_TEXT_INPUT, TOP_PASTE]
  },
  compositionEnd: {
    phasedRegistrationNames: {
      bubbled: 'onCompositionEnd',
      captured: 'onCompositionEndCapture'
    },
    dependencies: [TOP_BLUR, TOP_COMPOSITION_END, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
  },
  compositionStart: {
    phasedRegistrationNames: {
      bubbled: 'onCompositionStart',
      captured: 'onCompositionStartCapture'
    },
    dependencies: [TOP_BLUR, TOP_COMPOSITION_START, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
  },
  compositionUpdate: {
    phasedRegistrationNames: {
      bubbled: 'onCompositionUpdate',
      captured: 'onCompositionUpdateCapture'
    },
    dependencies: [TOP_BLUR, TOP_COMPOSITION_UPDATE, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
  }
};

// Track whether we've ever handled a keypress on the space key.
var hasSpaceKeypress = false;

/**
 * Return whether a native keypress event is assumed to be a command.
 * This is required because Firefox fires `keypress` events for key commands
 * (cut, copy, select-all, etc.) even though no character is inserted.
 */
function isKeypressCommand(nativeEvent) {
  return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) &&
  // ctrlKey && altKey is equivalent to AltGr, and is not a command.
  !(nativeEvent.ctrlKey && nativeEvent.altKey);
}

/**
 * Translate native top level events into event types.
 *
 * @param {string} topLevelType
 * @return {object}
 */
function getCompositionEventType(topLevelType) {
  switch (topLevelType) {
    case TOP_COMPOSITION_START:
      return eventTypes.compositionStart;
    case TOP_COMPOSITION_END:
      return eventTypes.compositionEnd;
    case TOP_COMPOSITION_UPDATE:
      return eventTypes.compositionUpdate;
  }
}

/**
 * Does our fallback best-guess model think this event signifies that
 * composition has begun?
 *
 * @param {string} topLevelType
 * @param {object} nativeEvent
 * @return {boolean}
 */
function isFallbackCompositionStart(topLevelType, nativeEvent) {
  return topLevelType === TOP_KEY_DOWN && nativeEvent.keyCode === START_KEYCODE;
}

/**
 * Does our fallback mode think that this event is the end of composition?
 *
 * @param {string} topLevelType
 * @param {object} nativeEvent
 * @return {boolean}
 */
function isFallbackCompositionEnd(topLevelType, nativeEvent) {
  switch (topLevelType) {
    case TOP_KEY_UP:
      // Command keys insert or clear IME input.
      return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
    case TOP_KEY_DOWN:
      // Expect IME keyCode on each keydown. If we get any other
      // code we must have exited earlier.
      return nativeEvent.keyCode !== START_KEYCODE;
    case TOP_KEY_PRESS:
    case TOP_MOUSE_DOWN:
    case TOP_BLUR:
      // Events are not possible without cancelling IME.
      return true;
    default:
      return false;
  }
}

/**
 * Google Input Tools provides composition data via a CustomEvent,
 * with the `data` property populated in the `detail` object. If this
 * is available on the event object, use it. If not, this is a plain
 * composition event and we have nothing special to extract.
 *
 * @param {object} nativeEvent
 * @return {?string}
 */
function getDataFromCustomEvent(nativeEvent) {
  var detail = nativeEvent.detail;
  if (typeof detail === 'object' && 'data' in detail) {
    return detail.data;
  }
  return null;
}

// Track the current IME composition status, if any.
var isComposing = false;

/**
 * @return {?object} A SyntheticCompositionEvent.
 */
function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
  var eventType = void 0;
  var fallbackData = void 0;

  if (canUseCompositionEvent) {
    eventType = getCompositionEventType(topLevelType);
  } else if (!isComposing) {
    if (isFallbackCompositionStart(topLevelType, nativeEvent)) {
      eventType = eventTypes.compositionStart;
    }
  } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) {
    eventType = eventTypes.compositionEnd;
  }

  if (!eventType) {
    return null;
  }

  if (useFallbackCompositionData) {
    // The current composition is stored statically and must not be
    // overwritten while composition continues.
    if (!isComposing && eventType === eventTypes.compositionStart) {
      isComposing = initialize(nativeEventTarget);
    } else if (eventType === eventTypes.compositionEnd) {
      if (isComposing) {
        fallbackData = getData();
      }
    }
  }

  var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget);

  if (fallbackData) {
    // Inject data generated from fallback path into the synthetic event.
    // This matches the property of native CompositionEventInterface.
    event.data = fallbackData;
  } else {
    var customData = getDataFromCustomEvent(nativeEvent);
    if (customData !== null) {
      event.data = customData;
    }
  }

  accumulateTwoPhaseDispatches(event);
  return event;
}

/**
 * @param {TopLevelType} topLevelType Number from `TopLevelType`.
 * @param {object} nativeEvent Native browser event.
 * @return {?string} The string corresponding to this `beforeInput` event.
 */
function getNativeBeforeInputChars(topLevelType, nativeEvent) {
  switch (topLevelType) {
    case TOP_COMPOSITION_END:
      return getDataFromCustomEvent(nativeEvent);
    case TOP_KEY_PRESS:
      /**
       * If native `textInput` events are available, our goal is to make
       * use of them. However, there is a special case: the spacebar key.
       * In Webkit, preventing default on a spacebar `textInput` event
       * cancels character insertion, but it *also* causes the browser
       * to fall back to its default spacebar behavior of scrolling the
       * page.
       *
       * Tracking at:
       * https://code.google.com/p/chromium/issues/detail?id=355103
       *
       * To avoid this issue, use the keypress event as if no `textInput`
       * event is available.
       */
      var which = nativeEvent.which;
      if (which !== SPACEBAR_CODE) {
        return null;
      }

      hasSpaceKeypress = true;
      return SPACEBAR_CHAR;

    case TOP_TEXT_INPUT:
      // Record the characters to be added to the DOM.
      var chars = nativeEvent.data;

      // If it's a spacebar character, assume that we have already handled
      // it at the keypress level and bail immediately. Android Chrome
      // doesn't give us keycodes, so we need to blacklist it.
      if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
        return null;
      }

      return chars;

    default:
      // For other native event types, do nothing.
      return null;
  }
}

/**
 * For browsers that do not provide the `textInput` event, extract the
 * appropriate string to use for SyntheticInputEvent.
 *
 * @param {number} topLevelType Number from `TopLevelEventTypes`.
 * @param {object} nativeEvent Native browser event.
 * @return {?string} The fallback string for this `beforeInput` event.
 */
function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
  // If we are currently composing (IME) and using a fallback to do so,
  // try to extract the composed characters from the fallback object.
  // If composition event is available, we extract a string only at
  // compositionevent, otherwise extract it at fallback events.
  if (isComposing) {
    if (topLevelType === TOP_COMPOSITION_END || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) {
      var chars = getData();
      reset();
      isComposing = false;
      return chars;
    }
    return null;
  }

  switch (topLevelType) {
    case TOP_PASTE:
      // If a paste event occurs after a keypress, throw out the input
      // chars. Paste events should not lead to BeforeInput events.
      return null;
    case TOP_KEY_PRESS:
      /**
       * As of v27, Firefox may fire keypress events even when no character
       * will be inserted. A few possibilities:
       *
       * - `which` is `0`. Arrow keys, Esc key, etc.
       *
       * - `which` is the pressed key code, but no char is available.
       *   Ex: 'AltGr + d` in Polish. There is no modified character for
       *   this key combination and no character is inserted into the
       *   document, but FF fires the keypress for char code `100` anyway.
       *   No `input` event will occur.
       *
       * - `which` is the pressed key code, but a command combination is
       *   being used. Ex: `Cmd+C`. No character is inserted, and no
       *   `input` event will occur.
       */
      if (!isKeypressCommand(nativeEvent)) {
        // IE fires the `keypress` event when a user types an emoji via
        // Touch keyboard of Windows.  In such a case, the `char` property
        // holds an emoji character like `\uD83D\uDE0A`.  Because its length
        // is 2, the property `which` does not represent an emoji correctly.
        // In such a case, we directly return the `char` property instead of
        // using `which`.
        if (nativeEvent.char && nativeEvent.char.length > 1) {
          return nativeEvent.char;
        } else if (nativeEvent.which) {
          return String.fromCharCode(nativeEvent.which);
        }
      }
      return null;
    case TOP_COMPOSITION_END:
      return useFallbackCompositionData ? null : nativeEvent.data;
    default:
      return null;
  }
}

/**
 * Extract a SyntheticInputEvent for `beforeInput`, based on either native
 * `textInput` or fallback behavior.
 *
 * @return {?object} A SyntheticInputEvent.
 */
function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
  var chars = void 0;

  if (canUseTextInputEvent) {
    chars = getNativeBeforeInputChars(topLevelType, nativeEvent);
  } else {
    chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);
  }

  // If no characters are being inserted, no BeforeInput event should
  // be fired.
  if (!chars) {
    return null;
  }

  var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget);

  event.data = chars;
  accumulateTwoPhaseDispatches(event);
  return event;
}

/**
 * Create an `onBeforeInput` event to match
 * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
 *
 * This event plugin is based on the native `textInput` event
 * available in Chrome, Safari, Opera, and IE. This event fires after
 * `onKeyPress` and `onCompositionEnd`, but before `onInput`.
 *
 * `beforeInput` is spec'd but not implemented in any browsers, and
 * the `input` event does not provide any useful information about what has
 * actually been added, contrary to the spec. Thus, `textInput` is the best
 * available event to identify the characters that have actually been inserted
 * into the target node.
 *
 * This plugin is also responsible for emitting `composition` events, thus
 * allowing us to share composition fallback code for both `beforeInput` and
 * `composition` event types.
 */
var BeforeInputEventPlugin = {
  eventTypes: eventTypes,

  extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
    var composition = extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);

    var beforeInput = extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);

    if (composition === null) {
      return beforeInput;
    }

    if (beforeInput === null) {
      return composition;
    }

    return [composition, beforeInput];
  }
};

// Use to restore controlled state after a change event has fired.

var fiberHostComponent = null;

var ReactControlledComponentInjection = {
  injectFiberControlledHostComponent: function (hostComponentImpl) {
    // The fiber implementation doesn't use dynamic dispatch so we need to
    // inject the implementation.
    fiberHostComponent = hostComponentImpl;
  }
};

var restoreTarget = null;
var restoreQueue = null;

function restoreStateOfTarget(target) {
  // We perform this translation at the end of the event loop so that we
  // always receive the correct fiber here
  var internalInstance = getInstanceFromNode(target);
  if (!internalInstance) {
    // Unmounted
    return;
  }
  !(fiberHostComponent && typeof fiberHostComponent.restoreControlledState === 'function') ? invariant(false, 'Fiber needs to be injected to handle a fiber target for controlled events. This error is likely caused by a bug in React. Please file an issue.') : void 0;
  var props = getFiberCurrentPropsFromNode(internalInstance.stateNode);
  fiberHostComponent.restoreControlledState(internalInstance.stateNode, internalInstance.type, props);
}

var injection$2 = ReactControlledComponentInjection;

function enqueueStateRestore(target) {
  if (restoreTarget) {
    if (restoreQueue) {
      restoreQueue.push(target);
    } else {
      restoreQueue = [target];
    }
  } else {
    restoreTarget = target;
  }
}

function needsStateRestore() {
  return restoreTarget !== null || restoreQueue !== null;
}

function restoreStateIfNeeded() {
  if (!restoreTarget) {
    return;
  }
  var target = restoreTarget;
  var queuedTargets = restoreQueue;
  restoreTarget = null;
  restoreQueue = null;

  restoreStateOfTarget(target);
  if (queuedTargets) {
    for (var i = 0; i < queuedTargets.length; i++) {
      restoreStateOfTarget(queuedTargets[i]);
    }
  }
}

var ReactControlledComponent = Object.freeze({
	injection: injection$2,
	enqueueStateRestore: enqueueStateRestore,
	needsStateRestore: needsStateRestore,
	restoreStateIfNeeded: restoreStateIfNeeded
});

// Used as a way to call batchedUpdates when we don't have a reference to
// the renderer. Such as when we're dispatching events or if third party
// libraries need to call batchedUpdates. Eventually, this API will go away when
// everything is batched by default. We'll then have a similar API to opt-out of
// scheduled work and instead do synchronous work.

// Defaults
var _batchedUpdates = function (fn, bookkeeping) {
  return fn(bookkeeping);
};
var _interactiveUpdates = function (fn, a, b) {
  return fn(a, b);
};
var _flushInteractiveUpdates = function () {};

var isBatching = false;
function batchedUpdates(fn, bookkeeping) {
  if (isBatching) {
    // If we are currently inside another batch, we need to wait until it
    // fully completes before restoring state.
    return fn(bookkeeping);
  }
  isBatching = true;
  try {
    return _batchedUpdates(fn, bookkeeping);
  } finally {
    // Here we wait until all updates have propagated, which is important
    // when using controlled components within layers:
    // https://github.com/facebook/react/issues/1698
    // Then we restore state of any controlled component.
    isBatching = false;
    var controlledComponentsHavePendingUpdates = needsStateRestore();
    if (controlledComponentsHavePendingUpdates) {
      // If a controlled event was fired, we may need to restore the state of
      // the DOM node back to the controlled value. This is necessary when React
      // bails out of the update without touching the DOM.
      _flushInteractiveUpdates();
      restoreStateIfNeeded();
    }
  }
}

function interactiveUpdates(fn, a, b) {
  return _interactiveUpdates(fn, a, b);
}



var injection$3 = {
  injectRenderer: function (renderer) {
    _batchedUpdates = renderer.batchedUpdates;
    _interactiveUpdates = renderer.interactiveUpdates;
    _flushInteractiveUpdates = renderer.flushInteractiveUpdates;
  }
};

/**
 * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
 */
var supportedInputTypes = {
  color: true,
  date: true,
  datetime: true,
  'datetime-local': true,
  email: true,
  month: true,
  number: true,
  password: true,
  range: true,
  search: true,
  tel: true,
  text: true,
  time: true,
  url: true,
  week: true
};

function isTextInputElement(elem) {
  var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();

  if (nodeName === 'input') {
    return !!supportedInputTypes[elem.type];
  }

  if (nodeName === 'textarea') {
    return true;
  }

  return false;
}

/**
 * HTML nodeType values that represent the type of the node
 */

var ELEMENT_NODE = 1;
var TEXT_NODE = 3;
var COMMENT_NODE = 8;
var DOCUMENT_NODE = 9;
var DOCUMENT_FRAGMENT_NODE = 11;

/**
 * Gets the target node from a native browser event by accounting for
 * inconsistencies in browser DOM APIs.
 *
 * @param {object} nativeEvent Native browser event.
 * @return {DOMEventTarget} Target node.
 */
function getEventTarget(nativeEvent) {
  // Fallback to nativeEvent.srcElement for IE9
  // https://github.com/facebook/react/issues/12506
  var target = nativeEvent.target || nativeEvent.srcElement || window;

  // Normalize SVG <use> element events #4963
  if (target.correspondingUseElement) {
    target = target.correspondingUseElement;
  }

  // Safari may fire events on text nodes (Node.TEXT_NODE is 3).
  // @see http://www.quirksmode.org/js/events_properties.html
  return target.nodeType === TEXT_NODE ? target.parentNode : target;
}

/**
 * Checks if an event is supported in the current execution environment.
 *
 * NOTE: This will not work correctly for non-generic events such as `change`,
 * `reset`, `load`, `error`, and `select`.
 *
 * Borrows from Modernizr.
 *
 * @param {string} eventNameSuffix Event name, e.g. "click".
 * @param {?boolean} capture Check if the capture phase is supported.
 * @return {boolean} True if the event is supported.
 * @internal
 * @license Modernizr 3.0.0pre (Custom Build) | MIT
 */
function isEventSupported(eventNameSuffix, capture) {
  if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) {
    return false;
  }

  var eventName = 'on' + eventNameSuffix;
  var isSupported = eventName in document;

  if (!isSupported) {
    var element = document.createElement('div');
    element.setAttribute(eventName, 'return;');
    isSupported = typeof element[eventName] === 'function';
  }

  return isSupported;
}

function isCheckable(elem) {
  var type = elem.type;
  var nodeName = elem.nodeName;
  return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio');
}

function getTracker(node) {
  return node._valueTracker;
}

function detachTracker(node) {
  node._valueTracker = null;
}

function getValueFromNode(node) {
  var value = '';
  if (!node) {
    return value;
  }

  if (isCheckable(node)) {
    value = node.checked ? 'true' : 'false';
  } else {
    value = node.value;
  }

  return value;
}

function trackValueOnNode(node) {
  var valueField = isCheckable(node) ? 'checked' : 'value';
  var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField);

  var currentValue = '' + node[valueField];

  // if someone has already defined a value or Safari, then bail
  // and don't track value will cause over reporting of changes,
  // but it's better then a hard failure
  // (needed for certain tests that spyOn input values and Safari)
  if (node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') {
    return;
  }
  var get = descriptor.get,
      set = descriptor.set;

  Object.defineProperty(node, valueField, {
    configurable: true,
    get: function () {
      return get.call(this);
    },
    set: function (value) {
      currentValue = '' + value;
      set.call(this, value);
    }
  });
  // We could've passed this the first time
  // but it triggers a bug in IE11 and Edge 14/15.
  // Calling defineProperty() again should be equivalent.
  // https://github.com/facebook/react/issues/11768
  Object.defineProperty(node, valueField, {
    enumerable: descriptor.enumerable
  });

  var tracker = {
    getValue: function () {
      return currentValue;
    },
    setValue: function (value) {
      currentValue = '' + value;
    },
    stopTracking: function () {
      detachTracker(node);
      delete node[valueField];
    }
  };
  return tracker;
}

function track(node) {
  if (getTracker(node)) {
    return;
  }

  // TODO: Once it's just Fiber we can move this to node._wrapperState
  node._valueTracker = trackValueOnNode(node);
}

function updateValueIfChanged(node) {
  if (!node) {
    return false;
  }

  var tracker = getTracker(node);
  // if there is no tracker at this point it's unlikely
  // that trying again will succeed
  if (!tracker) {
    return true;
  }

  var lastValue = tracker.getValue();
  var nextValue = getValueFromNode(node);
  if (nextValue !== lastValue) {
    tracker.setValue(nextValue);
    return true;
  }
  return false;
}

var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;

var ReactCurrentOwner = ReactInternals.ReactCurrentOwner;
var ReactDebugCurrentFrame = ReactInternals.ReactDebugCurrentFrame;

var describeComponentFrame = function (name, source, ownerName) {
  return '\n    in ' + (name || 'Unknown') + (source ? ' (at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' + source.lineNumber + ')' : ownerName ? ' (created by ' + ownerName + ')' : '');
};

// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var hasSymbol = typeof Symbol === 'function' && Symbol.for;

var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace;
var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;
var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
var REACT_TIMEOUT_TYPE = hasSymbol ? Symbol.for('react.timeout') : 0xead1;

var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator';

function getIteratorFn(maybeIterable) {
  if (maybeIterable === null || typeof maybeIterable === 'undefined') {
    return null;
  }
  var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
  if (typeof maybeIterator === 'function') {
    return maybeIterator;
  }
  return null;
}

function getComponentName(fiber) {
  var type = fiber.type;

  if (typeof type === 'function') {
    return type.displayName || type.name;
  }
  if (typeof type === 'string') {
    return type;
  }
  switch (type) {
    case REACT_ASYNC_MODE_TYPE:
      return 'AsyncMode';
    case REACT_CONTEXT_TYPE:
      return 'Context.Consumer';
    case REACT_FRAGMENT_TYPE:
      return 'ReactFragment';
    case REACT_PORTAL_TYPE:
      return 'ReactPortal';
    case REACT_PROFILER_TYPE:
      return 'Profiler(' + fiber.pendingProps.id + ')';
    case REACT_PROVIDER_TYPE:
      return 'Context.Provider';
    case REACT_STRICT_MODE_TYPE:
      return 'StrictMode';
    case REACT_TIMEOUT_TYPE:
      return 'Timeout';
  }
  if (typeof type === 'object' && type !== null) {
    switch (type.$$typeof) {
      case REACT_FORWARD_REF_TYPE:
        var functionName = type.render.displayName || type.render.name || '';
        return functionName !== '' ? 'ForwardRef(' + functionName + ')' : 'ForwardRef';
    }
  }
  return null;
}

function describeFiber(fiber) {
  switch (fiber.tag) {
    case IndeterminateComponent:
    case FunctionalComponent:
    case ClassComponent:
    case HostComponent:
      var owner = fiber._debugOwner;
      var source = fiber._debugSource;
      var name = getComponentName(fiber);
      var ownerName = null;
      if (owner) {
        ownerName = getComponentName(owner);
      }
      return describeComponentFrame(name, source, ownerName);
    default:
      return '';
  }
}

// This function can only be called with a work-in-progress fiber and
// only during begin or complete phase. Do not call it under any other
// circumstances.
function getStackAddendumByWorkInProgressFiber(workInProgress) {
  var info = '';
  var node = workInProgress;
  do {
    info += describeFiber(node);
    // Otherwise this return pointer might point to the wrong tree:
    node = node.return;
  } while (node);
  return info;
}

function getCurrentFiberOwnerName$1() {
  {
    var fiber = ReactDebugCurrentFiber.current;
    if (fiber === null) {
      return null;
    }
    var owner = fiber._debugOwner;
    if (owner !== null && typeof owner !== 'undefined') {
      return getComponentName(owner);
    }
  }
  return null;
}

function getCurrentFiberStackAddendum$1() {
  {
    var fiber = ReactDebugCurrentFiber.current;
    if (fiber === null) {
      return null;
    }
    // Safe because if current fiber exists, we are reconciling,
    // and it is guaranteed to be the work-in-progress version.
    return getStackAddendumByWorkInProgressFiber(fiber);
  }
  return null;
}

function resetCurrentFiber() {
  ReactDebugCurrentFrame.getCurrentStack = null;
  ReactDebugCurrentFiber.current = null;
  ReactDebugCurrentFiber.phase = null;
}

function setCurrentFiber(fiber) {
  ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackAddendum$1;
  ReactDebugCurrentFiber.current = fiber;
  ReactDebugCurrentFiber.phase = null;
}

function setCurrentPhase(phase) {
  ReactDebugCurrentFiber.phase = phase;
}

var ReactDebugCurrentFiber = {
  current: null,
  phase: null,
  resetCurrentFiber: resetCurrentFiber,
  setCurrentFiber: setCurrentFiber,
  setCurrentPhase: setCurrentPhase,
  getCurrentFiberOwnerName: getCurrentFiberOwnerName$1,
  getCurrentFiberStackAddendum: getCurrentFiberStackAddendum$1
};

// A reserved attribute.
// It is handled by React separately and shouldn't be written to the DOM.
var RESERVED = 0;

// A simple string attribute.
// Attributes that aren't in the whitelist are presumed to have this type.
var STRING = 1;

// A string attribute that accepts booleans in React. In HTML, these are called
// "enumerated" attributes with "true" and "false" as possible values.
// When true, it should be set to a "true" string.
// When false, it should be set to a "false" string.
var BOOLEANISH_STRING = 2;

// A real boolean attribute.
// When true, it should be present (set either to an empty string or its name).
// When false, it should be omitted.
var BOOLEAN = 3;

// An attribute that can be used as a flag as well as with a value.
// When true, it should be present (set either to an empty string or its name).
// When false, it should be omitted.
// For any other value, should be present with that value.
var OVERLOADED_BOOLEAN = 4;

// An attribute that must be numeric or parse as a numeric.
// When falsy, it should be removed.
var NUMERIC = 5;

// An attribute that must be positive numeric or parse as a positive numeric.
// When falsy, it should be removed.
var POSITIVE_NUMERIC = 6;

/* eslint-disable max-len */
var ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD';
/* eslint-enable max-len */
var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040';


var ROOT_ATTRIBUTE_NAME = 'data-reactroot';
var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');

var hasOwnProperty = Object.prototype.hasOwnProperty;
var illegalAttributeNameCache = {};
var validatedAttributeNameCache = {};

function isAttributeNameSafe(attributeName) {
  if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
    return true;
  }
  if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
    return false;
  }
  if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
    validatedAttributeNameCache[attributeName] = true;
    return true;
  }
  illegalAttributeNameCache[attributeName] = true;
  {
    warning(false, 'Invalid attribute name: `%s`', attributeName);
  }
  return false;
}

function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) {
  if (propertyInfo !== null) {
    return propertyInfo.type === RESERVED;
  }
  if (isCustomComponentTag) {
    return false;
  }
  if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
    return true;
  }
  return false;
}

function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
  if (propertyInfo !== null && propertyInfo.type === RESERVED) {
    return false;
  }
  switch (typeof value) {
    case 'function':
    // $FlowIssue symbol is perfectly valid here
    case 'symbol':
      // eslint-disable-line
      return true;
    case 'boolean':
      {
        if (isCustomComponentTag) {
          return false;
        }
        if (propertyInfo !== null) {
          return !propertyInfo.acceptsBooleans;
        } else {
          var prefix = name.toLowerCase().slice(0, 5);
          return prefix !== 'data-' && prefix !== 'aria-';
        }
      }
    default:
      return false;
  }
}

function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) {
  if (value === null || typeof value === 'undefined') {
    return true;
  }
  if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) {
    return true;
  }
  if (isCustomComponentTag) {
    return false;
  }
  if (propertyInfo !== null) {
    switch (propertyInfo.type) {
      case BOOLEAN:
        return !value;
      case OVERLOADED_BOOLEAN:
        return value === false;
      case NUMERIC:
        return isNaN(value);
      case POSITIVE_NUMERIC:
        return isNaN(value) || value < 1;
    }
  }
  return false;
}

function getPropertyInfo(name) {
  return properties.hasOwnProperty(name) ? properties[name] : null;
}

function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace) {
  this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
  this.attributeName = attributeName;
  this.attributeNamespace = attributeNamespace;
  this.mustUseProperty = mustUseProperty;
  this.propertyName = name;
  this.type = type;
}

// When adding attributes to this list, be sure to also add them to
// the `possibleStandardNames` module to ensure casing and incorrect
// name warnings.
var properties = {};

// These props are reserved by React. They shouldn't be written to the DOM.
['children', 'dangerouslySetInnerHTML',
// TODO: This prevents the assignment of defaultValue to regular
// elements (not just inputs). Now that ReactDOMInput assigns to the
// defaultValue property -- do we need this?
'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty
  name, // attributeName
  null);
} // attributeNamespace
);

// A few React string attributes have a different name.
// This is a mapping from React prop names to the attribute names.
[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {
  var name = _ref[0],
      attributeName = _ref[1];

  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, // attributeName
  null);
} // attributeNamespace
);

// These are "enumerated" HTML attributes that accept "true" and "false".
// In React, we let users pass `true` and `false` even though technically
// these aren't boolean attributes (they are coerced to strings).
['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
  name.toLowerCase(), // attributeName
  null);
} // attributeNamespace
);

// These are "enumerated" SVG attributes that accept "true" and "false".
// In React, we let users pass `true` and `false` even though technically
// these aren't boolean attributes (they are coerced to strings).
// Since these are SVG attributes, their attribute names are case-sensitive.
['autoReverse', 'externalResourcesRequired', 'preserveAlpha'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
  name, // attributeName
  null);
} // attributeNamespace
);

// These are HTML boolean attributes.
['allowFullScreen', 'async',
// Note: there is a special case that prevents it from being written to the DOM
// on the client side because the browsers are inconsistent. Instead we call focus().
'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless',
// Microdata
'itemScope'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty
  name.toLowerCase(), // attributeName
  null);
} // attributeNamespace
);

// These are the few React props that we set as DOM properties
// rather than attributes. These are all booleans.
['checked',
// Note: `option.selected` is not updated if `select.multiple` is
// disabled with `removeAttribute`. We have special logic for handling this.
'multiple', 'muted', 'selected'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty
  name.toLowerCase(), // attributeName
  null);
} // attributeNamespace
);

// These are HTML attributes that are "overloaded booleans": they behave like
// booleans, but can also accept a string value.
['capture', 'download'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty
  name.toLowerCase(), // attributeName
  null);
} // attributeNamespace
);

// These are HTML attributes that must be positive numbers.
['cols', 'rows', 'size', 'span'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty
  name.toLowerCase(), // attributeName
  null);
} // attributeNamespace
);

// These are HTML attributes that must be numbers.
['rowSpan', 'start'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty
  name.toLowerCase(), // attributeName
  null);
} // attributeNamespace
);

var CAMELIZE = /[\-\:]([a-z])/g;
var capitalize = function (token) {
  return token[1].toUpperCase();
};

// This is a list of all SVG attributes that need special casing, namespacing,
// or boolean value assignment. Regular attributes that just accept strings
// and have the same names are omitted, just like in the HTML whitelist.
// Some of these attributes can be hard to find. This list was created by
// scrapping the MDN documentation.
['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height'].forEach(function (attributeName) {
  var name = attributeName.replace(CAMELIZE, capitalize);
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, null);
} // attributeNamespace
);

// String SVG attributes with the xlink namespace.
['xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type'].forEach(function (attributeName) {
  var name = attributeName.replace(CAMELIZE, capitalize);
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, 'http://www.w3.org/1999/xlink');
});

// String SVG attributes with the xml namespace.
['xml:base', 'xml:lang', 'xml:space'].forEach(function (attributeName) {
  var name = attributeName.replace(CAMELIZE, capitalize);
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, 'http://www.w3.org/XML/1998/namespace');
});

// Special case: this attribute exists both in HTML and SVG.
// Its "tabindex" attribute name is case-sensitive in SVG so we can't just use
// its React `tabIndex` name, like we do for attributes that exist only in HTML.
properties.tabIndex = new PropertyInfoRecord('tabIndex', STRING, false, // mustUseProperty
'tabindex', // attributeName
null);

/**
 * Get the value for a property on a node. Only used in DEV for SSR validation.
 * The "expected" argument is used as a hint of what the expected value is.
 * Some properties have multiple equivalent values.
 */
function getValueForProperty(node, name, expected, propertyInfo) {
  {
    if (propertyInfo.mustUseProperty) {
      var propertyName = propertyInfo.propertyName;

      return node[propertyName];
    } else {
      var attributeName = propertyInfo.attributeName;

      var stringValue = null;

      if (propertyInfo.type === OVERLOADED_BOOLEAN) {
        if (node.hasAttribute(attributeName)) {
          var value = node.getAttribute(attributeName);
          if (value === '') {
            return true;
          }
          if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
            return value;
          }
          if (value === '' + expected) {
            return expected;
          }
          return value;
        }
      } else if (node.hasAttribute(attributeName)) {
        if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
          // We had an attribute but shouldn't have had one, so read it
          // for the error message.
          return node.getAttribute(attributeName);
        }
        if (propertyInfo.type === BOOLEAN) {
          // If this was a boolean, it doesn't matter what the value is
          // the fact that we have it is the same as the expected.
          return expected;
        }
        // Even if this property uses a namespace we use getAttribute
        // because we assume its namespaced name is the same as our config.
        // To use getAttributeNS we need the local name which we don't have
        // in our config atm.
        stringValue = node.getAttribute(attributeName);
      }

      if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
        return stringValue === null ? expected : stringValue;
      } else if (stringValue === '' + expected) {
        return expected;
      } else {
        return stringValue;
      }
    }
  }
}

/**
 * Get the value for a attribute on a node. Only used in DEV for SSR validation.
 * The third argument is used as a hint of what the expected value is. Some
 * attributes have multiple equivalent values.
 */
function getValueForAttribute(node, name, expected) {
  {
    if (!isAttributeNameSafe(name)) {
      return;
    }
    if (!node.hasAttribute(name)) {
      return expected === undefined ? undefined : null;
    }
    var value = node.getAttribute(name);
    if (value === '' + expected) {
      return expected;
    }
    return value;
  }
}

/**
 * Sets the value for a property on a node.
 *
 * @param {DOMElement} node
 * @param {string} name
 * @param {*} value
 */
function setValueForProperty(node, name, value, isCustomComponentTag) {
  var propertyInfo = getPropertyInfo(name);
  if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) {
    return;
  }
  if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) {
    value = null;
  }
  // If the prop isn't in the special list, treat it as a simple attribute.
  if (isCustomComponentTag || propertyInfo === null) {
    if (isAttributeNameSafe(name)) {
      var _attributeName = name;
      if (value === null) {
        node.removeAttribute(_attributeName);
      } else {
        node.setAttribute(_attributeName, '' + value);
      }
    }
    return;
  }
  var mustUseProperty = propertyInfo.mustUseProperty;

  if (mustUseProperty) {
    var propertyName = propertyInfo.propertyName;

    if (value === null) {
      var type = propertyInfo.type;

      node[propertyName] = type === BOOLEAN ? false : '';
    } else {
      // Contrary to `setAttribute`, object properties are properly
      // `toString`ed by IE8/9.
      node[propertyName] = value;
    }
    return;
  }
  // The rest are treated as attributes with special cases.
  var attributeName = propertyInfo.attributeName,
      attributeNamespace = propertyInfo.attributeNamespace;

  if (value === null) {
    node.removeAttribute(attributeName);
  } else {
    var _type = propertyInfo.type;

    var attributeValue = void 0;
    if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) {
      attributeValue = '';
    } else {
      // `setAttribute` with objects becomes only `[object]` in IE8/9,
      // ('' + value) makes it output the correct toString()-value.
      attributeValue = '' + value;
    }
    if (attributeNamespace) {
      node.setAttributeNS(attributeNamespace, attributeName, attributeValue);
    } else {
      node.setAttribute(attributeName, attributeValue);
    }
  }
}

var ReactControlledValuePropTypes = {
  checkPropTypes: null
};

{
  var hasReadOnlyValue = {
    button: true,
    checkbox: true,
    image: true,
    hidden: true,
    radio: true,
    reset: true,
    submit: true
  };

  var propTypes = {
    value: function (props, propName, componentName) {
      if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) {
        return null;
      }
      return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
    },
    checked: function (props, propName, componentName) {
      if (!props[propName] || props.onChange || props.readOnly || props.disabled) {
        return null;
      }
      return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
    }
  };

  /**
   * Provide a linked `value` attribute for controlled forms. You should not use
   * this outside of the ReactDOM controlled form components.
   */
  ReactControlledValuePropTypes.checkPropTypes = function (tagName, props, getStack) {
    checkPropTypes(propTypes, props, 'prop', tagName, getStack);
  };
}

// TODO: direct imports like some-package/src/* are bad. Fix me.
var getCurrentFiberOwnerName = ReactDebugCurrentFiber.getCurrentFiberOwnerName;
var getCurrentFiberStackAddendum = ReactDebugCurrentFiber.getCurrentFiberStackAddendum;

var didWarnValueDefaultValue = false;
var didWarnCheckedDefaultChecked = false;
var didWarnControlledToUncontrolled = false;
var didWarnUncontrolledToControlled = false;

function isControlled(props) {
  var usesChecked = props.type === 'checkbox' || props.type === 'radio';
  return usesChecked ? props.checked != null : props.value != null;
}

/**
 * Implements an <input> host component that allows setting these optional
 * props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
 *
 * If `checked` or `value` are not supplied (or null/undefined), user actions
 * that affect the checked state or value will trigger updates to the element.
 *
 * If they are supplied (and not null/undefined), the rendered element will not
 * trigger updates to the element. Instead, the props must change in order for
 * the rendered element to be updated.
 *
 * The rendered element will be initialized as unchecked (or `defaultChecked`)
 * with an empty value (or `defaultValue`).
 *
 * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
 */

function getHostProps(element, props) {
  var node = element;
  var checked = props.checked;

  var hostProps = _assign({}, props, {
    defaultChecked: undefined,
    defaultValue: undefined,
    value: undefined,
    checked: checked != null ? checked : node._wrapperState.initialChecked
  });

  return hostProps;
}

function initWrapperState(element, props) {
  {
    ReactControlledValuePropTypes.checkPropTypes('input', props, getCurrentFiberStackAddendum);

    if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) {
      warning(false, '%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerName() || 'A component', props.type);
      didWarnCheckedDefaultChecked = true;
    }
    if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {
      warning(false, '%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerName() || 'A component', props.type);
      didWarnValueDefaultValue = true;
    }
  }

  var node = element;
  var defaultValue = props.defaultValue == null ? '' : props.defaultValue;

  node._wrapperState = {
    initialChecked: props.checked != null ? props.checked : props.defaultChecked,
    initialValue: getSafeValue(props.value != null ? props.value : defaultValue),
    controlled: isControlled(props)
  };
}

function updateChecked(element, props) {
  var node = element;
  var checked = props.checked;
  if (checked != null) {
    setValueForProperty(node, 'checked', checked, false);
  }
}

function updateWrapper(element, props) {
  var node = element;
  {
    var _controlled = isControlled(props);

    if (!node._wrapperState.controlled && _controlled && !didWarnUncontrolledToControlled) {
      warning(false, 'A component is changing an uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components%s', props.type, getCurrentFiberStackAddendum());
      didWarnUncontrolledToControlled = true;
    }
    if (node._wrapperState.controlled && !_controlled && !didWarnControlledToUncontrolled) {
      warning(false, 'A component is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components%s', props.type, getCurrentFiberStackAddendum());
      didWarnControlledToUncontrolled = true;
    }
  }

  updateChecked(element, props);

  var value = getSafeValue(props.value);

  if (value != null) {
    if (props.type === 'number') {
      if (value === 0 && node.value === '' ||
      // eslint-disable-next-line
      node.value != value) {
        node.value = '' + value;
      }
    } else if (node.value !== '' + value) {
      node.value = '' + value;
    }
  }

  if (props.hasOwnProperty('value')) {
    setDefaultValue(node, props.type, value);
  } else if (props.hasOwnProperty('defaultValue')) {
    setDefaultValue(node, props.type, getSafeValue(props.defaultValue));
  }

  if (props.checked == null && props.defaultChecked != null) {
    node.defaultChecked = !!props.defaultChecked;
  }
}

function postMountWrapper(element, props, isHydrating) {
  var node = element;

  if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) {
    var _initialValue = '' + node._wrapperState.initialValue;
    var currentValue = node.value;

    // Do not assign value if it is already set. This prevents user text input
    // from being lost during SSR hydration.
    if (!isHydrating) {
      // Do not re-assign the value property if there is no change. This
      // potentially avoids a DOM write and prevents Firefox (~60.0.1) from
      // prematurely marking required inputs as invalid
      if (_initialValue !== currentValue) {
        node.value = _initialValue;
      }
    }

    // value must be assigned before defaultValue. This fixes an issue where the
    // visually displayed value of date inputs disappears on mobile Safari and Chrome:
    // https://github.com/facebook/react/issues/7233
    node.defaultValue = _initialValue;
  }

  // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug
  // this is needed to work around a chrome bug where setting defaultChecked
  // will sometimes influence the value of checked (even after detachment).
  // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416
  // We need to temporarily unset name to avoid disrupting radio button groups.
  var name = node.name;
  if (name !== '') {
    node.name = '';
  }
  node.defaultChecked = !node.defaultChecked;
  node.defaultChecked = !node.defaultChecked;
  if (name !== '') {
    node.name = name;
  }
}

function restoreControlledState(element, props) {
  var node = element;
  updateWrapper(node, props);
  updateNamedCousins(node, props);
}

function updateNamedCousins(rootNode, props) {
  var name = props.name;
  if (props.type === 'radio' && name != null) {
    var queryRoot = rootNode;

    while (queryRoot.parentNode) {
      queryRoot = queryRoot.parentNode;
    }

    // If `rootNode.form` was non-null, then we could try `form.elements`,
    // but that sometimes behaves strangely in IE8. We could also try using
    // `form.getElementsByName`, but that will only return direct children
    // and won't include inputs that use the HTML5 `form=` attribute. Since
    // the input might not even be in a form. It might not even be in the
    // document. Let's just use the local `querySelectorAll` to ensure we don't
    // miss anything.
    var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]');

    for (var i = 0; i < group.length; i++) {
      var otherNode = group[i];
      if (otherNode === rootNode || otherNode.form !== rootNode.form) {
        continue;
      }
      // This will throw if radio buttons rendered by different copies of React
      // and the same name are rendered into the same form (same as #1939).
      // That's probably okay; we don't support it just as we don't support
      // mixing React radio buttons with non-React ones.
      var otherProps = getFiberCurrentPropsFromNode$1(otherNode);
      !otherProps ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.') : void 0;

      // We need update the tracked value on the named cousin since the value
      // was changed but the input saw no event or value set
      updateValueIfChanged(otherNode);

      // If this is a controlled radio button group, forcing the input that
      // was previously checked to update will cause it to be come re-checked
      // as appropriate.
      updateWrapper(otherNode, otherProps);
    }
  }
}

// In Chrome, assigning defaultValue to certain input types triggers input validation.
// For number inputs, the display value loses trailing decimal points. For email inputs,
// Chrome raises "The specified value <x> is not a valid email address".
//
// Here we check to see if the defaultValue has actually changed, avoiding these problems
// when the user is inputting text
//
// https://github.com/facebook/react/issues/7253
function setDefaultValue(node, type, value) {
  if (
  // Focused number inputs synchronize on blur. See ChangeEventPlugin.js
  type !== 'number' || node.ownerDocument.activeElement !== node) {
    if (value == null) {
      node.defaultValue = '' + node._wrapperState.initialValue;
    } else if (node.defaultValue !== '' + value) {
      node.defaultValue = '' + value;
    }
  }
}

function getSafeValue(value) {
  switch (typeof value) {
    case 'boolean':
    case 'number':
    case 'object':
    case 'string':
    case 'undefined':
      return value;
    default:
      // function, symbol are assigned as empty strings
      return '';
  }
}

var eventTypes$1 = {
  change: {
    phasedRegistrationNames: {
      bubbled: 'onChange',
      captured: 'onChangeCapture'
    },
    dependencies: [TOP_BLUR, TOP_CHANGE, TOP_CLICK, TOP_FOCUS, TOP_INPUT, TOP_KEY_DOWN, TOP_KEY_UP, TOP_SELECTION_CHANGE]
  }
};

function createAndAccumulateChangeEvent(inst, nativeEvent, target) {
  var event = SyntheticEvent$1.getPooled(eventTypes$1.change, inst, nativeEvent, target);
  event.type = 'change';
  // Flag this event loop as needing state restore.
  enqueueStateRestore(target);
  accumulateTwoPhaseDispatches(event);
  return event;
}
/**
 * For IE shims
 */
var activeElement = null;
var activeElementInst = null;

/**
 * SECTION: handle `change` event
 */
function shouldUseChangeEvent(elem) {
  var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
  return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';
}

function manualDispatchChangeEvent(nativeEvent) {
  var event = createAndAccumulateChangeEvent(activeElementInst, nativeEvent, getEventTarget(nativeEvent));

  // If change and propertychange bubbled, we'd just bind to it like all the
  // other events and have it go through ReactBrowserEventEmitter. Since it
  // doesn't, we manually listen for the events and so we have to enqueue and
  // process the abstract event manually.
  //
  // Batching is necessary here in order to ensure that all event handlers run
  // before the next rerender (including event handlers attached to ancestor
  // elements instead of directly on the input). Without this, controlled
  // components don't work properly in conjunction with event bubbling because
  // the component is rerendered and the value reverted before all the event
  // handlers can run. See https://github.com/facebook/react/issues/708.
  batchedUpdates(runEventInBatch, event);
}

function runEventInBatch(event) {
  runEventsInBatch(event, false);
}

function getInstIfValueChanged(targetInst) {
  var targetNode = getNodeFromInstance$1(targetInst);
  if (updateValueIfChanged(targetNode)) {
    return targetInst;
  }
}

function getTargetInstForChangeEvent(topLevelType, targetInst) {
  if (topLevelType === TOP_CHANGE) {
    return targetInst;
  }
}

/**
 * SECTION: handle `input` event
 */
var isInputEventSupported = false;
if (ExecutionEnvironment.canUseDOM) {
  // IE9 claims to support the input event but fails to trigger it when
  // deleting text, so we ignore its input events.
  isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 9);
}

/**
 * (For IE <=9) Starts tracking propertychange events on the passed-in element
 * and override the value property so that we can distinguish user events from
 * value changes in JS.
 */
function startWatchingForValueChange(target, targetInst) {
  activeElement = target;
  activeElementInst = targetInst;
  activeElement.attachEvent('onpropertychange', handlePropertyChange);
}

/**
 * (For IE <=9) Removes the event listeners from the currently-tracked element,
 * if any exists.
 */
function stopWatchingForValueChange() {
  if (!activeElement) {
    return;
  }
  activeElement.detachEvent('onpropertychange', handlePropertyChange);
  activeElement = null;
  activeElementInst = null;
}

/**
 * (For IE <=9) Handles a propertychange event, sending a `change` event if
 * the value of the active element has changed.
 */
function handlePropertyChange(nativeEvent) {
  if (nativeEvent.propertyName !== 'value') {
    return;
  }
  if (getInstIfValueChanged(activeElementInst)) {
    manualDispatchChangeEvent(nativeEvent);
  }
}

function handleEventsForInputEventPolyfill(topLevelType, target, targetInst) {
  if (topLevelType === TOP_FOCUS) {
    // In IE9, propertychange fires for most input events but is buggy and
    // doesn't fire when text is deleted, but conveniently, selectionchange
    // appears to fire in all of the remaining cases so we catch those and
    // forward the event if the value has changed
    // In either case, we don't want to call the event handler if the value
    // is changed from JS so we redefine a setter for `.value` that updates
    // our activeElementValue variable, allowing us to ignore those changes
    //
    // stopWatching() should be a noop here but we call it just in case we
    // missed a blur event somehow.
    stopWatchingForValueChange();
    startWatchingForValueChange(target, targetInst);
  } else if (topLevelType === TOP_BLUR) {
    stopWatchingForValueChange();
  }
}

// For IE8 and IE9.
function getTargetInstForInputEventPolyfill(topLevelType, targetInst) {
  if (topLevelType === TOP_SELECTION_CHANGE || topLevelType === TOP_KEY_UP || topLevelType === TOP_KEY_DOWN) {
    // On the selectionchange event, the target is just document which isn't
    // helpful for us so just check activeElement instead.
    //
    // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
    // propertychange on the first input event after setting `value` from a
    // script and fires only keydown, keypress, keyup. Catching keyup usually
    // gets it and catching keydown lets us fire an event for the first
    // keystroke if user does a key repeat (it'll be a little delayed: right
    // before the second keystroke). Other input methods (e.g., paste) seem to
    // fire selectionchange normally.
    return getInstIfValueChanged(activeElementInst);
  }
}

/**
 * SECTION: handle `click` event
 */
function shouldUseClickEvent(elem) {
  // Use the `click` event to detect changes to checkbox and radio inputs.
  // This approach works across all browsers, whereas `change` does not fire
  // until `blur` in IE8.
  var nodeName = elem.nodeName;
  return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
}

function getTargetInstForClickEvent(topLevelType, targetInst) {
  if (topLevelType === TOP_CLICK) {
    return getInstIfValueChanged(targetInst);
  }
}

function getTargetInstForInputOrChangeEvent(topLevelType, targetInst) {
  if (topLevelType === TOP_INPUT || topLevelType === TOP_CHANGE) {
    return getInstIfValueChanged(targetInst);
  }
}

function handleControlledInputBlur(node) {
  var state = node._wrapperState;

  if (!state || !state.controlled || node.type !== 'number') {
    return;
  }

  // If controlled, assign the value attribute to the current value on blur
  setDefaultValue(node, 'number', node.value);
}

/**
 * This plugin creates an `onChange` event that normalizes change events
 * across form elements. This event fires at a time when it's possible to
 * change the element's value without seeing a flicker.
 *
 * Supported elements are:
 * - input (see `isTextInputElement`)
 * - textarea
 * - select
 */
var ChangeEventPlugin = {
  eventTypes: eventTypes$1,

  _isInputEventSupported: isInputEventSupported,

  extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
    var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;

    var getTargetInstFunc = void 0,
        handleEventFunc = void 0;
    if (shouldUseChangeEvent(targetNode)) {
      getTargetInstFunc = getTargetInstForChangeEvent;
    } else if (isTextInputElement(targetNode)) {
      if (isInputEventSupported) {
        getTargetInstFunc = getTargetInstForInputOrChangeEvent;
      } else {
        getTargetInstFunc = getTargetInstForInputEventPolyfill;
        handleEventFunc = handleEventsForInputEventPolyfill;
      }
    } else if (shouldUseClickEvent(targetNode)) {
      getTargetInstFunc = getTargetInstForClickEvent;
    }

    if (getTargetInstFunc) {
      var inst = getTargetInstFunc(topLevelType, targetInst);
      if (inst) {
        var event = createAndAccumulateChangeEvent(inst, nativeEvent, nativeEventTarget);
        return event;
      }
    }

    if (handleEventFunc) {
      handleEventFunc(topLevelType, targetNode, targetInst);
    }

    // When blurring, set the value attribute for number inputs
    if (topLevelType === TOP_BLUR) {
      handleControlledInputBlur(targetNode);
    }
  }
};

/**
 * Module that is injectable into `EventPluginHub`, that specifies a
 * deterministic ordering of `EventPlugin`s. A convenient way to reason about
 * plugins, without having to package every one of them. This is better than
 * having plugins be ordered in the same order that they are injected because
 * that ordering would be influenced by the packaging order.
 * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that
 * preventing default on events is convenient in `SimpleEventPlugin` handlers.
 */
var DOMEventPluginOrder = ['ResponderEventPlugin', 'SimpleEventPlugin', 'TapEventPlugin', 'EnterLeaveEventPlugin', 'ChangeEventPlugin', 'SelectEventPlugin', 'BeforeInputEventPlugin'];

var SyntheticUIEvent = SyntheticEvent$1.extend({
  view: null,
  detail: null
});

/**
 * Translation from modifier key to the associated property in the event.
 * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
 */

var modifierKeyToProp = {
  Alt: 'altKey',
  Control: 'ctrlKey',
  Meta: 'metaKey',
  Shift: 'shiftKey'
};

// IE8 does not implement getModifierState so we simply map it to the only
// modifier keys exposed by the event itself, does not support Lock-keys.
// Currently, all major browsers except Chrome seems to support Lock-keys.
function modifierStateGetter(keyArg) {
  var syntheticEvent = this;
  var nativeEvent = syntheticEvent.nativeEvent;
  if (nativeEvent.getModifierState) {
    return nativeEvent.getModifierState(keyArg);
  }
  var keyProp = modifierKeyToProp[keyArg];
  return keyProp ? !!nativeEvent[keyProp] : false;
}

function getEventModifierState(nativeEvent) {
  return modifierStateGetter;
}

/**
 * @interface MouseEvent
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */
var SyntheticMouseEvent = SyntheticUIEvent.extend({
  screenX: null,
  screenY: null,
  clientX: null,
  clientY: null,
  pageX: null,
  pageY: null,
  ctrlKey: null,
  shiftKey: null,
  altKey: null,
  metaKey: null,
  getModifierState: getEventModifierState,
  button: null,
  buttons: null,
  relatedTarget: function (event) {
    return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement);
  }
});

/**
 * @interface PointerEvent
 * @see http://www.w3.org/TR/pointerevents/
 */
var SyntheticPointerEvent = SyntheticMouseEvent.extend({
  pointerId: null,
  width: null,
  height: null,
  pressure: null,
  tiltX: null,
  tiltY: null,
  pointerType: null,
  isPrimary: null
});

var eventTypes$2 = {
  mouseEnter: {
    registrationName: 'onMouseEnter',
    dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]
  },
  mouseLeave: {
    registrationName: 'onMouseLeave',
    dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]
  },
  pointerEnter: {
    registrationName: 'onPointerEnter',
    dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]
  },
  pointerLeave: {
    registrationName: 'onPointerLeave',
    dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]
  }
};

var EnterLeaveEventPlugin = {
  eventTypes: eventTypes$2,

  /**
   * For almost every interaction we care about, there will be both a top-level
   * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
   * we do not extract duplicate events. However, moving the mouse into the
   * browser from outside will not fire a `mouseout` event. In this case, we use
   * the `mouseover` top-level event.
   */
  extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
    var isOverEvent = topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER;
    var isOutEvent = topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT;

    if (isOverEvent && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
      return null;
    }

    if (!isOutEvent && !isOverEvent) {
      // Must not be a mouse or pointer in or out - ignoring.
      return null;
    }

    var win = void 0;
    if (nativeEventTarget.window === nativeEventTarget) {
      // `nativeEventTarget` is probably a window object.
      win = nativeEventTarget;
    } else {
      // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
      var doc = nativeEventTarget.ownerDocument;
      if (doc) {
        win = doc.defaultView || doc.parentWindow;
      } else {
        win = window;
      }
    }

    var from = void 0;
    var to = void 0;
    if (isOutEvent) {
      from = targetInst;
      var related = nativeEvent.relatedTarget || nativeEvent.toElement;
      to = related ? getClosestInstanceFromNode(related) : null;
    } else {
      // Moving to a node from outside the window.
      from = null;
      to = targetInst;
    }

    if (from === to) {
      // Nothing pertains to our managed components.
      return null;
    }

    var eventInterface = void 0,
        leaveEventType = void 0,
        enterEventType = void 0,
        eventTypePrefix = void 0;

    if (topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER) {
      eventInterface = SyntheticMouseEvent;
      leaveEventType = eventTypes$2.mouseLeave;
      enterEventType = eventTypes$2.mouseEnter;
      eventTypePrefix = 'mouse';
    } else if (topLevelType === TOP_POINTER_OUT || topLevelType === TOP_POINTER_OVER) {
      eventInterface = SyntheticPointerEvent;
      leaveEventType = eventTypes$2.pointerLeave;
      enterEventType = eventTypes$2.pointerEnter;
      eventTypePrefix = 'pointer';
    }

    var fromNode = from == null ? win : getNodeFromInstance$1(from);
    var toNode = to == null ? win : getNodeFromInstance$1(to);

    var leave = eventInterface.getPooled(leaveEventType, from, nativeEvent, nativeEventTarget);
    leave.type = eventTypePrefix + 'leave';
    leave.target = fromNode;
    leave.relatedTarget = toNode;

    var enter = eventInterface.getPooled(enterEventType, to, nativeEvent, nativeEventTarget);
    enter.type = eventTypePrefix + 'enter';
    enter.target = toNode;
    enter.relatedTarget = fromNode;

    accumulateEnterLeaveDispatches(leave, enter, from, to);

    return [leave, enter];
  }
};

/**
 * `ReactInstanceMap` maintains a mapping from a public facing stateful
 * instance (key) and the internal representation (value). This allows public
 * methods to accept the user facing instance as an argument and map them back
 * to internal methods.
 *
 * Note that this module is currently shared and assumed to be stateless.
 * If this becomes an actual Map, that will break.
 */

/**
 * This API should be called `delete` but we'd have to make sure to always
 * transform these to strings for IE support. When this transform is fully
 * supported we can rename it.
 */


function get(key) {
  return key._reactInternalFiber;
}

function has(key) {
  return key._reactInternalFiber !== undefined;
}

function set(key, value) {
  key._reactInternalFiber = value;
}

// Don't change these two values. They're used by React Dev Tools.
var NoEffect = /*              */0;
var PerformedWork = /*         */1;

// You can change the rest (and add more).
var Placement = /*             */2;
var Update = /*                */4;
var PlacementAndUpdate = /*    */6;
var Deletion = /*              */8;
var ContentReset = /*          */16;
var Callback = /*              */32;
var DidCapture = /*            */64;
var Ref = /*                   */128;
var Snapshot = /*              */256;

// Union of all host effects
var HostEffectMask = /*        */511;

var Incomplete = /*            */512;
var ShouldCapture = /*         */1024;

var MOUNTING = 1;
var MOUNTED = 2;
var UNMOUNTED = 3;

function isFiberMountedImpl(fiber) {
  var node = fiber;
  if (!fiber.alternate) {
    // If there is no alternate, this might be a new tree that isn't inserted
    // yet. If it is, then it will have a pending insertion effect on it.
    if ((node.effectTag & Placement) !== NoEffect) {
      return MOUNTING;
    }
    while (node.return) {
      node = node.return;
      if ((node.effectTag & Placement) !== NoEffect) {
        return MOUNTING;
      }
    }
  } else {
    while (node.return) {
      node = node.return;
    }
  }
  if (node.tag === HostRoot) {
    // TODO: Check if this was a nested HostRoot when used with
    // renderContainerIntoSubtree.
    return MOUNTED;
  }
  // If we didn't hit the root, that means that we're in an disconnected tree
  // that has been unmounted.
  return UNMOUNTED;
}

function isFiberMounted(fiber) {
  return isFiberMountedImpl(fiber) === MOUNTED;
}

function isMounted(component) {
  {
    var owner = ReactCurrentOwner.current;
    if (owner !== null && owner.tag === ClassComponent) {
      var ownerFiber = owner;
      var instance = ownerFiber.stateNode;
      !instance._warnedAboutRefsInRender ? warning(false, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentName(ownerFiber) || 'A component') : void 0;
      instance._warnedAboutRefsInRender = true;
    }
  }

  var fiber = get(component);
  if (!fiber) {
    return false;
  }
  return isFiberMountedImpl(fiber) === MOUNTED;
}

function assertIsMounted(fiber) {
  !(isFiberMountedImpl(fiber) === MOUNTED) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0;
}

function findCurrentFiberUsingSlowPath(fiber) {
  var alternate = fiber.alternate;
  if (!alternate) {
    // If there is no alternate, then we only need to check if it is mounted.
    var state = isFiberMountedImpl(fiber);
    !(state !== UNMOUNTED) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0;
    if (state === MOUNTING) {
      return null;
    }
    return fiber;
  }
  // If we have two possible branches, we'll walk backwards up to the root
  // to see what path the root points to. On the way we may hit one of the
  // special cases and we'll deal with them.
  var a = fiber;
  var b = alternate;
  while (true) {
    var parentA = a.return;
    var parentB = parentA ? parentA.alternate : null;
    if (!parentA || !parentB) {
      // We're at the root.
      break;
    }

    // If both copies of the parent fiber point to the same child, we can
    // assume that the child is current. This happens when we bailout on low
    // priority: the bailed out fiber's child reuses the current child.
    if (parentA.child === parentB.child) {
      var child = parentA.child;
      while (child) {
        if (child === a) {
          // We've determined that A is the current branch.
          assertIsMounted(parentA);
          return fiber;
        }
        if (child === b) {
          // We've determined that B is the current branch.
          assertIsMounted(parentA);
          return alternate;
        }
        child = child.sibling;
      }
      // We should never have an alternate for any mounting node. So the only
      // way this could possibly happen is if this was unmounted, if at all.
      invariant(false, 'Unable to find node on an unmounted component.');
    }

    if (a.return !== b.return) {
      // The return pointer of A and the return pointer of B point to different
      // fibers. We assume that return pointers never criss-cross, so A must
      // belong to the child set of A.return, and B must belong to the child
      // set of B.return.
      a = parentA;
      b = parentB;
    } else {
      // The return pointers point to the same fiber. We'll have to use the
      // default, slow path: scan the child sets of each parent alternate to see
      // which child belongs to which set.
      //
      // Search parent A's child set
      var didFindChild = false;
      var _child = parentA.child;
      while (_child) {
        if (_child === a) {
          didFindChild = true;
          a = parentA;
          b = parentB;
          break;
        }
        if (_child === b) {
          didFindChild = true;
          b = parentA;
          a = parentB;
          break;
        }
        _child = _child.sibling;
      }
      if (!didFindChild) {
        // Search parent B's child set
        _child = parentB.child;
        while (_child) {
          if (_child === a) {
            didFindChild = true;
            a = parentB;
            b = parentA;
            break;
          }
          if (_child === b) {
            didFindChild = true;
            b = parentB;
            a = parentA;
            break;
          }
          _child = _child.sibling;
        }
        !didFindChild ? invariant(false, 'Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.') : void 0;
      }
    }

    !(a.alternate === b) ? invariant(false, 'Return fibers should always be each others\' alternates. This error is likely caused by a bug in React. Please file an issue.') : void 0;
  }
  // If the root is not a host container, we're in a disconnected tree. I.e.
  // unmounted.
  !(a.tag === HostRoot) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0;
  if (a.stateNode.current === a) {
    // We've determined that A is the current branch.
    return fiber;
  }
  // Otherwise B has to be current branch.
  return alternate;
}

function findCurrentHostFiber(parent) {
  var currentParent = findCurrentFiberUsingSlowPath(parent);
  if (!currentParent) {
    return null;
  }

  // Next we'll drill down this component to find the first HostComponent/Text.
  var node = currentParent;
  while (true) {
    if (node.tag === HostComponent || node.tag === HostText) {
      return node;
    } else if (node.child) {
      node.child.return = node;
      node = node.child;
      continue;
    }
    if (node === currentParent) {
      return null;
    }
    while (!node.sibling) {
      if (!node.return || node.return === currentParent) {
        return null;
      }
      node = node.return;
    }
    node.sibling.return = node.return;
    node = node.sibling;
  }
  // Flow needs the return null here, but ESLint complains about it.
  // eslint-disable-next-line no-unreachable
  return null;
}

function findCurrentHostFiberWithNoPortals(parent) {
  var currentParent = findCurrentFiberUsingSlowPath(parent);
  if (!currentParent) {
    return null;
  }

  // Next we'll drill down this component to find the first HostComponent/Text.
  var node = currentParent;
  while (true) {
    if (node.tag === HostComponent || node.tag === HostText) {
      return node;
    } else if (node.child && node.tag !== HostPortal) {
      node.child.return = node;
      node = node.child;
      continue;
    }
    if (node === currentParent) {
      return null;
    }
    while (!node.sibling) {
      if (!node.return || node.return === currentParent) {
        return null;
      }
      node = node.return;
    }
    node.sibling.return = node.return;
    node = node.sibling;
  }
  // Flow needs the return null here, but ESLint complains about it.
  // eslint-disable-next-line no-unreachable
  return null;
}

function addEventBubbleListener(element, eventType, listener) {
  element.addEventListener(eventType, listener, false);
}

function addEventCaptureListener(element, eventType, listener) {
  element.addEventListener(eventType, listener, true);
}

/**
 * @interface Event
 * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
 * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
 */
var SyntheticAnimationEvent = SyntheticEvent$1.extend({
  animationName: null,
  elapsedTime: null,
  pseudoElement: null
});

/**
 * @interface Event
 * @see http://www.w3.org/TR/clipboard-apis/
 */
var SyntheticClipboardEvent = SyntheticEvent$1.extend({
  clipboardData: function (event) {
    return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
  }
});

/**
 * @interface FocusEvent
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */
var SyntheticFocusEvent = SyntheticUIEvent.extend({
  relatedTarget: null
});

/**
 * `charCode` represents the actual "character code" and is safe to use with
 * `String.fromCharCode`. As such, only keys that correspond to printable
 * characters produce a valid `charCode`, the only exception to this is Enter.
 * The Tab-key is considered non-printable and does not have a `charCode`,
 * presumably because it does not produce a tab-character in browsers.
 *
 * @param {object} nativeEvent Native browser event.
 * @return {number} Normalized `charCode` property.
 */
function getEventCharCode(nativeEvent) {
  var charCode = void 0;
  var keyCode = nativeEvent.keyCode;

  if ('charCode' in nativeEvent) {
    charCode = nativeEvent.charCode;

    // FF does not set `charCode` for the Enter-key, check against `keyCode`.
    if (charCode === 0 && keyCode === 13) {
      charCode = 13;
    }
  } else {
    // IE8 does not implement `charCode`, but `keyCode` has the correct value.
    charCode = keyCode;
  }

  // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)
  // report Enter as charCode 10 when ctrl is pressed.
  if (charCode === 10) {
    charCode = 13;
  }

  // Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
  // Must not discard the (non-)printable Enter-key.
  if (charCode >= 32 || charCode === 13) {
    return charCode;
  }

  return 0;
}

/**
 * Normalization of deprecated HTML5 `key` values
 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
 */
var normalizeKey = {
  Esc: 'Escape',
  Spacebar: ' ',
  Left: 'ArrowLeft',
  Up: 'ArrowUp',
  Right: 'ArrowRight',
  Down: 'ArrowDown',
  Del: 'Delete',
  Win: 'OS',
  Menu: 'ContextMenu',
  Apps: 'ContextMenu',
  Scroll: 'ScrollLock',
  MozPrintableKey: 'Unidentified'
};

/**
 * Translation from legacy `keyCode` to HTML5 `key`
 * Only special keys supported, all others depend on keyboard layout or browser
 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
 */
var translateToKey = {
  '8': 'Backspace',
  '9': 'Tab',
  '12': 'Clear',
  '13': 'Enter',
  '16': 'Shift',
  '17': 'Control',
  '18': 'Alt',
  '19': 'Pause',
  '20': 'CapsLock',
  '27': 'Escape',
  '32': ' ',
  '33': 'PageUp',
  '34': 'PageDown',
  '35': 'End',
  '36': 'Home',
  '37': 'ArrowLeft',
  '38': 'ArrowUp',
  '39': 'ArrowRight',
  '40': 'ArrowDown',
  '45': 'Insert',
  '46': 'Delete',
  '112': 'F1',
  '113': 'F2',
  '114': 'F3',
  '115': 'F4',
  '116': 'F5',
  '117': 'F6',
  '118': 'F7',
  '119': 'F8',
  '120': 'F9',
  '121': 'F10',
  '122': 'F11',
  '123': 'F12',
  '144': 'NumLock',
  '145': 'ScrollLock',
  '224': 'Meta'
};

/**
 * @param {object} nativeEvent Native browser event.
 * @return {string} Normalized `key` property.
 */
function getEventKey(nativeEvent) {
  if (nativeEvent.key) {
    // Normalize inconsistent values reported by browsers due to
    // implementations of a working draft specification.

    // FireFox implements `key` but returns `MozPrintableKey` for all
    // printable characters (normalized to `Unidentified`), ignore it.
    var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
    if (key !== 'Unidentified') {
      return key;
    }
  }

  // Browser does not implement `key`, polyfill as much of it as we can.
  if (nativeEvent.type === 'keypress') {
    var charCode = getEventCharCode(nativeEvent);

    // The enter-key is technically both printable and non-printable and can
    // thus be captured by `keypress`, no other non-printable key should.
    return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
  }
  if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
    // While user keyboard layout determines the actual meaning of each
    // `keyCode` value, almost all function keys have a universal value.
    return translateToKey[nativeEvent.keyCode] || 'Unidentified';
  }
  return '';
}

/**
 * @interface KeyboardEvent
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */
var SyntheticKeyboardEvent = SyntheticUIEvent.extend({
  key: getEventKey,
  location: null,
  ctrlKey: null,
  shiftKey: null,
  altKey: null,
  metaKey: null,
  repeat: null,
  locale: null,
  getModifierState: getEventModifierState,
  // Legacy Interface
  charCode: function (event) {
    // `charCode` is the result of a KeyPress event and represents the value of
    // the actual printable character.

    // KeyPress is deprecated, but its replacement is not yet final and not
    // implemented in any major browser. Only KeyPress has charCode.
    if (event.type === 'keypress') {
      return getEventCharCode(event);
    }
    return 0;
  },
  keyCode: function (event) {
    // `keyCode` is the result of a KeyDown/Up event and represents the value of
    // physical keyboard key.

    // The actual meaning of the value depends on the users' keyboard layout
    // which cannot be detected. Assuming that it is a US keyboard layout
    // provides a surprisingly accurate mapping for US and European users.
    // Due to this, it is left to the user to implement at this time.
    if (event.type === 'keydown' || event.type === 'keyup') {
      return event.keyCode;
    }
    return 0;
  },
  which: function (event) {
    // `which` is an alias for either `keyCode` or `charCode` depending on the
    // type of the event.
    if (event.type === 'keypress') {
      return getEventCharCode(event);
    }
    if (event.type === 'keydown' || event.type === 'keyup') {
      return event.keyCode;
    }
    return 0;
  }
});

/**
 * @interface DragEvent
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */
var SyntheticDragEvent = SyntheticMouseEvent.extend({
  dataTransfer: null
});

/**
 * @interface TouchEvent
 * @see http://www.w3.org/TR/touch-events/
 */
var SyntheticTouchEvent = SyntheticUIEvent.extend({
  touches: null,
  targetTouches: null,
  changedTouches: null,
  altKey: null,
  metaKey: null,
  ctrlKey: null,
  shiftKey: null,
  getModifierState: getEventModifierState
});

/**
 * @interface Event
 * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
 * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
 */
var SyntheticTransitionEvent = SyntheticEvent$1.extend({
  propertyName: null,
  elapsedTime: null,
  pseudoElement: null
});

/**
 * @interface WheelEvent
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */
var SyntheticWheelEvent = SyntheticMouseEvent.extend({
  deltaX: function (event) {
    return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
    'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
  },
  deltaY: function (event) {
    return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
    'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
    'wheelDelta' in event ? -event.wheelDelta : 0;
  },

  deltaZ: null,

  // Browsers without "deltaMode" is reporting in raw wheel delta where one
  // notch on the scroll is always +/- 120, roughly equivalent to pixels.
  // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
  // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
  deltaMode: null
});

/**
 * Turns
 * ['abort', ...]
 * into
 * eventTypes = {
 *   'abort': {
 *     phasedRegistrationNames: {
 *       bubbled: 'onAbort',
 *       captured: 'onAbortCapture',
 *     },
 *     dependencies: [TOP_ABORT],
 *   },
 *   ...
 * };
 * topLevelEventsToDispatchConfig = new Map([
 *   [TOP_ABORT, { sameConfig }],
 * ]);
 */

var interactiveEventTypeNames = [[TOP_BLUR, 'blur'], [TOP_CANCEL, 'cancel'], [TOP_CLICK, 'click'], [TOP_CLOSE, 'close'], [TOP_CONTEXT_MENU, 'contextMenu'], [TOP_COPY, 'copy'], [TOP_CUT, 'cut'], [TOP_DOUBLE_CLICK, 'doubleClick'], [TOP_DRAG_END, 'dragEnd'], [TOP_DRAG_START, 'dragStart'], [TOP_DROP, 'drop'], [TOP_FOCUS, 'focus'], [TOP_INPUT, 'input'], [TOP_INVALID, 'invalid'], [TOP_KEY_DOWN, 'keyDown'], [TOP_KEY_PRESS, 'keyPress'], [TOP_KEY_UP, 'keyUp'], [TOP_MOUSE_DOWN, 'mouseDown'], [TOP_MOUSE_UP, 'mouseUp'], [TOP_PASTE, 'paste'], [TOP_PAUSE, 'pause'], [TOP_PLAY, 'play'], [TOP_POINTER_CANCEL, 'pointerCancel'], [TOP_POINTER_DOWN, 'pointerDown'], [TOP_POINTER_UP, 'pointerUp'], [TOP_RATE_CHANGE, 'rateChange'], [TOP_RESET, 'reset'], [TOP_SEEKED, 'seeked'], [TOP_SUBMIT, 'submit'], [TOP_TOUCH_CANCEL, 'touchCancel'], [TOP_TOUCH_END, 'touchEnd'], [TOP_TOUCH_START, 'touchStart'], [TOP_VOLUME_CHANGE, 'volumeChange']];
var nonInteractiveEventTypeNames = [[TOP_ABORT, 'abort'], [TOP_ANIMATION_END, 'animationEnd'], [TOP_ANIMATION_ITERATION, 'animationIteration'], [TOP_ANIMATION_START, 'animationStart'], [TOP_CAN_PLAY, 'canPlay'], [TOP_CAN_PLAY_THROUGH, 'canPlayThrough'], [TOP_DRAG, 'drag'], [TOP_DRAG_ENTER, 'dragEnter'], [TOP_DRAG_EXIT, 'dragExit'], [TOP_DRAG_LEAVE, 'dragLeave'], [TOP_DRAG_OVER, 'dragOver'], [TOP_DURATION_CHANGE, 'durationChange'], [TOP_EMPTIED, 'emptied'], [TOP_ENCRYPTED, 'encrypted'], [TOP_ENDED, 'ended'], [TOP_ERROR, 'error'], [TOP_GOT_POINTER_CAPTURE, 'gotPointerCapture'], [TOP_LOAD, 'load'], [TOP_LOADED_DATA, 'loadedData'], [TOP_LOADED_METADATA, 'loadedMetadata'], [TOP_LOAD_START, 'loadStart'], [TOP_LOST_POINTER_CAPTURE, 'lostPointerCapture'], [TOP_MOUSE_MOVE, 'mouseMove'], [TOP_MOUSE_OUT, 'mouseOut'], [TOP_MOUSE_OVER, 'mouseOver'], [TOP_PLAYING, 'playing'], [TOP_POINTER_MOVE, 'pointerMove'], [TOP_POINTER_OUT, 'pointerOut'], [TOP_POINTER_OVER, 'pointerOver'], [TOP_PROGRESS, 'progress'], [TOP_SCROLL, 'scroll'], [TOP_SEEKING, 'seeking'], [TOP_STALLED, 'stalled'], [TOP_SUSPEND, 'suspend'], [TOP_TIME_UPDATE, 'timeUpdate'], [TOP_TOGGLE, 'toggle'], [TOP_TOUCH_MOVE, 'touchMove'], [TOP_TRANSITION_END, 'transitionEnd'], [TOP_WAITING, 'waiting'], [TOP_WHEEL, 'wheel']];

var eventTypes$4 = {};
var topLevelEventsToDispatchConfig = {};

function addEventTypeNameToConfig(_ref, isInteractive) {
  var topEvent = _ref[0],
      event = _ref[1];

  var capitalizedEvent = event[0].toUpperCase() + event.slice(1);
  var onEvent = 'on' + capitalizedEvent;

  var type = {
    phasedRegistrationNames: {
      bubbled: onEvent,
      captured: onEvent + 'Capture'
    },
    dependencies: [topEvent],
    isInteractive: isInteractive
  };
  eventTypes$4[event] = type;
  topLevelEventsToDispatchConfig[topEvent] = type;
}

interactiveEventTypeNames.forEach(function (eventTuple) {
  addEventTypeNameToConfig(eventTuple, true);
});
nonInteractiveEventTypeNames.forEach(function (eventTuple) {
  addEventTypeNameToConfig(eventTuple, false);
});

// Only used in DEV for exhaustiveness validation.
var knownHTMLTopLevelTypes = [TOP_ABORT, TOP_CANCEL, TOP_CAN_PLAY, TOP_CAN_PLAY_THROUGH, TOP_CLOSE, TOP_DURATION_CHANGE, TOP_EMPTIED, TOP_ENCRYPTED, TOP_ENDED, TOP_ERROR, TOP_INPUT, TOP_INVALID, TOP_LOAD, TOP_LOADED_DATA, TOP_LOADED_METADATA, TOP_LOAD_START, TOP_PAUSE, TOP_PLAY, TOP_PLAYING, TOP_PROGRESS, TOP_RATE_CHANGE, TOP_RESET, TOP_SEEKED, TOP_SEEKING, TOP_STALLED, TOP_SUBMIT, TOP_SUSPEND, TOP_TIME_UPDATE, TOP_TOGGLE, TOP_VOLUME_CHANGE, TOP_WAITING];

var SimpleEventPlugin = {
  eventTypes: eventTypes$4,

  isInteractiveTopLevelEventType: function (topLevelType) {
    var config = topLevelEventsToDispatchConfig[topLevelType];
    return config !== undefined && config.isInteractive === true;
  },


  extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
    var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType];
    if (!dispatchConfig) {
      return null;
    }
    var EventConstructor = void 0;
    switch (topLevelType) {
      case TOP_KEY_PRESS:
        // Firefox creates a keypress event for function keys too. This removes
        // the unwanted keypress events. Enter is however both printable and
        // non-printable. One would expect Tab to be as well (but it isn't).
        if (getEventCharCode(nativeEvent) === 0) {
          return null;
        }
      /* falls through */
      case TOP_KEY_DOWN:
      case TOP_KEY_UP:
        EventConstructor = SyntheticKeyboardEvent;
        break;
      case TOP_BLUR:
      case TOP_FOCUS:
        EventConstructor = SyntheticFocusEvent;
        break;
      case TOP_CLICK:
        // Firefox creates a click event on right mouse clicks. This removes the
        // unwanted click events.
        if (nativeEvent.button === 2) {
          return null;
        }
      /* falls through */
      case TOP_DOUBLE_CLICK:
      case TOP_MOUSE_DOWN:
      case TOP_MOUSE_MOVE:
      case TOP_MOUSE_UP:
      // TODO: Disabled elements should not respond to mouse events
      /* falls through */
      case TOP_MOUSE_OUT:
      case TOP_MOUSE_OVER:
      case TOP_CONTEXT_MENU:
        EventConstructor = SyntheticMouseEvent;
        break;
      case TOP_DRAG:
      case TOP_DRAG_END:
      case TOP_DRAG_ENTER:
      case TOP_DRAG_EXIT:
      case TOP_DRAG_LEAVE:
      case TOP_DRAG_OVER:
      case TOP_DRAG_START:
      case TOP_DROP:
        EventConstructor = SyntheticDragEvent;
        break;
      case TOP_TOUCH_CANCEL:
      case TOP_TOUCH_END:
      case TOP_TOUCH_MOVE:
      case TOP_TOUCH_START:
        EventConstructor = SyntheticTouchEvent;
        break;
      case TOP_ANIMATION_END:
      case TOP_ANIMATION_ITERATION:
      case TOP_ANIMATION_START:
        EventConstructor = SyntheticAnimationEvent;
        break;
      case TOP_TRANSITION_END:
        EventConstructor = SyntheticTransitionEvent;
        break;
      case TOP_SCROLL:
        EventConstructor = SyntheticUIEvent;
        break;
      case TOP_WHEEL:
        EventConstructor = SyntheticWheelEvent;
        break;
      case TOP_COPY:
      case TOP_CUT:
      case TOP_PASTE:
        EventConstructor = SyntheticClipboardEvent;
        break;
      case TOP_GOT_POINTER_CAPTURE:
      case TOP_LOST_POINTER_CAPTURE:
      case TOP_POINTER_CANCEL:
      case TOP_POINTER_DOWN:
      case TOP_POINTER_MOVE:
      case TOP_POINTER_OUT:
      case TOP_POINTER_OVER:
      case TOP_POINTER_UP:
        EventConstructor = SyntheticPointerEvent;
        break;
      default:
        {
          if (knownHTMLTopLevelTypes.indexOf(topLevelType) === -1) {
            warning(false, 'SimpleEventPlugin: Unhandled event type, `%s`. This warning ' + 'is likely caused by a bug in React. Please file an issue.', topLevelType);
          }
        }
        // HTML Events
        // @see http://www.w3.org/TR/html5/index.html#events-0
        EventConstructor = SyntheticEvent$1;
        break;
    }
    var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget);
    accumulateTwoPhaseDispatches(event);
    return event;
  }
};

var isInteractiveTopLevelEventType = SimpleEventPlugin.isInteractiveTopLevelEventType;


var CALLBACK_BOOKKEEPING_POOL_SIZE = 10;
var callbackBookkeepingPool = [];

/**
 * Find the deepest React component completely containing the root of the
 * passed-in instance (for use when entire React trees are nested within each
 * other). If React trees are not nested, returns null.
 */
function findRootContainerNode(inst) {
  // TODO: It may be a good idea to cache this to prevent unnecessary DOM
  // traversal, but caching is difficult to do correctly without using a
  // mutation observer to listen for all DOM changes.
  while (inst.return) {
    inst = inst.return;
  }
  if (inst.tag !== HostRoot) {
    // This can happen if we're in a detached tree.
    return null;
  }
  return inst.stateNode.containerInfo;
}

// Used to store ancestor hierarchy in top level callback
function getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst) {
  if (callbackBookkeepingPool.length) {
    var instance = callbackBookkeepingPool.pop();
    instance.topLevelType = topLevelType;
    instance.nativeEvent = nativeEvent;
    instance.targetInst = targetInst;
    return instance;
  }
  return {
    topLevelType: topLevelType,
    nativeEvent: nativeEvent,
    targetInst: targetInst,
    ancestors: []
  };
}

function releaseTopLevelCallbackBookKeeping(instance) {
  instance.topLevelType = null;
  instance.nativeEvent = null;
  instance.targetInst = null;
  instance.ancestors.length = 0;
  if (callbackBookkeepingPool.length < CALLBACK_BOOKKEEPING_POOL_SIZE) {
    callbackBookkeepingPool.push(instance);
  }
}

function handleTopLevel(bookKeeping) {
  var targetInst = bookKeeping.targetInst;

  // Loop through the hierarchy, in case there's any nested components.
  // It's important that we build the array of ancestors before calling any
  // event handlers, because event handlers can modify the DOM, leading to
  // inconsistencies with ReactMount's node cache. See #1105.
  var ancestor = targetInst;
  do {
    if (!ancestor) {
      bookKeeping.ancestors.push(ancestor);
      break;
    }
    var root = findRootContainerNode(ancestor);
    if (!root) {
      break;
    }
    bookKeeping.ancestors.push(ancestor);
    ancestor = getClosestInstanceFromNode(root);
  } while (ancestor);

  for (var i = 0; i < bookKeeping.ancestors.length; i++) {
    targetInst = bookKeeping.ancestors[i];
    runExtractedEventsInBatch(bookKeeping.topLevelType, targetInst, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent));
  }
}

// TODO: can we stop exporting these?
var _enabled = true;

function setEnabled(enabled) {
  _enabled = !!enabled;
}

function isEnabled() {
  return _enabled;
}

/**
 * Traps top-level events by using event bubbling.
 *
 * @param {number} topLevelType Number from `TopLevelEventTypes`.
 * @param {object} element Element on which to attach listener.
 * @return {?object} An object with a remove function which will forcefully
 *                  remove the listener.
 * @internal
 */
function trapBubbledEvent(topLevelType, element) {
  if (!element) {
    return null;
  }
  var dispatch = isInteractiveTopLevelEventType(topLevelType) ? dispatchInteractiveEvent : dispatchEvent;

  addEventBubbleListener(element, getRawEventName(topLevelType),
  // Check if interactive and wrap in interactiveUpdates
  dispatch.bind(null, topLevelType));
}

/**
 * Traps a top-level event by using event capturing.
 *
 * @param {number} topLevelType Number from `TopLevelEventTypes`.
 * @param {object} element Element on which to attach listener.
 * @return {?object} An object with a remove function which will forcefully
 *                  remove the listener.
 * @internal
 */
function trapCapturedEvent(topLevelType, element) {
  if (!element) {
    return null;
  }
  var dispatch = isInteractiveTopLevelEventType(topLevelType) ? dispatchInteractiveEvent : dispatchEvent;

  addEventCaptureListener(element, getRawEventName(topLevelType),
  // Check if interactive and wrap in interactiveUpdates
  dispatch.bind(null, topLevelType));
}

function dispatchInteractiveEvent(topLevelType, nativeEvent) {
  interactiveUpdates(dispatchEvent, topLevelType, nativeEvent);
}

function dispatchEvent(topLevelType, nativeEvent) {
  if (!_enabled) {
    return;
  }

  var nativeEventTarget = getEventTarget(nativeEvent);
  var targetInst = getClosestInstanceFromNode(nativeEventTarget);
  if (targetInst !== null && typeof targetInst.tag === 'number' && !isFiberMounted(targetInst)) {
    // If we get an event (ex: img onload) before committing that
    // component's mount, ignore it for now (that is, treat it as if it was an
    // event on a non-React tree). We might also consider queueing events and
    // dispatching them after the mount.
    targetInst = null;
  }

  var bookKeeping = getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst);

  try {
    // Event queue being processed in the same cycle allows
    // `preventDefault`.
    batchedUpdates(handleTopLevel, bookKeeping);
  } finally {
    releaseTopLevelCallbackBookKeeping(bookKeeping);
  }
}

var ReactDOMEventListener = Object.freeze({
	get _enabled () { return _enabled; },
	setEnabled: setEnabled,
	isEnabled: isEnabled,
	trapBubbledEvent: trapBubbledEvent,
	trapCapturedEvent: trapCapturedEvent,
	dispatchEvent: dispatchEvent
});

/**
 * Summary of `ReactBrowserEventEmitter` event handling:
 *
 *  - Top-level delegation is used to trap most native browser events. This
 *    may only occur in the main thread and is the responsibility of
 *    ReactDOMEventListener, which is injected and can therefore support
 *    pluggable event sources. This is the only work that occurs in the main
 *    thread.
 *
 *  - We normalize and de-duplicate events to account for browser quirks. This
 *    may be done in the worker thread.
 *
 *  - Forward these native events (with the associated top-level type used to
 *    trap it) to `EventPluginHub`, which in turn will ask plugins if they want
 *    to extract any synthetic events.
 *
 *  - The `EventPluginHub` will then process each event by annotating them with
 *    "dispatches", a sequence of listeners and IDs that care about that event.
 *
 *  - The `EventPluginHub` then dispatches the events.
 *
 * Overview of React and the event system:
 *
 * +------------+    .
 * |    DOM     |    .
 * +------------+    .
 *       |           .
 *       v           .
 * +------------+    .
 * | ReactEvent |    .
 * |  Listener  |    .
 * +------------+    .                         +-----------+
 *       |           .               +--------+|SimpleEvent|
 *       |           .               |         |Plugin     |
 * +-----|------+    .               v         +-----------+
 * |     |      |    .    +--------------+                    +------------+
 * |     +-----------.--->|EventPluginHub|                    |    Event   |
 * |            |    .    |              |     +-----------+  | Propagators|
 * | ReactEvent |    .    |              |     |TapEvent   |  |------------|
 * |  Emitter   |    .    |              |<---+|Plugin     |  |other plugin|
 * |            |    .    |              |     +-----------+  |  utilities |
 * |     +-----------.--->|              |                    +------------+
 * |     |      |    .    +--------------+
 * +-----|------+    .                ^        +-----------+
 *       |           .                |        |Enter/Leave|
 *       +           .                +-------+|Plugin     |
 * +-------------+   .                         +-----------+
 * | application |   .
 * |-------------|   .
 * |             |   .
 * |             |   .
 * +-------------+   .
 *                   .
 *    React Core     .  General Purpose Event Plugin System
 */

var alreadyListeningTo = {};
var reactTopListenersCounter = 0;

/**
 * To ensure no conflicts with other potential React instances on the page
 */
var topListenersIDKey = '_reactListenersID' + ('' + Math.random()).slice(2);

function getListeningForDocument(mountAt) {
  // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty`
  // directly.
  if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) {
    mountAt[topListenersIDKey] = reactTopListenersCounter++;
    alreadyListeningTo[mountAt[topListenersIDKey]] = {};
  }
  return alreadyListeningTo[mountAt[topListenersIDKey]];
}

/**
 * We listen for bubbled touch events on the document object.
 *
 * Firefox v8.01 (and possibly others) exhibited strange behavior when
 * mounting `onmousemove` events at some node that was not the document
 * element. The symptoms were that if your mouse is not moving over something
 * contained within that mount point (for example on the background) the
 * top-level listeners for `onmousemove` won't be called. However, if you
 * register the `mousemove` on the document object, then it will of course
 * catch all `mousemove`s. This along with iOS quirks, justifies restricting
 * top-level listeners to the document object only, at least for these
 * movement types of events and possibly all events.
 *
 * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
 *
 * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
 * they bubble to document.
 *
 * @param {string} registrationName Name of listener (e.g. `onClick`).
 * @param {object} mountAt Container where to mount the listener
 */
function listenTo(registrationName, mountAt) {
  var isListening = getListeningForDocument(mountAt);
  var dependencies = registrationNameDependencies[registrationName];

  for (var i = 0; i < dependencies.length; i++) {
    var dependency = dependencies[i];
    if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) {
      switch (dependency) {
        case TOP_SCROLL:
          trapCapturedEvent(TOP_SCROLL, mountAt);
          break;
        case TOP_FOCUS:
        case TOP_BLUR:
          trapCapturedEvent(TOP_FOCUS, mountAt);
          trapCapturedEvent(TOP_BLUR, mountAt);
          // We set the flag for a single dependency later in this function,
          // but this ensures we mark both as attached rather than just one.
          isListening[TOP_BLUR] = true;
          isListening[TOP_FOCUS] = true;
          break;
        case TOP_CANCEL:
        case TOP_CLOSE:
          if (isEventSupported(getRawEventName(dependency), true)) {
            trapCapturedEvent(dependency, mountAt);
          }
          break;
        case TOP_INVALID:
        case TOP_SUBMIT:
        case TOP_RESET:
          // We listen to them on the target DOM elements.
          // Some of them bubble so we don't want them to fire twice.
          break;
        default:
          // By default, listen on the top level to all non-media events.
          // Media events don't bubble so adding the listener wouldn't do anything.
          var isMediaEvent = mediaEventTypes.indexOf(dependency) !== -1;
          if (!isMediaEvent) {
            trapBubbledEvent(dependency, mountAt);
          }
          break;
      }
      isListening[dependency] = true;
    }
  }
}

function isListeningToAllDependencies(registrationName, mountAt) {
  var isListening = getListeningForDocument(mountAt);
  var dependencies = registrationNameDependencies[registrationName];
  for (var i = 0; i < dependencies.length; i++) {
    var dependency = dependencies[i];
    if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) {
      return false;
    }
  }
  return true;
}

/**
 * Given any node return the first leaf node without children.
 *
 * @param {DOMElement|DOMTextNode} node
 * @return {DOMElement|DOMTextNode}
 */
function getLeafNode(node) {
  while (node && node.firstChild) {
    node = node.firstChild;
  }
  return node;
}

/**
 * Get the next sibling within a container. This will walk up the
 * DOM if a node's siblings have been exhausted.
 *
 * @param {DOMElement|DOMTextNode} node
 * @return {?DOMElement|DOMTextNode}
 */
function getSiblingNode(node) {
  while (node) {
    if (node.nextSibling) {
      return node.nextSibling;
    }
    node = node.parentNode;
  }
}

/**
 * Get object describing the nodes which contain characters at offset.
 *
 * @param {DOMElement|DOMTextNode} root
 * @param {number} offset
 * @return {?object}
 */
function getNodeForCharacterOffset(root, offset) {
  var node = getLeafNode(root);
  var nodeStart = 0;
  var nodeEnd = 0;

  while (node) {
    if (node.nodeType === TEXT_NODE) {
      nodeEnd = nodeStart + node.textContent.length;

      if (nodeStart <= offset && nodeEnd >= offset) {
        return {
          node: node,
          offset: offset - nodeStart
        };
      }

      nodeStart = nodeEnd;
    }

    node = getLeafNode(getSiblingNode(node));
  }
}

/**
 * @param {DOMElement} outerNode
 * @return {?object}
 */
function getOffsets(outerNode) {
  var selection = window.getSelection && window.getSelection();

  if (!selection || selection.rangeCount === 0) {
    return null;
  }

  var anchorNode = selection.anchorNode,
      anchorOffset = selection.anchorOffset,
      focusNode = selection.focusNode,
      focusOffset = selection.focusOffset;

  // In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the
  // up/down buttons on an <input type="number">. Anonymous divs do not seem to
  // expose properties, triggering a "Permission denied error" if any of its
  // properties are accessed. The only seemingly possible way to avoid erroring
  // is to access a property that typically works for non-anonymous divs and
  // catch any error that may otherwise arise. See
  // https://bugzilla.mozilla.org/show_bug.cgi?id=208427

  try {
    /* eslint-disable no-unused-expressions */
    anchorNode.nodeType;
    focusNode.nodeType;
    /* eslint-enable no-unused-expressions */
  } catch (e) {
    return null;
  }

  return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset);
}

/**
 * Returns {start, end} where `start` is the character/codepoint index of
 * (anchorNode, anchorOffset) within the textContent of `outerNode`, and
 * `end` is the index of (focusNode, focusOffset).
 *
 * Returns null if you pass in garbage input but we should probably just crash.
 *
 * Exported only for testing.
 */
function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) {
  var length = 0;
  var start = -1;
  var end = -1;
  var indexWithinAnchor = 0;
  var indexWithinFocus = 0;
  var node = outerNode;
  var parentNode = null;

  outer: while (true) {
    var next = null;

    while (true) {
      if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) {
        start = length + anchorOffset;
      }
      if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) {
        end = length + focusOffset;
      }

      if (node.nodeType === TEXT_NODE) {
        length += node.nodeValue.length;
      }

      if ((next = node.firstChild) === null) {
        break;
      }
      // Moving from `node` to its first child `next`.
      parentNode = node;
      node = next;
    }

    while (true) {
      if (node === outerNode) {
        // If `outerNode` has children, this is always the second time visiting
        // it. If it has no children, this is still the first loop, and the only
        // valid selection is anchorNode and focusNode both equal to this node
        // and both offsets 0, in which case we will have handled above.
        break outer;
      }
      if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) {
        start = length;
      }
      if (parentNode === focusNode && ++indexWithinFocus === focusOffset) {
        end = length;
      }
      if ((next = node.nextSibling) !== null) {
        break;
      }
      node = parentNode;
      parentNode = node.parentNode;
    }

    // Moving from `node` to its next sibling `next`.
    node = next;
  }

  if (start === -1 || end === -1) {
    // This should never happen. (Would happen if the anchor/focus nodes aren't
    // actually inside the passed-in node.)
    return null;
  }

  return {
    start: start,
    end: end
  };
}

/**
 * In modern non-IE browsers, we can support both forward and backward
 * selections.
 *
 * Note: IE10+ supports the Selection object, but it does not support
 * the `extend` method, which means that even in modern IE, it's not possible
 * to programmatically create a backward selection. Thus, for all IE
 * versions, we use the old IE API to create our selections.
 *
 * @param {DOMElement|DOMTextNode} node
 * @param {object} offsets
 */
function setOffsets(node, offsets) {
  if (!window.getSelection) {
    return;
  }

  var selection = window.getSelection();
  var length = node[getTextContentAccessor()].length;
  var start = Math.min(offsets.start, length);
  var end = offsets.end === undefined ? start : Math.min(offsets.end, length);

  // IE 11 uses modern selection, but doesn't support the extend method.
  // Flip backward selections, so we can set with a single range.
  if (!selection.extend && start > end) {
    var temp = end;
    end = start;
    start = temp;
  }

  var startMarker = getNodeForCharacterOffset(node, start);
  var endMarker = getNodeForCharacterOffset(node, end);

  if (startMarker && endMarker) {
    if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) {
      return;
    }
    var range = document.createRange();
    range.setStart(startMarker.node, startMarker.offset);
    selection.removeAllRanges();

    if (start > end) {
      selection.addRange(range);
      selection.extend(endMarker.node, endMarker.offset);
    } else {
      range.setEnd(endMarker.node, endMarker.offset);
      selection.addRange(range);
    }
  }
}

function isInDocument(node) {
  return containsNode(document.documentElement, node);
}

/**
 * @ReactInputSelection: React input selection module. Based on Selection.js,
 * but modified to be suitable for react and has a couple of bug fixes (doesn't
 * assume buttons have range selections allowed).
 * Input selection module for React.
 */

/**
 * @hasSelectionCapabilities: we get the element types that support selection
 * from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart`
 * and `selectionEnd` rows.
 */
function hasSelectionCapabilities(elem) {
  var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
  return nodeName && (nodeName === 'input' && (elem.type === 'text' || elem.type === 'search' || elem.type === 'tel' || elem.type === 'url' || elem.type === 'password') || nodeName === 'textarea' || elem.contentEditable === 'true');
}

function getSelectionInformation() {
  var focusedElem = getActiveElement();
  return {
    focusedElem: focusedElem,
    selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection$1(focusedElem) : null
  };
}

/**
 * @restoreSelection: If any selection information was potentially lost,
 * restore it. This is useful when performing operations that could remove dom
 * nodes and place them back in, resulting in focus being lost.
 */
function restoreSelection(priorSelectionInformation) {
  var curFocusedElem = getActiveElement();
  var priorFocusedElem = priorSelectionInformation.focusedElem;
  var priorSelectionRange = priorSelectionInformation.selectionRange;
  if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
    if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) {
      setSelection(priorFocusedElem, priorSelectionRange);
    }

    // Focusing a node can change the scroll position, which is undesirable
    var ancestors = [];
    var ancestor = priorFocusedElem;
    while (ancestor = ancestor.parentNode) {
      if (ancestor.nodeType === ELEMENT_NODE) {
        ancestors.push({
          element: ancestor,
          left: ancestor.scrollLeft,
          top: ancestor.scrollTop
        });
      }
    }

    if (typeof priorFocusedElem.focus === 'function') {
      priorFocusedElem.focus();
    }

    for (var i = 0; i < ancestors.length; i++) {
      var info = ancestors[i];
      info.element.scrollLeft = info.left;
      info.element.scrollTop = info.top;
    }
  }
}

/**
 * @getSelection: Gets the selection bounds of a focused textarea, input or
 * contentEditable node.
 * -@input: Look up selection bounds of this input
 * -@return {start: selectionStart, end: selectionEnd}
 */
function getSelection$1(input) {
  var selection = void 0;

  if ('selectionStart' in input) {
    // Modern browser with input or textarea.
    selection = {
      start: input.selectionStart,
      end: input.selectionEnd
    };
  } else {
    // Content editable or old IE textarea.
    selection = getOffsets(input);
  }

  return selection || { start: 0, end: 0 };
}

/**
 * @setSelection: Sets the selection bounds of a textarea or input and focuses
 * the input.
 * -@input     Set selection bounds of this input or textarea
 * -@offsets   Object of same form that is returned from get*
 */
function setSelection(input, offsets) {
  var start = offsets.start,
      end = offsets.end;

  if (end === undefined) {
    end = start;
  }

  if ('selectionStart' in input) {
    input.selectionStart = start;
    input.selectionEnd = Math.min(end, input.value.length);
  } else {
    setOffsets(input, offsets);
  }
}

var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && 'documentMode' in document && document.documentMode <= 11;

var eventTypes$3 = {
  select: {
    phasedRegistrationNames: {
      bubbled: 'onSelect',
      captured: 'onSelectCapture'
    },
    dependencies: [TOP_BLUR, TOP_CONTEXT_MENU, TOP_FOCUS, TOP_KEY_DOWN, TOP_KEY_UP, TOP_MOUSE_DOWN, TOP_MOUSE_UP, TOP_SELECTION_CHANGE]
  }
};

var activeElement$1 = null;
var activeElementInst$1 = null;
var lastSelection = null;
var mouseDown = false;

/**
 * Get an object which is a unique representation of the current selection.
 *
 * The return value will not be consistent across nodes or browsers, but
 * two identical selections on the same node will return identical objects.
 *
 * @param {DOMElement} node
 * @return {object}
 */
function getSelection(node) {
  if ('selectionStart' in node && hasSelectionCapabilities(node)) {
    return {
      start: node.selectionStart,
      end: node.selectionEnd
    };
  } else if (window.getSelection) {
    var selection = window.getSelection();
    return {
      anchorNode: selection.anchorNode,
      anchorOffset: selection.anchorOffset,
      focusNode: selection.focusNode,
      focusOffset: selection.focusOffset
    };
  }
}

/**
 * Poll selection to see whether it's changed.
 *
 * @param {object} nativeEvent
 * @return {?SyntheticEvent}
 */
function constructSelectEvent(nativeEvent, nativeEventTarget) {
  // Ensure we have the right element, and that the user is not dragging a
  // selection (this matches native `select` event behavior). In HTML5, select
  // fires only on input and textarea thus if there's no focused element we
  // won't dispatch.
  if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement()) {
    return null;
  }

  // Only fire when selection has actually changed.
  var currentSelection = getSelection(activeElement$1);
  if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
    lastSelection = currentSelection;

    var syntheticEvent = SyntheticEvent$1.getPooled(eventTypes$3.select, activeElementInst$1, nativeEvent, nativeEventTarget);

    syntheticEvent.type = 'select';
    syntheticEvent.target = activeElement$1;

    accumulateTwoPhaseDispatches(syntheticEvent);

    return syntheticEvent;
  }

  return null;
}

/**
 * This plugin creates an `onSelect` event that normalizes select events
 * across form elements.
 *
 * Supported elements are:
 * - input (see `isTextInputElement`)
 * - textarea
 * - contentEditable
 *
 * This differs from native browser implementations in the following ways:
 * - Fires on contentEditable fields as well as inputs.
 * - Fires for collapsed selection.
 * - Fires after user input.
 */
var SelectEventPlugin = {
  eventTypes: eventTypes$3,

  extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
    var doc = nativeEventTarget.window === nativeEventTarget ? nativeEventTarget.document : nativeEventTarget.nodeType === DOCUMENT_NODE ? nativeEventTarget : nativeEventTarget.ownerDocument;
    // Track whether all listeners exists for this plugin. If none exist, we do
    // not extract events. See #3639.
    if (!doc || !isListeningToAllDependencies('onSelect', doc)) {
      return null;
    }

    var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;

    switch (topLevelType) {
      // Track the input node that has focus.
      case TOP_FOCUS:
        if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') {
          activeElement$1 = targetNode;
          activeElementInst$1 = targetInst;
          lastSelection = null;
        }
        break;
      case TOP_BLUR:
        activeElement$1 = null;
        activeElementInst$1 = null;
        lastSelection = null;
        break;
      // Don't fire the event while the user is dragging. This matches the
      // semantics of the native select event.
      case TOP_MOUSE_DOWN:
        mouseDown = true;
        break;
      case TOP_CONTEXT_MENU:
      case TOP_MOUSE_UP:
        mouseDown = false;
        return constructSelectEvent(nativeEvent, nativeEventTarget);
      // Chrome and IE fire non-standard event when selection is changed (and
      // sometimes when it hasn't). IE's event fires out of order with respect
      // to key and input events on deletion, so we discard it.
      //
      // Firefox doesn't support selectionchange, so check selection status
      // after each key entry. The selection changes after keydown and before
      // keyup, but we check on keydown as well in the case of holding down a
      // key, when multiple keydown events are fired but only one keyup is.
      // This is also our approach for IE handling, for the reason above.
      case TOP_SELECTION_CHANGE:
        if (skipSelectionChangeEvent) {
          break;
        }
      // falls through
      case TOP_KEY_DOWN:
      case TOP_KEY_UP:
        return constructSelectEvent(nativeEvent, nativeEventTarget);
    }

    return null;
  }
};

/**
 * Inject modules for resolving DOM hierarchy and plugin ordering.
 */
injection.injectEventPluginOrder(DOMEventPluginOrder);
injection$1.injectComponentTree(ReactDOMComponentTree);

/**
 * Some important event plugins included by default (without having to require
 * them).
 */
injection.injectEventPluginsByName({
  SimpleEventPlugin: SimpleEventPlugin,
  EnterLeaveEventPlugin: EnterLeaveEventPlugin,
  ChangeEventPlugin: ChangeEventPlugin,
  SelectEventPlugin: SelectEventPlugin,
  BeforeInputEventPlugin: BeforeInputEventPlugin
});

// We capture a local reference to any global, in case it gets polyfilled after
// this module is initially evaluated.
// We want to be using a consistent implementation.

var localRequestAnimationFrame$1 = typeof requestAnimationFrame === 'function' ? requestAnimationFrame : undefined;

/**
 * A scheduling library to allow scheduling work with more granular priority and
 * control than requestAnimationFrame and requestIdleCallback.
 * Current TODO items:
 * X- Pull out the scheduleWork polyfill built into React
 * X- Initial test coverage
 * X- Support for multiple callbacks
 * - Support for two priorities; serial and deferred
 * - Better test coverage
 * - Better docblock
 * - Polish documentation, API
 */

// This is a built-in polyfill for requestIdleCallback. It works by scheduling
// a requestAnimationFrame, storing the time for the start of the frame, then
// scheduling a postMessage which gets scheduled after paint. Within the
// postMessage handler do as much work as possible until time + frame rate.
// By separating the idle call into a separate event tick we ensure that
// layout, paint and other browser work is counted against the available time.
// The frame rate is dynamically adjusted.

// We capture a local reference to any global, in case it gets polyfilled after
// this module is initially evaluated.
// We want to be using a consistent implementation.
var localDate = Date;
var localSetTimeout = setTimeout;
var localClearTimeout = clearTimeout;

var hasNativePerformanceNow = typeof performance === 'object' && typeof performance.now === 'function';

var now$1 = void 0;
if (hasNativePerformanceNow) {
  var Performance = performance;
  now$1 = function () {
    return Performance.now();
  };
} else {
  now$1 = function () {
    return localDate.now();
  };
}

var scheduleWork = void 0;
var cancelScheduledWork = void 0;

if (!ExecutionEnvironment.canUseDOM) {
  var timeoutIds = new Map();

  scheduleWork = function (callback, options) {
    // keeping return type consistent
    var callbackConfig = {
      scheduledCallback: callback,
      timeoutTime: 0,
      next: null,
      prev: null
    };
    var timeoutId = localSetTimeout(function () {
      callback({
        timeRemaining: function () {
          return Infinity;
        },

        didTimeout: false
      });
    });
    timeoutIds.set(callback, timeoutId);
    return callbackConfig;
  };
  cancelScheduledWork = function (callbackId) {
    var callback = callbackId.scheduledCallback;
    var timeoutId = timeoutIds.get(callback);
    timeoutIds.delete(callbackId);
    localClearTimeout(timeoutId);
  };
} else {
  {
    if (typeof localRequestAnimationFrame$1 !== 'function') {
      warning(false, 'React depends on requestAnimationFrame. Make sure that you load a ' + 'polyfill in older browsers. https://fb.me/react-polyfills');
    }
  }

  var localRequestAnimationFrame = typeof localRequestAnimationFrame$1 === 'function' ? localRequestAnimationFrame$1 : function (callback) {
    invariant(false, 'React depends on requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills');
  };

  var headOfPendingCallbacksLinkedList = null;
  var tailOfPendingCallbacksLinkedList = null;

  // We track what the next soonest timeoutTime is, to be able to quickly tell
  // if none of the scheduled callbacks have timed out.
  var nextSoonestTimeoutTime = -1;

  var isIdleScheduled = false;
  var isAnimationFrameScheduled = false;

  var frameDeadline = 0;
  // We start out assuming that we run at 30fps but then the heuristic tracking
  // will adjust this value to a faster fps if we get more frequent animation
  // frames.
  var previousFrameTime = 33;
  var activeFrameTime = 33;

  var frameDeadlineObject = {
    didTimeout: false,
    timeRemaining: function () {
      var remaining = frameDeadline - now$1();
      return remaining > 0 ? remaining : 0;
    }
  };

  /**
   * Handles the case where a callback errors:
   * - don't catch the error, because this changes debugging behavior
   * - do start a new postMessage callback, to call any remaining callbacks,
   * - but only if there is an error, so there is not extra overhead.
   */
  var callUnsafely = function (callbackConfig, arg) {
    var callback = callbackConfig.scheduledCallback;
    var finishedCalling = false;
    try {
      callback(arg);
      finishedCalling = true;
    } finally {
      // always remove it from linked list
      cancelScheduledWork(callbackConfig);

      if (!finishedCalling) {
        // an error must have been thrown
        isIdleScheduled = true;
        window.postMessage(messageKey, '*');
      }
    }
  };

  /**
   * Checks for timed out callbacks, runs them, and then checks again to see if
   * any more have timed out.
   * Keeps doing this until there are none which have currently timed out.
   */
  var callTimedOutCallbacks = function () {
    if (headOfPendingCallbacksLinkedList === null) {
      return;
    }

    var currentTime = now$1();
    // TODO: this would be more efficient if deferred callbacks are stored in
    // min heap.
    // Or in a linked list with links for both timeoutTime order and insertion
    // order.
    // For now an easy compromise is the current approach:
    // Keep a pointer to the soonest timeoutTime, and check that first.
    // If it has not expired, we can skip traversing the whole list.
    // If it has expired, then we step through all the callbacks.
    if (nextSoonestTimeoutTime === -1 || nextSoonestTimeoutTime > currentTime) {
      // We know that none of them have timed out yet.
      return;
    }
    // NOTE: we intentionally wait to update the nextSoonestTimeoutTime until
    // after successfully calling any timed out callbacks.
    // If a timed out callback throws an error, we could get stuck in a state
    // where the nextSoonestTimeoutTime was set wrong.
    var updatedNextSoonestTimeoutTime = -1; // we will update nextSoonestTimeoutTime below
    var timedOutCallbacks = [];

    // iterate once to find timed out callbacks and find nextSoonestTimeoutTime
    var currentCallbackConfig = headOfPendingCallbacksLinkedList;
    while (currentCallbackConfig !== null) {
      var _timeoutTime = currentCallbackConfig.timeoutTime;
      if (_timeoutTime !== -1 && _timeoutTime <= currentTime) {
        // it has timed out!
        timedOutCallbacks.push(currentCallbackConfig);
      } else {
        if (_timeoutTime !== -1 && (updatedNextSoonestTimeoutTime === -1 || _timeoutTime < updatedNextSoonestTimeoutTime)) {
          updatedNextSoonestTimeoutTime = _timeoutTime;
        }
      }
      currentCallbackConfig = currentCallbackConfig.next;
    }

    if (timedOutCallbacks.length > 0) {
      frameDeadlineObject.didTimeout = true;
      for (var i = 0, len = timedOutCallbacks.length; i < len; i++) {
        callUnsafely(timedOutCallbacks[i], frameDeadlineObject);
      }
    }

    // NOTE: we intentionally wait to update the nextSoonestTimeoutTime until
    // after successfully calling any timed out callbacks.
    nextSoonestTimeoutTime = updatedNextSoonestTimeoutTime;
  };

  // We use the postMessage trick to defer idle work until after the repaint.
  var messageKey = '__reactIdleCallback$' + Math.random().toString(36).slice(2);
  var idleTick = function (event) {
    if (event.source !== window || event.data !== messageKey) {
      return;
    }
    isIdleScheduled = false;

    if (headOfPendingCallbacksLinkedList === null) {
      return;
    }

    // First call anything which has timed out, until we have caught up.
    callTimedOutCallbacks();

    var currentTime = now$1();
    // Next, as long as we have idle time, try calling more callbacks.
    while (frameDeadline - currentTime > 0 && headOfPendingCallbacksLinkedList !== null) {
      var latestCallbackConfig = headOfPendingCallbacksLinkedList;
      frameDeadlineObject.didTimeout = false;
      // callUnsafely will remove it from the head of the linked list
      callUnsafely(latestCallbackConfig, frameDeadlineObject);
      currentTime = now$1();
    }
    if (headOfPendingCallbacksLinkedList !== null) {
      if (!isAnimationFrameScheduled) {
        // Schedule another animation callback so we retry later.
        isAnimationFrameScheduled = true;
        localRequestAnimationFrame(animationTick);
      }
    }
  };
  // Assumes that we have addEventListener in this environment. Might need
  // something better for old IE.
  window.addEventListener('message', idleTick, false);

  var animationTick = function (rafTime) {
    isAnimationFrameScheduled = false;
    var nextFrameTime = rafTime - frameDeadline + activeFrameTime;
    if (nextFrameTime < activeFrameTime && previousFrameTime < activeFrameTime) {
      if (nextFrameTime < 8) {
        // Defensive coding. We don't support higher frame rates than 120hz.
        // If we get lower than that, it is probably a bug.
        nextFrameTime = 8;
      }
      // If one frame goes long, then the next one can be short to catch up.
      // If two frames are short in a row, then that's an indication that we
      // actually have a higher frame rate than what we're currently optimizing.
      // We adjust our heuristic dynamically accordingly. For example, if we're
      // running on 120hz display or 90hz VR display.
      // Take the max of the two in case one of them was an anomaly due to
      // missed frame deadlines.
      activeFrameTime = nextFrameTime < previousFrameTime ? previousFrameTime : nextFrameTime;
    } else {
      previousFrameTime = nextFrameTime;
    }
    frameDeadline = rafTime + activeFrameTime;
    if (!isIdleScheduled) {
      isIdleScheduled = true;
      window.postMessage(messageKey, '*');
    }
  };

  scheduleWork = function (callback, options) /* CallbackConfigType */{
    var timeoutTime = -1;
    if (options != null && typeof options.timeout === 'number') {
      timeoutTime = now$1() + options.timeout;
    }
    if (nextSoonestTimeoutTime === -1 || timeoutTime !== -1 && timeoutTime < nextSoonestTimeoutTime) {
      nextSoonestTimeoutTime = timeoutTime;
    }

    var scheduledCallbackConfig = {
      scheduledCallback: callback,
      timeoutTime: timeoutTime,
      prev: null,
      next: null
    };
    if (headOfPendingCallbacksLinkedList === null) {
      // Make this callback the head and tail of our list
      headOfPendingCallbacksLinkedList = scheduledCallbackConfig;
      tailOfPendingCallbacksLinkedList = scheduledCallbackConfig;
    } else {
      // Add latest callback as the new tail of the list
      scheduledCallbackConfig.prev = tailOfPendingCallbacksLinkedList;
      // renaming for clarity
      var oldTailOfPendingCallbacksLinkedList = tailOfPendingCallbacksLinkedList;
      if (oldTailOfPendingCallbacksLinkedList !== null) {
        oldTailOfPendingCallbacksLinkedList.next = scheduledCallbackConfig;
      }
      tailOfPendingCallbacksLinkedList = scheduledCallbackConfig;
    }

    if (!isAnimationFrameScheduled) {
      // If rAF didn't already schedule one, we need to schedule a frame.
      // TODO: If this rAF doesn't materialize because the browser throttles, we
      // might want to still have setTimeout trigger scheduleWork as a backup to ensure
      // that we keep performing work.
      isAnimationFrameScheduled = true;
      localRequestAnimationFrame(animationTick);
    }
    return scheduledCallbackConfig;
  };

  cancelScheduledWork = function (callbackConfig /* CallbackConfigType */
  ) {
    if (callbackConfig.prev === null && headOfPendingCallbacksLinkedList !== callbackConfig) {
      // this callbackConfig has already been cancelled.
      // cancelScheduledWork should be idempotent, a no-op after first call.
      return;
    }

    /**
     * There are four possible cases:
     * - Head/nodeToRemove/Tail -> null
     *   In this case we set Head and Tail to null.
     * - Head -> ... middle nodes... -> Tail/nodeToRemove
     *   In this case we point the middle.next to null and put middle as the new
     *   Tail.
     * - Head/nodeToRemove -> ...middle nodes... -> Tail
     *   In this case we point the middle.prev at null and move the Head to
     *   middle.
     * - Head -> ... ?some nodes ... -> nodeToRemove -> ... ?some nodes ... -> Tail
     *   In this case we point the Head.next to the Tail and the Tail.prev to
     *   the Head.
     */
    var next = callbackConfig.next;
    var prev = callbackConfig.prev;
    callbackConfig.next = null;
    callbackConfig.prev = null;
    if (next !== null) {
      // we have a next

      if (prev !== null) {
        // we have a prev

        // callbackConfig is somewhere in the middle of a list of 3 or more nodes.
        prev.next = next;
        next.prev = prev;
        return;
      } else {
        // there is a next but not a previous one;
        // callbackConfig is the head of a list of 2 or more other nodes.
        next.prev = null;
        headOfPendingCallbacksLinkedList = next;
        return;
      }
    } else {
      // there is no next callback config; this must the tail of the list

      if (prev !== null) {
        // we have a prev

        // callbackConfig is the tail of a list of 2 or more other nodes.
        prev.next = null;
        tailOfPendingCallbacksLinkedList = prev;
        return;
      } else {
        // there is no previous callback config;
        // callbackConfig is the only thing in the linked list,
        // so both head and tail point to it.
        headOfPendingCallbacksLinkedList = null;
        tailOfPendingCallbacksLinkedList = null;
        return;
      }
    }
  };
}

var didWarnSelectedSetOnOption = false;

function flattenChildren(children) {
  var content = '';

  // Flatten children and warn if they aren't strings or numbers;
  // invalid types are ignored.
  // We can silently skip them because invalid DOM nesting warning
  // catches these cases in Fiber.
  React.Children.forEach(children, function (child) {
    if (child == null) {
      return;
    }
    if (typeof child === 'string' || typeof child === 'number') {
      content += child;
    }
  });

  return content;
}

/**
 * Implements an <option> host component that warns when `selected` is set.
 */

function validateProps(element, props) {
  // TODO (yungsters): Remove support for `selected` in <option>.
  {
    if (props.selected != null && !didWarnSelectedSetOnOption) {
      warning(false, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');
      didWarnSelectedSetOnOption = true;
    }
  }
}

function postMountWrapper$1(element, props) {
  // value="" should make a value attribute (#6219)
  if (props.value != null) {
    element.setAttribute('value', props.value);
  }
}

function getHostProps$1(element, props) {
  var hostProps = _assign({ children: undefined }, props);
  var content = flattenChildren(props.children);

  if (content) {
    hostProps.children = content;
  }

  return hostProps;
}

// TODO: direct imports like some-package/src/* are bad. Fix me.
var getCurrentFiberOwnerName$3 = ReactDebugCurrentFiber.getCurrentFiberOwnerName;
var getCurrentFiberStackAddendum$3 = ReactDebugCurrentFiber.getCurrentFiberStackAddendum;


var didWarnValueDefaultValue$1 = void 0;

{
  didWarnValueDefaultValue$1 = false;
}

function getDeclarationErrorAddendum() {
  var ownerName = getCurrentFiberOwnerName$3();
  if (ownerName) {
    return '\n\nCheck the render method of `' + ownerName + '`.';
  }
  return '';
}

var valuePropNames = ['value', 'defaultValue'];

/**
 * Validation function for `value` and `defaultValue`.
 */
function checkSelectPropTypes(props) {
  ReactControlledValuePropTypes.checkPropTypes('select', props, getCurrentFiberStackAddendum$3);

  for (var i = 0; i < valuePropNames.length; i++) {
    var propName = valuePropNames[i];
    if (props[propName] == null) {
      continue;
    }
    var isArray = Array.isArray(props[propName]);
    if (props.multiple && !isArray) {
      warning(false, 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum());
    } else if (!props.multiple && isArray) {
      warning(false, 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum());
    }
  }
}

function updateOptions(node, multiple, propValue, setDefaultSelected) {
  var options = node.options;

  if (multiple) {
    var selectedValues = propValue;
    var selectedValue = {};
    for (var i = 0; i < selectedValues.length; i++) {
      // Prefix to avoid chaos with special keys.
      selectedValue['$' + selectedValues[i]] = true;
    }
    for (var _i = 0; _i < options.length; _i++) {
      var selected = selectedValue.hasOwnProperty('$' + options[_i].value);
      if (options[_i].selected !== selected) {
        options[_i].selected = selected;
      }
      if (selected && setDefaultSelected) {
        options[_i].defaultSelected = true;
      }
    }
  } else {
    // Do not set `select.value` as exact behavior isn't consistent across all
    // browsers for all cases.
    var _selectedValue = '' + propValue;
    var defaultSelected = null;
    for (var _i2 = 0; _i2 < options.length; _i2++) {
      if (options[_i2].value === _selectedValue) {
        options[_i2].selected = true;
        if (setDefaultSelected) {
          options[_i2].defaultSelected = true;
        }
        return;
      }
      if (defaultSelected === null && !options[_i2].disabled) {
        defaultSelected = options[_i2];
      }
    }
    if (defaultSelected !== null) {
      defaultSelected.selected = true;
    }
  }
}

/**
 * Implements a <select> host component that allows optionally setting the
 * props `value` and `defaultValue`. If `multiple` is false, the prop must be a
 * stringable. If `multiple` is true, the prop must be an array of stringables.
 *
 * If `value` is not supplied (or null/undefined), user actions that change the
 * selected option will trigger updates to the rendered options.
 *
 * If it is supplied (and not null/undefined), the rendered options will not
 * update in response to user actions. Instead, the `value` prop must change in
 * order for the rendered options to update.
 *
 * If `defaultValue` is provided, any options with the supplied values will be
 * selected.
 */

function getHostProps$2(element, props) {
  return _assign({}, props, {
    value: undefined
  });
}

function initWrapperState$1(element, props) {
  var node = element;
  {
    checkSelectPropTypes(props);
  }

  var value = props.value;
  node._wrapperState = {
    initialValue: value != null ? value : props.defaultValue,
    wasMultiple: !!props.multiple
  };

  {
    if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue$1) {
      warning(false, 'Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components');
      didWarnValueDefaultValue$1 = true;
    }
  }
}

function postMountWrapper$2(element, props) {
  var node = element;
  node.multiple = !!props.multiple;
  var value = props.value;
  if (value != null) {
    updateOptions(node, !!props.multiple, value, false);
  } else if (props.defaultValue != null) {
    updateOptions(node, !!props.multiple, props.defaultValue, true);
  }
}

function postUpdateWrapper(element, props) {
  var node = element;
  // After the initial mount, we control selected-ness manually so don't pass
  // this value down
  node._wrapperState.initialValue = undefined;

  var wasMultiple = node._wrapperState.wasMultiple;
  node._wrapperState.wasMultiple = !!props.multiple;

  var value = props.value;
  if (value != null) {
    updateOptions(node, !!props.multiple, value, false);
  } else if (wasMultiple !== !!props.multiple) {
    // For simplicity, reapply `defaultValue` if `multiple` is toggled.
    if (props.defaultValue != null) {
      updateOptions(node, !!props.multiple, props.defaultValue, true);
    } else {
      // Revert the select back to its default unselected state.
      updateOptions(node, !!props.multiple, props.multiple ? [] : '', false);
    }
  }
}

function restoreControlledState$2(element, props) {
  var node = element;
  var value = props.value;

  if (value != null) {
    updateOptions(node, !!props.multiple, value, false);
  }
}

// TODO: direct imports like some-package/src/* are bad. Fix me.
var getCurrentFiberStackAddendum$4 = ReactDebugCurrentFiber.getCurrentFiberStackAddendum;

var didWarnValDefaultVal = false;

/**
 * Implements a <textarea> host component that allows setting `value`, and
 * `defaultValue`. This differs from the traditional DOM API because value is
 * usually set as PCDATA children.
 *
 * If `value` is not supplied (or null/undefined), user actions that affect the
 * value will trigger updates to the element.
 *
 * If `value` is supplied (and not null/undefined), the rendered element will
 * not trigger updates to the element. Instead, the `value` prop must change in
 * order for the rendered element to be updated.
 *
 * The rendered element will be initialized with an empty value, the prop
 * `defaultValue` if specified, or the children content (deprecated).
 */

function getHostProps$3(element, props) {
  var node = element;
  !(props.dangerouslySetInnerHTML == null) ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : void 0;

  // Always set children to the same thing. In IE9, the selection range will
  // get reset if `textContent` is mutated.  We could add a check in setTextContent
  // to only set the value if/when the value differs from the node value (which would
  // completely solve this IE9 bug), but Sebastian+Sophie seemed to like this
  // solution. The value can be a boolean or object so that's why it's forced
  // to be a string.
  var hostProps = _assign({}, props, {
    value: undefined,
    defaultValue: undefined,
    children: '' + node._wrapperState.initialValue
  });

  return hostProps;
}

function initWrapperState$2(element, props) {
  var node = element;
  {
    ReactControlledValuePropTypes.checkPropTypes('textarea', props, getCurrentFiberStackAddendum$4);
    if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) {
      warning(false, 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components');
      didWarnValDefaultVal = true;
    }
  }

  var initialValue = props.value;

  // Only bother fetching default value if we're going to use it
  if (initialValue == null) {
    var defaultValue = props.defaultValue;
    // TODO (yungsters): Remove support for children content in <textarea>.
    var children = props.children;
    if (children != null) {
      {
        warning(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
      }
      !(defaultValue == null) ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : void 0;
      if (Array.isArray(children)) {
        !(children.length <= 1) ? invariant(false, '<textarea> can only have at most one child.') : void 0;
        children = children[0];
      }

      defaultValue = '' + children;
    }
    if (defaultValue == null) {
      defaultValue = '';
    }
    initialValue = defaultValue;
  }

  node._wrapperState = {
    initialValue: '' + initialValue
  };
}

function updateWrapper$1(element, props) {
  var node = element;
  var value = props.value;
  if (value != null) {
    // Cast `value` to a string to ensure the value is set correctly. While
    // browsers typically do this as necessary, jsdom doesn't.
    var newValue = '' + value;

    // To avoid side effects (such as losing text selection), only set value if changed
    if (newValue !== node.value) {
      node.value = newValue;
    }
    if (props.defaultValue == null) {
      node.defaultValue = newValue;
    }
  }
  if (props.defaultValue != null) {
    node.defaultValue = props.defaultValue;
  }
}

function postMountWrapper$3(element, props) {
  var node = element;
  // This is in postMount because we need access to the DOM node, which is not
  // available until after the component has mounted.
  var textContent = node.textContent;

  // Only set node.value if textContent is equal to the expected
  // initial value. In IE10/IE11 there is a bug where the placeholder attribute
  // will populate textContent as well.
  // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/
  if (textContent === node._wrapperState.initialValue) {
    node.value = textContent;
  }
}

function restoreControlledState$3(element, props) {
  // DOM component is still mounted; update
  updateWrapper$1(element, props);
}

var HTML_NAMESPACE$1 = 'http://www.w3.org/1999/xhtml';
var MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';

var Namespaces = {
  html: HTML_NAMESPACE$1,
  mathml: MATH_NAMESPACE,
  svg: SVG_NAMESPACE
};

// Assumes there is no parent namespace.
function getIntrinsicNamespace(type) {
  switch (type) {
    case 'svg':
      return SVG_NAMESPACE;
    case 'math':
      return MATH_NAMESPACE;
    default:
      return HTML_NAMESPACE$1;
  }
}

function getChildNamespace(parentNamespace, type) {
  if (parentNamespace == null || parentNamespace === HTML_NAMESPACE$1) {
    // No (or default) parent namespace: potential entry point.
    return getIntrinsicNamespace(type);
  }
  if (parentNamespace === SVG_NAMESPACE && type === 'foreignObject') {
    // We're leaving SVG.
    return HTML_NAMESPACE$1;
  }
  // By default, pass namespace below.
  return parentNamespace;
}

/* globals MSApp */

/**
 * Create a function which has 'unsafe' privileges (required by windows8 apps)
 */
var createMicrosoftUnsafeLocalFunction = function (func) {
  if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
    return function (arg0, arg1, arg2, arg3) {
      MSApp.execUnsafeLocalFunction(function () {
        return func(arg0, arg1, arg2, arg3);
      });
    };
  } else {
    return func;
  }
};

// SVG temp container for IE lacking innerHTML
var reusableSVGContainer = void 0;

/**
 * Set the innerHTML property of a node
 *
 * @param {DOMElement} node
 * @param {string} html
 * @internal
 */
var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) {
  // IE does not have innerHTML for SVG nodes, so instead we inject the
  // new markup in a temp node and then move the child nodes across into
  // the target node

  if (node.namespaceURI === Namespaces.svg && !('innerHTML' in node)) {
    reusableSVGContainer = reusableSVGContainer || document.createElement('div');
    reusableSVGContainer.innerHTML = '<svg>' + html + '</svg>';
    var svgNode = reusableSVGContainer.firstChild;
    while (node.firstChild) {
      node.removeChild(node.firstChild);
    }
    while (svgNode.firstChild) {
      node.appendChild(svgNode.firstChild);
    }
  } else {
    node.innerHTML = html;
  }
});

/**
 * Set the textContent property of a node. For text updates, it's faster
 * to set the `nodeValue` of the Text node directly instead of using
 * `.textContent` which will remove the existing node and create a new one.
 *
 * @param {DOMElement} node
 * @param {string} text
 * @internal
 */
var setTextContent = function (node, text) {
  if (text) {
    var firstChild = node.firstChild;

    if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {
      firstChild.nodeValue = text;
      return;
    }
  }
  node.textContent = text;
};

/**
 * CSS properties which accept numbers but are not in units of "px".
 */
var isUnitlessNumber = {
  animationIterationCount: true,
  borderImageOutset: true,
  borderImageSlice: true,
  borderImageWidth: true,
  boxFlex: true,
  boxFlexGroup: true,
  boxOrdinalGroup: true,
  columnCount: true,
  columns: true,
  flex: true,
  flexGrow: true,
  flexPositive: true,
  flexShrink: true,
  flexNegative: true,
  flexOrder: true,
  gridRow: true,
  gridRowEnd: true,
  gridRowSpan: true,
  gridRowStart: true,
  gridColumn: true,
  gridColumnEnd: true,
  gridColumnSpan: true,
  gridColumnStart: true,
  fontWeight: true,
  lineClamp: true,
  lineHeight: true,
  opacity: true,
  order: true,
  orphans: true,
  tabSize: true,
  widows: true,
  zIndex: true,
  zoom: true,

  // SVG-related properties
  fillOpacity: true,
  floodOpacity: true,
  stopOpacity: true,
  strokeDasharray: true,
  strokeDashoffset: true,
  strokeMiterlimit: true,
  strokeOpacity: true,
  strokeWidth: true
};

/**
 * @param {string} prefix vendor-specific prefix, eg: Webkit
 * @param {string} key style name, eg: transitionDuration
 * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
 * WebkitTransitionDuration
 */
function prefixKey(prefix, key) {
  return prefix + key.charAt(0).toUpperCase() + key.substring(1);
}

/**
 * Support style names that may come passed in prefixed by adding permutations
 * of vendor prefixes.
 */
var prefixes = ['Webkit', 'ms', 'Moz', 'O'];

// Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
// infinite loop, because it iterates over the newly added props too.
Object.keys(isUnitlessNumber).forEach(function (prop) {
  prefixes.forEach(function (prefix) {
    isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
  });
});

/**
 * Convert a value into the proper css writable value. The style name `name`
 * should be logical (no hyphens), as specified
 * in `CSSProperty.isUnitlessNumber`.
 *
 * @param {string} name CSS property name such as `topMargin`.
 * @param {*} value CSS property value such as `10px`.
 * @return {string} Normalized style value with dimensions applied.
 */
function dangerousStyleValue(name, value, isCustomProperty) {
  // Note that we've removed escapeTextForBrowser() calls here since the
  // whole string will be escaped when the attribute is injected into
  // the markup. If you provide unsafe user data here they can inject
  // arbitrary CSS which may be problematic (I couldn't repro this):
  // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
  // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
  // This is not an XSS hole but instead a potential CSS injection issue
  // which has lead to a greater discussion about how we're going to
  // trust URLs moving forward. See #2115901

  var isEmpty = value == null || typeof value === 'boolean' || value === '';
  if (isEmpty) {
    return '';
  }

  if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) {
    return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers
  }

  return ('' + value).trim();
}

var warnValidStyle = emptyFunction;

{
  // 'msTransform' is correct, but the other prefixes should be capitalized
  var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;

  // style values shouldn't contain a semicolon
  var badStyleValueWithSemicolonPattern = /;\s*$/;

  var warnedStyleNames = {};
  var warnedStyleValues = {};
  var warnedForNaNValue = false;
  var warnedForInfinityValue = false;

  var warnHyphenatedStyleName = function (name, getStack) {
    if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
      return;
    }

    warnedStyleNames[name] = true;
    warning(false, 'Unsupported style property %s. Did you mean %s?%s', name, camelizeStyleName(name), getStack());
  };

  var warnBadVendoredStyleName = function (name, getStack) {
    if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
      return;
    }

    warnedStyleNames[name] = true;
    warning(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?%s', name, name.charAt(0).toUpperCase() + name.slice(1), getStack());
  };

  var warnStyleValueWithSemicolon = function (name, value, getStack) {
    if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
      return;
    }

    warnedStyleValues[value] = true;
    warning(false, "Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.%s', name, value.replace(badStyleValueWithSemicolonPattern, ''), getStack());
  };

  var warnStyleValueIsNaN = function (name, value, getStack) {
    if (warnedForNaNValue) {
      return;
    }

    warnedForNaNValue = true;
    warning(false, '`NaN` is an invalid value for the `%s` css style property.%s', name, getStack());
  };

  var warnStyleValueIsInfinity = function (name, value, getStack) {
    if (warnedForInfinityValue) {
      return;
    }

    warnedForInfinityValue = true;
    warning(false, '`Infinity` is an invalid value for the `%s` css style property.%s', name, getStack());
  };

  warnValidStyle = function (name, value, getStack) {
    if (name.indexOf('-') > -1) {
      warnHyphenatedStyleName(name, getStack);
    } else if (badVendoredStyleNamePattern.test(name)) {
      warnBadVendoredStyleName(name, getStack);
    } else if (badStyleValueWithSemicolonPattern.test(value)) {
      warnStyleValueWithSemicolon(name, value, getStack);
    }

    if (typeof value === 'number') {
      if (isNaN(value)) {
        warnStyleValueIsNaN(name, value, getStack);
      } else if (!isFinite(value)) {
        warnStyleValueIsInfinity(name, value, getStack);
      }
    }
  };
}

var warnValidStyle$1 = warnValidStyle;

/**
 * Operations for dealing with CSS properties.
 */

/**
 * This creates a string that is expected to be equivalent to the style
 * attribute generated by server-side rendering. It by-passes warnings and
 * security checks so it's not safe to use this value for anything other than
 * comparison. It is only used in DEV for SSR validation.
 */
function createDangerousStringForStyles(styles) {
  {
    var serialized = '';
    var delimiter = '';
    for (var styleName in styles) {
      if (!styles.hasOwnProperty(styleName)) {
        continue;
      }
      var styleValue = styles[styleName];
      if (styleValue != null) {
        var isCustomProperty = styleName.indexOf('--') === 0;
        serialized += delimiter + hyphenateStyleName(styleName) + ':';
        serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);

        delimiter = ';';
      }
    }
    return serialized || null;
  }
}

/**
 * Sets the value for multiple styles on a node.  If a value is specified as
 * '' (empty string), the corresponding style property will be unset.
 *
 * @param {DOMElement} node
 * @param {object} styles
 */
function setValueForStyles(node, styles, getStack) {
  var style = node.style;
  for (var styleName in styles) {
    if (!styles.hasOwnProperty(styleName)) {
      continue;
    }
    var isCustomProperty = styleName.indexOf('--') === 0;
    {
      if (!isCustomProperty) {
        warnValidStyle$1(styleName, styles[styleName], getStack);
      }
    }
    var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty);
    if (styleName === 'float') {
      styleName = 'cssFloat';
    }
    if (isCustomProperty) {
      style.setProperty(styleName, styleValue);
    } else {
      style[styleName] = styleValue;
    }
  }
}

// For HTML, certain tags should omit their close tag. We keep a whitelist for
// those special-case tags.

var omittedCloseTags = {
  area: true,
  base: true,
  br: true,
  col: true,
  embed: true,
  hr: true,
  img: true,
  input: true,
  keygen: true,
  link: true,
  meta: true,
  param: true,
  source: true,
  track: true,
  wbr: true
  // NOTE: menuitem's close tag should be omitted, but that causes problems.
};

// For HTML, certain tags cannot have children. This has the same purpose as
// `omittedCloseTags` except that `menuitem` should still have its closing tag.

var voidElementTags = _assign({
  menuitem: true
}, omittedCloseTags);

var HTML$1 = '__html';

function assertValidProps(tag, props, getStack) {
  if (!props) {
    return;
  }
  // Note the use of `==` which checks for null or undefined.
  if (voidElementTags[tag]) {
    !(props.children == null && props.dangerouslySetInnerHTML == null) ? invariant(false, '%s is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.%s', tag, getStack()) : void 0;
  }
  if (props.dangerouslySetInnerHTML != null) {
    !(props.children == null) ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : void 0;
    !(typeof props.dangerouslySetInnerHTML === 'object' && HTML$1 in props.dangerouslySetInnerHTML) ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.') : void 0;
  }
  {
    !(props.suppressContentEditableWarning || !props.contentEditable || props.children == null) ? warning(false, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.%s', getStack()) : void 0;
  }
  !(props.style == null || typeof props.style === 'object') ? invariant(false, 'The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + \'em\'}} when using JSX.%s', getStack()) : void 0;
}

function isCustomComponent(tagName, props) {
  if (tagName.indexOf('-') === -1) {
    return typeof props.is === 'string';
  }
  switch (tagName) {
    // These are reserved SVG and MathML elements.
    // We don't mind this whitelist too much because we expect it to never grow.
    // The alternative is to track the namespace in a few places which is convoluted.
    // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
    case 'annotation-xml':
    case 'color-profile':
    case 'font-face':
    case 'font-face-src':
    case 'font-face-uri':
    case 'font-face-format':
    case 'font-face-name':
    case 'missing-glyph':
      return false;
    default:
      return true;
  }
}

// When adding attributes to the HTML or SVG whitelist, be sure to
// also add them to this module to ensure casing and incorrect name
// warnings.
var possibleStandardNames = {
  // HTML
  accept: 'accept',
  acceptcharset: 'acceptCharset',
  'accept-charset': 'acceptCharset',
  accesskey: 'accessKey',
  action: 'action',
  allowfullscreen: 'allowFullScreen',
  alt: 'alt',
  as: 'as',
  async: 'async',
  autocapitalize: 'autoCapitalize',
  autocomplete: 'autoComplete',
  autocorrect: 'autoCorrect',
  autofocus: 'autoFocus',
  autoplay: 'autoPlay',
  autosave: 'autoSave',
  capture: 'capture',
  cellpadding: 'cellPadding',
  cellspacing: 'cellSpacing',
  challenge: 'challenge',
  charset: 'charSet',
  checked: 'checked',
  children: 'children',
  cite: 'cite',
  class: 'className',
  classid: 'classID',
  classname: 'className',
  cols: 'cols',
  colspan: 'colSpan',
  content: 'content',
  contenteditable: 'contentEditable',
  contextmenu: 'contextMenu',
  controls: 'controls',
  controlslist: 'controlsList',
  coords: 'coords',
  crossorigin: 'crossOrigin',
  dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
  data: 'data',
  datetime: 'dateTime',
  default: 'default',
  defaultchecked: 'defaultChecked',
  defaultvalue: 'defaultValue',
  defer: 'defer',
  dir: 'dir',
  disabled: 'disabled',
  download: 'download',
  draggable: 'draggable',
  enctype: 'encType',
  for: 'htmlFor',
  form: 'form',
  formmethod: 'formMethod',
  formaction: 'formAction',
  formenctype: 'formEncType',
  formnovalidate: 'formNoValidate',
  formtarget: 'formTarget',
  frameborder: 'frameBorder',
  headers: 'headers',
  height: 'height',
  hidden: 'hidden',
  high: 'high',
  href: 'href',
  hreflang: 'hrefLang',
  htmlfor: 'htmlFor',
  httpequiv: 'httpEquiv',
  'http-equiv': 'httpEquiv',
  icon: 'icon',
  id: 'id',
  innerhtml: 'innerHTML',
  inputmode: 'inputMode',
  integrity: 'integrity',
  is: 'is',
  itemid: 'itemID',
  itemprop: 'itemProp',
  itemref: 'itemRef',
  itemscope: 'itemScope',
  itemtype: 'itemType',
  keyparams: 'keyParams',
  keytype: 'keyType',
  kind: 'kind',
  label: 'label',
  lang: 'lang',
  list: 'list',
  loop: 'loop',
  low: 'low',
  manifest: 'manifest',
  marginwidth: 'marginWidth',
  marginheight: 'marginHeight',
  max: 'max',
  maxlength: 'maxLength',
  media: 'media',
  mediagroup: 'mediaGroup',
  method: 'method',
  min: 'min',
  minlength: 'minLength',
  multiple: 'multiple',
  muted: 'muted',
  name: 'name',
  nomodule: 'noModule',
  nonce: 'nonce',
  novalidate: 'noValidate',
  open: 'open',
  optimum: 'optimum',
  pattern: 'pattern',
  placeholder: 'placeholder',
  playsinline: 'playsInline',
  poster: 'poster',
  preload: 'preload',
  profile: 'profile',
  radiogroup: 'radioGroup',
  readonly: 'readOnly',
  referrerpolicy: 'referrerPolicy',
  rel: 'rel',
  required: 'required',
  reversed: 'reversed',
  role: 'role',
  rows: 'rows',
  rowspan: 'rowSpan',
  sandbox: 'sandbox',
  scope: 'scope',
  scoped: 'scoped',
  scrolling: 'scrolling',
  seamless: 'seamless',
  selected: 'selected',
  shape: 'shape',
  size: 'size',
  sizes: 'sizes',
  span: 'span',
  spellcheck: 'spellCheck',
  src: 'src',
  srcdoc: 'srcDoc',
  srclang: 'srcLang',
  srcset: 'srcSet',
  start: 'start',
  step: 'step',
  style: 'style',
  summary: 'summary',
  tabindex: 'tabIndex',
  target: 'target',
  title: 'title',
  type: 'type',
  usemap: 'useMap',
  value: 'value',
  width: 'width',
  wmode: 'wmode',
  wrap: 'wrap',

  // SVG
  about: 'about',
  accentheight: 'accentHeight',
  'accent-height': 'accentHeight',
  accumulate: 'accumulate',
  additive: 'additive',
  alignmentbaseline: 'alignmentBaseline',
  'alignment-baseline': 'alignmentBaseline',
  allowreorder: 'allowReorder',
  alphabetic: 'alphabetic',
  amplitude: 'amplitude',
  arabicform: 'arabicForm',
  'arabic-form': 'arabicForm',
  ascent: 'ascent',
  attributename: 'attributeName',
  attributetype: 'attributeType',
  autoreverse: 'autoReverse',
  azimuth: 'azimuth',
  basefrequency: 'baseFrequency',
  baselineshift: 'baselineShift',
  'baseline-shift': 'baselineShift',
  baseprofile: 'baseProfile',
  bbox: 'bbox',
  begin: 'begin',
  bias: 'bias',
  by: 'by',
  calcmode: 'calcMode',
  capheight: 'capHeight',
  'cap-height': 'capHeight',
  clip: 'clip',
  clippath: 'clipPath',
  'clip-path': 'clipPath',
  clippathunits: 'clipPathUnits',
  cliprule: 'clipRule',
  'clip-rule': 'clipRule',
  color: 'color',
  colorinterpolation: 'colorInterpolation',
  'color-interpolation': 'colorInterpolation',
  colorinterpolationfilters: 'colorInterpolationFilters',
  'color-interpolation-filters': 'colorInterpolationFilters',
  colorprofile: 'colorProfile',
  'color-profile': 'colorProfile',
  colorrendering: 'colorRendering',
  'color-rendering': 'colorRendering',
  contentscripttype: 'contentScriptType',
  contentstyletype: 'contentStyleType',
  cursor: 'cursor',
  cx: 'cx',
  cy: 'cy',
  d: 'd',
  datatype: 'datatype',
  decelerate: 'decelerate',
  descent: 'descent',
  diffuseconstant: 'diffuseConstant',
  direction: 'direction',
  display: 'display',
  divisor: 'divisor',
  dominantbaseline: 'dominantBaseline',
  'dominant-baseline': 'dominantBaseline',
  dur: 'dur',
  dx: 'dx',
  dy: 'dy',
  edgemode: 'edgeMode',
  elevation: 'elevation',
  enablebackground: 'enableBackground',
  'enable-background': 'enableBackground',
  end: 'end',
  exponent: 'exponent',
  externalresourcesrequired: 'externalResourcesRequired',
  fill: 'fill',
  fillopacity: 'fillOpacity',
  'fill-opacity': 'fillOpacity',
  fillrule: 'fillRule',
  'fill-rule': 'fillRule',
  filter: 'filter',
  filterres: 'filterRes',
  filterunits: 'filterUnits',
  floodopacity: 'floodOpacity',
  'flood-opacity': 'floodOpacity',
  floodcolor: 'floodColor',
  'flood-color': 'floodColor',
  focusable: 'focusable',
  fontfamily: 'fontFamily',
  'font-family': 'fontFamily',
  fontsize: 'fontSize',
  'font-size': 'fontSize',
  fontsizeadjust: 'fontSizeAdjust',
  'font-size-adjust': 'fontSizeAdjust',
  fontstretch: 'fontStretch',
  'font-stretch': 'fontStretch',
  fontstyle: 'fontStyle',
  'font-style': 'fontStyle',
  fontvariant: 'fontVariant',
  'font-variant': 'fontVariant',
  fontweight: 'fontWeight',
  'font-weight': 'fontWeight',
  format: 'format',
  from: 'from',
  fx: 'fx',
  fy: 'fy',
  g1: 'g1',
  g2: 'g2',
  glyphname: 'glyphName',
  'glyph-name': 'glyphName',
  glyphorientationhorizontal: 'glyphOrientationHorizontal',
  'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
  glyphorientationvertical: 'glyphOrientationVertical',
  'glyph-orientation-vertical': 'glyphOrientationVertical',
  glyphref: 'glyphRef',
  gradienttransform: 'gradientTransform',
  gradientunits: 'gradientUnits',
  hanging: 'hanging',
  horizadvx: 'horizAdvX',
  'horiz-adv-x': 'horizAdvX',
  horizoriginx: 'horizOriginX',
  'horiz-origin-x': 'horizOriginX',
  ideographic: 'ideographic',
  imagerendering: 'imageRendering',
  'image-rendering': 'imageRendering',
  in2: 'in2',
  in: 'in',
  inlist: 'inlist',
  intercept: 'intercept',
  k1: 'k1',
  k2: 'k2',
  k3: 'k3',
  k4: 'k4',
  k: 'k',
  kernelmatrix: 'kernelMatrix',
  kernelunitlength: 'kernelUnitLength',
  kerning: 'kerning',
  keypoints: 'keyPoints',
  keysplines: 'keySplines',
  keytimes: 'keyTimes',
  lengthadjust: 'lengthAdjust',
  letterspacing: 'letterSpacing',
  'letter-spacing': 'letterSpacing',
  lightingcolor: 'lightingColor',
  'lighting-color': 'lightingColor',
  limitingconeangle: 'limitingConeAngle',
  local: 'local',
  markerend: 'markerEnd',
  'marker-end': 'markerEnd',
  markerheight: 'markerHeight',
  markermid: 'markerMid',
  'marker-mid': 'markerMid',
  markerstart: 'markerStart',
  'marker-start': 'markerStart',
  markerunits: 'markerUnits',
  markerwidth: 'markerWidth',
  mask: 'mask',
  maskcontentunits: 'maskContentUnits',
  maskunits: 'maskUnits',
  mathematical: 'mathematical',
  mode: 'mode',
  numoctaves: 'numOctaves',
  offset: 'offset',
  opacity: 'opacity',
  operator: 'operator',
  order: 'order',
  orient: 'orient',
  orientation: 'orientation',
  origin: 'origin',
  overflow: 'overflow',
  overlineposition: 'overlinePosition',
  'overline-position': 'overlinePosition',
  overlinethickness: 'overlineThickness',
  'overline-thickness': 'overlineThickness',
  paintorder: 'paintOrder',
  'paint-order': 'paintOrder',
  panose1: 'panose1',
  'panose-1': 'panose1',
  pathlength: 'pathLength',
  patterncontentunits: 'patternContentUnits',
  patterntransform: 'patternTransform',
  patternunits: 'patternUnits',
  pointerevents: 'pointerEvents',
  'pointer-events': 'pointerEvents',
  points: 'points',
  pointsatx: 'pointsAtX',
  pointsaty: 'pointsAtY',
  pointsatz: 'pointsAtZ',
  prefix: 'prefix',
  preservealpha: 'preserveAlpha',
  preserveaspectratio: 'preserveAspectRatio',
  primitiveunits: 'primitiveUnits',
  property: 'property',
  r: 'r',
  radius: 'radius',
  refx: 'refX',
  refy: 'refY',
  renderingintent: 'renderingIntent',
  'rendering-intent': 'renderingIntent',
  repeatcount: 'repeatCount',
  repeatdur: 'repeatDur',
  requiredextensions: 'requiredExtensions',
  requiredfeatures: 'requiredFeatures',
  resource: 'resource',
  restart: 'restart',
  result: 'result',
  results: 'results',
  rotate: 'rotate',
  rx: 'rx',
  ry: 'ry',
  scale: 'scale',
  security: 'security',
  seed: 'seed',
  shaperendering: 'shapeRendering',
  'shape-rendering': 'shapeRendering',
  slope: 'slope',
  spacing: 'spacing',
  specularconstant: 'specularConstant',
  specularexponent: 'specularExponent',
  speed: 'speed',
  spreadmethod: 'spreadMethod',
  startoffset: 'startOffset',
  stddeviation: 'stdDeviation',
  stemh: 'stemh',
  stemv: 'stemv',
  stitchtiles: 'stitchTiles',
  stopcolor: 'stopColor',
  'stop-color': 'stopColor',
  stopopacity: 'stopOpacity',
  'stop-opacity': 'stopOpacity',
  strikethroughposition: 'strikethroughPosition',
  'strikethrough-position': 'strikethroughPosition',
  strikethroughthickness: 'strikethroughThickness',
  'strikethrough-thickness': 'strikethroughThickness',
  string: 'string',
  stroke: 'stroke',
  strokedasharray: 'strokeDasharray',
  'stroke-dasharray': 'strokeDasharray',
  strokedashoffset: 'strokeDashoffset',
  'stroke-dashoffset': 'strokeDashoffset',
  strokelinecap: 'strokeLinecap',
  'stroke-linecap': 'strokeLinecap',
  strokelinejoin: 'strokeLinejoin',
  'stroke-linejoin': 'strokeLinejoin',
  strokemiterlimit: 'strokeMiterlimit',
  'stroke-miterlimit': 'strokeMiterlimit',
  strokewidth: 'strokeWidth',
  'stroke-width': 'strokeWidth',
  strokeopacity: 'strokeOpacity',
  'stroke-opacity': 'strokeOpacity',
  suppresscontenteditablewarning: 'suppressContentEditableWarning',
  suppresshydrationwarning: 'suppressHydrationWarning',
  surfacescale: 'surfaceScale',
  systemlanguage: 'systemLanguage',
  tablevalues: 'tableValues',
  targetx: 'targetX',
  targety: 'targetY',
  textanchor: 'textAnchor',
  'text-anchor': 'textAnchor',
  textdecoration: 'textDecoration',
  'text-decoration': 'textDecoration',
  textlength: 'textLength',
  textrendering: 'textRendering',
  'text-rendering': 'textRendering',
  to: 'to',
  transform: 'transform',
  typeof: 'typeof',
  u1: 'u1',
  u2: 'u2',
  underlineposition: 'underlinePosition',
  'underline-position': 'underlinePosition',
  underlinethickness: 'underlineThickness',
  'underline-thickness': 'underlineThickness',
  unicode: 'unicode',
  unicodebidi: 'unicodeBidi',
  'unicode-bidi': 'unicodeBidi',
  unicoderange: 'unicodeRange',
  'unicode-range': 'unicodeRange',
  unitsperem: 'unitsPerEm',
  'units-per-em': 'unitsPerEm',
  unselectable: 'unselectable',
  valphabetic: 'vAlphabetic',
  'v-alphabetic': 'vAlphabetic',
  values: 'values',
  vectoreffect: 'vectorEffect',
  'vector-effect': 'vectorEffect',
  version: 'version',
  vertadvy: 'vertAdvY',
  'vert-adv-y': 'vertAdvY',
  vertoriginx: 'vertOriginX',
  'vert-origin-x': 'vertOriginX',
  vertoriginy: 'vertOriginY',
  'vert-origin-y': 'vertOriginY',
  vhanging: 'vHanging',
  'v-hanging': 'vHanging',
  videographic: 'vIdeographic',
  'v-ideographic': 'vIdeographic',
  viewbox: 'viewBox',
  viewtarget: 'viewTarget',
  visibility: 'visibility',
  vmathematical: 'vMathematical',
  'v-mathematical': 'vMathematical',
  vocab: 'vocab',
  widths: 'widths',
  wordspacing: 'wordSpacing',
  'word-spacing': 'wordSpacing',
  writingmode: 'writingMode',
  'writing-mode': 'writingMode',
  x1: 'x1',
  x2: 'x2',
  x: 'x',
  xchannelselector: 'xChannelSelector',
  xheight: 'xHeight',
  'x-height': 'xHeight',
  xlinkactuate: 'xlinkActuate',
  'xlink:actuate': 'xlinkActuate',
  xlinkarcrole: 'xlinkArcrole',
  'xlink:arcrole': 'xlinkArcrole',
  xlinkhref: 'xlinkHref',
  'xlink:href': 'xlinkHref',
  xlinkrole: 'xlinkRole',
  'xlink:role': 'xlinkRole',
  xlinkshow: 'xlinkShow',
  'xlink:show': 'xlinkShow',
  xlinktitle: 'xlinkTitle',
  'xlink:title': 'xlinkTitle',
  xlinktype: 'xlinkType',
  'xlink:type': 'xlinkType',
  xmlbase: 'xmlBase',
  'xml:base': 'xmlBase',
  xmllang: 'xmlLang',
  'xml:lang': 'xmlLang',
  xmlns: 'xmlns',
  'xml:space': 'xmlSpace',
  xmlnsxlink: 'xmlnsXlink',
  'xmlns:xlink': 'xmlnsXlink',
  xmlspace: 'xmlSpace',
  y1: 'y1',
  y2: 'y2',
  y: 'y',
  ychannelselector: 'yChannelSelector',
  z: 'z',
  zoomandpan: 'zoomAndPan'
};

var ariaProperties = {
  'aria-current': 0, // state
  'aria-details': 0,
  'aria-disabled': 0, // state
  'aria-hidden': 0, // state
  'aria-invalid': 0, // state
  'aria-keyshortcuts': 0,
  'aria-label': 0,
  'aria-roledescription': 0,
  // Widget Attributes
  'aria-autocomplete': 0,
  'aria-checked': 0,
  'aria-expanded': 0,
  'aria-haspopup': 0,
  'aria-level': 0,
  'aria-modal': 0,
  'aria-multiline': 0,
  'aria-multiselectable': 0,
  'aria-orientation': 0,
  'aria-placeholder': 0,
  'aria-pressed': 0,
  'aria-readonly': 0,
  'aria-required': 0,
  'aria-selected': 0,
  'aria-sort': 0,
  'aria-valuemax': 0,
  'aria-valuemin': 0,
  'aria-valuenow': 0,
  'aria-valuetext': 0,
  // Live Region Attributes
  'aria-atomic': 0,
  'aria-busy': 0,
  'aria-live': 0,
  'aria-relevant': 0,
  // Drag-and-Drop Attributes
  'aria-dropeffect': 0,
  'aria-grabbed': 0,
  // Relationship Attributes
  'aria-activedescendant': 0,
  'aria-colcount': 0,
  'aria-colindex': 0,
  'aria-colspan': 0,
  'aria-controls': 0,
  'aria-describedby': 0,
  'aria-errormessage': 0,
  'aria-flowto': 0,
  'aria-labelledby': 0,
  'aria-owns': 0,
  'aria-posinset': 0,
  'aria-rowcount': 0,
  'aria-rowindex': 0,
  'aria-rowspan': 0,
  'aria-setsize': 0
};

var warnedProperties = {};
var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');

var hasOwnProperty$1 = Object.prototype.hasOwnProperty;

function getStackAddendum() {
  var stack = ReactDebugCurrentFrame.getStackAddendum();
  return stack != null ? stack : '';
}

function validateProperty(tagName, name) {
  if (hasOwnProperty$1.call(warnedProperties, name) && warnedProperties[name]) {
    return true;
  }

  if (rARIACamel.test(name)) {
    var ariaName = 'aria-' + name.slice(4).toLowerCase();
    var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null;

    // If this is an aria-* attribute, but is not listed in the known DOM
    // DOM properties, then it is an invalid aria-* attribute.
    if (correctName == null) {
      warning(false, 'Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.%s', name, getStackAddendum());
      warnedProperties[name] = true;
      return true;
    }
    // aria-* attributes should be lowercase; suggest the lowercase version.
    if (name !== correctName) {
      warning(false, 'Invalid ARIA attribute `%s`. Did you mean `%s`?%s', name, correctName, getStackAddendum());
      warnedProperties[name] = true;
      return true;
    }
  }

  if (rARIA.test(name)) {
    var lowerCasedName = name.toLowerCase();
    var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null;

    // If this is an aria-* attribute, but is not listed in the known DOM
    // DOM properties, then it is an invalid aria-* attribute.
    if (standardName == null) {
      warnedProperties[name] = true;
      return false;
    }
    // aria-* attributes should be lowercase; suggest the lowercase version.
    if (name !== standardName) {
      warning(false, 'Unknown ARIA attribute `%s`. Did you mean `%s`?%s', name, standardName, getStackAddendum());
      warnedProperties[name] = true;
      return true;
    }
  }

  return true;
}

function warnInvalidARIAProps(type, props) {
  var invalidProps = [];

  for (var key in props) {
    var isValid = validateProperty(type, key);
    if (!isValid) {
      invalidProps.push(key);
    }
  }

  var unknownPropString = invalidProps.map(function (prop) {
    return '`' + prop + '`';
  }).join(', ');

  if (invalidProps.length === 1) {
    warning(false, 'Invalid aria prop %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop%s', unknownPropString, type, getStackAddendum());
  } else if (invalidProps.length > 1) {
    warning(false, 'Invalid aria props %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop%s', unknownPropString, type, getStackAddendum());
  }
}

function validateProperties(type, props) {
  if (isCustomComponent(type, props)) {
    return;
  }
  warnInvalidARIAProps(type, props);
}

var didWarnValueNull = false;

function getStackAddendum$1() {
  var stack = ReactDebugCurrentFrame.getStackAddendum();
  return stack != null ? stack : '';
}

function validateProperties$1(type, props) {
  if (type !== 'input' && type !== 'textarea' && type !== 'select') {
    return;
  }

  if (props != null && props.value === null && !didWarnValueNull) {
    didWarnValueNull = true;
    if (type === 'select' && props.multiple) {
      warning(false, '`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.%s', type, getStackAddendum$1());
    } else {
      warning(false, '`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.%s', type, getStackAddendum$1());
    }
  }
}

function getStackAddendum$2() {
  var stack = ReactDebugCurrentFrame.getStackAddendum();
  return stack != null ? stack : '';
}

var validateProperty$1 = function () {};

{
  var warnedProperties$1 = {};
  var _hasOwnProperty = Object.prototype.hasOwnProperty;
  var EVENT_NAME_REGEX = /^on./;
  var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
  var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
  var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');

  validateProperty$1 = function (tagName, name, value, canUseEventSystem) {
    if (_hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
      return true;
    }

    var lowerCasedName = name.toLowerCase();
    if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
      warning(false, 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.');
      warnedProperties$1[name] = true;
      return true;
    }

    // We can't rely on the event system being injected on the server.
    if (canUseEventSystem) {
      if (registrationNameModules.hasOwnProperty(name)) {
        return true;
      }
      var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;
      if (registrationName != null) {
        warning(false, 'Invalid event handler property `%s`. Did you mean `%s`?%s', name, registrationName, getStackAddendum$2());
        warnedProperties$1[name] = true;
        return true;
      }
      if (EVENT_NAME_REGEX.test(name)) {
        warning(false, 'Unknown event handler property `%s`. It will be ignored.%s', name, getStackAddendum$2());
        warnedProperties$1[name] = true;
        return true;
      }
    } else if (EVENT_NAME_REGEX.test(name)) {
      // If no event plugins have been injected, we are in a server environment.
      // So we can't tell if the event name is correct for sure, but we can filter
      // out known bad ones like `onclick`. We can't suggest a specific replacement though.
      if (INVALID_EVENT_NAME_REGEX.test(name)) {
        warning(false, 'Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.%s', name, getStackAddendum$2());
      }
      warnedProperties$1[name] = true;
      return true;
    }

    // Let the ARIA attribute hook validate ARIA attributes
    if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
      return true;
    }

    if (lowerCasedName === 'innerhtml') {
      warning(false, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');
      warnedProperties$1[name] = true;
      return true;
    }

    if (lowerCasedName === 'aria') {
      warning(false, 'The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');
      warnedProperties$1[name] = true;
      return true;
    }

    if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
      warning(false, 'Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.%s', typeof value, getStackAddendum$2());
      warnedProperties$1[name] = true;
      return true;
    }

    if (typeof value === 'number' && isNaN(value)) {
      warning(false, 'Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.%s', name, getStackAddendum$2());
      warnedProperties$1[name] = true;
      return true;
    }

    var propertyInfo = getPropertyInfo(name);
    var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED;

    // Known attributes should match the casing specified in the property config.
    if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
      var standardName = possibleStandardNames[lowerCasedName];
      if (standardName !== name) {
        warning(false, 'Invalid DOM property `%s`. Did you mean `%s`?%s', name, standardName, getStackAddendum$2());
        warnedProperties$1[name] = true;
        return true;
      }
    } else if (!isReserved && name !== lowerCasedName) {
      // Unknown attributes should have lowercase casing since that's how they
      // will be cased anyway with server rendering.
      warning(false, 'React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.%s', name, lowerCasedName, getStackAddendum$2());
      warnedProperties$1[name] = true;
      return true;
    }

    if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
      if (value) {
        warning(false, 'Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.%s', value, name, name, value, name, getStackAddendum$2());
      } else {
        warning(false, 'Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.%s', value, name, name, value, name, name, name, getStackAddendum$2());
      }
      warnedProperties$1[name] = true;
      return true;
    }

    // Now that we've validated casing, do not validate
    // data types for reserved props
    if (isReserved) {
      return true;
    }

    // Warn when a known attribute is a bad type
    if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
      warnedProperties$1[name] = true;
      return false;
    }

    return true;
  };
}

var warnUnknownProperties = function (type, props, canUseEventSystem) {
  var unknownProps = [];
  for (var key in props) {
    var isValid = validateProperty$1(type, key, props[key], canUseEventSystem);
    if (!isValid) {
      unknownProps.push(key);
    }
  }

  var unknownPropString = unknownProps.map(function (prop) {
    return '`' + prop + '`';
  }).join(', ');
  if (unknownProps.length === 1) {
    warning(false, 'Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://fb.me/react-attribute-behavior%s', unknownPropString, type, getStackAddendum$2());
  } else if (unknownProps.length > 1) {
    warning(false, 'Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://fb.me/react-attribute-behavior%s', unknownPropString, type, getStackAddendum$2());
  }
};

function validateProperties$2(type, props, canUseEventSystem) {
  if (isCustomComponent(type, props)) {
    return;
  }
  warnUnknownProperties(type, props, canUseEventSystem);
}

// TODO: direct imports like some-package/src/* are bad. Fix me.
var getCurrentFiberOwnerName$2 = ReactDebugCurrentFiber.getCurrentFiberOwnerName;
var getCurrentFiberStackAddendum$2 = ReactDebugCurrentFiber.getCurrentFiberStackAddendum;

var didWarnInvalidHydration = false;
var didWarnShadyDOM = false;

var DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML';
var SUPPRESS_CONTENT_EDITABLE_WARNING = 'suppressContentEditableWarning';
var SUPPRESS_HYDRATION_WARNING$1 = 'suppressHydrationWarning';
var AUTOFOCUS = 'autoFocus';
var CHILDREN = 'children';
var STYLE = 'style';
var HTML = '__html';

var HTML_NAMESPACE = Namespaces.html;


var getStack = emptyFunction.thatReturns('');

var warnedUnknownTags = void 0;
var suppressHydrationWarning = void 0;

var validatePropertiesInDevelopment = void 0;
var warnForTextDifference = void 0;
var warnForPropDifference = void 0;
var warnForExtraAttributes = void 0;
var warnForInvalidEventListener = void 0;

var normalizeMarkupForTextOrAttribute = void 0;
var normalizeHTML = void 0;

{
  getStack = getCurrentFiberStackAddendum$2;

  warnedUnknownTags = {
    // Chrome is the only major browser not shipping <time>. But as of July
    // 2017 it intends to ship it due to widespread usage. We intentionally
    // *don't* warn for <time> even if it's unrecognized by Chrome because
    // it soon will be, and many apps have been using it anyway.
    time: true,
    // There are working polyfills for <dialog>. Let people use it.
    dialog: true
  };

  validatePropertiesInDevelopment = function (type, props) {
    validateProperties(type, props);
    validateProperties$1(type, props);
    validateProperties$2(type, props, /* canUseEventSystem */true);
  };

  // HTML parsing normalizes CR and CRLF to LF.
  // It also can turn \u0000 into \uFFFD inside attributes.
  // https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream
  // If we have a mismatch, it might be caused by that.
  // We will still patch up in this case but not fire the warning.
  var NORMALIZE_NEWLINES_REGEX = /\r\n?/g;
  var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;

  normalizeMarkupForTextOrAttribute = function (markup) {
    var markupString = typeof markup === 'string' ? markup : '' + markup;
    return markupString.replace(NORMALIZE_NEWLINES_REGEX, '\n').replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, '');
  };

  warnForTextDifference = function (serverText, clientText) {
    if (didWarnInvalidHydration) {
      return;
    }
    var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText);
    var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText);
    if (normalizedServerText === normalizedClientText) {
      return;
    }
    didWarnInvalidHydration = true;
    warning(false, 'Text content did not match. Server: "%s" Client: "%s"', normalizedServerText, normalizedClientText);
  };

  warnForPropDifference = function (propName, serverValue, clientValue) {
    if (didWarnInvalidHydration) {
      return;
    }
    var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue);
    var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue);
    if (normalizedServerValue === normalizedClientValue) {
      return;
    }
    didWarnInvalidHydration = true;
    warning(false, 'Prop `%s` did not match. Server: %s Client: %s', propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue));
  };

  warnForExtraAttributes = function (attributeNames) {
    if (didWarnInvalidHydration) {
      return;
    }
    didWarnInvalidHydration = true;
    var names = [];
    attributeNames.forEach(function (name) {
      names.push(name);
    });
    warning(false, 'Extra attributes from the server: %s', names);
  };

  warnForInvalidEventListener = function (registrationName, listener) {
    if (listener === false) {
      warning(false, 'Expected `%s` listener to be a function, instead got `false`.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.%s', registrationName, registrationName, registrationName, getCurrentFiberStackAddendum$2());
    } else {
      warning(false, 'Expected `%s` listener to be a function, instead got a value of `%s` type.%s', registrationName, typeof listener, getCurrentFiberStackAddendum$2());
    }
  };

  // Parse the HTML and read it back to normalize the HTML string so that it
  // can be used for comparison.
  normalizeHTML = function (parent, html) {
    // We could have created a separate document here to avoid
    // re-initializing custom elements if they exist. But this breaks
    // how <noscript> is being handled. So we use the same document.
    // See the discussion in https://github.com/facebook/react/pull/11157.
    var testElement = parent.namespaceURI === HTML_NAMESPACE ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName);
    testElement.innerHTML = html;
    return testElement.innerHTML;
  };
}

function ensureListeningTo(rootContainerElement, registrationName) {
  var isDocumentOrFragment = rootContainerElement.nodeType === DOCUMENT_NODE || rootContainerElement.nodeType === DOCUMENT_FRAGMENT_NODE;
  var doc = isDocumentOrFragment ? rootContainerElement : rootContainerElement.ownerDocument;
  listenTo(registrationName, doc);
}

function getOwnerDocumentFromRootContainer(rootContainerElement) {
  return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;
}

function trapClickOnNonInteractiveElement(node) {
  // Mobile Safari does not fire properly bubble click events on
  // non-interactive elements, which means delegated click listeners do not
  // fire. The workaround for this bug involves attaching an empty click
  // listener on the target node.
  // http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
  // Just set it using the onclick property so that we don't have to manage any
  // bookkeeping for it. Not sure if we need to clear it when the listener is
  // removed.
  // TODO: Only do this for the relevant Safaris maybe?
  node.onclick = emptyFunction;
}

function setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) {
  for (var propKey in nextProps) {
    if (!nextProps.hasOwnProperty(propKey)) {
      continue;
    }
    var nextProp = nextProps[propKey];
    if (propKey === STYLE) {
      {
        if (nextProp) {
          // Freeze the next style object so that we can assume it won't be
          // mutated. We have already warned for this in the past.
          Object.freeze(nextProp);
        }
      }
      // Relies on `updateStylesByID` not mutating `styleUpdates`.
      setValueForStyles(domElement, nextProp, getStack);
    } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
      var nextHtml = nextProp ? nextProp[HTML] : undefined;
      if (nextHtml != null) {
        setInnerHTML(domElement, nextHtml);
      }
    } else if (propKey === CHILDREN) {
      if (typeof nextProp === 'string') {
        // Avoid setting initial textContent when the text is empty. In IE11 setting
        // textContent on a <textarea> will cause the placeholder to not
        // show within the <textarea> until it has been focused and blurred again.
        // https://github.com/facebook/react/issues/6731#issuecomment-254874553
        var canSetTextContent = tag !== 'textarea' || nextProp !== '';
        if (canSetTextContent) {
          setTextContent(domElement, nextProp);
        }
      } else if (typeof nextProp === 'number') {
        setTextContent(domElement, '' + nextProp);
      }
    } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {
      // Noop
    } else if (propKey === AUTOFOCUS) {
      // We polyfill it separately on the client during commit.
      // We blacklist it here rather than in the property list because we emit it in SSR.
    } else if (registrationNameModules.hasOwnProperty(propKey)) {
      if (nextProp != null) {
        if (true && typeof nextProp !== 'function') {
          warnForInvalidEventListener(propKey, nextProp);
        }
        ensureListeningTo(rootContainerElement, propKey);
      }
    } else if (nextProp != null) {
      setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag);
    }
  }
}

function updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) {
  // TODO: Handle wasCustomComponentTag
  for (var i = 0; i < updatePayload.length; i += 2) {
    var propKey = updatePayload[i];
    var propValue = updatePayload[i + 1];
    if (propKey === STYLE) {
      setValueForStyles(domElement, propValue, getStack);
    } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
      setInnerHTML(domElement, propValue);
    } else if (propKey === CHILDREN) {
      setTextContent(domElement, propValue);
    } else {
      setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);
    }
  }
}

function createElement$1(type, props, rootContainerElement, parentNamespace) {
  var isCustomComponentTag = void 0;

  // We create tags in the namespace of their parent container, except HTML
  // tags get no namespace.
  var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement);
  var domElement = void 0;
  var namespaceURI = parentNamespace;
  if (namespaceURI === HTML_NAMESPACE) {
    namespaceURI = getIntrinsicNamespace(type);
  }
  if (namespaceURI === HTML_NAMESPACE) {
    {
      isCustomComponentTag = isCustomComponent(type, props);
      // Should this check be gated by parent namespace? Not sure we want to
      // allow <SVG> or <mATH>.
      !(isCustomComponentTag || type === type.toLowerCase()) ? warning(false, '<%s /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', type) : void 0;
    }

    if (type === 'script') {
      // Create the script via .innerHTML so its "parser-inserted" flag is
      // set to true and it does not execute
      var div = ownerDocument.createElement('div');
      div.innerHTML = '<script><' + '/script>'; // eslint-disable-line
      // This is guaranteed to yield a script element.
      var firstChild = div.firstChild;
      domElement = div.removeChild(firstChild);
    } else if (typeof props.is === 'string') {
      // $FlowIssue `createElement` should be updated for Web Components
      domElement = ownerDocument.createElement(type, { is: props.is });
    } else {
      // Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.
      // See discussion in https://github.com/facebook/react/pull/6896
      // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
      domElement = ownerDocument.createElement(type);
    }
  } else {
    domElement = ownerDocument.createElementNS(namespaceURI, type);
  }

  {
    if (namespaceURI === HTML_NAMESPACE) {
      if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === '[object HTMLUnknownElement]' && !Object.prototype.hasOwnProperty.call(warnedUnknownTags, type)) {
        warnedUnknownTags[type] = true;
        warning(false, 'The tag <%s> is unrecognized in this browser. ' + 'If you meant to render a React component, start its name with ' + 'an uppercase letter.', type);
      }
    }
  }

  return domElement;
}

function createTextNode$1(text, rootContainerElement) {
  return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text);
}

function setInitialProperties$1(domElement, tag, rawProps, rootContainerElement) {
  var isCustomComponentTag = isCustomComponent(tag, rawProps);
  {
    validatePropertiesInDevelopment(tag, rawProps);
    if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
      warning(false, '%s is using shady DOM. Using shady DOM with React can ' + 'cause things to break subtly.', getCurrentFiberOwnerName$2() || 'A component');
      didWarnShadyDOM = true;
    }
  }

  // TODO: Make sure that we check isMounted before firing any of these events.
  var props = void 0;
  switch (tag) {
    case 'iframe':
    case 'object':
      trapBubbledEvent(TOP_LOAD, domElement);
      props = rawProps;
      break;
    case 'video':
    case 'audio':
      // Create listener for each media event
      for (var i = 0; i < mediaEventTypes.length; i++) {
        trapBubbledEvent(mediaEventTypes[i], domElement);
      }
      props = rawProps;
      break;
    case 'source':
      trapBubbledEvent(TOP_ERROR, domElement);
      props = rawProps;
      break;
    case 'img':
    case 'image':
    case 'link':
      trapBubbledEvent(TOP_ERROR, domElement);
      trapBubbledEvent(TOP_LOAD, domElement);
      props = rawProps;
      break;
    case 'form':
      trapBubbledEvent(TOP_RESET, domElement);
      trapBubbledEvent(TOP_SUBMIT, domElement);
      props = rawProps;
      break;
    case 'details':
      trapBubbledEvent(TOP_TOGGLE, domElement);
      props = rawProps;
      break;
    case 'input':
      initWrapperState(domElement, rawProps);
      props = getHostProps(domElement, rawProps);
      trapBubbledEvent(TOP_INVALID, domElement);
      // For controlled components we always need to ensure we're listening
      // to onChange. Even if there is no listener.
      ensureListeningTo(rootContainerElement, 'onChange');
      break;
    case 'option':
      validateProps(domElement, rawProps);
      props = getHostProps$1(domElement, rawProps);
      break;
    case 'select':
      initWrapperState$1(domElement, rawProps);
      props = getHostProps$2(domElement, rawProps);
      trapBubbledEvent(TOP_INVALID, domElement);
      // For controlled components we always need to ensure we're listening
      // to onChange. Even if there is no listener.
      ensureListeningTo(rootContainerElement, 'onChange');
      break;
    case 'textarea':
      initWrapperState$2(domElement, rawProps);
      props = getHostProps$3(domElement, rawProps);
      trapBubbledEvent(TOP_INVALID, domElement);
      // For controlled components we always need to ensure we're listening
      // to onChange. Even if there is no listener.
      ensureListeningTo(rootContainerElement, 'onChange');
      break;
    default:
      props = rawProps;
  }

  assertValidProps(tag, props, getStack);

  setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag);

  switch (tag) {
    case 'input':
      // TODO: Make sure we check if this is still unmounted or do any clean
      // up necessary since we never stop tracking anymore.
      track(domElement);
      postMountWrapper(domElement, rawProps, false);
      break;
    case 'textarea':
      // TODO: Make sure we check if this is still unmounted or do any clean
      // up necessary since we never stop tracking anymore.
      track(domElement);
      postMountWrapper$3(domElement, rawProps);
      break;
    case 'option':
      postMountWrapper$1(domElement, rawProps);
      break;
    case 'select':
      postMountWrapper$2(domElement, rawProps);
      break;
    default:
      if (typeof props.onClick === 'function') {
        // TODO: This cast may not be sound for SVG, MathML or custom elements.
        trapClickOnNonInteractiveElement(domElement);
      }
      break;
  }
}

// Calculate the diff between the two objects.
function diffProperties$1(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) {
  {
    validatePropertiesInDevelopment(tag, nextRawProps);
  }

  var updatePayload = null;

  var lastProps = void 0;
  var nextProps = void 0;
  switch (tag) {
    case 'input':
      lastProps = getHostProps(domElement, lastRawProps);
      nextProps = getHostProps(domElement, nextRawProps);
      updatePayload = [];
      break;
    case 'option':
      lastProps = getHostProps$1(domElement, lastRawProps);
      nextProps = getHostProps$1(domElement, nextRawProps);
      updatePayload = [];
      break;
    case 'select':
      lastProps = getHostProps$2(domElement, lastRawProps);
      nextProps = getHostProps$2(domElement, nextRawProps);
      updatePayload = [];
      break;
    case 'textarea':
      lastProps = getHostProps$3(domElement, lastRawProps);
      nextProps = getHostProps$3(domElement, nextRawProps);
      updatePayload = [];
      break;
    default:
      lastProps = lastRawProps;
      nextProps = nextRawProps;
      if (typeof lastProps.onClick !== 'function' && typeof nextProps.onClick === 'function') {
        // TODO: This cast may not be sound for SVG, MathML or custom elements.
        trapClickOnNonInteractiveElement(domElement);
      }
      break;
  }

  assertValidProps(tag, nextProps, getStack);

  var propKey = void 0;
  var styleName = void 0;
  var styleUpdates = null;
  for (propKey in lastProps) {
    if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {
      continue;
    }
    if (propKey === STYLE) {
      var lastStyle = lastProps[propKey];
      for (styleName in lastStyle) {
        if (lastStyle.hasOwnProperty(styleName)) {
          if (!styleUpdates) {
            styleUpdates = {};
          }
          styleUpdates[styleName] = '';
        }
      }
    } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) {
      // Noop. This is handled by the clear text mechanism.
    } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {
      // Noop
    } else if (propKey === AUTOFOCUS) {
      // Noop. It doesn't work on updates anyway.
    } else if (registrationNameModules.hasOwnProperty(propKey)) {
      // This is a special case. If any listener updates we need to ensure
      // that the "current" fiber pointer gets updated so we need a commit
      // to update this element.
      if (!updatePayload) {
        updatePayload = [];
      }
    } else {
      // For all other deleted properties we add it to the queue. We use
      // the whitelist in the commit phase instead.
      (updatePayload = updatePayload || []).push(propKey, null);
    }
  }
  for (propKey in nextProps) {
    var nextProp = nextProps[propKey];
    var lastProp = lastProps != null ? lastProps[propKey] : undefined;
    if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {
      continue;
    }
    if (propKey === STYLE) {
      {
        if (nextProp) {
          // Freeze the next style object so that we can assume it won't be
          // mutated. We have already warned for this in the past.
          Object.freeze(nextProp);
        }
      }
      if (lastProp) {
        // Unset styles on `lastProp` but not on `nextProp`.
        for (styleName in lastProp) {
          if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
            if (!styleUpdates) {
              styleUpdates = {};
            }
            styleUpdates[styleName] = '';
          }
        }
        // Update styles that changed since `lastProp`.
        for (styleName in nextProp) {
          if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
            if (!styleUpdates) {
              styleUpdates = {};
            }
            styleUpdates[styleName] = nextProp[styleName];
          }
        }
      } else {
        // Relies on `updateStylesByID` not mutating `styleUpdates`.
        if (!styleUpdates) {
          if (!updatePayload) {
            updatePayload = [];
          }
          updatePayload.push(propKey, styleUpdates);
        }
        styleUpdates = nextProp;
      }
    } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
      var nextHtml = nextProp ? nextProp[HTML] : undefined;
      var lastHtml = lastProp ? lastProp[HTML] : undefined;
      if (nextHtml != null) {
        if (lastHtml !== nextHtml) {
          (updatePayload = updatePayload || []).push(propKey, '' + nextHtml);
        }
      } else {
        // TODO: It might be too late to clear this if we have children
        // inserted already.
      }
    } else if (propKey === CHILDREN) {
      if (lastProp !== nextProp && (typeof nextProp === 'string' || typeof nextProp === 'number')) {
        (updatePayload = updatePayload || []).push(propKey, '' + nextProp);
      }
    } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {
      // Noop
    } else if (registrationNameModules.hasOwnProperty(propKey)) {
      if (nextProp != null) {
        // We eagerly listen to this even though we haven't committed yet.
        if (true && typeof nextProp !== 'function') {
          warnForInvalidEventListener(propKey, nextProp);
        }
        ensureListeningTo(rootContainerElement, propKey);
      }
      if (!updatePayload && lastProp !== nextProp) {
        // This is a special case. If any listener updates we need to ensure
        // that the "current" props pointer gets updated so we need a commit
        // to update this element.
        updatePayload = [];
      }
    } else {
      // For any other property we always add it to the queue and then we
      // filter it out using the whitelist during the commit.
      (updatePayload = updatePayload || []).push(propKey, nextProp);
    }
  }
  if (styleUpdates) {
    (updatePayload = updatePayload || []).push(STYLE, styleUpdates);
  }
  return updatePayload;
}

// Apply the diff.
function updateProperties$1(domElement, updatePayload, tag, lastRawProps, nextRawProps) {
  // Update checked *before* name.
  // In the middle of an update, it is possible to have multiple checked.
  // When a checked radio tries to change name, browser makes another radio's checked false.
  if (tag === 'input' && nextRawProps.type === 'radio' && nextRawProps.name != null) {
    updateChecked(domElement, nextRawProps);
  }

  var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
  var isCustomComponentTag = isCustomComponent(tag, nextRawProps);
  // Apply the diff.
  updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag);

  // TODO: Ensure that an update gets scheduled if any of the special props
  // changed.
  switch (tag) {
    case 'input':
      // Update the wrapper around inputs *after* updating props. This has to
      // happen after `updateDOMProperties`. Otherwise HTML5 input validations
      // raise warnings and prevent the new value from being assigned.
      updateWrapper(domElement, nextRawProps);
      break;
    case 'textarea':
      updateWrapper$1(domElement, nextRawProps);
      break;
    case 'select':
      // <select> value update needs to occur after <option> children
      // reconciliation
      postUpdateWrapper(domElement, nextRawProps);
      break;
  }
}

function getPossibleStandardName(propName) {
  {
    var lowerCasedName = propName.toLowerCase();
    if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) {
      return null;
    }
    return possibleStandardNames[lowerCasedName] || null;
  }
  return null;
}

function diffHydratedProperties$1(domElement, tag, rawProps, parentNamespace, rootContainerElement) {
  var isCustomComponentTag = void 0;
  var extraAttributeNames = void 0;

  {
    suppressHydrationWarning = rawProps[SUPPRESS_HYDRATION_WARNING$1] === true;
    isCustomComponentTag = isCustomComponent(tag, rawProps);
    validatePropertiesInDevelopment(tag, rawProps);
    if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
      warning(false, '%s is using shady DOM. Using shady DOM with React can ' + 'cause things to break subtly.', getCurrentFiberOwnerName$2() || 'A component');
      didWarnShadyDOM = true;
    }
  }

  // TODO: Make sure that we check isMounted before firing any of these events.
  switch (tag) {
    case 'iframe':
    case 'object':
      trapBubbledEvent(TOP_LOAD, domElement);
      break;
    case 'video':
    case 'audio':
      // Create listener for each media event
      for (var i = 0; i < mediaEventTypes.length; i++) {
        trapBubbledEvent(mediaEventTypes[i], domElement);
      }
      break;
    case 'source':
      trapBubbledEvent(TOP_ERROR, domElement);
      break;
    case 'img':
    case 'image':
    case 'link':
      trapBubbledEvent(TOP_ERROR, domElement);
      trapBubbledEvent(TOP_LOAD, domElement);
      break;
    case 'form':
      trapBubbledEvent(TOP_RESET, domElement);
      trapBubbledEvent(TOP_SUBMIT, domElement);
      break;
    case 'details':
      trapBubbledEvent(TOP_TOGGLE, domElement);
      break;
    case 'input':
      initWrapperState(domElement, rawProps);
      trapBubbledEvent(TOP_INVALID, domElement);
      // For controlled components we always need to ensure we're listening
      // to onChange. Even if there is no listener.
      ensureListeningTo(rootContainerElement, 'onChange');
      break;
    case 'option':
      validateProps(domElement, rawProps);
      break;
    case 'select':
      initWrapperState$1(domElement, rawProps);
      trapBubbledEvent(TOP_INVALID, domElement);
      // For controlled components we always need to ensure we're listening
      // to onChange. Even if there is no listener.
      ensureListeningTo(rootContainerElement, 'onChange');
      break;
    case 'textarea':
      initWrapperState$2(domElement, rawProps);
      trapBubbledEvent(TOP_INVALID, domElement);
      // For controlled components we always need to ensure we're listening
      // to onChange. Even if there is no listener.
      ensureListeningTo(rootContainerElement, 'onChange');
      break;
  }

  assertValidProps(tag, rawProps, getStack);

  {
    extraAttributeNames = new Set();
    var attributes = domElement.attributes;
    for (var _i = 0; _i < attributes.length; _i++) {
      var name = attributes[_i].name.toLowerCase();
      switch (name) {
        // Built-in SSR attribute is whitelisted
        case 'data-reactroot':
          break;
        // Controlled attributes are not validated
        // TODO: Only ignore them on controlled tags.
        case 'value':
          break;
        case 'checked':
          break;
        case 'selected':
          break;
        default:
          // Intentionally use the original name.
          // See discussion in https://github.com/facebook/react/pull/10676.
          extraAttributeNames.add(attributes[_i].name);
      }
    }
  }

  var updatePayload = null;
  for (var propKey in rawProps) {
    if (!rawProps.hasOwnProperty(propKey)) {
      continue;
    }
    var nextProp = rawProps[propKey];
    if (propKey === CHILDREN) {
      // For text content children we compare against textContent. This
      // might match additional HTML that is hidden when we read it using
      // textContent. E.g. "foo" will match "f<span>oo</span>" but that still
      // satisfies our requirement. Our requirement is not to produce perfect
      // HTML and attributes. Ideally we should preserve structure but it's
      // ok not to if the visible content is still enough to indicate what
      // even listeners these nodes might be wired up to.
      // TODO: Warn if there is more than a single textNode as a child.
      // TODO: Should we use domElement.firstChild.nodeValue to compare?
      if (typeof nextProp === 'string') {
        if (domElement.textContent !== nextProp) {
          if (true && !suppressHydrationWarning) {
            warnForTextDifference(domElement.textContent, nextProp);
          }
          updatePayload = [CHILDREN, nextProp];
        }
      } else if (typeof nextProp === 'number') {
        if (domElement.textContent !== '' + nextProp) {
          if (true && !suppressHydrationWarning) {
            warnForTextDifference(domElement.textContent, nextProp);
          }
          updatePayload = [CHILDREN, '' + nextProp];
        }
      }
    } else if (registrationNameModules.hasOwnProperty(propKey)) {
      if (nextProp != null) {
        if (true && typeof nextProp !== 'function') {
          warnForInvalidEventListener(propKey, nextProp);
        }
        ensureListeningTo(rootContainerElement, propKey);
      }
    } else if (true &&
    // Convince Flow we've calculated it (it's DEV-only in this method.)
    typeof isCustomComponentTag === 'boolean') {
      // Validate that the properties correspond to their expected values.
      var serverValue = void 0;
      var propertyInfo = getPropertyInfo(propKey);
      if (suppressHydrationWarning) {
        // Don't bother comparing. We're ignoring all these warnings.
      } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1 ||
      // Controlled attributes are not validated
      // TODO: Only ignore them on controlled tags.
      propKey === 'value' || propKey === 'checked' || propKey === 'selected') {
        // Noop
      } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
        var rawHtml = nextProp ? nextProp[HTML] || '' : '';
        var serverHTML = domElement.innerHTML;
        var expectedHTML = normalizeHTML(domElement, rawHtml);
        if (expectedHTML !== serverHTML) {
          warnForPropDifference(propKey, serverHTML, expectedHTML);
        }
      } else if (propKey === STYLE) {
        // $FlowFixMe - Should be inferred as not undefined.
        extraAttributeNames.delete(propKey);
        var expectedStyle = createDangerousStringForStyles(nextProp);
        serverValue = domElement.getAttribute('style');
        if (expectedStyle !== serverValue) {
          warnForPropDifference(propKey, serverValue, expectedStyle);
        }
      } else if (isCustomComponentTag) {
        // $FlowFixMe - Should be inferred as not undefined.
        extraAttributeNames.delete(propKey.toLowerCase());
        serverValue = getValueForAttribute(domElement, propKey, nextProp);

        if (nextProp !== serverValue) {
          warnForPropDifference(propKey, serverValue, nextProp);
        }
      } else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) {
        var isMismatchDueToBadCasing = false;
        if (propertyInfo !== null) {
          // $FlowFixMe - Should be inferred as not undefined.
          extraAttributeNames.delete(propertyInfo.attributeName);
          serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo);
        } else {
          var ownNamespace = parentNamespace;
          if (ownNamespace === HTML_NAMESPACE) {
            ownNamespace = getIntrinsicNamespace(tag);
          }
          if (ownNamespace === HTML_NAMESPACE) {
            // $FlowFixMe - Should be inferred as not undefined.
            extraAttributeNames.delete(propKey.toLowerCase());
          } else {
            var standardName = getPossibleStandardName(propKey);
            if (standardName !== null && standardName !== propKey) {
              // If an SVG prop is supplied with bad casing, it will
              // be successfully parsed from HTML, but will produce a mismatch
              // (and would be incorrectly rendered on the client).
              // However, we already warn about bad casing elsewhere.
              // So we'll skip the misleading extra mismatch warning in this case.
              isMismatchDueToBadCasing = true;
              // $FlowFixMe - Should be inferred as not undefined.
              extraAttributeNames.delete(standardName);
            }
            // $FlowFixMe - Should be inferred as not undefined.
            extraAttributeNames.delete(propKey);
          }
          serverValue = getValueForAttribute(domElement, propKey, nextProp);
        }

        if (nextProp !== serverValue && !isMismatchDueToBadCasing) {
          warnForPropDifference(propKey, serverValue, nextProp);
        }
      }
    }
  }

  {
    // $FlowFixMe - Should be inferred as not undefined.
    if (extraAttributeNames.size > 0 && !suppressHydrationWarning) {
      // $FlowFixMe - Should be inferred as not undefined.
      warnForExtraAttributes(extraAttributeNames);
    }
  }

  switch (tag) {
    case 'input':
      // TODO: Make sure we check if this is still unmounted or do any clean
      // up necessary since we never stop tracking anymore.
      track(domElement);
      postMountWrapper(domElement, rawProps, true);
      break;
    case 'textarea':
      // TODO: Make sure we check if this is still unmounted or do any clean
      // up necessary since we never stop tracking anymore.
      track(domElement);
      postMountWrapper$3(domElement, rawProps);
      break;
    case 'select':
    case 'option':
      // For input and textarea we current always set the value property at
      // post mount to force it to diverge from attributes. However, for
      // option and select we don't quite do the same thing and select
      // is not resilient to the DOM state changing so we don't do that here.
      // TODO: Consider not doing this for input and textarea.
      break;
    default:
      if (typeof rawProps.onClick === 'function') {
        // TODO: This cast may not be sound for SVG, MathML or custom elements.
        trapClickOnNonInteractiveElement(domElement);
      }
      break;
  }

  return updatePayload;
}

function diffHydratedText$1(textNode, text) {
  var isDifferent = textNode.nodeValue !== text;
  return isDifferent;
}

function warnForUnmatchedText$1(textNode, text) {
  {
    warnForTextDifference(textNode.nodeValue, text);
  }
}

function warnForDeletedHydratableElement$1(parentNode, child) {
  {
    if (didWarnInvalidHydration) {
      return;
    }
    didWarnInvalidHydration = true;
    warning(false, 'Did not expect server HTML to contain a <%s> in <%s>.', child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase());
  }
}

function warnForDeletedHydratableText$1(parentNode, child) {
  {
    if (didWarnInvalidHydration) {
      return;
    }
    didWarnInvalidHydration = true;
    warning(false, 'Did not expect server HTML to contain the text node "%s" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase());
  }
}

function warnForInsertedHydratedElement$1(parentNode, tag, props) {
  {
    if (didWarnInvalidHydration) {
      return;
    }
    didWarnInvalidHydration = true;
    warning(false, 'Expected server HTML to contain a matching <%s> in <%s>.', tag, parentNode.nodeName.toLowerCase());
  }
}

function warnForInsertedHydratedText$1(parentNode, text) {
  {
    if (text === '') {
      // We expect to insert empty text nodes since they're not represented in
      // the HTML.
      // TODO: Remove this special case if we can just avoid inserting empty
      // text nodes.
      return;
    }
    if (didWarnInvalidHydration) {
      return;
    }
    didWarnInvalidHydration = true;
    warning(false, 'Expected server HTML to contain a matching text node for "%s" in <%s>.', text, parentNode.nodeName.toLowerCase());
  }
}

function restoreControlledState$1(domElement, tag, props) {
  switch (tag) {
    case 'input':
      restoreControlledState(domElement, props);
      return;
    case 'textarea':
      restoreControlledState$3(domElement, props);
      return;
    case 'select':
      restoreControlledState$2(domElement, props);
      return;
  }
}

var ReactDOMFiberComponent = Object.freeze({
	createElement: createElement$1,
	createTextNode: createTextNode$1,
	setInitialProperties: setInitialProperties$1,
	diffProperties: diffProperties$1,
	updateProperties: updateProperties$1,
	diffHydratedProperties: diffHydratedProperties$1,
	diffHydratedText: diffHydratedText$1,
	warnForUnmatchedText: warnForUnmatchedText$1,
	warnForDeletedHydratableElement: warnForDeletedHydratableElement$1,
	warnForDeletedHydratableText: warnForDeletedHydratableText$1,
	warnForInsertedHydratedElement: warnForInsertedHydratedElement$1,
	warnForInsertedHydratedText: warnForInsertedHydratedText$1,
	restoreControlledState: restoreControlledState$1
});

// TODO: direct imports like some-package/src/* are bad. Fix me.
var getCurrentFiberStackAddendum$5 = ReactDebugCurrentFiber.getCurrentFiberStackAddendum;

var validateDOMNesting = emptyFunction;

{
  // This validation code was written based on the HTML5 parsing spec:
  // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
  //
  // Note: this does not catch all invalid nesting, nor does it try to (as it's
  // not clear what practical benefit doing so provides); instead, we warn only
  // for cases where the parser will give a parse tree differing from what React
  // intended. For example, <b><div></div></b> is invalid but we don't warn
  // because it still parses correctly; we do warn for other cases like nested
  // <p> tags where the beginning of the second element implicitly closes the
  // first, causing a confusing mess.

  // https://html.spec.whatwg.org/multipage/syntax.html#special
  var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp'];

  // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
  var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template',

  // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
  // TODO: Distinguish by namespace here -- for <title>, including it here
  // errs on the side of fewer warnings
  'foreignObject', 'desc', 'title'];

  // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
  var buttonScopeTags = inScopeTags.concat(['button']);

  // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
  var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];

  var emptyAncestorInfo = {
    current: null,

    formTag: null,
    aTagInScope: null,
    buttonTagInScope: null,
    nobrTagInScope: null,
    pTagInButtonScope: null,

    listItemTagAutoclosing: null,
    dlItemTagAutoclosing: null
  };

  var updatedAncestorInfo$1 = function (oldInfo, tag, instance) {
    var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo);
    var info = { tag: tag, instance: instance };

    if (inScopeTags.indexOf(tag) !== -1) {
      ancestorInfo.aTagInScope = null;
      ancestorInfo.buttonTagInScope = null;
      ancestorInfo.nobrTagInScope = null;
    }
    if (buttonScopeTags.indexOf(tag) !== -1) {
      ancestorInfo.pTagInButtonScope = null;
    }

    // See rules for 'li', 'dd', 'dt' start tags in
    // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
    if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {
      ancestorInfo.listItemTagAutoclosing = null;
      ancestorInfo.dlItemTagAutoclosing = null;
    }

    ancestorInfo.current = info;

    if (tag === 'form') {
      ancestorInfo.formTag = info;
    }
    if (tag === 'a') {
      ancestorInfo.aTagInScope = info;
    }
    if (tag === 'button') {
      ancestorInfo.buttonTagInScope = info;
    }
    if (tag === 'nobr') {
      ancestorInfo.nobrTagInScope = info;
    }
    if (tag === 'p') {
      ancestorInfo.pTagInButtonScope = info;
    }
    if (tag === 'li') {
      ancestorInfo.listItemTagAutoclosing = info;
    }
    if (tag === 'dd' || tag === 'dt') {
      ancestorInfo.dlItemTagAutoclosing = info;
    }

    return ancestorInfo;
  };

  /**
   * Returns whether
   */
  var isTagValidWithParent = function (tag, parentTag) {
    // First, let's check if we're in an unusual parsing mode...
    switch (parentTag) {
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
      case 'select':
        return tag === 'option' || tag === 'optgroup' || tag === '#text';
      case 'optgroup':
        return tag === 'option' || tag === '#text';
      // Strictly speaking, seeing an <option> doesn't mean we're in a <select>
      // but
      case 'option':
        return tag === '#text';
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
      // No special behavior since these rules fall back to "in body" mode for
      // all except special table nodes which cause bad parsing behavior anyway.

      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
      case 'tr':
        return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
      case 'tbody':
      case 'thead':
      case 'tfoot':
        return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
      case 'colgroup':
        return tag === 'col' || tag === 'template';
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
      case 'table':
        return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
      case 'head':
        return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';
      // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
      case 'html':
        return tag === 'head' || tag === 'body';
      case '#document':
        return tag === 'html';
    }

    // Probably in the "in body" parsing mode, so we outlaw only tag combos
    // where the parsing rules cause implicit opens or closes to be added.
    // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
    switch (tag) {
      case 'h1':
      case 'h2':
      case 'h3':
      case 'h4':
      case 'h5':
      case 'h6':
        return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';

      case 'rp':
      case 'rt':
        return impliedEndTags.indexOf(parentTag) === -1;

      case 'body':
      case 'caption':
      case 'col':
      case 'colgroup':
      case 'frame':
      case 'head':
      case 'html':
      case 'tbody':
      case 'td':
      case 'tfoot':
      case 'th':
      case 'thead':
      case 'tr':
        // These tags are only valid with a few parents that have special child
        // parsing rules -- if we're down here, then none of those matched and
        // so we allow it only if we don't know what the parent is, as all other
        // cases are invalid.
        return parentTag == null;
    }

    return true;
  };

  /**
   * Returns whether
   */
  var findInvalidAncestorForTag = function (tag, ancestorInfo) {
    switch (tag) {
      case 'address':
      case 'article':
      case 'aside':
      case 'blockquote':
      case 'center':
      case 'details':
      case 'dialog':
      case 'dir':
      case 'div':
      case 'dl':
      case 'fieldset':
      case 'figcaption':
      case 'figure':
      case 'footer':
      case 'header':
      case 'hgroup':
      case 'main':
      case 'menu':
      case 'nav':
      case 'ol':
      case 'p':
      case 'section':
      case 'summary':
      case 'ul':
      case 'pre':
      case 'listing':
      case 'table':
      case 'hr':
      case 'xmp':
      case 'h1':
      case 'h2':
      case 'h3':
      case 'h4':
      case 'h5':
      case 'h6':
        return ancestorInfo.pTagInButtonScope;

      case 'form':
        return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;

      case 'li':
        return ancestorInfo.listItemTagAutoclosing;

      case 'dd':
      case 'dt':
        return ancestorInfo.dlItemTagAutoclosing;

      case 'button':
        return ancestorInfo.buttonTagInScope;

      case 'a':
        // Spec says something about storing a list of markers, but it sounds
        // equivalent to this check.
        return ancestorInfo.aTagInScope;

      case 'nobr':
        return ancestorInfo.nobrTagInScope;
    }

    return null;
  };

  var didWarn = {};

  validateDOMNesting = function (childTag, childText, ancestorInfo) {
    ancestorInfo = ancestorInfo || emptyAncestorInfo;
    var parentInfo = ancestorInfo.current;
    var parentTag = parentInfo && parentInfo.tag;

    if (childText != null) {
      !(childTag == null) ? warning(false, 'validateDOMNesting: when childText is passed, childTag should be null') : void 0;
      childTag = '#text';
    }

    var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
    var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
    var invalidParentOrAncestor = invalidParent || invalidAncestor;
    if (!invalidParentOrAncestor) {
      return;
    }

    var ancestorTag = invalidParentOrAncestor.tag;
    var addendum = getCurrentFiberStackAddendum$5();

    var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + addendum;
    if (didWarn[warnKey]) {
      return;
    }
    didWarn[warnKey] = true;

    var tagDisplayName = childTag;
    var whitespaceInfo = '';
    if (childTag === '#text') {
      if (/\S/.test(childText)) {
        tagDisplayName = 'Text nodes';
      } else {
        tagDisplayName = 'Whitespace text nodes';
        whitespaceInfo = " Make sure you don't have any extra whitespace between tags on " + 'each line of your source code.';
      }
    } else {
      tagDisplayName = '<' + childTag + '>';
    }

    if (invalidParent) {
      var info = '';
      if (ancestorTag === 'table' && childTag === 'tr') {
        info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.';
      }
      warning(false, 'validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s%s', tagDisplayName, ancestorTag, whitespaceInfo, info, addendum);
    } else {
      warning(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.%s', tagDisplayName, ancestorTag, addendum);
    }
  };

  // TODO: turn this into a named export
  validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo$1;
}

var validateDOMNesting$1 = validateDOMNesting;

// Renderers that don't support persistence
// can re-export everything from this module.

function shim() {
  invariant(false, 'The current renderer does not support persistence. This error is likely caused by a bug in React. Please file an issue.');
}

// Persistence (when unsupported)
var supportsPersistence = false;
var cloneInstance = shim;
var createContainerChildSet = shim;
var appendChildToContainerChildSet = shim;
var finalizeContainerChildren = shim;
var replaceContainerChildren = shim;

// Unused

var createElement = createElement$1;
var createTextNode = createTextNode$1;
var setInitialProperties = setInitialProperties$1;
var diffProperties = diffProperties$1;
var updateProperties = updateProperties$1;
var diffHydratedProperties = diffHydratedProperties$1;
var diffHydratedText = diffHydratedText$1;
var warnForUnmatchedText = warnForUnmatchedText$1;
var warnForDeletedHydratableElement = warnForDeletedHydratableElement$1;
var warnForDeletedHydratableText = warnForDeletedHydratableText$1;
var warnForInsertedHydratedElement = warnForInsertedHydratedElement$1;
var warnForInsertedHydratedText = warnForInsertedHydratedText$1;
var updatedAncestorInfo = validateDOMNesting$1.updatedAncestorInfo;
var precacheFiberNode$1 = precacheFiberNode;
var updateFiberProps$1 = updateFiberProps;


var SUPPRESS_HYDRATION_WARNING = void 0;
{
  SUPPRESS_HYDRATION_WARNING = 'suppressHydrationWarning';
}

var eventsEnabled = null;
var selectionInformation = null;

function shouldAutoFocusHostComponent(type, props) {
  switch (type) {
    case 'button':
    case 'input':
    case 'select':
    case 'textarea':
      return !!props.autoFocus;
  }
  return false;
}

function getRootHostContext(rootContainerInstance) {
  var type = void 0;
  var namespace = void 0;
  var nodeType = rootContainerInstance.nodeType;
  switch (nodeType) {
    case DOCUMENT_NODE:
    case DOCUMENT_FRAGMENT_NODE:
      {
        type = nodeType === DOCUMENT_NODE ? '#document' : '#fragment';
        var root = rootContainerInstance.documentElement;
        namespace = root ? root.namespaceURI : getChildNamespace(null, '');
        break;
      }
    default:
      {
        var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance;
        var ownNamespace = container.namespaceURI || null;
        type = container.tagName;
        namespace = getChildNamespace(ownNamespace, type);
        break;
      }
  }
  {
    var validatedTag = type.toLowerCase();
    var _ancestorInfo = updatedAncestorInfo(null, validatedTag, null);
    return { namespace: namespace, ancestorInfo: _ancestorInfo };
  }
  return namespace;
}

function getChildHostContext(parentHostContext, type, rootContainerInstance) {
  {
    var parentHostContextDev = parentHostContext;
    var _namespace = getChildNamespace(parentHostContextDev.namespace, type);
    var _ancestorInfo2 = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type, null);
    return { namespace: _namespace, ancestorInfo: _ancestorInfo2 };
  }
  var parentNamespace = parentHostContext;
  return getChildNamespace(parentNamespace, type);
}

function getPublicInstance(instance) {
  return instance;
}

function prepareForCommit(containerInfo) {
  eventsEnabled = isEnabled();
  selectionInformation = getSelectionInformation();
  setEnabled(false);
}

function resetAfterCommit(containerInfo) {
  restoreSelection(selectionInformation);
  selectionInformation = null;
  setEnabled(eventsEnabled);
  eventsEnabled = null;
}

function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
  var parentNamespace = void 0;
  {
    // TODO: take namespace into account when validating.
    var hostContextDev = hostContext;
    validateDOMNesting$1(type, null, hostContextDev.ancestorInfo);
    if (typeof props.children === 'string' || typeof props.children === 'number') {
      var string = '' + props.children;
      var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type, null);
      validateDOMNesting$1(null, string, ownAncestorInfo);
    }
    parentNamespace = hostContextDev.namespace;
  }
  var domElement = createElement(type, props, rootContainerInstance, parentNamespace);
  precacheFiberNode$1(internalInstanceHandle, domElement);
  updateFiberProps$1(domElement, props);
  return domElement;
}

function appendInitialChild(parentInstance, child) {
  parentInstance.appendChild(child);
}

function finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) {
  setInitialProperties(domElement, type, props, rootContainerInstance);
  return shouldAutoFocusHostComponent(type, props);
}

function prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) {
  {
    var hostContextDev = hostContext;
    if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === 'string' || typeof newProps.children === 'number')) {
      var string = '' + newProps.children;
      var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type, null);
      validateDOMNesting$1(null, string, ownAncestorInfo);
    }
  }
  return diffProperties(domElement, type, oldProps, newProps, rootContainerInstance);
}

function shouldSetTextContent(type, props) {
  return type === 'textarea' || typeof props.children === 'string' || typeof props.children === 'number' || typeof props.dangerouslySetInnerHTML === 'object' && props.dangerouslySetInnerHTML !== null && typeof props.dangerouslySetInnerHTML.__html === 'string';
}

function shouldDeprioritizeSubtree(type, props) {
  return !!props.hidden;
}

function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {
  {
    var hostContextDev = hostContext;
    validateDOMNesting$1(null, text, hostContextDev.ancestorInfo);
  }
  var textNode = createTextNode(text, rootContainerInstance);
  precacheFiberNode$1(internalInstanceHandle, textNode);
  return textNode;
}

var now = now$1;
var isPrimaryRenderer = true;
var scheduleDeferredCallback = scheduleWork;
var cancelDeferredCallback = cancelScheduledWork;

// -------------------
//     Mutation
// -------------------

var supportsMutation = true;

function commitMount(domElement, type, newProps, internalInstanceHandle) {
  // Despite the naming that might imply otherwise, this method only
  // fires if there is an `Update` effect scheduled during mounting.
  // This happens if `finalizeInitialChildren` returns `true` (which it
  // does to implement the `autoFocus` attribute on the client). But
  // there are also other cases when this might happen (such as patching
  // up text content during hydration mismatch). So we'll check this again.
  if (shouldAutoFocusHostComponent(type, newProps)) {
    domElement.focus();
  }
}

function commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) {
  // Update the props handle so that we know which props are the ones with
  // with current event handlers.
  updateFiberProps$1(domElement, newProps);
  // Apply the diff to the DOM node.
  updateProperties(domElement, updatePayload, type, oldProps, newProps);
}

function resetTextContent(domElement) {
  setTextContent(domElement, '');
}

function commitTextUpdate(textInstance, oldText, newText) {
  textInstance.nodeValue = newText;
}

function appendChild(parentInstance, child) {
  parentInstance.appendChild(child);
}

function appendChildToContainer(container, child) {
  if (container.nodeType === COMMENT_NODE) {
    container.parentNode.insertBefore(child, container);
  } else {
    container.appendChild(child);
  }
}

function insertBefore(parentInstance, child, beforeChild) {
  parentInstance.insertBefore(child, beforeChild);
}

function insertInContainerBefore(container, child, beforeChild) {
  if (container.nodeType === COMMENT_NODE) {
    container.parentNode.insertBefore(child, beforeChild);
  } else {
    container.insertBefore(child, beforeChild);
  }
}

function removeChild(parentInstance, child) {
  parentInstance.removeChild(child);
}

function removeChildFromContainer(container, child) {
  if (container.nodeType === COMMENT_NODE) {
    container.parentNode.removeChild(child);
  } else {
    container.removeChild(child);
  }
}

// -------------------
//     Hydration
// -------------------

var supportsHydration = true;

function canHydrateInstance(instance, type, props) {
  if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) {
    return null;
  }
  // This has now been refined to an element node.
  return instance;
}

function canHydrateTextInstance(instance, text) {
  if (text === '' || instance.nodeType !== TEXT_NODE) {
    // Empty strings are not parsed by HTML so there won't be a correct match here.
    return null;
  }
  // This has now been refined to a text node.
  return instance;
}

function getNextHydratableSibling(instance) {
  var node = instance.nextSibling;
  // Skip non-hydratable nodes.
  while (node && node.nodeType !== ELEMENT_NODE && node.nodeType !== TEXT_NODE) {
    node = node.nextSibling;
  }
  return node;
}

function getFirstHydratableChild(parentInstance) {
  var next = parentInstance.firstChild;
  // Skip non-hydratable nodes.
  while (next && next.nodeType !== ELEMENT_NODE && next.nodeType !== TEXT_NODE) {
    next = next.nextSibling;
  }
  return next;
}

function hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
  precacheFiberNode$1(internalInstanceHandle, instance);
  // TODO: Possibly defer this until the commit phase where all the events
  // get attached.
  updateFiberProps$1(instance, props);
  var parentNamespace = void 0;
  {
    var hostContextDev = hostContext;
    parentNamespace = hostContextDev.namespace;
  }
  return diffHydratedProperties(instance, type, props, parentNamespace, rootContainerInstance);
}

function hydrateTextInstance(textInstance, text, internalInstanceHandle) {
  precacheFiberNode$1(internalInstanceHandle, textInstance);
  return diffHydratedText(textInstance, text);
}

function didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text) {
  {
    warnForUnmatchedText(textInstance, text);
  }
}

function didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text) {
  if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
    warnForUnmatchedText(textInstance, text);
  }
}

function didNotHydrateContainerInstance(parentContainer, instance) {
  {
    if (instance.nodeType === 1) {
      warnForDeletedHydratableElement(parentContainer, instance);
    } else {
      warnForDeletedHydratableText(parentContainer, instance);
    }
  }
}

function didNotHydrateInstance(parentType, parentProps, parentInstance, instance) {
  if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
    if (instance.nodeType === 1) {
      warnForDeletedHydratableElement(parentInstance, instance);
    } else {
      warnForDeletedHydratableText(parentInstance, instance);
    }
  }
}

function didNotFindHydratableContainerInstance(parentContainer, type, props) {
  {
    warnForInsertedHydratedElement(parentContainer, type, props);
  }
}

function didNotFindHydratableContainerTextInstance(parentContainer, text) {
  {
    warnForInsertedHydratedText(parentContainer, text);
  }
}

function didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props) {
  if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
    warnForInsertedHydratedElement(parentInstance, type, props);
  }
}

function didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text) {
  if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
    warnForInsertedHydratedText(parentInstance, text);
  }
}

// Exports ReactDOM.createRoot
var enableUserTimingAPI = true;

// Experimental error-boundary API that can recover from errors within a single
// render phase
var enableGetDerivedStateFromCatch = false;
// Suspense
var enableSuspense = false;
// Helps identify side effects in begin-phase lifecycle hooks and setState reducers:
var debugRenderPhaseSideEffects = false;

// In some cases, StrictMode should also double-render lifecycles.
// This can be confusing for tests though,
// And it can be bad for performance in production.
// This feature flag can be used to control the behavior:
var debugRenderPhaseSideEffectsForStrictMode = true;

// To preserve the "Pause on caught exceptions" behavior of the debugger, we
// replay the begin phase of a failed component inside invokeGuardedCallback.
var replayFailedUnitOfWorkWithInvokeGuardedCallback = true;

// Warn about deprecated, async-unsafe lifecycles; relates to RFC #6:
var warnAboutDeprecatedLifecycles = false;

// Warn about legacy context API
var warnAboutLegacyContextAPI = false;

// Gather advanced timing metrics for Profiler subtrees.
var enableProfilerTimer = true;

// Only used in www builds.

// Prefix measurements so that it's possible to filter them.
// Longer prefixes are hard to read in DevTools.
var reactEmoji = '\u269B';
var warningEmoji = '\u26D4';
var supportsUserTiming = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function';

// Keep track of current fiber so that we know the path to unwind on pause.
// TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them?
var currentFiber = null;
// If we're in the middle of user code, which fiber and method is it?
// Reusing `currentFiber` would be confusing for this because user code fiber
// can change during commit phase too, but we don't need to unwind it (since
// lifecycles in the commit phase don't resemble a tree).
var currentPhase = null;
var currentPhaseFiber = null;
// Did lifecycle hook schedule an update? This is often a performance problem,
// so we will keep track of it, and include it in the report.
// Track commits caused by cascading updates.
var isCommitting = false;
var hasScheduledUpdateInCurrentCommit = false;
var hasScheduledUpdateInCurrentPhase = false;
var commitCountInCurrentWorkLoop = 0;
var effectCountInCurrentCommit = 0;
var isWaitingForCallback = false;
// During commits, we only show a measurement once per method name
// to avoid stretch the commit phase with measurement overhead.
var labelsInCurrentCommit = new Set();

var formatMarkName = function (markName) {
  return reactEmoji + ' ' + markName;
};

var formatLabel = function (label, warning$$1) {
  var prefix = warning$$1 ? warningEmoji + ' ' : reactEmoji + ' ';
  var suffix = warning$$1 ? ' Warning: ' + warning$$1 : '';
  return '' + prefix + label + suffix;
};

var beginMark = function (markName) {
  performance.mark(formatMarkName(markName));
};

var clearMark = function (markName) {
  performance.clearMarks(formatMarkName(markName));
};

var endMark = function (label, markName, warning$$1) {
  var formattedMarkName = formatMarkName(markName);
  var formattedLabel = formatLabel(label, warning$$1);
  try {
    performance.measure(formattedLabel, formattedMarkName);
  } catch (err) {}
  // If previous mark was missing for some reason, this will throw.
  // This could only happen if React crashed in an unexpected place earlier.
  // Don't pile on with more errors.

  // Clear marks immediately to avoid growing buffer.
  performance.clearMarks(formattedMarkName);
  performance.clearMeasures(formattedLabel);
};

var getFiberMarkName = function (label, debugID) {
  return label + ' (#' + debugID + ')';
};

var getFiberLabel = function (componentName, isMounted, phase) {
  if (phase === null) {
    // These are composite component total time measurements.
    return componentName + ' [' + (isMounted ? 'update' : 'mount') + ']';
  } else {
    // Composite component methods.
    return componentName + '.' + phase;
  }
};

var beginFiberMark = function (fiber, phase) {
  var componentName = getComponentName(fiber) || 'Unknown';
  var debugID = fiber._debugID;
  var isMounted = fiber.alternate !== null;
  var label = getFiberLabel(componentName, isMounted, phase);

  if (isCommitting && labelsInCurrentCommit.has(label)) {
    // During the commit phase, we don't show duplicate labels because
    // there is a fixed overhead for every measurement, and we don't
    // want to stretch the commit phase beyond necessary.
    return false;
  }
  labelsInCurrentCommit.add(label);

  var markName = getFiberMarkName(label, debugID);
  beginMark(markName);
  return true;
};

var clearFiberMark = function (fiber, phase) {
  var componentName = getComponentName(fiber) || 'Unknown';
  var debugID = fiber._debugID;
  var isMounted = fiber.alternate !== null;
  var label = getFiberLabel(componentName, isMounted, phase);
  var markName = getFiberMarkName(label, debugID);
  clearMark(markName);
};

var endFiberMark = function (fiber, phase, warning$$1) {
  var componentName = getComponentName(fiber) || 'Unknown';
  var debugID = fiber._debugID;
  var isMounted = fiber.alternate !== null;
  var label = getFiberLabel(componentName, isMounted, phase);
  var markName = getFiberMarkName(label, debugID);
  endMark(label, markName, warning$$1);
};

var shouldIgnoreFiber = function (fiber) {
  // Host components should be skipped in the timeline.
  // We could check typeof fiber.type, but does this work with RN?
  switch (fiber.tag) {
    case HostRoot:
    case HostComponent:
    case HostText:
    case HostPortal:
    case Fragment:
    case ContextProvider:
    case ContextConsumer:
    case Mode:
      return true;
    default:
      return false;
  }
};

var clearPendingPhaseMeasurement = function () {
  if (currentPhase !== null && currentPhaseFiber !== null) {
    clearFiberMark(currentPhaseFiber, currentPhase);
  }
  currentPhaseFiber = null;
  currentPhase = null;
  hasScheduledUpdateInCurrentPhase = false;
};

var pauseTimers = function () {
  // Stops all currently active measurements so that they can be resumed
  // if we continue in a later deferred loop from the same unit of work.
  var fiber = currentFiber;
  while (fiber) {
    if (fiber._debugIsCurrentlyTiming) {
      endFiberMark(fiber, null, null);
    }
    fiber = fiber.return;
  }
};

var resumeTimersRecursively = function (fiber) {
  if (fiber.return !== null) {
    resumeTimersRecursively(fiber.return);
  }
  if (fiber._debugIsCurrentlyTiming) {
    beginFiberMark(fiber, null);
  }
};

var resumeTimers = function () {
  // Resumes all measurements that were active during the last deferred loop.
  if (currentFiber !== null) {
    resumeTimersRecursively(currentFiber);
  }
};

function recordEffect() {
  if (enableUserTimingAPI) {
    effectCountInCurrentCommit++;
  }
}

function recordScheduleUpdate() {
  if (enableUserTimingAPI) {
    if (isCommitting) {
      hasScheduledUpdateInCurrentCommit = true;
    }
    if (currentPhase !== null && currentPhase !== 'componentWillMount' && currentPhase !== 'componentWillReceiveProps') {
      hasScheduledUpdateInCurrentPhase = true;
    }
  }
}

function startRequestCallbackTimer() {
  if (enableUserTimingAPI) {
    if (supportsUserTiming && !isWaitingForCallback) {
      isWaitingForCallback = true;
      beginMark('(Waiting for async callback...)');
    }
  }
}

function stopRequestCallbackTimer(didExpire, expirationTime) {
  if (enableUserTimingAPI) {
    if (supportsUserTiming) {
      isWaitingForCallback = false;
      var warning$$1 = didExpire ? 'React was blocked by main thread' : null;
      endMark('(Waiting for async callback... will force flush in ' + expirationTime + ' ms)', '(Waiting for async callback...)', warning$$1);
    }
  }
}

function startWorkTimer(fiber) {
  if (enableUserTimingAPI) {
    if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
      return;
    }
    // If we pause, this is the fiber to unwind from.
    currentFiber = fiber;
    if (!beginFiberMark(fiber, null)) {
      return;
    }
    fiber._debugIsCurrentlyTiming = true;
  }
}

function cancelWorkTimer(fiber) {
  if (enableUserTimingAPI) {
    if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
      return;
    }
    // Remember we shouldn't complete measurement for this fiber.
    // Otherwise flamechart will be deep even for small updates.
    fiber._debugIsCurrentlyTiming = false;
    clearFiberMark(fiber, null);
  }
}

function stopWorkTimer(fiber) {
  if (enableUserTimingAPI) {
    if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
      return;
    }
    // If we pause, its parent is the fiber to unwind from.
    currentFiber = fiber.return;
    if (!fiber._debugIsCurrentlyTiming) {
      return;
    }
    fiber._debugIsCurrentlyTiming = false;
    endFiberMark(fiber, null, null);
  }
}

function stopFailedWorkTimer(fiber) {
  if (enableUserTimingAPI) {
    if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
      return;
    }
    // If we pause, its parent is the fiber to unwind from.
    currentFiber = fiber.return;
    if (!fiber._debugIsCurrentlyTiming) {
      return;
    }
    fiber._debugIsCurrentlyTiming = false;
    var warning$$1 = 'An error was thrown inside this error boundary';
    endFiberMark(fiber, null, warning$$1);
  }
}

function startPhaseTimer(fiber, phase) {
  if (enableUserTimingAPI) {
    if (!supportsUserTiming) {
      return;
    }
    clearPendingPhaseMeasurement();
    if (!beginFiberMark(fiber, phase)) {
      return;
    }
    currentPhaseFiber = fiber;
    currentPhase = phase;
  }
}

function stopPhaseTimer() {
  if (enableUserTimingAPI) {
    if (!supportsUserTiming) {
      return;
    }
    if (currentPhase !== null && currentPhaseFiber !== null) {
      var warning$$1 = hasScheduledUpdateInCurrentPhase ? 'Scheduled a cascading update' : null;
      endFiberMark(currentPhaseFiber, currentPhase, warning$$1);
    }
    currentPhase = null;
    currentPhaseFiber = null;
  }
}

function startWorkLoopTimer(nextUnitOfWork) {
  if (enableUserTimingAPI) {
    currentFiber = nextUnitOfWork;
    if (!supportsUserTiming) {
      return;
    }
    commitCountInCurrentWorkLoop = 0;
    // This is top level call.
    // Any other measurements are performed within.
    beginMark('(React Tree Reconciliation)');
    // Resume any measurements that were in progress during the last loop.
    resumeTimers();
  }
}

function stopWorkLoopTimer(interruptedBy, didCompleteRoot) {
  if (enableUserTimingAPI) {
    if (!supportsUserTiming) {
      return;
    }
    var warning$$1 = null;
    if (interruptedBy !== null) {
      if (interruptedBy.tag === HostRoot) {
        warning$$1 = 'A top-level update interrupted the previous render';
      } else {
        var componentName = getComponentName(interruptedBy) || 'Unknown';
        warning$$1 = 'An update to ' + componentName + ' interrupted the previous render';
      }
    } else if (commitCountInCurrentWorkLoop > 1) {
      warning$$1 = 'There were cascading updates';
    }
    commitCountInCurrentWorkLoop = 0;
    var label = didCompleteRoot ? '(React Tree Reconciliation: Completed Root)' : '(React Tree Reconciliation: Yielded)';
    // Pause any measurements until the next loop.
    pauseTimers();
    endMark(label, '(React Tree Reconciliation)', warning$$1);
  }
}

function startCommitTimer() {
  if (enableUserTimingAPI) {
    if (!supportsUserTiming) {
      return;
    }
    isCommitting = true;
    hasScheduledUpdateInCurrentCommit = false;
    labelsInCurrentCommit.clear();
    beginMark('(Committing Changes)');
  }
}

function stopCommitTimer() {
  if (enableUserTimingAPI) {
    if (!supportsUserTiming) {
      return;
    }

    var warning$$1 = null;
    if (hasScheduledUpdateInCurrentCommit) {
      warning$$1 = 'Lifecycle hook scheduled a cascading update';
    } else if (commitCountInCurrentWorkLoop > 0) {
      warning$$1 = 'Caused by a cascading update in earlier commit';
    }
    hasScheduledUpdateInCurrentCommit = false;
    commitCountInCurrentWorkLoop++;
    isCommitting = false;
    labelsInCurrentCommit.clear();

    endMark('(Committing Changes)', '(Committing Changes)', warning$$1);
  }
}

function startCommitSnapshotEffectsTimer() {
  if (enableUserTimingAPI) {
    if (!supportsUserTiming) {
      return;
    }
    effectCountInCurrentCommit = 0;
    beginMark('(Committing Snapshot Effects)');
  }
}

function stopCommitSnapshotEffectsTimer() {
  if (enableUserTimingAPI) {
    if (!supportsUserTiming) {
      return;
    }
    var count = effectCountInCurrentCommit;
    effectCountInCurrentCommit = 0;
    endMark('(Committing Snapshot Effects: ' + count + ' Total)', '(Committing Snapshot Effects)', null);
  }
}

function startCommitHostEffectsTimer() {
  if (enableUserTimingAPI) {
    if (!supportsUserTiming) {
      return;
    }
    effectCountInCurrentCommit = 0;
    beginMark('(Committing Host Effects)');
  }
}

function stopCommitHostEffectsTimer() {
  if (enableUserTimingAPI) {
    if (!supportsUserTiming) {
      return;
    }
    var count = effectCountInCurrentCommit;
    effectCountInCurrentCommit = 0;
    endMark('(Committing Host Effects: ' + count + ' Total)', '(Committing Host Effects)', null);
  }
}

function startCommitLifeCyclesTimer() {
  if (enableUserTimingAPI) {
    if (!supportsUserTiming) {
      return;
    }
    effectCountInCurrentCommit = 0;
    beginMark('(Calling Lifecycle Methods)');
  }
}

function stopCommitLifeCyclesTimer() {
  if (enableUserTimingAPI) {
    if (!supportsUserTiming) {
      return;
    }
    var count = effectCountInCurrentCommit;
    effectCountInCurrentCommit = 0;
    endMark('(Calling Lifecycle Methods: ' + count + ' Total)', '(Calling Lifecycle Methods)', null);
  }
}

var valueStack = [];

var fiberStack = void 0;

{
  fiberStack = [];
}

var index = -1;

function createCursor(defaultValue) {
  return {
    current: defaultValue
  };
}

function pop(cursor, fiber) {
  if (index < 0) {
    {
      warning(false, 'Unexpected pop.');
    }
    return;
  }

  {
    if (fiber !== fiberStack[index]) {
      warning(false, 'Unexpected Fiber popped.');
    }
  }

  cursor.current = valueStack[index];

  valueStack[index] = null;

  {
    fiberStack[index] = null;
  }

  index--;
}

function push(cursor, value, fiber) {
  index++;

  valueStack[index] = cursor.current;

  {
    fiberStack[index] = fiber;
  }

  cursor.current = value;
}

function checkThatStackIsEmpty() {
  {
    if (index !== -1) {
      warning(false, 'Expected an empty stack. Something was not reset properly.');
    }
  }
}

function resetStackAfterFatalErrorInDev() {
  {
    index = -1;
    valueStack.length = 0;
    fiberStack.length = 0;
  }
}

var warnedAboutMissingGetChildContext = void 0;

{
  warnedAboutMissingGetChildContext = {};
}

// A cursor to the current merged context object on the stack.
var contextStackCursor = createCursor(emptyObject);
// A cursor to a boolean indicating whether the context has changed.
var didPerformWorkStackCursor = createCursor(false);
// Keep track of the previous context object that was on the stack.
// We use this to get access to the parent context after we have already
// pushed the next context provider, and now need to merge their contexts.
var previousContext = emptyObject;

function getUnmaskedContext(workInProgress) {
  var hasOwnContext = isContextProvider(workInProgress);
  if (hasOwnContext) {
    // If the fiber is a context provider itself, when we read its context
    // we have already pushed its own child context on the stack. A context
    // provider should not "see" its own child context. Therefore we read the
    // previous (parent) context instead for a context provider.
    return previousContext;
  }
  return contextStackCursor.current;
}

function cacheContext(workInProgress, unmaskedContext, maskedContext) {
  var instance = workInProgress.stateNode;
  instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
  instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
}

function getMaskedContext(workInProgress, unmaskedContext) {
  var type = workInProgress.type;
  var contextTypes = type.contextTypes;
  if (!contextTypes) {
    return emptyObject;
  }

  // Avoid recreating masked context unless unmasked context has changed.
  // Failing to do this will result in unnecessary calls to componentWillReceiveProps.
  // This may trigger infinite loops if componentWillReceiveProps calls setState.
  var instance = workInProgress.stateNode;
  if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
    return instance.__reactInternalMemoizedMaskedChildContext;
  }

  var context = {};
  for (var key in contextTypes) {
    context[key] = unmaskedContext[key];
  }

  {
    var name = getComponentName(workInProgress) || 'Unknown';
    checkPropTypes(contextTypes, context, 'context', name, ReactDebugCurrentFiber.getCurrentFiberStackAddendum);
  }

  // Cache unmasked context so we can avoid recreating masked context unless necessary.
  // Context is created before the class component is instantiated so check for instance.
  if (instance) {
    cacheContext(workInProgress, unmaskedContext, context);
  }

  return context;
}

function hasContextChanged() {
  return didPerformWorkStackCursor.current;
}

function isContextConsumer(fiber) {
  return fiber.tag === ClassComponent && fiber.type.contextTypes != null;
}

function isContextProvider(fiber) {
  return fiber.tag === ClassComponent && fiber.type.childContextTypes != null;
}

function popContextProvider(fiber) {
  if (!isContextProvider(fiber)) {
    return;
  }

  pop(didPerformWorkStackCursor, fiber);
  pop(contextStackCursor, fiber);
}

function popTopLevelContextObject(fiber) {
  pop(didPerformWorkStackCursor, fiber);
  pop(contextStackCursor, fiber);
}

function pushTopLevelContextObject(fiber, context, didChange) {
  !(contextStackCursor.current === emptyObject) ? invariant(false, 'Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue.') : void 0;

  push(contextStackCursor, context, fiber);
  push(didPerformWorkStackCursor, didChange, fiber);
}

function processChildContext(fiber, parentContext) {
  var instance = fiber.stateNode;
  var childContextTypes = fiber.type.childContextTypes;

  // TODO (bvaughn) Replace this behavior with an invariant() in the future.
  // It has only been added in Fiber to match the (unintentional) behavior in Stack.
  if (typeof instance.getChildContext !== 'function') {
    {
      var componentName = getComponentName(fiber) || 'Unknown';

      if (!warnedAboutMissingGetChildContext[componentName]) {
        warnedAboutMissingGetChildContext[componentName] = true;
        warning(false, '%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName);
      }
    }
    return parentContext;
  }

  var childContext = void 0;
  {
    ReactDebugCurrentFiber.setCurrentPhase('getChildContext');
  }
  startPhaseTimer(fiber, 'getChildContext');
  childContext = instance.getChildContext();
  stopPhaseTimer();
  {
    ReactDebugCurrentFiber.setCurrentPhase(null);
  }
  for (var contextKey in childContext) {
    !(contextKey in childContextTypes) ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', getComponentName(fiber) || 'Unknown', contextKey) : void 0;
  }
  {
    var name = getComponentName(fiber) || 'Unknown';
    checkPropTypes(childContextTypes, childContext, 'child context', name,
    // In practice, there is one case in which we won't get a stack. It's when
    // somebody calls unstable_renderSubtreeIntoContainer() and we process
    // context from the parent component instance. The stack will be missing
    // because it's outside of the reconciliation, and so the pointer has not
    // been set. This is rare and doesn't matter. We'll also remove that API.
    ReactDebugCurrentFiber.getCurrentFiberStackAddendum);
  }

  return _assign({}, parentContext, childContext);
}

function pushContextProvider(workInProgress) {
  if (!isContextProvider(workInProgress)) {
    return false;
  }

  var instance = workInProgress.stateNode;
  // We push the context as early as possible to ensure stack integrity.
  // If the instance does not exist yet, we will push null at first,
  // and replace it on the stack later when invalidating the context.
  var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyObject;

  // Remember the parent context so we can merge with it later.
  // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.
  previousContext = contextStackCursor.current;
  push(contextStackCursor, memoizedMergedChildContext, workInProgress);
  push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);

  return true;
}

function invalidateContextProvider(workInProgress, didChange) {
  var instance = workInProgress.stateNode;
  !instance ? invariant(false, 'Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue.') : void 0;

  if (didChange) {
    // Merge parent and own context.
    // Skip this if we're not updating due to sCU.
    // This avoids unnecessarily recomputing memoized values.
    var mergedContext = processChildContext(workInProgress, previousContext);
    instance.__reactInternalMemoizedMergedChildContext = mergedContext;

    // Replace the old (or empty) context with the new one.
    // It is important to unwind the context in the reverse order.
    pop(didPerformWorkStackCursor, workInProgress);
    pop(contextStackCursor, workInProgress);
    // Now push the new context and mark that it has changed.
    push(contextStackCursor, mergedContext, workInProgress);
    push(didPerformWorkStackCursor, didChange, workInProgress);
  } else {
    pop(didPerformWorkStackCursor, workInProgress);
    push(didPerformWorkStackCursor, didChange, workInProgress);
  }
}

function findCurrentUnmaskedContext(fiber) {
  // Currently this is only used with renderSubtreeIntoContainer; not sure if it
  // makes sense elsewhere
  !(isFiberMounted(fiber) && fiber.tag === ClassComponent) ? invariant(false, 'Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue.') : void 0;

  var node = fiber;
  while (node.tag !== HostRoot) {
    if (isContextProvider(node)) {
      return node.stateNode.__reactInternalMemoizedMergedChildContext;
    }
    var parent = node.return;
    !parent ? invariant(false, 'Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue.') : void 0;
    node = parent;
  }
  return node.stateNode.context;
}

// Max 31 bit integer. The max integer size in V8 for 32-bit systems.
// Math.pow(2, 30) - 1
// 0b111111111111111111111111111111
var MAX_SIGNED_31_BIT_INT = 1073741823;

// TODO: Use an opaque type once ESLint et al support the syntax


var NoWork = 0;
var Sync = 1;
var Never = MAX_SIGNED_31_BIT_INT;

var UNIT_SIZE = 10;
var MAGIC_NUMBER_OFFSET = 2;

// 1 unit of expiration time represents 10ms.
function msToExpirationTime(ms) {
  // Always add an offset so that we don't clash with the magic number for NoWork.
  return (ms / UNIT_SIZE | 0) + MAGIC_NUMBER_OFFSET;
}

function expirationTimeToMs(expirationTime) {
  return (expirationTime - MAGIC_NUMBER_OFFSET) * UNIT_SIZE;
}

function ceiling(num, precision) {
  return ((num / precision | 0) + 1) * precision;
}

function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) {
  return MAGIC_NUMBER_OFFSET + ceiling(currentTime - MAGIC_NUMBER_OFFSET + expirationInMs / UNIT_SIZE, bucketSizeMs / UNIT_SIZE);
}

var NoContext = 0;
var AsyncMode = 1;
var StrictMode = 2;
var ProfileMode = 4;

var hasBadMapPolyfill = void 0;

{
  hasBadMapPolyfill = false;
  try {
    var nonExtensibleObject = Object.preventExtensions({});
    var testMap = new Map([[nonExtensibleObject, null]]);
    var testSet = new Set([nonExtensibleObject]);
    // This is necessary for Rollup to not consider these unused.
    // https://github.com/rollup/rollup/issues/1771
    // TODO: we can remove these if Rollup fixes the bug.
    testMap.set(0, 0);
    testSet.add(0);
  } catch (e) {
    // TODO: Consider warning about bad polyfills
    hasBadMapPolyfill = true;
  }
}

// A Fiber is work on a Component that needs to be done or was done. There can
// be more than one per component.


var debugCounter = void 0;

{
  debugCounter = 1;
}

function FiberNode(tag, pendingProps, key, mode) {
  // Instance
  this.tag = tag;
  this.key = key;
  this.type = null;
  this.stateNode = null;

  // Fiber
  this.return = null;
  this.child = null;
  this.sibling = null;
  this.index = 0;

  this.ref = null;

  this.pendingProps = pendingProps;
  this.memoizedProps = null;
  this.updateQueue = null;
  this.memoizedState = null;

  this.mode = mode;

  // Effects
  this.effectTag = NoEffect;
  this.nextEffect = null;

  this.firstEffect = null;
  this.lastEffect = null;

  this.expirationTime = NoWork;

  this.alternate = null;

  if (enableProfilerTimer) {
    this.actualDuration = 0;
    this.actualStartTime = 0;
    this.selfBaseTime = 0;
    this.treeBaseTime = 0;
  }

  {
    this._debugID = debugCounter++;
    this._debugSource = null;
    this._debugOwner = null;
    this._debugIsCurrentlyTiming = false;
    if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
      Object.preventExtensions(this);
    }
  }
}

// This is a constructor function, rather than a POJO constructor, still
// please ensure we do the following:
// 1) Nobody should add any instance methods on this. Instance methods can be
//    more difficult to predict when they get optimized and they are almost
//    never inlined properly in static compilers.
// 2) Nobody should rely on `instanceof Fiber` for type testing. We should
//    always know when it is a fiber.
// 3) We might want to experiment with using numeric keys since they are easier
//    to optimize in a non-JIT environment.
// 4) We can easily go from a constructor to a createFiber object literal if that
//    is faster.
// 5) It should be easy to port this to a C struct and keep a C implementation
//    compatible.
var createFiber = function (tag, pendingProps, key, mode) {
  // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
  return new FiberNode(tag, pendingProps, key, mode);
};

function shouldConstruct(Component) {
  return !!(Component.prototype && Component.prototype.isReactComponent);
}

// This is used to create an alternate fiber to do work on.
function createWorkInProgress(current, pendingProps, expirationTime) {
  var workInProgress = current.alternate;
  if (workInProgress === null) {
    // We use a double buffering pooling technique because we know that we'll
    // only ever need at most two versions of a tree. We pool the "other" unused
    // node that we're free to reuse. This is lazily created to avoid allocating
    // extra objects for things that are never updated. It also allow us to
    // reclaim the extra memory if needed.
    workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
    workInProgress.type = current.type;
    workInProgress.stateNode = current.stateNode;

    {
      // DEV-only fields
      workInProgress._debugID = current._debugID;
      workInProgress._debugSource = current._debugSource;
      workInProgress._debugOwner = current._debugOwner;
    }

    workInProgress.alternate = current;
    current.alternate = workInProgress;
  } else {
    workInProgress.pendingProps = pendingProps;

    // We already have an alternate.
    // Reset the effect tag.
    workInProgress.effectTag = NoEffect;

    // The effect list is no longer valid.
    workInProgress.nextEffect = null;
    workInProgress.firstEffect = null;
    workInProgress.lastEffect = null;

    if (enableProfilerTimer) {
      // We intentionally reset, rather than copy, actualDuration & actualStartTime.
      // This prevents time from endlessly accumulating in new commits.
      // This has the downside of resetting values for different priority renders,
      // But works for yielding (the common case) and should support resuming.
      workInProgress.actualDuration = 0;
      workInProgress.actualStartTime = 0;
    }
  }

  workInProgress.expirationTime = expirationTime;

  workInProgress.child = current.child;
  workInProgress.memoizedProps = current.memoizedProps;
  workInProgress.memoizedState = current.memoizedState;
  workInProgress.updateQueue = current.updateQueue;

  // These will be overridden during the parent's reconciliation
  workInProgress.sibling = current.sibling;
  workInProgress.index = current.index;
  workInProgress.ref = current.ref;

  if (enableProfilerTimer) {
    workInProgress.selfBaseTime = current.selfBaseTime;
    workInProgress.treeBaseTime = current.treeBaseTime;
  }

  return workInProgress;
}

function createHostRootFiber(isAsync) {
  var mode = isAsync ? AsyncMode | StrictMode : NoContext;
  return createFiber(HostRoot, null, null, mode);
}

function createFiberFromElement(element, mode, expirationTime) {
  var owner = null;
  {
    owner = element._owner;
  }

  var fiber = void 0;
  var type = element.type;
  var key = element.key;
  var pendingProps = element.props;

  var fiberTag = void 0;
  if (typeof type === 'function') {
    fiberTag = shouldConstruct(type) ? ClassComponent : IndeterminateComponent;
  } else if (typeof type === 'string') {
    fiberTag = HostComponent;
  } else {
    switch (type) {
      case REACT_FRAGMENT_TYPE:
        return createFiberFromFragment(pendingProps.children, mode, expirationTime, key);
      case REACT_ASYNC_MODE_TYPE:
        fiberTag = Mode;
        mode |= AsyncMode | StrictMode;
        break;
      case REACT_STRICT_MODE_TYPE:
        fiberTag = Mode;
        mode |= StrictMode;
        break;
      case REACT_PROFILER_TYPE:
        return createFiberFromProfiler(pendingProps, mode, expirationTime, key);
      case REACT_TIMEOUT_TYPE:
        fiberTag = TimeoutComponent;
        // Suspense does not require async, but its children should be strict
        // mode compatible.
        mode |= StrictMode;
        break;
      default:
        fiberTag = getFiberTagFromObjectType(type, owner);
        break;
    }
  }

  fiber = createFiber(fiberTag, pendingProps, key, mode);
  fiber.type = type;
  fiber.expirationTime = expirationTime;

  {
    fiber._debugSource = element._source;
    fiber._debugOwner = element._owner;
  }

  return fiber;
}

function getFiberTagFromObjectType(type, owner) {
  var $$typeof = typeof type === 'object' && type !== null ? type.$$typeof : null;

  switch ($$typeof) {
    case REACT_PROVIDER_TYPE:
      return ContextProvider;
    case REACT_CONTEXT_TYPE:
      // This is a consumer
      return ContextConsumer;
    case REACT_FORWARD_REF_TYPE:
      return ForwardRef;
    default:
      {
        var info = '';
        {
          if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
            info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.';
          }
          var ownerName = owner ? getComponentName(owner) : null;
          if (ownerName) {
            info += '\n\nCheck the render method of `' + ownerName + '`.';
          }
        }
        invariant(false, 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s', type == null ? type : typeof type, info);
      }
  }
}

function createFiberFromFragment(elements, mode, expirationTime, key) {
  var fiber = createFiber(Fragment, elements, key, mode);
  fiber.expirationTime = expirationTime;
  return fiber;
}

function createFiberFromProfiler(pendingProps, mode, expirationTime, key) {
  {
    if (typeof pendingProps.id !== 'string' || typeof pendingProps.onRender !== 'function') {
      invariant(false, 'Profiler must specify an "id" string and "onRender" function as props');
    }
  }

  var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode);
  fiber.type = REACT_PROFILER_TYPE;
  fiber.expirationTime = expirationTime;

  return fiber;
}

function createFiberFromText(content, mode, expirationTime) {
  var fiber = createFiber(HostText, content, null, mode);
  fiber.expirationTime = expirationTime;
  return fiber;
}

function createFiberFromHostInstanceForDeletion() {
  var fiber = createFiber(HostComponent, null, null, NoContext);
  fiber.type = 'DELETED';
  return fiber;
}

function createFiberFromPortal(portal, mode, expirationTime) {
  var pendingProps = portal.children !== null ? portal.children : [];
  var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
  fiber.expirationTime = expirationTime;
  fiber.stateNode = {
    containerInfo: portal.containerInfo,
    pendingChildren: null, // Used by persistent updates
    implementation: portal.implementation
  };
  return fiber;
}

// Used for stashing WIP properties to replay failed work in DEV.
function assignFiberPropertiesInDEV(target, source) {
  if (target === null) {
    // This Fiber's initial properties will always be overwritten.
    // We only use a Fiber to ensure the same hidden class so DEV isn't slow.
    target = createFiber(IndeterminateComponent, null, null, NoContext);
  }

  // This is intentionally written as a list of all properties.
  // We tried to use Object.assign() instead but this is called in
  // the hottest path, and Object.assign() was too slow:
  // https://github.com/facebook/react/issues/12502
  // This code is DEV-only so size is not a concern.

  target.tag = source.tag;
  target.key = source.key;
  target.type = source.type;
  target.stateNode = source.stateNode;
  target.return = source.return;
  target.child = source.child;
  target.sibling = source.sibling;
  target.index = source.index;
  target.ref = source.ref;
  target.pendingProps = source.pendingProps;
  target.memoizedProps = source.memoizedProps;
  target.updateQueue = source.updateQueue;
  target.memoizedState = source.memoizedState;
  target.mode = source.mode;
  target.effectTag = source.effectTag;
  target.nextEffect = source.nextEffect;
  target.firstEffect = source.firstEffect;
  target.lastEffect = source.lastEffect;
  target.expirationTime = source.expirationTime;
  target.alternate = source.alternate;
  if (enableProfilerTimer) {
    target.actualDuration = source.actualDuration;
    target.actualStartTime = source.actualStartTime;
    target.selfBaseTime = source.selfBaseTime;
    target.treeBaseTime = source.treeBaseTime;
  }
  target._debugID = source._debugID;
  target._debugSource = source._debugSource;
  target._debugOwner = source._debugOwner;
  target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming;
  return target;
}

// TODO: This should be lifted into the renderer.


function createFiberRoot(containerInfo, isAsync, hydrate) {
  // Cyclic construction. This cheats the type system right now because
  // stateNode is any.
  var uninitializedFiber = createHostRootFiber(isAsync);
  var root = {
    current: uninitializedFiber,
    containerInfo: containerInfo,
    pendingChildren: null,

    earliestPendingTime: NoWork,
    latestPendingTime: NoWork,
    earliestSuspendedTime: NoWork,
    latestSuspendedTime: NoWork,
    latestPingedTime: NoWork,

    pendingCommitExpirationTime: NoWork,
    finishedWork: null,
    context: null,
    pendingContext: null,
    hydrate: hydrate,
    remainingExpirationTime: NoWork,
    firstBatch: null,
    nextScheduledRoot: null
  };
  uninitializedFiber.stateNode = root;
  return root;
}

var onCommitFiberRoot = null;
var onCommitFiberUnmount = null;
var hasLoggedError = false;

function catchErrors(fn) {
  return function (arg) {
    try {
      return fn(arg);
    } catch (err) {
      if (true && !hasLoggedError) {
        hasLoggedError = true;
        warning(false, 'React DevTools encountered an error: %s', err);
      }
    }
  };
}

function injectInternals(internals) {
  if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
    // No DevTools
    return false;
  }
  var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
  if (hook.isDisabled) {
    // This isn't a real property on the hook, but it can be set to opt out
    // of DevTools integration and associated warnings and logs.
    // https://github.com/facebook/react/issues/3877
    return true;
  }
  if (!hook.supportsFiber) {
    {
      warning(false, 'The installed version of React DevTools is too old and will not work ' + 'with the current version of React. Please update React DevTools. ' + 'https://fb.me/react-devtools');
    }
    // DevTools exists, even though it doesn't support Fiber.
    return true;
  }
  try {
    var rendererID = hook.inject(internals);
    // We have successfully injected, so now it is safe to set up hooks.
    onCommitFiberRoot = catchErrors(function (root) {
      return hook.onCommitFiberRoot(rendererID, root);
    });
    onCommitFiberUnmount = catchErrors(function (fiber) {
      return hook.onCommitFiberUnmount(rendererID, fiber);
    });
  } catch (err) {
    // Catch all errors because it is unsafe to throw during initialization.
    {
      warning(false, 'React DevTools encountered an error: %s.', err);
    }
  }
  // DevTools exists
  return true;
}

function onCommitRoot(root) {
  if (typeof onCommitFiberRoot === 'function') {
    onCommitFiberRoot(root);
  }
}

function onCommitUnmount(fiber) {
  if (typeof onCommitFiberUnmount === 'function') {
    onCommitFiberUnmount(fiber);
  }
}

/**
 * Forked from fbjs/warning:
 * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
 *
 * Only change is we use console.warn instead of console.error,
 * and do nothing when 'console' is not supported.
 * This really simplifies the code.
 * ---
 * Similar to invariant but only logs a warning if the condition is not met.
 * This can be used to log issues in development environments in critical
 * paths. Removing the logging code for production environments will keep the
 * same logic and follow the same code paths.
 */

var lowPriorityWarning = function () {};

{
  var printWarning = function (format) {
    for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      args[_key - 1] = arguments[_key];
    }

    var argIndex = 0;
    var message = 'Warning: ' + format.replace(/%s/g, function () {
      return args[argIndex++];
    });
    if (typeof console !== 'undefined') {
      console.warn(message);
    }
    try {
      // --- Welcome to debugging React ---
      // This error was thrown as a convenience so that you can use this stack
      // to find the callsite that caused this warning to fire.
      throw new Error(message);
    } catch (x) {}
  };

  lowPriorityWarning = function (condition, format) {
    if (format === undefined) {
      throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
    }
    if (!condition) {
      for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
        args[_key2 - 2] = arguments[_key2];
      }

      printWarning.apply(undefined, [format].concat(args));
    }
  };
}

var lowPriorityWarning$1 = lowPriorityWarning;

var ReactStrictModeWarnings = {
  discardPendingWarnings: function () {},
  flushPendingDeprecationWarnings: function () {},
  flushPendingUnsafeLifecycleWarnings: function () {},
  recordDeprecationWarnings: function (fiber, instance) {},
  recordUnsafeLifecycleWarnings: function (fiber, instance) {},
  recordLegacyContextWarning: function (fiber, instance) {},
  flushLegacyContextWarning: function () {}
};

{
  var LIFECYCLE_SUGGESTIONS = {
    UNSAFE_componentWillMount: 'componentDidMount',
    UNSAFE_componentWillReceiveProps: 'static getDerivedStateFromProps',
    UNSAFE_componentWillUpdate: 'componentDidUpdate'
  };

  var pendingComponentWillMountWarnings = [];
  var pendingComponentWillReceivePropsWarnings = [];
  var pendingComponentWillUpdateWarnings = [];
  var pendingUnsafeLifecycleWarnings = new Map();
  var pendingLegacyContextWarning = new Map();

  // Tracks components we have already warned about.
  var didWarnAboutDeprecatedLifecycles = new Set();
  var didWarnAboutUnsafeLifecycles = new Set();
  var didWarnAboutLegacyContext = new Set();

  var setToSortedString = function (set) {
    var array = [];
    set.forEach(function (value) {
      array.push(value);
    });
    return array.sort().join(', ');
  };

  ReactStrictModeWarnings.discardPendingWarnings = function () {
    pendingComponentWillMountWarnings = [];
    pendingComponentWillReceivePropsWarnings = [];
    pendingComponentWillUpdateWarnings = [];
    pendingUnsafeLifecycleWarnings = new Map();
    pendingLegacyContextWarning = new Map();
  };

  ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {
    pendingUnsafeLifecycleWarnings.forEach(function (lifecycleWarningsMap, strictRoot) {
      var lifecyclesWarningMesages = [];

      Object.keys(lifecycleWarningsMap).forEach(function (lifecycle) {
        var lifecycleWarnings = lifecycleWarningsMap[lifecycle];
        if (lifecycleWarnings.length > 0) {
          var componentNames = new Set();
          lifecycleWarnings.forEach(function (fiber) {
            componentNames.add(getComponentName(fiber) || 'Component');
            didWarnAboutUnsafeLifecycles.add(fiber.type);
          });

          var formatted = lifecycle.replace('UNSAFE_', '');
          var suggestion = LIFECYCLE_SUGGESTIONS[lifecycle];
          var sortedComponentNames = setToSortedString(componentNames);

          lifecyclesWarningMesages.push(formatted + ': Please update the following components to use ' + (suggestion + ' instead: ' + sortedComponentNames));
        }
      });

      if (lifecyclesWarningMesages.length > 0) {
        var strictRootComponentStack = getStackAddendumByWorkInProgressFiber(strictRoot);

        warning(false, 'Unsafe lifecycle methods were found within a strict-mode tree:%s' + '\n\n%s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-strict-mode-warnings', strictRootComponentStack, lifecyclesWarningMesages.join('\n\n'));
      }
    });

    pendingUnsafeLifecycleWarnings = new Map();
  };

  var findStrictRoot = function (fiber) {
    var maybeStrictRoot = null;

    var node = fiber;
    while (node !== null) {
      if (node.mode & StrictMode) {
        maybeStrictRoot = node;
      }
      node = node.return;
    }

    return maybeStrictRoot;
  };

  ReactStrictModeWarnings.flushPendingDeprecationWarnings = function () {
    if (pendingComponentWillMountWarnings.length > 0) {
      var uniqueNames = new Set();
      pendingComponentWillMountWarnings.forEach(function (fiber) {
        uniqueNames.add(getComponentName(fiber) || 'Component');
        didWarnAboutDeprecatedLifecycles.add(fiber.type);
      });

      var sortedNames = setToSortedString(uniqueNames);

      lowPriorityWarning$1(false, 'componentWillMount is deprecated and will be removed in the next major version. ' + 'Use componentDidMount instead. As a temporary workaround, ' + 'you can rename to UNSAFE_componentWillMount.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-async-component-lifecycle-hooks', sortedNames);

      pendingComponentWillMountWarnings = [];
    }

    if (pendingComponentWillReceivePropsWarnings.length > 0) {
      var _uniqueNames = new Set();
      pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {
        _uniqueNames.add(getComponentName(fiber) || 'Component');
        didWarnAboutDeprecatedLifecycles.add(fiber.type);
      });

      var _sortedNames = setToSortedString(_uniqueNames);

      lowPriorityWarning$1(false, 'componentWillReceiveProps is deprecated and will be removed in the next major version. ' + 'Use static getDerivedStateFromProps instead.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-async-component-lifecycle-hooks', _sortedNames);

      pendingComponentWillReceivePropsWarnings = [];
    }

    if (pendingComponentWillUpdateWarnings.length > 0) {
      var _uniqueNames2 = new Set();
      pendingComponentWillUpdateWarnings.forEach(function (fiber) {
        _uniqueNames2.add(getComponentName(fiber) || 'Component');
        didWarnAboutDeprecatedLifecycles.add(fiber.type);
      });

      var _sortedNames2 = setToSortedString(_uniqueNames2);

      lowPriorityWarning$1(false, 'componentWillUpdate is deprecated and will be removed in the next major version. ' + 'Use componentDidUpdate instead. As a temporary workaround, ' + 'you can rename to UNSAFE_componentWillUpdate.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-async-component-lifecycle-hooks', _sortedNames2);

      pendingComponentWillUpdateWarnings = [];
    }
  };

  ReactStrictModeWarnings.recordDeprecationWarnings = function (fiber, instance) {
    // Dedup strategy: Warn once per component.
    if (didWarnAboutDeprecatedLifecycles.has(fiber.type)) {
      return;
    }

    // Don't warn about react-lifecycles-compat polyfilled components.
    if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
      pendingComponentWillMountWarnings.push(fiber);
    }
    if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
      pendingComponentWillReceivePropsWarnings.push(fiber);
    }
    if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
      pendingComponentWillUpdateWarnings.push(fiber);
    }
  };

  ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {
    var strictRoot = findStrictRoot(fiber);
    if (strictRoot === null) {
      warning(false, 'Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.');
      return;
    }

    // Dedup strategy: Warn once per component.
    // This is difficult to track any other way since component names
    // are often vague and are likely to collide between 3rd party libraries.
    // An expand property is probably okay to use here since it's DEV-only,
    // and will only be set in the event of serious warnings.
    if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
      return;
    }

    var warningsForRoot = void 0;
    if (!pendingUnsafeLifecycleWarnings.has(strictRoot)) {
      warningsForRoot = {
        UNSAFE_componentWillMount: [],
        UNSAFE_componentWillReceiveProps: [],
        UNSAFE_componentWillUpdate: []
      };

      pendingUnsafeLifecycleWarnings.set(strictRoot, warningsForRoot);
    } else {
      warningsForRoot = pendingUnsafeLifecycleWarnings.get(strictRoot);
    }

    var unsafeLifecycles = [];
    if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillMount === 'function') {
      unsafeLifecycles.push('UNSAFE_componentWillMount');
    }
    if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
      unsafeLifecycles.push('UNSAFE_componentWillReceiveProps');
    }
    if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillUpdate === 'function') {
      unsafeLifecycles.push('UNSAFE_componentWillUpdate');
    }

    if (unsafeLifecycles.length > 0) {
      unsafeLifecycles.forEach(function (lifecycle) {
        warningsForRoot[lifecycle].push(fiber);
      });
    }
  };

  ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {
    var strictRoot = findStrictRoot(fiber);
    if (strictRoot === null) {
      warning(false, 'Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.');
      return;
    }

    // Dedup strategy: Warn once per component.
    if (didWarnAboutLegacyContext.has(fiber.type)) {
      return;
    }

    var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);

    if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {
      if (warningsForRoot === undefined) {
        warningsForRoot = [];
        pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
      }
      warningsForRoot.push(fiber);
    }
  };

  ReactStrictModeWarnings.flushLegacyContextWarning = function () {
    pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {
      var uniqueNames = new Set();
      fiberArray.forEach(function (fiber) {
        uniqueNames.add(getComponentName(fiber) || 'Component');
        didWarnAboutLegacyContext.add(fiber.type);
      });

      var sortedNames = setToSortedString(uniqueNames);
      var strictRootComponentStack = getStackAddendumByWorkInProgressFiber(strictRoot);

      warning(false, 'Legacy context API has been detected within a strict-mode tree: %s' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-strict-mode-warnings', strictRootComponentStack, sortedNames);
    });
  };
}

// This lets us hook into Fiber to debug what it's doing.
// See https://github.com/facebook/react/pull/8033.
// This is not part of the public API, not even for React DevTools.
// You may only inject a debugTool if you work on React Fiber itself.
var ReactFiberInstrumentation = {
  debugTool: null
};

var ReactFiberInstrumentation_1 = ReactFiberInstrumentation;

// TODO: Offscreen updates

function markPendingPriorityLevel(root, expirationTime) {
  if (enableSuspense) {
    // Update the latest and earliest pending times
    var earliestPendingTime = root.earliestPendingTime;
    if (earliestPendingTime === NoWork) {
      // No other pending updates.
      root.earliestPendingTime = root.latestPendingTime = expirationTime;
    } else {
      if (earliestPendingTime > expirationTime) {
        // This is the earliest pending update.
        root.earliestPendingTime = expirationTime;
      } else {
        var latestPendingTime = root.latestPendingTime;
        if (latestPendingTime < expirationTime) {
          // This is the latest pending update
          root.latestPendingTime = expirationTime;
        }
      }
    }
  }
}

function markCommittedPriorityLevels(root, currentTime, earliestRemainingTime) {
  if (enableSuspense) {
    if (earliestRemainingTime === NoWork) {
      // Fast path. There's no remaining work. Clear everything.
      root.earliestPendingTime = NoWork;
      root.latestPendingTime = NoWork;
      root.earliestSuspendedTime = NoWork;
      root.latestSuspendedTime = NoWork;
      root.latestPingedTime = NoWork;
      return;
    }

    // Let's see if the previous latest known pending level was just flushed.
    var latestPendingTime = root.latestPendingTime;
    if (latestPendingTime !== NoWork) {
      if (latestPendingTime < earliestRemainingTime) {
        // We've flushed all the known pending levels.
        root.earliestPendingTime = root.latestPendingTime = NoWork;
      } else {
        var earliestPendingTime = root.earliestPendingTime;
        if (earliestPendingTime < earliestRemainingTime) {
          // We've flushed the earliest known pending level. Set this to the
          // latest pending time.
          root.earliestPendingTime = root.latestPendingTime;
        }
      }
    }

    // Now let's handle the earliest remaining level in the whole tree. We need to
    // decide whether to treat it as a pending level or as suspended. Check
    // it falls within the range of known suspended levels.

    var earliestSuspendedTime = root.earliestSuspendedTime;
    if (earliestSuspendedTime === NoWork) {
      // There's no suspended work. Treat the earliest remaining level as a
      // pending level.
      markPendingPriorityLevel(root, earliestRemainingTime);
      return;
    }

    var latestSuspendedTime = root.latestSuspendedTime;
    if (earliestRemainingTime > latestSuspendedTime) {
      // The earliest remaining level is later than all the suspended work. That
      // means we've flushed all the suspended work.
      root.earliestSuspendedTime = NoWork;
      root.latestSuspendedTime = NoWork;
      root.latestPingedTime = NoWork;

      // There's no suspended work. Treat the earliest remaining level as a
      // pending level.
      markPendingPriorityLevel(root, earliestRemainingTime);
      return;
    }

    if (earliestRemainingTime < earliestSuspendedTime) {
      // The earliest remaining time is earlier than all the suspended work.
      // Treat it as a pending update.
      markPendingPriorityLevel(root, earliestRemainingTime);
      return;
    }

    // The earliest remaining time falls within the range of known suspended
    // levels. We should treat this as suspended work.
  }
}

function markSuspendedPriorityLevel(root, suspendedTime) {
  if (enableSuspense) {
    // First, check the known pending levels and update them if needed.
    var earliestPendingTime = root.earliestPendingTime;
    var latestPendingTime = root.latestPendingTime;
    if (earliestPendingTime === suspendedTime) {
      if (latestPendingTime === suspendedTime) {
        // Both known pending levels were suspended. Clear them.
        root.earliestPendingTime = root.latestPendingTime = NoWork;
      } else {
        // The earliest pending level was suspended. Clear by setting it to the
        // latest pending level.
        root.earliestPendingTime = latestPendingTime;
      }
    } else if (latestPendingTime === suspendedTime) {
      // The latest pending level was suspended. Clear by setting it to the
      // latest pending level.
      root.latestPendingTime = earliestPendingTime;
    }

    // Next, if we're working on the lowest known suspended level, clear the ping.
    // TODO: What if a promise suspends and pings before the root completes?
    var latestSuspendedTime = root.latestSuspendedTime;
    if (latestSuspendedTime === suspendedTime) {
      root.latestPingedTime = NoWork;
    }

    // Finally, update the known suspended levels.
    var earliestSuspendedTime = root.earliestSuspendedTime;
    if (earliestSuspendedTime === NoWork) {
      // No other suspended levels.
      root.earliestSuspendedTime = root.latestSuspendedTime = suspendedTime;
    } else {
      if (earliestSuspendedTime > suspendedTime) {
        // This is the earliest suspended level.
        root.earliestSuspendedTime = suspendedTime;
      } else if (latestSuspendedTime < suspendedTime) {
        // This is the latest suspended level
        root.latestSuspendedTime = suspendedTime;
      }
    }
  }
}

function markPingedPriorityLevel(root, pingedTime) {
  if (enableSuspense) {
    var latestSuspendedTime = root.latestSuspendedTime;
    if (latestSuspendedTime !== NoWork && latestSuspendedTime <= pingedTime) {
      var latestPingedTime = root.latestPingedTime;
      if (latestPingedTime === NoWork || latestPingedTime < pingedTime) {
        root.latestPingedTime = pingedTime;
      }
    }
  }
}

function findNextPendingPriorityLevel(root) {
  if (enableSuspense) {
    var earliestSuspendedTime = root.earliestSuspendedTime;
    var earliestPendingTime = root.earliestPendingTime;
    if (earliestSuspendedTime === NoWork) {
      // Fast path. There's no suspended work.
      return earliestPendingTime;
    }

    // First, check if there's known pending work.
    if (earliestPendingTime !== NoWork) {
      return earliestPendingTime;
    }

    // Finally, if a suspended level was pinged, work on that. Otherwise there's
    // nothing to work on.
    return root.latestPingedTime;
  } else {
    return root.current.expirationTime;
  }
}

// UpdateQueue is a linked list of prioritized updates.
//
// Like fibers, update queues come in pairs: a current queue, which represents
// the visible state of the screen, and a work-in-progress queue, which is
// can be mutated and processed asynchronously before it is committed — a form
// of double buffering. If a work-in-progress render is discarded before
// finishing, we create a new work-in-progress by cloning the current queue.
//
// Both queues share a persistent, singly-linked list structure. To schedule an
// update, we append it to the end of both queues. Each queue maintains a
// pointer to first update in the persistent list that hasn't been processed.
// The work-in-progress pointer always has a position equal to or greater than
// the current queue, since we always work on that one. The current queue's
// pointer is only updated during the commit phase, when we swap in the
// work-in-progress.
//
// For example:
//
//   Current pointer:           A - B - C - D - E - F
//   Work-in-progress pointer:              D - E - F
//                                          ^
//                                          The work-in-progress queue has
//                                          processed more updates than current.
//
// The reason we append to both queues is because otherwise we might drop
// updates without ever processing them. For example, if we only add updates to
// the work-in-progress queue, some updates could be lost whenever a work-in
// -progress render restarts by cloning from current. Similarly, if we only add
// updates to the current queue, the updates will be lost whenever an already
// in-progress queue commits and swaps with the current queue. However, by
// adding to both queues, we guarantee that the update will be part of the next
// work-in-progress. (And because the work-in-progress queue becomes the
// current queue once it commits, there's no danger of applying the same
// update twice.)
//
// Prioritization
// --------------
//
// Updates are not sorted by priority, but by insertion; new updates are always
// appended to the end of the list.
//
// The priority is still important, though. When processing the update queue
// during the render phase, only the updates with sufficient priority are
// included in the result. If we skip an update because it has insufficient
// priority, it remains in the queue to be processed later, during a lower
// priority render. Crucially, all updates subsequent to a skipped update also
// remain in the queue *regardless of their priority*. That means high priority
// updates are sometimes processed twice, at two separate priorities. We also
// keep track of a base state, that represents the state before the first
// update in the queue is applied.
//
// For example:
//
//   Given a base state of '', and the following queue of updates
//
//     A1 - B2 - C1 - D2
//
//   where the number indicates the priority, and the update is applied to the
//   previous state by appending a letter, React will process these updates as
//   two separate renders, one per distinct priority level:
//
//   First render, at priority 1:
//     Base state: ''
//     Updates: [A1, C1]
//     Result state: 'AC'
//
//   Second render, at priority 2:
//     Base state: 'A'            <-  The base state does not include C1,
//                                    because B2 was skipped.
//     Updates: [B2, C1, D2]      <-  C1 was rebased on top of B2
//     Result state: 'ABCD'
//
// Because we process updates in insertion order, and rebase high priority
// updates when preceding updates are skipped, the final result is deterministic
// regardless of priority. Intermediate state may vary according to system
// resources, but the final state is always the same.

var UpdateState = 0;
var ReplaceState = 1;
var ForceUpdate = 2;
var CaptureUpdate = 3;

// Global state that is reset at the beginning of calling `processUpdateQueue`.
// It should only be read right after calling `processUpdateQueue`, via
// `checkHasForceUpdateAfterProcessing`.
var hasForceUpdate = false;

var didWarnUpdateInsideUpdate = void 0;
var currentlyProcessingQueue = void 0;
var resetCurrentlyProcessingQueue = void 0;
{
  didWarnUpdateInsideUpdate = false;
  currentlyProcessingQueue = null;
  resetCurrentlyProcessingQueue = function () {
    currentlyProcessingQueue = null;
  };
}

function createUpdateQueue(baseState) {
  var queue = {
    expirationTime: NoWork,
    baseState: baseState,
    firstUpdate: null,
    lastUpdate: null,
    firstCapturedUpdate: null,
    lastCapturedUpdate: null,
    firstEffect: null,
    lastEffect: null,
    firstCapturedEffect: null,
    lastCapturedEffect: null
  };
  return queue;
}

function cloneUpdateQueue(currentQueue) {
  var queue = {
    expirationTime: currentQueue.expirationTime,
    baseState: currentQueue.baseState,
    firstUpdate: currentQueue.firstUpdate,
    lastUpdate: currentQueue.lastUpdate,

    // TODO: With resuming, if we bail out and resuse the child tree, we should
    // keep these effects.
    firstCapturedUpdate: null,
    lastCapturedUpdate: null,

    firstEffect: null,
    lastEffect: null,

    firstCapturedEffect: null,
    lastCapturedEffect: null
  };
  return queue;
}

function createUpdate(expirationTime) {
  return {
    expirationTime: expirationTime,

    tag: UpdateState,
    payload: null,
    callback: null,

    next: null,
    nextEffect: null
  };
}

function appendUpdateToQueue(queue, update, expirationTime) {
  // Append the update to the end of the list.
  if (queue.lastUpdate === null) {
    // Queue is empty
    queue.firstUpdate = queue.lastUpdate = update;
  } else {
    queue.lastUpdate.next = update;
    queue.lastUpdate = update;
  }
  if (queue.expirationTime === NoWork || queue.expirationTime > expirationTime) {
    // The incoming update has the earliest expiration of any update in the
    // queue. Update the queue's expiration time.
    queue.expirationTime = expirationTime;
  }
}

function enqueueUpdate(fiber, update, expirationTime) {
  // Update queues are created lazily.
  var alternate = fiber.alternate;
  var queue1 = void 0;
  var queue2 = void 0;
  if (alternate === null) {
    // There's only one fiber.
    queue1 = fiber.updateQueue;
    queue2 = null;
    if (queue1 === null) {
      queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
    }
  } else {
    // There are two owners.
    queue1 = fiber.updateQueue;
    queue2 = alternate.updateQueue;
    if (queue1 === null) {
      if (queue2 === null) {
        // Neither fiber has an update queue. Create new ones.
        queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
        queue2 = alternate.updateQueue = createUpdateQueue(alternate.memoizedState);
      } else {
        // Only one fiber has an update queue. Clone to create a new one.
        queue1 = fiber.updateQueue = cloneUpdateQueue(queue2);
      }
    } else {
      if (queue2 === null) {
        // Only one fiber has an update queue. Clone to create a new one.
        queue2 = alternate.updateQueue = cloneUpdateQueue(queue1);
      } else {
        // Both owners have an update queue.
      }
    }
  }
  if (queue2 === null || queue1 === queue2) {
    // There's only a single queue.
    appendUpdateToQueue(queue1, update, expirationTime);
  } else {
    // There are two queues. We need to append the update to both queues,
    // while accounting for the persistent structure of the list — we don't
    // want the same update to be added multiple times.
    if (queue1.lastUpdate === null || queue2.lastUpdate === null) {
      // One of the queues is not empty. We must add the update to both queues.
      appendUpdateToQueue(queue1, update, expirationTime);
      appendUpdateToQueue(queue2, update, expirationTime);
    } else {
      // Both queues are non-empty. The last update is the same in both lists,
      // because of structural sharing. So, only append to one of the lists.
      appendUpdateToQueue(queue1, update, expirationTime);
      // But we still need to update the `lastUpdate` pointer of queue2.
      queue2.lastUpdate = update;
    }
  }

  {
    if (fiber.tag === ClassComponent && (currentlyProcessingQueue === queue1 || queue2 !== null && currentlyProcessingQueue === queue2) && !didWarnUpdateInsideUpdate) {
      warning(false, 'An update (setState, replaceState, or forceUpdate) was scheduled ' + 'from inside an update function. Update functions should be pure, ' + 'with zero side-effects. Consider using componentDidUpdate or a ' + 'callback.');
      didWarnUpdateInsideUpdate = true;
    }
  }
}

function enqueueCapturedUpdate(workInProgress, update, renderExpirationTime) {
  // Captured updates go into a separate list, and only on the work-in-
  // progress queue.
  var workInProgressQueue = workInProgress.updateQueue;
  if (workInProgressQueue === null) {
    workInProgressQueue = workInProgress.updateQueue = createUpdateQueue(workInProgress.memoizedState);
  } else {
    // TODO: I put this here rather than createWorkInProgress so that we don't
    // clone the queue unnecessarily. There's probably a better way to
    // structure this.
    workInProgressQueue = ensureWorkInProgressQueueIsAClone(workInProgress, workInProgressQueue);
  }

  // Append the update to the end of the list.
  if (workInProgressQueue.lastCapturedUpdate === null) {
    // This is the first render phase update
    workInProgressQueue.firstCapturedUpdate = workInProgressQueue.lastCapturedUpdate = update;
  } else {
    workInProgressQueue.lastCapturedUpdate.next = update;
    workInProgressQueue.lastCapturedUpdate = update;
  }
  if (workInProgressQueue.expirationTime === NoWork || workInProgressQueue.expirationTime > renderExpirationTime) {
    // The incoming update has the earliest expiration of any update in the
    // queue. Update the queue's expiration time.
    workInProgressQueue.expirationTime = renderExpirationTime;
  }
}

function ensureWorkInProgressQueueIsAClone(workInProgress, queue) {
  var current = workInProgress.alternate;
  if (current !== null) {
    // If the work-in-progress queue is equal to the current queue,
    // we need to clone it first.
    if (queue === current.updateQueue) {
      queue = workInProgress.updateQueue = cloneUpdateQueue(queue);
    }
  }
  return queue;
}

function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {
  switch (update.tag) {
    case ReplaceState:
      {
        var _payload = update.payload;
        if (typeof _payload === 'function') {
          // Updater function
          {
            if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
              _payload.call(instance, prevState, nextProps);
            }
          }
          return _payload.call(instance, prevState, nextProps);
        }
        // State object
        return _payload;
      }
    case CaptureUpdate:
      {
        workInProgress.effectTag = workInProgress.effectTag & ~ShouldCapture | DidCapture;
      }
    // Intentional fallthrough
    case UpdateState:
      {
        var _payload2 = update.payload;
        var partialState = void 0;
        if (typeof _payload2 === 'function') {
          // Updater function
          {
            if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
              _payload2.call(instance, prevState, nextProps);
            }
          }
          partialState = _payload2.call(instance, prevState, nextProps);
        } else {
          // Partial state object
          partialState = _payload2;
        }
        if (partialState === null || partialState === undefined) {
          // Null and undefined are treated as no-ops.
          return prevState;
        }
        // Merge the partial state and the previous state.
        return _assign({}, prevState, partialState);
      }
    case ForceUpdate:
      {
        hasForceUpdate = true;
        return prevState;
      }
  }
  return prevState;
}

function processUpdateQueue(workInProgress, queue, props, instance, renderExpirationTime) {
  hasForceUpdate = false;

  if (queue.expirationTime === NoWork || queue.expirationTime > renderExpirationTime) {
    // Insufficient priority. Bailout.
    return;
  }

  queue = ensureWorkInProgressQueueIsAClone(workInProgress, queue);

  {
    currentlyProcessingQueue = queue;
  }

  // These values may change as we process the queue.
  var newBaseState = queue.baseState;
  var newFirstUpdate = null;
  var newExpirationTime = NoWork;

  // Iterate through the list of updates to compute the result.
  var update = queue.firstUpdate;
  var resultState = newBaseState;
  while (update !== null) {
    var updateExpirationTime = update.expirationTime;
    if (updateExpirationTime > renderExpirationTime) {
      // This update does not have sufficient priority. Skip it.
      if (newFirstUpdate === null) {
        // This is the first skipped update. It will be the first update in
        // the new list.
        newFirstUpdate = update;
        // Since this is the first update that was skipped, the current result
        // is the new base state.
        newBaseState = resultState;
      }
      // Since this update will remain in the list, update the remaining
      // expiration time.
      if (newExpirationTime === NoWork || newExpirationTime > updateExpirationTime) {
        newExpirationTime = updateExpirationTime;
      }
    } else {
      // This update does have sufficient priority. Process it and compute
      // a new result.
      resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
      var _callback = update.callback;
      if (_callback !== null) {
        workInProgress.effectTag |= Callback;
        // Set this to null, in case it was mutated during an aborted render.
        update.nextEffect = null;
        if (queue.lastEffect === null) {
          queue.firstEffect = queue.lastEffect = update;
        } else {
          queue.lastEffect.nextEffect = update;
          queue.lastEffect = update;
        }
      }
    }
    // Continue to the next update.
    update = update.next;
  }

  // Separately, iterate though the list of captured updates.
  var newFirstCapturedUpdate = null;
  update = queue.firstCapturedUpdate;
  while (update !== null) {
    var _updateExpirationTime = update.expirationTime;
    if (_updateExpirationTime > renderExpirationTime) {
      // This update does not have sufficient priority. Skip it.
      if (newFirstCapturedUpdate === null) {
        // This is the first skipped captured update. It will be the first
        // update in the new list.
        newFirstCapturedUpdate = update;
        // If this is the first update that was skipped, the current result is
        // the new base state.
        if (newFirstUpdate === null) {
          newBaseState = resultState;
        }
      }
      // Since this update will remain in the list, update the remaining
      // expiration time.
      if (newExpirationTime === NoWork || newExpirationTime > _updateExpirationTime) {
        newExpirationTime = _updateExpirationTime;
      }
    } else {
      // This update does have sufficient priority. Process it and compute
      // a new result.
      resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
      var _callback2 = update.callback;
      if (_callback2 !== null) {
        workInProgress.effectTag |= Callback;
        // Set this to null, in case it was mutated during an aborted render.
        update.nextEffect = null;
        if (queue.lastCapturedEffect === null) {
          queue.firstCapturedEffect = queue.lastCapturedEffect = update;
        } else {
          queue.lastCapturedEffect.nextEffect = update;
          queue.lastCapturedEffect = update;
        }
      }
    }
    update = update.next;
  }

  if (newFirstUpdate === null) {
    queue.lastUpdate = null;
  }
  if (newFirstCapturedUpdate === null) {
    queue.lastCapturedUpdate = null;
  } else {
    workInProgress.effectTag |= Callback;
  }
  if (newFirstUpdate === null && newFirstCapturedUpdate === null) {
    // We processed every update, without skipping. That means the new base
    // state is the same as the result state.
    newBaseState = resultState;
  }

  queue.baseState = newBaseState;
  queue.firstUpdate = newFirstUpdate;
  queue.firstCapturedUpdate = newFirstCapturedUpdate;
  queue.expirationTime = newExpirationTime;

  workInProgress.memoizedState = resultState;

  {
    currentlyProcessingQueue = null;
  }
}

function callCallback(callback, context) {
  !(typeof callback === 'function') ? invariant(false, 'Invalid argument passed as callback. Expected a function. Instead received: %s', callback) : void 0;
  callback.call(context);
}

function resetHasForceUpdateBeforeProcessing() {
  hasForceUpdate = false;
}

function checkHasForceUpdateAfterProcessing() {
  return hasForceUpdate;
}

function commitUpdateQueue(finishedWork, finishedQueue, instance, renderExpirationTime) {
  // If the finished render included captured updates, and there are still
  // lower priority updates left over, we need to keep the captured updates
  // in the queue so that they are rebased and not dropped once we process the
  // queue again at the lower priority.
  if (finishedQueue.firstCapturedUpdate !== null) {
    // Join the captured update list to the end of the normal list.
    if (finishedQueue.lastUpdate !== null) {
      finishedQueue.lastUpdate.next = finishedQueue.firstCapturedUpdate;
      finishedQueue.lastUpdate = finishedQueue.lastCapturedUpdate;
    }
    // Clear the list of captured updates.
    finishedQueue.firstCapturedUpdate = finishedQueue.lastCapturedUpdate = null;
  }

  // Commit the effects
  var effect = finishedQueue.firstEffect;
  finishedQueue.firstEffect = finishedQueue.lastEffect = null;
  while (effect !== null) {
    var _callback3 = effect.callback;
    if (_callback3 !== null) {
      effect.callback = null;
      callCallback(_callback3, instance);
    }
    effect = effect.nextEffect;
  }

  effect = finishedQueue.firstCapturedEffect;
  finishedQueue.firstCapturedEffect = finishedQueue.lastCapturedEffect = null;
  while (effect !== null) {
    var _callback4 = effect.callback;
    if (_callback4 !== null) {
      effect.callback = null;
      callCallback(_callback4, instance);
    }
    effect = effect.nextEffect;
  }
}

function createCapturedValue(value, source) {
  // If the value is an error, call this function immediately after it is thrown
  // so the stack is accurate.
  return {
    value: value,
    source: source,
    stack: getStackAddendumByWorkInProgressFiber(source)
  };
}

var providerCursor = createCursor(null);
var valueCursor = createCursor(null);
var changedBitsCursor = createCursor(0);

var rendererSigil = void 0;
{
  // Use this to detect multiple renderers using the same context
  rendererSigil = {};
}

function pushProvider(providerFiber) {
  var context = providerFiber.type._context;

  if (isPrimaryRenderer) {
    push(changedBitsCursor, context._changedBits, providerFiber);
    push(valueCursor, context._currentValue, providerFiber);
    push(providerCursor, providerFiber, providerFiber);

    context._currentValue = providerFiber.pendingProps.value;
    context._changedBits = providerFiber.stateNode;
    {
      !(context._currentRenderer === undefined || context._currentRenderer === null || context._currentRenderer === rendererSigil) ? warning(false, 'Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.') : void 0;
      context._currentRenderer = rendererSigil;
    }
  } else {
    push(changedBitsCursor, context._changedBits2, providerFiber);
    push(valueCursor, context._currentValue2, providerFiber);
    push(providerCursor, providerFiber, providerFiber);

    context._currentValue2 = providerFiber.pendingProps.value;
    context._changedBits2 = providerFiber.stateNode;
    {
      !(context._currentRenderer2 === undefined || context._currentRenderer2 === null || context._currentRenderer2 === rendererSigil) ? warning(false, 'Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.') : void 0;
      context._currentRenderer2 = rendererSigil;
    }
  }
}

function popProvider(providerFiber) {
  var changedBits = changedBitsCursor.current;
  var currentValue = valueCursor.current;

  pop(providerCursor, providerFiber);
  pop(valueCursor, providerFiber);
  pop(changedBitsCursor, providerFiber);

  var context = providerFiber.type._context;
  if (isPrimaryRenderer) {
    context._currentValue = currentValue;
    context._changedBits = changedBits;
  } else {
    context._currentValue2 = currentValue;
    context._changedBits2 = changedBits;
  }
}

function getContextCurrentValue(context) {
  return isPrimaryRenderer ? context._currentValue : context._currentValue2;
}

function getContextChangedBits(context) {
  return isPrimaryRenderer ? context._changedBits : context._changedBits2;
}

var NO_CONTEXT = {};

var contextStackCursor$1 = createCursor(NO_CONTEXT);
var contextFiberStackCursor = createCursor(NO_CONTEXT);
var rootInstanceStackCursor = createCursor(NO_CONTEXT);

function requiredContext(c) {
  !(c !== NO_CONTEXT) ? invariant(false, 'Expected host context to exist. This error is likely caused by a bug in React. Please file an issue.') : void 0;
  return c;
}

function getRootHostContainer() {
  var rootInstance = requiredContext(rootInstanceStackCursor.current);
  return rootInstance;
}

function pushHostContainer(fiber, nextRootInstance) {
  // Push current root instance onto the stack;
  // This allows us to reset root when portals are popped.
  push(rootInstanceStackCursor, nextRootInstance, fiber);
  // Track the context and the Fiber that provided it.
  // This enables us to pop only Fibers that provide unique contexts.
  push(contextFiberStackCursor, fiber, fiber);

  // Finally, we need to push the host context to the stack.
  // However, we can't just call getRootHostContext() and push it because
  // we'd have a different number of entries on the stack depending on
  // whether getRootHostContext() throws somewhere in renderer code or not.
  // So we push an empty value first. This lets us safely unwind on errors.
  push(contextStackCursor$1, NO_CONTEXT, fiber);
  var nextRootContext = getRootHostContext(nextRootInstance);
  // Now that we know this function doesn't throw, replace it.
  pop(contextStackCursor$1, fiber);
  push(contextStackCursor$1, nextRootContext, fiber);
}

function popHostContainer(fiber) {
  pop(contextStackCursor$1, fiber);
  pop(contextFiberStackCursor, fiber);
  pop(rootInstanceStackCursor, fiber);
}

function getHostContext() {
  var context = requiredContext(contextStackCursor$1.current);
  return context;
}

function pushHostContext(fiber) {
  var rootInstance = requiredContext(rootInstanceStackCursor.current);
  var context = requiredContext(contextStackCursor$1.current);
  var nextContext = getChildHostContext(context, fiber.type, rootInstance);

  // Don't push this Fiber's context unless it's unique.
  if (context === nextContext) {
    return;
  }

  // Track the context and the Fiber that provided it.
  // This enables us to pop only Fibers that provide unique contexts.
  push(contextFiberStackCursor, fiber, fiber);
  push(contextStackCursor$1, nextContext, fiber);
}

function popHostContext(fiber) {
  // Do not pop unless this Fiber provided the current context.
  // pushHostContext() only pushes Fibers that provide unique contexts.
  if (contextFiberStackCursor.current !== fiber) {
    return;
  }

  pop(contextStackCursor$1, fiber);
  pop(contextFiberStackCursor, fiber);
}

var commitTime = 0;

function getCommitTime() {
  return commitTime;
}

function recordCommitTime() {
  if (!enableProfilerTimer) {
    return;
  }
  commitTime = now();
}

/**
 * The "actual" render time is total time required to render the descendants of a Profiler component.
 * This time is stored as a stack, since Profilers can be nested.
 * This time is started during the "begin" phase and stopped during the "complete" phase.
 * It is paused (and accumulated) in the event of an interruption or an aborted render.
 */

var fiberStack$1 = void 0;

{
  fiberStack$1 = [];
}

var timerPausedAt = 0;
var totalElapsedPauseTime = 0;

function checkActualRenderTimeStackEmpty() {
  if (!enableProfilerTimer) {
    return;
  }
  {
    !(fiberStack$1.length === 0) ? warning(false, 'Expected an empty stack. Something was not reset properly.') : void 0;
  }
}

function markActualRenderTimeStarted(fiber) {
  if (!enableProfilerTimer) {
    return;
  }
  {
    fiberStack$1.push(fiber);
  }

  fiber.actualDuration = now() - fiber.actualDuration - totalElapsedPauseTime;
  fiber.actualStartTime = now();
}

function pauseActualRenderTimerIfRunning() {
  if (!enableProfilerTimer) {
    return;
  }
  if (timerPausedAt === 0) {
    timerPausedAt = now();
  }
}

function recordElapsedActualRenderTime(fiber) {
  if (!enableProfilerTimer) {
    return;
  }
  {
    !(fiber === fiberStack$1.pop()) ? warning(false, 'Unexpected Fiber (%s) popped.', getComponentName(fiber)) : void 0;
  }

  fiber.actualDuration = now() - totalElapsedPauseTime - fiber.actualDuration;
}

function resetActualRenderTimer() {
  if (!enableProfilerTimer) {
    return;
  }
  totalElapsedPauseTime = 0;
}

function resumeActualRenderTimerIfPaused() {
  if (!enableProfilerTimer) {
    return;
  }
  if (timerPausedAt > 0) {
    totalElapsedPauseTime += now() - timerPausedAt;
    timerPausedAt = 0;
  }
}

/**
 * The "base" render time is the duration of the “begin” phase of work for a particular fiber.
 * This time is measured and stored on each fiber.
 * The time for all sibling fibers are accumulated and stored on their parent during the "complete" phase.
 * If a fiber bails out (sCU false) then its "base" timer is cancelled and the fiber is not updated.
 */

var baseStartTime = -1;

function recordElapsedBaseRenderTimeIfRunning(fiber) {
  if (!enableProfilerTimer) {
    return;
  }
  if (baseStartTime !== -1) {
    fiber.selfBaseTime = now() - baseStartTime;
  }
}

function startBaseRenderTimer() {
  if (!enableProfilerTimer) {
    return;
  }
  {
    if (baseStartTime !== -1) {
      warning(false, 'Cannot start base timer that is already running. ' + 'This error is likely caused by a bug in React. ' + 'Please file an issue.');
    }
  }
  baseStartTime = now();
}

function stopBaseRenderTimerIfRunning() {
  if (!enableProfilerTimer) {
    return;
  }
  baseStartTime = -1;
}

var fakeInternalInstance = {};
var isArray = Array.isArray;

var didWarnAboutStateAssignmentForComponent = void 0;
var didWarnAboutUninitializedState = void 0;
var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = void 0;
var didWarnAboutLegacyLifecyclesAndDerivedState = void 0;
var didWarnAboutUndefinedDerivedState = void 0;
var warnOnUndefinedDerivedState = void 0;
var warnOnInvalidCallback$1 = void 0;

{
  didWarnAboutStateAssignmentForComponent = new Set();
  didWarnAboutUninitializedState = new Set();
  didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
  didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
  didWarnAboutUndefinedDerivedState = new Set();

  var didWarnOnInvalidCallback = new Set();

  warnOnInvalidCallback$1 = function (callback, callerName) {
    if (callback === null || typeof callback === 'function') {
      return;
    }
    var key = callerName + '_' + callback;
    if (!didWarnOnInvalidCallback.has(key)) {
      didWarnOnInvalidCallback.add(key);
      warning(false, '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
    }
  };

  warnOnUndefinedDerivedState = function (workInProgress, partialState) {
    if (partialState === undefined) {
      var componentName = getComponentName(workInProgress) || 'Component';
      if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
        didWarnAboutUndefinedDerivedState.add(componentName);
        warning(false, '%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
      }
    }
  };

  // This is so gross but it's at least non-critical and can be removed if
  // it causes problems. This is meant to give a nicer error message for
  // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
  // ...)) which otherwise throws a "_processChildContext is not a function"
  // exception.
  Object.defineProperty(fakeInternalInstance, '_processChildContext', {
    enumerable: false,
    value: function () {
      invariant(false, '_processChildContext is not available in React 16+. This likely means you have multiple copies of React and are attempting to nest a React 15 tree inside a React 16 tree using unstable_renderSubtreeIntoContainer, which isn\'t supported. Try to make sure you have only one copy of React (and ideally, switch to ReactDOM.createPortal).');
    }
  });
  Object.freeze(fakeInternalInstance);
}

function applyDerivedStateFromProps(workInProgress, getDerivedStateFromProps, nextProps) {
  var prevState = workInProgress.memoizedState;

  {
    if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
      // Invoke the function an extra time to help detect side-effects.
      getDerivedStateFromProps(nextProps, prevState);
    }
  }

  var partialState = getDerivedStateFromProps(nextProps, prevState);

  {
    warnOnUndefinedDerivedState(workInProgress, partialState);
  }
  // Merge the partial state and the previous state.
  var memoizedState = partialState === null || partialState === undefined ? prevState : _assign({}, prevState, partialState);
  workInProgress.memoizedState = memoizedState;

  // Once the update queue is empty, persist the derived state onto the
  // base state.
  var updateQueue = workInProgress.updateQueue;
  if (updateQueue !== null && updateQueue.expirationTime === NoWork) {
    updateQueue.baseState = memoizedState;
  }
}

var classComponentUpdater = {
  isMounted: isMounted,
  enqueueSetState: function (inst, payload, callback) {
    var fiber = get(inst);
    var currentTime = recalculateCurrentTime();
    var expirationTime = computeExpirationForFiber(currentTime, fiber);

    var update = createUpdate(expirationTime);
    update.payload = payload;
    if (callback !== undefined && callback !== null) {
      {
        warnOnInvalidCallback$1(callback, 'setState');
      }
      update.callback = callback;
    }

    enqueueUpdate(fiber, update, expirationTime);
    scheduleWork$1(fiber, expirationTime);
  },
  enqueueReplaceState: function (inst, payload, callback) {
    var fiber = get(inst);
    var currentTime = recalculateCurrentTime();
    var expirationTime = computeExpirationForFiber(currentTime, fiber);

    var update = createUpdate(expirationTime);
    update.tag = ReplaceState;
    update.payload = payload;

    if (callback !== undefined && callback !== null) {
      {
        warnOnInvalidCallback$1(callback, 'replaceState');
      }
      update.callback = callback;
    }

    enqueueUpdate(fiber, update, expirationTime);
    scheduleWork$1(fiber, expirationTime);
  },
  enqueueForceUpdate: function (inst, callback) {
    var fiber = get(inst);
    var currentTime = recalculateCurrentTime();
    var expirationTime = computeExpirationForFiber(currentTime, fiber);

    var update = createUpdate(expirationTime);
    update.tag = ForceUpdate;

    if (callback !== undefined && callback !== null) {
      {
        warnOnInvalidCallback$1(callback, 'forceUpdate');
      }
      update.callback = callback;
    }

    enqueueUpdate(fiber, update, expirationTime);
    scheduleWork$1(fiber, expirationTime);
  }
};

function checkShouldComponentUpdate(workInProgress, oldProps, newProps, oldState, newState, newContext) {
  var instance = workInProgress.stateNode;
  var ctor = workInProgress.type;
  if (typeof instance.shouldComponentUpdate === 'function') {
    startPhaseTimer(workInProgress, 'shouldComponentUpdate');
    var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, newContext);
    stopPhaseTimer();

    {
      !(shouldUpdate !== undefined) ? warning(false, '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', getComponentName(workInProgress) || 'Component') : void 0;
    }

    return shouldUpdate;
  }

  if (ctor.prototype && ctor.prototype.isPureReactComponent) {
    return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
  }

  return true;
}

function checkClassInstance(workInProgress) {
  var instance = workInProgress.stateNode;
  var type = workInProgress.type;
  {
    var name = getComponentName(workInProgress) || 'Component';
    var renderPresent = instance.render;

    if (!renderPresent) {
      if (type.prototype && typeof type.prototype.render === 'function') {
        warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
      } else {
        warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
      }
    }

    var noGetInitialStateOnES6 = !instance.getInitialState || instance.getInitialState.isReactClassApproved || instance.state;
    !noGetInitialStateOnES6 ? warning(false, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name) : void 0;
    var noGetDefaultPropsOnES6 = !instance.getDefaultProps || instance.getDefaultProps.isReactClassApproved;
    !noGetDefaultPropsOnES6 ? warning(false, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name) : void 0;
    var noInstancePropTypes = !instance.propTypes;
    !noInstancePropTypes ? warning(false, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name) : void 0;
    var noInstanceContextTypes = !instance.contextTypes;
    !noInstanceContextTypes ? warning(false, 'contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name) : void 0;
    var noComponentShouldUpdate = typeof instance.componentShouldUpdate !== 'function';
    !noComponentShouldUpdate ? warning(false, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name) : void 0;
    if (type.prototype && type.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
      warning(false, '%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentName(workInProgress) || 'A pure component');
    }
    var noComponentDidUnmount = typeof instance.componentDidUnmount !== 'function';
    !noComponentDidUnmount ? warning(false, '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name) : void 0;
    var noComponentDidReceiveProps = typeof instance.componentDidReceiveProps !== 'function';
    !noComponentDidReceiveProps ? warning(false, '%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name) : void 0;
    var noComponentWillRecieveProps = typeof instance.componentWillRecieveProps !== 'function';
    !noComponentWillRecieveProps ? warning(false, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name) : void 0;
    var noUnsafeComponentWillRecieveProps = typeof instance.UNSAFE_componentWillRecieveProps !== 'function';
    !noUnsafeComponentWillRecieveProps ? warning(false, '%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name) : void 0;
    var hasMutatedProps = instance.props !== workInProgress.pendingProps;
    !(instance.props === undefined || !hasMutatedProps) ? warning(false, '%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name) : void 0;
    var noInstanceDefaultProps = !instance.defaultProps;
    !noInstanceDefaultProps ? warning(false, 'Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name) : void 0;

    if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(type)) {
      didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(type);
      warning(false, '%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentName(workInProgress));
    }

    var noInstanceGetDerivedStateFromProps = typeof instance.getDerivedStateFromProps !== 'function';
    !noInstanceGetDerivedStateFromProps ? warning(false, '%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name) : void 0;
    var noInstanceGetDerivedStateFromCatch = typeof instance.getDerivedStateFromCatch !== 'function';
    !noInstanceGetDerivedStateFromCatch ? warning(false, '%s: getDerivedStateFromCatch() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name) : void 0;
    var noStaticGetSnapshotBeforeUpdate = typeof type.getSnapshotBeforeUpdate !== 'function';
    !noStaticGetSnapshotBeforeUpdate ? warning(false, '%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name) : void 0;
    var _state = instance.state;
    if (_state && (typeof _state !== 'object' || isArray(_state))) {
      warning(false, '%s.state: must be set to an object or null', name);
    }
    if (typeof instance.getChildContext === 'function') {
      !(typeof type.childContextTypes === 'object') ? warning(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name) : void 0;
    }
  }
}

function adoptClassInstance(workInProgress, instance) {
  instance.updater = classComponentUpdater;
  workInProgress.stateNode = instance;
  // The instance needs access to the fiber so that it can schedule updates
  set(instance, workInProgress);
  {
    instance._reactInternalInstance = fakeInternalInstance;
  }
}

function constructClassInstance(workInProgress, props, renderExpirationTime) {
  var ctor = workInProgress.type;
  var unmaskedContext = getUnmaskedContext(workInProgress);
  var needsContext = isContextConsumer(workInProgress);
  var context = needsContext ? getMaskedContext(workInProgress, unmaskedContext) : emptyObject;

  // Instantiate twice to help detect side-effects.
  {
    if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
      new ctor(props, context); // eslint-disable-line no-new
    }
  }

  var instance = new ctor(props, context);
  var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;
  adoptClassInstance(workInProgress, instance);

  {
    if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
      var componentName = getComponentName(workInProgress) || 'Component';
      if (!didWarnAboutUninitializedState.has(componentName)) {
        didWarnAboutUninitializedState.add(componentName);
        warning(false, '%s: Did not properly initialize state during construction. ' + 'Expected state to be an object, but it was %s.', componentName, instance.state === null ? 'null' : 'undefined');
      }
    }

    // If new component APIs are defined, "unsafe" lifecycles won't be called.
    // Warn about these lifecycles if they are present.
    // Don't warn about react-lifecycles-compat polyfilled methods though.
    if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
      var foundWillMountName = null;
      var foundWillReceivePropsName = null;
      var foundWillUpdateName = null;
      if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
        foundWillMountName = 'componentWillMount';
      } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
        foundWillMountName = 'UNSAFE_componentWillMount';
      }
      if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
        foundWillReceivePropsName = 'componentWillReceiveProps';
      } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
        foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
      }
      if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
        foundWillUpdateName = 'componentWillUpdate';
      } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
        foundWillUpdateName = 'UNSAFE_componentWillUpdate';
      }
      if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
        var _componentName = getComponentName(workInProgress) || 'Component';
        var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';
        if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
          didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
          warning(false, 'Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://fb.me/react-async-component-lifecycle-hooks', _componentName, newApiName, foundWillMountName !== null ? '\n  ' + foundWillMountName : '', foundWillReceivePropsName !== null ? '\n  ' + foundWillReceivePropsName : '', foundWillUpdateName !== null ? '\n  ' + foundWillUpdateName : '');
        }
      }
    }
  }

  // Cache unmasked context so we can avoid recreating masked context unless necessary.
  // ReactFiberContext usually updates this cache but can't for newly-created instances.
  if (needsContext) {
    cacheContext(workInProgress, unmaskedContext, context);
  }

  return instance;
}

function callComponentWillMount(workInProgress, instance) {
  startPhaseTimer(workInProgress, 'componentWillMount');
  var oldState = instance.state;

  if (typeof instance.componentWillMount === 'function') {
    instance.componentWillMount();
  }
  if (typeof instance.UNSAFE_componentWillMount === 'function') {
    instance.UNSAFE_componentWillMount();
  }

  stopPhaseTimer();

  if (oldState !== instance.state) {
    {
      warning(false, '%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentName(workInProgress) || 'Component');
    }
    classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
  }
}

function callComponentWillReceiveProps(workInProgress, instance, newProps, newContext) {
  var oldState = instance.state;
  startPhaseTimer(workInProgress, 'componentWillReceiveProps');
  if (typeof instance.componentWillReceiveProps === 'function') {
    instance.componentWillReceiveProps(newProps, newContext);
  }
  if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
    instance.UNSAFE_componentWillReceiveProps(newProps, newContext);
  }
  stopPhaseTimer();

  if (instance.state !== oldState) {
    {
      var componentName = getComponentName(workInProgress) || 'Component';
      if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
        didWarnAboutStateAssignmentForComponent.add(componentName);
        warning(false, '%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName);
      }
    }
    classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
  }
}

// Invokes the mount life-cycles on a previously never rendered instance.
function mountClassInstance(workInProgress, renderExpirationTime) {
  var ctor = workInProgress.type;

  {
    checkClassInstance(workInProgress);
  }

  var instance = workInProgress.stateNode;
  var props = workInProgress.pendingProps;
  var unmaskedContext = getUnmaskedContext(workInProgress);

  instance.props = props;
  instance.state = workInProgress.memoizedState;
  instance.refs = emptyObject;
  instance.context = getMaskedContext(workInProgress, unmaskedContext);

  {
    if (workInProgress.mode & StrictMode) {
      ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);

      ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);
    }

    if (warnAboutDeprecatedLifecycles) {
      ReactStrictModeWarnings.recordDeprecationWarnings(workInProgress, instance);
    }
  }

  var updateQueue = workInProgress.updateQueue;
  if (updateQueue !== null) {
    processUpdateQueue(workInProgress, updateQueue, props, instance, renderExpirationTime);
    instance.state = workInProgress.memoizedState;
  }

  var getDerivedStateFromProps = workInProgress.type.getDerivedStateFromProps;
  if (typeof getDerivedStateFromProps === 'function') {
    applyDerivedStateFromProps(workInProgress, getDerivedStateFromProps, props);
    instance.state = workInProgress.memoizedState;
  }

  // In order to support react-lifecycles-compat polyfilled components,
  // Unsafe lifecycles should not be invoked for components using the new APIs.
  if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
    callComponentWillMount(workInProgress, instance);
    // If we had additional state updates during this life-cycle, let's
    // process them now.
    updateQueue = workInProgress.updateQueue;
    if (updateQueue !== null) {
      processUpdateQueue(workInProgress, updateQueue, props, instance, renderExpirationTime);
      instance.state = workInProgress.memoizedState;
    }
  }

  if (typeof instance.componentDidMount === 'function') {
    workInProgress.effectTag |= Update;
  }
}

function resumeMountClassInstance(workInProgress, renderExpirationTime) {
  var ctor = workInProgress.type;
  var instance = workInProgress.stateNode;

  var oldProps = workInProgress.memoizedProps;
  var newProps = workInProgress.pendingProps;
  instance.props = oldProps;

  var oldContext = instance.context;
  var newUnmaskedContext = getUnmaskedContext(workInProgress);
  var newContext = getMaskedContext(workInProgress, newUnmaskedContext);

  var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
  var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function';

  // Note: During these life-cycles, instance.props/instance.state are what
  // ever the previously attempted to render - not the "current". However,
  // during componentDidUpdate we pass the "current" props.

  // In order to support react-lifecycles-compat polyfilled components,
  // Unsafe lifecycles should not be invoked for components using the new APIs.
  if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
    if (oldProps !== newProps || oldContext !== newContext) {
      callComponentWillReceiveProps(workInProgress, instance, newProps, newContext);
    }
  }

  resetHasForceUpdateBeforeProcessing();

  var oldState = workInProgress.memoizedState;
  var newState = instance.state = oldState;
  var updateQueue = workInProgress.updateQueue;
  if (updateQueue !== null) {
    processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
    newState = workInProgress.memoizedState;
  }
  if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
    // If an update was already in progress, we should schedule an Update
    // effect even though we're bailing out, so that cWU/cDU are called.
    if (typeof instance.componentDidMount === 'function') {
      workInProgress.effectTag |= Update;
    }
    return false;
  }

  if (typeof getDerivedStateFromProps === 'function') {
    applyDerivedStateFromProps(workInProgress, getDerivedStateFromProps, newProps);
    newState = workInProgress.memoizedState;
  }

  var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, oldProps, newProps, oldState, newState, newContext);

  if (shouldUpdate) {
    // In order to support react-lifecycles-compat polyfilled components,
    // Unsafe lifecycles should not be invoked for components using the new APIs.
    if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
      startPhaseTimer(workInProgress, 'componentWillMount');
      if (typeof instance.componentWillMount === 'function') {
        instance.componentWillMount();
      }
      if (typeof instance.UNSAFE_componentWillMount === 'function') {
        instance.UNSAFE_componentWillMount();
      }
      stopPhaseTimer();
    }
    if (typeof instance.componentDidMount === 'function') {
      workInProgress.effectTag |= Update;
    }
  } else {
    // If an update was already in progress, we should schedule an Update
    // effect even though we're bailing out, so that cWU/cDU are called.
    if (typeof instance.componentDidMount === 'function') {
      workInProgress.effectTag |= Update;
    }

    // If shouldComponentUpdate returned false, we should still update the
    // memoized state to indicate that this work can be reused.
    workInProgress.memoizedProps = newProps;
    workInProgress.memoizedState = newState;
  }

  // Update the existing instance's state, props, and context pointers even
  // if shouldComponentUpdate returns false.
  instance.props = newProps;
  instance.state = newState;
  instance.context = newContext;

  return shouldUpdate;
}

// Invokes the update life-cycles and returns false if it shouldn't rerender.
function updateClassInstance(current, workInProgress, renderExpirationTime) {
  var ctor = workInProgress.type;
  var instance = workInProgress.stateNode;

  var oldProps = workInProgress.memoizedProps;
  var newProps = workInProgress.pendingProps;
  instance.props = oldProps;

  var oldContext = instance.context;
  var newUnmaskedContext = getUnmaskedContext(workInProgress);
  var newContext = getMaskedContext(workInProgress, newUnmaskedContext);

  var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
  var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function';

  // Note: During these life-cycles, instance.props/instance.state are what
  // ever the previously attempted to render - not the "current". However,
  // during componentDidUpdate we pass the "current" props.

  // In order to support react-lifecycles-compat polyfilled components,
  // Unsafe lifecycles should not be invoked for components using the new APIs.
  if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
    if (oldProps !== newProps || oldContext !== newContext) {
      callComponentWillReceiveProps(workInProgress, instance, newProps, newContext);
    }
  }

  resetHasForceUpdateBeforeProcessing();

  var oldState = workInProgress.memoizedState;
  var newState = instance.state = oldState;
  var updateQueue = workInProgress.updateQueue;
  if (updateQueue !== null) {
    processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
    newState = workInProgress.memoizedState;
  }

  if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
    // If an update was already in progress, we should schedule an Update
    // effect even though we're bailing out, so that cWU/cDU are called.
    if (typeof instance.componentDidUpdate === 'function') {
      if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
        workInProgress.effectTag |= Update;
      }
    }
    if (typeof instance.getSnapshotBeforeUpdate === 'function') {
      if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
        workInProgress.effectTag |= Snapshot;
      }
    }
    return false;
  }

  if (typeof getDerivedStateFromProps === 'function') {
    applyDerivedStateFromProps(workInProgress, getDerivedStateFromProps, newProps);
    newState = workInProgress.memoizedState;
  }

  var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, oldProps, newProps, oldState, newState, newContext);

  if (shouldUpdate) {
    // In order to support react-lifecycles-compat polyfilled components,
    // Unsafe lifecycles should not be invoked for components using the new APIs.
    if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {
      startPhaseTimer(workInProgress, 'componentWillUpdate');
      if (typeof instance.componentWillUpdate === 'function') {
        instance.componentWillUpdate(newProps, newState, newContext);
      }
      if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
        instance.UNSAFE_componentWillUpdate(newProps, newState, newContext);
      }
      stopPhaseTimer();
    }
    if (typeof instance.componentDidUpdate === 'function') {
      workInProgress.effectTag |= Update;
    }
    if (typeof instance.getSnapshotBeforeUpdate === 'function') {
      workInProgress.effectTag |= Snapshot;
    }
  } else {
    // If an update was already in progress, we should schedule an Update
    // effect even though we're bailing out, so that cWU/cDU are called.
    if (typeof instance.componentDidUpdate === 'function') {
      if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
        workInProgress.effectTag |= Update;
      }
    }
    if (typeof instance.getSnapshotBeforeUpdate === 'function') {
      if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
        workInProgress.effectTag |= Snapshot;
      }
    }

    // If shouldComponentUpdate returned false, we should still update the
    // memoized props/state to indicate that this work can be reused.
    workInProgress.memoizedProps = newProps;
    workInProgress.memoizedState = newState;
  }

  // Update the existing instance's state, props, and context pointers even
  // if shouldComponentUpdate returns false.
  instance.props = newProps;
  instance.state = newState;
  instance.context = newContext;

  return shouldUpdate;
}

var getCurrentFiberStackAddendum$7 = ReactDebugCurrentFiber.getCurrentFiberStackAddendum;


var didWarnAboutMaps = void 0;
var didWarnAboutStringRefInStrictMode = void 0;
var ownerHasKeyUseWarning = void 0;
var ownerHasFunctionTypeWarning = void 0;
var warnForMissingKey = function (child) {};

{
  didWarnAboutMaps = false;
  didWarnAboutStringRefInStrictMode = {};

  /**
   * Warn if there's no key explicitly set on dynamic arrays of children or
   * object keys are not valid. This allows us to keep track of children between
   * updates.
   */
  ownerHasKeyUseWarning = {};
  ownerHasFunctionTypeWarning = {};

  warnForMissingKey = function (child) {
    if (child === null || typeof child !== 'object') {
      return;
    }
    if (!child._store || child._store.validated || child.key != null) {
      return;
    }
    !(typeof child._store === 'object') ? invariant(false, 'React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue.') : void 0;
    child._store.validated = true;

    var currentComponentErrorInfo = 'Each child in an array or iterator should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.' + (getCurrentFiberStackAddendum$7() || '');
    if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
      return;
    }
    ownerHasKeyUseWarning[currentComponentErrorInfo] = true;

    warning(false, 'Each child in an array or iterator should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.%s', getCurrentFiberStackAddendum$7());
  };
}

var isArray$1 = Array.isArray;

function coerceRef(returnFiber, current, element) {
  var mixedRef = element.ref;
  if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {
    {
      if (returnFiber.mode & StrictMode) {
        var componentName = getComponentName(returnFiber) || 'Component';
        if (!didWarnAboutStringRefInStrictMode[componentName]) {
          warning(false, 'A string ref, "%s", has been found within a strict mode tree. ' + 'String refs are a source of potential bugs and should be avoided. ' + 'We recommend using createRef() instead.' + '\n%s' + '\n\nLearn more about using refs safely here:' + '\nhttps://fb.me/react-strict-mode-string-ref', mixedRef, getStackAddendumByWorkInProgressFiber(returnFiber));
          didWarnAboutStringRefInStrictMode[componentName] = true;
        }
      }
    }

    if (element._owner) {
      var owner = element._owner;
      var inst = void 0;
      if (owner) {
        var ownerFiber = owner;
        !(ownerFiber.tag === ClassComponent) ? invariant(false, 'Stateless function components cannot have refs.') : void 0;
        inst = ownerFiber.stateNode;
      }
      !inst ? invariant(false, 'Missing owner for string ref %s. This error is likely caused by a bug in React. Please file an issue.', mixedRef) : void 0;
      var stringRef = '' + mixedRef;
      // Check if previous string ref matches new string ref
      if (current !== null && current.ref !== null && typeof current.ref === 'function' && current.ref._stringRef === stringRef) {
        return current.ref;
      }
      var ref = function (value) {
        var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs;
        if (value === null) {
          delete refs[stringRef];
        } else {
          refs[stringRef] = value;
        }
      };
      ref._stringRef = stringRef;
      return ref;
    } else {
      !(typeof mixedRef === 'string') ? invariant(false, 'Expected ref to be a function or a string.') : void 0;
      !element._owner ? invariant(false, 'Element ref was specified as a string (%s) but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a functional component\n2. You may be adding a ref to a component that was not created inside a component\'s render method\n3. You have multiple copies of React loaded\nSee https://fb.me/react-refs-must-have-owner for more information.', mixedRef) : void 0;
    }
  }
  return mixedRef;
}

function throwOnInvalidObjectType(returnFiber, newChild) {
  if (returnFiber.type !== 'textarea') {
    var addendum = '';
    {
      addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + (getCurrentFiberStackAddendum$7() || '');
    }
    invariant(false, 'Objects are not valid as a React child (found: %s).%s', Object.prototype.toString.call(newChild) === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : newChild, addendum);
  }
}

function warnOnFunctionType() {
  var currentComponentErrorInfo = 'Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.' + (getCurrentFiberStackAddendum$7() || '');

  if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) {
    return;
  }
  ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true;

  warning(false, 'Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.%s', getCurrentFiberStackAddendum$7() || '');
}

// This wrapper function exists because I expect to clone the code in each path
// to be able to optimize each path individually by branching early. This needs
// a compiler or we can do it manually. Helpers that don't need this branching
// live outside of this function.
function ChildReconciler(shouldTrackSideEffects) {
  function deleteChild(returnFiber, childToDelete) {
    if (!shouldTrackSideEffects) {
      // Noop.
      return;
    }
    // Deletions are added in reversed order so we add it to the front.
    // At this point, the return fiber's effect list is empty except for
    // deletions, so we can just append the deletion to the list. The remaining
    // effects aren't added until the complete phase. Once we implement
    // resuming, this may not be true.
    var last = returnFiber.lastEffect;
    if (last !== null) {
      last.nextEffect = childToDelete;
      returnFiber.lastEffect = childToDelete;
    } else {
      returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
    }
    childToDelete.nextEffect = null;
    childToDelete.effectTag = Deletion;
  }

  function deleteRemainingChildren(returnFiber, currentFirstChild) {
    if (!shouldTrackSideEffects) {
      // Noop.
      return null;
    }

    // TODO: For the shouldClone case, this could be micro-optimized a bit by
    // assuming that after the first child we've already added everything.
    var childToDelete = currentFirstChild;
    while (childToDelete !== null) {
      deleteChild(returnFiber, childToDelete);
      childToDelete = childToDelete.sibling;
    }
    return null;
  }

  function mapRemainingChildren(returnFiber, currentFirstChild) {
    // Add the remaining children to a temporary map so that we can find them by
    // keys quickly. Implicit (null) keys get added to this set with their index
    var existingChildren = new Map();

    var existingChild = currentFirstChild;
    while (existingChild !== null) {
      if (existingChild.key !== null) {
        existingChildren.set(existingChild.key, existingChild);
      } else {
        existingChildren.set(existingChild.index, existingChild);
      }
      existingChild = existingChild.sibling;
    }
    return existingChildren;
  }

  function useFiber(fiber, pendingProps, expirationTime) {
    // We currently set sibling to null and index to 0 here because it is easy
    // to forget to do before returning it. E.g. for the single child case.
    var clone = createWorkInProgress(fiber, pendingProps, expirationTime);
    clone.index = 0;
    clone.sibling = null;
    return clone;
  }

  function placeChild(newFiber, lastPlacedIndex, newIndex) {
    newFiber.index = newIndex;
    if (!shouldTrackSideEffects) {
      // Noop.
      return lastPlacedIndex;
    }
    var current = newFiber.alternate;
    if (current !== null) {
      var oldIndex = current.index;
      if (oldIndex < lastPlacedIndex) {
        // This is a move.
        newFiber.effectTag = Placement;
        return lastPlacedIndex;
      } else {
        // This item can stay in place.
        return oldIndex;
      }
    } else {
      // This is an insertion.
      newFiber.effectTag = Placement;
      return lastPlacedIndex;
    }
  }

  function placeSingleChild(newFiber) {
    // This is simpler for the single child case. We only need to do a
    // placement for inserting new children.
    if (shouldTrackSideEffects && newFiber.alternate === null) {
      newFiber.effectTag = Placement;
    }
    return newFiber;
  }

  function updateTextNode(returnFiber, current, textContent, expirationTime) {
    if (current === null || current.tag !== HostText) {
      // Insert
      var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
      created.return = returnFiber;
      return created;
    } else {
      // Update
      var existing = useFiber(current, textContent, expirationTime);
      existing.return = returnFiber;
      return existing;
    }
  }

  function updateElement(returnFiber, current, element, expirationTime) {
    if (current !== null && current.type === element.type) {
      // Move based on index
      var existing = useFiber(current, element.props, expirationTime);
      existing.ref = coerceRef(returnFiber, current, element);
      existing.return = returnFiber;
      {
        existing._debugSource = element._source;
        existing._debugOwner = element._owner;
      }
      return existing;
    } else {
      // Insert
      var created = createFiberFromElement(element, returnFiber.mode, expirationTime);
      created.ref = coerceRef(returnFiber, current, element);
      created.return = returnFiber;
      return created;
    }
  }

  function updatePortal(returnFiber, current, portal, expirationTime) {
    if (current === null || current.tag !== HostPortal || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation) {
      // Insert
      var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
      created.return = returnFiber;
      return created;
    } else {
      // Update
      var existing = useFiber(current, portal.children || [], expirationTime);
      existing.return = returnFiber;
      return existing;
    }
  }

  function updateFragment(returnFiber, current, fragment, expirationTime, key) {
    if (current === null || current.tag !== Fragment) {
      // Insert
      var created = createFiberFromFragment(fragment, returnFiber.mode, expirationTime, key);
      created.return = returnFiber;
      return created;
    } else {
      // Update
      var existing = useFiber(current, fragment, expirationTime);
      existing.return = returnFiber;
      return existing;
    }
  }

  function createChild(returnFiber, newChild, expirationTime) {
    if (typeof newChild === 'string' || typeof newChild === 'number') {
      // Text nodes don't have keys. If the previous node is implicitly keyed
      // we can continue to replace it without aborting even if it is not a text
      // node.
      var created = createFiberFromText('' + newChild, returnFiber.mode, expirationTime);
      created.return = returnFiber;
      return created;
    }

    if (typeof newChild === 'object' && newChild !== null) {
      switch (newChild.$$typeof) {
        case REACT_ELEMENT_TYPE:
          {
            var _created = createFiberFromElement(newChild, returnFiber.mode, expirationTime);
            _created.ref = coerceRef(returnFiber, null, newChild);
            _created.return = returnFiber;
            return _created;
          }
        case REACT_PORTAL_TYPE:
          {
            var _created2 = createFiberFromPortal(newChild, returnFiber.mode, expirationTime);
            _created2.return = returnFiber;
            return _created2;
          }
      }

      if (isArray$1(newChild) || getIteratorFn(newChild)) {
        var _created3 = createFiberFromFragment(newChild, returnFiber.mode, expirationTime, null);
        _created3.return = returnFiber;
        return _created3;
      }

      throwOnInvalidObjectType(returnFiber, newChild);
    }

    {
      if (typeof newChild === 'function') {
        warnOnFunctionType();
      }
    }

    return null;
  }

  function updateSlot(returnFiber, oldFiber, newChild, expirationTime) {
    // Update the fiber if the keys match, otherwise return null.

    var key = oldFiber !== null ? oldFiber.key : null;

    if (typeof newChild === 'string' || typeof newChild === 'number') {
      // Text nodes don't have keys. If the previous node is implicitly keyed
      // we can continue to replace it without aborting even if it is not a text
      // node.
      if (key !== null) {
        return null;
      }
      return updateTextNode(returnFiber, oldFiber, '' + newChild, expirationTime);
    }

    if (typeof newChild === 'object' && newChild !== null) {
      switch (newChild.$$typeof) {
        case REACT_ELEMENT_TYPE:
          {
            if (newChild.key === key) {
              if (newChild.type === REACT_FRAGMENT_TYPE) {
                return updateFragment(returnFiber, oldFiber, newChild.props.children, expirationTime, key);
              }
              return updateElement(returnFiber, oldFiber, newChild, expirationTime);
            } else {
              return null;
            }
          }
        case REACT_PORTAL_TYPE:
          {
            if (newChild.key === key) {
              return updatePortal(returnFiber, oldFiber, newChild, expirationTime);
            } else {
              return null;
            }
          }
      }

      if (isArray$1(newChild) || getIteratorFn(newChild)) {
        if (key !== null) {
          return null;
        }

        return updateFragment(returnFiber, oldFiber, newChild, expirationTime, null);
      }

      throwOnInvalidObjectType(returnFiber, newChild);
    }

    {
      if (typeof newChild === 'function') {
        warnOnFunctionType();
      }
    }

    return null;
  }

  function updateFromMap(existingChildren, returnFiber, newIdx, newChild, expirationTime) {
    if (typeof newChild === 'string' || typeof newChild === 'number') {
      // Text nodes don't have keys, so we neither have to check the old nor
      // new node for the key. If both are text nodes, they match.
      var matchedFiber = existingChildren.get(newIdx) || null;
      return updateTextNode(returnFiber, matchedFiber, '' + newChild, expirationTime);
    }

    if (typeof newChild === 'object' && newChild !== null) {
      switch (newChild.$$typeof) {
        case REACT_ELEMENT_TYPE:
          {
            var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
            if (newChild.type === REACT_FRAGMENT_TYPE) {
              return updateFragment(returnFiber, _matchedFiber, newChild.props.children, expirationTime, newChild.key);
            }
            return updateElement(returnFiber, _matchedFiber, newChild, expirationTime);
          }
        case REACT_PORTAL_TYPE:
          {
            var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
            return updatePortal(returnFiber, _matchedFiber2, newChild, expirationTime);
          }
      }

      if (isArray$1(newChild) || getIteratorFn(newChild)) {
        var _matchedFiber3 = existingChildren.get(newIdx) || null;
        return updateFragment(returnFiber, _matchedFiber3, newChild, expirationTime, null);
      }

      throwOnInvalidObjectType(returnFiber, newChild);
    }

    {
      if (typeof newChild === 'function') {
        warnOnFunctionType();
      }
    }

    return null;
  }

  /**
   * Warns if there is a duplicate or missing key
   */
  function warnOnInvalidKey(child, knownKeys) {
    {
      if (typeof child !== 'object' || child === null) {
        return knownKeys;
      }
      switch (child.$$typeof) {
        case REACT_ELEMENT_TYPE:
        case REACT_PORTAL_TYPE:
          warnForMissingKey(child);
          var key = child.key;
          if (typeof key !== 'string') {
            break;
          }
          if (knownKeys === null) {
            knownKeys = new Set();
            knownKeys.add(key);
            break;
          }
          if (!knownKeys.has(key)) {
            knownKeys.add(key);
            break;
          }
          warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$7());
          break;
        default:
          break;
      }
    }
    return knownKeys;
  }

  function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, expirationTime) {
    // This algorithm can't optimize by searching from boths ends since we
    // don't have backpointers on fibers. I'm trying to see how far we can get
    // with that model. If it ends up not being worth the tradeoffs, we can
    // add it later.

    // Even with a two ended optimization, we'd want to optimize for the case
    // where there are few changes and brute force the comparison instead of
    // going for the Map. It'd like to explore hitting that path first in
    // forward-only mode and only go for the Map once we notice that we need
    // lots of look ahead. This doesn't handle reversal as well as two ended
    // search but that's unusual. Besides, for the two ended optimization to
    // work on Iterables, we'd need to copy the whole set.

    // In this first iteration, we'll just live with hitting the bad case
    // (adding everything to a Map) in for every insert/move.

    // If you change this code, also update reconcileChildrenIterator() which
    // uses the same algorithm.

    {
      // First, validate keys.
      var knownKeys = null;
      for (var i = 0; i < newChildren.length; i++) {
        var child = newChildren[i];
        knownKeys = warnOnInvalidKey(child, knownKeys);
      }
    }

    var resultingFirstChild = null;
    var previousNewFiber = null;

    var oldFiber = currentFirstChild;
    var lastPlacedIndex = 0;
    var newIdx = 0;
    var nextOldFiber = null;
    for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
      if (oldFiber.index > newIdx) {
        nextOldFiber = oldFiber;
        oldFiber = null;
      } else {
        nextOldFiber = oldFiber.sibling;
      }
      var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], expirationTime);
      if (newFiber === null) {
        // TODO: This breaks on empty slots like null children. That's
        // unfortunate because it triggers the slow path all the time. We need
        // a better way to communicate whether this was a miss or null,
        // boolean, undefined, etc.
        if (oldFiber === null) {
          oldFiber = nextOldFiber;
        }
        break;
      }
      if (shouldTrackSideEffects) {
        if (oldFiber && newFiber.alternate === null) {
          // We matched the slot, but we didn't reuse the existing fiber, so we
          // need to delete the existing child.
          deleteChild(returnFiber, oldFiber);
        }
      }
      lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
      if (previousNewFiber === null) {
        // TODO: Move out of the loop. This only happens for the first run.
        resultingFirstChild = newFiber;
      } else {
        // TODO: Defer siblings if we're not at the right index for this slot.
        // I.e. if we had null values before, then we want to defer this
        // for each null value. However, we also don't want to call updateSlot
        // with the previous one.
        previousNewFiber.sibling = newFiber;
      }
      previousNewFiber = newFiber;
      oldFiber = nextOldFiber;
    }

    if (newIdx === newChildren.length) {
      // We've reached the end of the new children. We can delete the rest.
      deleteRemainingChildren(returnFiber, oldFiber);
      return resultingFirstChild;
    }

    if (oldFiber === null) {
      // If we don't have any more existing children we can choose a fast path
      // since the rest will all be insertions.
      for (; newIdx < newChildren.length; newIdx++) {
        var _newFiber = createChild(returnFiber, newChildren[newIdx], expirationTime);
        if (!_newFiber) {
          continue;
        }
        lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);
        if (previousNewFiber === null) {
          // TODO: Move out of the loop. This only happens for the first run.
          resultingFirstChild = _newFiber;
        } else {
          previousNewFiber.sibling = _newFiber;
        }
        previousNewFiber = _newFiber;
      }
      return resultingFirstChild;
    }

    // Add all children to a key map for quick lookups.
    var existingChildren = mapRemainingChildren(returnFiber, oldFiber);

    // Keep scanning and use the map to restore deleted items as moves.
    for (; newIdx < newChildren.length; newIdx++) {
      var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], expirationTime);
      if (_newFiber2) {
        if (shouldTrackSideEffects) {
          if (_newFiber2.alternate !== null) {
            // The new fiber is a work in progress, but if there exists a
            // current, that means that we reused the fiber. We need to delete
            // it from the child list so that we don't add it to the deletion
            // list.
            existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
          }
        }
        lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);
        if (previousNewFiber === null) {
          resultingFirstChild = _newFiber2;
        } else {
          previousNewFiber.sibling = _newFiber2;
        }
        previousNewFiber = _newFiber2;
      }
    }

    if (shouldTrackSideEffects) {
      // Any existing children that weren't consumed above were deleted. We need
      // to add them to the deletion list.
      existingChildren.forEach(function (child) {
        return deleteChild(returnFiber, child);
      });
    }

    return resultingFirstChild;
  }

  function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, expirationTime) {
    // This is the same implementation as reconcileChildrenArray(),
    // but using the iterator instead.

    var iteratorFn = getIteratorFn(newChildrenIterable);
    !(typeof iteratorFn === 'function') ? invariant(false, 'An object is not an iterable. This error is likely caused by a bug in React. Please file an issue.') : void 0;

    {
      // Warn about using Maps as children
      if (newChildrenIterable.entries === iteratorFn) {
        !didWarnAboutMaps ? warning(false, 'Using Maps as children is unsupported and will likely yield ' + 'unexpected results. Convert it to a sequence/iterable of keyed ' + 'ReactElements instead.%s', getCurrentFiberStackAddendum$7()) : void 0;
        didWarnAboutMaps = true;
      }

      // First, validate keys.
      // We'll get a different iterator later for the main pass.
      var _newChildren = iteratorFn.call(newChildrenIterable);
      if (_newChildren) {
        var knownKeys = null;
        var _step = _newChildren.next();
        for (; !_step.done; _step = _newChildren.next()) {
          var child = _step.value;
          knownKeys = warnOnInvalidKey(child, knownKeys);
        }
      }
    }

    var newChildren = iteratorFn.call(newChildrenIterable);
    !(newChildren != null) ? invariant(false, 'An iterable object provided no iterator.') : void 0;

    var resultingFirstChild = null;
    var previousNewFiber = null;

    var oldFiber = currentFirstChild;
    var lastPlacedIndex = 0;
    var newIdx = 0;
    var nextOldFiber = null;

    var step = newChildren.next();
    for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
      if (oldFiber.index > newIdx) {
        nextOldFiber = oldFiber;
        oldFiber = null;
      } else {
        nextOldFiber = oldFiber.sibling;
      }
      var newFiber = updateSlot(returnFiber, oldFiber, step.value, expirationTime);
      if (newFiber === null) {
        // TODO: This breaks on empty slots like null children. That's
        // unfortunate because it triggers the slow path all the time. We need
        // a better way to communicate whether this was a miss or null,
        // boolean, undefined, etc.
        if (!oldFiber) {
          oldFiber = nextOldFiber;
        }
        break;
      }
      if (shouldTrackSideEffects) {
        if (oldFiber && newFiber.alternate === null) {
          // We matched the slot, but we didn't reuse the existing fiber, so we
          // need to delete the existing child.
          deleteChild(returnFiber, oldFiber);
        }
      }
      lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
      if (previousNewFiber === null) {
        // TODO: Move out of the loop. This only happens for the first run.
        resultingFirstChild = newFiber;
      } else {
        // TODO: Defer siblings if we're not at the right index for this slot.
        // I.e. if we had null values before, then we want to defer this
        // for each null value. However, we also don't want to call updateSlot
        // with the previous one.
        previousNewFiber.sibling = newFiber;
      }
      previousNewFiber = newFiber;
      oldFiber = nextOldFiber;
    }

    if (step.done) {
      // We've reached the end of the new children. We can delete the rest.
      deleteRemainingChildren(returnFiber, oldFiber);
      return resultingFirstChild;
    }

    if (oldFiber === null) {
      // If we don't have any more existing children we can choose a fast path
      // since the rest will all be insertions.
      for (; !step.done; newIdx++, step = newChildren.next()) {
        var _newFiber3 = createChild(returnFiber, step.value, expirationTime);
        if (_newFiber3 === null) {
          continue;
        }
        lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);
        if (previousNewFiber === null) {
          // TODO: Move out of the loop. This only happens for the first run.
          resultingFirstChild = _newFiber3;
        } else {
          previousNewFiber.sibling = _newFiber3;
        }
        previousNewFiber = _newFiber3;
      }
      return resultingFirstChild;
    }

    // Add all children to a key map for quick lookups.
    var existingChildren = mapRemainingChildren(returnFiber, oldFiber);

    // Keep scanning and use the map to restore deleted items as moves.
    for (; !step.done; newIdx++, step = newChildren.next()) {
      var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, expirationTime);
      if (_newFiber4 !== null) {
        if (shouldTrackSideEffects) {
          if (_newFiber4.alternate !== null) {
            // The new fiber is a work in progress, but if there exists a
            // current, that means that we reused the fiber. We need to delete
            // it from the child list so that we don't add it to the deletion
            // list.
            existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
          }
        }
        lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);
        if (previousNewFiber === null) {
          resultingFirstChild = _newFiber4;
        } else {
          previousNewFiber.sibling = _newFiber4;
        }
        previousNewFiber = _newFiber4;
      }
    }

    if (shouldTrackSideEffects) {
      // Any existing children that weren't consumed above were deleted. We need
      // to add them to the deletion list.
      existingChildren.forEach(function (child) {
        return deleteChild(returnFiber, child);
      });
    }

    return resultingFirstChild;
  }

  function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, expirationTime) {
    // There's no need to check for keys on text nodes since we don't have a
    // way to define them.
    if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
      // We already have an existing node so let's just update it and delete
      // the rest.
      deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
      var existing = useFiber(currentFirstChild, textContent, expirationTime);
      existing.return = returnFiber;
      return existing;
    }
    // The existing first child is not a text node so we need to create one
    // and delete the existing ones.
    deleteRemainingChildren(returnFiber, currentFirstChild);
    var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
    created.return = returnFiber;
    return created;
  }

  function reconcileSingleElement(returnFiber, currentFirstChild, element, expirationTime) {
    var key = element.key;
    var child = currentFirstChild;
    while (child !== null) {
      // TODO: If key === null and child.key === null, then this only applies to
      // the first item in the list.
      if (child.key === key) {
        if (child.tag === Fragment ? element.type === REACT_FRAGMENT_TYPE : child.type === element.type) {
          deleteRemainingChildren(returnFiber, child.sibling);
          var existing = useFiber(child, element.type === REACT_FRAGMENT_TYPE ? element.props.children : element.props, expirationTime);
          existing.ref = coerceRef(returnFiber, child, element);
          existing.return = returnFiber;
          {
            existing._debugSource = element._source;
            existing._debugOwner = element._owner;
          }
          return existing;
        } else {
          deleteRemainingChildren(returnFiber, child);
          break;
        }
      } else {
        deleteChild(returnFiber, child);
      }
      child = child.sibling;
    }

    if (element.type === REACT_FRAGMENT_TYPE) {
      var created = createFiberFromFragment(element.props.children, returnFiber.mode, expirationTime, element.key);
      created.return = returnFiber;
      return created;
    } else {
      var _created4 = createFiberFromElement(element, returnFiber.mode, expirationTime);
      _created4.ref = coerceRef(returnFiber, currentFirstChild, element);
      _created4.return = returnFiber;
      return _created4;
    }
  }

  function reconcileSinglePortal(returnFiber, currentFirstChild, portal, expirationTime) {
    var key = portal.key;
    var child = currentFirstChild;
    while (child !== null) {
      // TODO: If key === null and child.key === null, then this only applies to
      // the first item in the list.
      if (child.key === key) {
        if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
          deleteRemainingChildren(returnFiber, child.sibling);
          var existing = useFiber(child, portal.children || [], expirationTime);
          existing.return = returnFiber;
          return existing;
        } else {
          deleteRemainingChildren(returnFiber, child);
          break;
        }
      } else {
        deleteChild(returnFiber, child);
      }
      child = child.sibling;
    }

    var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
    created.return = returnFiber;
    return created;
  }

  // This API will tag the children with the side-effect of the reconciliation
  // itself. They will be added to the side-effect list as we pass through the
  // children and the parent.
  function reconcileChildFibers(returnFiber, currentFirstChild, newChild, expirationTime) {
    // This function is not recursive.
    // If the top level item is an array, we treat it as a set of children,
    // not as a fragment. Nested arrays on the other hand will be treated as
    // fragment nodes. Recursion happens at the normal flow.

    // Handle top level unkeyed fragments as if they were arrays.
    // This leads to an ambiguity between <>{[...]}</> and <>...</>.
    // We treat the ambiguous cases above the same.
    var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;
    if (isUnkeyedTopLevelFragment) {
      newChild = newChild.props.children;
    }

    // Handle object types
    var isObject = typeof newChild === 'object' && newChild !== null;

    if (isObject) {
      switch (newChild.$$typeof) {
        case REACT_ELEMENT_TYPE:
          return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, expirationTime));
        case REACT_PORTAL_TYPE:
          return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, expirationTime));
      }
    }

    if (typeof newChild === 'string' || typeof newChild === 'number') {
      return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, expirationTime));
    }

    if (isArray$1(newChild)) {
      return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, expirationTime);
    }

    if (getIteratorFn(newChild)) {
      return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, expirationTime);
    }

    if (isObject) {
      throwOnInvalidObjectType(returnFiber, newChild);
    }

    {
      if (typeof newChild === 'function') {
        warnOnFunctionType();
      }
    }
    if (typeof newChild === 'undefined' && !isUnkeyedTopLevelFragment) {
      // If the new child is undefined, and the return fiber is a composite
      // component, throw an error. If Fiber return types are disabled,
      // we already threw above.
      switch (returnFiber.tag) {
        case ClassComponent:
          {
            {
              var instance = returnFiber.stateNode;
              if (instance.render._isMockFunction) {
                // We allow auto-mocks to proceed as if they're returning null.
                break;
              }
            }
          }
        // Intentionally fall through to the next case, which handles both
        // functions and classes
        // eslint-disable-next-lined no-fallthrough
        case FunctionalComponent:
          {
            var Component = returnFiber.type;
            invariant(false, '%s(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.', Component.displayName || Component.name || 'Component');
          }
      }
    }

    // Remaining cases are all treated as empty.
    return deleteRemainingChildren(returnFiber, currentFirstChild);
  }

  return reconcileChildFibers;
}

var reconcileChildFibers = ChildReconciler(true);
var mountChildFibers = ChildReconciler(false);

function cloneChildFibers(current, workInProgress) {
  !(current === null || workInProgress.child === current.child) ? invariant(false, 'Resuming work not yet implemented.') : void 0;

  if (workInProgress.child === null) {
    return;
  }

  var currentChild = workInProgress.child;
  var newChild = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
  workInProgress.child = newChild;

  newChild.return = workInProgress;
  while (currentChild.sibling !== null) {
    currentChild = currentChild.sibling;
    newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
    newChild.return = workInProgress;
  }
  newChild.sibling = null;
}

// The deepest Fiber on the stack involved in a hydration context.
// This may have been an insertion or a hydration.
var hydrationParentFiber = null;
var nextHydratableInstance = null;
var isHydrating = false;

function enterHydrationState(fiber) {
  if (!supportsHydration) {
    return false;
  }

  var parentInstance = fiber.stateNode.containerInfo;
  nextHydratableInstance = getFirstHydratableChild(parentInstance);
  hydrationParentFiber = fiber;
  isHydrating = true;
  return true;
}

function deleteHydratableInstance(returnFiber, instance) {
  {
    switch (returnFiber.tag) {
      case HostRoot:
        didNotHydrateContainerInstance(returnFiber.stateNode.containerInfo, instance);
        break;
      case HostComponent:
        didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance);
        break;
    }
  }

  var childToDelete = createFiberFromHostInstanceForDeletion();
  childToDelete.stateNode = instance;
  childToDelete.return = returnFiber;
  childToDelete.effectTag = Deletion;

  // This might seem like it belongs on progressedFirstDeletion. However,
  // these children are not part of the reconciliation list of children.
  // Even if we abort and rereconcile the children, that will try to hydrate
  // again and the nodes are still in the host tree so these will be
  // recreated.
  if (returnFiber.lastEffect !== null) {
    returnFiber.lastEffect.nextEffect = childToDelete;
    returnFiber.lastEffect = childToDelete;
  } else {
    returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
  }
}

function insertNonHydratedInstance(returnFiber, fiber) {
  fiber.effectTag |= Placement;
  {
    switch (returnFiber.tag) {
      case HostRoot:
        {
          var parentContainer = returnFiber.stateNode.containerInfo;
          switch (fiber.tag) {
            case HostComponent:
              var type = fiber.type;
              var props = fiber.pendingProps;
              didNotFindHydratableContainerInstance(parentContainer, type, props);
              break;
            case HostText:
              var text = fiber.pendingProps;
              didNotFindHydratableContainerTextInstance(parentContainer, text);
              break;
          }
          break;
        }
      case HostComponent:
        {
          var parentType = returnFiber.type;
          var parentProps = returnFiber.memoizedProps;
          var parentInstance = returnFiber.stateNode;
          switch (fiber.tag) {
            case HostComponent:
              var _type = fiber.type;
              var _props = fiber.pendingProps;
              didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props);
              break;
            case HostText:
              var _text = fiber.pendingProps;
              didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text);
              break;
          }
          break;
        }
      default:
        return;
    }
  }
}

function tryHydrate(fiber, nextInstance) {
  switch (fiber.tag) {
    case HostComponent:
      {
        var type = fiber.type;
        var props = fiber.pendingProps;
        var instance = canHydrateInstance(nextInstance, type, props);
        if (instance !== null) {
          fiber.stateNode = instance;
          return true;
        }
        return false;
      }
    case HostText:
      {
        var text = fiber.pendingProps;
        var textInstance = canHydrateTextInstance(nextInstance, text);
        if (textInstance !== null) {
          fiber.stateNode = textInstance;
          return true;
        }
        return false;
      }
    default:
      return false;
  }
}

function tryToClaimNextHydratableInstance(fiber) {
  if (!isHydrating) {
    return;
  }
  var nextInstance = nextHydratableInstance;
  if (!nextInstance) {
    // Nothing to hydrate. Make it an insertion.
    insertNonHydratedInstance(hydrationParentFiber, fiber);
    isHydrating = false;
    hydrationParentFiber = fiber;
    return;
  }
  var firstAttemptedInstance = nextInstance;
  if (!tryHydrate(fiber, nextInstance)) {
    // If we can't hydrate this instance let's try the next one.
    // We use this as a heuristic. It's based on intuition and not data so it
    // might be flawed or unnecessary.
    nextInstance = getNextHydratableSibling(firstAttemptedInstance);
    if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
      // Nothing to hydrate. Make it an insertion.
      insertNonHydratedInstance(hydrationParentFiber, fiber);
      isHydrating = false;
      hydrationParentFiber = fiber;
      return;
    }
    // We matched the next one, we'll now assume that the first one was
    // superfluous and we'll delete it. Since we can't eagerly delete it
    // we'll have to schedule a deletion. To do that, this node needs a dummy
    // fiber associated with it.
    deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance);
  }
  hydrationParentFiber = fiber;
  nextHydratableInstance = getFirstHydratableChild(nextInstance);
}

function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {
  if (!supportsHydration) {
    invariant(false, 'Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
  }

  var instance = fiber.stateNode;
  var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber);
  // TODO: Type this specific to this type of component.
  fiber.updateQueue = updatePayload;
  // If the update payload indicates that there is a change or if there
  // is a new ref we mark this as an update.
  if (updatePayload !== null) {
    return true;
  }
  return false;
}

function prepareToHydrateHostTextInstance(fiber) {
  if (!supportsHydration) {
    invariant(false, 'Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
  }

  var textInstance = fiber.stateNode;
  var textContent = fiber.memoizedProps;
  var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);
  {
    if (shouldUpdate) {
      // We assume that prepareToHydrateHostTextInstance is called in a context where the
      // hydration parent is the parent host component of this host text.
      var returnFiber = hydrationParentFiber;
      if (returnFiber !== null) {
        switch (returnFiber.tag) {
          case HostRoot:
            {
              var parentContainer = returnFiber.stateNode.containerInfo;
              didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent);
              break;
            }
          case HostComponent:
            {
              var parentType = returnFiber.type;
              var parentProps = returnFiber.memoizedProps;
              var parentInstance = returnFiber.stateNode;
              didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent);
              break;
            }
        }
      }
    }
  }
  return shouldUpdate;
}

function popToNextHostParent(fiber) {
  var parent = fiber.return;
  while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot) {
    parent = parent.return;
  }
  hydrationParentFiber = parent;
}

function popHydrationState(fiber) {
  if (!supportsHydration) {
    return false;
  }
  if (fiber !== hydrationParentFiber) {
    // We're deeper than the current hydration context, inside an inserted
    // tree.
    return false;
  }
  if (!isHydrating) {
    // If we're not currently hydrating but we're in a hydration context, then
    // we were an insertion and now need to pop up reenter hydration of our
    // siblings.
    popToNextHostParent(fiber);
    isHydrating = true;
    return false;
  }

  var type = fiber.type;

  // If we have any remaining hydratable nodes, we need to delete them now.
  // We only do this deeper than head and body since they tend to have random
  // other nodes in them. We also ignore components with pure text content in
  // side of them.
  // TODO: Better heuristic.
  if (fiber.tag !== HostComponent || type !== 'head' && type !== 'body' && !shouldSetTextContent(type, fiber.memoizedProps)) {
    var nextInstance = nextHydratableInstance;
    while (nextInstance) {
      deleteHydratableInstance(fiber, nextInstance);
      nextInstance = getNextHydratableSibling(nextInstance);
    }
  }

  popToNextHostParent(fiber);
  nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
  return true;
}

function resetHydrationState() {
  if (!supportsHydration) {
    return;
  }

  hydrationParentFiber = null;
  nextHydratableInstance = null;
  isHydrating = false;
}

var getCurrentFiberStackAddendum$6 = ReactDebugCurrentFiber.getCurrentFiberStackAddendum;


var didWarnAboutBadClass = void 0;
var didWarnAboutGetDerivedStateOnFunctionalComponent = void 0;
var didWarnAboutStatelessRefs = void 0;

{
  didWarnAboutBadClass = {};
  didWarnAboutGetDerivedStateOnFunctionalComponent = {};
  didWarnAboutStatelessRefs = {};
}

// TODO: Remove this and use reconcileChildrenAtExpirationTime directly.
function reconcileChildren(current, workInProgress, nextChildren) {
  reconcileChildrenAtExpirationTime(current, workInProgress, nextChildren, workInProgress.expirationTime);
}

function reconcileChildrenAtExpirationTime(current, workInProgress, nextChildren, renderExpirationTime) {
  if (current === null) {
    // If this is a fresh new component that hasn't been rendered yet, we
    // won't update its child set by applying minimal side-effects. Instead,
    // we will add them all to the child before it gets rendered. That means
    // we can optimize this reconciliation pass by not tracking side-effects.
    workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
  } else {
    // If the current child is the same as the work in progress, it means that
    // we haven't yet started any work on these children. Therefore, we use
    // the clone algorithm to create a copy of all the current children.

    // If we had any progressed work already, that is invalid at this point so
    // let's throw it out.
    workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren, renderExpirationTime);
  }
}

function updateForwardRef(current, workInProgress) {
  var render = workInProgress.type.render;
  var nextProps = workInProgress.pendingProps;
  var ref = workInProgress.ref;
  if (hasContextChanged()) {
    // Normally we can bail out on props equality but if context has changed
    // we don't do the bailout and we have to reuse existing props instead.
  } else if (workInProgress.memoizedProps === nextProps) {
    var currentRef = current !== null ? current.ref : null;
    if (ref === currentRef) {
      return bailoutOnAlreadyFinishedWork(current, workInProgress);
    }
  }

  var nextChildren = void 0;
  {
    ReactCurrentOwner.current = workInProgress;
    ReactDebugCurrentFiber.setCurrentPhase('render');
    nextChildren = render(nextProps, ref);
    ReactDebugCurrentFiber.setCurrentPhase(null);
  }

  reconcileChildren(current, workInProgress, nextChildren);
  memoizeProps(workInProgress, nextProps);
  return workInProgress.child;
}

function updateFragment(current, workInProgress) {
  var nextChildren = workInProgress.pendingProps;
  if (hasContextChanged()) {
    // Normally we can bail out on props equality but if context has changed
    // we don't do the bailout and we have to reuse existing props instead.
  } else if (workInProgress.memoizedProps === nextChildren) {
    return bailoutOnAlreadyFinishedWork(current, workInProgress);
  }
  reconcileChildren(current, workInProgress, nextChildren);
  memoizeProps(workInProgress, nextChildren);
  return workInProgress.child;
}

function updateMode(current, workInProgress) {
  var nextChildren = workInProgress.pendingProps.children;
  if (hasContextChanged()) {
    // Normally we can bail out on props equality but if context has changed
    // we don't do the bailout and we have to reuse existing props instead.
  } else if (nextChildren === null || workInProgress.memoizedProps === nextChildren) {
    return bailoutOnAlreadyFinishedWork(current, workInProgress);
  }
  reconcileChildren(current, workInProgress, nextChildren);
  memoizeProps(workInProgress, nextChildren);
  return workInProgress.child;
}

function updateProfiler(current, workInProgress) {
  var nextProps = workInProgress.pendingProps;
  if (enableProfilerTimer) {
    workInProgress.effectTag |= Update;
  }
  if (workInProgress.memoizedProps === nextProps) {
    return bailoutOnAlreadyFinishedWork(current, workInProgress);
  }
  var nextChildren = nextProps.children;
  reconcileChildren(current, workInProgress, nextChildren);
  memoizeProps(workInProgress, nextProps);
  return workInProgress.child;
}

function markRef(current, workInProgress) {
  var ref = workInProgress.ref;
  if (current === null && ref !== null || current !== null && current.ref !== ref) {
    // Schedule a Ref effect
    workInProgress.effectTag |= Ref;
  }
}

function updateFunctionalComponent(current, workInProgress) {
  var fn = workInProgress.type;
  var nextProps = workInProgress.pendingProps;

  if (hasContextChanged()) {
    // Normally we can bail out on props equality but if context has changed
    // we don't do the bailout and we have to reuse existing props instead.
  } else {
    if (workInProgress.memoizedProps === nextProps) {
      return bailoutOnAlreadyFinishedWork(current, workInProgress);
    }
    // TODO: consider bringing fn.shouldComponentUpdate() back.
    // It used to be here.
  }

  var unmaskedContext = getUnmaskedContext(workInProgress);
  var context = getMaskedContext(workInProgress, unmaskedContext);

  var nextChildren = void 0;

  {
    ReactCurrentOwner.current = workInProgress;
    ReactDebugCurrentFiber.setCurrentPhase('render');
    nextChildren = fn(nextProps, context);
    ReactDebugCurrentFiber.setCurrentPhase(null);
  }
  // React DevTools reads this flag.
  workInProgress.effectTag |= PerformedWork;
  reconcileChildren(current, workInProgress, nextChildren);
  memoizeProps(workInProgress, nextProps);
  return workInProgress.child;
}

function updateClassComponent(current, workInProgress, renderExpirationTime) {
  // Push context providers early to prevent context stack mismatches.
  // During mounting we don't know the child context yet as the instance doesn't exist.
  // We will invalidate the child context in finishClassComponent() right after rendering.
  var hasContext = pushContextProvider(workInProgress);
  var shouldUpdate = void 0;
  if (current === null) {
    if (workInProgress.stateNode === null) {
      // In the initial pass we might need to construct the instance.
      constructClassInstance(workInProgress, workInProgress.pendingProps, renderExpirationTime);
      mountClassInstance(workInProgress, renderExpirationTime);

      shouldUpdate = true;
    } else {
      // In a resume, we'll already have an instance we can reuse.
      shouldUpdate = resumeMountClassInstance(workInProgress, renderExpirationTime);
    }
  } else {
    shouldUpdate = updateClassInstance(current, workInProgress, renderExpirationTime);
  }
  return finishClassComponent(current, workInProgress, shouldUpdate, hasContext, renderExpirationTime);
}

function finishClassComponent(current, workInProgress, shouldUpdate, hasContext, renderExpirationTime) {
  // Refs should update even if shouldComponentUpdate returns false
  markRef(current, workInProgress);

  var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect;

  if (!shouldUpdate && !didCaptureError) {
    // Context providers should defer to sCU for rendering
    if (hasContext) {
      invalidateContextProvider(workInProgress, false);
    }

    return bailoutOnAlreadyFinishedWork(current, workInProgress);
  }

  var ctor = workInProgress.type;
  var instance = workInProgress.stateNode;

  // Rerender
  ReactCurrentOwner.current = workInProgress;
  var nextChildren = void 0;
  if (didCaptureError && (!enableGetDerivedStateFromCatch || typeof ctor.getDerivedStateFromCatch !== 'function')) {
    // If we captured an error, but getDerivedStateFrom catch is not defined,
    // unmount all the children. componentDidCatch will schedule an update to
    // re-render a fallback. This is temporary until we migrate everyone to
    // the new API.
    // TODO: Warn in a future release.
    nextChildren = null;

    if (enableProfilerTimer) {
      stopBaseRenderTimerIfRunning();
    }
  } else {
    {
      ReactDebugCurrentFiber.setCurrentPhase('render');
      nextChildren = instance.render();
      if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
        instance.render();
      }
      ReactDebugCurrentFiber.setCurrentPhase(null);
    }
  }

  // React DevTools reads this flag.
  workInProgress.effectTag |= PerformedWork;
  if (didCaptureError) {
    // If we're recovering from an error, reconcile twice: first to delete
    // all the existing children.
    reconcileChildrenAtExpirationTime(current, workInProgress, null, renderExpirationTime);
    workInProgress.child = null;
    // Now we can continue reconciling like normal. This has the effect of
    // remounting all children regardless of whether their their
    // identity matches.
  }
  reconcileChildrenAtExpirationTime(current, workInProgress, nextChildren, renderExpirationTime);
  // Memoize props and state using the values we just used to render.
  // TODO: Restructure so we never read values from the instance.
  memoizeState(workInProgress, instance.state);
  memoizeProps(workInProgress, instance.props);

  // The context might have changed so we need to recalculate it.
  if (hasContext) {
    invalidateContextProvider(workInProgress, true);
  }

  return workInProgress.child;
}

function pushHostRootContext(workInProgress) {
  var root = workInProgress.stateNode;
  if (root.pendingContext) {
    pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);
  } else if (root.context) {
    // Should always be set
    pushTopLevelContextObject(workInProgress, root.context, false);
  }
  pushHostContainer(workInProgress, root.containerInfo);
}

function updateHostRoot(current, workInProgress, renderExpirationTime) {
  pushHostRootContext(workInProgress);
  var updateQueue = workInProgress.updateQueue;
  if (updateQueue !== null) {
    var nextProps = workInProgress.pendingProps;
    var prevState = workInProgress.memoizedState;
    var prevChildren = prevState !== null ? prevState.element : null;
    processUpdateQueue(workInProgress, updateQueue, nextProps, null, renderExpirationTime);
    var nextState = workInProgress.memoizedState;
    // Caution: React DevTools currently depends on this property
    // being called "element".
    var nextChildren = nextState.element;

    if (nextChildren === prevChildren) {
      // If the state is the same as before, that's a bailout because we had
      // no work that expires at this time.
      resetHydrationState();
      return bailoutOnAlreadyFinishedWork(current, workInProgress);
    }
    var root = workInProgress.stateNode;
    if ((current === null || current.child === null) && root.hydrate && enterHydrationState(workInProgress)) {
      // If we don't have any current children this might be the first pass.
      // We always try to hydrate. If this isn't a hydration pass there won't
      // be any children to hydrate which is effectively the same thing as
      // not hydrating.

      // This is a bit of a hack. We track the host root as a placement to
      // know that we're currently in a mounting state. That way isMounted
      // works as expected. We must reset this before committing.
      // TODO: Delete this when we delete isMounted and findDOMNode.
      workInProgress.effectTag |= Placement;

      // Ensure that children mount into this root without tracking
      // side-effects. This ensures that we don't store Placement effects on
      // nodes that will be hydrated.
      workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
    } else {
      // Otherwise reset hydration state in case we aborted and resumed another
      // root.
      resetHydrationState();
      reconcileChildren(current, workInProgress, nextChildren);
    }
    return workInProgress.child;
  }
  resetHydrationState();
  // If there is no update queue, that's a bailout because the root has no props.
  return bailoutOnAlreadyFinishedWork(current, workInProgress);
}

function updateHostComponent(current, workInProgress, renderExpirationTime) {
  pushHostContext(workInProgress);

  if (current === null) {
    tryToClaimNextHydratableInstance(workInProgress);
  }

  var type = workInProgress.type;
  var memoizedProps = workInProgress.memoizedProps;
  var nextProps = workInProgress.pendingProps;
  var prevProps = current !== null ? current.memoizedProps : null;

  if (hasContextChanged()) {
    // Normally we can bail out on props equality but if context has changed
    // we don't do the bailout and we have to reuse existing props instead.
  } else if (memoizedProps === nextProps) {
    var isHidden = workInProgress.mode & AsyncMode && shouldDeprioritizeSubtree(type, nextProps);
    if (isHidden) {
      // Before bailing out, make sure we've deprioritized a hidden component.
      workInProgress.expirationTime = Never;
    }
    if (!isHidden || renderExpirationTime !== Never) {
      return bailoutOnAlreadyFinishedWork(current, workInProgress);
    }
    // If we're rendering a hidden node at hidden priority, don't bailout. The
    // parent is complete, but the children may not be.
  }

  var nextChildren = nextProps.children;
  var isDirectTextChild = shouldSetTextContent(type, nextProps);

  if (isDirectTextChild) {
    // We special case a direct text child of a host node. This is a common
    // case. We won't handle it as a reified child. We will instead handle
    // this in the host environment that also have access to this prop. That
    // avoids allocating another HostText fiber and traversing it.
    nextChildren = null;
  } else if (prevProps && shouldSetTextContent(type, prevProps)) {
    // If we're switching from a direct text child to a normal child, or to
    // empty, we need to schedule the text content to be reset.
    workInProgress.effectTag |= ContentReset;
  }

  markRef(current, workInProgress);

  // Check the host config to see if the children are offscreen/hidden.
  if (renderExpirationTime !== Never && workInProgress.mode & AsyncMode && shouldDeprioritizeSubtree(type, nextProps)) {
    // Down-prioritize the children.
    workInProgress.expirationTime = Never;
    // Bailout and come back to this fiber later.
    workInProgress.memoizedProps = nextProps;
    return null;
  }

  reconcileChildren(current, workInProgress, nextChildren);
  memoizeProps(workInProgress, nextProps);
  return workInProgress.child;
}

function updateHostText(current, workInProgress) {
  if (current === null) {
    tryToClaimNextHydratableInstance(workInProgress);
  }
  var nextProps = workInProgress.pendingProps;
  memoizeProps(workInProgress, nextProps);
  // Nothing to do here. This is terminal. We'll do the completion step
  // immediately after.
  return null;
}

function mountIndeterminateComponent(current, workInProgress, renderExpirationTime) {
  !(current === null) ? invariant(false, 'An indeterminate component should never have mounted. This error is likely caused by a bug in React. Please file an issue.') : void 0;
  var fn = workInProgress.type;
  var props = workInProgress.pendingProps;
  var unmaskedContext = getUnmaskedContext(workInProgress);
  var context = getMaskedContext(workInProgress, unmaskedContext);

  var value = void 0;

  {
    if (fn.prototype && typeof fn.prototype.render === 'function') {
      var componentName = getComponentName(workInProgress) || 'Unknown';

      if (!didWarnAboutBadClass[componentName]) {
        warning(false, "The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName);
        didWarnAboutBadClass[componentName] = true;
      }
    }

    if (workInProgress.mode & StrictMode) {
      ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
    }

    ReactCurrentOwner.current = workInProgress;
    value = fn(props, context);
  }
  // React DevTools reads this flag.
  workInProgress.effectTag |= PerformedWork;

  if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
    var Component = workInProgress.type;

    // Proceed under the assumption that this is a class instance
    workInProgress.tag = ClassComponent;

    workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;

    var getDerivedStateFromProps = Component.getDerivedStateFromProps;
    if (typeof getDerivedStateFromProps === 'function') {
      applyDerivedStateFromProps(workInProgress, getDerivedStateFromProps, props);
    }

    // Push context providers early to prevent context stack mismatches.
    // During mounting we don't know the child context yet as the instance doesn't exist.
    // We will invalidate the child context in finishClassComponent() right after rendering.
    var hasContext = pushContextProvider(workInProgress);
    adoptClassInstance(workInProgress, value);
    mountClassInstance(workInProgress, renderExpirationTime);
    return finishClassComponent(current, workInProgress, true, hasContext, renderExpirationTime);
  } else {
    // Proceed under the assumption that this is a functional component
    workInProgress.tag = FunctionalComponent;
    {
      var _Component = workInProgress.type;

      if (_Component) {
        !!_Component.childContextTypes ? warning(false, '%s(...): childContextTypes cannot be defined on a functional component.', _Component.displayName || _Component.name || 'Component') : void 0;
      }
      if (workInProgress.ref !== null) {
        var info = '';
        var ownerName = ReactDebugCurrentFiber.getCurrentFiberOwnerName();
        if (ownerName) {
          info += '\n\nCheck the render method of `' + ownerName + '`.';
        }

        var warningKey = ownerName || workInProgress._debugID || '';
        var debugSource = workInProgress._debugSource;
        if (debugSource) {
          warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
        }
        if (!didWarnAboutStatelessRefs[warningKey]) {
          didWarnAboutStatelessRefs[warningKey] = true;
          warning(false, 'Stateless function components cannot be given refs. ' + 'Attempts to access this ref will fail.%s%s', info, ReactDebugCurrentFiber.getCurrentFiberStackAddendum());
        }
      }

      if (typeof fn.getDerivedStateFromProps === 'function') {
        var _componentName = getComponentName(workInProgress) || 'Unknown';

        if (!didWarnAboutGetDerivedStateOnFunctionalComponent[_componentName]) {
          warning(false, '%s: Stateless functional components do not support getDerivedStateFromProps.', _componentName);
          didWarnAboutGetDerivedStateOnFunctionalComponent[_componentName] = true;
        }
      }
    }
    reconcileChildren(current, workInProgress, value);
    memoizeProps(workInProgress, props);
    return workInProgress.child;
  }
}

function updateTimeoutComponent(current, workInProgress, renderExpirationTime) {
  if (enableSuspense) {
    var nextProps = workInProgress.pendingProps;
    var prevProps = workInProgress.memoizedProps;

    var prevDidTimeout = workInProgress.memoizedState;

    // Check if we already attempted to render the normal state. If we did,
    // and we timed out, render the placeholder state.
    var alreadyCaptured = (workInProgress.effectTag & DidCapture) === NoEffect;
    var nextDidTimeout = !alreadyCaptured;

    if (hasContextChanged()) {
      // Normally we can bail out on props equality but if context has changed
      // we don't do the bailout and we have to reuse existing props instead.
    } else if (nextProps === prevProps && nextDidTimeout === prevDidTimeout) {
      return bailoutOnAlreadyFinishedWork(current, workInProgress);
    }

    var render = nextProps.children;
    var nextChildren = render(nextDidTimeout);
    workInProgress.memoizedProps = nextProps;
    workInProgress.memoizedState = nextDidTimeout;
    reconcileChildren(current, workInProgress, nextChildren);
    return workInProgress.child;
  } else {
    return null;
  }
}

function updatePortalComponent(current, workInProgress, renderExpirationTime) {
  pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
  var nextChildren = workInProgress.pendingProps;
  if (hasContextChanged()) {
    // Normally we can bail out on props equality but if context has changed
    // we don't do the bailout and we have to reuse existing props instead.
  } else if (workInProgress.memoizedProps === nextChildren) {
    return bailoutOnAlreadyFinishedWork(current, workInProgress);
  }

  if (current === null) {
    // Portals are special because we don't append the children during mount
    // but at commit. Therefore we need to track insertions which the normal
    // flow doesn't do during mount. This doesn't happen at the root because
    // the root always starts with a "current" with a null child.
    // TODO: Consider unifying this with how the root works.
    workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
    memoizeProps(workInProgress, nextChildren);
  } else {
    reconcileChildren(current, workInProgress, nextChildren);
    memoizeProps(workInProgress, nextChildren);
  }
  return workInProgress.child;
}

function propagateContextChange(workInProgress, context, changedBits, renderExpirationTime) {
  var fiber = workInProgress.child;
  if (fiber !== null) {
    // Set the return pointer of the child to the work-in-progress fiber.
    fiber.return = workInProgress;
  }
  while (fiber !== null) {
    var nextFiber = void 0;
    // Visit this fiber.
    switch (fiber.tag) {
      case ContextConsumer:
        // Check if the context matches.
        var observedBits = fiber.stateNode | 0;
        if (fiber.type === context && (observedBits & changedBits) !== 0) {
          // Update the expiration time of all the ancestors, including
          // the alternates.
          var node = fiber;
          while (node !== null) {
            var alternate = node.alternate;
            if (node.expirationTime === NoWork || node.expirationTime > renderExpirationTime) {
              node.expirationTime = renderExpirationTime;
              if (alternate !== null && (alternate.expirationTime === NoWork || alternate.expirationTime > renderExpirationTime)) {
                alternate.expirationTime = renderExpirationTime;
              }
            } else if (alternate !== null && (alternate.expirationTime === NoWork || alternate.expirationTime > renderExpirationTime)) {
              alternate.expirationTime = renderExpirationTime;
            } else {
              // Neither alternate was updated, which means the rest of the
              // ancestor path already has sufficient priority.
              break;
            }
            node = node.return;
          }
          // Don't scan deeper than a matching consumer. When we render the
          // consumer, we'll continue scanning from that point. This way the
          // scanning work is time-sliced.
          nextFiber = null;
        } else {
          // Traverse down.
          nextFiber = fiber.child;
        }
        break;
      case ContextProvider:
        // Don't scan deeper if this is a matching provider
        nextFiber = fiber.type === workInProgress.type ? null : fiber.child;
        break;
      default:
        // Traverse down.
        nextFiber = fiber.child;
        break;
    }
    if (nextFiber !== null) {
      // Set the return pointer of the child to the work-in-progress fiber.
      nextFiber.return = fiber;
    } else {
      // No child. Traverse to next sibling.
      nextFiber = fiber;
      while (nextFiber !== null) {
        if (nextFiber === workInProgress) {
          // We're back to the root of this subtree. Exit.
          nextFiber = null;
          break;
        }
        var sibling = nextFiber.sibling;
        if (sibling !== null) {
          // Set the return pointer of the sibling to the work-in-progress fiber.
          sibling.return = nextFiber.return;
          nextFiber = sibling;
          break;
        }
        // No more siblings. Traverse up.
        nextFiber = nextFiber.return;
      }
    }
    fiber = nextFiber;
  }
}

function updateContextProvider(current, workInProgress, renderExpirationTime) {
  var providerType = workInProgress.type;
  var context = providerType._context;

  var newProps = workInProgress.pendingProps;
  var oldProps = workInProgress.memoizedProps;
  var canBailOnProps = true;

  if (hasContextChanged()) {
    canBailOnProps = false;
    // Normally we can bail out on props equality but if context has changed
    // we don't do the bailout and we have to reuse existing props instead.
  } else if (oldProps === newProps) {
    workInProgress.stateNode = 0;
    pushProvider(workInProgress);
    return bailoutOnAlreadyFinishedWork(current, workInProgress);
  }

  var newValue = newProps.value;
  workInProgress.memoizedProps = newProps;

  {
    var providerPropTypes = workInProgress.type.propTypes;

    if (providerPropTypes) {
      checkPropTypes(providerPropTypes, newProps, 'prop', 'Context.Provider', getCurrentFiberStackAddendum$6);
    }
  }

  var changedBits = void 0;
  if (oldProps === null) {
    // Initial render
    changedBits = MAX_SIGNED_31_BIT_INT;
  } else {
    if (oldProps.value === newProps.value) {
      // No change. Bailout early if children are the same.
      if (oldProps.children === newProps.children && canBailOnProps) {
        workInProgress.stateNode = 0;
        pushProvider(workInProgress);
        return bailoutOnAlreadyFinishedWork(current, workInProgress);
      }
      changedBits = 0;
    } else {
      var oldValue = oldProps.value;
      // Use Object.is to compare the new context value to the old value.
      // Inlined Object.is polyfill.
      // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
      if (oldValue === newValue && (oldValue !== 0 || 1 / oldValue === 1 / newValue) || oldValue !== oldValue && newValue !== newValue // eslint-disable-line no-self-compare
      ) {
          // No change. Bailout early if children are the same.
          if (oldProps.children === newProps.children && canBailOnProps) {
            workInProgress.stateNode = 0;
            pushProvider(workInProgress);
            return bailoutOnAlreadyFinishedWork(current, workInProgress);
          }
          changedBits = 0;
        } else {
        changedBits = typeof context._calculateChangedBits === 'function' ? context._calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;
        {
          !((changedBits & MAX_SIGNED_31_BIT_INT) === changedBits) ? warning(false, 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits) : void 0;
        }
        changedBits |= 0;

        if (changedBits === 0) {
          // No change. Bailout early if children are the same.
          if (oldProps.children === newProps.children && canBailOnProps) {
            workInProgress.stateNode = 0;
            pushProvider(workInProgress);
            return bailoutOnAlreadyFinishedWork(current, workInProgress);
          }
        } else {
          propagateContextChange(workInProgress, context, changedBits, renderExpirationTime);
        }
      }
    }
  }

  workInProgress.stateNode = changedBits;
  pushProvider(workInProgress);

  var newChildren = newProps.children;
  reconcileChildren(current, workInProgress, newChildren);
  return workInProgress.child;
}

function updateContextConsumer(current, workInProgress, renderExpirationTime) {
  var context = workInProgress.type;
  var newProps = workInProgress.pendingProps;
  var oldProps = workInProgress.memoizedProps;

  var newValue = getContextCurrentValue(context);
  var changedBits = getContextChangedBits(context);

  if (hasContextChanged()) {
    // Normally we can bail out on props equality but if context has changed
    // we don't do the bailout and we have to reuse existing props instead.
  } else if (changedBits === 0 && oldProps === newProps) {
    return bailoutOnAlreadyFinishedWork(current, workInProgress);
  }
  workInProgress.memoizedProps = newProps;

  var observedBits = newProps.unstable_observedBits;
  if (observedBits === undefined || observedBits === null) {
    // Subscribe to all changes by default
    observedBits = MAX_SIGNED_31_BIT_INT;
  }
  // Store the observedBits on the fiber's stateNode for quick access.
  workInProgress.stateNode = observedBits;

  if ((changedBits & observedBits) !== 0) {
    // Context change propagation stops at matching consumers, for time-
    // slicing. Continue the propagation here.
    propagateContextChange(workInProgress, context, changedBits, renderExpirationTime);
  } else if (oldProps === newProps) {
    // Skip over a memoized parent with a bitmask bailout even
    // if we began working on it because of a deeper matching child.
    return bailoutOnAlreadyFinishedWork(current, workInProgress);
  }
  // There is no bailout on `children` equality because we expect people
  // to often pass a bound method as a child, but it may reference
  // `this.state` or `this.props` (and thus needs to re-render on `setState`).

  var render = newProps.children;

  {
    !(typeof render === 'function') ? warning(false, 'A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.') : void 0;
  }

  var newChildren = void 0;
  {
    ReactCurrentOwner.current = workInProgress;
    ReactDebugCurrentFiber.setCurrentPhase('render');
    newChildren = render(newValue);
    ReactDebugCurrentFiber.setCurrentPhase(null);
  }

  // React DevTools reads this flag.
  workInProgress.effectTag |= PerformedWork;
  reconcileChildren(current, workInProgress, newChildren);
  return workInProgress.child;
}

/*
  function reuseChildrenEffects(returnFiber : Fiber, firstChild : Fiber) {
    let child = firstChild;
    do {
      // Ensure that the first and last effect of the parent corresponds
      // to the children's first and last effect.
      if (!returnFiber.firstEffect) {
        returnFiber.firstEffect = child.firstEffect;
      }
      if (child.lastEffect) {
        if (returnFiber.lastEffect) {
          returnFiber.lastEffect.nextEffect = child.firstEffect;
        }
        returnFiber.lastEffect = child.lastEffect;
      }
    } while (child = child.sibling);
  }
  */

function bailoutOnAlreadyFinishedWork(current, workInProgress) {
  cancelWorkTimer(workInProgress);

  if (enableProfilerTimer) {
    // Don't update "base" render times for bailouts.
    stopBaseRenderTimerIfRunning();
  }

  // TODO: We should ideally be able to bail out early if the children have no
  // more work to do. However, since we don't have a separation of this
  // Fiber's priority and its children yet - we don't know without doing lots
  // of the same work we do anyway. Once we have that separation we can just
  // bail out here if the children has no more work at this priority level.
  // if (workInProgress.priorityOfChildren <= priorityLevel) {
  //   // If there are side-effects in these children that have not yet been
  //   // committed we need to ensure that they get properly transferred up.
  //   if (current && current.child !== workInProgress.child) {
  //     reuseChildrenEffects(workInProgress, child);
  //   }
  //   return null;
  // }

  cloneChildFibers(current, workInProgress);
  return workInProgress.child;
}

function bailoutOnLowPriority(current, workInProgress) {
  cancelWorkTimer(workInProgress);

  if (enableProfilerTimer) {
    // Don't update "base" render times for bailouts.
    stopBaseRenderTimerIfRunning();
  }

  // TODO: Handle HostComponent tags here as well and call pushHostContext()?
  // See PR 8590 discussion for context
  switch (workInProgress.tag) {
    case HostRoot:
      pushHostRootContext(workInProgress);
      break;
    case ClassComponent:
      pushContextProvider(workInProgress);
      break;
    case HostPortal:
      pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
      break;
    case ContextProvider:
      pushProvider(workInProgress);
      break;
  }
  // TODO: What if this is currently in progress?
  // How can that happen? How is this not being cloned?
  return null;
}

// TODO: Delete memoizeProps/State and move to reconcile/bailout instead
function memoizeProps(workInProgress, nextProps) {
  workInProgress.memoizedProps = nextProps;
}

function memoizeState(workInProgress, nextState) {
  workInProgress.memoizedState = nextState;
  // Don't reset the updateQueue, in case there are pending updates. Resetting
  // is handled by processUpdateQueue.
}

function beginWork(current, workInProgress, renderExpirationTime) {
  if (enableProfilerTimer) {
    if (workInProgress.mode & ProfileMode) {
      markActualRenderTimeStarted(workInProgress);
    }
  }

  if (workInProgress.expirationTime === NoWork || workInProgress.expirationTime > renderExpirationTime) {
    return bailoutOnLowPriority(current, workInProgress);
  }

  switch (workInProgress.tag) {
    case IndeterminateComponent:
      return mountIndeterminateComponent(current, workInProgress, renderExpirationTime);
    case FunctionalComponent:
      return updateFunctionalComponent(current, workInProgress);
    case ClassComponent:
      return updateClassComponent(current, workInProgress, renderExpirationTime);
    case HostRoot:
      return updateHostRoot(current, workInProgress, renderExpirationTime);
    case HostComponent:
      return updateHostComponent(current, workInProgress, renderExpirationTime);
    case HostText:
      return updateHostText(current, workInProgress);
    case TimeoutComponent:
      return updateTimeoutComponent(current, workInProgress, renderExpirationTime);
    case HostPortal:
      return updatePortalComponent(current, workInProgress, renderExpirationTime);
    case ForwardRef:
      return updateForwardRef(current, workInProgress);
    case Fragment:
      return updateFragment(current, workInProgress);
    case Mode:
      return updateMode(current, workInProgress);
    case Profiler:
      return updateProfiler(current, workInProgress);
    case ContextProvider:
      return updateContextProvider(current, workInProgress, renderExpirationTime);
    case ContextConsumer:
      return updateContextConsumer(current, workInProgress, renderExpirationTime);
    default:
      invariant(false, 'Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.');
  }
}

function markUpdate(workInProgress) {
  // Tag the fiber with an update effect. This turns a Placement into
  // a PlacementAndUpdate.
  workInProgress.effectTag |= Update;
}

function markRef$1(workInProgress) {
  workInProgress.effectTag |= Ref;
}

function appendAllChildren(parent, workInProgress) {
  // We only have the top Fiber that was created but we need recurse down its
  // children to find all the terminal nodes.
  var node = workInProgress.child;
  while (node !== null) {
    if (node.tag === HostComponent || node.tag === HostText) {
      appendInitialChild(parent, node.stateNode);
    } else if (node.tag === HostPortal) {
      // If we have a portal child, then we don't want to traverse
      // down its children. Instead, we'll get insertions from each child in
      // the portal directly.
    } else if (node.child !== null) {
      node.child.return = node;
      node = node.child;
      continue;
    }
    if (node === workInProgress) {
      return;
    }
    while (node.sibling === null) {
      if (node.return === null || node.return === workInProgress) {
        return;
      }
      node = node.return;
    }
    node.sibling.return = node.return;
    node = node.sibling;
  }
}

var updateHostContainer = void 0;
var updateHostComponent$1 = void 0;
var updateHostText$1 = void 0;
if (supportsMutation) {
  // Mutation mode

  updateHostContainer = function (workInProgress) {
    // Noop
  };
  updateHostComponent$1 = function (current, workInProgress, updatePayload, type, oldProps, newProps, rootContainerInstance, currentHostContext) {
    // TODO: Type this specific to this type of component.
    workInProgress.updateQueue = updatePayload;
    // If the update payload indicates that there is a change or if there
    // is a new ref we mark this as an update. All the work is done in commitWork.
    if (updatePayload) {
      markUpdate(workInProgress);
    }
  };
  updateHostText$1 = function (current, workInProgress, oldText, newText) {
    // If the text differs, mark it as an update. All the work in done in commitWork.
    if (oldText !== newText) {
      markUpdate(workInProgress);
    }
  };
} else if (supportsPersistence) {
  // Persistent host tree mode

  // An unfortunate fork of appendAllChildren because we have two different parent types.
  var appendAllChildrenToContainer = function (containerChildSet, workInProgress) {
    // We only have the top Fiber that was created but we need recurse down its
    // children to find all the terminal nodes.
    var node = workInProgress.child;
    while (node !== null) {
      if (node.tag === HostComponent || node.tag === HostText) {
        appendChildToContainerChildSet(containerChildSet, node.stateNode);
      } else if (node.tag === HostPortal) {
        // If we have a portal child, then we don't want to traverse
        // down its children. Instead, we'll get insertions from each child in
        // the portal directly.
      } else if (node.child !== null) {
        node.child.return = node;
        node = node.child;
        continue;
      }
      if (node === workInProgress) {
        return;
      }
      while (node.sibling === null) {
        if (node.return === null || node.return === workInProgress) {
          return;
        }
        node = node.return;
      }
      node.sibling.return = node.return;
      node = node.sibling;
    }
  };
  updateHostContainer = function (workInProgress) {
    var portalOrRoot = workInProgress.stateNode;
    var childrenUnchanged = workInProgress.firstEffect === null;
    if (childrenUnchanged) {
      // No changes, just reuse the existing instance.
    } else {
      var container = portalOrRoot.containerInfo;
      var newChildSet = createContainerChildSet(container);
      // If children might have changed, we have to add them all to the set.
      appendAllChildrenToContainer(newChildSet, workInProgress);
      portalOrRoot.pendingChildren = newChildSet;
      // Schedule an update on the container to swap out the container.
      markUpdate(workInProgress);
      finalizeContainerChildren(container, newChildSet);
    }
  };
  updateHostComponent$1 = function (current, workInProgress, updatePayload, type, oldProps, newProps, rootContainerInstance, currentHostContext) {
    // If there are no effects associated with this node, then none of our children had any updates.
    // This guarantees that we can reuse all of them.
    var childrenUnchanged = workInProgress.firstEffect === null;
    var currentInstance = current.stateNode;
    if (childrenUnchanged && updatePayload === null) {
      // No changes, just reuse the existing instance.
      // Note that this might release a previous clone.
      workInProgress.stateNode = currentInstance;
    } else {
      var recyclableInstance = workInProgress.stateNode;
      var newInstance = cloneInstance(currentInstance, updatePayload, type, oldProps, newProps, workInProgress, childrenUnchanged, recyclableInstance);
      if (finalizeInitialChildren(newInstance, type, newProps, rootContainerInstance, currentHostContext)) {
        markUpdate(workInProgress);
      }
      workInProgress.stateNode = newInstance;
      if (childrenUnchanged) {
        // If there are no other effects in this tree, we need to flag this node as having one.
        // Even though we're not going to use it for anything.
        // Otherwise parents won't know that there are new children to propagate upwards.
        markUpdate(workInProgress);
      } else {
        // If children might have changed, we have to add them all to the set.
        appendAllChildren(newInstance, workInProgress);
      }
    }
  };
  updateHostText$1 = function (current, workInProgress, oldText, newText) {
    if (oldText !== newText) {
      // If the text content differs, we'll create a new text instance for it.
      var rootContainerInstance = getRootHostContainer();
      var currentHostContext = getHostContext();
      workInProgress.stateNode = createTextInstance(newText, rootContainerInstance, currentHostContext, workInProgress);
      // We'll have to mark it as having an effect, even though we won't use the effect for anything.
      // This lets the parents know that at least one of their children has changed.
      markUpdate(workInProgress);
    }
  };
} else {
  // No host operations
  updateHostContainer = function (workInProgress) {
    // Noop
  };
  updateHostComponent$1 = function (current, workInProgress, updatePayload, type, oldProps, newProps, rootContainerInstance, currentHostContext) {
    // Noop
  };
  updateHostText$1 = function (current, workInProgress, oldText, newText) {
    // Noop
  };
}

function completeWork(current, workInProgress, renderExpirationTime) {
  var newProps = workInProgress.pendingProps;

  if (enableProfilerTimer) {
    if (workInProgress.mode & ProfileMode) {
      recordElapsedActualRenderTime(workInProgress);
    }
  }

  switch (workInProgress.tag) {
    case FunctionalComponent:
      return null;
    case ClassComponent:
      {
        // We are leaving this subtree, so pop context if any.
        popContextProvider(workInProgress);
        return null;
      }
    case HostRoot:
      {
        popHostContainer(workInProgress);
        popTopLevelContextObject(workInProgress);
        var fiberRoot = workInProgress.stateNode;
        if (fiberRoot.pendingContext) {
          fiberRoot.context = fiberRoot.pendingContext;
          fiberRoot.pendingContext = null;
        }
        if (current === null || current.child === null) {
          // If we hydrated, pop so that we can delete any remaining children
          // that weren't hydrated.
          popHydrationState(workInProgress);
          // This resets the hacky state to fix isMounted before committing.
          // TODO: Delete this when we delete isMounted and findDOMNode.
          workInProgress.effectTag &= ~Placement;
        }
        updateHostContainer(workInProgress);
        return null;
      }
    case HostComponent:
      {
        popHostContext(workInProgress);
        var rootContainerInstance = getRootHostContainer();
        var type = workInProgress.type;
        if (current !== null && workInProgress.stateNode != null) {
          // If we have an alternate, that means this is an update and we need to
          // schedule a side-effect to do the updates.
          var oldProps = current.memoizedProps;
          // If we get updated because one of our children updated, we don't
          // have newProps so we'll have to reuse them.
          // TODO: Split the update API as separate for the props vs. children.
          // Even better would be if children weren't special cased at all tho.
          var instance = workInProgress.stateNode;
          var currentHostContext = getHostContext();
          // TODO: Experiencing an error where oldProps is null. Suggests a host
          // component is hitting the resume path. Figure out why. Possibly
          // related to `hidden`.
          var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext);

          updateHostComponent$1(current, workInProgress, updatePayload, type, oldProps, newProps, rootContainerInstance, currentHostContext);

          if (current.ref !== workInProgress.ref) {
            markRef$1(workInProgress);
          }
        } else {
          if (!newProps) {
            !(workInProgress.stateNode !== null) ? invariant(false, 'We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.') : void 0;
            // This can happen when we abort work.
            return null;
          }

          var _currentHostContext = getHostContext();
          // TODO: Move createInstance to beginWork and keep it on a context
          // "stack" as the parent. Then append children as we go in beginWork
          // or completeWork depending on we want to add then top->down or
          // bottom->up. Top->down is faster in IE11.
          var wasHydrated = popHydrationState(workInProgress);
          if (wasHydrated) {
            // TODO: Move this and createInstance step into the beginPhase
            // to consolidate.
            if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, _currentHostContext)) {
              // If changes to the hydrated node needs to be applied at the
              // commit-phase we mark this as such.
              markUpdate(workInProgress);
            }
          } else {
            var _instance = createInstance(type, newProps, rootContainerInstance, _currentHostContext, workInProgress);

            appendAllChildren(_instance, workInProgress);

            // Certain renderers require commit-time effects for initial mount.
            // (eg DOM renderer supports auto-focus for certain elements).
            // Make sure such renderers get scheduled for later work.
            if (finalizeInitialChildren(_instance, type, newProps, rootContainerInstance, _currentHostContext)) {
              markUpdate(workInProgress);
            }
            workInProgress.stateNode = _instance;
          }

          if (workInProgress.ref !== null) {
            // If there is a ref on a host node we need to schedule a callback
            markRef$1(workInProgress);
          }
        }
        return null;
      }
    case HostText:
      {
        var newText = newProps;
        if (current && workInProgress.stateNode != null) {
          var oldText = current.memoizedProps;
          // If we have an alternate, that means this is an update and we need
          // to schedule a side-effect to do the updates.
          updateHostText$1(current, workInProgress, oldText, newText);
        } else {
          if (typeof newText !== 'string') {
            !(workInProgress.stateNode !== null) ? invariant(false, 'We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.') : void 0;
            // This can happen when we abort work.
            return null;
          }
          var _rootContainerInstance = getRootHostContainer();
          var _currentHostContext2 = getHostContext();
          var _wasHydrated = popHydrationState(workInProgress);
          if (_wasHydrated) {
            if (prepareToHydrateHostTextInstance(workInProgress)) {
              markUpdate(workInProgress);
            }
          } else {
            workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext2, workInProgress);
          }
        }
        return null;
      }
    case ForwardRef:
      return null;
    case TimeoutComponent:
      return null;
    case Fragment:
      return null;
    case Mode:
      return null;
    case Profiler:
      return null;
    case HostPortal:
      popHostContainer(workInProgress);
      updateHostContainer(workInProgress);
      return null;
    case ContextProvider:
      // Pop provider fiber
      popProvider(workInProgress);
      return null;
    case ContextConsumer:
      return null;
    // Error cases
    case IndeterminateComponent:
      invariant(false, 'An indeterminate component should have become determinate before completing. This error is likely caused by a bug in React. Please file an issue.');
    // eslint-disable-next-line no-fallthrough
    default:
      invariant(false, 'Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.');
  }
}

// This module is forked in different environments.
// By default, return `true` to log errors to the console.
// Forks can return `false` if this isn't desirable.
function showErrorDialog(capturedError) {
  return true;
}

function logCapturedError(capturedError) {
  var logError = showErrorDialog(capturedError);

  // Allow injected showErrorDialog() to prevent default console.error logging.
  // This enables renderers like ReactNative to better manage redbox behavior.
  if (logError === false) {
    return;
  }

  var error = capturedError.error;
  var suppressLogging = error && error.suppressReactErrorLogging;
  if (suppressLogging) {
    return;
  }

  {
    var componentName = capturedError.componentName,
        componentStack = capturedError.componentStack,
        errorBoundaryName = capturedError.errorBoundaryName,
        errorBoundaryFound = capturedError.errorBoundaryFound,
        willRetry = capturedError.willRetry;


    var componentNameMessage = componentName ? 'The above error occurred in the <' + componentName + '> component:' : 'The above error occurred in one of your React components:';

    var errorBoundaryMessage = void 0;
    // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow.
    if (errorBoundaryFound && errorBoundaryName) {
      if (willRetry) {
        errorBoundaryMessage = 'React will try to recreate this component tree from scratch ' + ('using the error boundary you provided, ' + errorBoundaryName + '.');
      } else {
        errorBoundaryMessage = 'This error was initially handled by the error boundary ' + errorBoundaryName + '.\n' + 'Recreating the tree from scratch failed so React will unmount the tree.';
      }
    } else {
      errorBoundaryMessage = 'Consider adding an error boundary to your tree to customize error handling behavior.\n' + 'Visit https://fb.me/react-error-boundaries to learn more about error boundaries.';
    }
    var combinedMessage = '' + componentNameMessage + componentStack + '\n\n' + ('' + errorBoundaryMessage);

    // In development, we provide our own message with just the component stack.
    // We don't include the original error message and JS stack because the browser
    // has already printed it. Even if the application swallows the error, it is still
    // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
    console.error(combinedMessage);
  }
}

var invokeGuardedCallback$3 = ReactErrorUtils.invokeGuardedCallback;
var hasCaughtError$1 = ReactErrorUtils.hasCaughtError;
var clearCaughtError$1 = ReactErrorUtils.clearCaughtError;


var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
{
  didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
}

function logError(boundary, errorInfo) {
  var source = errorInfo.source;
  var stack = errorInfo.stack;
  if (stack === null && source !== null) {
    stack = getStackAddendumByWorkInProgressFiber(source);
  }

  var capturedError = {
    componentName: source !== null ? getComponentName(source) : null,
    componentStack: stack !== null ? stack : '',
    error: errorInfo.value,
    errorBoundary: null,
    errorBoundaryName: null,
    errorBoundaryFound: false,
    willRetry: false
  };

  if (boundary !== null && boundary.tag === ClassComponent) {
    capturedError.errorBoundary = boundary.stateNode;
    capturedError.errorBoundaryName = getComponentName(boundary);
    capturedError.errorBoundaryFound = true;
    capturedError.willRetry = true;
  }

  try {
    logCapturedError(capturedError);
  } catch (e) {
    // Prevent cycle if logCapturedError() throws.
    // A cycle may still occur if logCapturedError renders a component that throws.
    var suppressLogging = e && e.suppressReactErrorLogging;
    if (!suppressLogging) {
      console.error(e);
    }
  }
}

var callComponentWillUnmountWithTimer = function (current, instance) {
  startPhaseTimer(current, 'componentWillUnmount');
  instance.props = current.memoizedProps;
  instance.state = current.memoizedState;
  instance.componentWillUnmount();
  stopPhaseTimer();
};

// Capture errors so they don't interrupt unmounting.
function safelyCallComponentWillUnmount(current, instance) {
  {
    invokeGuardedCallback$3(null, callComponentWillUnmountWithTimer, null, current, instance);
    if (hasCaughtError$1()) {
      var unmountError = clearCaughtError$1();
      captureCommitPhaseError(current, unmountError);
    }
  }
}

function safelyDetachRef(current) {
  var ref = current.ref;
  if (ref !== null) {
    if (typeof ref === 'function') {
      {
        invokeGuardedCallback$3(null, ref, null, null);
        if (hasCaughtError$1()) {
          var refError = clearCaughtError$1();
          captureCommitPhaseError(current, refError);
        }
      }
    } else {
      ref.current = null;
    }
  }
}

function commitBeforeMutationLifeCycles(current, finishedWork) {
  switch (finishedWork.tag) {
    case ClassComponent:
      {
        if (finishedWork.effectTag & Snapshot) {
          if (current !== null) {
            var prevProps = current.memoizedProps;
            var prevState = current.memoizedState;
            startPhaseTimer(finishedWork, 'getSnapshotBeforeUpdate');
            var instance = finishedWork.stateNode;
            instance.props = finishedWork.memoizedProps;
            instance.state = finishedWork.memoizedState;
            var snapshot = instance.getSnapshotBeforeUpdate(prevProps, prevState);
            {
              var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;
              if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
                didWarnSet.add(finishedWork.type);
                warning(false, '%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentName(finishedWork));
              }
            }
            instance.__reactInternalSnapshotBeforeUpdate = snapshot;
            stopPhaseTimer();
          }
        }
        return;
      }
    case HostRoot:
    case HostComponent:
    case HostText:
    case HostPortal:
      // Nothing to do for these component types
      return;
    default:
      {
        invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
      }
  }
}

function commitLifeCycles(finishedRoot, current, finishedWork, currentTime, committedExpirationTime) {
  switch (finishedWork.tag) {
    case ClassComponent:
      {
        var instance = finishedWork.stateNode;
        if (finishedWork.effectTag & Update) {
          if (current === null) {
            startPhaseTimer(finishedWork, 'componentDidMount');
            instance.props = finishedWork.memoizedProps;
            instance.state = finishedWork.memoizedState;
            instance.componentDidMount();
            stopPhaseTimer();
          } else {
            var prevProps = current.memoizedProps;
            var prevState = current.memoizedState;
            startPhaseTimer(finishedWork, 'componentDidUpdate');
            instance.props = finishedWork.memoizedProps;
            instance.state = finishedWork.memoizedState;
            instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
            stopPhaseTimer();
          }
        }
        var updateQueue = finishedWork.updateQueue;
        if (updateQueue !== null) {
          instance.props = finishedWork.memoizedProps;
          instance.state = finishedWork.memoizedState;
          commitUpdateQueue(finishedWork, updateQueue, instance, committedExpirationTime);
        }
        return;
      }
    case HostRoot:
      {
        var _updateQueue = finishedWork.updateQueue;
        if (_updateQueue !== null) {
          var _instance = null;
          if (finishedWork.child !== null) {
            switch (finishedWork.child.tag) {
              case HostComponent:
                _instance = getPublicInstance(finishedWork.child.stateNode);
                break;
              case ClassComponent:
                _instance = finishedWork.child.stateNode;
                break;
            }
          }
          commitUpdateQueue(finishedWork, _updateQueue, _instance, committedExpirationTime);
        }
        return;
      }
    case HostComponent:
      {
        var _instance2 = finishedWork.stateNode;

        // Renderers may schedule work to be done after host components are mounted
        // (eg DOM renderer may schedule auto-focus for inputs and form controls).
        // These effects should only be committed when components are first mounted,
        // aka when there is no current/alternate.
        if (current === null && finishedWork.effectTag & Update) {
          var type = finishedWork.type;
          var props = finishedWork.memoizedProps;
          commitMount(_instance2, type, props, finishedWork);
        }

        return;
      }
    case HostText:
      {
        // We have no life-cycles associated with text.
        return;
      }
    case HostPortal:
      {
        // We have no life-cycles associated with portals.
        return;
      }
    case Profiler:
      {
        // We have no life-cycles associated with Profiler.
        return;
      }
    case TimeoutComponent:
      {
        // We have no life-cycles associated with Timeouts.
        return;
      }
    default:
      {
        invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
      }
  }
}

function commitAttachRef(finishedWork) {
  var ref = finishedWork.ref;
  if (ref !== null) {
    var instance = finishedWork.stateNode;
    var instanceToUse = void 0;
    switch (finishedWork.tag) {
      case HostComponent:
        instanceToUse = getPublicInstance(instance);
        break;
      default:
        instanceToUse = instance;
    }
    if (typeof ref === 'function') {
      ref(instanceToUse);
    } else {
      {
        if (!ref.hasOwnProperty('current')) {
          warning(false, 'Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().%s', getComponentName(finishedWork), getStackAddendumByWorkInProgressFiber(finishedWork));
        }
      }

      ref.current = instanceToUse;
    }
  }
}

function commitDetachRef(current) {
  var currentRef = current.ref;
  if (currentRef !== null) {
    if (typeof currentRef === 'function') {
      currentRef(null);
    } else {
      currentRef.current = null;
    }
  }
}

// User-originating errors (lifecycles and refs) should not interrupt
// deletion, so don't let them throw. Host-originating errors should
// interrupt deletion, so it's okay
function commitUnmount(current) {
  if (typeof onCommitUnmount === 'function') {
    onCommitUnmount(current);
  }

  switch (current.tag) {
    case ClassComponent:
      {
        safelyDetachRef(current);
        var instance = current.stateNode;
        if (typeof instance.componentWillUnmount === 'function') {
          safelyCallComponentWillUnmount(current, instance);
        }
        return;
      }
    case HostComponent:
      {
        safelyDetachRef(current);
        return;
      }
    case HostPortal:
      {
        // TODO: this is recursive.
        // We are also not using this parent because
        // the portal will get pushed immediately.
        if (supportsMutation) {
          unmountHostComponents(current);
        } else if (supportsPersistence) {
          emptyPortalContainer(current);
        }
        return;
      }
  }
}

function commitNestedUnmounts(root) {
  // While we're inside a removed host node we don't want to call
  // removeChild on the inner nodes because they're removed by the top
  // call anyway. We also want to call componentWillUnmount on all
  // composites before this host node is removed from the tree. Therefore
  var node = root;
  while (true) {
    commitUnmount(node);
    // Visit children because they may contain more composite or host nodes.
    // Skip portals because commitUnmount() currently visits them recursively.
    if (node.child !== null && (
    // If we use mutation we drill down into portals using commitUnmount above.
    // If we don't use mutation we drill down into portals here instead.
    !supportsMutation || node.tag !== HostPortal)) {
      node.child.return = node;
      node = node.child;
      continue;
    }
    if (node === root) {
      return;
    }
    while (node.sibling === null) {
      if (node.return === null || node.return === root) {
        return;
      }
      node = node.return;
    }
    node.sibling.return = node.return;
    node = node.sibling;
  }
}

function detachFiber(current) {
  // Cut off the return pointers to disconnect it from the tree. Ideally, we
  // should clear the child pointer of the parent alternate to let this
  // get GC:ed but we don't know which for sure which parent is the current
  // one so we'll settle for GC:ing the subtree of this child. This child
  // itself will be GC:ed when the parent updates the next time.
  current.return = null;
  current.child = null;
  if (current.alternate) {
    current.alternate.child = null;
    current.alternate.return = null;
  }
}

function emptyPortalContainer(current) {
  if (!supportsPersistence) {
    return;
  }

  var portal = current.stateNode;
  var containerInfo = portal.containerInfo;

  var emptyChildSet = createContainerChildSet(containerInfo);
  replaceContainerChildren(containerInfo, emptyChildSet);
}

function commitContainer(finishedWork) {
  if (!supportsPersistence) {
    return;
  }

  switch (finishedWork.tag) {
    case ClassComponent:
      {
        return;
      }
    case HostComponent:
      {
        return;
      }
    case HostText:
      {
        return;
      }
    case HostRoot:
    case HostPortal:
      {
        var portalOrRoot = finishedWork.stateNode;
        var containerInfo = portalOrRoot.containerInfo,
            _pendingChildren = portalOrRoot.pendingChildren;

        replaceContainerChildren(containerInfo, _pendingChildren);
        return;
      }
    default:
      {
        invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
      }
  }
}

function getHostParentFiber(fiber) {
  var parent = fiber.return;
  while (parent !== null) {
    if (isHostParent(parent)) {
      return parent;
    }
    parent = parent.return;
  }
  invariant(false, 'Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.');
}

function isHostParent(fiber) {
  return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
}

function getHostSibling(fiber) {
  // We're going to search forward into the tree until we find a sibling host
  // node. Unfortunately, if multiple insertions are done in a row we have to
  // search past them. This leads to exponential search for the next sibling.
  var node = fiber;
  siblings: while (true) {
    // If we didn't find anything, let's try the next sibling.
    while (node.sibling === null) {
      if (node.return === null || isHostParent(node.return)) {
        // If we pop out of the root or hit the parent the fiber we are the
        // last sibling.
        return null;
      }
      node = node.return;
    }
    node.sibling.return = node.return;
    node = node.sibling;
    while (node.tag !== HostComponent && node.tag !== HostText) {
      // If it is not host node and, we might have a host node inside it.
      // Try to search down until we find one.
      if (node.effectTag & Placement) {
        // If we don't have a child, try the siblings instead.
        continue siblings;
      }
      // If we don't have a child, try the siblings instead.
      // We also skip portals because they are not part of this host tree.
      if (node.child === null || node.tag === HostPortal) {
        continue siblings;
      } else {
        node.child.return = node;
        node = node.child;
      }
    }
    // Check if this host node is stable or about to be placed.
    if (!(node.effectTag & Placement)) {
      // Found it!
      return node.stateNode;
    }
  }
}

function commitPlacement(finishedWork) {
  if (!supportsMutation) {
    return;
  }

  // Recursively insert all host nodes into the parent.
  var parentFiber = getHostParentFiber(finishedWork);
  var parent = void 0;
  var isContainer = void 0;
  switch (parentFiber.tag) {
    case HostComponent:
      parent = parentFiber.stateNode;
      isContainer = false;
      break;
    case HostRoot:
      parent = parentFiber.stateNode.containerInfo;
      isContainer = true;
      break;
    case HostPortal:
      parent = parentFiber.stateNode.containerInfo;
      isContainer = true;
      break;
    default:
      invariant(false, 'Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.');
  }
  if (parentFiber.effectTag & ContentReset) {
    // Reset the text content of the parent before doing any insertions
    resetTextContent(parent);
    // Clear ContentReset from the effect tag
    parentFiber.effectTag &= ~ContentReset;
  }

  var before = getHostSibling(finishedWork);
  // We only have the top Fiber that was inserted but we need recurse down its
  // children to find all the terminal nodes.
  var node = finishedWork;
  while (true) {
    if (node.tag === HostComponent || node.tag === HostText) {
      if (before) {
        if (isContainer) {
          insertInContainerBefore(parent, node.stateNode, before);
        } else {
          insertBefore(parent, node.stateNode, before);
        }
      } else {
        if (isContainer) {
          appendChildToContainer(parent, node.stateNode);
        } else {
          appendChild(parent, node.stateNode);
        }
      }
    } else if (node.tag === HostPortal) {
      // If the insertion itself is a portal, then we don't want to traverse
      // down its children. Instead, we'll get insertions from each child in
      // the portal directly.
    } else if (node.child !== null) {
      node.child.return = node;
      node = node.child;
      continue;
    }
    if (node === finishedWork) {
      return;
    }
    while (node.sibling === null) {
      if (node.return === null || node.return === finishedWork) {
        return;
      }
      node = node.return;
    }
    node.sibling.return = node.return;
    node = node.sibling;
  }
}

function unmountHostComponents(current) {
  // We only have the top Fiber that was inserted but we need recurse down its
  var node = current;

  // Each iteration, currentParent is populated with node's host parent if not
  // currentParentIsValid.
  var currentParentIsValid = false;
  var currentParent = void 0;
  var currentParentIsContainer = void 0;

  while (true) {
    if (!currentParentIsValid) {
      var parent = node.return;
      findParent: while (true) {
        !(parent !== null) ? invariant(false, 'Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.') : void 0;
        switch (parent.tag) {
          case HostComponent:
            currentParent = parent.stateNode;
            currentParentIsContainer = false;
            break findParent;
          case HostRoot:
            currentParent = parent.stateNode.containerInfo;
            currentParentIsContainer = true;
            break findParent;
          case HostPortal:
            currentParent = parent.stateNode.containerInfo;
            currentParentIsContainer = true;
            break findParent;
        }
        parent = parent.return;
      }
      currentParentIsValid = true;
    }

    if (node.tag === HostComponent || node.tag === HostText) {
      commitNestedUnmounts(node);
      // After all the children have unmounted, it is now safe to remove the
      // node from the tree.
      if (currentParentIsContainer) {
        removeChildFromContainer(currentParent, node.stateNode);
      } else {
        removeChild(currentParent, node.stateNode);
      }
      // Don't visit children because we already visited them.
    } else if (node.tag === HostPortal) {
      // When we go into a portal, it becomes the parent to remove from.
      // We will reassign it back when we pop the portal on the way up.
      currentParent = node.stateNode.containerInfo;
      // Visit children because portals might contain host components.
      if (node.child !== null) {
        node.child.return = node;
        node = node.child;
        continue;
      }
    } else {
      commitUnmount(node);
      // Visit children because we may find more host components below.
      if (node.child !== null) {
        node.child.return = node;
        node = node.child;
        continue;
      }
    }
    if (node === current) {
      return;
    }
    while (node.sibling === null) {
      if (node.return === null || node.return === current) {
        return;
      }
      node = node.return;
      if (node.tag === HostPortal) {
        // When we go out of the portal, we need to restore the parent.
        // Since we don't keep a stack of them, we will search for it.
        currentParentIsValid = false;
      }
    }
    node.sibling.return = node.return;
    node = node.sibling;
  }
}

function commitDeletion(current) {
  if (supportsMutation) {
    // Recursively delete all host nodes from the parent.
    // Detach refs and call componentWillUnmount() on the whole subtree.
    unmountHostComponents(current);
  } else {
    // Detach refs and call componentWillUnmount() on the whole subtree.
    commitNestedUnmounts(current);
  }
  detachFiber(current);
}

function commitWork(current, finishedWork) {
  if (!supportsMutation) {
    commitContainer(finishedWork);
    return;
  }

  switch (finishedWork.tag) {
    case ClassComponent:
      {
        return;
      }
    case HostComponent:
      {
        var instance = finishedWork.stateNode;
        if (instance != null) {
          // Commit the work prepared earlier.
          var newProps = finishedWork.memoizedProps;
          // For hydration we reuse the update path but we treat the oldProps
          // as the newProps. The updatePayload will contain the real change in
          // this case.
          var oldProps = current !== null ? current.memoizedProps : newProps;
          var type = finishedWork.type;
          // TODO: Type the updateQueue to be specific to host components.
          var updatePayload = finishedWork.updateQueue;
          finishedWork.updateQueue = null;
          if (updatePayload !== null) {
            commitUpdate(instance, updatePayload, type, oldProps, newProps, finishedWork);
          }
        }
        return;
      }
    case HostText:
      {
        !(finishedWork.stateNode !== null) ? invariant(false, 'This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue.') : void 0;
        var textInstance = finishedWork.stateNode;
        var newText = finishedWork.memoizedProps;
        // For hydration we reuse the update path but we treat the oldProps
        // as the newProps. The updatePayload will contain the real change in
        // this case.
        var oldText = current !== null ? current.memoizedProps : newText;
        commitTextUpdate(textInstance, oldText, newText);
        return;
      }
    case HostRoot:
      {
        return;
      }
    case Profiler:
      {
        if (enableProfilerTimer) {
          var onRender = finishedWork.memoizedProps.onRender;
          onRender(finishedWork.memoizedProps.id, current === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseTime, finishedWork.actualStartTime, getCommitTime());
        }
        return;
      }
    case TimeoutComponent:
      {
        return;
      }
    default:
      {
        invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
      }
  }
}

function commitResetTextContent(current) {
  if (!supportsMutation) {
    return;
  }
  resetTextContent(current.stateNode);
}

function createRootErrorUpdate(fiber, errorInfo, expirationTime) {
  var update = createUpdate(expirationTime);
  // Unmount the root by rendering null.
  update.tag = CaptureUpdate;
  // Caution: React DevTools currently depends on this property
  // being called "element".
  update.payload = { element: null };
  var error = errorInfo.value;
  update.callback = function () {
    onUncaughtError(error);
    logError(fiber, errorInfo);
  };
  return update;
}

function createClassErrorUpdate(fiber, errorInfo, expirationTime) {
  var update = createUpdate(expirationTime);
  update.tag = CaptureUpdate;
  var getDerivedStateFromCatch = fiber.type.getDerivedStateFromCatch;
  if (enableGetDerivedStateFromCatch && typeof getDerivedStateFromCatch === 'function') {
    var error = errorInfo.value;
    update.payload = function () {
      return getDerivedStateFromCatch(error);
    };
  }

  var inst = fiber.stateNode;
  if (inst !== null && typeof inst.componentDidCatch === 'function') {
    update.callback = function callback() {
      if (!enableGetDerivedStateFromCatch || getDerivedStateFromCatch !== 'function') {
        // To preserve the preexisting retry behavior of error boundaries,
        // we keep track of which ones already failed during this batch.
        // This gets reset before we yield back to the browser.
        // TODO: Warn in strict mode if getDerivedStateFromCatch is
        // not defined.
        markLegacyErrorBoundaryAsFailed(this);
      }
      var error = errorInfo.value;
      var stack = errorInfo.stack;
      logError(fiber, errorInfo);
      this.componentDidCatch(error, {
        componentStack: stack !== null ? stack : ''
      });
    };
  }
  return update;
}

function schedulePing(finishedWork) {
  // Once the promise resolves, we should try rendering the non-
  // placeholder state again.
  var currentTime = recalculateCurrentTime();
  var expirationTime = computeExpirationForFiber(currentTime, finishedWork);
  var recoveryUpdate = createUpdate(expirationTime);
  enqueueUpdate(finishedWork, recoveryUpdate, expirationTime);
  scheduleWork$1(finishedWork, expirationTime);
}

function throwException(root, returnFiber, sourceFiber, value, renderIsExpired, renderExpirationTime, currentTimeMs) {
  // The source fiber did not complete.
  sourceFiber.effectTag |= Incomplete;
  // Its effect list is no longer valid.
  sourceFiber.firstEffect = sourceFiber.lastEffect = null;

  if (enableSuspense && value !== null && typeof value === 'object' && typeof value.then === 'function') {
    // This is a thenable.
    var thenable = value;

    var expirationTimeMs = expirationTimeToMs(renderExpirationTime);
    var startTimeMs = expirationTimeMs - 5000;
    var elapsedMs = currentTimeMs - startTimeMs;
    if (elapsedMs < 0) {
      elapsedMs = 0;
    }
    var remainingTimeMs = expirationTimeMs - currentTimeMs;

    // Find the earliest timeout of all the timeouts in the ancestor path.
    // TODO: Alternatively, we could store the earliest timeout on the context
    // stack, rather than searching on every suspend.
    var _workInProgress = returnFiber;
    var earliestTimeoutMs = -1;
    searchForEarliestTimeout: do {
      if (_workInProgress.tag === TimeoutComponent) {
        var current = _workInProgress.alternate;
        if (current !== null && current.memoizedState === true) {
          // A parent Timeout already committed in a placeholder state. We
          // need to handle this promise immediately. In other words, we
          // should never suspend inside a tree that already expired.
          earliestTimeoutMs = 0;
          break searchForEarliestTimeout;
        }
        var timeoutPropMs = _workInProgress.pendingProps.ms;
        if (typeof timeoutPropMs === 'number') {
          if (timeoutPropMs <= 0) {
            earliestTimeoutMs = 0;
            break searchForEarliestTimeout;
          } else if (earliestTimeoutMs === -1 || timeoutPropMs < earliestTimeoutMs) {
            earliestTimeoutMs = timeoutPropMs;
          }
        } else if (earliestTimeoutMs === -1) {
          earliestTimeoutMs = remainingTimeMs;
        }
      }
      _workInProgress = _workInProgress.return;
    } while (_workInProgress !== null);

    // Compute the remaining time until the timeout.
    var msUntilTimeout = earliestTimeoutMs - elapsedMs;

    if (renderExpirationTime === Never || msUntilTimeout > 0) {
      // There's still time remaining.
      suspendRoot(root, thenable, msUntilTimeout, renderExpirationTime);
      var onResolveOrReject = function () {
        retrySuspendedRoot(root, renderExpirationTime);
      };
      thenable.then(onResolveOrReject, onResolveOrReject);
      return;
    } else {
      // No time remaining. Need to fallback to placeholder.
      // Find the nearest timeout that can be retried.
      _workInProgress = returnFiber;
      do {
        switch (_workInProgress.tag) {
          case HostRoot:
            {
              // The root expired, but no fallback was provided. Throw a
              // helpful error.
              var message = renderExpirationTime === Sync ? 'A synchronous update was suspended, but no fallback UI ' + 'was provided.' : 'An update was suspended for longer than the timeout, ' + 'but no fallback UI was provided.';
              value = new Error(message);
              break;
            }
          case TimeoutComponent:
            {
              if ((_workInProgress.effectTag & DidCapture) === NoEffect) {
                _workInProgress.effectTag |= ShouldCapture;
                var _onResolveOrReject = schedulePing.bind(null, _workInProgress);
                thenable.then(_onResolveOrReject, _onResolveOrReject);
                return;
              }
              // Already captured during this render. Continue to the next
              // Timeout ancestor.
              break;
            }
        }
        _workInProgress = _workInProgress.return;
      } while (_workInProgress !== null);
    }
  }

  // We didn't find a boundary that could handle this type of exception. Start
  // over and traverse parent path again, this time treating the exception
  // as an error.
  value = createCapturedValue(value, sourceFiber);
  var workInProgress = returnFiber;
  do {
    switch (workInProgress.tag) {
      case HostRoot:
        {
          var _errorInfo = value;
          workInProgress.effectTag |= ShouldCapture;
          var update = createRootErrorUpdate(workInProgress, _errorInfo, renderExpirationTime);
          enqueueCapturedUpdate(workInProgress, update, renderExpirationTime);
          return;
        }
      case ClassComponent:
        // Capture and retry
        var errorInfo = value;
        var ctor = workInProgress.type;
        var instance = workInProgress.stateNode;
        if ((workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromCatch === 'function' && enableGetDerivedStateFromCatch || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) {
          workInProgress.effectTag |= ShouldCapture;
          // Schedule the error boundary to re-render using updated state
          var _update = createClassErrorUpdate(workInProgress, errorInfo, renderExpirationTime);
          enqueueCapturedUpdate(workInProgress, _update, renderExpirationTime);
          return;
        }
        break;
      default:
        break;
    }
    workInProgress = workInProgress.return;
  } while (workInProgress !== null);
}

function unwindWork(workInProgress, renderIsExpired, renderExpirationTime) {
  if (enableProfilerTimer) {
    if (workInProgress.mode & ProfileMode) {
      recordElapsedActualRenderTime(workInProgress);
    }
  }

  switch (workInProgress.tag) {
    case ClassComponent:
      {
        popContextProvider(workInProgress);
        var effectTag = workInProgress.effectTag;
        if (effectTag & ShouldCapture) {
          workInProgress.effectTag = effectTag & ~ShouldCapture | DidCapture;
          return workInProgress;
        }
        return null;
      }
    case HostRoot:
      {
        popHostContainer(workInProgress);
        popTopLevelContextObject(workInProgress);
        var _effectTag = workInProgress.effectTag;
        if (_effectTag & ShouldCapture) {
          workInProgress.effectTag = _effectTag & ~ShouldCapture | DidCapture;
          return workInProgress;
        }
        return null;
      }
    case HostComponent:
      {
        popHostContext(workInProgress);
        return null;
      }
    case TimeoutComponent:
      {
        var _effectTag2 = workInProgress.effectTag;
        if (_effectTag2 & ShouldCapture) {
          workInProgress.effectTag = _effectTag2 & ~ShouldCapture | DidCapture;
          return workInProgress;
        }
        return null;
      }
    case HostPortal:
      popHostContainer(workInProgress);
      return null;
    case ContextProvider:
      popProvider(workInProgress);
      return null;
    default:
      return null;
  }
}

function unwindInterruptedWork(interruptedWork) {
  if (enableProfilerTimer) {
    if (interruptedWork.mode & ProfileMode) {
      // Resume in case we're picking up on work that was paused.
      resumeActualRenderTimerIfPaused();
      recordElapsedActualRenderTime(interruptedWork);
    }
  }

  switch (interruptedWork.tag) {
    case ClassComponent:
      {
        popContextProvider(interruptedWork);
        break;
      }
    case HostRoot:
      {
        popHostContainer(interruptedWork);
        popTopLevelContextObject(interruptedWork);
        break;
      }
    case HostComponent:
      {
        popHostContext(interruptedWork);
        break;
      }
    case HostPortal:
      popHostContainer(interruptedWork);
      break;
    case ContextProvider:
      popProvider(interruptedWork);
      break;
    default:
      break;
  }
}

var invokeGuardedCallback$2 = ReactErrorUtils.invokeGuardedCallback;
var hasCaughtError = ReactErrorUtils.hasCaughtError;
var clearCaughtError = ReactErrorUtils.clearCaughtError;


var didWarnAboutStateTransition = void 0;
var didWarnSetStateChildContext = void 0;
var warnAboutUpdateOnUnmounted = void 0;
var warnAboutInvalidUpdates = void 0;

{
  didWarnAboutStateTransition = false;
  didWarnSetStateChildContext = false;
  var didWarnStateUpdateForUnmountedComponent = {};

  warnAboutUpdateOnUnmounted = function (fiber) {
    // We show the whole stack but dedupe on the top component's name because
    // the problematic code almost always lies inside that component.
    var componentName = getComponentName(fiber) || 'ReactClass';
    if (didWarnStateUpdateForUnmountedComponent[componentName]) {
      return;
    }
    warning(false, "Can't call setState (or forceUpdate) on an unmounted component. This " + 'is a no-op, but it indicates a memory leak in your application. To ' + 'fix, cancel all subscriptions and asynchronous tasks in the ' + 'componentWillUnmount method.%s', getStackAddendumByWorkInProgressFiber(fiber));
    didWarnStateUpdateForUnmountedComponent[componentName] = true;
  };

  warnAboutInvalidUpdates = function (instance) {
    switch (ReactDebugCurrentFiber.phase) {
      case 'getChildContext':
        if (didWarnSetStateChildContext) {
          return;
        }
        warning(false, 'setState(...): Cannot call setState() inside getChildContext()');
        didWarnSetStateChildContext = true;
        break;
      case 'render':
        if (didWarnAboutStateTransition) {
          return;
        }
        warning(false, 'Cannot update during an existing state transition (such as within ' + "`render` or another component's constructor). Render methods should " + 'be a pure function of props and state; constructor side-effects are ' + 'an anti-pattern, but can be moved to `componentWillMount`.');
        didWarnAboutStateTransition = true;
        break;
    }
  };
}

// Represents the current time in ms.
var originalStartTimeMs = now();
var mostRecentCurrentTime = msToExpirationTime(0);
var mostRecentCurrentTimeMs = originalStartTimeMs;

// Used to ensure computeUniqueAsyncExpiration is monotonically increases.
var lastUniqueAsyncExpiration = 0;

// Represents the expiration time that incoming updates should use. (If this
// is NoWork, use the default strategy: async updates in async mode, sync
// updates in sync mode.)
var expirationContext = NoWork;

var isWorking = false;

// The next work in progress fiber that we're currently working on.
var nextUnitOfWork = null;
var nextRoot = null;
// The time at which we're currently rendering work.
var nextRenderExpirationTime = NoWork;
var nextLatestTimeoutMs = -1;
var nextRenderIsExpired = false;

// The next fiber with an effect that we're currently committing.
var nextEffect = null;

var isCommitting$1 = false;

var isRootReadyForCommit = false;

var legacyErrorBoundariesThatAlreadyFailed = null;

// Used for performance tracking.
var interruptedBy = null;

var stashedWorkInProgressProperties = void 0;
var replayUnitOfWork = void 0;
var isReplayingFailedUnitOfWork = void 0;
var originalReplayError = void 0;
var rethrowOriginalError = void 0;
if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
  stashedWorkInProgressProperties = null;
  isReplayingFailedUnitOfWork = false;
  originalReplayError = null;
  replayUnitOfWork = function (failedUnitOfWork, thrownValue, isAsync) {
    if (thrownValue !== null && typeof thrownValue === 'object' && typeof thrownValue.then === 'function') {
      // Don't replay promises. Treat everything else like an error.
      // TODO: Need to figure out a different strategy if/when we add
      // support for catching other types.
      return;
    }

    // Restore the original state of the work-in-progress
    if (stashedWorkInProgressProperties === null) {
      // This should never happen. Don't throw because this code is DEV-only.
      warning(false, 'Could not replay rendering after an error. This is likely a bug in React. ' + 'Please file an issue.');
      return;
    }
    assignFiberPropertiesInDEV(failedUnitOfWork, stashedWorkInProgressProperties);

    switch (failedUnitOfWork.tag) {
      case HostRoot:
        popHostContainer(failedUnitOfWork);
        popTopLevelContextObject(failedUnitOfWork);
        break;
      case HostComponent:
        popHostContext(failedUnitOfWork);
        break;
      case ClassComponent:
        popContextProvider(failedUnitOfWork);
        break;
      case HostPortal:
        popHostContainer(failedUnitOfWork);
        break;
      case ContextProvider:
        popProvider(failedUnitOfWork);
        break;
    }
    // Replay the begin phase.
    isReplayingFailedUnitOfWork = true;
    originalReplayError = thrownValue;
    invokeGuardedCallback$2(null, workLoop, null, isAsync);
    isReplayingFailedUnitOfWork = false;
    originalReplayError = null;
    if (hasCaughtError()) {
      clearCaughtError();

      if (enableProfilerTimer) {
        if (failedUnitOfWork.mode & ProfileMode) {
          recordElapsedActualRenderTime(failedUnitOfWork);
        }

        // Stop "base" render timer again (after the re-thrown error).
        stopBaseRenderTimerIfRunning();
      }
    } else {
      // If the begin phase did not fail the second time, set this pointer
      // back to the original value.
      nextUnitOfWork = failedUnitOfWork;
    }
  };
  rethrowOriginalError = function () {
    throw originalReplayError;
  };
}

function resetStack() {
  if (nextUnitOfWork !== null) {
    var interruptedWork = nextUnitOfWork.return;
    while (interruptedWork !== null) {
      unwindInterruptedWork(interruptedWork);
      interruptedWork = interruptedWork.return;
    }
  }

  {
    ReactStrictModeWarnings.discardPendingWarnings();
    checkThatStackIsEmpty();
  }

  nextRoot = null;
  nextRenderExpirationTime = NoWork;
  nextLatestTimeoutMs = -1;
  nextRenderIsExpired = false;
  nextUnitOfWork = null;

  isRootReadyForCommit = false;
}

function commitAllHostEffects() {
  while (nextEffect !== null) {
    {
      ReactDebugCurrentFiber.setCurrentFiber(nextEffect);
    }
    recordEffect();

    var effectTag = nextEffect.effectTag;

    if (effectTag & ContentReset) {
      commitResetTextContent(nextEffect);
    }

    if (effectTag & Ref) {
      var current = nextEffect.alternate;
      if (current !== null) {
        commitDetachRef(current);
      }
    }

    // The following switch statement is only concerned about placement,
    // updates, and deletions. To avoid needing to add a case for every
    // possible bitmap value, we remove the secondary effects from the
    // effect tag and switch on that value.
    var primaryEffectTag = effectTag & (Placement | Update | Deletion);
    switch (primaryEffectTag) {
      case Placement:
        {
          commitPlacement(nextEffect);
          // Clear the "placement" from effect tag so that we know that this is inserted, before
          // any life-cycles like componentDidMount gets called.
          // TODO: findDOMNode doesn't rely on this any more but isMounted
          // does and isMounted is deprecated anyway so we should be able
          // to kill this.
          nextEffect.effectTag &= ~Placement;
          break;
        }
      case PlacementAndUpdate:
        {
          // Placement
          commitPlacement(nextEffect);
          // Clear the "placement" from effect tag so that we know that this is inserted, before
          // any life-cycles like componentDidMount gets called.
          nextEffect.effectTag &= ~Placement;

          // Update
          var _current = nextEffect.alternate;
          commitWork(_current, nextEffect);
          break;
        }
      case Update:
        {
          var _current2 = nextEffect.alternate;
          commitWork(_current2, nextEffect);
          break;
        }
      case Deletion:
        {
          commitDeletion(nextEffect);
          break;
        }
    }
    nextEffect = nextEffect.nextEffect;
  }

  {
    ReactDebugCurrentFiber.resetCurrentFiber();
  }
}

function commitBeforeMutationLifecycles() {
  while (nextEffect !== null) {
    var effectTag = nextEffect.effectTag;

    if (effectTag & Snapshot) {
      recordEffect();
      var current = nextEffect.alternate;
      commitBeforeMutationLifeCycles(current, nextEffect);
    }

    // Don't cleanup effects yet;
    // This will be done by commitAllLifeCycles()
    nextEffect = nextEffect.nextEffect;
  }
}

function commitAllLifeCycles(finishedRoot, currentTime, committedExpirationTime) {
  {
    ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();

    if (warnAboutDeprecatedLifecycles) {
      ReactStrictModeWarnings.flushPendingDeprecationWarnings();
    }

    if (warnAboutLegacyContextAPI) {
      ReactStrictModeWarnings.flushLegacyContextWarning();
    }
  }
  while (nextEffect !== null) {
    var effectTag = nextEffect.effectTag;

    if (effectTag & (Update | Callback)) {
      recordEffect();
      var current = nextEffect.alternate;
      commitLifeCycles(finishedRoot, current, nextEffect, currentTime, committedExpirationTime);
    }

    if (effectTag & Ref) {
      recordEffect();
      commitAttachRef(nextEffect);
    }

    var next = nextEffect.nextEffect;
    // Ensure that we clean these up so that we don't accidentally keep them.
    // I'm not actually sure this matters because we can't reset firstEffect
    // and lastEffect since they're on every node, not just the effectful
    // ones. So we have to clean everything as we reuse nodes anyway.
    nextEffect.nextEffect = null;
    // Ensure that we reset the effectTag here so that we can rely on effect
    // tags to reason about the current life-cycle.
    nextEffect = next;
  }
}

function isAlreadyFailedLegacyErrorBoundary(instance) {
  return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
}

function markLegacyErrorBoundaryAsFailed(instance) {
  if (legacyErrorBoundariesThatAlreadyFailed === null) {
    legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
  } else {
    legacyErrorBoundariesThatAlreadyFailed.add(instance);
  }
}

function commitRoot(finishedWork) {
  isWorking = true;
  isCommitting$1 = true;
  startCommitTimer();

  var root = finishedWork.stateNode;
  !(root.current !== finishedWork) ? invariant(false, 'Cannot commit the same tree as before. This is probably a bug related to the return field. This error is likely caused by a bug in React. Please file an issue.') : void 0;
  var committedExpirationTime = root.pendingCommitExpirationTime;
  !(committedExpirationTime !== NoWork) ? invariant(false, 'Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue.') : void 0;
  root.pendingCommitExpirationTime = NoWork;

  var currentTime = recalculateCurrentTime();

  // Reset this to null before calling lifecycles
  ReactCurrentOwner.current = null;

  var firstEffect = void 0;
  if (finishedWork.effectTag > PerformedWork) {
    // A fiber's effect list consists only of its children, not itself. So if
    // the root has an effect, we need to add it to the end of the list. The
    // resulting list is the set that would belong to the root's parent, if
    // it had one; that is, all the effects in the tree including the root.
    if (finishedWork.lastEffect !== null) {
      finishedWork.lastEffect.nextEffect = finishedWork;
      firstEffect = finishedWork.firstEffect;
    } else {
      firstEffect = finishedWork;
    }
  } else {
    // There is no effect on the root.
    firstEffect = finishedWork.firstEffect;
  }

  prepareForCommit(root.containerInfo);

  // Invoke instances of getSnapshotBeforeUpdate before mutation.
  nextEffect = firstEffect;
  startCommitSnapshotEffectsTimer();
  while (nextEffect !== null) {
    var didError = false;
    var error = void 0;
    {
      invokeGuardedCallback$2(null, commitBeforeMutationLifecycles, null);
      if (hasCaughtError()) {
        didError = true;
        error = clearCaughtError();
      }
    }
    if (didError) {
      !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0;
      captureCommitPhaseError(nextEffect, error);
      // Clean-up
      if (nextEffect !== null) {
        nextEffect = nextEffect.nextEffect;
      }
    }
  }
  stopCommitSnapshotEffectsTimer();

  if (enableProfilerTimer) {
    // Mark the current commit time to be shared by all Profilers in this batch.
    // This enables them to be grouped later.
    recordCommitTime();
  }

  // Commit all the side-effects within a tree. We'll do this in two passes.
  // The first pass performs all the host insertions, updates, deletions and
  // ref unmounts.
  nextEffect = firstEffect;
  startCommitHostEffectsTimer();
  while (nextEffect !== null) {
    var _didError = false;
    var _error = void 0;
    {
      invokeGuardedCallback$2(null, commitAllHostEffects, null);
      if (hasCaughtError()) {
        _didError = true;
        _error = clearCaughtError();
      }
    }
    if (_didError) {
      !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0;
      captureCommitPhaseError(nextEffect, _error);
      // Clean-up
      if (nextEffect !== null) {
        nextEffect = nextEffect.nextEffect;
      }
    }
  }
  stopCommitHostEffectsTimer();

  resetAfterCommit(root.containerInfo);

  // The work-in-progress tree is now the current tree. This must come after
  // the first pass of the commit phase, so that the previous tree is still
  // current during componentWillUnmount, but before the second pass, so that
  // the finished work is current during componentDidMount/Update.
  root.current = finishedWork;

  // In the second pass we'll perform all life-cycles and ref callbacks.
  // Life-cycles happen as a separate pass so that all placements, updates,
  // and deletions in the entire tree have already been invoked.
  // This pass also triggers any renderer-specific initial effects.
  nextEffect = firstEffect;
  startCommitLifeCyclesTimer();
  while (nextEffect !== null) {
    var _didError2 = false;
    var _error2 = void 0;
    {
      invokeGuardedCallback$2(null, commitAllLifeCycles, null, root, currentTime, committedExpirationTime);
      if (hasCaughtError()) {
        _didError2 = true;
        _error2 = clearCaughtError();
      }
    }
    if (_didError2) {
      !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0;
      captureCommitPhaseError(nextEffect, _error2);
      if (nextEffect !== null) {
        nextEffect = nextEffect.nextEffect;
      }
    }
  }

  if (enableProfilerTimer) {
    {
      checkActualRenderTimeStackEmpty();
    }
    resetActualRenderTimer();
  }

  isCommitting$1 = false;
  isWorking = false;
  stopCommitLifeCyclesTimer();
  stopCommitTimer();
  if (typeof onCommitRoot === 'function') {
    onCommitRoot(finishedWork.stateNode);
  }
  if (true && ReactFiberInstrumentation_1.debugTool) {
    ReactFiberInstrumentation_1.debugTool.onCommitWork(finishedWork);
  }

  markCommittedPriorityLevels(root, currentTime, root.current.expirationTime);
  var remainingTime = findNextPendingPriorityLevel(root);
  if (remainingTime === NoWork) {
    // If there's no remaining work, we can clear the set of already failed
    // error boundaries.
    legacyErrorBoundariesThatAlreadyFailed = null;
  }
  return remainingTime;
}

function resetExpirationTime(workInProgress, renderTime) {
  if (renderTime !== Never && workInProgress.expirationTime === Never) {
    // The children of this component are hidden. Don't bubble their
    // expiration times.
    return;
  }

  // Check for pending updates.
  var newExpirationTime = NoWork;
  switch (workInProgress.tag) {
    case HostRoot:
    case ClassComponent:
      {
        var updateQueue = workInProgress.updateQueue;
        if (updateQueue !== null) {
          newExpirationTime = updateQueue.expirationTime;
        }
      }
  }

  // TODO: Calls need to visit stateNode

  // Bubble up the earliest expiration time.
  // (And "base" render timers if that feature flag is enabled)
  if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
    var treeBaseTime = workInProgress.selfBaseTime;
    var child = workInProgress.child;
    while (child !== null) {
      treeBaseTime += child.treeBaseTime;
      if (child.expirationTime !== NoWork && (newExpirationTime === NoWork || newExpirationTime > child.expirationTime)) {
        newExpirationTime = child.expirationTime;
      }
      child = child.sibling;
    }
    workInProgress.treeBaseTime = treeBaseTime;
  } else {
    var _child = workInProgress.child;
    while (_child !== null) {
      if (_child.expirationTime !== NoWork && (newExpirationTime === NoWork || newExpirationTime > _child.expirationTime)) {
        newExpirationTime = _child.expirationTime;
      }
      _child = _child.sibling;
    }
  }

  workInProgress.expirationTime = newExpirationTime;
}

function completeUnitOfWork(workInProgress) {
  // Attempt to complete the current unit of work, then move to the
  // next sibling. If there are no more siblings, return to the
  // parent fiber.
  while (true) {
    // The current, flushed, state of this fiber is the alternate.
    // Ideally nothing should rely on this, but relying on it here
    // means that we don't need an additional field on the work in
    // progress.
    var current = workInProgress.alternate;
    {
      ReactDebugCurrentFiber.setCurrentFiber(workInProgress);
    }

    var returnFiber = workInProgress.return;
    var siblingFiber = workInProgress.sibling;

    if ((workInProgress.effectTag & Incomplete) === NoEffect) {
      // This fiber completed.
      var next = completeWork(current, workInProgress, nextRenderExpirationTime);
      stopWorkTimer(workInProgress);
      resetExpirationTime(workInProgress, nextRenderExpirationTime);
      {
        ReactDebugCurrentFiber.resetCurrentFiber();
      }

      if (next !== null) {
        stopWorkTimer(workInProgress);
        if (true && ReactFiberInstrumentation_1.debugTool) {
          ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
        }
        // If completing this work spawned new work, do that next. We'll come
        // back here again.
        return next;
      }

      if (returnFiber !== null &&
      // Do not append effects to parents if a sibling failed to complete
      (returnFiber.effectTag & Incomplete) === NoEffect) {
        // Append all the effects of the subtree and this fiber onto the effect
        // list of the parent. The completion order of the children affects the
        // side-effect order.
        if (returnFiber.firstEffect === null) {
          returnFiber.firstEffect = workInProgress.firstEffect;
        }
        if (workInProgress.lastEffect !== null) {
          if (returnFiber.lastEffect !== null) {
            returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;
          }
          returnFiber.lastEffect = workInProgress.lastEffect;
        }

        // If this fiber had side-effects, we append it AFTER the children's
        // side-effects. We can perform certain side-effects earlier if
        // needed, by doing multiple passes over the effect list. We don't want
        // to schedule our own side-effect on our own list because if end up
        // reusing children we'll schedule this effect onto itself since we're
        // at the end.
        var effectTag = workInProgress.effectTag;
        // Skip both NoWork and PerformedWork tags when creating the effect list.
        // PerformedWork effect is read by React DevTools but shouldn't be committed.
        if (effectTag > PerformedWork) {
          if (returnFiber.lastEffect !== null) {
            returnFiber.lastEffect.nextEffect = workInProgress;
          } else {
            returnFiber.firstEffect = workInProgress;
          }
          returnFiber.lastEffect = workInProgress;
        }
      }

      if (true && ReactFiberInstrumentation_1.debugTool) {
        ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
      }

      if (siblingFiber !== null) {
        // If there is more work to do in this returnFiber, do that next.
        return siblingFiber;
      } else if (returnFiber !== null) {
        // If there's no more work in this returnFiber. Complete the returnFiber.
        workInProgress = returnFiber;
        continue;
      } else {
        // We've reached the root.
        isRootReadyForCommit = true;
        return null;
      }
    } else {
      // This fiber did not complete because something threw. Pop values off
      // the stack without entering the complete phase. If this is a boundary,
      // capture values if possible.
      var _next = unwindWork(workInProgress, nextRenderIsExpired, nextRenderExpirationTime);
      // Because this fiber did not complete, don't reset its expiration time.
      if (workInProgress.effectTag & DidCapture) {
        // Restarting an error boundary
        stopFailedWorkTimer(workInProgress);
      } else {
        stopWorkTimer(workInProgress);
      }

      {
        ReactDebugCurrentFiber.resetCurrentFiber();
      }

      if (_next !== null) {
        stopWorkTimer(workInProgress);
        if (true && ReactFiberInstrumentation_1.debugTool) {
          ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
        }
        // If completing this work spawned new work, do that next. We'll come
        // back here again.
        // Since we're restarting, remove anything that is not a host effect
        // from the effect tag.
        _next.effectTag &= HostEffectMask;
        return _next;
      }

      if (returnFiber !== null) {
        // Mark the parent fiber as incomplete and clear its effect list.
        returnFiber.firstEffect = returnFiber.lastEffect = null;
        returnFiber.effectTag |= Incomplete;
      }

      if (true && ReactFiberInstrumentation_1.debugTool) {
        ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
      }

      if (siblingFiber !== null) {
        // If there is more work to do in this returnFiber, do that next.
        return siblingFiber;
      } else if (returnFiber !== null) {
        // If there's no more work in this returnFiber. Complete the returnFiber.
        workInProgress = returnFiber;
        continue;
      } else {
        return null;
      }
    }
  }

  // Without this explicit null return Flow complains of invalid return type
  // TODO Remove the above while(true) loop
  // eslint-disable-next-line no-unreachable
  return null;
}

function performUnitOfWork(workInProgress) {
  // The current, flushed, state of this fiber is the alternate.
  // Ideally nothing should rely on this, but relying on it here
  // means that we don't need an additional field on the work in
  // progress.
  var current = workInProgress.alternate;

  // See if beginning this work spawns more work.
  startWorkTimer(workInProgress);
  {
    ReactDebugCurrentFiber.setCurrentFiber(workInProgress);
  }

  if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
    stashedWorkInProgressProperties = assignFiberPropertiesInDEV(stashedWorkInProgressProperties, workInProgress);
  }

  var next = void 0;
  if (enableProfilerTimer) {
    if (workInProgress.mode & ProfileMode) {
      startBaseRenderTimer();
    }

    next = beginWork(current, workInProgress, nextRenderExpirationTime);

    if (workInProgress.mode & ProfileMode) {
      // Update "base" time if the render wasn't bailed out on.
      recordElapsedBaseRenderTimeIfRunning(workInProgress);
      stopBaseRenderTimerIfRunning();
    }
  } else {
    next = beginWork(current, workInProgress, nextRenderExpirationTime);
  }

  {
    ReactDebugCurrentFiber.resetCurrentFiber();
    if (isReplayingFailedUnitOfWork) {
      // Currently replaying a failed unit of work. This should be unreachable,
      // because the render phase is meant to be idempotent, and it should
      // have thrown again. Since it didn't, rethrow the original error, so
      // React's internal stack is not misaligned.
      rethrowOriginalError();
    }
  }
  if (true && ReactFiberInstrumentation_1.debugTool) {
    ReactFiberInstrumentation_1.debugTool.onBeginWork(workInProgress);
  }

  if (next === null) {
    // If this doesn't spawn new work, complete the current work.
    next = completeUnitOfWork(workInProgress);
  }

  ReactCurrentOwner.current = null;

  return next;
}

function workLoop(isAsync) {
  if (!isAsync) {
    // Flush all expired work.
    while (nextUnitOfWork !== null) {
      nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
    }
  } else {
    // Flush asynchronous work until the deadline runs out of time.
    while (nextUnitOfWork !== null && !shouldYield()) {
      nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
    }

    if (enableProfilerTimer) {
      // If we didn't finish, pause the "actual" render timer.
      // We'll restart it when we resume work.
      pauseActualRenderTimerIfRunning();
    }
  }
}

function renderRoot(root, expirationTime, isAsync) {
  !!isWorking ? invariant(false, 'renderRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.') : void 0;
  isWorking = true;

  // Check if we're starting from a fresh stack, or if we're resuming from
  // previously yielded work.
  if (expirationTime !== nextRenderExpirationTime || root !== nextRoot || nextUnitOfWork === null) {
    // Reset the stack and start working from the root.
    resetStack();
    nextRoot = root;
    nextRenderExpirationTime = expirationTime;
    nextLatestTimeoutMs = -1;
    nextUnitOfWork = createWorkInProgress(nextRoot.current, null, nextRenderExpirationTime);
    root.pendingCommitExpirationTime = NoWork;
  }

  var didFatal = false;

  nextRenderIsExpired = !isAsync || nextRenderExpirationTime <= mostRecentCurrentTime;

  startWorkLoopTimer(nextUnitOfWork);

  do {
    try {
      workLoop(isAsync);
    } catch (thrownValue) {
      if (enableProfilerTimer) {
        // Stop "base" render timer in the event of an error.
        stopBaseRenderTimerIfRunning();
      }

      if (nextUnitOfWork === null) {
        // This is a fatal error.
        didFatal = true;
        onUncaughtError(thrownValue);
      } else {
        {
          // Reset global debug state
          // We assume this is defined in DEV
          resetCurrentlyProcessingQueue();
        }

        var failedUnitOfWork = nextUnitOfWork;
        if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
          replayUnitOfWork(failedUnitOfWork, thrownValue, isAsync);
        }

        // TODO: we already know this isn't true in some cases.
        // At least this shows a nicer error message until we figure out the cause.
        // https://github.com/facebook/react/issues/12449#issuecomment-386727431
        !(nextUnitOfWork !== null) ? invariant(false, 'Failed to replay rendering after an error. This is likely caused by a bug in React. Please file an issue with a reproducing case to help us find it.') : void 0;

        var sourceFiber = nextUnitOfWork;
        var returnFiber = sourceFiber.return;
        if (returnFiber === null) {
          // This is the root. The root could capture its own errors. However,
          // we don't know if it errors before or after we pushed the host
          // context. This information is needed to avoid a stack mismatch.
          // Because we're not sure, treat this as a fatal error. We could track
          // which phase it fails in, but doesn't seem worth it. At least
          // for now.
          didFatal = true;
          onUncaughtError(thrownValue);
          break;
        }
        throwException(root, returnFiber, sourceFiber, thrownValue, nextRenderIsExpired, nextRenderExpirationTime, mostRecentCurrentTimeMs);
        nextUnitOfWork = completeUnitOfWork(sourceFiber);
      }
    }
    break;
  } while (true);

  // We're done performing work. Time to clean up.
  var didCompleteRoot = false;
  isWorking = false;

  // Yield back to main thread.
  if (didFatal) {
    stopWorkLoopTimer(interruptedBy, didCompleteRoot);
    interruptedBy = null;
    // There was a fatal error.
    {
      resetStackAfterFatalErrorInDev();
    }
    return null;
  } else if (nextUnitOfWork === null) {
    // We reached the root.
    if (isRootReadyForCommit) {
      didCompleteRoot = true;
      stopWorkLoopTimer(interruptedBy, didCompleteRoot);
      interruptedBy = null;
      // The root successfully completed. It's ready for commit.
      root.pendingCommitExpirationTime = expirationTime;
      var finishedWork = root.current.alternate;
      return finishedWork;
    } else {
      // The root did not complete.
      stopWorkLoopTimer(interruptedBy, didCompleteRoot);
      interruptedBy = null;
      !!nextRenderIsExpired ? invariant(false, 'Expired work should have completed. This error is likely caused by a bug in React. Please file an issue.') : void 0;
      markSuspendedPriorityLevel(root, expirationTime);
      if (nextLatestTimeoutMs >= 0) {
        setTimeout(function () {
          retrySuspendedRoot(root, expirationTime);
        }, nextLatestTimeoutMs);
      }
      var firstUnblockedExpirationTime = findNextPendingPriorityLevel(root);
      onBlock(firstUnblockedExpirationTime);
      return null;
    }
  } else {
    stopWorkLoopTimer(interruptedBy, didCompleteRoot);
    interruptedBy = null;
    // There's more work to do, but we ran out of time. Yield back to
    // the renderer.
    return null;
  }
}

function dispatch(sourceFiber, value, expirationTime) {
  !(!isWorking || isCommitting$1) ? invariant(false, 'dispatch: Cannot dispatch during the render phase.') : void 0;

  var fiber = sourceFiber.return;
  while (fiber !== null) {
    switch (fiber.tag) {
      case ClassComponent:
        var ctor = fiber.type;
        var instance = fiber.stateNode;
        if (typeof ctor.getDerivedStateFromCatch === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {
          var errorInfo = createCapturedValue(value, sourceFiber);
          var update = createClassErrorUpdate(fiber, errorInfo, expirationTime);
          enqueueUpdate(fiber, update, expirationTime);
          scheduleWork$1(fiber, expirationTime);
          return;
        }
        break;
      case HostRoot:
        {
          var _errorInfo = createCapturedValue(value, sourceFiber);
          var _update = createRootErrorUpdate(fiber, _errorInfo, expirationTime);
          enqueueUpdate(fiber, _update, expirationTime);
          scheduleWork$1(fiber, expirationTime);
          return;
        }
    }
    fiber = fiber.return;
  }

  if (sourceFiber.tag === HostRoot) {
    // Error was thrown at the root. There is no parent, so the root
    // itself should capture it.
    var rootFiber = sourceFiber;
    var _errorInfo2 = createCapturedValue(value, rootFiber);
    var _update2 = createRootErrorUpdate(rootFiber, _errorInfo2, expirationTime);
    enqueueUpdate(rootFiber, _update2, expirationTime);
    scheduleWork$1(rootFiber, expirationTime);
  }
}

function captureCommitPhaseError(fiber, error) {
  return dispatch(fiber, error, Sync);
}

function computeAsyncExpiration(currentTime) {
  // Given the current clock time, returns an expiration time. We use rounding
  // to batch like updates together.
  // Should complete within ~5000ms. 5250ms max.
  var expirationMs = 5000;
  var bucketSizeMs = 250;
  return computeExpirationBucket(currentTime, expirationMs, bucketSizeMs);
}

function computeInteractiveExpiration(currentTime) {
  var expirationMs = void 0;
  // We intentionally set a higher expiration time for interactive updates in
  // dev than in production.
  // If the main thread is being blocked so long that you hit the expiration,
  // it's a problem that could be solved with better scheduling.
  // People will be more likely to notice this and fix it with the long
  // expiration time in development.
  // In production we opt for better UX at the risk of masking scheduling
  // problems, by expiring fast.
  {
    // Should complete within ~500ms. 600ms max.
    expirationMs = 500;
  }
  var bucketSizeMs = 100;
  return computeExpirationBucket(currentTime, expirationMs, bucketSizeMs);
}

// Creates a unique async expiration time.
function computeUniqueAsyncExpiration() {
  var currentTime = recalculateCurrentTime();
  var result = computeAsyncExpiration(currentTime);
  if (result <= lastUniqueAsyncExpiration) {
    // Since we assume the current time monotonically increases, we only hit
    // this branch when computeUniqueAsyncExpiration is fired multiple times
    // within a 200ms window (or whatever the async bucket size is).
    result = lastUniqueAsyncExpiration + 1;
  }
  lastUniqueAsyncExpiration = result;
  return lastUniqueAsyncExpiration;
}

function computeExpirationForFiber(currentTime, fiber) {
  var expirationTime = void 0;
  if (expirationContext !== NoWork) {
    // An explicit expiration context was set;
    expirationTime = expirationContext;
  } else if (isWorking) {
    if (isCommitting$1) {
      // Updates that occur during the commit phase should have sync priority
      // by default.
      expirationTime = Sync;
    } else {
      // Updates during the render phase should expire at the same time as
      // the work that is being rendered.
      expirationTime = nextRenderExpirationTime;
    }
  } else {
    // No explicit expiration context was set, and we're not currently
    // performing work. Calculate a new expiration time.
    if (fiber.mode & AsyncMode) {
      if (isBatchingInteractiveUpdates) {
        // This is an interactive update
        expirationTime = computeInteractiveExpiration(currentTime);
      } else {
        // This is an async update
        expirationTime = computeAsyncExpiration(currentTime);
      }
    } else {
      // This is a sync update
      expirationTime = Sync;
    }
  }
  if (isBatchingInteractiveUpdates) {
    // This is an interactive update. Keep track of the lowest pending
    // interactive expiration time. This allows us to synchronously flush
    // all interactive updates when needed.
    if (lowestPendingInteractiveExpirationTime === NoWork || expirationTime > lowestPendingInteractiveExpirationTime) {
      lowestPendingInteractiveExpirationTime = expirationTime;
    }
  }
  return expirationTime;
}

// TODO: Rename this to scheduleTimeout or something
function suspendRoot(root, thenable, timeoutMs, suspendedTime) {
  // Schedule the timeout.
  if (timeoutMs >= 0 && nextLatestTimeoutMs < timeoutMs) {
    nextLatestTimeoutMs = timeoutMs;
  }
}

function retrySuspendedRoot(root, suspendedTime) {
  markPingedPriorityLevel(root, suspendedTime);
  var retryTime = findNextPendingPriorityLevel(root);
  if (retryTime !== NoWork) {
    requestRetry(root, retryTime);
  }
}

function scheduleWork$1(fiber, expirationTime) {
  recordScheduleUpdate();

  {
    if (fiber.tag === ClassComponent) {
      var instance = fiber.stateNode;
      warnAboutInvalidUpdates(instance);
    }
  }

  var node = fiber;
  while (node !== null) {
    // Walk the parent path to the root and update each node's
    // expiration time.
    if (node.expirationTime === NoWork || node.expirationTime > expirationTime) {
      node.expirationTime = expirationTime;
    }
    if (node.alternate !== null) {
      if (node.alternate.expirationTime === NoWork || node.alternate.expirationTime > expirationTime) {
        node.alternate.expirationTime = expirationTime;
      }
    }
    if (node.return === null) {
      if (node.tag === HostRoot) {
        var root = node.stateNode;
        if (!isWorking && nextRenderExpirationTime !== NoWork && expirationTime < nextRenderExpirationTime) {
          // This is an interruption. (Used for performance tracking.)
          interruptedBy = fiber;
          resetStack();
        }
        markPendingPriorityLevel(root, expirationTime);
        var nextExpirationTimeToWorkOn = findNextPendingPriorityLevel(root);
        if (
        // If we're in the render phase, we don't need to schedule this root
        // for an update, because we'll do it before we exit...
        !isWorking || isCommitting$1 ||
        // ...unless this is a different root than the one we're rendering.
        nextRoot !== root) {
          requestWork(root, nextExpirationTimeToWorkOn);
        }
        if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
          invariant(false, 'Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.');
        }
      } else {
        {
          if (fiber.tag === ClassComponent) {
            warnAboutUpdateOnUnmounted(fiber);
          }
        }
        return;
      }
    }
    node = node.return;
  }
}

function recalculateCurrentTime() {
  // Subtract initial time so it fits inside 32bits
  mostRecentCurrentTimeMs = now() - originalStartTimeMs;
  mostRecentCurrentTime = msToExpirationTime(mostRecentCurrentTimeMs);
  return mostRecentCurrentTime;
}

function deferredUpdates(fn) {
  var previousExpirationContext = expirationContext;
  var currentTime = recalculateCurrentTime();
  expirationContext = computeAsyncExpiration(currentTime);
  try {
    return fn();
  } finally {
    expirationContext = previousExpirationContext;
  }
}
function syncUpdates(fn, a, b, c, d) {
  var previousExpirationContext = expirationContext;
  expirationContext = Sync;
  try {
    return fn(a, b, c, d);
  } finally {
    expirationContext = previousExpirationContext;
  }
}

// TODO: Everything below this is written as if it has been lifted to the
// renderers. I'll do this in a follow-up.

// Linked-list of roots
var firstScheduledRoot = null;
var lastScheduledRoot = null;

var callbackExpirationTime = NoWork;
var callbackID = void 0;
var isRendering = false;
var nextFlushedRoot = null;
var nextFlushedExpirationTime = NoWork;
var lowestPendingInteractiveExpirationTime = NoWork;
var deadlineDidExpire = false;
var hasUnhandledError = false;
var unhandledError = null;
var deadline = null;

var isBatchingUpdates = false;
var isUnbatchingUpdates = false;
var isBatchingInteractiveUpdates = false;

var completedBatches = null;

// Use these to prevent an infinite loop of nested updates
var NESTED_UPDATE_LIMIT = 1000;
var nestedUpdateCount = 0;

var timeHeuristicForUnitOfWork = 1;

function scheduleCallbackWithExpiration(expirationTime) {
  if (callbackExpirationTime !== NoWork) {
    // A callback is already scheduled. Check its expiration time (timeout).
    if (expirationTime > callbackExpirationTime) {
      // Existing callback has sufficient timeout. Exit.
      return;
    } else {
      if (callbackID !== null) {
        // Existing callback has insufficient timeout. Cancel and schedule a
        // new one.
        cancelDeferredCallback(callbackID);
      }
    }
    // The request callback timer is already running. Don't start a new one.
  } else {
    startRequestCallbackTimer();
  }

  // Compute a timeout for the given expiration time.
  var currentMs = now() - originalStartTimeMs;
  var expirationMs = expirationTimeToMs(expirationTime);
  var timeout = expirationMs - currentMs;

  callbackExpirationTime = expirationTime;
  callbackID = scheduleDeferredCallback(performAsyncWork, { timeout: timeout });
}

function requestRetry(root, expirationTime) {
  if (root.remainingExpirationTime === NoWork || root.remainingExpirationTime < expirationTime) {
    // For a retry, only update the remaining expiration time if it has a
    // *lower priority* than the existing value. This is because, on a retry,
    // we should attempt to coalesce as much as possible.
    requestWork(root, expirationTime);
  }
}

// requestWork is called by the scheduler whenever a root receives an update.
// It's up to the renderer to call renderRoot at some point in the future.
function requestWork(root, expirationTime) {
  addRootToSchedule(root, expirationTime);

  if (isRendering) {
    // Prevent reentrancy. Remaining work will be scheduled at the end of
    // the currently rendering batch.
    return;
  }

  if (isBatchingUpdates) {
    // Flush work at the end of the batch.
    if (isUnbatchingUpdates) {
      // ...unless we're inside unbatchedUpdates, in which case we should
      // flush it now.
      nextFlushedRoot = root;
      nextFlushedExpirationTime = Sync;
      performWorkOnRoot(root, Sync, false);
    }
    return;
  }

  // TODO: Get rid of Sync and use current time?
  if (expirationTime === Sync) {
    performSyncWork();
  } else {
    scheduleCallbackWithExpiration(expirationTime);
  }
}

function addRootToSchedule(root, expirationTime) {
  // Add the root to the schedule.
  // Check if this root is already part of the schedule.
  if (root.nextScheduledRoot === null) {
    // This root is not already scheduled. Add it.
    root.remainingExpirationTime = expirationTime;
    if (lastScheduledRoot === null) {
      firstScheduledRoot = lastScheduledRoot = root;
      root.nextScheduledRoot = root;
    } else {
      lastScheduledRoot.nextScheduledRoot = root;
      lastScheduledRoot = root;
      lastScheduledRoot.nextScheduledRoot = firstScheduledRoot;
    }
  } else {
    // This root is already scheduled, but its priority may have increased.
    var remainingExpirationTime = root.remainingExpirationTime;
    if (remainingExpirationTime === NoWork || expirationTime < remainingExpirationTime) {
      // Update the priority.
      root.remainingExpirationTime = expirationTime;
    }
  }
}

function findHighestPriorityRoot() {
  var highestPriorityWork = NoWork;
  var highestPriorityRoot = null;
  if (lastScheduledRoot !== null) {
    var previousScheduledRoot = lastScheduledRoot;
    var root = firstScheduledRoot;
    while (root !== null) {
      var remainingExpirationTime = root.remainingExpirationTime;
      if (remainingExpirationTime === NoWork) {
        // This root no longer has work. Remove it from the scheduler.

        // TODO: This check is redudant, but Flow is confused by the branch
        // below where we set lastScheduledRoot to null, even though we break
        // from the loop right after.
        !(previousScheduledRoot !== null && lastScheduledRoot !== null) ? invariant(false, 'Should have a previous and last root. This error is likely caused by a bug in React. Please file an issue.') : void 0;
        if (root === root.nextScheduledRoot) {
          // This is the only root in the list.
          root.nextScheduledRoot = null;
          firstScheduledRoot = lastScheduledRoot = null;
          break;
        } else if (root === firstScheduledRoot) {
          // This is the first root in the list.
          var next = root.nextScheduledRoot;
          firstScheduledRoot = next;
          lastScheduledRoot.nextScheduledRoot = next;
          root.nextScheduledRoot = null;
        } else if (root === lastScheduledRoot) {
          // This is the last root in the list.
          lastScheduledRoot = previousScheduledRoot;
          lastScheduledRoot.nextScheduledRoot = firstScheduledRoot;
          root.nextScheduledRoot = null;
          break;
        } else {
          previousScheduledRoot.nextScheduledRoot = root.nextScheduledRoot;
          root.nextScheduledRoot = null;
        }
        root = previousScheduledRoot.nextScheduledRoot;
      } else {
        if (highestPriorityWork === NoWork || remainingExpirationTime < highestPriorityWork) {
          // Update the priority, if it's higher
          highestPriorityWork = remainingExpirationTime;
          highestPriorityRoot = root;
        }
        if (root === lastScheduledRoot) {
          break;
        }
        previousScheduledRoot = root;
        root = root.nextScheduledRoot;
      }
    }
  }

  // If the next root is the same as the previous root, this is a nested
  // update. To prevent an infinite loop, increment the nested update count.
  var previousFlushedRoot = nextFlushedRoot;
  if (previousFlushedRoot !== null && previousFlushedRoot === highestPriorityRoot && highestPriorityWork === Sync) {
    nestedUpdateCount++;
  } else {
    // Reset whenever we switch roots.
    nestedUpdateCount = 0;
  }
  nextFlushedRoot = highestPriorityRoot;
  nextFlushedExpirationTime = highestPriorityWork;
}

function performAsyncWork(dl) {
  performWork(NoWork, true, dl);
}

function performSyncWork() {
  performWork(Sync, false, null);
}

function performWork(minExpirationTime, isAsync, dl) {
  deadline = dl;

  // Keep working on roots until there's no more work, or until the we reach
  // the deadline.
  findHighestPriorityRoot();

  if (enableProfilerTimer) {
    resumeActualRenderTimerIfPaused();
  }

  if (enableUserTimingAPI && deadline !== null) {
    var didExpire = nextFlushedExpirationTime < recalculateCurrentTime();
    var timeout = expirationTimeToMs(nextFlushedExpirationTime);
    stopRequestCallbackTimer(didExpire, timeout);
  }

  if (isAsync) {
    while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && (minExpirationTime === NoWork || minExpirationTime >= nextFlushedExpirationTime) && (!deadlineDidExpire || recalculateCurrentTime() >= nextFlushedExpirationTime)) {
      recalculateCurrentTime();
      performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, !deadlineDidExpire);
      findHighestPriorityRoot();
    }
  } else {
    while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && (minExpirationTime === NoWork || minExpirationTime >= nextFlushedExpirationTime)) {
      performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, false);
      findHighestPriorityRoot();
    }
  }

  // We're done flushing work. Either we ran out of time in this callback,
  // or there's no more work left with sufficient priority.

  // If we're inside a callback, set this to false since we just completed it.
  if (deadline !== null) {
    callbackExpirationTime = NoWork;
    callbackID = null;
  }
  // If there's work left over, schedule a new callback.
  if (nextFlushedExpirationTime !== NoWork) {
    scheduleCallbackWithExpiration(nextFlushedExpirationTime);
  }

  // Clean-up.
  deadline = null;
  deadlineDidExpire = false;

  finishRendering();
}

function flushRoot(root, expirationTime) {
  !!isRendering ? invariant(false, 'work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method.') : void 0;
  // Perform work on root as if the given expiration time is the current time.
  // This has the effect of synchronously flushing all work up to and
  // including the given time.
  nextFlushedRoot = root;
  nextFlushedExpirationTime = expirationTime;
  performWorkOnRoot(root, expirationTime, false);
  // Flush any sync work that was scheduled by lifecycles
  performSyncWork();
  finishRendering();
}

function finishRendering() {
  nestedUpdateCount = 0;

  if (completedBatches !== null) {
    var batches = completedBatches;
    completedBatches = null;
    for (var i = 0; i < batches.length; i++) {
      var batch = batches[i];
      try {
        batch._onComplete();
      } catch (error) {
        if (!hasUnhandledError) {
          hasUnhandledError = true;
          unhandledError = error;
        }
      }
    }
  }

  if (hasUnhandledError) {
    var error = unhandledError;
    unhandledError = null;
    hasUnhandledError = false;
    throw error;
  }
}

function performWorkOnRoot(root, expirationTime, isAsync) {
  !!isRendering ? invariant(false, 'performWorkOnRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.') : void 0;

  isRendering = true;

  // Check if this is async work or sync/expired work.
  if (!isAsync) {
    // Flush sync work.
    var finishedWork = root.finishedWork;
    if (finishedWork !== null) {
      // This root is already complete. We can commit it.
      completeRoot(root, finishedWork, expirationTime);
    } else {
      finishedWork = renderRoot(root, expirationTime, false);
      if (finishedWork !== null) {
        // We've completed the root. Commit it.
        completeRoot(root, finishedWork, expirationTime);
      }
    }
  } else {
    // Flush async work.
    var _finishedWork = root.finishedWork;
    if (_finishedWork !== null) {
      // This root is already complete. We can commit it.
      completeRoot(root, _finishedWork, expirationTime);
    } else {
      _finishedWork = renderRoot(root, expirationTime, true);
      if (_finishedWork !== null) {
        // We've completed the root. Check the deadline one more time
        // before committing.
        if (!shouldYield()) {
          // Still time left. Commit the root.
          completeRoot(root, _finishedWork, expirationTime);
        } else {
          // There's no time left. Mark this root as complete. We'll come
          // back and commit it later.
          root.finishedWork = _finishedWork;

          if (enableProfilerTimer) {
            // If we didn't finish, pause the "actual" render timer.
            // We'll restart it when we resume work.
            pauseActualRenderTimerIfRunning();
          }
        }
      }
    }
  }

  isRendering = false;
}

function completeRoot(root, finishedWork, expirationTime) {
  // Check if there's a batch that matches this expiration time.
  var firstBatch = root.firstBatch;
  if (firstBatch !== null && firstBatch._expirationTime <= expirationTime) {
    if (completedBatches === null) {
      completedBatches = [firstBatch];
    } else {
      completedBatches.push(firstBatch);
    }
    if (firstBatch._defer) {
      // This root is blocked from committing by a batch. Unschedule it until
      // we receive another update.
      root.finishedWork = finishedWork;
      root.remainingExpirationTime = NoWork;
      return;
    }
  }

  // Commit the root.
  root.finishedWork = null;
  root.remainingExpirationTime = commitRoot(finishedWork);
}

// When working on async work, the reconciler asks the renderer if it should
// yield execution. For DOM, we implement this with requestIdleCallback.
function shouldYield() {
  if (deadline === null) {
    return false;
  }
  if (deadline.timeRemaining() > timeHeuristicForUnitOfWork) {
    // Disregard deadline.didTimeout. Only expired work should be flushed
    // during a timeout. This path is only hit for non-expired work.
    return false;
  }
  deadlineDidExpire = true;
  return true;
}

function onUncaughtError(error) {
  !(nextFlushedRoot !== null) ? invariant(false, 'Should be working on a root. This error is likely caused by a bug in React. Please file an issue.') : void 0;
  // Unschedule this root so we don't work on it again until there's
  // another update.
  nextFlushedRoot.remainingExpirationTime = NoWork;
  if (!hasUnhandledError) {
    hasUnhandledError = true;
    unhandledError = error;
  }
}

function onBlock(remainingExpirationTime) {
  !(nextFlushedRoot !== null) ? invariant(false, 'Should be working on a root. This error is likely caused by a bug in React. Please file an issue.') : void 0;
  // This root was blocked. Unschedule it until there's another update.
  nextFlushedRoot.remainingExpirationTime = remainingExpirationTime;
}

// TODO: Batching should be implemented at the renderer level, not inside
// the reconciler.
function batchedUpdates$1(fn, a) {
  var previousIsBatchingUpdates = isBatchingUpdates;
  isBatchingUpdates = true;
  try {
    return fn(a);
  } finally {
    isBatchingUpdates = previousIsBatchingUpdates;
    if (!isBatchingUpdates && !isRendering) {
      performSyncWork();
    }
  }
}

// TODO: Batching should be implemented at the renderer level, not inside
// the reconciler.
function unbatchedUpdates(fn, a) {
  if (isBatchingUpdates && !isUnbatchingUpdates) {
    isUnbatchingUpdates = true;
    try {
      return fn(a);
    } finally {
      isUnbatchingUpdates = false;
    }
  }
  return fn(a);
}

// TODO: Batching should be implemented at the renderer level, not within
// the reconciler.
function flushSync(fn, a) {
  !!isRendering ? invariant(false, 'flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.') : void 0;
  var previousIsBatchingUpdates = isBatchingUpdates;
  isBatchingUpdates = true;
  try {
    return syncUpdates(fn, a);
  } finally {
    isBatchingUpdates = previousIsBatchingUpdates;
    performSyncWork();
  }
}

function interactiveUpdates$1(fn, a, b) {
  if (isBatchingInteractiveUpdates) {
    return fn(a, b);
  }
  // If there are any pending interactive updates, synchronously flush them.
  // This needs to happen before we read any handlers, because the effect of
  // the previous event may influence which handlers are called during
  // this event.
  if (!isBatchingUpdates && !isRendering && lowestPendingInteractiveExpirationTime !== NoWork) {
    // Synchronously flush pending interactive updates.
    performWork(lowestPendingInteractiveExpirationTime, false, null);
    lowestPendingInteractiveExpirationTime = NoWork;
  }
  var previousIsBatchingInteractiveUpdates = isBatchingInteractiveUpdates;
  var previousIsBatchingUpdates = isBatchingUpdates;
  isBatchingInteractiveUpdates = true;
  isBatchingUpdates = true;
  try {
    return fn(a, b);
  } finally {
    isBatchingInteractiveUpdates = previousIsBatchingInteractiveUpdates;
    isBatchingUpdates = previousIsBatchingUpdates;
    if (!isBatchingUpdates && !isRendering) {
      performSyncWork();
    }
  }
}

function flushInteractiveUpdates$1() {
  if (!isRendering && lowestPendingInteractiveExpirationTime !== NoWork) {
    // Synchronously flush pending interactive updates.
    performWork(lowestPendingInteractiveExpirationTime, false, null);
    lowestPendingInteractiveExpirationTime = NoWork;
  }
}

function flushControlled(fn) {
  var previousIsBatchingUpdates = isBatchingUpdates;
  isBatchingUpdates = true;
  try {
    syncUpdates(fn);
  } finally {
    isBatchingUpdates = previousIsBatchingUpdates;
    if (!isBatchingUpdates && !isRendering) {
      performWork(Sync, false, null);
    }
  }
}

// 0 is PROD, 1 is DEV.
// Might add PROFILE later.


var didWarnAboutNestedUpdates = void 0;

{
  didWarnAboutNestedUpdates = false;
}

function getContextForSubtree(parentComponent) {
  if (!parentComponent) {
    return emptyObject;
  }

  var fiber = get(parentComponent);
  var parentContext = findCurrentUnmaskedContext(fiber);
  return isContextProvider(fiber) ? processChildContext(fiber, parentContext) : parentContext;
}

function scheduleRootUpdate(current, element, expirationTime, callback) {
  {
    if (ReactDebugCurrentFiber.phase === 'render' && ReactDebugCurrentFiber.current !== null && !didWarnAboutNestedUpdates) {
      didWarnAboutNestedUpdates = true;
      warning(false, 'Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + 'Check the render method of %s.', getComponentName(ReactDebugCurrentFiber.current) || 'Unknown');
    }
  }

  var update = createUpdate(expirationTime);
  // Caution: React DevTools currently depends on this property
  // being called "element".
  update.payload = { element: element };

  callback = callback === undefined ? null : callback;
  if (callback !== null) {
    !(typeof callback === 'function') ? warning(false, 'render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback) : void 0;
    update.callback = callback;
  }
  enqueueUpdate(current, update, expirationTime);

  scheduleWork$1(current, expirationTime);
  return expirationTime;
}

function updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, callback) {
  // TODO: If this is a nested container, this won't be the root.
  var current = container.current;

  {
    if (ReactFiberInstrumentation_1.debugTool) {
      if (current.alternate === null) {
        ReactFiberInstrumentation_1.debugTool.onMountContainer(container);
      } else if (element === null) {
        ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container);
      } else {
        ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container);
      }
    }
  }

  var context = getContextForSubtree(parentComponent);
  if (container.context === null) {
    container.context = context;
  } else {
    container.pendingContext = context;
  }

  return scheduleRootUpdate(current, element, expirationTime, callback);
}

function findHostInstance(component) {
  var fiber = get(component);
  if (fiber === undefined) {
    if (typeof component.render === 'function') {
      invariant(false, 'Unable to find node on an unmounted component.');
    } else {
      invariant(false, 'Argument appears to not be a ReactComponent. Keys: %s', Object.keys(component));
    }
  }
  var hostFiber = findCurrentHostFiber(fiber);
  if (hostFiber === null) {
    return null;
  }
  return hostFiber.stateNode;
}

function createContainer(containerInfo, isAsync, hydrate) {
  return createFiberRoot(containerInfo, isAsync, hydrate);
}

function updateContainer(element, container, parentComponent, callback) {
  var current = container.current;
  var currentTime = recalculateCurrentTime();
  var expirationTime = computeExpirationForFiber(currentTime, current);
  return updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, callback);
}

function getPublicRootInstance(container) {
  var containerFiber = container.current;
  if (!containerFiber.child) {
    return null;
  }
  switch (containerFiber.child.tag) {
    case HostComponent:
      return getPublicInstance(containerFiber.child.stateNode);
    default:
      return containerFiber.child.stateNode;
  }
}

function findHostInstanceWithNoPortals(fiber) {
  var hostFiber = findCurrentHostFiberWithNoPortals(fiber);
  if (hostFiber === null) {
    return null;
  }
  return hostFiber.stateNode;
}

function injectIntoDevTools(devToolsConfig) {
  var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;

  return injectInternals(_assign({}, devToolsConfig, {
    findHostInstanceByFiber: function (fiber) {
      var hostFiber = findCurrentHostFiber(fiber);
      if (hostFiber === null) {
        return null;
      }
      return hostFiber.stateNode;
    },
    findFiberByHostInstance: function (instance) {
      if (!findFiberByHostInstance) {
        // Might not be implemented by the renderer.
        return null;
      }
      return findFiberByHostInstance(instance);
    }
  }));
}

// This file intentionally does *not* have the Flow annotation.
// Don't add it. See `./inline-typed.js` for an explanation.



var DOMRenderer = Object.freeze({
	updateContainerAtExpirationTime: updateContainerAtExpirationTime,
	createContainer: createContainer,
	updateContainer: updateContainer,
	flushRoot: flushRoot,
	requestWork: requestWork,
	computeUniqueAsyncExpiration: computeUniqueAsyncExpiration,
	batchedUpdates: batchedUpdates$1,
	unbatchedUpdates: unbatchedUpdates,
	deferredUpdates: deferredUpdates,
	syncUpdates: syncUpdates,
	interactiveUpdates: interactiveUpdates$1,
	flushInteractiveUpdates: flushInteractiveUpdates$1,
	flushControlled: flushControlled,
	flushSync: flushSync,
	getPublicRootInstance: getPublicRootInstance,
	findHostInstance: findHostInstance,
	findHostInstanceWithNoPortals: findHostInstanceWithNoPortals,
	injectIntoDevTools: injectIntoDevTools
});

function createPortal$1(children, containerInfo,
// TODO: figure out the API for cross-renderer implementation.
implementation) {
  var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;

  return {
    // This tag allow us to uniquely identify this as a React Portal
    $$typeof: REACT_PORTAL_TYPE,
    key: key == null ? null : '' + key,
    children: children,
    containerInfo: containerInfo,
    implementation: implementation
  };
}

// TODO: this is special because it gets imported during build.

var ReactVersion = '16.4.2';

// TODO: This type is shared between the reconciler and ReactDOM, but will
// eventually be lifted out to the renderer.
var topLevelUpdateWarnings = void 0;
var warnOnInvalidCallback = void 0;
var didWarnAboutUnstableCreatePortal = false;

{
  if (typeof Map !== 'function' ||
  // $FlowIssue Flow incorrectly thinks Map has no prototype
  Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' ||
  // $FlowIssue Flow incorrectly thinks Set has no prototype
  Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') {
    warning(false, 'React depends on Map and Set built-in types. Make sure that you load a ' + 'polyfill in older browsers. https://fb.me/react-polyfills');
  }

  topLevelUpdateWarnings = function (container) {
    if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {
      var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer._internalRoot.current);
      if (hostInstance) {
        !(hostInstance.parentNode === container) ? warning(false, 'render(...): It looks like the React-rendered content of this ' + 'container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + 'ReactDOM.unmountComponentAtNode to empty a container.') : void 0;
      }
    }

    var isRootRenderedBySomeReact = !!container._reactRootContainer;
    var rootEl = getReactRootElementInContainer(container);
    var hasNonRootReactChild = !!(rootEl && getInstanceFromNode$1(rootEl));

    !(!hasNonRootReactChild || isRootRenderedBySomeReact) ? warning(false, 'render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.') : void 0;

    !(container.nodeType !== ELEMENT_NODE || !container.tagName || container.tagName.toUpperCase() !== 'BODY') ? warning(false, 'render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.') : void 0;
  };

  warnOnInvalidCallback = function (callback, callerName) {
    !(callback === null || typeof callback === 'function') ? warning(false, '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback) : void 0;
  };
}

injection$2.injectFiberControlledHostComponent(ReactDOMFiberComponent);

function ReactBatch(root) {
  var expirationTime = computeUniqueAsyncExpiration();
  this._expirationTime = expirationTime;
  this._root = root;
  this._next = null;
  this._callbacks = null;
  this._didComplete = false;
  this._hasChildren = false;
  this._children = null;
  this._defer = true;
}
ReactBatch.prototype.render = function (children) {
  !this._defer ? invariant(false, 'batch.render: Cannot render a batch that already committed.') : void 0;
  this._hasChildren = true;
  this._children = children;
  var internalRoot = this._root._internalRoot;
  var expirationTime = this._expirationTime;
  var work = new ReactWork();
  updateContainerAtExpirationTime(children, internalRoot, null, expirationTime, work._onCommit);
  return work;
};
ReactBatch.prototype.then = function (onComplete) {
  if (this._didComplete) {
    onComplete();
    return;
  }
  var callbacks = this._callbacks;
  if (callbacks === null) {
    callbacks = this._callbacks = [];
  }
  callbacks.push(onComplete);
};
ReactBatch.prototype.commit = function () {
  var internalRoot = this._root._internalRoot;
  var firstBatch = internalRoot.firstBatch;
  !(this._defer && firstBatch !== null) ? invariant(false, 'batch.commit: Cannot commit a batch multiple times.') : void 0;

  if (!this._hasChildren) {
    // This batch is empty. Return.
    this._next = null;
    this._defer = false;
    return;
  }

  var expirationTime = this._expirationTime;

  // Ensure this is the first batch in the list.
  if (firstBatch !== this) {
    // This batch is not the earliest batch. We need to move it to the front.
    // Update its expiration time to be the expiration time of the earliest
    // batch, so that we can flush it without flushing the other batches.
    if (this._hasChildren) {
      expirationTime = this._expirationTime = firstBatch._expirationTime;
      // Rendering this batch again ensures its children will be the final state
      // when we flush (updates are processed in insertion order: last
      // update wins).
      // TODO: This forces a restart. Should we print a warning?
      this.render(this._children);
    }

    // Remove the batch from the list.
    var previous = null;
    var batch = firstBatch;
    while (batch !== this) {
      previous = batch;
      batch = batch._next;
    }
    !(previous !== null) ? invariant(false, 'batch.commit: Cannot commit a batch multiple times.') : void 0;
    previous._next = batch._next;

    // Add it to the front.
    this._next = firstBatch;
    firstBatch = internalRoot.firstBatch = this;
  }

  // Synchronously flush all the work up to this batch's expiration time.
  this._defer = false;
  flushRoot(internalRoot, expirationTime);

  // Pop the batch from the list.
  var next = this._next;
  this._next = null;
  firstBatch = internalRoot.firstBatch = next;

  // Append the next earliest batch's children to the update queue.
  if (firstBatch !== null && firstBatch._hasChildren) {
    firstBatch.render(firstBatch._children);
  }
};
ReactBatch.prototype._onComplete = function () {
  if (this._didComplete) {
    return;
  }
  this._didComplete = true;
  var callbacks = this._callbacks;
  if (callbacks === null) {
    return;
  }
  // TODO: Error handling.
  for (var i = 0; i < callbacks.length; i++) {
    var _callback = callbacks[i];
    _callback();
  }
};

function ReactWork() {
  this._callbacks = null;
  this._didCommit = false;
  // TODO: Avoid need to bind by replacing callbacks in the update queue with
  // list of Work objects.
  this._onCommit = this._onCommit.bind(this);
}
ReactWork.prototype.then = function (onCommit) {
  if (this._didCommit) {
    onCommit();
    return;
  }
  var callbacks = this._callbacks;
  if (callbacks === null) {
    callbacks = this._callbacks = [];
  }
  callbacks.push(onCommit);
};
ReactWork.prototype._onCommit = function () {
  if (this._didCommit) {
    return;
  }
  this._didCommit = true;
  var callbacks = this._callbacks;
  if (callbacks === null) {
    return;
  }
  // TODO: Error handling.
  for (var i = 0; i < callbacks.length; i++) {
    var _callback2 = callbacks[i];
    !(typeof _callback2 === 'function') ? invariant(false, 'Invalid argument passed as callback. Expected a function. Instead received: %s', _callback2) : void 0;
    _callback2();
  }
};

function ReactRoot(container, isAsync, hydrate) {
  var root = createContainer(container, isAsync, hydrate);
  this._internalRoot = root;
}
ReactRoot.prototype.render = function (children, callback) {
  var root = this._internalRoot;
  var work = new ReactWork();
  callback = callback === undefined ? null : callback;
  {
    warnOnInvalidCallback(callback, 'render');
  }
  if (callback !== null) {
    work.then(callback);
  }
  updateContainer(children, root, null, work._onCommit);
  return work;
};
ReactRoot.prototype.unmount = function (callback) {
  var root = this._internalRoot;
  var work = new ReactWork();
  callback = callback === undefined ? null : callback;
  {
    warnOnInvalidCallback(callback, 'render');
  }
  if (callback !== null) {
    work.then(callback);
  }
  updateContainer(null, root, null, work._onCommit);
  return work;
};
ReactRoot.prototype.legacy_renderSubtreeIntoContainer = function (parentComponent, children, callback) {
  var root = this._internalRoot;
  var work = new ReactWork();
  callback = callback === undefined ? null : callback;
  {
    warnOnInvalidCallback(callback, 'render');
  }
  if (callback !== null) {
    work.then(callback);
  }
  updateContainer(children, root, parentComponent, work._onCommit);
  return work;
};
ReactRoot.prototype.createBatch = function () {
  var batch = new ReactBatch(this);
  var expirationTime = batch._expirationTime;

  var internalRoot = this._internalRoot;
  var firstBatch = internalRoot.firstBatch;
  if (firstBatch === null) {
    internalRoot.firstBatch = batch;
    batch._next = null;
  } else {
    // Insert sorted by expiration time then insertion order
    var insertAfter = null;
    var insertBefore = firstBatch;
    while (insertBefore !== null && insertBefore._expirationTime <= expirationTime) {
      insertAfter = insertBefore;
      insertBefore = insertBefore._next;
    }
    batch._next = insertBefore;
    if (insertAfter !== null) {
      insertAfter._next = batch;
    }
  }

  return batch;
};

/**
 * True if the supplied DOM node is a valid node element.
 *
 * @param {?DOMElement} node The candidate DOM node.
 * @return {boolean} True if the DOM is a valid DOM node.
 * @internal
 */
function isValidContainer(node) {
  return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || node.nodeType === COMMENT_NODE && node.nodeValue === ' react-mount-point-unstable '));
}

function getReactRootElementInContainer(container) {
  if (!container) {
    return null;
  }

  if (container.nodeType === DOCUMENT_NODE) {
    return container.documentElement;
  } else {
    return container.firstChild;
  }
}

function shouldHydrateDueToLegacyHeuristic(container) {
  var rootElement = getReactRootElementInContainer(container);
  return !!(rootElement && rootElement.nodeType === ELEMENT_NODE && rootElement.hasAttribute(ROOT_ATTRIBUTE_NAME));
}

injection$3.injectRenderer(DOMRenderer);

var warnedAboutHydrateAPI = false;

function legacyCreateRootFromDOMContainer(container, forceHydrate) {
  var shouldHydrate = forceHydrate || shouldHydrateDueToLegacyHeuristic(container);
  // First clear any existing content.
  if (!shouldHydrate) {
    var warned = false;
    var rootSibling = void 0;
    while (rootSibling = container.lastChild) {
      {
        if (!warned && rootSibling.nodeType === ELEMENT_NODE && rootSibling.hasAttribute(ROOT_ATTRIBUTE_NAME)) {
          warned = true;
          warning(false, 'render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.');
        }
      }
      container.removeChild(rootSibling);
    }
  }
  {
    if (shouldHydrate && !forceHydrate && !warnedAboutHydrateAPI) {
      warnedAboutHydrateAPI = true;
      lowPriorityWarning$1(false, 'render(): Calling ReactDOM.render() to hydrate server-rendered markup ' + 'will stop working in React v17. Replace the ReactDOM.render() call ' + 'with ReactDOM.hydrate() if you want React to attach to the server HTML.');
    }
  }
  // Legacy roots are not async by default.
  var isAsync = false;
  return new ReactRoot(container, isAsync, shouldHydrate);
}

function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) {
  // TODO: Ensure all entry points contain this check
  !isValidContainer(container) ? invariant(false, 'Target container is not a DOM element.') : void 0;

  {
    topLevelUpdateWarnings(container);
  }

  // TODO: Without `any` type, Flow says "Property cannot be accessed on any
  // member of intersection type." Whyyyyyy.
  var root = container._reactRootContainer;
  if (!root) {
    // Initial mount
    root = container._reactRootContainer = legacyCreateRootFromDOMContainer(container, forceHydrate);
    if (typeof callback === 'function') {
      var originalCallback = callback;
      callback = function () {
        var instance = getPublicRootInstance(root._internalRoot);
        originalCallback.call(instance);
      };
    }
    // Initial mount should not be batched.
    unbatchedUpdates(function () {
      if (parentComponent != null) {
        root.legacy_renderSubtreeIntoContainer(parentComponent, children, callback);
      } else {
        root.render(children, callback);
      }
    });
  } else {
    if (typeof callback === 'function') {
      var _originalCallback = callback;
      callback = function () {
        var instance = getPublicRootInstance(root._internalRoot);
        _originalCallback.call(instance);
      };
    }
    // Update
    if (parentComponent != null) {
      root.legacy_renderSubtreeIntoContainer(parentComponent, children, callback);
    } else {
      root.render(children, callback);
    }
  }
  return getPublicRootInstance(root._internalRoot);
}

function createPortal(children, container) {
  var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;

  !isValidContainer(container) ? invariant(false, 'Target container is not a DOM element.') : void 0;
  // TODO: pass ReactDOM portal implementation as third argument
  return createPortal$1(children, container, null, key);
}

var ReactDOM = {
  createPortal: createPortal,

  findDOMNode: function (componentOrElement) {
    {
      var owner = ReactCurrentOwner.current;
      if (owner !== null && owner.stateNode !== null) {
        var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;
        !warnedAboutRefsInRender ? warning(false, '%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentName(owner) || 'A component') : void 0;
        owner.stateNode._warnedAboutRefsInRender = true;
      }
    }
    if (componentOrElement == null) {
      return null;
    }
    if (componentOrElement.nodeType === ELEMENT_NODE) {
      return componentOrElement;
    }

    return findHostInstance(componentOrElement);
  },
  hydrate: function (element, container, callback) {
    // TODO: throw or warn if we couldn't hydrate?
    return legacyRenderSubtreeIntoContainer(null, element, container, true, callback);
  },
  render: function (element, container, callback) {
    return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
  },
  unstable_renderSubtreeIntoContainer: function (parentComponent, element, containerNode, callback) {
    !(parentComponent != null && has(parentComponent)) ? invariant(false, 'parentComponent must be a valid React Component') : void 0;
    return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback);
  },
  unmountComponentAtNode: function (container) {
    !isValidContainer(container) ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : void 0;

    if (container._reactRootContainer) {
      {
        var rootEl = getReactRootElementInContainer(container);
        var renderedByDifferentReact = rootEl && !getInstanceFromNode$1(rootEl);
        !!renderedByDifferentReact ? warning(false, "unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by another copy of React.') : void 0;
      }

      // Unmount should not be batched.
      unbatchedUpdates(function () {
        legacyRenderSubtreeIntoContainer(null, null, container, false, function () {
          container._reactRootContainer = null;
        });
      });
      // If you call unmountComponentAtNode twice in quick succession, you'll
      // get `true` twice. That's probably fine?
      return true;
    } else {
      {
        var _rootEl = getReactRootElementInContainer(container);
        var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode$1(_rootEl));

        // Check if the container itself is a React root node.
        var isContainerReactRoot = container.nodeType === 1 && isValidContainer(container.parentNode) && !!container.parentNode._reactRootContainer;

        !!hasNonRootReactChild ? warning(false, "unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.') : void 0;
      }

      return false;
    }
  },


  // Temporary alias since we already shipped React 16 RC with it.
  // TODO: remove in React 17.
  unstable_createPortal: function () {
    if (!didWarnAboutUnstableCreatePortal) {
      didWarnAboutUnstableCreatePortal = true;
      lowPriorityWarning$1(false, 'The ReactDOM.unstable_createPortal() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactDOM.createPortal() instead. It has the exact same API, ' + 'but without the "unstable_" prefix.');
    }
    return createPortal.apply(undefined, arguments);
  },


  unstable_batchedUpdates: batchedUpdates$1,

  unstable_deferredUpdates: deferredUpdates,

  unstable_interactiveUpdates: interactiveUpdates$1,

  flushSync: flushSync,

  unstable_flushControlled: flushControlled,

  __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
    // For TapEventPlugin which is popular in open source
    EventPluginHub: EventPluginHub,
    // Used by test-utils
    EventPluginRegistry: EventPluginRegistry,
    EventPropagators: EventPropagators,
    ReactControlledComponent: ReactControlledComponent,
    ReactDOMComponentTree: ReactDOMComponentTree,
    ReactDOMEventListener: ReactDOMEventListener
  }
};

ReactDOM.unstable_createRoot = function createRoot(container, options) {
  var hydrate = options != null && options.hydrate === true;
  return new ReactRoot(container, true, hydrate);
};

var foundDevTools = injectIntoDevTools({
  findFiberByHostInstance: getClosestInstanceFromNode,
  bundleType: 1,
  version: ReactVersion,
  rendererPackageName: 'react-dom'
});

{
  if (!foundDevTools && ExecutionEnvironment.canUseDOM && window.top === window.self) {
    // If we're in Chrome or Firefox, provide a download link if not installed.
    if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
      var protocol = window.location.protocol;
      // Don't warn in exotic cases like chrome-extension://.
      if (/^(https?|file):$/.test(protocol)) {
        console.info('%cDownload the React DevTools ' + 'for a better development experience: ' + 'https://fb.me/react-devtools' + (protocol === 'file:' ? '\nYou might need to use a local HTTP server (instead of file://): ' + 'https://fb.me/react-devtools-faq' : ''), 'font-weight:bold');
      }
    }
  }
}



var ReactDOM$2 = Object.freeze({
	default: ReactDOM
});

var ReactDOM$3 = ( ReactDOM$2 && ReactDOM ) || ReactDOM$2;

// TODO: decide on the top-level export form.
// This is hacky but makes it work with both Rollup and Jest.
var reactDom = ReactDOM$3.default ? ReactDOM$3.default : ReactDOM$3;

module.exports = reactDom;
  })();
}


/***/ }),

/***/ "YeVe":
/*!******************************************************!*\
  !*** ./node_modules/draft-js/lib/BlockMapBuilder.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule BlockMapBuilder
 * @format
 * 
 */



var Immutable = __webpack_require__(/*! immutable */ "JPcv");

var OrderedMap = Immutable.OrderedMap;


var BlockMapBuilder = {
  createFromArray: function createFromArray(blocks) {
    return OrderedMap(blocks.map(function (block) {
      return [block.getKey(), block];
    }));
  }
};

module.exports = BlockMapBuilder;

/***/ }),

/***/ "YewF":
/*!********************************************************************!*\
  !*** ./node_modules/react-json-tree/lib/createStylingFromTheme.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "QbLZ");

var _extends3 = _interopRequireDefault(_extends2);

var _reactBase16Styling = __webpack_require__(/*! react-base16-styling */ "jb+b");

var _solarized = __webpack_require__(/*! ./themes/solarized */ "u1VM");

var _solarized2 = _interopRequireDefault(_solarized);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var colorMap = function colorMap(theme) {
  return {
    BACKGROUND_COLOR: theme.base00,
    TEXT_COLOR: theme.base07,
    STRING_COLOR: theme.base0B,
    DATE_COLOR: theme.base0B,
    NUMBER_COLOR: theme.base09,
    BOOLEAN_COLOR: theme.base09,
    NULL_COLOR: theme.base08,
    UNDEFINED_COLOR: theme.base08,
    FUNCTION_COLOR: theme.base08,
    SYMBOL_COLOR: theme.base08,
    LABEL_COLOR: theme.base0D,
    ARROW_COLOR: theme.base0D,
    ITEM_STRING_COLOR: theme.base0B,
    ITEM_STRING_EXPANDED_COLOR: theme.base03
  };
};

var valueColorMap = function valueColorMap(colors) {
  return {
    String: colors.STRING_COLOR,
    Date: colors.DATE_COLOR,
    Number: colors.NUMBER_COLOR,
    Boolean: colors.BOOLEAN_COLOR,
    Null: colors.NULL_COLOR,
    Undefined: colors.UNDEFINED_COLOR,
    Function: colors.FUNCTION_COLOR,
    Symbol: colors.SYMBOL_COLOR
  };
};

var getDefaultThemeStyling = function getDefaultThemeStyling(theme) {
  var colors = colorMap(theme);

  return {
    tree: {
      border: 0,
      padding: 0,
      marginTop: '0.5em',
      marginBottom: '0.5em',
      marginLeft: '0.125em',
      marginRight: 0,
      listStyle: 'none',
      MozUserSelect: 'none',
      WebkitUserSelect: 'none',
      backgroundColor: colors.BACKGROUND_COLOR
    },

    value: function value(_ref, nodeType, keyPath) {
      var style = _ref.style;
      return {
        style: (0, _extends3['default'])({}, style, {
          paddingTop: '0.25em',
          paddingRight: 0,
          marginLeft: '0.875em',
          WebkitUserSelect: 'text',
          MozUserSelect: 'text',
          wordWrap: 'break-word',
          paddingLeft: keyPath.length > 1 ? '2.125em' : '1.25em',
          textIndent: '-0.5em',
          wordBreak: 'break-all'
        })
      };
    },

    label: {
      display: 'inline-block',
      color: colors.LABEL_COLOR
    },

    valueLabel: {
      margin: '0 0.5em 0 0'
    },

    valueText: function valueText(_ref2, nodeType) {
      var style = _ref2.style;
      return {
        style: (0, _extends3['default'])({}, style, {
          color: valueColorMap(colors)[nodeType]
        })
      };
    },

    itemRange: function itemRange(styling, expanded) {
      return {
        style: {
          paddingTop: expanded ? 0 : '0.25em',
          cursor: 'pointer',
          color: colors.LABEL_COLOR
        }
      };
    },

    arrow: function arrow(_ref3, nodeType, expanded) {
      var style = _ref3.style;
      return {
        style: (0, _extends3['default'])({}, style, {
          marginLeft: 0,
          transition: '150ms',
          WebkitTransition: '150ms',
          MozTransition: '150ms',
          WebkitTransform: expanded ? 'rotateZ(90deg)' : 'rotateZ(0deg)',
          MozTransform: expanded ? 'rotateZ(90deg)' : 'rotateZ(0deg)',
          transform: expanded ? 'rotateZ(90deg)' : 'rotateZ(0deg)',
          transformOrigin: '45% 50%',
          WebkitTransformOrigin: '45% 50%',
          MozTransformOrigin: '45% 50%',
          position: 'relative',
          lineHeight: '1.1em',
          fontSize: '0.75em'
        })
      };
    },

    arrowContainer: function arrowContainer(_ref4, arrowStyle) {
      var style = _ref4.style;
      return {
        style: (0, _extends3['default'])({}, style, {
          display: 'inline-block',
          paddingRight: '0.5em',
          paddingLeft: arrowStyle === 'double' ? '1em' : 0,
          cursor: 'pointer'
        })
      };
    },

    arrowSign: {
      color: colors.ARROW_COLOR
    },

    arrowSignInner: {
      position: 'absolute',
      top: 0,
      left: '-0.4em'
    },

    nestedNode: function nestedNode(_ref5, keyPath, nodeType, expanded, expandable) {
      var style = _ref5.style;
      return {
        style: (0, _extends3['default'])({}, style, {
          position: 'relative',
          paddingTop: '0.25em',
          marginLeft: keyPath.length > 1 ? '0.875em' : 0,
          paddingLeft: !expandable ? '1.125em' : 0
        })
      };
    },

    rootNode: {
      padding: 0,
      margin: 0
    },

    nestedNodeLabel: function nestedNodeLabel(_ref6, keyPath, nodeType, expanded, expandable) {
      var style = _ref6.style;
      return {
        style: (0, _extends3['default'])({}, style, {
          margin: 0,
          padding: 0,
          WebkitUserSelect: expandable ? 'inherit' : 'text',
          MozUserSelect: expandable ? 'inherit' : 'text',
          cursor: expandable ? 'pointer' : 'default'
        })
      };
    },

    nestedNodeItemString: function nestedNodeItemString(_ref7, keyPath, nodeType, expanded) {
      var style = _ref7.style;
      return {
        style: (0, _extends3['default'])({}, style, {
          paddingLeft: '0.5em',
          cursor: 'default',
          color: expanded ? colors.ITEM_STRING_EXPANDED_COLOR : colors.ITEM_STRING_COLOR
        })
      };
    },

    nestedNodeItemType: {
      marginLeft: '0.3em',
      marginRight: '0.3em'
    },

    nestedNodeChildren: function nestedNodeChildren(_ref8, nodeType, expanded) {
      var style = _ref8.style;
      return {
        style: (0, _extends3['default'])({}, style, {
          padding: 0,
          margin: 0,
          listStyle: 'none',
          display: expanded ? 'block' : 'none'
        })
      };
    },

    rootNodeChildren: {
      padding: 0,
      margin: 0,
      listStyle: 'none'
    }
  };
};

exports['default'] = (0, _reactBase16Styling.createStyling)(getDefaultThemeStyling, {
  defaultBase16: _solarized2['default']
});

/***/ }),

/***/ "Yixa":
/*!*********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/ColorwayPicker.js ***!
  \*********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _ColorscalePicker = __webpack_require__(/*! ../widgets/ColorscalePicker */ "7/El");

var _ColorscalePicker2 = _interopRequireDefault(_ColorscalePicker);

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UnconnectedColorwayPicker = function (_Component) {
  _inherits(UnconnectedColorwayPicker, _Component);

  function UnconnectedColorwayPicker() {
    _classCallCheck(this, UnconnectedColorwayPicker);

    return _possibleConstructorReturn(this, (UnconnectedColorwayPicker.__proto__ || Object.getPrototypeOf(UnconnectedColorwayPicker)).apply(this, arguments));
  }

  _createClass(UnconnectedColorwayPicker, [{
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        _Field2.default,
        this.props,
        _react2.default.createElement(_ColorscalePicker2.default, {
          selected: this.props.fullValue,
          onColorscaleChange: this.props.updatePlot,
          initialCategory: 'categorical',
          disableCategorySwitch: this.props.disableCategorySwitch
        })
      );
    }
  }]);

  return UnconnectedColorwayPicker;
}(_react.Component);

UnconnectedColorwayPicker.propTypes = _extends({
  fullValue: _propTypes2.default.any,
  updatePlot: _propTypes2.default.func
}, _Field2.default.propTypes);

exports.default = (0, _lib.connectToContainer)(UnconnectedColorwayPicker);
//# sourceMappingURL=ColorwayPicker.js.map

/***/ }),

/***/ "YkW1":
/*!*******************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/help-extension/style/index.css ***!
  \*******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.jp-Help {\n  min-width: 240px;\n  min-height: 240px;\n  background: white;\n  outline: none;\n}\n\n.jp-Help > iframe {\n  border: none;\n}\n\n.jp-About-body {\n  display: flex;\n  font-size: var(--jp-ui-font-size1);\n  color: var(--jp-ui-font-color1);\n  text-align: left;\n  flex-direction: column;\n  width: 100%;\n  min-width: 360px;\n  overflow: visible;\n}\n\n.jp-Dialog .jp-Dialog-content div.jp-About-header-wordmark {\n  flex: 0 0 auto;\n  height: 44px;\n  width: auto;\n  background-image: var(--jp-about-header-wordmark);\n  background-size: 196px 50px;\n  background-repeat: no-repeat;\n  padding-bottom: 0px;\n}\n\n.jp-About-version-info {\n  color: var(--jp-ui-font-color1);\n  /* Dialog-header sets the font size to 3, we reset to 1 */\n  font-size: var(--jp-ui-font-size1);\n  width: 200px;\n  font-weight: 400;\n  letter-spacing: 0.4px;\n  text-align: left;\n  padding-top: 8px;\n  line-height: 1.12;\n}\n\n.jp-Dialog\n  .jp-Dialog-content\n  .jp-Dialog-footer\n  .jp-Dialog-button.jp-About-button {\n  margin-right: 0px;\n}\n\n.jp-About-version {\n  display: block;\n}\n\n.jp-About-version {\n  padding-top: 8px;\n}\n\n.jp-About-externalLinks {\n  display: flex;\n  flex-direction: column;\n  justify-content: flex-start;\n  align-items: flex-start;\n  padding-top: 12px;\n}\n\n.jp-About-externalLinks .jp-Button-flat {\n  color: #f37726;\n}\n\n.jp-About-copyright {\n  padding-top: 25px;\n}\n\n.jp-About-header {\n  display: flex;\n  flex-direction: row;\n  align-items: center;\n}\n\n.jp-About-body pre {\n  white-space: pre-wrap;\n}\n\n.jp-About-header-info {\n  display: flex;\n  flex-direction: column;\n  margin-left: 16px;\n}\n\n.jp-About-header-logo {\n  height: 94px;\n  width: 77px;\n  background-image: var(--jp-about-header-logo);\n  background-repeat: no-repeat;\n  background-size: 58px auto;\n  background-position: center;\n}\n", ""]);

// exports


/***/ }),

/***/ "YmH9":
/*!************************************************************!*\
  !*** ./node_modules/@phosphor/datagrid/lib/sectionlist.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
/**
 * An object which manages a collection of variable sized sections.
 *
 * #### Notes
 * This class is an implementation detail. It is designed to manage
 * the variable row and column sizes for a data grid. User code will
 * not interact with this class directly.
 */
var SectionList = (function () {
    /**
     * Construct a new section list.
     *
     * @param options - The options for initializing the list.
     */
    function SectionList(options) {
        this._totalSize = 0;
        this._sectionCount = 0;
        this._sections = [];
        this._baseSize = Math.max(0, Math.floor(options.baseSize));
    }
    Object.defineProperty(SectionList.prototype, "totalSize", {
        /**
         * The total size of all sections in the list.
         *
         * #### Complexity
         * Constant.
         */
        get: function () {
            return this._totalSize;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(SectionList.prototype, "sectionCount", {
        /**
         * The total number of sections in the list.
         *
         * #### Complexity
         * Constant.
         */
        get: function () {
            return this._sectionCount;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(SectionList.prototype, "baseSize", {
        /**
         * Get the base size of sections in the list.
         *
         * #### Complexity
         * Constant.
         */
        get: function () {
            return this._baseSize;
        },
        /**
         * Set the base size of sections in the list.
         *
         * #### Complexity
         * Linear on the number of resized sections.
         */
        set: function (value) {
            // Normalize the value.
            value = Math.max(0, Math.floor(value));
            // Bail early if the value does not change.
            if (this._baseSize === value) {
                return;
            }
            // Compute the delta base size.
            var delta = value - this._baseSize;
            // Update the internal base size.
            this._baseSize = value;
            // Update the total size.
            this._totalSize += delta * (this._sectionCount - this._sections.length);
            // Bail early if there are no modified sections.
            if (this._sections.length === 0) {
                return;
            }
            // Recompute the offsets of the modified sections.
            for (var i = 0, n = this._sections.length; i < n; ++i) {
                // Look up the previous and current modified sections.
                var prev = this._sections[i - 1];
                var curr = this._sections[i];
                // Adjust the offset for the current section.
                if (prev) {
                    var count = curr.index - prev.index - 1;
                    curr.offset = prev.offset + prev.size + count * value;
                }
                else {
                    curr.offset = curr.index * value;
                }
            }
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Find the index of the section which covers the given offset.
     *
     * @param offset - The offset of the section of interest.
     *
     * @returns The index of the section which covers the given offset,
     *   or `-1` if the offset is out of range.
     *
     * #### Complexity
     * Logarithmic on the number of resized sections.
     */
    SectionList.prototype.sectionIndex = function (offset) {
        // Bail early if the offset is out of range.
        if (offset < 0 || offset >= this._totalSize || this._sectionCount === 0) {
            return -1;
        }
        // Handle the simple case of no modified sections.
        if (this._sections.length === 0) {
            return Math.floor(offset / this._baseSize);
        }
        // Find the modified section for the given offset.
        var i = algorithm_1.ArrayExt.lowerBound(this._sections, offset, Private.offsetCmp);
        // Return the index of an exact match.
        if (i < this._sections.length && this._sections[i].offset <= offset) {
            return this._sections[i].index;
        }
        // Handle the case of no modified sections before the offset.
        if (i === 0) {
            return Math.floor(offset / this._baseSize);
        }
        // Compute the index from the previous modified section.
        var section = this._sections[i - 1];
        var span = offset - (section.offset + section.size);
        return section.index + Math.floor(span / this._baseSize) + 1;
    };
    /**
     * Find the offset of the section at the given index.
     *
     * @param index - The index of the section of interest.
     *
     * @returns The offset of the section at the given index, or `-1`
     *   if the index is out of range.
     *
     * #### Undefined Behavior
     * An `index` which is non-integral.
     *
     * #### Complexity
     * Logarithmic on the number of resized sections.
     */
    SectionList.prototype.sectionOffset = function (index) {
        // Bail early if the index is out of range.
        if (index < 0 || index >= this._sectionCount) {
            return -1;
        }
        // Handle the simple case of no modified sections.
        if (this._sections.length === 0) {
            return index * this._baseSize;
        }
        // Find the modified section for the given index.
        var i = algorithm_1.ArrayExt.lowerBound(this._sections, index, Private.indexCmp);
        // Return the offset of an exact match.
        if (i < this._sections.length && this._sections[i].index === index) {
            return this._sections[i].offset;
        }
        // Handle the case of no modified sections before the index.
        if (i === 0) {
            return index * this._baseSize;
        }
        // Compute the offset from the previous modified section.
        var section = this._sections[i - 1];
        var span = index - section.index - 1;
        return section.offset + section.size + span * this._baseSize;
    };
    /**
     * Find the size of the section at the given index.
     *
     * @param index - The index of the section of interest.
     *
     * @returns The size of the section at the given index, or `-1`
     *   if the index is out of range.
     *
     * #### Undefined Behavior
     * An `index` which is non-integral.
     *
     * #### Complexity
     * Logarithmic on the number of resized sections.
     */
    SectionList.prototype.sectionSize = function (index) {
        // Bail early if the index is out of range.
        if (index < 0 || index >= this._sectionCount) {
            return -1;
        }
        // Handle the simple case of no modified sections.
        if (this._sections.length === 0) {
            return this._baseSize;
        }
        // Find the modified section for the given index.
        var i = algorithm_1.ArrayExt.lowerBound(this._sections, index, Private.indexCmp);
        // Return the size of an exact match.
        if (i < this._sections.length && this._sections[i].index === index) {
            return this._sections[i].size;
        }
        // Return the base size for all other cases.
        return this._baseSize;
    };
    /**
     * Resize a section in the list.
     *
     * @param index - The index of the section to resize. This method
     *   is a no-op if this value is out of range.
     *
     * @param size - The new size of the section. This value will be
     *   clamped to an integer `>= 0`.
     *
     * #### Undefined Behavior
     * An `index` which is non-integral.
     *
     * #### Complexity
     * Linear on the number of resized sections.
     */
    SectionList.prototype.resizeSection = function (index, size) {
        // Bail early if the index is out of range.
        if (index < 0 || index >= this._sectionCount) {
            return;
        }
        // Clamp the size to an integer >= 0.
        size = Math.max(0, Math.floor(size));
        // Find the modified section for the given index.
        var i = algorithm_1.ArrayExt.lowerBound(this._sections, index, Private.indexCmp);
        // Update or create the modified section as needed.
        var delta;
        if (i < this._sections.length && this._sections[i].index === index) {
            var section = this._sections[i];
            delta = size - section.size;
            section.size = size;
        }
        else if (i === 0) {
            var offset = index * this._baseSize;
            algorithm_1.ArrayExt.insert(this._sections, i, { index: index, offset: offset, size: size });
            delta = size - this._baseSize;
        }
        else {
            var section = this._sections[i - 1];
            var span = index - section.index - 1;
            var offset = section.offset + section.size + span * this._baseSize;
            algorithm_1.ArrayExt.insert(this._sections, i, { index: index, offset: offset, size: size });
            delta = size - this._baseSize;
        }
        // Adjust the totals.
        this._totalSize += delta;
        // Update all modified sections after the resized section.
        for (var j = i + 1, n = this._sections.length; j < n; ++j) {
            this._sections[j].offset += delta;
        }
    };
    /**
     * Insert sections into the list.
     *
     * @param index - The index at which to insert the sections. This
     *   value will be clamped to the bounds of the list.
     *
     * @param count - The number of sections to insert. This method
     *   is a no-op if this value is `<= 0`.
     *
     * #### Undefined Behavior
     * An `index` or `count` which is non-integral.
     *
     * #### Complexity
     * Linear on the number of resized sections.
     */
    SectionList.prototype.insertSections = function (index, count) {
        // Bail early if there are no sections to insert.
        if (count <= 0) {
            return;
        }
        // Clamp the index to the bounds of the list.
        index = Math.max(0, Math.min(index, this._sectionCount));
        // Add the new sections to the totals.
        var span = count * this._baseSize;
        this._sectionCount += count;
        this._totalSize += span;
        // Bail early if there are no modified sections to update.
        if (this._sections.length === 0) {
            return;
        }
        // Find the modified section for the given index.
        var i = algorithm_1.ArrayExt.lowerBound(this._sections, index, Private.indexCmp);
        // Update all modified sections after the insert location.
        for (var n = this._sections.length; i < n; ++i) {
            var section = this._sections[i];
            section.index += count;
            section.offset += span;
        }
    };
    /**
     * Remove sections from the list.
     *
     * @param index - The index of the first section to remove. This
     *   method is a no-op if this value is out of range.
     *
     * @param count - The number of sections to remove. This method
     *   is a no-op if this value is `<= 0`.
     *
     * #### Undefined Behavior
     * An `index` or `count` which is non-integral.
     *
     * #### Complexity
     * Linear on the number of resized sections.
     */
    SectionList.prototype.removeSections = function (index, count) {
        // Bail early if there is nothing to remove.
        if (index < 0 || index >= this._sectionCount || count <= 0) {
            return;
        }
        // Clamp the count to the bounds of the list.
        count = Math.min(this._sectionCount - index, count);
        // Handle the simple case of no modified sections to update.
        if (this._sections.length === 0) {
            this._sectionCount -= count;
            this._totalSize -= count * this._baseSize;
            return;
        }
        // Handle the simple case of removing all sections.
        if (count === this._sectionCount) {
            this._totalSize = 0;
            this._sectionCount = 0;
            this._sections.length = 0;
            return;
        }
        // Find the modified section for the start index.
        var i = algorithm_1.ArrayExt.lowerBound(this._sections, index, Private.indexCmp);
        // Find the modified section for the end index.
        var j = algorithm_1.ArrayExt.lowerBound(this._sections, index + count, Private.indexCmp);
        // Remove the relevant modified sections.
        var removed = this._sections.splice(i, j - i);
        // Compute the total removed span.
        var span = (count - removed.length) * this._baseSize;
        for (var k = 0, n = removed.length; k < n; ++k) {
            span += removed[k].size;
        }
        // Adjust the totals.
        this._sectionCount -= count;
        this._totalSize -= span;
        // Update all modified sections after the removed span.
        for (var k = i, n = this._sections.length; k < n; ++k) {
            var section = this._sections[k];
            section.index -= count;
            section.offset -= span;
        }
    };
    /**
     * Move sections within the list.
     *
     * @param index - The index of the first section to move. This method
     *   is a no-op if this value is out of range.
     *
     * @param count - The number of sections to move. This method is a
     *   no-op if this value is `<= 0`.
     *
     * @param destination - The destination index for the first section.
     *   This value will be clamped to the allowable range.
     *
     * #### Undefined Behavior
     * An `index`, `count`, or `destination` which is non-integral.
     *
     * #### Complexity
     * Linear on the number of moved resized sections.
     */
    SectionList.prototype.moveSections = function (index, count, destination) {
        // Bail early if there is nothing to move.
        if (index < 0 || index >= this._sectionCount || count <= 0) {
            return;
        }
        // Handle the simple case of no modified sections.
        if (this._sections.length === 0) {
            return;
        }
        // Clamp the move count to the limit.
        count = Math.min(count, this._sectionCount - index);
        // Clamp the destination index to the limit.
        destination = Math.min(Math.max(0, destination), this._sectionCount - count);
        // Bail early if there is no effective move.
        if (index === destination) {
            return;
        }
        // Compute the first affected index.
        var i1 = Math.min(index, destination);
        // Look up the first affected modified section.
        var k1 = algorithm_1.ArrayExt.lowerBound(this._sections, i1, Private.indexCmp);
        // Bail early if there are no affected modified sections.
        if (k1 === this._sections.length) {
            return;
        }
        // Compute the last affected index.
        var i2 = Math.max(index + count - 1, destination + count - 1);
        // Look up the last affected modified section.
        var k2 = algorithm_1.ArrayExt.upperBound(this._sections, i2, Private.indexCmp) - 1;
        // Bail early if there are no affected modified sections.
        if (k2 < k1) {
            return;
        }
        // Compute the pivot index.
        var pivot = destination < index ? index : index + count;
        // Compute the count for each side of the pivot.
        var count1 = pivot - i1;
        var count2 = i2 - pivot + 1;
        // Compute the span for each side of the pivot.
        var span1 = count1 * this._baseSize;
        var span2 = count2 * this._baseSize;
        // Adjust the spans for the modified sections.
        for (var j = k1; j <= k2; ++j) {
            var section = this._sections[j];
            if (section.index < pivot) {
                span1 += section.size - this._baseSize;
            }
            else {
                span2 += section.size - this._baseSize;
            }
        }
        // Look up the pivot section.
        var k3 = algorithm_1.ArrayExt.lowerBound(this._sections, pivot, Private.indexCmp);
        // Rotate the modified sections if needed.
        if (k1 <= k3 && k3 <= k2) {
            algorithm_1.ArrayExt.rotate(this._sections, k3 - k1, k1, k2);
        }
        // Adjust the modified section indices and offsets.
        for (var j = k1; j <= k2; ++j) {
            var section = this._sections[j];
            if (section.index < pivot) {
                section.index += count2;
                section.offset += span2;
            }
            else {
                section.index -= count1;
                section.offset -= span1;
            }
        }
    };
    /**
     * Reset all modified sections to the base size.
     *
     * #### Complexity
     * Constant.
     */
    SectionList.prototype.reset = function () {
        this._sections.length = 0;
        this._totalSize = this._sectionCount * this._baseSize;
    };
    /**
     * Remove all sections from the list.
     *
     * #### Complexity
     * Constant.
     */
    SectionList.prototype.clear = function () {
        this._totalSize = 0;
        this._sectionCount = 0;
        this._sections.length = 0;
    };
    return SectionList;
}());
exports.SectionList = SectionList;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * A comparison function for searching by offset.
     */
    function offsetCmp(section, offset) {
        if (offset < section.offset) {
            return 1;
        }
        if (section.offset + section.size <= offset) {
            return -1;
        }
        return 0;
    }
    Private.offsetCmp = offsetCmp;
    /**
     * A comparison function for searching by index.
     */
    function indexCmp(section, index) {
        return section.index - index;
    }
    Private.indexCmp = indexCmp;
})(Private || (Private = {}));


/***/ }),

/***/ "YoN+":
/*!******************************************************!*\
  !*** ./node_modules/asn1.js/lib/asn1/base/buffer.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var inherits = __webpack_require__(/*! inherits */ "P7XM");
var Reporter = __webpack_require__(/*! ../base */ "Qd/k").Reporter;
var Buffer = __webpack_require__(/*! buffer */ "tjlA").Buffer;

function DecoderBuffer(base, options) {
  Reporter.call(this, options);
  if (!Buffer.isBuffer(base)) {
    this.error('Input not Buffer');
    return;
  }

  this.base = base;
  this.offset = 0;
  this.length = base.length;
}
inherits(DecoderBuffer, Reporter);
exports.DecoderBuffer = DecoderBuffer;

DecoderBuffer.prototype.save = function save() {
  return { offset: this.offset, reporter: Reporter.prototype.save.call(this) };
};

DecoderBuffer.prototype.restore = function restore(save) {
  // Return skipped data
  var res = new DecoderBuffer(this.base);
  res.offset = save.offset;
  res.length = this.offset;

  this.offset = save.offset;
  Reporter.prototype.restore.call(this, save.reporter);

  return res;
};

DecoderBuffer.prototype.isEmpty = function isEmpty() {
  return this.offset === this.length;
};

DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) {
  if (this.offset + 1 <= this.length)
    return this.base.readUInt8(this.offset++, true);
  else
    return this.error(fail || 'DecoderBuffer overrun');
}

DecoderBuffer.prototype.skip = function skip(bytes, fail) {
  if (!(this.offset + bytes <= this.length))
    return this.error(fail || 'DecoderBuffer overrun');

  var res = new DecoderBuffer(this.base);

  // Share reporter state
  res._reporterState = this._reporterState;

  res.offset = this.offset;
  res.length = this.offset + bytes;
  this.offset += bytes;
  return res;
}

DecoderBuffer.prototype.raw = function raw(save) {
  return this.base.slice(save ? save.offset : this.offset, this.length);
}

function EncoderBuffer(value, reporter) {
  if (Array.isArray(value)) {
    this.length = 0;
    this.value = value.map(function(item) {
      if (!(item instanceof EncoderBuffer))
        item = new EncoderBuffer(item, reporter);
      this.length += item.length;
      return item;
    }, this);
  } else if (typeof value === 'number') {
    if (!(0 <= value && value <= 0xff))
      return reporter.error('non-byte EncoderBuffer value');
    this.value = value;
    this.length = 1;
  } else if (typeof value === 'string') {
    this.value = value;
    this.length = Buffer.byteLength(value);
  } else if (Buffer.isBuffer(value)) {
    this.value = value;
    this.length = value.length;
  } else {
    return reporter.error('Unsupported type: ' + typeof value);
  }
}
exports.EncoderBuffer = EncoderBuffer;

EncoderBuffer.prototype.join = function join(out, offset) {
  if (!out)
    out = new Buffer(this.length);
  if (!offset)
    offset = 0;

  if (this.length === 0)
    return out;

  if (Array.isArray(this.value)) {
    this.value.forEach(function(item) {
      item.join(out, offset);
      offset += item.length;
    });
  } else {
    if (typeof this.value === 'number')
      out[offset] = this.value;
    else if (typeof this.value === 'string')
      out.write(this.value, offset);
    else if (Buffer.isBuffer(this.value))
      this.value.copy(out, offset);
    offset += this.length;
  }

  return out;
};


/***/ }),

/***/ "YqAc":
/*!******************************************************!*\
  !*** ./node_modules/core-js/library/modules/_uid.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

var id = 0;
var px = Math.random();
module.exports = function (key) {
  return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};


/***/ }),

/***/ "YrNz":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/mainmenu/lib/settings.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const labmenu_1 = __webpack_require__(/*! ./labmenu */ "e7FE");
/**
 * An extensible Settings menu for the application.
 */
class SettingsMenu extends labmenu_1.JupyterLabMenu {
    /**
     * Construct the settings menu.
     */
    constructor(options) {
        super(options);
        this.menu.title.label = 'Settings';
    }
}
exports.SettingsMenu = SettingsMenu;


/***/ }),

/***/ "Yrnb":
/*!*************************************************************!*\
  !*** ./node_modules/draft-js/lib/isSelectionAtLeafStart.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule isSelectionAtLeafStart
 * @format
 * 
 */



function isSelectionAtLeafStart(editorState) {
  var selection = editorState.getSelection();
  var anchorKey = selection.getAnchorKey();
  var blockTree = editorState.getBlockTree(anchorKey);
  var offset = selection.getStartOffset();

  var isAtStart = false;

  blockTree.some(function (leafSet) {
    if (offset === leafSet.get('start')) {
      isAtStart = true;
      return true;
    }

    if (offset < leafSet.get('end')) {
      return leafSet.get('leaves').some(function (leaf) {
        var leafStart = leaf.get('start');
        if (offset === leafStart) {
          isAtStart = true;
          return true;
        }

        return false;
      });
    }

    return false;
  });

  return isAtStart;
}

module.exports = isSelectionAtLeafStart;

/***/ }),

/***/ "YskG":
/*!***************************************************!*\
  !*** ./node_modules/browserify-aes/modes/cfb8.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer

function encryptByte (self, byteParam, decrypt) {
  var pad = self._cipher.encryptBlock(self._prev)
  var out = pad[0] ^ byteParam

  self._prev = Buffer.concat([
    self._prev.slice(1),
    Buffer.from([decrypt ? byteParam : out])
  ])

  return out
}

exports.encrypt = function (self, chunk, decrypt) {
  var len = chunk.length
  var out = Buffer.allocUnsafe(len)
  var i = -1

  while (++i < len) {
    out[i] = encryptByte(self, chunk[i], decrypt)
  }

  return out
}


/***/ }),

/***/ "YuTi":
/*!***********************************!*\
  !*** (webpack)/buildin/module.js ***!
  \***********************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = function(module) {
	if (!module.webpackPolyfill) {
		module.deprecate = function() {};
		module.paths = [];
		// module.parent = undefined by default
		if (!module.children) module.children = [];
		Object.defineProperty(module, "loaded", {
			enumerable: true,
			get: function() {
				return module.l;
			}
		});
		Object.defineProperty(module, "id", {
			enumerable: true,
			get: function() {
				return module.i;
			}
		});
		module.webpackPolyfill = 1;
	}
	return module;
};


/***/ }),

/***/ "YzzP":
/*!************************************************!*\
  !*** ./node_modules/mdi-react/SettingsIcon.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var SettingsIcon = function SettingsIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M12,15.5C10.07,15.5 8.5,13.93 8.5,12C8.5,10.07 10.07,8.5 12,8.5C13.93,8.5 15.5,10.07 15.5,12C15.5,13.93 13.93,15.5 12,15.5M19.43,12.97C19.47,12.65 19.5,12.33 19.5,12C19.5,11.67 19.47,11.34 19.43,11L21.54,9.37C21.73,9.22 21.78,8.95 21.66,8.73L19.66,5.27C19.54,5.05 19.27,4.96 19.05,5.05L16.56,6.05C16.04,5.66 15.5,5.32 14.87,5.07L14.5,2.42C14.46,2.18 14.25,2 14,2H10C9.75,2 9.54,2.18 9.5,2.42L9.13,5.07C8.5,5.32 7.96,5.66 7.44,6.05L4.95,5.05C4.73,4.96 4.46,5.05 4.34,5.27L2.34,8.73C2.21,8.95 2.27,9.22 2.46,9.37L4.57,11C4.53,11.34 4.5,11.67 4.5,12C4.5,12.33 4.53,12.65 4.57,12.97L2.46,14.63C2.27,14.78 2.21,15.05 2.34,15.27L4.34,18.73C4.46,18.95 4.73,19.03 4.95,18.95L7.44,17.94C7.96,18.34 8.5,18.68 9.13,18.93L9.5,21.58C9.54,21.82 9.75,22 10,22H14C14.25,22 14.46,21.82 14.5,21.58L14.87,18.93C15.5,18.67 16.04,18.34 16.56,17.94L19.05,18.95C19.27,19.03 19.54,18.95 19.66,18.73L21.66,15.27C21.78,15.05 21.73,14.78 21.54,14.63L19.43,12.97Z' })
  );
};

module.exports = SettingsIcon;


/***/ }),

/***/ "Z/Y6":
/*!*************************************************************************!*\
  !*** ./node_modules/@jupyter-widgets/jupyterlab-manager/lib/manager.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const base_1 = __webpack_require__(/*! @jupyter-widgets/base */ "Rtm6");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const semver_1 = __webpack_require__(/*! semver */ "jWEn");
const semvercache_1 = __webpack_require__(/*! ./semvercache */ "Wd7j");
/**
 * The class name added to an BackboneViewWrapper widget.
 */
const BACKBONEVIEWWRAPPER_CLASS = 'jp-BackboneViewWrapper';
class BackboneViewWrapper extends widgets_1.Widget {
    /**
     * Construct a new `Backbone` wrapper widget.
     *
     * @param view - The `Backbone.View` instance being wrapped.
     */
    constructor(view) {
        super();
        this._view = null;
        this._view = view;
        view.on('remove', () => {
            this.dispose();
        });
        this.addClass(BACKBONEVIEWWRAPPER_CLASS);
        this.node.appendChild(view.el);
    }
    onAfterAttach(msg) {
        this._view.trigger('displayed');
    }
    dispose() {
        this._view = null;
        super.dispose();
    }
}
exports.BackboneViewWrapper = BackboneViewWrapper;
/**
 * A widget manager that returns phosphor widgets.
 */
class WidgetManager extends base_1.ManagerBase {
    constructor(context, rendermime) {
        super();
        this._registry = new semvercache_1.SemVerCache();
        this._context = context;
        this._rendermime = rendermime;
        // Set _handleCommOpen so `this` is captured.
        this._handleCommOpen = (comm, msg) => __awaiter(this, void 0, void 0, function* () {
            let oldComm = new base_1.shims.services.Comm(comm);
            yield this.handle_comm_open(oldComm, msg);
        });
        context.session.kernelChanged.connect((sender, args) => {
            this._handleKernelChanged(args);
        });
        if (context.session.kernel) {
            this._handleKernelChanged({ oldValue: null, newValue: context.session.kernel });
        }
    }
    /**
     * Register a new kernel
     */
    _handleKernelChanged({ oldValue, newValue }) {
        if (oldValue) {
            oldValue.removeCommTarget(this.comm_target_name, this._handleCommOpen);
        }
        if (newValue) {
            newValue.registerCommTarget(this.comm_target_name, this._handleCommOpen);
        }
    }
    /**
     * Return a phosphor widget representing the view
     */
    display_view(msg, view, options) {
        let widget = view.pWidget ? view.pWidget : new BackboneViewWrapper(view);
        return Promise.resolve(widget);
    }
    /**
     * Create a comm.
     */
    _create_comm(target_name, model_id, data, metadata, buffers) {
        return __awaiter(this, void 0, void 0, function* () {
            let comm = yield this._context.session.kernel.connectToComm(target_name, model_id);
            if (data || metadata) {
                comm.open(data, metadata, buffers);
            }
            return Promise.resolve(new base_1.shims.services.Comm(comm));
        });
    }
    /**
     * Get the currently-registered comms.
     */
    _get_comm_info() {
        return this._context.session.kernel.requestCommInfo({ target: this.comm_target_name }).then(reply => reply.content.comms);
    }
    /**
     * Get whether the manager is disposed.
     *
     * #### Notes
     * This is a read-only property.
     */
    get isDisposed() {
        return this._context === null;
    }
    /**
     * Dispose the resources held by the manager.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        if (this._commRegistration) {
            this._commRegistration.dispose();
        }
        this._context = null;
    }
    /**
     * Resolve a URL relative to the current notebook location.
     */
    resolveUrl(url) {
        return this.context.urlResolver.resolveUrl(url).then((partial) => {
            return this.context.urlResolver.getDownloadUrl(partial);
        });
    }
    /**
     * Load a class and return a promise to the loaded object.
     */
    loadClass(className, moduleName, moduleVersion) {
        // Special-case the Jupyter base and controls packages. If we have just a
        // plain version, with no indication of the compatible range, prepend a ^ to
        // get all compatible versions. We may eventually apply this logic to all
        // widget modules. See issues #2006 and #2017 for more discussion.
        if ((moduleName === "@jupyter-widgets/base"
            || moduleName === "@jupyter-widgets/controls")
            && semver_1.valid(moduleVersion)) {
            moduleVersion = `^${moduleVersion}`;
        }
        let mod = this._registry.get(moduleName, moduleVersion);
        if (!mod) {
            return Promise.reject(`Module ${moduleName}, semver range ${moduleVersion} is not registered as a widget module`);
        }
        let modPromise;
        if (typeof mod === 'function') {
            modPromise = Promise.resolve(mod());
        }
        else {
            modPromise = Promise.resolve(mod);
        }
        return modPromise.then((mod) => {
            let cls = mod[className];
            if (!cls) {
                return Promise.reject(`Class ${className} not found in module ${moduleName}`);
            }
            return cls;
        });
    }
    get context() {
        return this._context;
    }
    get rendermime() {
        return this._rendermime;
    }
    register(data) {
        this._registry.set(data.name, data.version, data.exports);
    }
}
exports.WidgetManager = WidgetManager;


/***/ }),

/***/ "Z0cm":
/*!****************************************!*\
  !*** ./node_modules/lodash/isArray.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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;

module.exports = isArray;


/***/ }),

/***/ "Z1RB":
/*!****************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/Dropzone.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactDropzone = __webpack_require__(/*! react-dropzone */ "yzbm");

var _reactDropzone2 = _interopRequireDefault(_reactDropzone);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Dropzone = function (_Component) {
  _inherits(Dropzone, _Component);

  function Dropzone(props, context) {
    _classCallCheck(this, Dropzone);

    var _this = _possibleConstructorReturn(this, (Dropzone.__proto__ || Object.getPrototypeOf(Dropzone)).call(this, props, context));

    var _ = context.localize;

    _this.state = {
      content: ''
    };

    _this.validFiletypes = {
      image: _('image/jpeg, image/jpg, image/svg, image/png, image/gif, image/bmp, image/webp')
    };

    _this.onDrop = _this.onDrop.bind(_this);
    _this.renderSuccess = _this.renderSuccess.bind(_this);
    return _this;
  }

  _createClass(Dropzone, [{
    key: 'renderSuccess',
    value: function renderSuccess(value) {
      var _ = this.context.localize;

      if (this.props.fileType === 'image') {
        return _react2.default.createElement('div', { className: 'dropzone-container__image', style: { backgroundImage: 'url(' + value + ')' } });
      }

      return _react2.default.createElement(
        'div',
        { className: 'dropzone-container__message' },
        _('File loaded!')
      );
    }
  }, {
    key: 'componentWillMount',
    value: function componentWillMount() {
      var _ = this.context.localize;

      if (this.props.value && this.props.value !== '') {
        this.setState({ content: this.renderSuccess(this.props.value) });
        return;
      }

      this.setState({
        content: _react2.default.createElement(
          'div',
          { className: 'dropzone-container__message' },
          _react2.default.createElement(
            'p',
            null,
            _('Drop the ') + this.props.fileType + _(' to upload here or click to choose a file from your computer.')
          ),
          this.props.fileType === 'image' ? _react2.default.createElement(
            'p',
            null,
            _('Supported formats are: ') + this.validFiletypes[this.props.fileType].split('image/').join('') + '.'
          ) : null
        )
      });
    }
  }, {
    key: 'onLoad',
    value: function onLoad(e) {
      var _ = this.context.localize;
      var supportedFileTypes = this.props.fileType === 'image' ? this.validFiletypes[this.props.fileType].split('image/').join('') : this.validFiletypes[this.props.fileType];

      var parsingError = _react2.default.createElement(
        'div',
        { className: 'dropzone-container__message' },
        _react2.default.createElement(
          'p',
          null,
          _('Yikes! An error occurred while parsing this file.')
        ),
        _react2.default.createElement(
          'p',
          null,
          _('Try again with a supported file format: ') + supportedFileTypes + '.'
        )
      );

      if (this.props.fileType === 'image') {
        try {
          this.props.onUpdate(e.target.result);
          this.setState({
            content: this.renderSuccess(e.target.result)
          });
        } catch (error) {
          console.warn(error); // eslint-disable-line
          this.setState({
            content: parsingError
          });
        }
      }
    }
  }, {
    key: 'onDrop',
    value: function onDrop(accepted, rejected) {
      var _this2 = this;

      var _ = this.context.localize;
      var reader = new FileReader();

      if (accepted.length) {
        if (accepted.length > 1) {
          this.setState({
            content: _react2.default.createElement(
              'div',
              { className: 'dropzone-container__message' },
              _react2.default.createElement(
                'p',
                null,
                _('Yikes! You can only upload one file at a time.')
              ),
              _react2.default.createElement(
                'p',
                null,
                _('To upload multiple files, create multiple files and upload them individually.')
              )
            )
          });
          return;
        }
        this.setState({ content: _('Loading...') });
        reader.onload = function (e) {
          return _this2.onLoad(e);
        };
        if (this.props.fileType === 'image') {
          reader.readAsDataURL(accepted[0]);
        }
      }

      if (rejected.length) {
        var supportedFileTypes = this.props.fileType === 'image' ? this.validFiletypes[this.props.fileType].split('image/').join('') : this.validFiletypes[this.props.fileType];

        this.setState({
          content: _react2.default.createElement(
            'div',
            { className: 'dropzone-container__message' },
            _react2.default.createElement(
              'p',
              null,
              _("Yikes! This doesn't look like a valid ") + this.props.fileType + _(' to us. ')
            ),
            _react2.default.createElement(
              'p',
              null,
              _('Try again with a ') + supportedFileTypes + ' file.'
            )
          )
        });
      }
    }
  }, {
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        _reactDropzone2.default,
        {
          accept: this.validFiletypes[this.props.fileType],
          onDrop: this.onDrop,
          className: 'dropzone-container',
          activeClassName: 'dropzone-container--active',
          rejectClassName: 'dropzone-container--rejected'
        },
        _react2.default.createElement(
          'div',
          { className: 'dropzone-container__content' },
          this.state.content
        )
      );
    }
  }]);

  return Dropzone;
}(_react.Component);

Dropzone.propTypes = {
  fileType: _propTypes2.default.string.isRequired,
  onUpdate: _propTypes2.default.func,
  value: _propTypes2.default.any
};

Dropzone.contextTypes = {
  localize: _propTypes2.default.func
};

exports.default = Dropzone;
//# sourceMappingURL=Dropzone.js.map

/***/ }),

/***/ "Z2+3":
/*!**********************************************************!*\
  !*** ./node_modules/elliptic/lib/elliptic/curve/mont.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var curve = __webpack_require__(/*! ../curve */ "QTa/");
var BN = __webpack_require__(/*! bn.js */ "OZ/i");
var inherits = __webpack_require__(/*! inherits */ "P7XM");
var Base = curve.base;

var elliptic = __webpack_require__(/*! ../../elliptic */ "MzeL");
var utils = elliptic.utils;

function MontCurve(conf) {
  Base.call(this, 'mont', conf);

  this.a = new BN(conf.a, 16).toRed(this.red);
  this.b = new BN(conf.b, 16).toRed(this.red);
  this.i4 = new BN(4).toRed(this.red).redInvm();
  this.two = new BN(2).toRed(this.red);
  this.a24 = this.i4.redMul(this.a.redAdd(this.two));
}
inherits(MontCurve, Base);
module.exports = MontCurve;

MontCurve.prototype.validate = function validate(point) {
  var x = point.normalize().x;
  var x2 = x.redSqr();
  var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);
  var y = rhs.redSqrt();

  return y.redSqr().cmp(rhs) === 0;
};

function Point(curve, x, z) {
  Base.BasePoint.call(this, curve, 'projective');
  if (x === null && z === null) {
    this.x = this.curve.one;
    this.z = this.curve.zero;
  } else {
    this.x = new BN(x, 16);
    this.z = new BN(z, 16);
    if (!this.x.red)
      this.x = this.x.toRed(this.curve.red);
    if (!this.z.red)
      this.z = this.z.toRed(this.curve.red);
  }
}
inherits(Point, Base.BasePoint);

MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
  return this.point(utils.toArray(bytes, enc), 1);
};

MontCurve.prototype.point = function point(x, z) {
  return new Point(this, x, z);
};

MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
  return Point.fromJSON(this, obj);
};

Point.prototype.precompute = function precompute() {
  // No-op
};

Point.prototype._encode = function _encode() {
  return this.getX().toArray('be', this.curve.p.byteLength());
};

Point.fromJSON = function fromJSON(curve, obj) {
  return new Point(curve, obj[0], obj[1] || curve.one);
};

Point.prototype.inspect = function inspect() {
  if (this.isInfinity())
    return '<EC Point Infinity>';
  return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
      ' z: ' + this.z.fromRed().toString(16, 2) + '>';
};

Point.prototype.isInfinity = function isInfinity() {
  // XXX This code assumes that zero is always zero in red
  return this.z.cmpn(0) === 0;
};

Point.prototype.dbl = function dbl() {
  // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
  // 2M + 2S + 4A

  // A = X1 + Z1
  var a = this.x.redAdd(this.z);
  // AA = A^2
  var aa = a.redSqr();
  // B = X1 - Z1
  var b = this.x.redSub(this.z);
  // BB = B^2
  var bb = b.redSqr();
  // C = AA - BB
  var c = aa.redSub(bb);
  // X3 = AA * BB
  var nx = aa.redMul(bb);
  // Z3 = C * (BB + A24 * C)
  var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));
  return this.curve.point(nx, nz);
};

Point.prototype.add = function add() {
  throw new Error('Not supported on Montgomery curve');
};

Point.prototype.diffAdd = function diffAdd(p, diff) {
  // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
  // 4M + 2S + 6A

  // A = X2 + Z2
  var a = this.x.redAdd(this.z);
  // B = X2 - Z2
  var b = this.x.redSub(this.z);
  // C = X3 + Z3
  var c = p.x.redAdd(p.z);
  // D = X3 - Z3
  var d = p.x.redSub(p.z);
  // DA = D * A
  var da = d.redMul(a);
  // CB = C * B
  var cb = c.redMul(b);
  // X5 = Z1 * (DA + CB)^2
  var nx = diff.z.redMul(da.redAdd(cb).redSqr());
  // Z5 = X1 * (DA - CB)^2
  var nz = diff.x.redMul(da.redISub(cb).redSqr());
  return this.curve.point(nx, nz);
};

Point.prototype.mul = function mul(k) {
  var t = k.clone();
  var a = this; // (N / 2) * Q + Q
  var b = this.curve.point(null, null); // (N / 2) * Q
  var c = this; // Q

  for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))
    bits.push(t.andln(1));

  for (var i = bits.length - 1; i >= 0; i--) {
    if (bits[i] === 0) {
      // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q
      a = a.diffAdd(b, c);
      // N * Q = 2 * ((N / 2) * Q + Q))
      b = b.dbl();
    } else {
      // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)
      b = a.diffAdd(b, c);
      // N * Q + Q = 2 * ((N / 2) * Q + Q)
      a = a.dbl();
    }
  }
  return b;
};

Point.prototype.mulAdd = function mulAdd() {
  throw new Error('Not supported on Montgomery curve');
};

Point.prototype.jumlAdd = function jumlAdd() {
  throw new Error('Not supported on Montgomery curve');
};

Point.prototype.eq = function eq(other) {
  return this.getX().cmp(other.getX()) === 0;
};

Point.prototype.normalize = function normalize() {
  this.x = this.x.redMul(this.z.redInvm());
  this.z = this.curve.one;
  return this;
};

Point.prototype.getX = function getX() {
  // Normalize coordinates
  this.normalize();

  return this.x.fromRed();
};


/***/ }),

/***/ "Z3kI":
/*!********************************************!*\
  !*** ./node_modules/mdi-react/PollIcon.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var PollIcon = function PollIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M3,22V8H7V22H3M10,22V2H14V22H10M17,22V14H21V22H17Z' })
  );
};

module.exports = PollIcon;


/***/ }),

/***/ "Z4QM":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/sd.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var months = [
    'جنوري',
    'فيبروري',
    'مارچ',
    'اپريل',
    'مئي',
    'جون',
    'جولاءِ',
    'آگسٽ',
    'سيپٽمبر',
    'آڪٽوبر',
    'نومبر',
    'ڊسمبر'
];
var days = [
    'آچر',
    'سومر',
    'اڱارو',
    'اربع',
    'خميس',
    'جمع',
    'ڇنڇر'
];

var sd = moment.defineLocale('sd', {
    months : months,
    monthsShort : months,
    weekdays : days,
    weekdaysShort : days,
    weekdaysMin : days,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd، D MMMM YYYY HH:mm'
    },
    meridiemParse: /صبح|شام/,
    isPM : function (input) {
        return 'شام' === input;
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 12) {
            return 'صبح';
        }
        return 'شام';
    },
    calendar : {
        sameDay : '[اڄ] LT',
        nextDay : '[سڀاڻي] LT',
        nextWeek : 'dddd [اڳين هفتي تي] LT',
        lastDay : '[ڪالهه] LT',
        lastWeek : '[گزريل هفتي] dddd [تي] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : '%s پوء',
        past : '%s اڳ',
        s : 'چند سيڪنڊ',
        ss : '%d سيڪنڊ',
        m : 'هڪ منٽ',
        mm : '%d منٽ',
        h : 'هڪ ڪلاڪ',
        hh : '%d ڪلاڪ',
        d : 'هڪ ڏينهن',
        dd : '%d ڏينهن',
        M : 'هڪ مهينو',
        MM : '%d مهينا',
        y : 'هڪ سال',
        yy : '%d سال'
    },
    preparse: function (string) {
        return string.replace(/،/g, ',');
    },
    postformat: function (string) {
        return string.replace(/,/g, '،');
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return sd;

})));


/***/ }),

/***/ "Z7lC":
/*!**************************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/text_editors/RichText/debounce.js ***!
  \**************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = debounce;
var DEBOUNCE_DELAY = 250;
var timeout = void 0;

function clearTimeout() {
  window.clearTimeout(timeout);
  timeout = null;
}

function debounce(fn, args) {
  if (timeout) {
    clearTimeout();
  }

  timeout = window.setTimeout(function () {
    fn.apply(null, args);
    timeout = null;
  }, DEBOUNCE_DELAY);
}
//# sourceMappingURL=debounce.js.map

/***/ }),

/***/ "Z8oC":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_listCacheSet.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var assocIndexOf = __webpack_require__(/*! ./_assocIndexOf */ "y1pI");

/**
 * 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;
}

module.exports = listCacheSet;


/***/ }),

/***/ "Z9sL":
/*!**************************************!*\
  !*** ./node_modules/fbjs/lib/URI.js ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * 
 */



function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var URI = function () {
  function URI(uri) {
    _classCallCheck(this, URI);

    this._uri = uri;
  }

  URI.prototype.toString = function toString() {
    return this._uri;
  };

  return URI;
}();

module.exports = URI;

/***/ }),

/***/ "ZAMP":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/ms-my.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var msMy = moment.defineLocale('ms-my', {
    months : 'Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember'.split('_'),
    monthsShort : 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis'.split('_'),
    weekdays : 'Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu'.split('_'),
    weekdaysShort : 'Ahd_Isn_Sel_Rab_Kha_Jum_Sab'.split('_'),
    weekdaysMin : 'Ah_Is_Sl_Rb_Km_Jm_Sb'.split('_'),
    longDateFormat : {
        LT : 'HH.mm',
        LTS : 'HH.mm.ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY [pukul] HH.mm',
        LLLL : 'dddd, D MMMM YYYY [pukul] HH.mm'
    },
    meridiemParse: /pagi|tengahari|petang|malam/,
    meridiemHour: function (hour, meridiem) {
        if (hour === 12) {
            hour = 0;
        }
        if (meridiem === 'pagi') {
            return hour;
        } else if (meridiem === 'tengahari') {
            return hour >= 11 ? hour : hour + 12;
        } else if (meridiem === 'petang' || meridiem === 'malam') {
            return hour + 12;
        }
    },
    meridiem : function (hours, minutes, isLower) {
        if (hours < 11) {
            return 'pagi';
        } else if (hours < 15) {
            return 'tengahari';
        } else if (hours < 19) {
            return 'petang';
        } else {
            return 'malam';
        }
    },
    calendar : {
        sameDay : '[Hari ini pukul] LT',
        nextDay : '[Esok pukul] LT',
        nextWeek : 'dddd [pukul] LT',
        lastDay : '[Kelmarin pukul] LT',
        lastWeek : 'dddd [lepas pukul] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'dalam %s',
        past : '%s yang lepas',
        s : 'beberapa saat',
        ss : '%d saat',
        m : 'seminit',
        mm : '%d minit',
        h : 'sejam',
        hh : '%d jam',
        d : 'sehari',
        dd : '%d hari',
        M : 'sebulan',
        MM : '%d bulan',
        y : 'setahun',
        yy : '%d tahun'
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return msMy;

})));


/***/ }),

/***/ "ZCpW":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_baseMatches.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseIsMatch = __webpack_require__(/*! ./_baseIsMatch */ "lm/5"),
    getMatchData = __webpack_require__(/*! ./_getMatchData */ "O7RO"),
    matchesStrictComparable = __webpack_require__(/*! ./_matchesStrictComparable */ "IOzZ");

/**
 * 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);
  };
}

module.exports = baseMatches;


/***/ }),

/***/ "ZD1G":
/*!*****************************************************************!*\
  !*** ./node_modules/@jupyter-widgets/base/lib/services-shim.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var shims;
(function (shims) {
    var services;
    (function (services) {
        /**
         * Public constructor
         * @param jsServicesKernel - @jupyterlab/services Kernel.IKernel instance
         */
        var CommManager = /** @class */ (function () {
            function CommManager(jsServicesKernel) {
                this.targets = Object.create(null);
                this.comms = Object.create(null);
                this.kernel = null;
                this.jsServicesKernel = null;
                this.init_kernel(jsServicesKernel);
            }
            /**
             * Hookup kernel events.
             * @param  {Kernel.IKernel} jsServicesKernel - @jupyterlab/services Kernel.IKernel instance
             */
            CommManager.prototype.init_kernel = function (jsServicesKernel) {
                this.kernel = jsServicesKernel; // These aren't really the same.
                this.jsServicesKernel = jsServicesKernel;
            };
            /**
             * Creates a new connected comm
             */
            CommManager.prototype.new_comm = function (target_name, data, callbacks, metadata, comm_id, buffers) {
                return __awaiter(this, void 0, void 0, function () {
                    var c, comm;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0: return [4 /*yield*/, Promise.resolve(this.jsServicesKernel.connectToComm(target_name, comm_id))];
                            case 1:
                                c = _a.sent();
                                comm = new Comm(c);
                                this.register_comm(comm);
                                comm.open(data, callbacks, metadata, buffers);
                                return [2 /*return*/, comm];
                        }
                    });
                });
            };
            /**
             * Register a comm target
             * @param  {string} target_name
             * @param  {(Comm, object) => void} f - callback that is called when the
             *                         comm is made.  Signature of f(comm, msg).
             */
            CommManager.prototype.register_target = function (target_name, f) {
                var _this = this;
                var handle = this.jsServicesKernel.registerCommTarget(target_name, function (jsServicesComm, msg) {
                    // Create the comm.
                    var comm = new Comm(jsServicesComm);
                    _this.register_comm(comm);
                    // Call the callback for the comm.
                    try {
                        return f(comm, msg);
                    }
                    catch (e) {
                        comm.close();
                        console.error(e);
                        console.error(new Error('Exception opening new comm'));
                    }
                });
                this.targets[target_name] = handle;
            };
            /**
             * Unregisters a comm target
             * @param  {string} target_name
             */
            CommManager.prototype.unregister_target = function (target_name, f) {
                var handle = this.targets[target_name];
                handle.dispose();
                delete this.targets[target_name];
            };
            /**
             * Register a comm in the mapping
             */
            CommManager.prototype.register_comm = function (comm) {
                this.comms[comm.comm_id] = Promise.resolve(comm);
                comm.kernel = this.kernel;
                return comm.comm_id;
            };
            return CommManager;
        }());
        services.CommManager = CommManager;
        /**
         * Public constructor
         * @param  {IComm} jsServicesComm - @jupyterlab/services IComm instance
         */
        var Comm = /** @class */ (function () {
            function Comm(jsServicesComm) {
                this.jsServicesComm = null;
                this.jsServicesComm = jsServicesComm;
            }
            Object.defineProperty(Comm.prototype, "comm_id", {
                /**
                 * Comm id
                 * @return {string}
                 */
                get: function () {
                    return this.jsServicesComm.commId;
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(Comm.prototype, "target_name", {
                /**
                 * Target name
                 * @return {string}
                 */
                get: function () {
                    return this.jsServicesComm.targetName;
                },
                enumerable: true,
                configurable: true
            });
            /**
             * Opens a sibling comm in the backend
             * @param  data
             * @param  callbacks
             * @param  metadata
             * @return msg id
             */
            Comm.prototype.open = function (data, callbacks, metadata, buffers) {
                var future = this.jsServicesComm.open(data, metadata, buffers);
                this._hookupCallbacks(future, callbacks);
                return future.msg.header.msg_id;
            };
            /**
             * Sends a message to the sibling comm in the backend
             * @param  data
             * @param  callbacks
             * @param  metadata
             * @param  buffers
             * @return message id
             */
            Comm.prototype.send = function (data, callbacks, metadata, buffers) {
                var future = this.jsServicesComm.send(data, metadata, buffers);
                this._hookupCallbacks(future, callbacks);
                return future.msg.header.msg_id;
            };
            /**
             * Closes the sibling comm in the backend
             * @param  data
             * @param  callbacks
             * @param  metadata
             * @return msg id
             */
            Comm.prototype.close = function (data, callbacks, metadata, buffers) {
                var future = this.jsServicesComm.close(data, metadata, buffers);
                this._hookupCallbacks(future, callbacks);
                return future.msg.header.msg_id;
            };
            /**
             * Register a message handler
             * @param  callback, which is given a message
             */
            Comm.prototype.on_msg = function (callback) {
                this.jsServicesComm.onMsg = callback.bind(this);
            };
            /**
             * Register a handler for when the comm is closed by the backend
             * @param  callback, which is given a message
             */
            Comm.prototype.on_close = function (callback) {
                this.jsServicesComm.onClose = callback.bind(this);
            };
            /**
             * Hooks callback object up with @jupyterlab/services IKernelFuture
             * @param  @jupyterlab/services IKernelFuture instance
             * @param  callbacks
             */
            Comm.prototype._hookupCallbacks = function (future, callbacks) {
                if (callbacks) {
                    future.onReply = function (msg) {
                        if (callbacks.shell && callbacks.shell.reply) {
                            callbacks.shell.reply(msg);
                        }
                        // TODO: Handle payloads.  See https://github.com/jupyter/notebook/blob/master/notebook/static/services/kernels/kernel.js#L923-L947
                    };
                    future.onStdin = function (msg) {
                        if (callbacks.input) {
                            callbacks.input(msg);
                        }
                    };
                    future.onIOPub = function (msg) {
                        if (callbacks.iopub) {
                            if (callbacks.iopub.status && msg.header.msg_type === 'status') {
                                callbacks.iopub.status(msg);
                            }
                            else if (callbacks.iopub.clear_output && msg.header.msg_type === 'clear_output') {
                                callbacks.iopub.clear_output(msg);
                            }
                            else if (callbacks.iopub.output) {
                                switch (msg.header.msg_type) {
                                    case 'display_data':
                                    case 'execute_result':
                                        callbacks.iopub.output(msg);
                                        break;
                                    default: break;
                                }
                            }
                        }
                    };
                }
            };
            return Comm;
        }());
        services.Comm = Comm;
    })(services = shims.services || (shims.services = {}));
})(shims = exports.shims || (exports.shims = {}));


/***/ }),

/***/ "ZDAU":
/*!*******************************************!*\
  !*** ./node_modules/cipher-base/index.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer
var Transform = __webpack_require__(/*! stream */ "1IWx").Transform
var StringDecoder = __webpack_require__(/*! string_decoder */ "qiJe").StringDecoder
var inherits = __webpack_require__(/*! inherits */ "P7XM")

function CipherBase (hashMode) {
  Transform.call(this)
  this.hashMode = typeof hashMode === 'string'
  if (this.hashMode) {
    this[hashMode] = this._finalOrDigest
  } else {
    this.final = this._finalOrDigest
  }
  if (this._final) {
    this.__final = this._final
    this._final = null
  }
  this._decoder = null
  this._encoding = null
}
inherits(CipherBase, Transform)

CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
  if (typeof data === 'string') {
    data = Buffer.from(data, inputEnc)
  }

  var outData = this._update(data)
  if (this.hashMode) return this

  if (outputEnc) {
    outData = this._toString(outData, outputEnc)
  }

  return outData
}

CipherBase.prototype.setAutoPadding = function () {}
CipherBase.prototype.getAuthTag = function () {
  throw new Error('trying to get auth tag in unsupported state')
}

CipherBase.prototype.setAuthTag = function () {
  throw new Error('trying to set auth tag in unsupported state')
}

CipherBase.prototype.setAAD = function () {
  throw new Error('trying to set aad in unsupported state')
}

CipherBase.prototype._transform = function (data, _, next) {
  var err
  try {
    if (this.hashMode) {
      this._update(data)
    } else {
      this.push(this._update(data))
    }
  } catch (e) {
    err = e
  } finally {
    next(err)
  }
}
CipherBase.prototype._flush = function (done) {
  var err
  try {
    this.push(this.__final())
  } catch (e) {
    err = e
  }

  done(err)
}
CipherBase.prototype._finalOrDigest = function (outputEnc) {
  var outData = this.__final() || Buffer.alloc(0)
  if (outputEnc) {
    outData = this._toString(outData, outputEnc, true)
  }
  return outData
}

CipherBase.prototype._toString = function (value, enc, fin) {
  if (!this._decoder) {
    this._decoder = new StringDecoder(enc)
    this._encoding = enc
  }

  if (this._encoding !== enc) throw new Error('can\'t switch encodings')

  var out = this._decoder.write(value)
  if (fin) {
    out += this._decoder.end()
  }

  return out
}

module.exports = CipherBase


/***/ }),

/***/ "ZDkZ":
/*!**********************************************************!*\
  !*** ./node_modules/@jupyter-widgets/base/css/index.css ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "2wu2");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "ZE44":
/*!*************************************************************!*\
  !*** ./node_modules/react-day-picker/lib/src/classNames.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
// Proxy object to map classnames when css modules are not used

exports.default = {
  container: 'DayPicker',
  wrapper: 'DayPicker-wrapper',
  interactionDisabled: 'DayPicker--interactionDisabled',
  months: 'DayPicker-Months',
  month: 'DayPicker-Month',

  navBar: 'DayPicker-NavBar',
  navButtonPrev: 'DayPicker-NavButton DayPicker-NavButton--prev',
  navButtonNext: 'DayPicker-NavButton DayPicker-NavButton--next',
  navButtonInteractionDisabled: 'DayPicker-NavButton--interactionDisabled',

  caption: 'DayPicker-Caption',
  weekdays: 'DayPicker-Weekdays',
  weekdaysRow: 'DayPicker-WeekdaysRow',
  weekday: 'DayPicker-Weekday',
  body: 'DayPicker-Body',
  week: 'DayPicker-Week',
  weekNumber: 'DayPicker-WeekNumber',
  day: 'DayPicker-Day',
  footer: 'DayPicker-Footer',
  todayButton: 'DayPicker-TodayButton',

  // default modifiers
  today: 'today',
  selected: 'selected',
  disabled: 'disabled',
  outside: 'outside'
};
//# sourceMappingURL=classNames.js.map

/***/ }),

/***/ "ZEK9":
/*!************************************************!*\
  !*** ./node_modules/public-encrypt/browser.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports.publicEncrypt = __webpack_require__(/*! ./publicEncrypt */ "rSVQ")
exports.privateDecrypt = __webpack_require__(/*! ./privateDecrypt */ "DyzK")

exports.privateEncrypt = function privateEncrypt (key, buf) {
  return exports.publicEncrypt(key, buf, true)
}

exports.publicDecrypt = function publicDecrypt (key, buf) {
  return exports.privateDecrypt(key, buf, true)
}


/***/ }),

/***/ "ZHg6":
/*!*****************************************************************!*\
  !*** ./node_modules/@jupyterlab/settingeditor/lib/raweditor.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const codeeditor_1 = __webpack_require__(/*! @jupyterlab/codeeditor */ "sLCx");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const inspector_1 = __webpack_require__(/*! ./inspector */ "a1E9");
const splitpanel_1 = __webpack_require__(/*! ./splitpanel */ "wHxL");
/**
 * A class name added to all raw editors.
 */
const RAW_EDITOR_CLASS = 'jp-SettingsRawEditor';
/**
 * A class name added to the user settings editor.
 */
const USER_CLASS = 'jp-SettingsRawEditor-user';
/**
 * A class name added to the user editor when there are validation errors.
 */
const ERROR_CLASS = 'jp-mod-error';
/**
 * The banner text for the default editor.
 */
const DEFAULT_TITLE = 'System Defaults';
/**
 * The banner text for the user settings editor.
 */
const USER_TITLE = 'User Overrides';
/**
 * A raw JSON settings editor.
 */
class RawEditor extends splitpanel_1.SplitPanel {
    /**
     * Create a new plugin editor.
     */
    constructor(options) {
        super({
            orientation: 'horizontal',
            renderer: splitpanel_1.SplitPanel.defaultRenderer,
            spacing: 1
        });
        this._canRevert = false;
        this._canSave = false;
        this._commandsChanged = new signaling_1.Signal(this);
        this._settings = null;
        this._toolbar = new apputils_1.Toolbar();
        const { commands, editorFactory, registry } = options;
        this.registry = registry;
        this._commands = commands;
        // Create read-only defaults editor.
        const defaults = (this._defaults = new codeeditor_1.CodeEditorWrapper({
            model: new codeeditor_1.CodeEditor.Model(),
            factory: editorFactory
        }));
        defaults.editor.model.value.text = '';
        defaults.editor.model.mimeType = 'text/javascript';
        defaults.editor.setOption('readOnly', true);
        // Create read-write user settings editor.
        const user = (this._user = new codeeditor_1.CodeEditorWrapper({
            model: new codeeditor_1.CodeEditor.Model(),
            factory: editorFactory,
            config: { lineNumbers: true }
        }));
        user.addClass(USER_CLASS);
        user.editor.model.mimeType = 'text/javascript';
        user.editor.model.value.changed.connect(this._onTextChanged, this);
        // Create and set up an inspector.
        this._inspector = inspector_1.createInspector(this, options.rendermime);
        this.addClass(RAW_EDITOR_CLASS);
        this._onSaveError = options.onSaveError;
        this.addWidget(Private.defaultsEditor(defaults));
        this.addWidget(Private.userEditor(user, this._toolbar, this._inspector));
    }
    /**
     * Whether the raw editor revert functionality is enabled.
     */
    get canRevert() {
        return this._canRevert;
    }
    /**
     * Whether the raw editor save functionality is enabled.
     */
    get canSave() {
        return this._canSave;
    }
    /**
     * Emits when the commands passed in at instantiation change.
     */
    get commandsChanged() {
        return this._commandsChanged;
    }
    /**
     * Whether the debug panel is visible.
     */
    get isDebugVisible() {
        return this._inspector.isVisible;
    }
    /**
     * Tests whether the settings have been modified and need saving.
     */
    get isDirty() {
        return this._user.editor.model.value.text !== this._settings.raw;
    }
    /**
     * The plugin settings being edited.
     */
    get settings() {
        return this._settings;
    }
    set settings(settings) {
        if (!settings && !this._settings) {
            return;
        }
        const samePlugin = settings && this._settings && settings.plugin === this._settings.plugin;
        if (samePlugin) {
            return;
        }
        const defaults = this._defaults;
        const user = this._user;
        // Disconnect old settings change handler.
        if (this._settings) {
            this._settings.changed.disconnect(this._onSettingsChanged, this);
        }
        if (settings) {
            this._settings = settings;
            this._settings.changed.connect(this._onSettingsChanged, this);
            this._onSettingsChanged();
        }
        else {
            this._settings = null;
            defaults.editor.model.value.text = '';
            user.editor.model.value.text = '';
        }
        this.update();
    }
    /**
     * Get the relative sizes of the two editor panels.
     */
    get sizes() {
        return this.relativeSizes();
    }
    set sizes(sizes) {
        this.setRelativeSizes(sizes);
    }
    /**
     * The inspectable source editor for user input.
     */
    get source() {
        return this._user.editor;
    }
    /**
     * Dispose of the resources held by the raw editor.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        super.dispose();
        this._defaults.dispose();
        this._user.dispose();
    }
    /**
     * Revert the editor back to original settings.
     */
    revert() {
        this._user.editor.model.value.text = this.settings.raw;
        this._updateToolbar(false, false);
    }
    /**
     * Save the contents of the raw editor.
     */
    save() {
        if (!this.isDirty) {
            return Promise.resolve(undefined);
        }
        const settings = this._settings;
        const source = this._user.editor.model.value.text;
        return settings
            .save(source)
            .then(() => {
            this._updateToolbar(false, false);
        })
            .catch(reason => {
            this._updateToolbar(true, false);
            this._onSaveError(reason);
        });
    }
    /**
     * Toggle the debug functionality.
     */
    toggleDebug() {
        const inspector = this._inspector;
        if (inspector.isHidden) {
            inspector.show();
        }
        else {
            inspector.hide();
        }
        this._updateToolbar();
    }
    /**
     * Handle `after-attach` messages.
     */
    onAfterAttach(msg) {
        Private.populateToolbar(this._commands, this._toolbar);
        this.update();
    }
    /**
     * Handle `'update-request'` messages.
     */
    onUpdateRequest(msg) {
        const settings = this._settings;
        const defaults = this._defaults;
        const user = this._user;
        if (settings) {
            defaults.editor.refresh();
            user.editor.refresh();
        }
    }
    /**
     * Handle text changes in the underlying editor.
     */
    _onTextChanged() {
        const raw = this._user.editor.model.value.text;
        const settings = this._settings;
        this.removeClass(ERROR_CLASS);
        // If there are no settings loaded or there are no changes, bail.
        if (!settings || settings.raw === raw) {
            this._updateToolbar(false, false);
            return;
        }
        const errors = settings.validate(raw);
        if (errors) {
            this.addClass(ERROR_CLASS);
            this._updateToolbar(true, false);
            return;
        }
        this._updateToolbar(true, true);
    }
    /**
     * Handle updates to the settings.
     */
    _onSettingsChanged() {
        const settings = this._settings;
        const defaults = this._defaults;
        const user = this._user;
        defaults.editor.model.value.text = settings.annotatedDefaults();
        user.editor.model.value.text = settings.raw;
    }
    _updateToolbar(revert = this._canRevert, save = this._canSave) {
        const commands = this._commands;
        this._canRevert = revert;
        this._canSave = save;
        this._commandsChanged.emit([
            commands.debug,
            commands.revert,
            commands.save
        ]);
    }
}
exports.RawEditor = RawEditor;
/**
 * A namespace for private module data.
 */
var Private;
(function (Private) {
    /**
     * Returns the wrapped setting defaults editor.
     */
    function defaultsEditor(editor) {
        const widget = new widgets_1.Widget();
        const layout = (widget.layout = new widgets_1.BoxLayout({ spacing: 0 }));
        const banner = new widgets_1.Widget();
        const bar = new apputils_1.Toolbar();
        banner.node.innerText = DEFAULT_TITLE;
        bar.insertItem(0, 'banner', banner);
        layout.addWidget(bar);
        layout.addWidget(editor);
        return widget;
    }
    Private.defaultsEditor = defaultsEditor;
    /**
     * Populate the raw editor toolbar.
     */
    function populateToolbar(commands, toolbar) {
        const { debug, registry, revert, save } = commands;
        toolbar.addItem('spacer', apputils_1.Toolbar.createSpacerItem());
        // Note the button order. The rationale here is that no matter what state
        // the toolbar is in, the relative location of the revert button in the
        // toolbar remains the same.
        [revert, debug, save].forEach(name => {
            const item = new apputils_1.CommandToolbarButton({ commands: registry, id: name });
            toolbar.addItem(name, item);
        });
    }
    Private.populateToolbar = populateToolbar;
    /**
     * Returns the wrapped user overrides editor.
     */
    function userEditor(editor, toolbar, inspector) {
        const widget = new widgets_1.Widget();
        const layout = (widget.layout = new widgets_1.BoxLayout({ spacing: 0 }));
        const banner = new widgets_1.Widget();
        banner.node.innerText = USER_TITLE;
        toolbar.insertItem(0, 'banner', banner);
        layout.addWidget(toolbar);
        layout.addWidget(editor);
        layout.addWidget(inspector);
        return widget;
    }
    Private.userEditor = userEditor;
})(Private || (Private = {}));


/***/ }),

/***/ "ZK8w":
/*!*******************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/application/style/datagrid.css ***!
  \*******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.p-DataGrid {\n  min-width: 64px;\n  min-height: 64px;\n  border: 1px solid #a0a0a0;\n}\n\n.p-DataGrid-scrollCorner {\n  background-color: #f0f0f0;\n}\n\n.p-DataGrid-scrollCorner::after {\n  content: '';\n  position: absolute;\n  top: 0;\n  left: 0;\n  width: 1px;\n  height: 1px;\n  background-color: #a0a0a0;\n}\n", ""]);

// exports


/***/ }),

/***/ "ZLJe":
/*!*********************************************!*\
  !*** ./node_modules/entities/maps/xml.json ***!
  \*********************************************/
/*! exports provided: amp, apos, gt, lt, quot, default */
/***/ (function(module) {

module.exports = {"amp":"&","apos":"'","gt":">","lt":"<","quot":"\""};

/***/ }),

/***/ "ZLPw":
/*!***************************************************!*\
  !*** ./node_modules/mdi-react/LinkedinBoxIcon.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var LinkedinBoxIcon = function LinkedinBoxIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M19,3C20.1,3 21,3.9 21,5V19C21,20.1 20.1,21 19,21H5C3.9,21 3,20.1 3,19V5C3,3.9 3.9,3 5,3H19M18.5,18.5V13.2C18.5,11.4 17.04,9.94 15.24,9.94C14.39,9.94 13.4,10.46 12.92,11.24V10.13H10.13V18.5H12.92V13.57C12.92,12.8 13.54,12.17 14.31,12.17C15.08,12.17 15.71,12.8 15.71,13.57V18.5H18.5M6.88,8.56C7.81,8.56 8.56,7.81 8.56,6.88C8.56,5.95 7.81,5.19 6.88,5.19C5.95,5.19 5.19,5.95 5.19,6.88C5.19,7.81 5.95,8.56 6.88,8.56M8.27,18.5V10.13H5.5V18.5H8.27Z' })
  );
};

module.exports = LinkedinBoxIcon;


/***/ }),

/***/ "ZM8Y":
/*!**********************************************************!*\
  !*** ./node_modules/draft-js-import-element/lib/main.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _stateFromElement = __webpack_require__(/*! ./stateFromElement */ "F3q3");

Object.keys(_stateFromElement).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _stateFromElement[key];
    }
  });
});

/***/ }),

/***/ "ZMQG":
/*!****************************************************!*\
  !*** ./node_modules/base16/lib/atelier-seaside.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'atelier seaside',
  author: 'bram de haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/seaside/)',
  base00: '#131513',
  base01: '#242924',
  base02: '#5e6e5e',
  base03: '#687d68',
  base04: '#809980',
  base05: '#8ca68c',
  base06: '#cfe8cf',
  base07: '#f0fff0',
  base08: '#e6193c',
  base09: '#87711d',
  base0A: '#c3c322',
  base0B: '#29a329',
  base0C: '#1999b3',
  base0D: '#3d62f5',
  base0E: '#ad2bee',
  base0F: '#e619c3'
};
module.exports = exports['default'];

/***/ }),

/***/ "ZPDT":
/*!**************************************************************************!*\
  !*** ./node_modules/@jupyterlab/extensionmanager-extension/lib/index.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const application_1 = __webpack_require__(/*! @jupyterlab/application */ "FkFl");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const extensionmanager_1 = __webpack_require__(/*! @jupyterlab/extensionmanager */ "pfxX");
/**
 * IDs of the commands added by this extension.
 */
var CommandIDs;
(function (CommandIDs) {
    CommandIDs.enable = 'extensionmanager:enable';
    CommandIDs.hide = 'extensionmanager:hide-main';
    CommandIDs.show = 'extensionmanager:activate-main';
    CommandIDs.toggle = 'extensionmanager:toggle-main';
})(CommandIDs || (CommandIDs = {}));
/**
 * The extension manager plugin.
 */
const plugin = {
    id: '@jupyterlab/extensionmanager-extension:plugin',
    autoStart: true,
    requires: [coreutils_1.ISettingRegistry, application_1.ILayoutRestorer, application_1.IRouter],
    activate: (app, registry, restorer, router) => __awaiter(this, void 0, void 0, function* () {
        const settings = yield registry.load(plugin.id);
        let enabled = settings.composite['enabled'] === true;
        const { shell, serviceManager } = app;
        let view;
        const createView = () => {
            const v = new extensionmanager_1.ExtensionView(serviceManager);
            v.id = 'extensionmanager.main-view';
            v.title.iconClass = 'jp-ExtensionIcon jp-SideBar-tabIcon';
            v.title.caption = 'Extension Manager';
            restorer.add(v, v.id);
            return v;
        };
        if (enabled) {
            view = createView();
            shell.addToLeftArea(view, { rank: 1000 });
        }
        // If the extension is enabled or disabled,
        // add or remove it from the left area.
        app.restored.then(() => {
            settings.changed.connect(() => __awaiter(this, void 0, void 0, function* () {
                enabled = settings.composite['enabled'] === true;
                if (enabled && (!view || (view && !view.isAttached))) {
                    const accepted = yield Private.showWarning();
                    if (!accepted) {
                        settings.set('enabled', false);
                        return;
                    }
                    view = view || createView();
                    shell.addToLeftArea(view);
                }
                else if (!enabled && view && view.isAttached) {
                    view.close();
                }
            }));
        });
        addCommands(app, view);
    })
};
/**
 * Add the main file view commands to the application's command registry.
 */
function addCommands(app, view) {
    const { commands } = app;
    commands.addCommand(CommandIDs.show, {
        label: 'Show Extension Manager',
        execute: () => {
            app.shell.activateById(view.id);
        }
    });
    commands.addCommand(CommandIDs.hide, {
        execute: () => {
            if (!view.isHidden) {
                app.shell.collapseLeft();
            }
        }
    });
    commands.addCommand(CommandIDs.toggle, {
        execute: () => {
            if (view.isHidden) {
                return commands.execute(CommandIDs.show, undefined);
            }
            else {
                return commands.execute(CommandIDs.hide, undefined);
            }
        }
    });
    // TODO: Also add to command palette
}
/**
 * Export the plugin as the default.
 */
exports.default = plugin;
/**
 * A namespace for module-private functions.
 */
var Private;
(function (Private) {
    /**
     * Show a warning dialog about extension security.
     *
     * @returns whether the user accepted the dialog.
     */
    function showWarning() {
        return __awaiter(this, void 0, void 0, function* () {
            return apputils_1.showDialog({
                title: 'Enable Extension Manager?',
                body: "Thanks for trying out JupyterLab's extension manager. " +
                    'The JupyterLab development team is excited to have a robust ' +
                    'third-party extension community. ' +
                    'However, we cannot vouch for every extension, ' +
                    'and some may introduce security risks. ' +
                    'Do you want to continue?',
                buttons: [
                    apputils_1.Dialog.cancelButton({ label: 'DISABLE' }),
                    apputils_1.Dialog.warnButton({ label: 'ENABLE' })
                ]
            }).then(result => {
                if (result.button.accept) {
                    return true;
                }
                else {
                    return false;
                }
            });
        });
    }
    Private.showWarning = showWarning;
})(Private || (Private = {}));


/***/ }),

/***/ "ZQT/":
/*!*************************************************************************!*\
  !*** ./node_modules/react-color/lib/components/compact/CompactColor.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CompactColor = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _color = __webpack_require__(/*! ../../helpers/color */ "p8yl");

var _color2 = _interopRequireDefault(_color);

var _common = __webpack_require__(/*! ../common */ "TM95");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var CompactColor = exports.CompactColor = function CompactColor(_ref) {
  var color = _ref.color,
      _ref$onClick = _ref.onClick,
      onClick = _ref$onClick === undefined ? function () {} : _ref$onClick,
      onSwatchHover = _ref.onSwatchHover,
      active = _ref.active;

  var styles = (0, _reactcss2.default)({
    'default': {
      color: {
        background: color,
        width: '15px',
        height: '15px',
        float: 'left',
        marginRight: '5px',
        marginBottom: '5px',
        position: 'relative',
        cursor: 'pointer'
      },
      dot: {
        absolute: '5px 5px 5px 5px',
        background: _color2.default.getContrastingColor(color),
        borderRadius: '50%',
        opacity: '0'
      }
    },
    'active': {
      dot: {
        opacity: '1'
      }
    },
    'color-#FFFFFF': {
      color: {
        boxShadow: 'inset 0 0 0 1px #ddd'
      },
      dot: {
        background: '#000'
      }
    },
    'transparent': {
      dot: {
        background: '#000'
      }
    }
  }, { active: active, 'color-#FFFFFF': color === '#FFFFFF', 'transparent': color === 'transparent' });

  return _react2.default.createElement(
    _common.Swatch,
    {
      style: styles.color,
      color: color,
      onClick: onClick,
      onHover: onSwatchHover,
      focusStyle: { boxShadow: '0 0 4px ' + color }
    },
    _react2.default.createElement('div', { style: styles.dot })
  );
};

exports.default = CompactColor;

/***/ }),

/***/ "ZWV2":
/*!*******************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/serverconnection.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
let FETCH;
let HEADERS;
let REQUEST;
let WEBSOCKET;
if (typeof window === 'undefined') {
    // Mangle the require statements so it does not get picked up in the
    // browser assets.
    /* tslint:disable */
    let fetchMod = eval('require')('node-fetch');
    FETCH = global.fetch || fetchMod;
    REQUEST = global.Request || fetchMod.Request;
    HEADERS = global.Headers || fetchMod.Headers;
    WEBSOCKET = global.WebSocket || eval('require')('ws');
    /* tslint:enable */
}
else {
    FETCH = fetch;
    REQUEST = Request;
    HEADERS = Headers;
    WEBSOCKET = WebSocket;
}
/**
 * The namespace for ServerConnection functions.
 *
 * #### Notes
 * This is only intended to manage communication with the Jupyter server.
 *
 * The default values can be used in a JupyterLab or Jupyter Notebook context.
 *
 * We use `token` authentication if available, falling back on an XSRF
 * cookie if one has been provided on the `document`.
 *
 * A content type of `'application/json'` is added when using authentication
 * and there is no body data to allow the server to prevent malicious forms.
 */
var ServerConnection;
(function (ServerConnection) {
    /**
     * Create a settings object given a subset of options.
     *
     * @param options - An optional partial set of options.
     *
     * @returns The full settings object.
     */
    function makeSettings(options) {
        return Private.makeSettings(options);
    }
    ServerConnection.makeSettings = makeSettings;
    /**
     * Make an request to the notebook server.
     *
     * @param url - The url for the request.
     *
     * @param init - The initialization options for the request.
     *
     * @param settings - The server settings to apply to the request.
     *
     * @returns a Promise that resolves with the response.
     *
     * @throws If the url of the request is not a notebook server url.
     *
     * #### Notes
     * The `url` must start with `settings.baseUrl`.  The `init` settings are
     * merged with `settings.init`, with `init` taking precedence.
     * The headers in the two objects are not merged.
     * If there is no body data, we set the content type to `application/json`
     * because it is required by the Notebook server.
     */
    function makeRequest(url, init, settings) {
        return Private.handleRequest(url, init, settings);
    }
    ServerConnection.makeRequest = makeRequest;
    /**
     * A wrapped error for a fetch response.
     */
    class ResponseError extends Error {
        /**
         * Create a new response error.
         */
        constructor(response, message) {
            message =
                message ||
                    `Invalid response: ${response.status} ${response.statusText}`;
            super(message);
            this.response = response;
        }
    }
    ServerConnection.ResponseError = ResponseError;
    /**
     * A wrapped error for a network error.
     */
    class NetworkError extends TypeError {
        /**
         * Create a new network error.
         */
        constructor(original) {
            super(original.message);
            this.stack = original.stack;
        }
    }
    ServerConnection.NetworkError = NetworkError;
    /**
     * The default settings.
     */
    ServerConnection.defaultSettings = {
        baseUrl: coreutils_1.PageConfig.getBaseUrl(),
        pageUrl: coreutils_1.PageConfig.getOption('pageUrl'),
        wsUrl: coreutils_1.PageConfig.getWsUrl(),
        token: coreutils_1.PageConfig.getToken(),
        init: { cache: 'no-store', credentials: 'same-origin' },
        fetch: FETCH,
        Headers: HEADERS,
        Request: REQUEST,
        WebSocket: WEBSOCKET
    };
})(ServerConnection = exports.ServerConnection || (exports.ServerConnection = {}));
/**
 * The namespace for module private data.
 */
var Private;
(function (Private) {
    /**
     * Handle the server connection settings, returning a new value.
     */
    function makeSettings(options = {}) {
        const defaultSettings = ServerConnection.defaultSettings;
        const baseUrl = coreutils_1.URLExt.normalize(options.baseUrl) || defaultSettings.baseUrl;
        let wsUrl = options.wsUrl;
        // Prefer the default wsUrl if we are using the default baseUrl.
        if (!wsUrl && baseUrl === defaultSettings.baseUrl) {
            wsUrl = defaultSettings.wsUrl;
        }
        // Otherwise convert the baseUrl to a wsUrl if possible.
        if (!wsUrl && baseUrl.indexOf('http') === 0) {
            wsUrl = 'ws' + baseUrl.slice(4);
        }
        // Otherwise fall back on the default wsUrl.
        wsUrl = wsUrl || defaultSettings.wsUrl;
        return Object.assign({}, defaultSettings, options, { wsUrl });
    }
    Private.makeSettings = makeSettings;
    /**
     * Handle a request.
     *
     * @param url - The url for the request.
     *
     * @param init - The overrides for the request init.
     *
     * @param settings - The settings object for the request.
     *
     * #### Notes
     * The `url` must start with `settings.baseUrl`.  The `init` settings
     * take precedence over `settings.init`.
     */
    function handleRequest(url, init, settings) {
        // Handle notebook server requests.
        if (url.indexOf(settings.baseUrl) !== 0) {
            throw new Error('Can only be used for notebook server requests');
        }
        // Use explicit cache buster when `no-store` is set since
        // not all browsers use it properly.
        let cache = init.cache || settings.init.cache;
        if (cache === 'no-store') {
            // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Bypassing_the_cache
            url += (/\?/.test(url) ? '&' : '?') + new Date().getTime();
        }
        let request = new settings.Request(url, Object.assign({}, settings.init, init));
        // Handle authentication.
        let authenticated = false;
        if (settings.token) {
            authenticated = true;
            request.headers.append('Authorization', `token ${settings.token}`);
        }
        else if (typeof document !== 'undefined' && document.cookie) {
            let xsrfToken = getCookie('_xsrf');
            if (xsrfToken !== void 0) {
                authenticated = true;
                request.headers.append('X-XSRFToken', xsrfToken);
            }
        }
        // Set the content type if there is no given data and we are
        // using an authenticated connection.
        if (!request.bodyUsed && authenticated) {
            request.headers.set('Content-Type', 'application/json');
        }
        // Use `call` to avoid a `TypeError` in the browser.
        return settings.fetch.call(null, request).catch((e) => {
            // Convert the TypeError into a more specific error.
            throw new ServerConnection.NetworkError(e);
        });
    }
    Private.handleRequest = handleRequest;
    /**
     * Get a cookie from the document.
     */
    function getCookie(name) {
        // from tornado docs: http://www.tornadoweb.org/en/stable/guide/security.html
        let r = document.cookie.match('\\b' + name + '=([^;]*)\\b');
        return r ? r[1] : void 0;
    }
})(Private || (Private = {}));

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "ZWtO":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_baseGet.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var castPath = __webpack_require__(/*! ./_castPath */ "4uTw"),
    toKey = __webpack_require__(/*! ./_toKey */ "9Nap");

/**
 * 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;
}

module.exports = baseGet;


/***/ }),

/***/ "Zduo":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/eo.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var eo = moment.defineLocale('eo', {
    months : 'januaro_februaro_marto_aprilo_majo_junio_julio_aŭgusto_septembro_oktobro_novembro_decembro'.split('_'),
    monthsShort : 'jan_feb_mar_apr_maj_jun_jul_aŭg_sep_okt_nov_dec'.split('_'),
    weekdays : 'dimanĉo_lundo_mardo_merkredo_ĵaŭdo_vendredo_sabato'.split('_'),
    weekdaysShort : 'dim_lun_mard_merk_ĵaŭ_ven_sab'.split('_'),
    weekdaysMin : 'di_lu_ma_me_ĵa_ve_sa'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'YYYY-MM-DD',
        LL : 'D[-a de] MMMM, YYYY',
        LLL : 'D[-a de] MMMM, YYYY HH:mm',
        LLLL : 'dddd, [la] D[-a de] MMMM, YYYY HH:mm'
    },
    meridiemParse: /[ap]\.t\.m/i,
    isPM: function (input) {
        return input.charAt(0).toLowerCase() === 'p';
    },
    meridiem : function (hours, minutes, isLower) {
        if (hours > 11) {
            return isLower ? 'p.t.m.' : 'P.T.M.';
        } else {
            return isLower ? 'a.t.m.' : 'A.T.M.';
        }
    },
    calendar : {
        sameDay : '[Hodiaŭ je] LT',
        nextDay : '[Morgaŭ je] LT',
        nextWeek : 'dddd [je] LT',
        lastDay : '[Hieraŭ je] LT',
        lastWeek : '[pasinta] dddd [je] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'post %s',
        past : 'antaŭ %s',
        s : 'sekundoj',
        ss : '%d sekundoj',
        m : 'minuto',
        mm : '%d minutoj',
        h : 'horo',
        hh : '%d horoj',
        d : 'tago',//ne 'diurno', ĉar estas uzita por proksimumo
        dd : '%d tagoj',
        M : 'monato',
        MM : '%d monatoj',
        y : 'jaro',
        yy : '%d jaroj'
    },
    dayOfMonthOrdinalParse: /\d{1,2}a/,
    ordinal : '%da',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return eo;

})));


/***/ }),

/***/ "Ze4w":
/*!******************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/LogoVisaIcon.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var LogoVisaIcon = function LogoVisaIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M5.375 11.875C5.25 11.187 4.812 11 4.25 11H0v.188c2.875.75 5.25 2.313 6.313 5.25zm1.188 6l-.25-1.438c-.563-1.438-1.875-2.813-3.375-3.375L5.001 21h2.75l4.125-10H9.063zM13.875 21L15.5 11h-2.625L11.25 21zm7.063-10.187c-2.563 0-4.375 1.375-4.375 3.313 0 1.438 1.313 2.25 2.25 2.75 1.063.5 1.375.813 1.375 1.25 0 .625-.813.938-1.563.938-1.063 0-1.625-.125-2.438-.5l-.313-.188-.375 2.25c.563.313 1.688.563 2.875.563 2.688 0 4.5-1.375 4.5-3.438 0-1.125-.688-2-2.188-2.75-.875-.438-1.438-.75-1.438-1.188s.5-.875 1.5-.875c.813 0 1.438.125 1.938.375l.25.125.313-2.188a6.565 6.565 0 0 0-2.313-.438zm7 .187c-.625 0-1.125.188-1.375.875L22.688 21h2.75c.438-1.188.563-1.5.563-1.5h3.313l.25 1.5h2.438l-2.063-10zm-1.25 6.5s.25-.625 1.063-2.813c0 0 .188-.625.313-.938l.188.813c.5 2.438.625 2.938.625 2.938h-2.188z' })
    );
};

exports.default = LogoVisaIcon;

/***/ }),

/***/ "Zf/v":
/*!*****************************************************!*\
  !*** ./node_modules/draft-js/lib/insertIntoList.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule insertIntoList
 * @format
 * 
 */



/**
 * Maintain persistence for target list when appending and prepending.
 */
function insertIntoList(targetList, toInsert, offset) {
  if (offset === targetList.count()) {
    toInsert.forEach(function (c) {
      targetList = targetList.push(c);
    });
  } else if (offset === 0) {
    toInsert.reverse().forEach(function (c) {
      targetList = targetList.unshift(c);
    });
  } else {
    var head = targetList.slice(0, offset);
    var tail = targetList.slice(offset);
    targetList = head.concat(toInsert, tail).toList();
  }
  return targetList;
}

module.exports = insertIntoList;

/***/ }),

/***/ "Zgb7":
/*!**************************************************************!*\
  !*** ./node_modules/draft-js/lib/getDraftEditorSelection.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule getDraftEditorSelection
 * @format
 * 
 */



var getDraftEditorSelectionWithNodes = __webpack_require__(/*! ./getDraftEditorSelectionWithNodes */ "ISee");

/**
 * Convert the current selection range to an anchor/focus pair of offset keys
 * and values that can be interpreted by components.
 */
function getDraftEditorSelection(editorState, root) {
  var selection = global.getSelection();

  // No active selection.
  if (selection.rangeCount === 0) {
    return {
      selectionState: editorState.getSelection().set('hasFocus', false),
      needsRecovery: false
    };
  }

  return getDraftEditorSelectionWithNodes(editorState, root, selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset);
}

module.exports = getDraftEditorSelection;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "Zgzb":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/terminal/style/index.css ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "Mta4");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "Zhzs":
/*!*************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/dates.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




var d3 = __webpack_require__(/*! d3 */ "bljh");
var isNumeric = __webpack_require__(/*! fast-isnumeric */ "GbLo");

var Loggers = __webpack_require__(/*! ./loggers */ "rhNM");
var mod = __webpack_require__(/*! ./mod */ "09xr").mod;

var constants = __webpack_require__(/*! ../constants/numerical */ "6AZA");
var BADNUM = constants.BADNUM;
var ONEDAY = constants.ONEDAY;
var ONEHOUR = constants.ONEHOUR;
var ONEMIN = constants.ONEMIN;
var ONESEC = constants.ONESEC;
var EPOCHJD = constants.EPOCHJD;

var Registry = __webpack_require__(/*! ../registry */ "Nx4I");

var utcFormat = d3.time.format.utc;

var DATETIME_REGEXP = /^\s*(-?\d\d\d\d|\d\d)(-(\d?\d)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d:?\d\d)?)?)?)?)?\s*$/m;
// special regex for chinese calendars to support yyyy-mmi-dd etc for intercalary months
var DATETIME_REGEXP_CN = /^\s*(-?\d\d\d\d|\d\d)(-(\d?\di?)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d:?\d\d)?)?)?)?)?\s*$/m;

// for 2-digit years, the first year we map them onto
var YFIRST = new Date().getFullYear() - 70;

function isWorldCalendar(calendar) {
    return (
        calendar &&
        Registry.componentsRegistry.calendars &&
        typeof calendar === 'string' && calendar !== 'gregorian'
    );
}

/*
 * dateTick0: get the canonical tick for this calendar
 *
 * bool sunday is for week ticks, shift it to a Sunday.
 */
exports.dateTick0 = function(calendar, sunday) {
    if(isWorldCalendar(calendar)) {
        return sunday ?
            Registry.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] :
            Registry.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar];
    }
    else {
        return sunday ? '2000-01-02' : '2000-01-01';
    }
};

/*
 * dfltRange: for each calendar, give a valid default range
 */
exports.dfltRange = function(calendar) {
    if(isWorldCalendar(calendar)) {
        return Registry.getComponentMethod('calendars', 'DFLTRANGE')[calendar];
    }
    else {
        return ['2000-01-01', '2001-01-01'];
    }
};

// is an object a javascript date?
exports.isJSDate = function(v) {
    return typeof v === 'object' && v !== null && typeof v.getTime === 'function';
};

// The absolute limits of our date-time system
// This is a little weird: we use MIN_MS and MAX_MS in dateTime2ms
// but we use dateTime2ms to calculate them (after defining it!)
var MIN_MS, MAX_MS;

/**
 * dateTime2ms - turn a date object or string s into milliseconds
 * (relative to 1970-01-01, per javascript standard)
 * optional calendar (string) to use a non-gregorian calendar
 *
 * Returns BADNUM if it doesn't find a date
 *
 * strings should have the form:
 *
 *    -?YYYY-mm-dd<sep>HH:MM:SS.sss<tzInfo>?
 *
 * <sep>: space (our normal standard) or T or t (ISO-8601)
 * <tzInfo>: Z, z, or [+\-]HH:?MM and we THROW IT AWAY
 * this format comes from https://tools.ietf.org/html/rfc3339#section-5.6
 * but we allow it even with a space as the separator
 *
 * May truncate after any full field, and sss can be any length
 * even >3 digits, though javascript dates truncate to milliseconds,
 * we keep as much as javascript numeric precision can hold, but we only
 * report back up to 100 microsecond precision, because most dates support
 * this precision (close to 1970 support more, very far away support less)
 *
 * Expanded to support negative years to -9999 but you must always
 * give 4 digits, except for 2-digit positive years which we assume are
 * near the present time.
 * Note that we follow ISO 8601:2004: there *is* a year 0, which
 * is 1BC/BCE, and -1===2BC etc.
 *
 * World calendars: not all of these *have* agreed extensions to this full range,
 * if you have another calendar system but want a date range outside its validity,
 * you can use a gregorian date string prefixed with 'G' or 'g'.
 *
 * Where to cut off 2-digit years between 1900s and 2000s?
 * from http://support.microsoft.com/kb/244664:
 *   1930-2029 (the most retro of all...)
 * but in my mac chrome from eg. d=new Date(Date.parse('8/19/50')):
 *   1950-2049
 * by Java, from http://stackoverflow.com/questions/2024273/:
 *   now-80 - now+19
 * or FileMaker Pro, from
 *      http://www.filemaker.com/12help/html/add_view_data.4.21.html:
 *   now-70 - now+29
 * but python strptime etc, via
 *      http://docs.python.org/py3k/library/time.html:
 *   1969-2068 (super forward-looking, but static, not sliding!)
 *
 * lets go with now-70 to now+29, and if anyone runs into this problem
 * they can learn the hard way not to use 2-digit years, as no choice we
 * make now will cover all possibilities. mostly this will all be taken
 * care of in initial parsing, should only be an issue for hand-entered data
 * currently (2016) this range is:
 *   1946-2045
 */
exports.dateTime2ms = function(s, calendar) {
    // first check if s is a date object
    if(exports.isJSDate(s)) {
        // Convert to the UTC milliseconds that give the same
        // hours as this date has in the local timezone
        var tzOffset = s.getTimezoneOffset() * ONEMIN;
        var offsetTweak = (s.getUTCMinutes() - s.getMinutes()) * ONEMIN +
            (s.getUTCSeconds() - s.getSeconds()) * ONESEC +
            (s.getUTCMilliseconds() - s.getMilliseconds());

        if(offsetTweak) {
            var comb = 3 * ONEMIN;
            tzOffset = tzOffset - comb / 2 + mod(offsetTweak - tzOffset + comb / 2, comb);
        }
        s = Number(s) - tzOffset;
        if(s >= MIN_MS && s <= MAX_MS) return s;
        return BADNUM;
    }
    // otherwise only accept strings and numbers
    if(typeof s !== 'string' && typeof s !== 'number') return BADNUM;

    s = String(s);

    var isWorld = isWorldCalendar(calendar);

    // to handle out-of-range dates in international calendars, accept
    // 'G' as a prefix to force the built-in gregorian calendar.
    var s0 = s.charAt(0);
    if(isWorld && (s0 === 'G' || s0 === 'g')) {
        s = s.substr(1);
        calendar = '';
    }

    var isChinese = isWorld && calendar.substr(0, 7) === 'chinese';

    var match = s.match(isChinese ? DATETIME_REGEXP_CN : DATETIME_REGEXP);
    if(!match) return BADNUM;
    var y = match[1];
    var m = match[3] || '1';
    var d = Number(match[5] || 1);
    var H = Number(match[7] || 0);
    var M = Number(match[9] || 0);
    var S = Number(match[11] || 0);

    if(isWorld) {
        // disallow 2-digit years for world calendars
        if(y.length === 2) return BADNUM;
        y = Number(y);

        var cDate;
        try {
            var calInstance = Registry.getComponentMethod('calendars', 'getCal')(calendar);
            if(isChinese) {
                var isIntercalary = m.charAt(m.length - 1) === 'i';
                m = parseInt(m, 10);
                cDate = calInstance.newDate(y, calInstance.toMonthIndex(y, m, isIntercalary), d);
            }
            else {
                cDate = calInstance.newDate(y, Number(m), d);
            }
        }
        catch(e) { return BADNUM; } // Invalid ... date

        if(!cDate) return BADNUM;

        return ((cDate.toJD() - EPOCHJD) * ONEDAY) +
            (H * ONEHOUR) + (M * ONEMIN) + (S * ONESEC);
    }

    if(y.length === 2) {
        y = (Number(y) + 2000 - YFIRST) % 100 + YFIRST;
    }
    else y = Number(y);

    // new Date uses months from 0; subtract 1 here just so we
    // don't have to do it again during the validity test below
    m -= 1;

    // javascript takes new Date(0..99,m,d) to mean 1900-1999, so
    // to support years 0-99 we need to use setFullYear explicitly
    // Note that 2000 is a leap year.
    var date = new Date(Date.UTC(2000, m, d, H, M));
    date.setUTCFullYear(y);

    if(date.getUTCMonth() !== m) return BADNUM;
    if(date.getUTCDate() !== d) return BADNUM;

    return date.getTime() + S * ONESEC;
};

MIN_MS = exports.MIN_MS = exports.dateTime2ms('-9999');
MAX_MS = exports.MAX_MS = exports.dateTime2ms('9999-12-31 23:59:59.9999');

// is string s a date? (see above)
exports.isDateTime = function(s, calendar) {
    return (exports.dateTime2ms(s, calendar) !== BADNUM);
};

// pad a number with zeroes, to given # of digits before the decimal point
function lpad(val, digits) {
    return String(val + Math.pow(10, digits)).substr(1);
}

/**
 * Turn ms into string of the form YYYY-mm-dd HH:MM:SS.ssss
 * Crop any trailing zeros in time, except never stop right after hours
 * (we could choose to crop '-01' from date too but for now we always
 * show the whole date)
 * Optional range r is the data range that applies, also in ms.
 * If rng is big, the later parts of time will be omitted
 */
var NINETYDAYS = 90 * ONEDAY;
var THREEHOURS = 3 * ONEHOUR;
var FIVEMIN = 5 * ONEMIN;
exports.ms2DateTime = function(ms, r, calendar) {
    if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return BADNUM;

    if(!r) r = 0;

    var msecTenths = Math.floor(mod(ms + 0.05, 1) * 10);
    var msRounded = Math.round(ms - msecTenths / 10);
    var dateStr, h, m, s, msec10, d;

    if(isWorldCalendar(calendar)) {
        var dateJD = Math.floor(msRounded / ONEDAY) + EPOCHJD;
        var timeMs = Math.floor(mod(ms, ONEDAY));
        try {
            dateStr = Registry.getComponentMethod('calendars', 'getCal')(calendar)
                .fromJD(dateJD).formatDate('yyyy-mm-dd');
        } catch(e) {
            // invalid date in this calendar - fall back to Gyyyy-mm-dd
            dateStr = utcFormat('G%Y-%m-%d')(new Date(msRounded));
        }

        // yyyy does NOT guarantee 4-digit years. YYYY mostly does, but does
        // other things for a few calendars, so we can't trust it. Just pad
        // it manually (after the '-' if there is one)
        if(dateStr.charAt(0) === '-') {
            while(dateStr.length < 11) dateStr = '-0' + dateStr.substr(1);
        } else {
            while(dateStr.length < 10) dateStr = '0' + dateStr;
        }

        // TODO: if this is faster, we could use this block for extracting
        // the time components of regular gregorian too
        h = (r < NINETYDAYS) ? Math.floor(timeMs / ONEHOUR) : 0;
        m = (r < NINETYDAYS) ? Math.floor((timeMs % ONEHOUR) / ONEMIN) : 0;
        s = (r < THREEHOURS) ? Math.floor((timeMs % ONEMIN) / ONESEC) : 0;
        msec10 = (r < FIVEMIN) ? (timeMs % ONESEC) * 10 + msecTenths : 0;
    }
    else {
        d = new Date(msRounded);

        dateStr = utcFormat('%Y-%m-%d')(d);

        // <90 days: add hours and minutes - never *only* add hours
        h = (r < NINETYDAYS) ? d.getUTCHours() : 0;
        m = (r < NINETYDAYS) ? d.getUTCMinutes() : 0;
        // <3 hours: add seconds
        s = (r < THREEHOURS) ? d.getUTCSeconds() : 0;
        // <5 minutes: add ms (plus one extra digit, this is msec*10)
        msec10 = (r < FIVEMIN) ? d.getUTCMilliseconds() * 10 + msecTenths : 0;
    }

    return includeTime(dateStr, h, m, s, msec10);
};

// For converting old-style milliseconds to date strings,
// we use the local timezone rather than UTC like we use
// everywhere else, both for backward compatibility and
// because that's how people mostly use javasript date objects.
// Clip one extra day off our date range though so we can't get
// thrown beyond the range by the timezone shift.
exports.ms2DateTimeLocal = function(ms) {
    if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return BADNUM;

    var msecTenths = Math.floor(mod(ms + 0.05, 1) * 10);
    var d = new Date(Math.round(ms - msecTenths / 10));
    var dateStr = d3.time.format('%Y-%m-%d')(d);
    var h = d.getHours();
    var m = d.getMinutes();
    var s = d.getSeconds();
    var msec10 = d.getUTCMilliseconds() * 10 + msecTenths;

    return includeTime(dateStr, h, m, s, msec10);
};

function includeTime(dateStr, h, m, s, msec10) {
    // include each part that has nonzero data in or after it
    if(h || m || s || msec10) {
        dateStr += ' ' + lpad(h, 2) + ':' + lpad(m, 2);
        if(s || msec10) {
            dateStr += ':' + lpad(s, 2);
            if(msec10) {
                var digits = 4;
                while(msec10 % 10 === 0) {
                    digits -= 1;
                    msec10 /= 10;
                }
                dateStr += '.' + lpad(msec10, digits);
            }
        }
    }
    return dateStr;
}

// normalize date format to date string, in case it starts as
// a Date object or milliseconds
// optional dflt is the return value if cleaning fails
exports.cleanDate = function(v, dflt, calendar) {
    // let us use cleanDate to provide a missing default without an error
    if(v === BADNUM) return dflt;
    if(exports.isJSDate(v) || (typeof v === 'number' && isFinite(v))) {
        // do not allow milliseconds (old) or jsdate objects (inherently
        // described as gregorian dates) with world calendars
        if(isWorldCalendar(calendar)) {
            Loggers.error('JS Dates and milliseconds are incompatible with world calendars', v);
            return dflt;
        }

        // NOTE: if someone puts in a year as a number rather than a string,
        // this will mistakenly convert it thinking it's milliseconds from 1970
        // that is: '2012' -> Jan. 1, 2012, but 2012 -> 2012 epoch milliseconds
        v = exports.ms2DateTimeLocal(+v);
        if(!v && dflt !== undefined) return dflt;
    }
    else if(!exports.isDateTime(v, calendar)) {
        Loggers.error('unrecognized date', v);
        return dflt;
    }
    return v;
};

/*
 *  Date formatting for ticks and hovertext
 */

/*
 * modDateFormat: Support world calendars, and add one item to
 * d3's vocabulary:
 * %{n}f where n is the max number of digits of fractional seconds
 */
var fracMatch = /%\d?f/g;
function modDateFormat(fmt, x, formatter, calendar) {

    fmt = fmt.replace(fracMatch, function(match) {
        var digits = Math.min(+(match.charAt(1)) || 6, 6);
        var fracSecs = ((x / 1000 % 1) + 2)
            .toFixed(digits)
            .substr(2).replace(/0+$/, '') || '0';
        return fracSecs;
    });

    var d = new Date(Math.floor(x + 0.05));

    if(isWorldCalendar(calendar)) {
        try {
            fmt = Registry.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar);
        }
        catch(e) {
            return 'Invalid';
        }
    }
    return formatter(fmt)(d);
}

/*
 * formatTime: create a time string from:
 *   x: milliseconds
 *   tr: tickround ('M', 'S', or # digits)
 * only supports UTC times (where every day is 24 hours and 0 is at midnight)
 */
var MAXSECONDS = [59, 59.9, 59.99, 59.999, 59.9999];
function formatTime(x, tr) {
    var timePart = mod(x + 0.05, ONEDAY);

    var timeStr = lpad(Math.floor(timePart / ONEHOUR), 2) + ':' +
        lpad(mod(Math.floor(timePart / ONEMIN), 60), 2);

    if(tr !== 'M') {
        if(!isNumeric(tr)) tr = 0; // should only be 'S'

        /*
         * this is a weird one - and shouldn't come up unless people
         * monkey with tick0 in weird ways, but we need to do something!
         * IN PARTICULAR we had better not display garbage (see below)
         * for numbers we always round to the nearest increment of the
         * precision we're showing, and this seems like the right way to
         * handle seconds and milliseconds, as they have a decimal point
         * and people will interpret that to mean rounding like numbers.
         * but for larger increments we floor the value: it's always
         * 2013 until the ball drops on the new year. We could argue about
         * which field it is where we start rounding (should 12:08:59
         * round to 12:09 if we're stopping at minutes?) but for now I'll
         * say we round seconds but floor everything else. BUT that means
         * we need to never round up to 60 seconds, ie 23:59:60
         */
        var sec = Math.min(mod(x / ONESEC, 60), MAXSECONDS[tr]);

        var secStr = (100 + sec).toFixed(tr).substr(1);
        if(tr > 0) {
            secStr = secStr.replace(/0+$/, '').replace(/[\.]$/, '');
        }

        timeStr += ':' + secStr;
    }
    return timeStr;
}

/*
 * formatDate: turn a date into tick or hover label text.
 *
 *   x: milliseconds, the value to convert
 *   fmt: optional, an explicit format string (d3 format, even for world calendars)
 *   tr: tickround ('y', 'm', 'd', 'M', 'S', or # digits)
 *      used if no explicit fmt is provided
 *   formatter: locale-aware d3 date formatter for standard gregorian calendars
 *      should be the result of exports.getD3DateFormat(gd)
 *   calendar: optional string, the world calendar system to use
 *
 * returns the date/time as a string, potentially with the leading portion
 * on a separate line (after '\n')
 * Note that this means if you provide an explicit format which includes '\n'
 * the axis may choose to strip things after it when they don't change from
 * one tick to the next (as it does with automatic formatting)
 */
exports.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) {
    calendar = isWorldCalendar(calendar) && calendar;

    if(!fmt) {
        if(tr === 'y') fmt = extraFormat.year;
        else if(tr === 'm') fmt = extraFormat.month;
        else if(tr === 'd') {
            fmt = extraFormat.dayMonth + '\n' + extraFormat.year;
        }
        else {
            return formatTime(x, tr) + '\n' + modDateFormat(extraFormat.dayMonthYear, x, formatter, calendar);
        }
    }

    return modDateFormat(fmt, x, formatter, calendar);
};

/*
 * incrementMonth: make a new milliseconds value from the given one,
 * having changed the month
 *
 * special case for world calendars: multiples of 12 are treated as years,
 * even for calendar systems that don't have (always or ever) 12 months/year
 * TODO: perhaps we need a different code for year increments to support this?
 *
 * ms (number): the initial millisecond value
 * dMonth (int): the (signed) number of months to shift
 * calendar (string): the calendar system to use
 *
 * changing month does not (and CANNOT) always preserve day, since
 * months have different lengths. The worst example of this is:
 *   d = new Date(1970,0,31); d.setMonth(1) -> Feb 31 turns into Mar 3
 *
 * But we want to be able to iterate over the last day of each month,
 * regardless of what its number is.
 * So shift 3 days forward, THEN set the new month, then unshift:
 *   1/31 -> 2/28 (or 29) -> 3/31 -> 4/30 -> ...
 *
 * Note that odd behavior still exists if you start from the 26th-28th:
 *   1/28 -> 2/28 -> 3/31
 * but at least you can't shift any dates into the wrong month,
 * and ticks on these days incrementing by month would be very unusual
 */
var THREEDAYS = 3 * ONEDAY;
exports.incrementMonth = function(ms, dMonth, calendar) {
    calendar = isWorldCalendar(calendar) && calendar;

    // pull time out and operate on pure dates, then add time back at the end
    // this gives maximum precision - not that we *normally* care if we're
    // incrementing by month, but better to be safe!
    var timeMs = mod(ms, ONEDAY);
    ms = Math.round(ms - timeMs);

    if(calendar) {
        try {
            var dateJD = Math.round(ms / ONEDAY) + EPOCHJD;
            var calInstance = Registry.getComponentMethod('calendars', 'getCal')(calendar);
            var cDate = calInstance.fromJD(dateJD);

            if(dMonth % 12) calInstance.add(cDate, dMonth, 'm');
            else calInstance.add(cDate, dMonth / 12, 'y');

            return (cDate.toJD() - EPOCHJD) * ONEDAY + timeMs;
        } catch(e) {
            Loggers.error('invalid ms ' + ms + ' in calendar ' + calendar);
            // then keep going in gregorian even though the result will be 'Invalid'
        }
    }

    var y = new Date(ms + THREEDAYS);
    return y.setUTCMonth(y.getUTCMonth() + dMonth) + timeMs - THREEDAYS;
};

/*
 * findExactDates: what fraction of data is exact days, months, or years?
 *
 * data: array of millisecond values
 * calendar (string) the calendar to test against
 */
exports.findExactDates = function(data, calendar) {
    var exactYears = 0;
    var exactMonths = 0;
    var exactDays = 0;
    var blankCount = 0;
    var d;
    var di;

    var calInstance = (
        isWorldCalendar(calendar) &&
        Registry.getComponentMethod('calendars', 'getCal')(calendar)
    );

    for(var i = 0; i < data.length; i++) {
        di = data[i];

        // not date data at all
        if(!isNumeric(di)) {
            blankCount ++;
            continue;
        }

        // not an exact date
        if(di % ONEDAY) continue;

        if(calInstance) {
            try {
                d = calInstance.fromJD(di / ONEDAY + EPOCHJD);
                if(d.day() === 1) {
                    if(d.month() === 1) exactYears++;
                    else exactMonths++;
                }
                else exactDays++;
            }
            catch(e) {
                // invalid date in this calendar - ignore it here.
            }
        }
        else {
            d = new Date(di);
            if(d.getUTCDate() === 1) {
                if(d.getUTCMonth() === 0) exactYears++;
                else exactMonths++;
            }
            else exactDays++;
        }
    }
    exactMonths += exactYears;
    exactDays += exactMonths;

    var dataCount = data.length - blankCount;

    return {
        exactYears: exactYears / dataCount,
        exactMonths: exactMonths / dataCount,
        exactDays: exactDays / dataCount
    };
};


/***/ }),

/***/ "Zi9O":
/*!****************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/dereference.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = dereference;

var _walkObject = __webpack_require__(/*! ./walkObject */ "/0O1");

var _walkObject2 = _interopRequireDefault(_walkObject);

var _index = __webpack_require__(/*! ./index */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var SRC_ATTR_PATTERN = /src$/;

function dereference(container, dataSources) {
  var config = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { deleteKeys: false };

  var replacer = function replacer(key, parent, srcPath) {
    if (!SRC_ATTR_PATTERN.test(key)) {
      return;
    }

    var dataKey = key.replace(SRC_ATTR_PATTERN, '');

    var srcRef = config.toSrc ? config.toSrc(parent[key]) : parent[key];

    // making this into an array to more easily lookup 1d and 2d srcs in dataSourceOptions
    if (!Array.isArray(srcRef)) {
      srcRef = [srcRef];
    }

    var dereferencedData = srcRef.map(function (ref) {
      if (config.deleteKeys && !(ref in dataSources)) {
        delete parent[dataKey];
      }
      return dataSources[ref];
    });

    // remove extra data wrapping
    if (srcRef.length === 1) {
      dereferencedData = dereferencedData[0];
    }

    if (!Array.isArray(dereferencedData)) {
      return;
    }

    if (Array.isArray(container)) {
      // Case where we were originally given data to dereference
      var traceType = parent.type;
      parent[dataKey] = (0, _index.maybeTransposeData)(dereferencedData, srcPath, traceType);
    } else {
      // This means we're dereferencing layout
      parent[dataKey] = dereferencedData;
    }
  };

  if (Array.isArray(container)) {
    (0, _walkObject2.default)(container, replacer, {
      walkArraysMatchingKeys: ['data', 'transforms'],
      pathType: 'nestedProperty'
    });
  } else {
    (0, _walkObject2.default)(container, replacer, { pathType: 'nestedProperty' });
  }
}
//# sourceMappingURL=dereference.js.map

/***/ }),

/***/ "ZlA+":
/*!************************************************************!*\
  !*** ./node_modules/@jupyterlab/csvviewer/style/index.css ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "9ECJ");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "ZnKQ":
/*!**************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/coerce.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var isNumeric = __webpack_require__(/*! fast-isnumeric */ "GbLo");
var tinycolor = __webpack_require__(/*! tinycolor2 */ "Zss7");

var baseTraceAttrs = __webpack_require__(/*! ../plots/attributes */ "qHYo");
var scales = __webpack_require__(/*! ../components/colorscale/scales */ "SFLx");
var DESELECTDIM = __webpack_require__(/*! ../constants/interactions */ "cqRZ").DESELECTDIM;

var nestedProperty = __webpack_require__(/*! ./nested_property */ "dNZO");
var counterRegex = __webpack_require__(/*! ./regex */ "BVrX").counter;
var modHalf = __webpack_require__(/*! ./mod */ "09xr").modHalf;
var isArrayOrTypedArray = __webpack_require__(/*! ./array */ "avjU").isArrayOrTypedArray;

exports.valObjectMeta = {
    data_array: {
        // You can use *dflt=[] to force said array to exist though.
        description: [
            'An {array} of data.',
            'The value MUST be an {array}, or we ignore it.',
            'Note that typed arrays (e.g. Float32Array) are supported.'
        ].join(' '),
        requiredOpts: [],
        otherOpts: ['dflt'],
        coerceFunction: function(v, propOut, dflt) {
            // TODO maybe `v: {type: 'float32', vals: [/* ... */]}` also
            if(isArrayOrTypedArray(v)) propOut.set(v);
            else if(dflt !== undefined) propOut.set(dflt);
        }
    },
    enumerated: {
        description: [
            'Enumerated value type. The available values are listed',
            'in `values`.'
        ].join(' '),
        requiredOpts: ['values'],
        otherOpts: ['dflt', 'coerceNumber', 'arrayOk'],
        coerceFunction: function(v, propOut, dflt, opts) {
            if(opts.coerceNumber) v = +v;
            if(opts.values.indexOf(v) === -1) propOut.set(dflt);
            else propOut.set(v);
        },
        validateFunction: function(v, opts) {
            if(opts.coerceNumber) v = +v;

            var values = opts.values;
            for(var i = 0; i < values.length; i++) {
                var k = String(values[i]);

                if((k.charAt(0) === '/' && k.charAt(k.length - 1) === '/')) {
                    var regex = new RegExp(k.substr(1, k.length - 2));
                    if(regex.test(v)) return true;
                } else if(v === values[i]) return true;
            }
            return false;
        }
    },
    'boolean': {
        description: 'A boolean (true/false) value.',
        requiredOpts: [],
        otherOpts: ['dflt'],
        coerceFunction: function(v, propOut, dflt) {
            if(v === true || v === false) propOut.set(v);
            else propOut.set(dflt);
        }
    },
    number: {
        description: [
            'A number or a numeric value',
            '(e.g. a number inside a string).',
            'When applicable, values greater (less) than `max` (`min`)',
            'are coerced to the `dflt`.'
        ].join(' '),
        requiredOpts: [],
        otherOpts: ['dflt', 'min', 'max', 'arrayOk'],
        coerceFunction: function(v, propOut, dflt, opts) {
            if(!isNumeric(v) ||
                    (opts.min !== undefined && v < opts.min) ||
                    (opts.max !== undefined && v > opts.max)) {
                propOut.set(dflt);
            }
            else propOut.set(+v);
        }
    },
    integer: {
        description: [
            'An integer or an integer inside a string.',
            'When applicable, values greater (less) than `max` (`min`)',
            'are coerced to the `dflt`.'
        ].join(' '),
        requiredOpts: [],
        otherOpts: ['dflt', 'min', 'max', 'arrayOk'],
        coerceFunction: function(v, propOut, dflt, opts) {
            if(v % 1 || !isNumeric(v) ||
                    (opts.min !== undefined && v < opts.min) ||
                    (opts.max !== undefined && v > opts.max)) {
                propOut.set(dflt);
            }
            else propOut.set(+v);
        }
    },
    string: {
        description: [
            'A string value.',
            'Numbers are converted to strings except for attributes with',
            '`strict` set to true.'
        ].join(' '),
        requiredOpts: [],
        // TODO 'values shouldn't be in there (edge case: 'dash' in Scatter)
        otherOpts: ['dflt', 'noBlank', 'strict', 'arrayOk', 'values'],
        coerceFunction: function(v, propOut, dflt, opts) {
            if(typeof v !== 'string') {
                var okToCoerce = (typeof v === 'number');

                if(opts.strict === true || !okToCoerce) propOut.set(dflt);
                else propOut.set(String(v));
            }
            else if(opts.noBlank && !v) propOut.set(dflt);
            else propOut.set(v);
        }
    },
    color: {
        description: [
            'A string describing color.',
            'Supported formats:',
            '- hex (e.g. \'#d3d3d3\')',
            '- rgb (e.g. \'rgb(255, 0, 0)\')',
            '- rgba (e.g. \'rgb(255, 0, 0, 0.5)\')',
            '- hsl (e.g. \'hsl(0, 100%, 50%)\')',
            '- hsv (e.g. \'hsv(0, 100%, 100%)\')',
            '- named colors (full list: http://www.w3.org/TR/css3-color/#svg-color)'
        ].join(' '),
        requiredOpts: [],
        otherOpts: ['dflt', 'arrayOk'],
        coerceFunction: function(v, propOut, dflt) {
            if(tinycolor(v).isValid()) propOut.set(v);
            else propOut.set(dflt);
        }
    },
    colorlist: {
        description: [
            'A list of colors.',
            'Must be an {array} containing valid colors.',
        ].join(' '),
        requiredOpts: [],
        otherOpts: ['dflt'],
        coerceFunction: function(v, propOut, dflt) {
            function isColor(color) {
                return tinycolor(color).isValid();
            }
            if(!Array.isArray(v) || !v.length) propOut.set(dflt);
            else if(v.every(isColor)) propOut.set(v);
            else propOut.set(dflt);
        }
    },
    colorscale: {
        description: [
            'A Plotly colorscale either picked by a name:',
            '(any of', Object.keys(scales.scales).join(', '), ')',
            'customized as an {array} of 2-element {arrays} where',
            'the first element is the normalized color level value',
            '(starting at *0* and ending at *1*),',
            'and the second item is a valid color string.'
        ].join(' '),
        requiredOpts: [],
        otherOpts: ['dflt'],
        coerceFunction: function(v, propOut, dflt) {
            propOut.set(scales.get(v, dflt));
        }
    },
    angle: {
        description: [
            'A number (in degree) between -180 and 180.'
        ].join(' '),
        requiredOpts: [],
        otherOpts: ['dflt'],
        coerceFunction: function(v, propOut, dflt) {
            if(v === 'auto') propOut.set('auto');
            else if(!isNumeric(v)) propOut.set(dflt);
            else propOut.set(modHalf(+v, 360));
        }
    },
    subplotid: {
        description: [
            'An id string of a subplot type (given by dflt), optionally',
            'followed by an integer >1. e.g. if dflt=\'geo\', we can have',
            '\'geo\', \'geo2\', \'geo3\', ...'
        ].join(' '),
        requiredOpts: ['dflt'],
        otherOpts: ['regex'],
        coerceFunction: function(v, propOut, dflt, opts) {
            var regex = opts.regex || counterRegex(dflt);
            if(typeof v === 'string' && regex.test(v)) {
                propOut.set(v);
                return;
            }
            propOut.set(dflt);
        },
        validateFunction: function(v, opts) {
            var dflt = opts.dflt;

            if(v === dflt) return true;
            if(typeof v !== 'string') return false;
            if(counterRegex(dflt).test(v)) return true;

            return false;
        }
    },
    flaglist: {
        description: [
            'A string representing a combination of flags',
            '(order does not matter here).',
            'Combine any of the available `flags` with *+*.',
            '(e.g. (\'lines+markers\')).',
            'Values in `extras` cannot be combined.'
        ].join(' '),
        requiredOpts: ['flags'],
        otherOpts: ['dflt', 'extras', 'arrayOk'],
        coerceFunction: function(v, propOut, dflt, opts) {
            if(typeof v !== 'string') {
                propOut.set(dflt);
                return;
            }
            if((opts.extras || []).indexOf(v) !== -1) {
                propOut.set(v);
                return;
            }
            var vParts = v.split('+');
            var i = 0;
            while(i < vParts.length) {
                var vi = vParts[i];
                if(opts.flags.indexOf(vi) === -1 || vParts.indexOf(vi) < i) {
                    vParts.splice(i, 1);
                }
                else i++;
            }
            if(!vParts.length) propOut.set(dflt);
            else propOut.set(vParts.join('+'));
        }
    },
    any: {
        description: 'Any type.',
        requiredOpts: [],
        otherOpts: ['dflt', 'values', 'arrayOk'],
        coerceFunction: function(v, propOut, dflt) {
            if(v === undefined) propOut.set(dflt);
            else propOut.set(v);
        }
    },
    info_array: {
        description: [
            'An {array} of plot information.'
        ].join(' '),
        requiredOpts: ['items'],
        // set `dimensions=2` for a 2D array or '1-2' for either
        // `items` may be a single object instead of an array, in which case
        // `freeLength` must be true.
        // if `dimensions='1-2'` and items is a 1D array, then the value can
        // either be a matching 1D array or an array of such matching 1D arrays
        otherOpts: ['dflt', 'freeLength', 'dimensions'],
        coerceFunction: function(v, propOut, dflt, opts) {

            // simplified coerce function just for array items
            function coercePart(v, opts, dflt) {
                var out;
                var propPart = {set: function(v) { out = v; }};

                if(dflt === undefined) dflt = opts.dflt;

                exports.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts);

                return out;
            }

            var twoD = opts.dimensions === 2 || (opts.dimensions === '1-2' && Array.isArray(v) && Array.isArray(v[0]));

            if(!Array.isArray(v)) {
                propOut.set(dflt);
                return;
            }

            var items = opts.items;
            var vOut = [];
            var arrayItems = Array.isArray(items);
            var arrayItems2D = arrayItems && twoD && Array.isArray(items[0]);
            var innerItemsOnly = twoD && arrayItems && !arrayItems2D;
            var len = (arrayItems && !innerItemsOnly) ? items.length : v.length;

            var i, j, row, item, len2, vNew;

            dflt = Array.isArray(dflt) ? dflt : [];

            if(twoD) {
                for(i = 0; i < len; i++) {
                    vOut[i] = [];
                    row = Array.isArray(v[i]) ? v[i] : [];
                    if(innerItemsOnly) len2 = items.length;
                    else if(arrayItems) len2 = items[i].length;
                    else len2 = row.length;

                    for(j = 0; j < len2; j++) {
                        if(innerItemsOnly) item = items[j];
                        else if(arrayItems) item = items[i][j];
                        else item = items;

                        vNew = coercePart(row[j], item, (dflt[i] || [])[j]);
                        if(vNew !== undefined) vOut[i][j] = vNew;
                    }
                }
            }
            else {
                for(i = 0; i < len; i++) {
                    vNew = coercePart(v[i], arrayItems ? items[i] : items, dflt[i]);
                    if(vNew !== undefined) vOut[i] = vNew;
                }
            }

            propOut.set(vOut);
        },
        validateFunction: function(v, opts) {
            if(!Array.isArray(v)) return false;

            var items = opts.items;
            var arrayItems = Array.isArray(items);
            var twoD = opts.dimensions === 2;

            // when free length is off, input and declared lengths must match
            if(!opts.freeLength && v.length !== items.length) return false;

            // valid when all input items are valid
            for(var i = 0; i < v.length; i++) {
                if(twoD) {
                    if(!Array.isArray(v[i]) || (!opts.freeLength && v[i].length !== items[i].length)) {
                        return false;
                    }
                    for(var j = 0; j < v[i].length; j++) {
                        if(!validate(v[i][j], arrayItems ? items[i][j] : items)) {
                            return false;
                        }
                    }
                }
                else if(!validate(v[i], arrayItems ? items[i] : items)) return false;
            }

            return true;
        }
    }
};

/**
 * Ensures that container[attribute] has a valid value.
 *
 * attributes[attribute] is an object with possible keys:
 * - valType: data_array, enumerated, boolean, ... as in valObjectMeta
 * - values: (enumerated only) array of allowed vals
 * - min, max: (number, integer only) inclusive bounds on allowed vals
 *      either or both may be omitted
 * - dflt: if attribute is invalid or missing, use this default
 *      if dflt is provided as an argument to lib.coerce it takes precedence
 *      as a convenience, returns the value it finally set
 */
exports.coerce = function(containerIn, containerOut, attributes, attribute, dflt) {
    var opts = nestedProperty(attributes, attribute).get();
    var propIn = nestedProperty(containerIn, attribute);
    var propOut = nestedProperty(containerOut, attribute);
    var v = propIn.get();

    var template = containerOut._template;
    if(v === undefined && template) {
        v = nestedProperty(template, attribute).get();
        // already used the template value, so short-circuit the second check
        template = 0;
    }

    if(dflt === undefined) dflt = opts.dflt;

    /**
     * arrayOk: value MAY be an array, then we do no value checking
     * at this point, because it can be more complicated than the
     * individual form (eg. some array vals can be numbers, even if the
     * single values must be color strings)
     */
    if(opts.arrayOk && isArrayOrTypedArray(v)) {
        propOut.set(v);
        return v;
    }

    var coerceFunction = exports.valObjectMeta[opts.valType].coerceFunction;
    coerceFunction(v, propOut, dflt, opts);

    var out = propOut.get();
    // in case v was provided but invalid, try the template again so it still
    // overrides the regular default
    if(template && out === dflt && !validate(v, opts)) {
        v = nestedProperty(template, attribute).get();
        coerceFunction(v, propOut, dflt, opts);
        out = propOut.get();
    }
    return out;
};

/**
 * Variation on coerce
 *
 * Uses coerce to get attribute value if user input is valid,
 * returns attribute default if user input it not valid or
 * returns false if there is no user input.
 */
exports.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) {
    var propIn = nestedProperty(containerIn, attribute);
    var propOut = exports.coerce(containerIn, containerOut, attributes, attribute, dflt);
    var valIn = propIn.get();

    return (valIn !== undefined && valIn !== null) ? propOut : false;
};

/*
 * Shortcut to coerce the three font attributes
 *
 * 'coerce' is a lib.coerce wrapper with implied first three arguments
 */
exports.coerceFont = function(coerce, attr, dfltObj) {
    var out = {};

    dfltObj = dfltObj || {};

    out.family = coerce(attr + '.family', dfltObj.family);
    out.size = coerce(attr + '.size', dfltObj.size);
    out.color = coerce(attr + '.color', dfltObj.color);

    return out;
};

/** Coerce shortcut for 'hoverinfo'
 * handling 1-vs-multi-trace dflt logic
 *
 * @param {object} traceIn : user trace object
 * @param {object} traceOut : full trace object (requires _module ref)
 * @param {object} layoutOut : full layout object (require _dataLength ref)
 * @return {any} : the coerced value
 */
exports.coerceHoverinfo = function(traceIn, traceOut, layoutOut) {
    var moduleAttrs = traceOut._module.attributes;
    var attrs = moduleAttrs.hoverinfo ? moduleAttrs : baseTraceAttrs;

    var valObj = attrs.hoverinfo;
    var dflt;

    if(layoutOut._dataLength === 1) {
        var flags = valObj.dflt === 'all' ?
            valObj.flags.slice() :
            valObj.dflt.split('+');

        flags.splice(flags.indexOf('name'), 1);
        dflt = flags.join('+');
    }

    return exports.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt);
};

/** Coerce shortcut for [un]selected.marker.opacity,
 *  which has special default logic, to ensure that it corresponds to the
 *  default selection behavior while allowing to be overtaken by any other
 *  [un]selected attribute.
 *
 *  N.B. This must be called *after* coercing all the other [un]selected attrs,
 *  to give the intended result.
 *
 * @param {object} traceOut : fullData item
 * @param {function} coerce : lib.coerce wrapper with implied first three arguments
 */
exports.coerceSelectionMarkerOpacity = function(traceOut, coerce) {
    if(!traceOut.marker) return;

    var mo = traceOut.marker.opacity;
    // you can still have a `marker` container with no markers if there's text
    if(mo === undefined) return;

    var smoDflt;
    var usmoDflt;

    // Don't give [un]selected.marker.opacity a default value if
    // marker.opacity is an array: handle this during style step.
    //
    // Only give [un]selected.marker.opacity a default value if you don't
    // set any other [un]selected attributes.
    if(!isArrayOrTypedArray(mo) && !traceOut.selected && !traceOut.unselected) {
        smoDflt = mo;
        usmoDflt = DESELECTDIM * mo;
    }

    coerce('selected.marker.opacity', smoDflt);
    coerce('unselected.marker.opacity', usmoDflt);
};

function validate(value, opts) {
    var valObjectDef = exports.valObjectMeta[opts.valType];

    if(opts.arrayOk && isArrayOrTypedArray(value)) return true;

    if(valObjectDef.validateFunction) {
        return valObjectDef.validateFunction(value, opts);
    }

    var failed = {};
    var out = failed;
    var propMock = { set: function(v) { out = v; } };

    // 'failed' just something mutable that won't be === anything else

    valObjectDef.coerceFunction(value, propMock, failed, opts);
    return out !== failed;
}
exports.validate = validate;


/***/ }),

/***/ "Zss7":
/*!**********************************************!*\
  !*** ./node_modules/tinycolor2/tinycolor.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_RESULT__;// TinyColor v1.4.1
// https://github.com/bgrins/TinyColor
// Brian Grinstead, MIT License

(function(Math) {

var trimLeft = /^\s+/,
    trimRight = /\s+$/,
    tinyCounter = 0,
    mathRound = Math.round,
    mathMin = Math.min,
    mathMax = Math.max,
    mathRandom = Math.random;

function tinycolor (color, opts) {

    color = (color) ? color : '';
    opts = opts || { };

    // If input is already a tinycolor, return itself
    if (color instanceof tinycolor) {
       return color;
    }
    // If we are called as a function, call using new instead
    if (!(this instanceof tinycolor)) {
        return new tinycolor(color, opts);
    }

    var rgb = inputToRGB(color);
    this._originalInput = color,
    this._r = rgb.r,
    this._g = rgb.g,
    this._b = rgb.b,
    this._a = rgb.a,
    this._roundA = mathRound(100*this._a) / 100,
    this._format = opts.format || rgb.format;
    this._gradientType = opts.gradientType;

    // Don't let the range of [0,255] come back in [0,1].
    // Potentially lose a little bit of precision here, but will fix issues where
    // .5 gets interpreted as half of the total, instead of half of 1
    // If it was supposed to be 128, this was already taken care of by `inputToRgb`
    if (this._r < 1) { this._r = mathRound(this._r); }
    if (this._g < 1) { this._g = mathRound(this._g); }
    if (this._b < 1) { this._b = mathRound(this._b); }

    this._ok = rgb.ok;
    this._tc_id = tinyCounter++;
}

tinycolor.prototype = {
    isDark: function() {
        return this.getBrightness() < 128;
    },
    isLight: function() {
        return !this.isDark();
    },
    isValid: function() {
        return this._ok;
    },
    getOriginalInput: function() {
      return this._originalInput;
    },
    getFormat: function() {
        return this._format;
    },
    getAlpha: function() {
        return this._a;
    },
    getBrightness: function() {
        //http://www.w3.org/TR/AERT#color-contrast
        var rgb = this.toRgb();
        return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
    },
    getLuminance: function() {
        //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
        var rgb = this.toRgb();
        var RsRGB, GsRGB, BsRGB, R, G, B;
        RsRGB = rgb.r/255;
        GsRGB = rgb.g/255;
        BsRGB = rgb.b/255;

        if (RsRGB <= 0.03928) {R = RsRGB / 12.92;} else {R = Math.pow(((RsRGB + 0.055) / 1.055), 2.4);}
        if (GsRGB <= 0.03928) {G = GsRGB / 12.92;} else {G = Math.pow(((GsRGB + 0.055) / 1.055), 2.4);}
        if (BsRGB <= 0.03928) {B = BsRGB / 12.92;} else {B = Math.pow(((BsRGB + 0.055) / 1.055), 2.4);}
        return (0.2126 * R) + (0.7152 * G) + (0.0722 * B);
    },
    setAlpha: function(value) {
        this._a = boundAlpha(value);
        this._roundA = mathRound(100*this._a) / 100;
        return this;
    },
    toHsv: function() {
        var hsv = rgbToHsv(this._r, this._g, this._b);
        return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };
    },
    toHsvString: function() {
        var hsv = rgbToHsv(this._r, this._g, this._b);
        var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);
        return (this._a == 1) ?
          "hsv("  + h + ", " + s + "%, " + v + "%)" :
          "hsva(" + h + ", " + s + "%, " + v + "%, "+ this._roundA + ")";
    },
    toHsl: function() {
        var hsl = rgbToHsl(this._r, this._g, this._b);
        return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };
    },
    toHslString: function() {
        var hsl = rgbToHsl(this._r, this._g, this._b);
        var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);
        return (this._a == 1) ?
          "hsl("  + h + ", " + s + "%, " + l + "%)" :
          "hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")";
    },
    toHex: function(allow3Char) {
        return rgbToHex(this._r, this._g, this._b, allow3Char);
    },
    toHexString: function(allow3Char) {
        return '#' + this.toHex(allow3Char);
    },
    toHex8: function(allow4Char) {
        return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char);
    },
    toHex8String: function(allow4Char) {
        return '#' + this.toHex8(allow4Char);
    },
    toRgb: function() {
        return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a };
    },
    toRgbString: function() {
        return (this._a == 1) ?
          "rgb("  + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" :
          "rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")";
    },
    toPercentageRgb: function() {
        return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a };
    },
    toPercentageRgbString: function() {
        return (this._a == 1) ?
          "rgb("  + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" :
          "rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")";
    },
    toName: function() {
        if (this._a === 0) {
            return "transparent";
        }

        if (this._a < 1) {
            return false;
        }

        return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
    },
    toFilter: function(secondColor) {
        var hex8String = '#' + rgbaToArgbHex(this._r, this._g, this._b, this._a);
        var secondHex8String = hex8String;
        var gradientType = this._gradientType ? "GradientType = 1, " : "";

        if (secondColor) {
            var s = tinycolor(secondColor);
            secondHex8String = '#' + rgbaToArgbHex(s._r, s._g, s._b, s._a);
        }

        return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")";
    },
    toString: function(format) {
        var formatSet = !!format;
        format = format || this._format;

        var formattedString = false;
        var hasAlpha = this._a < 1 && this._a >= 0;
        var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name");

        if (needsAlphaFormat) {
            // Special case for "transparent", all other non-alpha formats
            // will return rgba when there is transparency.
            if (format === "name" && this._a === 0) {
                return this.toName();
            }
            return this.toRgbString();
        }
        if (format === "rgb") {
            formattedString = this.toRgbString();
        }
        if (format === "prgb") {
            formattedString = this.toPercentageRgbString();
        }
        if (format === "hex" || format === "hex6") {
            formattedString = this.toHexString();
        }
        if (format === "hex3") {
            formattedString = this.toHexString(true);
        }
        if (format === "hex4") {
            formattedString = this.toHex8String(true);
        }
        if (format === "hex8") {
            formattedString = this.toHex8String();
        }
        if (format === "name") {
            formattedString = this.toName();
        }
        if (format === "hsl") {
            formattedString = this.toHslString();
        }
        if (format === "hsv") {
            formattedString = this.toHsvString();
        }

        return formattedString || this.toHexString();
    },
    clone: function() {
        return tinycolor(this.toString());
    },

    _applyModification: function(fn, args) {
        var color = fn.apply(null, [this].concat([].slice.call(args)));
        this._r = color._r;
        this._g = color._g;
        this._b = color._b;
        this.setAlpha(color._a);
        return this;
    },
    lighten: function() {
        return this._applyModification(lighten, arguments);
    },
    brighten: function() {
        return this._applyModification(brighten, arguments);
    },
    darken: function() {
        return this._applyModification(darken, arguments);
    },
    desaturate: function() {
        return this._applyModification(desaturate, arguments);
    },
    saturate: function() {
        return this._applyModification(saturate, arguments);
    },
    greyscale: function() {
        return this._applyModification(greyscale, arguments);
    },
    spin: function() {
        return this._applyModification(spin, arguments);
    },

    _applyCombination: function(fn, args) {
        return fn.apply(null, [this].concat([].slice.call(args)));
    },
    analogous: function() {
        return this._applyCombination(analogous, arguments);
    },
    complement: function() {
        return this._applyCombination(complement, arguments);
    },
    monochromatic: function() {
        return this._applyCombination(monochromatic, arguments);
    },
    splitcomplement: function() {
        return this._applyCombination(splitcomplement, arguments);
    },
    triad: function() {
        return this._applyCombination(triad, arguments);
    },
    tetrad: function() {
        return this._applyCombination(tetrad, arguments);
    }
};

// If input is an object, force 1 into "1.0" to handle ratios properly
// String input requires "1.0" as input, so 1 will be treated as 1
tinycolor.fromRatio = function(color, opts) {
    if (typeof color == "object") {
        var newColor = {};
        for (var i in color) {
            if (color.hasOwnProperty(i)) {
                if (i === "a") {
                    newColor[i] = color[i];
                }
                else {
                    newColor[i] = convertToPercentage(color[i]);
                }
            }
        }
        color = newColor;
    }

    return tinycolor(color, opts);
};

// Given a string or object, convert that input to RGB
// Possible string inputs:
//
//     "red"
//     "#f00" or "f00"
//     "#ff0000" or "ff0000"
//     "#ff000000" or "ff000000"
//     "rgb 255 0 0" or "rgb (255, 0, 0)"
//     "rgb 1.0 0 0" or "rgb (1, 0, 0)"
//     "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
//     "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
//     "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
//     "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
//     "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
//
function inputToRGB(color) {

    var rgb = { r: 0, g: 0, b: 0 };
    var a = 1;
    var s = null;
    var v = null;
    var l = null;
    var ok = false;
    var format = false;

    if (typeof color == "string") {
        color = stringInputToObject(color);
    }

    if (typeof color == "object") {
        if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) {
            rgb = rgbToRgb(color.r, color.g, color.b);
            ok = true;
            format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
        }
        else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) {
            s = convertToPercentage(color.s);
            v = convertToPercentage(color.v);
            rgb = hsvToRgb(color.h, s, v);
            ok = true;
            format = "hsv";
        }
        else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) {
            s = convertToPercentage(color.s);
            l = convertToPercentage(color.l);
            rgb = hslToRgb(color.h, s, l);
            ok = true;
            format = "hsl";
        }

        if (color.hasOwnProperty("a")) {
            a = color.a;
        }
    }

    a = boundAlpha(a);

    return {
        ok: ok,
        format: color.format || format,
        r: mathMin(255, mathMax(rgb.r, 0)),
        g: mathMin(255, mathMax(rgb.g, 0)),
        b: mathMin(255, mathMax(rgb.b, 0)),
        a: a
    };
}


// Conversion Functions
// --------------------

// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
// <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript>

// `rgbToRgb`
// Handle bounds / percentage checking to conform to CSS color spec
// <http://www.w3.org/TR/css3-color/>
// *Assumes:* r, g, b in [0, 255] or [0, 1]
// *Returns:* { r, g, b } in [0, 255]
function rgbToRgb(r, g, b){
    return {
        r: bound01(r, 255) * 255,
        g: bound01(g, 255) * 255,
        b: bound01(b, 255) * 255
    };
}

// `rgbToHsl`
// Converts an RGB color value to HSL.
// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]
// *Returns:* { h, s, l } in [0,1]
function rgbToHsl(r, g, b) {

    r = bound01(r, 255);
    g = bound01(g, 255);
    b = bound01(b, 255);

    var max = mathMax(r, g, b), min = mathMin(r, g, b);
    var h, s, l = (max + min) / 2;

    if(max == min) {
        h = s = 0; // achromatic
    }
    else {
        var d = max - min;
        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
        switch(max) {
            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
            case g: h = (b - r) / d + 2; break;
            case b: h = (r - g) / d + 4; break;
        }

        h /= 6;
    }

    return { h: h, s: s, l: l };
}

// `hslToRgb`
// Converts an HSL color value to RGB.
// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]
// *Returns:* { r, g, b } in the set [0, 255]
function hslToRgb(h, s, l) {
    var r, g, b;

    h = bound01(h, 360);
    s = bound01(s, 100);
    l = bound01(l, 100);

    function hue2rgb(p, q, t) {
        if(t < 0) t += 1;
        if(t > 1) t -= 1;
        if(t < 1/6) return p + (q - p) * 6 * t;
        if(t < 1/2) return q;
        if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
        return p;
    }

    if(s === 0) {
        r = g = b = l; // achromatic
    }
    else {
        var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
        var p = 2 * l - q;
        r = hue2rgb(p, q, h + 1/3);
        g = hue2rgb(p, q, h);
        b = hue2rgb(p, q, h - 1/3);
    }

    return { r: r * 255, g: g * 255, b: b * 255 };
}

// `rgbToHsv`
// Converts an RGB color value to HSV
// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]
// *Returns:* { h, s, v } in [0,1]
function rgbToHsv(r, g, b) {

    r = bound01(r, 255);
    g = bound01(g, 255);
    b = bound01(b, 255);

    var max = mathMax(r, g, b), min = mathMin(r, g, b);
    var h, s, v = max;

    var d = max - min;
    s = max === 0 ? 0 : d / max;

    if(max == min) {
        h = 0; // achromatic
    }
    else {
        switch(max) {
            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
            case g: h = (b - r) / d + 2; break;
            case b: h = (r - g) / d + 4; break;
        }
        h /= 6;
    }
    return { h: h, s: s, v: v };
}

// `hsvToRgb`
// Converts an HSV color value to RGB.
// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]
// *Returns:* { r, g, b } in the set [0, 255]
 function hsvToRgb(h, s, v) {

    h = bound01(h, 360) * 6;
    s = bound01(s, 100);
    v = bound01(v, 100);

    var i = Math.floor(h),
        f = h - i,
        p = v * (1 - s),
        q = v * (1 - f * s),
        t = v * (1 - (1 - f) * s),
        mod = i % 6,
        r = [v, q, p, p, t, v][mod],
        g = [t, v, v, q, p, p][mod],
        b = [p, p, t, v, v, q][mod];

    return { r: r * 255, g: g * 255, b: b * 255 };
}

// `rgbToHex`
// Converts an RGB color to hex
// Assumes r, g, and b are contained in the set [0, 255]
// Returns a 3 or 6 character hex
function rgbToHex(r, g, b, allow3Char) {

    var hex = [
        pad2(mathRound(r).toString(16)),
        pad2(mathRound(g).toString(16)),
        pad2(mathRound(b).toString(16))
    ];

    // Return a 3 character hex if possible
    if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
        return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
    }

    return hex.join("");
}

// `rgbaToHex`
// Converts an RGBA color plus alpha transparency to hex
// Assumes r, g, b are contained in the set [0, 255] and
// a in [0, 1]. Returns a 4 or 8 character rgba hex
function rgbaToHex(r, g, b, a, allow4Char) {

    var hex = [
        pad2(mathRound(r).toString(16)),
        pad2(mathRound(g).toString(16)),
        pad2(mathRound(b).toString(16)),
        pad2(convertDecimalToHex(a))
    ];

    // Return a 4 character hex if possible
    if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) {
        return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0);
    }

    return hex.join("");
}

// `rgbaToArgbHex`
// Converts an RGBA color to an ARGB Hex8 string
// Rarely used, but required for "toFilter()"
function rgbaToArgbHex(r, g, b, a) {

    var hex = [
        pad2(convertDecimalToHex(a)),
        pad2(mathRound(r).toString(16)),
        pad2(mathRound(g).toString(16)),
        pad2(mathRound(b).toString(16))
    ];

    return hex.join("");
}

// `equals`
// Can be called with any tinycolor input
tinycolor.equals = function (color1, color2) {
    if (!color1 || !color2) { return false; }
    return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
};

tinycolor.random = function() {
    return tinycolor.fromRatio({
        r: mathRandom(),
        g: mathRandom(),
        b: mathRandom()
    });
};


// Modification Functions
// ----------------------
// Thanks to less.js for some of the basics here
// <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js>

function desaturate(color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var hsl = tinycolor(color).toHsl();
    hsl.s -= amount / 100;
    hsl.s = clamp01(hsl.s);
    return tinycolor(hsl);
}

function saturate(color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var hsl = tinycolor(color).toHsl();
    hsl.s += amount / 100;
    hsl.s = clamp01(hsl.s);
    return tinycolor(hsl);
}

function greyscale(color) {
    return tinycolor(color).desaturate(100);
}

function lighten (color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var hsl = tinycolor(color).toHsl();
    hsl.l += amount / 100;
    hsl.l = clamp01(hsl.l);
    return tinycolor(hsl);
}

function brighten(color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var rgb = tinycolor(color).toRgb();
    rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100))));
    rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100))));
    rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100))));
    return tinycolor(rgb);
}

function darken (color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var hsl = tinycolor(color).toHsl();
    hsl.l -= amount / 100;
    hsl.l = clamp01(hsl.l);
    return tinycolor(hsl);
}

// Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.
// Values outside of this range will be wrapped into this range.
function spin(color, amount) {
    var hsl = tinycolor(color).toHsl();
    var hue = (hsl.h + amount) % 360;
    hsl.h = hue < 0 ? 360 + hue : hue;
    return tinycolor(hsl);
}

// Combination Functions
// ---------------------
// Thanks to jQuery xColor for some of the ideas behind these
// <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js>

function complement(color) {
    var hsl = tinycolor(color).toHsl();
    hsl.h = (hsl.h + 180) % 360;
    return tinycolor(hsl);
}

function triad(color) {
    var hsl = tinycolor(color).toHsl();
    var h = hsl.h;
    return [
        tinycolor(color),
        tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),
        tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l })
    ];
}

function tetrad(color) {
    var hsl = tinycolor(color).toHsl();
    var h = hsl.h;
    return [
        tinycolor(color),
        tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),
        tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),
        tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l })
    ];
}

function splitcomplement(color) {
    var hsl = tinycolor(color).toHsl();
    var h = hsl.h;
    return [
        tinycolor(color),
        tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}),
        tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l})
    ];
}

function analogous(color, results, slices) {
    results = results || 6;
    slices = slices || 30;

    var hsl = tinycolor(color).toHsl();
    var part = 360 / slices;
    var ret = [tinycolor(color)];

    for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) {
        hsl.h = (hsl.h + part) % 360;
        ret.push(tinycolor(hsl));
    }
    return ret;
}

function monochromatic(color, results) {
    results = results || 6;
    var hsv = tinycolor(color).toHsv();
    var h = hsv.h, s = hsv.s, v = hsv.v;
    var ret = [];
    var modification = 1 / results;

    while (results--) {
        ret.push(tinycolor({ h: h, s: s, v: v}));
        v = (v + modification) % 1;
    }

    return ret;
}

// Utility Functions
// ---------------------

tinycolor.mix = function(color1, color2, amount) {
    amount = (amount === 0) ? 0 : (amount || 50);

    var rgb1 = tinycolor(color1).toRgb();
    var rgb2 = tinycolor(color2).toRgb();

    var p = amount / 100;

    var rgba = {
        r: ((rgb2.r - rgb1.r) * p) + rgb1.r,
        g: ((rgb2.g - rgb1.g) * p) + rgb1.g,
        b: ((rgb2.b - rgb1.b) * p) + rgb1.b,
        a: ((rgb2.a - rgb1.a) * p) + rgb1.a
    };

    return tinycolor(rgba);
};


// Readability Functions
// ---------------------
// <http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef (WCAG Version 2)

// `contrast`
// Analyze the 2 colors and returns the color contrast defined by (WCAG Version 2)
tinycolor.readability = function(color1, color2) {
    var c1 = tinycolor(color1);
    var c2 = tinycolor(color2);
    return (Math.max(c1.getLuminance(),c2.getLuminance())+0.05) / (Math.min(c1.getLuminance(),c2.getLuminance())+0.05);
};

// `isReadable`
// Ensure that foreground and background color combinations meet WCAG2 guidelines.
// The third argument is an optional Object.
//      the 'level' property states 'AA' or 'AAA' - if missing or invalid, it defaults to 'AA';
//      the 'size' property states 'large' or 'small' - if missing or invalid, it defaults to 'small'.
// If the entire object is absent, isReadable defaults to {level:"AA",size:"small"}.

// *Example*
//    tinycolor.isReadable("#000", "#111") => false
//    tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false
tinycolor.isReadable = function(color1, color2, wcag2) {
    var readability = tinycolor.readability(color1, color2);
    var wcag2Parms, out;

    out = false;

    wcag2Parms = validateWCAG2Parms(wcag2);
    switch (wcag2Parms.level + wcag2Parms.size) {
        case "AAsmall":
        case "AAAlarge":
            out = readability >= 4.5;
            break;
        case "AAlarge":
            out = readability >= 3;
            break;
        case "AAAsmall":
            out = readability >= 7;
            break;
    }
    return out;

};

// `mostReadable`
// Given a base color and a list of possible foreground or background
// colors for that base, returns the most readable color.
// Optionally returns Black or White if the most readable color is unreadable.
// *Example*
//    tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255"
//    tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString();  // "#ffffff"
//    tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3"
//    tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff"
tinycolor.mostReadable = function(baseColor, colorList, args) {
    var bestColor = null;
    var bestScore = 0;
    var readability;
    var includeFallbackColors, level, size ;
    args = args || {};
    includeFallbackColors = args.includeFallbackColors ;
    level = args.level;
    size = args.size;

    for (var i= 0; i < colorList.length ; i++) {
        readability = tinycolor.readability(baseColor, colorList[i]);
        if (readability > bestScore) {
            bestScore = readability;
            bestColor = tinycolor(colorList[i]);
        }
    }

    if (tinycolor.isReadable(baseColor, bestColor, {"level":level,"size":size}) || !includeFallbackColors) {
        return bestColor;
    }
    else {
        args.includeFallbackColors=false;
        return tinycolor.mostReadable(baseColor,["#fff", "#000"],args);
    }
};


// Big List of Colors
// ------------------
// <http://www.w3.org/TR/css3-color/#svg-color>
var names = tinycolor.names = {
    aliceblue: "f0f8ff",
    antiquewhite: "faebd7",
    aqua: "0ff",
    aquamarine: "7fffd4",
    azure: "f0ffff",
    beige: "f5f5dc",
    bisque: "ffe4c4",
    black: "000",
    blanchedalmond: "ffebcd",
    blue: "00f",
    blueviolet: "8a2be2",
    brown: "a52a2a",
    burlywood: "deb887",
    burntsienna: "ea7e5d",
    cadetblue: "5f9ea0",
    chartreuse: "7fff00",
    chocolate: "d2691e",
    coral: "ff7f50",
    cornflowerblue: "6495ed",
    cornsilk: "fff8dc",
    crimson: "dc143c",
    cyan: "0ff",
    darkblue: "00008b",
    darkcyan: "008b8b",
    darkgoldenrod: "b8860b",
    darkgray: "a9a9a9",
    darkgreen: "006400",
    darkgrey: "a9a9a9",
    darkkhaki: "bdb76b",
    darkmagenta: "8b008b",
    darkolivegreen: "556b2f",
    darkorange: "ff8c00",
    darkorchid: "9932cc",
    darkred: "8b0000",
    darksalmon: "e9967a",
    darkseagreen: "8fbc8f",
    darkslateblue: "483d8b",
    darkslategray: "2f4f4f",
    darkslategrey: "2f4f4f",
    darkturquoise: "00ced1",
    darkviolet: "9400d3",
    deeppink: "ff1493",
    deepskyblue: "00bfff",
    dimgray: "696969",
    dimgrey: "696969",
    dodgerblue: "1e90ff",
    firebrick: "b22222",
    floralwhite: "fffaf0",
    forestgreen: "228b22",
    fuchsia: "f0f",
    gainsboro: "dcdcdc",
    ghostwhite: "f8f8ff",
    gold: "ffd700",
    goldenrod: "daa520",
    gray: "808080",
    green: "008000",
    greenyellow: "adff2f",
    grey: "808080",
    honeydew: "f0fff0",
    hotpink: "ff69b4",
    indianred: "cd5c5c",
    indigo: "4b0082",
    ivory: "fffff0",
    khaki: "f0e68c",
    lavender: "e6e6fa",
    lavenderblush: "fff0f5",
    lawngreen: "7cfc00",
    lemonchiffon: "fffacd",
    lightblue: "add8e6",
    lightcoral: "f08080",
    lightcyan: "e0ffff",
    lightgoldenrodyellow: "fafad2",
    lightgray: "d3d3d3",
    lightgreen: "90ee90",
    lightgrey: "d3d3d3",
    lightpink: "ffb6c1",
    lightsalmon: "ffa07a",
    lightseagreen: "20b2aa",
    lightskyblue: "87cefa",
    lightslategray: "789",
    lightslategrey: "789",
    lightsteelblue: "b0c4de",
    lightyellow: "ffffe0",
    lime: "0f0",
    limegreen: "32cd32",
    linen: "faf0e6",
    magenta: "f0f",
    maroon: "800000",
    mediumaquamarine: "66cdaa",
    mediumblue: "0000cd",
    mediumorchid: "ba55d3",
    mediumpurple: "9370db",
    mediumseagreen: "3cb371",
    mediumslateblue: "7b68ee",
    mediumspringgreen: "00fa9a",
    mediumturquoise: "48d1cc",
    mediumvioletred: "c71585",
    midnightblue: "191970",
    mintcream: "f5fffa",
    mistyrose: "ffe4e1",
    moccasin: "ffe4b5",
    navajowhite: "ffdead",
    navy: "000080",
    oldlace: "fdf5e6",
    olive: "808000",
    olivedrab: "6b8e23",
    orange: "ffa500",
    orangered: "ff4500",
    orchid: "da70d6",
    palegoldenrod: "eee8aa",
    palegreen: "98fb98",
    paleturquoise: "afeeee",
    palevioletred: "db7093",
    papayawhip: "ffefd5",
    peachpuff: "ffdab9",
    peru: "cd853f",
    pink: "ffc0cb",
    plum: "dda0dd",
    powderblue: "b0e0e6",
    purple: "800080",
    rebeccapurple: "663399",
    red: "f00",
    rosybrown: "bc8f8f",
    royalblue: "4169e1",
    saddlebrown: "8b4513",
    salmon: "fa8072",
    sandybrown: "f4a460",
    seagreen: "2e8b57",
    seashell: "fff5ee",
    sienna: "a0522d",
    silver: "c0c0c0",
    skyblue: "87ceeb",
    slateblue: "6a5acd",
    slategray: "708090",
    slategrey: "708090",
    snow: "fffafa",
    springgreen: "00ff7f",
    steelblue: "4682b4",
    tan: "d2b48c",
    teal: "008080",
    thistle: "d8bfd8",
    tomato: "ff6347",
    turquoise: "40e0d0",
    violet: "ee82ee",
    wheat: "f5deb3",
    white: "fff",
    whitesmoke: "f5f5f5",
    yellow: "ff0",
    yellowgreen: "9acd32"
};

// Make it easy to access colors via `hexNames[hex]`
var hexNames = tinycolor.hexNames = flip(names);


// Utilities
// ---------

// `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`
function flip(o) {
    var flipped = { };
    for (var i in o) {
        if (o.hasOwnProperty(i)) {
            flipped[o[i]] = i;
        }
    }
    return flipped;
}

// Return a valid alpha value [0,1] with all invalid values being set to 1
function boundAlpha(a) {
    a = parseFloat(a);

    if (isNaN(a) || a < 0 || a > 1) {
        a = 1;
    }

    return a;
}

// Take input from [0, n] and return it as [0, 1]
function bound01(n, max) {
    if (isOnePointZero(n)) { n = "100%"; }

    var processPercent = isPercentage(n);
    n = mathMin(max, mathMax(0, parseFloat(n)));

    // Automatically convert percentage into number
    if (processPercent) {
        n = parseInt(n * max, 10) / 100;
    }

    // Handle floating point rounding errors
    if ((Math.abs(n - max) < 0.000001)) {
        return 1;
    }

    // Convert into [0, 1] range if it isn't already
    return (n % max) / parseFloat(max);
}

// Force a number between 0 and 1
function clamp01(val) {
    return mathMin(1, mathMax(0, val));
}

// Parse a base-16 hex value into a base-10 integer
function parseIntFromHex(val) {
    return parseInt(val, 16);
}

// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
// <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
function isOnePointZero(n) {
    return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1;
}

// Check to see if string passed in is a percentage
function isPercentage(n) {
    return typeof n === "string" && n.indexOf('%') != -1;
}

// Force a hex value to have 2 characters
function pad2(c) {
    return c.length == 1 ? '0' + c : '' + c;
}

// Replace a decimal with it's percentage value
function convertToPercentage(n) {
    if (n <= 1) {
        n = (n * 100) + "%";
    }

    return n;
}

// Converts a decimal to a hex value
function convertDecimalToHex(d) {
    return Math.round(parseFloat(d) * 255).toString(16);
}
// Converts a hex value to a decimal
function convertHexToDecimal(h) {
    return (parseIntFromHex(h) / 255);
}

var matchers = (function() {

    // <http://www.w3.org/TR/css3-values/#integers>
    var CSS_INTEGER = "[-\\+]?\\d+%?";

    // <http://www.w3.org/TR/css3-values/#number-value>
    var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";

    // Allow positive/negative integer/number.  Don't capture the either/or, just the entire outcome.
    var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";

    // Actual matching.
    // Parentheses and commas are optional, but not required.
    // Whitespace can take the place of commas or opening paren
    var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
    var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";

    return {
        CSS_UNIT: new RegExp(CSS_UNIT),
        rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
        rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
        hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
        hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
        hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
        hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
        hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
        hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
        hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
        hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
    };
})();

// `isValidCSSUnit`
// Take in a single string / number and check to see if it looks like a CSS unit
// (see `matchers` above for definition).
function isValidCSSUnit(color) {
    return !!matchers.CSS_UNIT.exec(color);
}

// `stringInputToObject`
// Permissive string parsing.  Take in a number of formats, and output an object
// based on detected format.  Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`
function stringInputToObject(color) {

    color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase();
    var named = false;
    if (names[color]) {
        color = names[color];
        named = true;
    }
    else if (color == 'transparent') {
        return { r: 0, g: 0, b: 0, a: 0, format: "name" };
    }

    // Try to match string input using regular expressions.
    // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]
    // Just return an object and let the conversion functions handle that.
    // This way the result will be the same whether the tinycolor is initialized with string or object.
    var match;
    if ((match = matchers.rgb.exec(color))) {
        return { r: match[1], g: match[2], b: match[3] };
    }
    if ((match = matchers.rgba.exec(color))) {
        return { r: match[1], g: match[2], b: match[3], a: match[4] };
    }
    if ((match = matchers.hsl.exec(color))) {
        return { h: match[1], s: match[2], l: match[3] };
    }
    if ((match = matchers.hsla.exec(color))) {
        return { h: match[1], s: match[2], l: match[3], a: match[4] };
    }
    if ((match = matchers.hsv.exec(color))) {
        return { h: match[1], s: match[2], v: match[3] };
    }
    if ((match = matchers.hsva.exec(color))) {
        return { h: match[1], s: match[2], v: match[3], a: match[4] };
    }
    if ((match = matchers.hex8.exec(color))) {
        return {
            r: parseIntFromHex(match[1]),
            g: parseIntFromHex(match[2]),
            b: parseIntFromHex(match[3]),
            a: convertHexToDecimal(match[4]),
            format: named ? "name" : "hex8"
        };
    }
    if ((match = matchers.hex6.exec(color))) {
        return {
            r: parseIntFromHex(match[1]),
            g: parseIntFromHex(match[2]),
            b: parseIntFromHex(match[3]),
            format: named ? "name" : "hex"
        };
    }
    if ((match = matchers.hex4.exec(color))) {
        return {
            r: parseIntFromHex(match[1] + '' + match[1]),
            g: parseIntFromHex(match[2] + '' + match[2]),
            b: parseIntFromHex(match[3] + '' + match[3]),
            a: convertHexToDecimal(match[4] + '' + match[4]),
            format: named ? "name" : "hex8"
        };
    }
    if ((match = matchers.hex3.exec(color))) {
        return {
            r: parseIntFromHex(match[1] + '' + match[1]),
            g: parseIntFromHex(match[2] + '' + match[2]),
            b: parseIntFromHex(match[3] + '' + match[3]),
            format: named ? "name" : "hex"
        };
    }

    return false;
}

function validateWCAG2Parms(parms) {
    // return valid WCAG2 parms for isReadable.
    // If input parms are invalid, return {"level":"AA", "size":"small"}
    var level, size;
    parms = parms || {"level":"AA", "size":"small"};
    level = (parms.level || "AA").toUpperCase();
    size = (parms.size || "small").toLowerCase();
    if (level !== "AA" && level !== "AAA") {
        level = "AA";
    }
    if (size !== "small" && size !== "large") {
        size = "small";
    }
    return {"level":level, "size":size};
}

// Node: Export function
if (typeof module !== "undefined" && module.exports) {
    module.exports = tinycolor;
}
// AMD/requirejs: Define the module
else if (true) {
    !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {return tinycolor;}).call(exports, __webpack_require__, exports, module),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
// Browser: Expose to window
else {}

})(Math);


/***/ }),

/***/ "ZuxE":
/*!************************************************!*\
  !*** ./node_modules/domhandler/lib/element.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// DOM-Level-1-compliant structure
var NodePrototype = __webpack_require__(/*! ./node */ "AdCt");
var ElementPrototype = module.exports = Object.create(NodePrototype);

var domLvl1 = {
	tagName: "name"
};

Object.keys(domLvl1).forEach(function(key) {
	var shorthand = domLvl1[key];
	Object.defineProperty(ElementPrototype, key, {
		get: function() {
			return this[shorthand] || null;
		},
		set: function(val) {
			this[shorthand] = val;
			return val;
		}
	});
});


/***/ }),

/***/ "ZvEP":
/*!***********************************************************!*\
  !*** ./node_modules/react-tabs/esm/components/TabList.js ***!
  \***********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TabList; });
/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! prop-types */ "17x9");
/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(prop_types__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "q1tI");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! classnames */ "TSYQ");
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(classnames__WEBPACK_IMPORTED_MODULE_2__);
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }





var TabList =
/*#__PURE__*/
function (_Component) {
  _inheritsLoose(TabList, _Component);

  function TabList() {
    return _Component.apply(this, arguments) || this;
  }

  var _proto = TabList.prototype;

  _proto.render = function render() {
    var _this$props = this.props,
        children = _this$props.children,
        className = _this$props.className,
        attributes = _objectWithoutPropertiesLoose(_this$props, ["children", "className"]);

    return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("ul", _extends({}, attributes, {
      className: classnames__WEBPACK_IMPORTED_MODULE_2___default()(className),
      role: "tablist"
    }), children);
  };

  return TabList;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]);

TabList.defaultProps = {
  className: 'react-tabs__tab-list'
};

TabList.propTypes =  true ? {
  children: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.object, prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.array]),
  className: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.array, prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.object])
} : undefined;
TabList.tabsRole = 'TabList';

/***/ }),

/***/ "Zxgi":
/*!*************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_wks-define.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var global = __webpack_require__(/*! ./_global */ "5T2Y");
var core = __webpack_require__(/*! ./_core */ "WEpk");
var LIBRARY = __webpack_require__(/*! ./_library */ "uOPS");
var wksExt = __webpack_require__(/*! ./_wks-ext */ "zLkG");
var defineProperty = __webpack_require__(/*! ./_object-dp */ "2faE").f;
module.exports = function (name) {
  var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
  if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) });
};


/***/ }),

/***/ "ZyGS":
/*!****************************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/stringifier.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var defaultRaw = {
    colon: ': ',
    indent: '    ',
    beforeDecl: '\n',
    beforeRule: '\n',
    beforeOpen: ' ',
    beforeClose: '\n',
    beforeComment: '\n',
    after: '\n',
    emptyBody: '',
    commentLeft: ' ',
    commentRight: ' '
};

function capitalize(str) {
    return str[0].toUpperCase() + str.slice(1);
}

var Stringifier = function () {
    function Stringifier(builder) {
        _classCallCheck(this, Stringifier);

        this.builder = builder;
    }

    Stringifier.prototype.stringify = function stringify(node, semicolon) {
        this[node.type](node, semicolon);
    };

    Stringifier.prototype.root = function root(node) {
        this.body(node);
        if (node.raws.after) this.builder(node.raws.after);
    };

    Stringifier.prototype.comment = function comment(node) {
        var left = this.raw(node, 'left', 'commentLeft');
        var right = this.raw(node, 'right', 'commentRight');
        this.builder('/*' + left + node.text + right + '*/', node);
    };

    Stringifier.prototype.decl = function decl(node, semicolon) {
        var between = this.raw(node, 'between', 'colon');
        var string = node.prop + between + this.rawValue(node, 'value');

        if (node.important) {
            string += node.raws.important || ' !important';
        }

        if (semicolon) string += ';';
        this.builder(string, node);
    };

    Stringifier.prototype.rule = function rule(node) {
        this.block(node, this.rawValue(node, 'selector'));
        if (node.raws.ownSemicolon) {
            this.builder(node.raws.ownSemicolon, node, 'end');
        }
    };

    Stringifier.prototype.atrule = function atrule(node, semicolon) {
        var name = '@' + node.name;
        var params = node.params ? this.rawValue(node, 'params') : '';

        if (typeof node.raws.afterName !== 'undefined') {
            name += node.raws.afterName;
        } else if (params) {
            name += ' ';
        }

        if (node.nodes) {
            this.block(node, name + params);
        } else {
            var end = (node.raws.between || '') + (semicolon ? ';' : '');
            this.builder(name + params + end, node);
        }
    };

    Stringifier.prototype.body = function body(node) {
        var last = node.nodes.length - 1;
        while (last > 0) {
            if (node.nodes[last].type !== 'comment') break;
            last -= 1;
        }

        var semicolon = this.raw(node, 'semicolon');
        for (var i = 0; i < node.nodes.length; i++) {
            var child = node.nodes[i];
            var before = this.raw(child, 'before');
            if (before) this.builder(before);
            this.stringify(child, last !== i || semicolon);
        }
    };

    Stringifier.prototype.block = function block(node, start) {
        var between = this.raw(node, 'between', 'beforeOpen');
        this.builder(start + between + '{', node, 'start');

        var after = void 0;
        if (node.nodes && node.nodes.length) {
            this.body(node);
            after = this.raw(node, 'after');
        } else {
            after = this.raw(node, 'after', 'emptyBody');
        }

        if (after) this.builder(after);
        this.builder('}', node, 'end');
    };

    Stringifier.prototype.raw = function raw(node, own, detect) {
        var value = void 0;
        if (!detect) detect = own;

        // Already had
        if (own) {
            value = node.raws[own];
            if (typeof value !== 'undefined') return value;
        }

        var parent = node.parent;

        // Hack for first rule in CSS
        if (detect === 'before') {
            if (!parent || parent.type === 'root' && parent.first === node) {
                return '';
            }
        }

        // Floating child without parent
        if (!parent) return defaultRaw[detect];

        // Detect style by other nodes
        var root = node.root();
        if (!root.rawCache) root.rawCache = {};
        if (typeof root.rawCache[detect] !== 'undefined') {
            return root.rawCache[detect];
        }

        if (detect === 'before' || detect === 'after') {
            return this.beforeAfter(node, detect);
        } else {
            var method = 'raw' + capitalize(detect);
            if (this[method]) {
                value = this[method](root, node);
            } else {
                root.walk(function (i) {
                    value = i.raws[own];
                    if (typeof value !== 'undefined') return false;
                });
            }
        }

        if (typeof value === 'undefined') value = defaultRaw[detect];

        root.rawCache[detect] = value;
        return value;
    };

    Stringifier.prototype.rawSemicolon = function rawSemicolon(root) {
        var value = void 0;
        root.walk(function (i) {
            if (i.nodes && i.nodes.length && i.last.type === 'decl') {
                value = i.raws.semicolon;
                if (typeof value !== 'undefined') return false;
            }
        });
        return value;
    };

    Stringifier.prototype.rawEmptyBody = function rawEmptyBody(root) {
        var value = void 0;
        root.walk(function (i) {
            if (i.nodes && i.nodes.length === 0) {
                value = i.raws.after;
                if (typeof value !== 'undefined') return false;
            }
        });
        return value;
    };

    Stringifier.prototype.rawIndent = function rawIndent(root) {
        if (root.raws.indent) return root.raws.indent;
        var value = void 0;
        root.walk(function (i) {
            var p = i.parent;
            if (p && p !== root && p.parent && p.parent === root) {
                if (typeof i.raws.before !== 'undefined') {
                    var parts = i.raws.before.split('\n');
                    value = parts[parts.length - 1];
                    value = value.replace(/[^\s]/g, '');
                    return false;
                }
            }
        });
        return value;
    };

    Stringifier.prototype.rawBeforeComment = function rawBeforeComment(root, node) {
        var value = void 0;
        root.walkComments(function (i) {
            if (typeof i.raws.before !== 'undefined') {
                value = i.raws.before;
                if (value.indexOf('\n') !== -1) {
                    value = value.replace(/[^\n]+$/, '');
                }
                return false;
            }
        });
        if (typeof value === 'undefined') {
            value = this.raw(node, null, 'beforeDecl');
        } else if (value) {
            value = value.replace(/[^\s]/g, '');
        }
        return value;
    };

    Stringifier.prototype.rawBeforeDecl = function rawBeforeDecl(root, node) {
        var value = void 0;
        root.walkDecls(function (i) {
            if (typeof i.raws.before !== 'undefined') {
                value = i.raws.before;
                if (value.indexOf('\n') !== -1) {
                    value = value.replace(/[^\n]+$/, '');
                }
                return false;
            }
        });
        if (typeof value === 'undefined') {
            value = this.raw(node, null, 'beforeRule');
        } else if (value) {
            value = value.replace(/[^\s]/g, '');
        }
        return value;
    };

    Stringifier.prototype.rawBeforeRule = function rawBeforeRule(root) {
        var value = void 0;
        root.walk(function (i) {
            if (i.nodes && (i.parent !== root || root.first !== i)) {
                if (typeof i.raws.before !== 'undefined') {
                    value = i.raws.before;
                    if (value.indexOf('\n') !== -1) {
                        value = value.replace(/[^\n]+$/, '');
                    }
                    return false;
                }
            }
        });
        if (value) value = value.replace(/[^\s]/g, '');
        return value;
    };

    Stringifier.prototype.rawBeforeClose = function rawBeforeClose(root) {
        var value = void 0;
        root.walk(function (i) {
            if (i.nodes && i.nodes.length > 0) {
                if (typeof i.raws.after !== 'undefined') {
                    value = i.raws.after;
                    if (value.indexOf('\n') !== -1) {
                        value = value.replace(/[^\n]+$/, '');
                    }
                    return false;
                }
            }
        });
        if (value) value = value.replace(/[^\s]/g, '');
        return value;
    };

    Stringifier.prototype.rawBeforeOpen = function rawBeforeOpen(root) {
        var value = void 0;
        root.walk(function (i) {
            if (i.type !== 'decl') {
                value = i.raws.between;
                if (typeof value !== 'undefined') return false;
            }
        });
        return value;
    };

    Stringifier.prototype.rawColon = function rawColon(root) {
        var value = void 0;
        root.walkDecls(function (i) {
            if (typeof i.raws.between !== 'undefined') {
                value = i.raws.between.replace(/[^\s:]/g, '');
                return false;
            }
        });
        return value;
    };

    Stringifier.prototype.beforeAfter = function beforeAfter(node, detect) {
        var value = void 0;
        if (node.type === 'decl') {
            value = this.raw(node, null, 'beforeDecl');
        } else if (node.type === 'comment') {
            value = this.raw(node, null, 'beforeComment');
        } else if (detect === 'before') {
            value = this.raw(node, null, 'beforeRule');
        } else {
            value = this.raw(node, null, 'beforeClose');
        }

        var buf = node.parent;
        var depth = 0;
        while (buf && buf.type !== 'root') {
            depth += 1;
            buf = buf.parent;
        }

        if (value.indexOf('\n') !== -1) {
            var indent = this.raw(node, null, 'indent');
            if (indent.length) {
                for (var step = 0; step < depth; step++) {
                    value += indent;
                }
            }
        }

        return value;
    };

    Stringifier.prototype.rawValue = function rawValue(node, prop) {
        var value = node[prop];
        var raw = node.raws[prop];
        if (raw && raw.value === value) {
            return raw.raw;
        } else {
            return value;
        }
    };

    return Stringifier;
}();

exports.default = Stringifier;
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64, 


/***/ }),

/***/ "a0eB":
/*!******************************************!*\
  !*** ./node_modules/array-uniq/index.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {

// there's 3 implementations written in increasing order of efficiency

// 1 - no Set type is defined
function uniqNoSet(arr) {
	var ret = [];

	for (var i = 0; i < arr.length; i++) {
		if (ret.indexOf(arr[i]) === -1) {
			ret.push(arr[i]);
		}
	}

	return ret;
}

// 2 - a simple Set type is defined
function uniqSet(arr) {
	var seen = new Set();
	return arr.filter(function (el) {
		if (!seen.has(el)) {
			seen.add(el);
			return true;
		}

		return false;
	});
}

// 3 - a standard Set type is defined and it has a forEach method
function uniqSetWithForEach(arr) {
	var ret = [];

	(new Set(arr)).forEach(function (el) {
		ret.push(el);
	});

	return ret;
}

// V8 currently has a broken implementation
// https://github.com/joyent/node/issues/8449
function doesForEachActuallyWork() {
	var ret = false;

	(new Set([true])).forEach(function (el) {
		ret = el;
	});

	return ret === true;
}

if ('Set' in global) {
	if (typeof Set.prototype.forEach === 'function' && doesForEachActuallyWork()) {
		module.exports = uniqSetWithForEach;
	} else {
		module.exports = uniqSet;
	}
} else {
	module.exports = uniqNoSet;
}

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "a0xu":
/*!******************************************************!*\
  !*** ./node_modules/core-js/library/modules/_cof.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

var toString = {}.toString;

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


/***/ }),

/***/ "a1E9":
/*!*****************************************************************!*\
  !*** ./node_modules/@jupyterlab/settingeditor/lib/inspector.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const inspector_1 = __webpack_require__(/*! @jupyterlab/inspector */ "vy9w");
const rendermime_1 = __webpack_require__(/*! @jupyterlab/rendermime */ "Towz");
/**
 * Create a raw editor inspector.
 */
function createInspector(editor, rendermime) {
    const connector = new InspectorConnector(editor);
    const inspector = new inspector_1.InspectorPanel();
    const handler = new inspector_1.InspectionHandler({
        connector,
        rendermime: rendermime ||
            new rendermime_1.RenderMimeRegistry({
                initialFactories: rendermime_1.standardRendererFactories
            })
    });
    inspector.add({
        className: 'jp-SettingsDebug',
        name: 'Debug',
        rank: 0,
        type: 'hints'
    });
    inspector.source = handler;
    handler.editor = editor.source;
    return inspector;
}
exports.createInspector = createInspector;
/**
 * The data connector used to populate a code inspector.
 *
 * #### Notes
 * This data connector debounces fetch requests to throttle them at no more than
 * one request per 100ms. This means that using the connector to populate
 * multiple client objects can lead to missed fetch responses.
 */
class InspectorConnector extends coreutils_1.DataConnector {
    constructor(editor) {
        super();
        this._current = 0;
        this._editor = editor;
    }
    /**
     * Fetch inspection requests.
     */
    fetch(request) {
        return new Promise(resolve => {
            // Debounce requests at a rate of 100ms.
            const current = (this._current = window.setTimeout(() => {
                if (current !== this._current) {
                    return resolve(null);
                }
                const errors = this._validate(request.text);
                if (!errors) {
                    return resolve(null);
                }
                resolve({ data: Private.render(errors), metadata: {} });
            }, 100));
        });
    }
    _validate(raw) {
        const editor = this._editor;
        const data = { composite: {}, user: {} };
        const id = editor.settings.plugin;
        const schema = editor.settings.schema;
        const validator = editor.registry.validator;
        return validator.validateData({ data, id, raw, schema }, false);
    }
}
/**
 * A namespace for private module data.
 */
var Private;
(function (Private) {
    /**
     * Render validation errors as an HTML string.
     */
    function render(errors) {
        return { 'text/markdown': errors.map(renderError).join('') };
    }
    Private.render = render;
    /**
     * Render an individual validation error as a markdown string.
     */
    function renderError(error) {
        switch (error.keyword) {
            case 'additionalProperties':
                return `**\`[additional property error]\`**
          \`${error.params.additionalProperty}\` is not a valid property`;
            case 'syntax':
                return `**\`[syntax error]\`** *${error.message}*`;
            case 'type':
                return `**\`[type error]\`**
          \`${error.dataPath}\` ${error.message}`;
            default:
                return `**\`[error]\`** *${error.message}*`;
        }
    }
})(Private || (Private = {}));


/***/ }),

/***/ "a3Vw":
/*!*******************************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/text_editors/RichText/LinkDecorator.js ***!
  \*******************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/*
 * A DecoratorComponent is used by `draft-js` to render rich content
 *  beyond inline styles. This Decorator renders LINK entities.
 *
 * See
 * https://facebook.github.io/draft-js/docs/advanced-topics-decorators.html#decorator-components
 */

var LinkDecorator = function LinkDecorator(props) {
  return _react2.default.createElement(
    'a',
    { href: '#', style: props.style },
    props.children
  );
};

LinkDecorator.propTypes = {
  style: _propTypes2.default.object.isRequired,
  children: _propTypes2.default.oneOfType([_propTypes2.default.array, _propTypes2.default.element]).isRequired
};

exports.default = LinkDecorator;
//# sourceMappingURL=LinkDecorator.js.map

/***/ }),

/***/ "a3kb":
/*!************************************************!*\
  !*** ./node_modules/mdi-react/DownloadIcon.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var DownloadIcon = function DownloadIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M5,20H19V18H5M19,9H15V3H9V9H5L12,16L19,9Z' })
  );
};

module.exports = DownloadIcon;


/***/ }),

/***/ "a9J7":
/*!***********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/VisibilitySelect.js ***!
  \***********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UnconnectedVisibilitySelect = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _constants = __webpack_require__(/*! ../../lib/constants */ "5Bkx");

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _Radio = __webpack_require__(/*! ./Radio */ "5Riz");

var _Radio2 = _interopRequireDefault(_Radio);

var _Dropdown = __webpack_require__(/*! ./Dropdown */ "dRXW");

var _Dropdown2 = _interopRequireDefault(_Dropdown);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UnconnectedVisibilitySelect = exports.UnconnectedVisibilitySelect = function (_Component) {
  _inherits(UnconnectedVisibilitySelect, _Component);

  function UnconnectedVisibilitySelect(props, context) {
    _classCallCheck(this, UnconnectedVisibilitySelect);

    var _this = _possibleConstructorReturn(this, (UnconnectedVisibilitySelect.__proto__ || Object.getPrototypeOf(UnconnectedVisibilitySelect)).call(this, props, context));

    _this.setMode = _this.setMode.bind(_this);
    _this.setLocals = _this.setLocals.bind(_this);

    _this.setLocals(props);
    return _this;
  }

  _createClass(UnconnectedVisibilitySelect, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(props) {
      this.setLocals(props);
    }
  }, {
    key: 'setLocals',
    value: function setLocals(props) {
      this.mode = props.fullValue === undefined || props.fullValue === _constants.MULTI_VALUED_PLACEHOLDER // eslint-disable-line no-undefined
      ? this.props.defaultOpt : props.fullValue;
    }
  }, {
    key: 'setMode',
    value: function setMode(mode) {
      this.props.updateContainer(_defineProperty({}, this.props.attr, mode));
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          dropdown = _props.dropdown,
          clearable = _props.clearable,
          options = _props.options,
          showOn = _props.showOn,
          attr = _props.attr,
          label = _props.label;


      return _react2.default.createElement(
        _react.Fragment,
        null,
        dropdown ? _react2.default.createElement(_Dropdown2.default, {
          attr: attr,
          label: label,
          options: options,
          fullValue: this.mode,
          updatePlot: this.setMode,
          clearable: clearable
        }) : _react2.default.createElement(_Radio2.default, {
          attr: attr,
          label: label,
          options: options,
          fullValue: this.mode,
          updatePlot: this.setMode
        }),
        Array.isArray(showOn) && showOn.includes(this.mode) || this.mode === showOn ? this.props.children : null
      );
    }
  }]);

  return UnconnectedVisibilitySelect;
}(_react.Component);

UnconnectedVisibilitySelect.propTypes = _extends({
  fullValue: _propTypes2.default.any,
  updatePlot: _propTypes2.default.func,
  dropdown: _propTypes2.default.bool,
  clearable: _propTypes2.default.bool,
  showOn: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.bool, _propTypes2.default.string, _propTypes2.default.array]),
  defaultOpt: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.bool, _propTypes2.default.string]),
  label: _propTypes2.default.string,
  attr: _propTypes2.default.string
}, _Field2.default.propTypes);

UnconnectedVisibilitySelect.contextTypes = {
  updateContainer: _propTypes2.default.func
};

exports.default = (0, _lib.connectToContainer)(UnconnectedVisibilitySelect);
//# sourceMappingURL=VisibilitySelect.js.map

/***/ }),

/***/ "aD8L":
/*!*************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotStackedAreaIcon.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotStackedAreaIcon = function PlotStackedAreaIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M14.688 22.688L0 17.313v9.375h32v-5.375l-8-3.938zM24 8l-9.313 5.375L-.001 5.312v9.313L14.687 20 24 14.687l8 4v-6.75z' })
    );
};

exports.default = PlotStackedAreaIcon;

/***/ }),

/***/ "aET+":
/*!****************************************************!*\
  !*** ./node_modules/style-loader/lib/addStyles.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

var stylesInDom = {};

var	memoize = function (fn) {
	var memo;

	return function () {
		if (typeof memo === "undefined") memo = fn.apply(this, arguments);
		return memo;
	};
};

var isOldIE = memoize(function () {
	// 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
	return window && document && document.all && !window.atob;
});

var getTarget = function (target) {
  return document.querySelector(target);
};

var getElement = (function (fn) {
	var memo = {};

	return function(target) {
                // If passing function in options, then use it for resolve "head" element.
                // Useful for Shadow Root style i.e
                // {
                //   insertInto: function () { return document.querySelector("#foo").shadowRoot }
                // }
                if (typeof target === 'function') {
                        return target();
                }
                if (typeof memo[target] === "undefined") {
			var styleTarget = getTarget.call(this, 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) {
					styleTarget = null;
				}
			}
			memo[target] = styleTarget;
		}
		return memo[target]
	};
})();

var singleton = null;
var	singletonCounter = 0;
var	stylesInsertedAtTop = [];

var	fixUrls = __webpack_require__(/*! ./urls */ "9tPo");

module.exports = function(list, options) {
	if (typeof DEBUG !== "undefined" && DEBUG) {
		if (typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment");
	}

	options = options || {};

	options.attrs = typeof options.attrs === "object" ? options.attrs : {};

	// 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();

	// By default, add <style> tags to the <head> element
        if (!options.insertInto) options.insertInto = "head";

	// By default, add <style> tags to the bottom of the target
	if (!options.insertAt) options.insertAt = "bottom";

	var styles = listToStyles(list, options);

	addStylesToDom(styles, options);

	return function update (newList) {
		var mayRemove = [];

		for (var i = 0; i < styles.length; i++) {
			var item = styles[i];
			var domStyle = stylesInDom[item.id];

			domStyle.refs--;
			mayRemove.push(domStyle);
		}

		if(newList) {
			var newStyles = listToStyles(newList, options);
			addStylesToDom(newStyles, options);
		}

		for (var i = 0; i < mayRemove.length; i++) {
			var domStyle = mayRemove[i];

			if(domStyle.refs === 0) {
				for (var j = 0; j < domStyle.parts.length; j++) domStyle.parts[j]();

				delete stylesInDom[domStyle.id];
			}
		}
	};
};

function addStylesToDom (styles, options) {
	for (var i = 0; i < styles.length; i++) {
		var item = styles[i];
		var domStyle = stylesInDom[item.id];

		if(domStyle) {
			domStyle.refs++;

			for(var j = 0; j < domStyle.parts.length; j++) {
				domStyle.parts[j](item.parts[j]);
			}

			for(; j < item.parts.length; j++) {
				domStyle.parts.push(addStyle(item.parts[j], options));
			}
		} else {
			var parts = [];

			for(var j = 0; j < item.parts.length; j++) {
				parts.push(addStyle(item.parts[j], options));
			}

			stylesInDom[item.id] = {id: item.id, refs: 1, parts: parts};
		}
	}
}

function listToStyles (list, options) {
	var styles = [];
	var newStyles = {};

	for (var i = 0; i < list.length; i++) {
		var item = list[i];
		var id = options.base ? item[0] + options.base : item[0];
		var css = item[1];
		var media = item[2];
		var sourceMap = item[3];
		var part = {css: css, media: media, sourceMap: sourceMap};

		if(!newStyles[id]) styles.push(newStyles[id] = {id: id, parts: [part]});
		else newStyles[id].parts.push(part);
	}

	return styles;
}

function insertStyleElement (options, style) {
	var target = getElement(options.insertInto)

	if (!target) {
		throw new Error("Couldn't find a style target. This probably means that the value for the 'insertInto' parameter is invalid.");
	}

	var lastStyleElementInsertedAtTop = stylesInsertedAtTop[stylesInsertedAtTop.length - 1];

	if (options.insertAt === "top") {
		if (!lastStyleElementInsertedAtTop) {
			target.insertBefore(style, target.firstChild);
		} else if (lastStyleElementInsertedAtTop.nextSibling) {
			target.insertBefore(style, lastStyleElementInsertedAtTop.nextSibling);
		} else {
			target.appendChild(style);
		}
		stylesInsertedAtTop.push(style);
	} else if (options.insertAt === "bottom") {
		target.appendChild(style);
	} else if (typeof options.insertAt === "object" && options.insertAt.before) {
		var nextSibling = getElement(options.insertInto + " " + options.insertAt.before);
		target.insertBefore(style, nextSibling);
	} else {
		throw new Error("[Style Loader]\n\n Invalid value for parameter 'insertAt' ('options.insertAt') found.\n Must be 'top', 'bottom', or Object.\n (https://github.com/webpack-contrib/style-loader#insertat)\n");
	}
}

function removeStyleElement (style) {
	if (style.parentNode === null) return false;
	style.parentNode.removeChild(style);

	var idx = stylesInsertedAtTop.indexOf(style);
	if(idx >= 0) {
		stylesInsertedAtTop.splice(idx, 1);
	}
}

function createStyleElement (options) {
	var style = document.createElement("style");

	if(options.attrs.type === undefined) {
		options.attrs.type = "text/css";
	}

	addAttrs(style, options.attrs);
	insertStyleElement(options, style);

	return style;
}

function createLinkElement (options) {
	var link = document.createElement("link");

	if(options.attrs.type === undefined) {
		options.attrs.type = "text/css";
	}
	options.attrs.rel = "stylesheet";

	addAttrs(link, options.attrs);
	insertStyleElement(options, link);

	return link;
}

function addAttrs (el, attrs) {
	Object.keys(attrs).forEach(function (key) {
		el.setAttribute(key, attrs[key]);
	});
}

function addStyle (obj, options) {
	var style, update, remove, result;

	// If a transform function was defined, run it on the css
	if (options.transform && obj.css) {
	    result = options.transform(obj.css);

	    if (result) {
	    	// If transform returns a value, use that instead of the original css.
	    	// This allows running runtime transformations on the css.
	    	obj.css = result;
	    } else {
	    	// If the transform function returns a falsy value, don't add this css.
	    	// This allows conditional loading of css
	    	return function() {
	    		// noop
	    	};
	    }
	}

	if (options.singleton) {
		var styleIndex = singletonCounter++;

		style = singleton || (singleton = createStyleElement(options));

		update = applyToSingletonTag.bind(null, style, styleIndex, false);
		remove = applyToSingletonTag.bind(null, style, styleIndex, true);

	} else if (
		obj.sourceMap &&
		typeof URL === "function" &&
		typeof URL.createObjectURL === "function" &&
		typeof URL.revokeObjectURL === "function" &&
		typeof Blob === "function" &&
		typeof btoa === "function"
	) {
		style = createLinkElement(options);
		update = updateLink.bind(null, style, options);
		remove = function () {
			removeStyleElement(style);

			if(style.href) URL.revokeObjectURL(style.href);
		};
	} else {
		style = createStyleElement(options);
		update = applyToTag.bind(null, style);
		remove = function () {
			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();
		}
	};
}

var replaceText = (function () {
	var textStore = [];

	return function (index, replacement) {
		textStore[index] = replacement;

		return textStore.filter(Boolean).join('\n');
	};
})();

function applyToSingletonTag (style, index, remove, obj) {
	var css = remove ? "" : obj.css;

	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, obj) {
	var css = obj.css;
	var media = obj.media;

	if(media) {
		style.setAttribute("media", media)
	}

	if(style.styleSheet) {
		style.styleSheet.cssText = css;
	} else {
		while(style.firstChild) {
			style.removeChild(style.firstChild);
		}

		style.appendChild(document.createTextNode(css));
	}
}

function updateLink (link, options, obj) {
	var css = obj.css;
	var sourceMap = obj.sourceMap;

	/*
		If convertToAbsoluteUrls isn't defined, but sourcemaps are enabled
		and there is no publicPath defined then lets turn convertToAbsoluteUrls
		on by default.  Otherwise default to the convertToAbsoluteUrls option
		directly
	*/
	var autoFixUrls = options.convertToAbsoluteUrls === undefined && sourceMap;

	if (options.convertToAbsoluteUrls || autoFixUrls) {
		css = fixUrls(css);
	}

	if (sourceMap) {
		// http://stackoverflow.com/a/26603875
		css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */";
	}

	var blob = new Blob([css], { type: "text/css" });

	var oldSrc = link.href;

	link.href = URL.createObjectURL(blob);

	if(oldSrc) URL.revokeObjectURL(oldSrc);
}


/***/ }),

/***/ "aF6S":
/*!****************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeHistogramIcon.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeHistogramIcon = function TraceTypeHistogramIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement('path', { fill: 'none', d: 'M0 0h46v46H0z' }),
        _react2.default.createElement('path', { fill: '#1d9bfb', d: 'M7 20h8v20H7z' }),
        _react2.default.createElement('path', { fill: '#25fdfc', d: 'M32 28h8v12h-8zM15 16h9v24h-9z' }),
        _react2.default.createElement('path', { fill: '#1d9bfb', d: 'M24 20h8v20h-8z' })
    );
};

exports.default = TraceTypeHistogramIcon;

/***/ }),

/***/ "aIdf":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/br.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


function relativeTimeWithMutation(number, withoutSuffix, key) {
    var format = {
        'mm': 'munutenn',
        'MM': 'miz',
        'dd': 'devezh'
    };
    return number + ' ' + mutation(format[key], number);
}
function specialMutationForYears(number) {
    switch (lastNumber(number)) {
        case 1:
        case 3:
        case 4:
        case 5:
        case 9:
            return number + ' bloaz';
        default:
            return number + ' vloaz';
    }
}
function lastNumber(number) {
    if (number > 9) {
        return lastNumber(number % 10);
    }
    return number;
}
function mutation(text, number) {
    if (number === 2) {
        return softMutation(text);
    }
    return text;
}
function softMutation(text) {
    var mutationTable = {
        'm': 'v',
        'b': 'v',
        'd': 'z'
    };
    if (mutationTable[text.charAt(0)] === undefined) {
        return text;
    }
    return mutationTable[text.charAt(0)] + text.substring(1);
}

var br = moment.defineLocale('br', {
    months : 'Genver_C\'hwevrer_Meurzh_Ebrel_Mae_Mezheven_Gouere_Eost_Gwengolo_Here_Du_Kerzu'.split('_'),
    monthsShort : 'Gen_C\'hwe_Meu_Ebr_Mae_Eve_Gou_Eos_Gwe_Her_Du_Ker'.split('_'),
    weekdays : 'Sul_Lun_Meurzh_Merc\'her_Yaou_Gwener_Sadorn'.split('_'),
    weekdaysShort : 'Sul_Lun_Meu_Mer_Yao_Gwe_Sad'.split('_'),
    weekdaysMin : 'Su_Lu_Me_Mer_Ya_Gw_Sa'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'h[e]mm A',
        LTS : 'h[e]mm:ss A',
        L : 'DD/MM/YYYY',
        LL : 'D [a viz] MMMM YYYY',
        LLL : 'D [a viz] MMMM YYYY h[e]mm A',
        LLLL : 'dddd, D [a viz] MMMM YYYY h[e]mm A'
    },
    calendar : {
        sameDay : '[Hiziv da] LT',
        nextDay : '[Warc\'hoazh da] LT',
        nextWeek : 'dddd [da] LT',
        lastDay : '[Dec\'h da] LT',
        lastWeek : 'dddd [paset da] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'a-benn %s',
        past : '%s \'zo',
        s : 'un nebeud segondennoù',
        ss : '%d eilenn',
        m : 'ur vunutenn',
        mm : relativeTimeWithMutation,
        h : 'un eur',
        hh : '%d eur',
        d : 'un devezh',
        dd : relativeTimeWithMutation,
        M : 'ur miz',
        MM : relativeTimeWithMutation,
        y : 'ur bloaz',
        yy : specialMutationForYears
    },
    dayOfMonthOrdinalParse: /\d{1,2}(añ|vet)/,
    ordinal : function (number) {
        var output = (number === 1) ? 'añ' : 'vet';
        return number + output;
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return br;

})));


/***/ }),

/***/ "aIsn":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/mi.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var mi = moment.defineLocale('mi', {
    months: 'Kohi-tāte_Hui-tanguru_Poutū-te-rangi_Paenga-whāwhā_Haratua_Pipiri_Hōngoingoi_Here-turi-kōkā_Mahuru_Whiringa-ā-nuku_Whiringa-ā-rangi_Hakihea'.split('_'),
    monthsShort: 'Kohi_Hui_Pou_Pae_Hara_Pipi_Hōngoi_Here_Mahu_Whi-nu_Whi-ra_Haki'.split('_'),
    monthsRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i,
    monthsStrictRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i,
    monthsShortRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i,
    monthsShortStrictRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,2}/i,
    weekdays: 'Rātapu_Mane_Tūrei_Wenerei_Tāite_Paraire_Hātarei'.split('_'),
    weekdaysShort: 'Ta_Ma_Tū_We_Tāi_Pa_Hā'.split('_'),
    weekdaysMin: 'Ta_Ma_Tū_We_Tāi_Pa_Hā'.split('_'),
    longDateFormat: {
        LT: 'HH:mm',
        LTS: 'HH:mm:ss',
        L: 'DD/MM/YYYY',
        LL: 'D MMMM YYYY',
        LLL: 'D MMMM YYYY [i] HH:mm',
        LLLL: 'dddd, D MMMM YYYY [i] HH:mm'
    },
    calendar: {
        sameDay: '[i teie mahana, i] LT',
        nextDay: '[apopo i] LT',
        nextWeek: 'dddd [i] LT',
        lastDay: '[inanahi i] LT',
        lastWeek: 'dddd [whakamutunga i] LT',
        sameElse: 'L'
    },
    relativeTime: {
        future: 'i roto i %s',
        past: '%s i mua',
        s: 'te hēkona ruarua',
        ss: '%d hēkona',
        m: 'he meneti',
        mm: '%d meneti',
        h: 'te haora',
        hh: '%d haora',
        d: 'he ra',
        dd: '%d ra',
        M: 'he marama',
        MM: '%d marama',
        y: 'he tau',
        yy: '%d tau'
    },
    dayOfMonthOrdinalParse: /\d{1,2}º/,
    ordinal: '%dº',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return mi;

})));


/***/ }),

/***/ "aJvD":
/*!***************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/rendermime/style/index.css ***!
  \***************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n/*-----------------------------------------------------------------------------\n| RenderedText\n|----------------------------------------------------------------------------*/\n\n.jp-RenderedText {\n  text-align: left;\n  padding-left: var(--jp-code-padding);\n  font-size: var(--jp-code-font-size);\n  line-height: var(--jp-code-line-height);\n  font-family: var(--jp-code-font-family);\n}\n\n.jp-RenderedText pre,\n.jp-RenderedJavaScript pre,\n.jp-RenderedHTMLCommon pre {\n  color: var(--jp-content-font-color1);\n  border: none;\n  margin: 0px;\n  padding: 0px;\n}\n\n/* ansi_up creates classed spans for console foregrounds and backgrounds. */\n.jp-RenderedText pre .ansi-black-fg {\n  color: #3e424d;\n}\n.jp-RenderedText pre .ansi-red-fg {\n  color: #e75c58;\n}\n.jp-RenderedText pre .ansi-green-fg {\n  color: #00a250;\n}\n.jp-RenderedText pre .ansi-yellow-fg {\n  color: #ddb62b;\n}\n.jp-RenderedText pre .ansi-blue-fg {\n  color: #208ffb;\n}\n.jp-RenderedText pre .ansi-magenta-fg {\n  color: #d160c4;\n}\n.jp-RenderedText pre .ansi-cyan-fg {\n  color: #60c6c8;\n}\n.jp-RenderedText pre .ansi-white-fg {\n  color: #c5c1b4;\n}\n\n.jp-RenderedText pre .ansi-black-bg {\n  background-color: #3e424d;\n}\n.jp-RenderedText pre .ansi-red-bg {\n  background-color: #e75c58;\n}\n.jp-RenderedText pre .ansi-green-bg {\n  background-color: #00a250;\n}\n.jp-RenderedText pre .ansi-yellow-bg {\n  background-color: #ddb62b;\n}\n.jp-RenderedText pre .ansi-blue-bg {\n  background-color: #208ffb;\n}\n.jp-RenderedText pre .ansi-magenta-bg {\n  background-color: #d160c4;\n}\n.jp-RenderedText pre .ansi-cyan-bg {\n  background-color: #60c6c8;\n}\n.jp-RenderedText pre .ansi-white-bg {\n  background-color: #c5c1b4;\n}\n\n.jp-RenderedText pre .ansi-bright-black-fg {\n  color: #282c36;\n}\n.jp-RenderedText pre .ansi-bright-red-fg {\n  color: #b22b31;\n}\n.jp-RenderedText pre .ansi-bright-green-fg {\n  color: #007427;\n}\n.jp-RenderedText pre .ansi-bright-yellow-fg {\n  color: #b27d12;\n}\n.jp-RenderedText pre .ansi-bright-blue-fg {\n  color: #0065ca;\n}\n.jp-RenderedText pre .ansi-bright-magenta-fg {\n  color: #a03196;\n}\n.jp-RenderedText pre .ansi-bright-cyan-fg {\n  color: #258f8f;\n}\n.jp-RenderedText pre .ansi-bright-white-fg {\n  color: #a1a6b2;\n}\n\n.jp-RenderedText pre .ansi-bright-black-bg {\n  background-color: #282c36;\n}\n.jp-RenderedText pre .ansi-bright-red-bg {\n  background-color: #b22b31;\n}\n.jp-RenderedText pre .ansi-bright-green-bg {\n  background-color: #007427;\n}\n.jp-RenderedText pre .ansi-bright-yellow-bg {\n  background-color: #b27d12;\n}\n.jp-RenderedText pre .ansi-bright-blue-bg {\n  background-color: #0065ca;\n}\n.jp-RenderedText pre .ansi-bright-magenta-bg {\n  background-color: #a03196;\n}\n.jp-RenderedText pre .ansi-bright-cyan-bg {\n  background-color: #258f8f;\n}\n.jp-RenderedText pre .ansi-bright-white-bg {\n  background-color: #a1a6b2;\n}\n\n.jp-RenderedText[data-mime-type='application/vnd.jupyter.stderr'] {\n  background: var(--jp-rendermime-error-background);\n  padding-top: var(--jp-code-padding);\n}\n\n/*-----------------------------------------------------------------------------\n| RenderedLatex\n|----------------------------------------------------------------------------*/\n\n.jp-RenderedLatex {\n  color: var(--jp-content-font-color1);\n  font-size: var(--jp-content-font-size1);\n  line-height: var(--jp-content-line-height);\n}\n\n/* Left-justify outputs.*/\n.jp-OutputArea-output.jp-RenderedLatex {\n  text-align: left;\n}\n\n/*-----------------------------------------------------------------------------\n| RenderedHTML\n|----------------------------------------------------------------------------*/\n\n.jp-RenderedHTMLCommon {\n  color: var(--jp-content-font-color1);\n  font-family: var(--jp-content-font-family);\n  font-size: var(--jp-content-font-size1);\n  line-height: var(--jp-content-line-height);\n  /* Give a bit more R padding on Markdown text to keep line lengths reasonable */\n  padding-right: 20px;\n}\n\n.jp-RenderedHTMLCommon em {\n  font-style: italic;\n}\n\n.jp-RenderedHTMLCommon strong {\n  font-weight: bold;\n}\n\n.jp-RenderedHTMLCommon u {\n  text-decoration: underline;\n}\n\n.jp-RenderedHTMLCommon a:link {\n  text-decoration: none;\n  color: var(--jp-content-link-color);\n}\n\n.jp-RenderedHTMLCommon a:hover {\n  text-decoration: underline;\n  color: var(--jp-content-link-color);\n}\n\n.jp-RenderedHTMLCommon a:visited {\n  text-decoration: none;\n  color: var(--jp-content-link-color);\n}\n\n/* Headings */\n\n.jp-RenderedHTMLCommon h1,\n.jp-RenderedHTMLCommon h2,\n.jp-RenderedHTMLCommon h3,\n.jp-RenderedHTMLCommon h4,\n.jp-RenderedHTMLCommon h5,\n.jp-RenderedHTMLCommon h6 {\n  line-height: var(--jp-content-heading-line-height);\n  font-weight: var(--jp-content-heading-font-weight);\n  font-style: normal;\n  margin: var(--jp-content-heading-margin-top) 0\n    var(--jp-content-heading-margin-bottom) 0;\n}\n\n.jp-RenderedHTMLCommon h1:first-child,\n.jp-RenderedHTMLCommon h2:first-child,\n.jp-RenderedHTMLCommon h3:first-child,\n.jp-RenderedHTMLCommon h4:first-child,\n.jp-RenderedHTMLCommon h5:first-child,\n.jp-RenderedHTMLCommon h6:first-child {\n  margin-top: calc(0.5 * var(--jp-content-heading-margin-top));\n}\n\n.jp-RenderedHTMLCommon h1:last-child,\n.jp-RenderedHTMLCommon h2:last-child,\n.jp-RenderedHTMLCommon h3:last-child,\n.jp-RenderedHTMLCommon h4:last-child,\n.jp-RenderedHTMLCommon h5:last-child,\n.jp-RenderedHTMLCommon h6:last-child {\n  margin-bottom: calc(0.5 * var(--jp-content-heading-margin-bottom));\n}\n\n.jp-RenderedHTMLCommon h1 {\n  font-size: var(--jp-content-font-size5);\n}\n\n.jp-RenderedHTMLCommon h2 {\n  font-size: var(--jp-content-font-size4);\n}\n\n.jp-RenderedHTMLCommon h3 {\n  font-size: var(--jp-content-font-size3);\n}\n\n.jp-RenderedHTMLCommon h4 {\n  font-size: var(--jp-content-font-size2);\n}\n\n.jp-RenderedHTMLCommon h5 {\n  font-size: var(--jp-content-font-size1);\n}\n\n.jp-RenderedHTMLCommon h6 {\n  font-size: var(--jp-content-font-size0);\n}\n\n/* Lists */\n\n.jp-RenderedHTMLCommon ul:not(.list-inline),\n.jp-RenderedHTMLCommon ol:not(.list-inline) {\n  padding-left: 2em;\n}\n\n.jp-RenderedHTMLCommon ul {\n  list-style: disc;\n}\n\n.jp-RenderedHTMLCommon ul ul {\n  list-style: square;\n}\n\n.jp-RenderedHTMLCommon ul ul ul {\n  list-style: circle;\n}\n\n.jp-RenderedHTMLCommon ol {\n  list-style: decimal;\n}\n\n.jp-RenderedHTMLCommon ol ol {\n  list-style: upper-alpha;\n}\n\n.jp-RenderedHTMLCommon ol ol ol {\n  list-style: lower-alpha;\n}\n\n.jp-RenderedHTMLCommon ol ol ol ol {\n  list-style: lower-roman;\n}\n\n.jp-RenderedHTMLCommon ol ol ol ol ol {\n  list-style: decimal;\n}\n\n.jp-RenderedHTMLCommon ol,\n.jp-RenderedHTMLCommon ul {\n  margin-bottom: 1em;\n}\n\n.jp-RenderedHTMLCommon ul ul,\n.jp-RenderedHTMLCommon ul ol,\n.jp-RenderedHTMLCommon ol ul,\n.jp-RenderedHTMLCommon ol ol {\n  margin-bottom: 0em;\n}\n\n.jp-RenderedHTMLCommon hr {\n  color: var(--jp-border-color2);\n  background-color: var(--jp-border-color1);\n  margin-top: 1em;\n  margin-bottom: 1em;\n}\n\n.jp-RenderedHTMLCommon > pre {\n  margin: 1.5em 2em;\n}\n\n.jp-RenderedHTMLCommon pre,\n.jp-RenderedHTMLCommon code {\n  border: 0;\n  background-color: var(--jp-layout-color0);\n  color: var(--jp-content-font-color1);\n  font-family: var(--jp-code-font-family);\n  font-size: inherit;\n  line-height: var(--jp-code-line-height);\n  padding: 0;\n}\n\n.jp-RenderedHTMLCommon p > code {\n  background-color: var(--jp-layout-color2);\n  padding: 1px 5px;\n}\n\n/* Tables */\n\n.jp-RenderedHTMLCommon table {\n  border-collapse: collapse;\n  border-spacing: 0;\n  border: none;\n  color: var(--jp-ui-font-color1);\n  font-size: 12px;\n  table-layout: fixed;\n  margin-left: auto;\n  margin-right: auto;\n}\n\n.jp-RenderedHTMLCommon thead {\n  border-bottom: var(--jp-border-width) solid var(--jp-border-color1);\n  vertical-align: bottom;\n}\n\n.jp-RenderedHTMLCommon td,\n.jp-RenderedHTMLCommon th,\n.jp-RenderedHTMLCommon tr {\n  vertical-align: middle;\n  padding: 0.5em 0.5em;\n  line-height: normal;\n  white-space: normal;\n  max-width: none;\n  border: none;\n}\n\n.jp-RenderedMarkdown.jp-RenderedHTMLCommon td,\n.jp-RenderedMarkdown.jp-RenderedHTMLCommon th {\n  max-width: none;\n}\n\n:not(.jp-RenderedMarkdown).jp-RenderedHTMLCommon td,\n:not(.jp-RenderedMarkdown).jp-RenderedHTMLCommon th,\n:not(.jp-RenderedMarkdown).jp-RenderedHTMLCommon tr {\n  text-align: right;\n}\n\n.jp-RenderedHTMLCommon th {\n  font-weight: bold;\n}\n\n.jp-RenderedHTMLCommon tbody tr:nth-child(odd) {\n  background: var(--jp-layout-color0);\n}\n\n.jp-RenderedHTMLCommon tbody tr:nth-child(even) {\n  background: var(--jp-rendermime-table-row-background);\n}\n\n.jp-RenderedHTMLCommon tbody tr:hover {\n  background: var(--jp-rendermime-table-row-hover-background);\n}\n\n.jp-RenderedHTMLCommon table {\n  margin-bottom: 1em;\n}\n\n.jp-RenderedHTMLCommon p {\n  text-align: left;\n  margin: 0px;\n}\n\n.jp-RenderedHTMLCommon p {\n  margin-bottom: 1em;\n}\n\n.jp-RenderedHTMLCommon img {\n  -moz-force-broken-image-icon: 1;\n}\n\n/* Restrict to direct children as other images could be nested in other content. */\n.jp-RenderedHTMLCommon > img {\n  display: block;\n  margin-left: auto;\n  margin-right: auto;\n  margin-bottom: 1em;\n}\n\n/* Change color behind transparent images if they need it... */\n[data-theme-light='false'] .jp-RenderedImage img.jp-needs-light-background {\n  background-color: var(--jp-inverse-layout-color1);\n}\n[data-theme-light='true'] .jp-RenderedImage img.jp-needs-dark-background {\n  background-color: var(--jp-inverse-layout-color1);\n}\n/* ...or leave it untouched if they don't */\n[data-theme-light='false'] .jp-RenderedImage img.jp-needs-dark-background {\n}\n[data-theme-light='true'] .jp-RenderedImage img.jp-needs-light-background {\n}\n\n.jp-RenderedHTMLCommon img,\n.jp-RenderedImage img,\n.jp-RenderedHTMLCommon svg,\n.jp-RenderedSVG svg {\n  max-width: 100%;\n  height: auto;\n}\n\n.jp-RenderedHTMLCommon img.jp-mod-unconfined,\n.jp-RenderedImage img.jp-mod-unconfined,\n.jp-RenderedHTMLCommon svg.jp-mod-unconfined,\n.jp-RenderedSVG svg.jp-mod-unconfined {\n  max-width: none;\n}\n\n.jp-RenderedHTMLCommon .alert {\n  margin-bottom: 1em;\n}\n\n.jp-RenderedHTMLCommon blockquote {\n  margin: 1em 2em;\n  padding: 0 1em;\n  border-left: 5px solid var(--jp-border-color2);\n}\n\na.jp-InternalAnchorLink {\n  visibility: hidden;\n  margin-left: 8px;\n  color: var(--md-blue-800);\n}\n\nh1:hover .jp-InternalAnchorLink,\nh2:hover .jp-InternalAnchorLink,\nh3:hover .jp-InternalAnchorLink,\nh4:hover .jp-InternalAnchorLink,\nh5:hover .jp-InternalAnchorLink,\nh6:hover .jp-InternalAnchorLink {\n  visibility: visible;\n}\n\n/* Most direct children of .jp-RenderedHTMLCommon have a margin-bottom of 1.0.\n * At the bottom of cells this is a bit too much as there is also spacing\n * between cells. Going all the way to 0 gets too tight between markdown and\n * code cells.\n */\n.jp-RenderedHTMLCommon > *:last-child {\n  margin-bottom: 0.5em;\n}\n\n/*-----------------------------------------------------------------------------\n| RenderedPDF\n|----------------------------------------------------------------------------*/\n\n.jp-RenderedPDF {\n  font-size: var(--jp-ui-font-size1);\n}\n", ""]);

// exports


/***/ }),

/***/ "aLRh":
/*!************************************************!*\
  !*** ./node_modules/domutils/lib/stringify.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var ElementType = __webpack_require__(/*! domelementtype */ "TR4g"),
    getOuterHTML = __webpack_require__(/*! dom-serializer */ "GIBT"),
    isTag = ElementType.isTag;

module.exports = {
	getInnerHTML: getInnerHTML,
	getOuterHTML: getOuterHTML,
	getText: getText
};

function getInnerHTML(elem, opts){
	return elem.children ? elem.children.map(function(elem){
		return getOuterHTML(elem, opts);
	}).join("") : "";
}

function getText(elem){
	if(Array.isArray(elem)) return elem.map(getText).join("");
	if(isTag(elem)) return elem.name === "br" ? "\n" : getText(elem.children);
	if(elem.type === ElementType.CDATA) return getText(elem.children);
	if(elem.type === ElementType.Text) return elem.data;
	return "";
}


/***/ }),

/***/ "aN65":
/*!*******************************************************************!*\
  !*** ./node_modules/@jupyterlab/extensionmanager/style/index.css ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "6805");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "aOxJ":
/*!************************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/comment.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _node = __webpack_require__(/*! ./node */ "wWcZ");

var _node2 = _interopRequireDefault(_node);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * Represents a comment between declarations or statements (rule and at-rules).
 *
 * Comments inside selectors, at-rule parameters, or declaration values
 * will be stored in the `raws` properties explained above.
 *
 * @extends Node
 */
var Comment = function (_Node) {
  _inherits(Comment, _Node);

  function Comment(defaults) {
    _classCallCheck(this, Comment);

    var _this = _possibleConstructorReturn(this, _Node.call(this, defaults));

    _this.type = 'comment';
    return _this;
  }

  /**
   * @memberof Comment#
   * @member {string} text - the comment’s text
   */

  /**
   * @memberof Comment#
   * @member {object} raws - Information to generate byte-to-byte equal
   *                         node string as it was in the origin input.
   *
   * Every parser saves its own properties,
   * but the default CSS parser uses:
   *
   * * `before`: the space symbols before the node.
   * * `left`: the space symbols between `/*` and the comment’s text.
   * * `right`: the space symbols between the comment’s text.
   */


  return Comment;
}(_node2.default);

exports.default = Comment;
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImNvbW1lbnQuZXM2Il0sIm5hbWVzIjpbIkNvbW1lbnQiLCJkZWZhdWx0cyIsInR5cGUiLCJOb2RlIl0sIm1hcHBpbmdzIjoiOzs7O0FBQUE7Ozs7Ozs7Ozs7OztBQUVBOzs7Ozs7OztJQVFNQSxPOzs7QUFFRixtQkFBWUMsUUFBWixFQUFzQjtBQUFBOztBQUFBLGlEQUNsQixpQkFBTUEsUUFBTixDQURrQjs7QUFFbEIsVUFBS0MsSUFBTCxHQUFZLFNBQVo7QUFGa0I7QUFHckI7O0FBRUQ7Ozs7O0FBS0E7Ozs7Ozs7Ozs7Ozs7OztFQVprQkMsYzs7a0JBMEJQSCxPIiwiZmlsZSI6ImNvbW1lbnQuanMiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgTm9kZSBmcm9tICcuL25vZGUnO1xuXG4vKipcbiAqIFJlcHJlc2VudHMgYSBjb21tZW50IGJldHdlZW4gZGVjbGFyYXRpb25zIG9yIHN0YXRlbWVudHMgKHJ1bGUgYW5kIGF0LXJ1bGVzKS5cbiAqXG4gKiBDb21tZW50cyBpbnNpZGUgc2VsZWN0b3JzLCBhdC1ydWxlIHBhcmFtZXRlcnMsIG9yIGRlY2xhcmF0aW9uIHZhbHVlc1xuICogd2lsbCBiZSBzdG9yZWQgaW4gdGhlIGByYXdzYCBwcm9wZXJ0aWVzIGV4cGxhaW5lZCBhYm92ZS5cbiAqXG4gKiBAZXh0ZW5kcyBOb2RlXG4gKi9cbmNsYXNzIENvbW1lbnQgZXh0ZW5kcyBOb2RlIHtcblxuICAgIGNvbnN0cnVjdG9yKGRlZmF1bHRzKSB7XG4gICAgICAgIHN1cGVyKGRlZmF1bHRzKTtcbiAgICAgICAgdGhpcy50eXBlID0gJ2NvbW1lbnQnO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIEBtZW1iZXJvZiBDb21tZW50I1xuICAgICAqIEBtZW1iZXIge3N0cmluZ30gdGV4dCAtIHRoZSBjb21tZW504oCZcyB0ZXh0XG4gICAgICovXG5cbiAgICAvKipcbiAgICAgKiBAbWVtYmVyb2YgQ29tbWVudCNcbiAgICAgKiBAbWVtYmVyIHtvYmplY3R9IHJhd3MgLSBJbmZvcm1hdGlvbiB0byBnZW5lcmF0ZSBieXRlLXRvLWJ5dGUgZXF1YWxcbiAgICAgKiAgICAgICAgICAgICAgICAgICAgICAgICBub2RlIHN0cmluZyBhcyBpdCB3YXMgaW4gdGhlIG9yaWdpbiBpbnB1dC5cbiAgICAgKlxuICAgICAqIEV2ZXJ5IHBhcnNlciBzYXZlcyBpdHMgb3duIHByb3BlcnRpZXMsXG4gICAgICogYnV0IHRoZSBkZWZhdWx0IENTUyBwYXJzZXIgdXNlczpcbiAgICAgKlxuICAgICAqICogYGJlZm9yZWA6IHRoZSBzcGFjZSBzeW1ib2xzIGJlZm9yZSB0aGUgbm9kZS5cbiAgICAgKiAqIGBsZWZ0YDogdGhlIHNwYWNlIHN5bWJvbHMgYmV0d2VlbiBgLypgIGFuZCB0aGUgY29tbWVudOKAmXMgdGV4dC5cbiAgICAgKiAqIGByaWdodGA6IHRoZSBzcGFjZSBzeW1ib2xzIGJldHdlZW4gdGhlIGNvbW1lbnTigJlzIHRleHQuXG4gICAgICovXG59XG5cbmV4cG9ydCBkZWZhdWx0IENvbW1lbnQ7XG4iXX0=


/***/ }),

/***/ "aQ04":
/*!****************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/application/style/index.css ***!
  \****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports
exports.i(__webpack_require__(/*! -!../../../css-loader!@phosphor/widgets/style/index.css */ "jfpi"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./datagrid.css */ "ZK8w"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./dockpanel.css */ "jizN"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./images.css */ "tr+V"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./icons.css */ "I+VJ"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./menus.css */ "3Drf"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./scrollbar.css */ "6C2Z"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./tabs.css */ "f1NE"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./buttons.css */ "zkAc"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./sidepanel.css */ "UlQ5"), "");

// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.p-Widget.p-mod-hidden {\n  display: none !important;\n}\n\nbody {\n  font-family: var(--jp-ui-font-family);\n  background: var(--jp-layout-color3);\n  margin: 0;\n  padding: 0;\n  overflow: hidden;\n}\n\n.jp-ApplicationShell {\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n}\n\n.jp-ApplicationShell.jp-mod-devMode {\n  border-top: 4px solid red;\n}\n\n#jp-main-dock-panel {\n  padding: 5px;\n}\n\n#jp-top-panel {\n  border-bottom: var(--jp-border-width) solid var(--jp-border-color0);\n  background: var(--jp-layout-color1);\n  display: flex;\n  min-height: var(--jp-private-menubar-height);\n}\n\n#jp-bottom-panel {\n  background: var(--jp-layout-color1);\n  display: flex;\n}\n\n/* Sibling imports */\n", ""]);

// exports


/***/ }),

/***/ "aQkU":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/mk.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var mk = moment.defineLocale('mk', {
    months : 'јануари_февруари_март_април_мај_јуни_јули_август_септември_октомври_ноември_декември'.split('_'),
    monthsShort : 'јан_фев_мар_апр_мај_јун_јул_авг_сеп_окт_ное_дек'.split('_'),
    weekdays : 'недела_понеделник_вторник_среда_четврток_петок_сабота'.split('_'),
    weekdaysShort : 'нед_пон_вто_сре_чет_пет_саб'.split('_'),
    weekdaysMin : 'нe_пo_вт_ср_че_пе_сa'.split('_'),
    longDateFormat : {
        LT : 'H:mm',
        LTS : 'H:mm:ss',
        L : 'D.MM.YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY H:mm',
        LLLL : 'dddd, D MMMM YYYY H:mm'
    },
    calendar : {
        sameDay : '[Денес во] LT',
        nextDay : '[Утре во] LT',
        nextWeek : '[Во] dddd [во] LT',
        lastDay : '[Вчера во] LT',
        lastWeek : function () {
            switch (this.day()) {
                case 0:
                case 3:
                case 6:
                    return '[Изминатата] dddd [во] LT';
                case 1:
                case 2:
                case 4:
                case 5:
                    return '[Изминатиот] dddd [во] LT';
            }
        },
        sameElse : 'L'
    },
    relativeTime : {
        future : 'после %s',
        past : 'пред %s',
        s : 'неколку секунди',
        ss : '%d секунди',
        m : 'минута',
        mm : '%d минути',
        h : 'час',
        hh : '%d часа',
        d : 'ден',
        dd : '%d дена',
        M : 'месец',
        MM : '%d месеци',
        y : 'година',
        yy : '%d години'
    },
    dayOfMonthOrdinalParse: /\d{1,2}-(ев|ен|ти|ви|ри|ми)/,
    ordinal : function (number) {
        var lastDigit = number % 10,
            last2Digits = number % 100;
        if (number === 0) {
            return number + '-ев';
        } else if (last2Digits === 0) {
            return number + '-ен';
        } else if (last2Digits > 10 && last2Digits < 20) {
            return number + '-ти';
        } else if (lastDigit === 1) {
            return number + '-ви';
        } else if (lastDigit === 2) {
            return number + '-ри';
        } else if (lastDigit === 7 || lastDigit === 8) {
            return number + '-ми';
        } else {
            return number + '-ти';
        }
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return mk;

})));


/***/ }),

/***/ "aR6p":
/*!************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/PlotlySection.js ***!
  \************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Section = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Section = exports.Section = function (_Component) {
  _inherits(Section, _Component);

  function Section() {
    _classCallCheck(this, Section);

    var _this = _possibleConstructorReturn(this, (Section.__proto__ || Object.getPrototypeOf(Section)).call(this));

    _this.sectionVisible = true;
    return _this;
  }

  _createClass(Section, [{
    key: 'render',
    value: function render() {
      if (!this.sectionVisible) {
        return null;
      }

      return _react2.default.createElement(
        'div',
        { className: 'section' },
        this.props.name ? _react2.default.createElement(
          'div',
          { className: 'section__heading' },
          _react2.default.createElement(
            'div',
            { className: 'section__heading__text' },
            this.props.name
          )
        ) : null,
        this.props.children
      );
    }
  }]);

  return Section;
}(_react.Component);

Section.plotly_editor_traits = { no_visibility_forcing: false };
Section.propTypes = {
  children: _propTypes2.default.node,
  name: _propTypes2.default.string,
  attr: _propTypes2.default.string
};

var PlotlySection = function (_Section) {
  _inherits(PlotlySection, _Section);

  function PlotlySection(props, context) {
    _classCallCheck(this, PlotlySection);

    var _this2 = _possibleConstructorReturn(this, (PlotlySection.__proto__ || Object.getPrototypeOf(PlotlySection)).call(this, props, context));

    _this2.determineVisibility(props, context);
    return _this2;
  }

  _createClass(PlotlySection, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps, nextContext) {
      this.determineVisibility(nextProps, nextContext);
    }
  }, {
    key: 'determineVisibility',
    value: function determineVisibility(nextProps, nextContext) {
      var _this3 = this;

      var _unpackPlotProps = (0, _lib.unpackPlotProps)(nextProps, nextContext),
          isVisible = _unpackPlotProps.isVisible;

      this.sectionVisible = Boolean(isVisible);

      _react2.default.Children.forEach(nextProps.children, function (child) {
        if (!child || _this3.sectionVisible) {
          return;
        }

        if (child.props.attr) {
          var plotProps = (0, _lib.unpackPlotProps)(child.props, nextContext);
          if (child.type.modifyPlotProps) {
            child.type.modifyPlotProps(child.props, nextContext, plotProps);
          }
          _this3.sectionVisible = _this3.sectionVisible || plotProps.isVisible;
          return;
        }

        if (!(child.type.plotly_editor_traits || {}).no_visibility_forcing) {
          // non-attr components force visibility (unless they don't via traits)
          _this3.sectionVisible = true;
          return;
        }
      });
    }
  }]);

  return PlotlySection;
}(Section);

exports.default = PlotlySection;


PlotlySection.plotly_editor_traits = { no_visibility_forcing: true };
PlotlySection.contextTypes = _lib.containerConnectedContextTypes;
//# sourceMappingURL=PlotlySection.js.map

/***/ }),

/***/ "aaTI":
/*!********************************************!*\
  !*** ./node_modules/mdi-react/AppsIcon.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var AppsIcon = function AppsIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M16,20H20V16H16M16,14H20V10H16M10,8H14V4H10M16,8H20V4H16M10,14H14V10H10M4,14H8V10H4M4,20H8V16H4M10,20H14V16H10M4,8H8V4H4V8Z' })
  );
};

module.exports = AppsIcon;


/***/ }),

/***/ "adOz":
/*!***************************************************************************!*\
  !*** ./node_modules/core-js/library/modules/es7.symbol.async-iterator.js ***!
  \***************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(/*! ./_wks-define */ "Zxgi")('asyncIterator');


/***/ }),

/***/ "adU4":
/*!*************************************************!*\
  !*** ./node_modules/lodash/_listCacheDelete.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var assocIndexOf = __webpack_require__(/*! ./_assocIndexOf */ "y1pI");

/** Used for built-in method references. */
var arrayProto = Array.prototype;

/** Built-in value references. */
var splice = arrayProto.splice;

/**
 * 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;
}

module.exports = listCacheDelete;


/***/ }),

/***/ "afKu":
/*!**************************************!*\
  !*** ./node_modules/sha.js/index.js ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var exports = module.exports = function SHA (algorithm) {
  algorithm = algorithm.toLowerCase()

  var Algorithm = exports[algorithm]
  if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')

  return new Algorithm()
}

exports.sha = __webpack_require__(/*! ./sha */ "CH9F")
exports.sha1 = __webpack_require__(/*! ./sha1 */ "fnjI")
exports.sha224 = __webpack_require__(/*! ./sha224 */ "cqoG")
exports.sha256 = __webpack_require__(/*! ./sha256 */ "olUY")
exports.sha384 = __webpack_require__(/*! ./sha384 */ "uDfV")
exports.sha512 = __webpack_require__(/*! ./sha512 */ "T9HO")


/***/ }),

/***/ "ai3f":
/*!****************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/setting/index.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const serverconnection_1 = __webpack_require__(/*! ../serverconnection */ "ZWV2");
/**
 * The url for the lab settings service.
 */
const SERVICE_SETTINGS_URL = 'api/settings';
/**
 * The settings API service manager.
 */
class SettingManager {
    /**
     * Create a new setting manager.
     */
    constructor(options = {}) {
        this.serverSettings =
            options.serverSettings || serverconnection_1.ServerConnection.makeSettings();
    }
    /**
     * Fetch a plugin's settings.
     *
     * @param id - The plugin's ID.
     *
     * @returns A promise that resolves if successful.
     */
    fetch(id) {
        return __awaiter(this, void 0, void 0, function* () {
            const { serverSettings } = this;
            const { baseUrl, pageUrl } = serverSettings;
            const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;
            const base = baseUrl + pageUrl;
            const url = Private.url(base, id);
            const response = yield makeRequest(url, {}, serverSettings);
            if (response.status !== 200) {
                throw new ResponseError(response);
            }
            return response.json();
        });
    }
    /**
     * Save a plugin's settings.
     *
     * @param id - The plugin's ID.
     *
     * @param raw - The user setting values as a raw string of JSON with comments.
     *
     * @returns A promise that resolves if successful.
     */
    save(id, raw) {
        return __awaiter(this, void 0, void 0, function* () {
            const { serverSettings } = this;
            const { baseUrl, pageUrl } = serverSettings;
            const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;
            const base = baseUrl + pageUrl;
            const url = Private.url(base, id);
            const init = { body: raw, method: 'PUT' };
            const response = yield makeRequest(url, init, serverSettings);
            if (response.status !== 204) {
                throw new ResponseError(response);
            }
        });
    }
}
exports.SettingManager = SettingManager;
/**
 * A namespace for private data.
 */
var Private;
(function (Private) {
    /**
     * Get the url for a plugin's settings.
     */
    function url(base, id) {
        return coreutils_1.URLExt.join(base, SERVICE_SETTINGS_URL, id);
    }
    Private.url = url;
})(Private || (Private = {}));


/***/ }),

/***/ "aic/":
/*!********************************************!*\
  !*** ./node_modules/base16/lib/monokai.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'monokai',
  author: 'wimer hazenberg (http://www.monokai.nl)',
  base00: '#272822',
  base01: '#383830',
  base02: '#49483e',
  base03: '#75715e',
  base04: '#a59f85',
  base05: '#f8f8f2',
  base06: '#f5f4f1',
  base07: '#f9f8f5',
  base08: '#f92672',
  base09: '#fd971f',
  base0A: '#f4bf75',
  base0B: '#a6e22e',
  base0C: '#a1efe4',
  base0D: '#66d9ef',
  base0E: '#ae81ff',
  base0F: '#cc6633'
};
module.exports = exports['default'];

/***/ }),

/***/ "ajAQ":
/*!********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotMesh3dIcon.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotMesh3dIcon = function PlotMesh3dIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M16 0L1.312 8v16L16 32l14.688-8V8zM4 11.313l4 2v4.125l-4-2.25zm19.063-.25l-4.688-2.375 4.188-2 4.5 2.5zm-2.25 1.187L16 14.688l-4.813-2.438L16 9.875zM8.938 11.063l-4-2 4.5-2.375 4.188 2zm1.75 3.625l4 2v4.5l-4-2.25zm4 9.437v4l-4-2.125v-4.125zm2.625 0l4-2.25V26l-4 2.125zm0-2.937v-4.5l4-2v4.25zM24 13.313l4-2v3.875l-4 2.25zm-3.75-8L16 7.438l-4.25-2.125L16 3.063zM4 18.25l4 2.313v4.125l-4-2.125zm20 6.438v-4.125l4-2.313v4.125z' })
    );
};

exports.default = PlotMesh3dIcon;

/***/ }),

/***/ "amaH":
/*!***************************************************!*\
  !*** ./node_modules/source-map/lib/quick-sort.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/* -*- Mode: js; js-indent-level: 2; -*- */
/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

// It turns out that some (most?) JavaScript engines don't self-host
// `Array.prototype.sort`. This makes sense because C++ will likely remain
// faster than JS when doing raw CPU-intensive sorting. However, when using a
// custom comparator function, calling back and forth between the VM's C++ and
// JIT'd JS is rather slow *and* loses JIT type information, resulting in
// worse generated code for the comparator function than would be optimal. In
// fact, when sorting with a comparator, these costs outweigh the benefits of
// sorting in C++. By using our own JS-implemented Quick Sort (below), we get
// a ~3500ms mean speed-up in `bench/bench.html`.

/**
 * Swap the elements indexed by `x` and `y` in the array `ary`.
 *
 * @param {Array} ary
 *        The array.
 * @param {Number} x
 *        The index of the first item.
 * @param {Number} y
 *        The index of the second item.
 */
function swap(ary, x, y) {
  var temp = ary[x];
  ary[x] = ary[y];
  ary[y] = temp;
}

/**
 * Returns a random integer within the range `low .. high` inclusive.
 *
 * @param {Number} low
 *        The lower bound on the range.
 * @param {Number} high
 *        The upper bound on the range.
 */
function randomIntInRange(low, high) {
  return Math.round(low + (Math.random() * (high - low)));
}

/**
 * The Quick Sort algorithm.
 *
 * @param {Array} ary
 *        An array to sort.
 * @param {function} comparator
 *        Function to use to compare two items.
 * @param {Number} p
 *        Start index of the array
 * @param {Number} r
 *        End index of the array
 */
function doQuickSort(ary, comparator, p, r) {
  // If our lower bound is less than our upper bound, we (1) partition the
  // array into two pieces and (2) recurse on each half. If it is not, this is
  // the empty array and our base case.

  if (p < r) {
    // (1) Partitioning.
    //
    // The partitioning chooses a pivot between `p` and `r` and moves all
    // elements that are less than or equal to the pivot to the before it, and
    // all the elements that are greater than it after it. The effect is that
    // once partition is done, the pivot is in the exact place it will be when
    // the array is put in sorted order, and it will not need to be moved
    // again. This runs in O(n) time.

    // Always choose a random pivot so that an input array which is reverse
    // sorted does not cause O(n^2) running time.
    var pivotIndex = randomIntInRange(p, r);
    var i = p - 1;

    swap(ary, pivotIndex, r);
    var pivot = ary[r];

    // Immediately after `j` is incremented in this loop, the following hold
    // true:
    //
    //   * Every element in `ary[p .. i]` is less than or equal to the pivot.
    //
    //   * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
    for (var j = p; j < r; j++) {
      if (comparator(ary[j], pivot) <= 0) {
        i += 1;
        swap(ary, i, j);
      }
    }

    swap(ary, i + 1, j);
    var q = i + 1;

    // (2) Recurse on each half.

    doQuickSort(ary, comparator, p, q - 1);
    doQuickSort(ary, comparator, q + 1, r);
  }
}

/**
 * Sort the given array in-place with the given comparator function.
 *
 * @param {Array} ary
 *        An array to sort.
 * @param {function} comparator
 *        Function to use to compare two items.
 */
exports.quickSort = function (ary, comparator) {
  doQuickSort(ary, comparator, 0, ary.length - 1);
};


/***/ }),

/***/ "anm7":
/*!************************************************!*\
  !*** ./node_modules/mdi-react/MenuDownIcon.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var MenuDownIcon = function MenuDownIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M7,10L12,15L17,10H7Z' })
  );
};

module.exports = MenuDownIcon;


/***/ }),

/***/ "ao+V":
/*!**********************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/parse.js ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.default = parse;

var _parser = __webpack_require__(/*! ./parser */ "RoA7");

var _parser2 = _interopRequireDefault(_parser);

var _input = __webpack_require__(/*! ./input */ "pOV6");

var _input2 = _interopRequireDefault(_input);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function parse(css, opts) {
    if (opts && opts.safe) {
        throw new Error('Option safe was removed. ' + 'Use parser: require("postcss-safe-parser")');
    }

    var input = new _input2.default(css, opts);
    var parser = new _parser2.default(input);
    try {
        parser.parse();
    } catch (e) {
        if (e.name === 'CssSyntaxError' && opts && opts.from) {
            if (/\.scss$/i.test(opts.from)) {
                e.message += '\nYou tried to parse SCSS with ' + 'the standard CSS parser; ' + 'try again with the postcss-scss parser';
            } else if (/\.sass/i.test(opts.from)) {
                e.message += '\nYou tried to parse Sass with ' + 'the standard CSS parser; ' + 'try again with the postcss-sass parser';
            } else if (/\.less$/i.test(opts.from)) {
                e.message += '\nYou tried to parse Less with ' + 'the standard CSS parser; ' + 'try again with the postcss-less parser';
            }
        }
        throw e;
    }

    return parser.root;
}
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInBhcnNlLmVzNiJdLCJuYW1lcyI6WyJwYXJzZSIsImNzcyIsIm9wdHMiLCJzYWZlIiwiRXJyb3IiLCJpbnB1dCIsIklucHV0IiwicGFyc2VyIiwiUGFyc2VyIiwiZSIsIm5hbWUiLCJmcm9tIiwidGVzdCIsIm1lc3NhZ2UiLCJyb290Il0sIm1hcHBpbmdzIjoiOzs7a0JBR3dCQSxLOztBQUh4Qjs7OztBQUNBOzs7Ozs7QUFFZSxTQUFTQSxLQUFULENBQWVDLEdBQWYsRUFBb0JDLElBQXBCLEVBQTBCO0FBQ3JDLFFBQUtBLFFBQVFBLEtBQUtDLElBQWxCLEVBQXlCO0FBQ3JCLGNBQU0sSUFBSUMsS0FBSixDQUFVLDhCQUNBLDRDQURWLENBQU47QUFFSDs7QUFFRCxRQUFJQyxRQUFRLElBQUlDLGVBQUosQ0FBVUwsR0FBVixFQUFlQyxJQUFmLENBQVo7QUFDQSxRQUFJSyxTQUFTLElBQUlDLGdCQUFKLENBQVdILEtBQVgsQ0FBYjtBQUNBLFFBQUk7QUFDQUUsZUFBT1AsS0FBUDtBQUNILEtBRkQsQ0FFRSxPQUFPUyxDQUFQLEVBQVU7QUFDUixZQUFLQSxFQUFFQyxJQUFGLEtBQVcsZ0JBQVgsSUFBK0JSLElBQS9CLElBQXVDQSxLQUFLUyxJQUFqRCxFQUF3RDtBQUNwRCxnQkFBSyxXQUFXQyxJQUFYLENBQWdCVixLQUFLUyxJQUFyQixDQUFMLEVBQWtDO0FBQzlCRixrQkFBRUksT0FBRixJQUFhLG9DQUNBLDJCQURBLEdBRUEsd0NBRmI7QUFHSCxhQUpELE1BSU8sSUFBSyxVQUFVRCxJQUFWLENBQWVWLEtBQUtTLElBQXBCLENBQUwsRUFBaUM7QUFDcENGLGtCQUFFSSxPQUFGLElBQWEsb0NBQ0EsMkJBREEsR0FFQSx3Q0FGYjtBQUdILGFBSk0sTUFJQSxJQUFLLFdBQVdELElBQVgsQ0FBZ0JWLEtBQUtTLElBQXJCLENBQUwsRUFBa0M7QUFDckNGLGtCQUFFSSxPQUFGLElBQWEsb0NBQ0EsMkJBREEsR0FFQSx3Q0FGYjtBQUdIO0FBQ0o7QUFDRCxjQUFNSixDQUFOO0FBQ0g7O0FBRUQsV0FBT0YsT0FBT08sSUFBZDtBQUNIIiwiZmlsZSI6InBhcnNlLmpzIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IFBhcnNlciBmcm9tICcuL3BhcnNlcic7XG5pbXBvcnQgSW5wdXQgIGZyb20gJy4vaW5wdXQnO1xuXG5leHBvcnQgZGVmYXVsdCBmdW5jdGlvbiBwYXJzZShjc3MsIG9wdHMpIHtcbiAgICBpZiAoIG9wdHMgJiYgb3B0cy5zYWZlICkge1xuICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ09wdGlvbiBzYWZlIHdhcyByZW1vdmVkLiAnICtcbiAgICAgICAgICAgICAgICAgICAgICAgICdVc2UgcGFyc2VyOiByZXF1aXJlKFwicG9zdGNzcy1zYWZlLXBhcnNlclwiKScpO1xuICAgIH1cblxuICAgIGxldCBpbnB1dCA9IG5ldyBJbnB1dChjc3MsIG9wdHMpO1xuICAgIGxldCBwYXJzZXIgPSBuZXcgUGFyc2VyKGlucHV0KTtcbiAgICB0cnkge1xuICAgICAgICBwYXJzZXIucGFyc2UoKTtcbiAgICB9IGNhdGNoIChlKSB7XG4gICAgICAgIGlmICggZS5uYW1lID09PSAnQ3NzU3ludGF4RXJyb3InICYmIG9wdHMgJiYgb3B0cy5mcm9tICkge1xuICAgICAgICAgICAgaWYgKCAvXFwuc2NzcyQvaS50ZXN0KG9wdHMuZnJvbSkgKSB7XG4gICAgICAgICAgICAgICAgZS5tZXNzYWdlICs9ICdcXG5Zb3UgdHJpZWQgdG8gcGFyc2UgU0NTUyB3aXRoICcgK1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAndGhlIHN0YW5kYXJkIENTUyBwYXJzZXI7ICcgK1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAndHJ5IGFnYWluIHdpdGggdGhlIHBvc3Rjc3Mtc2NzcyBwYXJzZXInO1xuICAgICAgICAgICAgfSBlbHNlIGlmICggL1xcLnNhc3MvaS50ZXN0KG9wdHMuZnJvbSkgKSB7XG4gICAgICAgICAgICAgICAgZS5tZXNzYWdlICs9ICdcXG5Zb3UgdHJpZWQgdG8gcGFyc2UgU2FzcyB3aXRoICcgK1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAndGhlIHN0YW5kYXJkIENTUyBwYXJzZXI7ICcgK1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAndHJ5IGFnYWluIHdpdGggdGhlIHBvc3Rjc3Mtc2FzcyBwYXJzZXInO1xuICAgICAgICAgICAgfSBlbHNlIGlmICggL1xcLmxlc3MkL2kudGVzdChvcHRzLmZyb20pICkge1xuICAgICAgICAgICAgICAgIGUubWVzc2FnZSArPSAnXFxuWW91IHRyaWVkIHRvIHBhcnNlIExlc3Mgd2l0aCAnICtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgJ3RoZSBzdGFuZGFyZCBDU1MgcGFyc2VyOyAnICtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgJ3RyeSBhZ2FpbiB3aXRoIHRoZSBwb3N0Y3NzLWxlc3MgcGFyc2VyJztcbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgICB0aHJvdyBlO1xuICAgIH1cblxuICAgIHJldHVybiBwYXJzZXIucm9vdDtcbn1cbiJdfQ==


/***/ }),

/***/ "aqI/":
/*!*************************************************!*\
  !*** ./node_modules/hmac-drbg/lib/hmac-drbg.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var hash = __webpack_require__(/*! hash.js */ "fZJM");
var utils = __webpack_require__(/*! minimalistic-crypto-utils */ "dlgc");
var assert = __webpack_require__(/*! minimalistic-assert */ "2j6C");

function HmacDRBG(options) {
  if (!(this instanceof HmacDRBG))
    return new HmacDRBG(options);
  this.hash = options.hash;
  this.predResist = !!options.predResist;

  this.outLen = this.hash.outSize;
  this.minEntropy = options.minEntropy || this.hash.hmacStrength;

  this._reseed = null;
  this.reseedInterval = null;
  this.K = null;
  this.V = null;

  var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex');
  var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex');
  var pers = utils.toArray(options.pers, options.persEnc || 'hex');
  assert(entropy.length >= (this.minEntropy / 8),
         'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
  this._init(entropy, nonce, pers);
}
module.exports = HmacDRBG;

HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
  var seed = entropy.concat(nonce).concat(pers);

  this.K = new Array(this.outLen / 8);
  this.V = new Array(this.outLen / 8);
  for (var i = 0; i < this.V.length; i++) {
    this.K[i] = 0x00;
    this.V[i] = 0x01;
  }

  this._update(seed);
  this._reseed = 1;
  this.reseedInterval = 0x1000000000000;  // 2^48
};

HmacDRBG.prototype._hmac = function hmac() {
  return new hash.hmac(this.hash, this.K);
};

HmacDRBG.prototype._update = function update(seed) {
  var kmac = this._hmac()
                 .update(this.V)
                 .update([ 0x00 ]);
  if (seed)
    kmac = kmac.update(seed);
  this.K = kmac.digest();
  this.V = this._hmac().update(this.V).digest();
  if (!seed)
    return;

  this.K = this._hmac()
               .update(this.V)
               .update([ 0x01 ])
               .update(seed)
               .digest();
  this.V = this._hmac().update(this.V).digest();
};

HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
  // Optional entropy enc
  if (typeof entropyEnc !== 'string') {
    addEnc = add;
    add = entropyEnc;
    entropyEnc = null;
  }

  entropy = utils.toArray(entropy, entropyEnc);
  add = utils.toArray(add, addEnc);

  assert(entropy.length >= (this.minEntropy / 8),
         'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');

  this._update(entropy.concat(add || []));
  this._reseed = 1;
};

HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
  if (this._reseed > this.reseedInterval)
    throw new Error('Reseed is required');

  // Optional encoding
  if (typeof enc !== 'string') {
    addEnc = add;
    add = enc;
    enc = null;
  }

  // Optional additional data
  if (add) {
    add = utils.toArray(add, addEnc || 'hex');
    this._update(add);
  }

  var temp = [];
  while (temp.length < len) {
    this.V = this._hmac().update(this.V).digest();
    temp = temp.concat(this.V);
  }

  var res = temp.slice(0, len);
  this._update(add);
  this._reseed++;
  return utils.encode(res, enc);
};


/***/ }),

/***/ "aqbM":
/*!***********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeConeIcon.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeConeIcon = function TraceTypeConeIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 1360 1360' }, props),
        _react2.default.createElement('path', { fill: '#119DFF', d: 'M1247.981 867.856l-551.37-255.077a40.776 40.776 0 0 0-34.201 0L111.045 867.856a40.731 40.731 0 0 0-.267 73.819l551.362 259.917a40.777 40.777 0 0 0 17.374 3.887 40.722 40.722 0 0 0 17.363-3.887l551.37-259.917a40.754 40.754 0 0 0 23.37-36.994 40.74 40.74 0 0 0-23.636-36.825z' }),
        _react2.default.createElement(
            'linearGradient',
            { id: 'a', gradientUnits: 'userSpaceOnUse', x1: '730.859', y1: '916.448', x2: '860.664', y2: '991.391' },
            _react2.default.createElement('stop', { offset: '0', stopColor: '#119dff' }),
            _react2.default.createElement('stop', { offset: '.462', stopColor: '#09ffff' })
        ),
        _react2.default.createElement('path', { fill: 'url(#a)', d: 'M763.471 859.964c39.777-20.916 73.551.519 91.382 18.35 17.828 17.828 39.952 52.288 18.342 91.374l-160.126 50.409 50.402-160.133z' }),
        _react2.default.createElement(
            'linearGradient',
            { id: 'b', gradientUnits: 'userSpaceOnUse', x1: '730.856', y1: '617', x2: '860.663', y2: '691.945' },
            _react2.default.createElement('stop', { offset: '0', stopColor: '#119dff' }),
            _react2.default.createElement('stop', { offset: '.462', stopColor: '#09ffff' })
        ),
        _react2.default.createElement('path', { fill: 'url(#b)', d: 'M763.463 560.523c39.779-20.916 73.559.512 91.39 18.342 17.828 17.828 39.944 52.296 18.337 91.382l-160.121 50.404 50.394-160.128z' }),
        _react2.default.createElement(
            'linearGradient',
            { id: 'c', gradientUnits: 'userSpaceOnUse', x1: '1020.848', y1: '750.898', x2: '1150.659', y2: '825.844' },
            _react2.default.createElement('stop', { offset: '0', stopColor: '#119dff' }),
            _react2.default.createElement('stop', { offset: '.462', stopColor: '#09ffff' })
        ),
        _react2.default.createElement('path', { fill: 'url(#c)', d: 'M1053.46 694.414c39.774-20.921 73.549.514 91.382 18.35 17.828 17.83 39.952 52.286 18.348 91.379l-160.131 50.406 50.401-160.135z' }),
        _react2.default.createElement(
            'linearGradient',
            { id: 'd', gradientUnits: 'userSpaceOnUse', x1: '1106.724', y1: '555.481', x2: '1031.777', y2: '425.669' },
            _react2.default.createElement('stop', { offset: '.237', stopColor: '#119dff' }),
            _react2.default.createElement('stop', { offset: '.989', stopColor: '#09ffff' })
        ),
        _react2.default.createElement('path', { fill: 'url(#d)', d: 'M1053.452 413.156c39.775-20.916 73.552.512 91.385 18.345 17.831 17.833 39.944 52.296 18.345 91.384l-160.126 50.402 50.396-160.131z' }),
        _react2.default.createElement(
            'linearGradient',
            { id: 'e', gradientUnits: 'userSpaceOnUse', x1: '426.62', y1: '677.754', x2: '556.428', y2: '752.698' },
            _react2.default.createElement('stop', { offset: '0', stopColor: '#119dff' }),
            _react2.default.createElement('stop', { offset: '.462', stopColor: '#09ffff' })
        ),
        _react2.default.createElement('path', { fill: 'url(#e)', d: 'M459.229 621.274c39.775-20.918 73.552.509 91.382 18.342 17.833 17.833 39.95 52.291 18.345 91.382l-160.131 50.404 50.404-160.128z' }),
        _react2.default.createElement(
            'linearGradient',
            { id: 'f', gradientUnits: 'userSpaceOnUse', x1: '156.995', y1: '821.842', x2: '286.801', y2: '896.785' },
            _react2.default.createElement('stop', { offset: '0', stopColor: '#119dff' }),
            _react2.default.createElement('stop', { offset: '.462', stopColor: '#09ffff' })
        ),
        _react2.default.createElement('path', { fill: 'url(#f)', d: 'M189.604 765.361c39.775-20.921 73.549.51 91.382 18.343 17.828 17.828 39.942 52.286 18.342 91.382L139.2 925.49l50.404-160.129z' }),
        _react2.default.createElement(
            'linearGradient',
            { id: 'g', gradientUnits: 'userSpaceOnUse', x1: '242.869', y1: '578.82', x2: '167.925', y2: '449.012' },
            _react2.default.createElement('stop', { offset: '.237', stopColor: '#119dff' }),
            _react2.default.createElement('stop', { offset: '.989', stopColor: '#09ffff' })
        ),
        _react2.default.createElement('path', { fill: 'url(#g)', d: 'M189.604 436.496c39.77-20.916 73.549.512 91.382 18.345 17.828 17.828 39.939 52.291 18.342 91.382L139.2 596.626l50.404-160.13z' }),
        _react2.default.createElement(
            'linearGradient',
            { id: 'h', gradientUnits: 'userSpaceOnUse', x1: '512.5', y1: '309.669', x2: '437.554', y2: '179.859' },
            _react2.default.createElement('stop', { offset: '.237', stopColor: '#119dff' }),
            _react2.default.createElement('stop', { offset: '.989', stopColor: '#09ffff' })
        ),
        _react2.default.createElement('path', { fill: 'url(#h)', d: 'M459.234 167.341c39.777-20.922 73.549.514 91.38 18.347 17.833 17.833 39.955 52.285 18.35 91.381l-160.138 50.404 50.408-160.132z' }),
        _react2.default.createElement(
            'linearGradient',
            { id: 'i', gradientUnits: 'userSpaceOnUse', x1: '816.734', y1: '445.83', x2: '741.791', y2: '316.024' },
            _react2.default.createElement('stop', { offset: '.237', stopColor: '#119dff' }),
            _react2.default.createElement('stop', { offset: '.989', stopColor: '#09ffff' })
        ),
        _react2.default.createElement('path', { fill: 'url(#i)', d: 'M763.468 303.509c39.772-20.914 73.554.514 91.387 18.345 17.828 17.828 39.942 52.299 18.338 91.38l-160.126 50.409 50.401-160.134z' })
    );
};

exports.default = TraceTypeConeIcon;

/***/ }),

/***/ "ar/p":
/*!**************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_object-gopn.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = __webpack_require__(/*! ./_object-keys-internal */ "5vMV");
var hiddenKeys = __webpack_require__(/*! ./_enum-bug-keys */ "FpHa").concat('length', 'prototype');

exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
  return $keys(O, hiddenKeys);
};


/***/ }),

/***/ "at63":
/*!**************************************************!*\
  !*** ./node_modules/browserify-aes/modes/ctr.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var xor = __webpack_require__(/*! buffer-xor */ "jIre")
var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer
var incr32 = __webpack_require__(/*! ../incr32 */ "vZ2G")

function getBlock (self) {
  var out = self._cipher.encryptBlockRaw(self._prev)
  incr32(self._prev)
  return out
}

var blockSize = 16
exports.encrypt = function (self, chunk) {
  var chunkNum = Math.ceil(chunk.length / blockSize)
  var start = self._cache.length
  self._cache = Buffer.concat([
    self._cache,
    Buffer.allocUnsafe(chunkNum * blockSize)
  ])
  for (var i = 0; i < chunkNum; i++) {
    var out = getBlock(self)
    var offset = start + i * blockSize
    self._cache.writeUInt32BE(out[0], offset + 0)
    self._cache.writeUInt32BE(out[1], offset + 4)
    self._cache.writeUInt32BE(out[2], offset + 8)
    self._cache.writeUInt32BE(out[3], offset + 12)
  }
  var pad = self._cache.slice(0, chunk.length)
  self._cache = self._cache.slice(chunk.length)
  return xor(chunk, pad)
}


/***/ }),

/***/ "atcJ":
/*!******************************************************************!*\
  !*** ./node_modules/@jupyterlab/json-extension/lib/component.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const React = __importStar(__webpack_require__(/*! react */ "q1tI"));
const ReactDOM = __importStar(__webpack_require__(/*! react-dom */ "i8i4"));
const react_highlighter_1 = __importDefault(__webpack_require__(/*! react-highlighter */ "Ngil"));
const react_json_tree_1 = __importDefault(__webpack_require__(/*! react-json-tree */ "fNf1"));
/**
 * A component that renders JSON data as a collapsible tree.
 */
class Component extends React.Component {
    constructor() {
        super(...arguments);
        this.state = { filter: '' };
        this.input = null;
        this.timer = 0;
    }
    componentDidMount() {
        /**
         * Stop propagation of keyboard events to JupyterLab
         */
        ReactDOM.findDOMNode(this.input).addEventListener('keydown', (event) => {
            event.stopPropagation();
        }, false);
    }
    componentWillUnmount() {
        ReactDOM.findDOMNode(this.input).removeEventListener('keydown', (event) => {
            event.stopPropagation();
        }, false);
    }
    render() {
        const { data, metadata } = this.props;
        const root = metadata && metadata.root ? metadata.root : 'root';
        const keyPaths = this.state.filter
            ? filterPaths(data, this.state.filter, [root])
            : [root];
        return (React.createElement("div", { style: { position: 'relative', width: '100%' } },
            React.createElement("input", { ref: ref => (this.input = ref), onChange: event => {
                    if (this.timer) {
                        window.clearTimeout(this.timer);
                    }
                    const filter = event.target.value;
                    this.timer = window.setTimeout(() => {
                        this.setState({ filter });
                        this.timer = 0;
                    }, 300);
                }, style: {
                    position: 'absolute',
                    top: 0,
                    right: 0,
                    width: '33%',
                    maxWidth: 150,
                    zIndex: 10,
                    fontSize: 13,
                    padding: '4px 2px'
                }, type: "text", placeholder: "Filter..." }),
            React.createElement(react_json_tree_1.default, { data: data, collectionLimit: 100, theme: {
                    extend: theme,
                    // TODO: Use Jupyter Notebook's current CodeMirror theme vs. 'cm-s-ipython'
                    tree: `CodeMirror ${this.props.theme || 'cm-s-ipython'}`,
                    // valueLabel: 'cm-variable',
                    valueText: 'cm-string',
                    // nestedNodeLabel: 'cm-variable-2',
                    nestedNodeItemString: 'cm-comment',
                    // value: {},
                    // label: {},
                    // itemRange: {},
                    // nestedNode: {},
                    // nestedNodeItemType: {},
                    // nestedNodeChildren: {},
                    // rootNodeChildren: {},
                    arrowSign: { color: 'cm-variable' }
                }, invertTheme: false, keyPath: [root], labelRenderer: ([label, type]) => {
                    let className = 'cm-variable';
                    // if (type === 'root') className = 'cm-variable-2';
                    if (type === 'array') {
                        className = 'cm-variable-2';
                    }
                    if (type === 'object') {
                        className = 'cm-variable-3';
                    }
                    return (React.createElement("span", { className: className },
                        React.createElement(react_highlighter_1.default, { search: this.state.filter, matchStyle: { backgroundColor: 'yellow' } }, `${label}: `)));
                }, valueRenderer: raw => {
                    let className = 'cm-string';
                    if (typeof raw === 'number') {
                        className = 'cm-number';
                    }
                    if (raw === 'true' || raw === 'false') {
                        className = 'cm-keyword';
                    }
                    return (React.createElement("span", { className: className },
                        React.createElement(react_highlighter_1.default, { search: this.state.filter, matchStyle: { backgroundColor: 'yellow' } }, `${raw}`)));
                }, shouldExpandNode: (keyPath, data, level) => metadata && metadata.expanded
                    ? true
                    : keyPaths.join(',').includes(keyPath.join(',')) })));
    }
}
exports.Component = Component;
const theme = {
    scheme: 'jupyter',
    base00: '#fff',
    base01: '#fff',
    base02: '#d7d4f0',
    base03: '#408080',
    base04: '#b4b7b4',
    base05: '#c5c8c6',
    base06: '#d7d4f0',
    base07: '#fff',
    base08: '#000',
    base09: '#080',
    base0A: '#fba922',
    base0B: '#408080',
    base0C: '#aa22ff',
    base0D: '#00f',
    base0E: '#008000',
    base0F: '#00f'
};
function objectIncludes(data, query) {
    return JSON.stringify(data).includes(query);
}
function filterPaths(data, query, parent = ['root']) {
    if (Array.isArray(data)) {
        return data.reduce((result, item, index) => {
            if (item && typeof item === 'object' && objectIncludes(item, query)) {
                return [
                    ...result,
                    [index, ...parent].join(','),
                    ...filterPaths(item, query, [index, ...parent])
                ];
            }
            return result;
        }, []);
    }
    if (typeof data === 'object') {
        return Object.keys(data).reduce((result, key) => {
            let item = data[key];
            if (item &&
                typeof item === 'object' &&
                (key.includes(query) || objectIncludes(item, query))) {
                return [
                    ...result,
                    [key, ...parent].join(','),
                    ...filterPaths(item, query, [key, ...parent])
                ];
            }
            return result;
        }, []);
    }
}


/***/ }),

/***/ "avjU":
/*!*************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/array.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var isArray = Array.isArray;

// IE9 fallbacks

var ab = (typeof ArrayBuffer === 'undefined' || !ArrayBuffer.isView) ?
    {isView: function() { return false; }} :
    ArrayBuffer;

var dv = (typeof DataView === 'undefined') ?
    function() {} :
    DataView;

function isTypedArray(a) {
    return ab.isView(a) && !(a instanceof dv);
}
exports.isTypedArray = isTypedArray;

function isArrayOrTypedArray(a) {
    return isArray(a) || isTypedArray(a);
}
exports.isArrayOrTypedArray = isArrayOrTypedArray;

/*
 * Test whether an input object is 1D.
 *
 * Assumes we already know the object is an array.
 *
 * Looks only at the first element, if the dimensionality is
 * not consistent we won't figure that out here.
 */
function isArray1D(a) {
    return !isArrayOrTypedArray(a[0]);
}
exports.isArray1D = isArray1D;

/*
 * Ensures an array has the right amount of storage space. If it doesn't
 * exist, it creates an array. If it does exist, it returns it if too
 * short or truncates it in-place.
 *
 * The goal is to just reuse memory to avoid a bit of excessive garbage
 * collection.
 */
exports.ensureArray = function(out, n) {
    // TODO: typed array support here? This is only used in
    // traces/carpet/compute_control_points
    if(!isArray(out)) out = [];

    // If too long, truncate. (If too short, it will grow
    // automatically so we don't care about that case)
    out.length = n;

    return out;
};

/*
 * TypedArray-compatible concatenation of n arrays
 * if all arrays are the same type it will preserve that type,
 * otherwise it falls back on Array.
 * Also tries to avoid copying, in case one array has zero length
 * But never mutates an existing array
 */
exports.concat = function() {
    var args = [];
    var allArray = true;
    var totalLen = 0;

    var _constructor, arg0, i, argi, posi, leni, out, j;

    for(i = 0; i < arguments.length; i++) {
        argi = arguments[i];
        leni = argi.length;
        if(leni) {
            if(arg0) args.push(argi);
            else {
                arg0 = argi;
                posi = leni;
            }

            if(isArray(argi)) {
                _constructor = false;
            }
            else {
                allArray = false;
                if(!totalLen) {
                    _constructor = argi.constructor;
                }
                else if(_constructor !== argi.constructor) {
                    // TODO: in principle we could upgrade here,
                    // ie keep typed array but convert all to Float64Array?
                    _constructor = false;
                }
            }

            totalLen += leni;
        }
    }

    if(!totalLen) return [];
    if(!args.length) return arg0;

    if(allArray) return arg0.concat.apply(arg0, args);
    if(_constructor) {
        // matching typed arrays
        out = new _constructor(totalLen);
        out.set(arg0);
        for(i = 0; i < args.length; i++) {
            argi = args[i];
            out.set(argi, posi);
            posi += argi.length;
        }
        return out;
    }

    // mismatched types or Array + typed
    out = new Array(totalLen);
    for(j = 0; j < arg0.length; j++) out[j] = arg0[j];
    for(i = 0; i < args.length; i++) {
        argi = args[i];
        for(j = 0; j < argi.length; j++) out[posi + j] = argi[j];
        posi += j;
    }
    return out;
};

exports.maxRowLength = function(z) {
    return _rowLength(z, Math.max, 0);
};

exports.minRowLength = function(z) {
    return _rowLength(z, Math.min, Infinity);
};

function _rowLength(z, fn, len0) {
    if(isArrayOrTypedArray(z)) {
        if(isArrayOrTypedArray(z[0])) {
            var len = len0;
            for(var i = 0; i < z.length; i++) {
                len = fn(len, z[i].length);
            }
            return len;
        } else {
            return z.length;
        }
    }
    return 0;
}


/***/ }),

/***/ "b+dc":
/*!******************************************************!*\
  !*** ./node_modules/browserify-sign/browser/sign.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(Buffer) {// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
var createHmac = __webpack_require__(/*! create-hmac */ "Giow")
var crt = __webpack_require__(/*! browserify-rsa */ "qVij")
var EC = __webpack_require__(/*! elliptic */ "MzeL").ec
var BN = __webpack_require__(/*! bn.js */ "OZ/i")
var parseKeys = __webpack_require__(/*! parse-asn1 */ "Ku4m")
var curves = __webpack_require__(/*! ./curves.json */ "zZGF")

function sign (hash, key, hashType, signType, tag) {
  var priv = parseKeys(key)
  if (priv.curve) {
    // rsa keys can be interpreted as ecdsa ones in openssl
    if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')
    return ecSign(hash, priv)
  } else if (priv.type === 'dsa') {
    if (signType !== 'dsa') throw new Error('wrong private key type')
    return dsaSign(hash, priv, hashType)
  } else {
    if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')
  }
  hash = Buffer.concat([tag, hash])
  var len = priv.modulus.byteLength()
  var pad = [ 0, 1 ]
  while (hash.length + pad.length + 1 < len) pad.push(0xff)
  pad.push(0x00)
  var i = -1
  while (++i < hash.length) pad.push(hash[i])

  var out = crt(pad, priv)
  return out
}

function ecSign (hash, priv) {
  var curveId = curves[priv.curve.join('.')]
  if (!curveId) throw new Error('unknown curve ' + priv.curve.join('.'))

  var curve = new EC(curveId)
  var key = curve.keyFromPrivate(priv.privateKey)
  var out = key.sign(hash)

  return new Buffer(out.toDER())
}

function dsaSign (hash, priv, algo) {
  var x = priv.params.priv_key
  var p = priv.params.p
  var q = priv.params.q
  var g = priv.params.g
  var r = new BN(0)
  var k
  var H = bits2int(hash, q).mod(q)
  var s = false
  var kv = getKey(x, q, hash, algo)
  while (s === false) {
    k = makeKey(q, kv, algo)
    r = makeR(g, k, p, q)
    s = k.invm(q).imul(H.add(x.mul(r))).mod(q)
    if (s.cmpn(0) === 0) {
      s = false
      r = new BN(0)
    }
  }
  return toDER(r, s)
}

function toDER (r, s) {
  r = r.toArray()
  s = s.toArray()

  // Pad values
  if (r[0] & 0x80) r = [ 0 ].concat(r)
  if (s[0] & 0x80) s = [ 0 ].concat(s)

  var total = r.length + s.length + 4
  var res = [ 0x30, total, 0x02, r.length ]
  res = res.concat(r, [ 0x02, s.length ], s)
  return new Buffer(res)
}

function getKey (x, q, hash, algo) {
  x = new Buffer(x.toArray())
  if (x.length < q.byteLength()) {
    var zeros = new Buffer(q.byteLength() - x.length)
    zeros.fill(0)
    x = Buffer.concat([ zeros, x ])
  }
  var hlen = hash.length
  var hbits = bits2octets(hash, q)
  var v = new Buffer(hlen)
  v.fill(1)
  var k = new Buffer(hlen)
  k.fill(0)
  k = createHmac(algo, k).update(v).update(new Buffer([ 0 ])).update(x).update(hbits).digest()
  v = createHmac(algo, k).update(v).digest()
  k = createHmac(algo, k).update(v).update(new Buffer([ 1 ])).update(x).update(hbits).digest()
  v = createHmac(algo, k).update(v).digest()
  return { k: k, v: v }
}

function bits2int (obits, q) {
  var bits = new BN(obits)
  var shift = (obits.length << 3) - q.bitLength()
  if (shift > 0) bits.ishrn(shift)
  return bits
}

function bits2octets (bits, q) {
  bits = bits2int(bits, q)
  bits = bits.mod(q)
  var out = new Buffer(bits.toArray())
  if (out.length < q.byteLength()) {
    var zeros = new Buffer(q.byteLength() - out.length)
    zeros.fill(0)
    out = Buffer.concat([ zeros, out ])
  }
  return out
}

function makeKey (q, kv, algo) {
  var t
  var k

  do {
    t = new Buffer(0)

    while (t.length * 8 < q.bitLength()) {
      kv.v = createHmac(algo, kv.k).update(kv.v).digest()
      t = Buffer.concat([ t, kv.v ])
    }

    k = bits2int(t, q)
    kv.k = createHmac(algo, kv.k).update(kv.v).update(new Buffer([ 0 ])).digest()
    kv.v = createHmac(algo, kv.k).update(kv.v).digest()
  } while (k.cmp(q) !== -1)

  return k
}

function makeR (g, k, p, q) {
  return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q)
}

module.exports = sign
module.exports.getKey = getKey
module.exports.makeKey = makeKey

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../buffer/index.js */ "tjlA").Buffer))

/***/ }),

/***/ "b1Dy":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/en-nz.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var enNz = moment.defineLocale('en-nz', {
    months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
    monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
    weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
    weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
    weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
    longDateFormat : {
        LT : 'h:mm A',
        LTS : 'h:mm:ss A',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY h:mm A',
        LLLL : 'dddd, D MMMM YYYY h:mm A'
    },
    calendar : {
        sameDay : '[Today at] LT',
        nextDay : '[Tomorrow at] LT',
        nextWeek : 'dddd [at] LT',
        lastDay : '[Yesterday at] LT',
        lastWeek : '[Last] dddd [at] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'in %s',
        past : '%s ago',
        s : 'a few seconds',
        ss : '%d seconds',
        m : 'a minute',
        mm : '%d minutes',
        h : 'an hour',
        hh : '%d hours',
        d : 'a day',
        dd : '%d days',
        M : 'a month',
        MM : '%d months',
        y : 'a year',
        yy : '%d years'
    },
    dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/,
    ordinal : function (number) {
        var b = number % 10,
            output = (~~(number % 100 / 10) === 1) ? 'th' :
            (b === 1) ? 'st' :
            (b === 2) ? 'nd' :
            (b === 3) ? 'rd' : 'th';
        return number + output;
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return enNz;

})));


/***/ }),

/***/ "b2z7":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_cloneRegExp.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;

/**
 * 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;
}

module.exports = cloneRegExp;


/***/ }),

/***/ "b4Vw":
/*!*************************************************************!*\
  !*** ./node_modules/mdi-react/CheckboxMarkedOutlineIcon.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var CheckboxMarkedOutlineIcon = function CheckboxMarkedOutlineIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M19,19H5V5H15V3H5C3.89,3 3,3.89 3,5V19C3,20.1 3.9,21 5,21H19C20.1,21 21,20.1 21,19V11H19M7.91,10.08L6.5,11.5L11,16L21,6L19.59,4.58L11,13.17L7.91,10.08Z' })
  );
};

module.exports = CheckboxMarkedOutlineIcon;


/***/ }),

/***/ "b70m":
/*!***************************************************!*\
  !*** ./node_modules/htmlparser2/lib/Tokenizer.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = Tokenizer;

var decodeCodePoint = __webpack_require__(/*! entities/lib/decode_codepoint.js */ "cHMM");
var entityMap = __webpack_require__(/*! entities/maps/entities.json */ "8PLQ");
var legacyMap = __webpack_require__(/*! entities/maps/legacy.json */ "kWb8");
var xmlMap = __webpack_require__(/*! entities/maps/xml.json */ "ZLJe");

var i = 0;

var TEXT = i++;
var BEFORE_TAG_NAME = i++; //after <
var IN_TAG_NAME = i++;
var IN_SELF_CLOSING_TAG = i++;
var BEFORE_CLOSING_TAG_NAME = i++;
var IN_CLOSING_TAG_NAME = i++;
var AFTER_CLOSING_TAG_NAME = i++;

//attributes
var BEFORE_ATTRIBUTE_NAME = i++;
var IN_ATTRIBUTE_NAME = i++;
var AFTER_ATTRIBUTE_NAME = i++;
var BEFORE_ATTRIBUTE_VALUE = i++;
var IN_ATTRIBUTE_VALUE_DQ = i++; // "
var IN_ATTRIBUTE_VALUE_SQ = i++; // '
var IN_ATTRIBUTE_VALUE_NQ = i++;

//declarations
var BEFORE_DECLARATION = i++; // !
var IN_DECLARATION = i++;

//processing instructions
var IN_PROCESSING_INSTRUCTION = i++; // ?

//comments
var BEFORE_COMMENT = i++;
var IN_COMMENT = i++;
var AFTER_COMMENT_1 = i++;
var AFTER_COMMENT_2 = i++;

//cdata
var BEFORE_CDATA_1 = i++; // [
var BEFORE_CDATA_2 = i++; // C
var BEFORE_CDATA_3 = i++; // D
var BEFORE_CDATA_4 = i++; // A
var BEFORE_CDATA_5 = i++; // T
var BEFORE_CDATA_6 = i++; // A
var IN_CDATA = i++; // [
var AFTER_CDATA_1 = i++; // ]
var AFTER_CDATA_2 = i++; // ]

//special tags
var BEFORE_SPECIAL = i++; //S
var BEFORE_SPECIAL_END = i++; //S

var BEFORE_SCRIPT_1 = i++; //C
var BEFORE_SCRIPT_2 = i++; //R
var BEFORE_SCRIPT_3 = i++; //I
var BEFORE_SCRIPT_4 = i++; //P
var BEFORE_SCRIPT_5 = i++; //T
var AFTER_SCRIPT_1 = i++; //C
var AFTER_SCRIPT_2 = i++; //R
var AFTER_SCRIPT_3 = i++; //I
var AFTER_SCRIPT_4 = i++; //P
var AFTER_SCRIPT_5 = i++; //T

var BEFORE_STYLE_1 = i++; //T
var BEFORE_STYLE_2 = i++; //Y
var BEFORE_STYLE_3 = i++; //L
var BEFORE_STYLE_4 = i++; //E
var AFTER_STYLE_1 = i++; //T
var AFTER_STYLE_2 = i++; //Y
var AFTER_STYLE_3 = i++; //L
var AFTER_STYLE_4 = i++; //E

var BEFORE_ENTITY = i++; //&
var BEFORE_NUMERIC_ENTITY = i++; //#
var IN_NAMED_ENTITY = i++;
var IN_NUMERIC_ENTITY = i++;
var IN_HEX_ENTITY = i++; //X

var j = 0;

var SPECIAL_NONE = j++;
var SPECIAL_SCRIPT = j++;
var SPECIAL_STYLE = j++;

function whitespace(c) {
    return c === " " || c === "\n" || c === "\t" || c === "\f" || c === "\r";
}

function ifElseState(upper, SUCCESS, FAILURE) {
    var lower = upper.toLowerCase();

    if (upper === lower) {
        return function(c) {
            if (c === lower) {
                this._state = SUCCESS;
            } else {
                this._state = FAILURE;
                this._index--;
            }
        };
    } else {
        return function(c) {
            if (c === lower || c === upper) {
                this._state = SUCCESS;
            } else {
                this._state = FAILURE;
                this._index--;
            }
        };
    }
}

function consumeSpecialNameChar(upper, NEXT_STATE) {
    var lower = upper.toLowerCase();

    return function(c) {
        if (c === lower || c === upper) {
            this._state = NEXT_STATE;
        } else {
            this._state = IN_TAG_NAME;
            this._index--; //consume the token again
        }
    };
}

function Tokenizer(options, cbs) {
    this._state = TEXT;
    this._buffer = "";
    this._sectionStart = 0;
    this._index = 0;
    this._bufferOffset = 0; //chars removed from _buffer
    this._baseState = TEXT;
    this._special = SPECIAL_NONE;
    this._cbs = cbs;
    this._running = true;
    this._ended = false;
    this._xmlMode = !!(options && options.xmlMode);
    this._decodeEntities = !!(options && options.decodeEntities);
}

Tokenizer.prototype._stateText = function(c) {
    if (c === "<") {
        if (this._index > this._sectionStart) {
            this._cbs.ontext(this._getSection());
        }
        this._state = BEFORE_TAG_NAME;
        this._sectionStart = this._index;
    } else if (
        this._decodeEntities &&
        this._special === SPECIAL_NONE &&
        c === "&"
    ) {
        if (this._index > this._sectionStart) {
            this._cbs.ontext(this._getSection());
        }
        this._baseState = TEXT;
        this._state = BEFORE_ENTITY;
        this._sectionStart = this._index;
    }
};

Tokenizer.prototype._stateBeforeTagName = function(c) {
    if (c === "/") {
        this._state = BEFORE_CLOSING_TAG_NAME;
    } else if (c === "<") {
        this._cbs.ontext(this._getSection());
        this._sectionStart = this._index;
    } else if (c === ">" || this._special !== SPECIAL_NONE || whitespace(c)) {
        this._state = TEXT;
    } else if (c === "!") {
        this._state = BEFORE_DECLARATION;
        this._sectionStart = this._index + 1;
    } else if (c === "?") {
        this._state = IN_PROCESSING_INSTRUCTION;
        this._sectionStart = this._index + 1;
    } else {
        this._state =
            !this._xmlMode && (c === "s" || c === "S")
                ? BEFORE_SPECIAL
                : IN_TAG_NAME;
        this._sectionStart = this._index;
    }
};

Tokenizer.prototype._stateInTagName = function(c) {
    if (c === "/" || c === ">" || whitespace(c)) {
        this._emitToken("onopentagname");
        this._state = BEFORE_ATTRIBUTE_NAME;
        this._index--;
    }
};

Tokenizer.prototype._stateBeforeCloseingTagName = function(c) {
    if (whitespace(c));
    else if (c === ">") {
        this._state = TEXT;
    } else if (this._special !== SPECIAL_NONE) {
        if (c === "s" || c === "S") {
            this._state = BEFORE_SPECIAL_END;
        } else {
            this._state = TEXT;
            this._index--;
        }
    } else {
        this._state = IN_CLOSING_TAG_NAME;
        this._sectionStart = this._index;
    }
};

Tokenizer.prototype._stateInCloseingTagName = function(c) {
    if (c === ">" || whitespace(c)) {
        this._emitToken("onclosetag");
        this._state = AFTER_CLOSING_TAG_NAME;
        this._index--;
    }
};

Tokenizer.prototype._stateAfterCloseingTagName = function(c) {
    //skip everything until ">"
    if (c === ">") {
        this._state = TEXT;
        this._sectionStart = this._index + 1;
    }
};

Tokenizer.prototype._stateBeforeAttributeName = function(c) {
    if (c === ">") {
        this._cbs.onopentagend();
        this._state = TEXT;
        this._sectionStart = this._index + 1;
    } else if (c === "/") {
        this._state = IN_SELF_CLOSING_TAG;
    } else if (!whitespace(c)) {
        this._state = IN_ATTRIBUTE_NAME;
        this._sectionStart = this._index;
    }
};

Tokenizer.prototype._stateInSelfClosingTag = function(c) {
    if (c === ">") {
        this._cbs.onselfclosingtag();
        this._state = TEXT;
        this._sectionStart = this._index + 1;
    } else if (!whitespace(c)) {
        this._state = BEFORE_ATTRIBUTE_NAME;
        this._index--;
    }
};

Tokenizer.prototype._stateInAttributeName = function(c) {
    if (c === "=" || c === "/" || c === ">" || whitespace(c)) {
        this._cbs.onattribname(this._getSection());
        this._sectionStart = -1;
        this._state = AFTER_ATTRIBUTE_NAME;
        this._index--;
    }
};

Tokenizer.prototype._stateAfterAttributeName = function(c) {
    if (c === "=") {
        this._state = BEFORE_ATTRIBUTE_VALUE;
    } else if (c === "/" || c === ">") {
        this._cbs.onattribend();
        this._state = BEFORE_ATTRIBUTE_NAME;
        this._index--;
    } else if (!whitespace(c)) {
        this._cbs.onattribend();
        this._state = IN_ATTRIBUTE_NAME;
        this._sectionStart = this._index;
    }
};

Tokenizer.prototype._stateBeforeAttributeValue = function(c) {
    if (c === '"') {
        this._state = IN_ATTRIBUTE_VALUE_DQ;
        this._sectionStart = this._index + 1;
    } else if (c === "'") {
        this._state = IN_ATTRIBUTE_VALUE_SQ;
        this._sectionStart = this._index + 1;
    } else if (!whitespace(c)) {
        this._state = IN_ATTRIBUTE_VALUE_NQ;
        this._sectionStart = this._index;
        this._index--; //reconsume token
    }
};

Tokenizer.prototype._stateInAttributeValueDoubleQuotes = function(c) {
    if (c === '"') {
        this._emitToken("onattribdata");
        this._cbs.onattribend();
        this._state = BEFORE_ATTRIBUTE_NAME;
    } else if (this._decodeEntities && c === "&") {
        this._emitToken("onattribdata");
        this._baseState = this._state;
        this._state = BEFORE_ENTITY;
        this._sectionStart = this._index;
    }
};

Tokenizer.prototype._stateInAttributeValueSingleQuotes = function(c) {
    if (c === "'") {
        this._emitToken("onattribdata");
        this._cbs.onattribend();
        this._state = BEFORE_ATTRIBUTE_NAME;
    } else if (this._decodeEntities && c === "&") {
        this._emitToken("onattribdata");
        this._baseState = this._state;
        this._state = BEFORE_ENTITY;
        this._sectionStart = this._index;
    }
};

Tokenizer.prototype._stateInAttributeValueNoQuotes = function(c) {
    if (whitespace(c) || c === ">") {
        this._emitToken("onattribdata");
        this._cbs.onattribend();
        this._state = BEFORE_ATTRIBUTE_NAME;
        this._index--;
    } else if (this._decodeEntities && c === "&") {
        this._emitToken("onattribdata");
        this._baseState = this._state;
        this._state = BEFORE_ENTITY;
        this._sectionStart = this._index;
    }
};

Tokenizer.prototype._stateBeforeDeclaration = function(c) {
    this._state =
        c === "["
            ? BEFORE_CDATA_1
            : c === "-"
                ? BEFORE_COMMENT
                : IN_DECLARATION;
};

Tokenizer.prototype._stateInDeclaration = function(c) {
    if (c === ">") {
        this._cbs.ondeclaration(this._getSection());
        this._state = TEXT;
        this._sectionStart = this._index + 1;
    }
};

Tokenizer.prototype._stateInProcessingInstruction = function(c) {
    if (c === ">") {
        this._cbs.onprocessinginstruction(this._getSection());
        this._state = TEXT;
        this._sectionStart = this._index + 1;
    }
};

Tokenizer.prototype._stateBeforeComment = function(c) {
    if (c === "-") {
        this._state = IN_COMMENT;
        this._sectionStart = this._index + 1;
    } else {
        this._state = IN_DECLARATION;
    }
};

Tokenizer.prototype._stateInComment = function(c) {
    if (c === "-") this._state = AFTER_COMMENT_1;
};

Tokenizer.prototype._stateAfterComment1 = function(c) {
    if (c === "-") {
        this._state = AFTER_COMMENT_2;
    } else {
        this._state = IN_COMMENT;
    }
};

Tokenizer.prototype._stateAfterComment2 = function(c) {
    if (c === ">") {
        //remove 2 trailing chars
        this._cbs.oncomment(
            this._buffer.substring(this._sectionStart, this._index - 2)
        );
        this._state = TEXT;
        this._sectionStart = this._index + 1;
    } else if (c !== "-") {
        this._state = IN_COMMENT;
    }
    // else: stay in AFTER_COMMENT_2 (`--->`)
};

Tokenizer.prototype._stateBeforeCdata1 = ifElseState(
    "C",
    BEFORE_CDATA_2,
    IN_DECLARATION
);
Tokenizer.prototype._stateBeforeCdata2 = ifElseState(
    "D",
    BEFORE_CDATA_3,
    IN_DECLARATION
);
Tokenizer.prototype._stateBeforeCdata3 = ifElseState(
    "A",
    BEFORE_CDATA_4,
    IN_DECLARATION
);
Tokenizer.prototype._stateBeforeCdata4 = ifElseState(
    "T",
    BEFORE_CDATA_5,
    IN_DECLARATION
);
Tokenizer.prototype._stateBeforeCdata5 = ifElseState(
    "A",
    BEFORE_CDATA_6,
    IN_DECLARATION
);

Tokenizer.prototype._stateBeforeCdata6 = function(c) {
    if (c === "[") {
        this._state = IN_CDATA;
        this._sectionStart = this._index + 1;
    } else {
        this._state = IN_DECLARATION;
        this._index--;
    }
};

Tokenizer.prototype._stateInCdata = function(c) {
    if (c === "]") this._state = AFTER_CDATA_1;
};

Tokenizer.prototype._stateAfterCdata1 = function(c) {
    if (c === "]") this._state = AFTER_CDATA_2;
    else this._state = IN_CDATA;
};

Tokenizer.prototype._stateAfterCdata2 = function(c) {
    if (c === ">") {
        //remove 2 trailing chars
        this._cbs.oncdata(
            this._buffer.substring(this._sectionStart, this._index - 2)
        );
        this._state = TEXT;
        this._sectionStart = this._index + 1;
    } else if (c !== "]") {
        this._state = IN_CDATA;
    }
    //else: stay in AFTER_CDATA_2 (`]]]>`)
};

Tokenizer.prototype._stateBeforeSpecial = function(c) {
    if (c === "c" || c === "C") {
        this._state = BEFORE_SCRIPT_1;
    } else if (c === "t" || c === "T") {
        this._state = BEFORE_STYLE_1;
    } else {
        this._state = IN_TAG_NAME;
        this._index--; //consume the token again
    }
};

Tokenizer.prototype._stateBeforeSpecialEnd = function(c) {
    if (this._special === SPECIAL_SCRIPT && (c === "c" || c === "C")) {
        this._state = AFTER_SCRIPT_1;
    } else if (this._special === SPECIAL_STYLE && (c === "t" || c === "T")) {
        this._state = AFTER_STYLE_1;
    } else this._state = TEXT;
};

Tokenizer.prototype._stateBeforeScript1 = consumeSpecialNameChar(
    "R",
    BEFORE_SCRIPT_2
);
Tokenizer.prototype._stateBeforeScript2 = consumeSpecialNameChar(
    "I",
    BEFORE_SCRIPT_3
);
Tokenizer.prototype._stateBeforeScript3 = consumeSpecialNameChar(
    "P",
    BEFORE_SCRIPT_4
);
Tokenizer.prototype._stateBeforeScript4 = consumeSpecialNameChar(
    "T",
    BEFORE_SCRIPT_5
);

Tokenizer.prototype._stateBeforeScript5 = function(c) {
    if (c === "/" || c === ">" || whitespace(c)) {
        this._special = SPECIAL_SCRIPT;
    }
    this._state = IN_TAG_NAME;
    this._index--; //consume the token again
};

Tokenizer.prototype._stateAfterScript1 = ifElseState("R", AFTER_SCRIPT_2, TEXT);
Tokenizer.prototype._stateAfterScript2 = ifElseState("I", AFTER_SCRIPT_3, TEXT);
Tokenizer.prototype._stateAfterScript3 = ifElseState("P", AFTER_SCRIPT_4, TEXT);
Tokenizer.prototype._stateAfterScript4 = ifElseState("T", AFTER_SCRIPT_5, TEXT);

Tokenizer.prototype._stateAfterScript5 = function(c) {
    if (c === ">" || whitespace(c)) {
        this._special = SPECIAL_NONE;
        this._state = IN_CLOSING_TAG_NAME;
        this._sectionStart = this._index - 6;
        this._index--; //reconsume the token
    } else this._state = TEXT;
};

Tokenizer.prototype._stateBeforeStyle1 = consumeSpecialNameChar(
    "Y",
    BEFORE_STYLE_2
);
Tokenizer.prototype._stateBeforeStyle2 = consumeSpecialNameChar(
    "L",
    BEFORE_STYLE_3
);
Tokenizer.prototype._stateBeforeStyle3 = consumeSpecialNameChar(
    "E",
    BEFORE_STYLE_4
);

Tokenizer.prototype._stateBeforeStyle4 = function(c) {
    if (c === "/" || c === ">" || whitespace(c)) {
        this._special = SPECIAL_STYLE;
    }
    this._state = IN_TAG_NAME;
    this._index--; //consume the token again
};

Tokenizer.prototype._stateAfterStyle1 = ifElseState("Y", AFTER_STYLE_2, TEXT);
Tokenizer.prototype._stateAfterStyle2 = ifElseState("L", AFTER_STYLE_3, TEXT);
Tokenizer.prototype._stateAfterStyle3 = ifElseState("E", AFTER_STYLE_4, TEXT);

Tokenizer.prototype._stateAfterStyle4 = function(c) {
    if (c === ">" || whitespace(c)) {
        this._special = SPECIAL_NONE;
        this._state = IN_CLOSING_TAG_NAME;
        this._sectionStart = this._index - 5;
        this._index--; //reconsume the token
    } else this._state = TEXT;
};

Tokenizer.prototype._stateBeforeEntity = ifElseState(
    "#",
    BEFORE_NUMERIC_ENTITY,
    IN_NAMED_ENTITY
);
Tokenizer.prototype._stateBeforeNumericEntity = ifElseState(
    "X",
    IN_HEX_ENTITY,
    IN_NUMERIC_ENTITY
);

//for entities terminated with a semicolon
Tokenizer.prototype._parseNamedEntityStrict = function() {
    //offset = 1
    if (this._sectionStart + 1 < this._index) {
        var entity = this._buffer.substring(
                this._sectionStart + 1,
                this._index
            ),
            map = this._xmlMode ? xmlMap : entityMap;

        if (map.hasOwnProperty(entity)) {
            this._emitPartial(map[entity]);
            this._sectionStart = this._index + 1;
        }
    }
};

//parses legacy entities (without trailing semicolon)
Tokenizer.prototype._parseLegacyEntity = function() {
    var start = this._sectionStart + 1,
        limit = this._index - start;

    if (limit > 6) limit = 6; //the max length of legacy entities is 6

    while (limit >= 2) {
        //the min length of legacy entities is 2
        var entity = this._buffer.substr(start, limit);

        if (legacyMap.hasOwnProperty(entity)) {
            this._emitPartial(legacyMap[entity]);
            this._sectionStart += limit + 1;
            return;
        } else {
            limit--;
        }
    }
};

Tokenizer.prototype._stateInNamedEntity = function(c) {
    if (c === ";") {
        this._parseNamedEntityStrict();
        if (this._sectionStart + 1 < this._index && !this._xmlMode) {
            this._parseLegacyEntity();
        }
        this._state = this._baseState;
    } else if (
        (c < "a" || c > "z") &&
        (c < "A" || c > "Z") &&
        (c < "0" || c > "9")
    ) {
        if (this._xmlMode);
        else if (this._sectionStart + 1 === this._index);
        else if (this._baseState !== TEXT) {
            if (c !== "=") {
                this._parseNamedEntityStrict();
            }
        } else {
            this._parseLegacyEntity();
        }

        this._state = this._baseState;
        this._index--;
    }
};

Tokenizer.prototype._decodeNumericEntity = function(offset, base) {
    var sectionStart = this._sectionStart + offset;

    if (sectionStart !== this._index) {
        //parse entity
        var entity = this._buffer.substring(sectionStart, this._index);
        var parsed = parseInt(entity, base);

        this._emitPartial(decodeCodePoint(parsed));
        this._sectionStart = this._index;
    } else {
        this._sectionStart--;
    }

    this._state = this._baseState;
};

Tokenizer.prototype._stateInNumericEntity = function(c) {
    if (c === ";") {
        this._decodeNumericEntity(2, 10);
        this._sectionStart++;
    } else if (c < "0" || c > "9") {
        if (!this._xmlMode) {
            this._decodeNumericEntity(2, 10);
        } else {
            this._state = this._baseState;
        }
        this._index--;
    }
};

Tokenizer.prototype._stateInHexEntity = function(c) {
    if (c === ";") {
        this._decodeNumericEntity(3, 16);
        this._sectionStart++;
    } else if (
        (c < "a" || c > "f") &&
        (c < "A" || c > "F") &&
        (c < "0" || c > "9")
    ) {
        if (!this._xmlMode) {
            this._decodeNumericEntity(3, 16);
        } else {
            this._state = this._baseState;
        }
        this._index--;
    }
};

Tokenizer.prototype._cleanup = function() {
    if (this._sectionStart < 0) {
        this._buffer = "";
        this._bufferOffset += this._index;
        this._index = 0;
    } else if (this._running) {
        if (this._state === TEXT) {
            if (this._sectionStart !== this._index) {
                this._cbs.ontext(this._buffer.substr(this._sectionStart));
            }
            this._buffer = "";
            this._bufferOffset += this._index;
            this._index = 0;
        } else if (this._sectionStart === this._index) {
            //the section just started
            this._buffer = "";
            this._bufferOffset += this._index;
            this._index = 0;
        } else {
            //remove everything unnecessary
            this._buffer = this._buffer.substr(this._sectionStart);
            this._index -= this._sectionStart;
            this._bufferOffset += this._sectionStart;
        }

        this._sectionStart = 0;
    }
};

//TODO make events conditional
Tokenizer.prototype.write = function(chunk) {
    if (this._ended) this._cbs.onerror(Error(".write() after done!"));

    this._buffer += chunk;
    this._parse();
};

Tokenizer.prototype._parse = function() {
    while (this._index < this._buffer.length && this._running) {
        var c = this._buffer.charAt(this._index);
        if (this._state === TEXT) {
            this._stateText(c);
        } else if (this._state === BEFORE_TAG_NAME) {
            this._stateBeforeTagName(c);
        } else if (this._state === IN_TAG_NAME) {
            this._stateInTagName(c);
        } else if (this._state === BEFORE_CLOSING_TAG_NAME) {
            this._stateBeforeCloseingTagName(c);
        } else if (this._state === IN_CLOSING_TAG_NAME) {
            this._stateInCloseingTagName(c);
        } else if (this._state === AFTER_CLOSING_TAG_NAME) {
            this._stateAfterCloseingTagName(c);
        } else if (this._state === IN_SELF_CLOSING_TAG) {
            this._stateInSelfClosingTag(c);
        } else if (this._state === BEFORE_ATTRIBUTE_NAME) {

        /*
		*	attributes
		*/
            this._stateBeforeAttributeName(c);
        } else if (this._state === IN_ATTRIBUTE_NAME) {
            this._stateInAttributeName(c);
        } else if (this._state === AFTER_ATTRIBUTE_NAME) {
            this._stateAfterAttributeName(c);
        } else if (this._state === BEFORE_ATTRIBUTE_VALUE) {
            this._stateBeforeAttributeValue(c);
        } else if (this._state === IN_ATTRIBUTE_VALUE_DQ) {
            this._stateInAttributeValueDoubleQuotes(c);
        } else if (this._state === IN_ATTRIBUTE_VALUE_SQ) {
            this._stateInAttributeValueSingleQuotes(c);
        } else if (this._state === IN_ATTRIBUTE_VALUE_NQ) {
            this._stateInAttributeValueNoQuotes(c);
        } else if (this._state === BEFORE_DECLARATION) {

        /*
		*	declarations
		*/
            this._stateBeforeDeclaration(c);
        } else if (this._state === IN_DECLARATION) {
            this._stateInDeclaration(c);
        } else if (this._state === IN_PROCESSING_INSTRUCTION) {

        /*
		*	processing instructions
		*/
            this._stateInProcessingInstruction(c);
        } else if (this._state === BEFORE_COMMENT) {

        /*
		*	comments
		*/
            this._stateBeforeComment(c);
        } else if (this._state === IN_COMMENT) {
            this._stateInComment(c);
        } else if (this._state === AFTER_COMMENT_1) {
            this._stateAfterComment1(c);
        } else if (this._state === AFTER_COMMENT_2) {
            this._stateAfterComment2(c);
        } else if (this._state === BEFORE_CDATA_1) {

        /*
		*	cdata
		*/
            this._stateBeforeCdata1(c);
        } else if (this._state === BEFORE_CDATA_2) {
            this._stateBeforeCdata2(c);
        } else if (this._state === BEFORE_CDATA_3) {
            this._stateBeforeCdata3(c);
        } else if (this._state === BEFORE_CDATA_4) {
            this._stateBeforeCdata4(c);
        } else if (this._state === BEFORE_CDATA_5) {
            this._stateBeforeCdata5(c);
        } else if (this._state === BEFORE_CDATA_6) {
            this._stateBeforeCdata6(c);
        } else if (this._state === IN_CDATA) {
            this._stateInCdata(c);
        } else if (this._state === AFTER_CDATA_1) {
            this._stateAfterCdata1(c);
        } else if (this._state === AFTER_CDATA_2) {
            this._stateAfterCdata2(c);
        } else if (this._state === BEFORE_SPECIAL) {

        /*
		* special tags
		*/
            this._stateBeforeSpecial(c);
        } else if (this._state === BEFORE_SPECIAL_END) {
            this._stateBeforeSpecialEnd(c);
        } else if (this._state === BEFORE_SCRIPT_1) {

        /*
		* script
		*/
            this._stateBeforeScript1(c);
        } else if (this._state === BEFORE_SCRIPT_2) {
            this._stateBeforeScript2(c);
        } else if (this._state === BEFORE_SCRIPT_3) {
            this._stateBeforeScript3(c);
        } else if (this._state === BEFORE_SCRIPT_4) {
            this._stateBeforeScript4(c);
        } else if (this._state === BEFORE_SCRIPT_5) {
            this._stateBeforeScript5(c);
        } else if (this._state === AFTER_SCRIPT_1) {
            this._stateAfterScript1(c);
        } else if (this._state === AFTER_SCRIPT_2) {
            this._stateAfterScript2(c);
        } else if (this._state === AFTER_SCRIPT_3) {
            this._stateAfterScript3(c);
        } else if (this._state === AFTER_SCRIPT_4) {
            this._stateAfterScript4(c);
        } else if (this._state === AFTER_SCRIPT_5) {
            this._stateAfterScript5(c);
        } else if (this._state === BEFORE_STYLE_1) {

        /*
		* style
		*/
            this._stateBeforeStyle1(c);
        } else if (this._state === BEFORE_STYLE_2) {
            this._stateBeforeStyle2(c);
        } else if (this._state === BEFORE_STYLE_3) {
            this._stateBeforeStyle3(c);
        } else if (this._state === BEFORE_STYLE_4) {
            this._stateBeforeStyle4(c);
        } else if (this._state === AFTER_STYLE_1) {
            this._stateAfterStyle1(c);
        } else if (this._state === AFTER_STYLE_2) {
            this._stateAfterStyle2(c);
        } else if (this._state === AFTER_STYLE_3) {
            this._stateAfterStyle3(c);
        } else if (this._state === AFTER_STYLE_4) {
            this._stateAfterStyle4(c);
        } else if (this._state === BEFORE_ENTITY) {

        /*
		* entities
		*/
            this._stateBeforeEntity(c);
        } else if (this._state === BEFORE_NUMERIC_ENTITY) {
            this._stateBeforeNumericEntity(c);
        } else if (this._state === IN_NAMED_ENTITY) {
            this._stateInNamedEntity(c);
        } else if (this._state === IN_NUMERIC_ENTITY) {
            this._stateInNumericEntity(c);
        } else if (this._state === IN_HEX_ENTITY) {
            this._stateInHexEntity(c);
        } else {
            this._cbs.onerror(Error("unknown _state"), this._state);
        }

        this._index++;
    }

    this._cleanup();
};

Tokenizer.prototype.pause = function() {
    this._running = false;
};
Tokenizer.prototype.resume = function() {
    this._running = true;

    if (this._index < this._buffer.length) {
        this._parse();
    }
    if (this._ended) {
        this._finish();
    }
};

Tokenizer.prototype.end = function(chunk) {
    if (this._ended) this._cbs.onerror(Error(".end() after done!"));
    if (chunk) this.write(chunk);

    this._ended = true;

    if (this._running) this._finish();
};

Tokenizer.prototype._finish = function() {
    //if there is remaining data, emit it in a reasonable way
    if (this._sectionStart < this._index) {
        this._handleTrailingData();
    }

    this._cbs.onend();
};

Tokenizer.prototype._handleTrailingData = function() {
    var data = this._buffer.substr(this._sectionStart);

    if (
        this._state === IN_CDATA ||
        this._state === AFTER_CDATA_1 ||
        this._state === AFTER_CDATA_2
    ) {
        this._cbs.oncdata(data);
    } else if (
        this._state === IN_COMMENT ||
        this._state === AFTER_COMMENT_1 ||
        this._state === AFTER_COMMENT_2
    ) {
        this._cbs.oncomment(data);
    } else if (this._state === IN_NAMED_ENTITY && !this._xmlMode) {
        this._parseLegacyEntity();
        if (this._sectionStart < this._index) {
            this._state = this._baseState;
            this._handleTrailingData();
        }
    } else if (this._state === IN_NUMERIC_ENTITY && !this._xmlMode) {
        this._decodeNumericEntity(2, 10);
        if (this._sectionStart < this._index) {
            this._state = this._baseState;
            this._handleTrailingData();
        }
    } else if (this._state === IN_HEX_ENTITY && !this._xmlMode) {
        this._decodeNumericEntity(3, 16);
        if (this._sectionStart < this._index) {
            this._state = this._baseState;
            this._handleTrailingData();
        }
    } else if (
        this._state !== IN_TAG_NAME &&
        this._state !== BEFORE_ATTRIBUTE_NAME &&
        this._state !== BEFORE_ATTRIBUTE_VALUE &&
        this._state !== AFTER_ATTRIBUTE_NAME &&
        this._state !== IN_ATTRIBUTE_NAME &&
        this._state !== IN_ATTRIBUTE_VALUE_SQ &&
        this._state !== IN_ATTRIBUTE_VALUE_DQ &&
        this._state !== IN_ATTRIBUTE_VALUE_NQ &&
        this._state !== IN_CLOSING_TAG_NAME
    ) {
        this._cbs.ontext(data);
    }
    //else, ignore remaining data
    //TODO add a way to remove current tag
};

Tokenizer.prototype.reset = function() {
    Tokenizer.call(
        this,
        { xmlMode: this._xmlMode, decodeEntities: this._decodeEntities },
        this._cbs
    );
};

Tokenizer.prototype.getAbsoluteIndex = function() {
    return this._bufferOffset + this._index;
};

Tokenizer.prototype._getSection = function() {
    return this._buffer.substring(this._sectionStart, this._index);
};

Tokenizer.prototype._emitToken = function(name) {
    this._cbs[name](this._getSection());
    this._sectionStart = -1;
};

Tokenizer.prototype._emitPartial = function(value) {
    if (this._baseState !== TEXT) {
        this._cbs.onattribdata(value); //TODO implement the new event
    } else {
        this._cbs.ontext(value);
    }
};


/***/ }),

/***/ "b80T":
/*!***********************************************!*\
  !*** ./node_modules/lodash/_arrayLikeKeys.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseTimes = __webpack_require__(/*! ./_baseTimes */ "UNi/"),
    isArguments = __webpack_require__(/*! ./isArguments */ "03A+"),
    isArray = __webpack_require__(/*! ./isArray */ "Z0cm"),
    isBuffer = __webpack_require__(/*! ./isBuffer */ "DSRE"),
    isIndex = __webpack_require__(/*! ./_isIndex */ "wJg7"),
    isTypedArray = __webpack_require__(/*! ./isTypedArray */ "c6wG");

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * 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;
}

module.exports = arrayLikeKeys;


/***/ }),

/***/ "b8PE":
/*!**********************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/filter_visible.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



/** Filter out object items with visible !== true
 *  insider array container.
 *
 *  @param {array of objects} container
 *  @return {array of objects} of length <= container
 *
 */
module.exports = function filterVisible(container) {
    var filterFn = isCalcData(container) ? calcDataFilter : baseFilter;
    var out = [];

    for(var i = 0; i < container.length; i++) {
        var item = container[i];
        if(filterFn(item)) out.push(item);
    }

    return out;
};

function baseFilter(item) {
    return item.visible === true;
}

function calcDataFilter(item) {
    return item[0].trace.visible === true;
}

function isCalcData(cont) {
    return (
        Array.isArray(cont) &&
        Array.isArray(cont[0]) &&
        cont[0][0] &&
        cont[0][0].trace
    );
}


/***/ }),

/***/ "bBy9":
/*!******************************************************************!*\
  !*** ./node_modules/core-js/library/modules/web.dom.iterable.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(/*! ./es6.array.iterator */ "w2d+");
var global = __webpack_require__(/*! ./_global */ "5T2Y");
var hide = __webpack_require__(/*! ./_hide */ "NegM");
var Iterators = __webpack_require__(/*! ./_iterators */ "SBuE");
var TO_STRING_TAG = __webpack_require__(/*! ./_wks */ "UWiX")('toStringTag');

var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' +
  'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' +
  'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' +
  'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' +
  'TextTrackList,TouchList').split(',');

for (var i = 0; i < DOMIterables.length; i++) {
  var NAME = DOMIterables[i];
  var Collection = global[NAME];
  var proto = Collection && Collection.prototype;
  if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME);
  Iterators[NAME] = Iterators.Array;
}


/***/ }),

/***/ "bFr3":
/*!********************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/anchor_utils.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/





/**
 * Determine the position anchor property of x/y xanchor/yanchor components.
 *
 * - values < 1/3 align the low side at that fraction,
 * - values [1/3, 2/3] align the center at that fraction,
 * - values > 2/3 align the right at that fraction.
 */


exports.isLeftAnchor = function isLeftAnchor(opts) {
    return (
      opts.xanchor === 'left' ||
      (opts.xanchor === 'auto' && opts.x <= 1 / 3)
    );
};

exports.isCenterAnchor = function isCenterAnchor(opts) {
    return (
        opts.xanchor === 'center' ||
        (opts.xanchor === 'auto' && opts.x > 1 / 3 && opts.x < 2 / 3)
    );
};

exports.isRightAnchor = function isRightAnchor(opts) {
    return (
      opts.xanchor === 'right' ||
      (opts.xanchor === 'auto' && opts.x >= 2 / 3)
    );
};

exports.isTopAnchor = function isTopAnchor(opts) {
    return (
        opts.yanchor === 'top' ||
        (opts.yanchor === 'auto' && opts.y >= 2 / 3)
    );
};

exports.isMiddleAnchor = function isMiddleAnchor(opts) {
    return (
        opts.yanchor === 'middle' ||
        (opts.yanchor === 'auto' && opts.y > 1 / 3 && opts.y < 2 / 3)
    );
};

exports.isBottomAnchor = function isBottomAnchor(opts) {
    return (
      opts.yanchor === 'bottom' ||
      (opts.yanchor === 'auto' && opts.y <= 1 / 3)
    );
};


/***/ }),

/***/ "bKup":
/*!***********************************************************!*\
  !*** ./node_modules/mdi-react/CalendarMultiselectIcon.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var CalendarMultiselectIcon = function CalendarMultiselectIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M19,19V8H5V19H19M16,1H18V3H19C20.1,3 21,3.9 21,5V19C21,20.1 20.1,21 19,21H5C3.89,21 3,20.1 3,19V5C3,3.89 3.89,3 5,3H6V1H8V3H16V1M7,10H9V12H7V10M15,10H17V12H15V10M11,14H13V16H11V14M15,14H17V16H15V14Z' })
  );
};

module.exports = CalendarMultiselectIcon;


/***/ }),

/***/ "bNQv":
/*!****************************************!*\
  !*** ./node_modules/lodash/forEach.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var arrayEach = __webpack_require__(/*! ./_arrayEach */ "gFfm"),
    baseEach = __webpack_require__(/*! ./_baseEach */ "SKAX"),
    castFunction = __webpack_require__(/*! ./_castFunction */ "EwQA"),
    isArray = __webpack_require__(/*! ./isArray */ "Z0cm");

/**
 * 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, castFunction(iteratee));
}

module.exports = forEach;


/***/ }),

/***/ "bNdj":
/*!*********************************************************!*\
  !*** ./node_modules/draft-js/lib/decodeEntityRanges.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule decodeEntityRanges
 * @format
 * 
 */



var UnicodeUtils = __webpack_require__(/*! fbjs/lib/UnicodeUtils */ "jLRO");

var substr = UnicodeUtils.substr;

/**
 * Convert to native JavaScript string lengths to determine ranges.
 */

function decodeEntityRanges(text, ranges) {
  var entities = Array(text.length).fill(null);
  if (ranges) {
    ranges.forEach(function (range) {
      // Using Unicode-enabled substrings converted to JavaScript lengths,
      // fill the output array with entity keys.
      var start = substr(text, 0, range.offset).length;
      var end = start + substr(text, range.offset, range.length).length;
      for (var ii = start; ii < end; ii++) {
        entities[ii] = range.key;
      }
    });
  }
  return entities;
}

module.exports = decodeEntityRanges;

/***/ }),

/***/ "bOMt":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/nb.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var nb = moment.defineLocale('nb', {
    months : 'januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember'.split('_'),
    monthsShort : 'jan._feb._mars_april_mai_juni_juli_aug._sep._okt._nov._des.'.split('_'),
    monthsParseExact : true,
    weekdays : 'søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag'.split('_'),
    weekdaysShort : 'sø._ma._ti._on._to._fr._lø.'.split('_'),
    weekdaysMin : 'sø_ma_ti_on_to_fr_lø'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D. MMMM YYYY',
        LLL : 'D. MMMM YYYY [kl.] HH:mm',
        LLLL : 'dddd D. MMMM YYYY [kl.] HH:mm'
    },
    calendar : {
        sameDay: '[i dag kl.] LT',
        nextDay: '[i morgen kl.] LT',
        nextWeek: 'dddd [kl.] LT',
        lastDay: '[i går kl.] LT',
        lastWeek: '[forrige] dddd [kl.] LT',
        sameElse: 'L'
    },
    relativeTime : {
        future : 'om %s',
        past : '%s siden',
        s : 'noen sekunder',
        ss : '%d sekunder',
        m : 'ett minutt',
        mm : '%d minutter',
        h : 'en time',
        hh : '%d timer',
        d : 'en dag',
        dd : '%d dager',
        M : 'en måned',
        MM : '%d måneder',
        y : 'ett år',
        yy : '%d år'
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return nb;

})));


/***/ }),

/***/ "bQVC":
/*!******************************************************!*\
  !*** ./node_modules/@jupyterlab/cells/lib/widget.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const attachments_1 = __webpack_require__(/*! @jupyterlab/attachments */ "5M+I");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const outputarea_1 = __webpack_require__(/*! @jupyterlab/outputarea */ "nGIF");
const rendermime_1 = __webpack_require__(/*! @jupyterlab/rendermime */ "Towz");
const coreutils_2 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const collapser_1 = __webpack_require__(/*! ./collapser */ "ca2I");
const headerfooter_1 = __webpack_require__(/*! ./headerfooter */ "IMnP");
const inputarea_1 = __webpack_require__(/*! ./inputarea */ "exNP");
const placeholder_1 = __webpack_require__(/*! ./placeholder */ "K7N2");
/**
 * The CSS class added to cell widgets.
 */
const CELL_CLASS = 'jp-Cell';
/**
 * The CSS class added to the cell header.
 */
const CELL_HEADER_CLASS = 'jp-Cell-header';
/**
 * The CSS class added to the cell footer.
 */
const CELL_FOOTER_CLASS = 'jp-Cell-footer';
/**
 * The CSS class added to the cell input wrapper.
 */
const CELL_INPUT_WRAPPER_CLASS = 'jp-Cell-inputWrapper';
/**
 * The CSS class added to the cell output wrapper.
 */
const CELL_OUTPUT_WRAPPER_CLASS = 'jp-Cell-outputWrapper';
/**
 * The CSS class added to the cell input area.
 */
const CELL_INPUT_AREA_CLASS = 'jp-Cell-inputArea';
/**
 * The CSS class added to the cell output area.
 */
const CELL_OUTPUT_AREA_CLASS = 'jp-Cell-outputArea';
/**
 * The CSS class added to the cell input collapser.
 */
const CELL_INPUT_COLLAPSER_CLASS = 'jp-Cell-inputCollapser';
/**
 * The CSS class added to the cell output collapser.
 */
const CELL_OUTPUT_COLLAPSER_CLASS = 'jp-Cell-outputCollapser';
/**
 * The class name added to the cell when collapsed.
 */
const COLLAPSED_CLASS = 'jp-mod-collapsed';
/**
 * The class name added to the cell when readonly.
 */
const READONLY_CLASS = 'jp-mod-readOnly';
/**
 * The class name added to code cells.
 */
const CODE_CELL_CLASS = 'jp-CodeCell';
/**
 * The class name added to markdown cells.
 */
const MARKDOWN_CELL_CLASS = 'jp-MarkdownCell';
/**
 * The class name added to rendered markdown output widgets.
 */
const MARKDOWN_OUTPUT_CLASS = 'jp-MarkdownOutput';
/**
 * The class name added to raw cells.
 */
const RAW_CELL_CLASS = 'jp-RawCell';
/**
 * The class name added to a rendered input area.
 */
const RENDERED_CLASS = 'jp-mod-rendered';
const NO_OUTPUTS_CLASS = 'jp-mod-noOutputs';
/**
 * The text applied to an empty markdown cell.
 */
const DEFAULT_MARKDOWN_TEXT = 'Type Markdown and LaTeX: $ α^2 $';
/**
 * The timeout to wait for change activity to have ceased before rendering.
 */
const RENDER_TIMEOUT = 1000;
/******************************************************************************
 * Cell
 ******************************************************************************/
/**
 * A base cell widget.
 */
class Cell extends widgets_1.Widget {
    /**
     * Construct a new base cell widget.
     */
    constructor(options) {
        super();
        this._readOnly = false;
        this._model = null;
        this._inputHidden = false;
        this._input = null;
        this._inputWrapper = null;
        this._inputPlaceholder = null;
        this.addClass(CELL_CLASS);
        let model = (this._model = options.model);
        let contentFactory = (this.contentFactory =
            options.contentFactory || Cell.defaultContentFactory);
        this.layout = new widgets_1.PanelLayout();
        // Header
        let header = contentFactory.createCellHeader();
        header.addClass(CELL_HEADER_CLASS);
        this.layout.addWidget(header);
        // Input
        let inputWrapper = (this._inputWrapper = new widgets_1.Panel());
        inputWrapper.addClass(CELL_INPUT_WRAPPER_CLASS);
        let inputCollapser = new collapser_1.InputCollapser();
        inputCollapser.addClass(CELL_INPUT_COLLAPSER_CLASS);
        let input = (this._input = new inputarea_1.InputArea({ model, contentFactory }));
        input.addClass(CELL_INPUT_AREA_CLASS);
        inputWrapper.addWidget(inputCollapser);
        inputWrapper.addWidget(input);
        this.layout.addWidget(inputWrapper);
        this._inputPlaceholder = new placeholder_1.InputPlaceholder(() => {
            this.inputHidden = !this.inputHidden;
        });
        // Footer
        let footer = this.contentFactory.createCellFooter();
        footer.addClass(CELL_FOOTER_CLASS);
        this.layout.addWidget(footer);
        // Editor settings
        if (options.editorConfig) {
            Object.keys(options.editorConfig).forEach((key) => {
                this.editor.setOption(key, options.editorConfig[key]);
            });
        }
    }
    /**
     * Modify some state for initialization.
     *
     * Should be called at the end of the subclasses's constructor.
     */
    initializeState() {
        const jupyter = this.model.metadata.get('jupyter') || {};
        this.inputHidden = jupyter.source_hidden === true;
        this._readOnly = this.model.metadata.get('editable') === false;
    }
    /**
     * Get the prompt node used by the cell.
     */
    get promptNode() {
        if (!this._inputHidden) {
            return this._input.promptNode;
        }
        else {
            return this._inputPlaceholder.node
                .firstElementChild;
        }
    }
    /**
     * Get the CodeEditorWrapper used by the cell.
     */
    get editorWidget() {
        return this._input.editorWidget;
    }
    /**
     * Get the CodeEditor used by the cell.
     */
    get editor() {
        return this._input.editor;
    }
    /**
     * Get the model used by the cell.
     */
    get model() {
        return this._model;
    }
    /**
     * Get the input area for the cell.
     */
    get inputArea() {
        return this._input;
    }
    /**
     * The read only state of the cell.
     */
    get readOnly() {
        return this._readOnly;
    }
    set readOnly(value) {
        if (value === this._readOnly) {
            return;
        }
        this._readOnly = value;
        this.update();
    }
    /**
     * A promise that resolves when the widget renders for the first time.
     */
    get ready() {
        return Promise.resolve(undefined);
    }
    /**
     * Set the prompt for the widget.
     */
    setPrompt(value) {
        this._input.setPrompt(value);
    }
    /**
     * The view state of input being hidden.
     */
    get inputHidden() {
        return this._inputHidden;
    }
    set inputHidden(value) {
        if (this._inputHidden === value) {
            return;
        }
        let layout = this._inputWrapper.layout;
        if (value) {
            this._input.parent = null;
            layout.addWidget(this._inputPlaceholder);
        }
        else {
            this._inputPlaceholder.parent = null;
            layout.addWidget(this._input);
        }
        this._inputHidden = value;
        this.handleInputHidden(value);
    }
    /**
     * Handle the input being hidden.
     *
     * #### Notes
     * This is called by the `inputHidden` setter so that subclasses
     * can perform actions upon the input being hidden without accessing
     * private state.
     */
    handleInputHidden(value) {
        return;
    }
    /**
     * Clone the cell, using the same model.
     */
    clone() {
        let constructor = this.constructor;
        return new constructor({
            model: this.model,
            contentFactory: this.contentFactory
        });
    }
    /**
     * Dispose of the resources held by the widget.
     */
    dispose() {
        // Do nothing if already disposed.
        if (this.isDisposed) {
            return;
        }
        this._input = null;
        this._model = null;
        this._inputWrapper = null;
        this._inputPlaceholder = null;
        super.dispose();
    }
    /**
     * Handle `after-attach` messages.
     */
    onAfterAttach(msg) {
        this.update();
    }
    /**
     * Handle `'activate-request'` messages.
     */
    onActivateRequest(msg) {
        this.editor.focus();
    }
    /**
     * Handle `update-request` messages.
     */
    onUpdateRequest(msg) {
        if (!this._model) {
            return;
        }
        // Handle read only state.
        if (this.editor.getOption('readOnly') !== this._readOnly) {
            this.editor.setOption('readOnly', this._readOnly);
            this.toggleClass(READONLY_CLASS, this._readOnly);
        }
    }
}
exports.Cell = Cell;
/**
 * The namespace for the `Cell` class statics.
 */
(function (Cell) {
    /**
     * The default implementation of an `IContentFactory`.
     *
     * This includes a CodeMirror editor factory to make it easy to use out of the box.
     */
    class ContentFactory {
        /**
         * Create a content factory for a cell.
         */
        constructor(options = {}) {
            this._editorFactory = null;
            this._editorFactory =
                options.editorFactory || inputarea_1.InputArea.defaultEditorFactory;
        }
        /**
         * The readonly editor factory that create code editors
         */
        get editorFactory() {
            return this._editorFactory;
        }
        /**
         * Create a new cell header for the parent widget.
         */
        createCellHeader() {
            return new headerfooter_1.CellHeader();
        }
        /**
         * Create a new cell header for the parent widget.
         */
        createCellFooter() {
            return new headerfooter_1.CellFooter();
        }
        /**
         * Create an input prompt.
         */
        createInputPrompt() {
            return new inputarea_1.InputPrompt();
        }
        /**
         * Create the output prompt for the widget.
         */
        createOutputPrompt() {
            return new outputarea_1.OutputPrompt();
        }
        /**
         * Create an stdin widget.
         */
        createStdin(options) {
            return new outputarea_1.Stdin(options);
        }
    }
    Cell.ContentFactory = ContentFactory;
    /**
     * The default content factory for cells.
     */
    Cell.defaultContentFactory = new ContentFactory();
})(Cell = exports.Cell || (exports.Cell = {}));
/******************************************************************************
 * CodeCell
 ******************************************************************************/
/**
 * A widget for a code cell.
 */
class CodeCell extends Cell {
    /**
     * Construct a code cell widget.
     */
    constructor(options) {
        super(options);
        this._rendermime = null;
        this._outputHidden = false;
        this._outputWrapper = null;
        this._outputPlaceholder = null;
        this._output = null;
        this.addClass(CODE_CELL_CLASS);
        // Only save options not handled by parent constructor.
        let rendermime = (this._rendermime = options.rendermime);
        let contentFactory = this.contentFactory;
        let model = this.model;
        // Insert the output before the cell footer.
        let outputWrapper = (this._outputWrapper = new widgets_1.Panel());
        outputWrapper.addClass(CELL_OUTPUT_WRAPPER_CLASS);
        let outputCollapser = new collapser_1.OutputCollapser();
        outputCollapser.addClass(CELL_OUTPUT_COLLAPSER_CLASS);
        let output = (this._output = new outputarea_1.OutputArea({
            model: model.outputs,
            rendermime,
            contentFactory: contentFactory
        }));
        output.addClass(CELL_OUTPUT_AREA_CLASS);
        // Set a CSS if there are no outputs, and connect a signal for future
        // changes to the number of outputs. This is for conditional styling
        // if there are no outputs.
        if (model.outputs.length === 0) {
            this.addClass(NO_OUTPUTS_CLASS);
        }
        output.outputLengthChanged.connect(this._outputLengthHandler, this);
        outputWrapper.addWidget(outputCollapser);
        outputWrapper.addWidget(output);
        this.layout.insertWidget(2, outputWrapper);
        this._outputPlaceholder = new placeholder_1.OutputPlaceholder(() => {
            this.outputHidden = !this.outputHidden;
        });
        // Modify state
        this.initializeState();
        model.stateChanged.connect(this.onStateChanged, this);
        model.metadata.changed.connect(this.onMetadataChanged, this);
    }
    /**
     * Modify some state for initialization.
     *
     * Should be called at the end of the subclasses's constructor.
     */
    initializeState() {
        super.initializeState();
        const metadataScrolled = this.model.metadata.get('scrolled');
        this.outputsScrolled = metadataScrolled === true;
        const jupyter = this.model.metadata.get('jupyter') || {};
        const collapsed = this.model.metadata.get('collapsed');
        this.outputHidden = collapsed === true || jupyter.outputs_hidden === true;
        this.setPrompt(`${this.model.executionCount || ''}`);
    }
    /**
     * Get the output area for the cell.
     */
    get outputArea() {
        return this._output;
    }
    /**
     * The view state of output being collapsed.
     */
    get outputHidden() {
        return this._outputHidden;
    }
    set outputHidden(value) {
        if (this._outputHidden === value) {
            return;
        }
        let layout = this._outputWrapper.layout;
        if (value) {
            layout.removeWidget(this._output);
            layout.addWidget(this._outputPlaceholder);
            if (this.inputHidden && !this._outputWrapper.isHidden) {
                this._outputWrapper.hide();
            }
        }
        else {
            if (this._outputWrapper.isHidden) {
                this._outputWrapper.show();
            }
            layout.removeWidget(this._outputPlaceholder);
            layout.addWidget(this._output);
        }
        this._outputHidden = value;
    }
    /**
     * Whether the output is in a scrolled state?
     */
    get outputsScrolled() {
        return this._outputsScrolled;
    }
    set outputsScrolled(value) {
        this.toggleClass('jp-mod-outputsScrolled', value);
        this._outputsScrolled = value;
    }
    /**
     * Handle the input being hidden.
     *
     * #### Notes
     * This method is called by the case cell implementation and is
     * subclasses here so the code cell can watch to see when input
     * is hidden without accessing private state.
     */
    handleInputHidden(value) {
        if (!value && this._outputWrapper.isHidden) {
            this._outputWrapper.show();
        }
        else if (value && !this._outputWrapper.isHidden && this._outputHidden) {
            this._outputWrapper.hide();
        }
    }
    /**
     * Clone the cell, using the same model.
     */
    clone() {
        let constructor = this.constructor;
        return new constructor({
            model: this.model,
            contentFactory: this.contentFactory,
            rendermime: this._rendermime
        });
    }
    /**
     * Clone the OutputArea alone, returning a simplified output area, using the same model.
     */
    cloneOutputArea() {
        return new outputarea_1.SimplifiedOutputArea({
            model: this.model.outputs,
            contentFactory: this.contentFactory,
            rendermime: this._rendermime
        });
    }
    /**
     * Dispose of the resources used by the widget.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._output.outputLengthChanged.disconnect(this._outputLengthHandler, this);
        this._rendermime = null;
        this._output = null;
        this._outputWrapper = null;
        this._outputPlaceholder = null;
        super.dispose();
    }
    /**
     * Handle `update-request` messages.
     */
    onUpdateRequest(msg) {
        let value = this.model.metadata.get('collapsed');
        this.toggleClass(COLLAPSED_CLASS, value);
        if (this._output) {
            // TODO: handle scrolled state.
        }
        super.onUpdateRequest(msg);
    }
    /**
     * Handle changes in the model.
     */
    onStateChanged(model, args) {
        switch (args.name) {
            case 'executionCount':
                this.setPrompt(`${model.executionCount || ''}`);
                break;
            default:
                break;
        }
    }
    /**
     * Handle changes in the metadata.
     */
    onMetadataChanged(model, args) {
        switch (args.key) {
            case 'collapsed':
            case 'scrolled':
                this.update();
                break;
            case 'editable':
                this.readOnly = !args.newValue;
                break;
            default:
                break;
        }
    }
    /**
     * Handle changes in the number of outputs in the output area.
     */
    _outputLengthHandler(sender, args) {
        let force = args === 0 ? true : false;
        this.toggleClass(NO_OUTPUTS_CLASS, force);
        /* Turn off scrolling outputs if there are none */
        if (force) {
            this.outputsScrolled = false;
        }
    }
}
exports.CodeCell = CodeCell;
/**
 * The namespace for the `CodeCell` class statics.
 */
(function (CodeCell) {
    /**
     * Execute a cell given a client session.
     */
    function execute(cell, session, metadata) {
        let model = cell.model;
        let code = model.value.text;
        if (!code.trim() || !session.kernel) {
            model.executionCount = null;
            model.outputs.clear();
            return Promise.resolve(void 0);
        }
        let cellId = { cellId: model.id };
        metadata = Object.assign({}, metadata, cellId);
        model.executionCount = null;
        cell.outputHidden = false;
        cell.setPrompt('*');
        model.trusted = true;
        return outputarea_1.OutputArea.execute(code, cell.outputArea, session, metadata)
            .then(msg => {
            model.executionCount = msg.content.execution_count;
            return msg;
        })
            .catch(e => {
            if (e.message === 'Canceled') {
                cell.setPrompt('');
            }
            throw e;
        });
    }
    CodeCell.execute = execute;
})(CodeCell = exports.CodeCell || (exports.CodeCell = {}));
/******************************************************************************
 * MarkdownCell
 ******************************************************************************/
/**
 * A widget for a Markdown cell.
 *
 * #### Notes
 * Things get complicated if we want the rendered text to update
 * any time the text changes, the text editor model changes,
 * or the input area model changes.  We don't support automatically
 * updating the rendered text in all of these cases.
 */
class MarkdownCell extends Cell {
    /**
     * Construct a Markdown cell widget.
     */
    constructor(options) {
        super(options);
        this._monitor = null;
        this._renderer = null;
        this._rendered = true;
        this._prevText = '';
        this._ready = new coreutils_2.PromiseDelegate();
        this.addClass(MARKDOWN_CELL_CLASS);
        // Ensure we can resolve attachments:
        this._rendermime = options.rendermime.clone({
            resolver: new attachments_1.AttachmentsResolver({
                parent: options.rendermime.resolver,
                model: this.model.attachments
            })
        });
        // Throttle the rendering rate of the widget.
        this._monitor = new coreutils_1.ActivityMonitor({
            signal: this.model.contentChanged,
            timeout: RENDER_TIMEOUT
        });
        this._monitor.activityStopped.connect(() => {
            if (this._rendered) {
                this.update();
            }
        }, this);
        this._updateRenderedInput().then(() => {
            this._ready.resolve(void 0);
        });
        super.initializeState();
    }
    /**
     * A promise that resolves when the widget renders for the first time.
     */
    get ready() {
        return this._ready.promise;
    }
    /**
     * Whether the cell is rendered.
     */
    get rendered() {
        return this._rendered;
    }
    set rendered(value) {
        if (value === this._rendered) {
            return;
        }
        this._rendered = value;
        this._handleRendered();
    }
    /**
     * Render an input instead of the text editor.
     */
    renderInput(widget) {
        this.addClass(RENDERED_CLASS);
        this.inputArea.renderInput(widget);
    }
    /**
     * Show the text editor instead of rendered input.
     */
    showEditor() {
        this.removeClass(RENDERED_CLASS);
        this.inputArea.showEditor();
    }
    /*
     * Handle `update-request` messages.
     */
    onUpdateRequest(msg) {
        // Make sure we are properly rendered.
        this._handleRendered();
        super.onUpdateRequest(msg);
    }
    /**
     * Handle the rendered state.
     */
    _handleRendered() {
        if (!this._rendered) {
            this.showEditor();
        }
        else {
            this._updateRenderedInput();
            this.renderInput(this._renderer);
        }
    }
    /**
     * Update the rendered input.
     */
    _updateRenderedInput() {
        let model = this.model;
        let text = (model && model.value.text) || DEFAULT_MARKDOWN_TEXT;
        // Do not re-render if the text has not changed.
        if (text !== this._prevText) {
            let mimeModel = new rendermime_1.MimeModel({ data: { 'text/markdown': text } });
            if (!this._renderer) {
                this._renderer = this._rendermime.createRenderer('text/markdown');
                this._renderer.addClass(MARKDOWN_OUTPUT_CLASS);
            }
            this._prevText = text;
            return this._renderer.renderModel(mimeModel);
        }
        return Promise.resolve(void 0);
    }
    /**
     * Clone the cell, using the same model.
     */
    clone() {
        let constructor = this.constructor;
        return new constructor({
            model: this.model,
            contentFactory: this.contentFactory,
            rendermime: this._rendermime
        });
    }
}
exports.MarkdownCell = MarkdownCell;
/******************************************************************************
 * RawCell
 ******************************************************************************/
/**
 * A widget for a raw cell.
 */
class RawCell extends Cell {
    /**
     * Construct a raw cell widget.
     */
    constructor(options) {
        super(options);
        this.addClass(RAW_CELL_CLASS);
        super.initializeState();
    }
    /**
     * Clone the cell, using the same model.
     */
    clone() {
        let constructor = this.constructor;
        return new constructor({
            model: this.model,
            contentFactory: this.contentFactory
        });
    }
}
exports.RawCell = RawCell;


/***/ }),

/***/ "bTsU":
/*!************************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/warning.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Represents a plugin’s warning. It can be created using {@link Node#warn}.
 *
 * @example
 * if ( decl.important ) {
 *     decl.warn(result, 'Avoid !important', { word: '!important' });
 * }
 */
var Warning = function () {

  /**
   * @param {string} text        - warning message
   * @param {Object} [opts]      - warning options
   * @param {Node}   opts.node   - CSS node that caused the warning
   * @param {string} opts.word   - word in CSS source that caused the warning
   * @param {number} opts.index  - index in CSS node string that caused
   *                               the warning
   * @param {string} opts.plugin - name of the plugin that created
   *                               this warning. {@link Result#warn} fills
   *                               this property automatically.
   */
  function Warning(text) {
    var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

    _classCallCheck(this, Warning);

    /**
     * @member {string} - Type to filter warnings from
     *                    {@link Result#messages}. Always equal
     *                    to `"warning"`.
     *
     * @example
     * const nonWarning = result.messages.filter(i => i.type !== 'warning')
     */
    this.type = 'warning';
    /**
     * @member {string} - The warning message.
     *
     * @example
     * warning.text //=> 'Try to avoid !important'
     */
    this.text = text;

    if (opts.node && opts.node.source) {
      var pos = opts.node.positionBy(opts);
      /**
       * @member {number} - Line in the input file
       *                    with this warning’s source
       *
       * @example
       * warning.line //=> 5
       */
      this.line = pos.line;
      /**
       * @member {number} - Column in the input file
       *                    with this warning’s source.
       *
       * @example
       * warning.column //=> 6
       */
      this.column = pos.column;
    }

    for (var opt in opts) {
      this[opt] = opts[opt];
    }
  }

  /**
   * Returns a warning position and message.
   *
   * @example
   * warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important'
   *
   * @return {string} warning position and message
   */


  Warning.prototype.toString = function toString() {
    if (this.node) {
      return this.node.error(this.text, {
        plugin: this.plugin,
        index: this.index,
        word: this.word
      }).message;
    } else if (this.plugin) {
      return this.plugin + ': ' + this.text;
    } else {
      return this.text;
    }
  };

  /**
   * @memberof Warning#
   * @member {string} plugin - The name of the plugin that created
   *                           it will fill this property automatically.
   *                           this warning. When you call {@link Node#warn}
   *
   * @example
   * warning.plugin //=> 'postcss-important'
   */

  /**
   * @memberof Warning#
   * @member {Node} node - Contains the CSS node that caused the warning.
   *
   * @example
   * warning.node.toString() //=> 'color: white !important'
   */

  return Warning;
}();

exports.default = Warning;
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64, 


/***/ }),

/***/ "bU+Y":
/*!************************************************************!*\
  !*** ./node_modules/@jupyter-widgets/base/lib/viewlist.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * - create_view and remove_view are default functions called when adding or removing views
 * - create_view takes a model and an index and returns a view or a promise for a view for that model
 * - remove_view takes a view and destroys it (including calling `view.remove()`)
 * - each time the update() function is called with a new list, the create and remove
 *   callbacks will be called in an order so that if you append the views created in the
 *   create callback and remove the views in the remove callback, you will duplicate
 *   the order of the list.
 * - the remove callback defaults to just removing the view (e.g., pass in null for the second parameter)
 * - the context defaults to the created ViewList.  If you pass another context, the create and remove
 *   will be called in that context.
 */
var ViewList = /** @class */ (function () {
    function ViewList(create_view, remove_view, context) {
        this.initialize(create_view, remove_view, context);
    }
    ViewList.prototype.initialize = function (create_view, remove_view, context) {
        this._handler_context = context || this;
        this._models = [];
        this.views = []; // list of promises for views
        this._create_view = create_view;
        this._remove_view = remove_view || function (view) { view.remove(); };
    };
    /**
     * the create_view, remove_view, and context arguments override the defaults
     * specified when the list is created.
     * after this function, the .views attribute is a list of promises for views
     * if you want to perform some action on the list of views, do something like
     * `Promise.all(myviewlist.views).then(function(views) {...});`
     */
    ViewList.prototype.update = function (new_models, create_view, remove_view, context) {
        var remove = remove_view || this._remove_view;
        var create = create_view || this._create_view;
        context = context || this._handler_context;
        var i = 0;
        // first, skip past the beginning of the lists if they are identical
        for (; i < new_models.length; i++) {
            if (i >= this._models.length || new_models[i] !== this._models[i]) {
                break;
            }
        }
        var first_removed = i;
        // Remove the non-matching items from the old list.
        var removed = this.views.splice(first_removed, this.views.length - first_removed);
        for (var j = 0; j < removed.length; j++) {
            removed[j].then(function (view) {
                remove.call(context, view);
            });
        }
        // Add the rest of the new list items.
        for (; i < new_models.length; i++) {
            this.views.push(Promise.resolve(create.call(context, new_models[i], i)));
        }
        // make a copy of the input array
        this._models = new_models.slice();
        // return a promise that resolves to all of the resolved views
        return Promise.all(this.views);
    };
    /**
     * removes every view in the list; convenience function for `.update([])`
     * that should be faster
     * returns a promise that resolves after this removal is done
     */
    ViewList.prototype.remove = function () {
        var _this = this;
        return Promise.all(this.views).then(function (views) {
            views.forEach(function (value) { return _this._remove_view.call(_this._handler_context, value); });
            _this.views = [];
            _this._models = [];
        });
    };
    /**
     * Dispose this viewlist.
     *
     * A synchronous function which just deletes references to child views. This
     * function does not call .remove() on child views because that is
     * asynchronous. Use this in cases where child views will be removed in
     * another way.
     */
    ViewList.prototype.dispose = function () {
        this.views = null;
        this._models = null;
    };
    return ViewList;
}());
exports.ViewList = ViewList;


/***/ }),

/***/ "bVuD":
/*!********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/default_panels/StyleTracesPanel.js ***!
  \********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _components = __webpack_require__(/*! ../components */ "yF51");

var _derived = __webpack_require__(/*! ../components/fields/derived */ "5og8");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var StyleTracesPanel = function StyleTracesPanel(props, _ref) {
  var _ = _ref.localize;
  return _react2.default.createElement(
    _components.TraceAccordion,
    { canGroup: true },
    _react2.default.createElement(_components.TextEditor, { label: _('Name'), attr: 'name', richTextOnly: true }),
    _react2.default.createElement(_components.NumericFraction, { label: _('Trace Opacity'), attr: 'opacity' }),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Legend') },
      _react2.default.createElement(
        _derived.ShowInLegend,
        {
          label: _('Show in Legend'),
          attr: 'showlegend',
          options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }],
          showOn: true
        },
        _react2.default.createElement(_components.GroupCreator, { label: _('Legend Group'), prefix: _('Group'), attr: 'legendgroup' })
      )
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Cones & Streamtubes') },
      _react2.default.createElement(_components.Numeric, { label: _('Size'), attr: 'sizeref', stepmode: 'relative' }),
      _react2.default.createElement(_components.Dropdown, {
        label: _('Size Mode'),
        options: [{ label: _('scaled'), value: 'scaled' }, { label: _('absolute'), value: 'absolute' }],
        attr: 'sizemode'
      }),
      _react2.default.createElement(_components.Dropdown, {
        label: _('Cone Anchor'),
        options: [{ label: _('Tip'), value: 'tip' }, { label: _('Tail'), value: 'tail' }, { label: _('Center'), value: 'center' }, { label: _('Center of Mass'), value: 'cm' }],
        attr: 'anchor'
      }),
      _react2.default.createElement(_components.Numeric, { label: _('Max Tube segments'), attr: 'maxdisplayed' })
    ),
    _react2.default.createElement(_components.MultiColorPicker, { label: _('Color'), attr: 'color' }),
    _react2.default.createElement(
      _components.TraceTypeSection,
      { name: _('Pie Colors'), traceTypes: ['pie'], mode: 'trace' },
      _react2.default.createElement(
        _components.LayoutSection,
        { attr: 'name' },
        _react2.default.createElement(_components.ColorwayPicker, { label: _('Colors'), attr: 'piecolorway' }),
        _react2.default.createElement(_components.Radio, {
          label: _('Extended Colors'),
          attr: 'extendpiecolors',
          options: [{ label: _('On'), value: true }, { label: _('Off'), value: false }]
        })
      )
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Pie Title'), attr: 'title.text' },
      _react2.default.createElement(_components.TextEditor, { label: _('Name'), attr: 'title.text' }),
      _react2.default.createElement(_components.Dropdown, {
        label: 'Title Position',
        attr: 'titleposition',
        options: [{ label: _('Top Left'), value: 'top left' }, { label: _('Top Center'), value: 'top center' }, { label: _('Top Right'), value: 'top right' }, { label: _('Middle Center'), value: 'middle center' }, { label: _('Bottom Left'), value: 'bottom left' }, { label: _('Bottom Center'), value: 'bottom center' }, { label: _('Bottom Right'), value: 'bottom right' }]
      }),
      _react2.default.createElement(_components.FontSelector, { label: _('Typeface'), attr: 'title.font.family', clearable: false }),
      _react2.default.createElement(_components.Numeric, { label: _('Font Size'), attr: 'title.font.size', units: 'px' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Values') },
      _react2.default.createElement(_derived.BinningDropdown, { label: _('Histogram Function'), attr: 'histfunc' }),
      _react2.default.createElement(_components.Dropdown, {
        label: _('Histogram Normalization'),
        options: [{ label: _('Number of Occurences'), value: '' }, { label: _('Percent'), value: 'percent' }, { label: _('Probability'), value: 'probability' }, { label: _('Density'), value: 'density' }, { label: _('Probability Density'), value: 'probability density' }],
        attr: 'histnorm'
      })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Cumulative') },
      _react2.default.createElement(_components.Radio, {
        label: _('Cumulative'),
        attr: 'cumulative.enabled',
        options: [{ label: _('Enabled'), value: true }, { label: _('Disabled'), value: false }]
      }),
      _react2.default.createElement(_components.Radio, {
        label: _('Direction'),
        attr: 'cumulative.direction',
        options: [{ label: _('Increasing'), value: 'increasing' }, { label: _('Decreasing'), value: 'decreasing' }]
      }),
      _react2.default.createElement(_components.Radio, {
        label: _('Current Bin'),
        attr: 'cumulative.currentbin',
        options: [{ label: _('Include'), value: 'include' }, { label: _('Exclude'), value: 'exclude' }, { label: _('Half'), value: 'half' }]
      })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Header') },
      _react2.default.createElement(_components.Numeric, { label: _('Height'), attr: 'header.height' }),
      _react2.default.createElement(_components.MultiColorPicker, { label: _('Fill Color'), attr: 'header.fill.color' }),
      _react2.default.createElement(_components.FontSelector, { label: _('Typeface'), attr: 'header.font.family' }),
      _react2.default.createElement(_components.Numeric, { label: _('Font Size'), attr: 'header.font.size' }),
      _react2.default.createElement(_components.Dropdown, {
        label: _('Text Alignment'),
        options: [{ label: _('Left'), value: 'left' }, { label: _('Center'), value: 'center' }, { label: _('Right'), value: 'right' }],
        attr: 'header.align'
      }),
      _react2.default.createElement(_components.MultiColorPicker, { label: _('Font Color'), attr: 'header.font.color' }),
      _react2.default.createElement(_components.Numeric, { label: _('Border Width'), attr: 'header.line.width' }),
      _react2.default.createElement(_components.MultiColorPicker, { label: _('Border Color'), attr: 'header.line.color' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Cells') },
      _react2.default.createElement(_components.Numeric, { label: _('Height'), attr: 'cells.height' }),
      _react2.default.createElement(_components.MultiColorPicker, { label: _('Fill Color'), attr: 'cells.fill.color' }),
      _react2.default.createElement(_components.FontSelector, { label: _('Typeface'), attr: 'cells.font.family' }),
      _react2.default.createElement(_components.Numeric, { label: _('Font Size'), attr: 'cells.font.size' }),
      _react2.default.createElement(_components.Dropdown, {
        label: _('Text Alignment'),
        options: [{ label: _('Left'), value: 'left' }, { label: _('Center'), value: 'center' }, { label: _('Right'), value: 'right' }],
        attr: 'cells.align'
      }),
      _react2.default.createElement(_components.MultiColorPicker, { label: _('Font Color'), attr: 'cells.font.color' }),
      _react2.default.createElement(_components.Numeric, { label: _('Border Width'), attr: 'cells.line.width' }),
      _react2.default.createElement(_components.MultiColorPicker, { label: _('Border Color'), attr: 'cells.line.color' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Display') },
      _react2.default.createElement(_components.Flaglist, {
        attr: 'mode',
        options: [{ label: _('Points'), value: 'markers' }, { label: _('Lines'), value: 'lines' }, { label: _('Text'), value: 'text' }]
      }),
      _react2.default.createElement(_components.Radio, {
        attr: 'flatshading',
        label: _('Flatshading'),
        options: [{ label: _('Enable'), value: true }, { label: _('Disable'), value: false }]
      })
    ),
    _react2.default.createElement(
      _components.TraceTypeSection,
      {
        name: _('Bar Grouping, Sizing and Spacing'),
        traceTypes: ['bar', 'histogram'],
        mode: 'trace'
      },
      _react2.default.createElement(
        _components.LayoutSection,
        { attr: 'name' },
        _react2.default.createElement(_components.Dropdown, {
          label: _('Bar Mode'),
          attr: 'barmode',
          options: [{ label: _('Grouped'), value: 'group' }, { label: _('Positive/Negative Stacked'), value: 'relative' }, { label: _('Strict Sum Stacked'), value: 'stack' }, { label: _('Overlaid'), value: 'overlay' }],
          clearable: false
        }),
        _react2.default.createElement(_components.Dropdown, {
          label: _('Normalization'),
          attr: 'barnorm',
          options: [{ label: _('None'), value: '' }, { label: _('Fraction'), value: 'fraction' }, { label: _('Percent'), value: 'percent' }],
          clearable: false
        }),
        _react2.default.createElement(_components.NumericFractionInverse, { label: _('Bar Width'), attr: 'bargap' }),
        _react2.default.createElement(_components.NumericFraction, { label: _('Bar Padding'), attr: 'bargroupgap' })
      )
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Binning') },
      _react2.default.createElement(_components.NumericOrDate, { label: _('X Bin Start'), attr: 'xbins.start', axis: 'x' }),
      _react2.default.createElement(_components.NumericOrDate, { label: _('X Bin End'), attr: 'xbins.end', axis: 'x' }),
      _react2.default.createElement(_components.Numeric, { label: _('Max X Bins'), attr: 'nbinsx' }),
      _react2.default.createElement(_components.AxisInterval, { label: _('X Bin Size'), attr: 'xbins.size', axis: 'x' }),
      _react2.default.createElement(_components.NumericOrDate, { label: _('Y Bin Start'), attr: 'ybins.start', axis: 'y' }),
      _react2.default.createElement(_components.NumericOrDate, { label: _('Y Bin End'), attr: 'ybins.end', axis: 'y' }),
      _react2.default.createElement(_components.Numeric, { label: _('Max Y Bins'), attr: 'nbinsy' }),
      _react2.default.createElement(_components.AxisInterval, { label: _('Y Bin Size'), attr: 'ybins.size', axis: 'y' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { label: _('Bar Position') },
      _react2.default.createElement(_components.NumericOrDate, { label: _('Base'), attr: 'base' }),
      _react2.default.createElement(_components.Numeric, { label: _('Offset'), attr: 'offset' }),
      _react2.default.createElement(_components.Numeric, { label: _('Width'), attr: 'width' })
    ),
    _react2.default.createElement(
      _components.TraceTypeSection,
      { name: _('Box Size and Spacing'), traceTypes: ['box'], mode: 'trace' },
      _react2.default.createElement(
        _components.LayoutSection,
        { attr: 'name' },
        _react2.default.createElement(_components.Radio, {
          label: _('Box Mode'),
          attr: 'boxmode',
          options: [{ label: _('Overlay'), value: 'overlay' }, { label: _('Group'), value: 'group' }]
        }),
        _react2.default.createElement(_components.NumericFractionInverse, { label: _('Box Width'), attr: 'boxgap' }),
        _react2.default.createElement(_components.NumericFraction, { label: _('Box Padding'), attr: 'boxgroupgap' })
      )
    ),
    _react2.default.createElement(
      _components.TraceTypeSection,
      { name: _('Violin Size and Spacing'), traceTypes: ['violin'], mode: 'trace' },
      _react2.default.createElement(
        _components.LayoutSection,
        { attr: 'name' },
        _react2.default.createElement(_components.Radio, {
          label: _('Violin Mode'),
          attr: 'violinmode',
          options: [{ label: _('Overlay'), value: 'overlay' }, { label: _('Group'), value: 'group' }]
        }),
        _react2.default.createElement(_components.NumericFractionInverse, { label: _('Violin Width'), attr: 'violingap' }),
        _react2.default.createElement(_components.NumericFraction, { label: _('Violin Padding'), attr: 'violingroupgap' })
      )
    ),
    _react2.default.createElement(_components.NumericFraction, { label: _('Whisker Width'), attr: 'whiskerwidth' }),
    _react2.default.createElement(
      _components.TraceMarkerSection,
      null,
      _react2.default.createElement(_components.Radio, {
        label: _('Order'),
        attr: 'sort',
        options: [{ label: _('Sorted'), value: true }, { label: _('Unsorted'), value: false }]
      }),
      _react2.default.createElement(_components.Radio, {
        label: _('Direction'),
        attr: 'direction',
        options: [{ label: _('Clockwise'), value: 'clockwise' }, { label: _('Counterclockwise'), value: 'counterclockwise' }]
      }),
      _react2.default.createElement(_components.Numeric, { label: _('Rotation'), attr: 'rotation' }),
      _react2.default.createElement(_components.NumericFraction, { label: _('Hole Size'), attr: 'hole' }),
      _react2.default.createElement(_components.NumericFraction, { label: _('Pull'), attr: 'pull' }),
      _react2.default.createElement(_components.Dropdown, {
        options: [{ label: _('Show All'), value: 'all' }, { label: _('Outliers'), value: 'outliers' }, { label: _('Suspected Outliers'), value: 'suspectedoutliers' }, { label: _('Hide'), value: false }],
        attr: 'boxpoints',
        clearable: false
      }),
      _react2.default.createElement(_components.Dropdown, {
        options: [{ label: _('Show All'), value: 'all' }, { label: _('Outliers'), value: 'outliers' }, { label: _('Suspected Outliers'), value: 'suspectedoutliers' }, { label: _('Hide'), value: false }],
        attr: 'points',
        clearable: false
      }),
      _react2.default.createElement(_components.NumericFraction, { label: _('Jitter'), attr: 'jitter' }),
      _react2.default.createElement(_components.Numeric, { label: _('Position'), attr: 'pointpos', step: 0.1, showSlider: true }),
      _react2.default.createElement(_components.MarkerColor, {
        suppressMultiValuedMessage: true,
        label: _('Color'),
        attr: 'marker.color',
        labelWidth: 80
      }),
      _react2.default.createElement(_components.NumericFraction, { label: _('Point Opacity'), attr: 'marker.opacity' }),
      _react2.default.createElement(_components.MarkerSize, { label: _('Size'), attr: 'marker.size' }),
      _react2.default.createElement(_derived.NumericReciprocal, {
        label: _('Size Scale'),
        attr: 'marker.sizeref',
        step: 0.2,
        stepmode: 'relative'
      }),
      _react2.default.createElement(_components.Radio, {
        label: _('Size Mode'),
        attr: 'marker.sizemode',
        options: [{ label: _('Area'), value: 'area' }, { label: _('Diameter'), value: 'diameter' }]
      }),
      _react2.default.createElement(_components.Numeric, { label: _('Minimum Size'), attr: 'marker.sizemin' }),
      _react2.default.createElement(_components.SymbolSelector, { label: _('Symbol'), attr: 'marker.symbol' }),
      _react2.default.createElement(_components.Numeric, { label: _('Border Width'), attr: 'marker.line.width' }),
      _react2.default.createElement(_components.MultiColorPicker, { label: _('Border Color'), attr: 'marker.line.color' }),
      _react2.default.createElement(_components.Numeric, { label: _('Max Number of Points'), attr: 'marker.maxdisplayed' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Ticks') },
      _react2.default.createElement(_components.Numeric, { label: _('Width'), attr: 'tickwidth' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Contours') },
      _react2.default.createElement(_components.Radio, {
        label: _('Type'),
        attr: 'contours.type',
        options: [{ label: _('Levels'), value: 'levels' }, { label: _('Constraint'), value: 'constraint' }]
      }),
      _react2.default.createElement(_components.Dropdown, {
        label: _('Coloring'),
        attr: 'contours.coloring',
        options: [{ label: _('Fill'), value: 'fill' }, { label: _('Heatmap'), value: 'heatmap' }, { label: _('Lines'), value: 'lines' }, { label: _('None'), value: 'none' }],
        clearable: false
      }),
      _react2.default.createElement(_components.Radio, {
        label: _('Contour Lines'),
        attr: 'contours.showlines',
        options: [{ label: _('On'), value: true }, { label: _('Off'), value: false }]
      }),
      _react2.default.createElement(_components.Radio, {
        label: _('Contour Labels'),
        attr: 'contours.showlabels',
        options: [{ label: _('On'), value: true }, { label: _('Off'), value: false }]
      }),
      _react2.default.createElement(_components.Radio, {
        label: _('Number of Contours'),
        attr: 'autocontour',
        options: [{ label: _('Auto'), value: true }, { label: _('Custom'), value: false }]
      }),
      _react2.default.createElement(_components.Numeric, { label: _('Max Contours'), attr: 'ncontours' }),
      _react2.default.createElement(_components.ContourNumeric, { label: _('Step Size'), attr: 'contours.size' }),
      _react2.default.createElement(_components.ContourNumeric, { label: _('Min Contour'), attr: 'contours.start' }),
      _react2.default.createElement(_components.ContourNumeric, { label: _('Max Contour'), attr: 'contours.end' })
    ),
    _react2.default.createElement(
      _components.TraceTypeSection,
      { name: _('Stacking'), traceTypes: ['scatter'], mode: 'trace' },
      _react2.default.createElement(_components.GroupCreator, { label: _('Group'), prefix: _('Stack'), attr: 'stackgroup' }),
      _react2.default.createElement(_components.Radio, {
        label: _('Gaps'),
        attr: 'stackgaps',
        options: [{ label: _('Infer Zero'), value: 'infer zero' }, { label: _('Interpolate'), value: 'interpolate' }]
      }),
      _react2.default.createElement(_components.Radio, {
        label: _('Orientation'),
        attr: 'orientation',
        options: [{ label: _('Horizontal'), value: 'h' }, { label: _('Vertical'), value: 'v' }]
      }),
      _react2.default.createElement(_components.Radio, {
        label: _('Normalization'),
        attr: 'groupnorm',
        options: [{ label: _('None'), value: '' }, { label: _('Fraction'), value: 'fraction' }, { label: _('Percent'), value: 'percent' }]
      })
    ),
    _react2.default.createElement(
      _components.TraceTypeSection,
      {
        name: _('Lines'),
        traceTypes: ['scatter', 'contour', 'scatterternary', 'scatterpolar', 'scatterpolargl', 'scatter3d', 'scattergl', 'scattergeo', 'scattermapbox', 'box', 'violin'],
        mode: 'trace'
      },
      _react2.default.createElement(_components.Numeric, { label: _('Width'), attr: 'line.width' }),
      _react2.default.createElement(_components.MultiColorPicker, { label: _('Color'), attr: 'line.color' }),
      _react2.default.createElement(_components.Radio, {
        label: _('Color Bar'),
        attr: 'line.showscale',
        options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
      }),
      _react2.default.createElement(_components.ColorscalePicker, { label: _('Colorscale'), attr: 'line.colorscale' }),
      _react2.default.createElement(_components.LineDashSelector, { label: _('Type'), attr: 'line.dash' }),
      _react2.default.createElement(_components.LineShapeSelector, { label: _('Shape'), attr: 'line.shape' }),
      _react2.default.createElement(_components.Numeric, { label: _('Smoothing'), attr: 'line.smoothing', showSlider: true, step: 0.1 }),
      _react2.default.createElement(_components.Radio, {
        label: _('Connect Gaps'),
        attr: 'connectgaps',
        options: [{ label: _('Connect'), value: true }, { label: _('Blank'), value: false }]
      })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Filled Area') },
      _react2.default.createElement(_components.FillDropdown, { attr: 'fill', label: _('Fill to') }),
      _react2.default.createElement(_components.MultiColorPicker, { label: _('Color'), attr: 'fillcolor' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Text Attributes') },
      _react2.default.createElement(_derived.TextInfo, { attr: 'textinfo' })
    ),
    _react2.default.createElement(
      _components.TraceTypeSection,
      {
        name: _('Text'),
        traceTypes: ['scatter', 'scattergl', 'scatterpolar', 'scatterpolargl', 'barpolar', 'pie', 'scatter3d', 'scatterternary', 'bar', 'scattergeo', 'scattermapbox'],
        mode: 'trace'
      },
      _react2.default.createElement(_components.DataSelector, { label: _('Text'), attr: 'text' }),
      _react2.default.createElement(_components.TextPosition, { label: _('Text Position'), attr: 'textposition' }),
      _react2.default.createElement(_components.FontSelector, { label: _('Typeface'), attr: 'textfont.family' }),
      _react2.default.createElement(_components.Numeric, { label: _('Font Size'), attr: 'textfont.size', units: 'px' }),
      _react2.default.createElement(_components.MultiColorPicker, { label: _('Font Color'), attr: 'textfont.color' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Colorscale') },
      _react2.default.createElement(_components.ColorscalePicker, { label: _('Colorscale'), attr: 'colorscale' }),
      _react2.default.createElement(_components.Radio, {
        label: _('Color Bar'),
        attr: 'showscale',
        options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
      }),
      _react2.default.createElement(_components.Radio, {
        label: _('Orientation'),
        attr: 'reversescale',
        options: [{ label: _('Normal'), value: false }, { label: _('Reversed'), value: true }]
      }),
      _react2.default.createElement(
        _components.VisibilitySelect,
        {
          label: _('Range'),
          attr: 'zauto',
          options: [{ label: _('Auto'), value: true }, { label: _('Custom'), value: false }],
          showOn: false,
          defaultOpt: true
        },
        _react2.default.createElement(_components.Numeric, { label: _('Min'), attr: 'zmin' }),
        _react2.default.createElement(_components.Numeric, { label: _('Max'), attr: 'zmax' })
      ),
      _react2.default.createElement(
        _components.VisibilitySelect,
        {
          label: _('Range'),
          attr: 'cauto',
          options: [{ label: _('Auto'), value: true }, { label: _('Custom'), value: false }],
          showOn: false,
          defaultOpt: true
        },
        _react2.default.createElement(_components.Numeric, { label: _('Min'), attr: 'cmin' }),
        _react2.default.createElement(_components.Numeric, { label: _('Max'), attr: 'cmax' })
      ),
      _react2.default.createElement(_components.Radio, {
        label: _('Smoothing'),
        attr: 'zsmooth',
        options: [{ label: _('On'), value: 'best' }, { label: _('Off'), value: false }]
      })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Gaps Between Cells') },
      _react2.default.createElement(_components.Numeric, { label: _('Horizontal Gap'), attr: 'xgap' }),
      _react2.default.createElement(_components.Numeric, { label: _('Vertical Gap'), attr: 'ygap' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Heatmap') },
      _react2.default.createElement(_components.Numeric, { label: _('Horizontal Gaps'), attr: 'xgap' }),
      _react2.default.createElement(_components.Numeric, { label: _('Vertical Gaps'), attr: 'ygap' })
    ),
    _react2.default.createElement(
      _components.TraceTypeSection,
      {
        name: _('Gaps in Data'),
        traceTypes: ['heatmap', 'contour', 'heatmapgl'],
        mode: 'trace'
      },
      _react2.default.createElement(_components.Radio, {
        label: _('Interpolate Gaps'),
        attr: 'connectgaps',
        options: [{ label: _('On'), value: true }, { label: _('Off'), value: false }]
      })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Lighting') },
      _react2.default.createElement(_components.NumericFraction, { label: _('Ambient'), attr: 'lighting.ambient' }),
      _react2.default.createElement(_components.NumericFraction, { label: _('Diffuse'), attr: 'lighting.diffuse' }),
      _react2.default.createElement(_components.NumericFraction, { label: _('Specular'), attr: 'lighting.specular' }),
      _react2.default.createElement(_components.NumericFraction, { label: _('Roughness'), attr: 'lighting.roughness' }),
      _react2.default.createElement(_components.NumericFraction, { label: _('Fresnel'), attr: 'lighting.fresnel' }),
      _react2.default.createElement(_components.NumericFraction, { label: _('Vertex Normal'), attr: 'lighting.vertexnormalsepsilon' }),
      _react2.default.createElement(_components.NumericFraction, { label: _('Face Normal'), attr: 'lighting.facenormalsepsilon' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Light Position') },
      _react2.default.createElement(_components.NumericFraction, { label: _('X'), attr: 'lightposition.x' }),
      _react2.default.createElement(_components.NumericFraction, { label: _('Y'), attr: 'lightposition.y' }),
      _react2.default.createElement(_components.NumericFraction, { label: _('Z'), attr: 'lightposition.z' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Increasing Trace Styles') },
      _react2.default.createElement(_components.TextEditor, { label: _('Name'), attr: 'increasing.name', richTextOnly: true }),
      _react2.default.createElement(_components.Numeric, { label: _('Width'), attr: 'increasing.line.width' }),
      _react2.default.createElement(_components.MultiColorPicker, { label: _('Line Color'), attr: 'increasing.line.color' }),
      _react2.default.createElement(_components.MultiColorPicker, { label: _('Fill Color'), attr: 'increasing.fillcolor' }),
      _react2.default.createElement(_components.LineDashSelector, { label: _('Type'), attr: 'increasing.line.dash' }),
      _react2.default.createElement(_components.Radio, {
        label: _('Show in Legend'),
        attr: 'increasing.showlegend',
        options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
      })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Decreasing Trace Styles') },
      _react2.default.createElement(_components.TextEditor, { label: _('Name'), attr: 'decreasing.name', richTextOnly: true }),
      _react2.default.createElement(_components.Numeric, { label: _('Width'), attr: 'decreasing.line.width' }),
      _react2.default.createElement(_components.MultiColorPicker, { label: _('Line Color'), attr: 'decreasing.line.color' }),
      _react2.default.createElement(_components.MultiColorPicker, { label: _('Fill Color'), attr: 'decreasing.fillcolor' }),
      _react2.default.createElement(_components.LineDashSelector, { label: _('Type'), attr: 'decreasing.line.dash' }),
      _react2.default.createElement(_components.Radio, {
        label: _('Show in Legend'),
        attr: 'decreasing.showlegend',
        options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
      })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Scaling') },
      _react2.default.createElement(_components.GroupCreator, { label: _('Scale Group'), prefix: _('Group'), attr: 'scalegroup' }),
      _react2.default.createElement(_components.Radio, {
        label: _('Scale Mode'),
        attr: 'scalemode',
        options: [{ label: _('Width'), value: 'width' }, { label: _('Count'), value: 'count' }]
      }),
      _react2.default.createElement(_components.Radio, {
        label: _('Span Mode'),
        attr: 'spanmode',
        options: [{ label: _('Soft'), value: 'soft' }, { label: _('Hard'), value: 'hard' }, { label: _('Manual'), value: 'manual' }]
      }),
      _react2.default.createElement(_components.Numeric, { label: _('Bandwidth'), attr: 'bandwidth' }),
      _react2.default.createElement(_components.Numeric, { label: _('Span'), attr: 'span' }),
      _react2.default.createElement(_components.Radio, {
        attr: 'side',
        label: _('Visible Sides'),
        options: [{ label: _('Both'), value: 'both' }, { label: _('Positive'), value: 'positive' }, { label: _('Negative'), value: 'negative' }]
      })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Box Mean') },
      _react2.default.createElement(_components.Radio, {
        attr: 'boxmean',
        options: [{ label: _('Mean'), value: true }, { label: _('Mean & SD'), value: 'sd' }, { label: _('None'), value: false }]
      })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Box') },
      _react2.default.createElement(_components.Radio, {
        attr: 'box.visible',
        options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
      }),
      _react2.default.createElement(_components.NumericFraction, { label: _('Box Width'), attr: 'box.width' }),
      _react2.default.createElement(_components.MultiColorPicker, { label: _('Box Fill Color'), attr: 'box.color' }),
      _react2.default.createElement(_components.NumericFraction, { label: _('Box Line Width'), attr: 'box.line.width' }),
      _react2.default.createElement(_components.MultiColorPicker, { label: _('Box Line Color'), attr: 'box.line.color' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Meanline') },
      _react2.default.createElement(_components.Radio, {
        attr: 'meanline.visible',
        options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
      }),
      _react2.default.createElement(_components.NumericFraction, { label: _('Meanline Width'), attr: 'meanline.width' }),
      _react2.default.createElement(_components.MultiColorPicker, { label: _('Meanline Color'), attr: 'meanline.color' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Hover/Tooltip Text') },
      _react2.default.createElement(_components.HoverTemplateSwitch, { attr: 'hovertemplate', label: _('Mode') }),
      _react2.default.createElement(_components.HoverInfo, { attr: 'hoverinfo', label: _('Show') }),
      _react2.default.createElement(_components.HoverTemplateText, { attr: 'hovertemplate', label: _('Template') }),
      _react2.default.createElement(_components.Radio, {
        label: _('Split labels'),
        attr: 'hoverlabel.split',
        options: [{ label: _('Yes'), value: true }, { label: _('No'), value: false }]
      }),
      _react2.default.createElement(
        _components.VisibilitySelect,
        {
          attr: 'contour.show',
          label: _('Show Contour'),
          options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }],
          showOn: true,
          defaultOpt: false
        },
        _react2.default.createElement(_components.MultiColorPicker, { label: _('Contour Color'), attr: 'contour.color' }),
        _react2.default.createElement(_components.Numeric, { label: _('Contour Width'), attr: 'contour.width' })
      )
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Hover Action') },
      _react2.default.createElement(_derived.HoveronDropdown, { attr: 'hoveron', label: _('Hover on') })
    ),
    _react2.default.createElement(
      _components.TraceTypeSection,
      {
        name: _('Error Bars X'),
        traceTypes: ['scatter', 'scattergl', 'scatter3d', 'bar'],
        mode: 'trace'
      },
      _react2.default.createElement(_components.ErrorBars, { attr: 'error_x' })
    ),
    _react2.default.createElement(
      _components.TraceTypeSection,
      {
        name: _('Error Bars Y'),
        traceTypes: ['scatter', 'scattergl', 'scatter3d', 'bar'],
        mode: 'trace'
      },
      _react2.default.createElement(_components.ErrorBars, { attr: 'error_y' })
    ),
    _react2.default.createElement(
      _components.TraceTypeSection,
      { name: _('Error Bars Z'), traceTypes: ['scatter3d'], mode: 'trace' },
      _react2.default.createElement(_components.ErrorBars, { attr: 'error_z' })
    )
  );
};

StyleTracesPanel.contextTypes = {
  localize: _propTypes2.default.func
};

exports.default = StyleTracesPanel;
//# sourceMappingURL=StyleTracesPanel.js.map

/***/ }),

/***/ "bWPq":
/*!*****************************************************!*\
  !*** ./node_modules/ajv/lib/dotjs/propertyNames.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_propertyNames(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  if (it.util.schemaHasRules($schema, it.RULES.all)) {
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    var $key = 'key' + $lvl,
      $idx = 'idx' + $lvl,
      $i = 'i' + $lvl,
      $invalidName = '\' + ' + $key + ' + \'',
      $dataNxt = $it.dataLevel = it.dataLevel + 1,
      $nextData = 'data' + $dataNxt,
      $dataProperties = 'dataProperties' + $lvl,
      $ownProperties = it.opts.ownProperties,
      $currentBaseId = it.baseId;
    out += ' var ' + ($errs) + ' = errors; ';
    if ($ownProperties) {
      out += ' var ' + ($dataProperties) + ' = undefined; ';
    }
    if ($ownProperties) {
      out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
    } else {
      out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
    }
    out += ' var startErrs' + ($lvl) + ' = errors; ';
    var $passData = $key;
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    var $code = it.validate($it);
    $it.baseId = $currentBaseId;
    if (it.util.varOccurences($code, $nextData) < 2) {
      out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
    } else {
      out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
    }
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + '<errors; ' + ($i) + '++) { vErrors[' + ($i) + '].propertyName = ' + ($key) + '; }   var err =   '; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ('propertyNames') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { propertyName: \'' + ($invalidName) + '\' } ';
      if (it.opts.messages !== false) {
        out += ' , message: \'property name \\\'' + ($invalidName) + '\\\' is invalid\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError(vErrors); ';
      } else {
        out += ' validate.errors = vErrors; return false; ';
      }
    }
    if ($breakOnError) {
      out += ' break; ';
    }
    out += ' } }';
  }
  if ($breakOnError) {
    out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
  }
  out = it.util.cleanUpCode(out);
  return out;
}


/***/ }),

/***/ "bXTP":
/*!****************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotTernaryContourIcon.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotTernaryContourIcon = function PlotTernaryContourIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M30.375 28.688L16 1.188 3.625 24.813l-2 3.875zM4.688 25.75c.375-.313 1.188-.688 2-.563.375 0 .625.25.938.563.375.625 1.188 1.188 2.125 1.563h-6zm14.125 1.563s.125 0 .25-.125c2.25-1.313 4.813-2.625 7.188-3.563l2 3.688zm-7.188-14.5c.5-.563 1.813-.688 3.438-.688s3.313.125 4.563.438l3.313 5.438c-1.875.125-3.625 0-5.5 0-3.563-.125-6-2.125-6-4.688-.125-.125 0-.25.188-.5zm5.688 6.5c1.063 0 2.313.125 3.375.125h2c-1.5 1.875-4.938 5.5-9.063 4-2.188-.875-4.188-2-5.875-3.438l2.625-4.938c.688 2.375 3.375 4.125 6.938 4.25zm2.437-8c-1.188-.125-5.063-.625-7.5-.125L16 4.125zm-12.687 9.75c1.875 1.5 3.875 2.563 6.125 3.5.813.25 1.625.375 2.438.375 4.25 0 7.438-3.875 8.625-5.5l1.5 2.813c-2.563 1.063-4.938 2.313-7.375 3.75-3.438 2-8.625.563-9.688-1.188a2.572 2.572 0 0 0-1.75-1.188H5.75z' })
    );
};

exports.default = PlotTernaryContourIcon;

/***/ }),

/***/ "bXm7":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/kk.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var suffixes = {
    0: '-ші',
    1: '-ші',
    2: '-ші',
    3: '-ші',
    4: '-ші',
    5: '-ші',
    6: '-шы',
    7: '-ші',
    8: '-ші',
    9: '-шы',
    10: '-шы',
    20: '-шы',
    30: '-шы',
    40: '-шы',
    50: '-ші',
    60: '-шы',
    70: '-ші',
    80: '-ші',
    90: '-шы',
    100: '-ші'
};

var kk = moment.defineLocale('kk', {
    months : 'қаңтар_ақпан_наурыз_сәуір_мамыр_маусым_шілде_тамыз_қыркүйек_қазан_қараша_желтоқсан'.split('_'),
    monthsShort : 'қаң_ақп_нау_сәу_мам_мау_шіл_там_қыр_қаз_қар_жел'.split('_'),
    weekdays : 'жексенбі_дүйсенбі_сейсенбі_сәрсенбі_бейсенбі_жұма_сенбі'.split('_'),
    weekdaysShort : 'жек_дүй_сей_сәр_бей_жұм_сен'.split('_'),
    weekdaysMin : 'жк_дй_сй_ср_бй_жм_сн'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd, D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay : '[Бүгін сағат] LT',
        nextDay : '[Ертең сағат] LT',
        nextWeek : 'dddd [сағат] LT',
        lastDay : '[Кеше сағат] LT',
        lastWeek : '[Өткен аптаның] dddd [сағат] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : '%s ішінде',
        past : '%s бұрын',
        s : 'бірнеше секунд',
        ss : '%d секунд',
        m : 'бір минут',
        mm : '%d минут',
        h : 'бір сағат',
        hh : '%d сағат',
        d : 'бір күн',
        dd : '%d күн',
        M : 'бір ай',
        MM : '%d ай',
        y : 'бір жыл',
        yy : '%d жыл'
    },
    dayOfMonthOrdinalParse: /\d{1,2}-(ші|шы)/,
    ordinal : function (number) {
        var a = number % 10,
            b = number >= 100 ? 100 : null;
        return number + (suffixes[number] || suffixes[a] || suffixes[b]);
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return kk;

})));


/***/ }),

/***/ "bYM6":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/ar-tn.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var arTn = moment.defineLocale('ar-tn', {
    months: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),
    monthsShort: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),
    weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
    weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),
    weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),
    weekdaysParseExact : true,
    longDateFormat: {
        LT: 'HH:mm',
        LTS: 'HH:mm:ss',
        L: 'DD/MM/YYYY',
        LL: 'D MMMM YYYY',
        LLL: 'D MMMM YYYY HH:mm',
        LLLL: 'dddd D MMMM YYYY HH:mm'
    },
    calendar: {
        sameDay: '[اليوم على الساعة] LT',
        nextDay: '[غدا على الساعة] LT',
        nextWeek: 'dddd [على الساعة] LT',
        lastDay: '[أمس على الساعة] LT',
        lastWeek: 'dddd [على الساعة] LT',
        sameElse: 'L'
    },
    relativeTime: {
        future: 'في %s',
        past: 'منذ %s',
        s: 'ثوان',
        ss : '%d ثانية',
        m: 'دقيقة',
        mm: '%d دقائق',
        h: 'ساعة',
        hh: '%d ساعات',
        d: 'يوم',
        dd: '%d أيام',
        M: 'شهر',
        MM: '%d أشهر',
        y: 'سنة',
        yy: '%d سنوات'
    },
    week: {
        dow: 1, // Monday is the first day of the week.
        doy: 4 // The week that contains Jan 4th is the first week of the year.
    }
});

return arTn;

})));


/***/ }),

/***/ "bZMm":
/*!********************************************!*\
  !*** ./node_modules/whatwg-fetch/fetch.js ***!
  \********************************************/
/*! exports provided: Headers, Request, Response, DOMException, fetch */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Headers", function() { return Headers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Request", function() { return Request; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Response", function() { return Response; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DOMException", function() { return DOMException; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fetch", function() { return fetch; });
var support = {
  searchParams: 'URLSearchParams' in self,
  iterable: 'Symbol' in self && 'iterator' in Symbol,
  blob:
    'FileReader' in self &&
    'Blob' in self &&
    (function() {
      try {
        new Blob()
        return true
      } catch (e) {
        return false
      }
    })(),
  formData: 'FormData' in self,
  arrayBuffer: 'ArrayBuffer' in self
}

function isDataView(obj) {
  return obj && DataView.prototype.isPrototypeOf(obj)
}

if (support.arrayBuffer) {
  var viewClasses = [
    '[object Int8Array]',
    '[object Uint8Array]',
    '[object Uint8ClampedArray]',
    '[object Int16Array]',
    '[object Uint16Array]',
    '[object Int32Array]',
    '[object Uint32Array]',
    '[object Float32Array]',
    '[object Float64Array]'
  ]

  var isArrayBufferView =
    ArrayBuffer.isView ||
    function(obj) {
      return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1
    }
}

function normalizeName(name) {
  if (typeof name !== 'string') {
    name = String(name)
  }
  if (/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(name)) {
    throw new TypeError('Invalid character in header field name')
  }
  return name.toLowerCase()
}

function normalizeValue(value) {
  if (typeof value !== 'string') {
    value = String(value)
  }
  return value
}

// Build a destructive iterator for the value list
function iteratorFor(items) {
  var iterator = {
    next: function() {
      var value = items.shift()
      return {done: value === undefined, value: value}
    }
  }

  if (support.iterable) {
    iterator[Symbol.iterator] = function() {
      return iterator
    }
  }

  return iterator
}

function Headers(headers) {
  this.map = {}

  if (headers instanceof Headers) {
    headers.forEach(function(value, name) {
      this.append(name, value)
    }, this)
  } else if (Array.isArray(headers)) {
    headers.forEach(function(header) {
      this.append(header[0], header[1])
    }, this)
  } else if (headers) {
    Object.getOwnPropertyNames(headers).forEach(function(name) {
      this.append(name, headers[name])
    }, this)
  }
}

Headers.prototype.append = function(name, value) {
  name = normalizeName(name)
  value = normalizeValue(value)
  var oldValue = this.map[name]
  this.map[name] = oldValue ? oldValue + ', ' + value : value
}

Headers.prototype['delete'] = function(name) {
  delete this.map[normalizeName(name)]
}

Headers.prototype.get = function(name) {
  name = normalizeName(name)
  return this.has(name) ? this.map[name] : null
}

Headers.prototype.has = function(name) {
  return this.map.hasOwnProperty(normalizeName(name))
}

Headers.prototype.set = function(name, value) {
  this.map[normalizeName(name)] = normalizeValue(value)
}

Headers.prototype.forEach = function(callback, thisArg) {
  for (var name in this.map) {
    if (this.map.hasOwnProperty(name)) {
      callback.call(thisArg, this.map[name], name, this)
    }
  }
}

Headers.prototype.keys = function() {
  var items = []
  this.forEach(function(value, name) {
    items.push(name)
  })
  return iteratorFor(items)
}

Headers.prototype.values = function() {
  var items = []
  this.forEach(function(value) {
    items.push(value)
  })
  return iteratorFor(items)
}

Headers.prototype.entries = function() {
  var items = []
  this.forEach(function(value, name) {
    items.push([name, value])
  })
  return iteratorFor(items)
}

if (support.iterable) {
  Headers.prototype[Symbol.iterator] = Headers.prototype.entries
}

function consumed(body) {
  if (body.bodyUsed) {
    return Promise.reject(new TypeError('Already read'))
  }
  body.bodyUsed = true
}

function fileReaderReady(reader) {
  return new Promise(function(resolve, reject) {
    reader.onload = function() {
      resolve(reader.result)
    }
    reader.onerror = function() {
      reject(reader.error)
    }
  })
}

function readBlobAsArrayBuffer(blob) {
  var reader = new FileReader()
  var promise = fileReaderReady(reader)
  reader.readAsArrayBuffer(blob)
  return promise
}

function readBlobAsText(blob) {
  var reader = new FileReader()
  var promise = fileReaderReady(reader)
  reader.readAsText(blob)
  return promise
}

function readArrayBufferAsText(buf) {
  var view = new Uint8Array(buf)
  var chars = new Array(view.length)

  for (var i = 0; i < view.length; i++) {
    chars[i] = String.fromCharCode(view[i])
  }
  return chars.join('')
}

function bufferClone(buf) {
  if (buf.slice) {
    return buf.slice(0)
  } else {
    var view = new Uint8Array(buf.byteLength)
    view.set(new Uint8Array(buf))
    return view.buffer
  }
}

function Body() {
  this.bodyUsed = false

  this._initBody = function(body) {
    this._bodyInit = body
    if (!body) {
      this._bodyText = ''
    } else if (typeof body === 'string') {
      this._bodyText = body
    } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
      this._bodyBlob = body
    } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
      this._bodyFormData = body
    } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
      this._bodyText = body.toString()
    } else if (support.arrayBuffer && support.blob && isDataView(body)) {
      this._bodyArrayBuffer = bufferClone(body.buffer)
      // IE 10-11 can't handle a DataView body.
      this._bodyInit = new Blob([this._bodyArrayBuffer])
    } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
      this._bodyArrayBuffer = bufferClone(body)
    } else {
      this._bodyText = body = Object.prototype.toString.call(body)
    }

    if (!this.headers.get('content-type')) {
      if (typeof body === 'string') {
        this.headers.set('content-type', 'text/plain;charset=UTF-8')
      } else if (this._bodyBlob && this._bodyBlob.type) {
        this.headers.set('content-type', this._bodyBlob.type)
      } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
        this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8')
      }
    }
  }

  if (support.blob) {
    this.blob = function() {
      var rejected = consumed(this)
      if (rejected) {
        return rejected
      }

      if (this._bodyBlob) {
        return Promise.resolve(this._bodyBlob)
      } else if (this._bodyArrayBuffer) {
        return Promise.resolve(new Blob([this._bodyArrayBuffer]))
      } else if (this._bodyFormData) {
        throw new Error('could not read FormData body as blob')
      } else {
        return Promise.resolve(new Blob([this._bodyText]))
      }
    }

    this.arrayBuffer = function() {
      if (this._bodyArrayBuffer) {
        return consumed(this) || Promise.resolve(this._bodyArrayBuffer)
      } else {
        return this.blob().then(readBlobAsArrayBuffer)
      }
    }
  }

  this.text = function() {
    var rejected = consumed(this)
    if (rejected) {
      return rejected
    }

    if (this._bodyBlob) {
      return readBlobAsText(this._bodyBlob)
    } else if (this._bodyArrayBuffer) {
      return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))
    } else if (this._bodyFormData) {
      throw new Error('could not read FormData body as text')
    } else {
      return Promise.resolve(this._bodyText)
    }
  }

  if (support.formData) {
    this.formData = function() {
      return this.text().then(decode)
    }
  }

  this.json = function() {
    return this.text().then(JSON.parse)
  }

  return this
}

// HTTP methods whose capitalization should be normalized
var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']

function normalizeMethod(method) {
  var upcased = method.toUpperCase()
  return methods.indexOf(upcased) > -1 ? upcased : method
}

function Request(input, options) {
  options = options || {}
  var body = options.body

  if (input instanceof Request) {
    if (input.bodyUsed) {
      throw new TypeError('Already read')
    }
    this.url = input.url
    this.credentials = input.credentials
    if (!options.headers) {
      this.headers = new Headers(input.headers)
    }
    this.method = input.method
    this.mode = input.mode
    this.signal = input.signal
    if (!body && input._bodyInit != null) {
      body = input._bodyInit
      input.bodyUsed = true
    }
  } else {
    this.url = String(input)
  }

  this.credentials = options.credentials || this.credentials || 'same-origin'
  if (options.headers || !this.headers) {
    this.headers = new Headers(options.headers)
  }
  this.method = normalizeMethod(options.method || this.method || 'GET')
  this.mode = options.mode || this.mode || null
  this.signal = options.signal || this.signal
  this.referrer = null

  if ((this.method === 'GET' || this.method === 'HEAD') && body) {
    throw new TypeError('Body not allowed for GET or HEAD requests')
  }
  this._initBody(body)
}

Request.prototype.clone = function() {
  return new Request(this, {body: this._bodyInit})
}

function decode(body) {
  var form = new FormData()
  body
    .trim()
    .split('&')
    .forEach(function(bytes) {
      if (bytes) {
        var split = bytes.split('=')
        var name = split.shift().replace(/\+/g, ' ')
        var value = split.join('=').replace(/\+/g, ' ')
        form.append(decodeURIComponent(name), decodeURIComponent(value))
      }
    })
  return form
}

function parseHeaders(rawHeaders) {
  var headers = new Headers()
  // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space
  // https://tools.ietf.org/html/rfc7230#section-3.2
  var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' ')
  preProcessedHeaders.split(/\r?\n/).forEach(function(line) {
    var parts = line.split(':')
    var key = parts.shift().trim()
    if (key) {
      var value = parts.join(':').trim()
      headers.append(key, value)
    }
  })
  return headers
}

Body.call(Request.prototype)

function Response(bodyInit, options) {
  if (!options) {
    options = {}
  }

  this.type = 'default'
  this.status = options.status === undefined ? 200 : options.status
  this.ok = this.status >= 200 && this.status < 300
  this.statusText = 'statusText' in options ? options.statusText : 'OK'
  this.headers = new Headers(options.headers)
  this.url = options.url || ''
  this._initBody(bodyInit)
}

Body.call(Response.prototype)

Response.prototype.clone = function() {
  return new Response(this._bodyInit, {
    status: this.status,
    statusText: this.statusText,
    headers: new Headers(this.headers),
    url: this.url
  })
}

Response.error = function() {
  var response = new Response(null, {status: 0, statusText: ''})
  response.type = 'error'
  return response
}

var redirectStatuses = [301, 302, 303, 307, 308]

Response.redirect = function(url, status) {
  if (redirectStatuses.indexOf(status) === -1) {
    throw new RangeError('Invalid status code')
  }

  return new Response(null, {status: status, headers: {location: url}})
}

var DOMException = self.DOMException
try {
  new DOMException()
} catch (err) {
  DOMException = function(message, name) {
    this.message = message
    this.name = name
    var error = Error(message)
    this.stack = error.stack
  }
  DOMException.prototype = Object.create(Error.prototype)
  DOMException.prototype.constructor = DOMException
}

function fetch(input, init) {
  return new Promise(function(resolve, reject) {
    var request = new Request(input, init)

    if (request.signal && request.signal.aborted) {
      return reject(new DOMException('Aborted', 'AbortError'))
    }

    var xhr = new XMLHttpRequest()

    function abortXhr() {
      xhr.abort()
    }

    xhr.onload = function() {
      var options = {
        status: xhr.status,
        statusText: xhr.statusText,
        headers: parseHeaders(xhr.getAllResponseHeaders() || '')
      }
      options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')
      var body = 'response' in xhr ? xhr.response : xhr.responseText
      resolve(new Response(body, options))
    }

    xhr.onerror = function() {
      reject(new TypeError('Network request failed'))
    }

    xhr.ontimeout = function() {
      reject(new TypeError('Network request failed'))
    }

    xhr.onabort = function() {
      reject(new DOMException('Aborted', 'AbortError'))
    }

    xhr.open(request.method, request.url, true)

    if (request.credentials === 'include') {
      xhr.withCredentials = true
    } else if (request.credentials === 'omit') {
      xhr.withCredentials = false
    }

    if ('responseType' in xhr && support.blob) {
      xhr.responseType = 'blob'
    }

    request.headers.forEach(function(value, name) {
      xhr.setRequestHeader(name, value)
    })

    if (request.signal) {
      request.signal.addEventListener('abort', abortXhr)

      xhr.onreadystatechange = function() {
        // DONE (success or failure)
        if (xhr.readyState === 4) {
          request.signal.removeEventListener('abort', abortXhr)
        }
      }
    }

    xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)
  })
}

fetch.polyfill = true

if (!self.fetch) {
  self.fetch = fetch
  self.Headers = Headers
  self.Request = Request
  self.Response = Response
}


/***/ }),

/***/ "bd9B":
/*!********************************************!*\
  !*** ./node_modules/fbjs/lib/mapObject.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */



var hasOwnProperty = Object.prototype.hasOwnProperty;

/**
 * Executes the provided `callback` once for each enumerable own property in the
 * object and constructs a new object from the results. The `callback` is
 * invoked with three arguments:
 *
 *  - the property value
 *  - the property name
 *  - the object being traversed
 *
 * Properties that are added after the call to `mapObject` will not be visited
 * by `callback`. If the values of existing properties are changed, the value
 * passed to `callback` will be the value at the time `mapObject` visits them.
 * Properties that are deleted before being visited are not visited.
 *
 * @grep function objectMap()
 * @grep function objMap()
 *
 * @param {?object} object
 * @param {function} callback
 * @param {*} context
 * @return {?object}
 */
function mapObject(object, callback, context) {
  if (!object) {
    return null;
  }
  var result = {};
  for (var name in object) {
    if (hasOwnProperty.call(object, name)) {
      result[name] = callback.call(context, object[name], name, object);
    }
  }
  return result;
}

module.exports = mapObject;

/***/ }),

/***/ "bdgK":
/*!*************************************************************************!*\
  !*** ./node_modules/resize-observer-polyfill/dist/ResizeObserver.es.js ***!
  \*************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(global) {/**
 * A collection of shims that provide minimal functionality of the ES6 collections.
 *
 * These implementations are not meant to be used outside of the ResizeObserver
 * modules as they cover only a limited range of use cases.
 */
/* eslint-disable require-jsdoc, valid-jsdoc */
var MapShim = (function () {
    if (typeof Map !== 'undefined') {
        return Map;
    }
    /**
     * Returns index in provided array that matches the specified key.
     *
     * @param {Array<Array>} arr
     * @param {*} key
     * @returns {number}
     */
    function getIndex(arr, key) {
        var result = -1;
        arr.some(function (entry, index) {
            if (entry[0] === key) {
                result = index;
                return true;
            }
            return false;
        });
        return result;
    }
    return /** @class */ (function () {
        function class_1() {
            this.__entries__ = [];
        }
        Object.defineProperty(class_1.prototype, "size", {
            /**
             * @returns {boolean}
             */
            get: function () {
                return this.__entries__.length;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * @param {*} key
         * @returns {*}
         */
        class_1.prototype.get = function (key) {
            var index = getIndex(this.__entries__, key);
            var entry = this.__entries__[index];
            return entry && entry[1];
        };
        /**
         * @param {*} key
         * @param {*} value
         * @returns {void}
         */
        class_1.prototype.set = function (key, value) {
            var index = getIndex(this.__entries__, key);
            if (~index) {
                this.__entries__[index][1] = value;
            }
            else {
                this.__entries__.push([key, value]);
            }
        };
        /**
         * @param {*} key
         * @returns {void}
         */
        class_1.prototype.delete = function (key) {
            var entries = this.__entries__;
            var index = getIndex(entries, key);
            if (~index) {
                entries.splice(index, 1);
            }
        };
        /**
         * @param {*} key
         * @returns {void}
         */
        class_1.prototype.has = function (key) {
            return !!~getIndex(this.__entries__, key);
        };
        /**
         * @returns {void}
         */
        class_1.prototype.clear = function () {
            this.__entries__.splice(0);
        };
        /**
         * @param {Function} callback
         * @param {*} [ctx=null]
         * @returns {void}
         */
        class_1.prototype.forEach = function (callback, ctx) {
            if (ctx === void 0) { ctx = null; }
            for (var _i = 0, _a = this.__entries__; _i < _a.length; _i++) {
                var entry = _a[_i];
                callback.call(ctx, entry[1], entry[0]);
            }
        };
        return class_1;
    }());
})();

/**
 * Detects whether window and document objects are available in current environment.
 */
var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && window.document === document;

// Returns global object of a current environment.
var global$1 = (function () {
    if (typeof global !== 'undefined' && global.Math === Math) {
        return global;
    }
    if (typeof self !== 'undefined' && self.Math === Math) {
        return self;
    }
    if (typeof window !== 'undefined' && window.Math === Math) {
        return window;
    }
    // eslint-disable-next-line no-new-func
    return Function('return this')();
})();

/**
 * A shim for the requestAnimationFrame which falls back to the setTimeout if
 * first one is not supported.
 *
 * @returns {number} Requests' identifier.
 */
var requestAnimationFrame$1 = (function () {
    if (typeof requestAnimationFrame === 'function') {
        // It's required to use a bounded function because IE sometimes throws
        // an "Invalid calling object" error if rAF is invoked without the global
        // object on the left hand side.
        return requestAnimationFrame.bind(global$1);
    }
    return function (callback) { return setTimeout(function () { return callback(Date.now()); }, 1000 / 60); };
})();

// Defines minimum timeout before adding a trailing call.
var trailingTimeout = 2;
/**
 * Creates a wrapper function which ensures that provided callback will be
 * invoked only once during the specified delay period.
 *
 * @param {Function} callback - Function to be invoked after the delay period.
 * @param {number} delay - Delay after which to invoke callback.
 * @returns {Function}
 */
function throttle (callback, delay) {
    var leadingCall = false, trailingCall = false, lastCallTime = 0;
    /**
     * Invokes the original callback function and schedules new invocation if
     * the "proxy" was called during current request.
     *
     * @returns {void}
     */
    function resolvePending() {
        if (leadingCall) {
            leadingCall = false;
            callback();
        }
        if (trailingCall) {
            proxy();
        }
    }
    /**
     * Callback invoked after the specified delay. It will further postpone
     * invocation of the original function delegating it to the
     * requestAnimationFrame.
     *
     * @returns {void}
     */
    function timeoutCallback() {
        requestAnimationFrame$1(resolvePending);
    }
    /**
     * Schedules invocation of the original function.
     *
     * @returns {void}
     */
    function proxy() {
        var timeStamp = Date.now();
        if (leadingCall) {
            // Reject immediately following calls.
            if (timeStamp - lastCallTime < trailingTimeout) {
                return;
            }
            // Schedule new call to be in invoked when the pending one is resolved.
            // This is important for "transitions" which never actually start
            // immediately so there is a chance that we might miss one if change
            // happens amids the pending invocation.
            trailingCall = true;
        }
        else {
            leadingCall = true;
            trailingCall = false;
            setTimeout(timeoutCallback, delay);
        }
        lastCallTime = timeStamp;
    }
    return proxy;
}

// Minimum delay before invoking the update of observers.
var REFRESH_DELAY = 20;
// A list of substrings of CSS properties used to find transition events that
// might affect dimensions of observed elements.
var transitionKeys = ['top', 'right', 'bottom', 'left', 'width', 'height', 'size', 'weight'];
// Check if MutationObserver is available.
var mutationObserverSupported = typeof MutationObserver !== 'undefined';
/**
 * Singleton controller class which handles updates of ResizeObserver instances.
 */
var ResizeObserverController = /** @class */ (function () {
    /**
     * Creates a new instance of ResizeObserverController.
     *
     * @private
     */
    function ResizeObserverController() {
        /**
         * Indicates whether DOM listeners have been added.
         *
         * @private {boolean}
         */
        this.connected_ = false;
        /**
         * Tells that controller has subscribed for Mutation Events.
         *
         * @private {boolean}
         */
        this.mutationEventsAdded_ = false;
        /**
         * Keeps reference to the instance of MutationObserver.
         *
         * @private {MutationObserver}
         */
        this.mutationsObserver_ = null;
        /**
         * A list of connected observers.
         *
         * @private {Array<ResizeObserverSPI>}
         */
        this.observers_ = [];
        this.onTransitionEnd_ = this.onTransitionEnd_.bind(this);
        this.refresh = throttle(this.refresh.bind(this), REFRESH_DELAY);
    }
    /**
     * Adds observer to observers list.
     *
     * @param {ResizeObserverSPI} observer - Observer to be added.
     * @returns {void}
     */
    ResizeObserverController.prototype.addObserver = function (observer) {
        if (!~this.observers_.indexOf(observer)) {
            this.observers_.push(observer);
        }
        // Add listeners if they haven't been added yet.
        if (!this.connected_) {
            this.connect_();
        }
    };
    /**
     * Removes observer from observers list.
     *
     * @param {ResizeObserverSPI} observer - Observer to be removed.
     * @returns {void}
     */
    ResizeObserverController.prototype.removeObserver = function (observer) {
        var observers = this.observers_;
        var index = observers.indexOf(observer);
        // Remove observer if it's present in registry.
        if (~index) {
            observers.splice(index, 1);
        }
        // Remove listeners if controller has no connected observers.
        if (!observers.length && this.connected_) {
            this.disconnect_();
        }
    };
    /**
     * Invokes the update of observers. It will continue running updates insofar
     * it detects changes.
     *
     * @returns {void}
     */
    ResizeObserverController.prototype.refresh = function () {
        var changesDetected = this.updateObservers_();
        // Continue running updates if changes have been detected as there might
        // be future ones caused by CSS transitions.
        if (changesDetected) {
            this.refresh();
        }
    };
    /**
     * Updates every observer from observers list and notifies them of queued
     * entries.
     *
     * @private
     * @returns {boolean} Returns "true" if any observer has detected changes in
     *      dimensions of it's elements.
     */
    ResizeObserverController.prototype.updateObservers_ = function () {
        // Collect observers that have active observations.
        var activeObservers = this.observers_.filter(function (observer) {
            return observer.gatherActive(), observer.hasActive();
        });
        // Deliver notifications in a separate cycle in order to avoid any
        // collisions between observers, e.g. when multiple instances of
        // ResizeObserver are tracking the same element and the callback of one
        // of them changes content dimensions of the observed target. Sometimes
        // this may result in notifications being blocked for the rest of observers.
        activeObservers.forEach(function (observer) { return observer.broadcastActive(); });
        return activeObservers.length > 0;
    };
    /**
     * Initializes DOM listeners.
     *
     * @private
     * @returns {void}
     */
    ResizeObserverController.prototype.connect_ = function () {
        // Do nothing if running in a non-browser environment or if listeners
        // have been already added.
        if (!isBrowser || this.connected_) {
            return;
        }
        // Subscription to the "Transitionend" event is used as a workaround for
        // delayed transitions. This way it's possible to capture at least the
        // final state of an element.
        document.addEventListener('transitionend', this.onTransitionEnd_);
        window.addEventListener('resize', this.refresh);
        if (mutationObserverSupported) {
            this.mutationsObserver_ = new MutationObserver(this.refresh);
            this.mutationsObserver_.observe(document, {
                attributes: true,
                childList: true,
                characterData: true,
                subtree: true
            });
        }
        else {
            document.addEventListener('DOMSubtreeModified', this.refresh);
            this.mutationEventsAdded_ = true;
        }
        this.connected_ = true;
    };
    /**
     * Removes DOM listeners.
     *
     * @private
     * @returns {void}
     */
    ResizeObserverController.prototype.disconnect_ = function () {
        // Do nothing if running in a non-browser environment or if listeners
        // have been already removed.
        if (!isBrowser || !this.connected_) {
            return;
        }
        document.removeEventListener('transitionend', this.onTransitionEnd_);
        window.removeEventListener('resize', this.refresh);
        if (this.mutationsObserver_) {
            this.mutationsObserver_.disconnect();
        }
        if (this.mutationEventsAdded_) {
            document.removeEventListener('DOMSubtreeModified', this.refresh);
        }
        this.mutationsObserver_ = null;
        this.mutationEventsAdded_ = false;
        this.connected_ = false;
    };
    /**
     * "Transitionend" event handler.
     *
     * @private
     * @param {TransitionEvent} event
     * @returns {void}
     */
    ResizeObserverController.prototype.onTransitionEnd_ = function (_a) {
        var _b = _a.propertyName, propertyName = _b === void 0 ? '' : _b;
        // Detect whether transition may affect dimensions of an element.
        var isReflowProperty = transitionKeys.some(function (key) {
            return !!~propertyName.indexOf(key);
        });
        if (isReflowProperty) {
            this.refresh();
        }
    };
    /**
     * Returns instance of the ResizeObserverController.
     *
     * @returns {ResizeObserverController}
     */
    ResizeObserverController.getInstance = function () {
        if (!this.instance_) {
            this.instance_ = new ResizeObserverController();
        }
        return this.instance_;
    };
    /**
     * Holds reference to the controller's instance.
     *
     * @private {ResizeObserverController}
     */
    ResizeObserverController.instance_ = null;
    return ResizeObserverController;
}());

/**
 * Defines non-writable/enumerable properties of the provided target object.
 *
 * @param {Object} target - Object for which to define properties.
 * @param {Object} props - Properties to be defined.
 * @returns {Object} Target object.
 */
var defineConfigurable = (function (target, props) {
    for (var _i = 0, _a = Object.keys(props); _i < _a.length; _i++) {
        var key = _a[_i];
        Object.defineProperty(target, key, {
            value: props[key],
            enumerable: false,
            writable: false,
            configurable: true
        });
    }
    return target;
});

/**
 * Returns the global object associated with provided element.
 *
 * @param {Object} target
 * @returns {Object}
 */
var getWindowOf = (function (target) {
    // Assume that the element is an instance of Node, which means that it
    // has the "ownerDocument" property from which we can retrieve a
    // corresponding global object.
    var ownerGlobal = target && target.ownerDocument && target.ownerDocument.defaultView;
    // Return the local global object if it's not possible extract one from
    // provided element.
    return ownerGlobal || global$1;
});

// Placeholder of an empty content rectangle.
var emptyRect = createRectInit(0, 0, 0, 0);
/**
 * Converts provided string to a number.
 *
 * @param {number|string} value
 * @returns {number}
 */
function toFloat(value) {
    return parseFloat(value) || 0;
}
/**
 * Extracts borders size from provided styles.
 *
 * @param {CSSStyleDeclaration} styles
 * @param {...string} positions - Borders positions (top, right, ...)
 * @returns {number}
 */
function getBordersSize(styles) {
    var positions = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        positions[_i - 1] = arguments[_i];
    }
    return positions.reduce(function (size, position) {
        var value = styles['border-' + position + '-width'];
        return size + toFloat(value);
    }, 0);
}
/**
 * Extracts paddings sizes from provided styles.
 *
 * @param {CSSStyleDeclaration} styles
 * @returns {Object} Paddings box.
 */
function getPaddings(styles) {
    var positions = ['top', 'right', 'bottom', 'left'];
    var paddings = {};
    for (var _i = 0, positions_1 = positions; _i < positions_1.length; _i++) {
        var position = positions_1[_i];
        var value = styles['padding-' + position];
        paddings[position] = toFloat(value);
    }
    return paddings;
}
/**
 * Calculates content rectangle of provided SVG element.
 *
 * @param {SVGGraphicsElement} target - Element content rectangle of which needs
 *      to be calculated.
 * @returns {DOMRectInit}
 */
function getSVGContentRect(target) {
    var bbox = target.getBBox();
    return createRectInit(0, 0, bbox.width, bbox.height);
}
/**
 * Calculates content rectangle of provided HTMLElement.
 *
 * @param {HTMLElement} target - Element for which to calculate the content rectangle.
 * @returns {DOMRectInit}
 */
function getHTMLElementContentRect(target) {
    // Client width & height properties can't be
    // used exclusively as they provide rounded values.
    var clientWidth = target.clientWidth, clientHeight = target.clientHeight;
    // By this condition we can catch all non-replaced inline, hidden and
    // detached elements. Though elements with width & height properties less
    // than 0.5 will be discarded as well.
    //
    // Without it we would need to implement separate methods for each of
    // those cases and it's not possible to perform a precise and performance
    // effective test for hidden elements. E.g. even jQuery's ':visible' filter
    // gives wrong results for elements with width & height less than 0.5.
    if (!clientWidth && !clientHeight) {
        return emptyRect;
    }
    var styles = getWindowOf(target).getComputedStyle(target);
    var paddings = getPaddings(styles);
    var horizPad = paddings.left + paddings.right;
    var vertPad = paddings.top + paddings.bottom;
    // Computed styles of width & height are being used because they are the
    // only dimensions available to JS that contain non-rounded values. It could
    // be possible to utilize the getBoundingClientRect if only it's data wasn't
    // affected by CSS transformations let alone paddings, borders and scroll bars.
    var width = toFloat(styles.width), height = toFloat(styles.height);
    // Width & height include paddings and borders when the 'border-box' box
    // model is applied (except for IE).
    if (styles.boxSizing === 'border-box') {
        // Following conditions are required to handle Internet Explorer which
        // doesn't include paddings and borders to computed CSS dimensions.
        //
        // We can say that if CSS dimensions + paddings are equal to the "client"
        // properties then it's either IE, and thus we don't need to subtract
        // anything, or an element merely doesn't have paddings/borders styles.
        if (Math.round(width + horizPad) !== clientWidth) {
            width -= getBordersSize(styles, 'left', 'right') + horizPad;
        }
        if (Math.round(height + vertPad) !== clientHeight) {
            height -= getBordersSize(styles, 'top', 'bottom') + vertPad;
        }
    }
    // Following steps can't be applied to the document's root element as its
    // client[Width/Height] properties represent viewport area of the window.
    // Besides, it's as well not necessary as the <html> itself neither has
    // rendered scroll bars nor it can be clipped.
    if (!isDocumentElement(target)) {
        // In some browsers (only in Firefox, actually) CSS width & height
        // include scroll bars size which can be removed at this step as scroll
        // bars are the only difference between rounded dimensions + paddings
        // and "client" properties, though that is not always true in Chrome.
        var vertScrollbar = Math.round(width + horizPad) - clientWidth;
        var horizScrollbar = Math.round(height + vertPad) - clientHeight;
        // Chrome has a rather weird rounding of "client" properties.
        // E.g. for an element with content width of 314.2px it sometimes gives
        // the client width of 315px and for the width of 314.7px it may give
        // 314px. And it doesn't happen all the time. So just ignore this delta
        // as a non-relevant.
        if (Math.abs(vertScrollbar) !== 1) {
            width -= vertScrollbar;
        }
        if (Math.abs(horizScrollbar) !== 1) {
            height -= horizScrollbar;
        }
    }
    return createRectInit(paddings.left, paddings.top, width, height);
}
/**
 * Checks whether provided element is an instance of the SVGGraphicsElement.
 *
 * @param {Element} target - Element to be checked.
 * @returns {boolean}
 */
var isSVGGraphicsElement = (function () {
    // Some browsers, namely IE and Edge, don't have the SVGGraphicsElement
    // interface.
    if (typeof SVGGraphicsElement !== 'undefined') {
        return function (target) { return target instanceof getWindowOf(target).SVGGraphicsElement; };
    }
    // If it's so, then check that element is at least an instance of the
    // SVGElement and that it has the "getBBox" method.
    // eslint-disable-next-line no-extra-parens
    return function (target) { return (target instanceof getWindowOf(target).SVGElement &&
        typeof target.getBBox === 'function'); };
})();
/**
 * Checks whether provided element is a document element (<html>).
 *
 * @param {Element} target - Element to be checked.
 * @returns {boolean}
 */
function isDocumentElement(target) {
    return target === getWindowOf(target).document.documentElement;
}
/**
 * Calculates an appropriate content rectangle for provided html or svg element.
 *
 * @param {Element} target - Element content rectangle of which needs to be calculated.
 * @returns {DOMRectInit}
 */
function getContentRect(target) {
    if (!isBrowser) {
        return emptyRect;
    }
    if (isSVGGraphicsElement(target)) {
        return getSVGContentRect(target);
    }
    return getHTMLElementContentRect(target);
}
/**
 * Creates rectangle with an interface of the DOMRectReadOnly.
 * Spec: https://drafts.fxtf.org/geometry/#domrectreadonly
 *
 * @param {DOMRectInit} rectInit - Object with rectangle's x/y coordinates and dimensions.
 * @returns {DOMRectReadOnly}
 */
function createReadOnlyRect(_a) {
    var x = _a.x, y = _a.y, width = _a.width, height = _a.height;
    // If DOMRectReadOnly is available use it as a prototype for the rectangle.
    var Constr = typeof DOMRectReadOnly !== 'undefined' ? DOMRectReadOnly : Object;
    var rect = Object.create(Constr.prototype);
    // Rectangle's properties are not writable and non-enumerable.
    defineConfigurable(rect, {
        x: x, y: y, width: width, height: height,
        top: y,
        right: x + width,
        bottom: height + y,
        left: x
    });
    return rect;
}
/**
 * Creates DOMRectInit object based on the provided dimensions and the x/y coordinates.
 * Spec: https://drafts.fxtf.org/geometry/#dictdef-domrectinit
 *
 * @param {number} x - X coordinate.
 * @param {number} y - Y coordinate.
 * @param {number} width - Rectangle's width.
 * @param {number} height - Rectangle's height.
 * @returns {DOMRectInit}
 */
function createRectInit(x, y, width, height) {
    return { x: x, y: y, width: width, height: height };
}

/**
 * Class that is responsible for computations of the content rectangle of
 * provided DOM element and for keeping track of it's changes.
 */
var ResizeObservation = /** @class */ (function () {
    /**
     * Creates an instance of ResizeObservation.
     *
     * @param {Element} target - Element to be observed.
     */
    function ResizeObservation(target) {
        /**
         * Broadcasted width of content rectangle.
         *
         * @type {number}
         */
        this.broadcastWidth = 0;
        /**
         * Broadcasted height of content rectangle.
         *
         * @type {number}
         */
        this.broadcastHeight = 0;
        /**
         * Reference to the last observed content rectangle.
         *
         * @private {DOMRectInit}
         */
        this.contentRect_ = createRectInit(0, 0, 0, 0);
        this.target = target;
    }
    /**
     * Updates content rectangle and tells whether it's width or height properties
     * have changed since the last broadcast.
     *
     * @returns {boolean}
     */
    ResizeObservation.prototype.isActive = function () {
        var rect = getContentRect(this.target);
        this.contentRect_ = rect;
        return (rect.width !== this.broadcastWidth ||
            rect.height !== this.broadcastHeight);
    };
    /**
     * Updates 'broadcastWidth' and 'broadcastHeight' properties with a data
     * from the corresponding properties of the last observed content rectangle.
     *
     * @returns {DOMRectInit} Last observed content rectangle.
     */
    ResizeObservation.prototype.broadcastRect = function () {
        var rect = this.contentRect_;
        this.broadcastWidth = rect.width;
        this.broadcastHeight = rect.height;
        return rect;
    };
    return ResizeObservation;
}());

var ResizeObserverEntry = /** @class */ (function () {
    /**
     * Creates an instance of ResizeObserverEntry.
     *
     * @param {Element} target - Element that is being observed.
     * @param {DOMRectInit} rectInit - Data of the element's content rectangle.
     */
    function ResizeObserverEntry(target, rectInit) {
        var contentRect = createReadOnlyRect(rectInit);
        // According to the specification following properties are not writable
        // and are also not enumerable in the native implementation.
        //
        // Property accessors are not being used as they'd require to define a
        // private WeakMap storage which may cause memory leaks in browsers that
        // don't support this type of collections.
        defineConfigurable(this, { target: target, contentRect: contentRect });
    }
    return ResizeObserverEntry;
}());

var ResizeObserverSPI = /** @class */ (function () {
    /**
     * Creates a new instance of ResizeObserver.
     *
     * @param {ResizeObserverCallback} callback - Callback function that is invoked
     *      when one of the observed elements changes it's content dimensions.
     * @param {ResizeObserverController} controller - Controller instance which
     *      is responsible for the updates of observer.
     * @param {ResizeObserver} callbackCtx - Reference to the public
     *      ResizeObserver instance which will be passed to callback function.
     */
    function ResizeObserverSPI(callback, controller, callbackCtx) {
        /**
         * Collection of resize observations that have detected changes in dimensions
         * of elements.
         *
         * @private {Array<ResizeObservation>}
         */
        this.activeObservations_ = [];
        /**
         * Registry of the ResizeObservation instances.
         *
         * @private {Map<Element, ResizeObservation>}
         */
        this.observations_ = new MapShim();
        if (typeof callback !== 'function') {
            throw new TypeError('The callback provided as parameter 1 is not a function.');
        }
        this.callback_ = callback;
        this.controller_ = controller;
        this.callbackCtx_ = callbackCtx;
    }
    /**
     * Starts observing provided element.
     *
     * @param {Element} target - Element to be observed.
     * @returns {void}
     */
    ResizeObserverSPI.prototype.observe = function (target) {
        if (!arguments.length) {
            throw new TypeError('1 argument required, but only 0 present.');
        }
        // Do nothing if current environment doesn't have the Element interface.
        if (typeof Element === 'undefined' || !(Element instanceof Object)) {
            return;
        }
        if (!(target instanceof getWindowOf(target).Element)) {
            throw new TypeError('parameter 1 is not of type "Element".');
        }
        var observations = this.observations_;
        // Do nothing if element is already being observed.
        if (observations.has(target)) {
            return;
        }
        observations.set(target, new ResizeObservation(target));
        this.controller_.addObserver(this);
        // Force the update of observations.
        this.controller_.refresh();
    };
    /**
     * Stops observing provided element.
     *
     * @param {Element} target - Element to stop observing.
     * @returns {void}
     */
    ResizeObserverSPI.prototype.unobserve = function (target) {
        if (!arguments.length) {
            throw new TypeError('1 argument required, but only 0 present.');
        }
        // Do nothing if current environment doesn't have the Element interface.
        if (typeof Element === 'undefined' || !(Element instanceof Object)) {
            return;
        }
        if (!(target instanceof getWindowOf(target).Element)) {
            throw new TypeError('parameter 1 is not of type "Element".');
        }
        var observations = this.observations_;
        // Do nothing if element is not being observed.
        if (!observations.has(target)) {
            return;
        }
        observations.delete(target);
        if (!observations.size) {
            this.controller_.removeObserver(this);
        }
    };
    /**
     * Stops observing all elements.
     *
     * @returns {void}
     */
    ResizeObserverSPI.prototype.disconnect = function () {
        this.clearActive();
        this.observations_.clear();
        this.controller_.removeObserver(this);
    };
    /**
     * Collects observation instances the associated element of which has changed
     * it's content rectangle.
     *
     * @returns {void}
     */
    ResizeObserverSPI.prototype.gatherActive = function () {
        var _this = this;
        this.clearActive();
        this.observations_.forEach(function (observation) {
            if (observation.isActive()) {
                _this.activeObservations_.push(observation);
            }
        });
    };
    /**
     * Invokes initial callback function with a list of ResizeObserverEntry
     * instances collected from active resize observations.
     *
     * @returns {void}
     */
    ResizeObserverSPI.prototype.broadcastActive = function () {
        // Do nothing if observer doesn't have active observations.
        if (!this.hasActive()) {
            return;
        }
        var ctx = this.callbackCtx_;
        // Create ResizeObserverEntry instance for every active observation.
        var entries = this.activeObservations_.map(function (observation) {
            return new ResizeObserverEntry(observation.target, observation.broadcastRect());
        });
        this.callback_.call(ctx, entries, ctx);
        this.clearActive();
    };
    /**
     * Clears the collection of active observations.
     *
     * @returns {void}
     */
    ResizeObserverSPI.prototype.clearActive = function () {
        this.activeObservations_.splice(0);
    };
    /**
     * Tells whether observer has active observations.
     *
     * @returns {boolean}
     */
    ResizeObserverSPI.prototype.hasActive = function () {
        return this.activeObservations_.length > 0;
    };
    return ResizeObserverSPI;
}());

// Registry of internal observers. If WeakMap is not available use current shim
// for the Map collection as it has all required methods and because WeakMap
// can't be fully polyfilled anyway.
var observers = typeof WeakMap !== 'undefined' ? new WeakMap() : new MapShim();
/**
 * ResizeObserver API. Encapsulates the ResizeObserver SPI implementation
 * exposing only those methods and properties that are defined in the spec.
 */
var ResizeObserver = /** @class */ (function () {
    /**
     * Creates a new instance of ResizeObserver.
     *
     * @param {ResizeObserverCallback} callback - Callback that is invoked when
     *      dimensions of the observed elements change.
     */
    function ResizeObserver(callback) {
        if (!(this instanceof ResizeObserver)) {
            throw new TypeError('Cannot call a class as a function.');
        }
        if (!arguments.length) {
            throw new TypeError('1 argument required, but only 0 present.');
        }
        var controller = ResizeObserverController.getInstance();
        var observer = new ResizeObserverSPI(callback, controller, this);
        observers.set(this, observer);
    }
    return ResizeObserver;
}());
// Expose public methods of ResizeObserver.
[
    'observe',
    'unobserve',
    'disconnect'
].forEach(function (method) {
    ResizeObserver.prototype[method] = function () {
        var _a;
        return (_a = observers.get(this))[method].apply(_a, arguments);
    };
});

var index = (function () {
    // Export existing implementation if available.
    if (typeof global$1.ResizeObserver !== 'undefined') {
        return global$1.ResizeObserver;
    }
    return ResizeObserver;
})();

/* harmony default export */ __webpack_exports__["default"] = (index);

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "bkDJ":
/*!**************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/angles.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var modModule = __webpack_require__(/*! ./mod */ "09xr");
var mod = modModule.mod;
var modHalf = modModule.modHalf;

var PI = Math.PI;
var twoPI = 2 * PI;

function deg2rad(deg) { return deg / 180 * PI; }

function rad2deg(rad) { return rad / PI * 180; }

/**
 * is sector a full circle?
 * ... this comes up a lot in SVG path-drawing routines
 *
 * N.B. we consider all sectors that span more that 2pi 'full' circles
 *
 * @param {2-item array} aBnds : angular bounds in *radians*
 * @return {boolean}
 */
function isFullCircle(aBnds) {
    return Math.abs(aBnds[1] - aBnds[0]) > twoPI - 1e-15;
}

/**
 * angular delta between angle 'a' and 'b'
 * solution taken from: https://stackoverflow.com/a/2007279
 *
 * @param {number} a : first angle in *radians*
 * @param {number} b : second angle in *radians*
 * @return {number} angular delta in *radians*
 */
function angleDelta(a, b) {
    return modHalf(b - a, twoPI);
}

/**
 * angular distance between angle 'a' and 'b'
 *
 * @param {number} a : first angle in *radians*
 * @param {number} b : second angle in *radians*
 * @return {number} angular distance in *radians*
 */
function angleDist(a, b) {
    return Math.abs(angleDelta(a, b));
}

/**
 * is angle inside sector?
 *
 * @param {number} a : angle to test in *radians*
 * @param {2-item array} aBnds : sector's angular bounds in *radians*
 * @param {boolean}
 */
function isAngleInsideSector(a, aBnds) {
    if(isFullCircle(aBnds)) return true;

    var s0, s1;

    if(aBnds[0] < aBnds[1]) {
        s0 = aBnds[0];
        s1 = aBnds[1];
    } else {
        s0 = aBnds[1];
        s1 = aBnds[0];
    }

    s0 = mod(s0, twoPI);
    s1 = mod(s1, twoPI);
    if(s0 > s1) s1 += twoPI;

    var a0 = mod(a, twoPI);
    var a1 = a0 + twoPI;

    return (a0 >= s0 && a0 <= s1) || (a1 >= s0 && a1 <= s1);
}

/**
 * is pt (r,a) inside sector?
 *
 * @param {number} r : pt's radial coordinate
 * @param {number} a : pt's angular coordinate in *radians*
 * @param {2-item array} rBnds : sector's radial bounds
 * @param {2-item array} aBnds : sector's angular bounds in *radians*
 * @return {boolean}
 */
function isPtInsideSector(r, a, rBnds, aBnds) {
    if(!isAngleInsideSector(a, aBnds)) return false;

    var r0, r1;

    if(rBnds[0] < rBnds[1]) {
        r0 = rBnds[0];
        r1 = rBnds[1];
    } else {
        r0 = rBnds[1];
        r1 = rBnds[0];
    }

    return r >= r0 && r <= r1;
}

// common to pathArc, pathSector and pathAnnulus
function _path(r0, r1, a0, a1, cx, cy, isClosed) {
    cx = cx || 0;
    cy = cy || 0;

    var isCircle = isFullCircle([a0, a1]);
    var aStart, aMid, aEnd;
    var rStart, rEnd;

    if(isCircle) {
        aStart = 0;
        aMid = PI;
        aEnd = twoPI;
    } else {
        if(a0 < a1) {
            aStart = a0;
            aEnd = a1;
        } else {
            aStart = a1;
            aEnd = a0;
        }
    }

    if(r0 < r1) {
        rStart = r0;
        rEnd = r1;
    } else {
        rStart = r1;
        rEnd = r0;
    }

    // N.B. svg coordinates here, where y increases downward
    function pt(r, a) {
        return [r * Math.cos(a) + cx, cy - r * Math.sin(a)];
    }

    var largeArc = Math.abs(aEnd - aStart) <= PI ? 0 : 1;
    function arc(r, a, cw) {
        return 'A' + [r, r] + ' ' + [0, largeArc, cw] + ' ' + pt(r, a);
    }

    var p;

    if(isCircle) {
        if(rStart === null) {
            p = 'M' + pt(rEnd, aStart) +
                arc(rEnd, aMid, 0) +
                arc(rEnd, aEnd, 0) + 'Z';
        } else {
            p = 'M' + pt(rStart, aStart) +
                arc(rStart, aMid, 0) +
                arc(rStart, aEnd, 0) + 'Z' +
                'M' + pt(rEnd, aStart) +
                arc(rEnd, aMid, 1) +
                arc(rEnd, aEnd, 1) + 'Z';
        }
    } else {
        if(rStart === null) {
            p = 'M' + pt(rEnd, aStart) + arc(rEnd, aEnd, 0);
            if(isClosed) p += 'L0,0Z';
        } else {
            p = 'M' + pt(rStart, aStart) +
                'L' + pt(rEnd, aStart) +
                arc(rEnd, aEnd, 0) +
                'L' + pt(rStart, aEnd) +
                arc(rStart, aStart, 1) + 'Z';
        }
    }

    return p;
}

/**
 * path an arc
 *
 * @param {number} r : radius
 * @param {number} a0 : first angular coordinate in *radians*
 * @param {number} a1 : second angular coordinate in *radians*
 * @param {number (optional)} cx : x coordinate of center
 * @param {number (optional)} cy : y coordinate of center
 * @return {string} svg path
 */
function pathArc(r, a0, a1, cx, cy) {
    return _path(null, r, a0, a1, cx, cy, 0);
}

/**
 * path a sector
 *
 * @param {number} r : radius
 * @param {number} a0 : first angular coordinate in *radians*
 * @param {number} a1 : second angular coordinate in *radians*
 * @param {number (optional)} cx : x coordinate of center
 * @param {number (optional)} cy : y coordinate of center
 * @return {string} svg path
 */
function pathSector(r, a0, a1, cx, cy) {
    return _path(null, r, a0, a1, cx, cy, 1);
}

/**
 * path an annulus
 *
 * @param {number} r0 : first radial coordinate
 * @param {number} r1 : second radial coordinate
 * @param {number} a0 : first angular coordinate in *radians*
 * @param {number} a1 : second angular coordinate in *radians*
 * @param {number (optional)} cx : x coordinate of center
 * @param {number (optional)} cy : y coordinate of center
 * @return {string} svg path
 */
function pathAnnulus(r0, r1, a0, a1, cx, cy) {
    return _path(r0, r1, a0, a1, cx, cy, 1);
}

module.exports = {
    deg2rad: deg2rad,
    rad2deg: rad2deg,
    angleDelta: angleDelta,
    angleDist: angleDist,
    isFullCircle: isFullCircle,
    isAngleInsideSector: isAngleInsideSector,
    isPtInsideSector: isPtInsideSector,
    pathArc: pathArc,
    pathSector: pathSector,
    pathAnnulus: pathAnnulus
};


/***/ }),

/***/ "bljh":
/*!*******************************!*\
  !*** ./node_modules/d3/d3.js ***!
  \*******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;!function() {
  var d3 = {
    version: "3.5.17"
  };
  var d3_arraySlice = [].slice, d3_array = function(list) {
    return d3_arraySlice.call(list);
  };
  var d3_document = this.document;
  function d3_documentElement(node) {
    return node && (node.ownerDocument || node.document || node).documentElement;
  }
  function d3_window(node) {
    return node && (node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView);
  }
  if (d3_document) {
    try {
      d3_array(d3_document.documentElement.childNodes)[0].nodeType;
    } catch (e) {
      d3_array = function(list) {
        var i = list.length, array = new Array(i);
        while (i--) array[i] = list[i];
        return array;
      };
    }
  }
  if (!Date.now) Date.now = function() {
    return +new Date();
  };
  if (d3_document) {
    try {
      d3_document.createElement("DIV").style.setProperty("opacity", 0, "");
    } catch (error) {
      var d3_element_prototype = this.Element.prototype, d3_element_setAttribute = d3_element_prototype.setAttribute, d3_element_setAttributeNS = d3_element_prototype.setAttributeNS, d3_style_prototype = this.CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty;
      d3_element_prototype.setAttribute = function(name, value) {
        d3_element_setAttribute.call(this, name, value + "");
      };
      d3_element_prototype.setAttributeNS = function(space, local, value) {
        d3_element_setAttributeNS.call(this, space, local, value + "");
      };
      d3_style_prototype.setProperty = function(name, value, priority) {
        d3_style_setProperty.call(this, name, value + "", priority);
      };
    }
  }
  d3.ascending = d3_ascending;
  function d3_ascending(a, b) {
    return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
  }
  d3.descending = function(a, b) {
    return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
  };
  d3.min = function(array, f) {
    var i = -1, n = array.length, a, b;
    if (arguments.length === 1) {
      while (++i < n) if ((b = array[i]) != null && b >= b) {
        a = b;
        break;
      }
      while (++i < n) if ((b = array[i]) != null && a > b) a = b;
    } else {
      while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
        a = b;
        break;
      }
      while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b;
    }
    return a;
  };
  d3.max = function(array, f) {
    var i = -1, n = array.length, a, b;
    if (arguments.length === 1) {
      while (++i < n) if ((b = array[i]) != null && b >= b) {
        a = b;
        break;
      }
      while (++i < n) if ((b = array[i]) != null && b > a) a = b;
    } else {
      while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
        a = b;
        break;
      }
      while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b;
    }
    return a;
  };
  d3.extent = function(array, f) {
    var i = -1, n = array.length, a, b, c;
    if (arguments.length === 1) {
      while (++i < n) if ((b = array[i]) != null && b >= b) {
        a = c = b;
        break;
      }
      while (++i < n) if ((b = array[i]) != null) {
        if (a > b) a = b;
        if (c < b) c = b;
      }
    } else {
      while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
        a = c = b;
        break;
      }
      while (++i < n) if ((b = f.call(array, array[i], i)) != null) {
        if (a > b) a = b;
        if (c < b) c = b;
      }
    }
    return [ a, c ];
  };
  function d3_number(x) {
    return x === null ? NaN : +x;
  }
  function d3_numeric(x) {
    return !isNaN(x);
  }
  d3.sum = function(array, f) {
    var s = 0, n = array.length, a, i = -1;
    if (arguments.length === 1) {
      while (++i < n) if (d3_numeric(a = +array[i])) s += a;
    } else {
      while (++i < n) if (d3_numeric(a = +f.call(array, array[i], i))) s += a;
    }
    return s;
  };
  d3.mean = function(array, f) {
    var s = 0, n = array.length, a, i = -1, j = n;
    if (arguments.length === 1) {
      while (++i < n) if (d3_numeric(a = d3_number(array[i]))) s += a; else --j;
    } else {
      while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) s += a; else --j;
    }
    if (j) return s / j;
  };
  d3.quantile = function(values, p) {
    var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h;
    return e ? v + e * (values[h] - v) : v;
  };
  d3.median = function(array, f) {
    var numbers = [], n = array.length, a, i = -1;
    if (arguments.length === 1) {
      while (++i < n) if (d3_numeric(a = d3_number(array[i]))) numbers.push(a);
    } else {
      while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) numbers.push(a);
    }
    if (numbers.length) return d3.quantile(numbers.sort(d3_ascending), .5);
  };
  d3.variance = function(array, f) {
    var n = array.length, m = 0, a, d, s = 0, i = -1, j = 0;
    if (arguments.length === 1) {
      while (++i < n) {
        if (d3_numeric(a = d3_number(array[i]))) {
          d = a - m;
          m += d / ++j;
          s += d * (a - m);
        }
      }
    } else {
      while (++i < n) {
        if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) {
          d = a - m;
          m += d / ++j;
          s += d * (a - m);
        }
      }
    }
    if (j > 1) return s / (j - 1);
  };
  d3.deviation = function() {
    var v = d3.variance.apply(this, arguments);
    return v ? Math.sqrt(v) : v;
  };
  function d3_bisector(compare) {
    return {
      left: function(a, x, lo, hi) {
        if (arguments.length < 3) lo = 0;
        if (arguments.length < 4) hi = a.length;
        while (lo < hi) {
          var mid = lo + hi >>> 1;
          if (compare(a[mid], x) < 0) lo = mid + 1; else hi = mid;
        }
        return lo;
      },
      right: function(a, x, lo, hi) {
        if (arguments.length < 3) lo = 0;
        if (arguments.length < 4) hi = a.length;
        while (lo < hi) {
          var mid = lo + hi >>> 1;
          if (compare(a[mid], x) > 0) hi = mid; else lo = mid + 1;
        }
        return lo;
      }
    };
  }
  var d3_bisect = d3_bisector(d3_ascending);
  d3.bisectLeft = d3_bisect.left;
  d3.bisect = d3.bisectRight = d3_bisect.right;
  d3.bisector = function(f) {
    return d3_bisector(f.length === 1 ? function(d, x) {
      return d3_ascending(f(d), x);
    } : f);
  };
  d3.shuffle = function(array, i0, i1) {
    if ((m = arguments.length) < 3) {
      i1 = array.length;
      if (m < 2) i0 = 0;
    }
    var m = i1 - i0, t, i;
    while (m) {
      i = Math.random() * m-- | 0;
      t = array[m + i0], array[m + i0] = array[i + i0], array[i + i0] = t;
    }
    return array;
  };
  d3.permute = function(array, indexes) {
    var i = indexes.length, permutes = new Array(i);
    while (i--) permutes[i] = array[indexes[i]];
    return permutes;
  };
  d3.pairs = function(array) {
    var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n);
    while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ];
    return pairs;
  };
  d3.transpose = function(matrix) {
    if (!(n = matrix.length)) return [];
    for (var i = -1, m = d3.min(matrix, d3_transposeLength), transpose = new Array(m); ++i < m; ) {
      for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n; ) {
        row[j] = matrix[j][i];
      }
    }
    return transpose;
  };
  function d3_transposeLength(d) {
    return d.length;
  }
  d3.zip = function() {
    return d3.transpose(arguments);
  };
  d3.keys = function(map) {
    var keys = [];
    for (var key in map) keys.push(key);
    return keys;
  };
  d3.values = function(map) {
    var values = [];
    for (var key in map) values.push(map[key]);
    return values;
  };
  d3.entries = function(map) {
    var entries = [];
    for (var key in map) entries.push({
      key: key,
      value: map[key]
    });
    return entries;
  };
  d3.merge = function(arrays) {
    var n = arrays.length, m, i = -1, j = 0, merged, array;
    while (++i < n) j += arrays[i].length;
    merged = new Array(j);
    while (--n >= 0) {
      array = arrays[n];
      m = array.length;
      while (--m >= 0) {
        merged[--j] = array[m];
      }
    }
    return merged;
  };
  var abs = Math.abs;
  d3.range = function(start, stop, step) {
    if (arguments.length < 3) {
      step = 1;
      if (arguments.length < 2) {
        stop = start;
        start = 0;
      }
    }
    if ((stop - start) / step === Infinity) throw new Error("infinite range");
    var range = [], k = d3_range_integerScale(abs(step)), i = -1, j;
    start *= k, stop *= k, step *= k;
    if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k);
    return range;
  };
  function d3_range_integerScale(x) {
    var k = 1;
    while (x * k % 1) k *= 10;
    return k;
  }
  function d3_class(ctor, properties) {
    for (var key in properties) {
      Object.defineProperty(ctor.prototype, key, {
        value: properties[key],
        enumerable: false
      });
    }
  }
  d3.map = function(object, f) {
    var map = new d3_Map();
    if (object instanceof d3_Map) {
      object.forEach(function(key, value) {
        map.set(key, value);
      });
    } else if (Array.isArray(object)) {
      var i = -1, n = object.length, o;
      if (arguments.length === 1) while (++i < n) map.set(i, object[i]); else while (++i < n) map.set(f.call(object, o = object[i], i), o);
    } else {
      for (var key in object) map.set(key, object[key]);
    }
    return map;
  };
  function d3_Map() {
    this._ = Object.create(null);
  }
  var d3_map_proto = "__proto__", d3_map_zero = "\x00";
  d3_class(d3_Map, {
    has: d3_map_has,
    get: function(key) {
      return this._[d3_map_escape(key)];
    },
    set: function(key, value) {
      return this._[d3_map_escape(key)] = value;
    },
    remove: d3_map_remove,
    keys: d3_map_keys,
    values: function() {
      var values = [];
      for (var key in this._) values.push(this._[key]);
      return values;
    },
    entries: function() {
      var entries = [];
      for (var key in this._) entries.push({
        key: d3_map_unescape(key),
        value: this._[key]
      });
      return entries;
    },
    size: d3_map_size,
    empty: d3_map_empty,
    forEach: function(f) {
      for (var key in this._) f.call(this, d3_map_unescape(key), this._[key]);
    }
  });
  function d3_map_escape(key) {
    return (key += "") === d3_map_proto || key[0] === d3_map_zero ? d3_map_zero + key : key;
  }
  function d3_map_unescape(key) {
    return (key += "")[0] === d3_map_zero ? key.slice(1) : key;
  }
  function d3_map_has(key) {
    return d3_map_escape(key) in this._;
  }
  function d3_map_remove(key) {
    return (key = d3_map_escape(key)) in this._ && delete this._[key];
  }
  function d3_map_keys() {
    var keys = [];
    for (var key in this._) keys.push(d3_map_unescape(key));
    return keys;
  }
  function d3_map_size() {
    var size = 0;
    for (var key in this._) ++size;
    return size;
  }
  function d3_map_empty() {
    for (var key in this._) return false;
    return true;
  }
  d3.nest = function() {
    var nest = {}, keys = [], sortKeys = [], sortValues, rollup;
    function map(mapType, array, depth) {
      if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array;
      var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values;
      while (++i < n) {
        if (values = valuesByKey.get(keyValue = key(object = array[i]))) {
          values.push(object);
        } else {
          valuesByKey.set(keyValue, [ object ]);
        }
      }
      if (mapType) {
        object = mapType();
        setter = function(keyValue, values) {
          object.set(keyValue, map(mapType, values, depth));
        };
      } else {
        object = {};
        setter = function(keyValue, values) {
          object[keyValue] = map(mapType, values, depth);
        };
      }
      valuesByKey.forEach(setter);
      return object;
    }
    function entries(map, depth) {
      if (depth >= keys.length) return map;
      var array = [], sortKey = sortKeys[depth++];
      map.forEach(function(key, keyMap) {
        array.push({
          key: key,
          values: entries(keyMap, depth)
        });
      });
      return sortKey ? array.sort(function(a, b) {
        return sortKey(a.key, b.key);
      }) : array;
    }
    nest.map = function(array, mapType) {
      return map(mapType, array, 0);
    };
    nest.entries = function(array) {
      return entries(map(d3.map, array, 0), 0);
    };
    nest.key = function(d) {
      keys.push(d);
      return nest;
    };
    nest.sortKeys = function(order) {
      sortKeys[keys.length - 1] = order;
      return nest;
    };
    nest.sortValues = function(order) {
      sortValues = order;
      return nest;
    };
    nest.rollup = function(f) {
      rollup = f;
      return nest;
    };
    return nest;
  };
  d3.set = function(array) {
    var set = new d3_Set();
    if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]);
    return set;
  };
  function d3_Set() {
    this._ = Object.create(null);
  }
  d3_class(d3_Set, {
    has: d3_map_has,
    add: function(key) {
      this._[d3_map_escape(key += "")] = true;
      return key;
    },
    remove: d3_map_remove,
    values: d3_map_keys,
    size: d3_map_size,
    empty: d3_map_empty,
    forEach: function(f) {
      for (var key in this._) f.call(this, d3_map_unescape(key));
    }
  });
  d3.behavior = {};
  function d3_identity(d) {
    return d;
  }
  d3.rebind = function(target, source) {
    var i = 1, n = arguments.length, method;
    while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]);
    return target;
  };
  function d3_rebind(target, source, method) {
    return function() {
      var value = method.apply(source, arguments);
      return value === source ? target : value;
    };
  }
  function d3_vendorSymbol(object, name) {
    if (name in object) return name;
    name = name.charAt(0).toUpperCase() + name.slice(1);
    for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) {
      var prefixName = d3_vendorPrefixes[i] + name;
      if (prefixName in object) return prefixName;
    }
  }
  var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ];
  function d3_noop() {}
  d3.dispatch = function() {
    var dispatch = new d3_dispatch(), i = -1, n = arguments.length;
    while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch);
    return dispatch;
  };
  function d3_dispatch() {}
  d3_dispatch.prototype.on = function(type, listener) {
    var i = type.indexOf("."), name = "";
    if (i >= 0) {
      name = type.slice(i + 1);
      type = type.slice(0, i);
    }
    if (type) return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener);
    if (arguments.length === 2) {
      if (listener == null) for (type in this) {
        if (this.hasOwnProperty(type)) this[type].on(name, null);
      }
      return this;
    }
  };
  function d3_dispatch_event(dispatch) {
    var listeners = [], listenerByName = new d3_Map();
    function event() {
      var z = listeners, i = -1, n = z.length, l;
      while (++i < n) if (l = z[i].on) l.apply(this, arguments);
      return dispatch;
    }
    event.on = function(name, listener) {
      var l = listenerByName.get(name), i;
      if (arguments.length < 2) return l && l.on;
      if (l) {
        l.on = null;
        listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1));
        listenerByName.remove(name);
      }
      if (listener) listeners.push(listenerByName.set(name, {
        on: listener
      }));
      return dispatch;
    };
    return event;
  }
  d3.event = null;
  function d3_eventPreventDefault() {
    d3.event.preventDefault();
  }
  function d3_eventSource() {
    var e = d3.event, s;
    while (s = e.sourceEvent) e = s;
    return e;
  }
  function d3_eventDispatch(target) {
    var dispatch = new d3_dispatch(), i = 0, n = arguments.length;
    while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch);
    dispatch.of = function(thiz, argumentz) {
      return function(e1) {
        try {
          var e0 = e1.sourceEvent = d3.event;
          e1.target = target;
          d3.event = e1;
          dispatch[e1.type].apply(thiz, argumentz);
        } finally {
          d3.event = e0;
        }
      };
    };
    return dispatch;
  }
  d3.requote = function(s) {
    return s.replace(d3_requote_re, "\\$&");
  };
  var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;
  var d3_subclass = {}.__proto__ ? function(object, prototype) {
    object.__proto__ = prototype;
  } : function(object, prototype) {
    for (var property in prototype) object[property] = prototype[property];
  };
  function d3_selection(groups) {
    d3_subclass(groups, d3_selectionPrototype);
    return groups;
  }
  var d3_select = function(s, n) {
    return n.querySelector(s);
  }, d3_selectAll = function(s, n) {
    return n.querySelectorAll(s);
  }, d3_selectMatches = function(n, s) {
    var d3_selectMatcher = n.matches || n[d3_vendorSymbol(n, "matchesSelector")];
    d3_selectMatches = function(n, s) {
      return d3_selectMatcher.call(n, s);
    };
    return d3_selectMatches(n, s);
  };
  if (typeof Sizzle === "function") {
    d3_select = function(s, n) {
      return Sizzle(s, n)[0] || null;
    };
    d3_selectAll = Sizzle;
    d3_selectMatches = Sizzle.matchesSelector;
  }
  d3.selection = function() {
    return d3.select(d3_document.documentElement);
  };
  var d3_selectionPrototype = d3.selection.prototype = [];
  d3_selectionPrototype.select = function(selector) {
    var subgroups = [], subgroup, subnode, group, node;
    selector = d3_selection_selector(selector);
    for (var j = -1, m = this.length; ++j < m; ) {
      subgroups.push(subgroup = []);
      subgroup.parentNode = (group = this[j]).parentNode;
      for (var i = -1, n = group.length; ++i < n; ) {
        if (node = group[i]) {
          subgroup.push(subnode = selector.call(node, node.__data__, i, j));
          if (subnode && "__data__" in node) subnode.__data__ = node.__data__;
        } else {
          subgroup.push(null);
        }
      }
    }
    return d3_selection(subgroups);
  };
  function d3_selection_selector(selector) {
    return typeof selector === "function" ? selector : function() {
      return d3_select(selector, this);
    };
  }
  d3_selectionPrototype.selectAll = function(selector) {
    var subgroups = [], subgroup, node;
    selector = d3_selection_selectorAll(selector);
    for (var j = -1, m = this.length; ++j < m; ) {
      for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
        if (node = group[i]) {
          subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j)));
          subgroup.parentNode = node;
        }
      }
    }
    return d3_selection(subgroups);
  };
  function d3_selection_selectorAll(selector) {
    return typeof selector === "function" ? selector : function() {
      return d3_selectAll(selector, this);
    };
  }
  var d3_nsXhtml = "http://www.w3.org/1999/xhtml";
  var d3_nsPrefix = {
    svg: "http://www.w3.org/2000/svg",
    xhtml: d3_nsXhtml,
    xlink: "http://www.w3.org/1999/xlink",
    xml: "http://www.w3.org/XML/1998/namespace",
    xmlns: "http://www.w3.org/2000/xmlns/"
  };
  d3.ns = {
    prefix: d3_nsPrefix,
    qualify: function(name) {
      var i = name.indexOf(":"), prefix = name;
      if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1);
      return d3_nsPrefix.hasOwnProperty(prefix) ? {
        space: d3_nsPrefix[prefix],
        local: name
      } : name;
    }
  };
  d3_selectionPrototype.attr = function(name, value) {
    if (arguments.length < 2) {
      if (typeof name === "string") {
        var node = this.node();
        name = d3.ns.qualify(name);
        return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name);
      }
      for (value in name) this.each(d3_selection_attr(value, name[value]));
      return this;
    }
    return this.each(d3_selection_attr(name, value));
  };
  function d3_selection_attr(name, value) {
    name = d3.ns.qualify(name);
    function attrNull() {
      this.removeAttribute(name);
    }
    function attrNullNS() {
      this.removeAttributeNS(name.space, name.local);
    }
    function attrConstant() {
      this.setAttribute(name, value);
    }
    function attrConstantNS() {
      this.setAttributeNS(name.space, name.local, value);
    }
    function attrFunction() {
      var x = value.apply(this, arguments);
      if (x == null) this.removeAttribute(name); else this.setAttribute(name, x);
    }
    function attrFunctionNS() {
      var x = value.apply(this, arguments);
      if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x);
    }
    return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant;
  }
  function d3_collapse(s) {
    return s.trim().replace(/\s+/g, " ");
  }
  d3_selectionPrototype.classed = function(name, value) {
    if (arguments.length < 2) {
      if (typeof name === "string") {
        var node = this.node(), n = (name = d3_selection_classes(name)).length, i = -1;
        if (value = node.classList) {
          while (++i < n) if (!value.contains(name[i])) return false;
        } else {
          value = node.getAttribute("class");
          while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false;
        }
        return true;
      }
      for (value in name) this.each(d3_selection_classed(value, name[value]));
      return this;
    }
    return this.each(d3_selection_classed(name, value));
  };
  function d3_selection_classedRe(name) {
    return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g");
  }
  function d3_selection_classes(name) {
    return (name + "").trim().split(/^|\s+/);
  }
  function d3_selection_classed(name, value) {
    name = d3_selection_classes(name).map(d3_selection_classedName);
    var n = name.length;
    function classedConstant() {
      var i = -1;
      while (++i < n) name[i](this, value);
    }
    function classedFunction() {
      var i = -1, x = value.apply(this, arguments);
      while (++i < n) name[i](this, x);
    }
    return typeof value === "function" ? classedFunction : classedConstant;
  }
  function d3_selection_classedName(name) {
    var re = d3_selection_classedRe(name);
    return function(node, value) {
      if (c = node.classList) return value ? c.add(name) : c.remove(name);
      var c = node.getAttribute("class") || "";
      if (value) {
        re.lastIndex = 0;
        if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name));
      } else {
        node.setAttribute("class", d3_collapse(c.replace(re, " ")));
      }
    };
  }
  d3_selectionPrototype.style = function(name, value, priority) {
    var n = arguments.length;
    if (n < 3) {
      if (typeof name !== "string") {
        if (n < 2) value = "";
        for (priority in name) this.each(d3_selection_style(priority, name[priority], value));
        return this;
      }
      if (n < 2) {
        var node = this.node();
        return d3_window(node).getComputedStyle(node, null).getPropertyValue(name);
      }
      priority = "";
    }
    return this.each(d3_selection_style(name, value, priority));
  };
  function d3_selection_style(name, value, priority) {
    function styleNull() {
      this.style.removeProperty(name);
    }
    function styleConstant() {
      this.style.setProperty(name, value, priority);
    }
    function styleFunction() {
      var x = value.apply(this, arguments);
      if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority);
    }
    return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant;
  }
  d3_selectionPrototype.property = function(name, value) {
    if (arguments.length < 2) {
      if (typeof name === "string") return this.node()[name];
      for (value in name) this.each(d3_selection_property(value, name[value]));
      return this;
    }
    return this.each(d3_selection_property(name, value));
  };
  function d3_selection_property(name, value) {
    function propertyNull() {
      delete this[name];
    }
    function propertyConstant() {
      this[name] = value;
    }
    function propertyFunction() {
      var x = value.apply(this, arguments);
      if (x == null) delete this[name]; else this[name] = x;
    }
    return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant;
  }
  d3_selectionPrototype.text = function(value) {
    return arguments.length ? this.each(typeof value === "function" ? function() {
      var v = value.apply(this, arguments);
      this.textContent = v == null ? "" : v;
    } : value == null ? function() {
      this.textContent = "";
    } : function() {
      this.textContent = value;
    }) : this.node().textContent;
  };
  d3_selectionPrototype.html = function(value) {
    return arguments.length ? this.each(typeof value === "function" ? function() {
      var v = value.apply(this, arguments);
      this.innerHTML = v == null ? "" : v;
    } : value == null ? function() {
      this.innerHTML = "";
    } : function() {
      this.innerHTML = value;
    }) : this.node().innerHTML;
  };
  d3_selectionPrototype.append = function(name) {
    name = d3_selection_creator(name);
    return this.select(function() {
      return this.appendChild(name.apply(this, arguments));
    });
  };
  function d3_selection_creator(name) {
    function create() {
      var document = this.ownerDocument, namespace = this.namespaceURI;
      return namespace === d3_nsXhtml && document.documentElement.namespaceURI === d3_nsXhtml ? document.createElement(name) : document.createElementNS(namespace, name);
    }
    function createNS() {
      return this.ownerDocument.createElementNS(name.space, name.local);
    }
    return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? createNS : create;
  }
  d3_selectionPrototype.insert = function(name, before) {
    name = d3_selection_creator(name);
    before = d3_selection_selector(before);
    return this.select(function() {
      return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null);
    });
  };
  d3_selectionPrototype.remove = function() {
    return this.each(d3_selectionRemove);
  };
  function d3_selectionRemove() {
    var parent = this.parentNode;
    if (parent) parent.removeChild(this);
  }
  d3_selectionPrototype.data = function(value, key) {
    var i = -1, n = this.length, group, node;
    if (!arguments.length) {
      value = new Array(n = (group = this[0]).length);
      while (++i < n) {
        if (node = group[i]) {
          value[i] = node.__data__;
        }
      }
      return value;
    }
    function bind(group, groupData) {
      var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData;
      if (key) {
        var nodeByKeyValue = new d3_Map(), keyValues = new Array(n), keyValue;
        for (i = -1; ++i < n; ) {
          if (node = group[i]) {
            if (nodeByKeyValue.has(keyValue = key.call(node, node.__data__, i))) {
              exitNodes[i] = node;
            } else {
              nodeByKeyValue.set(keyValue, node);
            }
            keyValues[i] = keyValue;
          }
        }
        for (i = -1; ++i < m; ) {
          if (!(node = nodeByKeyValue.get(keyValue = key.call(groupData, nodeData = groupData[i], i)))) {
            enterNodes[i] = d3_selection_dataNode(nodeData);
          } else if (node !== true) {
            updateNodes[i] = node;
            node.__data__ = nodeData;
          }
          nodeByKeyValue.set(keyValue, true);
        }
        for (i = -1; ++i < n; ) {
          if (i in keyValues && nodeByKeyValue.get(keyValues[i]) !== true) {
            exitNodes[i] = group[i];
          }
        }
      } else {
        for (i = -1; ++i < n0; ) {
          node = group[i];
          nodeData = groupData[i];
          if (node) {
            node.__data__ = nodeData;
            updateNodes[i] = node;
          } else {
            enterNodes[i] = d3_selection_dataNode(nodeData);
          }
        }
        for (;i < m; ++i) {
          enterNodes[i] = d3_selection_dataNode(groupData[i]);
        }
        for (;i < n; ++i) {
          exitNodes[i] = group[i];
        }
      }
      enterNodes.update = updateNodes;
      enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode;
      enter.push(enterNodes);
      update.push(updateNodes);
      exit.push(exitNodes);
    }
    var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]);
    if (typeof value === "function") {
      while (++i < n) {
        bind(group = this[i], value.call(group, group.parentNode.__data__, i));
      }
    } else {
      while (++i < n) {
        bind(group = this[i], value);
      }
    }
    update.enter = function() {
      return enter;
    };
    update.exit = function() {
      return exit;
    };
    return update;
  };
  function d3_selection_dataNode(data) {
    return {
      __data__: data
    };
  }
  d3_selectionPrototype.datum = function(value) {
    return arguments.length ? this.property("__data__", value) : this.property("__data__");
  };
  d3_selectionPrototype.filter = function(filter) {
    var subgroups = [], subgroup, group, node;
    if (typeof filter !== "function") filter = d3_selection_filter(filter);
    for (var j = 0, m = this.length; j < m; j++) {
      subgroups.push(subgroup = []);
      subgroup.parentNode = (group = this[j]).parentNode;
      for (var i = 0, n = group.length; i < n; i++) {
        if ((node = group[i]) && filter.call(node, node.__data__, i, j)) {
          subgroup.push(node);
        }
      }
    }
    return d3_selection(subgroups);
  };
  function d3_selection_filter(selector) {
    return function() {
      return d3_selectMatches(this, selector);
    };
  }
  d3_selectionPrototype.order = function() {
    for (var j = -1, m = this.length; ++j < m; ) {
      for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) {
        if (node = group[i]) {
          if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next);
          next = node;
        }
      }
    }
    return this;
  };
  d3_selectionPrototype.sort = function(comparator) {
    comparator = d3_selection_sortComparator.apply(this, arguments);
    for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator);
    return this.order();
  };
  function d3_selection_sortComparator(comparator) {
    if (!arguments.length) comparator = d3_ascending;
    return function(a, b) {
      return a && b ? comparator(a.__data__, b.__data__) : !a - !b;
    };
  }
  d3_selectionPrototype.each = function(callback) {
    return d3_selection_each(this, function(node, i, j) {
      callback.call(node, node.__data__, i, j);
    });
  };
  function d3_selection_each(groups, callback) {
    for (var j = 0, m = groups.length; j < m; j++) {
      for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) {
        if (node = group[i]) callback(node, i, j);
      }
    }
    return groups;
  }
  d3_selectionPrototype.call = function(callback) {
    var args = d3_array(arguments);
    callback.apply(args[0] = this, args);
    return this;
  };
  d3_selectionPrototype.empty = function() {
    return !this.node();
  };
  d3_selectionPrototype.node = function() {
    for (var j = 0, m = this.length; j < m; j++) {
      for (var group = this[j], i = 0, n = group.length; i < n; i++) {
        var node = group[i];
        if (node) return node;
      }
    }
    return null;
  };
  d3_selectionPrototype.size = function() {
    var n = 0;
    d3_selection_each(this, function() {
      ++n;
    });
    return n;
  };
  function d3_selection_enter(selection) {
    d3_subclass(selection, d3_selection_enterPrototype);
    return selection;
  }
  var d3_selection_enterPrototype = [];
  d3.selection.enter = d3_selection_enter;
  d3.selection.enter.prototype = d3_selection_enterPrototype;
  d3_selection_enterPrototype.append = d3_selectionPrototype.append;
  d3_selection_enterPrototype.empty = d3_selectionPrototype.empty;
  d3_selection_enterPrototype.node = d3_selectionPrototype.node;
  d3_selection_enterPrototype.call = d3_selectionPrototype.call;
  d3_selection_enterPrototype.size = d3_selectionPrototype.size;
  d3_selection_enterPrototype.select = function(selector) {
    var subgroups = [], subgroup, subnode, upgroup, group, node;
    for (var j = -1, m = this.length; ++j < m; ) {
      upgroup = (group = this[j]).update;
      subgroups.push(subgroup = []);
      subgroup.parentNode = group.parentNode;
      for (var i = -1, n = group.length; ++i < n; ) {
        if (node = group[i]) {
          subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j));
          subnode.__data__ = node.__data__;
        } else {
          subgroup.push(null);
        }
      }
    }
    return d3_selection(subgroups);
  };
  d3_selection_enterPrototype.insert = function(name, before) {
    if (arguments.length < 2) before = d3_selection_enterInsertBefore(this);
    return d3_selectionPrototype.insert.call(this, name, before);
  };
  function d3_selection_enterInsertBefore(enter) {
    var i0, j0;
    return function(d, i, j) {
      var group = enter[j].update, n = group.length, node;
      if (j != j0) j0 = j, i0 = 0;
      if (i >= i0) i0 = i + 1;
      while (!(node = group[i0]) && ++i0 < n) ;
      return node;
    };
  }
  d3.select = function(node) {
    var group;
    if (typeof node === "string") {
      group = [ d3_select(node, d3_document) ];
      group.parentNode = d3_document.documentElement;
    } else {
      group = [ node ];
      group.parentNode = d3_documentElement(node);
    }
    return d3_selection([ group ]);
  };
  d3.selectAll = function(nodes) {
    var group;
    if (typeof nodes === "string") {
      group = d3_array(d3_selectAll(nodes, d3_document));
      group.parentNode = d3_document.documentElement;
    } else {
      group = d3_array(nodes);
      group.parentNode = null;
    }
    return d3_selection([ group ]);
  };
  d3_selectionPrototype.on = function(type, listener, capture) {
    var n = arguments.length;
    if (n < 3) {
      if (typeof type !== "string") {
        if (n < 2) listener = false;
        for (capture in type) this.each(d3_selection_on(capture, type[capture], listener));
        return this;
      }
      if (n < 2) return (n = this.node()["__on" + type]) && n._;
      capture = false;
    }
    return this.each(d3_selection_on(type, listener, capture));
  };
  function d3_selection_on(type, listener, capture) {
    var name = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener;
    if (i > 0) type = type.slice(0, i);
    var filter = d3_selection_onFilters.get(type);
    if (filter) type = filter, wrap = d3_selection_onFilter;
    function onRemove() {
      var l = this[name];
      if (l) {
        this.removeEventListener(type, l, l.$);
        delete this[name];
      }
    }
    function onAdd() {
      var l = wrap(listener, d3_array(arguments));
      onRemove.call(this);
      this.addEventListener(type, this[name] = l, l.$ = capture);
      l._ = listener;
    }
    function removeAll() {
      var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match;
      for (var name in this) {
        if (match = name.match(re)) {
          var l = this[name];
          this.removeEventListener(match[1], l, l.$);
          delete this[name];
        }
      }
    }
    return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll;
  }
  var d3_selection_onFilters = d3.map({
    mouseenter: "mouseover",
    mouseleave: "mouseout"
  });
  if (d3_document) {
    d3_selection_onFilters.forEach(function(k) {
      if ("on" + k in d3_document) d3_selection_onFilters.remove(k);
    });
  }
  function d3_selection_onListener(listener, argumentz) {
    return function(e) {
      var o = d3.event;
      d3.event = e;
      argumentz[0] = this.__data__;
      try {
        listener.apply(this, argumentz);
      } finally {
        d3.event = o;
      }
    };
  }
  function d3_selection_onFilter(listener, argumentz) {
    var l = d3_selection_onListener(listener, argumentz);
    return function(e) {
      var target = this, related = e.relatedTarget;
      if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) {
        l.call(target, e);
      }
    };
  }
  var d3_event_dragSelect, d3_event_dragId = 0;
  function d3_event_dragSuppress(node) {
    var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window(node)).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault);
    if (d3_event_dragSelect == null) {
      d3_event_dragSelect = "onselectstart" in node ? false : d3_vendorSymbol(node.style, "userSelect");
    }
    if (d3_event_dragSelect) {
      var style = d3_documentElement(node).style, select = style[d3_event_dragSelect];
      style[d3_event_dragSelect] = "none";
    }
    return function(suppressClick) {
      w.on(name, null);
      if (d3_event_dragSelect) style[d3_event_dragSelect] = select;
      if (suppressClick) {
        var off = function() {
          w.on(click, null);
        };
        w.on(click, function() {
          d3_eventPreventDefault();
          off();
        }, true);
        setTimeout(off, 0);
      }
    };
  }
  d3.mouse = function(container) {
    return d3_mousePoint(container, d3_eventSource());
  };
  var d3_mouse_bug44083 = this.navigator && /WebKit/.test(this.navigator.userAgent) ? -1 : 0;
  function d3_mousePoint(container, e) {
    if (e.changedTouches) e = e.changedTouches[0];
    var svg = container.ownerSVGElement || container;
    if (svg.createSVGPoint) {
      var point = svg.createSVGPoint();
      if (d3_mouse_bug44083 < 0) {
        var window = d3_window(container);
        if (window.scrollX || window.scrollY) {
          svg = d3.select("body").append("svg").style({
            position: "absolute",
            top: 0,
            left: 0,
            margin: 0,
            padding: 0,
            border: "none"
          }, "important");
          var ctm = svg[0][0].getScreenCTM();
          d3_mouse_bug44083 = !(ctm.f || ctm.e);
          svg.remove();
        }
      }
      if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; else point.x = e.clientX, 
      point.y = e.clientY;
      point = point.matrixTransform(container.getScreenCTM().inverse());
      return [ point.x, point.y ];
    }
    var rect = container.getBoundingClientRect();
    return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ];
  }
  d3.touch = function(container, touches, identifier) {
    if (arguments.length < 3) identifier = touches, touches = d3_eventSource().changedTouches;
    if (touches) for (var i = 0, n = touches.length, touch; i < n; ++i) {
      if ((touch = touches[i]).identifier === identifier) {
        return d3_mousePoint(container, touch);
      }
    }
  };
  d3.behavior.drag = function() {
    var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, d3_window, "mousemove", "mouseup"), touchstart = dragstart(d3_behavior_dragTouchId, d3.touch, d3_identity, "touchmove", "touchend");
    function drag() {
      this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart);
    }
    function dragstart(id, position, subject, move, end) {
      return function() {
        var that = this, target = d3.event.target.correspondingElement || d3.event.target, parent = that.parentNode, dispatch = event.of(that, arguments), dragged = 0, dragId = id(), dragName = ".drag" + (dragId == null ? "" : "-" + dragId), dragOffset, dragSubject = d3.select(subject(target)).on(move + dragName, moved).on(end + dragName, ended), dragRestore = d3_event_dragSuppress(target), position0 = position(parent, dragId);
        if (origin) {
          dragOffset = origin.apply(that, arguments);
          dragOffset = [ dragOffset.x - position0[0], dragOffset.y - position0[1] ];
        } else {
          dragOffset = [ 0, 0 ];
        }
        dispatch({
          type: "dragstart"
        });
        function moved() {
          var position1 = position(parent, dragId), dx, dy;
          if (!position1) return;
          dx = position1[0] - position0[0];
          dy = position1[1] - position0[1];
          dragged |= dx | dy;
          position0 = position1;
          dispatch({
            type: "drag",
            x: position1[0] + dragOffset[0],
            y: position1[1] + dragOffset[1],
            dx: dx,
            dy: dy
          });
        }
        function ended() {
          if (!position(parent, dragId)) return;
          dragSubject.on(move + dragName, null).on(end + dragName, null);
          dragRestore(dragged);
          dispatch({
            type: "dragend"
          });
        }
      };
    }
    drag.origin = function(x) {
      if (!arguments.length) return origin;
      origin = x;
      return drag;
    };
    return d3.rebind(drag, event, "on");
  };
  function d3_behavior_dragTouchId() {
    return d3.event.changedTouches[0].identifier;
  }
  d3.touches = function(container, touches) {
    if (arguments.length < 2) touches = d3_eventSource().touches;
    return touches ? d3_array(touches).map(function(touch) {
      var point = d3_mousePoint(container, touch);
      point.identifier = touch.identifier;
      return point;
    }) : [];
  };
  var ε = 1e-6, ε2 = ε * ε, π = Math.PI, τ = 2 * π, τε = τ - ε, halfπ = π / 2, d3_radians = π / 180, d3_degrees = 180 / π;
  function d3_sgn(x) {
    return x > 0 ? 1 : x < 0 ? -1 : 0;
  }
  function d3_cross2d(a, b, c) {
    return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
  }
  function d3_acos(x) {
    return x > 1 ? 0 : x < -1 ? π : Math.acos(x);
  }
  function d3_asin(x) {
    return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x);
  }
  function d3_sinh(x) {
    return ((x = Math.exp(x)) - 1 / x) / 2;
  }
  function d3_cosh(x) {
    return ((x = Math.exp(x)) + 1 / x) / 2;
  }
  function d3_tanh(x) {
    return ((x = Math.exp(2 * x)) - 1) / (x + 1);
  }
  function d3_haversin(x) {
    return (x = Math.sin(x / 2)) * x;
  }
  var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4;
  d3.interpolateZoom = function(p0, p1) {
    var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S;
    if (d2 < ε2) {
      S = Math.log(w1 / w0) / ρ;
      i = function(t) {
        return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * t * S) ];
      };
    } else {
      var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);
      S = (r1 - r0) / ρ;
      i = function(t) {
        var s = t * S, coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0));
        return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0) ];
      };
    }
    i.duration = S * 1e3;
    return i;
  };
  d3.behavior.zoom = function() {
    var view = {
      x: 0,
      y: 0,
      k: 1
    }, translate0, center0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, duration = 250, zooming = 0, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1;
    if (!d3_behavior_zoomWheel) {
      d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() {
        return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1);
      }, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() {
        return d3.event.wheelDelta;
      }, "mousewheel") : (d3_behavior_zoomDelta = function() {
        return -d3.event.detail;
      }, "MozMousePixelScroll");
    }
    function zoom(g) {
      g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted);
    }
    zoom.event = function(g) {
      g.each(function() {
        var dispatch = event.of(this, arguments), view1 = view;
        if (d3_transitionInheritId) {
          d3.select(this).transition().each("start.zoom", function() {
            view = this.__chart__ || {
              x: 0,
              y: 0,
              k: 1
            };
            zoomstarted(dispatch);
          }).tween("zoom:zoom", function() {
            var dx = size[0], dy = size[1], cx = center0 ? center0[0] : dx / 2, cy = center0 ? center0[1] : dy / 2, i = d3.interpolateZoom([ (cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k ], [ (cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k ]);
            return function(t) {
              var l = i(t), k = dx / l[2];
              this.__chart__ = view = {
                x: cx - l[0] * k,
                y: cy - l[1] * k,
                k: k
              };
              zoomed(dispatch);
            };
          }).each("interrupt.zoom", function() {
            zoomended(dispatch);
          }).each("end.zoom", function() {
            zoomended(dispatch);
          });
        } else {
          this.__chart__ = view;
          zoomstarted(dispatch);
          zoomed(dispatch);
          zoomended(dispatch);
        }
      });
    };
    zoom.translate = function(_) {
      if (!arguments.length) return [ view.x, view.y ];
      view = {
        x: +_[0],
        y: +_[1],
        k: view.k
      };
      rescale();
      return zoom;
    };
    zoom.scale = function(_) {
      if (!arguments.length) return view.k;
      view = {
        x: view.x,
        y: view.y,
        k: null
      };
      scaleTo(+_);
      rescale();
      return zoom;
    };
    zoom.scaleExtent = function(_) {
      if (!arguments.length) return scaleExtent;
      scaleExtent = _ == null ? d3_behavior_zoomInfinity : [ +_[0], +_[1] ];
      return zoom;
    };
    zoom.center = function(_) {
      if (!arguments.length) return center;
      center = _ && [ +_[0], +_[1] ];
      return zoom;
    };
    zoom.size = function(_) {
      if (!arguments.length) return size;
      size = _ && [ +_[0], +_[1] ];
      return zoom;
    };
    zoom.duration = function(_) {
      if (!arguments.length) return duration;
      duration = +_;
      return zoom;
    };
    zoom.x = function(z) {
      if (!arguments.length) return x1;
      x1 = z;
      x0 = z.copy();
      view = {
        x: 0,
        y: 0,
        k: 1
      };
      return zoom;
    };
    zoom.y = function(z) {
      if (!arguments.length) return y1;
      y1 = z;
      y0 = z.copy();
      view = {
        x: 0,
        y: 0,
        k: 1
      };
      return zoom;
    };
    function location(p) {
      return [ (p[0] - view.x) / view.k, (p[1] - view.y) / view.k ];
    }
    function point(l) {
      return [ l[0] * view.k + view.x, l[1] * view.k + view.y ];
    }
    function scaleTo(s) {
      view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s));
    }
    function translateTo(p, l) {
      l = point(l);
      view.x += p[0] - l[0];
      view.y += p[1] - l[1];
    }
    function zoomTo(that, p, l, k) {
      that.__chart__ = {
        x: view.x,
        y: view.y,
        k: view.k
      };
      scaleTo(Math.pow(2, k));
      translateTo(center0 = p, l);
      that = d3.select(that);
      if (duration > 0) that = that.transition().duration(duration);
      that.call(zoom.event);
    }
    function rescale() {
      if (x1) x1.domain(x0.range().map(function(x) {
        return (x - view.x) / view.k;
      }).map(x0.invert));
      if (y1) y1.domain(y0.range().map(function(y) {
        return (y - view.y) / view.k;
      }).map(y0.invert));
    }
    function zoomstarted(dispatch) {
      if (!zooming++) dispatch({
        type: "zoomstart"
      });
    }
    function zoomed(dispatch) {
      rescale();
      dispatch({
        type: "zoom",
        scale: view.k,
        translate: [ view.x, view.y ]
      });
    }
    function zoomended(dispatch) {
      if (!--zooming) dispatch({
        type: "zoomend"
      }), center0 = null;
    }
    function mousedowned() {
      var that = this, dispatch = event.of(that, arguments), dragged = 0, subject = d3.select(d3_window(that)).on(mousemove, moved).on(mouseup, ended), location0 = location(d3.mouse(that)), dragRestore = d3_event_dragSuppress(that);
      d3_selection_interrupt.call(that);
      zoomstarted(dispatch);
      function moved() {
        dragged = 1;
        translateTo(d3.mouse(that), location0);
        zoomed(dispatch);
      }
      function ended() {
        subject.on(mousemove, null).on(mouseup, null);
        dragRestore(dragged);
        zoomended(dispatch);
      }
    }
    function touchstarted() {
      var that = this, dispatch = event.of(that, arguments), locations0 = {}, distance0 = 0, scale0, zoomName = ".zoom-" + d3.event.changedTouches[0].identifier, touchmove = "touchmove" + zoomName, touchend = "touchend" + zoomName, targets = [], subject = d3.select(that), dragRestore = d3_event_dragSuppress(that);
      started();
      zoomstarted(dispatch);
      subject.on(mousedown, null).on(touchstart, started);
      function relocate() {
        var touches = d3.touches(that);
        scale0 = view.k;
        touches.forEach(function(t) {
          if (t.identifier in locations0) locations0[t.identifier] = location(t);
        });
        return touches;
      }
      function started() {
        var target = d3.event.target;
        d3.select(target).on(touchmove, moved).on(touchend, ended);
        targets.push(target);
        var changed = d3.event.changedTouches;
        for (var i = 0, n = changed.length; i < n; ++i) {
          locations0[changed[i].identifier] = null;
        }
        var touches = relocate(), now = Date.now();
        if (touches.length === 1) {
          if (now - touchtime < 500) {
            var p = touches[0];
            zoomTo(that, p, locations0[p.identifier], Math.floor(Math.log(view.k) / Math.LN2) + 1);
            d3_eventPreventDefault();
          }
          touchtime = now;
        } else if (touches.length > 1) {
          var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1];
          distance0 = dx * dx + dy * dy;
        }
      }
      function moved() {
        var touches = d3.touches(that), p0, l0, p1, l1;
        d3_selection_interrupt.call(that);
        for (var i = 0, n = touches.length; i < n; ++i, l1 = null) {
          p1 = touches[i];
          if (l1 = locations0[p1.identifier]) {
            if (l0) break;
            p0 = p1, l0 = l1;
          }
        }
        if (l1) {
          var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0);
          p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ];
          l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ];
          scaleTo(scale1 * scale0);
        }
        touchtime = null;
        translateTo(p0, l0);
        zoomed(dispatch);
      }
      function ended() {
        if (d3.event.touches.length) {
          var changed = d3.event.changedTouches;
          for (var i = 0, n = changed.length; i < n; ++i) {
            delete locations0[changed[i].identifier];
          }
          for (var identifier in locations0) {
            return void relocate();
          }
        }
        d3.selectAll(targets).on(zoomName, null);
        subject.on(mousedown, mousedowned).on(touchstart, touchstarted);
        dragRestore();
        zoomended(dispatch);
      }
    }
    function mousewheeled() {
      var dispatch = event.of(this, arguments);
      if (mousewheelTimer) clearTimeout(mousewheelTimer); else d3_selection_interrupt.call(this), 
      translate0 = location(center0 = center || d3.mouse(this)), zoomstarted(dispatch);
      mousewheelTimer = setTimeout(function() {
        mousewheelTimer = null;
        zoomended(dispatch);
      }, 50);
      d3_eventPreventDefault();
      scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k);
      translateTo(center0, translate0);
      zoomed(dispatch);
    }
    function dblclicked() {
      var p = d3.mouse(this), k = Math.log(view.k) / Math.LN2;
      zoomTo(this, p, location(p), d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1);
    }
    return d3.rebind(zoom, event, "on");
  };
  var d3_behavior_zoomInfinity = [ 0, Infinity ], d3_behavior_zoomDelta, d3_behavior_zoomWheel;
  d3.color = d3_color;
  function d3_color() {}
  d3_color.prototype.toString = function() {
    return this.rgb() + "";
  };
  d3.hsl = d3_hsl;
  function d3_hsl(h, s, l) {
    return this instanceof d3_hsl ? void (this.h = +h, this.s = +s, this.l = +l) : arguments.length < 2 ? h instanceof d3_hsl ? new d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : new d3_hsl(h, s, l);
  }
  var d3_hslPrototype = d3_hsl.prototype = new d3_color();
  d3_hslPrototype.brighter = function(k) {
    k = Math.pow(.7, arguments.length ? k : 1);
    return new d3_hsl(this.h, this.s, this.l / k);
  };
  d3_hslPrototype.darker = function(k) {
    k = Math.pow(.7, arguments.length ? k : 1);
    return new d3_hsl(this.h, this.s, k * this.l);
  };
  d3_hslPrototype.rgb = function() {
    return d3_hsl_rgb(this.h, this.s, this.l);
  };
  function d3_hsl_rgb(h, s, l) {
    var m1, m2;
    h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h;
    s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s;
    l = l < 0 ? 0 : l > 1 ? 1 : l;
    m2 = l <= .5 ? l * (1 + s) : l + s - l * s;
    m1 = 2 * l - m2;
    function v(h) {
      if (h > 360) h -= 360; else if (h < 0) h += 360;
      if (h < 60) return m1 + (m2 - m1) * h / 60;
      if (h < 180) return m2;
      if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60;
      return m1;
    }
    function vv(h) {
      return Math.round(v(h) * 255);
    }
    return new d3_rgb(vv(h + 120), vv(h), vv(h - 120));
  }
  d3.hcl = d3_hcl;
  function d3_hcl(h, c, l) {
    return this instanceof d3_hcl ? void (this.h = +h, this.c = +c, this.l = +l) : arguments.length < 2 ? h instanceof d3_hcl ? new d3_hcl(h.h, h.c, h.l) : h instanceof d3_lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : new d3_hcl(h, c, l);
  }
  var d3_hclPrototype = d3_hcl.prototype = new d3_color();
  d3_hclPrototype.brighter = function(k) {
    return new d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)));
  };
  d3_hclPrototype.darker = function(k) {
    return new d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)));
  };
  d3_hclPrototype.rgb = function() {
    return d3_hcl_lab(this.h, this.c, this.l).rgb();
  };
  function d3_hcl_lab(h, c, l) {
    if (isNaN(h)) h = 0;
    if (isNaN(c)) c = 0;
    return new d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c);
  }
  d3.lab = d3_lab;
  function d3_lab(l, a, b) {
    return this instanceof d3_lab ? void (this.l = +l, this.a = +a, this.b = +b) : arguments.length < 2 ? l instanceof d3_lab ? new d3_lab(l.l, l.a, l.b) : l instanceof d3_hcl ? d3_hcl_lab(l.h, l.c, l.l) : d3_rgb_lab((l = d3_rgb(l)).r, l.g, l.b) : new d3_lab(l, a, b);
  }
  var d3_lab_K = 18;
  var d3_lab_X = .95047, d3_lab_Y = 1, d3_lab_Z = 1.08883;
  var d3_labPrototype = d3_lab.prototype = new d3_color();
  d3_labPrototype.brighter = function(k) {
    return new d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b);
  };
  d3_labPrototype.darker = function(k) {
    return new d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b);
  };
  d3_labPrototype.rgb = function() {
    return d3_lab_rgb(this.l, this.a, this.b);
  };
  function d3_lab_rgb(l, a, b) {
    var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200;
    x = d3_lab_xyz(x) * d3_lab_X;
    y = d3_lab_xyz(y) * d3_lab_Y;
    z = d3_lab_xyz(z) * d3_lab_Z;
    return new d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z), d3_xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z), d3_xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z));
  }
  function d3_lab_hcl(l, a, b) {
    return l > 0 ? new d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : new d3_hcl(NaN, NaN, l);
  }
  function d3_lab_xyz(x) {
    return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037;
  }
  function d3_xyz_lab(x) {
    return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29;
  }
  function d3_xyz_rgb(r) {
    return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055));
  }
  d3.rgb = d3_rgb;
  function d3_rgb(r, g, b) {
    return this instanceof d3_rgb ? void (this.r = ~~r, this.g = ~~g, this.b = ~~b) : arguments.length < 2 ? r instanceof d3_rgb ? new d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : new d3_rgb(r, g, b);
  }
  function d3_rgbNumber(value) {
    return new d3_rgb(value >> 16, value >> 8 & 255, value & 255);
  }
  function d3_rgbString(value) {
    return d3_rgbNumber(value) + "";
  }
  var d3_rgbPrototype = d3_rgb.prototype = new d3_color();
  d3_rgbPrototype.brighter = function(k) {
    k = Math.pow(.7, arguments.length ? k : 1);
    var r = this.r, g = this.g, b = this.b, i = 30;
    if (!r && !g && !b) return new d3_rgb(i, i, i);
    if (r && r < i) r = i;
    if (g && g < i) g = i;
    if (b && b < i) b = i;
    return new d3_rgb(Math.min(255, r / k), Math.min(255, g / k), Math.min(255, b / k));
  };
  d3_rgbPrototype.darker = function(k) {
    k = Math.pow(.7, arguments.length ? k : 1);
    return new d3_rgb(k * this.r, k * this.g, k * this.b);
  };
  d3_rgbPrototype.hsl = function() {
    return d3_rgb_hsl(this.r, this.g, this.b);
  };
  d3_rgbPrototype.toString = function() {
    return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b);
  };
  function d3_rgb_hex(v) {
    return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16);
  }
  function d3_rgb_parse(format, rgb, hsl) {
    var r = 0, g = 0, b = 0, m1, m2, color;
    m1 = /([a-z]+)\((.*)\)/.exec(format = format.toLowerCase());
    if (m1) {
      m2 = m1[2].split(",");
      switch (m1[1]) {
       case "hsl":
        {
          return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100);
        }

       case "rgb":
        {
          return rgb(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2]));
        }
      }
    }
    if (color = d3_rgb_names.get(format)) {
      return rgb(color.r, color.g, color.b);
    }
    if (format != null && format.charAt(0) === "#" && !isNaN(color = parseInt(format.slice(1), 16))) {
      if (format.length === 4) {
        r = (color & 3840) >> 4;
        r = r >> 4 | r;
        g = color & 240;
        g = g >> 4 | g;
        b = color & 15;
        b = b << 4 | b;
      } else if (format.length === 7) {
        r = (color & 16711680) >> 16;
        g = (color & 65280) >> 8;
        b = color & 255;
      }
    }
    return rgb(r, g, b);
  }
  function d3_rgb_hsl(r, g, b) {
    var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2;
    if (d) {
      s = l < .5 ? d / (max + min) : d / (2 - max - min);
      if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4;
      h *= 60;
    } else {
      h = NaN;
      s = l > 0 && l < 1 ? 0 : h;
    }
    return new d3_hsl(h, s, l);
  }
  function d3_rgb_lab(r, g, b) {
    r = d3_rgb_xyz(r);
    g = d3_rgb_xyz(g);
    b = d3_rgb_xyz(b);
    var x = d3_xyz_lab((.4124564 * r + .3575761 * g + .1804375 * b) / d3_lab_X), y = d3_xyz_lab((.2126729 * r + .7151522 * g + .072175 * b) / d3_lab_Y), z = d3_xyz_lab((.0193339 * r + .119192 * g + .9503041 * b) / d3_lab_Z);
    return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z));
  }
  function d3_rgb_xyz(r) {
    return (r /= 255) <= .04045 ? r / 12.92 : Math.pow((r + .055) / 1.055, 2.4);
  }
  function d3_rgb_parseNumber(c) {
    var f = parseFloat(c);
    return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f;
  }
  var d3_rgb_names = d3.map({
    aliceblue: 15792383,
    antiquewhite: 16444375,
    aqua: 65535,
    aquamarine: 8388564,
    azure: 15794175,
    beige: 16119260,
    bisque: 16770244,
    black: 0,
    blanchedalmond: 16772045,
    blue: 255,
    blueviolet: 9055202,
    brown: 10824234,
    burlywood: 14596231,
    cadetblue: 6266528,
    chartreuse: 8388352,
    chocolate: 13789470,
    coral: 16744272,
    cornflowerblue: 6591981,
    cornsilk: 16775388,
    crimson: 14423100,
    cyan: 65535,
    darkblue: 139,
    darkcyan: 35723,
    darkgoldenrod: 12092939,
    darkgray: 11119017,
    darkgreen: 25600,
    darkgrey: 11119017,
    darkkhaki: 12433259,
    darkmagenta: 9109643,
    darkolivegreen: 5597999,
    darkorange: 16747520,
    darkorchid: 10040012,
    darkred: 9109504,
    darksalmon: 15308410,
    darkseagreen: 9419919,
    darkslateblue: 4734347,
    darkslategray: 3100495,
    darkslategrey: 3100495,
    darkturquoise: 52945,
    darkviolet: 9699539,
    deeppink: 16716947,
    deepskyblue: 49151,
    dimgray: 6908265,
    dimgrey: 6908265,
    dodgerblue: 2003199,
    firebrick: 11674146,
    floralwhite: 16775920,
    forestgreen: 2263842,
    fuchsia: 16711935,
    gainsboro: 14474460,
    ghostwhite: 16316671,
    gold: 16766720,
    goldenrod: 14329120,
    gray: 8421504,
    green: 32768,
    greenyellow: 11403055,
    grey: 8421504,
    honeydew: 15794160,
    hotpink: 16738740,
    indianred: 13458524,
    indigo: 4915330,
    ivory: 16777200,
    khaki: 15787660,
    lavender: 15132410,
    lavenderblush: 16773365,
    lawngreen: 8190976,
    lemonchiffon: 16775885,
    lightblue: 11393254,
    lightcoral: 15761536,
    lightcyan: 14745599,
    lightgoldenrodyellow: 16448210,
    lightgray: 13882323,
    lightgreen: 9498256,
    lightgrey: 13882323,
    lightpink: 16758465,
    lightsalmon: 16752762,
    lightseagreen: 2142890,
    lightskyblue: 8900346,
    lightslategray: 7833753,
    lightslategrey: 7833753,
    lightsteelblue: 11584734,
    lightyellow: 16777184,
    lime: 65280,
    limegreen: 3329330,
    linen: 16445670,
    magenta: 16711935,
    maroon: 8388608,
    mediumaquamarine: 6737322,
    mediumblue: 205,
    mediumorchid: 12211667,
    mediumpurple: 9662683,
    mediumseagreen: 3978097,
    mediumslateblue: 8087790,
    mediumspringgreen: 64154,
    mediumturquoise: 4772300,
    mediumvioletred: 13047173,
    midnightblue: 1644912,
    mintcream: 16121850,
    mistyrose: 16770273,
    moccasin: 16770229,
    navajowhite: 16768685,
    navy: 128,
    oldlace: 16643558,
    olive: 8421376,
    olivedrab: 7048739,
    orange: 16753920,
    orangered: 16729344,
    orchid: 14315734,
    palegoldenrod: 15657130,
    palegreen: 10025880,
    paleturquoise: 11529966,
    palevioletred: 14381203,
    papayawhip: 16773077,
    peachpuff: 16767673,
    peru: 13468991,
    pink: 16761035,
    plum: 14524637,
    powderblue: 11591910,
    purple: 8388736,
    rebeccapurple: 6697881,
    red: 16711680,
    rosybrown: 12357519,
    royalblue: 4286945,
    saddlebrown: 9127187,
    salmon: 16416882,
    sandybrown: 16032864,
    seagreen: 3050327,
    seashell: 16774638,
    sienna: 10506797,
    silver: 12632256,
    skyblue: 8900331,
    slateblue: 6970061,
    slategray: 7372944,
    slategrey: 7372944,
    snow: 16775930,
    springgreen: 65407,
    steelblue: 4620980,
    tan: 13808780,
    teal: 32896,
    thistle: 14204888,
    tomato: 16737095,
    turquoise: 4251856,
    violet: 15631086,
    wheat: 16113331,
    white: 16777215,
    whitesmoke: 16119285,
    yellow: 16776960,
    yellowgreen: 10145074
  });
  d3_rgb_names.forEach(function(key, value) {
    d3_rgb_names.set(key, d3_rgbNumber(value));
  });
  function d3_functor(v) {
    return typeof v === "function" ? v : function() {
      return v;
    };
  }
  d3.functor = d3_functor;
  d3.xhr = d3_xhrType(d3_identity);
  function d3_xhrType(response) {
    return function(url, mimeType, callback) {
      if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType, 
      mimeType = null;
      return d3_xhr(url, mimeType, response, callback);
    };
  }
  function d3_xhr(url, mimeType, response, callback) {
    var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null;
    if (this.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest();
    "onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() {
      request.readyState > 3 && respond();
    };
    function respond() {
      var status = request.status, result;
      if (!status && d3_xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) {
        try {
          result = response.call(xhr, request);
        } catch (e) {
          dispatch.error.call(xhr, e);
          return;
        }
        dispatch.load.call(xhr, result);
      } else {
        dispatch.error.call(xhr, request);
      }
    }
    request.onprogress = function(event) {
      var o = d3.event;
      d3.event = event;
      try {
        dispatch.progress.call(xhr, request);
      } finally {
        d3.event = o;
      }
    };
    xhr.header = function(name, value) {
      name = (name + "").toLowerCase();
      if (arguments.length < 2) return headers[name];
      if (value == null) delete headers[name]; else headers[name] = value + "";
      return xhr;
    };
    xhr.mimeType = function(value) {
      if (!arguments.length) return mimeType;
      mimeType = value == null ? null : value + "";
      return xhr;
    };
    xhr.responseType = function(value) {
      if (!arguments.length) return responseType;
      responseType = value;
      return xhr;
    };
    xhr.response = function(value) {
      response = value;
      return xhr;
    };
    [ "get", "post" ].forEach(function(method) {
      xhr[method] = function() {
        return xhr.send.apply(xhr, [ method ].concat(d3_array(arguments)));
      };
    });
    xhr.send = function(method, data, callback) {
      if (arguments.length === 2 && typeof data === "function") callback = data, data = null;
      request.open(method, url, true);
      if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*";
      if (request.setRequestHeader) for (var name in headers) request.setRequestHeader(name, headers[name]);
      if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType);
      if (responseType != null) request.responseType = responseType;
      if (callback != null) xhr.on("error", callback).on("load", function(request) {
        callback(null, request);
      });
      dispatch.beforesend.call(xhr, request);
      request.send(data == null ? null : data);
      return xhr;
    };
    xhr.abort = function() {
      request.abort();
      return xhr;
    };
    d3.rebind(xhr, dispatch, "on");
    return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback));
  }
  function d3_xhr_fixCallback(callback) {
    return callback.length === 1 ? function(error, request) {
      callback(error == null ? request : null);
    } : callback;
  }
  function d3_xhrHasResponse(request) {
    var type = request.responseType;
    return type && type !== "text" ? request.response : request.responseText;
  }
  d3.dsv = function(delimiter, mimeType) {
    var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0);
    function dsv(url, row, callback) {
      if (arguments.length < 3) callback = row, row = null;
      var xhr = d3_xhr(url, mimeType, row == null ? response : typedResponse(row), callback);
      xhr.row = function(_) {
        return arguments.length ? xhr.response((row = _) == null ? response : typedResponse(_)) : row;
      };
      return xhr;
    }
    function response(request) {
      return dsv.parse(request.responseText);
    }
    function typedResponse(f) {
      return function(request) {
        return dsv.parse(request.responseText, f);
      };
    }
    dsv.parse = function(text, f) {
      var o;
      return dsv.parseRows(text, function(row, i) {
        if (o) return o(row, i - 1);
        var a = new Function("d", "return {" + row.map(function(name, i) {
          return JSON.stringify(name) + ": d[" + i + "]";
        }).join(",") + "}");
        o = f ? function(row, i) {
          return f(a(row), i);
        } : a;
      });
    };
    dsv.parseRows = function(text, f) {
      var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol;
      function token() {
        if (I >= N) return EOF;
        if (eol) return eol = false, EOL;
        var j = I;
        if (text.charCodeAt(j) === 34) {
          var i = j;
          while (i++ < N) {
            if (text.charCodeAt(i) === 34) {
              if (text.charCodeAt(i + 1) !== 34) break;
              ++i;
            }
          }
          I = i + 2;
          var c = text.charCodeAt(i + 1);
          if (c === 13) {
            eol = true;
            if (text.charCodeAt(i + 2) === 10) ++I;
          } else if (c === 10) {
            eol = true;
          }
          return text.slice(j + 1, i).replace(/""/g, '"');
        }
        while (I < N) {
          var c = text.charCodeAt(I++), k = 1;
          if (c === 10) eol = true; else if (c === 13) {
            eol = true;
            if (text.charCodeAt(I) === 10) ++I, ++k;
          } else if (c !== delimiterCode) continue;
          return text.slice(j, I - k);
        }
        return text.slice(j);
      }
      while ((t = token()) !== EOF) {
        var a = [];
        while (t !== EOL && t !== EOF) {
          a.push(t);
          t = token();
        }
        if (f && (a = f(a, n++)) == null) continue;
        rows.push(a);
      }
      return rows;
    };
    dsv.format = function(rows) {
      if (Array.isArray(rows[0])) return dsv.formatRows(rows);
      var fieldSet = new d3_Set(), fields = [];
      rows.forEach(function(row) {
        for (var field in row) {
          if (!fieldSet.has(field)) {
            fields.push(fieldSet.add(field));
          }
        }
      });
      return [ fields.map(formatValue).join(delimiter) ].concat(rows.map(function(row) {
        return fields.map(function(field) {
          return formatValue(row[field]);
        }).join(delimiter);
      })).join("\n");
    };
    dsv.formatRows = function(rows) {
      return rows.map(formatRow).join("\n");
    };
    function formatRow(row) {
      return row.map(formatValue).join(delimiter);
    }
    function formatValue(text) {
      return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text;
    }
    return dsv;
  };
  d3.csv = d3.dsv(",", "text/csv");
  d3.tsv = d3.dsv("	", "text/tab-separated-values");
  var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_frame = this[d3_vendorSymbol(this, "requestAnimationFrame")] || function(callback) {
    setTimeout(callback, 17);
  };
  d3.timer = function() {
    d3_timer.apply(this, arguments);
  };
  function d3_timer(callback, delay, then) {
    var n = arguments.length;
    if (n < 2) delay = 0;
    if (n < 3) then = Date.now();
    var time = then + delay, timer = {
      c: callback,
      t: time,
      n: null
    };
    if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer;
    d3_timer_queueTail = timer;
    if (!d3_timer_interval) {
      d3_timer_timeout = clearTimeout(d3_timer_timeout);
      d3_timer_interval = 1;
      d3_timer_frame(d3_timer_step);
    }
    return timer;
  }
  function d3_timer_step() {
    var now = d3_timer_mark(), delay = d3_timer_sweep() - now;
    if (delay > 24) {
      if (isFinite(delay)) {
        clearTimeout(d3_timer_timeout);
        d3_timer_timeout = setTimeout(d3_timer_step, delay);
      }
      d3_timer_interval = 0;
    } else {
      d3_timer_interval = 1;
      d3_timer_frame(d3_timer_step);
    }
  }
  d3.timer.flush = function() {
    d3_timer_mark();
    d3_timer_sweep();
  };
  function d3_timer_mark() {
    var now = Date.now(), timer = d3_timer_queueHead;
    while (timer) {
      if (now >= timer.t && timer.c(now - timer.t)) timer.c = null;
      timer = timer.n;
    }
    return now;
  }
  function d3_timer_sweep() {
    var t0, t1 = d3_timer_queueHead, time = Infinity;
    while (t1) {
      if (t1.c) {
        if (t1.t < time) time = t1.t;
        t1 = (t0 = t1).n;
      } else {
        t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n;
      }
    }
    d3_timer_queueTail = t0;
    return time;
  }
  function d3_format_precision(x, p) {
    return p - (x ? Math.ceil(Math.log(x) / Math.LN10) : 1);
  }
  d3.round = function(x, n) {
    return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x);
  };
  var d3_formatPrefixes = [ "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" ].map(d3_formatPrefix);
  d3.formatPrefix = function(value, precision) {
    var i = 0;
    if (value = +value) {
      if (value < 0) value *= -1;
      if (precision) value = d3.round(value, d3_format_precision(value, precision));
      i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10);
      i = Math.max(-24, Math.min(24, Math.floor((i - 1) / 3) * 3));
    }
    return d3_formatPrefixes[8 + i / 3];
  };
  function d3_formatPrefix(d, i) {
    var k = Math.pow(10, abs(8 - i) * 3);
    return {
      scale: i > 8 ? function(d) {
        return d / k;
      } : function(d) {
        return d * k;
      },
      symbol: d
    };
  }
  function d3_locale_numberFormat(locale) {
    var locale_decimal = locale.decimal, locale_thousands = locale.thousands, locale_grouping = locale.grouping, locale_currency = locale.currency, formatGroup = locale_grouping && locale_thousands ? function(value, width) {
      var i = value.length, t = [], j = 0, g = locale_grouping[0], length = 0;
      while (i > 0 && g > 0) {
        if (length + g + 1 > width) g = Math.max(1, width - length);
        t.push(value.substring(i -= g, i + g));
        if ((length += g + 1) > width) break;
        g = locale_grouping[j = (j + 1) % locale_grouping.length];
      }
      return t.reverse().join(locale_thousands);
    } : d3_identity;
    return function(specifier) {
      var match = d3_format_re.exec(specifier), fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "-", symbol = match[4] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, prefix = "", suffix = "", integer = false, exponent = true;
      if (precision) precision = +precision.substring(1);
      if (zfill || fill === "0" && align === "=") {
        zfill = fill = "0";
        align = "=";
      }
      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();

       case "c":
        exponent = false;

       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 (type == "r" && !precision) type = "g";
      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));
      }
      type = d3_format_types.get(type) || d3_format_typeDefault;
      var zcomma = zfill && comma;
      return function(value) {
        var fullSuffix = suffix;
        if (integer && value % 1) return "";
        var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, "-") : sign === "-" ? "" : sign;
        if (scale < 0) {
          var unit = d3.formatPrefix(value, precision);
          value = unit.scale(value);
          fullSuffix = unit.symbol + suffix;
        } else {
          value *= scale;
        }
        value = type(value, precision);
        var i = value.lastIndexOf("."), before, after;
        if (i < 0) {
          var j = exponent ? value.lastIndexOf("e") : -1;
          if (j < 0) before = value, after = ""; else before = value.substring(0, j), after = value.substring(j);
        } else {
          before = value.substring(0, i);
          after = locale_decimal + value.substring(i + 1);
        }
        if (!zfill && comma) before = formatGroup(before, Infinity);
        var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length), padding = length < width ? new Array(length = width - length + 1).join(fill) : "";
        if (zcomma) before = formatGroup(padding + before, padding.length ? width - after.length : Infinity);
        negative += prefix;
        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;
      };
    };
  }
  var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i;
  var d3_format_types = d3.map({
    b: function(x) {
      return x.toString(2);
    },
    c: function(x) {
      return String.fromCharCode(x);
    },
    o: function(x) {
      return x.toString(8);
    },
    x: function(x) {
      return x.toString(16);
    },
    X: function(x) {
      return x.toString(16).toUpperCase();
    },
    g: function(x, p) {
      return x.toPrecision(p);
    },
    e: function(x, p) {
      return x.toExponential(p);
    },
    f: function(x, p) {
      return x.toFixed(p);
    },
    r: function(x, p) {
      return (x = d3.round(x, d3_format_precision(x, p))).toFixed(Math.max(0, Math.min(20, d3_format_precision(x * (1 + 1e-15), p))));
    }
  });
  function d3_format_typeDefault(x) {
    return x + "";
  }
  var d3_time = d3.time = {}, d3_date = Date;
  function d3_date_utc() {
    this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]);
  }
  d3_date_utc.prototype = {
    getDate: function() {
      return this._.getUTCDate();
    },
    getDay: function() {
      return this._.getUTCDay();
    },
    getFullYear: function() {
      return this._.getUTCFullYear();
    },
    getHours: function() {
      return this._.getUTCHours();
    },
    getMilliseconds: function() {
      return this._.getUTCMilliseconds();
    },
    getMinutes: function() {
      return this._.getUTCMinutes();
    },
    getMonth: function() {
      return this._.getUTCMonth();
    },
    getSeconds: function() {
      return this._.getUTCSeconds();
    },
    getTime: function() {
      return this._.getTime();
    },
    getTimezoneOffset: function() {
      return 0;
    },
    valueOf: function() {
      return this._.valueOf();
    },
    setDate: function() {
      d3_time_prototype.setUTCDate.apply(this._, arguments);
    },
    setDay: function() {
      d3_time_prototype.setUTCDay.apply(this._, arguments);
    },
    setFullYear: function() {
      d3_time_prototype.setUTCFullYear.apply(this._, arguments);
    },
    setHours: function() {
      d3_time_prototype.setUTCHours.apply(this._, arguments);
    },
    setMilliseconds: function() {
      d3_time_prototype.setUTCMilliseconds.apply(this._, arguments);
    },
    setMinutes: function() {
      d3_time_prototype.setUTCMinutes.apply(this._, arguments);
    },
    setMonth: function() {
      d3_time_prototype.setUTCMonth.apply(this._, arguments);
    },
    setSeconds: function() {
      d3_time_prototype.setUTCSeconds.apply(this._, arguments);
    },
    setTime: function() {
      d3_time_prototype.setTime.apply(this._, arguments);
    }
  };
  var d3_time_prototype = Date.prototype;
  function d3_time_interval(local, step, number) {
    function round(date) {
      var d0 = local(date), d1 = offset(d0, 1);
      return date - d0 < d1 - date ? d0 : d1;
    }
    function ceil(date) {
      step(date = local(new d3_date(date - 1)), 1);
      return date;
    }
    function offset(date, k) {
      step(date = new d3_date(+date), k);
      return date;
    }
    function range(t0, t1, dt) {
      var time = ceil(t0), times = [];
      if (dt > 1) {
        while (time < t1) {
          if (!(number(time) % dt)) times.push(new Date(+time));
          step(time, 1);
        }
      } else {
        while (time < t1) times.push(new Date(+time)), step(time, 1);
      }
      return times;
    }
    function range_utc(t0, t1, dt) {
      try {
        d3_date = d3_date_utc;
        var utc = new d3_date_utc();
        utc._ = t0;
        return range(utc, t1, dt);
      } finally {
        d3_date = Date;
      }
    }
    local.floor = local;
    local.round = round;
    local.ceil = ceil;
    local.offset = offset;
    local.range = range;
    var utc = local.utc = d3_time_interval_utc(local);
    utc.floor = utc;
    utc.round = d3_time_interval_utc(round);
    utc.ceil = d3_time_interval_utc(ceil);
    utc.offset = d3_time_interval_utc(offset);
    utc.range = range_utc;
    return local;
  }
  function d3_time_interval_utc(method) {
    return function(date, k) {
      try {
        d3_date = d3_date_utc;
        var utc = new d3_date_utc();
        utc._ = date;
        return method(utc, k)._;
      } finally {
        d3_date = Date;
      }
    };
  }
  d3_time.year = d3_time_interval(function(date) {
    date = d3_time.day(date);
    date.setMonth(0, 1);
    return date;
  }, function(date, offset) {
    date.setFullYear(date.getFullYear() + offset);
  }, function(date) {
    return date.getFullYear();
  });
  d3_time.years = d3_time.year.range;
  d3_time.years.utc = d3_time.year.utc.range;
  d3_time.day = d3_time_interval(function(date) {
    var day = new d3_date(2e3, 0);
    day.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());
    return day;
  }, function(date, offset) {
    date.setDate(date.getDate() + offset);
  }, function(date) {
    return date.getDate() - 1;
  });
  d3_time.days = d3_time.day.range;
  d3_time.days.utc = d3_time.day.utc.range;
  d3_time.dayOfYear = function(date) {
    var year = d3_time.year(date);
    return Math.floor((date - year - (date.getTimezoneOffset() - year.getTimezoneOffset()) * 6e4) / 864e5);
  };
  [ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ].forEach(function(day, i) {
    i = 7 - i;
    var interval = d3_time[day] = d3_time_interval(function(date) {
      (date = d3_time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7);
      return date;
    }, function(date, offset) {
      date.setDate(date.getDate() + Math.floor(offset) * 7);
    }, function(date) {
      var day = d3_time.year(date).getDay();
      return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i);
    });
    d3_time[day + "s"] = interval.range;
    d3_time[day + "s"].utc = interval.utc.range;
    d3_time[day + "OfYear"] = function(date) {
      var day = d3_time.year(date).getDay();
      return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7);
    };
  });
  d3_time.week = d3_time.sunday;
  d3_time.weeks = d3_time.sunday.range;
  d3_time.weeks.utc = d3_time.sunday.utc.range;
  d3_time.weekOfYear = d3_time.sundayOfYear;
  function d3_locale_timeFormat(locale) {
    var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_days = locale.days, locale_shortDays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths;
    function d3_time_format(template) {
      var n = template.length;
      function format(date) {
        var string = [], i = -1, j = 0, c, p, f;
        while (++i < n) {
          if (template.charCodeAt(i) === 37) {
            string.push(template.slice(j, i));
            if ((p = d3_time_formatPads[c = template.charAt(++i)]) != null) c = template.charAt(++i);
            if (f = d3_time_formats[c]) c = f(date, p == null ? c === "e" ? " " : "0" : p);
            string.push(c);
            j = i + 1;
          }
        }
        string.push(template.slice(j, i));
        return string.join("");
      }
      format.parse = function(string) {
        var d = {
          y: 1900,
          m: 0,
          d: 1,
          H: 0,
          M: 0,
          S: 0,
          L: 0,
          Z: null
        }, i = d3_time_parse(d, template, string, 0);
        if (i != string.length) return null;
        if ("p" in d) d.H = d.H % 12 + d.p * 12;
        var localZ = d.Z != null && d3_date !== d3_date_utc, date = new (localZ ? d3_date_utc : d3_date)();
        if ("j" in d) date.setFullYear(d.y, 0, d.j); else if ("W" in d || "U" in d) {
          if (!("w" in d)) d.w = "W" in d ? 1 : 0;
          date.setFullYear(d.y, 0, 1);
          date.setFullYear(d.y, 0, "W" in d ? (d.w + 6) % 7 + d.W * 7 - (date.getDay() + 5) % 7 : d.w + d.U * 7 - (date.getDay() + 6) % 7);
        } else date.setFullYear(d.y, d.m, d.d);
        date.setHours(d.H + (d.Z / 100 | 0), d.M + d.Z % 100, d.S, d.L);
        return localZ ? date._ : date;
      };
      format.toString = function() {
        return template;
      };
      return format;
    }
    function d3_time_parse(date, template, string, j) {
      var c, p, t, i = 0, n = template.length, m = string.length;
      while (i < n) {
        if (j >= m) return -1;
        c = template.charCodeAt(i++);
        if (c === 37) {
          t = template.charAt(i++);
          p = d3_time_parsers[t in d3_time_formatPads ? template.charAt(i++) : t];
          if (!p || (j = p(date, string, j)) < 0) return -1;
        } else if (c != string.charCodeAt(j++)) {
          return -1;
        }
      }
      return j;
    }
    d3_time_format.utc = function(template) {
      var local = d3_time_format(template);
      function format(date) {
        try {
          d3_date = d3_date_utc;
          var utc = new d3_date();
          utc._ = date;
          return local(utc);
        } finally {
          d3_date = Date;
        }
      }
      format.parse = function(string) {
        try {
          d3_date = d3_date_utc;
          var date = local.parse(string);
          return date && date._;
        } finally {
          d3_date = Date;
        }
      };
      format.toString = local.toString;
      return format;
    };
    d3_time_format.multi = d3_time_format.utc.multi = d3_time_formatMulti;
    var d3_time_periodLookup = d3.map(), d3_time_dayRe = d3_time_formatRe(locale_days), d3_time_dayLookup = d3_time_formatLookup(locale_days), d3_time_dayAbbrevRe = d3_time_formatRe(locale_shortDays), d3_time_dayAbbrevLookup = d3_time_formatLookup(locale_shortDays), d3_time_monthRe = d3_time_formatRe(locale_months), d3_time_monthLookup = d3_time_formatLookup(locale_months), d3_time_monthAbbrevRe = d3_time_formatRe(locale_shortMonths), d3_time_monthAbbrevLookup = d3_time_formatLookup(locale_shortMonths);
    locale_periods.forEach(function(p, i) {
      d3_time_periodLookup.set(p.toLowerCase(), i);
    });
    var d3_time_formats = {
      a: function(d) {
        return locale_shortDays[d.getDay()];
      },
      A: function(d) {
        return locale_days[d.getDay()];
      },
      b: function(d) {
        return locale_shortMonths[d.getMonth()];
      },
      B: function(d) {
        return locale_months[d.getMonth()];
      },
      c: d3_time_format(locale_dateTime),
      d: function(d, p) {
        return d3_time_formatPad(d.getDate(), p, 2);
      },
      e: function(d, p) {
        return d3_time_formatPad(d.getDate(), p, 2);
      },
      H: function(d, p) {
        return d3_time_formatPad(d.getHours(), p, 2);
      },
      I: function(d, p) {
        return d3_time_formatPad(d.getHours() % 12 || 12, p, 2);
      },
      j: function(d, p) {
        return d3_time_formatPad(1 + d3_time.dayOfYear(d), p, 3);
      },
      L: function(d, p) {
        return d3_time_formatPad(d.getMilliseconds(), p, 3);
      },
      m: function(d, p) {
        return d3_time_formatPad(d.getMonth() + 1, p, 2);
      },
      M: function(d, p) {
        return d3_time_formatPad(d.getMinutes(), p, 2);
      },
      p: function(d) {
        return locale_periods[+(d.getHours() >= 12)];
      },
      S: function(d, p) {
        return d3_time_formatPad(d.getSeconds(), p, 2);
      },
      U: function(d, p) {
        return d3_time_formatPad(d3_time.sundayOfYear(d), p, 2);
      },
      w: function(d) {
        return d.getDay();
      },
      W: function(d, p) {
        return d3_time_formatPad(d3_time.mondayOfYear(d), p, 2);
      },
      x: d3_time_format(locale_date),
      X: d3_time_format(locale_time),
      y: function(d, p) {
        return d3_time_formatPad(d.getFullYear() % 100, p, 2);
      },
      Y: function(d, p) {
        return d3_time_formatPad(d.getFullYear() % 1e4, p, 4);
      },
      Z: d3_time_zone,
      "%": function() {
        return "%";
      }
    };
    var d3_time_parsers = {
      a: d3_time_parseWeekdayAbbrev,
      A: d3_time_parseWeekday,
      b: d3_time_parseMonthAbbrev,
      B: d3_time_parseMonth,
      c: d3_time_parseLocaleFull,
      d: d3_time_parseDay,
      e: d3_time_parseDay,
      H: d3_time_parseHour24,
      I: d3_time_parseHour24,
      j: d3_time_parseDayOfYear,
      L: d3_time_parseMilliseconds,
      m: d3_time_parseMonthNumber,
      M: d3_time_parseMinutes,
      p: d3_time_parseAmPm,
      S: d3_time_parseSeconds,
      U: d3_time_parseWeekNumberSunday,
      w: d3_time_parseWeekdayNumber,
      W: d3_time_parseWeekNumberMonday,
      x: d3_time_parseLocaleDate,
      X: d3_time_parseLocaleTime,
      y: d3_time_parseYear,
      Y: d3_time_parseFullYear,
      Z: d3_time_parseZone,
      "%": d3_time_parseLiteralPercent
    };
    function d3_time_parseWeekdayAbbrev(date, string, i) {
      d3_time_dayAbbrevRe.lastIndex = 0;
      var n = d3_time_dayAbbrevRe.exec(string.slice(i));
      return n ? (date.w = d3_time_dayAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
    }
    function d3_time_parseWeekday(date, string, i) {
      d3_time_dayRe.lastIndex = 0;
      var n = d3_time_dayRe.exec(string.slice(i));
      return n ? (date.w = d3_time_dayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
    }
    function d3_time_parseMonthAbbrev(date, string, i) {
      d3_time_monthAbbrevRe.lastIndex = 0;
      var n = d3_time_monthAbbrevRe.exec(string.slice(i));
      return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
    }
    function d3_time_parseMonth(date, string, i) {
      d3_time_monthRe.lastIndex = 0;
      var n = d3_time_monthRe.exec(string.slice(i));
      return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
    }
    function d3_time_parseLocaleFull(date, string, i) {
      return d3_time_parse(date, d3_time_formats.c.toString(), string, i);
    }
    function d3_time_parseLocaleDate(date, string, i) {
      return d3_time_parse(date, d3_time_formats.x.toString(), string, i);
    }
    function d3_time_parseLocaleTime(date, string, i) {
      return d3_time_parse(date, d3_time_formats.X.toString(), string, i);
    }
    function d3_time_parseAmPm(date, string, i) {
      var n = d3_time_periodLookup.get(string.slice(i, i += 2).toLowerCase());
      return n == null ? -1 : (date.p = n, i);
    }
    return d3_time_format;
  }
  var d3_time_formatPads = {
    "-": "",
    _: " ",
    "0": "0"
  }, d3_time_numberRe = /^\s*\d+/, d3_time_percentRe = /^%/;
  function d3_time_formatPad(value, fill, width) {
    var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length;
    return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string);
  }
  function d3_time_formatRe(names) {
    return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i");
  }
  function d3_time_formatLookup(names) {
    var map = new d3_Map(), i = -1, n = names.length;
    while (++i < n) map.set(names[i].toLowerCase(), i);
    return map;
  }
  function d3_time_parseWeekdayNumber(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 1));
    return n ? (date.w = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseWeekNumberSunday(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i));
    return n ? (date.U = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseWeekNumberMonday(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i));
    return n ? (date.W = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseFullYear(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 4));
    return n ? (date.y = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseYear(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.y = d3_time_expandYear(+n[0]), i + n[0].length) : -1;
  }
  function d3_time_parseZone(date, string, i) {
    return /^[+-]\d{4}$/.test(string = string.slice(i, i + 5)) ? (date.Z = -string, 
    i + 5) : -1;
  }
  function d3_time_expandYear(d) {
    return d + (d > 68 ? 1900 : 2e3);
  }
  function d3_time_parseMonthNumber(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.m = n[0] - 1, i + n[0].length) : -1;
  }
  function d3_time_parseDay(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.d = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseDayOfYear(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 3));
    return n ? (date.j = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseHour24(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.H = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseMinutes(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.M = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseSeconds(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.S = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseMilliseconds(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 3));
    return n ? (date.L = +n[0], i + n[0].length) : -1;
  }
  function d3_time_zone(d) {
    var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = abs(z) / 60 | 0, zm = abs(z) % 60;
    return zs + d3_time_formatPad(zh, "0", 2) + d3_time_formatPad(zm, "0", 2);
  }
  function d3_time_parseLiteralPercent(date, string, i) {
    d3_time_percentRe.lastIndex = 0;
    var n = d3_time_percentRe.exec(string.slice(i, i + 1));
    return n ? i + n[0].length : -1;
  }
  function d3_time_formatMulti(formats) {
    var n = formats.length, i = -1;
    while (++i < n) formats[i][0] = this(formats[i][0]);
    return function(date) {
      var i = 0, f = formats[i];
      while (!f[1](date)) f = formats[++i];
      return f[0](date);
    };
  }
  d3.locale = function(locale) {
    return {
      numberFormat: d3_locale_numberFormat(locale),
      timeFormat: d3_locale_timeFormat(locale)
    };
  };
  var d3_locale_enUS = d3.locale({
    decimal: ".",
    thousands: ",",
    grouping: [ 3 ],
    currency: [ "$", "" ],
    dateTime: "%a %b %e %X %Y",
    date: "%m/%d/%Y",
    time: "%H:%M:%S",
    periods: [ "AM", "PM" ],
    days: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ],
    shortDays: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ],
    months: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ],
    shortMonths: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]
  });
  d3.format = d3_locale_enUS.numberFormat;
  d3.geo = {};
  function d3_adder() {}
  d3_adder.prototype = {
    s: 0,
    t: 0,
    add: function(y) {
      d3_adderSum(y, this.t, d3_adderTemp);
      d3_adderSum(d3_adderTemp.s, this.s, this);
      if (this.s) this.t += d3_adderTemp.t; else this.s = d3_adderTemp.t;
    },
    reset: function() {
      this.s = this.t = 0;
    },
    valueOf: function() {
      return this.s;
    }
  };
  var d3_adderTemp = new d3_adder();
  function d3_adderSum(a, b, o) {
    var x = o.s = a + b, bv = x - a, av = x - bv;
    o.t = a - av + (b - bv);
  }
  d3.geo.stream = function(object, listener) {
    if (object && d3_geo_streamObjectType.hasOwnProperty(object.type)) {
      d3_geo_streamObjectType[object.type](object, listener);
    } else {
      d3_geo_streamGeometry(object, listener);
    }
  };
  function d3_geo_streamGeometry(geometry, listener) {
    if (geometry && d3_geo_streamGeometryType.hasOwnProperty(geometry.type)) {
      d3_geo_streamGeometryType[geometry.type](geometry, listener);
    }
  }
  var d3_geo_streamObjectType = {
    Feature: function(feature, listener) {
      d3_geo_streamGeometry(feature.geometry, listener);
    },
    FeatureCollection: function(object, listener) {
      var features = object.features, i = -1, n = features.length;
      while (++i < n) d3_geo_streamGeometry(features[i].geometry, listener);
    }
  };
  var d3_geo_streamGeometryType = {
    Sphere: function(object, listener) {
      listener.sphere();
    },
    Point: function(object, listener) {
      object = object.coordinates;
      listener.point(object[0], object[1], object[2]);
    },
    MultiPoint: function(object, listener) {
      var coordinates = object.coordinates, i = -1, n = coordinates.length;
      while (++i < n) object = coordinates[i], listener.point(object[0], object[1], object[2]);
    },
    LineString: function(object, listener) {
      d3_geo_streamLine(object.coordinates, listener, 0);
    },
    MultiLineString: function(object, listener) {
      var coordinates = object.coordinates, i = -1, n = coordinates.length;
      while (++i < n) d3_geo_streamLine(coordinates[i], listener, 0);
    },
    Polygon: function(object, listener) {
      d3_geo_streamPolygon(object.coordinates, listener);
    },
    MultiPolygon: function(object, listener) {
      var coordinates = object.coordinates, i = -1, n = coordinates.length;
      while (++i < n) d3_geo_streamPolygon(coordinates[i], listener);
    },
    GeometryCollection: function(object, listener) {
      var geometries = object.geometries, i = -1, n = geometries.length;
      while (++i < n) d3_geo_streamGeometry(geometries[i], listener);
    }
  };
  function d3_geo_streamLine(coordinates, listener, closed) {
    var i = -1, n = coordinates.length - closed, coordinate;
    listener.lineStart();
    while (++i < n) coordinate = coordinates[i], listener.point(coordinate[0], coordinate[1], coordinate[2]);
    listener.lineEnd();
  }
  function d3_geo_streamPolygon(coordinates, listener) {
    var i = -1, n = coordinates.length;
    listener.polygonStart();
    while (++i < n) d3_geo_streamLine(coordinates[i], listener, 1);
    listener.polygonEnd();
  }
  d3.geo.area = function(object) {
    d3_geo_areaSum = 0;
    d3.geo.stream(object, d3_geo_area);
    return d3_geo_areaSum;
  };
  var d3_geo_areaSum, d3_geo_areaRingSum = new d3_adder();
  var d3_geo_area = {
    sphere: function() {
      d3_geo_areaSum += 4 * π;
    },
    point: d3_noop,
    lineStart: d3_noop,
    lineEnd: d3_noop,
    polygonStart: function() {
      d3_geo_areaRingSum.reset();
      d3_geo_area.lineStart = d3_geo_areaRingStart;
    },
    polygonEnd: function() {
      var area = 2 * d3_geo_areaRingSum;
      d3_geo_areaSum += area < 0 ? 4 * π + area : area;
      d3_geo_area.lineStart = d3_geo_area.lineEnd = d3_geo_area.point = d3_noop;
    }
  };
  function d3_geo_areaRingStart() {
    var λ00, φ00, λ0, cosφ0, sinφ0;
    d3_geo_area.point = function(λ, φ) {
      d3_geo_area.point = nextPoint;
      λ0 = (λ00 = λ) * d3_radians, cosφ0 = Math.cos(φ = (φ00 = φ) * d3_radians / 2 + π / 4), 
      sinφ0 = Math.sin(φ);
    };
    function nextPoint(λ, φ) {
      λ *= d3_radians;
      φ = φ * d3_radians / 2 + π / 4;
      var dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, cosφ = Math.cos(φ), sinφ = Math.sin(φ), k = sinφ0 * sinφ, u = cosφ0 * cosφ + k * Math.cos(adλ), v = k * sdλ * Math.sin(adλ);
      d3_geo_areaRingSum.add(Math.atan2(v, u));
      λ0 = λ, cosφ0 = cosφ, sinφ0 = sinφ;
    }
    d3_geo_area.lineEnd = function() {
      nextPoint(λ00, φ00);
    };
  }
  function d3_geo_cartesian(spherical) {
    var λ = spherical[0], φ = spherical[1], cosφ = Math.cos(φ);
    return [ cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ) ];
  }
  function d3_geo_cartesianDot(a, b) {
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  }
  function d3_geo_cartesianCross(a, b) {
    return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ];
  }
  function d3_geo_cartesianAdd(a, b) {
    a[0] += b[0];
    a[1] += b[1];
    a[2] += b[2];
  }
  function d3_geo_cartesianScale(vector, k) {
    return [ vector[0] * k, vector[1] * k, vector[2] * k ];
  }
  function d3_geo_cartesianNormalize(d) {
    var l = Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
    d[0] /= l;
    d[1] /= l;
    d[2] /= l;
  }
  function d3_geo_spherical(cartesian) {
    return [ Math.atan2(cartesian[1], cartesian[0]), d3_asin(cartesian[2]) ];
  }
  function d3_geo_sphericalEqual(a, b) {
    return abs(a[0] - b[0]) < ε && abs(a[1] - b[1]) < ε;
  }
  d3.geo.bounds = function() {
    var λ0, φ0, λ1, φ1, λ_, λ__, φ__, p0, dλSum, ranges, range;
    var bound = {
      point: point,
      lineStart: lineStart,
      lineEnd: lineEnd,
      polygonStart: function() {
        bound.point = ringPoint;
        bound.lineStart = ringStart;
        bound.lineEnd = ringEnd;
        dλSum = 0;
        d3_geo_area.polygonStart();
      },
      polygonEnd: function() {
        d3_geo_area.polygonEnd();
        bound.point = point;
        bound.lineStart = lineStart;
        bound.lineEnd = lineEnd;
        if (d3_geo_areaRingSum < 0) λ0 = -(λ1 = 180), φ0 = -(φ1 = 90); else if (dλSum > ε) φ1 = 90; else if (dλSum < -ε) φ0 = -90;
        range[0] = λ0, range[1] = λ1;
      }
    };
    function point(λ, φ) {
      ranges.push(range = [ λ0 = λ, λ1 = λ ]);
      if (φ < φ0) φ0 = φ;
      if (φ > φ1) φ1 = φ;
    }
    function linePoint(λ, φ) {
      var p = d3_geo_cartesian([ λ * d3_radians, φ * d3_radians ]);
      if (p0) {
        var normal = d3_geo_cartesianCross(p0, p), equatorial = [ normal[1], -normal[0], 0 ], inflection = d3_geo_cartesianCross(equatorial, normal);
        d3_geo_cartesianNormalize(inflection);
        inflection = d3_geo_spherical(inflection);
        var dλ = λ - λ_, s = dλ > 0 ? 1 : -1, λi = inflection[0] * d3_degrees * s, antimeridian = abs(dλ) > 180;
        if (antimeridian ^ (s * λ_ < λi && λi < s * λ)) {
          var φi = inflection[1] * d3_degrees;
          if (φi > φ1) φ1 = φi;
        } else if (λi = (λi + 360) % 360 - 180, antimeridian ^ (s * λ_ < λi && λi < s * λ)) {
          var φi = -inflection[1] * d3_degrees;
          if (φi < φ0) φ0 = φi;
        } else {
          if (φ < φ0) φ0 = φ;
          if (φ > φ1) φ1 = φ;
        }
        if (antimeridian) {
          if (λ < λ_) {
            if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ;
          } else {
            if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ;
          }
        } else {
          if (λ1 >= λ0) {
            if (λ < λ0) λ0 = λ;
            if (λ > λ1) λ1 = λ;
          } else {
            if (λ > λ_) {
              if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ;
            } else {
              if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ;
            }
          }
        }
      } else {
        point(λ, φ);
      }
      p0 = p, λ_ = λ;
    }
    function lineStart() {
      bound.point = linePoint;
    }
    function lineEnd() {
      range[0] = λ0, range[1] = λ1;
      bound.point = point;
      p0 = null;
    }
    function ringPoint(λ, φ) {
      if (p0) {
        var dλ = λ - λ_;
        dλSum += abs(dλ) > 180 ? dλ + (dλ > 0 ? 360 : -360) : dλ;
      } else λ__ = λ, φ__ = φ;
      d3_geo_area.point(λ, φ);
      linePoint(λ, φ);
    }
    function ringStart() {
      d3_geo_area.lineStart();
    }
    function ringEnd() {
      ringPoint(λ__, φ__);
      d3_geo_area.lineEnd();
      if (abs(dλSum) > ε) λ0 = -(λ1 = 180);
      range[0] = λ0, range[1] = λ1;
      p0 = null;
    }
    function angle(λ0, λ1) {
      return (λ1 -= λ0) < 0 ? λ1 + 360 : λ1;
    }
    function compareRanges(a, b) {
      return a[0] - b[0];
    }
    function withinRange(x, range) {
      return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x;
    }
    return function(feature) {
      φ1 = λ1 = -(λ0 = φ0 = Infinity);
      ranges = [];
      d3.geo.stream(feature, bound);
      var n = ranges.length;
      if (n) {
        ranges.sort(compareRanges);
        for (var i = 1, a = ranges[0], b, merged = [ a ]; i < n; ++i) {
          b = ranges[i];
          if (withinRange(b[0], a) || withinRange(b[1], a)) {
            if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1];
            if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0];
          } else {
            merged.push(a = b);
          }
        }
        var best = -Infinity, dλ;
        for (var n = merged.length - 1, i = 0, a = merged[n], b; i <= n; a = b, ++i) {
          b = merged[i];
          if ((dλ = angle(a[1], b[0])) > best) best = dλ, λ0 = b[0], λ1 = a[1];
        }
      }
      ranges = range = null;
      return λ0 === Infinity || φ0 === Infinity ? [ [ NaN, NaN ], [ NaN, NaN ] ] : [ [ λ0, φ0 ], [ λ1, φ1 ] ];
    };
  }();
  d3.geo.centroid = function(object) {
    d3_geo_centroidW0 = d3_geo_centroidW1 = d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0;
    d3.geo.stream(object, d3_geo_centroid);
    var x = d3_geo_centroidX2, y = d3_geo_centroidY2, z = d3_geo_centroidZ2, m = x * x + y * y + z * z;
    if (m < ε2) {
      x = d3_geo_centroidX1, y = d3_geo_centroidY1, z = d3_geo_centroidZ1;
      if (d3_geo_centroidW1 < ε) x = d3_geo_centroidX0, y = d3_geo_centroidY0, z = d3_geo_centroidZ0;
      m = x * x + y * y + z * z;
      if (m < ε2) return [ NaN, NaN ];
    }
    return [ Math.atan2(y, x) * d3_degrees, d3_asin(z / Math.sqrt(m)) * d3_degrees ];
  };
  var d3_geo_centroidW0, d3_geo_centroidW1, d3_geo_centroidX0, d3_geo_centroidY0, d3_geo_centroidZ0, d3_geo_centroidX1, d3_geo_centroidY1, d3_geo_centroidZ1, d3_geo_centroidX2, d3_geo_centroidY2, d3_geo_centroidZ2;
  var d3_geo_centroid = {
    sphere: d3_noop,
    point: d3_geo_centroidPoint,
    lineStart: d3_geo_centroidLineStart,
    lineEnd: d3_geo_centroidLineEnd,
    polygonStart: function() {
      d3_geo_centroid.lineStart = d3_geo_centroidRingStart;
    },
    polygonEnd: function() {
      d3_geo_centroid.lineStart = d3_geo_centroidLineStart;
    }
  };
  function d3_geo_centroidPoint(λ, φ) {
    λ *= d3_radians;
    var cosφ = Math.cos(φ *= d3_radians);
    d3_geo_centroidPointXYZ(cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ));
  }
  function d3_geo_centroidPointXYZ(x, y, z) {
    ++d3_geo_centroidW0;
    d3_geo_centroidX0 += (x - d3_geo_centroidX0) / d3_geo_centroidW0;
    d3_geo_centroidY0 += (y - d3_geo_centroidY0) / d3_geo_centroidW0;
    d3_geo_centroidZ0 += (z - d3_geo_centroidZ0) / d3_geo_centroidW0;
  }
  function d3_geo_centroidLineStart() {
    var x0, y0, z0;
    d3_geo_centroid.point = function(λ, φ) {
      λ *= d3_radians;
      var cosφ = Math.cos(φ *= d3_radians);
      x0 = cosφ * Math.cos(λ);
      y0 = cosφ * Math.sin(λ);
      z0 = Math.sin(φ);
      d3_geo_centroid.point = nextPoint;
      d3_geo_centroidPointXYZ(x0, y0, z0);
    };
    function nextPoint(λ, φ) {
      λ *= d3_radians;
      var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), w = Math.atan2(Math.sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z);
      d3_geo_centroidW1 += w;
      d3_geo_centroidX1 += w * (x0 + (x0 = x));
      d3_geo_centroidY1 += w * (y0 + (y0 = y));
      d3_geo_centroidZ1 += w * (z0 + (z0 = z));
      d3_geo_centroidPointXYZ(x0, y0, z0);
    }
  }
  function d3_geo_centroidLineEnd() {
    d3_geo_centroid.point = d3_geo_centroidPoint;
  }
  function d3_geo_centroidRingStart() {
    var λ00, φ00, x0, y0, z0;
    d3_geo_centroid.point = function(λ, φ) {
      λ00 = λ, φ00 = φ;
      d3_geo_centroid.point = nextPoint;
      λ *= d3_radians;
      var cosφ = Math.cos(φ *= d3_radians);
      x0 = cosφ * Math.cos(λ);
      y0 = cosφ * Math.sin(λ);
      z0 = Math.sin(φ);
      d3_geo_centroidPointXYZ(x0, y0, z0);
    };
    d3_geo_centroid.lineEnd = function() {
      nextPoint(λ00, φ00);
      d3_geo_centroid.lineEnd = d3_geo_centroidLineEnd;
      d3_geo_centroid.point = d3_geo_centroidPoint;
    };
    function nextPoint(λ, φ) {
      λ *= d3_radians;
      var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = Math.sqrt(cx * cx + cy * cy + cz * cz), u = x0 * x + y0 * y + z0 * z, v = m && -d3_acos(u) / m, w = Math.atan2(m, u);
      d3_geo_centroidX2 += v * cx;
      d3_geo_centroidY2 += v * cy;
      d3_geo_centroidZ2 += v * cz;
      d3_geo_centroidW1 += w;
      d3_geo_centroidX1 += w * (x0 + (x0 = x));
      d3_geo_centroidY1 += w * (y0 + (y0 = y));
      d3_geo_centroidZ1 += w * (z0 + (z0 = z));
      d3_geo_centroidPointXYZ(x0, y0, z0);
    }
  }
  function d3_geo_compose(a, b) {
    function compose(x, y) {
      return x = a(x, y), b(x[0], x[1]);
    }
    if (a.invert && b.invert) compose.invert = function(x, y) {
      return x = b.invert(x, y), x && a.invert(x[0], x[1]);
    };
    return compose;
  }
  function d3_true() {
    return true;
  }
  function d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener) {
    var subject = [], clip = [];
    segments.forEach(function(segment) {
      if ((n = segment.length - 1) <= 0) return;
      var n, p0 = segment[0], p1 = segment[n];
      if (d3_geo_sphericalEqual(p0, p1)) {
        listener.lineStart();
        for (var i = 0; i < n; ++i) listener.point((p0 = segment[i])[0], p0[1]);
        listener.lineEnd();
        return;
      }
      var a = new d3_geo_clipPolygonIntersection(p0, segment, null, true), b = new d3_geo_clipPolygonIntersection(p0, null, a, false);
      a.o = b;
      subject.push(a);
      clip.push(b);
      a = new d3_geo_clipPolygonIntersection(p1, segment, null, false);
      b = new d3_geo_clipPolygonIntersection(p1, null, a, true);
      a.o = b;
      subject.push(a);
      clip.push(b);
    });
    clip.sort(compare);
    d3_geo_clipPolygonLinkCircular(subject);
    d3_geo_clipPolygonLinkCircular(clip);
    if (!subject.length) return;
    for (var i = 0, entry = clipStartInside, n = clip.length; i < n; ++i) {
      clip[i].e = entry = !entry;
    }
    var start = subject[0], points, point;
    while (1) {
      var current = start, isSubject = true;
      while (current.v) if ((current = current.n) === start) return;
      points = current.z;
      listener.lineStart();
      do {
        current.v = current.o.v = true;
        if (current.e) {
          if (isSubject) {
            for (var i = 0, n = points.length; i < n; ++i) listener.point((point = points[i])[0], point[1]);
          } else {
            interpolate(current.x, current.n.x, 1, listener);
          }
          current = current.n;
        } else {
          if (isSubject) {
            points = current.p.z;
            for (var i = points.length - 1; i >= 0; --i) listener.point((point = points[i])[0], point[1]);
          } else {
            interpolate(current.x, current.p.x, -1, listener);
          }
          current = current.p;
        }
        current = current.o;
        points = current.z;
        isSubject = !isSubject;
      } while (!current.v);
      listener.lineEnd();
    }
  }
  function d3_geo_clipPolygonLinkCircular(array) {
    if (!(n = array.length)) return;
    var n, i = 0, a = array[0], b;
    while (++i < n) {
      a.n = b = array[i];
      b.p = a;
      a = b;
    }
    a.n = b = array[0];
    b.p = a;
  }
  function d3_geo_clipPolygonIntersection(point, points, other, entry) {
    this.x = point;
    this.z = points;
    this.o = other;
    this.e = entry;
    this.v = false;
    this.n = this.p = null;
  }
  function d3_geo_clip(pointVisible, clipLine, interpolate, clipStart) {
    return function(rotate, listener) {
      var line = clipLine(listener), rotatedClipStart = rotate.invert(clipStart[0], clipStart[1]);
      var clip = {
        point: point,
        lineStart: lineStart,
        lineEnd: lineEnd,
        polygonStart: function() {
          clip.point = pointRing;
          clip.lineStart = ringStart;
          clip.lineEnd = ringEnd;
          segments = [];
          polygon = [];
        },
        polygonEnd: function() {
          clip.point = point;
          clip.lineStart = lineStart;
          clip.lineEnd = lineEnd;
          segments = d3.merge(segments);
          var clipStartInside = d3_geo_pointInPolygon(rotatedClipStart, polygon);
          if (segments.length) {
            if (!polygonStarted) listener.polygonStart(), polygonStarted = true;
            d3_geo_clipPolygon(segments, d3_geo_clipSort, clipStartInside, interpolate, listener);
          } else if (clipStartInside) {
            if (!polygonStarted) listener.polygonStart(), polygonStarted = true;
            listener.lineStart();
            interpolate(null, null, 1, listener);
            listener.lineEnd();
          }
          if (polygonStarted) listener.polygonEnd(), polygonStarted = false;
          segments = polygon = null;
        },
        sphere: function() {
          listener.polygonStart();
          listener.lineStart();
          interpolate(null, null, 1, listener);
          listener.lineEnd();
          listener.polygonEnd();
        }
      };
      function point(λ, φ) {
        var point = rotate(λ, φ);
        if (pointVisible(λ = point[0], φ = point[1])) listener.point(λ, φ);
      }
      function pointLine(λ, φ) {
        var point = rotate(λ, φ);
        line.point(point[0], point[1]);
      }
      function lineStart() {
        clip.point = pointLine;
        line.lineStart();
      }
      function lineEnd() {
        clip.point = point;
        line.lineEnd();
      }
      var segments;
      var buffer = d3_geo_clipBufferListener(), ringListener = clipLine(buffer), polygonStarted = false, polygon, ring;
      function pointRing(λ, φ) {
        ring.push([ λ, φ ]);
        var point = rotate(λ, φ);
        ringListener.point(point[0], point[1]);
      }
      function ringStart() {
        ringListener.lineStart();
        ring = [];
      }
      function ringEnd() {
        pointRing(ring[0][0], ring[0][1]);
        ringListener.lineEnd();
        var clean = ringListener.clean(), ringSegments = buffer.buffer(), segment, n = ringSegments.length;
        ring.pop();
        polygon.push(ring);
        ring = null;
        if (!n) return;
        if (clean & 1) {
          segment = ringSegments[0];
          var n = segment.length - 1, i = -1, point;
          if (n > 0) {
            if (!polygonStarted) listener.polygonStart(), polygonStarted = true;
            listener.lineStart();
            while (++i < n) listener.point((point = segment[i])[0], point[1]);
            listener.lineEnd();
          }
          return;
        }
        if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift()));
        segments.push(ringSegments.filter(d3_geo_clipSegmentLength1));
      }
      return clip;
    };
  }
  function d3_geo_clipSegmentLength1(segment) {
    return segment.length > 1;
  }
  function d3_geo_clipBufferListener() {
    var lines = [], line;
    return {
      lineStart: function() {
        lines.push(line = []);
      },
      point: function(λ, φ) {
        line.push([ λ, φ ]);
      },
      lineEnd: d3_noop,
      buffer: function() {
        var buffer = lines;
        lines = [];
        line = null;
        return buffer;
      },
      rejoin: function() {
        if (lines.length > 1) lines.push(lines.pop().concat(lines.shift()));
      }
    };
  }
  function d3_geo_clipSort(a, b) {
    return ((a = a.x)[0] < 0 ? a[1] - halfπ - ε : halfπ - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfπ - ε : halfπ - b[1]);
  }
  var d3_geo_clipAntimeridian = d3_geo_clip(d3_true, d3_geo_clipAntimeridianLine, d3_geo_clipAntimeridianInterpolate, [ -π, -π / 2 ]);
  function d3_geo_clipAntimeridianLine(listener) {
    var λ0 = NaN, φ0 = NaN, sλ0 = NaN, clean;
    return {
      lineStart: function() {
        listener.lineStart();
        clean = 1;
      },
      point: function(λ1, φ1) {
        var sλ1 = λ1 > 0 ? π : -π, dλ = abs(λ1 - λ0);
        if (abs(dλ - π) < ε) {
          listener.point(λ0, φ0 = (φ0 + φ1) / 2 > 0 ? halfπ : -halfπ);
          listener.point(sλ0, φ0);
          listener.lineEnd();
          listener.lineStart();
          listener.point(sλ1, φ0);
          listener.point(λ1, φ0);
          clean = 0;
        } else if (sλ0 !== sλ1 && dλ >= π) {
          if (abs(λ0 - sλ0) < ε) λ0 -= sλ0 * ε;
          if (abs(λ1 - sλ1) < ε) λ1 -= sλ1 * ε;
          φ0 = d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1);
          listener.point(sλ0, φ0);
          listener.lineEnd();
          listener.lineStart();
          listener.point(sλ1, φ0);
          clean = 0;
        }
        listener.point(λ0 = λ1, φ0 = φ1);
        sλ0 = sλ1;
      },
      lineEnd: function() {
        listener.lineEnd();
        λ0 = φ0 = NaN;
      },
      clean: function() {
        return 2 - clean;
      }
    };
  }
  function d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1) {
    var cosφ0, cosφ1, sinλ0_λ1 = Math.sin(λ0 - λ1);
    return abs(sinλ0_λ1) > ε ? Math.atan((Math.sin(φ0) * (cosφ1 = Math.cos(φ1)) * Math.sin(λ1) - Math.sin(φ1) * (cosφ0 = Math.cos(φ0)) * Math.sin(λ0)) / (cosφ0 * cosφ1 * sinλ0_λ1)) : (φ0 + φ1) / 2;
  }
  function d3_geo_clipAntimeridianInterpolate(from, to, direction, listener) {
    var φ;
    if (from == null) {
      φ = direction * halfπ;
      listener.point(-π, φ);
      listener.point(0, φ);
      listener.point(π, φ);
      listener.point(π, 0);
      listener.point(π, -φ);
      listener.point(0, -φ);
      listener.point(-π, -φ);
      listener.point(-π, 0);
      listener.point(-π, φ);
    } else if (abs(from[0] - to[0]) > ε) {
      var s = from[0] < to[0] ? π : -π;
      φ = direction * s / 2;
      listener.point(-s, φ);
      listener.point(0, φ);
      listener.point(s, φ);
    } else {
      listener.point(to[0], to[1]);
    }
  }
  function d3_geo_pointInPolygon(point, polygon) {
    var meridian = point[0], parallel = point[1], meridianNormal = [ Math.sin(meridian), -Math.cos(meridian), 0 ], polarAngle = 0, winding = 0;
    d3_geo_areaRingSum.reset();
    for (var i = 0, n = polygon.length; i < n; ++i) {
      var ring = polygon[i], m = ring.length;
      if (!m) continue;
      var point0 = ring[0], λ0 = point0[0], φ0 = point0[1] / 2 + π / 4, sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), j = 1;
      while (true) {
        if (j === m) j = 0;
        point = ring[j];
        var λ = point[0], φ = point[1] / 2 + π / 4, sinφ = Math.sin(φ), cosφ = Math.cos(φ), dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, antimeridian = adλ > π, k = sinφ0 * sinφ;
        d3_geo_areaRingSum.add(Math.atan2(k * sdλ * Math.sin(adλ), cosφ0 * cosφ + k * Math.cos(adλ)));
        polarAngle += antimeridian ? dλ + sdλ * τ : dλ;
        if (antimeridian ^ λ0 >= meridian ^ λ >= meridian) {
          var arc = d3_geo_cartesianCross(d3_geo_cartesian(point0), d3_geo_cartesian(point));
          d3_geo_cartesianNormalize(arc);
          var intersection = d3_geo_cartesianCross(meridianNormal, arc);
          d3_geo_cartesianNormalize(intersection);
          var φarc = (antimeridian ^ dλ >= 0 ? -1 : 1) * d3_asin(intersection[2]);
          if (parallel > φarc || parallel === φarc && (arc[0] || arc[1])) {
            winding += antimeridian ^ dλ >= 0 ? 1 : -1;
          }
        }
        if (!j++) break;
        λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ, point0 = point;
      }
    }
    return (polarAngle < -ε || polarAngle < ε && d3_geo_areaRingSum < -ε) ^ winding & 1;
  }
  function d3_geo_clipCircle(radius) {
    var cr = Math.cos(radius), smallRadius = cr > 0, notHemisphere = abs(cr) > ε, interpolate = d3_geo_circleInterpolate(radius, 6 * d3_radians);
    return d3_geo_clip(visible, clipLine, interpolate, smallRadius ? [ 0, -radius ] : [ -π, radius - π ]);
    function visible(λ, φ) {
      return Math.cos(λ) * Math.cos(φ) > cr;
    }
    function clipLine(listener) {
      var point0, c0, v0, v00, clean;
      return {
        lineStart: function() {
          v00 = v0 = false;
          clean = 1;
        },
        point: function(λ, φ) {
          var point1 = [ λ, φ ], point2, v = visible(λ, φ), c = smallRadius ? v ? 0 : code(λ, φ) : v ? code(λ + (λ < 0 ? π : -π), φ) : 0;
          if (!point0 && (v00 = v0 = v)) listener.lineStart();
          if (v !== v0) {
            point2 = intersect(point0, point1);
            if (d3_geo_sphericalEqual(point0, point2) || d3_geo_sphericalEqual(point1, point2)) {
              point1[0] += ε;
              point1[1] += ε;
              v = visible(point1[0], point1[1]);
            }
          }
          if (v !== v0) {
            clean = 0;
            if (v) {
              listener.lineStart();
              point2 = intersect(point1, point0);
              listener.point(point2[0], point2[1]);
            } else {
              point2 = intersect(point0, point1);
              listener.point(point2[0], point2[1]);
              listener.lineEnd();
            }
            point0 = point2;
          } else if (notHemisphere && point0 && smallRadius ^ v) {
            var t;
            if (!(c & c0) && (t = intersect(point1, point0, true))) {
              clean = 0;
              if (smallRadius) {
                listener.lineStart();
                listener.point(t[0][0], t[0][1]);
                listener.point(t[1][0], t[1][1]);
                listener.lineEnd();
              } else {
                listener.point(t[1][0], t[1][1]);
                listener.lineEnd();
                listener.lineStart();
                listener.point(t[0][0], t[0][1]);
              }
            }
          }
          if (v && (!point0 || !d3_geo_sphericalEqual(point0, point1))) {
            listener.point(point1[0], point1[1]);
          }
          point0 = point1, v0 = v, c0 = c;
        },
        lineEnd: function() {
          if (v0) listener.lineEnd();
          point0 = null;
        },
        clean: function() {
          return clean | (v00 && v0) << 1;
        }
      };
    }
    function intersect(a, b, two) {
      var pa = d3_geo_cartesian(a), pb = d3_geo_cartesian(b);
      var n1 = [ 1, 0, 0 ], n2 = d3_geo_cartesianCross(pa, pb), n2n2 = d3_geo_cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2;
      if (!determinant) return !two && a;
      var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = d3_geo_cartesianCross(n1, n2), A = d3_geo_cartesianScale(n1, c1), B = d3_geo_cartesianScale(n2, c2);
      d3_geo_cartesianAdd(A, B);
      var u = n1xn2, w = d3_geo_cartesianDot(A, u), uu = d3_geo_cartesianDot(u, u), t2 = w * w - uu * (d3_geo_cartesianDot(A, A) - 1);
      if (t2 < 0) return;
      var t = Math.sqrt(t2), q = d3_geo_cartesianScale(u, (-w - t) / uu);
      d3_geo_cartesianAdd(q, A);
      q = d3_geo_spherical(q);
      if (!two) return q;
      var λ0 = a[0], λ1 = b[0], φ0 = a[1], φ1 = b[1], z;
      if (λ1 < λ0) z = λ0, λ0 = λ1, λ1 = z;
      var δλ = λ1 - λ0, polar = abs(δλ - π) < ε, meridian = polar || δλ < ε;
      if (!polar && φ1 < φ0) z = φ0, φ0 = φ1, φ1 = z;
      if (meridian ? polar ? φ0 + φ1 > 0 ^ q[1] < (abs(q[0] - λ0) < ε ? φ0 : φ1) : φ0 <= q[1] && q[1] <= φ1 : δλ > π ^ (λ0 <= q[0] && q[0] <= λ1)) {
        var q1 = d3_geo_cartesianScale(u, (-w + t) / uu);
        d3_geo_cartesianAdd(q1, A);
        return [ q, d3_geo_spherical(q1) ];
      }
    }
    function code(λ, φ) {
      var r = smallRadius ? radius : π - radius, code = 0;
      if (λ < -r) code |= 1; else if (λ > r) code |= 2;
      if (φ < -r) code |= 4; else if (φ > r) code |= 8;
      return code;
    }
  }
  function d3_geom_clipLine(x0, y0, x1, y1) {
    return function(line) {
      var a = line.a, b = line.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay, r;
      r = x0 - ax;
      if (!dx && r > 0) return;
      r /= dx;
      if (dx < 0) {
        if (r < t0) return;
        if (r < t1) t1 = r;
      } else if (dx > 0) {
        if (r > t1) return;
        if (r > t0) t0 = r;
      }
      r = x1 - ax;
      if (!dx && r < 0) return;
      r /= dx;
      if (dx < 0) {
        if (r > t1) return;
        if (r > t0) t0 = r;
      } else if (dx > 0) {
        if (r < t0) return;
        if (r < t1) t1 = r;
      }
      r = y0 - ay;
      if (!dy && r > 0) return;
      r /= dy;
      if (dy < 0) {
        if (r < t0) return;
        if (r < t1) t1 = r;
      } else if (dy > 0) {
        if (r > t1) return;
        if (r > t0) t0 = r;
      }
      r = y1 - ay;
      if (!dy && r < 0) return;
      r /= dy;
      if (dy < 0) {
        if (r > t1) return;
        if (r > t0) t0 = r;
      } else if (dy > 0) {
        if (r < t0) return;
        if (r < t1) t1 = r;
      }
      if (t0 > 0) line.a = {
        x: ax + t0 * dx,
        y: ay + t0 * dy
      };
      if (t1 < 1) line.b = {
        x: ax + t1 * dx,
        y: ay + t1 * dy
      };
      return line;
    };
  }
  var d3_geo_clipExtentMAX = 1e9;
  d3.geo.clipExtent = function() {
    var x0, y0, x1, y1, stream, clip, clipExtent = {
      stream: function(output) {
        if (stream) stream.valid = false;
        stream = clip(output);
        stream.valid = true;
        return stream;
      },
      extent: function(_) {
        if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ];
        clip = d3_geo_clipExtent(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]);
        if (stream) stream.valid = false, stream = null;
        return clipExtent;
      }
    };
    return clipExtent.extent([ [ 0, 0 ], [ 960, 500 ] ]);
  };
  function d3_geo_clipExtent(x0, y0, x1, y1) {
    return function(listener) {
      var listener_ = listener, bufferListener = d3_geo_clipBufferListener(), clipLine = d3_geom_clipLine(x0, y0, x1, y1), segments, polygon, ring;
      var clip = {
        point: point,
        lineStart: lineStart,
        lineEnd: lineEnd,
        polygonStart: function() {
          listener = bufferListener;
          segments = [];
          polygon = [];
          clean = true;
        },
        polygonEnd: function() {
          listener = listener_;
          segments = d3.merge(segments);
          var clipStartInside = insidePolygon([ x0, y1 ]), inside = clean && clipStartInside, visible = segments.length;
          if (inside || visible) {
            listener.polygonStart();
            if (inside) {
              listener.lineStart();
              interpolate(null, null, 1, listener);
              listener.lineEnd();
            }
            if (visible) {
              d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener);
            }
            listener.polygonEnd();
          }
          segments = polygon = ring = null;
        }
      };
      function insidePolygon(p) {
        var wn = 0, n = polygon.length, y = p[1];
        for (var i = 0; i < n; ++i) {
          for (var j = 1, v = polygon[i], m = v.length, a = v[0], b; j < m; ++j) {
            b = v[j];
            if (a[1] <= y) {
              if (b[1] > y && d3_cross2d(a, b, p) > 0) ++wn;
            } else {
              if (b[1] <= y && d3_cross2d(a, b, p) < 0) --wn;
            }
            a = b;
          }
        }
        return wn !== 0;
      }
      function interpolate(from, to, direction, listener) {
        var a = 0, a1 = 0;
        if (from == null || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoints(from, to) < 0 ^ direction > 0) {
          do {
            listener.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0);
          } while ((a = (a + direction + 4) % 4) !== a1);
        } else {
          listener.point(to[0], to[1]);
        }
      }
      function pointVisible(x, y) {
        return x0 <= x && x <= x1 && y0 <= y && y <= y1;
      }
      function point(x, y) {
        if (pointVisible(x, y)) listener.point(x, y);
      }
      var x__, y__, v__, x_, y_, v_, first, clean;
      function lineStart() {
        clip.point = linePoint;
        if (polygon) polygon.push(ring = []);
        first = true;
        v_ = false;
        x_ = y_ = NaN;
      }
      function lineEnd() {
        if (segments) {
          linePoint(x__, y__);
          if (v__ && v_) bufferListener.rejoin();
          segments.push(bufferListener.buffer());
        }
        clip.point = point;
        if (v_) listener.lineEnd();
      }
      function linePoint(x, y) {
        x = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, x));
        y = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, y));
        var v = pointVisible(x, y);
        if (polygon) ring.push([ x, y ]);
        if (first) {
          x__ = x, y__ = y, v__ = v;
          first = false;
          if (v) {
            listener.lineStart();
            listener.point(x, y);
          }
        } else {
          if (v && v_) listener.point(x, y); else {
            var l = {
              a: {
                x: x_,
                y: y_
              },
              b: {
                x: x,
                y: y
              }
            };
            if (clipLine(l)) {
              if (!v_) {
                listener.lineStart();
                listener.point(l.a.x, l.a.y);
              }
              listener.point(l.b.x, l.b.y);
              if (!v) listener.lineEnd();
              clean = false;
            } else if (v) {
              listener.lineStart();
              listener.point(x, y);
              clean = false;
            }
          }
        }
        x_ = x, y_ = y, v_ = v;
      }
      return clip;
    };
    function corner(p, direction) {
      return abs(p[0] - x0) < ε ? direction > 0 ? 0 : 3 : abs(p[0] - x1) < ε ? direction > 0 ? 2 : 1 : abs(p[1] - y0) < ε ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2;
    }
    function compare(a, b) {
      return comparePoints(a.x, b.x);
    }
    function comparePoints(a, b) {
      var ca = corner(a, 1), cb = corner(b, 1);
      return ca !== cb ? ca - cb : ca === 0 ? b[1] - a[1] : ca === 1 ? a[0] - b[0] : ca === 2 ? a[1] - b[1] : b[0] - a[0];
    }
  }
  function d3_geo_conic(projectAt) {
    var φ0 = 0, φ1 = π / 3, m = d3_geo_projectionMutator(projectAt), p = m(φ0, φ1);
    p.parallels = function(_) {
      if (!arguments.length) return [ φ0 / π * 180, φ1 / π * 180 ];
      return m(φ0 = _[0] * π / 180, φ1 = _[1] * π / 180);
    };
    return p;
  }
  function d3_geo_conicEqualArea(φ0, φ1) {
    var sinφ0 = Math.sin(φ0), n = (sinφ0 + Math.sin(φ1)) / 2, C = 1 + sinφ0 * (2 * n - sinφ0), ρ0 = Math.sqrt(C) / n;
    function forward(λ, φ) {
      var ρ = Math.sqrt(C - 2 * n * Math.sin(φ)) / n;
      return [ ρ * Math.sin(λ *= n), ρ0 - ρ * Math.cos(λ) ];
    }
    forward.invert = function(x, y) {
      var ρ0_y = ρ0 - y;
      return [ Math.atan2(x, ρ0_y) / n, d3_asin((C - (x * x + ρ0_y * ρ0_y) * n * n) / (2 * n)) ];
    };
    return forward;
  }
  (d3.geo.conicEqualArea = function() {
    return d3_geo_conic(d3_geo_conicEqualArea);
  }).raw = d3_geo_conicEqualArea;
  d3.geo.albers = function() {
    return d3.geo.conicEqualArea().rotate([ 96, 0 ]).center([ -.6, 38.7 ]).parallels([ 29.5, 45.5 ]).scale(1070);
  };
  d3.geo.albersUsa = function() {
    var lower48 = d3.geo.albers();
    var alaska = d3.geo.conicEqualArea().rotate([ 154, 0 ]).center([ -2, 58.5 ]).parallels([ 55, 65 ]);
    var hawaii = d3.geo.conicEqualArea().rotate([ 157, 0 ]).center([ -3, 19.9 ]).parallels([ 8, 18 ]);
    var point, pointStream = {
      point: function(x, y) {
        point = [ x, y ];
      }
    }, lower48Point, alaskaPoint, hawaiiPoint;
    function albersUsa(coordinates) {
      var x = coordinates[0], y = coordinates[1];
      point = null;
      (lower48Point(x, y), point) || (alaskaPoint(x, y), point) || hawaiiPoint(x, y);
      return point;
    }
    albersUsa.invert = function(coordinates) {
      var k = lower48.scale(), t = lower48.translate(), x = (coordinates[0] - t[0]) / k, y = (coordinates[1] - t[1]) / k;
      return (y >= .12 && y < .234 && x >= -.425 && x < -.214 ? alaska : y >= .166 && y < .234 && x >= -.214 && x < -.115 ? hawaii : lower48).invert(coordinates);
    };
    albersUsa.stream = function(stream) {
      var lower48Stream = lower48.stream(stream), alaskaStream = alaska.stream(stream), hawaiiStream = hawaii.stream(stream);
      return {
        point: function(x, y) {
          lower48Stream.point(x, y);
          alaskaStream.point(x, y);
          hawaiiStream.point(x, y);
        },
        sphere: function() {
          lower48Stream.sphere();
          alaskaStream.sphere();
          hawaiiStream.sphere();
        },
        lineStart: function() {
          lower48Stream.lineStart();
          alaskaStream.lineStart();
          hawaiiStream.lineStart();
        },
        lineEnd: function() {
          lower48Stream.lineEnd();
          alaskaStream.lineEnd();
          hawaiiStream.lineEnd();
        },
        polygonStart: function() {
          lower48Stream.polygonStart();
          alaskaStream.polygonStart();
          hawaiiStream.polygonStart();
        },
        polygonEnd: function() {
          lower48Stream.polygonEnd();
          alaskaStream.polygonEnd();
          hawaiiStream.polygonEnd();
        }
      };
    };
    albersUsa.precision = function(_) {
      if (!arguments.length) return lower48.precision();
      lower48.precision(_);
      alaska.precision(_);
      hawaii.precision(_);
      return albersUsa;
    };
    albersUsa.scale = function(_) {
      if (!arguments.length) return lower48.scale();
      lower48.scale(_);
      alaska.scale(_ * .35);
      hawaii.scale(_);
      return albersUsa.translate(lower48.translate());
    };
    albersUsa.translate = function(_) {
      if (!arguments.length) return lower48.translate();
      var k = lower48.scale(), x = +_[0], y = +_[1];
      lower48Point = lower48.translate(_).clipExtent([ [ x - .455 * k, y - .238 * k ], [ x + .455 * k, y + .238 * k ] ]).stream(pointStream).point;
      alaskaPoint = alaska.translate([ x - .307 * k, y + .201 * k ]).clipExtent([ [ x - .425 * k + ε, y + .12 * k + ε ], [ x - .214 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point;
      hawaiiPoint = hawaii.translate([ x - .205 * k, y + .212 * k ]).clipExtent([ [ x - .214 * k + ε, y + .166 * k + ε ], [ x - .115 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point;
      return albersUsa;
    };
    return albersUsa.scale(1070);
  };
  var d3_geo_pathAreaSum, d3_geo_pathAreaPolygon, d3_geo_pathArea = {
    point: d3_noop,
    lineStart: d3_noop,
    lineEnd: d3_noop,
    polygonStart: function() {
      d3_geo_pathAreaPolygon = 0;
      d3_geo_pathArea.lineStart = d3_geo_pathAreaRingStart;
    },
    polygonEnd: function() {
      d3_geo_pathArea.lineStart = d3_geo_pathArea.lineEnd = d3_geo_pathArea.point = d3_noop;
      d3_geo_pathAreaSum += abs(d3_geo_pathAreaPolygon / 2);
    }
  };
  function d3_geo_pathAreaRingStart() {
    var x00, y00, x0, y0;
    d3_geo_pathArea.point = function(x, y) {
      d3_geo_pathArea.point = nextPoint;
      x00 = x0 = x, y00 = y0 = y;
    };
    function nextPoint(x, y) {
      d3_geo_pathAreaPolygon += y0 * x - x0 * y;
      x0 = x, y0 = y;
    }
    d3_geo_pathArea.lineEnd = function() {
      nextPoint(x00, y00);
    };
  }
  var d3_geo_pathBoundsX0, d3_geo_pathBoundsY0, d3_geo_pathBoundsX1, d3_geo_pathBoundsY1;
  var d3_geo_pathBounds = {
    point: d3_geo_pathBoundsPoint,
    lineStart: d3_noop,
    lineEnd: d3_noop,
    polygonStart: d3_noop,
    polygonEnd: d3_noop
  };
  function d3_geo_pathBoundsPoint(x, y) {
    if (x < d3_geo_pathBoundsX0) d3_geo_pathBoundsX0 = x;
    if (x > d3_geo_pathBoundsX1) d3_geo_pathBoundsX1 = x;
    if (y < d3_geo_pathBoundsY0) d3_geo_pathBoundsY0 = y;
    if (y > d3_geo_pathBoundsY1) d3_geo_pathBoundsY1 = y;
  }
  function d3_geo_pathBuffer() {
    var pointCircle = d3_geo_pathBufferCircle(4.5), buffer = [];
    var stream = {
      point: point,
      lineStart: function() {
        stream.point = pointLineStart;
      },
      lineEnd: lineEnd,
      polygonStart: function() {
        stream.lineEnd = lineEndPolygon;
      },
      polygonEnd: function() {
        stream.lineEnd = lineEnd;
        stream.point = point;
      },
      pointRadius: function(_) {
        pointCircle = d3_geo_pathBufferCircle(_);
        return stream;
      },
      result: function() {
        if (buffer.length) {
          var result = buffer.join("");
          buffer = [];
          return result;
        }
      }
    };
    function point(x, y) {
      buffer.push("M", x, ",", y, pointCircle);
    }
    function pointLineStart(x, y) {
      buffer.push("M", x, ",", y);
      stream.point = pointLine;
    }
    function pointLine(x, y) {
      buffer.push("L", x, ",", y);
    }
    function lineEnd() {
      stream.point = point;
    }
    function lineEndPolygon() {
      buffer.push("Z");
    }
    return stream;
  }
  function d3_geo_pathBufferCircle(radius) {
    return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius + "z";
  }
  var d3_geo_pathCentroid = {
    point: d3_geo_pathCentroidPoint,
    lineStart: d3_geo_pathCentroidLineStart,
    lineEnd: d3_geo_pathCentroidLineEnd,
    polygonStart: function() {
      d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidRingStart;
    },
    polygonEnd: function() {
      d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint;
      d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidLineStart;
      d3_geo_pathCentroid.lineEnd = d3_geo_pathCentroidLineEnd;
    }
  };
  function d3_geo_pathCentroidPoint(x, y) {
    d3_geo_centroidX0 += x;
    d3_geo_centroidY0 += y;
    ++d3_geo_centroidZ0;
  }
  function d3_geo_pathCentroidLineStart() {
    var x0, y0;
    d3_geo_pathCentroid.point = function(x, y) {
      d3_geo_pathCentroid.point = nextPoint;
      d3_geo_pathCentroidPoint(x0 = x, y0 = y);
    };
    function nextPoint(x, y) {
      var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy);
      d3_geo_centroidX1 += z * (x0 + x) / 2;
      d3_geo_centroidY1 += z * (y0 + y) / 2;
      d3_geo_centroidZ1 += z;
      d3_geo_pathCentroidPoint(x0 = x, y0 = y);
    }
  }
  function d3_geo_pathCentroidLineEnd() {
    d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint;
  }
  function d3_geo_pathCentroidRingStart() {
    var x00, y00, x0, y0;
    d3_geo_pathCentroid.point = function(x, y) {
      d3_geo_pathCentroid.point = nextPoint;
      d3_geo_pathCentroidPoint(x00 = x0 = x, y00 = y0 = y);
    };
    function nextPoint(x, y) {
      var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy);
      d3_geo_centroidX1 += z * (x0 + x) / 2;
      d3_geo_centroidY1 += z * (y0 + y) / 2;
      d3_geo_centroidZ1 += z;
      z = y0 * x - x0 * y;
      d3_geo_centroidX2 += z * (x0 + x);
      d3_geo_centroidY2 += z * (y0 + y);
      d3_geo_centroidZ2 += z * 3;
      d3_geo_pathCentroidPoint(x0 = x, y0 = y);
    }
    d3_geo_pathCentroid.lineEnd = function() {
      nextPoint(x00, y00);
    };
  }
  function d3_geo_pathContext(context) {
    var pointRadius = 4.5;
    var stream = {
      point: point,
      lineStart: function() {
        stream.point = pointLineStart;
      },
      lineEnd: lineEnd,
      polygonStart: function() {
        stream.lineEnd = lineEndPolygon;
      },
      polygonEnd: function() {
        stream.lineEnd = lineEnd;
        stream.point = point;
      },
      pointRadius: function(_) {
        pointRadius = _;
        return stream;
      },
      result: d3_noop
    };
    function point(x, y) {
      context.moveTo(x + pointRadius, y);
      context.arc(x, y, pointRadius, 0, τ);
    }
    function pointLineStart(x, y) {
      context.moveTo(x, y);
      stream.point = pointLine;
    }
    function pointLine(x, y) {
      context.lineTo(x, y);
    }
    function lineEnd() {
      stream.point = point;
    }
    function lineEndPolygon() {
      context.closePath();
    }
    return stream;
  }
  function d3_geo_resample(project) {
    var δ2 = .5, cosMinDistance = Math.cos(30 * d3_radians), maxDepth = 16;
    function resample(stream) {
      return (maxDepth ? resampleRecursive : resampleNone)(stream);
    }
    function resampleNone(stream) {
      return d3_geo_transformPoint(stream, function(x, y) {
        x = project(x, y);
        stream.point(x[0], x[1]);
      });
    }
    function resampleRecursive(stream) {
      var λ00, φ00, x00, y00, a00, b00, c00, λ0, x0, y0, a0, b0, c0;
      var resample = {
        point: point,
        lineStart: lineStart,
        lineEnd: lineEnd,
        polygonStart: function() {
          stream.polygonStart();
          resample.lineStart = ringStart;
        },
        polygonEnd: function() {
          stream.polygonEnd();
          resample.lineStart = lineStart;
        }
      };
      function point(x, y) {
        x = project(x, y);
        stream.point(x[0], x[1]);
      }
      function lineStart() {
        x0 = NaN;
        resample.point = linePoint;
        stream.lineStart();
      }
      function linePoint(λ, φ) {
        var c = d3_geo_cartesian([ λ, φ ]), p = project(λ, φ);
        resampleLineTo(x0, y0, λ0, a0, b0, c0, x0 = p[0], y0 = p[1], λ0 = λ, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream);
        stream.point(x0, y0);
      }
      function lineEnd() {
        resample.point = point;
        stream.lineEnd();
      }
      function ringStart() {
        lineStart();
        resample.point = ringPoint;
        resample.lineEnd = ringEnd;
      }
      function ringPoint(λ, φ) {
        linePoint(λ00 = λ, φ00 = φ), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0;
        resample.point = linePoint;
      }
      function ringEnd() {
        resampleLineTo(x0, y0, λ0, a0, b0, c0, x00, y00, λ00, a00, b00, c00, maxDepth, stream);
        resample.lineEnd = lineEnd;
        lineEnd();
      }
      return resample;
    }
    function resampleLineTo(x0, y0, λ0, a0, b0, c0, x1, y1, λ1, a1, b1, c1, depth, stream) {
      var dx = x1 - x0, dy = y1 - y0, d2 = dx * dx + dy * dy;
      if (d2 > 4 * δ2 && depth--) {
        var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = Math.sqrt(a * a + b * b + c * c), φ2 = Math.asin(c /= m), λ2 = abs(abs(c) - 1) < ε || abs(λ0 - λ1) < ε ? (λ0 + λ1) / 2 : Math.atan2(b, a), p = project(λ2, φ2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2;
        if (dz * dz / d2 > δ2 || abs((dx * dx2 + dy * dy2) / d2 - .5) > .3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) {
          resampleLineTo(x0, y0, λ0, a0, b0, c0, x2, y2, λ2, a /= m, b /= m, c, depth, stream);
          stream.point(x2, y2);
          resampleLineTo(x2, y2, λ2, a, b, c, x1, y1, λ1, a1, b1, c1, depth, stream);
        }
      }
    }
    resample.precision = function(_) {
      if (!arguments.length) return Math.sqrt(δ2);
      maxDepth = (δ2 = _ * _) > 0 && 16;
      return resample;
    };
    return resample;
  }
  d3.geo.path = function() {
    var pointRadius = 4.5, projection, context, projectStream, contextStream, cacheStream;
    function path(object) {
      if (object) {
        if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments));
        if (!cacheStream || !cacheStream.valid) cacheStream = projectStream(contextStream);
        d3.geo.stream(object, cacheStream);
      }
      return contextStream.result();
    }
    path.area = function(object) {
      d3_geo_pathAreaSum = 0;
      d3.geo.stream(object, projectStream(d3_geo_pathArea));
      return d3_geo_pathAreaSum;
    };
    path.centroid = function(object) {
      d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0;
      d3.geo.stream(object, projectStream(d3_geo_pathCentroid));
      return d3_geo_centroidZ2 ? [ d3_geo_centroidX2 / d3_geo_centroidZ2, d3_geo_centroidY2 / d3_geo_centroidZ2 ] : d3_geo_centroidZ1 ? [ d3_geo_centroidX1 / d3_geo_centroidZ1, d3_geo_centroidY1 / d3_geo_centroidZ1 ] : d3_geo_centroidZ0 ? [ d3_geo_centroidX0 / d3_geo_centroidZ0, d3_geo_centroidY0 / d3_geo_centroidZ0 ] : [ NaN, NaN ];
    };
    path.bounds = function(object) {
      d3_geo_pathBoundsX1 = d3_geo_pathBoundsY1 = -(d3_geo_pathBoundsX0 = d3_geo_pathBoundsY0 = Infinity);
      d3.geo.stream(object, projectStream(d3_geo_pathBounds));
      return [ [ d3_geo_pathBoundsX0, d3_geo_pathBoundsY0 ], [ d3_geo_pathBoundsX1, d3_geo_pathBoundsY1 ] ];
    };
    path.projection = function(_) {
      if (!arguments.length) return projection;
      projectStream = (projection = _) ? _.stream || d3_geo_pathProjectStream(_) : d3_identity;
      return reset();
    };
    path.context = function(_) {
      if (!arguments.length) return context;
      contextStream = (context = _) == null ? new d3_geo_pathBuffer() : new d3_geo_pathContext(_);
      if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius);
      return reset();
    };
    path.pointRadius = function(_) {
      if (!arguments.length) return pointRadius;
      pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_);
      return path;
    };
    function reset() {
      cacheStream = null;
      return path;
    }
    return path.projection(d3.geo.albersUsa()).context(null);
  };
  function d3_geo_pathProjectStream(project) {
    var resample = d3_geo_resample(function(x, y) {
      return project([ x * d3_degrees, y * d3_degrees ]);
    });
    return function(stream) {
      return d3_geo_projectionRadians(resample(stream));
    };
  }
  d3.geo.transform = function(methods) {
    return {
      stream: function(stream) {
        var transform = new d3_geo_transform(stream);
        for (var k in methods) transform[k] = methods[k];
        return transform;
      }
    };
  };
  function d3_geo_transform(stream) {
    this.stream = stream;
  }
  d3_geo_transform.prototype = {
    point: function(x, y) {
      this.stream.point(x, y);
    },
    sphere: function() {
      this.stream.sphere();
    },
    lineStart: function() {
      this.stream.lineStart();
    },
    lineEnd: function() {
      this.stream.lineEnd();
    },
    polygonStart: function() {
      this.stream.polygonStart();
    },
    polygonEnd: function() {
      this.stream.polygonEnd();
    }
  };
  function d3_geo_transformPoint(stream, point) {
    return {
      point: point,
      sphere: function() {
        stream.sphere();
      },
      lineStart: function() {
        stream.lineStart();
      },
      lineEnd: function() {
        stream.lineEnd();
      },
      polygonStart: function() {
        stream.polygonStart();
      },
      polygonEnd: function() {
        stream.polygonEnd();
      }
    };
  }
  d3.geo.projection = d3_geo_projection;
  d3.geo.projectionMutator = d3_geo_projectionMutator;
  function d3_geo_projection(project) {
    return d3_geo_projectionMutator(function() {
      return project;
    })();
  }
  function d3_geo_projectionMutator(projectAt) {
    var project, rotate, projectRotate, projectResample = d3_geo_resample(function(x, y) {
      x = project(x, y);
      return [ x[0] * k + δx, δy - x[1] * k ];
    }), k = 150, x = 480, y = 250, λ = 0, φ = 0, δλ = 0, δφ = 0, δγ = 0, δx, δy, preclip = d3_geo_clipAntimeridian, postclip = d3_identity, clipAngle = null, clipExtent = null, stream;
    function projection(point) {
      point = projectRotate(point[0] * d3_radians, point[1] * d3_radians);
      return [ point[0] * k + δx, δy - point[1] * k ];
    }
    function invert(point) {
      point = projectRotate.invert((point[0] - δx) / k, (δy - point[1]) / k);
      return point && [ point[0] * d3_degrees, point[1] * d3_degrees ];
    }
    projection.stream = function(output) {
      if (stream) stream.valid = false;
      stream = d3_geo_projectionRadians(preclip(rotate, projectResample(postclip(output))));
      stream.valid = true;
      return stream;
    };
    projection.clipAngle = function(_) {
      if (!arguments.length) return clipAngle;
      preclip = _ == null ? (clipAngle = _, d3_geo_clipAntimeridian) : d3_geo_clipCircle((clipAngle = +_) * d3_radians);
      return invalidate();
    };
    projection.clipExtent = function(_) {
      if (!arguments.length) return clipExtent;
      clipExtent = _;
      postclip = _ ? d3_geo_clipExtent(_[0][0], _[0][1], _[1][0], _[1][1]) : d3_identity;
      return invalidate();
    };
    projection.scale = function(_) {
      if (!arguments.length) return k;
      k = +_;
      return reset();
    };
    projection.translate = function(_) {
      if (!arguments.length) return [ x, y ];
      x = +_[0];
      y = +_[1];
      return reset();
    };
    projection.center = function(_) {
      if (!arguments.length) return [ λ * d3_degrees, φ * d3_degrees ];
      λ = _[0] % 360 * d3_radians;
      φ = _[1] % 360 * d3_radians;
      return reset();
    };
    projection.rotate = function(_) {
      if (!arguments.length) return [ δλ * d3_degrees, δφ * d3_degrees, δγ * d3_degrees ];
      δλ = _[0] % 360 * d3_radians;
      δφ = _[1] % 360 * d3_radians;
      δγ = _.length > 2 ? _[2] % 360 * d3_radians : 0;
      return reset();
    };
    d3.rebind(projection, projectResample, "precision");
    function reset() {
      projectRotate = d3_geo_compose(rotate = d3_geo_rotation(δλ, δφ, δγ), project);
      var center = project(λ, φ);
      δx = x - center[0] * k;
      δy = y + center[1] * k;
      return invalidate();
    }
    function invalidate() {
      if (stream) stream.valid = false, stream = null;
      return projection;
    }
    return function() {
      project = projectAt.apply(this, arguments);
      projection.invert = project.invert && invert;
      return reset();
    };
  }
  function d3_geo_projectionRadians(stream) {
    return d3_geo_transformPoint(stream, function(x, y) {
      stream.point(x * d3_radians, y * d3_radians);
    });
  }
  function d3_geo_equirectangular(λ, φ) {
    return [ λ, φ ];
  }
  (d3.geo.equirectangular = function() {
    return d3_geo_projection(d3_geo_equirectangular);
  }).raw = d3_geo_equirectangular.invert = d3_geo_equirectangular;
  d3.geo.rotation = function(rotate) {
    rotate = d3_geo_rotation(rotate[0] % 360 * d3_radians, rotate[1] * d3_radians, rotate.length > 2 ? rotate[2] * d3_radians : 0);
    function forward(coordinates) {
      coordinates = rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians);
      return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates;
    }
    forward.invert = function(coordinates) {
      coordinates = rotate.invert(coordinates[0] * d3_radians, coordinates[1] * d3_radians);
      return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates;
    };
    return forward;
  };
  function d3_geo_identityRotation(λ, φ) {
    return [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ];
  }
  d3_geo_identityRotation.invert = d3_geo_equirectangular;
  function d3_geo_rotation(δλ, δφ, δγ) {
    return δλ ? δφ || δγ ? d3_geo_compose(d3_geo_rotationλ(δλ), d3_geo_rotationφγ(δφ, δγ)) : d3_geo_rotationλ(δλ) : δφ || δγ ? d3_geo_rotationφγ(δφ, δγ) : d3_geo_identityRotation;
  }
  function d3_geo_forwardRotationλ(δλ) {
    return function(λ, φ) {
      return λ += δλ, [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ];
    };
  }
  function d3_geo_rotationλ(δλ) {
    var rotation = d3_geo_forwardRotationλ(δλ);
    rotation.invert = d3_geo_forwardRotationλ(-δλ);
    return rotation;
  }
  function d3_geo_rotationφγ(δφ, δγ) {
    var cosδφ = Math.cos(δφ), sinδφ = Math.sin(δφ), cosδγ = Math.cos(δγ), sinδγ = Math.sin(δγ);
    function rotation(λ, φ) {
      var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδφ + x * sinδφ;
      return [ Math.atan2(y * cosδγ - k * sinδγ, x * cosδφ - z * sinδφ), d3_asin(k * cosδγ + y * sinδγ) ];
    }
    rotation.invert = function(λ, φ) {
      var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδγ - y * sinδγ;
      return [ Math.atan2(y * cosδγ + z * sinδγ, x * cosδφ + k * sinδφ), d3_asin(k * cosδφ - x * sinδφ) ];
    };
    return rotation;
  }
  d3.geo.circle = function() {
    var origin = [ 0, 0 ], angle, precision = 6, interpolate;
    function circle() {
      var center = typeof origin === "function" ? origin.apply(this, arguments) : origin, rotate = d3_geo_rotation(-center[0] * d3_radians, -center[1] * d3_radians, 0).invert, ring = [];
      interpolate(null, null, 1, {
        point: function(x, y) {
          ring.push(x = rotate(x, y));
          x[0] *= d3_degrees, x[1] *= d3_degrees;
        }
      });
      return {
        type: "Polygon",
        coordinates: [ ring ]
      };
    }
    circle.origin = function(x) {
      if (!arguments.length) return origin;
      origin = x;
      return circle;
    };
    circle.angle = function(x) {
      if (!arguments.length) return angle;
      interpolate = d3_geo_circleInterpolate((angle = +x) * d3_radians, precision * d3_radians);
      return circle;
    };
    circle.precision = function(_) {
      if (!arguments.length) return precision;
      interpolate = d3_geo_circleInterpolate(angle * d3_radians, (precision = +_) * d3_radians);
      return circle;
    };
    return circle.angle(90);
  };
  function d3_geo_circleInterpolate(radius, precision) {
    var cr = Math.cos(radius), sr = Math.sin(radius);
    return function(from, to, direction, listener) {
      var step = direction * precision;
      if (from != null) {
        from = d3_geo_circleAngle(cr, from);
        to = d3_geo_circleAngle(cr, to);
        if (direction > 0 ? from < to : from > to) from += direction * τ;
      } else {
        from = radius + direction * τ;
        to = radius - .5 * step;
      }
      for (var point, t = from; direction > 0 ? t > to : t < to; t -= step) {
        listener.point((point = d3_geo_spherical([ cr, -sr * Math.cos(t), -sr * Math.sin(t) ]))[0], point[1]);
      }
    };
  }
  function d3_geo_circleAngle(cr, point) {
    var a = d3_geo_cartesian(point);
    a[0] -= cr;
    d3_geo_cartesianNormalize(a);
    var angle = d3_acos(-a[1]);
    return ((-a[2] < 0 ? -angle : angle) + 2 * Math.PI - ε) % (2 * Math.PI);
  }
  d3.geo.distance = function(a, b) {
    var Δλ = (b[0] - a[0]) * d3_radians, φ0 = a[1] * d3_radians, φ1 = b[1] * d3_radians, sinΔλ = Math.sin(Δλ), cosΔλ = Math.cos(Δλ), sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), sinφ1 = Math.sin(φ1), cosφ1 = Math.cos(φ1), t;
    return Math.atan2(Math.sqrt((t = cosφ1 * sinΔλ) * t + (t = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * t), sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ);
  };
  d3.geo.graticule = function() {
    var x1, x0, X1, X0, y1, y0, Y1, Y0, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5;
    function graticule() {
      return {
        type: "MultiLineString",
        coordinates: lines()
      };
    }
    function lines() {
      return d3.range(Math.ceil(X0 / DX) * DX, X1, DX).map(X).concat(d3.range(Math.ceil(Y0 / DY) * DY, Y1, DY).map(Y)).concat(d3.range(Math.ceil(x0 / dx) * dx, x1, dx).filter(function(x) {
        return abs(x % DX) > ε;
      }).map(x)).concat(d3.range(Math.ceil(y0 / dy) * dy, y1, dy).filter(function(y) {
        return abs(y % DY) > ε;
      }).map(y));
    }
    graticule.lines = function() {
      return lines().map(function(coordinates) {
        return {
          type: "LineString",
          coordinates: coordinates
        };
      });
    };
    graticule.outline = function() {
      return {
        type: "Polygon",
        coordinates: [ X(X0).concat(Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1)) ]
      };
    };
    graticule.extent = function(_) {
      if (!arguments.length) return graticule.minorExtent();
      return graticule.majorExtent(_).minorExtent(_);
    };
    graticule.majorExtent = function(_) {
      if (!arguments.length) return [ [ X0, Y0 ], [ X1, Y1 ] ];
      X0 = +_[0][0], X1 = +_[1][0];
      Y0 = +_[0][1], Y1 = +_[1][1];
      if (X0 > X1) _ = X0, X0 = X1, X1 = _;
      if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _;
      return graticule.precision(precision);
    };
    graticule.minorExtent = function(_) {
      if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ];
      x0 = +_[0][0], x1 = +_[1][0];
      y0 = +_[0][1], y1 = +_[1][1];
      if (x0 > x1) _ = x0, x0 = x1, x1 = _;
      if (y0 > y1) _ = y0, y0 = y1, y1 = _;
      return graticule.precision(precision);
    };
    graticule.step = function(_) {
      if (!arguments.length) return graticule.minorStep();
      return graticule.majorStep(_).minorStep(_);
    };
    graticule.majorStep = function(_) {
      if (!arguments.length) return [ DX, DY ];
      DX = +_[0], DY = +_[1];
      return graticule;
    };
    graticule.minorStep = function(_) {
      if (!arguments.length) return [ dx, dy ];
      dx = +_[0], dy = +_[1];
      return graticule;
    };
    graticule.precision = function(_) {
      if (!arguments.length) return precision;
      precision = +_;
      x = d3_geo_graticuleX(y0, y1, 90);
      y = d3_geo_graticuleY(x0, x1, precision);
      X = d3_geo_graticuleX(Y0, Y1, 90);
      Y = d3_geo_graticuleY(X0, X1, precision);
      return graticule;
    };
    return graticule.majorExtent([ [ -180, -90 + ε ], [ 180, 90 - ε ] ]).minorExtent([ [ -180, -80 - ε ], [ 180, 80 + ε ] ]);
  };
  function d3_geo_graticuleX(y0, y1, dy) {
    var y = d3.range(y0, y1 - ε, dy).concat(y1);
    return function(x) {
      return y.map(function(y) {
        return [ x, y ];
      });
    };
  }
  function d3_geo_graticuleY(x0, x1, dx) {
    var x = d3.range(x0, x1 - ε, dx).concat(x1);
    return function(y) {
      return x.map(function(x) {
        return [ x, y ];
      });
    };
  }
  function d3_source(d) {
    return d.source;
  }
  function d3_target(d) {
    return d.target;
  }
  d3.geo.greatArc = function() {
    var source = d3_source, source_, target = d3_target, target_;
    function greatArc() {
      return {
        type: "LineString",
        coordinates: [ source_ || source.apply(this, arguments), target_ || target.apply(this, arguments) ]
      };
    }
    greatArc.distance = function() {
      return d3.geo.distance(source_ || source.apply(this, arguments), target_ || target.apply(this, arguments));
    };
    greatArc.source = function(_) {
      if (!arguments.length) return source;
      source = _, source_ = typeof _ === "function" ? null : _;
      return greatArc;
    };
    greatArc.target = function(_) {
      if (!arguments.length) return target;
      target = _, target_ = typeof _ === "function" ? null : _;
      return greatArc;
    };
    greatArc.precision = function() {
      return arguments.length ? greatArc : 0;
    };
    return greatArc;
  };
  d3.geo.interpolate = function(source, target) {
    return d3_geo_interpolate(source[0] * d3_radians, source[1] * d3_radians, target[0] * d3_radians, target[1] * d3_radians);
  };
  function d3_geo_interpolate(x0, y0, x1, y1) {
    var cy0 = Math.cos(y0), sy0 = Math.sin(y0), cy1 = Math.cos(y1), sy1 = Math.sin(y1), kx0 = cy0 * Math.cos(x0), ky0 = cy0 * Math.sin(x0), kx1 = cy1 * Math.cos(x1), ky1 = cy1 * Math.sin(x1), d = 2 * Math.asin(Math.sqrt(d3_haversin(y1 - y0) + cy0 * cy1 * d3_haversin(x1 - x0))), k = 1 / Math.sin(d);
    var interpolate = d ? function(t) {
      var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1;
      return [ Math.atan2(y, x) * d3_degrees, Math.atan2(z, Math.sqrt(x * x + y * y)) * d3_degrees ];
    } : function() {
      return [ x0 * d3_degrees, y0 * d3_degrees ];
    };
    interpolate.distance = d;
    return interpolate;
  }
  d3.geo.length = function(object) {
    d3_geo_lengthSum = 0;
    d3.geo.stream(object, d3_geo_length);
    return d3_geo_lengthSum;
  };
  var d3_geo_lengthSum;
  var d3_geo_length = {
    sphere: d3_noop,
    point: d3_noop,
    lineStart: d3_geo_lengthLineStart,
    lineEnd: d3_noop,
    polygonStart: d3_noop,
    polygonEnd: d3_noop
  };
  function d3_geo_lengthLineStart() {
    var λ0, sinφ0, cosφ0;
    d3_geo_length.point = function(λ, φ) {
      λ0 = λ * d3_radians, sinφ0 = Math.sin(φ *= d3_radians), cosφ0 = Math.cos(φ);
      d3_geo_length.point = nextPoint;
    };
    d3_geo_length.lineEnd = function() {
      d3_geo_length.point = d3_geo_length.lineEnd = d3_noop;
    };
    function nextPoint(λ, φ) {
      var sinφ = Math.sin(φ *= d3_radians), cosφ = Math.cos(φ), t = abs((λ *= d3_radians) - λ0), cosΔλ = Math.cos(t);
      d3_geo_lengthSum += Math.atan2(Math.sqrt((t = cosφ * Math.sin(t)) * t + (t = cosφ0 * sinφ - sinφ0 * cosφ * cosΔλ) * t), sinφ0 * sinφ + cosφ0 * cosφ * cosΔλ);
      λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ;
    }
  }
  function d3_geo_azimuthal(scale, angle) {
    function azimuthal(λ, φ) {
      var cosλ = Math.cos(λ), cosφ = Math.cos(φ), k = scale(cosλ * cosφ);
      return [ k * cosφ * Math.sin(λ), k * Math.sin(φ) ];
    }
    azimuthal.invert = function(x, y) {
      var ρ = Math.sqrt(x * x + y * y), c = angle(ρ), sinc = Math.sin(c), cosc = Math.cos(c);
      return [ Math.atan2(x * sinc, ρ * cosc), Math.asin(ρ && y * sinc / ρ) ];
    };
    return azimuthal;
  }
  var d3_geo_azimuthalEqualArea = d3_geo_azimuthal(function(cosλcosφ) {
    return Math.sqrt(2 / (1 + cosλcosφ));
  }, function(ρ) {
    return 2 * Math.asin(ρ / 2);
  });
  (d3.geo.azimuthalEqualArea = function() {
    return d3_geo_projection(d3_geo_azimuthalEqualArea);
  }).raw = d3_geo_azimuthalEqualArea;
  var d3_geo_azimuthalEquidistant = d3_geo_azimuthal(function(cosλcosφ) {
    var c = Math.acos(cosλcosφ);
    return c && c / Math.sin(c);
  }, d3_identity);
  (d3.geo.azimuthalEquidistant = function() {
    return d3_geo_projection(d3_geo_azimuthalEquidistant);
  }).raw = d3_geo_azimuthalEquidistant;
  function d3_geo_conicConformal(φ0, φ1) {
    var cosφ0 = Math.cos(φ0), t = function(φ) {
      return Math.tan(π / 4 + φ / 2);
    }, n = φ0 === φ1 ? Math.sin(φ0) : Math.log(cosφ0 / Math.cos(φ1)) / Math.log(t(φ1) / t(φ0)), F = cosφ0 * Math.pow(t(φ0), n) / n;
    if (!n) return d3_geo_mercator;
    function forward(λ, φ) {
      if (F > 0) {
        if (φ < -halfπ + ε) φ = -halfπ + ε;
      } else {
        if (φ > halfπ - ε) φ = halfπ - ε;
      }
      var ρ = F / Math.pow(t(φ), n);
      return [ ρ * Math.sin(n * λ), F - ρ * Math.cos(n * λ) ];
    }
    forward.invert = function(x, y) {
      var ρ0_y = F - y, ρ = d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y);
      return [ Math.atan2(x, ρ0_y) / n, 2 * Math.atan(Math.pow(F / ρ, 1 / n)) - halfπ ];
    };
    return forward;
  }
  (d3.geo.conicConformal = function() {
    return d3_geo_conic(d3_geo_conicConformal);
  }).raw = d3_geo_conicConformal;
  function d3_geo_conicEquidistant(φ0, φ1) {
    var cosφ0 = Math.cos(φ0), n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0), G = cosφ0 / n + φ0;
    if (abs(n) < ε) return d3_geo_equirectangular;
    function forward(λ, φ) {
      var ρ = G - φ;
      return [ ρ * Math.sin(n * λ), G - ρ * Math.cos(n * λ) ];
    }
    forward.invert = function(x, y) {
      var ρ0_y = G - y;
      return [ Math.atan2(x, ρ0_y) / n, G - d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y) ];
    };
    return forward;
  }
  (d3.geo.conicEquidistant = function() {
    return d3_geo_conic(d3_geo_conicEquidistant);
  }).raw = d3_geo_conicEquidistant;
  var d3_geo_gnomonic = d3_geo_azimuthal(function(cosλcosφ) {
    return 1 / cosλcosφ;
  }, Math.atan);
  (d3.geo.gnomonic = function() {
    return d3_geo_projection(d3_geo_gnomonic);
  }).raw = d3_geo_gnomonic;
  function d3_geo_mercator(λ, φ) {
    return [ λ, Math.log(Math.tan(π / 4 + φ / 2)) ];
  }
  d3_geo_mercator.invert = function(x, y) {
    return [ x, 2 * Math.atan(Math.exp(y)) - halfπ ];
  };
  function d3_geo_mercatorProjection(project) {
    var m = d3_geo_projection(project), scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, clipAuto;
    m.scale = function() {
      var v = scale.apply(m, arguments);
      return v === m ? clipAuto ? m.clipExtent(null) : m : v;
    };
    m.translate = function() {
      var v = translate.apply(m, arguments);
      return v === m ? clipAuto ? m.clipExtent(null) : m : v;
    };
    m.clipExtent = function(_) {
      var v = clipExtent.apply(m, arguments);
      if (v === m) {
        if (clipAuto = _ == null) {
          var k = π * scale(), t = translate();
          clipExtent([ [ t[0] - k, t[1] - k ], [ t[0] + k, t[1] + k ] ]);
        }
      } else if (clipAuto) {
        v = null;
      }
      return v;
    };
    return m.clipExtent(null);
  }
  (d3.geo.mercator = function() {
    return d3_geo_mercatorProjection(d3_geo_mercator);
  }).raw = d3_geo_mercator;
  var d3_geo_orthographic = d3_geo_azimuthal(function() {
    return 1;
  }, Math.asin);
  (d3.geo.orthographic = function() {
    return d3_geo_projection(d3_geo_orthographic);
  }).raw = d3_geo_orthographic;
  var d3_geo_stereographic = d3_geo_azimuthal(function(cosλcosφ) {
    return 1 / (1 + cosλcosφ);
  }, function(ρ) {
    return 2 * Math.atan(ρ);
  });
  (d3.geo.stereographic = function() {
    return d3_geo_projection(d3_geo_stereographic);
  }).raw = d3_geo_stereographic;
  function d3_geo_transverseMercator(λ, φ) {
    return [ Math.log(Math.tan(π / 4 + φ / 2)), -λ ];
  }
  d3_geo_transverseMercator.invert = function(x, y) {
    return [ -y, 2 * Math.atan(Math.exp(x)) - halfπ ];
  };
  (d3.geo.transverseMercator = function() {
    var projection = d3_geo_mercatorProjection(d3_geo_transverseMercator), center = projection.center, rotate = projection.rotate;
    projection.center = function(_) {
      return _ ? center([ -_[1], _[0] ]) : (_ = center(), [ _[1], -_[0] ]);
    };
    projection.rotate = function(_) {
      return _ ? rotate([ _[0], _[1], _.length > 2 ? _[2] + 90 : 90 ]) : (_ = rotate(), 
      [ _[0], _[1], _[2] - 90 ]);
    };
    return rotate([ 0, 0, 90 ]);
  }).raw = d3_geo_transverseMercator;
  d3.geom = {};
  function d3_geom_pointX(d) {
    return d[0];
  }
  function d3_geom_pointY(d) {
    return d[1];
  }
  d3.geom.hull = function(vertices) {
    var x = d3_geom_pointX, y = d3_geom_pointY;
    if (arguments.length) return hull(vertices);
    function hull(data) {
      if (data.length < 3) return [];
      var fx = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = [];
      for (i = 0; i < n; i++) {
        points.push([ +fx.call(this, data[i], i), +fy.call(this, data[i], i), i ]);
      }
      points.sort(d3_geom_hullOrder);
      for (i = 0; i < n; i++) flippedPoints.push([ points[i][0], -points[i][1] ]);
      var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints);
      var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon = [];
      for (i = upper.length - 1; i >= 0; --i) polygon.push(data[points[upper[i]][2]]);
      for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon.push(data[points[lower[i]][2]]);
      return polygon;
    }
    hull.x = function(_) {
      return arguments.length ? (x = _, hull) : x;
    };
    hull.y = function(_) {
      return arguments.length ? (y = _, hull) : y;
    };
    return hull;
  };
  function d3_geom_hullUpper(points) {
    var n = points.length, hull = [ 0, 1 ], hs = 2;
    for (var i = 2; i < n; i++) {
      while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs;
      hull[hs++] = i;
    }
    return hull.slice(0, hs);
  }
  function d3_geom_hullOrder(a, b) {
    return a[0] - b[0] || a[1] - b[1];
  }
  d3.geom.polygon = function(coordinates) {
    d3_subclass(coordinates, d3_geom_polygonPrototype);
    return coordinates;
  };
  var d3_geom_polygonPrototype = d3.geom.polygon.prototype = [];
  d3_geom_polygonPrototype.area = function() {
    var i = -1, n = this.length, a, b = this[n - 1], area = 0;
    while (++i < n) {
      a = b;
      b = this[i];
      area += a[1] * b[0] - a[0] * b[1];
    }
    return area * .5;
  };
  d3_geom_polygonPrototype.centroid = function(k) {
    var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c;
    if (!arguments.length) k = -1 / (6 * this.area());
    while (++i < n) {
      a = b;
      b = this[i];
      c = a[0] * b[1] - b[0] * a[1];
      x += (a[0] + b[0]) * c;
      y += (a[1] + b[1]) * c;
    }
    return [ x * k, y * k ];
  };
  d3_geom_polygonPrototype.clip = function(subject) {
    var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d;
    while (++i < n) {
      input = subject.slice();
      subject.length = 0;
      b = this[i];
      c = input[(m = input.length - closed) - 1];
      j = -1;
      while (++j < m) {
        d = input[j];
        if (d3_geom_polygonInside(d, a, b)) {
          if (!d3_geom_polygonInside(c, a, b)) {
            subject.push(d3_geom_polygonIntersect(c, d, a, b));
          }
          subject.push(d);
        } else if (d3_geom_polygonInside(c, a, b)) {
          subject.push(d3_geom_polygonIntersect(c, d, a, b));
        }
        c = d;
      }
      if (closed) subject.push(subject[0]);
      a = b;
    }
    return subject;
  };
  function d3_geom_polygonInside(p, a, b) {
    return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]);
  }
  function d3_geom_polygonIntersect(c, d, a, b) {
    var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21);
    return [ x1 + ua * x21, y1 + ua * y21 ];
  }
  function d3_geom_polygonClosed(coordinates) {
    var a = coordinates[0], b = coordinates[coordinates.length - 1];
    return !(a[0] - b[0] || a[1] - b[1]);
  }
  var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = [];
  function d3_geom_voronoiBeach() {
    d3_geom_voronoiRedBlackNode(this);
    this.edge = this.site = this.circle = null;
  }
  function d3_geom_voronoiCreateBeach(site) {
    var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach();
    beach.site = site;
    return beach;
  }
  function d3_geom_voronoiDetachBeach(beach) {
    d3_geom_voronoiDetachCircle(beach);
    d3_geom_voronoiBeaches.remove(beach);
    d3_geom_voronoiBeachPool.push(beach);
    d3_geom_voronoiRedBlackNode(beach);
  }
  function d3_geom_voronoiRemoveBeach(beach) {
    var circle = beach.circle, x = circle.x, y = circle.cy, vertex = {
      x: x,
      y: y
    }, previous = beach.P, next = beach.N, disappearing = [ beach ];
    d3_geom_voronoiDetachBeach(beach);
    var lArc = previous;
    while (lArc.circle && abs(x - lArc.circle.x) < ε && abs(y - lArc.circle.cy) < ε) {
      previous = lArc.P;
      disappearing.unshift(lArc);
      d3_geom_voronoiDetachBeach(lArc);
      lArc = previous;
    }
    disappearing.unshift(lArc);
    d3_geom_voronoiDetachCircle(lArc);
    var rArc = next;
    while (rArc.circle && abs(x - rArc.circle.x) < ε && abs(y - rArc.circle.cy) < ε) {
      next = rArc.N;
      disappearing.push(rArc);
      d3_geom_voronoiDetachBeach(rArc);
      rArc = next;
    }
    disappearing.push(rArc);
    d3_geom_voronoiDetachCircle(rArc);
    var nArcs = disappearing.length, iArc;
    for (iArc = 1; iArc < nArcs; ++iArc) {
      rArc = disappearing[iArc];
      lArc = disappearing[iArc - 1];
      d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex);
    }
    lArc = disappearing[0];
    rArc = disappearing[nArcs - 1];
    rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex);
    d3_geom_voronoiAttachCircle(lArc);
    d3_geom_voronoiAttachCircle(rArc);
  }
  function d3_geom_voronoiAddBeach(site) {
    var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._;
    while (node) {
      dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x;
      if (dxl > ε) node = node.L; else {
        dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix);
        if (dxr > ε) {
          if (!node.R) {
            lArc = node;
            break;
          }
          node = node.R;
        } else {
          if (dxl > -ε) {
            lArc = node.P;
            rArc = node;
          } else if (dxr > -ε) {
            lArc = node;
            rArc = node.N;
          } else {
            lArc = rArc = node;
          }
          break;
        }
      }
    }
    var newArc = d3_geom_voronoiCreateBeach(site);
    d3_geom_voronoiBeaches.insert(lArc, newArc);
    if (!lArc && !rArc) return;
    if (lArc === rArc) {
      d3_geom_voronoiDetachCircle(lArc);
      rArc = d3_geom_voronoiCreateBeach(lArc.site);
      d3_geom_voronoiBeaches.insert(newArc, rArc);
      newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site);
      d3_geom_voronoiAttachCircle(lArc);
      d3_geom_voronoiAttachCircle(rArc);
      return;
    }
    if (!rArc) {
      newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site);
      return;
    }
    d3_geom_voronoiDetachCircle(lArc);
    d3_geom_voronoiDetachCircle(rArc);
    var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = {
      x: (cy * hb - by * hc) / d + ax,
      y: (bx * hc - cx * hb) / d + ay
    };
    d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex);
    newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex);
    rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex);
    d3_geom_voronoiAttachCircle(lArc);
    d3_geom_voronoiAttachCircle(rArc);
  }
  function d3_geom_voronoiLeftBreakPoint(arc, directrix) {
    var site = arc.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix;
    if (!pby2) return rfocx;
    var lArc = arc.P;
    if (!lArc) return -Infinity;
    site = lArc.site;
    var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix;
    if (!plby2) return lfocx;
    var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2;
    if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx;
    return (rfocx + lfocx) / 2;
  }
  function d3_geom_voronoiRightBreakPoint(arc, directrix) {
    var rArc = arc.N;
    if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix);
    var site = arc.site;
    return site.y === directrix ? site.x : Infinity;
  }
  function d3_geom_voronoiCell(site) {
    this.site = site;
    this.edges = [];
  }
  d3_geom_voronoiCell.prototype.prepare = function() {
    var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge;
    while (iHalfEdge--) {
      edge = halfEdges[iHalfEdge].edge;
      if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1);
    }
    halfEdges.sort(d3_geom_voronoiHalfEdgeOrder);
    return halfEdges.length;
  };
  function d3_geom_voronoiCloseCells(extent) {
    var x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end;
    while (iCell--) {
      cell = cells[iCell];
      if (!cell || !cell.prepare()) continue;
      halfEdges = cell.edges;
      nHalfEdges = halfEdges.length;
      iHalfEdge = 0;
      while (iHalfEdge < nHalfEdges) {
        end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y;
        start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y;
        if (abs(x3 - x2) > ε || abs(y3 - y2) > ε) {
          halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < ε && y1 - y3 > ε ? {
            x: x0,
            y: abs(x2 - x0) < ε ? y2 : y1
          } : abs(y3 - y1) < ε && x1 - x3 > ε ? {
            x: abs(y2 - y1) < ε ? x2 : x1,
            y: y1
          } : abs(x3 - x1) < ε && y3 - y0 > ε ? {
            x: x1,
            y: abs(x2 - x1) < ε ? y2 : y0
          } : abs(y3 - y0) < ε && x3 - x0 > ε ? {
            x: abs(y2 - y0) < ε ? x2 : x0,
            y: y0
          } : null), cell.site, null));
          ++nHalfEdges;
        }
      }
    }
  }
  function d3_geom_voronoiHalfEdgeOrder(a, b) {
    return b.angle - a.angle;
  }
  function d3_geom_voronoiCircle() {
    d3_geom_voronoiRedBlackNode(this);
    this.x = this.y = this.arc = this.site = this.cy = null;
  }
  function d3_geom_voronoiAttachCircle(arc) {
    var lArc = arc.P, rArc = arc.N;
    if (!lArc || !rArc) return;
    var lSite = lArc.site, cSite = arc.site, rSite = rArc.site;
    if (lSite === rSite) return;
    var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by;
    var d = 2 * (ax * cy - ay * cx);
    if (d >= -ε2) return;
    var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by;
    var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle();
    circle.arc = arc;
    circle.site = cSite;
    circle.x = x + bx;
    circle.y = cy + Math.sqrt(x * x + y * y);
    circle.cy = cy;
    arc.circle = circle;
    var before = null, node = d3_geom_voronoiCircles._;
    while (node) {
      if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) {
        if (node.L) node = node.L; else {
          before = node.P;
          break;
        }
      } else {
        if (node.R) node = node.R; else {
          before = node;
          break;
        }
      }
    }
    d3_geom_voronoiCircles.insert(before, circle);
    if (!before) d3_geom_voronoiFirstCircle = circle;
  }
  function d3_geom_voronoiDetachCircle(arc) {
    var circle = arc.circle;
    if (circle) {
      if (!circle.P) d3_geom_voronoiFirstCircle = circle.N;
      d3_geom_voronoiCircles.remove(circle);
      d3_geom_voronoiCirclePool.push(circle);
      d3_geom_voronoiRedBlackNode(circle);
      arc.circle = null;
    }
  }
  function d3_geom_voronoiClipEdges(extent) {
    var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e;
    while (i--) {
      e = edges[i];
      if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < ε && abs(e.a.y - e.b.y) < ε) {
        e.a = e.b = null;
        edges.splice(i, 1);
      }
    }
  }
  function d3_geom_voronoiConnectEdge(edge, extent) {
    var vb = edge.b;
    if (vb) return true;
    var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb;
    if (ry === ly) {
      if (fx < x0 || fx >= x1) return;
      if (lx > rx) {
        if (!va) va = {
          x: fx,
          y: y0
        }; else if (va.y >= y1) return;
        vb = {
          x: fx,
          y: y1
        };
      } else {
        if (!va) va = {
          x: fx,
          y: y1
        }; else if (va.y < y0) return;
        vb = {
          x: fx,
          y: y0
        };
      }
    } else {
      fm = (lx - rx) / (ry - ly);
      fb = fy - fm * fx;
      if (fm < -1 || fm > 1) {
        if (lx > rx) {
          if (!va) va = {
            x: (y0 - fb) / fm,
            y: y0
          }; else if (va.y >= y1) return;
          vb = {
            x: (y1 - fb) / fm,
            y: y1
          };
        } else {
          if (!va) va = {
            x: (y1 - fb) / fm,
            y: y1
          }; else if (va.y < y0) return;
          vb = {
            x: (y0 - fb) / fm,
            y: y0
          };
        }
      } else {
        if (ly < ry) {
          if (!va) va = {
            x: x0,
            y: fm * x0 + fb
          }; else if (va.x >= x1) return;
          vb = {
            x: x1,
            y: fm * x1 + fb
          };
        } else {
          if (!va) va = {
            x: x1,
            y: fm * x1 + fb
          }; else if (va.x < x0) return;
          vb = {
            x: x0,
            y: fm * x0 + fb
          };
        }
      }
    }
    edge.a = va;
    edge.b = vb;
    return true;
  }
  function d3_geom_voronoiEdge(lSite, rSite) {
    this.l = lSite;
    this.r = rSite;
    this.a = this.b = null;
  }
  function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) {
    var edge = new d3_geom_voronoiEdge(lSite, rSite);
    d3_geom_voronoiEdges.push(edge);
    if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va);
    if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb);
    d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite));
    d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite));
    return edge;
  }
  function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) {
    var edge = new d3_geom_voronoiEdge(lSite, null);
    edge.a = va;
    edge.b = vb;
    d3_geom_voronoiEdges.push(edge);
    return edge;
  }
  function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) {
    if (!edge.a && !edge.b) {
      edge.a = vertex;
      edge.l = lSite;
      edge.r = rSite;
    } else if (edge.l === rSite) {
      edge.b = vertex;
    } else {
      edge.a = vertex;
    }
  }
  function d3_geom_voronoiHalfEdge(edge, lSite, rSite) {
    var va = edge.a, vb = edge.b;
    this.edge = edge;
    this.site = lSite;
    this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y);
  }
  d3_geom_voronoiHalfEdge.prototype = {
    start: function() {
      return this.edge.l === this.site ? this.edge.a : this.edge.b;
    },
    end: function() {
      return this.edge.l === this.site ? this.edge.b : this.edge.a;
    }
  };
  function d3_geom_voronoiRedBlackTree() {
    this._ = null;
  }
  function d3_geom_voronoiRedBlackNode(node) {
    node.U = node.C = node.L = node.R = node.P = node.N = null;
  }
  d3_geom_voronoiRedBlackTree.prototype = {
    insert: function(after, node) {
      var parent, grandpa, uncle;
      if (after) {
        node.P = after;
        node.N = after.N;
        if (after.N) after.N.P = node;
        after.N = node;
        if (after.R) {
          after = after.R;
          while (after.L) after = after.L;
          after.L = node;
        } else {
          after.R = node;
        }
        parent = after;
      } else if (this._) {
        after = d3_geom_voronoiRedBlackFirst(this._);
        node.P = null;
        node.N = after;
        after.P = after.L = node;
        parent = after;
      } else {
        node.P = node.N = null;
        this._ = node;
        parent = null;
      }
      node.L = node.R = null;
      node.U = parent;
      node.C = true;
      after = node;
      while (parent && parent.C) {
        grandpa = parent.U;
        if (parent === grandpa.L) {
          uncle = grandpa.R;
          if (uncle && uncle.C) {
            parent.C = uncle.C = false;
            grandpa.C = true;
            after = grandpa;
          } else {
            if (after === parent.R) {
              d3_geom_voronoiRedBlackRotateLeft(this, parent);
              after = parent;
              parent = after.U;
            }
            parent.C = false;
            grandpa.C = true;
            d3_geom_voronoiRedBlackRotateRight(this, grandpa);
          }
        } else {
          uncle = grandpa.L;
          if (uncle && uncle.C) {
            parent.C = uncle.C = false;
            grandpa.C = true;
            after = grandpa;
          } else {
            if (after === parent.L) {
              d3_geom_voronoiRedBlackRotateRight(this, parent);
              after = parent;
              parent = after.U;
            }
            parent.C = false;
            grandpa.C = true;
            d3_geom_voronoiRedBlackRotateLeft(this, grandpa);
          }
        }
        parent = after.U;
      }
      this._.C = false;
    },
    remove: function(node) {
      if (node.N) node.N.P = node.P;
      if (node.P) node.P.N = node.N;
      node.N = node.P = null;
      var parent = node.U, sibling, left = node.L, right = node.R, next, red;
      if (!left) next = right; else if (!right) next = left; else next = d3_geom_voronoiRedBlackFirst(right);
      if (parent) {
        if (parent.L === node) parent.L = next; else parent.R = next;
      } else {
        this._ = next;
      }
      if (left && right) {
        red = next.C;
        next.C = node.C;
        next.L = left;
        left.U = next;
        if (next !== right) {
          parent = next.U;
          next.U = node.U;
          node = next.R;
          parent.L = node;
          next.R = right;
          right.U = next;
        } else {
          next.U = parent;
          parent = next;
          node = next.R;
        }
      } else {
        red = node.C;
        node = next;
      }
      if (node) node.U = parent;
      if (red) return;
      if (node && node.C) {
        node.C = false;
        return;
      }
      do {
        if (node === this._) break;
        if (node === parent.L) {
          sibling = parent.R;
          if (sibling.C) {
            sibling.C = false;
            parent.C = true;
            d3_geom_voronoiRedBlackRotateLeft(this, parent);
            sibling = parent.R;
          }
          if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) {
            if (!sibling.R || !sibling.R.C) {
              sibling.L.C = false;
              sibling.C = true;
              d3_geom_voronoiRedBlackRotateRight(this, sibling);
              sibling = parent.R;
            }
            sibling.C = parent.C;
            parent.C = sibling.R.C = false;
            d3_geom_voronoiRedBlackRotateLeft(this, parent);
            node = this._;
            break;
          }
        } else {
          sibling = parent.L;
          if (sibling.C) {
            sibling.C = false;
            parent.C = true;
            d3_geom_voronoiRedBlackRotateRight(this, parent);
            sibling = parent.L;
          }
          if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) {
            if (!sibling.L || !sibling.L.C) {
              sibling.R.C = false;
              sibling.C = true;
              d3_geom_voronoiRedBlackRotateLeft(this, sibling);
              sibling = parent.L;
            }
            sibling.C = parent.C;
            parent.C = sibling.L.C = false;
            d3_geom_voronoiRedBlackRotateRight(this, parent);
            node = this._;
            break;
          }
        }
        sibling.C = true;
        node = parent;
        parent = parent.U;
      } while (!node.C);
      if (node) node.C = false;
    }
  };
  function d3_geom_voronoiRedBlackRotateLeft(tree, node) {
    var p = node, q = node.R, parent = p.U;
    if (parent) {
      if (parent.L === p) parent.L = q; else parent.R = q;
    } else {
      tree._ = q;
    }
    q.U = parent;
    p.U = q;
    p.R = q.L;
    if (p.R) p.R.U = p;
    q.L = p;
  }
  function d3_geom_voronoiRedBlackRotateRight(tree, node) {
    var p = node, q = node.L, parent = p.U;
    if (parent) {
      if (parent.L === p) parent.L = q; else parent.R = q;
    } else {
      tree._ = q;
    }
    q.U = parent;
    p.U = q;
    p.L = q.R;
    if (p.L) p.L.U = p;
    q.R = p;
  }
  function d3_geom_voronoiRedBlackFirst(node) {
    while (node.L) node = node.L;
    return node;
  }
  function d3_geom_voronoi(sites, bbox) {
    var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle;
    d3_geom_voronoiEdges = [];
    d3_geom_voronoiCells = new Array(sites.length);
    d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree();
    d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree();
    while (true) {
      circle = d3_geom_voronoiFirstCircle;
      if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) {
        if (site.x !== x0 || site.y !== y0) {
          d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site);
          d3_geom_voronoiAddBeach(site);
          x0 = site.x, y0 = site.y;
        }
        site = sites.pop();
      } else if (circle) {
        d3_geom_voronoiRemoveBeach(circle.arc);
      } else {
        break;
      }
    }
    if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox);
    var diagram = {
      cells: d3_geom_voronoiCells,
      edges: d3_geom_voronoiEdges
    };
    d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null;
    return diagram;
  }
  function d3_geom_voronoiVertexOrder(a, b) {
    return b.y - a.y || b.x - a.x;
  }
  d3.geom.voronoi = function(points) {
    var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent;
    if (points) return voronoi(points);
    function voronoi(data) {
      var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1];
      d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) {
        var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) {
          var s = e.start();
          return [ s.x, s.y ];
        }) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [ [ x0, y1 ], [ x1, y1 ], [ x1, y0 ], [ x0, y0 ] ] : [];
        polygon.point = data[i];
      });
      return polygons;
    }
    function sites(data) {
      return data.map(function(d, i) {
        return {
          x: Math.round(fx(d, i) / ε) * ε,
          y: Math.round(fy(d, i) / ε) * ε,
          i: i
        };
      });
    }
    voronoi.links = function(data) {
      return d3_geom_voronoi(sites(data)).edges.filter(function(edge) {
        return edge.l && edge.r;
      }).map(function(edge) {
        return {
          source: data[edge.l.i],
          target: data[edge.r.i]
        };
      });
    };
    voronoi.triangles = function(data) {
      var triangles = [];
      d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) {
        var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l;
        while (++j < m) {
          e0 = e1;
          s0 = s1;
          e1 = edges[j].edge;
          s1 = e1.l === site ? e1.r : e1.l;
          if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) {
            triangles.push([ data[i], data[s0.i], data[s1.i] ]);
          }
        }
      });
      return triangles;
    };
    voronoi.x = function(_) {
      return arguments.length ? (fx = d3_functor(x = _), voronoi) : x;
    };
    voronoi.y = function(_) {
      return arguments.length ? (fy = d3_functor(y = _), voronoi) : y;
    };
    voronoi.clipExtent = function(_) {
      if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent;
      clipExtent = _ == null ? d3_geom_voronoiClipExtent : _;
      return voronoi;
    };
    voronoi.size = function(_) {
      if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1];
      return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]);
    };
    return voronoi;
  };
  var d3_geom_voronoiClipExtent = [ [ -1e6, -1e6 ], [ 1e6, 1e6 ] ];
  function d3_geom_voronoiTriangleArea(a, b, c) {
    return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y);
  }
  d3.geom.delaunay = function(vertices) {
    return d3.geom.voronoi().triangles(vertices);
  };
  d3.geom.quadtree = function(points, x1, y1, x2, y2) {
    var x = d3_geom_pointX, y = d3_geom_pointY, compat;
    if (compat = arguments.length) {
      x = d3_geom_quadtreeCompatX;
      y = d3_geom_quadtreeCompatY;
      if (compat === 3) {
        y2 = y1;
        x2 = x1;
        y1 = x1 = 0;
      }
      return quadtree(points);
    }
    function quadtree(data) {
      var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_;
      if (x1 != null) {
        x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2;
      } else {
        x2_ = y2_ = -(x1_ = y1_ = Infinity);
        xs = [], ys = [];
        n = data.length;
        if (compat) for (i = 0; i < n; ++i) {
          d = data[i];
          if (d.x < x1_) x1_ = d.x;
          if (d.y < y1_) y1_ = d.y;
          if (d.x > x2_) x2_ = d.x;
          if (d.y > y2_) y2_ = d.y;
          xs.push(d.x);
          ys.push(d.y);
        } else for (i = 0; i < n; ++i) {
          var x_ = +fx(d = data[i], i), y_ = +fy(d, i);
          if (x_ < x1_) x1_ = x_;
          if (y_ < y1_) y1_ = y_;
          if (x_ > x2_) x2_ = x_;
          if (y_ > y2_) y2_ = y_;
          xs.push(x_);
          ys.push(y_);
        }
      }
      var dx = x2_ - x1_, dy = y2_ - y1_;
      if (dx > dy) y2_ = y1_ + dx; else x2_ = x1_ + dy;
      function insert(n, d, x, y, x1, y1, x2, y2) {
        if (isNaN(x) || isNaN(y)) return;
        if (n.leaf) {
          var nx = n.x, ny = n.y;
          if (nx != null) {
            if (abs(nx - x) + abs(ny - y) < .01) {
              insertChild(n, d, x, y, x1, y1, x2, y2);
            } else {
              var nPoint = n.point;
              n.x = n.y = n.point = null;
              insertChild(n, nPoint, nx, ny, x1, y1, x2, y2);
              insertChild(n, d, x, y, x1, y1, x2, y2);
            }
          } else {
            n.x = x, n.y = y, n.point = d;
          }
        } else {
          insertChild(n, d, x, y, x1, y1, x2, y2);
        }
      }
      function insertChild(n, d, x, y, x1, y1, x2, y2) {
        var xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym, i = below << 1 | right;
        n.leaf = false;
        n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode());
        if (right) x1 = xm; else x2 = xm;
        if (below) y1 = ym; else y2 = ym;
        insert(n, d, x, y, x1, y1, x2, y2);
      }
      var root = d3_geom_quadtreeNode();
      root.add = function(d) {
        insert(root, d, +fx(d, ++i), +fy(d, i), x1_, y1_, x2_, y2_);
      };
      root.visit = function(f) {
        d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_);
      };
      root.find = function(point) {
        return d3_geom_quadtreeFind(root, point[0], point[1], x1_, y1_, x2_, y2_);
      };
      i = -1;
      if (x1 == null) {
        while (++i < n) {
          insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_);
        }
        --i;
      } else data.forEach(root.add);
      xs = ys = data = d = null;
      return root;
    }
    quadtree.x = function(_) {
      return arguments.length ? (x = _, quadtree) : x;
    };
    quadtree.y = function(_) {
      return arguments.length ? (y = _, quadtree) : y;
    };
    quadtree.extent = function(_) {
      if (!arguments.length) return x1 == null ? null : [ [ x1, y1 ], [ x2, y2 ] ];
      if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0], 
      y2 = +_[1][1];
      return quadtree;
    };
    quadtree.size = function(_) {
      if (!arguments.length) return x1 == null ? null : [ x2 - x1, y2 - y1 ];
      if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = y1 = 0, x2 = +_[0], y2 = +_[1];
      return quadtree;
    };
    return quadtree;
  };
  function d3_geom_quadtreeCompatX(d) {
    return d.x;
  }
  function d3_geom_quadtreeCompatY(d) {
    return d.y;
  }
  function d3_geom_quadtreeNode() {
    return {
      leaf: true,
      nodes: [],
      point: null,
      x: null,
      y: null
    };
  }
  function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) {
    if (!f(node, x1, y1, x2, y2)) {
      var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes;
      if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy);
      if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy);
      if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2);
      if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2);
    }
  }
  function d3_geom_quadtreeFind(root, x, y, x0, y0, x3, y3) {
    var minDistance2 = Infinity, closestPoint;
    (function find(node, x1, y1, x2, y2) {
      if (x1 > x3 || y1 > y3 || x2 < x0 || y2 < y0) return;
      if (point = node.point) {
        var point, dx = x - node.x, dy = y - node.y, distance2 = dx * dx + dy * dy;
        if (distance2 < minDistance2) {
          var distance = Math.sqrt(minDistance2 = distance2);
          x0 = x - distance, y0 = y - distance;
          x3 = x + distance, y3 = y + distance;
          closestPoint = point;
        }
      }
      var children = node.nodes, xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym;
      for (var i = below << 1 | right, j = i + 4; i < j; ++i) {
        if (node = children[i & 3]) switch (i & 3) {
         case 0:
          find(node, x1, y1, xm, ym);
          break;

         case 1:
          find(node, xm, y1, x2, ym);
          break;

         case 2:
          find(node, x1, ym, xm, y2);
          break;

         case 3:
          find(node, xm, ym, x2, y2);
          break;
        }
      }
    })(root, x0, y0, x3, y3);
    return closestPoint;
  }
  d3.interpolateRgb = d3_interpolateRgb;
  function d3_interpolateRgb(a, b) {
    a = d3.rgb(a);
    b = d3.rgb(b);
    var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab;
    return function(t) {
      return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t));
    };
  }
  d3.interpolateObject = d3_interpolateObject;
  function d3_interpolateObject(a, b) {
    var i = {}, c = {}, k;
    for (k in a) {
      if (k in b) {
        i[k] = d3_interpolate(a[k], b[k]);
      } else {
        c[k] = a[k];
      }
    }
    for (k in b) {
      if (!(k in a)) {
        c[k] = b[k];
      }
    }
    return function(t) {
      for (k in i) c[k] = i[k](t);
      return c;
    };
  }
  d3.interpolateNumber = d3_interpolateNumber;
  function d3_interpolateNumber(a, b) {
    a = +a, b = +b;
    return function(t) {
      return a * (1 - t) + b * t;
    };
  }
  d3.interpolateString = d3_interpolateString;
  function d3_interpolateString(a, b) {
    var bi = d3_interpolate_numberA.lastIndex = d3_interpolate_numberB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = [];
    a = a + "", b = b + "";
    while ((am = d3_interpolate_numberA.exec(a)) && (bm = d3_interpolate_numberB.exec(b))) {
      if ((bs = bm.index) > bi) {
        bs = b.slice(bi, bs);
        if (s[i]) s[i] += bs; else s[++i] = bs;
      }
      if ((am = am[0]) === (bm = bm[0])) {
        if (s[i]) s[i] += bm; else s[++i] = bm;
      } else {
        s[++i] = null;
        q.push({
          i: i,
          x: d3_interpolateNumber(am, bm)
        });
      }
      bi = d3_interpolate_numberB.lastIndex;
    }
    if (bi < b.length) {
      bs = b.slice(bi);
      if (s[i]) s[i] += bs; else s[++i] = bs;
    }
    return s.length < 2 ? q[0] ? (b = q[0].x, function(t) {
      return b(t) + "";
    }) : function() {
      return b;
    } : (b = q.length, function(t) {
      for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);
      return s.join("");
    });
  }
  var d3_interpolate_numberA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, d3_interpolate_numberB = new RegExp(d3_interpolate_numberA.source, "g");
  d3.interpolate = d3_interpolate;
  function d3_interpolate(a, b) {
    var i = d3.interpolators.length, f;
    while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ;
    return f;
  }
  d3.interpolators = [ function(a, b) {
    var t = typeof b;
    return (t === "string" ? d3_rgb_names.has(b.toLowerCase()) || /^(#|rgb\(|hsl\()/i.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_color ? d3_interpolateRgb : Array.isArray(b) ? d3_interpolateArray : t === "object" && isNaN(b) ? d3_interpolateObject : d3_interpolateNumber)(a, b);
  } ];
  d3.interpolateArray = d3_interpolateArray;
  function d3_interpolateArray(a, b) {
    var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i;
    for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i]));
    for (;i < na; ++i) c[i] = a[i];
    for (;i < nb; ++i) c[i] = b[i];
    return function(t) {
      for (i = 0; i < n0; ++i) c[i] = x[i](t);
      return c;
    };
  }
  var d3_ease_default = function() {
    return d3_identity;
  };
  var d3_ease = d3.map({
    linear: d3_ease_default,
    poly: d3_ease_poly,
    quad: function() {
      return d3_ease_quad;
    },
    cubic: function() {
      return d3_ease_cubic;
    },
    sin: function() {
      return d3_ease_sin;
    },
    exp: function() {
      return d3_ease_exp;
    },
    circle: function() {
      return d3_ease_circle;
    },
    elastic: d3_ease_elastic,
    back: d3_ease_back,
    bounce: function() {
      return d3_ease_bounce;
    }
  });
  var d3_ease_mode = d3.map({
    "in": d3_identity,
    out: d3_ease_reverse,
    "in-out": d3_ease_reflect,
    "out-in": function(f) {
      return d3_ease_reflect(d3_ease_reverse(f));
    }
  });
  d3.ease = function(name) {
    var i = name.indexOf("-"), t = i >= 0 ? name.slice(0, i) : name, m = i >= 0 ? name.slice(i + 1) : "in";
    t = d3_ease.get(t) || d3_ease_default;
    m = d3_ease_mode.get(m) || d3_identity;
    return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1))));
  };
  function d3_ease_clamp(f) {
    return function(t) {
      return t <= 0 ? 0 : t >= 1 ? 1 : f(t);
    };
  }
  function d3_ease_reverse(f) {
    return function(t) {
      return 1 - f(1 - t);
    };
  }
  function d3_ease_reflect(f) {
    return function(t) {
      return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t));
    };
  }
  function d3_ease_quad(t) {
    return t * t;
  }
  function d3_ease_cubic(t) {
    return t * t * t;
  }
  function d3_ease_cubicInOut(t) {
    if (t <= 0) return 0;
    if (t >= 1) return 1;
    var t2 = t * t, t3 = t2 * t;
    return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75);
  }
  function d3_ease_poly(e) {
    return function(t) {
      return Math.pow(t, e);
    };
  }
  function d3_ease_sin(t) {
    return 1 - Math.cos(t * halfπ);
  }
  function d3_ease_exp(t) {
    return Math.pow(2, 10 * (t - 1));
  }
  function d3_ease_circle(t) {
    return 1 - Math.sqrt(1 - t * t);
  }
  function d3_ease_elastic(a, p) {
    var s;
    if (arguments.length < 2) p = .45;
    if (arguments.length) s = p / τ * Math.asin(1 / a); else a = 1, s = p / 4;
    return function(t) {
      return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * τ / p);
    };
  }
  function d3_ease_back(s) {
    if (!s) s = 1.70158;
    return function(t) {
      return t * t * ((s + 1) * t - s);
    };
  }
  function d3_ease_bounce(t) {
    return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375;
  }
  d3.interpolateHcl = d3_interpolateHcl;
  function d3_interpolateHcl(a, b) {
    a = d3.hcl(a);
    b = d3.hcl(b);
    var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al;
    if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac;
    if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360;
    return function(t) {
      return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + "";
    };
  }
  d3.interpolateHsl = d3_interpolateHsl;
  function d3_interpolateHsl(a, b) {
    a = d3.hsl(a);
    b = d3.hsl(b);
    var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al;
    if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as;
    if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360;
    return function(t) {
      return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + "";
    };
  }
  d3.interpolateLab = d3_interpolateLab;
  function d3_interpolateLab(a, b) {
    a = d3.lab(a);
    b = d3.lab(b);
    var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab;
    return function(t) {
      return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + "";
    };
  }
  d3.interpolateRound = d3_interpolateRound;
  function d3_interpolateRound(a, b) {
    b -= a;
    return function(t) {
      return Math.round(a + b * t);
    };
  }
  d3.transform = function(string) {
    var g = d3_document.createElementNS(d3.ns.prefix.svg, "g");
    return (d3.transform = function(string) {
      if (string != null) {
        g.setAttribute("transform", string);
        var t = g.transform.baseVal.consolidate();
      }
      return new d3_transform(t ? t.matrix : d3_transformIdentity);
    })(string);
  };
  function d3_transform(m) {
    var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0;
    if (r0[0] * r1[1] < r1[0] * r0[1]) {
      r0[0] *= -1;
      r0[1] *= -1;
      kx *= -1;
      kz *= -1;
    }
    this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees;
    this.translate = [ m.e, m.f ];
    this.scale = [ kx, ky ];
    this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0;
  }
  d3_transform.prototype.toString = function() {
    return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")";
  };
  function d3_transformDot(a, b) {
    return a[0] * b[0] + a[1] * b[1];
  }
  function d3_transformNormalize(a) {
    var k = Math.sqrt(d3_transformDot(a, a));
    if (k) {
      a[0] /= k;
      a[1] /= k;
    }
    return k;
  }
  function d3_transformCombine(a, b, k) {
    a[0] += k * b[0];
    a[1] += k * b[1];
    return a;
  }
  var d3_transformIdentity = {
    a: 1,
    b: 0,
    c: 0,
    d: 1,
    e: 0,
    f: 0
  };
  d3.interpolateTransform = d3_interpolateTransform;
  function d3_interpolateTransformPop(s) {
    return s.length ? s.pop() + "," : "";
  }
  function d3_interpolateTranslate(ta, tb, s, q) {
    if (ta[0] !== tb[0] || ta[1] !== tb[1]) {
      var i = s.push("translate(", null, ",", null, ")");
      q.push({
        i: i - 4,
        x: d3_interpolateNumber(ta[0], tb[0])
      }, {
        i: i - 2,
        x: d3_interpolateNumber(ta[1], tb[1])
      });
    } else if (tb[0] || tb[1]) {
      s.push("translate(" + tb + ")");
    }
  }
  function d3_interpolateRotate(ra, rb, s, q) {
    if (ra !== rb) {
      if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360;
      q.push({
        i: s.push(d3_interpolateTransformPop(s) + "rotate(", null, ")") - 2,
        x: d3_interpolateNumber(ra, rb)
      });
    } else if (rb) {
      s.push(d3_interpolateTransformPop(s) + "rotate(" + rb + ")");
    }
  }
  function d3_interpolateSkew(wa, wb, s, q) {
    if (wa !== wb) {
      q.push({
        i: s.push(d3_interpolateTransformPop(s) + "skewX(", null, ")") - 2,
        x: d3_interpolateNumber(wa, wb)
      });
    } else if (wb) {
      s.push(d3_interpolateTransformPop(s) + "skewX(" + wb + ")");
    }
  }
  function d3_interpolateScale(ka, kb, s, q) {
    if (ka[0] !== kb[0] || ka[1] !== kb[1]) {
      var i = s.push(d3_interpolateTransformPop(s) + "scale(", null, ",", null, ")");
      q.push({
        i: i - 4,
        x: d3_interpolateNumber(ka[0], kb[0])
      }, {
        i: i - 2,
        x: d3_interpolateNumber(ka[1], kb[1])
      });
    } else if (kb[0] !== 1 || kb[1] !== 1) {
      s.push(d3_interpolateTransformPop(s) + "scale(" + kb + ")");
    }
  }
  function d3_interpolateTransform(a, b) {
    var s = [], q = [];
    a = d3.transform(a), b = d3.transform(b);
    d3_interpolateTranslate(a.translate, b.translate, s, q);
    d3_interpolateRotate(a.rotate, b.rotate, s, q);
    d3_interpolateSkew(a.skew, b.skew, s, q);
    d3_interpolateScale(a.scale, b.scale, s, q);
    a = b = null;
    return function(t) {
      var i = -1, n = q.length, o;
      while (++i < n) s[(o = q[i]).i] = o.x(t);
      return s.join("");
    };
  }
  function d3_uninterpolateNumber(a, b) {
    b = (b -= a = +a) || 1 / b;
    return function(x) {
      return (x - a) / b;
    };
  }
  function d3_uninterpolateClamp(a, b) {
    b = (b -= a = +a) || 1 / b;
    return function(x) {
      return Math.max(0, Math.min(1, (x - a) / b));
    };
  }
  d3.layout = {};
  d3.layout.bundle = function() {
    return function(links) {
      var paths = [], i = -1, n = links.length;
      while (++i < n) paths.push(d3_layout_bundlePath(links[i]));
      return paths;
    };
  };
  function d3_layout_bundlePath(link) {
    var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ];
    while (start !== lca) {
      start = start.parent;
      points.push(start);
    }
    var k = points.length;
    while (end !== lca) {
      points.splice(k, 0, end);
      end = end.parent;
    }
    return points;
  }
  function d3_layout_bundleAncestors(node) {
    var ancestors = [], parent = node.parent;
    while (parent != null) {
      ancestors.push(node);
      node = parent;
      parent = parent.parent;
    }
    ancestors.push(node);
    return ancestors;
  }
  function d3_layout_bundleLeastCommonAncestor(a, b) {
    if (a === b) return a;
    var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null;
    while (aNode === bNode) {
      sharedNode = aNode;
      aNode = aNodes.pop();
      bNode = bNodes.pop();
    }
    return sharedNode;
  }
  d3.layout.chord = function() {
    var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords;
    function relayout() {
      var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j;
      chords = [];
      groups = [];
      k = 0, i = -1;
      while (++i < n) {
        x = 0, j = -1;
        while (++j < n) {
          x += matrix[i][j];
        }
        groupSums.push(x);
        subgroupIndex.push(d3.range(n));
        k += x;
      }
      if (sortGroups) {
        groupIndex.sort(function(a, b) {
          return sortGroups(groupSums[a], groupSums[b]);
        });
      }
      if (sortSubgroups) {
        subgroupIndex.forEach(function(d, i) {
          d.sort(function(a, b) {
            return sortSubgroups(matrix[i][a], matrix[i][b]);
          });
        });
      }
      k = (τ - padding * n) / k;
      x = 0, i = -1;
      while (++i < n) {
        x0 = x, j = -1;
        while (++j < n) {
          var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k;
          subgroups[di + "-" + dj] = {
            index: di,
            subindex: dj,
            startAngle: a0,
            endAngle: a1,
            value: v
          };
        }
        groups[di] = {
          index: di,
          startAngle: x0,
          endAngle: x,
          value: groupSums[di]
        };
        x += padding;
      }
      i = -1;
      while (++i < n) {
        j = i - 1;
        while (++j < n) {
          var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i];
          if (source.value || target.value) {
            chords.push(source.value < target.value ? {
              source: target,
              target: source
            } : {
              source: source,
              target: target
            });
          }
        }
      }
      if (sortChords) resort();
    }
    function resort() {
      chords.sort(function(a, b) {
        return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2);
      });
    }
    chord.matrix = function(x) {
      if (!arguments.length) return matrix;
      n = (matrix = x) && matrix.length;
      chords = groups = null;
      return chord;
    };
    chord.padding = function(x) {
      if (!arguments.length) return padding;
      padding = x;
      chords = groups = null;
      return chord;
    };
    chord.sortGroups = function(x) {
      if (!arguments.length) return sortGroups;
      sortGroups = x;
      chords = groups = null;
      return chord;
    };
    chord.sortSubgroups = function(x) {
      if (!arguments.length) return sortSubgroups;
      sortSubgroups = x;
      chords = null;
      return chord;
    };
    chord.sortChords = function(x) {
      if (!arguments.length) return sortChords;
      sortChords = x;
      if (chords) resort();
      return chord;
    };
    chord.chords = function() {
      if (!chords) relayout();
      return chords;
    };
    chord.groups = function() {
      if (!groups) relayout();
      return groups;
    };
    return chord;
  };
  d3.layout.force = function() {
    var force = {}, event = d3.dispatch("start", "tick", "end"), timer, size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, chargeDistance2 = d3_layout_forceChargeDistance2, gravity = .1, theta2 = .64, nodes = [], links = [], distances, strengths, charges;
    function repulse(node) {
      return function(quad, x1, _, x2) {
        if (quad.point !== node) {
          var dx = quad.cx - node.x, dy = quad.cy - node.y, dw = x2 - x1, dn = dx * dx + dy * dy;
          if (dw * dw / theta2 < dn) {
            if (dn < chargeDistance2) {
              var k = quad.charge / dn;
              node.px -= dx * k;
              node.py -= dy * k;
            }
            return true;
          }
          if (quad.point && dn && dn < chargeDistance2) {
            var k = quad.pointCharge / dn;
            node.px -= dx * k;
            node.py -= dy * k;
          }
        }
        return !quad.charge;
      };
    }
    force.tick = function() {
      if ((alpha *= .99) < .005) {
        timer = null;
        event.end({
          type: "end",
          alpha: alpha = 0
        });
        return true;
      }
      var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y;
      for (i = 0; i < m; ++i) {
        o = links[i];
        s = o.source;
        t = o.target;
        x = t.x - s.x;
        y = t.y - s.y;
        if (l = x * x + y * y) {
          l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l;
          x *= l;
          y *= l;
          t.x -= x * (k = s.weight + t.weight ? s.weight / (s.weight + t.weight) : .5);
          t.y -= y * k;
          s.x += x * (k = 1 - k);
          s.y += y * k;
        }
      }
      if (k = alpha * gravity) {
        x = size[0] / 2;
        y = size[1] / 2;
        i = -1;
        if (k) while (++i < n) {
          o = nodes[i];
          o.x += (x - o.x) * k;
          o.y += (y - o.y) * k;
        }
      }
      if (charge) {
        d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges);
        i = -1;
        while (++i < n) {
          if (!(o = nodes[i]).fixed) {
            q.visit(repulse(o));
          }
        }
      }
      i = -1;
      while (++i < n) {
        o = nodes[i];
        if (o.fixed) {
          o.x = o.px;
          o.y = o.py;
        } else {
          o.x -= (o.px - (o.px = o.x)) * friction;
          o.y -= (o.py - (o.py = o.y)) * friction;
        }
      }
      event.tick({
        type: "tick",
        alpha: alpha
      });
    };
    force.nodes = function(x) {
      if (!arguments.length) return nodes;
      nodes = x;
      return force;
    };
    force.links = function(x) {
      if (!arguments.length) return links;
      links = x;
      return force;
    };
    force.size = function(x) {
      if (!arguments.length) return size;
      size = x;
      return force;
    };
    force.linkDistance = function(x) {
      if (!arguments.length) return linkDistance;
      linkDistance = typeof x === "function" ? x : +x;
      return force;
    };
    force.distance = force.linkDistance;
    force.linkStrength = function(x) {
      if (!arguments.length) return linkStrength;
      linkStrength = typeof x === "function" ? x : +x;
      return force;
    };
    force.friction = function(x) {
      if (!arguments.length) return friction;
      friction = +x;
      return force;
    };
    force.charge = function(x) {
      if (!arguments.length) return charge;
      charge = typeof x === "function" ? x : +x;
      return force;
    };
    force.chargeDistance = function(x) {
      if (!arguments.length) return Math.sqrt(chargeDistance2);
      chargeDistance2 = x * x;
      return force;
    };
    force.gravity = function(x) {
      if (!arguments.length) return gravity;
      gravity = +x;
      return force;
    };
    force.theta = function(x) {
      if (!arguments.length) return Math.sqrt(theta2);
      theta2 = x * x;
      return force;
    };
    force.alpha = function(x) {
      if (!arguments.length) return alpha;
      x = +x;
      if (alpha) {
        if (x > 0) {
          alpha = x;
        } else {
          timer.c = null, timer.t = NaN, timer = null;
          event.end({
            type: "end",
            alpha: alpha = 0
          });
        }
      } else if (x > 0) {
        event.start({
          type: "start",
          alpha: alpha = x
        });
        timer = d3_timer(force.tick);
      }
      return force;
    };
    force.start = function() {
      var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o;
      for (i = 0; i < n; ++i) {
        (o = nodes[i]).index = i;
        o.weight = 0;
      }
      for (i = 0; i < m; ++i) {
        o = links[i];
        if (typeof o.source == "number") o.source = nodes[o.source];
        if (typeof o.target == "number") o.target = nodes[o.target];
        ++o.source.weight;
        ++o.target.weight;
      }
      for (i = 0; i < n; ++i) {
        o = nodes[i];
        if (isNaN(o.x)) o.x = position("x", w);
        if (isNaN(o.y)) o.y = position("y", h);
        if (isNaN(o.px)) o.px = o.x;
        if (isNaN(o.py)) o.py = o.y;
      }
      distances = [];
      if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance;
      strengths = [];
      if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength;
      charges = [];
      if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge;
      function position(dimension, size) {
        if (!neighbors) {
          neighbors = new Array(n);
          for (j = 0; j < n; ++j) {
            neighbors[j] = [];
          }
          for (j = 0; j < m; ++j) {
            var o = links[j];
            neighbors[o.source.index].push(o.target);
            neighbors[o.target.index].push(o.source);
          }
        }
        var candidates = neighbors[i], j = -1, l = candidates.length, x;
        while (++j < l) if (!isNaN(x = candidates[j][dimension])) return x;
        return Math.random() * size;
      }
      return force.resume();
    };
    force.resume = function() {
      return force.alpha(.1);
    };
    force.stop = function() {
      return force.alpha(0);
    };
    force.drag = function() {
      if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend);
      if (!arguments.length) return drag;
      this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag);
    };
    function dragmove(d) {
      d.px = d3.event.x, d.py = d3.event.y;
      force.resume();
    }
    return d3.rebind(force, event, "on");
  };
  function d3_layout_forceDragstart(d) {
    d.fixed |= 2;
  }
  function d3_layout_forceDragend(d) {
    d.fixed &= ~6;
  }
  function d3_layout_forceMouseover(d) {
    d.fixed |= 4;
    d.px = d.x, d.py = d.y;
  }
  function d3_layout_forceMouseout(d) {
    d.fixed &= ~4;
  }
  function d3_layout_forceAccumulate(quad, alpha, charges) {
    var cx = 0, cy = 0;
    quad.charge = 0;
    if (!quad.leaf) {
      var nodes = quad.nodes, n = nodes.length, i = -1, c;
      while (++i < n) {
        c = nodes[i];
        if (c == null) continue;
        d3_layout_forceAccumulate(c, alpha, charges);
        quad.charge += c.charge;
        cx += c.charge * c.cx;
        cy += c.charge * c.cy;
      }
    }
    if (quad.point) {
      if (!quad.leaf) {
        quad.point.x += Math.random() - .5;
        quad.point.y += Math.random() - .5;
      }
      var k = alpha * charges[quad.point.index];
      quad.charge += quad.pointCharge = k;
      cx += k * quad.point.x;
      cy += k * quad.point.y;
    }
    quad.cx = cx / quad.charge;
    quad.cy = cy / quad.charge;
  }
  var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1, d3_layout_forceChargeDistance2 = Infinity;
  d3.layout.hierarchy = function() {
    var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue;
    function hierarchy(root) {
      var stack = [ root ], nodes = [], node;
      root.depth = 0;
      while ((node = stack.pop()) != null) {
        nodes.push(node);
        if ((childs = children.call(hierarchy, node, node.depth)) && (n = childs.length)) {
          var n, childs, child;
          while (--n >= 0) {
            stack.push(child = childs[n]);
            child.parent = node;
            child.depth = node.depth + 1;
          }
          if (value) node.value = 0;
          node.children = childs;
        } else {
          if (value) node.value = +value.call(hierarchy, node, node.depth) || 0;
          delete node.children;
        }
      }
      d3_layout_hierarchyVisitAfter(root, function(node) {
        var childs, parent;
        if (sort && (childs = node.children)) childs.sort(sort);
        if (value && (parent = node.parent)) parent.value += node.value;
      });
      return nodes;
    }
    hierarchy.sort = function(x) {
      if (!arguments.length) return sort;
      sort = x;
      return hierarchy;
    };
    hierarchy.children = function(x) {
      if (!arguments.length) return children;
      children = x;
      return hierarchy;
    };
    hierarchy.value = function(x) {
      if (!arguments.length) return value;
      value = x;
      return hierarchy;
    };
    hierarchy.revalue = function(root) {
      if (value) {
        d3_layout_hierarchyVisitBefore(root, function(node) {
          if (node.children) node.value = 0;
        });
        d3_layout_hierarchyVisitAfter(root, function(node) {
          var parent;
          if (!node.children) node.value = +value.call(hierarchy, node, node.depth) || 0;
          if (parent = node.parent) parent.value += node.value;
        });
      }
      return root;
    };
    return hierarchy;
  };
  function d3_layout_hierarchyRebind(object, hierarchy) {
    d3.rebind(object, hierarchy, "sort", "children", "value");
    object.nodes = object;
    object.links = d3_layout_hierarchyLinks;
    return object;
  }
  function d3_layout_hierarchyVisitBefore(node, callback) {
    var nodes = [ node ];
    while ((node = nodes.pop()) != null) {
      callback(node);
      if ((children = node.children) && (n = children.length)) {
        var n, children;
        while (--n >= 0) nodes.push(children[n]);
      }
    }
  }
  function d3_layout_hierarchyVisitAfter(node, callback) {
    var nodes = [ node ], nodes2 = [];
    while ((node = nodes.pop()) != null) {
      nodes2.push(node);
      if ((children = node.children) && (n = children.length)) {
        var i = -1, n, children;
        while (++i < n) nodes.push(children[i]);
      }
    }
    while ((node = nodes2.pop()) != null) {
      callback(node);
    }
  }
  function d3_layout_hierarchyChildren(d) {
    return d.children;
  }
  function d3_layout_hierarchyValue(d) {
    return d.value;
  }
  function d3_layout_hierarchySort(a, b) {
    return b.value - a.value;
  }
  function d3_layout_hierarchyLinks(nodes) {
    return d3.merge(nodes.map(function(parent) {
      return (parent.children || []).map(function(child) {
        return {
          source: parent,
          target: child
        };
      });
    }));
  }
  d3.layout.partition = function() {
    var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ];
    function position(node, x, dx, dy) {
      var children = node.children;
      node.x = x;
      node.y = node.depth * dy;
      node.dx = dx;
      node.dy = dy;
      if (children && (n = children.length)) {
        var i = -1, n, c, d;
        dx = node.value ? dx / node.value : 0;
        while (++i < n) {
          position(c = children[i], x, d = c.value * dx, dy);
          x += d;
        }
      }
    }
    function depth(node) {
      var children = node.children, d = 0;
      if (children && (n = children.length)) {
        var i = -1, n;
        while (++i < n) d = Math.max(d, depth(children[i]));
      }
      return 1 + d;
    }
    function partition(d, i) {
      var nodes = hierarchy.call(this, d, i);
      position(nodes[0], 0, size[0], size[1] / depth(nodes[0]));
      return nodes;
    }
    partition.size = function(x) {
      if (!arguments.length) return size;
      size = x;
      return partition;
    };
    return d3_layout_hierarchyRebind(partition, hierarchy);
  };
  d3.layout.pie = function() {
    var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ, padAngle = 0;
    function pie(data) {
      var n = data.length, values = data.map(function(d, i) {
        return +value.call(pie, d, i);
      }), a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle), da = (typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a, p = Math.min(Math.abs(da) / n, +(typeof padAngle === "function" ? padAngle.apply(this, arguments) : padAngle)), pa = p * (da < 0 ? -1 : 1), sum = d3.sum(values), k = sum ? (da - n * pa) / sum : 0, index = d3.range(n), arcs = [], v;
      if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) {
        return values[j] - values[i];
      } : function(i, j) {
        return sort(data[i], data[j]);
      });
      index.forEach(function(i) {
        arcs[i] = {
          data: data[i],
          value: v = values[i],
          startAngle: a,
          endAngle: a += v * k + pa,
          padAngle: p
        };
      });
      return arcs;
    }
    pie.value = function(_) {
      if (!arguments.length) return value;
      value = _;
      return pie;
    };
    pie.sort = function(_) {
      if (!arguments.length) return sort;
      sort = _;
      return pie;
    };
    pie.startAngle = function(_) {
      if (!arguments.length) return startAngle;
      startAngle = _;
      return pie;
    };
    pie.endAngle = function(_) {
      if (!arguments.length) return endAngle;
      endAngle = _;
      return pie;
    };
    pie.padAngle = function(_) {
      if (!arguments.length) return padAngle;
      padAngle = _;
      return pie;
    };
    return pie;
  };
  var d3_layout_pieSortByValue = {};
  d3.layout.stack = function() {
    var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY;
    function stack(data, index) {
      if (!(n = data.length)) return data;
      var series = data.map(function(d, i) {
        return values.call(stack, d, i);
      });
      var points = series.map(function(d) {
        return d.map(function(v, i) {
          return [ x.call(stack, v, i), y.call(stack, v, i) ];
        });
      });
      var orders = order.call(stack, points, index);
      series = d3.permute(series, orders);
      points = d3.permute(points, orders);
      var offsets = offset.call(stack, points, index);
      var m = series[0].length, n, i, j, o;
      for (j = 0; j < m; ++j) {
        out.call(stack, series[0][j], o = offsets[j], points[0][j][1]);
        for (i = 1; i < n; ++i) {
          out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]);
        }
      }
      return data;
    }
    stack.values = function(x) {
      if (!arguments.length) return values;
      values = x;
      return stack;
    };
    stack.order = function(x) {
      if (!arguments.length) return order;
      order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault;
      return stack;
    };
    stack.offset = function(x) {
      if (!arguments.length) return offset;
      offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero;
      return stack;
    };
    stack.x = function(z) {
      if (!arguments.length) return x;
      x = z;
      return stack;
    };
    stack.y = function(z) {
      if (!arguments.length) return y;
      y = z;
      return stack;
    };
    stack.out = function(z) {
      if (!arguments.length) return out;
      out = z;
      return stack;
    };
    return stack;
  };
  function d3_layout_stackX(d) {
    return d.x;
  }
  function d3_layout_stackY(d) {
    return d.y;
  }
  function d3_layout_stackOut(d, y0, y) {
    d.y0 = y0;
    d.y = y;
  }
  var d3_layout_stackOrders = d3.map({
    "inside-out": function(data) {
      var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) {
        return max[a] - max[b];
      }), top = 0, bottom = 0, tops = [], bottoms = [];
      for (i = 0; i < n; ++i) {
        j = index[i];
        if (top < bottom) {
          top += sums[j];
          tops.push(j);
        } else {
          bottom += sums[j];
          bottoms.push(j);
        }
      }
      return bottoms.reverse().concat(tops);
    },
    reverse: function(data) {
      return d3.range(data.length).reverse();
    },
    "default": d3_layout_stackOrderDefault
  });
  var d3_layout_stackOffsets = d3.map({
    silhouette: function(data) {
      var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = [];
      for (j = 0; j < m; ++j) {
        for (i = 0, o = 0; i < n; i++) o += data[i][j][1];
        if (o > max) max = o;
        sums.push(o);
      }
      for (j = 0; j < m; ++j) {
        y0[j] = (max - sums[j]) / 2;
      }
      return y0;
    },
    wiggle: function(data) {
      var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = [];
      y0[0] = o = o0 = 0;
      for (j = 1; j < m; ++j) {
        for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1];
        for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) {
          for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) {
            s3 += (data[k][j][1] - data[k][j - 1][1]) / dx;
          }
          s2 += s3 * data[i][j][1];
        }
        y0[j] = o -= s1 ? s2 / s1 * dx : 0;
        if (o < o0) o0 = o;
      }
      for (j = 0; j < m; ++j) y0[j] -= o0;
      return y0;
    },
    expand: function(data) {
      var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = [];
      for (j = 0; j < m; ++j) {
        for (i = 0, o = 0; i < n; i++) o += data[i][j][1];
        if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k;
      }
      for (j = 0; j < m; ++j) y0[j] = 0;
      return y0;
    },
    zero: d3_layout_stackOffsetZero
  });
  function d3_layout_stackOrderDefault(data) {
    return d3.range(data.length);
  }
  function d3_layout_stackOffsetZero(data) {
    var j = -1, m = data[0].length, y0 = [];
    while (++j < m) y0[j] = 0;
    return y0;
  }
  function d3_layout_stackMaxIndex(array) {
    var i = 1, j = 0, v = array[0][1], k, n = array.length;
    for (;i < n; ++i) {
      if ((k = array[i][1]) > v) {
        j = i;
        v = k;
      }
    }
    return j;
  }
  function d3_layout_stackReduceSum(d) {
    return d.reduce(d3_layout_stackSum, 0);
  }
  function d3_layout_stackSum(p, d) {
    return p + d[1];
  }
  d3.layout.histogram = function() {
    var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges;
    function histogram(data, i) {
      var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x;
      while (++i < m) {
        bin = bins[i] = [];
        bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]);
        bin.y = 0;
      }
      if (m > 0) {
        i = -1;
        while (++i < n) {
          x = values[i];
          if (x >= range[0] && x <= range[1]) {
            bin = bins[d3.bisect(thresholds, x, 1, m) - 1];
            bin.y += k;
            bin.push(data[i]);
          }
        }
      }
      return bins;
    }
    histogram.value = function(x) {
      if (!arguments.length) return valuer;
      valuer = x;
      return histogram;
    };
    histogram.range = function(x) {
      if (!arguments.length) return ranger;
      ranger = d3_functor(x);
      return histogram;
    };
    histogram.bins = function(x) {
      if (!arguments.length) return binner;
      binner = typeof x === "number" ? function(range) {
        return d3_layout_histogramBinFixed(range, x);
      } : d3_functor(x);
      return histogram;
    };
    histogram.frequency = function(x) {
      if (!arguments.length) return frequency;
      frequency = !!x;
      return histogram;
    };
    return histogram;
  };
  function d3_layout_histogramBinSturges(range, values) {
    return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1));
  }
  function d3_layout_histogramBinFixed(range, n) {
    var x = -1, b = +range[0], m = (range[1] - b) / n, f = [];
    while (++x <= n) f[x] = m * x + b;
    return f;
  }
  function d3_layout_histogramRange(values) {
    return [ d3.min(values), d3.max(values) ];
  }
  d3.layout.pack = function() {
    var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ], radius;
    function pack(d, i) {
      var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() {
        return radius;
      };
      root.x = root.y = 0;
      d3_layout_hierarchyVisitAfter(root, function(d) {
        d.r = +r(d.value);
      });
      d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings);
      if (padding) {
        var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2;
        d3_layout_hierarchyVisitAfter(root, function(d) {
          d.r += dr;
        });
        d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings);
        d3_layout_hierarchyVisitAfter(root, function(d) {
          d.r -= dr;
        });
      }
      d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h));
      return nodes;
    }
    pack.size = function(_) {
      if (!arguments.length) return size;
      size = _;
      return pack;
    };
    pack.radius = function(_) {
      if (!arguments.length) return radius;
      radius = _ == null || typeof _ === "function" ? _ : +_;
      return pack;
    };
    pack.padding = function(_) {
      if (!arguments.length) return padding;
      padding = +_;
      return pack;
    };
    return d3_layout_hierarchyRebind(pack, hierarchy);
  };
  function d3_layout_packSort(a, b) {
    return a.value - b.value;
  }
  function d3_layout_packInsert(a, b) {
    var c = a._pack_next;
    a._pack_next = b;
    b._pack_prev = a;
    b._pack_next = c;
    c._pack_prev = b;
  }
  function d3_layout_packSplice(a, b) {
    a._pack_next = b;
    b._pack_prev = a;
  }
  function d3_layout_packIntersects(a, b) {
    var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r;
    return .999 * dr * dr > dx * dx + dy * dy;
  }
  function d3_layout_packSiblings(node) {
    if (!(nodes = node.children) || !(n = nodes.length)) return;
    var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n;
    function bound(node) {
      xMin = Math.min(node.x - node.r, xMin);
      xMax = Math.max(node.x + node.r, xMax);
      yMin = Math.min(node.y - node.r, yMin);
      yMax = Math.max(node.y + node.r, yMax);
    }
    nodes.forEach(d3_layout_packLink);
    a = nodes[0];
    a.x = -a.r;
    a.y = 0;
    bound(a);
    if (n > 1) {
      b = nodes[1];
      b.x = b.r;
      b.y = 0;
      bound(b);
      if (n > 2) {
        c = nodes[2];
        d3_layout_packPlace(a, b, c);
        bound(c);
        d3_layout_packInsert(a, c);
        a._pack_prev = c;
        d3_layout_packInsert(c, b);
        b = a._pack_next;
        for (i = 3; i < n; i++) {
          d3_layout_packPlace(a, b, c = nodes[i]);
          var isect = 0, s1 = 1, s2 = 1;
          for (j = b._pack_next; j !== b; j = j._pack_next, s1++) {
            if (d3_layout_packIntersects(j, c)) {
              isect = 1;
              break;
            }
          }
          if (isect == 1) {
            for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) {
              if (d3_layout_packIntersects(k, c)) {
                break;
              }
            }
          }
          if (isect) {
            if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b);
            i--;
          } else {
            d3_layout_packInsert(a, c);
            b = c;
            bound(c);
          }
        }
      }
    }
    var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0;
    for (i = 0; i < n; i++) {
      c = nodes[i];
      c.x -= cx;
      c.y -= cy;
      cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y));
    }
    node.r = cr;
    nodes.forEach(d3_layout_packUnlink);
  }
  function d3_layout_packLink(node) {
    node._pack_next = node._pack_prev = node;
  }
  function d3_layout_packUnlink(node) {
    delete node._pack_next;
    delete node._pack_prev;
  }
  function d3_layout_packTransform(node, x, y, k) {
    var children = node.children;
    node.x = x += k * node.x;
    node.y = y += k * node.y;
    node.r *= k;
    if (children) {
      var i = -1, n = children.length;
      while (++i < n) d3_layout_packTransform(children[i], x, y, k);
    }
  }
  function d3_layout_packPlace(a, b, c) {
    var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y;
    if (db && (dx || dy)) {
      var da = b.r + c.r, dc = dx * dx + dy * dy;
      da *= da;
      db *= db;
      var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc);
      c.x = a.x + x * dx + y * dy;
      c.y = a.y + x * dy - y * dx;
    } else {
      c.x = a.x + db;
      c.y = a.y;
    }
  }
  d3.layout.tree = function() {
    var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = null;
    function tree(d, i) {
      var nodes = hierarchy.call(this, d, i), root0 = nodes[0], root1 = wrapTree(root0);
      d3_layout_hierarchyVisitAfter(root1, firstWalk), root1.parent.m = -root1.z;
      d3_layout_hierarchyVisitBefore(root1, secondWalk);
      if (nodeSize) d3_layout_hierarchyVisitBefore(root0, sizeNode); else {
        var left = root0, right = root0, bottom = root0;
        d3_layout_hierarchyVisitBefore(root0, function(node) {
          if (node.x < left.x) left = node;
          if (node.x > right.x) right = node;
          if (node.depth > bottom.depth) bottom = node;
        });
        var tx = separation(left, right) / 2 - left.x, kx = size[0] / (right.x + separation(right, left) / 2 + tx), ky = size[1] / (bottom.depth || 1);
        d3_layout_hierarchyVisitBefore(root0, function(node) {
          node.x = (node.x + tx) * kx;
          node.y = node.depth * ky;
        });
      }
      return nodes;
    }
    function wrapTree(root0) {
      var root1 = {
        A: null,
        children: [ root0 ]
      }, queue = [ root1 ], node1;
      while ((node1 = queue.pop()) != null) {
        for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) {
          queue.push((children[i] = child = {
            _: children[i],
            parent: node1,
            children: (child = children[i].children) && child.slice() || [],
            A: null,
            a: null,
            z: 0,
            m: 0,
            c: 0,
            s: 0,
            t: null,
            i: i
          }).a = child);
        }
      }
      return root1.children[0];
    }
    function firstWalk(v) {
      var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null;
      if (children.length) {
        d3_layout_treeShift(v);
        var midpoint = (children[0].z + children[children.length - 1].z) / 2;
        if (w) {
          v.z = w.z + separation(v._, w._);
          v.m = v.z - midpoint;
        } else {
          v.z = midpoint;
        }
      } else if (w) {
        v.z = w.z + separation(v._, w._);
      }
      v.parent.A = apportion(v, w, v.parent.A || siblings[0]);
    }
    function secondWalk(v) {
      v._.x = v.z + v.parent.m;
      v.m += v.parent.m;
    }
    function apportion(v, w, ancestor) {
      if (w) {
        var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift;
        while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) {
          vom = d3_layout_treeLeft(vom);
          vop = d3_layout_treeRight(vop);
          vop.a = v;
          shift = vim.z + sim - vip.z - sip + separation(vim._, vip._);
          if (shift > 0) {
            d3_layout_treeMove(d3_layout_treeAncestor(vim, v, ancestor), v, shift);
            sip += shift;
            sop += shift;
          }
          sim += vim.m;
          sip += vip.m;
          som += vom.m;
          sop += vop.m;
        }
        if (vim && !d3_layout_treeRight(vop)) {
          vop.t = vim;
          vop.m += sim - sop;
        }
        if (vip && !d3_layout_treeLeft(vom)) {
          vom.t = vip;
          vom.m += sip - som;
          ancestor = v;
        }
      }
      return ancestor;
    }
    function sizeNode(node) {
      node.x *= size[0];
      node.y = node.depth * size[1];
    }
    tree.separation = function(x) {
      if (!arguments.length) return separation;
      separation = x;
      return tree;
    };
    tree.size = function(x) {
      if (!arguments.length) return nodeSize ? null : size;
      nodeSize = (size = x) == null ? sizeNode : null;
      return tree;
    };
    tree.nodeSize = function(x) {
      if (!arguments.length) return nodeSize ? size : null;
      nodeSize = (size = x) == null ? null : sizeNode;
      return tree;
    };
    return d3_layout_hierarchyRebind(tree, hierarchy);
  };
  function d3_layout_treeSeparation(a, b) {
    return a.parent == b.parent ? 1 : 2;
  }
  function d3_layout_treeLeft(v) {
    var children = v.children;
    return children.length ? children[0] : v.t;
  }
  function d3_layout_treeRight(v) {
    var children = v.children, n;
    return (n = children.length) ? children[n - 1] : v.t;
  }
  function d3_layout_treeMove(wm, wp, shift) {
    var change = shift / (wp.i - wm.i);
    wp.c -= change;
    wp.s += shift;
    wm.c += change;
    wp.z += shift;
    wp.m += shift;
  }
  function d3_layout_treeShift(v) {
    var shift = 0, change = 0, children = v.children, i = children.length, w;
    while (--i >= 0) {
      w = children[i];
      w.z += shift;
      w.m += shift;
      shift += w.s + (change += w.c);
    }
  }
  function d3_layout_treeAncestor(vim, v, ancestor) {
    return vim.a.parent === v.parent ? vim.a : ancestor;
  }
  d3.layout.cluster = function() {
    var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false;
    function cluster(d, i) {
      var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0;
      d3_layout_hierarchyVisitAfter(root, function(node) {
        var children = node.children;
        if (children && children.length) {
          node.x = d3_layout_clusterX(children);
          node.y = d3_layout_clusterY(children);
        } else {
          node.x = previousNode ? x += separation(node, previousNode) : 0;
          node.y = 0;
          previousNode = node;
        }
      });
      var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2;
      d3_layout_hierarchyVisitAfter(root, nodeSize ? function(node) {
        node.x = (node.x - root.x) * size[0];
        node.y = (root.y - node.y) * size[1];
      } : function(node) {
        node.x = (node.x - x0) / (x1 - x0) * size[0];
        node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1];
      });
      return nodes;
    }
    cluster.separation = function(x) {
      if (!arguments.length) return separation;
      separation = x;
      return cluster;
    };
    cluster.size = function(x) {
      if (!arguments.length) return nodeSize ? null : size;
      nodeSize = (size = x) == null;
      return cluster;
    };
    cluster.nodeSize = function(x) {
      if (!arguments.length) return nodeSize ? size : null;
      nodeSize = (size = x) != null;
      return cluster;
    };
    return d3_layout_hierarchyRebind(cluster, hierarchy);
  };
  function d3_layout_clusterY(children) {
    return 1 + d3.max(children, function(child) {
      return child.y;
    });
  }
  function d3_layout_clusterX(children) {
    return children.reduce(function(x, child) {
      return x + child.x;
    }, 0) / children.length;
  }
  function d3_layout_clusterLeft(node) {
    var children = node.children;
    return children && children.length ? d3_layout_clusterLeft(children[0]) : node;
  }
  function d3_layout_clusterRight(node) {
    var children = node.children, n;
    return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node;
  }
  d3.layout.treemap = function() {
    var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [ 1, 1 ], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = .5 * (1 + Math.sqrt(5));
    function scale(children, k) {
      var i = -1, n = children.length, child, area;
      while (++i < n) {
        area = (child = children[i]).value * (k < 0 ? 0 : k);
        child.area = isNaN(area) || area <= 0 ? 0 : area;
      }
    }
    function squarify(node) {
      var children = node.children;
      if (children && children.length) {
        var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = mode === "slice" ? rect.dx : mode === "dice" ? rect.dy : mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx : Math.min(rect.dx, rect.dy), n;
        scale(remaining, rect.dx * rect.dy / node.value);
        row.area = 0;
        while ((n = remaining.length) > 0) {
          row.push(child = remaining[n - 1]);
          row.area += child.area;
          if (mode !== "squarify" || (score = worst(row, u)) <= best) {
            remaining.pop();
            best = score;
          } else {
            row.area -= row.pop().area;
            position(row, u, rect, false);
            u = Math.min(rect.dx, rect.dy);
            row.length = row.area = 0;
            best = Infinity;
          }
        }
        if (row.length) {
          position(row, u, rect, true);
          row.length = row.area = 0;
        }
        children.forEach(squarify);
      }
    }
    function stickify(node) {
      var children = node.children;
      if (children && children.length) {
        var rect = pad(node), remaining = children.slice(), child, row = [];
        scale(remaining, rect.dx * rect.dy / node.value);
        row.area = 0;
        while (child = remaining.pop()) {
          row.push(child);
          row.area += child.area;
          if (child.z != null) {
            position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length);
            row.length = row.area = 0;
          }
        }
        children.forEach(stickify);
      }
    }
    function worst(row, u) {
      var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length;
      while (++i < n) {
        if (!(r = row[i].area)) continue;
        if (r < rmin) rmin = r;
        if (r > rmax) rmax = r;
      }
      s *= s;
      u *= u;
      return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity;
    }
    function position(row, u, rect, flush) {
      var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o;
      if (u == rect.dx) {
        if (flush || v > rect.dy) v = rect.dy;
        while (++i < n) {
          o = row[i];
          o.x = x;
          o.y = y;
          o.dy = v;
          x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0);
        }
        o.z = true;
        o.dx += rect.x + rect.dx - x;
        rect.y += v;
        rect.dy -= v;
      } else {
        if (flush || v > rect.dx) v = rect.dx;
        while (++i < n) {
          o = row[i];
          o.x = x;
          o.y = y;
          o.dx = v;
          y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0);
        }
        o.z = false;
        o.dy += rect.y + rect.dy - y;
        rect.x += v;
        rect.dx -= v;
      }
    }
    function treemap(d) {
      var nodes = stickies || hierarchy(d), root = nodes[0];
      root.x = root.y = 0;
      if (root.value) root.dx = size[0], root.dy = size[1]; else root.dx = root.dy = 0;
      if (stickies) hierarchy.revalue(root);
      scale([ root ], root.dx * root.dy / root.value);
      (stickies ? stickify : squarify)(root);
      if (sticky) stickies = nodes;
      return nodes;
    }
    treemap.size = function(x) {
      if (!arguments.length) return size;
      size = x;
      return treemap;
    };
    treemap.padding = function(x) {
      if (!arguments.length) return padding;
      function padFunction(node) {
        var p = x.call(treemap, node, node.depth);
        return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p);
      }
      function padConstant(node) {
        return d3_layout_treemapPad(node, x);
      }
      var type;
      pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ], 
      padConstant) : padConstant;
      return treemap;
    };
    treemap.round = function(x) {
      if (!arguments.length) return round != Number;
      round = x ? Math.round : Number;
      return treemap;
    };
    treemap.sticky = function(x) {
      if (!arguments.length) return sticky;
      sticky = x;
      stickies = null;
      return treemap;
    };
    treemap.ratio = function(x) {
      if (!arguments.length) return ratio;
      ratio = x;
      return treemap;
    };
    treemap.mode = function(x) {
      if (!arguments.length) return mode;
      mode = x + "";
      return treemap;
    };
    return d3_layout_hierarchyRebind(treemap, hierarchy);
  };
  function d3_layout_treemapPadNull(node) {
    return {
      x: node.x,
      y: node.y,
      dx: node.dx,
      dy: node.dy
    };
  }
  function d3_layout_treemapPad(node, padding) {
    var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2];
    if (dx < 0) {
      x += dx / 2;
      dx = 0;
    }
    if (dy < 0) {
      y += dy / 2;
      dy = 0;
    }
    return {
      x: x,
      y: y,
      dx: dx,
      dy: dy
    };
  }
  d3.random = {
    normal: function(µ, σ) {
      var n = arguments.length;
      if (n < 2) σ = 1;
      if (n < 1) µ = 0;
      return function() {
        var x, y, r;
        do {
          x = Math.random() * 2 - 1;
          y = Math.random() * 2 - 1;
          r = x * x + y * y;
        } while (!r || r > 1);
        return µ + σ * x * Math.sqrt(-2 * Math.log(r) / r);
      };
    },
    logNormal: function() {
      var random = d3.random.normal.apply(d3, arguments);
      return function() {
        return Math.exp(random());
      };
    },
    bates: function(m) {
      var random = d3.random.irwinHall(m);
      return function() {
        return random() / m;
      };
    },
    irwinHall: function(m) {
      return function() {
        for (var s = 0, j = 0; j < m; j++) s += Math.random();
        return s;
      };
    }
  };
  d3.scale = {};
  function d3_scaleExtent(domain) {
    var start = domain[0], stop = domain[domain.length - 1];
    return start < stop ? [ start, stop ] : [ stop, start ];
  }
  function d3_scaleRange(scale) {
    return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range());
  }
  function d3_scale_bilinear(domain, range, uninterpolate, interpolate) {
    var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]);
    return function(x) {
      return i(u(x));
    };
  }
  function d3_scale_nice(domain, nice) {
    var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx;
    if (x1 < x0) {
      dx = i0, i0 = i1, i1 = dx;
      dx = x0, x0 = x1, x1 = dx;
    }
    domain[i0] = nice.floor(x0);
    domain[i1] = nice.ceil(x1);
    return domain;
  }
  function d3_scale_niceStep(step) {
    return step ? {
      floor: function(x) {
        return Math.floor(x / step) * step;
      },
      ceil: function(x) {
        return Math.ceil(x / step) * step;
      }
    } : d3_scale_niceIdentity;
  }
  var d3_scale_niceIdentity = {
    floor: d3_identity,
    ceil: d3_identity
  };
  function d3_scale_polylinear(domain, range, uninterpolate, interpolate) {
    var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1;
    if (domain[k] < domain[0]) {
      domain = domain.slice().reverse();
      range = range.slice().reverse();
    }
    while (++j <= k) {
      u.push(uninterpolate(domain[j - 1], domain[j]));
      i.push(interpolate(range[j - 1], range[j]));
    }
    return function(x) {
      var j = d3.bisect(domain, x, 1, k) - 1;
      return i[j](u[j](x));
    };
  }
  d3.scale.linear = function() {
    return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3_interpolate, false);
  };
  function d3_scale_linear(domain, range, interpolate, clamp) {
    var output, input;
    function rescale() {
      var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber;
      output = linear(domain, range, uninterpolate, interpolate);
      input = linear(range, domain, uninterpolate, d3_interpolate);
      return scale;
    }
    function scale(x) {
      return output(x);
    }
    scale.invert = function(y) {
      return input(y);
    };
    scale.domain = function(x) {
      if (!arguments.length) return domain;
      domain = x.map(Number);
      return rescale();
    };
    scale.range = function(x) {
      if (!arguments.length) return range;
      range = x;
      return rescale();
    };
    scale.rangeRound = function(x) {
      return scale.range(x).interpolate(d3_interpolateRound);
    };
    scale.clamp = function(x) {
      if (!arguments.length) return clamp;
      clamp = x;
      return rescale();
    };
    scale.interpolate = function(x) {
      if (!arguments.length) return interpolate;
      interpolate = x;
      return rescale();
    };
    scale.ticks = function(m) {
      return d3_scale_linearTicks(domain, m);
    };
    scale.tickFormat = function(m, format) {
      return d3_scale_linearTickFormat(domain, m, format);
    };
    scale.nice = function(m) {
      d3_scale_linearNice(domain, m);
      return rescale();
    };
    scale.copy = function() {
      return d3_scale_linear(domain, range, interpolate, clamp);
    };
    return rescale();
  }
  function d3_scale_linearRebind(scale, linear) {
    return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp");
  }
  function d3_scale_linearNice(domain, m) {
    d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2]));
    d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2]));
    return domain;
  }
  function d3_scale_linearTickRange(domain, m) {
    if (m == null) m = 10;
    var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step;
    if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2;
    extent[0] = Math.ceil(extent[0] / step) * step;
    extent[1] = Math.floor(extent[1] / step) * step + step * .5;
    extent[2] = step;
    return extent;
  }
  function d3_scale_linearTicks(domain, m) {
    return d3.range.apply(d3, d3_scale_linearTickRange(domain, m));
  }
  function d3_scale_linearTickFormat(domain, m, format) {
    var range = d3_scale_linearTickRange(domain, m);
    if (format) {
      var match = d3_format_re.exec(format);
      match.shift();
      if (match[8] === "s") {
        var prefix = d3.formatPrefix(Math.max(abs(range[0]), abs(range[1])));
        if (!match[7]) match[7] = "." + d3_scale_linearPrecision(prefix.scale(range[2]));
        match[8] = "f";
        format = d3.format(match.join(""));
        return function(d) {
          return format(prefix.scale(d)) + prefix.symbol;
        };
      }
      if (!match[7]) match[7] = "." + d3_scale_linearFormatPrecision(match[8], range);
      format = match.join("");
    } else {
      format = ",." + d3_scale_linearPrecision(range[2]) + "f";
    }
    return d3.format(format);
  }
  var d3_scale_linearFormatSignificant = {
    s: 1,
    g: 1,
    p: 1,
    r: 1,
    e: 1
  };
  function d3_scale_linearPrecision(value) {
    return -Math.floor(Math.log(value) / Math.LN10 + .01);
  }
  function d3_scale_linearFormatPrecision(type, range) {
    var p = d3_scale_linearPrecision(range[2]);
    return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(abs(range[0]), abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2;
  }
  d3.scale.log = function() {
    return d3_scale_log(d3.scale.linear().domain([ 0, 1 ]), 10, true, [ 1, 10 ]);
  };
  function d3_scale_log(linear, base, positive, domain) {
    function log(x) {
      return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base);
    }
    function pow(x) {
      return positive ? Math.pow(base, x) : -Math.pow(base, -x);
    }
    function scale(x) {
      return linear(log(x));
    }
    scale.invert = function(x) {
      return pow(linear.invert(x));
    };
    scale.domain = function(x) {
      if (!arguments.length) return domain;
      positive = x[0] >= 0;
      linear.domain((domain = x.map(Number)).map(log));
      return scale;
    };
    scale.base = function(_) {
      if (!arguments.length) return base;
      base = +_;
      linear.domain(domain.map(log));
      return scale;
    };
    scale.nice = function() {
      var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative);
      linear.domain(niced);
      domain = niced.map(pow);
      return scale;
    };
    scale.ticks = function() {
      var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base;
      if (isFinite(j - i)) {
        if (positive) {
          for (;i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k);
          ticks.push(pow(i));
        } else {
          ticks.push(pow(i));
          for (;i++ < j; ) for (var k = n - 1; k > 0; k--) ticks.push(pow(i) * k);
        }
        for (i = 0; ticks[i] < u; i++) {}
        for (j = ticks.length; ticks[j - 1] > v; j--) {}
        ticks = ticks.slice(i, j);
      }
      return ticks;
    };
    scale.tickFormat = function(n, format) {
      if (!arguments.length) return d3_scale_logFormat;
      if (arguments.length < 2) format = d3_scale_logFormat; else if (typeof format !== "function") format = d3.format(format);
      var k = Math.max(1, base * n / scale.ticks().length);
      return function(d) {
        var i = d / pow(Math.round(log(d)));
        if (i * base < base - .5) i *= base;
        return i <= k ? format(d) : "";
      };
    };
    scale.copy = function() {
      return d3_scale_log(linear.copy(), base, positive, domain);
    };
    return d3_scale_linearRebind(scale, linear);
  }
  var d3_scale_logFormat = d3.format(".0e"), d3_scale_logNiceNegative = {
    floor: function(x) {
      return -Math.ceil(-x);
    },
    ceil: function(x) {
      return -Math.floor(-x);
    }
  };
  d3.scale.pow = function() {
    return d3_scale_pow(d3.scale.linear(), 1, [ 0, 1 ]);
  };
  function d3_scale_pow(linear, exponent, domain) {
    var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent);
    function scale(x) {
      return linear(powp(x));
    }
    scale.invert = function(x) {
      return powb(linear.invert(x));
    };
    scale.domain = function(x) {
      if (!arguments.length) return domain;
      linear.domain((domain = x.map(Number)).map(powp));
      return scale;
    };
    scale.ticks = function(m) {
      return d3_scale_linearTicks(domain, m);
    };
    scale.tickFormat = function(m, format) {
      return d3_scale_linearTickFormat(domain, m, format);
    };
    scale.nice = function(m) {
      return scale.domain(d3_scale_linearNice(domain, m));
    };
    scale.exponent = function(x) {
      if (!arguments.length) return exponent;
      powp = d3_scale_powPow(exponent = x);
      powb = d3_scale_powPow(1 / exponent);
      linear.domain(domain.map(powp));
      return scale;
    };
    scale.copy = function() {
      return d3_scale_pow(linear.copy(), exponent, domain);
    };
    return d3_scale_linearRebind(scale, linear);
  }
  function d3_scale_powPow(e) {
    return function(x) {
      return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e);
    };
  }
  d3.scale.sqrt = function() {
    return d3.scale.pow().exponent(.5);
  };
  d3.scale.ordinal = function() {
    return d3_scale_ordinal([], {
      t: "range",
      a: [ [] ]
    });
  };
  function d3_scale_ordinal(domain, ranger) {
    var index, range, rangeBand;
    function scale(x) {
      return range[((index.get(x) || (ranger.t === "range" ? index.set(x, domain.push(x)) : NaN)) - 1) % range.length];
    }
    function steps(start, step) {
      return d3.range(domain.length).map(function(i) {
        return start + step * i;
      });
    }
    scale.domain = function(x) {
      if (!arguments.length) return domain;
      domain = [];
      index = new d3_Map();
      var i = -1, n = x.length, xi;
      while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi));
      return scale[ranger.t].apply(scale, ranger.a);
    };
    scale.range = function(x) {
      if (!arguments.length) return range;
      range = x;
      rangeBand = 0;
      ranger = {
        t: "range",
        a: arguments
      };
      return scale;
    };
    scale.rangePoints = function(x, padding) {
      if (arguments.length < 2) padding = 0;
      var start = x[0], stop = x[1], step = domain.length < 2 ? (start = (start + stop) / 2, 
      0) : (stop - start) / (domain.length - 1 + padding);
      range = steps(start + step * padding / 2, step);
      rangeBand = 0;
      ranger = {
        t: "rangePoints",
        a: arguments
      };
      return scale;
    };
    scale.rangeRoundPoints = function(x, padding) {
      if (arguments.length < 2) padding = 0;
      var start = x[0], stop = x[1], step = domain.length < 2 ? (start = stop = Math.round((start + stop) / 2), 
      0) : (stop - start) / (domain.length - 1 + padding) | 0;
      range = steps(start + Math.round(step * padding / 2 + (stop - start - (domain.length - 1 + padding) * step) / 2), step);
      rangeBand = 0;
      ranger = {
        t: "rangeRoundPoints",
        a: arguments
      };
      return scale;
    };
    scale.rangeBands = function(x, padding, outerPadding) {
      if (arguments.length < 2) padding = 0;
      if (arguments.length < 3) outerPadding = padding;
      var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding);
      range = steps(start + step * outerPadding, step);
      if (reverse) range.reverse();
      rangeBand = step * (1 - padding);
      ranger = {
        t: "rangeBands",
        a: arguments
      };
      return scale;
    };
    scale.rangeRoundBands = function(x, padding, outerPadding) {
      if (arguments.length < 2) padding = 0;
      if (arguments.length < 3) outerPadding = padding;
      var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding));
      range = steps(start + Math.round((stop - start - (domain.length - padding) * step) / 2), step);
      if (reverse) range.reverse();
      rangeBand = Math.round(step * (1 - padding));
      ranger = {
        t: "rangeRoundBands",
        a: arguments
      };
      return scale;
    };
    scale.rangeBand = function() {
      return rangeBand;
    };
    scale.rangeExtent = function() {
      return d3_scaleExtent(ranger.a[0]);
    };
    scale.copy = function() {
      return d3_scale_ordinal(domain, ranger);
    };
    return scale.domain(domain);
  }
  d3.scale.category10 = function() {
    return d3.scale.ordinal().range(d3_category10);
  };
  d3.scale.category20 = function() {
    return d3.scale.ordinal().range(d3_category20);
  };
  d3.scale.category20b = function() {
    return d3.scale.ordinal().range(d3_category20b);
  };
  d3.scale.category20c = function() {
    return d3.scale.ordinal().range(d3_category20c);
  };
  var d3_category10 = [ 2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175 ].map(d3_rgbString);
  var d3_category20 = [ 2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725 ].map(d3_rgbString);
  var d3_category20b = [ 3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654 ].map(d3_rgbString);
  var d3_category20c = [ 3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081 ].map(d3_rgbString);
  d3.scale.quantile = function() {
    return d3_scale_quantile([], []);
  };
  function d3_scale_quantile(domain, range) {
    var thresholds;
    function rescale() {
      var k = 0, q = range.length;
      thresholds = [];
      while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q);
      return scale;
    }
    function scale(x) {
      if (!isNaN(x = +x)) return range[d3.bisect(thresholds, x)];
    }
    scale.domain = function(x) {
      if (!arguments.length) return domain;
      domain = x.map(d3_number).filter(d3_numeric).sort(d3_ascending);
      return rescale();
    };
    scale.range = function(x) {
      if (!arguments.length) return range;
      range = x;
      return rescale();
    };
    scale.quantiles = function() {
      return thresholds;
    };
    scale.invertExtent = function(y) {
      y = range.indexOf(y);
      return y < 0 ? [ NaN, NaN ] : [ y > 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1] ];
    };
    scale.copy = function() {
      return d3_scale_quantile(domain, range);
    };
    return rescale();
  }
  d3.scale.quantize = function() {
    return d3_scale_quantize(0, 1, [ 0, 1 ]);
  };
  function d3_scale_quantize(x0, x1, range) {
    var kx, i;
    function scale(x) {
      return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))];
    }
    function rescale() {
      kx = range.length / (x1 - x0);
      i = range.length - 1;
      return scale;
    }
    scale.domain = function(x) {
      if (!arguments.length) return [ x0, x1 ];
      x0 = +x[0];
      x1 = +x[x.length - 1];
      return rescale();
    };
    scale.range = function(x) {
      if (!arguments.length) return range;
      range = x;
      return rescale();
    };
    scale.invertExtent = function(y) {
      y = range.indexOf(y);
      y = y < 0 ? NaN : y / kx + x0;
      return [ y, y + 1 / kx ];
    };
    scale.copy = function() {
      return d3_scale_quantize(x0, x1, range);
    };
    return rescale();
  }
  d3.scale.threshold = function() {
    return d3_scale_threshold([ .5 ], [ 0, 1 ]);
  };
  function d3_scale_threshold(domain, range) {
    function scale(x) {
      if (x <= x) return range[d3.bisect(domain, x)];
    }
    scale.domain = function(_) {
      if (!arguments.length) return domain;
      domain = _;
      return scale;
    };
    scale.range = function(_) {
      if (!arguments.length) return range;
      range = _;
      return scale;
    };
    scale.invertExtent = function(y) {
      y = range.indexOf(y);
      return [ domain[y - 1], domain[y] ];
    };
    scale.copy = function() {
      return d3_scale_threshold(domain, range);
    };
    return scale;
  }
  d3.scale.identity = function() {
    return d3_scale_identity([ 0, 1 ]);
  };
  function d3_scale_identity(domain) {
    function identity(x) {
      return +x;
    }
    identity.invert = identity;
    identity.domain = identity.range = function(x) {
      if (!arguments.length) return domain;
      domain = x.map(identity);
      return identity;
    };
    identity.ticks = function(m) {
      return d3_scale_linearTicks(domain, m);
    };
    identity.tickFormat = function(m, format) {
      return d3_scale_linearTickFormat(domain, m, format);
    };
    identity.copy = function() {
      return d3_scale_identity(domain);
    };
    return identity;
  }
  d3.svg = {};
  function d3_zero() {
    return 0;
  }
  d3.svg.arc = function() {
    var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, cornerRadius = d3_zero, padRadius = d3_svg_arcAuto, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle, padAngle = d3_svg_arcPadAngle;
    function arc() {
      var r0 = Math.max(0, +innerRadius.apply(this, arguments)), r1 = Math.max(0, +outerRadius.apply(this, arguments)), a0 = startAngle.apply(this, arguments) - halfπ, a1 = endAngle.apply(this, arguments) - halfπ, da = Math.abs(a1 - a0), cw = a0 > a1 ? 0 : 1;
      if (r1 < r0) rc = r1, r1 = r0, r0 = rc;
      if (da >= τε) return circleSegment(r1, cw) + (r0 ? circleSegment(r0, 1 - cw) : "") + "Z";
      var rc, cr, rp, ap, p0 = 0, p1 = 0, x0, y0, x1, y1, x2, y2, x3, y3, path = [];
      if (ap = (+padAngle.apply(this, arguments) || 0) / 2) {
        rp = padRadius === d3_svg_arcAuto ? Math.sqrt(r0 * r0 + r1 * r1) : +padRadius.apply(this, arguments);
        if (!cw) p1 *= -1;
        if (r1) p1 = d3_asin(rp / r1 * Math.sin(ap));
        if (r0) p0 = d3_asin(rp / r0 * Math.sin(ap));
      }
      if (r1) {
        x0 = r1 * Math.cos(a0 + p1);
        y0 = r1 * Math.sin(a0 + p1);
        x1 = r1 * Math.cos(a1 - p1);
        y1 = r1 * Math.sin(a1 - p1);
        var l1 = Math.abs(a1 - a0 - 2 * p1) <= π ? 0 : 1;
        if (p1 && d3_svg_arcSweep(x0, y0, x1, y1) === cw ^ l1) {
          var h1 = (a0 + a1) / 2;
          x0 = r1 * Math.cos(h1);
          y0 = r1 * Math.sin(h1);
          x1 = y1 = null;
        }
      } else {
        x0 = y0 = 0;
      }
      if (r0) {
        x2 = r0 * Math.cos(a1 - p0);
        y2 = r0 * Math.sin(a1 - p0);
        x3 = r0 * Math.cos(a0 + p0);
        y3 = r0 * Math.sin(a0 + p0);
        var l0 = Math.abs(a0 - a1 + 2 * p0) <= π ? 0 : 1;
        if (p0 && d3_svg_arcSweep(x2, y2, x3, y3) === 1 - cw ^ l0) {
          var h0 = (a0 + a1) / 2;
          x2 = r0 * Math.cos(h0);
          y2 = r0 * Math.sin(h0);
          x3 = y3 = null;
        }
      } else {
        x2 = y2 = 0;
      }
      if (da > ε && (rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > .001) {
        cr = r0 < r1 ^ cw ? 0 : 1;
        var rc1 = rc, rc0 = rc;
        if (da < π) {
          var oc = x3 == null ? [ x2, y2 ] : x1 == null ? [ x0, y0 ] : d3_geom_polygonIntersect([ x0, y0 ], [ x3, y3 ], [ x1, y1 ], [ x2, y2 ]), ax = x0 - oc[0], ay = y0 - oc[1], bx = x1 - oc[0], by = y1 - oc[1], kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2), lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]);
          rc0 = Math.min(rc, (r0 - lc) / (kc - 1));
          rc1 = Math.min(rc, (r1 - lc) / (kc + 1));
        }
        if (x1 != null) {
          var t30 = d3_svg_arcCornerTangents(x3 == null ? [ x2, y2 ] : [ x3, y3 ], [ x0, y0 ], r1, rc1, cw), t12 = d3_svg_arcCornerTangents([ x1, y1 ], [ x2, y2 ], r1, rc1, cw);
          if (rc === rc1) {
            path.push("M", t30[0], "A", rc1, ",", rc1, " 0 0,", cr, " ", t30[1], "A", r1, ",", r1, " 0 ", 1 - cw ^ d3_svg_arcSweep(t30[1][0], t30[1][1], t12[1][0], t12[1][1]), ",", cw, " ", t12[1], "A", rc1, ",", rc1, " 0 0,", cr, " ", t12[0]);
          } else {
            path.push("M", t30[0], "A", rc1, ",", rc1, " 0 1,", cr, " ", t12[0]);
          }
        } else {
          path.push("M", x0, ",", y0);
        }
        if (x3 != null) {
          var t03 = d3_svg_arcCornerTangents([ x0, y0 ], [ x3, y3 ], r0, -rc0, cw), t21 = d3_svg_arcCornerTangents([ x2, y2 ], x1 == null ? [ x0, y0 ] : [ x1, y1 ], r0, -rc0, cw);
          if (rc === rc0) {
            path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t21[1], "A", r0, ",", r0, " 0 ", cw ^ d3_svg_arcSweep(t21[1][0], t21[1][1], t03[1][0], t03[1][1]), ",", 1 - cw, " ", t03[1], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]);
          } else {
            path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]);
          }
        } else {
          path.push("L", x2, ",", y2);
        }
      } else {
        path.push("M", x0, ",", y0);
        if (x1 != null) path.push("A", r1, ",", r1, " 0 ", l1, ",", cw, " ", x1, ",", y1);
        path.push("L", x2, ",", y2);
        if (x3 != null) path.push("A", r0, ",", r0, " 0 ", l0, ",", 1 - cw, " ", x3, ",", y3);
      }
      path.push("Z");
      return path.join("");
    }
    function circleSegment(r1, cw) {
      return "M0," + r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + -r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + r1;
    }
    arc.innerRadius = function(v) {
      if (!arguments.length) return innerRadius;
      innerRadius = d3_functor(v);
      return arc;
    };
    arc.outerRadius = function(v) {
      if (!arguments.length) return outerRadius;
      outerRadius = d3_functor(v);
      return arc;
    };
    arc.cornerRadius = function(v) {
      if (!arguments.length) return cornerRadius;
      cornerRadius = d3_functor(v);
      return arc;
    };
    arc.padRadius = function(v) {
      if (!arguments.length) return padRadius;
      padRadius = v == d3_svg_arcAuto ? d3_svg_arcAuto : d3_functor(v);
      return arc;
    };
    arc.startAngle = function(v) {
      if (!arguments.length) return startAngle;
      startAngle = d3_functor(v);
      return arc;
    };
    arc.endAngle = function(v) {
      if (!arguments.length) return endAngle;
      endAngle = d3_functor(v);
      return arc;
    };
    arc.padAngle = function(v) {
      if (!arguments.length) return padAngle;
      padAngle = d3_functor(v);
      return arc;
    };
    arc.centroid = function() {
      var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - halfπ;
      return [ Math.cos(a) * r, Math.sin(a) * r ];
    };
    return arc;
  };
  var d3_svg_arcAuto = "auto";
  function d3_svg_arcInnerRadius(d) {
    return d.innerRadius;
  }
  function d3_svg_arcOuterRadius(d) {
    return d.outerRadius;
  }
  function d3_svg_arcStartAngle(d) {
    return d.startAngle;
  }
  function d3_svg_arcEndAngle(d) {
    return d.endAngle;
  }
  function d3_svg_arcPadAngle(d) {
    return d && d.padAngle;
  }
  function d3_svg_arcSweep(x0, y0, x1, y1) {
    return (x0 - x1) * y0 - (y0 - y1) * x0 > 0 ? 0 : 1;
  }
  function d3_svg_arcCornerTangents(p0, p1, r1, rc, cw) {
    var x01 = p0[0] - p1[0], y01 = p0[1] - p1[1], lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x1 = p0[0] + ox, y1 = p0[1] + oy, x2 = p1[0] + ox, y2 = p1[1] + oy, x3 = (x1 + x2) / 2, y3 = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, d2 = dx * dx + dy * dy, r = r1 - rc, D = x1 * y2 - x2 * y1, d = (dy < 0 ? -1 : 1) * Math.sqrt(Math.max(0, r * r * d2 - D * D)), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x3, dy0 = cy0 - y3, dx1 = cx1 - x3, dy1 = cy1 - y3;
    if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1;
    return [ [ cx0 - ox, cy0 - oy ], [ cx0 * r1 / r, cy0 * r1 / r ] ];
  }
  function d3_svg_line(projection) {
    var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7;
    function line(data) {
      var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y);
      function segment() {
        segments.push("M", interpolate(projection(points), tension));
      }
      while (++i < n) {
        if (defined.call(this, d = data[i], i)) {
          points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]);
        } else if (points.length) {
          segment();
          points = [];
        }
      }
      if (points.length) segment();
      return segments.length ? segments.join("") : null;
    }
    line.x = function(_) {
      if (!arguments.length) return x;
      x = _;
      return line;
    };
    line.y = function(_) {
      if (!arguments.length) return y;
      y = _;
      return line;
    };
    line.defined = function(_) {
      if (!arguments.length) return defined;
      defined = _;
      return line;
    };
    line.interpolate = function(_) {
      if (!arguments.length) return interpolateKey;
      if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key;
      return line;
    };
    line.tension = function(_) {
      if (!arguments.length) return tension;
      tension = _;
      return line;
    };
    return line;
  }
  d3.svg.line = function() {
    return d3_svg_line(d3_identity);
  };
  var d3_svg_lineInterpolators = d3.map({
    linear: d3_svg_lineLinear,
    "linear-closed": d3_svg_lineLinearClosed,
    step: d3_svg_lineStep,
    "step-before": d3_svg_lineStepBefore,
    "step-after": d3_svg_lineStepAfter,
    basis: d3_svg_lineBasis,
    "basis-open": d3_svg_lineBasisOpen,
    "basis-closed": d3_svg_lineBasisClosed,
    bundle: d3_svg_lineBundle,
    cardinal: d3_svg_lineCardinal,
    "cardinal-open": d3_svg_lineCardinalOpen,
    "cardinal-closed": d3_svg_lineCardinalClosed,
    monotone: d3_svg_lineMonotone
  });
  d3_svg_lineInterpolators.forEach(function(key, value) {
    value.key = key;
    value.closed = /-closed$/.test(key);
  });
  function d3_svg_lineLinear(points) {
    return points.length > 1 ? points.join("L") : points + "Z";
  }
  function d3_svg_lineLinearClosed(points) {
    return points.join("L") + "Z";
  }
  function d3_svg_lineStep(points) {
    var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
    while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]);
    if (n > 1) path.push("H", p[0]);
    return path.join("");
  }
  function d3_svg_lineStepBefore(points) {
    var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
    while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]);
    return path.join("");
  }
  function d3_svg_lineStepAfter(points) {
    var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
    while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]);
    return path.join("");
  }
  function d3_svg_lineCardinalOpen(points, tension) {
    return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, -1), d3_svg_lineCardinalTangents(points, tension));
  }
  function d3_svg_lineCardinalClosed(points, tension) {
    return points.length < 3 ? d3_svg_lineLinearClosed(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), 
    points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension));
  }
  function d3_svg_lineCardinal(points, tension) {
    return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension));
  }
  function d3_svg_lineHermite(points, tangents) {
    if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) {
      return d3_svg_lineLinear(points);
    }
    var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1;
    if (quad) {
      path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1];
      p0 = points[1];
      pi = 2;
    }
    if (tangents.length > 1) {
      t = tangents[1];
      p = points[pi];
      pi++;
      path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
      for (var i = 2; i < tangents.length; i++, pi++) {
        p = points[pi];
        t = tangents[i];
        path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
      }
    }
    if (quad) {
      var lp = points[pi];
      path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1];
    }
    return path;
  }
  function d3_svg_lineCardinalTangents(points, tension) {
    var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length;
    while (++i < n) {
      p0 = p1;
      p1 = p2;
      p2 = points[i];
      tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]);
    }
    return tangents;
  }
  function d3_svg_lineBasis(points) {
    if (points.length < 3) return d3_svg_lineLinear(points);
    var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ];
    points.push(points[n - 1]);
    while (++i <= n) {
      pi = points[i];
      px.shift();
      px.push(pi[0]);
      py.shift();
      py.push(pi[1]);
      d3_svg_lineBasisBezier(path, px, py);
    }
    points.pop();
    path.push("L", pi);
    return path.join("");
  }
  function d3_svg_lineBasisOpen(points) {
    if (points.length < 4) return d3_svg_lineLinear(points);
    var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ];
    while (++i < 3) {
      pi = points[i];
      px.push(pi[0]);
      py.push(pi[1]);
    }
    path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py));
    --i;
    while (++i < n) {
      pi = points[i];
      px.shift();
      px.push(pi[0]);
      py.shift();
      py.push(pi[1]);
      d3_svg_lineBasisBezier(path, px, py);
    }
    return path.join("");
  }
  function d3_svg_lineBasisClosed(points) {
    var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = [];
    while (++i < 4) {
      pi = points[i % n];
      px.push(pi[0]);
      py.push(pi[1]);
    }
    path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ];
    --i;
    while (++i < m) {
      pi = points[i % n];
      px.shift();
      px.push(pi[0]);
      py.shift();
      py.push(pi[1]);
      d3_svg_lineBasisBezier(path, px, py);
    }
    return path.join("");
  }
  function d3_svg_lineBundle(points, tension) {
    var n = points.length - 1;
    if (n) {
      var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t;
      while (++i <= n) {
        p = points[i];
        t = i / n;
        p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx);
        p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy);
      }
    }
    return d3_svg_lineBasis(points);
  }
  function d3_svg_lineDot4(a, b) {
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
  }
  var d3_svg_lineBasisBezier1 = [ 0, 2 / 3, 1 / 3, 0 ], d3_svg_lineBasisBezier2 = [ 0, 1 / 3, 2 / 3, 0 ], d3_svg_lineBasisBezier3 = [ 0, 1 / 6, 2 / 3, 1 / 6 ];
  function d3_svg_lineBasisBezier(path, x, y) {
    path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y));
  }
  function d3_svg_lineSlope(p0, p1) {
    return (p1[1] - p0[1]) / (p1[0] - p0[0]);
  }
  function d3_svg_lineFiniteDifferences(points) {
    var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1);
    while (++i < j) {
      m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2;
    }
    m[i] = d;
    return m;
  }
  function d3_svg_lineMonotoneTangents(points) {
    var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1;
    while (++i < j) {
      d = d3_svg_lineSlope(points[i], points[i + 1]);
      if (abs(d) < ε) {
        m[i] = m[i + 1] = 0;
      } else {
        a = m[i] / d;
        b = m[i + 1] / d;
        s = a * a + b * b;
        if (s > 9) {
          s = d * 3 / Math.sqrt(s);
          m[i] = s * a;
          m[i + 1] = s * b;
        }
      }
    }
    i = -1;
    while (++i <= j) {
      s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i]));
      tangents.push([ s || 0, m[i] * s || 0 ]);
    }
    return tangents;
  }
  function d3_svg_lineMonotone(points) {
    return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points));
  }
  d3.svg.line.radial = function() {
    var line = d3_svg_line(d3_svg_lineRadial);
    line.radius = line.x, delete line.x;
    line.angle = line.y, delete line.y;
    return line;
  };
  function d3_svg_lineRadial(points) {
    var point, i = -1, n = points.length, r, a;
    while (++i < n) {
      point = points[i];
      r = point[0];
      a = point[1] - halfπ;
      point[0] = r * Math.cos(a);
      point[1] = r * Math.sin(a);
    }
    return points;
  }
  function d3_svg_area(projection) {
    var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7;
    function area(data) {
      var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() {
        return x;
      } : d3_functor(x1), fy1 = y0 === y1 ? function() {
        return y;
      } : d3_functor(y1), x, y;
      function segment() {
        segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z");
      }
      while (++i < n) {
        if (defined.call(this, d = data[i], i)) {
          points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]);
          points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]);
        } else if (points0.length) {
          segment();
          points0 = [];
          points1 = [];
        }
      }
      if (points0.length) segment();
      return segments.length ? segments.join("") : null;
    }
    area.x = function(_) {
      if (!arguments.length) return x1;
      x0 = x1 = _;
      return area;
    };
    area.x0 = function(_) {
      if (!arguments.length) return x0;
      x0 = _;
      return area;
    };
    area.x1 = function(_) {
      if (!arguments.length) return x1;
      x1 = _;
      return area;
    };
    area.y = function(_) {
      if (!arguments.length) return y1;
      y0 = y1 = _;
      return area;
    };
    area.y0 = function(_) {
      if (!arguments.length) return y0;
      y0 = _;
      return area;
    };
    area.y1 = function(_) {
      if (!arguments.length) return y1;
      y1 = _;
      return area;
    };
    area.defined = function(_) {
      if (!arguments.length) return defined;
      defined = _;
      return area;
    };
    area.interpolate = function(_) {
      if (!arguments.length) return interpolateKey;
      if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key;
      interpolateReverse = interpolate.reverse || interpolate;
      L = interpolate.closed ? "M" : "L";
      return area;
    };
    area.tension = function(_) {
      if (!arguments.length) return tension;
      tension = _;
      return area;
    };
    return area;
  }
  d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter;
  d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore;
  d3.svg.area = function() {
    return d3_svg_area(d3_identity);
  };
  d3.svg.area.radial = function() {
    var area = d3_svg_area(d3_svg_lineRadial);
    area.radius = area.x, delete area.x;
    area.innerRadius = area.x0, delete area.x0;
    area.outerRadius = area.x1, delete area.x1;
    area.angle = area.y, delete area.y;
    area.startAngle = area.y0, delete area.y0;
    area.endAngle = area.y1, delete area.y1;
    return area;
  };
  d3.svg.chord = function() {
    var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle;
    function chord(d, i) {
      var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i);
      return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z";
    }
    function subgroup(self, f, d, i) {
      var subgroup = f.call(self, d, i), r = radius.call(self, subgroup, i), a0 = startAngle.call(self, subgroup, i) - halfπ, a1 = endAngle.call(self, subgroup, i) - halfπ;
      return {
        r: r,
        a0: a0,
        a1: a1,
        p0: [ r * Math.cos(a0), r * Math.sin(a0) ],
        p1: [ r * Math.cos(a1), r * Math.sin(a1) ]
      };
    }
    function equals(a, b) {
      return a.a0 == b.a0 && a.a1 == b.a1;
    }
    function arc(r, p, a) {
      return "A" + r + "," + r + " 0 " + +(a > π) + ",1 " + p;
    }
    function curve(r0, p0, r1, p1) {
      return "Q 0,0 " + p1;
    }
    chord.radius = function(v) {
      if (!arguments.length) return radius;
      radius = d3_functor(v);
      return chord;
    };
    chord.source = function(v) {
      if (!arguments.length) return source;
      source = d3_functor(v);
      return chord;
    };
    chord.target = function(v) {
      if (!arguments.length) return target;
      target = d3_functor(v);
      return chord;
    };
    chord.startAngle = function(v) {
      if (!arguments.length) return startAngle;
      startAngle = d3_functor(v);
      return chord;
    };
    chord.endAngle = function(v) {
      if (!arguments.length) return endAngle;
      endAngle = d3_functor(v);
      return chord;
    };
    return chord;
  };
  function d3_svg_chordRadius(d) {
    return d.radius;
  }
  d3.svg.diagonal = function() {
    var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection;
    function diagonal(d, i) {
      var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, {
        x: p0.x,
        y: m
      }, {
        x: p3.x,
        y: m
      }, p3 ];
      p = p.map(projection);
      return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3];
    }
    diagonal.source = function(x) {
      if (!arguments.length) return source;
      source = d3_functor(x);
      return diagonal;
    };
    diagonal.target = function(x) {
      if (!arguments.length) return target;
      target = d3_functor(x);
      return diagonal;
    };
    diagonal.projection = function(x) {
      if (!arguments.length) return projection;
      projection = x;
      return diagonal;
    };
    return diagonal;
  };
  function d3_svg_diagonalProjection(d) {
    return [ d.x, d.y ];
  }
  d3.svg.diagonal.radial = function() {
    var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection;
    diagonal.projection = function(x) {
      return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection;
    };
    return diagonal;
  };
  function d3_svg_diagonalRadialProjection(projection) {
    return function() {
      var d = projection.apply(this, arguments), r = d[0], a = d[1] - halfπ;
      return [ r * Math.cos(a), r * Math.sin(a) ];
    };
  }
  d3.svg.symbol = function() {
    var type = d3_svg_symbolType, size = d3_svg_symbolSize;
    function symbol(d, i) {
      return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i));
    }
    symbol.type = function(x) {
      if (!arguments.length) return type;
      type = d3_functor(x);
      return symbol;
    };
    symbol.size = function(x) {
      if (!arguments.length) return size;
      size = d3_functor(x);
      return symbol;
    };
    return symbol;
  };
  function d3_svg_symbolSize() {
    return 64;
  }
  function d3_svg_symbolType() {
    return "circle";
  }
  function d3_svg_symbolCircle(size) {
    var r = Math.sqrt(size / π);
    return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z";
  }
  var d3_svg_symbols = d3.map({
    circle: d3_svg_symbolCircle,
    cross: function(size) {
      var r = Math.sqrt(size / 5) / 2;
      return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z";
    },
    diamond: function(size) {
      var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30;
      return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z";
    },
    square: function(size) {
      var r = Math.sqrt(size) / 2;
      return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z";
    },
    "triangle-down": function(size) {
      var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2;
      return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z";
    },
    "triangle-up": function(size) {
      var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2;
      return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z";
    }
  });
  d3.svg.symbolTypes = d3_svg_symbols.keys();
  var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians);
  d3_selectionPrototype.transition = function(name) {
    var id = d3_transitionInheritId || ++d3_transitionId, ns = d3_transitionNamespace(name), subgroups = [], subgroup, node, transition = d3_transitionInherit || {
      time: Date.now(),
      ease: d3_ease_cubicInOut,
      delay: 0,
      duration: 250
    };
    for (var j = -1, m = this.length; ++j < m; ) {
      subgroups.push(subgroup = []);
      for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
        if (node = group[i]) d3_transitionNode(node, i, ns, id, transition);
        subgroup.push(node);
      }
    }
    return d3_transition(subgroups, ns, id);
  };
  d3_selectionPrototype.interrupt = function(name) {
    return this.each(name == null ? d3_selection_interrupt : d3_selection_interruptNS(d3_transitionNamespace(name)));
  };
  var d3_selection_interrupt = d3_selection_interruptNS(d3_transitionNamespace());
  function d3_selection_interruptNS(ns) {
    return function() {
      var lock, activeId, active;
      if ((lock = this[ns]) && (active = lock[activeId = lock.active])) {
        active.timer.c = null;
        active.timer.t = NaN;
        if (--lock.count) delete lock[activeId]; else delete this[ns];
        lock.active += .5;
        active.event && active.event.interrupt.call(this, this.__data__, active.index);
      }
    };
  }
  function d3_transition(groups, ns, id) {
    d3_subclass(groups, d3_transitionPrototype);
    groups.namespace = ns;
    groups.id = id;
    return groups;
  }
  var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit;
  d3_transitionPrototype.call = d3_selectionPrototype.call;
  d3_transitionPrototype.empty = d3_selectionPrototype.empty;
  d3_transitionPrototype.node = d3_selectionPrototype.node;
  d3_transitionPrototype.size = d3_selectionPrototype.size;
  d3.transition = function(selection, name) {
    return selection && selection.transition ? d3_transitionInheritId ? selection.transition(name) : selection : d3.selection().transition(selection);
  };
  d3.transition.prototype = d3_transitionPrototype;
  d3_transitionPrototype.select = function(selector) {
    var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnode, node;
    selector = d3_selection_selector(selector);
    for (var j = -1, m = this.length; ++j < m; ) {
      subgroups.push(subgroup = []);
      for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
        if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) {
          if ("__data__" in node) subnode.__data__ = node.__data__;
          d3_transitionNode(subnode, i, ns, id, node[ns][id]);
          subgroup.push(subnode);
        } else {
          subgroup.push(null);
        }
      }
    }
    return d3_transition(subgroups, ns, id);
  };
  d3_transitionPrototype.selectAll = function(selector) {
    var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnodes, node, subnode, transition;
    selector = d3_selection_selectorAll(selector);
    for (var j = -1, m = this.length; ++j < m; ) {
      for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
        if (node = group[i]) {
          transition = node[ns][id];
          subnodes = selector.call(node, node.__data__, i, j);
          subgroups.push(subgroup = []);
          for (var k = -1, o = subnodes.length; ++k < o; ) {
            if (subnode = subnodes[k]) d3_transitionNode(subnode, k, ns, id, transition);
            subgroup.push(subnode);
          }
        }
      }
    }
    return d3_transition(subgroups, ns, id);
  };
  d3_transitionPrototype.filter = function(filter) {
    var subgroups = [], subgroup, group, node;
    if (typeof filter !== "function") filter = d3_selection_filter(filter);
    for (var j = 0, m = this.length; j < m; j++) {
      subgroups.push(subgroup = []);
      for (var group = this[j], i = 0, n = group.length; i < n; i++) {
        if ((node = group[i]) && filter.call(node, node.__data__, i, j)) {
          subgroup.push(node);
        }
      }
    }
    return d3_transition(subgroups, this.namespace, this.id);
  };
  d3_transitionPrototype.tween = function(name, tween) {
    var id = this.id, ns = this.namespace;
    if (arguments.length < 2) return this.node()[ns][id].tween.get(name);
    return d3_selection_each(this, tween == null ? function(node) {
      node[ns][id].tween.remove(name);
    } : function(node) {
      node[ns][id].tween.set(name, tween);
    });
  };
  function d3_transition_tween(groups, name, value, tween) {
    var id = groups.id, ns = groups.namespace;
    return d3_selection_each(groups, typeof value === "function" ? function(node, i, j) {
      node[ns][id].tween.set(name, tween(value.call(node, node.__data__, i, j)));
    } : (value = tween(value), function(node) {
      node[ns][id].tween.set(name, value);
    }));
  }
  d3_transitionPrototype.attr = function(nameNS, value) {
    if (arguments.length < 2) {
      for (value in nameNS) this.attr(value, nameNS[value]);
      return this;
    }
    var interpolate = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name = d3.ns.qualify(nameNS);
    function attrNull() {
      this.removeAttribute(name);
    }
    function attrNullNS() {
      this.removeAttributeNS(name.space, name.local);
    }
    function attrTween(b) {
      return b == null ? attrNull : (b += "", function() {
        var a = this.getAttribute(name), i;
        return a !== b && (i = interpolate(a, b), function(t) {
          this.setAttribute(name, i(t));
        });
      });
    }
    function attrTweenNS(b) {
      return b == null ? attrNullNS : (b += "", function() {
        var a = this.getAttributeNS(name.space, name.local), i;
        return a !== b && (i = interpolate(a, b), function(t) {
          this.setAttributeNS(name.space, name.local, i(t));
        });
      });
    }
    return d3_transition_tween(this, "attr." + nameNS, value, name.local ? attrTweenNS : attrTween);
  };
  d3_transitionPrototype.attrTween = function(nameNS, tween) {
    var name = d3.ns.qualify(nameNS);
    function attrTween(d, i) {
      var f = tween.call(this, d, i, this.getAttribute(name));
      return f && function(t) {
        this.setAttribute(name, f(t));
      };
    }
    function attrTweenNS(d, i) {
      var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local));
      return f && function(t) {
        this.setAttributeNS(name.space, name.local, f(t));
      };
    }
    return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween);
  };
  d3_transitionPrototype.style = function(name, value, priority) {
    var n = arguments.length;
    if (n < 3) {
      if (typeof name !== "string") {
        if (n < 2) value = "";
        for (priority in name) this.style(priority, name[priority], value);
        return this;
      }
      priority = "";
    }
    function styleNull() {
      this.style.removeProperty(name);
    }
    function styleString(b) {
      return b == null ? styleNull : (b += "", function() {
        var a = d3_window(this).getComputedStyle(this, null).getPropertyValue(name), i;
        return a !== b && (i = d3_interpolate(a, b), function(t) {
          this.style.setProperty(name, i(t), priority);
        });
      });
    }
    return d3_transition_tween(this, "style." + name, value, styleString);
  };
  d3_transitionPrototype.styleTween = function(name, tween, priority) {
    if (arguments.length < 3) priority = "";
    function styleTween(d, i) {
      var f = tween.call(this, d, i, d3_window(this).getComputedStyle(this, null).getPropertyValue(name));
      return f && function(t) {
        this.style.setProperty(name, f(t), priority);
      };
    }
    return this.tween("style." + name, styleTween);
  };
  d3_transitionPrototype.text = function(value) {
    return d3_transition_tween(this, "text", value, d3_transition_text);
  };
  function d3_transition_text(b) {
    if (b == null) b = "";
    return function() {
      this.textContent = b;
    };
  }
  d3_transitionPrototype.remove = function() {
    var ns = this.namespace;
    return this.each("end.transition", function() {
      var p;
      if (this[ns].count < 2 && (p = this.parentNode)) p.removeChild(this);
    });
  };
  d3_transitionPrototype.ease = function(value) {
    var id = this.id, ns = this.namespace;
    if (arguments.length < 1) return this.node()[ns][id].ease;
    if (typeof value !== "function") value = d3.ease.apply(d3, arguments);
    return d3_selection_each(this, function(node) {
      node[ns][id].ease = value;
    });
  };
  d3_transitionPrototype.delay = function(value) {
    var id = this.id, ns = this.namespace;
    if (arguments.length < 1) return this.node()[ns][id].delay;
    return d3_selection_each(this, typeof value === "function" ? function(node, i, j) {
      node[ns][id].delay = +value.call(node, node.__data__, i, j);
    } : (value = +value, function(node) {
      node[ns][id].delay = value;
    }));
  };
  d3_transitionPrototype.duration = function(value) {
    var id = this.id, ns = this.namespace;
    if (arguments.length < 1) return this.node()[ns][id].duration;
    return d3_selection_each(this, typeof value === "function" ? function(node, i, j) {
      node[ns][id].duration = Math.max(1, value.call(node, node.__data__, i, j));
    } : (value = Math.max(1, value), function(node) {
      node[ns][id].duration = value;
    }));
  };
  d3_transitionPrototype.each = function(type, listener) {
    var id = this.id, ns = this.namespace;
    if (arguments.length < 2) {
      var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId;
      try {
        d3_transitionInheritId = id;
        d3_selection_each(this, function(node, i, j) {
          d3_transitionInherit = node[ns][id];
          type.call(node, node.__data__, i, j);
        });
      } finally {
        d3_transitionInherit = inherit;
        d3_transitionInheritId = inheritId;
      }
    } else {
      d3_selection_each(this, function(node) {
        var transition = node[ns][id];
        (transition.event || (transition.event = d3.dispatch("start", "end", "interrupt"))).on(type, listener);
      });
    }
    return this;
  };
  d3_transitionPrototype.transition = function() {
    var id0 = this.id, id1 = ++d3_transitionId, ns = this.namespace, subgroups = [], subgroup, group, node, transition;
    for (var j = 0, m = this.length; j < m; j++) {
      subgroups.push(subgroup = []);
      for (var group = this[j], i = 0, n = group.length; i < n; i++) {
        if (node = group[i]) {
          transition = node[ns][id0];
          d3_transitionNode(node, i, ns, id1, {
            time: transition.time,
            ease: transition.ease,
            delay: transition.delay + transition.duration,
            duration: transition.duration
          });
        }
        subgroup.push(node);
      }
    }
    return d3_transition(subgroups, ns, id1);
  };
  function d3_transitionNamespace(name) {
    return name == null ? "__transition__" : "__transition_" + name + "__";
  }
  function d3_transitionNode(node, i, ns, id, inherit) {
    var lock = node[ns] || (node[ns] = {
      active: 0,
      count: 0
    }), transition = lock[id], time, timer, duration, ease, tweens;
    function schedule(elapsed) {
      var delay = transition.delay;
      timer.t = delay + time;
      if (delay <= elapsed) return start(elapsed - delay);
      timer.c = start;
    }
    function start(elapsed) {
      var activeId = lock.active, active = lock[activeId];
      if (active) {
        active.timer.c = null;
        active.timer.t = NaN;
        --lock.count;
        delete lock[activeId];
        active.event && active.event.interrupt.call(node, node.__data__, active.index);
      }
      for (var cancelId in lock) {
        if (+cancelId < id) {
          var cancel = lock[cancelId];
          cancel.timer.c = null;
          cancel.timer.t = NaN;
          --lock.count;
          delete lock[cancelId];
        }
      }
      timer.c = tick;
      d3_timer(function() {
        if (timer.c && tick(elapsed || 1)) {
          timer.c = null;
          timer.t = NaN;
        }
        return 1;
      }, 0, time);
      lock.active = id;
      transition.event && transition.event.start.call(node, node.__data__, i);
      tweens = [];
      transition.tween.forEach(function(key, value) {
        if (value = value.call(node, node.__data__, i)) {
          tweens.push(value);
        }
      });
      ease = transition.ease;
      duration = transition.duration;
    }
    function tick(elapsed) {
      var t = elapsed / duration, e = ease(t), n = tweens.length;
      while (n > 0) {
        tweens[--n].call(node, e);
      }
      if (t >= 1) {
        transition.event && transition.event.end.call(node, node.__data__, i);
        if (--lock.count) delete lock[id]; else delete node[ns];
        return 1;
      }
    }
    if (!transition) {
      time = inherit.time;
      timer = d3_timer(schedule, 0, time);
      transition = lock[id] = {
        tween: new d3_Map(),
        time: time,
        timer: timer,
        delay: inherit.delay,
        duration: inherit.duration,
        ease: inherit.ease,
        index: i
      };
      inherit = null;
      ++lock.count;
    }
  }
  d3.svg.axis = function() {
    var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_;
    function axis(g) {
      g.each(function() {
        var g = d3.select(this);
        var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy();
        var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d3.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d3.transition(tick.order()).style("opacity", 1), tickSpacing = Math.max(innerTickSize, 0) + tickPadding, tickTransform;
        var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"), 
        d3.transition(path));
        tickEnter.append("line");
        tickEnter.append("text");
        var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"), sign = orient === "top" || orient === "left" ? -1 : 1, x1, x2, y1, y2;
        if (orient === "bottom" || orient === "top") {
          tickTransform = d3_svg_axisX, x1 = "x", y1 = "y", x2 = "x2", y2 = "y2";
          text.attr("dy", sign < 0 ? "0em" : ".71em").style("text-anchor", "middle");
          pathUpdate.attr("d", "M" + range[0] + "," + sign * outerTickSize + "V0H" + range[1] + "V" + sign * outerTickSize);
        } else {
          tickTransform = d3_svg_axisY, x1 = "y", y1 = "x", x2 = "y2", y2 = "x2";
          text.attr("dy", ".32em").style("text-anchor", sign < 0 ? "end" : "start");
          pathUpdate.attr("d", "M" + sign * outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + sign * outerTickSize);
        }
        lineEnter.attr(y2, sign * innerTickSize);
        textEnter.attr(y1, sign * tickSpacing);
        lineUpdate.attr(x2, 0).attr(y2, sign * innerTickSize);
        textUpdate.attr(x1, 0).attr(y1, sign * tickSpacing);
        if (scale1.rangeBand) {
          var x = scale1, dx = x.rangeBand() / 2;
          scale0 = scale1 = function(d) {
            return x(d) + dx;
          };
        } else if (scale0.rangeBand) {
          scale0 = scale1;
        } else {
          tickExit.call(tickTransform, scale1, scale0);
        }
        tickEnter.call(tickTransform, scale0, scale1);
        tickUpdate.call(tickTransform, scale1, scale1);
      });
    }
    axis.scale = function(x) {
      if (!arguments.length) return scale;
      scale = x;
      return axis;
    };
    axis.orient = function(x) {
      if (!arguments.length) return orient;
      orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient;
      return axis;
    };
    axis.ticks = function() {
      if (!arguments.length) return tickArguments_;
      tickArguments_ = d3_array(arguments);
      return axis;
    };
    axis.tickValues = function(x) {
      if (!arguments.length) return tickValues;
      tickValues = x;
      return axis;
    };
    axis.tickFormat = function(x) {
      if (!arguments.length) return tickFormat_;
      tickFormat_ = x;
      return axis;
    };
    axis.tickSize = function(x) {
      var n = arguments.length;
      if (!n) return innerTickSize;
      innerTickSize = +x;
      outerTickSize = +arguments[n - 1];
      return axis;
    };
    axis.innerTickSize = function(x) {
      if (!arguments.length) return innerTickSize;
      innerTickSize = +x;
      return axis;
    };
    axis.outerTickSize = function(x) {
      if (!arguments.length) return outerTickSize;
      outerTickSize = +x;
      return axis;
    };
    axis.tickPadding = function(x) {
      if (!arguments.length) return tickPadding;
      tickPadding = +x;
      return axis;
    };
    axis.tickSubdivide = function() {
      return arguments.length && axis;
    };
    return axis;
  };
  var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = {
    top: 1,
    right: 1,
    bottom: 1,
    left: 1
  };
  function d3_svg_axisX(selection, x0, x1) {
    selection.attr("transform", function(d) {
      var v0 = x0(d);
      return "translate(" + (isFinite(v0) ? v0 : x1(d)) + ",0)";
    });
  }
  function d3_svg_axisY(selection, y0, y1) {
    selection.attr("transform", function(d) {
      var v0 = y0(d);
      return "translate(0," + (isFinite(v0) ? v0 : y1(d)) + ")";
    });
  }
  d3.svg.brush = function() {
    var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [ 0, 0 ], yExtent = [ 0, 0 ], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0];
    function brush(g) {
      g.each(function() {
        var g = d3.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart);
        var background = g.selectAll(".background").data([ 0 ]);
        background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair");
        g.selectAll(".extent").data([ 0 ]).enter().append("rect").attr("class", "extent").style("cursor", "move");
        var resize = g.selectAll(".resize").data(resizes, d3_identity);
        resize.exit().remove();
        resize.enter().append("g").attr("class", function(d) {
          return "resize " + d;
        }).style("cursor", function(d) {
          return d3_svg_brushCursor[d];
        }).append("rect").attr("x", function(d) {
          return /[ew]$/.test(d) ? -3 : null;
        }).attr("y", function(d) {
          return /^[ns]/.test(d) ? -3 : null;
        }).attr("width", 6).attr("height", 6).style("visibility", "hidden");
        resize.style("display", brush.empty() ? "none" : null);
        var gUpdate = d3.transition(g), backgroundUpdate = d3.transition(background), range;
        if (x) {
          range = d3_scaleRange(x);
          backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]);
          redrawX(gUpdate);
        }
        if (y) {
          range = d3_scaleRange(y);
          backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]);
          redrawY(gUpdate);
        }
        redraw(gUpdate);
      });
    }
    brush.event = function(g) {
      g.each(function() {
        var event_ = event.of(this, arguments), extent1 = {
          x: xExtent,
          y: yExtent,
          i: xExtentDomain,
          j: yExtentDomain
        }, extent0 = this.__chart__ || extent1;
        this.__chart__ = extent1;
        if (d3_transitionInheritId) {
          d3.select(this).transition().each("start.brush", function() {
            xExtentDomain = extent0.i;
            yExtentDomain = extent0.j;
            xExtent = extent0.x;
            yExtent = extent0.y;
            event_({
              type: "brushstart"
            });
          }).tween("brush:brush", function() {
            var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y);
            xExtentDomain = yExtentDomain = null;
            return function(t) {
              xExtent = extent1.x = xi(t);
              yExtent = extent1.y = yi(t);
              event_({
                type: "brush",
                mode: "resize"
              });
            };
          }).each("end.brush", function() {
            xExtentDomain = extent1.i;
            yExtentDomain = extent1.j;
            event_({
              type: "brush",
              mode: "resize"
            });
            event_({
              type: "brushend"
            });
          });
        } else {
          event_({
            type: "brushstart"
          });
          event_({
            type: "brush",
            mode: "resize"
          });
          event_({
            type: "brushend"
          });
        }
      });
    };
    function redraw(g) {
      g.selectAll(".resize").attr("transform", function(d) {
        return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")";
      });
    }
    function redrawX(g) {
      g.select(".extent").attr("x", xExtent[0]);
      g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]);
    }
    function redrawY(g) {
      g.select(".extent").attr("y", yExtent[0]);
      g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]);
    }
    function brushstart() {
      var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(target), center, origin = d3.mouse(target), offset;
      var w = d3.select(d3_window(target)).on("keydown.brush", keydown).on("keyup.brush", keyup);
      if (d3.event.changedTouches) {
        w.on("touchmove.brush", brushmove).on("touchend.brush", brushend);
      } else {
        w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend);
      }
      g.interrupt().selectAll("*").interrupt();
      if (dragging) {
        origin[0] = xExtent[0] - origin[0];
        origin[1] = yExtent[0] - origin[1];
      } else if (resizing) {
        var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing);
        offset = [ xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1] ];
        origin[0] = xExtent[ex];
        origin[1] = yExtent[ey];
      } else if (d3.event.altKey) center = origin.slice();
      g.style("pointer-events", "none").selectAll(".resize").style("display", null);
      d3.select("body").style("cursor", eventTarget.style("cursor"));
      event_({
        type: "brushstart"
      });
      brushmove();
      function keydown() {
        if (d3.event.keyCode == 32) {
          if (!dragging) {
            center = null;
            origin[0] -= xExtent[1];
            origin[1] -= yExtent[1];
            dragging = 2;
          }
          d3_eventPreventDefault();
        }
      }
      function keyup() {
        if (d3.event.keyCode == 32 && dragging == 2) {
          origin[0] += xExtent[1];
          origin[1] += yExtent[1];
          dragging = 0;
          d3_eventPreventDefault();
        }
      }
      function brushmove() {
        var point = d3.mouse(target), moved = false;
        if (offset) {
          point[0] += offset[0];
          point[1] += offset[1];
        }
        if (!dragging) {
          if (d3.event.altKey) {
            if (!center) center = [ (xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2 ];
            origin[0] = xExtent[+(point[0] < center[0])];
            origin[1] = yExtent[+(point[1] < center[1])];
          } else center = null;
        }
        if (resizingX && move1(point, x, 0)) {
          redrawX(g);
          moved = true;
        }
        if (resizingY && move1(point, y, 1)) {
          redrawY(g);
          moved = true;
        }
        if (moved) {
          redraw(g);
          event_({
            type: "brush",
            mode: dragging ? "move" : "resize"
          });
        }
      }
      function move1(point, scale, i) {
        var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], extent = i ? yExtent : xExtent, size = extent[1] - extent[0], min, max;
        if (dragging) {
          r0 -= position;
          r1 -= size + position;
        }
        min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i];
        if (dragging) {
          max = (min += position) + size;
        } else {
          if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min));
          if (position < min) {
            max = min;
            min = position;
          } else {
            max = position;
          }
        }
        if (extent[0] != min || extent[1] != max) {
          if (i) yExtentDomain = null; else xExtentDomain = null;
          extent[0] = min;
          extent[1] = max;
          return true;
        }
      }
      function brushend() {
        brushmove();
        g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null);
        d3.select("body").style("cursor", null);
        w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null);
        dragRestore();
        event_({
          type: "brushend"
        });
      }
    }
    brush.x = function(z) {
      if (!arguments.length) return x;
      x = z;
      resizes = d3_svg_brushResizes[!x << 1 | !y];
      return brush;
    };
    brush.y = function(z) {
      if (!arguments.length) return y;
      y = z;
      resizes = d3_svg_brushResizes[!x << 1 | !y];
      return brush;
    };
    brush.clamp = function(z) {
      if (!arguments.length) return x && y ? [ xClamp, yClamp ] : x ? xClamp : y ? yClamp : null;
      if (x && y) xClamp = !!z[0], yClamp = !!z[1]; else if (x) xClamp = !!z; else if (y) yClamp = !!z;
      return brush;
    };
    brush.extent = function(z) {
      var x0, x1, y0, y1, t;
      if (!arguments.length) {
        if (x) {
          if (xExtentDomain) {
            x0 = xExtentDomain[0], x1 = xExtentDomain[1];
          } else {
            x0 = xExtent[0], x1 = xExtent[1];
            if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1);
            if (x1 < x0) t = x0, x0 = x1, x1 = t;
          }
        }
        if (y) {
          if (yExtentDomain) {
            y0 = yExtentDomain[0], y1 = yExtentDomain[1];
          } else {
            y0 = yExtent[0], y1 = yExtent[1];
            if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1);
            if (y1 < y0) t = y0, y0 = y1, y1 = t;
          }
        }
        return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ];
      }
      if (x) {
        x0 = z[0], x1 = z[1];
        if (y) x0 = x0[0], x1 = x1[0];
        xExtentDomain = [ x0, x1 ];
        if (x.invert) x0 = x(x0), x1 = x(x1);
        if (x1 < x0) t = x0, x0 = x1, x1 = t;
        if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [ x0, x1 ];
      }
      if (y) {
        y0 = z[0], y1 = z[1];
        if (x) y0 = y0[1], y1 = y1[1];
        yExtentDomain = [ y0, y1 ];
        if (y.invert) y0 = y(y0), y1 = y(y1);
        if (y1 < y0) t = y0, y0 = y1, y1 = t;
        if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [ y0, y1 ];
      }
      return brush;
    };
    brush.clear = function() {
      if (!brush.empty()) {
        xExtent = [ 0, 0 ], yExtent = [ 0, 0 ];
        xExtentDomain = yExtentDomain = null;
      }
      return brush;
    };
    brush.empty = function() {
      return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1];
    };
    return d3.rebind(brush, event, "on");
  };
  var d3_svg_brushCursor = {
    n: "ns-resize",
    e: "ew-resize",
    s: "ns-resize",
    w: "ew-resize",
    nw: "nwse-resize",
    ne: "nesw-resize",
    se: "nwse-resize",
    sw: "nesw-resize"
  };
  var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ];
  var d3_time_format = d3_time.format = d3_locale_enUS.timeFormat;
  var d3_time_formatUtc = d3_time_format.utc;
  var d3_time_formatIso = d3_time_formatUtc("%Y-%m-%dT%H:%M:%S.%LZ");
  d3_time_format.iso = Date.prototype.toISOString && +new Date("2000-01-01T00:00:00.000Z") ? d3_time_formatIsoNative : d3_time_formatIso;
  function d3_time_formatIsoNative(date) {
    return date.toISOString();
  }
  d3_time_formatIsoNative.parse = function(string) {
    var date = new Date(string);
    return isNaN(date) ? null : date;
  };
  d3_time_formatIsoNative.toString = d3_time_formatIso.toString;
  d3_time.second = d3_time_interval(function(date) {
    return new d3_date(Math.floor(date / 1e3) * 1e3);
  }, function(date, offset) {
    date.setTime(date.getTime() + Math.floor(offset) * 1e3);
  }, function(date) {
    return date.getSeconds();
  });
  d3_time.seconds = d3_time.second.range;
  d3_time.seconds.utc = d3_time.second.utc.range;
  d3_time.minute = d3_time_interval(function(date) {
    return new d3_date(Math.floor(date / 6e4) * 6e4);
  }, function(date, offset) {
    date.setTime(date.getTime() + Math.floor(offset) * 6e4);
  }, function(date) {
    return date.getMinutes();
  });
  d3_time.minutes = d3_time.minute.range;
  d3_time.minutes.utc = d3_time.minute.utc.range;
  d3_time.hour = d3_time_interval(function(date) {
    var timezone = date.getTimezoneOffset() / 60;
    return new d3_date((Math.floor(date / 36e5 - timezone) + timezone) * 36e5);
  }, function(date, offset) {
    date.setTime(date.getTime() + Math.floor(offset) * 36e5);
  }, function(date) {
    return date.getHours();
  });
  d3_time.hours = d3_time.hour.range;
  d3_time.hours.utc = d3_time.hour.utc.range;
  d3_time.month = d3_time_interval(function(date) {
    date = d3_time.day(date);
    date.setDate(1);
    return date;
  }, function(date, offset) {
    date.setMonth(date.getMonth() + offset);
  }, function(date) {
    return date.getMonth();
  });
  d3_time.months = d3_time.month.range;
  d3_time.months.utc = d3_time.month.utc.range;
  function d3_time_scale(linear, methods, format) {
    function scale(x) {
      return linear(x);
    }
    scale.invert = function(x) {
      return d3_time_scaleDate(linear.invert(x));
    };
    scale.domain = function(x) {
      if (!arguments.length) return linear.domain().map(d3_time_scaleDate);
      linear.domain(x);
      return scale;
    };
    function tickMethod(extent, count) {
      var span = extent[1] - extent[0], target = span / count, i = d3.bisect(d3_time_scaleSteps, target);
      return i == d3_time_scaleSteps.length ? [ methods.year, d3_scale_linearTickRange(extent.map(function(d) {
        return d / 31536e6;
      }), count)[2] ] : !i ? [ d3_time_scaleMilliseconds, d3_scale_linearTickRange(extent, count)[2] ] : methods[target / d3_time_scaleSteps[i - 1] < d3_time_scaleSteps[i] / target ? i - 1 : i];
    }
    scale.nice = function(interval, skip) {
      var domain = scale.domain(), extent = d3_scaleExtent(domain), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" && tickMethod(extent, interval);
      if (method) interval = method[0], skip = method[1];
      function skipped(date) {
        return !isNaN(date) && !interval.range(date, d3_time_scaleDate(+date + 1), skip).length;
      }
      return scale.domain(d3_scale_nice(domain, skip > 1 ? {
        floor: function(date) {
          while (skipped(date = interval.floor(date))) date = d3_time_scaleDate(date - 1);
          return date;
        },
        ceil: function(date) {
          while (skipped(date = interval.ceil(date))) date = d3_time_scaleDate(+date + 1);
          return date;
        }
      } : interval));
    };
    scale.ticks = function(interval, skip) {
      var extent = d3_scaleExtent(scale.domain()), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" ? tickMethod(extent, interval) : !interval.range && [ {
        range: interval
      }, skip ];
      if (method) interval = method[0], skip = method[1];
      return interval.range(extent[0], d3_time_scaleDate(+extent[1] + 1), skip < 1 ? 1 : skip);
    };
    scale.tickFormat = function() {
      return format;
    };
    scale.copy = function() {
      return d3_time_scale(linear.copy(), methods, format);
    };
    return d3_scale_linearRebind(scale, linear);
  }
  function d3_time_scaleDate(t) {
    return new Date(t);
  }
  var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ];
  var d3_time_scaleLocalMethods = [ [ d3_time.second, 1 ], [ d3_time.second, 5 ], [ d3_time.second, 15 ], [ d3_time.second, 30 ], [ d3_time.minute, 1 ], [ d3_time.minute, 5 ], [ d3_time.minute, 15 ], [ d3_time.minute, 30 ], [ d3_time.hour, 1 ], [ d3_time.hour, 3 ], [ d3_time.hour, 6 ], [ d3_time.hour, 12 ], [ d3_time.day, 1 ], [ d3_time.day, 2 ], [ d3_time.week, 1 ], [ d3_time.month, 1 ], [ d3_time.month, 3 ], [ d3_time.year, 1 ] ];
  var d3_time_scaleLocalFormat = d3_time_format.multi([ [ ".%L", function(d) {
    return d.getMilliseconds();
  } ], [ ":%S", function(d) {
    return d.getSeconds();
  } ], [ "%I:%M", function(d) {
    return d.getMinutes();
  } ], [ "%I %p", function(d) {
    return d.getHours();
  } ], [ "%a %d", function(d) {
    return d.getDay() && d.getDate() != 1;
  } ], [ "%b %d", function(d) {
    return d.getDate() != 1;
  } ], [ "%B", function(d) {
    return d.getMonth();
  } ], [ "%Y", d3_true ] ]);
  var d3_time_scaleMilliseconds = {
    range: function(start, stop, step) {
      return d3.range(Math.ceil(start / step) * step, +stop, step).map(d3_time_scaleDate);
    },
    floor: d3_identity,
    ceil: d3_identity
  };
  d3_time_scaleLocalMethods.year = d3_time.year;
  d3_time.scale = function() {
    return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat);
  };
  var d3_time_scaleUtcMethods = d3_time_scaleLocalMethods.map(function(m) {
    return [ m[0].utc, m[1] ];
  });
  var d3_time_scaleUtcFormat = d3_time_formatUtc.multi([ [ ".%L", function(d) {
    return d.getUTCMilliseconds();
  } ], [ ":%S", function(d) {
    return d.getUTCSeconds();
  } ], [ "%I:%M", function(d) {
    return d.getUTCMinutes();
  } ], [ "%I %p", function(d) {
    return d.getUTCHours();
  } ], [ "%a %d", function(d) {
    return d.getUTCDay() && d.getUTCDate() != 1;
  } ], [ "%b %d", function(d) {
    return d.getUTCDate() != 1;
  } ], [ "%B", function(d) {
    return d.getUTCMonth();
  } ], [ "%Y", d3_true ] ]);
  d3_time_scaleUtcMethods.year = d3_time.year.utc;
  d3_time.scale.utc = function() {
    return d3_time_scale(d3.scale.linear(), d3_time_scaleUtcMethods, d3_time_scaleUtcFormat);
  };
  d3.text = d3_xhrType(function(request) {
    return request.responseText;
  });
  d3.json = function(url, callback) {
    return d3_xhr(url, "application/json", d3_json, callback);
  };
  function d3_json(request) {
    return JSON.parse(request.responseText);
  }
  d3.html = function(url, callback) {
    return d3_xhr(url, "text/html", d3_html, callback);
  };
  function d3_html(request) {
    var range = d3_document.createRange();
    range.selectNode(d3_document.body);
    return range.createContextualFragment(request.responseText);
  }
  d3.xml = d3_xhrType(function(request) {
    return request.responseXML;
  });
  if (true) this.d3 = d3, !(__WEBPACK_AMD_DEFINE_FACTORY__ = (d3),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
				__WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); else {}
}();

/***/ }),

/***/ "bpih":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/it.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var it = moment.defineLocale('it', {
    months : 'gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre'.split('_'),
    monthsShort : 'gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic'.split('_'),
    weekdays : 'domenica_lunedì_martedì_mercoledì_giovedì_venerdì_sabato'.split('_'),
    weekdaysShort : 'dom_lun_mar_mer_gio_ven_sab'.split('_'),
    weekdaysMin : 'do_lu_ma_me_gi_ve_sa'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay: '[Oggi alle] LT',
        nextDay: '[Domani alle] LT',
        nextWeek: 'dddd [alle] LT',
        lastDay: '[Ieri alle] LT',
        lastWeek: function () {
            switch (this.day()) {
                case 0:
                    return '[la scorsa] dddd [alle] LT';
                default:
                    return '[lo scorso] dddd [alle] LT';
            }
        },
        sameElse: 'L'
    },
    relativeTime : {
        future : function (s) {
            return ((/^[0-9].+$/).test(s) ? 'tra' : 'in') + ' ' + s;
        },
        past : '%s fa',
        s : 'alcuni secondi',
        ss : '%d secondi',
        m : 'un minuto',
        mm : '%d minuti',
        h : 'un\'ora',
        hh : '%d ore',
        d : 'un giorno',
        dd : '%d giorni',
        M : 'un mese',
        MM : '%d mesi',
        y : 'un anno',
        yy : '%d anni'
    },
    dayOfMonthOrdinalParse : /\d{1,2}º/,
    ordinal: '%dº',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return it;

})));


/***/ }),

/***/ "bu2F":
/*!**************************************************!*\
  !*** ./node_modules/hash.js/lib/hash/sha/256.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var utils = __webpack_require__(/*! ../utils */ "w8CP");
var common = __webpack_require__(/*! ../common */ "7ckf");
var shaCommon = __webpack_require__(/*! ./common */ "qlaj");
var assert = __webpack_require__(/*! minimalistic-assert */ "2j6C");

var sum32 = utils.sum32;
var sum32_4 = utils.sum32_4;
var sum32_5 = utils.sum32_5;
var ch32 = shaCommon.ch32;
var maj32 = shaCommon.maj32;
var s0_256 = shaCommon.s0_256;
var s1_256 = shaCommon.s1_256;
var g0_256 = shaCommon.g0_256;
var g1_256 = shaCommon.g1_256;

var BlockHash = common.BlockHash;

var sha256_K = [
  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
  0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
  0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
  0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
  0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
  0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
  0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
  0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
  0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
  0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
  0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
  0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
];

function SHA256() {
  if (!(this instanceof SHA256))
    return new SHA256();

  BlockHash.call(this);
  this.h = [
    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
    0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
  ];
  this.k = sha256_K;
  this.W = new Array(64);
}
utils.inherits(SHA256, BlockHash);
module.exports = SHA256;

SHA256.blockSize = 512;
SHA256.outSize = 256;
SHA256.hmacStrength = 192;
SHA256.padLength = 64;

SHA256.prototype._update = function _update(msg, start) {
  var W = this.W;

  for (var i = 0; i < 16; i++)
    W[i] = msg[start + i];
  for (; i < W.length; i++)
    W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);

  var a = this.h[0];
  var b = this.h[1];
  var c = this.h[2];
  var d = this.h[3];
  var e = this.h[4];
  var f = this.h[5];
  var g = this.h[6];
  var h = this.h[7];

  assert(this.k.length === W.length);
  for (i = 0; i < W.length; i++) {
    var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);
    var T2 = sum32(s0_256(a), maj32(a, b, c));
    h = g;
    g = f;
    f = e;
    e = sum32(d, T1);
    d = c;
    c = b;
    b = a;
    a = sum32(T1, T2);
  }

  this.h[0] = sum32(this.h[0], a);
  this.h[1] = sum32(this.h[1], b);
  this.h[2] = sum32(this.h[2], c);
  this.h[3] = sum32(this.h[3], d);
  this.h[4] = sum32(this.h[4], e);
  this.h[5] = sum32(this.h[5], f);
  this.h[6] = sum32(this.h[6], g);
  this.h[7] = sum32(this.h[7], h);
};

SHA256.prototype._digest = function digest(enc) {
  if (enc === 'hex')
    return utils.toHex32(this.h, 'big');
  else
    return utils.split32(this.h, 'big');
};


/***/ }),

/***/ "bu5B":
/*!************************************************************!*\
  !*** ./node_modules/draft-js/lib/removeEntitiesAtEdges.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule removeEntitiesAtEdges
 * @format
 * 
 */



var CharacterMetadata = __webpack_require__(/*! ./CharacterMetadata */ "lFJn");

var findRangesImmutable = __webpack_require__(/*! ./findRangesImmutable */ "Taje");
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");

function removeEntitiesAtEdges(contentState, selectionState) {
  var blockMap = contentState.getBlockMap();
  var entityMap = contentState.getEntityMap();

  var updatedBlocks = {};

  var startKey = selectionState.getStartKey();
  var startOffset = selectionState.getStartOffset();
  var startBlock = blockMap.get(startKey);
  var updatedStart = removeForBlock(entityMap, startBlock, startOffset);

  if (updatedStart !== startBlock) {
    updatedBlocks[startKey] = updatedStart;
  }

  var endKey = selectionState.getEndKey();
  var endOffset = selectionState.getEndOffset();
  var endBlock = blockMap.get(endKey);
  if (startKey === endKey) {
    endBlock = updatedStart;
  }

  var updatedEnd = removeForBlock(entityMap, endBlock, endOffset);

  if (updatedEnd !== endBlock) {
    updatedBlocks[endKey] = updatedEnd;
  }

  if (!Object.keys(updatedBlocks).length) {
    return contentState.set('selectionAfter', selectionState);
  }

  return contentState.merge({
    blockMap: blockMap.merge(updatedBlocks),
    selectionAfter: selectionState
  });
}

function getRemovalRange(characters, key, offset) {
  var removalRange;
  findRangesImmutable(characters, function (a, b) {
    return a.getEntity() === b.getEntity();
  }, function (element) {
    return element.getEntity() === key;
  }, function (start, end) {
    if (start <= offset && end >= offset) {
      removalRange = { start: start, end: end };
    }
  });
  !(typeof removalRange === 'object') ?  true ? invariant(false, 'Removal range must exist within character list.') : undefined : void 0;
  return removalRange;
}

function removeForBlock(entityMap, block, offset) {
  var chars = block.getCharacterList();
  var charBefore = offset > 0 ? chars.get(offset - 1) : undefined;
  var charAfter = offset < chars.count() ? chars.get(offset) : undefined;
  var entityBeforeCursor = charBefore ? charBefore.getEntity() : undefined;
  var entityAfterCursor = charAfter ? charAfter.getEntity() : undefined;

  if (entityAfterCursor && entityAfterCursor === entityBeforeCursor) {
    var entity = entityMap.__get(entityAfterCursor);
    if (entity.getMutability() !== 'MUTABLE') {
      var _getRemovalRange = getRemovalRange(chars, entityAfterCursor, offset),
          start = _getRemovalRange.start,
          end = _getRemovalRange.end;

      var current;
      while (start < end) {
        current = chars.get(start);
        chars = chars.set(start, CharacterMetadata.applyEntity(current, null));
        start++;
      }
      return block.set('characterList', chars);
    }
  }

  return block;
}

module.exports = removeEntitiesAtEdges;

/***/ }),

/***/ "buUt":
/*!*******************************************************************!*\
  !*** ./node_modules/draft-js-import-element/lib/lib/Constants.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var INLINE_ELEMENTS = exports.INLINE_ELEMENTS = {
  a: 1,
  abbr: 1,
  area: 1,
  audio: 1,
  b: 1,
  bdi: 1,
  bdo: 1,
  br: 1,
  button: 1,
  canvas: 1,
  cite: 1,
  code: 1,
  command: 1,
  datalist: 1,
  del: 1,
  dfn: 1,
  em: 1,
  embed: 1,
  i: 1,
  iframe: 1,
  img: 1,
  input: 1,
  ins: 1,
  kbd: 1,
  keygen: 1,
  label: 1,
  map: 1,
  mark: 1,
  meter: 1,
  noscript: 1,
  object: 1,
  output: 1,
  progress: 1,
  q: 1,
  ruby: 1,
  s: 1,
  samp: 1,
  script: 1,
  select: 1,
  small: 1,
  span: 1,
  strong: 1,
  sub: 1,
  sup: 1,
  textarea: 1,
  time: 1,
  u: 1,
  var: 1,
  video: 1,
  wbr: 1,
  acronym: 1,
  applet: 1,
  basefont: 1,
  big: 1,
  font: 1,
  isindex: 1,
  strike: 1,
  style: 1,
  tt: 1
};

// These elements are special because they cannot contain text as a direct
// child (some cannot contain childNodes at all).
var SPECIAL_ELEMENTS = exports.SPECIAL_ELEMENTS = {
  area: 1,
  base: 1,
  br: 1,
  col: 1,
  colgroup: 1,
  command: 1,
  dl: 1,
  embed: 1,
  head: 1,
  hgroup: 1,
  hr: 1,
  iframe: 1,
  img: 1,
  input: 1,
  keygen: 1,
  link: 1,
  meta: 1,
  ol: 1,
  optgroup: 1,
  option: 1,
  param: 1,
  script: 1,
  select: 1,
  source: 1,
  style: 1,
  table: 1,
  tbody: 1,
  textarea: 1,
  tfoot: 1,
  thead: 1,
  title: 1,
  tr: 1,
  track: 1,
  ul: 1,
  wbr: 1,
  basefont: 1,
  dialog: 1,
  dir: 1,
  isindex: 1
};

// These elements are special because they cannot contain childNodes.
// TODO: This is not an exhaustive list.
var SELF_CLOSING_ELEMENTS = exports.SELF_CLOSING_ELEMENTS = { img: 1 };

/***/ }),

/***/ "bvhh":
/*!*******************************************!*\
  !*** ./node_modules/ajv/lib/dotjs/ref.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_ref(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $async, $refCode;
  if ($schema == '#' || $schema == '#/') {
    if (it.isRoot) {
      $async = it.async;
      $refCode = 'validate';
    } else {
      $async = it.root.schema.$async === true;
      $refCode = 'root.refVal[0]';
    }
  } else {
    var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot);
    if ($refVal === undefined) {
      var $message = it.MissingRefError.message(it.baseId, $schema);
      if (it.opts.missingRefs == 'fail') {
        console.error($message);
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ('$ref') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { ref: \'' + (it.util.escapeQuotes($schema)) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'can\\\'t resolve reference ' + (it.util.escapeQuotes($schema)) + '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: ' + (it.util.toQuotedString($schema)) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        if ($breakOnError) {
          out += ' if (false) { ';
        }
      } else if (it.opts.missingRefs == 'ignore') {
        console.warn($message);
        if ($breakOnError) {
          out += ' if (true) { ';
        }
      } else {
        throw new it.MissingRefError(it.baseId, $schema, $message);
      }
    } else if ($refVal.inline) {
      var $it = it.util.copy(it);
      $it.level++;
      var $nextValid = 'valid' + $it.level;
      $it.schema = $refVal.schema;
      $it.schemaPath = '';
      $it.errSchemaPath = $schema;
      var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code);
      out += ' ' + ($code) + ' ';
      if ($breakOnError) {
        out += ' if (' + ($nextValid) + ') { ';
      }
    } else {
      $async = $refVal.$async === true;
      $refCode = $refVal.code;
    }
  }
  if ($refCode) {
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = '';
    if (it.opts.passContext) {
      out += ' ' + ($refCode) + '.call(this, ';
    } else {
      out += ' ' + ($refCode) + '( ';
    }
    out += ' ' + ($data) + ', (dataPath || \'\')';
    if (it.errorPath != '""') {
      out += ' + ' + (it.errorPath);
    }
    var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
      $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
    out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ', rootData)  ';
    var __callValidate = out;
    out = $$outStack.pop();
    if ($async) {
      if (!it.async) throw new Error('async schema referenced by sync schema');
      if ($breakOnError) {
        out += ' var ' + ($valid) + '; ';
      }
      out += ' try { ' + (it.yieldAwait) + ' ' + (__callValidate) + '; ';
      if ($breakOnError) {
        out += ' ' + ($valid) + ' = true; ';
      }
      out += ' } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ';
      if ($breakOnError) {
        out += ' ' + ($valid) + ' = false; ';
      }
      out += ' } ';
      if ($breakOnError) {
        out += ' if (' + ($valid) + ') { ';
      }
    } else {
      out += ' if (!' + (__callValidate) + ') { if (vErrors === null) vErrors = ' + ($refCode) + '.errors; else vErrors = vErrors.concat(' + ($refCode) + '.errors); errors = vErrors.length; } ';
      if ($breakOnError) {
        out += ' else { ';
      }
    }
  }
  return out;
}


/***/ }),

/***/ "c203":
/*!***************************************************************!*\
  !*** ./node_modules/draft-js/lib/getCharacterRemovalRange.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule getCharacterRemovalRange
 * @format
 * 
 */



var DraftEntitySegments = __webpack_require__(/*! ./DraftEntitySegments */ "/y0H");

var getRangesForDraftEntity = __webpack_require__(/*! ./getRangesForDraftEntity */ "fMZg");
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");

/**
 * Given a SelectionState and a removal direction, determine the entire range
 * that should be removed from a ContentState. This is based on any entities
 * within the target, with their `mutability` values taken into account.
 *
 * For instance, if we are attempting to remove part of an "immutable" entity
 * range, the entire entity must be removed. The returned `SelectionState`
 * will be adjusted accordingly.
 */
function getCharacterRemovalRange(entityMap, startBlock, endBlock, selectionState, direction) {
  var start = selectionState.getStartOffset();
  var end = selectionState.getEndOffset();
  var startEntityKey = startBlock.getEntityAt(start);
  var endEntityKey = endBlock.getEntityAt(end - 1);
  if (!startEntityKey && !endEntityKey) {
    return selectionState;
  }
  var newSelectionState = selectionState;
  if (startEntityKey && startEntityKey === endEntityKey) {
    newSelectionState = getEntityRemovalRange(entityMap, startBlock, newSelectionState, direction, startEntityKey, true, true);
  } else if (startEntityKey && endEntityKey) {
    var startSelectionState = getEntityRemovalRange(entityMap, startBlock, newSelectionState, direction, startEntityKey, false, true);
    var endSelectionState = getEntityRemovalRange(entityMap, endBlock, newSelectionState, direction, endEntityKey, false, false);
    newSelectionState = newSelectionState.merge({
      anchorOffset: startSelectionState.getAnchorOffset(),
      focusOffset: endSelectionState.getFocusOffset(),
      isBackward: false
    });
  } else if (startEntityKey) {
    var _startSelectionState = getEntityRemovalRange(entityMap, startBlock, newSelectionState, direction, startEntityKey, false, true);
    newSelectionState = newSelectionState.merge({
      anchorOffset: _startSelectionState.getStartOffset(),
      isBackward: false
    });
  } else if (endEntityKey) {
    var _endSelectionState = getEntityRemovalRange(entityMap, endBlock, newSelectionState, direction, endEntityKey, false, false);
    newSelectionState = newSelectionState.merge({
      focusOffset: _endSelectionState.getEndOffset(),
      isBackward: false
    });
  }
  return newSelectionState;
}

function getEntityRemovalRange(entityMap, block, selectionState, direction, entityKey, isEntireSelectionWithinEntity, isEntityAtStart) {
  var start = selectionState.getStartOffset();
  var end = selectionState.getEndOffset();
  var entity = entityMap.__get(entityKey);
  var mutability = entity.getMutability();
  var sideToConsider = isEntityAtStart ? start : end;

  // `MUTABLE` entities can just have the specified range of text removed
  // directly. No adjustments are needed.
  if (mutability === 'MUTABLE') {
    return selectionState;
  }

  // Find the entity range that overlaps with our removal range.
  var entityRanges = getRangesForDraftEntity(block, entityKey).filter(function (range) {
    return sideToConsider <= range.end && sideToConsider >= range.start;
  });

  !(entityRanges.length == 1) ?  true ? invariant(false, 'There should only be one entity range within this removal range.') : undefined : void 0;

  var entityRange = entityRanges[0];

  // For `IMMUTABLE` entity types, we will remove the entire entity range.
  if (mutability === 'IMMUTABLE') {
    return selectionState.merge({
      anchorOffset: entityRange.start,
      focusOffset: entityRange.end,
      isBackward: false
    });
  }

  // For `SEGMENTED` entity types, determine the appropriate segment to
  // remove.
  if (!isEntireSelectionWithinEntity) {
    if (isEntityAtStart) {
      end = entityRange.end;
    } else {
      start = entityRange.start;
    }
  }

  var removalRange = DraftEntitySegments.getRemovalRange(start, end, block.getText().slice(entityRange.start, entityRange.end), entityRange.start, direction);

  return selectionState.merge({
    anchorOffset: removalRange.start,
    focusOffset: removalRange.end,
    isBackward: false
  });
}

module.exports = getCharacterRemovalRange;

/***/ }),

/***/ "c6wG":
/*!*********************************************!*\
  !*** ./node_modules/lodash/isTypedArray.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseIsTypedArray = __webpack_require__(/*! ./_baseIsTypedArray */ "dD9F"),
    baseUnary = __webpack_require__(/*! ./_baseUnary */ "sEf8"),
    nodeUtil = __webpack_require__(/*! ./_nodeUtil */ "mdPL");

/* Node.js helper references. */
var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;

/**
 * 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;

module.exports = isTypedArray;


/***/ }),

/***/ "cHMM":
/*!*******************************************************!*\
  !*** ./node_modules/entities/lib/decode_codepoint.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var decodeMap = __webpack_require__(/*! ../maps/decode.json */ "tRRp");

module.exports = decodeCodePoint;

// modified version of https://github.com/mathiasbynens/he/blob/master/src/he.js#L94-L119
function decodeCodePoint(codePoint) {
    if ((codePoint >= 0xd800 && codePoint <= 0xdfff) || codePoint > 0x10ffff) {
        return "\uFFFD";
    }

    if (codePoint in decodeMap) {
        codePoint = decodeMap[codePoint];
    }

    var output = "";

    if (codePoint > 0xffff) {
        codePoint -= 0x10000;
        output += String.fromCharCode(((codePoint >>> 10) & 0x3ff) | 0xd800);
        codePoint = 0xdc00 | (codePoint & 0x3ff);
    }

    output += String.fromCharCode(codePoint);
    return output;
}


/***/ }),

/***/ "cHdg":
/*!**************************************************!*\
  !*** ./node_modules/mdi-react/FolderOpenIcon.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var FolderOpenIcon = function FolderOpenIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M19,20H4C2.89,20 2,19.1 2,18V6C2,4.89 2.89,4 4,4H10L12,6H19C20.1,6 21,6.9 21,8H21L4,8V18L6.14,10H23.21L20.93,18.5C20.7,19.37 19.92,20 19,20Z' })
  );
};

module.exports = FolderOpenIcon;


/***/ }),

/***/ "cN6I":
/*!********************************************************!*\
  !*** ./node_modules/@phosphor/coreutils/lib/random.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * The namespace for random number related functionality.
 */
var Random;
(function (Random) {
    /**
     * A function which generates random bytes.
     *
     * @param buffer - The `Uint8Array` to fill with random bytes.
     *
     * #### Notes
     * A cryptographically strong random number generator will be used if
     * available. Otherwise, `Math.random` will be used as a fallback for
     * randomness.
     *
     * The following RNGs are supported, listed in order of precedence:
     *   - `window.crypto.getRandomValues`
     *   - `window.msCrypto.getRandomValues`
     *   - `require('crypto').randomFillSync
     *   - `require('crypto').randomBytes
     *   - `Math.random`
     */
    Random.getRandomValues = (function () {
        // Look up the crypto module if available.
        var crypto = ((typeof window !== 'undefined' && (window.crypto || window.msCrypto)) ||
            ("function" !== 'undefined' && __webpack_require__(/*! crypto */ "HEbw")) || null);
        // Modern browsers and IE 11
        if (crypto && typeof crypto.getRandomValues === 'function') {
            return function getRandomValues(buffer) {
                return crypto.getRandomValues(buffer);
            };
        }
        // Node 7+
        if (crypto && typeof crypto.randomFillSync === 'function') {
            return function getRandomValues(buffer) {
                return crypto.randomFillSync(buffer);
            };
        }
        // Node 0.10+
        if (crypto && typeof crypto.randomBytes === 'function') {
            return function getRandomValues(buffer) {
                var bytes = crypto.randomBytes(buffer.length);
                for (var i = 0, n = bytes.length; i < n; ++i) {
                    buffer[i] = bytes[i];
                }
            };
        }
        // Fallback
        return function getRandomValues(buffer) {
            var value = 0;
            for (var i = 0, n = buffer.length; i < n; ++i) {
                if (i % 4 === 0) {
                    value = Math.random() * 0xFFFFFFFF >>> 0;
                }
                buffer[i] = value & 0xFF;
                value >>>= 8;
            }
        };
    })();
})(Random = exports.Random || (exports.Random = {}));


/***/ }),

/***/ "cRix":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/fy.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var monthsShortWithDots = 'jan._feb._mrt._apr._mai_jun._jul._aug._sep._okt._nov._des.'.split('_'),
    monthsShortWithoutDots = 'jan_feb_mrt_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_');

var fy = moment.defineLocale('fy', {
    months : 'jannewaris_febrewaris_maart_april_maaie_juny_july_augustus_septimber_oktober_novimber_desimber'.split('_'),
    monthsShort : function (m, format) {
        if (!m) {
            return monthsShortWithDots;
        } else if (/-MMM-/.test(format)) {
            return monthsShortWithoutDots[m.month()];
        } else {
            return monthsShortWithDots[m.month()];
        }
    },
    monthsParseExact : true,
    weekdays : 'snein_moandei_tiisdei_woansdei_tongersdei_freed_sneon'.split('_'),
    weekdaysShort : 'si._mo._ti._wo._to._fr._so.'.split('_'),
    weekdaysMin : 'Si_Mo_Ti_Wo_To_Fr_So'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD-MM-YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay: '[hjoed om] LT',
        nextDay: '[moarn om] LT',
        nextWeek: 'dddd [om] LT',
        lastDay: '[juster om] LT',
        lastWeek: '[ôfrûne] dddd [om] LT',
        sameElse: 'L'
    },
    relativeTime : {
        future : 'oer %s',
        past : '%s lyn',
        s : 'in pear sekonden',
        ss : '%d sekonden',
        m : 'ien minút',
        mm : '%d minuten',
        h : 'ien oere',
        hh : '%d oeren',
        d : 'ien dei',
        dd : '%d dagen',
        M : 'ien moanne',
        MM : '%d moannen',
        y : 'ien jier',
        yy : '%d jierren'
    },
    dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/,
    ordinal : function (number) {
        return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de');
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return fy;

})));


/***/ }),

/***/ "cUtX":
/*!***********************************************!*\
  !*** ./node_modules/ajv/lib/dotjs/pattern.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_pattern(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema);
  out += 'if ( ';
  if ($isData) {
    out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
  }
  out += ' !' + ($regexp) + '.test(' + ($data) + ') ) {   ';
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern:  ';
    if ($isData) {
      out += '' + ($schemaValue);
    } else {
      out += '' + (it.util.toQuotedString($schema));
    }
    out += '  } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should match pattern "';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + (it.util.escapeQuotes($schema));
      }
      out += '"\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + (it.util.toQuotedString($schema));
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}


/***/ }),

/***/ "cX45":
/*!********************************************************!*\
  !*** ./node_modules/draft-js/lib/DraftFeatureFlags.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DraftFeatureFlags
 * @format
 * 
 */



var DraftFeatureFlags = __webpack_require__(/*! ./DraftFeatureFlags-core */ "oPSa");

module.exports = DraftFeatureFlags;

/***/ }),

/***/ "ca2I":
/*!*********************************************************!*\
  !*** ./node_modules/@jupyterlab/cells/lib/collapser.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const React = __importStar(__webpack_require__(/*! react */ "q1tI"));
/**
 * The CSS class added to all collapsers.
 */
const COLLAPSER_CLASS = 'jp-Collapser';
/**
 * The CSS class added to the collapser child.
 */
const COLLAPSER_CHILD_CLASS = 'jp-Collapser-child';
/**
 * The CSS class added to input collapsers.
 */
const INPUT_COLLAPSER = 'jp-InputCollapser';
/**
 * The CSS class added to output collapsers.
 */
const OUTPUT_COLLAPSER = 'jp-OutputCollapser';
/**
 * The CSS class added the collapser child when collapsed.
 */
const MOD_COLLAPSED_CLASS = 'jp-mod-collapsed';
/**
 * Abstract collapser base class.
 *
 * ### Notes
 * A collapser is a visible div to the left of a cell's
 * input/output that a user can click on to collapse the
 * input/output.
 */
class Collapser extends apputils_1.VDomRenderer {
    /**
     * Construct a new collapser.
     */
    constructor() {
        super();
        this.addClass(COLLAPSER_CLASS);
    }
    /**
     * Is the input/output of the parent collapsed.
     */
    get collapsed() {
        return false;
    }
    /**
     * Render the collapser with the virtual DOM.
     */
    render() {
        let childClass = COLLAPSER_CHILD_CLASS;
        if (this.collapsed) {
            childClass += ` ${MOD_COLLAPSED_CLASS}`;
        }
        return React.createElement("div", { className: childClass, onClick: e => this.handleClick(e) });
    }
}
exports.Collapser = Collapser;
/**
 * A collapser subclass to collapse a cell's input area.
 */
class InputCollapser extends Collapser {
    /**
     * Construct a new input collapser.
     */
    constructor() {
        super();
        this.addClass(INPUT_COLLAPSER);
    }
    /**
     * Is the cell's input collapsed?
     */
    get collapsed() {
        let cell = this.parent.parent;
        if (cell) {
            return cell.inputHidden;
        }
        else {
            return false;
        }
    }
    /**
     * Handle a click event for the user to collapse the cell's input.
     */
    handleClick(e) {
        let cell = this.parent.parent;
        if (cell) {
            cell.inputHidden = !cell.inputHidden;
        }
        /* We need this until we watch the cell state */
        this.update();
    }
}
exports.InputCollapser = InputCollapser;
/**
 * A collapser subclass to collapse a cell's output area.
 */
class OutputCollapser extends Collapser {
    /**
     * Construct a new output collapser.
     */
    constructor() {
        super();
        this.addClass(OUTPUT_COLLAPSER);
    }
    /**
     * Is the cell's output collapsed?
     */
    get collapsed() {
        let cell = this.parent.parent;
        if (cell) {
            return cell.outputHidden;
        }
        else {
            return false;
        }
    }
    /**
     * Handle a click event for the user to collapse the cell's output.
     */
    handleClick(e) {
        let cell = this.parent.parent;
        if (cell) {
            cell.outputHidden = !cell.outputHidden;
        }
        /* We need this until we watch the cell state */
        this.update();
    }
}
exports.OutputCollapser = OutputCollapser;


/***/ }),

/***/ "caab":
/*!****************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/Modal.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ModalContent = exports.ModalHeader = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _plotlyIcons = __webpack_require__(/*! plotly-icons */ "hwSx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var ModalHeader = function ModalHeader(_ref) {
  var title = _ref.title,
      handleClose = _ref.handleClose;
  return _react2.default.createElement(
    'div',
    { className: 'modal__header' },
    title ? _react2.default.createElement(
      'div',
      { className: 'modal__header__title' },
      title
    ) : null,
    handleClose ? _react2.default.createElement(
      'div',
      { className: 'modal__header__close', onClick: handleClose ? function () {
          return handleClose();
        } : null },
      _react2.default.createElement(_plotlyIcons.CloseIcon, null)
    ) : null
  );
};

var ModalContent = function ModalContent(_ref2) {
  var children = _ref2.children;
  return _react2.default.createElement(
    'div',
    { className: 'modal__content' },
    children
  );
};

var Modal = function (_Component) {
  _inherits(Modal, _Component);

  function Modal(props) {
    _classCallCheck(this, Modal);

    var _this = _possibleConstructorReturn(this, (Modal.__proto__ || Object.getPrototypeOf(Modal)).call(this, props));

    _this.escFunction = _this.escFunction.bind(_this);
    return _this;
  }

  _createClass(Modal, [{
    key: 'escFunction',
    value: function escFunction(event) {
      var escKeyCode = 27;
      if (event.keyCode === escKeyCode) {
        this.context.handleClose();
      }
    }
  }, {
    key: 'componentDidMount',
    value: function componentDidMount() {
      document.addEventListener('keydown', this.escFunction, false);
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      document.removeEventListener('keydown', this.escFunction, false);
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _props = this.props,
          children = _props.children,
          title = _props.title;

      var classes = 'modal';
      if (this.context.isAnimatingOut) {
        classes += ' modal--animate-out';
      }
      return _react2.default.createElement(
        'div',
        { className: classes },
        _react2.default.createElement(
          'div',
          { className: 'modal__card' },
          _react2.default.createElement(ModalHeader, { title: title, handleClose: function handleClose() {
              return _this2.context.handleClose();
            } }),
          _react2.default.createElement(
            ModalContent,
            null,
            children
          )
        ),
        _react2.default.createElement('div', { className: 'modal__backdrop', onClick: function onClick() {
            return _this2.context.handleClose();
          } })
      );
    }
  }]);

  return Modal;
}(_react.Component);

ModalHeader.propTypes = {
  title: _propTypes2.default.node,
  handleClose: _propTypes2.default.func.isRequired
};

ModalContent.propTypes = {
  children: _propTypes2.default.node.isRequired
};

Modal.propTypes = {
  children: _propTypes2.default.node.isRequired,
  title: _propTypes2.default.node
};

Modal.contextTypes = {
  handleClose: _propTypes2.default.func,
  isAnimatingOut: _propTypes2.default.bool
};

exports.default = Modal;
exports.ModalHeader = ModalHeader;
exports.ModalContent = ModalContent;
//# sourceMappingURL=Modal.js.map

/***/ }),

/***/ "ccE7":
/*!************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_string-at.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var toInteger = __webpack_require__(/*! ./_to-integer */ "Ojgd");
var defined = __webpack_require__(/*! ./_defined */ "Jes0");
// true  -> String#at
// false -> String#codePointAt
module.exports = function (TO_STRING) {
  return function (that, pos) {
    var s = String(defined(that));
    var i = toInteger(pos);
    var l = s.length;
    var a, b;
    if (i < 0 || i >= l) return TO_STRING ? '' : undefined;
    a = s.charCodeAt(i);
    return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
      ? TO_STRING ? s.charAt(i) : a
      : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
  };
};


/***/ }),

/***/ "ccyi":
/*!**********************************************************************!*\
  !*** ./node_modules/react-color/lib/components/common/Saturation.js ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Saturation = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _throttle = __webpack_require__(/*! lodash/throttle */ "DzJC");

var _throttle2 = _interopRequireDefault(_throttle);

var _saturation = __webpack_require__(/*! ../../helpers/saturation */ "VVms");

var saturation = _interopRequireWildcard(_saturation);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Saturation = exports.Saturation = function (_ref) {
  _inherits(Saturation, _ref);

  function Saturation(props) {
    _classCallCheck(this, Saturation);

    var _this = _possibleConstructorReturn(this, (Saturation.__proto__ || Object.getPrototypeOf(Saturation)).call(this, props));

    _this.handleChange = function (e, skip) {
      _this.props.onChange && _this.throttle(_this.props.onChange, saturation.calculateChange(e, skip, _this.props, _this.container), e);
    };

    _this.handleMouseDown = function (e) {
      _this.handleChange(e, true);
      window.addEventListener('mousemove', _this.handleChange);
      window.addEventListener('mouseup', _this.handleMouseUp);
    };

    _this.handleMouseUp = function () {
      _this.unbindEventListeners();
    };

    _this.throttle = (0, _throttle2.default)(function (fn, data, e) {
      fn(data, e);
    }, 50);
    return _this;
  }

  _createClass(Saturation, [{
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      this.throttle.cancel();
      this.unbindEventListeners();
    }
  }, {
    key: 'unbindEventListeners',
    value: function unbindEventListeners() {
      window.removeEventListener('mousemove', this.handleChange);
      window.removeEventListener('mouseup', this.handleMouseUp);
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _ref2 = this.props.style || {},
          color = _ref2.color,
          white = _ref2.white,
          black = _ref2.black,
          pointer = _ref2.pointer,
          circle = _ref2.circle;

      var styles = (0, _reactcss2.default)({
        'default': {
          color: {
            absolute: '0px 0px 0px 0px',
            background: 'hsl(' + this.props.hsl.h + ',100%, 50%)',
            borderRadius: this.props.radius
          },
          white: {
            absolute: '0px 0px 0px 0px',
            borderRadius: this.props.radius
          },
          black: {
            absolute: '0px 0px 0px 0px',
            boxShadow: this.props.shadow,
            borderRadius: this.props.radius
          },
          pointer: {
            position: 'absolute',
            top: -(this.props.hsv.v * 100) + 100 + '%',
            left: this.props.hsv.s * 100 + '%',
            cursor: 'default'
          },
          circle: {
            width: '4px',
            height: '4px',
            boxShadow: '0 0 0 1.5px #fff, inset 0 0 1px 1px rgba(0,0,0,.3),\n            0 0 1px 2px rgba(0,0,0,.4)',
            borderRadius: '50%',
            cursor: 'hand',
            transform: 'translate(-2px, -2px)'
          }
        },
        'custom': {
          color: color,
          white: white,
          black: black,
          pointer: pointer,
          circle: circle
        }
      }, { 'custom': !!this.props.style });

      return _react2.default.createElement(
        'div',
        {
          style: styles.color,
          ref: function ref(container) {
            return _this2.container = container;
          },
          onMouseDown: this.handleMouseDown,
          onTouchMove: this.handleChange,
          onTouchStart: this.handleChange
        },
        _react2.default.createElement(
          'style',
          null,
          '\n          .saturation-white {\n            background: -webkit-linear-gradient(to right, #fff, rgba(255,255,255,0));\n            background: linear-gradient(to right, #fff, rgba(255,255,255,0));\n          }\n          .saturation-black {\n            background: -webkit-linear-gradient(to top, #000, rgba(0,0,0,0));\n            background: linear-gradient(to top, #000, rgba(0,0,0,0));\n          }\n        '
        ),
        _react2.default.createElement(
          'div',
          { style: styles.white, className: 'saturation-white' },
          _react2.default.createElement('div', { style: styles.black, className: 'saturation-black' }),
          _react2.default.createElement(
            'div',
            { style: styles.pointer },
            this.props.pointer ? _react2.default.createElement(this.props.pointer, this.props) : _react2.default.createElement('div', { style: styles.circle })
          )
        )
      );
    }
  }]);

  return Saturation;
}(_react.PureComponent || _react.Component);

exports.default = Saturation;

/***/ }),

/***/ "cexl":
/*!*************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/ShapeAccordion.js ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _PlotlyFold = __webpack_require__(/*! ./PlotlyFold */ "mQPs");

var _PlotlyFold2 = _interopRequireDefault(_PlotlyFold);

var _derived = __webpack_require__(/*! ./derived */ "ykRn");

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _constants = __webpack_require__(/*! ../../lib/constants */ "5Bkx");

var _PanelEmpty = __webpack_require__(/*! ./PanelEmpty */ "o21U");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var ShapeFold = (0, _lib.connectShapeToLayout)(_PlotlyFold2.default);

var ShapeAccordion = function (_Component) {
  _inherits(ShapeAccordion, _Component);

  function ShapeAccordion() {
    _classCallCheck(this, ShapeAccordion);

    return _possibleConstructorReturn(this, (ShapeAccordion.__proto__ || Object.getPrototypeOf(ShapeAccordion)).apply(this, arguments));
  }

  _createClass(ShapeAccordion, [{
    key: 'render',
    value: function render() {
      var _context = this.context,
          _context$layout$shape = _context.layout.shapes,
          shapes = _context$layout$shape === undefined ? [] : _context$layout$shape,
          _ = _context.localize;
      var _props = this.props,
          canAdd = _props.canAdd,
          children = _props.children;


      var content = shapes.length && shapes.map(function (shp, i) {
        return _react2.default.createElement(
          ShapeFold,
          { key: i, shapeIndex: i, name: _('Shape') + ' ' + (i + 1), canDelete: canAdd },
          children
        );
      });

      var addAction = {
        label: _('Shape'),
        handler: function handler(_ref) {
          var layout = _ref.layout,
              updateContainer = _ref.updateContainer;

          var shapeIndex = void 0;
          if (Array.isArray(layout.shapes)) {
            shapeIndex = layout.shapes.length;
          } else {
            shapeIndex = 0;
          }

          var key = 'shapes[' + shapeIndex + ']';
          var value = {
            line: { color: _constants.COLORS.charcoal },
            fillcolor: _constants.COLORS.middleGray,
            opacity: 0.3
          };

          if (updateContainer) {
            updateContainer(_defineProperty({}, key, value));
          }
        }
      };

      return _react2.default.createElement(
        _derived.LayoutPanel,
        { addAction: canAdd ? addAction : null },
        content ? content : _react2.default.createElement(
          _PanelEmpty.PanelMessage,
          { heading: _('Lines, Rectangles and Ellipses.') },
          _react2.default.createElement(
            'p',
            null,
            _('Add shapes to a figure to highlight points or periods in time, thresholds, or areas of interest.')
          ),
          _react2.default.createElement(
            'p',
            null,
            _('Click on the + button above to add a shape.')
          )
        )
      );
    }
  }]);

  return ShapeAccordion;
}(_react.Component);

ShapeAccordion.contextTypes = {
  layout: _propTypes2.default.object,
  localize: _propTypes2.default.func
};

ShapeAccordion.propTypes = {
  children: _propTypes2.default.node,
  canAdd: _propTypes2.default.bool
};

exports.default = ShapeAccordion;
//# sourceMappingURL=ShapeAccordion.js.map

/***/ }),

/***/ "chXj":
/*!**********************************************!*\
  !*** ./node_modules/base16/lib/marrakesh.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'marrakesh',
  author: 'alexandre gavioli (http://github.com/alexx2/)',
  base00: '#201602',
  base01: '#302e00',
  base02: '#5f5b17',
  base03: '#6c6823',
  base04: '#86813b',
  base05: '#948e48',
  base06: '#ccc37a',
  base07: '#faf0a5',
  base08: '#c35359',
  base09: '#b36144',
  base0A: '#a88339',
  base0B: '#18974e',
  base0C: '#75a738',
  base0D: '#477ca1',
  base0E: '#8868b3',
  base0F: '#b3588e'
};
module.exports = exports['default'];

/***/ }),

/***/ "cjZW":
/*!**********************************************!*\
  !*** ./node_modules/ajv/lib/dotjs/custom.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_custom(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $rule = this,
    $definition = 'definition' + $lvl,
    $rDef = $rule.definition,
    $closingBraces = '';
  var $compile, $inline, $macro, $ruleValidate, $validateCode;
  if ($isData && $rDef.$data) {
    $validateCode = 'keywordValidate' + $lvl;
    var $validateSchema = $rDef.validateSchema;
    out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;';
  } else {
    $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it);
    if (!$ruleValidate) return;
    $schemaValue = 'validate.schema' + $schemaPath;
    $validateCode = $ruleValidate.code;
    $compile = $rDef.compile;
    $inline = $rDef.inline;
    $macro = $rDef.macro;
  }
  var $ruleErrs = $validateCode + '.errors',
    $i = 'i' + $lvl,
    $ruleErr = 'ruleErr' + $lvl,
    $asyncKeyword = $rDef.async;
  if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema');
  if (!($inline || $macro)) {
    out += '' + ($ruleErrs) + ' = null;';
  }
  out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
  if ($isData && $rDef.$data) {
    $closingBraces += '}';
    out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { ';
    if ($validateSchema) {
      $closingBraces += '}';
      out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { ';
    }
  }
  if ($inline) {
    if ($rDef.statements) {
      out += ' ' + ($ruleValidate.validate) + ' ';
    } else {
      out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; ';
    }
  } else if ($macro) {
    var $it = it.util.copy(it);
    var $closingBraces = '';
    $it.level++;
    var $nextValid = 'valid' + $it.level;
    $it.schema = $ruleValidate.validate;
    $it.schemaPath = '';
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    var $code = it.validate($it).replace(/validate\.schema/g, $validateCode);
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += ' ' + ($code);
  } else {
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = '';
    out += '  ' + ($validateCode) + '.call( ';
    if (it.opts.passContext) {
      out += 'this';
    } else {
      out += 'self';
    }
    if ($compile || $rDef.schema === false) {
      out += ' , ' + ($data) + ' ';
    } else {
      out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' ';
    }
    out += ' , (dataPath || \'\')';
    if (it.errorPath != '""') {
      out += ' + ' + (it.errorPath);
    }
    var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
      $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
    out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData )  ';
    var def_callRuleValidate = out;
    out = $$outStack.pop();
    if ($rDef.errors === false) {
      out += ' ' + ($valid) + ' = ';
      if ($asyncKeyword) {
        out += '' + (it.yieldAwait);
      }
      out += '' + (def_callRuleValidate) + '; ';
    } else {
      if ($asyncKeyword) {
        $ruleErrs = 'customErrors' + $lvl;
        out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = ' + (it.yieldAwait) + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } ';
      } else {
        out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; ';
      }
    }
  }
  if ($rDef.modifying) {
    out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];';
  }
  out += '' + ($closingBraces);
  if ($rDef.valid) {
    if ($breakOnError) {
      out += ' if (true) { ';
    }
  } else {
    out += ' if ( ';
    if ($rDef.valid === undefined) {
      out += ' !';
      if ($macro) {
        out += '' + ($nextValid);
      } else {
        out += '' + ($valid);
      }
    } else {
      out += ' ' + (!$rDef.valid) + ' ';
    }
    out += ') { ';
    $errorKeyword = $rule.keyword;
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = '';
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = ''; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError([' + (__err) + ']); ';
      } else {
        out += ' validate.errors = [' + (__err) + ']; return false; ';
      }
    } else {
      out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    }
    var def_customError = out;
    out = $$outStack.pop();
    if ($inline) {
      if ($rDef.errors) {
        if ($rDef.errors != 'full') {
          out += '  for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } ';
          if (it.opts.verbose) {
            out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
          }
          out += ' } ';
        }
      } else {
        if ($rDef.errors === false) {
          out += ' ' + (def_customError) + ' ';
        } else {
          out += ' if (' + ($errs) + ' == errors) { ' + (def_customError) + ' } else {  for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } ';
          if (it.opts.verbose) {
            out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
          }
          out += ' } } ';
        }
      }
    } else if ($macro) {
      out += '   var err =   '; /* istanbul ignore else */
      if (it.createErrors !== false) {
        out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
        if (it.opts.messages !== false) {
          out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
        }
        if (it.opts.verbose) {
          out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
        }
        out += ' } ';
      } else {
        out += ' {} ';
      }
      out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
      if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
        if (it.async) {
          out += ' throw new ValidationError(vErrors); ';
        } else {
          out += ' validate.errors = vErrors; return false; ';
        }
      }
    } else {
      if ($rDef.errors === false) {
        out += ' ' + (def_customError) + ' ';
      } else {
        out += ' if (Array.isArray(' + ($ruleErrs) + ')) { if (vErrors === null) vErrors = ' + ($ruleErrs) + '; else vErrors = vErrors.concat(' + ($ruleErrs) + '); errors = vErrors.length;  for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + ';  ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '";  ';
        if (it.opts.verbose) {
          out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
        }
        out += ' } } else { ' + (def_customError) + ' } ';
      }
    }
    out += ' } ';
    if ($breakOnError) {
      out += ' else { ';
    }
  }
  return out;
}


/***/ }),

/***/ "cmQj":
/*!*****************************************************!*\
  !*** ./node_modules/draft-js/lib/editOnDragOver.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule editOnDragOver
 * @format
 * 
 */



/**
 * Drag behavior has begun from outside the editor element.
 */
function editOnDragOver(editor, e) {
  editor._internalDrag = false;
  editor.setMode('drag');
  e.preventDefault();
}

module.exports = editOnDragOver;

/***/ }),

/***/ "co0h":
/*!************************************************************************!*\
  !*** ./node_modules/@jupyterlab/markdownviewer-extension/lib/index.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const rendermime_1 = __webpack_require__(/*! @jupyterlab/rendermime */ "Towz");
__webpack_require__(/*! ../style/index.css */ "BnSx");
/**
 * The name of the factory that creates markdown widgets.
 */
const FACTORY = 'Markdown Preview';
/**
 * The markdown mime renderer extension.
 */
const extension = {
    id: '@jupyterlab/markdownviewer-extension:factory',
    rendererFactory: rendermime_1.markdownRendererFactory,
    dataType: 'string',
    documentWidgetFactoryOptions: {
        name: FACTORY,
        primaryFileType: 'markdown',
        fileTypes: ['markdown'],
        defaultRendered: ['markdown']
    }
};
/**
 * Export the extension as default.
 */
exports.default = extension;


/***/ }),

/***/ "cokd":
/*!**********************************************************!*\
  !*** ./node_modules/codemirror/addon/comment/comment.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"));
  else {}
})(function(CodeMirror) {
  "use strict";

  var noOptions = {};
  var nonWS = /[^\s\u00a0]/;
  var Pos = CodeMirror.Pos;

  function firstNonWS(str) {
    var found = str.search(nonWS);
    return found == -1 ? 0 : found;
  }

  CodeMirror.commands.toggleComment = function(cm) {
    cm.toggleComment();
  };

  CodeMirror.defineExtension("toggleComment", function(options) {
    if (!options) options = noOptions;
    var cm = this;
    var minLine = Infinity, ranges = this.listSelections(), mode = null;
    for (var i = ranges.length - 1; i >= 0; i--) {
      var from = ranges[i].from(), to = ranges[i].to();
      if (from.line >= minLine) continue;
      if (to.line >= minLine) to = Pos(minLine, 0);
      minLine = from.line;
      if (mode == null) {
        if (cm.uncomment(from, to, options)) mode = "un";
        else { cm.lineComment(from, to, options); mode = "line"; }
      } else if (mode == "un") {
        cm.uncomment(from, to, options);
      } else {
        cm.lineComment(from, to, options);
      }
    }
  });

  // Rough heuristic to try and detect lines that are part of multi-line string
  function probablyInsideString(cm, pos, line) {
    return /\bstring\b/.test(cm.getTokenTypeAt(Pos(pos.line, 0))) && !/^[\'\"\`]/.test(line)
  }

  function getMode(cm, pos) {
    var mode = cm.getMode()
    return mode.useInnerComments === false || !mode.innerMode ? mode : cm.getModeAt(pos)
  }

  CodeMirror.defineExtension("lineComment", function(from, to, options) {
    if (!options) options = noOptions;
    var self = this, mode = getMode(self, from);
    var firstLine = self.getLine(from.line);
    if (firstLine == null || probablyInsideString(self, from, firstLine)) return;

    var commentString = options.lineComment || mode.lineComment;
    if (!commentString) {
      if (options.blockCommentStart || mode.blockCommentStart) {
        options.fullLines = true;
        self.blockComment(from, to, options);
      }
      return;
    }

    var end = Math.min(to.ch != 0 || to.line == from.line ? to.line + 1 : to.line, self.lastLine() + 1);
    var pad = options.padding == null ? " " : options.padding;
    var blankLines = options.commentBlankLines || from.line == to.line;

    self.operation(function() {
      if (options.indent) {
        var baseString = null;
        for (var i = from.line; i < end; ++i) {
          var line = self.getLine(i);
          var whitespace = line.slice(0, firstNonWS(line));
          if (baseString == null || baseString.length > whitespace.length) {
            baseString = whitespace;
          }
        }
        for (var i = from.line; i < end; ++i) {
          var line = self.getLine(i), cut = baseString.length;
          if (!blankLines && !nonWS.test(line)) continue;
          if (line.slice(0, cut) != baseString) cut = firstNonWS(line);
          self.replaceRange(baseString + commentString + pad, Pos(i, 0), Pos(i, cut));
        }
      } else {
        for (var i = from.line; i < end; ++i) {
          if (blankLines || nonWS.test(self.getLine(i)))
            self.replaceRange(commentString + pad, Pos(i, 0));
        }
      }
    });
  });

  CodeMirror.defineExtension("blockComment", function(from, to, options) {
    if (!options) options = noOptions;
    var self = this, mode = getMode(self, from);
    var startString = options.blockCommentStart || mode.blockCommentStart;
    var endString = options.blockCommentEnd || mode.blockCommentEnd;
    if (!startString || !endString) {
      if ((options.lineComment || mode.lineComment) && options.fullLines != false)
        self.lineComment(from, to, options);
      return;
    }
    if (/\bcomment\b/.test(self.getTokenTypeAt(Pos(from.line, 0)))) return

    var end = Math.min(to.line, self.lastLine());
    if (end != from.line && to.ch == 0 && nonWS.test(self.getLine(end))) --end;

    var pad = options.padding == null ? " " : options.padding;
    if (from.line > end) return;

    self.operation(function() {
      if (options.fullLines != false) {
        var lastLineHasText = nonWS.test(self.getLine(end));
        self.replaceRange(pad + endString, Pos(end));
        self.replaceRange(startString + pad, Pos(from.line, 0));
        var lead = options.blockCommentLead || mode.blockCommentLead;
        if (lead != null) for (var i = from.line + 1; i <= end; ++i)
          if (i != end || lastLineHasText)
            self.replaceRange(lead + pad, Pos(i, 0));
      } else {
        self.replaceRange(endString, to);
        self.replaceRange(startString, from);
      }
    });
  });

  CodeMirror.defineExtension("uncomment", function(from, to, options) {
    if (!options) options = noOptions;
    var self = this, mode = getMode(self, from);
    var end = Math.min(to.ch != 0 || to.line == from.line ? to.line : to.line - 1, self.lastLine()), start = Math.min(from.line, end);

    // Try finding line comments
    var lineString = options.lineComment || mode.lineComment, lines = [];
    var pad = options.padding == null ? " " : options.padding, didSomething;
    lineComment: {
      if (!lineString) break lineComment;
      for (var i = start; i <= end; ++i) {
        var line = self.getLine(i);
        var found = line.indexOf(lineString);
        if (found > -1 && !/comment/.test(self.getTokenTypeAt(Pos(i, found + 1)))) found = -1;
        if (found == -1 && nonWS.test(line)) break lineComment;
        if (found > -1 && nonWS.test(line.slice(0, found))) break lineComment;
        lines.push(line);
      }
      self.operation(function() {
        for (var i = start; i <= end; ++i) {
          var line = lines[i - start];
          var pos = line.indexOf(lineString), endPos = pos + lineString.length;
          if (pos < 0) continue;
          if (line.slice(endPos, endPos + pad.length) == pad) endPos += pad.length;
          didSomething = true;
          self.replaceRange("", Pos(i, pos), Pos(i, endPos));
        }
      });
      if (didSomething) return true;
    }

    // Try block comments
    var startString = options.blockCommentStart || mode.blockCommentStart;
    var endString = options.blockCommentEnd || mode.blockCommentEnd;
    if (!startString || !endString) return false;
    var lead = options.blockCommentLead || mode.blockCommentLead;
    var startLine = self.getLine(start), open = startLine.indexOf(startString)
    if (open == -1) return false
    var endLine = end == start ? startLine : self.getLine(end)
    var close = endLine.indexOf(endString, end == start ? open + startString.length : 0);
    var insideStart = Pos(start, open + 1), insideEnd = Pos(end, close + 1)
    if (close == -1 ||
        !/comment/.test(self.getTokenTypeAt(insideStart)) ||
        !/comment/.test(self.getTokenTypeAt(insideEnd)) ||
        self.getRange(insideStart, insideEnd, "\n").indexOf(endString) > -1)
      return false;

    // Avoid killing block comments completely outside the selection.
    // Positions of the last startString before the start of the selection, and the first endString after it.
    var lastStart = startLine.lastIndexOf(startString, from.ch);
    var firstEnd = lastStart == -1 ? -1 : startLine.slice(0, from.ch).indexOf(endString, lastStart + startString.length);
    if (lastStart != -1 && firstEnd != -1 && firstEnd + endString.length != from.ch) return false;
    // Positions of the first endString after the end of the selection, and the last startString before it.
    firstEnd = endLine.indexOf(endString, to.ch);
    var almostLastStart = endLine.slice(to.ch).lastIndexOf(startString, firstEnd - to.ch);
    lastStart = (firstEnd == -1 || almostLastStart == -1) ? -1 : to.ch + almostLastStart;
    if (firstEnd != -1 && lastStart != -1 && lastStart != to.ch) return false;

    self.operation(function() {
      self.replaceRange("", Pos(end, close - (pad && endLine.slice(close - pad.length, close) == pad ? pad.length : 0)),
                        Pos(end, close + endString.length));
      var openEnd = open + startString.length;
      if (pad && startLine.slice(openEnd, openEnd + pad.length) == pad) openEnd += pad.length;
      self.replaceRange("", Pos(start, open), Pos(start, openEnd));
      if (lead) for (var i = start + 1; i <= end; ++i) {
        var line = self.getLine(i), found = line.indexOf(lead);
        if (found == -1 || nonWS.test(line.slice(0, found))) continue;
        var foundEnd = found + lead.length;
        if (pad && line.slice(foundEnd, foundEnd + pad.length) == pad) foundEnd += pad.length;
        self.replaceRange("", Pos(i, found), Pos(i, foundEnd));
      }
    });
    return true;
  });
});


/***/ }),

/***/ "cq/+":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_baseFor.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var createBaseFor = __webpack_require__(/*! ./_createBaseFor */ "mc0g");

/**
 * 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();

module.exports = baseFor;


/***/ }),

/***/ "cqRZ":
/*!**************************************************************!*\
  !*** ./node_modules/plotly.js/src/constants/interactions.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




module.exports = {
    /**
     * Timing information for interactive elements
     */
    SHOW_PLACEHOLDER: 100,
    HIDE_PLACEHOLDER: 1000,

    // ms between first mousedown and 2nd mouseup to constitute dblclick...
    // we don't seem to have access to the system setting
    DBLCLICKDELAY: 300,

    // opacity dimming fraction for points that are not in selection
    DESELECTDIM: 0.2
};


/***/ }),

/***/ "cqoG":
/*!***************************************!*\
  !*** ./node_modules/sha.js/sha224.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/**
 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
 * in FIPS 180-2
 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 *
 */

var inherits = __webpack_require__(/*! inherits */ "P7XM")
var Sha256 = __webpack_require__(/*! ./sha256 */ "olUY")
var Hash = __webpack_require__(/*! ./hash */ "tnIz")
var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer

var W = new Array(64)

function Sha224 () {
  this.init()

  this._w = W // new Array(64)

  Hash.call(this, 64, 56)
}

inherits(Sha224, Sha256)

Sha224.prototype.init = function () {
  this._a = 0xc1059ed8
  this._b = 0x367cd507
  this._c = 0x3070dd17
  this._d = 0xf70e5939
  this._e = 0xffc00b31
  this._f = 0x68581511
  this._g = 0x64f98fa7
  this._h = 0xbefa4fa4

  return this
}

Sha224.prototype._hash = function () {
  var H = Buffer.allocUnsafe(28)

  H.writeInt32BE(this._a, 0)
  H.writeInt32BE(this._b, 4)
  H.writeInt32BE(this._c, 8)
  H.writeInt32BE(this._d, 12)
  H.writeInt32BE(this._e, 16)
  H.writeInt32BE(this._f, 20)
  H.writeInt32BE(this._g, 24)

  return H
}

module.exports = Sha224


/***/ }),

/***/ "ctBr":
/*!*****************************************************!*\
  !*** ./node_modules/react/cjs/react.development.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/** @license React v16.4.2
 * react.development.js
 *
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */





if (true) {
  (function() {
'use strict';

var _assign = __webpack_require__(/*! object-assign */ "MgzW");
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");
var emptyObject = __webpack_require__(/*! fbjs/lib/emptyObject */ "t33a");
var warning = __webpack_require__(/*! fbjs/lib/warning */ "2mcs");
var emptyFunction = __webpack_require__(/*! fbjs/lib/emptyFunction */ "ohE5");
var checkPropTypes = __webpack_require__(/*! prop-types/checkPropTypes */ "oVyQ");

// TODO: this is special because it gets imported during build.

var ReactVersion = '16.4.2';

// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var hasSymbol = typeof Symbol === 'function' && Symbol.for;

var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace;
var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;
var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
var REACT_TIMEOUT_TYPE = hasSymbol ? Symbol.for('react.timeout') : 0xead1;

var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator';

function getIteratorFn(maybeIterable) {
  if (maybeIterable === null || typeof maybeIterable === 'undefined') {
    return null;
  }
  var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
  if (typeof maybeIterator === 'function') {
    return maybeIterator;
  }
  return null;
}

// Relying on the `invariant()` implementation lets us
// have preserve the format and params in the www builds.

// Exports ReactDOM.createRoot


// Experimental error-boundary API that can recover from errors within a single
// render phase

// Suspense
var enableSuspense = false;
// Helps identify side effects in begin-phase lifecycle hooks and setState reducers:


// In some cases, StrictMode should also double-render lifecycles.
// This can be confusing for tests though,
// And it can be bad for performance in production.
// This feature flag can be used to control the behavior:


// To preserve the "Pause on caught exceptions" behavior of the debugger, we
// replay the begin phase of a failed component inside invokeGuardedCallback.


// Warn about deprecated, async-unsafe lifecycles; relates to RFC #6:


// Warn about legacy context API


// Gather advanced timing metrics for Profiler subtrees.


// Only used in www builds.

/**
 * Forked from fbjs/warning:
 * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
 *
 * Only change is we use console.warn instead of console.error,
 * and do nothing when 'console' is not supported.
 * This really simplifies the code.
 * ---
 * Similar to invariant but only logs a warning if the condition is not met.
 * This can be used to log issues in development environments in critical
 * paths. Removing the logging code for production environments will keep the
 * same logic and follow the same code paths.
 */

var lowPriorityWarning = function () {};

{
  var printWarning = function (format) {
    for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      args[_key - 1] = arguments[_key];
    }

    var argIndex = 0;
    var message = 'Warning: ' + format.replace(/%s/g, function () {
      return args[argIndex++];
    });
    if (typeof console !== 'undefined') {
      console.warn(message);
    }
    try {
      // --- Welcome to debugging React ---
      // This error was thrown as a convenience so that you can use this stack
      // to find the callsite that caused this warning to fire.
      throw new Error(message);
    } catch (x) {}
  };

  lowPriorityWarning = function (condition, format) {
    if (format === undefined) {
      throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
    }
    if (!condition) {
      for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
        args[_key2 - 2] = arguments[_key2];
      }

      printWarning.apply(undefined, [format].concat(args));
    }
  };
}

var lowPriorityWarning$1 = lowPriorityWarning;

var didWarnStateUpdateForUnmountedComponent = {};

function warnNoop(publicInstance, callerName) {
  {
    var _constructor = publicInstance.constructor;
    var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass';
    var warningKey = componentName + '.' + callerName;
    if (didWarnStateUpdateForUnmountedComponent[warningKey]) {
      return;
    }
    warning(false, "Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName);
    didWarnStateUpdateForUnmountedComponent[warningKey] = true;
  }
}

/**
 * This is the abstract API for an update queue.
 */
var ReactNoopUpdateQueue = {
  /**
   * Checks whether or not this composite component is mounted.
   * @param {ReactClass} publicInstance The instance we want to test.
   * @return {boolean} True if mounted, false otherwise.
   * @protected
   * @final
   */
  isMounted: function (publicInstance) {
    return false;
  },

  /**
   * Forces an update. This should only be invoked when it is known with
   * certainty that we are **not** in a DOM transaction.
   *
   * You may want to call this when you know that some deeper aspect of the
   * component's state has changed but `setState` was not called.
   *
   * This will not invoke `shouldComponentUpdate`, but it will invoke
   * `componentWillUpdate` and `componentDidUpdate`.
   *
   * @param {ReactClass} publicInstance The instance that should rerender.
   * @param {?function} callback Called after component is updated.
   * @param {?string} callerName name of the calling function in the public API.
   * @internal
   */
  enqueueForceUpdate: function (publicInstance, callback, callerName) {
    warnNoop(publicInstance, 'forceUpdate');
  },

  /**
   * Replaces all of the state. Always use this or `setState` to mutate state.
   * You should treat `this.state` as immutable.
   *
   * There is no guarantee that `this.state` will be immediately updated, so
   * accessing `this.state` after calling this method may return the old value.
   *
   * @param {ReactClass} publicInstance The instance that should rerender.
   * @param {object} completeState Next state.
   * @param {?function} callback Called after component is updated.
   * @param {?string} callerName name of the calling function in the public API.
   * @internal
   */
  enqueueReplaceState: function (publicInstance, completeState, callback, callerName) {
    warnNoop(publicInstance, 'replaceState');
  },

  /**
   * Sets a subset of the state. This only exists because _pendingState is
   * internal. This provides a merging strategy that is not available to deep
   * properties which is confusing. TODO: Expose pendingState or don't use it
   * during the merge.
   *
   * @param {ReactClass} publicInstance The instance that should rerender.
   * @param {object} partialState Next partial state to be merged with state.
   * @param {?function} callback Called after component is updated.
   * @param {?string} Name of the calling function in the public API.
   * @internal
   */
  enqueueSetState: function (publicInstance, partialState, callback, callerName) {
    warnNoop(publicInstance, 'setState');
  }
};

/**
 * Base class helpers for the updating state of a component.
 */
function Component(props, context, updater) {
  this.props = props;
  this.context = context;
  this.refs = emptyObject;
  // We initialize the default updater but the real one gets injected by the
  // renderer.
  this.updater = updater || ReactNoopUpdateQueue;
}

Component.prototype.isReactComponent = {};

/**
 * Sets a subset of the state. Always use this to mutate
 * state. You should treat `this.state` as immutable.
 *
 * There is no guarantee that `this.state` will be immediately updated, so
 * accessing `this.state` after calling this method may return the old value.
 *
 * There is no guarantee that calls to `setState` will run synchronously,
 * as they may eventually be batched together.  You can provide an optional
 * callback that will be executed when the call to setState is actually
 * completed.
 *
 * When a function is provided to setState, it will be called at some point in
 * the future (not synchronously). It will be called with the up to date
 * component arguments (state, props, context). These values can be different
 * from this.* because your function may be called after receiveProps but before
 * shouldComponentUpdate, and this new state, props, and context will not yet be
 * assigned to this.
 *
 * @param {object|function} partialState Next partial state or function to
 *        produce next partial state to be merged with current state.
 * @param {?function} callback Called after state is updated.
 * @final
 * @protected
 */
Component.prototype.setState = function (partialState, callback) {
  !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.') : void 0;
  this.updater.enqueueSetState(this, partialState, callback, 'setState');
};

/**
 * Forces an update. This should only be invoked when it is known with
 * certainty that we are **not** in a DOM transaction.
 *
 * You may want to call this when you know that some deeper aspect of the
 * component's state has changed but `setState` was not called.
 *
 * This will not invoke `shouldComponentUpdate`, but it will invoke
 * `componentWillUpdate` and `componentDidUpdate`.
 *
 * @param {?function} callback Called after update is complete.
 * @final
 * @protected
 */
Component.prototype.forceUpdate = function (callback) {
  this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
};

/**
 * Deprecated APIs. These APIs used to exist on classic React classes but since
 * we would like to deprecate them, we're not going to move them over to this
 * modern base class. Instead, we define a getter that warns if it's accessed.
 */
{
  var deprecatedAPIs = {
    isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
    replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).']
  };
  var defineDeprecationWarning = function (methodName, info) {
    Object.defineProperty(Component.prototype, methodName, {
      get: function () {
        lowPriorityWarning$1(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]);
        return undefined;
      }
    });
  };
  for (var fnName in deprecatedAPIs) {
    if (deprecatedAPIs.hasOwnProperty(fnName)) {
      defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
    }
  }
}

function ComponentDummy() {}
ComponentDummy.prototype = Component.prototype;

/**
 * Convenience component with default shallow equality check for sCU.
 */
function PureComponent(props, context, updater) {
  this.props = props;
  this.context = context;
  this.refs = emptyObject;
  this.updater = updater || ReactNoopUpdateQueue;
}

var pureComponentPrototype = PureComponent.prototype = new ComponentDummy();
pureComponentPrototype.constructor = PureComponent;
// Avoid an extra prototype jump for these methods.
_assign(pureComponentPrototype, Component.prototype);
pureComponentPrototype.isPureReactComponent = true;

// an immutable object with a single mutable value
function createRef() {
  var refObject = {
    current: null
  };
  {
    Object.seal(refObject);
  }
  return refObject;
}

/**
 * Keeps track of the current owner.
 *
 * The current owner is the component who should own any components that are
 * currently being constructed.
 */
var ReactCurrentOwner = {
  /**
   * @internal
   * @type {ReactComponent}
   */
  current: null
};

var hasOwnProperty = Object.prototype.hasOwnProperty;

var RESERVED_PROPS = {
  key: true,
  ref: true,
  __self: true,
  __source: true
};

var specialPropKeyWarningShown = void 0;
var specialPropRefWarningShown = void 0;

function hasValidRef(config) {
  {
    if (hasOwnProperty.call(config, 'ref')) {
      var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
      if (getter && getter.isReactWarning) {
        return false;
      }
    }
  }
  return config.ref !== undefined;
}

function hasValidKey(config) {
  {
    if (hasOwnProperty.call(config, 'key')) {
      var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
      if (getter && getter.isReactWarning) {
        return false;
      }
    }
  }
  return config.key !== undefined;
}

function defineKeyPropWarningGetter(props, displayName) {
  var warnAboutAccessingKey = function () {
    if (!specialPropKeyWarningShown) {
      specialPropKeyWarningShown = true;
      warning(false, '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName);
    }
  };
  warnAboutAccessingKey.isReactWarning = true;
  Object.defineProperty(props, 'key', {
    get: warnAboutAccessingKey,
    configurable: true
  });
}

function defineRefPropWarningGetter(props, displayName) {
  var warnAboutAccessingRef = function () {
    if (!specialPropRefWarningShown) {
      specialPropRefWarningShown = true;
      warning(false, '%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName);
    }
  };
  warnAboutAccessingRef.isReactWarning = true;
  Object.defineProperty(props, 'ref', {
    get: warnAboutAccessingRef,
    configurable: true
  });
}

/**
 * Factory method to create a new React element. This no longer adheres to
 * the class pattern, so do not use new to call it. Also, no instanceof check
 * will work. Instead test $$typeof field against Symbol.for('react.element') to check
 * if something is a React Element.
 *
 * @param {*} type
 * @param {*} key
 * @param {string|object} ref
 * @param {*} self A *temporary* helper to detect places where `this` is
 * different from the `owner` when React.createElement is called, so that we
 * can warn. We want to get rid of owner and replace string `ref`s with arrow
 * functions, and as long as `this` and owner are the same, there will be no
 * change in behavior.
 * @param {*} source An annotation object (added by a transpiler or otherwise)
 * indicating filename, line number, and/or other information.
 * @param {*} owner
 * @param {*} props
 * @internal
 */
var ReactElement = function (type, key, ref, self, source, owner, props) {
  var element = {
    // This tag allows us to uniquely identify this as a React Element
    $$typeof: REACT_ELEMENT_TYPE,

    // Built-in properties that belong on the element
    type: type,
    key: key,
    ref: ref,
    props: props,

    // Record the component responsible for creating this element.
    _owner: owner
  };

  {
    // The validation flag is currently mutative. We put it on
    // an external backing store so that we can freeze the whole object.
    // This can be replaced with a WeakMap once they are implemented in
    // commonly used development environments.
    element._store = {};

    // To make comparing ReactElements easier for testing purposes, we make
    // the validation flag non-enumerable (where possible, which should
    // include every environment we run tests in), so the test framework
    // ignores it.
    Object.defineProperty(element._store, 'validated', {
      configurable: false,
      enumerable: false,
      writable: true,
      value: false
    });
    // self and source are DEV only properties.
    Object.defineProperty(element, '_self', {
      configurable: false,
      enumerable: false,
      writable: false,
      value: self
    });
    // Two elements created in two different places should be considered
    // equal for testing purposes and therefore we hide it from enumeration.
    Object.defineProperty(element, '_source', {
      configurable: false,
      enumerable: false,
      writable: false,
      value: source
    });
    if (Object.freeze) {
      Object.freeze(element.props);
      Object.freeze(element);
    }
  }

  return element;
};

/**
 * Create and return a new ReactElement of the given type.
 * See https://reactjs.org/docs/react-api.html#createelement
 */
function createElement(type, config, children) {
  var propName = void 0;

  // Reserved names are extracted
  var props = {};

  var key = null;
  var ref = null;
  var self = null;
  var source = null;

  if (config != null) {
    if (hasValidRef(config)) {
      ref = config.ref;
    }
    if (hasValidKey(config)) {
      key = '' + config.key;
    }

    self = config.__self === undefined ? null : config.__self;
    source = config.__source === undefined ? null : config.__source;
    // Remaining properties are added to a new props object
    for (propName in config) {
      if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
        props[propName] = config[propName];
      }
    }
  }

  // Children can be more than one argument, and those are transferred onto
  // the newly allocated props object.
  var childrenLength = arguments.length - 2;
  if (childrenLength === 1) {
    props.children = children;
  } else if (childrenLength > 1) {
    var childArray = Array(childrenLength);
    for (var i = 0; i < childrenLength; i++) {
      childArray[i] = arguments[i + 2];
    }
    {
      if (Object.freeze) {
        Object.freeze(childArray);
      }
    }
    props.children = childArray;
  }

  // Resolve default props
  if (type && type.defaultProps) {
    var defaultProps = type.defaultProps;
    for (propName in defaultProps) {
      if (props[propName] === undefined) {
        props[propName] = defaultProps[propName];
      }
    }
  }
  {
    if (key || ref) {
      if (typeof props.$$typeof === 'undefined' || props.$$typeof !== REACT_ELEMENT_TYPE) {
        var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
        if (key) {
          defineKeyPropWarningGetter(props, displayName);
        }
        if (ref) {
          defineRefPropWarningGetter(props, displayName);
        }
      }
    }
  }
  return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
}

/**
 * Return a function that produces ReactElements of a given type.
 * See https://reactjs.org/docs/react-api.html#createfactory
 */


function cloneAndReplaceKey(oldElement, newKey) {
  var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);

  return newElement;
}

/**
 * Clone and return a new ReactElement using element as the starting point.
 * See https://reactjs.org/docs/react-api.html#cloneelement
 */
function cloneElement(element, config, children) {
  !!(element === null || element === undefined) ? invariant(false, 'React.cloneElement(...): The argument must be a React element, but you passed %s.', element) : void 0;

  var propName = void 0;

  // Original props are copied
  var props = _assign({}, element.props);

  // Reserved names are extracted
  var key = element.key;
  var ref = element.ref;
  // Self is preserved since the owner is preserved.
  var self = element._self;
  // Source is preserved since cloneElement is unlikely to be targeted by a
  // transpiler, and the original source is probably a better indicator of the
  // true owner.
  var source = element._source;

  // Owner will be preserved, unless ref is overridden
  var owner = element._owner;

  if (config != null) {
    if (hasValidRef(config)) {
      // Silently steal the ref from the parent.
      ref = config.ref;
      owner = ReactCurrentOwner.current;
    }
    if (hasValidKey(config)) {
      key = '' + config.key;
    }

    // Remaining properties override existing props
    var defaultProps = void 0;
    if (element.type && element.type.defaultProps) {
      defaultProps = element.type.defaultProps;
    }
    for (propName in config) {
      if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
        if (config[propName] === undefined && defaultProps !== undefined) {
          // Resolve default props
          props[propName] = defaultProps[propName];
        } else {
          props[propName] = config[propName];
        }
      }
    }
  }

  // Children can be more than one argument, and those are transferred onto
  // the newly allocated props object.
  var childrenLength = arguments.length - 2;
  if (childrenLength === 1) {
    props.children = children;
  } else if (childrenLength > 1) {
    var childArray = Array(childrenLength);
    for (var i = 0; i < childrenLength; i++) {
      childArray[i] = arguments[i + 2];
    }
    props.children = childArray;
  }

  return ReactElement(element.type, key, ref, self, source, owner, props);
}

/**
 * Verifies the object is a ReactElement.
 * See https://reactjs.org/docs/react-api.html#isvalidelement
 * @param {?object} object
 * @return {boolean} True if `object` is a valid component.
 * @final
 */
function isValidElement(object) {
  return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}

var ReactDebugCurrentFrame = {};

{
  // Component that is being worked on
  ReactDebugCurrentFrame.getCurrentStack = null;

  ReactDebugCurrentFrame.getStackAddendum = function () {
    var impl = ReactDebugCurrentFrame.getCurrentStack;
    if (impl) {
      return impl();
    }
    return null;
  };
}

var SEPARATOR = '.';
var SUBSEPARATOR = ':';

/**
 * Escape and wrap key so it is safe to use as a reactid
 *
 * @param {string} key to be escaped.
 * @return {string} the escaped key.
 */
function escape(key) {
  var escapeRegex = /[=:]/g;
  var escaperLookup = {
    '=': '=0',
    ':': '=2'
  };
  var escapedString = ('' + key).replace(escapeRegex, function (match) {
    return escaperLookup[match];
  });

  return '$' + escapedString;
}

/**
 * TODO: Test that a single child and an array with one item have the same key
 * pattern.
 */

var didWarnAboutMaps = false;

var userProvidedKeyEscapeRegex = /\/+/g;
function escapeUserProvidedKey(text) {
  return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/');
}

var POOL_SIZE = 10;
var traverseContextPool = [];
function getPooledTraverseContext(mapResult, keyPrefix, mapFunction, mapContext) {
  if (traverseContextPool.length) {
    var traverseContext = traverseContextPool.pop();
    traverseContext.result = mapResult;
    traverseContext.keyPrefix = keyPrefix;
    traverseContext.func = mapFunction;
    traverseContext.context = mapContext;
    traverseContext.count = 0;
    return traverseContext;
  } else {
    return {
      result: mapResult,
      keyPrefix: keyPrefix,
      func: mapFunction,
      context: mapContext,
      count: 0
    };
  }
}

function releaseTraverseContext(traverseContext) {
  traverseContext.result = null;
  traverseContext.keyPrefix = null;
  traverseContext.func = null;
  traverseContext.context = null;
  traverseContext.count = 0;
  if (traverseContextPool.length < POOL_SIZE) {
    traverseContextPool.push(traverseContext);
  }
}

/**
 * @param {?*} children Children tree container.
 * @param {!string} nameSoFar Name of the key path so far.
 * @param {!function} callback Callback to invoke with each child found.
 * @param {?*} traverseContext Used to pass information throughout the traversal
 * process.
 * @return {!number} The number of children in this subtree.
 */
function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) {
  var type = typeof children;

  if (type === 'undefined' || type === 'boolean') {
    // All of the above are perceived as null.
    children = null;
  }

  var invokeCallback = false;

  if (children === null) {
    invokeCallback = true;
  } else {
    switch (type) {
      case 'string':
      case 'number':
        invokeCallback = true;
        break;
      case 'object':
        switch (children.$$typeof) {
          case REACT_ELEMENT_TYPE:
          case REACT_PORTAL_TYPE:
            invokeCallback = true;
        }
    }
  }

  if (invokeCallback) {
    callback(traverseContext, children,
    // If it's the only child, treat the name as if it was wrapped in an array
    // so that it's consistent if the number of children grows.
    nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar);
    return 1;
  }

  var child = void 0;
  var nextName = void 0;
  var subtreeCount = 0; // Count of children found in the current subtree.
  var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;

  if (Array.isArray(children)) {
    for (var i = 0; i < children.length; i++) {
      child = children[i];
      nextName = nextNamePrefix + getComponentKey(child, i);
      subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
    }
  } else {
    var iteratorFn = getIteratorFn(children);
    if (typeof iteratorFn === 'function') {
      {
        // Warn about using Maps as children
        if (iteratorFn === children.entries) {
          !didWarnAboutMaps ? warning(false, 'Using Maps as children is unsupported and will likely yield ' + 'unexpected results. Convert it to a sequence/iterable of keyed ' + 'ReactElements instead.%s', ReactDebugCurrentFrame.getStackAddendum()) : void 0;
          didWarnAboutMaps = true;
        }
      }

      var iterator = iteratorFn.call(children);
      var step = void 0;
      var ii = 0;
      while (!(step = iterator.next()).done) {
        child = step.value;
        nextName = nextNamePrefix + getComponentKey(child, ii++);
        subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
      }
    } else if (type === 'object') {
      var addendum = '';
      {
        addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + ReactDebugCurrentFrame.getStackAddendum();
      }
      var childrenString = '' + children;
      invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum);
    }
  }

  return subtreeCount;
}

/**
 * Traverses children that are typically specified as `props.children`, but
 * might also be specified through attributes:
 *
 * - `traverseAllChildren(this.props.children, ...)`
 * - `traverseAllChildren(this.props.leftPanelChildren, ...)`
 *
 * The `traverseContext` is an optional argument that is passed through the
 * entire traversal. It can be used to store accumulations or anything else that
 * the callback might find relevant.
 *
 * @param {?*} children Children tree object.
 * @param {!function} callback To invoke upon traversing each child.
 * @param {?*} traverseContext Context for traversal.
 * @return {!number} The number of children in this subtree.
 */
function traverseAllChildren(children, callback, traverseContext) {
  if (children == null) {
    return 0;
  }

  return traverseAllChildrenImpl(children, '', callback, traverseContext);
}

/**
 * Generate a key string that identifies a component within a set.
 *
 * @param {*} component A component that could contain a manual key.
 * @param {number} index Index that is used if a manual key is not provided.
 * @return {string}
 */
function getComponentKey(component, index) {
  // Do some typechecking here since we call this blindly. We want to ensure
  // that we don't block potential future ES APIs.
  if (typeof component === 'object' && component !== null && component.key != null) {
    // Explicit key
    return escape(component.key);
  }
  // Implicit key determined by the index in the set
  return index.toString(36);
}

function forEachSingleChild(bookKeeping, child, name) {
  var func = bookKeeping.func,
      context = bookKeeping.context;

  func.call(context, child, bookKeeping.count++);
}

/**
 * Iterates through children that are typically specified as `props.children`.
 *
 * See https://reactjs.org/docs/react-api.html#reactchildrenforeach
 *
 * The provided forEachFunc(child, index) will be called for each
 * leaf child.
 *
 * @param {?*} children Children tree container.
 * @param {function(*, int)} forEachFunc
 * @param {*} forEachContext Context for forEachContext.
 */
function forEachChildren(children, forEachFunc, forEachContext) {
  if (children == null) {
    return children;
  }
  var traverseContext = getPooledTraverseContext(null, null, forEachFunc, forEachContext);
  traverseAllChildren(children, forEachSingleChild, traverseContext);
  releaseTraverseContext(traverseContext);
}

function mapSingleChildIntoContext(bookKeeping, child, childKey) {
  var result = bookKeeping.result,
      keyPrefix = bookKeeping.keyPrefix,
      func = bookKeeping.func,
      context = bookKeeping.context;


  var mappedChild = func.call(context, child, bookKeeping.count++);
  if (Array.isArray(mappedChild)) {
    mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument);
  } else if (mappedChild != null) {
    if (isValidElement(mappedChild)) {
      mappedChild = cloneAndReplaceKey(mappedChild,
      // Keep both the (mapped) and old keys if they differ, just as
      // traverseAllChildren used to do for objects as children
      keyPrefix + (mappedChild.key && (!child || child.key !== mappedChild.key) ? escapeUserProvidedKey(mappedChild.key) + '/' : '') + childKey);
    }
    result.push(mappedChild);
  }
}

function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) {
  var escapedPrefix = '';
  if (prefix != null) {
    escapedPrefix = escapeUserProvidedKey(prefix) + '/';
  }
  var traverseContext = getPooledTraverseContext(array, escapedPrefix, func, context);
  traverseAllChildren(children, mapSingleChildIntoContext, traverseContext);
  releaseTraverseContext(traverseContext);
}

/**
 * Maps children that are typically specified as `props.children`.
 *
 * See https://reactjs.org/docs/react-api.html#reactchildrenmap
 *
 * The provided mapFunction(child, key, index) will be called for each
 * leaf child.
 *
 * @param {?*} children Children tree container.
 * @param {function(*, int)} func The map function.
 * @param {*} context Context for mapFunction.
 * @return {object} Object containing the ordered map of results.
 */
function mapChildren(children, func, context) {
  if (children == null) {
    return children;
  }
  var result = [];
  mapIntoWithKeyPrefixInternal(children, result, null, func, context);
  return result;
}

/**
 * Count the number of children that are typically specified as
 * `props.children`.
 *
 * See https://reactjs.org/docs/react-api.html#reactchildrencount
 *
 * @param {?*} children Children tree container.
 * @return {number} The number of children.
 */
function countChildren(children) {
  return traverseAllChildren(children, emptyFunction.thatReturnsNull, null);
}

/**
 * Flatten a children object (typically specified as `props.children`) and
 * return an array with appropriately re-keyed children.
 *
 * See https://reactjs.org/docs/react-api.html#reactchildrentoarray
 */
function toArray(children) {
  var result = [];
  mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument);
  return result;
}

/**
 * Returns the first child in a collection of children and verifies that there
 * is only one child in the collection.
 *
 * See https://reactjs.org/docs/react-api.html#reactchildrenonly
 *
 * The current implementation of this function assumes that a single child gets
 * passed without a wrapper, but the purpose of this helper function is to
 * abstract away the particular structure of children.
 *
 * @param {?object} children Child collection structure.
 * @return {ReactElement} The first and only `ReactElement` contained in the
 * structure.
 */
function onlyChild(children) {
  !isValidElement(children) ? invariant(false, 'React.Children.only expected to receive a single React element child.') : void 0;
  return children;
}

function createContext(defaultValue, calculateChangedBits) {
  if (calculateChangedBits === undefined) {
    calculateChangedBits = null;
  } else {
    {
      !(calculateChangedBits === null || typeof calculateChangedBits === 'function') ? warning(false, 'createContext: Expected the optional second argument to be a ' + 'function. Instead received: %s', calculateChangedBits) : void 0;
    }
  }

  var context = {
    $$typeof: REACT_CONTEXT_TYPE,
    _calculateChangedBits: calculateChangedBits,
    _defaultValue: defaultValue,
    _currentValue: defaultValue,
    // As a workaround to support multiple concurrent renderers, we categorize
    // some renderers as primary and others as secondary. We only expect
    // there to be two concurrent renderers at most: React Native (primary) and
    // Fabric (secondary); React DOM (primary) and React ART (secondary).
    // Secondary renderers store their context values on separate fields.
    _currentValue2: defaultValue,
    _changedBits: 0,
    _changedBits2: 0,
    // These are circular
    Provider: null,
    Consumer: null
  };

  context.Provider = {
    $$typeof: REACT_PROVIDER_TYPE,
    _context: context
  };
  context.Consumer = context;

  {
    context._currentRenderer = null;
    context._currentRenderer2 = null;
  }

  return context;
}

function forwardRef(render) {
  {
    !(typeof render === 'function') ? warning(false, 'forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render) : void 0;

    if (render != null) {
      !(render.defaultProps == null && render.propTypes == null) ? warning(false, 'forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?') : void 0;
    }
  }

  return {
    $$typeof: REACT_FORWARD_REF_TYPE,
    render: render
  };
}

var describeComponentFrame = function (name, source, ownerName) {
  return '\n    in ' + (name || 'Unknown') + (source ? ' (at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' + source.lineNumber + ')' : ownerName ? ' (created by ' + ownerName + ')' : '');
};

function isValidElementType(type) {
  return typeof type === 'string' || typeof type === 'function' ||
  // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
  type === REACT_FRAGMENT_TYPE || type === REACT_ASYNC_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_TIMEOUT_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE);
}

function getComponentName(fiber) {
  var type = fiber.type;

  if (typeof type === 'function') {
    return type.displayName || type.name;
  }
  if (typeof type === 'string') {
    return type;
  }
  switch (type) {
    case REACT_ASYNC_MODE_TYPE:
      return 'AsyncMode';
    case REACT_CONTEXT_TYPE:
      return 'Context.Consumer';
    case REACT_FRAGMENT_TYPE:
      return 'ReactFragment';
    case REACT_PORTAL_TYPE:
      return 'ReactPortal';
    case REACT_PROFILER_TYPE:
      return 'Profiler(' + fiber.pendingProps.id + ')';
    case REACT_PROVIDER_TYPE:
      return 'Context.Provider';
    case REACT_STRICT_MODE_TYPE:
      return 'StrictMode';
    case REACT_TIMEOUT_TYPE:
      return 'Timeout';
  }
  if (typeof type === 'object' && type !== null) {
    switch (type.$$typeof) {
      case REACT_FORWARD_REF_TYPE:
        var functionName = type.render.displayName || type.render.name || '';
        return functionName !== '' ? 'ForwardRef(' + functionName + ')' : 'ForwardRef';
    }
  }
  return null;
}

/**
 * ReactElementValidator provides a wrapper around a element factory
 * which validates the props passed to the element. This is intended to be
 * used only in DEV and could be replaced by a static type checker for languages
 * that support it.
 */

var currentlyValidatingElement = void 0;
var propTypesMisspellWarningShown = void 0;

var getDisplayName = function () {};
var getStackAddendum = function () {};

{
  currentlyValidatingElement = null;

  propTypesMisspellWarningShown = false;

  getDisplayName = function (element) {
    if (element == null) {
      return '#empty';
    } else if (typeof element === 'string' || typeof element === 'number') {
      return '#text';
    } else if (typeof element.type === 'string') {
      return element.type;
    }

    var type = element.type;
    if (type === REACT_FRAGMENT_TYPE) {
      return 'React.Fragment';
    } else if (typeof type === 'object' && type !== null && type.$$typeof === REACT_FORWARD_REF_TYPE) {
      var functionName = type.render.displayName || type.render.name || '';
      return functionName !== '' ? 'ForwardRef(' + functionName + ')' : 'ForwardRef';
    } else {
      return type.displayName || type.name || 'Unknown';
    }
  };

  getStackAddendum = function () {
    var stack = '';
    if (currentlyValidatingElement) {
      var name = getDisplayName(currentlyValidatingElement);
      var owner = currentlyValidatingElement._owner;
      stack += describeComponentFrame(name, currentlyValidatingElement._source, owner && getComponentName(owner));
    }
    stack += ReactDebugCurrentFrame.getStackAddendum() || '';
    return stack;
  };
}

function getDeclarationErrorAddendum() {
  if (ReactCurrentOwner.current) {
    var name = getComponentName(ReactCurrentOwner.current);
    if (name) {
      return '\n\nCheck the render method of `' + name + '`.';
    }
  }
  return '';
}

function getSourceInfoErrorAddendum(elementProps) {
  if (elementProps !== null && elementProps !== undefined && elementProps.__source !== undefined) {
    var source = elementProps.__source;
    var fileName = source.fileName.replace(/^.*[\\\/]/, '');
    var lineNumber = source.lineNumber;
    return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
  }
  return '';
}

/**
 * Warn if there's no key explicitly set on dynamic arrays of children or
 * object keys are not valid. This allows us to keep track of children between
 * updates.
 */
var ownerHasKeyUseWarning = {};

function getCurrentComponentErrorInfo(parentType) {
  var info = getDeclarationErrorAddendum();

  if (!info) {
    var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
    if (parentName) {
      info = '\n\nCheck the top-level render call using <' + parentName + '>.';
    }
  }
  return info;
}

/**
 * Warn if the element doesn't have an explicit key assigned to it.
 * This element is in an array. The array could grow and shrink or be
 * reordered. All children that haven't already been validated are required to
 * have a "key" property assigned to it. Error statuses are cached so a warning
 * will only be shown once.
 *
 * @internal
 * @param {ReactElement} element Element that requires a key.
 * @param {*} parentType element's parent's type.
 */
function validateExplicitKey(element, parentType) {
  if (!element._store || element._store.validated || element.key != null) {
    return;
  }
  element._store.validated = true;

  var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
  if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
    return;
  }
  ownerHasKeyUseWarning[currentComponentErrorInfo] = true;

  // Usually the current owner is the offender, but if it accepts children as a
  // property, it may be the creator of the child that's responsible for
  // assigning it a key.
  var childOwner = '';
  if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
    // Give the component that originally created this child.
    childOwner = ' It was passed a child from ' + getComponentName(element._owner) + '.';
  }

  currentlyValidatingElement = element;
  {
    warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s See https://fb.me/react-warning-keys for more information.%s', currentComponentErrorInfo, childOwner, getStackAddendum());
  }
  currentlyValidatingElement = null;
}

/**
 * Ensure that every element either is passed in a static location, in an
 * array with an explicit keys property defined, or in an object literal
 * with valid key property.
 *
 * @internal
 * @param {ReactNode} node Statically passed child of any type.
 * @param {*} parentType node's parent's type.
 */
function validateChildKeys(node, parentType) {
  if (typeof node !== 'object') {
    return;
  }
  if (Array.isArray(node)) {
    for (var i = 0; i < node.length; i++) {
      var child = node[i];
      if (isValidElement(child)) {
        validateExplicitKey(child, parentType);
      }
    }
  } else if (isValidElement(node)) {
    // This element was passed in a valid location.
    if (node._store) {
      node._store.validated = true;
    }
  } else if (node) {
    var iteratorFn = getIteratorFn(node);
    if (typeof iteratorFn === 'function') {
      // Entry iterators used to provide implicit keys,
      // but now we print a separate warning for them later.
      if (iteratorFn !== node.entries) {
        var iterator = iteratorFn.call(node);
        var step = void 0;
        while (!(step = iterator.next()).done) {
          if (isValidElement(step.value)) {
            validateExplicitKey(step.value, parentType);
          }
        }
      }
    }
  }
}

/**
 * Given an element, validate that its props follow the propTypes definition,
 * provided by the type.
 *
 * @param {ReactElement} element
 */
function validatePropTypes(element) {
  var type = element.type;
  var name = void 0,
      propTypes = void 0;
  if (typeof type === 'function') {
    // Class or functional component
    name = type.displayName || type.name;
    propTypes = type.propTypes;
  } else if (typeof type === 'object' && type !== null && type.$$typeof === REACT_FORWARD_REF_TYPE) {
    // ForwardRef
    var functionName = type.render.displayName || type.render.name || '';
    name = functionName !== '' ? 'ForwardRef(' + functionName + ')' : 'ForwardRef';
    propTypes = type.propTypes;
  } else {
    return;
  }
  if (propTypes) {
    currentlyValidatingElement = element;
    checkPropTypes(propTypes, element.props, 'prop', name, getStackAddendum);
    currentlyValidatingElement = null;
  } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
    propTypesMisspellWarningShown = true;
    warning(false, 'Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', name || 'Unknown');
  }
  if (typeof type.getDefaultProps === 'function') {
    !type.getDefaultProps.isReactClassApproved ? warning(false, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : void 0;
  }
}

/**
 * Given a fragment, validate that it can only be provided with fragment props
 * @param {ReactElement} fragment
 */
function validateFragmentProps(fragment) {
  currentlyValidatingElement = fragment;

  var keys = Object.keys(fragment.props);
  for (var i = 0; i < keys.length; i++) {
    var key = keys[i];
    if (key !== 'children' && key !== 'key') {
      warning(false, 'Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.%s', key, getStackAddendum());
      break;
    }
  }

  if (fragment.ref !== null) {
    warning(false, 'Invalid attribute `ref` supplied to `React.Fragment`.%s', getStackAddendum());
  }

  currentlyValidatingElement = null;
}

function createElementWithValidation(type, props, children) {
  var validType = isValidElementType(type);

  // We warn in this case but don't throw. We expect the element creation to
  // succeed and there will likely be errors in render.
  if (!validType) {
    var info = '';
    if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
      info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
    }

    var sourceInfo = getSourceInfoErrorAddendum(props);
    if (sourceInfo) {
      info += sourceInfo;
    } else {
      info += getDeclarationErrorAddendum();
    }

    info += getStackAddendum() || '';

    var typeString = void 0;
    if (type === null) {
      typeString = 'null';
    } else if (Array.isArray(type)) {
      typeString = 'array';
    } else {
      typeString = typeof type;
    }

    warning(false, 'React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
  }

  var element = createElement.apply(this, arguments);

  // The result can be nullish if a mock or a custom function is used.
  // TODO: Drop this when these are no longer allowed as the type argument.
  if (element == null) {
    return element;
  }

  // Skip key warning if the type isn't valid since our key validation logic
  // doesn't expect a non-string/function type and can throw confusing errors.
  // We don't want exception behavior to differ between dev and prod.
  // (Rendering will throw with a helpful message and as soon as the type is
  // fixed, the key warnings will appear.)
  if (validType) {
    for (var i = 2; i < arguments.length; i++) {
      validateChildKeys(arguments[i], type);
    }
  }

  if (type === REACT_FRAGMENT_TYPE) {
    validateFragmentProps(element);
  } else {
    validatePropTypes(element);
  }

  return element;
}

function createFactoryWithValidation(type) {
  var validatedFactory = createElementWithValidation.bind(null, type);
  validatedFactory.type = type;
  // Legacy hook: remove it
  {
    Object.defineProperty(validatedFactory, 'type', {
      enumerable: false,
      get: function () {
        lowPriorityWarning$1(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.');
        Object.defineProperty(this, 'type', {
          value: type
        });
        return type;
      }
    });
  }

  return validatedFactory;
}

function cloneElementWithValidation(element, props, children) {
  var newElement = cloneElement.apply(this, arguments);
  for (var i = 2; i < arguments.length; i++) {
    validateChildKeys(arguments[i], newElement.type);
  }
  validatePropTypes(newElement);
  return newElement;
}

var React = {
  Children: {
    map: mapChildren,
    forEach: forEachChildren,
    count: countChildren,
    toArray: toArray,
    only: onlyChild
  },

  createRef: createRef,
  Component: Component,
  PureComponent: PureComponent,

  createContext: createContext,
  forwardRef: forwardRef,

  Fragment: REACT_FRAGMENT_TYPE,
  StrictMode: REACT_STRICT_MODE_TYPE,
  unstable_AsyncMode: REACT_ASYNC_MODE_TYPE,
  unstable_Profiler: REACT_PROFILER_TYPE,

  createElement: createElementWithValidation,
  cloneElement: cloneElementWithValidation,
  createFactory: createFactoryWithValidation,
  isValidElement: isValidElement,

  version: ReactVersion,

  __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
    ReactCurrentOwner: ReactCurrentOwner,
    // Used by renderers to avoid bundling object-assign twice in UMD bundles:
    assign: _assign
  }
};

if (enableSuspense) {
  React.Timeout = REACT_TIMEOUT_TYPE;
}

{
  _assign(React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, {
    // These should not be included in production.
    ReactDebugCurrentFrame: ReactDebugCurrentFrame,
    // Shim for React DOM 16.0.0 which still destructured (but not used) this.
    // TODO: remove in React 17.0.
    ReactComponentTreeHook: {}
  });
}



var React$2 = Object.freeze({
	default: React
});

var React$3 = ( React$2 && React ) || React$2;

// TODO: decide on the top-level export form.
// This is hacky but makes it work with both Rollup and Jest.
var react = React$3.default ? React$3.default : React$3;

module.exports = react;
  })();
}


/***/ }),

/***/ "cvCv":
/*!*****************************************!*\
  !*** ./node_modules/lodash/constant.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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;
  };
}

module.exports = constant;


/***/ }),

/***/ "czMo":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/en-il.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var enIl = moment.defineLocale('en-il', {
    months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
    monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
    weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
    weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
    weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd, D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay : '[Today at] LT',
        nextDay : '[Tomorrow at] LT',
        nextWeek : 'dddd [at] LT',
        lastDay : '[Yesterday at] LT',
        lastWeek : '[Last] dddd [at] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'in %s',
        past : '%s ago',
        s : 'a few seconds',
        m : 'a minute',
        mm : '%d minutes',
        h : 'an hour',
        hh : '%d hours',
        d : 'a day',
        dd : '%d days',
        M : 'a month',
        MM : '%d months',
        y : 'a year',
        yy : '%d years'
    },
    dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/,
    ordinal : function (number) {
        var b = number % 10,
            output = (~~(number % 100 / 10) === 1) ? 'th' :
            (b === 1) ? 'st' :
            (b === 2) ? 'nd' :
            (b === 3) ? 'rd' : 'th';
        return number + output;
    }
});

return enIl;

})));


/***/ }),

/***/ "czxZ":
/*!***********************************************!*\
  !*** ./node_modules/domutils/lib/querying.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isTag = __webpack_require__(/*! domelementtype */ "TR4g").isTag;

module.exports = {
	filter: filter,
	find: find,
	findOneChild: findOneChild,
	findOne: findOne,
	existsOne: existsOne,
	findAll: findAll
};

function filter(test, element, recurse, limit){
	if(!Array.isArray(element)) element = [element];

	if(typeof limit !== "number" || !isFinite(limit)){
		limit = Infinity;
	}
	return find(test, element, recurse !== false, limit);
}

function find(test, elems, recurse, limit){
	var result = [], childs;

	for(var i = 0, j = elems.length; i < j; i++){
		if(test(elems[i])){
			result.push(elems[i]);
			if(--limit <= 0) break;
		}

		childs = elems[i].children;
		if(recurse && childs && childs.length > 0){
			childs = find(test, childs, recurse, limit);
			result = result.concat(childs);
			limit -= childs.length;
			if(limit <= 0) break;
		}
	}

	return result;
}

function findOneChild(test, elems){
	for(var i = 0, l = elems.length; i < l; i++){
		if(test(elems[i])) return elems[i];
	}

	return null;
}

function findOne(test, elems){
	var elem = null;

	for(var i = 0, l = elems.length; i < l && !elem; i++){
		if(!isTag(elems[i])){
			continue;
		} else if(test(elems[i])){
			elem = elems[i];
		} else if(elems[i].children.length > 0){
			elem = findOne(test, elems[i].children);
		}
	}

	return elem;
}

function existsOne(test, elems){
	for(var i = 0, l = elems.length; i < l; i++){
		if(
			isTag(elems[i]) && (
				test(elems[i]) || (
					elems[i].children.length > 0 &&
					existsOne(test, elems[i].children)
				)
			)
		){
			return true;
		}
	}

	return false;
}

function findAll(test, rootElems){
	var result = [];
	var stack = rootElems.slice();
	while(stack.length){
		var elem = stack.shift();
		if(!isTag(elem)) continue;
		if (elem.children && elem.children.length > 0) {
			stack.unshift.apply(stack, elem.children);
		}
		if(test(elem)) result.push(elem);
	}
	return result;
}


/***/ }),

/***/ "d+r/":
/*!********************************************************!*\
  !*** ./node_modules/ajv/lib/dotjs/_limitProperties.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate__limitProperties(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $op = $keyword == 'maxProperties' ? '>' : '<';
  out += 'if ( ';
  if ($isData) {
    out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
  }
  out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { ';
  var $errorKeyword = $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should NOT have ';
      if ($keyword == 'maxProperties') {
        out += 'more';
      } else {
        out += 'less';
      }
      out += ' than ';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + ($schema);
      }
      out += ' properties\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}


/***/ }),

/***/ "d17/":
/*!****************************************************!*\
  !*** ./node_modules/ajv/lib/compile/ucs2length.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


// https://mathiasbynens.be/notes/javascript-encoding
// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
module.exports = function ucs2length(str) {
  var length = 0
    , len = str.length
    , pos = 0
    , value;
  while (pos < len) {
    length++;
    value = str.charCodeAt(pos++);
    if (value >= 0xD800 && value <= 0xDBFF && pos < len) {
      // high surrogate, and there is a next character
      value = str.charCodeAt(pos);
      if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate
    }
  }
  return length;
};


/***/ }),

/***/ "d2xu":
/*!**********************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils/lib/spinner.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
/**
 * The spinner class.
 */
class Spinner extends widgets_1.Widget {
    /**
     * Construct a spinner widget.
     */
    constructor() {
        super();
        this.addClass('jp-Spinner');
        this.node.tabIndex = -1;
        let content = document.createElement('div');
        content.className = 'jp-SpinnerContent';
        this.node.appendChild(content);
    }
    /**
     * Handle `'activate-request'` messages.
     */
    onActivateRequest(msg) {
        this.node.focus();
    }
}
exports.Spinner = Spinner;


/***/ }),

/***/ "d4k2":
/*!*****************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/kernel/manager.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const __1 = __webpack_require__(/*! .. */ "S9up");
const kernel_1 = __webpack_require__(/*! ./kernel */ "0ks7");
/**
 * An implementation of a kernel manager.
 */
class KernelManager {
    /**
     * Construct a new kernel manager.
     *
     * @param options - The default options for kernel.
     */
    constructor(options = {}) {
        this._models = [];
        this._kernels = new Set();
        this._specs = null;
        this._isDisposed = false;
        this._modelsTimer = -1;
        this._specsTimer = -1;
        this._isReady = false;
        this._specsChanged = new signaling_1.Signal(this);
        this._runningChanged = new signaling_1.Signal(this);
        this.serverSettings =
            options.serverSettings || __1.ServerConnection.makeSettings();
        // Initialize internal data.
        this._readyPromise = this._refreshSpecs().then(() => {
            return this._refreshRunning();
        });
        // Set up polling.
        this._modelsTimer = setInterval(() => {
            if (typeof document !== 'undefined' && document.hidden) {
                // Don't poll when nobody's looking.
                return;
            }
            this._refreshRunning();
        }, 10000);
        this._specsTimer = setInterval(() => {
            if (typeof document !== 'undefined' && document.hidden) {
                // Don't poll when nobody's looking.
                return;
            }
            this._refreshSpecs();
        }, 61000);
    }
    /**
     * A signal emitted when the specs change.
     */
    get specsChanged() {
        return this._specsChanged;
    }
    /**
     * A signal emitted when the running kernels change.
     */
    get runningChanged() {
        return this._runningChanged;
    }
    /**
     * Test whether the terminal manager is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources used by the manager.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        clearInterval(this._modelsTimer);
        clearInterval(this._specsTimer);
        signaling_1.Signal.clearData(this);
        this._models = [];
    }
    /**
     * Get the most recently fetched kernel specs.
     */
    get specs() {
        return this._specs;
    }
    /**
     * Test whether the manager is ready.
     */
    get isReady() {
        return this._isReady;
    }
    /**
     * A promise that fulfills when the manager is ready.
     */
    get ready() {
        return this._readyPromise;
    }
    /**
     * Create an iterator over the most recent running kernels.
     *
     * @returns A new iterator over the running kernels.
     */
    running() {
        return algorithm_1.iter(this._models);
    }
    /**
     * Force a refresh of the specs from the server.
     *
     * @returns A promise that resolves when the specs are fetched.
     *
     * #### Notes
     * This is intended to be called only in response to a user action,
     * since the manager maintains its internal state.
     */
    refreshSpecs() {
        return this._refreshSpecs();
    }
    /**
     * Force a refresh of the running kernels.
     *
     * @returns A promise that with the list of running sessions.
     *
     * #### Notes
     * This is not typically meant to be called by the user, since the
     * manager maintains its own internal state.
     */
    refreshRunning() {
        return this._refreshRunning();
    }
    /**
     * Start a new kernel.
     *
     * @param options - The kernel options to use.
     *
     * @returns A promise that resolves with the kernel instance.
     *
     * #### Notes
     * The manager `serverSettings` will be always be used.
     */
    startNew(options = {}) {
        let newOptions = Object.assign({}, options, { serverSettings: this.serverSettings });
        return kernel_1.Kernel.startNew(newOptions).then(kernel => {
            this._onStarted(kernel);
            return kernel;
        });
    }
    /**
     * Find a kernel by id.
     *
     * @param id - The id of the target kernel.
     *
     * @returns A promise that resolves with the kernel's model.
     */
    findById(id) {
        return kernel_1.Kernel.findById(id, this.serverSettings);
    }
    /**
     * Connect to an existing kernel.
     *
     * @param model - The model of the target kernel.
     *
     * @returns A promise that resolves with the new kernel instance.
     */
    connectTo(model) {
        let kernel = kernel_1.Kernel.connectTo(model, this.serverSettings);
        this._onStarted(kernel);
        return kernel;
    }
    /**
     * Shut down a kernel by id.
     *
     * @param id - The id of the target kernel.
     *
     * @returns A promise that resolves when the operation is complete.
     *
     * #### Notes
     * This will emit [[runningChanged]] if the running kernels list
     * changes.
     */
    shutdown(id) {
        let index = algorithm_1.ArrayExt.findFirstIndex(this._models, value => value.id === id);
        if (index === -1) {
            return;
        }
        // Proactively remove the model.
        this._models.splice(index, 1);
        this._runningChanged.emit(this._models.slice());
        return kernel_1.Kernel.shutdown(id, this.serverSettings).then(() => {
            let toRemove = [];
            this._kernels.forEach(k => {
                if (k.id === id) {
                    k.dispose();
                    toRemove.push(k);
                }
            });
            toRemove.forEach(k => {
                this._kernels.delete(k);
            });
        });
    }
    /**
     * Shut down all kernels.
     *
     * @returns A promise that resolves when all of the kernels are shut down.
     */
    shutdownAll() {
        // Proactively remove all models.
        let models = this._models;
        if (models.length > 0) {
            this._models = [];
            this._runningChanged.emit([]);
        }
        return this._refreshRunning().then(() => {
            return Promise.all(models.map(model => {
                return kernel_1.Kernel.shutdown(model.id, this.serverSettings).then(() => {
                    let toRemove = [];
                    this._kernels.forEach(k => {
                        k.dispose();
                        toRemove.push(k);
                    });
                    toRemove.forEach(k => {
                        this._kernels.delete(k);
                    });
                });
            })).then(() => {
                return undefined;
            });
        });
    }
    /**
     * Handle a kernel terminating.
     */
    _onTerminated(id) {
        let index = algorithm_1.ArrayExt.findFirstIndex(this._models, value => value.id === id);
        if (index !== -1) {
            this._models.splice(index, 1);
            this._runningChanged.emit(this._models.slice());
        }
    }
    /**
     * Handle a kernel starting.
     */
    _onStarted(kernel) {
        let id = kernel.id;
        this._kernels.add(kernel);
        let index = algorithm_1.ArrayExt.findFirstIndex(this._models, value => value.id === id);
        if (index === -1) {
            this._models.push(kernel.model);
            this._runningChanged.emit(this._models.slice());
        }
        kernel.terminated.connect(() => {
            this._onTerminated(id);
        });
    }
    /**
     * Refresh the specs.
     */
    _refreshSpecs() {
        return kernel_1.Kernel.getSpecs(this.serverSettings).then(specs => {
            if (!coreutils_1.JSONExt.deepEqual(specs, this._specs)) {
                this._specs = specs;
                this._specsChanged.emit(specs);
            }
        });
    }
    /**
     * Refresh the running sessions.
     */
    _refreshRunning() {
        return kernel_1.Kernel.listRunning(this.serverSettings).then(models => {
            this._isReady = true;
            if (!coreutils_1.JSONExt.deepEqual(models, this._models)) {
                let ids = models.map(r => r.id);
                let toRemove = [];
                this._kernels.forEach(k => {
                    if (ids.indexOf(k.id) === -1) {
                        k.dispose();
                        toRemove.push(k);
                    }
                });
                toRemove.forEach(s => {
                    this._kernels.delete(s);
                });
                this._models = models.slice();
                this._runningChanged.emit(models);
            }
        });
    }
}
exports.KernelManager = KernelManager;


/***/ }),

/***/ "dATH":
/*!*************************************************************************!*\
  !*** ./node_modules/react-color/lib/components/slider/SliderPointer.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SliderPointer = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var SliderPointer = exports.SliderPointer = function SliderPointer() {
  var styles = (0, _reactcss2.default)({
    'default': {
      picker: {
        width: '14px',
        height: '14px',
        borderRadius: '6px',
        transform: 'translate(-7px, -1px)',
        backgroundColor: 'rgb(248, 248, 248)',
        boxShadow: '0 1px 4px 0 rgba(0, 0, 0, 0.37)'
      }
    }
  });

  return _react2.default.createElement('div', { style: styles.picker });
};

exports.default = SliderPointer;

/***/ }),

/***/ "dD9F":
/*!**************************************************!*\
  !*** ./node_modules/lodash/_baseIsTypedArray.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseGetTag = __webpack_require__(/*! ./_baseGetTag */ "NykK"),
    isLength = __webpack_require__(/*! ./isLength */ "shjB"),
    isObjectLike = __webpack_require__(/*! ./isObjectLike */ "ExA7");

/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
    arrayTag = '[object Array]',
    boolTag = '[object Boolean]',
    dateTag = '[object Date]',
    errorTag = '[object Error]',
    funcTag = '[object Function]',
    mapTag = '[object Map]',
    numberTag = '[object Number]',
    objectTag = '[object Object]',
    regexpTag = '[object RegExp]',
    setTag = '[object Set]',
    stringTag = '[object String]',
    weakMapTag = '[object WeakMap]';

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 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;

/**
 * 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)];
}

module.exports = baseIsTypedArray;


/***/ }),

/***/ "dMc4":
/*!*****************************************************************************!*\
  !*** ./node_modules/@plotly/draft-js-export-html/lib/helpers/styleToCSS.js ***!
  \*****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});


var VENDOR_PREFIX = /^(moz|ms|o|webkit)-/;

var NUMERIC_STRING = /^\d+$/;
var UPPERCASE_PATTERN = /([A-Z])/g;

// Lifted from:
// https://github.com/facebook/react/blob/ab4ddf64939aebbbc8d31be1022efd56e834c95c/src/renderers/dom/shared/CSSProperty.js
var isUnitlessNumber = {
  animationIterationCount: true,
  borderImageOutset: true,
  borderImageSlice: true,
  borderImageWidth: true,
  boxFlex: true,
  boxFlexGroup: true,
  boxOrdinalGroup: true,
  columnCount: true,
  flex: true,
  flexGrow: true,
  flexPositive: true,
  flexShrink: true,
  flexNegative: true,
  flexOrder: true,
  gridRow: true,
  gridRowEnd: true,
  gridRowSpan: true,
  gridRowStart: true,
  gridColumn: true,
  gridColumnEnd: true,
  gridColumnSpan: true,
  gridColumnStart: true,
  fontWeight: true,
  lineClamp: true,
  lineHeight: true,
  opacity: true,
  order: true,
  orphans: true,
  tabSize: true,
  widows: true,
  zIndex: true,
  zoom: true,
  // SVG-related properties
  fillOpacity: true,
  floodOpacity: true,
  stopOpacity: true,
  strokeDasharray: true,
  strokeDashoffset: true,
  strokeMiterlimit: true,
  strokeOpacity: true,
  strokeWidth: true
};

// Lifted from: https://github.com/facebook/react/blob/master/src/renderers/dom/shared/CSSPropertyOperations.js
function processStyleName(name) {
  return name.replace(UPPERCASE_PATTERN, '-$1').toLowerCase().replace(VENDOR_PREFIX, '-$1-');
}

// Lifted from: https://github.com/facebook/react/blob/master/src/renderers/dom/shared/dangerousStyleValue.js
function processStyleValue(name, value) {
  var isNumeric = void 0;
  if (typeof value === 'string') {
    isNumeric = NUMERIC_STRING.test(value);
  } else {
    isNumeric = true;
    value = String(value);
  }
  if (!isNumeric || value === '0' || isUnitlessNumber[name] === true) {
    return value;
  } else {
    return value + 'px';
  }
}

function styleToCSS(styleDescr) {
  return Object.keys(styleDescr).map(function (name) {
    var styleValue = processStyleValue(name, styleDescr[name]);
    var styleName = processStyleName(name);
    return styleName + ': ' + styleValue;
  }).join('; ');
}

exports.default = styleToCSS;

/***/ }),

/***/ "dNZO":
/*!***********************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/nested_property.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




var isNumeric = __webpack_require__(/*! fast-isnumeric */ "GbLo");
var isArrayOrTypedArray = __webpack_require__(/*! ./array */ "avjU").isArrayOrTypedArray;

/**
 * convert a string s (such as 'xaxis.range[0]')
 * representing a property of nested object into set and get methods
 * also return the string and object so we don't have to keep track of them
 * allows [-1] for an array index, to set a property inside all elements
 * of an array
 * eg if obj = {arr: [{a: 1}, {a: 2}]}
 * you can do p = nestedProperty(obj, 'arr[-1].a')
 * but you cannot set the array itself this way, to do that
 * just set the whole array.
 * eg if obj = {arr: [1, 2, 3]}
 * you can't do nestedProperty(obj, 'arr[-1]').set(5)
 * but you can do nestedProperty(obj, 'arr').set([5, 5, 5])
 */
module.exports = function nestedProperty(container, propStr) {
    if(isNumeric(propStr)) propStr = String(propStr);
    else if(typeof propStr !== 'string' ||
            propStr.substr(propStr.length - 4) === '[-1]') {
        throw 'bad property string';
    }

    var j = 0;
    var propParts = propStr.split('.');
    var indexed;
    var indices;
    var i;

    // check for parts of the nesting hierarchy that are numbers (ie array elements)
    while(j < propParts.length) {
        // look for non-bracket chars, then any number of [##] blocks
        indexed = String(propParts[j]).match(/^([^\[\]]*)((\[\-?[0-9]*\])+)$/);
        if(indexed) {
            if(indexed[1]) propParts[j] = indexed[1];
            // allow propStr to start with bracketed array indices
            else if(j === 0) propParts.splice(0, 1);
            else throw 'bad property string';

            indices = indexed[2]
                .substr(1, indexed[2].length - 2)
                .split('][');

            for(i = 0; i < indices.length; i++) {
                j++;
                propParts.splice(j, 0, Number(indices[i]));
            }
        }
        j++;
    }

    if(typeof container !== 'object') {
        return badContainer(container, propStr, propParts);
    }

    return {
        set: npSet(container, propParts, propStr),
        get: npGet(container, propParts),
        astr: propStr,
        parts: propParts,
        obj: container
    };
};

function npGet(cont, parts) {
    return function() {
        var curCont = cont;
        var curPart;
        var allSame;
        var out;
        var i;
        var j;

        for(i = 0; i < parts.length - 1; i++) {
            curPart = parts[i];
            if(curPart === -1) {
                allSame = true;
                out = [];
                for(j = 0; j < curCont.length; j++) {
                    out[j] = npGet(curCont[j], parts.slice(i + 1))();
                    if(out[j] !== out[0]) allSame = false;
                }
                return allSame ? out[0] : out;
            }
            if(typeof curPart === 'number' && !isArrayOrTypedArray(curCont)) {
                return undefined;
            }
            curCont = curCont[curPart];
            if(typeof curCont !== 'object' || curCont === null) {
                return undefined;
            }
        }

        // only hit this if parts.length === 1
        if(typeof curCont !== 'object' || curCont === null) return undefined;

        out = curCont[parts[i]];
        if(out === null) return undefined;
        return out;
    };
}

/*
 * Can this value be deleted? We can delete `undefined`, and `null` except INSIDE an
 * *args* array.
 *
 * Previously we also deleted some `{}` and `[]`, in order to try and make set/unset
 * a net noop; but this causes far more complication than it's worth, and still had
 * lots of exceptions. See https://github.com/plotly/plotly.js/issues/1410
 *
 * *args* arrays get passed directly to API methods and we should respect null if
 * the user put it there, but otherwise null is deleted as we use it as code
 * in restyle/relayout/update for "delete this value" whereas undefined means
 * "ignore this edit"
 */
var ARGS_PATTERN = /(^|\.)args\[/;
function isDeletable(val, propStr) {
    return (val === undefined) || (val === null && !propStr.match(ARGS_PATTERN));
}

function npSet(cont, parts, propStr) {
    return function(val) {
        var curCont = cont;
        var propPart = '';
        var containerLevels = [[cont, propPart]];
        var toDelete = isDeletable(val, propStr);
        var curPart;
        var i;

        for(i = 0; i < parts.length - 1; i++) {
            curPart = parts[i];

            if(typeof curPart === 'number' && !isArrayOrTypedArray(curCont)) {
                throw 'array index but container is not an array';
            }

            // handle special -1 array index
            if(curPart === -1) {
                toDelete = !setArrayAll(curCont, parts.slice(i + 1), val, propStr);
                if(toDelete) break;
                else return;
            }

            if(!checkNewContainer(curCont, curPart, parts[i + 1], toDelete)) {
                break;
            }

            curCont = curCont[curPart];

            if(typeof curCont !== 'object' || curCont === null) {
                throw 'container is not an object';
            }

            propPart = joinPropStr(propPart, curPart);

            containerLevels.push([curCont, propPart]);
        }

        if(toDelete) {
            if(i === parts.length - 1) {
                delete curCont[parts[i]];

                // The one bit of pruning we still do: drop `undefined` from the end of arrays.
                // In case someone has already unset previous items, continue until we hit a
                // non-undefined value.
                if(Array.isArray(curCont) && +parts[i] === curCont.length - 1) {
                    while(curCont.length && curCont[curCont.length - 1] === undefined) {
                        curCont.pop();
                    }
                }
            }
        }
        else curCont[parts[i]] = val;
    };
}

function joinPropStr(propStr, newPart) {
    var toAdd = newPart;
    if(isNumeric(newPart)) toAdd = '[' + newPart + ']';
    else if(propStr) toAdd = '.' + newPart;

    return propStr + toAdd;
}

// handle special -1 array index
function setArrayAll(containerArray, innerParts, val, propStr) {
    var arrayVal = isArrayOrTypedArray(val);
    var allSet = true;
    var thisVal = val;
    var thisPropStr = propStr.replace('-1', 0);
    var deleteThis = arrayVal ? false : isDeletable(val, thisPropStr);
    var firstPart = innerParts[0];
    var i;

    for(i = 0; i < containerArray.length; i++) {
        thisPropStr = propStr.replace('-1', i);
        if(arrayVal) {
            thisVal = val[i % val.length];
            deleteThis = isDeletable(thisVal, thisPropStr);
        }
        if(deleteThis) allSet = false;
        if(!checkNewContainer(containerArray, i, firstPart, deleteThis)) {
            continue;
        }
        npSet(containerArray[i], innerParts, propStr.replace('-1', i))(thisVal);
    }
    return allSet;
}

/**
 * make new sub-container as needed.
 * returns false if there's no container and none is needed
 * because we're only deleting an attribute
 */
function checkNewContainer(container, part, nextPart, toDelete) {
    if(container[part] === undefined) {
        if(toDelete) return false;

        if(typeof nextPart === 'number') container[part] = [];
        else container[part] = {};
    }
    return true;
}

function badContainer(container, propStr, propParts) {
    return {
        set: function() { throw 'bad container'; },
        get: function() {},
        astr: propStr,
        parts: propParts,
        obj: container
    };
}


/***/ }),

/***/ "dNwA":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/sw.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var sw = moment.defineLocale('sw', {
    months : 'Januari_Februari_Machi_Aprili_Mei_Juni_Julai_Agosti_Septemba_Oktoba_Novemba_Desemba'.split('_'),
    monthsShort : 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ago_Sep_Okt_Nov_Des'.split('_'),
    weekdays : 'Jumapili_Jumatatu_Jumanne_Jumatano_Alhamisi_Ijumaa_Jumamosi'.split('_'),
    weekdaysShort : 'Jpl_Jtat_Jnne_Jtan_Alh_Ijm_Jmos'.split('_'),
    weekdaysMin : 'J2_J3_J4_J5_Al_Ij_J1'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd, D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay : '[leo saa] LT',
        nextDay : '[kesho saa] LT',
        nextWeek : '[wiki ijayo] dddd [saat] LT',
        lastDay : '[jana] LT',
        lastWeek : '[wiki iliyopita] dddd [saat] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : '%s baadaye',
        past : 'tokea %s',
        s : 'hivi punde',
        ss : 'sekunde %d',
        m : 'dakika moja',
        mm : 'dakika %d',
        h : 'saa limoja',
        hh : 'masaa %d',
        d : 'siku moja',
        dd : 'masiku %d',
        M : 'mwezi mmoja',
        MM : 'miezi %d',
        y : 'mwaka mmoja',
        yy : 'miaka %d'
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return sw;

})));


/***/ }),

/***/ "dRFA":
/*!*******************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@phosphor/widgets/style/commandpalette.css ***!
  \*******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\r\n| Copyright (c) 2014-2017, PhosphorJS Contributors\r\n|\r\n| Distributed under the terms of the BSD 3-Clause License.\r\n|\r\n| The full license is in the file LICENSE, distributed with this software.\r\n|----------------------------------------------------------------------------*/\r\n\r\n\r\n.p-CommandPalette {\r\n  display: flex;\r\n  flex-direction: column;\r\n  -webkit-user-select: none;\r\n  -moz-user-select: none;\r\n  -ms-user-select: none;\r\n  user-select: none;\r\n}\r\n\r\n\r\n.p-CommandPalette-search {\r\n  flex: 0 0 auto;\r\n}\r\n\r\n\r\n.p-CommandPalette-content {\r\n  flex: 1 1 auto;\r\n  margin: 0;\r\n  padding: 0;\r\n  min-height: 0;\r\n  overflow: auto;\r\n  list-style-type: none;\r\n}\r\n\r\n\r\n.p-CommandPalette-header {\r\n  overflow: hidden;\r\n  white-space: nowrap;\r\n  text-overflow: ellipsis;\r\n}\r\n\r\n\r\n.p-CommandPalette-item {\r\n  display: flex;\r\n  flex-direction: row;\r\n}\r\n\r\n\r\n.p-CommandPalette-itemIcon {\r\n  flex: 0 0 auto;\r\n}\r\n\r\n\r\n.p-CommandPalette-itemContent {\r\n  flex: 1 1 auto;\r\n}\r\n\r\n\r\n.p-CommandPalette-itemShortcut {\r\n  flex: 0 0 auto;\r\n}\r\n\r\n\r\n.p-CommandPalette-itemLabel {\r\n  overflow: hidden;\r\n  white-space: nowrap;\r\n  text-overflow: ellipsis;\r\n}\r\n", ""]);

// exports


/***/ }),

/***/ "dRXW":
/*!***************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/Dropdown.js ***!
  \***************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UnconnectedDropdown = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Dropdown = __webpack_require__(/*! ../widgets/Dropdown */ "9Rtb");

var _Dropdown2 = _interopRequireDefault(_Dropdown);

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UnconnectedDropdown = exports.UnconnectedDropdown = function (_Component) {
  _inherits(UnconnectedDropdown, _Component);

  function UnconnectedDropdown() {
    _classCallCheck(this, UnconnectedDropdown);

    return _possibleConstructorReturn(this, (UnconnectedDropdown.__proto__ || Object.getPrototypeOf(UnconnectedDropdown)).apply(this, arguments));
  }

  _createClass(UnconnectedDropdown, [{
    key: 'render',
    value: function render() {
      var placeholder = void 0;
      if (this.props.multiValued) {
        placeholder = this.props.fullValue;
      }

      return _react2.default.createElement(
        _Field2.default,
        this.props,
        _react2.default.createElement(_Dropdown2.default, {
          backgroundDark: this.props.backgroundDark,
          options: this.props.options,
          value: this.props.fullValue,
          onChange: this.props.updatePlot,
          clearable: this.props.clearable,
          optionRenderer: this.props.optionRenderer,
          valueRenderer: this.props.valueRenderer,
          placeholder: placeholder,
          disabled: this.props.disabled
        })
      );
    }
  }]);

  return UnconnectedDropdown;
}(_react.Component);

UnconnectedDropdown.propTypes = _extends({
  backgroundDark: _propTypes2.default.bool,
  clearable: _propTypes2.default.bool,
  fullValue: _propTypes2.default.any,
  optionRenderer: _propTypes2.default.func,
  options: _propTypes2.default.array.isRequired,
  updatePlot: _propTypes2.default.func,
  valueRenderer: _propTypes2.default.func,
  disabled: _propTypes2.default.bool
}, _Field2.default.propTypes);

exports.default = (0, _lib.connectToContainer)(UnconnectedDropdown);
//# sourceMappingURL=Dropdown.js.map

/***/ }),

/***/ "dTAl":
/*!********************************************!*\
  !*** ./node_modules/lodash/_baseCreate.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isObject = __webpack_require__(/*! ./isObject */ "GoyQ");

/** Built-in value references. */
var objectCreate = Object.create;

/**
 * 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;
  };
}());

module.exports = baseCreate;


/***/ }),

/***/ "dUwI":
/*!****************************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/declaration.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _node = __webpack_require__(/*! ./node */ "wWcZ");

var _node2 = _interopRequireDefault(_node);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * Represents a CSS declaration.
 *
 * @extends Node
 *
 * @example
 * const root = postcss.parse('a { color: black }');
 * const decl = root.first.first;
 * decl.type       //=> 'decl'
 * decl.toString() //=> ' color: black'
 */
var Declaration = function (_Node) {
  _inherits(Declaration, _Node);

  function Declaration(defaults) {
    _classCallCheck(this, Declaration);

    var _this = _possibleConstructorReturn(this, _Node.call(this, defaults));

    _this.type = 'decl';
    return _this;
  }

  /**
   * @memberof Declaration#
   * @member {string} prop - the declaration’s property name
   *
   * @example
   * const root = postcss.parse('a { color: black }');
   * const decl = root.first.first;
   * decl.prop //=> 'color'
   */

  /**
   * @memberof Declaration#
   * @member {string} value - the declaration’s value
   *
   * @example
   * const root = postcss.parse('a { color: black }');
   * const decl = root.first.first;
   * decl.value //=> 'black'
   */

  /**
   * @memberof Declaration#
   * @member {boolean} important - `true` if the declaration
   *                               has an !important annotation.
   *
   * @example
   * const root = postcss.parse('a { color: black !important; color: red }');
   * root.first.first.important //=> true
   * root.first.last.important  //=> undefined
   */

  /**
   * @memberof Declaration#
   * @member {object} raws - Information to generate byte-to-byte equal
   *                         node string as it was in the origin input.
   *
   * Every parser saves its own properties,
   * but the default CSS parser uses:
   *
   * * `before`: the space symbols before the node. It also stores `*`
   *   and `_` symbols before the declaration (IE hack).
   * * `between`: the symbols between the property and value
   *   for declarations.
   * * `important`: the content of the important statement,
   *   if it is not just `!important`.
   *
   * PostCSS cleans declaration from comments and extra spaces,
   * but it stores origin content in raws properties.
   * As such, if you don’t change a declaration’s value,
   * PostCSS will use the raw value with comments.
   *
   * @example
   * const root = postcss.parse('a {\n  color:black\n}')
   * root.first.first.raws //=> { before: '\n  ', between: ':' }
   */

  return Declaration;
}(_node2.default);

exports.default = Declaration;
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImRlY2xhcmF0aW9uLmVzNiJdLCJuYW1lcyI6WyJEZWNsYXJhdGlvbiIsImRlZmF1bHRzIiwidHlwZSIsIk5vZGUiXSwibWFwcGluZ3MiOiI7Ozs7QUFBQTs7Ozs7Ozs7Ozs7O0FBRUE7Ozs7Ozs7Ozs7O0lBV01BLFc7OztBQUVGLHVCQUFZQyxRQUFaLEVBQXNCO0FBQUE7O0FBQUEsaURBQ2xCLGlCQUFNQSxRQUFOLENBRGtCOztBQUVsQixVQUFLQyxJQUFMLEdBQVksTUFBWjtBQUZrQjtBQUdyQjs7QUFFRDs7Ozs7Ozs7OztBQVVBOzs7Ozs7Ozs7O0FBVUE7Ozs7Ozs7Ozs7O0FBV0E7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0VBdENzQkMsYzs7a0JBaUVYSCxXIiwiZmlsZSI6ImRlY2xhcmF0aW9uLmpzIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IE5vZGUgZnJvbSAnLi9ub2RlJztcblxuLyoqXG4gKiBSZXByZXNlbnRzIGEgQ1NTIGRlY2xhcmF0aW9uLlxuICpcbiAqIEBleHRlbmRzIE5vZGVcbiAqXG4gKiBAZXhhbXBsZVxuICogY29uc3Qgcm9vdCA9IHBvc3Rjc3MucGFyc2UoJ2EgeyBjb2xvcjogYmxhY2sgfScpO1xuICogY29uc3QgZGVjbCA9IHJvb3QuZmlyc3QuZmlyc3Q7XG4gKiBkZWNsLnR5cGUgICAgICAgLy89PiAnZGVjbCdcbiAqIGRlY2wudG9TdHJpbmcoKSAvLz0+ICcgY29sb3I6IGJsYWNrJ1xuICovXG5jbGFzcyBEZWNsYXJhdGlvbiBleHRlbmRzIE5vZGUge1xuXG4gICAgY29uc3RydWN0b3IoZGVmYXVsdHMpIHtcbiAgICAgICAgc3VwZXIoZGVmYXVsdHMpO1xuICAgICAgICB0aGlzLnR5cGUgPSAnZGVjbCc7XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogQG1lbWJlcm9mIERlY2xhcmF0aW9uI1xuICAgICAqIEBtZW1iZXIge3N0cmluZ30gcHJvcCAtIHRoZSBkZWNsYXJhdGlvbuKAmXMgcHJvcGVydHkgbmFtZVxuICAgICAqXG4gICAgICogQGV4YW1wbGVcbiAgICAgKiBjb25zdCByb290ID0gcG9zdGNzcy5wYXJzZSgnYSB7IGNvbG9yOiBibGFjayB9Jyk7XG4gICAgICogY29uc3QgZGVjbCA9IHJvb3QuZmlyc3QuZmlyc3Q7XG4gICAgICogZGVjbC5wcm9wIC8vPT4gJ2NvbG9yJ1xuICAgICAqL1xuXG4gICAgLyoqXG4gICAgICogQG1lbWJlcm9mIERlY2xhcmF0aW9uI1xuICAgICAqIEBtZW1iZXIge3N0cmluZ30gdmFsdWUgLSB0aGUgZGVjbGFyYXRpb27igJlzIHZhbHVlXG4gICAgICpcbiAgICAgKiBAZXhhbXBsZVxuICAgICAqIGNvbnN0IHJvb3QgPSBwb3N0Y3NzLnBhcnNlKCdhIHsgY29sb3I6IGJsYWNrIH0nKTtcbiAgICAgKiBjb25zdCBkZWNsID0gcm9vdC5maXJzdC5maXJzdDtcbiAgICAgKiBkZWNsLnZhbHVlIC8vPT4gJ2JsYWNrJ1xuICAgICAqL1xuXG4gICAgLyoqXG4gICAgICogQG1lbWJlcm9mIERlY2xhcmF0aW9uI1xuICAgICAqIEBtZW1iZXIge2Jvb2xlYW59IGltcG9ydGFudCAtIGB0cnVlYCBpZiB0aGUgZGVjbGFyYXRpb25cbiAgICAgKiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBoYXMgYW4gIWltcG9ydGFudCBhbm5vdGF0aW9uLlxuICAgICAqXG4gICAgICogQGV4YW1wbGVcbiAgICAgKiBjb25zdCByb290ID0gcG9zdGNzcy5wYXJzZSgnYSB7IGNvbG9yOiBibGFjayAhaW1wb3J0YW50OyBjb2xvcjogcmVkIH0nKTtcbiAgICAgKiByb290LmZpcnN0LmZpcnN0LmltcG9ydGFudCAvLz0+IHRydWVcbiAgICAgKiByb290LmZpcnN0Lmxhc3QuaW1wb3J0YW50ICAvLz0+IHVuZGVmaW5lZFxuICAgICAqL1xuXG4gICAgLyoqXG4gICAgICogQG1lbWJlcm9mIERlY2xhcmF0aW9uI1xuICAgICAqIEBtZW1iZXIge29iamVjdH0gcmF3cyAtIEluZm9ybWF0aW9uIHRvIGdlbmVyYXRlIGJ5dGUtdG8tYnl0ZSBlcXVhbFxuICAgICAqICAgICAgICAgICAgICAgICAgICAgICAgIG5vZGUgc3RyaW5nIGFzIGl0IHdhcyBpbiB0aGUgb3JpZ2luIGlucHV0LlxuICAgICAqXG4gICAgICogRXZlcnkgcGFyc2VyIHNhdmVzIGl0cyBvd24gcHJvcGVydGllcyxcbiAgICAgKiBidXQgdGhlIGRlZmF1bHQgQ1NTIHBhcnNlciB1c2VzOlxuICAgICAqXG4gICAgICogKiBgYmVmb3JlYDogdGhlIHNwYWNlIHN5bWJvbHMgYmVmb3JlIHRoZSBub2RlLiBJdCBhbHNvIHN0b3JlcyBgKmBcbiAgICAgKiAgIGFuZCBgX2Agc3ltYm9scyBiZWZvcmUgdGhlIGRlY2xhcmF0aW9uIChJRSBoYWNrKS5cbiAgICAgKiAqIGBiZXR3ZWVuYDogdGhlIHN5bWJvbHMgYmV0d2VlbiB0aGUgcHJvcGVydHkgYW5kIHZhbHVlXG4gICAgICogICBmb3IgZGVjbGFyYXRpb25zLlxuICAgICAqICogYGltcG9ydGFudGA6IHRoZSBjb250ZW50IG9mIHRoZSBpbXBvcnRhbnQgc3RhdGVtZW50LFxuICAgICAqICAgaWYgaXQgaXMgbm90IGp1c3QgYCFpbXBvcnRhbnRgLlxuICAgICAqXG4gICAgICogUG9zdENTUyBjbGVhbnMgZGVjbGFyYXRpb24gZnJvbSBjb21tZW50cyBhbmQgZXh0cmEgc3BhY2VzLFxuICAgICAqIGJ1dCBpdCBzdG9yZXMgb3JpZ2luIGNvbnRlbnQgaW4gcmF3cyBwcm9wZXJ0aWVzLlxuICAgICAqIEFzIHN1Y2gsIGlmIHlvdSBkb27igJl0IGNoYW5nZSBhIGRlY2xhcmF0aW9u4oCZcyB2YWx1ZSxcbiAgICAgKiBQb3N0Q1NTIHdpbGwgdXNlIHRoZSByYXcgdmFsdWUgd2l0aCBjb21tZW50cy5cbiAgICAgKlxuICAgICAqIEBleGFtcGxlXG4gICAgICogY29uc3Qgcm9vdCA9IHBvc3Rjc3MucGFyc2UoJ2Ege1xcbiAgY29sb3I6YmxhY2tcXG59JylcbiAgICAgKiByb290LmZpcnN0LmZpcnN0LnJhd3MgLy89PiB7IGJlZm9yZTogJ1xcbiAgJywgYmV0d2VlbjogJzonIH1cbiAgICAgKi9cblxufVxuXG5leHBvcnQgZGVmYXVsdCBEZWNsYXJhdGlvbjtcbiJdfQ==


/***/ }),

/***/ "dZIv":
/*!********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/NumericOrDate.js ***!
  \********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UnconnectedNumericOrDate = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _Numeric = __webpack_require__(/*! ./Numeric */ "E01D");

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _lib2 = __webpack_require__(/*! plotly.js/src/lib */ "/CZE");

var _dates = __webpack_require__(/*! plotly.js/src/lib/dates */ "Zhzs");

var _DateTimePicker = __webpack_require__(/*! ./DateTimePicker */ "PLYX");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UnconnectedNumericOrDate = exports.UnconnectedNumericOrDate = function (_Component) {
  _inherits(UnconnectedNumericOrDate, _Component);

  function UnconnectedNumericOrDate() {
    _classCallCheck(this, UnconnectedNumericOrDate);

    return _possibleConstructorReturn(this, (UnconnectedNumericOrDate.__proto__ || Object.getPrototypeOf(UnconnectedNumericOrDate)).apply(this, arguments));
  }

  _createClass(UnconnectedNumericOrDate, [{
    key: 'render',
    value: function render() {
      var date = typeof this.props.fullValue === 'string' && this.props.fullValue.split(' ')[0];
      var fullValueIsDate = typeof this.props.fullValue === 'string' && date && ((0, _lib2.isDateTime)(date) || (0, _dates.isJSDate)(date));

      return fullValueIsDate ? _react2.default.createElement(_DateTimePicker.UnconnectedDateTimePicker, _extends({}, this.props, { placeholder: 'yyyy-mm-dd hh:mm:ss.xxx' })) : _react2.default.createElement(_Numeric.UnconnectedNumeric, this.props);
    }
  }]);

  return UnconnectedNumericOrDate;
}(_react.Component);

UnconnectedNumericOrDate.propTypes = _extends({
  defaultValue: _propTypes2.default.any,
  fullValue: _propTypes2.default.any,
  min: _propTypes2.default.number,
  max: _propTypes2.default.number,
  multiValued: _propTypes2.default.bool,
  hideArrows: _propTypes2.default.bool,
  showSlider: _propTypes2.default.bool,
  step: _propTypes2.default.number,
  fullContainer: _propTypes2.default.object,
  updatePlot: _propTypes2.default.func
}, _Field2.default.propTypes);

exports.default = (0, _lib.connectToContainer)(UnconnectedNumericOrDate);
//# sourceMappingURL=NumericOrDate.js.map

/***/ }),

/***/ "dcwN":
/*!********************************************!*\
  !*** ./node_modules/randomfill/browser.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global, process) {

function oldBrowser () {
  throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11')
}
var safeBuffer = __webpack_require__(/*! safe-buffer */ "hwdV")
var randombytes = __webpack_require__(/*! randombytes */ "Edxu")
var Buffer = safeBuffer.Buffer
var kBufferMaxLength = safeBuffer.kMaxLength
var crypto = global.crypto || global.msCrypto
var kMaxUint32 = Math.pow(2, 32) - 1
function assertOffset (offset, length) {
  if (typeof offset !== 'number' || offset !== offset) { // eslint-disable-line no-self-compare
    throw new TypeError('offset must be a number')
  }

  if (offset > kMaxUint32 || offset < 0) {
    throw new TypeError('offset must be a uint32')
  }

  if (offset > kBufferMaxLength || offset > length) {
    throw new RangeError('offset out of range')
  }
}

function assertSize (size, offset, length) {
  if (typeof size !== 'number' || size !== size) { // eslint-disable-line no-self-compare
    throw new TypeError('size must be a number')
  }

  if (size > kMaxUint32 || size < 0) {
    throw new TypeError('size must be a uint32')
  }

  if (size + offset > length || size > kBufferMaxLength) {
    throw new RangeError('buffer too small')
  }
}
if ((crypto && crypto.getRandomValues) || !process.browser) {
  exports.randomFill = randomFill
  exports.randomFillSync = randomFillSync
} else {
  exports.randomFill = oldBrowser
  exports.randomFillSync = oldBrowser
}
function randomFill (buf, offset, size, cb) {
  if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {
    throw new TypeError('"buf" argument must be a Buffer or Uint8Array')
  }

  if (typeof offset === 'function') {
    cb = offset
    offset = 0
    size = buf.length
  } else if (typeof size === 'function') {
    cb = size
    size = buf.length - offset
  } else if (typeof cb !== 'function') {
    throw new TypeError('"cb" argument must be a function')
  }
  assertOffset(offset, buf.length)
  assertSize(size, offset, buf.length)
  return actualFill(buf, offset, size, cb)
}

function actualFill (buf, offset, size, cb) {
  if (process.browser) {
    var ourBuf = buf.buffer
    var uint = new Uint8Array(ourBuf, offset, size)
    crypto.getRandomValues(uint)
    if (cb) {
      process.nextTick(function () {
        cb(null, buf)
      })
      return
    }
    return buf
  }
  if (cb) {
    randombytes(size, function (err, bytes) {
      if (err) {
        return cb(err)
      }
      bytes.copy(buf, offset)
      cb(null, buf)
    })
    return
  }
  var bytes = randombytes(size)
  bytes.copy(buf, offset)
  return buf
}
function randomFillSync (buf, offset, size) {
  if (typeof offset === 'undefined') {
    offset = 0
  }
  if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {
    throw new TypeError('"buf" argument must be a Buffer or Uint8Array')
  }

  assertOffset(offset, buf.length)

  if (size === undefined) size = buf.length - offset

  assertSize(size, offset, buf.length)

  return actualFill(buf, offset, size)
}

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "yLpj"), __webpack_require__(/*! ./../process/browser.js */ "8oxB")))

/***/ }),

/***/ "ddNL":
/*!**********************************************************!*\
  !*** ./node_modules/@jupyterlab/codemirror/lib/index.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
const factory_1 = __webpack_require__(/*! ./factory */ "9S6L");
const mimetype_1 = __webpack_require__(/*! ./mimetype */ "r8R9");
__webpack_require__(/*! ../style/index.css */ "482I");
__export(__webpack_require__(/*! ./mode */ "Gga1"));
__export(__webpack_require__(/*! ./editor */ "zGJM"));
__export(__webpack_require__(/*! ./factory */ "9S6L"));
__export(__webpack_require__(/*! ./mimetype */ "r8R9"));
/**
 * The default editor services.
 */
exports.editorServices = {
    factoryService: new factory_1.CodeMirrorEditorFactory(),
    mimeTypeService: new mimetype_1.CodeMirrorMimeTypeService()
};


/***/ }),

/***/ "dfSG":
/*!***********************************************!*\
  !*** ./node_modules/mdi-react/TooltipIcon.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var TooltipIcon = function TooltipIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M4,2H20C21.1,2 22,2.9 22,4V16C22,17.1 21.1,18 20,18H16L12,22L8,18H4C2.9,18 2,17.1 2,16V4C2,2.9 2.9,2 4,2Z' })
  );
};

module.exports = TooltipIcon;


/***/ }),

/***/ "dfh3":
/*!***********************************************!*\
  !*** ./node_modules/codemirror/keymap/vim.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

/**
 * Supported keybindings:
 *   Too many to list. Refer to defaultKeyMap below.
 *
 * Supported Ex commands:
 *   Refer to defaultExCommandMap below.
 *
 * Registers: unnamed, -, a-z, A-Z, 0-9
 *   (Does not respect the special case for number registers when delete
 *    operator is made with these commands: %, (, ),  , /, ?, n, N, {, } )
 *   TODO: Implement the remaining registers.
 *
 * Marks: a-z, A-Z, and 0-9
 *   TODO: Implement the remaining special marks. They have more complex
 *       behavior.
 *
 * Events:
 *  'vim-mode-change' - raised on the editor anytime the current mode changes,
 *                      Event object: {mode: "visual", subMode: "linewise"}
 *
 * Code structure:
 *  1. Default keymap
 *  2. Variable declarations and short basic helpers
 *  3. Instance (External API) implementation
 *  4. Internal state tracking objects (input state, counter) implementation
 *     and instantiation
 *  5. Key handler (the main command dispatcher) implementation
 *  6. Motion, operator, and action implementations
 *  7. Helper functions for the key handler, motions, operators, and actions
 *  8. Set up Vim to work as a keymap for CodeMirror.
 *  9. Ex command implementations.
 */

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../lib/codemirror */ "VrN/"), __webpack_require__(/*! ../addon/search/searchcursor */ "uTOq"), __webpack_require__(/*! ../addon/dialog/dialog */ "Ku0u"), __webpack_require__(/*! ../addon/edit/matchbrackets.js */ "jDMi"));
  else {}
})(function(CodeMirror) {
  'use strict';

  var defaultKeymap = [
    // Key to key mapping. This goes first to make it possible to override
    // existing mappings.
    { keys: '<Left>', type: 'keyToKey', toKeys: 'h' },
    { keys: '<Right>', type: 'keyToKey', toKeys: 'l' },
    { keys: '<Up>', type: 'keyToKey', toKeys: 'k' },
    { keys: '<Down>', type: 'keyToKey', toKeys: 'j' },
    { keys: '<Space>', type: 'keyToKey', toKeys: 'l' },
    { keys: '<BS>', type: 'keyToKey', toKeys: 'h', context: 'normal'},
    { keys: '<C-Space>', type: 'keyToKey', toKeys: 'W' },
    { keys: '<C-BS>', type: 'keyToKey', toKeys: 'B', context: 'normal' },
    { keys: '<S-Space>', type: 'keyToKey', toKeys: 'w' },
    { keys: '<S-BS>', type: 'keyToKey', toKeys: 'b', context: 'normal' },
    { keys: '<C-n>', type: 'keyToKey', toKeys: 'j' },
    { keys: '<C-p>', type: 'keyToKey', toKeys: 'k' },
    { keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>' },
    { keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>' },
    { keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },
    { keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },
    { keys: 's', type: 'keyToKey', toKeys: 'cl', context: 'normal' },
    { keys: 's', type: 'keyToKey', toKeys: 'c', context: 'visual'},
    { keys: 'S', type: 'keyToKey', toKeys: 'cc', context: 'normal' },
    { keys: 'S', type: 'keyToKey', toKeys: 'VdO', context: 'visual' },
    { keys: '<Home>', type: 'keyToKey', toKeys: '0' },
    { keys: '<End>', type: 'keyToKey', toKeys: '$' },
    { keys: '<PageUp>', type: 'keyToKey', toKeys: '<C-b>' },
    { keys: '<PageDown>', type: 'keyToKey', toKeys: '<C-f>' },
    { keys: '<CR>', type: 'keyToKey', toKeys: 'j^', context: 'normal' },
    { keys: '<Ins>', type: 'action', action: 'toggleOverwrite', context: 'insert' },
    // Motions
    { keys: 'H', type: 'motion', motion: 'moveToTopLine', motionArgs: { linewise: true, toJumplist: true }},
    { keys: 'M', type: 'motion', motion: 'moveToMiddleLine', motionArgs: { linewise: true, toJumplist: true }},
    { keys: 'L', type: 'motion', motion: 'moveToBottomLine', motionArgs: { linewise: true, toJumplist: true }},
    { keys: 'h', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: false }},
    { keys: 'l', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: true }},
    { keys: 'j', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, linewise: true }},
    { keys: 'k', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, linewise: true }},
    { keys: 'gj', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: true }},
    { keys: 'gk', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: false }},
    { keys: 'w', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false }},
    { keys: 'W', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false, bigWord: true }},
    { keys: 'e', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, inclusive: true }},
    { keys: 'E', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, bigWord: true, inclusive: true }},
    { keys: 'b', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }},
    { keys: 'B', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false, bigWord: true }},
    { keys: 'ge', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, inclusive: true }},
    { keys: 'gE', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, bigWord: true, inclusive: true }},
    { keys: '{', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: false, toJumplist: true }},
    { keys: '}', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: true, toJumplist: true }},
    { keys: '(', type: 'motion', motion: 'moveBySentence', motionArgs: { forward: false }},
    { keys: ')', type: 'motion', motion: 'moveBySentence', motionArgs: { forward: true }},
    { keys: '<C-f>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: true }},
    { keys: '<C-b>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: false }},
    { keys: '<C-d>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: true, explicitRepeat: true }},
    { keys: '<C-u>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: false, explicitRepeat: true }},
    { keys: 'gg', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }},
    { keys: 'G', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }},
    { keys: '0', type: 'motion', motion: 'moveToStartOfLine' },
    { keys: '^', type: 'motion', motion: 'moveToFirstNonWhiteSpaceCharacter' },
    { keys: '+', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true }},
    { keys: '-', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, toFirstChar:true }},
    { keys: '_', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }},
    { keys: '$', type: 'motion', motion: 'moveToEol', motionArgs: { inclusive: true }},
    { keys: '%', type: 'motion', motion: 'moveToMatchedSymbol', motionArgs: { inclusive: true, toJumplist: true }},
    { keys: 'f<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: true , inclusive: true }},
    { keys: 'F<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: false }},
    { keys: 't<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: true, inclusive: true }},
    { keys: 'T<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: false }},
    { keys: ';', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: true }},
    { keys: ',', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: false }},
    { keys: '\'<character>', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true, linewise: true}},
    { keys: '`<character>', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true}},
    { keys: ']`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } },
    { keys: '[`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } },
    { keys: ']\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } },
    { keys: '[\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } },
    // the next two aren't motions but must come before more general motion declarations
    { keys: ']p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true, matchIndent: true}},
    { keys: '[p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true, matchIndent: true}},
    { keys: ']<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: true, toJumplist: true}},
    { keys: '[<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: false, toJumplist: true}},
    { keys: '|', type: 'motion', motion: 'moveToColumn'},
    { keys: 'o', type: 'motion', motion: 'moveToOtherHighlightedEnd', context:'visual'},
    { keys: 'O', type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: {sameLine: true}, context:'visual'},
    // Operators
    { keys: 'd', type: 'operator', operator: 'delete' },
    { keys: 'y', type: 'operator', operator: 'yank' },
    { keys: 'c', type: 'operator', operator: 'change' },
    { keys: '>', type: 'operator', operator: 'indent', operatorArgs: { indentRight: true }},
    { keys: '<', type: 'operator', operator: 'indent', operatorArgs: { indentRight: false }},
    { keys: 'g~', type: 'operator', operator: 'changeCase' },
    { keys: 'gu', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, isEdit: true },
    { keys: 'gU', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, isEdit: true },
    { keys: 'n', type: 'motion', motion: 'findNext', motionArgs: { forward: true, toJumplist: true }},
    { keys: 'N', type: 'motion', motion: 'findNext', motionArgs: { forward: false, toJumplist: true }},
    // Operator-Motion dual commands
    { keys: 'x', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorMotionArgs: { visualLine: false }},
    { keys: 'X', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: false }, operatorMotionArgs: { visualLine: true }},
    { keys: 'D', type: 'operatorMotion', operator: 'delete', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
    { keys: 'D', type: 'operator', operator: 'delete', operatorArgs: { linewise: true }, context: 'visual'},
    { keys: 'Y', type: 'operatorMotion', operator: 'yank', motion: 'expandToLine', motionArgs: { linewise: true }, context: 'normal'},
    { keys: 'Y', type: 'operator', operator: 'yank', operatorArgs: { linewise: true }, context: 'visual'},
    { keys: 'C', type: 'operatorMotion', operator: 'change', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
    { keys: 'C', type: 'operator', operator: 'change', operatorArgs: { linewise: true }, context: 'visual'},
    { keys: '~', type: 'operatorMotion', operator: 'changeCase', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorArgs: { shouldMoveCursor: true }, context: 'normal'},
    { keys: '~', type: 'operator', operator: 'changeCase', context: 'visual'},
    { keys: '<C-w>', type: 'operatorMotion', operator: 'delete', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }, context: 'insert' },
    // Actions
    { keys: '<C-i>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: true }},
    { keys: '<C-o>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: false }},
    { keys: '<C-e>', type: 'action', action: 'scroll', actionArgs: { forward: true, linewise: true }},
    { keys: '<C-y>', type: 'action', action: 'scroll', actionArgs: { forward: false, linewise: true }},
    { keys: 'a', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'charAfter' }, context: 'normal' },
    { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'eol' }, context: 'normal' },
    { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'endOfSelectedArea' }, context: 'visual' },
    { keys: 'i', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'inplace' }, context: 'normal' },
    { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'firstNonBlank'}, context: 'normal' },
    { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'startOfSelectedArea' }, context: 'visual' },
    { keys: 'o', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: true }, context: 'normal' },
    { keys: 'O', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: false }, context: 'normal' },
    { keys: 'v', type: 'action', action: 'toggleVisualMode' },
    { keys: 'V', type: 'action', action: 'toggleVisualMode', actionArgs: { linewise: true }},
    { keys: '<C-v>', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }},
    { keys: '<C-q>', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }},
    { keys: 'gv', type: 'action', action: 'reselectLastSelection' },
    { keys: 'J', type: 'action', action: 'joinLines', isEdit: true },
    { keys: 'p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true }},
    { keys: 'P', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true }},
    { keys: 'r<character>', type: 'action', action: 'replace', isEdit: true },
    { keys: '@<character>', type: 'action', action: 'replayMacro' },
    { keys: 'q<character>', type: 'action', action: 'enterMacroRecordMode' },
    // Handle Replace-mode as a special case of insert mode.
    { keys: 'R', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { replace: true }},
    { keys: 'u', type: 'action', action: 'undo', context: 'normal' },
    { keys: 'u', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, context: 'visual', isEdit: true },
    { keys: 'U', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, context: 'visual', isEdit: true },
    { keys: '<C-r>', type: 'action', action: 'redo' },
    { keys: 'm<character>', type: 'action', action: 'setMark' },
    { keys: '"<character>', type: 'action', action: 'setRegister' },
    { keys: 'zz', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }},
    { keys: 'z.', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
    { keys: 'zt', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }},
    { keys: 'z<CR>', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
    { keys: 'z-', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }},
    { keys: 'zb', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
    { keys: '.', type: 'action', action: 'repeatLastEdit' },
    { keys: '<C-a>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: true, backtrack: false}},
    { keys: '<C-x>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: false, backtrack: false}},
    { keys: '<C-t>', type: 'action', action: 'indent', actionArgs: { indentRight: true }, context: 'insert' },
    { keys: '<C-d>', type: 'action', action: 'indent', actionArgs: { indentRight: false }, context: 'insert' },
    // Text object motions
    { keys: 'a<character>', type: 'motion', motion: 'textObjectManipulation' },
    { keys: 'i<character>', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true }},
    // Search
    { keys: '/', type: 'search', searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }},
    { keys: '?', type: 'search', searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }},
    { keys: '*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
    { keys: '#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
    { keys: 'g*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }},
    { keys: 'g#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }},
    // Ex command
    { keys: ':', type: 'ex' }
  ];

  /**
   * Ex commands
   * Care must be taken when adding to the default Ex command map. For any
   * pair of commands that have a shared prefix, at least one of their
   * shortNames must not match the prefix of the other command.
   */
  var defaultExCommandMap = [
    { name: 'colorscheme', shortName: 'colo' },
    { name: 'map' },
    { name: 'imap', shortName: 'im' },
    { name: 'nmap', shortName: 'nm' },
    { name: 'vmap', shortName: 'vm' },
    { name: 'unmap' },
    { name: 'write', shortName: 'w' },
    { name: 'undo', shortName: 'u' },
    { name: 'redo', shortName: 'red' },
    { name: 'set', shortName: 'se' },
    { name: 'set', shortName: 'se' },
    { name: 'setlocal', shortName: 'setl' },
    { name: 'setglobal', shortName: 'setg' },
    { name: 'sort', shortName: 'sor' },
    { name: 'substitute', shortName: 's', possiblyAsync: true },
    { name: 'nohlsearch', shortName: 'noh' },
    { name: 'yank', shortName: 'y' },
    { name: 'delmarks', shortName: 'delm' },
    { name: 'registers', shortName: 'reg', excludeFromCommandHistory: true },
    { name: 'global', shortName: 'g' }
  ];

  var Pos = CodeMirror.Pos;

  var Vim = function() {
    function enterVimMode(cm) {
      cm.setOption('disableInput', true);
      cm.setOption('showCursorWhenSelecting', false);
      CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
      cm.on('cursorActivity', onCursorActivity);
      maybeInitVimState(cm);
      CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm));
    }

    function leaveVimMode(cm) {
      cm.setOption('disableInput', false);
      cm.off('cursorActivity', onCursorActivity);
      CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm));
      cm.state.vim = null;
    }

    function detachVimMap(cm, next) {
      if (this == CodeMirror.keyMap.vim) {
        CodeMirror.rmClass(cm.getWrapperElement(), "cm-fat-cursor");
        if (cm.getOption("inputStyle") == "contenteditable" && document.body.style.caretColor != null) {
          disableFatCursorMark(cm);
          cm.getInputField().style.caretColor = "";
        }
      }

      if (!next || next.attach != attachVimMap)
        leaveVimMode(cm);
    }
    function attachVimMap(cm, prev) {
      if (this == CodeMirror.keyMap.vim) {
        CodeMirror.addClass(cm.getWrapperElement(), "cm-fat-cursor");
        if (cm.getOption("inputStyle") == "contenteditable" && document.body.style.caretColor != null) {
          enableFatCursorMark(cm);
          cm.getInputField().style.caretColor = "transparent";
        }
      }

      if (!prev || prev.attach != attachVimMap)
        enterVimMode(cm);
    }

    function fatCursorMarks(cm) {
      var ranges = cm.listSelections(), result = []
      for (var i = 0; i < ranges.length; i++) {
        var range = ranges[i]
        if (range.empty()) {
          if (range.anchor.ch < cm.getLine(range.anchor.line).length) {
            result.push(cm.markText(range.anchor, Pos(range.anchor.line, range.anchor.ch + 1),
                                    {className: "cm-fat-cursor-mark"}))
          } else {
            var widget = document.createElement("span")
            widget.textContent = "\u00a0"
            widget.className = "cm-fat-cursor-mark"
            result.push(cm.setBookmark(range.anchor, {widget: widget}))
          }
        }
      }
      return result
    }

    function updateFatCursorMark(cm) {
      var marks = cm.state.fatCursorMarks
      if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear()
      cm.state.fatCursorMarks = fatCursorMarks(cm)
    }

    function enableFatCursorMark(cm) {
      cm.state.fatCursorMarks = fatCursorMarks(cm)
      cm.on("cursorActivity", updateFatCursorMark)
    }

    function disableFatCursorMark(cm) {
      var marks = cm.state.fatCursorMarks
      if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear()
      cm.state.fatCursorMarks = null
      cm.off("cursorActivity", updateFatCursorMark)
    }

    // Deprecated, simply setting the keymap works again.
    CodeMirror.defineOption('vimMode', false, function(cm, val, prev) {
      if (val && cm.getOption("keyMap") != "vim")
        cm.setOption("keyMap", "vim");
      else if (!val && prev != CodeMirror.Init && /^vim/.test(cm.getOption("keyMap")))
        cm.setOption("keyMap", "default");
    });

    function cmKey(key, cm) {
      if (!cm) { return undefined; }
      if (this[key]) { return this[key]; }
      var vimKey = cmKeyToVimKey(key);
      if (!vimKey) {
        return false;
      }
      var cmd = CodeMirror.Vim.findKey(cm, vimKey);
      if (typeof cmd == 'function') {
        CodeMirror.signal(cm, 'vim-keypress', vimKey);
      }
      return cmd;
    }

    var modifiers = {'Shift': 'S', 'Ctrl': 'C', 'Alt': 'A', 'Cmd': 'D', 'Mod': 'A'};
    var specialKeys = {Enter:'CR',Backspace:'BS',Delete:'Del',Insert:'Ins'};
    function cmKeyToVimKey(key) {
      if (key.charAt(0) == '\'') {
        // Keypress character binding of format "'a'"
        return key.charAt(1);
      }
      var pieces = key.split(/-(?!$)/);
      var lastPiece = pieces[pieces.length - 1];
      if (pieces.length == 1 && pieces[0].length == 1) {
        // No-modifier bindings use literal character bindings above. Skip.
        return false;
      } else if (pieces.length == 2 && pieces[0] == 'Shift' && lastPiece.length == 1) {
        // Ignore Shift+char bindings as they should be handled by literal character.
        return false;
      }
      var hasCharacter = false;
      for (var i = 0; i < pieces.length; i++) {
        var piece = pieces[i];
        if (piece in modifiers) { pieces[i] = modifiers[piece]; }
        else { hasCharacter = true; }
        if (piece in specialKeys) { pieces[i] = specialKeys[piece]; }
      }
      if (!hasCharacter) {
        // Vim does not support modifier only keys.
        return false;
      }
      // TODO: Current bindings expect the character to be lower case, but
      // it looks like vim key notation uses upper case.
      if (isUpperCase(lastPiece)) {
        pieces[pieces.length - 1] = lastPiece.toLowerCase();
      }
      return '<' + pieces.join('-') + '>';
    }

    function getOnPasteFn(cm) {
      var vim = cm.state.vim;
      if (!vim.onPasteFn) {
        vim.onPasteFn = function() {
          if (!vim.insertMode) {
            cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
            actions.enterInsertMode(cm, {}, vim);
          }
        };
      }
      return vim.onPasteFn;
    }

    var numberRegex = /[\d]/;
    var wordCharTest = [CodeMirror.isWordChar, function(ch) {
      return ch && !CodeMirror.isWordChar(ch) && !/\s/.test(ch);
    }], bigWordCharTest = [function(ch) {
      return /\S/.test(ch);
    }];
    function makeKeyRange(start, size) {
      var keys = [];
      for (var i = start; i < start + size; i++) {
        keys.push(String.fromCharCode(i));
      }
      return keys;
    }
    var upperCaseAlphabet = makeKeyRange(65, 26);
    var lowerCaseAlphabet = makeKeyRange(97, 26);
    var numbers = makeKeyRange(48, 10);
    var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']);
    var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"', '.', ':', '/']);

    function isLine(cm, line) {
      return line >= cm.firstLine() && line <= cm.lastLine();
    }
    function isLowerCase(k) {
      return (/^[a-z]$/).test(k);
    }
    function isMatchableSymbol(k) {
      return '()[]{}'.indexOf(k) != -1;
    }
    function isNumber(k) {
      return numberRegex.test(k);
    }
    function isUpperCase(k) {
      return (/^[A-Z]$/).test(k);
    }
    function isWhiteSpaceString(k) {
      return (/^\s*$/).test(k);
    }
    function isEndOfSentenceSymbol(k) {
      return '.?!'.indexOf(k) != -1;
    }
    function inArray(val, arr) {
      for (var i = 0; i < arr.length; i++) {
        if (arr[i] == val) {
          return true;
        }
      }
      return false;
    }

    var options = {};
    function defineOption(name, defaultValue, type, aliases, callback) {
      if (defaultValue === undefined && !callback) {
        throw Error('defaultValue is required unless callback is provided');
      }
      if (!type) { type = 'string'; }
      options[name] = {
        type: type,
        defaultValue: defaultValue,
        callback: callback
      };
      if (aliases) {
        for (var i = 0; i < aliases.length; i++) {
          options[aliases[i]] = options[name];
        }
      }
      if (defaultValue) {
        setOption(name, defaultValue);
      }
    }

    function setOption(name, value, cm, cfg) {
      var option = options[name];
      cfg = cfg || {};
      var scope = cfg.scope;
      if (!option) {
        return new Error('Unknown option: ' + name);
      }
      if (option.type == 'boolean') {
        if (value && value !== true) {
          return new Error('Invalid argument: ' + name + '=' + value);
        } else if (value !== false) {
          // Boolean options are set to true if value is not defined.
          value = true;
        }
      }
      if (option.callback) {
        if (scope !== 'local') {
          option.callback(value, undefined);
        }
        if (scope !== 'global' && cm) {
          option.callback(value, cm);
        }
      } else {
        if (scope !== 'local') {
          option.value = option.type == 'boolean' ? !!value : value;
        }
        if (scope !== 'global' && cm) {
          cm.state.vim.options[name] = {value: value};
        }
      }
    }

    function getOption(name, cm, cfg) {
      var option = options[name];
      cfg = cfg || {};
      var scope = cfg.scope;
      if (!option) {
        return new Error('Unknown option: ' + name);
      }
      if (option.callback) {
        var local = cm && option.callback(undefined, cm);
        if (scope !== 'global' && local !== undefined) {
          return local;
        }
        if (scope !== 'local') {
          return option.callback();
        }
        return;
      } else {
        var local = (scope !== 'global') && (cm && cm.state.vim.options[name]);
        return (local || (scope !== 'local') && option || {}).value;
      }
    }

    defineOption('filetype', undefined, 'string', ['ft'], function(name, cm) {
      // Option is local. Do nothing for global.
      if (cm === undefined) {
        return;
      }
      // The 'filetype' option proxies to the CodeMirror 'mode' option.
      if (name === undefined) {
        var mode = cm.getOption('mode');
        return mode == 'null' ? '' : mode;
      } else {
        var mode = name == '' ? 'null' : name;
        cm.setOption('mode', mode);
      }
    });

    var createCircularJumpList = function() {
      var size = 100;
      var pointer = -1;
      var head = 0;
      var tail = 0;
      var buffer = new Array(size);
      function add(cm, oldCur, newCur) {
        var current = pointer % size;
        var curMark = buffer[current];
        function useNextSlot(cursor) {
          var next = ++pointer % size;
          var trashMark = buffer[next];
          if (trashMark) {
            trashMark.clear();
          }
          buffer[next] = cm.setBookmark(cursor);
        }
        if (curMark) {
          var markPos = curMark.find();
          // avoid recording redundant cursor position
          if (markPos && !cursorEqual(markPos, oldCur)) {
            useNextSlot(oldCur);
          }
        } else {
          useNextSlot(oldCur);
        }
        useNextSlot(newCur);
        head = pointer;
        tail = pointer - size + 1;
        if (tail < 0) {
          tail = 0;
        }
      }
      function move(cm, offset) {
        pointer += offset;
        if (pointer > head) {
          pointer = head;
        } else if (pointer < tail) {
          pointer = tail;
        }
        var mark = buffer[(size + pointer) % size];
        // skip marks that are temporarily removed from text buffer
        if (mark && !mark.find()) {
          var inc = offset > 0 ? 1 : -1;
          var newCur;
          var oldCur = cm.getCursor();
          do {
            pointer += inc;
            mark = buffer[(size + pointer) % size];
            // skip marks that are the same as current position
            if (mark &&
                (newCur = mark.find()) &&
                !cursorEqual(oldCur, newCur)) {
              break;
            }
          } while (pointer < head && pointer > tail);
        }
        return mark;
      }
      return {
        cachedCursor: undefined, //used for # and * jumps
        add: add,
        move: move
      };
    };

    // Returns an object to track the changes associated insert mode.  It
    // clones the object that is passed in, or creates an empty object one if
    // none is provided.
    var createInsertModeChanges = function(c) {
      if (c) {
        // Copy construction
        return {
          changes: c.changes,
          expectCursorActivityForChange: c.expectCursorActivityForChange
        };
      }
      return {
        // Change list
        changes: [],
        // Set to true on change, false on cursorActivity.
        expectCursorActivityForChange: false
      };
    };

    function MacroModeState() {
      this.latestRegister = undefined;
      this.isPlaying = false;
      this.isRecording = false;
      this.replaySearchQueries = [];
      this.onRecordingDone = undefined;
      this.lastInsertModeChanges = createInsertModeChanges();
    }
    MacroModeState.prototype = {
      exitMacroRecordMode: function() {
        var macroModeState = vimGlobalState.macroModeState;
        if (macroModeState.onRecordingDone) {
          macroModeState.onRecordingDone(); // close dialog
        }
        macroModeState.onRecordingDone = undefined;
        macroModeState.isRecording = false;
      },
      enterMacroRecordMode: function(cm, registerName) {
        var register =
            vimGlobalState.registerController.getRegister(registerName);
        if (register) {
          register.clear();
          this.latestRegister = registerName;
          if (cm.openDialog) {
            this.onRecordingDone = cm.openDialog(
                '(recording)['+registerName+']', null, {bottom:true});
          }
          this.isRecording = true;
        }
      }
    };

    function maybeInitVimState(cm) {
      if (!cm.state.vim) {
        // Store instance state in the CodeMirror object.
        cm.state.vim = {
          inputState: new InputState(),
          // Vim's input state that triggered the last edit, used to repeat
          // motions and operators with '.'.
          lastEditInputState: undefined,
          // Vim's action command before the last edit, used to repeat actions
          // with '.' and insert mode repeat.
          lastEditActionCommand: undefined,
          // When using jk for navigation, if you move from a longer line to a
          // shorter line, the cursor may clip to the end of the shorter line.
          // If j is pressed again and cursor goes to the next line, the
          // cursor should go back to its horizontal position on the longer
          // line if it can. This is to keep track of the horizontal position.
          lastHPos: -1,
          // Doing the same with screen-position for gj/gk
          lastHSPos: -1,
          // The last motion command run. Cleared if a non-motion command gets
          // executed in between.
          lastMotion: null,
          marks: {},
          // Mark for rendering fake cursor for visual mode.
          fakeCursor: null,
          insertMode: false,
          // Repeat count for changes made in insert mode, triggered by key
          // sequences like 3,i. Only exists when insertMode is true.
          insertModeRepeat: undefined,
          visualMode: false,
          // If we are in visual line mode. No effect if visualMode is false.
          visualLine: false,
          visualBlock: false,
          lastSelection: null,
          lastPastedText: null,
          sel: {},
          // Buffer-local/window-local values of vim options.
          options: {}
        };
      }
      return cm.state.vim;
    }
    var vimGlobalState;
    function resetVimGlobalState() {
      vimGlobalState = {
        // The current search query.
        searchQuery: null,
        // Whether we are searching backwards.
        searchIsReversed: false,
        // Replace part of the last substituted pattern
        lastSubstituteReplacePart: undefined,
        jumpList: createCircularJumpList(),
        macroModeState: new MacroModeState,
        // Recording latest f, t, F or T motion command.
        lastCharacterSearch: {increment:0, forward:true, selectedCharacter:''},
        registerController: new RegisterController({}),
        // search history buffer
        searchHistoryController: new HistoryController(),
        // ex Command history buffer
        exCommandHistoryController : new HistoryController()
      };
      for (var optionName in options) {
        var option = options[optionName];
        option.value = option.defaultValue;
      }
    }

    var lastInsertModeKeyTimer;
    var vimApi= {
      buildKeyMap: function() {
        // TODO: Convert keymap into dictionary format for fast lookup.
      },
      // Testing hook, though it might be useful to expose the register
      // controller anyways.
      getRegisterController: function() {
        return vimGlobalState.registerController;
      },
      // Testing hook.
      resetVimGlobalState_: resetVimGlobalState,

      // Testing hook.
      getVimGlobalState_: function() {
        return vimGlobalState;
      },

      // Testing hook.
      maybeInitVimState_: maybeInitVimState,

      suppressErrorLogging: false,

      InsertModeKey: InsertModeKey,
      map: function(lhs, rhs, ctx) {
        // Add user defined key bindings.
        exCommandDispatcher.map(lhs, rhs, ctx);
      },
      unmap: function(lhs, ctx) {
        exCommandDispatcher.unmap(lhs, ctx);
      },
      // TODO: Expose setOption and getOption as instance methods. Need to decide how to namespace
      // them, or somehow make them work with the existing CodeMirror setOption/getOption API.
      setOption: setOption,
      getOption: getOption,
      defineOption: defineOption,
      defineEx: function(name, prefix, func){
        if (!prefix) {
          prefix = name;
        } else if (name.indexOf(prefix) !== 0) {
          throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered');
        }
        exCommands[name]=func;
        exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'};
      },
      handleKey: function (cm, key, origin) {
        var command = this.findKey(cm, key, origin);
        if (typeof command === 'function') {
          return command();
        }
      },
      /**
       * This is the outermost function called by CodeMirror, after keys have
       * been mapped to their Vim equivalents.
       *
       * Finds a command based on the key (and cached keys if there is a
       * multi-key sequence). Returns `undefined` if no key is matched, a noop
       * function if a partial match is found (multi-key), and a function to
       * execute the bound command if a a key is matched. The function always
       * returns true.
       */
      findKey: function(cm, key, origin) {
        var vim = maybeInitVimState(cm);
        function handleMacroRecording() {
          var macroModeState = vimGlobalState.macroModeState;
          if (macroModeState.isRecording) {
            if (key == 'q') {
              macroModeState.exitMacroRecordMode();
              clearInputState(cm);
              return true;
            }
            if (origin != 'mapping') {
              logKey(macroModeState, key);
            }
          }
        }
        function handleEsc() {
          if (key == '<Esc>') {
            // Clear input state and get back to normal mode.
            clearInputState(cm);
            if (vim.visualMode) {
              exitVisualMode(cm);
            } else if (vim.insertMode) {
              exitInsertMode(cm);
            }
            return true;
          }
        }
        function doKeyToKey(keys) {
          // TODO: prevent infinite recursion.
          var match;
          while (keys) {
            // Pull off one command key, which is either a single character
            // or a special sequence wrapped in '<' and '>', e.g. '<Space>'.
            match = (/<\w+-.+?>|<\w+>|./).exec(keys);
            key = match[0];
            keys = keys.substring(match.index + key.length);
            CodeMirror.Vim.handleKey(cm, key, 'mapping');
          }
        }

        function handleKeyInsertMode() {
          if (handleEsc()) { return true; }
          var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;
          var keysAreChars = key.length == 1;
          var match = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
          // Need to check all key substrings in insert mode.
          while (keys.length > 1 && match.type != 'full') {
            var keys = vim.inputState.keyBuffer = keys.slice(1);
            var thisMatch = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
            if (thisMatch.type != 'none') { match = thisMatch; }
          }
          if (match.type == 'none') { clearInputState(cm); return false; }
          else if (match.type == 'partial') {
            if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
            lastInsertModeKeyTimer = window.setTimeout(
              function() { if (vim.insertMode && vim.inputState.keyBuffer) { clearInputState(cm); } },
              getOption('insertModeEscKeysTimeout'));
            return !keysAreChars;
          }

          if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
          if (keysAreChars) {
            var selections = cm.listSelections();
            for (var i = 0; i < selections.length; i++) {
              var here = selections[i].head;
              cm.replaceRange('', offsetCursor(here, 0, -(keys.length - 1)), here, '+input');
            }
            vimGlobalState.macroModeState.lastInsertModeChanges.changes.pop();
          }
          clearInputState(cm);
          return match.command;
        }

        function handleKeyNonInsertMode() {
          if (handleMacroRecording() || handleEsc()) { return true; }

          var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;
          if (/^[1-9]\d*$/.test(keys)) { return true; }

          var keysMatcher = /^(\d*)(.*)$/.exec(keys);
          if (!keysMatcher) { clearInputState(cm); return false; }
          var context = vim.visualMode ? 'visual' :
                                         'normal';
          var match = commandDispatcher.matchCommand(keysMatcher[2] || keysMatcher[1], defaultKeymap, vim.inputState, context);
          if (match.type == 'none') { clearInputState(cm); return false; }
          else if (match.type == 'partial') { return true; }

          vim.inputState.keyBuffer = '';
          var keysMatcher = /^(\d*)(.*)$/.exec(keys);
          if (keysMatcher[1] && keysMatcher[1] != '0') {
            vim.inputState.pushRepeatDigit(keysMatcher[1]);
          }
          return match.command;
        }

        var command;
        if (vim.insertMode) { command = handleKeyInsertMode(); }
        else { command = handleKeyNonInsertMode(); }
        if (command === false) {
          return !vim.insertMode && key.length === 1 ? function() { return true; } : undefined;
        } else if (command === true) {
          // TODO: Look into using CodeMirror's multi-key handling.
          // Return no-op since we are caching the key. Counts as handled, but
          // don't want act on it just yet.
          return function() { return true; };
        } else {
          return function() {
            return cm.operation(function() {
              cm.curOp.isVimOp = true;
              try {
                if (command.type == 'keyToKey') {
                  doKeyToKey(command.toKeys);
                } else {
                  commandDispatcher.processCommand(cm, vim, command);
                }
              } catch (e) {
                // clear VIM state in case it's in a bad state.
                cm.state.vim = undefined;
                maybeInitVimState(cm);
                if (!CodeMirror.Vim.suppressErrorLogging) {
                  console['log'](e);
                }
                throw e;
              }
              return true;
            });
          };
        }
      },
      handleEx: function(cm, input) {
        exCommandDispatcher.processCommand(cm, input);
      },

      defineMotion: defineMotion,
      defineAction: defineAction,
      defineOperator: defineOperator,
      mapCommand: mapCommand,
      _mapCommand: _mapCommand,

      defineRegister: defineRegister,

      exitVisualMode: exitVisualMode,
      exitInsertMode: exitInsertMode
    };

    // Represents the current input state.
    function InputState() {
      this.prefixRepeat = [];
      this.motionRepeat = [];

      this.operator = null;
      this.operatorArgs = null;
      this.motion = null;
      this.motionArgs = null;
      this.keyBuffer = []; // For matching multi-key commands.
      this.registerName = null; // Defaults to the unnamed register.
    }
    InputState.prototype.pushRepeatDigit = function(n) {
      if (!this.operator) {
        this.prefixRepeat = this.prefixRepeat.concat(n);
      } else {
        this.motionRepeat = this.motionRepeat.concat(n);
      }
    };
    InputState.prototype.getRepeat = function() {
      var repeat = 0;
      if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) {
        repeat = 1;
        if (this.prefixRepeat.length > 0) {
          repeat *= parseInt(this.prefixRepeat.join(''), 10);
        }
        if (this.motionRepeat.length > 0) {
          repeat *= parseInt(this.motionRepeat.join(''), 10);
        }
      }
      return repeat;
    };

    function clearInputState(cm, reason) {
      cm.state.vim.inputState = new InputState();
      CodeMirror.signal(cm, 'vim-command-done', reason);
    }

    /*
     * Register stores information about copy and paste registers.  Besides
     * text, a register must store whether it is linewise (i.e., when it is
     * pasted, should it insert itself into a new line, or should the text be
     * inserted at the cursor position.)
     */
    function Register(text, linewise, blockwise) {
      this.clear();
      this.keyBuffer = [text || ''];
      this.insertModeChanges = [];
      this.searchQueries = [];
      this.linewise = !!linewise;
      this.blockwise = !!blockwise;
    }
    Register.prototype = {
      setText: function(text, linewise, blockwise) {
        this.keyBuffer = [text || ''];
        this.linewise = !!linewise;
        this.blockwise = !!blockwise;
      },
      pushText: function(text, linewise) {
        // if this register has ever been set to linewise, use linewise.
        if (linewise) {
          if (!this.linewise) {
            this.keyBuffer.push('\n');
          }
          this.linewise = true;
        }
        this.keyBuffer.push(text);
      },
      pushInsertModeChanges: function(changes) {
        this.insertModeChanges.push(createInsertModeChanges(changes));
      },
      pushSearchQuery: function(query) {
        this.searchQueries.push(query);
      },
      clear: function() {
        this.keyBuffer = [];
        this.insertModeChanges = [];
        this.searchQueries = [];
        this.linewise = false;
      },
      toString: function() {
        return this.keyBuffer.join('');
      }
    };

    /**
     * Defines an external register.
     *
     * The name should be a single character that will be used to reference the register.
     * The register should support setText, pushText, clear, and toString(). See Register
     * for a reference implementation.
     */
    function defineRegister(name, register) {
      var registers = vimGlobalState.registerController.registers;
      if (!name || name.length != 1) {
        throw Error('Register name must be 1 character');
      }
      if (registers[name]) {
        throw Error('Register already defined ' + name);
      }
      registers[name] = register;
      validRegisters.push(name);
    }

    /*
     * vim registers allow you to keep many independent copy and paste buffers.
     * See http://usevim.com/2012/04/13/registers/ for an introduction.
     *
     * RegisterController keeps the state of all the registers.  An initial
     * state may be passed in.  The unnamed register '"' will always be
     * overridden.
     */
    function RegisterController(registers) {
      this.registers = registers;
      this.unnamedRegister = registers['"'] = new Register();
      registers['.'] = new Register();
      registers[':'] = new Register();
      registers['/'] = new Register();
    }
    RegisterController.prototype = {
      pushText: function(registerName, operator, text, linewise, blockwise) {
        if (linewise && text.charAt(text.length - 1) !== '\n'){
          text += '\n';
        }
        // Lowercase and uppercase registers refer to the same register.
        // Uppercase just means append.
        var register = this.isValidRegister(registerName) ?
            this.getRegister(registerName) : null;
        // if no register/an invalid register was specified, things go to the
        // default registers
        if (!register) {
          switch (operator) {
            case 'yank':
              // The 0 register contains the text from the most recent yank.
              this.registers['0'] = new Register(text, linewise, blockwise);
              break;
            case 'delete':
            case 'change':
              if (text.indexOf('\n') == -1) {
                // Delete less than 1 line. Update the small delete register.
                this.registers['-'] = new Register(text, linewise);
              } else {
                // Shift down the contents of the numbered registers and put the
                // deleted text into register 1.
                this.shiftNumericRegisters_();
                this.registers['1'] = new Register(text, linewise);
              }
              break;
          }
          // Make sure the unnamed register is set to what just happened
          this.unnamedRegister.setText(text, linewise, blockwise);
          return;
        }

        // If we've gotten to this point, we've actually specified a register
        var append = isUpperCase(registerName);
        if (append) {
          register.pushText(text, linewise);
        } else {
          register.setText(text, linewise, blockwise);
        }
        // The unnamed register always has the same value as the last used
        // register.
        this.unnamedRegister.setText(register.toString(), linewise);
      },
      // Gets the register named @name.  If one of @name doesn't already exist,
      // create it.  If @name is invalid, return the unnamedRegister.
      getRegister: function(name) {
        if (!this.isValidRegister(name)) {
          return this.unnamedRegister;
        }
        name = name.toLowerCase();
        if (!this.registers[name]) {
          this.registers[name] = new Register();
        }
        return this.registers[name];
      },
      isValidRegister: function(name) {
        return name && inArray(name, validRegisters);
      },
      shiftNumericRegisters_: function() {
        for (var i = 9; i >= 2; i--) {
          this.registers[i] = this.getRegister('' + (i - 1));
        }
      }
    };
    function HistoryController() {
        this.historyBuffer = [];
        this.iterator = 0;
        this.initialPrefix = null;
    }
    HistoryController.prototype = {
      // the input argument here acts a user entered prefix for a small time
      // until we start autocompletion in which case it is the autocompleted.
      nextMatch: function (input, up) {
        var historyBuffer = this.historyBuffer;
        var dir = up ? -1 : 1;
        if (this.initialPrefix === null) this.initialPrefix = input;
        for (var i = this.iterator + dir; up ? i >= 0 : i < historyBuffer.length; i+= dir) {
          var element = historyBuffer[i];
          for (var j = 0; j <= element.length; j++) {
            if (this.initialPrefix == element.substring(0, j)) {
              this.iterator = i;
              return element;
            }
          }
        }
        // should return the user input in case we reach the end of buffer.
        if (i >= historyBuffer.length) {
          this.iterator = historyBuffer.length;
          return this.initialPrefix;
        }
        // return the last autocompleted query or exCommand as it is.
        if (i < 0 ) return input;
      },
      pushInput: function(input) {
        var index = this.historyBuffer.indexOf(input);
        if (index > -1) this.historyBuffer.splice(index, 1);
        if (input.length) this.historyBuffer.push(input);
      },
      reset: function() {
        this.initialPrefix = null;
        this.iterator = this.historyBuffer.length;
      }
    };
    var commandDispatcher = {
      matchCommand: function(keys, keyMap, inputState, context) {
        var matches = commandMatches(keys, keyMap, context, inputState);
        if (!matches.full && !matches.partial) {
          return {type: 'none'};
        } else if (!matches.full && matches.partial) {
          return {type: 'partial'};
        }

        var bestMatch;
        for (var i = 0; i < matches.full.length; i++) {
          var match = matches.full[i];
          if (!bestMatch) {
            bestMatch = match;
          }
        }
        if (bestMatch.keys.slice(-11) == '<character>') {
          var character = lastChar(keys);
          if (!character) return {type: 'none'};
          inputState.selectedCharacter = character;
        }
        return {type: 'full', command: bestMatch};
      },
      processCommand: function(cm, vim, command) {
        vim.inputState.repeatOverride = command.repeatOverride;
        switch (command.type) {
          case 'motion':
            this.processMotion(cm, vim, command);
            break;
          case 'operator':
            this.processOperator(cm, vim, command);
            break;
          case 'operatorMotion':
            this.processOperatorMotion(cm, vim, command);
            break;
          case 'action':
            this.processAction(cm, vim, command);
            break;
          case 'search':
            this.processSearch(cm, vim, command);
            break;
          case 'ex':
          case 'keyToEx':
            this.processEx(cm, vim, command);
            break;
          default:
            break;
        }
      },
      processMotion: function(cm, vim, command) {
        vim.inputState.motion = command.motion;
        vim.inputState.motionArgs = copyArgs(command.motionArgs);
        this.evalInput(cm, vim);
      },
      processOperator: function(cm, vim, command) {
        var inputState = vim.inputState;
        if (inputState.operator) {
          if (inputState.operator == command.operator) {
            // Typing an operator twice like 'dd' makes the operator operate
            // linewise
            inputState.motion = 'expandToLine';
            inputState.motionArgs = { linewise: true };
            this.evalInput(cm, vim);
            return;
          } else {
            // 2 different operators in a row doesn't make sense.
            clearInputState(cm);
          }
        }
        inputState.operator = command.operator;
        inputState.operatorArgs = copyArgs(command.operatorArgs);
        if (vim.visualMode) {
          // Operating on a selection in visual mode. We don't need a motion.
          this.evalInput(cm, vim);
        }
      },
      processOperatorMotion: function(cm, vim, command) {
        var visualMode = vim.visualMode;
        var operatorMotionArgs = copyArgs(command.operatorMotionArgs);
        if (operatorMotionArgs) {
          // Operator motions may have special behavior in visual mode.
          if (visualMode && operatorMotionArgs.visualLine) {
            vim.visualLine = true;
          }
        }
        this.processOperator(cm, vim, command);
        if (!visualMode) {
          this.processMotion(cm, vim, command);
        }
      },
      processAction: function(cm, vim, command) {
        var inputState = vim.inputState;
        var repeat = inputState.getRepeat();
        var repeatIsExplicit = !!repeat;
        var actionArgs = copyArgs(command.actionArgs) || {};
        if (inputState.selectedCharacter) {
          actionArgs.selectedCharacter = inputState.selectedCharacter;
        }
        // Actions may or may not have motions and operators. Do these first.
        if (command.operator) {
          this.processOperator(cm, vim, command);
        }
        if (command.motion) {
          this.processMotion(cm, vim, command);
        }
        if (command.motion || command.operator) {
          this.evalInput(cm, vim);
        }
        actionArgs.repeat = repeat || 1;
        actionArgs.repeatIsExplicit = repeatIsExplicit;
        actionArgs.registerName = inputState.registerName;
        clearInputState(cm);
        vim.lastMotion = null;
        if (command.isEdit) {
          this.recordLastEdit(vim, inputState, command);
        }
        actions[command.action](cm, actionArgs, vim);
      },
      processSearch: function(cm, vim, command) {
        if (!cm.getSearchCursor) {
          // Search depends on SearchCursor.
          return;
        }
        var forward = command.searchArgs.forward;
        var wholeWordOnly = command.searchArgs.wholeWordOnly;
        getSearchState(cm).setReversed(!forward);
        var promptPrefix = (forward) ? '/' : '?';
        var originalQuery = getSearchState(cm).getQuery();
        var originalScrollPos = cm.getScrollInfo();
        function handleQuery(query, ignoreCase, smartCase) {
          vimGlobalState.searchHistoryController.pushInput(query);
          vimGlobalState.searchHistoryController.reset();
          try {
            updateSearchQuery(cm, query, ignoreCase, smartCase);
          } catch (e) {
            showConfirm(cm, 'Invalid regex: ' + query);
            clearInputState(cm);
            return;
          }
          commandDispatcher.processMotion(cm, vim, {
            type: 'motion',
            motion: 'findNext',
            motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist }
          });
        }
        function onPromptClose(query) {
          cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
          handleQuery(query, true /** ignoreCase */, true /** smartCase */);
          var macroModeState = vimGlobalState.macroModeState;
          if (macroModeState.isRecording) {
            logSearchQuery(macroModeState, query);
          }
        }
        function onPromptKeyUp(e, query, close) {
          var keyName = CodeMirror.keyName(e), up, offset;
          if (keyName == 'Up' || keyName == 'Down') {
            up = keyName == 'Up' ? true : false;
            offset = e.target ? e.target.selectionEnd : 0;
            query = vimGlobalState.searchHistoryController.nextMatch(query, up) || '';
            close(query);
            if (offset && e.target) e.target.selectionEnd = e.target.selectionStart = Math.min(offset, e.target.value.length);
          } else {
            if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift')
              vimGlobalState.searchHistoryController.reset();
          }
          var parsedQuery;
          try {
            parsedQuery = updateSearchQuery(cm, query,
                true /** ignoreCase */, true /** smartCase */);
          } catch (e) {
            // Swallow bad regexes for incremental search.
          }
          if (parsedQuery) {
            cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30);
          } else {
            clearSearchHighlight(cm);
            cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
          }
        }
        function onPromptKeyDown(e, query, close) {
          var keyName = CodeMirror.keyName(e);
          if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' ||
              (keyName == 'Backspace' && query == '')) {
            vimGlobalState.searchHistoryController.pushInput(query);
            vimGlobalState.searchHistoryController.reset();
            updateSearchQuery(cm, originalQuery);
            clearSearchHighlight(cm);
            cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
            CodeMirror.e_stop(e);
            clearInputState(cm);
            close();
            cm.focus();
          } else if (keyName == 'Up' || keyName == 'Down') {
            CodeMirror.e_stop(e);
          } else if (keyName == 'Ctrl-U') {
            // Ctrl-U clears input.
            CodeMirror.e_stop(e);
            close('');
          }
        }
        switch (command.searchArgs.querySrc) {
          case 'prompt':
            var macroModeState = vimGlobalState.macroModeState;
            if (macroModeState.isPlaying) {
              var query = macroModeState.replaySearchQueries.shift();
              handleQuery(query, true /** ignoreCase */, false /** smartCase */);
            } else {
              showPrompt(cm, {
                  onClose: onPromptClose,
                  prefix: promptPrefix,
                  desc: searchPromptDesc,
                  onKeyUp: onPromptKeyUp,
                  onKeyDown: onPromptKeyDown
              });
            }
            break;
          case 'wordUnderCursor':
            var word = expandWordUnderCursor(cm, false /** inclusive */,
                true /** forward */, false /** bigWord */,
                true /** noSymbol */);
            var isKeyword = true;
            if (!word) {
              word = expandWordUnderCursor(cm, false /** inclusive */,
                  true /** forward */, false /** bigWord */,
                  false /** noSymbol */);
              isKeyword = false;
            }
            if (!word) {
              return;
            }
            var query = cm.getLine(word.start.line).substring(word.start.ch,
                word.end.ch);
            if (isKeyword && wholeWordOnly) {
                query = '\\b' + query + '\\b';
            } else {
              query = escapeRegex(query);
            }

            // cachedCursor is used to save the old position of the cursor
            // when * or # causes vim to seek for the nearest word and shift
            // the cursor before entering the motion.
            vimGlobalState.jumpList.cachedCursor = cm.getCursor();
            cm.setCursor(word.start);

            handleQuery(query, true /** ignoreCase */, false /** smartCase */);
            break;
        }
      },
      processEx: function(cm, vim, command) {
        function onPromptClose(input) {
          // Give the prompt some time to close so that if processCommand shows
          // an error, the elements don't overlap.
          vimGlobalState.exCommandHistoryController.pushInput(input);
          vimGlobalState.exCommandHistoryController.reset();
          exCommandDispatcher.processCommand(cm, input);
        }
        function onPromptKeyDown(e, input, close) {
          var keyName = CodeMirror.keyName(e), up, offset;
          if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' ||
              (keyName == 'Backspace' && input == '')) {
            vimGlobalState.exCommandHistoryController.pushInput(input);
            vimGlobalState.exCommandHistoryController.reset();
            CodeMirror.e_stop(e);
            clearInputState(cm);
            close();
            cm.focus();
          }
          if (keyName == 'Up' || keyName == 'Down') {
            CodeMirror.e_stop(e);
            up = keyName == 'Up' ? true : false;
            offset = e.target ? e.target.selectionEnd : 0;
            input = vimGlobalState.exCommandHistoryController.nextMatch(input, up) || '';
            close(input);
            if (offset && e.target) e.target.selectionEnd = e.target.selectionStart = Math.min(offset, e.target.value.length);
          } else if (keyName == 'Ctrl-U') {
            // Ctrl-U clears input.
            CodeMirror.e_stop(e);
            close('');
          } else {
            if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift')
              vimGlobalState.exCommandHistoryController.reset();
          }
        }
        if (command.type == 'keyToEx') {
          // Handle user defined Ex to Ex mappings
          exCommandDispatcher.processCommand(cm, command.exArgs.input);
        } else {
          if (vim.visualMode) {
            showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>',
                onKeyDown: onPromptKeyDown, selectValueOnOpen: false});
          } else {
            showPrompt(cm, { onClose: onPromptClose, prefix: ':',
                onKeyDown: onPromptKeyDown});
          }
        }
      },
      evalInput: function(cm, vim) {
        // If the motion command is set, execute both the operator and motion.
        // Otherwise return.
        var inputState = vim.inputState;
        var motion = inputState.motion;
        var motionArgs = inputState.motionArgs || {};
        var operator = inputState.operator;
        var operatorArgs = inputState.operatorArgs || {};
        var registerName = inputState.registerName;
        var sel = vim.sel;
        // TODO: Make sure cm and vim selections are identical outside visual mode.
        var origHead = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.head): cm.getCursor('head'));
        var origAnchor = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.anchor) : cm.getCursor('anchor'));
        var oldHead = copyCursor(origHead);
        var oldAnchor = copyCursor(origAnchor);
        var newHead, newAnchor;
        var repeat;
        if (operator) {
          this.recordLastEdit(vim, inputState);
        }
        if (inputState.repeatOverride !== undefined) {
          // If repeatOverride is specified, that takes precedence over the
          // input state's repeat. Used by Ex mode and can be user defined.
          repeat = inputState.repeatOverride;
        } else {
          repeat = inputState.getRepeat();
        }
        if (repeat > 0 && motionArgs.explicitRepeat) {
          motionArgs.repeatIsExplicit = true;
        } else if (motionArgs.noRepeat ||
            (!motionArgs.explicitRepeat && repeat === 0)) {
          repeat = 1;
          motionArgs.repeatIsExplicit = false;
        }
        if (inputState.selectedCharacter) {
          // If there is a character input, stick it in all of the arg arrays.
          motionArgs.selectedCharacter = operatorArgs.selectedCharacter =
              inputState.selectedCharacter;
        }
        motionArgs.repeat = repeat;
        clearInputState(cm);
        if (motion) {
          var motionResult = motions[motion](cm, origHead, motionArgs, vim);
          vim.lastMotion = motions[motion];
          if (!motionResult) {
            return;
          }
          if (motionArgs.toJumplist) {
            var jumpList = vimGlobalState.jumpList;
            // if the current motion is # or *, use cachedCursor
            var cachedCursor = jumpList.cachedCursor;
            if (cachedCursor) {
              recordJumpPosition(cm, cachedCursor, motionResult);
              delete jumpList.cachedCursor;
            } else {
              recordJumpPosition(cm, origHead, motionResult);
            }
          }
          if (motionResult instanceof Array) {
            newAnchor = motionResult[0];
            newHead = motionResult[1];
          } else {
            newHead = motionResult;
          }
          // TODO: Handle null returns from motion commands better.
          if (!newHead) {
            newHead = copyCursor(origHead);
          }
          if (vim.visualMode) {
            if (!(vim.visualBlock && newHead.ch === Infinity)) {
              newHead = clipCursorToContent(cm, newHead, vim.visualBlock);
            }
            if (newAnchor) {
              newAnchor = clipCursorToContent(cm, newAnchor, true);
            }
            newAnchor = newAnchor || oldAnchor;
            sel.anchor = newAnchor;
            sel.head = newHead;
            updateCmSelection(cm);
            updateMark(cm, vim, '<',
                cursorIsBefore(newAnchor, newHead) ? newAnchor
                    : newHead);
            updateMark(cm, vim, '>',
                cursorIsBefore(newAnchor, newHead) ? newHead
                    : newAnchor);
          } else if (!operator) {
            newHead = clipCursorToContent(cm, newHead);
            cm.setCursor(newHead.line, newHead.ch);
          }
        }
        if (operator) {
          if (operatorArgs.lastSel) {
            // Replaying a visual mode operation
            newAnchor = oldAnchor;
            var lastSel = operatorArgs.lastSel;
            var lineOffset = Math.abs(lastSel.head.line - lastSel.anchor.line);
            var chOffset = Math.abs(lastSel.head.ch - lastSel.anchor.ch);
            if (lastSel.visualLine) {
              // Linewise Visual mode: The same number of lines.
              newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
            } else if (lastSel.visualBlock) {
              // Blockwise Visual mode: The same number of lines and columns.
              newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch + chOffset);
            } else if (lastSel.head.line == lastSel.anchor.line) {
              // Normal Visual mode within one line: The same number of characters.
              newHead = Pos(oldAnchor.line, oldAnchor.ch + chOffset);
            } else {
              // Normal Visual mode with several lines: The same number of lines, in the
              // last line the same number of characters as in the last line the last time.
              newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
            }
            vim.visualMode = true;
            vim.visualLine = lastSel.visualLine;
            vim.visualBlock = lastSel.visualBlock;
            sel = vim.sel = {
              anchor: newAnchor,
              head: newHead
            };
            updateCmSelection(cm);
          } else if (vim.visualMode) {
            operatorArgs.lastSel = {
              anchor: copyCursor(sel.anchor),
              head: copyCursor(sel.head),
              visualBlock: vim.visualBlock,
              visualLine: vim.visualLine
            };
          }
          var curStart, curEnd, linewise, mode;
          var cmSel;
          if (vim.visualMode) {
            // Init visual op
            curStart = cursorMin(sel.head, sel.anchor);
            curEnd = cursorMax(sel.head, sel.anchor);
            linewise = vim.visualLine || operatorArgs.linewise;
            mode = vim.visualBlock ? 'block' :
                   linewise ? 'line' :
                   'char';
            cmSel = makeCmSelection(cm, {
              anchor: curStart,
              head: curEnd
            }, mode);
            if (linewise) {
              var ranges = cmSel.ranges;
              if (mode == 'block') {
                // Linewise operators in visual block mode extend to end of line
                for (var i = 0; i < ranges.length; i++) {
                  ranges[i].head.ch = lineLength(cm, ranges[i].head.line);
                }
              } else if (mode == 'line') {
                ranges[0].head = Pos(ranges[0].head.line + 1, 0);
              }
            }
          } else {
            // Init motion op
            curStart = copyCursor(newAnchor || oldAnchor);
            curEnd = copyCursor(newHead || oldHead);
            if (cursorIsBefore(curEnd, curStart)) {
              var tmp = curStart;
              curStart = curEnd;
              curEnd = tmp;
            }
            linewise = motionArgs.linewise || operatorArgs.linewise;
            if (linewise) {
              // Expand selection to entire line.
              expandSelectionToLine(cm, curStart, curEnd);
            } else if (motionArgs.forward) {
              // Clip to trailing newlines only if the motion goes forward.
              clipToLine(cm, curStart, curEnd);
            }
            mode = 'char';
            var exclusive = !motionArgs.inclusive || linewise;
            cmSel = makeCmSelection(cm, {
              anchor: curStart,
              head: curEnd
            }, mode, exclusive);
          }
          cm.setSelections(cmSel.ranges, cmSel.primary);
          vim.lastMotion = null;
          operatorArgs.repeat = repeat; // For indent in visual mode.
          operatorArgs.registerName = registerName;
          // Keep track of linewise as it affects how paste and change behave.
          operatorArgs.linewise = linewise;
          var operatorMoveTo = operators[operator](
            cm, operatorArgs, cmSel.ranges, oldAnchor, newHead);
          if (vim.visualMode) {
            exitVisualMode(cm, operatorMoveTo != null);
          }
          if (operatorMoveTo) {
            cm.setCursor(operatorMoveTo);
          }
        }
      },
      recordLastEdit: function(vim, inputState, actionCommand) {
        var macroModeState = vimGlobalState.macroModeState;
        if (macroModeState.isPlaying) { return; }
        vim.lastEditInputState = inputState;
        vim.lastEditActionCommand = actionCommand;
        macroModeState.lastInsertModeChanges.changes = [];
        macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false;
      }
    };

    /**
     * typedef {Object{line:number,ch:number}} Cursor An object containing the
     *     position of the cursor.
     */
    // All of the functions below return Cursor objects.
    var motions = {
      moveToTopLine: function(cm, _head, motionArgs) {
        var line = getUserVisibleLines(cm).top + motionArgs.repeat -1;
        return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
      },
      moveToMiddleLine: function(cm) {
        var range = getUserVisibleLines(cm);
        var line = Math.floor((range.top + range.bottom) * 0.5);
        return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
      },
      moveToBottomLine: function(cm, _head, motionArgs) {
        var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1;
        return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
      },
      expandToLine: function(_cm, head, motionArgs) {
        // Expands forward to end of line, and then to next line if repeat is
        // >1. Does not handle backward motion!
        var cur = head;
        return Pos(cur.line + motionArgs.repeat - 1, Infinity);
      },
      findNext: function(cm, _head, motionArgs) {
        var state = getSearchState(cm);
        var query = state.getQuery();
        if (!query) {
          return;
        }
        var prev = !motionArgs.forward;
        // If search is initiated with ? instead of /, negate direction.
        prev = (state.isReversed()) ? !prev : prev;
        highlightSearchMatches(cm, query);
        return findNext(cm, prev/** prev */, query, motionArgs.repeat);
      },
      goToMark: function(cm, _head, motionArgs, vim) {
        var pos = getMarkPos(cm, vim, motionArgs.selectedCharacter);
        if (pos) {
          return motionArgs.linewise ? { line: pos.line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(pos.line)) } : pos;
        }
        return null;
      },
      moveToOtherHighlightedEnd: function(cm, _head, motionArgs, vim) {
        if (vim.visualBlock && motionArgs.sameLine) {
          var sel = vim.sel;
          return [
            clipCursorToContent(cm, Pos(sel.anchor.line, sel.head.ch)),
            clipCursorToContent(cm, Pos(sel.head.line, sel.anchor.ch))
          ];
        } else {
          return ([vim.sel.head, vim.sel.anchor]);
        }
      },
      jumpToMark: function(cm, head, motionArgs, vim) {
        var best = head;
        for (var i = 0; i < motionArgs.repeat; i++) {
          var cursor = best;
          for (var key in vim.marks) {
            if (!isLowerCase(key)) {
              continue;
            }
            var mark = vim.marks[key].find();
            var isWrongDirection = (motionArgs.forward) ?
              cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark);

            if (isWrongDirection) {
              continue;
            }
            if (motionArgs.linewise && (mark.line == cursor.line)) {
              continue;
            }

            var equal = cursorEqual(cursor, best);
            var between = (motionArgs.forward) ?
              cursorIsBetween(cursor, mark, best) :
              cursorIsBetween(best, mark, cursor);

            if (equal || between) {
              best = mark;
            }
          }
        }

        if (motionArgs.linewise) {
          // Vim places the cursor on the first non-whitespace character of
          // the line if there is one, else it places the cursor at the end
          // of the line, regardless of whether a mark was found.
          best = Pos(best.line, findFirstNonWhiteSpaceCharacter(cm.getLine(best.line)));
        }
        return best;
      },
      moveByCharacters: function(_cm, head, motionArgs) {
        var cur = head;
        var repeat = motionArgs.repeat;
        var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat;
        return Pos(cur.line, ch);
      },
      moveByLines: function(cm, head, motionArgs, vim) {
        var cur = head;
        var endCh = cur.ch;
        // Depending what our last motion was, we may want to do different
        // things. If our last motion was moving vertically, we want to
        // preserve the HPos from our last horizontal move.  If our last motion
        // was going to the end of a line, moving vertically we should go to
        // the end of the line, etc.
        switch (vim.lastMotion) {
          case this.moveByLines:
          case this.moveByDisplayLines:
          case this.moveByScroll:
          case this.moveToColumn:
          case this.moveToEol:
            endCh = vim.lastHPos;
            break;
          default:
            vim.lastHPos = endCh;
        }
        var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0);
        var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat;
        var first = cm.firstLine();
        var last = cm.lastLine();
        // Vim go to line begin or line end when cursor at first/last line and
        // move to previous/next line is triggered.
        if (line < first && cur.line == first){
          return this.moveToStartOfLine(cm, head, motionArgs, vim);
        }else if (line > last && cur.line == last){
            return this.moveToEol(cm, head, motionArgs, vim);
        }
        if (motionArgs.toFirstChar){
          endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line));
          vim.lastHPos = endCh;
        }
        vim.lastHSPos = cm.charCoords(Pos(line, endCh),'div').left;
        return Pos(line, endCh);
      },
      moveByDisplayLines: function(cm, head, motionArgs, vim) {
        var cur = head;
        switch (vim.lastMotion) {
          case this.moveByDisplayLines:
          case this.moveByScroll:
          case this.moveByLines:
          case this.moveToColumn:
          case this.moveToEol:
            break;
          default:
            vim.lastHSPos = cm.charCoords(cur,'div').left;
        }
        var repeat = motionArgs.repeat;
        var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos);
        if (res.hitSide) {
          if (motionArgs.forward) {
            var lastCharCoords = cm.charCoords(res, 'div');
            var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos };
            var res = cm.coordsChar(goalCoords, 'div');
          } else {
            var resCoords = cm.charCoords(Pos(cm.firstLine(), 0), 'div');
            resCoords.left = vim.lastHSPos;
            res = cm.coordsChar(resCoords, 'div');
          }
        }
        vim.lastHPos = res.ch;
        return res;
      },
      moveByPage: function(cm, head, motionArgs) {
        // CodeMirror only exposes functions that move the cursor page down, so
        // doing this bad hack to move the cursor and move it back. evalInput
        // will move the cursor to where it should be in the end.
        var curStart = head;
        var repeat = motionArgs.repeat;
        return cm.findPosV(curStart, (motionArgs.forward ? repeat : -repeat), 'page');
      },
      moveByParagraph: function(cm, head, motionArgs) {
        var dir = motionArgs.forward ? 1 : -1;
        return findParagraph(cm, head, motionArgs.repeat, dir);
      },
      moveBySentence: function(cm, head, motionArgs) {
        var dir = motionArgs.forward ? 1 : -1;
        return findSentence(cm, head, motionArgs.repeat, dir);
      },
      moveByScroll: function(cm, head, motionArgs, vim) {
        var scrollbox = cm.getScrollInfo();
        var curEnd = null;
        var repeat = motionArgs.repeat;
        if (!repeat) {
          repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight());
        }
        var orig = cm.charCoords(head, 'local');
        motionArgs.repeat = repeat;
        var curEnd = motions.moveByDisplayLines(cm, head, motionArgs, vim);
        if (!curEnd) {
          return null;
        }
        var dest = cm.charCoords(curEnd, 'local');
        cm.scrollTo(null, scrollbox.top + dest.top - orig.top);
        return curEnd;
      },
      moveByWords: function(cm, head, motionArgs) {
        return moveToWord(cm, head, motionArgs.repeat, !!motionArgs.forward,
            !!motionArgs.wordEnd, !!motionArgs.bigWord);
      },
      moveTillCharacter: function(cm, _head, motionArgs) {
        var repeat = motionArgs.repeat;
        var curEnd = moveToCharacter(cm, repeat, motionArgs.forward,
            motionArgs.selectedCharacter);
        var increment = motionArgs.forward ? -1 : 1;
        recordLastCharacterSearch(increment, motionArgs);
        if (!curEnd) return null;
        curEnd.ch += increment;
        return curEnd;
      },
      moveToCharacter: function(cm, head, motionArgs) {
        var repeat = motionArgs.repeat;
        recordLastCharacterSearch(0, motionArgs);
        return moveToCharacter(cm, repeat, motionArgs.forward,
            motionArgs.selectedCharacter) || head;
      },
      moveToSymbol: function(cm, head, motionArgs) {
        var repeat = motionArgs.repeat;
        return findSymbol(cm, repeat, motionArgs.forward,
            motionArgs.selectedCharacter) || head;
      },
      moveToColumn: function(cm, head, motionArgs, vim) {
        var repeat = motionArgs.repeat;
        // repeat is equivalent to which column we want to move to!
        vim.lastHPos = repeat - 1;
        vim.lastHSPos = cm.charCoords(head,'div').left;
        return moveToColumn(cm, repeat);
      },
      moveToEol: function(cm, head, motionArgs, vim) {
        var cur = head;
        vim.lastHPos = Infinity;
        var retval= Pos(cur.line + motionArgs.repeat - 1, Infinity);
        var end=cm.clipPos(retval);
        end.ch--;
        vim.lastHSPos = cm.charCoords(end,'div').left;
        return retval;
      },
      moveToFirstNonWhiteSpaceCharacter: function(cm, head) {
        // Go to the start of the line where the text begins, or the end for
        // whitespace-only lines
        var cursor = head;
        return Pos(cursor.line,
                   findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)));
      },
      moveToMatchedSymbol: function(cm, head) {
        var cursor = head;
        var line = cursor.line;
        var ch = cursor.ch;
        var lineText = cm.getLine(line);
        var symbol;
        for (; ch < lineText.length; ch++) {
          symbol = lineText.charAt(ch);
          if (symbol && isMatchableSymbol(symbol)) {
            var style = cm.getTokenTypeAt(Pos(line, ch + 1));
            if (style !== "string" && style !== "comment") {
              break;
            }
          }
        }
        if (ch < lineText.length) {
          var matched = cm.findMatchingBracket(Pos(line, ch));
          return matched.to;
        } else {
          return cursor;
        }
      },
      moveToStartOfLine: function(_cm, head) {
        return Pos(head.line, 0);
      },
      moveToLineOrEdgeOfDocument: function(cm, _head, motionArgs) {
        var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine();
        if (motionArgs.repeatIsExplicit) {
          lineNum = motionArgs.repeat - cm.getOption('firstLineNumber');
        }
        return Pos(lineNum,
                   findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)));
      },
      textObjectManipulation: function(cm, head, motionArgs, vim) {
        // TODO: lots of possible exceptions that can be thrown here. Try da(
        //     outside of a () block.

        // TODO: adding <> >< to this map doesn't work, presumably because
        // they're operators
        var mirroredPairs = {'(': ')', ')': '(',
                             '{': '}', '}': '{',
                             '[': ']', ']': '['};
        var selfPaired = {'\'': true, '"': true};

        var character = motionArgs.selectedCharacter;
        // 'b' refers to  '()' block.
        // 'B' refers to  '{}' block.
        if (character == 'b') {
          character = '(';
        } else if (character == 'B') {
          character = '{';
        }

        // Inclusive is the difference between a and i
        // TODO: Instead of using the additional text object map to perform text
        //     object operations, merge the map into the defaultKeyMap and use
        //     motionArgs to define behavior. Define separate entries for 'aw',
        //     'iw', 'a[', 'i[', etc.
        var inclusive = !motionArgs.textObjectInner;

        var tmp;
        if (mirroredPairs[character]) {
          tmp = selectCompanionObject(cm, head, character, inclusive);
        } else if (selfPaired[character]) {
          tmp = findBeginningAndEnd(cm, head, character, inclusive);
        } else if (character === 'W') {
          tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
                                                     true /** bigWord */);
        } else if (character === 'w') {
          tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
                                                     false /** bigWord */);
        } else if (character === 'p') {
          tmp = findParagraph(cm, head, motionArgs.repeat, 0, inclusive);
          motionArgs.linewise = true;
          if (vim.visualMode) {
            if (!vim.visualLine) { vim.visualLine = true; }
          } else {
            var operatorArgs = vim.inputState.operatorArgs;
            if (operatorArgs) { operatorArgs.linewise = true; }
            tmp.end.line--;
          }
        } else {
          // No text object defined for this, don't move.
          return null;
        }

        if (!cm.state.vim.visualMode) {
          return [tmp.start, tmp.end];
        } else {
          return expandSelection(cm, tmp.start, tmp.end);
        }
      },

      repeatLastCharacterSearch: function(cm, head, motionArgs) {
        var lastSearch = vimGlobalState.lastCharacterSearch;
        var repeat = motionArgs.repeat;
        var forward = motionArgs.forward === lastSearch.forward;
        var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1);
        cm.moveH(-increment, 'char');
        motionArgs.inclusive = forward ? true : false;
        var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter);
        if (!curEnd) {
          cm.moveH(increment, 'char');
          return head;
        }
        curEnd.ch += increment;
        return curEnd;
      }
    };

    function defineMotion(name, fn) {
      motions[name] = fn;
    }

    function fillArray(val, times) {
      var arr = [];
      for (var i = 0; i < times; i++) {
        arr.push(val);
      }
      return arr;
    }
    /**
     * An operator acts on a text selection. It receives the list of selections
     * as input. The corresponding CodeMirror selection is guaranteed to
    * match the input selection.
     */
    var operators = {
      change: function(cm, args, ranges) {
        var finalHead, text;
        var vim = cm.state.vim;
        vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock = vim.visualBlock;
        if (!vim.visualMode) {
          var anchor = ranges[0].anchor,
              head = ranges[0].head;
          text = cm.getRange(anchor, head);
          var lastState = vim.lastEditInputState || {};
          if (lastState.motion == "moveByWords" && !isWhiteSpaceString(text)) {
            // Exclude trailing whitespace if the range is not all whitespace.
            var match = (/\s+$/).exec(text);
            if (match && lastState.motionArgs && lastState.motionArgs.forward) {
              head = offsetCursor(head, 0, - match[0].length);
              text = text.slice(0, - match[0].length);
            }
          }
          var prevLineEnd = new Pos(anchor.line - 1, Number.MAX_VALUE);
          var wasLastLine = cm.firstLine() == cm.lastLine();
          if (head.line > cm.lastLine() && args.linewise && !wasLastLine) {
            cm.replaceRange('', prevLineEnd, head);
          } else {
            cm.replaceRange('', anchor, head);
          }
          if (args.linewise) {
            // Push the next line back down, if there is a next line.
            if (!wasLastLine) {
              cm.setCursor(prevLineEnd);
              CodeMirror.commands.newlineAndIndent(cm);
            }
            // make sure cursor ends up at the end of the line.
            anchor.ch = Number.MAX_VALUE;
          }
          finalHead = anchor;
        } else {
          text = cm.getSelection();
          var replacement = fillArray('', ranges.length);
          cm.replaceSelections(replacement);
          finalHead = cursorMin(ranges[0].head, ranges[0].anchor);
        }
        vimGlobalState.registerController.pushText(
            args.registerName, 'change', text,
            args.linewise, ranges.length > 1);
        actions.enterInsertMode(cm, {head: finalHead}, cm.state.vim);
      },
      // delete is a javascript keyword.
      'delete': function(cm, args, ranges) {
        var finalHead, text;
        var vim = cm.state.vim;
        if (!vim.visualBlock) {
          var anchor = ranges[0].anchor,
              head = ranges[0].head;
          if (args.linewise &&
              head.line != cm.firstLine() &&
              anchor.line == cm.lastLine() &&
              anchor.line == head.line - 1) {
            // Special case for dd on last line (and first line).
            if (anchor.line == cm.firstLine()) {
              anchor.ch = 0;
            } else {
              anchor = Pos(anchor.line - 1, lineLength(cm, anchor.line - 1));
            }
          }
          text = cm.getRange(anchor, head);
          cm.replaceRange('', anchor, head);
          finalHead = anchor;
          if (args.linewise) {
            finalHead = motions.moveToFirstNonWhiteSpaceCharacter(cm, anchor);
          }
        } else {
          text = cm.getSelection();
          var replacement = fillArray('', ranges.length);
          cm.replaceSelections(replacement);
          finalHead = ranges[0].anchor;
        }
        vimGlobalState.registerController.pushText(
            args.registerName, 'delete', text,
            args.linewise, vim.visualBlock);
        var includeLineBreak = vim.insertMode
        return clipCursorToContent(cm, finalHead, includeLineBreak);
      },
      indent: function(cm, args, ranges) {
        var vim = cm.state.vim;
        var startLine = ranges[0].anchor.line;
        var endLine = vim.visualBlock ?
          ranges[ranges.length - 1].anchor.line :
          ranges[0].head.line;
        // In visual mode, n> shifts the selection right n times, instead of
        // shifting n lines right once.
        var repeat = (vim.visualMode) ? args.repeat : 1;
        if (args.linewise) {
          // The only way to delete a newline is to delete until the start of
          // the next line, so in linewise mode evalInput will include the next
          // line. We don't want this in indent, so we go back a line.
          endLine--;
        }
        for (var i = startLine; i <= endLine; i++) {
          for (var j = 0; j < repeat; j++) {
            cm.indentLine(i, args.indentRight);
          }
        }
        return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor);
      },
      changeCase: function(cm, args, ranges, oldAnchor, newHead) {
        var selections = cm.getSelections();
        var swapped = [];
        var toLower = args.toLower;
        for (var j = 0; j < selections.length; j++) {
          var toSwap = selections[j];
          var text = '';
          if (toLower === true) {
            text = toSwap.toLowerCase();
          } else if (toLower === false) {
            text = toSwap.toUpperCase();
          } else {
            for (var i = 0; i < toSwap.length; i++) {
              var character = toSwap.charAt(i);
              text += isUpperCase(character) ? character.toLowerCase() :
                  character.toUpperCase();
            }
          }
          swapped.push(text);
        }
        cm.replaceSelections(swapped);
        if (args.shouldMoveCursor){
          return newHead;
        } else if (!cm.state.vim.visualMode && args.linewise && ranges[0].anchor.line + 1 == ranges[0].head.line) {
          return motions.moveToFirstNonWhiteSpaceCharacter(cm, oldAnchor);
        } else if (args.linewise){
          return oldAnchor;
        } else {
          return cursorMin(ranges[0].anchor, ranges[0].head);
        }
      },
      yank: function(cm, args, ranges, oldAnchor) {
        var vim = cm.state.vim;
        var text = cm.getSelection();
        var endPos = vim.visualMode
          ? cursorMin(vim.sel.anchor, vim.sel.head, ranges[0].head, ranges[0].anchor)
          : oldAnchor;
        vimGlobalState.registerController.pushText(
            args.registerName, 'yank',
            text, args.linewise, vim.visualBlock);
        return endPos;
      }
    };

    function defineOperator(name, fn) {
      operators[name] = fn;
    }

    var actions = {
      jumpListWalk: function(cm, actionArgs, vim) {
        if (vim.visualMode) {
          return;
        }
        var repeat = actionArgs.repeat;
        var forward = actionArgs.forward;
        var jumpList = vimGlobalState.jumpList;

        var mark = jumpList.move(cm, forward ? repeat : -repeat);
        var markPos = mark ? mark.find() : undefined;
        markPos = markPos ? markPos : cm.getCursor();
        cm.setCursor(markPos);
      },
      scroll: function(cm, actionArgs, vim) {
        if (vim.visualMode) {
          return;
        }
        var repeat = actionArgs.repeat || 1;
        var lineHeight = cm.defaultTextHeight();
        var top = cm.getScrollInfo().top;
        var delta = lineHeight * repeat;
        var newPos = actionArgs.forward ? top + delta : top - delta;
        var cursor = copyCursor(cm.getCursor());
        var cursorCoords = cm.charCoords(cursor, 'local');
        if (actionArgs.forward) {
          if (newPos > cursorCoords.top) {
             cursor.line += (newPos - cursorCoords.top) / lineHeight;
             cursor.line = Math.ceil(cursor.line);
             cm.setCursor(cursor);
             cursorCoords = cm.charCoords(cursor, 'local');
             cm.scrollTo(null, cursorCoords.top);
          } else {
             // Cursor stays within bounds.  Just reposition the scroll window.
             cm.scrollTo(null, newPos);
          }
        } else {
          var newBottom = newPos + cm.getScrollInfo().clientHeight;
          if (newBottom < cursorCoords.bottom) {
             cursor.line -= (cursorCoords.bottom - newBottom) / lineHeight;
             cursor.line = Math.floor(cursor.line);
             cm.setCursor(cursor);
             cursorCoords = cm.charCoords(cursor, 'local');
             cm.scrollTo(
                 null, cursorCoords.bottom - cm.getScrollInfo().clientHeight);
          } else {
             // Cursor stays within bounds.  Just reposition the scroll window.
             cm.scrollTo(null, newPos);
          }
        }
      },
      scrollToCursor: function(cm, actionArgs) {
        var lineNum = cm.getCursor().line;
        var charCoords = cm.charCoords(Pos(lineNum, 0), 'local');
        var height = cm.getScrollInfo().clientHeight;
        var y = charCoords.top;
        var lineHeight = charCoords.bottom - y;
        switch (actionArgs.position) {
          case 'center': y = y - (height / 2) + lineHeight;
            break;
          case 'bottom': y = y - height + lineHeight;
            break;
        }
        cm.scrollTo(null, y);
      },
      replayMacro: function(cm, actionArgs, vim) {
        var registerName = actionArgs.selectedCharacter;
        var repeat = actionArgs.repeat;
        var macroModeState = vimGlobalState.macroModeState;
        if (registerName == '@') {
          registerName = macroModeState.latestRegister;
        }
        while(repeat--){
          executeMacroRegister(cm, vim, macroModeState, registerName);
        }
      },
      enterMacroRecordMode: function(cm, actionArgs) {
        var macroModeState = vimGlobalState.macroModeState;
        var registerName = actionArgs.selectedCharacter;
        if (vimGlobalState.registerController.isValidRegister(registerName)) {
          macroModeState.enterMacroRecordMode(cm, registerName);
        }
      },
      toggleOverwrite: function(cm) {
        if (!cm.state.overwrite) {
          cm.toggleOverwrite(true);
          cm.setOption('keyMap', 'vim-replace');
          CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"});
        } else {
          cm.toggleOverwrite(false);
          cm.setOption('keyMap', 'vim-insert');
          CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"});
        }
      },
      enterInsertMode: function(cm, actionArgs, vim) {
        if (cm.getOption('readOnly')) { return; }
        vim.insertMode = true;
        vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1;
        var insertAt = (actionArgs) ? actionArgs.insertAt : null;
        var sel = vim.sel;
        var head = actionArgs.head || cm.getCursor('head');
        var height = cm.listSelections().length;
        if (insertAt == 'eol') {
          head = Pos(head.line, lineLength(cm, head.line));
        } else if (insertAt == 'charAfter') {
          head = offsetCursor(head, 0, 1);
        } else if (insertAt == 'firstNonBlank') {
          head = motions.moveToFirstNonWhiteSpaceCharacter(cm, head);
        } else if (insertAt == 'startOfSelectedArea') {
          if (!vim.visualBlock) {
            if (sel.head.line < sel.anchor.line) {
              head = sel.head;
            } else {
              head = Pos(sel.anchor.line, 0);
            }
          } else {
            head = Pos(
                Math.min(sel.head.line, sel.anchor.line),
                Math.min(sel.head.ch, sel.anchor.ch));
            height = Math.abs(sel.head.line - sel.anchor.line) + 1;
          }
        } else if (insertAt == 'endOfSelectedArea') {
          if (!vim.visualBlock) {
            if (sel.head.line >= sel.anchor.line) {
              head = offsetCursor(sel.head, 0, 1);
            } else {
              head = Pos(sel.anchor.line, 0);
            }
          } else {
            head = Pos(
                Math.min(sel.head.line, sel.anchor.line),
                Math.max(sel.head.ch + 1, sel.anchor.ch));
            height = Math.abs(sel.head.line - sel.anchor.line) + 1;
          }
        } else if (insertAt == 'inplace') {
          if (vim.visualMode){
            return;
          }
        }
        cm.setOption('disableInput', false);
        if (actionArgs && actionArgs.replace) {
          // Handle Replace-mode as a special case of insert mode.
          cm.toggleOverwrite(true);
          cm.setOption('keyMap', 'vim-replace');
          CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"});
        } else {
          cm.toggleOverwrite(false);
          cm.setOption('keyMap', 'vim-insert');
          CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"});
        }
        if (!vimGlobalState.macroModeState.isPlaying) {
          // Only record if not replaying.
          cm.on('change', onChange);
          CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
        }
        if (vim.visualMode) {
          exitVisualMode(cm);
        }
        selectForInsert(cm, head, height);
      },
      toggleVisualMode: function(cm, actionArgs, vim) {
        var repeat = actionArgs.repeat;
        var anchor = cm.getCursor();
        var head;
        // TODO: The repeat should actually select number of characters/lines
        //     equal to the repeat times the size of the previous visual
        //     operation.
        if (!vim.visualMode) {
          // Entering visual mode
          vim.visualMode = true;
          vim.visualLine = !!actionArgs.linewise;
          vim.visualBlock = !!actionArgs.blockwise;
          head = clipCursorToContent(
              cm, Pos(anchor.line, anchor.ch + repeat - 1),
              true /** includeLineBreak */);
          vim.sel = {
            anchor: anchor,
            head: head
          };
          CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
          updateCmSelection(cm);
          updateMark(cm, vim, '<', cursorMin(anchor, head));
          updateMark(cm, vim, '>', cursorMax(anchor, head));
        } else if (vim.visualLine ^ actionArgs.linewise ||
            vim.visualBlock ^ actionArgs.blockwise) {
          // Toggling between modes
          vim.visualLine = !!actionArgs.linewise;
          vim.visualBlock = !!actionArgs.blockwise;
          CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
          updateCmSelection(cm);
        } else {
          exitVisualMode(cm);
        }
      },
      reselectLastSelection: function(cm, _actionArgs, vim) {
        var lastSelection = vim.lastSelection;
        if (vim.visualMode) {
          updateLastSelection(cm, vim);
        }
        if (lastSelection) {
          var anchor = lastSelection.anchorMark.find();
          var head = lastSelection.headMark.find();
          if (!anchor || !head) {
            // If the marks have been destroyed due to edits, do nothing.
            return;
          }
          vim.sel = {
            anchor: anchor,
            head: head
          };
          vim.visualMode = true;
          vim.visualLine = lastSelection.visualLine;
          vim.visualBlock = lastSelection.visualBlock;
          updateCmSelection(cm);
          updateMark(cm, vim, '<', cursorMin(anchor, head));
          updateMark(cm, vim, '>', cursorMax(anchor, head));
          CodeMirror.signal(cm, 'vim-mode-change', {
            mode: 'visual',
            subMode: vim.visualLine ? 'linewise' :
                     vim.visualBlock ? 'blockwise' : ''});
        }
      },
      joinLines: function(cm, actionArgs, vim) {
        var curStart, curEnd;
        if (vim.visualMode) {
          curStart = cm.getCursor('anchor');
          curEnd = cm.getCursor('head');
          if (cursorIsBefore(curEnd, curStart)) {
            var tmp = curEnd;
            curEnd = curStart;
            curStart = tmp;
          }
          curEnd.ch = lineLength(cm, curEnd.line) - 1;
        } else {
          // Repeat is the number of lines to join. Minimum 2 lines.
          var repeat = Math.max(actionArgs.repeat, 2);
          curStart = cm.getCursor();
          curEnd = clipCursorToContent(cm, Pos(curStart.line + repeat - 1,
                                               Infinity));
        }
        var finalCh = 0;
        for (var i = curStart.line; i < curEnd.line; i++) {
          finalCh = lineLength(cm, curStart.line);
          var tmp = Pos(curStart.line + 1,
                        lineLength(cm, curStart.line + 1));
          var text = cm.getRange(curStart, tmp);
          text = text.replace(/\n\s*/g, ' ');
          cm.replaceRange(text, curStart, tmp);
        }
        var curFinalPos = Pos(curStart.line, finalCh);
        if (vim.visualMode) {
          exitVisualMode(cm, false);
        }
        cm.setCursor(curFinalPos);
      },
      newLineAndEnterInsertMode: function(cm, actionArgs, vim) {
        vim.insertMode = true;
        var insertAt = copyCursor(cm.getCursor());
        if (insertAt.line === cm.firstLine() && !actionArgs.after) {
          // Special case for inserting newline before start of document.
          cm.replaceRange('\n', Pos(cm.firstLine(), 0));
          cm.setCursor(cm.firstLine(), 0);
        } else {
          insertAt.line = (actionArgs.after) ? insertAt.line :
              insertAt.line - 1;
          insertAt.ch = lineLength(cm, insertAt.line);
          cm.setCursor(insertAt);
          var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment ||
              CodeMirror.commands.newlineAndIndent;
          newlineFn(cm);
        }
        this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim);
      },
      paste: function(cm, actionArgs, vim) {
        var cur = copyCursor(cm.getCursor());
        var register = vimGlobalState.registerController.getRegister(
            actionArgs.registerName);
        var text = register.toString();
        if (!text) {
          return;
        }
        if (actionArgs.matchIndent) {
          var tabSize = cm.getOption("tabSize");
          // length that considers tabs and tabSize
          var whitespaceLength = function(str) {
            var tabs = (str.split("\t").length - 1);
            var spaces = (str.split(" ").length - 1);
            return tabs * tabSize + spaces * 1;
          };
          var currentLine = cm.getLine(cm.getCursor().line);
          var indent = whitespaceLength(currentLine.match(/^\s*/)[0]);
          // chomp last newline b/c don't want it to match /^\s*/gm
          var chompedText = text.replace(/\n$/, '');
          var wasChomped = text !== chompedText;
          var firstIndent = whitespaceLength(text.match(/^\s*/)[0]);
          var text = chompedText.replace(/^\s*/gm, function(wspace) {
            var newIndent = indent + (whitespaceLength(wspace) - firstIndent);
            if (newIndent < 0) {
              return "";
            }
            else if (cm.getOption("indentWithTabs")) {
              var quotient = Math.floor(newIndent / tabSize);
              return Array(quotient + 1).join('\t');
            }
            else {
              return Array(newIndent + 1).join(' ');
            }
          });
          text += wasChomped ? "\n" : "";
        }
        if (actionArgs.repeat > 1) {
          var text = Array(actionArgs.repeat + 1).join(text);
        }
        var linewise = register.linewise;
        var blockwise = register.blockwise;
        if (linewise) {
          if(vim.visualMode) {
            text = vim.visualLine ? text.slice(0, -1) : '\n' + text.slice(0, text.length - 1) + '\n';
          } else if (actionArgs.after) {
            // Move the newline at the end to the start instead, and paste just
            // before the newline character of the line we are on right now.
            text = '\n' + text.slice(0, text.length - 1);
            cur.ch = lineLength(cm, cur.line);
          } else {
            cur.ch = 0;
          }
        } else {
          if (blockwise) {
            text = text.split('\n');
            for (var i = 0; i < text.length; i++) {
              text[i] = (text[i] == '') ? ' ' : text[i];
            }
          }
          cur.ch += actionArgs.after ? 1 : 0;
        }
        var curPosFinal;
        var idx;
        if (vim.visualMode) {
          //  save the pasted text for reselection if the need arises
          vim.lastPastedText = text;
          var lastSelectionCurEnd;
          var selectedArea = getSelectedAreaRange(cm, vim);
          var selectionStart = selectedArea[0];
          var selectionEnd = selectedArea[1];
          var selectedText = cm.getSelection();
          var selections = cm.listSelections();
          var emptyStrings = new Array(selections.length).join('1').split('1');
          // save the curEnd marker before it get cleared due to cm.replaceRange.
          if (vim.lastSelection) {
            lastSelectionCurEnd = vim.lastSelection.headMark.find();
          }
          // push the previously selected text to unnamed register
          vimGlobalState.registerController.unnamedRegister.setText(selectedText);
          if (blockwise) {
            // first delete the selected text
            cm.replaceSelections(emptyStrings);
            // Set new selections as per the block length of the yanked text
            selectionEnd = Pos(selectionStart.line + text.length-1, selectionStart.ch);
            cm.setCursor(selectionStart);
            selectBlock(cm, selectionEnd);
            cm.replaceSelections(text);
            curPosFinal = selectionStart;
          } else if (vim.visualBlock) {
            cm.replaceSelections(emptyStrings);
            cm.setCursor(selectionStart);
            cm.replaceRange(text, selectionStart, selectionStart);
            curPosFinal = selectionStart;
          } else {
            cm.replaceRange(text, selectionStart, selectionEnd);
            curPosFinal = cm.posFromIndex(cm.indexFromPos(selectionStart) + text.length - 1);
          }
          // restore the the curEnd marker
          if(lastSelectionCurEnd) {
            vim.lastSelection.headMark = cm.setBookmark(lastSelectionCurEnd);
          }
          if (linewise) {
            curPosFinal.ch=0;
          }
        } else {
          if (blockwise) {
            cm.setCursor(cur);
            for (var i = 0; i < text.length; i++) {
              var line = cur.line+i;
              if (line > cm.lastLine()) {
                cm.replaceRange('\n',  Pos(line, 0));
              }
              var lastCh = lineLength(cm, line);
              if (lastCh < cur.ch) {
                extendLineToColumn(cm, line, cur.ch);
              }
            }
            cm.setCursor(cur);
            selectBlock(cm, Pos(cur.line + text.length-1, cur.ch));
            cm.replaceSelections(text);
            curPosFinal = cur;
          } else {
            cm.replaceRange(text, cur);
            // Now fine tune the cursor to where we want it.
            if (linewise && actionArgs.after) {
              curPosFinal = Pos(
              cur.line + 1,
              findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1)));
            } else if (linewise && !actionArgs.after) {
              curPosFinal = Pos(
                cur.line,
                findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line)));
            } else if (!linewise && actionArgs.after) {
              idx = cm.indexFromPos(cur);
              curPosFinal = cm.posFromIndex(idx + text.length - 1);
            } else {
              idx = cm.indexFromPos(cur);
              curPosFinal = cm.posFromIndex(idx + text.length);
            }
          }
        }
        if (vim.visualMode) {
          exitVisualMode(cm, false);
        }
        cm.setCursor(curPosFinal);
      },
      undo: function(cm, actionArgs) {
        cm.operation(function() {
          repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)();
          cm.setCursor(cm.getCursor('anchor'));
        });
      },
      redo: function(cm, actionArgs) {
        repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)();
      },
      setRegister: function(_cm, actionArgs, vim) {
        vim.inputState.registerName = actionArgs.selectedCharacter;
      },
      setMark: function(cm, actionArgs, vim) {
        var markName = actionArgs.selectedCharacter;
        updateMark(cm, vim, markName, cm.getCursor());
      },
      replace: function(cm, actionArgs, vim) {
        var replaceWith = actionArgs.selectedCharacter;
        var curStart = cm.getCursor();
        var replaceTo;
        var curEnd;
        var selections = cm.listSelections();
        if (vim.visualMode) {
          curStart = cm.getCursor('start');
          curEnd = cm.getCursor('end');
        } else {
          var line = cm.getLine(curStart.line);
          replaceTo = curStart.ch + actionArgs.repeat;
          if (replaceTo > line.length) {
            replaceTo=line.length;
          }
          curEnd = Pos(curStart.line, replaceTo);
        }
        if (replaceWith=='\n') {
          if (!vim.visualMode) cm.replaceRange('', curStart, curEnd);
          // special case, where vim help says to replace by just one line-break
          (CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm);
        } else {
          var replaceWithStr = cm.getRange(curStart, curEnd);
          //replace all characters in range by selected, but keep linebreaks
          replaceWithStr = replaceWithStr.replace(/[^\n]/g, replaceWith);
          if (vim.visualBlock) {
            // Tabs are split in visua block before replacing
            var spaces = new Array(cm.getOption("tabSize")+1).join(' ');
            replaceWithStr = cm.getSelection();
            replaceWithStr = replaceWithStr.replace(/\t/g, spaces).replace(/[^\n]/g, replaceWith).split('\n');
            cm.replaceSelections(replaceWithStr);
          } else {
            cm.replaceRange(replaceWithStr, curStart, curEnd);
          }
          if (vim.visualMode) {
            curStart = cursorIsBefore(selections[0].anchor, selections[0].head) ?
                         selections[0].anchor : selections[0].head;
            cm.setCursor(curStart);
            exitVisualMode(cm, false);
          } else {
            cm.setCursor(offsetCursor(curEnd, 0, -1));
          }
        }
      },
      incrementNumberToken: function(cm, actionArgs) {
        var cur = cm.getCursor();
        var lineStr = cm.getLine(cur.line);
        var re = /(-?)(?:(0x)([\da-f]+)|(0b|0|)(\d+))/gi;
        var match;
        var start;
        var end;
        var numberStr;
        while ((match = re.exec(lineStr)) !== null) {
          start = match.index;
          end = start + match[0].length;
          if (cur.ch < end)break;
        }
        if (!actionArgs.backtrack && (end <= cur.ch))return;
        if (match) {
          var baseStr = match[2] || match[4]
          var digits = match[3] || match[5]
          var increment = actionArgs.increase ? 1 : -1;
          var base = {'0b': 2, '0': 8, '': 10, '0x': 16}[baseStr.toLowerCase()];
          var number = parseInt(match[1] + digits, base) + (increment * actionArgs.repeat);
          numberStr = number.toString(base);
          var zeroPadding = baseStr ? new Array(digits.length - numberStr.length + 1 + match[1].length).join('0') : ''
          if (numberStr.charAt(0) === '-') {
            numberStr = '-' + baseStr + zeroPadding + numberStr.substr(1);
          } else {
            numberStr = baseStr + zeroPadding + numberStr;
          }
          var from = Pos(cur.line, start);
          var to = Pos(cur.line, end);
          cm.replaceRange(numberStr, from, to);
        } else {
          return;
        }
        cm.setCursor(Pos(cur.line, start + numberStr.length - 1));
      },
      repeatLastEdit: function(cm, actionArgs, vim) {
        var lastEditInputState = vim.lastEditInputState;
        if (!lastEditInputState) { return; }
        var repeat = actionArgs.repeat;
        if (repeat && actionArgs.repeatIsExplicit) {
          vim.lastEditInputState.repeatOverride = repeat;
        } else {
          repeat = vim.lastEditInputState.repeatOverride || repeat;
        }
        repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */);
      },
      indent: function(cm, actionArgs) {
        cm.indentLine(cm.getCursor().line, actionArgs.indentRight);
      },
      exitInsertMode: exitInsertMode
    };

    function defineAction(name, fn) {
      actions[name] = fn;
    }

    /*
     * Below are miscellaneous utility functions used by vim.js
     */

    /**
     * Clips cursor to ensure that line is within the buffer's range
     * If includeLineBreak is true, then allow cur.ch == lineLength.
     */
    function clipCursorToContent(cm, cur, includeLineBreak) {
      var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() );
      var maxCh = lineLength(cm, line) - 1;
      maxCh = (includeLineBreak) ? maxCh + 1 : maxCh;
      var ch = Math.min(Math.max(0, cur.ch), maxCh);
      return Pos(line, ch);
    }
    function copyArgs(args) {
      var ret = {};
      for (var prop in args) {
        if (args.hasOwnProperty(prop)) {
          ret[prop] = args[prop];
        }
      }
      return ret;
    }
    function offsetCursor(cur, offsetLine, offsetCh) {
      if (typeof offsetLine === 'object') {
        offsetCh = offsetLine.ch;
        offsetLine = offsetLine.line;
      }
      return Pos(cur.line + offsetLine, cur.ch + offsetCh);
    }
    function getOffset(anchor, head) {
      return {
        line: head.line - anchor.line,
        ch: head.line - anchor.line
      };
    }
    function commandMatches(keys, keyMap, context, inputState) {
      // Partial matches are not applied. They inform the key handler
      // that the current key sequence is a subsequence of a valid key
      // sequence, so that the key buffer is not cleared.
      var match, partial = [], full = [];
      for (var i = 0; i < keyMap.length; i++) {
        var command = keyMap[i];
        if (context == 'insert' && command.context != 'insert' ||
            command.context && command.context != context ||
            inputState.operator && command.type == 'action' ||
            !(match = commandMatch(keys, command.keys))) { continue; }
        if (match == 'partial') { partial.push(command); }
        if (match == 'full') { full.push(command); }
      }
      return {
        partial: partial.length && partial,
        full: full.length && full
      };
    }
    function commandMatch(pressed, mapped) {
      if (mapped.slice(-11) == '<character>') {
        // Last character matches anything.
        var prefixLen = mapped.length - 11;
        var pressedPrefix = pressed.slice(0, prefixLen);
        var mappedPrefix = mapped.slice(0, prefixLen);
        return pressedPrefix == mappedPrefix && pressed.length > prefixLen ? 'full' :
               mappedPrefix.indexOf(pressedPrefix) == 0 ? 'partial' : false;
      } else {
        return pressed == mapped ? 'full' :
               mapped.indexOf(pressed) == 0 ? 'partial' : false;
      }
    }
    function lastChar(keys) {
      var match = /^.*(<[^>]+>)$/.exec(keys);
      var selectedCharacter = match ? match[1] : keys.slice(-1);
      if (selectedCharacter.length > 1){
        switch(selectedCharacter){
          case '<CR>':
            selectedCharacter='\n';
            break;
          case '<Space>':
            selectedCharacter=' ';
            break;
          default:
            selectedCharacter='';
            break;
        }
      }
      return selectedCharacter;
    }
    function repeatFn(cm, fn, repeat) {
      return function() {
        for (var i = 0; i < repeat; i++) {
          fn(cm);
        }
      };
    }
    function copyCursor(cur) {
      return Pos(cur.line, cur.ch);
    }
    function cursorEqual(cur1, cur2) {
      return cur1.ch == cur2.ch && cur1.line == cur2.line;
    }
    function cursorIsBefore(cur1, cur2) {
      if (cur1.line < cur2.line) {
        return true;
      }
      if (cur1.line == cur2.line && cur1.ch < cur2.ch) {
        return true;
      }
      return false;
    }
    function cursorMin(cur1, cur2) {
      if (arguments.length > 2) {
        cur2 = cursorMin.apply(undefined, Array.prototype.slice.call(arguments, 1));
      }
      return cursorIsBefore(cur1, cur2) ? cur1 : cur2;
    }
    function cursorMax(cur1, cur2) {
      if (arguments.length > 2) {
        cur2 = cursorMax.apply(undefined, Array.prototype.slice.call(arguments, 1));
      }
      return cursorIsBefore(cur1, cur2) ? cur2 : cur1;
    }
    function cursorIsBetween(cur1, cur2, cur3) {
      // returns true if cur2 is between cur1 and cur3.
      var cur1before2 = cursorIsBefore(cur1, cur2);
      var cur2before3 = cursorIsBefore(cur2, cur3);
      return cur1before2 && cur2before3;
    }
    function lineLength(cm, lineNum) {
      return cm.getLine(lineNum).length;
    }
    function trim(s) {
      if (s.trim) {
        return s.trim();
      }
      return s.replace(/^\s+|\s+$/g, '');
    }
    function escapeRegex(s) {
      return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1');
    }
    function extendLineToColumn(cm, lineNum, column) {
      var endCh = lineLength(cm, lineNum);
      var spaces = new Array(column-endCh+1).join(' ');
      cm.setCursor(Pos(lineNum, endCh));
      cm.replaceRange(spaces, cm.getCursor());
    }
    // This functions selects a rectangular block
    // of text with selectionEnd as any of its corner
    // Height of block:
    // Difference in selectionEnd.line and first/last selection.line
    // Width of the block:
    // Distance between selectionEnd.ch and any(first considered here) selection.ch
    function selectBlock(cm, selectionEnd) {
      var selections = [], ranges = cm.listSelections();
      var head = copyCursor(cm.clipPos(selectionEnd));
      var isClipped = !cursorEqual(selectionEnd, head);
      var curHead = cm.getCursor('head');
      var primIndex = getIndex(ranges, curHead);
      var wasClipped = cursorEqual(ranges[primIndex].head, ranges[primIndex].anchor);
      var max = ranges.length - 1;
      var index = max - primIndex > primIndex ? max : 0;
      var base = ranges[index].anchor;

      var firstLine = Math.min(base.line, head.line);
      var lastLine = Math.max(base.line, head.line);
      var baseCh = base.ch, headCh = head.ch;

      var dir = ranges[index].head.ch - baseCh;
      var newDir = headCh - baseCh;
      if (dir > 0 && newDir <= 0) {
        baseCh++;
        if (!isClipped) { headCh--; }
      } else if (dir < 0 && newDir >= 0) {
        baseCh--;
        if (!wasClipped) { headCh++; }
      } else if (dir < 0 && newDir == -1) {
        baseCh--;
        headCh++;
      }
      for (var line = firstLine; line <= lastLine; line++) {
        var range = {anchor: new Pos(line, baseCh), head: new Pos(line, headCh)};
        selections.push(range);
      }
      cm.setSelections(selections);
      selectionEnd.ch = headCh;
      base.ch = baseCh;
      return base;
    }
    function selectForInsert(cm, head, height) {
      var sel = [];
      for (var i = 0; i < height; i++) {
        var lineHead = offsetCursor(head, i, 0);
        sel.push({anchor: lineHead, head: lineHead});
      }
      cm.setSelections(sel, 0);
    }
    // getIndex returns the index of the cursor in the selections.
    function getIndex(ranges, cursor, end) {
      for (var i = 0; i < ranges.length; i++) {
        var atAnchor = end != 'head' && cursorEqual(ranges[i].anchor, cursor);
        var atHead = end != 'anchor' && cursorEqual(ranges[i].head, cursor);
        if (atAnchor || atHead) {
          return i;
        }
      }
      return -1;
    }
    function getSelectedAreaRange(cm, vim) {
      var lastSelection = vim.lastSelection;
      var getCurrentSelectedAreaRange = function() {
        var selections = cm.listSelections();
        var start =  selections[0];
        var end = selections[selections.length-1];
        var selectionStart = cursorIsBefore(start.anchor, start.head) ? start.anchor : start.head;
        var selectionEnd = cursorIsBefore(end.anchor, end.head) ? end.head : end.anchor;
        return [selectionStart, selectionEnd];
      };
      var getLastSelectedAreaRange = function() {
        var selectionStart = cm.getCursor();
        var selectionEnd = cm.getCursor();
        var block = lastSelection.visualBlock;
        if (block) {
          var width = block.width;
          var height = block.height;
          selectionEnd = Pos(selectionStart.line + height, selectionStart.ch + width);
          var selections = [];
          // selectBlock creates a 'proper' rectangular block.
          // We do not want that in all cases, so we manually set selections.
          for (var i = selectionStart.line; i < selectionEnd.line; i++) {
            var anchor = Pos(i, selectionStart.ch);
            var head = Pos(i, selectionEnd.ch);
            var range = {anchor: anchor, head: head};
            selections.push(range);
          }
          cm.setSelections(selections);
        } else {
          var start = lastSelection.anchorMark.find();
          var end = lastSelection.headMark.find();
          var line = end.line - start.line;
          var ch = end.ch - start.ch;
          selectionEnd = {line: selectionEnd.line + line, ch: line ? selectionEnd.ch : ch + selectionEnd.ch};
          if (lastSelection.visualLine) {
            selectionStart = Pos(selectionStart.line, 0);
            selectionEnd = Pos(selectionEnd.line, lineLength(cm, selectionEnd.line));
          }
          cm.setSelection(selectionStart, selectionEnd);
        }
        return [selectionStart, selectionEnd];
      };
      if (!vim.visualMode) {
      // In case of replaying the action.
        return getLastSelectedAreaRange();
      } else {
        return getCurrentSelectedAreaRange();
      }
    }
    // Updates the previous selection with the current selection's values. This
    // should only be called in visual mode.
    function updateLastSelection(cm, vim) {
      var anchor = vim.sel.anchor;
      var head = vim.sel.head;
      // To accommodate the effect of lastPastedText in the last selection
      if (vim.lastPastedText) {
        head = cm.posFromIndex(cm.indexFromPos(anchor) + vim.lastPastedText.length);
        vim.lastPastedText = null;
      }
      vim.lastSelection = {'anchorMark': cm.setBookmark(anchor),
                           'headMark': cm.setBookmark(head),
                           'anchor': copyCursor(anchor),
                           'head': copyCursor(head),
                           'visualMode': vim.visualMode,
                           'visualLine': vim.visualLine,
                           'visualBlock': vim.visualBlock};
    }
    function expandSelection(cm, start, end) {
      var sel = cm.state.vim.sel;
      var head = sel.head;
      var anchor = sel.anchor;
      var tmp;
      if (cursorIsBefore(end, start)) {
        tmp = end;
        end = start;
        start = tmp;
      }
      if (cursorIsBefore(head, anchor)) {
        head = cursorMin(start, head);
        anchor = cursorMax(anchor, end);
      } else {
        anchor = cursorMin(start, anchor);
        head = cursorMax(head, end);
        head = offsetCursor(head, 0, -1);
        if (head.ch == -1 && head.line != cm.firstLine()) {
          head = Pos(head.line - 1, lineLength(cm, head.line - 1));
        }
      }
      return [anchor, head];
    }
    /**
     * Updates the CodeMirror selection to match the provided vim selection.
     * If no arguments are given, it uses the current vim selection state.
     */
    function updateCmSelection(cm, sel, mode) {
      var vim = cm.state.vim;
      sel = sel || vim.sel;
      var mode = mode ||
        vim.visualLine ? 'line' : vim.visualBlock ? 'block' : 'char';
      var cmSel = makeCmSelection(cm, sel, mode);
      cm.setSelections(cmSel.ranges, cmSel.primary);
      updateFakeCursor(cm);
    }
    function makeCmSelection(cm, sel, mode, exclusive) {
      var head = copyCursor(sel.head);
      var anchor = copyCursor(sel.anchor);
      if (mode == 'char') {
        var headOffset = !exclusive && !cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
        var anchorOffset = cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
        head = offsetCursor(sel.head, 0, headOffset);
        anchor = offsetCursor(sel.anchor, 0, anchorOffset);
        return {
          ranges: [{anchor: anchor, head: head}],
          primary: 0
        };
      } else if (mode == 'line') {
        if (!cursorIsBefore(sel.head, sel.anchor)) {
          anchor.ch = 0;

          var lastLine = cm.lastLine();
          if (head.line > lastLine) {
            head.line = lastLine;
          }
          head.ch = lineLength(cm, head.line);
        } else {
          head.ch = 0;
          anchor.ch = lineLength(cm, anchor.line);
        }
        return {
          ranges: [{anchor: anchor, head: head}],
          primary: 0
        };
      } else if (mode == 'block') {
        var top = Math.min(anchor.line, head.line),
            left = Math.min(anchor.ch, head.ch),
            bottom = Math.max(anchor.line, head.line),
            right = Math.max(anchor.ch, head.ch) + 1;
        var height = bottom - top + 1;
        var primary = head.line == top ? 0 : height - 1;
        var ranges = [];
        for (var i = 0; i < height; i++) {
          ranges.push({
            anchor: Pos(top + i, left),
            head: Pos(top + i, right)
          });
        }
        return {
          ranges: ranges,
          primary: primary
        };
      }
    }
    function getHead(cm) {
      var cur = cm.getCursor('head');
      if (cm.getSelection().length == 1) {
        // Small corner case when only 1 character is selected. The "real"
        // head is the left of head and anchor.
        cur = cursorMin(cur, cm.getCursor('anchor'));
      }
      return cur;
    }

    /**
     * If moveHead is set to false, the CodeMirror selection will not be
     * touched. The caller assumes the responsibility of putting the cursor
    * in the right place.
     */
    function exitVisualMode(cm, moveHead) {
      var vim = cm.state.vim;
      if (moveHead !== false) {
        cm.setCursor(clipCursorToContent(cm, vim.sel.head));
      }
      updateLastSelection(cm, vim);
      vim.visualMode = false;
      vim.visualLine = false;
      vim.visualBlock = false;
      CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
      if (vim.fakeCursor) {
        vim.fakeCursor.clear();
      }
    }

    // Remove any trailing newlines from the selection. For
    // example, with the caret at the start of the last word on the line,
    // 'dw' should word, but not the newline, while 'w' should advance the
    // caret to the first character of the next line.
    function clipToLine(cm, curStart, curEnd) {
      var selection = cm.getRange(curStart, curEnd);
      // Only clip if the selection ends with trailing newline + whitespace
      if (/\n\s*$/.test(selection)) {
        var lines = selection.split('\n');
        // We know this is all whitespace.
        lines.pop();

        // Cases:
        // 1. Last word is an empty line - do not clip the trailing '\n'
        // 2. Last word is not an empty line - clip the trailing '\n'
        var line;
        // Find the line containing the last word, and clip all whitespace up
        // to it.
        for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) {
          curEnd.line--;
          curEnd.ch = 0;
        }
        // If the last word is not an empty line, clip an additional newline
        if (line) {
          curEnd.line--;
          curEnd.ch = lineLength(cm, curEnd.line);
        } else {
          curEnd.ch = 0;
        }
      }
    }

    // Expand the selection to line ends.
    function expandSelectionToLine(_cm, curStart, curEnd) {
      curStart.ch = 0;
      curEnd.ch = 0;
      curEnd.line++;
    }

    function findFirstNonWhiteSpaceCharacter(text) {
      if (!text) {
        return 0;
      }
      var firstNonWS = text.search(/\S/);
      return firstNonWS == -1 ? text.length : firstNonWS;
    }

    function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) {
      var cur = getHead(cm);
      var line = cm.getLine(cur.line);
      var idx = cur.ch;

      // Seek to first word or non-whitespace character, depending on if
      // noSymbol is true.
      var test = noSymbol ? wordCharTest[0] : bigWordCharTest [0];
      while (!test(line.charAt(idx))) {
        idx++;
        if (idx >= line.length) { return null; }
      }

      if (bigWord) {
        test = bigWordCharTest[0];
      } else {
        test = wordCharTest[0];
        if (!test(line.charAt(idx))) {
          test = wordCharTest[1];
        }
      }

      var end = idx, start = idx;
      while (test(line.charAt(end)) && end < line.length) { end++; }
      while (test(line.charAt(start)) && start >= 0) { start--; }
      start++;

      if (inclusive) {
        // If present, include all whitespace after word.
        // Otherwise, include all whitespace before word, except indentation.
        var wordEnd = end;
        while (/\s/.test(line.charAt(end)) && end < line.length) { end++; }
        if (wordEnd == end) {
          var wordStart = start;
          while (/\s/.test(line.charAt(start - 1)) && start > 0) { start--; }
          if (!start) { start = wordStart; }
        }
      }
      return { start: Pos(cur.line, start), end: Pos(cur.line, end) };
    }

    function recordJumpPosition(cm, oldCur, newCur) {
      if (!cursorEqual(oldCur, newCur)) {
        vimGlobalState.jumpList.add(cm, oldCur, newCur);
      }
    }

    function recordLastCharacterSearch(increment, args) {
        vimGlobalState.lastCharacterSearch.increment = increment;
        vimGlobalState.lastCharacterSearch.forward = args.forward;
        vimGlobalState.lastCharacterSearch.selectedCharacter = args.selectedCharacter;
    }

    var symbolToMode = {
        '(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket',
        '[': 'section', ']': 'section',
        '*': 'comment', '/': 'comment',
        'm': 'method', 'M': 'method',
        '#': 'preprocess'
    };
    var findSymbolModes = {
      bracket: {
        isComplete: function(state) {
          if (state.nextCh === state.symb) {
            state.depth++;
            if (state.depth >= 1)return true;
          } else if (state.nextCh === state.reverseSymb) {
            state.depth--;
          }
          return false;
        }
      },
      section: {
        init: function(state) {
          state.curMoveThrough = true;
          state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}';
        },
        isComplete: function(state) {
          return state.index === 0 && state.nextCh === state.symb;
        }
      },
      comment: {
        isComplete: function(state) {
          var found = state.lastCh === '*' && state.nextCh === '/';
          state.lastCh = state.nextCh;
          return found;
        }
      },
      // TODO: The original Vim implementation only operates on level 1 and 2.
      // The current implementation doesn't check for code block level and
      // therefore it operates on any levels.
      method: {
        init: function(state) {
          state.symb = (state.symb === 'm' ? '{' : '}');
          state.reverseSymb = state.symb === '{' ? '}' : '{';
        },
        isComplete: function(state) {
          if (state.nextCh === state.symb)return true;
          return false;
        }
      },
      preprocess: {
        init: function(state) {
          state.index = 0;
        },
        isComplete: function(state) {
          if (state.nextCh === '#') {
            var token = state.lineText.match(/#(\w+)/)[1];
            if (token === 'endif') {
              if (state.forward && state.depth === 0) {
                return true;
              }
              state.depth++;
            } else if (token === 'if') {
              if (!state.forward && state.depth === 0) {
                return true;
              }
              state.depth--;
            }
            if (token === 'else' && state.depth === 0)return true;
          }
          return false;
        }
      }
    };
    function findSymbol(cm, repeat, forward, symb) {
      var cur = copyCursor(cm.getCursor());
      var increment = forward ? 1 : -1;
      var endLine = forward ? cm.lineCount() : -1;
      var curCh = cur.ch;
      var line = cur.line;
      var lineText = cm.getLine(line);
      var state = {
        lineText: lineText,
        nextCh: lineText.charAt(curCh),
        lastCh: null,
        index: curCh,
        symb: symb,
        reverseSymb: (forward ?  { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb],
        forward: forward,
        depth: 0,
        curMoveThrough: false
      };
      var mode = symbolToMode[symb];
      if (!mode)return cur;
      var init = findSymbolModes[mode].init;
      var isComplete = findSymbolModes[mode].isComplete;
      if (init) { init(state); }
      while (line !== endLine && repeat) {
        state.index += increment;
        state.nextCh = state.lineText.charAt(state.index);
        if (!state.nextCh) {
          line += increment;
          state.lineText = cm.getLine(line) || '';
          if (increment > 0) {
            state.index = 0;
          } else {
            var lineLen = state.lineText.length;
            state.index = (lineLen > 0) ? (lineLen-1) : 0;
          }
          state.nextCh = state.lineText.charAt(state.index);
        }
        if (isComplete(state)) {
          cur.line = line;
          cur.ch = state.index;
          repeat--;
        }
      }
      if (state.nextCh || state.curMoveThrough) {
        return Pos(line, state.index);
      }
      return cur;
    }

    /*
     * Returns the boundaries of the next word. If the cursor in the middle of
     * the word, then returns the boundaries of the current word, starting at
     * the cursor. If the cursor is at the start/end of a word, and we are going
     * forward/backward, respectively, find the boundaries of the next word.
     *
     * @param {CodeMirror} cm CodeMirror object.
     * @param {Cursor} cur The cursor position.
     * @param {boolean} forward True to search forward. False to search
     *     backward.
     * @param {boolean} bigWord True if punctuation count as part of the word.
     *     False if only [a-zA-Z0-9] characters count as part of the word.
     * @param {boolean} emptyLineIsWord True if empty lines should be treated
     *     as words.
     * @return {Object{from:number, to:number, line: number}} The boundaries of
     *     the word, or null if there are no more words.
     */
    function findWord(cm, cur, forward, bigWord, emptyLineIsWord) {
      var lineNum = cur.line;
      var pos = cur.ch;
      var line = cm.getLine(lineNum);
      var dir = forward ? 1 : -1;
      var charTests = bigWord ? bigWordCharTest: wordCharTest;

      if (emptyLineIsWord && line == '') {
        lineNum += dir;
        line = cm.getLine(lineNum);
        if (!isLine(cm, lineNum)) {
          return null;
        }
        pos = (forward) ? 0 : line.length;
      }

      while (true) {
        if (emptyLineIsWord && line == '') {
          return { from: 0, to: 0, line: lineNum };
        }
        var stop = (dir > 0) ? line.length : -1;
        var wordStart = stop, wordEnd = stop;
        // Find bounds of next word.
        while (pos != stop) {
          var foundWord = false;
          for (var i = 0; i < charTests.length && !foundWord; ++i) {
            if (charTests[i](line.charAt(pos))) {
              wordStart = pos;
              // Advance to end of word.
              while (pos != stop && charTests[i](line.charAt(pos))) {
                pos += dir;
              }
              wordEnd = pos;
              foundWord = wordStart != wordEnd;
              if (wordStart == cur.ch && lineNum == cur.line &&
                  wordEnd == wordStart + dir) {
                // We started at the end of a word. Find the next one.
                continue;
              } else {
                return {
                  from: Math.min(wordStart, wordEnd + 1),
                  to: Math.max(wordStart, wordEnd),
                  line: lineNum };
              }
            }
          }
          if (!foundWord) {
            pos += dir;
          }
        }
        // Advance to next/prev line.
        lineNum += dir;
        if (!isLine(cm, lineNum)) {
          return null;
        }
        line = cm.getLine(lineNum);
        pos = (dir > 0) ? 0 : line.length;
      }
    }

    /**
     * @param {CodeMirror} cm CodeMirror object.
     * @param {Pos} cur The position to start from.
     * @param {int} repeat Number of words to move past.
     * @param {boolean} forward True to search forward. False to search
     *     backward.
     * @param {boolean} wordEnd True to move to end of word. False to move to
     *     beginning of word.
     * @param {boolean} bigWord True if punctuation count as part of the word.
     *     False if only alphabet characters count as part of the word.
     * @return {Cursor} The position the cursor should move to.
     */
    function moveToWord(cm, cur, repeat, forward, wordEnd, bigWord) {
      var curStart = copyCursor(cur);
      var words = [];
      if (forward && !wordEnd || !forward && wordEnd) {
        repeat++;
      }
      // For 'e', empty lines are not considered words, go figure.
      var emptyLineIsWord = !(forward && wordEnd);
      for (var i = 0; i < repeat; i++) {
        var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord);
        if (!word) {
          var eodCh = lineLength(cm, cm.lastLine());
          words.push(forward
              ? {line: cm.lastLine(), from: eodCh, to: eodCh}
              : {line: 0, from: 0, to: 0});
          break;
        }
        words.push(word);
        cur = Pos(word.line, forward ? (word.to - 1) : word.from);
      }
      var shortCircuit = words.length != repeat;
      var firstWord = words[0];
      var lastWord = words.pop();
      if (forward && !wordEnd) {
        // w
        if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) {
          // We did not start in the middle of a word. Discard the extra word at the end.
          lastWord = words.pop();
        }
        return Pos(lastWord.line, lastWord.from);
      } else if (forward && wordEnd) {
        return Pos(lastWord.line, lastWord.to - 1);
      } else if (!forward && wordEnd) {
        // ge
        if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) {
          // We did not start in the middle of a word. Discard the extra word at the end.
          lastWord = words.pop();
        }
        return Pos(lastWord.line, lastWord.to);
      } else {
        // b
        return Pos(lastWord.line, lastWord.from);
      }
    }

    function moveToCharacter(cm, repeat, forward, character) {
      var cur = cm.getCursor();
      var start = cur.ch;
      var idx;
      for (var i = 0; i < repeat; i ++) {
        var line = cm.getLine(cur.line);
        idx = charIdxInLine(start, line, character, forward, true);
        if (idx == -1) {
          return null;
        }
        start = idx;
      }
      return Pos(cm.getCursor().line, idx);
    }

    function moveToColumn(cm, repeat) {
      // repeat is always >= 1, so repeat - 1 always corresponds
      // to the column we want to go to.
      var line = cm.getCursor().line;
      return clipCursorToContent(cm, Pos(line, repeat - 1));
    }

    function updateMark(cm, vim, markName, pos) {
      if (!inArray(markName, validMarks)) {
        return;
      }
      if (vim.marks[markName]) {
        vim.marks[markName].clear();
      }
      vim.marks[markName] = cm.setBookmark(pos);
    }

    function charIdxInLine(start, line, character, forward, includeChar) {
      // Search for char in line.
      // motion_options: {forward, includeChar}
      // If includeChar = true, include it too.
      // If forward = true, search forward, else search backwards.
      // If char is not found on this line, do nothing
      var idx;
      if (forward) {
        idx = line.indexOf(character, start + 1);
        if (idx != -1 && !includeChar) {
          idx -= 1;
        }
      } else {
        idx = line.lastIndexOf(character, start - 1);
        if (idx != -1 && !includeChar) {
          idx += 1;
        }
      }
      return idx;
    }

    function findParagraph(cm, head, repeat, dir, inclusive) {
      var line = head.line;
      var min = cm.firstLine();
      var max = cm.lastLine();
      var start, end, i = line;
      function isEmpty(i) { return !cm.getLine(i); }
      function isBoundary(i, dir, any) {
        if (any) { return isEmpty(i) != isEmpty(i + dir); }
        return !isEmpty(i) && isEmpty(i + dir);
      }
      if (dir) {
        while (min <= i && i <= max && repeat > 0) {
          if (isBoundary(i, dir)) { repeat--; }
          i += dir;
        }
        return new Pos(i, 0);
      }

      var vim = cm.state.vim;
      if (vim.visualLine && isBoundary(line, 1, true)) {
        var anchor = vim.sel.anchor;
        if (isBoundary(anchor.line, -1, true)) {
          if (!inclusive || anchor.line != line) {
            line += 1;
          }
        }
      }
      var startState = isEmpty(line);
      for (i = line; i <= max && repeat; i++) {
        if (isBoundary(i, 1, true)) {
          if (!inclusive || isEmpty(i) != startState) {
            repeat--;
          }
        }
      }
      end = new Pos(i, 0);
      // select boundary before paragraph for the last one
      if (i > max && !startState) { startState = true; }
      else { inclusive = false; }
      for (i = line; i > min; i--) {
        if (!inclusive || isEmpty(i) == startState || i == line) {
          if (isBoundary(i, -1, true)) { break; }
        }
      }
      start = new Pos(i, 0);
      return { start: start, end: end };
    }

    function findSentence(cm, cur, repeat, dir) {

      /*
        Takes an index object
        {
          line: the line string,
          ln: line number,
          pos: index in line,
          dir: direction of traversal (-1 or 1)
        }
        and modifies the line, ln, and pos members to represent the
        next valid position or sets them to null if there are
        no more valid positions.
       */
      function nextChar(cm, idx) {
        if (idx.pos + idx.dir < 0 || idx.pos + idx.dir >= idx.line.length) {
          idx.ln += idx.dir;
          if (!isLine(cm, idx.ln)) {
            idx.line = null;
            idx.ln = null;
            idx.pos = null;
            return;
          }
          idx.line = cm.getLine(idx.ln);
          idx.pos = (idx.dir > 0) ? 0 : idx.line.length - 1;
        }
        else {
          idx.pos += idx.dir;
        }
      }

      /*
        Performs one iteration of traversal in forward direction
        Returns an index object of the new location
       */
      function forward(cm, ln, pos, dir) {
        var line = cm.getLine(ln);
        var stop = (line === "");

        var curr = {
          line: line,
          ln: ln,
          pos: pos,
          dir: dir,
        }

        var last_valid = {
          ln: curr.ln,
          pos: curr.pos,
        }

        var skip_empty_lines = (curr.line === "");

        // Move one step to skip character we start on
        nextChar(cm, curr);

        while (curr.line !== null) {
          last_valid.ln = curr.ln;
          last_valid.pos = curr.pos;

          if (curr.line === "" && !skip_empty_lines) {
            return { ln: curr.ln, pos: curr.pos, };
          }
          else if (stop && curr.line !== "" && !isWhiteSpaceString(curr.line[curr.pos])) {
            return { ln: curr.ln, pos: curr.pos, };
          }
          else if (isEndOfSentenceSymbol(curr.line[curr.pos])
            && !stop
            && (curr.pos === curr.line.length - 1
              || isWhiteSpaceString(curr.line[curr.pos + 1]))) {
            stop = true;
          }

          nextChar(cm, curr);
        }

        /*
          Set the position to the last non whitespace character on the last
          valid line in the case that we reach the end of the document.
        */
        var line = cm.getLine(last_valid.ln);
        last_valid.pos = 0;
        for(var i = line.length - 1; i >= 0; --i) {
          if (!isWhiteSpaceString(line[i])) {
            last_valid.pos = i;
            break;
          }
        }

        return last_valid;

      }

      /*
        Performs one iteration of traversal in reverse direction
        Returns an index object of the new location
       */
      function reverse(cm, ln, pos, dir) {
        var line = cm.getLine(ln);

        var curr = {
          line: line,
          ln: ln,
          pos: pos,
          dir: dir,
        }

        var last_valid = {
          ln: curr.ln,
          pos: null,
        };

        var skip_empty_lines = (curr.line === "");

        // Move one step to skip character we start on
        nextChar(cm, curr);

        while (curr.line !== null) {

          if (curr.line === "" && !skip_empty_lines) {
            if (last_valid.pos !== null) {
              return last_valid;
            }
            else {
              return { ln: curr.ln, pos: curr.pos };
            }
          }
          else if (isEndOfSentenceSymbol(curr.line[curr.pos])
              && last_valid.pos !== null
              && !(curr.ln === last_valid.ln && curr.pos + 1 === last_valid.pos)) {
            return last_valid;
          }
          else if (curr.line !== "" && !isWhiteSpaceString(curr.line[curr.pos])) {
            skip_empty_lines = false;
            last_valid = { ln: curr.ln, pos: curr.pos }
          }

          nextChar(cm, curr);
        }

        /*
          Set the position to the first non whitespace character on the last
          valid line in the case that we reach the beginning of the document.
        */
        var line = cm.getLine(last_valid.ln);
        last_valid.pos = 0;
        for(var i = 0; i < line.length; ++i) {
          if (!isWhiteSpaceString(line[i])) {
            last_valid.pos = i;
            break;
          }
        }
        return last_valid;
      }

      var curr_index = {
        ln: cur.line,
        pos: cur.ch,
      };

      while (repeat > 0) {
        if (dir < 0) {
          curr_index = reverse(cm, curr_index.ln, curr_index.pos, dir);
        }
        else {
          curr_index = forward(cm, curr_index.ln, curr_index.pos, dir);
        }
        repeat--;
      }

      return Pos(curr_index.ln, curr_index.pos);
    }

    // TODO: perhaps this finagling of start and end positions belonds
    // in codemirror/replaceRange?
    function selectCompanionObject(cm, head, symb, inclusive) {
      var cur = head, start, end;

      var bracketRegexp = ({
        '(': /[()]/, ')': /[()]/,
        '[': /[[\]]/, ']': /[[\]]/,
        '{': /[{}]/, '}': /[{}]/})[symb];
      var openSym = ({
        '(': '(', ')': '(',
        '[': '[', ']': '[',
        '{': '{', '}': '{'})[symb];
      var curChar = cm.getLine(cur.line).charAt(cur.ch);
      // Due to the behavior of scanForBracket, we need to add an offset if the
      // cursor is on a matching open bracket.
      var offset = curChar === openSym ? 1 : 0;

      start = cm.scanForBracket(Pos(cur.line, cur.ch + offset), -1, undefined, {'bracketRegex': bracketRegexp});
      end = cm.scanForBracket(Pos(cur.line, cur.ch + offset), 1, undefined, {'bracketRegex': bracketRegexp});

      if (!start || !end) {
        return { start: cur, end: cur };
      }

      start = start.pos;
      end = end.pos;

      if ((start.line == end.line && start.ch > end.ch)
          || (start.line > end.line)) {
        var tmp = start;
        start = end;
        end = tmp;
      }

      if (inclusive) {
        end.ch += 1;
      } else {
        start.ch += 1;
      }

      return { start: start, end: end };
    }

    // Takes in a symbol and a cursor and tries to simulate text objects that
    // have identical opening and closing symbols
    // TODO support across multiple lines
    function findBeginningAndEnd(cm, head, symb, inclusive) {
      var cur = copyCursor(head);
      var line = cm.getLine(cur.line);
      var chars = line.split('');
      var start, end, i, len;
      var firstIndex = chars.indexOf(symb);

      // the decision tree is to always look backwards for the beginning first,
      // but if the cursor is in front of the first instance of the symb,
      // then move the cursor forward
      if (cur.ch < firstIndex) {
        cur.ch = firstIndex;
        // Why is this line even here???
        // cm.setCursor(cur.line, firstIndex+1);
      }
      // otherwise if the cursor is currently on the closing symbol
      else if (firstIndex < cur.ch && chars[cur.ch] == symb) {
        end = cur.ch; // assign end to the current cursor
        --cur.ch; // make sure to look backwards
      }

      // if we're currently on the symbol, we've got a start
      if (chars[cur.ch] == symb && !end) {
        start = cur.ch + 1; // assign start to ahead of the cursor
      } else {
        // go backwards to find the start
        for (i = cur.ch; i > -1 && !start; i--) {
          if (chars[i] == symb) {
            start = i + 1;
          }
        }
      }

      // look forwards for the end symbol
      if (start && !end) {
        for (i = start, len = chars.length; i < len && !end; i++) {
          if (chars[i] == symb) {
            end = i;
          }
        }
      }

      // nothing found
      if (!start || !end) {
        return { start: cur, end: cur };
      }

      // include the symbols
      if (inclusive) {
        --start; ++end;
      }

      return {
        start: Pos(cur.line, start),
        end: Pos(cur.line, end)
      };
    }

    // Search functions
    defineOption('pcre', true, 'boolean');
    function SearchState() {}
    SearchState.prototype = {
      getQuery: function() {
        return vimGlobalState.query;
      },
      setQuery: function(query) {
        vimGlobalState.query = query;
      },
      getOverlay: function() {
        return this.searchOverlay;
      },
      setOverlay: function(overlay) {
        this.searchOverlay = overlay;
      },
      isReversed: function() {
        return vimGlobalState.isReversed;
      },
      setReversed: function(reversed) {
        vimGlobalState.isReversed = reversed;
      },
      getScrollbarAnnotate: function() {
        return this.annotate;
      },
      setScrollbarAnnotate: function(annotate) {
        this.annotate = annotate;
      }
    };
    function getSearchState(cm) {
      var vim = cm.state.vim;
      return vim.searchState_ || (vim.searchState_ = new SearchState());
    }
    function dialog(cm, template, shortText, onClose, options) {
      if (cm.openDialog) {
        cm.openDialog(template, onClose, { bottom: true, value: options.value,
            onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp,
            selectValueOnOpen: false});
      }
      else {
        onClose(prompt(shortText, ''));
      }
    }
    function splitBySlash(argString) {
      return splitBySeparator(argString, '/');
    }

    function findUnescapedSlashes(argString) {
      return findUnescapedSeparators(argString, '/');
    }

    function splitBySeparator(argString, separator) {
      var slashes = findUnescapedSeparators(argString, separator) || [];
      if (!slashes.length) return [];
      var tokens = [];
      // in case of strings like foo/bar
      if (slashes[0] !== 0) return;
      for (var i = 0; i < slashes.length; i++) {
        if (typeof slashes[i] == 'number')
          tokens.push(argString.substring(slashes[i] + 1, slashes[i+1]));
      }
      return tokens;
    }

    function findUnescapedSeparators(str, separator) {
      if (!separator)
        separator = '/';

      var escapeNextChar = false;
      var slashes = [];
      for (var i = 0; i < str.length; i++) {
        var c = str.charAt(i);
        if (!escapeNextChar && c == separator) {
          slashes.push(i);
        }
        escapeNextChar = !escapeNextChar && (c == '\\');
      }
      return slashes;
    }

    // Translates a search string from ex (vim) syntax into javascript form.
    function translateRegex(str) {
      // When these match, add a '\' if unescaped or remove one if escaped.
      var specials = '|(){';
      // Remove, but never add, a '\' for these.
      var unescape = '}';
      var escapeNextChar = false;
      var out = [];
      for (var i = -1; i < str.length; i++) {
        var c = str.charAt(i) || '';
        var n = str.charAt(i+1) || '';
        var specialComesNext = (n && specials.indexOf(n) != -1);
        if (escapeNextChar) {
          if (c !== '\\' || !specialComesNext) {
            out.push(c);
          }
          escapeNextChar = false;
        } else {
          if (c === '\\') {
            escapeNextChar = true;
            // Treat the unescape list as special for removing, but not adding '\'.
            if (n && unescape.indexOf(n) != -1) {
              specialComesNext = true;
            }
            // Not passing this test means removing a '\'.
            if (!specialComesNext || n === '\\') {
              out.push(c);
            }
          } else {
            out.push(c);
            if (specialComesNext && n !== '\\') {
              out.push('\\');
            }
          }
        }
      }
      return out.join('');
    }

    // Translates the replace part of a search and replace from ex (vim) syntax into
    // javascript form.  Similar to translateRegex, but additionally fixes back references
    // (translates '\[0..9]' to '$[0..9]') and follows different rules for escaping '$'.
    var charUnescapes = {'\\n': '\n', '\\r': '\r', '\\t': '\t'};
    function translateRegexReplace(str) {
      var escapeNextChar = false;
      var out = [];
      for (var i = -1; i < str.length; i++) {
        var c = str.charAt(i) || '';
        var n = str.charAt(i+1) || '';
        if (charUnescapes[c + n]) {
          out.push(charUnescapes[c+n]);
          i++;
        } else if (escapeNextChar) {
          // At any point in the loop, escapeNextChar is true if the previous
          // character was a '\' and was not escaped.
          out.push(c);
          escapeNextChar = false;
        } else {
          if (c === '\\') {
            escapeNextChar = true;
            if ((isNumber(n) || n === '$')) {
              out.push('$');
            } else if (n !== '/' && n !== '\\') {
              out.push('\\');
            }
          } else {
            if (c === '$') {
              out.push('$');
            }
            out.push(c);
            if (n === '/') {
              out.push('\\');
            }
          }
        }
      }
      return out.join('');
    }

    // Unescape \ and / in the replace part, for PCRE mode.
    var unescapes = {'\\/': '/', '\\\\': '\\', '\\n': '\n', '\\r': '\r', '\\t': '\t'};
    function unescapeRegexReplace(str) {
      var stream = new CodeMirror.StringStream(str);
      var output = [];
      while (!stream.eol()) {
        // Search for \.
        while (stream.peek() && stream.peek() != '\\') {
          output.push(stream.next());
        }
        var matched = false;
        for (var matcher in unescapes) {
          if (stream.match(matcher, true)) {
            matched = true;
            output.push(unescapes[matcher]);
            break;
          }
        }
        if (!matched) {
          // Don't change anything
          output.push(stream.next());
        }
      }
      return output.join('');
    }

    /**
     * Extract the regular expression from the query and return a Regexp object.
     * Returns null if the query is blank.
     * If ignoreCase is passed in, the Regexp object will have the 'i' flag set.
     * If smartCase is passed in, and the query contains upper case letters,
     *   then ignoreCase is overridden, and the 'i' flag will not be set.
     * If the query contains the /i in the flag part of the regular expression,
     *   then both ignoreCase and smartCase are ignored, and 'i' will be passed
     *   through to the Regex object.
     */
    function parseQuery(query, ignoreCase, smartCase) {
      // First update the last search register
      var lastSearchRegister = vimGlobalState.registerController.getRegister('/');
      lastSearchRegister.setText(query);
      // Check if the query is already a regex.
      if (query instanceof RegExp) { return query; }
      // First try to extract regex + flags from the input. If no flags found,
      // extract just the regex. IE does not accept flags directly defined in
      // the regex string in the form /regex/flags
      var slashes = findUnescapedSlashes(query);
      var regexPart;
      var forceIgnoreCase;
      if (!slashes.length) {
        // Query looks like 'regexp'
        regexPart = query;
      } else {
        // Query looks like 'regexp/...'
        regexPart = query.substring(0, slashes[0]);
        var flagsPart = query.substring(slashes[0]);
        forceIgnoreCase = (flagsPart.indexOf('i') != -1);
      }
      if (!regexPart) {
        return null;
      }
      if (!getOption('pcre')) {
        regexPart = translateRegex(regexPart);
      }
      if (smartCase) {
        ignoreCase = (/^[^A-Z]*$/).test(regexPart);
      }
      var regexp = new RegExp(regexPart,
          (ignoreCase || forceIgnoreCase) ? 'i' : undefined);
      return regexp;
    }
    function showConfirm(cm, text) {
      if (cm.openNotification) {
        cm.openNotification('<span style="color: red">' + text + '</span>',
                            {bottom: true, duration: 5000});
      } else {
        alert(text);
      }
    }
    function makePrompt(prefix, desc) {
      var raw = '<span style="font-family: monospace; white-space: pre">' +
          (prefix || "") + '<input type="text"></span>';
      if (desc)
        raw += ' <span style="color: #888">' + desc + '</span>';
      return raw;
    }
    var searchPromptDesc = '(Javascript regexp)';
    function showPrompt(cm, options) {
      var shortText = (options.prefix || '') + ' ' + (options.desc || '');
      var prompt = makePrompt(options.prefix, options.desc);
      dialog(cm, prompt, shortText, options.onClose, options);
    }
    function regexEqual(r1, r2) {
      if (r1 instanceof RegExp && r2 instanceof RegExp) {
          var props = ['global', 'multiline', 'ignoreCase', 'source'];
          for (var i = 0; i < props.length; i++) {
              var prop = props[i];
              if (r1[prop] !== r2[prop]) {
                  return false;
              }
          }
          return true;
      }
      return false;
    }
    // Returns true if the query is valid.
    function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) {
      if (!rawQuery) {
        return;
      }
      var state = getSearchState(cm);
      var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase);
      if (!query) {
        return;
      }
      highlightSearchMatches(cm, query);
      if (regexEqual(query, state.getQuery())) {
        return query;
      }
      state.setQuery(query);
      return query;
    }
    function searchOverlay(query) {
      if (query.source.charAt(0) == '^') {
        var matchSol = true;
      }
      return {
        token: function(stream) {
          if (matchSol && !stream.sol()) {
            stream.skipToEnd();
            return;
          }
          var match = stream.match(query, false);
          if (match) {
            if (match[0].length == 0) {
              // Matched empty string, skip to next.
              stream.next();
              return 'searching';
            }
            if (!stream.sol()) {
              // Backtrack 1 to match \b
              stream.backUp(1);
              if (!query.exec(stream.next() + match[0])) {
                stream.next();
                return null;
              }
            }
            stream.match(query);
            return 'searching';
          }
          while (!stream.eol()) {
            stream.next();
            if (stream.match(query, false)) break;
          }
        },
        query: query
      };
    }
    function highlightSearchMatches(cm, query) {
      var searchState = getSearchState(cm);
      var overlay = searchState.getOverlay();
      if (!overlay || query != overlay.query) {
        if (overlay) {
          cm.removeOverlay(overlay);
        }
        overlay = searchOverlay(query);
        cm.addOverlay(overlay);
        if (cm.showMatchesOnScrollbar) {
          if (searchState.getScrollbarAnnotate()) {
            searchState.getScrollbarAnnotate().clear();
          }
          searchState.setScrollbarAnnotate(cm.showMatchesOnScrollbar(query));
        }
        searchState.setOverlay(overlay);
      }
    }
    function findNext(cm, prev, query, repeat) {
      if (repeat === undefined) { repeat = 1; }
      return cm.operation(function() {
        var pos = cm.getCursor();
        var cursor = cm.getSearchCursor(query, pos);
        for (var i = 0; i < repeat; i++) {
          var found = cursor.find(prev);
          if (i == 0 && found && cursorEqual(cursor.from(), pos)) { found = cursor.find(prev); }
          if (!found) {
            // SearchCursor may have returned null because it hit EOF, wrap
            // around and try again.
            cursor = cm.getSearchCursor(query,
                (prev) ? Pos(cm.lastLine()) : Pos(cm.firstLine(), 0) );
            if (!cursor.find(prev)) {
              return;
            }
          }
        }
        return cursor.from();
      });
    }
    function clearSearchHighlight(cm) {
      var state = getSearchState(cm);
      cm.removeOverlay(getSearchState(cm).getOverlay());
      state.setOverlay(null);
      if (state.getScrollbarAnnotate()) {
        state.getScrollbarAnnotate().clear();
        state.setScrollbarAnnotate(null);
      }
    }
    /**
     * Check if pos is in the specified range, INCLUSIVE.
     * Range can be specified with 1 or 2 arguments.
     * If the first range argument is an array, treat it as an array of line
     * numbers. Match pos against any of the lines.
     * If the first range argument is a number,
     *   if there is only 1 range argument, check if pos has the same line
     *       number
     *   if there are 2 range arguments, then check if pos is in between the two
     *       range arguments.
     */
    function isInRange(pos, start, end) {
      if (typeof pos != 'number') {
        // Assume it is a cursor position. Get the line number.
        pos = pos.line;
      }
      if (start instanceof Array) {
        return inArray(pos, start);
      } else {
        if (end) {
          return (pos >= start && pos <= end);
        } else {
          return pos == start;
        }
      }
    }
    function getUserVisibleLines(cm) {
      var scrollInfo = cm.getScrollInfo();
      var occludeToleranceTop = 6;
      var occludeToleranceBottom = 10;
      var from = cm.coordsChar({left:0, top: occludeToleranceTop + scrollInfo.top}, 'local');
      var bottomY = scrollInfo.clientHeight - occludeToleranceBottom + scrollInfo.top;
      var to = cm.coordsChar({left:0, top: bottomY}, 'local');
      return {top: from.line, bottom: to.line};
    }

    function getMarkPos(cm, vim, markName) {
      if (markName == '\'') {
        var history = cm.doc.history.done;
        var event = history[history.length - 2];
        return event && event.ranges && event.ranges[0].head;
      } else if (markName == '.') {
        if (cm.doc.history.lastModTime == 0) {
          return  // If no changes, bail out; don't bother to copy or reverse history array.
        } else {
          var changeHistory = cm.doc.history.done.filter(function(el){ if (el.changes !== undefined) { return el } });
          changeHistory.reverse();
          var lastEditPos = changeHistory[0].changes[0].to;
        }
        return lastEditPos;
      }

      var mark = vim.marks[markName];
      return mark && mark.find();
    }

    var ExCommandDispatcher = function() {
      this.buildCommandMap_();
    };
    ExCommandDispatcher.prototype = {
      processCommand: function(cm, input, opt_params) {
        var that = this;
        cm.operation(function () {
          cm.curOp.isVimOp = true;
          that._processCommand(cm, input, opt_params);
        });
      },
      _processCommand: function(cm, input, opt_params) {
        var vim = cm.state.vim;
        var commandHistoryRegister = vimGlobalState.registerController.getRegister(':');
        var previousCommand = commandHistoryRegister.toString();
        if (vim.visualMode) {
          exitVisualMode(cm);
        }
        var inputStream = new CodeMirror.StringStream(input);
        // update ": with the latest command whether valid or invalid
        commandHistoryRegister.setText(input);
        var params = opt_params || {};
        params.input = input;
        try {
          this.parseInput_(cm, inputStream, params);
        } catch(e) {
          showConfirm(cm, e);
          throw e;
        }
        var command;
        var commandName;
        if (!params.commandName) {
          // If only a line range is defined, move to the line.
          if (params.line !== undefined) {
            commandName = 'move';
          }
        } else {
          command = this.matchCommand_(params.commandName);
          if (command) {
            commandName = command.name;
            if (command.excludeFromCommandHistory) {
              commandHistoryRegister.setText(previousCommand);
            }
            this.parseCommandArgs_(inputStream, params, command);
            if (command.type == 'exToKey') {
              // Handle Ex to Key mapping.
              for (var i = 0; i < command.toKeys.length; i++) {
                CodeMirror.Vim.handleKey(cm, command.toKeys[i], 'mapping');
              }
              return;
            } else if (command.type == 'exToEx') {
              // Handle Ex to Ex mapping.
              this.processCommand(cm, command.toInput);
              return;
            }
          }
        }
        if (!commandName) {
          showConfirm(cm, 'Not an editor command ":' + input + '"');
          return;
        }
        try {
          exCommands[commandName](cm, params);
          // Possibly asynchronous commands (e.g. substitute, which might have a
          // user confirmation), are responsible for calling the callback when
          // done. All others have it taken care of for them here.
          if ((!command || !command.possiblyAsync) && params.callback) {
            params.callback();
          }
        } catch(e) {
          showConfirm(cm, e);
          throw e;
        }
      },
      parseInput_: function(cm, inputStream, result) {
        inputStream.eatWhile(':');
        // Parse range.
        if (inputStream.eat('%')) {
          result.line = cm.firstLine();
          result.lineEnd = cm.lastLine();
        } else {
          result.line = this.parseLineSpec_(cm, inputStream);
          if (result.line !== undefined && inputStream.eat(',')) {
            result.lineEnd = this.parseLineSpec_(cm, inputStream);
          }
        }

        // Parse command name.
        var commandMatch = inputStream.match(/^(\w+)/);
        if (commandMatch) {
          result.commandName = commandMatch[1];
        } else {
          result.commandName = inputStream.match(/.*/)[0];
        }

        return result;
      },
      parseLineSpec_: function(cm, inputStream) {
        var numberMatch = inputStream.match(/^(\d+)/);
        if (numberMatch) {
          // Absolute line number plus offset (N+M or N-M) is probably a typo,
          // not something the user actually wanted. (NB: vim does allow this.)
          return parseInt(numberMatch[1], 10) - 1;
        }
        switch (inputStream.next()) {
          case '.':
            return this.parseLineSpecOffset_(inputStream, cm.getCursor().line);
          case '$':
            return this.parseLineSpecOffset_(inputStream, cm.lastLine());
          case '\'':
            var markName = inputStream.next();
            var markPos = getMarkPos(cm, cm.state.vim, markName);
            if (!markPos) throw new Error('Mark not set');
            return this.parseLineSpecOffset_(inputStream, markPos.line);
          case '-':
          case '+':
            inputStream.backUp(1);
            // Offset is relative to current line if not otherwise specified.
            return this.parseLineSpecOffset_(inputStream, cm.getCursor().line);
          default:
            inputStream.backUp(1);
            return undefined;
        }
      },
      parseLineSpecOffset_: function(inputStream, line) {
        var offsetMatch = inputStream.match(/^([+-])?(\d+)/);
        if (offsetMatch) {
          var offset = parseInt(offsetMatch[2], 10);
          if (offsetMatch[1] == "-") {
            line -= offset;
          } else {
            line += offset;
          }
        }
        return line;
      },
      parseCommandArgs_: function(inputStream, params, command) {
        if (inputStream.eol()) {
          return;
        }
        params.argString = inputStream.match(/.*/)[0];
        // Parse command-line arguments
        var delim = command.argDelimiter || /\s+/;
        var args = trim(params.argString).split(delim);
        if (args.length && args[0]) {
          params.args = args;
        }
      },
      matchCommand_: function(commandName) {
        // Return the command in the command map that matches the shortest
        // prefix of the passed in command name. The match is guaranteed to be
        // unambiguous if the defaultExCommandMap's shortNames are set up
        // correctly. (see @code{defaultExCommandMap}).
        for (var i = commandName.length; i > 0; i--) {
          var prefix = commandName.substring(0, i);
          if (this.commandMap_[prefix]) {
            var command = this.commandMap_[prefix];
            if (command.name.indexOf(commandName) === 0) {
              return command;
            }
          }
        }
        return null;
      },
      buildCommandMap_: function() {
        this.commandMap_ = {};
        for (var i = 0; i < defaultExCommandMap.length; i++) {
          var command = defaultExCommandMap[i];
          var key = command.shortName || command.name;
          this.commandMap_[key] = command;
        }
      },
      map: function(lhs, rhs, ctx) {
        if (lhs != ':' && lhs.charAt(0) == ':') {
          if (ctx) { throw Error('Mode not supported for ex mappings'); }
          var commandName = lhs.substring(1);
          if (rhs != ':' && rhs.charAt(0) == ':') {
            // Ex to Ex mapping
            this.commandMap_[commandName] = {
              name: commandName,
              type: 'exToEx',
              toInput: rhs.substring(1),
              user: true
            };
          } else {
            // Ex to key mapping
            this.commandMap_[commandName] = {
              name: commandName,
              type: 'exToKey',
              toKeys: rhs,
              user: true
            };
          }
        } else {
          if (rhs != ':' && rhs.charAt(0) == ':') {
            // Key to Ex mapping.
            var mapping = {
              keys: lhs,
              type: 'keyToEx',
              exArgs: { input: rhs.substring(1) }
            };
            if (ctx) { mapping.context = ctx; }
            defaultKeymap.unshift(mapping);
          } else {
            // Key to key mapping
            var mapping = {
              keys: lhs,
              type: 'keyToKey',
              toKeys: rhs
            };
            if (ctx) { mapping.context = ctx; }
            defaultKeymap.unshift(mapping);
          }
        }
      },
      unmap: function(lhs, ctx) {
        if (lhs != ':' && lhs.charAt(0) == ':') {
          // Ex to Ex or Ex to key mapping
          if (ctx) { throw Error('Mode not supported for ex mappings'); }
          var commandName = lhs.substring(1);
          if (this.commandMap_[commandName] && this.commandMap_[commandName].user) {
            delete this.commandMap_[commandName];
            return;
          }
        } else {
          // Key to Ex or key to key mapping
          var keys = lhs;
          for (var i = 0; i < defaultKeymap.length; i++) {
            if (keys == defaultKeymap[i].keys
                && defaultKeymap[i].context === ctx) {
              defaultKeymap.splice(i, 1);
              return;
            }
          }
        }
        throw Error('No such mapping.');
      }
    };

    var exCommands = {
      colorscheme: function(cm, params) {
        if (!params.args || params.args.length < 1) {
          showConfirm(cm, cm.getOption('theme'));
          return;
        }
        cm.setOption('theme', params.args[0]);
      },
      map: function(cm, params, ctx) {
        var mapArgs = params.args;
        if (!mapArgs || mapArgs.length < 2) {
          if (cm) {
            showConfirm(cm, 'Invalid mapping: ' + params.input);
          }
          return;
        }
        exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx);
      },
      imap: function(cm, params) { this.map(cm, params, 'insert'); },
      nmap: function(cm, params) { this.map(cm, params, 'normal'); },
      vmap: function(cm, params) { this.map(cm, params, 'visual'); },
      unmap: function(cm, params, ctx) {
        var mapArgs = params.args;
        if (!mapArgs || mapArgs.length < 1) {
          if (cm) {
            showConfirm(cm, 'No such mapping: ' + params.input);
          }
          return;
        }
        exCommandDispatcher.unmap(mapArgs[0], ctx);
      },
      move: function(cm, params) {
        commandDispatcher.processCommand(cm, cm.state.vim, {
            type: 'motion',
            motion: 'moveToLineOrEdgeOfDocument',
            motionArgs: { forward: false, explicitRepeat: true,
              linewise: true },
            repeatOverride: params.line+1});
      },
      set: function(cm, params) {
        var setArgs = params.args;
        // Options passed through to the setOption/getOption calls. May be passed in by the
        // local/global versions of the set command
        var setCfg = params.setCfg || {};
        if (!setArgs || setArgs.length < 1) {
          if (cm) {
            showConfirm(cm, 'Invalid mapping: ' + params.input);
          }
          return;
        }
        var expr = setArgs[0].split('=');
        var optionName = expr[0];
        var value = expr[1];
        var forceGet = false;

        if (optionName.charAt(optionName.length - 1) == '?') {
          // If post-fixed with ?, then the set is actually a get.
          if (value) { throw Error('Trailing characters: ' + params.argString); }
          optionName = optionName.substring(0, optionName.length - 1);
          forceGet = true;
        }
        if (value === undefined && optionName.substring(0, 2) == 'no') {
          // To set boolean options to false, the option name is prefixed with
          // 'no'.
          optionName = optionName.substring(2);
          value = false;
        }

        var optionIsBoolean = options[optionName] && options[optionName].type == 'boolean';
        if (optionIsBoolean && value == undefined) {
          // Calling set with a boolean option sets it to true.
          value = true;
        }
        // If no value is provided, then we assume this is a get.
        if (!optionIsBoolean && value === undefined || forceGet) {
          var oldValue = getOption(optionName, cm, setCfg);
          if (oldValue instanceof Error) {
            showConfirm(cm, oldValue.message);
          } else if (oldValue === true || oldValue === false) {
            showConfirm(cm, ' ' + (oldValue ? '' : 'no') + optionName);
          } else {
            showConfirm(cm, '  ' + optionName + '=' + oldValue);
          }
        } else {
          var setOptionReturn = setOption(optionName, value, cm, setCfg);
          if (setOptionReturn instanceof Error) {
            showConfirm(cm, setOptionReturn.message);
          }
        }
      },
      setlocal: function (cm, params) {
        // setCfg is passed through to setOption
        params.setCfg = {scope: 'local'};
        this.set(cm, params);
      },
      setglobal: function (cm, params) {
        // setCfg is passed through to setOption
        params.setCfg = {scope: 'global'};
        this.set(cm, params);
      },
      registers: function(cm, params) {
        var regArgs = params.args;
        var registers = vimGlobalState.registerController.registers;
        var regInfo = '----------Registers----------<br><br>';
        if (!regArgs) {
          for (var registerName in registers) {
            var text = registers[registerName].toString();
            if (text.length) {
              regInfo += '"' + registerName + '    ' + text + '<br>';
            }
          }
        } else {
          var registerName;
          regArgs = regArgs.join('');
          for (var i = 0; i < regArgs.length; i++) {
            registerName = regArgs.charAt(i);
            if (!vimGlobalState.registerController.isValidRegister(registerName)) {
              continue;
            }
            var register = registers[registerName] || new Register();
            regInfo += '"' + registerName + '    ' + register.toString() + '<br>';
          }
        }
        showConfirm(cm, regInfo);
      },
      sort: function(cm, params) {
        var reverse, ignoreCase, unique, number, pattern;
        function parseArgs() {
          if (params.argString) {
            var args = new CodeMirror.StringStream(params.argString);
            if (args.eat('!')) { reverse = true; }
            if (args.eol()) { return; }
            if (!args.eatSpace()) { return 'Invalid arguments'; }
            var opts = args.match(/([dinuox]+)?\s*(\/.+\/)?\s*/);
            if (!opts && !args.eol()) { return 'Invalid arguments'; }
            if (opts[1]) {
              ignoreCase = opts[1].indexOf('i') != -1;
              unique = opts[1].indexOf('u') != -1;
              var decimal = opts[1].indexOf('d') != -1 || opts[1].indexOf('n') != -1 && 1;
              var hex = opts[1].indexOf('x') != -1 && 1;
              var octal = opts[1].indexOf('o') != -1 && 1;
              if (decimal + hex + octal > 1) { return 'Invalid arguments'; }
              number = decimal && 'decimal' || hex && 'hex' || octal && 'octal';
            }
            if (opts[2]) {
              pattern = new RegExp(opts[2].substr(1, opts[2].length - 2), ignoreCase ? 'i' : '');
            }
          }
        }
        var err = parseArgs();
        if (err) {
          showConfirm(cm, err + ': ' + params.argString);
          return;
        }
        var lineStart = params.line || cm.firstLine();
        var lineEnd = params.lineEnd || params.line || cm.lastLine();
        if (lineStart == lineEnd) { return; }
        var curStart = Pos(lineStart, 0);
        var curEnd = Pos(lineEnd, lineLength(cm, lineEnd));
        var text = cm.getRange(curStart, curEnd).split('\n');
        var numberRegex = pattern ? pattern :
           (number == 'decimal') ? /(-?)([\d]+)/ :
           (number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i :
           (number == 'octal') ? /([0-7]+)/ : null;
        var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null;
        var numPart = [], textPart = [];
        if (number || pattern) {
          for (var i = 0; i < text.length; i++) {
            var matchPart = pattern ? text[i].match(pattern) : null;
            if (matchPart && matchPart[0] != '') {
              numPart.push(matchPart);
            } else if (!pattern && numberRegex.exec(text[i])) {
              numPart.push(text[i]);
            } else {
              textPart.push(text[i]);
            }
          }
        } else {
          textPart = text;
        }
        function compareFn(a, b) {
          if (reverse) { var tmp; tmp = a; a = b; b = tmp; }
          if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); }
          var anum = number && numberRegex.exec(a);
          var bnum = number && numberRegex.exec(b);
          if (!anum) { return a < b ? -1 : 1; }
          anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix);
          bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix);
          return anum - bnum;
        }
        function comparePatternFn(a, b) {
          if (reverse) { var tmp; tmp = a; a = b; b = tmp; }
          if (ignoreCase) { a[0] = a[0].toLowerCase(); b[0] = b[0].toLowerCase(); }
          return (a[0] < b[0]) ? -1 : 1;
        }
        numPart.sort(pattern ? comparePatternFn : compareFn);
        if (pattern) {
          for (var i = 0; i < numPart.length; i++) {
            numPart[i] = numPart[i].input;
          }
        } else if (!number) { textPart.sort(compareFn); }
        text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart);
        if (unique) { // Remove duplicate lines
          var textOld = text;
          var lastLine;
          text = [];
          for (var i = 0; i < textOld.length; i++) {
            if (textOld[i] != lastLine) {
              text.push(textOld[i]);
            }
            lastLine = textOld[i];
          }
        }
        cm.replaceRange(text.join('\n'), curStart, curEnd);
      },
      global: function(cm, params) {
        // a global command is of the form
        // :[range]g/pattern/[cmd]
        // argString holds the string /pattern/[cmd]
        var argString = params.argString;
        if (!argString) {
          showConfirm(cm, 'Regular Expression missing from global');
          return;
        }
        // range is specified here
        var lineStart = (params.line !== undefined) ? params.line : cm.firstLine();
        var lineEnd = params.lineEnd || params.line || cm.lastLine();
        // get the tokens from argString
        var tokens = splitBySlash(argString);
        var regexPart = argString, cmd;
        if (tokens.length) {
          regexPart = tokens[0];
          cmd = tokens.slice(1, tokens.length).join('/');
        }
        if (regexPart) {
          // If regex part is empty, then use the previous query. Otherwise
          // use the regex part as the new query.
          try {
           updateSearchQuery(cm, regexPart, true /** ignoreCase */,
             true /** smartCase */);
          } catch (e) {
           showConfirm(cm, 'Invalid regex: ' + regexPart);
           return;
          }
        }
        // now that we have the regexPart, search for regex matches in the
        // specified range of lines
        var query = getSearchState(cm).getQuery();
        var matchedLines = [], content = '';
        for (var i = lineStart; i <= lineEnd; i++) {
          var matched = query.test(cm.getLine(i));
          if (matched) {
            matchedLines.push(i+1);
            content+= cm.getLine(i) + '<br>';
          }
        }
        // if there is no [cmd], just display the list of matched lines
        if (!cmd) {
          showConfirm(cm, content);
          return;
        }
        var index = 0;
        var nextCommand = function() {
          if (index < matchedLines.length) {
            var command = matchedLines[index] + cmd;
            exCommandDispatcher.processCommand(cm, command, {
              callback: nextCommand
            });
          }
          index++;
        };
        nextCommand();
      },
      substitute: function(cm, params) {
        if (!cm.getSearchCursor) {
          throw new Error('Search feature not available. Requires searchcursor.js or ' +
              'any other getSearchCursor implementation.');
        }
        var argString = params.argString;
        var tokens = argString ? splitBySeparator(argString, argString[0]) : [];
        var regexPart, replacePart = '', trailing, flagsPart, count;
        var confirm = false; // Whether to confirm each replace.
        var global = false; // True to replace all instances on a line, false to replace only 1.
        if (tokens.length) {
          regexPart = tokens[0];
          replacePart = tokens[1];
          if (regexPart && regexPart[regexPart.length - 1] === '$') {
            regexPart = regexPart.slice(0, regexPart.length - 1) + '\\n';
            replacePart = replacePart ? replacePart + '\n' : '\n';
          }
          if (replacePart !== undefined) {
            if (getOption('pcre')) {
              replacePart = unescapeRegexReplace(replacePart);
            } else {
              replacePart = translateRegexReplace(replacePart);
            }
            vimGlobalState.lastSubstituteReplacePart = replacePart;
          }
          trailing = tokens[2] ? tokens[2].split(' ') : [];
        } else {
          // either the argString is empty or its of the form ' hello/world'
          // actually splitBySlash returns a list of tokens
          // only if the string starts with a '/'
          if (argString && argString.length) {
            showConfirm(cm, 'Substitutions should be of the form ' +
                ':s/pattern/replace/');
            return;
          }
        }
        // After the 3rd slash, we can have flags followed by a space followed
        // by count.
        if (trailing) {
          flagsPart = trailing[0];
          count = parseInt(trailing[1]);
          if (flagsPart) {
            if (flagsPart.indexOf('c') != -1) {
              confirm = true;
              flagsPart.replace('c', '');
            }
            if (flagsPart.indexOf('g') != -1) {
              global = true;
              flagsPart.replace('g', '');
            }
            regexPart = regexPart.replace(/\//g, "\\/") + '/' + flagsPart;
          }
        }
        if (regexPart) {
          // If regex part is empty, then use the previous query. Otherwise use
          // the regex part as the new query.
          try {
            updateSearchQuery(cm, regexPart, true /** ignoreCase */,
              true /** smartCase */);
          } catch (e) {
            showConfirm(cm, 'Invalid regex: ' + regexPart);
            return;
          }
        }
        replacePart = replacePart || vimGlobalState.lastSubstituteReplacePart;
        if (replacePart === undefined) {
          showConfirm(cm, 'No previous substitute regular expression');
          return;
        }
        var state = getSearchState(cm);
        var query = state.getQuery();
        var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line;
        var lineEnd = params.lineEnd || lineStart;
        if (lineStart == cm.firstLine() && lineEnd == cm.lastLine()) {
          lineEnd = Infinity;
        }
        if (count) {
          lineStart = lineEnd;
          lineEnd = lineStart + count - 1;
        }
        var startPos = clipCursorToContent(cm, Pos(lineStart, 0));
        var cursor = cm.getSearchCursor(query, startPos);
        doReplace(cm, confirm, global, lineStart, lineEnd, cursor, query, replacePart, params.callback);
      },
      redo: CodeMirror.commands.redo,
      undo: CodeMirror.commands.undo,
      write: function(cm) {
        if (CodeMirror.commands.save) {
          // If a save command is defined, call it.
          CodeMirror.commands.save(cm);
        } else if (cm.save) {
          // Saves to text area if no save command is defined and cm.save() is available.
          cm.save();
        }
      },
      nohlsearch: function(cm) {
        clearSearchHighlight(cm);
      },
      yank: function (cm) {
        var cur = copyCursor(cm.getCursor());
        var line = cur.line;
        var lineText = cm.getLine(line);
        vimGlobalState.registerController.pushText(
          '0', 'yank', lineText, true, true);
      },
      delmarks: function(cm, params) {
        if (!params.argString || !trim(params.argString)) {
          showConfirm(cm, 'Argument required');
          return;
        }

        var state = cm.state.vim;
        var stream = new CodeMirror.StringStream(trim(params.argString));
        while (!stream.eol()) {
          stream.eatSpace();

          // Record the streams position at the beginning of the loop for use
          // in error messages.
          var count = stream.pos;

          if (!stream.match(/[a-zA-Z]/, false)) {
            showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
            return;
          }

          var sym = stream.next();
          // Check if this symbol is part of a range
          if (stream.match('-', true)) {
            // This symbol is part of a range.

            // The range must terminate at an alphabetic character.
            if (!stream.match(/[a-zA-Z]/, false)) {
              showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
              return;
            }

            var startMark = sym;
            var finishMark = stream.next();
            // The range must terminate at an alphabetic character which
            // shares the same case as the start of the range.
            if (isLowerCase(startMark) && isLowerCase(finishMark) ||
                isUpperCase(startMark) && isUpperCase(finishMark)) {
              var start = startMark.charCodeAt(0);
              var finish = finishMark.charCodeAt(0);
              if (start >= finish) {
                showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
                return;
              }

              // Because marks are always ASCII values, and we have
              // determined that they are the same case, we can use
              // their char codes to iterate through the defined range.
              for (var j = 0; j <= finish - start; j++) {
                var mark = String.fromCharCode(start + j);
                delete state.marks[mark];
              }
            } else {
              showConfirm(cm, 'Invalid argument: ' + startMark + '-');
              return;
            }
          } else {
            // This symbol is a valid mark, and is not part of a range.
            delete state.marks[sym];
          }
        }
      }
    };

    var exCommandDispatcher = new ExCommandDispatcher();

    /**
    * @param {CodeMirror} cm CodeMirror instance we are in.
    * @param {boolean} confirm Whether to confirm each replace.
    * @param {Cursor} lineStart Line to start replacing from.
    * @param {Cursor} lineEnd Line to stop replacing at.
    * @param {RegExp} query Query for performing matches with.
    * @param {string} replaceWith Text to replace matches with. May contain $1,
    *     $2, etc for replacing captured groups using Javascript replace.
    * @param {function()} callback A callback for when the replace is done.
    */
    function doReplace(cm, confirm, global, lineStart, lineEnd, searchCursor, query,
        replaceWith, callback) {
      // Set up all the functions.
      cm.state.vim.exMode = true;
      var done = false;
      var lastPos = searchCursor.from();
      function replaceAll() {
        cm.operation(function() {
          while (!done) {
            replace();
            next();
          }
          stop();
        });
      }
      function replace() {
        var text = cm.getRange(searchCursor.from(), searchCursor.to());
        var newText = text.replace(query, replaceWith);
        searchCursor.replace(newText);
      }
      function next() {
        // The below only loops to skip over multiple occurrences on the same
        // line when 'global' is not true.
        while(searchCursor.findNext() &&
              isInRange(searchCursor.from(), lineStart, lineEnd)) {
          if (!global && lastPos && searchCursor.from().line == lastPos.line) {
            continue;
          }
          cm.scrollIntoView(searchCursor.from(), 30);
          cm.setSelection(searchCursor.from(), searchCursor.to());
          lastPos = searchCursor.from();
          done = false;
          return;
        }
        done = true;
      }
      function stop(close) {
        if (close) { close(); }
        cm.focus();
        if (lastPos) {
          cm.setCursor(lastPos);
          var vim = cm.state.vim;
          vim.exMode = false;
          vim.lastHPos = vim.lastHSPos = lastPos.ch;
        }
        if (callback) { callback(); }
      }
      function onPromptKeyDown(e, _value, close) {
        // Swallow all keys.
        CodeMirror.e_stop(e);
        var keyName = CodeMirror.keyName(e);
        switch (keyName) {
          case 'Y':
            replace(); next(); break;
          case 'N':
            next(); break;
          case 'A':
            // replaceAll contains a call to close of its own. We don't want it
            // to fire too early or multiple times.
            var savedCallback = callback;
            callback = undefined;
            cm.operation(replaceAll);
            callback = savedCallback;
            break;
          case 'L':
            replace();
            // fall through and exit.
          case 'Q':
          case 'Esc':
          case 'Ctrl-C':
          case 'Ctrl-[':
            stop(close);
            break;
        }
        if (done) { stop(close); }
        return true;
      }

      // Actually do replace.
      next();
      if (done) {
        showConfirm(cm, 'No matches for ' + query.source);
        return;
      }
      if (!confirm) {
        replaceAll();
        if (callback) { callback(); }
        return;
      }
      showPrompt(cm, {
        prefix: 'replace with <strong>' + replaceWith + '</strong> (y/n/a/q/l)',
        onKeyDown: onPromptKeyDown
      });
    }

    CodeMirror.keyMap.vim = {
      attach: attachVimMap,
      detach: detachVimMap,
      call: cmKey
    };

    function exitInsertMode(cm) {
      var vim = cm.state.vim;
      var macroModeState = vimGlobalState.macroModeState;
      var insertModeChangeRegister = vimGlobalState.registerController.getRegister('.');
      var isPlaying = macroModeState.isPlaying;
      var lastChange = macroModeState.lastInsertModeChanges;
      // In case of visual block, the insertModeChanges are not saved as a
      // single word, so we convert them to a single word
      // so as to update the ". register as expected in real vim.
      var text = [];
      if (!isPlaying) {
        var selLength = lastChange.inVisualBlock && vim.lastSelection ?
            vim.lastSelection.visualBlock.height : 1;
        var changes = lastChange.changes;
        var text = [];
        var i = 0;
        // In case of multiple selections in blockwise visual,
        // the inserted text, for example: 'f<Backspace>oo', is stored as
        // 'f', 'f', InsertModeKey 'o', 'o', 'o', 'o'. (if you have a block with 2 lines).
        // We push the contents of the changes array as per the following:
        // 1. In case of InsertModeKey, just increment by 1.
        // 2. In case of a character, jump by selLength (2 in the example).
        while (i < changes.length) {
          // This loop will convert 'ff<bs>oooo' to 'f<bs>oo'.
          text.push(changes[i]);
          if (changes[i] instanceof InsertModeKey) {
             i++;
          } else {
             i+= selLength;
          }
        }
        lastChange.changes = text;
        cm.off('change', onChange);
        CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
      }
      if (!isPlaying && vim.insertModeRepeat > 1) {
        // Perform insert mode repeat for commands like 3,a and 3,o.
        repeatLastEdit(cm, vim, vim.insertModeRepeat - 1,
            true /** repeatForInsert */);
        vim.lastEditInputState.repeatOverride = vim.insertModeRepeat;
      }
      delete vim.insertModeRepeat;
      vim.insertMode = false;
      cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1);
      cm.setOption('keyMap', 'vim');
      cm.setOption('disableInput', true);
      cm.toggleOverwrite(false); // exit replace mode if we were in it.
      // update the ". register before exiting insert mode
      insertModeChangeRegister.setText(lastChange.changes.join(''));
      CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
      if (macroModeState.isRecording) {
        logInsertModeChange(macroModeState);
      }
    }

    function _mapCommand(command) {
      defaultKeymap.unshift(command);
    }

    function mapCommand(keys, type, name, args, extra) {
      var command = {keys: keys, type: type};
      command[type] = name;
      command[type + "Args"] = args;
      for (var key in extra)
        command[key] = extra[key];
      _mapCommand(command);
    }

    // The timeout in milliseconds for the two-character ESC keymap should be
    // adjusted according to your typing speed to prevent false positives.
    defineOption('insertModeEscKeysTimeout', 200, 'number');

    CodeMirror.keyMap['vim-insert'] = {
      // TODO: override navigation keys so that Esc will cancel automatic
      // indentation from o, O, i_<CR>
      fallthrough: ['default'],
      attach: attachVimMap,
      detach: detachVimMap,
      call: cmKey
    };

    CodeMirror.keyMap['vim-replace'] = {
      'Backspace': 'goCharLeft',
      fallthrough: ['vim-insert'],
      attach: attachVimMap,
      detach: detachVimMap,
      call: cmKey
    };

    function executeMacroRegister(cm, vim, macroModeState, registerName) {
      var register = vimGlobalState.registerController.getRegister(registerName);
      if (registerName == ':') {
        // Read-only register containing last Ex command.
        if (register.keyBuffer[0]) {
          exCommandDispatcher.processCommand(cm, register.keyBuffer[0]);
        }
        macroModeState.isPlaying = false;
        return;
      }
      var keyBuffer = register.keyBuffer;
      var imc = 0;
      macroModeState.isPlaying = true;
      macroModeState.replaySearchQueries = register.searchQueries.slice(0);
      for (var i = 0; i < keyBuffer.length; i++) {
        var text = keyBuffer[i];
        var match, key;
        while (text) {
          // Pull off one command key, which is either a single character
          // or a special sequence wrapped in '<' and '>', e.g. '<Space>'.
          match = (/<\w+-.+?>|<\w+>|./).exec(text);
          key = match[0];
          text = text.substring(match.index + key.length);
          CodeMirror.Vim.handleKey(cm, key, 'macro');
          if (vim.insertMode) {
            var changes = register.insertModeChanges[imc++].changes;
            vimGlobalState.macroModeState.lastInsertModeChanges.changes =
                changes;
            repeatInsertModeChanges(cm, changes, 1);
            exitInsertMode(cm);
          }
        }
      }
      macroModeState.isPlaying = false;
    }

    function logKey(macroModeState, key) {
      if (macroModeState.isPlaying) { return; }
      var registerName = macroModeState.latestRegister;
      var register = vimGlobalState.registerController.getRegister(registerName);
      if (register) {
        register.pushText(key);
      }
    }

    function logInsertModeChange(macroModeState) {
      if (macroModeState.isPlaying) { return; }
      var registerName = macroModeState.latestRegister;
      var register = vimGlobalState.registerController.getRegister(registerName);
      if (register && register.pushInsertModeChanges) {
        register.pushInsertModeChanges(macroModeState.lastInsertModeChanges);
      }
    }

    function logSearchQuery(macroModeState, query) {
      if (macroModeState.isPlaying) { return; }
      var registerName = macroModeState.latestRegister;
      var register = vimGlobalState.registerController.getRegister(registerName);
      if (register && register.pushSearchQuery) {
        register.pushSearchQuery(query);
      }
    }

    /**
     * Listens for changes made in insert mode.
     * Should only be active in insert mode.
     */
    function onChange(cm, changeObj) {
      var macroModeState = vimGlobalState.macroModeState;
      var lastChange = macroModeState.lastInsertModeChanges;
      if (!macroModeState.isPlaying) {
        while(changeObj) {
          lastChange.expectCursorActivityForChange = true;
          if (changeObj.origin == '+input' || changeObj.origin == 'paste'
              || changeObj.origin === undefined /* only in testing */) {
            var text = changeObj.text.join('\n');
            if (lastChange.maybeReset) {
              lastChange.changes = [];
              lastChange.maybeReset = false;
            }
            if (cm.state.overwrite && !/\n/.test(text)) {
                lastChange.changes.push([text]);
            } else {
                lastChange.changes.push(text);
            }
          }
          // Change objects may be chained with next.
          changeObj = changeObj.next;
        }
      }
    }

    /**
    * Listens for any kind of cursor activity on CodeMirror.
    */
    function onCursorActivity(cm) {
      var vim = cm.state.vim;
      if (vim.insertMode) {
        // Tracking cursor activity in insert mode (for macro support).
        var macroModeState = vimGlobalState.macroModeState;
        if (macroModeState.isPlaying) { return; }
        var lastChange = macroModeState.lastInsertModeChanges;
        if (lastChange.expectCursorActivityForChange) {
          lastChange.expectCursorActivityForChange = false;
        } else {
          // Cursor moved outside the context of an edit. Reset the change.
          lastChange.maybeReset = true;
        }
      } else if (!cm.curOp.isVimOp) {
        handleExternalSelection(cm, vim);
      }
      if (vim.visualMode) {
        updateFakeCursor(cm);
      }
    }
    function updateFakeCursor(cm) {
      var vim = cm.state.vim;
      var from = clipCursorToContent(cm, copyCursor(vim.sel.head));
      var to = offsetCursor(from, 0, 1);
      if (vim.fakeCursor) {
        vim.fakeCursor.clear();
      }
      vim.fakeCursor = cm.markText(from, to, {className: 'cm-animate-fat-cursor'});
    }
    function handleExternalSelection(cm, vim) {
      var anchor = cm.getCursor('anchor');
      var head = cm.getCursor('head');
      // Enter or exit visual mode to match mouse selection.
      if (vim.visualMode && !cm.somethingSelected()) {
        exitVisualMode(cm, false);
      } else if (!vim.visualMode && !vim.insertMode && cm.somethingSelected()) {
        vim.visualMode = true;
        vim.visualLine = false;
        CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
      }
      if (vim.visualMode) {
        // Bind CodeMirror selection model to vim selection model.
        // Mouse selections are considered visual characterwise.
        var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0;
        var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0;
        head = offsetCursor(head, 0, headOffset);
        anchor = offsetCursor(anchor, 0, anchorOffset);
        vim.sel = {
          anchor: anchor,
          head: head
        };
        updateMark(cm, vim, '<', cursorMin(head, anchor));
        updateMark(cm, vim, '>', cursorMax(head, anchor));
      } else if (!vim.insertMode) {
        // Reset lastHPos if selection was modified by something outside of vim mode e.g. by mouse.
        vim.lastHPos = cm.getCursor().ch;
      }
    }

    /** Wrapper for special keys pressed in insert mode */
    function InsertModeKey(keyName) {
      this.keyName = keyName;
    }

    /**
    * Handles raw key down events from the text area.
    * - Should only be active in insert mode.
    * - For recording deletes in insert mode.
    */
    function onKeyEventTargetKeyDown(e) {
      var macroModeState = vimGlobalState.macroModeState;
      var lastChange = macroModeState.lastInsertModeChanges;
      var keyName = CodeMirror.keyName(e);
      if (!keyName) { return; }
      function onKeyFound() {
        if (lastChange.maybeReset) {
          lastChange.changes = [];
          lastChange.maybeReset = false;
        }
        lastChange.changes.push(new InsertModeKey(keyName));
        return true;
      }
      if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {
        CodeMirror.lookupKey(keyName, 'vim-insert', onKeyFound);
      }
    }

    /**
     * Repeats the last edit, which includes exactly 1 command and at most 1
     * insert. Operator and motion commands are read from lastEditInputState,
     * while action commands are read from lastEditActionCommand.
     *
     * If repeatForInsert is true, then the function was called by
     * exitInsertMode to repeat the insert mode changes the user just made. The
     * corresponding enterInsertMode call was made with a count.
     */
    function repeatLastEdit(cm, vim, repeat, repeatForInsert) {
      var macroModeState = vimGlobalState.macroModeState;
      macroModeState.isPlaying = true;
      var isAction = !!vim.lastEditActionCommand;
      var cachedInputState = vim.inputState;
      function repeatCommand() {
        if (isAction) {
          commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand);
        } else {
          commandDispatcher.evalInput(cm, vim);
        }
      }
      function repeatInsert(repeat) {
        if (macroModeState.lastInsertModeChanges.changes.length > 0) {
          // For some reason, repeat cw in desktop VIM does not repeat
          // insert mode changes. Will conform to that behavior.
          repeat = !vim.lastEditActionCommand ? 1 : repeat;
          var changeObject = macroModeState.lastInsertModeChanges;
          repeatInsertModeChanges(cm, changeObject.changes, repeat);
        }
      }
      vim.inputState = vim.lastEditInputState;
      if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) {
        // o and O repeat have to be interlaced with insert repeats so that the
        // insertions appear on separate lines instead of the last line.
        for (var i = 0; i < repeat; i++) {
          repeatCommand();
          repeatInsert(1);
        }
      } else {
        if (!repeatForInsert) {
          // Hack to get the cursor to end up at the right place. If I is
          // repeated in insert mode repeat, cursor will be 1 insert
          // change set left of where it should be.
          repeatCommand();
        }
        repeatInsert(repeat);
      }
      vim.inputState = cachedInputState;
      if (vim.insertMode && !repeatForInsert) {
        // Don't exit insert mode twice. If repeatForInsert is set, then we
        // were called by an exitInsertMode call lower on the stack.
        exitInsertMode(cm);
      }
      macroModeState.isPlaying = false;
    }

    function repeatInsertModeChanges(cm, changes, repeat) {
      function keyHandler(binding) {
        if (typeof binding == 'string') {
          CodeMirror.commands[binding](cm);
        } else {
          binding(cm);
        }
        return true;
      }
      var head = cm.getCursor('head');
      var inVisualBlock = vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock;
      if (inVisualBlock) {
        // Set up block selection again for repeating the changes.
        var vim = cm.state.vim;
        var lastSel = vim.lastSelection;
        var offset = getOffset(lastSel.anchor, lastSel.head);
        selectForInsert(cm, head, offset.line + 1);
        repeat = cm.listSelections().length;
        cm.setCursor(head);
      }
      for (var i = 0; i < repeat; i++) {
        if (inVisualBlock) {
          cm.setCursor(offsetCursor(head, i, 0));
        }
        for (var j = 0; j < changes.length; j++) {
          var change = changes[j];
          if (change instanceof InsertModeKey) {
            CodeMirror.lookupKey(change.keyName, 'vim-insert', keyHandler);
          } else if (typeof change == "string") {
            var cur = cm.getCursor();
            cm.replaceRange(change, cur, cur);
          } else {
            var start = cm.getCursor();
            var end = offsetCursor(start, 0, change[0].length);
            cm.replaceRange(change[0], start, end);
          }
        }
      }
      if (inVisualBlock) {
        cm.setCursor(offsetCursor(head, 0, 1));
      }
    }

    resetVimGlobalState();
    return vimApi;
  };
  // Initialize Vim and make it available as an API.
  CodeMirror.Vim = Vim();
});


/***/ }),

/***/ "diG1":
/*!*****************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeTimeSeriesIcon.js ***!
  \*****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeTimeSeriesIcon = function TraceTypeTimeSeriesIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement(
            'g',
            { fill: 'none' },
            _react2.default.createElement('path', { stroke: '#25fdfc', d: 'M7 6v31M23 6v31M15 6v34M31 6v34m8-34v31', strokeMiterlimit: '10', strokeWidth: '2' }),
            _react2.default.createElement('path', { d: 'M0 0h46v46H0z' }),
            _react2.default.createElement('path', { stroke: '#1d9bfb', d: 'M5.13 24.645L11 29l4-6.871 3.458 2.516L23 17.29l3.917 10.032L31 15.451 35.082 24l4.168-4.355 2.054-5.71', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2' }),
            _react2.default.createElement('path', { stroke: '#1d9bfb', d: 'M4 39h6m2 3h6m2-3h6m2 3h6m2-3h6', strokeLinejoin: 'round', strokeWidth: '2' })
        )
    );
};

exports.default = TraceTypeTimeSeriesIcon;

/***/ }),

/***/ "disn":
/*!***************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/apputils/style/spinner.css ***!
  \***************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) 2017, Jupyter Development Team.\n|\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.jp-Spinner {\n  position: absolute;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  z-index: 10;\n  left: 0;\n  top: 0;\n  width: 100%;\n  height: 100%;\n  background: var(--jp-layout-color0);\n  outline: none;\n}\n\n.jp-SpinnerContent {\n  font-size: 10px;\n  margin: 50px auto;\n  text-indent: -9999em;\n  width: 3em;\n  height: 3em;\n  border-radius: 50%;\n  background: var(--jp-brand-color3);\n  background: linear-gradient(\n    to right,\n    #f37626 10%,\n    rgba(255, 255, 255, 0) 42%\n  );\n  position: relative;\n  animation: load3 1s infinite linear, fadeIn 1s;\n}\n\n.jp-SpinnerContent:before {\n  width: 50%;\n  height: 50%;\n  background: #f37626;\n  border-radius: 100% 0 0 0;\n  position: absolute;\n  top: 0;\n  left: 0;\n  content: '';\n}\n\n.jp-SpinnerContent:after {\n  background: var(--jp-layout-color0);\n  width: 75%;\n  height: 75%;\n  border-radius: 50%;\n  content: '';\n  margin: auto;\n  position: absolute;\n  top: 0;\n  left: 0;\n  bottom: 0;\n  right: 0;\n}\n\n@keyframes fadeIn {\n  0% {\n    opacity: 0;\n  }\n  100% {\n    opacity: 1;\n  }\n}\n\n@keyframes load3 {\n  0% {\n    transform: rotate(0deg);\n  }\n  100% {\n    transform: rotate(360deg);\n  }\n}\n", ""]);

// exports


/***/ }),

/***/ "djTv":
/*!******************************************************!*\
  !*** ./node_modules/@phosphor/keyboard/lib/index.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * Get the global application keyboard layout instance.
 *
 * @returns The keyboard layout for use by the application.
 *
 * #### Notes
 * The default keyboard layout is US-English.
 */
function getKeyboardLayout() {
    return Private.keyboardLayout;
}
exports.getKeyboardLayout = getKeyboardLayout;
/**
 * Set the global application keyboard layout instance.
 *
 * @param - The keyboard layout for use by the application.
 *
 * #### Notes
 * The keyboard layout should typically be set on application startup
 * to a layout which is appropriate for the user's system.
 */
function setKeyboardLayout(layout) {
    Private.keyboardLayout = layout;
}
exports.setKeyboardLayout = setKeyboardLayout;
/**
 * A concrete implementation of [[IKeyboardLayout]] based on keycodes.
 *
 * The `keyCode` property of a `'keydown'` event is a browser and OS
 * specific representation of the physical key (not character) which
 * was pressed on a keyboard. While not the most convenient API, it
 * is currently the only one which works reliably on all browsers.
 *
 * This class accepts a user-defined mapping of keycode to key, which
 * allows for reliable shortcuts tailored to the user's system.
 */
var KeycodeLayout = (function () {
    /**
     * Construct a new keycode layout.
     *
     * @param name - The human readable name for the layout.
     *
     * @param codes - A mapping of keycode to key value.
     */
    function KeycodeLayout(name, codes) {
        this.name = name;
        this._codes = codes;
        this._keys = KeycodeLayout.extractKeys(codes);
    }
    /**
     * Get an array of the key values supported by the layout.
     *
     * @returns A new array of the supported key values.
     */
    KeycodeLayout.prototype.keys = function () {
        return Object.keys(this._keys);
    };
    /**
     * Test whether the given key is a valid value for the layout.
     *
     * @param key - The user provided key to test for validity.
     *
     * @returns `true` if the key is valid, `false` otherwise.
     */
    KeycodeLayout.prototype.isValidKey = function (key) {
        return key in this._keys;
    };
    /**
     * Get the key for a `'keydown'` event.
     *
     * @param event - The event object for a `'keydown'` event.
     *
     * @returns The associated key value, or an empty string if
     *   the event does not represent a valid primary key.
     */
    KeycodeLayout.prototype.keyForKeydownEvent = function (event) {
        return this._codes[event.keyCode] || '';
    };
    return KeycodeLayout;
}());
exports.KeycodeLayout = KeycodeLayout;
/**
 * The namespace for the `KeycodeLayout` class statics.
 */
(function (KeycodeLayout) {
    /**
     * Extract the set of keys from a code map.
     *
     * @param code - The code map of interest.
     *
     * @returns A set of the keys in the code map.
     */
    function extractKeys(codes) {
        var keys = Object.create(null);
        for (var c in codes) {
            keys[codes[c]] = true;
        }
        return keys;
    }
    KeycodeLayout.extractKeys = extractKeys;
})(KeycodeLayout = exports.KeycodeLayout || (exports.KeycodeLayout = {}));
exports.KeycodeLayout = KeycodeLayout;
/**
 * A keycode-based keyboard layout for US English keyboards.
 *
 * This layout is valid for the following OS/Browser combinations.
 *
 * - Windows
 *   - Chrome
 *   - Firefox
 *   - IE
 *
 * - OSX
 *   - Chrome
 *   - Firefox
 *   - Safari
 *
 * - Linux
 *   - Chrome
 *   - Firefox
 *
 * Other combinations may also work, but are untested.
 */
exports.EN_US = new KeycodeLayout('en-us', {
    8: 'Backspace',
    9: 'Tab',
    13: 'Enter',
    19: 'Pause',
    27: 'Escape',
    32: 'Space',
    33: 'PageUp',
    34: 'PageDown',
    35: 'End',
    36: 'Home',
    37: 'ArrowLeft',
    38: 'ArrowUp',
    39: 'ArrowRight',
    40: 'ArrowDown',
    45: 'Insert',
    46: 'Delete',
    48: '0',
    49: '1',
    50: '2',
    51: '3',
    52: '4',
    53: '5',
    54: '6',
    55: '7',
    56: '8',
    57: '9',
    59: ';',
    61: '=',
    65: 'A',
    66: 'B',
    67: 'C',
    68: 'D',
    69: 'E',
    70: 'F',
    71: 'G',
    72: 'H',
    73: 'I',
    74: 'J',
    75: 'K',
    76: 'L',
    77: 'M',
    78: 'N',
    79: 'O',
    80: 'P',
    81: 'Q',
    82: 'R',
    83: 'S',
    84: 'T',
    85: 'U',
    86: 'V',
    87: 'W',
    88: 'X',
    89: 'Y',
    90: 'Z',
    93: 'ContextMenu',
    96: '0',
    97: '1',
    98: '2',
    99: '3',
    100: '4',
    101: '5',
    102: '6',
    103: '7',
    104: '8',
    105: '9',
    106: '*',
    107: '+',
    109: '-',
    110: '.',
    111: '/',
    112: 'F1',
    113: 'F2',
    114: 'F3',
    115: 'F4',
    116: 'F5',
    117: 'F6',
    118: 'F7',
    119: 'F8',
    120: 'F9',
    121: 'F10',
    122: 'F11',
    123: 'F12',
    173: '-',
    186: ';',
    187: '=',
    188: ',',
    189: '-',
    190: '.',
    191: '/',
    192: '`',
    219: '[',
    220: '\\',
    221: ']',
    222: '\''
});
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * The global keyboard layout instance.
     */
    Private.keyboardLayout = exports.EN_US;
})(Private || (Private = {}));


/***/ }),

/***/ "djUo":
/*!****************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/SingleSidebarItem.js ***!
  \****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var SingleSidebarItem = function (_Component) {
  _inherits(SingleSidebarItem, _Component);

  function SingleSidebarItem() {
    _classCallCheck(this, SingleSidebarItem);

    return _possibleConstructorReturn(this, (SingleSidebarItem.__proto__ || Object.getPrototypeOf(SingleSidebarItem)).apply(this, arguments));
  }

  _createClass(SingleSidebarItem, [{
    key: 'render',
    value: function render() {
      return this.props.children ? _react2.default.createElement(
        'div',
        { className: 'sidebar__item--single' },
        this.props.children
      ) : null;
    }
  }]);

  return SingleSidebarItem;
}(_react.Component);

exports.default = SingleSidebarItem;


SingleSidebarItem.plotly_editor_traits = { sidebar_element: true };

SingleSidebarItem.propTypes = {
  children: _propTypes2.default.any
};
//# sourceMappingURL=SingleSidebarItem.js.map

/***/ }),

/***/ "dl0q":
/*!***********************************************************************!*\
  !*** ./node_modules/core-js/library/modules/es7.symbol.observable.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(/*! ./_wks-define */ "Zxgi")('observable');


/***/ }),

/***/ "dlgc":
/*!*************************************************************!*\
  !*** ./node_modules/minimalistic-crypto-utils/lib/utils.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var utils = exports;

function toArray(msg, enc) {
  if (Array.isArray(msg))
    return msg.slice();
  if (!msg)
    return [];
  var res = [];
  if (typeof msg !== 'string') {
    for (var i = 0; i < msg.length; i++)
      res[i] = msg[i] | 0;
    return res;
  }
  if (enc === 'hex') {
    msg = msg.replace(/[^a-z0-9]+/ig, '');
    if (msg.length % 2 !== 0)
      msg = '0' + msg;
    for (var i = 0; i < msg.length; i += 2)
      res.push(parseInt(msg[i] + msg[i + 1], 16));
  } else {
    for (var i = 0; i < msg.length; i++) {
      var c = msg.charCodeAt(i);
      var hi = c >> 8;
      var lo = c & 0xff;
      if (hi)
        res.push(hi, lo);
      else
        res.push(lo);
    }
  }
  return res;
}
utils.toArray = toArray;

function zero2(word) {
  if (word.length === 1)
    return '0' + word;
  else
    return word;
}
utils.zero2 = zero2;

function toHex(msg) {
  var res = '';
  for (var i = 0; i < msg.length; i++)
    res += zero2(msg[i].toString(16));
  return res;
}
utils.toHex = toHex;

utils.encode = function encode(arr, enc) {
  if (enc === 'hex')
    return toHex(arr);
  else
    return arr;
};


/***/ }),

/***/ "dn6z":
/*!****************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/codemirror/theme/abcdef.css ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, ".cm-s-abcdef.CodeMirror { background: #0f0f0f; color: #defdef; }\n.cm-s-abcdef div.CodeMirror-selected { background: #515151; }\n.cm-s-abcdef .CodeMirror-line::selection, .cm-s-abcdef .CodeMirror-line > span::selection, .cm-s-abcdef .CodeMirror-line > span > span::selection { background: rgba(56, 56, 56, 0.99); }\n.cm-s-abcdef .CodeMirror-line::-moz-selection, .cm-s-abcdef .CodeMirror-line > span::-moz-selection, .cm-s-abcdef .CodeMirror-line > span > span::-moz-selection { background: rgba(56, 56, 56, 0.99); }\n.cm-s-abcdef .CodeMirror-gutters { background: #555; border-right: 2px solid #314151; }\n.cm-s-abcdef .CodeMirror-guttermarker { color: #222; }\n.cm-s-abcdef .CodeMirror-guttermarker-subtle { color: azure; }\n.cm-s-abcdef .CodeMirror-linenumber { color: #FFFFFF; }\n.cm-s-abcdef .CodeMirror-cursor { border-left: 1px solid #00FF00; }\n\n.cm-s-abcdef span.cm-keyword { color: darkgoldenrod; font-weight: bold; }\n.cm-s-abcdef span.cm-atom { color: #77F; }\n.cm-s-abcdef span.cm-number { color: violet; }\n.cm-s-abcdef span.cm-def { color: #fffabc; }\n.cm-s-abcdef span.cm-variable { color: #abcdef; }\n.cm-s-abcdef span.cm-variable-2 { color: #cacbcc; }\n.cm-s-abcdef span.cm-variable-3, .cm-s-abcdef span.cm-type { color: #def; }\n.cm-s-abcdef span.cm-property { color: #fedcba; }\n.cm-s-abcdef span.cm-operator { color: #ff0; }\n.cm-s-abcdef span.cm-comment { color: #7a7b7c; font-style: italic;}\n.cm-s-abcdef span.cm-string { color: #2b4; }\n.cm-s-abcdef span.cm-meta { color: #C9F; }\n.cm-s-abcdef span.cm-qualifier { color: #FFF700; }\n.cm-s-abcdef span.cm-builtin { color: #30aabc; }\n.cm-s-abcdef span.cm-bracket { color: #8a8a8a; }\n.cm-s-abcdef span.cm-tag { color: #FFDD44; }\n.cm-s-abcdef span.cm-attribute { color: #DDFF00; }\n.cm-s-abcdef span.cm-error { color: #FF0000; }\n.cm-s-abcdef span.cm-header { color: aquamarine; font-weight: bold; }\n.cm-s-abcdef span.cm-link { color: blueviolet; }\n\n.cm-s-abcdef .CodeMirror-activeline-background { background: #314151; }\n", ""]);

// exports


/***/ }),

/***/ "dnhB":
/*!*********************************************!*\
  !*** ./node_modules/mdi-react/EarthIcon.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var EarthIcon = function EarthIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M17.9,17.39C17.64,16.59 16.89,16 16,16H15V13C15,12.45 14.55,12 14,12H8V10H10C10.55,10 11,9.55 11,9V7H13C14.1,7 15,6.1 15,5V4.59C17.93,5.77 20,8.64 20,12C20,14.08 19.2,15.97 17.9,17.39M11,19.93C7.05,19.44 4,16.08 4,12C4,11.38 4.08,10.78 4.21,10.21L9,15V16C9,17.1 9.9,18 11,18M12,2C6.48,2 2,6.48 2,12C2,17.52 6.48,22 12,22C17.52,22 22,17.52 22,12C22,6.48 17.52,2 12,2Z' })
  );
};

module.exports = EarthIcon;


/***/ }),

/***/ "dnr1":
/*!****************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/extend.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




var isPlainObject = __webpack_require__(/*! ./is_plain_object.js */ "SWc2");
var isArray = Array.isArray;

function primitivesLoopSplice(source, target) {
    var i, value;
    for(i = 0; i < source.length; i++) {
        value = source[i];
        if(value !== null && typeof(value) === 'object') {
            return false;
        }
        if(value !== void(0)) {
            target[i] = value;
        }
    }
    return true;
}

exports.extendFlat = function() {
    return _extend(arguments, false, false, false);
};

exports.extendDeep = function() {
    return _extend(arguments, true, false, false);
};

exports.extendDeepAll = function() {
    return _extend(arguments, true, true, false);
};

exports.extendDeepNoArrays = function() {
    return _extend(arguments, true, false, true);
};

/*
 * Inspired by https://github.com/justmoon/node-extend/blob/master/index.js
 * All credit to the jQuery authors for perfecting this amazing utility.
 *
 * API difference with jQuery version:
 * - No optional boolean (true -> deep extend) first argument,
 *   use `extendFlat` for first-level only extend and
 *   use `extendDeep` for a deep extend.
 *
 * Other differences with jQuery version:
 * - Uses a modern (and faster) isPlainObject routine.
 * - Expected to work with object {} and array [] arguments only.
 * - Does not check for circular structure.
 *   FYI: jQuery only does a check across one level.
 *   Warning: this might result in infinite loops.
 *
 */
function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) {
    var target = inputs[0];
    var length = inputs.length;

    var input, key, src, copy, copyIsArray, clone, allPrimitives;

    // TODO does this do the right thing for typed arrays?

    if(length === 2 && isArray(target) && isArray(inputs[1]) && target.length === 0) {

        allPrimitives = primitivesLoopSplice(inputs[1], target);

        if(allPrimitives) {
            return target;
        } else {
            target.splice(0, target.length); // reset target and continue to next block
        }
    }

    for(var i = 1; i < length; i++) {
        input = inputs[i];

        for(key in input) {
            src = target[key];
            copy = input[key];

            // Stop early and just transfer the array if array copies are disallowed:
            if(noArrayCopies && isArray(copy)) {
                target[key] = copy;
            }

            // recurse if we're merging plain objects or arrays
            else if(isDeep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
                if(copyIsArray) {
                    copyIsArray = false;
                    clone = src && isArray(src) ? src : [];
                } else {
                    clone = src && isPlainObject(src) ? src : {};
                }

                // never move original objects, clone them
                target[key] = _extend([clone, copy], isDeep, keepAllKeys, noArrayCopies);
            }

            // don't bring in undefined values, except for extendDeepAll
            else if(typeof copy !== 'undefined' || keepAllKeys) {
                target[key] = copy;
            }
        }
    }

    return target;
}


/***/ }),

/***/ "dsut":
/*!***************************************!*\
  !*** ./node_modules/jsonify/index.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports.parse = __webpack_require__(/*! ./lib/parse */ "RGXH");
exports.stringify = __webpack_require__(/*! ./lib/stringify */ "uPSP");


/***/ }),

/***/ "dt0z":
/*!*****************************************!*\
  !*** ./node_modules/lodash/toString.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseToString = __webpack_require__(/*! ./_baseToString */ "zoYe");

/**
 * 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);
}

module.exports = toString;


/***/ }),

/***/ "dv5i":
/*!*******************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/DataSelector.js ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UnconnectedDataSelector = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

exports.attributeIsData = attributeIsData;

var _Dropdown = __webpack_require__(/*! ../widgets/Dropdown */ "9Rtb");

var _Dropdown2 = _interopRequireDefault(_Dropdown);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _nested_property = __webpack_require__(/*! plotly.js/src/lib/nested_property */ "dNZO");

var _nested_property2 = _interopRequireDefault(_nested_property);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _constants = __webpack_require__(/*! ../../lib/constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function attributeIsData() {
  var meta = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

  return meta.valType === 'data_array' || meta.arrayOk;
}

var UnconnectedDataSelector = exports.UnconnectedDataSelector = function (_Component) {
  _inherits(UnconnectedDataSelector, _Component);

  function UnconnectedDataSelector(props, context) {
    _classCallCheck(this, UnconnectedDataSelector);

    var _this = _possibleConstructorReturn(this, (UnconnectedDataSelector.__proto__ || Object.getPrototypeOf(UnconnectedDataSelector)).call(this, props, context));

    _this.updatePlot = _this.updatePlot.bind(_this);
    _this.setLocals(props, context);
    return _this;
  }

  _createClass(UnconnectedDataSelector, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps, nextContext) {
      this.setLocals(nextProps, nextContext);
    }
  }, {
    key: 'setLocals',
    value: function setLocals(props, context) {
      this.dataSources = context.dataSources || {};
      this.dataSourceOptions = context.dataSourceOptions || [];

      this.srcAttr = props.attr + 'src';
      this.srcProperty = (0, _nested_property2.default)(props.container, this.srcAttr).get();
      this.fullValue = this.context.srcConverters ? this.context.srcConverters.toSrc(this.srcProperty, props.container.type) : this.srcProperty;

      this.is2D = false;
      if (props.container) {
        this.is2D = (props.attr === 'x' || props.attr === 'y') && ['scatter', 'scattergl', 'bar', 'heatmap', 'heatmapgl', 'violin', 'box', 'contour', 'contourgl'].includes(props.container.type) || props.attr === 'z' && ['contour', 'contourgl', 'heatmap', 'heatmapgl', 'surface', 'carpet', 'contourcarpet'].includes(props.container.type) || props.container.type === 'table' && props.attr !== 'columnorder' || Array.isArray(this.fullValue);
      }

      this.hasData = props.container ? props.attr in props.container : false;
    }
  }, {
    key: 'updatePlot',
    value: function updatePlot(value) {
      var _this2 = this;

      if (!this.props.updateContainer) {
        return;
      }

      var update = {};
      var data = void 0;

      var adjustedValue = Array.isArray(value) && value.length === 1 && (this.props.attr === 'x' || this.props.attr === 'y') ? value[0] : value;

      if (Array.isArray(adjustedValue)) {
        data = adjustedValue.filter(function (v) {
          return Array.isArray(_this2.dataSources[v]);
        }).map(function (v) {
          return _this2.dataSources[v];
        });
      } else {
        data = this.dataSources[adjustedValue] || null;
      }

      update[this.props.attr] = (0, _lib.maybeTransposeData)(data, this.srcAttr, this.props.container.type);
      update[this.srcAttr] = (0, _lib.maybeAdjustSrc)(adjustedValue, this.srcAttr, this.props.container.type, {
        fromSrc: this.context.srcConverters ? this.context.srcConverters.fromSrc : null
      });

      this.props.updateContainer(update);
    }
  }, {
    key: 'render',
    value: function render() {
      var label = this.props.label;

      var newLabel = void 0;
      if ((typeof label === 'undefined' ? 'undefined' : _typeof(label)) === 'object') {
        var traceType = this.props.container.type;
        if (label[traceType]) {
          newLabel = label[traceType];
        } else {
          newLabel = label['*'];
        }
      } else {
        newLabel = label;
      }

      return _react2.default.createElement(
        _Field2.default,
        _extends({}, this.props, { label: newLabel }),
        _react2.default.createElement(_Dropdown2.default, {
          options: this.dataSourceOptions,
          value: this.fullValue,
          onChange: this.updatePlot,
          multi: this.is2D,
          searchable: true,
          optionRenderer: this.context.dataSourceOptionRenderer,
          valueRenderer: this.context.dataSourceValueRenderer,
          clearable: true,
          placeholder: this.hasData ? 'Data inlined in figure' : 'Choose data...',
          disabled: this.dataSourceOptions.length === 0
        })
      );
    }
  }]);

  return UnconnectedDataSelector;
}(_react.Component);

UnconnectedDataSelector.propTypes = _extends({
  fullValue: _propTypes2.default.any,
  updatePlot: _propTypes2.default.func,
  container: _propTypes2.default.object
}, _Field2.default.propTypes);

UnconnectedDataSelector.contextTypes = {
  dataSources: _propTypes2.default.object,
  dataSourceOptions: _propTypes2.default.array,
  dataSourceValueRenderer: _propTypes2.default.func,
  dataSourceOptionRenderer: _propTypes2.default.func,
  srcConverters: _propTypes2.default.shape({
    toSrc: _propTypes2.default.func.isRequired,
    fromSrc: _propTypes2.default.func.isRequired
  }),
  container: _propTypes2.default.object
};

function modifyPlotProps(props, context, plotProps) {
  if (attributeIsData(plotProps.attrMeta) && context.container && _constants.TRANSFORMS_LIST.indexOf(context.container.type) === -1) {
    plotProps.isVisible = true;
  }
}

exports.default = (0, _lib.connectToContainer)(UnconnectedDataSelector, { modifyPlotProps: modifyPlotProps });
//# sourceMappingURL=DataSelector.js.map

/***/ }),

/***/ "dwfJ":
/*!******************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/pdf-extension/style/index.css ***!
  \******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.jp-Notebook .jp-Cell .jp-OutputArea .jp-PDFViewer {\n  min-height: 500px;\n}\n\n/*\nWhen drag events occur, `p-mod-override-cursor` is added to the body.\nThis reuses the same CSS selector logic as jp-IFrame to prevent embedded\nPDFs from swallowing cursor events.\n*/\nbody.p-mod-override-cursor .jp-PDFContainer {\n  position: relative;\n}\n\nbody.p-mod-override-cursor .jp-PDFContainer:before {\n  content: '';\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background: transparent;\n}\n\n.jp-PDFViewer {\n  width: 100%;\n  height: 100%;\n}\n", ""]);

// exports


/***/ }),

/***/ "dyxW":
/*!*****************************************************!*\
  !*** ./node_modules/draft-js/lib/DraftStringKey.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DraftStringKey
 * @format
 * 
 */



var DraftStringKey = {
  stringify: function stringify(key) {
    return '_' + String(key);
  },

  unstringify: function unstringify(key) {
    return key.slice(1);
  }
};

module.exports = DraftStringKey;

/***/ }),

/***/ "e+ae":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/sk.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var months = 'január_február_marec_apríl_máj_jún_júl_august_september_október_november_december'.split('_'),
    monthsShort = 'jan_feb_mar_apr_máj_jún_júl_aug_sep_okt_nov_dec'.split('_');
function plural(n) {
    return (n > 1) && (n < 5);
}
function translate(number, withoutSuffix, key, isFuture) {
    var result = number + ' ';
    switch (key) {
        case 's':  // a few seconds / in a few seconds / a few seconds ago
            return (withoutSuffix || isFuture) ? 'pár sekúnd' : 'pár sekundami';
        case 'ss': // 9 seconds / in 9 seconds / 9 seconds ago
            if (withoutSuffix || isFuture) {
                return result + (plural(number) ? 'sekundy' : 'sekúnd');
            } else {
                return result + 'sekundami';
            }
            break;
        case 'm':  // a minute / in a minute / a minute ago
            return withoutSuffix ? 'minúta' : (isFuture ? 'minútu' : 'minútou');
        case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago
            if (withoutSuffix || isFuture) {
                return result + (plural(number) ? 'minúty' : 'minút');
            } else {
                return result + 'minútami';
            }
            break;
        case 'h':  // an hour / in an hour / an hour ago
            return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou');
        case 'hh': // 9 hours / in 9 hours / 9 hours ago
            if (withoutSuffix || isFuture) {
                return result + (plural(number) ? 'hodiny' : 'hodín');
            } else {
                return result + 'hodinami';
            }
            break;
        case 'd':  // a day / in a day / a day ago
            return (withoutSuffix || isFuture) ? 'deň' : 'dňom';
        case 'dd': // 9 days / in 9 days / 9 days ago
            if (withoutSuffix || isFuture) {
                return result + (plural(number) ? 'dni' : 'dní');
            } else {
                return result + 'dňami';
            }
            break;
        case 'M':  // a month / in a month / a month ago
            return (withoutSuffix || isFuture) ? 'mesiac' : 'mesiacom';
        case 'MM': // 9 months / in 9 months / 9 months ago
            if (withoutSuffix || isFuture) {
                return result + (plural(number) ? 'mesiace' : 'mesiacov');
            } else {
                return result + 'mesiacmi';
            }
            break;
        case 'y':  // a year / in a year / a year ago
            return (withoutSuffix || isFuture) ? 'rok' : 'rokom';
        case 'yy': // 9 years / in 9 years / 9 years ago
            if (withoutSuffix || isFuture) {
                return result + (plural(number) ? 'roky' : 'rokov');
            } else {
                return result + 'rokmi';
            }
            break;
    }
}

var sk = moment.defineLocale('sk', {
    months : months,
    monthsShort : monthsShort,
    weekdays : 'nedeľa_pondelok_utorok_streda_štvrtok_piatok_sobota'.split('_'),
    weekdaysShort : 'ne_po_ut_st_št_pi_so'.split('_'),
    weekdaysMin : 'ne_po_ut_st_št_pi_so'.split('_'),
    longDateFormat : {
        LT: 'H:mm',
        LTS : 'H:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D. MMMM YYYY',
        LLL : 'D. MMMM YYYY H:mm',
        LLLL : 'dddd D. MMMM YYYY H:mm'
    },
    calendar : {
        sameDay: '[dnes o] LT',
        nextDay: '[zajtra o] LT',
        nextWeek: function () {
            switch (this.day()) {
                case 0:
                    return '[v nedeľu o] LT';
                case 1:
                case 2:
                    return '[v] dddd [o] LT';
                case 3:
                    return '[v stredu o] LT';
                case 4:
                    return '[vo štvrtok o] LT';
                case 5:
                    return '[v piatok o] LT';
                case 6:
                    return '[v sobotu o] LT';
            }
        },
        lastDay: '[včera o] LT',
        lastWeek: function () {
            switch (this.day()) {
                case 0:
                    return '[minulú nedeľu o] LT';
                case 1:
                case 2:
                    return '[minulý] dddd [o] LT';
                case 3:
                    return '[minulú stredu o] LT';
                case 4:
                case 5:
                    return '[minulý] dddd [o] LT';
                case 6:
                    return '[minulú sobotu o] LT';
            }
        },
        sameElse: 'L'
    },
    relativeTime : {
        future : 'za %s',
        past : 'pred %s',
        s : translate,
        ss : translate,
        m : translate,
        mm : translate,
        h : translate,
        hh : translate,
        d : translate,
        dd : translate,
        M : translate,
        MM : translate,
        y : translate,
        yy : translate
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return sk;

})));


/***/ }),

/***/ "e/Ok":
/*!************************************************!*\
  !*** ./node_modules/draft-js/lib/editOnCut.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule editOnCut
 * @format
 * 
 */



var DraftModifier = __webpack_require__(/*! ./DraftModifier */ "fyOY");
var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");
var Style = __webpack_require__(/*! fbjs/lib/Style */ "6Xrj");

var getFragmentFromSelection = __webpack_require__(/*! ./getFragmentFromSelection */ "hyAj");
var getScrollPosition = __webpack_require__(/*! fbjs/lib/getScrollPosition */ "DeIs");

/**
 * On `cut` events, native behavior is allowed to occur so that the system
 * clipboard is set properly. This means that we need to take steps to recover
 * the editor DOM state after the `cut` has occurred in order to maintain
 * control of the component.
 *
 * In addition, we can keep a copy of the removed fragment, including all
 * styles and entities, for use as an internal paste.
 */
function editOnCut(editor, e) {
  var editorState = editor._latestEditorState;
  var selection = editorState.getSelection();
  var element = e.target;
  var scrollPosition = void 0;

  // No selection, so there's nothing to cut.
  if (selection.isCollapsed()) {
    e.preventDefault();
    return;
  }

  // Track the current scroll position so that it can be forced back in place
  // after the editor regains control of the DOM.
  if (element instanceof Node) {
    scrollPosition = getScrollPosition(Style.getScrollParent(element));
  }

  var fragment = getFragmentFromSelection(editorState);
  editor.setClipboard(fragment);

  // Set `cut` mode to disable all event handling temporarily.
  editor.setMode('cut');

  // Let native `cut` behavior occur, then recover control.
  setTimeout(function () {
    editor.restoreEditorDOM(scrollPosition);
    editor.exitCurrentMode();
    editor.update(removeFragment(editorState));
  }, 0);
}

function removeFragment(editorState) {
  var newContent = DraftModifier.removeRange(editorState.getCurrentContent(), editorState.getSelection(), 'forward');
  return EditorState.push(editorState, newContent, 'remove-range');
}

module.exports = editOnCut;

/***/ }),

/***/ "e0n3":
/*!************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/ModalProvider.js ***!
  \************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var ModalProvider = function (_React$Component) {
  _inherits(ModalProvider, _React$Component);

  function ModalProvider(props) {
    _classCallCheck(this, ModalProvider);

    var _this = _possibleConstructorReturn(this, (ModalProvider.__proto__ || Object.getPrototypeOf(ModalProvider)).call(this, props));

    _this.state = {
      component: null,
      componentProps: {},
      open: false,
      isAnimatingOut: false
    };
    return _this;
  }

  _createClass(ModalProvider, [{
    key: 'componentDidUpdate',
    value: function componentDidUpdate() {
      var body = document.body;
      var open = this.state.open;

      // Toggle scroll on document body if modal is open

      var hasClass = body.classList.contains('no-scroll');

      if (open && !hasClass) {
        body.classList.add('no-scroll');
      }
      if (!open && hasClass) {
        body.classList.remove('no-scroll');
      }
    }
  }, {
    key: 'openModal',
    value: function openModal(component, componentProps) {
      var _ = this.context.localize;

      if (!component) {
        throw Error(_('You need to provide a component for the modal to open!'));
      }
      var open = this.state.open;


      if (!open) {
        this.setState({
          component: component,
          componentProps: componentProps,
          open: true
        });
      }
    }
  }, {
    key: 'closeModal',
    value: function closeModal() {
      var open = this.state.open;

      if (open) {
        this.setState({
          open: false,
          component: null
        });
      }
    }
  }, {
    key: 'handleClose',
    value: function handleClose() {
      var _this2 = this;

      this.setState({ isAnimatingOut: true });
      var animationDuration = 600;
      setTimeout(function () {
        _this2.setState({ isAnimatingOut: false });
        _this2.closeModal();
      }, animationDuration);
    }
  }, {
    key: 'getChildContext',
    value: function getChildContext() {
      var _this3 = this;

      return {
        openModal: function openModal(c, p) {
          return _this3.openModal(c, p);
        },
        closeModal: function closeModal() {
          return _this3.closeModal();
        },
        handleClose: function handleClose() {
          return _this3.handleClose();
        },
        isAnimatingOut: this.state.isAnimatingOut
      };
    }
  }, {
    key: 'render',
    value: function render() {
      var _state = this.state,
          Component = _state.component,
          componentProps = _state.componentProps,
          isAnimatingOut = _state.isAnimatingOut;

      return _react2.default.createElement(
        _react.Fragment,
        null,
        this.props.children,
        this.state.open ? _react2.default.createElement(Component, _extends({ isAnimatingOut: isAnimatingOut }, componentProps)) : null
      );
    }
  }]);

  return ModalProvider;
}(_react2.default.Component);

ModalProvider.propTypes = {
  children: _propTypes2.default.node
};
ModalProvider.contextTypes = {
  localize: _propTypes2.default.func
};
ModalProvider.childContextTypes = {
  openModal: _propTypes2.default.func,
  closeModal: _propTypes2.default.func,
  handleClose: _propTypes2.default.func,
  isAnimatingOut: _propTypes2.default.bool
};

exports.default = ModalProvider;
//# sourceMappingURL=ModalProvider.js.map

/***/ }),

/***/ "e2yc":
/*!************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotStreamtubeIcon.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotStreamtubeIcon = function PlotStreamtubeIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 1360 1360' }, props),
        _react2.default.createElement('path', { fill: 'currentColor', d: 'M855.254 790.532l-37.135-16.591c-.04-.019-.081-.03-.121-.046-.055-.021-.107-.043-.162-.061-.057-.018-.113-.031-.17-.045a3.018 3.018 0 0 0-.158-.038 2.195 2.195 0 0 0-.179-.024c-.052-.007-.104-.014-.157-.018-.061-.004-.121-.003-.181-.003-.053.001-.104 0-.157.003-.061.004-.119.012-.18.02-.053.007-.104.012-.156.021-.059.012-.117.027-.177.042-.052.013-.103.025-.153.041-.058.019-.113.041-.17.063-.039.016-.078.026-.117.044l-37.135 16.591a2.743 2.743 0 0 0-1.624 2.505v42.066c0 1.063.613 2.029 1.573 2.481l37.135 17.506a3.225 3.225 0 0 0 .544.19l.049.012a2.616 2.616 0 0 0 .32.049c.083.008.166.013.25.014h.016a2.968 2.968 0 0 0 .568-.063c.018-.003.034-.009.052-.013.072-.017.145-.037.216-.061.02-.006.04-.012.06-.02.084-.029.166-.063.246-.1l.02-.008 37.135-17.506a2.74 2.74 0 0 0 1.573-2.481v-42.066a2.747 2.747 0 0 0-1.625-2.504zm-3.863 40.299l-13.438-6.225c-2.421.948-4.859 1.151-6.923 1.151a36.83 36.83 0 0 1-1.673-.041 5.964 5.964 0 0 0-1.711.163l19.984 9.257-30.63 14.44-30.631-14.439 10.344-4.791a6.421 6.421 0 0 1-1.898-2.356 6.434 6.434 0 0 1-.598-2.535l-11.607 5.377v-36.015l31.647-14.14v15.256l.118.003c2.863 0 4.104-.491 5.369-3.279v-11.979l31.646 14.14v36.013z' }),
        _react2.default.createElement('path', { fill: 'currentColor', d: 'M792.381 818.253a2.47 2.47 0 0 1-1.054-4.702c.047-.022 4.723-2.294 9.344-8.231.714-1.17 4.561-6.783 12.392-6.417 4.753.222 7.546-.564 9.62-5.472a2.467 2.467 0 0 1 3.235-1.313 2.47 2.47 0 0 1 1.313 3.235c-3.335 7.889-8.891 8.738-14.399 8.482-5.511-.258-7.93 4.023-7.954 4.066-.061.11-.131.217-.207.318-5.436 7.04-11.014 9.692-11.248 9.802a2.446 2.446 0 0 1-1.042.232zM800.68 827.728a2.468 2.468 0 0 1-1.052-4.703c.092-.044 4.744-2.321 9.343-8.232.715-1.168 4.567-6.781 12.392-6.415 4.754.222 7.547-.565 9.621-5.473a2.469 2.469 0 0 1 4.547 1.921c-3.334 7.891-8.891 8.741-14.397 8.483-5.509-.253-7.931 4.022-7.954 4.066a2.562 2.562 0 0 1-.209.318c-5.434 7.04-11.013 9.693-11.247 9.802a2.483 2.483 0 0 1-1.044.233zM809.045 837.138a2.469 2.469 0 0 1-1.053-4.701c.067-.033 4.731-2.308 9.343-8.234.715-1.168 4.564-6.784 12.393-6.416 4.753.223 7.545-.564 9.62-5.471a2.466 2.466 0 0 1 3.235-1.313 2.467 2.467 0 0 1 1.313 3.233c-3.334 7.891-8.891 8.741-14.398 8.484-5.51-.254-7.931 4.022-7.954 4.066a2.79 2.79 0 0 1-.208.317c-5.434 7.041-11.013 9.694-11.247 9.804-.34.156-.694.231-1.044.231z' }),
        _react2.default.createElement('path', { fill: 'currentColor', d: 'M1066.344 423.203l-376.77-168.33c-.406-.188-.822-.308-1.229-.466-.555-.208-1.09-.437-1.645-.615a27.59 27.59 0 0 0-1.725-.456 31.707 31.707 0 0 0-1.605-.387 27.974 27.974 0 0 0-1.813-.247c-.525-.07-1.06-.139-1.594-.179-.615-.04-1.229-.03-1.834-.03-.534.01-1.061 0-1.595.03-.615.04-1.209.119-1.822.198-.536.07-1.062.119-1.587.219-.594.119-1.188.277-1.794.425a28.1 28.1 0 0 0-1.556.417c-.584.188-1.148.416-1.724.644-.396.159-.792.268-1.188.446l-376.77 168.33a27.832 27.832 0 0 0-16.478 25.415v426.806a27.833 27.833 0 0 0 15.961 25.178l376.771 177.615c.06.029.12.047.179.068.832.385 1.665.723 2.536 1.029.189.07.387.129.574.189.735.238 1.467.447 2.221.625.158.039.337.09.494.119.834.178 1.676.316 2.518.414a30.561 30.561 0 0 0 3.269.219h.168a30.488 30.488 0 0 0 3.27-.219 29.164 29.164 0 0 0 2.498-.414c.178-.029.346-.09.523-.129a24.45 24.45 0 0 0 2.191-.615c.197-.061.406-.119.604-.197a28.35 28.35 0 0 0 2.498-1.012c.068-.031.139-.049.197-.078l376.77-177.615a27.816 27.816 0 0 0 15.962-25.178V448.618a27.83 27.83 0 0 0-16.475-25.415zm-39.198 408.873L890.811 768.92c-24.563 9.621-49.303 11.682-70.24 11.682-5.359 0-10.928-.139-16.973-.416a64.196 64.196 0 0 0-3.348-.08c-5.143 0-9.711.734-14.012 1.734l202.764 93.922-310.783 146.502-310.781-146.502 104.948-48.611c-8.075-6.281-14.803-14.326-19.261-23.908a65.195 65.195 0 0 1-6.065-25.721l-117.77 54.555V466.671L650.387 323.21v154.787c.388 0 .813.029 1.199.029 29.051 0 41.644-4.984 54.476-33.271V323.209l321.084 143.461v365.406z' }),
        _react2.default.createElement('path', { fill: 'currentColor', d: 'M428.433 704.459c-9.443 0-18.468-5.352-22.729-14.457-5.827-12.514-.437-27.376 12.028-33.252.476-.228 47.916-23.274 94.801-83.516 7.245-11.87 46.272-68.822 125.728-65.106 48.222 2.249 76.562-5.728 97.605-55.516 5.381-12.743 20.074-18.717 32.828-13.327 12.73 5.39 18.695 20.084 13.324 32.826-33.836 80.039-90.205 88.659-146.096 86.063-55.913-2.615-80.455 40.822-80.704 41.258a26.872 26.872 0 0 1-2.101 3.229C497.969 674.089 441.372 701 438.995 702.109a24.848 24.848 0 0 1-10.562 2.35zM512.633 800.586c-9.434 0-18.47-5.359-22.711-14.475-5.825-12.516-.445-27.365 12.03-33.242.931-.447 48.134-23.551 94.792-83.526 7.253-11.851 46.341-68.803 125.725-65.087 48.232 2.249 76.572-5.737 97.617-55.526 5.379-12.732 20.074-18.697 32.816-13.327 12.742 5.39 18.705 20.084 13.316 32.816-33.826 80.059-90.205 88.688-146.076 86.072-55.894-2.566-80.466 40.811-80.704 41.258a25.655 25.655 0 0 1-2.12 3.23c-55.13 71.428-111.736 98.348-114.114 99.447a24.915 24.915 0 0 1-10.571 2.36zM597.506 896.063c-9.433 0-18.468-5.35-22.73-14.455-5.825-12.516-.436-27.377 12.039-33.242.685-.338 48.005-23.414 94.792-83.547 7.252-11.852 46.311-68.832 125.736-65.098 48.223 2.26 76.551-5.727 97.605-55.505 5.391-12.761 20.074-18.716 32.824-13.325 12.744 5.38 18.709 20.083 13.318 32.806-33.828 80.058-90.205 88.689-146.086 86.083-55.902-2.576-80.465 40.811-80.703 41.256a27.541 27.541 0 0 1-2.111 3.221c-55.129 71.438-111.735 98.357-114.113 99.469a25.118 25.118 0 0 1-10.571 2.337z' })
    );
};

exports.default = PlotStreamtubeIcon;

/***/ }),

/***/ "e3Tu":
/*!***************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/config/index.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const __1 = __webpack_require__(/*! .. */ "S9up");
/**
 * The url for the config service.
 */
let SERVICE_CONFIG_URL = 'api/config';
/**
 * The namespace for ConfigSection statics.
 */
var ConfigSection;
(function (ConfigSection) {
    /**
     * Create a config section.
     *
     * @returns A Promise that is fulfilled with the config section is loaded.
     */
    function create(options) {
        let section = new DefaultConfigSection(options);
        return section.load().then(() => {
            return section;
        });
    }
    ConfigSection.create = create;
})(ConfigSection = exports.ConfigSection || (exports.ConfigSection = {}));
/**
 * Implementation of the Configurable data section.
 */
class DefaultConfigSection {
    /**
     * Construct a new config section.
     */
    constructor(options) {
        this._url = 'unknown';
        let settings = (this.serverSettings =
            options.serverSettings || __1.ServerConnection.makeSettings());
        this._url = coreutils_1.URLExt.join(settings.baseUrl, SERVICE_CONFIG_URL, encodeURIComponent(options.name));
    }
    /**
     * Get the data for this section.
     */
    get data() {
        return this._data;
    }
    /**
     * Load the initial data for this section.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/config).
     *
     * The promise is fulfilled on a valid response and rejected otherwise.
     */
    load() {
        return __1.ServerConnection.makeRequest(this._url, {}, this.serverSettings)
            .then(response => {
            if (response.status !== 200) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            return response.json();
        })
            .then(data => {
            this._data = data;
        });
    }
    /**
     * Modify the stored config values.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/config).
     *
     * The promise is fulfilled on a valid response and rejected otherwise.
     *
     * Updates the local data immediately, sends the change to the server,
     * and updates the local data with the response, and fulfils the promise
     * with that data.
     */
    update(newdata) {
        this._data = Object.assign({}, this._data, newdata);
        let init = {
            method: 'PATCH',
            body: JSON.stringify(newdata)
        };
        return __1.ServerConnection.makeRequest(this._url, init, this.serverSettings)
            .then(response => {
            if (response.status !== 200) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            return response.json();
        })
            .then(data => {
            this._data = data;
            return this._data;
        });
    }
}
/**
 * Configurable object with defaults.
 */
class ConfigWithDefaults {
    /**
     * Create a new config with defaults.
     */
    constructor(options) {
        this._className = '';
        this._section = options.section;
        this._defaults = options.defaults || {};
        this._className = options.className || '';
    }
    /**
     * Get data from the config section or fall back to defaults.
     */
    get(key) {
        let data = this._classData();
        return key in data ? data[key] : this._defaults[key];
    }
    /**
     * Set a config value.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/config).
     *
     * The promise is fulfilled on a valid response and rejected otherwise.
     *
     * Sends the update to the server, and changes our local copy of the data
     * immediately.
     */
    set(key, value) {
        let d = {};
        d[key] = value;
        if (this._className) {
            let d2 = {};
            d2[this._className] = d;
            return this._section.update(d2);
        }
        else {
            return this._section.update(d);
        }
    }
    /**
     * Get data from the Section with our classname, if available.
     *
     * #### Notes
     * If we have no classname, get all of the data in the Section
     */
    _classData() {
        let data = this._section.data;
        if (this._className && this._className in data) {
            return data[this._className];
        }
        return data;
    }
}
exports.ConfigWithDefaults = ConfigWithDefaults;


/***/ }),

/***/ "e3q/":
/*!********************************************************!*\
  !*** ./node_modules/@jupyterlab/mathjax2/lib/index.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
__webpack_require__(/*! ../style/index.css */ "9Yhm");
/**
 * The MathJax Typesetter.
 */
class MathJaxTypesetter {
    /**
     * Create a new MathJax typesetter.
     */
    constructor(options) {
        this._initPromise = new coreutils_1.PromiseDelegate();
        this._initialized = false;
        this._url = options.url;
        this._config = options.config;
    }
    /**
     * Typeset the math in a node.
     *
     * #### Notes
     * MathJax schedules the typesetting asynchronously,
     * but there are not currently any callbacks or Promises
     * firing when it is done.
     */
    typeset(node) {
        if (!this._initialized) {
            this._init();
        }
        this._initPromise.promise.then(() => {
            MathJax.Hub.Queue(['Typeset', MathJax.Hub, node]);
            try {
                MathJax.Hub.Queue(['Require', MathJax.Ajax, '[MathJax]/extensions/TeX/AMSmath.js'], () => {
                    MathJax.InputJax.TeX.resetEquationNumbers();
                });
            }
            catch (e) {
                console.error('Error queueing resetEquationNumbers:', e);
            }
        });
    }
    /**
     * Initialize MathJax.
     */
    _init() {
        let head = document.getElementsByTagName('head')[0];
        let script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = `${this._url}?config=${this._config}&amp;delayStartupUntil=configured" charset="utf-8"`;
        head.appendChild(script);
        script.addEventListener('load', () => {
            this._onLoad();
        });
        this._initialized = true;
    }
    /**
     * Handle MathJax loading.
     */
    _onLoad() {
        MathJax.Hub.Config({
            tex2jax: {
                inlineMath: [['$', '$'], ['\\(', '\\)']],
                displayMath: [['$$', '$$'], ['\\[', '\\]']],
                processEscapes: true,
                processEnvironments: true
            },
            // Center justify equations in code and markdown cells. Elsewhere
            // we use CSS to left justify single line equations in code cells.
            displayAlign: 'center',
            CommonHTML: {
                linebreaks: { automatic: true }
            },
            'HTML-CSS': {
                availableFonts: [],
                imageFont: null,
                preferredFont: null,
                webFont: 'STIX-Web',
                styles: { '.MathJax_Display': { margin: 0 } },
                linebreaks: { automatic: true }
            },
            skipStartupTypeset: true
        });
        MathJax.Hub.Configured();
        this._initPromise.resolve(void 0);
    }
}
exports.MathJaxTypesetter = MathJaxTypesetter;


/***/ }),

/***/ "e4Nc":
/*!******************************************!*\
  !*** ./node_modules/lodash/_MapCache.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var mapCacheClear = __webpack_require__(/*! ./_mapCacheClear */ "fGT3"),
    mapCacheDelete = __webpack_require__(/*! ./_mapCacheDelete */ "k+1r"),
    mapCacheGet = __webpack_require__(/*! ./_mapCacheGet */ "JHgL"),
    mapCacheHas = __webpack_require__(/*! ./_mapCacheHas */ "pSRY"),
    mapCacheSet = __webpack_require__(/*! ./_mapCacheSet */ "H8j4");

/**
 * 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]);
  }
}

// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;

module.exports = MapCache;


/***/ }),

/***/ "e5Mh":
/*!*********************************************************************!*\
  !*** ./node_modules/@jupyterlab/application-extension/lib/index.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const application_1 = __webpack_require__(/*! @jupyterlab/application */ "FkFl");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const React = __importStar(__webpack_require__(/*! react */ "q1tI"));
/**
 * The command IDs used by the application plugin.
 */
var CommandIDs;
(function (CommandIDs) {
    CommandIDs.activateNextTab = 'application:activate-next-tab';
    CommandIDs.activatePreviousTab = 'application:activate-previous-tab';
    CommandIDs.closeAll = 'application:close-all';
    CommandIDs.setMode = 'application:set-mode';
    CommandIDs.toggleMode = 'application:toggle-mode';
    CommandIDs.toggleLeftArea = 'application:toggle-left-area';
    CommandIDs.toggleRightArea = 'application:toggle-right-area';
    CommandIDs.togglePresentationMode = 'application:toggle-presentation-mode';
    CommandIDs.tree = 'router:tree';
    CommandIDs.switchSidebar = 'sidebar:switch';
})(CommandIDs || (CommandIDs = {}));
/**
 * The routing regular expressions used by the application plugin.
 */
var Patterns;
(function (Patterns) {
    Patterns.tree = new RegExp(`^${coreutils_1.PageConfig.getOption('treeUrl')}([^?]+)`);
    Patterns.workspace = new RegExp(`^${coreutils_1.PageConfig.getOption('workspacesUrl')}[^?\/]+/tree/([^?]+)`);
})(Patterns || (Patterns = {}));
/**
 * The main extension.
 */
const main = {
    id: '@jupyterlab/application-extension:main',
    requires: [apputils_1.ICommandPalette, application_1.IRouter, apputils_1.IWindowResolver],
    activate: (app, palette, router, resolver) => {
        // Requiring the window resolver guarantees that the application extension
        // only loads if there is a viable window name. Otherwise, the application
        // will short-circuit and ask the user to navigate away.
        const workspace = resolver.name;
        console.log(`Starting application in workspace: ${workspace}`);
        // If there were errors registering plugins, tell the user.
        if (app.registerPluginErrors.length !== 0) {
            const body = (React.createElement("pre", null, app.registerPluginErrors.map(e => e.message).join('\n')));
            apputils_1.showErrorMessage('Error Registering Plugins', { message: body });
        }
        addCommands(app, palette);
        // If the application shell layout is modified,
        // trigger a refresh of the commands.
        app.shell.layoutModified.connect(() => {
            app.commands.notifyCommandChanged();
        });
        const builder = app.serviceManager.builder;
        const build = () => {
            return builder
                .build()
                .then(() => {
                return apputils_1.showDialog({
                    title: 'Build Complete',
                    body: 'Build successfully completed, reload page?',
                    buttons: [
                        apputils_1.Dialog.cancelButton(),
                        apputils_1.Dialog.warnButton({ label: 'RELOAD' })
                    ]
                });
            })
                .then(result => {
                if (result.button.accept) {
                    router.reload();
                }
            })
                .catch(err => {
                apputils_1.showErrorMessage('Build Failed', {
                    message: React.createElement("pre", null, err.message)
                });
            });
        };
        if (builder.isAvailable && builder.shouldCheck) {
            builder.getStatus().then(response => {
                if (response.status === 'building') {
                    return build();
                }
                if (response.status !== 'needed') {
                    return;
                }
                const body = (React.createElement("div", null,
                    React.createElement("p", null,
                        "JupyterLab build is suggested:",
                        React.createElement("br", null),
                        React.createElement("pre", null, response.message))));
                apputils_1.showDialog({
                    title: 'Build Recommended',
                    body,
                    buttons: [apputils_1.Dialog.cancelButton(), apputils_1.Dialog.okButton({ label: 'BUILD' })]
                }).then(result => (result.button.accept ? build() : undefined));
            });
        }
        const message = 'Are you sure you want to exit JupyterLab?\n' +
            'Any unsaved changes will be lost.';
        // The spec for the `beforeunload` event is implemented differently by
        // the different browser vendors. Consequently, the `event.returnValue`
        // attribute needs to set in addition to a return value being returned.
        // For more information, see:
        // https://developer.mozilla.org/en/docs/Web/Events/beforeunload
        window.addEventListener('beforeunload', event => {
            if (app.isDirty) {
                return (event.returnValue = message);
            }
        });
    },
    autoStart: true
};
/**
 * The default layout restorer provider.
 */
const layout = {
    id: '@jupyterlab/application-extension:layout',
    requires: [coreutils_1.IStateDB],
    activate: (app, state) => {
        const first = app.started;
        const registry = app.commands;
        const restorer = new application_1.LayoutRestorer({ first, registry, state });
        restorer.fetch().then(saved => {
            app.shell.restoreLayout(saved);
            app.shell.layoutModified.connect(() => {
                restorer.save(app.shell.saveLayout());
            });
        });
        return restorer;
    },
    autoStart: true,
    provides: application_1.ILayoutRestorer
};
/**
 * The default URL router provider.
 */
const router = {
    id: '@jupyterlab/application-extension:router',
    activate: (app) => {
        const { commands } = app;
        const base = coreutils_1.PageConfig.getOption('baseUrl');
        const router = new application_1.Router({ base, commands });
        app.started.then(() => {
            // Route the very first request on load.
            router.route();
            // Route all pop state events.
            window.addEventListener('popstate', () => {
                router.route();
            });
        });
        return router;
    },
    autoStart: true,
    provides: application_1.IRouter
};
/**
 * The tree route handler provider.
 */
const tree = {
    id: '@jupyterlab/application-extension:tree',
    autoStart: true,
    requires: [application_1.IRouter],
    activate: (app, router) => {
        const { commands } = app;
        commands.addCommand(CommandIDs.tree, {
            execute: (args) => __awaiter(this, void 0, void 0, function* () {
                const treeMatch = args.path.match(Patterns.tree);
                const workspaceMatch = args.path.match(Patterns.workspace);
                const match = treeMatch || workspaceMatch;
                const path = decodeURI(match[1]);
                const { page, workspaces } = app.info.urls;
                const workspace = coreutils_1.PathExt.basename(app.info.workspace);
                const url = (workspaceMatch ? coreutils_1.URLExt.join(workspaces, workspace) : page) +
                    args.search +
                    args.hash;
                const immediate = true;
                const silent = true;
                // Silently remove the tree portion of the URL leaving the rest intact.
                router.navigate(url, { silent });
                try {
                    yield commands.execute('filebrowser:navigate', { path });
                    yield commands.execute('apputils:save-statedb', { immediate });
                }
                catch (error) {
                    console.warn('Tree routing failed.', error);
                }
            })
        });
        router.register({ command: CommandIDs.tree, pattern: Patterns.tree });
        router.register({ command: CommandIDs.tree, pattern: Patterns.workspace });
    }
};
/**
 * The default URL not found extension.
 */
const notfound = {
    id: '@jupyterlab/application-extension:notfound',
    activate: (app, router) => {
        const bad = coreutils_1.PageConfig.getOption('notFoundUrl');
        const base = router.base;
        const message = `
      The path: ${bad} was not found. JupyterLab redirected to: ${base}
    `;
        if (!bad) {
            return;
        }
        // Change the URL back to the base application URL without adding the
        // URL change to the browser history.
        router.navigate('', { silent: true });
        apputils_1.showErrorMessage('Path Not Found', { message });
    },
    requires: [application_1.IRouter],
    autoStart: true
};
/**
 * Change the favicon changing based on the busy status;
 */
const busy = {
    id: '@jupyterlab/application-extension:faviconbusy',
    activate: (app) => __awaiter(this, void 0, void 0, function* () {
        app.busySignal.connect((_, isBusy) => {
            const favicon = document.querySelector(`link[rel="icon"]${isBusy ? '.idle.favicon' : '.busy.favicon'}`);
            if (!favicon) {
                return;
            }
            const newFavicon = document.querySelector(`link${isBusy ? '.busy.favicon' : '.idle.favicon'}`);
            if (!newFavicon) {
                return;
            }
            // If we have the two icons with the special classes, then toggle them.
            if (favicon !== newFavicon) {
                favicon.rel = '';
                newFavicon.rel = 'icon';
                // Firefox doesn't seem to recognize just changing rel, so we also
                // reinsert the link into the DOM.
                newFavicon.parentNode.replaceChild(newFavicon, newFavicon);
            }
        });
    }),
    requires: [],
    autoStart: true
};
const SIDEBAR_ID = '@jupyterlab/application-extension:sidebar';
/**
 * Keep user settings for where to show the side panels.
 */
const sidebar = {
    id: SIDEBAR_ID,
    activate: (app, settingRegistry) => {
        let overrides = {};
        const handleLayoutOverrides = () => {
            algorithm_1.each(app.shell.widgets('left'), widget => {
                if (overrides[widget.id] && overrides[widget.id] === 'right') {
                    app.shell.addToRightArea(widget);
                }
            });
            algorithm_1.each(app.shell.widgets('right'), widget => {
                if (overrides[widget.id] && overrides[widget.id] === 'left') {
                    app.shell.addToLeftArea(widget);
                }
            });
        };
        app.shell.layoutModified.connect(handleLayoutOverrides);
        // Fetch overrides from the settings system.
        Promise.all([settingRegistry.load(SIDEBAR_ID), app.restored]).then(([settings]) => {
            overrides = settings.get('overrides').composite || {};
            settings.changed.connect(settings => {
                overrides =
                    settings.get('overrides').composite || {};
                handleLayoutOverrides();
            });
        });
        // Add a command to switch a side panels's side
        app.commands.addCommand(CommandIDs.switchSidebar, {
            label: 'Switch Sidebar Side',
            execute: () => {
                // First, try to find the right panel based on the
                // application context menu click,
                // If we can't find it there, look for use the active
                // left/right widgets.
                const contextNode = app.contextMenuFirst(node => !!node.dataset.id);
                let id;
                let side;
                if (contextNode) {
                    id = contextNode.dataset['id'];
                    const leftPanel = document.getElementById('jp-left-stack');
                    const node = document.getElementById(id);
                    if (leftPanel && node && leftPanel.contains(node)) {
                        side = 'right';
                    }
                    else {
                        side = 'left';
                    }
                }
                else if (document.body.dataset.leftSidebarWidget) {
                    id = document.body.dataset.leftSidebarWidget;
                    side = 'right';
                }
                else if (document.body.dataset.rightSidebarWidget) {
                    id = document.body.dataset.rightSidebarWidget;
                    side = 'left';
                }
                // Move the panel to the other side.
                const newOverrides = Object.assign({}, overrides);
                newOverrides[id] = side;
                settingRegistry.set(SIDEBAR_ID, 'overrides', newOverrides);
            }
        });
        // Add a context menu item to sidebar tabs.
        app.contextMenu.addItem({
            command: CommandIDs.switchSidebar,
            selector: '.jp-SideBar .p-TabBar-tab',
            rank: 500
        });
    },
    requires: [coreutils_1.ISettingRegistry],
    autoStart: true
};
/**
 * Add the main application commands.
 */
function addCommands(app, palette) {
    const category = 'Main Area';
    let command = CommandIDs.activateNextTab;
    app.commands.addCommand(command, {
        label: 'Activate Next Tab',
        execute: () => {
            app.shell.activateNextTab();
        }
    });
    palette.addItem({ command, category });
    command = CommandIDs.activatePreviousTab;
    app.commands.addCommand(command, {
        label: 'Activate Previous Tab',
        execute: () => {
            app.shell.activatePreviousTab();
        }
    });
    palette.addItem({ command, category });
    command = CommandIDs.closeAll;
    app.commands.addCommand(command, {
        label: 'Close All Widgets',
        execute: () => {
            app.shell.closeAll();
        }
    });
    palette.addItem({ command, category });
    command = CommandIDs.toggleLeftArea;
    app.commands.addCommand(command, {
        label: args => 'Show Left Sidebar',
        execute: () => {
            if (app.shell.leftCollapsed) {
                app.shell.expandLeft();
            }
            else {
                app.shell.collapseLeft();
                if (app.shell.currentWidget) {
                    app.shell.activateById(app.shell.currentWidget.id);
                }
            }
        },
        isToggled: () => !app.shell.leftCollapsed,
        isVisible: () => !app.shell.isEmpty('left')
    });
    palette.addItem({ command, category });
    command = CommandIDs.toggleRightArea;
    app.commands.addCommand(command, {
        label: args => 'Show Right Sidebar',
        execute: () => {
            if (app.shell.rightCollapsed) {
                app.shell.expandRight();
            }
            else {
                app.shell.collapseRight();
                if (app.shell.currentWidget) {
                    app.shell.activateById(app.shell.currentWidget.id);
                }
            }
        },
        isToggled: () => !app.shell.rightCollapsed,
        isVisible: () => !app.shell.isEmpty('right')
    });
    palette.addItem({ command, category });
    command = CommandIDs.togglePresentationMode;
    app.commands.addCommand(command, {
        label: args => 'Presentation Mode',
        execute: () => {
            app.shell.presentationMode = !app.shell.presentationMode;
        },
        isToggled: () => app.shell.presentationMode,
        isVisible: () => true
    });
    palette.addItem({ command, category });
    command = CommandIDs.setMode;
    app.commands.addCommand(command, {
        isVisible: args => {
            const mode = args['mode'];
            return mode === 'single-document' || mode === 'multiple-document';
        },
        execute: args => {
            const mode = args['mode'];
            if (mode === 'single-document' || mode === 'multiple-document') {
                app.shell.mode = mode;
                return;
            }
            throw new Error(`Unsupported application shell mode: ${mode}`);
        }
    });
    command = CommandIDs.toggleMode;
    app.commands.addCommand(command, {
        label: 'Single-Document Mode',
        isToggled: () => app.shell.mode === 'single-document',
        execute: () => {
            const args = app.shell.mode === 'multiple-document'
                ? { mode: 'single-document' }
                : { mode: 'multiple-document' };
            return app.commands.execute(CommandIDs.setMode, args);
        }
    });
    palette.addItem({ command, category });
}
/**
 * Export the plugins as default.
 */
const plugins = [
    main,
    layout,
    router,
    tree,
    notfound,
    busy,
    sidebar
];
exports.default = plugins;


/***/ }),

/***/ "e5cp":
/*!*************************************************!*\
  !*** ./node_modules/lodash/_baseIsEqualDeep.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Stack = __webpack_require__(/*! ./_Stack */ "fmRc"),
    equalArrays = __webpack_require__(/*! ./_equalArrays */ "or5M"),
    equalByTag = __webpack_require__(/*! ./_equalByTag */ "HDyB"),
    equalObjects = __webpack_require__(/*! ./_equalObjects */ "seXi"),
    getTag = __webpack_require__(/*! ./_getTag */ "QqLw"),
    isArray = __webpack_require__(/*! ./isArray */ "Z0cm"),
    isBuffer = __webpack_require__(/*! ./isBuffer */ "DSRE"),
    isTypedArray = __webpack_require__(/*! ./isTypedArray */ "c6wG");

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1;

/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
    arrayTag = '[object Array]',
    objectTag = '[object Object]';

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * 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);
}

module.exports = baseIsEqualDeep;


/***/ }),

/***/ "e7FE":
/*!**********************************************************!*\
  !*** ./node_modules/@jupyterlab/mainmenu/lib/labmenu.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const disposable_1 = __webpack_require__(/*! @phosphor/disposable */ "uNUc");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
/**
 * An extensible menu for JupyterLab application menus.
 */
class JupyterLabMenu {
    /**
     * Construct a new menu.
     *
     * @param options - Options for the phosphor menu.
     *
     * @param includeSeparators - whether to include separators between the
     *   groups that are added to the menu.
     */
    constructor(options, includeSeparators = true) {
        this._groups = [];
        this._isDisposed = false;
        this.menu = new widgets_1.Menu(options);
        this._includeSeparators = includeSeparators;
    }
    /**
     * Add a group of menu items specific to a particular
     * plugin.
     *
     * @param items - the list of menu items to add.
     *
     * @param rank - the rank in the menu in which to insert the group.
     */
    addGroup(items, rank) {
        const rankGroup = {
            size: items.length,
            rank: rank === undefined ? 100 : rank
        };
        // Insert the plugin group into the list of groups.
        const groupIndex = algorithm_1.ArrayExt.upperBound(this._groups, rankGroup, Private.itemCmp);
        // Determine the index of the menu at which to insert the group.
        let insertIndex = 0;
        for (let i = 0; i < groupIndex; ++i) {
            if (this._groups[i].size > 0) {
                insertIndex += this._groups[i].size;
                // Increase the insert index by two extra in order
                // to include the leading and trailing separators.
                insertIndex += this._includeSeparators ? 2 : 0;
            }
        }
        // Keep an array of the menu items that have been created.
        const added = [];
        // Insert a separator before the group.
        // Phosphor takes care of superfluous leading,
        // trailing, and duplicate separators.
        if (this._includeSeparators) {
            added.push(this.menu.insertItem(insertIndex++, { type: 'separator' }));
        }
        // Insert the group.
        for (let item of items) {
            added.push(this.menu.insertItem(insertIndex++, item));
        }
        // Insert a separator after the group.
        if (this._includeSeparators) {
            added.push(this.menu.insertItem(insertIndex++, { type: 'separator' }));
        }
        algorithm_1.ArrayExt.insert(this._groups, groupIndex, rankGroup);
        return new disposable_1.DisposableDelegate(() => {
            added.forEach(i => this.menu.removeItem(i));
            this._groups.splice(groupIndex, 1);
        });
    }
    /**
     * Whether the menu has been disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources held by the menu.
     */
    dispose() {
        this._groups.length = 0;
        this._isDisposed = true;
        this.menu.dispose();
    }
}
exports.JupyterLabMenu = JupyterLabMenu;
/**
 * A namespace for private data.
 */
var Private;
(function (Private) {
    /**
     * A comparator function for menu rank items.
     */
    function itemCmp(first, second) {
        return first.rank - second.rank;
    }
    Private.itemCmp = itemCmp;
})(Private || (Private = {}));


/***/ }),

/***/ "e7Ga":
/*!*************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotHistogram2dIcon.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotHistogram2dIcon = function PlotHistogram2dIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M32 16h-5.313v-5.313h-5.375V5.312H10.687v5.375H-.001V16h5.313v5.313h5.375v5.375h10.625v-5.375H32z' })
    );
};

exports.default = PlotHistogram2dIcon;

/***/ }),

/***/ "e7Py":
/*!*******************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/AutoscaleIcon.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var AutoscaleIcon = function AutoscaleIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 16 16' }, props),
        _react2.default.createElement('path', { d: 'M4 0H0v4h1V1h3V0zm11 0h-3v1h3v3h1V0h-1zM1 15v-3H0v4h4v-1H1zm14-3v3h-3v1h4v-4h-1zm-2-3l-.008-.003L11.5 10.5 9 8l2.5-2.5L12.971 7H13V3H9v.03l1.5 1.47L8 7 5.5 4.5 7 3.03V3H3v4l1.5-1.5L7 8l-2.5 2.5L3 9v4h4l-1.5-1.5L8 9l2.5 2.5L9 13h4V9z' })
    );
};

exports.default = AutoscaleIcon;

/***/ }),

/***/ "eA/Y":
/*!*****************************************************************!*\
  !*** ./node_modules/readable-stream/lib/_stream_passthrough.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.

// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.



module.exports = PassThrough;

var Transform = __webpack_require__(/*! ./_stream_transform */ "J78i");

/*<replacement>*/
var util = __webpack_require__(/*! core-util-is */ "Onz0");
util.inherits = __webpack_require__(/*! inherits */ "P7XM");
/*</replacement>*/

util.inherits(PassThrough, Transform);

function PassThrough(options) {
  if (!(this instanceof PassThrough)) return new PassThrough(options);

  Transform.call(this, options);
}

PassThrough.prototype._transform = function (chunk, encoding, cb) {
  cb(null, chunk);
};

/***/ }),

/***/ "eDmQ":
/*!********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/TraceSelector.js ***!
  \********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Dropdown = __webpack_require__(/*! ./Dropdown */ "dRXW");

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _constants = __webpack_require__(/*! ../../lib/constants */ "5Bkx");

var _widgets = __webpack_require__(/*! ../widgets */ "VizT");

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _plotlyIcons = __webpack_require__(/*! plotly-icons */ "hwSx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var TraceSelector = function (_Component) {
  _inherits(TraceSelector, _Component);

  function TraceSelector(props, context) {
    _classCallCheck(this, TraceSelector);

    var _this = _possibleConstructorReturn(this, (TraceSelector.__proto__ || Object.getPrototypeOf(TraceSelector)).call(this, props, context));

    _this.updatePlot = _this.updatePlot.bind(_this);
    _this.setGl = _this.setGl.bind(_this);
    _this.glEnabled = _this.glEnabled.bind(_this);
    _this.setTraceDefaults = _this.setTraceDefaults.bind(_this);
    _this.toggleGlControls = _this.toggleGlControls.bind(_this);

    _this.setTraceDefaults(props.container, props.fullContainer, props.updateContainer);
    _this.setLocals(props, context);

    _this.state = { showGlControls: false };
    return _this;
  }

  _createClass(TraceSelector, [{
    key: 'glEnabled',
    value: function glEnabled() {
      return this.props.container.type && this.props.container.type.endsWith('gl') ? 'gl' : '';
    }
  }, {
    key: 'toggleGlControls',
    value: function toggleGlControls() {
      this.setState({ showGlControls: !this.state.showGlControls });
    }
  }, {
    key: 'setLocals',
    value: function setLocals(props, context) {
      var _ = context.localize;
      if (props.traceOptions) {
        this.traceOptions = props.traceOptions;
      } else if (context.traceTypesConfig) {
        this.traceOptions = context.traceTypesConfig.traces(_);
      } else if (context.plotSchema) {
        this.traceOptions = (0, _lib.computeTraceOptionsFromSchema)(context.plotSchema, _, this.context);
      } else {
        this.traceOptions = [{ label: _('Scatter'), value: 'scatter' }];
      }
      if (props.container) {
        this.fullValue = (0, _lib.plotlyTraceToCustomTrace)(props.container);
      }
    }
  }, {
    key: 'setTraceDefaults',
    value: function setTraceDefaults(container, fullContainer, updateContainer, gl) {
      if (container && !container.mode && fullContainer.type === 'scatter') {
        updateContainer({
          type: 'scatter' + (gl || this.context.glByDefault ? gl : this.glEnabled()),
          mode: fullContainer.mode || 'markers'
        });
      }
    }
  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps, nextContext) {
      var container = nextProps.container,
          fullContainer = nextProps.fullContainer,
          updateContainer = nextProps.updateContainer;

      this.setTraceDefaults(container, fullContainer, updateContainer);
      this.setLocals(nextProps, nextContext);
    }
  }, {
    key: 'updatePlot',
    value: function updatePlot(value) {
      var updateContainer = this.props.updateContainer;
      var glByDefault = this.context.glByDefault;

      if (updateContainer) {
        updateContainer((0, _lib.traceTypeToPlotlyInitFigure)(value, this.glEnabled() || glByDefault));
      }
    }
  }, {
    key: 'setGl',
    value: function setGl(value) {
      var _props = this.props,
          container = _props.container,
          fullContainer = _props.fullContainer,
          updateContainer = _props.updateContainer;

      var gl = 'gl';

      this.setTraceDefaults(container, fullContainer, updateContainer, value);

      var traceType = this.fullValue.endsWith(gl) && value === '' ? this.fullValue.slice(0, -gl.length) : this.fullValue;

      updateContainer((0, _lib.traceTypeToPlotlyInitFigure)(traceType, value));
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var props = Object.assign({}, this.props, {
        fullValue: this.fullValue,
        updatePlot: this.updatePlot,
        options: this.traceOptions,
        clearable: false
      });
      var _context = this.context,
          _ = _context.localize,
          advancedTraceTypeSelector = _context.advancedTraceTypeSelector;


      var options = [{ label: _('SVG'), value: '' }, { label: _('WebGL'), value: 'gl' }];

      // Check and see if the advanced selector prop is true
      if (advancedTraceTypeSelector) {
        return _react2.default.createElement(
          'div',
          null,
          _react2.default.createElement(
            _Field2.default,
            props,
            _react2.default.createElement(
              'div',
              {
                style: {
                  display: 'flex',
                  width: '100%',
                  alignItems: 'center'
                }
              },
              _react2.default.createElement(_widgets.TraceTypeSelectorButton, _extends({}, props, {
                traceTypesConfig: this.context.traceTypesConfig,
                handleClick: function handleClick() {
                  return _this2.context.openModal(_widgets.TraceTypeSelector, _extends({}, props, {
                    traceTypesConfig: _this2.context.traceTypesConfig,
                    glByDefault: _this2.context.glByDefault
                  }));
                }
              })),
              !_constants.TRACES_WITH_GL.includes(this.props.container.type) ? '' : _react2.default.createElement(_plotlyIcons.CogIcon, { className: 'menupanel__icon', onClick: this.toggleGlControls })
            )
          ),
          !(_constants.TRACES_WITH_GL.includes(this.props.container.type) && this.state.showGlControls) ? '' : _react2.default.createElement(
            _Field2.default,
            { label: _('Rendering') },
            _react2.default.createElement(_widgets.RadioBlocks, {
              options: options,
              activeOption: this.glEnabled(),
              onOptionChange: this.setGl
            })
          )
        );
      }

      return _react2.default.createElement(_Dropdown.UnconnectedDropdown, props);
    }
  }]);

  return TraceSelector;
}(_react.Component);

TraceSelector.contextTypes = {
  openModal: _propTypes2.default.func,
  advancedTraceTypeSelector: _propTypes2.default.bool,
  traceTypesConfig: _propTypes2.default.object,
  plotSchema: _propTypes2.default.object,
  config: _propTypes2.default.object,
  localize: _propTypes2.default.func,
  glByDefault: _propTypes2.default.bool
};

TraceSelector.propTypes = {
  container: _propTypes2.default.object.isRequired,
  fullContainer: _propTypes2.default.object.isRequired,
  fullValue: _propTypes2.default.any,
  updateContainer: _propTypes2.default.func
};

exports.default = (0, _lib.connectToContainer)(TraceSelector);
//# sourceMappingURL=TraceSelector.js.map

/***/ }),

/***/ "eDuk":
/*!*************************************!*\
  !*** ./node_modules/ajv/lib/ajv.js ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var compileSchema = __webpack_require__(/*! ./compile */ "jQLo")
  , resolve = __webpack_require__(/*! ./compile/resolve */ "qXHa")
  , Cache = __webpack_require__(/*! ./cache */ "6pwk")
  , SchemaObject = __webpack_require__(/*! ./compile/schema_obj */ "ugD5")
  , stableStringify = __webpack_require__(/*! json-stable-stringify */ "rE/H")
  , formats = __webpack_require__(/*! ./compile/formats */ "n+SQ")
  , rules = __webpack_require__(/*! ./compile/rules */ "wXyd")
  , $dataMetaSchema = __webpack_require__(/*! ./$data */ "qqOP")
  , patternGroups = __webpack_require__(/*! ./patternGroups */ "2uPQ")
  , util = __webpack_require__(/*! ./compile/util */ "+9rK")
  , co = __webpack_require__(/*! co */ "GH25");

module.exports = Ajv;

Ajv.prototype.validate = validate;
Ajv.prototype.compile = compile;
Ajv.prototype.addSchema = addSchema;
Ajv.prototype.addMetaSchema = addMetaSchema;
Ajv.prototype.validateSchema = validateSchema;
Ajv.prototype.getSchema = getSchema;
Ajv.prototype.removeSchema = removeSchema;
Ajv.prototype.addFormat = addFormat;
Ajv.prototype.errorsText = errorsText;

Ajv.prototype._addSchema = _addSchema;
Ajv.prototype._compile = _compile;

Ajv.prototype.compileAsync = __webpack_require__(/*! ./compile/async */ "sagP");
var customKeyword = __webpack_require__(/*! ./keyword */ "//Jx");
Ajv.prototype.addKeyword = customKeyword.add;
Ajv.prototype.getKeyword = customKeyword.get;
Ajv.prototype.removeKeyword = customKeyword.remove;

var errorClasses = __webpack_require__(/*! ./compile/error_classes */ "iZoB");
Ajv.ValidationError = errorClasses.Validation;
Ajv.MissingRefError = errorClasses.MissingRef;
Ajv.$dataMetaSchema = $dataMetaSchema;

var META_SCHEMA_ID = 'http://json-schema.org/draft-06/schema';

var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes' ];
var META_SUPPORT_DATA = ['/properties'];

/**
 * Creates validator instance.
 * Usage: `Ajv(opts)`
 * @param {Object} opts optional options
 * @return {Object} ajv instance
 */
function Ajv(opts) {
  if (!(this instanceof Ajv)) return new Ajv(opts);
  opts = this._opts = util.copy(opts) || {};
  this._schemas = {};
  this._refs = {};
  this._fragments = {};
  this._formats = formats(opts.format);
  var schemaUriFormat = this._schemaUriFormat = this._formats['uri-reference'];
  this._schemaUriFormatFunc = function (str) { return schemaUriFormat.test(str); };

  this._cache = opts.cache || new Cache;
  this._loadingSchemas = {};
  this._compilations = [];
  this.RULES = rules();
  this._getId = chooseGetId(opts);

  opts.loopRequired = opts.loopRequired || Infinity;
  if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true;
  if (opts.serialize === undefined) opts.serialize = stableStringify;
  this._metaOpts = getMetaSchemaOptions(this);

  if (opts.formats) addInitialFormats(this);
  addDraft6MetaSchema(this);
  if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);
  addInitialSchemas(this);
  if (opts.patternGroups) patternGroups(this);
}



/**
 * Validate data using schema
 * Schema will be compiled and cached (using serialized JSON as key. [json-stable-stringify](https://github.com/substack/json-stable-stringify) is used to serialize.
 * @this   Ajv
 * @param  {String|Object} schemaKeyRef key, ref or schema object
 * @param  {Any} data to be validated
 * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
 */
function validate(schemaKeyRef, data) {
  var v;
  if (typeof schemaKeyRef == 'string') {
    v = this.getSchema(schemaKeyRef);
    if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
  } else {
    var schemaObj = this._addSchema(schemaKeyRef);
    v = schemaObj.validate || this._compile(schemaObj);
  }

  var valid = v(data);
  if (v.$async === true)
    return this._opts.async == '*' ? co(valid) : valid;
  this.errors = v.errors;
  return valid;
}


/**
 * Create validating function for passed schema.
 * @this   Ajv
 * @param  {Object} schema schema object
 * @param  {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.
 * @return {Function} validating function
 */
function compile(schema, _meta) {
  var schemaObj = this._addSchema(schema, undefined, _meta);
  return schemaObj.validate || this._compile(schemaObj);
}


/**
 * Adds schema to the instance.
 * @this   Ajv
 * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
 * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
 * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.
 * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
 */
function addSchema(schema, key, _skipValidation, _meta) {
  if (Array.isArray(schema)){
    for (var i=0; i<schema.length; i++) this.addSchema(schema[i], undefined, _skipValidation, _meta);
    return;
  }
  var id = this._getId(schema);
  if (id !== undefined && typeof id != 'string')
    throw new Error('schema id must be string');
  key = resolve.normalizeId(key || id);
  checkUnique(this, key);
  this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
}


/**
 * Add schema that will be used to validate other schemas
 * options in META_IGNORE_OPTIONS are alway set to false
 * @this   Ajv
 * @param {Object} schema schema object
 * @param {String} key optional schema key
 * @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema
 */
function addMetaSchema(schema, key, skipValidation) {
  this.addSchema(schema, key, skipValidation, true);
}


/**
 * Validate schema
 * @this   Ajv
 * @param {Object} schema schema to validate
 * @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid
 * @return {Boolean} true if schema is valid
 */
function validateSchema(schema, throwOrLogError) {
  var $schema = schema.$schema;
  if ($schema !== undefined && typeof $schema != 'string')
    throw new Error('$schema must be a string');
  $schema = $schema || this._opts.defaultMeta || defaultMeta(this);
  if (!$schema) {
    console.warn('meta-schema not available');
    this.errors = null;
    return true;
  }
  var currentUriFormat = this._formats.uri;
  this._formats.uri = typeof currentUriFormat == 'function'
                      ? this._schemaUriFormatFunc
                      : this._schemaUriFormat;
  var valid;
  try { valid = this.validate($schema, schema); }
  finally { this._formats.uri = currentUriFormat; }
  if (!valid && throwOrLogError) {
    var message = 'schema is invalid: ' + this.errorsText();
    if (this._opts.validateSchema == 'log') console.error(message);
    else throw new Error(message);
  }
  return valid;
}


function defaultMeta(self) {
  var meta = self._opts.meta;
  self._opts.defaultMeta = typeof meta == 'object'
                            ? self._getId(meta) || meta
                            : self.getSchema(META_SCHEMA_ID)
                              ? META_SCHEMA_ID
                              : undefined;
  return self._opts.defaultMeta;
}


/**
 * Get compiled schema from the instance by `key` or `ref`.
 * @this   Ajv
 * @param  {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
 * @return {Function} schema validating function (with property `schema`).
 */
function getSchema(keyRef) {
  var schemaObj = _getSchemaObj(this, keyRef);
  switch (typeof schemaObj) {
    case 'object': return schemaObj.validate || this._compile(schemaObj);
    case 'string': return this.getSchema(schemaObj);
    case 'undefined': return _getSchemaFragment(this, keyRef);
  }
}


function _getSchemaFragment(self, ref) {
  var res = resolve.schema.call(self, { schema: {} }, ref);
  if (res) {
    var schema = res.schema
      , root = res.root
      , baseId = res.baseId;
    var v = compileSchema.call(self, schema, root, undefined, baseId);
    self._fragments[ref] = new SchemaObject({
      ref: ref,
      fragment: true,
      schema: schema,
      root: root,
      baseId: baseId,
      validate: v
    });
    return v;
  }
}


function _getSchemaObj(self, keyRef) {
  keyRef = resolve.normalizeId(keyRef);
  return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef];
}


/**
 * Remove cached schema(s).
 * If no parameter is passed all schemas but meta-schemas are removed.
 * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
 * Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
 * @this   Ajv
 * @param  {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object
 */
function removeSchema(schemaKeyRef) {
  if (schemaKeyRef instanceof RegExp) {
    _removeAllSchemas(this, this._schemas, schemaKeyRef);
    _removeAllSchemas(this, this._refs, schemaKeyRef);
    return;
  }
  switch (typeof schemaKeyRef) {
    case 'undefined':
      _removeAllSchemas(this, this._schemas);
      _removeAllSchemas(this, this._refs);
      this._cache.clear();
      return;
    case 'string':
      var schemaObj = _getSchemaObj(this, schemaKeyRef);
      if (schemaObj) this._cache.del(schemaObj.cacheKey);
      delete this._schemas[schemaKeyRef];
      delete this._refs[schemaKeyRef];
      return;
    case 'object':
      var serialize = this._opts.serialize;
      var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef;
      this._cache.del(cacheKey);
      var id = this._getId(schemaKeyRef);
      if (id) {
        id = resolve.normalizeId(id);
        delete this._schemas[id];
        delete this._refs[id];
      }
  }
}


function _removeAllSchemas(self, schemas, regex) {
  for (var keyRef in schemas) {
    var schemaObj = schemas[keyRef];
    if (!schemaObj.meta && (!regex || regex.test(keyRef))) {
      self._cache.del(schemaObj.cacheKey);
      delete schemas[keyRef];
    }
  }
}


/* @this   Ajv */
function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
  if (typeof schema != 'object' && typeof schema != 'boolean')
    throw new Error('schema should be object or boolean');
  var serialize = this._opts.serialize;
  var cacheKey = serialize ? serialize(schema) : schema;
  var cached = this._cache.get(cacheKey);
  if (cached) return cached;

  shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false;

  var id = resolve.normalizeId(this._getId(schema));
  if (id && shouldAddSchema) checkUnique(this, id);

  var willValidate = this._opts.validateSchema !== false && !skipValidation;
  var recursiveMeta;
  if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema)))
    this.validateSchema(schema, true);

  var localRefs = resolve.ids.call(this, schema);

  var schemaObj = new SchemaObject({
    id: id,
    schema: schema,
    localRefs: localRefs,
    cacheKey: cacheKey,
    meta: meta
  });

  if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj;
  this._cache.put(cacheKey, schemaObj);

  if (willValidate && recursiveMeta) this.validateSchema(schema, true);

  return schemaObj;
}


/* @this   Ajv */
function _compile(schemaObj, root) {
  if (schemaObj.compiling) {
    schemaObj.validate = callValidate;
    callValidate.schema = schemaObj.schema;
    callValidate.errors = null;
    callValidate.root = root ? root : callValidate;
    if (schemaObj.schema.$async === true)
      callValidate.$async = true;
    return callValidate;
  }
  schemaObj.compiling = true;

  var currentOpts;
  if (schemaObj.meta) {
    currentOpts = this._opts;
    this._opts = this._metaOpts;
  }

  var v;
  try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); }
  finally {
    schemaObj.compiling = false;
    if (schemaObj.meta) this._opts = currentOpts;
  }

  schemaObj.validate = v;
  schemaObj.refs = v.refs;
  schemaObj.refVal = v.refVal;
  schemaObj.root = v.root;
  return v;


  function callValidate() {
    var _validate = schemaObj.validate;
    var result = _validate.apply(null, arguments);
    callValidate.errors = _validate.errors;
    return result;
  }
}


function chooseGetId(opts) {
  switch (opts.schemaId) {
    case '$id': return _get$Id;
    case 'id': return _getId;
    default: return _get$IdOrId;
  }
}


function _getId(schema) {
  if (schema.$id) console.warn('schema $id ignored', schema.$id);
  return schema.id;
}


function _get$Id(schema) {
  if (schema.id) console.warn('schema id ignored', schema.id);
  return schema.$id;
}


function _get$IdOrId(schema) {
  if (schema.$id && schema.id && schema.$id != schema.id)
    throw new Error('schema $id is different from id');
  return schema.$id || schema.id;
}


/**
 * Convert array of error message objects to string
 * @this   Ajv
 * @param  {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used.
 * @param  {Object} options optional options with properties `separator` and `dataVar`.
 * @return {String} human readable string with all errors descriptions
 */
function errorsText(errors, options) {
  errors = errors || this.errors;
  if (!errors) return 'No errors';
  options = options || {};
  var separator = options.separator === undefined ? ', ' : options.separator;
  var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;

  var text = '';
  for (var i=0; i<errors.length; i++) {
    var e = errors[i];
    if (e) text += dataVar + e.dataPath + ' ' + e.message + separator;
  }
  return text.slice(0, -separator.length);
}


/**
 * Add custom format
 * @this   Ajv
 * @param {String} name format name
 * @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
 */
function addFormat(name, format) {
  if (typeof format == 'string') format = new RegExp(format);
  this._formats[name] = format;
}


function addDraft6MetaSchema(self) {
  var $dataSchema;
  if (self._opts.$data) {
    $dataSchema = __webpack_require__(/*! ./refs/$data.json */ "pviQ");
    self.addMetaSchema($dataSchema, $dataSchema.$id, true);
  }
  if (self._opts.meta === false) return;
  var metaSchema = __webpack_require__(/*! ./refs/json-schema-draft-06.json */ "Dg32");
  if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA);
  self.addMetaSchema(metaSchema, META_SCHEMA_ID, true);
  self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID;
}


function addInitialSchemas(self) {
  var optsSchemas = self._opts.schemas;
  if (!optsSchemas) return;
  if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas);
  else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key);
}


function addInitialFormats(self) {
  for (var name in self._opts.formats) {
    var format = self._opts.formats[name];
    self.addFormat(name, format);
  }
}


function checkUnique(self, id) {
  if (self._schemas[id] || self._refs[id])
    throw new Error('schema with key or id "' + id + '" already exists');
}


function getMetaSchemaOptions(self) {
  var metaOpts = util.copy(self._opts);
  for (var i=0; i<META_IGNORE_OPTIONS.length; i++)
    delete metaOpts[META_IGNORE_OPTIONS[i]];
  return metaOpts;
}


/***/ }),

/***/ "eE4k":
/*!***************************************************!*\
  !*** ./node_modules/mdi-react/ChevronDownIcon.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var ChevronDownIcon = function ChevronDownIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M7.41,8.58L12,13.17L16.59,8.58L18,10L12,16L6,10L7.41,8.58Z' })
  );
};

module.exports = ChevronDownIcon;


/***/ }),

/***/ "eGGc":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/codeeditor/lib/widget.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
/**
 * The class name added to an editor widget that has a primary selection.
 */
const HAS_SELECTION_CLASS = 'jp-mod-has-primary-selection';
/**
 * The class name added to an editor widget that has a cursor/selection
 * within the whitespace at the beginning of a line
 */
const HAS_IN_LEADING_WHITESPACE_CLASS = 'jp-mod-in-leading-whitespace';
/**
 * RegExp to test for leading whitespace
 */
const leadingWhitespaceRe = /^\s+$/;
/**
 * A widget which hosts a code editor.
 */
class CodeEditorWrapper extends widgets_1.Widget {
    /**
     * Construct a new code editor widget.
     */
    constructor(options) {
        super();
        const editor = (this.editor = options.factory({
            host: this.node,
            model: options.model,
            uuid: options.uuid,
            config: options.config,
            selectionStyle: options.selectionStyle
        }));
        editor.model.selections.changed.connect(this._onSelectionsChanged, this);
    }
    /**
     * Get the model used by the widget.
     */
    get model() {
        return this.editor.model;
    }
    /**
     * Dispose of the resources held by the widget.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        super.dispose();
        this.editor.dispose();
    }
    /**
     * Handle `'activate-request'` messages.
     */
    onActivateRequest(msg) {
        this.editor.focus();
    }
    /**
     * A message handler invoked on an `'after-attach'` message.
     */
    onAfterAttach(msg) {
        super.onAfterAttach(msg);
        if (this.isVisible) {
            this.update();
        }
    }
    /**
     * A message handler invoked on an `'after-show'` message.
     */
    onAfterShow(msg) {
        this.update();
    }
    /**
     * A message handler invoked on a `'resize'` message.
     */
    onResize(msg) {
        if (msg.width >= 0 && msg.height >= 0) {
            this.editor.setSize(msg);
        }
        else if (this.isVisible) {
            this.editor.resizeToFit();
        }
    }
    /**
     * A message handler invoked on an `'update-request'` message.
     */
    onUpdateRequest(msg) {
        this.editor.refresh();
    }
    /**
     * Handle a change in model selections.
     */
    _onSelectionsChanged() {
        const { start, end } = this.editor.getSelection();
        if (start.column !== end.column || start.line !== end.line) {
            // a selection was made
            this.addClass(HAS_SELECTION_CLASS);
            this.removeClass(HAS_IN_LEADING_WHITESPACE_CLASS);
        }
        else {
            // the cursor was placed
            this.removeClass(HAS_SELECTION_CLASS);
            if (this.editor
                .getLine(end.line)
                .slice(0, end.column)
                .match(leadingWhitespaceRe)) {
                this.addClass(HAS_IN_LEADING_WHITESPACE_CLASS);
            }
            else {
                this.removeClass(HAS_IN_LEADING_WHITESPACE_CLASS);
            }
        }
    }
}
exports.CodeEditorWrapper = CodeEditorWrapper;


/***/ }),

/***/ "eHBW":
/*!******************************************************************************!*\
  !*** ./node_modules/react-color/lib/components/sketch/SketchPresetColors.js ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SketchPresetColors = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _common = __webpack_require__(/*! ../common */ "TM95");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var SketchPresetColors = exports.SketchPresetColors = function SketchPresetColors(_ref) {
  var colors = _ref.colors,
      _ref$onClick = _ref.onClick,
      onClick = _ref$onClick === undefined ? function () {} : _ref$onClick,
      onSwatchHover = _ref.onSwatchHover;

  var styles = (0, _reactcss2.default)({
    'default': {
      colors: {
        margin: '0 -10px',
        padding: '10px 0 0 10px',
        borderTop: '1px solid #eee',
        display: 'flex',
        flexWrap: 'wrap',
        position: 'relative'
      },
      swatchWrap: {
        width: '16px',
        height: '16px',
        margin: '0 10px 10px 0'
      },
      swatch: {
        borderRadius: '3px',
        boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.15)'
      }
    },
    'no-presets': {
      colors: {
        display: 'none'
      }
    }
  }, {
    'no-presets': !colors || !colors.length
  });

  var handleClick = function handleClick(hex, e) {
    onClick({
      hex: hex,
      source: 'hex'
    }, e);
  };

  return _react2.default.createElement(
    'div',
    { style: styles.colors, className: 'flexbox-fix' },
    colors.map(function (colorObjOrString) {
      var c = typeof colorObjOrString === 'string' ? { color: colorObjOrString } : colorObjOrString;
      var key = '' + c.color + (c.title || '');
      return _react2.default.createElement(
        'div',
        { key: key, style: styles.swatchWrap },
        _react2.default.createElement(_common.Swatch, _extends({}, c, {
          style: styles.swatch,
          onClick: handleClick,
          onHover: onSwatchHover,
          focusStyle: {
            boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.15), 0 0 4px ' + c.color
          }
        }))
      );
    })
  );
};

SketchPresetColors.propTypes = {
  colors: _propTypes2.default.arrayOf(_propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.shape({
    color: _propTypes2.default.string,
    title: _propTypes2.default.string
  })])).isRequired
};

exports.default = SketchPresetColors;

/***/ }),

/***/ "eIPM":
/*!**************************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/commandpalette.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
        s = arguments[i];
        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
            t[p] = s[p];
    }
    return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
var coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
var commands_1 = __webpack_require__(/*! @phosphor/commands */ "5TpB");
var domutils_1 = __webpack_require__(/*! @phosphor/domutils */ "XWTc");
var virtualdom_1 = __webpack_require__(/*! @phosphor/virtualdom */ "Gqu+");
var widget_1 = __webpack_require__(/*! ./widget */ "FmDU");
/**
 * A widget which displays command items as a searchable palette.
 */
var CommandPalette = (function (_super) {
    __extends(CommandPalette, _super);
    /**
     * Construct a new command palette.
     *
     * @param options - The options for initializing the palette.
     */
    function CommandPalette(options) {
        var _this = _super.call(this, { node: Private.createNode() }) || this;
        _this._activeIndex = -1;
        _this._items = [];
        _this._results = null;
        _this.addClass('p-CommandPalette');
        _this.setFlag(widget_1.Widget.Flag.DisallowLayout);
        _this.commands = options.commands;
        _this.renderer = options.renderer || CommandPalette.defaultRenderer;
        _this.commands.commandChanged.connect(_this._onGenericChange, _this);
        _this.commands.keyBindingChanged.connect(_this._onGenericChange, _this);
        return _this;
    }
    /**
     * Dispose of the resources held by the widget.
     */
    CommandPalette.prototype.dispose = function () {
        this._items.length = 0;
        this._results = null;
        _super.prototype.dispose.call(this);
    };
    Object.defineProperty(CommandPalette.prototype, "searchNode", {
        /**
         * The command palette search node.
         *
         * #### Notes
         * This is the node which contains the search-related elements.
         */
        get: function () {
            return this.node.getElementsByClassName('p-CommandPalette-search')[0];
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(CommandPalette.prototype, "inputNode", {
        /**
         * The command palette input node.
         *
         * #### Notes
         * This is the actual input node for the search area.
         */
        get: function () {
            return this.node.getElementsByClassName('p-CommandPalette-input')[0];
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(CommandPalette.prototype, "contentNode", {
        /**
         * The command palette content node.
         *
         * #### Notes
         * This is the node which holds the command item nodes.
         *
         * Modifying this node directly can lead to undefined behavior.
         */
        get: function () {
            return this.node.getElementsByClassName('p-CommandPalette-content')[0];
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(CommandPalette.prototype, "items", {
        /**
         * A read-only array of the command items in the palette.
         */
        get: function () {
            return this._items;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Add a command item to the command palette.
     *
     * @param options - The options for creating the command item.
     *
     * @returns The command item added to the palette.
     */
    CommandPalette.prototype.addItem = function (options) {
        // Create a new command item for the options.
        var item = Private.createItem(this.commands, options);
        // Add the item to the array.
        this._items.push(item);
        // Refresh the search results.
        this.refresh();
        // Return the item added to the palette.
        return item;
    };
    /**
     * Remove an item from the command palette.
     *
     * @param item - The item to remove from the palette.
     *
     * #### Notes
     * This is a no-op if the item is not in the palette.
     */
    CommandPalette.prototype.removeItem = function (item) {
        this.removeItemAt(this._items.indexOf(item));
    };
    /**
     * Remove the item at a given index from the command palette.
     *
     * @param index - The index of the item to remove.
     *
     * #### Notes
     * This is a no-op if the index is out of range.
     */
    CommandPalette.prototype.removeItemAt = function (index) {
        // Remove the item from the array.
        var item = algorithm_1.ArrayExt.removeAt(this._items, index);
        // Bail if the index is out of range.
        if (!item) {
            return;
        }
        // Refresh the search results.
        this.refresh();
    };
    /**
     * Remove all items from the command palette.
     */
    CommandPalette.prototype.clearItems = function () {
        // Bail if there is nothing to remove.
        if (this._items.length === 0) {
            return;
        }
        // Clear the array of items.
        this._items.length = 0;
        // Refresh the search results.
        this.refresh();
    };
    /**
     * Clear the search results and schedule an update.
     *
     * #### Notes
     * This should be called whenever the search results of the palette
     * should be updated.
     *
     * This is typically called automatically by the palette as needed,
     * but can be called manually if the input text is programatically
     * changed.
     *
     * The rendered results are updated asynchronously.
     */
    CommandPalette.prototype.refresh = function () {
        this._results = null;
        this.update();
    };
    /**
     * Handle the DOM events for the command palette.
     *
     * @param event - The DOM event sent to the command palette.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the command palette's DOM node.
     * It should not be called directly by user code.
     */
    CommandPalette.prototype.handleEvent = function (event) {
        switch (event.type) {
            case 'click':
                this._evtClick(event);
                break;
            case 'keydown':
                this._evtKeyDown(event);
                break;
            case 'input':
                this.refresh();
                break;
            case 'focus':
            case 'blur':
                this._toggleFocused();
                break;
        }
    };
    /**
     * A message handler invoked on a `'before-attach'` message.
     */
    CommandPalette.prototype.onBeforeAttach = function (msg) {
        this.node.addEventListener('click', this);
        this.node.addEventListener('keydown', this);
        this.node.addEventListener('input', this);
        this.node.addEventListener('focus', this, true);
        this.node.addEventListener('blur', this, true);
    };
    /**
     * A message handler invoked on an `'after-detach'` message.
     */
    CommandPalette.prototype.onAfterDetach = function (msg) {
        this.node.removeEventListener('click', this);
        this.node.removeEventListener('keydown', this);
        this.node.removeEventListener('input', this);
        this.node.removeEventListener('focus', this, true);
        this.node.removeEventListener('blur', this, true);
    };
    /**
     * A message handler invoked on an `'activate-request'` message.
     */
    CommandPalette.prototype.onActivateRequest = function (msg) {
        if (this.isAttached) {
            var input = this.inputNode;
            input.focus();
            input.select();
        }
    };
    /**
     * A message handler invoked on an `'update-request'` message.
     */
    CommandPalette.prototype.onUpdateRequest = function (msg) {
        // Fetch the current query text and content node.
        var query = this.inputNode.value;
        var contentNode = this.contentNode;
        // Ensure the search results are generated.
        var results = this._results;
        if (!results) {
            // Generate and store the new search results.
            results = this._results = Private.search(this._items, query);
            // Reset the active index.
            this._activeIndex = (query ? algorithm_1.ArrayExt.findFirstIndex(results, Private.canActivate) : -1);
        }
        // If there is no query and no results, clear the content.
        if (!query && results.length === 0) {
            virtualdom_1.VirtualDOM.render(null, contentNode);
            return;
        }
        // If the is a query but no results, render the empty message.
        if (query && results.length === 0) {
            var content_1 = this.renderer.renderEmptyMessage({ query: query });
            virtualdom_1.VirtualDOM.render(content_1, contentNode);
            return;
        }
        // Create the render content for the search results.
        var renderer = this.renderer;
        var activeIndex = this._activeIndex;
        var content = new Array(results.length);
        for (var i = 0, n = results.length; i < n; ++i) {
            var result = results[i];
            if (result.type === 'header') {
                var indices = result.indices;
                var category = result.category;
                content[i] = renderer.renderHeader({ category: category, indices: indices });
            }
            else {
                var item = result.item;
                var indices = result.indices;
                var active = i === activeIndex;
                content[i] = renderer.renderItem({ item: item, indices: indices, active: active });
            }
        }
        // Render the search result content.
        virtualdom_1.VirtualDOM.render(content, contentNode);
        // Adjust the scroll position as needed.
        if (activeIndex < 0 || activeIndex >= results.length) {
            contentNode.scrollTop = 0;
        }
        else {
            var element = contentNode.children[activeIndex];
            domutils_1.ElementExt.scrollIntoViewIfNeeded(contentNode, element);
        }
    };
    /**
     * Handle the `'click'` event for the command palette.
     */
    CommandPalette.prototype._evtClick = function (event) {
        // Bail if the click is not the left button.
        if (event.button !== 0) {
            return;
        }
        // Find the index of the item which was clicked.
        var index = algorithm_1.ArrayExt.findFirstIndex(this.contentNode.children, function (node) {
            return node.contains(event.target);
        });
        // Bail if the click was not on an item.
        if (index === -1) {
            return;
        }
        // Kill the event when a content item is clicked.
        event.preventDefault();
        event.stopPropagation();
        // Execute the item if possible.
        this._execute(index);
    };
    /**
     * Handle the `'keydown'` event for the command palette.
     */
    CommandPalette.prototype._evtKeyDown = function (event) {
        if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {
            return;
        }
        switch (event.keyCode) {
            case 13:
                event.preventDefault();
                event.stopPropagation();
                this._execute(this._activeIndex);
                break;
            case 38:
                event.preventDefault();
                event.stopPropagation();
                this._activatePreviousItem();
                break;
            case 40:
                event.preventDefault();
                event.stopPropagation();
                this._activateNextItem();
                break;
        }
    };
    /**
     * Activate the next enabled command item.
     */
    CommandPalette.prototype._activateNextItem = function () {
        // Bail if there are no search results.
        if (!this._results || this._results.length === 0) {
            return;
        }
        // Find the next enabled item index.
        var ai = this._activeIndex;
        var n = this._results.length;
        var start = ai < n - 1 ? ai + 1 : 0;
        var stop = start === 0 ? n - 1 : start - 1;
        this._activeIndex = algorithm_1.ArrayExt.findFirstIndex(this._results, Private.canActivate, start, stop);
        // Schedule an update of the items.
        this.update();
    };
    /**
     * Activate the previous enabled command item.
     */
    CommandPalette.prototype._activatePreviousItem = function () {
        // Bail if there are no search results.
        if (!this._results || this._results.length === 0) {
            return;
        }
        // Find the previous enabled item index.
        var ai = this._activeIndex;
        var n = this._results.length;
        var start = ai <= 0 ? n - 1 : ai - 1;
        var stop = start === n - 1 ? 0 : start + 1;
        this._activeIndex = algorithm_1.ArrayExt.findLastIndex(this._results, Private.canActivate, start, stop);
        // Schedule an update of the items.
        this.update();
    };
    /**
     * Execute the command item at the given index, if possible.
     */
    CommandPalette.prototype._execute = function (index) {
        // Bail if there are no search results.
        if (!this._results) {
            return;
        }
        // Bail if the index is out of range.
        var part = this._results[index];
        if (!part) {
            return;
        }
        // Update the search text if the item is a header.
        if (part.type === 'header') {
            var input = this.inputNode;
            input.value = part.category.toLowerCase() + " ";
            input.focus();
            this.refresh();
            return;
        }
        // Bail if item is not enabled.
        if (!part.item.isEnabled) {
            return;
        }
        // Execute the item.
        this.commands.execute(part.item.command, part.item.args);
        // Clear the query text.
        this.inputNode.value = '';
        // Refresh the search results.
        this.refresh();
    };
    /**
     * Toggle the focused modifier based on the input node focus state.
     */
    CommandPalette.prototype._toggleFocused = function () {
        var focused = document.activeElement === this.inputNode;
        this.toggleClass('p-mod-focused', focused);
    };
    /**
     * A signal handler for generic command changes.
     */
    CommandPalette.prototype._onGenericChange = function () {
        this.refresh();
    };
    return CommandPalette;
}(widget_1.Widget));
exports.CommandPalette = CommandPalette;
/**
 * The namespace for the `CommandPalette` class statics.
 */
(function (CommandPalette) {
    /**
     * The default implementation of `IRenderer`.
     */
    var Renderer = (function () {
        function Renderer() {
        }
        /**
         * Render the virtual element for a command palette header.
         *
         * @param data - The data to use for rendering the header.
         *
         * @returns A virtual element representing the header.
         */
        Renderer.prototype.renderHeader = function (data) {
            var content = this.formatHeader(data);
            return virtualdom_1.h.li({ className: 'p-CommandPalette-header' }, content);
        };
        /**
         * Render the virtual element for a command palette item.
         *
         * @param data - The data to use for rendering the item.
         *
         * @returns A virtual element representing the item.
         */
        Renderer.prototype.renderItem = function (data) {
            var className = this.createItemClass(data);
            var dataset = this.createItemDataset(data);
            return (virtualdom_1.h.li({ className: className, dataset: dataset }, this.renderItemIcon(data), this.renderItemContent(data), this.renderItemShortcut(data)));
        };
        /**
         * Render the empty results message for a command palette.
         *
         * @param data - The data to use for rendering the message.
         *
         * @returns A virtual element representing the message.
         */
        Renderer.prototype.renderEmptyMessage = function (data) {
            var content = this.formatEmptyMessage(data);
            return virtualdom_1.h.li({ className: 'p-CommandPalette-emptyMessage' }, content);
        };
        /**
         * Render the icon for a command palette item.
         *
         * @param data - The data to use for rendering the icon.
         *
         * @returns A virtual element representing the icon.
         */
        Renderer.prototype.renderItemIcon = function (data) {
            var className = this.createIconClass(data);
            return virtualdom_1.h.div({ className: className }, data.item.iconLabel);
        };
        /**
         * Render the content for a command palette item.
         *
         * @param data - The data to use for rendering the content.
         *
         * @returns A virtual element representing the content.
         */
        Renderer.prototype.renderItemContent = function (data) {
            return (virtualdom_1.h.div({ className: 'p-CommandPalette-itemContent' }, this.renderItemLabel(data), this.renderItemCaption(data)));
        };
        /**
         * Render the label for a command palette item.
         *
         * @param data - The data to use for rendering the label.
         *
         * @returns A virtual element representing the label.
         */
        Renderer.prototype.renderItemLabel = function (data) {
            var content = this.formatItemLabel(data);
            return virtualdom_1.h.div({ className: 'p-CommandPalette-itemLabel' }, content);
        };
        /**
         * Render the caption for a command palette item.
         *
         * @param data - The data to use for rendering the caption.
         *
         * @returns A virtual element representing the caption.
         */
        Renderer.prototype.renderItemCaption = function (data) {
            var content = this.formatItemCaption(data);
            return virtualdom_1.h.div({ className: 'p-CommandPalette-itemCaption' }, content);
        };
        /**
         * Render the shortcut for a command palette item.
         *
         * @param data - The data to use for rendering the shortcut.
         *
         * @returns A virtual element representing the shortcut.
         */
        Renderer.prototype.renderItemShortcut = function (data) {
            var content = this.formatItemShortcut(data);
            return virtualdom_1.h.div({ className: 'p-CommandPalette-itemShortcut' }, content);
        };
        /**
         * Create the class name for the command palette item.
         *
         * @param data - The data to use for the class name.
         *
         * @returns The full class name for the command palette item.
         */
        Renderer.prototype.createItemClass = function (data) {
            // Set up the initial class name.
            var name = 'p-CommandPalette-item';
            // Add the boolean state classes.
            if (!data.item.isEnabled) {
                name += ' p-mod-disabled';
            }
            if (data.item.isToggled) {
                name += ' p-mod-toggled';
            }
            if (data.active) {
                name += ' p-mod-active';
            }
            // Add the extra class.
            var extra = data.item.className;
            if (extra) {
                name += " " + extra;
            }
            // Return the complete class name.
            return name;
        };
        /**
         * Create the dataset for the command palette item.
         *
         * @param data - The data to use for creating the dataset.
         *
         * @returns The dataset for the command palette item.
         */
        Renderer.prototype.createItemDataset = function (data) {
            return __assign({}, data.item.dataset, { command: data.item.command });
        };
        /**
         * Create the class name for the command item icon.
         *
         * @param data - The data to use for the class name.
         *
         * @returns The full class name for the item icon.
         */
        Renderer.prototype.createIconClass = function (data) {
            var name = 'p-CommandPalette-itemIcon';
            var extra = data.item.iconClass;
            return extra ? name + " " + extra : name;
        };
        /**
         * Create the render content for the header node.
         *
         * @param data - The data to use for the header content.
         *
         * @returns The content to add to the header node.
         */
        Renderer.prototype.formatHeader = function (data) {
            if (!data.indices || data.indices.length === 0) {
                return data.category;
            }
            return algorithm_1.StringExt.highlight(data.category, data.indices, virtualdom_1.h.mark);
        };
        /**
         * Create the render content for the empty message node.
         *
         * @param data - The data to use for the empty message content.
         *
         * @returns The content to add to the empty message node.
         */
        Renderer.prototype.formatEmptyMessage = function (data) {
            return "No commands found that match '" + data.query + "'";
        };
        /**
         * Create the render content for the item shortcut node.
         *
         * @param data - The data to use for the shortcut content.
         *
         * @returns The content to add to the shortcut node.
         */
        Renderer.prototype.formatItemShortcut = function (data) {
            var kb = data.item.keyBinding;
            return kb ? kb.keys.map(Private.formatKeystroke).join(', ') : null;
        };
        /**
         * Create the render content for the item label node.
         *
         * @param data - The data to use for the label content.
         *
         * @returns The content to add to the label node.
         */
        Renderer.prototype.formatItemLabel = function (data) {
            if (!data.indices || data.indices.length === 0) {
                return data.item.label;
            }
            return algorithm_1.StringExt.highlight(data.item.label, data.indices, virtualdom_1.h.mark);
        };
        /**
         * Create the render content for the item caption node.
         *
         * @param data - The data to use for the caption content.
         *
         * @returns The content to add to the caption node.
         */
        Renderer.prototype.formatItemCaption = function (data) {
            return data.item.caption;
        };
        return Renderer;
    }());
    CommandPalette.Renderer = Renderer;
    /**
     * The default `Renderer` instance.
     */
    CommandPalette.defaultRenderer = new Renderer();
})(CommandPalette = exports.CommandPalette || (exports.CommandPalette = {}));
exports.CommandPalette = CommandPalette;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * Create the DOM node for a command palette.
     */
    function createNode() {
        var node = document.createElement('div');
        var search = document.createElement('div');
        var wrapper = document.createElement('div');
        var input = document.createElement('input');
        var content = document.createElement('ul');
        search.className = 'p-CommandPalette-search';
        wrapper.className = 'p-CommandPalette-wrapper';
        input.className = 'p-CommandPalette-input';
        content.className = 'p-CommandPalette-content';
        input.spellcheck = false;
        wrapper.appendChild(input);
        search.appendChild(wrapper);
        node.appendChild(search);
        node.appendChild(content);
        return node;
    }
    Private.createNode = createNode;
    /**
     * Create a new command item from a command registry and options.
     */
    function createItem(commands, options) {
        return new CommandItem(commands, options);
    }
    Private.createItem = createItem;
    /**
     * Format a keystroke for display on the local system.
     */
    function formatKeystroke(keystroke) {
        var mods = '';
        var parts = commands_1.CommandRegistry.parseKeystroke(keystroke);
        if (domutils_1.Platform.IS_MAC) {
            if (parts.ctrl) {
                mods += '\u2303 ';
            }
            if (parts.alt) {
                mods += '\u2325 ';
            }
            if (parts.shift) {
                mods += '\u21E7 ';
            }
            if (parts.cmd) {
                mods += '\u2318 ';
            }
        }
        else {
            if (parts.ctrl) {
                mods += 'Ctrl+';
            }
            if (parts.alt) {
                mods += 'Alt+';
            }
            if (parts.shift) {
                mods += 'Shift+';
            }
        }
        return mods + parts.key;
    }
    Private.formatKeystroke = formatKeystroke;
    /**
     * Search an array of command items for fuzzy matches.
     */
    function search(items, query) {
        // Fuzzy match the items for the query.
        var scores = matchItems(items, query);
        // Sort the items based on their score.
        scores.sort(scoreCmp);
        // Create the results for the search.
        return createResults(scores);
    }
    Private.search = search;
    /**
     * Test whether a result item can be activated.
     */
    function canActivate(result) {
        return result.type === 'item' && result.item.isEnabled;
    }
    Private.canActivate = canActivate;
    /**
     * Normalize a category for a command item.
     */
    function normalizeCategory(category) {
        return category.trim().replace(/\s+/g, ' ');
    }
    /**
     * Normalize the query text for a fuzzy search.
     */
    function normalizeQuery(text) {
        return text.replace(/\s+/g, '').toLowerCase();
    }
    /**
     * Perform a fuzzy match on an array of command items.
     */
    function matchItems(items, query) {
        // Normalize the query text to lower case with no whitespace.
        query = normalizeQuery(query);
        // Create the array to hold the scores.
        var scores = [];
        // Iterate over the items and match against the query.
        for (var i = 0, n = items.length; i < n; ++i) {
            // Ignore items which are not visible.
            var item = items[i];
            if (!item.isVisible) {
                continue;
            }
            // If the query is empty, all items are matched by default.
            if (!query) {
                scores.push({
                    matchType: 3 /* Default */,
                    categoryIndices: null,
                    labelIndices: null,
                    score: 0, item: item
                });
                continue;
            }
            // Run the fuzzy search for the item and query.
            var score = fuzzySearch(item, query);
            // Ignore the item if it is not a match.
            if (!score) {
                continue;
            }
            // Penalize disabled items.
            // TODO - push disabled items all the way down in sort cmp?
            if (!item.isEnabled) {
                score.score += 1000;
            }
            // Add the score to the results.
            scores.push(score);
        }
        // Return the final array of scores.
        return scores;
    }
    /**
     * Perform a fuzzy search on a single command item.
     */
    function fuzzySearch(item, query) {
        // Create the source text to be searched.
        var category = item.category.toLowerCase();
        var label = item.label.toLowerCase();
        var source = category + " " + label;
        // Set up the match score and indices array.
        var score = Infinity;
        var indices = null;
        // The regex for search word boundaries
        var rgx = /\b\w/g;
        // Search the source by word boundary.
        while (true) {
            // Find the next word boundary in the source.
            var rgxMatch = rgx.exec(source);
            // Break if there is no more source context.
            if (!rgxMatch) {
                break;
            }
            // Run the string match on the relevant substring.
            var match = algorithm_1.StringExt.matchSumOfDeltas(source, query, rgxMatch.index);
            // Break if there is no match.
            if (!match) {
                break;
            }
            // Update the match if the score is better.
            if (match && match.score <= score) {
                score = match.score;
                indices = match.indices;
            }
        }
        // Bail if there was no match.
        if (!indices || score === Infinity) {
            return null;
        }
        // Compute the pivot index between category and label text.
        var pivot = category.length + 1;
        // Find the slice index to separate matched indices.
        var j = algorithm_1.ArrayExt.lowerBound(indices, pivot, function (a, b) { return a - b; });
        // Extract the matched category and label indices.
        var categoryIndices = indices.slice(0, j);
        var labelIndices = indices.slice(j);
        // Adjust the label indices for the pivot offset.
        for (var i = 0, n = labelIndices.length; i < n; ++i) {
            labelIndices[i] -= pivot;
        }
        // Handle a pure label match.
        if (categoryIndices.length === 0) {
            return {
                matchType: 0 /* Label */,
                categoryIndices: null,
                labelIndices: labelIndices,
                score: score, item: item
            };
        }
        // Handle a pure category match.
        if (labelIndices.length === 0) {
            return {
                matchType: 1 /* Category */,
                categoryIndices: categoryIndices,
                labelIndices: null,
                score: score, item: item
            };
        }
        // Handle a split match.
        return {
            matchType: 2 /* Split */,
            categoryIndices: categoryIndices,
            labelIndices: labelIndices,
            score: score, item: item
        };
    }
    /**
     * A sort comparison function for a match score.
     */
    function scoreCmp(a, b) {
        // First compare based on the match type
        var m1 = a.matchType - b.matchType;
        if (m1 !== 0) {
            return m1;
        }
        // Otherwise, compare based on the match score.
        var d1 = a.score - b.score;
        if (d1 !== 0) {
            return d1;
        }
        // Find the match index based on the match type.
        var i1 = 0;
        var i2 = 0;
        switch (a.matchType) {
            case 0 /* Label */:
                i1 = a.labelIndices[0];
                i2 = b.labelIndices[0];
                break;
            case 1 /* Category */:
            case 2 /* Split */:
                i1 = a.categoryIndices[0];
                i2 = b.categoryIndices[0];
                break;
        }
        // Compare based on the match index.
        if (i1 !== i2) {
            return i1 - i2;
        }
        // Otherwise, compare by category.
        var d2 = a.item.category.localeCompare(b.item.category);
        if (d2 !== 0) {
            return d2;
        }
        // Otherwise, compare by rank.
        var r1 = a.item.rank;
        var r2 = b.item.rank;
        if (r1 !== r2) {
            return r1 < r2 ? -1 : 1; // Infinity safe
        }
        // Finally, compare by label.
        return a.item.label.localeCompare(b.item.label);
    }
    /**
     * Create the results from an array of sorted scores.
     */
    function createResults(scores) {
        // Set up an array to track which scores have been visited.
        var visited = new Array(scores.length);
        algorithm_1.ArrayExt.fill(visited, false);
        // Set up the search results array.
        var results = [];
        // Iterate over each score in the array.
        for (var i = 0, n = scores.length; i < n; ++i) {
            // Ignore a score which has already been processed.
            if (visited[i]) {
                continue;
            }
            // Extract the current item and indices.
            var _a = scores[i], item = _a.item, categoryIndices = _a.categoryIndices;
            // Extract the category for the current item.
            var category = item.category;
            // Add the header result for the category.
            results.push({ type: 'header', category: category, indices: categoryIndices });
            // Find the rest of the scores with the same category.
            for (var j = i; j < n; ++j) {
                // Ignore a score which has already been processed.
                if (visited[j]) {
                    continue;
                }
                // Extract the data for the current score.
                var _b = scores[j], item_1 = _b.item, labelIndices = _b.labelIndices;
                // Ignore an item with a different category.
                if (item_1.category !== category) {
                    continue;
                }
                // Create the item result for the score.
                results.push({ type: 'item', item: item_1, indices: labelIndices });
                // Mark the score as processed.
                visited[j] = true;
            }
        }
        // Return the final results.
        return results;
    }
    /**
     * A concrete implementation of `CommandPalette.IItem`.
     */
    var CommandItem = (function () {
        /**
         * Construct a new command item.
         */
        function CommandItem(commands, options) {
            this._commands = commands;
            this.category = normalizeCategory(options.category);
            this.command = options.command;
            this.args = options.args || coreutils_1.JSONExt.emptyObject;
            this.rank = options.rank !== undefined ? options.rank : Infinity;
        }
        Object.defineProperty(CommandItem.prototype, "label", {
            /**
             * The display label for the command item.
             */
            get: function () {
                return this._commands.label(this.command, this.args);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(CommandItem.prototype, "iconClass", {
            /**
             * The icon class for the command item.
             */
            get: function () {
                return this._commands.iconClass(this.command, this.args);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(CommandItem.prototype, "iconLabel", {
            /**
             * The icon label for the command item.
             */
            get: function () {
                return this._commands.iconLabel(this.command, this.args);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(CommandItem.prototype, "caption", {
            /**
             * The display caption for the command item.
             */
            get: function () {
                return this._commands.caption(this.command, this.args);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(CommandItem.prototype, "className", {
            /**
             * The extra class name for the command item.
             */
            get: function () {
                return this._commands.className(this.command, this.args);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(CommandItem.prototype, "dataset", {
            /**
             * The dataset for the command item.
             */
            get: function () {
                return this._commands.dataset(this.command, this.args);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(CommandItem.prototype, "isEnabled", {
            /**
             * Whether the command item is enabled.
             */
            get: function () {
                return this._commands.isEnabled(this.command, this.args);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(CommandItem.prototype, "isToggled", {
            /**
             * Whether the command item is toggled.
             */
            get: function () {
                return this._commands.isToggled(this.command, this.args);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(CommandItem.prototype, "isVisible", {
            /**
             * Whether the command item is visible.
             */
            get: function () {
                return this._commands.isVisible(this.command, this.args);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(CommandItem.prototype, "keyBinding", {
            /**
             * The key binding for the command item.
             */
            get: function () {
                var _a = this, command = _a.command, args = _a.args;
                return algorithm_1.ArrayExt.findLastValue(this._commands.keyBindings, function (kb) {
                    return kb.command === command && coreutils_1.JSONExt.deepEqual(kb.args, args);
                }) || null;
            },
            enumerable: true,
            configurable: true
        });
        return CommandItem;
    }());
})(Private || (Private = {}));


/***/ }),

/***/ "eMbh":
/*!************************************************!*\
  !*** ./node_modules/attr-accept/dist/index.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports=function(t){function n(e){if(r[e])return r[e].exports;var o=r[e]={i:e,l:!1,exports:{}};return t[e].call(o.exports,o,o.exports,n),o.l=!0,o.exports}var r={};return n.m=t,n.c=r,n.d=function(t,r,e){n.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:e})},n.n=function(t){var r=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(r,"a",r),r},n.o=function(t,n){return Object.prototype.hasOwnProperty.call(t,n)},n.p="",n(n.s=13)}([function(t,n){var r=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=r)},function(t,n){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,n){var r=t.exports={version:"2.5.0"};"number"==typeof __e&&(__e=r)},function(t,n,r){t.exports=!r(4)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,n){t.exports=function(t){try{return!!t()}catch(t){return!0}}},function(t,n){var r={}.toString;t.exports=function(t){return r.call(t).slice(8,-1)}},function(t,n,r){var e=r(32)("wks"),o=r(9),i=r(0).Symbol,u="function"==typeof i;(t.exports=function(t){return e[t]||(e[t]=u&&i[t]||(u?i:o)("Symbol."+t))}).store=e},function(t,n,r){var e=r(0),o=r(2),i=r(8),u=r(22),c=r(10),f=function(t,n,r){var a,s,p,l,v=t&f.F,y=t&f.G,h=t&f.S,d=t&f.P,x=t&f.B,g=y?e:h?e[n]||(e[n]={}):(e[n]||{}).prototype,m=y?o:o[n]||(o[n]={}),b=m.prototype||(m.prototype={});y&&(r=n);for(a in r)s=!v&&g&&void 0!==g[a],p=(s?g:r)[a],l=x&&s?c(p,e):d&&"function"==typeof p?c(Function.call,p):p,g&&u(g,a,p,t&f.U),m[a]!=p&&i(m,a,l),d&&b[a]!=p&&(b[a]=p)};e.core=o,f.F=1,f.G=2,f.S=4,f.P=8,f.B=16,f.W=32,f.U=64,f.R=128,t.exports=f},function(t,n,r){var e=r(16),o=r(21);t.exports=r(3)?function(t,n,r){return e.f(t,n,o(1,r))}:function(t,n,r){return t[n]=r,t}},function(t,n){var r=0,e=Math.random();t.exports=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++r+e).toString(36))}},function(t,n,r){var e=r(24);t.exports=function(t,n,r){if(e(t),void 0===n)return t;switch(r){case 1:return function(r){return t.call(n,r)};case 2:return function(r,e){return t.call(n,r,e)};case 3:return function(r,e,o){return t.call(n,r,e,o)}}return function(){return t.apply(n,arguments)}}},function(t,n){t.exports=function(t){if(void 0==t)throw TypeError("Can't call method on  "+t);return t}},function(t,n,r){var e=r(28),o=Math.min;t.exports=function(t){return t>0?o(e(t),9007199254740991):0}},function(t,n,r){"use strict";n.__esModule=!0,n.default=function(t,n){if(t&&n){var r=Array.isArray(n)?n:n.split(","),e=t.name||"",o=t.type||"",i=o.replace(/\/.*$/,"");return r.some(function(t){var n=t.trim();return"."===n.charAt(0)?e.toLowerCase().endsWith(n.toLowerCase()):n.endsWith("/*")?i===n.replace(/\/.*$/,""):o===n})}return!0},r(14),r(34)},function(t,n,r){r(15),t.exports=r(2).Array.some},function(t,n,r){"use strict";var e=r(7),o=r(25)(3);e(e.P+e.F*!r(33)([].some,!0),"Array",{some:function(t){return o(this,t,arguments[1])}})},function(t,n,r){var e=r(17),o=r(18),i=r(20),u=Object.defineProperty;n.f=r(3)?Object.defineProperty:function(t,n,r){if(e(t),n=i(n,!0),e(r),o)try{return u(t,n,r)}catch(t){}if("get"in r||"set"in r)throw TypeError("Accessors not supported!");return"value"in r&&(t[n]=r.value),t}},function(t,n,r){var e=r(1);t.exports=function(t){if(!e(t))throw TypeError(t+" is not an object!");return t}},function(t,n,r){t.exports=!r(3)&&!r(4)(function(){return 7!=Object.defineProperty(r(19)("div"),"a",{get:function(){return 7}}).a})},function(t,n,r){var e=r(1),o=r(0).document,i=e(o)&&e(o.createElement);t.exports=function(t){return i?o.createElement(t):{}}},function(t,n,r){var e=r(1);t.exports=function(t,n){if(!e(t))return t;var r,o;if(n&&"function"==typeof(r=t.toString)&&!e(o=r.call(t)))return o;if("function"==typeof(r=t.valueOf)&&!e(o=r.call(t)))return o;if(!n&&"function"==typeof(r=t.toString)&&!e(o=r.call(t)))return o;throw TypeError("Can't convert object to primitive value")}},function(t,n){t.exports=function(t,n){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:n}}},function(t,n,r){var e=r(0),o=r(8),i=r(23),u=r(9)("src"),c=Function.toString,f=(""+c).split("toString");r(2).inspectSource=function(t){return c.call(t)},(t.exports=function(t,n,r,c){var a="function"==typeof r;a&&(i(r,"name")||o(r,"name",n)),t[n]!==r&&(a&&(i(r,u)||o(r,u,t[n]?""+t[n]:f.join(String(n)))),t===e?t[n]=r:c?t[n]?t[n]=r:o(t,n,r):(delete t[n],o(t,n,r)))})(Function.prototype,"toString",function(){return"function"==typeof this&&this[u]||c.call(this)})},function(t,n){var r={}.hasOwnProperty;t.exports=function(t,n){return r.call(t,n)}},function(t,n){t.exports=function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!");return t}},function(t,n,r){var e=r(10),o=r(26),i=r(27),u=r(12),c=r(29);t.exports=function(t,n){var r=1==t,f=2==t,a=3==t,s=4==t,p=6==t,l=5==t||p,v=n||c;return function(n,c,y){for(var h,d,x=i(n),g=o(x),m=e(c,y,3),b=u(g.length),_=0,w=r?v(n,b):f?v(n,0):void 0;b>_;_++)if((l||_ in g)&&(h=g[_],d=m(h,_,x),t))if(r)w[_]=d;else if(d)switch(t){case 3:return!0;case 5:return h;case 6:return _;case 2:w.push(h)}else if(s)return!1;return p?-1:a||s?s:w}}},function(t,n,r){var e=r(5);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==e(t)?t.split(""):Object(t)}},function(t,n,r){var e=r(11);t.exports=function(t){return Object(e(t))}},function(t,n){var r=Math.ceil,e=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(t>0?e:r)(t)}},function(t,n,r){var e=r(30);t.exports=function(t,n){return new(e(t))(n)}},function(t,n,r){var e=r(1),o=r(31),i=r(6)("species");t.exports=function(t){var n;return o(t)&&(n=t.constructor,"function"!=typeof n||n!==Array&&!o(n.prototype)||(n=void 0),e(n)&&null===(n=n[i])&&(n=void 0)),void 0===n?Array:n}},function(t,n,r){var e=r(5);t.exports=Array.isArray||function(t){return"Array"==e(t)}},function(t,n,r){var e=r(0),o=e["__core-js_shared__"]||(e["__core-js_shared__"]={});t.exports=function(t){return o[t]||(o[t]={})}},function(t,n,r){"use strict";var e=r(4);t.exports=function(t,n){return!!t&&e(function(){n?t.call(null,function(){},1):t.call(null)})}},function(t,n,r){r(35),t.exports=r(2).String.endsWith},function(t,n,r){"use strict";var e=r(7),o=r(12),i=r(36),u="".endsWith;e(e.P+e.F*r(38)("endsWith"),"String",{endsWith:function(t){var n=i(this,t,"endsWith"),r=arguments.length>1?arguments[1]:void 0,e=o(n.length),c=void 0===r?e:Math.min(o(r),e),f=String(t);return u?u.call(n,f,c):n.slice(c-f.length,c)===f}})},function(t,n,r){var e=r(37),o=r(11);t.exports=function(t,n,r){if(e(n))throw TypeError("String#"+r+" doesn't accept regex!");return String(o(t))}},function(t,n,r){var e=r(1),o=r(5),i=r(6)("match");t.exports=function(t){var n;return e(t)&&(void 0!==(n=t[i])?!!n:"RegExp"==o(t))}},function(t,n,r){var e=r(6)("match");t.exports=function(t){var n=/./;try{"/./"[t](n)}catch(r){try{return n[e]=!1,!"/./"[t](n)}catch(t){}}return!0}}]);

/***/ }),

/***/ "eOzY":
/*!***********************************************!*\
  !*** ./node_modules/fbjs/lib/setImmediate.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */



// setimmediate adds setImmediate to the global. We want to make sure we export
// the actual function.

__webpack_require__(/*! setimmediate */ "YBdB");
module.exports = global.setImmediate;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "eRYw":
/*!*********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/AxisRangeValue.js ***!
  \*********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UnconnectedAxisRangeValue = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _Numeric = __webpack_require__(/*! ./Numeric */ "E01D");

var _DateTimePicker = __webpack_require__(/*! ./DateTimePicker */ "PLYX");

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _Info = __webpack_require__(/*! ./Info */ "iOcY");

var _Info2 = _interopRequireDefault(_Info);

var _constants = __webpack_require__(/*! ../../lib/constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UnconnectedAxisRangeValue = exports.UnconnectedAxisRangeValue = function (_Component) {
  _inherits(UnconnectedAxisRangeValue, _Component);

  function UnconnectedAxisRangeValue() {
    _classCallCheck(this, UnconnectedAxisRangeValue);

    return _possibleConstructorReturn(this, (UnconnectedAxisRangeValue.__proto__ || Object.getPrototypeOf(UnconnectedAxisRangeValue)).apply(this, arguments));
  }

  _createClass(UnconnectedAxisRangeValue, [{
    key: 'render',
    value: function render() {
      // only when all axes have the type date, can we output an UnconnectedDateTimePicker
      if (this.props.fullContainer && this.props.fullContainer.type === 'date') {
        return _react2.default.createElement(_DateTimePicker.UnconnectedDateTimePicker, this.props);
      }
      // If its multivalued, it can be multivalued for different reasons:
      // - the range is different, but same type
      // - the type is different (i.e. date + number axes)
      // If we're in the case of a mixed axis type (i.e. date + number) case,
      // There's going to be a this.props.fullContainer.type, but it's going to be MULTIVALUED
      if (this.props.multiValued && this.props.fullContainer.type === _constants.MULTI_VALUED) {
        return _react2.default.createElement(_Info2.default, this.props);
      }

      // For cases that the range is numeric, but does not have the same number
      // Or numeric and has the same number
      return _react2.default.createElement(_Numeric.UnconnectedNumeric, this.props);
    }
  }]);

  return UnconnectedAxisRangeValue;
}(_react.Component);

UnconnectedAxisRangeValue.propTypes = _extends({
  defaultValue: _propTypes2.default.any,
  fullValue: _propTypes2.default.any,
  min: _propTypes2.default.number,
  max: _propTypes2.default.number,
  multiValued: _propTypes2.default.bool,
  hideArrows: _propTypes2.default.bool,
  showSlider: _propTypes2.default.bool,
  step: _propTypes2.default.number,
  fullContainer: _propTypes2.default.object,
  updatePlot: _propTypes2.default.func
}, _Field2.default.propTypes);

exports.default = (0, _lib.connectToContainer)(UnconnectedAxisRangeValue);
//# sourceMappingURL=AxisRangeValue.js.map

/***/ }),

/***/ "eRtU":
/*!*************************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/stackedlayout.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
var domutils_1 = __webpack_require__(/*! @phosphor/domutils */ "XWTc");
var messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
var layout_1 = __webpack_require__(/*! ./layout */ "yNaG");
var panellayout_1 = __webpack_require__(/*! ./panellayout */ "HWBy");
var widget_1 = __webpack_require__(/*! ./widget */ "FmDU");
/**
 * A layout where visible widgets are stacked atop one another.
 *
 * #### Notes
 * The Z-order of the visible widgets follows their layout order.
 */
var StackedLayout = (function (_super) {
    __extends(StackedLayout, _super);
    function StackedLayout() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this._dirty = false;
        _this._items = [];
        _this._box = null;
        return _this;
    }
    /**
     * Dispose of the resources held by the layout.
     */
    StackedLayout.prototype.dispose = function () {
        // Dispose of the layout items.
        algorithm_1.each(this._items, function (item) { item.dispose(); });
        // Clear the layout state.
        this._box = null;
        this._items.length = 0;
        // Dispose of the rest of the layout.
        _super.prototype.dispose.call(this);
    };
    /**
     * Attach a widget to the parent's DOM node.
     *
     * @param index - The current index of the widget in the layout.
     *
     * @param widget - The widget to attach to the parent.
     *
     * #### Notes
     * This is a reimplementation of the superclass method.
     */
    StackedLayout.prototype.attachWidget = function (index, widget) {
        // Create and add a new layout item for the widget.
        algorithm_1.ArrayExt.insert(this._items, index, new layout_1.LayoutItem(widget));
        // Send a `'before-attach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.BeforeAttach);
        }
        // Add the widget's node to the parent.
        this.parent.node.appendChild(widget.node);
        // Send an `'after-attach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.AfterAttach);
        }
        // Post a fit request for the parent widget.
        this.parent.fit();
    };
    /**
     * Move a widget in the parent's DOM node.
     *
     * @param fromIndex - The previous index of the widget in the layout.
     *
     * @param toIndex - The current index of the widget in the layout.
     *
     * @param widget - The widget to move in the parent.
     *
     * #### Notes
     * This is a reimplementation of the superclass method.
     */
    StackedLayout.prototype.moveWidget = function (fromIndex, toIndex, widget) {
        // Move the layout item for the widget.
        algorithm_1.ArrayExt.move(this._items, fromIndex, toIndex);
        // Post an update request for the parent widget.
        this.parent.update();
    };
    /**
     * Detach a widget from the parent's DOM node.
     *
     * @param index - The previous index of the widget in the layout.
     *
     * @param widget - The widget to detach from the parent.
     *
     * #### Notes
     * This is a reimplementation of the superclass method.
     */
    StackedLayout.prototype.detachWidget = function (index, widget) {
        // Remove the layout item for the widget.
        var item = algorithm_1.ArrayExt.removeAt(this._items, index);
        // Send a `'before-detach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.BeforeDetach);
        }
        // Remove the widget's node from the parent.
        this.parent.node.removeChild(widget.node);
        // Send an `'after-detach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.AfterDetach);
        }
        // Reset the z-index for the widget.
        item.widget.node.style.zIndex = '';
        // Dispose of the layout item.
        item.dispose();
        // Post a fit request for the parent widget.
        this.parent.fit();
    };
    /**
     * A message handler invoked on a `'before-show'` message.
     */
    StackedLayout.prototype.onBeforeShow = function (msg) {
        _super.prototype.onBeforeShow.call(this, msg);
        this.parent.update();
    };
    /**
     * A message handler invoked on a `'before-attach'` message.
     */
    StackedLayout.prototype.onBeforeAttach = function (msg) {
        _super.prototype.onBeforeAttach.call(this, msg);
        this.parent.fit();
    };
    /**
     * A message handler invoked on a `'child-shown'` message.
     */
    StackedLayout.prototype.onChildShown = function (msg) {
        this.parent.fit();
    };
    /**
     * A message handler invoked on a `'child-hidden'` message.
     */
    StackedLayout.prototype.onChildHidden = function (msg) {
        this.parent.fit();
    };
    /**
     * A message handler invoked on a `'resize'` message.
     */
    StackedLayout.prototype.onResize = function (msg) {
        if (this.parent.isVisible) {
            this._update(msg.width, msg.height);
        }
    };
    /**
     * A message handler invoked on an `'update-request'` message.
     */
    StackedLayout.prototype.onUpdateRequest = function (msg) {
        if (this.parent.isVisible) {
            this._update(-1, -1);
        }
    };
    /**
     * A message handler invoked on a `'fit-request'` message.
     */
    StackedLayout.prototype.onFitRequest = function (msg) {
        if (this.parent.isAttached) {
            this._fit();
        }
    };
    /**
     * Fit the layout to the total size required by the widgets.
     */
    StackedLayout.prototype._fit = function () {
        // Set up the computed minimum size.
        var minW = 0;
        var minH = 0;
        // Update the computed minimum size.
        for (var i = 0, n = this._items.length; i < n; ++i) {
            // Fetch the item.
            var item = this._items[i];
            // Ignore hidden items.
            if (item.isHidden) {
                continue;
            }
            // Update the size limits for the item.
            item.fit();
            // Update the computed minimum size.
            minW = Math.max(minW, item.minWidth);
            minH = Math.max(minH, item.minHeight);
        }
        // Update the box sizing and add it to the computed min size.
        var box = this._box = domutils_1.ElementExt.boxSizing(this.parent.node);
        minW += box.horizontalSum;
        minH += box.verticalSum;
        // Update the parent's min size constraints.
        var style = this.parent.node.style;
        style.minWidth = minW + "px";
        style.minHeight = minH + "px";
        // Set the dirty flag to ensure only a single update occurs.
        this._dirty = true;
        // Notify the ancestor that it should fit immediately. This may
        // cause a resize of the parent, fulfilling the required update.
        if (this.parent.parent) {
            messaging_1.MessageLoop.sendMessage(this.parent.parent, widget_1.Widget.Msg.FitRequest);
        }
        // If the dirty flag is still set, the parent was not resized.
        // Trigger the required update on the parent widget immediately.
        if (this._dirty) {
            messaging_1.MessageLoop.sendMessage(this.parent, widget_1.Widget.Msg.UpdateRequest);
        }
    };
    /**
     * Update the layout position and size of the widgets.
     *
     * The parent offset dimensions should be `-1` if unknown.
     */
    StackedLayout.prototype._update = function (offsetWidth, offsetHeight) {
        // Clear the dirty flag to indicate the update occurred.
        this._dirty = false;
        // Compute the visible item count.
        var nVisible = 0;
        for (var i = 0, n = this._items.length; i < n; ++i) {
            nVisible += +!this._items[i].isHidden;
        }
        // Bail early if there are no visible items to layout.
        if (nVisible === 0) {
            return;
        }
        // Measure the parent if the offset dimensions are unknown.
        if (offsetWidth < 0) {
            offsetWidth = this.parent.node.offsetWidth;
        }
        if (offsetHeight < 0) {
            offsetHeight = this.parent.node.offsetHeight;
        }
        // Ensure the parent box sizing data is computed.
        if (!this._box) {
            this._box = domutils_1.ElementExt.boxSizing(this.parent.node);
        }
        // Compute the actual layout bounds adjusted for border and padding.
        var top = this._box.paddingTop;
        var left = this._box.paddingLeft;
        var width = offsetWidth - this._box.horizontalSum;
        var height = offsetHeight - this._box.verticalSum;
        // Update the widget stacking order and layout geometry.
        for (var i = 0, n = this._items.length; i < n; ++i) {
            // Fetch the item.
            var item = this._items[i];
            // Ignore hidden items.
            if (item.isHidden) {
                continue;
            }
            // Set the z-index for the widget.
            item.widget.node.style.zIndex = "" + i;
            // Update the item geometry.
            item.update(left, top, width, height);
        }
    };
    return StackedLayout;
}(panellayout_1.PanelLayout));
exports.StackedLayout = StackedLayout;


/***/ }),

/***/ "eTKl":
/*!*************************************************************!*\
  !*** ./node_modules/@jupyterlab/rendermime/style/index.css ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "aJvD");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "eUgh":
/*!******************************************!*\
  !*** ./node_modules/lodash/_arrayMap.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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;
}

module.exports = arrayMap;


/***/ }),

/***/ "eUtF":
/*!*****************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_ie8-dom-define.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = !__webpack_require__(/*! ./_descriptors */ "jmDH") && !__webpack_require__(/*! ./_fails */ "KUxP")(function () {
  return Object.defineProperty(__webpack_require__(/*! ./_dom-create */ "Hsns")('div'), 'a', { get: function () { return 7; } }).a != 7;
});


/***/ }),

/***/ "eX6c":
/*!**************************************************!*\
  !*** ./node_modules/mdi-react/ArrowRightIcon.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var ArrowRightIcon = function ArrowRightIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M4,11V13H16L10.5,18.5L11.92,19.92L19.84,12L11.92,4.08L10.5,5.5L16,11H4Z' })
  );
};

module.exports = ArrowRightIcon;


/***/ }),

/***/ "eXBS":
/*!********************************************************************!*\
  !*** ./node_modules/@jupyterlab/observables/lib/observablelist.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
/**
 * A concrete implementation of [[IObservableList]].
 */
class ObservableList {
    /**
     * Construct a new observable map.
     */
    constructor(options = {}) {
        this._array = [];
        this._isDisposed = false;
        this._changed = new signaling_1.Signal(this);
        if (options.values !== void 0) {
            algorithm_1.each(options.values, value => {
                this._array.push(value);
            });
        }
        this._itemCmp = options.itemCmp || Private.itemCmp;
    }
    /**
     * The type of this object.
     */
    get type() {
        return 'List';
    }
    /**
     * A signal emitted when the list has changed.
     */
    get changed() {
        return this._changed;
    }
    /**
     * The length of the list.
     */
    get length() {
        return this._array.length;
    }
    /**
     * Test whether the list has been disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources held by the list.
     */
    dispose() {
        if (this._isDisposed) {
            return;
        }
        this._isDisposed = true;
        signaling_1.Signal.clearData(this);
        this.clear();
    }
    /**
     * Create an iterator over the values in the list.
     *
     * @returns A new iterator starting at the front of the list.
     *
     * #### Complexity
     * Constant.
     *
     * #### Iterator Validity
     * No changes.
     */
    iter() {
        return new algorithm_1.ArrayIterator(this._array);
    }
    /**
     * Get the value at the specified index.
     *
     * @param index - The positive integer index of interest.
     *
     * @returns The value at the specified index.
     *
     * #### Undefined Behavior
     * An `index` which is non-integral or out of range.
     */
    get(index) {
        return this._array[index];
    }
    /**
     * Set the value at the specified index.
     *
     * @param index - The positive integer index of interest.
     *
     * @param value - The value to set at the specified index.
     *
     * #### Complexity
     * Constant.
     *
     * #### Iterator Validity
     * No changes.
     *
     * #### Undefined Behavior
     * An `index` which is non-integral or out of range.
     */
    set(index, value) {
        let oldValue = this._array[index];
        if (value === undefined) {
            throw new Error('Cannot set an undefined item');
        }
        // Bail if the value does not change.
        let itemCmp = this._itemCmp;
        if (itemCmp(oldValue, value)) {
            return;
        }
        this._array[index] = value;
        this._changed.emit({
            type: 'set',
            oldIndex: index,
            newIndex: index,
            oldValues: [oldValue],
            newValues: [value]
        });
    }
    /**
     * Add a value to the end of the list.
     *
     * @param value - The value to add to the end of the list.
     *
     * @returns The new length of the list.
     *
     * #### Complexity
     * Constant.
     *
     * #### Iterator Validity
     * No changes.
     */
    push(value) {
        let num = this._array.push(value);
        this._changed.emit({
            type: 'add',
            oldIndex: -1,
            newIndex: this.length - 1,
            oldValues: [],
            newValues: [value]
        });
        return num;
    }
    /**
     * Insert a value into the list at a specific index.
     *
     * @param index - The index at which to insert the value.
     *
     * @param value - The value to set at the specified index.
     *
     * #### Complexity
     * Linear.
     *
     * #### Iterator Validity
     * No changes.
     *
     * #### Notes
     * The `index` will be clamped to the bounds of the list.
     *
     * #### Undefined Behavior
     * An `index` which is non-integral.
     */
    insert(index, value) {
        algorithm_1.ArrayExt.insert(this._array, index, value);
        this._changed.emit({
            type: 'add',
            oldIndex: -1,
            newIndex: index,
            oldValues: [],
            newValues: [value]
        });
    }
    /**
     * Remove the first occurrence of a value from the list.
     *
     * @param value - The value of interest.
     *
     * @returns The index of the removed value, or `-1` if the value
     *   is not contained in the list.
     *
     * #### Complexity
     * Linear.
     *
     * #### Iterator Validity
     * Iterators pointing at the removed value and beyond are invalidated.
     */
    removeValue(value) {
        let itemCmp = this._itemCmp;
        let index = algorithm_1.ArrayExt.findFirstIndex(this._array, item => {
            return itemCmp(item, value);
        });
        this.remove(index);
        return index;
    }
    /**
     * Remove and return the value at a specific index.
     *
     * @param index - The index of the value of interest.
     *
     * @returns The value at the specified index, or `undefined` if the
     *   index is out of range.
     *
     * #### Complexity
     * Constant.
     *
     * #### Iterator Validity
     * Iterators pointing at the removed value and beyond are invalidated.
     *
     * #### Undefined Behavior
     * An `index` which is non-integral.
     */
    remove(index) {
        let value = algorithm_1.ArrayExt.removeAt(this._array, index);
        if (value === undefined) {
            return;
        }
        this._changed.emit({
            type: 'remove',
            oldIndex: index,
            newIndex: -1,
            newValues: [],
            oldValues: [value]
        });
        return value;
    }
    /**
     * Remove all values from the list.
     *
     * #### Complexity
     * Linear.
     *
     * #### Iterator Validity
     * All current iterators are invalidated.
     */
    clear() {
        let copy = this._array.slice();
        this._array.length = 0;
        this._changed.emit({
            type: 'remove',
            oldIndex: 0,
            newIndex: 0,
            newValues: [],
            oldValues: copy
        });
    }
    /**
     * Move a value from one index to another.
     *
     * @parm fromIndex - The index of the element to move.
     *
     * @param toIndex - The index to move the element to.
     *
     * #### Complexity
     * Constant.
     *
     * #### Iterator Validity
     * Iterators pointing at the lesser of the `fromIndex` and the `toIndex`
     * and beyond are invalidated.
     *
     * #### Undefined Behavior
     * A `fromIndex` or a `toIndex` which is non-integral.
     */
    move(fromIndex, toIndex) {
        if (this.length <= 1 || fromIndex === toIndex) {
            return;
        }
        let values = [this._array[fromIndex]];
        algorithm_1.ArrayExt.move(this._array, fromIndex, toIndex);
        this._changed.emit({
            type: 'move',
            oldIndex: fromIndex,
            newIndex: toIndex,
            oldValues: values,
            newValues: values
        });
    }
    /**
     * Push a set of values to the back of the list.
     *
     * @param values - An iterable or array-like set of values to add.
     *
     * @returns The new length of the list.
     *
     * #### Complexity
     * Linear.
     *
     * #### Iterator Validity
     * No changes.
     */
    pushAll(values) {
        let newIndex = this.length;
        algorithm_1.each(values, value => {
            this._array.push(value);
        });
        this._changed.emit({
            type: 'add',
            oldIndex: -1,
            newIndex,
            oldValues: [],
            newValues: algorithm_1.toArray(values)
        });
        return this.length;
    }
    /**
     * Insert a set of items into the list at the specified index.
     *
     * @param index - The index at which to insert the values.
     *
     * @param values - The values to insert at the specified index.
     *
     * #### Complexity.
     * Linear.
     *
     * #### Iterator Validity
     * No changes.
     *
     * #### Notes
     * The `index` will be clamped to the bounds of the list.
     *
     * #### Undefined Behavior.
     * An `index` which is non-integral.
     */
    insertAll(index, values) {
        let newIndex = index;
        algorithm_1.each(values, value => {
            algorithm_1.ArrayExt.insert(this._array, index++, value);
        });
        this._changed.emit({
            type: 'add',
            oldIndex: -1,
            newIndex,
            oldValues: [],
            newValues: algorithm_1.toArray(values)
        });
    }
    /**
     * Remove a range of items from the list.
     *
     * @param startIndex - The start index of the range to remove (inclusive).
     *
     * @param endIndex - The end index of the range to remove (exclusive).
     *
     * @returns The new length of the list.
     *
     * #### Complexity
     * Linear.
     *
     * #### Iterator Validity
     * Iterators pointing to the first removed value and beyond are invalid.
     *
     * #### Undefined Behavior
     * A `startIndex` or `endIndex` which is non-integral.
     */
    removeRange(startIndex, endIndex) {
        let oldValues = this._array.slice(startIndex, endIndex);
        for (let i = startIndex; i < endIndex; i++) {
            algorithm_1.ArrayExt.removeAt(this._array, startIndex);
        }
        this._changed.emit({
            type: 'remove',
            oldIndex: startIndex,
            newIndex: -1,
            oldValues,
            newValues: []
        });
        return this.length;
    }
}
exports.ObservableList = ObservableList;
/**
 * The namespace for module private data.
 */
var Private;
(function (Private) {
    /**
     * The default strict equality item cmp.
     */
    function itemCmp(first, second) {
        return first === second;
    }
    Private.itemCmp = itemCmp;
})(Private || (Private = {}));


/***/ }),

/***/ "eY4P":
/*!*********************************************!*\
  !*** ./node_modules/ajv/lib/dotjs/items.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_items(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $idx = 'i' + $lvl,
    $dataNxt = $it.dataLevel = it.dataLevel + 1,
    $nextData = 'data' + $dataNxt,
    $currentBaseId = it.baseId;
  out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
  if (Array.isArray($schema)) {
    var $additionalItems = it.schema.additionalItems;
    if ($additionalItems === false) {
      out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; ';
      var $currErrSchemaPath = $errSchemaPath;
      $errSchemaPath = it.errSchemaPath + '/additionalItems';
      out += '  if (!' + ($valid) + ') {   ';
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = ''; /* istanbul ignore else */
      if (it.createErrors !== false) {
        out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } ';
        if (it.opts.messages !== false) {
          out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' ';
        }
        if (it.opts.verbose) {
          out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
        }
        out += ' } ';
      } else {
        out += ' {} ';
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
        if (it.async) {
          out += ' throw new ValidationError([' + (__err) + ']); ';
        } else {
          out += ' validate.errors = [' + (__err) + ']; return false; ';
        }
      } else {
        out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
      }
      out += ' } ';
      $errSchemaPath = $currErrSchemaPath;
      if ($breakOnError) {
        $closingBraces += '}';
        out += ' else { ';
      }
    }
    var arr1 = $schema;
    if (arr1) {
      var $sch, $i = -1,
        l1 = arr1.length - 1;
      while ($i < l1) {
        $sch = arr1[$i += 1];
        if (it.util.schemaHasRules($sch, it.RULES.all)) {
          out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { ';
          var $passData = $data + '[' + $i + ']';
          $it.schema = $sch;
          $it.schemaPath = $schemaPath + '[' + $i + ']';
          $it.errSchemaPath = $errSchemaPath + '/' + $i;
          $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);
          $it.dataPathArr[$dataNxt] = $i;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
          } else {
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
          }
          out += ' }  ';
          if ($breakOnError) {
            out += ' if (' + ($nextValid) + ') { ';
            $closingBraces += '}';
          }
        }
      }
    }
    if (typeof $additionalItems == 'object' && it.util.schemaHasRules($additionalItems, it.RULES.all)) {
      $it.schema = $additionalItems;
      $it.schemaPath = it.schemaPath + '.additionalItems';
      $it.errSchemaPath = it.errSchemaPath + '/additionalItems';
      out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') {  for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
      $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
      var $passData = $data + '[' + $idx + ']';
      $it.dataPathArr[$dataNxt] = $idx;
      var $code = it.validate($it);
      $it.baseId = $currentBaseId;
      if (it.util.varOccurences($code, $nextData) < 2) {
        out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
      } else {
        out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
      }
      if ($breakOnError) {
        out += ' if (!' + ($nextValid) + ') break; ';
      }
      out += ' } }  ';
      if ($breakOnError) {
        out += ' if (' + ($nextValid) + ') { ';
        $closingBraces += '}';
      }
    }
  } else if (it.util.schemaHasRules($schema, it.RULES.all)) {
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    out += '  for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
    $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
    var $passData = $data + '[' + $idx + ']';
    $it.dataPathArr[$dataNxt] = $idx;
    var $code = it.validate($it);
    $it.baseId = $currentBaseId;
    if (it.util.varOccurences($code, $nextData) < 2) {
      out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
    } else {
      out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
    }
    if ($breakOnError) {
      out += ' if (!' + ($nextValid) + ') break; ';
    }
    out += ' }';
  }
  if ($breakOnError) {
    out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
  }
  out = it.util.cleanUpCode(out);
  return out;
}


/***/ }),

/***/ "eYkc":
/*!******************************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils-extension/lib/index.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const application_1 = __webpack_require__(/*! @jupyterlab/application */ "FkFl");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const mainmenu_1 = __webpack_require__(/*! @jupyterlab/mainmenu */ "N4Qf");
const coreutils_2 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const disposable_1 = __webpack_require__(/*! @phosphor/disposable */ "uNUc");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const palette_1 = __webpack_require__(/*! ./palette */ "Sqtn");
const redirect_1 = __webpack_require__(/*! ./redirect */ "YOC8");
__webpack_require__(/*! ../style/index.css */ "IVJK");
/**
 * The interval in milliseconds that calls to save a workspace are debounced
 * to allow for multiple quickly executed state changes to result in a single
 * workspace save operation.
 */
const WORKSPACE_SAVE_DEBOUNCE_INTERVAL = 750;
/**
 * The interval in milliseconds before recover options appear during splash.
 */
const SPLASH_RECOVER_TIMEOUT = 12000;
/**
 * The command IDs used by the apputils plugin.
 */
var CommandIDs;
(function (CommandIDs) {
    CommandIDs.changeTheme = 'apputils:change-theme';
    CommandIDs.loadState = 'apputils:load-statedb';
    CommandIDs.recoverState = 'apputils:recover-statedb';
    CommandIDs.reset = 'apputils:reset';
    CommandIDs.resetOnLoad = 'apputils:reset-on-load';
    CommandIDs.saveState = 'apputils:save-statedb';
})(CommandIDs || (CommandIDs = {}));
/**
 * The routing regular expressions used by the apputils plugin.
 */
var Patterns;
(function (Patterns) {
    Patterns.resetOnLoad = /(\?reset|\&reset)($|&)/;
    Patterns.workspace = new RegExp(`^${coreutils_1.PageConfig.getOption('workspacesUrl')}([^?\/]+)`);
})(Patterns || (Patterns = {}));
/**
 * A data connector to access plugin settings.
 */
class SettingsConnector extends coreutils_1.DataConnector {
    /**
     * Create a new settings connector.
     */
    constructor(manager) {
        super();
        this._manager = manager;
    }
    /**
     * Retrieve a saved bundle from the data connector.
     */
    fetch(id) {
        return this._manager.settings.fetch(id).then(data => {
            // Replace the server ID with the original unmodified version.
            data.id = id;
            return data;
        });
    }
    /**
     * Save the user setting data in the data connector.
     */
    save(id, raw) {
        return this._manager.settings.save(id, raw);
    }
}
/**
 * The default command palette extension.
 */
const palette = {
    activate: palette_1.activatePalette,
    id: '@jupyterlab/apputils-extension:palette',
    provides: apputils_1.ICommandPalette,
    autoStart: true
};
/**
 * The default command palette's restoration extension.
 *
 * #### Notes
 * The command palette's restoration logic is handled separately from the
 * command palette provider extension because the layout restorer dependency
 * causes the command palette to be unavailable to other extensions earlier
 * in the application load cycle.
 */
const paletteRestorer = {
    activate: palette_1.restorePalette,
    id: '@jupyterlab/apputils-extension:palette-restorer',
    requires: [application_1.ILayoutRestorer],
    autoStart: true
};
/**
 * The default setting registry provider.
 */
const settings = {
    id: '@jupyterlab/apputils-extension:settings',
    activate: (app) => {
        const connector = new SettingsConnector(app.serviceManager);
        return new coreutils_1.SettingRegistry({ connector });
    },
    autoStart: true,
    provides: coreutils_1.ISettingRegistry
};
/**
 * The default theme manager provider.
 */
const themes = {
    id: '@jupyterlab/apputils-extension:themes',
    requires: [coreutils_1.ISettingRegistry, apputils_1.ISplashScreen],
    optional: [apputils_1.ICommandPalette, mainmenu_1.IMainMenu],
    activate: (app, settings, splash, palette, mainMenu) => {
        const host = app.shell;
        const commands = app.commands;
        const url = coreutils_1.URLExt.join(app.info.urls.base, app.info.urls.themes);
        const key = themes.id;
        const manager = new apputils_1.ThemeManager({ key, host, settings, splash, url });
        // Keep a synchronously set reference to the current theme,
        // since the asynchronous setting of the theme in `changeTheme`
        // can lead to an incorrect toggle on the currently used theme.
        let currentTheme;
        // Set data attributes on the application shell for the current theme.
        manager.themeChanged.connect((sender, args) => {
            currentTheme = args.newValue;
            app.shell.dataset.themeLight = String(manager.isLight(currentTheme));
            app.shell.dataset.themeName = currentTheme;
            commands.notifyCommandChanged(CommandIDs.changeTheme);
        });
        commands.addCommand(CommandIDs.changeTheme, {
            label: args => {
                const theme = args['theme'];
                return args['isPalette'] ? `Use ${theme} Theme` : theme;
            },
            isToggled: args => args['theme'] === currentTheme,
            execute: args => {
                const theme = args['theme'];
                if (theme === manager.theme) {
                    return;
                }
                manager.setTheme(theme);
            }
        });
        // If we have a main menu, add the theme manager to the settings menu.
        if (mainMenu) {
            const themeMenu = new widgets_1.Menu({ commands });
            themeMenu.title.label = 'JupyterLab Theme';
            app.restored.then(() => {
                const command = CommandIDs.changeTheme;
                const isPalette = false;
                manager.themes.forEach(theme => {
                    themeMenu.addItem({ command, args: { isPalette, theme } });
                });
            });
            mainMenu.settingsMenu.addGroup([
                {
                    type: 'submenu',
                    submenu: themeMenu
                }
            ], 0);
        }
        // If we have a command palette, add theme switching options to it.
        if (palette) {
            app.restored.then(() => {
                const category = 'Settings';
                const command = CommandIDs.changeTheme;
                const isPalette = true;
                currentTheme = manager.theme;
                manager.themes.forEach(theme => {
                    palette.addItem({ command, args: { isPalette, theme }, category });
                });
            });
        }
        return manager;
    },
    autoStart: true,
    provides: apputils_1.IThemeManager
};
/**
 * The default window name resolver provider.
 */
const resolver = {
    id: '@jupyterlab/apputils-extension:resolver',
    autoStart: true,
    provides: apputils_1.IWindowResolver,
    requires: [application_1.IRouter],
    activate: (app, router) => __awaiter(this, void 0, void 0, function* () {
        const resolver = new apputils_1.WindowResolver();
        const match = router.current.path.match(Patterns.workspace);
        const workspace = (match && decodeURIComponent(match[1])) || '';
        const candidate = workspace
            ? coreutils_1.URLExt.join(coreutils_1.PageConfig.getOption('baseUrl'), coreutils_1.PageConfig.getOption('workspacesUrl'), workspace)
            : app.info.defaultWorkspace;
        try {
            yield resolver.resolve(candidate);
        }
        catch (error) {
            console.warn('Window resolution failed:', error);
            // Return a promise that never resolves.
            return new Promise(() => {
                Private.redirect(router);
            });
        }
        coreutils_1.PageConfig.setOption('workspace', resolver.name);
        return resolver;
    })
};
/**
 * The default splash screen provider.
 */
const splash = {
    id: '@jupyterlab/apputils-extension:splash',
    autoStart: true,
    provides: apputils_1.ISplashScreen,
    activate: app => {
        return {
            show: (light = true) => {
                const { commands, restored } = app;
                return Private.showSplash(restored, commands, CommandIDs.reset, light);
            }
        };
    }
};
/**
 * The default state database for storing application state.
 */
const state = {
    id: '@jupyterlab/apputils-extension:state',
    autoStart: true,
    provides: coreutils_1.IStateDB,
    requires: [application_1.IRouter, apputils_1.IWindowResolver, apputils_1.ISplashScreen],
    activate: (app, router, resolver, splash) => {
        let debouncer;
        let resolved = false;
        const { commands, info, serviceManager } = app;
        const { workspaces } = serviceManager;
        const transform = new coreutils_2.PromiseDelegate();
        const state = new coreutils_1.StateDB({
            namespace: info.namespace,
            transform: transform.promise,
            windowName: resolver.name
        });
        commands.addCommand(CommandIDs.recoverState, {
            execute: ({ global }) => __awaiter(this, void 0, void 0, function* () {
                const immediate = true;
                const silent = true;
                // Clear the state silently so that the state changed signal listener
                // will not be triggered as it causes a save state.
                yield state.clear(silent);
                // If the user explictly chooses to recover state, all of local storage
                // should be cleared.
                if (global) {
                    try {
                        window.localStorage.clear();
                        console.log('Cleared local storage');
                    }
                    catch (error) {
                        console.warn('Clearing local storage failed.', error);
                        // To give the user time to see the console warning before redirect,
                        // do not set the `immediate` flag.
                        return commands.execute(CommandIDs.saveState);
                    }
                }
                return commands.execute(CommandIDs.saveState, { immediate });
            })
        });
        // Conflate all outstanding requests to the save state command that happen
        // within the `WORKSPACE_SAVE_DEBOUNCE_INTERVAL` into a single promise.
        let conflated = null;
        commands.addCommand(CommandIDs.saveState, {
            label: () => `Save Workspace (${app.info.workspace})`,
            execute: ({ immediate }) => {
                const { workspace } = app.info;
                const timeout = immediate ? 0 : WORKSPACE_SAVE_DEBOUNCE_INTERVAL;
                const id = workspace;
                const metadata = { id };
                // Only instantiate a new conflated promise if one is not outstanding.
                if (!conflated) {
                    conflated = new coreutils_2.PromiseDelegate();
                }
                if (debouncer) {
                    window.clearTimeout(debouncer);
                }
                debouncer = window.setTimeout(() => __awaiter(this, void 0, void 0, function* () {
                    // Prevent a race condition between the timeout and saving.
                    if (!conflated) {
                        return;
                    }
                    const data = yield state.toJSON();
                    try {
                        yield workspaces.save(id, { data, metadata });
                        conflated.resolve(undefined);
                    }
                    catch (error) {
                        conflated.reject(error);
                    }
                    conflated = null;
                }), timeout);
                return conflated.promise;
            }
        });
        const listener = (sender, change) => {
            commands.execute(CommandIDs.saveState);
        };
        commands.addCommand(CommandIDs.loadState, {
            execute: (args) => __awaiter(this, void 0, void 0, function* () {
                // Since the command can be executed an arbitrary number of times, make
                // sure it is safe to call multiple times.
                if (resolved) {
                    return;
                }
                const { hash, path, search } = args;
                const { defaultWorkspace, workspace } = app.info;
                const query = coreutils_1.URLExt.queryStringToObject(search || '');
                const clone = typeof query['clone'] === 'string'
                    ? query['clone'] === ''
                        ? defaultWorkspace
                        : coreutils_1.URLExt.join(coreutils_1.PageConfig.getOption('baseUrl'), coreutils_1.PageConfig.getOption('workspacesUrl'), query['clone'])
                    : null;
                const source = clone || workspace;
                try {
                    const saved = yield workspaces.fetch(source);
                    // If this command is called after a reset, the state database
                    // will already be resolved.
                    if (!resolved) {
                        resolved = true;
                        transform.resolve({ type: 'overwrite', contents: saved.data });
                    }
                }
                catch (error) {
                    console.warn(`Fetching workspace (${workspace}) failed:`, error);
                    // If the workspace does not exist, cancel the data transformation
                    // and save a workspace with the current user state data.
                    if (!resolved) {
                        resolved = true;
                        transform.resolve({ type: 'cancel', contents: null });
                    }
                }
                // Any time the local state database changes, save the workspace.
                if (workspace) {
                    state.changed.connect(listener, state);
                }
                const immediate = true;
                if (source === clone) {
                    // Maintain the query string parameters but remove `clone`.
                    delete query['clone'];
                    const url = path + coreutils_1.URLExt.objectToQueryString(query) + hash;
                    const cloned = commands
                        .execute(CommandIDs.saveState, { immediate })
                        .then(() => router.stop);
                    // After the state has been cloned, navigate to the URL.
                    cloned.then(() => {
                        console.log(`HERE: ${url}`);
                        router.navigate(url, { silent: true });
                    });
                    return cloned;
                }
                // After the state database has finished loading, save it.
                return commands.execute(CommandIDs.saveState, { immediate });
            })
        });
        router.register({
            command: CommandIDs.loadState,
            pattern: /.?/,
            rank: 20 // Very high priority: 20/100.
        });
        commands.addCommand(CommandIDs.reset, {
            label: 'Reset Application State',
            execute: () => __awaiter(this, void 0, void 0, function* () {
                const global = true;
                try {
                    yield commands.execute(CommandIDs.recoverState, { global });
                }
                catch (error) {
                    /* Ignore failures and redirect. */
                }
                router.reload();
            })
        });
        commands.addCommand(CommandIDs.resetOnLoad, {
            execute: (args) => {
                const { hash, path, search } = args;
                const query = coreutils_1.URLExt.queryStringToObject(search || '');
                const reset = 'reset' in query;
                const clone = 'clone' in query;
                if (!reset) {
                    return;
                }
                const loading = splash.show();
                // If the state database has already been resolved, resetting is
                // impossible without reloading.
                if (resolved) {
                    return router.reload();
                }
                // Empty the state database.
                resolved = true;
                transform.resolve({ type: 'clear', contents: null });
                // Maintain the query string parameters but remove `reset`.
                delete query['reset'];
                const silent = true;
                const hard = true;
                const url = path + coreutils_1.URLExt.objectToQueryString(query) + hash;
                const cleared = commands
                    .execute(CommandIDs.recoverState)
                    .then(() => router.stop); // Stop routing before new route navigation.
                // After the state has been reset, navigate to the URL.
                if (clone) {
                    cleared.then(() => {
                        router.navigate(url, { silent, hard });
                    });
                }
                else {
                    cleared.then(() => {
                        router.navigate(url, { silent });
                        loading.dispose();
                    });
                }
                return cleared;
            }
        });
        router.register({
            command: CommandIDs.resetOnLoad,
            pattern: Patterns.resetOnLoad,
            rank: 10 // Set reset rank at a higher priority than the default 100.
        });
        // Clean up state database when the window unloads.
        window.addEventListener('beforeunload', () => {
            const silent = true;
            state.clear(silent).catch(() => {
                /* no-op */
            });
        });
        return state;
    }
};
/**
 * Export the plugins as default.
 */
const plugins = [
    palette,
    paletteRestorer,
    resolver,
    settings,
    state,
    splash,
    themes
];
exports.default = plugins;
/**
 * The namespace for module private data.
 */
var Private;
(function (Private) {
    /**
     * Create a splash element.
     */
    function createSplash() {
        const splash = document.createElement('div');
        const galaxy = document.createElement('div');
        const logo = document.createElement('div');
        splash.id = 'jupyterlab-splash';
        galaxy.id = 'galaxy';
        logo.id = 'main-logo';
        galaxy.appendChild(logo);
        ['1', '2', '3'].forEach(id => {
            const moon = document.createElement('div');
            const planet = document.createElement('div');
            moon.id = `moon${id}`;
            moon.className = 'moon orbit';
            planet.id = `planet${id}`;
            planet.className = 'planet';
            moon.appendChild(planet);
            galaxy.appendChild(moon);
        });
        splash.appendChild(galaxy);
        return splash;
    }
    /**
     * A debouncer for recovery attempts.
     */
    let debouncer = 0;
    /**
     * The recovery dialog.
     */
    let dialog;
    /**
     * Allows the user to clear state if splash screen takes too long.
     */
    function recover(fn) {
        if (dialog) {
            return;
        }
        dialog = new apputils_1.Dialog({
            title: 'Loading...',
            body: `The loading screen is taking a long time.
        Would you like to clear the workspace or keep waiting?`,
            buttons: [
                apputils_1.Dialog.cancelButton({ label: 'Keep Waiting' }),
                apputils_1.Dialog.warnButton({ label: 'Clear Workspace' })
            ]
        });
        dialog
            .launch()
            .then(result => {
            if (result.button.accept) {
                return fn();
            }
            dialog.dispose();
            dialog = null;
            debouncer = window.setTimeout(() => {
                recover(fn);
            }, SPLASH_RECOVER_TIMEOUT);
        })
            .catch(() => {
            /* no-op */
        });
    }
    /**
     * Allows the user to clear state if splash screen takes too long.
     */
    function redirect(router, warn = false) {
        return __awaiter(this, void 0, void 0, function* () {
            const form = redirect_1.createRedirectForm(warn);
            const dialog = new apputils_1.Dialog({
                title: 'Please use a different workspace.',
                body: form,
                focusNodeSelector: 'input',
                buttons: [apputils_1.Dialog.okButton({ label: 'Switch Workspace' })]
            });
            const result = yield dialog.launch();
            dialog.dispose();
            if (!result.value) {
                return redirect(router, true);
            }
            // Navigate to a new workspace URL and abandon this session altogether.
            const workspaces = coreutils_1.PageConfig.getOption('workspacesUrl');
            const url = coreutils_1.URLExt.join(workspaces, result.value);
            router.navigate(url, { hard: true, silent: true });
            // This promise will never resolve because the application navigates
            // away to a new location. It only exists to satisfy the return type
            // of the `redirect` function.
            return new Promise(() => undefined);
        });
    }
    Private.redirect = redirect;
    /**
     * The splash element.
     */
    const splash = createSplash();
    /**
     * The splash screen counter.
     */
    let splashCount = 0;
    /**
     * Show the splash element.
     *
     * @param ready - A promise that must be resolved before splash disappears.
     *
     * @param recovery - A command that recovers from a hanging splash.
     */
    function showSplash(ready, commands, recovery, light) {
        splash.classList.remove('splash-fade');
        splash.classList.toggle('light', light);
        splash.classList.toggle('dark', !light);
        splashCount++;
        if (debouncer) {
            window.clearTimeout(debouncer);
        }
        debouncer = window.setTimeout(() => {
            if (commands.hasCommand(recovery)) {
                recover(() => {
                    commands.execute(recovery);
                });
            }
        }, SPLASH_RECOVER_TIMEOUT);
        document.body.appendChild(splash);
        return new disposable_1.DisposableDelegate(() => {
            ready.then(() => {
                if (--splashCount === 0) {
                    if (debouncer) {
                        window.clearTimeout(debouncer);
                        debouncer = 0;
                    }
                    if (dialog) {
                        dialog.dispose();
                        dialog = null;
                    }
                    splash.classList.add('splash-fade');
                    window.setTimeout(() => {
                        document.body.removeChild(splash);
                    }, 500);
                }
            });
        });
    }
    Private.showSplash = showSplash;
})(Private || (Private = {}));


/***/ }),

/***/ "eaoh":
/*!*************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_a-function.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = function (it) {
  if (typeof it != 'function') throw TypeError(it + ' is not a function!');
  return it;
};


/***/ }),

/***/ "eay7":
/*!*********************************************************!*\
  !*** ./node_modules/@phosphor/coreutils/lib/promise.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * A class which wraps a promise into a delegate object.
 *
 * #### Notes
 * This class is useful when the logic to resolve or reject a promise
 * cannot be defined at the point where the promise is created.
 */
var PromiseDelegate = (function () {
    /**
     * Construct a new promise delegate.
     */
    function PromiseDelegate() {
        var _this = this;
        this.promise = new Promise(function (resolve, reject) {
            _this._resolve = resolve;
            _this._reject = reject;
        });
    }
    /**
     * Resolve the wrapped promise with the given value.
     *
     * @param value - The value to use for resolving the promise.
     */
    PromiseDelegate.prototype.resolve = function (value) {
        var resolve = this._resolve;
        resolve(value);
    };
    /**
     * Reject the wrapped promise with the given value.
     *
     * @reason - The reason for rejecting the promise.
     */
    PromiseDelegate.prototype.reject = function (reason) {
        var reject = this._reject;
        reject(reason);
    };
    return PromiseDelegate;
}());
exports.PromiseDelegate = PromiseDelegate;


/***/ }),

/***/ "ebwN":
/*!*************************************!*\
  !*** ./node_modules/lodash/_Map.js ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getNative = __webpack_require__(/*! ./_getNative */ "Cwc5"),
    root = __webpack_require__(/*! ./_root */ "Kz5y");

/* Built-in method references that are verified to be native. */
var Map = getNative(root, 'Map');

module.exports = Map;


/***/ }),

/***/ "eeV2":
/*!*******************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/AxisInterval.js ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UnconnectedAxisInterval = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _Dropdown = __webpack_require__(/*! ../widgets/Dropdown */ "9Rtb");

var _Dropdown2 = _interopRequireDefault(_Dropdown);

var _NumericInput = __webpack_require__(/*! ../widgets/NumericInput */ "2NAh");

var _NumericInput2 = _interopRequireDefault(_NumericInput);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _lib2 = __webpack_require__(/*! plotly.js/src/lib */ "/CZE");

var _dates = __webpack_require__(/*! plotly.js/src/lib/dates */ "Zhzs");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var MILLISECONDS_IN_SECOND = 1000;
var MILLISECONDS_IN_MINUTE = MILLISECONDS_IN_SECOND * 60; // eslint-disable-line
var MILLISECONDS_IN_DAY = MILLISECONDS_IN_MINUTE * 60 * 24; // eslint-disable-line
var DAYS_IN_MONTH = 30;
var MONTHS_IN_YEAR = 12; //eslint-disable-line

function twoDecimalsRound(value) {
  return Math.round(value * 100) / 100;
}

function getSmallestUnit(milliseconds) {
  var units = {
    seconds: MILLISECONDS_IN_SECOND,
    minutes: MILLISECONDS_IN_MINUTE,
    days: MILLISECONDS_IN_DAY
  };

  var smallestUnit = 'milliseconds';

  ['seconds', 'minutes', 'days'].forEach(function (unit) {
    if (milliseconds % units[unit] === 0 && (smallestUnit === 'milliseconds' || smallestUnit !== 'milliseconds' && milliseconds / units[smallestUnit] > milliseconds / units[unit])) {
      smallestUnit = unit;
    }
  });

  return smallestUnit;
}

var UnconnectedAxisInterval = exports.UnconnectedAxisInterval = function (_Component) {
  _inherits(UnconnectedAxisInterval, _Component);

  function UnconnectedAxisInterval(props) {
    _classCallCheck(this, UnconnectedAxisInterval);

    var _this = _possibleConstructorReturn(this, (UnconnectedAxisInterval.__proto__ || Object.getPrototypeOf(UnconnectedAxisInterval)).call(this, props));

    var initialUnit = props.fullValue && typeof props.fullValue === 'string' && props.fullValue[0] === 'M' ? parseInt(props.fullValue.substring(1), 10) % MONTHS_IN_YEAR === 0 ? 'years' : 'months' : getSmallestUnit(props.fullValue);

    _this.state = {
      units: initialUnit
    };
    return _this;
  }

  _createClass(UnconnectedAxisInterval, [{
    key: 'update',
    value: function update(value) {
      var adjustedValue = value < 0 ? 0 : value;
      var isValueInteger = adjustedValue % 1 === 0;

      if (this.state.units === 'years') {
        if (isValueInteger) {
          adjustedValue = 'M' + adjustedValue * MONTHS_IN_YEAR;
        } else {
          adjustedValue = adjustedValue * MONTHS_IN_YEAR * DAYS_IN_MONTH * MILLISECONDS_IN_DAY;
        }
      }

      if (this.state.units === 'months') {
        if (isValueInteger) {
          adjustedValue = 'M' + adjustedValue;
        } else {
          adjustedValue = adjustedValue * DAYS_IN_MONTH * MILLISECONDS_IN_DAY;
        }
      }

      if (this.state.units === 'days') {
        adjustedValue = adjustedValue * MILLISECONDS_IN_DAY;
      }

      if (this.state.units === 'minutes') {
        adjustedValue = adjustedValue * MILLISECONDS_IN_MINUTE;
      }

      if (this.state.units === 'seconds') {
        adjustedValue = adjustedValue * MILLISECONDS_IN_SECOND;
      }

      this.props.updatePlot(adjustedValue);
    }
  }, {
    key: 'onUnitChange',
    value: function onUnitChange(value) {
      var isFullValueMonthFormat = typeof this.props.fullValue === 'string' && this.props.fullValue[0] === 'M';

      var milliseconds = isFullValueMonthFormat ? parseInt(this.props.fullValue.substring(1), 10) * DAYS_IN_MONTH * MILLISECONDS_IN_DAY : this.props.fullValue;

      this.setState({ units: value });

      if (['years', 'months'].includes(value)) {
        var nbMonths = milliseconds / MILLISECONDS_IN_DAY / DAYS_IN_MONTH;
        if (nbMonths % 1 === 0) {
          this.props.updatePlot('M' + nbMonths);
        } else {
          this.props.updatePlot(milliseconds);
        }
      } else {
        this.props.updatePlot(milliseconds);
      }
    }
  }, {
    key: 'getDisplayValue',
    value: function getDisplayValue(value) {
      var numericValue = typeof value === 'string' && value[0] === 'M' ? parseInt(value.substring(1), 10) : value;

      if (this.state.units === 'years') {
        if (typeof value === 'string') {
          return twoDecimalsRound(numericValue / MONTHS_IN_YEAR);
        }
        return twoDecimalsRound(numericValue / MILLISECONDS_IN_DAY / DAYS_IN_MONTH / MONTHS_IN_YEAR);
      }
      if (this.state.units === 'months') {
        if (typeof value === 'string') {
          return twoDecimalsRound(numericValue);
        }
        return twoDecimalsRound(numericValue / MILLISECONDS_IN_DAY / DAYS_IN_MONTH);
      }
      if (this.state.units === 'days') {
        return twoDecimalsRound(numericValue / MILLISECONDS_IN_DAY);
      }
      if (this.state.units === 'minutes') {
        return twoDecimalsRound(numericValue / MILLISECONDS_IN_MINUTE);
      }
      if (this.state.units === 'seconds') {
        return twoDecimalsRound(numericValue / MILLISECONDS_IN_SECOND);
      }
      if (this.state.units === 'milliseconds') {
        return numericValue;
      }
      return null;
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _ = this.context.localize;
      var attrHead = this.props.attr.split('.')[0];
      var binStartValue = this.props.fullContainer[attrHead].start;
      var BinStartIsDate = typeof binStartValue === 'string' && ((0, _lib2.isDateTime)(binStartValue) || (0, _dates.isJSDate)(binStartValue));
      var tick0 = this.props.fullContainer.tick0 && (this.props.fullContainer.tick0 || this.props.fullContainer.colorbar.tick0);
      var tick0IsDate = tick0 && ((0, _lib2.isDateTime)(tick0) || (0, _dates.isJSDate)(tick0));

      return BinStartIsDate || tick0IsDate ? _react2.default.createElement(
        _Field2.default,
        this.props,
        _react2.default.createElement(_Dropdown2.default, {
          options: [{ value: 'years', label: _('Years') }, { value: 'months', label: _('Months') }, { value: 'days', label: _('Days') }, { value: 'minutes', label: _('Minutes') }, { value: 'seconds', label: _('Seconds') }, { value: 'milliseconds', label: _('Milliseconds') }],
          clearable: false,
          onChange: function onChange(value) {
            return _this2.onUnitChange(value);
          },
          value: this.state.units
        }),
        _react2.default.createElement(
          'div',
          { style: { width: '100%', display: 'block' } },
          ' '
        ),
        _react2.default.createElement(_NumericInput2.default, {
          value: this.getDisplayValue(this.props.fullValue),
          onUpdate: function onUpdate(value) {
            return _this2.update(value);
          },
          editableClassName: 'AxisInterval-milliseconds'
        })
      ) : _react2.default.createElement(
        _Field2.default,
        this.props,
        _react2.default.createElement(_NumericInput2.default, {
          value: this.props.fullValue,
          onUpdate: function onUpdate(value) {
            return _this2.props.updatePlot(value);
          }
        })
      );
    }
  }]);

  return UnconnectedAxisInterval;
}(_react.Component);

UnconnectedAxisInterval.contextTypes = {
  localize: _propTypes2.default.func
};

UnconnectedAxisInterval.propTypes = _extends({
  fullValue: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.string]),
  updatePlot: _propTypes2.default.func,
  attr: _propTypes2.default.string,
  fullContainer: _propTypes2.default.object
}, _Field2.default.propTypes);

exports.default = (0, _lib.connectToContainer)(UnconnectedAxisInterval);
//# sourceMappingURL=AxisInterval.js.map

/***/ }),

/***/ "ehAg":
/*!*********************************************!*\
  !*** ./node_modules/miller-rabin/lib/mr.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var bn = __webpack_require__(/*! bn.js */ "OZ/i");
var brorand = __webpack_require__(/*! brorand */ "/ayr");

function MillerRabin(rand) {
  this.rand = rand || new brorand.Rand();
}
module.exports = MillerRabin;

MillerRabin.create = function create(rand) {
  return new MillerRabin(rand);
};

MillerRabin.prototype._randbelow = function _randbelow(n) {
  var len = n.bitLength();
  var min_bytes = Math.ceil(len / 8);

  // Generage random bytes until a number less than n is found.
  // This ensures that 0..n-1 have an equal probability of being selected.
  do
    var a = new bn(this.rand.generate(min_bytes));
  while (a.cmp(n) >= 0);

  return a;
};

MillerRabin.prototype._randrange = function _randrange(start, stop) {
  // Generate a random number greater than or equal to start and less than stop.
  var size = stop.sub(start);
  return start.add(this._randbelow(size));
};

MillerRabin.prototype.test = function test(n, k, cb) {
  var len = n.bitLength();
  var red = bn.mont(n);
  var rone = new bn(1).toRed(red);

  if (!k)
    k = Math.max(1, (len / 48) | 0);

  // Find d and s, (n - 1) = (2 ^ s) * d;
  var n1 = n.subn(1);
  for (var s = 0; !n1.testn(s); s++) {}
  var d = n.shrn(s);

  var rn1 = n1.toRed(red);

  var prime = true;
  for (; k > 0; k--) {
    var a = this._randrange(new bn(2), n1);
    if (cb)
      cb(a);

    var x = a.toRed(red).redPow(d);
    if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
      continue;

    for (var i = 1; i < s; i++) {
      x = x.redSqr();

      if (x.cmp(rone) === 0)
        return false;
      if (x.cmp(rn1) === 0)
        break;
    }

    if (i === s)
      return false;
  }

  return prime;
};

MillerRabin.prototype.getDivisor = function getDivisor(n, k) {
  var len = n.bitLength();
  var red = bn.mont(n);
  var rone = new bn(1).toRed(red);

  if (!k)
    k = Math.max(1, (len / 48) | 0);

  // Find d and s, (n - 1) = (2 ^ s) * d;
  var n1 = n.subn(1);
  for (var s = 0; !n1.testn(s); s++) {}
  var d = n.shrn(s);

  var rn1 = n1.toRed(red);

  for (; k > 0; k--) {
    var a = this._randrange(new bn(2), n1);

    var g = n.gcd(a);
    if (g.cmpn(1) !== 0)
      return g;

    var x = a.toRed(red).redPow(d);
    if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
      continue;

    for (var i = 1; i < s; i++) {
      x = x.redSqr();

      if (x.cmp(rone) === 0)
        return x.fromRed().subn(1).gcd(n);
      if (x.cmp(rn1) === 0)
        break;
    }

    if (i === s) {
      x = x.redSqr();
      return x.fromRed().subn(1).gcd(n);
    }
  }

  return false;
};


/***/ }),

/***/ "eiat":
/*!**********************************************************************!*\
  !*** ./node_modules/@jupyterlab/observables/lib/observablestring.js ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
/**
 * A concrete implementation of [[IObservableString]]
 */
class ObservableString {
    /**
     * Construct a new observable string.
     */
    constructor(initialText = '') {
        this._text = '';
        this._isDisposed = false;
        this._changed = new signaling_1.Signal(this);
        this._text = initialText;
    }
    /**
     * The type of the Observable.
     */
    get type() {
        return 'String';
    }
    /**
     * A signal emitted when the string has changed.
     */
    get changed() {
        return this._changed;
    }
    /**
     * Set the value of the string.
     */
    set text(value) {
        if (value.length === this._text.length && value === this._text) {
            return;
        }
        this._text = value;
        this._changed.emit({
            type: 'set',
            start: 0,
            end: value.length,
            value: value
        });
    }
    /**
     * Get the value of the string.
     */
    get text() {
        return this._text;
    }
    /**
     * Insert a substring.
     *
     * @param index - The starting index.
     *
     * @param text - The substring to insert.
     */
    insert(index, text) {
        this._text = this._text.slice(0, index) + text + this._text.slice(index);
        this._changed.emit({
            type: 'insert',
            start: index,
            end: index + text.length,
            value: text
        });
    }
    /**
     * Remove a substring.
     *
     * @param start - The starting index.
     *
     * @param end - The ending index.
     */
    remove(start, end) {
        let oldValue = this._text.slice(start, end);
        this._text = this._text.slice(0, start) + this._text.slice(end);
        this._changed.emit({
            type: 'remove',
            start: start,
            end: end,
            value: oldValue
        });
    }
    /**
     * Set the ObservableString to an empty string.
     */
    clear() {
        this.text = '';
    }
    /**
     * Test whether the string has been disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources held by the string.
     */
    dispose() {
        if (this._isDisposed) {
            return;
        }
        this._isDisposed = true;
        signaling_1.Signal.clearData(this);
        this.clear();
    }
}
exports.ObservableString = ObservableString;


/***/ }),

/***/ "ejln":
/*!***************************************************!*\
  !*** ./node_modules/domutils/lib/manipulation.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

exports.removeElement = function(elem){
	if(elem.prev) elem.prev.next = elem.next;
	if(elem.next) elem.next.prev = elem.prev;

	if(elem.parent){
		var childs = elem.parent.children;
		childs.splice(childs.lastIndexOf(elem), 1);
	}
};

exports.replaceElement = function(elem, replacement){
	var prev = replacement.prev = elem.prev;
	if(prev){
		prev.next = replacement;
	}

	var next = replacement.next = elem.next;
	if(next){
		next.prev = replacement;
	}

	var parent = replacement.parent = elem.parent;
	if(parent){
		var childs = parent.children;
		childs[childs.lastIndexOf(elem)] = replacement;
	}
};

exports.appendChild = function(elem, child){
	child.parent = elem;

	if(elem.children.push(child) !== 1){
		var sibling = elem.children[elem.children.length - 2];
		sibling.next = child;
		child.prev = sibling;
		child.next = null;
	}
};

exports.append = function(elem, next){
	var parent = elem.parent,
		currNext = elem.next;

	next.next = currNext;
	next.prev = elem;
	elem.next = next;
	next.parent = parent;

	if(currNext){
		currNext.prev = next;
		if(parent){
			var childs = parent.children;
			childs.splice(childs.lastIndexOf(currNext), 0, next);
		}
	} else if(parent){
		parent.children.push(next);
	}
};

exports.prepend = function(elem, prev){
	var parent = elem.parent;
	if(parent){
		var childs = parent.children;
		childs.splice(childs.lastIndexOf(elem), 0, prev);
	}

	if(elem.prev){
		elem.prev.next = prev;
	}
	
	prev.parent = parent;
	prev.prev = elem.prev;
	prev.next = elem;
	elem.prev = prev;
};




/***/ }),

/***/ "ekgI":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_hashHas.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var nativeCreate = __webpack_require__(/*! ./_nativeCreate */ "YESw");

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * 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);
}

module.exports = hashHas;


/***/ }),

/***/ "euxk":
/*!***********************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/vendor.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
/**
 * Contains helpers for working with vendor prefixes.
 *
 * @example
 * const vendor = postcss.vendor;
 *
 * @namespace vendor
 */
var vendor = {

    /**
     * Returns the vendor prefix extracted from an input string.
     *
     * @param {string} prop - string with or without vendor prefix
     *
     * @return {string} vendor prefix or empty string
     *
     * @example
     * postcss.vendor.prefix('-moz-tab-size') //=> '-moz-'
     * postcss.vendor.prefix('tab-size')      //=> ''
     */
    prefix: function prefix(prop) {
        var match = prop.match(/^(-\w+-)/);
        if (match) {
            return match[0];
        } else {
            return '';
        }
    },


    /**
     * Returns the input string stripped of its vendor prefix.
     *
     * @param {string} prop - string with or without vendor prefix
     *
     * @return {string} string name without vendor prefixes
     *
     * @example
     * postcss.vendor.unprefixed('-moz-tab-size') //=> 'tab-size'
     */
    unprefixed: function unprefixed(prop) {
        return prop.replace(/^-\w+-/, '');
    }
};

exports.default = vendor;
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInZlbmRvci5lczYiXSwibmFtZXMiOlsidmVuZG9yIiwicHJlZml4IiwicHJvcCIsIm1hdGNoIiwidW5wcmVmaXhlZCIsInJlcGxhY2UiXSwibWFwcGluZ3MiOiI7OztBQUFBOzs7Ozs7OztBQVFBLElBQUlBLFNBQVM7O0FBRVQ7Ozs7Ozs7Ozs7O0FBV0FDLFVBYlMsa0JBYUZDLElBYkUsRUFhSTtBQUNULFlBQUlDLFFBQVFELEtBQUtDLEtBQUwsQ0FBVyxVQUFYLENBQVo7QUFDQSxZQUFLQSxLQUFMLEVBQWE7QUFDVCxtQkFBT0EsTUFBTSxDQUFOLENBQVA7QUFDSCxTQUZELE1BRU87QUFDSCxtQkFBTyxFQUFQO0FBQ0g7QUFDSixLQXBCUTs7O0FBc0JUOzs7Ozs7Ozs7O0FBVUFDLGNBaENTLHNCQWdDRUYsSUFoQ0YsRUFnQ1E7QUFDYixlQUFPQSxLQUFLRyxPQUFMLENBQWEsUUFBYixFQUF1QixFQUF2QixDQUFQO0FBQ0g7QUFsQ1EsQ0FBYjs7a0JBc0NlTCxNIiwiZmlsZSI6InZlbmRvci5qcyIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQ29udGFpbnMgaGVscGVycyBmb3Igd29ya2luZyB3aXRoIHZlbmRvciBwcmVmaXhlcy5cbiAqXG4gKiBAZXhhbXBsZVxuICogY29uc3QgdmVuZG9yID0gcG9zdGNzcy52ZW5kb3I7XG4gKlxuICogQG5hbWVzcGFjZSB2ZW5kb3JcbiAqL1xubGV0IHZlbmRvciA9IHtcblxuICAgIC8qKlxuICAgICAqIFJldHVybnMgdGhlIHZlbmRvciBwcmVmaXggZXh0cmFjdGVkIGZyb20gYW4gaW5wdXQgc3RyaW5nLlxuICAgICAqXG4gICAgICogQHBhcmFtIHtzdHJpbmd9IHByb3AgLSBzdHJpbmcgd2l0aCBvciB3aXRob3V0IHZlbmRvciBwcmVmaXhcbiAgICAgKlxuICAgICAqIEByZXR1cm4ge3N0cmluZ30gdmVuZG9yIHByZWZpeCBvciBlbXB0eSBzdHJpbmdcbiAgICAgKlxuICAgICAqIEBleGFtcGxlXG4gICAgICogcG9zdGNzcy52ZW5kb3IucHJlZml4KCctbW96LXRhYi1zaXplJykgLy89PiAnLW1vei0nXG4gICAgICogcG9zdGNzcy52ZW5kb3IucHJlZml4KCd0YWItc2l6ZScpICAgICAgLy89PiAnJ1xuICAgICAqL1xuICAgIHByZWZpeChwcm9wKSB7XG4gICAgICAgIGxldCBtYXRjaCA9IHByb3AubWF0Y2goL14oLVxcdystKS8pO1xuICAgICAgICBpZiAoIG1hdGNoICkge1xuICAgICAgICAgICAgcmV0dXJuIG1hdGNoWzBdO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgcmV0dXJuICcnO1xuICAgICAgICB9XG4gICAgfSxcblxuICAgIC8qKlxuICAgICAqIFJldHVybnMgdGhlIGlucHV0IHN0cmluZyBzdHJpcHBlZCBvZiBpdHMgdmVuZG9yIHByZWZpeC5cbiAgICAgKlxuICAgICAqIEBwYXJhbSB7c3RyaW5nfSBwcm9wIC0gc3RyaW5nIHdpdGggb3Igd2l0aG91dCB2ZW5kb3IgcHJlZml4XG4gICAgICpcbiAgICAgKiBAcmV0dXJuIHtzdHJpbmd9IHN0cmluZyBuYW1lIHdpdGhvdXQgdmVuZG9yIHByZWZpeGVzXG4gICAgICpcbiAgICAgKiBAZXhhbXBsZVxuICAgICAqIHBvc3Rjc3MudmVuZG9yLnVucHJlZml4ZWQoJy1tb3otdGFiLXNpemUnKSAvLz0+ICd0YWItc2l6ZSdcbiAgICAgKi9cbiAgICB1bnByZWZpeGVkKHByb3ApIHtcbiAgICAgICAgcmV0dXJuIHByb3AucmVwbGFjZSgvXi1cXHcrLS8sICcnKTtcbiAgICB9XG5cbn07XG5cbmV4cG9ydCBkZWZhdWx0IHZlbmRvcjtcbiJdfQ==


/***/ }),

/***/ "evZB":
/*!***********************************************!*\
  !*** ./node_modules/fbjs/lib/TokenizeUtil.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks
 * @stub
 * 
 */



// \u00a1-\u00b1\u00b4-\u00b8\u00ba\u00bb\u00bf
//             is latin supplement punctuation except fractions and superscript
//             numbers
// \u2010-\u2027\u2030-\u205e
//             is punctuation from the general punctuation block:
//             weird quotes, commas, bullets, dashes, etc.
// \u30fb\u3001\u3002\u3008-\u3011\u3014-\u301f
//             is CJK punctuation
// \uff1a-\uff1f\uff01-\uff0f\uff3b-\uff40\uff5b-\uff65
//             is some full-width/half-width punctuation
// \u2E2E\u061f\u066a-\u066c\u061b\u060c\u060d\uFD3e\uFD3F
//             is some Arabic punctuation marks
// \u1801\u0964\u104a\u104b
//             is misc. other language punctuation marks

var PUNCTUATION = '[.,+*?$|#{}()\'\\^\\-\\[\\]\\\\\\/!@%"~=<>_:;' + '\u30FB\u3001\u3002\u3008-\u3011\u3014-\u301F\uFF1A-\uFF1F\uFF01-\uFF0F' + '\uFF3B-\uFF40\uFF5B-\uFF65\u2E2E\u061F\u066A-\u066C\u061B\u060C\u060D' + '\uFD3E\uFD3F\u1801\u0964\u104A\u104B\u2010-\u2027\u2030-\u205E' + '\xA1-\xB1\xB4-\xB8\xBA\xBB\xBF]';

module.exports = {
  getPunctuation: function getPunctuation() {
    return PUNCTUATION;
  }
};

/***/ }),

/***/ "ewDg":
/*!*************************************************!*\
  !*** ./node_modules/codemirror/mode/css/css.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"));
  else {}
})(function(CodeMirror) {
"use strict";

CodeMirror.defineMode("css", function(config, parserConfig) {
  var inline = parserConfig.inline
  if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css");

  var indentUnit = config.indentUnit,
      tokenHooks = parserConfig.tokenHooks,
      documentTypes = parserConfig.documentTypes || {},
      mediaTypes = parserConfig.mediaTypes || {},
      mediaFeatures = parserConfig.mediaFeatures || {},
      mediaValueKeywords = parserConfig.mediaValueKeywords || {},
      propertyKeywords = parserConfig.propertyKeywords || {},
      nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {},
      fontProperties = parserConfig.fontProperties || {},
      counterDescriptors = parserConfig.counterDescriptors || {},
      colorKeywords = parserConfig.colorKeywords || {},
      valueKeywords = parserConfig.valueKeywords || {},
      allowNested = parserConfig.allowNested,
      lineComment = parserConfig.lineComment,
      supportsAtComponent = parserConfig.supportsAtComponent === true;

  var type, override;
  function ret(style, tp) { type = tp; return style; }

  // Tokenizers

  function tokenBase(stream, state) {
    var ch = stream.next();
    if (tokenHooks[ch]) {
      var result = tokenHooks[ch](stream, state);
      if (result !== false) return result;
    }
    if (ch == "@") {
      stream.eatWhile(/[\w\\\-]/);
      return ret("def", stream.current());
    } else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) {
      return ret(null, "compare");
    } else if (ch == "\"" || ch == "'") {
      state.tokenize = tokenString(ch);
      return state.tokenize(stream, state);
    } else if (ch == "#") {
      stream.eatWhile(/[\w\\\-]/);
      return ret("atom", "hash");
    } else if (ch == "!") {
      stream.match(/^\s*\w*/);
      return ret("keyword", "important");
    } else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) {
      stream.eatWhile(/[\w.%]/);
      return ret("number", "unit");
    } else if (ch === "-") {
      if (/[\d.]/.test(stream.peek())) {
        stream.eatWhile(/[\w.%]/);
        return ret("number", "unit");
      } else if (stream.match(/^-[\w\\\-]+/)) {
        stream.eatWhile(/[\w\\\-]/);
        if (stream.match(/^\s*:/, false))
          return ret("variable-2", "variable-definition");
        return ret("variable-2", "variable");
      } else if (stream.match(/^\w+-/)) {
        return ret("meta", "meta");
      }
    } else if (/[,+>*\/]/.test(ch)) {
      return ret(null, "select-op");
    } else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) {
      return ret("qualifier", "qualifier");
    } else if (/[:;{}\[\]\(\)]/.test(ch)) {
      return ret(null, ch);
    } else if (((ch == "u" || ch == "U") && stream.match(/rl(-prefix)?\(/i)) ||
               ((ch == "d" || ch == "D") && stream.match("omain(", true, true)) ||
               ((ch == "r" || ch == "R") && stream.match("egexp(", true, true))) {
      stream.backUp(1);
      state.tokenize = tokenParenthesized;
      return ret("property", "word");
    } else if (/[\w\\\-]/.test(ch)) {
      stream.eatWhile(/[\w\\\-]/);
      return ret("property", "word");
    } else {
      return ret(null, null);
    }
  }

  function tokenString(quote) {
    return function(stream, state) {
      var escaped = false, ch;
      while ((ch = stream.next()) != null) {
        if (ch == quote && !escaped) {
          if (quote == ")") stream.backUp(1);
          break;
        }
        escaped = !escaped && ch == "\\";
      }
      if (ch == quote || !escaped && quote != ")") state.tokenize = null;
      return ret("string", "string");
    };
  }

  function tokenParenthesized(stream, state) {
    stream.next(); // Must be '('
    if (!stream.match(/\s*[\"\')]/, false))
      state.tokenize = tokenString(")");
    else
      state.tokenize = null;
    return ret(null, "(");
  }

  // Context management

  function Context(type, indent, prev) {
    this.type = type;
    this.indent = indent;
    this.prev = prev;
  }

  function pushContext(state, stream, type, indent) {
    state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context);
    return type;
  }

  function popContext(state) {
    if (state.context.prev)
      state.context = state.context.prev;
    return state.context.type;
  }

  function pass(type, stream, state) {
    return states[state.context.type](type, stream, state);
  }
  function popAndPass(type, stream, state, n) {
    for (var i = n || 1; i > 0; i--)
      state.context = state.context.prev;
    return pass(type, stream, state);
  }

  // Parser

  function wordAsValue(stream) {
    var word = stream.current().toLowerCase();
    if (valueKeywords.hasOwnProperty(word))
      override = "atom";
    else if (colorKeywords.hasOwnProperty(word))
      override = "keyword";
    else
      override = "variable";
  }

  var states = {};

  states.top = function(type, stream, state) {
    if (type == "{") {
      return pushContext(state, stream, "block");
    } else if (type == "}" && state.context.prev) {
      return popContext(state);
    } else if (supportsAtComponent && /@component/i.test(type)) {
      return pushContext(state, stream, "atComponentBlock");
    } else if (/^@(-moz-)?document$/i.test(type)) {
      return pushContext(state, stream, "documentTypes");
    } else if (/^@(media|supports|(-moz-)?document|import)$/i.test(type)) {
      return pushContext(state, stream, "atBlock");
    } else if (/^@(font-face|counter-style)/i.test(type)) {
      state.stateArg = type;
      return "restricted_atBlock_before";
    } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(type)) {
      return "keyframes";
    } else if (type && type.charAt(0) == "@") {
      return pushContext(state, stream, "at");
    } else if (type == "hash") {
      override = "builtin";
    } else if (type == "word") {
      override = "tag";
    } else if (type == "variable-definition") {
      return "maybeprop";
    } else if (type == "interpolation") {
      return pushContext(state, stream, "interpolation");
    } else if (type == ":") {
      return "pseudo";
    } else if (allowNested && type == "(") {
      return pushContext(state, stream, "parens");
    }
    return state.context.type;
  };

  states.block = function(type, stream, state) {
    if (type == "word") {
      var word = stream.current().toLowerCase();
      if (propertyKeywords.hasOwnProperty(word)) {
        override = "property";
        return "maybeprop";
      } else if (nonStandardPropertyKeywords.hasOwnProperty(word)) {
        override = "string-2";
        return "maybeprop";
      } else if (allowNested) {
        override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag";
        return "block";
      } else {
        override += " error";
        return "maybeprop";
      }
    } else if (type == "meta") {
      return "block";
    } else if (!allowNested && (type == "hash" || type == "qualifier")) {
      override = "error";
      return "block";
    } else {
      return states.top(type, stream, state);
    }
  };

  states.maybeprop = function(type, stream, state) {
    if (type == ":") return pushContext(state, stream, "prop");
    return pass(type, stream, state);
  };

  states.prop = function(type, stream, state) {
    if (type == ";") return popContext(state);
    if (type == "{" && allowNested) return pushContext(state, stream, "propBlock");
    if (type == "}" || type == "{") return popAndPass(type, stream, state);
    if (type == "(") return pushContext(state, stream, "parens");

    if (type == "hash" && !/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())) {
      override += " error";
    } else if (type == "word") {
      wordAsValue(stream);
    } else if (type == "interpolation") {
      return pushContext(state, stream, "interpolation");
    }
    return "prop";
  };

  states.propBlock = function(type, _stream, state) {
    if (type == "}") return popContext(state);
    if (type == "word") { override = "property"; return "maybeprop"; }
    return state.context.type;
  };

  states.parens = function(type, stream, state) {
    if (type == "{" || type == "}") return popAndPass(type, stream, state);
    if (type == ")") return popContext(state);
    if (type == "(") return pushContext(state, stream, "parens");
    if (type == "interpolation") return pushContext(state, stream, "interpolation");
    if (type == "word") wordAsValue(stream);
    return "parens";
  };

  states.pseudo = function(type, stream, state) {
    if (type == "meta") return "pseudo";

    if (type == "word") {
      override = "variable-3";
      return state.context.type;
    }
    return pass(type, stream, state);
  };

  states.documentTypes = function(type, stream, state) {
    if (type == "word" && documentTypes.hasOwnProperty(stream.current())) {
      override = "tag";
      return state.context.type;
    } else {
      return states.atBlock(type, stream, state);
    }
  };

  states.atBlock = function(type, stream, state) {
    if (type == "(") return pushContext(state, stream, "atBlock_parens");
    if (type == "}" || type == ";") return popAndPass(type, stream, state);
    if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top");

    if (type == "interpolation") return pushContext(state, stream, "interpolation");

    if (type == "word") {
      var word = stream.current().toLowerCase();
      if (word == "only" || word == "not" || word == "and" || word == "or")
        override = "keyword";
      else if (mediaTypes.hasOwnProperty(word))
        override = "attribute";
      else if (mediaFeatures.hasOwnProperty(word))
        override = "property";
      else if (mediaValueKeywords.hasOwnProperty(word))
        override = "keyword";
      else if (propertyKeywords.hasOwnProperty(word))
        override = "property";
      else if (nonStandardPropertyKeywords.hasOwnProperty(word))
        override = "string-2";
      else if (valueKeywords.hasOwnProperty(word))
        override = "atom";
      else if (colorKeywords.hasOwnProperty(word))
        override = "keyword";
      else
        override = "error";
    }
    return state.context.type;
  };

  states.atComponentBlock = function(type, stream, state) {
    if (type == "}")
      return popAndPass(type, stream, state);
    if (type == "{")
      return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top", false);
    if (type == "word")
      override = "error";
    return state.context.type;
  };

  states.atBlock_parens = function(type, stream, state) {
    if (type == ")") return popContext(state);
    if (type == "{" || type == "}") return popAndPass(type, stream, state, 2);
    return states.atBlock(type, stream, state);
  };

  states.restricted_atBlock_before = function(type, stream, state) {
    if (type == "{")
      return pushContext(state, stream, "restricted_atBlock");
    if (type == "word" && state.stateArg == "@counter-style") {
      override = "variable";
      return "restricted_atBlock_before";
    }
    return pass(type, stream, state);
  };

  states.restricted_atBlock = function(type, stream, state) {
    if (type == "}") {
      state.stateArg = null;
      return popContext(state);
    }
    if (type == "word") {
      if ((state.stateArg == "@font-face" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) ||
          (state.stateArg == "@counter-style" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase())))
        override = "error";
      else
        override = "property";
      return "maybeprop";
    }
    return "restricted_atBlock";
  };

  states.keyframes = function(type, stream, state) {
    if (type == "word") { override = "variable"; return "keyframes"; }
    if (type == "{") return pushContext(state, stream, "top");
    return pass(type, stream, state);
  };

  states.at = function(type, stream, state) {
    if (type == ";") return popContext(state);
    if (type == "{" || type == "}") return popAndPass(type, stream, state);
    if (type == "word") override = "tag";
    else if (type == "hash") override = "builtin";
    return "at";
  };

  states.interpolation = function(type, stream, state) {
    if (type == "}") return popContext(state);
    if (type == "{" || type == ";") return popAndPass(type, stream, state);
    if (type == "word") override = "variable";
    else if (type != "variable" && type != "(" && type != ")") override = "error";
    return "interpolation";
  };

  return {
    startState: function(base) {
      return {tokenize: null,
              state: inline ? "block" : "top",
              stateArg: null,
              context: new Context(inline ? "block" : "top", base || 0, null)};
    },

    token: function(stream, state) {
      if (!state.tokenize && stream.eatSpace()) return null;
      var style = (state.tokenize || tokenBase)(stream, state);
      if (style && typeof style == "object") {
        type = style[1];
        style = style[0];
      }
      override = style;
      if (type != "comment")
        state.state = states[state.state](type, stream, state);
      return override;
    },

    indent: function(state, textAfter) {
      var cx = state.context, ch = textAfter && textAfter.charAt(0);
      var indent = cx.indent;
      if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev;
      if (cx.prev) {
        if (ch == "}" && (cx.type == "block" || cx.type == "top" ||
                          cx.type == "interpolation" || cx.type == "restricted_atBlock")) {
          // Resume indentation from parent context.
          cx = cx.prev;
          indent = cx.indent;
        } else if (ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") ||
            ch == "{" && (cx.type == "at" || cx.type == "atBlock")) {
          // Dedent relative to current context.
          indent = Math.max(0, cx.indent - indentUnit);
        }
      }
      return indent;
    },

    electricChars: "}",
    blockCommentStart: "/*",
    blockCommentEnd: "*/",
    blockCommentContinue: " * ",
    lineComment: lineComment,
    fold: "brace"
  };
});

  function keySet(array) {
    var keys = {};
    for (var i = 0; i < array.length; ++i) {
      keys[array[i].toLowerCase()] = true;
    }
    return keys;
  }

  var documentTypes_ = [
    "domain", "regexp", "url", "url-prefix"
  ], documentTypes = keySet(documentTypes_);

  var mediaTypes_ = [
    "all", "aural", "braille", "handheld", "print", "projection", "screen",
    "tty", "tv", "embossed"
  ], mediaTypes = keySet(mediaTypes_);

  var mediaFeatures_ = [
    "width", "min-width", "max-width", "height", "min-height", "max-height",
    "device-width", "min-device-width", "max-device-width", "device-height",
    "min-device-height", "max-device-height", "aspect-ratio",
    "min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio",
    "min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color",
    "max-color", "color-index", "min-color-index", "max-color-index",
    "monochrome", "min-monochrome", "max-monochrome", "resolution",
    "min-resolution", "max-resolution", "scan", "grid", "orientation",
    "device-pixel-ratio", "min-device-pixel-ratio", "max-device-pixel-ratio",
    "pointer", "any-pointer", "hover", "any-hover"
  ], mediaFeatures = keySet(mediaFeatures_);

  var mediaValueKeywords_ = [
    "landscape", "portrait", "none", "coarse", "fine", "on-demand", "hover",
    "interlace", "progressive"
  ], mediaValueKeywords = keySet(mediaValueKeywords_);

  var propertyKeywords_ = [
    "align-content", "align-items", "align-self", "alignment-adjust",
    "alignment-baseline", "anchor-point", "animation", "animation-delay",
    "animation-direction", "animation-duration", "animation-fill-mode",
    "animation-iteration-count", "animation-name", "animation-play-state",
    "animation-timing-function", "appearance", "azimuth", "backface-visibility",
    "background", "background-attachment", "background-blend-mode", "background-clip",
    "background-color", "background-image", "background-origin", "background-position",
    "background-repeat", "background-size", "baseline-shift", "binding",
    "bleed", "bookmark-label", "bookmark-level", "bookmark-state",
    "bookmark-target", "border", "border-bottom", "border-bottom-color",
    "border-bottom-left-radius", "border-bottom-right-radius",
    "border-bottom-style", "border-bottom-width", "border-collapse",
    "border-color", "border-image", "border-image-outset",
    "border-image-repeat", "border-image-slice", "border-image-source",
    "border-image-width", "border-left", "border-left-color",
    "border-left-style", "border-left-width", "border-radius", "border-right",
    "border-right-color", "border-right-style", "border-right-width",
    "border-spacing", "border-style", "border-top", "border-top-color",
    "border-top-left-radius", "border-top-right-radius", "border-top-style",
    "border-top-width", "border-width", "bottom", "box-decoration-break",
    "box-shadow", "box-sizing", "break-after", "break-before", "break-inside",
    "caption-side", "caret-color", "clear", "clip", "color", "color-profile", "column-count",
    "column-fill", "column-gap", "column-rule", "column-rule-color",
    "column-rule-style", "column-rule-width", "column-span", "column-width",
    "columns", "content", "counter-increment", "counter-reset", "crop", "cue",
    "cue-after", "cue-before", "cursor", "direction", "display",
    "dominant-baseline", "drop-initial-after-adjust",
    "drop-initial-after-align", "drop-initial-before-adjust",
    "drop-initial-before-align", "drop-initial-size", "drop-initial-value",
    "elevation", "empty-cells", "fit", "fit-position", "flex", "flex-basis",
    "flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap",
    "float", "float-offset", "flow-from", "flow-into", "font", "font-feature-settings",
    "font-family", "font-kerning", "font-language-override", "font-size", "font-size-adjust",
    "font-stretch", "font-style", "font-synthesis", "font-variant",
    "font-variant-alternates", "font-variant-caps", "font-variant-east-asian",
    "font-variant-ligatures", "font-variant-numeric", "font-variant-position",
    "font-weight", "grid", "grid-area", "grid-auto-columns", "grid-auto-flow",
    "grid-auto-rows", "grid-column", "grid-column-end", "grid-column-gap",
    "grid-column-start", "grid-gap", "grid-row", "grid-row-end", "grid-row-gap",
    "grid-row-start", "grid-template", "grid-template-areas", "grid-template-columns",
    "grid-template-rows", "hanging-punctuation", "height", "hyphens",
    "icon", "image-orientation", "image-rendering", "image-resolution",
    "inline-box-align", "justify-content", "justify-items", "justify-self", "left", "letter-spacing",
    "line-break", "line-height", "line-stacking", "line-stacking-ruby",
    "line-stacking-shift", "line-stacking-strategy", "list-style",
    "list-style-image", "list-style-position", "list-style-type", "margin",
    "margin-bottom", "margin-left", "margin-right", "margin-top",
    "marks", "marquee-direction", "marquee-loop",
    "marquee-play-count", "marquee-speed", "marquee-style", "max-height",
    "max-width", "min-height", "min-width", "move-to", "nav-down", "nav-index",
    "nav-left", "nav-right", "nav-up", "object-fit", "object-position",
    "opacity", "order", "orphans", "outline",
    "outline-color", "outline-offset", "outline-style", "outline-width",
    "overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y",
    "padding", "padding-bottom", "padding-left", "padding-right", "padding-top",
    "page", "page-break-after", "page-break-before", "page-break-inside",
    "page-policy", "pause", "pause-after", "pause-before", "perspective",
    "perspective-origin", "pitch", "pitch-range", "place-content", "place-items", "place-self", "play-during", "position",
    "presentation-level", "punctuation-trim", "quotes", "region-break-after",
    "region-break-before", "region-break-inside", "region-fragment",
    "rendering-intent", "resize", "rest", "rest-after", "rest-before", "richness",
    "right", "rotation", "rotation-point", "ruby-align", "ruby-overhang",
    "ruby-position", "ruby-span", "shape-image-threshold", "shape-inside", "shape-margin",
    "shape-outside", "size", "speak", "speak-as", "speak-header",
    "speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set",
    "tab-size", "table-layout", "target", "target-name", "target-new",
    "target-position", "text-align", "text-align-last", "text-decoration",
    "text-decoration-color", "text-decoration-line", "text-decoration-skip",
    "text-decoration-style", "text-emphasis", "text-emphasis-color",
    "text-emphasis-position", "text-emphasis-style", "text-height",
    "text-indent", "text-justify", "text-outline", "text-overflow", "text-shadow",
    "text-size-adjust", "text-space-collapse", "text-transform", "text-underline-position",
    "text-wrap", "top", "transform", "transform-origin", "transform-style",
    "transition", "transition-delay", "transition-duration",
    "transition-property", "transition-timing-function", "unicode-bidi",
    "user-select", "vertical-align", "visibility", "voice-balance", "voice-duration",
    "voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress",
    "voice-volume", "volume", "white-space", "widows", "width", "will-change", "word-break",
    "word-spacing", "word-wrap", "z-index",
    // SVG-specific
    "clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color",
    "flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events",
    "color-interpolation", "color-interpolation-filters",
    "color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering",
    "marker", "marker-end", "marker-mid", "marker-start", "shape-rendering", "stroke",
    "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin",
    "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering",
    "baseline-shift", "dominant-baseline", "glyph-orientation-horizontal",
    "glyph-orientation-vertical", "text-anchor", "writing-mode"
  ], propertyKeywords = keySet(propertyKeywords_);

  var nonStandardPropertyKeywords_ = [
    "scrollbar-arrow-color", "scrollbar-base-color", "scrollbar-dark-shadow-color",
    "scrollbar-face-color", "scrollbar-highlight-color", "scrollbar-shadow-color",
    "scrollbar-3d-light-color", "scrollbar-track-color", "shape-inside",
    "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button",
    "searchfield-results-decoration", "zoom"
  ], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_);

  var fontProperties_ = [
    "font-family", "src", "unicode-range", "font-variant", "font-feature-settings",
    "font-stretch", "font-weight", "font-style"
  ], fontProperties = keySet(fontProperties_);

  var counterDescriptors_ = [
    "additive-symbols", "fallback", "negative", "pad", "prefix", "range",
    "speak-as", "suffix", "symbols", "system"
  ], counterDescriptors = keySet(counterDescriptors_);

  var colorKeywords_ = [
    "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige",
    "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown",
    "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue",
    "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod",
    "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen",
    "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen",
    "darkslateblue", "darkslategray", "darkturquoise", "darkviolet",
    "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick",
    "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite",
    "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew",
    "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender",
    "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral",
    "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink",
    "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray",
    "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta",
    "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple",
    "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise",
    "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin",
    "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered",
    "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred",
    "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue",
    "purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown",
    "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue",
    "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan",
    "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white",
    "whitesmoke", "yellow", "yellowgreen"
  ], colorKeywords = keySet(colorKeywords_);

  var valueKeywords_ = [
    "above", "absolute", "activeborder", "additive", "activecaption", "afar",
    "after-white-space", "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate",
    "always", "amharic", "amharic-abegede", "antialiased", "appworkspace",
    "arabic-indic", "armenian", "asterisks", "attr", "auto", "auto-flow", "avoid", "avoid-column", "avoid-page",
    "avoid-region", "background", "backwards", "baseline", "below", "bidi-override", "binary",
    "bengali", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box",
    "both", "bottom", "break", "break-all", "break-word", "bullets", "button", "button-bevel",
    "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "cambodian",
    "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret",
    "cell", "center", "checkbox", "circle", "cjk-decimal", "cjk-earthly-branch",
    "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote",
    "col-resize", "collapse", "color", "color-burn", "color-dodge", "column", "column-reverse",
    "compact", "condensed", "contain", "content", "contents",
    "content-box", "context-menu", "continuous", "copy", "counter", "counters", "cover", "crop",
    "cross", "crosshair", "currentcolor", "cursive", "cyclic", "darken", "dashed", "decimal",
    "decimal-leading-zero", "default", "default-button", "dense", "destination-atop",
    "destination-in", "destination-out", "destination-over", "devanagari", "difference",
    "disc", "discard", "disclosure-closed", "disclosure-open", "document",
    "dot-dash", "dot-dot-dash",
    "dotted", "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out",
    "element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede",
    "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er",
    "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er",
    "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et",
    "ethiopic-halehame-gez", "ethiopic-halehame-om-et",
    "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et",
    "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig",
    "ethiopic-numeric", "ew-resize", "exclusion", "expanded", "extends", "extra-condensed",
    "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes",
    "forwards", "from", "geometricPrecision", "georgian", "graytext", "grid", "groove",
    "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hard-light", "hebrew",
    "help", "hidden", "hide", "higher", "highlight", "highlighttext",
    "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "hue", "icon", "ignore",
    "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite",
    "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis",
    "inline-block", "inline-flex", "inline-grid", "inline-table", "inset", "inside", "intrinsic", "invert",
    "italic", "japanese-formal", "japanese-informal", "justify", "kannada",
    "katakana", "katakana-iroha", "keep-all", "khmer",
    "korean-hangul-formal", "korean-hanja-formal", "korean-hanja-informal",
    "landscape", "lao", "large", "larger", "left", "level", "lighter", "lighten",
    "line-through", "linear", "linear-gradient", "lines", "list-item", "listbox", "listitem",
    "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian",
    "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian",
    "lower-roman", "lowercase", "ltr", "luminosity", "malayalam", "match", "matrix", "matrix3d",
    "media-controls-background", "media-current-time-display",
    "media-fullscreen-button", "media-mute-button", "media-play-button",
    "media-return-to-realtime-button", "media-rewind-button",
    "media-seek-back-button", "media-seek-forward-button", "media-slider",
    "media-sliderthumb", "media-time-remaining-display", "media-volume-slider",
    "media-volume-slider-container", "media-volume-sliderthumb", "medium",
    "menu", "menulist", "menulist-button", "menulist-text",
    "menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic",
    "mix", "mongolian", "monospace", "move", "multiple", "multiply", "myanmar", "n-resize",
    "narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop",
    "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap",
    "ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize", "oblique", "octal", "opacity", "open-quote",
    "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset",
    "outside", "outside-shape", "overlay", "overline", "padding", "padding-box",
    "painted", "page", "paused", "persian", "perspective", "plus-darker", "plus-lighter",
    "pointer", "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d",
    "progress", "push-button", "radial-gradient", "radio", "read-only",
    "read-write", "read-write-plaintext-only", "rectangle", "region",
    "relative", "repeat", "repeating-linear-gradient",
    "repeating-radial-gradient", "repeat-x", "repeat-y", "reset", "reverse",
    "rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY",
    "rotateZ", "round", "row", "row-resize", "row-reverse", "rtl", "run-in", "running",
    "s-resize", "sans-serif", "saturation", "scale", "scale3d", "scaleX", "scaleY", "scaleZ", "screen",
    "scroll", "scrollbar", "scroll-position", "se-resize", "searchfield",
    "searchfield-cancel-button", "searchfield-decoration",
    "searchfield-results-button", "searchfield-results-decoration", "self-start", "self-end",
    "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama",
    "simp-chinese-formal", "simp-chinese-informal", "single",
    "skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal",
    "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow",
    "small", "small-caps", "small-caption", "smaller", "soft-light", "solid", "somali",
    "source-atop", "source-in", "source-out", "source-over", "space", "space-around", "space-between", "space-evenly", "spell-out", "square",
    "square-button", "start", "static", "status-bar", "stretch", "stroke", "sub",
    "subpixel-antialiased", "super", "sw-resize", "symbolic", "symbols", "system-ui", "table",
    "table-caption", "table-cell", "table-column", "table-column-group",
    "table-footer-group", "table-header-group", "table-row", "table-row-group",
    "tamil",
    "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai",
    "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight",
    "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er",
    "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top",
    "trad-chinese-formal", "trad-chinese-informal", "transform",
    "translate", "translate3d", "translateX", "translateY", "translateZ",
    "transparent", "ultra-condensed", "ultra-expanded", "underline", "unset", "up",
    "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal",
    "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url",
    "var", "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted",
    "visibleStroke", "visual", "w-resize", "wait", "wave", "wider",
    "window", "windowframe", "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor",
    "xx-large", "xx-small"
  ], valueKeywords = keySet(valueKeywords_);

  var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_)
    .concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_)
    .concat(valueKeywords_);
  CodeMirror.registerHelper("hintWords", "css", allWords);

  function tokenCComment(stream, state) {
    var maybeEnd = false, ch;
    while ((ch = stream.next()) != null) {
      if (maybeEnd && ch == "/") {
        state.tokenize = null;
        break;
      }
      maybeEnd = (ch == "*");
    }
    return ["comment", "comment"];
  }

  CodeMirror.defineMIME("text/css", {
    documentTypes: documentTypes,
    mediaTypes: mediaTypes,
    mediaFeatures: mediaFeatures,
    mediaValueKeywords: mediaValueKeywords,
    propertyKeywords: propertyKeywords,
    nonStandardPropertyKeywords: nonStandardPropertyKeywords,
    fontProperties: fontProperties,
    counterDescriptors: counterDescriptors,
    colorKeywords: colorKeywords,
    valueKeywords: valueKeywords,
    tokenHooks: {
      "/": function(stream, state) {
        if (!stream.eat("*")) return false;
        state.tokenize = tokenCComment;
        return tokenCComment(stream, state);
      }
    },
    name: "css"
  });

  CodeMirror.defineMIME("text/x-scss", {
    mediaTypes: mediaTypes,
    mediaFeatures: mediaFeatures,
    mediaValueKeywords: mediaValueKeywords,
    propertyKeywords: propertyKeywords,
    nonStandardPropertyKeywords: nonStandardPropertyKeywords,
    colorKeywords: colorKeywords,
    valueKeywords: valueKeywords,
    fontProperties: fontProperties,
    allowNested: true,
    lineComment: "//",
    tokenHooks: {
      "/": function(stream, state) {
        if (stream.eat("/")) {
          stream.skipToEnd();
          return ["comment", "comment"];
        } else if (stream.eat("*")) {
          state.tokenize = tokenCComment;
          return tokenCComment(stream, state);
        } else {
          return ["operator", "operator"];
        }
      },
      ":": function(stream) {
        if (stream.match(/\s*\{/, false))
          return [null, null]
        return false;
      },
      "$": function(stream) {
        stream.match(/^[\w-]+/);
        if (stream.match(/^\s*:/, false))
          return ["variable-2", "variable-definition"];
        return ["variable-2", "variable"];
      },
      "#": function(stream) {
        if (!stream.eat("{")) return false;
        return [null, "interpolation"];
      }
    },
    name: "css",
    helperType: "scss"
  });

  CodeMirror.defineMIME("text/x-less", {
    mediaTypes: mediaTypes,
    mediaFeatures: mediaFeatures,
    mediaValueKeywords: mediaValueKeywords,
    propertyKeywords: propertyKeywords,
    nonStandardPropertyKeywords: nonStandardPropertyKeywords,
    colorKeywords: colorKeywords,
    valueKeywords: valueKeywords,
    fontProperties: fontProperties,
    allowNested: true,
    lineComment: "//",
    tokenHooks: {
      "/": function(stream, state) {
        if (stream.eat("/")) {
          stream.skipToEnd();
          return ["comment", "comment"];
        } else if (stream.eat("*")) {
          state.tokenize = tokenCComment;
          return tokenCComment(stream, state);
        } else {
          return ["operator", "operator"];
        }
      },
      "@": function(stream) {
        if (stream.eat("{")) return [null, "interpolation"];
        if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/i, false)) return false;
        stream.eatWhile(/[\w\\\-]/);
        if (stream.match(/^\s*:/, false))
          return ["variable-2", "variable-definition"];
        return ["variable-2", "variable"];
      },
      "&": function() {
        return ["atom", "atom"];
      }
    },
    name: "css",
    helperType: "less"
  });

  CodeMirror.defineMIME("text/x-gss", {
    documentTypes: documentTypes,
    mediaTypes: mediaTypes,
    mediaFeatures: mediaFeatures,
    propertyKeywords: propertyKeywords,
    nonStandardPropertyKeywords: nonStandardPropertyKeywords,
    fontProperties: fontProperties,
    counterDescriptors: counterDescriptors,
    colorKeywords: colorKeywords,
    valueKeywords: valueKeywords,
    supportsAtComponent: true,
    tokenHooks: {
      "/": function(stream, state) {
        if (!stream.eat("*")) return false;
        state.tokenize = tokenCComment;
        return tokenCComment(stream, state);
      }
    },
    name: "css",
    helperType: "gss"
  });

});


/***/ }),

/***/ "exNP":
/*!*********************************************************!*\
  !*** ./node_modules/@jupyterlab/cells/lib/inputarea.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const widgets_2 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const codeeditor_1 = __webpack_require__(/*! @jupyterlab/codeeditor */ "sLCx");
const codemirror_1 = __webpack_require__(/*! @jupyterlab/codemirror */ "ddNL");
/**
 * The class name added to input area widgets.
 */
const INPUT_AREA_CLASS = 'jp-InputArea';
/**
 * The class name added to the prompt area of cell.
 */
const INPUT_AREA_PROMPT_CLASS = 'jp-InputArea-prompt';
/**
 * The class name added to OutputPrompt.
 */
const INPUT_PROMPT_CLASS = 'jp-InputPrompt';
/**
 * The class name added to the editor area of the cell.
 */
const INPUT_AREA_EDITOR_CLASS = 'jp-InputArea-editor';
/******************************************************************************
 * InputArea
 ******************************************************************************/
/**
 * An input area widget, which hosts a prompt and an editor widget.
 */
class InputArea extends widgets_2.Widget {
    /**
     * Construct an input area widget.
     */
    constructor(options) {
        super();
        this._prompt = null;
        this._editor = null;
        this._rendered = null;
        this.addClass(INPUT_AREA_CLASS);
        let model = (this.model = options.model);
        let contentFactory = (this.contentFactory =
            options.contentFactory || InputArea.defaultContentFactory);
        // Prompt
        let prompt = (this._prompt = contentFactory.createInputPrompt());
        prompt.addClass(INPUT_AREA_PROMPT_CLASS);
        // Editor
        let editorOptions = { model, factory: contentFactory.editorFactory };
        let editor = (this._editor = new codeeditor_1.CodeEditorWrapper(editorOptions));
        editor.addClass(INPUT_AREA_EDITOR_CLASS);
        let layout = (this.layout = new widgets_1.PanelLayout());
        layout.addWidget(prompt);
        layout.addWidget(editor);
    }
    /**
     * Get the CodeEditorWrapper used by the cell.
     */
    get editorWidget() {
        return this._editor;
    }
    /**
     * Get the CodeEditor used by the cell.
     */
    get editor() {
        return this._editor.editor;
    }
    /**
     * Get the prompt node used by the cell.
     */
    get promptNode() {
        return this._prompt.node;
    }
    /**
     * Render an input instead of the text editor.
     */
    renderInput(widget) {
        let layout = this.layout;
        if (this._rendered) {
            this._rendered.parent = null;
        }
        this._editor.hide();
        this._rendered = widget;
        layout.addWidget(widget);
    }
    /**
     * Show the text editor.
     */
    showEditor() {
        if (this._rendered) {
            this._rendered.parent = null;
        }
        this._editor.show();
    }
    /**
     * Set the prompt of the input area.
     */
    setPrompt(value) {
        this._prompt.executionCount = value;
    }
    /**
     * Dispose of the resources held by the widget.
     */
    dispose() {
        // Do nothing if already disposed.
        if (this.isDisposed) {
            return;
        }
        this._prompt = null;
        this._editor = null;
        this._rendered = null;
        super.dispose();
    }
}
exports.InputArea = InputArea;
/**
 * A namespace for `InputArea` statics.
 */
(function (InputArea) {
    /**
     * Default implementation of `IContentFactory`.
     *
     * This defaults to using an `editorFactory` based on CodeMirror.
     */
    class ContentFactory {
        /**
         * Construct a `ContentFactory`.
         */
        constructor(options = {}) {
            this._editor = null;
            this._editor = options.editorFactory || InputArea.defaultEditorFactory;
        }
        /**
         * Return the `CodeEditor.Factory` being used.
         */
        get editorFactory() {
            return this._editor;
        }
        /**
         * Create an input prompt.
         */
        createInputPrompt() {
            return new InputPrompt();
        }
    }
    InputArea.ContentFactory = ContentFactory;
    /**
     * A function to create the default CodeMirror editor factory.
     */
    function _createDefaultEditorFactory() {
        let editorServices = new codemirror_1.CodeMirrorEditorFactory();
        return editorServices.newInlineEditor;
    }
    /**
     * The default editor factory singleton based on CodeMirror.
     */
    InputArea.defaultEditorFactory = _createDefaultEditorFactory();
    /**
     * The default `ContentFactory` instance.
     */
    InputArea.defaultContentFactory = new ContentFactory({});
})(InputArea = exports.InputArea || (exports.InputArea = {}));
/**
 * The default input prompt implementation.
 */
class InputPrompt extends widgets_2.Widget {
    /*
     * Create an output prompt widget.
     */
    constructor() {
        super();
        this._executionCount = null;
        this.addClass(INPUT_PROMPT_CLASS);
    }
    /**
     * The execution count for the prompt.
     */
    get executionCount() {
        return this._executionCount;
    }
    set executionCount(value) {
        this._executionCount = value;
        if (value === null) {
            this.node.textContent = ' ';
        }
        else {
            this.node.textContent = `[${value || ' '}]:`;
        }
    }
}
exports.InputPrompt = InputPrompt;


/***/ }),

/***/ "f+Xr":
/*!********************************************************!*\
  !*** ./node_modules/@jupyterlab/terminal/lib/index.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
__webpack_require__(/*! ../style/index.css */ "Zgzb");
__export(__webpack_require__(/*! ./widget */ "ly1K"));
/* tslint:disable */
/**
 * The editor tracker token.
 */
exports.ITerminalTracker = new coreutils_1.Token('@jupyterlab/terminal:ITerminalTracker');
/* tslint:enable */


/***/ }),

/***/ "f1NE":
/*!***************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/application/style/tabs.css ***!
  \***************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n/*-----------------------------------------------------------------------------\n| Variables\n|----------------------------------------------------------------------------*/\n\n:root {\n  /* These need to be root because tabs get attached to the body during dragging. */\n  --jp-private-horizontal-tab-height: 24px;\n  --jp-private-horizontal-tab-width: 216px;\n  --jp-private-horizontal-tab-active-top-border: 2px;\n}\n\n/*-----------------------------------------------------------------------------\n| Tabs in the dock panel\n|----------------------------------------------------------------------------*/\n\n.p-DockPanel-tabBar {\n  border-bottom: var(--jp-border-width) solid var(--jp-border-color1);\n  overflow: visible;\n  color: var(--jp-ui-font-color1);\n  font-size: var(--jp-ui-font-size1);\n}\n\n.p-DockPanel-tabBar[data-orientation='horizontal'] {\n  min-height: calc(\n    var(--jp-private-horizontal-tab-height) + 2 * var(--jp-border-width)\n  );\n}\n\n.p-DockPanel-tabBar[data-orientation='vertical'] {\n  min-width: 80px;\n}\n\n.p-DockPanel-tabBar > .p-TabBar-content {\n  align-items: flex-end;\n  min-width: 0;\n  min-height: 0;\n}\n\n.p-DockPanel-tabBar .p-TabBar-tab {\n  flex: 0 1 var(--jp-private-horizontal-tab-width);\n  min-height: calc(\n    var(--jp-private-horizontal-tab-height) + var(--jp-border-width)\n  );\n  min-width: 36px;\n  margin-left: calc(-1 * var(--jp-border-width));\n  line-height: var(--jp-private-horizontal-tab-height);\n  padding: 0px 8px;\n  background: var(--jp-layout-color2);\n  border: var(--jp-border-width) solid var(--jp-border-color1);\n  border-bottom: none;\n  position: relative;\n  overflow: visible;\n}\n\n.p-DockPanel-tabBar .p-TabBar-tab:hover:not(.p-mod-current) {\n  background: var(--jp-layout-color1);\n}\n\n.p-DockPanel-tabBar .p-TabBar-tab:first-child {\n  margin-left: 0;\n}\n\n/* This is a current tab of a tab bar in the dock panel: each tab bar has 1. */\n.p-DockPanel-tabBar .p-TabBar-tab.p-mod-current {\n  background: var(--jp-layout-color1);\n  color: var(--jp-ui-font-color0);\n  min-height: calc(\n    var(--jp-private-horizontal-tab-height) + 2 * var(--jp-border-width)\n  );\n  transform: translateY(var(--jp-border-width));\n}\n\n/* This is the main application level current tab: only 1 exists. */\n.p-DockPanel-tabBar .p-TabBar-tab.jp-mod-current:before {\n  position: absolute;\n  top: calc(-1 * var(--jp-border-width));\n  left: calc(-1 * var(--jp-border-width));\n  content: '';\n  height: var(--jp-private-horizontal-tab-active-top-border);\n  width: calc(100% + 2 * var(--jp-border-width));\n  background: var(--jp-brand-color1);\n}\n\n/* This is the left tab bar current tab: only 1 exists. */\n.p-TabBar-tab.p-mod-current {\n  color: var(--jp-ui-font-color0);\n  background: var(--jp-layout-color1);\n}\n\n.p-TabBar-tab.p-mod-current:hover {\n  background: var(--jp-layout-color1);\n}\n\n.p-DockPanel-tabBar .p-TabBar.p-mod-left .p-TabBar-tab,\n.p-DockPanel-tabBar .p-TabBar.p-mod-right .p-TabBar-tab {\n  flex: 0 1 40px;\n  margin-top: -1px;\n  line-height: 40px;\n}\n\n.p-DockPanel-tabBar .p-TabBar.p-mod-left .p-TabBar-tab {\n  border-right: none;\n}\n\n.p-DockPanel-tabBar .p-TabBar.p-mod-right .p-TabBar-tab {\n  border-left: none;\n}\n\n.p-DockPanel-tabBar .p-TabBar.p-mod-left .p-TabBar-tab:first-child,\n.p-DockPanel-tabBar .p-TabBar.p-mod-right .p-TabBar-tab:first-child {\n  margin-top: 0;\n}\n\n.p-DockPanel-tabBar .p-TabBar.p-mod-left .p-TabBar-tab.p-mod-current,\n.p-DockPanel-tabBar .p-TabBar.p-mod-right .p-TabBar-tab.p-mod-current {\n  min-width: 80px;\n  max-width: 80px;\n}\n\n.p-DockPanel-tabBar .p-TabBar.p-mod-right .p-TabBar-tab.p-mod-current {\n  transform: translateX(-1px);\n}\n\n.p-DockPanel-tabBar .p-TabBar-tabIcon,\n.p-DockPanel-tabBar .p-TabBar-tabLabel,\n.p-DockPanel-tabBar .p-TabBar-tabCloseIcon {\n  display: inline-block;\n}\n\n.p-DockPanel-tabBar .p-TabBar-tab .p-TabBar-tabIcon,\n.p-TabBar-tab.p-mod-drag-image .p-TabBar-tabIcon {\n  width: 14px;\n  background-position: left center;\n  background-repeat: no-repeat;\n  margin-right: 4px;\n}\n\n.p-DockPanel-tabBar .p-TabBar-tab.p-mod-current .p-TabBar-tabIcon {\n  margin-bottom: var(--jp-border-width);\n}\n\n.p-TabBar-WindowTabLabel {\n  margin-top: 4px;\n}\n\n.p-DockPanel-tabBar .p-TabBar-tab.p-mod-closable > .p-TabBar-tabCloseIcon {\n  margin-left: 4px;\n  padding-top: 8px;\n  background-size: 16px;\n  height: 16px;\n  width: 16px;\n  background-image: var(--jp-icon-close);\n  background-position: center;\n  background-repeat: no-repeat;\n}\n\n.p-DockPanel-tabBar\n  .p-TabBar-tab.p-mod-closable.jp-mod-dirty\n  > .p-TabBar-tabCloseIcon {\n  background-size: 10px;\n  background-image: var(--jp-icon-circle);\n}\n\n.p-DockPanel-tabBar\n  .p-TabBar-tab.p-mod-closable\n  > .p-TabBar-tabCloseIcon:hover {\n  background-size: 16px;\n  background-image: var(--jp-icon-close-circle);\n}\n\n.p-TabBar-tab.p-mod-drag-image {\n  background: var(--jp-layout-color1);\n  border: var(--jp-border-width) solid var(--jp-border-color1);\n  border-top: var(--jp-border-width) solid var(--jp-brand-color1);\n  box-shadow: var(--jp-elevation-z4);\n  color: var(--jp-ui-font-color1);\n  font-size: var(--jp-ui-font-size1);\n  line-height: var(--jp-private-horizontal-tab-height);\n  min-height: var(--jp-private-horizontal-tab-height);\n  min-width: var(--jp-private-horizontal-tab-width);\n  padding: 0px 10px;\n  transform: translateX(-40%) translateY(-58%);\n}\n\n/* .p-TabBar-tab.p-mod-drag-image .p-TabBar-tabLabel {\n  margin-left: 4px;\n} */\n", ""]);

// exports


/***/ }),

/***/ "f3pb":
/*!******************************************!*\
  !*** ./node_modules/asn1.js/lib/asn1.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var asn1 = exports;

asn1.bignum = __webpack_require__(/*! bn.js */ "OZ/i");

asn1.define = __webpack_require__(/*! ./asn1/api */ "7zrB").define;
asn1.base = __webpack_require__(/*! ./asn1/base */ "Qd/k");
asn1.constants = __webpack_require__(/*! ./asn1/constants */ "AhHn");
asn1.decoders = __webpack_require__(/*! ./asn1/decoders */ "IPZY");
asn1.encoders = __webpack_require__(/*! ./asn1/encoders */ "ND7S");


/***/ }),

/***/ "fEyW":
/*!******************************************************************!*\
  !*** ./node_modules/draft-js/lib/removeRangeFromContentState.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule removeRangeFromContentState
 * @format
 * 
 */



var ContentBlockNode = __webpack_require__(/*! ./ContentBlockNode */ "JL7T");
var Immutable = __webpack_require__(/*! immutable */ "JPcv");

var getNextDelimiterBlockKey = __webpack_require__(/*! ./getNextDelimiterBlockKey */ "VTBg");

var List = Immutable.List,
    Map = Immutable.Map;


var transformBlock = function transformBlock(key, blockMap, func) {
  if (!key) {
    return;
  }

  var block = blockMap.get(key);

  if (!block) {
    return;
  }

  blockMap.set(key, func(block));
};

/**
 * Ancestors needs to be preserved when there are non selected
 * children to make sure we do not leave any orphans behind
 */
var getAncestorsKeys = function getAncestorsKeys(blockKey, blockMap) {
  var parents = [];

  if (!blockKey) {
    return parents;
  }

  var blockNode = blockMap.get(blockKey);
  while (blockNode && blockNode.getParentKey()) {
    var parentKey = blockNode.getParentKey();
    if (parentKey) {
      parents.push(parentKey);
    }
    blockNode = parentKey ? blockMap.get(parentKey) : null;
  }

  return parents;
};

/**
 * Get all next delimiter keys until we hit a root delimiter and return
 * an array of key references
 */
var getNextDelimitersBlockKeys = function getNextDelimitersBlockKeys(block, blockMap) {
  var nextDelimiters = [];

  if (!block) {
    return nextDelimiters;
  }

  var nextDelimiter = getNextDelimiterBlockKey(block, blockMap);
  while (nextDelimiter && blockMap.get(nextDelimiter)) {
    var _block = blockMap.get(nextDelimiter);
    nextDelimiters.push(nextDelimiter);

    // we do not need to keep checking all root node siblings, just the first occurance
    nextDelimiter = _block.getParentKey() ? getNextDelimiterBlockKey(_block, blockMap) : null;
  }

  return nextDelimiters;
};

var getNextValidSibling = function getNextValidSibling(block, blockMap, originalBlockMap) {
  if (!block) {
    return null;
  }

  // note that we need to make sure we refer to the original block since this
  // function is called within a withMutations
  var nextValidSiblingKey = originalBlockMap.get(block.getKey()).getNextSiblingKey();

  while (nextValidSiblingKey && !blockMap.get(nextValidSiblingKey)) {
    nextValidSiblingKey = originalBlockMap.get(nextValidSiblingKey).getNextSiblingKey() || null;
  }

  return nextValidSiblingKey;
};

var getPrevValidSibling = function getPrevValidSibling(block, blockMap, originalBlockMap) {
  if (!block) {
    return null;
  }

  // note that we need to make sure we refer to the original block since this
  // function is called within a withMutations
  var prevValidSiblingKey = originalBlockMap.get(block.getKey()).getPrevSiblingKey();

  while (prevValidSiblingKey && !blockMap.get(prevValidSiblingKey)) {
    prevValidSiblingKey = originalBlockMap.get(prevValidSiblingKey).getPrevSiblingKey() || null;
  }

  return prevValidSiblingKey;
};

var updateBlockMapLinks = function updateBlockMapLinks(blockMap, startBlock, endBlock, originalBlockMap) {
  return blockMap.withMutations(function (blocks) {
    // update start block if its retained
    transformBlock(startBlock.getKey(), blocks, function (block) {
      return block.merge({
        nextSibling: getNextValidSibling(startBlock, blocks, originalBlockMap),
        prevSibling: getPrevValidSibling(startBlock, blocks, originalBlockMap)
      });
    });

    // update endblock if its retained
    transformBlock(endBlock.getKey(), blocks, function (block) {
      return block.merge({
        nextSibling: getNextValidSibling(endBlock, blocks, originalBlockMap),
        prevSibling: getPrevValidSibling(endBlock, blocks, originalBlockMap)
      });
    });

    // update start block parent ancestors
    getAncestorsKeys(startBlock.getKey(), originalBlockMap).forEach(function (parentKey) {
      return transformBlock(parentKey, blocks, function (block) {
        return block.merge({
          children: block.getChildKeys().filter(function (key) {
            return blocks.get(key);
          }),
          nextSibling: getNextValidSibling(block, blocks, originalBlockMap),
          prevSibling: getPrevValidSibling(block, blocks, originalBlockMap)
        });
      });
    });

    // update start block next - can only happen if startBlock == endBlock
    transformBlock(startBlock.getNextSiblingKey(), blocks, function (block) {
      return block.merge({
        prevSibling: startBlock.getPrevSiblingKey()
      });
    });

    // update start block prev
    transformBlock(startBlock.getPrevSiblingKey(), blocks, function (block) {
      return block.merge({
        nextSibling: getNextValidSibling(startBlock, blocks, originalBlockMap)
      });
    });

    // update end block next
    transformBlock(endBlock.getNextSiblingKey(), blocks, function (block) {
      return block.merge({
        prevSibling: getPrevValidSibling(endBlock, blocks, originalBlockMap)
      });
    });

    // update end block prev
    transformBlock(endBlock.getPrevSiblingKey(), blocks, function (block) {
      return block.merge({
        nextSibling: endBlock.getNextSiblingKey()
      });
    });

    // update end block parent ancestors
    getAncestorsKeys(endBlock.getKey(), originalBlockMap).forEach(function (parentKey) {
      transformBlock(parentKey, blocks, function (block) {
        return block.merge({
          children: block.getChildKeys().filter(function (key) {
            return blocks.get(key);
          }),
          nextSibling: getNextValidSibling(block, blocks, originalBlockMap),
          prevSibling: getPrevValidSibling(block, blocks, originalBlockMap)
        });
      });
    });

    // update next delimiters all the way to a root delimiter
    getNextDelimitersBlockKeys(endBlock, originalBlockMap).forEach(function (delimiterKey) {
      return transformBlock(delimiterKey, blocks, function (block) {
        return block.merge({
          nextSibling: getNextValidSibling(block, blocks, originalBlockMap),
          prevSibling: getPrevValidSibling(block, blocks, originalBlockMap)
        });
      });
    });
  });
};

var removeRangeFromContentState = function removeRangeFromContentState(contentState, selectionState) {
  if (selectionState.isCollapsed()) {
    return contentState;
  }

  var blockMap = contentState.getBlockMap();
  var startKey = selectionState.getStartKey();
  var startOffset = selectionState.getStartOffset();
  var endKey = selectionState.getEndKey();
  var endOffset = selectionState.getEndOffset();

  var startBlock = blockMap.get(startKey);
  var endBlock = blockMap.get(endKey);

  // we assume that ContentBlockNode and ContentBlocks are not mixed together
  var isExperimentalTreeBlock = startBlock instanceof ContentBlockNode;

  // used to retain blocks that should not be deleted to avoid orphan children
  var parentAncestors = [];

  if (isExperimentalTreeBlock) {
    var endBlockchildrenKeys = endBlock.getChildKeys();
    var endBlockAncestors = getAncestorsKeys(endKey, blockMap);

    // endBlock has unselected sibblings so we can not remove its ancestors parents
    if (endBlock.getNextSiblingKey()) {
      parentAncestors = parentAncestors.concat(endBlockAncestors);
    }

    // endBlock has children so can not remove this block or any of its ancestors
    if (!endBlockchildrenKeys.isEmpty()) {
      parentAncestors = parentAncestors.concat(endBlockAncestors.concat([endKey]));
    }

    // we need to retain all ancestors of the next delimiter block
    parentAncestors = parentAncestors.concat(getAncestorsKeys(getNextDelimiterBlockKey(endBlock, blockMap), blockMap));
  }

  var characterList = void 0;

  if (startBlock === endBlock) {
    characterList = removeFromList(startBlock.getCharacterList(), startOffset, endOffset);
  } else {
    characterList = startBlock.getCharacterList().slice(0, startOffset).concat(endBlock.getCharacterList().slice(endOffset));
  }

  var modifiedStart = startBlock.merge({
    text: startBlock.getText().slice(0, startOffset) + endBlock.getText().slice(endOffset),
    characterList: characterList
  });

  var newBlocks = blockMap.toSeq().skipUntil(function (_, k) {
    return k === startKey;
  }).takeUntil(function (_, k) {
    return k === endKey;
  }).filter(function (_, k) {
    return parentAncestors.indexOf(k) === -1;
  }).concat(Map([[endKey, null]])).map(function (_, k) {
    return k === startKey ? modifiedStart : null;
  });

  var updatedBlockMap = blockMap.merge(newBlocks).filter(function (block) {
    return !!block;
  });

  if (isExperimentalTreeBlock) {
    updatedBlockMap = updateBlockMapLinks(updatedBlockMap, startBlock, endBlock, blockMap);
  }

  return contentState.merge({
    blockMap: updatedBlockMap,
    selectionBefore: selectionState,
    selectionAfter: selectionState.merge({
      anchorKey: startKey,
      anchorOffset: startOffset,
      focusKey: startKey,
      focusOffset: startOffset,
      isBackward: false
    })
  });
};

/**
 * Maintain persistence for target list when removing characters on the
 * head and tail of the character list.
 */
var removeFromList = function removeFromList(targetList, startOffset, endOffset) {
  if (startOffset === 0) {
    while (startOffset < endOffset) {
      targetList = targetList.shift();
      startOffset++;
    }
  } else if (endOffset === targetList.count()) {
    while (endOffset > startOffset) {
      targetList = targetList.pop();
      endOffset--;
    }
  } else {
    var head = targetList.slice(0, startOffset);
    var tail = targetList.slice(endOffset);
    targetList = head.concat(tail).toList();
  }
  return targetList;
};

module.exports = removeRangeFromContentState;

/***/ }),

/***/ "fFD0":
/*!*************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeMesh3dIcon.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeMesh3dIcon = function TraceTypeMesh3dIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement(
            'g',
            { fill: 'none' },
            _react2.default.createElement('path', { d: 'M0 0h46v46H0z' }),
            _react2.default.createElement('path', { stroke: '#1d9bfb', d: 'M23.511 20.062L9.516 13.588l13.929-6.319 14.039 6.319-13.973 6.474zM9.516 13.588v16.75l13.999 6.026-.004-16.302-13.995-6.474z', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2' }),
            _react2.default.createElement('path', { stroke: '#1d9bfb', d: 'M37.484 13.588v16.75l-13.999 6.026.004-16.302 13.995-6.474z', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2' }),
            _react2.default.createElement('path', { stroke: '#1d9bfb', d: 'M18.489 17.739v16.408M14 15.662V32.5m9.515-1.695L9.516 24.588m13.999 1.217L9.516 19.588m19.026-1.924v16.483m4.489-18.387V32.5m-9.516-1.695l14-6.217m-14 1.217l14-6.217m-23.128-8.21l14.155 6.286m-9.814-8.255l14.303 6.351m-14.542 1.979l14.124-6.292M14 15.662l14.123-6.291', strokeLinecap: 'round', strokeLinejoin: 'round' })
        )
    );
};

exports.default = TraceTypeMesh3dIcon;

/***/ }),

/***/ "fGT3":
/*!***********************************************!*\
  !*** ./node_modules/lodash/_mapCacheClear.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Hash = __webpack_require__(/*! ./_Hash */ "4kuk"),
    ListCache = __webpack_require__(/*! ./_ListCache */ "Xi7e"),
    Map = __webpack_require__(/*! ./_Map */ "ebwN");

/**
 * 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
  };
}

module.exports = mapCacheClear;


/***/ }),

/***/ "fHvq":
/*!*******************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/vdom-extension/style/index.css ***!
  \*******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var escape = __webpack_require__(/*! ../../../css-loader/lib/url/escape.js */ "sEG9");
exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/**\n  Copyright (c) Jupyter Development Team.\n  Distributed under the terms of the Modified BSD License.\n*/\n\n/* Add CSS variables to :root */\n:root {\n  --jp-icon-vdom: url(" + escape(__webpack_require__(/*! ./react.svg */ "6jVa")) + ");\n}\n\n/* Base styles */\n.jp-RenderedVDOM {\n  width: 100%;\n  height: 100%;\n  padding: 0;\n  overflow: auto;\n}\n\n/* Document styles */\n.jp-MimeDocument .jp-RenderedVDOM {\n  padding: 5px;\n}\n\n/* Output styles */\n.jp-OutputArea .jp-RenderedVDOM {\n}\n\n/* Document icon */\n.jp-VDOMIcon {\n  background-image: var(--jp-icon-vdom);\n  background-size: 24px;\n  background-position: center !important;\n}\n", ""]);

// exports


/***/ }),

/***/ "fL/d":
/*!******************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotAreaIcon.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotAreaIcon = function PlotAreaIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M32 26.625l-12-16L16 16 9.312 5.25-.001 26.625z' })
    );
};

exports.default = PlotAreaIcon;

/***/ }),

/***/ "fMZg":
/*!**************************************************************!*\
  !*** ./node_modules/draft-js/lib/getRangesForDraftEntity.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule getRangesForDraftEntity
 * @format
 * 
 */



var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");

/**
 * Obtain the start and end positions of the range that has the
 * specified entity applied to it.
 *
 * Entity keys are applied only to contiguous stretches of text, so this
 * method searches for the first instance of the entity key and returns
 * the subsequent range.
 */
function getRangesForDraftEntity(block, key) {
  var ranges = [];
  block.findEntityRanges(function (c) {
    return c.getEntity() === key;
  }, function (start, end) {
    ranges.push({ start: start, end: end });
  });

  !!!ranges.length ?  true ? invariant(false, 'Entity key not found in this range.') : undefined : void 0;

  return ranges;
}

module.exports = getRangesForDraftEntity;

/***/ }),

/***/ "fMtF":
/*!**********************************************************!*\
  !*** ./node_modules/@jupyterlab/notebook/lib/tracker.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
/* tslint:disable */
/**
 * The notebook tracker token.
 */
exports.INotebookTracker = new coreutils_1.Token('@jupyterlab/notebook:INotebookTracker');
/* tslint:enable */
class NotebookTracker extends apputils_1.InstanceTracker {
    constructor() {
        super(...arguments);
        this._activeCell = null;
        this._activeCellChanged = new signaling_1.Signal(this);
        this._selectionChanged = new signaling_1.Signal(this);
    }
    /**
     * The currently focused cell.
     *
     * #### Notes
     * This is a read-only property. If there is no cell with the focus, then this
     * value is `null`.
     */
    get activeCell() {
        let widget = this.currentWidget;
        if (!widget) {
            return null;
        }
        return widget.content.activeCell || null;
    }
    /**
     * A signal emitted when the current active cell changes.
     *
     * #### Notes
     * If there is no cell with the focus, then `null` will be emitted.
     */
    get activeCellChanged() {
        return this._activeCellChanged;
    }
    /**
     * A signal emitted when the selection state changes.
     */
    get selectionChanged() {
        return this._selectionChanged;
    }
    /**
     * Add a new notebook panel to the tracker.
     *
     * @param panel - The notebook panel being added.
     */
    add(panel) {
        const promise = super.add(panel);
        panel.content.activeCellChanged.connect(this._onActiveCellChanged, this);
        panel.content.selectionChanged.connect(this._onSelectionChanged, this);
        return promise;
    }
    /**
     * Dispose of the resources held by the tracker.
     */
    dispose() {
        this._activeCell = null;
        super.dispose();
    }
    /**
     * Handle the current change event.
     */
    onCurrentChanged(widget) {
        // Store an internal reference to active cell to prevent false positives.
        let activeCell = this.activeCell;
        if (activeCell && activeCell === this._activeCell) {
            return;
        }
        this._activeCell = activeCell;
        if (!widget) {
            return;
        }
        // Since the notebook has changed, immediately signal an active cell change
        this._activeCellChanged.emit(widget.content.activeCell || null);
    }
    _onActiveCellChanged(sender, cell) {
        // Check if the active cell change happened for the current notebook.
        if (this.currentWidget && this.currentWidget.content === sender) {
            this._activeCell = cell || null;
            this._activeCellChanged.emit(this._activeCell);
        }
    }
    _onSelectionChanged(sender) {
        // Check if the selection change happened for the current notebook.
        if (this.currentWidget && this.currentWidget.content === sender) {
            this._selectionChanged.emit(void 0);
        }
    }
}
exports.NotebookTracker = NotebookTracker;


/***/ }),

/***/ "fNZA":
/*!**************************************************************************!*\
  !*** ./node_modules/core-js/library/modules/core.get-iterator-method.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var classof = __webpack_require__(/*! ./_classof */ "QMMT");
var ITERATOR = __webpack_require__(/*! ./_wks */ "UWiX")('iterator');
var Iterators = __webpack_require__(/*! ./_iterators */ "SBuE");
module.exports = __webpack_require__(/*! ./_core */ "WEpk").getIteratorMethod = function (it) {
  if (it != undefined) return it[ITERATOR]
    || it['@@iterator']
    || Iterators[classof(it)];
};


/***/ }),

/***/ "fNf1":
/*!***************************************************!*\
  !*** ./node_modules/react-json-tree/lib/index.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _objectWithoutProperties2 = __webpack_require__(/*! babel-runtime/helpers/objectWithoutProperties */ "jo6Y");

var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);

var _classCallCheck2 = __webpack_require__(/*! babel-runtime/helpers/classCallCheck */ "iCc5");

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _possibleConstructorReturn2 = __webpack_require__(/*! babel-runtime/helpers/possibleConstructorReturn */ "FYw3");

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __webpack_require__(/*! babel-runtime/helpers/inherits */ "mRg0");

var _inherits3 = _interopRequireDefault(_inherits2);

var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "QbLZ");

var _extends3 = _interopRequireDefault(_extends2);

var _keys = __webpack_require__(/*! babel-runtime/core-js/object/keys */ "GQeE");

var _keys2 = _interopRequireDefault(_keys);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _JSONNode = __webpack_require__(/*! ./JSONNode */ "rTFf");

var _JSONNode2 = _interopRequireDefault(_JSONNode);

var _createStylingFromTheme = __webpack_require__(/*! ./createStylingFromTheme */ "YewF");

var _createStylingFromTheme2 = _interopRequireDefault(_createStylingFromTheme);

var _reactBase16Styling = __webpack_require__(/*! react-base16-styling */ "jb+b");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var identity = function identity(value) {
  return value;
}; // ES6 + inline style port of JSONViewer https://bitbucket.org/davevedder/react-json-viewer/
// all credits and original code to the author
// Dave Vedder <veddermatic@gmail.com> http://www.eskimospy.com/
// port by Daniele Zannotti http://www.github.com/dzannotti <dzannotti@me.com>

var expandRootNode = function expandRootNode(keyName, data, level) {
  return level === 0;
};
var defaultItemString = function defaultItemString(type, data, itemType, itemString) {
  return _react2['default'].createElement(
    'span',
    null,
    itemType,
    ' ',
    itemString
  );
};
var defaultLabelRenderer = function defaultLabelRenderer(_ref) {
  var label = _ref[0];
  return _react2['default'].createElement(
    'span',
    null,
    label,
    ':'
  );
};
var noCustomNode = function noCustomNode() {
  return false;
};

function checkLegacyTheming(theme, props) {
  var deprecatedStylingMethodsMap = {
    getArrowStyle: 'arrow',
    getListStyle: 'nestedNodeChildren',
    getItemStringStyle: 'nestedNodeItemString',
    getLabelStyle: 'label',
    getValueStyle: 'valueText'
  };

  var deprecatedStylingMethods = (0, _keys2['default'])(deprecatedStylingMethodsMap).filter(function (name) {
    return props[name];
  });

  if (deprecatedStylingMethods.length > 0) {
    if (typeof theme === 'string') {
      theme = {
        extend: theme
      };
    } else {
      theme = (0, _extends3['default'])({}, theme);
    }

    deprecatedStylingMethods.forEach(function (name) {
      // eslint-disable-next-line no-console
      console.error('Styling method "' + name + '" is deprecated, use "theme" property instead');

      theme[deprecatedStylingMethodsMap[name]] = function (_ref2) {
        for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
          args[_key - 1] = arguments[_key];
        }

        var style = _ref2.style;
        return {
          style: (0, _extends3['default'])({}, style, props[name].apply(props, args))
        };
      };
    });
  }

  return theme;
}

function getStateFromProps(props) {
  var theme = checkLegacyTheming(props.theme, props);
  if (props.invertTheme) {
    if (typeof theme === 'string') {
      theme = theme + ':inverted';
    } else if (theme && theme.extend) {
      if (typeof theme === 'string') {
        theme = (0, _extends3['default'])({}, theme, { extend: theme.extend + ':inverted' });
      } else {
        theme = (0, _extends3['default'])({}, theme, { extend: (0, _reactBase16Styling.invertTheme)(theme.extend) });
      }
    } else if (theme) {
      theme = (0, _reactBase16Styling.invertTheme)(theme);
    }
  }
  return {
    styling: (0, _createStylingFromTheme2['default'])(theme)
  };
}

var JSONTree = function (_React$Component) {
  (0, _inherits3['default'])(JSONTree, _React$Component);

  function JSONTree(props) {
    (0, _classCallCheck3['default'])(this, JSONTree);

    var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props));

    _this.state = getStateFromProps(props);
    return _this;
  }

  JSONTree.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
    var _this2 = this;

    if (['theme', 'invertTheme'].find(function (k) {
      return nextProps[k] !== _this2.props[k];
    })) {
      this.setState(getStateFromProps(nextProps));
    }
  };

  JSONTree.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
    var _this3 = this;

    return !!(0, _keys2['default'])(nextProps).find(function (k) {
      return k === 'keyPath' ? nextProps[k].join('/') !== _this3.props[k].join('/') : nextProps[k] !== _this3.props[k];
    });
  };

  JSONTree.prototype.render = function render() {
    var _props = this.props,
        value = _props.data,
        keyPath = _props.keyPath,
        postprocessValue = _props.postprocessValue,
        hideRoot = _props.hideRoot,
        theme = _props.theme,
        _ = _props.invertTheme,
        rest = (0, _objectWithoutProperties3['default'])(_props, ['data', 'keyPath', 'postprocessValue', 'hideRoot', 'theme', 'invertTheme']);
    var styling = this.state.styling;


    return _react2['default'].createElement(
      'ul',
      styling('tree'),
      _react2['default'].createElement(_JSONNode2['default'], (0, _extends3['default'])({}, (0, _extends3['default'])({ postprocessValue: postprocessValue, hideRoot: hideRoot, styling: styling }, rest), {
        keyPath: hideRoot ? [] : keyPath,
        value: postprocessValue(value)
      }))
    );
  };

  return JSONTree;
}(_react2['default'].Component);

JSONTree.propTypes = {
  data: _propTypes2['default'].oneOfType([_propTypes2['default'].array, _propTypes2['default'].object]).isRequired,
  hideRoot: _propTypes2['default'].bool,
  theme: _propTypes2['default'].oneOfType([_propTypes2['default'].object, _propTypes2['default'].string]),
  invertTheme: _propTypes2['default'].bool,
  keyPath: _propTypes2['default'].arrayOf(_propTypes2['default'].oneOfType([_propTypes2['default'].string, _propTypes2['default'].number])),
  postprocessValue: _propTypes2['default'].func,
  sortObjectKeys: _propTypes2['default'].oneOfType([_propTypes2['default'].func, _propTypes2['default'].bool])
};
JSONTree.defaultProps = {
  shouldExpandNode: expandRootNode,
  hideRoot: false,
  keyPath: ['root'],
  getItemString: defaultItemString,
  labelRenderer: defaultLabelRenderer,
  valueRenderer: identity,
  postprocessValue: identity,
  isCustomNode: noCustomNode,
  collectionLimit: 50,
  invertTheme: true
};
exports['default'] = JSONTree;

/***/ }),

/***/ "fNmR":
/*!*************************************************************!*\
  !*** ./node_modules/@jupyterlab/codeeditor/lib/mimetype.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * A namespace for `IEditorMimeTypeService`.
 */
var IEditorMimeTypeService;
(function (IEditorMimeTypeService) {
    /**
     * The default mime type.
     */
    IEditorMimeTypeService.defaultMimeType = 'text/plain';
})(IEditorMimeTypeService = exports.IEditorMimeTypeService || (exports.IEditorMimeTypeService = {}));


/***/ }),

/***/ "fNzb":
/*!*************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/ImageAccordion.js ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _PlotlyFold = __webpack_require__(/*! ./PlotlyFold */ "mQPs");

var _PlotlyFold2 = _interopRequireDefault(_PlotlyFold);

var _derived = __webpack_require__(/*! ./derived */ "ykRn");

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _PanelEmpty = __webpack_require__(/*! ./PanelEmpty */ "o21U");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var ImageFold = (0, _lib.connectImageToLayout)(_PlotlyFold2.default);

var ImageAccordion = function (_Component) {
  _inherits(ImageAccordion, _Component);

  function ImageAccordion() {
    _classCallCheck(this, ImageAccordion);

    return _possibleConstructorReturn(this, (ImageAccordion.__proto__ || Object.getPrototypeOf(ImageAccordion)).apply(this, arguments));
  }

  _createClass(ImageAccordion, [{
    key: 'render',
    value: function render() {
      var _context = this.context,
          _context$layout$image = _context.layout.images,
          images = _context$layout$image === undefined ? [] : _context$layout$image,
          _ = _context.localize;
      var _props = this.props,
          canAdd = _props.canAdd,
          children = _props.children;


      var content = images.length && images.map(function (img, i) {
        return _react2.default.createElement(
          ImageFold,
          { key: i, imageIndex: i, name: _('Image') + ' ' + (i + 1), canDelete: canAdd },
          children
        );
      });

      var addAction = {
        label: _('Image'),
        handler: function handler(_ref) {
          var layout = _ref.layout,
              updateContainer = _ref.updateContainer;

          var imageIndex = void 0;
          if (Array.isArray(layout.images)) {
            imageIndex = layout.images.length;
          } else {
            imageIndex = 0;
          }

          var key = 'images[' + imageIndex + ']';
          var value = {
            sizex: 0.1,
            sizey: 0.1,
            x: 0.5,
            y: 0.5
          };

          if (updateContainer) {
            updateContainer(_defineProperty({}, key, value));
          }
        }
      };

      return _react2.default.createElement(
        _derived.LayoutPanel,
        { addAction: canAdd ? addAction : null },
        content ? content : _react2.default.createElement(
          _PanelEmpty.PanelMessage,
          { heading: _('Logos, watermarks and more.') },
          _react2.default.createElement(
            'p',
            null,
            _('Embed images in your figure to make the data more readable or to brand your content.')
          ),
          _react2.default.createElement(
            'p',
            null,
            _('Click on the + button above to add an image.')
          )
        )
      );
    }
  }]);

  return ImageAccordion;
}(_react.Component);

ImageAccordion.contextTypes = {
  layout: _propTypes2.default.object,
  localize: _propTypes2.default.func
};

ImageAccordion.propTypes = {
  children: _propTypes2.default.node,
  canAdd: _propTypes2.default.bool
};

exports.default = ImageAccordion;
//# sourceMappingURL=ImageAccordion.js.map

/***/ }),

/***/ "fP2p":
/*!******************************************************************!*\
  !*** ./node_modules/@jupyterlab/notebook-extension/lib/index.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const application_1 = __webpack_require__(/*! @jupyterlab/application */ "FkFl");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const codeeditor_1 = __webpack_require__(/*! @jupyterlab/codeeditor */ "sLCx");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const coreutils_2 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const filebrowser_1 = __webpack_require__(/*! @jupyterlab/filebrowser */ "my6z");
const launcher_1 = __webpack_require__(/*! @jupyterlab/launcher */ "78yt");
const mainmenu_1 = __webpack_require__(/*! @jupyterlab/mainmenu */ "N4Qf");
const notebook_1 = __webpack_require__(/*! @jupyterlab/notebook */ "JOGU");
const rendermime_1 = __webpack_require__(/*! @jupyterlab/rendermime */ "Towz");
const messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
/**
 * The command IDs used by the notebook plugin.
 */
var CommandIDs;
(function (CommandIDs) {
    CommandIDs.createNew = 'notebook:create-new';
    CommandIDs.interrupt = 'notebook:interrupt-kernel';
    CommandIDs.restart = 'notebook:restart-kernel';
    CommandIDs.restartClear = 'notebook:restart-clear-output';
    CommandIDs.restartRunAll = 'notebook:restart-run-all';
    CommandIDs.reconnectToKernel = 'notebook:reconnect-to-kernel';
    CommandIDs.changeKernel = 'notebook:change-kernel';
    CommandIDs.createConsole = 'notebook:create-console';
    CommandIDs.createOutputView = 'notebook:create-output-view';
    CommandIDs.clearAllOutputs = 'notebook:clear-all-cell-outputs';
    CommandIDs.closeAndShutdown = 'notebook:close-and-shutdown';
    CommandIDs.trust = 'notebook:trust';
    CommandIDs.exportToFormat = 'notebook:export-to-format';
    CommandIDs.run = 'notebook:run-cell';
    CommandIDs.runAndAdvance = 'notebook:run-cell-and-select-next';
    CommandIDs.runAndInsert = 'notebook:run-cell-and-insert-below';
    CommandIDs.runInConsole = 'notebook:run-in-console';
    CommandIDs.runAll = 'notebook:run-all-cells';
    CommandIDs.runAllAbove = 'notebook:run-all-above';
    CommandIDs.runAllBelow = 'notebook:run-all-below';
    CommandIDs.toCode = 'notebook:change-cell-to-code';
    CommandIDs.toMarkdown = 'notebook:change-cell-to-markdown';
    CommandIDs.toRaw = 'notebook:change-cell-to-raw';
    CommandIDs.cut = 'notebook:cut-cell';
    CommandIDs.copy = 'notebook:copy-cell';
    CommandIDs.pasteAbove = 'notebook:paste-cell-above';
    CommandIDs.pasteBelow = 'notebook:paste-cell-below';
    CommandIDs.pasteAndReplace = 'notebook:paste-and-replace-cell';
    CommandIDs.moveUp = 'notebook:move-cell-up';
    CommandIDs.moveDown = 'notebook:move-cell-down';
    CommandIDs.clearOutputs = 'notebook:clear-cell-output';
    CommandIDs.deleteCell = 'notebook:delete-cell';
    CommandIDs.insertAbove = 'notebook:insert-cell-above';
    CommandIDs.insertBelow = 'notebook:insert-cell-below';
    CommandIDs.selectAbove = 'notebook:move-cursor-up';
    CommandIDs.selectBelow = 'notebook:move-cursor-down';
    CommandIDs.extendAbove = 'notebook:extend-marked-cells-above';
    CommandIDs.extendBelow = 'notebook:extend-marked-cells-below';
    CommandIDs.selectAll = 'notebook:select-all';
    CommandIDs.deselectAll = 'notebook:deselect-all';
    CommandIDs.editMode = 'notebook:enter-edit-mode';
    CommandIDs.merge = 'notebook:merge-cells';
    CommandIDs.split = 'notebook:split-cell-at-cursor';
    CommandIDs.commandMode = 'notebook:enter-command-mode';
    CommandIDs.toggleAllLines = 'notebook:toggle-all-cell-line-numbers';
    CommandIDs.undoCellAction = 'notebook:undo-cell-action';
    CommandIDs.redoCellAction = 'notebook:redo-cell-action';
    CommandIDs.markdown1 = 'notebook:change-cell-to-heading-1';
    CommandIDs.markdown2 = 'notebook:change-cell-to-heading-2';
    CommandIDs.markdown3 = 'notebook:change-cell-to-heading-3';
    CommandIDs.markdown4 = 'notebook:change-cell-to-heading-4';
    CommandIDs.markdown5 = 'notebook:change-cell-to-heading-5';
    CommandIDs.markdown6 = 'notebook:change-cell-to-heading-6';
    CommandIDs.hideCode = 'notebook:hide-cell-code';
    CommandIDs.showCode = 'notebook:show-cell-code';
    CommandIDs.hideAllCode = 'notebook:hide-all-cell-code';
    CommandIDs.showAllCode = 'notebook:show-all-cell-code';
    CommandIDs.hideOutput = 'notebook:hide-cell-outputs';
    CommandIDs.showOutput = 'notebook:show-cell-outputs';
    CommandIDs.hideAllOutputs = 'notebook:hide-all-cell-outputs';
    CommandIDs.showAllOutputs = 'notebook:show-all-cell-outputs';
    CommandIDs.enableOutputScrolling = 'notebook:enable-output-scrolling';
    CommandIDs.disableOutputScrolling = 'notebook:disable-output-scrolling';
    CommandIDs.saveWithView = 'notebook:save-with-view';
})(CommandIDs || (CommandIDs = {}));
/**
 * The class name for the notebook icon from the default theme.
 */
const NOTEBOOK_ICON_CLASS = 'jp-NotebookIcon';
/**
 * The name of the factory that creates notebooks.
 */
const FACTORY = 'Notebook';
/**
 * The rank of the cell tools tab in the sidebar
 */
const CELL_TOOLS_RANK = 400;
/**
 * The exluded Export To ...
 * (returned from nbconvert's export list)
 */
const FORMAT_EXCLUDE = ['notebook', 'python', 'custom'];
/**
 * The exluded Cell Inspector Raw NbConvert Formats
 * (returned from nbconvert's export list)
 */
const RAW_FORMAT_EXCLUDE = ['pdf', 'slides', 'script', 'notebook', 'custom'];
/**
 * The default Export To ... formats and their human readable labels.
 */
const FORMAT_LABEL = {
    html: 'HTML',
    latex: 'LaTeX',
    markdown: 'Markdown',
    pdf: 'PDF',
    rst: 'ReStructured Text',
    script: 'Executable Script',
    slides: 'Reveal.js Slides'
};
/**
 * The notebook widget tracker provider.
 */
const trackerPlugin = {
    id: '@jupyterlab/notebook-extension:tracker',
    provides: notebook_1.INotebookTracker,
    requires: [
        mainmenu_1.IMainMenu,
        apputils_1.ICommandPalette,
        notebook_1.NotebookPanel.IContentFactory,
        codeeditor_1.IEditorServices,
        application_1.ILayoutRestorer,
        rendermime_1.IRenderMimeRegistry,
        coreutils_1.ISettingRegistry
    ],
    optional: [filebrowser_1.IFileBrowserFactory, launcher_1.ILauncher],
    activate: activateNotebookHandler,
    autoStart: true
};
/**
 * The notebook cell factory provider.
 */
const factory = {
    id: '@jupyterlab/notebook-extension:factory',
    provides: notebook_1.NotebookPanel.IContentFactory,
    requires: [codeeditor_1.IEditorServices],
    autoStart: true,
    activate: (app, editorServices) => {
        let editorFactory = editorServices.factoryService.newInlineEditor;
        return new notebook_1.NotebookPanel.ContentFactory({ editorFactory });
    }
};
/**
 * The cell tools extension.
 */
const tools = {
    activate: activateCellTools,
    provides: notebook_1.ICellTools,
    id: '@jupyterlab/notebook-extension:tools',
    autoStart: true,
    requires: [notebook_1.INotebookTracker, codeeditor_1.IEditorServices, coreutils_1.IStateDB]
};
/**
 * Export the plugins as default.
 */
const plugins = [factory, trackerPlugin, tools];
exports.default = plugins;
/**
 * Activate the cell tools extension.
 */
function activateCellTools(app, tracker, editorServices, state) {
    const id = 'cell-tools';
    const celltools = new notebook_1.CellTools({ tracker });
    const activeCellTool = new notebook_1.CellTools.ActiveCellTool();
    const slideShow = notebook_1.CellTools.createSlideShowSelector();
    const editorFactory = editorServices.factoryService.newInlineEditor;
    const metadataEditor = new notebook_1.CellTools.MetadataEditorTool({ editorFactory });
    const services = app.serviceManager;
    // Create message hook for triggers to save to the database.
    const hook = (sender, message) => {
        switch (message.type) {
            case 'activate-request':
                state.save(id, { open: true });
                break;
            case 'after-hide':
            case 'close-request':
                state.remove(id);
                break;
            default:
                break;
        }
        return true;
    };
    let optionsMap = {};
    optionsMap.None = '-';
    services.nbconvert.getExportFormats().then(response => {
        if (response) {
            // convert exportList to palette and menu items
            const formatList = Object.keys(response);
            formatList.forEach(function (key) {
                if (RAW_FORMAT_EXCLUDE.indexOf(key) === -1) {
                    let capCaseKey = key[0].toUpperCase() + key.substr(1);
                    let labelStr = FORMAT_LABEL[key] ? FORMAT_LABEL[key] : capCaseKey;
                    let mimeType = response[key].output_mimetype;
                    optionsMap[labelStr] = mimeType;
                }
            });
            const nbConvert = notebook_1.CellTools.createNBConvertSelector(optionsMap);
            celltools.addItem({ tool: nbConvert, rank: 3 });
        }
    });
    celltools.title.iconClass = 'jp-BuildIcon jp-SideBar-tabIcon';
    celltools.title.caption = 'Cell Inspector';
    celltools.id = id;
    celltools.addItem({ tool: activeCellTool, rank: 1 });
    celltools.addItem({ tool: slideShow, rank: 2 });
    celltools.addItem({ tool: metadataEditor, rank: 4 });
    messaging_1.MessageLoop.installMessageHook(celltools, hook);
    // Wait until the application has finished restoring before rendering.
    Promise.all([state.fetch(id), app.restored]).then(([args]) => {
        const open = !!(args && args['open']);
        // After initial restoration, check if the cell tools should render.
        if (tracker.size) {
            app.shell.addToLeftArea(celltools, { rank: CELL_TOOLS_RANK });
            if (open) {
                app.shell.activateById(celltools.id);
            }
        }
        // For all subsequent widget changes, check if the cell tools should render.
        app.shell.currentChanged.connect((sender, args) => {
            // If there are any open notebooks, add cell tools to the side panel if
            // it is not already there.
            if (tracker.size) {
                if (!celltools.isAttached) {
                    app.shell.addToLeftArea(celltools, { rank: CELL_TOOLS_RANK });
                }
                return;
            }
            // If there are no notebooks, close cell tools.
            celltools.close();
        });
    });
    return Promise.resolve(celltools);
}
/**
 * Activate the notebook handler extension.
 */
function activateNotebookHandler(app, mainMenu, palette, contentFactory, editorServices, restorer, rendermime, settingRegistry, browserFactory, launcher) {
    const services = app.serviceManager;
    // An object for tracking the current notebook settings.
    let editorConfig = notebook_1.StaticNotebook.defaultEditorConfig;
    const factory = new notebook_1.NotebookWidgetFactory({
        name: FACTORY,
        fileTypes: ['notebook'],
        modelName: 'notebook',
        defaultFor: ['notebook'],
        preferKernel: true,
        canStartKernel: true,
        rendermime: rendermime,
        contentFactory,
        editorConfig,
        mimeTypeService: editorServices.mimeTypeService
    });
    const { commands, restored } = app;
    const tracker = new notebook_1.NotebookTracker({ namespace: 'notebook' });
    // Handle state restoration.
    restorer.restore(tracker, {
        command: 'docmanager:open',
        args: panel => ({ path: panel.context.path, factory: FACTORY }),
        name: panel => panel.context.path,
        when: services.ready
    });
    let registry = app.docRegistry;
    registry.addModelFactory(new notebook_1.NotebookModelFactory({}));
    registry.addWidgetFactory(factory);
    addCommands(app, services, tracker);
    populatePalette(palette, services);
    let id = 0; // The ID counter for notebook panels.
    factory.widgetCreated.connect((sender, widget) => {
        // If the notebook panel does not have an ID, assign it one.
        widget.id = widget.id || `notebook-${++id}`;
        widget.title.icon = NOTEBOOK_ICON_CLASS;
        // Notify the instance tracker if restore data needs to update.
        widget.context.pathChanged.connect(() => {
            tracker.save(widget);
        });
        // Add the notebook panel to the tracker.
        tracker.add(widget);
    });
    /**
     * Update the setting values.
     */
    function updateConfig(settings) {
        let cached = settings.get('codeCellConfig').composite;
        let code = Object.assign({}, notebook_1.StaticNotebook.defaultEditorConfig.code);
        Object.keys(code).forEach((key) => {
            code[key] =
                cached[key] === null || cached[key] === undefined
                    ? code[key]
                    : cached[key];
        });
        cached = settings.get('markdownCellConfig').composite;
        let markdown = Object.assign({}, notebook_1.StaticNotebook.defaultEditorConfig.markdown);
        Object.keys(markdown).forEach((key) => {
            markdown[key] =
                cached[key] === null || cached[key] === undefined
                    ? markdown[key]
                    : cached[key];
        });
        cached = settings.get('rawCellConfig').composite;
        let raw = Object.assign({}, notebook_1.StaticNotebook.defaultEditorConfig.raw);
        Object.keys(raw).forEach((key) => {
            raw[key] =
                cached[key] === null || cached[key] === undefined
                    ? raw[key]
                    : cached[key];
        });
        factory.editorConfig = editorConfig = { code, markdown, raw };
    }
    /**
     * Update the settings of the current tracker instances.
     */
    function updateTracker() {
        tracker.forEach(widget => {
            widget.content.editorConfig = editorConfig;
        });
    }
    // Fetch the initial state of the settings.
    Promise.all([settingRegistry.load(trackerPlugin.id), restored])
        .then(([settings]) => {
        updateConfig(settings);
        updateTracker();
        settings.changed.connect(() => {
            updateConfig(settings);
            updateTracker();
        });
    })
        .catch((reason) => {
        console.error(reason.message);
        updateTracker();
    });
    // Add main menu notebook menu.
    populateMenus(app, mainMenu, tracker, services, palette);
    // Utility function to create a new notebook.
    const createNew = (cwd, kernelName) => {
        return commands
            .execute('docmanager:new-untitled', { path: cwd, type: 'notebook' })
            .then(model => {
            return commands.execute('docmanager:open', {
                path: model.path,
                factory: FACTORY,
                kernel: { name: kernelName }
            });
        });
    };
    // Add a command for creating a new notebook.
    commands.addCommand(CommandIDs.createNew, {
        label: args => {
            const kernelName = args['kernelName'] || '';
            if (args['isLauncher'] && args['kernelName']) {
                return services.specs.kernelspecs[kernelName].display_name;
            }
            if (args['isPalette']) {
                return 'New Notebook';
            }
            return 'Notebook';
        },
        caption: 'Create a new notebook',
        iconClass: args => (args['isPalette'] ? '' : 'jp-NotebookIcon'),
        execute: args => {
            const cwd = args['cwd'] ||
                (browserFactory ? browserFactory.defaultBrowser.model.path : '');
            const kernelName = args['kernelName'] || '';
            return createNew(cwd, kernelName);
        }
    });
    // Add a launcher item if the launcher is available.
    if (launcher) {
        services.ready.then(() => {
            const specs = services.specs;
            const baseUrl = coreutils_1.PageConfig.getBaseUrl();
            for (let name in specs.kernelspecs) {
                let rank = name === specs.default ? 0 : Infinity;
                let kernelIconUrl = specs.kernelspecs[name].resources['logo-64x64'];
                if (kernelIconUrl) {
                    let index = kernelIconUrl.indexOf('kernelspecs');
                    kernelIconUrl = baseUrl + kernelIconUrl.slice(index);
                }
                launcher.add({
                    command: CommandIDs.createNew,
                    args: { isLauncher: true, kernelName: name },
                    category: 'Notebook',
                    rank,
                    kernelIconUrl
                });
            }
        });
    }
    // Cell context menu groups
    app.contextMenu.addItem({
        type: 'separator',
        selector: '.jp-Notebook .jp-Cell',
        rank: 0
    });
    app.contextMenu.addItem({
        command: CommandIDs.cut,
        selector: '.jp-Notebook .jp-Cell',
        rank: 1
    });
    app.contextMenu.addItem({
        command: CommandIDs.copy,
        selector: '.jp-Notebook .jp-Cell',
        rank: 2
    });
    app.contextMenu.addItem({
        command: CommandIDs.pasteBelow,
        selector: '.jp-Notebook .jp-Cell',
        rank: 3
    });
    app.contextMenu.addItem({
        type: 'separator',
        selector: '.jp-Notebook .jp-Cell',
        rank: 4
    });
    app.contextMenu.addItem({
        command: CommandIDs.deleteCell,
        selector: '.jp-Notebook .jp-Cell',
        rank: 5
    });
    app.contextMenu.addItem({
        type: 'separator',
        selector: '.jp-Notebook .jp-Cell',
        rank: 6
    });
    app.contextMenu.addItem({
        command: CommandIDs.split,
        selector: '.jp-Notebook .jp-Cell',
        rank: 7
    });
    app.contextMenu.addItem({
        type: 'separator',
        selector: '.jp-Notebook .jp-Cell',
        rank: 8
    });
    // CodeCell context menu groups
    app.contextMenu.addItem({
        command: CommandIDs.createOutputView,
        selector: '.jp-Notebook .jp-CodeCell',
        rank: 9
    });
    app.contextMenu.addItem({
        type: 'separator',
        selector: '.jp-Notebook .jp-CodeCell',
        rank: 10
    });
    app.contextMenu.addItem({
        command: CommandIDs.clearOutputs,
        selector: '.jp-Notebook .jp-CodeCell',
        rank: 11
    });
    // Notebook context menu groups
    app.contextMenu.addItem({
        command: CommandIDs.clearAllOutputs,
        selector: '.jp-Notebook',
        rank: 0
    });
    app.contextMenu.addItem({
        type: 'separator',
        selector: '.jp-Notebook',
        rank: 1
    });
    app.contextMenu.addItem({
        command: CommandIDs.enableOutputScrolling,
        selector: '.jp-Notebook',
        rank: 2
    });
    app.contextMenu.addItem({
        command: CommandIDs.disableOutputScrolling,
        selector: '.jp-Notebook',
        rank: 3
    });
    app.contextMenu.addItem({
        type: 'separator',
        selector: '.jp-Notebook',
        rank: 4
    });
    app.contextMenu.addItem({
        command: CommandIDs.undoCellAction,
        selector: '.jp-Notebook',
        rank: 5
    });
    app.contextMenu.addItem({
        command: CommandIDs.redoCellAction,
        selector: '.jp-Notebook',
        rank: 6
    });
    app.contextMenu.addItem({
        command: CommandIDs.restart,
        selector: '.jp-Notebook',
        rank: 7
    });
    app.contextMenu.addItem({
        type: 'separator',
        selector: '.jp-Notebook',
        rank: 8
    });
    app.contextMenu.addItem({
        command: CommandIDs.createConsole,
        selector: '.jp-Notebook',
        rank: 9
    });
    return tracker;
}
/**
 * Add the notebook commands to the application's command registry.
 */
function addCommands(app, services, tracker) {
    const { commands, shell } = app;
    // Get the current widget and activate unless the args specify otherwise.
    function getCurrent(args) {
        const widget = tracker.currentWidget;
        const activate = args['activate'] !== false;
        if (activate && widget) {
            shell.activateById(widget.id);
        }
        return widget;
    }
    /**
     * Whether there is an active notebook.
     */
    function isEnabled() {
        return (tracker.currentWidget !== null &&
            tracker.currentWidget === app.shell.currentWidget);
    }
    /**
     * Whether there is an notebook active, with a single selected cell.
     */
    function isEnabledAndSingleSelected() {
        if (!isEnabled()) {
            return false;
        }
        const { content } = tracker.currentWidget;
        const index = content.activeCellIndex;
        // If there are selections that are not the active cell,
        // this command is confusing, so disable it.
        for (let i = 0; i < content.widgets.length; ++i) {
            if (content.isSelected(content.widgets[i]) && i !== index) {
                return false;
            }
        }
        return true;
    }
    commands.addCommand(CommandIDs.runAndAdvance, {
        label: 'Run Selected Cells',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                const { context, content } = current;
                return notebook_1.NotebookActions.runAndAdvance(content, context.session);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.run, {
        label: "Run Selected Cells and Don't Advance",
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                const { context, content } = current;
                return notebook_1.NotebookActions.run(content, context.session);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.runAndInsert, {
        label: 'Run Selected Cells and Insert Below',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                const { context, content } = current;
                return notebook_1.NotebookActions.runAndInsert(content, context.session);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.runInConsole, {
        label: 'Run Selected Text or Current Line in Console',
        execute: (args) => __awaiter(this, void 0, void 0, function* () {
            // Default to not activating the notebook (thereby putting the notebook
            // into command mode)
            const current = getCurrent(Object.assign({ activate: false }, args));
            if (!current) {
                return;
            }
            const { context, content } = current;
            let cell = content.activeCell;
            let path = context.path;
            // ignore action in non-code cell
            if (!cell || cell.model.type !== 'code') {
                return;
            }
            let code;
            const editor = cell.editor;
            const selection = editor.getSelection();
            const { start, end } = selection;
            let selected = start.column !== end.column || start.line !== end.line;
            if (selected) {
                // Get the selected code from the editor.
                const start = editor.getOffsetAt(selection.start);
                const end = editor.getOffsetAt(selection.end);
                code = editor.model.value.text.substring(start, end);
            }
            else {
                // no selection, submit whole line and advance
                code = editor.getLine(selection.start.line);
                const cursor = editor.getCursorPosition();
                if (cursor.line + 1 !== editor.lineCount) {
                    editor.setCursorPosition({
                        line: cursor.line + 1,
                        column: cursor.column
                    });
                }
            }
            if (!code) {
                return;
            }
            yield commands.execute('console:open', {
                activate: false,
                insertMode: 'split-bottom',
                path
            });
            yield commands.execute('console:inject', {
                activate: false,
                code,
                path
            });
        }),
        isEnabled
    });
    commands.addCommand(CommandIDs.runAll, {
        label: 'Run All Cells',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                const { context, content } = current;
                return notebook_1.NotebookActions.runAll(content, context.session);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.runAllAbove, {
        label: 'Run All Above Selected Cell',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                const { context, content } = current;
                return notebook_1.NotebookActions.runAllAbove(content, context.session);
            }
        },
        isEnabled: () => {
            // Can't run above if there are multiple cells selected,
            // or if we are at the top of the notebook.
            return (isEnabledAndSingleSelected() &&
                tracker.currentWidget.content.activeCellIndex !== 0);
        }
    });
    commands.addCommand(CommandIDs.runAllBelow, {
        label: 'Run Selected Cell and All Below',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                const { context, content } = current;
                return notebook_1.NotebookActions.runAllBelow(content, context.session);
            }
        },
        isEnabled: () => {
            // Can't run below if there are multiple cells selected,
            // or if we are at the bottom of the notebook.
            return (isEnabledAndSingleSelected() &&
                tracker.currentWidget.content.activeCellIndex !==
                    tracker.currentWidget.content.widgets.length - 1);
        }
    });
    commands.addCommand(CommandIDs.restart, {
        label: 'Restart Kernel…',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return current.session.restart();
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.closeAndShutdown, {
        label: 'Close and Shutdown',
        execute: args => {
            const current = getCurrent(args);
            if (!current) {
                return;
            }
            const fileName = current.title.label;
            return apputils_1.showDialog({
                title: 'Shutdown the notebook?',
                body: `Are you sure you want to close "${fileName}"?`,
                buttons: [apputils_1.Dialog.cancelButton(), apputils_1.Dialog.warnButton()]
            }).then(result => {
                if (result.button.accept) {
                    return current.context.session.shutdown().then(() => {
                        current.dispose();
                    });
                }
            });
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.trust, {
        label: () => 'Trust Notebook',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                const { context, content } = current;
                return notebook_1.NotebookActions.trust(content).then(() => context.save());
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.exportToFormat, {
        label: args => {
            const formatLabel = args['label'];
            return (args['isPalette'] ? 'Export Notebook to ' : '') + formatLabel;
        },
        execute: args => {
            const current = getCurrent(args);
            if (!current) {
                return;
            }
            const notebookPath = coreutils_1.URLExt.encodeParts(current.context.path);
            const url = coreutils_1.URLExt.join(services.serverSettings.baseUrl, 'nbconvert', args['format'], notebookPath) + '?download=true';
            const child = window.open('', '_blank');
            const { context } = current;
            if (context.model.dirty && !context.model.readOnly) {
                return context.save().then(() => {
                    child.location.assign(url);
                });
            }
            return new Promise(resolve => {
                child.location.assign(url);
                resolve(undefined);
            });
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.restartClear, {
        label: 'Restart Kernel and Clear All Outputs…',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                const { content, session } = current;
                return session.restart().then(() => {
                    notebook_1.NotebookActions.clearAllOutputs(content);
                });
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.restartRunAll, {
        label: 'Restart Kernel and Run All Cells…',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                const { context, content, session } = current;
                return session.restart().then(restarted => {
                    if (restarted) {
                        notebook_1.NotebookActions.runAll(content, context.session);
                    }
                    return restarted;
                });
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.clearAllOutputs, {
        label: 'Clear All Outputs',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.clearAllOutputs(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.clearOutputs, {
        label: 'Clear Outputs',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.clearOutputs(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.interrupt, {
        label: 'Interrupt Kernel',
        execute: args => {
            const current = getCurrent(args);
            if (!current) {
                return;
            }
            const kernel = current.context.session.kernel;
            if (kernel) {
                return kernel.interrupt();
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.toCode, {
        label: 'Change to Code Cell Type',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.changeCellType(current.content, 'code');
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.toMarkdown, {
        label: 'Change to Markdown Cell Type',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.changeCellType(current.content, 'markdown');
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.toRaw, {
        label: 'Change to Raw Cell Type',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.changeCellType(current.content, 'raw');
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.cut, {
        label: 'Cut Cells',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.cut(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.copy, {
        label: 'Copy Cells',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.copy(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.pasteBelow, {
        label: 'Paste Cells Below',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.paste(current.content, 'below');
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.pasteAbove, {
        label: 'Paste Cells Above',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.paste(current.content, 'above');
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.pasteAndReplace, {
        label: 'Paste Cells and Replace',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.paste(current.content, 'replace');
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.deleteCell, {
        label: 'Delete Cells',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.deleteCells(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.split, {
        label: 'Split Cell',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.splitCell(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.merge, {
        label: 'Merge Selected Cells',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.mergeCells(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.insertAbove, {
        label: 'Insert Cell Above',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.insertAbove(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.insertBelow, {
        label: 'Insert Cell Below',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.insertBelow(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.selectAbove, {
        label: 'Select Cell Above',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.selectAbove(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.selectBelow, {
        label: 'Select Cell Below',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.selectBelow(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.extendAbove, {
        label: 'Extend Selection Above',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.extendSelectionAbove(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.extendBelow, {
        label: 'Extend Selection Below',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.extendSelectionBelow(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.selectAll, {
        label: 'Select All Cells',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.selectAll(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.deselectAll, {
        label: 'Deselect All Cells',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.deselectAll(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.moveUp, {
        label: 'Move Cells Up',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.moveUp(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.moveDown, {
        label: 'Move Cells Down',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.moveDown(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.toggleAllLines, {
        label: 'Toggle All Line Numbers',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.toggleAllLineNumbers(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.commandMode, {
        label: 'Enter Command Mode',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                current.content.mode = 'command';
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.editMode, {
        label: 'Enter Edit Mode',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                current.content.mode = 'edit';
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.undoCellAction, {
        label: 'Undo Cell Operation',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.undo(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.redoCellAction, {
        label: 'Redo Cell Operation',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.redo(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.changeKernel, {
        label: 'Change Kernel…',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return current.context.session.selectKernel();
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.reconnectToKernel, {
        label: 'Reconnect To Kernel',
        execute: args => {
            const current = getCurrent(args);
            if (!current) {
                return;
            }
            const kernel = current.context.session.kernel;
            if (kernel) {
                return kernel.reconnect();
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.createOutputView, {
        label: 'Create New View for Output',
        execute: args => {
            // Clone the OutputArea
            const current = getCurrent(Object.assign({}, args, { activate: false }));
            const nb = current.content;
            const content = nb.activeCell.cloneOutputArea();
            // Create a MainAreaWidget
            const widget = new apputils_1.MainAreaWidget({ content });
            widget.id = `LinkedOutputView-${coreutils_2.UUID.uuid4()}`;
            widget.title.label = 'Output View';
            widget.title.icon = NOTEBOOK_ICON_CLASS;
            widget.title.caption = current.title.label
                ? `For Notebook: ${current.title.label}`
                : 'For Notebook:';
            widget.addClass('jp-LinkedOutputView');
            current.context.addSibling(widget, {
                ref: current.id,
                mode: 'split-bottom'
            });
            // Remove the output view if the parent notebook is closed.
            nb.disposed.connect(widget.dispose);
        },
        isEnabled: isEnabledAndSingleSelected
    });
    commands.addCommand(CommandIDs.createConsole, {
        label: 'New Console for Notebook',
        execute: args => {
            const current = getCurrent(Object.assign({}, args, { activate: false }));
            const widget = tracker.currentWidget;
            if (!current || !widget) {
                return;
            }
            const options = {
                path: widget.context.path,
                preferredLanguage: widget.context.model.defaultKernelLanguage,
                activate: args['activate'],
                ref: current.id,
                insertMode: 'split-bottom'
            };
            return commands.execute('console:create', options);
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.markdown1, {
        label: 'Change to Heading 1',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.setMarkdownHeader(current.content, 1);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.markdown2, {
        label: 'Change to Heading 2',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.setMarkdownHeader(current.content, 2);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.markdown3, {
        label: 'Change to Heading 3',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.setMarkdownHeader(current.content, 3);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.markdown4, {
        label: 'Change to Heading 4',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.setMarkdownHeader(current.content, 4);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.markdown5, {
        label: 'Change to Heading 5',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.setMarkdownHeader(current.content, 5);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.markdown6, {
        label: 'Change to Heading 6',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.setMarkdownHeader(current.content, 6);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.hideCode, {
        label: 'Collapse Selected Code',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.hideCode(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.showCode, {
        label: 'Expand Selected Code',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.showCode(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.hideAllCode, {
        label: 'Collapse All Code',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.hideAllCode(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.showAllCode, {
        label: 'Expand All Code',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.showAllCode(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.hideOutput, {
        label: 'Collapse Selected Outputs',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.hideOutput(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.showOutput, {
        label: 'Expand Selected Outputs',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.showOutput(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.hideAllOutputs, {
        label: 'Collapse All Outputs',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.hideAllOutputs(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.showAllOutputs, {
        label: 'Expand All Outputs',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.showAllOutputs(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.enableOutputScrolling, {
        label: 'Enable Scrolling for Outputs',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.enableOutputScrolling(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.disableOutputScrolling, {
        label: 'Disable Scrolling for Outputs',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                return notebook_1.NotebookActions.disableOutputScrolling(current.content);
            }
        },
        isEnabled
    });
    commands.addCommand(CommandIDs.saveWithView, {
        label: 'Save Notebook with View State',
        execute: args => {
            const current = getCurrent(args);
            if (current) {
                notebook_1.NotebookActions.persistViewState(current.content);
                app.commands.execute('docmanager:save');
            }
        },
        isEnabled: args => {
            return isEnabled() && commands.isEnabled('docmanager:save', args);
        }
    });
}
/**
 * Populate the application's command palette with notebook commands.
 */
function populatePalette(palette, services) {
    let category = 'Notebook Operations';
    [
        CommandIDs.interrupt,
        CommandIDs.restart,
        CommandIDs.restartClear,
        CommandIDs.restartRunAll,
        CommandIDs.runAll,
        CommandIDs.runAllAbove,
        CommandIDs.runAllBelow,
        CommandIDs.selectAll,
        CommandIDs.deselectAll,
        CommandIDs.clearAllOutputs,
        CommandIDs.toggleAllLines,
        CommandIDs.editMode,
        CommandIDs.commandMode,
        CommandIDs.changeKernel,
        CommandIDs.reconnectToKernel,
        CommandIDs.createConsole,
        CommandIDs.closeAndShutdown,
        CommandIDs.trust,
        CommandIDs.saveWithView
    ].forEach(command => {
        palette.addItem({ command, category });
    });
    palette.addItem({
        command: CommandIDs.createNew,
        category,
        args: { isPalette: true }
    });
    category = 'Notebook Cell Operations';
    [
        CommandIDs.run,
        CommandIDs.runAndAdvance,
        CommandIDs.runAndInsert,
        CommandIDs.runInConsole,
        CommandIDs.clearOutputs,
        CommandIDs.toCode,
        CommandIDs.toMarkdown,
        CommandIDs.toRaw,
        CommandIDs.cut,
        CommandIDs.copy,
        CommandIDs.pasteBelow,
        CommandIDs.pasteAbove,
        CommandIDs.pasteAndReplace,
        CommandIDs.deleteCell,
        CommandIDs.split,
        CommandIDs.merge,
        CommandIDs.insertAbove,
        CommandIDs.insertBelow,
        CommandIDs.selectAbove,
        CommandIDs.selectBelow,
        CommandIDs.extendAbove,
        CommandIDs.extendBelow,
        CommandIDs.moveDown,
        CommandIDs.moveUp,
        CommandIDs.undoCellAction,
        CommandIDs.redoCellAction,
        CommandIDs.markdown1,
        CommandIDs.markdown2,
        CommandIDs.markdown3,
        CommandIDs.markdown4,
        CommandIDs.markdown5,
        CommandIDs.markdown6,
        CommandIDs.hideCode,
        CommandIDs.showCode,
        CommandIDs.hideAllCode,
        CommandIDs.showAllCode,
        CommandIDs.hideOutput,
        CommandIDs.showOutput,
        CommandIDs.hideAllOutputs,
        CommandIDs.showAllOutputs,
        CommandIDs.enableOutputScrolling,
        CommandIDs.disableOutputScrolling
    ].forEach(command => {
        palette.addItem({ command, category });
    });
}
/**
 * Populates the application menus for the notebook.
 */
function populateMenus(app, mainMenu, tracker, services, palette) {
    let { commands } = app;
    // Add undo/redo hooks to the edit menu.
    mainMenu.editMenu.undoers.add({
        tracker,
        undo: widget => {
            widget.content.activeCell.editor.undo();
        },
        redo: widget => {
            widget.content.activeCell.editor.redo();
        }
    });
    // Add a clearer to the edit menu
    mainMenu.editMenu.clearers.add({
        tracker,
        noun: 'Outputs',
        pluralNoun: 'Outputs',
        clearCurrent: (current) => {
            return notebook_1.NotebookActions.clearOutputs(current.content);
        },
        clearAll: (current) => {
            return notebook_1.NotebookActions.clearAllOutputs(current.content);
        }
    });
    // Add new notebook creation to the file menu.
    mainMenu.fileMenu.newMenu.addGroup([{ command: CommandIDs.createNew }], 10);
    // Add a close and shutdown command to the file menu.
    mainMenu.fileMenu.closeAndCleaners.add({
        tracker,
        action: 'Shutdown',
        name: 'Notebook',
        closeAndCleanup: (current) => {
            const fileName = current.title.label;
            return apputils_1.showDialog({
                title: 'Shutdown the notebook?',
                body: `Are you sure you want to close "${fileName}"?`,
                buttons: [apputils_1.Dialog.cancelButton(), apputils_1.Dialog.warnButton()]
            }).then(result => {
                if (result.button.accept) {
                    return current.context.session.shutdown().then(() => {
                        current.dispose();
                    });
                }
            });
        }
    });
    // Add a save with view command to the file menu.
    mainMenu.fileMenu.persistAndSavers.add({
        tracker,
        action: 'with View State',
        name: 'Notebook',
        persistAndSave: (current) => {
            notebook_1.NotebookActions.persistViewState(current.content);
            return app.commands.execute('docmanager:save');
        }
    });
    // Add a notebook group to the File menu.
    let exportTo = new widgets_1.Menu({ commands });
    exportTo.title.label = 'Export Notebook As…';
    services.nbconvert.getExportFormats().then(response => {
        if (response) {
            // convert exportList to palette and menu items
            const formatList = Object.keys(response);
            const category = 'Notebook Operations';
            formatList.forEach(function (key) {
                let capCaseKey = key[0].toUpperCase() + key.substr(1);
                let labelStr = FORMAT_LABEL[key] ? FORMAT_LABEL[key] : capCaseKey;
                let args = {
                    format: key,
                    label: labelStr,
                    isPalette: true
                };
                if (FORMAT_EXCLUDE.indexOf(key) === -1) {
                    exportTo.addItem({
                        command: CommandIDs.exportToFormat,
                        args: args
                    });
                    palette.addItem({
                        command: CommandIDs.exportToFormat,
                        category,
                        args
                    });
                }
            });
            const fileGroup = [
                { command: CommandIDs.trust },
                { type: 'submenu', submenu: exportTo }
            ];
            mainMenu.fileMenu.addGroup(fileGroup, 10);
        }
    });
    // Add a kernel user to the Kernel menu
    mainMenu.kernelMenu.kernelUsers.add({
        tracker,
        interruptKernel: current => {
            let kernel = current.session.kernel;
            if (kernel) {
                return kernel.interrupt();
            }
            return Promise.resolve(void 0);
        },
        noun: 'All Outputs',
        restartKernel: current => current.session.restart(),
        restartKernelAndClear: current => {
            return current.session.restart().then(restarted => {
                if (restarted) {
                    notebook_1.NotebookActions.clearAllOutputs(current.content);
                }
                return restarted;
            });
        },
        changeKernel: current => current.session.selectKernel(),
        shutdownKernel: current => current.session.shutdown()
    });
    // Add a console creator the the Kernel menu
    mainMenu.fileMenu.consoleCreators.add({
        tracker,
        name: 'Notebook',
        createConsole: current => {
            const options = {
                path: current.context.path,
                preferredLanguage: current.context.model.defaultKernelLanguage,
                activate: true,
                ref: current.id,
                insertMode: 'split-bottom'
            };
            return commands.execute('console:create', options);
        }
    });
    // Add some commands to the application view menu.
    const collapseGroup = [
        CommandIDs.hideCode,
        CommandIDs.hideOutput,
        CommandIDs.hideAllCode,
        CommandIDs.hideAllOutputs
    ].map(command => {
        return { command };
    });
    mainMenu.viewMenu.addGroup(collapseGroup, 10);
    const expandGroup = [
        CommandIDs.showCode,
        CommandIDs.showOutput,
        CommandIDs.showAllCode,
        CommandIDs.showAllOutputs
    ].map(command => {
        return { command };
    });
    mainMenu.viewMenu.addGroup(expandGroup, 11);
    // Add an IEditorViewer to the application view menu
    mainMenu.viewMenu.editorViewers.add({
        tracker,
        toggleLineNumbers: widget => {
            notebook_1.NotebookActions.toggleAllLineNumbers(widget.content);
        },
        lineNumbersToggled: widget => {
            const config = widget.content.editorConfig;
            return !!(config.code.lineNumbers &&
                config.markdown.lineNumbers &&
                config.raw.lineNumbers);
        }
    });
    // Add an ICodeRunner to the application run menu
    mainMenu.runMenu.codeRunners.add({
        tracker,
        noun: 'Cells',
        run: current => {
            const { context, content } = current;
            return notebook_1.NotebookActions.runAndAdvance(content, context.session).then(() => void 0);
        },
        runAll: current => {
            const { context, content } = current;
            return notebook_1.NotebookActions.runAll(content, context.session).then(() => void 0);
        },
        restartAndRunAll: current => {
            const { context, content } = current;
            return context.session.restart().then(restarted => {
                if (restarted) {
                    notebook_1.NotebookActions.runAll(content, context.session);
                }
                return restarted;
            });
        }
    });
    // Add a run+insert and run+don't advance group to the run menu.
    const runExtras = [
        CommandIDs.runAndInsert,
        CommandIDs.run,
        CommandIDs.runInConsole
    ].map(command => {
        return { command };
    });
    // Add a run all above/below group to the run menu.
    const runAboveBelowGroup = [
        CommandIDs.runAllAbove,
        CommandIDs.runAllBelow
    ].map(command => {
        return { command };
    });
    // Add commands to the application edit menu.
    const undoCellActionGroup = [
        CommandIDs.undoCellAction,
        CommandIDs.redoCellAction
    ].map(command => {
        return { command };
    });
    const copyGroup = [
        CommandIDs.cut,
        CommandIDs.copy,
        CommandIDs.pasteBelow,
        CommandIDs.pasteAbove,
        CommandIDs.pasteAndReplace
    ].map(command => {
        return { command };
    });
    const selectGroup = [CommandIDs.selectAll, CommandIDs.deselectAll].map(command => {
        return { command };
    });
    const splitMergeGroup = [CommandIDs.split, CommandIDs.merge].map(command => {
        return { command };
    });
    const moveCellsGroup = [CommandIDs.moveUp, CommandIDs.moveDown].map(command => {
        return { command };
    });
    mainMenu.editMenu.addGroup(undoCellActionGroup, 4);
    mainMenu.editMenu.addGroup(copyGroup, 5);
    mainMenu.editMenu.addGroup([{ command: CommandIDs.deleteCell }], 6);
    mainMenu.editMenu.addGroup(selectGroup, 7);
    mainMenu.editMenu.addGroup(moveCellsGroup, 8);
    mainMenu.editMenu.addGroup(splitMergeGroup, 9);
    mainMenu.runMenu.addGroup(runExtras, 10);
    mainMenu.runMenu.addGroup(runAboveBelowGroup, 11);
    // Add kernel information to the application help menu.
    mainMenu.helpMenu.kernelUsers.add({
        tracker,
        getKernel: current => current.session.kernel
    });
}


/***/ }),

/***/ "fR/l":
/*!************************************************!*\
  !*** ./node_modules/lodash/_baseGetAllKeys.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var arrayPush = __webpack_require__(/*! ./_arrayPush */ "CH3K"),
    isArray = __webpack_require__(/*! ./isArray */ "Z0cm");

/**
 * 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));
}

module.exports = baseGetAllKeys;


/***/ }),

/***/ "fS+6":
/*!***************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/Flaglist.js ***!
  \***************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UnconnectedFlaglist = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _FlaglistCheckboxGroup = __webpack_require__(/*! ../widgets/FlaglistCheckboxGroup */ "yYMQ");

var _FlaglistCheckboxGroup2 = _interopRequireDefault(_FlaglistCheckboxGroup);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UnconnectedFlaglist = exports.UnconnectedFlaglist = function (_Component) {
  _inherits(UnconnectedFlaglist, _Component);

  function UnconnectedFlaglist() {
    _classCallCheck(this, UnconnectedFlaglist);

    return _possibleConstructorReturn(this, (UnconnectedFlaglist.__proto__ || Object.getPrototypeOf(UnconnectedFlaglist)).apply(this, arguments));
  }

  _createClass(UnconnectedFlaglist, [{
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        _Field2.default,
        this.props,
        _react2.default.createElement(_FlaglistCheckboxGroup2.default, {
          options: this.props.options,
          activeOption: this.props.fullValue,
          onChange: this.props.updatePlot
        })
      );
    }
  }]);

  return UnconnectedFlaglist;
}(_react.Component);

UnconnectedFlaglist.propTypes = _extends({
  fullValue: _propTypes2.default.any,
  options: _propTypes2.default.array.isRequired,
  updatePlot: _propTypes2.default.func
}, _Field2.default.propTypes);

exports.default = (0, _lib.connectToContainer)(UnconnectedFlaglist);
//# sourceMappingURL=Flaglist.js.map

/***/ }),

/***/ "fSpj":
/*!*************************************************!*\
  !*** ./node_modules/pbkdf2/lib/precondition.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(Buffer) {var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs

function checkBuffer (buf, name) {
  if (typeof buf !== 'string' && !Buffer.isBuffer(buf)) {
    throw new TypeError(name + ' must be a buffer or string')
  }
}

module.exports = function (password, salt, iterations, keylen) {
  checkBuffer(password, 'Password')
  checkBuffer(salt, 'Salt')

  if (typeof iterations !== 'number') {
    throw new TypeError('Iterations not a number')
  }

  if (iterations < 0) {
    throw new TypeError('Bad iterations')
  }

  if (typeof keylen !== 'number') {
    throw new TypeError('Key length not a number')
  }

  if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */
    throw new TypeError('Bad key length')
  }
}

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../buffer/index.js */ "tjlA").Buffer))

/***/ }),

/***/ "fSz3":
/*!*********************************************************************!*\
  !*** ./node_modules/@jupyterlab/theme-light-extension/lib/index.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
/**
 * A plugin for the Jupyter Light Theme.
 */
const plugin = {
    id: '@jupyterlab/theme-light-extension:plugin',
    requires: [apputils_1.IThemeManager],
    activate: function (app, manager) {
        const style = '@jupyterlab/theme-light-extension/index.css';
        manager.register({
            name: 'JupyterLab Light',
            isLight: true,
            load: () => manager.loadCSS(style),
            unload: () => Promise.resolve(undefined)
        });
    },
    autoStart: true
};
exports.default = plugin;


/***/ }),

/***/ "fXsU":
/*!*******************************************************************!*\
  !*** ./node_modules/core-js/library/modules/core.get-iterator.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var anObject = __webpack_require__(/*! ./_an-object */ "5K7Z");
var get = __webpack_require__(/*! ./core.get-iterator-method */ "fNZA");
module.exports = __webpack_require__(/*! ./_core */ "WEpk").getIterator = function (it) {
  var iterFn = get(it);
  if (typeof iterFn != 'function') throw TypeError(it + ' is not iterable!');
  return anObject(iterFn.call(it));
};


/***/ }),

/***/ "fZAc":
/*!**********************************************!*\
  !*** ./node_modules/fbjs/lib/UnicodeBidi.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks
 * 
 */

/**
 * Basic (stateless) API for text direction detection
 *
 * Part of our implementation of Unicode Bidirectional Algorithm (UBA)
 * Unicode Standard Annex #9 (UAX9)
 * http://www.unicode.org/reports/tr9/
 */



var UnicodeBidiDirection = __webpack_require__(/*! ./UnicodeBidiDirection */ "mjHj");

var invariant = __webpack_require__(/*! ./invariant */ "2NuI");

/**
 * RegExp ranges of characters with a *Strong* Bidi_Class value.
 *
 * Data is based on DerivedBidiClass.txt in UCD version 7.0.0.
 *
 * NOTE: For performance reasons, we only support Unicode's
 *       Basic Multilingual Plane (BMP) for now.
 */
var RANGE_BY_BIDI_TYPE = {

  L: 'A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u01BA\u01BB' + '\u01BC-\u01BF\u01C0-\u01C3\u01C4-\u0293\u0294\u0295-\u02AF\u02B0-\u02B8' + '\u02BB-\u02C1\u02D0-\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376-\u0377' + '\u037A\u037B-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1' + '\u03A3-\u03F5\u03F7-\u0481\u0482\u048A-\u052F\u0531-\u0556\u0559' + '\u055A-\u055F\u0561-\u0587\u0589\u0903\u0904-\u0939\u093B\u093D' + '\u093E-\u0940\u0949-\u094C\u094E-\u094F\u0950\u0958-\u0961\u0964-\u0965' + '\u0966-\u096F\u0970\u0971\u0972-\u0980\u0982-\u0983\u0985-\u098C' + '\u098F-\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD' + '\u09BE-\u09C0\u09C7-\u09C8\u09CB-\u09CC\u09CE\u09D7\u09DC-\u09DD' + '\u09DF-\u09E1\u09E6-\u09EF\u09F0-\u09F1\u09F4-\u09F9\u09FA\u0A03' + '\u0A05-\u0A0A\u0A0F-\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32-\u0A33' + '\u0A35-\u0A36\u0A38-\u0A39\u0A3E-\u0A40\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F' + '\u0A72-\u0A74\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0' + '\u0AB2-\u0AB3\u0AB5-\u0AB9\u0ABD\u0ABE-\u0AC0\u0AC9\u0ACB-\u0ACC\u0AD0' + '\u0AE0-\u0AE1\u0AE6-\u0AEF\u0AF0\u0B02-\u0B03\u0B05-\u0B0C\u0B0F-\u0B10' + '\u0B13-\u0B28\u0B2A-\u0B30\u0B32-\u0B33\u0B35-\u0B39\u0B3D\u0B3E\u0B40' + '\u0B47-\u0B48\u0B4B-\u0B4C\u0B57\u0B5C-\u0B5D\u0B5F-\u0B61\u0B66-\u0B6F' + '\u0B70\u0B71\u0B72-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95' + '\u0B99-\u0B9A\u0B9C\u0B9E-\u0B9F\u0BA3-\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9' + '\u0BBE-\u0BBF\u0BC1-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCC\u0BD0\u0BD7' + '\u0BE6-\u0BEF\u0BF0-\u0BF2\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10' + '\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C41-\u0C44\u0C58-\u0C59\u0C60-\u0C61' + '\u0C66-\u0C6F\u0C7F\u0C82-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8' + '\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CBE\u0CBF\u0CC0-\u0CC4\u0CC6' + '\u0CC7-\u0CC8\u0CCA-\u0CCB\u0CD5-\u0CD6\u0CDE\u0CE0-\u0CE1\u0CE6-\u0CEF' + '\u0CF1-\u0CF2\u0D02-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D' + '\u0D3E-\u0D40\u0D46-\u0D48\u0D4A-\u0D4C\u0D4E\u0D57\u0D60-\u0D61' + '\u0D66-\u0D6F\u0D70-\u0D75\u0D79\u0D7A-\u0D7F\u0D82-\u0D83\u0D85-\u0D96' + '\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCF-\u0DD1\u0DD8-\u0DDF' + '\u0DE6-\u0DEF\u0DF2-\u0DF3\u0DF4\u0E01-\u0E30\u0E32-\u0E33\u0E40-\u0E45' + '\u0E46\u0E4F\u0E50-\u0E59\u0E5A-\u0E5B\u0E81-\u0E82\u0E84\u0E87-\u0E88' + '\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7' + '\u0EAA-\u0EAB\u0EAD-\u0EB0\u0EB2-\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6' + '\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F01-\u0F03\u0F04-\u0F12\u0F13\u0F14' + '\u0F15-\u0F17\u0F1A-\u0F1F\u0F20-\u0F29\u0F2A-\u0F33\u0F34\u0F36\u0F38' + '\u0F3E-\u0F3F\u0F40-\u0F47\u0F49-\u0F6C\u0F7F\u0F85\u0F88-\u0F8C' + '\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FCF\u0FD0-\u0FD4\u0FD5-\u0FD8' + '\u0FD9-\u0FDA\u1000-\u102A\u102B-\u102C\u1031\u1038\u103B-\u103C\u103F' + '\u1040-\u1049\u104A-\u104F\u1050-\u1055\u1056-\u1057\u105A-\u105D\u1061' + '\u1062-\u1064\u1065-\u1066\u1067-\u106D\u106E-\u1070\u1075-\u1081' + '\u1083-\u1084\u1087-\u108C\u108E\u108F\u1090-\u1099\u109A-\u109C' + '\u109E-\u109F\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FB\u10FC' + '\u10FD-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288' + '\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5' + '\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1360-\u1368' + '\u1369-\u137C\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166D-\u166E' + '\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EB-\u16ED\u16EE-\u16F0' + '\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1735-\u1736' + '\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17B6\u17BE-\u17C5' + '\u17C7-\u17C8\u17D4-\u17D6\u17D7\u17D8-\u17DA\u17DC\u17E0-\u17E9' + '\u1810-\u1819\u1820-\u1842\u1843\u1844-\u1877\u1880-\u18A8\u18AA' + '\u18B0-\u18F5\u1900-\u191E\u1923-\u1926\u1929-\u192B\u1930-\u1931' + '\u1933-\u1938\u1946-\u194F\u1950-\u196D\u1970-\u1974\u1980-\u19AB' + '\u19B0-\u19C0\u19C1-\u19C7\u19C8-\u19C9\u19D0-\u19D9\u19DA\u1A00-\u1A16' + '\u1A19-\u1A1A\u1A1E-\u1A1F\u1A20-\u1A54\u1A55\u1A57\u1A61\u1A63-\u1A64' + '\u1A6D-\u1A72\u1A80-\u1A89\u1A90-\u1A99\u1AA0-\u1AA6\u1AA7\u1AA8-\u1AAD' + '\u1B04\u1B05-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B44\u1B45-\u1B4B' + '\u1B50-\u1B59\u1B5A-\u1B60\u1B61-\u1B6A\u1B74-\u1B7C\u1B82\u1B83-\u1BA0' + '\u1BA1\u1BA6-\u1BA7\u1BAA\u1BAE-\u1BAF\u1BB0-\u1BB9\u1BBA-\u1BE5\u1BE7' + '\u1BEA-\u1BEC\u1BEE\u1BF2-\u1BF3\u1BFC-\u1BFF\u1C00-\u1C23\u1C24-\u1C2B' + '\u1C34-\u1C35\u1C3B-\u1C3F\u1C40-\u1C49\u1C4D-\u1C4F\u1C50-\u1C59' + '\u1C5A-\u1C77\u1C78-\u1C7D\u1C7E-\u1C7F\u1CC0-\u1CC7\u1CD3\u1CE1' + '\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF2-\u1CF3\u1CF5-\u1CF6\u1D00-\u1D2B' + '\u1D2C-\u1D6A\u1D6B-\u1D77\u1D78\u1D79-\u1D9A\u1D9B-\u1DBF\u1E00-\u1F15' + '\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D' + '\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC' + '\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200E' + '\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D' + '\u2124\u2126\u2128\u212A-\u212D\u212F-\u2134\u2135-\u2138\u2139' + '\u213C-\u213F\u2145-\u2149\u214E\u214F\u2160-\u2182\u2183-\u2184' + '\u2185-\u2188\u2336-\u237A\u2395\u249C-\u24E9\u26AC\u2800-\u28FF' + '\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2C7B\u2C7C-\u2C7D\u2C7E-\u2CE4' + '\u2CEB-\u2CEE\u2CF2-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F' + '\u2D70\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE' + '\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005\u3006\u3007' + '\u3021-\u3029\u302E-\u302F\u3031-\u3035\u3038-\u303A\u303B\u303C' + '\u3041-\u3096\u309D-\u309E\u309F\u30A1-\u30FA\u30FC-\u30FE\u30FF' + '\u3105-\u312D\u3131-\u318E\u3190-\u3191\u3192-\u3195\u3196-\u319F' + '\u31A0-\u31BA\u31F0-\u31FF\u3200-\u321C\u3220-\u3229\u322A-\u3247' + '\u3248-\u324F\u3260-\u327B\u327F\u3280-\u3289\u328A-\u32B0\u32C0-\u32CB' + '\u32D0-\u32FE\u3300-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DB5' + '\u4E00-\u9FCC\uA000-\uA014\uA015\uA016-\uA48C\uA4D0-\uA4F7\uA4F8-\uA4FD' + '\uA4FE-\uA4FF\uA500-\uA60B\uA60C\uA610-\uA61F\uA620-\uA629\uA62A-\uA62B' + '\uA640-\uA66D\uA66E\uA680-\uA69B\uA69C-\uA69D\uA6A0-\uA6E5\uA6E6-\uA6EF' + '\uA6F2-\uA6F7\uA722-\uA76F\uA770\uA771-\uA787\uA789-\uA78A\uA78B-\uA78E' + '\uA790-\uA7AD\uA7B0-\uA7B1\uA7F7\uA7F8-\uA7F9\uA7FA\uA7FB-\uA801' + '\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA823-\uA824\uA827\uA830-\uA835' + '\uA836-\uA837\uA840-\uA873\uA880-\uA881\uA882-\uA8B3\uA8B4-\uA8C3' + '\uA8CE-\uA8CF\uA8D0-\uA8D9\uA8F2-\uA8F7\uA8F8-\uA8FA\uA8FB\uA900-\uA909' + '\uA90A-\uA925\uA92E-\uA92F\uA930-\uA946\uA952-\uA953\uA95F\uA960-\uA97C' + '\uA983\uA984-\uA9B2\uA9B4-\uA9B5\uA9BA-\uA9BB\uA9BD-\uA9C0\uA9C1-\uA9CD' + '\uA9CF\uA9D0-\uA9D9\uA9DE-\uA9DF\uA9E0-\uA9E4\uA9E6\uA9E7-\uA9EF' + '\uA9F0-\uA9F9\uA9FA-\uA9FE\uAA00-\uAA28\uAA2F-\uAA30\uAA33-\uAA34' + '\uAA40-\uAA42\uAA44-\uAA4B\uAA4D\uAA50-\uAA59\uAA5C-\uAA5F\uAA60-\uAA6F' + '\uAA70\uAA71-\uAA76\uAA77-\uAA79\uAA7A\uAA7B\uAA7D\uAA7E-\uAAAF\uAAB1' + '\uAAB5-\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADC\uAADD\uAADE-\uAADF' + '\uAAE0-\uAAEA\uAAEB\uAAEE-\uAAEF\uAAF0-\uAAF1\uAAF2\uAAF3-\uAAF4\uAAF5' + '\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E' + '\uAB30-\uAB5A\uAB5B\uAB5C-\uAB5F\uAB64-\uAB65\uABC0-\uABE2\uABE3-\uABE4' + '\uABE6-\uABE7\uABE9-\uABEA\uABEB\uABEC\uABF0-\uABF9\uAC00-\uD7A3' + '\uD7B0-\uD7C6\uD7CB-\uD7FB\uE000-\uF8FF\uF900-\uFA6D\uFA70-\uFAD9' + '\uFB00-\uFB06\uFB13-\uFB17\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFF6F\uFF70' + '\uFF71-\uFF9D\uFF9E-\uFF9F\uFFA0-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF' + '\uFFD2-\uFFD7\uFFDA-\uFFDC',

  R: '\u0590\u05BE\u05C0\u05C3\u05C6\u05C8-\u05CF\u05D0-\u05EA\u05EB-\u05EF' + '\u05F0-\u05F2\u05F3-\u05F4\u05F5-\u05FF\u07C0-\u07C9\u07CA-\u07EA' + '\u07F4-\u07F5\u07FA\u07FB-\u07FF\u0800-\u0815\u081A\u0824\u0828' + '\u082E-\u082F\u0830-\u083E\u083F\u0840-\u0858\u085C-\u085D\u085E' + '\u085F-\u089F\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB37\uFB38-\uFB3C' + '\uFB3D\uFB3E\uFB3F\uFB40-\uFB41\uFB42\uFB43-\uFB44\uFB45\uFB46-\uFB4F',

  AL: '\u0608\u060B\u060D\u061B\u061C\u061D\u061E-\u061F\u0620-\u063F\u0640' + '\u0641-\u064A\u066D\u066E-\u066F\u0671-\u06D3\u06D4\u06D5\u06E5-\u06E6' + '\u06EE-\u06EF\u06FA-\u06FC\u06FD-\u06FE\u06FF\u0700-\u070D\u070E\u070F' + '\u0710\u0712-\u072F\u074B-\u074C\u074D-\u07A5\u07B1\u07B2-\u07BF' + '\u08A0-\u08B2\u08B3-\u08E3\uFB50-\uFBB1\uFBB2-\uFBC1\uFBC2-\uFBD2' + '\uFBD3-\uFD3D\uFD40-\uFD4F\uFD50-\uFD8F\uFD90-\uFD91\uFD92-\uFDC7' + '\uFDC8-\uFDCF\uFDF0-\uFDFB\uFDFC\uFDFE-\uFDFF\uFE70-\uFE74\uFE75' + '\uFE76-\uFEFC\uFEFD-\uFEFE'

};

var REGEX_STRONG = new RegExp('[' + RANGE_BY_BIDI_TYPE.L + RANGE_BY_BIDI_TYPE.R + RANGE_BY_BIDI_TYPE.AL + ']');

var REGEX_RTL = new RegExp('[' + RANGE_BY_BIDI_TYPE.R + RANGE_BY_BIDI_TYPE.AL + ']');

/**
 * Returns the first strong character (has Bidi_Class value of L, R, or AL).
 *
 * @param str  A text block; e.g. paragraph, table cell, tag
 * @return     A character with strong bidi direction, or null if not found
 */
function firstStrongChar(str) {
  var match = REGEX_STRONG.exec(str);
  return match == null ? null : match[0];
}

/**
 * Returns the direction of a block of text, based on the direction of its
 * first strong character (has Bidi_Class value of L, R, or AL).
 *
 * @param str  A text block; e.g. paragraph, table cell, tag
 * @return     The resolved direction
 */
function firstStrongCharDir(str) {
  var strongChar = firstStrongChar(str);
  if (strongChar == null) {
    return UnicodeBidiDirection.NEUTRAL;
  }
  return REGEX_RTL.exec(strongChar) ? UnicodeBidiDirection.RTL : UnicodeBidiDirection.LTR;
}

/**
 * Returns the direction of a block of text, based on the direction of its
 * first strong character (has Bidi_Class value of L, R, or AL), or a fallback
 * direction, if no strong character is found.
 *
 * This function is supposed to be used in respect to Higher-Level Protocol
 * rule HL1. (http://www.unicode.org/reports/tr9/#HL1)
 *
 * @param str       A text block; e.g. paragraph, table cell, tag
 * @param fallback  Fallback direction, used if no strong direction detected
 *                  for the block (default = NEUTRAL)
 * @return          The resolved direction
 */
function resolveBlockDir(str, fallback) {
  fallback = fallback || UnicodeBidiDirection.NEUTRAL;
  if (!str.length) {
    return fallback;
  }
  var blockDir = firstStrongCharDir(str);
  return blockDir === UnicodeBidiDirection.NEUTRAL ? fallback : blockDir;
}

/**
 * Returns the direction of a block of text, based on the direction of its
 * first strong character (has Bidi_Class value of L, R, or AL), or a fallback
 * direction, if no strong character is found.
 *
 * NOTE: This function is similar to resolveBlockDir(), but uses the global
 * direction as the fallback, so it *always* returns a Strong direction,
 * making it useful for integration in places that you need to make the final
 * decision, like setting some CSS class.
 *
 * This function is supposed to be used in respect to Higher-Level Protocol
 * rule HL1. (http://www.unicode.org/reports/tr9/#HL1)
 *
 * @param str             A text block; e.g. paragraph, table cell
 * @param strongFallback  Fallback direction, used if no strong direction
 *                        detected for the block (default = global direction)
 * @return                The resolved Strong direction
 */
function getDirection(str, strongFallback) {
  if (!strongFallback) {
    strongFallback = UnicodeBidiDirection.getGlobalDir();
  }
  !UnicodeBidiDirection.isStrong(strongFallback) ?  true ? invariant(false, 'Fallback direction must be a strong direction') : undefined : void 0;
  return resolveBlockDir(str, strongFallback);
}

/**
 * Returns true if getDirection(arguments...) returns LTR.
 *
 * @param str             A text block; e.g. paragraph, table cell
 * @param strongFallback  Fallback direction, used if no strong direction
 *                        detected for the block (default = global direction)
 * @return                True if the resolved direction is LTR
 */
function isDirectionLTR(str, strongFallback) {
  return getDirection(str, strongFallback) === UnicodeBidiDirection.LTR;
}

/**
 * Returns true if getDirection(arguments...) returns RTL.
 *
 * @param str             A text block; e.g. paragraph, table cell
 * @param strongFallback  Fallback direction, used if no strong direction
 *                        detected for the block (default = global direction)
 * @return                True if the resolved direction is RTL
 */
function isDirectionRTL(str, strongFallback) {
  return getDirection(str, strongFallback) === UnicodeBidiDirection.RTL;
}

var UnicodeBidi = {
  firstStrongChar: firstStrongChar,
  firstStrongCharDir: firstStrongCharDir,
  resolveBlockDir: resolveBlockDir,
  getDirection: getDirection,
  isDirectionLTR: isDirectionLTR,
  isDirectionRTL: isDirectionRTL
};

module.exports = UnicodeBidi;

/***/ }),

/***/ "fZJM":
/*!******************************************!*\
  !*** ./node_modules/hash.js/lib/hash.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var hash = exports;

hash.utils = __webpack_require__(/*! ./hash/utils */ "w8CP");
hash.common = __webpack_require__(/*! ./hash/common */ "7ckf");
hash.sha = __webpack_require__(/*! ./hash/sha */ "WRkp");
hash.ripemd = __webpack_require__(/*! ./hash/ripemd */ "u0Sq");
hash.hmac = __webpack_require__(/*! ./hash/hmac */ "ITfd");

// Proxy hash functions to the main object
hash.sha1 = hash.sha.sha1;
hash.sha256 = hash.sha.sha256;
hash.sha224 = hash.sha.sha224;
hash.sha384 = hash.sha.sha384;
hash.sha512 = hash.sha.sha512;
hash.ripemd160 = hash.ripemd.ripemd160;


/***/ }),

/***/ "faBS":
/*!**********************************************!*\
  !*** ./node_modules/fbjs/lib/joinClasses.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks static-only
 */



/**
 * Combines multiple className strings into one.
 * http://jsperf.com/joinclasses-args-vs-array
 *
 * @param {...?string} className
 * @return {string}
 */

function joinClasses(className /*, ... */) {
  if (!className) {
    className = '';
  }
  var nextClass = void 0;
  var argLength = arguments.length;
  if (argLength > 1) {
    for (var ii = 1; ii < argLength; ii++) {
      nextClass = arguments[ii];
      if (nextClass) {
        className = (className ? className + ' ' : '') + nextClass;
      }
    }
  }
  return className;
}

module.exports = joinClasses;

/***/ }),

/***/ "fbbY":
/*!*****************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotBarIcon.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotBarIcon = function PlotBarIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M0 21.313h10.688v5.375H0zm0-7.938h21.375v5.313H0zm0-8.062h32v5.375H0z' })
    );
};

exports.default = PlotBarIcon;

/***/ }),

/***/ "fegh":
/*!****************************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/text_editors/RichText/LinkEditor.js ***!
  \****************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _constants = __webpack_require__(/*! ../../../../lib/constants */ "5Bkx");

var _reactDom = __webpack_require__(/*! react-dom */ "i8i4");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /*
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                * The LinkEditor is a simple UI component that floats below a selected link
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                * in the RichTextEditor, and lets the user enter a URL.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                */

var LinkEditor = function (_Component) {
  _inherits(LinkEditor, _Component);

  function LinkEditor(props) {
    _classCallCheck(this, LinkEditor);

    var _this = _possibleConstructorReturn(this, (LinkEditor.__proto__ || Object.getPrototypeOf(LinkEditor)).call(this, props));

    _this.state = {
      // Use cached position to maintain position during times of focus.
      position: _this.getUpdatedPosition(props),
      originalLinkURL: props.linkURL
    };
    return _this;
  }

  _createClass(LinkEditor, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      // Focus the input field if the URL value is empty
      if (this.props.linkURL.trim() === '') {
        (0, _reactDom.findDOMNode)(this.input).focus();
      }
    }
  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      var props = this.props;

      // Update position if we are editing a new link

      if (nextProps.linkID !== props.linkID) {
        this.setState({
          position: this.getUpdatedPosition(props)
        });
      }
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate() {
      // Cursor dissappears when component rerenders, to make sure it's present
      // we're using setSelection range to make it appear at the end of text:
      // https://github.com/plotly/streambed/issues/9964
      (0, _reactDom.findDOMNode)(this.input).setSelectionRange(this.props.linkURL.length, this.props.linkURL.length);
    }
  }, {
    key: 'getUpdatedPosition',
    value: function getUpdatedPosition(props) {
      var _props$coordinates = props.coordinates,
          x = _props$coordinates.x,
          y = _props$coordinates.y;


      return { x: x, y: y };
    }
  }, {
    key: 'onInputChange',
    value: function onInputChange(urlValue) {
      var _props = this.props,
          linkID = _props.linkID,
          onURLChange = _props.onURLChange;

      // Call back to parent

      onURLChange(linkID, urlValue);
    }
  }, {
    key: 'onInputKeyDown',
    value: function onInputKeyDown(ev) {
      /*
           * `KeyboardEvent.key` enjoys excellent cross-browser support.
           * https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
           */
      var key = ev.key;


      if (key === _constants.RETURN_KEY) {
        // Save changes
        ev.preventDefault();

        this.props.onClose(this.props.linkID);
      }

      if (key === _constants.ESCAPE_KEY) {
        // Cancel changes
        ev.preventDefault();

        // Restore original URL
        this.onInputChange(this.state.originalLinkURL);

        this.props.onClose(this.props.linkID);
      }
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _ = this.context.localize;
      var position = this.state.position;
      var _props2 = this.props,
          onBlur = _props2.onBlur,
          onFocus = _props2.onFocus,
          linkURL = _props2.linkURL;

      var placeholderText = _('Enter Link URL');
      var urlText = _('URL');
      // TODO: add close button
      return _react2.default.createElement(
        'div',
        { className: 'rich-text-editor__link-editor', style: { left: position.x, top: position.y } },
        _react2.default.createElement(
          'span',
          { className: 'rich-text-editor__link-editor__label' },
          urlText
        ),
        _react2.default.createElement('input', {
          className: 'rich-text-editor__link-editor__input',
          onBlur: onBlur,
          onFocus: onFocus,
          onChange: function onChange(ev) {
            return _this2.onInputChange(ev.target.value);
          },
          onKeyDown: function onKeyDown(ev) {
            return _this2.onInputKeyDown(ev);
          },
          ref: function ref(input) {
            return _this2.input = input;
          },
          value: linkURL,
          placeholder: placeholderText
        })
      );
    }
  }]);

  return LinkEditor;
}(_react.Component);

LinkEditor.propTypes = {
  linkID: _propTypes2.default.string.isRequired,
  linkURL: _propTypes2.default.string.isRequired,
  onBlur: _propTypes2.default.func.isRequired,
  onFocus: _propTypes2.default.func.isRequired,
  onClose: _propTypes2.default.func.isRequired,
  onURLChange: _propTypes2.default.func.isRequired,

  coordinates: _propTypes2.default.shape({
    x: _propTypes2.default.number,
    y: _propTypes2.default.number
  })
};

LinkEditor.defaultProps = {
  coordinates: {
    x: 0,
    y: 0
  }
};

LinkEditor.contextTypes = {
  localize: _propTypes2.default.func.isRequired
};

exports.default = LinkEditor;
//# sourceMappingURL=LinkEditor.js.map

/***/ }),

/***/ "ffJW":
/*!****************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/throttle.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var timerCache = {};

/**
 * Throttle a callback. `callback` executes synchronously only if
 * more than `minInterval` milliseconds have already elapsed since the latest
 * call (if any). Otherwise we wait until `minInterval` is over and execute the
 * last callback received while waiting.
 * So the first and last events in a train are always executed (eventually)
 * but some of the events in the middle can be dropped.
 *
 * @param {string} id: an identifier to mark events to throttle together
 * @param {number} minInterval: minimum time, in milliseconds, between
 *   invocations of `callback`
 * @param {function} callback: the function to throttle. `callback` itself
 *   should be a purely synchronous function.
 */
exports.throttle = function throttle(id, minInterval, callback) {
    var cache = timerCache[id];
    var now = Date.now();

    if(!cache) {
        /*
         * Throw out old items before making a new one, to prevent the cache
         * getting overgrown, for example from old plots that have been replaced.
         * 1 minute age is arbitrary.
         */
        for(var idi in timerCache) {
            if(timerCache[idi].ts < now - 60000) {
                delete timerCache[idi];
            }
        }
        cache = timerCache[id] = {ts: 0, timer: null};
    }

    _clearTimeout(cache);

    function exec() {
        callback();
        cache.ts = Date.now();
        if(cache.onDone) {
            cache.onDone();
            cache.onDone = null;
        }
    }

    if(now > cache.ts + minInterval) {
        exec();
        return;
    }

    cache.timer = setTimeout(function() {
        exec();
        cache.timer = null;
    }, minInterval);
};

exports.done = function(id) {
    var cache = timerCache[id];
    if(!cache || !cache.timer) return Promise.resolve();

    return new Promise(function(resolve) {
        var previousOnDone = cache.onDone;
        cache.onDone = function onDone() {
            if(previousOnDone) previousOnDone();
            resolve();
            cache.onDone = null;
        };
    });
};

/**
 * Clear the throttle cache for one or all timers
 * @param {optional string} id:
 *   if provided, clear just this timer
 *   if omitted, clear all timers (mainly useful for testing)
 */
exports.clear = function(id) {
    if(id) {
        _clearTimeout(timerCache[id]);
        delete timerCache[id];
    }
    else {
        for(var idi in timerCache) exports.clear(idi);
    }
};

function _clearTimeout(cache) {
    if(cache && cache.timer !== null) {
        clearTimeout(cache.timer);
        cache.timer = null;
    }
}


/***/ }),

/***/ "fhzG":
/*!**************************************************!*\
  !*** ./node_modules/create-react-class/index.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */



var React = __webpack_require__(/*! react */ "q1tI");
var factory = __webpack_require__(/*! ./factory */ "lT4e");

if (typeof React === 'undefined') {
  throw Error(
    'create-react-class could not find the React object. If you are using script tags, ' +
      'make sure that React is being loaded before create-react-class.'
  );
}

// Hack to grab NoopUpdateQueue from isomorphic React
var ReactNoopUpdateQueue = new React.Component().updater;

module.exports = factory(
  React.Component,
  React.isValidElement,
  ReactNoopUpdateQueue
);


/***/ }),

/***/ "flHX":
/*!*******************************************************!*\
  !*** ./node_modules/@phosphor/algorithm/lib/retro.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/**
 * Create an iterator for a retroable object.
 *
 * @param object - The retroable or array-like object of interest.
 *
 * @returns An iterator which traverses the object's values in reverse.
 *
 * #### Example
 * ```typescript
 * import { retro, toArray } from '@phosphor/algorithm';
 *
 * let data = [1, 2, 3, 4, 5, 6];
 *
 * let stream = retro(data);
 *
 * toArray(stream);  // [6, 5, 4, 3, 2, 1]
 * ```
 */
function retro(object) {
    var it;
    if (typeof object.retro === 'function') {
        it = object.retro();
    }
    else {
        it = new RetroArrayIterator(object);
    }
    return it;
}
exports.retro = retro;
/**
 * An iterator which traverses an array-like object in reverse.
 *
 * #### Notes
 * This iterator can be used for any builtin JS array-like object.
 */
var RetroArrayIterator = (function () {
    /**
     * Construct a new retro iterator.
     *
     * @param source - The array-like object of interest.
     */
    function RetroArrayIterator(source) {
        this._source = source;
        this._index = source.length - 1;
    }
    /**
     * Get an iterator over the object's values.
     *
     * @returns An iterator which yields the object's values.
     */
    RetroArrayIterator.prototype.iter = function () {
        return this;
    };
    /**
     * Create an independent clone of the iterator.
     *
     * @returns A new independent clone of the iterator.
     */
    RetroArrayIterator.prototype.clone = function () {
        var result = new RetroArrayIterator(this._source);
        result._index = this._index;
        return result;
    };
    /**
     * Get the next value from the iterator.
     *
     * @returns The next value from the iterator, or `undefined`.
     */
    RetroArrayIterator.prototype.next = function () {
        if (this._index < 0 || this._index >= this._source.length) {
            return undefined;
        }
        return this._source[this._index--];
    };
    return RetroArrayIterator;
}());
exports.RetroArrayIterator = RetroArrayIterator;


/***/ }),

/***/ "fmRc":
/*!***************************************!*\
  !*** ./node_modules/lodash/_Stack.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var ListCache = __webpack_require__(/*! ./_ListCache */ "Xi7e"),
    stackClear = __webpack_require__(/*! ./_stackClear */ "77Zs"),
    stackDelete = __webpack_require__(/*! ./_stackDelete */ "L8xA"),
    stackGet = __webpack_require__(/*! ./_stackGet */ "gCq4"),
    stackHas = __webpack_require__(/*! ./_stackHas */ "VaNO"),
    stackSet = __webpack_require__(/*! ./_stackSet */ "0Cz8");

/**
 * 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;
}

// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;

module.exports = Stack;


/***/ }),

/***/ "fnjI":
/*!*************************************!*\
  !*** ./node_modules/sha.js/sha1.js ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/*
 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
 * in FIPS PUB 180-1
 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for details.
 */

var inherits = __webpack_require__(/*! inherits */ "P7XM")
var Hash = __webpack_require__(/*! ./hash */ "tnIz")
var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer

var K = [
  0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
]

var W = new Array(80)

function Sha1 () {
  this.init()
  this._w = W

  Hash.call(this, 64, 56)
}

inherits(Sha1, Hash)

Sha1.prototype.init = function () {
  this._a = 0x67452301
  this._b = 0xefcdab89
  this._c = 0x98badcfe
  this._d = 0x10325476
  this._e = 0xc3d2e1f0

  return this
}

function rotl1 (num) {
  return (num << 1) | (num >>> 31)
}

function rotl5 (num) {
  return (num << 5) | (num >>> 27)
}

function rotl30 (num) {
  return (num << 30) | (num >>> 2)
}

function ft (s, b, c, d) {
  if (s === 0) return (b & c) | ((~b) & d)
  if (s === 2) return (b & c) | (b & d) | (c & d)
  return b ^ c ^ d
}

Sha1.prototype._update = function (M) {
  var W = this._w

  var a = this._a | 0
  var b = this._b | 0
  var c = this._c | 0
  var d = this._d | 0
  var e = this._e | 0

  for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
  for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])

  for (var j = 0; j < 80; ++j) {
    var s = ~~(j / 20)
    var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0

    e = d
    d = c
    c = rotl30(b)
    b = a
    a = t
  }

  this._a = (a + this._a) | 0
  this._b = (b + this._b) | 0
  this._c = (c + this._c) | 0
  this._d = (d + this._d) | 0
  this._e = (e + this._e) | 0
}

Sha1.prototype._hash = function () {
  var H = Buffer.allocUnsafe(20)

  H.writeInt32BE(this._a | 0, 0)
  H.writeInt32BE(this._b | 0, 4)
  H.writeInt32BE(this._c | 0, 8)
  H.writeInt32BE(this._d | 0, 12)
  H.writeInt32BE(this._e | 0, 16)

  return H
}

module.exports = Sha1


/***/ }),

/***/ "fpC5":
/*!*************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_object-dps.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var dP = __webpack_require__(/*! ./_object-dp */ "2faE");
var anObject = __webpack_require__(/*! ./_an-object */ "5K7Z");
var getKeys = __webpack_require__(/*! ./_object-keys */ "w6GO");

module.exports = __webpack_require__(/*! ./_descriptors */ "jmDH") ? Object.defineProperties : function defineProperties(O, Properties) {
  anObject(O);
  var keys = getKeys(Properties);
  var length = keys.length;
  var i = 0;
  var P;
  while (length > i) dP.f(O, P = keys[i++], Properties[P]);
  return O;
};


/***/ }),

/***/ "ftKO":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_setCacheAdd.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';

/**
 * 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;
}

module.exports = setCacheAdd;


/***/ }),

/***/ "fxcN":
/*!*************************************************************!*\
  !*** ./node_modules/react-tabs/esm/helpers/elementTypes.js ***!
  \*************************************************************/
/*! exports provided: isTab, isTabPanel, isTabList */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isTab", function() { return isTab; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isTabPanel", function() { return isTabPanel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isTabList", function() { return isTabList; });
function isTab(el) {
  return el.type && el.type.tabsRole === 'Tab';
}
function isTabPanel(el) {
  return el.type && el.type.tabsRole === 'TabPanel';
}
function isTabList(el) {
  return el.type && el.type.tabsRole === 'TabList';
}

/***/ }),

/***/ "fy0I":
/*!************************************************!*\
  !*** ./node_modules/comment-json/lib/parse.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


module.exports = parse;

var parser = __webpack_require__(/*! json-parser */ "tui4");

function parse (code, reviver, removes_comments) {
  return parser.parse(code, reviver, removes_comments);
}


/***/ }),

/***/ "fyOY":
/*!****************************************************!*\
  !*** ./node_modules/draft-js/lib/DraftModifier.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DraftModifier
 * @format
 * 
 */



var CharacterMetadata = __webpack_require__(/*! ./CharacterMetadata */ "lFJn");
var ContentStateInlineStyle = __webpack_require__(/*! ./ContentStateInlineStyle */ "M6rc");
var DraftFeatureFlags = __webpack_require__(/*! ./DraftFeatureFlags */ "cX45");
var Immutable = __webpack_require__(/*! immutable */ "JPcv");

var applyEntityToContentState = __webpack_require__(/*! ./applyEntityToContentState */ "ilWa");
var getCharacterRemovalRange = __webpack_require__(/*! ./getCharacterRemovalRange */ "c203");
var getContentStateFragment = __webpack_require__(/*! ./getContentStateFragment */ "DYKh");
var insertFragmentIntoContentState = __webpack_require__(/*! ./insertFragmentIntoContentState */ "L2EA");
var insertTextIntoContentState = __webpack_require__(/*! ./insertTextIntoContentState */ "81KI");
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");
var modifyBlockForContentState = __webpack_require__(/*! ./modifyBlockForContentState */ "Mh8y");
var removeEntitiesAtEdges = __webpack_require__(/*! ./removeEntitiesAtEdges */ "bu5B");
var removeRangeFromContentState = __webpack_require__(/*! ./removeRangeFromContentState */ "fEyW");
var splitBlockInContentState = __webpack_require__(/*! ./splitBlockInContentState */ "B0ab");

var OrderedSet = Immutable.OrderedSet;

/**
 * `DraftModifier` provides a set of convenience methods that apply
 * modifications to a `ContentState` object based on a target `SelectionState`.
 *
 * Any change to a `ContentState` should be decomposable into a series of
 * transaction functions that apply the required changes and return output
 * `ContentState` objects.
 *
 * These functions encapsulate some of the most common transaction sequences.
 */

var DraftModifier = {
  replaceText: function replaceText(contentState, rangeToReplace, text, inlineStyle, entityKey) {
    var withoutEntities = removeEntitiesAtEdges(contentState, rangeToReplace);
    var withoutText = removeRangeFromContentState(withoutEntities, rangeToReplace);

    var character = CharacterMetadata.create({
      style: inlineStyle || OrderedSet(),
      entity: entityKey || null
    });

    return insertTextIntoContentState(withoutText, withoutText.getSelectionAfter(), text, character);
  },

  insertText: function insertText(contentState, targetRange, text, inlineStyle, entityKey) {
    !targetRange.isCollapsed() ?  true ? invariant(false, 'Target range must be collapsed for `insertText`.') : undefined : void 0;
    return DraftModifier.replaceText(contentState, targetRange, text, inlineStyle, entityKey);
  },

  moveText: function moveText(contentState, removalRange, targetRange) {
    var movedFragment = getContentStateFragment(contentState, removalRange);

    var afterRemoval = DraftModifier.removeRange(contentState, removalRange, 'backward');

    return DraftModifier.replaceWithFragment(afterRemoval, targetRange, movedFragment);
  },

  replaceWithFragment: function replaceWithFragment(contentState, targetRange, fragment) {
    var withoutEntities = removeEntitiesAtEdges(contentState, targetRange);
    var withoutText = removeRangeFromContentState(withoutEntities, targetRange);

    return insertFragmentIntoContentState(withoutText, withoutText.getSelectionAfter(), fragment);
  },

  removeRange: function removeRange(contentState, rangeToRemove, removalDirection) {
    var startKey = void 0,
        endKey = void 0,
        startBlock = void 0,
        endBlock = void 0;
    if (rangeToRemove.getIsBackward()) {
      rangeToRemove = rangeToRemove.merge({
        anchorKey: rangeToRemove.getFocusKey(),
        anchorOffset: rangeToRemove.getFocusOffset(),
        focusKey: rangeToRemove.getAnchorKey(),
        focusOffset: rangeToRemove.getAnchorOffset(),
        isBackward: false
      });
    }
    startKey = rangeToRemove.getAnchorKey();
    endKey = rangeToRemove.getFocusKey();
    startBlock = contentState.getBlockForKey(startKey);
    endBlock = contentState.getBlockForKey(endKey);
    var startOffset = rangeToRemove.getStartOffset();
    var endOffset = rangeToRemove.getEndOffset();

    var startEntityKey = startBlock.getEntityAt(startOffset);
    var endEntityKey = endBlock.getEntityAt(endOffset - 1);

    // Check whether the selection state overlaps with a single entity.
    // If so, try to remove the appropriate substring of the entity text.
    if (startKey === endKey) {
      if (startEntityKey && startEntityKey === endEntityKey) {
        var _adjustedRemovalRange = getCharacterRemovalRange(contentState.getEntityMap(), startBlock, endBlock, rangeToRemove, removalDirection);
        return removeRangeFromContentState(contentState, _adjustedRemovalRange);
      }
    }
    var adjustedRemovalRange = rangeToRemove;
    if (DraftFeatureFlags.draft_segmented_entities_behavior) {
      // Adjust the selection to properly delete segemented and immutable
      // entities
      adjustedRemovalRange = getCharacterRemovalRange(contentState.getEntityMap(), startBlock, endBlock, rangeToRemove, removalDirection);
    }

    var withoutEntities = removeEntitiesAtEdges(contentState, adjustedRemovalRange);
    return removeRangeFromContentState(withoutEntities, adjustedRemovalRange);
  },

  splitBlock: function splitBlock(contentState, selectionState) {
    var withoutEntities = removeEntitiesAtEdges(contentState, selectionState);
    var withoutText = removeRangeFromContentState(withoutEntities, selectionState);

    return splitBlockInContentState(withoutText, withoutText.getSelectionAfter());
  },

  applyInlineStyle: function applyInlineStyle(contentState, selectionState, inlineStyle) {
    return ContentStateInlineStyle.add(contentState, selectionState, inlineStyle);
  },

  removeInlineStyle: function removeInlineStyle(contentState, selectionState, inlineStyle) {
    return ContentStateInlineStyle.remove(contentState, selectionState, inlineStyle);
  },

  setBlockType: function setBlockType(contentState, selectionState, blockType) {
    return modifyBlockForContentState(contentState, selectionState, function (block) {
      return block.merge({ type: blockType, depth: 0 });
    });
  },

  setBlockData: function setBlockData(contentState, selectionState, blockData) {
    return modifyBlockForContentState(contentState, selectionState, function (block) {
      return block.merge({ data: blockData });
    });
  },

  mergeBlockData: function mergeBlockData(contentState, selectionState, blockData) {
    return modifyBlockForContentState(contentState, selectionState, function (block) {
      return block.merge({ data: block.getData().merge(blockData) });
    });
  },

  applyEntity: function applyEntity(contentState, selectionState, entityKey) {
    var withoutEntities = removeEntitiesAtEdges(contentState, selectionState);
    return applyEntityToContentState(withoutEntities, selectionState, entityKey);
  }
};

module.exports = DraftModifier;

/***/ }),

/***/ "fyRy":
/*!*******************************************************!*\
  !*** ./node_modules/draft-js/lib/AtomicBlockUtils.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule AtomicBlockUtils
 * @format
 * 
 */



var _assign = __webpack_require__(/*! object-assign */ "MgzW");

var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var BlockMapBuilder = __webpack_require__(/*! ./BlockMapBuilder */ "YeVe");
var CharacterMetadata = __webpack_require__(/*! ./CharacterMetadata */ "lFJn");
var ContentBlock = __webpack_require__(/*! ./ContentBlock */ "8uQm");
var ContentBlockNode = __webpack_require__(/*! ./ContentBlockNode */ "JL7T");
var DraftFeatureFlags = __webpack_require__(/*! ./DraftFeatureFlags */ "cX45");
var DraftModifier = __webpack_require__(/*! ./DraftModifier */ "fyOY");
var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");
var Immutable = __webpack_require__(/*! immutable */ "JPcv");
var SelectionState = __webpack_require__(/*! ./SelectionState */ "hMpd");

var generateRandomKey = __webpack_require__(/*! ./generateRandomKey */ "rJY1");
var moveBlockInContentState = __webpack_require__(/*! ./moveBlockInContentState */ "I2Ug");

var experimentalTreeDataSupport = DraftFeatureFlags.draft_tree_data_support;
var ContentBlockRecord = experimentalTreeDataSupport ? ContentBlockNode : ContentBlock;

var List = Immutable.List,
    Repeat = Immutable.Repeat;


var AtomicBlockUtils = {
  insertAtomicBlock: function insertAtomicBlock(editorState, entityKey, character) {
    var contentState = editorState.getCurrentContent();
    var selectionState = editorState.getSelection();

    var afterRemoval = DraftModifier.removeRange(contentState, selectionState, 'backward');

    var targetSelection = afterRemoval.getSelectionAfter();
    var afterSplit = DraftModifier.splitBlock(afterRemoval, targetSelection);
    var insertionTarget = afterSplit.getSelectionAfter();

    var asAtomicBlock = DraftModifier.setBlockType(afterSplit, insertionTarget, 'atomic');

    var charData = CharacterMetadata.create({ entity: entityKey });

    var atomicBlockConfig = {
      key: generateRandomKey(),
      type: 'atomic',
      text: character,
      characterList: List(Repeat(charData, character.length))
    };

    var atomicDividerBlockConfig = {
      key: generateRandomKey(),
      type: 'unstyled'
    };

    if (experimentalTreeDataSupport) {
      atomicBlockConfig = _extends({}, atomicBlockConfig, {
        nextSibling: atomicDividerBlockConfig.key
      });
      atomicDividerBlockConfig = _extends({}, atomicDividerBlockConfig, {
        prevSibling: atomicBlockConfig.key
      });
    }

    var fragmentArray = [new ContentBlockRecord(atomicBlockConfig), new ContentBlockRecord(atomicDividerBlockConfig)];

    var fragment = BlockMapBuilder.createFromArray(fragmentArray);

    var withAtomicBlock = DraftModifier.replaceWithFragment(asAtomicBlock, insertionTarget, fragment);

    var newContent = withAtomicBlock.merge({
      selectionBefore: selectionState,
      selectionAfter: withAtomicBlock.getSelectionAfter().set('hasFocus', true)
    });

    return EditorState.push(editorState, newContent, 'insert-fragment');
  },

  moveAtomicBlock: function moveAtomicBlock(editorState, atomicBlock, targetRange, insertionMode) {
    var contentState = editorState.getCurrentContent();
    var selectionState = editorState.getSelection();

    var withMovedAtomicBlock = void 0;

    if (insertionMode === 'before' || insertionMode === 'after') {
      var targetBlock = contentState.getBlockForKey(insertionMode === 'before' ? targetRange.getStartKey() : targetRange.getEndKey());

      withMovedAtomicBlock = moveBlockInContentState(contentState, atomicBlock, targetBlock, insertionMode);
    } else {
      var afterRemoval = DraftModifier.removeRange(contentState, targetRange, 'backward');

      var selectionAfterRemoval = afterRemoval.getSelectionAfter();
      var _targetBlock = afterRemoval.getBlockForKey(selectionAfterRemoval.getFocusKey());

      if (selectionAfterRemoval.getStartOffset() === 0) {
        withMovedAtomicBlock = moveBlockInContentState(afterRemoval, atomicBlock, _targetBlock, 'before');
      } else if (selectionAfterRemoval.getEndOffset() === _targetBlock.getLength()) {
        withMovedAtomicBlock = moveBlockInContentState(afterRemoval, atomicBlock, _targetBlock, 'after');
      } else {
        var afterSplit = DraftModifier.splitBlock(afterRemoval, selectionAfterRemoval);

        var selectionAfterSplit = afterSplit.getSelectionAfter();
        var _targetBlock2 = afterSplit.getBlockForKey(selectionAfterSplit.getFocusKey());

        withMovedAtomicBlock = moveBlockInContentState(afterSplit, atomicBlock, _targetBlock2, 'before');
      }
    }

    var newContent = withMovedAtomicBlock.merge({
      selectionBefore: selectionState,
      selectionAfter: withMovedAtomicBlock.getSelectionAfter().set('hasFocus', true)
    });

    return EditorState.push(editorState, newContent, 'move-block');
  }
};

module.exports = AtomicBlockUtils;

/***/ }),

/***/ "fz/m":
/*!*********************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@phosphor/widgets/style/menu.css ***!
  \*********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\r\n| Copyright (c) 2014-2017, PhosphorJS Contributors\r\n|\r\n| Distributed under the terms of the BSD 3-Clause License.\r\n|\r\n| The full license is in the file LICENSE, distributed with this software.\r\n|----------------------------------------------------------------------------*/\r\n\r\n\r\n.p-Menu {\r\n  z-index: 10000;\r\n  position: absolute;\r\n  white-space: nowrap;\r\n  overflow-x: hidden;\r\n  overflow-y: auto;\r\n  outline: none;\r\n  -webkit-user-select: none;\r\n  -moz-user-select: none;\r\n  -ms-user-select: none;\r\n  user-select: none;\r\n}\r\n\r\n\r\n.p-Menu-content {\r\n  margin: 0;\r\n  padding: 0;\r\n  display: table;\r\n  list-style-type: none;\r\n}\r\n\r\n\r\n.p-Menu-item {\r\n  display: table-row;\r\n}\r\n\r\n\r\n.p-Menu-item.p-mod-hidden,\r\n.p-Menu-item.p-mod-collapsed {\r\n  display: none !important;\r\n}\r\n\r\n\r\n.p-Menu-itemIcon,\r\n.p-Menu-itemSubmenuIcon {\r\n  display: table-cell;\r\n  text-align: center;\r\n}\r\n\r\n\r\n.p-Menu-itemLabel {\r\n  display: table-cell;\r\n  text-align: left;\r\n}\r\n\r\n\r\n.p-Menu-itemShortcut {\r\n  display: table-cell;\r\n  text-align: right;\r\n}\r\n", ""]);

// exports


/***/ }),

/***/ "fzPg":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/yo.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var yo = moment.defineLocale('yo', {
    months : 'Sẹ́rẹ́_Èrèlè_Ẹrẹ̀nà_Ìgbé_Èbibi_Òkùdu_Agẹmo_Ògún_Owewe_Ọ̀wàrà_Bélú_Ọ̀pẹ̀̀'.split('_'),
    monthsShort : 'Sẹ́r_Èrl_Ẹrn_Ìgb_Èbi_Òkù_Agẹ_Ògú_Owe_Ọ̀wà_Bél_Ọ̀pẹ̀̀'.split('_'),
    weekdays : 'Àìkú_Ajé_Ìsẹ́gun_Ọjọ́rú_Ọjọ́bọ_Ẹtì_Àbámẹ́ta'.split('_'),
    weekdaysShort : 'Àìk_Ajé_Ìsẹ́_Ọjr_Ọjb_Ẹtì_Àbá'.split('_'),
    weekdaysMin : 'Àì_Aj_Ìs_Ọr_Ọb_Ẹt_Àb'.split('_'),
    longDateFormat : {
        LT : 'h:mm A',
        LTS : 'h:mm:ss A',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY h:mm A',
        LLLL : 'dddd, D MMMM YYYY h:mm A'
    },
    calendar : {
        sameDay : '[Ònì ni] LT',
        nextDay : '[Ọ̀la ni] LT',
        nextWeek : 'dddd [Ọsẹ̀ tón\'bọ] [ni] LT',
        lastDay : '[Àna ni] LT',
        lastWeek : 'dddd [Ọsẹ̀ tólọ́] [ni] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'ní %s',
        past : '%s kọjá',
        s : 'ìsẹjú aayá die',
        ss :'aayá %d',
        m : 'ìsẹjú kan',
        mm : 'ìsẹjú %d',
        h : 'wákati kan',
        hh : 'wákati %d',
        d : 'ọjọ́ kan',
        dd : 'ọjọ́ %d',
        M : 'osù kan',
        MM : 'osù %d',
        y : 'ọdún kan',
        yy : 'ọdún %d'
    },
    dayOfMonthOrdinalParse : /ọjọ́\s\d{1,2}/,
    ordinal : 'ọjọ́ %d',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4 // The week that contains Jan 4th is the first week of the year.
    }
});

return yo;

})));


/***/ }),

/***/ "g07C":
/*!******************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/tabbar.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
var domutils_1 = __webpack_require__(/*! @phosphor/domutils */ "XWTc");
var dragdrop_1 = __webpack_require__(/*! @phosphor/dragdrop */ "v7cI");
var messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
var signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
var virtualdom_1 = __webpack_require__(/*! @phosphor/virtualdom */ "Gqu+");
var title_1 = __webpack_require__(/*! ./title */ "0jI2");
var widget_1 = __webpack_require__(/*! ./widget */ "FmDU");
/**
 * A widget which displays titles as a single row or column of tabs.
 *
 * #### Notes
 * If CSS transforms are used to rotate nodes for vertically oriented
 * text, then tab dragging will not work correctly. The `tabsMovable`
 * property should be set to `false` when rotating nodes from CSS.
 */
var TabBar = (function (_super) {
    __extends(TabBar, _super);
    /**
     * Construct a new tab bar.
     *
     * @param options - The options for initializing the tab bar.
     */
    function TabBar(options) {
        if (options === void 0) { options = {}; }
        var _this = _super.call(this, { node: Private.createNode() }) || this;
        _this._currentIndex = -1;
        _this._titles = [];
        _this._previousTitle = null;
        _this._dragData = null;
        _this._tabMoved = new signaling_1.Signal(_this);
        _this._currentChanged = new signaling_1.Signal(_this);
        _this._tabCloseRequested = new signaling_1.Signal(_this);
        _this._tabDetachRequested = new signaling_1.Signal(_this);
        _this._tabActivateRequested = new signaling_1.Signal(_this);
        _this.addClass('p-TabBar');
        _this.setFlag(widget_1.Widget.Flag.DisallowLayout);
        _this.tabsMovable = options.tabsMovable || false;
        _this.allowDeselect = options.allowDeselect || false;
        _this.insertBehavior = options.insertBehavior || 'select-tab-if-needed';
        _this.removeBehavior = options.removeBehavior || 'select-tab-after';
        _this.renderer = options.renderer || TabBar.defaultRenderer;
        _this._orientation = options.orientation || 'horizontal';
        _this.dataset['orientation'] = _this._orientation;
        return _this;
    }
    /**
     * Dispose of the resources held by the widget.
     */
    TabBar.prototype.dispose = function () {
        this._releaseMouse();
        this._titles.length = 0;
        this._previousTitle = null;
        _super.prototype.dispose.call(this);
    };
    Object.defineProperty(TabBar.prototype, "currentChanged", {
        /**
         * A signal emitted when the current tab is changed.
         *
         * #### Notes
         * This signal is emitted when the currently selected tab is changed
         * either through user or programmatic interaction.
         *
         * Notably, this signal is not emitted when the index of the current
         * tab changes due to tabs being inserted, removed, or moved. It is
         * only emitted when the actual current tab node is changed.
         */
        get: function () {
            return this._currentChanged;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(TabBar.prototype, "tabMoved", {
        /**
         * A signal emitted when a tab is moved by the user.
         *
         * #### Notes
         * This signal is emitted when a tab is moved by user interaction.
         *
         * This signal is not emitted when a tab is moved programmatically.
         */
        get: function () {
            return this._tabMoved;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(TabBar.prototype, "tabActivateRequested", {
        /**
         * A signal emitted when a tab is clicked by the user.
         *
         * #### Notes
         * If the clicked tab is not the current tab, the clicked tab will be
         * made current and the `currentChanged` signal will be emitted first.
         *
         * This signal is emitted even if the clicked tab is the current tab.
         */
        get: function () {
            return this._tabActivateRequested;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(TabBar.prototype, "tabCloseRequested", {
        /**
         * A signal emitted when a tab close icon is clicked.
         *
         * #### Notes
         * This signal is not emitted unless the tab title is `closable`.
         */
        get: function () {
            return this._tabCloseRequested;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(TabBar.prototype, "tabDetachRequested", {
        /**
         * A signal emitted when a tab is dragged beyond the detach threshold.
         *
         * #### Notes
         * This signal is emitted when the user drags a tab with the mouse,
         * and mouse is dragged beyond the detach threshold.
         *
         * The consumer of the signal should call `releaseMouse` and remove
         * the tab in order to complete the detach.
         *
         * This signal is only emitted once per drag cycle.
         */
        get: function () {
            return this._tabDetachRequested;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(TabBar.prototype, "currentTitle", {
        /**
         * Get the currently selected title.
         *
         * #### Notes
         * This will be `null` if no tab is selected.
         */
        get: function () {
            return this._titles[this._currentIndex] || null;
        },
        /**
         * Set the currently selected title.
         *
         * #### Notes
         * If the title does not exist, the title will be set to `null`.
         */
        set: function (value) {
            this.currentIndex = value ? this._titles.indexOf(value) : -1;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(TabBar.prototype, "currentIndex", {
        /**
         * Get the index of the currently selected tab.
         *
         * #### Notes
         * This will be `-1` if no tab is selected.
         */
        get: function () {
            return this._currentIndex;
        },
        /**
         * Set the index of the currently selected tab.
         *
         * #### Notes
         * If the value is out of range, the index will be set to `-1`.
         */
        set: function (value) {
            // Adjust for an out of range index.
            if (value < 0 || value >= this._titles.length) {
                value = -1;
            }
            // Bail early if the index will not change.
            if (this._currentIndex === value) {
                return;
            }
            // Look up the previous index and title.
            var pi = this._currentIndex;
            var pt = this._titles[pi] || null;
            // Look up the current index and title.
            var ci = value;
            var ct = this._titles[ci] || null;
            // Update the current index and previous title.
            this._currentIndex = ci;
            this._previousTitle = pt;
            // Schedule an update of the tabs.
            this.update();
            // Emit the current changed signal.
            this._currentChanged.emit({
                previousIndex: pi, previousTitle: pt,
                currentIndex: ci, currentTitle: ct
            });
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(TabBar.prototype, "orientation", {
        /**
         * Get the orientation of the tab bar.
         *
         * #### Notes
         * This controls whether the tabs are arranged in a row or column.
         */
        get: function () {
            return this._orientation;
        },
        /**
         * Set the orientation of the tab bar.
         *
         * #### Notes
         * This controls whether the tabs are arranged in a row or column.
         */
        set: function (value) {
            // Do nothing if the orientation does not change.
            if (this._orientation === value) {
                return;
            }
            // Release the mouse before making any changes.
            this._releaseMouse();
            // Toggle the orientation values.
            this._orientation = value;
            this.dataset['orientation'] = value;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(TabBar.prototype, "titles", {
        /**
         * A read-only array of the titles in the tab bar.
         */
        get: function () {
            return this._titles;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(TabBar.prototype, "contentNode", {
        /**
         * The tab bar content node.
         *
         * #### Notes
         * This is the node which holds the tab nodes.
         *
         * Modifying this node directly can lead to undefined behavior.
         */
        get: function () {
            return this.node.getElementsByClassName('p-TabBar-content')[0];
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Add a tab to the end of the tab bar.
     *
     * @param value - The title which holds the data for the tab,
     *   or an options object to convert to a title.
     *
     * @returns The title object added to the tab bar.
     *
     * #### Notes
     * If the title is already added to the tab bar, it will be moved.
     */
    TabBar.prototype.addTab = function (value) {
        return this.insertTab(this._titles.length, value);
    };
    /**
     * Insert a tab into the tab bar at the specified index.
     *
     * @param index - The index at which to insert the tab.
     *
     * @param value - The title which holds the data for the tab,
     *   or an options object to convert to a title.
     *
     * @returns The title object added to the tab bar.
     *
     * #### Notes
     * The index will be clamped to the bounds of the tabs.
     *
     * If the title is already added to the tab bar, it will be moved.
     */
    TabBar.prototype.insertTab = function (index, value) {
        // Release the mouse before making any changes.
        this._releaseMouse();
        // Coerce the value to a title.
        var title = Private.asTitle(value);
        // Look up the index of the title.
        var i = this._titles.indexOf(title);
        // Clamp the insert index to the array bounds.
        var j = Math.max(0, Math.min(index, this._titles.length));
        // If the title is not in the array, insert it.
        if (i === -1) {
            // Insert the title into the array.
            algorithm_1.ArrayExt.insert(this._titles, j, title);
            // Connect to the title changed signal.
            title.changed.connect(this._onTitleChanged, this);
            // Schedule an update of the tabs.
            this.update();
            // Adjust the current index for the insert.
            this._adjustCurrentForInsert(j, title);
            // Return the title added to the tab bar.
            return title;
        }
        // Otherwise, the title exists in the array and should be moved.
        // Adjust the index if the location is at the end of the array.
        if (j === this._titles.length) {
            j--;
        }
        // Bail if there is no effective move.
        if (i === j) {
            return title;
        }
        // Move the title to the new location.
        algorithm_1.ArrayExt.move(this._titles, i, j);
        // Schedule an update of the tabs.
        this.update();
        // Adjust the current index for the move.
        this._adjustCurrentForMove(i, j);
        // Return the title added to the tab bar.
        return title;
    };
    /**
     * Remove a tab from the tab bar.
     *
     * @param title - The title for the tab to remove.
     *
     * #### Notes
     * This is a no-op if the title is not in the tab bar.
     */
    TabBar.prototype.removeTab = function (title) {
        this.removeTabAt(this._titles.indexOf(title));
    };
    /**
     * Remove the tab at a given index from the tab bar.
     *
     * @param index - The index of the tab to remove.
     *
     * #### Notes
     * This is a no-op if the index is out of range.
     */
    TabBar.prototype.removeTabAt = function (index) {
        // Release the mouse before making any changes.
        this._releaseMouse();
        // Remove the title from the array.
        var title = algorithm_1.ArrayExt.removeAt(this._titles, index);
        // Bail if the index is out of range.
        if (!title) {
            return;
        }
        // Disconnect from the title changed signal.
        title.changed.disconnect(this._onTitleChanged, this);
        // Clear the previous title if it's being removed.
        if (title === this._previousTitle) {
            this._previousTitle = null;
        }
        // Schedule an update of the tabs.
        this.update();
        // Adjust the current index for the remove.
        this._adjustCurrentForRemove(index, title);
    };
    /**
     * Remove all tabs from the tab bar.
     */
    TabBar.prototype.clearTabs = function () {
        // Bail if there is nothing to remove.
        if (this._titles.length === 0) {
            return;
        }
        // Release the mouse before making any changes.
        this._releaseMouse();
        // Disconnect from the title changed signals.
        for (var _i = 0, _a = this._titles; _i < _a.length; _i++) {
            var title = _a[_i];
            title.changed.disconnect(this._onTitleChanged, this);
        }
        // Get the current index and title.
        var pi = this.currentIndex;
        var pt = this.currentTitle;
        // Reset the current index and previous title.
        this._currentIndex = -1;
        this._previousTitle = null;
        // Clear the title array.
        this._titles.length = 0;
        // Schedule an update of the tabs.
        this.update();
        // If no tab was selected, there's nothing else to do.
        if (pi === -1) {
            return;
        }
        // Emit the current changed signal.
        this._currentChanged.emit({
            previousIndex: pi, previousTitle: pt,
            currentIndex: -1, currentTitle: null
        });
    };
    /**
     * Release the mouse and restore the non-dragged tab positions.
     *
     * #### Notes
     * This will cause the tab bar to stop handling mouse events and to
     * restore the tabs to their non-dragged positions.
     */
    TabBar.prototype.releaseMouse = function () {
        this._releaseMouse();
    };
    /**
     * Handle the DOM events for the tab bar.
     *
     * @param event - The DOM event sent to the tab bar.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the tab bar's DOM node.
     *
     * This should not be called directly by user code.
     */
    TabBar.prototype.handleEvent = function (event) {
        switch (event.type) {
            case 'mousedown':
                this._evtMouseDown(event);
                break;
            case 'mousemove':
                this._evtMouseMove(event);
                break;
            case 'mouseup':
                this._evtMouseUp(event);
                break;
            case 'keydown':
                this._evtKeyDown(event);
                break;
            case 'contextmenu':
                event.preventDefault();
                event.stopPropagation();
                break;
        }
    };
    /**
     * A message handler invoked on a `'before-attach'` message.
     */
    TabBar.prototype.onBeforeAttach = function (msg) {
        this.node.addEventListener('mousedown', this);
    };
    /**
     * A message handler invoked on an `'after-detach'` message.
     */
    TabBar.prototype.onAfterDetach = function (msg) {
        this.node.removeEventListener('mousedown', this);
        this._releaseMouse();
    };
    /**
     * A message handler invoked on an `'update-request'` message.
     */
    TabBar.prototype.onUpdateRequest = function (msg) {
        var titles = this._titles;
        var renderer = this.renderer;
        var currentTitle = this.currentTitle;
        var content = new Array(titles.length);
        for (var i = 0, n = titles.length; i < n; ++i) {
            var title = titles[i];
            var current = title === currentTitle;
            var zIndex = current ? n : n - i - 1;
            content[i] = renderer.renderTab({ title: title, current: current, zIndex: zIndex });
        }
        virtualdom_1.VirtualDOM.render(content, this.contentNode);
    };
    /**
     * Handle the `'keydown'` event for the tab bar.
     */
    TabBar.prototype._evtKeyDown = function (event) {
        // Stop all input events during drag.
        event.preventDefault();
        event.stopPropagation();
        // Release the mouse if `Escape` is pressed.
        if (event.keyCode === 27) {
            this._releaseMouse();
        }
    };
    /**
     * Handle the `'mousedown'` event for the tab bar.
     */
    TabBar.prototype._evtMouseDown = function (event) {
        // Do nothing if it's not a left or middle mouse press.
        if (event.button !== 0 && event.button !== 1) {
            return;
        }
        // Do nothing if a drag is in progress.
        if (this._dragData) {
            return;
        }
        // Lookup the tab nodes.
        var tabs = this.contentNode.children;
        // Find the index of the pressed tab.
        var index = algorithm_1.ArrayExt.findFirstIndex(tabs, function (tab) {
            return domutils_1.ElementExt.hitTest(tab, event.clientX, event.clientY);
        });
        // Do nothing if the press is not on a tab.
        if (index === -1) {
            return;
        }
        // Pressing on a tab stops the event propagation.
        event.preventDefault();
        event.stopPropagation();
        // Initialize the non-measured parts of the drag data.
        this._dragData = {
            tab: tabs[index],
            index: index,
            pressX: event.clientX,
            pressY: event.clientY,
            tabPos: -1,
            tabSize: -1,
            tabPressPos: -1,
            targetIndex: -1,
            tabLayout: null,
            contentRect: null,
            override: null,
            dragActive: false,
            dragAborted: false,
            detachRequested: false
        };
        // Add the document mouse up listener.
        document.addEventListener('mouseup', this, true);
        // Do nothing else if the middle button is clicked.
        if (event.button === 1) {
            return;
        }
        // Do nothing else if the close icon is clicked.
        var icon = tabs[index].querySelector(this.renderer.closeIconSelector);
        if (icon && icon.contains(event.target)) {
            return;
        }
        // Add the extra listeners if the tabs are movable.
        if (this.tabsMovable) {
            document.addEventListener('mousemove', this, true);
            document.addEventListener('keydown', this, true);
            document.addEventListener('contextmenu', this, true);
        }
        // Update the current index as appropriate.
        if (this.allowDeselect && this.currentIndex === index) {
            this.currentIndex = -1;
        }
        else {
            this.currentIndex = index;
        }
        // Do nothing else if there is no current tab.
        if (this.currentIndex === -1) {
            return;
        }
        // Emit the tab activate request signal.
        this._tabActivateRequested.emit({
            index: this.currentIndex, title: this.currentTitle
        });
    };
    /**
     * Handle the `'mousemove'` event for the tab bar.
     */
    TabBar.prototype._evtMouseMove = function (event) {
        // Do nothing if no drag is in progress.
        var data = this._dragData;
        if (!data) {
            return;
        }
        // Suppress the event during a drag.
        event.preventDefault();
        event.stopPropagation();
        // Lookup the tab nodes.
        var tabs = this.contentNode.children;
        // Bail early if the drag threshold has not been met.
        if (!data.dragActive && !Private.dragExceeded(data, event)) {
            return;
        }
        // Activate the drag if necessary.
        if (!data.dragActive) {
            // Fill in the rest of the drag data measurements.
            var tabRect = data.tab.getBoundingClientRect();
            if (this._orientation === 'horizontal') {
                data.tabPos = data.tab.offsetLeft;
                data.tabSize = tabRect.width;
                data.tabPressPos = data.pressX - tabRect.left;
            }
            else {
                data.tabPos = data.tab.offsetTop;
                data.tabSize = tabRect.height;
                data.tabPressPos = data.pressY - tabRect.top;
            }
            data.tabLayout = Private.snapTabLayout(tabs, this._orientation);
            data.contentRect = this.contentNode.getBoundingClientRect();
            data.override = dragdrop_1.Drag.overrideCursor('default');
            // Add the dragging style classes.
            data.tab.classList.add('p-mod-dragging');
            this.addClass('p-mod-dragging');
            // Mark the drag as active.
            data.dragActive = true;
        }
        // Emit the detach requested signal if the threshold is exceeded.
        if (!data.detachRequested && Private.detachExceeded(data, event)) {
            // Only emit the signal once per drag cycle.
            data.detachRequested = true;
            // Setup the arguments for the signal.
            var index = data.index;
            var clientX = event.clientX;
            var clientY = event.clientY;
            var tab = tabs[index];
            var title = this._titles[index];
            // Emit the tab detach requested signal.
            this._tabDetachRequested.emit({ index: index, title: title, tab: tab, clientX: clientX, clientY: clientY });
            // Bail if the signal handler aborted the drag.
            if (data.dragAborted) {
                return;
            }
        }
        // Update the positions of the tabs.
        Private.layoutTabs(tabs, data, event, this._orientation);
    };
    /**
     * Handle the `'mouseup'` event for the document.
     */
    TabBar.prototype._evtMouseUp = function (event) {
        var _this = this;
        // Do nothing if it's not a left or middle mouse release.
        if (event.button !== 0 && event.button !== 1) {
            return;
        }
        // Do nothing if no drag is in progress.
        var data = this._dragData;
        if (!data) {
            return;
        }
        // Stop the event propagation.
        event.preventDefault();
        event.stopPropagation();
        // Remove the extra mouse event listeners.
        document.removeEventListener('mousemove', this, true);
        document.removeEventListener('mouseup', this, true);
        document.removeEventListener('keydown', this, true);
        document.removeEventListener('contextmenu', this, true);
        // Handle a release when the drag is not active.
        if (!data.dragActive) {
            // Clear the drag data.
            this._dragData = null;
            // Lookup the tab nodes.
            var tabs = this.contentNode.children;
            // Find the index of the released tab.
            var index = algorithm_1.ArrayExt.findFirstIndex(tabs, function (tab) {
                return domutils_1.ElementExt.hitTest(tab, event.clientX, event.clientY);
            });
            // Do nothing if the release is not on the original pressed tab.
            if (index !== data.index) {
                return;
            }
            // Ignore the release if the title is not closable.
            var title = this._titles[index];
            if (!title.closable) {
                return;
            }
            // Emit the close requested signal if the middle button is released.
            if (event.button === 1) {
                this._tabCloseRequested.emit({ index: index, title: title });
                return;
            }
            // Emit the close requested signal if the close icon was released.
            var icon = tabs[index].querySelector(this.renderer.closeIconSelector);
            if (icon && icon.contains(event.target)) {
                this._tabCloseRequested.emit({ index: index, title: title });
                return;
            }
            // Otherwise, there is nothing left to do.
            return;
        }
        // Do nothing if the left button is not released.
        if (event.button !== 0) {
            return;
        }
        // Position the tab at its final resting position.
        Private.finalizeTabPosition(data, this._orientation);
        // Remove the dragging class from the tab so it can be transitioned.
        data.tab.classList.remove('p-mod-dragging');
        // Parse the transition duration for releasing the tab.
        var duration = Private.parseTransitionDuration(data.tab);
        // Complete the release on a timer to allow the tab to transition.
        setTimeout(function () {
            // Do nothing if the drag has been aborted.
            if (data.dragAborted) {
                return;
            }
            // Clear the drag data reference.
            _this._dragData = null;
            // Reset the positions of the tabs.
            Private.resetTabPositions(_this.contentNode.children, _this._orientation);
            // Clear the cursor grab.
            data.override.dispose();
            // Remove the remaining dragging style.
            _this.removeClass('p-mod-dragging');
            // If the tab was not moved, there is nothing else to do.
            var i = data.index;
            var j = data.targetIndex;
            if (j === -1 || i === j) {
                return;
            }
            // Move the title to the new locations.
            algorithm_1.ArrayExt.move(_this._titles, i, j);
            // Adjust the current index for the move.
            _this._adjustCurrentForMove(i, j);
            // Emit the tab moved signal.
            _this._tabMoved.emit({
                fromIndex: i, toIndex: j, title: _this._titles[j]
            });
            // Update the tabs immediately to prevent flicker.
            messaging_1.MessageLoop.sendMessage(_this, widget_1.Widget.Msg.UpdateRequest);
        }, duration);
    };
    /**
     * Release the mouse and restore the non-dragged tab positions.
     */
    TabBar.prototype._releaseMouse = function () {
        // Do nothing if no drag is in progress.
        var data = this._dragData;
        if (!data) {
            return;
        }
        // Clear the drag data reference.
        this._dragData = null;
        // Remove the extra mouse listeners.
        document.removeEventListener('mousemove', this, true);
        document.removeEventListener('mouseup', this, true);
        document.removeEventListener('keydown', this, true);
        document.removeEventListener('contextmenu', this, true);
        // Indicate the drag has been aborted. This allows the mouse
        // event handlers to return early when the drag is canceled.
        data.dragAborted = true;
        // If the drag is not active, there's nothing more to do.
        if (!data.dragActive) {
            return;
        }
        // Reset the tabs to their non-dragged positions.
        Private.resetTabPositions(this.contentNode.children, this._orientation);
        // Clear the cursor override.
        data.override.dispose();
        // Clear the dragging style classes.
        data.tab.classList.remove('p-mod-dragging');
        this.removeClass('p-mod-dragging');
    };
    /**
     * Adjust the current index for a tab insert operation.
     *
     * This method accounts for the tab bar's insertion behavior when
     * adjusting the current index and emitting the changed signal.
     */
    TabBar.prototype._adjustCurrentForInsert = function (i, title) {
        // Lookup commonly used variables.
        var ct = this.currentTitle;
        var ci = this._currentIndex;
        var bh = this.insertBehavior;
        // Handle the behavior where the new tab is always selected,
        // or the behavior where the new tab is selected if needed.
        if (bh === 'select-tab' || (bh === 'select-tab-if-needed' && ci === -1)) {
            this._currentIndex = i;
            this._previousTitle = ct;
            this._currentChanged.emit({
                previousIndex: ci, previousTitle: ct,
                currentIndex: i, currentTitle: title
            });
            return;
        }
        // Otherwise, silently adjust the current index if needed.
        if (ci >= i) {
            this._currentIndex++;
        }
    };
    /**
     * Adjust the current index for a tab move operation.
     *
     * This method will not cause the actual current tab to change.
     * It silently adjusts the index to account for the given move.
     */
    TabBar.prototype._adjustCurrentForMove = function (i, j) {
        if (this._currentIndex === i) {
            this._currentIndex = j;
        }
        else if (this._currentIndex < i && this._currentIndex >= j) {
            this._currentIndex++;
        }
        else if (this._currentIndex > i && this._currentIndex <= j) {
            this._currentIndex--;
        }
    };
    /**
     * Adjust the current index for a tab remove operation.
     *
     * This method accounts for the tab bar's remove behavior when
     * adjusting the current index and emitting the changed signal.
     */
    TabBar.prototype._adjustCurrentForRemove = function (i, title) {
        // Lookup commonly used variables.
        var ci = this._currentIndex;
        var bh = this.removeBehavior;
        // Silently adjust the index if the current tab is not removed.
        if (ci !== i) {
            if (ci > i) {
                this._currentIndex--;
            }
            return;
        }
        // No tab gets selected if the tab bar is empty.
        if (this._titles.length === 0) {
            this._currentIndex = -1;
            this._currentChanged.emit({
                previousIndex: i, previousTitle: title,
                currentIndex: -1, currentTitle: null
            });
            return;
        }
        // Handle behavior where the next sibling tab is selected.
        if (bh === 'select-tab-after') {
            this._currentIndex = Math.min(i, this._titles.length - 1);
            this._currentChanged.emit({
                previousIndex: i, previousTitle: title,
                currentIndex: this._currentIndex, currentTitle: this.currentTitle
            });
            return;
        }
        // Handle behavior where the previous sibling tab is selected.
        if (bh === 'select-tab-before') {
            this._currentIndex = Math.max(0, i - 1);
            this._currentChanged.emit({
                previousIndex: i, previousTitle: title,
                currentIndex: this._currentIndex, currentTitle: this.currentTitle
            });
            return;
        }
        // Handle behavior where the previous history tab is selected.
        if (bh === 'select-previous-tab') {
            if (this._previousTitle) {
                this._currentIndex = this._titles.indexOf(this._previousTitle);
                this._previousTitle = null;
            }
            else {
                this._currentIndex = Math.min(i, this._titles.length - 1);
            }
            this._currentChanged.emit({
                previousIndex: i, previousTitle: title,
                currentIndex: this._currentIndex, currentTitle: this.currentTitle
            });
            return;
        }
        // Otherwise, no tab gets selected.
        this._currentIndex = -1;
        this._currentChanged.emit({
            previousIndex: i, previousTitle: title,
            currentIndex: -1, currentTitle: null
        });
    };
    /**
     * Handle the `changed` signal of a title object.
     */
    TabBar.prototype._onTitleChanged = function (sender) {
        this.update();
    };
    return TabBar;
}(widget_1.Widget));
exports.TabBar = TabBar;
/**
 * The namespace for the `TabBar` class statics.
 */
(function (TabBar) {
    /**
     * The default implementation of `IRenderer`.
     *
     * #### Notes
     * Subclasses are free to reimplement rendering methods as needed.
     */
    var Renderer = (function () {
        /**
         * Construct a new renderer.
         */
        function Renderer() {
            /**
             * A selector which matches the close icon node in a tab.
             */
            this.closeIconSelector = '.p-TabBar-tabCloseIcon';
            this._tabID = 0;
            this._tabKeys = new WeakMap();
        }
        /**
         * Render the virtual element for a tab.
         *
         * @param data - The data to use for rendering the tab.
         *
         * @returns A virtual element representing the tab.
         */
        Renderer.prototype.renderTab = function (data) {
            var title = data.title.caption;
            var key = this.createTabKey(data);
            var style = this.createTabStyle(data);
            var className = this.createTabClass(data);
            var dataset = this.createTabDataset(data);
            return (virtualdom_1.h.li({ key: key, className: className, title: title, style: style, dataset: dataset }, this.renderIcon(data), this.renderLabel(data), this.renderCloseIcon(data)));
        };
        /**
         * Render the icon element for a tab.
         *
         * @param data - The data to use for rendering the tab.
         *
         * @returns A virtual element representing the tab icon.
         */
        Renderer.prototype.renderIcon = function (data) {
            var className = this.createIconClass(data);
            return virtualdom_1.h.div({ className: className }, data.title.iconLabel);
        };
        /**
         * Render the label element for a tab.
         *
         * @param data - The data to use for rendering the tab.
         *
         * @returns A virtual element representing the tab label.
         */
        Renderer.prototype.renderLabel = function (data) {
            return virtualdom_1.h.div({ className: 'p-TabBar-tabLabel' }, data.title.label);
        };
        /**
         * Render the close icon element for a tab.
         *
         * @param data - The data to use for rendering the tab.
         *
         * @returns A virtual element representing the tab close icon.
         */
        Renderer.prototype.renderCloseIcon = function (data) {
            return virtualdom_1.h.div({ className: 'p-TabBar-tabCloseIcon' });
        };
        /**
         * Create a unique render key for the tab.
         *
         * @param data - The data to use for the tab.
         *
         * @returns The unique render key for the tab.
         *
         * #### Notes
         * This method caches the key against the tab title the first time
         * the key is generated. This enables efficient rendering of moved
         * tabs and avoids subtle hover style artifacts.
         */
        Renderer.prototype.createTabKey = function (data) {
            var key = this._tabKeys.get(data.title);
            if (key === undefined) {
                key = "tab-key-" + this._tabID++;
                this._tabKeys.set(data.title, key);
            }
            return key;
        };
        /**
         * Create the inline style object for a tab.
         *
         * @param data - The data to use for the tab.
         *
         * @returns The inline style data for the tab.
         */
        Renderer.prototype.createTabStyle = function (data) {
            return { zIndex: "" + data.zIndex };
        };
        /**
         * Create the class name for the tab.
         *
         * @param data - The data to use for the tab.
         *
         * @returns The full class name for the tab.
         */
        Renderer.prototype.createTabClass = function (data) {
            var name = 'p-TabBar-tab';
            if (data.title.className) {
                name += " " + data.title.className;
            }
            if (data.title.closable) {
                name += ' p-mod-closable';
            }
            if (data.current) {
                name += ' p-mod-current';
            }
            return name;
        };
        /**
         * Create the dataset for a tab.
         *
         * @param data - The data to use for the tab.
         *
         * @returns The dataset for the tab.
         */
        Renderer.prototype.createTabDataset = function (data) {
            return data.title.dataset;
        };
        /**
         * Create the class name for the tab icon.
         *
         * @param data - The data to use for the tab.
         *
         * @returns The full class name for the tab icon.
         */
        Renderer.prototype.createIconClass = function (data) {
            var name = 'p-TabBar-tabIcon';
            var extra = data.title.iconClass;
            return extra ? name + " " + extra : name;
        };
        return Renderer;
    }());
    TabBar.Renderer = Renderer;
    /**
     * The default `Renderer` instance.
     */
    TabBar.defaultRenderer = new Renderer();
})(TabBar = exports.TabBar || (exports.TabBar = {}));
exports.TabBar = TabBar;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * The start drag distance threshold.
     */
    Private.DRAG_THRESHOLD = 5;
    /**
     * The detach distance threshold.
     */
    Private.DETACH_THRESHOLD = 20;
    /**
     * Create the DOM node for a tab bar.
     */
    function createNode() {
        var node = document.createElement('div');
        var content = document.createElement('ul');
        content.className = 'p-TabBar-content';
        node.appendChild(content);
        return node;
    }
    Private.createNode = createNode;
    /**
     * Coerce a title or options into a real title.
     */
    function asTitle(value) {
        return value instanceof title_1.Title ? value : new title_1.Title(value);
    }
    Private.asTitle = asTitle;
    /**
     * Parse the transition duration for a tab node.
     */
    function parseTransitionDuration(tab) {
        var style = window.getComputedStyle(tab);
        return 1000 * (parseFloat(style.transitionDuration) || 0);
    }
    Private.parseTransitionDuration = parseTransitionDuration;
    /**
     * Get a snapshot of the current tab layout values.
     */
    function snapTabLayout(tabs, orientation) {
        var layout = new Array(tabs.length);
        for (var i = 0, n = tabs.length; i < n; ++i) {
            var node = tabs[i];
            var style = window.getComputedStyle(node);
            if (orientation === 'horizontal') {
                layout[i] = {
                    pos: node.offsetLeft,
                    size: node.offsetWidth,
                    margin: parseFloat(style.marginLeft) || 0
                };
            }
            else {
                layout[i] = {
                    pos: node.offsetTop,
                    size: node.offsetHeight,
                    margin: parseFloat(style.marginTop) || 0
                };
            }
        }
        return layout;
    }
    Private.snapTabLayout = snapTabLayout;
    /**
     * Test if the event exceeds the drag threshold.
     */
    function dragExceeded(data, event) {
        var dx = Math.abs(event.clientX - data.pressX);
        var dy = Math.abs(event.clientY - data.pressY);
        return dx >= Private.DRAG_THRESHOLD || dy >= Private.DRAG_THRESHOLD;
    }
    Private.dragExceeded = dragExceeded;
    /**
     * Test if the event exceeds the drag detach threshold.
     */
    function detachExceeded(data, event) {
        var rect = data.contentRect;
        return ((event.clientX < rect.left - Private.DETACH_THRESHOLD) ||
            (event.clientX >= rect.right + Private.DETACH_THRESHOLD) ||
            (event.clientY < rect.top - Private.DETACH_THRESHOLD) ||
            (event.clientY >= rect.bottom + Private.DETACH_THRESHOLD));
    }
    Private.detachExceeded = detachExceeded;
    /**
     * Update the relative tab positions and computed target index.
     */
    function layoutTabs(tabs, data, event, orientation) {
        // Compute the orientation-sensitive values.
        var pressPos;
        var localPos;
        var clientPos;
        var clientSize;
        if (orientation === 'horizontal') {
            pressPos = data.pressX;
            localPos = event.clientX - data.contentRect.left;
            clientPos = event.clientX;
            clientSize = data.contentRect.width;
        }
        else {
            pressPos = data.pressY;
            localPos = event.clientY - data.contentRect.top;
            clientPos = event.clientY;
            clientSize = data.contentRect.height;
        }
        // Compute the target data.
        var targetIndex = data.index;
        var targetPos = localPos - data.tabPressPos;
        var targetEnd = targetPos + data.tabSize;
        // Update the relative tab positions.
        for (var i = 0, n = tabs.length; i < n; ++i) {
            var pxPos = void 0;
            var layout = data.tabLayout[i];
            var threshold = layout.pos + (layout.size >> 1);
            if (i < data.index && targetPos < threshold) {
                pxPos = data.tabSize + data.tabLayout[i + 1].margin + "px";
                targetIndex = Math.min(targetIndex, i);
            }
            else if (i > data.index && targetEnd > threshold) {
                pxPos = -data.tabSize - layout.margin + "px";
                targetIndex = Math.max(targetIndex, i);
            }
            else if (i === data.index) {
                var ideal = clientPos - pressPos;
                var limit = clientSize - (data.tabPos + data.tabSize);
                pxPos = Math.max(-data.tabPos, Math.min(ideal, limit)) + "px";
            }
            else {
                pxPos = '';
            }
            if (orientation === 'horizontal') {
                tabs[i].style.left = pxPos;
            }
            else {
                tabs[i].style.top = pxPos;
            }
        }
        // Update the computed target index.
        data.targetIndex = targetIndex;
    }
    Private.layoutTabs = layoutTabs;
    /**
     * Position the drag tab at its final resting relative position.
     */
    function finalizeTabPosition(data, orientation) {
        // Compute the orientation-sensitive client size.
        var clientSize;
        if (orientation === 'horizontal') {
            clientSize = data.contentRect.width;
        }
        else {
            clientSize = data.contentRect.height;
        }
        // Compute the ideal final tab position.
        var ideal;
        if (data.targetIndex === data.index) {
            ideal = 0;
        }
        else if (data.targetIndex > data.index) {
            var tgt = data.tabLayout[data.targetIndex];
            ideal = tgt.pos + tgt.size - data.tabSize - data.tabPos;
        }
        else {
            var tgt = data.tabLayout[data.targetIndex];
            ideal = tgt.pos - data.tabPos;
        }
        // Compute the tab position limit.
        var limit = clientSize - (data.tabPos + data.tabSize);
        var final = Math.max(-data.tabPos, Math.min(ideal, limit));
        // Set the final orientation-sensitive position.
        if (orientation === 'horizontal') {
            data.tab.style.left = final + "px";
        }
        else {
            data.tab.style.top = final + "px";
        }
    }
    Private.finalizeTabPosition = finalizeTabPosition;
    /**
     * Reset the relative positions of the given tabs.
     */
    function resetTabPositions(tabs, orientation) {
        algorithm_1.each(tabs, function (tab) {
            if (orientation === 'horizontal') {
                tab.style.left = '';
            }
            else {
                tab.style.top = '';
            }
        });
    }
    Private.resetTabPositions = resetTabPositions;
})(Private || (Private = {}));


/***/ }),

/***/ "g2Dh":
/*!****************************************************!*\
  !*** ./node_modules/asn1.js/lib/asn1/base/node.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Reporter = __webpack_require__(/*! ../base */ "Qd/k").Reporter;
var EncoderBuffer = __webpack_require__(/*! ../base */ "Qd/k").EncoderBuffer;
var DecoderBuffer = __webpack_require__(/*! ../base */ "Qd/k").DecoderBuffer;
var assert = __webpack_require__(/*! minimalistic-assert */ "2j6C");

// Supported tags
var tags = [
  'seq', 'seqof', 'set', 'setof', 'objid', 'bool',
  'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc',
  'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str',
  'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr'
];

// Public methods list
var methods = [
  'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice',
  'any', 'contains'
].concat(tags);

// Overrided methods list
var overrided = [
  '_peekTag', '_decodeTag', '_use',
  '_decodeStr', '_decodeObjid', '_decodeTime',
  '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList',

  '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime',
  '_encodeNull', '_encodeInt', '_encodeBool'
];

function Node(enc, parent) {
  var state = {};
  this._baseState = state;

  state.enc = enc;

  state.parent = parent || null;
  state.children = null;

  // State
  state.tag = null;
  state.args = null;
  state.reverseArgs = null;
  state.choice = null;
  state.optional = false;
  state.any = false;
  state.obj = false;
  state.use = null;
  state.useDecoder = null;
  state.key = null;
  state['default'] = null;
  state.explicit = null;
  state.implicit = null;
  state.contains = null;

  // Should create new instance on each method
  if (!state.parent) {
    state.children = [];
    this._wrap();
  }
}
module.exports = Node;

var stateProps = [
  'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice',
  'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit',
  'implicit', 'contains'
];

Node.prototype.clone = function clone() {
  var state = this._baseState;
  var cstate = {};
  stateProps.forEach(function(prop) {
    cstate[prop] = state[prop];
  });
  var res = new this.constructor(cstate.parent);
  res._baseState = cstate;
  return res;
};

Node.prototype._wrap = function wrap() {
  var state = this._baseState;
  methods.forEach(function(method) {
    this[method] = function _wrappedMethod() {
      var clone = new this.constructor(this);
      state.children.push(clone);
      return clone[method].apply(clone, arguments);
    };
  }, this);
};

Node.prototype._init = function init(body) {
  var state = this._baseState;

  assert(state.parent === null);
  body.call(this);

  // Filter children
  state.children = state.children.filter(function(child) {
    return child._baseState.parent === this;
  }, this);
  assert.equal(state.children.length, 1, 'Root node can have only one child');
};

Node.prototype._useArgs = function useArgs(args) {
  var state = this._baseState;

  // Filter children and args
  var children = args.filter(function(arg) {
    return arg instanceof this.constructor;
  }, this);
  args = args.filter(function(arg) {
    return !(arg instanceof this.constructor);
  }, this);

  if (children.length !== 0) {
    assert(state.children === null);
    state.children = children;

    // Replace parent to maintain backward link
    children.forEach(function(child) {
      child._baseState.parent = this;
    }, this);
  }
  if (args.length !== 0) {
    assert(state.args === null);
    state.args = args;
    state.reverseArgs = args.map(function(arg) {
      if (typeof arg !== 'object' || arg.constructor !== Object)
        return arg;

      var res = {};
      Object.keys(arg).forEach(function(key) {
        if (key == (key | 0))
          key |= 0;
        var value = arg[key];
        res[value] = key;
      });
      return res;
    });
  }
};

//
// Overrided methods
//

overrided.forEach(function(method) {
  Node.prototype[method] = function _overrided() {
    var state = this._baseState;
    throw new Error(method + ' not implemented for encoding: ' + state.enc);
  };
});

//
// Public methods
//

tags.forEach(function(tag) {
  Node.prototype[tag] = function _tagMethod() {
    var state = this._baseState;
    var args = Array.prototype.slice.call(arguments);

    assert(state.tag === null);
    state.tag = tag;

    this._useArgs(args);

    return this;
  };
});

Node.prototype.use = function use(item) {
  assert(item);
  var state = this._baseState;

  assert(state.use === null);
  state.use = item;

  return this;
};

Node.prototype.optional = function optional() {
  var state = this._baseState;

  state.optional = true;

  return this;
};

Node.prototype.def = function def(val) {
  var state = this._baseState;

  assert(state['default'] === null);
  state['default'] = val;
  state.optional = true;

  return this;
};

Node.prototype.explicit = function explicit(num) {
  var state = this._baseState;

  assert(state.explicit === null && state.implicit === null);
  state.explicit = num;

  return this;
};

Node.prototype.implicit = function implicit(num) {
  var state = this._baseState;

  assert(state.explicit === null && state.implicit === null);
  state.implicit = num;

  return this;
};

Node.prototype.obj = function obj() {
  var state = this._baseState;
  var args = Array.prototype.slice.call(arguments);

  state.obj = true;

  if (args.length !== 0)
    this._useArgs(args);

  return this;
};

Node.prototype.key = function key(newKey) {
  var state = this._baseState;

  assert(state.key === null);
  state.key = newKey;

  return this;
};

Node.prototype.any = function any() {
  var state = this._baseState;

  state.any = true;

  return this;
};

Node.prototype.choice = function choice(obj) {
  var state = this._baseState;

  assert(state.choice === null);
  state.choice = obj;
  this._useArgs(Object.keys(obj).map(function(key) {
    return obj[key];
  }));

  return this;
};

Node.prototype.contains = function contains(item) {
  var state = this._baseState;

  assert(state.use === null);
  state.contains = item;

  return this;
};

//
// Decoding
//

Node.prototype._decode = function decode(input, options) {
  var state = this._baseState;

  // Decode root node
  if (state.parent === null)
    return input.wrapResult(state.children[0]._decode(input, options));

  var result = state['default'];
  var present = true;

  var prevKey = null;
  if (state.key !== null)
    prevKey = input.enterKey(state.key);

  // Check if tag is there
  if (state.optional) {
    var tag = null;
    if (state.explicit !== null)
      tag = state.explicit;
    else if (state.implicit !== null)
      tag = state.implicit;
    else if (state.tag !== null)
      tag = state.tag;

    if (tag === null && !state.any) {
      // Trial and Error
      var save = input.save();
      try {
        if (state.choice === null)
          this._decodeGeneric(state.tag, input, options);
        else
          this._decodeChoice(input, options);
        present = true;
      } catch (e) {
        present = false;
      }
      input.restore(save);
    } else {
      present = this._peekTag(input, tag, state.any);

      if (input.isError(present))
        return present;
    }
  }

  // Push object on stack
  var prevObj;
  if (state.obj && present)
    prevObj = input.enterObject();

  if (present) {
    // Unwrap explicit values
    if (state.explicit !== null) {
      var explicit = this._decodeTag(input, state.explicit);
      if (input.isError(explicit))
        return explicit;
      input = explicit;
    }

    var start = input.offset;

    // Unwrap implicit and normal values
    if (state.use === null && state.choice === null) {
      if (state.any)
        var save = input.save();
      var body = this._decodeTag(
        input,
        state.implicit !== null ? state.implicit : state.tag,
        state.any
      );
      if (input.isError(body))
        return body;

      if (state.any)
        result = input.raw(save);
      else
        input = body;
    }

    if (options && options.track && state.tag !== null)
      options.track(input.path(), start, input.length, 'tagged');

    if (options && options.track && state.tag !== null)
      options.track(input.path(), input.offset, input.length, 'content');

    // Select proper method for tag
    if (state.any)
      result = result;
    else if (state.choice === null)
      result = this._decodeGeneric(state.tag, input, options);
    else
      result = this._decodeChoice(input, options);

    if (input.isError(result))
      return result;

    // Decode children
    if (!state.any && state.choice === null && state.children !== null) {
      state.children.forEach(function decodeChildren(child) {
        // NOTE: We are ignoring errors here, to let parser continue with other
        // parts of encoded data
        child._decode(input, options);
      });
    }

    // Decode contained/encoded by schema, only in bit or octet strings
    if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) {
      var data = new DecoderBuffer(result);
      result = this._getUse(state.contains, input._reporterState.obj)
          ._decode(data, options);
    }
  }

  // Pop object
  if (state.obj && present)
    result = input.leaveObject(prevObj);

  // Set key
  if (state.key !== null && (result !== null || present === true))
    input.leaveKey(prevKey, state.key, result);
  else if (prevKey !== null)
    input.exitKey(prevKey);

  return result;
};

Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) {
  var state = this._baseState;

  if (tag === 'seq' || tag === 'set')
    return null;
  if (tag === 'seqof' || tag === 'setof')
    return this._decodeList(input, tag, state.args[0], options);
  else if (/str$/.test(tag))
    return this._decodeStr(input, tag, options);
  else if (tag === 'objid' && state.args)
    return this._decodeObjid(input, state.args[0], state.args[1], options);
  else if (tag === 'objid')
    return this._decodeObjid(input, null, null, options);
  else if (tag === 'gentime' || tag === 'utctime')
    return this._decodeTime(input, tag, options);
  else if (tag === 'null_')
    return this._decodeNull(input, options);
  else if (tag === 'bool')
    return this._decodeBool(input, options);
  else if (tag === 'objDesc')
    return this._decodeStr(input, tag, options);
  else if (tag === 'int' || tag === 'enum')
    return this._decodeInt(input, state.args && state.args[0], options);

  if (state.use !== null) {
    return this._getUse(state.use, input._reporterState.obj)
        ._decode(input, options);
  } else {
    return input.error('unknown tag: ' + tag);
  }
};

Node.prototype._getUse = function _getUse(entity, obj) {

  var state = this._baseState;
  // Create altered use decoder if implicit is set
  state.useDecoder = this._use(entity, obj);
  assert(state.useDecoder._baseState.parent === null);
  state.useDecoder = state.useDecoder._baseState.children[0];
  if (state.implicit !== state.useDecoder._baseState.implicit) {
    state.useDecoder = state.useDecoder.clone();
    state.useDecoder._baseState.implicit = state.implicit;
  }
  return state.useDecoder;
};

Node.prototype._decodeChoice = function decodeChoice(input, options) {
  var state = this._baseState;
  var result = null;
  var match = false;

  Object.keys(state.choice).some(function(key) {
    var save = input.save();
    var node = state.choice[key];
    try {
      var value = node._decode(input, options);
      if (input.isError(value))
        return false;

      result = { type: key, value: value };
      match = true;
    } catch (e) {
      input.restore(save);
      return false;
    }
    return true;
  }, this);

  if (!match)
    return input.error('Choice not matched');

  return result;
};

//
// Encoding
//

Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) {
  return new EncoderBuffer(data, this.reporter);
};

Node.prototype._encode = function encode(data, reporter, parent) {
  var state = this._baseState;
  if (state['default'] !== null && state['default'] === data)
    return;

  var result = this._encodeValue(data, reporter, parent);
  if (result === undefined)
    return;

  if (this._skipDefault(result, reporter, parent))
    return;

  return result;
};

Node.prototype._encodeValue = function encode(data, reporter, parent) {
  var state = this._baseState;

  // Decode root node
  if (state.parent === null)
    return state.children[0]._encode(data, reporter || new Reporter());

  var result = null;

  // Set reporter to share it with a child class
  this.reporter = reporter;

  // Check if data is there
  if (state.optional && data === undefined) {
    if (state['default'] !== null)
      data = state['default']
    else
      return;
  }

  // Encode children first
  var content = null;
  var primitive = false;
  if (state.any) {
    // Anything that was given is translated to buffer
    result = this._createEncoderBuffer(data);
  } else if (state.choice) {
    result = this._encodeChoice(data, reporter);
  } else if (state.contains) {
    content = this._getUse(state.contains, parent)._encode(data, reporter);
    primitive = true;
  } else if (state.children) {
    content = state.children.map(function(child) {
      if (child._baseState.tag === 'null_')
        return child._encode(null, reporter, data);

      if (child._baseState.key === null)
        return reporter.error('Child should have a key');
      var prevKey = reporter.enterKey(child._baseState.key);

      if (typeof data !== 'object')
        return reporter.error('Child expected, but input is not object');

      var res = child._encode(data[child._baseState.key], reporter, data);
      reporter.leaveKey(prevKey);

      return res;
    }, this).filter(function(child) {
      return child;
    });
    content = this._createEncoderBuffer(content);
  } else {
    if (state.tag === 'seqof' || state.tag === 'setof') {
      // TODO(indutny): this should be thrown on DSL level
      if (!(state.args && state.args.length === 1))
        return reporter.error('Too many args for : ' + state.tag);

      if (!Array.isArray(data))
        return reporter.error('seqof/setof, but data is not Array');

      var child = this.clone();
      child._baseState.implicit = null;
      content = this._createEncoderBuffer(data.map(function(item) {
        var state = this._baseState;

        return this._getUse(state.args[0], data)._encode(item, reporter);
      }, child));
    } else if (state.use !== null) {
      result = this._getUse(state.use, parent)._encode(data, reporter);
    } else {
      content = this._encodePrimitive(state.tag, data);
      primitive = true;
    }
  }

  // Encode data itself
  var result;
  if (!state.any && state.choice === null) {
    var tag = state.implicit !== null ? state.implicit : state.tag;
    var cls = state.implicit === null ? 'universal' : 'context';

    if (tag === null) {
      if (state.use === null)
        reporter.error('Tag could be omitted only for .use()');
    } else {
      if (state.use === null)
        result = this._encodeComposite(tag, primitive, cls, content);
    }
  }

  // Wrap in explicit
  if (state.explicit !== null)
    result = this._encodeComposite(state.explicit, false, 'context', result);

  return result;
};

Node.prototype._encodeChoice = function encodeChoice(data, reporter) {
  var state = this._baseState;

  var node = state.choice[data.type];
  if (!node) {
    assert(
        false,
        data.type + ' not found in ' +
            JSON.stringify(Object.keys(state.choice)));
  }
  return node._encode(data.value, reporter);
};

Node.prototype._encodePrimitive = function encodePrimitive(tag, data) {
  var state = this._baseState;

  if (/str$/.test(tag))
    return this._encodeStr(data, tag);
  else if (tag === 'objid' && state.args)
    return this._encodeObjid(data, state.reverseArgs[0], state.args[1]);
  else if (tag === 'objid')
    return this._encodeObjid(data, null, null);
  else if (tag === 'gentime' || tag === 'utctime')
    return this._encodeTime(data, tag);
  else if (tag === 'null_')
    return this._encodeNull();
  else if (tag === 'int' || tag === 'enum')
    return this._encodeInt(data, state.args && state.reverseArgs[0]);
  else if (tag === 'bool')
    return this._encodeBool(data);
  else if (tag === 'objDesc')
    return this._encodeStr(data, tag);
  else
    throw new Error('Unsupported tag: ' + tag);
};

Node.prototype._isNumstr = function isNumstr(str) {
  return /^[0-9 ]*$/.test(str);
};

Node.prototype._isPrintstr = function isPrintstr(str) {
  return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str);
};


/***/ }),

/***/ "g3A5":
/*!*********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/SymbolSelector.js ***!
  \*********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _SymbolSelector = __webpack_require__(/*! ../widgets/SymbolSelector */ "Nsyh");

var _SymbolSelector2 = _interopRequireDefault(_SymbolSelector);

var _nested_property = __webpack_require__(/*! plotly.js/src/lib/nested_property */ "dNZO");

var _nested_property2 = _interopRequireDefault(_nested_property);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _constants = __webpack_require__(/*! ../../lib/constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

// TODO compute these from plotly.js
var SYMBOLS = [{
  value: 'circle',
  label: 'M5,0A5,5 0 1,1 0,-5A5,5 0 0,1 5,0Z',
  threeD: true,
  gl: true
}, {
  value: 'circle-open',
  label: 'M5,0A5,5 0 1,1 0,-5A5,5 0 0,1 5,0Z',
  fill: 'none',
  threeD: true,
  gl: true
}, {
  value: 'circle-open-dot',
  label: 'M5,0A5,5 0 1,1 0,-5A5,5 0 0,1 5,0ZM0,0.5L0.5,0L0,-0.5L-0.5,0Z',
  fill: 'none'
}, { value: 'square', label: 'M5,5H-5V-5H5Z', threeD: true, gl: true }, {
  value: 'square-open',
  label: 'M5,5H-5V-5H5Z',
  fill: 'none',
  threeD: true,
  gl: true
}, {
  value: 'square-open-dot',
  label: 'M5,5H-5V-5H5ZM0,0.5L0.5,0L0,-0.5L-0.5,0Z',
  fill: 'none'
}, {
  value: 'diamond',
  label: 'M6.5,0L0,6.5L-6.5,0L0,-6.5Z',
  threeD: true,
  gl: true
}, {
  value: 'diamond-open',
  label: 'M6.5,0L0,6.5L-6.5,0L0,-6.5Z',
  fill: 'none',
  threeD: true,
  gl: true
}, {
  value: 'diamond-open-dot',
  label: 'M6.5,0L0,6.5L-6.5,0L0,-6.5ZM0,0.5L0.5,0L0,-0.5L-0.5,0Z',
  fill: 'none'
}, {
  value: 'cross',
  label: 'M6,2H2V6H-2V2H-6V-2H-2V-6H2V-2H6Z',
  threeD: true,
  gl: true
}, {
  value: 'cross-open',
  label: 'M6,2H2V6H-2V2H-6V-2H-2V-6H2V-2H6Z',
  fill: 'none',
  gl: true
}, {
  value: 'x',
  label: 'M0,2.83l2.83,2.83l2.83,-2.83l-2.83,-2.83l2.83,-2.83l-2.83,-2.83l-2.83,2.83l-2.83,-2.83l-2.83,2.83l2.83,2.83l-2.83,2.83l2.83,2.83Z',
  threeD: true,
  gl: true
}, {
  value: 'x-open',
  label: 'M0,2.83l2.83,2.83l2.83,-2.83l-2.83,-2.83l2.83,-2.83l-2.83,-2.83l-2.83,2.83l-2.83,-2.83l-2.83,2.83l2.83,2.83l-2.83,2.83l2.83,2.83Z',
  fill: 'none',
  gl: true
}, { value: 'triangle-up', label: 'M-5.77,2.5H5.77L0,-5Z', gl: true }, {
  value: 'triangle-up-open',
  label: 'M-5.77,2.5H5.77L0,-5Z',
  fill: 'none',
  gl: true
}, { value: 'triangle-down', label: 'M-5.77,-2.5H5.77L0,5Z', gl: true }, {
  value: 'triangle-down-open',
  label: 'M-5.77,-2.5H5.77L0,5Z',
  fill: 'none',
  gl: true
}, { value: 'triangle-left', label: 'M2.5,-5.77V5.77L-5,0Z', gl: true }, {
  value: 'triangle-left-open',
  label: 'M2.5,-5.77V5.77L-5,0Z',
  fill: 'none',
  gl: true
}, { value: 'triangle-right', label: 'M-2.5,-5.77V5.77L5,0Z', gl: true }, {
  value: 'triangle-right-open',
  label: 'M-2.5,-5.77V5.77L5,0Z',
  fill: 'none',
  gl: true
}, { value: 'triangle-ne', label: 'M-6,-3H3V6Z', gl: true }, {
  value: 'triangle-ne-open',
  label: 'M-6,-3H3V6Z',
  fill: 'none',
  gl: true
}, { value: 'triangle-se', label: 'M3,-6V3H-6Z', gl: true }, {
  value: 'triangle-se-open',
  label: 'M3,-6V3H-6Z',
  fill: 'none',
  gl: true
}, { value: 'triangle-sw', label: 'M6,3H-3V-6Z', gl: true }, {
  value: 'triangle-sw-open',
  label: 'M6,3H-3V-6Z',
  fill: 'none',
  gl: true
}, { value: 'triangle-nw', label: 'M-3,6V-3H6Z', gl: true }, {
  value: 'triangle-nw-open',
  label: 'M-3,6V-3H6Z',
  fill: 'none',
  gl: true
}, {
  value: 'pentagon',
  label: 'M4.76,-1.54L2.94,4.05H-2.94L-4.76,-1.54L0,-5Z',
  gl: true
}, {
  value: 'pentagon-open',
  label: 'M4.76,-1.54L2.94,4.05H-2.94L-4.76,-1.54L0,-5Z',
  fill: 'none',
  gl: true
}, {
  value: 'hexagon',
  label: 'M4.33,-2.5V2.5L0,5L-4.33,2.5V-2.5L0,-5Z',
  gl: true
}, {
  value: 'hexagon-open',
  label: 'M4.33,-2.5V2.5L0,5L-4.33,2.5V-2.5L0,-5Z',
  fill: 'none',
  gl: true
}, {
  value: 'hexagon2',
  label: 'M-2.5,4.33H2.5L5,0L2.5,-4.33H-2.5L-5,0Z',
  gl: true
}, {
  value: 'hexagon2-open',
  label: 'M-2.5,4.33H2.5L5,0L2.5,-4.33H-2.5L-5,0Z',
  fill: 'none',
  gl: true
}, {
  value: 'octagon',
  label: 'M-1.92,-4.62H1.92L4.62,-1.92V1.92L1.92,4.62H-1.92L-4.62,1.92V-1.92Z'
}, {
  value: 'octagon-open',
  label: 'M-1.92,-4.62H1.92L4.62,-1.92V1.92L1.92,4.62H-1.92L-4.62,1.92V-1.92Z',
  fill: 'none'
}, {
  value: 'star',
  label: 'M1.58,-2.16H6.66L2.54,0.83L4.12,5.66L0,2.67L-4.12,5.66L-2.54,0.83L-6.66,-2.16H-1.58L0,-7Z',
  gl: true
}, {
  value: 'star-open',
  alias: 17,
  label: 'M1.58,-2.16H6.66L2.54,0.83L4.12,5.66L0,2.67L-4.12,5.66L-2.54,0.83L-6.66,-2.16H-1.58L0,-7Z',
  fill: 'none',
  gl: true
}, {
  value: 'hexagram',
  label: 'M-3.8,0l-1.9,-3.3h3.8l1.9,-3.3l1.9,3.3h3.8l-1.9,3.3l1.9,3.3h-3.8l-1.9,3.3l-1.9,-3.3h-3.8Z'
}, {
  value: 'hexagram-open',
  label: 'M-3.8,0l-1.9,-3.3h3.8l1.9,-3.3l1.9,3.3h3.8l-1.9,3.3l1.9,3.3h-3.8l-1.9,3.3l-1.9,-3.3h-3.8Z',
  fill: 'none'
}, {
  value: 'star-triangle-up',
  label: 'M-6.93,4A 20,20 0 0 1 6.93,4A 20,20 0 0 1 0,-8A 20,20 0 0 1 -6.93,4Z'
}, {
  value: 'star-triangle-up-open',
  label: 'M-6.93,4A 20,20 0 0 1 6.93,4A 20,20 0 0 1 0,-8A 20,20 0 0 1 -6.93,4Z',
  fill: 'none'
}, {
  value: 'star-triangle-down',
  label: 'M6.93,-4A 20,20 0 0 1 -6.93,-4A 20,20 0 0 1 0,8A 20,20 0 0 1 6.93,-4Z'
}, {
  value: 'star-triangle-down-open',
  label: 'M6.93,-4A 20,20 0 0 1 -6.93,-4A 20,20 0 0 1 0,8A 20,20 0 0 1 6.93,-4Z',
  fill: 'none'
}, {
  value: 'star-square',
  label: 'M-5.5,-5.5A 10,10 0 0 1 -5.5,5.5A 10,10 0 0 1 5.5,5.5A 10,10 0 0 1 5.5,-5.5A 10,10 0 0 1 -5.5,-5.5Z'
}, {
  value: 'star-square-open',
  label: 'M-5.5,-5.5A 10,10 0 0 1 -5.5,5.5A 10,10 0 0 1 5.5,5.5A 10,10 0 0 1 5.5,-5.5A 10,10 0 0 1 -5.5,-5.5Z',
  fill: 'none'
}, {
  value: 'star-diamond',
  label: 'M-7,0A 9.5,9.5 0 0 1 0,7A 9.5,9.5 0 0 1 7,0A 9.5,9.5 0 0 1 0,-7A 9.5,9.5 0 0 1 -7,0Z'
}, {
  value: 'star-diamond-open',
  label: 'M-7,0A 9.5,9.5 0 0 1 0,7A 9.5,9.5 0 0 1 7,0A 9.5,9.5 0 0 1 0,-7A 9.5,9.5 0 0 1 -7,0Z',
  fill: 'none'
}, {
  value: 'diamond-tall',
  label: 'M0,7L3.5,0L0,-7L-3.5,0Z',
  gl: true
}, {
  value: 'diamond-tall-open',
  label: 'M0,7L3.5,0L0,-7L-3.5,0Z',
  fill: 'none',
  gl: true
}, { value: 'diamond-wide', label: 'M0,3.5L7,0L0,-3.5L-7,0Z' }, {
  value: 'diamond-wide-open',
  label: 'M0,3.5L7,0L0,-3.5L-7,0Z',
  fill: 'none'
}, { value: 'hourglass', label: 'M5,5H-5L5,-5H-5Z' }, { value: 'bowtie', label: 'M5,5V-5L-5,5V-5Z', gl: true }, {
  value: 'cross-thin-open',
  label: 'M0,7V-7M7,0H-7',
  fill: 'none',
  gl: true
}, {
  value: 'x-thin-open',
  label: 'M5,5L-5,-5M5,-5L-5,5',
  fill: 'none'
}, {
  value: 'asterisk-open',
  label: 'M0,6V-6M6,0H-6M4.25,4.25L-4.25,-4.25M4.25,-4.25L-4.25,4.25',
  fill: 'none',
  gl: true
}, {
  value: 'hash-open',
  label: 'M2.5,5V-5m-5,0V5M5,2.5H-5m0,-5H5',
  fill: 'none'
}, {
  value: 'hash-open-dot',
  label: 'M2.5,5V-5m-5,0V5M5,2.5H-5m0,-5H5M0,0.5L0.5,0L0,-0.5L-0.5,0Z',
  fill: 'none'
}, {
  value: 'y-up-open',
  label: 'M-6,4L0,0M6,4L0,0M0,-8L0,0',
  fill: 'none',
  gl: true
}, {
  value: 'y-down-open',
  label: 'M-6,-4L0,0M6,-4L0,0M0,8L0,0',
  fill: 'none',
  gl: true
}, {
  value: 'y-left-open',
  label: 'M4,6L0,0M4,-6L0,0M-8,0L0,0',
  fill: 'none'
}, {
  value: 'y-right-open',
  label: 'M-4,6L0,0M-4,-6L0,0M8,0L0,0',
  fill: 'none'
}, { value: 'line-ew-open', label: 'M7,0H-7', fill: 'none', gl: true }, { value: 'line-ns-open', label: 'M0,7V-7', fill: 'none', gl: true }, { value: 'line-ne-open', label: 'M5,-5L-5,5', fill: 'none' }, { value: 'line-nw-open', label: 'M5,5L-5,-5', fill: 'none' }];

var SymbolSelector = function (_Component) {
  _inherits(SymbolSelector, _Component);

  function SymbolSelector(props, context) {
    _classCallCheck(this, SymbolSelector);

    var _this = _possibleConstructorReturn(this, (SymbolSelector.__proto__ || Object.getPrototypeOf(SymbolSelector)).call(this, props, context));

    _this.setLocals(props, context);
    return _this;
  }

  _createClass(SymbolSelector, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps, nextContext) {
      this.setLocals(nextProps, nextContext);
    }
  }, {
    key: 'setLocals',
    value: function setLocals(props, context) {
      var fullContainer = props.fullContainer;
      var defaultContainer = context.defaultContainer;


      this.markerColor = (0, _nested_property2.default)(fullContainer, 'marker.color').get();
      this.borderWidth = (0, _nested_property2.default)(fullContainer, 'marker.line.width').get();

      if (this.markerColor === _constants.MULTI_VALUED) {
        this.markerColor = (0, _nested_property2.default)(defaultContainer, 'marker.color').get();
      }
      this.markerColor = Array.isArray(this.markerColor) ? _constants.COLORS.mutedBlue : this.markerColor;

      this.borderColor = this.markerColor;
      if (this.borderWidth) {
        this.borderColor = (0, _nested_property2.default)(fullContainer, 'marker.line.color').get();
        if (this.borderColor === _constants.MULTI_VALUED) {
          this.borderColor = (0, _nested_property2.default)(defaultContainer, 'marker.line.color').get();
        }
      }

      this.borderColor = Array.isArray(this.borderColor) ? _constants.COLORS.charcoal : this.borderColor;

      if (this.props.is3D) {
        this.symbolOptions = SYMBOLS.filter(function (option) {
          return option.threeD;
        });
      } else {
        this.symbolOptions = [].concat(SYMBOLS);
      }
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          fullValue = _props.fullValue,
          updatePlot = _props.updatePlot;

      return _react2.default.createElement(
        _Field2.default,
        this.props,
        _react2.default.createElement(_SymbolSelector2.default, {
          markerColor: this.markerColor,
          borderColor: this.borderColor,
          value: fullValue,
          onChange: updatePlot,
          symbolOptions: this.symbolOptions,
          backgroundDark: (0, _lib.tooLight)(this.markerColor)
        })
      );
    }
  }]);

  return SymbolSelector;
}(_react.Component);

SymbolSelector.propTypes = _extends({
  defaultValue: _propTypes2.default.string,
  fullValue: _propTypes2.default.any,
  updatePlot: _propTypes2.default.func
}, _Field2.default.propTypes);
SymbolSelector.contextTypes = {
  defaultContainer: _propTypes2.default.object
};

SymbolSelector.defaultProps = {
  showArrows: true
};

exports.default = (0, _lib.connectToContainer)(SymbolSelector);
//# sourceMappingURL=SymbolSelector.js.map

/***/ }),

/***/ "g5w3":
/*!**********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/connectAggregationToTransform.js ***!
  \**********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

exports.default = connectAggregationToTransform;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _lib = __webpack_require__(/*! ../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function connectAggregationToTransform(WrappedComponent) {
  var AggregationConnectedComponent = function (_Component) {
    _inherits(AggregationConnectedComponent, _Component);

    function AggregationConnectedComponent(props, context) {
      _classCallCheck(this, AggregationConnectedComponent);

      var _this = _possibleConstructorReturn(this, (AggregationConnectedComponent.__proto__ || Object.getPrototypeOf(AggregationConnectedComponent)).call(this, props, context));

      _this.updateAggregation = _this.updateAggregation.bind(_this);
      _this.setLocals(props, context);
      return _this;
    }

    _createClass(AggregationConnectedComponent, [{
      key: 'componentWillReceiveProps',
      value: function componentWillReceiveProps(nextProps, nextContext) {
        this.setLocals(nextProps, nextContext);
      }
    }, {
      key: 'setLocals',
      value: function setLocals(props, context) {
        var aggregationIndex = props.aggregationIndex;
        var container = context.container,
            fullContainer = context.fullContainer;


        var aggregations = container && container.aggregations || [];
        var fullAggregations = fullContainer.aggregations || [];
        this.container = aggregations[aggregationIndex];
        this.fullContainer = fullAggregations[aggregationIndex];
      }
    }, {
      key: 'getChildContext',
      value: function getChildContext() {
        var _this2 = this;

        return {
          getValObject: function getValObject(attr) {
            return !_this2.context.getValObject ? null : _this2.context.getValObject('aggregations[].' + attr);
          },
          updateContainer: this.updateAggregation,
          container: this.container,
          fullContainer: this.fullContainer
        };
      }
    }, {
      key: 'updateAggregation',
      value: function updateAggregation(update) {
        var newUpdate = {};
        var path = 'aggregations[' + this.props.aggregationIndex + ']';
        for (var key in update) {
          newUpdate[path + '.' + key] = update[key];
        }
        newUpdate[path + '.target'] = this.fullContainer.target;
        newUpdate[path + '.enabled'] = true;
        this.context.updateContainer(newUpdate);
      }
    }, {
      key: 'render',
      value: function render() {
        return _react2.default.createElement(WrappedComponent, this.props);
      }
    }]);

    return AggregationConnectedComponent;
  }(_react.Component);

  AggregationConnectedComponent.displayName = 'AggregationConnected' + (0, _lib.getDisplayName)(WrappedComponent);

  AggregationConnectedComponent.propTypes = {
    aggregationIndex: _propTypes2.default.number.isRequired
  };

  AggregationConnectedComponent.contextTypes = {
    container: _propTypes2.default.object,
    fullContainer: _propTypes2.default.object,
    data: _propTypes2.default.array,
    onUpdate: _propTypes2.default.func,
    updateContainer: _propTypes2.default.func,
    getValObject: _propTypes2.default.func
  };

  AggregationConnectedComponent.childContextTypes = {
    updateContainer: _propTypes2.default.func,
    deleteContainer: _propTypes2.default.func,
    container: _propTypes2.default.object,
    fullContainer: _propTypes2.default.object,
    getValObject: _propTypes2.default.func
  };

  var plotly_editor_traits = WrappedComponent.plotly_editor_traits;

  AggregationConnectedComponent.plotly_editor_traits = plotly_editor_traits;

  return AggregationConnectedComponent;
}
//# sourceMappingURL=connectAggregationToTransform.js.map

/***/ }),

/***/ "g8L2":
/*!**********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeBarIcon.js ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeBarIcon = function TraceTypeBarIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement('path', { fill: 'none', d: 'M0 0h46v46H0z' }),
        _react2.default.createElement('path', { fill: '#25fdfc', d: 'M7 28h6v12H7z' }),
        _react2.default.createElement('path', { fill: '#1d9bfb', d: 'M32 28h6v12h-6zM15 10h6v30h-6z' }),
        _react2.default.createElement('path', { fill: '#25fdfc', d: 'M24 20h6v20h-6z' })
    );
};

exports.default = TraceTypeBarIcon;

/***/ }),

/***/ "g9U9":
/*!********************************************!*\
  !*** ./node_modules/public-encrypt/xor.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = function xor (a, b) {
  var len = a.length
  var i = -1
  while (++i < len) {
    a[i] ^= b[i]
  }
  return a
}


/***/ }),

/***/ "gAjT":
/*!************************************************************!*\
  !*** ./node_modules/@phosphor/datagrid/lib/renderermap.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
var signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
/**
 * An object which manages a mapping of cell renderers.
 *
 * #### Notes
 * This class is used to configure cell renderers for a data grid.
 */
var RendererMap = (function () {
    /**
     * Construct a new renderer map.
     *
     * @param options - The options for initializing the map.
     */
    function RendererMap(options) {
        if (options === void 0) { options = {}; }
        this._entries = [];
        this._changed = new signaling_1.Signal(this);
        this._renderers = Object.create(null);
        this._ranks = Private.createRankMap(options.priority || []);
    }
    Object.defineProperty(RendererMap.prototype, "changed", {
        /**
         * A signal emitted when the map contents are changed.
         */
        get: function () {
            return this._changed;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Get the cell renderer to use for the given region and metadata.
     *
     * @param region - The cell region of interest.
     *
     * @param metadata - The data model metadata for the region.
     *
     * @returns The best matching cell renderer, or `undefined`.
     *
     * #### Notes
     * Non-string metadata values are ignored.
     */
    RendererMap.prototype.get = function (region, metadata) {
        // Iterate through the map entries to find the best cell renderer.
        for (var i = 0, n = this._entries.length; i < n; ++i) {
            // Create the key for the current entry.
            var key = this._entries[i].createKey(metadata);
            // Skip the entry if no key could be generated.
            if (key === undefined) {
                continue;
            }
            // Prepend the region to the key.
            key = region + "|" + key;
            // Look up the renderer for the generated key.
            var renderer = this._renderers[key];
            // If the renderer exists, it is the best match.
            if (renderer !== undefined) {
                return renderer;
            }
        }
        // Return `undefined` to indicate no match.
        return undefined;
    };
    /**
     * Set the cell renderer for a particular region and metadata.
     *
     * @param region - The cell region of interest.
     *
     * @param metadata - The metadata to match against the model.
     *
     * @param renderer - The cell renderer to set in the map.
     *
     * #### Notes
     * The keys and values in the supplied metadata are matched against
     * the metadata supplied by the data model. The given metadata must
     * be an exact matching subset of the model metadata in order for
     * there to be a match.
     *
     * Matches are ranked according the number of matched values, with
     * ties broken based on the priorty order given to the constructor.
     *
     * Non-string metadata values are ignored.
     */
    RendererMap.prototype.set = function (region, metadata, renderer) {
        var _this = this;
        // Create a new map entry for the metadata.
        var entry = Private.MapEntry.create(metadata, this._ranks);
        // Find the insert location for the entry.
        var i = algorithm_1.ArrayExt.lowerBound(this._entries, entry, function (a, b) {
            return Private.MapEntry.cmp(a, b, _this._ranks);
        });
        // Add the entry to the array if needed.
        if (i === this._entries.length) {
            this._entries.push(entry);
        }
        else if (!Private.MapEntry.equal(entry, this._entries[i])) {
            algorithm_1.ArrayExt.insert(this._entries, i, entry);
        }
        // Create the key for the entry.
        var key = entry.createKey(metadata);
        // Prepend the region to the key.
        key = region + "|" + key;
        // Add the new renderer to the map.
        this._renderers[key] = renderer;
        // Emit the changed signal.
        this._changed.emit(undefined);
    };
    /**
     * Remove all custom cell renderers from the map.
     */
    RendererMap.prototype.clear = function () {
        this._entries = [];
        this._renderers = Object.create(null);
        this._changed.emit(undefined);
    };
    return RendererMap;
}());
exports.RendererMap = RendererMap;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * Create a rank map from a priority key array.
     */
    function createRankMap(priority) {
        var ranks = Object.create(null);
        for (var i = 0, n = priority.length; i < n; ++i) {
            ranks[priority[i]] = i;
        }
        return ranks;
    }
    Private.createRankMap = createRankMap;
    /**
     * An entry in a cell renderer map.
     */
    var MapEntry = (function () {
        /**
         * Construct a new map entry from ordered key names.
         */
        function MapEntry(keys) {
            this._keys = keys;
        }
        /**
         * Create a new map entry.
         *
         * @param metadata - The metadata which will be used as the key
         *  for matching against the model metadata.
         *
         * @param ranks - The priority ranks for the metadata keys.
         *
         * @returns A new map entry for the given metadata key.
         */
        MapEntry.create = function (metadata, ranks) {
            // Extra the string-valued keys from the metadata.
            var keys = [];
            for (var key in metadata) {
                if (typeof metadata[key] === 'string') {
                    keys.push(key);
                }
            }
            // Sort the keys based on rank and locale.
            keys.sort(function (k1, k2) {
                var r1 = ranks[k1];
                var r2 = ranks[k2];
                if (r1 !== undefined && r2 !== undefined) {
                    return r1 - r2;
                }
                if (r2 === undefined) {
                    return -1;
                }
                if (r1 === undefined) {
                    return 1;
                }
                return k1.localeCompare(k2);
            });
            // Create an return a new map entry.
            return new MapEntry(keys);
        };
        /**
         * Compare two map entries for relative ordering.
         *
         * @param a - The LHS map entry.
         *
         * @param b - The RHS map entry.
         *
         * @param ranks - The priority ranks for the metadata keys.
         *
         * @returns `< 0` if `a < b`, `> 0` if `a > b`, or `0` if `a = b`.
         */
        MapEntry.cmp = function (a, b, ranks) {
            // Compare first based on key length.
            var n1 = a._keys.length;
            var n2 = b._keys.length;
            if (n1 !== n2) {
                return n2 - n1;
            }
            // Compare next based on key content.
            for (var i = 0; i < n1; ++i) {
                // Look up the current keys.
                var k1 = a._keys[i];
                var k2 = b._keys[i];
                // Skip if the keys are equal.
                if (k1 === k2) {
                    continue;
                }
                // Look up the current ranks.
                var r1 = ranks[k1];
                var r2 = ranks[k2];
                // Use rank order if possible.
                if (r1 !== undefined && r2 !== undefined) {
                    return r1 - r2;
                }
                // Handle the case of one key having rank.
                if (r2 === undefined) {
                    return -1;
                }
                if (r1 === undefined) {
                    return 1;
                }
                // Fall back to locale order.
                return k1.localeCompare(k2);
            }
            // Otherwise, the map entries are equivalent.
            return 0;
        };
        /**
         * Compare two map entries for equality.
         *
         * @param a - The LHS map entry.
         *
         * @param b - The RHS map entry.
         *
         * @returns Whether the two entries are functionally equivalent.
         */
        MapEntry.equal = function (a, b) {
            // Bail early if the keys have different length.
            if (a._keys.length !== b._keys.length) {
                return false;
            }
            // Test each key for equality.
            for (var i = 0, n = a._keys.length; i < n; ++i) {
                if (a._keys[i] !== b._keys[i]) {
                    return false;
                }
            }
            // Otherwise, the entries are equivalent.
            return true;
        };
        /**
         * Create the renderer map key for a metadata object.
         *
         * @param metadata - The metadata supplied by the data model.
         *
         * @returns The key for the metadata object, or `undefined` if the
         *   metadata is not a valid candidate match for the entry.
         */
        MapEntry.prototype.createKey = function (metadata) {
            // Set up the result variable.
            var result = '';
            // Loop over each key and create the value pairs.
            for (var i = 0, n = this._keys.length; i < n; ++i) {
                // Look up metadata value for the key.
                var key = this._keys[i];
                var value = metadata[key];
                // Bail if the metadata value is not a string.
                if (typeof value !== 'string') {
                    return undefined;
                }
                // Add the key/value pair to the result.
                result += "{" + key + ": " + value + "}";
            }
            // Return the final key.
            return result;
        };
        return MapEntry;
    }());
    Private.MapEntry = MapEntry;
})(Private || (Private = {}));


/***/ }),

/***/ "gB9I":
/*!*********************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/RangeSelectorAccordion.js ***!
  \*********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _PlotlyFold = __webpack_require__(/*! ./PlotlyFold */ "mQPs");

var _PlotlyFold2 = _interopRequireDefault(_PlotlyFold);

var _PlotlyPanel = __webpack_require__(/*! ./PlotlyPanel */ "54u7");

var _PlotlyPanel2 = _interopRequireDefault(_PlotlyPanel);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var RangeSelectorFold = (0, _lib.connectRangeSelectorToAxis)(_PlotlyFold2.default);

var RangeSelectorAccordion = function (_Component) {
  _inherits(RangeSelectorAccordion, _Component);

  function RangeSelectorAccordion() {
    _classCallCheck(this, RangeSelectorAccordion);

    return _possibleConstructorReturn(this, (RangeSelectorAccordion.__proto__ || Object.getPrototypeOf(RangeSelectorAccordion)).apply(this, arguments));
  }

  _createClass(RangeSelectorAccordion, [{
    key: 'render',
    value: function render() {
      if (!this.context.fullContainer || !this.context.fullContainer.rangeselector || !this.context.fullContainer.rangeselector.visible ||
      // next line checks for "all" case
      this.context.fullContainer._axisGroup === 0) {
        return null;
      }

      var _context = this.context,
          _context$fullContaine = _context.fullContainer.rangeselector.buttons,
          buttons = _context$fullContaine === undefined ? [] : _context$fullContaine,
          _ = _context.localize,
          meta = _context.layout;
      var children = this.props.children;


      var content = buttons.length && buttons.map(function (btn, i) {
        return _react2.default.createElement(
          RangeSelectorFold,
          {
            key: i,
            rangeselectorIndex: i,
            name: (0, _lib.getParsedTemplateString)(btn.label, meta),
            canDelete: true
          },
          children
        );
      });

      var addAction = {
        label: _('Button'),
        handler: function handler(context) {
          var fullContainer = context.fullContainer,
              updateContainer = context.updateContainer;

          if (updateContainer) {
            var rangeselectorIndex = Array.isArray(fullContainer.rangeselector.buttons) ? fullContainer.rangeselector.buttons.length : 0;

            updateContainer(_defineProperty({}, 'rangeselector.buttons[' + rangeselectorIndex + ']', {}));
          }
        }
      };

      return _react2.default.createElement(
        _PlotlyPanel2.default,
        { addAction: addAction },
        content ? content : null
      );
    }
  }]);

  return RangeSelectorAccordion;
}(_react.Component);

RangeSelectorAccordion.contextTypes = {
  fullContainer: _propTypes2.default.object,
  localize: _propTypes2.default.func,
  layout: _propTypes2.default.object
};

RangeSelectorAccordion.propTypes = {
  children: _propTypes2.default.node
};

RangeSelectorAccordion.plotly_editor_traits = {
  no_visibility_forcing: true
};

exports.default = RangeSelectorAccordion;
//# sourceMappingURL=RangeSelectorAccordion.js.map

/***/ }),

/***/ "gBRr":
/*!*********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/CheckboxGroup.js ***!
  \*********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _classnames = __webpack_require__(/*! classnames */ "TSYQ");

var _classnames2 = _interopRequireDefault(_classnames);

var _plotlyIcons = __webpack_require__(/*! plotly-icons */ "hwSx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var CheckboxGroup = function (_Component) {
  _inherits(CheckboxGroup, _Component);

  function CheckboxGroup(props) {
    _classCallCheck(this, CheckboxGroup);

    var _this = _possibleConstructorReturn(this, (CheckboxGroup.__proto__ || Object.getPrototypeOf(CheckboxGroup)).call(this, props));

    _this.state = { options: _this.props.options };
    _this.handleChange = _this.handleChange.bind(_this);
    return _this;
  }

  _createClass(CheckboxGroup, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      this.setState({ options: nextProps.options });
    }
  }, {
    key: 'handleChange',
    value: function handleChange(i) {
      var newOptions = this.props.options.slice();
      newOptions[i] = Object.assign(newOptions[i], {
        checked: !newOptions[i].checked
      });
      this.props.onChange(newOptions);
    }
  }, {
    key: 'renderOptions',
    value: function renderOptions() {
      var _this2 = this;

      return this.state.options.map(function (option, i) {
        var checkClass = (0, _classnames2.default)(['checkbox__check', 'icon'], {
          'checkbox__check--checked': option.checked
        });

        var itemClass = (0, _classnames2.default)('checkbox__item', {
          'checkbox__item--vertical': _this2.props.orientation === 'vertical',
          'checkbox__item--horizontal': _this2.props.orientation === 'horizontal'
        });

        return _react2.default.createElement(
          'div',
          { key: i, className: itemClass },
          _react2.default.createElement(
            'div',
            {
              className: 'checkbox__box' + (option.checked ? ' checkbox__box--checked' : ''),
              onClick: function onClick() {
                return _this2.handleChange(i);
              }
            },
            option.checked && _react2.default.createElement(
              'div',
              { className: checkClass },
              _react2.default.createElement(_plotlyIcons.CheckIcon, null)
            )
          ),
          _react2.default.createElement(
            'div',
            { className: 'checkbox__label', onClick: function onClick() {
                return _this2.handleChange(i);
              } },
            option.label
          )
        );
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var boxClass = (0, _classnames2.default)('checkbox__group', this.props.className, {
        checkbox__group_horizontal: this.props.orientation === 'horizontal'
      });

      return _react2.default.createElement(
        'div',
        { className: boxClass },
        this.renderOptions()
      );
    }
  }]);

  return CheckboxGroup;
}(_react.Component);

CheckboxGroup.propTypes = {
  options: _propTypes2.default.arrayOf(_propTypes2.default.shape({
    label: _propTypes2.default.string.isRequired,
    value: _propTypes2.default.string.isRequired,
    checked: _propTypes2.default.bool.isRequired
  })).isRequired,
  onChange: _propTypes2.default.func,
  className: _propTypes2.default.string,
  orientation: _propTypes2.default.string
};

CheckboxGroup.defaultProps = {
  className: ''
};

exports.default = CheckboxGroup;
//# sourceMappingURL=CheckboxGroup.js.map

/***/ }),

/***/ "gC0g":
/*!*********************************************************************!*\
  !*** ./node_modules/@jupyterlab/imageviewer-extension/lib/index.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const application_1 = __webpack_require__(/*! @jupyterlab/application */ "FkFl");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const imageviewer_1 = __webpack_require__(/*! @jupyterlab/imageviewer */ "GbqW");
/**
 * The command IDs used by the image widget plugin.
 */
var CommandIDs;
(function (CommandIDs) {
    CommandIDs.resetImage = 'imageviewer:reset-image';
    CommandIDs.zoomIn = 'imageviewer:zoom-in';
    CommandIDs.zoomOut = 'imageviewer:zoom-out';
    CommandIDs.flipHorizontal = 'imageviewer:flip-horizontal';
    CommandIDs.flipVertical = 'imageviewer:flip-vertical';
    CommandIDs.rotateClockwise = 'imageviewer:rotate-clockwise';
    CommandIDs.rotateCounterclockwise = 'imageviewer:rotate-counterclockwise';
    CommandIDs.invertColors = 'imageviewer:invert-colors';
})(CommandIDs || (CommandIDs = {}));
/**
 * The list of file types for images.
 */
const FILE_TYPES = ['png', 'gif', 'jpeg', 'svg', 'bmp', 'ico', 'xbm', 'tiff'];
/**
 * The name of the factory that creates image widgets.
 */
const FACTORY = 'Image';
/**
 * The image file handler extension.
 */
const plugin = {
    activate,
    id: '@jupyterlab/imageviewer-extension:plugin',
    provides: imageviewer_1.IImageTracker,
    requires: [apputils_1.ICommandPalette, application_1.ILayoutRestorer],
    autoStart: true
};
/**
 * Export the plugin as default.
 */
exports.default = plugin;
/**
 * Activate the image widget extension.
 */
function activate(app, palette, restorer) {
    const namespace = 'image-widget';
    const factory = new imageviewer_1.ImageViewerFactory({
        name: FACTORY,
        modelName: 'base64',
        fileTypes: FILE_TYPES,
        defaultFor: FILE_TYPES,
        readOnly: true
    });
    const tracker = new apputils_1.InstanceTracker({
        namespace
    });
    // Handle state restoration.
    restorer.restore(tracker, {
        command: 'docmanager:open',
        args: widget => ({ path: widget.context.path, factory: FACTORY }),
        name: widget => widget.context.path
    });
    app.docRegistry.addWidgetFactory(factory);
    factory.widgetCreated.connect((sender, widget) => {
        // Notify the instance tracker if restore data needs to update.
        widget.context.pathChanged.connect(() => {
            tracker.save(widget);
        });
        tracker.add(widget);
        const types = app.docRegistry.getFileTypesForPath(widget.context.path);
        if (types.length > 0) {
            widget.title.iconClass = types[0].iconClass;
            widget.title.iconLabel = types[0].iconLabel;
        }
    });
    addCommands(app, tracker);
    const category = 'Image Viewer';
    [
        CommandIDs.zoomIn,
        CommandIDs.zoomOut,
        CommandIDs.resetImage,
        CommandIDs.rotateClockwise,
        CommandIDs.rotateCounterclockwise,
        CommandIDs.flipHorizontal,
        CommandIDs.flipVertical,
        CommandIDs.invertColors
    ].forEach(command => {
        palette.addItem({ command, category });
    });
    return tracker;
}
/**
 * Add the commands for the image widget.
 */
function addCommands(app, tracker) {
    const { commands } = app;
    /**
     * Whether there is an active image viewer.
     */
    function isEnabled() {
        return (tracker.currentWidget !== null &&
            tracker.currentWidget === app.shell.currentWidget);
    }
    commands.addCommand('imageviewer:zoom-in', {
        execute: zoomIn,
        label: 'Zoom In',
        isEnabled
    });
    commands.addCommand('imageviewer:zoom-out', {
        execute: zoomOut,
        label: 'Zoom Out',
        isEnabled
    });
    commands.addCommand('imageviewer:reset-image', {
        execute: resetImage,
        label: 'Reset Image',
        isEnabled
    });
    commands.addCommand('imageviewer:rotate-clockwise', {
        execute: rotateClockwise,
        label: 'Rotate Clockwise',
        isEnabled
    });
    commands.addCommand('imageviewer:rotate-counterclockwise', {
        execute: rotateCounterclockwise,
        label: 'Rotate Counterclockwise',
        isEnabled
    });
    commands.addCommand('imageviewer:flip-horizontal', {
        execute: flipHorizontal,
        label: 'Flip image horizontally',
        isEnabled
    });
    commands.addCommand('imageviewer:flip-vertical', {
        execute: flipVertical,
        label: 'Flip image vertically',
        isEnabled
    });
    commands.addCommand('imageviewer:invert-colors', {
        execute: invertColors,
        label: 'Invert Colors',
        isEnabled
    });
    function zoomIn() {
        const widget = tracker.currentWidget.content;
        if (widget) {
            widget.scale = widget.scale > 1 ? widget.scale + 0.5 : widget.scale * 2;
        }
    }
    function zoomOut() {
        const widget = tracker.currentWidget.content;
        if (widget) {
            widget.scale = widget.scale > 1 ? widget.scale - 0.5 : widget.scale / 2;
        }
    }
    function resetImage() {
        const widget = tracker.currentWidget.content;
        if (widget) {
            widget.scale = 1;
            widget.colorinversion = 0;
            widget.resetRotationFlip();
        }
    }
    function rotateClockwise() {
        const widget = tracker.currentWidget.content;
        if (widget) {
            widget.rotateClockwise();
        }
    }
    function rotateCounterclockwise() {
        const widget = tracker.currentWidget.content;
        if (widget) {
            widget.rotateCounterclockwise();
        }
    }
    function flipHorizontal() {
        const widget = tracker.currentWidget.content;
        if (widget) {
            widget.flipHorizontal();
        }
    }
    function flipVertical() {
        const widget = tracker.currentWidget.content;
        if (widget) {
            widget.flipVertical();
        }
    }
    function invertColors() {
        const widget = tracker.currentWidget.content;
        if (widget) {
            widget.colorinversion += 1;
            widget.colorinversion %= 2;
        }
    }
}
exports.addCommands = addCommands;


/***/ }),

/***/ "gCq4":
/*!******************************************!*\
  !*** ./node_modules/lodash/_stackGet.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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);
}

module.exports = stackGet;


/***/ }),

/***/ "gFfm":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_arrayEach.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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;
}

module.exports = arrayEach;


/***/ }),

/***/ "gHr8":
/*!*********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotMapLineIcon.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotMapLineIcon = function PlotMapLineIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M31.625 8.813s.125 0 0 0c.125 0 0-.125 0 0zm-4.312 16.25c.313-.125.438-.375.563-.688-.125 0 0 .188-.125.188 0 .25-.438.25-.438.5zm5.062-17.438c-.125 0-.125.125-.25 0v-.313h-.25c0-.375-.25-.625-.25-1.063-.188 0-.313 0-.313-.125l-.25.25c-.125 0 0-.125-.125-.125-.25.438-.375.938-.25 1.375-.125.125-.125.375-.125.5h-.313c0 .125 0 .25-.125.25-.375.188-.813.313-1.188.313-.125 0-.375 0-.563.125-.125.125-.25.375-.375.5s-.25.125-.25.313c.125.125.125.25.125.375-.438.688-1.063.375-1.625.688 0 .125.125.25.125.375-.5.688-1.188 1.063-1.813 1.5-.188 0-.438-.188-.563-.313 0-.25.25-.5.375-.625 0-.438-.125-.813-.375-1.063l-.375.375c-.188 0-.188-.125-.188-.25.438-.125.188-.813.313-.938-.125 0-.125-.125-.125-.125-.438 0-.688-.438-.938 0 0 .125.125 0 .125.125-.125 0-.125 0-.25.125 0 .25.125.375-.188.375 0-.125.188-.25 0-.375-.25.375-.375.938-.375 1.438.375.438.25 1.063-.125 1.5l-.125.125c-.813-.688-.313-2.125-.125-2.938-.188.25-.313.375-.563.563.25-.563.375-.938.563-1.25.25 0 .625-.125.938-.25h.75c-.125 0-.25-.125-.125-.375h-.375v-.313c-.438.188-.938.313-1.375.313 0-.313-.25-.313-.5-.313h-.125c.125-.25.125-.375.375-.5-.25 0-.5.125-.625.375-.313.125-.563.313-.813.438 0-.125-.313 0-.313-.125 0 0 .188-.188.188-.313-.313.125-.438.125-.688.125.25-.25.375-.375.688-.625.25-.125.5-.313.625-.438-.25 0-.5 0-.625-.125-.188.125-.438.125-.563 0l-.125-.125c-.25-.125-.563-.125-.938-.125-.125-.125-.25-.125-.563-.125-.125-.125 0-.563-.25-.563-.125 0 0 .313-.125.313-4.813 0-9.625-.563-14.25-1.875.125.625.125.938.125 1.188-.125 0-.25-.125-.125-.25-.125 0-.125 0-.25.125-.313-.125-.563-.313-.813-.438-.125.438 0 .813.125 1.25h-.125s0 .125.125.125c-.125.125-.25.25 0 .375-.125 0-.125.125-.125.125-.438.813-.688 1.625-1.188 2.25 0 .188 0 .438-.188.563 0 .563-.125 1.063-.375 1.438.375.313 0 .813.125 1.125.125.125.25.375.25.625 0 .125 0 .438.188.438-.188.25 0 .625.25.75 0 .188-.125.188-.125.313 0 .5.5.75.5 1.313v.563c.438.125.813.375 1.188.625v.125c.438.125.688.563.563 1.063.375.188.938.313 1.438.313 0 .125-.125 0-.125.125.563.25 1.063.625 1.625 1.063.813.375 1.563.5 2.5.688 0-.188 0-.313.188-.438.375.125.75.125 1.063.125.25.438.5.688.75.938.313.125.438.438.438.688.25.375.5.688.938.813.125-.313.375-.563.625-.688.688 0 1.375.688 1.375 1.313.25.125.25.563.5.688-.125.938.938 1.188 1.5 1.313-.125-.5-.125-1.063 0-1.438.625-.438 1.313-.813 1.875-1.188.625-.313 1.313-.313 2-.125 0-.313-.313 0-.313-.188.313-.25.438.188.688.188v.125c.125.125.25.125.375.125.188-.125.188-.125.313-.125.125.125-.125.125 0 .125.125-.125.25-.25.25-.438 0 .188.5.438.5.188-.125 0-.25-.188-.5-.313.125 0 .25-.25.125-.375-.125.125-.125.125-.25.125.125-.375.5-.375 1.063-.375 0 0 0-.313.125-.313s.125.313 0 .313c.563-.438 1.313-.313 1.875.25.25 0 .5-.125.688-.438.625 0 .5.563 1.063.563.25.25 0 .938.25 1.188v-.25h.125c0 .125-.125.25-.125.25.125.25.375.563.5.688l.188-.125c.125.125.125.25.125.375.25 0 .5.25.5.563.125-.125.25-.125.563-.125.125-.813-.125-1.625-.563-2.313 0 0 .125 0 .125-.125-.625-.5-1.063-1.563-.75-2.5.125-.188.25-.438.25-.563.25-.125.5-.375.625-.688 0-.375.188-.625.563-.625h.125c0-.813.938-.563.938-1.063-.125.125-.25.125-.375 0 .125.125.25-.125.125-.313.125.188.375 0 .5-.125v-.125h-.25c.125 0 .25 0 .25-.125-.125-.25-.25-.563-.375-.813h-.25c.125-.125-.125-.25-.125-.375h.125a.657.657 0 0 0-.313-.563c.188 0 0-.125.188-.125-.313-.125-.313-.813 0-.938-.188.125.125.25-.188.563.188 0 0 0 .188.25.125.125.25.125.25.25v-.25c.375.125 0 .688.25.938.25-.563.25-.938.25-1.5-.25-.125-.375-.25-.375-.5.125.25.25.375.375.375v.125c.438-.375.563-.75.438-1.313h-.125c.125 0 0-.125.125-.125v-.125c.375-.438.938-.688 1.438-.938 0-.125 0-.125.125-.25 0 .125 0 .125-.125.25.125-.125.25-.25.563-.25 0-.125 0-.313-.313-.313.188.188.188.188.188.313-.313.25-.438-.438-.688-.313 0-.375 0-.75.125-1.188.25 0 .375-.125.563-.25v-.125-.25s.125 0 .125.125c.125 0 .25-.125.25-.313 0 .188 0 .188.125.188s-.125-.188-.125-.313c.25.125.813-.375.375-.625zm-7.812 9.313h-2.688v-.813l-7.188.563v.938h-2.688v-2l-4.813-4.688h-2V8.25h2.688v2l4.813 4.688h2v.813l7.188-.438v-.938h2.688z' })
    );
};

exports.default = PlotMapLineIcon;

/***/ }),

/***/ "gQ7D":
/*!***********************************************!*\
  !*** ./node_modules/ajv/lib/compile/equal.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/*eslint complexity: 0*/

module.exports = function equal(a, b) {
  if (a === b) return true;

  var arrA = Array.isArray(a)
    , arrB = Array.isArray(b)
    , i;

  if (arrA && arrB) {
    if (a.length != b.length) return false;
    for (i = 0; i < a.length; i++)
      if (!equal(a[i], b[i])) return false;
    return true;
  }

  if (arrA != arrB) return false;

  if (a && b && typeof a === 'object' && typeof b === 'object') {
    var keys = Object.keys(a);
    if (keys.length !== Object.keys(b).length) return false;

    var dateA = a instanceof Date
      , dateB = b instanceof Date;
    if (dateA && dateB) return a.getTime() == b.getTime();
    if (dateA != dateB) return false;

    var regexpA = a instanceof RegExp
      , regexpB = b instanceof RegExp;
    if (regexpA && regexpB) return a.toString() == b.toString();
    if (regexpA != regexpB) return false;

    for (i = 0; i < keys.length; i++)
      if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;

    for (i = 0; i < keys.length; i++)
      if(!equal(a[keys[i]], b[keys[i]])) return false;

    return true;
  }

  return false;
};


/***/ }),

/***/ "gTk9":
/*!*****************************************************!*\
  !*** ./node_modules/react-tabs/esm/helpers/uuid.js ***!
  \*****************************************************/
/*! exports provided: default, reset */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return uuid; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reset", function() { return reset; });
// Get a universally unique identifier
var count = 0;
function uuid() {
  return "react-tabs-" + count++;
}
function reset() {
  count = 0;
}

/***/ }),

/***/ "gVVK":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/sl.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


function processRelativeTime(number, withoutSuffix, key, isFuture) {
    var result = number + ' ';
    switch (key) {
        case 's':
            return withoutSuffix || isFuture ? 'nekaj sekund' : 'nekaj sekundami';
        case 'ss':
            if (number === 1) {
                result += withoutSuffix ? 'sekundo' : 'sekundi';
            } else if (number === 2) {
                result += withoutSuffix || isFuture ? 'sekundi' : 'sekundah';
            } else if (number < 5) {
                result += withoutSuffix || isFuture ? 'sekunde' : 'sekundah';
            } else {
                result += withoutSuffix || isFuture ? 'sekund' : 'sekund';
            }
            return result;
        case 'm':
            return withoutSuffix ? 'ena minuta' : 'eno minuto';
        case 'mm':
            if (number === 1) {
                result += withoutSuffix ? 'minuta' : 'minuto';
            } else if (number === 2) {
                result += withoutSuffix || isFuture ? 'minuti' : 'minutama';
            } else if (number < 5) {
                result += withoutSuffix || isFuture ? 'minute' : 'minutami';
            } else {
                result += withoutSuffix || isFuture ? 'minut' : 'minutami';
            }
            return result;
        case 'h':
            return withoutSuffix ? 'ena ura' : 'eno uro';
        case 'hh':
            if (number === 1) {
                result += withoutSuffix ? 'ura' : 'uro';
            } else if (number === 2) {
                result += withoutSuffix || isFuture ? 'uri' : 'urama';
            } else if (number < 5) {
                result += withoutSuffix || isFuture ? 'ure' : 'urami';
            } else {
                result += withoutSuffix || isFuture ? 'ur' : 'urami';
            }
            return result;
        case 'd':
            return withoutSuffix || isFuture ? 'en dan' : 'enim dnem';
        case 'dd':
            if (number === 1) {
                result += withoutSuffix || isFuture ? 'dan' : 'dnem';
            } else if (number === 2) {
                result += withoutSuffix || isFuture ? 'dni' : 'dnevoma';
            } else {
                result += withoutSuffix || isFuture ? 'dni' : 'dnevi';
            }
            return result;
        case 'M':
            return withoutSuffix || isFuture ? 'en mesec' : 'enim mesecem';
        case 'MM':
            if (number === 1) {
                result += withoutSuffix || isFuture ? 'mesec' : 'mesecem';
            } else if (number === 2) {
                result += withoutSuffix || isFuture ? 'meseca' : 'mesecema';
            } else if (number < 5) {
                result += withoutSuffix || isFuture ? 'mesece' : 'meseci';
            } else {
                result += withoutSuffix || isFuture ? 'mesecev' : 'meseci';
            }
            return result;
        case 'y':
            return withoutSuffix || isFuture ? 'eno leto' : 'enim letom';
        case 'yy':
            if (number === 1) {
                result += withoutSuffix || isFuture ? 'leto' : 'letom';
            } else if (number === 2) {
                result += withoutSuffix || isFuture ? 'leti' : 'letoma';
            } else if (number < 5) {
                result += withoutSuffix || isFuture ? 'leta' : 'leti';
            } else {
                result += withoutSuffix || isFuture ? 'let' : 'leti';
            }
            return result;
    }
}

var sl = moment.defineLocale('sl', {
    months : 'januar_februar_marec_april_maj_junij_julij_avgust_september_oktober_november_december'.split('_'),
    monthsShort : 'jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.'.split('_'),
    monthsParseExact: true,
    weekdays : 'nedelja_ponedeljek_torek_sreda_četrtek_petek_sobota'.split('_'),
    weekdaysShort : 'ned._pon._tor._sre._čet._pet._sob.'.split('_'),
    weekdaysMin : 'ne_po_to_sr_če_pe_so'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'H:mm',
        LTS : 'H:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D. MMMM YYYY',
        LLL : 'D. MMMM YYYY H:mm',
        LLLL : 'dddd, D. MMMM YYYY H:mm'
    },
    calendar : {
        sameDay  : '[danes ob] LT',
        nextDay  : '[jutri ob] LT',

        nextWeek : function () {
            switch (this.day()) {
                case 0:
                    return '[v] [nedeljo] [ob] LT';
                case 3:
                    return '[v] [sredo] [ob] LT';
                case 6:
                    return '[v] [soboto] [ob] LT';
                case 1:
                case 2:
                case 4:
                case 5:
                    return '[v] dddd [ob] LT';
            }
        },
        lastDay  : '[včeraj ob] LT',
        lastWeek : function () {
            switch (this.day()) {
                case 0:
                    return '[prejšnjo] [nedeljo] [ob] LT';
                case 3:
                    return '[prejšnjo] [sredo] [ob] LT';
                case 6:
                    return '[prejšnjo] [soboto] [ob] LT';
                case 1:
                case 2:
                case 4:
                case 5:
                    return '[prejšnji] dddd [ob] LT';
            }
        },
        sameElse : 'L'
    },
    relativeTime : {
        future : 'čez %s',
        past   : 'pred %s',
        s      : processRelativeTime,
        ss     : processRelativeTime,
        m      : processRelativeTime,
        mm     : processRelativeTime,
        h      : processRelativeTime,
        hh     : processRelativeTime,
        d      : processRelativeTime,
        dd     : processRelativeTime,
        M      : processRelativeTime,
        MM     : processRelativeTime,
        y      : processRelativeTime,
        yy     : processRelativeTime
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return sl;

})));


/***/ }),

/***/ "gWRK":
/*!*********************************************!*\
  !*** ./node_modules/fbjs/lib/nullthrows.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * 
 */

var nullthrows = function nullthrows(x) {
  if (x != null) {
    return x;
  }
  throw new Error("Got unexpected null or undefined");
};

module.exports = nullthrows;

/***/ }),

/***/ "gYcd":
/*!**************************************************************!*\
  !*** ./node_modules/react-json-tree/lib/JSONIterableNode.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "QbLZ");

var _extends3 = _interopRequireDefault(_extends2);

var _objectWithoutProperties2 = __webpack_require__(/*! babel-runtime/helpers/objectWithoutProperties */ "jo6Y");

var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);

var _getIterator2 = __webpack_require__(/*! babel-runtime/core-js/get-iterator */ "FyfS");

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _isSafeInteger = __webpack_require__(/*! babel-runtime/core-js/number/is-safe-integer */ "5qYI");

var _isSafeInteger2 = _interopRequireDefault(_isSafeInteger);

exports['default'] = JSONIterableNode;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _JSONNestedNode = __webpack_require__(/*! ./JSONNestedNode */ "X834");

var _JSONNestedNode2 = _interopRequireDefault(_JSONNestedNode);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

// Returns the "n Items" string for this node,
// generating and caching it if it hasn't been created yet.
function createItemString(data, limit) {
  var count = 0;
  var hasMore = false;
  if ((0, _isSafeInteger2['default'])(data.size)) {
    count = data.size;
  } else {
    // eslint-disable-next-line no-unused-vars
    for (var _iterator = data, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3['default'])(_iterator);;) {
      var _ref;

      if (_isArray) {
        if (_i >= _iterator.length) break;
        _ref = _iterator[_i++];
      } else {
        _i = _iterator.next();
        if (_i.done) break;
        _ref = _i.value;
      }

      var entry = _ref;

      if (limit && count + 1 > limit) {
        hasMore = true;
        break;
      }
      count += 1;
    }
  }
  return '' + (hasMore ? '>' : '') + count + ' ' + (count !== 1 ? 'entries' : 'entry');
}

// Configures <JSONNestedNode> to render an iterable
function JSONIterableNode(_ref2) {
  var props = (0, _objectWithoutProperties3['default'])(_ref2, []);

  return _react2['default'].createElement(_JSONNestedNode2['default'], (0, _extends3['default'])({}, props, {
    nodeType: 'Iterable',
    nodeTypeIndicator: '()',
    createItemString: createItemString
  }));
}

/***/ }),

/***/ "gekB":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/fi.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var numbersPast = 'nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän'.split(' '),
    numbersFuture = [
        'nolla', 'yhden', 'kahden', 'kolmen', 'neljän', 'viiden', 'kuuden',
        numbersPast[7], numbersPast[8], numbersPast[9]
    ];
function translate(number, withoutSuffix, key, isFuture) {
    var result = '';
    switch (key) {
        case 's':
            return isFuture ? 'muutaman sekunnin' : 'muutama sekunti';
        case 'ss':
            return isFuture ? 'sekunnin' : 'sekuntia';
        case 'm':
            return isFuture ? 'minuutin' : 'minuutti';
        case 'mm':
            result = isFuture ? 'minuutin' : 'minuuttia';
            break;
        case 'h':
            return isFuture ? 'tunnin' : 'tunti';
        case 'hh':
            result = isFuture ? 'tunnin' : 'tuntia';
            break;
        case 'd':
            return isFuture ? 'päivän' : 'päivä';
        case 'dd':
            result = isFuture ? 'päivän' : 'päivää';
            break;
        case 'M':
            return isFuture ? 'kuukauden' : 'kuukausi';
        case 'MM':
            result = isFuture ? 'kuukauden' : 'kuukautta';
            break;
        case 'y':
            return isFuture ? 'vuoden' : 'vuosi';
        case 'yy':
            result = isFuture ? 'vuoden' : 'vuotta';
            break;
    }
    result = verbalNumber(number, isFuture) + ' ' + result;
    return result;
}
function verbalNumber(number, isFuture) {
    return number < 10 ? (isFuture ? numbersFuture[number] : numbersPast[number]) : number;
}

var fi = moment.defineLocale('fi', {
    months : 'tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu'.split('_'),
    monthsShort : 'tammi_helmi_maalis_huhti_touko_kesä_heinä_elo_syys_loka_marras_joulu'.split('_'),
    weekdays : 'sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai'.split('_'),
    weekdaysShort : 'su_ma_ti_ke_to_pe_la'.split('_'),
    weekdaysMin : 'su_ma_ti_ke_to_pe_la'.split('_'),
    longDateFormat : {
        LT : 'HH.mm',
        LTS : 'HH.mm.ss',
        L : 'DD.MM.YYYY',
        LL : 'Do MMMM[ta] YYYY',
        LLL : 'Do MMMM[ta] YYYY, [klo] HH.mm',
        LLLL : 'dddd, Do MMMM[ta] YYYY, [klo] HH.mm',
        l : 'D.M.YYYY',
        ll : 'Do MMM YYYY',
        lll : 'Do MMM YYYY, [klo] HH.mm',
        llll : 'ddd, Do MMM YYYY, [klo] HH.mm'
    },
    calendar : {
        sameDay : '[tänään] [klo] LT',
        nextDay : '[huomenna] [klo] LT',
        nextWeek : 'dddd [klo] LT',
        lastDay : '[eilen] [klo] LT',
        lastWeek : '[viime] dddd[na] [klo] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : '%s päästä',
        past : '%s sitten',
        s : translate,
        ss : translate,
        m : translate,
        mm : translate,
        h : translate,
        hh : translate,
        d : translate,
        dd : translate,
        M : translate,
        MM : translate,
        y : translate,
        yy : translate
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return fi;

})));


/***/ }),

/***/ "gfI5":
/*!**************************************************************!*\
  !*** ./node_modules/@jupyterlab/rendermime/lib/factories.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const widgets = __importStar(__webpack_require__(/*! ./widgets */ "75di"));
/**
 * A mime renderer factory for raw html.
 */
exports.htmlRendererFactory = {
    safe: true,
    mimeTypes: ['text/html'],
    defaultRank: 50,
    createRenderer: options => new widgets.RenderedHTML(options)
};
/**
 * A mime renderer factory for images.
 */
exports.imageRendererFactory = {
    safe: true,
    mimeTypes: ['image/bmp', 'image/png', 'image/jpeg', 'image/gif'],
    defaultRank: 90,
    createRenderer: options => new widgets.RenderedImage(options)
};
/**
 * A mime renderer factory for LaTeX.
 */
exports.latexRendererFactory = {
    safe: true,
    mimeTypes: ['text/latex'],
    defaultRank: 70,
    createRenderer: options => new widgets.RenderedLatex(options)
};
/**
 * A mime renderer factory for Markdown.
 */
exports.markdownRendererFactory = {
    safe: true,
    mimeTypes: ['text/markdown'],
    defaultRank: 60,
    createRenderer: options => new widgets.RenderedMarkdown(options)
};
/**
 * A mime renderer factory for svg.
 */
exports.svgRendererFactory = {
    safe: false,
    mimeTypes: ['image/svg+xml'],
    defaultRank: 80,
    createRenderer: options => new widgets.RenderedSVG(options)
};
/**
 * A mime renderer factory for plain and jupyter console text data.
 */
exports.textRendererFactory = {
    safe: true,
    mimeTypes: [
        'text/plain',
        'application/vnd.jupyter.stdout',
        'application/vnd.jupyter.stderr'
    ],
    defaultRank: 120,
    createRenderer: options => new widgets.RenderedText(options)
};
/**
 * A placeholder factory for deprecated rendered JavaScript.
 */
exports.javaScriptRendererFactory = {
    safe: false,
    mimeTypes: ['text/javascript', 'application/javascript'],
    defaultRank: 110,
    createRenderer: options => new widgets.RenderedJavaScript(options)
};
/**
 * The standard factories provided by the rendermime package.
 */
exports.standardRendererFactories = [
    exports.htmlRendererFactory,
    exports.markdownRendererFactory,
    exports.latexRendererFactory,
    exports.svgRendererFactory,
    exports.imageRendererFactory,
    exports.javaScriptRendererFactory,
    exports.textRendererFactory
];


/***/ }),

/***/ "gjCT":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/ar-sa.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var symbolMap = {
    '1': '١',
    '2': '٢',
    '3': '٣',
    '4': '٤',
    '5': '٥',
    '6': '٦',
    '7': '٧',
    '8': '٨',
    '9': '٩',
    '0': '٠'
}, numberMap = {
    '١': '1',
    '٢': '2',
    '٣': '3',
    '٤': '4',
    '٥': '5',
    '٦': '6',
    '٧': '7',
    '٨': '8',
    '٩': '9',
    '٠': '0'
};

var arSa = moment.defineLocale('ar-sa', {
    months : 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),
    monthsShort : 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),
    weekdays : 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
    weekdaysShort : 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),
    weekdaysMin : 'ح_ن_ث_ر_خ_ج_س'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd D MMMM YYYY HH:mm'
    },
    meridiemParse: /ص|م/,
    isPM : function (input) {
        return 'م' === input;
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 12) {
            return 'ص';
        } else {
            return 'م';
        }
    },
    calendar : {
        sameDay: '[اليوم على الساعة] LT',
        nextDay: '[غدا على الساعة] LT',
        nextWeek: 'dddd [على الساعة] LT',
        lastDay: '[أمس على الساعة] LT',
        lastWeek: 'dddd [على الساعة] LT',
        sameElse: 'L'
    },
    relativeTime : {
        future : 'في %s',
        past : 'منذ %s',
        s : 'ثوان',
        ss : '%d ثانية',
        m : 'دقيقة',
        mm : '%d دقائق',
        h : 'ساعة',
        hh : '%d ساعات',
        d : 'يوم',
        dd : '%d أيام',
        M : 'شهر',
        MM : '%d أشهر',
        y : 'سنة',
        yy : '%d سنوات'
    },
    preparse: function (string) {
        return string.replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) {
            return numberMap[match];
        }).replace(/،/g, ',');
    },
    postformat: function (string) {
        return string.replace(/\d/g, function (match) {
            return symbolMap[match];
        }).replace(/,/g, '،');
    },
    week : {
        dow : 0, // Sunday is the first day of the week.
        doy : 6  // The week that contains Jan 1st is the first week of the year.
    }
});

return arSa;

})));


/***/ }),

/***/ "glbb":
/*!***************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotScattermapboxIcon.js ***!
  \***************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotScattermapboxIcon = function PlotScattermapboxIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M23.75 19.438a.791.791 0 0 0-1.125 0l-1 1.063-1.313-1.313 2.625-2.625a.791.791 0 0 0 0-1.125l-2.625-2.625 1.313-1.313c1 .688 2.125 1.063 3.313 1.063.938 0 1.813-.188 2.625-.688.25-.125.375-.313.438-.563 0-.25-.063-.5-.25-.688l-2.625-2.625 1.063-1.063c.313-.313.313-.813 0-1.125s-.813-.313-1.125 0l-1.063 1.063-2.625-2.625c-.188-.188-.438-.25-.688-.25-.25.063-.438.188-.563.438-1.063 1.875-.875 4.188.375 5.938l-1.313 1.313-2.625-2.625a.791.791 0 0 0-1.125 0l-2.625 2.625-1.25-1.313 1-1a.791.791 0 0 0 0-1.125L6.187 1.812a.791.791 0 0 0-1.125 0l-3.25 3.25a.791.791 0 0 0 0 1.125l6.438 6.375c.125.188.375.25.563.25s.375-.063.563-.25l1-1 1.313 1.25-2.625 2.625a.791.791 0 0 0 0 1.125l2.625 2.625-1.313 1.313c-1.75-1.25-4.063-1.438-5.938-.375-.25.125-.375.313-.438.563 0 .25.063.5.25.688l2.625 2.625-1.063 1.063a.791.791 0 0 0 0 1.125c.188.125.375.188.563.188.25 0 .438-.063.563-.188l1.063-1.063 2.625 2.625c.188.188.375.25.563.25h.125c.25-.063.438-.188.563-.438 1.063-1.875.875-4.188-.375-5.938l1.313-1.313 2.625 2.625c.125.188.375.25.563.25s.438-.063.563-.25l2.625-2.625 1.313 1.313-1.063 1a.791.791 0 0 0 0 1.125l6.375 6.438c.188.125.375.188.563.188.25 0 .438-.063.563-.188l3.25-3.25a.791.791 0 0 0 0-1.125zM21.125 6.25l4.625 4.625a3.672 3.672 0 0 1-3.563-1.063 3.674 3.674 0 0 1-1.063-3.563zM3.563 5.625l2.063-2.063 2.063 2.063-2.063 2.063zm5.25 5.25L6.75 8.812l2.063-2.063 2.063 2.063zm2.062 14.875L6.25 21.125a3.672 3.672 0 0 1 3.563 1.063 3.674 3.674 0 0 1 1.063 3.563zM16 21.25L10.75 16 16 10.75 21.25 16zm5.125 1.938l2.063-2.063 2.063 2.063-2.063 2.063zm5.25 5.25l-2.063-2.063 2.063-2.063 2.125 2.063z' })
    );
};

exports.default = PlotScattermapboxIcon;

/***/ }),

/***/ "gpep":
/*!********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/sidebar/SidebarGroup.js ***!
  \********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _plotlyIcons = __webpack_require__(/*! plotly-icons */ "hwSx");

var _SidebarItem = __webpack_require__(/*! ./SidebarItem */ "H+vO");

var _SidebarItem2 = _interopRequireDefault(_SidebarItem);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var SidebarGroup = function (_Component) {
  _inherits(SidebarGroup, _Component);

  function SidebarGroup(props) {
    _classCallCheck(this, SidebarGroup);

    var _this = _possibleConstructorReturn(this, (SidebarGroup.__proto__ || Object.getPrototypeOf(SidebarGroup)).call(this, props));

    _this.state = {
      expanded: _this.props.group === _this.props.selectedGroup
    };

    _this.toggleExpanded = _this.toggleExpanded.bind(_this);
    _this.onChangeGroup = _this.onChangeGroup.bind(_this);
    _this.renderSubItem = _this.renderSubItem.bind(_this);
    return _this;
  }

  _createClass(SidebarGroup, [{
    key: 'toggleExpanded',
    value: function toggleExpanded() {
      this.setState({ expanded: !this.state.expanded });
    }
  }, {
    key: 'onChangeGroup',
    value: function onChangeGroup(panel) {
      this.props.onChangeGroup(this.props.group, panel);
    }
  }, {
    key: 'renderSubItem',
    value: function renderSubItem(panel, i) {
      var _this2 = this;

      var isActive = this.props.selectedPanel === panel && this.props.group === this.props.selectedGroup;

      return _react2.default.createElement(_SidebarItem2.default, {
        key: 'subitem-' + i,
        active: isActive,
        onClick: function onClick() {
          return _this2.onChangeGroup(panel);
        },
        label: panel
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          group = _props.group,
          panels = _props.panels,
          selectedGroup = _props.selectedGroup;
      var expanded = this.state.expanded;

      return _react2.default.createElement(
        'div',
        {
          className: (0, _lib.bem)('sidebar__group', [expanded ? 'is-expanded' : '', selectedGroup === group ? 'is-active' : ''])
        },
        _react2.default.createElement(
          'div',
          { onClick: this.toggleExpanded, className: (0, _lib.bem)('sidebar__group', 'title') },
          _react2.default.createElement(
            'div',
            { className: (0, _lib.bem)('sidebar__group', 'title__icon') },
            _react2.default.createElement(_plotlyIcons.AngleRightIcon, null)
          ),
          _react2.default.createElement(
            'div',
            { className: (0, _lib.bem)('sidebar__group', 'title__label') },
            group
          )
        ),
        expanded && panels.map(this.renderSubItem)
      );
    }
  }]);

  return SidebarGroup;
}(_react.Component);

exports.default = SidebarGroup;


SidebarGroup.propTypes = {
  group: _propTypes2.default.string,
  onChangeGroup: _propTypes2.default.func,
  panels: _propTypes2.default.array,
  selectedGroup: _propTypes2.default.string,
  selectedPanel: _propTypes2.default.string
};
//# sourceMappingURL=SidebarGroup.js.map

/***/ }),

/***/ "gqd8":
/*!*******************************************************!*\
  !*** ./node_modules/@jupyterlab/mainmenu/lib/view.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const labmenu_1 = __webpack_require__(/*! ./labmenu */ "e7FE");
/**
 * An extensible View menu for the application.
 */
class ViewMenu extends labmenu_1.JupyterLabMenu {
    /**
     * Construct the view menu.
     */
    constructor(options) {
        super(options);
        this.menu.title.label = 'View';
        this.editorViewers = new Set();
    }
    /**
     * Dispose of the resources held by the view menu.
     */
    dispose() {
        this.editorViewers.clear();
        super.dispose();
    }
}
exports.ViewMenu = ViewMenu;


/***/ }),

/***/ "grU7":
/*!************************************************************!*\
  !*** ./node_modules/plotly.js/src/plots/pad_attributes.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



/**
 * Creates a set of padding attributes.
 *
 * @param {object} opts
 *   @param {string} editType:
 *     the editType for all pieces of this padding definition
 *
 * @return {object} attributes object containing {t, r, b, l} as specified
 */
module.exports = function(opts) {
    var editType = opts.editType;
    return {
        t: {
            valType: 'number',
            dflt: 0,
            role: 'style',
            editType: editType,
            description: 'The amount of padding (in px) along the top of the component.'
        },
        r: {
            valType: 'number',
            dflt: 0,
            role: 'style',
            editType: editType,
            description: 'The amount of padding (in px) on the right side of the component.'
        },
        b: {
            valType: 'number',
            dflt: 0,
            role: 'style',
            editType: editType,
            description: 'The amount of padding (in px) along the bottom of the component.'
        },
        l: {
            valType: 'number',
            dflt: 0,
            role: 'style',
            editType: editType,
            description: 'The amount of padding (in px) on the left side of the component.'
        },
        editType: editType
    };
};


/***/ }),

/***/ "guEx":
/*!********************************************************************!*\
  !*** ./node_modules/react-tabs/esm/components/UncontrolledTabs.js ***!
  \********************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return UncontrolledTabs; });
/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! prop-types */ "17x9");
/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(prop_types__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "q1tI");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! classnames */ "TSYQ");
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(classnames__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _helpers_uuid__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../helpers/uuid */ "gTk9");
/* harmony import */ var _helpers_propTypes__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../helpers/propTypes */ "6ak3");
/* harmony import */ var _helpers_count__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../helpers/count */ "Oive");
/* harmony import */ var _helpers_childrenDeepMap__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../helpers/childrenDeepMap */ "pMj9");
/* harmony import */ var _helpers_elementTypes__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../helpers/elementTypes */ "fxcN");
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }








 // Determine if a node from event.target is a Tab element

function isTabNode(node) {
  return 'getAttribute' in node && node.getAttribute('role') === 'tab';
} // Determine if a tab node is disabled


function isTabDisabled(node) {
  return node.getAttribute('aria-disabled') === 'true';
}

var canUseActiveElement;

try {
  canUseActiveElement = !!(typeof window !== 'undefined' && window.document && window.document.activeElement);
} catch (e) {
  // Work around for IE bug when accessing document.activeElement in an iframe
  // Refer to the following resources:
  // http://stackoverflow.com/a/10982960/369687
  // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/12733599
  canUseActiveElement = false;
}

var UncontrolledTabs =
/*#__PURE__*/
function (_Component) {
  _inheritsLoose(UncontrolledTabs, _Component);

  function UncontrolledTabs() {
    var _this;

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _Component.call.apply(_Component, [this].concat(args)) || this;
    _this.tabNodes = [];

    _this.handleKeyDown = function (e) {
      if (_this.isTabFromContainer(e.target)) {
        var index = _this.props.selectedIndex;
        var preventDefault = false;
        var useSelectedIndex = false;

        if (e.keyCode === 32 || e.keyCode === 13) {
          preventDefault = true;
          useSelectedIndex = false;

          _this.handleClick(e);
        }

        if (e.keyCode === 37 || e.keyCode === 38) {
          // Select next tab to the left
          index = _this.getPrevTab(index);
          preventDefault = true;
          useSelectedIndex = true;
        } else if (e.keyCode === 39 || e.keyCode === 40) {
          // Select next tab to the right
          index = _this.getNextTab(index);
          preventDefault = true;
          useSelectedIndex = true;
        } else if (e.keyCode === 35) {
          // Select last tab (End key)
          index = _this.getLastTab();
          preventDefault = true;
          useSelectedIndex = true;
        } else if (e.keyCode === 36) {
          // Select first tab (Home key)
          index = _this.getFirstTab();
          preventDefault = true;
          useSelectedIndex = true;
        } // This prevents scrollbars from moving around


        if (preventDefault) {
          e.preventDefault();
        } // Only use the selected index in the state if we're not using the tabbed index


        if (useSelectedIndex) {
          _this.setSelected(index, e);
        }
      }
    };

    _this.handleClick = function (e) {
      var node = e.target; // eslint-disable-next-line no-cond-assign

      do {
        if (_this.isTabFromContainer(node)) {
          if (isTabDisabled(node)) {
            return;
          }

          var index = [].slice.call(node.parentNode.children).filter(isTabNode).indexOf(node);

          _this.setSelected(index, e);

          return;
        }
      } while ((node = node.parentNode) !== null);
    };

    return _this;
  }

  var _proto = UncontrolledTabs.prototype;

  _proto.setSelected = function setSelected(index, event) {
    // Check index boundary
    if (index < 0 || index >= this.getTabsCount()) return;
    var _this$props = this.props,
        onSelect = _this$props.onSelect,
        selectedIndex = _this$props.selectedIndex; // Call change event handler

    onSelect(index, selectedIndex, event);
  };

  _proto.getNextTab = function getNextTab(index) {
    var count = this.getTabsCount(); // Look for non-disabled tab from index to the last tab on the right

    for (var i = index + 1; i < count; i++) {
      if (!isTabDisabled(this.getTab(i))) {
        return i;
      }
    } // If no tab found, continue searching from first on left to index


    for (var _i = 0; _i < index; _i++) {
      if (!isTabDisabled(this.getTab(_i))) {
        return _i;
      }
    } // No tabs are disabled, return index


    return index;
  };

  _proto.getPrevTab = function getPrevTab(index) {
    var i = index; // Look for non-disabled tab from index to first tab on the left

    while (i--) {
      if (!isTabDisabled(this.getTab(i))) {
        return i;
      }
    } // If no tab found, continue searching from last tab on right to index


    i = this.getTabsCount();

    while (i-- > index) {
      if (!isTabDisabled(this.getTab(i))) {
        return i;
      }
    } // No tabs are disabled, return index


    return index;
  };

  _proto.getFirstTab = function getFirstTab() {
    var count = this.getTabsCount(); // Look for non disabled tab from the first tab

    for (var i = 0; i < count; i++) {
      if (!isTabDisabled(this.getTab(i))) {
        return i;
      }
    }

    return null;
  };

  _proto.getLastTab = function getLastTab() {
    var i = this.getTabsCount(); // Look for non disabled tab from the last tab

    while (i--) {
      if (!isTabDisabled(this.getTab(i))) {
        return i;
      }
    }

    return null;
  };

  _proto.getTabsCount = function getTabsCount() {
    var children = this.props.children;
    return Object(_helpers_count__WEBPACK_IMPORTED_MODULE_5__["getTabsCount"])(children);
  };

  _proto.getPanelsCount = function getPanelsCount() {
    var children = this.props.children;
    return Object(_helpers_count__WEBPACK_IMPORTED_MODULE_5__["getPanelsCount"])(children);
  };

  _proto.getTab = function getTab(index) {
    return this.tabNodes["tabs-" + index];
  };

  _proto.getChildren = function getChildren() {
    var _this2 = this;

    var index = 0;
    var _this$props2 = this.props,
        children = _this$props2.children,
        disabledTabClassName = _this$props2.disabledTabClassName,
        focus = _this$props2.focus,
        forceRenderTabPanel = _this$props2.forceRenderTabPanel,
        selectedIndex = _this$props2.selectedIndex,
        selectedTabClassName = _this$props2.selectedTabClassName,
        selectedTabPanelClassName = _this$props2.selectedTabPanelClassName;
    this.tabIds = this.tabIds || [];
    this.panelIds = this.panelIds || [];
    var diff = this.tabIds.length - this.getTabsCount(); // Add ids if new tabs have been added
    // Don't bother removing ids, just keep them in case they are added again
    // This is more efficient, and keeps the uuid counter under control

    while (diff++ < 0) {
      this.tabIds.push(Object(_helpers_uuid__WEBPACK_IMPORTED_MODULE_3__["default"])());
      this.panelIds.push(Object(_helpers_uuid__WEBPACK_IMPORTED_MODULE_3__["default"])());
    } // Map children to dynamically setup refs


    return Object(_helpers_childrenDeepMap__WEBPACK_IMPORTED_MODULE_6__["deepMap"])(children, function (child) {
      var result = child; // Clone TabList and Tab components to have refs

      if (Object(_helpers_elementTypes__WEBPACK_IMPORTED_MODULE_7__["isTabList"])(child)) {
        var listIndex = 0; // Figure out if the current focus in the DOM is set on a Tab
        // If it is we should keep the focus on the next selected tab

        var wasTabFocused = false;

        if (canUseActiveElement) {
          wasTabFocused = react__WEBPACK_IMPORTED_MODULE_1___default.a.Children.toArray(child.props.children).filter(_helpers_elementTypes__WEBPACK_IMPORTED_MODULE_7__["isTab"]).some(function (tab, i) {
            return document.activeElement === _this2.getTab(i);
          });
        }

        result = Object(react__WEBPACK_IMPORTED_MODULE_1__["cloneElement"])(child, {
          children: Object(_helpers_childrenDeepMap__WEBPACK_IMPORTED_MODULE_6__["deepMap"])(child.props.children, function (tab) {
            var key = "tabs-" + listIndex;
            var selected = selectedIndex === listIndex;
            var props = {
              tabRef: function tabRef(node) {
                _this2.tabNodes[key] = node;
              },
              id: _this2.tabIds[listIndex],
              panelId: _this2.panelIds[listIndex],
              selected: selected,
              focus: selected && (focus || wasTabFocused)
            };
            if (selectedTabClassName) props.selectedClassName = selectedTabClassName;
            if (disabledTabClassName) props.disabledClassName = disabledTabClassName;
            listIndex++;
            return Object(react__WEBPACK_IMPORTED_MODULE_1__["cloneElement"])(tab, props);
          })
        });
      } else if (Object(_helpers_elementTypes__WEBPACK_IMPORTED_MODULE_7__["isTabPanel"])(child)) {
        var props = {
          id: _this2.panelIds[index],
          tabId: _this2.tabIds[index],
          selected: selectedIndex === index
        };
        if (forceRenderTabPanel) props.forceRender = forceRenderTabPanel;
        if (selectedTabPanelClassName) props.selectedClassName = selectedTabPanelClassName;
        index++;
        result = Object(react__WEBPACK_IMPORTED_MODULE_1__["cloneElement"])(child, props);
      }

      return result;
    });
  };

  /**
   * Determine if a node from event.target is a Tab element for the current Tabs container.
   * If the clicked element is not a Tab, it returns false.
   * If it finds another Tabs container between the Tab and `this`, it returns false.
   */
  _proto.isTabFromContainer = function isTabFromContainer(node) {
    // return immediately if the clicked element is not a Tab.
    if (!isTabNode(node)) {
      return false;
    } // Check if the first occurrence of a Tabs container is `this` one.


    var nodeAncestor = node.parentElement;

    do {
      if (nodeAncestor === this.node) return true;
      if (nodeAncestor.getAttribute('data-tabs')) break;
      nodeAncestor = nodeAncestor.parentElement;
    } while (nodeAncestor);

    return false;
  };

  _proto.render = function render() {
    var _this3 = this;

    // Delete all known props, so they don't get added to DOM
    var _this$props3 = this.props,
        children = _this$props3.children,
        className = _this$props3.className,
        disabledTabClassName = _this$props3.disabledTabClassName,
        domRef = _this$props3.domRef,
        focus = _this$props3.focus,
        forceRenderTabPanel = _this$props3.forceRenderTabPanel,
        onSelect = _this$props3.onSelect,
        selectedIndex = _this$props3.selectedIndex,
        selectedTabClassName = _this$props3.selectedTabClassName,
        selectedTabPanelClassName = _this$props3.selectedTabPanelClassName,
        attributes = _objectWithoutPropertiesLoose(_this$props3, ["children", "className", "disabledTabClassName", "domRef", "focus", "forceRenderTabPanel", "onSelect", "selectedIndex", "selectedTabClassName", "selectedTabPanelClassName"]);

    return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", _extends({}, attributes, {
      className: classnames__WEBPACK_IMPORTED_MODULE_2___default()(className),
      onClick: this.handleClick,
      onKeyDown: this.handleKeyDown,
      ref: function ref(node) {
        _this3.node = node;
        if (domRef) domRef(node);
      },
      "data-tabs": true
    }), this.getChildren());
  };

  return UncontrolledTabs;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]);

UncontrolledTabs.defaultProps = {
  className: 'react-tabs',
  focus: false
};

UncontrolledTabs.propTypes =  true ? {
  children: _helpers_propTypes__WEBPACK_IMPORTED_MODULE_4__["childrenPropType"],
  className: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.array, prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.object]),
  disabledTabClassName: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.string,
  domRef: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.func,
  focus: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.bool,
  forceRenderTabPanel: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.bool,
  onSelect: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.func.isRequired,
  selectedIndex: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.number.isRequired,
  selectedTabClassName: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.string,
  selectedTabPanelClassName: prop_types__WEBPACK_IMPORTED_MODULE_0___default.a.string
} : undefined;

/***/ }),

/***/ "gvAe":
/*!***************************************************!*\
  !*** ./node_modules/browserify-aes/authCipher.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var aes = __webpack_require__(/*! ./aes */ "OfWw")
var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer
var Transform = __webpack_require__(/*! cipher-base */ "ZDAU")
var inherits = __webpack_require__(/*! inherits */ "P7XM")
var GHASH = __webpack_require__(/*! ./ghash */ "P2KE")
var xor = __webpack_require__(/*! buffer-xor */ "jIre")
var incr32 = __webpack_require__(/*! ./incr32 */ "vZ2G")

function xorTest (a, b) {
  var out = 0
  if (a.length !== b.length) out++

  var len = Math.min(a.length, b.length)
  for (var i = 0; i < len; ++i) {
    out += (a[i] ^ b[i])
  }

  return out
}

function calcIv (self, iv, ck) {
  if (iv.length === 12) {
    self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])])
    return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])])
  }
  var ghash = new GHASH(ck)
  var len = iv.length
  var toPad = len % 16
  ghash.update(iv)
  if (toPad) {
    toPad = 16 - toPad
    ghash.update(Buffer.alloc(toPad, 0))
  }
  ghash.update(Buffer.alloc(8, 0))
  var ivBits = len * 8
  var tail = Buffer.alloc(8)
  tail.writeUIntBE(ivBits, 0, 8)
  ghash.update(tail)
  self._finID = ghash.state
  var out = Buffer.from(self._finID)
  incr32(out)
  return out
}
function StreamCipher (mode, key, iv, decrypt) {
  Transform.call(this)

  var h = Buffer.alloc(4, 0)

  this._cipher = new aes.AES(key)
  var ck = this._cipher.encryptBlock(h)
  this._ghash = new GHASH(ck)
  iv = calcIv(this, iv, ck)

  this._prev = Buffer.from(iv)
  this._cache = Buffer.allocUnsafe(0)
  this._secCache = Buffer.allocUnsafe(0)
  this._decrypt = decrypt
  this._alen = 0
  this._len = 0
  this._mode = mode

  this._authTag = null
  this._called = false
}

inherits(StreamCipher, Transform)

StreamCipher.prototype._update = function (chunk) {
  if (!this._called && this._alen) {
    var rump = 16 - (this._alen % 16)
    if (rump < 16) {
      rump = Buffer.alloc(rump, 0)
      this._ghash.update(rump)
    }
  }

  this._called = true
  var out = this._mode.encrypt(this, chunk)
  if (this._decrypt) {
    this._ghash.update(chunk)
  } else {
    this._ghash.update(out)
  }
  this._len += chunk.length
  return out
}

StreamCipher.prototype._final = function () {
  if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data')

  var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID))
  if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data')

  this._authTag = tag
  this._cipher.scrub()
}

StreamCipher.prototype.getAuthTag = function getAuthTag () {
  if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state')

  return this._authTag
}

StreamCipher.prototype.setAuthTag = function setAuthTag (tag) {
  if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state')

  this._authTag = tag
}

StreamCipher.prototype.setAAD = function setAAD (buf) {
  if (this._called) throw new Error('Attempting to set AAD in unsupported state')

  this._ghash.update(buf)
  this._alen += buf.length
}

module.exports = StreamCipher


/***/ }),

/***/ "h+Gr":
/*!************************************************!*\
  !*** ./node_modules/mdi-react/BookmarkIcon.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var BookmarkIcon = function BookmarkIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M17,3H7C5.9,3 5,3.9 5,5V21L12,18L19,21V5C19,3.89 18.1,3 17,3Z' })
  );
};

module.exports = BookmarkIcon;


/***/ }),

/***/ "h/2P":
/*!********************************************************!*\
  !*** ./node_modules/draft-js/lib/editOnBeforeInput.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule editOnBeforeInput
 * @format
 * 
 */



var BlockTree = __webpack_require__(/*! ./BlockTree */ "L0q3");
var DraftModifier = __webpack_require__(/*! ./DraftModifier */ "fyOY");
var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");
var UserAgent = __webpack_require__(/*! fbjs/lib/UserAgent */ "CYTE");

var getEntityKeyForSelection = __webpack_require__(/*! ./getEntityKeyForSelection */ "hpMJ");
var isEventHandled = __webpack_require__(/*! ./isEventHandled */ "T401");
var isSelectionAtLeafStart = __webpack_require__(/*! ./isSelectionAtLeafStart */ "Yrnb");
var nullthrows = __webpack_require__(/*! fbjs/lib/nullthrows */ "gWRK");
var setImmediate = __webpack_require__(/*! fbjs/lib/setImmediate */ "eOzY");

// When nothing is focused, Firefox regards two characters, `'` and `/`, as
// commands that should open and focus the "quickfind" search bar. This should
// *never* happen while a contenteditable is focused, but as of v28, it
// sometimes does, even when the keypress event target is the contenteditable.
// This breaks the input. Special case these characters to ensure that when
// they are typed, we prevent default on the event to make sure not to
// trigger quickfind.
var FF_QUICKFIND_CHAR = "'";
var FF_QUICKFIND_LINK_CHAR = '/';
var isFirefox = UserAgent.isBrowser('Firefox');

function mustPreventDefaultForCharacter(character) {
  return isFirefox && (character == FF_QUICKFIND_CHAR || character == FF_QUICKFIND_LINK_CHAR);
}

/**
 * Replace the current selection with the specified text string, with the
 * inline style and entity key applied to the newly inserted text.
 */
function replaceText(editorState, text, inlineStyle, entityKey) {
  var contentState = DraftModifier.replaceText(editorState.getCurrentContent(), editorState.getSelection(), text, inlineStyle, entityKey);
  return EditorState.push(editorState, contentState, 'insert-characters');
}

/**
 * When `onBeforeInput` executes, the browser is attempting to insert a
 * character into the editor. Apply this character data to the document,
 * allowing native insertion if possible.
 *
 * Native insertion is encouraged in order to limit re-rendering and to
 * preserve spellcheck highlighting, which disappears or flashes if re-render
 * occurs on the relevant text nodes.
 */
function editOnBeforeInput(editor, e) {
  if (editor._pendingStateFromBeforeInput !== undefined) {
    editor.update(editor._pendingStateFromBeforeInput);
    editor._pendingStateFromBeforeInput = undefined;
  }

  var editorState = editor._latestEditorState;

  var chars = e.data;

  // In some cases (ex: IE ideographic space insertion) no character data
  // is provided. There's nothing to do when this happens.
  if (!chars) {
    return;
  }

  // Allow the top-level component to handle the insertion manually. This is
  // useful when triggering interesting behaviors for a character insertion,
  // Simple examples: replacing a raw text ':)' with a smile emoji or image
  // decorator, or setting a block to be a list item after typing '- ' at the
  // start of the block.
  if (editor.props.handleBeforeInput && isEventHandled(editor.props.handleBeforeInput(chars, editorState))) {
    e.preventDefault();
    return;
  }

  // If selection is collapsed, conditionally allow native behavior. This
  // reduces re-renders and preserves spellcheck highlighting. If the selection
  // is not collapsed, we will re-render.
  var selection = editorState.getSelection();
  var selectionStart = selection.getStartOffset();
  var selectionEnd = selection.getEndOffset();
  var anchorKey = selection.getAnchorKey();

  if (!selection.isCollapsed()) {
    e.preventDefault();

    // If the currently selected text matches what the user is trying to
    // replace it with, let's just update the `SelectionState`. If not, update
    // the `ContentState` with the new text.
    var currentlySelectedChars = editorState.getCurrentContent().getPlainText().slice(selectionStart, selectionEnd);
    if (chars === currentlySelectedChars) {
      editor.update(EditorState.forceSelection(editorState, selection.merge({
        focusOffset: selectionEnd
      })));
    } else {
      editor.update(replaceText(editorState, chars, editorState.getCurrentInlineStyle(), getEntityKeyForSelection(editorState.getCurrentContent(), editorState.getSelection())));
    }
    return;
  }

  var newEditorState = replaceText(editorState, chars, editorState.getCurrentInlineStyle(), getEntityKeyForSelection(editorState.getCurrentContent(), editorState.getSelection()));

  // Bunch of different cases follow where we need to prevent native insertion.
  var mustPreventNative = false;
  if (!mustPreventNative) {
    // Browsers tend to insert text in weird places in the DOM when typing at
    // the start of a leaf, so we'll handle it ourselves.
    mustPreventNative = isSelectionAtLeafStart(editor._latestCommittedEditorState);
  }
  if (!mustPreventNative) {
    // Chrome will also split up a node into two pieces if it contains a Tab
    // char, for no explicable reason. Seemingly caused by this commit:
    // https://chromium.googlesource.com/chromium/src/+/013ac5eaf3%5E%21/
    var nativeSelection = global.getSelection();
    // Selection is necessarily collapsed at this point due to earlier check.
    if (nativeSelection.anchorNode && nativeSelection.anchorNode.nodeType === Node.TEXT_NODE) {
      // See isTabHTMLSpanElement in chromium EditingUtilities.cpp.
      var parentNode = nativeSelection.anchorNode.parentNode;
      mustPreventNative = parentNode.nodeName === 'SPAN' && parentNode.firstChild.nodeType === Node.TEXT_NODE && parentNode.firstChild.nodeValue.indexOf('\t') !== -1;
    }
  }
  if (!mustPreventNative) {
    // Check the old and new "fingerprints" of the current block to determine
    // whether this insertion requires any addition or removal of text nodes,
    // in which case we would prevent the native character insertion.
    var originalFingerprint = BlockTree.getFingerprint(editorState.getBlockTree(anchorKey));
    var newFingerprint = BlockTree.getFingerprint(newEditorState.getBlockTree(anchorKey));
    mustPreventNative = originalFingerprint !== newFingerprint;
  }
  if (!mustPreventNative) {
    mustPreventNative = mustPreventDefaultForCharacter(chars);
  }
  if (!mustPreventNative) {
    mustPreventNative = nullthrows(newEditorState.getDirectionMap()).get(anchorKey) !== nullthrows(editorState.getDirectionMap()).get(anchorKey);
  }

  if (mustPreventNative) {
    e.preventDefault();
    editor.update(newEditorState);
    return;
  }

  // We made it all the way! Let the browser do its thing and insert the char.
  newEditorState = EditorState.set(newEditorState, {
    nativelyRenderedContent: newEditorState.getCurrentContent()
  });
  // The native event is allowed to occur. To allow user onChange handlers to
  // change the inserted text, we wait until the text is actually inserted
  // before we actually update our state. That way when we rerender, the text
  // we see in the DOM will already have been inserted properly.
  editor._pendingStateFromBeforeInput = newEditorState;
  setImmediate(function () {
    if (editor._pendingStateFromBeforeInput !== undefined) {
      editor.update(editor._pendingStateFromBeforeInput);
      editor._pendingStateFromBeforeInput = undefined;
    }
  });
}

module.exports = editOnBeforeInput;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "h2ac":
/*!*********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotBarAxesIcon.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotBarAxesIcon = function PlotBarAxesIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M0 0h1.625v32H0zm32 30.375V32H0v-1.625zM3.188 12.813h3.188v16H3.188zM8 11.188h3.188v17.625H8zm4.813 1.625h3.188v16h-3.188zm4.812-3.188h3.188v19.188h-3.188zM22.375 8h3.25v20.813h-3.25zm4.813-3.187h3.188v24h-3.188z' })
    );
};

exports.default = PlotBarAxesIcon;

/***/ }),

/***/ "h2lD":
/*!********************************************************!*\
  !*** ./node_modules/htmlparser2/lib/WritableStream.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = Stream;

var Parser = __webpack_require__(/*! ./Parser.js */ "WASD");
var WritableStream = __webpack_require__(/*! readable-stream */ 6).Writable;
var StringDecoder = __webpack_require__(/*! string_decoder */ "qiJe").StringDecoder;
var Buffer = __webpack_require__(/*! buffer */ "tjlA").Buffer;

function Stream(cbs, options) {
    var parser = (this._parser = new Parser(cbs, options));
    var decoder = (this._decoder = new StringDecoder());

    WritableStream.call(this, { decodeStrings: false });

    this.once("finish", function() {
        parser.end(decoder.end());
    });
}

__webpack_require__(/*! inherits */ "P7XM")(Stream, WritableStream);

Stream.prototype._write = function(chunk, encoding, cb) {
    if (chunk instanceof Buffer) chunk = this._decoder.write(chunk);
    this._parser.write(chunk);
    cb();
};


/***/ }),

/***/ "h4KJ":
/*!*************************************************************!*\
  !*** ./node_modules/@jupyterlab/filebrowser/lib/browser.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const services_1 = __webpack_require__(/*! @jupyterlab/services */ "S9up");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const crumbs_1 = __webpack_require__(/*! ./crumbs */ "R4GQ");
const listing_1 = __webpack_require__(/*! ./listing */ "m5lF");
const upload_1 = __webpack_require__(/*! ./upload */ "XtOF");
/**
 * The class name added to file browsers.
 */
const FILE_BROWSER_CLASS = 'jp-FileBrowser';
/**
 * The class name added to the filebrowser crumbs node.
 */
const CRUMBS_CLASS = 'jp-FileBrowser-crumbs';
/**
 * The class name added to the filebrowser toolbar node.
 */
const TOOLBAR_CLASS = 'jp-FileBrowser-toolbar';
/**
 * The class name added to the filebrowser listing node.
 */
const LISTING_CLASS = 'jp-FileBrowser-listing';
/**
 * A widget which hosts a file browser.
 *
 * The widget uses the Jupyter Contents API to retrieve contents,
 * and presents itself as a flat list of files and directories with
 * breadcrumbs.
 */
class FileBrowser extends widgets_1.Widget {
    /**
     * Construct a new file browser.
     *
     * @param model - The file browser view model.
     */
    constructor(options) {
        super();
        this._showingError = false;
        this.addClass(FILE_BROWSER_CLASS);
        this.id = options.id;
        const model = (this.model = options.model);
        const renderer = options.renderer;
        model.connectionFailure.connect(this._onConnectionFailure, this);
        this._manager = model.manager;
        this._crumbs = new crumbs_1.BreadCrumbs({ model });
        this.toolbar = new apputils_1.Toolbar();
        let directoryPending = false;
        let newFolder = new apputils_1.ToolbarButton({
            iconClassName: 'jp-NewFolderIcon jp-Icon jp-Icon-16',
            onClick: () => {
                if (directoryPending === true) {
                    return;
                }
                directoryPending = true;
                this._manager
                    .newUntitled({
                    path: model.path,
                    type: 'directory'
                })
                    .then(model => {
                    this._listing.selectItemByName(model.name);
                    directoryPending = false;
                })
                    .catch(err => {
                    directoryPending = false;
                });
            },
            tooltip: 'New Folder'
        });
        let uploader = new upload_1.Uploader({ model });
        let refresher = new apputils_1.ToolbarButton({
            iconClassName: 'jp-RefreshIcon jp-Icon jp-Icon-16',
            onClick: () => {
                model.refresh();
            },
            tooltip: 'Refresh File List'
        });
        this.toolbar.addItem('newFolder', newFolder);
        this.toolbar.addItem('upload', uploader);
        this.toolbar.addItem('refresher', refresher);
        this._listing = new listing_1.DirListing({ model, renderer });
        this._crumbs.addClass(CRUMBS_CLASS);
        this.toolbar.addClass(TOOLBAR_CLASS);
        this._listing.addClass(LISTING_CLASS);
        let layout = new widgets_1.PanelLayout();
        layout.addWidget(this.toolbar);
        layout.addWidget(this._crumbs);
        layout.addWidget(this._listing);
        this.layout = layout;
        model.restore(this.id);
    }
    /**
     * Create an iterator over the listing's selected items.
     *
     * @returns A new iterator over the listing's selected items.
     */
    selectedItems() {
        return this._listing.selectedItems();
    }
    /**
     * Rename the first currently selected item.
     *
     * @returns A promise that resolves with the new name of the item.
     */
    rename() {
        return this._listing.rename();
    }
    /**
     * Cut the selected items.
     */
    cut() {
        this._listing.cut();
    }
    /**
     * Copy the selected items.
     */
    copy() {
        this._listing.copy();
    }
    /**
     * Paste the items from the clipboard.
     *
     * @returns A promise that resolves when the operation is complete.
     */
    paste() {
        return this._listing.paste();
    }
    /**
     * Delete the currently selected item(s).
     *
     * @returns A promise that resolves when the operation is complete.
     */
    delete() {
        return this._listing.delete();
    }
    /**
     * Duplicate the currently selected item(s).
     *
     * @returns A promise that resolves when the operation is complete.
     */
    duplicate() {
        return this._listing.duplicate();
    }
    /**
     * Download the currently selected item(s).
     */
    download() {
        this._listing.download();
    }
    /**
     * Shut down kernels on the applicable currently selected items.
     *
     * @returns A promise that resolves when the operation is complete.
     */
    shutdownKernels() {
        return this._listing.shutdownKernels();
    }
    /**
     * Select next item.
     */
    selectNext() {
        this._listing.selectNext();
    }
    /**
     * Select previous item.
     */
    selectPrevious() {
        this._listing.selectPrevious();
    }
    /**
     * Find a model given a click.
     *
     * @param event - The mouse event.
     *
     * @returns The model for the selected file.
     */
    modelForClick(event) {
        return this._listing.modelForClick(event);
    }
    /**
     * Handle a connection lost signal from the model.
     */
    _onConnectionFailure(sender, args) {
        if (this._showingError) {
            return;
        }
        this._showingError = true;
        let title = 'Server Connection Error';
        let networkMsg = 'A connection to the Jupyter server could not be established.\n' +
            'JupyterLab will continue trying to reconnect.\n' +
            'Check your network connection or Jupyter server configuration.\n';
        // Check for a fetch error.
        if (args instanceof services_1.ServerConnection.NetworkError) {
            args.message = networkMsg;
        }
        else if (args instanceof services_1.ServerConnection.ResponseError) {
            if (args.response.status === 404) {
                title = 'Directory not found';
                args.message = `Directory not found: "${this.model.path}"`;
            }
        }
        apputils_1.showErrorMessage(title, args).then(() => {
            this._showingError = false;
        });
    }
}
exports.FileBrowser = FileBrowser;


/***/ }),

/***/ "h5Cg":
/*!*********************************************!*\
  !*** ./node_modules/mdi-react/MinusIcon.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var MinusIcon = function MinusIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M19,13H5V11H19V13Z' })
  );
};

module.exports = MinusIcon;


/***/ }),

/***/ "h687":
/*!******************************************************!*\
  !*** ./node_modules/@phosphor/coreutils/lib/mime.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * An object which stores MIME data for general application use.
 *
 * #### Notes
 * This class does not attempt to enforce "correctness" of MIME types
 * and their associated data. Since this class is designed to transfer
 * arbitrary data and objects within the same application, it assumes
 * that the user provides correct and accurate data.
 */
var MimeData = (function () {
    function MimeData() {
        this._types = [];
        this._values = [];
    }
    /**
     * Get an array of the MIME types contained within the dataset.
     *
     * @returns A new array of the MIME types, in order of insertion.
     */
    MimeData.prototype.types = function () {
        return this._types.slice();
    };
    /**
     * Test whether the dataset has an entry for the given type.
     *
     * @param mime - The MIME type of interest.
     *
     * @returns `true` if the dataset contains a value for the given
     *   MIME type, `false` otherwise.
     */
    MimeData.prototype.hasData = function (mime) {
        return this._types.indexOf(mime) !== -1;
    };
    /**
     * Get the data value for the given MIME type.
     *
     * @param mime - The MIME type of interest.
     *
     * @returns The value for the given MIME type, or `undefined` if
     *   the dataset does not contain a value for the type.
     */
    MimeData.prototype.getData = function (mime) {
        var i = this._types.indexOf(mime);
        return i !== -1 ? this._values[i] : undefined;
    };
    /**
     * Set the data value for the given MIME type.
     *
     * @param mime - The MIME type of interest.
     *
     * @param data - The data value for the given MIME type.
     *
     * #### Notes
     * This will overwrite any previous entry for the MIME type.
     */
    MimeData.prototype.setData = function (mime, data) {
        this.clearData(mime);
        this._types.push(mime);
        this._values.push(data);
    };
    /**
     * Remove the data entry for the given MIME type.
     *
     * @param mime - The MIME type of interest.
     *
     * #### Notes
     * This is a no-op if there is no entry for the given MIME type.
     */
    MimeData.prototype.clearData = function (mime) {
        var i = this._types.indexOf(mime);
        if (i !== -1) {
            this._types.splice(i, 1);
            this._values.splice(i, 1);
        }
    };
    /**
     * Remove all data entries from the dataset.
     */
    MimeData.prototype.clear = function () {
        this._types.length = 0;
        this._values.length = 0;
    };
    return MimeData;
}());
exports.MimeData = MimeData;


/***/ }),

/***/ "hBOs":
/*!***************************************************************!*\
  !*** ./node_modules/@jupyterlab/codeeditor/lib/jsoneditor.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const React = __importStar(__webpack_require__(/*! react */ "q1tI"));
const ReactDOM = __importStar(__webpack_require__(/*! react-dom */ "i8i4"));
const editor_1 = __webpack_require__(/*! ./editor */ "oMAC");
/**
 * The class name added to a JSONEditor instance.
 */
const JSONEDITOR_CLASS = 'jp-JSONEditor';
/**
 * The class name added when the Metadata editor contains invalid JSON.
 */
const ERROR_CLASS = 'jp-mod-error';
/**
 * The class name added to the editor host node.
 */
const HOST_CLASS = 'jp-JSONEditor-host';
/**
 * The class name added to the header area.
 */
const HEADER_CLASS = 'jp-JSONEditor-header';
/**
 * The class name added to the title node.
 */
const TITLE_CLASS = 'jp-JSONEditor-title';
/**
 * The class name added to the collapser node.
 */
const COLLAPSER_CLASS = 'jp-JSONEditor-collapser';
/**
 * The class name added to the collapser node that is enabled.
 */
const COLLAPSE_ENABLED_CLASS = 'jp-mod-collapse-enabled';
/**
 * The class name added to the revert button.
 */
const REVERT_CLASS = 'jp-JSONEditor-revertButton';
/**
 * The class name added to the commit button.
 */
const COMMIT_CLASS = 'jp-JSONEditor-commitButton';
/**
 * The class name added to collapsed items.
 */
const COLLAPSED_CLASS = 'jp-mod-collapsed';
/**
 * A widget for editing observable JSON.
 */
class JSONEditor extends widgets_1.Widget {
    /**
     * Construct a new JSON editor.
     */
    constructor(options) {
        super();
        this._dataDirty = false;
        this._inputDirty = false;
        this._source = null;
        this._originalValue = coreutils_1.JSONExt.emptyObject;
        this._changeGuard = false;
        this.addClass(JSONEDITOR_CLASS);
        ReactDOM.render(Private.createEditorContent(options), this.node);
        let host = this.editorHostNode;
        let model = new editor_1.CodeEditor.Model();
        model.value.text = 'No data!';
        model.mimeType = 'application/json';
        model.value.changed.connect(this._onValueChanged, this);
        this.model = model;
        this.editor = options.editorFactory({ host, model });
        this.editor.setOption('readOnly', true);
        this.collapsible = !!options.collapsible;
    }
    /**
     * The title of the editor.
     */
    get editorTitle() {
        return this.titleNode.textContent || '';
    }
    set editorTitle(value) {
        this.titleNode.textContent = value;
    }
    /**
     * Get the editor host node used by the JSON editor.
     */
    get editorHostNode() {
        return this.node.getElementsByClassName(HOST_CLASS)[0];
    }
    /**
     * Get the header node used by the JSON editor.
     */
    get headerNode() {
        return this.node.getElementsByClassName(HEADER_CLASS)[0];
    }
    /**
     * Get the title node used by the JSON editor.
     */
    get titleNode() {
        return this.node.getElementsByClassName(TITLE_CLASS)[0];
    }
    /**
     * Get the collapser node used by the JSON editor.
     */
    get collapserNode() {
        return this.node.getElementsByClassName(COLLAPSER_CLASS)[0];
    }
    /**
     * Get the revert button used by the JSON editor.
     */
    get revertButtonNode() {
        return this.node.getElementsByClassName(REVERT_CLASS)[0];
    }
    /**
     * Get the commit button used by the JSON editor.
     */
    get commitButtonNode() {
        return this.node.getElementsByClassName(COMMIT_CLASS)[0];
    }
    /**
     * The observable source.
     */
    get source() {
        return this._source;
    }
    set source(value) {
        if (this._source === value) {
            return;
        }
        if (this._source) {
            this._source.changed.disconnect(this._onSourceChanged, this);
        }
        this._source = value;
        this.editor.setOption('readOnly', value === null);
        if (value) {
            value.changed.connect(this._onSourceChanged, this);
        }
        this._setValue();
    }
    /**
     * Get whether the editor is dirty.
     */
    get isDirty() {
        return this._dataDirty || this._inputDirty;
    }
    /**
     * Handle the DOM events for the widget.
     *
     * @param event - The DOM event sent to the widget.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the notebook panel's node. It should
     * not be called directly by user code.
     */
    handleEvent(event) {
        switch (event.type) {
            case 'blur':
                this._evtBlur(event);
                break;
            case 'click':
                this._evtClick(event);
                break;
            default:
                break;
        }
    }
    /**
     * Handle `after-attach` messages for the widget.
     */
    onAfterAttach(msg) {
        let node = this.editorHostNode;
        node.addEventListener('blur', this, true);
        node.addEventListener('click', this, true);
        this.revertButtonNode.hidden = true;
        this.commitButtonNode.hidden = true;
        this.headerNode.addEventListener('click', this);
        if (this.isVisible) {
            this.update();
        }
    }
    /**
     * Handle `after-show` messages for the widget.
     */
    onAfterShow(msg) {
        this.update();
    }
    /**
     * Handle `update-request` messages for the widget.
     */
    onUpdateRequest(msg) {
        this.editor.refresh();
    }
    /**
     * Handle `before-detach` messages for the widget.
     */
    onBeforeDetach(msg) {
        let node = this.editorHostNode;
        node.removeEventListener('blur', this, true);
        node.removeEventListener('click', this, true);
        this.headerNode.removeEventListener('click', this);
    }
    /**
     * Handle a change to the metadata of the source.
     */
    _onSourceChanged(sender, args) {
        if (this._changeGuard) {
            return;
        }
        if (this._inputDirty || this.editor.hasFocus()) {
            this._dataDirty = true;
            return;
        }
        this._setValue();
    }
    /**
     * Handle change events.
     */
    _onValueChanged() {
        let valid = true;
        try {
            let value = JSON.parse(this.editor.model.value.text);
            this.removeClass(ERROR_CLASS);
            this._inputDirty =
                !this._changeGuard && !coreutils_1.JSONExt.deepEqual(value, this._originalValue);
        }
        catch (err) {
            this.addClass(ERROR_CLASS);
            this._inputDirty = true;
            valid = false;
        }
        this.revertButtonNode.hidden = !this._inputDirty;
        this.commitButtonNode.hidden = !valid || !this._inputDirty;
    }
    /**
     * Handle blur events for the text area.
     */
    _evtBlur(event) {
        // Update the metadata if necessary.
        if (!this._inputDirty && this._dataDirty) {
            this._setValue();
        }
    }
    /**
     * Handle click events for the buttons.
     */
    _evtClick(event) {
        let target = event.target;
        switch (target) {
            case this.revertButtonNode:
                this._setValue();
                break;
            case this.commitButtonNode:
                if (!this.commitButtonNode.hidden && !this.hasClass(ERROR_CLASS)) {
                    this._changeGuard = true;
                    this._mergeContent();
                    this._changeGuard = false;
                    this._setValue();
                }
                break;
            case this.titleNode:
            case this.collapserNode:
                if (this.collapsible) {
                    let collapser = this.collapserNode;
                    if (collapser.classList.contains(COLLAPSED_CLASS)) {
                        collapser.classList.remove(COLLAPSED_CLASS);
                        this.editorHostNode.classList.remove(COLLAPSED_CLASS);
                    }
                    else {
                        collapser.classList.add(COLLAPSED_CLASS);
                        this.editorHostNode.classList.add(COLLAPSED_CLASS);
                    }
                }
                break;
            case this.editorHostNode:
                this.editor.focus();
                break;
            default:
                break;
        }
    }
    /**
     * Merge the user content.
     */
    _mergeContent() {
        let model = this.editor.model;
        let current = this._source ? this._source.toJSON() : {};
        let old = this._originalValue;
        let user = JSON.parse(model.value.text);
        let source = this.source;
        if (!source) {
            return;
        }
        // If it is in user and has changed from old, set in current.
        for (let key in user) {
            if (!coreutils_1.JSONExt.deepEqual(user[key], old[key] || null)) {
                current[key] = user[key];
            }
        }
        // If it was in old and is not in user, remove from current.
        for (let key in old) {
            if (!(key in user)) {
                delete current[key];
                source.delete(key);
            }
        }
        // Set the values.
        for (let key in current) {
            source.set(key, current[key]);
        }
    }
    /**
     * Set the value given the owner contents.
     */
    _setValue() {
        this._dataDirty = false;
        this._inputDirty = false;
        this.revertButtonNode.hidden = true;
        this.commitButtonNode.hidden = true;
        this.removeClass(ERROR_CLASS);
        let model = this.editor.model;
        let content = this._source ? this._source.toJSON() : {};
        this._changeGuard = true;
        if (content === void 0) {
            model.value.text = 'No data!';
            this._originalValue = coreutils_1.JSONExt.emptyObject;
        }
        else {
            let value = JSON.stringify(content, null, 4);
            model.value.text = value;
            this._originalValue = content;
            // Move the cursor to within the brace.
            if (value.length > 1 && value[0] === '{') {
                this.editor.setCursorPosition({ line: 0, column: 1 });
            }
        }
        this.editor.refresh();
        this._changeGuard = false;
        this.commitButtonNode.hidden = true;
        this.revertButtonNode.hidden = true;
    }
}
exports.JSONEditor = JSONEditor;
/**
 * The namespace for module private data.
 */
var Private;
(function (Private) {
    /**
     * Create the JSON Editor node's content.
     */
    function createEditorContent(options) {
        const revertTitle = 'Revert changes to data';
        const confirmTitle = 'Commit changes to data';
        const title = options.title || '';
        const collapseClass = options.collapsible
            ? `${COLLAPSER_CLASS} ${COLLAPSE_ENABLED_CLASS}`
            : COLLAPSER_CLASS;
        return (React.createElement(React.Fragment, null,
            React.createElement("div", { className: HEADER_CLASS },
                React.createElement("span", { className: TITLE_CLASS }, title),
                React.createElement("span", { className: collapseClass }),
                React.createElement("span", { className: REVERT_CLASS, title: revertTitle }),
                React.createElement("span", { className: COMMIT_CLASS, title: confirmTitle })),
            React.createElement("div", { className: HOST_CLASS })));
    }
    Private.createEditorContent = createEditorContent;
})(Private || (Private = {}));


/***/ }),

/***/ "hBxh":
/*!******************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/nbconvert/index.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const serverconnection_1 = __webpack_require__(/*! ../serverconnection */ "ZWV2");
/**
 * The url for the lab nbconvert service.
 */
const NBCONVERT_SETTINGS_URL = 'api/nbconvert';
/**
 * The nbconvert API service manager.
 */
class NbConvertManager {
    /**
     * Create a new nbconvert manager.
     */
    constructor(options = {}) {
        this.serverSettings =
            options.serverSettings || serverconnection_1.ServerConnection.makeSettings();
    }
    /**
     * Get whether the application should be built.
     */
    getExportFormats() {
        const base = this.serverSettings.baseUrl;
        const url = coreutils_1.URLExt.join(base, NBCONVERT_SETTINGS_URL);
        const { serverSettings } = this;
        const promise = serverconnection_1.ServerConnection.makeRequest(url, {}, serverSettings);
        return promise
            .then(response => {
            if (response.status !== 200) {
                throw new serverconnection_1.ServerConnection.ResponseError(response);
            }
            return response.json();
        })
            .then(data => {
            let exportList = {};
            let keys = Object.keys(data);
            keys.forEach(function (key) {
                let mimeType = data[key].output_mimetype;
                exportList[key] = { output_mimetype: mimeType };
            });
            return exportList;
        });
    }
}
exports.NbConvertManager = NbConvertManager;


/***/ }),

/***/ "hDFp":
/*!***************************************************************!*\
  !*** ./node_modules/jupyterlab-chart-editor/style/plotly.svg ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB3aWR0aD0iMjFweCIgaGVpZ2h0PSIyMHB4IiB2aWV3Qm94PSIwIDAgMjEgMjAiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CiAgICA8IS0tIEdlbmVyYXRvcjogU2tldGNoIDQyICgzNjc4MSkgLSBodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2ggLS0+CiAgICA8dGl0bGU+cGxvdGx5PC90aXRsZT4KICAgIDxkZXNjPkNyZWF0ZWQgd2l0aCBTa2V0Y2guPC9kZXNjPgogICAgPGRlZnM+PC9kZWZzPgogICAgPGcgaWQ9IlBhZ2UtMSIgc3Ryb2tlPSJub25lIiBzdHJva2Utd2lkdGg9IjEiIGZpbGw9Im5vbmUiIGZpbGwtcnVsZT0iZXZlbm9kZCI+CiAgICAgICAgPGcgaWQ9InBsb3RseSIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTIuMDAwMDAwLCAtMi4wMDAwMDApIj4KICAgICAgICAgICAgPGcgaWQ9Ikdyb3VwIj4KICAgICAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbD0iIzQ0N0FEQiIgZmlsbC1ydWxlPSJub256ZXJvIiB4PSIxOS45OTA1OTkiIHk9IjE5LjE4ODMwOTkiIHdpZHRoPSIyLjM2NDQ3NzE2IiBoZWlnaHQ9IjIuODAxMDc5ODEiPjwvcmVjdD4KICAgICAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbD0iIzQ0N0FEQiIgZmlsbC1ydWxlPSJub256ZXJvIiB4PSIxNy4wMzQ5OTQ5IiB5PSIxNi4yODU5OTM3IiB3aWR0aD0iMi4zNjQ0NzcxNiIgaGVpZ2h0PSI1LjcwMzM5NTkzIj48L3JlY3Q+CiAgICAgICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLXBhdGgiIGZpbGw9IiM0NDdBREIiIGZpbGwtcnVsZT0ibm9uemVybyIgeD0iMTQuMTIzMTg3OCIgeT0iMi4wMTA2MTAzMyIgd2lkdGg9IjIuMzY0NDc3MTYiIGhlaWdodD0iMTkuOTc4Nzc5MyI+PC9yZWN0PgogICAgICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS1wYXRoIiBmaWxsPSIjNDQ3QURCIiBmaWxsLXJ1bGU9Im5vbnplcm8iIHg9IjExLjIwNzg0NzciIHk9IjcuNjk3MTM2MTUiIHdpZHRoPSIyLjM2NDQ3NzE2IiBoZWlnaHQ9IjE0LjI5MjI1MzUiPjwvcmVjdD4KICAgICAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbD0iIzQ0N0FEQiIgZmlsbC1ydWxlPSJub256ZXJvIiB4PSI4LjI4NTA4NjI5IiB5PSI0Ljg2MjMxNjEyIiB3aWR0aD0iMi4zNjQ0NzcxNiIgaGVpZ2h0PSIxNy4xMjcwNzM2Ij48L3JlY3Q+CiAgICAgICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLXBhdGgiIGZpbGw9IiM0NDdBREIiIGZpbGwtcnVsZT0ibm9uemVybyIgeD0iNS4yOTY2Mzk1OSIgeT0iMTMuNDI1ODUyOSIgd2lkdGg9IjIuMzY0NDc3MTYiIGhlaWdodD0iOC41NjM1MzY3OCI+PC9yZWN0PgogICAgICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS1wYXRoIiBmaWxsPSIjNDQ3QURCIiBmaWxsLXJ1bGU9Im5vbnplcm8iIHg9IjIuMzczODg4MzIiIHk9IjE5LjIzNjk0ODQiIHdpZHRoPSIyLjM2NDQ3NzE2IiBoZWlnaHQ9IjIuNzUyNDQxMzEiPjwvcmVjdD4KICAgICAgICAgICAgICAgIDxwb2x5Z29uIGlkPSJTaGFwZSIgcG9pbnRzPSIwIDAgMjQgMCAyNCAyNCAwIDI0Ij48L3BvbHlnb24+CiAgICAgICAgICAgIDwvZz4KICAgICAgICA8L2c+CiAgICA8L2c+Cjwvc3ZnPg=="

/***/ }),

/***/ "hDam":
/*!*********************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_add-to-unscopables.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = function () { /* empty */ };


/***/ }),

/***/ "hG2j":
/*!******************************************************!*\
  !*** ./node_modules/@phosphor/coreutils/lib/json.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * The namespace for JSON-specific functions.
 */
var JSONExt;
(function (JSONExt) {
    /**
     * A shared frozen empty JSONObject
     */
    JSONExt.emptyObject = Object.freeze({});
    /**
     * A shared frozen empty JSONArray
     */
    JSONExt.emptyArray = Object.freeze([]);
    /**
     * Test whether a JSON value is a primitive.
     *
     * @param value - The JSON value of interest.
     *
     * @returns `true` if the value is a primitive,`false` otherwise.
     */
    function isPrimitive(value) {
        return (value === null ||
            typeof value === 'boolean' ||
            typeof value === 'number' ||
            typeof value === 'string');
    }
    JSONExt.isPrimitive = isPrimitive;
    function isArray(value) {
        return Array.isArray(value);
    }
    JSONExt.isArray = isArray;
    function isObject(value) {
        return !isPrimitive(value) && !isArray(value);
    }
    JSONExt.isObject = isObject;
    /**
     * Compare two JSON values for deep equality.
     *
     * @param first - The first JSON value of interest.
     *
     * @param second - The second JSON value of interest.
     *
     * @returns `true` if the values are equivalent, `false` otherwise.
     */
    function deepEqual(first, second) {
        // Check referential and primitive equality first.
        if (first === second) {
            return true;
        }
        // If one is a primitive, the `===` check ruled out the other.
        if (isPrimitive(first) || isPrimitive(second)) {
            return false;
        }
        // Test whether they are arrays.
        var a1 = isArray(first);
        var a2 = isArray(second);
        // Bail if the types are different.
        if (a1 !== a2) {
            return false;
        }
        // If they are both arrays, compare them.
        if (a1 && a2) {
            return deepArrayEqual(first, second);
        }
        // At this point, they must both be objects.
        return deepObjectEqual(first, second);
    }
    JSONExt.deepEqual = deepEqual;
    /**
     * Create a deep copy of a JSON value.
     *
     * @param value - The JSON value to copy.
     *
     * @returns A deep copy of the given JSON value.
     */
    function deepCopy(value) {
        // Do nothing for primitive values.
        if (isPrimitive(value)) {
            return value;
        }
        // Deep copy an array.
        if (isArray(value)) {
            return deepArrayCopy(value);
        }
        // Deep copy an object.
        return deepObjectCopy(value);
    }
    JSONExt.deepCopy = deepCopy;
    /**
     * Compare two JSON arrays for deep equality.
     */
    function deepArrayEqual(first, second) {
        // Check referential equality first.
        if (first === second) {
            return true;
        }
        // Test the arrays for equal length.
        if (first.length !== second.length) {
            return false;
        }
        // Compare the values for equality.
        for (var i = 0, n = first.length; i < n; ++i) {
            if (!deepEqual(first[i], second[i])) {
                return false;
            }
        }
        // At this point, the arrays are equal.
        return true;
    }
    /**
     * Compare two JSON objects for deep equality.
     */
    function deepObjectEqual(first, second) {
        // Check referential equality first.
        if (first === second) {
            return true;
        }
        // Check for the first object's keys in the second object.
        for (var key in first) {
            if (!(key in second)) {
                return false;
            }
        }
        // Check for the second object's keys in the first object.
        for (var key in second) {
            if (!(key in first)) {
                return false;
            }
        }
        // Compare the values for equality.
        for (var key in first) {
            if (!deepEqual(first[key], second[key])) {
                return false;
            }
        }
        // At this point, the objects are equal.
        return true;
    }
    /**
     * Create a deep copy of a JSON array.
     */
    function deepArrayCopy(value) {
        var result = new Array(value.length);
        for (var i = 0, n = value.length; i < n; ++i) {
            result[i] = deepCopy(value[i]);
        }
        return result;
    }
    /**
     * Create a deep copy of a JSON object.
     */
    function deepObjectCopy(value) {
        var result = {};
        for (var key in value) {
            result[key] = deepCopy(value[key]);
        }
        return result;
    }
})(JSONExt = exports.JSONExt || (exports.JSONExt = {}));


/***/ }),

/***/ "hI0s":
/*!*********************************************************!*\
  !*** ./node_modules/@jupyterlab/coreutils/lib/index.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(__webpack_require__(/*! ./activitymonitor */ "PZa4"));
__export(__webpack_require__(/*! ./dataconnector */ "XXoZ"));
__export(__webpack_require__(/*! ./markdowncodeblocks */ "Cn7X"));
__export(__webpack_require__(/*! ./nbformat */ "F/Rj"));
__export(__webpack_require__(/*! ./pageconfig */ "JQOU"));
__export(__webpack_require__(/*! ./path */ "Dt/b"));
__export(__webpack_require__(/*! ./settingregistry */ "0KId"));
__export(__webpack_require__(/*! ./statedb */ "tT1j"));
__export(__webpack_require__(/*! ./text */ "6KKe"));
__export(__webpack_require__(/*! ./time */ "WMCC"));
__export(__webpack_require__(/*! ./url */ "huh6"));


/***/ }),

/***/ "hKML":
/*!*************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeLine3dIcon.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeLine3dIcon = function TraceTypeLine3dIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement(
            'g',
            { fill: 'none' },
            _react2.default.createElement('path', { d: 'M0 0h46v46H0z' }),
            _react2.default.createElement('path', { stroke: '#25fdfc', d: 'M23.511 23.571l.005-15.302L37 14.295v15.75l-13.489-6.474z', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2' }),
            _react2.default.createElement('path', { stroke: '#25fdfc', d: 'M23.511 23.571L9.516 30.045l13.929 6.319L37 30.045l-13.489-6.474z', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2' }),
            _react2.default.createElement('path', { stroke: '#25fdfc', d: 'M9.516 30.045v-15.75l13.999-6.026-.004 15.302-13.995 6.474z', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2' }),
            _react2.default.createElement('path', { d: 'M31.536 15.247a6.357 6.357 0 0 1-4.188 6.763c-5.017 2.166-11.255.028-11.255-3.14s5.11-3.87 7.48-3.87 7.48 1.908 7.48 5.684c0 3.654-3.797 5.485-8.216 5.566s-6.744-2.266-6.744-4.104 2.786-3.986 7.458-3.986 7.492 3.526 7.492 5.934a5.722 5.722 0 0 1-2.82 5.074', stroke: '#1d9bfb', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2' })
        )
    );
};

exports.default = TraceTypeLine3dIcon;

/***/ }),

/***/ "hKrs":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/bg.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var bg = moment.defineLocale('bg', {
    months : 'януари_февруари_март_април_май_юни_юли_август_септември_октомври_ноември_декември'.split('_'),
    monthsShort : 'янр_фев_мар_апр_май_юни_юли_авг_сеп_окт_ное_дек'.split('_'),
    weekdays : 'неделя_понеделник_вторник_сряда_четвъртък_петък_събота'.split('_'),
    weekdaysShort : 'нед_пон_вто_сря_чет_пет_съб'.split('_'),
    weekdaysMin : 'нд_пн_вт_ср_чт_пт_сб'.split('_'),
    longDateFormat : {
        LT : 'H:mm',
        LTS : 'H:mm:ss',
        L : 'D.MM.YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY H:mm',
        LLLL : 'dddd, D MMMM YYYY H:mm'
    },
    calendar : {
        sameDay : '[Днес в] LT',
        nextDay : '[Утре в] LT',
        nextWeek : 'dddd [в] LT',
        lastDay : '[Вчера в] LT',
        lastWeek : function () {
            switch (this.day()) {
                case 0:
                case 3:
                case 6:
                    return '[В изминалата] dddd [в] LT';
                case 1:
                case 2:
                case 4:
                case 5:
                    return '[В изминалия] dddd [в] LT';
            }
        },
        sameElse : 'L'
    },
    relativeTime : {
        future : 'след %s',
        past : 'преди %s',
        s : 'няколко секунди',
        ss : '%d секунди',
        m : 'минута',
        mm : '%d минути',
        h : 'час',
        hh : '%d часа',
        d : 'ден',
        dd : '%d дни',
        M : 'месец',
        MM : '%d месеца',
        y : 'година',
        yy : '%d години'
    },
    dayOfMonthOrdinalParse: /\d{1,2}-(ев|ен|ти|ви|ри|ми)/,
    ordinal : function (number) {
        var lastDigit = number % 10,
            last2Digits = number % 100;
        if (number === 0) {
            return number + '-ев';
        } else if (last2Digits === 0) {
            return number + '-ен';
        } else if (last2Digits > 10 && last2Digits < 20) {
            return number + '-ти';
        } else if (lastDigit === 1) {
            return number + '-ви';
        } else if (lastDigit === 2) {
            return number + '-ри';
        } else if (lastDigit === 7 || lastDigit === 8) {
            return number + '-ми';
        } else {
            return number + '-ти';
        }
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return bg;

})));


/***/ }),

/***/ "hMpd":
/*!*****************************************************!*\
  !*** ./node_modules/draft-js/lib/SelectionState.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule SelectionState
 * @format
 * 
 */



function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Immutable = __webpack_require__(/*! immutable */ "JPcv");

var Record = Immutable.Record;


var defaultRecord = {
  anchorKey: '',
  anchorOffset: 0,
  focusKey: '',
  focusOffset: 0,
  isBackward: false,
  hasFocus: false
};

var SelectionStateRecord = Record(defaultRecord);

var SelectionState = function (_SelectionStateRecord) {
  _inherits(SelectionState, _SelectionStateRecord);

  function SelectionState() {
    _classCallCheck(this, SelectionState);

    return _possibleConstructorReturn(this, _SelectionStateRecord.apply(this, arguments));
  }

  SelectionState.prototype.serialize = function serialize() {
    return 'Anchor: ' + this.getAnchorKey() + ':' + this.getAnchorOffset() + ', ' + 'Focus: ' + this.getFocusKey() + ':' + this.getFocusOffset() + ', ' + 'Is Backward: ' + String(this.getIsBackward()) + ', ' + 'Has Focus: ' + String(this.getHasFocus());
  };

  SelectionState.prototype.getAnchorKey = function getAnchorKey() {
    return this.get('anchorKey');
  };

  SelectionState.prototype.getAnchorOffset = function getAnchorOffset() {
    return this.get('anchorOffset');
  };

  SelectionState.prototype.getFocusKey = function getFocusKey() {
    return this.get('focusKey');
  };

  SelectionState.prototype.getFocusOffset = function getFocusOffset() {
    return this.get('focusOffset');
  };

  SelectionState.prototype.getIsBackward = function getIsBackward() {
    return this.get('isBackward');
  };

  SelectionState.prototype.getHasFocus = function getHasFocus() {
    return this.get('hasFocus');
  };

  /**
   * Return whether the specified range overlaps with an edge of the
   * SelectionState.
   */


  SelectionState.prototype.hasEdgeWithin = function hasEdgeWithin(blockKey, start, end) {
    var anchorKey = this.getAnchorKey();
    var focusKey = this.getFocusKey();

    if (anchorKey === focusKey && anchorKey === blockKey) {
      var selectionStart = this.getStartOffset();
      var selectionEnd = this.getEndOffset();
      return start <= selectionEnd && selectionStart <= end;
    }

    if (blockKey !== anchorKey && blockKey !== focusKey) {
      return false;
    }

    var offsetToCheck = blockKey === anchorKey ? this.getAnchorOffset() : this.getFocusOffset();

    return start <= offsetToCheck && end >= offsetToCheck;
  };

  SelectionState.prototype.isCollapsed = function isCollapsed() {
    return this.getAnchorKey() === this.getFocusKey() && this.getAnchorOffset() === this.getFocusOffset();
  };

  SelectionState.prototype.getStartKey = function getStartKey() {
    return this.getIsBackward() ? this.getFocusKey() : this.getAnchorKey();
  };

  SelectionState.prototype.getStartOffset = function getStartOffset() {
    return this.getIsBackward() ? this.getFocusOffset() : this.getAnchorOffset();
  };

  SelectionState.prototype.getEndKey = function getEndKey() {
    return this.getIsBackward() ? this.getAnchorKey() : this.getFocusKey();
  };

  SelectionState.prototype.getEndOffset = function getEndOffset() {
    return this.getIsBackward() ? this.getAnchorOffset() : this.getFocusOffset();
  };

  SelectionState.createEmpty = function createEmpty(key) {
    return new SelectionState({
      anchorKey: key,
      anchorOffset: 0,
      focusKey: key,
      focusOffset: 0,
      isBackward: false,
      hasFocus: false
    });
  };

  return SelectionState;
}(SelectionStateRecord);

module.exports = SelectionState;

/***/ }),

/***/ "hNpt":
/*!************************************************************************!*\
  !*** ./node_modules/@jupyter-widgets/jupyterlab-manager/lib/output.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const outputBase = __importStar(__webpack_require__(/*! @jupyter-widgets/output */ "DypV"));
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const outputarea_1 = __webpack_require__(/*! @jupyterlab/outputarea */ "nGIF");
const jquery_1 = __importDefault(__webpack_require__(/*! jquery */ "EVdn"));
exports.OUTPUT_WIDGET_VERSION = outputBase.OUTPUT_WIDGET_VERSION;
class OutputModel extends outputBase.OutputModel {
    defaults() {
        return Object.assign({}, super.defaults(), { msg_id: '', outputs: [] });
    }
    initialize(attributes, options) {
        super.initialize(attributes, options);
        // The output area model is trusted since widgets are only rendered in trusted contexts.
        this._outputs = new outputarea_1.OutputAreaModel({ trusted: true });
        this._msgHook = (msg) => {
            this.add(msg);
            return false;
        };
        this.widget_manager.context.session.kernelChanged.connect((sender, args) => {
            this._handleKernelChanged(args);
        });
        this.listenTo(this, 'change:msg_id', this.reset_msg_id);
        this.listenTo(this, 'change:outputs', this.setOutputs);
        this.setOutputs();
    }
    /**
     * Register a new kernel
     */
    _handleKernelChanged({ oldValue }) {
        const msgId = this.get('msg_id');
        if (msgId && oldValue) {
            oldValue.removeMessageHook(msgId, this._msgHook);
            this.set('msg_id', null);
        }
    }
    /**
     * Reset the message id.
     */
    reset_msg_id() {
        const kernel = this.widget_manager.context.session.kernel;
        const msgId = this.get('msg_id');
        const oldMsgId = this.previous('msg_id');
        // Clear any old handler.
        if (oldMsgId && kernel) {
            kernel.removeMessageHook(oldMsgId, this._msgHook);
        }
        // Register any new handler.
        if (msgId && kernel) {
            kernel.registerMessageHook(msgId, this._msgHook);
        }
    }
    add(msg) {
        let msgType = msg.header.msg_type;
        switch (msgType) {
            case 'execute_result':
            case 'display_data':
            case 'stream':
            case 'error':
                let model = msg.content;
                model.output_type = msgType;
                this._outputs.add(model);
                this.set('outputs', this._outputs.toJSON(), { newMessage: true });
                this.save_changes();
                break;
            case 'clear_output':
                this.clear_output(msg.content.wait);
                this.set('outputs', [], { newMessage: true });
                this.save_changes();
                break;
            default:
                break;
        }
    }
    clear_output(wait = false) {
        this._outputs.clear(wait);
    }
    get outputs() {
        return this._outputs;
    }
    setOutputs(model, value, options) {
        if (!(options && options.newMessage)) {
            // fromJSON does not clear the existing output
            this.clear_output();
            // fromJSON does not copy the message, so we make a deep copy
            this._outputs.fromJSON(JSON.parse(JSON.stringify(this.get('outputs'))));
        }
    }
}
exports.OutputModel = OutputModel;
class JupyterPhosphorPanelWidget extends widgets_1.Panel {
    constructor(options) {
        let view = options.view;
        delete options.view;
        super(options);
        this._view = view;
    }
    /**
     * Process the phosphor message.
     *
     * Any custom phosphor widget used inside a Jupyter widget should override
     * the processMessage function like this.
     */
    processMessage(msg) {
        super.processMessage(msg);
        this._view.processPhosphorMessage(msg);
    }
    /**
     * Dispose the widget.
     *
     * This causes the view to be destroyed as well with 'remove'
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        super.dispose();
        if (this._view) {
            this._view.remove();
        }
        this._view = null;
    }
}
exports.JupyterPhosphorPanelWidget = JupyterPhosphorPanelWidget;
class OutputView extends outputBase.OutputView {
    _createElement(tagName) {
        this.pWidget = new JupyterPhosphorPanelWidget({ view: this });
        return this.pWidget.node;
    }
    _setElement(el) {
        if (this.el || el !== this.pWidget.node) {
            // Boxes don't allow setting the element beyond the initial creation.
            throw new Error('Cannot reset the DOM element.');
        }
        this.el = this.pWidget.node;
        this.$el = jquery_1.default(this.pWidget.node);
    }
    /**
     * Called when view is rendered.
     */
    render() {
        super.render();
        this._outputView = new outputarea_1.OutputArea({
            rendermime: this.model.widget_manager.rendermime,
            contentFactory: outputarea_1.OutputArea.defaultContentFactory,
            model: this.model.outputs
        });
        // TODO: why is this a readonly property now?
        // this._outputView.model = this.model.outputs;
        // TODO: why is this on the model now?
        // this._outputView.trusted = true;
        this.pWidget.insertWidget(0, this._outputView);
        this.pWidget.addClass('jupyter-widgets');
        this.pWidget.addClass('widget-output');
        this.update(); // Set defaults.
    }
    remove() {
        this._outputView.dispose();
        return super.remove();
    }
}
exports.OutputView = OutputView;


/***/ }),

/***/ "hS6j":
/*!***********************************************!*\
  !*** ./node_modules/htmlparser2/lib/index.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Parser = __webpack_require__(/*! ./Parser.js */ "WASD");
var DomHandler = __webpack_require__(/*! domhandler */ "Nsz2");

function defineProp(name, value) {
    delete module.exports[name];
    module.exports[name] = value;
    return value;
}

module.exports = {
    Parser: Parser,
    Tokenizer: __webpack_require__(/*! ./Tokenizer.js */ "b70m"),
    ElementType: __webpack_require__(/*! domelementtype */ "TR4g"),
    DomHandler: DomHandler,
    get FeedHandler() {
        return defineProp("FeedHandler", __webpack_require__(/*! ./FeedHandler.js */ "Uwf0"));
    },
    get Stream() {
        return defineProp("Stream", __webpack_require__(/*! ./Stream.js */ "0ejA"));
    },
    get WritableStream() {
        return defineProp("WritableStream", __webpack_require__(/*! ./WritableStream.js */ "h2lD"));
    },
    get ProxyHandler() {
        return defineProp("ProxyHandler", __webpack_require__(/*! ./ProxyHandler.js */ "vX2W"));
    },
    get DomUtils() {
        return defineProp("DomUtils", __webpack_require__(/*! domutils */ "D5Sy"));
    },
    get CollectingHandler() {
        return defineProp(
            "CollectingHandler",
            __webpack_require__(/*! ./CollectingHandler.js */ "0fF6")
        );
    },
    // For legacy support
    DefaultHandler: DomHandler,
    get RssHandler() {
        return defineProp("RssHandler", this.FeedHandler);
    },
    //helper methods
    parseDOM: function(data, options) {
        var handler = new DomHandler(options);
        new Parser(handler, options).end(data);
        return handler.dom;
    },
    parseFeed: function(feed, options) {
        var handler = new module.exports.FeedHandler(options);
        new Parser(handler, options).end(feed);
        return handler.dom;
    },
    createDomStream: function(cb, options, elementCb) {
        var handler = new DomHandler(cb, options, elementCb);
        return new Parser(handler, options);
    },
    // List of all events that the parser emits
    EVENTS: {
        /* Format: eventname: number of arguments */
        attribute: 2,
        cdatastart: 0,
        cdataend: 0,
        text: 1,
        processinginstruction: 2,
        comment: 1,
        commentend: 0,
        closetag: 1,
        opentag: 2,
        opentagname: 1,
        error: 1,
        end: 0
    }
};


/***/ }),

/***/ "hVAS":
/*!********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotTube3dIcon.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotTube3dIcon = function PlotTube3dIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M1.313 32h4c.75 0 1.375-.625 1.375-1.313V19.999c0-.75-.625-1.313-1.375-1.313h-4A1.32 1.32 0 0 0 0 19.999v10.688C0 31.375.625 32 1.313 32zm1.375-2.687v-8h1.313v8zM20 6.688h10.688c.688 0 1.313-.625 1.313-1.375v-4C32.001.625 31.376 0 30.688 0H20a1.32 1.32 0 0 0-1.313 1.313v4c0 .75.563 1.375 1.313 1.375zm1.313-4h8v1.313h-8zM20 5.313v9c0 3.75-1.938 5.688-5.5 5.688H5.312c-.688 0-1.313.625-1.313 1.313v8c0 .75.625 1.375 1.313 1.375H14.5c8.75 0 16.188-7.563 16.188-16.375v-9c0-.688-.625-1.313-1.375-1.313h-8c-.688 0-1.313.625-1.313 1.313zm2.688 1.375h5.313v7.625c0 7.375-6.188 13.688-13.5 13.688H6.688v-5.313h7.813c5 0 8.188-3.125 8.188-8.375z' })
    );
};

exports.default = PlotTube3dIcon;

/***/ }),

/***/ "hZ7w":
/*!**************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeScatterIcon.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeScatterIcon = function TraceTypeScatterIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement('path', { fill: 'none', d: 'M0 0h46v46H0z' }),
        _react2.default.createElement('circle', { cx: '13', cy: '32', r: '3', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '21', cy: '27', r: '3', fill: '#25fdfc' }),
        _react2.default.createElement('circle', { cx: '23', cy: '18', r: '3', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '32', cy: '24', r: '3', fill: '#25fdfc' }),
        _react2.default.createElement('circle', { cx: '32', cy: '11', r: '3', fill: '#25fdfc' })
    );
};

exports.default = TraceTypeScatterIcon;

/***/ }),

/***/ "hbMA":
/*!*******************************************************!*\
  !*** ./node_modules/asn1.js/lib/asn1/encoders/pem.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var inherits = __webpack_require__(/*! inherits */ "P7XM");

var DEREncoder = __webpack_require__(/*! ./der */ "N2jm");

function PEMEncoder(entity) {
  DEREncoder.call(this, entity);
  this.enc = 'pem';
};
inherits(PEMEncoder, DEREncoder);
module.exports = PEMEncoder;

PEMEncoder.prototype.encode = function encode(data, options) {
  var buf = DEREncoder.prototype.encode.call(this, data);

  var p = buf.toString('base64');
  var out = [ '-----BEGIN ' + options.label + '-----' ];
  for (var i = 0; i < p.length; i += 64)
    out.push(p.slice(i, i + 64));
  out.push('-----END ' + options.label + '-----');
  return out.join('\n');
};


/***/ }),

/***/ "hcLw":
/*!************************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/apputils-extension/style/splash.css ***!
  \************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var escape = __webpack_require__(/*! ../../../css-loader/lib/url/escape.js */ "sEG9");
exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2016, Jupyter Development Team.\n|\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n#jupyterlab-splash {\n  z-index: 10;\n  position: absolute;\n  overflow: hidden;\n  width: 100%;\n  height: 100%;\n  background-position: center 40%;\n  background-repeat: no-repeat;\n  background-size: cover;\n}\n\n#jupyterlab-splash.light {\n  background-color: white;\n}\n\n#jupyterlab-splash.dark {\n  background-color: var(--md-grey-900);\n}\n\n.splash-fade {\n  animation: 0.5s fade-out forwards;\n}\n\n#galaxy {\n  position: relative;\n  width: 100%;\n  height: 100%;\n}\n\n#main-logo {\n  background-image: url(" + escape(__webpack_require__(/*! ./images/jupyter-favicon.svg */ "0cA8")) + ");\n  background-repeat: no-repeat;\n  background-size: 100px;\n  position: absolute;\n  background-position: center;\n  width: 100%;\n  height: 100%;\n  z-index: 1;\n  animation: 0.3s fade-in linear forwards;\n}\n\n.planet {\n  background-repeat: no-repeat;\n  background-size: cover;\n  animation-iteration-count: infinite;\n  animation-name: orbit;\n}\n\n#moon1.orbit {\n  opacity: 1;\n  animation: orbit 2s ease;\n  width: 200px;\n  height: 140px;\n  margin-top: -53px;\n  margin-left: -54px;\n}\n\n#moon2.orbit {\n  opacity: 1;\n  animation: orbit 2s ease;\n  width: 132px;\n  height: 180px;\n  margin-top: -66px;\n  margin-left: -85px;\n}\n\n#moon3.orbit {\n  opacity: 1;\n  display: flex;\n  align-items: flex-end;\n  animation: orbit 2s ease;\n  width: 220px;\n  height: 166px;\n  margin-top: -96px;\n  margin-left: -50px;\n}\n\n#moon1 .planet {\n  height: 12px;\n  width: 12px;\n  border-radius: 50%;\n}\n\n#moon2 .planet {\n  height: 16px;\n  width: 16px;\n  border-radius: 50%;\n  float: right;\n}\n\n#moon3 .planet {\n  height: 20px;\n  width: 20px;\n  border-radius: 50%;\n}\n\n#jupyterlab-splash.light #moon1 .planet {\n  background-color: #6f7070;\n}\n\n#jupyterlab-splash.light #moon2 .planet {\n  background-color: #767677;\n}\n\n#jupyterlab-splash.light #moon3 .planet {\n  background-color: #989798;\n}\n\n#jupyterlab-splash.dark #moon1 .planet,\n#jupyterlab-splash.dark #moon2 .planet,\n#jupyterlab-splash.dark #moon3 .planet {\n  background-color: white;\n}\n\n.orbit {\n  animation-iteration-count: 1;\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  border-radius: 50%;\n}\n\n@keyframes orbit {\n  0% {\n    transform: rotateZ(0deg);\n  }\n  100% {\n    transform: rotateZ(-720deg);\n  }\n}\n\n@keyframes orbit2 {\n  0% {\n    transform: rotateZ(0deg);\n  }\n  100% {\n    transform: rotateZ(720deg);\n  }\n}\n\n@keyframes fade-in {\n  0% {\n    opacity: 0;\n  }\n  100% {\n    opacity: 1;\n  }\n}\n\n@keyframes fade-out {\n  0% {\n    opacity: 1;\n  }\n  100% {\n    opacity: 0;\n  }\n}\n", ""]);

// exports


/***/ }),

/***/ "heNW":
/*!***************************************!*\
  !*** ./node_modules/lodash/_apply.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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);
}

module.exports = apply;


/***/ }),

/***/ "hgQt":
/*!**************************************!*\
  !*** ./node_modules/lodash/hasIn.js ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseHasIn = __webpack_require__(/*! ./_baseHasIn */ "Juji"),
    hasPath = __webpack_require__(/*! ./_hasPath */ "4sDh");

/**
 * 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);
}

module.exports = hasIn;


/***/ }),

/***/ "hiFl":
/*!*********************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeScatterternaryIcon.js ***!
  \*********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeScatterternaryIcon = function TraceTypeScatterternaryIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement('path', { fill: 'none', d: 'M0 0h46v46H0z' }),
        _react2.default.createElement('path', { fill: '#25fdfc', d: 'M23 6l17 32H6L23 6z' }),
        _react2.default.createElement('circle', { cx: '19', cy: '22', r: '2', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '23', cy: '17', r: '2', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '23', cy: '30', r: '2', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '27', cy: '26', r: '2', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '17', cy: '35', r: '2', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '28', cy: '34', r: '2', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '11', cy: '35', r: '2', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '32', cy: '30', r: '2', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '23', cy: '12', r: '2', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '35', cy: '35', r: '2', fill: '#1d9bfb' })
    );
};

exports.default = TraceTypeScatterternaryIcon;

/***/ }),

/***/ "hlmY":
/*!**************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/codemirror/theme/seti.css ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*\n\n    Name:       seti\n    Author:     Michael Kaminsky (http://github.com/mkaminsky11)\n\n    Original seti color scheme by Jesse Weed (https://github.com/jesseweed/seti-syntax)\n\n*/\n\n\n.cm-s-seti.CodeMirror {\n  background-color: #151718 !important;\n  color: #CFD2D1 !important;\n  border: none;\n}\n.cm-s-seti .CodeMirror-gutters {\n  color: #404b53;\n  background-color: #0E1112;\n  border: none;\n}\n.cm-s-seti .CodeMirror-cursor { border-left: solid thin #f8f8f0; }\n.cm-s-seti .CodeMirror-linenumber { color: #6D8A88; }\n.cm-s-seti.CodeMirror-focused div.CodeMirror-selected { background: rgba(255, 255, 255, 0.10); }\n.cm-s-seti .CodeMirror-line::selection, .cm-s-seti .CodeMirror-line > span::selection, .cm-s-seti .CodeMirror-line > span > span::selection { background: rgba(255, 255, 255, 0.10); }\n.cm-s-seti .CodeMirror-line::-moz-selection, .cm-s-seti .CodeMirror-line > span::-moz-selection, .cm-s-seti .CodeMirror-line > span > span::-moz-selection { background: rgba(255, 255, 255, 0.10); }\n.cm-s-seti span.cm-comment { color: #41535b; }\n.cm-s-seti span.cm-string, .cm-s-seti span.cm-string-2 { color: #55b5db; }\n.cm-s-seti span.cm-number { color: #cd3f45; }\n.cm-s-seti span.cm-variable { color: #55b5db; }\n.cm-s-seti span.cm-variable-2 { color: #a074c4; }\n.cm-s-seti span.cm-def { color: #55b5db; }\n.cm-s-seti span.cm-keyword { color: #ff79c6; }\n.cm-s-seti span.cm-operator { color: #9fca56; }\n.cm-s-seti span.cm-keyword { color: #e6cd69; }\n.cm-s-seti span.cm-atom { color: #cd3f45; }\n.cm-s-seti span.cm-meta { color: #55b5db; }\n.cm-s-seti span.cm-tag { color: #55b5db; }\n.cm-s-seti span.cm-attribute { color: #9fca56; }\n.cm-s-seti span.cm-qualifier { color: #9fca56; }\n.cm-s-seti span.cm-property { color: #a074c4; }\n.cm-s-seti span.cm-variable-3, .cm-s-seti span.cm-type { color: #9fca56; }\n.cm-s-seti span.cm-builtin { color: #9fca56; }\n.cm-s-seti .CodeMirror-activeline-background { background: #101213; }\n.cm-s-seti .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; }\n", ""]);

// exports


/***/ }),

/***/ "hmv/":
/*!***********************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyter-widgets/controls/css/widgets-base.css ***!
  \***********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports
exports.i(__webpack_require__(/*! -!../../../css-loader!./phosphor.css */ "W3a3"), "");

// module
exports.push([module.i, "/* Copyright (c) Jupyter Development Team.\n * Distributed under the terms of the Modified BSD License.\n */\n\n/*\n * We assume that the CSS variables in\n * https://github.com/jupyterlab/jupyterlab/blob/master/src/default-theme/variables.css\n * have been defined.\n */\n\n:root {\n    --jp-widgets-color: var(--jp-content-font-color1);\n    --jp-widgets-label-color: var(--jp-widgets-color);\n    --jp-widgets-readout-color: var(--jp-widgets-color);\n    --jp-widgets-font-size: var(--jp-ui-font-size1);\n    --jp-widgets-margin: 2px;\n    --jp-widgets-inline-height: 28px;\n    --jp-widgets-inline-width: 300px;\n    --jp-widgets-inline-width-short: calc(var(--jp-widgets-inline-width) / 2 - var(--jp-widgets-margin));\n    --jp-widgets-inline-width-tiny: calc(var(--jp-widgets-inline-width-short) / 2 - var(--jp-widgets-margin));\n    --jp-widgets-inline-margin: 4px; /* margin between inline elements */\n    --jp-widgets-inline-label-width: 80px;\n    --jp-widgets-border-width: var(--jp-border-width);\n    --jp-widgets-vertical-height: 200px;\n    --jp-widgets-horizontal-tab-height: 24px;\n    --jp-widgets-horizontal-tab-width: 144px;\n    --jp-widgets-horizontal-tab-top-border: 2px;\n    --jp-widgets-progress-thickness: 20px;\n    --jp-widgets-container-padding: 15px;\n    --jp-widgets-input-padding: 4px;\n    --jp-widgets-radio-item-height-adjustment: 8px;\n    --jp-widgets-radio-item-height: calc(var(--jp-widgets-inline-height) - var(--jp-widgets-radio-item-height-adjustment));\n    --jp-widgets-slider-track-thickness: 4px;\n    --jp-widgets-slider-border-width: var(--jp-widgets-border-width);\n    --jp-widgets-slider-handle-size: 16px;\n    --jp-widgets-slider-handle-border-color: var(--jp-border-color1);\n    --jp-widgets-slider-handle-background-color: var(--jp-layout-color1);\n    --jp-widgets-slider-active-handle-color: var(--jp-brand-color1);\n    --jp-widgets-menu-item-height: 24px;\n    --jp-widgets-dropdown-arrow: url(\"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDE5LjIuMSwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPgo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IkxheWVyXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4IgoJIHZpZXdCb3g9IjAgMCAxOCAxOCIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgMTggMTg7IiB4bWw6c3BhY2U9InByZXNlcnZlIj4KPHN0eWxlIHR5cGU9InRleHQvY3NzIj4KCS5zdDB7ZmlsbDpub25lO30KPC9zdHlsZT4KPHBhdGggZD0iTTUuMiw1LjlMOSw5LjdsMy44LTMuOGwxLjIsMS4ybC00LjksNWwtNC45LTVMNS4yLDUuOXoiLz4KPHBhdGggY2xhc3M9InN0MCIgZD0iTTAtMC42aDE4djE4SDBWLTAuNnoiLz4KPC9zdmc+Cg\");\n    --jp-widgets-input-color: var(--jp-ui-font-color1);\n    --jp-widgets-input-background-color: var(--jp-layout-color1);\n    --jp-widgets-input-border-color: var(--jp-border-color1);\n    --jp-widgets-input-focus-border-color: var(--jp-brand-color2);\n    --jp-widgets-input-border-width: var(--jp-widgets-border-width);\n    --jp-widgets-disabled-opacity: 0.6;\n\n    /* From Material Design Lite */\n    --md-shadow-key-umbra-opacity: 0.2;\n    --md-shadow-key-penumbra-opacity: 0.14;\n    --md-shadow-ambient-shadow-opacity: 0.12;\n}\n\n.jupyter-widgets {\n    margin: var(--jp-widgets-margin);\n    box-sizing: border-box;\n    color: var(--jp-widgets-color);\n    overflow: visible;\n}\n\n.jupyter-widgets.jupyter-widgets-disconnected::before {\n    line-height: var(--jp-widgets-inline-height);\n    height: var(--jp-widgets-inline-height);\n}\n\n.jp-Output-result > .jupyter-widgets {\n    margin-left: 0;\n    margin-right: 0;\n}\n\n/* vbox and hbox */\n\n.widget-inline-hbox {\n    /* Horizontal widgets */\n    box-sizing: border-box;\n    display: flex;\n    flex-direction: row;\n    align-items: baseline;\n}\n\n.widget-inline-vbox {\n    /* Vertical Widgets */\n    box-sizing: border-box;\n    display: flex;\n    flex-direction: column;\n    align-items: center;\n}\n\n.widget-box {\n    box-sizing: border-box;\n    display: flex;\n    margin: 0;\n    overflow: auto;\n}\n\n.widget-gridbox {\n    box-sizing: border-box;\n    display: grid;\n    margin: 0;\n    overflow: auto;\n}\n\n.widget-hbox {\n    flex-direction: row;\n}\n\n.widget-vbox {\n    flex-direction: column;\n}\n\n/* General Button Styling */\n\n.jupyter-button {\n    padding-left: 10px;\n    padding-right: 10px;\n    padding-top: 0px;\n    padding-bottom: 0px;\n    display: inline-block;\n    white-space: nowrap;\n    overflow: hidden;\n    text-overflow: ellipsis;\n    text-align: center;\n    font-size: var(--jp-widgets-font-size);\n    cursor: pointer;\n\n    height: var(--jp-widgets-inline-height);\n    border: 0px solid;\n    line-height: var(--jp-widgets-inline-height);\n    box-shadow: none;\n\n    color: var(--jp-ui-font-color1);\n    background-color: var(--jp-layout-color2);\n    border-color: var(--jp-border-color2);\n    border: none;\n}\n\n.jupyter-button i.fa {\n    margin-right: var(--jp-widgets-inline-margin);\n    pointer-events: none;\n}\n\n.jupyter-button:empty:before {\n    content: \"\\200B\"; /* zero-width space */\n}\n\n.jupyter-widgets.jupyter-button:disabled {\n    opacity: var(--jp-widgets-disabled-opacity);\n}\n\n.jupyter-button i.fa.center {\n    margin-right: 0;\n}\n\n.jupyter-button:hover:enabled, .jupyter-button:focus:enabled {\n    /* MD Lite 2dp shadow */\n    box-shadow: 0 2px 2px 0 rgba(0, 0, 0, var(--md-shadow-key-penumbra-opacity)),\n                0 3px 1px -2px rgba(0, 0, 0, var(--md-shadow-key-umbra-opacity)),\n                0 1px 5px 0 rgba(0, 0, 0, var(--md-shadow-ambient-shadow-opacity));\n}\n\n.jupyter-button:active, .jupyter-button.mod-active {\n    /* MD Lite 4dp shadow */\n    box-shadow: 0 4px 5px 0 rgba(0, 0, 0, var(--md-shadow-key-penumbra-opacity)),\n                0 1px 10px 0 rgba(0, 0, 0, var(--md-shadow-ambient-shadow-opacity)),\n                0 2px 4px -1px rgba(0, 0, 0, var(--md-shadow-key-umbra-opacity));\n    color: var(--jp-ui-font-color1);\n    background-color: var(--jp-layout-color3);\n}\n\n.jupyter-button:focus:enabled {\n    outline: 1px solid var(--jp-widgets-input-focus-border-color);\n}\n\n/* Button \"Primary\" Styling */\n\n.jupyter-button.mod-primary {\n    color: var(--jp-inverse-ui-font-color1);\n    background-color: var(--jp-brand-color1);\n}\n\n.jupyter-button.mod-primary.mod-active {\n    color: var(--jp-inverse-ui-font-color0);\n    background-color: var(--jp-brand-color0);\n}\n\n.jupyter-button.mod-primary:active {\n    color: var(--jp-inverse-ui-font-color0);\n    background-color: var(--jp-brand-color0);\n}\n\n/* Button \"Success\" Styling */\n\n.jupyter-button.mod-success {\n    color: var(--jp-inverse-ui-font-color1);\n    background-color: var(--jp-success-color1);\n}\n\n.jupyter-button.mod-success.mod-active {\n    color: var(--jp-inverse-ui-font-color0);\n    background-color: var(--jp-success-color0);\n }\n\n.jupyter-button.mod-success:active {\n    color: var(--jp-inverse-ui-font-color0);\n    background-color: var(--jp-success-color0);\n }\n\n /* Button \"Info\" Styling */\n\n.jupyter-button.mod-info {\n    color: var(--jp-inverse-ui-font-color1);\n    background-color: var(--jp-info-color1);\n}\n\n.jupyter-button.mod-info.mod-active {\n    color: var(--jp-inverse-ui-font-color0);\n    background-color: var(--jp-info-color0);\n}\n\n.jupyter-button.mod-info:active {\n    color: var(--jp-inverse-ui-font-color0);\n    background-color: var(--jp-info-color0);\n}\n\n/* Button \"Warning\" Styling */\n\n.jupyter-button.mod-warning {\n    color: var(--jp-inverse-ui-font-color1);\n    background-color: var(--jp-warn-color1);\n}\n\n.jupyter-button.mod-warning.mod-active {\n    color: var(--jp-inverse-ui-font-color0);\n    background-color: var(--jp-warn-color0);\n}\n\n.jupyter-button.mod-warning:active {\n    color: var(--jp-inverse-ui-font-color0);\n    background-color: var(--jp-warn-color0);\n}\n\n/* Button \"Danger\" Styling */\n\n.jupyter-button.mod-danger {\n    color: var(--jp-inverse-ui-font-color1);\n    background-color: var(--jp-error-color1);\n}\n\n.jupyter-button.mod-danger.mod-active {\n    color: var(--jp-inverse-ui-font-color0);\n    background-color: var(--jp-error-color0);\n}\n\n.jupyter-button.mod-danger:active {\n    color: var(--jp-inverse-ui-font-color0);\n    background-color: var(--jp-error-color0);\n}\n\n/* Widget Button*/\n\n.widget-button, .widget-toggle-button {\n    width: var(--jp-widgets-inline-width-short);\n}\n\n/* Widget Label Styling */\n\n/* Override Bootstrap label css */\n.jupyter-widgets label {\n    margin-bottom: initial;\n}\n\n.widget-label-basic {\n    /* Basic Label */\n    color: var(--jp-widgets-label-color);\n    font-size: var(--jp-widgets-font-size);\n    overflow: hidden;\n    text-overflow: ellipsis;\n    white-space: nowrap;\n    line-height: var(--jp-widgets-inline-height);\n}\n\n.widget-label {\n    /* Label */\n    color: var(--jp-widgets-label-color);\n    font-size: var(--jp-widgets-font-size);\n    overflow: hidden;\n    text-overflow: ellipsis;\n    white-space: nowrap;\n    line-height: var(--jp-widgets-inline-height);\n}\n\n.widget-inline-hbox .widget-label {\n    /* Horizontal Widget Label */\n    color: var(--jp-widgets-label-color);\n    text-align: right;\n    margin-right: calc( var(--jp-widgets-inline-margin) * 2 );\n    width: var(--jp-widgets-inline-label-width);\n    flex-shrink: 0;\n}\n\n.widget-inline-vbox .widget-label {\n    /* Vertical Widget Label */\n    color: var(--jp-widgets-label-color);\n    text-align: center;\n    line-height: var(--jp-widgets-inline-height);\n}\n\n/* Widget Readout Styling */\n\n.widget-readout {\n    color: var(--jp-widgets-readout-color);\n    font-size: var(--jp-widgets-font-size);\n    height: var(--jp-widgets-inline-height);\n    line-height: var(--jp-widgets-inline-height);\n    overflow: hidden;\n    white-space: nowrap;\n    text-align: center;\n}\n\n.widget-readout.overflow {\n    /* Overflowing Readout */\n\n    /* From Material Design Lite\n        shadow-key-umbra-opacity: 0.2;\n        shadow-key-penumbra-opacity: 0.14;\n        shadow-ambient-shadow-opacity: 0.12;\n     */\n    -webkit-box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.2),\n                        0 3px 1px -2px rgba(0, 0, 0, 0.14),\n                        0 1px 5px 0 rgba(0, 0, 0, 0.12);\n\n    -moz-box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.2),\n                     0 3px 1px -2px rgba(0, 0, 0, 0.14),\n                     0 1px 5px 0 rgba(0, 0, 0, 0.12);\n\n    box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.2),\n                0 3px 1px -2px rgba(0, 0, 0, 0.14),\n                0 1px 5px 0 rgba(0, 0, 0, 0.12);\n}\n\n.widget-inline-hbox .widget-readout {\n    /* Horizontal Readout */\n    text-align: center;\n    max-width: var(--jp-widgets-inline-width-short);\n    min-width: var(--jp-widgets-inline-width-tiny);\n    margin-left: var(--jp-widgets-inline-margin);\n}\n\n.widget-inline-vbox .widget-readout {\n    /* Vertical Readout */\n    margin-top: var(--jp-widgets-inline-margin);\n    /* as wide as the widget */\n    width: inherit;\n}\n\n/* Widget Checkbox Styling */\n\n.widget-checkbox {\n    width: var(--jp-widgets-inline-width);\n    height: var(--jp-widgets-inline-height);\n    line-height: var(--jp-widgets-inline-height);\n}\n\n.widget-checkbox input[type=\"checkbox\"] {\n    margin: 0px calc( var(--jp-widgets-inline-margin) * 2 ) 0px 0px;\n    line-height: var(--jp-widgets-inline-height);\n    font-size: large;\n    flex-grow: 1;\n    flex-shrink: 0;\n    align-self: center;\n}\n\n/* Widget Valid Styling */\n\n.widget-valid {\n    height: var(--jp-widgets-inline-height);\n    line-height: var(--jp-widgets-inline-height);\n    width: var(--jp-widgets-inline-width-short);\n    font-size: var(--jp-widgets-font-size);\n}\n\n.widget-valid i:before {\n    line-height: var(--jp-widgets-inline-height);\n    margin-right: var(--jp-widgets-inline-margin);\n    margin-left: var(--jp-widgets-inline-margin);\n\n    /* from the fa class in FontAwesome: https://github.com/FortAwesome/Font-Awesome/blob/49100c7c3a7b58d50baa71efef11af41a66b03d3/css/font-awesome.css#L14 */\n    display: inline-block;\n    font: normal normal normal 14px/1 FontAwesome;\n    font-size: inherit;\n    text-rendering: auto;\n    -webkit-font-smoothing: antialiased;\n    -moz-osx-font-smoothing: grayscale;\n}\n\n.widget-valid.mod-valid i:before {\n    content: \"\\F00C\";\n    color: green;\n}\n\n.widget-valid.mod-invalid i:before {\n    content: \"\\F00D\";\n    color: red;\n}\n\n.widget-valid.mod-valid .widget-valid-readout {\n    display: none;\n}\n\n/* Widget Text and TextArea Stying */\n\n.widget-textarea, .widget-text {\n    width: var(--jp-widgets-inline-width);\n}\n\n.widget-text input[type=\"text\"], .widget-text input[type=\"number\"]{\n    height: var(--jp-widgets-inline-height);\n    line-height: var(--jp-widgets-inline-height);\n}\n\n.widget-text input[type=\"text\"]:disabled, .widget-text input[type=\"number\"]:disabled, .widget-textarea textarea:disabled {\n    opacity: var(--jp-widgets-disabled-opacity);\n}\n\n.widget-text input[type=\"text\"], .widget-text input[type=\"number\"], .widget-textarea textarea {\n    box-sizing: border-box;\n    border: var(--jp-widgets-input-border-width) solid var(--jp-widgets-input-border-color);\n    background-color: var(--jp-widgets-input-background-color);\n    color: var(--jp-widgets-input-color);\n    font-size: var(--jp-widgets-font-size);\n    padding: var(--jp-widgets-input-padding) calc( var(--jp-widgets-input-padding) *  2 );\n    flex-grow: 1;\n    min-width: 0; /* This makes it possible for the flexbox to shrink this input */\n    flex-shrink: 1;\n    outline: none !important;\n}\n\n.widget-textarea textarea {\n    height: inherit;\n    width: inherit;\n}\n\n.widget-text input:focus, .widget-textarea textarea:focus {\n    border-color: var(--jp-widgets-input-focus-border-color);\n}\n\n/* Widget Slider */\n\n.widget-slider .ui-slider {\n    /* Slider Track */\n    border: var(--jp-widgets-slider-border-width) solid var(--jp-layout-color3);\n    background: var(--jp-layout-color3);\n    box-sizing: border-box;\n    position: relative;\n    border-radius: 0px;\n}\n\n.widget-slider .ui-slider .ui-slider-handle {\n    /* Slider Handle */\n    outline: none !important; /* focused slider handles are colored - see below */\n    position: absolute;\n    background-color: var(--jp-widgets-slider-handle-background-color);\n    border: var(--jp-widgets-slider-border-width) solid var(--jp-widgets-slider-handle-border-color);\n    box-sizing: border-box;\n    z-index: 1;\n    background-image: none; /* Override jquery-ui */\n}\n\n/* Override jquery-ui */\n.widget-slider .ui-slider .ui-slider-handle:hover, .widget-slider .ui-slider .ui-slider-handle:focus {\n    background-color: var(--jp-widgets-slider-active-handle-color);\n    border: var(--jp-widgets-slider-border-width) solid var(--jp-widgets-slider-active-handle-color);\n}\n\n.widget-slider .ui-slider .ui-slider-handle:active {\n    background-color: var(--jp-widgets-slider-active-handle-color);\n    border-color: var(--jp-widgets-slider-active-handle-color);\n    z-index: 2;\n    transform: scale(1.2);\n}\n\n.widget-slider  .ui-slider .ui-slider-range {\n    /* Interval between the two specified value of a double slider */\n    position: absolute;\n    background: var(--jp-widgets-slider-active-handle-color);\n    z-index: 0;\n}\n\n/* Shapes of Slider Handles */\n\n.widget-hslider .ui-slider .ui-slider-handle {\n    width: var(--jp-widgets-slider-handle-size);\n    height: var(--jp-widgets-slider-handle-size);\n    margin-top: calc((var(--jp-widgets-slider-track-thickness) - var(--jp-widgets-slider-handle-size)) / 2 - var(--jp-widgets-slider-border-width));\n    margin-left: calc(var(--jp-widgets-slider-handle-size) / -2 + var(--jp-widgets-slider-border-width));\n    border-radius: 50%;\n    top: 0;\n}\n\n.widget-vslider .ui-slider .ui-slider-handle {\n    width: var(--jp-widgets-slider-handle-size);\n    height: var(--jp-widgets-slider-handle-size);\n    margin-bottom: calc(var(--jp-widgets-slider-handle-size) / -2 + var(--jp-widgets-slider-border-width));\n    margin-left: calc((var(--jp-widgets-slider-track-thickness) - var(--jp-widgets-slider-handle-size)) / 2 - var(--jp-widgets-slider-border-width));\n    border-radius: 50%;\n    left: 0;\n}\n\n.widget-hslider .ui-slider .ui-slider-range {\n    height: calc( var(--jp-widgets-slider-track-thickness) * 2 );\n    margin-top: calc((var(--jp-widgets-slider-track-thickness) - var(--jp-widgets-slider-track-thickness) * 2 ) / 2 - var(--jp-widgets-slider-border-width));\n}\n\n.widget-vslider .ui-slider .ui-slider-range {\n    width: calc( var(--jp-widgets-slider-track-thickness) * 2 );\n    margin-left: calc((var(--jp-widgets-slider-track-thickness) - var(--jp-widgets-slider-track-thickness) * 2 ) / 2 - var(--jp-widgets-slider-border-width));\n}\n\n/* Horizontal Slider */\n\n.widget-hslider {\n    width: var(--jp-widgets-inline-width);\n    height: var(--jp-widgets-inline-height);\n    line-height: var(--jp-widgets-inline-height);\n\n    /* Override the align-items baseline. This way, the description and readout\n    still seem to align their baseline properly, and we don't have to have\n    align-self: stretch in the .slider-container. */\n    align-items: center;\n}\n\n.widgets-slider .slider-container {\n    overflow: visible;\n}\n\n.widget-hslider .slider-container {\n    height: var(--jp-widgets-inline-height);\n    margin-left: calc(var(--jp-widgets-slider-handle-size) / 2 - 2 * var(--jp-widgets-slider-border-width));\n    margin-right: calc(var(--jp-widgets-slider-handle-size) / 2 - 2 * var(--jp-widgets-slider-border-width));\n    flex: 1 1 var(--jp-widgets-inline-width-short);\n}\n\n.widget-hslider .ui-slider {\n    /* Inner, invisible slide div */\n    height: var(--jp-widgets-slider-track-thickness);\n    margin-top: calc((var(--jp-widgets-inline-height) - var(--jp-widgets-slider-track-thickness)) / 2);\n    width: 100%;\n}\n\n/* Vertical Slider */\n\n.widget-vbox .widget-label {\n    height: var(--jp-widgets-inline-height);\n    line-height: var(--jp-widgets-inline-height);\n}\n\n.widget-vslider {\n    /* Vertical Slider */\n    height: var(--jp-widgets-vertical-height);\n    width: var(--jp-widgets-inline-width-tiny);\n}\n\n.widget-vslider .slider-container {\n    flex: 1 1 var(--jp-widgets-inline-width-short);\n    margin-left: auto;\n    margin-right: auto;\n    margin-bottom: calc(var(--jp-widgets-slider-handle-size) / 2 - 2 * var(--jp-widgets-slider-border-width));\n    margin-top: calc(var(--jp-widgets-slider-handle-size) / 2 - 2 * var(--jp-widgets-slider-border-width));\n    display: flex;\n    flex-direction: column;\n}\n\n.widget-vslider .ui-slider-vertical {\n    /* Inner, invisible slide div */\n    width: var(--jp-widgets-slider-track-thickness);\n    flex-grow: 1;\n    margin-left: auto;\n    margin-right: auto;\n}\n\n/* Widget Progress Styling */\n\n.progress-bar {\n    -webkit-transition: none;\n    -moz-transition: none;\n    -ms-transition: none;\n    -o-transition: none;\n    transition: none;\n}\n\n.progress-bar {\n    height: var(--jp-widgets-inline-height);\n}\n\n.progress-bar {\n    background-color: var(--jp-brand-color1);\n}\n\n.progress-bar-success {\n    background-color: var(--jp-success-color1);\n}\n\n.progress-bar-info {\n    background-color: var(--jp-info-color1);\n}\n\n.progress-bar-warning {\n    background-color: var(--jp-warn-color1);\n}\n\n.progress-bar-danger {\n    background-color: var(--jp-error-color1);\n}\n\n.progress {\n    background-color: var(--jp-layout-color2);\n    border: none;\n    box-shadow: none;\n}\n\n/* Horisontal Progress */\n\n.widget-hprogress {\n    /* Progress Bar */\n    height: var(--jp-widgets-inline-height);\n    line-height: var(--jp-widgets-inline-height);\n    width: var(--jp-widgets-inline-width);\n    align-items: center;\n\n}\n\n.widget-hprogress .progress {\n    flex-grow: 1;\n    margin-top: var(--jp-widgets-input-padding);\n    margin-bottom: var(--jp-widgets-input-padding);\n    align-self: stretch;\n    /* Override bootstrap style */\n    height: initial;\n}\n\n/* Vertical Progress */\n\n.widget-vprogress {\n    height: var(--jp-widgets-vertical-height);\n    width: var(--jp-widgets-inline-width-tiny);\n}\n\n.widget-vprogress .progress {\n    flex-grow: 1;\n    width: var(--jp-widgets-progress-thickness);\n    margin-left: auto;\n    margin-right: auto;\n    margin-bottom: 0;\n}\n\n/* Select Widget Styling */\n\n.widget-dropdown {\n    height: var(--jp-widgets-inline-height);\n    width: var(--jp-widgets-inline-width);\n    line-height: var(--jp-widgets-inline-height);\n}\n\n.widget-dropdown > select {\n    padding-right: 20px;\n    border: var(--jp-widgets-input-border-width) solid var(--jp-widgets-input-border-color);\n    border-radius: 0;\n    height: inherit;\n    flex: 1 1 var(--jp-widgets-inline-width-short);\n    min-width: 0; /* This makes it possible for the flexbox to shrink this input */\n    box-sizing: border-box;\n    outline: none !important;\n    box-shadow: none;\n    background-color: var(--jp-widgets-input-background-color);\n    color: var(--jp-widgets-input-color);\n    font-size: var(--jp-widgets-font-size);\n    vertical-align: top;\n    padding-left: calc( var(--jp-widgets-input-padding) * 2);\n\tappearance: none;\n\t-webkit-appearance: none;\n\t-moz-appearance: none;\n    background-repeat: no-repeat;\n\tbackground-size: 20px;\n\tbackground-position: right center;\n    background-image: var(--jp-widgets-dropdown-arrow);\n}\n.widget-dropdown > select:focus {\n    border-color: var(--jp-widgets-input-focus-border-color);\n}\n\n.widget-dropdown > select:disabled {\n    opacity: var(--jp-widgets-disabled-opacity);\n}\n\n/* To disable the dotted border in Firefox around select controls.\n   See http://stackoverflow.com/a/18853002 */\n.widget-dropdown > select:-moz-focusring {\n    color: transparent;\n    text-shadow: 0 0 0 #000;\n}\n\n/* Select and SelectMultiple */\n\n.widget-select {\n    width: var(--jp-widgets-inline-width);\n    line-height: var(--jp-widgets-inline-height);\n\n    /* Because Firefox defines the baseline of a select as the bottom of the\n    control, we align the entire control to the top and add padding to the\n    select to get an approximate first line baseline alignment. */\n    align-items: flex-start;\n}\n\n.widget-select > select {\n    border: var(--jp-widgets-input-border-width) solid var(--jp-widgets-input-border-color);\n    background-color: var(--jp-widgets-input-background-color);\n    color: var(--jp-widgets-input-color);\n    font-size: var(--jp-widgets-font-size);\n    flex: 1 1 var(--jp-widgets-inline-width-short);\n    outline: none !important;\n    overflow: auto;\n    height: inherit;\n\n    /* Because Firefox defines the baseline of a select as the bottom of the\n    control, we align the entire control to the top and add padding to the\n    select to get an approximate first line baseline alignment. */\n    padding-top: 5px;\n}\n\n.widget-select > select:focus {\n    border-color: var(--jp-widgets-input-focus-border-color);\n}\n\n.wiget-select > select > option {\n    padding-left: var(--jp-widgets-input-padding);\n    line-height: var(--jp-widgets-inline-height);\n    /* line-height doesn't work on some browsers for select options */\n    padding-top: calc(var(--jp-widgets-inline-height)-var(--jp-widgets-font-size)/2);\n    padding-bottom: calc(var(--jp-widgets-inline-height)-var(--jp-widgets-font-size)/2);\n}\n\n\n\n/* Toggle Buttons Styling */\n\n.widget-toggle-buttons {\n    line-height: var(--jp-widgets-inline-height);\n}\n\n.widget-toggle-buttons .widget-toggle-button {\n    margin-left: var(--jp-widgets-margin);\n    margin-right: var(--jp-widgets-margin);\n}\n\n.widget-toggle-buttons .jupyter-button:disabled {\n    opacity: var(--jp-widgets-disabled-opacity);\n}\n\n/* Radio Buttons Styling */\n\n.widget-radio {\n    width: var(--jp-widgets-inline-width);\n    line-height: var(--jp-widgets-inline-height);\n}\n\n.widget-radio-box {\n    display: flex;\n    flex-direction: column;\n    align-items: stretch;\n    box-sizing: border-box;\n    flex-grow: 1;\n    margin-bottom: var(--jp-widgets-radio-item-height-adjustment);\n}\n\n.widget-radio-box label {\n    height: var(--jp-widgets-radio-item-height);\n    line-height: var(--jp-widgets-radio-item-height);\n    font-size: var(--jp-widgets-font-size);\n}\n\n.widget-radio-box input {\n    height: var(--jp-widgets-radio-item-height);\n    line-height: var(--jp-widgets-radio-item-height);\n    margin: 0 calc( var(--jp-widgets-input-padding) * 2 ) 0 1px;\n    float: left;\n}\n\n/* Color Picker Styling */\n\n.widget-colorpicker {\n    width: var(--jp-widgets-inline-width);\n    height: var(--jp-widgets-inline-height);\n    line-height: var(--jp-widgets-inline-height);\n}\n\n.widget-colorpicker > .widget-colorpicker-input {\n    flex-grow: 1;\n    flex-shrink: 1;\n    min-width: var(--jp-widgets-inline-width-tiny);\n}\n\n.widget-colorpicker input[type=\"color\"] {\n    width: var(--jp-widgets-inline-height);\n    height: var(--jp-widgets-inline-height);\n    padding: 0 2px; /* make the color square actually square on Chrome on OS X */\n    background: var(--jp-widgets-input-background-color);\n    color: var(--jp-widgets-input-color);\n    border: var(--jp-widgets-input-border-width) solid var(--jp-widgets-input-border-color);\n    border-left: none;\n    flex-grow: 0;\n    flex-shrink: 0;\n    box-sizing: border-box;\n    align-self: stretch;\n    outline: none !important;\n}\n\n.widget-colorpicker.concise input[type=\"color\"] {\n    border-left: var(--jp-widgets-input-border-width) solid var(--jp-widgets-input-border-color);\n}\n\n.widget-colorpicker input[type=\"color\"]:focus, .widget-colorpicker input[type=\"text\"]:focus {\n    border-color: var(--jp-widgets-input-focus-border-color);\n}\n\n.widget-colorpicker input[type=\"text\"] {\n    flex-grow: 1;\n    outline: none !important;\n    height: var(--jp-widgets-inline-height);\n    line-height: var(--jp-widgets-inline-height);\n    background: var(--jp-widgets-input-background-color);\n    color: var(--jp-widgets-input-color);\n    border: var(--jp-widgets-input-border-width) solid var(--jp-widgets-input-border-color);\n    font-size: var(--jp-widgets-font-size);\n    padding: var(--jp-widgets-input-padding) calc( var(--jp-widgets-input-padding) *  2 );\n    min-width: 0; /* This makes it possible for the flexbox to shrink this input */\n    flex-shrink: 1;\n    box-sizing: border-box;\n}\n\n.widget-colorpicker input[type=\"text\"]:disabled {\n    opacity: var(--jp-widgets-disabled-opacity);\n}\n\n/* Date Picker Styling */\n\n.widget-datepicker {\n    width: var(--jp-widgets-inline-width);\n    height: var(--jp-widgets-inline-height);\n    line-height: var(--jp-widgets-inline-height);\n}\n\n.widget-datepicker input[type=\"date\"] {\n    flex-grow: 1;\n    flex-shrink: 1;\n    min-width: 0; /* This makes it possible for the flexbox to shrink this input */\n    outline: none !important;\n    height: var(--jp-widgets-inline-height);\n    border: var(--jp-widgets-input-border-width) solid var(--jp-widgets-input-border-color);\n    background-color: var(--jp-widgets-input-background-color);\n    color: var(--jp-widgets-input-color);\n    font-size: var(--jp-widgets-font-size);\n    padding: var(--jp-widgets-input-padding) calc( var(--jp-widgets-input-padding) *  2 );\n    box-sizing: border-box;\n}\n\n.widget-datepicker input[type=\"date\"]:focus {\n    border-color: var(--jp-widgets-input-focus-border-color);\n}\n\n.widget-datepicker input[type=\"date\"]:invalid {\n    border-color: var(--jp-warn-color1);\n}\n\n.widget-datepicker input[type=\"date\"]:disabled {\n    opacity: var(--jp-widgets-disabled-opacity);\n}\n\n/* Play Widget */\n\n.widget-play {\n    width: var(--jp-widgets-inline-width-short);\n    display: flex;\n    align-items: stretch;\n}\n\n.widget-play .jupyter-button {\n    flex-grow: 1;\n    height: auto;\n}\n\n.widget-play .jupyter-button:disabled {\n    opacity: var(--jp-widgets-disabled-opacity);\n}\n\n/* Tab Widget */\n\n.jupyter-widgets.widget-tab {\n    display: flex;\n    flex-direction: column;\n}\n\n.jupyter-widgets.widget-tab > .p-TabBar {\n    /* Necessary so that a tab can be shifted down to overlay the border of the box below. */\n    overflow-x: visible;\n    overflow-y: visible;\n}\n\n.jupyter-widgets.widget-tab > .p-TabBar > .p-TabBar-content {\n    /* Make sure that the tab grows from bottom up */\n    align-items: flex-end;\n    min-width: 0;\n    min-height: 0;\n}\n\n.jupyter-widgets.widget-tab > .widget-tab-contents {\n    width: 100%;\n    box-sizing: border-box;\n    margin: 0;\n    background: var(--jp-layout-color1);\n    color: var(--jp-ui-font-color1);\n    border: var(--jp-border-width) solid var(--jp-border-color1);\n    padding: var(--jp-widgets-container-padding);\n    flex-grow: 1;\n    overflow: auto;\n}\n\n.jupyter-widgets.widget-tab > .p-TabBar {\n    font: var(--jp-widgets-font-size) Helvetica, Arial, sans-serif;\n    min-height: calc(var(--jp-widgets-horizontal-tab-height) + var(--jp-border-width));\n}\n\n.jupyter-widgets.widget-tab > .p-TabBar .p-TabBar-tab {\n    flex: 0 1 var(--jp-widgets-horizontal-tab-width);\n    min-width: 35px;\n    min-height: calc(var(--jp-widgets-horizontal-tab-height) + var(--jp-border-width));\n    line-height: var(--jp-widgets-horizontal-tab-height);\n    margin-left: calc(-1 * var(--jp-border-width));\n    padding: 0px 10px;\n    background: var(--jp-layout-color2);\n    color: var(--jp-ui-font-color2);\n    border: var(--jp-border-width) solid var(--jp-border-color1);\n    border-bottom: none;\n    position: relative;\n}\n\n.jupyter-widgets.widget-tab > .p-TabBar .p-TabBar-tab.p-mod-current {\n    color: var(--jp-ui-font-color0);\n    /* We want the background to match the tab content background */\n    background: var(--jp-layout-color1);\n    min-height: calc(var(--jp-widgets-horizontal-tab-height) + 2 * var(--jp-border-width));\n    transform: translateY(var(--jp-border-width));\n    overflow: visible;\n}\n\n.jupyter-widgets.widget-tab > .p-TabBar .p-TabBar-tab.p-mod-current:before {\n    position: absolute;\n    top: calc(-1 * var(--jp-border-width));\n    left: calc(-1 * var(--jp-border-width));\n    content: '';\n    height: var(--jp-widgets-horizontal-tab-top-border);\n    width: calc(100% + 2 * var(--jp-border-width));\n    background: var(--jp-brand-color1);\n}\n\n.jupyter-widgets.widget-tab > .p-TabBar .p-TabBar-tab:first-child {\n    margin-left: 0;\n}\n\n.jupyter-widgets.widget-tab > .p-TabBar .p-TabBar-tab:hover:not(.p-mod-current) {\n    background: var(--jp-layout-color1);\n    color: var(--jp-ui-font-color1);\n}\n\n.jupyter-widgets.widget-tab > .p-TabBar .p-mod-closable > .p-TabBar-tabCloseIcon {\n    margin-left: 4px;\n}\n\n.jupyter-widgets.widget-tab > .p-TabBar .p-mod-closable > .p-TabBar-tabCloseIcon:before {\n    font-family: FontAwesome;\n    content: '\\F00D'; /* close */\n}\n\n.jupyter-widgets.widget-tab > .p-TabBar .p-TabBar-tabIcon,\n.jupyter-widgets.widget-tab > .p-TabBar .p-TabBar-tabLabel,\n.jupyter-widgets.widget-tab > .p-TabBar .p-TabBar-tabCloseIcon {\n    line-height: var(--jp-widgets-horizontal-tab-height);\n}\n\n/* Accordion Widget */\n\n.p-Collapse {\n    display: flex;\n    flex-direction: column;\n    align-items: stretch;\n}\n\n.p-Collapse-header {\n    padding: var(--jp-widgets-input-padding);\n    cursor: pointer;\n    color: var(--jp-ui-font-color2);\n    background-color: var(--jp-layout-color2);\n    border: var(--jp-widgets-border-width) solid var(--jp-border-color1);\n    padding: calc(var(--jp-widgets-container-padding) * 2 / 3) var(--jp-widgets-container-padding);\n    font-weight: bold;\n}\n\n.p-Collapse-header:hover {\n    background-color: var(--jp-layout-color1);\n    color: var(--jp-ui-font-color1);\n}\n\n.p-Collapse-open > .p-Collapse-header {\n    background-color: var(--jp-layout-color1);\n    color: var(--jp-ui-font-color0);\n    cursor: default;\n    border-bottom: none;\n}\n\n.p-Collapse .p-Collapse-header::before {\n    content: '\\F0DA\\A0';  /* caret-right, non-breaking space */\n    display: inline-block;\n    font: normal normal normal 14px/1 FontAwesome;\n    font-size: inherit;\n    text-rendering: auto;\n    -webkit-font-smoothing: antialiased;\n    -moz-osx-font-smoothing: grayscale;\n}\n\n.p-Collapse-open > .p-Collapse-header::before {\n    content: '\\F0D7\\A0'; /* caret-down, non-breaking space */\n}\n\n.p-Collapse-contents {\n    padding: var(--jp-widgets-container-padding);\n    background-color: var(--jp-layout-color1);\n    color: var(--jp-ui-font-color1);\n    border-left: var(--jp-widgets-border-width) solid var(--jp-border-color1);\n    border-right: var(--jp-widgets-border-width) solid var(--jp-border-color1);\n    border-bottom: var(--jp-widgets-border-width) solid var(--jp-border-color1);\n    overflow: auto;\n}\n\n.p-Accordion {\n    display: flex;\n    flex-direction: column;\n    align-items: stretch;\n}\n\n.p-Accordion .p-Collapse {\n    margin-bottom: 0;\n}\n\n.p-Accordion .p-Collapse + .p-Collapse {\n    margin-top: 4px;\n}\n\n\n\n/* HTML widget */\n\n.widget-html, .widget-htmlmath {\n    font-size: var(--jp-widgets-font-size);\n}\n\n.widget-html > .widget-html-content, .widget-htmlmath > .widget-html-content {\n    /* Fill out the area in the HTML widget */\n    align-self: stretch;\n    flex-grow: 1;\n    flex-shrink: 1;\n    /* Makes sure the baseline is still aligned with other elements */\n    line-height: var(--jp-widgets-inline-height);\n    /* Make it possible to have absolutely-positioned elements in the html */\n    position: relative;\n}\n", ""]);

// exports


/***/ }),

/***/ "hoXd":
/*!***********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotErrorBarsIcon.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotErrorBarsIcon = function PlotErrorBarsIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M0 9.313h4v3.438H2v4h2v3.25H0v4h12v-4H8v-3.25h1.938v-4H8V9.313h4v-4H0zM32 12V8H20v4h4v3.313h-2v4h2v3.375h-4v4h12v-4h-4v-3.375h2v-4h-2V12z' })
    );
};

exports.default = PlotErrorBarsIcon;

/***/ }),

/***/ "honF":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/my.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var symbolMap = {
    '1': '၁',
    '2': '၂',
    '3': '၃',
    '4': '၄',
    '5': '၅',
    '6': '၆',
    '7': '၇',
    '8': '၈',
    '9': '၉',
    '0': '၀'
}, numberMap = {
    '၁': '1',
    '၂': '2',
    '၃': '3',
    '၄': '4',
    '၅': '5',
    '၆': '6',
    '၇': '7',
    '၈': '8',
    '၉': '9',
    '၀': '0'
};

var my = moment.defineLocale('my', {
    months: 'ဇန်နဝါရီ_ဖေဖော်ဝါရီ_မတ်_ဧပြီ_မေ_ဇွန်_ဇူလိုင်_သြဂုတ်_စက်တင်ဘာ_အောက်တိုဘာ_နိုဝင်ဘာ_ဒီဇင်ဘာ'.split('_'),
    monthsShort: 'ဇန်_ဖေ_မတ်_ပြီ_မေ_ဇွန်_လိုင်_သြ_စက်_အောက်_နို_ဒီ'.split('_'),
    weekdays: 'တနင်္ဂနွေ_တနင်္လာ_အင်္ဂါ_ဗုဒ္ဓဟူး_ကြာသပတေး_သောကြာ_စနေ'.split('_'),
    weekdaysShort: 'နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ'.split('_'),
    weekdaysMin: 'နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ'.split('_'),

    longDateFormat: {
        LT: 'HH:mm',
        LTS: 'HH:mm:ss',
        L: 'DD/MM/YYYY',
        LL: 'D MMMM YYYY',
        LLL: 'D MMMM YYYY HH:mm',
        LLLL: 'dddd D MMMM YYYY HH:mm'
    },
    calendar: {
        sameDay: '[ယနေ.] LT [မှာ]',
        nextDay: '[မနက်ဖြန်] LT [မှာ]',
        nextWeek: 'dddd LT [မှာ]',
        lastDay: '[မနေ.က] LT [မှာ]',
        lastWeek: '[ပြီးခဲ့သော] dddd LT [မှာ]',
        sameElse: 'L'
    },
    relativeTime: {
        future: 'လာမည့် %s မှာ',
        past: 'လွန်ခဲ့သော %s က',
        s: 'စက္ကန်.အနည်းငယ်',
        ss : '%d စက္ကန့်',
        m: 'တစ်မိနစ်',
        mm: '%d မိနစ်',
        h: 'တစ်နာရီ',
        hh: '%d နာရီ',
        d: 'တစ်ရက်',
        dd: '%d ရက်',
        M: 'တစ်လ',
        MM: '%d လ',
        y: 'တစ်နှစ်',
        yy: '%d နှစ်'
    },
    preparse: function (string) {
        return string.replace(/[၁၂၃၄၅၆၇၈၉၀]/g, function (match) {
            return numberMap[match];
        });
    },
    postformat: function (string) {
        return string.replace(/\d/g, function (match) {
            return symbolMap[match];
        });
    },
    week: {
        dow: 1, // Monday is the first day of the week.
        doy: 4 // The week that contains Jan 1st is the first week of the year.
    }
});

return my;

})));


/***/ }),

/***/ "hpMJ":
/*!***************************************************************!*\
  !*** ./node_modules/draft-js/lib/getEntityKeyForSelection.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule getEntityKeyForSelection
 * @format
 * 
 */



/**
 * Return the entity key that should be used when inserting text for the
 * specified target selection, only if the entity is `MUTABLE`. `IMMUTABLE`
 * and `SEGMENTED` entities should not be used for insertion behavior.
 */
function getEntityKeyForSelection(contentState, targetSelection) {
  var entityKey;

  if (targetSelection.isCollapsed()) {
    var key = targetSelection.getAnchorKey();
    var offset = targetSelection.getAnchorOffset();
    if (offset > 0) {
      entityKey = contentState.getBlockForKey(key).getEntityAt(offset - 1);
      if (entityKey !== contentState.getBlockForKey(key).getEntityAt(offset)) {
        return null;
      }
      return filterKey(contentState.getEntityMap(), entityKey);
    }
    return null;
  }

  var startKey = targetSelection.getStartKey();
  var startOffset = targetSelection.getStartOffset();
  var startBlock = contentState.getBlockForKey(startKey);

  entityKey = startOffset === startBlock.getLength() ? null : startBlock.getEntityAt(startOffset);

  return filterKey(contentState.getEntityMap(), entityKey);
}

/**
 * Determine whether an entity key corresponds to a `MUTABLE` entity. If so,
 * return it. If not, return null.
 */
function filterKey(entityMap, entityKey) {
  if (entityKey) {
    var entity = entityMap.__get(entityKey);
    return entity.getMutability() === 'MUTABLE' ? entityKey : null;
  }
  return null;
}

module.exports = getEntityKeyForSelection;

/***/ }),

/***/ "hpl1":
/*!*******************************************************!*\
  !*** ./node_modules/@phosphor/messaging/lib/index.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(setImmediate, clearImmediate) {
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
var collections_1 = __webpack_require__(/*! @phosphor/collections */ "LxhV");
/**
 * A message which can be delivered to a message handler.
 *
 * #### Notes
 * This class may be subclassed to create complex message types.
 */
var Message = (function () {
    /**
     * Construct a new message.
     *
     * @param type - The type of the message.
     */
    function Message(type) {
        this.type = type;
    }
    Object.defineProperty(Message.prototype, "isConflatable", {
        /**
         * Test whether the message is conflatable.
         *
         * #### Notes
         * Message conflation is an advanced topic. Most message types will
         * not make use of this feature.
         *
         * If a conflatable message is posted to a handler while another
         * conflatable message of the same `type` has already been posted
         * to the handler, the `conflate()` method of the existing message
         * will be invoked. If that method returns `true`, the new message
         * will not be enqueued. This allows messages to be compressed, so
         * that only a single instance of the message type is processed per
         * cycle, no matter how many times messages of that type are posted.
         *
         * Custom message types may reimplement this property.
         *
         * The default implementation is always `false`.
         */
        get: function () {
            return false;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Conflate this message with another message of the same `type`.
     *
     * @param other - A conflatable message of the same `type`.
     *
     * @returns `true` if the message was successfully conflated, or
     *   `false` otherwise.
     *
     * #### Notes
     * Message conflation is an advanced topic. Most message types will
     * not make use of this feature.
     *
     * This method is called automatically by the message loop when the
     * given message is posted to the handler paired with this message.
     * This message will already be enqueued and conflatable, and the
     * given message will have the same `type` and also be conflatable.
     *
     * This method should merge the state of the other message into this
     * message as needed so that when this message is finally delivered
     * to the handler, it receives the most up-to-date information.
     *
     * If this method returns `true`, it signals that the other message
     * was successfully conflated and that message will not be enqueued.
     *
     * If this method returns `false`, the other message will be enqueued
     * for normal delivery.
     *
     * Custom message types may reimplement this method.
     *
     * The default implementation always returns `false`.
     */
    Message.prototype.conflate = function (other) {
        return false;
    };
    return Message;
}());
exports.Message = Message;
/**
 * A convenience message class which conflates automatically.
 *
 * #### Notes
 * Message conflation is an advanced topic. Most user code will not
 * make use of this class.
 *
 * This message class is useful for creating message instances which
 * should be conflated, but which have no state other than `type`.
 *
 * If conflation of stateful messages is required, a custom `Message`
 * subclass should be created.
 */
var ConflatableMessage = (function (_super) {
    __extends(ConflatableMessage, _super);
    function ConflatableMessage() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ConflatableMessage.prototype, "isConflatable", {
        /**
         * Test whether the message is conflatable.
         *
         * #### Notes
         * This property is always `true`.
         */
        get: function () {
            return true;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Conflate this message with another message of the same `type`.
     *
     * #### Notes
     * This method always returns `true`.
     */
    ConflatableMessage.prototype.conflate = function (other) {
        return true;
    };
    return ConflatableMessage;
}(Message));
exports.ConflatableMessage = ConflatableMessage;
/**
 * The namespace for the global singleton message loop.
 */
var MessageLoop;
(function (MessageLoop) {
    /**
     * Send a message to a message handler to process immediately.
     *
     * @param handler - The handler which should process the message.
     *
     * @param msg - The message to deliver to the handler.
     *
     * #### Notes
     * The message will first be sent through any installed message hooks
     * for the handler. If the message passes all hooks, it will then be
     * delivered to the `processMessage` method of the handler.
     *
     * The message will not be conflated with pending posted messages.
     *
     * Exceptions in hooks and handlers will be caught and logged.
     */
    function sendMessage(handler, msg) {
        // Lookup the message hooks for the handler.
        var hooks = messageHooks.get(handler);
        // Handle the common case of no installed hooks.
        if (!hooks || hooks.length === 0) {
            invokeHandler(handler, msg);
            return;
        }
        // Invoke the message hooks starting with the newest first.
        var passed = algorithm_1.every(algorithm_1.retro(hooks), function (hook) {
            return hook ? invokeHook(hook, handler, msg) : true;
        });
        // Invoke the handler if the message passes all hooks.
        if (passed) {
            invokeHandler(handler, msg);
        }
    }
    MessageLoop.sendMessage = sendMessage;
    /**
     * Post a message to a message handler to process in the future.
     *
     * @param handler - The handler which should process the message.
     *
     * @param msg - The message to post to the handler.
     *
     * #### Notes
     * The message will be conflated with the pending posted messages for
     * the handler, if possible. If the message is not conflated, it will
     * be queued for normal delivery on the next cycle of the event loop.
     *
     * Exceptions in hooks and handlers will be caught and logged.
     */
    function postMessage(handler, msg) {
        // Handle the common case of a non-conflatable message.
        if (!msg.isConflatable) {
            enqueueMessage(handler, msg);
            return;
        }
        // Conflate the message with an existing message if possible.
        var conflated = algorithm_1.some(messageQueue, function (posted) {
            if (posted.handler !== handler) {
                return false;
            }
            if (!posted.msg) {
                return false;
            }
            if (posted.msg.type !== msg.type) {
                return false;
            }
            if (!posted.msg.isConflatable) {
                return false;
            }
            return posted.msg.conflate(msg);
        });
        // Enqueue the message if it was not conflated.
        if (!conflated) {
            enqueueMessage(handler, msg);
        }
    }
    MessageLoop.postMessage = postMessage;
    /**
     * Install a message hook for a message handler.
     *
     * @param handler - The message handler of interest.
     *
     * @param hook - The message hook to install.
     *
     * #### Notes
     * A message hook is invoked before a message is delivered to the
     * handler. If the hook returns `false`, no other hooks will be
     * invoked and the message will not be delivered to the handler.
     *
     * The most recently installed message hook is executed first.
     *
     * If the hook is already installed, this is a no-op.
     */
    function installMessageHook(handler, hook) {
        // Lookup the hooks for the handler.
        var hooks = messageHooks.get(handler);
        // Bail early if the hook is already installed.
        if (hooks && hooks.indexOf(hook) !== -1) {
            return;
        }
        // Add the hook to the end, so it will be the first to execute.
        if (!hooks) {
            messageHooks.set(handler, [hook]);
        }
        else {
            hooks.push(hook);
        }
    }
    MessageLoop.installMessageHook = installMessageHook;
    /**
     * Remove an installed message hook for a message handler.
     *
     * @param handler - The message handler of interest.
     *
     * @param hook - The message hook to remove.
     *
     * #### Notes
     * It is safe to call this function while the hook is executing.
     *
     * If the hook is not installed, this is a no-op.
     */
    function removeMessageHook(handler, hook) {
        // Lookup the hooks for the handler.
        var hooks = messageHooks.get(handler);
        // Bail early if the hooks do not exist.
        if (!hooks) {
            return;
        }
        // Lookup the index of the hook and bail if not found.
        var i = hooks.indexOf(hook);
        if (i === -1) {
            return;
        }
        // Clear the hook and schedule a cleanup of the array.
        hooks[i] = null;
        scheduleCleanup(hooks);
    }
    MessageLoop.removeMessageHook = removeMessageHook;
    /**
     * Clear all message data associated with a message handler.
     *
     * @param handler - The message handler of interest.
     *
     * #### Notes
     * This will clear all posted messages and hooks for the handler.
     */
    function clearData(handler) {
        // Lookup the hooks for the handler.
        var hooks = messageHooks.get(handler);
        // Clear all messsage hooks for the handler.
        if (hooks && hooks.length > 0) {
            algorithm_1.ArrayExt.fill(hooks, null);
            scheduleCleanup(hooks);
        }
        // Clear all posted messages for the handler.
        algorithm_1.each(messageQueue, function (posted) {
            if (posted.handler === handler) {
                posted.handler = null;
                posted.msg = null;
            }
        });
    }
    MessageLoop.clearData = clearData;
    /**
     * Process the pending posted messages in the queue immediately.
     *
     * #### Notes
     * This function is useful when posted messages must be processed
     * immediately, instead of on the next animation frame.
     *
     * This function should normally not be needed, but it may be
     * required to work around certain browser idiosyncrasies.
     *
     * Recursing into this function is a no-op.
     */
    function flush() {
        // Bail if recursion is detected or if there is no pending task.
        if (flushGuard || loopTaskID === 0) {
            return;
        }
        // Unschedule the pending loop task.
        unschedule(loopTaskID);
        // Run the message loop within the recursion guard.
        flushGuard = true;
        runMessageLoop();
        flushGuard = false;
    }
    MessageLoop.flush = flush;
    /**
     * Get the message loop exception handler.
     *
     * @returns The current exception handler.
     *
     * #### Notes
     * The default exception handler is `console.error`.
     */
    function getExceptionHandler() {
        return exceptionHandler;
    }
    MessageLoop.getExceptionHandler = getExceptionHandler;
    /**
     * Set the message loop exception handler.
     *
     * @param handler - The function to use as the exception handler.
     *
     * @returns The old exception handler.
     *
     * #### Notes
     * The exception handler is invoked when a message handler or a
     * message hook throws an exception.
     */
    function setExceptionHandler(handler) {
        var old = exceptionHandler;
        exceptionHandler = handler;
        return old;
    }
    MessageLoop.setExceptionHandler = setExceptionHandler;
    /**
     * The queue of posted message pairs.
     */
    var messageQueue = new collections_1.LinkedList();
    /**
     * A mapping of handler to array of installed message hooks.
     */
    var messageHooks = new WeakMap();
    /**
     * A set of message hook arrays which are pending cleanup.
     */
    var dirtySet = new Set();
    /**
     * The message loop exception handler.
     */
    var exceptionHandler = function (err) {
        console.error(err);
    };
    /**
     * The id of the pending loop task animation frame.
     */
    var loopTaskID = 0;
    /**
     * A guard flag to prevent flush recursion.
     */
    var flushGuard = false;
    /**
     * A function to schedule an event loop callback.
     */
    var schedule = (function () {
        var ok = typeof requestAnimationFrame === 'function';
        return ok ? requestAnimationFrame : setImmediate;
    })();
    /**
     * A function to unschedule an event loop callback.
     */
    var unschedule = (function () {
        var ok = typeof cancelAnimationFrame === 'function';
        return ok ? cancelAnimationFrame : clearImmediate;
    })();
    /**
     * Invoke a message hook with the specified handler and message.
     *
     * Returns the result of the hook, or `true` if the hook throws.
     *
     * Exceptions in the hook will be caught and logged.
     */
    function invokeHook(hook, handler, msg) {
        var result = true;
        try {
            if (typeof hook === 'function') {
                result = hook(handler, msg);
            }
            else {
                result = hook.messageHook(handler, msg);
            }
        }
        catch (err) {
            exceptionHandler(err);
        }
        return result;
    }
    /**
     * Invoke a message handler with the specified message.
     *
     * Exceptions in the handler will be caught and logged.
     */
    function invokeHandler(handler, msg) {
        try {
            handler.processMessage(msg);
        }
        catch (err) {
            exceptionHandler(err);
        }
    }
    /**
     * Add a message to the end of the message queue.
     *
     * This will automatically schedule a run of the message loop.
     */
    function enqueueMessage(handler, msg) {
        // Add the posted message to the queue.
        messageQueue.addLast({ handler: handler, msg: msg });
        // Bail if a loop task is already pending.
        if (loopTaskID !== 0) {
            return;
        }
        // Schedule a run of the message loop.
        loopTaskID = schedule(runMessageLoop);
    }
    /**
     * Run an iteration of the message loop.
     *
     * This will process all pending messages in the queue. If a message
     * is added to the queue while the message loop is running, it will
     * be processed on the next cycle of the loop.
     */
    function runMessageLoop() {
        // Clear the task ID so the next loop can be scheduled.
        loopTaskID = 0;
        // If the message queue is empty, there is nothing else to do.
        if (messageQueue.isEmpty) {
            return;
        }
        // Add a sentinel value to the end of the queue. The queue will
        // only be processed up to the sentinel. Messages posted during
        // this cycle will execute on the next cycle.
        var sentinel = { handler: null, msg: null };
        messageQueue.addLast(sentinel);
        // Enter the message loop.
        while (true) {
            // Remove the first posted message in the queue.
            var posted = messageQueue.removeFirst();
            // If the value is the sentinel, exit the loop.
            if (posted === sentinel) {
                return;
            }
            // Dispatch the message if it has not been cleared.
            if (posted.handler && posted.msg) {
                sendMessage(posted.handler, posted.msg);
            }
        }
    }
    /**
     * Schedule a cleanup of a message hooks array.
     *
     * This will add the array to the dirty set and schedule a deferred
     * cleanup of the array contents. On cleanup, any `null` hook will
     * be removed from the array.
     */
    function scheduleCleanup(hooks) {
        if (dirtySet.size === 0) {
            schedule(cleanupDirtySet);
        }
        dirtySet.add(hooks);
    }
    /**
     * Cleanup the message hook arrays in the dirty set.
     *
     * This function should only be invoked asynchronously, when the
     * stack frame is guaranteed to not be on the path of user code.
     */
    function cleanupDirtySet() {
        dirtySet.forEach(cleanupHooks);
        dirtySet.clear();
    }
    /**
     * Cleanup the dirty hooks in a message hooks array.
     *
     * This will remove any `null` hook from the array.
     *
     * This function should only be invoked asynchronously, when the
     * stack frame is guaranteed to not be on the path of user code.
     */
    function cleanupHooks(hooks) {
        algorithm_1.ArrayExt.removeAllWhere(hooks, isNull);
    }
    /**
     * Test whether a value is `null`.
     */
    function isNull(value) {
        return value === null;
    }
})(MessageLoop = exports.MessageLoop || (exports.MessageLoop = {}));

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../timers-browserify/main.js */ "URgk").setImmediate, __webpack_require__(/*! ./../../../timers-browserify/main.js */ "URgk").clearImmediate))

/***/ }),

/***/ "hqvf":
/*!*******************************************!*\
  !*** ./node_modules/xterm/lib/Strings.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.blankLine = 'Blank line';
exports.promptLabel = 'Terminal input';
exports.tooMuchOutput = 'Too much output to announce, navigate to rows manually to read';

//# sourceMappingURL=Strings.js.map


/***/ }),

/***/ "hraO":
/*!**********************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/anchor_utils.js ***!
  \**********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/





/**
 * Determine the position anchor property of x/y xanchor/yanchor components.
 *
 * - values < 1/3 align the low side at that fraction,
 * - values [1/3, 2/3] align the center at that fraction,
 * - values > 2/3 align the right at that fraction.
 */


exports.isLeftAnchor = function isLeftAnchor(opts) {
    return (
      opts.xanchor === 'left' ||
      (opts.xanchor === 'auto' && opts.x <= 1 / 3)
    );
};

exports.isCenterAnchor = function isCenterAnchor(opts) {
    return (
        opts.xanchor === 'center' ||
        (opts.xanchor === 'auto' && opts.x > 1 / 3 && opts.x < 2 / 3)
    );
};

exports.isRightAnchor = function isRightAnchor(opts) {
    return (
      opts.xanchor === 'right' ||
      (opts.xanchor === 'auto' && opts.x >= 2 / 3)
    );
};

exports.isTopAnchor = function isTopAnchor(opts) {
    return (
        opts.yanchor === 'top' ||
        (opts.yanchor === 'auto' && opts.y >= 2 / 3)
    );
};

exports.isMiddleAnchor = function isMiddleAnchor(opts) {
    return (
        opts.yanchor === 'middle' ||
        (opts.yanchor === 'auto' && opts.y > 1 / 3 && opts.y < 2 / 3)
    );
};

exports.isBottomAnchor = function isBottomAnchor(opts) {
    return (
      opts.yanchor === 'bottom' ||
      (opts.yanchor === 'auto' && opts.y <= 1 / 3)
    );
};


/***/ }),

/***/ "hs2k":
/*!****************************************************************!*\
  !*** ./node_modules/@jupyter-widgets/base/lib/manager-base.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var utils = __webpack_require__(/*! ./utils */ "o9P/");
var version_1 = __webpack_require__(/*! ./version */ "tLa0");
var PROTOCOL_MAJOR_VERSION = version_1.PROTOCOL_VERSION.split('.', 1)[0];
/**
 * Manager abstract base class
 */
var ManagerBase = /** @class */ (function () {
    function ManagerBase() {
        /**
         * The comm target name to register
         */
        this.comm_target_name = 'jupyter.widget';
        /**
         * Dictionary of model ids and model instance promises
         */
        this._models = Object.create(null);
    }
    /**
     * Display a view for a particular model.
     */
    ManagerBase.prototype.display_model = function (msg, model, options) {
        var _this = this;
        if (options === void 0) { options = {}; }
        return this.create_view(model, options).then(function (view) { return _this.display_view(msg, view, options); }).catch(utils.reject('Could not create view', true));
    };
    /**
     * Modifies view options. Generally overloaded in custom widget manager
     * implementations.
     */
    ManagerBase.prototype.setViewOptions = function (options) {
        if (options === void 0) { options = {}; }
        return options;
    };
    /**
     * Creates a promise for a view of a given model
     *
     * Make sure the view creation is not out of order with
     * any state updates.
     */
    ManagerBase.prototype.create_view = function (model, options) {
        var _this = this;
        if (options === void 0) { options = {}; }
        var viewPromise = model.state_change = model.state_change.then(function () {
            return _this.loadClass(model.get('_view_name'), model.get('_view_module'), model.get('_view_module_version')).then(function (ViewType) {
                var view = new ViewType({
                    model: model,
                    options: _this.setViewOptions(options)
                });
                view.listenTo(model, 'destroy', view.remove);
                return Promise.resolve(view.render()).then(function () { return view; });
            }).catch(utils.reject('Could not create a view for model id ' + model.model_id, true));
        });
        var id = utils.uuid();
        model.views[id] = viewPromise;
        viewPromise.then(function (view) {
            view.once('remove', function () { delete view.model.views[id]; }, _this);
        });
        return model.state_change;
    };
    /**
     * callback handlers specific to a view
     */
    ManagerBase.prototype.callbacks = function (view) {
        return {};
    };
    /**
     * Get a promise for a model by model id.
     */
    ManagerBase.prototype.get_model = function (model_id) {
        // TODO: Perhaps we should return a Promise.reject if the model is not
        // found. Right now this isn't a true async function because it doesn't
        // always return a promise.
        return this._models[model_id];
    };
    /**
     * Handle when a comm is opened.
     */
    ManagerBase.prototype.handle_comm_open = function (comm, msg) {
        var protocolVersion = (msg.metadata || {}).version || '';
        if (protocolVersion.split('.', 1)[0] !== PROTOCOL_MAJOR_VERSION) {
            var error = "Wrong widget protocol version: received protocol version '" + protocolVersion + "', but was expecting major version '" + PROTOCOL_MAJOR_VERSION + "'";
            console.error(error);
            return Promise.reject(error);
        }
        var data = msg.content.data;
        var buffer_paths = data.buffer_paths || [];
        // Make sure the buffers are DataViews
        var buffers = (msg.buffers || []).map(function (b) {
            if (b instanceof DataView) {
                return b;
            }
            else {
                return new DataView(b instanceof ArrayBuffer ? b : b.buffer);
            }
        });
        utils.put_buffers(data.state, buffer_paths, buffers);
        return this.new_model({
            model_name: data.state['_model_name'],
            model_module: data.state['_model_module'],
            model_module_version: data.state['_model_module_version'],
            comm: comm
        }, data.state).catch(utils.reject('Could not create a model.', true));
    };
    /**
     * Create a comm and new widget model.
     * @param  options - same options as new_model but comm is not
     *                          required and additional options are available.
     * @param  serialized_state - serialized model attributes.
     */
    ManagerBase.prototype.new_widget = function (options, serialized_state) {
        var _this = this;
        if (serialized_state === void 0) { serialized_state = {}; }
        var commPromise;
        // we check to make sure the view information is provided, to help catch
        // backwards incompatibility errors.
        if (options.view_name === undefined
            || options.view_module === undefined
            || options.view_module_version === undefined) {
            return Promise.reject('new_widget(...) must be given view information in the options.');
        }
        // If no comm is provided, a new comm is opened for the jupyter.widget
        // target.
        if (options.comm) {
            commPromise = Promise.resolve(options.comm);
        }
        else {
            commPromise = this._create_comm(this.comm_target_name, options.model_id, {
                state: {
                    _model_module: options.model_module,
                    _model_module_version: options.model_module_version,
                    _model_name: options.model_name,
                    _view_module: options.view_module,
                    _view_module_version: options.view_module_version,
                    _view_name: options.view_name
                },
            }, { version: version_1.PROTOCOL_VERSION });
        }
        // The options dictionary is copied since data will be added to it.
        var options_clone = __assign({}, options);
        // Create the model. In the case where the comm promise is rejected a
        // comm-less model is still created with the required model id.
        return commPromise.then(function (comm) {
            // Comm Promise Resolved.
            options_clone.comm = comm;
            var widget_model = _this.new_model(options_clone, serialized_state);
            return widget_model.then(function (model) {
                model.sync('create', model);
                return model;
            });
        }, function () {
            // Comm Promise Rejected.
            if (!options_clone.model_id) {
                options_clone.model_id = utils.uuid();
            }
            return _this.new_model(options_clone, serialized_state);
        });
    };
    ManagerBase.prototype.register_model = function (model_id, modelPromise) {
        var _this = this;
        this._models[model_id] = modelPromise;
        modelPromise.then(function (model) {
            model.once('comm:close', function () {
                delete _this._models[model_id];
            });
        });
    };
    /**
     * Create and return a promise for a new widget model
     *
     * @param options - the options for creating the model.
     * @param serialized_state - attribute values for the model.
     *
     * @example
     * widget_manager.new_model({
     *      model_name: 'IntSlider',
     *      model_module: '@jupyter-widgets/controls',
     *      model_module_version: '1.0.0',
     *      model_id: 'u-u-i-d'
     * }).then((model) => { console.log('Create success!', model); },
     *  (err) => {console.error(err)});
     *
     */
    ManagerBase.prototype.new_model = function (options, serialized_state) {
        if (serialized_state === void 0) { serialized_state = {}; }
        return __awaiter(this, void 0, void 0, function () {
            var model_id, modelPromise;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (options.model_id) {
                            model_id = options.model_id;
                        }
                        else if (options.comm) {
                            model_id = options.model_id = options.comm.comm_id;
                        }
                        else {
                            throw new Error('Neither comm nor model_id provided in options object. At least one must exist.');
                        }
                        modelPromise = this._make_model(options, serialized_state);
                        // this call needs to happen before the first `await`, see note in `set_state`:
                        this.register_model(model_id, modelPromise);
                        return [4 /*yield*/, modelPromise];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    ManagerBase.prototype._make_model = function (options, serialized_state) {
        if (serialized_state === void 0) { serialized_state = {}; }
        return __awaiter(this, void 0, void 0, function () {
            var model_id, model_promise, ModelType, error_1, attributes, modelOptions, widget_model;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        model_id = options.model_id;
                        model_promise = this.loadClass(options.model_name, options.model_module, options.model_module_version);
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, model_promise];
                    case 2:
                        ModelType = _a.sent();
                        return [3 /*break*/, 4];
                    case 3:
                        error_1 = _a.sent();
                        console.error('Could not instantiate widget');
                        throw error_1;
                    case 4:
                        if (!ModelType) {
                            throw new Error("Cannot find model module " + options.model_module + "@" + options.model_module_version + ", " + options.model_name);
                        }
                        return [4 /*yield*/, ModelType._deserialize_state(serialized_state, this)];
                    case 5:
                        attributes = _a.sent();
                        modelOptions = {
                            widget_manager: this,
                            model_id: model_id,
                            comm: options.comm,
                        };
                        widget_model = new ModelType(attributes, modelOptions);
                        widget_model.name = options.model_name;
                        widget_model.module = options.model_module;
                        return [2 /*return*/, widget_model];
                }
            });
        });
    };
    /**
     * Close all widgets and empty the widget state.
     * @return Promise that resolves when the widget state is cleared.
     */
    ManagerBase.prototype.clear_state = function () {
        var _this = this;
        return utils.resolvePromisesDict(this._models).then(function (models) {
            Object.keys(models).forEach(function (id) { return models[id].close(); });
            _this._models = {};
        });
    };
    /**
     * Asynchronously get the state of the widget manager.
     *
     * This includes all of the widget models, and follows the format given in
     * the @jupyter-widgets/schema package.
     *
     * @param options - The options for what state to return.
     * @returns Promise for a state dictionary
     */
    ManagerBase.prototype.get_state = function (options) {
        if (options === void 0) { options = {}; }
        return utils.resolvePromisesDict(this._models).then(function (models) {
            var state = {};
            Object.keys(models).forEach(function (model_id) {
                var model = models[model_id];
                var split = utils.remove_buffers(model.serialize(model.get_state(options.drop_defaults)));
                var buffers = split.buffers.map(function (buffer, index) {
                    return { data: utils.bufferToBase64(buffer), path: split.buffer_paths[index], encoding: 'base64' };
                });
                state[model_id] = {
                    model_name: model.name,
                    model_module: model.module,
                    model_module_version: model.get('_model_module_version'),
                    state: split.state
                };
                // To save space, only include the buffer key if we have buffers
                if (buffers.length > 0) {
                    state[model_id].buffers = buffers;
                }
            });
            return { version_major: 2, version_minor: 0, state: state };
        });
    };
    /**
     * Set the widget manager state.
     *
     * @param state - a Javascript object conforming to the application/vnd.jupyter.widget-state+json spec.
     *
     * Reconstructs all of the widget models in the state, merges that with the
     * current manager state, and then attempts to redisplay the widgets in the
     * state.
     */
    ManagerBase.prototype.set_state = function (state) {
        var _this = this;
        // Check to make sure that it's the same version we are parsing.
        if (!(state.version_major && state.version_major <= 2)) {
            throw 'Unsupported widget state format';
        }
        var models = state.state;
        // Recreate all the widget models for the given widget manager state.
        var all_models = this._get_comm_info().then(function (live_comms) {
            /* Note: It is currently safe to just loop over the models in any order,
               given that the following holds (does at the time of writing):
               1: any call to `new_model` with state registers the model promise (e.g. with `register_model`)
                  synchronously (before it's first `await` statement).
               2: any calls to a model constructor or the `set_state` method on a model,
                  happens asynchronously (in a `then` clause, or after an `await` statement).

              Without these assumptions, one risks trying to set model state with a reference
              to another model that doesn't exist yet!
            */
            return Promise.all(Object.keys(models).map(function (model_id) {
                // First put back the binary buffers
                var decode = { 'base64': utils.base64ToBuffer, 'hex': utils.hexToBuffer };
                var model = models[model_id];
                var modelState = model.state;
                if (model.buffers) {
                    var bufferPaths = model.buffers.map(function (b) { return b.path; });
                    // put_buffers expects buffers to be DataViews
                    var buffers = model.buffers.map(function (b) { return new DataView(decode[b.encoding](b.data)); });
                    utils.put_buffers(model.state, bufferPaths, buffers);
                }
                // If the model has already been created, set its state and then
                // return it.
                if (_this._models[model_id]) {
                    return _this._models[model_id].then(function (model) {
                        // deserialize state
                        return model.constructor._deserialize_state(modelState || {}, _this).then(function (attributes) {
                            model.set_state(attributes); // case 2
                            return model;
                        });
                    });
                }
                var modelCreate = {
                    model_id: model_id,
                    model_name: model.model_name,
                    model_module: model.model_module,
                    model_module_version: model.model_module_version
                };
                if (live_comms.hasOwnProperty(model_id)) { // live comm
                    // This connects to an existing comm if it exists, and
                    // should *not* send a comm open message.
                    return _this._create_comm(_this.comm_target_name, model_id).then(function (comm) {
                        modelCreate.comm = comm;
                        return _this.new_model(modelCreate); // No state, so safe wrt. case 1
                    });
                }
                else {
                    return _this.new_model(modelCreate, modelState); // case 1
                }
            }));
        });
        return all_models;
    };
    /**
     * Disconnect the widget manager from the kernel, setting each model's comm
     * as dead.
     */
    ManagerBase.prototype.disconnect = function () {
        var _this = this;
        Object.keys(this._models).forEach(function (i) {
            _this._models[i].then(function (model) { model.comm_live = false; });
        });
    };
    /**
     * Resolve a URL relative to the current notebook location.
     *
     * The default implementation just returns the original url.
     */
    ManagerBase.prototype.resolveUrl = function (url) {
        return Promise.resolve(url);
    };
    return ManagerBase;
}());
exports.ManagerBase = ManagerBase;


/***/ }),

/***/ "huh6":
/*!*******************************************************!*\
  !*** ./node_modules/@jupyterlab/coreutils/lib/url.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const url_parse_1 = __importDefault(__webpack_require__(/*! url-parse */ "GBY4"));
/**
 * The namespace for URL-related functions.
 */
var URLExt;
(function (URLExt) {
    /**
     * Parse a url into a URL object.
     *
     * @param urlString - The URL string to parse.
     *
     * @returns A URL object.
     */
    function parse(url) {
        if (typeof document !== 'undefined') {
            let a = document.createElement('a');
            a.href = url;
            return a;
        }
        return url_parse_1.default(url);
    }
    URLExt.parse = parse;
    /**
     * Normalize a url.
     */
    function normalize(url) {
        return url && parse(url).toString();
    }
    URLExt.normalize = normalize;
    /**
     * Join a sequence of url components and normalizes as in node `path.join`.
     *
     * @param parts - The url components.
     *
     * @returns the joined url.
     */
    function join(...parts) {
        parts = parts || [];
        // Isolate the top element.
        const top = parts[0] || '';
        // Check whether protocol shorthand is being used.
        const shorthand = top.indexOf('//') === 0;
        // Parse the top element into a header collection.
        const header = top.match(/(\w+)(:)(\/\/)?/);
        const protocol = header && header[1];
        const colon = protocol && header[2];
        const slashes = colon && header[3];
        // Construct the URL prefix.
        const prefix = shorthand
            ? '//'
            : [protocol, colon, slashes].filter(str => str).join('');
        // Construct the URL body omitting the prefix of the top value.
        const body = [top.indexOf(prefix) === 0 ? top.replace(prefix, '') : top]
            // Filter out top value if empty.
            .filter(str => str)
            // Remove leading slashes in all subsequent URL body elements.
            .concat(parts.slice(1).map(str => str.replace(/^\//, '')))
            .join('/')
            // Replace multiple slashes with one.
            .replace(/\/+/g, '/');
        return prefix + body;
    }
    URLExt.join = join;
    /**
     * Encode the components of a multi-segment url.
     *
     * @param url - The url to encode.
     *
     * @returns the encoded url.
     *
     * #### Notes
     * Preserves the `'/'` separators.
     * Should not include the base url, since all parts are escaped.
     */
    function encodeParts(url) {
        return join(...url.split('/').map(encodeURIComponent));
    }
    URLExt.encodeParts = encodeParts;
    /**
     * Return a serialized object string suitable for a query.
     *
     * @param object - The source object.
     *
     * @returns an encoded url query.
     *
     * #### Notes
     * Modified version of [stackoverflow](http://stackoverflow.com/a/30707423).
     */
    function objectToQueryString(value) {
        const keys = Object.keys(value);
        if (!keys.length) {
            return '';
        }
        return ('?' +
            keys
                .map(key => {
                const content = encodeURIComponent(String(value[key]));
                return key + (content ? '=' + content : '');
            })
                .join('&'));
    }
    URLExt.objectToQueryString = objectToQueryString;
    /**
     * Return a parsed object that represents the values in a query string.
     */
    function queryStringToObject(value) {
        return value
            .replace(/^\?/, '')
            .split('&')
            .reduce((acc, val) => {
            const [key, value] = val.split('=');
            acc[key] = decodeURIComponent(value || '');
            return acc;
        }, {});
    }
    URLExt.queryStringToObject = queryStringToObject;
    /**
     * Test whether the url is a local url.
     *
     * #### Notes
     * This function returns `false` for any fully qualified url, including
     * `data:`, `file:`, and `//` protocol URLs.
     */
    function isLocal(url) {
        const { protocol } = parse(url);
        return url.toLowerCase().indexOf(protocol) !== 0 && url.indexOf('//') !== 0;
    }
    URLExt.isLocal = isLocal;
})(URLExt = exports.URLExt || (exports.URLExt = {}));


/***/ }),

/***/ "hwSx":
/*!************************************************!*\
  !*** ./node_modules/plotly-icons/lib/index.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.TraceTypeStreamtubeIcon = exports.TraceTypeSplomIcon = exports.TraceTypeConeIcon = exports.TraceTypeBarpolarIcon = exports.PlotStreamtubeIcon = exports.PlotSplomIcon = exports.PlotConeIcon = exports.PlotBarpolarIcon = undefined;
exports.ZoomboxIcon = exports.ZoomPlusIcon = exports.ZoomMinusIcon = exports.WrenchIcon = exports.VideoIcon = exports.UploadIcon = exports.UploadFileIcon = exports.UnlockIcon = exports.TwitterIcon = exports.TrashIcon = exports.TraceTypeViolinIcon = exports.TraceTypeTimeSeriesIcon = exports.TraceTypeTableIcon = exports.TraceTypeSurfaceIcon = exports.TraceTypeScatterternaryIcon = exports.TraceTypeScatterpolarIcon = exports.TraceTypeScattermapboxIcon = exports.TraceTypeScattergeoIcon = exports.TraceTypeScatterIcon = exports.TraceTypeScatter3dIcon = exports.TraceTypeSankeyIcon = exports.TraceTypeRangeSliderIcon = exports.TraceTypePieIcon = exports.TraceTypeParcoordsIcon = exports.TraceTypeOhlcIcon = exports.TraceTypeMesh3dIcon = exports.TraceTypeLineIcon = exports.TraceTypeLine3dIcon = exports.TraceTypeHistogramIcon = exports.TraceTypeHistogram2dcontourIcon = exports.TraceTypeHistogram2dIcon = exports.TraceTypeHeatmapIcon = exports.TraceTypeErrorBarsIcon = exports.TraceTypeContourIcon = exports.TraceTypeChoroplethIcon = exports.TraceTypeCarpetIcon = exports.TraceTypeCandlestickIcon = exports.TraceTypeBoxIcon = exports.TraceTypeBarIcon = exports.TraceTypeAreaIcon = exports.TraceTypeAnimationIcon = exports.TooltipTextIcon = exports.TooltipIcon = exports.TooltipCompareIcon = exports.TooltipBasicIcon = exports.ThumnailViewIcon = exports.ThemeIcon = exports.TeamIcon = exports.TalkChatMultipleIcon = exports.TalkChatIcon = exports.TagOutlineIcon = exports.TagIcon = exports.SuitcaseIcon = exports.StarIcon = exports.SquareIcon = exports.SpikelineIcon = exports.SignOutIcon = exports.ShareVariantIcon = exports.ShareIcon = exports.SearchIcon = exports.ScriptIcon = exports.SaveIcon = exports.RotateRightIcon = exports.RotateLeftIcon = exports.RevisionsIcon = exports.ResizeUpIcon = exports.ResizeDownIcon = exports.ReorderVerticalIcon = exports.ReorderHorizontalIcon = exports.RefreshIcon = exports.RecentIcon = exports.QuestionIcon = exports.PlusIcon = exports.PlotVolume3dIcon = exports.PlotViolinIcon = exports.PlotTube3dIcon = exports.PlotTimeSeriesIcon = exports.PlotTernaryContourIcon = exports.PlotTableIcon = exports.PlotSurfaceIcon = exports.PlotStackedAreaIcon = exports.PlotScatterternaryIcon = exports.PlotScatterpolarIcon = exports.PlotScattermapboxIcon = exports.PlotScattergeoIcon = exports.PlotScatterMatrixIcon = exports.PlotScatterIcon = exports.PlotScatterChartIcon = exports.PlotScatterAxesIcon = exports.PlotScatter3dIcon = exports.PlotSankeyIcon = exports.PlotRadarIcon = exports.PlotPolarFilledIcon = exports.PlotPieShadedIcon = exports.PlotPieIcon = exports.PlotParcoordsIcon = exports.PlotOhlcIcon = exports.PlotMesh3dIcon = exports.PlotMapLineIcon = exports.PlotLineMarkersIcon = undefined;
exports.PlotLineIcon = exports.PlotLine3dIcon = exports.PlotIsosurface3dIcon = exports.PlotIcon = exports.PlotHistogramIcon = exports.PlotHistogram2dIcon = exports.PlotHistogram2dBricksIcon = exports.PlotHeatmapIcon = exports.PlotFitIcon = exports.PlotErrorBarsIcon = exports.PlotDonutIcon = exports.PlotContourIcon = exports.PlotCone3dIcon = exports.PlotChoroplethIcon = exports.PlotCarpetIcon = exports.PlotCandlestickIcon = exports.PlotCandlestickAltIcon = exports.PlotBubblesIcon = exports.PlotBoxIcon = exports.PlotBarIcon = exports.PlotBarAxesIcon = exports.PlotAreaStackedIcon = exports.PlotAreaIcon = exports.PlayIcon = exports.PhoneIcon = exports.PanIcon = exports.OfficeIcon = exports.NotebookRIcon = exports.NotebookMIconIcon = exports.NotebookIpIcon = exports.MinusIcon = exports.LogoVisaIcon = exports.LogoStripeIcon = exports.LogoMastercardIcon = exports.LogoAmexIcon = exports.LockIcon = exports.ListViewIcon = exports.LinkedInIcon = exports.LinkVariantIcon = exports.LinkIcon = exports.InstagramIcon = exports.InboxIcon = exports.InboxArrowIcon = exports.ImportIcon = exports.HeartIcon = exports.GridIcon = exports.GraphIcon = exports.GooglePlusIcon = exports.GlobeIcon = exports.GitHubIcon = exports.GearsSettingIcon = exports.FullViewIcon = exports.FormatAlignRightIcon = exports.FormatAlignLeftIcon = exports.FormatAlignCenterIcon = exports.ForkIcon = exports.ForkEditIcon = exports.FolderOpenIcon = exports.FolderIcon = exports.FilterIcon = exports.FilingCabinetIcon = exports.FileMultipleIcon = exports.FileIcon = exports.FileDocumentIcon = exports.FacebookIcon = exports.ExternalLinkIcon = exports.EnvelopeOutlineIcon = exports.EnvelopeIcon = exports.EmbedIconIcon = exports.EditIcon = exports.DownloadIcon = exports.CreditCardIcon = exports.ContentCopyIcon = exports.CollaboratorIcon = exports.CogIcon = exports.CodeBracesIcon = exports.CloudIcon = exports.CloseIcon = exports.CheckboxMarkedOutlineIcon = exports.CheckIcon = exports.ChatOutlineIcon = exports.ChatIcon = exports.ChartLineIcon = exports.CarretUpIcon = exports.CarretDownIcon = exports.CalendarMultiselectIcon = exports.BookmarkIcon = exports.BellIcon = exports.BarsIcon = exports.AutoscaleIcon = exports.ArrowUpIcon = exports.ArrowRightIcon = exports.ArrowLeftIcon = exports.ArrowDownIcon = exports.AnimationIcon = exports.AngleUpIcon = exports.AngleRightIcon = exports.AngleLeftIcon = exports.AngleDownIcon = exports.AccountIcon = undefined;

var _AccountIcon = __webpack_require__(/*! mdi-react/AccountIcon */ "CsZw");

var _AccountIcon2 = _interopRequireDefault(_AccountIcon);

var _ChevronDownIcon = __webpack_require__(/*! mdi-react/ChevronDownIcon */ "eE4k");

var _ChevronDownIcon2 = _interopRequireDefault(_ChevronDownIcon);

var _ChevronLeftIcon = __webpack_require__(/*! mdi-react/ChevronLeftIcon */ "V5+5");

var _ChevronLeftIcon2 = _interopRequireDefault(_ChevronLeftIcon);

var _ChevronRightIcon = __webpack_require__(/*! mdi-react/ChevronRightIcon */ "/bma");

var _ChevronRightIcon2 = _interopRequireDefault(_ChevronRightIcon);

var _ChevronUpIcon = __webpack_require__(/*! mdi-react/ChevronUpIcon */ "sxmJ");

var _ChevronUpIcon2 = _interopRequireDefault(_ChevronUpIcon);

var _AnimationIcon = __webpack_require__(/*! mdi-react/AnimationIcon */ "uDDF");

var _AnimationIcon2 = _interopRequireDefault(_AnimationIcon);

var _ArrowDownIcon = __webpack_require__(/*! mdi-react/ArrowDownIcon */ "uxIL");

var _ArrowDownIcon2 = _interopRequireDefault(_ArrowDownIcon);

var _ArrowLeftIcon = __webpack_require__(/*! mdi-react/ArrowLeftIcon */ "NA37");

var _ArrowLeftIcon2 = _interopRequireDefault(_ArrowLeftIcon);

var _ArrowRightIcon = __webpack_require__(/*! mdi-react/ArrowRightIcon */ "eX6c");

var _ArrowRightIcon2 = _interopRequireDefault(_ArrowRightIcon);

var _ArrowUpIcon = __webpack_require__(/*! mdi-react/ArrowUpIcon */ "KEyW");

var _ArrowUpIcon2 = _interopRequireDefault(_ArrowUpIcon);

var _MenuIcon = __webpack_require__(/*! mdi-react/MenuIcon */ "Dy5G");

var _MenuIcon2 = _interopRequireDefault(_MenuIcon);

var _BellIcon = __webpack_require__(/*! mdi-react/BellIcon */ "8m37");

var _BellIcon2 = _interopRequireDefault(_BellIcon);

var _BookmarkIcon = __webpack_require__(/*! mdi-react/BookmarkIcon */ "h+Gr");

var _BookmarkIcon2 = _interopRequireDefault(_BookmarkIcon);

var _MenuDownIcon = __webpack_require__(/*! mdi-react/MenuDownIcon */ "anm7");

var _MenuDownIcon2 = _interopRequireDefault(_MenuDownIcon);

var _MenuUpIcon = __webpack_require__(/*! mdi-react/MenuUpIcon */ "rhW2");

var _MenuUpIcon2 = _interopRequireDefault(_MenuUpIcon);

var _ChartLineIcon = __webpack_require__(/*! mdi-react/ChartLineIcon */ "q9pQ");

var _ChartLineIcon2 = _interopRequireDefault(_ChartLineIcon);

var _MessageIcon = __webpack_require__(/*! mdi-react/MessageIcon */ "BGip");

var _MessageIcon2 = _interopRequireDefault(_MessageIcon);

var _MessageOutlineIcon = __webpack_require__(/*! mdi-react/MessageOutlineIcon */ "FExI");

var _MessageOutlineIcon2 = _interopRequireDefault(_MessageOutlineIcon);

var _CheckboxMarkedOutlineIcon = __webpack_require__(/*! mdi-react/CheckboxMarkedOutlineIcon */ "b4Vw");

var _CheckboxMarkedOutlineIcon2 = _interopRequireDefault(_CheckboxMarkedOutlineIcon);

var _CheckIcon = __webpack_require__(/*! mdi-react/CheckIcon */ "xkL0");

var _CheckIcon2 = _interopRequireDefault(_CheckIcon);

var _CloseIcon = __webpack_require__(/*! mdi-react/CloseIcon */ "t9bh");

var _CloseIcon2 = _interopRequireDefault(_CloseIcon);

var _CloudIcon = __webpack_require__(/*! mdi-react/CloudIcon */ "CUWc");

var _CloudIcon2 = _interopRequireDefault(_CloudIcon);

var _CodeBracesIcon = __webpack_require__(/*! mdi-react/CodeBracesIcon */ "thoC");

var _CodeBracesIcon2 = _interopRequireDefault(_CodeBracesIcon);

var _SettingsIcon = __webpack_require__(/*! mdi-react/SettingsIcon */ "YzzP");

var _SettingsIcon2 = _interopRequireDefault(_SettingsIcon);

var _AccountMultipleIcon = __webpack_require__(/*! mdi-react/AccountMultipleIcon */ "SXi3");

var _AccountMultipleIcon2 = _interopRequireDefault(_AccountMultipleIcon);

var _ContentCopyIcon = __webpack_require__(/*! mdi-react/ContentCopyIcon */ "I1EO");

var _ContentCopyIcon2 = _interopRequireDefault(_ContentCopyIcon);

var _CreditCardIcon = __webpack_require__(/*! mdi-react/CreditCardIcon */ "+vba");

var _CreditCardIcon2 = _interopRequireDefault(_CreditCardIcon);

var _DownloadIcon = __webpack_require__(/*! mdi-react/DownloadIcon */ "a3kb");

var _DownloadIcon2 = _interopRequireDefault(_DownloadIcon);

var _PencilIcon = __webpack_require__(/*! mdi-react/PencilIcon */ "v8QY");

var _PencilIcon2 = _interopRequireDefault(_PencilIcon);

var _EmailIcon = __webpack_require__(/*! mdi-react/EmailIcon */ "w0JW");

var _EmailIcon2 = _interopRequireDefault(_EmailIcon);

var _EmailOutlineIcon = __webpack_require__(/*! mdi-react/EmailOutlineIcon */ "9g5G");

var _EmailOutlineIcon2 = _interopRequireDefault(_EmailOutlineIcon);

var _OpenInNewIcon = __webpack_require__(/*! mdi-react/OpenInNewIcon */ "A5vG");

var _OpenInNewIcon2 = _interopRequireDefault(_OpenInNewIcon);

var _FacebookBoxIcon = __webpack_require__(/*! mdi-react/FacebookBoxIcon */ "plRf");

var _FacebookBoxIcon2 = _interopRequireDefault(_FacebookBoxIcon);

var _FileDocumentIcon = __webpack_require__(/*! mdi-react/FileDocumentIcon */ "mJcH");

var _FileDocumentIcon2 = _interopRequireDefault(_FileDocumentIcon);

var _FileIcon = __webpack_require__(/*! mdi-react/FileIcon */ "mYFI");

var _FileIcon2 = _interopRequireDefault(_FileIcon);

var _FileMultipleIcon = __webpack_require__(/*! mdi-react/FileMultipleIcon */ "K8RU");

var _FileMultipleIcon2 = _interopRequireDefault(_FileMultipleIcon);

var _FilterIcon = __webpack_require__(/*! mdi-react/FilterIcon */ "u2j1");

var _FilterIcon2 = _interopRequireDefault(_FilterIcon);

var _FolderIcon = __webpack_require__(/*! mdi-react/FolderIcon */ "4+N0");

var _FolderIcon2 = _interopRequireDefault(_FolderIcon);

var _FolderOpenIcon = __webpack_require__(/*! mdi-react/FolderOpenIcon */ "cHdg");

var _FolderOpenIcon2 = _interopRequireDefault(_FolderOpenIcon);

var _FormatAlignCenterIcon = __webpack_require__(/*! mdi-react/FormatAlignCenterIcon */ "LUd0");

var _FormatAlignCenterIcon2 = _interopRequireDefault(_FormatAlignCenterIcon);

var _FormatAlignLeftIcon = __webpack_require__(/*! mdi-react/FormatAlignLeftIcon */ "vncK");

var _FormatAlignLeftIcon2 = _interopRequireDefault(_FormatAlignLeftIcon);

var _FormatAlignRightIcon = __webpack_require__(/*! mdi-react/FormatAlignRightIcon */ "sgcl");

var _FormatAlignRightIcon2 = _interopRequireDefault(_FormatAlignRightIcon);

var _FullscreenIcon = __webpack_require__(/*! mdi-react/FullscreenIcon */ "uA+y");

var _FullscreenIcon2 = _interopRequireDefault(_FullscreenIcon);

var _GithubCircleIcon = __webpack_require__(/*! mdi-react/GithubCircleIcon */ "DE1x");

var _GithubCircleIcon2 = _interopRequireDefault(_GithubCircleIcon);

var _EarthIcon = __webpack_require__(/*! mdi-react/EarthIcon */ "dnhB");

var _EarthIcon2 = _interopRequireDefault(_EarthIcon);

var _GooglePlusIcon = __webpack_require__(/*! mdi-react/GooglePlusIcon */ "vRxK");

var _GooglePlusIcon2 = _interopRequireDefault(_GooglePlusIcon);

var _PollIcon = __webpack_require__(/*! mdi-react/PollIcon */ "Z3kI");

var _PollIcon2 = _interopRequireDefault(_PollIcon);

var _GridIcon = __webpack_require__(/*! mdi-react/GridIcon */ "pboZ");

var _GridIcon2 = _interopRequireDefault(_GridIcon);

var _HeartIcon = __webpack_require__(/*! mdi-react/HeartIcon */ "+7xj");

var _HeartIcon2 = _interopRequireDefault(_HeartIcon);

var _ImportIcon = __webpack_require__(/*! mdi-react/ImportIcon */ "RAar");

var _ImportIcon2 = _interopRequireDefault(_ImportIcon);

var _InboxArrowDownIcon = __webpack_require__(/*! mdi-react/InboxArrowDownIcon */ "x5nQ");

var _InboxArrowDownIcon2 = _interopRequireDefault(_InboxArrowDownIcon);

var _InboxIcon = __webpack_require__(/*! mdi-react/InboxIcon */ "AaHf");

var _InboxIcon2 = _interopRequireDefault(_InboxIcon);

var _InstagramIcon = __webpack_require__(/*! mdi-react/InstagramIcon */ "+xTY");

var _InstagramIcon2 = _interopRequireDefault(_InstagramIcon);

var _LinkedinBoxIcon = __webpack_require__(/*! mdi-react/LinkedinBoxIcon */ "ZLPw");

var _LinkedinBoxIcon2 = _interopRequireDefault(_LinkedinBoxIcon);

var _LinkVariantIcon = __webpack_require__(/*! mdi-react/LinkVariantIcon */ "JReR");

var _LinkVariantIcon2 = _interopRequireDefault(_LinkVariantIcon);

var _ViewListIcon = __webpack_require__(/*! mdi-react/ViewListIcon */ "t7hN");

var _ViewListIcon2 = _interopRequireDefault(_ViewListIcon);

var _LockIcon = __webpack_require__(/*! mdi-react/LockIcon */ "x1Ex");

var _LockIcon2 = _interopRequireDefault(_LockIcon);

var _MinusIcon = __webpack_require__(/*! mdi-react/MinusIcon */ "h5Cg");

var _MinusIcon2 = _interopRequireDefault(_MinusIcon);

var _DomainIcon = __webpack_require__(/*! mdi-react/DomainIcon */ "xDYf");

var _DomainIcon2 = _interopRequireDefault(_DomainIcon);

var _PhoneIcon = __webpack_require__(/*! mdi-react/PhoneIcon */ "AiYS");

var _PhoneIcon2 = _interopRequireDefault(_PhoneIcon);

var _PlayIcon = __webpack_require__(/*! mdi-react/PlayIcon */ "oFr5");

var _PlayIcon2 = _interopRequireDefault(_PlayIcon);

var _PlusIcon = __webpack_require__(/*! mdi-react/PlusIcon */ "QXkm");

var _PlusIcon2 = _interopRequireDefault(_PlusIcon);

var _HelpCircleIcon = __webpack_require__(/*! mdi-react/HelpCircleIcon */ "il2e");

var _HelpCircleIcon2 = _interopRequireDefault(_HelpCircleIcon);

var _ClockIcon = __webpack_require__(/*! mdi-react/ClockIcon */ "RIFs");

var _ClockIcon2 = _interopRequireDefault(_ClockIcon);

var _RefreshIcon = __webpack_require__(/*! mdi-react/RefreshIcon */ "1Ub6");

var _RefreshIcon2 = _interopRequireDefault(_RefreshIcon);

var _ReorderHorizontalIcon = __webpack_require__(/*! mdi-react/ReorderHorizontalIcon */ "PShT");

var _ReorderHorizontalIcon2 = _interopRequireDefault(_ReorderHorizontalIcon);

var _ReorderVerticalIcon = __webpack_require__(/*! mdi-react/ReorderVerticalIcon */ "XXzh");

var _ReorderVerticalIcon2 = _interopRequireDefault(_ReorderVerticalIcon);

var _ArrowCollapseIcon = __webpack_require__(/*! mdi-react/ArrowCollapseIcon */ "iWb3");

var _ArrowCollapseIcon2 = _interopRequireDefault(_ArrowCollapseIcon);

var _ArrowExpandIcon = __webpack_require__(/*! mdi-react/ArrowExpandIcon */ "+5Rf");

var _ArrowExpandIcon2 = _interopRequireDefault(_ArrowExpandIcon);

var _HistoryIcon = __webpack_require__(/*! mdi-react/HistoryIcon */ "VnmM");

var _HistoryIcon2 = _interopRequireDefault(_HistoryIcon);

var _RotateLeftIcon = __webpack_require__(/*! mdi-react/RotateLeftIcon */ "up8o");

var _RotateLeftIcon2 = _interopRequireDefault(_RotateLeftIcon);

var _RotateRightIcon = __webpack_require__(/*! mdi-react/RotateRightIcon */ "RcvF");

var _RotateRightIcon2 = _interopRequireDefault(_RotateRightIcon);

var _ContentSaveIcon = __webpack_require__(/*! mdi-react/ContentSaveIcon */ "tQ3M");

var _ContentSaveIcon2 = _interopRequireDefault(_ContentSaveIcon);

var _MagnifyIcon = __webpack_require__(/*! mdi-react/MagnifyIcon */ "W+nl");

var _MagnifyIcon2 = _interopRequireDefault(_MagnifyIcon);

var _ShareIcon = __webpack_require__(/*! mdi-react/ShareIcon */ "vMpC");

var _ShareIcon2 = _interopRequireDefault(_ShareIcon);

var _ShareVariantIcon = __webpack_require__(/*! mdi-react/ShareVariantIcon */ "2Y0J");

var _ShareVariantIcon2 = _interopRequireDefault(_ShareVariantIcon);

var _LogoutIcon = __webpack_require__(/*! mdi-react/LogoutIcon */ "u84l");

var _LogoutIcon2 = _interopRequireDefault(_LogoutIcon);

var _CropSquareIcon = __webpack_require__(/*! mdi-react/CropSquareIcon */ "52JE");

var _CropSquareIcon2 = _interopRequireDefault(_CropSquareIcon);

var _StarIcon = __webpack_require__(/*! mdi-react/StarIcon */ "GwDy");

var _StarIcon2 = _interopRequireDefault(_StarIcon);

var _BriefcaseIcon = __webpack_require__(/*! mdi-react/BriefcaseIcon */ "3B+o");

var _BriefcaseIcon2 = _interopRequireDefault(_BriefcaseIcon);

var _TableIcon = __webpack_require__(/*! mdi-react/TableIcon */ "0+hG");

var _TableIcon2 = _interopRequireDefault(_TableIcon);

var _TagIcon = __webpack_require__(/*! mdi-react/TagIcon */ "nLT/");

var _TagIcon2 = _interopRequireDefault(_TagIcon);

var _TagOutlineIcon = __webpack_require__(/*! mdi-react/TagOutlineIcon */ "TYdR");

var _TagOutlineIcon2 = _interopRequireDefault(_TagOutlineIcon);

var _ForumIcon = __webpack_require__(/*! mdi-react/ForumIcon */ "UV20");

var _ForumIcon2 = _interopRequireDefault(_ForumIcon);

var _AccountMultipleOutlineIcon = __webpack_require__(/*! mdi-react/AccountMultipleOutlineIcon */ "EzBX");

var _AccountMultipleOutlineIcon2 = _interopRequireDefault(_AccountMultipleOutlineIcon);

var _FormatPaintIcon = __webpack_require__(/*! mdi-react/FormatPaintIcon */ "YJeH");

var _FormatPaintIcon2 = _interopRequireDefault(_FormatPaintIcon);

var _AppsIcon = __webpack_require__(/*! mdi-react/AppsIcon */ "aaTI");

var _AppsIcon2 = _interopRequireDefault(_AppsIcon);

var _TooltipIcon = __webpack_require__(/*! mdi-react/TooltipIcon */ "dfSG");

var _TooltipIcon2 = _interopRequireDefault(_TooltipIcon);

var _TooltipTextIcon = __webpack_require__(/*! mdi-react/TooltipTextIcon */ "XYy6");

var _TooltipTextIcon2 = _interopRequireDefault(_TooltipTextIcon);

var _DeleteIcon = __webpack_require__(/*! mdi-react/DeleteIcon */ "9q4B");

var _DeleteIcon2 = _interopRequireDefault(_DeleteIcon);

var _TwitterIcon = __webpack_require__(/*! mdi-react/TwitterIcon */ "XdQh");

var _TwitterIcon2 = _interopRequireDefault(_TwitterIcon);

var _LockOpenIcon = __webpack_require__(/*! mdi-react/LockOpenIcon */ "lANe");

var _LockOpenIcon2 = _interopRequireDefault(_LockOpenIcon);

var _FileExportIcon = __webpack_require__(/*! mdi-react/FileExportIcon */ "o7Pk");

var _FileExportIcon2 = _interopRequireDefault(_FileExportIcon);

var _UploadIcon = __webpack_require__(/*! mdi-react/UploadIcon */ "nwCA");

var _UploadIcon2 = _interopRequireDefault(_UploadIcon);

var _VideoIcon = __webpack_require__(/*! mdi-react/VideoIcon */ "QqEw");

var _VideoIcon2 = _interopRequireDefault(_VideoIcon);

var _WrenchIcon = __webpack_require__(/*! mdi-react/WrenchIcon */ "u6YH");

var _WrenchIcon2 = _interopRequireDefault(_WrenchIcon);

var _CalendarMultiselectIcon = __webpack_require__(/*! mdi-react/CalendarMultiselectIcon */ "bKup");

var _CalendarMultiselectIcon2 = _interopRequireDefault(_CalendarMultiselectIcon);

var _components = __webpack_require__(/*! ./components */ "0HMq");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

// Material Design Icons
exports.AccountIcon = _AccountIcon2.default;
exports.AngleDownIcon = _ChevronDownIcon2.default;
exports.AngleLeftIcon = _ChevronLeftIcon2.default;
exports.AngleRightIcon = _ChevronRightIcon2.default;
exports.AngleUpIcon = _ChevronUpIcon2.default;
exports.AnimationIcon = _AnimationIcon2.default;
exports.ArrowDownIcon = _ArrowDownIcon2.default;
exports.ArrowLeftIcon = _ArrowLeftIcon2.default;
exports.ArrowRightIcon = _ArrowRightIcon2.default;
exports.ArrowUpIcon = _ArrowUpIcon2.default;
exports.AutoscaleIcon = _components.AutoscaleIcon;
exports.BarsIcon = _MenuIcon2.default;
exports.BellIcon = _BellIcon2.default;
exports.BookmarkIcon = _BookmarkIcon2.default;
exports.CalendarMultiselectIcon = _CalendarMultiselectIcon2.default;
exports.CarretDownIcon = _MenuDownIcon2.default;
exports.CarretUpIcon = _MenuUpIcon2.default;
exports.ChartLineIcon = _ChartLineIcon2.default;
exports.ChatIcon = _MessageIcon2.default;
exports.ChatOutlineIcon = _MessageOutlineIcon2.default;
exports.CheckIcon = _CheckIcon2.default;
exports.CheckboxMarkedOutlineIcon = _CheckboxMarkedOutlineIcon2.default;
exports.CloseIcon = _CloseIcon2.default;
exports.CloudIcon = _CloudIcon2.default;
exports.CodeBracesIcon = _CodeBracesIcon2.default;
exports.CogIcon = _SettingsIcon2.default;
exports.CollaboratorIcon = _AccountMultipleIcon2.default;
exports.ContentCopyIcon = _ContentCopyIcon2.default;
exports.CreditCardIcon = _CreditCardIcon2.default;
exports.DownloadIcon = _DownloadIcon2.default;
exports.EditIcon = _PencilIcon2.default;
exports.EmbedIconIcon = _components.EmbedIconIcon;
exports.EnvelopeIcon = _EmailIcon2.default;
exports.EnvelopeOutlineIcon = _EmailOutlineIcon2.default;
exports.ExternalLinkIcon = _OpenInNewIcon2.default;
exports.FacebookIcon = _FacebookBoxIcon2.default;
exports.FileDocumentIcon = _FileDocumentIcon2.default;
exports.FileIcon = _FileIcon2.default;
exports.FileMultipleIcon = _FileMultipleIcon2.default;
exports.FilingCabinetIcon = _components.FilingCabinetIcon;
exports.FilterIcon = _FilterIcon2.default;
exports.FolderIcon = _FolderIcon2.default;
exports.FolderOpenIcon = _FolderOpenIcon2.default;
exports.ForkEditIcon = _components.ForkEditIcon;
exports.ForkIcon = _components.ForkIcon;
exports.FormatAlignCenterIcon = _FormatAlignCenterIcon2.default;
exports.FormatAlignLeftIcon = _FormatAlignLeftIcon2.default;
exports.FormatAlignRightIcon = _FormatAlignRightIcon2.default;
exports.FullViewIcon = _FullscreenIcon2.default;
exports.GearsSettingIcon = _components.GearsSettingIcon;
exports.GitHubIcon = _GithubCircleIcon2.default;
exports.GlobeIcon = _EarthIcon2.default;
exports.GooglePlusIcon = _GooglePlusIcon2.default;
exports.GraphIcon = _PollIcon2.default;
exports.GridIcon = _GridIcon2.default;
exports.HeartIcon = _HeartIcon2.default;
exports.ImportIcon = _ImportIcon2.default;
exports.InboxArrowIcon = _InboxArrowDownIcon2.default;
exports.InboxIcon = _InboxIcon2.default;
exports.InstagramIcon = _InstagramIcon2.default;
exports.LinkIcon = _LinkVariantIcon2.default;
exports.LinkVariantIcon = _LinkVariantIcon2.default;
exports.LinkedInIcon = _LinkedinBoxIcon2.default;
exports.ListViewIcon = _ViewListIcon2.default;
exports.LockIcon = _LockIcon2.default;
exports.LogoAmexIcon = _components.LogoAmexIcon;
exports.LogoMastercardIcon = _components.LogoMastercardIcon;
exports.LogoStripeIcon = _components.LogoStripeIcon;
exports.LogoVisaIcon = _components.LogoVisaIcon;
exports.MinusIcon = _MinusIcon2.default;
exports.NotebookIpIcon = _components.NotebookIpIcon;
exports.NotebookMIconIcon = _components.NotebookMIconIcon;
exports.NotebookRIcon = _components.NotebookRIcon;
exports.OfficeIcon = _DomainIcon2.default;
exports.PanIcon = _components.PanIcon;
exports.PhoneIcon = _PhoneIcon2.default;
exports.PlayIcon = _PlayIcon2.default;
exports.PlotAreaIcon = _components.PlotAreaIcon;
exports.PlotAreaStackedIcon = _components.PlotAreaStackedIcon;
exports.PlotBarAxesIcon = _components.PlotBarAxesIcon;
exports.PlotBarIcon = _components.PlotBarIcon;
exports.PlotBoxIcon = _components.PlotBoxIcon;
exports.PlotBubblesIcon = _components.PlotBubblesIcon;
exports.PlotCandlestickAltIcon = _components.PlotCandlestickAltIcon;
exports.PlotCandlestickIcon = _components.PlotCandlestickIcon;
exports.PlotCarpetIcon = _components.PlotCarpetIcon;
exports.PlotChoroplethIcon = _components.PlotChoroplethIcon;
exports.PlotCone3dIcon = _components.PlotCone3dIcon;
exports.PlotContourIcon = _components.PlotContourIcon;
exports.PlotDonutIcon = _components.PlotDonutIcon;
exports.PlotErrorBarsIcon = _components.PlotErrorBarsIcon;
exports.PlotFitIcon = _components.PlotFitIcon;
exports.PlotHeatmapIcon = _components.PlotHeatmapIcon;
exports.PlotHistogram2dBricksIcon = _components.PlotHistogram2dBricksIcon;
exports.PlotHistogram2dIcon = _components.PlotHistogram2dIcon;
exports.PlotHistogramIcon = _components.PlotHistogramIcon;
exports.PlotIcon = _components.PlotIcon;
exports.PlotIsosurface3dIcon = _components.PlotIsosurface3dIcon;
exports.PlotLine3dIcon = _components.PlotLine3dIcon;
exports.PlotLineIcon = _components.PlotLineIcon;
exports.PlotLineMarkersIcon = _components.PlotLineMarkersIcon;
exports.PlotMapLineIcon = _components.PlotMapLineIcon;
exports.PlotMesh3dIcon = _components.PlotMesh3dIcon;
exports.PlotOhlcIcon = _components.PlotOhlcIcon;
exports.PlotParcoordsIcon = _components.PlotParcoordsIcon;
exports.PlotPieIcon = _components.PlotPieIcon;
exports.PlotPieShadedIcon = _components.PlotPieShadedIcon;
exports.PlotPolarFilledIcon = _components.PlotPolarFilledIcon;
exports.PlotRadarIcon = _components.PlotRadarIcon;
exports.PlotSankeyIcon = _components.PlotSankeyIcon;
exports.PlotScatter3dIcon = _components.PlotScatter3dIcon;
exports.PlotScatterAxesIcon = _components.PlotScatterAxesIcon;
exports.PlotScatterChartIcon = _components.PlotScatterChartIcon;
exports.PlotScatterIcon = _components.PlotScatterIcon;
exports.PlotScatterMatrixIcon = _components.PlotScatterMatrixIcon;
exports.PlotScattergeoIcon = _components.PlotScattergeoIcon;
exports.PlotScattermapboxIcon = _components.PlotScattermapboxIcon;
exports.PlotScatterpolarIcon = _components.PlotScatterpolarIcon;
exports.PlotScatterternaryIcon = _components.PlotScatterternaryIcon;
exports.PlotStackedAreaIcon = _components.PlotStackedAreaIcon;
exports.PlotSurfaceIcon = _components.PlotSurfaceIcon;
exports.PlotTableIcon = _TableIcon2.default;
exports.PlotTernaryContourIcon = _components.PlotTernaryContourIcon;
exports.PlotTimeSeriesIcon = _components.PlotTimeSeriesIcon;
exports.PlotTube3dIcon = _components.PlotTube3dIcon;
exports.PlotViolinIcon = _components.PlotViolinIcon;
exports.PlotVolume3dIcon = _components.PlotVolume3dIcon;
exports.PlusIcon = _PlusIcon2.default;
exports.QuestionIcon = _HelpCircleIcon2.default;
exports.RecentIcon = _ClockIcon2.default;
exports.RefreshIcon = _RefreshIcon2.default;
exports.ReorderHorizontalIcon = _ReorderHorizontalIcon2.default;
exports.ReorderVerticalIcon = _ReorderVerticalIcon2.default;
exports.ResizeDownIcon = _ArrowCollapseIcon2.default;
exports.ResizeUpIcon = _ArrowExpandIcon2.default;
exports.RevisionsIcon = _HistoryIcon2.default;
exports.RotateLeftIcon = _RotateLeftIcon2.default;
exports.RotateRightIcon = _RotateRightIcon2.default;
exports.SaveIcon = _ContentSaveIcon2.default;
exports.ScriptIcon = _components.ScriptIcon;
exports.SearchIcon = _MagnifyIcon2.default;
exports.ShareIcon = _ShareIcon2.default;
exports.ShareVariantIcon = _ShareVariantIcon2.default;
exports.SignOutIcon = _LogoutIcon2.default;
exports.SpikelineIcon = _components.SpikelineIcon;
exports.SquareIcon = _CropSquareIcon2.default;
exports.StarIcon = _StarIcon2.default;
exports.SuitcaseIcon = _BriefcaseIcon2.default;
exports.TagIcon = _TagIcon2.default;
exports.TagOutlineIcon = _TagOutlineIcon2.default;
exports.TalkChatIcon = _MessageIcon2.default;
exports.TalkChatMultipleIcon = _ForumIcon2.default;
exports.TeamIcon = _AccountMultipleOutlineIcon2.default;
exports.ThemeIcon = _FormatPaintIcon2.default;
exports.ThumnailViewIcon = _AppsIcon2.default;
exports.TooltipBasicIcon = _components.TooltipBasicIcon;
exports.TooltipCompareIcon = _components.TooltipCompareIcon;
exports.TooltipIcon = _TooltipIcon2.default;
exports.TooltipTextIcon = _TooltipTextIcon2.default;
exports.TraceTypeAnimationIcon = _components.TraceTypeAnimationIcon;
exports.TraceTypeAreaIcon = _components.TraceTypeAreaIcon;
exports.TraceTypeBarIcon = _components.TraceTypeBarIcon;
exports.TraceTypeBoxIcon = _components.TraceTypeBoxIcon;
exports.TraceTypeCandlestickIcon = _components.TraceTypeCandlestickIcon;
exports.TraceTypeCarpetIcon = _components.TraceTypeCarpetIcon;
exports.TraceTypeChoroplethIcon = _components.TraceTypeChoroplethIcon;
exports.TraceTypeContourIcon = _components.TraceTypeContourIcon;
exports.TraceTypeErrorBarsIcon = _components.TraceTypeErrorBarsIcon;
exports.TraceTypeHeatmapIcon = _components.TraceTypeHeatmapIcon;
exports.TraceTypeHistogram2dIcon = _components.TraceTypeHistogram2dIcon;
exports.TraceTypeHistogram2dcontourIcon = _components.TraceTypeHistogram2dcontourIcon;
exports.TraceTypeHistogramIcon = _components.TraceTypeHistogramIcon;
exports.TraceTypeLine3dIcon = _components.TraceTypeLine3dIcon;
exports.TraceTypeLineIcon = _components.TraceTypeLineIcon;
exports.TraceTypeMesh3dIcon = _components.TraceTypeMesh3dIcon;
exports.TraceTypeOhlcIcon = _components.TraceTypeOhlcIcon;
exports.TraceTypeParcoordsIcon = _components.TraceTypeParcoordsIcon;
exports.TraceTypePieIcon = _components.TraceTypePieIcon;
exports.TraceTypeRangeSliderIcon = _components.TraceTypeRangeSliderIcon;
exports.TraceTypeSankeyIcon = _components.TraceTypeSankeyIcon;
exports.TraceTypeScatter3dIcon = _components.TraceTypeScatter3dIcon;
exports.TraceTypeScatterIcon = _components.TraceTypeScatterIcon;
exports.TraceTypeScattergeoIcon = _components.TraceTypeScattergeoIcon;
exports.TraceTypeScattermapboxIcon = _components.TraceTypeScattermapboxIcon;
exports.TraceTypeScatterpolarIcon = _components.TraceTypeScatterpolarIcon;
exports.TraceTypeScatterternaryIcon = _components.TraceTypeScatterternaryIcon;
exports.TraceTypeSurfaceIcon = _components.TraceTypeSurfaceIcon;
exports.TraceTypeTableIcon = _components.TraceTypeTableIcon;
exports.TraceTypeTimeSeriesIcon = _components.TraceTypeTimeSeriesIcon;
exports.TraceTypeViolinIcon = _components.TraceTypeViolinIcon;
exports.TrashIcon = _DeleteIcon2.default;
exports.TwitterIcon = _TwitterIcon2.default;
exports.UnlockIcon = _LockOpenIcon2.default;
exports.UploadFileIcon = _FileExportIcon2.default;
exports.UploadIcon = _UploadIcon2.default;
exports.VideoIcon = _VideoIcon2.default;
exports.WrenchIcon = _WrenchIcon2.default;
exports.ZoomMinusIcon = _components.ZoomMinusIcon;
exports.ZoomPlusIcon = _components.ZoomPlusIcon;
exports.ZoomboxIcon = _components.ZoomboxIcon;
exports.PlotBarpolarIcon = _components.PlotBarpolarIcon;
exports.PlotConeIcon = _components.PlotConeIcon;
exports.PlotSplomIcon = _components.PlotSplomIcon;
exports.PlotStreamtubeIcon = _components.PlotStreamtubeIcon;
exports.TraceTypeBarpolarIcon = _components.TraceTypeBarpolarIcon;
exports.TraceTypeConeIcon = _components.TraceTypeConeIcon;
exports.TraceTypeSplomIcon = _components.TraceTypeSplomIcon;
exports.TraceTypeStreamtubeIcon = _components.TraceTypeStreamtubeIcon;

/***/ }),

/***/ "hwdV":
/*!*******************************************!*\
  !*** ./node_modules/safe-buffer/index.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* eslint-disable node/no-deprecated-api */
var buffer = __webpack_require__(/*! buffer */ "tjlA")
var Buffer = buffer.Buffer

// alternative to using Object.keys for old browsers
function copyProps (src, dst) {
  for (var key in src) {
    dst[key] = src[key]
  }
}
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  module.exports = buffer
} else {
  // Copy properties from require('buffer')
  copyProps(buffer, exports)
  exports.Buffer = SafeBuffer
}

function SafeBuffer (arg, encodingOrOffset, length) {
  return Buffer(arg, encodingOrOffset, length)
}

// Copy static methods from Buffer
copyProps(Buffer, SafeBuffer)

SafeBuffer.from = function (arg, encodingOrOffset, length) {
  if (typeof arg === 'number') {
    throw new TypeError('Argument must not be a number')
  }
  return Buffer(arg, encodingOrOffset, length)
}

SafeBuffer.alloc = function (size, fill, encoding) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  var buf = Buffer(size)
  if (fill !== undefined) {
    if (typeof encoding === 'string') {
      buf.fill(fill, encoding)
    } else {
      buf.fill(fill)
    }
  } else {
    buf.fill(0)
  }
  return buf
}

SafeBuffer.allocUnsafe = function (size) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  return Buffer(size)
}

SafeBuffer.allocUnsafeSlow = function (size) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  return buffer.SlowBuffer(size)
}


/***/ }),

/***/ "hyAj":
/*!***************************************************************!*\
  !*** ./node_modules/draft-js/lib/getFragmentFromSelection.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule getFragmentFromSelection
 * @format
 * 
 */



var getContentStateFragment = __webpack_require__(/*! ./getContentStateFragment */ "DYKh");

function getFragmentFromSelection(editorState) {
  var selectionState = editorState.getSelection();

  if (selectionState.isCollapsed()) {
    return null;
  }

  return getContentStateFragment(editorState.getCurrentContent(), selectionState);
}

module.exports = getFragmentFromSelection;

/***/ }),

/***/ "hypo":
/*!*************************************************!*\
  !*** ./node_modules/lodash/_baseAssignValue.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var defineProperty = __webpack_require__(/*! ./_defineProperty */ "O0oS");

/**
 * 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;
  }
}

module.exports = baseAssignValue;


/***/ }),

/***/ "i/Fu":
/*!************************************************************!*\
  !*** ./node_modules/xterm/lib/renderer/TextRenderLayer.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Buffer_1 = __webpack_require__(/*! ../Buffer */ "MsZC");
var Types_1 = __webpack_require__(/*! ./Types */ "jVSn");
var Types_2 = __webpack_require__(/*! ./atlas/Types */ "2+Wn");
var GridCache_1 = __webpack_require__(/*! ./GridCache */ "7vZz");
var BaseRenderLayer_1 = __webpack_require__(/*! ./BaseRenderLayer */ "HHOg");
var TextRenderLayer = (function (_super) {
    __extends(TextRenderLayer, _super);
    function TextRenderLayer(container, zIndex, colors, alpha) {
        var _this = _super.call(this, container, 'text', zIndex, alpha, colors) || this;
        _this._characterOverlapCache = {};
        _this._state = new GridCache_1.GridCache();
        return _this;
    }
    TextRenderLayer.prototype.resize = function (terminal, dim) {
        _super.prototype.resize.call(this, terminal, dim);
        var terminalFont = this._getFont(terminal, false);
        if (this._characterWidth !== dim.scaledCharWidth || this._characterFont !== terminalFont) {
            this._characterWidth = dim.scaledCharWidth;
            this._characterFont = terminalFont;
            this._characterOverlapCache = {};
        }
        this._state.clear();
        this._state.resize(terminal.cols, terminal.rows);
    };
    TextRenderLayer.prototype.reset = function (terminal) {
        this._state.clear();
        this.clearAll();
    };
    TextRenderLayer.prototype.onGridChanged = function (terminal, startRow, endRow) {
        if (this._state.cache.length === 0) {
            return;
        }
        for (var y = startRow; y <= endRow; y++) {
            var row = y + terminal.buffer.ydisp;
            var line = terminal.buffer.lines.get(row);
            this.clearCells(0, y, terminal.cols, 1);
            for (var x = 0; x < terminal.cols; x++) {
                var charData = line[x];
                var code = charData[Buffer_1.CHAR_DATA_CODE_INDEX];
                var char = charData[Buffer_1.CHAR_DATA_CHAR_INDEX];
                var attr = charData[Buffer_1.CHAR_DATA_ATTR_INDEX];
                var width = charData[Buffer_1.CHAR_DATA_WIDTH_INDEX];
                if (width === 0) {
                    continue;
                }
                if (code === 32) {
                    if (x > 0) {
                        var previousChar = line[x - 1];
                        if (this._isOverlapping(previousChar)) {
                            continue;
                        }
                    }
                }
                var flags = attr >> 18;
                var bg = attr & 0x1ff;
                var isDefaultBackground = bg >= 256;
                var isInvisible = flags & Types_1.FLAGS.INVISIBLE;
                var isInverted = flags & Types_1.FLAGS.INVERSE;
                if (!code || (code === 32 && isDefaultBackground && !isInverted) || isInvisible) {
                    continue;
                }
                if (width !== 0 && this._isOverlapping(charData)) {
                    if (x < line.length - 1 && line[x + 1][Buffer_1.CHAR_DATA_CODE_INDEX] === 32) {
                        width = 2;
                    }
                }
                var fg = (attr >> 9) & 0x1ff;
                if (isInverted) {
                    var temp = bg;
                    bg = fg;
                    fg = temp;
                    if (fg === 256) {
                        fg = Types_2.INVERTED_DEFAULT_COLOR;
                    }
                    if (bg === 257) {
                        bg = Types_2.INVERTED_DEFAULT_COLOR;
                    }
                }
                if (width === 2) {
                }
                if (bg < 256) {
                    this._ctx.save();
                    this._ctx.fillStyle = (bg === Types_2.INVERTED_DEFAULT_COLOR ? this._colors.foreground.css : this._colors.ansi[bg].css);
                    this.fillCells(x, y, width, 1);
                    this._ctx.restore();
                }
                this._ctx.save();
                if (flags & Types_1.FLAGS.BOLD) {
                    this._ctx.font = this._getFont(terminal, true);
                    if (fg < 8) {
                        fg += 8;
                    }
                }
                if (flags & Types_1.FLAGS.UNDERLINE) {
                    if (fg === Types_2.INVERTED_DEFAULT_COLOR) {
                        this._ctx.fillStyle = this._colors.background.css;
                    }
                    else if (fg < 256) {
                        this._ctx.fillStyle = this._colors.ansi[fg].css;
                    }
                    else {
                        this._ctx.fillStyle = this._colors.foreground.css;
                    }
                    this.fillBottomLineAtCells(x, y);
                }
                this.drawChar(terminal, char, code, width, x, y, fg, bg, !!(flags & Types_1.FLAGS.BOLD), !!(flags & Types_1.FLAGS.DIM));
                this._ctx.restore();
            }
        }
    };
    TextRenderLayer.prototype.onOptionsChanged = function (terminal) {
        this.setTransparency(terminal, terminal.options.allowTransparency);
    };
    TextRenderLayer.prototype._isOverlapping = function (charData) {
        if (charData[Buffer_1.CHAR_DATA_WIDTH_INDEX] !== 1) {
            return false;
        }
        var code = charData[Buffer_1.CHAR_DATA_CODE_INDEX];
        if (code < 256) {
            return false;
        }
        var char = charData[Buffer_1.CHAR_DATA_CHAR_INDEX];
        if (this._characterOverlapCache.hasOwnProperty(char)) {
            return this._characterOverlapCache[char];
        }
        this._ctx.save();
        this._ctx.font = this._characterFont;
        var overlaps = Math.floor(this._ctx.measureText(char).width) > this._characterWidth;
        this._ctx.restore();
        this._characterOverlapCache[char] = overlaps;
        return overlaps;
    };
    return TextRenderLayer;
}(BaseRenderLayer_1.BaseRenderLayer));
exports.TextRenderLayer = TextRenderLayer;

//# sourceMappingURL=TextRenderLayer.js.map


/***/ }),

/***/ "i0cE":
/*!******************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/connectUpdateMenuToLayout.js ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

exports.default = connectUpdateMenuToLayout;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _lib = __webpack_require__(/*! ../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function connectUpdateMenuToLayout(WrappedComponent) {
  var UpdateMenuConnectedComponent = function (_Component) {
    _inherits(UpdateMenuConnectedComponent, _Component);

    function UpdateMenuConnectedComponent(props, context) {
      _classCallCheck(this, UpdateMenuConnectedComponent);

      var _this = _possibleConstructorReturn(this, (UpdateMenuConnectedComponent.__proto__ || Object.getPrototypeOf(UpdateMenuConnectedComponent)).call(this, props, context));

      _this.updateUpdateMenu = _this.updateUpdateMenu.bind(_this);
      _this.setLocals(props, context);
      return _this;
    }

    _createClass(UpdateMenuConnectedComponent, [{
      key: 'componentWillReceiveProps',
      value: function componentWillReceiveProps(nextProps, nextContext) {
        this.setLocals(nextProps, nextContext);
      }
    }, {
      key: 'setLocals',
      value: function setLocals(props, context) {
        var updateMenuIndex = props.updateMenuIndex;
        var container = context.container,
            fullContainer = context.fullContainer;


        var updatemenus = container.updatemenus || [];
        var fullUpdateMenus = fullContainer.updatemenus || [];
        this.container = updatemenus[updateMenuIndex];
        this.fullContainer = fullUpdateMenus[updateMenuIndex];
      }
    }, {
      key: 'getChildContext',
      value: function getChildContext() {
        var _this2 = this;

        return {
          getValObject: function getValObject(attr) {
            return !_this2.context.getValObject ? null : _this2.context.getValObject('updatemenus[].' + attr);
          },
          updateContainer: this.updateUpdateMenu,
          container: this.container,
          fullContainer: this.fullContainer
        };
      }
    }, {
      key: 'updateUpdateMenu',
      value: function updateUpdateMenu(update) {
        var newUpdate = {};
        var updateMenuIndex = this.props.updateMenuIndex;

        for (var key in update) {
          var newkey = 'updatemenus[' + updateMenuIndex + '].' + key;
          newUpdate[newkey] = update[key];
        }
        this.context.updateContainer(newUpdate);
      }
    }, {
      key: 'render',
      value: function render() {
        return _react2.default.createElement(WrappedComponent, this.props);
      }
    }]);

    return UpdateMenuConnectedComponent;
  }(_react.Component);

  UpdateMenuConnectedComponent.displayName = 'UpdateMenuConnected' + (0, _lib.getDisplayName)(WrappedComponent);

  UpdateMenuConnectedComponent.propTypes = {
    updateMenuIndex: _propTypes2.default.number.isRequired
  };

  UpdateMenuConnectedComponent.contextTypes = {
    container: _propTypes2.default.object,
    fullContainer: _propTypes2.default.object,
    onUpdate: _propTypes2.default.func,
    updateContainer: _propTypes2.default.func,
    getValObject: _propTypes2.default.func
  };

  UpdateMenuConnectedComponent.childContextTypes = {
    updateContainer: _propTypes2.default.func,
    container: _propTypes2.default.object,
    fullContainer: _propTypes2.default.object,
    getValObject: _propTypes2.default.func
  };

  var plotly_editor_traits = WrappedComponent.plotly_editor_traits;

  UpdateMenuConnectedComponent.plotly_editor_traits = plotly_editor_traits;

  return UpdateMenuConnectedComponent;
}
//# sourceMappingURL=connectUpdateMenuToLayout.js.map

/***/ }),

/***/ "i2zi":
/*!**********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypePieIcon.js ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypePieIcon = function TraceTypePieIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement('path', { fill: 'none', d: 'M0 0h46v46H0z' }),
        _react2.default.createElement('path', { d: 'M23 23l-10.725 8.999A14 14 0 0 0 37 23z', fill: '#1d9bfb' }),
        _react2.default.createElement('path', { d: 'M23 23h14A14 14 0 0 0 25.431 9.213zm0 0H9a14 14 0 0 0 3.275 8.999zm0 0l2.431 13.787A14 14 0 0 0 32 33.725z', fill: '#25fdfc' }),
        _react2.default.createElement('path', { d: 'M23 23l2.431-13.787A14 14 0 0 0 9 23z', fill: '#1d9bfb' }),
        _react2.default.createElement('circle', { cx: '23', cy: '23', r: '6', fill: '#fff' })
    );
};

exports.default = TraceTypePieIcon;

/***/ }),

/***/ "i3FT":
/*!********************************************************!*\
  !*** ./node_modules/asn1.js/lib/asn1/constants/der.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var constants = __webpack_require__(/*! ../constants */ "AhHn");

exports.tagClass = {
  0: 'universal',
  1: 'application',
  2: 'context',
  3: 'private'
};
exports.tagClassByName = constants._reverse(exports.tagClass);

exports.tag = {
  0x00: 'end',
  0x01: 'bool',
  0x02: 'int',
  0x03: 'bitstr',
  0x04: 'octstr',
  0x05: 'null_',
  0x06: 'objid',
  0x07: 'objDesc',
  0x08: 'external',
  0x09: 'real',
  0x0a: 'enum',
  0x0b: 'embed',
  0x0c: 'utf8str',
  0x0d: 'relativeOid',
  0x10: 'seq',
  0x11: 'set',
  0x12: 'numstr',
  0x13: 'printstr',
  0x14: 't61str',
  0x15: 'videostr',
  0x16: 'ia5str',
  0x17: 'utctime',
  0x18: 'gentime',
  0x19: 'graphstr',
  0x1a: 'iso646str',
  0x1b: 'genstr',
  0x1c: 'unistr',
  0x1d: 'charstr',
  0x1e: 'bmpstr'
};
exports.tagByName = constants._reverse(exports.tag);


/***/ }),

/***/ "i5UE":
/*!**************************************************!*\
  !*** ./node_modules/hash.js/lib/hash/sha/384.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var utils = __webpack_require__(/*! ../utils */ "w8CP");

var SHA512 = __webpack_require__(/*! ./512 */ "tSWc");

function SHA384() {
  if (!(this instanceof SHA384))
    return new SHA384();

  SHA512.call(this);
  this.h = [
    0xcbbb9d5d, 0xc1059ed8,
    0x629a292a, 0x367cd507,
    0x9159015a, 0x3070dd17,
    0x152fecd8, 0xf70e5939,
    0x67332667, 0xffc00b31,
    0x8eb44a87, 0x68581511,
    0xdb0c2e0d, 0x64f98fa7,
    0x47b5481d, 0xbefa4fa4 ];
}
utils.inherits(SHA384, SHA512);
module.exports = SHA384;

SHA384.blockSize = 1024;
SHA384.outSize = 384;
SHA384.hmacStrength = 192;
SHA384.padLength = 128;

SHA384.prototype._digest = function digest(enc) {
  if (enc === 'hex')
    return utils.toHex32(this.h.slice(0, 12), 'big');
  else
    return utils.split32(this.h.slice(0, 12), 'big');
};


/***/ }),

/***/ "i8+h":
/*!***************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/EditorControls.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _DefaultEditor = __webpack_require__(/*! ./DefaultEditor */ "p5Q0");

var _DefaultEditor2 = _interopRequireDefault(_DefaultEditor);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ./lib */ "RXjw");

var _shame = __webpack_require__(/*! ./shame */ "2KtR");

var _constants = __webpack_require__(/*! ./lib/constants */ "5Bkx");

var _fastIsnumeric = __webpack_require__(/*! fast-isnumeric */ "GbLo");

var _fastIsnumeric2 = _interopRequireDefault(_fastIsnumeric);

var _nested_property = __webpack_require__(/*! plotly.js/src/lib/nested_property */ "dNZO");

var _nested_property2 = _interopRequireDefault(_nested_property);

var _traceTypes = __webpack_require__(/*! ./lib/traceTypes */ "M2ap");

var _containers = __webpack_require__(/*! ./components/containers */ "Te0A");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var EditorControls = function (_Component) {
  _inherits(EditorControls, _Component);

  function EditorControls(props, context) {
    _classCallCheck(this, EditorControls);

    var _this = _possibleConstructorReturn(this, (EditorControls.__proto__ || Object.getPrototypeOf(EditorControls)).call(this, props, context));

    _this.localize = function (key) {
      return (0, _lib.localizeString)(_this.props.dictionaries || {}, _this.props.locale, key);
    };

    // we only need to compute this once.
    if (_this.props.plotly) {
      _this.plotSchema = _this.props.plotly.PlotSchema.get();
    }
    return _this;
  }

  _createClass(EditorControls, [{
    key: 'getChildContext',
    value: function getChildContext() {
      var gd = this.props.graphDiv || {};
      return {
        advancedTraceTypeSelector: this.props.advancedTraceTypeSelector,
        config: gd._context,
        srcConverters: this.props.srcConverters,
        data: gd.data,
        dataSources: this.props.dataSources,
        dataSourceOptions: this.props.dataSourceOptions,
        dataSourceValueRenderer: this.props.dataSourceValueRenderer,
        dataSourceOptionRenderer: this.props.dataSourceOptionRenderer,
        dictionaries: this.props.dictionaries || {},
        localize: this.localize,
        frames: gd._transitionData ? gd._transitionData._frames : [],
        fullData: gd._fullData,
        fullLayout: gd._fullLayout,
        graphDiv: gd,
        layout: gd.layout,
        locale: this.props.locale,
        onUpdate: this.handleUpdate.bind(this),
        plotSchema: this.plotSchema,
        plotly: this.props.plotly,
        traceTypesConfig: this.props.traceTypesConfig,
        showFieldTooltips: this.props.showFieldTooltips,
        glByDefault: this.props.glByDefault,
        mapBoxAccess: this.props.mapBoxAccess,
        fontOptions: this.props.fontOptions,
        chartHelp: this.props.chartHelp
      };
    }
  }, {
    key: 'handleUpdate',
    value: function handleUpdate(_ref) {
      var type = _ref.type,
          payload = _ref.payload;
      var graphDiv = this.props.graphDiv;


      switch (type) {
        case _constants.EDITOR_ACTIONS.UPDATE_TRACES:
          if (this.props.beforeUpdateTraces) {
            this.props.beforeUpdateTraces(payload);
          }

          (0, _shame.shamefullyAdjustSizeref)(graphDiv, payload);

          (0, _shame.shamefullyClearAxisTypes)(graphDiv, payload);
          (0, _shame.shamefullyAdjustAxisRef)(graphDiv, payload);
          (0, _shame.shamefullyAddTableColumns)(graphDiv, payload);
          (0, _shame.shamefullyAdjustSplitStyleTargetContainers)(graphDiv, payload);

          for (var i = 0; i < payload.traceIndexes.length; i++) {
            var _loop = function _loop(attr) {
              var traceIndex = payload.traceIndexes[i];

              var splitTraceGroup = payload.splitTraceGroup ? payload.splitTraceGroup.toString() : null;

              var props = [(0, _nested_property2.default)(graphDiv.data[traceIndex], attr)];
              var value = payload.update[attr];

              if (splitTraceGroup) {
                props = (0, _shame.shamefullyCreateSplitStyleProps)(graphDiv, attr, traceIndex, splitTraceGroup);
              }

              props.forEach(function (p) {
                if (value !== void 0) {
                  p.set(value);
                }
              });
            };

            for (var attr in payload.update) {
              _loop(attr);
            }
          }

          if (this.props.afterUpdateTraces) {
            this.props.afterUpdateTraces(payload);
          }
          if (this.props.onUpdate) {
            this.props.onUpdate(graphDiv.data.slice(), graphDiv.layout, graphDiv._transitionData._frames);
          }
          break;

        case _constants.EDITOR_ACTIONS.UPDATE_LAYOUT:
          (0, _shame.shamefullyAdjustGeo)(graphDiv, payload);

          if (this.props.beforeUpdateLayout) {
            this.props.beforeUpdateLayout(payload);
          }
          for (var attr in payload.update) {
            var prop = (0, _nested_property2.default)(graphDiv.layout, attr);
            var _value = payload.update[attr];
            if (_value !== void 0) {
              prop.set(_value);
            }
          }
          if (this.props.afterUpdateLayout) {
            this.props.afterUpdateLayout(payload);
          }
          if (this.props.onUpdate) {
            this.props.onUpdate(graphDiv.data, Object.assign({}, graphDiv.layout), graphDiv._transitionData._frames);
          }
          break;

        case _constants.EDITOR_ACTIONS.ADD_TRACE:
          if (this.props.beforeAddTrace) {
            this.props.beforeAddTrace(payload);
          }

          // can't use default prop because plotly.js mutates it:
          // https://github.com/plotly/react-chart-editor/issues/509
          if (graphDiv.data.length === 0) {
            graphDiv.data.push(this.props.makeDefaultTrace ? this.props.makeDefaultTrace() : {
              type: 'scatter' + (this.props.glByDefault ? 'gl' : ''),
              mode: 'markers'
            });
          } else {
            var prevTrace = graphDiv.data[graphDiv.data.length - 1];
            var prevTraceType = (0, _lib.plotlyTraceToCustomTrace)(prevTrace);
            graphDiv.data.push((0, _lib.traceTypeToPlotlyInitFigure)(prevTraceType, prevTrace.type && prevTrace.type.endsWith('gl') ? 'gl' : ''));
          }

          if (this.props.afterAddTrace) {
            this.props.afterAddTrace(payload);
          }
          if (this.props.onUpdate) {
            this.props.onUpdate(graphDiv.data.slice(), graphDiv.layout, graphDiv._transitionData._frames);
          }
          break;

        case _constants.EDITOR_ACTIONS.DELETE_TRACE:
          if (payload.traceIndexes && payload.traceIndexes.length) {
            if (this.props.beforeDeleteTrace) {
              this.props.beforeDeleteTrace(payload);
            }

            (0, _shame.shamefullyAdjustAxisRef)(graphDiv, payload);
            (0, _shame.shamefullyDeleteRelatedAnalysisTransforms)(graphDiv, payload);

            graphDiv.data.splice(payload.traceIndexes[0], 1);
            if (this.props.afterDeleteTrace) {
              this.props.afterDeleteTrace(payload);
            }
            if (this.props.onUpdate) {
              this.props.onUpdate(graphDiv.data.slice(), graphDiv.layout, graphDiv._transitionData._frames);
            }
          }
          break;

        case _constants.EDITOR_ACTIONS.DELETE_ANNOTATION:
          if ((0, _fastIsnumeric2.default)(payload.annotationIndex)) {
            if (this.props.beforeDeleteAnnotation) {
              this.props.beforeDeleteAnnotation(payload);
            }
            graphDiv.layout.annotations.splice(payload.annotationIndex, 1);
            if (this.props.afterDeleteAnnotation) {
              this.props.afterDeleteAnnotation(payload);
            }
            if (this.props.onUpdate) {
              this.props.onUpdate(graphDiv.data, Object.assign({}, graphDiv.layout), graphDiv._transitionData._frames);
            }
          }
          break;

        case _constants.EDITOR_ACTIONS.DELETE_SHAPE:
          if ((0, _fastIsnumeric2.default)(payload.shapeIndex)) {
            if (this.props.beforeDeleteShape) {
              this.props.beforeDeleteShape(payload);
            }
            graphDiv.layout.shapes.splice(payload.shapeIndex, 1);
            if (this.props.afterDeleteShape) {
              this.props.afterDeleteShape(payload);
            }
            if (this.props.onUpdate) {
              this.props.onUpdate(graphDiv.data, Object.assign({}, graphDiv.layout), graphDiv._transitionData._frames);
            }
          }
          break;

        case _constants.EDITOR_ACTIONS.DELETE_IMAGE:
          if ((0, _fastIsnumeric2.default)(payload.imageIndex)) {
            if (this.props.beforeDeleteImage) {
              this.props.beforeDeleteImage(payload);
            }
            graphDiv.layout.images.splice(payload.imageIndex, 1);
            if (this.props.afterDeleteImage) {
              this.props.afterDeleteImage(payload);
            }
            if (this.props.onUpdate) {
              this.props.onUpdate(graphDiv.data, Object.assign({}, graphDiv.layout), graphDiv._transitionData._frames);
            }
          }
          break;

        case _constants.EDITOR_ACTIONS.DELETE_RANGESELECTOR:
          if ((0, _fastIsnumeric2.default)(payload.rangeselectorIndex)) {
            graphDiv.layout[payload.axisId].rangeselector.buttons.splice(payload.rangeselectorIndex, 1);
            if (this.props.onUpdate) {
              this.props.onUpdate(graphDiv.data, Object.assign({}, graphDiv.layout), graphDiv._transitionData._frames);
            }
          }
          break;

        case _constants.EDITOR_ACTIONS.DELETE_TRANSFORM:
          if ((0, _fastIsnumeric2.default)(payload.transformIndex) && payload.traceIndex < graphDiv.data.length) {
            if (graphDiv.data[payload.traceIndex].transforms.length === 1) {
              delete graphDiv.data[payload.traceIndex].transforms;
            } else {
              graphDiv.data[payload.traceIndex].transforms.splice(payload.transformIndex, 1);
            }
            if (this.props.onUpdate) {
              this.props.onUpdate(graphDiv.data.slice(), graphDiv.layout, graphDiv._transitionData._frames);
            }
          }
          break;

        default:
          throw new Error(this.localize('must specify an action type to handleEditorUpdate'));
      }
    }
  }, {
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        'div',
        {
          className: (0, _lib.bem)('editor_controls') + ' plotly-editor--theme-provider' + ('' + (this.props.className ? ' ' + this.props.className : ''))
        },
        _react2.default.createElement(
          _containers.ModalProvider,
          null,
          this.props.graphDiv && this.props.graphDiv._fullLayout && (this.props.children ? this.props.children : _react2.default.createElement(_DefaultEditor2.default, null))
        )
      );
    }
  }]);

  return EditorControls;
}(_react.Component);

EditorControls.propTypes = {
  advancedTraceTypeSelector: _propTypes2.default.bool,
  afterAddTrace: _propTypes2.default.func,
  afterDeleteAnnotation: _propTypes2.default.func,
  afterDeleteShape: _propTypes2.default.func,
  afterDeleteImage: _propTypes2.default.func,
  afterDeleteTrace: _propTypes2.default.func,
  afterUpdateLayout: _propTypes2.default.func,
  afterUpdateTraces: _propTypes2.default.func,
  beforeAddTrace: _propTypes2.default.func,
  beforeDeleteAnnotation: _propTypes2.default.func,
  beforeDeleteShape: _propTypes2.default.func,
  beforeDeleteImage: _propTypes2.default.func,
  beforeDeleteTrace: _propTypes2.default.func,
  beforeUpdateLayout: _propTypes2.default.func,
  beforeUpdateTraces: _propTypes2.default.func,
  children: _propTypes2.default.node,
  className: _propTypes2.default.string,
  srcConverters: _propTypes2.default.shape({
    toSrc: _propTypes2.default.func.isRequired,
    fromSrc: _propTypes2.default.func.isRequired
  }),
  dataSourceOptionRenderer: _propTypes2.default.func,
  dataSourceOptions: _propTypes2.default.array,
  dataSources: _propTypes2.default.object,
  dataSourceValueRenderer: _propTypes2.default.func,
  dictionaries: _propTypes2.default.object,
  graphDiv: _propTypes2.default.object,
  locale: _propTypes2.default.string,
  onUpdate: _propTypes2.default.func,
  plotly: _propTypes2.default.object,
  showFieldTooltips: _propTypes2.default.bool,
  traceTypesConfig: _propTypes2.default.object,
  makeDefaultTrace: _propTypes2.default.func,
  glByDefault: _propTypes2.default.bool,
  mapBoxAccess: _propTypes2.default.bool,
  fontOptions: _propTypes2.default.array,
  chartHelp: _propTypes2.default.object
};

EditorControls.defaultProps = {
  showFieldTooltips: false,
  locale: 'en',
  traceTypesConfig: {
    categories: function categories(_) {
      return (0, _traceTypes.categoryLayout)(_);
    },
    traces: function traces(_) {
      return (0, _traceTypes.traceTypes)(_);
    },
    complex: true
  },
  fontOptions: _constants.DEFAULT_FONTS
};

EditorControls.childContextTypes = {
  advancedTraceTypeSelector: _propTypes2.default.bool,
  config: _propTypes2.default.object,
  srcConverters: _propTypes2.default.shape({
    toSrc: _propTypes2.default.func.isRequired,
    fromSrc: _propTypes2.default.func.isRequired
  }),
  data: _propTypes2.default.array,
  dataSourceOptionRenderer: _propTypes2.default.func,
  dataSourceOptions: _propTypes2.default.array,
  dataSources: _propTypes2.default.object,
  dataSourceValueRenderer: _propTypes2.default.func,
  dictionaries: _propTypes2.default.object,
  frames: _propTypes2.default.array,
  fullData: _propTypes2.default.array,
  fullLayout: _propTypes2.default.object,
  graphDiv: _propTypes2.default.any,
  layout: _propTypes2.default.object,
  locale: _propTypes2.default.string,
  localize: _propTypes2.default.func,
  onUpdate: _propTypes2.default.func,
  plotly: _propTypes2.default.object,
  plotSchema: _propTypes2.default.object,
  traceTypesConfig: _propTypes2.default.object,
  showFieldTooltips: _propTypes2.default.bool,
  glByDefault: _propTypes2.default.bool,
  mapBoxAccess: _propTypes2.default.bool,
  fontOptions: _propTypes2.default.array,
  chartHelp: _propTypes2.default.object
};

exports.default = EditorControls;
//# sourceMappingURL=EditorControls.js.map

/***/ }),

/***/ "i8i4":
/*!*****************************************!*\
  !*** ./node_modules/react-dom/index.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function checkDCE() {
  /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
  if (
    typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' ||
    typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function'
  ) {
    return;
  }
  if (true) {
    // This branch is unreachable because this function is only called
    // in production, but the condition is true only in development.
    // Therefore if the branch is still here, dead code elimination wasn't
    // properly applied.
    // Don't change the message. React DevTools relies on it. Also make sure
    // this message doesn't occur elsewhere in this function, or it will cause
    // a false positive.
    throw new Error('^_^');
  }
  try {
    // Verify that the code above has been dead code eliminated (DCE'd).
    __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);
  } catch (err) {
    // DevTools shouldn't crash React, no matter what.
    // We should still report in case we break this code.
    console.error(err);
  }
}

if (false) {} else {
  module.exports = __webpack_require__(/*! ./cjs/react-dom.development.js */ "Ybsr");
}


/***/ }),

/***/ "i9Oj":
/*!*******************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotRadarIcon.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotRadarIcon = function PlotRadarIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M24.5 4.438l-.063-.063h-.063c-2.375-1.75-5.25-2.75-8.375-2.75s-6 1-8.375 2.75h-.063l-.063.063c-3.563 2.625-5.875 6.813-5.875 11.563 0 1.563.25 3 .688 4.438 0 0 .063 0 .063.063a14.302 14.302 0 0 0 13.625 9.875c6.313 0 11.688-4.125 13.625-9.813v-.063c.5-1.438.75-2.938.75-4.5 0-4.75-2.313-8.938-5.875-11.563zM16 4.25c2.125 0 4.063.563 5.813 1.5l-2.125 2.875C18.625 8.062 17.313 7.75 16 7.75a8.291 8.291 0 0 0-3.75.875L10.187 5.75c1.75-.938 3.688-1.5 5.813-1.5zm2.125 11.063l2.125-3c.875 1 1.438 2.25 1.438 3.688 0 .188-.063.313-.063.438zm2.688 3.625c-.813 1.25-2 2.188-3.5 2.563v-3.688zm-6.938-3.625l-3.5 1.125c0-.125-.063-.25-.063-.438 0-1.438.563-2.688 1.375-3.688zM4.25 16c0-3.25 1.313-6.188 3.438-8.313l.375-.375 2.063 2.813c-1.5 1.5-2.375 3.625-2.375 5.875 0 .438.063.875.125 1.25l-3.375 1.125c-.188-.75-.25-1.563-.25-2.375zm10.438 11.688a11.779 11.779 0 0 1-7-3.375c-1-1-1.813-2.188-2.375-3.438l3.375-1.125c1.125 2.313 3.375 3.938 6 4.375v3.563zm0-6.188a5.673 5.673 0 0 1-3.5-2.563l3.5-1.125zm-.875-10.75c.688-.25 1.375-.438 2.188-.438.75 0 1.5.188 2.188.438l-2.188 3zm10.5 13.563c-1.875 1.813-4.313 3.063-7 3.375v-3.563a8.226 8.226 0 0 0 6-4.375l3.375 1.125a11.696 11.696 0 0 1-2.375 3.438zm3.187-5.938l-3.375-1.125c.063-.375.125-.813.125-1.25 0-2.25-.875-4.375-2.375-5.875l2-2.813c.188.125.313.25.438.375A11.715 11.715 0 0 1 27.751 16c0 .813-.063 1.625-.25 2.375z' })
    );
};

exports.default = PlotRadarIcon;

/***/ }),

/***/ "iCc5":
/*!**************************************************************!*\
  !*** ./node_modules/babel-runtime/helpers/classCallCheck.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

exports.default = function (instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
};

/***/ }),

/***/ "iEDd":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/gl.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var gl = moment.defineLocale('gl', {
    months : 'xaneiro_febreiro_marzo_abril_maio_xuño_xullo_agosto_setembro_outubro_novembro_decembro'.split('_'),
    monthsShort : 'xan._feb._mar._abr._mai._xuñ._xul._ago._set._out._nov._dec.'.split('_'),
    monthsParseExact: true,
    weekdays : 'domingo_luns_martes_mércores_xoves_venres_sábado'.split('_'),
    weekdaysShort : 'dom._lun._mar._mér._xov._ven._sáb.'.split('_'),
    weekdaysMin : 'do_lu_ma_mé_xo_ve_sá'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'H:mm',
        LTS : 'H:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D [de] MMMM [de] YYYY',
        LLL : 'D [de] MMMM [de] YYYY H:mm',
        LLLL : 'dddd, D [de] MMMM [de] YYYY H:mm'
    },
    calendar : {
        sameDay : function () {
            return '[hoxe ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT';
        },
        nextDay : function () {
            return '[mañá ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT';
        },
        nextWeek : function () {
            return 'dddd [' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT';
        },
        lastDay : function () {
            return '[onte ' + ((this.hours() !== 1) ? 'á' : 'a') + '] LT';
        },
        lastWeek : function () {
            return '[o] dddd [pasado ' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT';
        },
        sameElse : 'L'
    },
    relativeTime : {
        future : function (str) {
            if (str.indexOf('un') === 0) {
                return 'n' + str;
            }
            return 'en ' + str;
        },
        past : 'hai %s',
        s : 'uns segundos',
        ss : '%d segundos',
        m : 'un minuto',
        mm : '%d minutos',
        h : 'unha hora',
        hh : '%d horas',
        d : 'un día',
        dd : '%d días',
        M : 'un mes',
        MM : '%d meses',
        y : 'un ano',
        yy : '%d anos'
    },
    dayOfMonthOrdinalParse : /\d{1,2}º/,
    ordinal : '%dº',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return gl;

})));


/***/ }),

/***/ "iGDq":
/*!************************************************************************!*\
  !*** ./node_modules/react-color/lib/components/github/GithubSwatch.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.GithubSwatch = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _common = __webpack_require__(/*! ../common */ "TM95");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var GithubSwatch = exports.GithubSwatch = function GithubSwatch(_ref) {
  var hover = _ref.hover,
      color = _ref.color,
      onClick = _ref.onClick,
      onSwatchHover = _ref.onSwatchHover;

  var hoverSwatch = {
    position: 'relative',
    zIndex: '2',
    outline: '2px solid #fff',
    boxShadow: '0 0 5px 2px rgba(0,0,0,0.25)'
  };

  var styles = (0, _reactcss2.default)({
    'default': {
      swatch: {
        width: '25px',
        height: '25px',
        fontSize: '0'
      }
    },
    'hover': {
      swatch: hoverSwatch
    }
  }, { hover: hover });

  return _react2.default.createElement(
    'div',
    { style: styles.swatch },
    _react2.default.createElement(_common.Swatch, {
      color: color,
      onClick: onClick,
      onHover: onSwatchHover,
      focusStyle: hoverSwatch
    })
  );
};

exports.default = (0, _reactcss.handleHover)(GithubSwatch);

/***/ }),

/***/ "iNX9":
/*!****************************************************!*\
  !*** ./node_modules/xterm/lib/SelectionManager.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var MouseHelper_1 = __webpack_require__(/*! ./utils/MouseHelper */ "jrO0");
var Browser = __webpack_require__(/*! ./shared/utils/Browser */ "1XL3");
var EventEmitter_1 = __webpack_require__(/*! ./EventEmitter */ "t2YR");
var SelectionModel_1 = __webpack_require__(/*! ./SelectionModel */ "3Y3P");
var Buffer_1 = __webpack_require__(/*! ./Buffer */ "MsZC");
var AltClickHandler_1 = __webpack_require__(/*! ./handlers/AltClickHandler */ "rHEf");
var DRAG_SCROLL_MAX_THRESHOLD = 50;
var DRAG_SCROLL_MAX_SPEED = 15;
var DRAG_SCROLL_INTERVAL = 50;
var ALT_CLICK_MOVE_CURSOR_TIME = 500;
var WORD_SEPARATORS = ' ()[]{}\'"';
var NON_BREAKING_SPACE_CHAR = String.fromCharCode(160);
var ALL_NON_BREAKING_SPACE_REGEX = new RegExp(NON_BREAKING_SPACE_CHAR, 'g');
var SelectionMode;
(function (SelectionMode) {
    SelectionMode[SelectionMode["NORMAL"] = 0] = "NORMAL";
    SelectionMode[SelectionMode["WORD"] = 1] = "WORD";
    SelectionMode[SelectionMode["LINE"] = 2] = "LINE";
})(SelectionMode || (SelectionMode = {}));
var SelectionManager = (function (_super) {
    __extends(SelectionManager, _super);
    function SelectionManager(_terminal, _charMeasure) {
        var _this = _super.call(this) || this;
        _this._terminal = _terminal;
        _this._charMeasure = _charMeasure;
        _this._enabled = true;
        _this._initListeners();
        _this.enable();
        _this._model = new SelectionModel_1.SelectionModel(_terminal);
        _this._activeSelectionMode = SelectionMode.NORMAL;
        return _this;
    }
    Object.defineProperty(SelectionManager.prototype, "_buffer", {
        get: function () {
            return this._terminal.buffers.active;
        },
        enumerable: true,
        configurable: true
    });
    SelectionManager.prototype._initListeners = function () {
        var _this = this;
        this._mouseMoveListener = function (event) { return _this._onMouseMove(event); };
        this._mouseUpListener = function (event) { return _this._onMouseUp(event); };
        this._trimListener = function (amount) { return _this._onTrim(amount); };
        this.initBuffersListeners();
    };
    SelectionManager.prototype.initBuffersListeners = function () {
        var _this = this;
        this._terminal.buffer.lines.on('trim', this._trimListener);
        this._terminal.buffers.on('activate', function (e) { return _this._onBufferActivate(e); });
    };
    SelectionManager.prototype.disable = function () {
        this.clearSelection();
        this._enabled = false;
    };
    SelectionManager.prototype.enable = function () {
        this._enabled = true;
    };
    Object.defineProperty(SelectionManager.prototype, "selectionStart", {
        get: function () { return this._model.finalSelectionStart; },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(SelectionManager.prototype, "selectionEnd", {
        get: function () { return this._model.finalSelectionEnd; },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(SelectionManager.prototype, "hasSelection", {
        get: function () {
            var start = this._model.finalSelectionStart;
            var end = this._model.finalSelectionEnd;
            if (!start || !end) {
                return false;
            }
            return start[0] !== end[0] || start[1] !== end[1];
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(SelectionManager.prototype, "selectionText", {
        get: function () {
            var start = this._model.finalSelectionStart;
            var end = this._model.finalSelectionEnd;
            if (!start || !end) {
                return '';
            }
            var startRowEndCol = start[1] === end[1] ? end[0] : null;
            var result = [];
            result.push(this._buffer.translateBufferLineToString(start[1], true, start[0], startRowEndCol));
            for (var i = start[1] + 1; i <= end[1] - 1; i++) {
                var bufferLine = this._buffer.lines.get(i);
                var lineText = this._buffer.translateBufferLineToString(i, true);
                if (bufferLine.isWrapped) {
                    result[result.length - 1] += lineText;
                }
                else {
                    result.push(lineText);
                }
            }
            if (start[1] !== end[1]) {
                var bufferLine = this._buffer.lines.get(end[1]);
                var lineText = this._buffer.translateBufferLineToString(end[1], true, 0, end[0]);
                if (bufferLine.isWrapped) {
                    result[result.length - 1] += lineText;
                }
                else {
                    result.push(lineText);
                }
            }
            var formattedResult = result.map(function (line) {
                return line.replace(ALL_NON_BREAKING_SPACE_REGEX, ' ');
            }).join(Browser.isMSWindows ? '\r\n' : '\n');
            return formattedResult;
        },
        enumerable: true,
        configurable: true
    });
    SelectionManager.prototype.clearSelection = function () {
        this._model.clearSelection();
        this._removeMouseDownListeners();
        this.refresh();
    };
    SelectionManager.prototype.refresh = function (isNewSelection) {
        var _this = this;
        if (!this._refreshAnimationFrame) {
            this._refreshAnimationFrame = window.requestAnimationFrame(function () { return _this._refresh(); });
        }
        if (Browser.isLinux && isNewSelection) {
            var selectionText = this.selectionText;
            if (selectionText.length) {
                this.emit('newselection', this.selectionText);
            }
        }
    };
    SelectionManager.prototype._refresh = function () {
        this._refreshAnimationFrame = null;
        this.emit('refresh', { start: this._model.finalSelectionStart, end: this._model.finalSelectionEnd });
    };
    SelectionManager.prototype.isClickInSelection = function (event) {
        var coords = this._getMouseBufferCoords(event);
        var start = this._model.finalSelectionStart;
        var end = this._model.finalSelectionEnd;
        if (!start || !end) {
            return false;
        }
        return (coords[1] > start[1] && coords[1] < end[1]) ||
            (start[1] === end[1] && coords[1] === start[1] && coords[0] > start[0] && coords[0] < end[0]) ||
            (start[1] < end[1] && coords[1] === end[1] && coords[0] < end[0]);
    };
    SelectionManager.prototype.selectWordAtCursor = function (event) {
        var coords = this._getMouseBufferCoords(event);
        if (coords) {
            this._selectWordAt(coords, false);
            this._model.selectionEnd = null;
            this.refresh(true);
        }
    };
    SelectionManager.prototype.selectAll = function () {
        this._model.isSelectAllActive = true;
        this.refresh();
        this._terminal.emit('selection');
    };
    SelectionManager.prototype.selectLines = function (start, end) {
        this._model.clearSelection();
        start = Math.max(start, 0);
        end = Math.min(end, this._terminal.buffer.lines.length - 1);
        this._model.selectionStart = [0, start];
        this._model.selectionEnd = [this._terminal.cols, end];
        this.refresh();
        this._terminal.emit('selection');
    };
    SelectionManager.prototype._onTrim = function (amount) {
        var needsRefresh = this._model.onTrim(amount);
        if (needsRefresh) {
            this.refresh();
        }
    };
    SelectionManager.prototype._getMouseBufferCoords = function (event) {
        var coords = this._terminal.mouseHelper.getCoords(event, this._terminal.screenElement, this._charMeasure, this._terminal.options.lineHeight, this._terminal.cols, this._terminal.rows, true);
        if (!coords) {
            return null;
        }
        coords[0]--;
        coords[1]--;
        coords[1] += this._terminal.buffer.ydisp;
        return coords;
    };
    SelectionManager.prototype._getMouseEventScrollAmount = function (event) {
        var offset = MouseHelper_1.MouseHelper.getCoordsRelativeToElement(event, this._terminal.screenElement)[1];
        var terminalHeight = this._terminal.rows * Math.ceil(this._charMeasure.height * this._terminal.options.lineHeight);
        if (offset >= 0 && offset <= terminalHeight) {
            return 0;
        }
        if (offset > terminalHeight) {
            offset -= terminalHeight;
        }
        offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD);
        offset /= DRAG_SCROLL_MAX_THRESHOLD;
        return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1));
    };
    SelectionManager.prototype.shouldForceSelection = function (event) {
        return Browser.isMac ? event.altKey : event.shiftKey;
    };
    SelectionManager.prototype.onMouseDown = function (event) {
        this._mouseDownTimeStamp = event.timeStamp;
        if (event.button === 2 && this.hasSelection) {
            return;
        }
        if (event.button !== 0) {
            return;
        }
        if (!this._enabled) {
            if (!this.shouldForceSelection(event)) {
                return;
            }
            event.stopPropagation();
        }
        event.preventDefault();
        this._dragScrollAmount = 0;
        if (this._enabled && event.shiftKey) {
            this._onIncrementalClick(event);
        }
        else {
            if (event.detail === 1) {
                this._onSingleClick(event);
            }
            else if (event.detail === 2) {
                this._onDoubleClick(event);
            }
            else if (event.detail === 3) {
                this._onTripleClick(event);
            }
        }
        this._addMouseDownListeners();
        this.refresh(true);
    };
    SelectionManager.prototype._addMouseDownListeners = function () {
        var _this = this;
        this._terminal.element.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);
        this._terminal.element.ownerDocument.addEventListener('mouseup', this._mouseUpListener);
        this._dragScrollIntervalTimer = setInterval(function () { return _this._dragScroll(); }, DRAG_SCROLL_INTERVAL);
    };
    SelectionManager.prototype._removeMouseDownListeners = function () {
        this._terminal.element.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);
        this._terminal.element.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);
        clearInterval(this._dragScrollIntervalTimer);
        this._dragScrollIntervalTimer = null;
    };
    SelectionManager.prototype._onIncrementalClick = function (event) {
        if (this._model.selectionStart) {
            this._model.selectionEnd = this._getMouseBufferCoords(event);
        }
    };
    SelectionManager.prototype._onSingleClick = function (event) {
        this._model.selectionStartLength = 0;
        this._model.isSelectAllActive = false;
        this._activeSelectionMode = SelectionMode.NORMAL;
        this._model.selectionStart = this._getMouseBufferCoords(event);
        if (!this._model.selectionStart) {
            return;
        }
        this._model.selectionEnd = null;
        var line = this._buffer.lines.get(this._model.selectionStart[1]);
        if (!line) {
            return;
        }
        if (line.length >= this._model.selectionStart[0]) {
            return;
        }
        var char = line[this._model.selectionStart[0]];
        if (char[Buffer_1.CHAR_DATA_WIDTH_INDEX] === 0) {
            this._model.selectionStart[0]++;
        }
    };
    SelectionManager.prototype._onDoubleClick = function (event) {
        var coords = this._getMouseBufferCoords(event);
        if (coords) {
            this._activeSelectionMode = SelectionMode.WORD;
            this._selectWordAt(coords, true);
        }
    };
    SelectionManager.prototype._onTripleClick = function (event) {
        var coords = this._getMouseBufferCoords(event);
        if (coords) {
            this._activeSelectionMode = SelectionMode.LINE;
            this._selectLineAt(coords[1]);
        }
    };
    SelectionManager.prototype._onMouseMove = function (event) {
        event.stopImmediatePropagation();
        var previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;
        this._model.selectionEnd = this._getMouseBufferCoords(event);
        if (!this._model.selectionEnd) {
            this.refresh(true);
            return;
        }
        if (this._activeSelectionMode === SelectionMode.LINE) {
            if (this._model.selectionEnd[1] < this._model.selectionStart[1]) {
                this._model.selectionEnd[0] = 0;
            }
            else {
                this._model.selectionEnd[0] = this._terminal.cols;
            }
        }
        else if (this._activeSelectionMode === SelectionMode.WORD) {
            this._selectToWordAt(this._model.selectionEnd);
        }
        this._dragScrollAmount = this._getMouseEventScrollAmount(event);
        if (this._dragScrollAmount > 0) {
            this._model.selectionEnd[0] = this._terminal.cols;
        }
        else if (this._dragScrollAmount < 0) {
            this._model.selectionEnd[0] = 0;
        }
        if (this._model.selectionEnd[1] < this._buffer.lines.length) {
            var char = this._buffer.lines.get(this._model.selectionEnd[1])[this._model.selectionEnd[0]];
            if (char && char[Buffer_1.CHAR_DATA_WIDTH_INDEX] === 0) {
                this._model.selectionEnd[0]++;
            }
        }
        if (!previousSelectionEnd ||
            previousSelectionEnd[0] !== this._model.selectionEnd[0] ||
            previousSelectionEnd[1] !== this._model.selectionEnd[1]) {
            this.refresh(true);
        }
    };
    SelectionManager.prototype._dragScroll = function () {
        if (this._dragScrollAmount) {
            this._terminal.scrollLines(this._dragScrollAmount, false);
            if (this._dragScrollAmount > 0) {
                this._model.selectionEnd = [this._terminal.cols - 1, Math.min(this._terminal.buffer.ydisp + this._terminal.rows, this._terminal.buffer.lines.length - 1)];
            }
            else {
                this._model.selectionEnd = [0, this._terminal.buffer.ydisp];
            }
            this.refresh();
        }
    };
    SelectionManager.prototype._onMouseUp = function (event) {
        var timeElapsed = event.timeStamp - this._mouseDownTimeStamp;
        this._removeMouseDownListeners();
        if (this.selectionText.length <= 1 && timeElapsed < ALT_CLICK_MOVE_CURSOR_TIME) {
            (new AltClickHandler_1.AltClickHandler(event, this._terminal)).move();
        }
        else if (this.hasSelection) {
            this._terminal.emit('selection');
        }
    };
    SelectionManager.prototype._onBufferActivate = function (e) {
        this.clearSelection();
        e.inactiveBuffer.lines.off('trim', this._trimListener);
        e.activeBuffer.lines.on('trim', this._trimListener);
    };
    SelectionManager.prototype._convertViewportColToCharacterIndex = function (bufferLine, coords) {
        var charIndex = coords[0];
        for (var i = 0; coords[0] >= i; i++) {
            var char = bufferLine[i];
            if (char[Buffer_1.CHAR_DATA_WIDTH_INDEX] === 0) {
                charIndex--;
            }
            else if (char[Buffer_1.CHAR_DATA_CHAR_INDEX].length > 1 && coords[0] !== i) {
                charIndex += char[Buffer_1.CHAR_DATA_CHAR_INDEX].length - 1;
            }
        }
        return charIndex;
    };
    SelectionManager.prototype.setSelection = function (col, row, length) {
        this._model.clearSelection();
        this._removeMouseDownListeners();
        this._model.selectionStart = [col, row];
        this._model.selectionStartLength = length;
        this.refresh();
    };
    SelectionManager.prototype._getWordAt = function (coords, allowWhitespaceOnlySelection) {
        if (coords[0] >= this._terminal.cols) {
            return null;
        }
        var bufferLine = this._buffer.lines.get(coords[1]);
        if (!bufferLine) {
            return null;
        }
        var line = this._buffer.translateBufferLineToString(coords[1], false);
        var startIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);
        var endIndex = startIndex;
        var charOffset = coords[0] - startIndex;
        var leftWideCharCount = 0;
        var rightWideCharCount = 0;
        var leftLongCharOffset = 0;
        var rightLongCharOffset = 0;
        if (line.charAt(startIndex) === ' ') {
            while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {
                startIndex--;
            }
            while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {
                endIndex++;
            }
        }
        else {
            var startCol = coords[0];
            var endCol = coords[0];
            if (bufferLine[startCol][Buffer_1.CHAR_DATA_WIDTH_INDEX] === 0) {
                leftWideCharCount++;
                startCol--;
            }
            if (bufferLine[endCol][Buffer_1.CHAR_DATA_WIDTH_INDEX] === 2) {
                rightWideCharCount++;
                endCol++;
            }
            if (bufferLine[endCol][Buffer_1.CHAR_DATA_CHAR_INDEX].length > 1) {
                rightLongCharOffset += bufferLine[endCol][Buffer_1.CHAR_DATA_CHAR_INDEX].length - 1;
                endIndex += bufferLine[endCol][Buffer_1.CHAR_DATA_CHAR_INDEX].length - 1;
            }
            while (startCol > 0 && startIndex > 0 && !this._isCharWordSeparator(bufferLine[startCol - 1])) {
                var char = bufferLine[startCol - 1];
                if (char[Buffer_1.CHAR_DATA_WIDTH_INDEX] === 0) {
                    leftWideCharCount++;
                    startCol--;
                }
                else if (char[Buffer_1.CHAR_DATA_CHAR_INDEX].length > 1) {
                    leftLongCharOffset += char[Buffer_1.CHAR_DATA_CHAR_INDEX].length - 1;
                    startIndex -= char[Buffer_1.CHAR_DATA_CHAR_INDEX].length - 1;
                }
                startIndex--;
                startCol--;
            }
            while (endCol < bufferLine.length && endIndex + 1 < line.length && !this._isCharWordSeparator(bufferLine[endCol + 1])) {
                var char = bufferLine[endCol + 1];
                if (char[Buffer_1.CHAR_DATA_WIDTH_INDEX] === 2) {
                    rightWideCharCount++;
                    endCol++;
                }
                else if (char[Buffer_1.CHAR_DATA_CHAR_INDEX].length > 1) {
                    rightLongCharOffset += char[Buffer_1.CHAR_DATA_CHAR_INDEX].length - 1;
                    endIndex += char[Buffer_1.CHAR_DATA_CHAR_INDEX].length - 1;
                }
                endIndex++;
                endCol++;
            }
        }
        endIndex++;
        var start = startIndex
            + charOffset
            - leftWideCharCount
            + leftLongCharOffset;
        var length = Math.min(this._terminal.cols, endIndex
            - startIndex
            + leftWideCharCount
            + rightWideCharCount
            - leftLongCharOffset
            - rightLongCharOffset);
        if (!allowWhitespaceOnlySelection && line.slice(startIndex, endIndex).trim() === '') {
            return null;
        }
        return { start: start, length: length };
    };
    SelectionManager.prototype._selectWordAt = function (coords, allowWhitespaceOnlySelection) {
        var wordPosition = this._getWordAt(coords, allowWhitespaceOnlySelection);
        if (wordPosition) {
            this._model.selectionStart = [wordPosition.start, coords[1]];
            this._model.selectionStartLength = wordPosition.length;
        }
    };
    SelectionManager.prototype._selectToWordAt = function (coords) {
        var wordPosition = this._getWordAt(coords, true);
        if (wordPosition) {
            this._model.selectionEnd = [this._model.areSelectionValuesReversed() ? wordPosition.start : (wordPosition.start + wordPosition.length), coords[1]];
        }
    };
    SelectionManager.prototype._isCharWordSeparator = function (charData) {
        if (charData[Buffer_1.CHAR_DATA_WIDTH_INDEX] === 0) {
            return false;
        }
        return WORD_SEPARATORS.indexOf(charData[Buffer_1.CHAR_DATA_CHAR_INDEX]) >= 0;
    };
    SelectionManager.prototype._selectLineAt = function (line) {
        this._model.selectionStart = [0, line];
        this._model.selectionStartLength = this._terminal.cols;
    };
    return SelectionManager;
}(EventEmitter_1.EventEmitter));
exports.SelectionManager = SelectionManager;

//# sourceMappingURL=SelectionManager.js.map


/***/ }),

/***/ "iOcY":
/*!***********************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/Info.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Info = function (_Component) {
  _inherits(Info, _Component);

  function Info() {
    _classCallCheck(this, Info);

    return _possibleConstructorReturn(this, (Info.__proto__ || Object.getPrototypeOf(Info)).apply(this, arguments));
  }

  _createClass(Info, [{
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        _Field2.default,
        this.props,
        _react2.default.createElement(
          'div',
          { className: 'js-test-info ' + (this.props.className ? this.props.className : '') },
          this.props.children
        )
      );
    }
  }]);

  return Info;
}(_react.Component);

exports.default = Info;


Info.plotly_editor_traits = {
  no_visibility_forcing: true
};

Info.propTypes = _extends({}, _Field2.default.propTypes);
//# sourceMappingURL=Info.js.map

/***/ }),

/***/ "iUdu":
/*!**************************************************!*\
  !*** ./node_modules/browserify-aes/encrypter.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var MODES = __webpack_require__(/*! ./modes */ "usKN")
var AuthCipher = __webpack_require__(/*! ./authCipher */ "gvAe")
var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer
var StreamCipher = __webpack_require__(/*! ./streamCipher */ "CfXC")
var Transform = __webpack_require__(/*! cipher-base */ "ZDAU")
var aes = __webpack_require__(/*! ./aes */ "OfWw")
var ebtk = __webpack_require__(/*! evp_bytestokey */ "roQf")
var inherits = __webpack_require__(/*! inherits */ "P7XM")

function Cipher (mode, key, iv) {
  Transform.call(this)

  this._cache = new Splitter()
  this._cipher = new aes.AES(key)
  this._prev = Buffer.from(iv)
  this._mode = mode
  this._autopadding = true
}

inherits(Cipher, Transform)

Cipher.prototype._update = function (data) {
  this._cache.add(data)
  var chunk
  var thing
  var out = []

  while ((chunk = this._cache.get())) {
    thing = this._mode.encrypt(this, chunk)
    out.push(thing)
  }

  return Buffer.concat(out)
}

var PADDING = Buffer.alloc(16, 0x10)

Cipher.prototype._final = function () {
  var chunk = this._cache.flush()
  if (this._autopadding) {
    chunk = this._mode.encrypt(this, chunk)
    this._cipher.scrub()
    return chunk
  }

  if (!chunk.equals(PADDING)) {
    this._cipher.scrub()
    throw new Error('data not multiple of block length')
  }
}

Cipher.prototype.setAutoPadding = function (setTo) {
  this._autopadding = !!setTo
  return this
}

function Splitter () {
  this.cache = Buffer.allocUnsafe(0)
}

Splitter.prototype.add = function (data) {
  this.cache = Buffer.concat([this.cache, data])
}

Splitter.prototype.get = function () {
  if (this.cache.length > 15) {
    var out = this.cache.slice(0, 16)
    this.cache = this.cache.slice(16)
    return out
  }
  return null
}

Splitter.prototype.flush = function () {
  var len = 16 - this.cache.length
  var padBuff = Buffer.allocUnsafe(len)

  var i = -1
  while (++i < len) {
    padBuff.writeUInt8(len, i)
  }

  return Buffer.concat([this.cache, padBuff])
}

function createCipheriv (suite, password, iv) {
  var config = MODES[suite.toLowerCase()]
  if (!config) throw new TypeError('invalid suite type')

  if (typeof password === 'string') password = Buffer.from(password)
  if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)

  if (typeof iv === 'string') iv = Buffer.from(iv)
  if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)

  if (config.type === 'stream') {
    return new StreamCipher(config.module, password, iv)
  } else if (config.type === 'auth') {
    return new AuthCipher(config.module, password, iv)
  }

  return new Cipher(config.module, password, iv)
}

function createCipher (suite, password) {
  var config = MODES[suite.toLowerCase()]
  if (!config) throw new TypeError('invalid suite type')

  var keys = ebtk(password, false, config.key, config.iv)
  return createCipheriv(suite, keys.key, keys.iv)
}

exports.createCipheriv = createCipheriv
exports.createCipher = createCipher


/***/ }),

/***/ "iWb3":
/*!*****************************************************!*\
  !*** ./node_modules/mdi-react/ArrowCollapseIcon.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var ArrowCollapseIcon = function ArrowCollapseIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M19.5,3.09L15,7.59V4H13V11H20V9H16.41L20.91,4.5L19.5,3.09M4,13V15H7.59L3.09,19.5L4.5,20.91L9,16.41V20H11V13H4Z' })
  );
};

module.exports = ArrowCollapseIcon;


/***/ }),

/***/ "iYuL":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/es.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'),
    monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_');

var monthsParse = [/^ene/i, /^feb/i, /^mar/i, /^abr/i, /^may/i, /^jun/i, /^jul/i, /^ago/i, /^sep/i, /^oct/i, /^nov/i, /^dic/i];
var monthsRegex = /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i;

var es = moment.defineLocale('es', {
    months : 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'),
    monthsShort : function (m, format) {
        if (!m) {
            return monthsShortDot;
        } else if (/-MMM-/.test(format)) {
            return monthsShort[m.month()];
        } else {
            return monthsShortDot[m.month()];
        }
    },
    monthsRegex : monthsRegex,
    monthsShortRegex : monthsRegex,
    monthsStrictRegex : /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i,
    monthsShortStrictRegex : /^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i,
    monthsParse : monthsParse,
    longMonthsParse : monthsParse,
    shortMonthsParse : monthsParse,
    weekdays : 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'),
    weekdaysShort : 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'),
    weekdaysMin : 'do_lu_ma_mi_ju_vi_sá'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'H:mm',
        LTS : 'H:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D [de] MMMM [de] YYYY',
        LLL : 'D [de] MMMM [de] YYYY H:mm',
        LLLL : 'dddd, D [de] MMMM [de] YYYY H:mm'
    },
    calendar : {
        sameDay : function () {
            return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
        },
        nextDay : function () {
            return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
        },
        nextWeek : function () {
            return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
        },
        lastDay : function () {
            return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
        },
        lastWeek : function () {
            return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
        },
        sameElse : 'L'
    },
    relativeTime : {
        future : 'en %s',
        past : 'hace %s',
        s : 'unos segundos',
        ss : '%d segundos',
        m : 'un minuto',
        mm : '%d minutos',
        h : 'una hora',
        hh : '%d horas',
        d : 'un día',
        dd : '%d días',
        M : 'un mes',
        MM : '%d meses',
        y : 'un año',
        yy : '%d años'
    },
    dayOfMonthOrdinalParse : /\d{1,2}º/,
    ordinal : '%dº',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return es;

})));


/***/ }),

/***/ "iZoB":
/*!*******************************************************!*\
  !*** ./node_modules/ajv/lib/compile/error_classes.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var resolve = __webpack_require__(/*! ./resolve */ "qXHa");

module.exports = {
  Validation: errorSubclass(ValidationError),
  MissingRef: errorSubclass(MissingRefError)
};


function ValidationError(errors) {
  this.message = 'validation failed';
  this.errors = errors;
  this.ajv = this.validation = true;
}


MissingRefError.message = function (baseId, ref) {
  return 'can\'t resolve reference ' + ref + ' from id ' + baseId;
};


function MissingRefError(baseId, ref, message) {
  this.message = message || MissingRefError.message(baseId, ref);
  this.missingRef = resolve.url(baseId, ref);
  this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef));
}


function errorSubclass(Subclass) {
  Subclass.prototype = Object.create(Error.prototype);
  Subclass.prototype.constructor = Subclass;
  return Subclass;
}


/***/ }),

/***/ "ia9w":
/*!*************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PanIcon.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PanIcon = function PanIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 16 16' }, props),
        _react2.default.createElement('path', { d: 'M16 8l-3-3v2H9V3h2L8 0 5 3h2v4H3V4.999L0 8l2.977 3V9H7v4H5l3 3 3-3H9V9h4v2.001L16 8z' })
    );
};

exports.default = PanIcon;

/***/ }),

/***/ "iaXi":
/*!*********************************************************************!*\
  !*** ./node_modules/@jupyterlab/extensionmanager/lib/companions.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const React = __importStar(__webpack_require__(/*! react */ "q1tI"));
/**
 * Prompt the user what do about companion packages, if present.
 *
 * @param builder the build manager
 */
function presentCompanions(kernelCompanions, serverCompanion) {
    let entries = [];
    if (serverCompanion) {
        entries.push(React.createElement("p", null,
            "This package has indicated that it needs a corresponding server extension:",
            React.createElement("code", null,
                " ",
                serverCompanion.base.name)));
    }
    if (kernelCompanions.length > 0) {
        entries.push(React.createElement("p", null, "This package has indicated that it needs a corresponding package for the kernel."));
        for (let entry of kernelCompanions) {
            entries.push(React.createElement("p", null,
                "The package",
                React.createElement("code", null, entry.kernelInfo.base.name),
                ", is required by the following kernels:"));
            let kernelEntries = [];
            for (let kernel of entry.kernels) {
                kernelEntries.push(React.createElement("li", null,
                    React.createElement("code", null, kernel.display_name)));
            }
            entries.push(React.createElement("ul", null, kernelEntries));
        }
    }
    let body = (React.createElement("div", null,
        entries,
        React.createElement("p", null, "You should make sure that the indicated packages are installed before trying to use the extension. Do you want to continue with the extension installation?")));
    return apputils_1.showDialog({
        title: 'Kernel companions',
        body,
        buttons: [
            apputils_1.Dialog.cancelButton(),
            apputils_1.Dialog.okButton({
                label: 'OK',
                caption: 'Install the Jupyterlab extension.'
            })
        ]
    }).then(result => {
        return result.button.accept;
    });
}
exports.presentCompanions = presentCompanions;


/***/ }),

/***/ "iadR":
/*!*******************************************************!*\
  !*** ./node_modules/@phosphor/coreutils/lib/index.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
__export(__webpack_require__(/*! ./json */ "hG2j"));
__export(__webpack_require__(/*! ./mime */ "h687"));
__export(__webpack_require__(/*! ./promise */ "eay7"));
__export(__webpack_require__(/*! ./random */ "cN6I"));
__export(__webpack_require__(/*! ./token */ "IiDj"));
__export(__webpack_require__(/*! ./uuid */ "RBQu"));


/***/ }),

/***/ "ialn":
/*!****************************************************!*\
  !*** ./node_modules/json-schema-traverse/index.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var traverse = module.exports = function (schema, opts, cb) {
  if (typeof opts == 'function') {
    cb = opts;
    opts = {};
  }
  _traverse(opts, cb, schema, '', schema);
};


traverse.keywords = {
  additionalItems: true,
  items: true,
  contains: true,
  additionalProperties: true,
  propertyNames: true,
  not: true
};

traverse.arrayKeywords = {
  items: true,
  allOf: true,
  anyOf: true,
  oneOf: true
};

traverse.propsKeywords = {
  definitions: true,
  properties: true,
  patternProperties: true,
  dependencies: true
};

traverse.skipKeywords = {
  enum: true,
  const: true,
  required: true,
  maximum: true,
  minimum: true,
  exclusiveMaximum: true,
  exclusiveMinimum: true,
  multipleOf: true,
  maxLength: true,
  minLength: true,
  pattern: true,
  format: true,
  maxItems: true,
  minItems: true,
  uniqueItems: true,
  maxProperties: true,
  minProperties: true
};


function _traverse(opts, cb, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
  if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
    cb(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
    for (var key in schema) {
      var sch = schema[key];
      if (Array.isArray(sch)) {
        if (key in traverse.arrayKeywords) {
          for (var i=0; i<sch.length; i++)
            _traverse(opts, cb, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);
        }
      } else if (key in traverse.propsKeywords) {
        if (sch && typeof sch == 'object') {
          for (var prop in sch)
            _traverse(opts, cb, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
        }
      } else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {
        _traverse(opts, cb, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);
      }
    }
  }
}


function escapeJsonPtr(str) {
  return str.replace(/~/g, '~0').replace(/\//g, '~1');
}


/***/ }),

/***/ "iatg":
/*!*************************************************!*\
  !*** ./node_modules/fbjs/lib/getElementRect.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks
 */

var containsNode = __webpack_require__(/*! ./containsNode */ "TWoB");

/**
 * Gets an element's bounding rect in pixels relative to the viewport.
 *
 * @param {DOMElement} elem
 * @return {object}
 */
function getElementRect(elem) {
  var docElem = elem.ownerDocument.documentElement;

  // FF 2, Safari 3 and Opera 9.5- do not support getBoundingClientRect().
  // IE9- will throw if the element is not in the document.
  if (!('getBoundingClientRect' in elem) || !containsNode(docElem, elem)) {
    return {
      left: 0,
      right: 0,
      top: 0,
      bottom: 0
    };
  }

  // Subtracts clientTop/Left because IE8- added a 2px border to the
  // <html> element (see http://fburl.com/1493213). IE 7 in
  // Quicksmode does not report clientLeft/clientTop so there
  // will be an unaccounted offset of 2px when in quirksmode
  var rect = elem.getBoundingClientRect();

  return {
    left: Math.round(rect.left) - docElem.clientLeft,
    right: Math.round(rect.right) - docElem.clientLeft,
    top: Math.round(rect.top) - docElem.clientTop,
    bottom: Math.round(rect.bottom) - docElem.clientTop
  };
}

module.exports = getElementRect;

/***/ }),

/***/ "idGr":
/*!******************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/kernel/validate.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * Required fields for `IKernelHeader`.
 */
const HEADER_FIELDS = ['username', 'version', 'session', 'msg_id', 'msg_type'];
/**
 * Required fields and types for contents of various types of `kernel.IMessage`
 * messages on the iopub channel.
 */
const IOPUB_CONTENT_FIELDS = {
    stream: { name: 'string', text: 'string' },
    display_data: { data: 'object', metadata: 'object' },
    execute_input: { code: 'string', execution_count: 'number' },
    execute_result: {
        execution_count: 'number',
        data: 'object',
        metadata: 'object'
    },
    error: { ename: 'string', evalue: 'string', traceback: 'object' },
    status: { execution_state: 'string' },
    clear_output: { wait: 'boolean' },
    comm_open: { comm_id: 'string', target_name: 'string', data: 'object' },
    comm_msg: { comm_id: 'string', data: 'object' },
    comm_close: { comm_id: 'string' },
    shutdown_reply: { restart: 'boolean' } // Emitted by the IPython kernel.
};
/**
 * Validate a property as being on an object, and optionally
 * of a given type.
 */
function validateProperty(object, name, typeName) {
    if (!object.hasOwnProperty(name)) {
        throw Error(`Missing property '${name}'`);
    }
    if (typeName !== void 0) {
        let valid = true;
        let value = object[name];
        switch (typeName) {
            case 'array':
                valid = Array.isArray(value);
                break;
            case 'object':
                valid = typeof value !== 'undefined';
                break;
            default:
                valid = typeof value === typeName;
        }
        if (!valid) {
            throw new Error(`Property '${name}' is not of type '${typeName}`);
        }
    }
}
/**
 * Validate the header of a kernel message.
 */
function validateHeader(header) {
    for (let i = 0; i < HEADER_FIELDS.length; i++) {
        validateProperty(header, HEADER_FIELDS[i], 'string');
    }
}
/**
 * Validate a kernel message object.
 */
function validateMessage(msg) {
    validateProperty(msg, 'metadata', 'object');
    validateProperty(msg, 'content', 'object');
    validateProperty(msg, 'channel', 'string');
    validateHeader(msg.header);
    if (msg.channel === 'iopub') {
        validateIOPubContent(msg);
    }
}
exports.validateMessage = validateMessage;
/**
 * Validate content an kernel message on the iopub channel.
 */
function validateIOPubContent(msg) {
    if (msg.channel === 'iopub') {
        let fields = IOPUB_CONTENT_FIELDS[msg.header.msg_type];
        // Check for unknown message type.
        if (fields === void 0) {
            return;
        }
        let names = Object.keys(fields);
        let content = msg.content;
        for (let i = 0; i < names.length; i++) {
            validateProperty(content, names[i], fields[names[i]]);
        }
    }
}
/**
 * Validate a `Kernel.IModel` object.
 */
function validateModel(model) {
    validateProperty(model, 'name', 'string');
    validateProperty(model, 'id', 'string');
}
exports.validateModel = validateModel;
/**
 * Validate a server kernelspec model to a client side model.
 */
function validateSpecModel(data) {
    let spec = data.spec;
    if (!spec) {
        throw new Error('Invalid kernel spec');
    }
    validateProperty(data, 'name', 'string');
    validateProperty(data, 'resources', 'object');
    validateProperty(spec, 'language', 'string');
    validateProperty(spec, 'display_name', 'string');
    validateProperty(spec, 'argv', 'array');
    return {
        name: data.name,
        resources: data.resources,
        language: spec.language,
        display_name: spec.display_name,
        argv: spec.argv
    };
}
exports.validateSpecModel = validateSpecModel;
/**
 * Validate a `Kernel.ISpecModels` object.
 */
function validateSpecModels(data) {
    if (!data.hasOwnProperty('kernelspecs')) {
        throw new Error('No kernelspecs found');
    }
    let keys = Object.keys(data.kernelspecs);
    let kernelspecs = Object.create(null);
    let defaultSpec = data.default;
    for (let i = 0; i < keys.length; i++) {
        let ks = data.kernelspecs[keys[i]];
        try {
            kernelspecs[keys[i]] = validateSpecModel(ks);
        }
        catch (err) {
            // Remove the errant kernel spec.
            console.warn(`Removing errant kernel spec: ${keys[i]}`);
        }
    }
    keys = Object.keys(kernelspecs);
    if (!keys.length) {
        throw new Error('No valid kernelspecs found');
    }
    if (!defaultSpec ||
        typeof defaultSpec !== 'string' ||
        !(defaultSpec in kernelspecs)) {
        defaultSpec = keys[0];
        console.warn(`Default kernel not found, using '${keys[0]}'`);
    }
    return {
        default: defaultSpec,
        kernelspecs
    };
}
exports.validateSpecModels = validateSpecModels;


/***/ }),

/***/ "ihYd":
/*!******************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/connectAnnotationToLayout.js ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

exports.default = connectAnnotationToLayout;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _lib = __webpack_require__(/*! ../lib */ "RXjw");

var _constants = __webpack_require__(/*! ./constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function connectAnnotationToLayout(WrappedComponent) {
  var AnnotationConnectedComponent = function (_Component) {
    _inherits(AnnotationConnectedComponent, _Component);

    function AnnotationConnectedComponent(props, context) {
      _classCallCheck(this, AnnotationConnectedComponent);

      var _this = _possibleConstructorReturn(this, (AnnotationConnectedComponent.__proto__ || Object.getPrototypeOf(AnnotationConnectedComponent)).call(this, props, context));

      _this.deleteAnnotation = _this.deleteAnnotation.bind(_this);
      _this.updateAnnotation = _this.updateAnnotation.bind(_this);
      _this.setLocals(props, context);
      return _this;
    }

    _createClass(AnnotationConnectedComponent, [{
      key: 'componentWillReceiveProps',
      value: function componentWillReceiveProps(nextProps, nextContext) {
        this.setLocals(nextProps, nextContext);
      }
    }, {
      key: 'setLocals',
      value: function setLocals(props, context) {
        var annotationIndex = props.annotationIndex;
        var container = context.container,
            fullContainer = context.fullContainer;


        var annotations = container.annotations || [];
        var fullAnnotations = fullContainer.annotations || [];
        this.container = annotations[annotationIndex];
        this.fullContainer = fullAnnotations[annotationIndex];
      }
    }, {
      key: 'getChildContext',
      value: function getChildContext() {
        var _this2 = this;

        return {
          getValObject: function getValObject(attr) {
            return !_this2.context.getValObject ? null : _this2.context.getValObject('annotations[].' + attr);
          },
          updateContainer: this.updateAnnotation,
          deleteContainer: this.deleteAnnotation,
          container: this.container,
          fullContainer: this.fullContainer
        };
      }
    }, {
      key: 'updateAnnotation',
      value: function updateAnnotation(update) {
        var newUpdate = {};
        var annotationIndex = this.props.annotationIndex;

        for (var key in update) {
          var newkey = 'annotations[' + annotationIndex + '].' + key;
          newUpdate[newkey] = update[key];
        }
        this.context.updateContainer(newUpdate);
      }
    }, {
      key: 'deleteAnnotation',
      value: function deleteAnnotation() {
        if (this.context.onUpdate) {
          this.context.onUpdate({
            type: _constants.EDITOR_ACTIONS.DELETE_ANNOTATION,
            payload: { annotationIndex: this.props.annotationIndex }
          });
        }
      }
    }, {
      key: 'render',
      value: function render() {
        return _react2.default.createElement(WrappedComponent, this.props);
      }
    }]);

    return AnnotationConnectedComponent;
  }(_react.Component);

  AnnotationConnectedComponent.displayName = 'AnnotationConnected' + (0, _lib.getDisplayName)(WrappedComponent);

  AnnotationConnectedComponent.propTypes = {
    annotationIndex: _propTypes2.default.number.isRequired
  };

  AnnotationConnectedComponent.contextTypes = {
    container: _propTypes2.default.object,
    fullContainer: _propTypes2.default.object,
    data: _propTypes2.default.array,
    onUpdate: _propTypes2.default.func,
    updateContainer: _propTypes2.default.func,
    getValObject: _propTypes2.default.func
  };

  AnnotationConnectedComponent.childContextTypes = {
    updateContainer: _propTypes2.default.func,
    deleteContainer: _propTypes2.default.func,
    container: _propTypes2.default.object,
    fullContainer: _propTypes2.default.object,
    getValObject: _propTypes2.default.func
  };

  var plotly_editor_traits = WrappedComponent.plotly_editor_traits;

  AnnotationConnectedComponent.plotly_editor_traits = plotly_editor_traits;

  return AnnotationConnectedComponent;
}
//# sourceMappingURL=connectAnnotationToLayout.js.map

/***/ }),

/***/ "iisS":
/*!**************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/IconBase.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

var PlotlyIconBase = function PlotlyIconBase(_ref) {
    var children = _ref.children,
        width = _ref.width,
        height = _ref.height,
        _ref$style = _ref.style,
        style = _ref$style === undefined ? {} : _ref$style,
        props = _objectWithoutProperties(_ref, ['children', 'width', 'height', 'style']);

    return _react2.default.createElement('svg', _extends({
        children: children,
        fill: 'currentColor',
        preserveAspectRatio: 'xMidYMid meet',
        height: height,
        width: width,
        style: style
    }, props));
};

PlotlyIconBase.propTypes = {
    children: _propTypes2.default.node.isRequired,
    width: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.string]),
    height: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.string]),
    style: _propTypes2.default.object
};

exports.default = PlotlyIconBase;

/***/ }),

/***/ "il2e":
/*!**************************************************!*\
  !*** ./node_modules/mdi-react/HelpCircleIcon.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var HelpCircleIcon = function HelpCircleIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M15.07,11.25L14.17,12.17C13.45,12.89 13,13.5 13,15H11V14.5C11,13.39 11.45,12.39 12.17,11.67L13.41,10.41C13.78,10.05 14,9.55 14,9C14,7.89 13.1,7 12,7C10.9,7 10,7.9 10,9H8C8,6.79 9.79,5 12,5C14.21,5 16,6.79 16,9C16,9.88 15.64,10.67 15.07,11.25M13,19H11V17H13M12,2C6.48,2 2,6.48 2,12C2,17.52 6.48,22 12,22C17.52,22 22,17.52 22,12C22,6.47 17.5,2 12,2Z' })
  );
};

module.exports = HelpCircleIcon;


/***/ }),

/***/ "ilWa":
/*!****************************************************************!*\
  !*** ./node_modules/draft-js/lib/applyEntityToContentState.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule applyEntityToContentState
 * @format
 * 
 */



var Immutable = __webpack_require__(/*! immutable */ "JPcv");

var applyEntityToContentBlock = __webpack_require__(/*! ./applyEntityToContentBlock */ "vYwu");

function applyEntityToContentState(contentState, selectionState, entityKey) {
  var blockMap = contentState.getBlockMap();
  var startKey = selectionState.getStartKey();
  var startOffset = selectionState.getStartOffset();
  var endKey = selectionState.getEndKey();
  var endOffset = selectionState.getEndOffset();

  var newBlocks = blockMap.skipUntil(function (_, k) {
    return k === startKey;
  }).takeUntil(function (_, k) {
    return k === endKey;
  }).toOrderedMap().merge(Immutable.OrderedMap([[endKey, blockMap.get(endKey)]])).map(function (block, blockKey) {
    var sliceStart = blockKey === startKey ? startOffset : 0;
    var sliceEnd = blockKey === endKey ? endOffset : block.getLength();
    return applyEntityToContentBlock(block, sliceStart, sliceEnd, entityKey);
  });

  return contentState.merge({
    blockMap: blockMap.merge(newBlocks),
    selectionBefore: selectionState,
    selectionAfter: selectionState
  });
}

module.exports = applyEntityToContentState;

/***/ }),

/***/ "ilay":
/*!*************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeSankeyIcon.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeSankeyIcon = function TraceTypeSankeyIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement('path', { d: 'M9 20c.68-.038 1.36-.062 2.04-.065l.51-.002c.118 0 .093-.003.106-.004h.023a.225.225 0 0 1 .096 0 3.276 3.276 0 0 0 .436-.003c.245-.1-.029.275 1.324-1.046l2.965-2.813 3.328-3.172a18.619 18.619 0 0 1 9.888-4.556q.907-.126 1.821-.16l1.384-.016c1.36.002 2.72-.006 4.08-.083v16c-1.36-.076-2.72-.085-4.08-.083l-.51-.002c-.115.003-.093.011-.146.011-.07.01-.14.022-.208.037a1.784 1.784 0 0 0-.385.161 1.838 1.838 0 0 0-.555.568c-.02.023-.029.058-.047.082l-.266.322-.647.791-1.296 1.581-2.587 3.164a21.69 21.69 0 0 1-1.732 1.97 18.844 18.844 0 0 1-2.987 2.418 18.143 18.143 0 0 1-7.18 2.76 15.55 15.55 0 0 1-1.935.19l-.89.017-.51-.002c-.68-.003-1.36-.027-2.04-.065z', fill: '#25fdfc' }),
        _react2.default.createElement('path', { fill: 'none', d: 'M0 0h46v46H0z' }),
        _react2.default.createElement('path', { fill: 'none', stroke: '#1d9bfb', d: 'M9 20v18M9 8v10M37 8v30', strokeMiterlimit: '10', strokeWidth: '2' }),
        _react2.default.createElement('path', { d: 'M9 13.08h1.35a10 10 0 0 1 8.566 4.84l6.169 10.24A10 10 0 0 0 33.65 33H37', fill: 'none', stroke: '#1d9bfb', opacity: '.5', strokeMiterlimit: '10', strokeWidth: '10' }),
        _react2.default.createElement('path', { d: 'M10 9.04h.002a14.77 14.77 0 0 1 12.37 6.698l7.444 11.408a4 4 0 0 0 3.35 1.814H36', fill: 'none', stroke: '#1d9bfb', strokeMiterlimit: '10', strokeWidth: '2' })
    );
};

exports.default = TraceTypeSankeyIcon;

/***/ }),

/***/ "im7S":
/*!*************************************************************************!*\
  !*** ./node_modules/font-awesome/fonts/fontawesome-webfont.ttf?v=4.7.0 ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__.p + "b06871f281fee6b241d60582ae9369b9.ttf";

/***/ }),

/***/ "imJ1":
/*!**********************************************************!*\
  !*** ./node_modules/@jupyterlab/csvviewer/lib/widget.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
            t[p[i]] = s[p[i]];
    return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const docregistry_1 = __webpack_require__(/*! @jupyterlab/docregistry */ "jTF0");
const coreutils_2 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const datagrid_1 = __webpack_require__(/*! @phosphor/datagrid */ "Dblc");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const toolbar_1 = __webpack_require__(/*! ./toolbar */ "MSdE");
const model_1 = __webpack_require__(/*! ./model */ "EC7n");
/**
 * The class name added to a CSV viewer.
 */
const CSV_CLASS = 'jp-CSVViewer';
/**
 * The class name added to a CSV viewer datagrid.
 */
const CSV_GRID_CLASS = 'jp-CSVViewer-grid';
/**
 * The timeout to wait for change activity to have ceased before rendering.
 */
const RENDER_TIMEOUT = 1000;
/**
 * A viewer for CSV tables.
 */
class CSVViewer extends widgets_1.Widget {
    /**
     * Construct a new CSV viewer.
     */
    constructor(options) {
        super();
        this._monitor = null;
        this._delimiter = ',';
        this._revealed = new coreutils_2.PromiseDelegate();
        let context = (this._context = options.context);
        let layout = (this.layout = new widgets_1.PanelLayout());
        this.addClass(CSV_CLASS);
        this._grid = new datagrid_1.DataGrid({
            baseRowSize: 24,
            baseColumnSize: 144,
            baseColumnHeaderSize: 36,
            baseRowHeaderSize: 64
        });
        this._grid.addClass(CSV_GRID_CLASS);
        this._grid.headerVisibility = 'all';
        layout.addWidget(this._grid);
        this._context.ready.then(() => {
            this._updateGrid();
            this._revealed.resolve(undefined);
            // Throttle the rendering rate of the widget.
            this._monitor = new coreutils_1.ActivityMonitor({
                signal: context.model.contentChanged,
                timeout: RENDER_TIMEOUT
            });
            this._monitor.activityStopped.connect(this._updateGrid, this);
        });
    }
    /**
     * The CSV widget's context.
     */
    get context() {
        return this._context;
    }
    /**
     * A promise that resolves when the csv viewer is ready to be revealed.
     */
    get revealed() {
        return this._revealed.promise;
    }
    /**
     * The delimiter for the file.
     */
    get delimiter() {
        return this._delimiter;
    }
    set delimiter(value) {
        if (value === this._delimiter) {
            return;
        }
        this._delimiter = value;
        this._updateGrid();
    }
    /**
     * The style used by the data grid.
     */
    get style() {
        return this._grid.style;
    }
    set style(value) {
        this._grid.style = value;
    }
    /**
     * The text renderer used by the data grid.
     */
    get renderer() {
        return this._grid.defaultRenderer;
    }
    set renderer(value) {
        this._grid.defaultRenderer = value;
    }
    /**
     * Dispose of the resources used by the widget.
     */
    dispose() {
        if (this._monitor) {
            this._monitor.dispose();
        }
        super.dispose();
    }
    /**
     * Handle `'activate-request'` messages.
     */
    onActivateRequest(msg) {
        this.node.tabIndex = -1;
        this.node.focus();
    }
    /**
     * Create the model for the grid.
     */
    _updateGrid() {
        let data = this._context.model.toString();
        let delimiter = this._delimiter;
        let oldModel = this._grid.model;
        this._grid.model = new model_1.DSVModel({ data, delimiter });
        if (oldModel) {
            oldModel.dispose();
        }
    }
}
exports.CSVViewer = CSVViewer;
/**
 * A document widget for CSV content widgets.
 */
class CSVDocumentWidget extends docregistry_1.DocumentWidget {
    constructor(options) {
        let { content, context, delimiter, reveal } = options, other = __rest(options, ["content", "context", "delimiter", "reveal"]);
        content = content || Private.createContent(context);
        reveal = Promise.all([reveal, content.revealed]);
        super(Object.assign({ content, context, reveal }, other));
        if (delimiter) {
            content.delimiter = delimiter;
        }
        const csvDelimiter = new toolbar_1.CSVDelimiter({ selected: content.delimiter });
        this.toolbar.addItem('delimiter', csvDelimiter);
        csvDelimiter.delimiterChanged.connect((sender, delimiter) => {
            content.delimiter = delimiter;
        });
    }
}
exports.CSVDocumentWidget = CSVDocumentWidget;
var Private;
(function (Private) {
    function createContent(context) {
        return new CSVViewer({ context });
    }
    Private.createContent = createContent;
})(Private || (Private = {}));
/**
 * A widget factory for CSV widgets.
 */
class CSVViewerFactory extends docregistry_1.ABCWidgetFactory {
    /**
     * Create a new widget given a context.
     */
    createNewWidget(context) {
        return new CSVDocumentWidget({ context });
    }
}
exports.CSVViewerFactory = CSVViewerFactory;
/**
 * A widget factory for TSV widgets.
 */
class TSVViewerFactory extends docregistry_1.ABCWidgetFactory {
    /**
     * Create a new widget given a context.
     */
    createNewWidget(context) {
        const delimiter = '\t';
        return new CSVDocumentWidget({ context, delimiter });
    }
}
exports.TSVViewerFactory = TSVViewerFactory;


/***/ }),

/***/ "iq4v":
/*!********************************************************!*\
  !*** ./node_modules/core-js/library/fn/object/keys.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(/*! ../../modules/es6.object.keys */ "Mqbl");
module.exports = __webpack_require__(/*! ../../modules/_core */ "WEpk").Object.keys;


/***/ }),

/***/ "itsj":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_safeGet.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * Gets the value at `key`, unless `key` is "__proto__".
 *
 * @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 == '__proto__') {
    return;
  }

  return object[key];
}

module.exports = safeGet;


/***/ }),

/***/ "iw4z":
/*!****************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/ErrorBars.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _index = __webpack_require__(/*! ../index */ "yF51");

var _RadioBlocks = __webpack_require__(/*! ../widgets/RadioBlocks */ "N8y9");

var _RadioBlocks2 = _interopRequireDefault(_RadioBlocks);

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var ErrorBars = function (_Component) {
  _inherits(ErrorBars, _Component);

  function ErrorBars(props, context) {
    _classCallCheck(this, ErrorBars);

    var _this = _possibleConstructorReturn(this, (ErrorBars.__proto__ || Object.getPrototypeOf(ErrorBars)).call(this, props, context));

    _this.updatePlot = _this.updatePlot.bind(_this);
    return _this;
  }

  _createClass(ErrorBars, [{
    key: 'updatePlot',
    value: function updatePlot(value) {
      if (value === 'symmetric') {
        this.props.updatePlot(_extends({}, this.props.fullValue, {
          visible: true,
          symmetric: true
        }));
      }

      if (value === 'asymmetric') {
        this.props.updatePlot(_extends({}, this.props.fullValue, {
          visible: true,
          symmetric: false
        }));
      }

      if (value === 'hidden') {
        this.props.updatePlot(_extends({}, this.props.fullValue, {
          visible: false
        }));
      }
    }
  }, {
    key: 'getMode',
    value: function getMode() {
      var mode = void 0;

      if (!this.props.fullValue.visible) {
        mode = 'hidden';
      }

      if (this.props.fullValue.visible && (this.props.fullValue.symmetric || typeof this.props.fullValue.symmetric === 'undefined')) {
        // when this.props.fullValue.type === 'sqrt',
        // then this.props.fullValue.symmetric is undefined, but 'sqrt' is only
        // applicable when we want symmetric error bars
        // https://github.com/plotly/plotly.js/issues/2359
        mode = 'symmetric';
      }

      if (this.props.fullValue.visible && this.props.fullValue.symmetric === false) {
        // it has to be explicitly set to false, because we don't want it to catch
        // cases when it's undefined
        mode = 'asymmetric';
      }

      return mode;
    }
  }, {
    key: 'renderModeSelector',
    value: function renderModeSelector() {
      var _ = this.context.localize;


      return _react2.default.createElement(
        _Field2.default,
        null,
        _react2.default.createElement(_RadioBlocks2.default, {
          alignment: 'center',
          onOptionChange: this.updatePlot,
          activeOption: this.getMode(),
          options: [{ label: _('None'), value: 'hidden' }, { label: _('Symmetric'), value: 'symmetric' }, { label: _('Asymmetric'), value: 'asymmetric' }]
        })
      );
    }
  }, {
    key: 'renderErrorBarControls',
    value: function renderErrorBarControls() {
      var _ = this.context.localize;

      var mode = this.getMode();
      var showCustomDataControl = this.props.fullValue.type === 'data';

      var styleAttrs = _react2.default.createElement(
        _react.Fragment,
        null,
        _react2.default.createElement(_index.Radio, {
          label: _('Copy Y Style'),
          attr: this.props.attr + '.copy_ystyle',
          options: [{ label: _('Yes'), value: true }, { label: _('No'), value: false }]
        }),
        _react2.default.createElement(_index.Radio, {
          label: _('Copy Z Style'),
          attr: this.props.attr + '.copy_zstyle',
          options: [{ label: _('Yes'), value: true }, { label: _('No'), value: false }]
        }),
        _react2.default.createElement(_index.MultiColorPicker, { label: _('Color'), attr: this.props.attr + '.color' }),
        _react2.default.createElement(_index.Numeric, { label: _('Thickness'), attr: this.props.attr + '.thickness' }),
        _react2.default.createElement(_index.Numeric, { label: _('Crossbar Width'), attr: this.props.attr + '.width' })
      );

      if (mode === 'symmetric') {
        return _react2.default.createElement(
          _react.Fragment,
          null,
          _react2.default.createElement(_index.Radio, {
            label: _('Error Type'),
            attr: this.props.attr + '.type',
            options: [{ label: _('%'), value: 'percent' }, { label: _('Constant'), value: 'constant' }, { label: _('√'), value: 'sqrt' }, { label: _('Data'), value: 'data' }]
          }),
          _react2.default.createElement(_index.Numeric, { label: _('Value'), attr: this.props.attr + '.value' }),
          showCustomDataControl ? _react2.default.createElement(_index.DataSelector, { label: _('Custom Data'), attr: this.props.attr + '.array' }) : null,
          styleAttrs
        );
      }

      if (mode === 'asymmetric') {
        return _react2.default.createElement(
          _react.Fragment,
          null,
          _react2.default.createElement(_index.Radio, {
            label: _('Error Type'),
            attr: this.props.attr + '.type',
            options: [{ label: _('%'), value: 'percent' }, { label: _('Constant'), value: 'constant' }, { label: _('Data'), value: 'data' }]
          }),
          _react2.default.createElement(_index.Numeric, { label: _('Value'), attr: this.props.attr + '.value' }),
          _react2.default.createElement(_index.Numeric, { label: _('Value (-)'), attr: this.props.attr + '.valueminus' }),
          showCustomDataControl ? _react2.default.createElement(
            _react.Fragment,
            null,
            _react2.default.createElement(_index.DataSelector, { label: _('Error (+)'), attr: this.props.attr + '.array' }),
            _react2.default.createElement(_index.DataSelector, { label: _('Error (-)'), attr: this.props.attr + '.arrayminus' })
          ) : null,
          styleAttrs
        );
      }

      return null;
    }
  }, {
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        _react.Fragment,
        null,
        this.renderModeSelector(),
        this.renderErrorBarControls()
      );
    }
  }]);

  return ErrorBars;
}(_react.Component);

ErrorBars.propTypes = {
  attr: _propTypes2.default.string,
  fullValue: _propTypes2.default.object,
  updatePlot: _propTypes2.default.func
};

ErrorBars.contextTypes = {
  localize: _propTypes2.default.func
};

exports.default = (0, _lib.connectToContainer)(ErrorBars);
//# sourceMappingURL=ErrorBars.js.map

/***/ }),

/***/ "j/+3":
/*!***********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeAreaIcon.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeAreaIcon = function TraceTypeAreaIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement('path', { fill: 'none', d: 'M0 0h46v46H0z' }),
        _react2.default.createElement('path', { fill: '#25fdfc', d: 'M38 39V23l-11 4-9-3-11 3v12h31z' }),
        _react2.default.createElement('path', { fill: '#1d9bfb', d: 'M38 21l-11 4-9-3-11 3V14l14 5L38 7v14z' })
    );
};

exports.default = TraceTypeAreaIcon;

/***/ }),

/***/ "j/1Z":
/*!*************************************************************************************!*\
  !*** ./node_modules/node-libs-browser/node_modules/util/support/isBufferBrowser.js ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = function isBuffer(arg) {
  return arg && typeof arg === 'object'
    && typeof arg.copy === 'function'
    && typeof arg.fill === 'function'
    && typeof arg.readUInt8 === 'function';
}

/***/ }),

/***/ "j2DC":
/*!**************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_iter-create.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var create = __webpack_require__(/*! ./_object-create */ "oVml");
var descriptor = __webpack_require__(/*! ./_property-desc */ "rr1i");
var setToStringTag = __webpack_require__(/*! ./_set-to-string-tag */ "RfKB");
var IteratorPrototype = {};

// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
__webpack_require__(/*! ./_hide */ "NegM")(IteratorPrototype, __webpack_require__(/*! ./_wks */ "UWiX")('iterator'), function () { return this; });

module.exports = function (Constructor, NAME, next) {
  Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) });
  setToStringTag(Constructor, NAME + ' Iterator');
};


/***/ }),

/***/ "jAxu":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/notebook/style/index.css ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "GO48");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "jDMi":
/*!*************************************************************!*\
  !*** ./node_modules/codemirror/addon/edit/matchbrackets.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"));
  else {}
})(function(CodeMirror) {
  var ie_lt8 = /MSIE \d/.test(navigator.userAgent) &&
    (document.documentMode == null || document.documentMode < 8);

  var Pos = CodeMirror.Pos;

  var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};

  function findMatchingBracket(cm, where, config) {
    var line = cm.getLineHandle(where.line), pos = where.ch - 1;
    var afterCursor = config && config.afterCursor
    if (afterCursor == null)
      afterCursor = /(^| )cm-fat-cursor($| )/.test(cm.getWrapperElement().className)

    // A cursor is defined as between two characters, but in in vim command mode
    // (i.e. not insert mode), the cursor is visually represented as a
    // highlighted box on top of the 2nd character. Otherwise, we allow matches
    // from before or after the cursor.
    var match = (!afterCursor && pos >= 0 && matching[line.text.charAt(pos)]) ||
        matching[line.text.charAt(++pos)];
    if (!match) return null;
    var dir = match.charAt(1) == ">" ? 1 : -1;
    if (config && config.strict && (dir > 0) != (pos == where.ch)) return null;
    var style = cm.getTokenTypeAt(Pos(where.line, pos + 1));

    var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style || null, config);
    if (found == null) return null;
    return {from: Pos(where.line, pos), to: found && found.pos,
            match: found && found.ch == match.charAt(0), forward: dir > 0};
  }

  // bracketRegex is used to specify which type of bracket to scan
  // should be a regexp, e.g. /[[\]]/
  //
  // Note: If "where" is on an open bracket, then this bracket is ignored.
  //
  // Returns false when no bracket was found, null when it reached
  // maxScanLines and gave up
  function scanForBracket(cm, where, dir, style, config) {
    var maxScanLen = (config && config.maxScanLineLength) || 10000;
    var maxScanLines = (config && config.maxScanLines) || 1000;

    var stack = [];
    var re = config && config.bracketRegex ? config.bracketRegex : /[(){}[\]]/;
    var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1)
                          : Math.max(cm.firstLine() - 1, where.line - maxScanLines);
    for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) {
      var line = cm.getLine(lineNo);
      if (!line) continue;
      var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1;
      if (line.length > maxScanLen) continue;
      if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0);
      for (; pos != end; pos += dir) {
        var ch = line.charAt(pos);
        if (re.test(ch) && (style === undefined || cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style)) {
          var match = matching[ch];
          if ((match.charAt(1) == ">") == (dir > 0)) stack.push(ch);
          else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch};
          else stack.pop();
        }
      }
    }
    return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null;
  }

  function matchBrackets(cm, autoclear, config) {
    // Disable brace matching in long lines, since it'll cause hugely slow updates
    var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000;
    var marks = [], ranges = cm.listSelections();
    for (var i = 0; i < ranges.length; i++) {
      var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, config);
      if (match && cm.getLine(match.from.line).length <= maxHighlightLen) {
        var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
        marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style}));
        if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen)
          marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style}));
      }
    }

    if (marks.length) {
      // Kludge to work around the IE bug from issue #1193, where text
      // input stops going to the textare whever this fires.
      if (ie_lt8 && cm.state.focused) cm.focus();

      var clear = function() {
        cm.operation(function() {
          for (var i = 0; i < marks.length; i++) marks[i].clear();
        });
      };
      if (autoclear) setTimeout(clear, 800);
      else return clear;
    }
  }

  function doMatchBrackets(cm) {
    cm.operation(function() {
      if (cm.state.matchBrackets.currentlyHighlighted) {
        cm.state.matchBrackets.currentlyHighlighted();
        cm.state.matchBrackets.currentlyHighlighted = null;
      }
      cm.state.matchBrackets.currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets);
    });
  }

  CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
    if (old && old != CodeMirror.Init) {
      cm.off("cursorActivity", doMatchBrackets);
      if (cm.state.matchBrackets && cm.state.matchBrackets.currentlyHighlighted) {
        cm.state.matchBrackets.currentlyHighlighted();
        cm.state.matchBrackets.currentlyHighlighted = null;
      }
    }
    if (val) {
      cm.state.matchBrackets = typeof val == "object" ? val : {};
      cm.on("cursorActivity", doMatchBrackets);
    }
  });

  CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);});
  CodeMirror.defineExtension("findMatchingBracket", function(pos, config, oldConfig){
    // Backwards-compatibility kludge
    if (oldConfig || typeof config == "boolean") {
      if (!oldConfig) {
        config = config ? {strict: true} : null
      } else {
        oldConfig.strict = config
        config = oldConfig
      }
    }
    return findMatchingBracket(this, pos, config)
  });
  CodeMirror.defineExtension("scanForBracket", function(pos, dir, style, config){
    return scanForBracket(this, pos, dir, style, config);
  });
});


/***/ }),

/***/ "jH4x":
/*!*************************************************************!*\
  !*** ./node_modules/draft-js/lib/editOnCompositionStart.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule editOnCompositionStart
 * @format
 * 
 */



var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");

/**
 * The user has begun using an IME input system. Switching to `composite` mode
 * allows handling composition input and disables other edit behavior.
 */
function editOnCompositionStart(editor, e) {
  editor.setMode('composite');
  editor.update(EditorState.set(editor._latestEditorState, { inCompositionMode: true }));
  // Allow composition handler to interpret the compositionstart event
  editor._onCompositionStart(e);
}

module.exports = editOnCompositionStart;

/***/ }),

/***/ "jIre":
/*!******************************************!*\
  !*** ./node_modules/buffer-xor/index.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(Buffer) {module.exports = function xor (a, b) {
  var length = Math.min(a.length, b.length)
  var buffer = new Buffer(length)

  for (var i = 0; i < length; ++i) {
    buffer[i] = a[i] ^ b[i]
  }

  return buffer
}

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../buffer/index.js */ "tjlA").Buffer))

/***/ }),

/***/ "jLRO":
/*!***********************************************!*\
  !*** ./node_modules/fbjs/lib/UnicodeUtils.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks
 */

/**
 * Unicode-enabled replacesments for basic String functions.
 *
 * All the functions in this module assume that the input string is a valid
 * UTF-16 encoding of a Unicode sequence. If it's not the case, the behavior
 * will be undefined.
 *
 * WARNING: Since this module is typechecks-enforced, you may find new bugs
 * when replacing normal String functions with ones provided here.
 */



var invariant = __webpack_require__(/*! ./invariant */ "2NuI");

// These two ranges are consecutive so anything in [HIGH_START, LOW_END] is a
// surrogate code unit.
var SURROGATE_HIGH_START = 0xD800;
var SURROGATE_HIGH_END = 0xDBFF;
var SURROGATE_LOW_START = 0xDC00;
var SURROGATE_LOW_END = 0xDFFF;
var SURROGATE_UNITS_REGEX = /[\uD800-\uDFFF]/;

/**
 * @param {number} codeUnit   A Unicode code-unit, in range [0, 0x10FFFF]
 * @return {boolean}          Whether code-unit is in a surrogate (hi/low) range
 */
function isCodeUnitInSurrogateRange(codeUnit) {
  return SURROGATE_HIGH_START <= codeUnit && codeUnit <= SURROGATE_LOW_END;
}

/**
 * Returns whether the two characters starting at `index` form a surrogate pair.
 * For example, given the string s = "\uD83D\uDE0A", (s, 0) returns true and
 * (s, 1) returns false.
 *
 * @param {string} str
 * @param {number} index
 * @return {boolean}
 */
function isSurrogatePair(str, index) {
  !(0 <= index && index < str.length) ?  true ? invariant(false, 'isSurrogatePair: Invalid index %s for string length %s.', index, str.length) : undefined : void 0;
  if (index + 1 === str.length) {
    return false;
  }
  var first = str.charCodeAt(index);
  var second = str.charCodeAt(index + 1);
  return SURROGATE_HIGH_START <= first && first <= SURROGATE_HIGH_END && SURROGATE_LOW_START <= second && second <= SURROGATE_LOW_END;
}

/**
 * @param {string} str  Non-empty string
 * @return {boolean}    True if the input includes any surrogate code units
 */
function hasSurrogateUnit(str) {
  return SURROGATE_UNITS_REGEX.test(str);
}

/**
 * Return the length of the original Unicode character at given position in the
 * String by looking into the UTF-16 code unit; that is equal to 1 for any
 * non-surrogate characters in BMP ([U+0000..U+D7FF] and [U+E000, U+FFFF]); and
 * returns 2 for the hi/low surrogates ([U+D800..U+DFFF]), which are in fact
 * representing non-BMP characters ([U+10000..U+10FFFF]).
 *
 * Examples:
 * - '\u0020' => 1
 * - '\u3020' => 1
 * - '\uD835' => 2
 * - '\uD835\uDDEF' => 2
 * - '\uDDEF' => 2
 *
 * @param {string} str  Non-empty string
 * @param {number} pos  Position in the string to look for one code unit
 * @return {number}      Number 1 or 2
 */
function getUTF16Length(str, pos) {
  return 1 + isCodeUnitInSurrogateRange(str.charCodeAt(pos));
}

/**
 * Fully Unicode-enabled replacement for String#length
 *
 * @param {string} str  Valid Unicode string
 * @return {number}     The number of Unicode characters in the string
 */
function strlen(str) {
  // Call the native functions if there's no surrogate char
  if (!hasSurrogateUnit(str)) {
    return str.length;
  }

  var len = 0;
  for (var pos = 0; pos < str.length; pos += getUTF16Length(str, pos)) {
    len++;
  }
  return len;
}

/**
 * Fully Unicode-enabled replacement for String#substr()
 *
 * @param {string} str      Valid Unicode string
 * @param {number} start    Location in Unicode sequence to begin extracting
 * @param {?number} length  The number of Unicode characters to extract
 *                          (default: to the end of the string)
 * @return {string}         Extracted sub-string
 */
function substr(str, start, length) {
  start = start || 0;
  length = length === undefined ? Infinity : length || 0;

  // Call the native functions if there's no surrogate char
  if (!hasSurrogateUnit(str)) {
    return str.substr(start, length);
  }

  // Obvious cases
  var size = str.length;
  if (size <= 0 || start > size || length <= 0) {
    return '';
  }

  // Find the actual starting position
  var posA = 0;
  if (start > 0) {
    for (; start > 0 && posA < size; start--) {
      posA += getUTF16Length(str, posA);
    }
    if (posA >= size) {
      return '';
    }
  } else if (start < 0) {
    for (posA = size; start < 0 && 0 < posA; start++) {
      posA -= getUTF16Length(str, posA - 1);
    }
    if (posA < 0) {
      posA = 0;
    }
  }

  // Find the actual ending position
  var posB = size;
  if (length < size) {
    for (posB = posA; length > 0 && posB < size; length--) {
      posB += getUTF16Length(str, posB);
    }
  }

  return str.substring(posA, posB);
}

/**
 * Fully Unicode-enabled replacement for String#substring()
 *
 * @param {string} str    Valid Unicode string
 * @param {number} start  Location in Unicode sequence to begin extracting
 * @param {?number} end   Location in Unicode sequence to end extracting
 *                        (default: end of the string)
 * @return {string}       Extracted sub-string
 */
function substring(str, start, end) {
  start = start || 0;
  end = end === undefined ? Infinity : end || 0;

  if (start < 0) {
    start = 0;
  }
  if (end < 0) {
    end = 0;
  }

  var length = Math.abs(end - start);
  start = start < end ? start : end;
  return substr(str, start, length);
}

/**
 * Get a list of Unicode code-points from a String
 *
 * @param {string} str        Valid Unicode string
 * @return {array<number>}    A list of code-points in [0..0x10FFFF]
 */
function getCodePoints(str) {
  var codePoints = [];
  for (var pos = 0; pos < str.length; pos += getUTF16Length(str, pos)) {
    codePoints.push(str.codePointAt(pos));
  }
  return codePoints;
}

var UnicodeUtils = {
  getCodePoints: getCodePoints,
  getUTF16Length: getUTF16Length,
  hasSurrogateUnit: hasSurrogateUnit,
  isCodeUnitInSurrogateRange: isCodeUnitInSurrogateRange,
  isSurrogatePair: isSurrogatePair,
  strlen: strlen,
  substring: substring,
  substr: substr
};

module.exports = UnicodeUtils;

/***/ }),

/***/ "jNJa":
/*!*****************************************************************!*\
  !*** ./node_modules/xterm/lib/renderer/atlas/CharAtlasUtils.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function generateConfig(scaledCharWidth, scaledCharHeight, terminal, colors) {
    var clonedColors = {
        foreground: colors.foreground,
        background: colors.background,
        cursor: null,
        cursorAccent: null,
        selection: null,
        ansi: colors.ansi.slice(0, 16)
    };
    return {
        devicePixelRatio: window.devicePixelRatio,
        scaledCharWidth: scaledCharWidth,
        scaledCharHeight: scaledCharHeight,
        fontFamily: terminal.options.fontFamily,
        fontSize: terminal.options.fontSize,
        fontWeight: terminal.options.fontWeight,
        fontWeightBold: terminal.options.fontWeightBold,
        allowTransparency: terminal.options.allowTransparency,
        colors: clonedColors
    };
}
exports.generateConfig = generateConfig;
function configEquals(a, b) {
    for (var i = 0; i < a.colors.ansi.length; i++) {
        if (a.colors.ansi[i].rgba !== b.colors.ansi[i].rgba) {
            return false;
        }
    }
    return a.devicePixelRatio === b.devicePixelRatio &&
        a.fontFamily === b.fontFamily &&
        a.fontSize === b.fontSize &&
        a.fontWeight === b.fontWeight &&
        a.fontWeightBold === b.fontWeightBold &&
        a.allowTransparency === b.allowTransparency &&
        a.scaledCharWidth === b.scaledCharWidth &&
        a.scaledCharHeight === b.scaledCharHeight &&
        a.colors.foreground === b.colors.foreground &&
        a.colors.background === b.colors.background;
}
exports.configEquals = configEquals;

//# sourceMappingURL=CharAtlasUtils.js.map


/***/ }),

/***/ "jQLo":
/*!***********************************************!*\
  !*** ./node_modules/ajv/lib/compile/index.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var resolve = __webpack_require__(/*! ./resolve */ "qXHa")
  , util = __webpack_require__(/*! ./util */ "+9rK")
  , errorClasses = __webpack_require__(/*! ./error_classes */ "iZoB")
  , stableStringify = __webpack_require__(/*! json-stable-stringify */ "rE/H");

var validateGenerator = __webpack_require__(/*! ../dotjs/validate */ "1QhW");

/**
 * Functions below are used inside compiled validations function
 */

var co = __webpack_require__(/*! co */ "GH25");
var ucs2length = util.ucs2length;
var equal = __webpack_require__(/*! ./equal */ "gQ7D");

// this error is thrown by async schemas to return validation errors via exception
var ValidationError = errorClasses.Validation;

module.exports = compile;


/**
 * Compiles schema to validation function
 * @this   Ajv
 * @param  {Object} schema schema object
 * @param  {Object} root object with information about the root schema for this schema
 * @param  {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution
 * @param  {String} baseId base ID for IDs in the schema
 * @return {Function} validation function
 */
function compile(schema, root, localRefs, baseId) {
  /* jshint validthis: true, evil: true */
  /* eslint no-shadow: 0 */
  var self = this
    , opts = this._opts
    , refVal = [ undefined ]
    , refs = {}
    , patterns = []
    , patternsHash = {}
    , defaults = []
    , defaultsHash = {}
    , customRules = [];

  root = root || { schema: schema, refVal: refVal, refs: refs };

  var c = checkCompiling.call(this, schema, root, baseId);
  var compilation = this._compilations[c.index];
  if (c.compiling) return (compilation.callValidate = callValidate);

  var formats = this._formats;
  var RULES = this.RULES;

  try {
    var v = localCompile(schema, root, localRefs, baseId);
    compilation.validate = v;
    var cv = compilation.callValidate;
    if (cv) {
      cv.schema = v.schema;
      cv.errors = null;
      cv.refs = v.refs;
      cv.refVal = v.refVal;
      cv.root = v.root;
      cv.$async = v.$async;
      if (opts.sourceCode) cv.source = v.source;
    }
    return v;
  } finally {
    endCompiling.call(this, schema, root, baseId);
  }

  function callValidate() {
    var validate = compilation.validate;
    var result = validate.apply(null, arguments);
    callValidate.errors = validate.errors;
    return result;
  }

  function localCompile(_schema, _root, localRefs, baseId) {
    var isRoot = !_root || (_root && _root.schema == _schema);
    if (_root.schema != root.schema)
      return compile.call(self, _schema, _root, localRefs, baseId);

    var $async = _schema.$async === true;

    var sourceCode = validateGenerator({
      isTop: true,
      schema: _schema,
      isRoot: isRoot,
      baseId: baseId,
      root: _root,
      schemaPath: '',
      errSchemaPath: '#',
      errorPath: '""',
      MissingRefError: errorClasses.MissingRef,
      RULES: RULES,
      validate: validateGenerator,
      util: util,
      resolve: resolve,
      resolveRef: resolveRef,
      usePattern: usePattern,
      useDefault: useDefault,
      useCustomRule: useCustomRule,
      opts: opts,
      formats: formats,
      self: self
    });

    sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode)
                   + vars(defaults, defaultCode) + vars(customRules, customRuleCode)
                   + sourceCode;

    if (opts.processCode) sourceCode = opts.processCode(sourceCode);
    // console.log('\n\n\n *** \n', JSON.stringify(sourceCode));
    var validate;
    try {
      var makeValidate = new Function(
        'self',
        'RULES',
        'formats',
        'root',
        'refVal',
        'defaults',
        'customRules',
        'co',
        'equal',
        'ucs2length',
        'ValidationError',
        sourceCode
      );

      validate = makeValidate(
        self,
        RULES,
        formats,
        root,
        refVal,
        defaults,
        customRules,
        co,
        equal,
        ucs2length,
        ValidationError
      );

      refVal[0] = validate;
    } catch(e) {
      console.error('Error compiling schema, function code:', sourceCode);
      throw e;
    }

    validate.schema = _schema;
    validate.errors = null;
    validate.refs = refs;
    validate.refVal = refVal;
    validate.root = isRoot ? validate : _root;
    if ($async) validate.$async = true;
    if (opts.sourceCode === true) {
      validate.source = {
        code: sourceCode,
        patterns: patterns,
        defaults: defaults
      };
    }

    return validate;
  }

  function resolveRef(baseId, ref, isRoot) {
    ref = resolve.url(baseId, ref);
    var refIndex = refs[ref];
    var _refVal, refCode;
    if (refIndex !== undefined) {
      _refVal = refVal[refIndex];
      refCode = 'refVal[' + refIndex + ']';
      return resolvedRef(_refVal, refCode);
    }
    if (!isRoot && root.refs) {
      var rootRefId = root.refs[ref];
      if (rootRefId !== undefined) {
        _refVal = root.refVal[rootRefId];
        refCode = addLocalRef(ref, _refVal);
        return resolvedRef(_refVal, refCode);
      }
    }

    refCode = addLocalRef(ref);
    var v = resolve.call(self, localCompile, root, ref);
    if (v === undefined) {
      var localSchema = localRefs && localRefs[ref];
      if (localSchema) {
        v = resolve.inlineRef(localSchema, opts.inlineRefs)
            ? localSchema
            : compile.call(self, localSchema, root, localRefs, baseId);
      }
    }

    if (v !== undefined) {
      replaceLocalRef(ref, v);
      return resolvedRef(v, refCode);
    }
  }

  function addLocalRef(ref, v) {
    var refId = refVal.length;
    refVal[refId] = v;
    refs[ref] = refId;
    return 'refVal' + refId;
  }

  function replaceLocalRef(ref, v) {
    var refId = refs[ref];
    refVal[refId] = v;
  }

  function resolvedRef(refVal, code) {
    return typeof refVal == 'object' || typeof refVal == 'boolean'
            ? { code: code, schema: refVal, inline: true }
            : { code: code, $async: refVal && refVal.$async };
  }

  function usePattern(regexStr) {
    var index = patternsHash[regexStr];
    if (index === undefined) {
      index = patternsHash[regexStr] = patterns.length;
      patterns[index] = regexStr;
    }
    return 'pattern' + index;
  }

  function useDefault(value) {
    switch (typeof value) {
      case 'boolean':
      case 'number':
        return '' + value;
      case 'string':
        return util.toQuotedString(value);
      case 'object':
        if (value === null) return 'null';
        var valueStr = stableStringify(value);
        var index = defaultsHash[valueStr];
        if (index === undefined) {
          index = defaultsHash[valueStr] = defaults.length;
          defaults[index] = value;
        }
        return 'default' + index;
    }
  }

  function useCustomRule(rule, schema, parentSchema, it) {
    var validateSchema = rule.definition.validateSchema;
    if (validateSchema && self._opts.validateSchema !== false) {
      var valid = validateSchema(schema);
      if (!valid) {
        var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);
        if (self._opts.validateSchema == 'log') console.error(message);
        else throw new Error(message);
      }
    }

    var compile = rule.definition.compile
      , inline = rule.definition.inline
      , macro = rule.definition.macro;

    var validate;
    if (compile) {
      validate = compile.call(self, schema, parentSchema, it);
    } else if (macro) {
      validate = macro.call(self, schema, parentSchema, it);
      if (opts.validateSchema !== false) self.validateSchema(validate, true);
    } else if (inline) {
      validate = inline.call(self, it, rule.keyword, schema, parentSchema);
    } else {
      validate = rule.definition.validate;
      if (!validate) return;
    }

    if (validate === undefined)
      throw new Error('custom keyword "' + rule.keyword + '"failed to compile');

    var index = customRules.length;
    customRules[index] = validate;

    return {
      code: 'customRule' + index,
      validate: validate
    };
  }
}


/**
 * Checks if the schema is currently compiled
 * @this   Ajv
 * @param  {Object} schema schema to compile
 * @param  {Object} root root object
 * @param  {String} baseId base schema ID
 * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean)
 */
function checkCompiling(schema, root, baseId) {
  /* jshint validthis: true */
  var index = compIndex.call(this, schema, root, baseId);
  if (index >= 0) return { index: index, compiling: true };
  index = this._compilations.length;
  this._compilations[index] = {
    schema: schema,
    root: root,
    baseId: baseId
  };
  return { index: index, compiling: false };
}


/**
 * Removes the schema from the currently compiled list
 * @this   Ajv
 * @param  {Object} schema schema to compile
 * @param  {Object} root root object
 * @param  {String} baseId base schema ID
 */
function endCompiling(schema, root, baseId) {
  /* jshint validthis: true */
  var i = compIndex.call(this, schema, root, baseId);
  if (i >= 0) this._compilations.splice(i, 1);
}


/**
 * Index of schema compilation in the currently compiled list
 * @this   Ajv
 * @param  {Object} schema schema to compile
 * @param  {Object} root root object
 * @param  {String} baseId base schema ID
 * @return {Integer} compilation index
 */
function compIndex(schema, root, baseId) {
  /* jshint validthis: true */
  for (var i=0; i<this._compilations.length; i++) {
    var c = this._compilations[i];
    if (c.schema == schema && c.root == root && c.baseId == baseId) return i;
  }
  return -1;
}


function patternCode(i, patterns) {
  return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');';
}


function defaultCode(i) {
  return 'var default' + i + ' = defaults[' + i + '];';
}


function refValCode(i, refVal) {
  return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];';
}


function customRuleCode(i) {
  return 'var customRule' + i + ' = customRules[' + i + '];';
}


function vars(arr, statement) {
  if (!arr.length) return '';
  var code = '';
  for (var i=0; i<arr.length; i++)
    code += statement(i, arr);
  return code;
}


/***/ }),

/***/ "jQqP":
/*!*****************************************************!*\
  !*** ./node_modules/@phosphor/algorithm/lib/map.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var iter_1 = __webpack_require__(/*! ./iter */ "DMSk");
/**
 * Transform the values of an iterable with a mapping function.
 *
 * @param object - The iterable or array-like object of interest.
 *
 * @param fn - The mapping function to invoke for each value.
 *
 * @returns An iterator which yields the transformed values.
 *
 * #### Example
 * ```typescript
 * import { map, toArray } from '@phosphor/algorithm';
 *
 * let data = [1, 2, 3];
 *
 * let stream = map(data, value => value * 2);
 *
 * toArray(stream);  // [2, 4, 6]
 * ```
 */
function map(object, fn) {
    return new MapIterator(iter_1.iter(object), fn);
}
exports.map = map;
/**
 * An iterator which transforms values using a mapping function.
 */
var MapIterator = (function () {
    /**
     * Construct a new map iterator.
     *
     * @param source - The iterator of values of interest.
     *
     * @param fn - The mapping function to invoke for each value.
     */
    function MapIterator(source, fn) {
        this._index = 0;
        this._source = source;
        this._fn = fn;
    }
    /**
     * Get an iterator over the object's values.
     *
     * @returns An iterator which yields the object's values.
     */
    MapIterator.prototype.iter = function () {
        return this;
    };
    /**
     * Create an independent clone of the iterator.
     *
     * @returns A new independent clone of the iterator.
     */
    MapIterator.prototype.clone = function () {
        var result = new MapIterator(this._source.clone(), this._fn);
        result._index = this._index;
        return result;
    };
    /**
     * Get the next value from the iterator.
     *
     * @returns The next value from the iterator, or `undefined`.
     */
    MapIterator.prototype.next = function () {
        var value = this._source.next();
        if (value === undefined) {
            return undefined;
        }
        return this._fn.call(undefined, value, this._index++);
    };
    return MapIterator;
}());
exports.MapIterator = MapIterator;


/***/ }),

/***/ "jRlY":
/*!************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/default_panels/GraphTransformsPanel.js ***!
  \************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Aggregations = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _components = __webpack_require__(/*! ../components */ "yF51");

var _lib = __webpack_require__(/*! ../lib */ "RXjw");

var _constants = __webpack_require__(/*! ../lib/constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var AggregationSection = (0, _lib.connectAggregationToTransform)(_components.PlotlySection);

var Aggregations = exports.Aggregations = function (_Component) {
  _inherits(Aggregations, _Component);

  function Aggregations() {
    _classCallCheck(this, Aggregations);

    return _possibleConstructorReturn(this, (Aggregations.__proto__ || Object.getPrototypeOf(Aggregations)).apply(this, arguments));
  }

  _createClass(Aggregations, [{
    key: 'render',
    value: function render() {
      var _context$fullContaine = this.context.fullContainer.aggregations,
          aggregations = _context$fullContaine === undefined ? [] : _context$fullContaine;
      var _ = this.context.localize;

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

      return _react2.default.createElement(
        _components.PlotlySection,
        { name: _('Aggregations'), attr: 'aggregations' },
        aggregations.filter(function (aggr) {
          return aggr.target && aggr.target.match(/transforms\[\d*\]\./gi) === null;
        }).map(function (_ref, i) {
          var target = _ref.target;
          return _react2.default.createElement(
            AggregationSection,
            { show: true, key: i, aggregationIndex: i },
            _react2.default.createElement(_components.Dropdown, {
              attr: 'func',
              label: target,
              options: [{ label: _('Count'), value: 'count' }, { label: _('Sum'), value: 'sum' }, { label: _('Average'), value: 'avg' }, { label: _('Median'), value: 'median' }, { label: _('Mode'), value: 'mode' }, { label: _('RMS'), value: 'rms' }, { label: _('Standard Deviation'), value: 'stddev' }, { label: _('Min'), value: 'min' }, { label: _('Max'), value: 'max' }, { label: _('First'), value: 'first' }, { label: _('Last'), value: 'last' }, { label: _('Change'), value: 'change' }, { label: _('Range'), value: 'range' }],
              clearable: false
            })
          );
        })
      );
    }
  }]);

  return Aggregations;
}(_react.Component);

Aggregations.plotly_editor_traits = { no_visibility_forcing: true };
Aggregations.contextTypes = {
  fullContainer: _propTypes2.default.object,
  localize: _propTypes2.default.func
};

var GraphTransformsPanel = function GraphTransformsPanel(props, _ref2) {
  var _ = _ref2.localize;

  return _react2.default.createElement(
    _components.TraceAccordion,
    { traceFilterCondition: function traceFilterCondition(t) {
        return _constants.TRANSFORMABLE_TRACES.includes(t.type);
      } },
    _react2.default.createElement(
      _components.TransformAccordion,
      null,
      _react2.default.createElement(_components.Radio, {
        attr: 'enabled',
        options: [{ label: _('Enabled'), value: true }, { label: _('Disabled'), value: false }]
      }),
      _react2.default.createElement(_components.DataSelector, { label: _('By'), attr: 'groups' }),
      _react2.default.createElement(_components.DataSelector, { label: _('Target'), attr: 'target' }),
      _react2.default.createElement(_components.FilterOperation, { label: _('Operator'), attr: 'operation' }),
      _react2.default.createElement(_components.FilterValue, { label: _('Value'), attr: 'value' }),
      _react2.default.createElement(_components.Radio, {
        attr: 'order',
        options: [{ label: _('Ascending'), value: 'ascending' }, { label: _('Descending'), value: 'descending' }]
      }),
      _react2.default.createElement(Aggregations, null)
    )
  );
};

GraphTransformsPanel.contextTypes = {
  localize: _propTypes2.default.func
};

exports.default = GraphTransformsPanel;
//# sourceMappingURL=GraphTransformsPanel.js.map

/***/ }),

/***/ "jTF0":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/docregistry/lib/index.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(__webpack_require__(/*! ./context */ "xotT"));
__export(__webpack_require__(/*! ./default */ "Or5M"));
__export(__webpack_require__(/*! ./mimedocument */ "9vST"));
__export(__webpack_require__(/*! ./registry */ "EW/T"));
__webpack_require__(/*! ../style/index.css */ "oDlj");


/***/ }),

/***/ "jTUL":
/*!**************************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/processor.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _lazyResult = __webpack_require__(/*! ./lazy-result */ "A7MO");

var _lazyResult2 = _interopRequireDefault(_lazyResult);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Contains plugins to process CSS. Create one `Processor` instance,
 * initialize its plugins, and then use that instance on numerous CSS files.
 *
 * @example
 * const processor = postcss([autoprefixer, precss]);
 * processor.process(css1).then(result => console.log(result.css));
 * processor.process(css2).then(result => console.log(result.css));
 */
var Processor = function () {

  /**
   * @param {Array.<Plugin|pluginFunction>|Processor} plugins - PostCSS
   *        plugins. See {@link Processor#use} for plugin format.
   */
  function Processor() {
    var plugins = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];

    _classCallCheck(this, Processor);

    /**
     * @member {string} - Current PostCSS version.
     *
     * @example
     * if ( result.processor.version.split('.')[0] !== '6' ) {
     *   throw new Error('This plugin works only with PostCSS 6');
     * }
     */
    this.version = '6.0.23';
    /**
     * @member {pluginFunction[]} - Plugins added to this processor.
     *
     * @example
     * const processor = postcss([autoprefixer, precss]);
     * processor.plugins.length //=> 2
     */
    this.plugins = this.normalize(plugins);
  }

  /**
   * Adds a plugin to be used as a CSS processor.
   *
   * PostCSS plugin can be in 4 formats:
   * * A plugin created by {@link postcss.plugin} method.
   * * A function. PostCSS will pass the function a @{link Root}
   *   as the first argument and current {@link Result} instance
   *   as the second.
   * * An object with a `postcss` method. PostCSS will use that method
   *   as described in #2.
   * * Another {@link Processor} instance. PostCSS will copy plugins
   *   from that instance into this one.
   *
   * Plugins can also be added by passing them as arguments when creating
   * a `postcss` instance (see [`postcss(plugins)`]).
   *
   * Asynchronous plugins should return a `Promise` instance.
   *
   * @param {Plugin|pluginFunction|Processor} plugin - PostCSS plugin
   *                                                   or {@link Processor}
   *                                                   with plugins
   *
   * @example
   * const processor = postcss()
   *   .use(autoprefixer)
   *   .use(precss);
   *
   * @return {Processes} current processor to make methods chain
   */


  Processor.prototype.use = function use(plugin) {
    this.plugins = this.plugins.concat(this.normalize([plugin]));
    return this;
  };

  /**
   * Parses source CSS and returns a {@link LazyResult} Promise proxy.
   * Because some plugins can be asynchronous it doesn’t make
   * any transformations. Transformations will be applied
   * in the {@link LazyResult} methods.
   *
   * @param {string|toString|Result} css - String with input CSS or
   *                                       any object with a `toString()`
   *                                       method, like a Buffer.
   *                                       Optionally, send a {@link Result}
   *                                       instance and the processor will
   *                                       take the {@link Root} from it.
   * @param {processOptions} [opts]      - options
   *
   * @return {LazyResult} Promise proxy
   *
   * @example
   * processor.process(css, { from: 'a.css', to: 'a.out.css' })
   *   .then(result => {
   *      console.log(result.css);
   *   });
   */


  Processor.prototype.process = function process(css) {
    var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

    return new _lazyResult2.default(this, css, opts);
  };

  Processor.prototype.normalize = function normalize(plugins) {
    var normalized = [];
    for (var _iterator = plugins, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
      var _ref;

      if (_isArray) {
        if (_i >= _iterator.length) break;
        _ref = _iterator[_i++];
      } else {
        _i = _iterator.next();
        if (_i.done) break;
        _ref = _i.value;
      }

      var i = _ref;

      if (i.postcss) i = i.postcss;

      if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object' && Array.isArray(i.plugins)) {
        normalized = normalized.concat(i.plugins);
      } else if (typeof i === 'function') {
        normalized.push(i);
      } else if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object' && (i.parse || i.stringify)) {
        throw new Error('PostCSS syntaxes cannot be used as plugins. ' + 'Instead, please use one of the ' + 'syntax/parser/stringifier options as ' + 'outlined in your PostCSS ' + 'runner documentation.');
      } else {
        throw new Error(i + ' is not a PostCSS plugin');
      }
    }
    return normalized;
  };

  return Processor;
}();

exports.default = Processor;

/**
 * @callback builder
 * @param {string} part          - part of generated CSS connected to this node
 * @param {Node}   node          - AST node
 * @param {"start"|"end"} [type] - node’s part type
 */

/**
 * @callback parser
 *
 * @param {string|toString} css   - string with input CSS or any object
 *                                  with toString() method, like a Buffer
 * @param {processOptions} [opts] - options with only `from` and `map` keys
 *
 * @return {Root} PostCSS AST
 */

/**
 * @callback stringifier
 *
 * @param {Node} node       - start node for stringifing. Usually {@link Root}.
 * @param {builder} builder - function to concatenate CSS from node’s parts
 *                            or generate string and source map
 *
 * @return {void}
 */

/**
 * @typedef {object} syntax
 * @property {parser} parse          - function to generate AST by string
 * @property {stringifier} stringify - function to generate string by AST
 */

/**
 * @typedef {object} toString
 * @property {function} toString
 */

/**
 * @callback pluginFunction
 * @param {Root} root     - parsed input CSS
 * @param {Result} result - result to set warnings or check other plugins
 */

/**
 * @typedef {object} Plugin
 * @property {function} postcss - PostCSS plugin function
 */

/**
 * @typedef {object} processOptions
 * @property {string} from             - the path of the CSS source file.
 *                                       You should always set `from`,
 *                                       because it is used in source map
 *                                       generation and syntax error messages.
 * @property {string} to               - the path where you’ll put the output
 *                                       CSS file. You should always set `to`
 *                                       to generate correct source maps.
 * @property {parser} parser           - function to generate AST by string
 * @property {stringifier} stringifier - class to generate string by AST
 * @property {syntax} syntax           - object with `parse` and `stringify`
 * @property {object} map              - source map options
 * @property {boolean} map.inline                    - does source map should
 *                                                     be embedded in the output
 *                                                     CSS as a base64-encoded
 *                                                     comment
 * @property {string|object|false|function} map.prev - source map content
 *                                                     from a previous
 *                                                     processing step
 *                                                     (for example, Sass).
 *                                                     PostCSS will try to find
 *                                                     previous map
 *                                                     automatically, so you
 *                                                     could disable it by
 *                                                     `false` value.
 * @property {boolean} map.sourcesContent            - does PostCSS should set
 *                                                     the origin content to map
 * @property {string|false} map.annotation           - does PostCSS should set
 *                                                     annotation comment to map
 * @property {string} map.from                       - override `from` in map’s
 *                                                     `sources`
 */

module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64, 


/***/ }),

/***/ "jTZ7":
/*!**************************************************************!*\
  !*** ./node_modules/@jupyterlab/filebrowser/style/index.css ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "5yTg");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "jUeY":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/el.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';

function isFunction(input) {
    return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
}


var el = moment.defineLocale('el', {
    monthsNominativeEl : 'Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος'.split('_'),
    monthsGenitiveEl : 'Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου'.split('_'),
    months : function (momentToFormat, format) {
        if (!momentToFormat) {
            return this._monthsNominativeEl;
        } else if (typeof format === 'string' && /D/.test(format.substring(0, format.indexOf('MMMM')))) { // if there is a day number before 'MMMM'
            return this._monthsGenitiveEl[momentToFormat.month()];
        } else {
            return this._monthsNominativeEl[momentToFormat.month()];
        }
    },
    monthsShort : 'Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ'.split('_'),
    weekdays : 'Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο'.split('_'),
    weekdaysShort : 'Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ'.split('_'),
    weekdaysMin : 'Κυ_Δε_Τρ_Τε_Πε_Πα_Σα'.split('_'),
    meridiem : function (hours, minutes, isLower) {
        if (hours > 11) {
            return isLower ? 'μμ' : 'ΜΜ';
        } else {
            return isLower ? 'πμ' : 'ΠΜ';
        }
    },
    isPM : function (input) {
        return ((input + '').toLowerCase()[0] === 'μ');
    },
    meridiemParse : /[ΠΜ]\.?Μ?\.?/i,
    longDateFormat : {
        LT : 'h:mm A',
        LTS : 'h:mm:ss A',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY h:mm A',
        LLLL : 'dddd, D MMMM YYYY h:mm A'
    },
    calendarEl : {
        sameDay : '[Σήμερα {}] LT',
        nextDay : '[Αύριο {}] LT',
        nextWeek : 'dddd [{}] LT',
        lastDay : '[Χθες {}] LT',
        lastWeek : function () {
            switch (this.day()) {
                case 6:
                    return '[το προηγούμενο] dddd [{}] LT';
                default:
                    return '[την προηγούμενη] dddd [{}] LT';
            }
        },
        sameElse : 'L'
    },
    calendar : function (key, mom) {
        var output = this._calendarEl[key],
            hours = mom && mom.hours();
        if (isFunction(output)) {
            output = output.apply(mom);
        }
        return output.replace('{}', (hours % 12 === 1 ? 'στη' : 'στις'));
    },
    relativeTime : {
        future : 'σε %s',
        past : '%s πριν',
        s : 'λίγα δευτερόλεπτα',
        ss : '%d δευτερόλεπτα',
        m : 'ένα λεπτό',
        mm : '%d λεπτά',
        h : 'μία ώρα',
        hh : '%d ώρες',
        d : 'μία μέρα',
        dd : '%d μέρες',
        M : 'ένας μήνας',
        MM : '%d μήνες',
        y : 'ένας χρόνος',
        yy : '%d χρόνια'
    },
    dayOfMonthOrdinalParse: /\d{1,2}η/,
    ordinal: '%dη',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4st is the first week of the year.
    }
});

return el;

})));


/***/ }),

/***/ "jVSn":
/*!**************************************************!*\
  !*** ./node_modules/xterm/lib/renderer/Types.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var FLAGS;
(function (FLAGS) {
    FLAGS[FLAGS["BOLD"] = 1] = "BOLD";
    FLAGS[FLAGS["UNDERLINE"] = 2] = "UNDERLINE";
    FLAGS[FLAGS["BLINK"] = 4] = "BLINK";
    FLAGS[FLAGS["INVERSE"] = 8] = "INVERSE";
    FLAGS[FLAGS["INVISIBLE"] = 16] = "INVISIBLE";
    FLAGS[FLAGS["DIM"] = 32] = "DIM";
})(FLAGS = exports.FLAGS || (exports.FLAGS = {}));

//# sourceMappingURL=Types.js.map


/***/ }),

/***/ "jVdC":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/pl.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var monthsNominative = 'styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień'.split('_'),
    monthsSubjective = 'stycznia_lutego_marca_kwietnia_maja_czerwca_lipca_sierpnia_września_października_listopada_grudnia'.split('_');
function plural(n) {
    return (n % 10 < 5) && (n % 10 > 1) && ((~~(n / 10) % 10) !== 1);
}
function translate(number, withoutSuffix, key) {
    var result = number + ' ';
    switch (key) {
        case 'ss':
            return result + (plural(number) ? 'sekundy' : 'sekund');
        case 'm':
            return withoutSuffix ? 'minuta' : 'minutę';
        case 'mm':
            return result + (plural(number) ? 'minuty' : 'minut');
        case 'h':
            return withoutSuffix  ? 'godzina'  : 'godzinę';
        case 'hh':
            return result + (plural(number) ? 'godziny' : 'godzin');
        case 'MM':
            return result + (plural(number) ? 'miesiące' : 'miesięcy');
        case 'yy':
            return result + (plural(number) ? 'lata' : 'lat');
    }
}

var pl = moment.defineLocale('pl', {
    months : function (momentToFormat, format) {
        if (!momentToFormat) {
            return monthsNominative;
        } else if (format === '') {
            // Hack: if format empty we know this is used to generate
            // RegExp by moment. Give then back both valid forms of months
            // in RegExp ready format.
            return '(' + monthsSubjective[momentToFormat.month()] + '|' + monthsNominative[momentToFormat.month()] + ')';
        } else if (/D MMMM/.test(format)) {
            return monthsSubjective[momentToFormat.month()];
        } else {
            return monthsNominative[momentToFormat.month()];
        }
    },
    monthsShort : 'sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru'.split('_'),
    weekdays : 'niedziela_poniedziałek_wtorek_środa_czwartek_piątek_sobota'.split('_'),
    weekdaysShort : 'ndz_pon_wt_śr_czw_pt_sob'.split('_'),
    weekdaysMin : 'Nd_Pn_Wt_Śr_Cz_Pt_So'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd, D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay: '[Dziś o] LT',
        nextDay: '[Jutro o] LT',
        nextWeek: function () {
            switch (this.day()) {
                case 0:
                    return '[W niedzielę o] LT';

                case 2:
                    return '[We wtorek o] LT';

                case 3:
                    return '[W środę o] LT';

                case 6:
                    return '[W sobotę o] LT';

                default:
                    return '[W] dddd [o] LT';
            }
        },
        lastDay: '[Wczoraj o] LT',
        lastWeek: function () {
            switch (this.day()) {
                case 0:
                    return '[W zeszłą niedzielę o] LT';
                case 3:
                    return '[W zeszłą środę o] LT';
                case 6:
                    return '[W zeszłą sobotę o] LT';
                default:
                    return '[W zeszły] dddd [o] LT';
            }
        },
        sameElse: 'L'
    },
    relativeTime : {
        future : 'za %s',
        past : '%s temu',
        s : 'kilka sekund',
        ss : translate,
        m : translate,
        mm : translate,
        h : translate,
        hh : translate,
        d : '1 dzień',
        dd : '%d dni',
        M : 'miesiąc',
        MM : translate,
        y : 'rok',
        yy : translate
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return pl;

})));


/***/ }),

/***/ "jWEn":
/*!***************************************!*\
  !*** ./node_modules/semver/semver.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(process) {exports = module.exports = SemVer;

// The debug function is excluded entirely from the minified version.
/* nomin */ var debug;
/* nomin */ if (typeof process === 'object' &&
    /* nomin */ process.env &&
    /* nomin */ process.env.NODE_DEBUG &&
    /* nomin */ /\bsemver\b/i.test(process.env.NODE_DEBUG))
  /* nomin */ debug = function() {
    /* nomin */ var args = Array.prototype.slice.call(arguments, 0);
    /* nomin */ args.unshift('SEMVER');
    /* nomin */ console.log.apply(console, args);
    /* nomin */ };
/* nomin */ else
  /* nomin */ debug = function() {};

// Note: this is the semver.org version of the spec that it implements
// Not necessarily the package version of this code.
exports.SEMVER_SPEC_VERSION = '2.0.0';

var MAX_LENGTH = 256;
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;

// Max safe segment length for coercion.
var MAX_SAFE_COMPONENT_LENGTH = 16;

// The actual regexps go on exports.re
var re = exports.re = [];
var src = exports.src = [];
var R = 0;

// The following Regular Expressions can be used for tokenizing,
// validating, and parsing SemVer version strings.

// ## Numeric Identifier
// A single `0`, or a non-zero digit followed by zero or more digits.

var NUMERICIDENTIFIER = R++;
src[NUMERICIDENTIFIER] = '0|[1-9]\\d*';
var NUMERICIDENTIFIERLOOSE = R++;
src[NUMERICIDENTIFIERLOOSE] = '[0-9]+';


// ## Non-numeric Identifier
// Zero or more digits, followed by a letter or hyphen, and then zero or
// more letters, digits, or hyphens.

var NONNUMERICIDENTIFIER = R++;
src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*';


// ## Main Version
// Three dot-separated numeric identifiers.

var MAINVERSION = R++;
src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' +
                   '(' + src[NUMERICIDENTIFIER] + ')\\.' +
                   '(' + src[NUMERICIDENTIFIER] + ')';

var MAINVERSIONLOOSE = R++;
src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' +
                        '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' +
                        '(' + src[NUMERICIDENTIFIERLOOSE] + ')';

// ## Pre-release Version Identifier
// A numeric identifier, or a non-numeric identifier.

var PRERELEASEIDENTIFIER = R++;
src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] +
                            '|' + src[NONNUMERICIDENTIFIER] + ')';

var PRERELEASEIDENTIFIERLOOSE = R++;
src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] +
                                 '|' + src[NONNUMERICIDENTIFIER] + ')';


// ## Pre-release Version
// Hyphen, followed by one or more dot-separated pre-release version
// identifiers.

var PRERELEASE = R++;
src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] +
                  '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))';

var PRERELEASELOOSE = R++;
src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] +
                       '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))';

// ## Build Metadata Identifier
// Any combination of digits, letters, or hyphens.

var BUILDIDENTIFIER = R++;
src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+';

// ## Build Metadata
// Plus sign, followed by one or more period-separated build metadata
// identifiers.

var BUILD = R++;
src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] +
             '(?:\\.' + src[BUILDIDENTIFIER] + ')*))';


// ## Full Version String
// A main version, followed optionally by a pre-release version and
// build metadata.

// Note that the only major, minor, patch, and pre-release sections of
// the version string are capturing groups.  The build metadata is not a
// capturing group, because it should not ever be used in version
// comparison.

var FULL = R++;
var FULLPLAIN = 'v?' + src[MAINVERSION] +
                src[PRERELEASE] + '?' +
                src[BUILD] + '?';

src[FULL] = '^' + FULLPLAIN + '$';

// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
// common in the npm registry.
var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] +
                 src[PRERELEASELOOSE] + '?' +
                 src[BUILD] + '?';

var LOOSE = R++;
src[LOOSE] = '^' + LOOSEPLAIN + '$';

var GTLT = R++;
src[GTLT] = '((?:<|>)?=?)';

// Something like "2.*" or "1.2.x".
// Note that "x.x" is a valid xRange identifer, meaning "any version"
// Only the first item is strictly required.
var XRANGEIDENTIFIERLOOSE = R++;
src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*';
var XRANGEIDENTIFIER = R++;
src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*';

var XRANGEPLAIN = R++;
src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' +
                   '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' +
                   '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' +
                   '(?:' + src[PRERELEASE] + ')?' +
                   src[BUILD] + '?' +
                   ')?)?';

var XRANGEPLAINLOOSE = R++;
src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' +
                        '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' +
                        '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' +
                        '(?:' + src[PRERELEASELOOSE] + ')?' +
                        src[BUILD] + '?' +
                        ')?)?';

var XRANGE = R++;
src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$';
var XRANGELOOSE = R++;
src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$';

// Coercion.
// Extract anything that could conceivably be a part of a valid semver
var COERCE = R++;
src[COERCE] = '(?:^|[^\\d])' +
              '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' +
              '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +
              '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +
              '(?:$|[^\\d])';

// Tilde ranges.
// Meaning is "reasonably at or greater than"
var LONETILDE = R++;
src[LONETILDE] = '(?:~>?)';

var TILDETRIM = R++;
src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+';
re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g');
var tildeTrimReplace = '$1~';

var TILDE = R++;
src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$';
var TILDELOOSE = R++;
src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$';

// Caret ranges.
// Meaning is "at least and backwards compatible with"
var LONECARET = R++;
src[LONECARET] = '(?:\\^)';

var CARETTRIM = R++;
src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+';
re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g');
var caretTrimReplace = '$1^';

var CARET = R++;
src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$';
var CARETLOOSE = R++;
src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$';

// A simple gt/lt/eq thing, or just "" to indicate "any version"
var COMPARATORLOOSE = R++;
src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$';
var COMPARATOR = R++;
src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$';


// An expression to strip any whitespace between the gtlt and the thing
// it modifies, so that `> 1.2.3` ==> `>1.2.3`
var COMPARATORTRIM = R++;
src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] +
                      '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')';

// this one has to use the /g flag
re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g');
var comparatorTrimReplace = '$1$2$3';


// Something like `1.2.3 - 1.2.4`
// Note that these all use the loose form, because they'll be
// checked against either the strict or loose comparator form
// later.
var HYPHENRANGE = R++;
src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' +
                   '\\s+-\\s+' +
                   '(' + src[XRANGEPLAIN] + ')' +
                   '\\s*$';

var HYPHENRANGELOOSE = R++;
src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' +
                        '\\s+-\\s+' +
                        '(' + src[XRANGEPLAINLOOSE] + ')' +
                        '\\s*$';

// Star ranges basically just allow anything at all.
var STAR = R++;
src[STAR] = '(<|>)?=?\\s*\\*';

// Compile to actual regexp objects.
// All are flag-free, unless they were created above with a flag.
for (var i = 0; i < R; i++) {
  debug(i, src[i]);
  if (!re[i])
    re[i] = new RegExp(src[i]);
}

exports.parse = parse;
function parse(version, options) {
  if (!options || typeof options !== 'object')
    options = { loose: !!options, includePrerelease: false }

  if (version instanceof SemVer)
    return version;

  if (typeof version !== 'string')
    return null;

  if (version.length > MAX_LENGTH)
    return null;

  var r = options.loose ? re[LOOSE] : re[FULL];
  if (!r.test(version))
    return null;

  try {
    return new SemVer(version, options);
  } catch (er) {
    return null;
  }
}

exports.valid = valid;
function valid(version, options) {
  var v = parse(version, options);
  return v ? v.version : null;
}


exports.clean = clean;
function clean(version, options) {
  var s = parse(version.trim().replace(/^[=v]+/, ''), options);
  return s ? s.version : null;
}

exports.SemVer = SemVer;

function SemVer(version, options) {
  if (!options || typeof options !== 'object')
    options = { loose: !!options, includePrerelease: false }
  if (version instanceof SemVer) {
    if (version.loose === options.loose)
      return version;
    else
      version = version.version;
  } else if (typeof version !== 'string') {
    throw new TypeError('Invalid Version: ' + version);
  }

  if (version.length > MAX_LENGTH)
    throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters')

  if (!(this instanceof SemVer))
    return new SemVer(version, options);

  debug('SemVer', version, options);
  this.options = options;
  this.loose = !!options.loose;

  var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]);

  if (!m)
    throw new TypeError('Invalid Version: ' + version);

  this.raw = version;

  // these are actually numbers
  this.major = +m[1];
  this.minor = +m[2];
  this.patch = +m[3];

  if (this.major > MAX_SAFE_INTEGER || this.major < 0)
    throw new TypeError('Invalid major version')

  if (this.minor > MAX_SAFE_INTEGER || this.minor < 0)
    throw new TypeError('Invalid minor version')

  if (this.patch > MAX_SAFE_INTEGER || this.patch < 0)
    throw new TypeError('Invalid patch version')

  // numberify any prerelease numeric ids
  if (!m[4])
    this.prerelease = [];
  else
    this.prerelease = m[4].split('.').map(function(id) {
      if (/^[0-9]+$/.test(id)) {
        var num = +id;
        if (num >= 0 && num < MAX_SAFE_INTEGER)
          return num;
      }
      return id;
    });

  this.build = m[5] ? m[5].split('.') : [];
  this.format();
}

SemVer.prototype.format = function() {
  this.version = this.major + '.' + this.minor + '.' + this.patch;
  if (this.prerelease.length)
    this.version += '-' + this.prerelease.join('.');
  return this.version;
};

SemVer.prototype.toString = function() {
  return this.version;
};

SemVer.prototype.compare = function(other) {
  debug('SemVer.compare', this.version, this.options, other);
  if (!(other instanceof SemVer))
    other = new SemVer(other, this.options);

  return this.compareMain(other) || this.comparePre(other);
};

SemVer.prototype.compareMain = function(other) {
  if (!(other instanceof SemVer))
    other = new SemVer(other, this.options);

  return compareIdentifiers(this.major, other.major) ||
         compareIdentifiers(this.minor, other.minor) ||
         compareIdentifiers(this.patch, other.patch);
};

SemVer.prototype.comparePre = function(other) {
  if (!(other instanceof SemVer))
    other = new SemVer(other, this.options);

  // NOT having a prerelease is > having one
  if (this.prerelease.length && !other.prerelease.length)
    return -1;
  else if (!this.prerelease.length && other.prerelease.length)
    return 1;
  else if (!this.prerelease.length && !other.prerelease.length)
    return 0;

  var i = 0;
  do {
    var a = this.prerelease[i];
    var b = other.prerelease[i];
    debug('prerelease compare', i, a, b);
    if (a === undefined && b === undefined)
      return 0;
    else if (b === undefined)
      return 1;
    else if (a === undefined)
      return -1;
    else if (a === b)
      continue;
    else
      return compareIdentifiers(a, b);
  } while (++i);
};

// preminor will bump the version up to the next minor release, and immediately
// down to pre-release. premajor and prepatch work the same way.
SemVer.prototype.inc = function(release, identifier) {
  switch (release) {
    case 'premajor':
      this.prerelease.length = 0;
      this.patch = 0;
      this.minor = 0;
      this.major++;
      this.inc('pre', identifier);
      break;
    case 'preminor':
      this.prerelease.length = 0;
      this.patch = 0;
      this.minor++;
      this.inc('pre', identifier);
      break;
    case 'prepatch':
      // If this is already a prerelease, it will bump to the next version
      // drop any prereleases that might already exist, since they are not
      // relevant at this point.
      this.prerelease.length = 0;
      this.inc('patch', identifier);
      this.inc('pre', identifier);
      break;
    // If the input is a non-prerelease version, this acts the same as
    // prepatch.
    case 'prerelease':
      if (this.prerelease.length === 0)
        this.inc('patch', identifier);
      this.inc('pre', identifier);
      break;

    case 'major':
      // If this is a pre-major version, bump up to the same major version.
      // Otherwise increment major.
      // 1.0.0-5 bumps to 1.0.0
      // 1.1.0 bumps to 2.0.0
      if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0)
        this.major++;
      this.minor = 0;
      this.patch = 0;
      this.prerelease = [];
      break;
    case 'minor':
      // If this is a pre-minor version, bump up to the same minor version.
      // Otherwise increment minor.
      // 1.2.0-5 bumps to 1.2.0
      // 1.2.1 bumps to 1.3.0
      if (this.patch !== 0 || this.prerelease.length === 0)
        this.minor++;
      this.patch = 0;
      this.prerelease = [];
      break;
    case 'patch':
      // If this is not a pre-release version, it will increment the patch.
      // If it is a pre-release it will bump up to the same patch version.
      // 1.2.0-5 patches to 1.2.0
      // 1.2.0 patches to 1.2.1
      if (this.prerelease.length === 0)
        this.patch++;
      this.prerelease = [];
      break;
    // This probably shouldn't be used publicly.
    // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
    case 'pre':
      if (this.prerelease.length === 0)
        this.prerelease = [0];
      else {
        var i = this.prerelease.length;
        while (--i >= 0) {
          if (typeof this.prerelease[i] === 'number') {
            this.prerelease[i]++;
            i = -2;
          }
        }
        if (i === -1) // didn't increment anything
          this.prerelease.push(0);
      }
      if (identifier) {
        // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
        // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
        if (this.prerelease[0] === identifier) {
          if (isNaN(this.prerelease[1]))
            this.prerelease = [identifier, 0];
        } else
          this.prerelease = [identifier, 0];
      }
      break;

    default:
      throw new Error('invalid increment argument: ' + release);
  }
  this.format();
  this.raw = this.version;
  return this;
};

exports.inc = inc;
function inc(version, release, loose, identifier) {
  if (typeof(loose) === 'string') {
    identifier = loose;
    loose = undefined;
  }

  try {
    return new SemVer(version, loose).inc(release, identifier).version;
  } catch (er) {
    return null;
  }
}

exports.diff = diff;
function diff(version1, version2) {
  if (eq(version1, version2)) {
    return null;
  } else {
    var v1 = parse(version1);
    var v2 = parse(version2);
    if (v1.prerelease.length || v2.prerelease.length) {
      for (var key in v1) {
        if (key === 'major' || key === 'minor' || key === 'patch') {
          if (v1[key] !== v2[key]) {
            return 'pre'+key;
          }
        }
      }
      return 'prerelease';
    }
    for (var key in v1) {
      if (key === 'major' || key === 'minor' || key === 'patch') {
        if (v1[key] !== v2[key]) {
          return key;
        }
      }
    }
  }
}

exports.compareIdentifiers = compareIdentifiers;

var numeric = /^[0-9]+$/;
function compareIdentifiers(a, b) {
  var anum = numeric.test(a);
  var bnum = numeric.test(b);

  if (anum && bnum) {
    a = +a;
    b = +b;
  }

  return (anum && !bnum) ? -1 :
         (bnum && !anum) ? 1 :
         a < b ? -1 :
         a > b ? 1 :
         0;
}

exports.rcompareIdentifiers = rcompareIdentifiers;
function rcompareIdentifiers(a, b) {
  return compareIdentifiers(b, a);
}

exports.major = major;
function major(a, loose) {
  return new SemVer(a, loose).major;
}

exports.minor = minor;
function minor(a, loose) {
  return new SemVer(a, loose).minor;
}

exports.patch = patch;
function patch(a, loose) {
  return new SemVer(a, loose).patch;
}

exports.compare = compare;
function compare(a, b, loose) {
  return new SemVer(a, loose).compare(new SemVer(b, loose));
}

exports.compareLoose = compareLoose;
function compareLoose(a, b) {
  return compare(a, b, true);
}

exports.rcompare = rcompare;
function rcompare(a, b, loose) {
  return compare(b, a, loose);
}

exports.sort = sort;
function sort(list, loose) {
  return list.sort(function(a, b) {
    return exports.compare(a, b, loose);
  });
}

exports.rsort = rsort;
function rsort(list, loose) {
  return list.sort(function(a, b) {
    return exports.rcompare(a, b, loose);
  });
}

exports.gt = gt;
function gt(a, b, loose) {
  return compare(a, b, loose) > 0;
}

exports.lt = lt;
function lt(a, b, loose) {
  return compare(a, b, loose) < 0;
}

exports.eq = eq;
function eq(a, b, loose) {
  return compare(a, b, loose) === 0;
}

exports.neq = neq;
function neq(a, b, loose) {
  return compare(a, b, loose) !== 0;
}

exports.gte = gte;
function gte(a, b, loose) {
  return compare(a, b, loose) >= 0;
}

exports.lte = lte;
function lte(a, b, loose) {
  return compare(a, b, loose) <= 0;
}

exports.cmp = cmp;
function cmp(a, op, b, loose) {
  var ret;
  switch (op) {
    case '===':
      if (typeof a === 'object') a = a.version;
      if (typeof b === 'object') b = b.version;
      ret = a === b;
      break;
    case '!==':
      if (typeof a === 'object') a = a.version;
      if (typeof b === 'object') b = b.version;
      ret = a !== b;
      break;
    case '': case '=': case '==': ret = eq(a, b, loose); break;
    case '!=': ret = neq(a, b, loose); break;
    case '>': ret = gt(a, b, loose); break;
    case '>=': ret = gte(a, b, loose); break;
    case '<': ret = lt(a, b, loose); break;
    case '<=': ret = lte(a, b, loose); break;
    default: throw new TypeError('Invalid operator: ' + op);
  }
  return ret;
}

exports.Comparator = Comparator;
function Comparator(comp, options) {
  if (!options || typeof options !== 'object')
    options = { loose: !!options, includePrerelease: false }

  if (comp instanceof Comparator) {
    if (comp.loose === !!options.loose)
      return comp;
    else
      comp = comp.value;
  }

  if (!(this instanceof Comparator))
    return new Comparator(comp, options);

  debug('comparator', comp, options);
  this.options = options;
  this.loose = !!options.loose;
  this.parse(comp);

  if (this.semver === ANY)
    this.value = '';
  else
    this.value = this.operator + this.semver.version;

  debug('comp', this);
}

var ANY = {};
Comparator.prototype.parse = function(comp) {
  var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
  var m = comp.match(r);

  if (!m)
    throw new TypeError('Invalid comparator: ' + comp);

  this.operator = m[1];
  if (this.operator === '=')
    this.operator = '';

  // if it literally is just '>' or '' then allow anything.
  if (!m[2])
    this.semver = ANY;
  else
    this.semver = new SemVer(m[2], this.options.loose);
};

Comparator.prototype.toString = function() {
  return this.value;
};

Comparator.prototype.test = function(version) {
  debug('Comparator.test', version, this.options.loose);

  if (this.semver === ANY)
    return true;

  if (typeof version === 'string')
    version = new SemVer(version, this.options);

  return cmp(version, this.operator, this.semver, this.options);
};

Comparator.prototype.intersects = function(comp, options) {
  if (!(comp instanceof Comparator)) {
    throw new TypeError('a Comparator is required');
  }

  if (!options || typeof options !== 'object')
    options = { loose: !!options, includePrerelease: false }

  var rangeTmp;

  if (this.operator === '') {
    rangeTmp = new Range(comp.value, options);
    return satisfies(this.value, rangeTmp, options);
  } else if (comp.operator === '') {
    rangeTmp = new Range(this.value, options);
    return satisfies(comp.semver, rangeTmp, options);
  }

  var sameDirectionIncreasing =
    (this.operator === '>=' || this.operator === '>') &&
    (comp.operator === '>=' || comp.operator === '>');
  var sameDirectionDecreasing =
    (this.operator === '<=' || this.operator === '<') &&
    (comp.operator === '<=' || comp.operator === '<');
  var sameSemVer = this.semver.version === comp.semver.version;
  var differentDirectionsInclusive =
    (this.operator === '>=' || this.operator === '<=') &&
    (comp.operator === '>=' || comp.operator === '<=');
  var oppositeDirectionsLessThan =
    cmp(this.semver, '<', comp.semver, options) &&
    ((this.operator === '>=' || this.operator === '>') &&
    (comp.operator === '<=' || comp.operator === '<'));
  var oppositeDirectionsGreaterThan =
    cmp(this.semver, '>', comp.semver, options) &&
    ((this.operator === '<=' || this.operator === '<') &&
    (comp.operator === '>=' || comp.operator === '>'));

  return sameDirectionIncreasing || sameDirectionDecreasing ||
    (sameSemVer && differentDirectionsInclusive) ||
    oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;
};


exports.Range = Range;
function Range(range, options) {
  if (!options || typeof options !== 'object')
    options = { loose: !!options, includePrerelease: false }

  if (range instanceof Range) {
    if (range.loose === !!options.loose &&
        range.includePrerelease === !!options.includePrerelease) {
      return range;
    } else {
      return new Range(range.raw, options);
    }
  }

  if (range instanceof Comparator) {
    return new Range(range.value, options);
  }

  if (!(this instanceof Range))
    return new Range(range, options);

  this.options = options;
  this.loose = !!options.loose;
  this.includePrerelease = !!options.includePrerelease

  // First, split based on boolean or ||
  this.raw = range;
  this.set = range.split(/\s*\|\|\s*/).map(function(range) {
    return this.parseRange(range.trim());
  }, this).filter(function(c) {
    // throw out any that are not relevant for whatever reason
    return c.length;
  });

  if (!this.set.length) {
    throw new TypeError('Invalid SemVer Range: ' + range);
  }

  this.format();
}

Range.prototype.format = function() {
  this.range = this.set.map(function(comps) {
    return comps.join(' ').trim();
  }).join('||').trim();
  return this.range;
};

Range.prototype.toString = function() {
  return this.range;
};

Range.prototype.parseRange = function(range) {
  var loose = this.options.loose;
  range = range.trim();
  // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
  var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE];
  range = range.replace(hr, hyphenReplace);
  debug('hyphen replace', range);
  // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
  range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace);
  debug('comparator trim', range, re[COMPARATORTRIM]);

  // `~ 1.2.3` => `~1.2.3`
  range = range.replace(re[TILDETRIM], tildeTrimReplace);

  // `^ 1.2.3` => `^1.2.3`
  range = range.replace(re[CARETTRIM], caretTrimReplace);

  // normalize spaces
  range = range.split(/\s+/).join(' ');

  // At this point, the range is completely trimmed and
  // ready to be split into comparators.

  var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
  var set = range.split(' ').map(function(comp) {
    return parseComparator(comp, this.options);
  }, this).join(' ').split(/\s+/);
  if (this.options.loose) {
    // in loose mode, throw out any that are not valid comparators
    set = set.filter(function(comp) {
      return !!comp.match(compRe);
    });
  }
  set = set.map(function(comp) {
    return new Comparator(comp, this.options);
  }, this);

  return set;
};

Range.prototype.intersects = function(range, options) {
  if (!(range instanceof Range)) {
    throw new TypeError('a Range is required');
  }

  return this.set.some(function(thisComparators) {
    return thisComparators.every(function(thisComparator) {
      return range.set.some(function(rangeComparators) {
        return rangeComparators.every(function(rangeComparator) {
          return thisComparator.intersects(rangeComparator, options);
        });
      });
    });
  });
};

// Mostly just for testing and legacy API reasons
exports.toComparators = toComparators;
function toComparators(range, options) {
  return new Range(range, options).set.map(function(comp) {
    return comp.map(function(c) {
      return c.value;
    }).join(' ').trim().split(' ');
  });
}

// comprised of xranges, tildes, stars, and gtlt's at this point.
// already replaced the hyphen ranges
// turn into a set of JUST comparators.
function parseComparator(comp, options) {
  debug('comp', comp, options);
  comp = replaceCarets(comp, options);
  debug('caret', comp);
  comp = replaceTildes(comp, options);
  debug('tildes', comp);
  comp = replaceXRanges(comp, options);
  debug('xrange', comp);
  comp = replaceStars(comp, options);
  debug('stars', comp);
  return comp;
}

function isX(id) {
  return !id || id.toLowerCase() === 'x' || id === '*';
}

// ~, ~> --> * (any, kinda silly)
// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0
// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0
// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0
// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0
// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0
function replaceTildes(comp, options) {
  return comp.trim().split(/\s+/).map(function(comp) {
    return replaceTilde(comp, options);
  }).join(' ');
}

function replaceTilde(comp, options) {
  if (!options || typeof options !== 'object')
    options = { loose: !!options, includePrerelease: false }
  var r = options.loose ? re[TILDELOOSE] : re[TILDE];
  return comp.replace(r, function(_, M, m, p, pr) {
    debug('tilde', comp, _, M, m, p, pr);
    var ret;

    if (isX(M))
      ret = '';
    else if (isX(m))
      ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
    else if (isX(p))
      // ~1.2 == >=1.2.0 <1.3.0
      ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
    else if (pr) {
      debug('replaceTilde pr', pr);
      if (pr.charAt(0) !== '-')
        pr = '-' + pr;
      ret = '>=' + M + '.' + m + '.' + p + pr +
            ' <' + M + '.' + (+m + 1) + '.0';
    } else
      // ~1.2.3 == >=1.2.3 <1.3.0
      ret = '>=' + M + '.' + m + '.' + p +
            ' <' + M + '.' + (+m + 1) + '.0';

    debug('tilde return', ret);
    return ret;
  });
}

// ^ --> * (any, kinda silly)
// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0
// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0
// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0
// ^1.2.3 --> >=1.2.3 <2.0.0
// ^1.2.0 --> >=1.2.0 <2.0.0
function replaceCarets(comp, options) {
  return comp.trim().split(/\s+/).map(function(comp) {
    return replaceCaret(comp, options);
  }).join(' ');
}

function replaceCaret(comp, options) {
  debug('caret', comp, options);
  if (!options || typeof options !== 'object')
    options = { loose: !!options, includePrerelease: false }
  var r = options.loose ? re[CARETLOOSE] : re[CARET];
  return comp.replace(r, function(_, M, m, p, pr) {
    debug('caret', comp, _, M, m, p, pr);
    var ret;

    if (isX(M))
      ret = '';
    else if (isX(m))
      ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
    else if (isX(p)) {
      if (M === '0')
        ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
      else
        ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0';
    } else if (pr) {
      debug('replaceCaret pr', pr);
      if (pr.charAt(0) !== '-')
        pr = '-' + pr;
      if (M === '0') {
        if (m === '0')
          ret = '>=' + M + '.' + m + '.' + p + pr +
                ' <' + M + '.' + m + '.' + (+p + 1);
        else
          ret = '>=' + M + '.' + m + '.' + p + pr +
                ' <' + M + '.' + (+m + 1) + '.0';
      } else
        ret = '>=' + M + '.' + m + '.' + p + pr +
              ' <' + (+M + 1) + '.0.0';
    } else {
      debug('no pr');
      if (M === '0') {
        if (m === '0')
          ret = '>=' + M + '.' + m + '.' + p +
                ' <' + M + '.' + m + '.' + (+p + 1);
        else
          ret = '>=' + M + '.' + m + '.' + p +
                ' <' + M + '.' + (+m + 1) + '.0';
      } else
        ret = '>=' + M + '.' + m + '.' + p +
              ' <' + (+M + 1) + '.0.0';
    }

    debug('caret return', ret);
    return ret;
  });
}

function replaceXRanges(comp, options) {
  debug('replaceXRanges', comp, options);
  return comp.split(/\s+/).map(function(comp) {
    return replaceXRange(comp, options);
  }).join(' ');
}

function replaceXRange(comp, options) {
  comp = comp.trim();
  if (!options || typeof options !== 'object')
    options = { loose: !!options, includePrerelease: false }
  var r = options.loose ? re[XRANGELOOSE] : re[XRANGE];
  return comp.replace(r, function(ret, gtlt, M, m, p, pr) {
    debug('xRange', comp, ret, gtlt, M, m, p, pr);
    var xM = isX(M);
    var xm = xM || isX(m);
    var xp = xm || isX(p);
    var anyX = xp;

    if (gtlt === '=' && anyX)
      gtlt = '';

    if (xM) {
      if (gtlt === '>' || gtlt === '<') {
        // nothing is allowed
        ret = '<0.0.0';
      } else {
        // nothing is forbidden
        ret = '*';
      }
    } else if (gtlt && anyX) {
      // replace X with 0
      if (xm)
        m = 0;
      if (xp)
        p = 0;

      if (gtlt === '>') {
        // >1 => >=2.0.0
        // >1.2 => >=1.3.0
        // >1.2.3 => >= 1.2.4
        gtlt = '>=';
        if (xm) {
          M = +M + 1;
          m = 0;
          p = 0;
        } else if (xp) {
          m = +m + 1;
          p = 0;
        }
      } else if (gtlt === '<=') {
        // <=0.7.x is actually <0.8.0, since any 0.7.x should
        // pass.  Similarly, <=7.x is actually <8.0.0, etc.
        gtlt = '<';
        if (xm)
          M = +M + 1;
        else
          m = +m + 1;
      }

      ret = gtlt + M + '.' + m + '.' + p;
    } else if (xm) {
      ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
    } else if (xp) {
      ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
    }

    debug('xRange return', ret);

    return ret;
  });
}

// Because * is AND-ed with everything else in the comparator,
// and '' means "any version", just remove the *s entirely.
function replaceStars(comp, options) {
  debug('replaceStars', comp, options);
  // Looseness is ignored here.  star is always as loose as it gets!
  return comp.trim().replace(re[STAR], '');
}

// This function is passed to string.replace(re[HYPHENRANGE])
// M, m, patch, prerelease, build
// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do
// 1.2 - 3.4 => >=1.2.0 <3.5.0
function hyphenReplace($0,
                       from, fM, fm, fp, fpr, fb,
                       to, tM, tm, tp, tpr, tb) {

  if (isX(fM))
    from = '';
  else if (isX(fm))
    from = '>=' + fM + '.0.0';
  else if (isX(fp))
    from = '>=' + fM + '.' + fm + '.0';
  else
    from = '>=' + from;

  if (isX(tM))
    to = '';
  else if (isX(tm))
    to = '<' + (+tM + 1) + '.0.0';
  else if (isX(tp))
    to = '<' + tM + '.' + (+tm + 1) + '.0';
  else if (tpr)
    to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr;
  else
    to = '<=' + to;

  return (from + ' ' + to).trim();
}


// if ANY of the sets match ALL of its comparators, then pass
Range.prototype.test = function(version) {
  if (!version)
    return false;

  if (typeof version === 'string')
    version = new SemVer(version, this.options);

  for (var i = 0; i < this.set.length; i++) {
    if (testSet(this.set[i], version, this.options))
      return true;
  }
  return false;
};

function testSet(set, version, options) {
  for (var i = 0; i < set.length; i++) {
    if (!set[i].test(version))
      return false;
  }

  if (!options)
    options = {}

  if (version.prerelease.length && !options.includePrerelease) {
    // Find the set of versions that are allowed to have prereleases
    // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
    // That should allow `1.2.3-pr.2` to pass.
    // However, `1.2.4-alpha.notready` should NOT be allowed,
    // even though it's within the range set by the comparators.
    for (var i = 0; i < set.length; i++) {
      debug(set[i].semver);
      if (set[i].semver === ANY)
        continue;

      if (set[i].semver.prerelease.length > 0) {
        var allowed = set[i].semver;
        if (allowed.major === version.major &&
            allowed.minor === version.minor &&
            allowed.patch === version.patch)
          return true;
      }
    }

    // Version has a -pre, but it's not one of the ones we like.
    return false;
  }

  return true;
}

exports.satisfies = satisfies;
function satisfies(version, range, options) {
  try {
    range = new Range(range, options);
  } catch (er) {
    return false;
  }
  return range.test(version);
}

exports.maxSatisfying = maxSatisfying;
function maxSatisfying(versions, range, options) {
  var max = null;
  var maxSV = null;
  try {
    var rangeObj = new Range(range, options);
  } catch (er) {
    return null;
  }
  versions.forEach(function (v) {
    if (rangeObj.test(v)) { // satisfies(v, range, options)
      if (!max || maxSV.compare(v) === -1) { // compare(max, v, true)
        max = v;
        maxSV = new SemVer(max, options);
      }
    }
  })
  return max;
}

exports.minSatisfying = minSatisfying;
function minSatisfying(versions, range, options) {
  var min = null;
  var minSV = null;
  try {
    var rangeObj = new Range(range, options);
  } catch (er) {
    return null;
  }
  versions.forEach(function (v) {
    if (rangeObj.test(v)) { // satisfies(v, range, options)
      if (!min || minSV.compare(v) === 1) { // compare(min, v, true)
        min = v;
        minSV = new SemVer(min, options);
      }
    }
  })
  return min;
}

exports.validRange = validRange;
function validRange(range, options) {
  try {
    // Return '*' instead of '' so that truthiness works.
    // This will throw if it's invalid anyway
    return new Range(range, options).range || '*';
  } catch (er) {
    return null;
  }
}

// Determine if version is less than all the versions possible in the range
exports.ltr = ltr;
function ltr(version, range, options) {
  return outside(version, range, '<', options);
}

// Determine if version is greater than all the versions possible in the range.
exports.gtr = gtr;
function gtr(version, range, options) {
  return outside(version, range, '>', options);
}

exports.outside = outside;
function outside(version, range, hilo, options) {
  version = new SemVer(version, options);
  range = new Range(range, options);

  var gtfn, ltefn, ltfn, comp, ecomp;
  switch (hilo) {
    case '>':
      gtfn = gt;
      ltefn = lte;
      ltfn = lt;
      comp = '>';
      ecomp = '>=';
      break;
    case '<':
      gtfn = lt;
      ltefn = gte;
      ltfn = gt;
      comp = '<';
      ecomp = '<=';
      break;
    default:
      throw new TypeError('Must provide a hilo val of "<" or ">"');
  }

  // If it satisifes the range it is not outside
  if (satisfies(version, range, options)) {
    return false;
  }

  // From now on, variable terms are as if we're in "gtr" mode.
  // but note that everything is flipped for the "ltr" function.

  for (var i = 0; i < range.set.length; ++i) {
    var comparators = range.set[i];

    var high = null;
    var low = null;

    comparators.forEach(function(comparator) {
      if (comparator.semver === ANY) {
        comparator = new Comparator('>=0.0.0')
      }
      high = high || comparator;
      low = low || comparator;
      if (gtfn(comparator.semver, high.semver, options)) {
        high = comparator;
      } else if (ltfn(comparator.semver, low.semver, options)) {
        low = comparator;
      }
    });

    // If the edge version comparator has a operator then our version
    // isn't outside it
    if (high.operator === comp || high.operator === ecomp) {
      return false;
    }

    // If the lowest version comparator has an operator and our version
    // is less than it then it isn't higher than the range
    if ((!low.operator || low.operator === comp) &&
        ltefn(version, low.semver)) {
      return false;
    } else if (low.operator === ecomp && ltfn(version, low.semver)) {
      return false;
    }
  }
  return true;
}

exports.prerelease = prerelease;
function prerelease(version, options) {
  var parsed = parse(version, options);
  return (parsed && parsed.prerelease.length) ? parsed.prerelease : null;
}

exports.intersects = intersects;
function intersects(r1, r2, options) {
  r1 = new Range(r1, options)
  r2 = new Range(r2, options)
  return r1.intersects(r2)
}

exports.coerce = coerce;
function coerce(version) {
  if (version instanceof SemVer)
    return version;

  if (typeof version !== 'string')
    return null;

  var match = version.match(re[COERCE]);

  if (match == null)
    return null;

  return parse((match[1] || '0') + '.' + (match[2] || '0') + '.' + (match[3] || '0')); 
}

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../process/browser.js */ "8oxB")))

/***/ }),

/***/ "jWoU":
/*!********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/NotebookIpIcon.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var NotebookIpIcon = function NotebookIpIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M27.625 32H5.812a.722.722 0 0 1-.75-.75V.75c0-.438.313-.75.75-.75h21.813c.438 0 .75.313.75.75v30.5c0 .438-.313.75-.75.75zM6.563 30.563h20.375V1.438H6.563zm.687-24.75H4.375c-.438 0-.75-.313-.75-.75s.313-.688.75-.688H7.25c.438 0 .75.25.75.688s-.313.75-.75.75zm0 4.375H4.375c-.438 0-.75-.313-.75-.75s.313-.688.75-.688H7.25c.438 0 .75.25.75.688s-.313.75-.75.75zm0 4.375H4.375c-.438 0-.75-.313-.75-.75s.313-.75.75-.75H7.25c.438 0 .75.313.75.75s-.313.75-.75.75zm0 4.375H4.375c-.438 0-.75-.313-.75-.75s.313-.75.75-.75H7.25c.438 0 .75.313.75.75s-.313.75-.75.75zm0 4.312H4.375c-.438 0-.75-.25-.75-.688s.313-.75.75-.75H7.25c.438 0 .75.313.75.75s-.313.688-.75.688zm0 4.375H4.375c-.438 0-.75-.25-.75-.688s.313-.75.75-.75H7.25c.438 0 .75.313.75.75s-.313.688-.75.688zM21.813 10.75c-2-.125-3.75 0-3.75 0v10.5h1.313v-4.063h2.438c2.063-.188 2.75-2.063 2.75-3.25 0-1.313-.688-3-2.75-3.188zm-.313 5.375h-2.125v-4.188H21.5c.625 0 1.625.563 1.625 2 0 1.5-1 2.188-1.625 2.188zm-5.062-4.5v-.875h-5.5v.875h2v8.75h-2v1h5.5v-1h-2.063v-8.75z' })
    );
};

exports.default = NotebookIpIcon;

/***/ }),

/***/ "jWph":
/*!******************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/ForkEditIcon.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var ForkEditIcon = function ForkEditIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M22 6c-2.188 0-4 1.813-4 4 0 1.5.813 2.75 2 3.438v.563c0 2-2 4-4 4-1.625 0-2.938.375-4 .938v-9.5c1.188-.688 2-1.938 2-3.438 0-2.188-1.75-4-4-4-2.188 0-4 1.813-4 4 0 1.5.813 2.75 2 3.438v13.125c-1.188.688-2 1.938-2 3.438 0 2.188 1.813 4 4 4 2.25 0 4-1.813 4-4 0-1.063-.375-2-1.063-2.75.625-.688 1.563-1.25 3.063-1.25 4 0 8-4 8-8v-.563c1.188-.688 2-2 2-3.438 0-2.25-1.75-4-4-4zM10 4c1.125 0 2 .938 2 2 0 1.125-.875 2-2 2-1.063 0-2-.875-2-2 0-1.063.938-2 2-2zm0 24c-1.063 0-2-.875-2-2 0-1.063.938-2 2-2 1.125 0 2 .938 2 2 0 1.125-.875 2-2 2zm12-16c-1.063 0-2-.875-2-2 0-1.063.938-2 2-2 1.125 0 2 .938 2 2 0 1.125-.875 2-2 2z' })
    );
};

exports.default = ForkEditIcon;

/***/ }),

/***/ "japM":
/*!*************************************************************!*\
  !*** ./node_modules/react-color/lib/helpers/interaction.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.handleFocus = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint-disable no-invalid-this */


var handleFocus = exports.handleFocus = function handleFocus(Component) {
  var Span = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'span';
  return function (_React$Component) {
    _inherits(Focus, _React$Component);

    function Focus() {
      var _ref;

      var _temp, _this, _ret;

      _classCallCheck(this, Focus);

      for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Focus.__proto__ || Object.getPrototypeOf(Focus)).call.apply(_ref, [this].concat(args))), _this), _this.state = { focus: false }, _this.handleFocus = function () {
        return _this.setState({ focus: true });
      }, _this.handleBlur = function () {
        return _this.setState({ focus: false });
      }, _temp), _possibleConstructorReturn(_this, _ret);
    }

    _createClass(Focus, [{
      key: 'render',
      value: function render() {
        return _react2.default.createElement(
          Span,
          { onFocus: this.handleFocus, onBlur: this.handleBlur },
          _react2.default.createElement(Component, _extends({}, this.props, this.state))
        );
      }
    }]);

    return Focus;
  }(_react2.default.Component);
};

/***/ }),

/***/ "jb+b":
/*!********************************************************!*\
  !*** ./node_modules/react-base16-styling/lib/index.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getBase16Theme = exports.createStyling = exports.invertTheme = undefined;

var _typeof2 = __webpack_require__(/*! babel-runtime/helpers/typeof */ "EJiy");

var _typeof3 = _interopRequireDefault(_typeof2);

var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "QbLZ");

var _extends3 = _interopRequireDefault(_extends2);

var _slicedToArray2 = __webpack_require__(/*! babel-runtime/helpers/slicedToArray */ "sk9p");

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _keys = __webpack_require__(/*! babel-runtime/core-js/object/keys */ "GQeE");

var _keys2 = _interopRequireDefault(_keys);

var _lodash = __webpack_require__(/*! lodash.curry */ "FdJ0");

var _lodash2 = _interopRequireDefault(_lodash);

var _base = __webpack_require__(/*! base16 */ "Ihzh");

var base16 = _interopRequireWildcard(_base);

var _rgb2hex = __webpack_require__(/*! pure-color/convert/rgb2hex */ "G7cy");

var _rgb2hex2 = _interopRequireDefault(_rgb2hex);

var _parse = __webpack_require__(/*! pure-color/parse */ "DtRd");

var _parse2 = _interopRequireDefault(_parse);

var _lodash3 = __webpack_require__(/*! lodash.flow */ "R1z+");

var _lodash4 = _interopRequireDefault(_lodash3);

var _colorConverters = __webpack_require__(/*! ./colorConverters */ "s6NM");

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var DEFAULT_BASE16 = base16.default;

var BASE16_KEYS = (0, _keys2.default)(DEFAULT_BASE16);

// we need a correcting factor, so that a dark, but not black background color
// converts to bright enough inversed color
var flip = function flip(x) {
  return x < 0.25 ? 1 : x < 0.5 ? 0.9 - x : 1.1 - x;
};

var invertColor = (0, _lodash4.default)(_parse2.default, _colorConverters.rgb2yuv, function (_ref) {
  var _ref2 = (0, _slicedToArray3.default)(_ref, 3),
      y = _ref2[0],
      u = _ref2[1],
      v = _ref2[2];

  return [flip(y), u, v];
}, _colorConverters.yuv2rgb, _rgb2hex2.default);

var merger = function merger(styling) {
  return function (prevStyling) {
    return {
      className: [prevStyling.className, styling.className].filter(Boolean).join(' '),
      style: (0, _extends3.default)({}, prevStyling.style || {}, styling.style || {})
    };
  };
};

var mergeStyling = function mergeStyling(customStyling, defaultStyling) {
  if (customStyling === undefined) {
    return defaultStyling;
  }
  if (defaultStyling === undefined) {
    return customStyling;
  }

  var customType = typeof customStyling === 'undefined' ? 'undefined' : (0, _typeof3.default)(customStyling);
  var defaultType = typeof defaultStyling === 'undefined' ? 'undefined' : (0, _typeof3.default)(defaultStyling);

  switch (customType) {
    case 'string':
      switch (defaultType) {
        case 'string':
          return [defaultStyling, customStyling].filter(Boolean).join(' ');
        case 'object':
          return merger({ className: customStyling, style: defaultStyling });
        case 'function':
          return function (styling) {
            for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
              args[_key - 1] = arguments[_key];
            }

            return merger({
              className: customStyling
            })(defaultStyling.apply(undefined, [styling].concat(args)));
          };
      }
    case 'object':
      switch (defaultType) {
        case 'string':
          return merger({ className: defaultStyling, style: customStyling });
        case 'object':
          return (0, _extends3.default)({}, defaultStyling, customStyling);
        case 'function':
          return function (styling) {
            for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
              args[_key2 - 1] = arguments[_key2];
            }

            return merger({
              style: customStyling
            })(defaultStyling.apply(undefined, [styling].concat(args)));
          };
      }
    case 'function':
      switch (defaultType) {
        case 'string':
          return function (styling) {
            for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
              args[_key3 - 1] = arguments[_key3];
            }

            return customStyling.apply(undefined, [merger(styling)({
              className: defaultStyling
            })].concat(args));
          };
        case 'object':
          return function (styling) {
            for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
              args[_key4 - 1] = arguments[_key4];
            }

            return customStyling.apply(undefined, [merger(styling)({
              style: defaultStyling
            })].concat(args));
          };
        case 'function':
          return function (styling) {
            for (var _len5 = arguments.length, args = Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
              args[_key5 - 1] = arguments[_key5];
            }

            return customStyling.apply(undefined, [defaultStyling.apply(undefined, [styling].concat(args))].concat(args));
          };
      }
  }
};

var mergeStylings = function mergeStylings(customStylings, defaultStylings) {
  var keys = (0, _keys2.default)(defaultStylings);
  for (var key in customStylings) {
    if (keys.indexOf(key) === -1) keys.push(key);
  }

  return keys.reduce(function (mergedStyling, key) {
    return mergedStyling[key] = mergeStyling(customStylings[key], defaultStylings[key]), mergedStyling;
  }, {});
};

var getStylingByKeys = function getStylingByKeys(mergedStyling, keys) {
  for (var _len6 = arguments.length, args = Array(_len6 > 2 ? _len6 - 2 : 0), _key6 = 2; _key6 < _len6; _key6++) {
    args[_key6 - 2] = arguments[_key6];
  }

  if (keys === null) {
    return mergedStyling;
  }

  if (!Array.isArray(keys)) {
    keys = [keys];
  }

  var styles = keys.map(function (key) {
    return mergedStyling[key];
  }).filter(Boolean);

  var props = styles.reduce(function (obj, s) {
    if (typeof s === 'string') {
      obj.className = [obj.className, s].filter(Boolean).join(' ');
    } else if ((typeof s === 'undefined' ? 'undefined' : (0, _typeof3.default)(s)) === 'object') {
      obj.style = (0, _extends3.default)({}, obj.style, s);
    } else if (typeof s === 'function') {
      obj = (0, _extends3.default)({}, obj, s.apply(undefined, [obj].concat(args)));
    }

    return obj;
  }, { className: '', style: {} });

  if (!props.className) {
    delete props.className;
  }

  if ((0, _keys2.default)(props.style).length === 0) {
    delete props.style;
  }

  return props;
};

var invertTheme = exports.invertTheme = function invertTheme(theme) {
  return (0, _keys2.default)(theme).reduce(function (t, key) {
    return t[key] = /^base/.test(key) ? invertColor(theme[key]) : key === 'scheme' ? theme[key] + ':inverted' : theme[key], t;
  }, {});
};

var createStyling = exports.createStyling = (0, _lodash2.default)(function (getStylingFromBase16) {
  for (var _len7 = arguments.length, args = Array(_len7 > 3 ? _len7 - 3 : 0), _key7 = 3; _key7 < _len7; _key7++) {
    args[_key7 - 3] = arguments[_key7];
  }

  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var themeOrStyling = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var _options$defaultBase = options.defaultBase16,
      defaultBase16 = _options$defaultBase === undefined ? DEFAULT_BASE16 : _options$defaultBase,
      _options$base16Themes = options.base16Themes,
      base16Themes = _options$base16Themes === undefined ? null : _options$base16Themes;


  var base16Theme = getBase16Theme(themeOrStyling, base16Themes);
  if (base16Theme) {
    themeOrStyling = (0, _extends3.default)({}, base16Theme, themeOrStyling);
  }

  var theme = BASE16_KEYS.reduce(function (t, key) {
    return t[key] = themeOrStyling[key] || defaultBase16[key], t;
  }, {});

  var customStyling = (0, _keys2.default)(themeOrStyling).reduce(function (s, key) {
    return BASE16_KEYS.indexOf(key) === -1 ? (s[key] = themeOrStyling[key], s) : s;
  }, {});

  var defaultStyling = getStylingFromBase16(theme);

  var mergedStyling = mergeStylings(customStyling, defaultStyling);

  return (0, _lodash2.default)(getStylingByKeys, 2).apply(undefined, [mergedStyling].concat(args));
}, 3);

var getBase16Theme = exports.getBase16Theme = function getBase16Theme(theme, base16Themes) {
  if (theme && theme.extend) {
    theme = theme.extend;
  }

  if (typeof theme === 'string') {
    var _theme$split = theme.split(':'),
        _theme$split2 = (0, _slicedToArray3.default)(_theme$split, 2),
        themeName = _theme$split2[0],
        modifier = _theme$split2[1];

    theme = (base16Themes || {})[themeName] || base16[themeName];
    if (modifier === 'inverted') {
      theme = invertTheme(theme);
    }
  }

  return theme && theme.hasOwnProperty('base00') ? theme : undefined;
};

/***/ }),

/***/ "jb54":
/*!**************************************************************!*\
  !*** ./node_modules/draft-js-utils/lib/getSelectedBlocks.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

/**
 * Returns an array of all `ContentBlock` instances within two block keys
 *
 * @param  {object} contentState A draft.js `ContentState` instance
 * @param  {string} anchorKey    The block key to start searching from
 * @param  {string} focusKey     The block key until which to search
 *
 * @return {array} An array containing the found content blocks
 */
exports.default = function (contentState, anchorKey, focusKey) {
  var isSameBlock = anchorKey === focusKey;
  var startingBlock = contentState.getBlockForKey(anchorKey);

  if (!startingBlock) {
    return [];
  }

  var selectedBlocks = [startingBlock];

  if (!isSameBlock) {
    var blockKey = anchorKey;

    while (blockKey !== focusKey) {
      var nextBlock = contentState.getBlockAfter(blockKey);

      if (!nextBlock) {
        selectedBlocks = [];
        break;
      }

      selectedBlocks.push(nextBlock);
      blockKey = nextBlock.getKey();
    }
  }

  return selectedBlocks;
};

/***/ }),

/***/ "jdEz":
/*!******************************************************************!*\
  !*** ./node_modules/@jupyterlab/notebook/lib/default-toolbar.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const actions_1 = __webpack_require__(/*! ./actions */ "qhsb");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
/**
 * The class name added to toolbar save button.
 */
const TOOLBAR_SAVE_CLASS = 'jp-SaveIcon';
/**
 * The class name added to toolbar insert button.
 */
const TOOLBAR_INSERT_CLASS = 'jp-AddIcon';
/**
 * The class name added to toolbar cut button.
 */
const TOOLBAR_CUT_CLASS = 'jp-CutIcon';
/**
 * The class name added to toolbar copy button.
 */
const TOOLBAR_COPY_CLASS = 'jp-CopyIcon';
/**
 * The class name added to toolbar paste button.
 */
const TOOLBAR_PASTE_CLASS = 'jp-PasteIcon';
/**
 * The class name added to toolbar run button.
 */
const TOOLBAR_RUN_CLASS = 'jp-RunIcon';
/**
 * The class name added to toolbar cell type dropdown wrapper.
 */
const TOOLBAR_CELLTYPE_CLASS = 'jp-Notebook-toolbarCellType';
/**
 * The class name added to toolbar cell type dropdown.
 */
const TOOLBAR_CELLTYPE_DROPDOWN_CLASS = 'jp-Notebook-toolbarCellTypeDropdown';
/**
 * A namespace for the default toolbar items.
 */
var ToolbarItems;
(function (ToolbarItems) {
    /**
     * Create save button toolbar item.
     */
    function createSaveButton(panel) {
        return new apputils_1.ToolbarButton({
            iconClassName: TOOLBAR_SAVE_CLASS + ' foo jp-Icon jp-Icon-16',
            onClick: () => {
                if (panel.context.model.readOnly) {
                    return apputils_1.showDialog({
                        title: 'Cannot Save',
                        body: 'Document is read-only',
                        buttons: [apputils_1.Dialog.okButton()]
                    });
                }
                panel.context.save().then(() => {
                    if (!panel.isDisposed) {
                        return panel.context.createCheckpoint();
                    }
                });
            },
            tooltip: 'Save the notebook contents and create checkpoint'
        });
    }
    ToolbarItems.createSaveButton = createSaveButton;
    /**
     * Create an insert toolbar item.
     */
    function createInsertButton(panel) {
        return new apputils_1.ToolbarButton({
            iconClassName: TOOLBAR_INSERT_CLASS + ' jp-Icon jp-Icon-16',
            onClick: () => {
                actions_1.NotebookActions.insertBelow(panel.content);
            },
            tooltip: 'Insert a cell below'
        });
    }
    ToolbarItems.createInsertButton = createInsertButton;
    /**
     * Create a cut toolbar item.
     */
    function createCutButton(panel) {
        return new apputils_1.ToolbarButton({
            iconClassName: TOOLBAR_CUT_CLASS + ' jp-Icon jp-Icon-16',
            onClick: () => {
                actions_1.NotebookActions.cut(panel.content);
            },
            tooltip: 'Cut the selected cells'
        });
    }
    ToolbarItems.createCutButton = createCutButton;
    /**
     * Create a copy toolbar item.
     */
    function createCopyButton(panel) {
        return new apputils_1.ToolbarButton({
            iconClassName: TOOLBAR_COPY_CLASS + ' jp-Icon jp-Icon-16',
            onClick: () => {
                actions_1.NotebookActions.copy(panel.content);
            },
            tooltip: 'Copy the selected cells'
        });
    }
    ToolbarItems.createCopyButton = createCopyButton;
    /**
     * Create a paste toolbar item.
     */
    function createPasteButton(panel) {
        return new apputils_1.ToolbarButton({
            iconClassName: TOOLBAR_PASTE_CLASS + ' jp-Icon jp-Icon-16',
            onClick: () => {
                actions_1.NotebookActions.paste(panel.content);
            },
            tooltip: 'Paste cells from the clipboard'
        });
    }
    ToolbarItems.createPasteButton = createPasteButton;
    /**
     * Create a run toolbar item.
     */
    function createRunButton(panel) {
        return new apputils_1.ToolbarButton({
            iconClassName: TOOLBAR_RUN_CLASS + ' jp-Icon jp-Icon-16',
            onClick: () => {
                actions_1.NotebookActions.runAndAdvance(panel.content, panel.session);
            },
            tooltip: 'Run the selected cells and advance'
        });
    }
    ToolbarItems.createRunButton = createRunButton;
    /**
     * Create a cell type switcher item.
     *
     * #### Notes
     * It will display the type of the current active cell.
     * If more than one cell is selected but are of different types,
     * it will display `'-'`.
     * When the user changes the cell type, it will change the
     * cell types of the selected cells.
     * It can handle a change to the context.
     */
    function createCellTypeItem(panel) {
        return new CellTypeSwitcher(panel.content);
    }
    ToolbarItems.createCellTypeItem = createCellTypeItem;
    /**
     * Add the default items to the panel toolbar.
     */
    function populateDefaults(panel) {
        let toolbar = panel.toolbar;
        toolbar.addItem('save', createSaveButton(panel));
        toolbar.addItem('insert', createInsertButton(panel));
        toolbar.addItem('cut', createCutButton(panel));
        toolbar.addItem('copy', createCopyButton(panel));
        toolbar.addItem('paste', createPasteButton(panel));
        toolbar.addItem('run', createRunButton(panel));
        toolbar.addItem('interrupt', apputils_1.Toolbar.createInterruptButton(panel.session));
        toolbar.addItem('restart', apputils_1.Toolbar.createRestartButton(panel.session));
        toolbar.addItem('cellType', createCellTypeItem(panel));
        toolbar.addItem('spacer', apputils_1.Toolbar.createSpacerItem());
        toolbar.addItem('kernelName', apputils_1.Toolbar.createKernelNameItem(panel.session));
        toolbar.addItem('kernelStatus', apputils_1.Toolbar.createKernelStatusItem(panel.session));
    }
    ToolbarItems.populateDefaults = populateDefaults;
    /**
     * Get the default toolbar items for panel
     */
    function getDefaultItems(panel) {
        return [
            { name: 'save', widget: createSaveButton(panel) },
            { name: 'insert', widget: createInsertButton(panel) },
            { name: 'cut', widget: createCutButton(panel) },
            { name: 'copy', widget: createCopyButton(panel) },
            { name: 'paste', widget: createPasteButton(panel) },
            { name: 'run', widget: createRunButton(panel) },
            {
                name: 'interrupt',
                widget: apputils_1.Toolbar.createInterruptButton(panel.session)
            },
            {
                name: 'restart',
                widget: apputils_1.Toolbar.createRestartButton(panel.session)
            },
            { name: 'cellType', widget: createCellTypeItem(panel) },
            { name: 'spacer', widget: apputils_1.Toolbar.createSpacerItem() },
            {
                name: 'kernelName',
                widget: apputils_1.Toolbar.createKernelNameItem(panel.session)
            },
            {
                name: 'kernelStatus',
                widget: apputils_1.Toolbar.createKernelStatusItem(panel.session)
            }
        ];
    }
    ToolbarItems.getDefaultItems = getDefaultItems;
})(ToolbarItems = exports.ToolbarItems || (exports.ToolbarItems = {}));
/**
 * A toolbar widget that switches cell types.
 */
class CellTypeSwitcher extends widgets_1.Widget {
    /**
     * Construct a new cell type switcher.
     */
    constructor(widget) {
        super({ node: createCellTypeSwitcherNode() });
        this._changeGuard = false;
        this._wildCard = null;
        this._select = null;
        this._notebook = null;
        this.addClass(TOOLBAR_CELLTYPE_CLASS);
        this._select = this.node.firstChild;
        apputils_1.Styling.wrapSelect(this._select);
        this._wildCard = document.createElement('option');
        this._wildCard.value = '-';
        this._wildCard.textContent = '-';
        this._notebook = widget;
        // Set the initial value.
        if (widget.model) {
            this._updateValue();
        }
        // Follow the type of the active cell.
        widget.activeCellChanged.connect(this._updateValue, this);
        // Follow a change in the selection.
        widget.selectionChanged.connect(this._updateValue, this);
    }
    /**
     * Handle the DOM events for the widget.
     *
     * @param event - The DOM event sent to the widget.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the dock panel's node. It should
     * not be called directly by user code.
     */
    handleEvent(event) {
        switch (event.type) {
            case 'change':
                this._evtChange(event);
                break;
            case 'keydown':
                this._evtKeyDown(event);
                break;
            default:
                break;
        }
    }
    /**
     * Handle `after-attach` messages for the widget.
     */
    onAfterAttach(msg) {
        this._select.addEventListener('change', this);
        this._select.addEventListener('keydown', this);
    }
    /**
     * Handle `before-detach` messages for the widget.
     */
    onBeforeDetach(msg) {
        this._select.removeEventListener('change', this);
        this._select.removeEventListener('keydown', this);
    }
    /**
     * Handle `changed` events for the widget.
     */
    _evtChange(event) {
        let select = this._select;
        let widget = this._notebook;
        if (select.value === '-') {
            return;
        }
        if (!this._changeGuard) {
            let value = select.value;
            actions_1.NotebookActions.changeCellType(widget, value);
            widget.activate();
        }
    }
    /**
     * Handle `keydown` events for the widget.
     */
    _evtKeyDown(event) {
        if (event.keyCode === 13) {
            // Enter
            this._notebook.activate();
        }
    }
    /**
     * Update the value of the dropdown from the widget state.
     */
    _updateValue() {
        let widget = this._notebook;
        let select = this._select;
        if (!widget.activeCell) {
            return;
        }
        let mType = widget.activeCell.model.type;
        for (let i = 0; i < widget.widgets.length; i++) {
            let child = widget.widgets[i];
            if (widget.isSelectedOrActive(child)) {
                if (child.model.type !== mType) {
                    mType = '-';
                    select.appendChild(this._wildCard);
                    break;
                }
            }
        }
        if (mType !== '-') {
            select.remove(3);
        }
        this._changeGuard = true;
        select.value = mType;
        this._changeGuard = false;
    }
}
/**
 * Create the node for the cell type switcher.
 */
function createCellTypeSwitcherNode() {
    let div = document.createElement('div');
    let select = document.createElement('select');
    for (let t of ['Code', 'Markdown', 'Raw']) {
        let option = document.createElement('option');
        option.value = t.toLowerCase();
        option.textContent = t;
        select.appendChild(option);
    }
    select.className = TOOLBAR_CELLTYPE_DROPDOWN_CLASS;
    div.appendChild(select);
    return div;
}


/***/ }),

/***/ "jeLo":
/*!**********************************************!*\
  !*** ./node_modules/lodash/toPlainObject.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var copyObject = __webpack_require__(/*! ./_copyObject */ "juv8"),
    keysIn = __webpack_require__(/*! ./keysIn */ "mTTR");

/**
 * 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;


/***/ }),

/***/ "jfSC":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/fa.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var symbolMap = {
    '1': '۱',
    '2': '۲',
    '3': '۳',
    '4': '۴',
    '5': '۵',
    '6': '۶',
    '7': '۷',
    '8': '۸',
    '9': '۹',
    '0': '۰'
}, numberMap = {
    '۱': '1',
    '۲': '2',
    '۳': '3',
    '۴': '4',
    '۵': '5',
    '۶': '6',
    '۷': '7',
    '۸': '8',
    '۹': '9',
    '۰': '0'
};

var fa = moment.defineLocale('fa', {
    months : 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'),
    monthsShort : 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'),
    weekdays : 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'),
    weekdaysShort : 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'),
    weekdaysMin : 'ی_د_س_چ_پ_ج_ش'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd, D MMMM YYYY HH:mm'
    },
    meridiemParse: /قبل از ظهر|بعد از ظهر/,
    isPM: function (input) {
        return /بعد از ظهر/.test(input);
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 12) {
            return 'قبل از ظهر';
        } else {
            return 'بعد از ظهر';
        }
    },
    calendar : {
        sameDay : '[امروز ساعت] LT',
        nextDay : '[فردا ساعت] LT',
        nextWeek : 'dddd [ساعت] LT',
        lastDay : '[دیروز ساعت] LT',
        lastWeek : 'dddd [پیش] [ساعت] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'در %s',
        past : '%s پیش',
        s : 'چند ثانیه',
        ss : 'ثانیه d%',
        m : 'یک دقیقه',
        mm : '%d دقیقه',
        h : 'یک ساعت',
        hh : '%d ساعت',
        d : 'یک روز',
        dd : '%d روز',
        M : 'یک ماه',
        MM : '%d ماه',
        y : 'یک سال',
        yy : '%d سال'
    },
    preparse: function (string) {
        return string.replace(/[۰-۹]/g, function (match) {
            return numberMap[match];
        }).replace(/،/g, ',');
    },
    postformat: function (string) {
        return string.replace(/\d/g, function (match) {
            return symbolMap[match];
        }).replace(/,/g, '،');
    },
    dayOfMonthOrdinalParse: /\d{1,2}م/,
    ordinal : '%dم',
    week : {
        dow : 6, // Saturday is the first day of the week.
        doy : 12 // The week that contains Jan 1st is the first week of the year.
    }
});

return fa;

})));


/***/ }),

/***/ "jfd1":
/*!*******************************************************!*\
  !*** ./node_modules/asn1.js/lib/asn1/decoders/pem.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var inherits = __webpack_require__(/*! inherits */ "P7XM");
var Buffer = __webpack_require__(/*! buffer */ "tjlA").Buffer;

var DERDecoder = __webpack_require__(/*! ./der */ "z71Z");

function PEMDecoder(entity) {
  DERDecoder.call(this, entity);
  this.enc = 'pem';
};
inherits(PEMDecoder, DERDecoder);
module.exports = PEMDecoder;

PEMDecoder.prototype.decode = function decode(data, options) {
  var lines = data.toString().split(/[\r\n]+/g);

  var label = options.label.toUpperCase();

  var re = /^-----(BEGIN|END) ([^-]+)-----$/;
  var start = -1;
  var end = -1;
  for (var i = 0; i < lines.length; i++) {
    var match = lines[i].match(re);
    if (match === null)
      continue;

    if (match[2] !== label)
      continue;

    if (start === -1) {
      if (match[1] !== 'BEGIN')
        break;
      start = i;
    } else {
      if (match[1] !== 'END')
        break;
      end = i;
      break;
    }
  }
  if (start === -1 || end === -1)
    throw new Error('PEM section not found for: ' + label);

  var base64 = lines.slice(start + 1, end).join('');
  // Remove excessive symbols
  base64.replace(/[^a-z0-9\+\/=]+/gi, '');

  var input = new Buffer(base64, 'base64');
  return DERDecoder.prototype.decode.call(this, input, options);
};


/***/ }),

/***/ "jfpi":
/*!**********************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@phosphor/widgets/style/index.css ***!
  \**********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports
exports.i(__webpack_require__(/*! -!../../../css-loader!./widget.css */ "QtI6"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./commandpalette.css */ "dRFA"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./dockpanel.css */ "I4rr"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./menu.css */ "fz/m"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./menubar.css */ "X4Z0"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./scrollbar.css */ "VI8P"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./splitpanel.css */ "2arF"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./tabbar.css */ "7j9i"), "");
exports.i(__webpack_require__(/*! -!../../../css-loader!./tabpanel.css */ "Rva2"), "");

// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\r\n| Copyright (c) 2014-2017, PhosphorJS Contributors\r\n|\r\n| Distributed under the terms of the BSD 3-Clause License.\r\n|\r\n| The full license is in the file LICENSE, distributed with this software.\r\n|----------------------------------------------------------------------------*/\r\n", ""]);

// exports


/***/ }),

/***/ "jizN":
/*!********************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/application/style/dockpanel.css ***!
  \********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n/*-----------------------------------------------------------------------------\n| Variables\n|----------------------------------------------------------------------------*/\n\n/*-----------------------------------------------------------------------------\n| DockPanel\n|----------------------------------------------------------------------------*/\n\n.p-DockPanel-widget {\n  background: var(--jp-layout-color0);\n  border-left: var(--jp-border-width) solid var(--jp-border-color1);\n  border-right: var(--jp-border-width) solid var(--jp-border-color1);\n  border-bottom: var(--jp-border-width) solid var(--jp-border-color1);\n}\n\n.p-DockPanel-overlay {\n  background: rgba(33, 150, 243, 0.1);\n  border: var(--jp-border-width) dashed var(--jp-brand-color1);\n  transition-property: top, left, right, bottom;\n  transition-duration: 150ms;\n  transition-timing-function: ease;\n}\n\n.p-DockPanel-overlay.p-mod-root-top,\n.p-DockPanel-overlay.p-mod-root-left,\n.p-DockPanel-overlay.p-mod-root-right,\n.p-DockPanel-overlay.p-mod-root-bottom,\n.p-DockPanel-overlay.p-mod-root-center {\n  border-width: 2px;\n}\n", ""]);

// exports


/***/ }),

/***/ "jjzf":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils/lib/hoverbox.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * The class name added to all hover boxes.
 */
const HOVERBOX_CLASS = 'jp-HoverBox';
/**
 * The class name added to a hovering node that is scrolled out of view.
 */
const OUTOFVIEW_CLASS = 'jp-mod-outofview';
/**
 * A namespace for `HoverBox` members.
 */
var HoverBox;
(function (HoverBox) {
    /**
     * Set the visible dimensions of a hovering box anchored to an editor cursor.
     *
     * @param options - The hover box geometry calculation options.
     */
    function setGeometry(options) {
        const { anchor, host, node, privilege } = options;
        // Add hover box class if it does not exist.
        node.classList.add(HOVERBOX_CLASS);
        // Hide the hover box before querying the DOM for the anchor coordinates.
        node.classList.add(OUTOFVIEW_CLASS);
        // If the current coordinates are not visible, bail.
        if (!host.contains(document.elementFromPoint(anchor.left, anchor.top))) {
            return;
        }
        // Clear any previously set max-height.
        node.style.maxHeight = '';
        // Clear any programmatically set margin-top.
        node.style.marginTop = '';
        // Make sure the node is visible so that its dimensions can be queried.
        node.classList.remove(OUTOFVIEW_CLASS);
        const style = options.style || window.getComputedStyle(node);
        const innerHeight = window.innerHeight;
        const spaceAbove = anchor.top;
        const spaceBelow = innerHeight - anchor.bottom;
        const marginTop = parseInt(style.marginTop, 10) || 0;
        const minHeight = parseInt(style.minHeight, 10) || options.minHeight;
        let maxHeight = parseInt(style.maxHeight, 10) || options.maxHeight;
        // Determine whether to render above or below; check privilege.
        const renderBelow = privilege === 'forceAbove'
            ? false
            : privilege === 'forceBelow'
                ? true
                : privilege === 'above'
                    ? spaceAbove < maxHeight && spaceAbove < spaceBelow
                    : spaceBelow >= maxHeight || spaceBelow >= spaceAbove;
        if (renderBelow) {
            maxHeight = Math.min(spaceBelow - marginTop, maxHeight);
        }
        else {
            maxHeight = Math.min(spaceAbove, maxHeight);
            // If the box renders above the text, its top margin is irrelevant.
            node.style.marginTop = '0px';
        }
        node.style.maxHeight = `${maxHeight}px`;
        // Make sure the box ought to be visible.
        const withinBounds = maxHeight > minHeight &&
            (spaceBelow >= minHeight || spaceAbove >= minHeight);
        if (!withinBounds) {
            node.classList.add(OUTOFVIEW_CLASS);
            return;
        }
        // Position the box vertically.
        const offsetAbove = (options.offset &&
            options.offset.vertical &&
            options.offset.vertical.above) ||
            0;
        const offsetBelow = (options.offset &&
            options.offset.vertical &&
            options.offset.vertical.below) ||
            0;
        const top = renderBelow
            ? innerHeight - spaceBelow + offsetBelow
            : spaceAbove - node.getBoundingClientRect().height + offsetAbove;
        node.style.top = `${Math.floor(top)}px`;
        // Position the box horizontally.
        const offsetHorizontal = (options.offset && options.offset.horizontal) || 0;
        let left = anchor.left + offsetHorizontal;
        node.style.left = `${Math.ceil(left)}px`;
        node.style.width = 'auto';
        // Expand the menu width by the scrollbar size, if present.
        if (node.scrollHeight >= maxHeight) {
            node.style.width = `${2 * node.offsetWidth - node.clientWidth}`;
            node.scrollTop = 0;
        }
        // Move left to fit in the window.
        let right = node.getBoundingClientRect().right;
        if (right > window.innerWidth) {
            left -= right - window.innerWidth;
            node.style.left = `${Math.ceil(left)}px`;
        }
    }
    HoverBox.setGeometry = setGeometry;
})(HoverBox = exports.HoverBox || (exports.HoverBox = {}));


/***/ }),

/***/ "jl1W":
/*!********************************************************************!*\
  !*** ./node_modules/draft-js/lib/DraftEditorCompositionHandler.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DraftEditorCompositionHandler
 * @format
 * 
 */



var DraftFeatureFlags = __webpack_require__(/*! ./DraftFeatureFlags */ "cX45");
var DraftModifier = __webpack_require__(/*! ./DraftModifier */ "fyOY");
var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");
var Keys = __webpack_require__(/*! fbjs/lib/Keys */ "7wDu");

var getEntityKeyForSelection = __webpack_require__(/*! ./getEntityKeyForSelection */ "hpMJ");
var isEventHandled = __webpack_require__(/*! ./isEventHandled */ "T401");
var isSelectionAtLeafStart = __webpack_require__(/*! ./isSelectionAtLeafStart */ "Yrnb");

/**
 * Millisecond delay to allow `compositionstart` to fire again upon
 * `compositionend`.
 *
 * This is used for Korean input to ensure that typing can continue without
 * the editor trying to render too quickly. More specifically, Safari 7.1+
 * triggers `compositionstart` a little slower than Chrome/FF, which
 * leads to composed characters being resolved and re-render occurring
 * sooner than we want.
 */
var RESOLVE_DELAY = 20;

/**
 * A handful of variables used to track the current composition and its
 * resolution status. These exist at the module level because it is not
 * possible to have compositions occurring in multiple editors simultaneously,
 * and it simplifies state management with respect to the DraftEditor component.
 */
var resolved = false;
var stillComposing = false;
var textInputData = '';

var DraftEditorCompositionHandler = {
  onBeforeInput: function onBeforeInput(editor, e) {
    textInputData = (textInputData || '') + e.data;
  },

  /**
   * A `compositionstart` event has fired while we're still in composition
   * mode. Continue the current composition session to prevent a re-render.
   */
  onCompositionStart: function onCompositionStart(editor) {
    stillComposing = true;
  },

  /**
   * Attempt to end the current composition session.
   *
   * Defer handling because browser will still insert the chars into active
   * element after `compositionend`. If a `compositionstart` event fires
   * before `resolveComposition` executes, our composition session will
   * continue.
   *
   * The `resolved` flag is useful because certain IME interfaces fire the
   * `compositionend` event multiple times, thus queueing up multiple attempts
   * at handling the composition. Since handling the same composition event
   * twice could break the DOM, we only use the first event. Example: Arabic
   * Google Input Tools on Windows 8.1 fires `compositionend` three times.
   */
  onCompositionEnd: function onCompositionEnd(editor) {
    resolved = false;
    stillComposing = false;
    setTimeout(function () {
      if (!resolved) {
        DraftEditorCompositionHandler.resolveComposition(editor);
      }
    }, RESOLVE_DELAY);
  },

  /**
   * In Safari, keydown events may fire when committing compositions. If
   * the arrow keys are used to commit, prevent default so that the cursor
   * doesn't move, otherwise it will jump back noticeably on re-render.
   */
  onKeyDown: function onKeyDown(editor, e) {
    if (!stillComposing) {
      // If a keydown event is received after compositionend but before the
      // 20ms timer expires (ex: type option-E then backspace, or type A then
      // backspace in 2-Set Korean), we should immediately resolve the
      // composition and reinterpret the key press in edit mode.
      DraftEditorCompositionHandler.resolveComposition(editor);
      editor._onKeyDown(e);
      return;
    }
    if (e.which === Keys.RIGHT || e.which === Keys.LEFT) {
      e.preventDefault();
    }
  },

  /**
   * Keypress events may fire when committing compositions. In Firefox,
   * pressing RETURN commits the composition and inserts extra newline
   * characters that we do not want. `preventDefault` allows the composition
   * to be committed while preventing the extra characters.
   */
  onKeyPress: function onKeyPress(editor, e) {
    if (e.which === Keys.RETURN) {
      e.preventDefault();
    }
  },

  /**
   * Attempt to insert composed characters into the document.
   *
   * If we are still in a composition session, do nothing. Otherwise, insert
   * the characters into the document and terminate the composition session.
   *
   * If no characters were composed -- for instance, the user
   * deleted all composed characters and committed nothing new --
   * force a re-render. We also re-render when the composition occurs
   * at the beginning of a leaf, to ensure that if the browser has
   * created a new text node for the composition, we will discard it.
   *
   * Resetting innerHTML will move focus to the beginning of the editor,
   * so we update to force it back to the correct place.
   */
  resolveComposition: function resolveComposition(editor) {
    if (stillComposing) {
      return;
    }

    resolved = true;
    var composedChars = textInputData;
    textInputData = '';

    var editorState = EditorState.set(editor._latestEditorState, {
      inCompositionMode: false
    });

    var currentStyle = editorState.getCurrentInlineStyle();
    var entityKey = getEntityKeyForSelection(editorState.getCurrentContent(), editorState.getSelection());

    var mustReset = !composedChars || isSelectionAtLeafStart(editorState) || currentStyle.size > 0 || entityKey !== null;

    if (mustReset) {
      editor.restoreEditorDOM();
    }

    editor.exitCurrentMode();

    if (composedChars) {
      if (DraftFeatureFlags.draft_handlebeforeinput_composed_text && editor.props.handleBeforeInput && isEventHandled(editor.props.handleBeforeInput(composedChars, editorState))) {
        return;
      }
      // If characters have been composed, re-rendering with the update
      // is sufficient to reset the editor.
      var contentState = DraftModifier.replaceText(editorState.getCurrentContent(), editorState.getSelection(), composedChars, currentStyle, entityKey);
      editor.update(EditorState.push(editorState, contentState, 'insert-characters'));
      return;
    }

    if (mustReset) {
      editor.update(EditorState.set(editorState, {
        nativelyRenderedContent: null,
        forceSelection: true
      }));
    }
  }
};

module.exports = DraftEditorCompositionHandler;

/***/ }),

/***/ "jl2H":
/*!***************************************************!*\
  !*** ./node_modules/fbjs/lib/getActiveElement.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks
 */

/* eslint-disable fb-www/typeof-undefined */

/**
 * Same as document.activeElement but wraps in a try-catch block. In IE it is
 * not safe to call document.activeElement if there is nothing focused.
 *
 * The activeElement will be null only if the document or document body is not
 * yet defined.
 *
 * @param {?DOMDocument} doc Defaults to current document.
 * @return {?DOMElement}
 */
function getActiveElement(doc) /*?DOMElement*/{
  doc = doc || (typeof document !== 'undefined' ? document : undefined);
  if (typeof doc === 'undefined') {
    return null;
  }
  try {
    return doc.activeElement || doc.body;
  } catch (e) {
    return doc.body;
  }
}

module.exports = getActiveElement;

/***/ }),

/***/ "jmDH":
/*!**************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_descriptors.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__(/*! ./_fails */ "KUxP")(function () {
  return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
});


/***/ }),

/***/ "jnO4":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/ar.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var symbolMap = {
    '1': '١',
    '2': '٢',
    '3': '٣',
    '4': '٤',
    '5': '٥',
    '6': '٦',
    '7': '٧',
    '8': '٨',
    '9': '٩',
    '0': '٠'
}, numberMap = {
    '١': '1',
    '٢': '2',
    '٣': '3',
    '٤': '4',
    '٥': '5',
    '٦': '6',
    '٧': '7',
    '٨': '8',
    '٩': '9',
    '٠': '0'
}, pluralForm = function (n) {
    return n === 0 ? 0 : n === 1 ? 1 : n === 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5;
}, plurals = {
    s : ['أقل من ثانية', 'ثانية واحدة', ['ثانيتان', 'ثانيتين'], '%d ثوان', '%d ثانية', '%d ثانية'],
    m : ['أقل من دقيقة', 'دقيقة واحدة', ['دقيقتان', 'دقيقتين'], '%d دقائق', '%d دقيقة', '%d دقيقة'],
    h : ['أقل من ساعة', 'ساعة واحدة', ['ساعتان', 'ساعتين'], '%d ساعات', '%d ساعة', '%d ساعة'],
    d : ['أقل من يوم', 'يوم واحد', ['يومان', 'يومين'], '%d أيام', '%d يومًا', '%d يوم'],
    M : ['أقل من شهر', 'شهر واحد', ['شهران', 'شهرين'], '%d أشهر', '%d شهرا', '%d شهر'],
    y : ['أقل من عام', 'عام واحد', ['عامان', 'عامين'], '%d أعوام', '%d عامًا', '%d عام']
}, pluralize = function (u) {
    return function (number, withoutSuffix, string, isFuture) {
        var f = pluralForm(number),
            str = plurals[u][pluralForm(number)];
        if (f === 2) {
            str = str[withoutSuffix ? 0 : 1];
        }
        return str.replace(/%d/i, number);
    };
}, months = [
    'يناير',
    'فبراير',
    'مارس',
    'أبريل',
    'مايو',
    'يونيو',
    'يوليو',
    'أغسطس',
    'سبتمبر',
    'أكتوبر',
    'نوفمبر',
    'ديسمبر'
];

var ar = moment.defineLocale('ar', {
    months : months,
    monthsShort : months,
    weekdays : 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
    weekdaysShort : 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),
    weekdaysMin : 'ح_ن_ث_ر_خ_ج_س'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'D/\u200FM/\u200FYYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd D MMMM YYYY HH:mm'
    },
    meridiemParse: /ص|م/,
    isPM : function (input) {
        return 'م' === input;
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 12) {
            return 'ص';
        } else {
            return 'م';
        }
    },
    calendar : {
        sameDay: '[اليوم عند الساعة] LT',
        nextDay: '[غدًا عند الساعة] LT',
        nextWeek: 'dddd [عند الساعة] LT',
        lastDay: '[أمس عند الساعة] LT',
        lastWeek: 'dddd [عند الساعة] LT',
        sameElse: 'L'
    },
    relativeTime : {
        future : 'بعد %s',
        past : 'منذ %s',
        s : pluralize('s'),
        ss : pluralize('s'),
        m : pluralize('m'),
        mm : pluralize('m'),
        h : pluralize('h'),
        hh : pluralize('h'),
        d : pluralize('d'),
        dd : pluralize('d'),
        M : pluralize('M'),
        MM : pluralize('M'),
        y : pluralize('y'),
        yy : pluralize('y')
    },
    preparse: function (string) {
        return string.replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) {
            return numberMap[match];
        }).replace(/،/g, ',');
    },
    postformat: function (string) {
        return string.replace(/\d/g, function (match) {
            return symbolMap[match];
        }).replace(/,/g, '،');
    },
    week : {
        dow : 6, // Saturday is the first day of the week.
        doy : 12  // The week that contains Jan 1st is the first week of the year.
    }
});

return ar;

})));


/***/ }),

/***/ "jo6Y":
/*!***********************************************************************!*\
  !*** ./node_modules/babel-runtime/helpers/objectWithoutProperties.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

exports.default = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

/***/ }),

/***/ "jrO0":
/*!*****************************************************!*\
  !*** ./node_modules/xterm/lib/utils/MouseHelper.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var MouseHelper = (function () {
    function MouseHelper(_renderer) {
        this._renderer = _renderer;
    }
    MouseHelper.getCoordsRelativeToElement = function (event, element) {
        if (event.pageX == null) {
            return null;
        }
        var originalElement = element;
        var x = event.pageX;
        var y = event.pageY;
        while (element) {
            x -= element.offsetLeft;
            y -= element.offsetTop;
            element = element.offsetParent;
        }
        element = originalElement;
        while (element && element !== element.ownerDocument.body) {
            x += element.scrollLeft;
            y += element.scrollTop;
            element = element.parentElement;
        }
        return [x, y];
    };
    MouseHelper.prototype.getCoords = function (event, element, charMeasure, lineHeight, colCount, rowCount, isSelection) {
        if (!charMeasure.width || !charMeasure.height) {
            return null;
        }
        var coords = MouseHelper.getCoordsRelativeToElement(event, element);
        if (!coords) {
            return null;
        }
        coords[0] = Math.ceil((coords[0] + (isSelection ? this._renderer.dimensions.actualCellWidth / 2 : 0)) / this._renderer.dimensions.actualCellWidth);
        coords[1] = Math.ceil(coords[1] / this._renderer.dimensions.actualCellHeight);
        coords[0] = Math.min(Math.max(coords[0], 1), colCount + (isSelection ? 1 : 0));
        coords[1] = Math.min(Math.max(coords[1], 1), rowCount);
        return coords;
    };
    MouseHelper.prototype.getRawByteCoords = function (event, element, charMeasure, lineHeight, colCount, rowCount) {
        var coords = this.getCoords(event, element, charMeasure, lineHeight, colCount, rowCount);
        var x = coords[0];
        var y = coords[1];
        x += 32;
        y += 32;
        return { x: x, y: y };
    };
    return MouseHelper;
}());
exports.MouseHelper = MouseHelper;

//# sourceMappingURL=MouseHelper.js.map


/***/ }),

/***/ "jrUH":
/*!***************************************************************!*\
  !*** ./node_modules/@jupyterlab/notebook/lib/modelfactory.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const model_1 = __webpack_require__(/*! ./model */ "wGmf");
/**
 * A model factory for notebooks.
 */
class NotebookModelFactory {
    /**
     * Construct a new notebook model factory.
     */
    constructor(options) {
        this._disposed = false;
        let codeCellContentFactory = options.codeCellContentFactory;
        this.contentFactory =
            options.contentFactory ||
                new model_1.NotebookModel.ContentFactory({ codeCellContentFactory });
    }
    /**
     * The name of the model.
     */
    get name() {
        return 'notebook';
    }
    /**
     * The content type of the file.
     */
    get contentType() {
        return 'notebook';
    }
    /**
     * The format of the file.
     */
    get fileFormat() {
        return 'json';
    }
    /**
     * Get whether the model factory has been disposed.
     */
    get isDisposed() {
        return this._disposed;
    }
    /**
     * Dispose of the model factory.
     */
    dispose() {
        this._disposed = true;
    }
    /**
     * Create a new model for a given path.
     *
     * @param languagePreference - An optional kernel language preference.
     *
     * @returns A new document model.
     */
    createNew(languagePreference, modelDB) {
        let contentFactory = this.contentFactory;
        return new model_1.NotebookModel({ languagePreference, contentFactory, modelDB });
    }
    /**
     * Get the preferred kernel language given a path.
     */
    preferredLanguage(path) {
        return '';
    }
}
exports.NotebookModelFactory = NotebookModelFactory;


/***/ }),

/***/ "jroS":
/*!*******************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/codemirror/theme/solarized.css ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*\nSolarized theme for code-mirror\nhttp://ethanschoonover.com/solarized\n*/\n\n/*\nSolarized color palette\nhttp://ethanschoonover.com/solarized/img/solarized-palette.png\n*/\n\n.solarized.base03 { color: #002b36; }\n.solarized.base02 { color: #073642; }\n.solarized.base01 { color: #586e75; }\n.solarized.base00 { color: #657b83; }\n.solarized.base0 { color: #839496; }\n.solarized.base1 { color: #93a1a1; }\n.solarized.base2 { color: #eee8d5; }\n.solarized.base3  { color: #fdf6e3; }\n.solarized.solar-yellow  { color: #b58900; }\n.solarized.solar-orange  { color: #cb4b16; }\n.solarized.solar-red { color: #dc322f; }\n.solarized.solar-magenta { color: #d33682; }\n.solarized.solar-violet  { color: #6c71c4; }\n.solarized.solar-blue { color: #268bd2; }\n.solarized.solar-cyan { color: #2aa198; }\n.solarized.solar-green { color: #859900; }\n\n/* Color scheme for code-mirror */\n\n.cm-s-solarized {\n  line-height: 1.45em;\n  color-profile: sRGB;\n  rendering-intent: auto;\n}\n.cm-s-solarized.cm-s-dark {\n  color: #839496;\n  background-color: #002b36;\n  text-shadow: #002b36 0 1px;\n}\n.cm-s-solarized.cm-s-light {\n  background-color: #fdf6e3;\n  color: #657b83;\n  text-shadow: #eee8d5 0 1px;\n}\n\n.cm-s-solarized .CodeMirror-widget {\n  text-shadow: none;\n}\n\n.cm-s-solarized .cm-header { color: #586e75; }\n.cm-s-solarized .cm-quote { color: #93a1a1; }\n\n.cm-s-solarized .cm-keyword { color: #cb4b16; }\n.cm-s-solarized .cm-atom { color: #d33682; }\n.cm-s-solarized .cm-number { color: #d33682; }\n.cm-s-solarized .cm-def { color: #2aa198; }\n\n.cm-s-solarized .cm-variable { color: #839496; }\n.cm-s-solarized .cm-variable-2 { color: #b58900; }\n.cm-s-solarized .cm-variable-3, .cm-s-solarized .cm-type { color: #6c71c4; }\n\n.cm-s-solarized .cm-property { color: #2aa198; }\n.cm-s-solarized .cm-operator { color: #6c71c4; }\n\n.cm-s-solarized .cm-comment { color: #586e75; font-style:italic; }\n\n.cm-s-solarized .cm-string { color: #859900; }\n.cm-s-solarized .cm-string-2 { color: #b58900; }\n\n.cm-s-solarized .cm-meta { color: #859900; }\n.cm-s-solarized .cm-qualifier { color: #b58900; }\n.cm-s-solarized .cm-builtin { color: #d33682; }\n.cm-s-solarized .cm-bracket { color: #cb4b16; }\n.cm-s-solarized .CodeMirror-matchingbracket { color: #859900; }\n.cm-s-solarized .CodeMirror-nonmatchingbracket { color: #dc322f; }\n.cm-s-solarized .cm-tag { color: #93a1a1; }\n.cm-s-solarized .cm-attribute { color: #2aa198; }\n.cm-s-solarized .cm-hr {\n  color: transparent;\n  border-top: 1px solid #586e75;\n  display: block;\n}\n.cm-s-solarized .cm-link { color: #93a1a1; cursor: pointer; }\n.cm-s-solarized .cm-special { color: #6c71c4; }\n.cm-s-solarized .cm-em {\n  color: #999;\n  text-decoration: underline;\n  text-decoration-style: dotted;\n}\n.cm-s-solarized .cm-error,\n.cm-s-solarized .cm-invalidchar {\n  color: #586e75;\n  border-bottom: 1px dotted #dc322f;\n}\n\n.cm-s-solarized.cm-s-dark div.CodeMirror-selected { background: #073642; }\n.cm-s-solarized.cm-s-dark.CodeMirror ::selection { background: rgba(7, 54, 66, 0.99); }\n.cm-s-solarized.cm-s-dark .CodeMirror-line::-moz-selection, .cm-s-dark .CodeMirror-line > span::-moz-selection, .cm-s-dark .CodeMirror-line > span > span::-moz-selection { background: rgba(7, 54, 66, 0.99); }\n\n.cm-s-solarized.cm-s-light div.CodeMirror-selected { background: #eee8d5; }\n.cm-s-solarized.cm-s-light .CodeMirror-line::selection, .cm-s-light .CodeMirror-line > span::selection, .cm-s-light .CodeMirror-line > span > span::selection { background: #eee8d5; }\n.cm-s-solarized.cm-s-light .CodeMirror-line::-moz-selection, .cm-s-ligh .CodeMirror-line > span::-moz-selection, .cm-s-ligh .CodeMirror-line > span > span::-moz-selection { background: #eee8d5; }\n\n/* Editor styling */\n\n\n\n/* Little shadow on the view-port of the buffer view */\n.cm-s-solarized.CodeMirror {\n  -moz-box-shadow: inset 7px 0 12px -6px #000;\n  -webkit-box-shadow: inset 7px 0 12px -6px #000;\n  box-shadow: inset 7px 0 12px -6px #000;\n}\n\n/* Remove gutter border */\n.cm-s-solarized .CodeMirror-gutters {\n  border-right: 0;\n}\n\n/* Gutter colors and line number styling based of color scheme (dark / light) */\n\n/* Dark */\n.cm-s-solarized.cm-s-dark .CodeMirror-gutters {\n  background-color: #073642;\n}\n\n.cm-s-solarized.cm-s-dark .CodeMirror-linenumber {\n  color: #586e75;\n  text-shadow: #021014 0 -1px;\n}\n\n/* Light */\n.cm-s-solarized.cm-s-light .CodeMirror-gutters {\n  background-color: #eee8d5;\n}\n\n.cm-s-solarized.cm-s-light .CodeMirror-linenumber {\n  color: #839496;\n}\n\n/* Common */\n.cm-s-solarized .CodeMirror-linenumber {\n  padding: 0 5px;\n}\n.cm-s-solarized .CodeMirror-guttermarker-subtle { color: #586e75; }\n.cm-s-solarized.cm-s-dark .CodeMirror-guttermarker { color: #ddd; }\n.cm-s-solarized.cm-s-light .CodeMirror-guttermarker { color: #cb4b16; }\n\n.cm-s-solarized .CodeMirror-gutter .CodeMirror-gutter-text {\n  color: #586e75;\n}\n\n/* Cursor */\n.cm-s-solarized .CodeMirror-cursor { border-left: 1px solid #819090; }\n\n/* Fat cursor */\n.cm-s-solarized.cm-s-light.cm-fat-cursor .CodeMirror-cursor { background: #77ee77; }\n.cm-s-solarized.cm-s-light .cm-animate-fat-cursor { background-color: #77ee77; }\n.cm-s-solarized.cm-s-dark.cm-fat-cursor .CodeMirror-cursor { background: #586e75; }\n.cm-s-solarized.cm-s-dark .cm-animate-fat-cursor { background-color: #586e75; }\n\n/* Active line */\n.cm-s-solarized.cm-s-dark .CodeMirror-activeline-background {\n  background: rgba(255, 255, 255, 0.06);\n}\n.cm-s-solarized.cm-s-light .CodeMirror-activeline-background {\n  background: rgba(0, 0, 0, 0.06);\n}\n", ""]);

// exports


/***/ }),

/***/ "jsC2":
/*!**********************************************************!*\
  !*** ./node_modules/react-day-picker/lib/src/Weekday.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Weekday = function (_Component) {
  _inherits(Weekday, _Component);

  function Weekday() {
    _classCallCheck(this, Weekday);

    return _possibleConstructorReturn(this, (Weekday.__proto__ || Object.getPrototypeOf(Weekday)).apply(this, arguments));
  }

  _createClass(Weekday, [{
    key: 'shouldComponentUpdate',
    value: function shouldComponentUpdate(nextProps) {
      return this.props !== nextProps;
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          weekday = _props.weekday,
          className = _props.className,
          weekdaysLong = _props.weekdaysLong,
          weekdaysShort = _props.weekdaysShort,
          localeUtils = _props.localeUtils,
          locale = _props.locale;

      var title = void 0;
      if (weekdaysLong) {
        title = weekdaysLong[weekday];
      } else {
        title = localeUtils.formatWeekdayLong(weekday, locale);
      }
      var content = void 0;
      if (weekdaysShort) {
        content = weekdaysShort[weekday];
      } else {
        content = localeUtils.formatWeekdayShort(weekday, locale);
      }

      return _react2.default.createElement(
        'div',
        { className: className, role: 'columnheader' },
        _react2.default.createElement(
          'abbr',
          { title: title },
          content
        )
      );
    }
  }]);

  return Weekday;
}(_react.Component);

exports.default = Weekday;
Weekday.propTypes =  true ? {
  weekday: _propTypes2.default.number,
  className: _propTypes2.default.string,
  locale: _propTypes2.default.string,
  localeUtils: _propTypes2.default.object,

  weekdaysLong: _propTypes2.default.arrayOf(_propTypes2.default.string),
  weekdaysShort: _propTypes2.default.arrayOf(_propTypes2.default.string)
} : undefined;
//# sourceMappingURL=Weekday.js.map

/***/ }),

/***/ "ju9h":
/*!******************************************!*\
  !*** ./node_modules/base16/lib/chalk.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'chalk',
  author: 'chris kempson (http://chriskempson.com)',
  base00: '#151515',
  base01: '#202020',
  base02: '#303030',
  base03: '#505050',
  base04: '#b0b0b0',
  base05: '#d0d0d0',
  base06: '#e0e0e0',
  base07: '#f5f5f5',
  base08: '#fb9fb1',
  base09: '#eda987',
  base0A: '#ddb26f',
  base0B: '#acc267',
  base0C: '#12cfc0',
  base0D: '#6fc2ef',
  base0E: '#e1a3ee',
  base0F: '#deaf8f'
};
module.exports = exports['default'];

/***/ }),

/***/ "juv8":
/*!********************************************!*\
  !*** ./node_modules/lodash/_copyObject.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var assignValue = __webpack_require__(/*! ./_assignValue */ "MrPd"),
    baseAssignValue = __webpack_require__(/*! ./_baseAssignValue */ "hypo");

/**
 * 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;
}

module.exports = copyObject;


/***/ }),

/***/ "jxix":
/*!*********************************************************!*\
  !*** ./node_modules/@phosphor/domutils/lib/platform.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * The namespace for platform related utilities.
 */
var Platform;
(function (Platform) {
    /**
     * A flag indicating whether the platform is Mac.
     */
    Platform.IS_MAC = !!navigator.platform.match(/Mac/i);
    /**
     * A flag indicating whether the platform is Windows.
     */
    Platform.IS_WIN = !!navigator.platform.match(/Win/i);
    /**
     * A flag indicating whether the browser is IE.
     */
    Platform.IS_IE = /Trident/.test(navigator.userAgent);
    /**
     * A flag indicating whether the browser is Edge.
     */
    Platform.IS_EDGE = /Edge/.test(navigator.userAgent);
})(Platform = exports.Platform || (exports.Platform = {}));


/***/ }),

/***/ "jyDg":
/*!**************************************************!*\
  !*** ./node_modules/draft-js/lib/editOnInput.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule editOnInput
 * @format
 * 
 */



var DraftFeatureFlags = __webpack_require__(/*! ./DraftFeatureFlags */ "cX45");
var DraftModifier = __webpack_require__(/*! ./DraftModifier */ "fyOY");
var DraftOffsetKey = __webpack_require__(/*! ./DraftOffsetKey */ "Iq8E");
var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");
var UserAgent = __webpack_require__(/*! fbjs/lib/UserAgent */ "CYTE");

var findAncestorOffsetKey = __webpack_require__(/*! ./findAncestorOffsetKey */ "kc9Y");
var nullthrows = __webpack_require__(/*! fbjs/lib/nullthrows */ "gWRK");

var isGecko = UserAgent.isEngine('Gecko');

var DOUBLE_NEWLINE = '\n\n';

/**
 * This function is intended to handle spellcheck and autocorrect changes,
 * which occur in the DOM natively without any opportunity to observe or
 * interpret the changes before they occur.
 *
 * The `input` event fires in contentEditable elements reliably for non-IE
 * browsers, immediately after changes occur to the editor DOM. Since our other
 * handlers override or otherwise handle cover other varieties of text input,
 * the DOM state should match the model in all controlled input cases. Thus,
 * when an `input` change leads to a DOM/model mismatch, the change should be
 * due to a spellcheck change, and we can incorporate it into our model.
 */
function editOnInput(editor) {
  if (editor._pendingStateFromBeforeInput !== undefined) {
    editor.update(editor._pendingStateFromBeforeInput);
    editor._pendingStateFromBeforeInput = undefined;
  }

  var domSelection = global.getSelection();

  var anchorNode = domSelection.anchorNode,
      isCollapsed = domSelection.isCollapsed;

  var isNotTextNode = anchorNode.nodeType !== Node.TEXT_NODE;
  var isNotTextOrElementNode = anchorNode.nodeType !== Node.TEXT_NODE && anchorNode.nodeType !== Node.ELEMENT_NODE;

  if (DraftFeatureFlags.draft_killswitch_allow_nontextnodes) {
    if (isNotTextNode) {
      return;
    }
  } else {
    if (isNotTextOrElementNode) {
      // TODO: (t16149272) figure out context for this change
      return;
    }
  }

  if (anchorNode.nodeType === Node.TEXT_NODE && (anchorNode.previousSibling !== null || anchorNode.nextSibling !== null)) {
    // When typing at the beginning of a visual line, Chrome splits the text
    // nodes into two. Why? No one knows. This commit is suspicious:
    // https://chromium.googlesource.com/chromium/src/+/a3b600981286b135632371477f902214c55a1724
    // To work around, we'll merge the sibling text nodes back into this one.
    var span = anchorNode.parentNode;
    anchorNode.nodeValue = span.textContent;
    for (var child = span.firstChild; child !== null; child = child.nextSibling) {
      if (child !== anchorNode) {
        span.removeChild(child);
      }
    }
  }

  var domText = anchorNode.textContent;
  var editorState = editor._latestEditorState;
  var offsetKey = nullthrows(findAncestorOffsetKey(anchorNode));

  var _DraftOffsetKey$decod = DraftOffsetKey.decode(offsetKey),
      blockKey = _DraftOffsetKey$decod.blockKey,
      decoratorKey = _DraftOffsetKey$decod.decoratorKey,
      leafKey = _DraftOffsetKey$decod.leafKey;

  var _editorState$getBlock = editorState.getBlockTree(blockKey).getIn([decoratorKey, 'leaves', leafKey]),
      start = _editorState$getBlock.start,
      end = _editorState$getBlock.end;

  var content = editorState.getCurrentContent();
  var block = content.getBlockForKey(blockKey);
  var modelText = block.getText().slice(start, end);

  // Special-case soft newlines here. If the DOM text ends in a soft newline,
  // we will have manually inserted an extra soft newline in DraftEditorLeaf.
  // We want to remove this extra newline for the purpose of our comparison
  // of DOM and model text.
  if (domText.endsWith(DOUBLE_NEWLINE)) {
    domText = domText.slice(0, -1);
  }

  // No change -- the DOM is up to date. Nothing to do here.
  if (domText === modelText) {
    // This can be buggy for some Android keyboards because they don't fire
    // standard onkeydown/pressed events and only fired editOnInput
    // so domText is already changed by the browser and ends up being equal
    // to modelText unexpectedly
    return;
  }

  var selection = editorState.getSelection();

  // We'll replace the entire leaf with the text content of the target.
  var targetRange = selection.merge({
    anchorOffset: start,
    focusOffset: end,
    isBackward: false
  });

  var entityKey = block.getEntityAt(start);
  var entity = entityKey && content.getEntity(entityKey);
  var entityType = entity && entity.getMutability();
  var preserveEntity = entityType === 'MUTABLE';

  // Immutable or segmented entities cannot properly be handled by the
  // default browser undo, so we have to use a different change type to
  // force using our internal undo method instead of falling through to the
  // native browser undo.
  var changeType = preserveEntity ? 'spellcheck-change' : 'apply-entity';

  var newContent = DraftModifier.replaceText(content, targetRange, domText, block.getInlineStyleAt(start), preserveEntity ? block.getEntityAt(start) : null);

  var anchorOffset, focusOffset, startOffset, endOffset;

  if (isGecko) {
    // Firefox selection does not change while the context menu is open, so
    // we preserve the anchor and focus values of the DOM selection.
    anchorOffset = domSelection.anchorOffset;
    focusOffset = domSelection.focusOffset;
    startOffset = start + Math.min(anchorOffset, focusOffset);
    endOffset = startOffset + Math.abs(anchorOffset - focusOffset);
    anchorOffset = startOffset;
    focusOffset = endOffset;
  } else {
    // Browsers other than Firefox may adjust DOM selection while the context
    // menu is open, and Safari autocorrect is prone to providing an inaccurate
    // DOM selection. Don't trust it. Instead, use our existing SelectionState
    // and adjust it based on the number of characters changed during the
    // mutation.
    var charDelta = domText.length - modelText.length;
    startOffset = selection.getStartOffset();
    endOffset = selection.getEndOffset();

    anchorOffset = isCollapsed ? endOffset + charDelta : startOffset;
    focusOffset = endOffset + charDelta;
  }

  // Segmented entities are completely or partially removed when their
  // text content changes. For this case we do not want any text to be selected
  // after the change, so we are not merging the selection.
  var contentWithAdjustedDOMSelection = newContent.merge({
    selectionBefore: content.getSelectionAfter(),
    selectionAfter: selection.merge({ anchorOffset: anchorOffset, focusOffset: focusOffset })
  });

  editor.update(EditorState.push(editorState, contentWithAdjustedDOMSelection, changeType));
}

module.exports = editOnInput;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "k+1r":
/*!************************************************!*\
  !*** ./node_modules/lodash/_mapCacheDelete.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getMapData = __webpack_require__(/*! ./_getMapData */ "QkVE");

/**
 * 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;
}

module.exports = mapCacheDelete;


/***/ }),

/***/ "k+aG":
/*!*****************************************!*\
  !*** ./node_modules/hash-base/index.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer
var Transform = __webpack_require__(/*! stream */ "1IWx").Transform
var inherits = __webpack_require__(/*! inherits */ "P7XM")

function throwIfNotStringOrBuffer (val, prefix) {
  if (!Buffer.isBuffer(val) && typeof val !== 'string') {
    throw new TypeError(prefix + ' must be a string or a buffer')
  }
}

function HashBase (blockSize) {
  Transform.call(this)

  this._block = Buffer.allocUnsafe(blockSize)
  this._blockSize = blockSize
  this._blockOffset = 0
  this._length = [0, 0, 0, 0]

  this._finalized = false
}

inherits(HashBase, Transform)

HashBase.prototype._transform = function (chunk, encoding, callback) {
  var error = null
  try {
    this.update(chunk, encoding)
  } catch (err) {
    error = err
  }

  callback(error)
}

HashBase.prototype._flush = function (callback) {
  var error = null
  try {
    this.push(this.digest())
  } catch (err) {
    error = err
  }

  callback(error)
}

HashBase.prototype.update = function (data, encoding) {
  throwIfNotStringOrBuffer(data, 'Data')
  if (this._finalized) throw new Error('Digest already called')
  if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding)

  // consume data
  var block = this._block
  var offset = 0
  while (this._blockOffset + data.length - offset >= this._blockSize) {
    for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]
    this._update()
    this._blockOffset = 0
  }
  while (offset < data.length) block[this._blockOffset++] = data[offset++]

  // update length
  for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
    this._length[j] += carry
    carry = (this._length[j] / 0x0100000000) | 0
    if (carry > 0) this._length[j] -= 0x0100000000 * carry
  }

  return this
}

HashBase.prototype._update = function () {
  throw new Error('_update is not implemented')
}

HashBase.prototype.digest = function (encoding) {
  if (this._finalized) throw new Error('Digest already called')
  this._finalized = true

  var digest = this._digest()
  if (encoding !== undefined) digest = digest.toString(encoding)

  // reset state
  this._block.fill(0)
  this._blockOffset = 0
  for (var i = 0; i < 4; ++i) this._length[i] = 0

  return digest
}

HashBase.prototype._digest = function () {
  throw new Error('_digest is not implemented')
}

module.exports = HashBase


/***/ }),

/***/ "k/8l":
/*!***********************************************************!*\
  !*** ./node_modules/babel-runtime/core-js/is-iterable.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = { "default": __webpack_require__(/*! core-js/library/fn/is-iterable */ "VKFn"), __esModule: true };

/***/ }),

/***/ "k/Ue":
/*!****************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/matrix.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/





exports.init2dArray = function(rowLength, colLength) {
    var array = new Array(rowLength);
    for(var i = 0; i < rowLength; i++) array[i] = new Array(colLength);
    return array;
};

/**
 * transpose a (possibly ragged) 2d array z. inspired by
 * http://stackoverflow.com/questions/17428587/
 * transposing-a-2d-array-in-javascript
 */
exports.transposeRagged = function(z) {
    var maxlen = 0;
    var zlen = z.length;
    var i, j;
    // Maximum row length:
    for(i = 0; i < zlen; i++) maxlen = Math.max(maxlen, z[i].length);

    var t = new Array(maxlen);
    for(i = 0; i < maxlen; i++) {
        t[i] = new Array(zlen);
        for(j = 0; j < zlen; j++) t[i][j] = z[j][i];
    }

    return t;
};

// our own dot function so that we don't need to include numeric
exports.dot = function(x, y) {
    if(!(x.length && y.length) || x.length !== y.length) return null;

    var len = x.length;
    var out;
    var i;

    if(x[0].length) {
        // mat-vec or mat-mat
        out = new Array(len);
        for(i = 0; i < len; i++) out[i] = exports.dot(x[i], y);
    }
    else if(y[0].length) {
        // vec-mat
        var yTranspose = exports.transposeRagged(y);
        out = new Array(yTranspose.length);
        for(i = 0; i < yTranspose.length; i++) out[i] = exports.dot(x, yTranspose[i]);
    }
    else {
        // vec-vec
        out = 0;
        for(i = 0; i < len; i++) out += x[i] * y[i];
    }

    return out;
};

// translate by (x,y)
exports.translationMatrix = function(x, y) {
    return [[1, 0, x], [0, 1, y], [0, 0, 1]];
};

// rotate by alpha around (0,0)
exports.rotationMatrix = function(alpha) {
    var a = alpha * Math.PI / 180;
    return [[Math.cos(a), -Math.sin(a), 0],
            [Math.sin(a), Math.cos(a), 0],
            [0, 0, 1]];
};

// rotate by alpha around (x,y)
exports.rotationXYMatrix = function(a, x, y) {
    return exports.dot(
        exports.dot(exports.translationMatrix(x, y),
                    exports.rotationMatrix(a)),
        exports.translationMatrix(-x, -y));
};

// applies a 2D transformation matrix to either x and y params or an [x,y] array
exports.apply2DTransform = function(transform) {
    return function() {
        var args = arguments;
        if(args.length === 3) {
            args = args[0];
        }// from map
        var xy = arguments.length === 1 ? args[0] : [args[0], args[1]];
        return exports.dot(transform, [xy[0], xy[1], 1]).slice(0, 2);
    };
};

// applies a 2D transformation matrix to an [x1,y1,x2,y2] array (to transform a segment)
exports.apply2DTransform2 = function(transform) {
    var at = exports.apply2DTransform(transform);
    return function(xys) {
        return at(xys.slice(0, 2)).concat(at(xys.slice(2, 4)));
    };
};


/***/ }),

/***/ "k2Qq":
/*!**************************************************************************************!*\
  !*** ./node_modules/@plotly/draft-js-export-html/lib/helpers/normalizeAttributes.js ***!
  \**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});


// Lifted from: https://github.com/facebook/react/blob/master/src/renderers/dom/shared/HTMLDOMPropertyConfig.js
var ATTR_NAME_MAP = {
  acceptCharset: 'accept-charset',
  className: 'class',
  htmlFor: 'for',
  httpEquiv: 'http-equiv'
};

function normalizeAttributes(attributes) {
  if (attributes == null) {
    return attributes;
  }
  var normalized = {};
  var didNormalize = false;
  var _iteratorNormalCompletion = true;
  var _didIteratorError = false;
  var _iteratorError = undefined;

  try {
    for (var _iterator = Object.keys(attributes)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
      var name = _step.value;

      var newName = name;
      if (ATTR_NAME_MAP.hasOwnProperty(name)) {
        newName = ATTR_NAME_MAP[name];
        didNormalize = true;
      }
      normalized[newName] = attributes[name];
    }
  } catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion && _iterator.return) {
        _iterator.return();
      }
    } finally {
      if (_didIteratorError) {
        throw _iteratorError;
      }
    }
  }

  return didNormalize ? normalized : attributes;
}

exports.default = normalizeAttributes;

/***/ }),

/***/ "k3G+":
/*!*************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/connectShapeToLayout.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

exports.default = connectShapeToLayout;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _lib = __webpack_require__(/*! ../lib */ "RXjw");

var _constants = __webpack_require__(/*! ./constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function connectShapeToLayout(WrappedComponent) {
  var ShapeConnectedComponent = function (_Component) {
    _inherits(ShapeConnectedComponent, _Component);

    function ShapeConnectedComponent(props, context) {
      _classCallCheck(this, ShapeConnectedComponent);

      var _this = _possibleConstructorReturn(this, (ShapeConnectedComponent.__proto__ || Object.getPrototypeOf(ShapeConnectedComponent)).call(this, props, context));

      _this.deleteShape = _this.deleteShape.bind(_this);
      _this.updateShape = _this.updateShape.bind(_this);
      _this.setLocals(props, context);
      return _this;
    }

    _createClass(ShapeConnectedComponent, [{
      key: 'componentWillReceiveProps',
      value: function componentWillReceiveProps(nextProps, nextContext) {
        this.setLocals(nextProps, nextContext);
      }
    }, {
      key: 'setLocals',
      value: function setLocals(props, context) {
        var shapeIndex = props.shapeIndex;
        var container = context.container,
            fullContainer = context.fullContainer;


        var shapes = container.shapes || [];
        var fullShapes = fullContainer.shapes || [];
        this.container = shapes[shapeIndex];
        this.fullContainer = fullShapes[shapeIndex];
      }
    }, {
      key: 'getChildContext',
      value: function getChildContext() {
        var _this2 = this;

        return {
          getValObject: function getValObject(attr) {
            return !_this2.context.getValObject ? null : _this2.context.getValObject('shapes[].' + attr);
          },
          updateContainer: this.updateShape,
          deleteContainer: this.deleteShape,
          container: this.container,
          fullContainer: this.fullContainer
        };
      }
    }, {
      key: 'updateShape',
      value: function updateShape(update) {
        var newUpdate = {};
        var shapeIndex = this.props.shapeIndex;

        for (var key in update) {
          var newkey = 'shapes[' + shapeIndex + '].' + key;
          newUpdate[newkey] = update[key];
        }
        this.context.updateContainer(newUpdate);
      }
    }, {
      key: 'deleteShape',
      value: function deleteShape() {
        if (this.context.onUpdate) {
          this.context.onUpdate({
            type: _constants.EDITOR_ACTIONS.DELETE_SHAPE,
            payload: { shapeIndex: this.props.shapeIndex }
          });
        }
      }
    }, {
      key: 'render',
      value: function render() {
        return _react2.default.createElement(WrappedComponent, this.props);
      }
    }]);

    return ShapeConnectedComponent;
  }(_react.Component);

  ShapeConnectedComponent.displayName = 'ShapeConnected' + (0, _lib.getDisplayName)(WrappedComponent);

  ShapeConnectedComponent.propTypes = {
    shapeIndex: _propTypes2.default.number.isRequired
  };

  ShapeConnectedComponent.contextTypes = {
    container: _propTypes2.default.object,
    fullContainer: _propTypes2.default.object,
    data: _propTypes2.default.array,
    onUpdate: _propTypes2.default.func,
    updateContainer: _propTypes2.default.func,
    getValObject: _propTypes2.default.func
  };

  ShapeConnectedComponent.childContextTypes = {
    updateContainer: _propTypes2.default.func,
    deleteContainer: _propTypes2.default.func,
    container: _propTypes2.default.object,
    fullContainer: _propTypes2.default.object,
    getValObject: _propTypes2.default.func
  };

  var plotly_editor_traits = WrappedComponent.plotly_editor_traits;

  ShapeConnectedComponent.plotly_editor_traits = plotly_editor_traits;

  return ShapeConnectedComponent;
}
//# sourceMappingURL=connectShapeToLayout.js.map

/***/ }),

/***/ "k3sf":
/*!*******************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/GroupCreator.js ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _Dropdown = __webpack_require__(/*! ./Dropdown */ "dRXW");

var _Dropdown2 = _interopRequireDefault(_Dropdown);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _Button = __webpack_require__(/*! ../widgets/Button */ "rZxl");

var _Button2 = _interopRequireDefault(_Button);

var _plotlyIcons = __webpack_require__(/*! plotly-icons */ "hwSx");

var _constants = __webpack_require__(/*! ../../lib/constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UnconnectedGroupCreator = function (_Component) {
  _inherits(UnconnectedGroupCreator, _Component);

  function UnconnectedGroupCreator() {
    _classCallCheck(this, UnconnectedGroupCreator);

    return _possibleConstructorReturn(this, (UnconnectedGroupCreator.__proto__ || Object.getPrototypeOf(UnconnectedGroupCreator)).apply(this, arguments));
  }

  _createClass(UnconnectedGroupCreator, [{
    key: 'getAllGroups',
    value: function getAllGroups() {
      var _this2 = this;

      return [].concat(_toConsumableArray(new Set(this.context.data.map(function (t) {
        return t[_this2.props.attr];
      })))).filter(function (g) {
        return Boolean(g);
      });
    }
  }, {
    key: 'canAddGroup',
    value: function canAddGroup() {
      var _props = this.props,
          fullContainer = _props.fullContainer,
          attr = _props.attr;

      var currentGroup = fullContainer[attr];
      var currentTraceIndex = fullContainer.index;

      if (fullContainer.index === _constants.MULTI_VALUED) {
        return this.getAllGroups().length === 0;
      }

      return !currentGroup || this.context.fullData.some(function (d) {
        return d.index !== currentTraceIndex && d[attr] === currentGroup;
      });
    }
  }, {
    key: 'addAndUpdateGroup',
    value: function addAndUpdateGroup() {
      var _this3 = this;

      var allGroups = this.context.fullData.map(function (t) {
        return parseInt(t[_this3.props.attr], 10);
      }).filter(function (n) {
        return Number.isInteger(n);
      });
      // don't want to pass empty array to max
      allGroups.push(0);

      var lastGroupNumber = Math.max.apply(Math, allGroups);

      this.props.updatePlot(lastGroupNumber + 1);
    }
  }, {
    key: 'render',
    value: function render() {
      var _this4 = this;

      var _ = this.context.localize;
      var _props2 = this.props,
          attr = _props2.attr,
          label = _props2.label,
          prefix = _props2.prefix,
          updatePlot = _props2.updatePlot;


      var options = [{ label: _('None'), value: '' }];
      var allGroups = this.getAllGroups();
      allGroups.forEach(function (g) {
        return options.push({ label: prefix + ' ' + g, value: g });
      });
      options.sort(function (a, b) {
        return a.value - b.value;
      });

      var icon = _react2.default.createElement(_plotlyIcons.PlusIcon, null);
      var addButton = this.canAddGroup() ? _react2.default.createElement(_Button2.default, { variant: 'no-text', icon: icon, onClick: function onClick() {
          return _this4.addAndUpdateGroup();
        } }) : _react2.default.createElement(_Button2.default, { variant: 'no-text--disabled', icon: icon, onClick: function onClick() {} });

      return _react2.default.createElement(_Dropdown2.default, {
        label: label,
        attr: attr,
        clearable: false,
        options: options,
        updatePlot: updatePlot,
        extraComponent: addButton
      });
    }
  }]);

  return UnconnectedGroupCreator;
}(_react.Component);

UnconnectedGroupCreator.propTypes = _extends({
  attr: _propTypes2.default.string,
  fullContainer: _propTypes2.default.object,
  prefix: _propTypes2.default.string
}, _Field2.default.propTypes);

UnconnectedGroupCreator.contextTypes = {
  localize: _propTypes2.default.func,
  data: _propTypes2.default.array,
  fullData: _propTypes2.default.array
};

exports.default = (0, _lib.connectToContainer)(UnconnectedGroupCreator);
//# sourceMappingURL=GroupCreator.js.map

/***/ }),

/***/ "k5hY":
/*!*****************************************************!*\
  !*** ./node_modules/react-rangeslider/lib/index.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _Rangeslider = __webpack_require__(/*! ./Rangeslider */ "2DcK");

var _Rangeslider2 = _interopRequireDefault(_Rangeslider);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = _Rangeslider2.default;

/***/ }),

/***/ "k8wc":
/*!*******************************************************************!*\
  !*** ./node_modules/@jupyterlab/completer/lib/kernelconnector.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
/**
 * A kernel connector for completion handlers.
 */
class KernelConnector extends coreutils_1.DataConnector {
    /**
     * Create a new kernel connector for completion requests.
     *
     * @param options - The instatiation options for the kernel connector.
     */
    constructor(options) {
        super();
        this._session = options.session;
    }
    /**
     * Fetch completion requests.
     *
     * @param request - The completion request text and details.
     */
    fetch(request) {
        const kernel = this._session.kernel;
        if (!kernel) {
            return Promise.reject(new Error('No kernel for completion request.'));
        }
        const contents = {
            code: request.text,
            cursor_pos: request.offset
        };
        return kernel.requestComplete(contents).then(msg => {
            const response = msg.content;
            if (response.status !== 'ok') {
                throw new Error('Completion fetch failed to return successfully.');
            }
            return {
                start: response.cursor_start,
                end: response.cursor_end,
                matches: response.matches,
                metadata: response.metadata
            };
        });
    }
}
exports.KernelConnector = KernelConnector;


/***/ }),

/***/ "kAMH":
/*!***********************************************************!*\
  !*** ./node_modules/core-js/library/modules/_is-array.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// 7.2.2 IsArray(argument)
var cof = __webpack_require__(/*! ./_cof */ "a0xu");
module.exports = Array.isArray || function isArray(arg) {
  return cof(arg) == 'Array';
};


/***/ }),

/***/ "kBvz":
/*!******************************************************!*\
  !*** ./node_modules/@phosphor/algorithm/lib/take.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var iter_1 = __webpack_require__(/*! ./iter */ "DMSk");
/**
 * Take a fixed number of items from an iterable.
 *
 * @param object - The iterable or array-like object of interest.
 *
 * @param count - The number of items to take from the iterable.
 *
 * @returns An iterator which yields the specified number of items
 *   from the source iterable.
 *
 * #### Notes
 * The returned iterator will exhaust early if the source iterable
 * contains an insufficient number of items.
 */
function take(object, count) {
    return new TakeIterator(iter_1.iter(object), count);
}
exports.take = take;
/**
 * An iterator which takes a fixed number of items from a source.
 */
var TakeIterator = (function () {
    /**
     * Construct a new take iterator.
     *
     * @param source - The iterator of interest.
     *
     * @param count - The number of items to take from the source.
     */
    function TakeIterator(source, count) {
        this._source = source;
        this._count = count;
    }
    /**
     * Get an iterator over the object's values.
     *
     * @returns An iterator which yields the object's values.
     */
    TakeIterator.prototype.iter = function () {
        return this;
    };
    /**
     * Create an independent clone of the iterator.
     *
     * @returns A new independent clone of the iterator.
     */
    TakeIterator.prototype.clone = function () {
        return new TakeIterator(this._source.clone(), this._count);
    };
    /**
     * Get the next value from the iterator.
     *
     * @returns The next value from the iterator, or `undefined`.
     */
    TakeIterator.prototype.next = function () {
        if (this._count <= 0) {
            return undefined;
        }
        var value = this._source.next();
        if (value === undefined) {
            return undefined;
        }
        this._count--;
        return value;
    };
    return TakeIterator;
}());
exports.TakeIterator = TakeIterator;


/***/ }),

/***/ "kCS6":
/*!*******************************************************!*\
  !*** ./node_modules/react-json-tree/lib/ItemRange.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "QbLZ");

var _extends3 = _interopRequireDefault(_extends2);

var _classCallCheck2 = __webpack_require__(/*! babel-runtime/helpers/classCallCheck */ "iCc5");

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _possibleConstructorReturn2 = __webpack_require__(/*! babel-runtime/helpers/possibleConstructorReturn */ "FYw3");

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __webpack_require__(/*! babel-runtime/helpers/inherits */ "mRg0");

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _JSONArrow = __webpack_require__(/*! ./JSONArrow */ "ktrZ");

var _JSONArrow2 = _interopRequireDefault(_JSONArrow);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var ItemRange = function (_React$Component) {
  (0, _inherits3['default'])(ItemRange, _React$Component);

  function ItemRange(props) {
    (0, _classCallCheck3['default'])(this, ItemRange);

    var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props));

    _this.state = { expanded: false };

    _this.handleClick = _this.handleClick.bind(_this);
    return _this;
  }

  ItemRange.prototype.render = function render() {
    var _props = this.props,
        styling = _props.styling,
        from = _props.from,
        to = _props.to,
        renderChildNodes = _props.renderChildNodes,
        nodeType = _props.nodeType;


    return this.state.expanded ? _react2['default'].createElement(
      'div',
      styling('itemRange', this.state.expanded),
      renderChildNodes(this.props, from, to)
    ) : _react2['default'].createElement(
      'div',
      (0, _extends3['default'])({}, styling('itemRange', this.state.expanded), {
        onClick: this.handleClick
      }),
      _react2['default'].createElement(_JSONArrow2['default'], {
        nodeType: nodeType,
        styling: styling,
        expanded: false,
        onClick: this.handleClick,
        arrowStyle: 'double'
      }),
      from + ' ... ' + to
    );
  };

  ItemRange.prototype.handleClick = function handleClick() {
    this.setState({ expanded: !this.state.expanded });
  };

  return ItemRange;
}(_react2['default'].Component);

ItemRange.propTypes = {
  styling: _propTypes2['default'].func.isRequired,
  from: _propTypes2['default'].number.isRequired,
  to: _propTypes2['default'].number.isRequired,
  renderChildNodes: _propTypes2['default'].func.isRequired,
  nodeType: _propTypes2['default'].string.isRequired
};
exports['default'] = ItemRange;

/***/ }),

/***/ "kD6b":
/*!*********************************************!*\
  !*** ./node_modules/codemirror/mode/r/r.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"));
  else {}
})(function(CodeMirror) {
"use strict";

CodeMirror.registerHelper("wordChars", "r", /[\w.]/);

CodeMirror.defineMode("r", function(config) {
  function wordObj(str) {
    var words = str.split(" "), res = {};
    for (var i = 0; i < words.length; ++i) res[words[i]] = true;
    return res;
  }
  var atoms = wordObj("NULL NA Inf NaN NA_integer_ NA_real_ NA_complex_ NA_character_");
  var builtins = wordObj("list quote bquote eval return call parse deparse");
  var keywords = wordObj("if else repeat while function for in next break");
  var blockkeywords = wordObj("if else repeat while function for");
  var opChars = /[+\-*\/^<>=!&|~$:]/;
  var curPunc;

  function tokenBase(stream, state) {
    curPunc = null;
    var ch = stream.next();
    if (ch == "#") {
      stream.skipToEnd();
      return "comment";
    } else if (ch == "0" && stream.eat("x")) {
      stream.eatWhile(/[\da-f]/i);
      return "number";
    } else if (ch == "." && stream.eat(/\d/)) {
      stream.match(/\d*(?:e[+\-]?\d+)?/);
      return "number";
    } else if (/\d/.test(ch)) {
      stream.match(/\d*(?:\.\d+)?(?:e[+\-]\d+)?L?/);
      return "number";
    } else if (ch == "'" || ch == '"') {
      state.tokenize = tokenString(ch);
      return "string";
    } else if (ch == "`") {
      stream.match(/[^`]+`/);
      return "variable-3";
    } else if (ch == "." && stream.match(/.[.\d]+/)) {
      return "keyword";
    } else if (/[\w\.]/.test(ch) && ch != "_") {
      stream.eatWhile(/[\w\.]/);
      var word = stream.current();
      if (atoms.propertyIsEnumerable(word)) return "atom";
      if (keywords.propertyIsEnumerable(word)) {
        // Block keywords start new blocks, except 'else if', which only starts
        // one new block for the 'if', no block for the 'else'.
        if (blockkeywords.propertyIsEnumerable(word) &&
            !stream.match(/\s*if(\s+|$)/, false))
          curPunc = "block";
        return "keyword";
      }
      if (builtins.propertyIsEnumerable(word)) return "builtin";
      return "variable";
    } else if (ch == "%") {
      if (stream.skipTo("%")) stream.next();
      return "operator variable-2";
    } else if (
        (ch == "<" && stream.eat("-")) ||
        (ch == "<" && stream.match("<-")) ||
        (ch == "-" && stream.match(/>>?/))
      ) {
      return "operator arrow";
    } else if (ch == "=" && state.ctx.argList) {
      return "arg-is";
    } else if (opChars.test(ch)) {
      if (ch == "$") return "operator dollar";
      stream.eatWhile(opChars);
      return "operator";
    } else if (/[\(\){}\[\];]/.test(ch)) {
      curPunc = ch;
      if (ch == ";") return "semi";
      return null;
    } else {
      return null;
    }
  }

  function tokenString(quote) {
    return function(stream, state) {
      if (stream.eat("\\")) {
        var ch = stream.next();
        if (ch == "x") stream.match(/^[a-f0-9]{2}/i);
        else if ((ch == "u" || ch == "U") && stream.eat("{") && stream.skipTo("}")) stream.next();
        else if (ch == "u") stream.match(/^[a-f0-9]{4}/i);
        else if (ch == "U") stream.match(/^[a-f0-9]{8}/i);
        else if (/[0-7]/.test(ch)) stream.match(/^[0-7]{1,2}/);
        return "string-2";
      } else {
        var next;
        while ((next = stream.next()) != null) {
          if (next == quote) { state.tokenize = tokenBase; break; }
          if (next == "\\") { stream.backUp(1); break; }
        }
        return "string";
      }
    };
  }

  var ALIGN_YES = 1, ALIGN_NO = 2, BRACELESS = 4

  function push(state, type, stream) {
    state.ctx = {type: type,
                 indent: state.indent,
                 flags: 0,
                 column: stream.column(),
                 prev: state.ctx};
  }
  function setFlag(state, flag) {
    var ctx = state.ctx
    state.ctx = {type: ctx.type,
                 indent: ctx.indent,
                 flags: ctx.flags | flag,
                 column: ctx.column,
                 prev: ctx.prev}
  }
  function pop(state) {
    state.indent = state.ctx.indent;
    state.ctx = state.ctx.prev;
  }

  return {
    startState: function() {
      return {tokenize: tokenBase,
              ctx: {type: "top",
                    indent: -config.indentUnit,
                    flags: ALIGN_NO},
              indent: 0,
              afterIdent: false};
    },

    token: function(stream, state) {
      if (stream.sol()) {
        if ((state.ctx.flags & 3) == 0) state.ctx.flags |= ALIGN_NO
        if (state.ctx.flags & BRACELESS) pop(state)
        state.indent = stream.indentation();
      }
      if (stream.eatSpace()) return null;
      var style = state.tokenize(stream, state);
      if (style != "comment" && (state.ctx.flags & ALIGN_NO) == 0) setFlag(state, ALIGN_YES)

      if ((curPunc == ";" || curPunc == "{" || curPunc == "}") && state.ctx.type == "block") pop(state);
      if (curPunc == "{") push(state, "}", stream);
      else if (curPunc == "(") {
        push(state, ")", stream);
        if (state.afterIdent) state.ctx.argList = true;
      }
      else if (curPunc == "[") push(state, "]", stream);
      else if (curPunc == "block") push(state, "block", stream);
      else if (curPunc == state.ctx.type) pop(state);
      else if (state.ctx.type == "block" && style != "comment") setFlag(state, BRACELESS)
      state.afterIdent = style == "variable" || style == "keyword";
      return style;
    },

    indent: function(state, textAfter) {
      if (state.tokenize != tokenBase) return 0;
      var firstChar = textAfter && textAfter.charAt(0), ctx = state.ctx,
          closing = firstChar == ctx.type;
      if (ctx.flags & BRACELESS) ctx = ctx.prev
      if (ctx.type == "block") return ctx.indent + (firstChar == "{" ? 0 : config.indentUnit);
      else if (ctx.flags & ALIGN_YES) return ctx.column + (closing ? 0 : 1);
      else return ctx.indent + (closing ? 0 : config.indentUnit);
    },

    lineComment: "#"
  };
});

CodeMirror.defineMIME("text/x-rsrc", "r");

});


/***/ }),

/***/ "kDkJ":
/*!**************************************************!*\
  !*** ./node_modules/draft-js/lib/editOnPaste.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule editOnPaste
 * @format
 * 
 */



var BlockMapBuilder = __webpack_require__(/*! ./BlockMapBuilder */ "YeVe");
var CharacterMetadata = __webpack_require__(/*! ./CharacterMetadata */ "lFJn");
var DataTransfer = __webpack_require__(/*! fbjs/lib/DataTransfer */ "QvxS");
var DraftModifier = __webpack_require__(/*! ./DraftModifier */ "fyOY");
var DraftPasteProcessor = __webpack_require__(/*! ./DraftPasteProcessor */ "PQhE");
var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");
var RichTextEditorUtil = __webpack_require__(/*! ./RichTextEditorUtil */ "Nx4+");

var getEntityKeyForSelection = __webpack_require__(/*! ./getEntityKeyForSelection */ "hpMJ");
var getTextContentFromFiles = __webpack_require__(/*! ./getTextContentFromFiles */ "HKS5");
var isEventHandled = __webpack_require__(/*! ./isEventHandled */ "T401");
var splitTextIntoTextBlocks = __webpack_require__(/*! ./splitTextIntoTextBlocks */ "RK+W");

/**
 * Paste content.
 */
function editOnPaste(editor, e) {
  e.preventDefault();
  var data = new DataTransfer(e.clipboardData);

  // Get files, unless this is likely to be a string the user wants inline.
  if (!data.isRichText()) {
    var files = data.getFiles();
    var defaultFileText = data.getText();
    if (files.length > 0) {
      // Allow customized paste handling for images, etc. Otherwise, fall
      // through to insert text contents into the editor.
      if (editor.props.handlePastedFiles && isEventHandled(editor.props.handlePastedFiles(files))) {
        return;
      }

      getTextContentFromFiles(files, function ( /*string*/fileText) {
        fileText = fileText || defaultFileText;
        if (!fileText) {
          return;
        }

        var editorState = editor._latestEditorState;
        var blocks = splitTextIntoTextBlocks(fileText);
        var character = CharacterMetadata.create({
          style: editorState.getCurrentInlineStyle(),
          entity: getEntityKeyForSelection(editorState.getCurrentContent(), editorState.getSelection())
        });
        var currentBlockType = RichTextEditorUtil.getCurrentBlockType(editorState);

        var text = DraftPasteProcessor.processText(blocks, character, currentBlockType);
        var fragment = BlockMapBuilder.createFromArray(text);

        var withInsertedText = DraftModifier.replaceWithFragment(editorState.getCurrentContent(), editorState.getSelection(), fragment);

        editor.update(EditorState.push(editorState, withInsertedText, 'insert-fragment'));
      });

      return;
    }
  }

  var textBlocks = [];
  var text = data.getText();
  var html = data.getHTML();
  var editorState = editor._latestEditorState;

  if (editor.props.handlePastedText && isEventHandled(editor.props.handlePastedText(text, html, editorState))) {
    return;
  }

  if (text) {
    textBlocks = splitTextIntoTextBlocks(text);
  }

  if (!editor.props.stripPastedStyles) {
    // If the text from the paste event is rich content that matches what we
    // already have on the internal clipboard, assume that we should just use
    // the clipboard fragment for the paste. This will allow us to preserve
    // styling and entities, if any are present. Note that newlines are
    // stripped during comparison -- this is because copy/paste within the
    // editor in Firefox and IE will not include empty lines. The resulting
    // paste will preserve the newlines correctly.
    var internalClipboard = editor.getClipboard();
    if (data.isRichText() && internalClipboard) {
      if (
      // If the editorKey is present in the pasted HTML, it should be safe to
      // assume this is an internal paste.
      html.indexOf(editor.getEditorKey()) !== -1 ||
      // The copy may have been made within a single block, in which case the
      // editor key won't be part of the paste. In this case, just check
      // whether the pasted text matches the internal clipboard.
      textBlocks.length === 1 && internalClipboard.size === 1 && internalClipboard.first().getText() === text) {
        editor.update(insertFragment(editor._latestEditorState, internalClipboard));
        return;
      }
    } else if (internalClipboard && data.types.includes('com.apple.webarchive') && !data.types.includes('text/html') && areTextBlocksAndClipboardEqual(textBlocks, internalClipboard)) {
      // Safari does not properly store text/html in some cases.
      // Use the internalClipboard if present and equal to what is on
      // the clipboard. See https://bugs.webkit.org/show_bug.cgi?id=19893.
      editor.update(insertFragment(editor._latestEditorState, internalClipboard));
      return;
    }

    // If there is html paste data, try to parse that.
    if (html) {
      var htmlFragment = DraftPasteProcessor.processHTML(html, editor.props.blockRenderMap);
      if (htmlFragment) {
        var contentBlocks = htmlFragment.contentBlocks,
            entityMap = htmlFragment.entityMap;

        if (contentBlocks) {
          var htmlMap = BlockMapBuilder.createFromArray(contentBlocks);
          editor.update(insertFragment(editor._latestEditorState, htmlMap, entityMap));
          return;
        }
      }
    }

    // Otherwise, create a new fragment from our pasted text. Also
    // empty the internal clipboard, since it's no longer valid.
    editor.setClipboard(null);
  }

  if (textBlocks.length) {
    var character = CharacterMetadata.create({
      style: editorState.getCurrentInlineStyle(),
      entity: getEntityKeyForSelection(editorState.getCurrentContent(), editorState.getSelection())
    });

    var currentBlockType = RichTextEditorUtil.getCurrentBlockType(editorState);

    var textFragment = DraftPasteProcessor.processText(textBlocks, character, currentBlockType);

    var textMap = BlockMapBuilder.createFromArray(textFragment);
    editor.update(insertFragment(editor._latestEditorState, textMap));
  }
}

function insertFragment(editorState, fragment, entityMap) {
  var newContent = DraftModifier.replaceWithFragment(editorState.getCurrentContent(), editorState.getSelection(), fragment);
  // TODO: merge the entity map once we stop using DraftEntity
  // like this:
  // const mergedEntityMap = newContent.getEntityMap().merge(entityMap);

  return EditorState.push(editorState, newContent.set('entityMap', entityMap), 'insert-fragment');
}

function areTextBlocksAndClipboardEqual(textBlocks, blockMap) {
  return textBlocks.length === blockMap.size && blockMap.valueSeq().every(function (block, ii) {
    return block.getText() === textBlocks[ii];
  });
}

module.exports = editOnPaste;

/***/ }),

/***/ "kEOa":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/bn.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var symbolMap = {
    '1': '১',
    '2': '২',
    '3': '৩',
    '4': '৪',
    '5': '৫',
    '6': '৬',
    '7': '৭',
    '8': '৮',
    '9': '৯',
    '0': '০'
},
numberMap = {
    '১': '1',
    '২': '2',
    '৩': '3',
    '৪': '4',
    '৫': '5',
    '৬': '6',
    '৭': '7',
    '৮': '8',
    '৯': '9',
    '০': '0'
};

var bn = moment.defineLocale('bn', {
    months : 'জানুয়ারী_ফেব্রুয়ারি_মার্চ_এপ্রিল_মে_জুন_জুলাই_আগস্ট_সেপ্টেম্বর_অক্টোবর_নভেম্বর_ডিসেম্বর'.split('_'),
    monthsShort : 'জানু_ফেব_মার্চ_এপ্র_মে_জুন_জুল_আগ_সেপ্ট_অক্টো_নভে_ডিসে'.split('_'),
    weekdays : 'রবিবার_সোমবার_মঙ্গলবার_বুধবার_বৃহস্পতিবার_শুক্রবার_শনিবার'.split('_'),
    weekdaysShort : 'রবি_সোম_মঙ্গল_বুধ_বৃহস্পতি_শুক্র_শনি'.split('_'),
    weekdaysMin : 'রবি_সোম_মঙ্গ_বুধ_বৃহঃ_শুক্র_শনি'.split('_'),
    longDateFormat : {
        LT : 'A h:mm সময়',
        LTS : 'A h:mm:ss সময়',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY, A h:mm সময়',
        LLLL : 'dddd, D MMMM YYYY, A h:mm সময়'
    },
    calendar : {
        sameDay : '[আজ] LT',
        nextDay : '[আগামীকাল] LT',
        nextWeek : 'dddd, LT',
        lastDay : '[গতকাল] LT',
        lastWeek : '[গত] dddd, LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : '%s পরে',
        past : '%s আগে',
        s : 'কয়েক সেকেন্ড',
        ss : '%d সেকেন্ড',
        m : 'এক মিনিট',
        mm : '%d মিনিট',
        h : 'এক ঘন্টা',
        hh : '%d ঘন্টা',
        d : 'এক দিন',
        dd : '%d দিন',
        M : 'এক মাস',
        MM : '%d মাস',
        y : 'এক বছর',
        yy : '%d বছর'
    },
    preparse: function (string) {
        return string.replace(/[১২৩৪৫৬৭৮৯০]/g, function (match) {
            return numberMap[match];
        });
    },
    postformat: function (string) {
        return string.replace(/\d/g, function (match) {
            return symbolMap[match];
        });
    },
    meridiemParse: /রাত|সকাল|দুপুর|বিকাল|রাত/,
    meridiemHour : function (hour, meridiem) {
        if (hour === 12) {
            hour = 0;
        }
        if ((meridiem === 'রাত' && hour >= 4) ||
                (meridiem === 'দুপুর' && hour < 5) ||
                meridiem === 'বিকাল') {
            return hour + 12;
        } else {
            return hour;
        }
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 4) {
            return 'রাত';
        } else if (hour < 10) {
            return 'সকাল';
        } else if (hour < 17) {
            return 'দুপুর';
        } else if (hour < 20) {
            return 'বিকাল';
        } else {
            return 'রাত';
        }
    },
    week : {
        dow : 0, // Sunday is the first day of the week.
        doy : 6  // The week that contains Jan 1st is the first week of the year.
    }
});

return bn;

})));


/***/ }),

/***/ "kJIm":
/*!**************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/extend.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




var isPlainObject = __webpack_require__(/*! ./is_plain_object.js */ "E4V0");
var isArray = Array.isArray;

function primitivesLoopSplice(source, target) {
    var i, value;
    for(i = 0; i < source.length; i++) {
        value = source[i];
        if(value !== null && typeof(value) === 'object') {
            return false;
        }
        if(value !== void(0)) {
            target[i] = value;
        }
    }
    return true;
}

exports.extendFlat = function() {
    return _extend(arguments, false, false, false);
};

exports.extendDeep = function() {
    return _extend(arguments, true, false, false);
};

exports.extendDeepAll = function() {
    return _extend(arguments, true, true, false);
};

exports.extendDeepNoArrays = function() {
    return _extend(arguments, true, false, true);
};

/*
 * Inspired by https://github.com/justmoon/node-extend/blob/master/index.js
 * All credit to the jQuery authors for perfecting this amazing utility.
 *
 * API difference with jQuery version:
 * - No optional boolean (true -> deep extend) first argument,
 *   use `extendFlat` for first-level only extend and
 *   use `extendDeep` for a deep extend.
 *
 * Other differences with jQuery version:
 * - Uses a modern (and faster) isPlainObject routine.
 * - Expected to work with object {} and array [] arguments only.
 * - Does not check for circular structure.
 *   FYI: jQuery only does a check across one level.
 *   Warning: this might result in infinite loops.
 *
 */
function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) {
    var target = inputs[0];
    var length = inputs.length;

    var input, key, src, copy, copyIsArray, clone, allPrimitives;

    // TODO does this do the right thing for typed arrays?

    if(length === 2 && isArray(target) && isArray(inputs[1]) && target.length === 0) {

        allPrimitives = primitivesLoopSplice(inputs[1], target);

        if(allPrimitives) {
            return target;
        } else {
            target.splice(0, target.length); // reset target and continue to next block
        }
    }

    for(var i = 1; i < length; i++) {
        input = inputs[i];

        for(key in input) {
            src = target[key];
            copy = input[key];

            // Stop early and just transfer the array if array copies are disallowed:
            if(noArrayCopies && isArray(copy)) {
                target[key] = copy;
            }

            // recurse if we're merging plain objects or arrays
            else if(isDeep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
                if(copyIsArray) {
                    copyIsArray = false;
                    clone = src && isArray(src) ? src : [];
                } else {
                    clone = src && isPlainObject(src) ? src : {};
                }

                // never move original objects, clone them
                target[key] = _extend([clone, copy], isDeep, keepAllKeys, noArrayCopies);
            }

            // don't bring in undefined values, except for extendDeepAll
            else if(typeof copy !== 'undefined' || keepAllKeys) {
                target[key] = copy;
            }
        }
    }

    return target;
}


/***/ }),

/***/ "kL29":
/*!**********************************************************!*\
  !*** ./node_modules/@jupyterlab/docmanager/lib/index.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(__webpack_require__(/*! ./dialogs */ "umhg"));
__export(__webpack_require__(/*! ./manager */ "vMpn"));
__export(__webpack_require__(/*! ./savehandler */ "5dP4"));
__export(__webpack_require__(/*! ./widgetmanager */ "q/j9"));


/***/ }),

/***/ "kOpN":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/zh-tw.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var zhTw = moment.defineLocale('zh-tw', {
    months : '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
    monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
    weekdays : '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
    weekdaysShort : '週日_週一_週二_週三_週四_週五_週六'.split('_'),
    weekdaysMin : '日_一_二_三_四_五_六'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'YYYY/MM/DD',
        LL : 'YYYY年M月D日',
        LLL : 'YYYY年M月D日 HH:mm',
        LLLL : 'YYYY年M月D日dddd HH:mm',
        l : 'YYYY/M/D',
        ll : 'YYYY年M月D日',
        lll : 'YYYY年M月D日 HH:mm',
        llll : 'YYYY年M月D日dddd HH:mm'
    },
    meridiemParse: /凌晨|早上|上午|中午|下午|晚上/,
    meridiemHour : function (hour, meridiem) {
        if (hour === 12) {
            hour = 0;
        }
        if (meridiem === '凌晨' || meridiem === '早上' || meridiem === '上午') {
            return hour;
        } else if (meridiem === '中午') {
            return hour >= 11 ? hour : hour + 12;
        } else if (meridiem === '下午' || meridiem === '晚上') {
            return hour + 12;
        }
    },
    meridiem : function (hour, minute, isLower) {
        var hm = hour * 100 + minute;
        if (hm < 600) {
            return '凌晨';
        } else if (hm < 900) {
            return '早上';
        } else if (hm < 1130) {
            return '上午';
        } else if (hm < 1230) {
            return '中午';
        } else if (hm < 1800) {
            return '下午';
        } else {
            return '晚上';
        }
    },
    calendar : {
        sameDay : '[今天]LT',
        nextDay : '[明天]LT',
        nextWeek : '[下]ddddLT',
        lastDay : '[昨天]LT',
        lastWeek : '[上]ddddLT',
        sameElse : 'L'
    },
    dayOfMonthOrdinalParse: /\d{1,2}(日|月|週)/,
    ordinal : function (number, period) {
        switch (period) {
            case 'd' :
            case 'D' :
            case 'DDD' :
                return number + '日';
            case 'M' :
                return number + '月';
            case 'w' :
            case 'W' :
                return number + '週';
            default :
                return number;
        }
    },
    relativeTime : {
        future : '%s內',
        past : '%s前',
        s : '幾秒',
        ss : '%d 秒',
        m : '1 分鐘',
        mm : '%d 分鐘',
        h : '1 小時',
        hh : '%d 小時',
        d : '1 天',
        dd : '%d 天',
        M : '1 個月',
        MM : '%d 個月',
        y : '1 年',
        yy : '%d 年'
    }
});

return zhTw;

})));


/***/ }),

/***/ "kTiW":
/*!***********************************************************!*\
  !*** ./node_modules/core-js/library/modules/_redefine.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(/*! ./_hide */ "NegM");


/***/ }),

/***/ "kVK+":
/*!***************************************!*\
  !*** ./node_modules/ieee754/index.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports) {

exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  var e, m
  var eLen = (nBytes * 8) - mLen - 1
  var eMax = (1 << eLen) - 1
  var eBias = eMax >> 1
  var nBits = -7
  var i = isLE ? (nBytes - 1) : 0
  var d = isLE ? -1 : 1
  var s = buffer[offset + i]

  i += d

  e = s & ((1 << (-nBits)) - 1)
  s >>= (-nBits)
  nBits += eLen
  for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  m = e & ((1 << (-nBits)) - 1)
  e >>= (-nBits)
  nBits += mLen
  for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  if (e === 0) {
    e = 1 - eBias
  } else if (e === eMax) {
    return m ? NaN : ((s ? -1 : 1) * Infinity)
  } else {
    m = m + Math.pow(2, mLen)
    e = e - eBias
  }
  return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}

exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  var e, m, c
  var eLen = (nBytes * 8) - mLen - 1
  var eMax = (1 << eLen) - 1
  var eBias = eMax >> 1
  var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  var i = isLE ? 0 : (nBytes - 1)
  var d = isLE ? 1 : -1
  var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0

  value = Math.abs(value)

  if (isNaN(value) || value === Infinity) {
    m = isNaN(value) ? 1 : 0
    e = eMax
  } else {
    e = Math.floor(Math.log(value) / Math.LN2)
    if (value * (c = Math.pow(2, -e)) < 1) {
      e--
      c *= 2
    }
    if (e + eBias >= 1) {
      value += rt / c
    } else {
      value += rt * Math.pow(2, 1 - eBias)
    }
    if (value * c >= 2) {
      e++
      c /= 2
    }

    if (e + eBias >= eMax) {
      m = 0
      e = eMax
    } else if (e + eBias >= 1) {
      m = ((value * c) - 1) * Math.pow(2, mLen)
      e = e + eBias
    } else {
      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
      e = 0
    }
  }

  for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}

  e = (e << mLen) | m
  eLen += mLen
  for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}

  buffer[offset + i - d] |= s * 128
}


/***/ }),

/***/ "kWb8":
/*!************************************************!*\
  !*** ./node_modules/entities/maps/legacy.json ***!
  \************************************************/
/*! exports provided: Aacute, aacute, Acirc, acirc, acute, AElig, aelig, Agrave, agrave, amp, AMP, Aring, aring, Atilde, atilde, Auml, auml, brvbar, Ccedil, ccedil, cedil, cent, copy, COPY, curren, deg, divide, Eacute, eacute, Ecirc, ecirc, Egrave, egrave, ETH, eth, Euml, euml, frac12, frac14, frac34, gt, GT, Iacute, iacute, Icirc, icirc, iexcl, Igrave, igrave, iquest, Iuml, iuml, laquo, lt, LT, macr, micro, middot, nbsp, not, Ntilde, ntilde, Oacute, oacute, Ocirc, ocirc, Ograve, ograve, ordf, ordm, Oslash, oslash, Otilde, otilde, Ouml, ouml, para, plusmn, pound, quot, QUOT, raquo, reg, REG, sect, shy, sup1, sup2, sup3, szlig, THORN, thorn, times, Uacute, uacute, Ucirc, ucirc, Ugrave, ugrave, uml, Uuml, uuml, Yacute, yacute, yen, yuml, default */
/***/ (function(module) {

module.exports = {"Aacute":"Á","aacute":"á","Acirc":"Â","acirc":"â","acute":"´","AElig":"Æ","aelig":"æ","Agrave":"À","agrave":"à","amp":"&","AMP":"&","Aring":"Å","aring":"å","Atilde":"Ã","atilde":"ã","Auml":"Ä","auml":"ä","brvbar":"¦","Ccedil":"Ç","ccedil":"ç","cedil":"¸","cent":"¢","copy":"©","COPY":"©","curren":"¤","deg":"°","divide":"÷","Eacute":"É","eacute":"é","Ecirc":"Ê","ecirc":"ê","Egrave":"È","egrave":"è","ETH":"Ð","eth":"ð","Euml":"Ë","euml":"ë","frac12":"½","frac14":"¼","frac34":"¾","gt":">","GT":">","Iacute":"Í","iacute":"í","Icirc":"Î","icirc":"î","iexcl":"¡","Igrave":"Ì","igrave":"ì","iquest":"¿","Iuml":"Ï","iuml":"ï","laquo":"«","lt":"<","LT":"<","macr":"¯","micro":"µ","middot":"·","nbsp":" ","not":"¬","Ntilde":"Ñ","ntilde":"ñ","Oacute":"Ó","oacute":"ó","Ocirc":"Ô","ocirc":"ô","Ograve":"Ò","ograve":"ò","ordf":"ª","ordm":"º","Oslash":"Ø","oslash":"ø","Otilde":"Õ","otilde":"õ","Ouml":"Ö","ouml":"ö","para":"¶","plusmn":"±","pound":"£","quot":"\"","QUOT":"\"","raquo":"»","reg":"®","REG":"®","sect":"§","shy":"­","sup1":"¹","sup2":"²","sup3":"³","szlig":"ß","THORN":"Þ","thorn":"þ","times":"×","Uacute":"Ú","uacute":"ú","Ucirc":"Û","ucirc":"û","Ugrave":"Ù","ugrave":"ù","uml":"¨","Uuml":"Ü","uuml":"ü","Yacute":"Ý","yacute":"ý","yen":"¥","yuml":"ÿ"};

/***/ }),

/***/ "kWjT":
/*!************************************************************!*\
  !*** ./node_modules/draft-js/lib/moveSelectionBackward.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule moveSelectionBackward
 * @format
 * 
 */



/**
 * Given a collapsed selection, move the focus `maxDistance` backward within
 * the selected block. If the selection will go beyond the start of the block,
 * move focus to the end of the previous block, but no further.
 *
 * This function is not Unicode-aware, so surrogate pairs will be treated
 * as having length 2.
 */
function moveSelectionBackward(editorState, maxDistance) {
  var selection = editorState.getSelection();
  var content = editorState.getCurrentContent();
  var key = selection.getStartKey();
  var offset = selection.getStartOffset();

  var focusKey = key;
  var focusOffset = 0;

  if (maxDistance > offset) {
    var keyBefore = content.getKeyBefore(key);
    if (keyBefore == null) {
      focusKey = key;
    } else {
      focusKey = keyBefore;
      var blockBefore = content.getBlockForKey(keyBefore);
      focusOffset = blockBefore.getText().length;
    }
  } else {
    focusOffset = offset - maxDistance;
  }

  return selection.merge({
    focusKey: focusKey,
    focusOffset: focusOffset,
    isBackward: true
  });
}

module.exports = moveSelectionBackward;

/***/ }),

/***/ "kZHY":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/attachments/lib/model.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const observables_1 = __webpack_require__(/*! @jupyterlab/observables */ "V4vH");
const rendermime_1 = __webpack_require__(/*! @jupyterlab/rendermime */ "Towz");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
/**
 * The default implementation of the IAttachmentsModel.
 */
class AttachmentsModel {
    /**
     * Construct a new observable outputs instance.
     */
    constructor(options = {}) {
        this._map = new observables_1.ObservableMap();
        this._isDisposed = false;
        this._stateChanged = new signaling_1.Signal(this);
        this._changed = new signaling_1.Signal(this);
        this._modelDB = null;
        this._serialized = null;
        this._changeGuard = false;
        this.contentFactory =
            options.contentFactory || AttachmentsModel.defaultContentFactory;
        if (options.values) {
            for (let key of Object.keys(options.values)) {
                this.set(key, options.values[key]);
            }
        }
        this._map.changed.connect(this._onMapChanged, this);
        // If we are given a IModelDB, keep an up-to-date
        // serialized copy of the AttachmentsModel in it.
        if (options.modelDB) {
            this._modelDB = options.modelDB;
            this._serialized = this._modelDB.createValue('attachments');
            if (this._serialized.get()) {
                this.fromJSON(this._serialized.get());
            }
            else {
                this._serialized.set(this.toJSON());
            }
            this._serialized.changed.connect(this._onSerializedChanged, this);
        }
    }
    /**
     * A signal emitted when the model state changes.
     */
    get stateChanged() {
        return this._stateChanged;
    }
    /**
     * A signal emitted when the model changes.
     */
    get changed() {
        return this._changed;
    }
    /**
     * The keys of the attachments in the model.
     */
    get keys() {
        return this._map.keys();
    }
    /**
     * Get the length of the items in the model.
     */
    get length() {
        return this._map.keys().length;
    }
    /**
     * Test whether the model is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources used by the model.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        this._map.dispose();
        signaling_1.Signal.clearData(this);
    }
    /**
     * Whether the specified key is set.
     */
    has(key) {
        return this._map.has(key);
    }
    /**
     * Get an item at the specified key.
     */
    get(key) {
        return this._map.get(key);
    }
    /**
     * Set the value at the specified key.
     */
    set(key, value) {
        // Normalize stream data.
        let item = this._createItem({ value });
        this._map.set(key, item);
    }
    /**
     * Clear all of the attachments.
     */
    clear() {
        this._map.values().forEach((item) => {
            item.dispose();
        });
        this._map.clear();
    }
    /**
     * Deserialize the model from JSON.
     *
     * #### Notes
     * This will clear any existing data.
     */
    fromJSON(values) {
        this.clear();
        Object.keys(values).forEach(key => {
            this.set(key, values[key]);
        });
    }
    /**
     * Serialize the model to JSON.
     */
    toJSON() {
        let ret = {};
        for (let key of this._map.keys()) {
            ret[key] = this._map.get(key).toJSON();
        }
        return ret;
    }
    /**
     * Create an attachment item and hook up its signals.
     */
    _createItem(options) {
        let factory = this.contentFactory;
        let item = factory.createAttachmentModel(options);
        item.changed.connect(this._onGenericChange, this);
        return item;
    }
    /**
     * Handle a change to the list.
     */
    _onMapChanged(sender, args) {
        if (this._serialized && !this._changeGuard) {
            this._changeGuard = true;
            this._serialized.set(this.toJSON());
            this._changeGuard = false;
        }
        this._changed.emit(args);
        this._stateChanged.emit(void 0);
    }
    /**
     * If the serialized version of the outputs have changed due to a remote
     * action, then update the model accordingly.
     */
    _onSerializedChanged(sender, args) {
        if (!this._changeGuard) {
            this._changeGuard = true;
            this.fromJSON(args.newValue);
            this._changeGuard = false;
        }
    }
    /**
     * Handle a change to an item.
     */
    _onGenericChange() {
        this._stateChanged.emit(void 0);
    }
}
exports.AttachmentsModel = AttachmentsModel;
/**
 * The namespace for AttachmentsModel class statics.
 */
(function (AttachmentsModel) {
    /**
     * The default implementation of a `IAttachemntsModel.IContentFactory`.
     */
    class ContentFactory {
        /**
         * Create an attachment model.
         */
        createAttachmentModel(options) {
            return new rendermime_1.AttachmentModel(options);
        }
    }
    AttachmentsModel.ContentFactory = ContentFactory;
    /**
     * The default attachment model factory.
     */
    AttachmentsModel.defaultContentFactory = new ContentFactory();
})(AttachmentsModel = exports.AttachmentsModel || (exports.AttachmentsModel = {}));
/**
 * A resolver for cell attachments 'attchment:filename'.
 *
 * Will resolve to a data: url.
 */
class AttachmentsResolver {
    /**
     * Create an attachments resolver object.
     */
    constructor(options) {
        this._parent = options.parent || null;
        this._model = options.model;
    }
    /**
     * Resolve a relative url to a correct server path.
     */
    resolveUrl(url) {
        if (this._parent && !url.startsWith('attachment:')) {
            return this._parent.resolveUrl(url);
        }
        return Promise.resolve(url);
    }
    /**
     * Get the download url of a given absolute server path.
     */
    getDownloadUrl(path) {
        if (this._parent && !path.startsWith('attachment:')) {
            return this._parent.getDownloadUrl(path);
        }
        // Return a data URL with the data of the url
        const key = path.slice('attachment:'.length);
        if (!this._model.has(key)) {
            // Resolve with unprocessed path, to show as broken image
            return Promise.resolve(path);
        }
        const { data } = this._model.get(key);
        const mimeType = Object.keys(data)[0];
        // Only support known safe types:
        if (rendermime_1.imageRendererFactory.mimeTypes.indexOf(mimeType) === -1) {
            return Promise.reject(`Cannot render unknown image mime type "${mimeType}".`);
        }
        const dataUrl = `data:${mimeType};base64,${data[mimeType]}`;
        return Promise.resolve(dataUrl);
    }
    /**
     * Whether the URL should be handled by the resolver
     * or not.
     */
    isLocal(url) {
        if (this._parent && !url.startsWith('attachment:')) {
            return this._parent.isLocal(url);
        }
        return true;
    }
}
exports.AttachmentsResolver = AttachmentsResolver;


/***/ }),

/***/ "kamm":
/*!**********************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/apputils/style/commandpalette.css ***!
  \**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n/*-----------------------------------------------------------------------------\n| Variables\n|----------------------------------------------------------------------------*/\n\n:root {\n  --jp-private-commandpalette-search-height: 28px;\n}\n\n/*-----------------------------------------------------------------------------\n| Overall styles\n|----------------------------------------------------------------------------*/\n\n.p-CommandPalette {\n  padding-bottom: 0px;\n  color: var(--jp-ui-font-color1);\n  background: var(--jp-layout-color1);\n  /* This is needed so that all font sizing of children done in ems is\n   * relative to this base size */\n  font-size: var(--jp-ui-font-size1);\n}\n\n/*-----------------------------------------------------------------------------\n| Search\n|----------------------------------------------------------------------------*/\n\n.p-CommandPalette-search {\n  padding: 8px;\n  background-color: var(--jp-layout-color1);\n  z-index: 2;\n}\n\n.p-CommandPalette-wrapper {\n  overflow: overlay;\n  padding: 0px 8px;\n  border: 1px solid var(--jp-border-color0);\n  background-color: var(--jp-input-active-background);\n  height: 30px;\n}\n\n.p-CommandPalette.p-mod-focused .p-CommandPalette-wrapper {\n  border: var(--jp-border-width) solid var(--md-blue-500);\n  box-shadow: inset 0 0 4px var(--md-blue-300);\n}\n\n.p-CommandPalette-wrapper::after {\n  content: ' ';\n  color: white;\n  background-color: var(--jp-brand-color1);\n  position: absolute;\n  top: 8px;\n  right: 8px;\n  height: 32px;\n  width: 12px;\n  padding: 0px 12px;\n  background-image: var(--jp-icon-search-white);\n  background-size: 20px;\n  background-repeat: no-repeat;\n  background-position: center;\n}\n\n.p-CommandPalette-input {\n  background: transparent;\n  width: calc(100% - 18px);\n  float: left;\n  border: none;\n  outline: none;\n  font-size: var(--jp-ui-font-size1);\n  color: var(--jp-ui-font-color0);\n  line-height: var(--jp-private-commandpalette-search-height);\n}\n\n.p-CommandPalette-input::-webkit-input-placeholder {\n  color: var(--jp-ui-font-color3);\n  font-size: var(--jp-ui-font-size1);\n}\n\n.p-CommandPalette-input::-moz-placeholder {\n  color: var(--jp-ui-font-color3);\n  font-size: var(--jp-ui-font-size1);\n}\n\n.p-CommandPalette-input:-ms-input-placeholder {\n  color: var(--jp-ui-font-color3);\n  font-size: var(--jp-ui-font-size1);\n}\n\n/*-----------------------------------------------------------------------------\n| Results\n|----------------------------------------------------------------------------*/\n\n.p-CommandPalette-header {\n  padding: 8px 0 8px 22px;\n  color: var(--jp-ui-font-color1);\n  font-size: var(--jp-ui-font-size0);\n  font-weight: 600;\n  cursor: pointer;\n  text-transform: uppercase;\n  border-bottom: solid var(--jp-border-width) var(--jp-border-color2);\n  letter-spacing: 1px;\n}\n\n.p-CommandPalette-header.p-mod-active {\n  background: var(--jp-layout-color2);\n}\n\n.p-CommandPalette-header:hover::before {\n  content: '\\2026'; /* ellipsis */\n  float: right;\n  margin-right: 4px;\n}\n\n.p-CommandPalette-header > mark {\n  background-color: transparent;\n  font-weight: bold;\n}\n\n.p-CommandPalette-item {\n  padding: 4px 12px 4px 4px;\n  color: var(--jp-ui-font-color1);\n  font-size: var(--jp-ui-font-size1);\n  font-weight: 400;\n  display: flex;\n}\n\n.p-CommandPalette-item.p-mod-disabled {\n  color: var(--jp-ui-font-color3);\n}\n\n.p-CommandPalette-item.p-mod-active {\n  background: var(--jp-layout-color3);\n}\n\n.p-CommandPalette-item:hover:not(.p-mod-active):not(.p-mod-disabled) {\n  background: var(--jp-layout-color2);\n}\n\n.p-CommandPalette-itemContent {\n  overflow: hidden;\n}\n\n.p-CommandPalette-itemLabel > mark {\n  color: var(--jp-ui-font-color0);\n  background-color: transparent;\n  font-weight: bold;\n}\n\n.p-CommandPalette-item.p-mod-disabled mark {\n  color: rgba(0, 0, 0, 0.4);\n}\n\n.p-CommandPalette-item.p-mod-toggled .p-CommandPalette-itemIcon {\n  background-image: var(--jp-icon-checkmark);\n  background-size: 16px;\n  background-repeat: no-repeat;\n}\n\n.p-CommandPalette-item .p-CommandPalette-itemIcon {\n  padding: 0px 0px 0px 4px;\n  position: relative;\n  width: 16px;\n  top: 2px;\n  flex: 0 0 auto;\n}\n\n.p-CommandPalette-item.p-mod-disabled .p-CommandPalette-itemIcon {\n  opacity: 0.4;\n}\n\n.p-CommandPalette-item .p-CommandPalette-itemShortcut {\n  flex: 0 0 auto;\n}\n\n.p-CommandPalette-itemCaption {\n  display: none;\n}\n\n.p-CommandPalette-content {\n  background-color: var(--jp-layout-color1);\n}\n\n.p-CommandPalette-content:empty:after {\n  content: 'No results';\n  margin: auto;\n  margin-top: 20px;\n  width: 100px;\n  display: block;\n  font-size: var(--jp-ui-font-size2);\n  font-family: var(--jp-ui-font-family);\n  font-weight: lighter;\n}\n\n.p-CommandPalette-emptyMessage {\n  text-align: center;\n  margin-top: 24px;\n  line-height: 1.32;\n  padding: 0px 8px;\n  color: var(--jp-content-font-color3);\n}\n", ""]);

// exports


/***/ }),

/***/ "kbcq":
/*!*******************************************************************!*\
  !*** ./node_modules/@jupyterlab/shortcuts-extension/lib/index.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const disposable_1 = __webpack_require__(/*! @phosphor/disposable */ "uNUc");
/**
 * The default shortcuts extension.
 *
 * #### Notes
 * Shortcut values are stored in the setting system. The default values for each
 * shortcut are preset in the settings schema file of this extension.
 * Additionally, each shortcut can be individually set by the end user by
 * modifying its setting (either in the text editor or by modifying its
 * underlying JSON schema file).
 *
 * When setting shortcut selectors, there are two concepts to consider:
 * specificity and matchability. These two interact in sometimes
 * counterintuitive ways. Keyboard events are triggered from an element and
 * they propagate up the DOM until they reach the `documentElement` (`<body>`).
 *
 * When a registered shortcut sequence is fired, the shortcut manager checks
 * the node that fired the event and each of its ancestors until a node matches
 * one or more registered selectors. The *first* matching selector in the
 * chain of ancestors will invoke the shortcut handler and the traversal will
 * end at that point. If a node matches more than one selector, the handler for
 * whichever selector is more *specific* fires.
 * @see https://www.w3.org/TR/css3-selectors/#specificity
 *
 * The practical consequence of this is that a very broadly matching selector,
 * e.g. `'*'` or `'div'` may match and therefore invoke a handler *before* a
 * more specific selector. The most common pitfall is to use the universal
 * (`'*'`) selector. For almost any use case where a global keyboard shortcut is
 * required, using the `'body'` selector is more appropriate.
 */
const plugin = {
    id: '@jupyterlab/shortcuts-extension:plugin',
    requires: [coreutils_1.ISettingRegistry],
    activate: (app, settingRegistry) => {
        const { commands } = app;
        settingRegistry
            .load(plugin.id)
            .then(settings => {
            Private.loadShortcuts(commands, settings.composite);
            settings.changed.connect(() => {
                Private.loadShortcuts(commands, settings.composite);
            });
        })
            .catch((reason) => {
            console.error('Loading shortcut settings failed.', reason.message);
        });
    },
    autoStart: true
};
/**
 * Export the plugin as default.
 */
exports.default = plugin;
/**
 * A namespace for private module data.
 */
var Private;
(function (Private) {
    /**
     * The internal collection of currently loaded shortcuts.
     */
    let disposables;
    /**
     * Load the keyboard shortcuts from settings.
     */
    function loadShortcuts(commands, composite) {
        if (disposables) {
            disposables.dispose();
        }
        disposables = Object.keys(composite).reduce((acc, val) => {
            const options = normalizeOptions(composite[val]);
            if (options) {
                acc.add(commands.addKeyBinding(options));
            }
            return acc;
        }, new disposable_1.DisposableSet());
    }
    Private.loadShortcuts = loadShortcuts;
    /**
     * Normalize potential keyboard shortcut options.
     */
    function normalizeOptions(value) {
        if (!value || typeof value !== 'object') {
            return undefined;
        }
        const { isArray } = Array;
        const valid = 'command' in value &&
            'keys' in value &&
            'selector' in value &&
            isArray(value.keys);
        return valid ? value : undefined;
    }
})(Private || (Private = {}));


/***/ }),

/***/ "kc9Y":
/*!************************************************************!*\
  !*** ./node_modules/draft-js/lib/findAncestorOffsetKey.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule findAncestorOffsetKey
 * @format
 * 
 */



var getSelectionOffsetKeyForNode = __webpack_require__(/*! ./getSelectionOffsetKeyForNode */ "zORg");

/**
 * Get the key from the node's nearest offset-aware ancestor.
 */
function findAncestorOffsetKey(node) {
  var searchNode = node;
  while (searchNode && searchNode !== document.documentElement) {
    var key = getSelectionOffsetKeyForNode(searchNode);
    if (key != null) {
      return key;
    }
    searchNode = searchNode.parentNode;
  }
  return null;
}

module.exports = findAncestorOffsetKey;

/***/ }),

/***/ "kd2E":
/*!************************************************!*\
  !*** ./node_modules/querystring-es3/decode.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.



// If obj.hasOwnProperty has been overridden, then calling
// obj.hasOwnProperty(prop) will break.
// See: https://github.com/joyent/node/issues/1707
function hasOwnProperty(obj, prop) {
  return Object.prototype.hasOwnProperty.call(obj, prop);
}

module.exports = function(qs, sep, eq, options) {
  sep = sep || '&';
  eq = eq || '=';
  var obj = {};

  if (typeof qs !== 'string' || qs.length === 0) {
    return obj;
  }

  var regexp = /\+/g;
  qs = qs.split(sep);

  var maxKeys = 1000;
  if (options && typeof options.maxKeys === 'number') {
    maxKeys = options.maxKeys;
  }

  var len = qs.length;
  // maxKeys <= 0 means that we should not limit keys count
  if (maxKeys > 0 && len > maxKeys) {
    len = maxKeys;
  }

  for (var i = 0; i < len; ++i) {
    var x = qs[i].replace(regexp, '%20'),
        idx = x.indexOf(eq),
        kstr, vstr, k, v;

    if (idx >= 0) {
      kstr = x.substr(0, idx);
      vstr = x.substr(idx + 1);
    } else {
      kstr = x;
      vstr = '';
    }

    k = decodeURIComponent(kstr);
    v = decodeURIComponent(vstr);

    if (!hasOwnProperty(obj, k)) {
      obj[k] = v;
    } else if (isArray(obj[k])) {
      obj[k].push(v);
    } else {
      obj[k] = [obj[k], v];
    }
  }

  return obj;
};

var isArray = Array.isArray || function (xs) {
  return Object.prototype.toString.call(xs) === '[object Array]';
};


/***/ }),

/***/ "kdwK":
/*!*********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotHeatmapIcon.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotHeatmapIcon = function PlotHeatmapIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M0 5.313h5.313v5.375H0zm5.313 16V16H0v10.688h10.688v-5.375zm5.375-16h5.313v5.375h-5.313zm-5.375 5.375h5.375v5.313H5.313zm10.687 0h5.313v5.313H16zM10.688 16h5.313v5.313h-5.313zm16-10.687h-5.375v5.375h5.375v5.313h5.313V5.313zM21.313 16h5.375v5.313h-5.375zM16 21.313h5.313v5.375H16zm10.688 0h5.313v5.375h-5.313z' })
    );
};

exports.default = PlotHeatmapIcon;

/***/ }),

/***/ "kekF":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_overArg.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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));
  };
}

module.exports = overArg;


/***/ }),

/***/ "km5Q":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/outputarea/lib/widget.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const widgets_2 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const services_1 = __webpack_require__(/*! @jupyterlab/services */ "S9up");
/**
 * The class name added to an output area widget.
 */
const OUTPUT_AREA_CLASS = 'jp-OutputArea';
/**
 * The class name added to the direction children of OutputArea
 */
const OUTPUT_AREA_ITEM_CLASS = 'jp-OutputArea-child';
/**
 * The class name added to actual outputs
 */
const OUTPUT_AREA_OUTPUT_CLASS = 'jp-OutputArea-output';
/**
 * The class name added to prompt children of OutputArea.
 */
const OUTPUT_AREA_PROMPT_CLASS = 'jp-OutputArea-prompt';
/**
 * The class name added to OutputPrompt.
 */
const OUTPUT_PROMPT_CLASS = 'jp-OutputPrompt';
/**
 * The class name added to an execution result.
 */
const EXECUTE_CLASS = 'jp-OutputArea-executeResult';
/**
 * The class name added stdin items of OutputArea
 */
const OUTPUT_AREA_STDIN_ITEM_CLASS = 'jp-OutputArea-stdin-item';
/**
 * The class name added to stdin widgets.
 */
const STDIN_CLASS = 'jp-Stdin';
/**
 * The class name added to stdin data prompt nodes.
 */
const STDIN_PROMPT_CLASS = 'jp-Stdin-prompt';
/**
 * The class name added to stdin data input nodes.
 */
const STDIN_INPUT_CLASS = 'jp-Stdin-input';
/******************************************************************************
 * OutputArea
 ******************************************************************************/
/**
 * An output area widget.
 *
 * #### Notes
 * The widget model must be set separately and can be changed
 * at any time.  Consumers of the widget must account for a
 * `null` model, and may want to listen to the `modelChanged`
 * signal.
 */
class OutputArea extends widgets_2.Widget {
    /**
     * Construct an output area widget.
     */
    constructor(options) {
        super();
        /**
         * A public signal used to indicate the number of outputs has changed.
         *
         * #### Notes
         * This is useful for parents who want to apply styling based on the number
         * of outputs. Emits the current number of outputs.
         */
        this.outputLengthChanged = new signaling_1.Signal(this);
        /**
         * Handle an iopub message.
         */
        this._onIOPub = (msg) => {
            let model = this.model;
            let msgType = msg.header.msg_type;
            let output;
            let transient = (msg.content.transient || {});
            let displayId = transient['display_id'];
            let targets;
            switch (msgType) {
                case 'execute_result':
                case 'display_data':
                case 'stream':
                case 'error':
                    output = msg.content;
                    output.output_type = msgType;
                    model.add(output);
                    break;
                case 'clear_output':
                    let wait = msg.content.wait;
                    model.clear(wait);
                    break;
                case 'update_display_data':
                    output = msg.content;
                    output.output_type = 'display_data';
                    targets = this._displayIdMap.get(displayId);
                    if (targets) {
                        for (let index of targets) {
                            model.set(index, output);
                        }
                    }
                    break;
                default:
                    break;
            }
            if (displayId && msgType === 'display_data') {
                targets = this._displayIdMap.get(displayId) || [];
                targets.push(model.length - 1);
                this._displayIdMap.set(displayId, targets);
            }
        };
        /**
         * Handle an execute reply message.
         */
        this._onExecuteReply = (msg) => {
            // API responses that contain a pager are special cased and their type
            // is overridden from 'execute_reply' to 'display_data' in order to
            // render output.
            let model = this.model;
            let content = msg.content;
            let payload = content && content.payload;
            if (!payload || !payload.length) {
                return;
            }
            let pages = payload.filter((i) => i.source === 'page');
            if (!pages.length) {
                return;
            }
            let page = JSON.parse(JSON.stringify(pages[0]));
            let output = {
                output_type: 'display_data',
                data: page.data,
                metadata: {}
            };
            model.add(output);
        };
        this._minHeightTimeout = null;
        this._future = null;
        this._displayIdMap = new Map();
        let model = (this.model = options.model);
        this.addClass(OUTPUT_AREA_CLASS);
        this.rendermime = options.rendermime;
        this.contentFactory =
            options.contentFactory || OutputArea.defaultContentFactory;
        this.layout = new widgets_1.PanelLayout();
        for (let i = 0; i < model.length; i++) {
            let output = model.get(i);
            this._insertOutput(i, output);
        }
        model.changed.connect(this.onModelChanged, this);
        model.stateChanged.connect(this.onStateChanged, this);
    }
    /**
     * A read-only sequence of the chidren widgets in the output area.
     */
    get widgets() {
        return this.layout.widgets;
    }
    /**
     * The kernel future associated with the output area.
     */
    get future() {
        return this._future;
    }
    set future(value) {
        // Bail if the model is disposed.
        if (this.model.isDisposed) {
            throw Error('Model is disposed');
        }
        if (this._future === value) {
            return;
        }
        if (this._future) {
            this._future.dispose();
        }
        this._future = value;
        this.model.clear();
        // Make sure there were no input widgets.
        if (this.widgets.length) {
            this._clear();
            this.outputLengthChanged.emit(this.model.length);
        }
        // Handle published messages.
        value.onIOPub = this._onIOPub;
        // Handle the execute reply.
        value.onReply = this._onExecuteReply;
        // Handle stdin.
        value.onStdin = msg => {
            if (services_1.KernelMessage.isInputRequestMsg(msg)) {
                this.onInputRequest(msg, value);
            }
        };
    }
    /**
     * Dispose of the resources used by the output area.
     */
    dispose() {
        if (this._future) {
            this._future.dispose();
        }
        this._future = null;
        this._displayIdMap.clear();
        super.dispose();
    }
    /**
     * Follow changes on the model state.
     */
    onModelChanged(sender, args) {
        switch (args.type) {
            case 'add':
                this._insertOutput(args.newIndex, args.newValues[0]);
                this.outputLengthChanged.emit(this.model.length);
                break;
            case 'remove':
                // Only clear is supported by the model.
                if (this.widgets.length) {
                    this._clear();
                    this.outputLengthChanged.emit(this.model.length);
                }
                break;
            case 'set':
                this._setOutput(args.newIndex, args.newValues[0]);
                this.outputLengthChanged.emit(this.model.length);
                break;
            default:
                break;
        }
    }
    /**
     * Follow changes on the output model state.
     */
    onStateChanged(sender) {
        for (let i = 0; i < this.model.length; i++) {
            this._setOutput(i, this.model.get(i));
        }
        this.outputLengthChanged.emit(this.model.length);
    }
    /**
     * Clear the widget inputs and outputs.
     */
    _clear() {
        // Bail if there is no work to do.
        if (!this.widgets.length) {
            return;
        }
        // Remove all of our widgets.
        let length = this.widgets.length;
        for (let i = 0; i < length; i++) {
            let widget = this.widgets[0];
            widget.parent = null;
            widget.dispose();
        }
        // Clear the display id map.
        this._displayIdMap.clear();
        // When an output area is cleared and then quickly replaced with new
        // content (as happens with @interact in widgets, for example), the
        // quickly changing height can make the page jitter.
        // We introduce a small delay in the minimum height
        // to prevent this jitter.
        let rect = this.node.getBoundingClientRect();
        this.node.style.minHeight = `${rect.height}px`;
        if (this._minHeightTimeout) {
            clearTimeout(this._minHeightTimeout);
        }
        this._minHeightTimeout = window.setTimeout(() => {
            if (this.isDisposed) {
                return;
            }
            this.node.style.minHeight = '';
        }, 50);
    }
    /**
     * Handle an input request from a kernel.
     */
    onInputRequest(msg, future) {
        // Add an output widget to the end.
        let factory = this.contentFactory;
        let stdinPrompt = msg.content.prompt;
        let password = msg.content.password;
        let panel = new widgets_1.Panel();
        panel.addClass(OUTPUT_AREA_ITEM_CLASS);
        panel.addClass(OUTPUT_AREA_STDIN_ITEM_CLASS);
        let prompt = factory.createOutputPrompt();
        prompt.addClass(OUTPUT_AREA_PROMPT_CLASS);
        panel.addWidget(prompt);
        let input = factory.createStdin({ prompt: stdinPrompt, password, future });
        input.addClass(OUTPUT_AREA_OUTPUT_CLASS);
        panel.addWidget(input);
        let layout = this.layout;
        layout.addWidget(panel);
        /**
         * Wait for the stdin to complete, add it to the model (so it persists)
         * and remove the stdin widget.
         */
        input.value.then(value => {
            // Use stdin as the stream so it does not get combined with stdout.
            this.model.add({
                output_type: 'stream',
                name: 'stdin',
                text: value + '\n'
            });
            panel.dispose();
        });
    }
    /**
     * Update an output in the layout in place.
     */
    _setOutput(index, model) {
        let layout = this.layout;
        let panel = layout.widgets[index];
        let renderer = (panel.widgets
            ? panel.widgets[1]
            : panel);
        if (renderer.renderModel) {
            renderer.renderModel(model);
        }
        else {
            layout.widgets[index].dispose();
            this._insertOutput(index, model);
        }
    }
    /**
     * Render and insert a single output into the layout.
     */
    _insertOutput(index, model) {
        let output = this.createOutputItem(model);
        output.toggleClass(EXECUTE_CLASS, model.executionCount !== null);
        let layout = this.layout;
        layout.insertWidget(index, output);
    }
    /**
     * Create an output item with a prompt and actual output
     */
    createOutputItem(model) {
        let panel = new widgets_1.Panel();
        panel.addClass(OUTPUT_AREA_ITEM_CLASS);
        let prompt = this.contentFactory.createOutputPrompt();
        prompt.executionCount = model.executionCount;
        prompt.addClass(OUTPUT_AREA_PROMPT_CLASS);
        panel.addWidget(prompt);
        let output = this.createRenderedMimetype(model);
        output.addClass(OUTPUT_AREA_OUTPUT_CLASS);
        panel.addWidget(output);
        return panel;
    }
    /**
     * Render a mimetype
     */
    createRenderedMimetype(model) {
        let widget;
        let mimeType = this.rendermime.preferredMimeType(model.data, model.trusted ? 'any' : 'ensure');
        if (mimeType) {
            let metadata = model.metadata;
            let mimeMd = metadata[mimeType];
            let isolated = false;
            // mime-specific higher priority
            if (mimeMd && mimeMd['isolated'] !== undefined) {
                isolated = mimeMd['isolated'];
            }
            else {
                // fallback on global
                isolated = metadata['isolated'];
            }
            let output = this.rendermime.createRenderer(mimeType);
            if (isolated === true) {
                output = new Private.IsolatedRenderer(output);
            }
            output.renderModel(model).catch(error => {
                // Manually append error message to output
                output.node.innerHTML = `<pre>Javascript Error: ${error.message}</pre>`;
                // Remove mime-type-specific CSS classes
                output.node.className = 'p-Widget jp-RenderedText';
                output.node.setAttribute('data-mime-type', 'application/vnd.jupyter.stderr');
            });
            widget = output;
        }
        else {
            widget = new widgets_2.Widget();
            widget.node.innerHTML =
                `No ${model.trusted ? '' : '(safe) '}renderer could be ` +
                    'found for output. It has the following MIME types: ' +
                    Object.keys(model.data).join(', ');
        }
        return widget;
    }
}
exports.OutputArea = OutputArea;
class SimplifiedOutputArea extends OutputArea {
    /**
     * Handle an input request from a kernel by doing nothing.
     */
    onInputRequest(msg, future) {
        return;
    }
    /**
     * Create an output item without a prompt, just the output widgets
     */
    createOutputItem(model) {
        let output = this.createRenderedMimetype(model);
        output.addClass(OUTPUT_AREA_OUTPUT_CLASS);
        return output;
    }
}
exports.SimplifiedOutputArea = SimplifiedOutputArea;
/**
 * A namespace for OutputArea statics.
 */
(function (OutputArea) {
    /**
     * Execute code on an output area.
     */
    function execute(code, output, session, metadata) {
        // Override the default for `stop_on_error`.
        let content = {
            code,
            stop_on_error: true
        };
        if (!session.kernel) {
            return Promise.reject('Session has no kernel.');
        }
        let future = session.kernel.requestExecute(content, false, metadata);
        output.future = future;
        return future.done;
    }
    OutputArea.execute = execute;
    /**
     * The default implementation of `IContentFactory`.
     */
    class ContentFactory {
        /**
         * Create the output prompt for the widget.
         */
        createOutputPrompt() {
            return new OutputPrompt();
        }
        /**
         * Create an stdin widget.
         */
        createStdin(options) {
            return new Stdin(options);
        }
    }
    OutputArea.ContentFactory = ContentFactory;
    /**
     * The default `ContentFactory` instance.
     */
    OutputArea.defaultContentFactory = new ContentFactory();
})(OutputArea = exports.OutputArea || (exports.OutputArea = {}));
/**
 * The default output prompt implementation
 */
class OutputPrompt extends widgets_2.Widget {
    /*
      * Create an output prompt widget.
      */
    constructor() {
        super();
        this._executionCount = null;
        this.addClass(OUTPUT_PROMPT_CLASS);
    }
    /**
     * The execution count for the prompt.
     */
    get executionCount() {
        return this._executionCount;
    }
    set executionCount(value) {
        this._executionCount = value;
        if (value === null) {
            this.node.textContent = '';
        }
        else {
            this.node.textContent = `[${value}]:`;
        }
    }
}
exports.OutputPrompt = OutputPrompt;
/**
 * The default stdin widget.
 */
class Stdin extends widgets_2.Widget {
    /**
     * Construct a new input widget.
     */
    constructor(options) {
        super({
            node: Private.createInputWidgetNode(options.prompt, options.password)
        });
        this._future = null;
        this._input = null;
        this._promise = new coreutils_1.PromiseDelegate();
        this.addClass(STDIN_CLASS);
        this._input = this.node.getElementsByTagName('input')[0];
        this._input.focus();
        this._future = options.future;
        this._value = options.prompt + ' ';
    }
    /**
     * The value of the widget.
     */
    get value() {
        return this._promise.promise.then(() => this._value);
    }
    /**
     * Handle the DOM events for the widget.
     *
     * @param event - The DOM event sent to the widget.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the dock panel's node. It should
     * not be called directly by user code.
     */
    handleEvent(event) {
        let input = this._input;
        if (event.type === 'keydown') {
            if (event.keyCode === 13) {
                // Enter
                this._future.sendInputReply({
                    value: input.value
                });
                if (input.type === 'password') {
                    this._value += Array(input.value.length + 1).join('·');
                }
                else {
                    this._value += input.value;
                }
                this._promise.resolve(void 0);
            }
        }
    }
    /**
     * Handle `after-attach` messages sent to the widget.
     */
    onAfterAttach(msg) {
        this._input.addEventListener('keydown', this);
        this.update();
    }
    /**
     * Handle `update-request` messages sent to the widget.
     */
    onUpdateRequest(msg) {
        this._input.focus();
    }
    /**
     * Handle `before-detach` messages sent to the widget.
     */
    onBeforeDetach(msg) {
        this._input.removeEventListener('keydown', this);
    }
}
exports.Stdin = Stdin;
/******************************************************************************
 * Private namespace
 ******************************************************************************/
/**
 * A namespace for private data.
 */
var Private;
(function (Private) {
    /**
     * Create the node for an InputWidget.
     */
    function createInputWidgetNode(prompt, password) {
        let node = document.createElement('div');
        let promptNode = document.createElement('pre');
        promptNode.className = STDIN_PROMPT_CLASS;
        promptNode.textContent = prompt;
        let input = document.createElement('input');
        input.className = STDIN_INPUT_CLASS;
        if (password) {
            input.type = 'password';
        }
        node.appendChild(promptNode);
        promptNode.appendChild(input);
        return node;
    }
    Private.createInputWidgetNode = createInputWidgetNode;
    /**
     * A renderer for IFrame data.
     */
    class IsolatedRenderer extends widgets_2.Widget {
        /**
         * Create an isolated renderer.
         */
        constructor(wrapped) {
            super({ node: document.createElement('iframe') });
            this.addClass('jp-mod-isolated');
            this._wrapped = wrapped;
            // Once the iframe is loaded, the subarea is dynamically inserted
            let iframe = this.node;
            iframe.frameBorder = '0';
            iframe.scrolling = 'auto';
            iframe.addEventListener('load', () => {
                // Workaround needed by Firefox, to properly render svg inside
                // iframes, see https://stackoverflow.com/questions/10177190/
                // svg-dynamically-added-to-iframe-does-not-render-correctly
                iframe.contentDocument.open();
                // Insert the subarea into the iframe
                // We must directly write the html. At this point, subarea doesn't
                // contain any user content.
                iframe.contentDocument.write(this._wrapped.node.innerHTML);
                iframe.contentDocument.close();
                let body = iframe.contentDocument.body;
                // Adjust the iframe height automatically
                iframe.style.height = body.scrollHeight + 'px';
            });
        }
        /**
         * Render a mime model.
         *
         * @param model - The mime model to render.
         *
         * @returns A promise which resolves when rendering is complete.
         *
         * #### Notes
         * This method may be called multiple times during the lifetime
         * of the widget to update it if and when new data is available.
         */
        renderModel(model) {
            return this._wrapped.renderModel(model).then(() => {
                let win = this.node.contentWindow;
                if (win) {
                    win.location.reload();
                }
            });
        }
    }
    Private.IsolatedRenderer = IsolatedRenderer;
})(Private || (Private = {}));


/***/ }),

/***/ "ks0Q":
/*!**********************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/to_log_range.js ***!
  \**********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var isNumeric = __webpack_require__(/*! fast-isnumeric */ "GbLo");

/**
 * convert a linear value into a logged value, folding negative numbers into
 * the given range
 */
module.exports = function toLogRange(val, range) {
    if(val > 0) return Math.log(val) / Math.LN10;

    // move a negative value reference to a log axis - just put the
    // result at the lowest range value on the plot (or if the range also went negative,
    // one millionth of the top of the range)
    var newVal = Math.log(Math.min(range[0], range[1])) / Math.LN10;
    if(!isNumeric(newVal)) newVal = Math.log(Math.max(range[0], range[1])) / Math.LN10 - 6;
    return newVal;
};


/***/ }),

/***/ "ktrZ":
/*!*******************************************************!*\
  !*** ./node_modules/react-json-tree/lib/JSONArrow.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "QbLZ");

var _extends3 = _interopRequireDefault(_extends2);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var JSONArrow = function JSONArrow(_ref) {
  var styling = _ref.styling,
      arrowStyle = _ref.arrowStyle,
      expanded = _ref.expanded,
      nodeType = _ref.nodeType,
      onClick = _ref.onClick;
  return _react2['default'].createElement(
    'div',
    (0, _extends3['default'])({}, styling('arrowContainer', arrowStyle), { onClick: onClick }),
    _react2['default'].createElement(
      'div',
      styling(['arrow', 'arrowSign'], nodeType, expanded, arrowStyle),
      '\u25B6',
      arrowStyle === 'double' && _react2['default'].createElement(
        'div',
        styling(['arrowSign', 'arrowSignInner']),
        '\u25B6'
      )
    )
  );
};

JSONArrow.propTypes = {
  styling: _propTypes2['default'].func.isRequired,
  arrowStyle: _propTypes2['default'].oneOf(['single', 'double']),
  expanded: _propTypes2['default'].bool.isRequired,
  nodeType: _propTypes2['default'].string.isRequired,
  onClick: _propTypes2['default'].func.isRequired
};

JSONArrow.defaultProps = {
  arrowStyle: 'single'
};

exports['default'] = JSONArrow;

/***/ }),

/***/ "kwZ1":
/*!****************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_object-assign.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// 19.1.2.1 Object.assign(target, source, ...)
var getKeys = __webpack_require__(/*! ./_object-keys */ "w6GO");
var gOPS = __webpack_require__(/*! ./_object-gops */ "mqlF");
var pIE = __webpack_require__(/*! ./_object-pie */ "NV0k");
var toObject = __webpack_require__(/*! ./_to-object */ "JB68");
var IObject = __webpack_require__(/*! ./_iobject */ "M1xp");
var $assign = Object.assign;

// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || __webpack_require__(/*! ./_fails */ "KUxP")(function () {
  var A = {};
  var B = {};
  // eslint-disable-next-line no-undef
  var S = Symbol();
  var K = 'abcdefghijklmnopqrst';
  A[S] = 7;
  K.split('').forEach(function (k) { B[k] = k; });
  return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source) { // eslint-disable-line no-unused-vars
  var T = toObject(target);
  var aLen = arguments.length;
  var index = 1;
  var getSymbols = gOPS.f;
  var isEnum = pIE.f;
  while (aLen > index) {
    var S = IObject(arguments[index++]);
    var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S);
    var length = keys.length;
    var j = 0;
    var key;
    while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key];
  } return T;
} : $assign;


/***/ }),

/***/ "kzof":
/*!***************************************************************!*\
  !*** ./node_modules/react-paginate/dist/PaginationBoxView.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _PageView = __webpack_require__(/*! ./PageView */ "3LHp");

var _PageView2 = _interopRequireDefault(_PageView);

var _BreakView = __webpack_require__(/*! ./BreakView */ "1c7f");

var _BreakView2 = _interopRequireDefault(_BreakView);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var PaginationBoxView = function (_Component) {
  _inherits(PaginationBoxView, _Component);

  function PaginationBoxView(props) {
    _classCallCheck(this, PaginationBoxView);

    var _this = _possibleConstructorReturn(this, (PaginationBoxView.__proto__ || Object.getPrototypeOf(PaginationBoxView)).call(this, props));

    _this.handlePreviousPage = function (evt) {
      var selected = _this.state.selected;

      evt.preventDefault ? evt.preventDefault() : evt.returnValue = false;
      if (selected > 0) {
        _this.handlePageSelected(selected - 1, evt);
      }
    };

    _this.handleNextPage = function (evt) {
      var selected = _this.state.selected;
      var pageCount = _this.props.pageCount;


      evt.preventDefault ? evt.preventDefault() : evt.returnValue = false;
      if (selected < pageCount - 1) {
        _this.handlePageSelected(selected + 1, evt);
      }
    };

    _this.handlePageSelected = function (selected, evt) {
      evt.preventDefault ? evt.preventDefault() : evt.returnValue = false;

      if (_this.state.selected === selected) return;

      _this.setState({ selected: selected });

      // Call the callback with the new selected item:
      _this.callCallback(selected);
    };

    _this.callCallback = function (selectedItem) {
      if (typeof _this.props.onPageChange !== "undefined" && typeof _this.props.onPageChange === "function") {
        _this.props.onPageChange({ selected: selectedItem });
      }
    };

    _this.pagination = function () {
      var items = [];
      var _this$props = _this.props,
          pageRangeDisplayed = _this$props.pageRangeDisplayed,
          pageCount = _this$props.pageCount,
          marginPagesDisplayed = _this$props.marginPagesDisplayed,
          breakLabel = _this$props.breakLabel,
          breakClassName = _this$props.breakClassName;
      var selected = _this.state.selected;


      if (pageCount <= pageRangeDisplayed) {

        for (var index = 0; index < pageCount; index++) {
          items.push(_this.getPageElement(index));
        }
      } else {

        var leftSide = pageRangeDisplayed / 2;
        var rightSide = pageRangeDisplayed - leftSide;

        // If the selected page index is on the default right side of the pagination,
        // we consider that the new right side is made up of it (= only one break element).
        // If the selected page index is on the default left side of the pagination,
        // we consider that the new left side is made up of it (= only one break element).
        if (selected > pageCount - pageRangeDisplayed / 2) {
          rightSide = pageCount - selected;
          leftSide = pageRangeDisplayed - rightSide;
        } else if (selected < pageRangeDisplayed / 2) {
          leftSide = selected;
          rightSide = pageRangeDisplayed - leftSide;
        }

        var _index = void 0;
        var page = void 0;
        var breakView = void 0;
        var createPageView = function createPageView(index) {
          return _this.getPageElement(index);
        };

        for (_index = 0; _index < pageCount; _index++) {

          page = _index + 1;

          // If the page index is lower than the margin defined,
          // the page has to be displayed on the left side of
          // the pagination.
          if (page <= marginPagesDisplayed) {
            items.push(createPageView(_index));
            continue;
          }

          // If the page index is greater than the page count
          // minus the margin defined, the page has to be
          // displayed on the right side of the pagination.
          if (page > pageCount - marginPagesDisplayed) {
            items.push(createPageView(_index));
            continue;
          }

          // If the page index is near the selected page index
          // and inside the defined range (pageRangeDisplayed)
          // we have to display it (it will create the center
          // part of the pagination).
          if (_index >= selected - leftSide && _index <= selected + rightSide) {
            items.push(createPageView(_index));
            continue;
          }

          // If the page index doesn't meet any of the conditions above,
          // we check if the last item of the current "items" array
          // is a break element. If not, we add a break element, else,
          // we do nothing (because we don't want to display the page).
          if (breakLabel && items[items.length - 1] !== breakView) {
            breakView = _react2.default.createElement(_BreakView2.default, {
              key: _index,
              breakLabel: breakLabel,
              breakClassName: breakClassName
            });
            items.push(breakView);
          }
        }
      }

      return items;
    };

    _this.state = {
      selected: props.initialPage ? props.initialPage : props.forcePage ? props.forcePage : 0
    };
    return _this;
  }

  _createClass(PaginationBoxView, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      var _props = this.props,
          initialPage = _props.initialPage,
          disableInitialCallback = _props.disableInitialCallback;
      // Call the callback with the initialPage item:

      if (typeof initialPage !== 'undefined' && !disableInitialCallback) {
        this.callCallback(initialPage);
      }
    }
  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      if (typeof nextProps.forcePage !== 'undefined' && this.props.forcePage !== nextProps.forcePage) {
        this.setState({ selected: nextProps.forcePage });
      }
    }
  }, {
    key: 'hrefBuilder',
    value: function hrefBuilder(pageIndex) {
      var _props2 = this.props,
          hrefBuilder = _props2.hrefBuilder,
          pageCount = _props2.pageCount;

      if (hrefBuilder && pageIndex !== this.state.selected && pageIndex >= 0 && pageIndex < pageCount) {
        return hrefBuilder(pageIndex + 1);
      }
    }
  }, {
    key: 'getPageElement',
    value: function getPageElement(index) {
      var selected = this.state.selected;
      var _props3 = this.props,
          pageClassName = _props3.pageClassName,
          pageLinkClassName = _props3.pageLinkClassName,
          activeClassName = _props3.activeClassName,
          activeLinkClassName = _props3.activeLinkClassName,
          extraAriaContext = _props3.extraAriaContext;


      return _react2.default.createElement(_PageView2.default, {
        key: index,
        onClick: this.handlePageSelected.bind(null, index),
        selected: selected === index,
        pageClassName: pageClassName,
        pageLinkClassName: pageLinkClassName,
        activeClassName: activeClassName,
        activeLinkClassName: activeLinkClassName,
        extraAriaContext: extraAriaContext,
        href: this.hrefBuilder(index),
        page: index + 1 });
    }
  }, {
    key: 'render',
    value: function render() {
      var _props4 = this.props,
          disabledClassName = _props4.disabledClassName,
          previousClassName = _props4.previousClassName,
          nextClassName = _props4.nextClassName,
          pageCount = _props4.pageCount,
          containerClassName = _props4.containerClassName,
          previousLinkClassName = _props4.previousLinkClassName,
          previousLabel = _props4.previousLabel,
          nextLinkClassName = _props4.nextLinkClassName,
          nextLabel = _props4.nextLabel;
      var selected = this.state.selected;


      var previousClasses = previousClassName + (selected === 0 ? ' ' + disabledClassName : '');
      var nextClasses = nextClassName + (selected === pageCount - 1 ? ' ' + disabledClassName : '');

      return _react2.default.createElement(
        'ul',
        { className: containerClassName },
        _react2.default.createElement(
          'li',
          { className: previousClasses },
          _react2.default.createElement(
            'a',
            { onClick: this.handlePreviousPage,
              className: previousLinkClassName,
              href: this.hrefBuilder(selected - 1),
              tabIndex: '0',
              role: 'button',
              onKeyPress: this.handlePreviousPage },
            previousLabel
          )
        ),
        this.pagination(),
        _react2.default.createElement(
          'li',
          { className: nextClasses },
          _react2.default.createElement(
            'a',
            { onClick: this.handleNextPage,
              className: nextLinkClassName,
              href: this.hrefBuilder(selected + 1),
              tabIndex: '0',
              role: 'button',
              onKeyPress: this.handleNextPage },
            nextLabel
          )
        )
      );
    }
  }]);

  return PaginationBoxView;
}(_react.Component);

PaginationBoxView.propTypes = {
  pageCount: _propTypes2.default.number.isRequired,
  pageRangeDisplayed: _propTypes2.default.number.isRequired,
  marginPagesDisplayed: _propTypes2.default.number.isRequired,
  previousLabel: _propTypes2.default.node,
  nextLabel: _propTypes2.default.node,
  breakLabel: _propTypes2.default.node,
  hrefBuilder: _propTypes2.default.func,
  onPageChange: _propTypes2.default.func,
  initialPage: _propTypes2.default.number,
  forcePage: _propTypes2.default.number,
  disableInitialCallback: _propTypes2.default.bool,
  containerClassName: _propTypes2.default.string,
  pageClassName: _propTypes2.default.string,
  pageLinkClassName: _propTypes2.default.string,
  activeClassName: _propTypes2.default.string,
  activeLinkClassName: _propTypes2.default.string,
  previousClassName: _propTypes2.default.string,
  nextClassName: _propTypes2.default.string,
  previousLinkClassName: _propTypes2.default.string,
  nextLinkClassName: _propTypes2.default.string,
  disabledClassName: _propTypes2.default.string,
  breakClassName: _propTypes2.default.string
};
PaginationBoxView.defaultProps = {
  pageCount: 10,
  pageRangeDisplayed: 2,
  marginPagesDisplayed: 3,
  activeClassName: "selected",
  previousClassName: "previous",
  nextClassName: "next",
  previousLabel: "Previous",
  nextLabel: "Next",
  breakLabel: "...",
  disabledClassName: "disabled",
  disableInitialCallback: false
};
exports.default = PaginationBoxView;
;
//# sourceMappingURL=PaginationBoxView.js.map

/***/ }),

/***/ "l//F":
/*!*********************************************************!*\
  !*** ./node_modules/react-day-picker/lib/src/Navbar.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _classNames = __webpack_require__(/*! ./classNames */ "ZE44");

var _classNames2 = _interopRequireDefault(_classNames);

var _keys = __webpack_require__(/*! ./keys */ "VBVY");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Navbar = function (_Component) {
  _inherits(Navbar, _Component);

  function Navbar() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, Navbar);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Navbar.__proto__ || Object.getPrototypeOf(Navbar)).call.apply(_ref, [this].concat(args))), _this), _this.handleNextClick = function () {
      if (_this.props.onNextClick) {
        _this.props.onNextClick();
      }
    }, _this.handlePreviousClick = function () {
      if (_this.props.onPreviousClick) {
        _this.props.onPreviousClick();
      }
    }, _this.handleNextKeyDown = function (e) {
      if (e.keyCode !== _keys.ENTER && e.keyCode !== _keys.SPACE) {
        return;
      }
      e.preventDefault();
      _this.handleNextClick();
    }, _this.handlePreviousKeyDown = function (e) {
      if (e.keyCode !== _keys.ENTER && e.keyCode !== _keys.SPACE) {
        return;
      }
      e.preventDefault();
      _this.handlePreviousClick();
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(Navbar, [{
    key: 'shouldComponentUpdate',
    value: function shouldComponentUpdate(nextProps) {
      return nextProps.labels !== this.props.labels || nextProps.dir !== this.props.dir || this.props.showPreviousButton !== nextProps.showPreviousButton || this.props.showNextButton !== nextProps.showNextButton;
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          classNames = _props.classNames,
          className = _props.className,
          showPreviousButton = _props.showPreviousButton,
          showNextButton = _props.showNextButton,
          labels = _props.labels,
          dir = _props.dir;


      var previousClickHandler = void 0;
      var nextClickHandler = void 0;
      var previousKeyDownHandler = void 0;
      var nextKeyDownHandler = void 0;
      var shouldShowPrevious = void 0;
      var shouldShowNext = void 0;

      if (dir === 'rtl') {
        previousClickHandler = this.handleNextClick;
        nextClickHandler = this.handlePreviousClick;
        previousKeyDownHandler = this.handleNextKeyDown;
        nextKeyDownHandler = this.handlePreviousKeyDown;
        shouldShowNext = showPreviousButton;
        shouldShowPrevious = showNextButton;
      } else {
        previousClickHandler = this.handlePreviousClick;
        nextClickHandler = this.handleNextClick;
        previousKeyDownHandler = this.handlePreviousKeyDown;
        nextKeyDownHandler = this.handleNextKeyDown;
        shouldShowNext = showNextButton;
        shouldShowPrevious = showPreviousButton;
      }

      var previousClassName = shouldShowPrevious ? classNames.navButtonPrev : classNames.navButtonPrev + ' ' + classNames.navButtonInteractionDisabled;

      var nextClassName = shouldShowNext ? classNames.navButtonNext : classNames.navButtonNext + ' ' + classNames.navButtonInteractionDisabled;

      var previousButton = _react2.default.createElement('span', {
        tabIndex: '0',
        role: 'button',
        'aria-label': labels.previousMonth,
        key: 'previous',
        className: previousClassName,
        onKeyDown: shouldShowPrevious ? previousKeyDownHandler : undefined,
        onClick: shouldShowPrevious ? previousClickHandler : undefined
      });

      var nextButton = _react2.default.createElement('span', {
        tabIndex: '0',
        role: 'button',
        'aria-label': labels.nextMonth,
        key: 'right',
        className: nextClassName,
        onKeyDown: shouldShowNext ? nextKeyDownHandler : undefined,
        onClick: shouldShowNext ? nextClickHandler : undefined
      });

      return _react2.default.createElement(
        'div',
        { className: className || classNames.navBar },
        dir === 'rtl' ? [nextButton, previousButton] : [previousButton, nextButton]
      );
    }
  }]);

  return Navbar;
}(_react.Component);

Navbar.defaultProps = {
  classNames: _classNames2.default,
  dir: 'ltr',
  labels: {
    previousMonth: 'Previous Month',
    nextMonth: 'Next Month'
  },
  showPreviousButton: true,
  showNextButton: true
};
exports.default = Navbar;
Navbar.propTypes =  true ? {
  classNames: _propTypes2.default.shape({
    navBar: _propTypes2.default.string.isRequired,
    navButtonPrev: _propTypes2.default.string.isRequired,
    navButtonNext: _propTypes2.default.string.isRequired
  }),
  className: _propTypes2.default.string,
  showPreviousButton: _propTypes2.default.bool,
  showNextButton: _propTypes2.default.bool,
  onPreviousClick: _propTypes2.default.func,
  onNextClick: _propTypes2.default.func,
  dir: _propTypes2.default.string,
  labels: _propTypes2.default.shape({
    previousMonth: _propTypes2.default.string.isRequired,
    nextMonth: _propTypes2.default.string.isRequired
  })
} : undefined;
//# sourceMappingURL=Navbar.js.map

/***/ }),

/***/ "l26e":
/*!****************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/multiValues.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.setMultiValuedContainer = exports.deepCopyPublic = undefined;

var _constants = __webpack_require__(/*! ./constants */ "5Bkx");

var _lib = __webpack_require__(/*! ../lib */ "RXjw");

/**
 * Deep-copies the value using JSON. Underscored (private) keys are removed.
 * @param {*} value Some nested value from the plotDiv object.
 * @returns {*} A deepcopy of the value.
 */
function deepCopyPublic(value) {
  if (typeof value === 'undefined') {
    return value;
  }

  var skipPrivateKeys = function skipPrivateKeys(key, value) {
    return key.startsWith('_') ? 0 : value;
  };

  return window.JSON.parse(window.JSON.stringify(value, skipPrivateKeys));
}

/*
 * WARNING: When using this function, make intoObj and fromObject are copies of
 * your objects, so that no mutations occur
 */
function setMultiValuedContainer(intoObj, fromObj, key) {
  var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};

  var intoVal = intoObj[key];
  var fromVal = fromObj[key];

  // don't merge private attrs
  if (typeof key === 'string' && key.charAt(0) === '_' && key !== '_group' || typeof intoVal === 'function' || key === 'module') {
    return;
  }

  // already a mixture of values, can't get any worse
  if (intoVal === _constants.MULTI_VALUED) {
    return;
  } else if (intoVal === void 0) {
    // if the original doesn't have the key it's because that key
    // doesn't do anything there - so use the new value
    // note that if fromObj doesn't have a key in intoObj we will not
    // attempt to merge them at all, so this behavior makes the merge
    // independent of order.

    // WARNING: Careful that data copies were passed in as args here, as mutation can occur
    intoObj[key] = fromVal;
  } else if (key === 'colorscale') {
    // colorscales are arrays... need to stringify before comparing
    // (other vals we don't want to stringify, as differences could
    // potentially be real, like 'false' and false)
    if (String(intoVal) !== String(fromVal)) {
      intoObj[key] = _constants.MULTI_VALUED;
    }
  } else if (Array.isArray(intoVal)) {
    // in data, other arrays are data, which we don't care about
    // for styling purposes
    if (!config.searchArrays) {
      return;
    }
    if (!Array.isArray(fromVal)) {
      intoObj[key] = _constants.MULTI_VALUED;
    } else {
      // in layout though, we need to recurse into arrays
      for (var i = 0; i < fromVal.length; i++) {
        setMultiValuedContainer(intoVal, fromVal, i, config);
      }
    }
  } else if ((0, _lib.isPlainObject)(fromVal)) {
    // recurse into objects
    if (!(0, _lib.isPlainObject)(intoVal)) {
      throw new Error('tried to merge object into non-object: ' + key);
    }
    Object.keys(fromVal).forEach(function (key2) {
      setMultiValuedContainer(intoVal, fromVal, key2, config);
    });
  } else if ((0, _lib.isPlainObject)(intoVal)) {
    throw new Error('tried to merge non-object into object: ' + key);
  } else if (intoVal !== fromVal) {
    // different non-empty values -
    intoObj[key] = _constants.MULTI_VALUED;
  }
}

exports.deepCopyPublic = deepCopyPublic;
exports.setMultiValuedContainer = setMultiValuedContainer;
//# sourceMappingURL=multiValues.js.map

/***/ }),

/***/ "l5ep":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/cy.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var cy = moment.defineLocale('cy', {
    months: 'Ionawr_Chwefror_Mawrth_Ebrill_Mai_Mehefin_Gorffennaf_Awst_Medi_Hydref_Tachwedd_Rhagfyr'.split('_'),
    monthsShort: 'Ion_Chwe_Maw_Ebr_Mai_Meh_Gor_Aws_Med_Hyd_Tach_Rhag'.split('_'),
    weekdays: 'Dydd Sul_Dydd Llun_Dydd Mawrth_Dydd Mercher_Dydd Iau_Dydd Gwener_Dydd Sadwrn'.split('_'),
    weekdaysShort: 'Sul_Llun_Maw_Mer_Iau_Gwe_Sad'.split('_'),
    weekdaysMin: 'Su_Ll_Ma_Me_Ia_Gw_Sa'.split('_'),
    weekdaysParseExact : true,
    // time formats are the same as en-gb
    longDateFormat: {
        LT: 'HH:mm',
        LTS : 'HH:mm:ss',
        L: 'DD/MM/YYYY',
        LL: 'D MMMM YYYY',
        LLL: 'D MMMM YYYY HH:mm',
        LLLL: 'dddd, D MMMM YYYY HH:mm'
    },
    calendar: {
        sameDay: '[Heddiw am] LT',
        nextDay: '[Yfory am] LT',
        nextWeek: 'dddd [am] LT',
        lastDay: '[Ddoe am] LT',
        lastWeek: 'dddd [diwethaf am] LT',
        sameElse: 'L'
    },
    relativeTime: {
        future: 'mewn %s',
        past: '%s yn ôl',
        s: 'ychydig eiliadau',
        ss: '%d eiliad',
        m: 'munud',
        mm: '%d munud',
        h: 'awr',
        hh: '%d awr',
        d: 'diwrnod',
        dd: '%d diwrnod',
        M: 'mis',
        MM: '%d mis',
        y: 'blwyddyn',
        yy: '%d flynedd'
    },
    dayOfMonthOrdinalParse: /\d{1,2}(fed|ain|af|il|ydd|ed|eg)/,
    // traditional ordinal numbers above 31 are not commonly used in colloquial Welsh
    ordinal: function (number) {
        var b = number,
            output = '',
            lookup = [
                '', 'af', 'il', 'ydd', 'ydd', 'ed', 'ed', 'ed', 'fed', 'fed', 'fed', // 1af to 10fed
                'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'fed' // 11eg to 20fed
            ];
        if (b > 20) {
            if (b === 40 || b === 50 || b === 60 || b === 80 || b === 100) {
                output = 'fed'; // not 30ain, 70ain or 90ain
            } else {
                output = 'ain';
            }
        } else if (b > 0) {
            output = lookup[b];
        }
        return number + output;
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return cy;

})));


/***/ }),

/***/ "l9OW":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_baseMap.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseEach = __webpack_require__(/*! ./_baseEach */ "SKAX"),
    isArrayLike = __webpack_require__(/*! ./isArrayLike */ "MMmD");

/**
 * 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;
}

module.exports = baseMap;


/***/ }),

/***/ "lA0h":
/*!*******************************************************************!*\
  !*** ./node_modules/core-js/library/fn/number/is-safe-integer.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(/*! ../../modules/es6.number.is-safe-integer */ "odad");
module.exports = __webpack_require__(/*! ../../modules/_core */ "WEpk").Number.isSafeInteger;


/***/ }),

/***/ "lANe":
/*!************************************************!*\
  !*** ./node_modules/mdi-react/LockOpenIcon.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var LockOpenIcon = function LockOpenIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M18,8C19.1,8 20,8.9 20,10V20C20,21.1 19.1,22 18,22H6C4.89,22 4,21.1 4,20V10C4,8.9 4.9,8 6,8H15V6C15,4.34 13.66,3 12,3C10.34,3 9,4.34 9,6H7C7,3.24 9.24,1 12,1C14.76,1 17,3.24 17,6V8H18M12,17C13.1,17 14,16.1 14,15C14,13.9 13.1,13 12,13C10.9,13 10,13.9 10,15C10,16.1 10.9,17 12,17Z' })
  );
};

module.exports = LockOpenIcon;


/***/ }),

/***/ "lCc8":
/*!*******************************************************************!*\
  !*** ./node_modules/core-js/library/modules/es6.object.create.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var $export = __webpack_require__(/*! ./_export */ "Y7ZC");
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
$export($export.S, 'Object', { create: __webpack_require__(/*! ./_object-create */ "oVml") });


/***/ }),

/***/ "lCvc":
/*!***************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/array.js ***!
  \***************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var isArray = Array.isArray;

// IE9 fallbacks

var ab = (typeof ArrayBuffer === 'undefined' || !ArrayBuffer.isView) ?
    {isView: function() { return false; }} :
    ArrayBuffer;

var dv = (typeof DataView === 'undefined') ?
    function() {} :
    DataView;

function isTypedArray(a) {
    return ab.isView(a) && !(a instanceof dv);
}
exports.isTypedArray = isTypedArray;

function isArrayOrTypedArray(a) {
    return isArray(a) || isTypedArray(a);
}
exports.isArrayOrTypedArray = isArrayOrTypedArray;

/*
 * Test whether an input object is 1D.
 *
 * Assumes we already know the object is an array.
 *
 * Looks only at the first element, if the dimensionality is
 * not consistent we won't figure that out here.
 */
function isArray1D(a) {
    return !isArrayOrTypedArray(a[0]);
}
exports.isArray1D = isArray1D;

/*
 * Ensures an array has the right amount of storage space. If it doesn't
 * exist, it creates an array. If it does exist, it returns it if too
 * short or truncates it in-place.
 *
 * The goal is to just reuse memory to avoid a bit of excessive garbage
 * collection.
 */
exports.ensureArray = function(out, n) {
    // TODO: typed array support here? This is only used in
    // traces/carpet/compute_control_points
    if(!isArray(out)) out = [];

    // If too long, truncate. (If too short, it will grow
    // automatically so we don't care about that case)
    out.length = n;

    return out;
};

/*
 * TypedArray-compatible concatenation of n arrays
 * if all arrays are the same type it will preserve that type,
 * otherwise it falls back on Array.
 * Also tries to avoid copying, in case one array has zero length
 * But never mutates an existing array
 */
exports.concat = function() {
    var args = [];
    var allArray = true;
    var totalLen = 0;

    var _constructor, arg0, i, argi, posi, leni, out, j;

    for(i = 0; i < arguments.length; i++) {
        argi = arguments[i];
        leni = argi.length;
        if(leni) {
            if(arg0) args.push(argi);
            else {
                arg0 = argi;
                posi = leni;
            }

            if(isArray(argi)) {
                _constructor = false;
            }
            else {
                allArray = false;
                if(!totalLen) {
                    _constructor = argi.constructor;
                }
                else if(_constructor !== argi.constructor) {
                    // TODO: in principle we could upgrade here,
                    // ie keep typed array but convert all to Float64Array?
                    _constructor = false;
                }
            }

            totalLen += leni;
        }
    }

    if(!totalLen) return [];
    if(!args.length) return arg0;

    if(allArray) return arg0.concat.apply(arg0, args);
    if(_constructor) {
        // matching typed arrays
        out = new _constructor(totalLen);
        out.set(arg0);
        for(i = 0; i < args.length; i++) {
            argi = args[i];
            out.set(argi, posi);
            posi += argi.length;
        }
        return out;
    }

    // mismatched types or Array + typed
    out = new Array(totalLen);
    for(j = 0; j < arg0.length; j++) out[j] = arg0[j];
    for(i = 0; i < args.length; i++) {
        argi = args[i];
        for(j = 0; j < argi.length; j++) out[posi + j] = argi[j];
        posi += j;
    }
    return out;
};

exports.maxRowLength = function(z) {
    return _rowLength(z, Math.max, 0);
};

exports.minRowLength = function(z) {
    return _rowLength(z, Math.min, Infinity);
};

function _rowLength(z, fn, len0) {
    if(isArrayOrTypedArray(z)) {
        if(isArrayOrTypedArray(z[0])) {
            var len = len0;
            for(var i = 0; i < z.length; i++) {
                len = fn(len, z[i].length);
            }
            return len;
        } else {
            return z.length;
        }
    }
    return 0;
}


/***/ }),

/***/ "lDDf":
/*!**********************************************!*\
  !*** ./node_modules/base16/lib/solarized.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'solarized',
  author: 'ethan schoonover (http://ethanschoonover.com/solarized)',
  base00: '#002b36',
  base01: '#073642',
  base02: '#586e75',
  base03: '#657b83',
  base04: '#839496',
  base05: '#93a1a1',
  base06: '#eee8d5',
  base07: '#fdf6e3',
  base08: '#dc322f',
  base09: '#cb4b16',
  base0A: '#b58900',
  base0B: '#859900',
  base0C: '#2aa198',
  base0D: '#268bd2',
  base0E: '#6c71c4',
  base0F: '#d33682'
};
module.exports = exports['default'];

/***/ }),

/***/ "lF1L":
/*!***********************************************************!*\
  !*** ./node_modules/elliptic/lib/elliptic/eddsa/index.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var hash = __webpack_require__(/*! hash.js */ "fZJM");
var elliptic = __webpack_require__(/*! ../../elliptic */ "MzeL");
var utils = elliptic.utils;
var assert = utils.assert;
var parseBytes = utils.parseBytes;
var KeyPair = __webpack_require__(/*! ./key */ "OA+I");
var Signature = __webpack_require__(/*! ./signature */ "RKMU");

function EDDSA(curve) {
  assert(curve === 'ed25519', 'only tested with ed25519 so far');

  if (!(this instanceof EDDSA))
    return new EDDSA(curve);

  var curve = elliptic.curves[curve].curve;
  this.curve = curve;
  this.g = curve.g;
  this.g.precompute(curve.n.bitLength() + 1);

  this.pointClass = curve.point().constructor;
  this.encodingLength = Math.ceil(curve.n.bitLength() / 8);
  this.hash = hash.sha512;
}

module.exports = EDDSA;

/**
* @param {Array|String} message - message bytes
* @param {Array|String|KeyPair} secret - secret bytes or a keypair
* @returns {Signature} - signature
*/
EDDSA.prototype.sign = function sign(message, secret) {
  message = parseBytes(message);
  var key = this.keyFromSecret(secret);
  var r = this.hashInt(key.messagePrefix(), message);
  var R = this.g.mul(r);
  var Rencoded = this.encodePoint(R);
  var s_ = this.hashInt(Rencoded, key.pubBytes(), message)
               .mul(key.priv());
  var S = r.add(s_).umod(this.curve.n);
  return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });
};

/**
* @param {Array} message - message bytes
* @param {Array|String|Signature} sig - sig bytes
* @param {Array|String|Point|KeyPair} pub - public key
* @returns {Boolean} - true if public key matches sig of message
*/
EDDSA.prototype.verify = function verify(message, sig, pub) {
  message = parseBytes(message);
  sig = this.makeSignature(sig);
  var key = this.keyFromPublic(pub);
  var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);
  var SG = this.g.mul(sig.S());
  var RplusAh = sig.R().add(key.pub().mul(h));
  return RplusAh.eq(SG);
};

EDDSA.prototype.hashInt = function hashInt() {
  var hash = this.hash();
  for (var i = 0; i < arguments.length; i++)
    hash.update(arguments[i]);
  return utils.intFromLE(hash.digest()).umod(this.curve.n);
};

EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {
  return KeyPair.fromPublic(this, pub);
};

EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {
  return KeyPair.fromSecret(this, secret);
};

EDDSA.prototype.makeSignature = function makeSignature(sig) {
  if (sig instanceof Signature)
    return sig;
  return new Signature(this, sig);
};

/**
* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2
*
* EDDSA defines methods for encoding and decoding points and integers. These are
* helper convenience methods, that pass along to utility functions implied
* parameters.
*
*/
EDDSA.prototype.encodePoint = function encodePoint(point) {
  var enc = point.getY().toArray('le', this.encodingLength);
  enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;
  return enc;
};

EDDSA.prototype.decodePoint = function decodePoint(bytes) {
  bytes = utils.parseBytes(bytes);

  var lastIx = bytes.length - 1;
  var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);
  var xIsOdd = (bytes[lastIx] & 0x80) !== 0;

  var y = utils.intFromLE(normed);
  return this.curve.pointFromY(y, xIsOdd);
};

EDDSA.prototype.encodeInt = function encodeInt(num) {
  return num.toArray('le', this.encodingLength);
};

EDDSA.prototype.decodeInt = function decodeInt(bytes) {
  return utils.intFromLE(bytes);
};

EDDSA.prototype.isPoint = function isPoint(val) {
  return val instanceof this.pointClass;
};


/***/ }),

/***/ "lFJn":
/*!********************************************************!*\
  !*** ./node_modules/draft-js/lib/CharacterMetadata.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule CharacterMetadata
 * @format
 * 
 */



function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var _require = __webpack_require__(/*! immutable */ "JPcv"),
    Map = _require.Map,
    OrderedSet = _require.OrderedSet,
    Record = _require.Record;

// Immutable.map is typed such that the value for every key in the map
// must be the same type


var EMPTY_SET = OrderedSet();

var defaultRecord = {
  style: EMPTY_SET,
  entity: null
};

var CharacterMetadataRecord = Record(defaultRecord);

var CharacterMetadata = function (_CharacterMetadataRec) {
  _inherits(CharacterMetadata, _CharacterMetadataRec);

  function CharacterMetadata() {
    _classCallCheck(this, CharacterMetadata);

    return _possibleConstructorReturn(this, _CharacterMetadataRec.apply(this, arguments));
  }

  CharacterMetadata.prototype.getStyle = function getStyle() {
    return this.get('style');
  };

  CharacterMetadata.prototype.getEntity = function getEntity() {
    return this.get('entity');
  };

  CharacterMetadata.prototype.hasStyle = function hasStyle(style) {
    return this.getStyle().includes(style);
  };

  CharacterMetadata.applyStyle = function applyStyle(record, style) {
    var withStyle = record.set('style', record.getStyle().add(style));
    return CharacterMetadata.create(withStyle);
  };

  CharacterMetadata.removeStyle = function removeStyle(record, style) {
    var withoutStyle = record.set('style', record.getStyle().remove(style));
    return CharacterMetadata.create(withoutStyle);
  };

  CharacterMetadata.applyEntity = function applyEntity(record, entityKey) {
    var withEntity = record.getEntity() === entityKey ? record : record.set('entity', entityKey);
    return CharacterMetadata.create(withEntity);
  };

  /**
   * Use this function instead of the `CharacterMetadata` constructor.
   * Since most content generally uses only a very small number of
   * style/entity permutations, we can reuse these objects as often as
   * possible.
   */


  CharacterMetadata.create = function create(config) {
    if (!config) {
      return EMPTY;
    }

    var defaultConfig = {
      style: EMPTY_SET,
      entity: null
    };

    // Fill in unspecified properties, if necessary.
    var configMap = Map(defaultConfig).merge(config);

    var existing = pool.get(configMap);
    if (existing) {
      return existing;
    }

    var newCharacter = new CharacterMetadata(configMap);
    pool = pool.set(configMap, newCharacter);
    return newCharacter;
  };

  return CharacterMetadata;
}(CharacterMetadataRecord);

var EMPTY = new CharacterMetadata();
var pool = Map([[Map(defaultRecord), EMPTY]]);

CharacterMetadata.EMPTY = EMPTY;

module.exports = CharacterMetadata;

/***/ }),

/***/ "lKy8":
/*!**************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/noop.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



// Simple helper functions
// none of these need any external deps

module.exports = function noop() {};


/***/ }),

/***/ "lNXy":
/*!********************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/geometry2d.js ***!
  \********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var mod = __webpack_require__(/*! ./mod */ "74Od").mod;

/*
 * look for intersection of two line segments
 *   (1->2 and 3->4) - returns array [x,y] if they do, null if not
 */
exports.segmentsIntersect = segmentsIntersect;
function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) {
    var a = x2 - x1;
    var b = x3 - x1;
    var c = x4 - x3;
    var d = y2 - y1;
    var e = y3 - y1;
    var f = y4 - y3;
    var det = a * f - c * d;
    // parallel lines? intersection is undefined
    // ignore the case where they are colinear
    if(det === 0) return null;
    var t = (b * f - c * e) / det;
    var u = (b * d - a * e) / det;
    // segments do not intersect?
    if(u < 0 || u > 1 || t < 0 || t > 1) return null;

    return {x: x1 + a * t, y: y1 + d * t};
}

/*
 * find the minimum distance between two line segments (1->2 and 3->4)
 */
exports.segmentDistance = function segmentDistance(x1, y1, x2, y2, x3, y3, x4, y4) {
    if(segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4)) return 0;

    // the two segments and their lengths squared
    var x12 = x2 - x1;
    var y12 = y2 - y1;
    var x34 = x4 - x3;
    var y34 = y4 - y3;
    var ll12 = x12 * x12 + y12 * y12;
    var ll34 = x34 * x34 + y34 * y34;

    // calculate distance squared, then take the sqrt at the very end
    var dist2 = Math.min(
        perpDistance2(x12, y12, ll12, x3 - x1, y3 - y1),
        perpDistance2(x12, y12, ll12, x4 - x1, y4 - y1),
        perpDistance2(x34, y34, ll34, x1 - x3, y1 - y3),
        perpDistance2(x34, y34, ll34, x2 - x3, y2 - y3)
    );

    return Math.sqrt(dist2);
};

/*
 * distance squared from segment ab to point c
 * [xab, yab] is the vector b-a
 * [xac, yac] is the vector c-a
 * llab is the length squared of (b-a), just to simplify calculation
 */
function perpDistance2(xab, yab, llab, xac, yac) {
    var fcAB = (xac * xab + yac * yab);
    if(fcAB < 0) {
        // point c is closer to point a
        return xac * xac + yac * yac;
    }
    else if(fcAB > llab) {
        // point c is closer to point b
        var xbc = xac - xab;
        var ybc = yac - yab;
        return xbc * xbc + ybc * ybc;
    }
    else {
        // perpendicular distance is the shortest
        var crossProduct = xac * yab - yac * xab;
        return crossProduct * crossProduct / llab;
    }
}

// a very short-term cache for getTextLocation, just because
// we're often looping over the same locations multiple times
// invalidated as soon as we look at a different path
var locationCache, workingPath, workingTextWidth;

// turn a path and position along it into x, y, and angle for the given text
exports.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) {
    if(path !== workingPath || textWidth !== workingTextWidth) {
        locationCache = {};
        workingPath = path;
        workingTextWidth = textWidth;
    }
    if(locationCache[positionOnPath]) {
        return locationCache[positionOnPath];
    }

    // for the angle, use points on the path separated by the text width
    // even though due to curvature, the text will cover a bit more than that
    var p0 = path.getPointAtLength(mod(positionOnPath - textWidth / 2, totalPathLen));
    var p1 = path.getPointAtLength(mod(positionOnPath + textWidth / 2, totalPathLen));
    // note: atan handles 1/0 nicely
    var theta = Math.atan((p1.y - p0.y) / (p1.x - p0.x));
    // center the text at 2/3 of the center position plus 1/3 the p0/p1 midpoint
    // that's the average position of this segment, assuming it's roughly quadratic
    var pCenter = path.getPointAtLength(mod(positionOnPath, totalPathLen));
    var x = (pCenter.x * 4 + p0.x + p1.x) / 6;
    var y = (pCenter.y * 4 + p0.y + p1.y) / 6;

    var out = {x: x, y: y, theta: theta};
    locationCache[positionOnPath] = out;
    return out;
};

exports.clearLocationCache = function() {
    workingPath = null;
};

/*
 * Find the segment of `path` that's within the visible area
 * given by `bounds` {left, right, top, bottom}, to within a
 * precision of `buffer` px
 *
 * returns: undefined if nothing is visible, else object:
 * {
 *   min: position where the path first enters bounds, or 0 if it
 *        starts within bounds
 *   max: position where the path last exits bounds, or the path length
 *        if it finishes within bounds
 *   len: max - min, ie the length of visible path
 *   total: the total path length - just included so the caller doesn't
 *        need to call path.getTotalLength() again
 *   isClosed: true iff the start and end points of the path are both visible
 *        and are at the same point
 * }
 *
 * Works by starting from either end and repeatedly finding the distance from
 * that point to the plot area, and if it's outside the plot, moving along the
 * path by that distance (because the plot must be at least that far away on
 * the path). Note that if a path enters, exits, and re-enters the plot, we
 * will not capture this behavior.
 */
exports.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) {
    var left = bounds.left;
    var right = bounds.right;
    var top = bounds.top;
    var bottom = bounds.bottom;

    var pMin = 0;
    var pTotal = path.getTotalLength();
    var pMax = pTotal;

    var pt0, ptTotal;

    function getDistToPlot(len) {
        var pt = path.getPointAtLength(len);

        // hold on to the start and end points for `closed`
        if(len === 0) pt0 = pt;
        else if(len === pTotal) ptTotal = pt;

        var dx = (pt.x < left) ? left - pt.x : (pt.x > right ? pt.x - right : 0);
        var dy = (pt.y < top) ? top - pt.y : (pt.y > bottom ? pt.y - bottom : 0);
        return Math.sqrt(dx * dx + dy * dy);
    }

    var distToPlot = getDistToPlot(pMin);
    while(distToPlot) {
        pMin += distToPlot + buffer;
        if(pMin > pMax) return;
        distToPlot = getDistToPlot(pMin);
    }

    distToPlot = getDistToPlot(pMax);
    while(distToPlot) {
        pMax -= distToPlot + buffer;
        if(pMin > pMax) return;
        distToPlot = getDistToPlot(pMax);
    }

    return {
        min: pMin,
        max: pMax,
        len: pMax - pMin,
        total: pTotal,
        isClosed: pMin === 0 && pMax === pTotal &&
            Math.abs(pt0.x - ptTotal.x) < 0.1 &&
            Math.abs(pt0.y - ptTotal.y) < 0.1
    };
};

/**
 * Find point on SVG path corresponding to a given constraint coordinate
 *
 * @param {SVGPathElement} path
 * @param {Number} val : constraint coordinate value
 * @param {String} coord : 'x' or 'y' the constraint coordinate
 * @param {Object} opts :
 *  - {Number} pathLength : supply total path length before hand
 *  - {Number} tolerance
 *  - {Number} iterationLimit
 * @return {SVGPoint}
 */
exports.findPointOnPath = function findPointOnPath(path, val, coord, opts) {
    opts = opts || {};

    var pathLength = opts.pathLength || path.getTotalLength();
    var tolerance = opts.tolerance || 1e-3;
    var iterationLimit = opts.iterationLimit || 30;

    // if path starts at a val greater than the path tail (like on vertical violins),
    // we must flip the sign of the computed diff.
    var mul = path.getPointAtLength(0)[coord] > path.getPointAtLength(pathLength)[coord] ? -1 : 1;

    var i = 0;
    var b0 = 0;
    var b1 = pathLength;
    var mid;
    var pt;
    var diff;

    while(i < iterationLimit) {
        mid = (b0 + b1) / 2;
        pt = path.getPointAtLength(mid);
        diff = pt[coord] - val;

        if(Math.abs(diff) < tolerance) {
            return pt;
        } else {
            if(mul * diff > 0) {
                b1 = mid;
            } else {
                b0 = mid;
            }
            i++;
        }
    }
    return pt;
};


/***/ }),

/***/ "lOjS":
/*!**********************************************************!*\
  !*** ./node_modules/@jupyterlab/rendermime/lib/latex.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
// Some magic for deferring mathematical expressions to MathJax
// by hiding them from the Markdown parser.
// Some of the code here is adapted with permission from Davide Cervone
// under the terms of the Apache2 license governing the MathJax project.
// Other minor modifications are also due to StackExchange and are used with
// permission.
Object.defineProperty(exports, "__esModule", { value: true });
const inline = '$'; // the inline math delimiter
// MATHSPLIT contains the pattern for math delimiters and special symbols
// needed for searching for math in the text input.
const MATHSPLIT = /(\$\$?|\\(?:begin|end)\{[a-z]*\*?\}|\\[{}$]|[{}]|(?:\n\s*)+|@@\d+@@|\\\\(?:\(|\)|\[|\]))/i;
/**
 *  Break up the text into its component parts and search
 *    through them for math delimiters, braces, linebreaks, etc.
 *  Math delimiters must match and braces must balance.
 *  Don't allow math to pass through a double linebreak
 *    (which will be a paragraph).
 */
function removeMath(text) {
    let math = []; // stores math strings for later
    let start = null;
    let end = null;
    let last = null;
    let braces = 0;
    let deTilde;
    // Except for extreme edge cases, this should catch precisely those pieces of the markdown
    // source that will later be turned into code spans. While MathJax will not TeXify code spans,
    // we still have to consider them at this point; the following issue has happened several times:
    //
    //     `$foo` and `$bar` are variables.  -->  <code>$foo ` and `$bar</code> are variables.
    let hasCodeSpans = /`/.test(text);
    if (hasCodeSpans) {
        text = text
            .replace(/~/g, '~T')
            .replace(/(^|[^\\])(`+)([^\n]*?[^`\n])\2(?!`)/gm, wholematch => wholematch.replace(/\$/g, '~D'));
        deTilde = (text) => {
            return text.replace(/~([TD])/g, (wholematch, character) => (character === 'T' ? '~' : inline));
        };
    }
    else {
        deTilde = (text) => {
            return text;
        };
    }
    let blocks = text.replace(/\r\n?/g, '\n').split(MATHSPLIT);
    for (let i = 1, m = blocks.length; i < m; i += 2) {
        let block = blocks[i];
        if (block.charAt(0) === '@') {
            //
            //  Things that look like our math markers will get
            //  stored and then retrieved along with the math.
            //
            blocks[i] = '@@' + math.length + '@@';
            math.push(block);
        }
        else if (start !== null) {
            //
            //  If we are in math, look for the end delimiter,
            //    but don't go past double line breaks, and
            //    and balance braces within the math.
            //
            if (block === end) {
                if (braces) {
                    last = i;
                }
                else {
                    blocks = processMath(start, i, deTilde, math, blocks);
                    start = null;
                    end = null;
                    last = null;
                }
            }
            else if (block.match(/\n.*\n/)) {
                if (last !== null) {
                    i = last;
                    blocks = processMath(start, i, deTilde, math, blocks);
                }
                start = null;
                end = null;
                last = null;
                braces = 0;
            }
            else if (block === '{') {
                braces++;
            }
            else if (block === '}' && braces) {
                braces--;
            }
        }
        else {
            //
            //  Look for math start delimiters and when
            //    found, set up the end delimiter.
            //
            if (block === inline || block === '$$') {
                start = i;
                end = block;
                braces = 0;
            }
            else if (block === '\\\\(' || block === '\\\\[') {
                start = i;
                end = block.slice(-1) === '(' ? '\\\\)' : '\\\\]';
                braces = 0;
            }
            else if (block.substr(1, 5) === 'begin') {
                start = i;
                end = '\\end' + block.substr(6);
                braces = 0;
            }
        }
    }
    if (start !== null && last !== null) {
        blocks = processMath(start, last, deTilde, math, blocks);
        start = null;
        end = null;
        last = null;
    }
    return { text: deTilde(blocks.join('')), math };
}
exports.removeMath = removeMath;
/**
 * Put back the math strings that were saved,
 * and clear the math array (no need to keep it around).
 */
function replaceMath(text, math) {
    /**
     * Replace a math placeholder with its corresponding group.
     * The math delimiters "\\(", "\\[", "\\)" and "\\]" are replaced
     * removing one backslash in order to be interpreted correctly by MathJax.
     */
    let process = (match, n) => {
        let group = math[n];
        if (group.substr(0, 3) === '\\\\(' &&
            group.substr(group.length - 3) === '\\\\)') {
            group = '\\(' + group.substring(3, group.length - 3) + '\\)';
        }
        else if (group.substr(0, 3) === '\\\\[' &&
            group.substr(group.length - 3) === '\\\\]') {
            group = '\\[' + group.substring(3, group.length - 3) + '\\]';
        }
        return group;
    };
    // Replace all the math group placeholders in the text
    // with the saved strings.
    return text.replace(/@@(\d+)@@/g, process);
}
exports.replaceMath = replaceMath;
/**
 * Process math blocks.
 *
 * The math is in blocks i through j, so
 *   collect it into one block and clear the others.
 *  Replace &, <, and > by named entities.
 *  For IE, put <br> at the ends of comments since IE removes \n.
 *  Clear the current math positions and store the index of the
 *   math, then push the math string onto the storage array.
 *  The preProcess function is called on all blocks if it has been passed in
 */
function processMath(i, j, preProcess, math, blocks) {
    let block = blocks
        .slice(i, j + 1)
        .join('')
        .replace(/&/g, '&amp;') // use HTML entity for &
        .replace(/</g, '&lt;') // use HTML entity for <
        .replace(/>/g, '&gt;'); // use HTML entity for >
    if (navigator && navigator.appName === 'Microsoft Internet Explorer') {
        block = block.replace(/(%[^\n]*)\n/g, '$1<br/>\n');
    }
    while (j > i) {
        blocks[j] = '';
        j--;
    }
    blocks[i] = '@@' + math.length + '@@'; // replace the current block text with a unique tag to find later
    if (preProcess) {
        block = preProcess(block);
    }
    math.push(block);
    return blocks;
}


/***/ }),

/***/ "lQqw":
/*!************************************************!*\
  !*** ./node_modules/lodash/_createBaseEach.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isArrayLike = __webpack_require__(/*! ./isArrayLike */ "MMmD");

/**
 * 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;
  };
}

module.exports = createBaseEach;


/***/ }),

/***/ "lSCD":
/*!*******************************************!*\
  !*** ./node_modules/lodash/isFunction.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseGetTag = __webpack_require__(/*! ./_baseGetTag */ "NykK"),
    isObject = __webpack_require__(/*! ./isObject */ "GoyQ");

/** `Object#toString` result references. */
var asyncTag = '[object AsyncFunction]',
    funcTag = '[object Function]',
    genTag = '[object GeneratorFunction]',
    proxyTag = '[object Proxy]';

/**
 * 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;
}

module.exports = isFunction;


/***/ }),

/***/ "lT4e":
/*!****************************************************!*\
  !*** ./node_modules/create-react-class/factory.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */



var _assign = __webpack_require__(/*! object-assign */ "MgzW");

var emptyObject = __webpack_require__(/*! fbjs/lib/emptyObject */ "t33a");
var _invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");

if (true) {
  var warning = __webpack_require__(/*! fbjs/lib/warning */ "2mcs");
}

var MIXINS_KEY = 'mixins';

// Helper function to allow the creation of anonymous functions which do not
// have .name set to the name of the variable being assigned to.
function identity(fn) {
  return fn;
}

var ReactPropTypeLocationNames;
if (true) {
  ReactPropTypeLocationNames = {
    prop: 'prop',
    context: 'context',
    childContext: 'child context'
  };
} else {}

function factory(ReactComponent, isValidElement, ReactNoopUpdateQueue) {
  /**
   * Policies that describe methods in `ReactClassInterface`.
   */

  var injectedMixins = [];

  /**
   * Composite components are higher-level components that compose other composite
   * or host components.
   *
   * To create a new type of `ReactClass`, pass a specification of
   * your new class to `React.createClass`. The only requirement of your class
   * specification is that you implement a `render` method.
   *
   *   var MyComponent = React.createClass({
   *     render: function() {
   *       return <div>Hello World</div>;
   *     }
   *   });
   *
   * The class specification supports a specific protocol of methods that have
   * special meaning (e.g. `render`). See `ReactClassInterface` for
   * more the comprehensive protocol. Any other properties and methods in the
   * class specification will be available on the prototype.
   *
   * @interface ReactClassInterface
   * @internal
   */
  var ReactClassInterface = {
    /**
     * An array of Mixin objects to include when defining your component.
     *
     * @type {array}
     * @optional
     */
    mixins: 'DEFINE_MANY',

    /**
     * An object containing properties and methods that should be defined on
     * the component's constructor instead of its prototype (static methods).
     *
     * @type {object}
     * @optional
     */
    statics: 'DEFINE_MANY',

    /**
     * Definition of prop types for this component.
     *
     * @type {object}
     * @optional
     */
    propTypes: 'DEFINE_MANY',

    /**
     * Definition of context types for this component.
     *
     * @type {object}
     * @optional
     */
    contextTypes: 'DEFINE_MANY',

    /**
     * Definition of context types this component sets for its children.
     *
     * @type {object}
     * @optional
     */
    childContextTypes: 'DEFINE_MANY',

    // ==== Definition methods ====

    /**
     * Invoked when the component is mounted. Values in the mapping will be set on
     * `this.props` if that prop is not specified (i.e. using an `in` check).
     *
     * This method is invoked before `getInitialState` and therefore cannot rely
     * on `this.state` or use `this.setState`.
     *
     * @return {object}
     * @optional
     */
    getDefaultProps: 'DEFINE_MANY_MERGED',

    /**
     * Invoked once before the component is mounted. The return value will be used
     * as the initial value of `this.state`.
     *
     *   getInitialState: function() {
     *     return {
     *       isOn: false,
     *       fooBaz: new BazFoo()
     *     }
     *   }
     *
     * @return {object}
     * @optional
     */
    getInitialState: 'DEFINE_MANY_MERGED',

    /**
     * @return {object}
     * @optional
     */
    getChildContext: 'DEFINE_MANY_MERGED',

    /**
     * Uses props from `this.props` and state from `this.state` to render the
     * structure of the component.
     *
     * No guarantees are made about when or how often this method is invoked, so
     * it must not have side effects.
     *
     *   render: function() {
     *     var name = this.props.name;
     *     return <div>Hello, {name}!</div>;
     *   }
     *
     * @return {ReactComponent}
     * @required
     */
    render: 'DEFINE_ONCE',

    // ==== Delegate methods ====

    /**
     * Invoked when the component is initially created and about to be mounted.
     * This may have side effects, but any external subscriptions or data created
     * by this method must be cleaned up in `componentWillUnmount`.
     *
     * @optional
     */
    componentWillMount: 'DEFINE_MANY',

    /**
     * Invoked when the component has been mounted and has a DOM representation.
     * However, there is no guarantee that the DOM node is in the document.
     *
     * Use this as an opportunity to operate on the DOM when the component has
     * been mounted (initialized and rendered) for the first time.
     *
     * @param {DOMElement} rootNode DOM element representing the component.
     * @optional
     */
    componentDidMount: 'DEFINE_MANY',

    /**
     * Invoked before the component receives new props.
     *
     * Use this as an opportunity to react to a prop transition by updating the
     * state using `this.setState`. Current props are accessed via `this.props`.
     *
     *   componentWillReceiveProps: function(nextProps, nextContext) {
     *     this.setState({
     *       likesIncreasing: nextProps.likeCount > this.props.likeCount
     *     });
     *   }
     *
     * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop
     * transition may cause a state change, but the opposite is not true. If you
     * need it, you are probably looking for `componentWillUpdate`.
     *
     * @param {object} nextProps
     * @optional
     */
    componentWillReceiveProps: 'DEFINE_MANY',

    /**
     * Invoked while deciding if the component should be updated as a result of
     * receiving new props, state and/or context.
     *
     * Use this as an opportunity to `return false` when you're certain that the
     * transition to the new props/state/context will not require a component
     * update.
     *
     *   shouldComponentUpdate: function(nextProps, nextState, nextContext) {
     *     return !equal(nextProps, this.props) ||
     *       !equal(nextState, this.state) ||
     *       !equal(nextContext, this.context);
     *   }
     *
     * @param {object} nextProps
     * @param {?object} nextState
     * @param {?object} nextContext
     * @return {boolean} True if the component should update.
     * @optional
     */
    shouldComponentUpdate: 'DEFINE_ONCE',

    /**
     * Invoked when the component is about to update due to a transition from
     * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState`
     * and `nextContext`.
     *
     * Use this as an opportunity to perform preparation before an update occurs.
     *
     * NOTE: You **cannot** use `this.setState()` in this method.
     *
     * @param {object} nextProps
     * @param {?object} nextState
     * @param {?object} nextContext
     * @param {ReactReconcileTransaction} transaction
     * @optional
     */
    componentWillUpdate: 'DEFINE_MANY',

    /**
     * Invoked when the component's DOM representation has been updated.
     *
     * Use this as an opportunity to operate on the DOM when the component has
     * been updated.
     *
     * @param {object} prevProps
     * @param {?object} prevState
     * @param {?object} prevContext
     * @param {DOMElement} rootNode DOM element representing the component.
     * @optional
     */
    componentDidUpdate: 'DEFINE_MANY',

    /**
     * Invoked when the component is about to be removed from its parent and have
     * its DOM representation destroyed.
     *
     * Use this as an opportunity to deallocate any external resources.
     *
     * NOTE: There is no `componentDidUnmount` since your component will have been
     * destroyed by that point.
     *
     * @optional
     */
    componentWillUnmount: 'DEFINE_MANY',

    /**
     * Replacement for (deprecated) `componentWillMount`.
     *
     * @optional
     */
    UNSAFE_componentWillMount: 'DEFINE_MANY',

    /**
     * Replacement for (deprecated) `componentWillReceiveProps`.
     *
     * @optional
     */
    UNSAFE_componentWillReceiveProps: 'DEFINE_MANY',

    /**
     * Replacement for (deprecated) `componentWillUpdate`.
     *
     * @optional
     */
    UNSAFE_componentWillUpdate: 'DEFINE_MANY',

    // ==== Advanced methods ====

    /**
     * Updates the component's currently mounted DOM representation.
     *
     * By default, this implements React's rendering and reconciliation algorithm.
     * Sophisticated clients may wish to override this.
     *
     * @param {ReactReconcileTransaction} transaction
     * @internal
     * @overridable
     */
    updateComponent: 'OVERRIDE_BASE'
  };

  /**
   * Similar to ReactClassInterface but for static methods.
   */
  var ReactClassStaticInterface = {
    /**
     * This method is invoked after a component is instantiated and when it
     * receives new props. Return an object to update state in response to
     * prop changes. Return null to indicate no change to state.
     *
     * If an object is returned, its keys will be merged into the existing state.
     *
     * @return {object || null}
     * @optional
     */
    getDerivedStateFromProps: 'DEFINE_MANY_MERGED'
  };

  /**
   * Mapping from class specification keys to special processing functions.
   *
   * Although these are declared like instance properties in the specification
   * when defining classes using `React.createClass`, they are actually static
   * and are accessible on the constructor instead of the prototype. Despite
   * being static, they must be defined outside of the "statics" key under
   * which all other static methods are defined.
   */
  var RESERVED_SPEC_KEYS = {
    displayName: function(Constructor, displayName) {
      Constructor.displayName = displayName;
    },
    mixins: function(Constructor, mixins) {
      if (mixins) {
        for (var i = 0; i < mixins.length; i++) {
          mixSpecIntoComponent(Constructor, mixins[i]);
        }
      }
    },
    childContextTypes: function(Constructor, childContextTypes) {
      if (true) {
        validateTypeDef(Constructor, childContextTypes, 'childContext');
      }
      Constructor.childContextTypes = _assign(
        {},
        Constructor.childContextTypes,
        childContextTypes
      );
    },
    contextTypes: function(Constructor, contextTypes) {
      if (true) {
        validateTypeDef(Constructor, contextTypes, 'context');
      }
      Constructor.contextTypes = _assign(
        {},
        Constructor.contextTypes,
        contextTypes
      );
    },
    /**
     * Special case getDefaultProps which should move into statics but requires
     * automatic merging.
     */
    getDefaultProps: function(Constructor, getDefaultProps) {
      if (Constructor.getDefaultProps) {
        Constructor.getDefaultProps = createMergedResultFunction(
          Constructor.getDefaultProps,
          getDefaultProps
        );
      } else {
        Constructor.getDefaultProps = getDefaultProps;
      }
    },
    propTypes: function(Constructor, propTypes) {
      if (true) {
        validateTypeDef(Constructor, propTypes, 'prop');
      }
      Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes);
    },
    statics: function(Constructor, statics) {
      mixStaticSpecIntoComponent(Constructor, statics);
    },
    autobind: function() {}
  };

  function validateTypeDef(Constructor, typeDef, location) {
    for (var propName in typeDef) {
      if (typeDef.hasOwnProperty(propName)) {
        // use a warning instead of an _invariant so components
        // don't show up in prod but only in __DEV__
        if (true) {
          warning(
            typeof typeDef[propName] === 'function',
            '%s: %s type `%s` is invalid; it must be a function, usually from ' +
              'React.PropTypes.',
            Constructor.displayName || 'ReactClass',
            ReactPropTypeLocationNames[location],
            propName
          );
        }
      }
    }
  }

  function validateMethodOverride(isAlreadyDefined, name) {
    var specPolicy = ReactClassInterface.hasOwnProperty(name)
      ? ReactClassInterface[name]
      : null;

    // Disallow overriding of base class methods unless explicitly allowed.
    if (ReactClassMixin.hasOwnProperty(name)) {
      _invariant(
        specPolicy === 'OVERRIDE_BASE',
        'ReactClassInterface: You are attempting to override ' +
          '`%s` from your class specification. Ensure that your method names ' +
          'do not overlap with React methods.',
        name
      );
    }

    // Disallow defining methods more than once unless explicitly allowed.
    if (isAlreadyDefined) {
      _invariant(
        specPolicy === 'DEFINE_MANY' || specPolicy === 'DEFINE_MANY_MERGED',
        'ReactClassInterface: You are attempting to define ' +
          '`%s` on your component more than once. This conflict may be due ' +
          'to a mixin.',
        name
      );
    }
  }

  /**
   * Mixin helper which handles policy validation and reserved
   * specification keys when building React classes.
   */
  function mixSpecIntoComponent(Constructor, spec) {
    if (!spec) {
      if (true) {
        var typeofSpec = typeof spec;
        var isMixinValid = typeofSpec === 'object' && spec !== null;

        if (true) {
          warning(
            isMixinValid,
            "%s: You're attempting to include a mixin that is either null " +
              'or not an object. Check the mixins included by the component, ' +
              'as well as any mixins they include themselves. ' +
              'Expected object but got %s.',
            Constructor.displayName || 'ReactClass',
            spec === null ? null : typeofSpec
          );
        }
      }

      return;
    }

    _invariant(
      typeof spec !== 'function',
      "ReactClass: You're attempting to " +
        'use a component class or function as a mixin. Instead, just use a ' +
        'regular object.'
    );
    _invariant(
      !isValidElement(spec),
      "ReactClass: You're attempting to " +
        'use a component as a mixin. Instead, just use a regular object.'
    );

    var proto = Constructor.prototype;
    var autoBindPairs = proto.__reactAutoBindPairs;

    // By handling mixins before any other properties, we ensure the same
    // chaining order is applied to methods with DEFINE_MANY policy, whether
    // mixins are listed before or after these methods in the spec.
    if (spec.hasOwnProperty(MIXINS_KEY)) {
      RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins);
    }

    for (var name in spec) {
      if (!spec.hasOwnProperty(name)) {
        continue;
      }

      if (name === MIXINS_KEY) {
        // We have already handled mixins in a special case above.
        continue;
      }

      var property = spec[name];
      var isAlreadyDefined = proto.hasOwnProperty(name);
      validateMethodOverride(isAlreadyDefined, name);

      if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {
        RESERVED_SPEC_KEYS[name](Constructor, property);
      } else {
        // Setup methods on prototype:
        // The following member methods should not be automatically bound:
        // 1. Expected ReactClass methods (in the "interface").
        // 2. Overridden methods (that were mixed in).
        var isReactClassMethod = ReactClassInterface.hasOwnProperty(name);
        var isFunction = typeof property === 'function';
        var shouldAutoBind =
          isFunction &&
          !isReactClassMethod &&
          !isAlreadyDefined &&
          spec.autobind !== false;

        if (shouldAutoBind) {
          autoBindPairs.push(name, property);
          proto[name] = property;
        } else {
          if (isAlreadyDefined) {
            var specPolicy = ReactClassInterface[name];

            // These cases should already be caught by validateMethodOverride.
            _invariant(
              isReactClassMethod &&
                (specPolicy === 'DEFINE_MANY_MERGED' ||
                  specPolicy === 'DEFINE_MANY'),
              'ReactClass: Unexpected spec policy %s for key %s ' +
                'when mixing in component specs.',
              specPolicy,
              name
            );

            // For methods which are defined more than once, call the existing
            // methods before calling the new property, merging if appropriate.
            if (specPolicy === 'DEFINE_MANY_MERGED') {
              proto[name] = createMergedResultFunction(proto[name], property);
            } else if (specPolicy === 'DEFINE_MANY') {
              proto[name] = createChainedFunction(proto[name], property);
            }
          } else {
            proto[name] = property;
            if (true) {
              // Add verbose displayName to the function, which helps when looking
              // at profiling tools.
              if (typeof property === 'function' && spec.displayName) {
                proto[name].displayName = spec.displayName + '_' + name;
              }
            }
          }
        }
      }
    }
  }

  function mixStaticSpecIntoComponent(Constructor, statics) {
    if (!statics) {
      return;
    }

    for (var name in statics) {
      var property = statics[name];
      if (!statics.hasOwnProperty(name)) {
        continue;
      }

      var isReserved = name in RESERVED_SPEC_KEYS;
      _invariant(
        !isReserved,
        'ReactClass: You are attempting to define a reserved ' +
          'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' +
          'as an instance property instead; it will still be accessible on the ' +
          'constructor.',
        name
      );

      var isAlreadyDefined = name in Constructor;
      if (isAlreadyDefined) {
        var specPolicy = ReactClassStaticInterface.hasOwnProperty(name)
          ? ReactClassStaticInterface[name]
          : null;

        _invariant(
          specPolicy === 'DEFINE_MANY_MERGED',
          'ReactClass: You are attempting to define ' +
            '`%s` on your component more than once. This conflict may be ' +
            'due to a mixin.',
          name
        );

        Constructor[name] = createMergedResultFunction(Constructor[name], property);

        return;
      }

      Constructor[name] = property;
    }
  }

  /**
   * Merge two objects, but throw if both contain the same key.
   *
   * @param {object} one The first object, which is mutated.
   * @param {object} two The second object
   * @return {object} one after it has been mutated to contain everything in two.
   */
  function mergeIntoWithNoDuplicateKeys(one, two) {
    _invariant(
      one && two && typeof one === 'object' && typeof two === 'object',
      'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.'
    );

    for (var key in two) {
      if (two.hasOwnProperty(key)) {
        _invariant(
          one[key] === undefined,
          'mergeIntoWithNoDuplicateKeys(): ' +
            'Tried to merge two objects with the same key: `%s`. This conflict ' +
            'may be due to a mixin; in particular, this may be caused by two ' +
            'getInitialState() or getDefaultProps() methods returning objects ' +
            'with clashing keys.',
          key
        );
        one[key] = two[key];
      }
    }
    return one;
  }

  /**
   * Creates a function that invokes two functions and merges their return values.
   *
   * @param {function} one Function to invoke first.
   * @param {function} two Function to invoke second.
   * @return {function} Function that invokes the two argument functions.
   * @private
   */
  function createMergedResultFunction(one, two) {
    return function mergedResult() {
      var a = one.apply(this, arguments);
      var b = two.apply(this, arguments);
      if (a == null) {
        return b;
      } else if (b == null) {
        return a;
      }
      var c = {};
      mergeIntoWithNoDuplicateKeys(c, a);
      mergeIntoWithNoDuplicateKeys(c, b);
      return c;
    };
  }

  /**
   * Creates a function that invokes two functions and ignores their return vales.
   *
   * @param {function} one Function to invoke first.
   * @param {function} two Function to invoke second.
   * @return {function} Function that invokes the two argument functions.
   * @private
   */
  function createChainedFunction(one, two) {
    return function chainedFunction() {
      one.apply(this, arguments);
      two.apply(this, arguments);
    };
  }

  /**
   * Binds a method to the component.
   *
   * @param {object} component Component whose method is going to be bound.
   * @param {function} method Method to be bound.
   * @return {function} The bound method.
   */
  function bindAutoBindMethod(component, method) {
    var boundMethod = method.bind(component);
    if (true) {
      boundMethod.__reactBoundContext = component;
      boundMethod.__reactBoundMethod = method;
      boundMethod.__reactBoundArguments = null;
      var componentName = component.constructor.displayName;
      var _bind = boundMethod.bind;
      boundMethod.bind = function(newThis) {
        for (
          var _len = arguments.length,
            args = Array(_len > 1 ? _len - 1 : 0),
            _key = 1;
          _key < _len;
          _key++
        ) {
          args[_key - 1] = arguments[_key];
        }

        // User is trying to bind() an autobound method; we effectively will
        // ignore the value of "this" that the user is trying to use, so
        // let's warn.
        if (newThis !== component && newThis !== null) {
          if (true) {
            warning(
              false,
              'bind(): React component methods may only be bound to the ' +
                'component instance. See %s',
              componentName
            );
          }
        } else if (!args.length) {
          if (true) {
            warning(
              false,
              'bind(): You are binding a component method to the component. ' +
                'React does this for you automatically in a high-performance ' +
                'way, so you can safely remove this call. See %s',
              componentName
            );
          }
          return boundMethod;
        }
        var reboundMethod = _bind.apply(boundMethod, arguments);
        reboundMethod.__reactBoundContext = component;
        reboundMethod.__reactBoundMethod = method;
        reboundMethod.__reactBoundArguments = args;
        return reboundMethod;
      };
    }
    return boundMethod;
  }

  /**
   * Binds all auto-bound methods in a component.
   *
   * @param {object} component Component whose method is going to be bound.
   */
  function bindAutoBindMethods(component) {
    var pairs = component.__reactAutoBindPairs;
    for (var i = 0; i < pairs.length; i += 2) {
      var autoBindKey = pairs[i];
      var method = pairs[i + 1];
      component[autoBindKey] = bindAutoBindMethod(component, method);
    }
  }

  var IsMountedPreMixin = {
    componentDidMount: function() {
      this.__isMounted = true;
    }
  };

  var IsMountedPostMixin = {
    componentWillUnmount: function() {
      this.__isMounted = false;
    }
  };

  /**
   * Add more to the ReactClass base class. These are all legacy features and
   * therefore not already part of the modern ReactComponent.
   */
  var ReactClassMixin = {
    /**
     * TODO: This will be deprecated because state should always keep a consistent
     * type signature and the only use case for this, is to avoid that.
     */
    replaceState: function(newState, callback) {
      this.updater.enqueueReplaceState(this, newState, callback);
    },

    /**
     * Checks whether or not this composite component is mounted.
     * @return {boolean} True if mounted, false otherwise.
     * @protected
     * @final
     */
    isMounted: function() {
      if (true) {
        warning(
          this.__didWarnIsMounted,
          '%s: isMounted is deprecated. Instead, make sure to clean up ' +
            'subscriptions and pending requests in componentWillUnmount to ' +
            'prevent memory leaks.',
          (this.constructor && this.constructor.displayName) ||
            this.name ||
            'Component'
        );
        this.__didWarnIsMounted = true;
      }
      return !!this.__isMounted;
    }
  };

  var ReactClassComponent = function() {};
  _assign(
    ReactClassComponent.prototype,
    ReactComponent.prototype,
    ReactClassMixin
  );

  /**
   * Creates a composite component class given a class specification.
   * See https://facebook.github.io/react/docs/top-level-api.html#react.createclass
   *
   * @param {object} spec Class specification (which must define `render`).
   * @return {function} Component constructor function.
   * @public
   */
  function createClass(spec) {
    // To keep our warnings more understandable, we'll use a little hack here to
    // ensure that Constructor.name !== 'Constructor'. This makes sure we don't
    // unnecessarily identify a class without displayName as 'Constructor'.
    var Constructor = identity(function(props, context, updater) {
      // This constructor gets overridden by mocks. The argument is used
      // by mocks to assert on what gets mounted.

      if (true) {
        warning(
          this instanceof Constructor,
          'Something is calling a React component directly. Use a factory or ' +
            'JSX instead. See: https://fb.me/react-legacyfactory'
        );
      }

      // Wire up auto-binding
      if (this.__reactAutoBindPairs.length) {
        bindAutoBindMethods(this);
      }

      this.props = props;
      this.context = context;
      this.refs = emptyObject;
      this.updater = updater || ReactNoopUpdateQueue;

      this.state = null;

      // ReactClasses doesn't have constructors. Instead, they use the
      // getInitialState and componentWillMount methods for initialization.

      var initialState = this.getInitialState ? this.getInitialState() : null;
      if (true) {
        // We allow auto-mocks to proceed as if they're returning null.
        if (
          initialState === undefined &&
          this.getInitialState._isMockFunction
        ) {
          // This is probably bad practice. Consider warning here and
          // deprecating this convenience.
          initialState = null;
        }
      }
      _invariant(
        typeof initialState === 'object' && !Array.isArray(initialState),
        '%s.getInitialState(): must return an object or null',
        Constructor.displayName || 'ReactCompositeComponent'
      );

      this.state = initialState;
    });
    Constructor.prototype = new ReactClassComponent();
    Constructor.prototype.constructor = Constructor;
    Constructor.prototype.__reactAutoBindPairs = [];

    injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor));

    mixSpecIntoComponent(Constructor, IsMountedPreMixin);
    mixSpecIntoComponent(Constructor, spec);
    mixSpecIntoComponent(Constructor, IsMountedPostMixin);

    // Initialize the defaultProps property after all mixins have been merged.
    if (Constructor.getDefaultProps) {
      Constructor.defaultProps = Constructor.getDefaultProps();
    }

    if (true) {
      // This is a tag to indicate that the use of these method names is ok,
      // since it's used with createClass. If it's not, then it's likely a
      // mistake so we'll warn you to use the static property, property
      // initializer or constructor respectively.
      if (Constructor.getDefaultProps) {
        Constructor.getDefaultProps.isReactClassApproved = {};
      }
      if (Constructor.prototype.getInitialState) {
        Constructor.prototype.getInitialState.isReactClassApproved = {};
      }
    }

    _invariant(
      Constructor.prototype.render,
      'createClass(...): Class specification must implement a `render` method.'
    );

    if (true) {
      warning(
        !Constructor.prototype.componentShouldUpdate,
        '%s has a method called ' +
          'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
          'The name is phrased as a question because the function is ' +
          'expected to return a value.',
        spec.displayName || 'A component'
      );
      warning(
        !Constructor.prototype.componentWillRecieveProps,
        '%s has a method called ' +
          'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?',
        spec.displayName || 'A component'
      );
      warning(
        !Constructor.prototype.UNSAFE_componentWillRecieveProps,
        '%s has a method called UNSAFE_componentWillRecieveProps(). ' +
          'Did you mean UNSAFE_componentWillReceiveProps()?',
        spec.displayName || 'A component'
      );
    }

    // Reduce time spent doing lookups by setting these on the prototype.
    for (var methodName in ReactClassInterface) {
      if (!Constructor.prototype[methodName]) {
        Constructor.prototype[methodName] = null;
      }
    }

    return Constructor;
  }

  return createClass;
}

module.exports = factory;


/***/ }),

/***/ "lTKM":
/*!************************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/filter_visible.js ***!
  \************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



/** Filter out object items with visible !== true
 *  insider array container.
 *
 *  @param {array of objects} container
 *  @return {array of objects} of length <= container
 *
 */
module.exports = function filterVisible(container) {
    var filterFn = isCalcData(container) ? calcDataFilter : baseFilter;
    var out = [];

    for(var i = 0; i < container.length; i++) {
        var item = container[i];
        if(filterFn(item)) out.push(item);
    }

    return out;
};

function baseFilter(item) {
    return item.visible === true;
}

function calcDataFilter(item) {
    return item[0].trace.visible === true;
}

function isCalcData(cont) {
    return (
        Array.isArray(cont) &&
        Array.isArray(cont[0]) &&
        cont[0][0] &&
        cont[0][0].trace
    );
}


/***/ }),

/***/ "lV/m":
/*!********************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/terminal/terminal.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const default_1 = __webpack_require__(/*! ./default */ "tJ7k");
/**
 * The namespace for ISession statics.
 */
var TerminalSession;
(function (TerminalSession) {
    /**
     * Test whether the terminal service is available.
     */
    function isAvailable() {
        return default_1.DefaultTerminalSession.isAvailable();
    }
    TerminalSession.isAvailable = isAvailable;
    /**
     * Start a new terminal session.
     *
     * @param options - The session options to use.
     *
     * @returns A promise that resolves with the session instance.
     */
    function startNew(options) {
        return default_1.DefaultTerminalSession.startNew(options);
    }
    TerminalSession.startNew = startNew;
    /*
     * Connect to a running session.
     *
     * @param name - The name of the target session.
     *
     * @param options - The session options to use.
     *
     * @returns A promise that resolves with the new session instance.
     *
     * #### Notes
     * If the session was already started via `startNew`, the existing
     * session object is used as the fulfillment value.
     *
     * Otherwise, if `options` are given, we resolve the promise after
     * confirming that the session exists on the server.
     *
     * If the session does not exist on the server, the promise is rejected.
     */
    function connectTo(name, options) {
        return default_1.DefaultTerminalSession.connectTo(name, options);
    }
    TerminalSession.connectTo = connectTo;
    /**
     * List the running terminal sessions.
     *
     * @param settings - The server settings to use.
     *
     * @returns A promise that resolves with the list of running session models.
     */
    function listRunning(settings) {
        return default_1.DefaultTerminalSession.listRunning(settings);
    }
    TerminalSession.listRunning = listRunning;
    /**
     * Shut down a terminal session by name.
     *
     * @param name - The name of the target session.
     *
     * @param settings - The server settings to use.
     *
     * @returns A promise that resolves when the session is shut down.
     */
    function shutdown(name, settings) {
        return default_1.DefaultTerminalSession.shutdown(name, settings);
    }
    TerminalSession.shutdown = shutdown;
    /**
     * Shut down all terminal sessions.
     *
     * @returns A promise that resolves when all of the sessions are shut down.
     */
    function shutdownAll(settings) {
        return default_1.DefaultTerminalSession.shutdownAll(settings);
    }
    TerminalSession.shutdownAll = shutdownAll;
})(TerminalSession = exports.TerminalSession || (exports.TerminalSession = {}));


/***/ }),

/***/ "lWpZ":
/*!***************************************************!*\
  !*** ./node_modules/browserify-cipher/browser.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var DES = __webpack_require__(/*! browserify-des */ "Hjy1")
var aes = __webpack_require__(/*! browserify-aes/browser */ "/ab2")
var aesModes = __webpack_require__(/*! browserify-aes/modes */ "usKN")
var desModes = __webpack_require__(/*! browserify-des/modes */ "C+gy")
var ebtk = __webpack_require__(/*! evp_bytestokey */ "roQf")

function createCipher (suite, password) {
  suite = suite.toLowerCase()

  var keyLen, ivLen
  if (aesModes[suite]) {
    keyLen = aesModes[suite].key
    ivLen = aesModes[suite].iv
  } else if (desModes[suite]) {
    keyLen = desModes[suite].key * 8
    ivLen = desModes[suite].iv
  } else {
    throw new TypeError('invalid suite type')
  }

  var keys = ebtk(password, false, keyLen, ivLen)
  return createCipheriv(suite, keys.key, keys.iv)
}

function createDecipher (suite, password) {
  suite = suite.toLowerCase()

  var keyLen, ivLen
  if (aesModes[suite]) {
    keyLen = aesModes[suite].key
    ivLen = aesModes[suite].iv
  } else if (desModes[suite]) {
    keyLen = desModes[suite].key * 8
    ivLen = desModes[suite].iv
  } else {
    throw new TypeError('invalid suite type')
  }

  var keys = ebtk(password, false, keyLen, ivLen)
  return createDecipheriv(suite, keys.key, keys.iv)
}

function createCipheriv (suite, key, iv) {
  suite = suite.toLowerCase()
  if (aesModes[suite]) return aes.createCipheriv(suite, key, iv)
  if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite })

  throw new TypeError('invalid suite type')
}

function createDecipheriv (suite, key, iv) {
  suite = suite.toLowerCase()
  if (aesModes[suite]) return aes.createDecipheriv(suite, key, iv)
  if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite, decrypt: true })

  throw new TypeError('invalid suite type')
}

function getCiphers () {
  return Object.keys(desModes).concat(aes.getCiphers())
}

exports.createCipher = exports.Cipher = createCipher
exports.createCipheriv = exports.Cipheriv = createCipheriv
exports.createDecipher = exports.Decipher = createDecipher
exports.createDecipheriv = exports.Decipheriv = createDecipheriv
exports.listCiphers = exports.getCiphers = getCiphers


/***/ }),

/***/ "lXzo":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/ru.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


function plural(word, num) {
    var forms = word.split('_');
    return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]);
}
function relativeTimeWithPlural(number, withoutSuffix, key) {
    var format = {
        'ss': withoutSuffix ? 'секунда_секунды_секунд' : 'секунду_секунды_секунд',
        'mm': withoutSuffix ? 'минута_минуты_минут' : 'минуту_минуты_минут',
        'hh': 'час_часа_часов',
        'dd': 'день_дня_дней',
        'MM': 'месяц_месяца_месяцев',
        'yy': 'год_года_лет'
    };
    if (key === 'm') {
        return withoutSuffix ? 'минута' : 'минуту';
    }
    else {
        return number + ' ' + plural(format[key], +number);
    }
}
var monthsParse = [/^янв/i, /^фев/i, /^мар/i, /^апр/i, /^ма[йя]/i, /^июн/i, /^июл/i, /^авг/i, /^сен/i, /^окт/i, /^ноя/i, /^дек/i];

// http://new.gramota.ru/spravka/rules/139-prop : § 103
// Сокращения месяцев: http://new.gramota.ru/spravka/buro/search-answer?s=242637
// CLDR data:          http://www.unicode.org/cldr/charts/28/summary/ru.html#1753
var ru = moment.defineLocale('ru', {
    months : {
        format: 'января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря'.split('_'),
        standalone: 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_')
    },
    monthsShort : {
        // по CLDR именно "июл." и "июн.", но какой смысл менять букву на точку ?
        format: 'янв._февр._мар._апр._мая_июня_июля_авг._сент._окт._нояб._дек.'.split('_'),
        standalone: 'янв._февр._март_апр._май_июнь_июль_авг._сент._окт._нояб._дек.'.split('_')
    },
    weekdays : {
        standalone: 'воскресенье_понедельник_вторник_среда_четверг_пятница_суббота'.split('_'),
        format: 'воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу'.split('_'),
        isFormat: /\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?\] ?dddd/
    },
    weekdaysShort : 'вс_пн_вт_ср_чт_пт_сб'.split('_'),
    weekdaysMin : 'вс_пн_вт_ср_чт_пт_сб'.split('_'),
    monthsParse : monthsParse,
    longMonthsParse : monthsParse,
    shortMonthsParse : monthsParse,

    // полные названия с падежами, по три буквы, для некоторых, по 4 буквы, сокращения с точкой и без точки
    monthsRegex: /^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i,

    // копия предыдущего
    monthsShortRegex: /^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i,

    // полные названия с падежами
    monthsStrictRegex: /^(январ[яь]|феврал[яь]|марта?|апрел[яь]|ма[яй]|июн[яь]|июл[яь]|августа?|сентябр[яь]|октябр[яь]|ноябр[яь]|декабр[яь])/i,

    // Выражение, которое соотвествует только сокращённым формам
    monthsShortStrictRegex: /^(янв\.|февр?\.|мар[т.]|апр\.|ма[яй]|июн[ья.]|июл[ья.]|авг\.|сент?\.|окт\.|нояб?\.|дек\.)/i,
    longDateFormat : {
        LT : 'H:mm',
        LTS : 'H:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D MMMM YYYY г.',
        LLL : 'D MMMM YYYY г., H:mm',
        LLLL : 'dddd, D MMMM YYYY г., H:mm'
    },
    calendar : {
        sameDay: '[Сегодня в] LT',
        nextDay: '[Завтра в] LT',
        lastDay: '[Вчера в] LT',
        nextWeek: function (now) {
            if (now.week() !== this.week()) {
                switch (this.day()) {
                    case 0:
                        return '[В следующее] dddd [в] LT';
                    case 1:
                    case 2:
                    case 4:
                        return '[В следующий] dddd [в] LT';
                    case 3:
                    case 5:
                    case 6:
                        return '[В следующую] dddd [в] LT';
                }
            } else {
                if (this.day() === 2) {
                    return '[Во] dddd [в] LT';
                } else {
                    return '[В] dddd [в] LT';
                }
            }
        },
        lastWeek: function (now) {
            if (now.week() !== this.week()) {
                switch (this.day()) {
                    case 0:
                        return '[В прошлое] dddd [в] LT';
                    case 1:
                    case 2:
                    case 4:
                        return '[В прошлый] dddd [в] LT';
                    case 3:
                    case 5:
                    case 6:
                        return '[В прошлую] dddd [в] LT';
                }
            } else {
                if (this.day() === 2) {
                    return '[Во] dddd [в] LT';
                } else {
                    return '[В] dddd [в] LT';
                }
            }
        },
        sameElse: 'L'
    },
    relativeTime : {
        future : 'через %s',
        past : '%s назад',
        s : 'несколько секунд',
        ss : relativeTimeWithPlural,
        m : relativeTimeWithPlural,
        mm : relativeTimeWithPlural,
        h : 'час',
        hh : relativeTimeWithPlural,
        d : 'день',
        dd : relativeTimeWithPlural,
        M : 'месяц',
        MM : relativeTimeWithPlural,
        y : 'год',
        yy : relativeTimeWithPlural
    },
    meridiemParse: /ночи|утра|дня|вечера/i,
    isPM : function (input) {
        return /^(дня|вечера)$/.test(input);
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 4) {
            return 'ночи';
        } else if (hour < 12) {
            return 'утра';
        } else if (hour < 17) {
            return 'дня';
        } else {
            return 'вечера';
        }
    },
    dayOfMonthOrdinalParse: /\d{1,2}-(й|го|я)/,
    ordinal: function (number, period) {
        switch (period) {
            case 'M':
            case 'd':
            case 'DDD':
                return number + '-й';
            case 'D':
                return number + '-го';
            case 'w':
            case 'W':
                return number + '-я';
            default:
                return number;
        }
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return ru;

})));


/***/ }),

/***/ "lZ34":
/*!****************************************************!*\
  !*** ./node_modules/fbjs/lib/camelizeStyleName.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks
 */



var camelize = __webpack_require__(/*! ./camelize */ "NgHg");

var msPattern = /^-ms-/;

/**
 * Camelcases a hyphenated CSS property name, for example:
 *
 *   > camelizeStyleName('background-color')
 *   < "backgroundColor"
 *   > camelizeStyleName('-moz-transition')
 *   < "MozTransition"
 *   > camelizeStyleName('-ms-transition')
 *   < "msTransition"
 *
 * As Andi Smith suggests
 * (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
 * is converted to lowercase `ms`.
 *
 * @param {string} string
 * @return {string}
 */
function camelizeStyleName(string) {
  return camelize(string.replace(msPattern, 'ms-'));
}

module.exports = camelizeStyleName;

/***/ }),

/***/ "lZu9":
/*!***********************************************************!*\
  !*** ./node_modules/codemirror/mode/markdown/markdown.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"), __webpack_require__(/*! ../xml/xml */ "1eCo"), __webpack_require__(/*! ../meta */ "8EBN"));
  else {}
})(function(CodeMirror) {
"use strict";

CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) {

  var htmlMode = CodeMirror.getMode(cmCfg, "text/html");
  var htmlModeMissing = htmlMode.name == "null"

  function getMode(name) {
    if (CodeMirror.findModeByName) {
      var found = CodeMirror.findModeByName(name);
      if (found) name = found.mime || found.mimes[0];
    }
    var mode = CodeMirror.getMode(cmCfg, name);
    return mode.name == "null" ? null : mode;
  }

  // Should characters that affect highlighting be highlighted separate?
  // Does not include characters that will be output (such as `1.` and `-` for lists)
  if (modeCfg.highlightFormatting === undefined)
    modeCfg.highlightFormatting = false;

  // Maximum number of nested blockquotes. Set to 0 for infinite nesting.
  // Excess `>` will emit `error` token.
  if (modeCfg.maxBlockquoteDepth === undefined)
    modeCfg.maxBlockquoteDepth = 0;

  // Turn on task lists? ("- [ ] " and "- [x] ")
  if (modeCfg.taskLists === undefined) modeCfg.taskLists = false;

  // Turn on strikethrough syntax
  if (modeCfg.strikethrough === undefined)
    modeCfg.strikethrough = false;

  if (modeCfg.emoji === undefined)
    modeCfg.emoji = false;

  if (modeCfg.fencedCodeBlockHighlighting === undefined)
    modeCfg.fencedCodeBlockHighlighting = true;

  if (modeCfg.xml === undefined)
    modeCfg.xml = true;

  // Allow token types to be overridden by user-provided token types.
  if (modeCfg.tokenTypeOverrides === undefined)
    modeCfg.tokenTypeOverrides = {};

  var tokenTypes = {
    header: "header",
    code: "comment",
    quote: "quote",
    list1: "variable-2",
    list2: "variable-3",
    list3: "keyword",
    hr: "hr",
    image: "image",
    imageAltText: "image-alt-text",
    imageMarker: "image-marker",
    formatting: "formatting",
    linkInline: "link",
    linkEmail: "link",
    linkText: "link",
    linkHref: "string",
    em: "em",
    strong: "strong",
    strikethrough: "strikethrough",
    emoji: "builtin"
  };

  for (var tokenType in tokenTypes) {
    if (tokenTypes.hasOwnProperty(tokenType) && modeCfg.tokenTypeOverrides[tokenType]) {
      tokenTypes[tokenType] = modeCfg.tokenTypeOverrides[tokenType];
    }
  }

  var hrRE = /^([*\-_])(?:\s*\1){2,}\s*$/
  ,   listRE = /^(?:[*\-+]|^[0-9]+([.)]))\s+/
  ,   taskListRE = /^\[(x| )\](?=\s)/i // Must follow listRE
  ,   atxHeaderRE = modeCfg.allowAtxHeaderWithoutSpace ? /^(#+)/ : /^(#+)(?: |$)/
  ,   setextHeaderRE = /^ *(?:\={1,}|-{1,})\s*$/
  ,   textRE = /^[^#!\[\]*_\\<>` "'(~:]+/
  ,   fencedCodeRE = /^(~~~+|```+)[ \t]*([\w+#-]*)[^\n`]*$/
  ,   linkDefRE = /^\s*\[[^\]]+?\]:.*$/ // naive link-definition
  ,   punctuation = /[!\"#$%&\'()*+,\-\.\/:;<=>?@\[\\\]^_`{|}~—]/
  ,   expandedTab = "    " // CommonMark specifies tab as 4 spaces

  function switchInline(stream, state, f) {
    state.f = state.inline = f;
    return f(stream, state);
  }

  function switchBlock(stream, state, f) {
    state.f = state.block = f;
    return f(stream, state);
  }

  function lineIsEmpty(line) {
    return !line || !/\S/.test(line.string)
  }

  // Blocks

  function blankLine(state) {
    // Reset linkTitle state
    state.linkTitle = false;
    state.linkHref = false;
    state.linkText = false;
    // Reset EM state
    state.em = false;
    // Reset STRONG state
    state.strong = false;
    // Reset strikethrough state
    state.strikethrough = false;
    // Reset state.quote
    state.quote = 0;
    // Reset state.indentedCode
    state.indentedCode = false;
    if (state.f == htmlBlock) {
      var exit = htmlModeMissing
      if (!exit) {
        var inner = CodeMirror.innerMode(htmlMode, state.htmlState)
        exit = inner.mode.name == "xml" && inner.state.tagStart === null &&
          (!inner.state.context && inner.state.tokenize.isInText)
      }
      if (exit) {
        state.f = inlineNormal;
        state.block = blockNormal;
        state.htmlState = null;
      }
    }
    // Reset state.trailingSpace
    state.trailingSpace = 0;
    state.trailingSpaceNewLine = false;
    // Mark this line as blank
    state.prevLine = state.thisLine
    state.thisLine = {stream: null}
    return null;
  }

  function blockNormal(stream, state) {
    var firstTokenOnLine = stream.column() === state.indentation;
    var prevLineLineIsEmpty = lineIsEmpty(state.prevLine.stream);
    var prevLineIsIndentedCode = state.indentedCode;
    var prevLineIsHr = state.prevLine.hr;
    var prevLineIsList = state.list !== false;
    var maxNonCodeIndentation = (state.listStack[state.listStack.length - 1] || 0) + 3;

    state.indentedCode = false;

    var lineIndentation = state.indentation;
    // compute once per line (on first token)
    if (state.indentationDiff === null) {
      state.indentationDiff = state.indentation;
      if (prevLineIsList) {
        // Reset inline styles which shouldn't propagate aross list items
        state.em = false;
        state.strong = false;
        state.code = false;
        state.strikethrough = false;

        state.list = null;
        // While this list item's marker's indentation is less than the deepest
        //  list item's content's indentation,pop the deepest list item
        //  indentation off the stack, and update block indentation state
        while (lineIndentation < state.listStack[state.listStack.length - 1]) {
          state.listStack.pop();
          if (state.listStack.length) {
            state.indentation = state.listStack[state.listStack.length - 1];
          // less than the first list's indent -> the line is no longer a list
          } else {
            state.list = false;
          }
        }
        if (state.list !== false) {
          state.indentationDiff = lineIndentation - state.listStack[state.listStack.length - 1]
        }
      }
    }

    // not comprehensive (currently only for setext detection purposes)
    var allowsInlineContinuation = (
        !prevLineLineIsEmpty && !prevLineIsHr && !state.prevLine.header &&
        (!prevLineIsList || !prevLineIsIndentedCode) &&
        !state.prevLine.fencedCodeEnd
    );

    var isHr = (state.list === false || prevLineIsHr || prevLineLineIsEmpty) &&
      state.indentation <= maxNonCodeIndentation && stream.match(hrRE);

    var match = null;
    if (state.indentationDiff >= 4 && (prevLineIsIndentedCode || state.prevLine.fencedCodeEnd ||
         state.prevLine.header || prevLineLineIsEmpty)) {
      stream.skipToEnd();
      state.indentedCode = true;
      return tokenTypes.code;
    } else if (stream.eatSpace()) {
      return null;
    } else if (firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(atxHeaderRE)) && match[1].length <= 6) {
      state.quote = 0;
      state.header = match[1].length;
      state.thisLine.header = true;
      if (modeCfg.highlightFormatting) state.formatting = "header";
      state.f = state.inline;
      return getType(state);
    } else if (state.indentation <= maxNonCodeIndentation && stream.eat('>')) {
      state.quote = firstTokenOnLine ? 1 : state.quote + 1;
      if (modeCfg.highlightFormatting) state.formatting = "quote";
      stream.eatSpace();
      return getType(state);
    } else if (!isHr && !state.setext && firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(listRE))) {
      var listType = match[1] ? "ol" : "ul";

      state.indentation = lineIndentation + stream.current().length;
      state.list = true;
      state.quote = 0;

      // Add this list item's content's indentation to the stack
      state.listStack.push(state.indentation);

      if (modeCfg.taskLists && stream.match(taskListRE, false)) {
        state.taskList = true;
      }
      state.f = state.inline;
      if (modeCfg.highlightFormatting) state.formatting = ["list", "list-" + listType];
      return getType(state);
    } else if (firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(fencedCodeRE, true))) {
      state.quote = 0;
      state.fencedEndRE = new RegExp(match[1] + "+ *$");
      // try switching mode
      state.localMode = modeCfg.fencedCodeBlockHighlighting && getMode(match[2]);
      if (state.localMode) state.localState = CodeMirror.startState(state.localMode);
      state.f = state.block = local;
      if (modeCfg.highlightFormatting) state.formatting = "code-block";
      state.code = -1
      return getType(state);
    // SETEXT has lowest block-scope precedence after HR, so check it after
    //  the others (code, blockquote, list...)
    } else if (
      // if setext set, indicates line after ---/===
      state.setext || (
        // line before ---/===
        (!allowsInlineContinuation || !prevLineIsList) && !state.quote && state.list === false &&
        !state.code && !isHr && !linkDefRE.test(stream.string) &&
        (match = stream.lookAhead(1)) && (match = match.match(setextHeaderRE))
      )
    ) {
      if ( !state.setext ) {
        state.header = match[0].charAt(0) == '=' ? 1 : 2;
        state.setext = state.header;
      } else {
        state.header = state.setext;
        // has no effect on type so we can reset it now
        state.setext = 0;
        stream.skipToEnd();
        if (modeCfg.highlightFormatting) state.formatting = "header";
      }
      state.thisLine.header = true;
      state.f = state.inline;
      return getType(state);
    } else if (isHr) {
      stream.skipToEnd();
      state.hr = true;
      state.thisLine.hr = true;
      return tokenTypes.hr;
    } else if (stream.peek() === '[') {
      return switchInline(stream, state, footnoteLink);
    }

    return switchInline(stream, state, state.inline);
  }

  function htmlBlock(stream, state) {
    var style = htmlMode.token(stream, state.htmlState);
    if (!htmlModeMissing) {
      var inner = CodeMirror.innerMode(htmlMode, state.htmlState)
      if ((inner.mode.name == "xml" && inner.state.tagStart === null &&
           (!inner.state.context && inner.state.tokenize.isInText)) ||
          (state.md_inside && stream.current().indexOf(">") > -1)) {
        state.f = inlineNormal;
        state.block = blockNormal;
        state.htmlState = null;
      }
    }
    return style;
  }

  function local(stream, state) {
    var currListInd = state.listStack[state.listStack.length - 1] || 0;
    var hasExitedList = state.indentation < currListInd;
    var maxFencedEndInd = currListInd + 3;
    if (state.fencedEndRE && state.indentation <= maxFencedEndInd && (hasExitedList || stream.match(state.fencedEndRE))) {
      if (modeCfg.highlightFormatting) state.formatting = "code-block";
      var returnType;
      if (!hasExitedList) returnType = getType(state)
      state.localMode = state.localState = null;
      state.block = blockNormal;
      state.f = inlineNormal;
      state.fencedEndRE = null;
      state.code = 0
      state.thisLine.fencedCodeEnd = true;
      if (hasExitedList) return switchBlock(stream, state, state.block);
      return returnType;
    } else if (state.localMode) {
      return state.localMode.token(stream, state.localState);
    } else {
      stream.skipToEnd();
      return tokenTypes.code;
    }
  }

  // Inline
  function getType(state) {
    var styles = [];

    if (state.formatting) {
      styles.push(tokenTypes.formatting);

      if (typeof state.formatting === "string") state.formatting = [state.formatting];

      for (var i = 0; i < state.formatting.length; i++) {
        styles.push(tokenTypes.formatting + "-" + state.formatting[i]);

        if (state.formatting[i] === "header") {
          styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.header);
        }

        // Add `formatting-quote` and `formatting-quote-#` for blockquotes
        // Add `error` instead if the maximum blockquote nesting depth is passed
        if (state.formatting[i] === "quote") {
          if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {
            styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.quote);
          } else {
            styles.push("error");
          }
        }
      }
    }

    if (state.taskOpen) {
      styles.push("meta");
      return styles.length ? styles.join(' ') : null;
    }
    if (state.taskClosed) {
      styles.push("property");
      return styles.length ? styles.join(' ') : null;
    }

    if (state.linkHref) {
      styles.push(tokenTypes.linkHref, "url");
    } else { // Only apply inline styles to non-url text
      if (state.strong) { styles.push(tokenTypes.strong); }
      if (state.em) { styles.push(tokenTypes.em); }
      if (state.strikethrough) { styles.push(tokenTypes.strikethrough); }
      if (state.emoji) { styles.push(tokenTypes.emoji); }
      if (state.linkText) { styles.push(tokenTypes.linkText); }
      if (state.code) { styles.push(tokenTypes.code); }
      if (state.image) { styles.push(tokenTypes.image); }
      if (state.imageAltText) { styles.push(tokenTypes.imageAltText, "link"); }
      if (state.imageMarker) { styles.push(tokenTypes.imageMarker); }
    }

    if (state.header) { styles.push(tokenTypes.header, tokenTypes.header + "-" + state.header); }

    if (state.quote) {
      styles.push(tokenTypes.quote);

      // Add `quote-#` where the maximum for `#` is modeCfg.maxBlockquoteDepth
      if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {
        styles.push(tokenTypes.quote + "-" + state.quote);
      } else {
        styles.push(tokenTypes.quote + "-" + modeCfg.maxBlockquoteDepth);
      }
    }

    if (state.list !== false) {
      var listMod = (state.listStack.length - 1) % 3;
      if (!listMod) {
        styles.push(tokenTypes.list1);
      } else if (listMod === 1) {
        styles.push(tokenTypes.list2);
      } else {
        styles.push(tokenTypes.list3);
      }
    }

    if (state.trailingSpaceNewLine) {
      styles.push("trailing-space-new-line");
    } else if (state.trailingSpace) {
      styles.push("trailing-space-" + (state.trailingSpace % 2 ? "a" : "b"));
    }

    return styles.length ? styles.join(' ') : null;
  }

  function handleText(stream, state) {
    if (stream.match(textRE, true)) {
      return getType(state);
    }
    return undefined;
  }

  function inlineNormal(stream, state) {
    var style = state.text(stream, state);
    if (typeof style !== 'undefined')
      return style;

    if (state.list) { // List marker (*, +, -, 1., etc)
      state.list = null;
      return getType(state);
    }

    if (state.taskList) {
      var taskOpen = stream.match(taskListRE, true)[1] === " ";
      if (taskOpen) state.taskOpen = true;
      else state.taskClosed = true;
      if (modeCfg.highlightFormatting) state.formatting = "task";
      state.taskList = false;
      return getType(state);
    }

    state.taskOpen = false;
    state.taskClosed = false;

    if (state.header && stream.match(/^#+$/, true)) {
      if (modeCfg.highlightFormatting) state.formatting = "header";
      return getType(state);
    }

    var ch = stream.next();

    // Matches link titles present on next line
    if (state.linkTitle) {
      state.linkTitle = false;
      var matchCh = ch;
      if (ch === '(') {
        matchCh = ')';
      }
      matchCh = (matchCh+'').replace(/([.?*+^\[\]\\(){}|-])/g, "\\$1");
      var regex = '^\\s*(?:[^' + matchCh + '\\\\]+|\\\\\\\\|\\\\.)' + matchCh;
      if (stream.match(new RegExp(regex), true)) {
        return tokenTypes.linkHref;
      }
    }

    // If this block is changed, it may need to be updated in GFM mode
    if (ch === '`') {
      var previousFormatting = state.formatting;
      if (modeCfg.highlightFormatting) state.formatting = "code";
      stream.eatWhile('`');
      var count = stream.current().length
      if (state.code == 0 && (!state.quote || count == 1)) {
        state.code = count
        return getType(state)
      } else if (count == state.code) { // Must be exact
        var t = getType(state)
        state.code = 0
        return t
      } else {
        state.formatting = previousFormatting
        return getType(state)
      }
    } else if (state.code) {
      return getType(state);
    }

    if (ch === '\\') {
      stream.next();
      if (modeCfg.highlightFormatting) {
        var type = getType(state);
        var formattingEscape = tokenTypes.formatting + "-escape";
        return type ? type + " " + formattingEscape : formattingEscape;
      }
    }

    if (ch === '!' && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) {
      state.imageMarker = true;
      state.image = true;
      if (modeCfg.highlightFormatting) state.formatting = "image";
      return getType(state);
    }

    if (ch === '[' && state.imageMarker && stream.match(/[^\]]*\](\(.*?\)| ?\[.*?\])/, false)) {
      state.imageMarker = false;
      state.imageAltText = true
      if (modeCfg.highlightFormatting) state.formatting = "image";
      return getType(state);
    }

    if (ch === ']' && state.imageAltText) {
      if (modeCfg.highlightFormatting) state.formatting = "image";
      var type = getType(state);
      state.imageAltText = false;
      state.image = false;
      state.inline = state.f = linkHref;
      return type;
    }

    if (ch === '[' && !state.image) {
      if (state.linkText && stream.match(/^.*?\]/)) return getType(state)
      state.linkText = true;
      if (modeCfg.highlightFormatting) state.formatting = "link";
      return getType(state);
    }

    if (ch === ']' && state.linkText) {
      if (modeCfg.highlightFormatting) state.formatting = "link";
      var type = getType(state);
      state.linkText = false;
      state.inline = state.f = stream.match(/\(.*?\)| ?\[.*?\]/, false) ? linkHref : inlineNormal
      return type;
    }

    if (ch === '<' && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, false)) {
      state.f = state.inline = linkInline;
      if (modeCfg.highlightFormatting) state.formatting = "link";
      var type = getType(state);
      if (type){
        type += " ";
      } else {
        type = "";
      }
      return type + tokenTypes.linkInline;
    }

    if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, false)) {
      state.f = state.inline = linkInline;
      if (modeCfg.highlightFormatting) state.formatting = "link";
      var type = getType(state);
      if (type){
        type += " ";
      } else {
        type = "";
      }
      return type + tokenTypes.linkEmail;
    }

    if (modeCfg.xml && ch === '<' && stream.match(/^(!--|\?|!\[CDATA\[|[a-z][a-z0-9-]*(?:\s+[a-z_:.\-]+(?:\s*=\s*[^>]+)?)*\s*(?:>|$))/i, false)) {
      var end = stream.string.indexOf(">", stream.pos);
      if (end != -1) {
        var atts = stream.string.substring(stream.start, end);
        if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) state.md_inside = true;
      }
      stream.backUp(1);
      state.htmlState = CodeMirror.startState(htmlMode);
      return switchBlock(stream, state, htmlBlock);
    }

    if (modeCfg.xml && ch === '<' && stream.match(/^\/\w*?>/)) {
      state.md_inside = false;
      return "tag";
    } else if (ch === "*" || ch === "_") {
      var len = 1, before = stream.pos == 1 ? " " : stream.string.charAt(stream.pos - 2)
      while (len < 3 && stream.eat(ch)) len++
      var after = stream.peek() || " "
      // See http://spec.commonmark.org/0.27/#emphasis-and-strong-emphasis
      var leftFlanking = !/\s/.test(after) && (!punctuation.test(after) || /\s/.test(before) || punctuation.test(before))
      var rightFlanking = !/\s/.test(before) && (!punctuation.test(before) || /\s/.test(after) || punctuation.test(after))
      var setEm = null, setStrong = null
      if (len % 2) { // Em
        if (!state.em && leftFlanking && (ch === "*" || !rightFlanking || punctuation.test(before)))
          setEm = true
        else if (state.em == ch && rightFlanking && (ch === "*" || !leftFlanking || punctuation.test(after)))
          setEm = false
      }
      if (len > 1) { // Strong
        if (!state.strong && leftFlanking && (ch === "*" || !rightFlanking || punctuation.test(before)))
          setStrong = true
        else if (state.strong == ch && rightFlanking && (ch === "*" || !leftFlanking || punctuation.test(after)))
          setStrong = false
      }
      if (setStrong != null || setEm != null) {
        if (modeCfg.highlightFormatting) state.formatting = setEm == null ? "strong" : setStrong == null ? "em" : "strong em"
        if (setEm === true) state.em = ch
        if (setStrong === true) state.strong = ch
        var t = getType(state)
        if (setEm === false) state.em = false
        if (setStrong === false) state.strong = false
        return t
      }
    } else if (ch === ' ') {
      if (stream.eat('*') || stream.eat('_')) { // Probably surrounded by spaces
        if (stream.peek() === ' ') { // Surrounded by spaces, ignore
          return getType(state);
        } else { // Not surrounded by spaces, back up pointer
          stream.backUp(1);
        }
      }
    }

    if (modeCfg.strikethrough) {
      if (ch === '~' && stream.eatWhile(ch)) {
        if (state.strikethrough) {// Remove strikethrough
          if (modeCfg.highlightFormatting) state.formatting = "strikethrough";
          var t = getType(state);
          state.strikethrough = false;
          return t;
        } else if (stream.match(/^[^\s]/, false)) {// Add strikethrough
          state.strikethrough = true;
          if (modeCfg.highlightFormatting) state.formatting = "strikethrough";
          return getType(state);
        }
      } else if (ch === ' ') {
        if (stream.match(/^~~/, true)) { // Probably surrounded by space
          if (stream.peek() === ' ') { // Surrounded by spaces, ignore
            return getType(state);
          } else { // Not surrounded by spaces, back up pointer
            stream.backUp(2);
          }
        }
      }
    }

    if (modeCfg.emoji && ch === ":" && stream.match(/^[a-z_\d+-]+:/)) {
      state.emoji = true;
      if (modeCfg.highlightFormatting) state.formatting = "emoji";
      var retType = getType(state);
      state.emoji = false;
      return retType;
    }

    if (ch === ' ') {
      if (stream.match(/^ +$/, false)) {
        state.trailingSpace++;
      } else if (state.trailingSpace) {
        state.trailingSpaceNewLine = true;
      }
    }

    return getType(state);
  }

  function linkInline(stream, state) {
    var ch = stream.next();

    if (ch === ">") {
      state.f = state.inline = inlineNormal;
      if (modeCfg.highlightFormatting) state.formatting = "link";
      var type = getType(state);
      if (type){
        type += " ";
      } else {
        type = "";
      }
      return type + tokenTypes.linkInline;
    }

    stream.match(/^[^>]+/, true);

    return tokenTypes.linkInline;
  }

  function linkHref(stream, state) {
    // Check if space, and return NULL if so (to avoid marking the space)
    if(stream.eatSpace()){
      return null;
    }
    var ch = stream.next();
    if (ch === '(' || ch === '[') {
      state.f = state.inline = getLinkHrefInside(ch === "(" ? ")" : "]");
      if (modeCfg.highlightFormatting) state.formatting = "link-string";
      state.linkHref = true;
      return getType(state);
    }
    return 'error';
  }

  var linkRE = {
    ")": /^(?:[^\\\(\)]|\\.|\((?:[^\\\(\)]|\\.)*\))*?(?=\))/,
    "]": /^(?:[^\\\[\]]|\\.|\[(?:[^\\\[\]]|\\.)*\])*?(?=\])/
  }

  function getLinkHrefInside(endChar) {
    return function(stream, state) {
      var ch = stream.next();

      if (ch === endChar) {
        state.f = state.inline = inlineNormal;
        if (modeCfg.highlightFormatting) state.formatting = "link-string";
        var returnState = getType(state);
        state.linkHref = false;
        return returnState;
      }

      stream.match(linkRE[endChar])
      state.linkHref = true;
      return getType(state);
    };
  }

  function footnoteLink(stream, state) {
    if (stream.match(/^([^\]\\]|\\.)*\]:/, false)) {
      state.f = footnoteLinkInside;
      stream.next(); // Consume [
      if (modeCfg.highlightFormatting) state.formatting = "link";
      state.linkText = true;
      return getType(state);
    }
    return switchInline(stream, state, inlineNormal);
  }

  function footnoteLinkInside(stream, state) {
    if (stream.match(/^\]:/, true)) {
      state.f = state.inline = footnoteUrl;
      if (modeCfg.highlightFormatting) state.formatting = "link";
      var returnType = getType(state);
      state.linkText = false;
      return returnType;
    }

    stream.match(/^([^\]\\]|\\.)+/, true);

    return tokenTypes.linkText;
  }

  function footnoteUrl(stream, state) {
    // Check if space, and return NULL if so (to avoid marking the space)
    if(stream.eatSpace()){
      return null;
    }
    // Match URL
    stream.match(/^[^\s]+/, true);
    // Check for link title
    if (stream.peek() === undefined) { // End of line, set flag to check next line
      state.linkTitle = true;
    } else { // More content on line, check if link title
      stream.match(/^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/, true);
    }
    state.f = state.inline = inlineNormal;
    return tokenTypes.linkHref + " url";
  }

  var mode = {
    startState: function() {
      return {
        f: blockNormal,

        prevLine: {stream: null},
        thisLine: {stream: null},

        block: blockNormal,
        htmlState: null,
        indentation: 0,

        inline: inlineNormal,
        text: handleText,

        formatting: false,
        linkText: false,
        linkHref: false,
        linkTitle: false,
        code: 0,
        em: false,
        strong: false,
        header: 0,
        setext: 0,
        hr: false,
        taskList: false,
        list: false,
        listStack: [],
        quote: 0,
        trailingSpace: 0,
        trailingSpaceNewLine: false,
        strikethrough: false,
        emoji: false,
        fencedEndRE: null
      };
    },

    copyState: function(s) {
      return {
        f: s.f,

        prevLine: s.prevLine,
        thisLine: s.thisLine,

        block: s.block,
        htmlState: s.htmlState && CodeMirror.copyState(htmlMode, s.htmlState),
        indentation: s.indentation,

        localMode: s.localMode,
        localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null,

        inline: s.inline,
        text: s.text,
        formatting: false,
        linkText: s.linkText,
        linkTitle: s.linkTitle,
        linkHref: s.linkHref,
        code: s.code,
        em: s.em,
        strong: s.strong,
        strikethrough: s.strikethrough,
        emoji: s.emoji,
        header: s.header,
        setext: s.setext,
        hr: s.hr,
        taskList: s.taskList,
        list: s.list,
        listStack: s.listStack.slice(0),
        quote: s.quote,
        indentedCode: s.indentedCode,
        trailingSpace: s.trailingSpace,
        trailingSpaceNewLine: s.trailingSpaceNewLine,
        md_inside: s.md_inside,
        fencedEndRE: s.fencedEndRE
      };
    },

    token: function(stream, state) {

      // Reset state.formatting
      state.formatting = false;

      if (stream != state.thisLine.stream) {
        state.header = 0;
        state.hr = false;

        if (stream.match(/^\s*$/, true)) {
          blankLine(state);
          return null;
        }

        state.prevLine = state.thisLine
        state.thisLine = {stream: stream}

        // Reset state.taskList
        state.taskList = false;

        // Reset state.trailingSpace
        state.trailingSpace = 0;
        state.trailingSpaceNewLine = false;

        if (!state.localState) {
          state.f = state.block;
          if (state.f != htmlBlock) {
            var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, expandedTab).length;
            state.indentation = indentation;
            state.indentationDiff = null;
            if (indentation > 0) return null;
          }
        }
      }
      return state.f(stream, state);
    },

    innerMode: function(state) {
      if (state.block == htmlBlock) return {state: state.htmlState, mode: htmlMode};
      if (state.localState) return {state: state.localState, mode: state.localMode};
      return {state: state, mode: mode};
    },

    indent: function(state, textAfter, line) {
      if (state.block == htmlBlock && htmlMode.indent) return htmlMode.indent(state.htmlState, textAfter, line)
      if (state.localState && state.localMode.indent) return state.localMode.indent(state.localState, textAfter, line)
      return CodeMirror.Pass
    },

    blankLine: blankLine,

    getType: getType,

    closeBrackets: "()[]{}''\"\"``",
    fold: "markdown"
  };
  return mode;
}, "xml");

CodeMirror.defineMIME("text/markdown", "markdown");

CodeMirror.defineMIME("text/x-markdown", "markdown");

});


/***/ }),

/***/ "ldDC":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/application/lib/shell.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
/**
 * The class name added to AppShell instances.
 */
const APPLICATION_SHELL_CLASS = 'jp-ApplicationShell';
/**
 * The class name added to side bar instances.
 */
const SIDEBAR_CLASS = 'jp-SideBar';
/**
 * The class name added to the current widget's title.
 */
const CURRENT_CLASS = 'jp-mod-current';
/**
 * The class name added to the active widget's title.
 */
const ACTIVE_CLASS = 'jp-mod-active';
/**
 * The default rank of items added to a sidebar.
 */
const DEFAULT_RANK = 500;
/**
 * The data attribute added to the document body indicating shell's mode.
 */
const MODE_ATTRIBUTE = 'data-shell-mode';
const ACTIVITY_CLASS = 'jp-Activity';
/**
 * The application shell for JupyterLab.
 */
class ApplicationShell extends widgets_1.Widget {
    /**
     * Construct a new application shell.
     */
    constructor() {
        super();
        /**
         * A message hook for child add/remove messages on the main area dock panel.
         */
        this._dockChildHook = (handler, msg) => {
            switch (msg.type) {
                case 'child-added':
                    msg.child.addClass(ACTIVITY_CLASS);
                    this._tracker.add(msg.child);
                    break;
                case 'child-removed':
                    msg.child.removeClass(ACTIVITY_CLASS);
                    this._tracker.remove(msg.child);
                    break;
                default:
                    break;
            }
            return true;
        };
        this._activeChanged = new signaling_1.Signal(this);
        this._cachedLayout = null;
        this._currentChanged = new signaling_1.Signal(this);
        this._isRestored = false;
        this._layoutModified = new signaling_1.Signal(this);
        this._restored = new coreutils_1.PromiseDelegate();
        this._tracker = new widgets_1.FocusTracker();
        this._debouncer = 0;
        this._addOptionsCache = new Map();
        this._sideOptionsCache = new Map();
        this.addClass(APPLICATION_SHELL_CLASS);
        this.id = 'main';
        let bottomPanel = (this._bottomPanel = new widgets_1.BoxPanel());
        let topPanel = (this._topPanel = new widgets_1.Panel());
        let hboxPanel = new widgets_1.BoxPanel();
        let dockPanel = (this._dockPanel = new widgets_1.DockPanel());
        messaging_1.MessageLoop.installMessageHook(dockPanel, this._dockChildHook);
        let hsplitPanel = new widgets_1.SplitPanel();
        let leftHandler = (this._leftHandler = new Private.SideBarHandler('left'));
        let rightHandler = (this._rightHandler = new Private.SideBarHandler('right'));
        let rootLayout = new widgets_1.BoxLayout();
        bottomPanel.id = 'jp-bottom-panel';
        topPanel.id = 'jp-top-panel';
        hboxPanel.id = 'jp-main-content-panel';
        dockPanel.id = 'jp-main-dock-panel';
        hsplitPanel.id = 'jp-main-split-panel';
        leftHandler.sideBar.addClass(SIDEBAR_CLASS);
        leftHandler.sideBar.addClass('jp-mod-left');
        leftHandler.stackedPanel.id = 'jp-left-stack';
        rightHandler.sideBar.addClass(SIDEBAR_CLASS);
        rightHandler.sideBar.addClass('jp-mod-right');
        rightHandler.stackedPanel.id = 'jp-right-stack';
        bottomPanel.direction = 'bottom-to-top';
        hboxPanel.spacing = 0;
        dockPanel.spacing = 5;
        hsplitPanel.spacing = 1;
        hboxPanel.direction = 'left-to-right';
        hsplitPanel.orientation = 'horizontal';
        widgets_1.SplitPanel.setStretch(leftHandler.stackedPanel, 0);
        widgets_1.SplitPanel.setStretch(dockPanel, 1);
        widgets_1.SplitPanel.setStretch(rightHandler.stackedPanel, 0);
        widgets_1.BoxPanel.setStretch(leftHandler.sideBar, 0);
        widgets_1.BoxPanel.setStretch(hsplitPanel, 1);
        widgets_1.BoxPanel.setStretch(rightHandler.sideBar, 0);
        hsplitPanel.addWidget(leftHandler.stackedPanel);
        hsplitPanel.addWidget(dockPanel);
        hsplitPanel.addWidget(rightHandler.stackedPanel);
        hboxPanel.addWidget(leftHandler.sideBar);
        hboxPanel.addWidget(hsplitPanel);
        hboxPanel.addWidget(rightHandler.sideBar);
        rootLayout.direction = 'top-to-bottom';
        rootLayout.spacing = 0; // TODO make this configurable?
        // Use relative sizing to set the width of the side panels.
        // This will still respect the min-size of children widget in the stacked panel.
        hsplitPanel.setRelativeSizes([1, 2.5, 1]);
        widgets_1.BoxLayout.setStretch(topPanel, 0);
        widgets_1.BoxLayout.setStretch(hboxPanel, 1);
        widgets_1.BoxLayout.setStretch(bottomPanel, 0);
        rootLayout.addWidget(topPanel);
        rootLayout.addWidget(hboxPanel);
        rootLayout.addWidget(bottomPanel);
        // initially hiding bottom panel when no elements inside
        this._bottomPanel.hide();
        this.layout = rootLayout;
        // Connect change listeners.
        this._tracker.currentChanged.connect(this._onCurrentChanged, this);
        this._tracker.activeChanged.connect(this._onActiveChanged, this);
        // Connect main layout change listener.
        this._dockPanel.layoutModified.connect(this._onLayoutModified, this);
        // Catch current changed events on the side handlers.
        this._leftHandler.sideBar.currentChanged.connect(this._onLayoutModified, this);
        this._rightHandler.sideBar.currentChanged.connect(this._onLayoutModified, this);
    }
    /**
     * A signal emitted when main area's active focus changes.
     */
    get activeChanged() {
        return this._activeChanged;
    }
    /**
     * The active widget in the shell's main area.
     */
    get activeWidget() {
        return this._tracker.activeWidget;
    }
    /**
     * A signal emitted when main area's current focus changes.
     */
    get currentChanged() {
        return this._currentChanged;
    }
    /**
     * The current widget in the shell's main area.
     */
    get currentWidget() {
        return this._tracker.currentWidget;
    }
    /**
     * A signal emitted when the main area's layout is modified.
     */
    get layoutModified() {
        return this._layoutModified;
    }
    /**
     * Whether the left area is collapsed.
     */
    get leftCollapsed() {
        return !this._leftHandler.sideBar.currentTitle;
    }
    /**
     * Whether the left area is collapsed.
     */
    get rightCollapsed() {
        return !this._rightHandler.sideBar.currentTitle;
    }
    /**
     * Whether JupyterLab is in presentation mode with the `jp-mod-presentationMode` CSS class.
     */
    get presentationMode() {
        return this.hasClass('jp-mod-presentationMode');
    }
    /**
     * Enable/disable presentation mode (`jp-mod-presentationMode` CSS class) with a boolean.
     */
    set presentationMode(value) {
        this.toggleClass('jp-mod-presentationMode', value);
    }
    /**
     * The main dock area's user interface mode.
     */
    get mode() {
        return this._dockPanel.mode;
    }
    set mode(mode) {
        const dock = this._dockPanel;
        if (mode === dock.mode) {
            return;
        }
        const applicationCurrentWidget = this.currentWidget;
        if (mode === 'single-document') {
            this._cachedLayout = dock.saveLayout();
            dock.mode = mode;
            // In case the active widget in the dock panel is *not* the active widget
            // of the application, defer to the application.
            if (this.currentWidget) {
                dock.activateWidget(this.currentWidget);
            }
            // Set the mode data attribute on the document body.
            document.body.setAttribute(MODE_ATTRIBUTE, mode);
            return;
        }
        // Cache a reference to every widget currently in the dock panel.
        const widgets = algorithm_1.toArray(dock.widgets());
        // Toggle back to multiple document mode.
        dock.mode = mode;
        // Restore the original layout.
        if (this._cachedLayout) {
            // Remove any disposed widgets in the cached layout and restore.
            Private.normalizeAreaConfig(dock, this._cachedLayout.main);
            dock.restoreLayout(this._cachedLayout);
            this._cachedLayout = null;
        }
        // Add any widgets created during single document mode, which have
        // subsequently been removed from the dock panel after the multiple document
        // layout has been restored. If the widget has add options cached for
        // it (i.e., if it has been placed with respect to another widget),
        // then take that into account.
        widgets.forEach(widget => {
            if (!widget.parent) {
                this.addToMainArea(widget, Object.assign({}, this._addOptionsCache.get(widget), { activate: false }));
            }
        });
        this._addOptionsCache.clear();
        // In case the active widget in the dock panel is *not* the active widget
        // of the application, defer to the application.
        if (applicationCurrentWidget) {
            dock.activateWidget(applicationCurrentWidget);
        }
        // Set the mode data attribute on the document body.
        document.body.setAttribute(MODE_ATTRIBUTE, mode);
    }
    /**
     * Promise that resolves when state is first restored, returning layout
     * description.
     */
    get restored() {
        return this._restored.promise;
    }
    /**
     * Activate a widget in its area.
     */
    activateById(id) {
        if (this._leftHandler.has(id)) {
            this._leftHandler.activate(id);
            return;
        }
        if (this._rightHandler.has(id)) {
            this._rightHandler.activate(id);
            return;
        }
        const dock = this._dockPanel;
        const widget = algorithm_1.find(dock.widgets(), value => value.id === id);
        if (widget) {
            dock.activateWidget(widget);
        }
    }
    /*
     * Activate the next Tab in the active TabBar.
    */
    activateNextTab() {
        let current = this._currentTabBar();
        if (!current) {
            return;
        }
        let ci = current.currentIndex;
        if (ci === -1) {
            return;
        }
        if (ci < current.titles.length - 1) {
            current.currentIndex += 1;
            if (current.currentTitle) {
                current.currentTitle.owner.activate();
            }
            return;
        }
        if (ci === current.titles.length - 1) {
            let nextBar = this._adjacentBar('next');
            if (nextBar) {
                nextBar.currentIndex = 0;
                if (nextBar.currentTitle) {
                    nextBar.currentTitle.owner.activate();
                }
            }
        }
    }
    /*
     * Activate the previous Tab in the active TabBar.
    */
    activatePreviousTab() {
        let current = this._currentTabBar();
        if (!current) {
            return;
        }
        let ci = current.currentIndex;
        if (ci === -1) {
            return;
        }
        if (ci > 0) {
            current.currentIndex -= 1;
            if (current.currentTitle) {
                current.currentTitle.owner.activate();
            }
            return;
        }
        if (ci === 0) {
            let prevBar = this._adjacentBar('previous');
            if (prevBar) {
                let len = prevBar.titles.length;
                prevBar.currentIndex = len - 1;
                if (prevBar.currentTitle) {
                    prevBar.currentTitle.owner.activate();
                }
            }
        }
    }
    /**
     * Add a widget to the left content area.
     *
     * #### Notes
     * Widgets must have a unique `id` property, which will be used as the DOM id.
     */
    addToLeftArea(widget, options) {
        if (!widget.id) {
            console.error('Widgets added to app shell must have unique id property.');
            return;
        }
        options = options || this._sideOptionsCache.get(widget) || {};
        this._sideOptionsCache.set(widget, options);
        let rank = 'rank' in options ? options.rank : DEFAULT_RANK;
        this._leftHandler.addWidget(widget, rank);
        this._onLayoutModified();
    }
    /**
     * Add a widget to the main content area.
     *
     * #### Notes
     * Widgets must have a unique `id` property, which will be used as the DOM id.
     * All widgets added to the main area should be disposed after removal
     * (disposal before removal will remove the widget automatically).
     *
     * In the options, `ref` defaults to `null`, `mode` defaults to `'tab-after'`,
     * and `activate` defaults to `true`.
     */
    addToMainArea(widget, options = {}) {
        if (!widget.id) {
            console.error('Widgets added to app shell must have unique id property.');
            return;
        }
        let dock = this._dockPanel;
        let ref = null;
        if (options.ref) {
            ref = algorithm_1.find(dock.widgets(), value => value.id === options.ref) || null;
        }
        let mode = options.mode || 'tab-after';
        dock.addWidget(widget, { mode, ref });
        // The dock panel doesn't account for placement information while
        // in single document mode, so upon rehydrating any widgets that were
        // added will not be in the correct place. Cache the placement information
        // here so that we can later rehydrate correctly.
        if (dock.mode === 'single-document') {
            this._addOptionsCache.set(widget, options);
        }
        if (options.activate !== false) {
            dock.activateWidget(widget);
        }
    }
    /**
     * Add a widget to the right content area.
     *
     * #### Notes
     * Widgets must have a unique `id` property, which will be used as the DOM id.
     */
    addToRightArea(widget, options) {
        if (!widget.id) {
            console.error('Widgets added to app shell must have unique id property.');
            return;
        }
        options = options || this._sideOptionsCache.get(widget) || {};
        this._sideOptionsCache.set(widget, options);
        let rank = 'rank' in options ? options.rank : DEFAULT_RANK;
        this._rightHandler.addWidget(widget, rank);
        this._onLayoutModified();
    }
    /**
     * Add a widget to the top content area.
     *
     * #### Notes
     * Widgets must have a unique `id` property, which will be used as the DOM id.
     */
    addToTopArea(widget, options = {}) {
        if (!widget.id) {
            console.error('Widgets added to app shell must have unique id property.');
            return;
        }
        // Temporary: widgets are added to the panel in order of insertion.
        this._topPanel.addWidget(widget);
        this._onLayoutModified();
    }
    /**
     * Add a widget to the bottom content area.
     *
     * #### Notes
     * Widgets must have a unique `id` property, which will be used as the DOM id.
     */
    addToBottomArea(widget, options = {}) {
        if (!widget.id) {
            console.error('Widgets added to app shell must have unique id property.');
            return;
        }
        // Temporary: widgets are added to the panel in order of insertion.
        this._bottomPanel.addWidget(widget);
        this._onLayoutModified();
        if (this._bottomPanel.isHidden) {
            this._bottomPanel.show();
        }
    }
    /**
     * Collapse the left area.
     */
    collapseLeft() {
        this._leftHandler.collapse();
        this._onLayoutModified();
    }
    /**
     * Collapse the right area.
     */
    collapseRight() {
        this._rightHandler.collapse();
        this._onLayoutModified();
    }
    /**
     * Expand the left area.
     *
     * #### Notes
     * This will open the most recently used tab,
     * or the first tab if there is no most recently used.
     */
    expandLeft() {
        this._leftHandler.expand();
        this._onLayoutModified();
    }
    /**
     * Expand the right area.
     *
     * #### Notes
     * This will open the most recently used tab,
     * or the first tab if there is no most recently used.
     */
    expandRight() {
        this._rightHandler.expand();
        this._onLayoutModified();
    }
    /**
     * Close all widgets in the main area.
     */
    closeAll() {
        // Make a copy of all the widget in the dock panel (using `toArray()`)
        // before removing them because removing them while iterating through them
        // modifies the underlying data of the iterator.
        algorithm_1.toArray(this._dockPanel.widgets()).forEach(widget => widget.close());
    }
    /**
     * True if the given area is empty.
     */
    isEmpty(area) {
        switch (area) {
            case 'left':
                return this._leftHandler.stackedPanel.widgets.length === 0;
            case 'main':
                return this._dockPanel.isEmpty;
            case 'top':
                return this._topPanel.widgets.length === 0;
            case 'bottom':
                return this._bottomPanel.widgets.length === 0;
            case 'right':
                return this._rightHandler.stackedPanel.widgets.length === 0;
            default:
                return true;
        }
    }
    /**
     * Restore the layout state for the application shell.
     */
    restoreLayout(layout) {
        const { mainArea, leftArea, rightArea } = layout;
        // Rehydrate the main area.
        if (mainArea) {
            const { currentWidget, dock, mode } = mainArea;
            if (dock) {
                this._dockPanel.restoreLayout(dock);
            }
            if (mode) {
                this.mode = mode;
            }
            if (currentWidget) {
                this.activateById(currentWidget.id);
            }
        }
        // Rehydrate the left area.
        if (leftArea) {
            this._leftHandler.rehydrate(leftArea);
        }
        // Rehydrate the right area.
        if (rightArea) {
            this._rightHandler.rehydrate(rightArea);
        }
        if (!this._isRestored) {
            // Make sure all messages in the queue are finished before notifying
            // any extensions that are waiting for the promise that guarantees the
            // application state has been restored.
            messaging_1.MessageLoop.flush();
            this._restored.resolve(layout);
        }
    }
    /**
     * Save the dehydrated state of the application shell.
     */
    saveLayout() {
        // If the application is in single document mode, use the cached layout if
        // available. Otherwise, default to querying the dock panel for layout.
        return {
            mainArea: {
                currentWidget: this._tracker.currentWidget,
                dock: this.mode === 'single-document'
                    ? this._cachedLayout || this._dockPanel.saveLayout()
                    : this._dockPanel.saveLayout(),
                mode: this._dockPanel.mode
            },
            leftArea: this._leftHandler.dehydrate(),
            rightArea: this._rightHandler.dehydrate()
        };
    }
    /**
     * Returns the widgets for an application area.
     */
    widgets(area) {
        switch (area) {
            case 'main':
                return this._dockPanel.widgets();
            case 'left':
                return algorithm_1.iter(this._leftHandler.sideBar.titles.map(t => t.owner));
            case 'right':
                return algorithm_1.iter(this._rightHandler.sideBar.titles.map(t => t.owner));
            case 'top':
                return this._topPanel.children();
            case 'bottom':
                return this._bottomPanel.children();
            default:
                throw new Error('Invalid area');
        }
    }
    /**
     * Handle `after-attach` messages for the application shell.
     */
    onAfterAttach(msg) {
        document.body.setAttribute(MODE_ATTRIBUTE, this.mode);
    }
    /*
     * Return the tab bar adjacent to the current TabBar or `null`.
     */
    _adjacentBar(direction) {
        const current = this._currentTabBar();
        if (!current) {
            return null;
        }
        const bars = algorithm_1.toArray(this._dockPanel.tabBars());
        const len = bars.length;
        const index = bars.indexOf(current);
        if (direction === 'previous') {
            return index > 0 ? bars[index - 1] : index === 0 ? bars[len - 1] : null;
        }
        // Otherwise, direction is 'next'.
        return index < len - 1
            ? bars[index + 1]
            : index === len - 1
                ? bars[0]
                : null;
    }
    /*
     * Return the TabBar that has the currently active Widget or null.
     */
    _currentTabBar() {
        const current = this._tracker.currentWidget;
        if (!current) {
            return null;
        }
        const title = current.title;
        const bars = this._dockPanel.tabBars();
        return algorithm_1.find(bars, bar => bar.titles.indexOf(title) > -1) || null;
    }
    /**
     * Handle a change to the dock area active widget.
     */
    _onActiveChanged(sender, args) {
        if (args.newValue) {
            args.newValue.title.className += ` ${ACTIVE_CLASS}`;
        }
        if (args.oldValue) {
            args.oldValue.title.className = args.oldValue.title.className.replace(ACTIVE_CLASS, '');
        }
        this._activeChanged.emit(args);
    }
    /**
     * Handle a change to the dock area current widget.
     */
    _onCurrentChanged(sender, args) {
        if (args.newValue) {
            args.newValue.title.className += ` ${CURRENT_CLASS}`;
        }
        if (args.oldValue) {
            args.oldValue.title.className = args.oldValue.title.className.replace(CURRENT_CLASS, '');
        }
        this._currentChanged.emit(args);
        this._onLayoutModified();
    }
    /**
     * Handle a change to the layout.
     */
    _onLayoutModified() {
        // The dock can emit layout modified signals while in transient
        // states (for instance, when switching from single-document to
        // multiple-document mode). In those states, it can be unreliable
        // for the signal consumers to query layout properties.
        // We fix this by debouncing the layout modified signal so that it
        // is only emitted after rearranging is done.
        window.clearTimeout(this._debouncer);
        this._debouncer = window.setTimeout(() => {
            this._layoutModified.emit(undefined);
        }, 0);
    }
}
exports.ApplicationShell = ApplicationShell;
var Private;
(function (Private) {
    /**
     * A less-than comparison function for side bar rank items.
     */
    function itemCmp(first, second) {
        return first.rank - second.rank;
    }
    Private.itemCmp = itemCmp;
    /**
     * Removes widgets that have been disposed from an area config, mutates area.
     */
    function normalizeAreaConfig(parent, area) {
        if (!area) {
            return;
        }
        if (area.type === 'tab-area') {
            area.widgets = area.widgets.filter(widget => !widget.isDisposed && widget.parent === parent);
            return;
        }
        area.children.forEach(child => {
            normalizeAreaConfig(parent, child);
        });
    }
    Private.normalizeAreaConfig = normalizeAreaConfig;
    /**
     * A class which manages a side bar and related stacked panel.
     */
    class SideBarHandler {
        /**
         * Construct a new side bar handler.
         */
        constructor(side) {
            this._items = new Array();
            this._side = side;
            this._sideBar = new widgets_1.TabBar({
                insertBehavior: 'none',
                removeBehavior: 'none',
                allowDeselect: true
            });
            this._stackedPanel = new widgets_1.StackedPanel();
            this._sideBar.hide();
            this._stackedPanel.hide();
            this._lastCurrent = null;
            this._sideBar.currentChanged.connect(this._onCurrentChanged, this);
            this._sideBar.tabActivateRequested.connect(this._onTabActivateRequested, this);
            this._stackedPanel.widgetRemoved.connect(this._onWidgetRemoved, this);
        }
        /**
         * Get the tab bar managed by the handler.
         */
        get sideBar() {
            return this._sideBar;
        }
        /**
         * Get the stacked panel managed by the handler
         */
        get stackedPanel() {
            return this._stackedPanel;
        }
        /**
         * Expand the sidebar.
         *
         * #### Notes
         * This will open the most recently used tab, or the first tab
         * if there is no most recently used.
         */
        expand() {
            const previous = this._lastCurrent || (this._items.length > 0 && this._items[0].widget);
            if (previous) {
                this.activate(previous.id);
            }
        }
        /**
         * Activate a widget residing in the side bar by ID.
         *
         * @param id - The widget's unique ID.
         */
        activate(id) {
            let widget = this._findWidgetByID(id);
            if (widget) {
                this._sideBar.currentTitle = widget.title;
                widget.activate();
            }
        }
        /**
         * Test whether the sidebar has the given widget by id.
         */
        has(id) {
            return this._findWidgetByID(id) !== null;
        }
        /**
         * Collapse the sidebar so no items are expanded.
         */
        collapse() {
            this._sideBar.currentTitle = null;
        }
        /**
         * Add a widget and its title to the stacked panel and side bar.
         *
         * If the widget is already added, it will be moved.
         */
        addWidget(widget, rank) {
            widget.parent = null;
            widget.hide();
            let item = { widget, rank };
            let index = this._findInsertIndex(item);
            algorithm_1.ArrayExt.insert(this._items, index, item);
            this._stackedPanel.insertWidget(index, widget);
            const title = this._sideBar.insertTab(index, widget.title);
            // Store the parent id in the title dataset
            // in order to dispatch click events to the right widget.
            title.dataset = { id: widget.id };
            this._refreshVisibility();
        }
        /**
         * Dehydrate the side bar data.
         */
        dehydrate() {
            let collapsed = this._sideBar.currentTitle === null;
            let widgets = algorithm_1.toArray(this._stackedPanel.widgets);
            let currentWidget = widgets[this._sideBar.currentIndex];
            return { collapsed, currentWidget, widgets };
        }
        /**
         * Rehydrate the side bar.
         */
        rehydrate(data) {
            if (data.currentWidget) {
                this.activate(data.currentWidget.id);
            }
            else if (data.collapsed) {
                this.collapse();
            }
        }
        /**
         * Find the insertion index for a rank item.
         */
        _findInsertIndex(item) {
            return algorithm_1.ArrayExt.upperBound(this._items, item, Private.itemCmp);
        }
        /**
         * Find the index of the item with the given widget, or `-1`.
         */
        _findWidgetIndex(widget) {
            return algorithm_1.ArrayExt.findFirstIndex(this._items, i => i.widget === widget);
        }
        /**
         * Find the widget which owns the given title, or `null`.
         */
        _findWidgetByTitle(title) {
            let item = algorithm_1.find(this._items, value => value.widget.title === title);
            return item ? item.widget : null;
        }
        /**
         * Find the widget with the given id, or `null`.
         */
        _findWidgetByID(id) {
            let item = algorithm_1.find(this._items, value => value.widget.id === id);
            return item ? item.widget : null;
        }
        /**
         * Refresh the visibility of the side bar and stacked panel.
         */
        _refreshVisibility() {
            this._sideBar.setHidden(this._sideBar.titles.length === 0);
            this._stackedPanel.setHidden(this._sideBar.currentTitle === null);
        }
        /**
         * Handle the `currentChanged` signal from the sidebar.
         */
        _onCurrentChanged(sender, args) {
            const oldWidget = args.previousTitle
                ? this._findWidgetByTitle(args.previousTitle)
                : null;
            const newWidget = args.currentTitle
                ? this._findWidgetByTitle(args.currentTitle)
                : null;
            if (oldWidget) {
                oldWidget.hide();
            }
            if (newWidget) {
                newWidget.show();
            }
            this._lastCurrent = newWidget || oldWidget;
            if (newWidget) {
                const id = newWidget.id;
                document.body.setAttribute(`data-${this._side}-sidebar-widget`, id);
            }
            else {
                document.body.removeAttribute(`data-${this._side}-sidebar-widget`);
            }
            this._refreshVisibility();
        }
        /**
         * Handle a `tabActivateRequest` signal from the sidebar.
         */
        _onTabActivateRequested(sender, args) {
            args.title.owner.activate();
        }
        /*
         * Handle the `widgetRemoved` signal from the stacked panel.
         */
        _onWidgetRemoved(sender, widget) {
            if (widget === this._lastCurrent) {
                this._lastCurrent = null;
            }
            algorithm_1.ArrayExt.removeAt(this._items, this._findWidgetIndex(widget));
            this._sideBar.removeTab(widget.title);
            this._refreshVisibility();
        }
    }
    Private.SideBarHandler = SideBarHandler;
})(Private || (Private = {}));


/***/ }),

/***/ "ldVq":
/*!******************************************************************!*\
  !*** ./node_modules/core-js/library/modules/core.is-iterable.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var classof = __webpack_require__(/*! ./_classof */ "QMMT");
var ITERATOR = __webpack_require__(/*! ./_wks */ "UWiX")('iterator');
var Iterators = __webpack_require__(/*! ./_iterators */ "SBuE");
module.exports = __webpack_require__(/*! ./_core */ "WEpk").isIterable = function (it) {
  var O = Object(it);
  return O[ITERATOR] !== undefined
    || '@@iterator' in O
    // eslint-disable-next-line no-prototype-builtins
    || Iterators.hasOwnProperty(classof(O));
};


/***/ }),

/***/ "le5Z":
/*!*******************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/SpikelineIcon.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var SpikelineIcon = function SpikelineIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M32 6.438c0 3.563-2.875 6.5-6.438 6.5s-6.5-2.938-6.5-6.5C19.062 2.875 22 0 25.562 0S32 2.875 32 6.438zM11.563 8.875h5.75v-5.75h-5.75zM0 8.875h5.75v-5.75H0zM23.125 20.5h5.75v-5.813h-5.75zm0 11.5h5.75v-5.75h-5.75z' })
    );
};

exports.default = SpikelineIcon;

/***/ }),

/***/ "leYh":
/*!****************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/PanelMenuWrapper.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _SidebarGroup = __webpack_require__(/*! ./sidebar/SidebarGroup */ "gpep");

var _SidebarGroup2 = _interopRequireDefault(_SidebarGroup);

var _lib = __webpack_require__(/*! ../lib */ "RXjw");

var _sortMenu = __webpack_require__(/*! ../lib/sortMenu */ "4gkd");

var _sortMenu2 = _interopRequireDefault(_sortMenu);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var PanelsWithSidebar = function (_Component) {
  _inherits(PanelsWithSidebar, _Component);

  function PanelsWithSidebar(props) {
    _classCallCheck(this, PanelsWithSidebar);

    var _this = _possibleConstructorReturn(this, (PanelsWithSidebar.__proto__ || Object.getPrototypeOf(PanelsWithSidebar)).call(this, props));

    var opts = _this.computeMenuOptions(props);
    var firstSidebarGroup = opts.filter(function (o) {
      return o.panels;
    })[0];

    _this.state = {
      group: firstSidebarGroup.name,
      panel: firstSidebarGroup.panels[0]
    };

    _this.setPanel = _this.setPanel.bind(_this);
    _this.renderSection = _this.renderSection.bind(_this);
    return _this;
  }

  _createClass(PanelsWithSidebar, [{
    key: 'setPanel',
    value: function setPanel(group, panel) {
      this.setState({ group: group, panel: panel });
    }
  }, {
    key: 'getChildContext',
    value: function getChildContext() {
      return {
        setPanel: this.setPanel
      };
    }
  }, {
    key: 'renderSection',
    value: function renderSection(section, i) {
      if (section.type && (section.type.plotly_editor_traits || {}).sidebar_element) {
        return (0, _react.cloneElement)(section, { key: i });
      }
      return _react2.default.createElement(_SidebarGroup2.default, {
        key: i,
        selectedGroup: this.state.group,
        selectedPanel: this.state.panel,
        group: section.name,
        panels: section.panels,
        onChangeGroup: this.setPanel
      });
    }
  }, {
    key: 'computeMenuOptions',
    value: function computeMenuOptions(props) {
      var children = props.children,
          menuPanelOrder = props.menuPanelOrder;

      var sections = [];
      var groupLookup = {};
      var groupIndex = void 0;
      var childrenArray = (0, _sortMenu2.default)(_react2.default.Children.toArray(children), menuPanelOrder);

      childrenArray.forEach(function (child) {
        if (!child) {
          return;
        }
        var group = child.props.group;
        var name = child.props.name;

        if (group && name) {
          var obj = void 0;
          if (groupLookup.hasOwnProperty(group)) {
            groupIndex = groupLookup[group];
            obj = sections[groupIndex];
          } else {
            groupLookup[group] = sections.length;
            obj = { name: group, panels: [] };
            sections.push(obj);
          }
          obj.panels.push(name);
        }

        if ((child.type.plotly_editor_traits || {}).sidebar_element) {
          sections.push(child);
        }
      });

      return sections;
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var menuOpts = this.computeMenuOptions(this.props);

      return _react2.default.createElement(
        'div',
        { className: (0, _lib.bem)('editor_controls', 'wrapper') },
        _react2.default.createElement(
          'div',
          { className: (0, _lib.bem)('sidebar') },
          menuOpts.map(this.renderSection)
        ),
        _react2.default.Children.map(this.props.children, function (child, i) {
          return child === null || _this2.state.group !== child.props.group || _this2.state.panel !== child.props.name ? null : (0, _react.cloneElement)(child, { key: i });
        })
      );
    }
  }]);

  return PanelsWithSidebar;
}(_react.Component);

PanelsWithSidebar.propTypes = {
  children: _propTypes2.default.node,
  menuPanelOrder: _propTypes2.default.array
};

PanelsWithSidebar.childContextTypes = {
  setPanel: _propTypes2.default.func
};

exports.default = PanelsWithSidebar;
//# sourceMappingURL=PanelMenuWrapper.js.map

/***/ }),

/***/ "lgnt":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/ky.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var suffixes = {
    0: '-чү',
    1: '-чи',
    2: '-чи',
    3: '-чү',
    4: '-чү',
    5: '-чи',
    6: '-чы',
    7: '-чи',
    8: '-чи',
    9: '-чу',
    10: '-чу',
    20: '-чы',
    30: '-чу',
    40: '-чы',
    50: '-чү',
    60: '-чы',
    70: '-чи',
    80: '-чи',
    90: '-чу',
    100: '-чү'
};

var ky = moment.defineLocale('ky', {
    months : 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_'),
    monthsShort : 'янв_фев_март_апр_май_июнь_июль_авг_сен_окт_ноя_дек'.split('_'),
    weekdays : 'Жекшемби_Дүйшөмбү_Шейшемби_Шаршемби_Бейшемби_Жума_Ишемби'.split('_'),
    weekdaysShort : 'Жек_Дүй_Шей_Шар_Бей_Жум_Ише'.split('_'),
    weekdaysMin : 'Жк_Дй_Шй_Шр_Бй_Жм_Иш'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd, D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay : '[Бүгүн саат] LT',
        nextDay : '[Эртең саат] LT',
        nextWeek : 'dddd [саат] LT',
        lastDay : '[Кече саат] LT',
        lastWeek : '[Өткен аптанын] dddd [күнү] [саат] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : '%s ичинде',
        past : '%s мурун',
        s : 'бирнече секунд',
        ss : '%d секунд',
        m : 'бир мүнөт',
        mm : '%d мүнөт',
        h : 'бир саат',
        hh : '%d саат',
        d : 'бир күн',
        dd : '%d күн',
        M : 'бир ай',
        MM : '%d ай',
        y : 'бир жыл',
        yy : '%d жыл'
    },
    dayOfMonthOrdinalParse: /\d{1,2}-(чи|чы|чү|чу)/,
    ordinal : function (number) {
        var a = number % 10,
            b = number >= 100 ? 100 : null;
        return number + (suffixes[number] || suffixes[a] || suffixes[b]);
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return ky;

})));


/***/ }),

/***/ "ljhN":
/*!***********************************!*\
  !*** ./node_modules/lodash/eq.js ***!
  \***********************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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);
}

module.exports = eq;


/***/ }),

/***/ "lm/5":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_baseIsMatch.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Stack = __webpack_require__(/*! ./_Stack */ "fmRc"),
    baseIsEqual = __webpack_require__(/*! ./_baseIsEqual */ "wF/u");

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
    COMPARE_UNORDERED_FLAG = 2;

/**
 * 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;
}

module.exports = baseIsMatch;


/***/ }),

/***/ "lm0R":
/*!****************************************************!*\
  !*** ./node_modules/process-nextick-args/index.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(process) {

if (!process.version ||
    process.version.indexOf('v0.') === 0 ||
    process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  module.exports = { nextTick: nextTick };
} else {
  module.exports = process
}

function nextTick(fn, arg1, arg2, arg3) {
  if (typeof fn !== 'function') {
    throw new TypeError('"callback" argument must be a function');
  }
  var len = arguments.length;
  var args, i;
  switch (len) {
  case 0:
  case 1:
    return process.nextTick(fn);
  case 2:
    return process.nextTick(function afterTickOne() {
      fn.call(null, arg1);
    });
  case 3:
    return process.nextTick(function afterTickTwo() {
      fn.call(null, arg1, arg2);
    });
  case 4:
    return process.nextTick(function afterTickThree() {
      fn.call(null, arg1, arg2, arg3);
    });
  default:
    args = new Array(len - 1);
    i = 0;
    while (i < args.length) {
      args[i++] = arguments[i];
    }
    return process.nextTick(function afterTick() {
      fn.apply(null, args);
    });
  }
}


/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../process/browser.js */ "8oxB")))

/***/ }),

/***/ "lmUn":
/*!*****************************************************************!*\
  !*** ./node_modules/@jupyterlab/tooltip-extension/lib/index.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const services_1 = __webpack_require__(/*! @jupyterlab/services */ "S9up");
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const console_1 = __webpack_require__(/*! @jupyterlab/console */ "DrOJ");
const fileeditor_1 = __webpack_require__(/*! @jupyterlab/fileeditor */ "RHTn");
const notebook_1 = __webpack_require__(/*! @jupyterlab/notebook */ "JOGU");
const rendermime_1 = __webpack_require__(/*! @jupyterlab/rendermime */ "Towz");
const tooltip_1 = __webpack_require__(/*! @jupyterlab/tooltip */ "t2Lz");
/**
 * The command IDs used by the tooltip plugin.
 */
var CommandIDs;
(function (CommandIDs) {
    CommandIDs.dismiss = 'tooltip:dismiss';
    CommandIDs.launchConsole = 'tooltip:launch-console';
    CommandIDs.launchNotebook = 'tooltip:launch-notebook';
    CommandIDs.launchFile = 'tooltip:launch-file';
})(CommandIDs || (CommandIDs = {}));
/**
 * The main tooltip manager plugin.
 */
const manager = {
    id: '@jupyterlab/tooltip-extension:manager',
    autoStart: true,
    provides: tooltip_1.ITooltipManager,
    activate: (app) => {
        let tooltip = null;
        // Add tooltip dismiss command.
        app.commands.addCommand(CommandIDs.dismiss, {
            execute: () => {
                if (tooltip) {
                    tooltip.dispose();
                    tooltip = null;
                }
            }
        });
        return {
            invoke(options) {
                const detail = 0;
                const { anchor, editor, kernel, rendermime } = options;
                if (tooltip) {
                    tooltip.dispose();
                    tooltip = null;
                }
                return Private.fetch({ detail, editor, kernel })
                    .then(bundle => {
                    tooltip = new tooltip_1.Tooltip({ anchor, bundle, editor, rendermime });
                    widgets_1.Widget.attach(tooltip, document.body);
                })
                    .catch(() => {
                    /* Fails silently. */
                });
            }
        };
    }
};
/**
 * The console tooltip plugin.
 */
const consoles = {
    id: '@jupyterlab/tooltip-extension:consoles',
    autoStart: true,
    requires: [tooltip_1.ITooltipManager, console_1.IConsoleTracker],
    activate: (app, manager, consoles) => {
        // Add tooltip launch command.
        app.commands.addCommand(CommandIDs.launchConsole, {
            execute: () => {
                const parent = consoles.currentWidget;
                if (!parent) {
                    return;
                }
                const anchor = parent.console;
                const editor = anchor.promptCell.editor;
                const kernel = anchor.session.kernel;
                const rendermime = anchor.rendermime;
                // If all components necessary for rendering exist, create a tooltip.
                if (!!editor && !!kernel && !!rendermime) {
                    return manager.invoke({ anchor, editor, kernel, rendermime });
                }
            }
        });
    }
};
/**
 * The notebook tooltip plugin.
 */
const notebooks = {
    id: '@jupyterlab/tooltip-extension:notebooks',
    autoStart: true,
    requires: [tooltip_1.ITooltipManager, notebook_1.INotebookTracker],
    activate: (app, manager, notebooks) => {
        // Add tooltip launch command.
        app.commands.addCommand(CommandIDs.launchNotebook, {
            execute: () => {
                const parent = notebooks.currentWidget;
                if (!parent) {
                    return;
                }
                const anchor = parent.content;
                const editor = anchor.activeCell.editor;
                const kernel = parent.session.kernel;
                const rendermime = parent.rendermime;
                // If all components necessary for rendering exist, create a tooltip.
                if (!!editor && !!kernel && !!rendermime) {
                    return manager.invoke({ anchor, editor, kernel, rendermime });
                }
            }
        });
    }
};
/**
 * The file editor tooltip plugin.
 */
const files = {
    id: '@jupyterlab/tooltip-extension:files',
    autoStart: true,
    requires: [tooltip_1.ITooltipManager, fileeditor_1.IEditorTracker, rendermime_1.IRenderMimeRegistry],
    activate: (app, manager, editorTracker, rendermime) => {
        // Keep a list of active ISessions so that we can
        // clean them up when they are no longer needed.
        const activeSessions = {};
        const sessions = app.serviceManager.sessions;
        // When the list of running sessions changes,
        // check to see if there are any kernels with a
        // matching path for the file editors.
        const onRunningChanged = (sender, models) => {
            editorTracker.forEach(file => {
                const model = algorithm_1.find(models, m => file.context.path === m.path);
                if (model) {
                    const oldSession = activeSessions[file.id];
                    // If there is a matching path, but it is the same
                    // session as we previously had, do nothing.
                    if (oldSession && oldSession.id === model.id) {
                        return;
                    }
                    // Otherwise, dispose of the old session and reset to
                    // a new CompletionConnector.
                    if (oldSession) {
                        delete activeSessions[file.id];
                        oldSession.dispose();
                    }
                    const session = sessions.connectTo(model);
                    activeSessions[file.id] = session;
                }
                else {
                    const session = activeSessions[file.id];
                    if (session) {
                        session.dispose();
                        delete activeSessions[file.id];
                    }
                }
            });
        };
        services_1.Session.listRunning().then(models => {
            onRunningChanged(sessions, models);
        });
        sessions.runningChanged.connect(onRunningChanged);
        // Clean up after a widget when it is disposed
        editorTracker.widgetAdded.connect((sender, widget) => {
            widget.disposed.connect(w => {
                const session = activeSessions[w.id];
                if (session) {
                    session.dispose();
                    delete activeSessions[w.id];
                }
            });
        });
        // Add tooltip launch command.
        app.commands.addCommand(CommandIDs.launchFile, {
            execute: () => __awaiter(this, void 0, void 0, function* () {
                const parent = editorTracker.currentWidget;
                const kernel = parent &&
                    activeSessions[parent.id] &&
                    activeSessions[parent.id].kernel;
                if (!kernel) {
                    return;
                }
                const anchor = parent.content;
                const editor = anchor.editor;
                // If all components necessary for rendering exist, create a tooltip.
                if (!!editor && !!kernel && !!rendermime) {
                    return manager.invoke({ anchor, editor, kernel, rendermime });
                }
            })
        });
    }
};
/**
 * Export the plugins as default.
 */
const plugins = [manager, consoles, notebooks, files];
exports.default = plugins;
/**
 * A namespace for private data.
 */
var Private;
(function (Private) {
    /**
     * A counter for outstanding requests.
     */
    let pending = 0;
    /**
     * Fetch a tooltip's content from the API server.
     */
    function fetch(options) {
        let { detail, editor, kernel } = options;
        let code = editor.model.value.text;
        let position = editor.getCursorPosition();
        let offset = coreutils_1.Text.jsIndexToCharIndex(editor.getOffsetAt(position), code);
        // Clear hints if the new text value is empty or kernel is unavailable.
        if (!code || !kernel) {
            return Promise.reject(void 0);
        }
        let contents = {
            code,
            cursor_pos: offset,
            detail_level: detail || 0
        };
        let current = ++pending;
        return kernel.requestInspect(contents).then(msg => {
            let value = msg.content;
            // If a newer request is pending, bail.
            if (current !== pending) {
                return Promise.reject(void 0);
            }
            // If request fails or returns negative results, bail.
            if (value.status !== 'ok' || !value.found) {
                return Promise.reject(void 0);
            }
            return Promise.resolve(value.data);
        });
    }
    Private.fetch = fetch;
})(Private || (Private = {}));


/***/ }),

/***/ "lolG":
/*!**************************************************************!*\
  !*** ./node_modules/@jupyterlab/vdom-extension/lib/index.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const React = __importStar(__webpack_require__(/*! react */ "q1tI"));
const ReactDOM = __importStar(__webpack_require__(/*! react-dom */ "i8i4"));
const transform_vdom_1 = __importDefault(__webpack_require__(/*! @nteract/transform-vdom */ "vR7t"));
__webpack_require__(/*! ../style/index.css */ "3Egu");
/**
 * The CSS class to add to the VDOM Widget.
 */
const CSS_CLASS = 'jp-RenderedVDOM';
/**
 * The CSS class for a VDOM icon.
 */
const CSS_ICON_CLASS = 'jp-MaterialIcon jp-VDOMIcon';
/**
 * The MIME type for VDOM.
 */
exports.MIME_TYPE = 'application/vdom.v1+json';
/**
 * A renderer for declarative virtual DOM content.
 */
class RenderedVDOM extends widgets_1.Widget {
    /**
     * Create a new widget for rendering DOM.
     */
    constructor(options) {
        super();
        this.addClass(CSS_CLASS);
        this._mimeType = options.mimeType;
    }
    /**
     * Render VDOM into this widget's node.
     */
    renderModel(model) {
        const data = model.data[this._mimeType];
        // const metadata = model.metadata[this._mimeType] as any || {};
        return new Promise((resolve, reject) => {
            ReactDOM.render(React.createElement(transform_vdom_1.default, { data: data }), this.node, () => {
                resolve(undefined);
            });
        });
    }
}
exports.RenderedVDOM = RenderedVDOM;
/**
 * A mime renderer factory for VDOM data.
 */
exports.rendererFactory = {
    safe: true,
    mimeTypes: [exports.MIME_TYPE],
    createRenderer: options => new RenderedVDOM(options)
};
const extensions = [
    {
        id: '@jupyterlab/vdom-extension:factory',
        rendererFactory: exports.rendererFactory,
        rank: 0,
        dataType: 'json',
        fileTypes: [
            {
                name: 'vdom',
                mimeTypes: [exports.MIME_TYPE],
                extensions: ['.vdom', '.vdom.json'],
                iconClass: CSS_ICON_CLASS
            }
        ],
        documentWidgetFactoryOptions: {
            name: 'VDOM',
            primaryFileType: 'vdom',
            fileTypes: ['vdom', 'json'],
            defaultFor: ['vdom']
        }
    }
];
exports.default = extensions;


/***/ }),

/***/ "lreK":
/*!***************************************************!*\
  !*** ./node_modules/reactcss/lib/mergeClasses.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.mergeClasses = undefined;

var _forOwn2 = __webpack_require__(/*! lodash/forOwn */ "Ag8Z");

var _forOwn3 = _interopRequireDefault(_forOwn2);

var _cloneDeep2 = __webpack_require__(/*! lodash/cloneDeep */ "BkRI");

var _cloneDeep3 = _interopRequireDefault(_cloneDeep2);

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var mergeClasses = exports.mergeClasses = function mergeClasses(classes) {
  var activeNames = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];

  var styles = classes.default && (0, _cloneDeep3.default)(classes.default) || {};
  activeNames.map(function (name) {
    var toMerge = classes[name];
    if (toMerge) {
      (0, _forOwn3.default)(toMerge, function (value, key) {
        if (!styles[key]) {
          styles[key] = {};
        }

        styles[key] = _extends({}, styles[key], toMerge[key]);
      });
    }

    return name;
  });
  return styles;
};

exports.default = mergeClasses;

/***/ }),

/***/ "lw7W":
/*!*********************************************!*\
  !*** ./node_modules/base16/lib/harmonic.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'harmonic16',
  author: 'jannik siebert (https://github.com/janniks)',
  base00: '#0b1c2c',
  base01: '#223b54',
  base02: '#405c79',
  base03: '#627e99',
  base04: '#aabcce',
  base05: '#cbd6e2',
  base06: '#e5ebf1',
  base07: '#f7f9fb',
  base08: '#bf8b56',
  base09: '#bfbf56',
  base0A: '#8bbf56',
  base0B: '#56bf8b',
  base0C: '#568bbf',
  base0D: '#8b56bf',
  base0E: '#bf568b',
  base0F: '#bf5656'
};
module.exports = exports['default'];

/***/ }),

/***/ "lx3m":
/*!*************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotScatterAxesIcon.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotScatterAxesIcon = function PlotScatterAxesIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M29.375 28.375H5.062c-.75 0-1.438-.625-1.438-1.375V2.625c0-.563-.438-1-1-1s-1 .438-1 1V27c0 1.875 1.5 3.375 3.438 3.375h24.375c.563 0 1-.438 1-1s-.5-1-1.063-1zm-18.437-6.312c0 1-.813 1.75-1.75 1.75s-1.75-.75-1.75-1.75c0-.938.813-1.688 1.75-1.688s1.75.75 1.75 1.688zm6.312-9.25c0 1-.75 1.75-1.75 1.75-.938 0-1.688-.75-1.688-1.75 0-.938.75-1.688 1.688-1.688 1 0 1.75.75 1.75 1.688zm2.188 6.812c0 1-.75 1.75-1.688 1.75-1 0-1.75-.75-1.75-1.75 0-.938.75-1.688 1.75-1.688.938 0 1.688.75 1.688 1.688zm4.875-5.562c0 .938-.75 1.688-1.75 1.688-.938 0-1.688-.75-1.688-1.688s.75-1.75 1.688-1.75c1 0 1.75.813 1.75 1.75zM27 7.5c0 .938-.813 1.688-1.75 1.688S23.5 8.438 23.5 7.5s.813-1.75 1.75-1.75S27 6.563 27 7.5z' })
    );
};

exports.default = PlotScatterAxesIcon;

/***/ }),

/***/ "ly1K":
/*!*********************************************************!*\
  !*** ./node_modules/@jupyterlab/terminal/lib/widget.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const xterm_1 = __webpack_require__(/*! xterm */ "pkdz");
const fit_1 = __webpack_require__(/*! xterm/lib/addons/fit */ "xVS5");
/**
 * The class name added to a terminal widget.
 */
const TERMINAL_CLASS = 'jp-Terminal';
/**
 * The class name added to a terminal body.
 */
const TERMINAL_BODY_CLASS = 'jp-Terminal-body';
/**
 * A widget which manages a terminal session.
 */
class Terminal extends widgets_1.Widget {
    /**
     * Construct a new terminal widget.
     *
     * @param options - The terminal configuration options.
     */
    constructor(options = {}) {
        super();
        this._needsResize = true;
        this._theme = 'dark';
        this._session = null;
        this._termOpened = false;
        this._offsetWidth = -1;
        this._offsetHeight = -1;
        this.addClass(TERMINAL_CLASS);
        // Create the xterm.
        this._term = new xterm_1.Terminal(Private.getConfig(options));
        this._initializeTerm();
        // Initialize settings.
        let defaults = Terminal.defaultOptions;
        this._initialCommand = options.initialCommand || defaults.initialCommand;
        this.theme = options.theme || defaults.theme;
        this.id = `jp-Terminal-${Private.id++}`;
        this.title.label = 'Terminal';
    }
    /**
     * The terminal session associated with the widget.
     */
    get session() {
        return this._session;
    }
    set session(value) {
        if (this._session && !this._session.isDisposed) {
            this._session.messageReceived.disconnect(this._onMessage, this);
        }
        this._session = value || null;
        if (!value) {
            return;
        }
        value.ready.then(() => {
            if (this.isDisposed || value !== this._session) {
                return;
            }
            value.messageReceived.connect(this._onMessage, this);
            this.title.label = `Terminal ${value.name}`;
            this._setSessionSize();
            if (this._initialCommand) {
                this._session.send({
                    type: 'stdin',
                    content: [this._initialCommand + '\r']
                });
            }
        });
    }
    /**
     * Get the font size of the terminal in pixels.
     */
    get fontSize() {
        return this._term.getOption('fontSize');
    }
    /**
     * Set the font size of the terminal in pixels.
     */
    set fontSize(size) {
        if (this.fontSize === size) {
            return;
        }
        this._term.setOption('fontSize', size);
        this._needsResize = true;
        this.update();
    }
    /**
     * Get the current theme, either light or dark.
     */
    get theme() {
        return this._theme;
    }
    /**
     * Set the current theme, either light or dark.
     */
    set theme(value) {
        this._theme = value;
        if (value === 'light') {
            this.addClass('jp-mod-light');
            this._term.setOption('theme', Private.lightTheme);
        }
        else {
            this.removeClass('jp-mod-light');
            this._term.setOption('theme', Private.darkTheme);
        }
        this.update();
    }
    /**
     * Dispose of the resources held by the terminal widget.
     */
    dispose() {
        this._session = null;
        super.dispose();
    }
    /**
     * Refresh the terminal session.
     */
    refresh() {
        if (!this._session) {
            return Promise.reject(void 0);
        }
        return this._session.reconnect().then(() => {
            this._term.clear();
        });
    }
    /**
     * Process a message sent to the widget.
     *
     * @param msg - The message sent to the widget.
     *
     * #### Notes
     * Subclasses may reimplement this method as needed.
     */
    processMessage(msg) {
        super.processMessage(msg);
        switch (msg.type) {
            case 'fit-request':
                this.onFitRequest(msg);
                break;
            default:
                break;
        }
    }
    /**
     * Set the size of the terminal when attached if dirty.
     */
    onAfterAttach(msg) {
        this.update();
    }
    /**
     * Set the size of the terminal when shown if dirty.
     */
    onAfterShow(msg) {
        this.update();
    }
    /**
     * On resize, use the computed row and column sizes to resize the terminal.
     */
    onResize(msg) {
        this._offsetWidth = msg.width;
        this._offsetHeight = msg.height;
        this._needsResize = true;
        this.update();
    }
    /**
     * A message handler invoked on an `'update-request'` message.
     */
    onUpdateRequest(msg) {
        if (!this.isVisible || !this.isAttached) {
            return;
        }
        // Open the terminal if necessary.
        if (!this._termOpened) {
            this._term.open(this.node);
            this._term.element.classList.add(TERMINAL_BODY_CLASS);
            this._termOpened = true;
        }
        if (this._needsResize) {
            this._resizeTerminal();
        }
    }
    /**
     * A message handler invoked on an `'fit-request'` message.
     */
    onFitRequest(msg) {
        let resize = widgets_1.Widget.ResizeMessage.UnknownSize;
        messaging_1.MessageLoop.sendMessage(this, resize);
    }
    /**
     * Handle `'activate-request'` messages.
     */
    onActivateRequest(msg) {
        this._term.focus();
    }
    /**
     * Initialize the terminal object.
     */
    _initializeTerm() {
        this._term.on('data', (data) => {
            if (this._session) {
                this._session.send({
                    type: 'stdin',
                    content: [data]
                });
            }
        });
        this._term.on('title', (title) => {
            this.title.label = title;
        });
    }
    /**
     * Handle a message from the terminal session.
     */
    _onMessage(sender, msg) {
        switch (msg.type) {
            case 'stdout':
                if (msg.content) {
                    this._term.write(msg.content[0]);
                }
                break;
            case 'disconnect':
                this._term.write('\r\n\r\n[Finished... Term Session]\r\n');
                break;
            default:
                break;
        }
    }
    /**
     * Resize the terminal based on computed geometry.
     */
    _resizeTerminal() {
        fit_1.fit(this._term);
        if (this._offsetWidth === -1) {
            this._offsetWidth = this.node.offsetWidth;
        }
        if (this._offsetHeight === -1) {
            this._offsetHeight = this.node.offsetHeight;
        }
        this._setSessionSize();
        this._needsResize = false;
    }
    /**
     * Set the size of the terminal in the session.
     */
    _setSessionSize() {
        let content = [
            this._term.rows,
            this._term.cols,
            this._offsetHeight,
            this._offsetWidth
        ];
        if (this._session) {
            this._session.send({ type: 'set_size', content });
        }
    }
}
exports.Terminal = Terminal;
/**
 * The namespace for `Terminal` class statics.
 */
(function (Terminal) {
    /**
     * The default options used for creating terminals.
     */
    Terminal.defaultOptions = {
        theme: 'dark',
        fontSize: 13,
        cursorBlink: true,
        initialCommand: ''
    };
})(Terminal = exports.Terminal || (exports.Terminal = {}));
/**
 * A namespace for private data.
 */
var Private;
(function (Private) {
    /**
     * Get term.js options from ITerminalOptions.
     */
    function getConfig(options) {
        let config = {};
        if (options.cursorBlink !== void 0) {
            config.cursorBlink = options.cursorBlink;
        }
        else {
            config.cursorBlink = Terminal.defaultOptions.cursorBlink;
        }
        if (options.fontSize !== void 0) {
            config.fontSize = options.fontSize;
        }
        else {
            config.fontSize = Terminal.defaultOptions.fontSize;
        }
        return config;
    }
    Private.getConfig = getConfig;
    /**
     * An incrementing counter for ids.
     */
    Private.id = 0;
    /**
     * The light terminal theme.
     */
    Private.lightTheme = {
        foreground: '#000',
        background: '#fff',
        cursor: '#616161',
        cursorAccent: '#F5F5F5',
        selection: 'rgba(97, 97, 97, 0.3)' // md-grey-700
    };
    /**
     * The dark terminal theme.
     */
    Private.darkTheme = {
        foreground: '#fff',
        background: '#000',
        cursor: '#fff',
        cursorAccent: '#000',
        selection: 'rgba(255, 255, 255, 0.3)'
    };
})(Private || (Private = {}));


/***/ }),

/***/ "lyJQ":
/*!***************************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/make_trace_groups.js ***!
  \***************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




/**
 * General helper to manage trace groups based on calcdata
 *
 * @param {d3.selection} traceLayer: a selection containing a single group
 *     to draw these traces into
 * @param {array} cdModule: array of calcdata items for this
 *     module and subplot combination. Assumes the calcdata item for each
 *     trace is an array with the fullData trace attached to the first item.
 * @param {string} cls: the class attribute to give each trace group
 *     so you can give multiple classes separated by spaces
 */
module.exports = function makeTraceGroups(traceLayer, cdModule, cls) {
    var traces = traceLayer.selectAll('g.' + cls.replace(/\s/g, '.'))
        .data(cdModule, function(cd) { return cd[0].trace.uid; });

    traces.exit().remove();

    traces.enter().append('g')
        .attr('class', cls);

    traces.order();

    return traces;
};


/***/ }),

/***/ "lyxo":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/ro.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


function relativeTimeWithPlural(number, withoutSuffix, key) {
    var format = {
            'ss': 'secunde',
            'mm': 'minute',
            'hh': 'ore',
            'dd': 'zile',
            'MM': 'luni',
            'yy': 'ani'
        },
        separator = ' ';
    if (number % 100 >= 20 || (number >= 100 && number % 100 === 0)) {
        separator = ' de ';
    }
    return number + separator + format[key];
}

var ro = moment.defineLocale('ro', {
    months : 'ianuarie_februarie_martie_aprilie_mai_iunie_iulie_august_septembrie_octombrie_noiembrie_decembrie'.split('_'),
    monthsShort : 'ian._febr._mart._apr._mai_iun._iul._aug._sept._oct._nov._dec.'.split('_'),
    monthsParseExact: true,
    weekdays : 'duminică_luni_marți_miercuri_joi_vineri_sâmbătă'.split('_'),
    weekdaysShort : 'Dum_Lun_Mar_Mie_Joi_Vin_Sâm'.split('_'),
    weekdaysMin : 'Du_Lu_Ma_Mi_Jo_Vi_Sâ'.split('_'),
    longDateFormat : {
        LT : 'H:mm',
        LTS : 'H:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY H:mm',
        LLLL : 'dddd, D MMMM YYYY H:mm'
    },
    calendar : {
        sameDay: '[azi la] LT',
        nextDay: '[mâine la] LT',
        nextWeek: 'dddd [la] LT',
        lastDay: '[ieri la] LT',
        lastWeek: '[fosta] dddd [la] LT',
        sameElse: 'L'
    },
    relativeTime : {
        future : 'peste %s',
        past : '%s în urmă',
        s : 'câteva secunde',
        ss : relativeTimeWithPlural,
        m : 'un minut',
        mm : relativeTimeWithPlural,
        h : 'o oră',
        hh : relativeTimeWithPlural,
        d : 'o zi',
        dd : relativeTimeWithPlural,
        M : 'o lună',
        MM : relativeTimeWithPlural,
        y : 'un an',
        yy : relativeTimeWithPlural
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return ro;

})));


/***/ }),

/***/ "m+Ef":
/*!*****************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/codemirror/theme/zenburn.css ***!
  \*****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/**\n * \"\n *  Using Zenburn color palette from the Emacs Zenburn Theme\n *  https://github.com/bbatsov/zenburn-emacs/blob/master/zenburn-theme.el\n *\n *  Also using parts of https://github.com/xavi/coderay-lighttable-theme\n * \"\n * From: https://github.com/wisenomad/zenburn-lighttable-theme/blob/master/zenburn.css\n */\n\n.cm-s-zenburn .CodeMirror-gutters { background: #3f3f3f !important; }\n.cm-s-zenburn .CodeMirror-foldgutter-open, .CodeMirror-foldgutter-folded { color: #999; }\n.cm-s-zenburn .CodeMirror-cursor { border-left: 1px solid white; }\n.cm-s-zenburn { background-color: #3f3f3f; color: #dcdccc; }\n.cm-s-zenburn span.cm-builtin { color: #dcdccc; font-weight: bold; }\n.cm-s-zenburn span.cm-comment { color: #7f9f7f; }\n.cm-s-zenburn span.cm-keyword { color: #f0dfaf; font-weight: bold; }\n.cm-s-zenburn span.cm-atom { color: #bfebbf; }\n.cm-s-zenburn span.cm-def { color: #dcdccc; }\n.cm-s-zenburn span.cm-variable { color: #dfaf8f; }\n.cm-s-zenburn span.cm-variable-2 { color: #dcdccc; }\n.cm-s-zenburn span.cm-string { color: #cc9393; }\n.cm-s-zenburn span.cm-string-2 { color: #cc9393; }\n.cm-s-zenburn span.cm-number { color: #dcdccc; }\n.cm-s-zenburn span.cm-tag { color: #93e0e3; }\n.cm-s-zenburn span.cm-property { color: #dfaf8f; }\n.cm-s-zenburn span.cm-attribute { color: #dfaf8f; }\n.cm-s-zenburn span.cm-qualifier { color: #7cb8bb; }\n.cm-s-zenburn span.cm-meta { color: #f0dfaf; }\n.cm-s-zenburn span.cm-header { color: #f0efd0; }\n.cm-s-zenburn span.cm-operator { color: #f0efd0; }\n.cm-s-zenburn span.CodeMirror-matchingbracket { box-sizing: border-box; background: transparent; border-bottom: 1px solid; }\n.cm-s-zenburn span.CodeMirror-nonmatchingbracket { border-bottom: 1px solid; background: none; }\n.cm-s-zenburn .CodeMirror-activeline { background: #000000; }\n.cm-s-zenburn .CodeMirror-activeline-background { background: #000000; }\n.cm-s-zenburn div.CodeMirror-selected { background: #545454; }\n.cm-s-zenburn .CodeMirror-focused div.CodeMirror-selected { background: #4f4f4f; }\n", ""]);

// exports


/***/ }),

/***/ "m3yW":
/*!************************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/stackedpanel.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
var panel_1 = __webpack_require__(/*! ./panel */ "RlJB");
var stackedlayout_1 = __webpack_require__(/*! ./stackedlayout */ "eRtU");
/**
 * A panel where visible widgets are stacked atop one another.
 *
 * #### Notes
 * This class provides a convenience wrapper around a [[StackedLayout]].
 */
var StackedPanel = (function (_super) {
    __extends(StackedPanel, _super);
    /**
     * Construct a new stacked panel.
     *
     * @param options - The options for initializing the panel.
     */
    function StackedPanel(options) {
        if (options === void 0) { options = {}; }
        var _this = _super.call(this, { layout: Private.createLayout(options) }) || this;
        _this._widgetRemoved = new signaling_1.Signal(_this);
        _this.addClass('p-StackedPanel');
        return _this;
    }
    Object.defineProperty(StackedPanel.prototype, "widgetRemoved", {
        /**
         * A signal emitted when a widget is removed from a stacked panel.
         */
        get: function () {
            return this._widgetRemoved;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * A message handler invoked on a `'child-added'` message.
     */
    StackedPanel.prototype.onChildAdded = function (msg) {
        msg.child.addClass('p-StackedPanel-child');
    };
    /**
     * A message handler invoked on a `'child-removed'` message.
     */
    StackedPanel.prototype.onChildRemoved = function (msg) {
        msg.child.removeClass('p-StackedPanel-child');
        this._widgetRemoved.emit(msg.child);
    };
    return StackedPanel;
}(panel_1.Panel));
exports.StackedPanel = StackedPanel;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * Create a stacked layout for the given panel options.
     */
    function createLayout(options) {
        return options.layout || new stackedlayout_1.StackedLayout();
    }
    Private.createLayout = createLayout;
})(Private || (Private = {}));


/***/ }),

/***/ "m5lF":
/*!*************************************************************!*\
  !*** ./node_modules/@jupyterlab/filebrowser/lib/listing.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const docmanager_1 = __webpack_require__(/*! @jupyterlab/docmanager */ "kL29");
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const coreutils_2 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const dragdrop_1 = __webpack_require__(/*! @phosphor/dragdrop */ "v7cI");
const domutils_1 = __webpack_require__(/*! @phosphor/domutils */ "XWTc");
const messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
/**
 * The class name added to DirListing widget.
 */
const DIR_LISTING_CLASS = 'jp-DirListing';
/**
 * The class name added to a dir listing header node.
 */
const HEADER_CLASS = 'jp-DirListing-header';
/**
 * The class name added to a dir listing list header cell.
 */
const HEADER_ITEM_CLASS = 'jp-DirListing-headerItem';
/**
 * The class name added to a header cell text node.
 */
const HEADER_ITEM_TEXT_CLASS = 'jp-DirListing-headerItemText';
/**
 * The class name added to a header cell icon node.
 */
const HEADER_ITEM_ICON_CLASS = 'jp-DirListing-headerItemIcon';
/**
 * The class name added to the dir listing content node.
 */
const CONTENT_CLASS = 'jp-DirListing-content';
/**
 * The class name added to dir listing content item.
 */
const ITEM_CLASS = 'jp-DirListing-item';
/**
 * The class name added to the listing item text cell.
 */
const ITEM_TEXT_CLASS = 'jp-DirListing-itemText';
/**
 * The class name added to the listing item icon cell.
 */
const ITEM_ICON_CLASS = 'jp-DirListing-itemIcon';
/**
 * The class name added to the listing item modified cell.
 */
const ITEM_MODIFIED_CLASS = 'jp-DirListing-itemModified';
/**
 * The class name added to the dir listing editor node.
 */
const EDITOR_CLASS = 'jp-DirListing-editor';
/**
 * The class name added to the name column header cell.
 */
const NAME_ID_CLASS = 'jp-id-name';
/**
 * The class name added to the modified column header cell.
 */
const MODIFIED_ID_CLASS = 'jp-id-modified';
/**
 * The mime type for a con tents drag object.
 */
const CONTENTS_MIME = 'application/x-jupyter-icontents';
/**
 * The class name added to drop targets.
 */
const DROP_TARGET_CLASS = 'jp-mod-dropTarget';
/**
 * The class name added to selected rows.
 */
const SELECTED_CLASS = 'jp-mod-selected';
/**
 * The class name added to drag state icons to add space between the icon and the file name
 */
const DRAG_ICON_CLASS = 'jp-DragIcon';
/**
 * The class name added to the widget when there are items on the clipboard.
 */
const CLIPBOARD_CLASS = 'jp-mod-clipboard';
/**
 * The class name added to cut rows.
 */
const CUT_CLASS = 'jp-mod-cut';
/**
 * The class name added when there are more than one selected rows.
 */
const MULTI_SELECTED_CLASS = 'jp-mod-multiSelected';
/**
 * The class name added to indicate running notebook.
 */
const RUNNING_CLASS = 'jp-mod-running';
/**
 * The class name added for a decending sort.
 */
const DESCENDING_CLASS = 'jp-mod-descending';
/**
 * The maximum duration between two key presses when selecting files by prefix.
 */
const PREFIX_APPEND_DURATION = 1000;
/**
 * The threshold in pixels to start a drag event.
 */
const DRAG_THRESHOLD = 5;
/**
 * A boolean indicating whether the platform is Mac.
 */
const IS_MAC = !!navigator.platform.match(/Mac/i);
/**
 * The factory MIME type supported by phosphor dock panels.
 */
const FACTORY_MIME = 'application/vnd.phosphor.widget-factory';
/**
 * A widget which hosts a file list area.
 */
class DirListing extends widgets_1.Widget {
    /**
     * Construct a new file browser directory listing widget.
     *
     * @param model - The file browser view model.
     */
    constructor(options) {
        super({
            node: (options.renderer || DirListing.defaultRenderer).createNode()
        });
        this._items = [];
        this._sortedItems = [];
        this._sortState = {
            direction: 'ascending',
            key: 'name'
        };
        this._drag = null;
        this._dragData = null;
        this._selectTimer = -1;
        this._isCut = false;
        this._prevPath = '';
        this._clipboard = [];
        this._softSelection = '';
        this._selection = Object.create(null);
        this._searchPrefix = '';
        this._searchPrefixTimer = -1;
        this._inRename = false;
        this._isDirty = false;
        this.addClass(DIR_LISTING_CLASS);
        this._model = options.model;
        this._model.fileChanged.connect(this._onFileChanged, this);
        this._model.refreshed.connect(this._onModelRefreshed, this);
        this._model.pathChanged.connect(this._onPathChanged, this);
        this._editNode = document.createElement('input');
        this._editNode.className = EDITOR_CLASS;
        this._manager = this._model.manager;
        this._renderer = options.renderer || DirListing.defaultRenderer;
        const headerNode = apputils_1.DOMUtils.findElement(this.node, HEADER_CLASS);
        this._renderer.populateHeaderNode(headerNode);
        this._manager.activateRequested.connect(this._onActivateRequested, this);
    }
    /**
     * Dispose of the resources held by the directory listing.
     */
    dispose() {
        this._items.length = 0;
        this._sortedItems.length = 0;
        this._clipboard.length = 0;
        super.dispose();
    }
    /**
     * Get the model used by the listing.
     */
    get model() {
        return this._model;
    }
    /**
     * Get the dir listing header node.
     *
     * #### Notes
     * This is the node which holds the header cells.
     *
     * Modifying this node directly can lead to undefined behavior.
     */
    get headerNode() {
        return apputils_1.DOMUtils.findElement(this.node, HEADER_CLASS);
    }
    /**
     * Get the dir listing content node.
     *
     * #### Notes
     * This is the node which holds the item nodes.
     *
     * Modifying this node directly can lead to undefined behavior.
     */
    get contentNode() {
        return apputils_1.DOMUtils.findElement(this.node, CONTENT_CLASS);
    }
    /**
     * The renderer instance used by the directory listing.
     */
    get renderer() {
        return this._renderer;
    }
    /**
     * The current sort state.
     */
    get sortState() {
        return this._sortState;
    }
    /**
     * Create an iterator over the listing's selected items.
     *
     * @returns A new iterator over the listing's selected items.
     */
    selectedItems() {
        let items = this._sortedItems;
        return algorithm_1.filter(items, item => this._selection[item.name]);
    }
    /**
     * Create an iterator over the listing's sorted items.
     *
     * @returns A new iterator over the listing's sorted items.
     */
    sortedItems() {
        return new algorithm_1.ArrayIterator(this._sortedItems);
    }
    /**
     * Sort the items using a sort condition.
     */
    sort(state) {
        this._sortedItems = Private.sort(this.model.items(), state);
        this._sortState = state;
        this.update();
    }
    /**
     * Rename the first currently selected item.
     *
     * @returns A promise that resolves with the new name of the item.
     */
    rename() {
        return this._doRename();
    }
    /**
     * Cut the selected items.
     */
    cut() {
        this._isCut = true;
        this._copy();
        this.update();
    }
    /**
     * Copy the selected items.
     */
    copy() {
        this._copy();
    }
    /**
     * Paste the items from the clipboard.
     *
     * @returns A promise that resolves when the operation is complete.
     */
    paste() {
        if (!this._clipboard.length) {
            this._isCut = false;
            return Promise.resolve(undefined);
        }
        const basePath = this._model.path;
        let promises = [];
        algorithm_1.each(this._clipboard, path => {
            if (this._isCut) {
                const parts = path.split('/');
                const name = parts[parts.length - 1];
                const newPath = coreutils_1.PathExt.join(basePath, name);
                promises.push(this._model.manager.rename(path, newPath));
            }
            else {
                promises.push(this._model.manager.copy(path, basePath));
            }
        });
        // Remove any cut modifiers.
        algorithm_1.each(this._items, item => {
            item.classList.remove(CUT_CLASS);
        });
        this._clipboard.length = 0;
        this._isCut = false;
        this.removeClass(CLIPBOARD_CLASS);
        return Promise.all(promises)
            .then(() => {
            return undefined;
        })
            .catch(error => {
            apputils_1.showErrorMessage('Paste Error', error);
        });
    }
    /**
     * Delete the currently selected item(s).
     *
     * @returns A promise that resolves when the operation is complete.
     */
    delete() {
        let names = [];
        algorithm_1.each(this._sortedItems, item => {
            if (this._selection[item.name]) {
                names.push(item.name);
            }
        });
        let message = `Are you sure you want to permanently delete the ${names.length} files/folders selected?`;
        if (names.length === 1) {
            message = `Are you sure you want to permanently delete: ${names[0]}?`;
        }
        if (names.length) {
            return apputils_1.showDialog({
                title: 'Delete',
                body: message,
                buttons: [apputils_1.Dialog.cancelButton(), apputils_1.Dialog.warnButton({ label: 'DELETE' })]
            }).then(result => {
                if (!this.isDisposed && result.button.accept) {
                    return this._delete(names);
                }
            });
        }
        return Promise.resolve(void 0);
    }
    /**
     * Duplicate the currently selected item(s).
     *
     * @returns A promise that resolves when the operation is complete.
     */
    duplicate() {
        const basePath = this._model.path;
        let promises = [];
        algorithm_1.each(this.selectedItems(), item => {
            if (item.type !== 'directory') {
                let oldPath = coreutils_1.PathExt.join(basePath, item.name);
                promises.push(this._model.manager.copy(oldPath, basePath));
            }
        });
        return Promise.all(promises)
            .then(() => {
            return undefined;
        })
            .catch(error => {
            apputils_1.showErrorMessage('Duplicate file', error);
        });
    }
    /**
     * Download the currently selected item(s).
     */
    download() {
        algorithm_1.each(this.selectedItems(), item => {
            if (item.type !== 'directory') {
                this._model.download(item.path);
            }
        });
    }
    /**
     * Shut down kernels on the applicable currently selected items.
     *
     * @returns A promise that resolves when the operation is complete.
     */
    shutdownKernels() {
        const model = this._model;
        const items = this._sortedItems;
        const paths = items.map(item => item.path);
        const promises = algorithm_1.toArray(this._model.sessions())
            .filter(session => {
            let index = algorithm_1.ArrayExt.firstIndexOf(paths, session.path);
            return this._selection[items[index].name];
        })
            .map(session => model.manager.services.sessions.shutdown(session.id));
        return Promise.all(promises)
            .then(() => {
            return undefined;
        })
            .catch(error => {
            apputils_1.showErrorMessage('Shutdown kernel', error);
        });
    }
    /**
     * Select next item.
     *
     * @param keepExisting - Whether to keep the current selection and add to it.
     */
    selectNext(keepExisting = false) {
        let index = -1;
        let selected = Object.keys(this._selection);
        let items = this._sortedItems;
        if (selected.length === 1 || keepExisting) {
            // Select the next item.
            let name = selected[selected.length - 1];
            index = algorithm_1.ArrayExt.findFirstIndex(items, value => value.name === name);
            index += 1;
            if (index === this._items.length) {
                index = 0;
            }
        }
        else if (selected.length === 0) {
            // Select the first item.
            index = 0;
        }
        else {
            // Select the last selected item.
            let name = selected[selected.length - 1];
            index = algorithm_1.ArrayExt.findFirstIndex(items, value => value.name === name);
        }
        if (index !== -1) {
            this._selectItem(index, keepExisting);
            domutils_1.ElementExt.scrollIntoViewIfNeeded(this.contentNode, this._items[index]);
        }
    }
    /**
     * Select previous item.
     *
     * @param keepExisting - Whether to keep the current selection and add to it.
     */
    selectPrevious(keepExisting = false) {
        let index = -1;
        let selected = Object.keys(this._selection);
        let items = this._sortedItems;
        if (selected.length === 1 || keepExisting) {
            // Select the previous item.
            let name = selected[0];
            index = algorithm_1.ArrayExt.findFirstIndex(items, value => value.name === name);
            index -= 1;
            if (index === -1) {
                index = this._items.length - 1;
            }
        }
        else if (selected.length === 0) {
            // Select the last item.
            index = this._items.length - 1;
        }
        else {
            // Select the first selected item.
            let name = selected[0];
            index = algorithm_1.ArrayExt.findFirstIndex(items, value => value.name === name);
        }
        if (index !== -1) {
            this._selectItem(index, keepExisting);
            domutils_1.ElementExt.scrollIntoViewIfNeeded(this.contentNode, this._items[index]);
        }
    }
    /**
     * Select the first item that starts with prefix being typed.
     */
    selectByPrefix() {
        const prefix = this._searchPrefix;
        let items = this._sortedItems;
        let index = algorithm_1.ArrayExt.findFirstIndex(items, value => {
            return value.name.toLowerCase().substr(0, prefix.length) === prefix;
        });
        if (index !== -1) {
            this._selectItem(index, false);
            domutils_1.ElementExt.scrollIntoViewIfNeeded(this.contentNode, this._items[index]);
        }
    }
    /**
     * Get whether an item is selected by name.
     *
     * @param name - The name of of the item.
     *
     * @returns Whether the item is selected.
     */
    isSelected(name) {
        return this._selection[name] === true;
    }
    /**
     * Find a model given a click.
     *
     * @param event - The mouse event.
     *
     * @returns The model for the selected file.
     */
    modelForClick(event) {
        let items = this._sortedItems;
        let index = Private.hitTestNodes(this._items, event.clientX, event.clientY);
        if (index !== -1) {
            return items[index];
        }
        return undefined;
    }
    /**
     * Select an item by name.
     *
     * @parem name - The name of the item to select.
     *
     * @returns A promise that resolves when the name is selected.
     */
    selectItemByName(name) {
        // Make sure the file is available.
        return this.model.refresh().then(() => {
            if (this.isDisposed) {
                throw new Error('File browser is disposed.');
            }
            let items = this._sortedItems;
            let index = algorithm_1.ArrayExt.findFirstIndex(items, value => value.name === name);
            if (index === -1) {
                throw new Error('Item does not exist.');
            }
            this._selectItem(index, false);
            messaging_1.MessageLoop.sendMessage(this, widgets_1.Widget.Msg.UpdateRequest);
            domutils_1.ElementExt.scrollIntoViewIfNeeded(this.contentNode, this._items[index]);
        });
    }
    /**
     * Handle the DOM events for the directory listing.
     *
     * @param event - The DOM event sent to the widget.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the panel's DOM node. It should
     * not be called directly by user code.
     */
    handleEvent(event) {
        switch (event.type) {
            case 'mousedown':
                this._evtMousedown(event);
                break;
            case 'mouseup':
                this._evtMouseup(event);
                break;
            case 'mousemove':
                this._evtMousemove(event);
                break;
            case 'keydown':
                this._evtKeydown(event);
                break;
            case 'click':
                this._evtClick(event);
                break;
            case 'dblclick':
                this._evtDblClick(event);
                break;
            case 'dragenter':
            case 'dragover':
                this.addClass('jp-mod-native-drop');
                event.preventDefault();
                break;
            case 'dragleave':
            case 'dragend':
                this.removeClass('jp-mod-native-drop');
                break;
            case 'drop':
                this.removeClass('jp-mod-native-drop');
                this._evtNativeDrop(event);
                break;
            case 'scroll':
                this._evtScroll(event);
                break;
            case 'p-dragenter':
                this._evtDragEnter(event);
                break;
            case 'p-dragleave':
                this._evtDragLeave(event);
                break;
            case 'p-dragover':
                this._evtDragOver(event);
                break;
            case 'p-drop':
                this._evtDrop(event);
                break;
            default:
                break;
        }
    }
    /**
     * A message handler invoked on an `'after-attach'` message.
     */
    onAfterAttach(msg) {
        super.onAfterAttach(msg);
        let node = this.node;
        let content = apputils_1.DOMUtils.findElement(node, CONTENT_CLASS);
        node.addEventListener('mousedown', this);
        node.addEventListener('keydown', this);
        node.addEventListener('click', this);
        node.addEventListener('dblclick', this);
        content.addEventListener('dragenter', this);
        content.addEventListener('dragover', this);
        content.addEventListener('dragleave', this);
        content.addEventListener('dragend', this);
        content.addEventListener('drop', this);
        content.addEventListener('scroll', this);
        content.addEventListener('p-dragenter', this);
        content.addEventListener('p-dragleave', this);
        content.addEventListener('p-dragover', this);
        content.addEventListener('p-drop', this);
    }
    /**
     * A message handler invoked on a `'before-detach'` message.
     */
    onBeforeDetach(msg) {
        super.onBeforeDetach(msg);
        let node = this.node;
        let content = apputils_1.DOMUtils.findElement(node, CONTENT_CLASS);
        node.removeEventListener('mousedown', this);
        node.removeEventListener('keydown', this);
        node.removeEventListener('click', this);
        node.removeEventListener('dblclick', this);
        content.removeEventListener('scroll', this);
        content.removeEventListener('dragover', this);
        content.removeEventListener('dragover', this);
        content.removeEventListener('dragleave', this);
        content.removeEventListener('dragend', this);
        content.removeEventListener('drop', this);
        content.removeEventListener('p-dragenter', this);
        content.removeEventListener('p-dragleave', this);
        content.removeEventListener('p-dragover', this);
        content.removeEventListener('p-drop', this);
        document.removeEventListener('mousemove', this, true);
        document.removeEventListener('mouseup', this, true);
    }
    /**
     * A message handler invoked on an `'after-show'` message.
     */
    onAfterShow(msg) {
        if (this._isDirty) {
            // Update the sorted items.
            this.sort(this.sortState);
            this.update();
        }
    }
    /**
     * A handler invoked on an `'update-request'` message.
     */
    onUpdateRequest(msg) {
        this._isDirty = false;
        // Fetch common variables.
        let items = this._sortedItems;
        let nodes = this._items;
        let content = apputils_1.DOMUtils.findElement(this.node, CONTENT_CLASS);
        let renderer = this._renderer;
        this.removeClass(MULTI_SELECTED_CLASS);
        this.removeClass(SELECTED_CLASS);
        // Remove any excess item nodes.
        while (nodes.length > items.length) {
            content.removeChild(nodes.pop());
        }
        // Add any missing item nodes.
        while (nodes.length < items.length) {
            let node = renderer.createItemNode();
            node.classList.add(ITEM_CLASS);
            nodes.push(node);
            content.appendChild(node);
        }
        // Remove extra classes from the nodes.
        nodes.forEach(item => {
            item.classList.remove(SELECTED_CLASS);
            item.classList.remove(RUNNING_CLASS);
            item.classList.remove(CUT_CLASS);
        });
        // Add extra classes to item nodes based on widget state.
        items.forEach((item, i) => {
            let node = nodes[i];
            let ft = this._manager.registry.getFileTypeForModel(item);
            renderer.updateItemNode(node, item, ft);
            if (this._selection[item.name]) {
                node.classList.add(SELECTED_CLASS);
                if (this._isCut && this._model.path === this._prevPath) {
                    node.classList.add(CUT_CLASS);
                }
            }
            // add metadata to the node
            node.setAttribute('data-isdir', item.type === 'directory' ? 'true' : 'false');
        });
        // Handle the selectors on the widget node.
        let selected = Object.keys(this._selection).length;
        if (selected) {
            this.addClass(SELECTED_CLASS);
            if (selected > 1) {
                this.addClass(MULTI_SELECTED_CLASS);
            }
        }
        // Handle file session statuses.
        let paths = items.map(item => item.path);
        algorithm_1.each(this._model.sessions(), session => {
            let index = algorithm_1.ArrayExt.firstIndexOf(paths, session.path);
            let node = nodes[index];
            let name = session.kernel.name;
            let specs = this._model.specs;
            node.classList.add(RUNNING_CLASS);
            if (specs) {
                name = specs.kernelspecs[name].display_name;
            }
            node.title = `${node.title}\nKernel: ${name}`;
        });
        this._prevPath = this._model.path;
    }
    /**
     * Handle the `'click'` event for the widget.
     */
    _evtClick(event) {
        let target = event.target;
        let header = this.headerNode;
        if (header.contains(target)) {
            let state = this.renderer.handleHeaderClick(header, event);
            if (state) {
                this.sort(state);
            }
            return;
        }
    }
    /**
     * Handle the `'scroll'` event for the widget.
     */
    _evtScroll(event) {
        this.headerNode.scrollLeft = this.contentNode.scrollLeft;
    }
    /**
     * Handle the `'mousedown'` event for the widget.
     */
    _evtMousedown(event) {
        // Bail if clicking within the edit node
        if (event.target === this._editNode) {
            return;
        }
        // Blur the edit node if necessary.
        if (this._editNode.parentNode) {
            if (this._editNode !== event.target) {
                this._editNode.focus();
                this._editNode.blur();
                clearTimeout(this._selectTimer);
            }
            else {
                return;
            }
        }
        let index = Private.hitTestNodes(this._items, event.clientX, event.clientY);
        if (index === -1) {
            return;
        }
        this._handleFileSelect(event);
        if (event.button !== 0) {
            clearTimeout(this._selectTimer);
        }
        // Check for clearing a context menu.
        let newContext = (IS_MAC && event.ctrlKey) || event.button === 2;
        if (newContext) {
            return;
        }
        // Left mouse press for drag start.
        if (event.button === 0) {
            this._dragData = {
                pressX: event.clientX,
                pressY: event.clientY,
                index: index
            };
            document.addEventListener('mouseup', this, true);
            document.addEventListener('mousemove', this, true);
        }
    }
    /**
     * Handle the `'mouseup'` event for the widget.
     */
    _evtMouseup(event) {
        // Handle any soft selection from the previous mouse down.
        if (this._softSelection) {
            let altered = event.metaKey || event.shiftKey || event.ctrlKey;
            // See if we need to clear the other selection.
            if (!altered && event.button === 0) {
                this._selection = Object.create(null);
                this._selection[this._softSelection] = true;
                this.update();
            }
            this._softSelection = '';
        }
        // Remove the drag listeners if necessary.
        if (event.button !== 0 || !this._drag) {
            document.removeEventListener('mousemove', this, true);
            document.removeEventListener('mouseup', this, true);
            return;
        }
        event.preventDefault();
        event.stopPropagation();
    }
    /**
     * Handle the `'mousemove'` event for the widget.
     */
    _evtMousemove(event) {
        event.preventDefault();
        event.stopPropagation();
        // Bail if we are the one dragging.
        if (this._drag || !this._dragData) {
            return;
        }
        // Check for a drag initialization.
        let data = this._dragData;
        let dx = Math.abs(event.clientX - data.pressX);
        let dy = Math.abs(event.clientY - data.pressY);
        if (dx < DRAG_THRESHOLD && dy < DRAG_THRESHOLD) {
            return;
        }
        this._startDrag(data.index, event.clientX, event.clientY);
    }
    /**
     * Handle the `'keydown'` event for the widget.
     */
    _evtKeydown(event) {
        switch (event.keyCode) {
            case 13: // Enter
                // Do nothing if any modifier keys are pressed.
                if (event.ctrlKey || event.shiftKey || event.altKey || event.metaKey) {
                    return;
                }
                event.preventDefault();
                event.stopPropagation();
                let selected = Object.keys(this._selection);
                let name = selected[0];
                let items = this._sortedItems;
                let i = algorithm_1.ArrayExt.findFirstIndex(items, value => value.name === name);
                if (i === -1) {
                    return;
                }
                let model = this._model;
                let item = this._sortedItems[i];
                if (item.type === 'directory') {
                    model
                        .cd(item.name)
                        .catch(error => apputils_1.showErrorMessage('Open directory', error));
                }
                else {
                    let path = item.path;
                    this._manager.openOrReveal(path);
                }
                break;
            case 38: // Up arrow
                this.selectPrevious(event.shiftKey);
                event.stopPropagation();
                event.preventDefault();
                break;
            case 40: // Down arrow
                this.selectNext(event.shiftKey);
                event.stopPropagation();
                event.preventDefault();
                break;
            default:
                break;
        }
        // Detects printable characters typed by the user.
        // Not all browsers support .key, but it discharges us from reconstructing
        // characters from key codes.
        if (!this._inRename && event.key !== undefined && event.key.length === 1) {
            this._searchPrefix += event.key;
            clearTimeout(this._searchPrefixTimer);
            this._searchPrefixTimer = window.setTimeout(() => {
                this._searchPrefix = '';
            }, PREFIX_APPEND_DURATION);
            this.selectByPrefix();
            event.stopPropagation();
            event.preventDefault();
        }
    }
    /**
     * Handle the `'dblclick'` event for the widget.
     */
    _evtDblClick(event) {
        // Do nothing if it's not a left mouse press.
        if (event.button !== 0) {
            return;
        }
        // Do nothing if any modifier keys are pressed.
        if (event.ctrlKey || event.shiftKey || event.altKey || event.metaKey) {
            return;
        }
        // Stop the event propagation.
        event.preventDefault();
        event.stopPropagation();
        clearTimeout(this._selectTimer);
        this._editNode.blur();
        // Find a valid double click target.
        let target = event.target;
        let i = algorithm_1.ArrayExt.findFirstIndex(this._items, node => node.contains(target));
        if (i === -1) {
            return;
        }
        let model = this._model;
        let item = this._sortedItems[i];
        if (item.type === 'directory') {
            model
                .cd(item.name)
                .catch(error => apputils_1.showErrorMessage('Open directory', error));
        }
        else {
            let path = item.path;
            this._manager.openOrReveal(path);
        }
    }
    /**
     * Handle the `drop` event for the widget.
     */
    _evtNativeDrop(event) {
        let files = event.dataTransfer.files;
        if (files.length === 0) {
            return;
        }
        event.preventDefault();
        for (let i = 0; i < files.length; i++) {
            this._model.upload(files[i]);
        }
    }
    /**
     * Handle the `'p-dragenter'` event for the widget.
     */
    _evtDragEnter(event) {
        if (event.mimeData.hasData(CONTENTS_MIME)) {
            let index = Private.hitTestNodes(this._items, event.clientX, event.clientY);
            if (index === -1) {
                return;
            }
            let item = this._sortedItems[index];
            if (item.type !== 'directory' || this._selection[item.name]) {
                return;
            }
            let target = event.target;
            target.classList.add(DROP_TARGET_CLASS);
            event.preventDefault();
            event.stopPropagation();
        }
    }
    /**
     * Handle the `'p-dragleave'` event for the widget.
     */
    _evtDragLeave(event) {
        event.preventDefault();
        event.stopPropagation();
        let dropTarget = apputils_1.DOMUtils.findElement(this.node, DROP_TARGET_CLASS);
        if (dropTarget) {
            dropTarget.classList.remove(DROP_TARGET_CLASS);
        }
    }
    /**
     * Handle the `'p-dragover'` event for the widget.
     */
    _evtDragOver(event) {
        event.preventDefault();
        event.stopPropagation();
        event.dropAction = event.proposedAction;
        let dropTarget = apputils_1.DOMUtils.findElement(this.node, DROP_TARGET_CLASS);
        if (dropTarget) {
            dropTarget.classList.remove(DROP_TARGET_CLASS);
        }
        let index = Private.hitTestNodes(this._items, event.clientX, event.clientY);
        this._items[index].classList.add(DROP_TARGET_CLASS);
    }
    /**
     * Handle the `'p-drop'` event for the widget.
     */
    _evtDrop(event) {
        event.preventDefault();
        event.stopPropagation();
        clearTimeout(this._selectTimer);
        if (event.proposedAction === 'none') {
            event.dropAction = 'none';
            return;
        }
        if (!event.mimeData.hasData(CONTENTS_MIME)) {
            return;
        }
        event.dropAction = event.proposedAction;
        let target = event.target;
        while (target && target.parentElement) {
            if (target.classList.contains(DROP_TARGET_CLASS)) {
                target.classList.remove(DROP_TARGET_CLASS);
                break;
            }
            target = target.parentElement;
        }
        // Get the path based on the target node.
        const index = algorithm_1.ArrayExt.firstIndexOf(this._items, target);
        const items = this._sortedItems;
        let basePath = this._model.path;
        if (items[index].type === 'directory') {
            basePath = coreutils_1.PathExt.join(basePath, items[index].name);
        }
        const manager = this._manager;
        // Handle the items.
        const promises = [];
        const paths = event.mimeData.getData(CONTENTS_MIME);
        for (let path of paths) {
            let localPath = manager.services.contents.localPath(path);
            let name = coreutils_1.PathExt.basename(localPath);
            let newPath = coreutils_1.PathExt.join(basePath, name);
            // Skip files that are not moving.
            if (newPath === path) {
                continue;
            }
            promises.push(docmanager_1.renameFile(manager, path, newPath));
        }
        Promise.all(promises).catch(error => {
            apputils_1.showErrorMessage('Move Error', error);
        });
    }
    /**
     * Start a drag event.
     */
    _startDrag(index, clientX, clientY) {
        let selectedNames = Object.keys(this._selection);
        let source = this._items[index];
        let items = this._sortedItems;
        let item;
        // If the source node is not selected, use just that node.
        if (!source.classList.contains(SELECTED_CLASS)) {
            item = items[index];
            selectedNames = [item.name];
        }
        else {
            let name = selectedNames[0];
            item = algorithm_1.find(items, value => value.name === name);
        }
        if (!item) {
            return;
        }
        // Create the drag image.
        let ft = this._manager.registry.getFileTypeForModel(item);
        let dragImage = this.renderer.createDragImage(source, selectedNames.length, ft);
        // Set up the drag event.
        this._drag = new dragdrop_1.Drag({
            dragImage,
            mimeData: new coreutils_2.MimeData(),
            supportedActions: 'move',
            proposedAction: 'move'
        });
        let basePath = this._model.path;
        let paths = algorithm_1.toArray(algorithm_1.map(selectedNames, name => {
            return coreutils_1.PathExt.join(basePath, name);
        }));
        this._drag.mimeData.setData(CONTENTS_MIME, paths);
        if (item && item.type !== 'directory') {
            const otherPaths = paths.slice(1).reverse();
            this._drag.mimeData.setData(FACTORY_MIME, () => {
                if (!item) {
                    return;
                }
                let path = item.path;
                let widget = this._manager.findWidget(path);
                if (!widget) {
                    widget = this._manager.open(item.path);
                }
                if (otherPaths.length) {
                    const firstWidgetPlaced = new coreutils_2.PromiseDelegate();
                    firstWidgetPlaced.promise.then(() => {
                        let prevWidget = widget;
                        otherPaths.forEach(path => {
                            const options = {
                                ref: prevWidget.id,
                                mode: 'tab-after'
                            };
                            prevWidget = this._manager.openOrReveal(path, void 0, void 0, options);
                            this._manager.openOrReveal(item.path);
                        });
                    });
                    firstWidgetPlaced.resolve(void 0);
                }
                return widget;
            });
        }
        // Start the drag and remove the mousemove and mouseup listeners.
        document.removeEventListener('mousemove', this, true);
        document.removeEventListener('mouseup', this, true);
        clearTimeout(this._selectTimer);
        this._drag.start(clientX, clientY).then(action => {
            this._drag = null;
            clearTimeout(this._selectTimer);
        });
    }
    /**
     * Handle selection on a file node.
     */
    _handleFileSelect(event) {
        // Fetch common variables.
        let items = this._sortedItems;
        let index = Private.hitTestNodes(this._items, event.clientX, event.clientY);
        clearTimeout(this._selectTimer);
        if (index === -1) {
            return;
        }
        // Clear any existing soft selection.
        this._softSelection = '';
        let name = items[index].name;
        let selected = Object.keys(this._selection);
        // Handle toggling.
        if ((IS_MAC && event.metaKey) || (!IS_MAC && event.ctrlKey)) {
            if (this._selection[name]) {
                delete this._selection[name];
            }
            else {
                this._selection[name] = true;
            }
            // Handle multiple select.
        }
        else if (event.shiftKey) {
            this._handleMultiSelect(selected, index);
            // Handle a 'soft' selection
        }
        else if (name in this._selection && selected.length > 1) {
            this._softSelection = name;
            // Default to selecting the only the item.
        }
        else {
            // Select only the given item.
            this._selection = Object.create(null);
            this._selection[name] = true;
        }
        this.update();
    }
    /**
     * Handle a multiple select on a file item node.
     */
    _handleMultiSelect(selected, index) {
        // Find the "nearest selected".
        let items = this._sortedItems;
        let nearestIndex = -1;
        for (let i = 0; i < this._items.length; i++) {
            if (i === index) {
                continue;
            }
            let name = items[i].name;
            if (selected.indexOf(name) !== -1) {
                if (nearestIndex === -1) {
                    nearestIndex = i;
                }
                else {
                    if (Math.abs(index - i) < Math.abs(nearestIndex - i)) {
                        nearestIndex = i;
                    }
                }
            }
        }
        // Default to the first element (and fill down).
        if (nearestIndex === -1) {
            nearestIndex = 0;
        }
        // Select the rows between the current and the nearest selected.
        for (let i = 0; i < this._items.length; i++) {
            if ((nearestIndex >= i && index <= i) ||
                (nearestIndex <= i && index >= i)) {
                this._selection[items[i].name] = true;
            }
        }
    }
    /**
     * Copy the selected items, and optionally cut as well.
     */
    _copy() {
        this._clipboard.length = 0;
        algorithm_1.each(this.selectedItems(), item => {
            this._clipboard.push(item.path);
        });
    }
    /**
     * Delete the files with the given names.
     */
    _delete(names) {
        const promises = [];
        const basePath = this._model.path;
        for (let name of names) {
            let newPath = coreutils_1.PathExt.join(basePath, name);
            let promise = this._model.manager.deleteFile(newPath).catch(err => {
                apputils_1.showErrorMessage('Delete Failed', err);
            });
            promises.push(promise);
        }
        return Promise.all(promises).then(() => undefined);
    }
    /**
     * Allow the user to rename item on a given row.
     */
    _doRename() {
        this._inRename = true;
        let items = this._sortedItems;
        let name = Object.keys(this._selection)[0];
        let index = algorithm_1.ArrayExt.findFirstIndex(items, value => value.name === name);
        let row = this._items[index];
        let item = items[index];
        let nameNode = this.renderer.getNameNode(row);
        let original = item.name;
        this._editNode.value = original;
        this._selectItem(index, false);
        return Private.doRename(nameNode, this._editNode).then(newName => {
            if (!newName || newName === original) {
                this._inRename = false;
                return original;
            }
            if (!docmanager_1.isValidFileName(newName)) {
                apputils_1.showErrorMessage('Rename Error', Error(`"${newName}" is not a valid name for a file. ` +
                    `Names must have nonzero length, ` +
                    `and cannot include "/", "\\", or ":"`));
                this._inRename = false;
                return original;
            }
            if (this.isDisposed) {
                this._inRename = false;
                throw new Error('File browser is disposed.');
            }
            const manager = this._manager;
            const oldPath = coreutils_1.PathExt.join(this._model.path, original);
            const newPath = coreutils_1.PathExt.join(this._model.path, newName);
            const promise = docmanager_1.renameFile(manager, oldPath, newPath);
            return promise
                .catch(error => {
                if (error !== 'File not renamed') {
                    apputils_1.showErrorMessage('Rename Error', error);
                }
                this._inRename = false;
                return original;
            })
                .then(() => {
                if (this.isDisposed) {
                    this._inRename = false;
                    throw new Error('File browser is disposed.');
                }
                if (this._inRename) {
                    // No need to catch because `newName` will always exit.
                    this.selectItemByName(newName);
                }
                this._inRename = false;
                return newName;
            });
        });
    }
    /**
     * Select a given item.
     */
    _selectItem(index, keepExisting) {
        // Selected the given row(s)
        let items = this._sortedItems;
        if (!keepExisting) {
            this._selection = Object.create(null);
        }
        let name = items[index].name;
        this._selection[name] = true;
        this.update();
    }
    /**
     * Handle the `refreshed` signal from the model.
     */
    _onModelRefreshed() {
        // Update the selection.
        let existing = Object.keys(this._selection);
        this._selection = Object.create(null);
        algorithm_1.each(this._model.items(), item => {
            let name = item.name;
            if (existing.indexOf(name) !== -1) {
                this._selection[name] = true;
            }
        });
        if (this.isVisible) {
            // Update the sorted items.
            this.sort(this.sortState);
        }
        else {
            this._isDirty = true;
        }
    }
    /**
     * Handle a `pathChanged` signal from the model.
     */
    _onPathChanged() {
        // Reset the selection.
        this._selection = Object.create(null);
        // Update the sorted items.
        this.sort(this.sortState);
    }
    /**
     * Handle a `fileChanged` signal from the model.
     */
    _onFileChanged(sender, args) {
        let newValue = args.newValue;
        if (!newValue) {
            return;
        }
        if (args.type !== 'new' || !name) {
            return;
        }
        this.selectItemByName(name)
            .then(() => {
            if (!this.isDisposed && newValue.type === 'directory') {
                this._doRename();
            }
        })
            .catch(() => {
            /* Ignore if file does not exist. */
        });
    }
    /**
     * Handle an `activateRequested` signal from the manager.
     */
    _onActivateRequested(sender, args) {
        let dirname = coreutils_1.PathExt.dirname(args);
        if (dirname !== this._model.path) {
            return;
        }
        let basename = coreutils_1.PathExt.basename(args);
        this.selectItemByName(basename).catch(() => {
            /* Ignore if file does not exist. */
        });
    }
}
exports.DirListing = DirListing;
/**
 * The namespace for the `DirListing` class statics.
 */
(function (DirListing) {
    /**
     * The default implementation of an `IRenderer`.
     */
    class Renderer {
        /**
         * Create the DOM node for a dir listing.
         */
        createNode() {
            let node = document.createElement('div');
            let header = document.createElement('div');
            let content = document.createElement('ul');
            content.className = CONTENT_CLASS;
            header.className = HEADER_CLASS;
            node.appendChild(header);
            node.appendChild(content);
            node.tabIndex = 1;
            return node;
        }
        /**
         * Populate and empty header node for a dir listing.
         *
         * @param node - The header node to populate.
         */
        populateHeaderNode(node) {
            let name = this._createHeaderItemNode('Name');
            let modified = this._createHeaderItemNode('Last Modified');
            name.classList.add(NAME_ID_CLASS);
            name.classList.add(SELECTED_CLASS);
            modified.classList.add(MODIFIED_ID_CLASS);
            node.appendChild(name);
            node.appendChild(modified);
        }
        /**
         * Handle a header click.
         *
         * @param node - A node populated by [[populateHeaderNode]].
         *
         * @param event - A click event on the node.
         *
         * @returns The sort state of the header after the click event.
         */
        handleHeaderClick(node, event) {
            let name = apputils_1.DOMUtils.findElement(node, NAME_ID_CLASS);
            let modified = apputils_1.DOMUtils.findElement(node, MODIFIED_ID_CLASS);
            let state = { direction: 'ascending', key: 'name' };
            let target = event.target;
            if (name.contains(target)) {
                if (name.classList.contains(SELECTED_CLASS)) {
                    if (!name.classList.contains(DESCENDING_CLASS)) {
                        state.direction = 'descending';
                        name.classList.add(DESCENDING_CLASS);
                    }
                    else {
                        name.classList.remove(DESCENDING_CLASS);
                    }
                }
                else {
                    name.classList.remove(DESCENDING_CLASS);
                }
                name.classList.add(SELECTED_CLASS);
                modified.classList.remove(SELECTED_CLASS);
                modified.classList.remove(DESCENDING_CLASS);
                return state;
            }
            if (modified.contains(target)) {
                state.key = 'last_modified';
                if (modified.classList.contains(SELECTED_CLASS)) {
                    if (!modified.classList.contains(DESCENDING_CLASS)) {
                        state.direction = 'descending';
                        modified.classList.add(DESCENDING_CLASS);
                    }
                    else {
                        modified.classList.remove(DESCENDING_CLASS);
                    }
                }
                else {
                    modified.classList.remove(DESCENDING_CLASS);
                }
                modified.classList.add(SELECTED_CLASS);
                name.classList.remove(SELECTED_CLASS);
                name.classList.remove(DESCENDING_CLASS);
                return state;
            }
            return state;
        }
        /**
         * Create a new item node for a dir listing.
         *
         * @returns A new DOM node to use as a content item.
         */
        createItemNode() {
            let node = document.createElement('li');
            let icon = document.createElement('span');
            let text = document.createElement('span');
            let modified = document.createElement('span');
            icon.className = ITEM_ICON_CLASS;
            text.className = ITEM_TEXT_CLASS;
            modified.className = ITEM_MODIFIED_CLASS;
            node.appendChild(icon);
            node.appendChild(text);
            node.appendChild(modified);
            return node;
        }
        /**
         * Update an item node to reflect the current state of a model.
         *
         * @param node - A node created by [[createItemNode]].
         *
         * @param model - The model object to use for the item state.
         *
         * @param fileType - The file type of the item, if applicable.
         *
         */
        updateItemNode(node, model, fileType) {
            let icon = apputils_1.DOMUtils.findElement(node, ITEM_ICON_CLASS);
            let text = apputils_1.DOMUtils.findElement(node, ITEM_TEXT_CLASS);
            let modified = apputils_1.DOMUtils.findElement(node, ITEM_MODIFIED_CLASS);
            if (fileType) {
                icon.textContent = fileType.iconLabel || '';
                icon.className = `${ITEM_ICON_CLASS} ${fileType.iconClass || ''}`;
            }
            else {
                icon.textContent = '';
                icon.className = ITEM_ICON_CLASS;
            }
            node.title = model.name;
            // If an item is being edited currently, its text node is unavailable.
            if (text) {
                text.textContent = model.name;
            }
            let modText = '';
            let modTitle = '';
            if (model.last_modified) {
                modText = coreutils_1.Time.formatHuman(new Date(model.last_modified));
                modTitle = coreutils_1.Time.format(new Date(model.last_modified));
            }
            modified.textContent = modText;
            modified.title = modTitle;
        }
        /**
         * Get the node containing the file name.
         *
         * @param node - A node created by [[createItemNode]].
         *
         * @returns The node containing the file name.
         */
        getNameNode(node) {
            return apputils_1.DOMUtils.findElement(node, ITEM_TEXT_CLASS);
        }
        /**
         * Create a drag image for an item.
         *
         * @param node - A node created by [[createItemNode]].
         *
         * @param count - The number of items being dragged.
         *
         * @param fileType - The file type of the item, if applicable.
         *
         * @returns An element to use as the drag image.
         */
        createDragImage(node, count, fileType) {
            let dragImage = node.cloneNode(true);
            let modified = apputils_1.DOMUtils.findElement(dragImage, ITEM_MODIFIED_CLASS);
            let icon = apputils_1.DOMUtils.findElement(dragImage, ITEM_ICON_CLASS);
            dragImage.removeChild(modified);
            if (!fileType) {
                icon.textContent = '';
                icon.className = '';
            }
            else {
                icon.textContent = fileType.iconLabel || '';
                icon.className = fileType.iconClass || '';
            }
            icon.classList.add(DRAG_ICON_CLASS);
            if (count > 1) {
                let nameNode = apputils_1.DOMUtils.findElement(dragImage, ITEM_TEXT_CLASS);
                nameNode.textContent = count + ' Items';
            }
            return dragImage;
        }
        /**
         * Create a node for a header item.
         */
        _createHeaderItemNode(label) {
            let node = document.createElement('div');
            let text = document.createElement('span');
            let icon = document.createElement('span');
            node.className = HEADER_ITEM_CLASS;
            text.className = HEADER_ITEM_TEXT_CLASS;
            icon.className = HEADER_ITEM_ICON_CLASS;
            text.textContent = label;
            node.appendChild(text);
            node.appendChild(icon);
            return node;
        }
    }
    DirListing.Renderer = Renderer;
    /**
     * The default `IRenderer` instance.
     */
    DirListing.defaultRenderer = new Renderer();
})(DirListing = exports.DirListing || (exports.DirListing = {}));
/**
 * The namespace for the listing private data.
 */
var Private;
(function (Private) {
    /**
     * Handle editing text on a node.
     *
     * @returns Boolean indicating whether the name changed.
     */
    function doRename(text, edit) {
        let parent = text.parentElement;
        parent.replaceChild(edit, text);
        edit.focus();
        let index = edit.value.lastIndexOf('.');
        if (index === -1) {
            edit.setSelectionRange(0, edit.value.length);
        }
        else {
            edit.setSelectionRange(0, index);
        }
        return new Promise((resolve, reject) => {
            edit.onblur = () => {
                parent.replaceChild(text, edit);
                resolve(edit.value);
            };
            edit.onkeydown = (event) => {
                switch (event.keyCode) {
                    case 13: // Enter
                        event.stopPropagation();
                        event.preventDefault();
                        edit.blur();
                        break;
                    case 27: // Escape
                        event.stopPropagation();
                        event.preventDefault();
                        edit.blur();
                        break;
                    case 38: // Up arrow
                        event.stopPropagation();
                        event.preventDefault();
                        if (edit.selectionStart !== edit.selectionEnd) {
                            edit.selectionStart = edit.selectionEnd = 0;
                        }
                        break;
                    case 40: // Down arrow
                        event.stopPropagation();
                        event.preventDefault();
                        if (edit.selectionStart !== edit.selectionEnd) {
                            edit.selectionStart = edit.selectionEnd = edit.value.length;
                        }
                        break;
                    default:
                        break;
                }
            };
        });
    }
    Private.doRename = doRename;
    /**
     * Sort a list of items by sort state as a new array.
     */
    function sort(items, state) {
        let copy = algorithm_1.toArray(items);
        if (state.key === 'last_modified') {
            // Sort by type and then by last modified.
            copy.sort((a, b) => {
                // Compare based on type.
                let t1 = typeWeight(a);
                let t2 = typeWeight(b);
                if (t1 !== t2) {
                    return t1 < t2 ? -1 : 1; // Infinity safe
                }
                let valA = new Date(a.last_modified).getTime();
                let valB = new Date(b.last_modified).getTime();
                if (state.direction === 'descending') {
                    return valA - valB;
                }
                return valB - valA;
            });
        }
        else {
            // Sort by type and then by name.
            copy.sort((a, b) => {
                // Compare based on type.
                let t1 = typeWeight(a);
                let t2 = typeWeight(b);
                if (t1 !== t2) {
                    return t1 < t2 ? -1 : 1; // Infinity safe
                }
                // Compare by display name.
                if (state.direction === 'descending') {
                    return b.name.localeCompare(a.name);
                }
                return a.name.localeCompare(b.name);
            });
        }
        return copy;
    }
    Private.sort = sort;
    /**
     * Get the index of the node at a client position, or `-1`.
     */
    function hitTestNodes(nodes, x, y) {
        return algorithm_1.ArrayExt.findFirstIndex(nodes, node => domutils_1.ElementExt.hitTest(node, x, y));
    }
    Private.hitTestNodes = hitTestNodes;
    /**
     * Weight a contents model by type.
     */
    function typeWeight(model) {
        switch (model.type) {
            case 'directory':
                return 0;
            case 'notebook':
                return 1;
            case 'file':
                return 2;
            default:
                return Infinity;
        }
    }
})(Private || (Private = {}));


/***/ }),

/***/ "mAz1":
/*!********************************************************!*\
  !*** ./node_modules/browserify-sign/browser/verify.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(Buffer) {// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
var BN = __webpack_require__(/*! bn.js */ "OZ/i")
var EC = __webpack_require__(/*! elliptic */ "MzeL").ec
var parseKeys = __webpack_require__(/*! parse-asn1 */ "Ku4m")
var curves = __webpack_require__(/*! ./curves.json */ "zZGF")

function verify (sig, hash, key, signType, tag) {
  var pub = parseKeys(key)
  if (pub.type === 'ec') {
    // rsa keys can be interpreted as ecdsa ones in openssl
    if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')
    return ecVerify(sig, hash, pub)
  } else if (pub.type === 'dsa') {
    if (signType !== 'dsa') throw new Error('wrong public key type')
    return dsaVerify(sig, hash, pub)
  } else {
    if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')
  }
  hash = Buffer.concat([tag, hash])
  var len = pub.modulus.byteLength()
  var pad = [ 1 ]
  var padNum = 0
  while (hash.length + pad.length + 2 < len) {
    pad.push(0xff)
    padNum++
  }
  pad.push(0x00)
  var i = -1
  while (++i < hash.length) {
    pad.push(hash[i])
  }
  pad = new Buffer(pad)
  var red = BN.mont(pub.modulus)
  sig = new BN(sig).toRed(red)

  sig = sig.redPow(new BN(pub.publicExponent))
  sig = new Buffer(sig.fromRed().toArray())
  var out = padNum < 8 ? 1 : 0
  len = Math.min(sig.length, pad.length)
  if (sig.length !== pad.length) out = 1

  i = -1
  while (++i < len) out |= sig[i] ^ pad[i]
  return out === 0
}

function ecVerify (sig, hash, pub) {
  var curveId = curves[pub.data.algorithm.curve.join('.')]
  if (!curveId) throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.'))

  var curve = new EC(curveId)
  var pubkey = pub.data.subjectPrivateKey.data

  return curve.verify(hash, sig, pubkey)
}

function dsaVerify (sig, hash, pub) {
  var p = pub.data.p
  var q = pub.data.q
  var g = pub.data.g
  var y = pub.data.pub_key
  var unpacked = parseKeys.signature.decode(sig, 'der')
  var s = unpacked.s
  var r = unpacked.r
  checkValue(s, q)
  checkValue(r, q)
  var montp = BN.mont(p)
  var w = s.invm(q)
  var v = g.toRed(montp)
    .redPow(new BN(hash).mul(w).mod(q))
    .fromRed()
    .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed())
    .mod(p)
    .mod(q)
  return v.cmp(r) === 0
}

function checkValue (b, q) {
  if (b.cmpn(0) <= 0) throw new Error('invalid sig')
  if (b.cmp(q) >= q) throw new Error('invalid sig')
}

module.exports = verify

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../buffer/index.js */ "tjlA").Buffer))

/***/ }),

/***/ "mBDu":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils/style/index.css ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "+NTi");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "mEBQ":
/*!**************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/ForkIcon.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var ForkIcon = function ForkIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M12 26.313c0-.5-.188-.938-.5-1.25s-.75-.5-1.188-.5c-.5 0-.938.188-1.25.5s-.5.75-.5 1.25c0 .438.188.875.5 1.188s.75.5 1.25.5A1.71 1.71 0 0 0 12 26.313zm0-20.625A1.71 1.71 0 0 0 10.312 4c-.5 0-.938.188-1.25.5s-.5.75-.5 1.188c0 .5.188.938.5 1.25s.75.5 1.25.5c.438 0 .875-.188 1.188-.5s.5-.75.5-1.25zM23.438 8c0-.5-.188-.875-.5-1.188-.313-.375-.75-.5-1.25-.5-.438 0-.875.125-1.188.5-.313.313-.5.688-.5 1.188s.188.875.5 1.188c.313.375.75.5 1.188.5.5 0 .938-.125 1.25-.5a1.6 1.6 0 0 0 .5-1.188zm1.687 0c0 .625-.125 1.188-.438 1.75-.313.5-.75.938-1.25 1.188-.063 3.438-1.375 5.938-4.063 7.438-.813.438-2 .938-3.625 1.438-1.5.438-2.5.875-3 1.25s-.75 1-.75 1.813v.438c.5.313.938.75 1.25 1.25s.438 1.125.438 1.75c0 .938-.313 1.75-1 2.375-.625.688-1.438 1-2.375 1-1 0-1.813-.313-2.438-1-.688-.625-1-1.438-1-2.375 0-.625.125-1.25.438-1.75s.75-.938 1.25-1.25V8.69c-.5-.313-.938-.75-1.25-1.25s-.438-1.125-.438-1.75c0-.938.313-1.75 1-2.375.625-.688 1.438-1 2.438-1 .938 0 1.75.313 2.375 1 .688.625 1 1.438 1 2.375 0 .625-.125 1.25-.438 1.75s-.75.938-1.25 1.25v8.875c.625-.313 1.563-.688 2.75-1 .625-.25 1.188-.375 1.563-.563a7.07 7.07 0 0 0 1.25-.563c.438-.188.813-.438 1.063-.688s.5-.563.75-.938c.188-.313.375-.75.5-1.188.063-.5.125-1.063.125-1.688-.5-.25-.938-.688-1.25-1.188a3.464 3.464 0 0 1-.438-1.75c0-.938.313-1.75 1-2.438.625-.688 1.438-1 2.375-1 1 0 1.813.313 2.438 1 .688.688 1 1.5 1 2.438z' })
    );
};

exports.default = ForkIcon;

/***/ }),

/***/ "mEVB":
/*!*************************************************************!*\
  !*** ./node_modules/plotly.js/src/plots/font_attributes.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



/*
 * make a font attribute group
 *
 * @param {object} opts
 *   @param {string}
 *     opts.description: where & how this font is used
 *   @param {optional bool} arrayOk:
 *     should each part (family, size, color) be arrayOk? default false.
 *   @param {string} editType:
 *     the editType for all pieces of this font
 *   @param {optional string} colorEditType:
 *     a separate editType just for color
 *
 * @return {object} attributes object containing {family, size, color} as specified
 */
module.exports = function(opts) {
    var editType = opts.editType;
    var colorEditType = opts.colorEditType;
    if(colorEditType === undefined) colorEditType = editType;
    var attrs = {
        family: {
            valType: 'string',
            role: 'style',
            noBlank: true,
            strict: true,
            editType: editType,
            description: [
                'HTML font family - the typeface that will be applied by the web browser.',
                'The web browser will only be able to apply a font if it is available on the system',
                'which it operates. Provide multiple font families, separated by commas, to indicate',
                'the preference in which to apply fonts if they aren\'t available on the system.',
                'The plotly service (at https://plot.ly or on-premise) generates images on a server,',
                'where only a select number of',
                'fonts are installed and supported.',
                'These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*,',
                '*Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*,',
                '*PT Sans Narrow*, *Raleway*, *Times New Roman*.'
            ].join(' ')
        },
        size: {
            valType: 'number',
            role: 'style',
            min: 1,
            editType: editType
        },
        color: {
            valType: 'color',
            role: 'style',
            editType: colorEditType
        },
        editType: editType,
        // blank strings so compress_attributes can remove
        // TODO - that's uber hacky... better solution?
        description: '' + (opts.description || '') + ''
    };

    if(opts.arrayOk) {
        attrs.family.arrayOk = true;
        attrs.size.arrayOk = true;
        attrs.color.arrayOk = true;
    }

    return attrs;
};


/***/ }),

/***/ "mHnu":
/*!************************************************************!*\
  !*** ./node_modules/react-day-picker/lib/src/DateUtils.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.clone = clone;
exports.isDate = isDate;
exports.addMonths = addMonths;
exports.isSameDay = isSameDay;
exports.isSameMonth = isSameMonth;
exports.isDayBefore = isDayBefore;
exports.isDayAfter = isDayAfter;
exports.isPastDay = isPastDay;
exports.isFutureDay = isFutureDay;
exports.isDayBetween = isDayBetween;
exports.addDayToRange = addDayToRange;
exports.isDayInRange = isDayInRange;
exports.getWeekNumber = getWeekNumber;
/**
 * Clone a date object.
 *
 * @export
 * @param  {Date} d The date to clone
 * @return {Date} The cloned date
 */
function clone(d) {
  return new Date(d.getTime());
}

/**
 * Return `true` if the passed value is a valid JavaScript Date object.
 *
 * @export
 * @param {any} value
 * @returns {Boolean}
 */
function isDate(value) {
  return value instanceof Date && !isNaN(value.valueOf());
}

/**
 * Return `d` as a new date with `n` months added.
 *
 * @export
 * @param {[type]} d
 * @param {[type]} n
 */
function addMonths(d, n) {
  var newDate = clone(d);
  newDate.setMonth(d.getMonth() + n);
  return newDate;
}

/**
 * Return `true` if two dates are the same day, ignoring the time.
 *
 * @export
 * @param  {Date}  d1
 * @param  {Date}  d2
 * @return {Boolean}
 */
function isSameDay(d1, d2) {
  if (!d1 || !d2) {
    return false;
  }
  return d1.getDate() === d2.getDate() && d1.getMonth() === d2.getMonth() && d1.getFullYear() === d2.getFullYear();
}

/**
 * Return `true` if two dates fall in the same month.
 *
 * @export
 * @param  {Date}  d1
 * @param  {Date}  d2
 * @return {Boolean}
 */
function isSameMonth(d1, d2) {
  if (!d1 || !d2) {
    return false;
  }
  return d1.getMonth() === d2.getMonth() && d1.getFullYear() === d2.getFullYear();
}

/**
 * Returns `true` if the first day is before the second day.
 *
 * @export
 * @param {Date} d1
 * @param {Date} d2
 * @returns {Boolean}
 */
function isDayBefore(d1, d2) {
  var day1 = clone(d1).setHours(0, 0, 0, 0);
  var day2 = clone(d2).setHours(0, 0, 0, 0);
  return day1 < day2;
}

/**
 * Returns `true` if the first day is after the second day.
 *
 * @export
 * @param {Date} d1
 * @param {Date} d2
 * @returns {Boolean}
 */
function isDayAfter(d1, d2) {
  var day1 = clone(d1).setHours(0, 0, 0, 0);
  var day2 = clone(d2).setHours(0, 0, 0, 0);
  return day1 > day2;
}

/**
 * Return `true` if a day is in the past, e.g. yesterday or any day
 * before yesterday.
 *
 * @export
 * @param  {Date}  d
 * @return {Boolean}
 */
function isPastDay(d) {
  var today = new Date();
  today.setHours(0, 0, 0, 0);
  return isDayBefore(d, today);
}

/**
 * Return `true` if a day is in the future, e.g. tomorrow or any day
 * after tomorrow.
 *
 * @export
 * @param  {Date}  d
 * @return {Boolean}
 */
function isFutureDay(d) {
  var tomorrow = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
  tomorrow.setHours(0, 0, 0, 0);
  return d >= tomorrow;
}

/**
 * Return `true` if day `d` is between days `d1` and `d2`,
 * without including them.
 *
 * @export
 * @param  {Date}  d
 * @param  {Date}  d1
 * @param  {Date}  d2
 * @return {Boolean}
 */
function isDayBetween(d, d1, d2) {
  var date = clone(d);
  date.setHours(0, 0, 0, 0);
  return isDayAfter(date, d1) && isDayBefore(date, d2) || isDayAfter(date, d2) && isDayBefore(date, d1);
}

/**
 * Add a day to a range and return a new range. A range is an object with
 * `from` and `to` days.
 *
 * @export
 * @param {Date} day
 * @param {Object} range
 * @return {Object} Returns a new range object
 */
function addDayToRange(day) {
  var range = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { from: null, to: null };
  var from = range.from,
      to = range.to;

  if (!from) {
    from = day;
  } else if (from && to && isSameDay(from, to) && isSameDay(day, from)) {
    from = null;
    to = null;
  } else if (to && isDayBefore(day, from)) {
    from = day;
  } else if (to && isSameDay(day, to)) {
    from = day;
    to = day;
  } else {
    to = day;
    if (isDayBefore(to, from)) {
      to = from;
      from = day;
    }
  }

  return { from: from, to: to };
}

/**
 * Return `true` if a day is included in a range of days.
 *
 * @export
 * @param  {Date}  day
 * @param  {Object}  range
 * @return {Boolean}
 */
function isDayInRange(day, range) {
  var from = range.from,
      to = range.to;

  return from && isSameDay(day, from) || to && isSameDay(day, to) || from && to && isDayBetween(day, from, to);
}

/**
 * Return the year's week number (as per ISO, i.e. with the week starting from monday)
 * for the given day.
 *
 * @export
 * @param {Date} day
 * @returns {Number}
 */
function getWeekNumber(day) {
  var date = clone(day);
  date.setHours(0, 0, 0);
  date.setDate(date.getDate() + 4 - (date.getDay() || 7));
  return Math.ceil(((date - new Date(date.getFullYear(), 0, 1)) / 8.64e7 + 1) / 7);
}

exports.default = {
  addDayToRange: addDayToRange,
  addMonths: addMonths,
  clone: clone,
  getWeekNumber: getWeekNumber,
  isDate: isDate,
  isDayAfter: isDayAfter,
  isDayBefore: isDayBefore,
  isDayBetween: isDayBetween,
  isDayInRange: isDayInRange,
  isFutureDay: isFutureDay,
  isPastDay: isPastDay,
  isSameDay: isSameDay,
  isSameMonth: isSameMonth
};
//# sourceMappingURL=DateUtils.js.map

/***/ }),

/***/ "mJcH":
/*!****************************************************!*\
  !*** ./node_modules/mdi-react/FileDocumentIcon.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var FileDocumentIcon = function FileDocumentIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M13,9H18.5L13,3.5V9M6,2H14L20,8V20C20,21.1 19.1,22 18,22H6C4.89,22 4,21.1 4,20V4C4,2.89 4.89,2 6,2M15,18V16H6V18H15M18,14V12H6V14H18Z' })
  );
};

module.exports = FileDocumentIcon;


/***/ }),

/***/ "mObS":
/*!*********************************************!*\
  !*** ./node_modules/create-hash/browser.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var inherits = __webpack_require__(/*! inherits */ "P7XM")
var MD5 = __webpack_require__(/*! md5.js */ "9XZ3")
var RIPEMD160 = __webpack_require__(/*! ripemd160 */ "tcrS")
var sha = __webpack_require__(/*! sha.js */ "afKu")
var Base = __webpack_require__(/*! cipher-base */ "ZDAU")

function Hash (hash) {
  Base.call(this, 'digest')

  this._hash = hash
}

inherits(Hash, Base)

Hash.prototype._update = function (data) {
  this._hash.update(data)
}

Hash.prototype._final = function () {
  return this._hash.digest()
}

module.exports = function createHash (alg) {
  alg = alg.toLowerCase()
  if (alg === 'md5') return new MD5()
  if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160()

  return new Hash(sha(alg))
}


/***/ }),

/***/ "mPu1":
/*!******************************************************************!*\
  !*** ./node_modules/@jupyterlab/vega4-extension/style/index.css ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "Uggb");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "mQPs":
/*!*********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/PlotlyFold.js ***!
  \*********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Fold = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _FoldEmpty = __webpack_require__(/*! ./FoldEmpty */ "nFxz");

var _FoldEmpty2 = _interopRequireDefault(_FoldEmpty);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _classnames = __webpack_require__(/*! classnames */ "TSYQ");

var _classnames2 = _interopRequireDefault(_classnames);

var _plotlyIcons = __webpack_require__(/*! plotly-icons */ "hwSx");

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Fold = exports.Fold = function (_Component) {
  _inherits(Fold, _Component);

  function Fold() {
    _classCallCheck(this, Fold);

    var _this = _possibleConstructorReturn(this, (Fold.__proto__ || Object.getPrototypeOf(Fold)).call(this));

    _this.foldVisible = true;
    return _this;
  }

  _createClass(Fold, [{
    key: 'getChildContext',
    value: function getChildContext() {
      return {
        foldInfo: this.props.foldInfo ? this.props.foldInfo : null
      };
    }
  }, {
    key: 'render',
    value: function render() {
      if (!this.foldVisible && !this.props.messageIfEmpty) {
        return null;
      }
      var deleteContainer = this.context.deleteContainer;
      var _props = this.props,
          canDelete = _props.canDelete,
          children = _props.children,
          className = _props.className,
          folded = _props.folded,
          foldInfo = _props.foldInfo,
          toggleFold = _props.toggleFold,
          hideHeader = _props.hideHeader,
          Icon = _props.icon,
          messageIfEmpty = _props.messageIfEmpty,
          name = _props.name;


      var contentClass = (0, _classnames2.default)('fold__content', {
        'fold__content--noheader': hideHeader
      });

      var headerClass = (0, _classnames2.default)('fold__top', {
        'fold__top--open': !folded
      });

      var arrowClass = (0, _classnames2.default)('fold__top__arrow', {
        'fold__top__arrow--open': !folded
      });

      var arrowIcon = _react2.default.createElement(
        'div',
        { className: arrowClass },
        _react2.default.createElement(
          'div',
          { className: 'fold__top__arrow__wrapper' },
          _react2.default.createElement(_plotlyIcons.AngleDownIcon, null)
        )
      );

      var icon = Icon ? _react2.default.createElement(Icon, { className: 'fold__top__icon' }) : null;

      var deleteButton = canDelete && typeof deleteContainer === 'function' ? _react2.default.createElement(
        'div',
        {
          className: 'fold__top__delete js-fold__delete',
          onClick: function onClick(e) {
            e.stopPropagation();
            deleteContainer(foldInfo);
          }
        },
        _react2.default.createElement(_plotlyIcons.CloseIcon, null)
      ) : null;

      var foldHeader = !hideHeader && _react2.default.createElement(
        'div',
        { className: headerClass, onClick: toggleFold },
        _react2.default.createElement(
          'div',
          { className: 'fold__top__arrow-title' },
          arrowIcon,
          icon,
          _react2.default.createElement(
            'div',
            { className: 'fold__top__title' },
            (0, _lib.striptags)(name)
          )
        ),
        deleteButton
      );

      var foldContent = null;
      if (!folded) {
        if (this.foldVisible) {
          foldContent = _react2.default.createElement(
            'div',
            { className: contentClass },
            children
          );
        } else {
          foldContent = _react2.default.createElement(
            'div',
            { className: contentClass },
            _react2.default.createElement(_FoldEmpty2.default, { icon: Icon, messagePrimary: messageIfEmpty })
          );
        }
      }

      var classes = className ? ' ' + className : '';

      return _react2.default.createElement(
        'div',
        { className: 'fold' + classes },
        foldHeader,
        foldContent
      );
    }
  }]);

  return Fold;
}(_react.Component);

Fold.plotly_editor_traits = { foldable: true };

Fold.propTypes = {
  canDelete: _propTypes2.default.bool,
  children: _propTypes2.default.node,
  className: _propTypes2.default.string,
  folded: _propTypes2.default.bool,
  foldInfo: _propTypes2.default.object,
  toggleFold: _propTypes2.default.func,
  hideHeader: _propTypes2.default.bool,
  icon: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]),
  messageIfEmpty: _propTypes2.default.string,
  name: _propTypes2.default.string
};

Fold.contextTypes = {
  deleteContainer: _propTypes2.default.func
};

Fold.childContextTypes = {
  foldInfo: _propTypes2.default.object
};

var PlotlyFold = function (_Fold) {
  _inherits(PlotlyFold, _Fold);

  function PlotlyFold(props, context) {
    _classCallCheck(this, PlotlyFold);

    var _this2 = _possibleConstructorReturn(this, (PlotlyFold.__proto__ || Object.getPrototypeOf(PlotlyFold)).call(this, props, context));

    _this2.foldVisible = false;
    _this2.determineVisibility(props, context);
    return _this2;
  }

  _createClass(PlotlyFold, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps, nextContext) {
      this.determineVisibility(nextProps, nextContext);
    }
  }, {
    key: 'determineVisibility',
    value: function determineVisibility(nextProps, nextContext) {
      var _this3 = this;

      this.foldVisible = false;

      _react2.default.Children.forEach(nextProps.children, function (child) {
        if (!child || _this3.foldVisible) {
          return;
        }

        if (child.props.attr) {
          // attr components force fold open if they are visible
          var plotProps = (0, _lib.unpackPlotProps)(child.props, nextContext);
          if (child.type.modifyPlotProps) {
            child.type.modifyPlotProps(child.props, nextContext, plotProps);
          }

          _this3.foldVisible = _this3.foldVisible || plotProps.isVisible;
          return;
        }

        if (!(child.type.plotly_editor_traits || {}).no_visibility_forcing) {
          // non-attr components force visibility (unless they don't via traits)
          _this3.foldVisible = true;
          return;
        }
      });
    }
  }]);

  return PlotlyFold;
}(Fold);

PlotlyFold.plotly_editor_traits = {
  foldable: true
};

PlotlyFold.contextTypes = Object.assign({
  deleteContainer: _propTypes2.default.func
}, _lib.containerConnectedContextTypes);

exports.default = PlotlyFold;
//# sourceMappingURL=PlotlyFold.js.map

/***/ }),

/***/ "mQYA":
/*!****************************************************!*\
  !*** ./node_modules/ajv/lib/dotjs/_limitLength.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate__limitLength(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $op = $keyword == 'maxLength' ? '>' : '<';
  out += 'if ( ';
  if ($isData) {
    out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
  }
  if (it.opts.unicode === false) {
    out += ' ' + ($data) + '.length ';
  } else {
    out += ' ucs2length(' + ($data) + ') ';
  }
  out += ' ' + ($op) + ' ' + ($schemaValue) + ') { ';
  var $errorKeyword = $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should NOT be ';
      if ($keyword == 'maxLength') {
        out += 'longer';
      } else {
        out += 'shorter';
      }
      out += ' than ';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + ($schema);
      }
      out += ' characters\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}


/***/ }),

/***/ "mRg0":
/*!********************************************************!*\
  !*** ./node_modules/babel-runtime/helpers/inherits.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _setPrototypeOf = __webpack_require__(/*! ../core-js/object/set-prototype-of */ "s3Ml");

var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf);

var _create = __webpack_require__(/*! ../core-js/object/create */ "AyUB");

var _create2 = _interopRequireDefault(_create);

var _typeof2 = __webpack_require__(/*! ../helpers/typeof */ "EJiy");

var _typeof3 = _interopRequireDefault(_typeof2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = function (subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass)));
  }

  subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, {
    constructor: {
      value: subClass,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
  if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass;
};

/***/ }),

/***/ "mT+/":
/*!****************************************************************!*\
  !*** ./node_modules/@jupyterlab/extensionmanager/lib/model.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const services_1 = __webpack_require__(/*! @jupyterlab/services */ "S9up");
const semver = __importStar(__webpack_require__(/*! semver */ "jWEn"));
const build_helper_1 = __webpack_require__(/*! ./build-helper */ "ydF4");
const companions_1 = __webpack_require__(/*! ./companions */ "iaXi");
const dialog_1 = __webpack_require__(/*! ./dialog */ "Bx99");
const query_1 = __webpack_require__(/*! ./query */ "NW3o");
/**
 * The server API path for querying/modifying installed extensions.
 */
const EXTENSION_API_PATH = 'lab/api/extensions';
/**
 * Model for an extension list.
 */
class ListModel extends apputils_1.VDomModel {
    constructor(serviceManager) {
        super();
        /**
         * Contains an error message if an error occurred when querying installed extensions.
         */
        this.installedError = null;
        /**
         * Contains an error message if an error occurred when searching for extensions.
         */
        this.searchError = null;
        /**
         * Contains an error message if an error occurred when querying the server extension.
         */
        this.serverConnectionError = null;
        /**
         * Contains an error message if the server has unfulfilled requirements.
         */
        this.serverRequirementsError = null;
        /**
         * Whether the model has finished async initialization.
         */
        this.initialized = false;
        /**
         * Whether a fresh build should be considered due to actions taken.
         */
        this.promptBuild = false;
        /**
         * A helper for performing searches of jupyterlab extensions on the NPM repository.
         */
        this.searcher = new query_1.Searcher();
        this._query = null;
        this._page = 0;
        this._pagination = 250;
        this._totalEntries = 0;
        this._pendingActions = [];
        this._installed = [];
        this._searchResult = [];
        this.serviceManager = serviceManager;
        this.serverConnectionSettings = services_1.ServerConnection.makeSettings();
    }
    /**
     * A readonly array of the installed extensions.
     */
    get installed() {
        return this._installed;
    }
    /**
     * A readonly array containing the latest search result
     */
    get searchResult() {
        return this._searchResult;
    }
    /**
     * The current NPM repository search query.
     *
     * Setting its value triggers a new search.
     */
    get query() {
        return this._query;
    }
    set query(value) {
        this._query = value;
        this.update();
    }
    /**
     * The current NPM repository search page.
     *
     * The npm repository search is paginated by the `pagination` attribute.
     * The `page` value selects which page is used.
     *
     * Setting its value triggers a new search.
     */
    get page() {
        return this._page;
    }
    set page(value) {
        this._page = value;
        this.update();
    }
    /**
     * The NPM repository search pagination.
     *
     * The npm repository search is paginated by the `pagination` attribute.
     * The `page` value selects which page is used.
     *
     * Setting its value triggers a new search.
     */
    get pagination() {
        return this._pagination;
    }
    set pagination(value) {
        this._pagination = value;
        this.update();
    }
    /**
     * The total number of results in the current search.
     */
    get totalEntries() {
        return this._totalEntries;
    }
    /**
     * Initialize the model.
     */
    initialize() {
        this.update()
            .then(() => {
            this.initialized = true;
            this.stateChanged.emit(undefined);
        })
            .catch(() => {
            this.initialized = true;
            this.stateChanged.emit(undefined);
        });
    }
    /**
     * Whether there are currently any actions pending.
     */
    hasPendingActions() {
        return this._pendingActions.length > 0;
    }
    /**
     * Install an extension.
     *
     * @param entry An entry indicating which extension to install.
     */
    install(entry) {
        if (entry.installed) {
            // Updating
            return this._performAction('install', entry).then(data => {
                if (data.status !== 'ok') {
                    dialog_1.reportInstallError(entry.name, data.message);
                }
                this.update();
            });
        }
        this.checkCompanionPackages(entry).then(shouldInstall => {
            if (shouldInstall) {
                return this._performAction('install', entry).then(data => {
                    if (data.status !== 'ok') {
                        dialog_1.reportInstallError(entry.name, data.message);
                    }
                    this.update();
                });
            }
        });
    }
    /**
     * Uninstall an extension.
     *
     * @param entry An entry indicating which extension to uninstall.
     */
    uninstall(entry) {
        if (!entry.installed) {
            throw new Error(`Not installed, cannot uninstall: ${entry.name}`);
        }
        this._performAction('uninstall', entry).then(data => {
            this.update();
        });
    }
    /**
     * Enable an extension.
     *
     * @param entry An entry indicating which extension to enable.
     */
    enable(entry) {
        if (entry.enabled) {
            throw new Error(`Already enabled: ${entry.name}`);
        }
        this._performAction('enable', entry).then(data => {
            this.update();
        });
    }
    /**
     * Disable an extension.
     *
     * @param entry An entry indicating which extension to disable.
     */
    disable(entry) {
        if (!entry.enabled) {
            throw new Error(`Already disabled: ${entry.name}`);
        }
        this._performAction('disable', entry).then(data => {
            this.update();
        });
    }
    /**
     * Check for companion packages in kernels or server.
     *
     * @param entry An entry indicating which extension to check.
     */
    checkCompanionPackages(entry) {
        return this.searcher
            .fetchPackageData(entry.name, entry.latest_version)
            .then(data => {
            if (!data || !data.jupyterlab || !data.jupyterlab.discovery) {
                return true;
            }
            let discovery = data.jupyterlab.discovery;
            let kernelCompanions = [];
            if (discovery.kernel) {
                // match specs
                for (let kernelInfo of discovery.kernel) {
                    let matches = Private.matchSpecs(kernelInfo, this.serviceManager.specs);
                    kernelCompanions.push({ kernelInfo, kernels: matches });
                }
            }
            if (kernelCompanions.length < 1 && !discovery.server) {
                return true;
            }
            return companions_1.presentCompanions(kernelCompanions, discovery.server);
        });
    }
    /**
     * Trigger a build check to incorporate actions taken.
     */
    triggerBuildCheck() {
        let builder = this.serviceManager.builder;
        if (builder.isAvailable && !this.promptBuild) {
            const completed = builder.getStatus().then(response => {
                if (response.status === 'building') {
                    // Piggy-back onto existing build
                    // TODO: Can this cause dialog collision on build completion?
                    return build_helper_1.doBuild(builder);
                }
                if (response.status !== 'needed') {
                    return;
                }
                if (!this.promptBuild) {
                    this.promptBuild = true;
                    this.stateChanged.emit(undefined);
                }
            });
            this._addPendingAction(completed);
        }
    }
    /**
     * Perform a build on the server
     */
    performBuild() {
        if (this.promptBuild) {
            this.promptBuild = false;
            this.stateChanged.emit(undefined);
        }
        const completed = build_helper_1.doBuild(this.serviceManager.builder);
        this._addPendingAction(completed);
    }
    /**
     * Ignore a build recommendation
     */
    ignoreBuildRecommendation() {
        if (this.promptBuild) {
            this.promptBuild = false;
            this.stateChanged.emit(undefined);
        }
    }
    /**
     * Ignore a build recommendation
     */
    refreshInstalled() {
        const refresh = this.update(true);
        this._addPendingAction(refresh);
    }
    /**
     * Translate search results from an npm repository query into entries
     * and remove entries with 'deprecated' in the keyword list
     *
     * @param res Promise to an npm query result.
     */
    translateSearchResult(res) {
        return __awaiter(this, void 0, void 0, function* () {
            let entries = {};
            for (let obj of (yield res).objects) {
                let pkg = obj.package;
                if (pkg.keywords.indexOf('deprecated') >= 0) {
                    continue;
                }
                entries[pkg.name] = {
                    name: pkg.name,
                    description: pkg.description,
                    url: 'homepage' in pkg.links
                        ? pkg.links.homepage
                        : 'repository' in pkg.links
                            ? pkg.links.repository
                            : pkg.links.npm,
                    installed: false,
                    enabled: false,
                    status: null,
                    latest_version: pkg.version,
                    installed_version: ''
                };
            }
            return entries;
        });
    }
    /**
     * Translate installed extensions information from the server into entries.
     *
     * @param res Promise to the server reply data.
     */
    translateInstalled(res) {
        return __awaiter(this, void 0, void 0, function* () {
            const promises = [];
            const entries = {};
            for (let pkg of yield res) {
                promises.push(res.then(info => {
                    entries[pkg.name] = {
                        name: pkg.name,
                        description: pkg.description,
                        url: pkg.url,
                        installed: pkg.installed !== false,
                        enabled: pkg.enabled,
                        status: pkg.status,
                        latest_version: pkg.latest_version,
                        installed_version: pkg.installed_version
                    };
                }));
            }
            return Promise.all(promises).then(() => {
                return entries;
            });
        });
    }
    /**
     * Make a request to the server for info about its installed extensions.
     */
    fetchInstalled(refreshInstalled = false) {
        const url = new URL(EXTENSION_API_PATH, this.serverConnectionSettings.baseUrl);
        if (refreshInstalled) {
            url.searchParams.append('refresh', '1');
        }
        const request = services_1.ServerConnection.makeRequest(url.toString(), {}, this.serverConnectionSettings).then(response => {
            Private.handleError(response);
            return response.json();
        });
        request.then(() => {
            this.serverConnectionError = null;
        }, reason => {
            this.serverConnectionError = reason.toString();
        });
        return request;
    }
    /**
     * Search with current query.
     *
     * Sets searchError and totalEntries as appropriate.
     *
     * @returns {Promise<{ [key: string]: IEntry; }>} The search result as a map of entries.
     */
    performSearch() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.query === null) {
                this._searchResult = [];
                this._totalEntries = 0;
                this.searchError = null;
                return {};
            }
            // Start the search without waiting for it:
            let search = this.searcher.searchExtensions(this.query, this.page, this.pagination);
            let searchMapPromise = this.translateSearchResult(search);
            let searchMap;
            try {
                searchMap = yield searchMapPromise;
                this.searchError = null;
            }
            catch (reason) {
                searchMap = {};
                this.searchError = reason.toString();
            }
            try {
                this._totalEntries = (yield search).total;
            }
            catch (error) {
                this._totalEntries = 0;
            }
            return searchMap;
        });
    }
    /**
     * Query the installed extensions.
     *
     * Sets installedError as appropriate.
     *
     * @returns {Promise<{ [key: string]: IEntry; }>} A map of installed extensions.
     */
    queryInstalled(refreshInstalled) {
        return __awaiter(this, void 0, void 0, function* () {
            let installedMap;
            try {
                installedMap = yield this.translateInstalled(this.fetchInstalled(refreshInstalled));
                this.installedError = null;
            }
            catch (reason) {
                installedMap = {};
                this.installedError = reason.toString();
            }
            return installedMap;
        });
    }
    /**
     * Update the current model.
     *
     * This will query the NPM repository, and the notebook server.
     *
     * Emits the `stateChanged` signal on successful completion.
     */
    update(refreshInstalled = false) {
        return __awaiter(this, void 0, void 0, function* () {
            // Start both queries before awaiting:
            const searchMapPromise = this.performSearch();
            const installedMapPromise = this.queryInstalled(refreshInstalled);
            // Await results:
            const searchMap = yield searchMapPromise;
            const installedMap = yield installedMapPromise;
            // Map results to attributes:
            let installed = [];
            for (let key of Object.keys(installedMap)) {
                installed.push(installedMap[key]);
            }
            this._installed = installed.sort(Private.comparator);
            let searchResult = [];
            for (let key of Object.keys(searchMap)) {
                // Filter out installed entries from search results:
                if (installedMap[key] === undefined) {
                    searchResult.push(searchMap[key]);
                }
                else {
                    searchResult.push(installedMap[key]);
                }
            }
            this._searchResult = searchResult.sort(Private.comparator);
            // Signal updated state
            this.stateChanged.emit(undefined);
        });
    }
    /**
     * Send a request to the server to perform an action on an extension.
     *
     * @param action A valid action to perform.
     * @param entry The extension to perform the action on.
     */
    _performAction(action, entry) {
        const url = new URL(EXTENSION_API_PATH, this.serverConnectionSettings.baseUrl);
        let request = {
            method: 'POST',
            body: JSON.stringify({
                cmd: action,
                extension_name: entry.name
            })
        };
        const completed = services_1.ServerConnection.makeRequest(url.toString(), request, this.serverConnectionSettings).then(response => {
            Private.handleError(response);
            this.triggerBuildCheck();
            return response.json();
        });
        completed.then(() => {
            this.serverConnectionError = null;
        }, reason => {
            this.serverConnectionError = reason.toString();
        });
        this._addPendingAction(completed);
        return completed;
    }
    /**
     * Add a pending action.
     *
     * @param pending A promise that resolves when the action is completed.
     */
    _addPendingAction(pending) {
        // Add to pending actions collection
        this._pendingActions.push(pending);
        // Ensure action is removed when resolved
        const remove = () => {
            const i = this._pendingActions.indexOf(pending);
            this._pendingActions.splice(i, 1);
            this.stateChanged.emit(undefined);
        };
        pending.then(remove, remove);
        // Signal changed state
        this.stateChanged.emit(undefined);
    }
}
exports.ListModel = ListModel;
/**
 * ListModel statics.
 */
(function (ListModel) {
    /**
     * Utility function to check whether an entry can be updated.
     *
     * @param entry The entry to check.
     */
    function entryHasUpdate(entry) {
        if (!entry.installed || !entry.latest_version) {
            return false;
        }
        return semver.lt(entry.installed_version, entry.latest_version);
    }
    ListModel.entryHasUpdate = entryHasUpdate;
})(ListModel = exports.ListModel || (exports.ListModel = {}));
/**
 * A namespace for private functionality.
 */
var Private;
(function (Private) {
    /**
     * A comparator function that sorts whitelisted orgs to the top.
     */
    function comparator(a, b) {
        if (a.name === b.name) {
            return 0;
        }
        let testA = query_1.isJupyterOrg(a.name);
        let testB = query_1.isJupyterOrg(b.name);
        if (testA === testB) {
            return a.name.localeCompare(b.name);
        }
        else if (testA && !testB) {
            return -1;
        }
        else {
            return 1;
        }
    }
    Private.comparator = comparator;
    /**
     * Match kernel specs against kernel spec regexps
     *
     * @param kernelInfo The info containing the regexp patterns
     * @param specs The available kernel specs.
     */
    function matchSpecs(kernelInfo, specs) {
        if (!specs) {
            return [];
        }
        let matches = [];
        let reLang = null;
        let reName = null;
        if (kernelInfo.kernel_spec.language) {
            reLang = new RegExp(kernelInfo.kernel_spec.language);
        }
        if (kernelInfo.kernel_spec.display_name) {
            reName = new RegExp(kernelInfo.kernel_spec.display_name);
        }
        for (let key of Object.keys(specs.kernelspecs)) {
            let spec = specs.kernelspecs[key];
            let match = false;
            if (reLang) {
                match = reLang.test(spec.language);
            }
            if (!match && reName) {
                match = reName.test(spec.display_name);
            }
            if (match) {
                matches.push(spec);
                continue;
            }
        }
        return matches;
    }
    Private.matchSpecs = matchSpecs;
    /**
     * Convert a response to an exception on error.
     *
     * @param response The response to inspect.
     */
    function handleError(response) {
        if (!response.ok) {
            throw new Error(`${response.status} (${response.statusText})`);
        }
        return response;
    }
    Private.handleError = handleError;
})(Private || (Private = {}));


/***/ }),

/***/ "mTTR":
/*!***************************************!*\
  !*** ./node_modules/lodash/keysIn.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var arrayLikeKeys = __webpack_require__(/*! ./_arrayLikeKeys */ "b80T"),
    baseKeysIn = __webpack_require__(/*! ./_baseKeysIn */ "QcOe"),
    isArrayLike = __webpack_require__(/*! ./isArrayLike */ "MMmD");

/**
 * 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);
}

module.exports = keysIn;


/***/ }),

/***/ "mYFI":
/*!********************************************!*\
  !*** ./node_modules/mdi-react/FileIcon.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var FileIcon = function FileIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M13,9V3.5L18.5,9M6,2C4.89,2 4,2.89 4,4V20C4,21.1 4.9,22 6,22H18C19.1,22 20,21.1 20,20V8L14,2H6Z' })
  );
};

module.exports = FileIcon;


/***/ }),

/***/ "mYkm":
/*!****************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/docregistry/style/index.css ***!
  \****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.jp-MimeDocument {\n  outline: none;\n}\n", ""]);

// exports


/***/ }),

/***/ "makB":
/*!**************************************************************!*\
  !*** ./node_modules/xterm/lib/renderer/CursorRenderLayer.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Buffer_1 = __webpack_require__(/*! ../Buffer */ "MsZC");
var BaseRenderLayer_1 = __webpack_require__(/*! ./BaseRenderLayer */ "HHOg");
var BLINK_INTERVAL = 600;
var CursorRenderLayer = (function (_super) {
    __extends(CursorRenderLayer, _super);
    function CursorRenderLayer(container, zIndex, colors) {
        var _this = _super.call(this, container, 'cursor', zIndex, true, colors) || this;
        _this._state = {
            x: null,
            y: null,
            isFocused: null,
            style: null,
            width: null
        };
        _this._cursorRenderers = {
            'bar': _this._renderBarCursor.bind(_this),
            'block': _this._renderBlockCursor.bind(_this),
            'underline': _this._renderUnderlineCursor.bind(_this)
        };
        return _this;
    }
    CursorRenderLayer.prototype.resize = function (terminal, dim) {
        _super.prototype.resize.call(this, terminal, dim);
        this._state = {
            x: null,
            y: null,
            isFocused: null,
            style: null,
            width: null
        };
    };
    CursorRenderLayer.prototype.reset = function (terminal) {
        this._clearCursor();
        if (this._cursorBlinkStateManager) {
            this._cursorBlinkStateManager.dispose();
            this._cursorBlinkStateManager = null;
            this.onOptionsChanged(terminal);
        }
    };
    CursorRenderLayer.prototype.onBlur = function (terminal) {
        if (this._cursorBlinkStateManager) {
            this._cursorBlinkStateManager.pause();
        }
        terminal.refresh(terminal.buffer.y, terminal.buffer.y);
    };
    CursorRenderLayer.prototype.onFocus = function (terminal) {
        if (this._cursorBlinkStateManager) {
            this._cursorBlinkStateManager.resume(terminal);
        }
        else {
            terminal.refresh(terminal.buffer.y, terminal.buffer.y);
        }
    };
    CursorRenderLayer.prototype.onOptionsChanged = function (terminal) {
        var _this = this;
        if (terminal.options.cursorBlink) {
            if (!this._cursorBlinkStateManager) {
                this._cursorBlinkStateManager = new CursorBlinkStateManager(terminal, function () {
                    _this._render(terminal, true);
                });
            }
        }
        else {
            if (this._cursorBlinkStateManager) {
                this._cursorBlinkStateManager.dispose();
                this._cursorBlinkStateManager = null;
            }
            terminal.refresh(terminal.buffer.y, terminal.buffer.y);
        }
    };
    CursorRenderLayer.prototype.onCursorMove = function (terminal) {
        if (this._cursorBlinkStateManager) {
            this._cursorBlinkStateManager.restartBlinkAnimation(terminal);
        }
    };
    CursorRenderLayer.prototype.onGridChanged = function (terminal, startRow, endRow) {
        if (!this._cursorBlinkStateManager || this._cursorBlinkStateManager.isPaused) {
            this._render(terminal, false);
        }
        else {
            this._cursorBlinkStateManager.restartBlinkAnimation(terminal);
        }
    };
    CursorRenderLayer.prototype._render = function (terminal, triggeredByAnimationFrame) {
        if (!terminal.cursorState || terminal.cursorHidden) {
            this._clearCursor();
            return;
        }
        var cursorY = terminal.buffer.ybase + terminal.buffer.y;
        var viewportRelativeCursorY = cursorY - terminal.buffer.ydisp;
        if (viewportRelativeCursorY < 0 || viewportRelativeCursorY >= terminal.rows) {
            this._clearCursor();
            return;
        }
        var charData = terminal.buffer.lines.get(cursorY)[terminal.buffer.x];
        if (!charData) {
            return;
        }
        if (!terminal.isFocused) {
            this._clearCursor();
            this._ctx.save();
            this._ctx.fillStyle = this._colors.cursor.css;
            this._renderBlurCursor(terminal, terminal.buffer.x, viewportRelativeCursorY, charData);
            this._ctx.restore();
            this._state.x = terminal.buffer.x;
            this._state.y = viewportRelativeCursorY;
            this._state.isFocused = false;
            this._state.style = terminal.options.cursorStyle;
            this._state.width = charData[Buffer_1.CHAR_DATA_WIDTH_INDEX];
            return;
        }
        if (this._cursorBlinkStateManager && !this._cursorBlinkStateManager.isCursorVisible) {
            this._clearCursor();
            return;
        }
        if (this._state) {
            if (this._state.x === terminal.buffer.x &&
                this._state.y === viewportRelativeCursorY &&
                this._state.isFocused === terminal.isFocused &&
                this._state.style === terminal.options.cursorStyle &&
                this._state.width === charData[Buffer_1.CHAR_DATA_WIDTH_INDEX]) {
                return;
            }
            this._clearCursor();
        }
        this._ctx.save();
        this._cursorRenderers[terminal.options.cursorStyle || 'block'](terminal, terminal.buffer.x, viewportRelativeCursorY, charData);
        this._ctx.restore();
        this._state.x = terminal.buffer.x;
        this._state.y = viewportRelativeCursorY;
        this._state.isFocused = false;
        this._state.style = terminal.options.cursorStyle;
        this._state.width = charData[Buffer_1.CHAR_DATA_WIDTH_INDEX];
    };
    CursorRenderLayer.prototype._clearCursor = function () {
        if (this._state) {
            this.clearCells(this._state.x, this._state.y, this._state.width, 1);
            this._state = {
                x: null,
                y: null,
                isFocused: null,
                style: null,
                width: null
            };
        }
    };
    CursorRenderLayer.prototype._renderBarCursor = function (terminal, x, y, charData) {
        this._ctx.save();
        this._ctx.fillStyle = this._colors.cursor.css;
        this.fillLeftLineAtCell(x, y);
        this._ctx.restore();
    };
    CursorRenderLayer.prototype._renderBlockCursor = function (terminal, x, y, charData) {
        this._ctx.save();
        this._ctx.fillStyle = this._colors.cursor.css;
        this.fillCells(x, y, charData[Buffer_1.CHAR_DATA_WIDTH_INDEX], 1);
        this._ctx.fillStyle = this._colors.cursorAccent.css;
        this.fillCharTrueColor(terminal, charData, x, y);
        this._ctx.restore();
    };
    CursorRenderLayer.prototype._renderUnderlineCursor = function (terminal, x, y, charData) {
        this._ctx.save();
        this._ctx.fillStyle = this._colors.cursor.css;
        this.fillBottomLineAtCells(x, y);
        this._ctx.restore();
    };
    CursorRenderLayer.prototype._renderBlurCursor = function (terminal, x, y, charData) {
        this._ctx.save();
        this._ctx.strokeStyle = this._colors.cursor.css;
        this.strokeRectAtCell(x, y, charData[Buffer_1.CHAR_DATA_WIDTH_INDEX], 1);
        this._ctx.restore();
    };
    return CursorRenderLayer;
}(BaseRenderLayer_1.BaseRenderLayer));
exports.CursorRenderLayer = CursorRenderLayer;
var CursorBlinkStateManager = (function () {
    function CursorBlinkStateManager(terminal, _renderCallback) {
        this._renderCallback = _renderCallback;
        this.isCursorVisible = true;
        if (terminal.isFocused) {
            this._restartInterval();
        }
    }
    Object.defineProperty(CursorBlinkStateManager.prototype, "isPaused", {
        get: function () { return !(this._blinkStartTimeout || this._blinkInterval); },
        enumerable: true,
        configurable: true
    });
    CursorBlinkStateManager.prototype.dispose = function () {
        if (this._blinkInterval) {
            window.clearInterval(this._blinkInterval);
            this._blinkInterval = null;
        }
        if (this._blinkStartTimeout) {
            window.clearTimeout(this._blinkStartTimeout);
            this._blinkStartTimeout = null;
        }
        if (this._animationFrame) {
            window.cancelAnimationFrame(this._animationFrame);
            this._animationFrame = null;
        }
    };
    CursorBlinkStateManager.prototype.restartBlinkAnimation = function (terminal) {
        var _this = this;
        if (this.isPaused) {
            return;
        }
        this._animationTimeRestarted = Date.now();
        this.isCursorVisible = true;
        if (!this._animationFrame) {
            this._animationFrame = window.requestAnimationFrame(function () {
                _this._renderCallback();
                _this._animationFrame = null;
            });
        }
    };
    CursorBlinkStateManager.prototype._restartInterval = function (timeToStart) {
        var _this = this;
        if (timeToStart === void 0) { timeToStart = BLINK_INTERVAL; }
        if (this._blinkInterval) {
            window.clearInterval(this._blinkInterval);
        }
        this._blinkStartTimeout = setTimeout(function () {
            if (_this._animationTimeRestarted) {
                var time = BLINK_INTERVAL - (Date.now() - _this._animationTimeRestarted);
                _this._animationTimeRestarted = null;
                if (time > 0) {
                    _this._restartInterval(time);
                    return;
                }
            }
            _this.isCursorVisible = false;
            _this._animationFrame = window.requestAnimationFrame(function () {
                _this._renderCallback();
                _this._animationFrame = null;
            });
            _this._blinkInterval = setInterval(function () {
                if (_this._animationTimeRestarted) {
                    var time = BLINK_INTERVAL - (Date.now() - _this._animationTimeRestarted);
                    _this._animationTimeRestarted = null;
                    _this._restartInterval(time);
                    return;
                }
                _this.isCursorVisible = !_this.isCursorVisible;
                _this._animationFrame = window.requestAnimationFrame(function () {
                    _this._renderCallback();
                    _this._animationFrame = null;
                });
            }, BLINK_INTERVAL);
        }, timeToStart);
    };
    CursorBlinkStateManager.prototype.pause = function () {
        this.isCursorVisible = true;
        if (this._blinkInterval) {
            window.clearInterval(this._blinkInterval);
            this._blinkInterval = null;
        }
        if (this._blinkStartTimeout) {
            window.clearTimeout(this._blinkStartTimeout);
            this._blinkStartTimeout = null;
        }
        if (this._animationFrame) {
            window.cancelAnimationFrame(this._animationFrame);
            this._animationFrame = null;
        }
    };
    CursorBlinkStateManager.prototype.resume = function (terminal) {
        this._animationTimeRestarted = null;
        this._restartInterval();
        this.restartBlinkAnimation(terminal);
    };
    return CursorBlinkStateManager;
}());

//# sourceMappingURL=CursorRenderLayer.js.map


/***/ }),

/***/ "mc0g":
/*!***********************************************!*\
  !*** ./node_modules/lodash/_createBaseFor.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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;
  };
}

module.exports = createBaseFor;


/***/ }),

/***/ "mdPL":
/*!******************************************!*\
  !*** ./node_modules/lodash/_nodeUtil.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(/*! ./_freeGlobal */ "WFqU");

/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;

/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == '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) {}
}());

module.exports = nodeUtil;

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/module.js */ "YuTi")(module)))

/***/ }),

/***/ "mfZb":
/*!*****************************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/plots/layout_attributes.js ***!
  \*****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var fontAttrs = __webpack_require__(/*! ./font_attributes */ "9HwK");
var animationAttrs = __webpack_require__(/*! ./animation_attributes */ "TEEm");
var colorAttrs = __webpack_require__(/*! ../components/color/attributes */ "r6nK");
var colorscaleAttrs = __webpack_require__(/*! ../components/colorscale/layout_attributes */ "PL31");
var padAttrs = __webpack_require__(/*! ./pad_attributes */ "YJZ8");
var extendFlat = __webpack_require__(/*! ../lib/extend */ "dnr1").extendFlat;

var globalFont = fontAttrs({
    editType: 'calc',
    description: [
        'Sets the global font.',
        'Note that fonts used in traces and other',
        'layout components inherit from the global font.'
    ].join(' ')
});
globalFont.family.dflt = '"Open Sans", verdana, arial, sans-serif';
globalFont.size.dflt = 12;
globalFont.color.dflt = colorAttrs.defaultLine;

module.exports = {
    font: globalFont,
    title: {
        text: {
            valType: 'string',
            role: 'info',
            editType: 'layoutstyle',
            description: [
                'Sets the plot\'s title.',
                'Note that before the existence of `title.text`, the title\'s',
                'contents used to be defined as the `title` attribute itself.',
                'This behavior has been deprecated.'
            ].join(' ')
        },
        font: fontAttrs({
            editType: 'layoutstyle',
            description: [
                'Sets the title font.',
                'Note that the title\'s font used to be customized',
                'by the now deprecated `titlefont` attribute.'
            ].join(' ')
        }),
        xref: {
            valType: 'enumerated',
            dflt: 'container',
            values: ['container', 'paper'],
            role: 'info',
            editType: 'layoutstyle',
            description: [
                'Sets the container `x` refers to.',
                '*container* spans the entire `width` of the plot.',
                '*paper* refers to the width of the plotting area only.'
            ].join(' ')
        },
        yref: {
            valType: 'enumerated',
            dflt: 'container',
            values: ['container', 'paper'],
            role: 'info',
            editType: 'layoutstyle',
            description: [
                'Sets the container `y` refers to.',
                '*container* spans the entire `height` of the plot.',
                '*paper* refers to the height of the plotting area only.'
            ].join(' ')
        },
        x: {
            valType: 'number',
            min: 0,
            max: 1,
            dflt: 0.5,
            role: 'style',
            editType: 'layoutstyle',
            description: [
                'Sets the x position with respect to `xref` in normalized',
                'coordinates from *0* (left) to *1* (right).'
            ].join(' ')
        },
        y: {
            valType: 'number',
            min: 0,
            max: 1,
            dflt: 'auto',
            role: 'style',
            editType: 'layoutstyle',
            description: [
                'Sets the y position with respect to `yref` in normalized',
                'coordinates from *0* (bottom) to *1* (top).',
                '*auto* places the baseline of the title onto the',
                'vertical center of the top margin.'
            ].join(' ')
        },
        xanchor: {
            valType: 'enumerated',
            dflt: 'auto',
            values: ['auto', 'left', 'center', 'right'],
            role: 'info',
            editType: 'layoutstyle',
            description: [
                'Sets the title\'s horizontal alignment with respect to its x position.',
                '*left* means that the title starts at x,',
                '*right* means that the title ends at x',
                'and *center* means that the title\'s center is at x.',
                '*auto* divides `xref` by three and calculates the `xanchor`',
                'value automatically based on the value of `x`.'
            ].join(' ')
        },
        yanchor: {
            valType: 'enumerated',
            dflt: 'auto',
            values: ['auto', 'top', 'middle', 'bottom'],
            role: 'info',
            editType: 'layoutstyle',
            description: [
                'Sets the title\'s vertical alignment with respect to its y position.',
                '*top* means that the title\'s cap line is at y,',
                '*bottom* means that the title\'s baseline is at y',
                'and *middle* means that the title\'s midline is at y.',
                '*auto* divides `yref` by three and calculates the `yanchor`',
                'value automatically based on the value of `y`.'
            ].join(' ')
        },
        pad: extendFlat(padAttrs({editType: 'layoutstyle'}), {
            description: [
                'Sets the padding of the title.',
                'Each padding value only applies when the corresponding',
                '`xanchor`/`yanchor` value is set accordingly. E.g. for left',
                'padding to take effect, `xanchor` must be set to *left*.',
                'The same rule applies if `xanchor`/`yanchor` is determined automatically.',
                'Padding is muted if the respective anchor value is *middle*/*center*.'
            ].join(' ')
        }),
        editType: 'layoutstyle'
    },
    autosize: {
        valType: 'boolean',
        role: 'info',
        dflt: false,
        // autosize, width, and height get special editType treatment in _relayout
        // so we can handle noop resizes more efficiently
        editType: 'none',
        description: [
            'Determines whether or not a layout width or height',
            'that has been left undefined by the user',
            'is initialized on each relayout.',

            'Note that, regardless of this attribute,',
            'an undefined layout width or height',
            'is always initialized on the first call to plot.'
        ].join(' ')
    },
    width: {
        valType: 'number',
        role: 'info',
        min: 10,
        dflt: 700,
        editType: 'plot',
        description: [
            'Sets the plot\'s width (in px).'
        ].join(' ')
    },
    height: {
        valType: 'number',
        role: 'info',
        min: 10,
        dflt: 450,
        editType: 'plot',
        description: [
            'Sets the plot\'s height (in px).'
        ].join(' ')
    },
    margin: {
        l: {
            valType: 'number',
            role: 'info',
            min: 0,
            dflt: 80,
            editType: 'plot',
            description: 'Sets the left margin (in px).'
        },
        r: {
            valType: 'number',
            role: 'info',
            min: 0,
            dflt: 80,
            editType: 'plot',
            description: 'Sets the right margin (in px).'
        },
        t: {
            valType: 'number',
            role: 'info',
            min: 0,
            dflt: 100,
            editType: 'plot',
            description: 'Sets the top margin (in px).'
        },
        b: {
            valType: 'number',
            role: 'info',
            min: 0,
            dflt: 80,
            editType: 'plot',
            description: 'Sets the bottom margin (in px).'
        },
        pad: {
            valType: 'number',
            role: 'info',
            min: 0,
            dflt: 0,
            editType: 'plot',
            description: [
                'Sets the amount of padding (in px)',
                'between the plotting area and the axis lines'
            ].join(' ')
        },
        autoexpand: {
            valType: 'boolean',
            role: 'info',
            dflt: true,
            editType: 'plot'
        },
        editType: 'plot'
    },
    paper_bgcolor: {
        valType: 'color',
        role: 'style',
        dflt: colorAttrs.background,
        editType: 'plot',
        description: 'Sets the color of paper where the graph is drawn.'
    },
    plot_bgcolor: {
        // defined here, but set in cartesian.supplyLayoutDefaults
        // because it needs to know if there are (2D) axes or not
        valType: 'color',
        role: 'style',
        dflt: colorAttrs.background,
        editType: 'layoutstyle',
        description: [
            'Sets the color of plotting area in-between x and y axes.'
        ].join(' ')
    },
    separators: {
        valType: 'string',
        role: 'style',
        editType: 'plot',
        description: [
            'Sets the decimal and thousand separators.',
            'For example, *. * puts a \'.\' before decimals and a space',
            'between thousands. In English locales, dflt is *.,* but',
            'other locales may alter this default.'
        ].join(' ')
    },
    hidesources: {
        valType: 'boolean',
        role: 'info',
        dflt: false,
        editType: 'plot',
        description: [
            'Determines whether or not a text link citing the data source is',
            'placed at the bottom-right cored of the figure.',
            'Has only an effect only on graphs that have been generated via',
            'forked graphs from the plotly service (at https://plot.ly or on-premise).'
        ].join(' ')
    },
    showlegend: {
        // handled in legend.supplyLayoutDefaults
        // but included here because it's not in the legend object
        valType: 'boolean',
        role: 'info',
        editType: 'legend',
        description: [
            'Determines whether or not a legend is drawn.',
            'Default is `true` if there is a trace to show and any of these:',
            'a) Two or more traces would by default be shown in the legend.',
            'b) One pie trace is shown in the legend.',
            'c) One trace is explicitly given with `showlegend: true`.'
        ].join(' ')
    },
    colorway: {
        valType: 'colorlist',
        dflt: colorAttrs.defaults,
        role: 'style',
        editType: 'calc',
        description: 'Sets the default trace colors.'
    },
    colorscale: colorscaleAttrs,
    datarevision: {
        valType: 'any',
        role: 'info',
        editType: 'calc',
        description: [
            'If provided, a changed value tells `Plotly.react` that',
            'one or more data arrays has changed. This way you can modify',
            'arrays in-place rather than making a complete new copy for an',
            'incremental change.',
            'If NOT provided, `Plotly.react` assumes that data arrays are',
            'being treated as immutable, thus any data array with a',
            'different identity from its predecessor contains new data.'
        ].join(' ')
    },
    uirevision: {
        valType: 'any',
        role: 'info',
        editType: 'none',
        description: [
            'Used to allow user interactions with the plot to persist after',
            '`Plotly.react` calls that are unaware of these interactions.',
            'If `uirevision` is omitted, or if it is given and it changed from',
            'the previous `Plotly.react` call, the exact new figure is used.',
            'If `uirevision` is truthy and did NOT change, any attribute',
            'that has been affected by user interactions and did not receive a',
            'different value in the new figure will keep the interaction value.',
            '`layout.uirevision` attribute serves as the default for',
            '`uirevision` attributes in various sub-containers. For finer',
            'control you can set these sub-attributes directly. For example,',
            'if your app separately controls the data on the x and y axes you',
            'might set `xaxis.uirevision=*time*` and `yaxis.uirevision=*cost*`.',
            'Then if only the y data is changed, you can update',
            '`yaxis.uirevision=*quantity*` and the y axis range will reset but',
            'the x axis range will retain any user-driven zoom.'
        ].join(' ')
    },
    editrevision: {
        valType: 'any',
        role: 'info',
        editType: 'none',
        description: [
            'Controls persistence of user-driven changes in `editable: true`',
            'configuration, other than trace names and axis titles.',
            'Defaults to `layout.uirevision`.'
        ].join(' ')
    },
    selectionrevision: {
        valType: 'any',
        role: 'info',
        editType: 'none',
        description: [
            'Controls persistence of user-driven changes in selected points',
            'from all traces.'
        ].join(' ')
    },
    template: {
        valType: 'any',
        role: 'info',
        editType: 'calc',
        description: [
            'Default attributes to be applied to the plot. Templates can be',
            'created from existing plots using `Plotly.makeTemplate`, or',
            'created manually. They should be objects with format:',
            '`{layout: layoutTemplate, data: {[type]: [traceTemplate, ...]}, ...}`',
            '`layoutTemplate` and `traceTemplate` are objects matching the',
            'attribute structure of `layout` and a data trace. ',
            'Trace templates are applied cyclically to traces of each type.',
            'Container arrays (eg `annotations`) have special handling:',
            'An object ending in `defaults` (eg `annotationdefaults`) is applied',
            'to each array item. But if an item has a `templateitemname` key',
            'we look in the template array for an item with matching `name` and',
            'apply that instead. If no matching `name` is found we mark the item',
            'invisible. Any named template item not referenced is appended to',
            'the end of the array, so you can use this for a watermark annotation',
            'or a logo image, for example. To omit one of these items on the plot,',
            'make an item with matching `templateitemname` and `visible: false`.'
        ].join(' ')
    },
    modebar: {
        orientation: {
            valType: 'enumerated',
            values: ['v', 'h'],
            dflt: 'h',
            role: 'info',
            editType: 'modebar',
            description: 'Sets the orientation of the modebar.'
        },
        bgcolor: {
            valType: 'color',
            role: 'style',
            editType: 'modebar',
            description: 'Sets the background color of the modebar.'
        },
        color: {
            valType: 'color',
            role: 'style',
            editType: 'modebar',
            description: 'Sets the color of the icons in the modebar.'
        },
        activecolor: {
            valType: 'color',
            role: 'style',
            editType: 'modebar',
            description: 'Sets the color of the active or hovered on icons in the modebar.'
        },
        uirevision: {
            valType: 'any',
            role: 'info',
            editType: 'none',
            description: [
                'Controls persistence of user-driven changes related to the modebar,',
                'including `hovermode`, `dragmode`, and `showspikes` at both the',
                'root level and inside subplots. Defaults to `layout.uirevision`.'
            ].join(' ')
        },
        editType: 'modebar'
    },

    meta: {
        valType: 'data_array',
        editType: 'plot',
        description: [
            'Assigns extra meta information that can be used in various `text` attributes.',
            'Attributes such as the graph, axis and colorbar `title.text`, annotation `text`',
            '`trace.name` in legend items, `rangeselector`, `updatemenues` and `sliders` `label` text',
            'all support `meta`. One can access `meta` fields using template strings:',
            '`%{meta[i]}` where `i` is the index of the `meta`',
            'item in question.'
        ].join(' ')
    },

    transition: extendFlat({}, animationAttrs.transition, {
        description: [
            'Sets transition options used during Plotly.react updates.'
        ].join(' '),
        editType: 'none'
    }),

    _deprecated: {
        title: {
            valType: 'string',
            role: 'info',
            editType: 'layoutstyle',
            description: [
                'Value of `title` is no longer a simple *string* but a set of sub-attributes.',
                'To set the contents of the title, please use `title.text` now.'
            ].join(' ')
        },
        titlefont: fontAttrs({
            editType: 'layoutstyle',
            description: [
                'Former `titlefont` is now the sub-attribute `font` of `title`.',
                'To customize title font properties, please use `title.font` now.'
            ].join(' ')
        })
    }
};


/***/ }),

/***/ "mfmY":
/*!***********************************************!*\
  !*** ./node_modules/lodash.isstring/index.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * lodash 4.0.1 (Custom Build) <https://lodash.com/>
 * Build: `lodash modularize exports="npm" -o ./`
 * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <https://lodash.com/license>
 */

/** `Object#toString` result references. */
var stringTag = '[object String]';

/** Used for built-in method references. */
var objectProto = Object.prototype;

/**
 * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
 * of values.
 */
var objectToString = objectProto.toString;

/**
 * Checks if `value` is classified as an `Array` object.
 *
 * @static
 * @memberOf _
 * @type Function
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is correctly classified, 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 object-like. A value is object-like if it's not `null`
 * and has a `typeof` result of "object".
 *
 * @static
 * @memberOf _
 * @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 && typeof value == 'object';
}

/**
 * Checks if `value` is classified as a `String` primitive or object.
 *
 * @static
 * @memberOf _
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
 * @example
 *
 * _.isString('abc');
 * // => true
 *
 * _.isString(1);
 * // => false
 */
function isString(value) {
  return typeof value == 'string' ||
    (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag);
}

module.exports = isString;


/***/ }),

/***/ "mfsF":
/*!*****************************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/text_editors/RichText/StyleButton.js ***!
  \*****************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _classnames = __webpack_require__(/*! classnames */ "TSYQ");

var _classnames2 = _interopRequireDefault(_classnames);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var StyleButton = function (_Component) {
  _inherits(StyleButton, _Component);

  function StyleButton(props) {
    _classCallCheck(this, StyleButton);

    var _this = _possibleConstructorReturn(this, (StyleButton.__proto__ || Object.getPrototypeOf(StyleButton)).call(this, props));

    _this.onToggle = _this.onToggle.bind(_this);
    return _this;
  }

  _createClass(StyleButton, [{
    key: 'onToggle',
    value: function onToggle(ev) {
      // Prevent focus moving from editor to button
      ev.preventDefault();
      this.props.onToggle(this.props.value);
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          active = _props.active,
          label = _props.label,
          value = _props.value;


      var className = (0, _classnames2.default)('rich-text-editor__styleButton', 'rich-text-editor__styleButton__' + value, {
        'rich-text-editor__styleButton--active': active
      });

      return _react2.default.createElement(
        'span',
        { className: 'rich-text-editor__styleButton__wrapper' },
        _react2.default.createElement(
          'span',
          {
            className: className,
            onMouseDown: this.onToggle,
            'data-role': 'button',
            'data-pressed': active
          },
          label
        )
      );
    }
  }]);

  return StyleButton;
}(_react.Component);

StyleButton.propTypes = {
  active: _propTypes2.default.bool,

  // A (styled) React element to display as label
  label: _propTypes2.default.element.isRequired,

  // Callback for clicks
  onToggle: _propTypes2.default.func.isRequired,

  // The value passed to `onToggle` when clicked
  value: _propTypes2.default.string.isRequired
};

exports.default = StyleButton;
//# sourceMappingURL=StyleButton.js.map

/***/ }),

/***/ "mg2g":
/*!**************************************************************!*\
  !*** ./node_modules/@jupyterlab/imageviewer/style/index.css ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "MnKG");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "mjHj":
/*!*******************************************************!*\
  !*** ./node_modules/fbjs/lib/UnicodeBidiDirection.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks
 * 
 */

/**
 * Constants to represent text directionality
 *
 * Also defines a *global* direciton, to be used in bidi algorithms as a
 * default fallback direciton, when no better direction is found or provided.
 *
 * NOTE: Use `setGlobalDir()`, or update `initGlobalDir()`, to set the initial
 *       global direction value based on the application.
 *
 * Part of the implementation of Unicode Bidirectional Algorithm (UBA)
 * Unicode Standard Annex #9 (UAX9)
 * http://www.unicode.org/reports/tr9/
 */



var invariant = __webpack_require__(/*! ./invariant */ "2NuI");

var NEUTRAL = 'NEUTRAL'; // No strong direction
var LTR = 'LTR'; // Left-to-Right direction
var RTL = 'RTL'; // Right-to-Left direction

var globalDir = null;

// == Helpers ==

/**
 * Check if a directionality value is a Strong one
 */
function isStrong(dir) {
  return dir === LTR || dir === RTL;
}

/**
 * Get string value to be used for `dir` HTML attribute or `direction` CSS
 * property.
 */
function getHTMLDir(dir) {
  !isStrong(dir) ?  true ? invariant(false, '`dir` must be a strong direction to be converted to HTML Direction') : undefined : void 0;
  return dir === LTR ? 'ltr' : 'rtl';
}

/**
 * Get string value to be used for `dir` HTML attribute or `direction` CSS
 * property, but returns null if `dir` has same value as `otherDir`.
 * `null`.
 */
function getHTMLDirIfDifferent(dir, otherDir) {
  !isStrong(dir) ?  true ? invariant(false, '`dir` must be a strong direction to be converted to HTML Direction') : undefined : void 0;
  !isStrong(otherDir) ?  true ? invariant(false, '`otherDir` must be a strong direction to be converted to HTML Direction') : undefined : void 0;
  return dir === otherDir ? null : getHTMLDir(dir);
}

// == Global Direction ==

/**
 * Set the global direction.
 */
function setGlobalDir(dir) {
  globalDir = dir;
}

/**
 * Initialize the global direction
 */
function initGlobalDir() {
  setGlobalDir(LTR);
}

/**
 * Get the global direction
 */
function getGlobalDir() {
  if (!globalDir) {
    this.initGlobalDir();
  }
  !globalDir ?  true ? invariant(false, 'Global direction not set.') : undefined : void 0;
  return globalDir;
}

var UnicodeBidiDirection = {
  // Values
  NEUTRAL: NEUTRAL,
  LTR: LTR,
  RTL: RTL,
  // Helpers
  isStrong: isStrong,
  getHTMLDir: getHTMLDir,
  getHTMLDirIfDifferent: getHTMLDirIfDifferent,
  // Global Direction
  setGlobalDir: setGlobalDir,
  initGlobalDir: initGlobalDir,
  getGlobalDir: getGlobalDir
};

module.exports = UnicodeBidiDirection;

/***/ }),

/***/ "mki7":
/*!***************************************************!*\
  !*** ./node_modules/codemirror/keymap/sublime.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

// A rough approximation of Sublime Text's keybindings
// Depends on addon/search/searchcursor.js and optionally addon/dialog/dialogs.js

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../lib/codemirror */ "VrN/"), __webpack_require__(/*! ../addon/search/searchcursor */ "uTOq"), __webpack_require__(/*! ../addon/edit/matchbrackets */ "jDMi"));
  else {}
})(function(CodeMirror) {
  "use strict";

  var cmds = CodeMirror.commands;
  var Pos = CodeMirror.Pos;

  // This is not exactly Sublime's algorithm. I couldn't make heads or tails of that.
  function findPosSubword(doc, start, dir) {
    if (dir < 0 && start.ch == 0) return doc.clipPos(Pos(start.line - 1));
    var line = doc.getLine(start.line);
    if (dir > 0 && start.ch >= line.length) return doc.clipPos(Pos(start.line + 1, 0));
    var state = "start", type;
    for (var pos = start.ch, e = dir < 0 ? 0 : line.length, i = 0; pos != e; pos += dir, i++) {
      var next = line.charAt(dir < 0 ? pos - 1 : pos);
      var cat = next != "_" && CodeMirror.isWordChar(next) ? "w" : "o";
      if (cat == "w" && next.toUpperCase() == next) cat = "W";
      if (state == "start") {
        if (cat != "o") { state = "in"; type = cat; }
      } else if (state == "in") {
        if (type != cat) {
          if (type == "w" && cat == "W" && dir < 0) pos--;
          if (type == "W" && cat == "w" && dir > 0) { type = "w"; continue; }
          break;
        }
      }
    }
    return Pos(start.line, pos);
  }

  function moveSubword(cm, dir) {
    cm.extendSelectionsBy(function(range) {
      if (cm.display.shift || cm.doc.extend || range.empty())
        return findPosSubword(cm.doc, range.head, dir);
      else
        return dir < 0 ? range.from() : range.to();
    });
  }

  cmds.goSubwordLeft = function(cm) { moveSubword(cm, -1); };
  cmds.goSubwordRight = function(cm) { moveSubword(cm, 1); };

  cmds.scrollLineUp = function(cm) {
    var info = cm.getScrollInfo();
    if (!cm.somethingSelected()) {
      var visibleBottomLine = cm.lineAtHeight(info.top + info.clientHeight, "local");
      if (cm.getCursor().line >= visibleBottomLine)
        cm.execCommand("goLineUp");
    }
    cm.scrollTo(null, info.top - cm.defaultTextHeight());
  };
  cmds.scrollLineDown = function(cm) {
    var info = cm.getScrollInfo();
    if (!cm.somethingSelected()) {
      var visibleTopLine = cm.lineAtHeight(info.top, "local")+1;
      if (cm.getCursor().line <= visibleTopLine)
        cm.execCommand("goLineDown");
    }
    cm.scrollTo(null, info.top + cm.defaultTextHeight());
  };

  cmds.splitSelectionByLine = function(cm) {
    var ranges = cm.listSelections(), lineRanges = [];
    for (var i = 0; i < ranges.length; i++) {
      var from = ranges[i].from(), to = ranges[i].to();
      for (var line = from.line; line <= to.line; ++line)
        if (!(to.line > from.line && line == to.line && to.ch == 0))
          lineRanges.push({anchor: line == from.line ? from : Pos(line, 0),
                           head: line == to.line ? to : Pos(line)});
    }
    cm.setSelections(lineRanges, 0);
  };

  cmds.singleSelectionTop = function(cm) {
    var range = cm.listSelections()[0];
    cm.setSelection(range.anchor, range.head, {scroll: false});
  };

  cmds.selectLine = function(cm) {
    var ranges = cm.listSelections(), extended = [];
    for (var i = 0; i < ranges.length; i++) {
      var range = ranges[i];
      extended.push({anchor: Pos(range.from().line, 0),
                     head: Pos(range.to().line + 1, 0)});
    }
    cm.setSelections(extended);
  };

  function insertLine(cm, above) {
    if (cm.isReadOnly()) return CodeMirror.Pass
    cm.operation(function() {
      var len = cm.listSelections().length, newSelection = [], last = -1;
      for (var i = 0; i < len; i++) {
        var head = cm.listSelections()[i].head;
        if (head.line <= last) continue;
        var at = Pos(head.line + (above ? 0 : 1), 0);
        cm.replaceRange("\n", at, null, "+insertLine");
        cm.indentLine(at.line, null, true);
        newSelection.push({head: at, anchor: at});
        last = head.line + 1;
      }
      cm.setSelections(newSelection);
    });
    cm.execCommand("indentAuto");
  }

  cmds.insertLineAfter = function(cm) { return insertLine(cm, false); };

  cmds.insertLineBefore = function(cm) { return insertLine(cm, true); };

  function wordAt(cm, pos) {
    var start = pos.ch, end = start, line = cm.getLine(pos.line);
    while (start && CodeMirror.isWordChar(line.charAt(start - 1))) --start;
    while (end < line.length && CodeMirror.isWordChar(line.charAt(end))) ++end;
    return {from: Pos(pos.line, start), to: Pos(pos.line, end), word: line.slice(start, end)};
  }

  cmds.selectNextOccurrence = function(cm) {
    var from = cm.getCursor("from"), to = cm.getCursor("to");
    var fullWord = cm.state.sublimeFindFullWord == cm.doc.sel;
    if (CodeMirror.cmpPos(from, to) == 0) {
      var word = wordAt(cm, from);
      if (!word.word) return;
      cm.setSelection(word.from, word.to);
      fullWord = true;
    } else {
      var text = cm.getRange(from, to);
      var query = fullWord ? new RegExp("\\b" + text + "\\b") : text;
      var cur = cm.getSearchCursor(query, to);
      var found = cur.findNext();
      if (!found) {
        cur = cm.getSearchCursor(query, Pos(cm.firstLine(), 0));
        found = cur.findNext();
      }
      if (!found || isSelectedRange(cm.listSelections(), cur.from(), cur.to()))
        return CodeMirror.Pass
      cm.addSelection(cur.from(), cur.to());
    }
    if (fullWord)
      cm.state.sublimeFindFullWord = cm.doc.sel;
  };

  function addCursorToSelection(cm, dir) {
    var ranges = cm.listSelections(), newRanges = [];
    for (var i = 0; i < ranges.length; i++) {
      var range = ranges[i];
      var newAnchor = cm.findPosV(
          range.anchor, dir, "line", range.anchor.goalColumn);
      var newHead = cm.findPosV(
          range.head, dir, "line", range.head.goalColumn);
      newAnchor.goalColumn = range.anchor.goalColumn != null ?
          range.anchor.goalColumn : cm.cursorCoords(range.anchor, "div").left;
      newHead.goalColumn = range.head.goalColumn != null ?
          range.head.goalColumn : cm.cursorCoords(range.head, "div").left;
      var newRange = {anchor: newAnchor, head: newHead};
      newRanges.push(range);
      newRanges.push(newRange);
    }
    cm.setSelections(newRanges);
  }
  cmds.addCursorToPrevLine = function(cm) { addCursorToSelection(cm, -1); };
  cmds.addCursorToNextLine = function(cm) { addCursorToSelection(cm, 1); };

  function isSelectedRange(ranges, from, to) {
    for (var i = 0; i < ranges.length; i++)
      if (ranges[i].from() == from && ranges[i].to() == to) return true
    return false
  }

  var mirror = "(){}[]";
  function selectBetweenBrackets(cm) {
    var ranges = cm.listSelections(), newRanges = []
    for (var i = 0; i < ranges.length; i++) {
      var range = ranges[i], pos = range.head, opening = cm.scanForBracket(pos, -1);
      if (!opening) return false;
      for (;;) {
        var closing = cm.scanForBracket(pos, 1);
        if (!closing) return false;
        if (closing.ch == mirror.charAt(mirror.indexOf(opening.ch) + 1)) {
          var startPos = Pos(opening.pos.line, opening.pos.ch + 1);
          if (CodeMirror.cmpPos(startPos, range.from()) == 0 &&
              CodeMirror.cmpPos(closing.pos, range.to()) == 0) {
            opening = cm.scanForBracket(opening.pos, -1);
            if (!opening) return false;
          } else {
            newRanges.push({anchor: startPos, head: closing.pos});
            break;
          }
        }
        pos = Pos(closing.pos.line, closing.pos.ch + 1);
      }
    }
    cm.setSelections(newRanges);
    return true;
  }

  cmds.selectScope = function(cm) {
    selectBetweenBrackets(cm) || cm.execCommand("selectAll");
  };
  cmds.selectBetweenBrackets = function(cm) {
    if (!selectBetweenBrackets(cm)) return CodeMirror.Pass;
  };

  cmds.goToBracket = function(cm) {
    cm.extendSelectionsBy(function(range) {
      var next = cm.scanForBracket(range.head, 1);
      if (next && CodeMirror.cmpPos(next.pos, range.head) != 0) return next.pos;
      var prev = cm.scanForBracket(range.head, -1);
      return prev && Pos(prev.pos.line, prev.pos.ch + 1) || range.head;
    });
  };

  cmds.swapLineUp = function(cm) {
    if (cm.isReadOnly()) return CodeMirror.Pass
    var ranges = cm.listSelections(), linesToMove = [], at = cm.firstLine() - 1, newSels = [];
    for (var i = 0; i < ranges.length; i++) {
      var range = ranges[i], from = range.from().line - 1, to = range.to().line;
      newSels.push({anchor: Pos(range.anchor.line - 1, range.anchor.ch),
                    head: Pos(range.head.line - 1, range.head.ch)});
      if (range.to().ch == 0 && !range.empty()) --to;
      if (from > at) linesToMove.push(from, to);
      else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to;
      at = to;
    }
    cm.operation(function() {
      for (var i = 0; i < linesToMove.length; i += 2) {
        var from = linesToMove[i], to = linesToMove[i + 1];
        var line = cm.getLine(from);
        cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine");
        if (to > cm.lastLine())
          cm.replaceRange("\n" + line, Pos(cm.lastLine()), null, "+swapLine");
        else
          cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine");
      }
      cm.setSelections(newSels);
      cm.scrollIntoView();
    });
  };

  cmds.swapLineDown = function(cm) {
    if (cm.isReadOnly()) return CodeMirror.Pass
    var ranges = cm.listSelections(), linesToMove = [], at = cm.lastLine() + 1;
    for (var i = ranges.length - 1; i >= 0; i--) {
      var range = ranges[i], from = range.to().line + 1, to = range.from().line;
      if (range.to().ch == 0 && !range.empty()) from--;
      if (from < at) linesToMove.push(from, to);
      else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to;
      at = to;
    }
    cm.operation(function() {
      for (var i = linesToMove.length - 2; i >= 0; i -= 2) {
        var from = linesToMove[i], to = linesToMove[i + 1];
        var line = cm.getLine(from);
        if (from == cm.lastLine())
          cm.replaceRange("", Pos(from - 1), Pos(from), "+swapLine");
        else
          cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine");
        cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine");
      }
      cm.scrollIntoView();
    });
  };

  cmds.toggleCommentIndented = function(cm) {
    cm.toggleComment({ indent: true });
  }

  cmds.joinLines = function(cm) {
    var ranges = cm.listSelections(), joined = [];
    for (var i = 0; i < ranges.length; i++) {
      var range = ranges[i], from = range.from();
      var start = from.line, end = range.to().line;
      while (i < ranges.length - 1 && ranges[i + 1].from().line == end)
        end = ranges[++i].to().line;
      joined.push({start: start, end: end, anchor: !range.empty() && from});
    }
    cm.operation(function() {
      var offset = 0, ranges = [];
      for (var i = 0; i < joined.length; i++) {
        var obj = joined[i];
        var anchor = obj.anchor && Pos(obj.anchor.line - offset, obj.anchor.ch), head;
        for (var line = obj.start; line <= obj.end; line++) {
          var actual = line - offset;
          if (line == obj.end) head = Pos(actual, cm.getLine(actual).length + 1);
          if (actual < cm.lastLine()) {
            cm.replaceRange(" ", Pos(actual), Pos(actual + 1, /^\s*/.exec(cm.getLine(actual + 1))[0].length));
            ++offset;
          }
        }
        ranges.push({anchor: anchor || head, head: head});
      }
      cm.setSelections(ranges, 0);
    });
  };

  cmds.duplicateLine = function(cm) {
    cm.operation(function() {
      var rangeCount = cm.listSelections().length;
      for (var i = 0; i < rangeCount; i++) {
        var range = cm.listSelections()[i];
        if (range.empty())
          cm.replaceRange(cm.getLine(range.head.line) + "\n", Pos(range.head.line, 0));
        else
          cm.replaceRange(cm.getRange(range.from(), range.to()), range.from());
      }
      cm.scrollIntoView();
    });
  };


  function sortLines(cm, caseSensitive) {
    if (cm.isReadOnly()) return CodeMirror.Pass
    var ranges = cm.listSelections(), toSort = [], selected;
    for (var i = 0; i < ranges.length; i++) {
      var range = ranges[i];
      if (range.empty()) continue;
      var from = range.from().line, to = range.to().line;
      while (i < ranges.length - 1 && ranges[i + 1].from().line == to)
        to = ranges[++i].to().line;
      if (!ranges[i].to().ch) to--;
      toSort.push(from, to);
    }
    if (toSort.length) selected = true;
    else toSort.push(cm.firstLine(), cm.lastLine());

    cm.operation(function() {
      var ranges = [];
      for (var i = 0; i < toSort.length; i += 2) {
        var from = toSort[i], to = toSort[i + 1];
        var start = Pos(from, 0), end = Pos(to);
        var lines = cm.getRange(start, end, false);
        if (caseSensitive)
          lines.sort();
        else
          lines.sort(function(a, b) {
            var au = a.toUpperCase(), bu = b.toUpperCase();
            if (au != bu) { a = au; b = bu; }
            return a < b ? -1 : a == b ? 0 : 1;
          });
        cm.replaceRange(lines, start, end);
        if (selected) ranges.push({anchor: start, head: Pos(to + 1, 0)});
      }
      if (selected) cm.setSelections(ranges, 0);
    });
  }

  cmds.sortLines = function(cm) { sortLines(cm, true); };
  cmds.sortLinesInsensitive = function(cm) { sortLines(cm, false); };

  cmds.nextBookmark = function(cm) {
    var marks = cm.state.sublimeBookmarks;
    if (marks) while (marks.length) {
      var current = marks.shift();
      var found = current.find();
      if (found) {
        marks.push(current);
        return cm.setSelection(found.from, found.to);
      }
    }
  };

  cmds.prevBookmark = function(cm) {
    var marks = cm.state.sublimeBookmarks;
    if (marks) while (marks.length) {
      marks.unshift(marks.pop());
      var found = marks[marks.length - 1].find();
      if (!found)
        marks.pop();
      else
        return cm.setSelection(found.from, found.to);
    }
  };

  cmds.toggleBookmark = function(cm) {
    var ranges = cm.listSelections();
    var marks = cm.state.sublimeBookmarks || (cm.state.sublimeBookmarks = []);
    for (var i = 0; i < ranges.length; i++) {
      var from = ranges[i].from(), to = ranges[i].to();
      var found = ranges[i].empty() ? cm.findMarksAt(from) : cm.findMarks(from, to);
      for (var j = 0; j < found.length; j++) {
        if (found[j].sublimeBookmark) {
          found[j].clear();
          for (var k = 0; k < marks.length; k++)
            if (marks[k] == found[j])
              marks.splice(k--, 1);
          break;
        }
      }
      if (j == found.length)
        marks.push(cm.markText(from, to, {sublimeBookmark: true, clearWhenEmpty: false}));
    }
  };

  cmds.clearBookmarks = function(cm) {
    var marks = cm.state.sublimeBookmarks;
    if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear();
    marks.length = 0;
  };

  cmds.selectBookmarks = function(cm) {
    var marks = cm.state.sublimeBookmarks, ranges = [];
    if (marks) for (var i = 0; i < marks.length; i++) {
      var found = marks[i].find();
      if (!found)
        marks.splice(i--, 0);
      else
        ranges.push({anchor: found.from, head: found.to});
    }
    if (ranges.length)
      cm.setSelections(ranges, 0);
  };

  function modifyWordOrSelection(cm, mod) {
    cm.operation(function() {
      var ranges = cm.listSelections(), indices = [], replacements = [];
      for (var i = 0; i < ranges.length; i++) {
        var range = ranges[i];
        if (range.empty()) { indices.push(i); replacements.push(""); }
        else replacements.push(mod(cm.getRange(range.from(), range.to())));
      }
      cm.replaceSelections(replacements, "around", "case");
      for (var i = indices.length - 1, at; i >= 0; i--) {
        var range = ranges[indices[i]];
        if (at && CodeMirror.cmpPos(range.head, at) > 0) continue;
        var word = wordAt(cm, range.head);
        at = word.from;
        cm.replaceRange(mod(word.word), word.from, word.to);
      }
    });
  }

  cmds.smartBackspace = function(cm) {
    if (cm.somethingSelected()) return CodeMirror.Pass;

    cm.operation(function() {
      var cursors = cm.listSelections();
      var indentUnit = cm.getOption("indentUnit");

      for (var i = cursors.length - 1; i >= 0; i--) {
        var cursor = cursors[i].head;
        var toStartOfLine = cm.getRange({line: cursor.line, ch: 0}, cursor);
        var column = CodeMirror.countColumn(toStartOfLine, null, cm.getOption("tabSize"));

        // Delete by one character by default
        var deletePos = cm.findPosH(cursor, -1, "char", false);

        if (toStartOfLine && !/\S/.test(toStartOfLine) && column % indentUnit == 0) {
          var prevIndent = new Pos(cursor.line,
            CodeMirror.findColumn(toStartOfLine, column - indentUnit, indentUnit));

          // Smart delete only if we found a valid prevIndent location
          if (prevIndent.ch != cursor.ch) deletePos = prevIndent;
        }

        cm.replaceRange("", deletePos, cursor, "+delete");
      }
    });
  };

  cmds.delLineRight = function(cm) {
    cm.operation(function() {
      var ranges = cm.listSelections();
      for (var i = ranges.length - 1; i >= 0; i--)
        cm.replaceRange("", ranges[i].anchor, Pos(ranges[i].to().line), "+delete");
      cm.scrollIntoView();
    });
  };

  cmds.upcaseAtCursor = function(cm) {
    modifyWordOrSelection(cm, function(str) { return str.toUpperCase(); });
  };
  cmds.downcaseAtCursor = function(cm) {
    modifyWordOrSelection(cm, function(str) { return str.toLowerCase(); });
  };

  cmds.setSublimeMark = function(cm) {
    if (cm.state.sublimeMark) cm.state.sublimeMark.clear();
    cm.state.sublimeMark = cm.setBookmark(cm.getCursor());
  };
  cmds.selectToSublimeMark = function(cm) {
    var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
    if (found) cm.setSelection(cm.getCursor(), found);
  };
  cmds.deleteToSublimeMark = function(cm) {
    var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
    if (found) {
      var from = cm.getCursor(), to = found;
      if (CodeMirror.cmpPos(from, to) > 0) { var tmp = to; to = from; from = tmp; }
      cm.state.sublimeKilled = cm.getRange(from, to);
      cm.replaceRange("", from, to);
    }
  };
  cmds.swapWithSublimeMark = function(cm) {
    var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
    if (found) {
      cm.state.sublimeMark.clear();
      cm.state.sublimeMark = cm.setBookmark(cm.getCursor());
      cm.setCursor(found);
    }
  };
  cmds.sublimeYank = function(cm) {
    if (cm.state.sublimeKilled != null)
      cm.replaceSelection(cm.state.sublimeKilled, null, "paste");
  };

  cmds.showInCenter = function(cm) {
    var pos = cm.cursorCoords(null, "local");
    cm.scrollTo(null, (pos.top + pos.bottom) / 2 - cm.getScrollInfo().clientHeight / 2);
  };

  function getTarget(cm) {
    var from = cm.getCursor("from"), to = cm.getCursor("to");
    if (CodeMirror.cmpPos(from, to) == 0) {
      var word = wordAt(cm, from);
      if (!word.word) return;
      from = word.from;
      to = word.to;
    }
    return {from: from, to: to, query: cm.getRange(from, to), word: word};
  }

  function findAndGoTo(cm, forward) {
    var target = getTarget(cm);
    if (!target) return;
    var query = target.query;
    var cur = cm.getSearchCursor(query, forward ? target.to : target.from);

    if (forward ? cur.findNext() : cur.findPrevious()) {
      cm.setSelection(cur.from(), cur.to());
    } else {
      cur = cm.getSearchCursor(query, forward ? Pos(cm.firstLine(), 0)
                                              : cm.clipPos(Pos(cm.lastLine())));
      if (forward ? cur.findNext() : cur.findPrevious())
        cm.setSelection(cur.from(), cur.to());
      else if (target.word)
        cm.setSelection(target.from, target.to);
    }
  };
  cmds.findUnder = function(cm) { findAndGoTo(cm, true); };
  cmds.findUnderPrevious = function(cm) { findAndGoTo(cm,false); };
  cmds.findAllUnder = function(cm) {
    var target = getTarget(cm);
    if (!target) return;
    var cur = cm.getSearchCursor(target.query);
    var matches = [];
    var primaryIndex = -1;
    while (cur.findNext()) {
      matches.push({anchor: cur.from(), head: cur.to()});
      if (cur.from().line <= target.from.line && cur.from().ch <= target.from.ch)
        primaryIndex++;
    }
    cm.setSelections(matches, primaryIndex);
  };


  var keyMap = CodeMirror.keyMap;
  keyMap.macSublime = {
    "Cmd-Left": "goLineStartSmart",
    "Shift-Tab": "indentLess",
    "Shift-Ctrl-K": "deleteLine",
    "Alt-Q": "wrapLines",
    "Ctrl-Left": "goSubwordLeft",
    "Ctrl-Right": "goSubwordRight",
    "Ctrl-Alt-Up": "scrollLineUp",
    "Ctrl-Alt-Down": "scrollLineDown",
    "Cmd-L": "selectLine",
    "Shift-Cmd-L": "splitSelectionByLine",
    "Esc": "singleSelectionTop",
    "Cmd-Enter": "insertLineAfter",
    "Shift-Cmd-Enter": "insertLineBefore",
    "Cmd-D": "selectNextOccurrence",
    "Shift-Cmd-Space": "selectScope",
    "Shift-Cmd-M": "selectBetweenBrackets",
    "Cmd-M": "goToBracket",
    "Cmd-Ctrl-Up": "swapLineUp",
    "Cmd-Ctrl-Down": "swapLineDown",
    "Cmd-/": "toggleCommentIndented",
    "Cmd-J": "joinLines",
    "Shift-Cmd-D": "duplicateLine",
    "F9": "sortLines",
    "Cmd-F9": "sortLinesInsensitive",
    "F2": "nextBookmark",
    "Shift-F2": "prevBookmark",
    "Cmd-F2": "toggleBookmark",
    "Shift-Cmd-F2": "clearBookmarks",
    "Alt-F2": "selectBookmarks",
    "Backspace": "smartBackspace",
    "Cmd-K Cmd-K": "delLineRight",
    "Cmd-K Cmd-U": "upcaseAtCursor",
    "Cmd-K Cmd-L": "downcaseAtCursor",
    "Cmd-K Cmd-Space": "setSublimeMark",
    "Cmd-K Cmd-A": "selectToSublimeMark",
    "Cmd-K Cmd-W": "deleteToSublimeMark",
    "Cmd-K Cmd-X": "swapWithSublimeMark",
    "Cmd-K Cmd-Y": "sublimeYank",
    "Cmd-K Cmd-C": "showInCenter",
    "Cmd-K Cmd-G": "clearBookmarks",
    "Cmd-K Cmd-Backspace": "delLineLeft",
    "Cmd-K Cmd-0": "unfoldAll",
    "Cmd-K Cmd-J": "unfoldAll",
    "Ctrl-Shift-Up": "addCursorToPrevLine",
    "Ctrl-Shift-Down": "addCursorToNextLine",
    "Cmd-F3": "findUnder",
    "Shift-Cmd-F3": "findUnderPrevious",
    "Alt-F3": "findAllUnder",
    "Shift-Cmd-[": "fold",
    "Shift-Cmd-]": "unfold",
    "Cmd-I": "findIncremental",
    "Shift-Cmd-I": "findIncrementalReverse",
    "Cmd-H": "replace",
    "F3": "findNext",
    "Shift-F3": "findPrev",
    "fallthrough": "macDefault"
  };
  CodeMirror.normalizeKeyMap(keyMap.macSublime);

  keyMap.pcSublime = {
    "Shift-Tab": "indentLess",
    "Shift-Ctrl-K": "deleteLine",
    "Alt-Q": "wrapLines",
    "Ctrl-T": "transposeChars",
    "Alt-Left": "goSubwordLeft",
    "Alt-Right": "goSubwordRight",
    "Ctrl-Up": "scrollLineUp",
    "Ctrl-Down": "scrollLineDown",
    "Ctrl-L": "selectLine",
    "Shift-Ctrl-L": "splitSelectionByLine",
    "Esc": "singleSelectionTop",
    "Ctrl-Enter": "insertLineAfter",
    "Shift-Ctrl-Enter": "insertLineBefore",
    "Ctrl-D": "selectNextOccurrence",
    "Shift-Ctrl-Space": "selectScope",
    "Shift-Ctrl-M": "selectBetweenBrackets",
    "Ctrl-M": "goToBracket",
    "Shift-Ctrl-Up": "swapLineUp",
    "Shift-Ctrl-Down": "swapLineDown",
    "Ctrl-/": "toggleCommentIndented",
    "Ctrl-J": "joinLines",
    "Shift-Ctrl-D": "duplicateLine",
    "F9": "sortLines",
    "Ctrl-F9": "sortLinesInsensitive",
    "F2": "nextBookmark",
    "Shift-F2": "prevBookmark",
    "Ctrl-F2": "toggleBookmark",
    "Shift-Ctrl-F2": "clearBookmarks",
    "Alt-F2": "selectBookmarks",
    "Backspace": "smartBackspace",
    "Ctrl-K Ctrl-K": "delLineRight",
    "Ctrl-K Ctrl-U": "upcaseAtCursor",
    "Ctrl-K Ctrl-L": "downcaseAtCursor",
    "Ctrl-K Ctrl-Space": "setSublimeMark",
    "Ctrl-K Ctrl-A": "selectToSublimeMark",
    "Ctrl-K Ctrl-W": "deleteToSublimeMark",
    "Ctrl-K Ctrl-X": "swapWithSublimeMark",
    "Ctrl-K Ctrl-Y": "sublimeYank",
    "Ctrl-K Ctrl-C": "showInCenter",
    "Ctrl-K Ctrl-G": "clearBookmarks",
    "Ctrl-K Ctrl-Backspace": "delLineLeft",
    "Ctrl-K Ctrl-0": "unfoldAll",
    "Ctrl-K Ctrl-J": "unfoldAll",
    "Ctrl-Alt-Up": "addCursorToPrevLine",
    "Ctrl-Alt-Down": "addCursorToNextLine",
    "Ctrl-F3": "findUnder",
    "Shift-Ctrl-F3": "findUnderPrevious",
    "Alt-F3": "findAllUnder",
    "Shift-Ctrl-[": "fold",
    "Shift-Ctrl-]": "unfold",
    "Ctrl-I": "findIncremental",
    "Shift-Ctrl-I": "findIncrementalReverse",
    "Ctrl-H": "replace",
    "F3": "findNext",
    "Shift-F3": "findPrev",
    "fallthrough": "pcDefault"
  };
  CodeMirror.normalizeKeyMap(keyMap.pcSublime);

  var mac = keyMap.default == keyMap.macDefault;
  keyMap.sublime = mac ? keyMap.macSublime : keyMap.pcSublime;
});


/***/ }),

/***/ "mqlF":
/*!**************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_object-gops.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

exports.f = Object.getOwnPropertySymbols;


/***/ }),

/***/ "mv/X":
/*!************************************************!*\
  !*** ./node_modules/lodash/_isIterateeCall.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var eq = __webpack_require__(/*! ./eq */ "ljhN"),
    isArrayLike = __webpack_require__(/*! ./isArrayLike */ "MMmD"),
    isIndex = __webpack_require__(/*! ./_isIndex */ "wJg7"),
    isObject = __webpack_require__(/*! ./isObject */ "GoyQ");

/**
 * 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;


/***/ }),

/***/ "mvme":
/*!*********************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/boxlayout.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
var domutils_1 = __webpack_require__(/*! @phosphor/domutils */ "XWTc");
var messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
var properties_1 = __webpack_require__(/*! @phosphor/properties */ "3kwb");
var boxengine_1 = __webpack_require__(/*! ./boxengine */ "ovjo");
var layout_1 = __webpack_require__(/*! ./layout */ "yNaG");
var panellayout_1 = __webpack_require__(/*! ./panellayout */ "HWBy");
var widget_1 = __webpack_require__(/*! ./widget */ "FmDU");
/**
 * A layout which arranges its widgets in a single row or column.
 */
var BoxLayout = (function (_super) {
    __extends(BoxLayout, _super);
    /**
     * Construct a new box layout.
     *
     * @param options - The options for initializing the layout.
     */
    function BoxLayout(options) {
        if (options === void 0) { options = {}; }
        var _this = _super.call(this) || this;
        _this._fixed = 0;
        _this._spacing = 4;
        _this._dirty = false;
        _this._sizers = [];
        _this._items = [];
        _this._box = null;
        _this._alignment = 'start';
        _this._direction = 'top-to-bottom';
        if (options.direction !== undefined) {
            _this._direction = options.direction;
        }
        if (options.alignment !== undefined) {
            _this._alignment = options.alignment;
        }
        if (options.spacing !== undefined) {
            _this._spacing = Private.clampSpacing(options.spacing);
        }
        return _this;
    }
    /**
     * Dispose of the resources held by the layout.
     */
    BoxLayout.prototype.dispose = function () {
        // Dispose of the layout items.
        algorithm_1.each(this._items, function (item) { item.dispose(); });
        // Clear the layout state.
        this._box = null;
        this._items.length = 0;
        this._sizers.length = 0;
        // Dispose of the rest of the layout.
        _super.prototype.dispose.call(this);
    };
    Object.defineProperty(BoxLayout.prototype, "direction", {
        /**
         * Get the layout direction for the box layout.
         */
        get: function () {
            return this._direction;
        },
        /**
         * Set the layout direction for the box layout.
         */
        set: function (value) {
            if (this._direction === value) {
                return;
            }
            this._direction = value;
            if (!this.parent) {
                return;
            }
            this.parent.dataset['direction'] = value;
            this.parent.fit();
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(BoxLayout.prototype, "alignment", {
        /**
         * Get the content alignment for the box layout.
         *
         * #### Notes
         * This is the alignment of the widgets in the layout direction.
         *
         * The alignment has no effect if the widgets can expand to fill the
         * entire box layout.
         */
        get: function () {
            return this._alignment;
        },
        /**
         * Set the content alignment for the box layout.
         *
         * #### Notes
         * This is the alignment of the widgets in the layout direction.
         *
         * The alignment has no effect if the widgets can expand to fill the
         * entire box layout.
         */
        set: function (value) {
            if (this._alignment === value) {
                return;
            }
            this._alignment = value;
            if (!this.parent) {
                return;
            }
            this.parent.dataset['alignment'] = value;
            this.parent.update();
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(BoxLayout.prototype, "spacing", {
        /**
         * Get the inter-element spacing for the box layout.
         */
        get: function () {
            return this._spacing;
        },
        /**
         * Set the inter-element spacing for the box layout.
         */
        set: function (value) {
            value = Private.clampSpacing(value);
            if (this._spacing === value) {
                return;
            }
            this._spacing = value;
            if (!this.parent) {
                return;
            }
            this.parent.fit();
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Perform layout initialization which requires the parent widget.
     */
    BoxLayout.prototype.init = function () {
        this.parent.dataset['direction'] = this.direction;
        this.parent.dataset['alignment'] = this.alignment;
        _super.prototype.init.call(this);
    };
    /**
     * Attach a widget to the parent's DOM node.
     *
     * @param index - The current index of the widget in the layout.
     *
     * @param widget - The widget to attach to the parent.
     *
     * #### Notes
     * This is a reimplementation of the superclass method.
     */
    BoxLayout.prototype.attachWidget = function (index, widget) {
        // Create and add a new layout item for the widget.
        algorithm_1.ArrayExt.insert(this._items, index, new layout_1.LayoutItem(widget));
        // Create and add a new sizer for the widget.
        algorithm_1.ArrayExt.insert(this._sizers, index, new boxengine_1.BoxSizer());
        // Send a `'before-attach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.BeforeAttach);
        }
        // Add the widget's node to the parent.
        this.parent.node.appendChild(widget.node);
        // Send an `'after-attach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.AfterAttach);
        }
        // Post a fit request for the parent widget.
        this.parent.fit();
    };
    /**
     * Move a widget in the parent's DOM node.
     *
     * @param fromIndex - The previous index of the widget in the layout.
     *
     * @param toIndex - The current index of the widget in the layout.
     *
     * @param widget - The widget to move in the parent.
     *
     * #### Notes
     * This is a reimplementation of the superclass method.
     */
    BoxLayout.prototype.moveWidget = function (fromIndex, toIndex, widget) {
        // Move the layout item for the widget.
        algorithm_1.ArrayExt.move(this._items, fromIndex, toIndex);
        // Move the sizer for the widget.
        algorithm_1.ArrayExt.move(this._sizers, fromIndex, toIndex);
        // Post an update request for the parent widget.
        this.parent.update();
    };
    /**
     * Detach a widget from the parent's DOM node.
     *
     * @param index - The previous index of the widget in the layout.
     *
     * @param widget - The widget to detach from the parent.
     *
     * #### Notes
     * This is a reimplementation of the superclass method.
     */
    BoxLayout.prototype.detachWidget = function (index, widget) {
        // Remove the layout item for the widget.
        var item = algorithm_1.ArrayExt.removeAt(this._items, index);
        // Remove the sizer for the widget.
        algorithm_1.ArrayExt.removeAt(this._sizers, index);
        // Send a `'before-detach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.BeforeDetach);
        }
        // Remove the widget's node from the parent.
        this.parent.node.removeChild(widget.node);
        // Send an `'after-detach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.AfterDetach);
        }
        // Dispose of the layout item.
        item.dispose();
        // Post a fit request for the parent widget.
        this.parent.fit();
    };
    /**
     * A message handler invoked on a `'before-show'` message.
     */
    BoxLayout.prototype.onBeforeShow = function (msg) {
        _super.prototype.onBeforeShow.call(this, msg);
        this.parent.update();
    };
    /**
     * A message handler invoked on a `'before-attach'` message.
     */
    BoxLayout.prototype.onBeforeAttach = function (msg) {
        _super.prototype.onBeforeAttach.call(this, msg);
        this.parent.fit();
    };
    /**
     * A message handler invoked on a `'child-shown'` message.
     */
    BoxLayout.prototype.onChildShown = function (msg) {
        this.parent.fit();
    };
    /**
     * A message handler invoked on a `'child-hidden'` message.
     */
    BoxLayout.prototype.onChildHidden = function (msg) {
        this.parent.fit();
    };
    /**
     * A message handler invoked on a `'resize'` message.
     */
    BoxLayout.prototype.onResize = function (msg) {
        if (this.parent.isVisible) {
            this._update(msg.width, msg.height);
        }
    };
    /**
     * A message handler invoked on an `'update-request'` message.
     */
    BoxLayout.prototype.onUpdateRequest = function (msg) {
        if (this.parent.isVisible) {
            this._update(-1, -1);
        }
    };
    /**
     * A message handler invoked on a `'fit-request'` message.
     */
    BoxLayout.prototype.onFitRequest = function (msg) {
        if (this.parent.isAttached) {
            this._fit();
        }
    };
    /**
     * Fit the layout to the total size required by the widgets.
     */
    BoxLayout.prototype._fit = function () {
        // Compute the visible item count.
        var nVisible = 0;
        for (var i = 0, n = this._items.length; i < n; ++i) {
            nVisible += +!this._items[i].isHidden;
        }
        // Update the fixed space for the visible items.
        this._fixed = this._spacing * Math.max(0, nVisible - 1);
        // Setup the computed minimum size.
        var horz = Private.isHorizontal(this._direction);
        var minW = horz ? this._fixed : 0;
        var minH = horz ? 0 : this._fixed;
        // Update the sizers and computed minimum size.
        for (var i = 0, n = this._items.length; i < n; ++i) {
            // Fetch the item and corresponding box sizer.
            var item = this._items[i];
            var sizer = this._sizers[i];
            // If the item is hidden, it should consume zero size.
            if (item.isHidden) {
                sizer.minSize = 0;
                sizer.maxSize = 0;
                continue;
            }
            // Update the size limits for the item.
            item.fit();
            // Update the size basis and stretch factor.
            sizer.sizeHint = BoxLayout.getSizeBasis(item.widget);
            sizer.stretch = BoxLayout.getStretch(item.widget);
            // Update the sizer limits and computed min size.
            if (horz) {
                sizer.minSize = item.minWidth;
                sizer.maxSize = item.maxWidth;
                minW += item.minWidth;
                minH = Math.max(minH, item.minHeight);
            }
            else {
                sizer.minSize = item.minHeight;
                sizer.maxSize = item.maxHeight;
                minH += item.minHeight;
                minW = Math.max(minW, item.minWidth);
            }
        }
        // Update the box sizing and add it to the computed min size.
        var box = this._box = domutils_1.ElementExt.boxSizing(this.parent.node);
        minW += box.horizontalSum;
        minH += box.verticalSum;
        // Update the parent's min size constraints.
        var style = this.parent.node.style;
        style.minWidth = minW + "px";
        style.minHeight = minH + "px";
        // Set the dirty flag to ensure only a single update occurs.
        this._dirty = true;
        // Notify the ancestor that it should fit immediately. This may
        // cause a resize of the parent, fulfilling the required update.
        if (this.parent.parent) {
            messaging_1.MessageLoop.sendMessage(this.parent.parent, widget_1.Widget.Msg.FitRequest);
        }
        // If the dirty flag is still set, the parent was not resized.
        // Trigger the required update on the parent widget immediately.
        if (this._dirty) {
            messaging_1.MessageLoop.sendMessage(this.parent, widget_1.Widget.Msg.UpdateRequest);
        }
    };
    /**
     * Update the layout position and size of the widgets.
     *
     * The parent offset dimensions should be `-1` if unknown.
     */
    BoxLayout.prototype._update = function (offsetWidth, offsetHeight) {
        // Clear the dirty flag to indicate the update occurred.
        this._dirty = false;
        // Compute the visible item count.
        var nVisible = 0;
        for (var i = 0, n = this._items.length; i < n; ++i) {
            nVisible += +!this._items[i].isHidden;
        }
        // Bail early if there are no visible items to layout.
        if (nVisible === 0) {
            return;
        }
        // Measure the parent if the offset dimensions are unknown.
        if (offsetWidth < 0) {
            offsetWidth = this.parent.node.offsetWidth;
        }
        if (offsetHeight < 0) {
            offsetHeight = this.parent.node.offsetHeight;
        }
        // Ensure the parent box sizing data is computed.
        if (!this._box) {
            this._box = domutils_1.ElementExt.boxSizing(this.parent.node);
        }
        // Compute the layout area adjusted for border and padding.
        var top = this._box.paddingTop;
        var left = this._box.paddingLeft;
        var width = offsetWidth - this._box.horizontalSum;
        var height = offsetHeight - this._box.verticalSum;
        // Distribute the layout space and adjust the start position.
        var delta;
        switch (this._direction) {
            case 'left-to-right':
                delta = boxengine_1.BoxEngine.calc(this._sizers, Math.max(0, width - this._fixed));
                break;
            case 'top-to-bottom':
                delta = boxengine_1.BoxEngine.calc(this._sizers, Math.max(0, height - this._fixed));
                break;
            case 'right-to-left':
                delta = boxengine_1.BoxEngine.calc(this._sizers, Math.max(0, width - this._fixed));
                left += width;
                break;
            case 'bottom-to-top':
                delta = boxengine_1.BoxEngine.calc(this._sizers, Math.max(0, height - this._fixed));
                top += height;
                break;
            default:
                throw 'unreachable';
        }
        // Setup the variables for justification and alignment offset.
        var extra = 0;
        var offset = 0;
        // Account for alignment if there is extra layout space.
        if (delta > 0) {
            switch (this._alignment) {
                case 'start':
                    break;
                case 'center':
                    extra = 0;
                    offset = delta / 2;
                    break;
                case 'end':
                    extra = 0;
                    offset = delta;
                    break;
                case 'justify':
                    extra = delta / nVisible;
                    offset = 0;
                    break;
                default:
                    throw 'unreachable';
            }
        }
        // Layout the items using the computed box sizes.
        for (var i = 0, n = this._items.length; i < n; ++i) {
            // Fetch the item.
            var item = this._items[i];
            // Ignore hidden items.
            if (item.isHidden) {
                continue;
            }
            // Fetch the computed size for the widget.
            var size = this._sizers[i].size;
            // Update the widget geometry and advance the relevant edge.
            switch (this._direction) {
                case 'left-to-right':
                    item.update(left + offset, top, size + extra, height);
                    left += size + extra + this._spacing;
                    break;
                case 'top-to-bottom':
                    item.update(left, top + offset, width, size + extra);
                    top += size + extra + this._spacing;
                    break;
                case 'right-to-left':
                    item.update(left - offset - size - extra, top, size + extra, height);
                    left -= size + extra + this._spacing;
                    break;
                case 'bottom-to-top':
                    item.update(left, top - offset - size - extra, width, size + extra);
                    top -= size + extra + this._spacing;
                    break;
                default:
                    throw 'unreachable';
            }
        }
    };
    return BoxLayout;
}(panellayout_1.PanelLayout));
exports.BoxLayout = BoxLayout;
/**
 * The namespace for the `BoxLayout` class statics.
 */
(function (BoxLayout) {
    /**
     * Get the box layout stretch factor for the given widget.
     *
     * @param widget - The widget of interest.
     *
     * @returns The box layout stretch factor for the widget.
     */
    function getStretch(widget) {
        return Private.stretchProperty.get(widget);
    }
    BoxLayout.getStretch = getStretch;
    /**
     * Set the box layout stretch factor for the given widget.
     *
     * @param widget - The widget of interest.
     *
     * @param value - The value for the stretch factor.
     */
    function setStretch(widget, value) {
        Private.stretchProperty.set(widget, value);
    }
    BoxLayout.setStretch = setStretch;
    /**
     * Get the box layout size basis for the given widget.
     *
     * @param widget - The widget of interest.
     *
     * @returns The box layout size basis for the widget.
     */
    function getSizeBasis(widget) {
        return Private.sizeBasisProperty.get(widget);
    }
    BoxLayout.getSizeBasis = getSizeBasis;
    /**
     * Set the box layout size basis for the given widget.
     *
     * @param widget - The widget of interest.
     *
     * @param value - The value for the size basis.
     */
    function setSizeBasis(widget, value) {
        Private.sizeBasisProperty.set(widget, value);
    }
    BoxLayout.setSizeBasis = setSizeBasis;
})(BoxLayout = exports.BoxLayout || (exports.BoxLayout = {}));
exports.BoxLayout = BoxLayout;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * The property descriptor for a widget stretch factor.
     */
    Private.stretchProperty = new properties_1.AttachedProperty({
        name: 'stretch',
        create: function () { return 0; },
        coerce: function (owner, value) { return Math.max(0, Math.floor(value)); },
        changed: onChildSizingChanged
    });
    /**
     * The property descriptor for a widget size basis.
     */
    Private.sizeBasisProperty = new properties_1.AttachedProperty({
        name: 'sizeBasis',
        create: function () { return 0; },
        coerce: function (owner, value) { return Math.max(0, Math.floor(value)); },
        changed: onChildSizingChanged
    });
    /**
     * Test whether a direction has horizontal orientation.
     */
    function isHorizontal(dir) {
        return dir === 'left-to-right' || dir === 'right-to-left';
    }
    Private.isHorizontal = isHorizontal;
    /**
     * Clamp a spacing value to an integer >= 0.
     */
    function clampSpacing(value) {
        return Math.max(0, Math.floor(value));
    }
    Private.clampSpacing = clampSpacing;
    /**
     * The change handler for the attached sizing properties.
     */
    function onChildSizingChanged(child) {
        if (child.parent && child.parent.layout instanceof BoxLayout) {
            child.parent.fit();
        }
    }
})(Private || (Private = {}));


/***/ }),

/***/ "mwIZ":
/*!************************************!*\
  !*** ./node_modules/lodash/get.js ***!
  \************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseGet = __webpack_require__(/*! ./_baseGet */ "ZWtO");

/**
 * 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;
}

module.exports = get;


/***/ }),

/***/ "mwTM":
/*!****************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/ScriptIcon.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var ScriptIcon = function ScriptIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 16 16' }, props),
        _react2.default.createElement('path', { d: 'M0 7c.617 0 1.197-.123 1.5-.5.303-.377.5-1.051.5-2V3c0-1.078.407-1.752.899-2.255C3.392.242 4.186 0 5.281 0H6v2l-.068.002c-.751 0-1.208.097-1.373.289s-.246.729-.246 1.611c0 1.127-.083 1.98-.25 2.558C3.896 7.037 3.64 7.548 3 8c.64.447.896.965 1.063 1.543.167.578.25 1.432.25 2.561 0 .884.082 1.421.246 1.614.164.192.622.289 1.373.289L6 14v2h-.719c-1.096 0-1.89-.233-2.382-.736S2 14.078 2 13v-1.5c0-.955-.197-1.626-.5-2C1.197 9.126.617 9.006 0 9V7zm16 2c-.617.006-1.199.126-1.5.5-.3.374-.5 1.045-.5 2V13c0 1.078-.312 1.761-.805 2.264S11.906 16 10.804 16H10v-2l.154.007c.756 0 1.217-.097 1.381-.289.164-.193.246-.73.246-1.614 0-1.129.083-1.982.25-2.561S12.366 8.447 13 8c-.634-.452-.802-.963-.969-1.541s-.25-1.43-.25-2.558c0-.882-.082-1.419-.246-1.611s-.625-.288-1.381-.288L10 2V0h.805c1.102 0 1.898.242 2.391.745C13.688 1.248 14 1.922 14 3v1.5c0 .949.2 1.623.5 2 .301.377.883.5 1.5.5v2z' })
    );
};

exports.default = ScriptIcon;

/***/ }),

/***/ "my6z":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/filebrowser/lib/index.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__webpack_require__(/*! ../style/index.css */ "jTZ7");
__export(__webpack_require__(/*! ./browser */ "h4KJ"));
__export(__webpack_require__(/*! ./crumbs */ "R4GQ"));
__export(__webpack_require__(/*! ./factory */ "7kzI"));
__export(__webpack_require__(/*! ./listing */ "m5lF"));
__export(__webpack_require__(/*! ./model */ "MM3R"));
__export(__webpack_require__(/*! ./upload */ "XtOF"));


/***/ }),

/***/ "mz0i":
/*!********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotSankeyIcon.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotSankeyIcon = function PlotSankeyIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M1.313 13.375v-.063h21.375v4l9.313-8-9.313-8v4H0V24c4.5 0 8.25 1.625 10.313 4.438l-1.875.75 6.25 2.813 2.813-6.25-2.063.75c-2.75-4.563-7.938-7.375-14.125-7.75v-.063c9.938.188 15.688 2.25 21.375 7.625l-1.563 1.5 6.875.188.188-6.875-1.563 1.5c-6.813-6.5-13.813-9.063-25.313-9.25z' })
    );
};

exports.default = PlotSankeyIcon;

/***/ }),

/***/ "n+SQ":
/*!*************************************************!*\
  !*** ./node_modules/ajv/lib/compile/formats.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var util = __webpack_require__(/*! ./util */ "+9rK");

var DATE = /^\d\d\d\d-(\d\d)-(\d\d)$/;
var DAYS = [0,31,29,31,30,31,30,31,31,30,31,30,31];
var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d:\d\d)?$/i;
var HOSTNAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*$/i;
var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@\/?]|%[0-9a-f]{2})*)?(?:\#(?:[a-z0-9\-._~!$&'()*+,;=:@\/?]|%[0-9a-f]{2})*)?$/i;
var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@\/?]|%[0-9a-f]{2})*)?(?:\#(?:[a-z0-9\-._~!$&'"()*+,;=:@\/?]|%[0-9a-f]{2})*)?$/i;
// uri-template: https://tools.ietf.org/html/rfc6570
var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#.\/;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\:[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\:[1-9][0-9]{0,3}|\*)?)*\})*$/i;
// For the source: https://gist.github.com/dperini/729294
// For test cases: https://mathiasbynens.be/demo/url-regex
// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983.
// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;
var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+\-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+\-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i;
var UUID = /^(?:urn\:uuid\:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
var JSON_POINTER = /^(?:\/(?:[^~\/]|~0|~1)*)*$|^\#(?:\/(?:[a-z0-9_\-\.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:\#|(?:\/(?:[^~\/]|~0|~1)*)*)$/;


module.exports = formats;

function formats(mode) {
  mode = mode == 'full' ? 'full' : 'fast';
  return util.copy(formats[mode]);
}


formats.fast = {
  // date: http://tools.ietf.org/html/rfc3339#section-5.6
  date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
  // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
  time: /^[0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)?$/i,
  'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s][0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)$/i,
  // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
  uri: /^(?:[a-z][a-z0-9+-.]*)(?:\:|\/)\/?[^\s]*$/i,
  'uri-reference': /^(?:(?:[a-z][a-z0-9+-.]*:)?\/\/)?[^\s]*$/i,
  'uri-template': URITEMPLATE,
  url: URL,
  // email (sources from jsen validator):
  // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
  // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation')
  email: /^[a-z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
  hostname: HOSTNAME,
  // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
  ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
  // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
  ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
  regex: regex,
  // uuid: http://tools.ietf.org/html/rfc4122
  uuid: UUID,
  // JSON-pointer: https://tools.ietf.org/html/rfc6901
  // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
  'json-pointer': JSON_POINTER,
  // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
  'relative-json-pointer': RELATIVE_JSON_POINTER
};


formats.full = {
  date: date,
  time: time,
  'date-time': date_time,
  uri: uri,
  'uri-reference': URIREF,
  'uri-template': URITEMPLATE,
  url: URL,
  email: /^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&''*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
  hostname: hostname,
  ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
  ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
  regex: regex,
  uuid: UUID,
  'json-pointer': JSON_POINTER,
  'relative-json-pointer': RELATIVE_JSON_POINTER
};


function date(str) {
  // full-date from http://tools.ietf.org/html/rfc3339#section-5.6
  var matches = str.match(DATE);
  if (!matches) return false;

  var month = +matches[1];
  var day = +matches[2];
  return month >= 1 && month <= 12 && day >= 1 && day <= DAYS[month];
}


function time(str, full) {
  var matches = str.match(TIME);
  if (!matches) return false;

  var hour = matches[1];
  var minute = matches[2];
  var second = matches[3];
  var timeZone = matches[5];
  return hour <= 23 && minute <= 59 && second <= 59 && (!full || timeZone);
}


var DATE_TIME_SEPARATOR = /t|\s/i;
function date_time(str) {
  // http://tools.ietf.org/html/rfc3339#section-5.6
  var dateTime = str.split(DATE_TIME_SEPARATOR);
  return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true);
}


function hostname(str) {
  // https://tools.ietf.org/html/rfc1034#section-3.5
  // https://tools.ietf.org/html/rfc1123#section-2
  return str.length <= 255 && HOSTNAME.test(str);
}


var NOT_URI_FRAGMENT = /\/|\:/;
function uri(str) {
  // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "."
  return NOT_URI_FRAGMENT.test(str) && URI.test(str);
}


var Z_ANCHOR = /[^\\]\\Z/;
function regex(str) {
  if (Z_ANCHOR.test(str)) return false;
  try {
    new RegExp(str);
    return true;
  } catch(e) {
    return false;
  }
}


/***/ }),

/***/ "n/bZ":
/*!*************************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/tabmanager-extension/style/index.css ***!
  \*************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n/*-----------------------------------------------------------------------------\n| Variables\n|----------------------------------------------------------------------------*/\n\n:root {\n  --jp-private-tab-manager-active-top-border: 2px;\n  --jp-private-tab-manager-tab-height: 24px;\n  --jp-private-tab-manager-tab-padding-top: 8px;\n}\n\n/*-----------------------------------------------------------------------------\n| Tabs in the dock panel\n|----------------------------------------------------------------------------*/\n\n#tab-manager {\n  background: var(--jp-layout-color1);\n  overflow: visible;\n  color: var(--jp-ui-font-color1);\n  /* This is needed so that all font sizing of children done in ems is\n   * relative to this base size */\n  font-size: var(--jp-ui-font-size1);\n}\n\n#tab-manager header {\n  border-bottom: var(--jp-border-width) solid var(--jp-border-color2);\n  flex: 0 0 auto;\n  font-size: var(--jp-ui-font-size0);\n  font-weight: 600;\n  letter-spacing: 1px;\n  margin: 0px;\n  padding: 8px 12px;\n  text-transform: uppercase;\n}\n\n#tab-manager .p-TabBar-tab {\n  height: var(--jp-private-tab-manager-tab-height);\n  padding: 0px 12px;\n  border: none;\n  position: relative;\n  overflow: visible;\n}\n\n#tab-manager .p-TabBar-tab:hover:not(.jp-mod-active) {\n  background: var(--jp-layout-color2);\n}\n\n#tab-manager .p-TabBar-tab:first-child {\n  margin-left: 0;\n}\n\n#tab-manager .p-TabBar-tab.jp-mod-active {\n  color: white;\n  background: var(--jp-brand-color1);\n}\n\n#tab-manager .p-TabBar-tabIcon,\n#tab-manager .p-TabBar-tabLabel,\n#tab-manager .p-TabBar-tabCloseIcon {\n  display: inline-block;\n}\n\n#tab-manager .p-TabBar-tabLabel {\n  line-height: var(--jp-private-tab-manager-tab-height);\n  padding-left: 4px;\n}\n\n#tab-manager .p-TabBar-tab .p-TabBar-tabIcon {\n  width: 14px;\n  background-position: left center;\n  background-repeat: no-repeat;\n  margin-right: 2px;\n}\n\n#tab-manager .p-TabBar-tab.p-mod-closable > .p-TabBar-tabCloseIcon {\n  padding: 4px 0px 4px 4px;\n  background-size: 16px;\n  height: 16px;\n  width: 16px;\n  background-image: var(--jp-icon-close);\n  background-position: center;\n  background-repeat: no-repeat;\n}\n\n#tab-manager\n  .p-TabBar-tab.p-mod-closable.jp-mod-dirty\n  > .p-TabBar-tabCloseIcon {\n  background-size: 10px;\n  background-image: var(--jp-icon-circle);\n}\n\n#tab-manager\n  .p-TabBar-tab.p-mod-closable.jp-mod-dirty.jp-mod-active\n  > .p-TabBar-tabCloseIcon {\n  background-size: 10px;\n  background-image: var(--jp-icon-inverse-circle);\n}\n\n#tab-manager\n  .p-TabBar-tab.p-mod-closable.jp-mod-active\n  > .p-TabBar-tabCloseIcon {\n  background-image: var(--jp-icon-inverse-close);\n}\n\n#tab-manager .p-TabBar-tab.p-mod-closable > .p-TabBar-tabCloseIcon:hover {\n  background-size: 16px;\n  background-image: var(--jp-icon-close-circle);\n}\n\n#tab-manager\n  .p-TabBar-tab.p-mod-closable.jp-mod-active\n  > .p-TabBar-tabCloseIcon:hover {\n  background-size: 16px;\n  background-image: var(--jp-icon-inverse-close-circle);\n}\n", ""]);

// exports


/***/ }),

/***/ "n/zs":
/*!******************************************************!*\
  !*** ./node_modules/@phosphor/algorithm/lib/sort.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var iter_1 = __webpack_require__(/*! ./iter */ "DMSk");
/**
 * Topologically sort an iterable of edges.
 *
 * @param edges - The iterable or array-like object of edges to sort.
 *   An edge is represented as a 2-tuple of `[fromNode, toNode]`.
 *
 * @returns The topologically sorted array of nodes.
 *
 * #### Notes
 * If a cycle is present in the graph, the cycle will be ignored and
 * the return value will be only approximately sorted.
 *
 * #### Example
 * ```typescript
 * import { topologicSort } from '@phosphor/algorithm';
 *
 * let data = [
 *   ['d', 'e'],
 *   ['c', 'd'],
 *   ['a', 'b'],
 *   ['b', 'c']
 * ];
 *
 * topologicSort(data);  // ['a', 'b', 'c', 'd', 'e']
 */
function topologicSort(edges) {
    // Setup the shared sorting state.
    var sorted = [];
    var visited = new Set();
    var graph = new Map();
    // Add the edges to the graph.
    iter_1.each(edges, addEdge);
    // Visit each node in the graph.
    graph.forEach(function (v, k) { visit(k); });
    // Return the sorted results.
    return sorted;
    // Add an edge to the graph.
    function addEdge(edge) {
        var fromNode = edge[0], toNode = edge[1];
        var children = graph.get(toNode);
        if (children) {
            children.push(fromNode);
        }
        else {
            graph.set(toNode, [fromNode]);
        }
    }
    // Recursively visit the node.
    function visit(node) {
        if (visited.has(node)) {
            return;
        }
        visited.add(node);
        var children = graph.get(node);
        if (children) {
            children.forEach(visit);
        }
        sorted.push(node);
    }
}
exports.topologicSort = topologicSort;


/***/ }),

/***/ "n53Y":
/*!*****************************************************!*\
  !*** ./node_modules/pbkdf2/lib/default-encoding.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(process) {var defaultEncoding
/* istanbul ignore next */
if (process.browser) {
  defaultEncoding = 'utf-8'
} else {
  var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10)

  defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary'
}
module.exports = defaultEncoding

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ "8oxB")))

/***/ }),

/***/ "n8IF":
/*!**************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeHeatmapIcon.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeHeatmapIcon = function TraceTypeHeatmapIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement('path', { fill: 'none', d: 'M0 0h46v46H0z' }),
        _react2.default.createElement('path', { fill: '#1d9bfb', d: 'M32 20h6v6h-6zm-12-6h6v6h-6zm-6 6h6v6h-6zm0 12h6v6h-6zm6 0h6v6h-6zm12 0h6v6h-6zm-6-12h6v6h-6z' }),
        _react2.default.createElement('path', { fill: '#25fdfc', d: 'M26 14h6v6h-6zm6 0h6v6h-6zm-12 6h6v6h-6zM8 20h6v6H8z' }),
        _react2.default.createElement('path', { fill: '#1d9bfb', d: 'M14 14h6v6h-6z' }),
        _react2.default.createElement('path', { fill: '#25fdfc', d: 'M8 14h6v6H8z' }),
        _react2.default.createElement('path', { fill: '#1d9bfb', d: 'M26 26h6v6h-6zM8 26h6v6H8z' }),
        _react2.default.createElement('path', { fill: '#25fdfc', d: 'M20 26h6v6h-6zm12 0h6v6h-6zm-18 0h6v6h-6zM26 8h6v6h-6z' }),
        _react2.default.createElement('path', { fill: '#1d9bfb', d: 'M8 8h6v6H8zm12 0h6v6h-6zm12 0h6v6h-6z' }),
        _react2.default.createElement('path', { fill: '#25fdfc', d: 'M14 8h6v6h-6zM8 32h6v6H8zm18 0h6v6h-6z' })
    );
};

exports.default = TraceTypeHeatmapIcon;

/***/ }),

/***/ "n9MJ":
/*!*****************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/dist/plotly.min.js ***!
  \*****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global) {var require;var require;/**
* plotly.js v1.45.2
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
* Licensed under the MIT license
*/
!function(t){if(true)module.exports=t();else {}}(function(){return function(){return function t(e,r,n){function i(o,s){if(!r[o]){if(!e[o]){var l="function"==typeof require&&require;if(!s&&l)return require(o,!0);if(a)return a(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var u=r[o]={exports:{}};e[o][0].call(u.exports,function(t){return i(e[o][1][t]||t)},u,u.exports,t,e,r,n)}return r[o].exports}for(var a="function"==typeof require&&require,o=0;o<n.length;o++)i(n[o]);return i}}()({1:[function(t,e,r){"use strict";var n=t("../src/lib"),i={"X,X div":"direction:ltr;font-family:'Open Sans', verdana, arial, sans-serif;margin:0;padding:0;","X input,X button":"font-family:'Open Sans', verdana, arial, sans-serif;","X input:focus,X button:focus":"outline:none;","X a":"text-decoration:none;","X a:hover":"text-decoration:none;","X .crisp":"shape-rendering:crispEdges;","X .user-select-none":"-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;","X svg":"overflow:hidden;","X svg a":"fill:#447adb;","X svg a:hover":"fill:#3c6dc5;","X .main-svg":"position:absolute;top:0;left:0;pointer-events:none;","X .main-svg .draglayer":"pointer-events:all;","X .cursor-default":"cursor:default;","X .cursor-pointer":"cursor:pointer;","X .cursor-crosshair":"cursor:crosshair;","X .cursor-move":"cursor:move;","X .cursor-col-resize":"cursor:col-resize;","X .cursor-row-resize":"cursor:row-resize;","X .cursor-ns-resize":"cursor:ns-resize;","X .cursor-ew-resize":"cursor:ew-resize;","X .cursor-sw-resize":"cursor:sw-resize;","X .cursor-s-resize":"cursor:s-resize;","X .cursor-se-resize":"cursor:se-resize;","X .cursor-w-resize":"cursor:w-resize;","X .cursor-e-resize":"cursor:e-resize;","X .cursor-nw-resize":"cursor:nw-resize;","X .cursor-n-resize":"cursor:n-resize;","X .cursor-ne-resize":"cursor:ne-resize;","X .cursor-grab":"cursor:-webkit-grab;cursor:grab;","X .modebar":"position:absolute;top:2px;right:2px;z-index:1001;","X .ease-bg":"-webkit-transition:background-color 0.3s ease 0s;-moz-transition:background-color 0.3s ease 0s;-ms-transition:background-color 0.3s ease 0s;-o-transition:background-color 0.3s ease 0s;transition:background-color 0.3s ease 0s;","X .modebar--hover>:not(.watermark)":"opacity:0;-webkit-transition:opacity 0.3s ease 0s;-moz-transition:opacity 0.3s ease 0s;-ms-transition:opacity 0.3s ease 0s;-o-transition:opacity 0.3s ease 0s;transition:opacity 0.3s ease 0s;","X:hover .modebar--hover .modebar-group":"opacity:1;","X .modebar-group":"float:left;display:inline-block;box-sizing:border-box;padding-left:8px;position:relative;vertical-align:middle;white-space:nowrap;","X .modebar-btn":"position:relative;font-size:16px;padding:3px 4px;height:22px;cursor:pointer;line-height:normal;box-sizing:border-box;","X .modebar-btn svg":"position:relative;top:2px;","X .modebar.vertical":"display:flex;flex-direction:column;flex-wrap:wrap;align-content:flex-end;max-height:100%;","X .modebar.vertical svg":"top:-1px;","X .modebar.vertical .modebar-group":"display:block;float:none;padding-left:0px;padding-bottom:8px;","X .modebar.vertical .modebar-group .modebar-btn":"display:block;text-align:center;","X [data-title]:before,X [data-title]:after":"position:absolute;-webkit-transform:translate3d(0, 0, 0);-moz-transform:translate3d(0, 0, 0);-ms-transform:translate3d(0, 0, 0);-o-transform:translate3d(0, 0, 0);transform:translate3d(0, 0, 0);display:none;opacity:0;z-index:1001;pointer-events:none;top:110%;right:50%;","X [data-title]:hover:before,X [data-title]:hover:after":"display:block;opacity:1;","X [data-title]:before":"content:'';position:absolute;background:transparent;border:6px solid transparent;z-index:1002;margin-top:-12px;border-bottom-color:#69738a;margin-right:-6px;","X [data-title]:after":"content:attr(data-title);background:#69738a;color:white;padding:8px 10px;font-size:12px;line-height:12px;white-space:nowrap;margin-right:-18px;border-radius:2px;","X .vertical [data-title]:before,X .vertical [data-title]:after":"top:0%;right:200%;","X .vertical [data-title]:before":"border:6px solid transparent;border-left-color:#69738a;margin-top:8px;margin-right:-30px;","X .select-outline":"fill:none;stroke-width:1;shape-rendering:crispEdges;","X .select-outline-1":"stroke:white;","X .select-outline-2":"stroke:black;stroke-dasharray:2px 2px;",Y:"font-family:'Open Sans';position:fixed;top:50px;right:20px;z-index:10000;font-size:10pt;max-width:180px;","Y p":"margin:0;","Y .notifier-note":"min-width:180px;max-width:250px;border:1px solid #fff;z-index:3000;margin:0;background-color:#8c97af;background-color:rgba(140,151,175,0.9);color:#fff;padding:10px;overflow-wrap:break-word;word-wrap:break-word;-ms-hyphens:auto;-webkit-hyphens:auto;hyphens:auto;","Y .notifier-close":"color:#fff;opacity:0.8;float:right;padding:0 5px;background:none;border:none;font-size:20px;font-weight:bold;line-height:20px;","Y .notifier-close:hover":"color:#444;text-decoration:none;cursor:pointer;"};for(var a in i){var o=a.replace(/^,/," ,").replace(/X/g,".js-plotly-plot .plotly").replace(/Y/g,".plotly-notifier");n.addStyleRule(o,i[a])}},{"../src/lib":697}],2:[function(t,e,r){"use strict";e.exports={undo:{width:857.1,height:1e3,path:"m857 350q0-87-34-166t-91-137-137-92-166-34q-96 0-183 41t-147 114q-4 6-4 13t5 11l76 77q6 5 14 5 9-1 13-7 41-53 100-82t126-29q58 0 110 23t92 61 61 91 22 111-22 111-61 91-92 61-110 23q-55 0-105-20t-90-57l77-77q17-16 8-38-10-23-33-23h-250q-15 0-25 11t-11 25v250q0 24 22 33 22 10 39-8l72-72q60 57 137 88t159 31q87 0 166-34t137-92 91-137 34-166z",transform:"matrix(1 0 0 -1 0 850)"},home:{width:928.6,height:1e3,path:"m786 296v-267q0-15-11-26t-25-10h-214v214h-143v-214h-214q-15 0-25 10t-11 26v267q0 1 0 2t0 2l321 264 321-264q1-1 1-4z m124 39l-34-41q-5-5-12-6h-2q-7 0-12 3l-386 322-386-322q-7-4-13-4-7 2-12 7l-35 41q-4 5-3 13t6 12l401 334q18 15 42 15t43-15l136-114v109q0 8 5 13t13 5h107q8 0 13-5t5-13v-227l122-102q5-5 6-12t-4-13z",transform:"matrix(1 0 0 -1 0 850)"},"camera-retro":{width:1e3,height:1e3,path:"m518 386q0 8-5 13t-13 5q-37 0-63-27t-26-63q0-8 5-13t13-5 12 5 5 13q0 23 16 38t38 16q8 0 13 5t5 13z m125-73q0-59-42-101t-101-42-101 42-42 101 42 101 101 42 101-42 42-101z m-572-320h858v71h-858v-71z m643 320q0 89-62 152t-152 62-151-62-63-152 63-151 151-63 152 63 62 151z m-571 358h214v72h-214v-72z m-72-107h858v143h-462l-36-71h-360v-72z m929 143v-714q0-30-21-51t-50-21h-858q-29 0-50 21t-21 51v714q0 30 21 51t50 21h858q29 0 50-21t21-51z",transform:"matrix(1 0 0 -1 0 850)"},zoombox:{width:1e3,height:1e3,path:"m1000-25l-250 251c40 63 63 138 63 218 0 224-182 406-407 406-224 0-406-182-406-406s183-406 407-406c80 0 155 22 218 62l250-250 125 125z m-812 250l0 438 437 0 0-438-437 0z m62 375l313 0 0-312-313 0 0 312z",transform:"matrix(1 0 0 -1 0 850)"},pan:{width:1e3,height:1e3,path:"m1000 350l-187 188 0-125-250 0 0 250 125 0-188 187-187-187 125 0 0-250-250 0 0 125-188-188 186-187 0 125 252 0 0-250-125 0 187-188 188 188-125 0 0 250 250 0 0-126 187 188z",transform:"matrix(1 0 0 -1 0 850)"},zoom_plus:{width:875,height:1e3,path:"m1 787l0-875 875 0 0 875-875 0z m687-500l-187 0 0-187-125 0 0 187-188 0 0 125 188 0 0 187 125 0 0-187 187 0 0-125z",transform:"matrix(1 0 0 -1 0 850)"},zoom_minus:{width:875,height:1e3,path:"m0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z",transform:"matrix(1 0 0 -1 0 850)"},autoscale:{width:1e3,height:1e3,path:"m250 850l-187 0-63 0 0-62 0-188 63 0 0 188 187 0 0 62z m688 0l-188 0 0-62 188 0 0-188 62 0 0 188 0 62-62 0z m-875-938l0 188-63 0 0-188 0-62 63 0 187 0 0 62-187 0z m875 188l0-188-188 0 0-62 188 0 62 0 0 62 0 188-62 0z m-125 188l-1 0-93-94-156 156 156 156 92-93 2 0 0 250-250 0 0-2 93-92-156-156-156 156 94 92 0 2-250 0 0-250 0 0 93 93 157-156-157-156-93 94 0 0 0-250 250 0 0 0-94 93 156 157 156-157-93-93 0 0 250 0 0 250z",transform:"matrix(1 0 0 -1 0 850)"},tooltip_basic:{width:1500,height:1e3,path:"m375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z",transform:"matrix(1 0 0 -1 0 850)"},tooltip_compare:{width:1125,height:1e3,path:"m187 786l0 2-187-188 188-187 0 0 937 0 0 373-938 0z m0-499l0 1-187-188 188-188 0 0 937 0 0 376-938-1z",transform:"matrix(1 0 0 -1 0 850)"},plotlylogo:{width:1542,height:1e3,path:"m0-10h182v-140h-182v140z m228 146h183v-286h-183v286z m225 714h182v-1000h-182v1000z m225-285h182v-715h-182v715z m225 142h183v-857h-183v857z m231-428h182v-429h-182v429z m225-291h183v-138h-183v138z",transform:"matrix(1 0 0 -1 0 850)"},"z-axis":{width:1e3,height:1e3,path:"m833 5l-17 108v41l-130-65 130-66c0 0 0 38 0 39 0-1 36-14 39-25 4-15-6-22-16-30-15-12-39-16-56-20-90-22-187-23-279-23-261 0-341 34-353 59 3 60 228 110 228 110-140-8-351-35-351-116 0-120 293-142 474-142 155 0 477 22 477 142 0 50-74 79-163 96z m-374 94c-58-5-99-21-99-40 0-24 65-43 144-43 79 0 143 19 143 43 0 19-42 34-98 40v216h87l-132 135-133-135h88v-216z m167 515h-136v1c16 16 31 34 46 52l84 109v54h-230v-71h124v-1c-16-17-28-32-44-51l-89-114v-51h245v72z",transform:"matrix(1 0 0 -1 0 850)"},"3d_rotate":{width:1e3,height:1e3,path:"m922 660c-5 4-9 7-14 11-359 263-580-31-580-31l-102 28 58-400c0 1 1 1 2 2 118 108 351 249 351 249s-62 27-100 42c88 83 222 183 347 122 16-8 30-17 44-27-2 1-4 2-6 4z m36-329c0 0 64 229-88 296-62 27-124 14-175-11 157-78 225-208 249-266 8-19 11-31 11-31 2 5 6 15 11 32-5-13-8-20-8-20z m-775-239c70-31 117-50 198-32-121 80-199 346-199 346l-96-15-58-12c0 0 55-226 155-287z m603 133l-317-139c0 0 4-4 19-14 7-5 24-15 24-15s-177-147-389 4c235-287 536-112 536-112l31-22 100 299-4-1z m-298-153c6-4 14-9 24-15 0 0-17 10-24 15z",transform:"matrix(1 0 0 -1 0 850)"},camera:{width:1e3,height:1e3,path:"m500 450c-83 0-150-67-150-150 0-83 67-150 150-150 83 0 150 67 150 150 0 83-67 150-150 150z m400 150h-120c-16 0-34 13-39 29l-31 93c-6 15-23 28-40 28h-340c-16 0-34-13-39-28l-31-94c-6-15-23-28-40-28h-120c-55 0-100-45-100-100v-450c0-55 45-100 100-100h800c55 0 100 45 100 100v450c0 55-45 100-100 100z m-400-550c-138 0-250 112-250 250 0 138 112 250 250 250 138 0 250-112 250-250 0-138-112-250-250-250z m365 380c-19 0-35 16-35 35 0 19 16 35 35 35 19 0 35-16 35-35 0-19-16-35-35-35z",transform:"matrix(1 0 0 -1 0 850)"},movie:{width:1e3,height:1e3,path:"m938 413l-188-125c0 37-17 71-44 94 64 38 107 107 107 187 0 121-98 219-219 219-121 0-219-98-219-219 0-61 25-117 66-156h-115c30 33 49 76 49 125 0 103-84 187-187 187s-188-84-188-187c0-57 26-107 65-141-38-22-65-62-65-109v-250c0-70 56-126 125-126h500c69 0 125 56 125 126l188-126c34 0 62 28 62 63v375c0 35-28 63-62 63z m-750 0c-69 0-125 56-125 125s56 125 125 125 125-56 125-125-56-125-125-125z m406-1c-87 0-157 70-157 157 0 86 70 156 157 156s156-70 156-156-70-157-156-157z",transform:"matrix(1 0 0 -1 0 850)"},question:{width:857.1,height:1e3,path:"m500 82v107q0 8-5 13t-13 5h-107q-8 0-13-5t-5-13v-107q0-8 5-13t13-5h107q8 0 13 5t5 13z m143 375q0 49-31 91t-77 65-95 23q-136 0-207-119-9-14 4-24l74-55q4-4 10-4 9 0 14 7 30 38 48 51 19 14 48 14 27 0 48-15t21-33q0-21-11-34t-38-25q-35-16-65-48t-29-70v-20q0-8 5-13t13-5h107q8 0 13 5t5 13q0 10 12 27t30 28q18 10 28 16t25 19 25 27 16 34 7 45z m214-107q0-117-57-215t-156-156-215-58-216 58-155 156-58 215 58 215 155 156 216 58 215-58 156-156 57-215z",transform:"matrix(1 0 0 -1 0 850)"},disk:{width:857.1,height:1e3,path:"m214-7h429v214h-429v-214z m500 0h72v500q0 8-6 21t-11 20l-157 156q-5 6-19 12t-22 5v-232q0-22-15-38t-38-16h-322q-22 0-37 16t-16 38v232h-72v-714h72v232q0 22 16 38t37 16h465q22 0 38-16t15-38v-232z m-214 518v178q0 8-5 13t-13 5h-107q-7 0-13-5t-5-13v-178q0-8 5-13t13-5h107q7 0 13 5t5 13z m357-18v-518q0-22-15-38t-38-16h-750q-23 0-38 16t-16 38v750q0 22 16 38t38 16h517q23 0 50-12t42-26l156-157q16-15 27-42t11-49z",transform:"matrix(1 0 0 -1 0 850)"},lasso:{width:1031,height:1e3,path:"m1018 538c-36 207-290 336-568 286-277-48-473-256-436-463 10-57 36-108 76-151-13-66 11-137 68-183 34-28 75-41 114-42l-55-70 0 0c-2-1-3-2-4-3-10-14-8-34 5-45 14-11 34-8 45 4 1 1 2 3 2 5l0 0 113 140c16 11 31 24 45 40 4 3 6 7 8 11 48-3 100 0 151 9 278 48 473 255 436 462z m-624-379c-80 14-149 48-197 96 42 42 109 47 156 9 33-26 47-66 41-105z m-187-74c-19 16-33 37-39 60 50-32 109-55 174-68-42-25-95-24-135 8z m360 75c-34-7-69-9-102-8 8 62-16 128-68 170-73 59-175 54-244-5-9 20-16 40-20 61-28 159 121 317 333 354s407-60 434-217c28-159-121-318-333-355z",transform:"matrix(1 0 0 -1 0 850)"},selectbox:{width:1e3,height:1e3,path:"m0 850l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-285l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z",transform:"matrix(1 0 0 -1 0 850)"},spikeline:{width:1e3,height:1e3,path:"M512 409c0-57-46-104-103-104-57 0-104 47-104 104 0 57 47 103 104 103 57 0 103-46 103-103z m-327-39l92 0 0 92-92 0z m-185 0l92 0 0 92-92 0z m370-186l92 0 0 93-92 0z m0-184l92 0 0 92-92 0z",transform:"matrix(1.5 0 0 -1.5 0 850)"},newplotlylogo:{name:"newplotlylogo",svg:"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 132 132'><defs><style>.cls-1 {fill: #119dff;} .cls-2 {fill: #25fefd;} .cls-3 {fill: #fff;}</style></defs><title>plotly-logomark</title><g id='symbol'><rect class='cls-1' width='132' height='132' rx='6' ry='6'/><circle class='cls-2' cx='78' cy='54' r='6'/><circle class='cls-2' cx='102' cy='30' r='6'/><circle class='cls-2' cx='78' cy='30' r='6'/><circle class='cls-2' cx='54' cy='30' r='6'/><circle class='cls-2' cx='30' cy='30' r='6'/><circle class='cls-2' cx='30' cy='54' r='6'/><path class='cls-3' d='M30,72a6,6,0,0,0-6,6v24a6,6,0,0,0,12,0V78A6,6,0,0,0,30,72Z'/><path class='cls-3' d='M78,72a6,6,0,0,0-6,6v24a6,6,0,0,0,12,0V78A6,6,0,0,0,78,72Z'/><path class='cls-3' d='M54,48a6,6,0,0,0-6,6v48a6,6,0,0,0,12,0V54A6,6,0,0,0,54,48Z'/><path class='cls-3' d='M102,48a6,6,0,0,0-6,6v48a6,6,0,0,0,12,0V54A6,6,0,0,0,102,48Z'/></g></svg>"}}},{}],3:[function(t,e,r){"use strict";e.exports=t("../src/transforms/aggregate")},{"../src/transforms/aggregate":1160}],4:[function(t,e,r){"use strict";e.exports=t("../src/traces/bar")},{"../src/traces/bar":843}],5:[function(t,e,r){"use strict";e.exports=t("../src/traces/barpolar")},{"../src/traces/barpolar":855}],6:[function(t,e,r){"use strict";e.exports=t("../src/traces/box")},{"../src/traces/box":865}],7:[function(t,e,r){"use strict";e.exports=t("../src/components/calendars")},{"../src/components/calendars":572}],8:[function(t,e,r){"use strict";e.exports=t("../src/traces/candlestick")},{"../src/traces/candlestick":874}],9:[function(t,e,r){"use strict";e.exports=t("../src/traces/carpet")},{"../src/traces/carpet":893}],10:[function(t,e,r){"use strict";e.exports=t("../src/traces/choropleth")},{"../src/traces/choropleth":907}],11:[function(t,e,r){"use strict";e.exports=t("../src/traces/cone")},{"../src/traces/cone":915}],12:[function(t,e,r){"use strict";e.exports=t("../src/traces/contour")},{"../src/traces/contour":930}],13:[function(t,e,r){"use strict";e.exports=t("../src/traces/contourcarpet")},{"../src/traces/contourcarpet":941}],14:[function(t,e,r){"use strict";e.exports=t("../src/core")},{"../src/core":676}],15:[function(t,e,r){"use strict";e.exports=t("../src/transforms/filter")},{"../src/transforms/filter":1161}],16:[function(t,e,r){"use strict";e.exports=t("../src/transforms/groupby")},{"../src/transforms/groupby":1162}],17:[function(t,e,r){"use strict";e.exports=t("../src/traces/heatmap")},{"../src/traces/heatmap":953}],18:[function(t,e,r){"use strict";e.exports=t("../src/traces/heatmapgl")},{"../src/traces/heatmapgl":962}],19:[function(t,e,r){"use strict";e.exports=t("../src/traces/histogram")},{"../src/traces/histogram":974}],20:[function(t,e,r){"use strict";e.exports=t("../src/traces/histogram2d")},{"../src/traces/histogram2d":981}],21:[function(t,e,r){"use strict";e.exports=t("../src/traces/histogram2dcontour")},{"../src/traces/histogram2dcontour":985}],22:[function(t,e,r){"use strict";var n=t("./core");n.register([t("./bar"),t("./box"),t("./heatmap"),t("./histogram"),t("./histogram2d"),t("./histogram2dcontour"),t("./pie"),t("./contour"),t("./scatterternary"),t("./violin"),t("./scatter3d"),t("./surface"),t("./isosurface"),t("./mesh3d"),t("./cone"),t("./streamtube"),t("./scattergeo"),t("./choropleth"),t("./scattergl"),t("./splom"),t("./pointcloud"),t("./heatmapgl"),t("./parcoords"),t("./parcats"),t("./scattermapbox"),t("./sankey"),t("./table"),t("./carpet"),t("./scattercarpet"),t("./contourcarpet"),t("./ohlc"),t("./candlestick"),t("./scatterpolar"),t("./scatterpolargl"),t("./barpolar")]),n.register([t("./aggregate"),t("./filter"),t("./groupby"),t("./sort")]),n.register([t("./calendars")]),e.exports=n},{"./aggregate":3,"./bar":4,"./barpolar":5,"./box":6,"./calendars":7,"./candlestick":8,"./carpet":9,"./choropleth":10,"./cone":11,"./contour":12,"./contourcarpet":13,"./core":14,"./filter":15,"./groupby":16,"./heatmap":17,"./heatmapgl":18,"./histogram":19,"./histogram2d":20,"./histogram2dcontour":21,"./isosurface":23,"./mesh3d":24,"./ohlc":25,"./parcats":26,"./parcoords":27,"./pie":28,"./pointcloud":29,"./sankey":30,"./scatter3d":31,"./scattercarpet":32,"./scattergeo":33,"./scattergl":34,"./scattermapbox":35,"./scatterpolar":36,"./scatterpolargl":37,"./scatterternary":38,"./sort":39,"./splom":40,"./streamtube":41,"./surface":42,"./table":43,"./violin":44}],23:[function(t,e,r){"use strict";e.exports=t("../src/traces/isosurface")},{"../src/traces/isosurface":990}],24:[function(t,e,r){"use strict";e.exports=t("../src/traces/mesh3d")},{"../src/traces/mesh3d":995}],25:[function(t,e,r){"use strict";e.exports=t("../src/traces/ohlc")},{"../src/traces/ohlc":1e3}],26:[function(t,e,r){"use strict";e.exports=t("../src/traces/parcats")},{"../src/traces/parcats":1009}],27:[function(t,e,r){"use strict";e.exports=t("../src/traces/parcoords")},{"../src/traces/parcoords":1018}],28:[function(t,e,r){"use strict";e.exports=t("../src/traces/pie")},{"../src/traces/pie":1029}],29:[function(t,e,r){"use strict";e.exports=t("../src/traces/pointcloud")},{"../src/traces/pointcloud":1038}],30:[function(t,e,r){"use strict";e.exports=t("../src/traces/sankey")},{"../src/traces/sankey":1044}],31:[function(t,e,r){"use strict";e.exports=t("../src/traces/scatter3d")},{"../src/traces/scatter3d":1080}],32:[function(t,e,r){"use strict";e.exports=t("../src/traces/scattercarpet")},{"../src/traces/scattercarpet":1086}],33:[function(t,e,r){"use strict";e.exports=t("../src/traces/scattergeo")},{"../src/traces/scattergeo":1093}],34:[function(t,e,r){"use strict";e.exports=t("../src/traces/scattergl")},{"../src/traces/scattergl":1101}],35:[function(t,e,r){"use strict";e.exports=t("../src/traces/scattermapbox")},{"../src/traces/scattermapbox":1107}],36:[function(t,e,r){"use strict";e.exports=t("../src/traces/scatterpolar")},{"../src/traces/scatterpolar":1114}],37:[function(t,e,r){"use strict";e.exports=t("../src/traces/scatterpolargl")},{"../src/traces/scatterpolargl":1118}],38:[function(t,e,r){"use strict";e.exports=t("../src/traces/scatterternary")},{"../src/traces/scatterternary":1124}],39:[function(t,e,r){"use strict";e.exports=t("../src/transforms/sort")},{"../src/transforms/sort":1164}],40:[function(t,e,r){"use strict";e.exports=t("../src/traces/splom")},{"../src/traces/splom":1129}],41:[function(t,e,r){"use strict";e.exports=t("../src/traces/streamtube")},{"../src/traces/streamtube":1134}],42:[function(t,e,r){"use strict";e.exports=t("../src/traces/surface")},{"../src/traces/surface":1139}],43:[function(t,e,r){"use strict";e.exports=t("../src/traces/table")},{"../src/traces/table":1147}],44:[function(t,e,r){"use strict";e.exports=t("../src/traces/violin")},{"../src/traces/violin":1155}],45:[function(t,e,r){"use strict";e.exports=function(t){var e=(t=t||{}).eye||[0,0,1],r=t.center||[0,0,0],s=t.up||[0,1,0],l=t.distanceLimits||[0,1/0],c=t.mode||"turntable",u=n(),h=i(),f=a();return u.setDistanceLimits(l[0],l[1]),u.lookAt(0,e,r,s),h.setDistanceLimits(l[0],l[1]),h.lookAt(0,e,r,s),f.setDistanceLimits(l[0],l[1]),f.lookAt(0,e,r,s),new o({turntable:u,orbit:h,matrix:f},c)};var n=t("turntable-camera-controller"),i=t("orbit-camera-controller"),a=t("matrix-camera-controller");function o(t,e){this._controllerNames=Object.keys(t),this._controllerList=this._controllerNames.map(function(e){return t[e]}),this._mode=e,this._active=t[e],this._active||(this._mode="turntable",this._active=t.turntable),this.modes=this._controllerNames,this.computedMatrix=this._active.computedMatrix,this.computedEye=this._active.computedEye,this.computedUp=this._active.computedUp,this.computedCenter=this._active.computedCenter,this.computedRadius=this._active.computedRadius}var s=o.prototype;[["flush",1],["idle",1],["lookAt",4],["rotate",4],["pan",4],["translate",4],["setMatrix",2],["setDistanceLimits",2],["setDistance",2]].forEach(function(t){for(var e=t[0],r=[],n=0;n<t[1];++n)r.push("a"+n);var i="var cc=this._controllerList;for(var i=0;i<cc.length;++i){cc[i]."+t[0]+"("+r.join()+")}";s[e]=Function.apply(null,r.concat(i))}),s.recalcMatrix=function(t){this._active.recalcMatrix(t)},s.getDistance=function(t){return this._active.getDistance(t)},s.getDistanceLimits=function(t){return this._active.getDistanceLimits(t)},s.lastT=function(){return this._active.lastT()},s.setMode=function(t){if(t!==this._mode){var e=this._controllerNames.indexOf(t);if(!(e<0)){var r=this._active,n=this._controllerList[e],i=Math.max(r.lastT(),n.lastT());r.recalcMatrix(i),n.setMatrix(i,r.computedMatrix),this._active=n,this._mode=t,this.computedMatrix=this._active.computedMatrix,this.computedEye=this._active.computedEye,this.computedUp=this._active.computedUp,this.computedCenter=this._active.computedCenter,this.computedRadius=this._active.computedRadius}}},s.getMode=function(){return this._mode}},{"matrix-camera-controller":422,"orbit-camera-controller":445,"turntable-camera-controller":523}],46:[function(t,e,r){var n,i;n=this,i=function(t,e,r,n){"use strict";function i(t){return t.target.depth}function a(t,e){return t.sourceLinks.length?t.depth:e-1}function o(t){return function(){return t}}function s(t,e){return c(t.source,e.source)||t.index-e.index}function l(t,e){return c(t.target,e.target)||t.index-e.index}function c(t,e){return t.y0-e.y0}function u(t){return t.value}function h(t){return(t.y0+t.y1)/2}function f(t){return h(t.source)*t.value}function p(t){return h(t.target)*t.value}function d(t){return t.index}function g(t){return t.nodes}function v(t){return t.links}function m(t,e){var r=t.get(e);if(!r)throw new Error("missing: "+e);return r}function y(t){return[t.source.x1,t.y0]}function x(t){return[t.target.x0,t.y1]}t.sankey=function(){var t=0,n=0,i=1,y=1,x=24,b=8,_=d,w=a,k=g,A=v,M=32,T=2/3;function S(){var a={nodes:k.apply(null,arguments),links:A.apply(null,arguments)};return function(t){t.nodes.forEach(function(t,e){t.index=e,t.sourceLinks=[],t.targetLinks=[]});var e=r.map(t.nodes,_);t.links.forEach(function(t,r){t.index=r;var n=t.source,i=t.target;"object"!=typeof n&&(n=t.source=m(e,n)),"object"!=typeof i&&(i=t.target=m(e,i)),n.sourceLinks.push(t),i.targetLinks.push(t)})}(a),function(t){t.nodes.forEach(function(t){t.value=Math.max(e.sum(t.sourceLinks,u),e.sum(t.targetLinks,u))})}(a),function(e){var r,n,a;for(r=e.nodes,n=[],a=0;r.length;++a,r=n,n=[])r.forEach(function(t){t.depth=a,t.sourceLinks.forEach(function(t){n.indexOf(t.target)<0&&n.push(t.target)})});for(r=e.nodes,n=[],a=0;r.length;++a,r=n,n=[])r.forEach(function(t){t.height=a,t.targetLinks.forEach(function(t){n.indexOf(t.source)<0&&n.push(t.source)})});var o=(i-t-x)/(a-1);e.nodes.forEach(function(e){e.x1=(e.x0=t+Math.max(0,Math.min(a-1,Math.floor(w.call(null,e,a))))*o)+x})}(a),function(t){var i=r.nest().key(function(t){return t.x0}).sortKeys(e.ascending).entries(t.nodes).map(function(t){return t.values});(function(){var r=e.max(i,function(t){return t.length}),a=T*(y-n)/(r-1);b>a&&(b=a);var o=e.min(i,function(t){return(y-n-(t.length-1)*b)/e.sum(t,u)});i.forEach(function(t){t.forEach(function(t,e){t.y1=(t.y0=e)+t.value*o})}),t.links.forEach(function(t){t.width=t.value*o})})(),d();for(var a=1,o=M;o>0;--o)l(a*=.99),d(),s(a),d();function s(t){i.forEach(function(r){r.forEach(function(r){if(r.targetLinks.length){var n=(e.sum(r.targetLinks,f)/e.sum(r.targetLinks,u)-h(r))*t;r.y0+=n,r.y1+=n}})})}function l(t){i.slice().reverse().forEach(function(r){r.forEach(function(r){if(r.sourceLinks.length){var n=(e.sum(r.sourceLinks,p)/e.sum(r.sourceLinks,u)-h(r))*t;r.y0+=n,r.y1+=n}})})}function d(){i.forEach(function(t){var e,r,i,a=n,o=t.length;for(t.sort(c),i=0;i<o;++i)e=t[i],(r=a-e.y0)>0&&(e.y0+=r,e.y1+=r),a=e.y1+b;if((r=a-b-y)>0)for(a=e.y0-=r,e.y1-=r,i=o-2;i>=0;--i)e=t[i],(r=e.y1+b-a)>0&&(e.y0-=r,e.y1-=r),a=e.y0})}}(a),E(a),a}function E(t){t.nodes.forEach(function(t){t.sourceLinks.sort(l),t.targetLinks.sort(s)}),t.nodes.forEach(function(t){var e=t.y0,r=e;t.sourceLinks.forEach(function(t){t.y0=e+t.width/2,e+=t.width}),t.targetLinks.forEach(function(t){t.y1=r+t.width/2,r+=t.width})})}return S.update=function(t){return E(t),t},S.nodeId=function(t){return arguments.length?(_="function"==typeof t?t:o(t),S):_},S.nodeAlign=function(t){return arguments.length?(w="function"==typeof t?t:o(t),S):w},S.nodeWidth=function(t){return arguments.length?(x=+t,S):x},S.nodePadding=function(t){return arguments.length?(b=+t,S):b},S.nodes=function(t){return arguments.length?(k="function"==typeof t?t:o(t),S):k},S.links=function(t){return arguments.length?(A="function"==typeof t?t:o(t),S):A},S.size=function(e){return arguments.length?(t=n=0,i=+e[0],y=+e[1],S):[i-t,y-n]},S.extent=function(e){return arguments.length?(t=+e[0][0],i=+e[1][0],n=+e[0][1],y=+e[1][1],S):[[t,n],[i,y]]},S.iterations=function(t){return arguments.length?(M=+t,S):M},S},t.sankeyCenter=function(t){return t.targetLinks.length?t.depth:t.sourceLinks.length?e.min(t.sourceLinks,i)-1:0},t.sankeyLeft=function(t){return t.depth},t.sankeyRight=function(t,e){return e-1-t.height},t.sankeyJustify=a,t.sankeyLinkHorizontal=function(){return n.linkHorizontal().source(y).target(x)},Object.defineProperty(t,"__esModule",{value:!0})},"object"==typeof r&&"undefined"!=typeof e?i(r,t("d3-array"),t("d3-collection"),t("d3-shape")):i(n.d3=n.d3||{},n.d3,n.d3,n.d3)},{"d3-array":140,"d3-collection":141,"d3-shape":149}],47:[function(t,e,r){"use strict";var n="undefined"==typeof WeakMap?t("weak-map"):WeakMap,i=t("gl-buffer"),a=t("gl-vao"),o=new n;e.exports=function(t){var e=o.get(t),r=e&&(e._triangleBuffer.handle||e._triangleBuffer.buffer);if(!r||!t.isBuffer(r)){var n=i(t,new Float32Array([-1,-1,-1,4,4,-1]));(e=a(t,[{buffer:n,type:t.FLOAT,size:2}]))._triangleBuffer=n,o.set(t,e)}e.bind(),t.drawArrays(t.TRIANGLES,0,3),e.unbind()}},{"gl-buffer":234,"gl-vao":316,"weak-map":533}],48:[function(t,e,r){e.exports=function(t){var e=0,r=0,n=0,i=0;return t.map(function(t){var a=(t=t.slice())[0],o=a.toUpperCase();if(a!=o)switch(t[0]=o,a){case"a":t[6]+=n,t[7]+=i;break;case"v":t[1]+=i;break;case"h":t[1]+=n;break;default:for(var s=1;s<t.length;)t[s++]+=n,t[s++]+=i}switch(o){case"Z":n=e,i=r;break;case"H":n=t[1];break;case"V":i=t[1];break;case"M":n=e=t[1],i=r=t[2];break;default:n=t[t.length-2],i=t[t.length-1]}return t})}},{}],49:[function(t,e,r){var n=t("pad-left");e.exports=function(t,e,r){e="number"==typeof e?e:1,r=r||": ";var i=t.split(/\r?\n/),a=String(i.length+e-1).length;return i.map(function(t,i){var o=i+e,s=String(o).length,l=n(o,a-s);return l+r+t}).join("\n")}},{"pad-left":446}],50:[function(t,e,r){"use strict";e.exports=function(t){var e=t.length;if(0===e)return[];if(1===e)return[0];for(var r=t[0].length,n=[t[0]],a=[0],o=1;o<e;++o)if(n.push(t[o]),i(n,r)){if(a.push(o),a.length===r+1)return a}else n.pop();return a};var n=t("robust-orientation");function i(t,e){for(var r=new Array(e+1),i=0;i<t.length;++i)r[i]=t[i];for(i=0;i<=t.length;++i){for(var a=t.length;a<=e;++a){for(var o=new Array(e),s=0;s<e;++s)o[s]=Math.pow(a+1-i,s);r[a]=o}if(n.apply(void 0,r))return!0}return!1}},{"robust-orientation":491}],51:[function(t,e,r){"use strict";e.exports=function(t,e){return n(e).filter(function(r){for(var n=new Array(r.length),a=0;a<r.length;++a)n[a]=e[r[a]];return i(n)*t<1})};var n=t("delaunay-triangulate"),i=t("circumradius")},{circumradius:102,"delaunay-triangulate":153}],52:[function(t,e,r){e.exports=function(t,e){return i(n(t,e))};var n=t("alpha-complex"),i=t("simplicial-complex-boundary")},{"alpha-complex":51,"simplicial-complex-boundary":498}],53:[function(t,e,r){"use strict";e.exports=function(t,e){if(!t||null==t.length)throw Error("Argument should be an array");e=null==e?1:Math.floor(e);for(var r=Array(2*e),n=0;n<e;n++){for(var i=-1/0,a=1/0,o=n,s=t.length;o<s;o+=e)t[o]>i&&(i=t[o]),t[o]<a&&(a=t[o]);r[n]=a,r[e+n]=i}return r}},{}],54:[function(t,e,r){"use strict";var n=t("array-bounds");e.exports=function(t,e,r){if(!t||null==t.length)throw Error("Argument should be an array");null==e&&(e=1);null==r&&(r=n(t,e));for(var i=0;i<e;i++){var a=r[e+i],o=r[i],s=i,l=t.length;if(a===1/0&&o===-1/0)for(s=i;s<l;s+=e)t[s]=t[s]===a?1:t[s]===o?0:.5;else if(a===1/0)for(s=i;s<l;s+=e)t[s]=t[s]===a?1:0;else if(o===-1/0)for(s=i;s<l;s+=e)t[s]=t[s]===o?0:1;else{var c=a-o;for(s=i;s<l;s+=e)t[s]=0===c?.5:(t[s]-o)/c}}return t}},{"array-bounds":53}],55:[function(t,e,r){e.exports=function(t,e){var r="number"==typeof t,n="number"==typeof e;r&&!n?(e=t,t=0):r||n||(t=0,e=0);var i=(e|=0)-(t|=0);if(i<0)throw new Error("array length must be positive");for(var a=new Array(i),o=0,s=t;o<i;o++,s++)a[o]=s;return a}},{}],56:[function(t,e,r){(function(r){"use strict";function n(t,e){if(t===e)return 0;for(var r=t.length,n=e.length,i=0,a=Math.min(r,n);i<a;++i)if(t[i]!==e[i]){r=t[i],n=e[i];break}return r<n?-1:n<r?1:0}function i(t){return r.Buffer&&"function"==typeof r.Buffer.isBuffer?r.Buffer.isBuffer(t):!(null==t||!t._isBuffer)}var a=t("util/"),o=Object.prototype.hasOwnProperty,s=Array.prototype.slice,l="foo"===function(){}.name;function c(t){return Object.prototype.toString.call(t)}function u(t){return!i(t)&&("function"==typeof r.ArrayBuffer&&("function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):!!t&&(t instanceof DataView||!!(t.buffer&&t.buffer instanceof ArrayBuffer))))}var h=e.exports=m,f=/\s*function\s+([^\(\s]*)\s*/;function p(t){if(a.isFunction(t)){if(l)return t.name;var e=t.toString().match(f);return e&&e[1]}}function d(t,e){return"string"==typeof t?t.length<e?t:t.slice(0,e):t}function g(t){if(l||!a.isFunction(t))return a.inspect(t);var e=p(t);return"[Function"+(e?": "+e:"")+"]"}function v(t,e,r,n,i){throw new h.AssertionError({message:r,actual:t,expected:e,operator:n,stackStartFunction:i})}function m(t,e){t||v(t,!0,e,"==",h.ok)}function y(t,e,r,o){if(t===e)return!0;if(i(t)&&i(e))return 0===n(t,e);if(a.isDate(t)&&a.isDate(e))return t.getTime()===e.getTime();if(a.isRegExp(t)&&a.isRegExp(e))return t.source===e.source&&t.global===e.global&&t.multiline===e.multiline&&t.lastIndex===e.lastIndex&&t.ignoreCase===e.ignoreCase;if(null!==t&&"object"==typeof t||null!==e&&"object"==typeof e){if(u(t)&&u(e)&&c(t)===c(e)&&!(t instanceof Float32Array||t instanceof Float64Array))return 0===n(new Uint8Array(t.buffer),new Uint8Array(e.buffer));if(i(t)!==i(e))return!1;var l=(o=o||{actual:[],expected:[]}).actual.indexOf(t);return-1!==l&&l===o.expected.indexOf(e)||(o.actual.push(t),o.expected.push(e),function(t,e,r,n){if(null==t||null==e)return!1;if(a.isPrimitive(t)||a.isPrimitive(e))return t===e;if(r&&Object.getPrototypeOf(t)!==Object.getPrototypeOf(e))return!1;var i=x(t),o=x(e);if(i&&!o||!i&&o)return!1;if(i)return t=s.call(t),e=s.call(e),y(t,e,r);var l,c,u=w(t),h=w(e);if(u.length!==h.length)return!1;for(u.sort(),h.sort(),c=u.length-1;c>=0;c--)if(u[c]!==h[c])return!1;for(c=u.length-1;c>=0;c--)if(l=u[c],!y(t[l],e[l],r,n))return!1;return!0}(t,e,r,o))}return r?t===e:t==e}function x(t){return"[object Arguments]"==Object.prototype.toString.call(t)}function b(t,e){if(!t||!e)return!1;if("[object RegExp]"==Object.prototype.toString.call(e))return e.test(t);try{if(t instanceof e)return!0}catch(t){}return!Error.isPrototypeOf(e)&&!0===e.call({},t)}function _(t,e,r,n){var i;if("function"!=typeof e)throw new TypeError('"block" argument must be a function');"string"==typeof r&&(n=r,r=null),i=function(t){var e;try{t()}catch(t){e=t}return e}(e),n=(r&&r.name?" ("+r.name+").":".")+(n?" "+n:"."),t&&!i&&v(i,r,"Missing expected exception"+n);var o="string"==typeof n,s=!t&&i&&!r;if((!t&&a.isError(i)&&o&&b(i,r)||s)&&v(i,r,"Got unwanted exception"+n),t&&i&&r&&!b(i,r)||!t&&i)throw i}h.AssertionError=function(t){var e;this.name="AssertionError",this.actual=t.actual,this.expected=t.expected,this.operator=t.operator,t.message?(this.message=t.message,this.generatedMessage=!1):(this.message=d(g((e=this).actual),128)+" "+e.operator+" "+d(g(e.expected),128),this.generatedMessage=!0);var r=t.stackStartFunction||v;if(Error.captureStackTrace)Error.captureStackTrace(this,r);else{var n=new Error;if(n.stack){var i=n.stack,a=p(r),o=i.indexOf("\n"+a);if(o>=0){var s=i.indexOf("\n",o+1);i=i.substring(s+1)}this.stack=i}}},a.inherits(h.AssertionError,Error),h.fail=v,h.ok=m,h.equal=function(t,e,r){t!=e&&v(t,e,r,"==",h.equal)},h.notEqual=function(t,e,r){t==e&&v(t,e,r,"!=",h.notEqual)},h.deepEqual=function(t,e,r){y(t,e,!1)||v(t,e,r,"deepEqual",h.deepEqual)},h.deepStrictEqual=function(t,e,r){y(t,e,!0)||v(t,e,r,"deepStrictEqual",h.deepStrictEqual)},h.notDeepEqual=function(t,e,r){y(t,e,!1)&&v(t,e,r,"notDeepEqual",h.notDeepEqual)},h.notDeepStrictEqual=function t(e,r,n){y(e,r,!0)&&v(e,r,n,"notDeepStrictEqual",t)},h.strictEqual=function(t,e,r){t!==e&&v(t,e,r,"===",h.strictEqual)},h.notStrictEqual=function(t,e,r){t===e&&v(t,e,r,"!==",h.notStrictEqual)},h.throws=function(t,e,r){_(!0,t,e,r)},h.doesNotThrow=function(t,e,r){_(!1,t,e,r)},h.ifError=function(t){if(t)throw t};var w=Object.keys||function(t){var e=[];for(var r in t)o.call(t,r)&&e.push(r);return e}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"util/":59}],57:[function(t,e,r){"function"==typeof Object.create?e.exports=function(t,e){t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:e.exports=function(t,e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}},{}],58:[function(t,e,r){e.exports=function(t){return t&&"object"==typeof t&&"function"==typeof t.copy&&"function"==typeof t.fill&&"function"==typeof t.readUInt8}},{}],59:[function(t,e,r){(function(e,n){var i=/%[sdj%]/g;r.format=function(t){if(!m(t)){for(var e=[],r=0;r<arguments.length;r++)e.push(s(arguments[r]));return e.join(" ")}r=1;for(var n=arguments,a=n.length,o=String(t).replace(i,function(t){if("%%"===t)return"%";if(r>=a)return t;switch(t){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(t){return"[Circular]"}default:return t}}),l=n[r];r<a;l=n[++r])g(l)||!b(l)?o+=" "+l:o+=" "+s(l);return o},r.deprecate=function(t,i){if(y(n.process))return function(){return r.deprecate(t,i).apply(this,arguments)};if(!0===e.noDeprecation)return t;var a=!1;return function(){if(!a){if(e.throwDeprecation)throw new Error(i);e.traceDeprecation?console.trace(i):console.error(i),a=!0}return t.apply(this,arguments)}};var a,o={};function s(t,e){var n={seen:[],stylize:c};return arguments.length>=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),d(e)?n.showHidden=e:e&&r._extend(n,e),y(n.showHidden)&&(n.showHidden=!1),y(n.depth)&&(n.depth=2),y(n.colors)&&(n.colors=!1),y(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=l),u(n,t,n.depth)}function l(t,e){var r=s.styles[e];return r?"\x1b["+s.colors[r][0]+"m"+t+"\x1b["+s.colors[r][1]+"m":t}function c(t,e){return t}function u(t,e,n){if(t.customInspect&&e&&k(e.inspect)&&e.inspect!==r.inspect&&(!e.constructor||e.constructor.prototype!==e)){var i=e.inspect(n,t);return m(i)||(i=u(t,i,n)),i}var a=function(t,e){if(y(e))return t.stylize("undefined","undefined");if(m(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(v(e))return t.stylize(""+e,"number");if(d(e))return t.stylize(""+e,"boolean");if(g(e))return t.stylize("null","null")}(t,e);if(a)return a;var o=Object.keys(e),s=function(t){var e={};return t.forEach(function(t,r){e[t]=!0}),e}(o);if(t.showHidden&&(o=Object.getOwnPropertyNames(e)),w(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return h(e);if(0===o.length){if(k(e)){var l=e.name?": "+e.name:"";return t.stylize("[Function"+l+"]","special")}if(x(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(_(e))return t.stylize(Date.prototype.toString.call(e),"date");if(w(e))return h(e)}var c,b="",A=!1,M=["{","}"];(p(e)&&(A=!0,M=["[","]"]),k(e))&&(b=" [Function"+(e.name?": "+e.name:"")+"]");return x(e)&&(b=" "+RegExp.prototype.toString.call(e)),_(e)&&(b=" "+Date.prototype.toUTCString.call(e)),w(e)&&(b=" "+h(e)),0!==o.length||A&&0!=e.length?n<0?x(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special"):(t.seen.push(e),c=A?function(t,e,r,n,i){for(var a=[],o=0,s=e.length;o<s;++o)S(e,String(o))?a.push(f(t,e,r,n,String(o),!0)):a.push("");return i.forEach(function(i){i.match(/^\d+$/)||a.push(f(t,e,r,n,i,!0))}),a}(t,e,n,s,o):o.map(function(r){return f(t,e,n,s,r,A)}),t.seen.pop(),function(t,e,r){if(t.reduce(function(t,e){return 0,e.indexOf("\n")>=0&&0,t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60)return r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n  ")+" "+r[1];return r[0]+e+" "+t.join(", ")+" "+r[1]}(c,b,M)):M[0]+b+M[1]}function h(t){return"["+Error.prototype.toString.call(t)+"]"}function f(t,e,r,n,i,a){var o,s,l;if((l=Object.getOwnPropertyDescriptor(e,i)||{value:e[i]}).get?s=l.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):l.set&&(s=t.stylize("[Setter]","special")),S(n,i)||(o="["+i+"]"),s||(t.seen.indexOf(l.value)<0?(s=g(r)?u(t,l.value,null):u(t,l.value,r-1)).indexOf("\n")>-1&&(s=a?s.split("\n").map(function(t){return"  "+t}).join("\n").substr(2):"\n"+s.split("\n").map(function(t){return"   "+t}).join("\n")):s=t.stylize("[Circular]","special")),y(o)){if(a&&i.match(/^\d+$/))return s;(o=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=t.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=t.stylize(o,"string"))}return o+": "+s}function p(t){return Array.isArray(t)}function d(t){return"boolean"==typeof t}function g(t){return null===t}function v(t){return"number"==typeof t}function m(t){return"string"==typeof t}function y(t){return void 0===t}function x(t){return b(t)&&"[object RegExp]"===A(t)}function b(t){return"object"==typeof t&&null!==t}function _(t){return b(t)&&"[object Date]"===A(t)}function w(t){return b(t)&&("[object Error]"===A(t)||t instanceof Error)}function k(t){return"function"==typeof t}function A(t){return Object.prototype.toString.call(t)}function M(t){return t<10?"0"+t.toString(10):t.toString(10)}r.debuglog=function(t){if(y(a)&&(a=e.env.NODE_DEBUG||""),t=t.toUpperCase(),!o[t])if(new RegExp("\\b"+t+"\\b","i").test(a)){var n=e.pid;o[t]=function(){var e=r.format.apply(r,arguments);console.error("%s %d: %s",t,n,e)}}else o[t]=function(){};return o[t]},r.inspect=s,s.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},s.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},r.isArray=p,r.isBoolean=d,r.isNull=g,r.isNullOrUndefined=function(t){return null==t},r.isNumber=v,r.isString=m,r.isSymbol=function(t){return"symbol"==typeof t},r.isUndefined=y,r.isRegExp=x,r.isObject=b,r.isDate=_,r.isError=w,r.isFunction=k,r.isPrimitive=function(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||"undefined"==typeof t},r.isBuffer=t("./support/isBuffer");var T=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function S(t,e){return Object.prototype.hasOwnProperty.call(t,e)}r.log=function(){var t,e;console.log("%s - %s",(t=new Date,e=[M(t.getHours()),M(t.getMinutes()),M(t.getSeconds())].join(":"),[t.getDate(),T[t.getMonth()],e].join(" ")),r.format.apply(r,arguments))},r.inherits=t("inherits"),r._extend=function(t,e){if(!e||!b(e))return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t}}).call(this,t("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":58,_process:471,inherits:57}],60:[function(t,e,r){e.exports=function(t){return atob(t)}},{}],61:[function(t,e,r){"use strict";e.exports=function(t,e){for(var r=e.length,a=new Array(r+1),o=0;o<r;++o){for(var s=new Array(r+1),l=0;l<=r;++l)s[l]=t[l][o];a[o]=s}a[r]=new Array(r+1);for(var o=0;o<=r;++o)a[r][o]=1;for(var c=new Array(r+1),o=0;o<r;++o)c[o]=e[o];c[r]=1;var u=n(a,c),h=i(u[r+1]);0===h&&(h=1);for(var f=new Array(r+1),o=0;o<=r;++o)f[o]=i(u[o])/h;return f};var n=t("robust-linear-solve");function i(t){for(var e=0,r=0;r<t.length;++r)e+=t[r];return e}},{"robust-linear-solve":490}],62:[function(t,e,r){"use strict";r.byteLength=function(t){var e=c(t),r=e[0],n=e[1];return 3*(r+n)/4-n},r.toByteArray=function(t){for(var e,r=c(t),n=r[0],o=r[1],s=new a(function(t,e,r){return 3*(e+r)/4-r}(0,n,o)),l=0,u=o>0?n-4:n,h=0;h<u;h+=4)e=i[t.charCodeAt(h)]<<18|i[t.charCodeAt(h+1)]<<12|i[t.charCodeAt(h+2)]<<6|i[t.charCodeAt(h+3)],s[l++]=e>>16&255,s[l++]=e>>8&255,s[l++]=255&e;2===o&&(e=i[t.charCodeAt(h)]<<2|i[t.charCodeAt(h+1)]>>4,s[l++]=255&e);1===o&&(e=i[t.charCodeAt(h)]<<10|i[t.charCodeAt(h+1)]<<4|i[t.charCodeAt(h+2)]>>2,s[l++]=e>>8&255,s[l++]=255&e);return s},r.fromByteArray=function(t){for(var e,r=t.length,i=r%3,a=[],o=0,s=r-i;o<s;o+=16383)a.push(u(t,o,o+16383>s?s:o+16383));1===i?(e=t[r-1],a.push(n[e>>2]+n[e<<4&63]+"==")):2===i&&(e=(t[r-2]<<8)+t[r-1],a.push(n[e>>10]+n[e>>4&63]+n[e<<2&63]+"="));return a.join("")};for(var n=[],i=[],a="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,l=o.length;s<l;++s)n[s]=o[s],i[o.charCodeAt(s)]=s;function c(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function u(t,e,r){for(var i,a,o=[],s=e;s<r;s+=3)i=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(255&t[s+2]),o.push(n[(a=i)>>18&63]+n[a>>12&63]+n[a>>6&63]+n[63&a]);return o.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},{}],63:[function(t,e,r){"use strict";var n=t("./lib/rationalize");e.exports=function(t,e){return n(t[0].mul(e[1]).add(e[0].mul(t[1])),t[1].mul(e[1]))}},{"./lib/rationalize":73}],64:[function(t,e,r){"use strict";e.exports=function(t,e){return t[0].mul(e[1]).cmp(e[0].mul(t[1]))}},{}],65:[function(t,e,r){"use strict";var n=t("./lib/rationalize");e.exports=function(t,e){return n(t[0].mul(e[1]),t[1].mul(e[0]))}},{"./lib/rationalize":73}],66:[function(t,e,r){"use strict";var n=t("./is-rat"),i=t("./lib/is-bn"),a=t("./lib/num-to-bn"),o=t("./lib/str-to-bn"),s=t("./lib/rationalize"),l=t("./div");e.exports=function t(e,r){if(n(e))return r?l(e,t(r)):[e[0].clone(),e[1].clone()];var c=0;var u,h;if(i(e))u=e.clone();else if("string"==typeof e)u=o(e);else{if(0===e)return[a(0),a(1)];if(e===Math.floor(e))u=a(e);else{for(;e!==Math.floor(e);)e*=Math.pow(2,256),c-=256;u=a(e)}}if(n(r))u.mul(r[1]),h=r[0].clone();else if(i(r))h=r.clone();else if("string"==typeof r)h=o(r);else if(r)if(r===Math.floor(r))h=a(r);else{for(;r!==Math.floor(r);)r*=Math.pow(2,256),c+=256;h=a(r)}else h=a(1);c>0?u=u.ushln(c):c<0&&(h=h.ushln(-c));return s(u,h)}},{"./div":65,"./is-rat":67,"./lib/is-bn":71,"./lib/num-to-bn":72,"./lib/rationalize":73,"./lib/str-to-bn":74}],67:[function(t,e,r){"use strict";var n=t("./lib/is-bn");e.exports=function(t){return Array.isArray(t)&&2===t.length&&n(t[0])&&n(t[1])}},{"./lib/is-bn":71}],68:[function(t,e,r){"use strict";var n=t("bn.js");e.exports=function(t){return t.cmp(new n(0))}},{"bn.js":82}],69:[function(t,e,r){"use strict";var n=t("./bn-sign");e.exports=function(t){var e=t.length,r=t.words,i=0;if(1===e)i=r[0];else if(2===e)i=r[0]+67108864*r[1];else for(var a=0;a<e;a++){var o=r[a];i+=o*Math.pow(67108864,a)}return n(t)*i}},{"./bn-sign":68}],70:[function(t,e,r){"use strict";var n=t("double-bits"),i=t("bit-twiddle").countTrailingZeros;e.exports=function(t){var e=i(n.lo(t));if(e<32)return e;var r=i(n.hi(t));if(r>20)return 52;return r+32}},{"bit-twiddle":80,"double-bits":155}],71:[function(t,e,r){"use strict";t("bn.js");e.exports=function(t){return t&&"object"==typeof t&&Boolean(t.words)}},{"bn.js":82}],72:[function(t,e,r){"use strict";var n=t("bn.js"),i=t("double-bits");e.exports=function(t){var e=i.exponent(t);return e<52?new n(t):new n(t*Math.pow(2,52-e)).ushln(e-52)}},{"bn.js":82,"double-bits":155}],73:[function(t,e,r){"use strict";var n=t("./num-to-bn"),i=t("./bn-sign");e.exports=function(t,e){var r=i(t),a=i(e);if(0===r)return[n(0),n(1)];if(0===a)return[n(0),n(0)];a<0&&(t=t.neg(),e=e.neg());var o=t.gcd(e);if(o.cmpn(1))return[t.div(o),e.div(o)];return[t,e]}},{"./bn-sign":68,"./num-to-bn":72}],74:[function(t,e,r){"use strict";var n=t("bn.js");e.exports=function(t){return new n(t)}},{"bn.js":82}],75:[function(t,e,r){"use strict";var n=t("./lib/rationalize");e.exports=function(t,e){return n(t[0].mul(e[0]),t[1].mul(e[1]))}},{"./lib/rationalize":73}],76:[function(t,e,r){"use strict";var n=t("./lib/bn-sign");e.exports=function(t){return n(t[0])*n(t[1])}},{"./lib/bn-sign":68}],77:[function(t,e,r){"use strict";var n=t("./lib/rationalize");e.exports=function(t,e){return n(t[0].mul(e[1]).sub(t[1].mul(e[0])),t[1].mul(e[1]))}},{"./lib/rationalize":73}],78:[function(t,e,r){"use strict";var n=t("./lib/bn-to-num"),i=t("./lib/ctz");e.exports=function(t){var e=t[0],r=t[1];if(0===e.cmpn(0))return 0;var a=e.abs().divmod(r.abs()),o=a.div,s=n(o),l=a.mod,c=e.negative!==r.negative?-1:1;if(0===l.cmpn(0))return c*s;if(s){var u=i(s)+4,h=n(l.ushln(u).divRound(r));return c*(s+h*Math.pow(2,-u))}var f=r.bitLength()-l.bitLength()+53,h=n(l.ushln(f).divRound(r));return f<1023?c*h*Math.pow(2,-f):(h*=Math.pow(2,-1023),c*h*Math.pow(2,1023-f))}},{"./lib/bn-to-num":69,"./lib/ctz":70}],79:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){var o=["function ",t,"(a,l,h,",n.join(","),"){",a?"":"var i=",r?"l-1":"h+1",";while(l<=h){var m=(l+h)>>>1,x=a",i?".get(m)":"[m]"];return a?e.indexOf("c")<0?o.push(";if(x===y){return m}else if(x<=y){"):o.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):o.push(";if(",e,"){i=m;"),r?o.push("l=m+1}else{h=m-1}"):o.push("h=m-1}else{l=m+1}"),o.push("}"),a?o.push("return -1};"):o.push("return i};"),o.join("")}function i(t,e,r,i){return new Function([n("A","x"+t+"y",e,["y"],!1,i),n("B","x"+t+"y",e,["y"],!0,i),n("P","c(x,y)"+t+"0",e,["y","c"],!1,i),n("Q","c(x,y)"+t+"0",e,["y","c"],!0,i),"function dispatchBsearch",r,"(a,y,c,l,h){if(a.shape){if(typeof(c)==='function'){return Q(a,(l===undefined)?0:l|0,(h===undefined)?a.shape[0]-1:h|0,y,c)}else{return B(a,(c===undefined)?0:c|0,(l===undefined)?a.shape[0]-1:l|0,y)}}else{if(typeof(c)==='function'){return P(a,(l===undefined)?0:l|0,(h===undefined)?a.length-1:h|0,y,c)}else{return A(a,(c===undefined)?0:c|0,(l===undefined)?a.length-1:l|0,y)}}}return dispatchBsearch",r].join(""))()}e.exports={ge:i(">=",!1,"GE"),gt:i(">",!1,"GT"),lt:i("<",!0,"LT"),le:i("<=",!0,"LE"),eq:i("-",!0,"EQ",!0)}},{}],80:[function(t,e,r){"use strict";function n(t){var e=32;return(t&=-t)&&e--,65535&t&&(e-=16),16711935&t&&(e-=8),252645135&t&&(e-=4),858993459&t&&(e-=2),1431655765&t&&(e-=1),e}r.INT_BITS=32,r.INT_MAX=2147483647,r.INT_MIN=-1<<31,r.sign=function(t){return(t>0)-(t<0)},r.abs=function(t){var e=t>>31;return(t^e)-e},r.min=function(t,e){return e^(t^e)&-(t<e)},r.max=function(t,e){return t^(t^e)&-(t<e)},r.isPow2=function(t){return!(t&t-1||!t)},r.log2=function(t){var e,r;return e=(t>65535)<<4,e|=r=((t>>>=e)>255)<<3,e|=r=((t>>>=r)>15)<<2,(e|=r=((t>>>=r)>3)<<1)|(t>>>=r)>>1},r.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},r.popCount=function(t){return 16843009*((t=(858993459&(t-=t>>>1&1431655765))+(t>>>2&858993459))+(t>>>4)&252645135)>>>24},r.countTrailingZeros=n,r.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1},r.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)-(t>>>1)},r.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,27030>>>(t&=15)&1};var i=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<<i&255}}(i),r.reverse=function(t){return i[255&t]<<24|i[t>>>8&255]<<16|i[t>>>16&255]<<8|i[t>>>24&255]},r.interleave2=function(t,e){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t&=65535)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e&=65535)|e<<8))|e<<4))|e<<2))|e<<1))<<1},r.deinterleave2=function(t,e){return(t=65535&((t=16711935&((t=252645135&((t=858993459&((t=t>>>e&1431655765)|t>>>1))|t>>>2))|t>>>4))|t>>>16))<<16>>16},r.interleave3=function(t,e,r){return t=1227133513&((t=3272356035&((t=251719695&((t=4278190335&((t&=1023)|t<<16))|t<<8))|t<<4))|t<<2),(t|=(e=1227133513&((e=3272356035&((e=251719695&((e=4278190335&((e&=1023)|e<<16))|e<<8))|e<<4))|e<<2))<<1)|(r=1227133513&((r=3272356035&((r=251719695&((r=4278190335&((r&=1023)|r<<16))|r<<8))|r<<4))|r<<2))<<2},r.deinterleave3=function(t,e){return(t=1023&((t=4278190335&((t=251719695&((t=3272356035&((t=t>>>e&1227133513)|t>>>2))|t>>>4))|t>>>8))|t>>>16))<<22>>22},r.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>n(t)+1}},{}],81:[function(t,e,r){"use strict";var n=t("clamp");e.exports=function(t,e){e||(e={});var r,o,s,l,c,u,h,f,p,d,g,v=null==e.cutoff?.25:e.cutoff,m=null==e.radius?8:e.radius,y=e.channel||0;if(ArrayBuffer.isView(t)||Array.isArray(t)){if(!e.width||!e.height)throw Error("For raw data width and height should be provided by options");r=e.width,o=e.height,l=t,u=e.stride?e.stride:Math.floor(t.length/r/o)}else window.HTMLCanvasElement&&t instanceof window.HTMLCanvasElement?(h=(f=t).getContext("2d"),r=f.width,o=f.height,p=h.getImageData(0,0,r,o),l=p.data,u=4):window.CanvasRenderingContext2D&&t instanceof window.CanvasRenderingContext2D?(f=t.canvas,h=t,r=f.width,o=f.height,p=h.getImageData(0,0,r,o),l=p.data,u=4):window.ImageData&&t instanceof window.ImageData&&(p=t,r=t.width,o=t.height,l=p.data,u=4);if(s=Math.max(r,o),window.Uint8ClampedArray&&l instanceof window.Uint8ClampedArray||window.Uint8Array&&l instanceof window.Uint8Array)for(c=l,l=Array(r*o),d=0,g=c.length;d<g;d++)l[d]=c[d*u+y]/255;else if(1!==u)throw Error("Raw data can have only 1 value per pixel");var x=Array(r*o),b=Array(r*o),_=Array(s),w=Array(s),k=Array(s+1),A=Array(s);for(d=0,g=r*o;d<g;d++){var M=l[d];x[d]=1===M?0:0===M?i:Math.pow(Math.max(0,.5-M),2),b[d]=1===M?i:0===M?0:Math.pow(Math.max(0,M-.5),2)}a(x,r,o,_,w,A,k),a(b,r,o,_,w,A,k);var T=window.Float32Array?new Float32Array(r*o):new Array(r*o);for(d=0,g=r*o;d<g;d++)T[d]=n(1-((x[d]-b[d])/m+v),0,1);return T};var i=1e20;function a(t,e,r,n,i,a,s){for(var l=0;l<e;l++){for(var c=0;c<r;c++)n[c]=t[c*e+l];for(o(n,i,a,s,r),c=0;c<r;c++)t[c*e+l]=i[c]}for(c=0;c<r;c++){for(l=0;l<e;l++)n[l]=t[c*e+l];for(o(n,i,a,s,e),l=0;l<e;l++)t[c*e+l]=Math.sqrt(i[l])}}function o(t,e,r,n,a){r[0]=0,n[0]=-i,n[1]=+i;for(var o=1,s=0;o<a;o++){for(var l=(t[o]+o*o-(t[r[s]]+r[s]*r[s]))/(2*o-2*r[s]);l<=n[s];)s--,l=(t[o]+o*o-(t[r[s]]+r[s]*r[s]))/(2*o-2*r[s]);r[++s]=o,n[s]=l,n[s+1]=+i}for(o=0,s=0;o<a;o++){for(;n[s+1]<o;)s++;e[o]=(o-r[s])*(o-r[s])+t[r[s]]}}},{clamp:103}],82:[function(t,e,r){!function(e,r){"use strict";function n(t,e){if(!t)throw new Error(e||"Assertion failed")}function i(t,e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}function a(t,e,r){if(a.isBN(t))return t;this.negative=0,this.words=null,this.length=0,this.red=null,null!==t&&("le"!==e&&"be"!==e||(r=e,e=10),this._init(t||0,e||10,r||"be"))}var o;"object"==typeof e?e.exports=a:r.BN=a,a.BN=a,a.wordSize=26;try{o=t("buffer").Buffer}catch(t){}function s(t,e,r){for(var n=0,i=Math.min(t.length,r),a=e;a<i;a++){var o=t.charCodeAt(a)-48;n<<=4,n|=o>=49&&o<=54?o-49+10:o>=17&&o<=22?o-17+10:15&o}return n}function l(t,e,r,n){for(var i=0,a=Math.min(t.length,r),o=e;o<a;o++){var s=t.charCodeAt(o)-48;i*=n,i+=s>=49?s-49+10:s>=17?s-17+10:s}return i}a.isBN=function(t){return t instanceof a||null!==t&&"object"==typeof t&&t.constructor.wordSize===a.wordSize&&Array.isArray(t.words)},a.max=function(t,e){return t.cmp(e)>0?t:e},a.min=function(t,e){return t.cmp(e)<0?t:e},a.prototype._init=function(t,e,r){if("number"==typeof t)return this._initNumber(t,e,r);if("object"==typeof t)return this._initArray(t,e,r);"hex"===e&&(e=16),n(e===(0|e)&&e>=2&&e<=36);var i=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&i++,16===e?this._parseHex(t,i):this._parseBase(t,e,i),"-"===t[0]&&(this.negative=1),this.strip(),"le"===r&&this._initArray(this.toArray(),e,r)},a.prototype._initNumber=function(t,e,r){t<0&&(this.negative=1,t=-t),t<67108864?(this.words=[67108863&t],this.length=1):t<4503599627370496?(this.words=[67108863&t,t/67108864&67108863],this.length=2):(n(t<9007199254740992),this.words=[67108863&t,t/67108864&67108863,1],this.length=3),"le"===r&&this._initArray(this.toArray(),e,r)},a.prototype._initArray=function(t,e,r){if(n("number"==typeof t.length),t.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(t.length/3),this.words=new Array(this.length);for(var i=0;i<this.length;i++)this.words[i]=0;var a,o,s=0;if("be"===r)for(i=t.length-1,a=0;i>=0;i-=3)o=t[i]|t[i-1]<<8|t[i-2]<<16,this.words[a]|=o<<s&67108863,this.words[a+1]=o>>>26-s&67108863,(s+=24)>=26&&(s-=26,a++);else if("le"===r)for(i=0,a=0;i<t.length;i+=3)o=t[i]|t[i+1]<<8|t[i+2]<<16,this.words[a]|=o<<s&67108863,this.words[a+1]=o>>>26-s&67108863,(s+=24)>=26&&(s-=26,a++);return this.strip()},a.prototype._parseHex=function(t,e){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var r=0;r<this.length;r++)this.words[r]=0;var n,i,a=0;for(r=t.length-6,n=0;r>=e;r-=6)i=s(t,r,r+6),this.words[n]|=i<<a&67108863,this.words[n+1]|=i>>>26-a&4194303,(a+=24)>=26&&(a-=26,n++);r+6!==e&&(i=s(t,e,r+6),this.words[n]|=i<<a&67108863,this.words[n+1]|=i>>>26-a&4194303),this.strip()},a.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=e)n++;n--,i=i/e|0;for(var a=t.length-r,o=a%n,s=Math.min(a,a-o)+r,c=0,u=r;u<s;u+=n)c=l(t,u,u+n,e),this.imuln(i),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c);if(0!==o){var h=1;for(c=l(t,u,t.length,e),u=0;u<o;u++)h*=e;this.imuln(h),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c)}},a.prototype.copy=function(t){t.words=new Array(this.length);for(var e=0;e<this.length;e++)t.words[e]=this.words[e];t.length=this.length,t.negative=this.negative,t.red=this.red},a.prototype.clone=function(){var t=new a(null);return this.copy(t),t},a.prototype._expand=function(t){for(;this.length<t;)this.words[this.length++]=0;return this},a.prototype.strip=function(){for(;this.length>1&&0===this.words[this.length-1];)this.length--;return this._normSign()},a.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},a.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var c=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],u=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],h=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function f(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var i=0|t.words[0],a=0|e.words[0],o=i*a,s=67108863&o,l=o/67108864|0;r.words[0]=s;for(var c=1;c<n;c++){for(var u=l>>>26,h=67108863&l,f=Math.min(c,e.length-1),p=Math.max(0,c-t.length+1);p<=f;p++){var d=c-p|0;u+=(o=(i=0|t.words[d])*(a=0|e.words[p])+h)/67108864|0,h=67108863&o}r.words[c]=0|h,l=0|u}return 0!==l?r.words[c]=0|l:r.length--,r.strip()}a.prototype.toString=function(t,e){var r;if(e=0|e||1,16===(t=t||10)||"hex"===t){r="";for(var i=0,a=0,o=0;o<this.length;o++){var s=this.words[o],l=(16777215&(s<<i|a)).toString(16);r=0!==(a=s>>>24-i&16777215)||o!==this.length-1?c[6-l.length]+l+r:l+r,(i+=2)>=26&&(i-=26,o--)}for(0!==a&&(r=a.toString(16)+r);r.length%e!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(t===(0|t)&&t>=2&&t<=36){var f=u[t],p=h[t];r="";var d=this.clone();for(d.negative=0;!d.isZero();){var g=d.modn(p).toString(t);r=(d=d.idivn(p)).isZero()?g+r:c[f-g.length]+g+r}for(this.isZero()&&(r="0"+r);r.length%e!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},a.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},a.prototype.toJSON=function(){return this.toString(16)},a.prototype.toBuffer=function(t,e){return n("undefined"!=typeof o),this.toArrayLike(o,t,e)},a.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},a.prototype.toArrayLike=function(t,e,r){var i=this.byteLength(),a=r||Math.max(1,i);n(i<=a,"byte array longer than desired length"),n(a>0,"Requested array length <= 0"),this.strip();var o,s,l="le"===e,c=new t(a),u=this.clone();if(l){for(s=0;!u.isZero();s++)o=u.andln(255),u.iushrn(8),c[s]=o;for(;s<a;s++)c[s]=0}else{for(s=0;s<a-i;s++)c[s]=0;for(s=0;!u.isZero();s++)o=u.andln(255),u.iushrn(8),c[a-s-1]=o}return c},Math.clz32?a.prototype._countBits=function(t){return 32-Math.clz32(t)}:a.prototype._countBits=function(t){var e=t,r=0;return e>=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},a.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0==(8191&e)&&(r+=13,e>>>=13),0==(127&e)&&(r+=7,e>>>=7),0==(15&e)&&(r+=4,e>>>=4),0==(3&e)&&(r+=2,e>>>=2),0==(1&e)&&r++,r},a.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},a.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;e<this.length;e++){var r=this._zeroBits(this.words[e]);if(t+=r,26!==r)break}return t},a.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},a.prototype.toTwos=function(t){return 0!==this.negative?this.abs().inotn(t).iaddn(1):this.clone()},a.prototype.fromTwos=function(t){return this.testn(t-1)?this.notn(t).iaddn(1).ineg():this.clone()},a.prototype.isNeg=function(){return 0!==this.negative},a.prototype.neg=function(){return this.clone().ineg()},a.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},a.prototype.iuor=function(t){for(;this.length<t.length;)this.words[this.length++]=0;for(var e=0;e<t.length;e++)this.words[e]=this.words[e]|t.words[e];return this.strip()},a.prototype.ior=function(t){return n(0==(this.negative|t.negative)),this.iuor(t)},a.prototype.or=function(t){return this.length>t.length?this.clone().ior(t):t.clone().ior(this)},a.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},a.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;r<e.length;r++)this.words[r]=this.words[r]&t.words[r];return this.length=e.length,this.strip()},a.prototype.iand=function(t){return n(0==(this.negative|t.negative)),this.iuand(t)},a.prototype.and=function(t){return this.length>t.length?this.clone().iand(t):t.clone().iand(this)},a.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},a.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;n<r.length;n++)this.words[n]=e.words[n]^r.words[n];if(this!==e)for(;n<e.length;n++)this.words[n]=e.words[n];return this.length=e.length,this.strip()},a.prototype.ixor=function(t){return n(0==(this.negative|t.negative)),this.iuxor(t)},a.prototype.xor=function(t){return this.length>t.length?this.clone().ixor(t):t.clone().ixor(this)},a.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},a.prototype.inotn=function(t){n("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),r=t%26;this._expand(e),r>0&&e--;for(var i=0;i<e;i++)this.words[i]=67108863&~this.words[i];return r>0&&(this.words[i]=~this.words[i]&67108863>>26-r),this.strip()},a.prototype.notn=function(t){return this.clone().inotn(t)},a.prototype.setn=function(t,e){n("number"==typeof t&&t>=0);var r=t/26|0,i=t%26;return this._expand(r+1),this.words[r]=e?this.words[r]|1<<i:this.words[r]&~(1<<i),this.strip()},a.prototype.iadd=function(t){var e,r,n;if(0!==this.negative&&0===t.negative)return this.negative=0,e=this.isub(t),this.negative^=1,this._normSign();if(0===this.negative&&0!==t.negative)return t.negative=0,e=this.isub(t),t.negative=1,e._normSign();this.length>t.length?(r=this,n=t):(r=t,n=this);for(var i=0,a=0;a<n.length;a++)e=(0|r.words[a])+(0|n.words[a])+i,this.words[a]=67108863&e,i=e>>>26;for(;0!==i&&a<r.length;a++)e=(0|r.words[a])+i,this.words[a]=67108863&e,i=e>>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;a<r.length;a++)this.words[a]=r.words[a];return this},a.prototype.add=function(t){var e;return 0!==t.negative&&0===this.negative?(t.negative=0,e=this.sub(t),t.negative^=1,e):0===t.negative&&0!==this.negative?(this.negative=0,e=t.sub(this),this.negative=1,e):this.length>t.length?this.clone().iadd(t):t.clone().iadd(this)},a.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,i=this.cmp(t);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=t):(r=t,n=this);for(var a=0,o=0;o<n.length;o++)a=(e=(0|r.words[o])-(0|n.words[o])+a)>>26,this.words[o]=67108863&e;for(;0!==a&&o<r.length;o++)a=(e=(0|r.words[o])+a)>>26,this.words[o]=67108863&e;if(0===a&&o<r.length&&r!==this)for(;o<r.length;o++)this.words[o]=r.words[o];return this.length=Math.max(this.length,o),r!==this&&(this.negative=1),this.strip()},a.prototype.sub=function(t){return this.clone().isub(t)};var p=function(t,e,r){var n,i,a,o=t.words,s=e.words,l=r.words,c=0,u=0|o[0],h=8191&u,f=u>>>13,p=0|o[1],d=8191&p,g=p>>>13,v=0|o[2],m=8191&v,y=v>>>13,x=0|o[3],b=8191&x,_=x>>>13,w=0|o[4],k=8191&w,A=w>>>13,M=0|o[5],T=8191&M,S=M>>>13,E=0|o[6],C=8191&E,L=E>>>13,z=0|o[7],O=8191&z,I=z>>>13,D=0|o[8],P=8191&D,R=D>>>13,F=0|o[9],B=8191&F,N=F>>>13,j=0|s[0],V=8191&j,U=j>>>13,q=0|s[1],H=8191&q,G=q>>>13,Y=0|s[2],W=8191&Y,X=Y>>>13,Z=0|s[3],$=8191&Z,J=Z>>>13,K=0|s[4],Q=8191&K,tt=K>>>13,et=0|s[5],rt=8191&et,nt=et>>>13,it=0|s[6],at=8191&it,ot=it>>>13,st=0|s[7],lt=8191&st,ct=st>>>13,ut=0|s[8],ht=8191&ut,ft=ut>>>13,pt=0|s[9],dt=8191&pt,gt=pt>>>13;r.negative=t.negative^e.negative,r.length=19;var vt=(c+(n=Math.imul(h,V))|0)+((8191&(i=(i=Math.imul(h,U))+Math.imul(f,V)|0))<<13)|0;c=((a=Math.imul(f,U))+(i>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(d,V),i=(i=Math.imul(d,U))+Math.imul(g,V)|0,a=Math.imul(g,U);var mt=(c+(n=n+Math.imul(h,H)|0)|0)+((8191&(i=(i=i+Math.imul(h,G)|0)+Math.imul(f,H)|0))<<13)|0;c=((a=a+Math.imul(f,G)|0)+(i>>>13)|0)+(mt>>>26)|0,mt&=67108863,n=Math.imul(m,V),i=(i=Math.imul(m,U))+Math.imul(y,V)|0,a=Math.imul(y,U),n=n+Math.imul(d,H)|0,i=(i=i+Math.imul(d,G)|0)+Math.imul(g,H)|0,a=a+Math.imul(g,G)|0;var yt=(c+(n=n+Math.imul(h,W)|0)|0)+((8191&(i=(i=i+Math.imul(h,X)|0)+Math.imul(f,W)|0))<<13)|0;c=((a=a+Math.imul(f,X)|0)+(i>>>13)|0)+(yt>>>26)|0,yt&=67108863,n=Math.imul(b,V),i=(i=Math.imul(b,U))+Math.imul(_,V)|0,a=Math.imul(_,U),n=n+Math.imul(m,H)|0,i=(i=i+Math.imul(m,G)|0)+Math.imul(y,H)|0,a=a+Math.imul(y,G)|0,n=n+Math.imul(d,W)|0,i=(i=i+Math.imul(d,X)|0)+Math.imul(g,W)|0,a=a+Math.imul(g,X)|0;var xt=(c+(n=n+Math.imul(h,$)|0)|0)+((8191&(i=(i=i+Math.imul(h,J)|0)+Math.imul(f,$)|0))<<13)|0;c=((a=a+Math.imul(f,J)|0)+(i>>>13)|0)+(xt>>>26)|0,xt&=67108863,n=Math.imul(k,V),i=(i=Math.imul(k,U))+Math.imul(A,V)|0,a=Math.imul(A,U),n=n+Math.imul(b,H)|0,i=(i=i+Math.imul(b,G)|0)+Math.imul(_,H)|0,a=a+Math.imul(_,G)|0,n=n+Math.imul(m,W)|0,i=(i=i+Math.imul(m,X)|0)+Math.imul(y,W)|0,a=a+Math.imul(y,X)|0,n=n+Math.imul(d,$)|0,i=(i=i+Math.imul(d,J)|0)+Math.imul(g,$)|0,a=a+Math.imul(g,J)|0;var bt=(c+(n=n+Math.imul(h,Q)|0)|0)+((8191&(i=(i=i+Math.imul(h,tt)|0)+Math.imul(f,Q)|0))<<13)|0;c=((a=a+Math.imul(f,tt)|0)+(i>>>13)|0)+(bt>>>26)|0,bt&=67108863,n=Math.imul(T,V),i=(i=Math.imul(T,U))+Math.imul(S,V)|0,a=Math.imul(S,U),n=n+Math.imul(k,H)|0,i=(i=i+Math.imul(k,G)|0)+Math.imul(A,H)|0,a=a+Math.imul(A,G)|0,n=n+Math.imul(b,W)|0,i=(i=i+Math.imul(b,X)|0)+Math.imul(_,W)|0,a=a+Math.imul(_,X)|0,n=n+Math.imul(m,$)|0,i=(i=i+Math.imul(m,J)|0)+Math.imul(y,$)|0,a=a+Math.imul(y,J)|0,n=n+Math.imul(d,Q)|0,i=(i=i+Math.imul(d,tt)|0)+Math.imul(g,Q)|0,a=a+Math.imul(g,tt)|0;var _t=(c+(n=n+Math.imul(h,rt)|0)|0)+((8191&(i=(i=i+Math.imul(h,nt)|0)+Math.imul(f,rt)|0))<<13)|0;c=((a=a+Math.imul(f,nt)|0)+(i>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(C,V),i=(i=Math.imul(C,U))+Math.imul(L,V)|0,a=Math.imul(L,U),n=n+Math.imul(T,H)|0,i=(i=i+Math.imul(T,G)|0)+Math.imul(S,H)|0,a=a+Math.imul(S,G)|0,n=n+Math.imul(k,W)|0,i=(i=i+Math.imul(k,X)|0)+Math.imul(A,W)|0,a=a+Math.imul(A,X)|0,n=n+Math.imul(b,$)|0,i=(i=i+Math.imul(b,J)|0)+Math.imul(_,$)|0,a=a+Math.imul(_,J)|0,n=n+Math.imul(m,Q)|0,i=(i=i+Math.imul(m,tt)|0)+Math.imul(y,Q)|0,a=a+Math.imul(y,tt)|0,n=n+Math.imul(d,rt)|0,i=(i=i+Math.imul(d,nt)|0)+Math.imul(g,rt)|0,a=a+Math.imul(g,nt)|0;var wt=(c+(n=n+Math.imul(h,at)|0)|0)+((8191&(i=(i=i+Math.imul(h,ot)|0)+Math.imul(f,at)|0))<<13)|0;c=((a=a+Math.imul(f,ot)|0)+(i>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(O,V),i=(i=Math.imul(O,U))+Math.imul(I,V)|0,a=Math.imul(I,U),n=n+Math.imul(C,H)|0,i=(i=i+Math.imul(C,G)|0)+Math.imul(L,H)|0,a=a+Math.imul(L,G)|0,n=n+Math.imul(T,W)|0,i=(i=i+Math.imul(T,X)|0)+Math.imul(S,W)|0,a=a+Math.imul(S,X)|0,n=n+Math.imul(k,$)|0,i=(i=i+Math.imul(k,J)|0)+Math.imul(A,$)|0,a=a+Math.imul(A,J)|0,n=n+Math.imul(b,Q)|0,i=(i=i+Math.imul(b,tt)|0)+Math.imul(_,Q)|0,a=a+Math.imul(_,tt)|0,n=n+Math.imul(m,rt)|0,i=(i=i+Math.imul(m,nt)|0)+Math.imul(y,rt)|0,a=a+Math.imul(y,nt)|0,n=n+Math.imul(d,at)|0,i=(i=i+Math.imul(d,ot)|0)+Math.imul(g,at)|0,a=a+Math.imul(g,ot)|0;var kt=(c+(n=n+Math.imul(h,lt)|0)|0)+((8191&(i=(i=i+Math.imul(h,ct)|0)+Math.imul(f,lt)|0))<<13)|0;c=((a=a+Math.imul(f,ct)|0)+(i>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(P,V),i=(i=Math.imul(P,U))+Math.imul(R,V)|0,a=Math.imul(R,U),n=n+Math.imul(O,H)|0,i=(i=i+Math.imul(O,G)|0)+Math.imul(I,H)|0,a=a+Math.imul(I,G)|0,n=n+Math.imul(C,W)|0,i=(i=i+Math.imul(C,X)|0)+Math.imul(L,W)|0,a=a+Math.imul(L,X)|0,n=n+Math.imul(T,$)|0,i=(i=i+Math.imul(T,J)|0)+Math.imul(S,$)|0,a=a+Math.imul(S,J)|0,n=n+Math.imul(k,Q)|0,i=(i=i+Math.imul(k,tt)|0)+Math.imul(A,Q)|0,a=a+Math.imul(A,tt)|0,n=n+Math.imul(b,rt)|0,i=(i=i+Math.imul(b,nt)|0)+Math.imul(_,rt)|0,a=a+Math.imul(_,nt)|0,n=n+Math.imul(m,at)|0,i=(i=i+Math.imul(m,ot)|0)+Math.imul(y,at)|0,a=a+Math.imul(y,ot)|0,n=n+Math.imul(d,lt)|0,i=(i=i+Math.imul(d,ct)|0)+Math.imul(g,lt)|0,a=a+Math.imul(g,ct)|0;var At=(c+(n=n+Math.imul(h,ht)|0)|0)+((8191&(i=(i=i+Math.imul(h,ft)|0)+Math.imul(f,ht)|0))<<13)|0;c=((a=a+Math.imul(f,ft)|0)+(i>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(B,V),i=(i=Math.imul(B,U))+Math.imul(N,V)|0,a=Math.imul(N,U),n=n+Math.imul(P,H)|0,i=(i=i+Math.imul(P,G)|0)+Math.imul(R,H)|0,a=a+Math.imul(R,G)|0,n=n+Math.imul(O,W)|0,i=(i=i+Math.imul(O,X)|0)+Math.imul(I,W)|0,a=a+Math.imul(I,X)|0,n=n+Math.imul(C,$)|0,i=(i=i+Math.imul(C,J)|0)+Math.imul(L,$)|0,a=a+Math.imul(L,J)|0,n=n+Math.imul(T,Q)|0,i=(i=i+Math.imul(T,tt)|0)+Math.imul(S,Q)|0,a=a+Math.imul(S,tt)|0,n=n+Math.imul(k,rt)|0,i=(i=i+Math.imul(k,nt)|0)+Math.imul(A,rt)|0,a=a+Math.imul(A,nt)|0,n=n+Math.imul(b,at)|0,i=(i=i+Math.imul(b,ot)|0)+Math.imul(_,at)|0,a=a+Math.imul(_,ot)|0,n=n+Math.imul(m,lt)|0,i=(i=i+Math.imul(m,ct)|0)+Math.imul(y,lt)|0,a=a+Math.imul(y,ct)|0,n=n+Math.imul(d,ht)|0,i=(i=i+Math.imul(d,ft)|0)+Math.imul(g,ht)|0,a=a+Math.imul(g,ft)|0;var Mt=(c+(n=n+Math.imul(h,dt)|0)|0)+((8191&(i=(i=i+Math.imul(h,gt)|0)+Math.imul(f,dt)|0))<<13)|0;c=((a=a+Math.imul(f,gt)|0)+(i>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(B,H),i=(i=Math.imul(B,G))+Math.imul(N,H)|0,a=Math.imul(N,G),n=n+Math.imul(P,W)|0,i=(i=i+Math.imul(P,X)|0)+Math.imul(R,W)|0,a=a+Math.imul(R,X)|0,n=n+Math.imul(O,$)|0,i=(i=i+Math.imul(O,J)|0)+Math.imul(I,$)|0,a=a+Math.imul(I,J)|0,n=n+Math.imul(C,Q)|0,i=(i=i+Math.imul(C,tt)|0)+Math.imul(L,Q)|0,a=a+Math.imul(L,tt)|0,n=n+Math.imul(T,rt)|0,i=(i=i+Math.imul(T,nt)|0)+Math.imul(S,rt)|0,a=a+Math.imul(S,nt)|0,n=n+Math.imul(k,at)|0,i=(i=i+Math.imul(k,ot)|0)+Math.imul(A,at)|0,a=a+Math.imul(A,ot)|0,n=n+Math.imul(b,lt)|0,i=(i=i+Math.imul(b,ct)|0)+Math.imul(_,lt)|0,a=a+Math.imul(_,ct)|0,n=n+Math.imul(m,ht)|0,i=(i=i+Math.imul(m,ft)|0)+Math.imul(y,ht)|0,a=a+Math.imul(y,ft)|0;var Tt=(c+(n=n+Math.imul(d,dt)|0)|0)+((8191&(i=(i=i+Math.imul(d,gt)|0)+Math.imul(g,dt)|0))<<13)|0;c=((a=a+Math.imul(g,gt)|0)+(i>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,n=Math.imul(B,W),i=(i=Math.imul(B,X))+Math.imul(N,W)|0,a=Math.imul(N,X),n=n+Math.imul(P,$)|0,i=(i=i+Math.imul(P,J)|0)+Math.imul(R,$)|0,a=a+Math.imul(R,J)|0,n=n+Math.imul(O,Q)|0,i=(i=i+Math.imul(O,tt)|0)+Math.imul(I,Q)|0,a=a+Math.imul(I,tt)|0,n=n+Math.imul(C,rt)|0,i=(i=i+Math.imul(C,nt)|0)+Math.imul(L,rt)|0,a=a+Math.imul(L,nt)|0,n=n+Math.imul(T,at)|0,i=(i=i+Math.imul(T,ot)|0)+Math.imul(S,at)|0,a=a+Math.imul(S,ot)|0,n=n+Math.imul(k,lt)|0,i=(i=i+Math.imul(k,ct)|0)+Math.imul(A,lt)|0,a=a+Math.imul(A,ct)|0,n=n+Math.imul(b,ht)|0,i=(i=i+Math.imul(b,ft)|0)+Math.imul(_,ht)|0,a=a+Math.imul(_,ft)|0;var St=(c+(n=n+Math.imul(m,dt)|0)|0)+((8191&(i=(i=i+Math.imul(m,gt)|0)+Math.imul(y,dt)|0))<<13)|0;c=((a=a+Math.imul(y,gt)|0)+(i>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(B,$),i=(i=Math.imul(B,J))+Math.imul(N,$)|0,a=Math.imul(N,J),n=n+Math.imul(P,Q)|0,i=(i=i+Math.imul(P,tt)|0)+Math.imul(R,Q)|0,a=a+Math.imul(R,tt)|0,n=n+Math.imul(O,rt)|0,i=(i=i+Math.imul(O,nt)|0)+Math.imul(I,rt)|0,a=a+Math.imul(I,nt)|0,n=n+Math.imul(C,at)|0,i=(i=i+Math.imul(C,ot)|0)+Math.imul(L,at)|0,a=a+Math.imul(L,ot)|0,n=n+Math.imul(T,lt)|0,i=(i=i+Math.imul(T,ct)|0)+Math.imul(S,lt)|0,a=a+Math.imul(S,ct)|0,n=n+Math.imul(k,ht)|0,i=(i=i+Math.imul(k,ft)|0)+Math.imul(A,ht)|0,a=a+Math.imul(A,ft)|0;var Et=(c+(n=n+Math.imul(b,dt)|0)|0)+((8191&(i=(i=i+Math.imul(b,gt)|0)+Math.imul(_,dt)|0))<<13)|0;c=((a=a+Math.imul(_,gt)|0)+(i>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(B,Q),i=(i=Math.imul(B,tt))+Math.imul(N,Q)|0,a=Math.imul(N,tt),n=n+Math.imul(P,rt)|0,i=(i=i+Math.imul(P,nt)|0)+Math.imul(R,rt)|0,a=a+Math.imul(R,nt)|0,n=n+Math.imul(O,at)|0,i=(i=i+Math.imul(O,ot)|0)+Math.imul(I,at)|0,a=a+Math.imul(I,ot)|0,n=n+Math.imul(C,lt)|0,i=(i=i+Math.imul(C,ct)|0)+Math.imul(L,lt)|0,a=a+Math.imul(L,ct)|0,n=n+Math.imul(T,ht)|0,i=(i=i+Math.imul(T,ft)|0)+Math.imul(S,ht)|0,a=a+Math.imul(S,ft)|0;var Ct=(c+(n=n+Math.imul(k,dt)|0)|0)+((8191&(i=(i=i+Math.imul(k,gt)|0)+Math.imul(A,dt)|0))<<13)|0;c=((a=a+Math.imul(A,gt)|0)+(i>>>13)|0)+(Ct>>>26)|0,Ct&=67108863,n=Math.imul(B,rt),i=(i=Math.imul(B,nt))+Math.imul(N,rt)|0,a=Math.imul(N,nt),n=n+Math.imul(P,at)|0,i=(i=i+Math.imul(P,ot)|0)+Math.imul(R,at)|0,a=a+Math.imul(R,ot)|0,n=n+Math.imul(O,lt)|0,i=(i=i+Math.imul(O,ct)|0)+Math.imul(I,lt)|0,a=a+Math.imul(I,ct)|0,n=n+Math.imul(C,ht)|0,i=(i=i+Math.imul(C,ft)|0)+Math.imul(L,ht)|0,a=a+Math.imul(L,ft)|0;var Lt=(c+(n=n+Math.imul(T,dt)|0)|0)+((8191&(i=(i=i+Math.imul(T,gt)|0)+Math.imul(S,dt)|0))<<13)|0;c=((a=a+Math.imul(S,gt)|0)+(i>>>13)|0)+(Lt>>>26)|0,Lt&=67108863,n=Math.imul(B,at),i=(i=Math.imul(B,ot))+Math.imul(N,at)|0,a=Math.imul(N,ot),n=n+Math.imul(P,lt)|0,i=(i=i+Math.imul(P,ct)|0)+Math.imul(R,lt)|0,a=a+Math.imul(R,ct)|0,n=n+Math.imul(O,ht)|0,i=(i=i+Math.imul(O,ft)|0)+Math.imul(I,ht)|0,a=a+Math.imul(I,ft)|0;var zt=(c+(n=n+Math.imul(C,dt)|0)|0)+((8191&(i=(i=i+Math.imul(C,gt)|0)+Math.imul(L,dt)|0))<<13)|0;c=((a=a+Math.imul(L,gt)|0)+(i>>>13)|0)+(zt>>>26)|0,zt&=67108863,n=Math.imul(B,lt),i=(i=Math.imul(B,ct))+Math.imul(N,lt)|0,a=Math.imul(N,ct),n=n+Math.imul(P,ht)|0,i=(i=i+Math.imul(P,ft)|0)+Math.imul(R,ht)|0,a=a+Math.imul(R,ft)|0;var Ot=(c+(n=n+Math.imul(O,dt)|0)|0)+((8191&(i=(i=i+Math.imul(O,gt)|0)+Math.imul(I,dt)|0))<<13)|0;c=((a=a+Math.imul(I,gt)|0)+(i>>>13)|0)+(Ot>>>26)|0,Ot&=67108863,n=Math.imul(B,ht),i=(i=Math.imul(B,ft))+Math.imul(N,ht)|0,a=Math.imul(N,ft);var It=(c+(n=n+Math.imul(P,dt)|0)|0)+((8191&(i=(i=i+Math.imul(P,gt)|0)+Math.imul(R,dt)|0))<<13)|0;c=((a=a+Math.imul(R,gt)|0)+(i>>>13)|0)+(It>>>26)|0,It&=67108863;var Dt=(c+(n=Math.imul(B,dt))|0)+((8191&(i=(i=Math.imul(B,gt))+Math.imul(N,dt)|0))<<13)|0;return c=((a=Math.imul(N,gt))+(i>>>13)|0)+(Dt>>>26)|0,Dt&=67108863,l[0]=vt,l[1]=mt,l[2]=yt,l[3]=xt,l[4]=bt,l[5]=_t,l[6]=wt,l[7]=kt,l[8]=At,l[9]=Mt,l[10]=Tt,l[11]=St,l[12]=Et,l[13]=Ct,l[14]=Lt,l[15]=zt,l[16]=Ot,l[17]=It,l[18]=Dt,0!==c&&(l[19]=c,r.length++),r};function d(t,e,r){return(new g).mulp(t,e,r)}function g(t,e){this.x=t,this.y=e}Math.imul||(p=f),a.prototype.mulTo=function(t,e){var r=this.length+t.length;return 10===this.length&&10===t.length?p(this,t,e):r<63?f(this,t,e):r<1024?function(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,i=0,a=0;a<r.length-1;a++){var o=i;i=0;for(var s=67108863&n,l=Math.min(a,e.length-1),c=Math.max(0,a-t.length+1);c<=l;c++){var u=a-c,h=(0|t.words[u])*(0|e.words[c]),f=67108863&h;s=67108863&(f=f+s|0),i+=(o=(o=o+(h/67108864|0)|0)+(f>>>26)|0)>>>26,o&=67108863}r.words[a]=s,n=o,o=i}return 0!==n?r.words[a]=n:r.length--,r.strip()}(this,t,e):d(this,t,e)},g.prototype.makeRBT=function(t){for(var e=new Array(t),r=a.prototype._countBits(t)-1,n=0;n<t;n++)e[n]=this.revBin(n,r,t);return e},g.prototype.revBin=function(t,e,r){if(0===t||t===r-1)return t;for(var n=0,i=0;i<e;i++)n|=(1&t)<<e-i-1,t>>=1;return n},g.prototype.permute=function(t,e,r,n,i,a){for(var o=0;o<a;o++)n[o]=e[t[o]],i[o]=r[t[o]]},g.prototype.transform=function(t,e,r,n,i,a){this.permute(a,t,e,r,n,i);for(var o=1;o<i;o<<=1)for(var s=o<<1,l=Math.cos(2*Math.PI/s),c=Math.sin(2*Math.PI/s),u=0;u<i;u+=s)for(var h=l,f=c,p=0;p<o;p++){var d=r[u+p],g=n[u+p],v=r[u+p+o],m=n[u+p+o],y=h*v-f*m;m=h*m+f*v,v=y,r[u+p]=d+v,n[u+p]=g+m,r[u+p+o]=d-v,n[u+p+o]=g-m,p!==s&&(y=l*h-c*f,f=l*f+c*h,h=y)}},g.prototype.guessLen13b=function(t,e){var r=1|Math.max(e,t),n=1&r,i=0;for(r=r/2|0;r;r>>>=1)i++;return 1<<i+1+n},g.prototype.conjugate=function(t,e,r){if(!(r<=1))for(var n=0;n<r/2;n++){var i=t[n];t[n]=t[r-n-1],t[r-n-1]=i,i=e[n],e[n]=-e[r-n-1],e[r-n-1]=-i}},g.prototype.normalize13b=function(t,e){for(var r=0,n=0;n<e/2;n++){var i=8192*Math.round(t[2*n+1]/e)+Math.round(t[2*n]/e)+r;t[n]=67108863&i,r=i<67108864?0:i/67108864|0}return t},g.prototype.convert13b=function(t,e,r,i){for(var a=0,o=0;o<e;o++)a+=0|t[o],r[2*o]=8191&a,a>>>=13,r[2*o+1]=8191&a,a>>>=13;for(o=2*e;o<i;++o)r[o]=0;n(0===a),n(0==(-8192&a))},g.prototype.stub=function(t){for(var e=new Array(t),r=0;r<t;r++)e[r]=0;return e},g.prototype.mulp=function(t,e,r){var n=2*this.guessLen13b(t.length,e.length),i=this.makeRBT(n),a=this.stub(n),o=new Array(n),s=new Array(n),l=new Array(n),c=new Array(n),u=new Array(n),h=new Array(n),f=r.words;f.length=n,this.convert13b(t.words,t.length,o,n),this.convert13b(e.words,e.length,c,n),this.transform(o,a,s,l,n,i),this.transform(c,a,u,h,n,i);for(var p=0;p<n;p++){var d=s[p]*u[p]-l[p]*h[p];l[p]=s[p]*h[p]+l[p]*u[p],s[p]=d}return this.conjugate(s,l,n),this.transform(s,l,f,a,n,i),this.conjugate(f,a,n),this.normalize13b(f,n),r.negative=t.negative^e.negative,r.length=t.length+e.length,r.strip()},a.prototype.mul=function(t){var e=new a(null);return e.words=new Array(this.length+t.length),this.mulTo(t,e)},a.prototype.mulf=function(t){var e=new a(null);return e.words=new Array(this.length+t.length),d(this,t,e)},a.prototype.imul=function(t){return this.clone().mulTo(t,this)},a.prototype.imuln=function(t){n("number"==typeof t),n(t<67108864);for(var e=0,r=0;r<this.length;r++){var i=(0|this.words[r])*t,a=(67108863&i)+(67108863&e);e>>=26,e+=i/67108864|0,e+=a>>>26,this.words[r]=67108863&a}return 0!==e&&(this.words[r]=e,this.length++),this},a.prototype.muln=function(t){return this.clone().imuln(t)},a.prototype.sqr=function(){return this.mul(this)},a.prototype.isqr=function(){return this.imul(this.clone())},a.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r<e.length;r++){var n=r/26|0,i=r%26;e[r]=(t.words[n]&1<<i)>>>i}return e}(t);if(0===e.length)return new a(1);for(var r=this,n=0;n<e.length&&0===e[n];n++,r=r.sqr());if(++n<e.length)for(var i=r.sqr();n<e.length;n++,i=i.sqr())0!==e[n]&&(r=r.mul(i));return r},a.prototype.iushln=function(t){n("number"==typeof t&&t>=0);var e,r=t%26,i=(t-r)/26,a=67108863>>>26-r<<26-r;if(0!==r){var o=0;for(e=0;e<this.length;e++){var s=this.words[e]&a,l=(0|this.words[e])-s<<r;this.words[e]=l|o,o=s>>>26-r}o&&(this.words[e]=o,this.length++)}if(0!==i){for(e=this.length-1;e>=0;e--)this.words[e+i]=this.words[e];for(e=0;e<i;e++)this.words[e]=0;this.length+=i}return this.strip()},a.prototype.ishln=function(t){return n(0===this.negative),this.iushln(t)},a.prototype.iushrn=function(t,e,r){var i;n("number"==typeof t&&t>=0),i=e?(e-e%26)/26:0;var a=t%26,o=Math.min((t-a)/26,this.length),s=67108863^67108863>>>a<<a,l=r;if(i-=o,i=Math.max(0,i),l){for(var c=0;c<o;c++)l.words[c]=this.words[c];l.length=o}if(0===o);else if(this.length>o)for(this.length-=o,c=0;c<this.length;c++)this.words[c]=this.words[c+o];else this.words[0]=0,this.length=1;var u=0;for(c=this.length-1;c>=0&&(0!==u||c>=i);c--){var h=0|this.words[c];this.words[c]=u<<26-a|h>>>a,u=h&s}return l&&0!==u&&(l.words[l.length++]=u),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},a.prototype.ishrn=function(t,e,r){return n(0===this.negative),this.iushrn(t,e,r)},a.prototype.shln=function(t){return this.clone().ishln(t)},a.prototype.ushln=function(t){return this.clone().iushln(t)},a.prototype.shrn=function(t){return this.clone().ishrn(t)},a.prototype.ushrn=function(t){return this.clone().iushrn(t)},a.prototype.testn=function(t){n("number"==typeof t&&t>=0);var e=t%26,r=(t-e)/26,i=1<<e;return!(this.length<=r)&&!!(this.words[r]&i)},a.prototype.imaskn=function(t){n("number"==typeof t&&t>=0);var e=t%26,r=(t-e)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==e&&r++,this.length=Math.min(r,this.length),0!==e){var i=67108863^67108863>>>e<<e;this.words[this.length-1]&=i}return this.strip()},a.prototype.maskn=function(t){return this.clone().imaskn(t)},a.prototype.iaddn=function(t){return n("number"==typeof t),n(t<67108864),t<0?this.isubn(-t):0!==this.negative?1===this.length&&(0|this.words[0])<t?(this.words[0]=t-(0|this.words[0]),this.negative=0,this):(this.negative=0,this.isubn(t),this.negative=1,this):this._iaddn(t)},a.prototype._iaddn=function(t){this.words[0]+=t;for(var e=0;e<this.length&&this.words[e]>=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},a.prototype.isubn=function(t){if(n("number"==typeof t),n(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e<this.length&&this.words[e]<0;e++)this.words[e]+=67108864,this.words[e+1]-=1;return this.strip()},a.prototype.addn=function(t){return this.clone().iaddn(t)},a.prototype.subn=function(t){return this.clone().isubn(t)},a.prototype.iabs=function(){return this.negative=0,this},a.prototype.abs=function(){return this.clone().iabs()},a.prototype._ishlnsubmul=function(t,e,r){var i,a,o=t.length+r;this._expand(o);var s=0;for(i=0;i<t.length;i++){a=(0|this.words[i+r])+s;var l=(0|t.words[i])*e;s=((a-=67108863&l)>>26)-(l/67108864|0),this.words[i+r]=67108863&a}for(;i<this.length-r;i++)s=(a=(0|this.words[i+r])+s)>>26,this.words[i+r]=67108863&a;if(0===s)return this.strip();for(n(-1===s),s=0,i=0;i<this.length;i++)s=(a=-(0|this.words[i])+s)>>26,this.words[i]=67108863&a;return this.negative=1,this.strip()},a.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),i=t,o=0|i.words[i.length-1];0!==(r=26-this._countBits(o))&&(i=i.ushln(r),n.iushln(r),o=0|i.words[i.length-1]);var s,l=n.length-i.length;if("mod"!==e){(s=new a(null)).length=l+1,s.words=new Array(s.length);for(var c=0;c<s.length;c++)s.words[c]=0}var u=n.clone()._ishlnsubmul(i,1,l);0===u.negative&&(n=u,s&&(s.words[l]=1));for(var h=l-1;h>=0;h--){var f=67108864*(0|n.words[i.length+h])+(0|n.words[i.length+h-1]);for(f=Math.min(f/o|0,67108863),n._ishlnsubmul(i,f,h);0!==n.negative;)f--,n.negative=0,n._ishlnsubmul(i,1,h),n.isZero()||(n.negative^=1);s&&(s.words[h]=f)}return s&&s.strip(),n.strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:s||null,mod:n}},a.prototype.divmod=function(t,e,r){return n(!t.isZero()),this.isZero()?{div:new a(0),mod:new a(0)}:0!==this.negative&&0===t.negative?(s=this.neg().divmod(t,e),"mod"!==e&&(i=s.div.neg()),"div"!==e&&(o=s.mod.neg(),r&&0!==o.negative&&o.iadd(t)),{div:i,mod:o}):0===this.negative&&0!==t.negative?(s=this.divmod(t.neg(),e),"mod"!==e&&(i=s.div.neg()),{div:i,mod:s.mod}):0!=(this.negative&t.negative)?(s=this.neg().divmod(t.neg(),e),"div"!==e&&(o=s.mod.neg(),r&&0!==o.negative&&o.isub(t)),{div:s.div,mod:o}):t.length>this.length||this.cmp(t)<0?{div:new a(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new a(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new a(this.modn(t.words[0]))}:this._wordDiv(t,e);var i,o,s},a.prototype.div=function(t){return this.divmod(t,"div",!1).div},a.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},a.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},a.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),i=t.andln(1),a=r.cmp(n);return a<0||1===i&&0===a?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},a.prototype.modn=function(t){n(t<=67108863);for(var e=(1<<26)%t,r=0,i=this.length-1;i>=0;i--)r=(e*r+(0|this.words[i]))%t;return r},a.prototype.idivn=function(t){n(t<=67108863);for(var e=0,r=this.length-1;r>=0;r--){var i=(0|this.words[r])+67108864*e;this.words[r]=i/t|0,e=i%t}return this.strip()},a.prototype.divn=function(t){return this.clone().idivn(t)},a.prototype.egcd=function(t){n(0===t.negative),n(!t.isZero());var e=this,r=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var i=new a(1),o=new a(0),s=new a(0),l=new a(1),c=0;e.isEven()&&r.isEven();)e.iushrn(1),r.iushrn(1),++c;for(var u=r.clone(),h=e.clone();!e.isZero();){for(var f=0,p=1;0==(e.words[0]&p)&&f<26;++f,p<<=1);if(f>0)for(e.iushrn(f);f-- >0;)(i.isOdd()||o.isOdd())&&(i.iadd(u),o.isub(h)),i.iushrn(1),o.iushrn(1);for(var d=0,g=1;0==(r.words[0]&g)&&d<26;++d,g<<=1);if(d>0)for(r.iushrn(d);d-- >0;)(s.isOdd()||l.isOdd())&&(s.iadd(u),l.isub(h)),s.iushrn(1),l.iushrn(1);e.cmp(r)>=0?(e.isub(r),i.isub(s),o.isub(l)):(r.isub(e),s.isub(i),l.isub(o))}return{a:s,b:l,gcd:r.iushln(c)}},a.prototype._invmp=function(t){n(0===t.negative),n(!t.isZero());var e=this,r=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var i,o=new a(1),s=new a(0),l=r.clone();e.cmpn(1)>0&&r.cmpn(1)>0;){for(var c=0,u=1;0==(e.words[0]&u)&&c<26;++c,u<<=1);if(c>0)for(e.iushrn(c);c-- >0;)o.isOdd()&&o.iadd(l),o.iushrn(1);for(var h=0,f=1;0==(r.words[0]&f)&&h<26;++h,f<<=1);if(h>0)for(r.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(l),s.iushrn(1);e.cmp(r)>=0?(e.isub(r),o.isub(s)):(r.isub(e),s.isub(o))}return(i=0===e.cmpn(1)?o:s).cmpn(0)<0&&i.iadd(t),i},a.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=e.cmp(r);if(i<0){var a=e;e=r,r=a}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},a.prototype.invm=function(t){return this.egcd(t).a.umod(t)},a.prototype.isEven=function(){return 0==(1&this.words[0])},a.prototype.isOdd=function(){return 1==(1&this.words[0])},a.prototype.andln=function(t){return this.words[0]&t},a.prototype.bincn=function(t){n("number"==typeof t);var e=t%26,r=(t-e)/26,i=1<<e;if(this.length<=r)return this._expand(r+1),this.words[r]|=i,this;for(var a=i,o=r;0!==a&&o<this.length;o++){var s=0|this.words[o];a=(s+=a)>>>26,s&=67108863,this.words[o]=s}return 0!==a&&(this.words[o]=a,this.length++),this},a.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},a.prototype.cmpn=function(t){var e,r=t<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this.strip(),this.length>1)e=1;else{r&&(t=-t),n(t<=67108863,"Number is too big");var i=0|this.words[0];e=i===t?0:i<t?-1:1}return 0!==this.negative?0|-e:e},a.prototype.cmp=function(t){if(0!==this.negative&&0===t.negative)return-1;if(0===this.negative&&0!==t.negative)return 1;var e=this.ucmp(t);return 0!==this.negative?0|-e:e},a.prototype.ucmp=function(t){if(this.length>t.length)return 1;if(this.length<t.length)return-1;for(var e=0,r=this.length-1;r>=0;r--){var n=0|this.words[r],i=0|t.words[r];if(n!==i){n<i?e=-1:n>i&&(e=1);break}}return e},a.prototype.gtn=function(t){return 1===this.cmpn(t)},a.prototype.gt=function(t){return 1===this.cmp(t)},a.prototype.gten=function(t){return this.cmpn(t)>=0},a.prototype.gte=function(t){return this.cmp(t)>=0},a.prototype.ltn=function(t){return-1===this.cmpn(t)},a.prototype.lt=function(t){return-1===this.cmp(t)},a.prototype.lten=function(t){return this.cmpn(t)<=0},a.prototype.lte=function(t){return this.cmp(t)<=0},a.prototype.eqn=function(t){return 0===this.cmpn(t)},a.prototype.eq=function(t){return 0===this.cmp(t)},a.red=function(t){return new w(t)},a.prototype.toRed=function(t){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},a.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},a.prototype._forceRed=function(t){return this.red=t,this},a.prototype.forceRed=function(t){return n(!this.red,"Already a number in reduction context"),this._forceRed(t)},a.prototype.redAdd=function(t){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},a.prototype.redIAdd=function(t){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},a.prototype.redSub=function(t){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},a.prototype.redISub=function(t){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},a.prototype.redShl=function(t){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},a.prototype.redMul=function(t){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},a.prototype.redIMul=function(t){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},a.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},a.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},a.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},a.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},a.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},a.prototype.redPow=function(t){return n(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var v={k256:null,p224:null,p192:null,p25519:null};function m(t,e){this.name=t,this.p=new a(e,16),this.n=this.p.bitLength(),this.k=new a(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function y(){m.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function x(){m.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function b(){m.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function _(){m.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function w(t){if("string"==typeof t){var e=a._prime(t);this.m=e.p,this.prime=e}else n(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function k(t){w.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new a(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}m.prototype._tmp=function(){var t=new a(null);return t.words=new Array(Math.ceil(this.n/13)),t},m.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e<this.n?-1:r.ucmp(this.p);return 0===n?(r.words[0]=0,r.length=1):n>0?r.isub(this.p):r.strip(),r},m.prototype.split=function(t,e){t.iushrn(this.n,0,e)},m.prototype.imulK=function(t){return t.imul(this.k)},i(y,m),y.prototype.split=function(t,e){for(var r=Math.min(t.length,9),n=0;n<r;n++)e.words[n]=t.words[n];if(e.length=r,t.length<=9)return t.words[0]=0,void(t.length=1);var i=t.words[9];for(e.words[e.length++]=4194303&i,n=10;n<t.length;n++){var a=0|t.words[n];t.words[n-10]=(4194303&a)<<4|i>>>22,i=a}i>>>=22,t.words[n-10]=i,0===i&&t.length>10?t.length-=10:t.length-=9},y.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r<t.length;r++){var n=0|t.words[r];e+=977*n,t.words[r]=67108863&e,e=64*n+(e/67108864|0)}return 0===t.words[t.length-1]&&(t.length--,0===t.words[t.length-1]&&t.length--),t},i(x,m),i(b,m),i(_,m),_.prototype.imulK=function(t){for(var e=0,r=0;r<t.length;r++){var n=19*(0|t.words[r])+e,i=67108863&n;n>>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},a._prime=function(t){if(v[t])return v[t];var e;if("k256"===t)e=new y;else if("p224"===t)e=new x;else if("p192"===t)e=new b;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new _}return v[t]=e,e},w.prototype._verify1=function(t){n(0===t.negative,"red works only with positives"),n(t.red,"red works only with red numbers")},w.prototype._verify2=function(t,e){n(0==(t.negative|e.negative),"red works only with positives"),n(t.red&&t.red===e.red,"red works only with red numbers")},w.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},w.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},w.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},w.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},w.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},w.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},w.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},w.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},w.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},w.prototype.isqr=function(t){return this.imul(t,t.clone())},w.prototype.sqr=function(t){return this.mul(t,t)},w.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(n(e%2==1),3===e){var r=this.m.add(new a(1)).iushrn(2);return this.pow(t,r)}for(var i=this.m.subn(1),o=0;!i.isZero()&&0===i.andln(1);)o++,i.iushrn(1);n(!i.isZero());var s=new a(1).toRed(this),l=s.redNeg(),c=this.m.subn(1).iushrn(1),u=this.m.bitLength();for(u=new a(2*u*u).toRed(this);0!==this.pow(u,c).cmp(l);)u.redIAdd(l);for(var h=this.pow(u,i),f=this.pow(t,i.addn(1).iushrn(1)),p=this.pow(t,i),d=o;0!==p.cmp(s);){for(var g=p,v=0;0!==g.cmp(s);v++)g=g.redSqr();n(v<d);var m=this.pow(h,new a(1).iushln(d-v-1));f=f.redMul(m),h=m.redSqr(),p=p.redMul(h),d=v}return f},w.prototype.invm=function(t){var e=t._invmp(this.m);return 0!==e.negative?(e.negative=0,this.imod(e).redNeg()):this.imod(e)},w.prototype.pow=function(t,e){if(e.isZero())return new a(1).toRed(this);if(0===e.cmpn(1))return t.clone();var r=new Array(16);r[0]=new a(1).toRed(this),r[1]=t;for(var n=2;n<r.length;n++)r[n]=this.mul(r[n-1],t);var i=r[0],o=0,s=0,l=e.bitLength()%26;for(0===l&&(l=26),n=e.length-1;n>=0;n--){for(var c=e.words[n],u=l-1;u>=0;u--){var h=c>>u&1;i!==r[0]&&(i=this.sqr(i)),0!==h||0!==o?(o<<=1,o|=h,(4===++s||0===n&&0===u)&&(i=this.mul(i,r[o]),s=0,o=0)):s=0}l=26}return i},w.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},w.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},a.mont=function(t){return new k(t)},i(k,w),k.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},k.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},k.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},k.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new a(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},k.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}("undefined"==typeof e||e,this)},{buffer:91}],83:[function(t,e,r){"use strict";e.exports=function(t){var e,r,n,i=t.length,a=0;for(e=0;e<i;++e)a+=t[e].length;var o=new Array(a),s=0;for(e=0;e<i;++e){var l=t[e],c=l.length;for(r=0;r<c;++r){var u=o[s++]=new Array(c-1),h=0;for(n=0;n<c;++n)n!==r&&(u[h++]=l[n]);if(1&r){var f=u[1];u[1]=u[0],u[0]=f}}}return o}},{}],84:[function(t,e,r){"use strict";e.exports=function(t,e,r){switch(arguments.length){case 1:return n=[],c(i=t,i,u,!0),n;case 2:return"function"==typeof e?c(t,t,e,!0):function(t,e){return n=[],c(t,e,u,!1),n}(t,e);case 3:return c(t,e,r,!1);default:throw new Error("box-intersect: Invalid arguments")}var i};var n,i=t("typedarray-pool"),a=t("./lib/sweep"),o=t("./lib/intersect");function s(t,e){for(var r=0;r<t;++r)if(!(e[r]<=e[r+t]))return!0;return!1}function l(t,e,r,n){for(var i=0,a=0,o=0,l=t.length;o<l;++o){var c=t[o];if(!s(e,c)){for(var u=0;u<2*e;++u)r[i++]=c[u];n[a++]=o}}return a}function c(t,e,r,n){var s=t.length,c=e.length;if(!(s<=0||c<=0)){var u=t[0].length>>>1;if(!(u<=0)){var h,f=i.mallocDouble(2*u*s),p=i.mallocInt32(s);if((s=l(t,u,f,p))>0){if(1===u&&n)a.init(s),h=a.sweepComplete(u,r,0,s,f,p,0,s,f,p);else{var d=i.mallocDouble(2*u*c),g=i.mallocInt32(c);(c=l(e,u,d,g))>0&&(a.init(s+c),h=1===u?a.sweepBipartite(u,r,0,s,f,p,0,c,d,g):o(u,r,n,s,f,p,c,d,g),i.free(d),i.free(g))}i.free(f),i.free(p)}return h}}}function u(t,e){n.push([t,e])}},{"./lib/intersect":86,"./lib/sweep":90,"typedarray-pool":526}],85:[function(t,e,r){"use strict";var n="d",i="ax",a="vv",o="fp",s="es",l="rs",c="re",u="rb",h="ri",f="rp",p="bs",d="be",g="bb",v="bi",m="bp",y="rv",x="Q",b=[n,i,a,l,c,u,h,p,d,g,v];function _(t){var e="bruteForce"+(t?"Full":"Partial"),r=[],_=b.slice();t||_.splice(3,0,o);var w=["function "+e+"("+_.join()+"){"];function k(e,o){var _=function(t,e,r){var o="bruteForce"+(t?"Red":"Blue")+(e?"Flip":"")+(r?"Full":""),_=["function ",o,"(",b.join(),"){","var ",s,"=2*",n,";"],w="for(var i="+l+","+f+"="+s+"*"+l+";i<"+c+";++i,"+f+"+="+s+"){var x0="+u+"["+i+"+"+f+"],x1="+u+"["+i+"+"+f+"+"+n+"],xi="+h+"[i];",k="for(var j="+p+","+m+"="+s+"*"+p+";j<"+d+";++j,"+m+"+="+s+"){var y0="+g+"["+i+"+"+m+"],"+(r?"y1="+g+"["+i+"+"+m+"+"+n+"],":"")+"yi="+v+"[j];";return t?_.push(w,x,":",k):_.push(k,x,":",w),r?_.push("if(y1<x0||x1<y0)continue;"):e?_.push("if(y0<=x0||x1<y0)continue;"):_.push("if(y0<x0||x1<y0)continue;"),_.push("for(var k="+i+"+1;k<"+n+";++k){var r0="+u+"[k+"+f+"],r1="+u+"[k+"+n+"+"+f+"],b0="+g+"[k+"+m+"],b1="+g+"[k+"+n+"+"+m+"];if(r1<b0||b1<r0)continue "+x+";}var "+y+"="+a+"("),e?_.push("yi,xi"):_.push("xi,yi"),_.push(");if("+y+"!==void 0)return "+y+";}}}"),{name:o,code:_.join("")}}(e,o,t);r.push(_.code),w.push("return "+_.name+"("+b.join()+");")}w.push("if("+c+"-"+l+">"+d+"-"+p+"){"),t?(k(!0,!1),w.push("}else{"),k(!1,!1)):(w.push("if("+o+"){"),k(!0,!0),w.push("}else{"),k(!0,!1),w.push("}}else{if("+o+"){"),k(!1,!0),w.push("}else{"),k(!1,!1),w.push("}")),w.push("}}return "+e);var A=r.join("")+w.join("");return new Function(A)()}r.partial=_(!1),r.full=_(!0)},{}],86:[function(t,e,r){"use strict";e.exports=function(t,e,r,a,u,S,E,C,L){!function(t,e){var r=8*i.log2(e+1)*(t+1)|0,a=i.nextPow2(b*r);w.length<a&&(n.free(w),w=n.mallocInt32(a));var o=i.nextPow2(_*r);k<o&&(n.free(k),k=n.mallocDouble(o))}(t,a+E);var z,O=0,I=2*t;A(O++,0,0,a,0,E,r?16:0,-1/0,1/0),r||A(O++,0,0,E,0,a,1,-1/0,1/0);for(;O>0;){var D=(O-=1)*b,P=w[D],R=w[D+1],F=w[D+2],B=w[D+3],N=w[D+4],j=w[D+5],V=O*_,U=k[V],q=k[V+1],H=1&j,G=!!(16&j),Y=u,W=S,X=C,Z=L;if(H&&(Y=C,W=L,X=u,Z=S),!(2&j&&(F=v(t,P,R,F,Y,W,q),R>=F)||4&j&&(R=m(t,P,R,F,Y,W,U))>=F)){var $=F-R,J=N-B;if(G){if(t*$*($+J)<p){if(void 0!==(z=l.scanComplete(t,P,e,R,F,Y,W,B,N,X,Z)))return z;continue}}else{if(t*Math.min($,J)<h){if(void 0!==(z=o(t,P,e,H,R,F,Y,W,B,N,X,Z)))return z;continue}if(t*$*J<f){if(void 0!==(z=l.scanBipartite(t,P,e,H,R,F,Y,W,B,N,X,Z)))return z;continue}}var K=d(t,P,R,F,Y,W,U,q);if(R<K)if(t*(K-R)<h){if(void 0!==(z=s(t,P+1,e,R,K,Y,W,B,N,X,Z)))return z}else if(P===t-2){if(void 0!==(z=H?l.sweepBipartite(t,e,B,N,X,Z,R,K,Y,W):l.sweepBipartite(t,e,R,K,Y,W,B,N,X,Z)))return z}else A(O++,P+1,R,K,B,N,H,-1/0,1/0),A(O++,P+1,B,N,R,K,1^H,-1/0,1/0);if(K<F){var Q=c(t,P,B,N,X,Z),tt=X[I*Q+P],et=g(t,P,Q,N,X,Z,tt);if(et<N&&A(O++,P,K,F,et,N,(4|H)+(G?16:0),tt,q),B<Q&&A(O++,P,K,F,B,Q,(2|H)+(G?16:0),U,tt),Q+1===et){if(void 0!==(z=G?T(t,P,e,K,F,Y,W,Q,X,Z[Q]):M(t,P,e,H,K,F,Y,W,Q,X,Z[Q])))return z}else if(Q<et){var rt;if(G){if(rt=y(t,P,K,F,Y,W,tt),K<rt){var nt=g(t,P,K,rt,Y,W,tt);if(P===t-2){if(K<nt&&void 0!==(z=l.sweepComplete(t,e,K,nt,Y,W,Q,et,X,Z)))return z;if(nt<rt&&void 0!==(z=l.sweepBipartite(t,e,nt,rt,Y,W,Q,et,X,Z)))return z}else K<nt&&A(O++,P+1,K,nt,Q,et,16,-1/0,1/0),nt<rt&&(A(O++,P+1,nt,rt,Q,et,0,-1/0,1/0),A(O++,P+1,Q,et,nt,rt,1,-1/0,1/0))}}else rt=H?x(t,P,K,F,Y,W,tt):y(t,P,K,F,Y,W,tt),K<rt&&(P===t-2?z=H?l.sweepBipartite(t,e,Q,et,X,Z,K,rt,Y,W):l.sweepBipartite(t,e,K,rt,Y,W,Q,et,X,Z):(A(O++,P+1,K,rt,Q,et,H,-1/0,1/0),A(O++,P+1,Q,et,K,rt,1^H,-1/0,1/0)))}}}}};var n=t("typedarray-pool"),i=t("bit-twiddle"),a=t("./brute"),o=a.partial,s=a.full,l=t("./sweep"),c=t("./median"),u=t("./partition"),h=128,f=1<<22,p=1<<22,d=u("!(lo>=p0)&&!(p1>=hi)",["p0","p1"]),g=u("lo===p0",["p0"]),v=u("lo<p0",["p0"]),m=u("hi<=p0",["p0"]),y=u("lo<=p0&&p0<=hi",["p0"]),x=u("lo<p0&&p0<=hi",["p0"]),b=6,_=2,w=n.mallocInt32(1024),k=n.mallocDouble(1024);function A(t,e,r,n,i,a,o,s,l){var c=b*t;w[c]=e,w[c+1]=r,w[c+2]=n,w[c+3]=i,w[c+4]=a,w[c+5]=o;var u=_*t;k[u]=s,k[u+1]=l}function M(t,e,r,n,i,a,o,s,l,c,u){var h=2*t,f=l*h,p=c[f+e];t:for(var d=i,g=i*h;d<a;++d,g+=h){var v=o[g+e],m=o[g+e+t];if(!(p<v||m<p)&&(!n||p!==v)){for(var y,x=s[d],b=e+1;b<t;++b){v=o[g+b],m=o[g+b+t];var _=c[f+b],w=c[f+b+t];if(m<_||w<v)continue t}if(void 0!==(y=n?r(u,x):r(x,u)))return y}}}function T(t,e,r,n,i,a,o,s,l,c){var u=2*t,h=s*u,f=l[h+e];t:for(var p=n,d=n*u;p<i;++p,d+=u){var g=o[p];if(g!==c){var v=a[d+e],m=a[d+e+t];if(!(f<v||m<f)){for(var y=e+1;y<t;++y){v=a[d+y],m=a[d+y+t];var x=l[h+y],b=l[h+y+t];if(m<x||b<v)continue t}var _=r(g,c);if(void 0!==_)return _}}}}},{"./brute":85,"./median":87,"./partition":88,"./sweep":90,"bit-twiddle":80,"typedarray-pool":526}],87:[function(t,e,r){"use strict";e.exports=function(t,e,r,o,s,l){if(o<=r+1)return r;var c=r,u=o,h=o+r>>>1,f=2*t,p=h,d=s[f*h+e];for(;c<u;){if(u-c<i){a(t,e,c,u,s,l),d=s[f*h+e];break}var g=u-c,v=Math.random()*g+c|0,m=s[f*v+e],y=Math.random()*g+c|0,x=s[f*y+e],b=Math.random()*g+c|0,_=s[f*b+e];m<=x?_>=x?(p=y,d=x):m>=_?(p=v,d=m):(p=b,d=_):x>=_?(p=y,d=x):_>=m?(p=v,d=m):(p=b,d=_);for(var w=f*(u-1),k=f*p,A=0;A<f;++A,++w,++k){var M=s[w];s[w]=s[k],s[k]=M}var T=l[u-1];l[u-1]=l[p],l[p]=T,p=n(t,e,c,u-1,s,l,d);for(var w=f*(u-1),k=f*p,A=0;A<f;++A,++w,++k){var M=s[w];s[w]=s[k],s[k]=M}var T=l[u-1];if(l[u-1]=l[p],l[p]=T,h<p){for(u=p-1;c<u&&s[f*(u-1)+e]===d;)u-=1;u+=1}else{if(!(p<h))break;for(c=p+1;c<u&&s[f*c+e]===d;)c+=1}}return n(t,e,r,h,s,l,s[f*h+e])};var n=t("./partition")("lo<p0",["p0"]),i=8;function a(t,e,r,n,i,a){for(var o=2*t,s=o*(r+1)+e,l=r+1;l<n;++l,s+=o)for(var c=i[s],u=l,h=o*(l-1);u>r&&i[h+e]>c;--u,h-=o){for(var f=h,p=h+o,d=0;d<o;++d,++f,++p){var g=i[f];i[f]=i[p],i[p]=g}var v=a[u];a[u]=a[u-1],a[u-1]=v}}},{"./partition":88}],88:[function(t,e,r){"use strict";e.exports=function(t,e){var r="abcdef".split("").concat(e),i=[];t.indexOf("lo")>=0&&i.push("lo=e[k+n]");t.indexOf("hi")>=0&&i.push("hi=e[k+o]");return r.push(n.replace("_",i.join()).replace("$",t)),Function.apply(void 0,r)};var n="for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m"},{}],89:[function(t,e,r){"use strict";e.exports=function(t,e){e<=4*n?i(0,e-1,t):function t(e,r,h){var f=(r-e+1)/6|0,p=e+f,d=r-f,g=e+r>>1,v=g-f,m=g+f,y=p,x=v,b=g,_=m,w=d,k=e+1,A=r-1,M=0;c(y,x,h)&&(M=y,y=x,x=M);c(_,w,h)&&(M=_,_=w,w=M);c(y,b,h)&&(M=y,y=b,b=M);c(x,b,h)&&(M=x,x=b,b=M);c(y,_,h)&&(M=y,y=_,_=M);c(b,_,h)&&(M=b,b=_,_=M);c(x,w,h)&&(M=x,x=w,w=M);c(x,b,h)&&(M=x,x=b,b=M);c(_,w,h)&&(M=_,_=w,w=M);var T=h[2*x];var S=h[2*x+1];var E=h[2*_];var C=h[2*_+1];var L=2*y;var z=2*b;var O=2*w;var I=2*p;var D=2*g;var P=2*d;for(var R=0;R<2;++R){var F=h[L+R],B=h[z+R],N=h[O+R];h[I+R]=F,h[D+R]=B,h[P+R]=N}o(v,e,h);o(m,r,h);for(var j=k;j<=A;++j)if(u(j,T,S,h))j!==k&&a(j,k,h),++k;else if(!u(j,E,C,h))for(;;){if(u(A,E,C,h)){u(A,T,S,h)?(s(j,k,A,h),++k,--A):(a(j,A,h),--A);break}if(--A<j)break}l(e,k-1,T,S,h);l(r,A+1,E,C,h);k-2-e<=n?i(e,k-2,h):t(e,k-2,h);r-(A+2)<=n?i(A+2,r,h):t(A+2,r,h);A-k<=n?i(k,A,h):t(k,A,h)}(0,e-1,t)};var n=32;function i(t,e,r){for(var n=2*(t+1),i=t+1;i<=e;++i){for(var a=r[n++],o=r[n++],s=i,l=n-2;s-- >t;){var c=r[l-2],u=r[l-1];if(c<a)break;if(c===a&&u<o)break;r[l]=c,r[l+1]=u,l-=2}r[l]=a,r[l+1]=o}}function a(t,e,r){e*=2;var n=r[t*=2],i=r[t+1];r[t]=r[e],r[t+1]=r[e+1],r[e]=n,r[e+1]=i}function o(t,e,r){e*=2,r[t*=2]=r[e],r[t+1]=r[e+1]}function s(t,e,r,n){e*=2,r*=2;var i=n[t*=2],a=n[t+1];n[t]=n[e],n[t+1]=n[e+1],n[e]=n[r],n[e+1]=n[r+1],n[r]=i,n[r+1]=a}function l(t,e,r,n,i){e*=2,i[t*=2]=i[e],i[e]=r,i[t+1]=i[e+1],i[e+1]=n}function c(t,e,r){e*=2;var n=r[t*=2],i=r[e];return!(n<i)&&(n!==i||r[t+1]>r[e+1])}function u(t,e,r,n){var i=n[t*=2];return i<e||i===e&&n[t+1]<r}},{}],90:[function(t,e,r){"use strict";e.exports={init:function(t){var e=i.nextPow2(t);s.length<e&&(n.free(s),s=n.mallocInt32(e));l.length<e&&(n.free(l),l=n.mallocInt32(e));c.length<e&&(n.free(c),c=n.mallocInt32(e));u.length<e&&(n.free(u),u=n.mallocInt32(e));h.length<e&&(n.free(h),h=n.mallocInt32(e));f.length<e&&(n.free(f),f=n.mallocInt32(e));var r=8*e;p.length<r&&(n.free(p),p=n.mallocDouble(r))},sweepBipartite:function(t,e,r,n,i,h,f,v,m,y){for(var x=0,b=2*t,_=t-1,w=b-1,k=r;k<n;++k){var A=h[k],M=b*k;p[x++]=i[M+_],p[x++]=-(A+1),p[x++]=i[M+w],p[x++]=A}for(var k=f;k<v;++k){var A=y[k]+o,T=b*k;p[x++]=m[T+_],p[x++]=-A,p[x++]=m[T+w],p[x++]=A}var S=x>>>1;a(p,S);for(var E=0,C=0,k=0;k<S;++k){var L=0|p[2*k+1];if(L>=o)d(c,u,C--,L=L-o|0);else if(L>=0)d(s,l,E--,L);else if(L<=-o){L=-L-o|0;for(var z=0;z<E;++z){var O=e(s[z],L);if(void 0!==O)return O}g(c,u,C++,L)}else{L=-L-1|0;for(var z=0;z<C;++z){var O=e(L,c[z]);if(void 0!==O)return O}g(s,l,E++,L)}}},sweepComplete:function(t,e,r,n,i,o,v,m,y,x){for(var b=0,_=2*t,w=t-1,k=_-1,A=r;A<n;++A){var M=o[A]+1<<1,T=_*A;p[b++]=i[T+w],p[b++]=-M,p[b++]=i[T+k],p[b++]=M}for(var A=v;A<m;++A){var M=x[A]+1<<1,S=_*A;p[b++]=y[S+w],p[b++]=1|-M,p[b++]=y[S+k],p[b++]=1|M}var E=b>>>1;a(p,E);for(var C=0,L=0,z=0,A=0;A<E;++A){var O=0|p[2*A+1],I=1&O;if(A<E-1&&O>>1==p[2*A+3]>>1&&(I=2,A+=1),O<0){for(var D=-(O>>1)-1,P=0;P<z;++P){var R=e(h[P],D);if(void 0!==R)return R}if(0!==I)for(var P=0;P<C;++P){var R=e(s[P],D);if(void 0!==R)return R}if(1!==I)for(var P=0;P<L;++P){var R=e(c[P],D);if(void 0!==R)return R}0===I?g(s,l,C++,D):1===I?g(c,u,L++,D):2===I&&g(h,f,z++,D)}else{var D=(O>>1)-1;0===I?d(s,l,C--,D):1===I?d(c,u,L--,D):2===I&&d(h,f,z--,D)}}},scanBipartite:function(t,e,r,n,i,c,u,h,f,v,m,y){var x=0,b=2*t,_=e,w=e+t,k=1,A=1;n?A=o:k=o;for(var M=i;M<c;++M){var T=M+k,S=b*M;p[x++]=u[S+_],p[x++]=-T,p[x++]=u[S+w],p[x++]=T}for(var M=f;M<v;++M){var T=M+A,E=b*M;p[x++]=m[E+_],p[x++]=-T}var C=x>>>1;a(p,C);for(var L=0,M=0;M<C;++M){var z=0|p[2*M+1];if(z<0){var T=-z,O=!1;if(T>=o?(O=!n,T-=o):(O=!!n,T-=1),O)g(s,l,L++,T);else{var I=y[T],D=b*T,P=m[D+e+1],R=m[D+e+1+t];t:for(var F=0;F<L;++F){var B=s[F],N=b*B;if(!(R<u[N+e+1]||u[N+e+1+t]<P)){for(var j=e+2;j<t;++j)if(m[D+j+t]<u[N+j]||u[N+j+t]<m[D+j])continue t;var V,U=h[B];if(void 0!==(V=n?r(I,U):r(U,I)))return V}}}}else d(s,l,L--,z-k)}},scanComplete:function(t,e,r,n,i,l,c,u,h,f,d){for(var g=0,v=2*t,m=e,y=e+t,x=n;x<i;++x){var b=x+o,_=v*x;p[g++]=l[_+m],p[g++]=-b,p[g++]=l[_+y],p[g++]=b}for(var x=u;x<h;++x){var b=x+1,w=v*x;p[g++]=f[w+m],p[g++]=-b}var k=g>>>1;a(p,k);for(var A=0,x=0;x<k;++x){var M=0|p[2*x+1];if(M<0){var b=-M;if(b>=o)s[A++]=b-o;else{var T=d[b-=1],S=v*b,E=f[S+e+1],C=f[S+e+1+t];t:for(var L=0;L<A;++L){var z=s[L],O=c[z];if(O===T)break;var I=v*z;if(!(C<l[I+e+1]||l[I+e+1+t]<E)){for(var D=e+2;D<t;++D)if(f[S+D+t]<l[I+D]||l[I+D+t]<f[S+D])continue t;var P=r(O,T);if(void 0!==P)return P}}}}else{for(var b=M-o,L=A-1;L>=0;--L)if(s[L]===b){for(var D=L+1;D<A;++D)s[D-1]=s[D];break}--A}}}};var n=t("typedarray-pool"),i=t("bit-twiddle"),a=t("./sort"),o=1<<28,s=n.mallocInt32(1024),l=n.mallocInt32(1024),c=n.mallocInt32(1024),u=n.mallocInt32(1024),h=n.mallocInt32(1024),f=n.mallocInt32(1024),p=n.mallocDouble(8192);function d(t,e,r,n){var i=e[n],a=t[r-1];t[i]=a,e[a]=i}function g(t,e,r,n){t[r]=n,e[n]=r}},{"./sort":89,"bit-twiddle":80,"typedarray-pool":526}],91:[function(t,e,r){},{}],92:[function(t,e,r){var n=Object.create||function(t){var e=function(){};return e.prototype=t,new e},i=Object.keys||function(t){var e=[];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.push(r);return r},a=Function.prototype.bind||function(t){var e=this;return function(){return e.apply(t,arguments)}};function o(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=n(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}e.exports=o,o.EventEmitter=o,o.prototype._events=void 0,o.prototype._maxListeners=void 0;var s,l=10;try{var c={};Object.defineProperty&&Object.defineProperty(c,"x",{value:0}),s=0===c.x}catch(t){s=!1}function u(t){return void 0===t._maxListeners?o.defaultMaxListeners:t._maxListeners}function h(t,e,r,i){var a,o,s;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((o=t._events)?(o.newListener&&(t.emit("newListener",e,r.listener?r.listener:r),o=t._events),s=o[e]):(o=t._events=n(null),t._eventsCount=0),s){if("function"==typeof s?s=o[e]=i?[r,s]:[s,r]:i?s.unshift(r):s.push(r),!s.warned&&(a=u(t))&&a>0&&s.length>a){s.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+s.length+' "'+String(e)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');l.name="MaxListenersExceededWarning",l.emitter=t,l.type=e,l.count=s.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",l.name,l.message)}}else s=o[e]=r,++t._eventsCount;return t}function f(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var t=new Array(arguments.length),e=0;e<t.length;++e)t[e]=arguments[e];this.listener.apply(this.target,t)}}function p(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=a.call(f,n);return i.listener=r,n.wrapFn=i,i}function d(t,e,r){var n=t._events;if(!n)return[];var i=n[e];return i?"function"==typeof i?r?[i.listener||i]:[i]:r?function(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}(i):v(i,i.length):[]}function g(t){var e=this._events;if(e){var r=e[t];if("function"==typeof r)return 1;if(r)return r.length}return 0}function v(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}s?Object.defineProperty(o,"defaultMaxListeners",{enumerable:!0,get:function(){return l},set:function(t){if("number"!=typeof t||t<0||t!=t)throw new TypeError('"defaultMaxListeners" must be a positive number');l=t}}):o.defaultMaxListeners=l,o.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||isNaN(t))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=t,this},o.prototype.getMaxListeners=function(){return u(this)},o.prototype.emit=function(t){var e,r,n,i,a,o,s="error"===t;if(o=this._events)s=s&&null==o.error;else if(!s)return!1;if(s){if(arguments.length>1&&(e=arguments[1]),e instanceof Error)throw e;var l=new Error('Unhandled "error" event. ('+e+")");throw l.context=e,l}if(!(r=o[t]))return!1;var c="function"==typeof r;switch(n=arguments.length){case 1:!function(t,e,r){if(e)t.call(r);else for(var n=t.length,i=v(t,n),a=0;a<n;++a)i[a].call(r)}(r,c,this);break;case 2:!function(t,e,r,n){if(e)t.call(r,n);else for(var i=t.length,a=v(t,i),o=0;o<i;++o)a[o].call(r,n)}(r,c,this,arguments[1]);break;case 3:!function(t,e,r,n,i){if(e)t.call(r,n,i);else for(var a=t.length,o=v(t,a),s=0;s<a;++s)o[s].call(r,n,i)}(r,c,this,arguments[1],arguments[2]);break;case 4:!function(t,e,r,n,i,a){if(e)t.call(r,n,i,a);else for(var o=t.length,s=v(t,o),l=0;l<o;++l)s[l].call(r,n,i,a)}(r,c,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(n-1),a=1;a<n;a++)i[a-1]=arguments[a];!function(t,e,r,n){if(e)t.apply(r,n);else for(var i=t.length,a=v(t,i),o=0;o<i;++o)a[o].apply(r,n)}(r,c,this,i)}return!0},o.prototype.addListener=function(t,e){return h(this,t,e,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(t,e){return h(this,t,e,!0)},o.prototype.once=function(t,e){if("function"!=typeof e)throw new TypeError('"listener" argument must be a function');return this.on(t,p(this,t,e)),this},o.prototype.prependOnceListener=function(t,e){if("function"!=typeof e)throw new TypeError('"listener" argument must be a function');return this.prependListener(t,p(this,t,e)),this},o.prototype.removeListener=function(t,e){var r,i,a,o,s;if("function"!=typeof e)throw new TypeError('"listener" argument must be a function');if(!(i=this._events))return this;if(!(r=i[t]))return this;if(r===e||r.listener===e)0==--this._eventsCount?this._events=n(null):(delete i[t],i.removeListener&&this.emit("removeListener",t,r.listener||e));else if("function"!=typeof r){for(a=-1,o=r.length-1;o>=0;o--)if(r[o]===e||r[o].listener===e){s=r[o].listener,a=o;break}if(a<0)return this;0===a?r.shift():function(t,e){for(var r=e,n=r+1,i=t.length;n<i;r+=1,n+=1)t[r]=t[n];t.pop()}(r,a),1===r.length&&(i[t]=r[0]),i.removeListener&&this.emit("removeListener",t,s||e)}return this},o.prototype.removeAllListeners=function(t){var e,r,a;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=n(null),this._eventsCount=0):r[t]&&(0==--this._eventsCount?this._events=n(null):delete r[t]),this;if(0===arguments.length){var o,s=i(r);for(a=0;a<s.length;++a)"removeListener"!==(o=s[a])&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=n(null),this._eventsCount=0,this}if("function"==typeof(e=r[t]))this.removeListener(t,e);else if(e)for(a=e.length-1;a>=0;a--)this.removeListener(t,e[a]);return this},o.prototype.listeners=function(t){return d(this,t,!0)},o.prototype.rawListeners=function(t){return d(this,t,!1)},o.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):g.call(t,e)},o.prototype.listenerCount=g,o.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],93:[function(t,e,r){"use strict";var n=t("base64-js"),i=t("ieee754");r.Buffer=s,r.SlowBuffer=function(t){+t!=t&&(t=0);return s.alloc(+t)},r.INSPECT_MAX_BYTES=50;var a=2147483647;function o(t){if(t>a)throw new RangeError('The value "'+t+'" is invalid for option "size"');var e=new Uint8Array(t);return e.__proto__=s.prototype,e}function s(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return u(t)}return l(t,e,r)}function l(t,e,r){if("string"==typeof t)return function(t,e){"string"==typeof e&&""!==e||(e="utf8");if(!s.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var r=0|p(t,e),n=o(r),i=n.write(t,e);i!==r&&(n=n.slice(0,i));return n}(t,e);if(ArrayBuffer.isView(t))return h(t);if(null==t)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(j(t,ArrayBuffer)||t&&j(t.buffer,ArrayBuffer))return function(t,e,r){if(e<0||t.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<e+(r||0))throw new RangeError('"length" is outside of buffer bounds');var n;n=void 0===e&&void 0===r?new Uint8Array(t):void 0===r?new Uint8Array(t,e):new Uint8Array(t,e,r);return n.__proto__=s.prototype,n}(t,e,r);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');var n=t.valueOf&&t.valueOf();if(null!=n&&n!==t)return s.from(n,e,r);var i=function(t){if(s.isBuffer(t)){var e=0|f(t.length),r=o(e);return 0===r.length?r:(t.copy(r,0,0,e),r)}if(void 0!==t.length)return"number"!=typeof t.length||V(t.length)?o(0):h(t);if("Buffer"===t.type&&Array.isArray(t.data))return h(t.data)}(t);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return s.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function c(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function u(t){return c(t),o(t<0?0:0|f(t))}function h(t){for(var e=t.length<0?0:0|f(t.length),r=o(e),n=0;n<e;n+=1)r[n]=255&t[n];return r}function f(t){if(t>=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return 0|t}function p(t,e){if(s.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||j(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var r=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;for(var i=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return F(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return B(t).length;default:if(i)return n?-1:F(t).length;e=(""+e).toLowerCase(),i=!0}}function d(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function g(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),V(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=s.from(e,n)),s.isBuffer(e))return 0===e.length?-1:v(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):v(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function v(t,e,r,n,i){var a,o=1,s=t.length,l=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;o=2,s/=2,l/=2,r/=2}function c(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}if(i){var u=-1;for(a=r;a<s;a++)if(c(t,a)===c(e,-1===u?0:a-u)){if(-1===u&&(u=a),a-u+1===l)return u*o}else-1!==u&&(a-=a-u),u=-1}else for(r+l>s&&(r=s-l),a=r;a>=0;a--){for(var h=!0,f=0;f<l;f++)if(c(t,a+f)!==c(e,f)){h=!1;break}if(h)return a}return-1}function m(t,e,r,n){r=Number(r)||0;var i=t.length-r;n?(n=Number(n))>i&&(n=i):n=i;var a=e.length;n>a/2&&(n=a/2);for(var o=0;o<n;++o){var s=parseInt(e.substr(2*o,2),16);if(V(s))return o;t[r+o]=s}return o}function y(t,e,r,n){return N(F(e,t.length-r),t,r,n)}function x(t,e,r,n){return N(function(t){for(var e=[],r=0;r<t.length;++r)e.push(255&t.charCodeAt(r));return e}(e),t,r,n)}function b(t,e,r,n){return x(t,e,r,n)}function _(t,e,r,n){return N(B(e),t,r,n)}function w(t,e,r,n){return N(function(t,e){for(var r,n,i,a=[],o=0;o<t.length&&!((e-=2)<0);++o)r=t.charCodeAt(o),n=r>>8,i=r%256,a.push(i),a.push(n);return a}(e,t.length-r),t,r,n)}function k(t,e,r){return 0===e&&r===t.length?n.fromByteArray(t):n.fromByteArray(t.slice(e,r))}function A(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i<r;){var a,o,s,l,c=t[i],u=null,h=c>239?4:c>223?3:c>191?2:1;if(i+h<=r)switch(h){case 1:c<128&&(u=c);break;case 2:128==(192&(a=t[i+1]))&&(l=(31&c)<<6|63&a)>127&&(u=l);break;case 3:a=t[i+1],o=t[i+2],128==(192&a)&&128==(192&o)&&(l=(15&c)<<12|(63&a)<<6|63&o)>2047&&(l<55296||l>57343)&&(u=l);break;case 4:a=t[i+1],o=t[i+2],s=t[i+3],128==(192&a)&&128==(192&o)&&128==(192&s)&&(l=(15&c)<<18|(63&a)<<12|(63&o)<<6|63&s)>65535&&l<1114112&&(u=l)}null===u?(u=65533,h=1):u>65535&&(u-=65536,n.push(u>>>10&1023|55296),u=56320|1023&u),n.push(u),i+=h}return function(t){var e=t.length;if(e<=M)return String.fromCharCode.apply(String,t);var r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=M));return r}(n)}r.kMaxLength=a,s.TYPED_ARRAY_SUPPORT=function(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()}catch(t){return!1}}(),s.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&s[Symbol.species]===s&&Object.defineProperty(s,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),s.poolSize=8192,s.from=function(t,e,r){return l(t,e,r)},s.prototype.__proto__=Uint8Array.prototype,s.__proto__=Uint8Array,s.alloc=function(t,e,r){return function(t,e,r){return c(t),t<=0?o(t):void 0!==e?"string"==typeof r?o(t).fill(e,r):o(t).fill(e):o(t)}(t,e,r)},s.allocUnsafe=function(t){return u(t)},s.allocUnsafeSlow=function(t){return u(t)},s.isBuffer=function(t){return null!=t&&!0===t._isBuffer&&t!==s.prototype},s.compare=function(t,e){if(j(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),j(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(t)||!s.isBuffer(e))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(t===e)return 0;for(var r=t.length,n=e.length,i=0,a=Math.min(r,n);i<a;++i)if(t[i]!==e[i]){r=t[i],n=e[i];break}return r<n?-1:n<r?1:0},s.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.concat=function(t,e){if(!Array.isArray(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return s.alloc(0);var r;if(void 0===e)for(e=0,r=0;r<t.length;++r)e+=t[r].length;var n=s.allocUnsafe(e),i=0;for(r=0;r<t.length;++r){var a=t[r];if(j(a,Uint8Array)&&(a=s.from(a)),!s.isBuffer(a))throw new TypeError('"list" argument must be an Array of Buffers');a.copy(n,i),i+=a.length}return n},s.byteLength=p,s.prototype._isBuffer=!0,s.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var e=0;e<t;e+=2)d(this,e,e+1);return this},s.prototype.swap32=function(){var t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var e=0;e<t;e+=4)d(this,e,e+3),d(this,e+1,e+2);return this},s.prototype.swap64=function(){var t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var e=0;e<t;e+=8)d(this,e,e+7),d(this,e+1,e+6),d(this,e+2,e+5),d(this,e+3,e+4);return this},s.prototype.toString=function(){var t=this.length;return 0===t?"":0===arguments.length?A(this,0,t):function(t,e,r){var n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return E(this,e,r);case"utf8":case"utf-8":return A(this,e,r);case"ascii":return T(this,e,r);case"latin1":case"binary":return S(this,e,r);case"base64":return k(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(t){if(!s.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===s.compare(this,t)},s.prototype.inspect=function(){var t="",e=r.INSPECT_MAX_BYTES;return t=this.toString("hex",0,e).replace(/(.{2})/g,"$1 ").trim(),this.length>e&&(t+=" ... "),"<Buffer "+t+">"},s.prototype.compare=function(t,e,r,n,i){if(j(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;for(var a=(i>>>=0)-(n>>>=0),o=(r>>>=0)-(e>>>=0),l=Math.min(a,o),c=this.slice(n,i),u=t.slice(e,r),h=0;h<l;++h)if(c[h]!==u[h]){a=c[h],o=u[h];break}return a<o?-1:o<a?1:0},s.prototype.includes=function(t,e,r){return-1!==this.indexOf(t,e,r)},s.prototype.indexOf=function(t,e,r){return g(this,t,e,r,!0)},s.prototype.lastIndexOf=function(t,e,r){return g(this,t,e,r,!1)},s.prototype.write=function(t,e,r,n){if(void 0===e)n="utf8",r=this.length,e=0;else if(void 0===r&&"string"==typeof e)n=e,r=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e>>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return m(this,t,e,r);case"utf8":case"utf-8":return y(this,t,e,r);case"ascii":return x(this,t,e,r);case"latin1":case"binary":return b(this,t,e,r);case"base64":return _(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return w(this,t,e,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var M=4096;function T(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;i<r;++i)n+=String.fromCharCode(127&t[i]);return n}function S(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;i<r;++i)n+=String.fromCharCode(t[i]);return n}function E(t,e,r){var n=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>n)&&(r=n);for(var i="",a=e;a<r;++a)i+=R(t[a]);return i}function C(t,e,r){for(var n=t.slice(e,r),i="",a=0;a<n.length;a+=2)i+=String.fromCharCode(n[a]+256*n[a+1]);return i}function L(t,e,r){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function z(t,e,r,n,i,a){if(!s.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||e<a)throw new RangeError('"value" argument is out of bounds');if(r+n>t.length)throw new RangeError("Index out of range")}function O(t,e,r,n,i,a){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function I(t,e,r,n,a){return e=+e,r>>>=0,a||O(t,0,r,4),i.write(t,e,r,n,23,4),r+4}function D(t,e,r,n,a){return e=+e,r>>>=0,a||O(t,0,r,8),i.write(t,e,r,n,52,8),r+8}s.prototype.slice=function(t,e){var r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(e=void 0===e?r:~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),e<t&&(e=t);var n=this.subarray(t,e);return n.__proto__=s.prototype,n},s.prototype.readUIntLE=function(t,e,r){t>>>=0,e>>>=0,r||L(t,e,this.length);for(var n=this[t],i=1,a=0;++a<e&&(i*=256);)n+=this[t+a]*i;return n},s.prototype.readUIntBE=function(t,e,r){t>>>=0,e>>>=0,r||L(t,e,this.length);for(var n=this[t+--e],i=1;e>0&&(i*=256);)n+=this[t+--e]*i;return n},s.prototype.readUInt8=function(t,e){return t>>>=0,e||L(t,1,this.length),this[t]},s.prototype.readUInt16LE=function(t,e){return t>>>=0,e||L(t,2,this.length),this[t]|this[t+1]<<8},s.prototype.readUInt16BE=function(t,e){return t>>>=0,e||L(t,2,this.length),this[t]<<8|this[t+1]},s.prototype.readUInt32LE=function(t,e){return t>>>=0,e||L(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},s.prototype.readUInt32BE=function(t,e){return t>>>=0,e||L(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},s.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||L(t,e,this.length);for(var n=this[t],i=1,a=0;++a<e&&(i*=256);)n+=this[t+a]*i;return n>=(i*=128)&&(n-=Math.pow(2,8*e)),n},s.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||L(t,e,this.length);for(var n=e,i=1,a=this[t+--n];n>0&&(i*=256);)a+=this[t+--n]*i;return a>=(i*=128)&&(a-=Math.pow(2,8*e)),a},s.prototype.readInt8=function(t,e){return t>>>=0,e||L(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},s.prototype.readInt16LE=function(t,e){t>>>=0,e||L(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt16BE=function(t,e){t>>>=0,e||L(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt32LE=function(t,e){return t>>>=0,e||L(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},s.prototype.readInt32BE=function(t,e){return t>>>=0,e||L(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},s.prototype.readFloatLE=function(t,e){return t>>>=0,e||L(t,4,this.length),i.read(this,t,!0,23,4)},s.prototype.readFloatBE=function(t,e){return t>>>=0,e||L(t,4,this.length),i.read(this,t,!1,23,4)},s.prototype.readDoubleLE=function(t,e){return t>>>=0,e||L(t,8,this.length),i.read(this,t,!0,52,8)},s.prototype.readDoubleBE=function(t,e){return t>>>=0,e||L(t,8,this.length),i.read(this,t,!1,52,8)},s.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e>>>=0,r>>>=0,n)||z(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,a=0;for(this[e]=255&t;++a<r&&(i*=256);)this[e+a]=t/i&255;return e+r},s.prototype.writeUIntBE=function(t,e,r,n){(t=+t,e>>>=0,r>>>=0,n)||z(this,t,e,r,Math.pow(2,8*r)-1,0);var i=r-1,a=1;for(this[e+i]=255&t;--i>=0&&(a*=256);)this[e+i]=t/a&255;return e+r},s.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||z(this,t,e,1,255,0),this[e]=255&t,e+1},s.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||z(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},s.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||z(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},s.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||z(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},s.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||z(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},s.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);z(this,t,e,r,i-1,-i)}var a=0,o=1,s=0;for(this[e]=255&t;++a<r&&(o*=256);)t<0&&0===s&&0!==this[e+a-1]&&(s=1),this[e+a]=(t/o>>0)-s&255;return e+r},s.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);z(this,t,e,r,i-1,-i)}var a=r-1,o=1,s=0;for(this[e+a]=255&t;--a>=0&&(o*=256);)t<0&&0===s&&0!==this[e+a+1]&&(s=1),this[e+a]=(t/o>>0)-s&255;return e+r},s.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||z(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},s.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||z(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},s.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||z(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},s.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||z(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},s.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||z(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},s.prototype.writeFloatLE=function(t,e,r){return I(this,t,e,!0,r)},s.prototype.writeFloatBE=function(t,e,r){return I(this,t,e,!1,r)},s.prototype.writeDoubleLE=function(t,e,r){return D(this,t,e,!0,r)},s.prototype.writeDoubleBE=function(t,e,r){return D(this,t,e,!1,r)},s.prototype.copy=function(t,e,r,n){if(!s.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n<r&&(n=r),n===r)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e<n-r&&(n=t.length-e+r);var i=n-r;if(this===t&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(e,r,n);else if(this===t&&r<e&&e<n)for(var a=i-1;a>=0;--a)t[a+e]=this[a+r];else Uint8Array.prototype.set.call(t,this.subarray(r,n),e);return i},s.prototype.fill=function(t,e,r,n){if("string"==typeof t){if("string"==typeof e?(n=e,e=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!s.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===t.length){var i=t.charCodeAt(0);("utf8"===n&&i<128||"latin1"===n)&&(t=i)}}else"number"==typeof t&&(t&=255);if(e<0||this.length<e||this.length<r)throw new RangeError("Out of range index");if(r<=e)return this;var a;if(e>>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(a=e;a<r;++a)this[a]=t;else{var o=s.isBuffer(t)?t:s.from(t,n),l=o.length;if(0===l)throw new TypeError('The value "'+t+'" is invalid for argument "value"');for(a=0;a<r-e;++a)this[a+e]=o[a%l]}return this};var P=/[^+\/0-9A-Za-z-_]/g;function R(t){return t<16?"0"+t.toString(16):t.toString(16)}function F(t,e){var r;e=e||1/0;for(var n=t.length,i=null,a=[],o=0;o<n;++o){if((r=t.charCodeAt(o))>55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&a.push(239,191,189);continue}if(o+1===n){(e-=3)>-1&&a.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&a.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&a.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;a.push(r)}else if(r<2048){if((e-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function B(t){return n.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(P,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function N(t,e,r,n){for(var i=0;i<n&&!(i+r>=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function j(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function V(t){return t!=t}},{"base64-js":62,ieee754:401}],94:[function(t,e,r){"use strict";var n=t("./lib/monotone"),i=t("./lib/triangulation"),a=t("./lib/delaunay"),o=t("./lib/filter");function s(t){return[Math.min(t[0],t[1]),Math.max(t[0],t[1])]}function l(t,e){return t[0]-e[0]||t[1]-e[1]}function c(t,e,r){return e in t?t[e]:r}e.exports=function(t,e,r){Array.isArray(e)?(r=r||{},e=e||[]):(r=e||{},e=[]);var u=!!c(r,"delaunay",!0),h=!!c(r,"interior",!0),f=!!c(r,"exterior",!0),p=!!c(r,"infinity",!1);if(!h&&!f||0===t.length)return[];var d=n(t,e);if(u||h!==f||p){for(var g=i(t.length,function(t){return t.map(s).sort(l)}(e)),v=0;v<d.length;++v){var m=d[v];g.addTriangle(m[0],m[1],m[2])}return u&&a(t,g),f?h?p?o(g,0,p):g.cells():o(g,1,p):o(g,-1)}return d}},{"./lib/delaunay":95,"./lib/filter":96,"./lib/monotone":97,"./lib/triangulation":98}],95:[function(t,e,r){"use strict";var n=t("robust-in-sphere")[4];t("binary-search-bounds");function i(t,e,r,i,a,o){var s=e.opposite(i,a);if(!(s<0)){if(a<i){var l=i;i=a,a=l,l=o,o=s,s=l}e.isConstraint(i,a)||n(t[i],t[a],t[o],t[s])<0&&r.push(i,a)}}e.exports=function(t,e){for(var r=[],a=t.length,o=e.stars,s=0;s<a;++s)for(var l=o[s],c=1;c<l.length;c+=2){var u=l[c];if(!(u<s)&&!e.isConstraint(s,u)){for(var h=l[c-1],f=-1,p=1;p<l.length;p+=2)if(l[p-1]===u){f=l[p];break}f<0||n(t[s],t[u],t[h],t[f])<0&&r.push(s,u)}}for(;r.length>0;){for(var u=r.pop(),s=r.pop(),h=-1,f=-1,l=o[s],d=1;d<l.length;d+=2){var g=l[d-1],v=l[d];g===u?f=v:v===u&&(h=g)}h<0||f<0||(n(t[s],t[u],t[h],t[f])>=0||(e.flip(s,u),i(t,e,r,h,s,f),i(t,e,r,s,f,h),i(t,e,r,f,u,h),i(t,e,r,u,h,f)))}}},{"binary-search-bounds":99,"robust-in-sphere":489}],96:[function(t,e,r){"use strict";var n,i=t("binary-search-bounds");function a(t,e,r,n,i,a,o){this.cells=t,this.neighbor=e,this.flags=n,this.constraint=r,this.active=i,this.next=a,this.boundary=o}function o(t,e){return t[0]-e[0]||t[1]-e[1]||t[2]-e[2]}e.exports=function(t,e,r){var n=function(t,e){for(var r=t.cells(),n=r.length,i=0;i<n;++i){var s=r[i],l=s[0],c=s[1],u=s[2];c<u?c<l&&(s[0]=c,s[1]=u,s[2]=l):u<l&&(s[0]=u,s[1]=l,s[2]=c)}r.sort(o);for(var h=new Array(n),i=0;i<h.length;++i)h[i]=0;var f=[],p=[],d=new Array(3*n),g=new Array(3*n),v=null;e&&(v=[]);for(var m=new a(r,d,g,h,f,p,v),i=0;i<n;++i)for(var s=r[i],y=0;y<3;++y){var l=s[y],c=s[(y+1)%3],x=d[3*i+y]=m.locate(c,l,t.opposite(c,l)),b=g[3*i+y]=t.isConstraint(l,c);x<0&&(b?p.push(i):(f.push(i),h[i]=1),e&&v.push([c,l,-1]))}return m}(t,r);if(0===e)return r?n.cells.concat(n.boundary):n.cells;var i=1,s=n.active,l=n.next,c=n.flags,u=n.cells,h=n.constraint,f=n.neighbor;for(;s.length>0||l.length>0;){for(;s.length>0;){var p=s.pop();if(c[p]!==-i){c[p]=i;u[p];for(var d=0;d<3;++d){var g=f[3*p+d];g>=0&&0===c[g]&&(h[3*p+d]?l.push(g):(s.push(g),c[g]=i))}}}var v=l;l=s,s=v,l.length=0,i=-i}var m=function(t,e,r){for(var n=0,i=0;i<t.length;++i)e[i]===r&&(t[n++]=t[i]);return t.length=n,t}(u,c,e);if(r)return m.concat(n.boundary);return m},a.prototype.locate=(n=[0,0,0],function(t,e,r){var a=t,s=e,l=r;return e<r?e<t&&(a=e,s=r,l=t):r<t&&(a=r,s=t,l=e),a<0?-1:(n[0]=a,n[1]=s,n[2]=l,i.eq(this.cells,n,o))})},{"binary-search-bounds":99}],97:[function(t,e,r){"use strict";var n=t("binary-search-bounds"),i=t("robust-orientation")[3],a=0,o=1,s=2;function l(t,e,r,n,i){this.a=t,this.b=e,this.idx=r,this.lowerIds=n,this.upperIds=i}function c(t,e,r,n){this.a=t,this.b=e,this.type=r,this.idx=n}function u(t,e){var r=t.a[0]-e.a[0]||t.a[1]-e.a[1]||t.type-e.type;return r||(t.type!==a&&(r=i(t.a,t.b,e.b))?r:t.idx-e.idx)}function h(t,e){return i(t.a,t.b,e)}function f(t,e,r,a,o){for(var s=n.lt(e,a,h),l=n.gt(e,a,h),c=s;c<l;++c){for(var u=e[c],f=u.lowerIds,p=f.length;p>1&&i(r[f[p-2]],r[f[p-1]],a)>0;)t.push([f[p-1],f[p-2],o]),p-=1;f.length=p,f.push(o);var d=u.upperIds;for(p=d.length;p>1&&i(r[d[p-2]],r[d[p-1]],a)<0;)t.push([d[p-2],d[p-1],o]),p-=1;d.length=p,d.push(o)}}function p(t,e){var r;return(r=t.a[0]<e.a[0]?i(t.a,t.b,e.a):i(e.b,e.a,t.a))?r:(r=e.b[0]<t.b[0]?i(t.a,t.b,e.b):i(e.b,e.a,t.b))||t.idx-e.idx}function d(t,e,r){var i=n.le(t,r,p),a=t[i],o=a.upperIds,s=o[o.length-1];a.upperIds=[s],t.splice(i+1,0,new l(r.a,r.b,r.idx,[s],o))}function g(t,e,r){var i=r.a;r.a=r.b,r.b=i;var a=n.eq(t,r,p),o=t[a];t[a-1].upperIds=o.upperIds,t.splice(a,1)}e.exports=function(t,e){for(var r=t.length,n=e.length,i=[],h=0;h<r;++h)i.push(new c(t[h],null,a,h));for(var h=0;h<n;++h){var p=e[h],v=t[p[0]],m=t[p[1]];v[0]<m[0]?i.push(new c(v,m,s,h),new c(m,v,o,h)):v[0]>m[0]&&i.push(new c(m,v,s,h),new c(v,m,o,h))}i.sort(u);for(var y=i[0].a[0]-(1+Math.abs(i[0].a[0]))*Math.pow(2,-52),x=[new l([y,1],[y,0],-1,[],[],[],[])],b=[],h=0,_=i.length;h<_;++h){var w=i[h],k=w.type;k===a?f(b,x,t,w.a,w.idx):k===s?d(x,t,w):g(x,t,w)}return b}},{"binary-search-bounds":99,"robust-orientation":491}],98:[function(t,e,r){"use strict";var n=t("binary-search-bounds");function i(t,e){this.stars=t,this.edges=e}e.exports=function(t,e){for(var r=new Array(t),n=0;n<t;++n)r[n]=[];return new i(r,e)};var a=i.prototype;function o(t,e,r){for(var n=1,i=t.length;n<i;n+=2)if(t[n-1]===e&&t[n]===r)return t[n-1]=t[i-2],t[n]=t[i-1],void(t.length=i-2)}a.isConstraint=function(){var t=[0,0];function e(t,e){return t[0]-e[0]||t[1]-e[1]}return function(r,i){return t[0]=Math.min(r,i),t[1]=Math.max(r,i),n.eq(this.edges,t,e)>=0}}(),a.removeTriangle=function(t,e,r){var n=this.stars;o(n[t],e,r),o(n[e],r,t),o(n[r],t,e)},a.addTriangle=function(t,e,r){var n=this.stars;n[t].push(e,r),n[e].push(r,t),n[r].push(t,e)},a.opposite=function(t,e){for(var r=this.stars[e],n=1,i=r.length;n<i;n+=2)if(r[n]===t)return r[n-1];return-1},a.flip=function(t,e){var r=this.opposite(t,e),n=this.opposite(e,t);this.removeTriangle(t,e,r),this.removeTriangle(e,t,n),this.addTriangle(t,n,r),this.addTriangle(e,r,n)},a.edges=function(){for(var t=this.stars,e=[],r=0,n=t.length;r<n;++r)for(var i=t[r],a=0,o=i.length;a<o;a+=2)e.push([i[a],i[a+1]]);return e},a.cells=function(){for(var t=this.stars,e=[],r=0,n=t.length;r<n;++r)for(var i=t[r],a=0,o=i.length;a<o;a+=2){var s=i[a],l=i[a+1];r<Math.min(s,l)&&e.push([r,s,l])}return e}},{"binary-search-bounds":99}],99:[function(t,e,r){"use strict";function n(t,e,r,n,i){var a=["function ",t,"(a,l,h,",n.join(","),"){",i?"":"var i=",r?"l-1":"h+1",";while(l<=h){var m=(l+h)>>>1,x=a[m]"];return i?e.indexOf("c")<0?a.push(";if(x===y){return m}else if(x<=y){"):a.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):a.push(";if(",e,"){i=m;"),r?a.push("l=m+1}else{h=m-1}"):a.push("h=m-1}else{l=m+1}"),a.push("}"),i?a.push("return -1};"):a.push("return i};"),a.join("")}function i(t,e,r,i){return new Function([n("A","x"+t+"y",e,["y"],i),n("P","c(x,y)"+t+"0",e,["y","c"],i),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""))()}e.exports={ge:i(">=",!1,"GE"),gt:i(">",!1,"GT"),lt:i("<",!0,"LT"),le:i("<=",!0,"LE"),eq:i("-",!0,"EQ",!0)}},{}],100:[function(t,e,r){"use strict";e.exports=function(t){for(var e=1,r=1;r<t.length;++r)for(var n=0;n<r;++n)if(t[r]<t[n])e=-e;else if(t[n]===t[r])return 0;return e}},{}],101:[function(t,e,r){"use strict";var n=t("dup"),i=t("robust-linear-solve");function a(t,e){for(var r=0,n=t.length,i=0;i<n;++i)r+=t[i]*e[i];return r}function o(t){var e=t.length;if(0===e)return[];t[0].length;var r=n([t.length+1,t.length+1],1),o=n([t.length+1],1);r[e][e]=0;for(var s=0;s<e;++s){for(var l=0;l<=s;++l)r[l][s]=r[s][l]=2*a(t[s],t[l]);o[s]=a(t[s],t[s])}var c=i(r,o),u=0,h=c[e+1];for(s=0;s<h.length;++s)u+=h[s];var f=new Array(e);for(s=0;s<e;++s){h=c[s];var p=0;for(l=0;l<h.length;++l)p+=h[l];f[s]=p/u}return f}function s(t){if(0===t.length)return[];for(var e=t[0].length,r=n([e]),i=o(t),a=0;a<t.length;++a)for(var s=0;s<e;++s)r[s]+=t[a][s]*i[a];return r}s.barycenetric=o,e.exports=s},{dup:158,"robust-linear-solve":490}],102:[function(t,e,r){e.exports=function(t){for(var e=n(t),r=0,i=0;i<t.length;++i)for(var a=t[i],o=0;o<e.length;++o)r+=Math.pow(a[o]-e[o],2);return Math.sqrt(r/t.length)};var n=t("circumcenter")},{circumcenter:101}],103:[function(t,e,r){e.exports=function(t,e,r){return e<r?t<e?e:t>r?r:t:t<r?r:t>e?e:t}},{}],104:[function(t,e,r){"use strict";e.exports=function(t,e,r){var n;if(r){n=e;for(var i=new Array(e.length),a=0;a<e.length;++a){var o=e[a];i[a]=[o[0],o[1],r[a]]}e=i}var s=function(t,e,r){var n=d(t,[],p(t));return m(e,n,r),!!n}(t,e,!!r);for(;y(t,e,!!r);)s=!0;if(r&&s){n.length=0,r.length=0;for(var a=0;a<e.length;++a){var o=e[a];n.push([o[0],o[1]]),r.push(o[2])}}return s};var n=t("union-find"),i=t("box-intersect"),a=t("robust-segment-intersect"),o=t("big-rat"),s=t("big-rat/cmp"),l=t("big-rat/to-float"),c=t("rat-vec"),u=t("nextafter"),h=t("./lib/rat-seg-intersect");function f(t){var e=l(t);return[u(e,-1/0),u(e,1/0)]}function p(t){for(var e=new Array(t.length),r=0;r<t.length;++r){var n=t[r];e[r]=[u(n[0],-1/0),u(n[1],-1/0),u(n[0],1/0),u(n[1],1/0)]}return e}function d(t,e,r){for(var a=e.length,o=new n(a),s=[],l=0;l<e.length;++l){var c=e[l],h=f(c[0]),p=f(c[1]);s.push([u(h[0],-1/0),u(p[0],-1/0),u(h[1],1/0),u(p[1],1/0)])}i(s,function(t,e){o.link(t,e)});var d=!0,g=new Array(a);for(l=0;l<a;++l){(m=o.find(l))!==l&&(d=!1,t[m]=[Math.min(t[l][0],t[m][0]),Math.min(t[l][1],t[m][1])])}if(d)return null;var v=0;for(l=0;l<a;++l){var m;(m=o.find(l))===l?(g[l]=v,t[v++]=t[l]):g[l]=-1}t.length=v;for(l=0;l<a;++l)g[l]<0&&(g[l]=g[o.find(l)]);return g}function g(t,e){return t[0]-e[0]||t[1]-e[1]}function v(t,e){var r=t[0]-e[0]||t[1]-e[1];return r||(t[2]<e[2]?-1:t[2]>e[2]?1:0)}function m(t,e,r){if(0!==t.length){if(e)for(var n=0;n<t.length;++n){var i=e[(o=t[n])[0]],a=e[o[1]];o[0]=Math.min(i,a),o[1]=Math.max(i,a)}else for(n=0;n<t.length;++n){var o;i=(o=t[n])[0],a=o[1];o[0]=Math.min(i,a),o[1]=Math.max(i,a)}r?t.sort(v):t.sort(g);var s=1;for(n=1;n<t.length;++n){var l=t[n-1],c=t[n];(c[0]!==l[0]||c[1]!==l[1]||r&&c[2]!==l[2])&&(t[s++]=c)}t.length=s}}function y(t,e,r){var n=function(t,e){for(var r=new Array(e.length),n=0;n<e.length;++n){var i=e[n],a=t[i[0]],o=t[i[1]];r[n]=[u(Math.min(a[0],o[0]),-1/0),u(Math.min(a[1],o[1]),-1/0),u(Math.max(a[0],o[0]),1/0),u(Math.max(a[1],o[1]),1/0)]}return r}(t,e),f=function(t,e,r){var n=[];return i(r,function(r,i){var o=e[r],s=e[i];if(o[0]!==s[0]&&o[0]!==s[1]&&o[1]!==s[0]&&o[1]!==s[1]){var l=t[o[0]],c=t[o[1]],u=t[s[0]],h=t[s[1]];a(l,c,u,h)&&n.push([r,i])}}),n}(t,e,n),g=p(t),v=function(t,e,r,n){var o=[];return i(r,n,function(r,n){var i=e[r];if(i[0]!==n&&i[1]!==n){var s=t[n],l=t[i[0]],c=t[i[1]];a(l,c,s,s)&&o.push([r,n])}}),o}(t,e,n,g),y=d(t,function(t,e,r,n,i){var a,u,f=t.map(function(t){return[o(t[0]),o(t[1])]});for(a=0;a<r.length;++a){var p=r[a];u=p[0];var d=p[1],g=e[u],v=e[d],m=h(c(t[g[0]]),c(t[g[1]]),c(t[v[0]]),c(t[v[1]]));if(m){var y=t.length;t.push([l(m[0]),l(m[1])]),f.push(m),n.push([u,y],[d,y])}}for(n.sort(function(t,e){if(t[0]!==e[0])return t[0]-e[0];var r=f[t[1]],n=f[e[1]];return s(r[0],n[0])||s(r[1],n[1])}),a=n.length-1;a>=0;--a){var x=e[u=(S=n[a])[0]],b=x[0],_=x[1],w=t[b],k=t[_];if((w[0]-k[0]||w[1]-k[1])<0){var A=b;b=_,_=A}x[0]=b;var M,T=x[1]=S[1];for(i&&(M=x[2]);a>0&&n[a-1][0]===u;){var S,E=(S=n[--a])[1];i?e.push([T,E,M]):e.push([T,E]),T=E}i?e.push([T,_,M]):e.push([T,_])}return f}(t,e,f,v,r));return m(e,y,r),!!y||(f.length>0||v.length>0)}},{"./lib/rat-seg-intersect":105,"big-rat":66,"big-rat/cmp":64,"big-rat/to-float":78,"box-intersect":84,nextafter:440,"rat-vec":475,"robust-segment-intersect":494,"union-find":527}],105:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){var a=s(e,t),h=s(n,r),f=u(a,h);if(0===o(f))return null;var p=s(t,r),d=u(h,p),g=i(d,f),v=c(a,g);return l(t,v)};var n=t("big-rat/mul"),i=t("big-rat/div"),a=t("big-rat/sub"),o=t("big-rat/sign"),s=t("rat-vec/sub"),l=t("rat-vec/add"),c=t("rat-vec/muls");function u(t,e){return a(n(t[0],e[1]),n(t[1],e[0]))}},{"big-rat/div":65,"big-rat/mul":75,"big-rat/sign":76,"big-rat/sub":77,"rat-vec/add":474,"rat-vec/muls":476,"rat-vec/sub":477}],106:[function(t,e,r){"use strict";var n=t("clamp");function i(t,e){null==e&&(e=!0);var r=t[0],i=t[1],a=t[2],o=t[3];return null==o&&(o=e?1:255),e&&(r*=255,i*=255,a*=255,o*=255),16777216*(r=255&n(r,0,255))+((i=255&n(i,0,255))<<16)+((a=255&n(a,0,255))<<8)+(o=255&n(o,0,255))}e.exports=i,e.exports.to=i,e.exports.from=function(t,e){var r=(t=+t)>>>24,n=(16711680&t)>>>16,i=(65280&t)>>>8,a=255&t;return!1===e?[r,n,i,a]:[r/255,n/255,i/255,a/255]}},{clamp:103}],107:[function(t,e,r){"use strict";e.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}},{}],108:[function(t,e,r){"use strict";var n=t("color-rgba"),i=t("clamp"),a=t("dtype");e.exports=function(t,e){"float"!==e&&e||(e="array"),"uint"===e&&(e="uint8"),"uint_clamped"===e&&(e="uint8_clamped");var r=new(a(e))(4),o="uint8"!==e&&"uint8_clamped"!==e;return t.length&&"string"!=typeof t||((t=n(t))[0]/=255,t[1]/=255,t[2]/=255),function(t){return t instanceof Uint8Array||t instanceof Uint8ClampedArray||!!(Array.isArray(t)&&(t[0]>1||0===t[0])&&(t[1]>1||0===t[1])&&(t[2]>1||0===t[2])&&(!t[3]||t[3]>1))}(t)?(r[0]=t[0],r[1]=t[1],r[2]=t[2],r[3]=null!=t[3]?t[3]:255,o&&(r[0]/=255,r[1]/=255,r[2]/=255,r[3]/=255),r):(o?(r[0]=t[0],r[1]=t[1],r[2]=t[2],r[3]=null!=t[3]?t[3]:1):(r[0]=i(Math.floor(255*t[0]),0,255),r[1]=i(Math.floor(255*t[1]),0,255),r[2]=i(Math.floor(255*t[2]),0,255),r[3]=null==t[3]?255:i(Math.floor(255*t[3]),0,255)),r)}},{clamp:103,"color-rgba":110,dtype:157}],109:[function(t,e,r){(function(r){"use strict";var n=t("color-name"),i=t("is-plain-obj"),a=t("defined");e.exports=function(t){var e,s,l=[],c=1;if("string"==typeof t)if(n[t])l=n[t].slice(),s="rgb";else if("transparent"===t)c=0,s="rgb",l=[0,0,0];else if(/^#[A-Fa-f0-9]+$/.test(t)){var u=t.slice(1),h=u.length,f=h<=4;c=1,f?(l=[parseInt(u[0]+u[0],16),parseInt(u[1]+u[1],16),parseInt(u[2]+u[2],16)],4===h&&(c=parseInt(u[3]+u[3],16)/255)):(l=[parseInt(u[0]+u[1],16),parseInt(u[2]+u[3],16),parseInt(u[4]+u[5],16)],8===h&&(c=parseInt(u[6]+u[7],16)/255)),l[0]||(l[0]=0),l[1]||(l[1]=0),l[2]||(l[2]=0),s="rgb"}else if(e=/^((?:rgb|hs[lvb]|hwb|cmyk?|xy[zy]|gray|lab|lchu?v?|[ly]uv|lms)a?)\s*\(([^\)]*)\)/.exec(t)){var p=e[1],u=p.replace(/a$/,"");s=u;var h="cmyk"===u?4:"gray"===u?1:3;l=e[2].trim().split(/\s*,\s*/).map(function(t,e){if(/%$/.test(t))return e===h?parseFloat(t)/100:"rgb"===u?255*parseFloat(t)/100:parseFloat(t);if("h"===u[e]){if(/deg$/.test(t))return parseFloat(t);if(void 0!==o[t])return o[t]}return parseFloat(t)}),p===u&&l.push(1),c=void 0===l[h]?1:l[h],l=l.slice(0,h)}else t.length>10&&/[0-9](?:\s|\/)/.test(t)&&(l=t.match(/([0-9]+)/g).map(function(t){return parseFloat(t)}),s=t.match(/([a-z])/gi).join("").toLowerCase());else if(isNaN(t))if(i(t)){var d=a(t.r,t.red,t.R,null);null!==d?(s="rgb",l=[d,a(t.g,t.green,t.G),a(t.b,t.blue,t.B)]):(s="hsl",l=[a(t.h,t.hue,t.H),a(t.s,t.saturation,t.S),a(t.l,t.lightness,t.L,t.b,t.brightness)]),c=a(t.a,t.alpha,t.opacity,1),null!=t.opacity&&(c/=100)}else(Array.isArray(t)||r.ArrayBuffer&&ArrayBuffer.isView&&ArrayBuffer.isView(t))&&(l=[t[0],t[1],t[2]],s="rgb",c=4===t.length?t[3]:1);else s="rgb",l=[t>>>16,(65280&t)>>>8,255&t];return{space:s,values:l,alpha:c}};var o={red:0,orange:60,yellow:120,green:180,blue:240,purple:300}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"color-name":107,defined:152,"is-plain-obj":411}],110:[function(t,e,r){"use strict";var n=t("color-parse"),i=t("color-space/hsl"),a=t("clamp");e.exports=function(t){var e,r=n(t);return r.space?((e=Array(3))[0]=a(r.values[0],0,255),e[1]=a(r.values[1],0,255),e[2]=a(r.values[2],0,255),"h"===r.space[0]&&(e=i.rgb(e)),e.push(a(r.alpha,0,1)),e):[]}},{clamp:103,"color-parse":109,"color-space/hsl":111}],111:[function(t,e,r){"use strict";var n=t("./rgb");e.exports={name:"hsl",min:[0,0,0],max:[360,100,100],channel:["hue","saturation","lightness"],alias:["HSL"],rgb:function(t){var e,r,n,i,a,o=t[0]/360,s=t[1]/100,l=t[2]/100;if(0===s)return[a=255*l,a,a];e=2*l-(r=l<.5?l*(1+s):l+s-l*s),i=[0,0,0];for(var c=0;c<3;c++)(n=o+1/3*-(c-1))<0?n++:n>1&&n--,a=6*n<1?e+6*(r-e)*n:2*n<1?r:3*n<2?e+(r-e)*(2/3-n)*6:e,i[c]=255*a;return i}},n.hsl=function(t){var e,r,n=t[0]/255,i=t[1]/255,a=t[2]/255,o=Math.min(n,i,a),s=Math.max(n,i,a),l=s-o;return s===o?e=0:n===s?e=(i-a)/l:i===s?e=2+(a-n)/l:a===s&&(e=4+(n-i)/l),(e=Math.min(60*e,360))<0&&(e+=360),r=(o+s)/2,[e,100*(s===o?0:r<=.5?l/(s+o):l/(2-s-o)),100*r]}},{"./rgb":112}],112:[function(t,e,r){"use strict";e.exports={name:"rgb",min:[0,0,0],max:[255,255,255],channel:["red","green","blue"],alias:["RGB"]}},{}],113:[function(t,e,r){e.exports={jet:[{index:0,rgb:[0,0,131]},{index:.125,rgb:[0,60,170]},{index:.375,rgb:[5,255,255]},{index:.625,rgb:[255,255,0]},{index:.875,rgb:[250,0,0]},{index:1,rgb:[128,0,0]}],hsv:[{index:0,rgb:[255,0,0]},{index:.169,rgb:[253,255,2]},{index:.173,rgb:[247,255,2]},{index:.337,rgb:[0,252,4]},{index:.341,rgb:[0,252,10]},{index:.506,rgb:[1,249,255]},{index:.671,rgb:[2,0,253]},{index:.675,rgb:[8,0,253]},{index:.839,rgb:[255,0,251]},{index:.843,rgb:[255,0,245]},{index:1,rgb:[255,0,6]}],hot:[{index:0,rgb:[0,0,0]},{index:.3,rgb:[230,0,0]},{index:.6,rgb:[255,210,0]},{index:1,rgb:[255,255,255]}],cool:[{index:0,rgb:[0,255,255]},{index:1,rgb:[255,0,255]}],spring:[{index:0,rgb:[255,0,255]},{index:1,rgb:[255,255,0]}],summer:[{index:0,rgb:[0,128,102]},{index:1,rgb:[255,255,102]}],autumn:[{index:0,rgb:[255,0,0]},{index:1,rgb:[255,255,0]}],winter:[{index:0,rgb:[0,0,255]},{index:1,rgb:[0,255,128]}],bone:[{index:0,rgb:[0,0,0]},{index:.376,rgb:[84,84,116]},{index:.753,rgb:[169,200,200]},{index:1,rgb:[255,255,255]}],copper:[{index:0,rgb:[0,0,0]},{index:.804,rgb:[255,160,102]},{index:1,rgb:[255,199,127]}],greys:[{index:0,rgb:[0,0,0]},{index:1,rgb:[255,255,255]}],yignbu:[{index:0,rgb:[8,29,88]},{index:.125,rgb:[37,52,148]},{index:.25,rgb:[34,94,168]},{index:.375,rgb:[29,145,192]},{index:.5,rgb:[65,182,196]},{index:.625,rgb:[127,205,187]},{index:.75,rgb:[199,233,180]},{index:.875,rgb:[237,248,217]},{index:1,rgb:[255,255,217]}],greens:[{index:0,rgb:[0,68,27]},{index:.125,rgb:[0,109,44]},{index:.25,rgb:[35,139,69]},{index:.375,rgb:[65,171,93]},{index:.5,rgb:[116,196,118]},{index:.625,rgb:[161,217,155]},{index:.75,rgb:[199,233,192]},{index:.875,rgb:[229,245,224]},{index:1,rgb:[247,252,245]}],yiorrd:[{index:0,rgb:[128,0,38]},{index:.125,rgb:[189,0,38]},{index:.25,rgb:[227,26,28]},{index:.375,rgb:[252,78,42]},{index:.5,rgb:[253,141,60]},{index:.625,rgb:[254,178,76]},{index:.75,rgb:[254,217,118]},{index:.875,rgb:[255,237,160]},{index:1,rgb:[255,255,204]}],bluered:[{index:0,rgb:[0,0,255]},{index:1,rgb:[255,0,0]}],rdbu:[{index:0,rgb:[5,10,172]},{index:.35,rgb:[106,137,247]},{index:.5,rgb:[190,190,190]},{index:.6,rgb:[220,170,132]},{index:.7,rgb:[230,145,90]},{index:1,rgb:[178,10,28]}],picnic:[{index:0,rgb:[0,0,255]},{index:.1,rgb:[51,153,255]},{index:.2,rgb:[102,204,255]},{index:.3,rgb:[153,204,255]},{index:.4,rgb:[204,204,255]},{index:.5,rgb:[255,255,255]},{index:.6,rgb:[255,204,255]},{index:.7,rgb:[255,153,255]},{index:.8,rgb:[255,102,204]},{index:.9,rgb:[255,102,102]},{index:1,rgb:[255,0,0]}],rainbow:[{index:0,rgb:[150,0,90]},{index:.125,rgb:[0,0,200]},{index:.25,rgb:[0,25,255]},{index:.375,rgb:[0,152,255]},{index:.5,rgb:[44,255,150]},{index:.625,rgb:[151,255,0]},{index:.75,rgb:[255,234,0]},{index:.875,rgb:[255,111,0]},{index:1,rgb:[255,0,0]}],portland:[{index:0,rgb:[12,51,131]},{index:.25,rgb:[10,136,186]},{index:.5,rgb:[242,211,56]},{index:.75,rgb:[242,143,56]},{index:1,rgb:[217,30,30]}],blackbody:[{index:0,rgb:[0,0,0]},{index:.2,rgb:[230,0,0]},{index:.4,rgb:[230,210,0]},{index:.7,rgb:[255,255,255]},{index:1,rgb:[160,200,255]}],earth:[{index:0,rgb:[0,0,130]},{index:.1,rgb:[0,180,180]},{index:.2,rgb:[40,210,40]},{index:.4,rgb:[230,230,50]},{index:.6,rgb:[120,70,20]},{index:1,rgb:[255,255,255]}],electric:[{index:0,rgb:[0,0,0]},{index:.15,rgb:[30,0,100]},{index:.4,rgb:[120,0,100]},{index:.6,rgb:[160,90,0]},{index:.8,rgb:[230,200,0]},{index:1,rgb:[255,250,220]}],alpha:[{index:0,rgb:[255,255,255,0]},{index:1,rgb:[255,255,255,1]}],viridis:[{index:0,rgb:[68,1,84]},{index:.13,rgb:[71,44,122]},{index:.25,rgb:[59,81,139]},{index:.38,rgb:[44,113,142]},{index:.5,rgb:[33,144,141]},{index:.63,rgb:[39,173,129]},{index:.75,rgb:[92,200,99]},{index:.88,rgb:[170,220,50]},{index:1,rgb:[253,231,37]}],inferno:[{index:0,rgb:[0,0,4]},{index:.13,rgb:[31,12,72]},{index:.25,rgb:[85,15,109]},{index:.38,rgb:[136,34,106]},{index:.5,rgb:[186,54,85]},{index:.63,rgb:[227,89,51]},{index:.75,rgb:[249,140,10]},{index:.88,rgb:[249,201,50]},{index:1,rgb:[252,255,164]}],magma:[{index:0,rgb:[0,0,4]},{index:.13,rgb:[28,16,68]},{index:.25,rgb:[79,18,123]},{index:.38,rgb:[129,37,129]},{index:.5,rgb:[181,54,122]},{index:.63,rgb:[229,80,100]},{index:.75,rgb:[251,135,97]},{index:.88,rgb:[254,194,135]},{index:1,rgb:[252,253,191]}],plasma:[{index:0,rgb:[13,8,135]},{index:.13,rgb:[75,3,161]},{index:.25,rgb:[125,3,168]},{index:.38,rgb:[168,34,150]},{index:.5,rgb:[203,70,121]},{index:.63,rgb:[229,107,93]},{index:.75,rgb:[248,148,65]},{index:.88,rgb:[253,195,40]},{index:1,rgb:[240,249,33]}],warm:[{index:0,rgb:[125,0,179]},{index:.13,rgb:[172,0,187]},{index:.25,rgb:[219,0,170]},{index:.38,rgb:[255,0,130]},{index:.5,rgb:[255,63,74]},{index:.63,rgb:[255,123,0]},{index:.75,rgb:[234,176,0]},{index:.88,rgb:[190,228,0]},{index:1,rgb:[147,255,0]}],cool:[{index:0,rgb:[125,0,179]},{index:.13,rgb:[116,0,218]},{index:.25,rgb:[98,74,237]},{index:.38,rgb:[68,146,231]},{index:.5,rgb:[0,204,197]},{index:.63,rgb:[0,247,146]},{index:.75,rgb:[0,255,88]},{index:.88,rgb:[40,255,8]},{index:1,rgb:[147,255,0]}],"rainbow-soft":[{index:0,rgb:[125,0,179]},{index:.1,rgb:[199,0,180]},{index:.2,rgb:[255,0,121]},{index:.3,rgb:[255,108,0]},{index:.4,rgb:[222,194,0]},{index:.5,rgb:[150,255,0]},{index:.6,rgb:[0,255,55]},{index:.7,rgb:[0,246,150]},{index:.8,rgb:[50,167,222]},{index:.9,rgb:[103,51,235]},{index:1,rgb:[124,0,186]}],bathymetry:[{index:0,rgb:[40,26,44]},{index:.13,rgb:[59,49,90]},{index:.25,rgb:[64,76,139]},{index:.38,rgb:[63,110,151]},{index:.5,rgb:[72,142,158]},{index:.63,rgb:[85,174,163]},{index:.75,rgb:[120,206,163]},{index:.88,rgb:[187,230,172]},{index:1,rgb:[253,254,204]}],cdom:[{index:0,rgb:[47,15,62]},{index:.13,rgb:[87,23,86]},{index:.25,rgb:[130,28,99]},{index:.38,rgb:[171,41,96]},{index:.5,rgb:[206,67,86]},{index:.63,rgb:[230,106,84]},{index:.75,rgb:[242,149,103]},{index:.88,rgb:[249,193,135]},{index:1,rgb:[254,237,176]}],chlorophyll:[{index:0,rgb:[18,36,20]},{index:.13,rgb:[25,63,41]},{index:.25,rgb:[24,91,59]},{index:.38,rgb:[13,119,72]},{index:.5,rgb:[18,148,80]},{index:.63,rgb:[80,173,89]},{index:.75,rgb:[132,196,122]},{index:.88,rgb:[175,221,162]},{index:1,rgb:[215,249,208]}],density:[{index:0,rgb:[54,14,36]},{index:.13,rgb:[89,23,80]},{index:.25,rgb:[110,45,132]},{index:.38,rgb:[120,77,178]},{index:.5,rgb:[120,113,213]},{index:.63,rgb:[115,151,228]},{index:.75,rgb:[134,185,227]},{index:.88,rgb:[177,214,227]},{index:1,rgb:[230,241,241]}],"freesurface-blue":[{index:0,rgb:[30,4,110]},{index:.13,rgb:[47,14,176]},{index:.25,rgb:[41,45,236]},{index:.38,rgb:[25,99,212]},{index:.5,rgb:[68,131,200]},{index:.63,rgb:[114,156,197]},{index:.75,rgb:[157,181,203]},{index:.88,rgb:[200,208,216]},{index:1,rgb:[241,237,236]}],"freesurface-red":[{index:0,rgb:[60,9,18]},{index:.13,rgb:[100,17,27]},{index:.25,rgb:[142,20,29]},{index:.38,rgb:[177,43,27]},{index:.5,rgb:[192,87,63]},{index:.63,rgb:[205,125,105]},{index:.75,rgb:[216,162,148]},{index:.88,rgb:[227,199,193]},{index:1,rgb:[241,237,236]}],oxygen:[{index:0,rgb:[64,5,5]},{index:.13,rgb:[106,6,15]},{index:.25,rgb:[144,26,7]},{index:.38,rgb:[168,64,3]},{index:.5,rgb:[188,100,4]},{index:.63,rgb:[206,136,11]},{index:.75,rgb:[220,174,25]},{index:.88,rgb:[231,215,44]},{index:1,rgb:[248,254,105]}],par:[{index:0,rgb:[51,20,24]},{index:.13,rgb:[90,32,35]},{index:.25,rgb:[129,44,34]},{index:.38,rgb:[159,68,25]},{index:.5,rgb:[182,99,19]},{index:.63,rgb:[199,134,22]},{index:.75,rgb:[212,171,35]},{index:.88,rgb:[221,210,54]},{index:1,rgb:[225,253,75]}],phase:[{index:0,rgb:[145,105,18]},{index:.13,rgb:[184,71,38]},{index:.25,rgb:[186,58,115]},{index:.38,rgb:[160,71,185]},{index:.5,rgb:[110,97,218]},{index:.63,rgb:[50,123,164]},{index:.75,rgb:[31,131,110]},{index:.88,rgb:[77,129,34]},{index:1,rgb:[145,105,18]}],salinity:[{index:0,rgb:[42,24,108]},{index:.13,rgb:[33,50,162]},{index:.25,rgb:[15,90,145]},{index:.38,rgb:[40,118,137]},{index:.5,rgb:[59,146,135]},{index:.63,rgb:[79,175,126]},{index:.75,rgb:[120,203,104]},{index:.88,rgb:[193,221,100]},{index:1,rgb:[253,239,154]}],temperature:[{index:0,rgb:[4,35,51]},{index:.13,rgb:[23,51,122]},{index:.25,rgb:[85,59,157]},{index:.38,rgb:[129,79,143]},{index:.5,rgb:[175,95,130]},{index:.63,rgb:[222,112,101]},{index:.75,rgb:[249,146,66]},{index:.88,rgb:[249,196,65]},{index:1,rgb:[232,250,91]}],turbidity:[{index:0,rgb:[34,31,27]},{index:.13,rgb:[65,50,41]},{index:.25,rgb:[98,69,52]},{index:.38,rgb:[131,89,57]},{index:.5,rgb:[161,112,59]},{index:.63,rgb:[185,140,66]},{index:.75,rgb:[202,174,88]},{index:.88,rgb:[216,209,126]},{index:1,rgb:[233,246,171]}],"velocity-blue":[{index:0,rgb:[17,32,64]},{index:.13,rgb:[35,52,116]},{index:.25,rgb:[29,81,156]},{index:.38,rgb:[31,113,162]},{index:.5,rgb:[50,144,169]},{index:.63,rgb:[87,173,176]},{index:.75,rgb:[149,196,189]},{index:.88,rgb:[203,221,211]},{index:1,rgb:[254,251,230]}],"velocity-green":[{index:0,rgb:[23,35,19]},{index:.13,rgb:[24,64,38]},{index:.25,rgb:[11,95,45]},{index:.38,rgb:[39,123,35]},{index:.5,rgb:[95,146,12]},{index:.63,rgb:[152,165,18]},{index:.75,rgb:[201,186,69]},{index:.88,rgb:[233,216,137]},{index:1,rgb:[255,253,205]}],cubehelix:[{index:0,rgb:[0,0,0]},{index:.07,rgb:[22,5,59]},{index:.13,rgb:[60,4,105]},{index:.2,rgb:[109,1,135]},{index:.27,rgb:[161,0,147]},{index:.33,rgb:[210,2,142]},{index:.4,rgb:[251,11,123]},{index:.47,rgb:[255,29,97]},{index:.53,rgb:[255,54,69]},{index:.6,rgb:[255,85,46]},{index:.67,rgb:[255,120,34]},{index:.73,rgb:[255,157,37]},{index:.8,rgb:[241,191,57]},{index:.87,rgb:[224,220,93]},{index:.93,rgb:[218,241,142]},{index:1,rgb:[227,253,198]}]}},{}],114:[function(t,e,r){"use strict";var n=t("./colorScale"),i=t("lerp");function a(t){return[t[0]/255,t[1]/255,t[2]/255,t[3]]}function o(t){for(var e,r="#",n=0;n<3;++n)r+=("00"+(e=(e=t[n]).toString(16))).substr(e.length);return r}function s(t){return"rgba("+t.join(",")+")"}e.exports=function(t){var e,r,l,c,u,h,f,p,d,g;t||(t={});p=(t.nshades||72)-1,f=t.format||"hex",(h=t.colormap)||(h="jet");if("string"==typeof h){if(h=h.toLowerCase(),!n[h])throw Error(h+" not a supported colorscale");u=n[h]}else{if(!Array.isArray(h))throw Error("unsupported colormap option",h);u=h.slice()}if(u.length>p)throw new Error(h+" map requires nshades to be at least size "+u.length);d=Array.isArray(t.alpha)?2!==t.alpha.length?[1,1]:t.alpha.slice():"number"==typeof t.alpha?[t.alpha,t.alpha]:[1,1];e=u.map(function(t){return Math.round(t.index*p)}),d[0]=Math.min(Math.max(d[0],0),1),d[1]=Math.min(Math.max(d[1],0),1);var v=u.map(function(t,e){var r=u[e].index,n=u[e].rgb.slice();return 4===n.length&&n[3]>=0&&n[3]<=1?n:(n[3]=d[0]+(d[1]-d[0])*r,n)}),m=[];for(g=0;g<e.length-1;++g){c=e[g+1]-e[g],r=v[g],l=v[g+1];for(var y=0;y<c;y++){var x=y/c;m.push([Math.round(i(r[0],l[0],x)),Math.round(i(r[1],l[1],x)),Math.round(i(r[2],l[2],x)),i(r[3],l[3],x)])}}m.push(u[u.length-1].rgb.concat(d[1])),"hex"===f?m=m.map(o):"rgbaString"===f?m=m.map(s):"float"===f&&(m=m.map(a));return m}},{"./colorScale":113,lerp:414}],115:[function(t,e,r){"use strict";e.exports=function(t,e,r,a){var o=n(e,r,a);if(0===o){var s=i(n(t,e,r)),c=i(n(t,e,a));if(s===c){if(0===s){var u=l(t,e,r),h=l(t,e,a);return u===h?0:u?1:-1}return 0}return 0===c?s>0?-1:l(t,e,a)?-1:1:0===s?c>0?1:l(t,e,r)?1:-1:i(c-s)}var f=n(t,e,r);if(f>0)return o>0&&n(t,e,a)>0?1:-1;if(f<0)return o>0||n(t,e,a)>0?1:-1;var p=n(t,e,a);return p>0?1:l(t,e,r)?1:-1};var n=t("robust-orientation"),i=t("signum"),a=t("two-sum"),o=t("robust-product"),s=t("robust-sum");function l(t,e,r){var n=a(t[0],-e[0]),i=a(t[1],-e[1]),l=a(r[0],-e[0]),c=a(r[1],-e[1]),u=s(o(n,l),o(i,c));return u[u.length-1]>=0}},{"robust-orientation":491,"robust-product":492,"robust-sum":496,signum:497,"two-sum":525}],116:[function(t,e,r){e.exports=function(t,e){var r=t.length,a=t.length-e.length;if(a)return a;switch(r){case 0:return 0;case 1:return t[0]-e[0];case 2:return t[0]+t[1]-e[0]-e[1]||n(t[0],t[1])-n(e[0],e[1]);case 3:var o=t[0]+t[1],s=e[0]+e[1];if(a=o+t[2]-(s+e[2]))return a;var l=n(t[0],t[1]),c=n(e[0],e[1]);return n(l,t[2])-n(c,e[2])||n(l+t[2],o)-n(c+e[2],s);case 4:var u=t[0],h=t[1],f=t[2],p=t[3],d=e[0],g=e[1],v=e[2],m=e[3];return u+h+f+p-(d+g+v+m)||n(u,h,f,p)-n(d,g,v,m,d)||n(u+h,u+f,u+p,h+f,h+p,f+p)-n(d+g,d+v,d+m,g+v,g+m,v+m)||n(u+h+f,u+h+p,u+f+p,h+f+p)-n(d+g+v,d+g+m,d+v+m,g+v+m);default:for(var y=t.slice().sort(i),x=e.slice().sort(i),b=0;b<r;++b)if(a=y[b]-x[b])return a;return 0}};var n=Math.min;function i(t,e){return t-e}},{}],117:[function(t,e,r){"use strict";var n=t("compare-cell"),i=t("cell-orientation");e.exports=function(t,e){return n(t,e)||i(t)-i(e)}},{"cell-orientation":100,"compare-cell":116}],118:[function(t,e,r){"use strict";var n=t("./lib/ch1d"),i=t("./lib/ch2d"),a=t("./lib/chnd");e.exports=function(t){var e=t.length;if(0===e)return[];if(1===e)return[[0]];var r=t[0].length;if(0===r)return[];if(1===r)return n(t);if(2===r)return i(t);return a(t,r)}},{"./lib/ch1d":119,"./lib/ch2d":120,"./lib/chnd":121}],119:[function(t,e,r){"use strict";e.exports=function(t){for(var e=0,r=0,n=1;n<t.length;++n)t[n][0]<t[e][0]&&(e=n),t[n][0]>t[r][0]&&(r=n);return e<r?[[e],[r]]:e>r?[[r],[e]]:[[e]]}},{}],120:[function(t,e,r){"use strict";e.exports=function(t){var e=n(t),r=e.length;if(r<=2)return[];for(var i=new Array(r),a=e[r-1],o=0;o<r;++o){var s=e[o];i[o]=[a,s],a=s}return i};var n=t("monotone-convex-hull-2d")},{"monotone-convex-hull-2d":423}],121:[function(t,e,r){"use strict";e.exports=function(t,e){try{return n(t,!0)}catch(s){var r=i(t);if(r.length<=e)return[];var a=function(t,e){for(var r=t.length,n=new Array(r),i=0;i<e.length;++i)n[i]=t[e[i]];for(var a=e.length,i=0;i<r;++i)e.indexOf(i)<0&&(n[a++]=t[i]);return n}(t,r),o=n(a,!0);return function(t,e){for(var r=t.length,n=e.length,i=0;i<r;++i)for(var a=t[i],o=0;o<a.length;++o){var s=a[o];if(s<n)a[o]=e[s];else{s-=n;for(var l=0;l<n;++l)s>=e[l]&&(s+=1);a[o]=s}}return t}(o,r)}};var n=t("incremental-convex-hull"),i=t("affine-hull")},{"affine-hull":50,"incremental-convex-hull":402}],122:[function(t,e,r){e.exports={AFG:"afghan",ALA:"\\b\\wland",ALB:"albania",DZA:"algeria",ASM:"^(?=.*americ).*samoa",AND:"andorra",AGO:"angola",AIA:"anguill?a",ATA:"antarctica",ATG:"antigua",ARG:"argentin",ARM:"armenia",ABW:"^(?!.*bonaire).*\\baruba",AUS:"australia",AUT:"^(?!.*hungary).*austria|\\baustri.*\\bemp",AZE:"azerbaijan",BHS:"bahamas",BHR:"bahrain",BGD:"bangladesh|^(?=.*east).*paki?stan",BRB:"barbados",BLR:"belarus|byelo",BEL:"^(?!.*luxem).*belgium",BLZ:"belize|^(?=.*british).*honduras",BEN:"benin|dahome",BMU:"bermuda",BTN:"bhutan",BOL:"bolivia",BES:"^(?=.*bonaire).*eustatius|^(?=.*carib).*netherlands|\\bbes.?islands",BIH:"herzegovina|bosnia",BWA:"botswana|bechuana",BVT:"bouvet",BRA:"brazil",IOT:"british.?indian.?ocean",BRN:"brunei",BGR:"bulgaria",BFA:"burkina|\\bfaso|upper.?volta",BDI:"burundi",CPV:"verde",KHM:"cambodia|kampuchea|khmer",CMR:"cameroon",CAN:"canada",CYM:"cayman",CAF:"\\bcentral.african.republic",TCD:"\\bchad",CHL:"\\bchile",CHN:"^(?!.*\\bmac)(?!.*\\bhong)(?!.*\\btai)(?!.*\\brep).*china|^(?=.*peo)(?=.*rep).*china",CXR:"christmas",CCK:"\\bcocos|keeling",COL:"colombia",COM:"comoro",COG:"^(?!.*\\bdem)(?!.*\\bd[\\.]?r)(?!.*kinshasa)(?!.*zaire)(?!.*belg)(?!.*l.opoldville)(?!.*free).*\\bcongo",COK:"\\bcook",CRI:"costa.?rica",CIV:"ivoire|ivory",HRV:"croatia",CUB:"\\bcuba",CUW:"^(?!.*bonaire).*\\bcura(c|\xe7)ao",CYP:"cyprus",CSK:"czechoslovakia",CZE:"^(?=.*rep).*czech|czechia|bohemia",COD:"\\bdem.*congo|congo.*\\bdem|congo.*\\bd[\\.]?r|\\bd[\\.]?r.*congo|belgian.?congo|congo.?free.?state|kinshasa|zaire|l.opoldville|drc|droc|rdc",DNK:"denmark",DJI:"djibouti",DMA:"dominica(?!n)",DOM:"dominican.rep",ECU:"ecuador",EGY:"egypt",SLV:"el.?salvador",GNQ:"guine.*eq|eq.*guine|^(?=.*span).*guinea",ERI:"eritrea",EST:"estonia",ETH:"ethiopia|abyssinia",FLK:"falkland|malvinas",FRO:"faroe|faeroe",FJI:"fiji",FIN:"finland",FRA:"^(?!.*\\bdep)(?!.*martinique).*france|french.?republic|\\bgaul",GUF:"^(?=.*french).*guiana",PYF:"french.?polynesia|tahiti",ATF:"french.?southern",GAB:"gabon",GMB:"gambia",GEO:"^(?!.*south).*georgia",DDR:"german.?democratic.?republic|democratic.?republic.*germany|east.germany",DEU:"^(?!.*east).*germany|^(?=.*\\bfed.*\\brep).*german",GHA:"ghana|gold.?coast",GIB:"gibraltar",GRC:"greece|hellenic|hellas",GRL:"greenland",GRD:"grenada",GLP:"guadeloupe",GUM:"\\bguam",GTM:"guatemala",GGY:"guernsey",GIN:"^(?!.*eq)(?!.*span)(?!.*bissau)(?!.*portu)(?!.*new).*guinea",GNB:"bissau|^(?=.*portu).*guinea",GUY:"guyana|british.?guiana",HTI:"haiti",HMD:"heard.*mcdonald",VAT:"holy.?see|vatican|papal.?st",HND:"^(?!.*brit).*honduras",HKG:"hong.?kong",HUN:"^(?!.*austr).*hungary",ISL:"iceland",IND:"india(?!.*ocea)",IDN:"indonesia",IRN:"\\biran|persia",IRQ:"\\biraq|mesopotamia",IRL:"(^ireland)|(^republic.*ireland)",IMN:"^(?=.*isle).*\\bman",ISR:"israel",ITA:"italy",JAM:"jamaica",JPN:"japan",JEY:"jersey",JOR:"jordan",KAZ:"kazak",KEN:"kenya|british.?east.?africa|east.?africa.?prot",KIR:"kiribati",PRK:"^(?=.*democrat|people|north|d.*p.*.r).*\\bkorea|dprk|korea.*(d.*p.*r)",KWT:"kuwait",KGZ:"kyrgyz|kirghiz",LAO:"\\blaos?\\b",LVA:"latvia",LBN:"lebanon",LSO:"lesotho|basuto",LBR:"liberia",LBY:"libya",LIE:"liechtenstein",LTU:"lithuania",LUX:"^(?!.*belg).*luxem",MAC:"maca(o|u)",MDG:"madagascar|malagasy",MWI:"malawi|nyasa",MYS:"malaysia",MDV:"maldive",MLI:"\\bmali\\b",MLT:"\\bmalta",MHL:"marshall",MTQ:"martinique",MRT:"mauritania",MUS:"mauritius",MYT:"\\bmayotte",MEX:"\\bmexic",FSM:"fed.*micronesia|micronesia.*fed",MCO:"monaco",MNG:"mongolia",MNE:"^(?!.*serbia).*montenegro",MSR:"montserrat",MAR:"morocco|\\bmaroc",MOZ:"mozambique",MMR:"myanmar|burma",NAM:"namibia",NRU:"nauru",NPL:"nepal",NLD:"^(?!.*\\bant)(?!.*\\bcarib).*netherlands",ANT:"^(?=.*\\bant).*(nether|dutch)",NCL:"new.?caledonia",NZL:"new.?zealand",NIC:"nicaragua",NER:"\\bniger(?!ia)",NGA:"nigeria",NIU:"niue",NFK:"norfolk",MNP:"mariana",NOR:"norway",OMN:"\\boman|trucial",PAK:"^(?!.*east).*paki?stan",PLW:"palau",PSE:"palestin|\\bgaza|west.?bank",PAN:"panama",PNG:"papua|new.?guinea",PRY:"paraguay",PER:"peru",PHL:"philippines",PCN:"pitcairn",POL:"poland",PRT:"portugal",PRI:"puerto.?rico",QAT:"qatar",KOR:"^(?!.*d.*p.*r)(?!.*democrat)(?!.*people)(?!.*north).*\\bkorea(?!.*d.*p.*r)",MDA:"moldov|b(a|e)ssarabia",REU:"r(e|\xe9)union",ROU:"r(o|u|ou)mania",RUS:"\\brussia|soviet.?union|u\\.?s\\.?s\\.?r|socialist.?republics",RWA:"rwanda",BLM:"barth(e|\xe9)lemy",SHN:"helena",KNA:"kitts|\\bnevis",LCA:"\\blucia",MAF:"^(?=.*collectivity).*martin|^(?=.*france).*martin(?!ique)|^(?=.*french).*martin(?!ique)",SPM:"miquelon",VCT:"vincent",WSM:"^(?!.*amer).*samoa",SMR:"san.?marino",STP:"\\bs(a|\xe3)o.?tom(e|\xe9)",SAU:"\\bsa\\w*.?arabia",SEN:"senegal",SRB:"^(?!.*monte).*serbia",SYC:"seychell",SLE:"sierra",SGP:"singapore",SXM:"^(?!.*martin)(?!.*saba).*maarten",SVK:"^(?!.*cze).*slovak",SVN:"slovenia",SLB:"solomon",SOM:"somali",ZAF:"south.africa|s\\\\..?africa",SGS:"south.?georgia|sandwich",SSD:"\\bs\\w*.?sudan",ESP:"spain",LKA:"sri.?lanka|ceylon",SDN:"^(?!.*\\bs(?!u)).*sudan",SUR:"surinam|dutch.?guiana",SJM:"svalbard",SWZ:"swaziland",SWE:"sweden",CHE:"switz|swiss",SYR:"syria",TWN:"taiwan|taipei|formosa|^(?!.*peo)(?=.*rep).*china",TJK:"tajik",THA:"thailand|\\bsiam",MKD:"macedonia|fyrom",TLS:"^(?=.*leste).*timor|^(?=.*east).*timor",TGO:"togo",TKL:"tokelau",TON:"tonga",TTO:"trinidad|tobago",TUN:"tunisia",TUR:"turkey",TKM:"turkmen",TCA:"turks",TUV:"tuvalu",UGA:"uganda",UKR:"ukrain",ARE:"emirates|^u\\.?a\\.?e\\.?$|united.?arab.?em",GBR:"united.?kingdom|britain|^u\\.?k\\.?$",TZA:"tanzania",USA:"united.?states\\b(?!.*islands)|\\bu\\.?s\\.?a\\.?\\b|^\\s*u\\.?s\\.?\\b(?!.*islands)",UMI:"minor.?outlying.?is",URY:"uruguay",UZB:"uzbek",VUT:"vanuatu|new.?hebrides",VEN:"venezuela",VNM:"^(?!.*republic).*viet.?nam|^(?=.*socialist).*viet.?nam",VGB:"^(?=.*\\bu\\.?\\s?k).*virgin|^(?=.*brit).*virgin|^(?=.*kingdom).*virgin",VIR:"^(?=.*\\bu\\.?\\s?s).*virgin|^(?=.*states).*virgin",WLF:"futuna|wallis",ESH:"western.sahara",YEM:"^(?!.*arab)(?!.*north)(?!.*sana)(?!.*peo)(?!.*dem)(?!.*south)(?!.*aden)(?!.*\\bp\\.?d\\.?r).*yemen",YMD:"^(?=.*peo).*yemen|^(?!.*rep)(?=.*dem).*yemen|^(?=.*south).*yemen|^(?=.*aden).*yemen|^(?=.*\\bp\\.?d\\.?r).*yemen",YUG:"yugoslavia",ZMB:"zambia|northern.?rhodesia",EAZ:"zanzibar",ZWE:"zimbabwe|^(?!.*northern).*rhodesia"}},{}],123:[function(t,e,r){e.exports=["xx-small","x-small","small","medium","large","x-large","xx-large","larger","smaller"]},{}],124:[function(t,e,r){e.exports=["normal","condensed","semi-condensed","extra-condensed","ultra-condensed","expanded","semi-expanded","extra-expanded","ultra-expanded"]},{}],125:[function(t,e,r){e.exports=["normal","italic","oblique"]},{}],126:[function(t,e,r){e.exports=["normal","bold","bolder","lighter","100","200","300","400","500","600","700","800","900"]},{}],127:[function(t,e,r){"use strict";e.exports={parse:t("./parse"),stringify:t("./stringify")}},{"./parse":129,"./stringify":130}],128:[function(t,e,r){"use strict";var n=t("css-font-size-keywords");e.exports={isSize:function(t){return/^[\d\.]/.test(t)||-1!==t.indexOf("/")||-1!==n.indexOf(t)}}},{"css-font-size-keywords":123}],129:[function(t,e,r){"use strict";var n=t("unquote"),i=t("css-global-keywords"),a=t("css-system-font-keywords"),o=t("css-font-weight-keywords"),s=t("css-font-style-keywords"),l=t("css-font-stretch-keywords"),c=t("string-split-by"),u=t("./lib/util").isSize;e.exports=f;var h=f.cache={};function f(t){if("string"!=typeof t)throw new Error("Font argument must be a string.");if(h[t])return h[t];if(""===t)throw new Error("Cannot parse an empty string.");if(-1!==a.indexOf(t))return h[t]={system:t};for(var e,r={style:"normal",variant:"normal",weight:"normal",stretch:"normal",lineHeight:"normal",size:"1rem",family:["serif"]},f=c(t,/\s+/);e=f.shift();){if(-1!==i.indexOf(e))return["style","variant","weight","stretch"].forEach(function(t){r[t]=e}),h[t]=r;if(-1===s.indexOf(e))if("normal"!==e&&"small-caps"!==e)if(-1===l.indexOf(e)){if(-1===o.indexOf(e)){if(u(e)){var d=c(e,"/");if(r.size=d[0],null!=d[1]?r.lineHeight=p(d[1]):"/"===f[0]&&(f.shift(),r.lineHeight=p(f.shift())),!f.length)throw new Error("Missing required font-family.");return r.family=c(f.join(" "),/\s*,\s*/).map(n),h[t]=r}throw new Error("Unknown or unsupported font token: "+e)}r.weight=e}else r.stretch=e;else r.variant=e;else r.style=e}throw new Error("Missing required font-size.")}function p(t){var e=parseFloat(t);return e.toString()===t?e:t}},{"./lib/util":128,"css-font-stretch-keywords":124,"css-font-style-keywords":125,"css-font-weight-keywords":126,"css-global-keywords":131,"css-system-font-keywords":132,"string-split-by":510,unquote:529}],130:[function(t,e,r){"use strict";var n=t("pick-by-alias"),i=t("./lib/util").isSize,a=g(t("css-global-keywords")),o=g(t("css-system-font-keywords")),s=g(t("css-font-weight-keywords")),l=g(t("css-font-style-keywords")),c=g(t("css-font-stretch-keywords")),u={normal:1,"small-caps":1},h={serif:1,"sans-serif":1,monospace:1,cursive:1,fantasy:1,"system-ui":1},f="1rem",p="serif";function d(t,e){if(t&&!e[t]&&!a[t])throw Error("Unknown keyword `"+t+"`");return t}function g(t){for(var e={},r=0;r<t.length;r++)e[t[r]]=1;return e}e.exports=function(t){if((t=n(t,{style:"style fontstyle fontStyle font-style slope distinction",variant:"variant font-variant fontVariant fontvariant var capitalization",weight:"weight w font-weight fontWeight fontweight",stretch:"stretch font-stretch fontStretch fontstretch width",size:"size s font-size fontSize fontsize height em emSize",lineHeight:"lh line-height lineHeight lineheight leading",family:"font family fontFamily font-family fontfamily type typeface face",system:"system reserved default global"})).system)return t.system&&d(t.system,o),t.system;if(d(t.style,l),d(t.variant,u),d(t.weight,s),d(t.stretch,c),null==t.size&&(t.size=f),"number"==typeof t.size&&(t.size+="px"),!i)throw Error("Bad size value `"+t.size+"`");t.family||(t.family=p),Array.isArray(t.family)&&(t.family.length||(t.family=[p]),t.family=t.family.map(function(t){return h[t]?t:'"'+t+'"'}).join(", "));var e=[];return e.push(t.style),t.variant!==t.style&&e.push(t.variant),t.weight!==t.variant&&t.weight!==t.style&&e.push(t.weight),t.stretch!==t.weight&&t.stretch!==t.variant&&t.stretch!==t.style&&e.push(t.stretch),e.push(t.size+(null==t.lineHeight||"normal"===t.lineHeight||t.lineHeight+""=="1"?"":"/"+t.lineHeight)),e.push(t.family),e.filter(Boolean).join(" ")}},{"./lib/util":128,"css-font-stretch-keywords":124,"css-font-style-keywords":125,"css-font-weight-keywords":126,"css-global-keywords":131,"css-system-font-keywords":132,"pick-by-alias":454}],131:[function(t,e,r){e.exports=["inherit","initial","unset"]},{}],132:[function(t,e,r){e.exports=["caption","icon","menu","message-box","small-caption","status-bar"]},{}],133:[function(t,e,r){"use strict";e.exports=function(t,e,r,n,i,a){var o=i-1,s=i*i,l=o*o,c=(1+2*i)*l,u=i*l,h=s*(3-2*i),f=s*o;if(t.length){a||(a=new Array(t.length));for(var p=t.length-1;p>=0;--p)a[p]=c*t[p]+u*e[p]+h*r[p]+f*n[p];return a}return c*t+u*e+h*r+f*n},e.exports.derivative=function(t,e,r,n,i,a){var o=6*i*i-6*i,s=3*i*i-4*i+1,l=-6*i*i+6*i,c=3*i*i-2*i;if(t.length){a||(a=new Array(t.length));for(var u=t.length-1;u>=0;--u)a[u]=o*t[u]+s*e[u]+l*r[u]+c*n[u];return a}return o*t+s*e+l*r[u]+c*n}},{}],134:[function(t,e,r){"use strict";var n=t("./lib/thunk.js");function i(){this.argTypes=[],this.shimArgs=[],this.arrayArgs=[],this.arrayBlockIndices=[],this.scalarArgs=[],this.offsetArgs=[],this.offsetArgIndex=[],this.indexArgs=[],this.shapeArgs=[],this.funcName="",this.pre=null,this.body=null,this.post=null,this.debug=!1}e.exports=function(t){var e=new i;e.pre=t.pre,e.body=t.body,e.post=t.post;var r=t.args.slice(0);e.argTypes=r;for(var a=0;a<r.length;++a){var o=r[a];if("array"===o||"object"==typeof o&&o.blockIndices){if(e.argTypes[a]="array",e.arrayArgs.push(a),e.arrayBlockIndices.push(o.blockIndices?o.blockIndices:0),e.shimArgs.push("array"+a),a<e.pre.args.length&&e.pre.args[a].count>0)throw new Error("cwise: pre() block may not reference array args");if(a<e.post.args.length&&e.post.args[a].count>0)throw new Error("cwise: post() block may not reference array args")}else if("scalar"===o)e.scalarArgs.push(a),e.shimArgs.push("scalar"+a);else if("index"===o){if(e.indexArgs.push(a),a<e.pre.args.length&&e.pre.args[a].count>0)throw new Error("cwise: pre() block may not reference array index");if(a<e.body.args.length&&e.body.args[a].lvalue)throw new Error("cwise: body() block may not write to array index");if(a<e.post.args.length&&e.post.args[a].count>0)throw new Error("cwise: post() block may not reference array index")}else if("shape"===o){if(e.shapeArgs.push(a),a<e.pre.args.length&&e.pre.args[a].lvalue)throw new Error("cwise: pre() block may not write to array shape");if(a<e.body.args.length&&e.body.args[a].lvalue)throw new Error("cwise: body() block may not write to array shape");if(a<e.post.args.length&&e.post.args[a].lvalue)throw new Error("cwise: post() block may not write to array shape")}else{if("object"!=typeof o||!o.offset)throw new Error("cwise: Unknown argument type "+r[a]);e.argTypes[a]="offset",e.offsetArgs.push({array:o.array,offset:o.offset}),e.offsetArgIndex.push(a)}}if(e.arrayArgs.length<=0)throw new Error("cwise: No array arguments specified");if(e.pre.args.length>r.length)throw new Error("cwise: Too many arguments in pre() block");if(e.body.args.length>r.length)throw new Error("cwise: Too many arguments in body() block");if(e.post.args.length>r.length)throw new Error("cwise: Too many arguments in post() block");return e.debug=!!t.printCode||!!t.debug,e.funcName=t.funcName||"cwise",e.blockSize=t.blockSize||64,n(e)}},{"./lib/thunk.js":136}],135:[function(t,e,r){"use strict";var n=t("uniq");function i(t,e,r){var n,i,a=t.length,o=e.arrayArgs.length,s=e.indexArgs.length>0,l=[],c=[],u=0,h=0;for(n=0;n<a;++n)c.push(["i",n,"=0"].join(""));for(i=0;i<o;++i)for(n=0;n<a;++n)h=u,u=t[n],0===n?c.push(["d",i,"s",n,"=t",i,"p",u].join("")):c.push(["d",i,"s",n,"=(t",i,"p",u,"-s",h,"*t",i,"p",h,")"].join(""));for(c.length>0&&l.push("var "+c.join(",")),n=a-1;n>=0;--n)u=t[n],l.push(["for(i",n,"=0;i",n,"<s",u,";++i",n,"){"].join(""));for(l.push(r),n=0;n<a;++n){for(h=u,u=t[n],i=0;i<o;++i)l.push(["p",i,"+=d",i,"s",n].join(""));s&&(n>0&&l.push(["index[",h,"]-=s",h].join("")),l.push(["++index[",u,"]"].join(""))),l.push("}")}return l.join("\n")}function a(t,e,r){for(var n=t.body,i=[],a=[],o=0;o<t.args.length;++o){var s=t.args[o];if(!(s.count<=0)){var l=new RegExp(s.name,"g"),c="",u=e.arrayArgs.indexOf(o);switch(e.argTypes[o]){case"offset":var h=e.offsetArgIndex.indexOf(o);u=e.offsetArgs[h].array,c="+q"+h;case"array":c="p"+u+c;var f="l"+o,p="a"+u;if(0===e.arrayBlockIndices[u])1===s.count?"generic"===r[u]?s.lvalue?(i.push(["var ",f,"=",p,".get(",c,")"].join("")),n=n.replace(l,f),a.push([p,".set(",c,",",f,")"].join(""))):n=n.replace(l,[p,".get(",c,")"].join("")):n=n.replace(l,[p,"[",c,"]"].join("")):"generic"===r[u]?(i.push(["var ",f,"=",p,".get(",c,")"].join("")),n=n.replace(l,f),s.lvalue&&a.push([p,".set(",c,",",f,")"].join(""))):(i.push(["var ",f,"=",p,"[",c,"]"].join("")),n=n.replace(l,f),s.lvalue&&a.push([p,"[",c,"]=",f].join("")));else{for(var d=[s.name],g=[c],v=0;v<Math.abs(e.arrayBlockIndices[u]);v++)d.push("\\s*\\[([^\\]]+)\\]"),g.push("$"+(v+1)+"*t"+u+"b"+v);if(l=new RegExp(d.join(""),"g"),c=g.join("+"),"generic"===r[u])throw new Error("cwise: Generic arrays not supported in combination with blocks!");n=n.replace(l,[p,"[",c,"]"].join(""))}break;case"scalar":n=n.replace(l,"Y"+e.scalarArgs.indexOf(o));break;case"index":n=n.replace(l,"index");break;case"shape":n=n.replace(l,"shape")}}}return[i.join("\n"),n,a.join("\n")].join("\n").trim()}e.exports=function(t,e){for(var r=e[1].length-Math.abs(t.arrayBlockIndices[0])|0,o=new Array(t.arrayArgs.length),s=new Array(t.arrayArgs.length),l=0;l<t.arrayArgs.length;++l)s[l]=e[2*l],o[l]=e[2*l+1];var c=[],u=[],h=[],f=[],p=[];for(l=0;l<t.arrayArgs.length;++l){t.arrayBlockIndices[l]<0?(h.push(0),f.push(r),c.push(r),u.push(r+t.arrayBlockIndices[l])):(h.push(t.arrayBlockIndices[l]),f.push(t.arrayBlockIndices[l]+r),c.push(0),u.push(t.arrayBlockIndices[l]));for(var d=[],g=0;g<o[l].length;g++)h[l]<=o[l][g]&&o[l][g]<f[l]&&d.push(o[l][g]-h[l]);p.push(d)}var v=["SS"],m=["'use strict'"],y=[];for(g=0;g<r;++g)y.push(["s",g,"=SS[",g,"]"].join(""));for(l=0;l<t.arrayArgs.length;++l){for(v.push("a"+l),v.push("t"+l),v.push("p"+l),g=0;g<r;++g)y.push(["t",l,"p",g,"=t",l,"[",h[l]+g,"]"].join(""));for(g=0;g<Math.abs(t.arrayBlockIndices[l]);++g)y.push(["t",l,"b",g,"=t",l,"[",c[l]+g,"]"].join(""))}for(l=0;l<t.scalarArgs.length;++l)v.push("Y"+l);if(t.shapeArgs.length>0&&y.push("shape=SS.slice(0)"),t.indexArgs.length>0){var x=new Array(r);for(l=0;l<r;++l)x[l]="0";y.push(["index=[",x.join(","),"]"].join(""))}for(l=0;l<t.offsetArgs.length;++l){var b=t.offsetArgs[l],_=[];for(g=0;g<b.offset.length;++g)0!==b.offset[g]&&(1===b.offset[g]?_.push(["t",b.array,"p",g].join("")):_.push([b.offset[g],"*t",b.array,"p",g].join("")));0===_.length?y.push("q"+l+"=0"):y.push(["q",l,"=",_.join("+")].join(""))}var w=n([].concat(t.pre.thisVars).concat(t.body.thisVars).concat(t.post.thisVars));for((y=y.concat(w)).length>0&&m.push("var "+y.join(",")),l=0;l<t.arrayArgs.length;++l)m.push("p"+l+"|=0");t.pre.body.length>3&&m.push(a(t.pre,t,s));var k=a(t.body,t,s),A=function(t){for(var e=0,r=t[0].length;e<r;){for(var n=1;n<t.length;++n)if(t[n][e]!==t[0][e])return e;++e}return e}(p);A<r?m.push(function(t,e,r,n){for(var a=e.length,o=r.arrayArgs.length,s=r.blockSize,l=r.indexArgs.length>0,c=[],u=0;u<o;++u)c.push(["var offset",u,"=p",u].join(""));for(u=t;u<a;++u)c.push(["for(var j"+u+"=SS[",e[u],"]|0;j",u,">0;){"].join("")),c.push(["if(j",u,"<",s,"){"].join("")),c.push(["s",e[u],"=j",u].join("")),c.push(["j",u,"=0"].join("")),c.push(["}else{s",e[u],"=",s].join("")),c.push(["j",u,"-=",s,"}"].join("")),l&&c.push(["index[",e[u],"]=j",u].join(""));for(u=0;u<o;++u){for(var h=["offset"+u],f=t;f<a;++f)h.push(["j",f,"*t",u,"p",e[f]].join(""));c.push(["p",u,"=(",h.join("+"),")"].join(""))}for(c.push(i(e,r,n)),u=t;u<a;++u)c.push("}");return c.join("\n")}(A,p[0],t,k)):m.push(i(p[0],t,k)),t.post.body.length>3&&m.push(a(t.post,t,s)),t.debug&&console.log("-----Generated cwise routine for ",e,":\n"+m.join("\n")+"\n----------");var M=[t.funcName||"unnamed","_cwise_loop_",o[0].join("s"),"m",A,function(t){for(var e=new Array(t.length),r=!0,n=0;n<t.length;++n){var i=t[n],a=i.match(/\d+/);a=a?a[0]:"",0===i.charAt(0)?e[n]="u"+i.charAt(1)+a:e[n]=i.charAt(0)+a,n>0&&(r=r&&e[n]===e[n-1])}return r?e[0]:e.join("")}(s)].join("");return new Function(["function ",M,"(",v.join(","),"){",m.join("\n"),"} return ",M].join(""))()}},{uniq:528}],136:[function(t,e,r){"use strict";var n=t("./compile.js");e.exports=function(t){var e=["'use strict'","var CACHED={}"],r=[],i=t.funcName+"_cwise_thunk";e.push(["return function ",i,"(",t.shimArgs.join(","),"){"].join(""));for(var a=[],o=[],s=[["array",t.arrayArgs[0],".shape.slice(",Math.max(0,t.arrayBlockIndices[0]),t.arrayBlockIndices[0]<0?","+t.arrayBlockIndices[0]+")":")"].join("")],l=[],c=[],u=0;u<t.arrayArgs.length;++u){var h=t.arrayArgs[u];r.push(["t",h,"=array",h,".dtype,","r",h,"=array",h,".order"].join("")),a.push("t"+h),a.push("r"+h),o.push("t"+h),o.push("r"+h+".join()"),s.push("array"+h+".data"),s.push("array"+h+".stride"),s.push("array"+h+".offset|0"),u>0&&(l.push("array"+t.arrayArgs[0]+".shape.length===array"+h+".shape.length+"+(Math.abs(t.arrayBlockIndices[0])-Math.abs(t.arrayBlockIndices[u]))),c.push("array"+t.arrayArgs[0]+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[0])+"]===array"+h+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[u])+"]"))}for(t.arrayArgs.length>1&&(e.push("if (!("+l.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same dimensionality!')"),e.push("for(var shapeIndex=array"+t.arrayArgs[0]+".shape.length-"+Math.abs(t.arrayBlockIndices[0])+"; shapeIndex--\x3e0;) {"),e.push("if (!("+c.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same shape!')"),e.push("}")),u=0;u<t.scalarArgs.length;++u)s.push("scalar"+t.scalarArgs[u]);return r.push(["type=[",o.join(","),"].join()"].join("")),r.push("proc=CACHED[type]"),e.push("var "+r.join(",")),e.push(["if(!proc){","CACHED[type]=proc=compile([",a.join(","),"])}","return proc(",s.join(","),")}"].join("")),t.debug&&console.log("-----Generated thunk:\n"+e.join("\n")+"\n----------"),new Function("compile",e.join("\n"))(n.bind(void 0,t))}},{"./compile.js":135}],137:[function(t,e,r){e.exports=t("cwise-compiler")},{"cwise-compiler":134}],138:[function(t,e,r){"use strict";var n,i=t("es5-ext/object/copy"),a=t("es5-ext/object/normalize-options"),o=t("es5-ext/object/valid-callable"),s=t("es5-ext/object/map"),l=t("es5-ext/object/valid-callable"),c=t("es5-ext/object/valid-value"),u=Function.prototype.bind,h=Object.defineProperty,f=Object.prototype.hasOwnProperty;n=function(t,e,r){var n,a=c(e)&&l(e.value);return delete(n=i(e)).writable,delete n.value,n.get=function(){return!r.overwriteDefinition&&f.call(this,t)?a:(e.value=u.call(a,r.resolveContext?r.resolveContext(this):this),h(this,t,e),this[t])},n},e.exports=function(t){var e=a(arguments[1]);return null!=e.resolveContext&&o(e.resolveContext),s(t,function(t,r){return n(r,t,e)})}},{"es5-ext/object/copy":178,"es5-ext/object/map":187,"es5-ext/object/normalize-options":188,"es5-ext/object/valid-callable":192,"es5-ext/object/valid-value":194}],139:[function(t,e,r){"use strict";var n=t("es5-ext/object/assign"),i=t("es5-ext/object/normalize-options"),a=t("es5-ext/object/is-callable"),o=t("es5-ext/string/#/contains");(e.exports=function(t,e){var r,a,s,l,c;return arguments.length<2||"string"!=typeof t?(l=e,e=t,t=null):l=arguments[2],null==t?(r=s=!0,a=!1):(r=o.call(t,"c"),a=o.call(t,"e"),s=o.call(t,"w")),c={value:e,configurable:r,enumerable:a,writable:s},l?n(i(l),c):c}).gs=function(t,e,r){var s,l,c,u;return"string"!=typeof t?(c=r,r=e,e=t,t=null):c=arguments[3],null==e?e=void 0:a(e)?null==r?r=void 0:a(r)||(c=r,r=void 0):(c=e,e=r=void 0),null==t?(s=!0,l=!1):(s=o.call(t,"c"),l=o.call(t,"e")),u={get:e,set:r,configurable:s,enumerable:l},c?n(i(c),u):u}},{"es5-ext/object/assign":175,"es5-ext/object/is-callable":181,"es5-ext/object/normalize-options":188,"es5-ext/string/#/contains":195}],140:[function(t,e,r){var n;n=this,function(t){"use strict";function e(t,e){return t<e?-1:t>e?1:t>=e?0:NaN}function r(t){var r;return 1===t.length&&(r=t,t=function(t,n){return e(r(t),n)}),{left:function(e,r,n,i){for(null==n&&(n=0),null==i&&(i=e.length);n<i;){var a=n+i>>>1;t(e[a],r)<0?n=a+1:i=a}return n},right:function(e,r,n,i){for(null==n&&(n=0),null==i&&(i=e.length);n<i;){var a=n+i>>>1;t(e[a],r)>0?i=a:n=a+1}return n}}}var n=r(e),i=n.right,a=n.left;function o(t,e){return[t,e]}function s(t){return null===t?NaN:+t}function l(t,e){var r,n,i=t.length,a=0,o=-1,l=0,c=0;if(null==e)for(;++o<i;)isNaN(r=s(t[o]))||(c+=(n=r-l)*(r-(l+=n/++a)));else for(;++o<i;)isNaN(r=s(e(t[o],o,t)))||(c+=(n=r-l)*(r-(l+=n/++a)));if(a>1)return c/(a-1)}function c(t,e){var r=l(t,e);return r?Math.sqrt(r):r}function u(t,e){var r,n,i,a=t.length,o=-1;if(null==e){for(;++o<a;)if(null!=(r=t[o])&&r>=r)for(n=i=r;++o<a;)null!=(r=t[o])&&(n>r&&(n=r),i<r&&(i=r))}else for(;++o<a;)if(null!=(r=e(t[o],o,t))&&r>=r)for(n=i=r;++o<a;)null!=(r=e(t[o],o,t))&&(n>r&&(n=r),i<r&&(i=r));return[n,i]}var h=Array.prototype,f=h.slice,p=h.map;function d(t){return function(){return t}}function g(t){return t}function v(t,e,r){t=+t,e=+e,r=(i=arguments.length)<2?(e=t,t=0,1):i<3?1:+r;for(var n=-1,i=0|Math.max(0,Math.ceil((e-t)/r)),a=new Array(i);++n<i;)a[n]=t+n*r;return a}var m=Math.sqrt(50),y=Math.sqrt(10),x=Math.sqrt(2);function b(t,e,r){var n=(e-t)/Math.max(0,r),i=Math.floor(Math.log(n)/Math.LN10),a=n/Math.pow(10,i);return i>=0?(a>=m?10:a>=y?5:a>=x?2:1)*Math.pow(10,i):-Math.pow(10,-i)/(a>=m?10:a>=y?5:a>=x?2:1)}function _(t,e,r){var n=Math.abs(e-t)/Math.max(0,r),i=Math.pow(10,Math.floor(Math.log(n)/Math.LN10)),a=n/i;return a>=m?i*=10:a>=y?i*=5:a>=x&&(i*=2),e<t?-i:i}function w(t){return Math.ceil(Math.log(t.length)/Math.LN2)+1}function k(t,e,r){if(null==r&&(r=s),n=t.length){if((e=+e)<=0||n<2)return+r(t[0],0,t);if(e>=1)return+r(t[n-1],n-1,t);var n,i=(n-1)*e,a=Math.floor(i),o=+r(t[a],a,t);return o+(+r(t[a+1],a+1,t)-o)*(i-a)}}function A(t,e){var r,n,i=t.length,a=-1;if(null==e){for(;++a<i;)if(null!=(r=t[a])&&r>=r)for(n=r;++a<i;)null!=(r=t[a])&&n>r&&(n=r)}else for(;++a<i;)if(null!=(r=e(t[a],a,t))&&r>=r)for(n=r;++a<i;)null!=(r=e(t[a],a,t))&&n>r&&(n=r);return n}function M(t){if(!(i=t.length))return[];for(var e=-1,r=A(t,T),n=new Array(r);++e<r;)for(var i,a=-1,o=n[e]=new Array(i);++a<i;)o[a]=t[a][e];return n}function T(t){return t.length}t.bisect=i,t.bisectRight=i,t.bisectLeft=a,t.ascending=e,t.bisector=r,t.cross=function(t,e,r){var n,i,a,s,l=t.length,c=e.length,u=new Array(l*c);for(null==r&&(r=o),n=a=0;n<l;++n)for(s=t[n],i=0;i<c;++i,++a)u[a]=r(s,e[i]);return u},t.descending=function(t,e){return e<t?-1:e>t?1:e>=t?0:NaN},t.deviation=c,t.extent=u,t.histogram=function(){var t=g,e=u,r=w;function n(n){var a,o,s=n.length,l=new Array(s);for(a=0;a<s;++a)l[a]=t(n[a],a,n);var c=e(l),u=c[0],h=c[1],f=r(l,u,h);Array.isArray(f)||(f=_(u,h,f),f=v(Math.ceil(u/f)*f,h,f));for(var p=f.length;f[0]<=u;)f.shift(),--p;for(;f[p-1]>h;)f.pop(),--p;var d,g=new Array(p+1);for(a=0;a<=p;++a)(d=g[a]=[]).x0=a>0?f[a-1]:u,d.x1=a<p?f[a]:h;for(a=0;a<s;++a)u<=(o=l[a])&&o<=h&&g[i(f,o,0,p)].push(n[a]);return g}return n.value=function(e){return arguments.length?(t="function"==typeof e?e:d(e),n):t},n.domain=function(t){return arguments.length?(e="function"==typeof t?t:d([t[0],t[1]]),n):e},n.thresholds=function(t){return arguments.length?(r="function"==typeof t?t:Array.isArray(t)?d(f.call(t)):d(t),n):r},n},t.thresholdFreedmanDiaconis=function(t,r,n){return t=p.call(t,s).sort(e),Math.ceil((n-r)/(2*(k(t,.75)-k(t,.25))*Math.pow(t.length,-1/3)))},t.thresholdScott=function(t,e,r){return Math.ceil((r-e)/(3.5*c(t)*Math.pow(t.length,-1/3)))},t.thresholdSturges=w,t.max=function(t,e){var r,n,i=t.length,a=-1;if(null==e){for(;++a<i;)if(null!=(r=t[a])&&r>=r)for(n=r;++a<i;)null!=(r=t[a])&&r>n&&(n=r)}else for(;++a<i;)if(null!=(r=e(t[a],a,t))&&r>=r)for(n=r;++a<i;)null!=(r=e(t[a],a,t))&&r>n&&(n=r);return n},t.mean=function(t,e){var r,n=t.length,i=n,a=-1,o=0;if(null==e)for(;++a<n;)isNaN(r=s(t[a]))?--i:o+=r;else for(;++a<n;)isNaN(r=s(e(t[a],a,t)))?--i:o+=r;if(i)return o/i},t.median=function(t,r){var n,i=t.length,a=-1,o=[];if(null==r)for(;++a<i;)isNaN(n=s(t[a]))||o.push(n);else for(;++a<i;)isNaN(n=s(r(t[a],a,t)))||o.push(n);return k(o.sort(e),.5)},t.merge=function(t){for(var e,r,n,i=t.length,a=-1,o=0;++a<i;)o+=t[a].length;for(r=new Array(o);--i>=0;)for(e=(n=t[i]).length;--e>=0;)r[--o]=n[e];return r},t.min=A,t.pairs=function(t,e){null==e&&(e=o);for(var r=0,n=t.length-1,i=t[0],a=new Array(n<0?0:n);r<n;)a[r]=e(i,i=t[++r]);return a},t.permute=function(t,e){for(var r=e.length,n=new Array(r);r--;)n[r]=t[e[r]];return n},t.quantile=k,t.range=v,t.scan=function(t,r){if(n=t.length){var n,i,a=0,o=0,s=t[o];for(null==r&&(r=e);++a<n;)(r(i=t[a],s)<0||0!==r(s,s))&&(s=i,o=a);return 0===r(s,s)?o:void 0}},t.shuffle=function(t,e,r){for(var n,i,a=(null==r?t.length:r)-(e=null==e?0:+e);a;)i=Math.random()*a--|0,n=t[a+e],t[a+e]=t[i+e],t[i+e]=n;return t},t.sum=function(t,e){var r,n=t.length,i=-1,a=0;if(null==e)for(;++i<n;)(r=+t[i])&&(a+=r);else for(;++i<n;)(r=+e(t[i],i,t))&&(a+=r);return a},t.ticks=function(t,e,r){var n,i,a,o,s=-1;if(r=+r,(t=+t)==(e=+e)&&r>0)return[t];if((n=e<t)&&(i=t,t=e,e=i),0===(o=b(t,e,r))||!isFinite(o))return[];if(o>0)for(t=Math.ceil(t/o),e=Math.floor(e/o),a=new Array(i=Math.ceil(e-t+1));++s<i;)a[s]=(t+s)*o;else for(t=Math.floor(t*o),e=Math.ceil(e*o),a=new Array(i=Math.ceil(t-e+1));++s<i;)a[s]=(t-s)/o;return n&&a.reverse(),a},t.tickIncrement=b,t.tickStep=_,t.transpose=M,t.variance=l,t.zip=function(){return M(arguments)},Object.defineProperty(t,"__esModule",{value:!0})}("object"==typeof r&&"undefined"!=typeof e?r:n.d3=n.d3||{})},{}],141:[function(t,e,r){var n;n=this,function(t){"use strict";function e(){}function r(t,r){var n=new e;if(t instanceof e)t.each(function(t,e){n.set(e,t)});else if(Array.isArray(t)){var i,a=-1,o=t.length;if(null==r)for(;++a<o;)n.set(a,t[a]);else for(;++a<o;)n.set(r(i=t[a],a,t),i)}else if(t)for(var s in t)n.set(s,t[s]);return n}e.prototype=r.prototype={constructor:e,has:function(t){return"$"+t in this},get:function(t){return this["$"+t]},set:function(t,e){return this["$"+t]=e,this},remove:function(t){var e="$"+t;return e in this&&delete this[e]},clear:function(){for(var t in this)"$"===t[0]&&delete this[t]},keys:function(){var t=[];for(var e in this)"$"===e[0]&&t.push(e.slice(1));return t},values:function(){var t=[];for(var e in this)"$"===e[0]&&t.push(this[e]);return t},entries:function(){var t=[];for(var e in this)"$"===e[0]&&t.push({key:e.slice(1),value:this[e]});return t},size:function(){var t=0;for(var e in this)"$"===e[0]&&++t;return t},empty:function(){for(var t in this)if("$"===t[0])return!1;return!0},each:function(t){for(var e in this)"$"===e[0]&&t(this[e],e.slice(1),this)}};function n(){return{}}function i(t,e,r){t[e]=r}function a(){return r()}function o(t,e,r){t.set(e,r)}function s(){}var l=r.prototype;function c(t,e){var r=new s;if(t instanceof s)t.each(function(t){r.add(t)});else if(t){var n=-1,i=t.length;if(null==e)for(;++n<i;)r.add(t[n]);else for(;++n<i;)r.add(e(t[n],n,t))}return r}s.prototype=c.prototype={constructor:s,has:l.has,add:function(t){return this["$"+(t+="")]=t,this},remove:l.remove,clear:l.clear,values:l.keys,size:l.size,empty:l.empty,each:l.each};t.nest=function(){var t,e,s,l=[],c=[];function u(n,i,a,o){if(i>=l.length)return null!=t&&n.sort(t),null!=e?e(n):n;for(var s,c,h,f=-1,p=n.length,d=l[i++],g=r(),v=a();++f<p;)(h=g.get(s=d(c=n[f])+""))?h.push(c):g.set(s,[c]);return g.each(function(t,e){o(v,e,u(t,i,a,o))}),v}return s={object:function(t){return u(t,0,n,i)},map:function(t){return u(t,0,a,o)},entries:function(t){return function t(r,n){if(++n>l.length)return r;var i,a=c[n-1];return null!=e&&n>=l.length?i=r.entries():(i=[],r.each(function(e,r){i.push({key:r,values:t(e,n)})})),null!=a?i.sort(function(t,e){return a(t.key,e.key)}):i}(u(t,0,a,o),0)},key:function(t){return l.push(t),s},sortKeys:function(t){return c[l.length-1]=t,s},sortValues:function(e){return t=e,s},rollup:function(t){return e=t,s}}},t.set=c,t.map=r,t.keys=function(t){var e=[];for(var r in t)e.push(r);return e},t.values=function(t){var e=[];for(var r in t)e.push(t[r]);return e},t.entries=function(t){var e=[];for(var r in t)e.push({key:r,value:t[r]});return e},Object.defineProperty(t,"__esModule",{value:!0})}("object"==typeof r&&"undefined"!=typeof e?r:n.d3=n.d3||{})},{}],142:[function(t,e,r){var n;n=this,function(t){"use strict";function e(t,e,r){t.prototype=e.prototype=r,r.constructor=t}function r(t,e){var r=Object.create(t.prototype);for(var n in e)r[n]=e[n];return r}function n(){}var i="\\s*([+-]?\\d+)\\s*",a="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",o="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",s=/^#([0-9a-f]{3})$/,l=/^#([0-9a-f]{6})$/,c=new RegExp("^rgb\\("+[i,i,i]+"\\)$"),u=new RegExp("^rgb\\("+[o,o,o]+"\\)$"),h=new RegExp("^rgba\\("+[i,i,i,a]+"\\)$"),f=new RegExp("^rgba\\("+[o,o,o,a]+"\\)$"),p=new RegExp("^hsl\\("+[a,o,o]+"\\)$"),d=new RegExp("^hsla\\("+[a,o,o,a]+"\\)$"),g={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};function v(t){var e;return t=(t+"").trim().toLowerCase(),(e=s.exec(t))?new _((e=parseInt(e[1],16))>>8&15|e>>4&240,e>>4&15|240&e,(15&e)<<4|15&e,1):(e=l.exec(t))?m(parseInt(e[1],16)):(e=c.exec(t))?new _(e[1],e[2],e[3],1):(e=u.exec(t))?new _(255*e[1]/100,255*e[2]/100,255*e[3]/100,1):(e=h.exec(t))?y(e[1],e[2],e[3],e[4]):(e=f.exec(t))?y(255*e[1]/100,255*e[2]/100,255*e[3]/100,e[4]):(e=p.exec(t))?k(e[1],e[2]/100,e[3]/100,1):(e=d.exec(t))?k(e[1],e[2]/100,e[3]/100,e[4]):g.hasOwnProperty(t)?m(g[t]):"transparent"===t?new _(NaN,NaN,NaN,0):null}function m(t){return new _(t>>16&255,t>>8&255,255&t,1)}function y(t,e,r,n){return n<=0&&(t=e=r=NaN),new _(t,e,r,n)}function x(t){return t instanceof n||(t=v(t)),t?new _((t=t.rgb()).r,t.g,t.b,t.opacity):new _}function b(t,e,r,n){return 1===arguments.length?x(t):new _(t,e,r,null==n?1:n)}function _(t,e,r,n){this.r=+t,this.g=+e,this.b=+r,this.opacity=+n}function w(t){return((t=Math.max(0,Math.min(255,Math.round(t)||0)))<16?"0":"")+t.toString(16)}function k(t,e,r,n){return n<=0?t=e=r=NaN:r<=0||r>=1?t=e=NaN:e<=0&&(t=NaN),new M(t,e,r,n)}function A(t,e,r,i){return 1===arguments.length?function(t){if(t instanceof M)return new M(t.h,t.s,t.l,t.opacity);if(t instanceof n||(t=v(t)),!t)return new M;if(t instanceof M)return t;var e=(t=t.rgb()).r/255,r=t.g/255,i=t.b/255,a=Math.min(e,r,i),o=Math.max(e,r,i),s=NaN,l=o-a,c=(o+a)/2;return l?(s=e===o?(r-i)/l+6*(r<i):r===o?(i-e)/l+2:(e-r)/l+4,l/=c<.5?o+a:2-o-a,s*=60):l=c>0&&c<1?0:s,new M(s,l,c,t.opacity)}(t):new M(t,e,r,null==i?1:i)}function M(t,e,r,n){this.h=+t,this.s=+e,this.l=+r,this.opacity=+n}function T(t,e,r){return 255*(t<60?e+(r-e)*t/60:t<180?r:t<240?e+(r-e)*(240-t)/60:e)}e(n,v,{displayable:function(){return this.rgb().displayable()},hex:function(){return this.rgb().hex()},toString:function(){return this.rgb()+""}}),e(_,b,r(n,{brighter:function(t){return t=null==t?1/.7:Math.pow(1/.7,t),new _(this.r*t,this.g*t,this.b*t,this.opacity)},darker:function(t){return t=null==t?.7:Math.pow(.7,t),new _(this.r*t,this.g*t,this.b*t,this.opacity)},rgb:function(){return this},displayable:function(){return 0<=this.r&&this.r<=255&&0<=this.g&&this.g<=255&&0<=this.b&&this.b<=255&&0<=this.opacity&&this.opacity<=1},hex:function(){return"#"+w(this.r)+w(this.g)+w(this.b)},toString:function(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"rgb(":"rgba(")+Math.max(0,Math.min(255,Math.round(this.r)||0))+", "+Math.max(0,Math.min(255,Math.round(this.g)||0))+", "+Math.max(0,Math.min(255,Math.round(this.b)||0))+(1===t?")":", "+t+")")}})),e(M,A,r(n,{brighter:function(t){return t=null==t?1/.7:Math.pow(1/.7,t),new M(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?.7:Math.pow(.7,t),new M(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=this.h%360+360*(this.h<0),e=isNaN(t)||isNaN(this.s)?0:this.s,r=this.l,n=r+(r<.5?r:1-r)*e,i=2*r-n;return new _(T(t>=240?t-240:t+120,i,n),T(t,i,n),T(t<120?t+240:t-120,i,n),this.opacity)},displayable:function(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1}}));var S=Math.PI/180,E=180/Math.PI,C=.96422,L=1,z=.82521,O=4/29,I=6/29,D=3*I*I,P=I*I*I;function R(t){if(t instanceof B)return new B(t.l,t.a,t.b,t.opacity);if(t instanceof G){if(isNaN(t.h))return new B(t.l,0,0,t.opacity);var e=t.h*S;return new B(t.l,Math.cos(e)*t.c,Math.sin(e)*t.c,t.opacity)}t instanceof _||(t=x(t));var r,n,i=U(t.r),a=U(t.g),o=U(t.b),s=N((.2225045*i+.7168786*a+.0606169*o)/L);return i===a&&a===o?r=n=s:(r=N((.4360747*i+.3850649*a+.1430804*o)/C),n=N((.0139322*i+.0971045*a+.7141733*o)/z)),new B(116*s-16,500*(r-s),200*(s-n),t.opacity)}function F(t,e,r,n){return 1===arguments.length?R(t):new B(t,e,r,null==n?1:n)}function B(t,e,r,n){this.l=+t,this.a=+e,this.b=+r,this.opacity=+n}function N(t){return t>P?Math.pow(t,1/3):t/D+O}function j(t){return t>I?t*t*t:D*(t-O)}function V(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function U(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function q(t){if(t instanceof G)return new G(t.h,t.c,t.l,t.opacity);if(t instanceof B||(t=R(t)),0===t.a&&0===t.b)return new G(NaN,0,t.l,t.opacity);var e=Math.atan2(t.b,t.a)*E;return new G(e<0?e+360:e,Math.sqrt(t.a*t.a+t.b*t.b),t.l,t.opacity)}function H(t,e,r,n){return 1===arguments.length?q(t):new G(t,e,r,null==n?1:n)}function G(t,e,r,n){this.h=+t,this.c=+e,this.l=+r,this.opacity=+n}e(B,F,r(n,{brighter:function(t){return new B(this.l+18*(null==t?1:t),this.a,this.b,this.opacity)},darker:function(t){return new B(this.l-18*(null==t?1:t),this.a,this.b,this.opacity)},rgb:function(){var t=(this.l+16)/116,e=isNaN(this.a)?t:t+this.a/500,r=isNaN(this.b)?t:t-this.b/200;return new _(V(3.1338561*(e=C*j(e))-1.6168667*(t=L*j(t))-.4906146*(r=z*j(r))),V(-.9787684*e+1.9161415*t+.033454*r),V(.0719453*e-.2289914*t+1.4052427*r),this.opacity)}})),e(G,H,r(n,{brighter:function(t){return new G(this.h,this.c,this.l+18*(null==t?1:t),this.opacity)},darker:function(t){return new G(this.h,this.c,this.l-18*(null==t?1:t),this.opacity)},rgb:function(){return R(this).rgb()}}));var Y=-.14861,W=1.78277,X=-.29227,Z=-.90649,$=1.97294,J=$*Z,K=$*W,Q=W*X-Z*Y;function tt(t,e,r,n){return 1===arguments.length?function(t){if(t instanceof et)return new et(t.h,t.s,t.l,t.opacity);t instanceof _||(t=x(t));var e=t.r/255,r=t.g/255,n=t.b/255,i=(Q*n+J*e-K*r)/(Q+J-K),a=n-i,o=($*(r-i)-X*a)/Z,s=Math.sqrt(o*o+a*a)/($*i*(1-i)),l=s?Math.atan2(o,a)*E-120:NaN;return new et(l<0?l+360:l,s,i,t.opacity)}(t):new et(t,e,r,null==n?1:n)}function et(t,e,r,n){this.h=+t,this.s=+e,this.l=+r,this.opacity=+n}e(et,tt,r(n,{brighter:function(t){return t=null==t?1/.7:Math.pow(1/.7,t),new et(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?.7:Math.pow(.7,t),new et(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=isNaN(this.h)?0:(this.h+120)*S,e=+this.l,r=isNaN(this.s)?0:this.s*e*(1-e),n=Math.cos(t),i=Math.sin(t);return new _(255*(e+r*(Y*n+W*i)),255*(e+r*(X*n+Z*i)),255*(e+r*($*n)),this.opacity)}})),t.color=v,t.rgb=b,t.hsl=A,t.lab=F,t.hcl=H,t.lch=function(t,e,r,n){return 1===arguments.length?q(t):new G(r,e,t,null==n?1:n)},t.gray=function(t,e){return new B(t,0,0,null==e?1:e)},t.cubehelix=tt,Object.defineProperty(t,"__esModule",{value:!0})}("object"==typeof r&&"undefined"!=typeof e?r:n.d3=n.d3||{})},{}],143:[function(t,e,r){var n;n=this,function(t){"use strict";var e={value:function(){}};function r(){for(var t,e=0,r=arguments.length,i={};e<r;++e){if(!(t=arguments[e]+"")||t in i)throw new Error("illegal type: "+t);i[t]=[]}return new n(i)}function n(t){this._=t}function i(t,e){for(var r,n=0,i=t.length;n<i;++n)if((r=t[n]).name===e)return r.value}function a(t,r,n){for(var i=0,a=t.length;i<a;++i)if(t[i].name===r){t[i]=e,t=t.slice(0,i).concat(t.slice(i+1));break}return null!=n&&t.push({name:r,value:n}),t}n.prototype=r.prototype={constructor:n,on:function(t,e){var r,n,o=this._,s=(n=o,(t+"").trim().split(/^|\s+/).map(function(t){var e="",r=t.indexOf(".");if(r>=0&&(e=t.slice(r+1),t=t.slice(0,r)),t&&!n.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:e}})),l=-1,c=s.length;if(!(arguments.length<2)){if(null!=e&&"function"!=typeof e)throw new Error("invalid callback: "+e);for(;++l<c;)if(r=(t=s[l]).type)o[r]=a(o[r],t.name,e);else if(null==e)for(r in o)o[r]=a(o[r],t.name,null);return this}for(;++l<c;)if((r=(t=s[l]).type)&&(r=i(o[r],t.name)))return r},copy:function(){var t={},e=this._;for(var r in e)t[r]=e[r].slice();return new n(t)},call:function(t,e){if((r=arguments.length-2)>0)for(var r,n,i=new Array(r),a=0;a<r;++a)i[a]=arguments[a+2];if(!this._.hasOwnProperty(t))throw new Error("unknown type: "+t);for(a=0,r=(n=this._[t]).length;a<r;++a)n[a].value.apply(e,i)},apply:function(t,e,r){if(!this._.hasOwnProperty(t))throw new Error("unknown type: "+t);for(var n=this._[t],i=0,a=n.length;i<a;++i)n[i].value.apply(e,r)}},t.dispatch=r,Object.defineProperty(t,"__esModule",{value:!0})}("object"==typeof r&&"undefined"!=typeof e?r:n.d3=n.d3||{})},{}],144:[function(t,e,r){var n,i;n=this,i=function(t,e,r,n,i){"use strict";var a=function(t){return function(){return t}},o=function(){return 1e-6*(Math.random()-.5)};function s(t){return t.x+t.vx}function l(t){return t.y+t.vy}function c(t){return t.index}function u(t,e){var r=t.get(e);if(!r)throw new Error("missing: "+e);return r}function h(t){return t.x}function f(t){return t.y}var p=10,d=Math.PI*(3-Math.sqrt(5));t.forceCenter=function(t,e){var r;function n(){var n,i,a=r.length,o=0,s=0;for(n=0;n<a;++n)o+=(i=r[n]).x,s+=i.y;for(o=o/a-t,s=s/a-e,n=0;n<a;++n)(i=r[n]).x-=o,i.y-=s}return null==t&&(t=0),null==e&&(e=0),n.initialize=function(t){r=t},n.x=function(e){return arguments.length?(t=+e,n):t},n.y=function(t){return arguments.length?(e=+t,n):e},n},t.forceCollide=function(t){var r,n,i=1,c=1;function u(){for(var t,a,u,f,p,d,g,v=r.length,m=0;m<c;++m)for(a=e.quadtree(r,s,l).visitAfter(h),t=0;t<v;++t)u=r[t],d=n[u.index],g=d*d,f=u.x+u.vx,p=u.y+u.vy,a.visit(y);function y(t,e,r,n,a){var s=t.data,l=t.r,c=d+l;if(!s)return e>f+c||n<f-c||r>p+c||a<p-c;if(s.index>u.index){var h=f-s.x-s.vx,v=p-s.y-s.vy,m=h*h+v*v;m<c*c&&(0===h&&(m+=(h=o())*h),0===v&&(m+=(v=o())*v),m=(c-(m=Math.sqrt(m)))/m*i,u.vx+=(h*=m)*(c=(l*=l)/(g+l)),u.vy+=(v*=m)*c,s.vx-=h*(c=1-c),s.vy-=v*c)}}}function h(t){if(t.data)return t.r=n[t.data.index];for(var e=t.r=0;e<4;++e)t[e]&&t[e].r>t.r&&(t.r=t[e].r)}function f(){if(r){var e,i,a=r.length;for(n=new Array(a),e=0;e<a;++e)i=r[e],n[i.index]=+t(i,e,r)}}return"function"!=typeof t&&(t=a(null==t?1:+t)),u.initialize=function(t){r=t,f()},u.iterations=function(t){return arguments.length?(c=+t,u):c},u.strength=function(t){return arguments.length?(i=+t,u):i},u.radius=function(e){return arguments.length?(t="function"==typeof e?e:a(+e),f(),u):t},u},t.forceLink=function(t){var e,n,i,s,l,h=c,f=function(t){return 1/Math.min(s[t.source.index],s[t.target.index])},p=a(30),d=1;function g(r){for(var i=0,a=t.length;i<d;++i)for(var s,c,u,h,f,p,g,v=0;v<a;++v)c=(s=t[v]).source,h=(u=s.target).x+u.vx-c.x-c.vx||o(),f=u.y+u.vy-c.y-c.vy||o(),h*=p=((p=Math.sqrt(h*h+f*f))-n[v])/p*r*e[v],f*=p,u.vx-=h*(g=l[v]),u.vy-=f*g,c.vx+=h*(g=1-g),c.vy+=f*g}function v(){if(i){var a,o,c=i.length,f=t.length,p=r.map(i,h);for(a=0,s=new Array(c);a<f;++a)(o=t[a]).index=a,"object"!=typeof o.source&&(o.source=u(p,o.source)),"object"!=typeof o.target&&(o.target=u(p,o.target)),s[o.source.index]=(s[o.source.index]||0)+1,s[o.target.index]=(s[o.target.index]||0)+1;for(a=0,l=new Array(f);a<f;++a)o=t[a],l[a]=s[o.source.index]/(s[o.source.index]+s[o.target.index]);e=new Array(f),m(),n=new Array(f),y()}}function m(){if(i)for(var r=0,n=t.length;r<n;++r)e[r]=+f(t[r],r,t)}function y(){if(i)for(var e=0,r=t.length;e<r;++e)n[e]=+p(t[e],e,t)}return null==t&&(t=[]),g.initialize=function(t){i=t,v()},g.links=function(e){return arguments.length?(t=e,v(),g):t},g.id=function(t){return arguments.length?(h=t,g):h},g.iterations=function(t){return arguments.length?(d=+t,g):d},g.strength=function(t){return arguments.length?(f="function"==typeof t?t:a(+t),m(),g):f},g.distance=function(t){return arguments.length?(p="function"==typeof t?t:a(+t),y(),g):p},g},t.forceManyBody=function(){var t,r,n,i,s=a(-30),l=1,c=1/0,u=.81;function p(i){var a,o=t.length,s=e.quadtree(t,h,f).visitAfter(g);for(n=i,a=0;a<o;++a)r=t[a],s.visit(v)}function d(){if(t){var e,r,n=t.length;for(i=new Array(n),e=0;e<n;++e)r=t[e],i[r.index]=+s(r,e,t)}}function g(t){var e,r,n,a,o,s=0,l=0;if(t.length){for(n=a=o=0;o<4;++o)(e=t[o])&&(r=Math.abs(e.value))&&(s+=e.value,l+=r,n+=r*e.x,a+=r*e.y);t.x=n/l,t.y=a/l}else{(e=t).x=e.data.x,e.y=e.data.y;do{s+=i[e.data.index]}while(e=e.next)}t.value=s}function v(t,e,a,s){if(!t.value)return!0;var h=t.x-r.x,f=t.y-r.y,p=s-e,d=h*h+f*f;if(p*p/u<d)return d<c&&(0===h&&(d+=(h=o())*h),0===f&&(d+=(f=o())*f),d<l&&(d=Math.sqrt(l*d)),r.vx+=h*t.value*n/d,r.vy+=f*t.value*n/d),!0;if(!(t.length||d>=c)){(t.data!==r||t.next)&&(0===h&&(d+=(h=o())*h),0===f&&(d+=(f=o())*f),d<l&&(d=Math.sqrt(l*d)));do{t.data!==r&&(p=i[t.data.index]*n/d,r.vx+=h*p,r.vy+=f*p)}while(t=t.next)}}return p.initialize=function(e){t=e,d()},p.strength=function(t){return arguments.length?(s="function"==typeof t?t:a(+t),d(),p):s},p.distanceMin=function(t){return arguments.length?(l=t*t,p):Math.sqrt(l)},p.distanceMax=function(t){return arguments.length?(c=t*t,p):Math.sqrt(c)},p.theta=function(t){return arguments.length?(u=t*t,p):Math.sqrt(u)},p},t.forceRadial=function(t,e,r){var n,i,o,s=a(.1);function l(t){for(var a=0,s=n.length;a<s;++a){var l=n[a],c=l.x-e||1e-6,u=l.y-r||1e-6,h=Math.sqrt(c*c+u*u),f=(o[a]-h)*i[a]*t/h;l.vx+=c*f,l.vy+=u*f}}function c(){if(n){var e,r=n.length;for(i=new Array(r),o=new Array(r),e=0;e<r;++e)o[e]=+t(n[e],e,n),i[e]=isNaN(o[e])?0:+s(n[e],e,n)}}return"function"!=typeof t&&(t=a(+t)),null==e&&(e=0),null==r&&(r=0),l.initialize=function(t){n=t,c()},l.strength=function(t){return arguments.length?(s="function"==typeof t?t:a(+t),c(),l):s},l.radius=function(e){return arguments.length?(t="function"==typeof e?e:a(+e),c(),l):t},l.x=function(t){return arguments.length?(e=+t,l):e},l.y=function(t){return arguments.length?(r=+t,l):r},l},t.forceSimulation=function(t){var e,a=1,o=.001,s=1-Math.pow(o,1/300),l=0,c=.6,u=r.map(),h=i.timer(g),f=n.dispatch("tick","end");function g(){v(),f.call("tick",e),a<o&&(h.stop(),f.call("end",e))}function v(){var e,r,n=t.length;for(a+=(l-a)*s,u.each(function(t){t(a)}),e=0;e<n;++e)null==(r=t[e]).fx?r.x+=r.vx*=c:(r.x=r.fx,r.vx=0),null==r.fy?r.y+=r.vy*=c:(r.y=r.fy,r.vy=0)}function m(){for(var e,r=0,n=t.length;r<n;++r){if((e=t[r]).index=r,isNaN(e.x)||isNaN(e.y)){var i=p*Math.sqrt(r),a=r*d;e.x=i*Math.cos(a),e.y=i*Math.sin(a)}(isNaN(e.vx)||isNaN(e.vy))&&(e.vx=e.vy=0)}}function y(e){return e.initialize&&e.initialize(t),e}return null==t&&(t=[]),m(),e={tick:v,restart:function(){return h.restart(g),e},stop:function(){return h.stop(),e},nodes:function(r){return arguments.length?(t=r,m(),u.each(y),e):t},alpha:function(t){return arguments.length?(a=+t,e):a},alphaMin:function(t){return arguments.length?(o=+t,e):o},alphaDecay:function(t){return arguments.length?(s=+t,e):+s},alphaTarget:function(t){return arguments.length?(l=+t,e):l},velocityDecay:function(t){return arguments.length?(c=1-t,e):1-c},force:function(t,r){return arguments.length>1?(null==r?u.remove(t):u.set(t,y(r)),e):u.get(t)},find:function(e,r,n){var i,a,o,s,l,c=0,u=t.length;for(null==n?n=1/0:n*=n,c=0;c<u;++c)(o=(i=e-(s=t[c]).x)*i+(a=r-s.y)*a)<n&&(l=s,n=o);return l},on:function(t,r){return arguments.length>1?(f.on(t,r),e):f.on(t)}}},t.forceX=function(t){var e,r,n,i=a(.1);function o(t){for(var i,a=0,o=e.length;a<o;++a)(i=e[a]).vx+=(n[a]-i.x)*r[a]*t}function s(){if(e){var a,o=e.length;for(r=new Array(o),n=new Array(o),a=0;a<o;++a)r[a]=isNaN(n[a]=+t(e[a],a,e))?0:+i(e[a],a,e)}}return"function"!=typeof t&&(t=a(null==t?0:+t)),o.initialize=function(t){e=t,s()},o.strength=function(t){return arguments.length?(i="function"==typeof t?t:a(+t),s(),o):i},o.x=function(e){return arguments.length?(t="function"==typeof e?e:a(+e),s(),o):t},o},t.forceY=function(t){var e,r,n,i=a(.1);function o(t){for(var i,a=0,o=e.length;a<o;++a)(i=e[a]).vy+=(n[a]-i.y)*r[a]*t}function s(){if(e){var a,o=e.length;for(r=new Array(o),n=new Array(o),a=0;a<o;++a)r[a]=isNaN(n[a]=+t(e[a],a,e))?0:+i(e[a],a,e)}}return"function"!=typeof t&&(t=a(null==t?0:+t)),o.initialize=function(t){e=t,s()},o.strength=function(t){return arguments.length?(i="function"==typeof t?t:a(+t),s(),o):i},o.y=function(e){return arguments.length?(t="function"==typeof e?e:a(+e),s(),o):t},o},Object.defineProperty(t,"__esModule",{value:!0})},"object"==typeof r&&"undefined"!=typeof e?i(r,t("d3-quadtree"),t("d3-collection"),t("d3-dispatch"),t("d3-timer")):i(n.d3=n.d3||{},n.d3,n.d3,n.d3,n.d3)},{"d3-collection":141,"d3-dispatch":143,"d3-quadtree":147,"d3-timer":150}],145:[function(t,e,r){var n,i;n=this,i=function(t,e){"use strict";function r(t,e,r,n,i){var a=t*t,o=a*t;return((1-3*t+3*a-o)*e+(4-6*a+3*o)*r+(1+3*t+3*a-3*o)*n+o*i)/6}function n(t){var e=t.length-1;return function(n){var i=n<=0?n=0:n>=1?(n=1,e-1):Math.floor(n*e),a=t[i],o=t[i+1],s=i>0?t[i-1]:2*a-o,l=i<e-1?t[i+2]:2*o-a;return r((n-i/e)*e,s,a,o,l)}}function i(t){var e=t.length;return function(n){var i=Math.floor(((n%=1)<0?++n:n)*e),a=t[(i+e-1)%e],o=t[i%e],s=t[(i+1)%e],l=t[(i+2)%e];return r((n-i/e)*e,a,o,s,l)}}function a(t){return function(){return t}}function o(t,e){return function(r){return t+r*e}}function s(t,e){var r=e-t;return r?o(t,r>180||r<-180?r-360*Math.round(r/360):r):a(isNaN(t)?e:t)}function l(t){return 1==(t=+t)?c:function(e,r){return r-e?function(t,e,r){return t=Math.pow(t,r),e=Math.pow(e,r)-t,r=1/r,function(n){return Math.pow(t+n*e,r)}}(e,r,t):a(isNaN(e)?r:e)}}function c(t,e){var r=e-t;return r?o(t,r):a(isNaN(t)?e:t)}var u=function t(r){var n=l(r);function i(t,r){var i=n((t=e.rgb(t)).r,(r=e.rgb(r)).r),a=n(t.g,r.g),o=n(t.b,r.b),s=c(t.opacity,r.opacity);return function(e){return t.r=i(e),t.g=a(e),t.b=o(e),t.opacity=s(e),t+""}}return i.gamma=t,i}(1);function h(t){return function(r){var n,i,a=r.length,o=new Array(a),s=new Array(a),l=new Array(a);for(n=0;n<a;++n)i=e.rgb(r[n]),o[n]=i.r||0,s[n]=i.g||0,l[n]=i.b||0;return o=t(o),s=t(s),l=t(l),i.opacity=1,function(t){return i.r=o(t),i.g=s(t),i.b=l(t),i+""}}}var f=h(n),p=h(i);function d(t,e){var r,n=e?e.length:0,i=t?Math.min(n,t.length):0,a=new Array(i),o=new Array(n);for(r=0;r<i;++r)a[r]=_(t[r],e[r]);for(;r<n;++r)o[r]=e[r];return function(t){for(r=0;r<i;++r)o[r]=a[r](t);return o}}function g(t,e){var r=new Date;return e-=t=+t,function(n){return r.setTime(t+e*n),r}}function v(t,e){return e-=t=+t,function(r){return t+e*r}}function m(t,e){var r,n={},i={};for(r in null!==t&&"object"==typeof t||(t={}),null!==e&&"object"==typeof e||(e={}),e)r in t?n[r]=_(t[r],e[r]):i[r]=e[r];return function(t){for(r in n)i[r]=n[r](t);return i}}var y=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,x=new RegExp(y.source,"g");function b(t,e){var r,n,i,a=y.lastIndex=x.lastIndex=0,o=-1,s=[],l=[];for(t+="",e+="";(r=y.exec(t))&&(n=x.exec(e));)(i=n.index)>a&&(i=e.slice(a,i),s[o]?s[o]+=i:s[++o]=i),(r=r[0])===(n=n[0])?s[o]?s[o]+=n:s[++o]=n:(s[++o]=null,l.push({i:o,x:v(r,n)})),a=x.lastIndex;return a<e.length&&(i=e.slice(a),s[o]?s[o]+=i:s[++o]=i),s.length<2?l[0]?function(t){return function(e){return t(e)+""}}(l[0].x):function(t){return function(){return t}}(e):(e=l.length,function(t){for(var r,n=0;n<e;++n)s[(r=l[n]).i]=r.x(t);return s.join("")})}function _(t,r){var n,i=typeof r;return null==r||"boolean"===i?a(r):("number"===i?v:"string"===i?(n=e.color(r))?(r=n,u):b:r instanceof e.color?u:r instanceof Date?g:Array.isArray(r)?d:"function"!=typeof r.valueOf&&"function"!=typeof r.toString||isNaN(r)?m:v)(t,r)}var w,k,A,M,T=180/Math.PI,S={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function E(t,e,r,n,i,a){var o,s,l;return(o=Math.sqrt(t*t+e*e))&&(t/=o,e/=o),(l=t*r+e*n)&&(r-=t*l,n-=e*l),(s=Math.sqrt(r*r+n*n))&&(r/=s,n/=s,l/=s),t*n<e*r&&(t=-t,e=-e,l=-l,o=-o),{translateX:i,translateY:a,rotate:Math.atan2(e,t)*T,skewX:Math.atan(l)*T,scaleX:o,scaleY:s}}function C(t,e,r,n){function i(t){return t.length?t.pop()+" ":""}return function(a,o){var s=[],l=[];return a=t(a),o=t(o),function(t,n,i,a,o,s){if(t!==i||n!==a){var l=o.push("translate(",null,e,null,r);s.push({i:l-4,x:v(t,i)},{i:l-2,x:v(n,a)})}else(i||a)&&o.push("translate("+i+e+a+r)}(a.translateX,a.translateY,o.translateX,o.translateY,s,l),function(t,e,r,a){t!==e?(t-e>180?e+=360:e-t>180&&(t+=360),a.push({i:r.push(i(r)+"rotate(",null,n)-2,x:v(t,e)})):e&&r.push(i(r)+"rotate("+e+n)}(a.rotate,o.rotate,s,l),function(t,e,r,a){t!==e?a.push({i:r.push(i(r)+"skewX(",null,n)-2,x:v(t,e)}):e&&r.push(i(r)+"skewX("+e+n)}(a.skewX,o.skewX,s,l),function(t,e,r,n,a,o){if(t!==r||e!==n){var s=a.push(i(a)+"scale(",null,",",null,")");o.push({i:s-4,x:v(t,r)},{i:s-2,x:v(e,n)})}else 1===r&&1===n||a.push(i(a)+"scale("+r+","+n+")")}(a.scaleX,a.scaleY,o.scaleX,o.scaleY,s,l),a=o=null,function(t){for(var e,r=-1,n=l.length;++r<n;)s[(e=l[r]).i]=e.x(t);return s.join("")}}}var L=C(function(t){return"none"===t?S:(w||(w=document.createElement("DIV"),k=document.documentElement,A=document.defaultView),w.style.transform=t,t=A.getComputedStyle(k.appendChild(w),null).getPropertyValue("transform"),k.removeChild(w),E(+(t=t.slice(7,-1).split(","))[0],+t[1],+t[2],+t[3],+t[4],+t[5]))},"px, ","px)","deg)"),z=C(function(t){return null==t?S:(M||(M=document.createElementNS("http://www.w3.org/2000/svg","g")),M.setAttribute("transform",t),(t=M.transform.baseVal.consolidate())?E((t=t.matrix).a,t.b,t.c,t.d,t.e,t.f):S)},", ",")",")"),O=Math.SQRT2,I=2,D=4,P=1e-12;function R(t){return((t=Math.exp(t))+1/t)/2}function F(t){return function(r,n){var i=t((r=e.hsl(r)).h,(n=e.hsl(n)).h),a=c(r.s,n.s),o=c(r.l,n.l),s=c(r.opacity,n.opacity);return function(t){return r.h=i(t),r.s=a(t),r.l=o(t),r.opacity=s(t),r+""}}}var B=F(s),N=F(c);function j(t){return function(r,n){var i=t((r=e.hcl(r)).h,(n=e.hcl(n)).h),a=c(r.c,n.c),o=c(r.l,n.l),s=c(r.opacity,n.opacity);return function(t){return r.h=i(t),r.c=a(t),r.l=o(t),r.opacity=s(t),r+""}}}var V=j(s),U=j(c);function q(t){return function r(n){function i(r,i){var a=t((r=e.cubehelix(r)).h,(i=e.cubehelix(i)).h),o=c(r.s,i.s),s=c(r.l,i.l),l=c(r.opacity,i.opacity);return function(t){return r.h=a(t),r.s=o(t),r.l=s(Math.pow(t,n)),r.opacity=l(t),r+""}}return n=+n,i.gamma=r,i}(1)}var H=q(s),G=q(c);t.interpolate=_,t.interpolateArray=d,t.interpolateBasis=n,t.interpolateBasisClosed=i,t.interpolateDate=g,t.interpolateDiscrete=function(t){var e=t.length;return function(r){return t[Math.max(0,Math.min(e-1,Math.floor(r*e)))]}},t.interpolateHue=function(t,e){var r=s(+t,+e);return function(t){var e=r(t);return e-360*Math.floor(e/360)}},t.interpolateNumber=v,t.interpolateObject=m,t.interpolateRound=function(t,e){return e-=t=+t,function(r){return Math.round(t+e*r)}},t.interpolateString=b,t.interpolateTransformCss=L,t.interpolateTransformSvg=z,t.interpolateZoom=function(t,e){var r,n,i=t[0],a=t[1],o=t[2],s=e[0],l=e[1],c=e[2],u=s-i,h=l-a,f=u*u+h*h;if(f<P)n=Math.log(c/o)/O,r=function(t){return[i+t*u,a+t*h,o*Math.exp(O*t*n)]};else{var p=Math.sqrt(f),d=(c*c-o*o+D*f)/(2*o*I*p),g=(c*c-o*o-D*f)/(2*c*I*p),v=Math.log(Math.sqrt(d*d+1)-d),m=Math.log(Math.sqrt(g*g+1)-g);n=(m-v)/O,r=function(t){var e,r=t*n,s=R(v),l=o/(I*p)*(s*(e=O*r+v,((e=Math.exp(2*e))-1)/(e+1))-function(t){return((t=Math.exp(t))-1/t)/2}(v));return[i+l*u,a+l*h,o*s/R(O*r+v)]}}return r.duration=1e3*n,r},t.interpolateRgb=u,t.interpolateRgbBasis=f,t.interpolateRgbBasisClosed=p,t.interpolateHsl=B,t.interpolateHslLong=N,t.interpolateLab=function(t,r){var n=c((t=e.lab(t)).l,(r=e.lab(r)).l),i=c(t.a,r.a),a=c(t.b,r.b),o=c(t.opacity,r.opacity);return function(e){return t.l=n(e),t.a=i(e),t.b=a(e),t.opacity=o(e),t+""}},t.interpolateHcl=V,t.interpolateHclLong=U,t.interpolateCubehelix=H,t.interpolateCubehelixLong=G,t.piecewise=function(t,e){for(var r=0,n=e.length-1,i=e[0],a=new Array(n<0?0:n);r<n;)a[r]=t(i,i=e[++r]);return function(t){var e=Math.max(0,Math.min(n-1,Math.floor(t*=n)));return a[e](t-e)}},t.quantize=function(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t(n/(e-1));return r},Object.defineProperty(t,"__esModule",{value:!0})},"object"==typeof r&&"undefined"!=typeof e?i(r,t("d3-color")):i(n.d3=n.d3||{},n.d3)},{"d3-color":142}],146:[function(t,e,r){var n;n=this,function(t){"use strict";var e=Math.PI,r=2*e,n=r-1e-6;function i(){this._x0=this._y0=this._x1=this._y1=null,this._=""}function a(){return new i}i.prototype=a.prototype={constructor:i,moveTo:function(t,e){this._+="M"+(this._x0=this._x1=+t)+","+(this._y0=this._y1=+e)},closePath:function(){null!==this._x1&&(this._x1=this._x0,this._y1=this._y0,this._+="Z")},lineTo:function(t,e){this._+="L"+(this._x1=+t)+","+(this._y1=+e)},quadraticCurveTo:function(t,e,r,n){this._+="Q"+ +t+","+ +e+","+(this._x1=+r)+","+(this._y1=+n)},bezierCurveTo:function(t,e,r,n,i,a){this._+="C"+ +t+","+ +e+","+ +r+","+ +n+","+(this._x1=+i)+","+(this._y1=+a)},arcTo:function(t,r,n,i,a){t=+t,r=+r,n=+n,i=+i,a=+a;var o=this._x1,s=this._y1,l=n-t,c=i-r,u=o-t,h=s-r,f=u*u+h*h;if(a<0)throw new Error("negative radius: "+a);if(null===this._x1)this._+="M"+(this._x1=t)+","+(this._y1=r);else if(f>1e-6)if(Math.abs(h*l-c*u)>1e-6&&a){var p=n-o,d=i-s,g=l*l+c*c,v=p*p+d*d,m=Math.sqrt(g),y=Math.sqrt(f),x=a*Math.tan((e-Math.acos((g+f-v)/(2*m*y)))/2),b=x/y,_=x/m;Math.abs(b-1)>1e-6&&(this._+="L"+(t+b*u)+","+(r+b*h)),this._+="A"+a+","+a+",0,0,"+ +(h*p>u*d)+","+(this._x1=t+_*l)+","+(this._y1=r+_*c)}else this._+="L"+(this._x1=t)+","+(this._y1=r);else;},arc:function(t,i,a,o,s,l){t=+t,i=+i;var c=(a=+a)*Math.cos(o),u=a*Math.sin(o),h=t+c,f=i+u,p=1^l,d=l?o-s:s-o;if(a<0)throw new Error("negative radius: "+a);null===this._x1?this._+="M"+h+","+f:(Math.abs(this._x1-h)>1e-6||Math.abs(this._y1-f)>1e-6)&&(this._+="L"+h+","+f),a&&(d<0&&(d=d%r+r),d>n?this._+="A"+a+","+a+",0,1,"+p+","+(t-c)+","+(i-u)+"A"+a+","+a+",0,1,"+p+","+(this._x1=h)+","+(this._y1=f):d>1e-6&&(this._+="A"+a+","+a+",0,"+ +(d>=e)+","+p+","+(this._x1=t+a*Math.cos(s))+","+(this._y1=i+a*Math.sin(s))))},rect:function(t,e,r,n){this._+="M"+(this._x0=this._x1=+t)+","+(this._y0=this._y1=+e)+"h"+ +r+"v"+ +n+"h"+-r+"Z"},toString:function(){return this._}},t.path=a,Object.defineProperty(t,"__esModule",{value:!0})}("object"==typeof r&&"undefined"!=typeof e?r:n.d3=n.d3||{})},{}],147:[function(t,e,r){var n;n=this,function(t){"use strict";function e(t,e,r,n){if(isNaN(e)||isNaN(r))return t;var i,a,o,s,l,c,u,h,f,p=t._root,d={data:n},g=t._x0,v=t._y0,m=t._x1,y=t._y1;if(!p)return t._root=d,t;for(;p.length;)if((c=e>=(a=(g+m)/2))?g=a:m=a,(u=r>=(o=(v+y)/2))?v=o:y=o,i=p,!(p=p[h=u<<1|c]))return i[h]=d,t;if(s=+t._x.call(null,p.data),l=+t._y.call(null,p.data),e===s&&r===l)return d.next=p,i?i[h]=d:t._root=d,t;do{i=i?i[h]=new Array(4):t._root=new Array(4),(c=e>=(a=(g+m)/2))?g=a:m=a,(u=r>=(o=(v+y)/2))?v=o:y=o}while((h=u<<1|c)==(f=(l>=o)<<1|s>=a));return i[f]=p,i[h]=d,t}var r=function(t,e,r,n,i){this.node=t,this.x0=e,this.y0=r,this.x1=n,this.y1=i};function n(t){return t[0]}function i(t){return t[1]}function a(t,e,r){var a=new o(null==e?n:e,null==r?i:r,NaN,NaN,NaN,NaN);return null==t?a:a.addAll(t)}function o(t,e,r,n,i,a){this._x=t,this._y=e,this._x0=r,this._y0=n,this._x1=i,this._y1=a,this._root=void 0}function s(t){for(var e={data:t.data},r=e;t=t.next;)r=r.next={data:t.data};return e}var l=a.prototype=o.prototype;l.copy=function(){var t,e,r=new o(this._x,this._y,this._x0,this._y0,this._x1,this._y1),n=this._root;if(!n)return r;if(!n.length)return r._root=s(n),r;for(t=[{source:n,target:r._root=new Array(4)}];n=t.pop();)for(var i=0;i<4;++i)(e=n.source[i])&&(e.length?t.push({source:e,target:n.target[i]=new Array(4)}):n.target[i]=s(e));return r},l.add=function(t){var r=+this._x.call(null,t),n=+this._y.call(null,t);return e(this.cover(r,n),r,n,t)},l.addAll=function(t){var r,n,i,a,o=t.length,s=new Array(o),l=new Array(o),c=1/0,u=1/0,h=-1/0,f=-1/0;for(n=0;n<o;++n)isNaN(i=+this._x.call(null,r=t[n]))||isNaN(a=+this._y.call(null,r))||(s[n]=i,l[n]=a,i<c&&(c=i),i>h&&(h=i),a<u&&(u=a),a>f&&(f=a));for(h<c&&(c=this._x0,h=this._x1),f<u&&(u=this._y0,f=this._y1),this.cover(c,u).cover(h,f),n=0;n<o;++n)e(this,s[n],l[n],t[n]);return this},l.cover=function(t,e){if(isNaN(t=+t)||isNaN(e=+e))return this;var r=this._x0,n=this._y0,i=this._x1,a=this._y1;if(isNaN(r))i=(r=Math.floor(t))+1,a=(n=Math.floor(e))+1;else{if(!(r>t||t>i||n>e||e>a))return this;var o,s,l=i-r,c=this._root;switch(s=(e<(n+a)/2)<<1|t<(r+i)/2){case 0:do{(o=new Array(4))[s]=c,c=o}while(a=n+(l*=2),t>(i=r+l)||e>a);break;case 1:do{(o=new Array(4))[s]=c,c=o}while(a=n+(l*=2),(r=i-l)>t||e>a);break;case 2:do{(o=new Array(4))[s]=c,c=o}while(n=a-(l*=2),t>(i=r+l)||n>e);break;case 3:do{(o=new Array(4))[s]=c,c=o}while(n=a-(l*=2),(r=i-l)>t||n>e)}this._root&&this._root.length&&(this._root=c)}return this._x0=r,this._y0=n,this._x1=i,this._y1=a,this},l.data=function(){var t=[];return this.visit(function(e){if(!e.length)do{t.push(e.data)}while(e=e.next)}),t},l.extent=function(t){return arguments.length?this.cover(+t[0][0],+t[0][1]).cover(+t[1][0],+t[1][1]):isNaN(this._x0)?void 0:[[this._x0,this._y0],[this._x1,this._y1]]},l.find=function(t,e,n){var i,a,o,s,l,c,u,h=this._x0,f=this._y0,p=this._x1,d=this._y1,g=[],v=this._root;for(v&&g.push(new r(v,h,f,p,d)),null==n?n=1/0:(h=t-n,f=e-n,p=t+n,d=e+n,n*=n);c=g.pop();)if(!(!(v=c.node)||(a=c.x0)>p||(o=c.y0)>d||(s=c.x1)<h||(l=c.y1)<f))if(v.length){var m=(a+s)/2,y=(o+l)/2;g.push(new r(v[3],m,y,s,l),new r(v[2],a,y,m,l),new r(v[1],m,o,s,y),new r(v[0],a,o,m,y)),(u=(e>=y)<<1|t>=m)&&(c=g[g.length-1],g[g.length-1]=g[g.length-1-u],g[g.length-1-u]=c)}else{var x=t-+this._x.call(null,v.data),b=e-+this._y.call(null,v.data),_=x*x+b*b;if(_<n){var w=Math.sqrt(n=_);h=t-w,f=e-w,p=t+w,d=e+w,i=v.data}}return i},l.remove=function(t){if(isNaN(a=+this._x.call(null,t))||isNaN(o=+this._y.call(null,t)))return this;var e,r,n,i,a,o,s,l,c,u,h,f,p=this._root,d=this._x0,g=this._y0,v=this._x1,m=this._y1;if(!p)return this;if(p.length)for(;;){if((c=a>=(s=(d+v)/2))?d=s:v=s,(u=o>=(l=(g+m)/2))?g=l:m=l,e=p,!(p=p[h=u<<1|c]))return this;if(!p.length)break;(e[h+1&3]||e[h+2&3]||e[h+3&3])&&(r=e,f=h)}for(;p.data!==t;)if(n=p,!(p=p.next))return this;return(i=p.next)&&delete p.next,n?(i?n.next=i:delete n.next,this):e?(i?e[h]=i:delete e[h],(p=e[0]||e[1]||e[2]||e[3])&&p===(e[3]||e[2]||e[1]||e[0])&&!p.length&&(r?r[f]=p:this._root=p),this):(this._root=i,this)},l.removeAll=function(t){for(var e=0,r=t.length;e<r;++e)this.remove(t[e]);return this},l.root=function(){return this._root},l.size=function(){var t=0;return this.visit(function(e){if(!e.length)do{++t}while(e=e.next)}),t},l.visit=function(t){var e,n,i,a,o,s,l=[],c=this._root;for(c&&l.push(new r(c,this._x0,this._y0,this._x1,this._y1));e=l.pop();)if(!t(c=e.node,i=e.x0,a=e.y0,o=e.x1,s=e.y1)&&c.length){var u=(i+o)/2,h=(a+s)/2;(n=c[3])&&l.push(new r(n,u,h,o,s)),(n=c[2])&&l.push(new r(n,i,h,u,s)),(n=c[1])&&l.push(new r(n,u,a,o,h)),(n=c[0])&&l.push(new r(n,i,a,u,h))}return this},l.visitAfter=function(t){var e,n=[],i=[];for(this._root&&n.push(new r(this._root,this._x0,this._y0,this._x1,this._y1));e=n.pop();){var a=e.node;if(a.length){var o,s=e.x0,l=e.y0,c=e.x1,u=e.y1,h=(s+c)/2,f=(l+u)/2;(o=a[0])&&n.push(new r(o,s,l,h,f)),(o=a[1])&&n.push(new r(o,h,l,c,f)),(o=a[2])&&n.push(new r(o,s,f,h,u)),(o=a[3])&&n.push(new r(o,h,f,c,u))}i.push(e)}for(;e=i.pop();)t(e.node,e.x0,e.y0,e.x1,e.y1);return this},l.x=function(t){return arguments.length?(this._x=t,this):this._x},l.y=function(t){return arguments.length?(this._y=t,this):this._y},t.quadtree=a,Object.defineProperty(t,"__esModule",{value:!0})}("object"==typeof r&&"undefined"!=typeof e?r:n.d3=n.d3||{})},{}],148:[function(t,e,r){var n,i;n=this,i=function(t,e,r,n,i){"use strict";function a(t){return t.target.depth}function o(t,e){return t.sourceLinks.length?t.depth:e-1}function s(t){return function(){return t}}i=i&&i.hasOwnProperty("default")?i.default:i;var l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};function c(t,e){return h(t.source,e.source)||t.index-e.index}function u(t,e){return h(t.target,e.target)||t.index-e.index}function h(t,e){return t.partOfCycle===e.partOfCycle?t.y0-e.y0:"top"===t.circularLinkType||"bottom"===e.circularLinkType?-1:1}function f(t){return t.value}function p(t){return(t.y0+t.y1)/2}function d(t){return p(t.source)}function g(t){return p(t.target)}function v(t){return t.index}function m(t){return t.nodes}function y(t){return t.links}function x(t,e){var r=t.get(e);if(!r)throw new Error("missing: "+e);return r}function b(t,e){return e(t)}var _=25,w=10,k=.3;function A(t,e){var r=0,n=0;t.links.forEach(function(i){i.circular&&(i.source.circularLinkType||i.target.circularLinkType?i.circularLinkType=i.source.circularLinkType?i.source.circularLinkType:i.target.circularLinkType:i.circularLinkType=r<n?"top":"bottom","top"==i.circularLinkType?r+=1:n+=1,t.nodes.forEach(function(t){b(t,e)!=b(i.source,e)&&b(t,e)!=b(i.target,e)||(t.circularLinkType=i.circularLinkType)}))}),t.links.forEach(function(t){t.circular&&(t.source.circularLinkType==t.target.circularLinkType&&(t.circularLinkType=t.source.circularLinkType),Y(t,e)&&(t.circularLinkType=t.source.circularLinkType))})}function M(t){var e=Math.abs(t.y1-t.y0),r=Math.abs(t.target.x0-t.source.x1);return Math.atan(r/e)}function T(t,e){var r=0;t.sourceLinks.forEach(function(t){r=t.circular&&!Y(t,e)?r+1:r});var n=0;return t.targetLinks.forEach(function(t){n=t.circular&&!Y(t,e)?n+1:n}),r+n}function S(t){var e=t.source.sourceLinks,r=0;e.forEach(function(t){r=t.circular?r+1:r});var n=t.target.targetLinks,i=0;return n.forEach(function(t){i=t.circular?i+1:i}),!(r>1||i>1)}function E(t,e,r){return t.sort(L),t.forEach(function(n,i){var a,o,s=0;if(Y(n,r)&&S(n))n.circularPathData.verticalBuffer=s+n.width/2;else{for(var l=0;l<i;l++)if(a=t[i],o=t[l],!(a.source.column<o.target.column||a.target.column>o.source.column)){var c=t[l].circularPathData.verticalBuffer+t[l].width/2+e;s=c>s?c:s}n.circularPathData.verticalBuffer=s+n.width/2}}),t}function C(t,r,i,a){var o=e.min(t.links,function(t){return t.source.y0});t.links.forEach(function(t){t.circular&&(t.circularPathData={})}),E(t.links.filter(function(t){return"top"==t.circularLinkType}),r,a),E(t.links.filter(function(t){return"bottom"==t.circularLinkType}),r,a),t.links.forEach(function(e){if(e.circular){if(e.circularPathData.arcRadius=e.width+w,e.circularPathData.leftNodeBuffer=5,e.circularPathData.rightNodeBuffer=5,e.circularPathData.sourceWidth=e.source.x1-e.source.x0,e.circularPathData.sourceX=e.source.x0+e.circularPathData.sourceWidth,e.circularPathData.targetX=e.target.x0,e.circularPathData.sourceY=e.y0,e.circularPathData.targetY=e.y1,Y(e,a)&&S(e))e.circularPathData.leftSmallArcRadius=w+e.width/2,e.circularPathData.leftLargeArcRadius=w+e.width/2,e.circularPathData.rightSmallArcRadius=w+e.width/2,e.circularPathData.rightLargeArcRadius=w+e.width/2,"bottom"==e.circularLinkType?(e.circularPathData.verticalFullExtent=e.source.y1+_+e.circularPathData.verticalBuffer,e.circularPathData.verticalLeftInnerExtent=e.circularPathData.verticalFullExtent-e.circularPathData.leftLargeArcRadius,e.circularPathData.verticalRightInnerExtent=e.circularPathData.verticalFullExtent-e.circularPathData.rightLargeArcRadius):(e.circularPathData.verticalFullExtent=e.source.y0-_-e.circularPathData.verticalBuffer,e.circularPathData.verticalLeftInnerExtent=e.circularPathData.verticalFullExtent+e.circularPathData.leftLargeArcRadius,e.circularPathData.verticalRightInnerExtent=e.circularPathData.verticalFullExtent+e.circularPathData.rightLargeArcRadius);else{var s=e.source.column,l=e.circularLinkType,c=t.links.filter(function(t){return t.source.column==s&&t.circularLinkType==l});"bottom"==e.circularLinkType?c.sort(O):c.sort(z);var u=0;c.forEach(function(t,n){t.circularLinkID==e.circularLinkID&&(e.circularPathData.leftSmallArcRadius=w+e.width/2+u,e.circularPathData.leftLargeArcRadius=w+e.width/2+n*r+u),u+=t.width}),s=e.target.column,c=t.links.filter(function(t){return t.target.column==s&&t.circularLinkType==l}),"bottom"==e.circularLinkType?c.sort(D):c.sort(I),u=0,c.forEach(function(t,n){t.circularLinkID==e.circularLinkID&&(e.circularPathData.rightSmallArcRadius=w+e.width/2+u,e.circularPathData.rightLargeArcRadius=w+e.width/2+n*r+u),u+=t.width}),"bottom"==e.circularLinkType?(e.circularPathData.verticalFullExtent=Math.max(i,e.source.y1,e.target.y1)+_+e.circularPathData.verticalBuffer,e.circularPathData.verticalLeftInnerExtent=e.circularPathData.verticalFullExtent-e.circularPathData.leftLargeArcRadius,e.circularPathData.verticalRightInnerExtent=e.circularPathData.verticalFullExtent-e.circularPathData.rightLargeArcRadius):(e.circularPathData.verticalFullExtent=o-_-e.circularPathData.verticalBuffer,e.circularPathData.verticalLeftInnerExtent=e.circularPathData.verticalFullExtent+e.circularPathData.leftLargeArcRadius,e.circularPathData.verticalRightInnerExtent=e.circularPathData.verticalFullExtent+e.circularPathData.rightLargeArcRadius)}e.circularPathData.leftInnerExtent=e.circularPathData.sourceX+e.circularPathData.leftNodeBuffer,e.circularPathData.rightInnerExtent=e.circularPathData.targetX-e.circularPathData.rightNodeBuffer,e.circularPathData.leftFullExtent=e.circularPathData.sourceX+e.circularPathData.leftLargeArcRadius+e.circularPathData.leftNodeBuffer,e.circularPathData.rightFullExtent=e.circularPathData.targetX-e.circularPathData.rightLargeArcRadius-e.circularPathData.rightNodeBuffer}if(e.circular)e.path=function(t){var e="";e="top"==t.circularLinkType?"M"+t.circularPathData.sourceX+" "+t.circularPathData.sourceY+" L"+t.circularPathData.leftInnerExtent+" "+t.circularPathData.sourceY+" A"+t.circularPathData.leftLargeArcRadius+" "+t.circularPathData.leftSmallArcRadius+" 0 0 0 "+t.circularPathData.leftFullExtent+" "+(t.circularPathData.sourceY-t.circularPathData.leftSmallArcRadius)+" L"+t.circularPathData.leftFullExtent+" "+t.circularPathData.verticalLeftInnerExtent+" A"+t.circularPathData.leftLargeArcRadius+" "+t.circularPathData.leftLargeArcRadius+" 0 0 0 "+t.circularPathData.leftInnerExtent+" "+t.circularPathData.verticalFullExtent+" L"+t.circularPathData.rightInnerExtent+" "+t.circularPathData.verticalFullExtent+" A"+t.circularPathData.rightLargeArcRadius+" "+t.circularPathData.rightLargeArcRadius+" 0 0 0 "+t.circularPathData.rightFullExtent+" "+t.circularPathData.verticalRightInnerExtent+" L"+t.circularPathData.rightFullExtent+" "+(t.circularPathData.targetY-t.circularPathData.rightSmallArcRadius)+" A"+t.circularPathData.rightLargeArcRadius+" "+t.circularPathData.rightSmallArcRadius+" 0 0 0 "+t.circularPathData.rightInnerExtent+" "+t.circularPathData.targetY+" L"+t.circularPathData.targetX+" "+t.circularPathData.targetY:"M"+t.circularPathData.sourceX+" "+t.circularPathData.sourceY+" L"+t.circularPathData.leftInnerExtent+" "+t.circularPathData.sourceY+" A"+t.circularPathData.leftLargeArcRadius+" "+t.circularPathData.leftSmallArcRadius+" 0 0 1 "+t.circularPathData.leftFullExtent+" "+(t.circularPathData.sourceY+t.circularPathData.leftSmallArcRadius)+" L"+t.circularPathData.leftFullExtent+" "+t.circularPathData.verticalLeftInnerExtent+" A"+t.circularPathData.leftLargeArcRadius+" "+t.circularPathData.leftLargeArcRadius+" 0 0 1 "+t.circularPathData.leftInnerExtent+" "+t.circularPathData.verticalFullExtent+" L"+t.circularPathData.rightInnerExtent+" "+t.circularPathData.verticalFullExtent+" A"+t.circularPathData.rightLargeArcRadius+" "+t.circularPathData.rightLargeArcRadius+" 0 0 1 "+t.circularPathData.rightFullExtent+" "+t.circularPathData.verticalRightInnerExtent+" L"+t.circularPathData.rightFullExtent+" "+(t.circularPathData.targetY+t.circularPathData.rightSmallArcRadius)+" A"+t.circularPathData.rightLargeArcRadius+" "+t.circularPathData.rightSmallArcRadius+" 0 0 1 "+t.circularPathData.rightInnerExtent+" "+t.circularPathData.targetY+" L"+t.circularPathData.targetX+" "+t.circularPathData.targetY;return e}(e);else{var h=n.linkHorizontal().source(function(t){return[t.source.x0+(t.source.x1-t.source.x0),t.y0]}).target(function(t){return[t.target.x0,t.y1]});e.path=h(e)}})}function L(t,e){return P(t)==P(e)?"bottom"==t.circularLinkType?O(t,e):z(t,e):P(e)-P(t)}function z(t,e){return t.y0-e.y0}function O(t,e){return e.y0-t.y0}function I(t,e){return t.y1-e.y1}function D(t,e){return e.y1-t.y1}function P(t){return t.target.column-t.source.column}function R(t){return t.target.x0-t.source.x1}function F(t,e){var r=M(t),n=R(e)/Math.tan(r);return"up"==G(t)?t.y1+n:t.y1-n}function B(t,e){var r=M(t),n=R(e)/Math.tan(r);return"up"==G(t)?t.y1-n:t.y1+n}function N(t,e,r,n){t.links.forEach(function(i){if(!i.circular&&i.target.column-i.source.column>1){var a=i.source.column+1,o=i.target.column-1,s=1,l=o-a+1;for(s=1;a<=o;a++,s++)t.nodes.forEach(function(o){if(o.column==a){var c,u=s/(l+1),h=Math.pow(1-u,3),f=3*u*Math.pow(1-u,2),p=3*Math.pow(u,2)*(1-u),d=Math.pow(u,3),g=h*i.y0+f*i.y0+p*i.y1+d*i.y1,v=g-i.width/2,m=g+i.width/2;v>o.y0&&v<o.y1?(c=o.y1-v+10,c="bottom"==o.circularLinkType?c:-c,o=V(o,c,e,r),t.nodes.forEach(function(t){b(t,n)!=b(o,n)&&t.column==o.column&&j(o,t)&&V(t,c,e,r)})):m>o.y0&&m<o.y1?(c=m-o.y0+10,o=V(o,c,e,r),t.nodes.forEach(function(t){b(t,n)!=b(o,n)&&t.column==o.column&&t.y0<o.y1&&t.y1>o.y1&&V(t,c,e,r)})):v<o.y0&&m>o.y1&&(c=m-o.y0+10,o=V(o,c,e,r),t.nodes.forEach(function(t){b(t,n)!=b(o,n)&&t.column==o.column&&t.y0<o.y1&&t.y1>o.y1&&V(t,c,e,r)}))}})}})}function j(t,e){return t.y0>e.y0&&t.y0<e.y1||(t.y1>e.y0&&t.y1<e.y1||t.y0<e.y0&&t.y1>e.y1)}function V(t,e,r,n){return t.y0+e>=r&&t.y1+e<=n&&(t.y0=t.y0+e,t.y1=t.y1+e,t.targetLinks.forEach(function(t){t.y1=t.y1+e}),t.sourceLinks.forEach(function(t){t.y0=t.y0+e})),t}function U(t,e,r,n){t.nodes.forEach(function(i){n&&i.y+(i.y1-i.y0)>e&&(i.y=i.y-(i.y+(i.y1-i.y0)-e));var a=t.links.filter(function(t){return b(t.source,r)==b(i,r)}),o=a.length;o>1&&a.sort(function(t,e){if(!t.circular&&!e.circular){if(t.target.column==e.target.column)return t.y1-e.y1;if(!H(t,e))return t.y1-e.y1;if(t.target.column>e.target.column){var r=B(e,t);return t.y1-r}if(e.target.column>t.target.column)return B(t,e)-e.y1}return t.circular&&!e.circular?"top"==t.circularLinkType?-1:1:e.circular&&!t.circular?"top"==e.circularLinkType?1:-1:t.circular&&e.circular?t.circularLinkType===e.circularLinkType&&"top"==t.circularLinkType?t.target.column===e.target.column?t.target.y1-e.target.y1:e.target.column-t.target.column:t.circularLinkType===e.circularLinkType&&"bottom"==t.circularLinkType?t.target.column===e.target.column?e.target.y1-t.target.y1:t.target.column-e.target.column:"top"==t.circularLinkType?-1:1:void 0});var s=i.y0;a.forEach(function(t){t.y0=s+t.width/2,s+=t.width}),a.forEach(function(t,e){if("bottom"==t.circularLinkType){for(var r=e+1,n=0;r<o;r++)n+=a[r].width;t.y0=i.y1-n-t.width/2}})})}function q(t,e,r){t.nodes.forEach(function(e){var n=t.links.filter(function(t){return b(t.target,r)==b(e,r)}),i=n.length;i>1&&n.sort(function(t,e){if(!t.circular&&!e.circular){if(t.source.column==e.source.column)return t.y0-e.y0;if(!H(t,e))return t.y0-e.y0;if(e.source.column<t.source.column){var r=F(e,t);return t.y0-r}if(t.source.column<e.source.column)return F(t,e)-e.y0}return t.circular&&!e.circular?"top"==t.circularLinkType?-1:1:e.circular&&!t.circular?"top"==e.circularLinkType?1:-1:t.circular&&e.circular?t.circularLinkType===e.circularLinkType&&"top"==t.circularLinkType?t.source.column===e.source.column?t.source.y1-e.source.y1:t.source.column-e.source.column:t.circularLinkType===e.circularLinkType&&"bottom"==t.circularLinkType?t.source.column===e.source.column?t.source.y1-e.source.y1:e.source.column-t.source.column:"top"==t.circularLinkType?-1:1:void 0});var a=e.y0;n.forEach(function(t){t.y1=a+t.width/2,a+=t.width}),n.forEach(function(t,r){if("bottom"==t.circularLinkType){for(var a=r+1,o=0;a<i;a++)o+=n[a].width;t.y1=e.y1-o-t.width/2}})})}function H(t,e){return G(t)==G(e)}function G(t){return t.y0-t.y1>0?"up":"down"}function Y(t,e){return b(t.source,e)==b(t.target,e)}t.sankeyCircular=function(){var t,n,a=0,b=0,M=1,S=1,E=24,L=v,z=o,O=m,I=y,D=32,P=2,R=null;function F(){var o={nodes:O.apply(null,arguments),links:I.apply(null,arguments)};!function(t){t.nodes.forEach(function(t,e){t.index=e,t.sourceLinks=[],t.targetLinks=[]});var e=r.map(t.nodes,L);t.links.forEach(function(t,r){t.index=r;var n=t.source,i=t.target;"object"!==("undefined"==typeof n?"undefined":l(n))&&(n=t.source=x(e,n)),"object"!==("undefined"==typeof i?"undefined":l(i))&&(i=t.target=x(e,i)),n.sourceLinks.push(t),i.targetLinks.push(t)})}(o),function(t,e,r){var n=0;if(null===r){for(var a=[],o=0;o<t.links.length;o++){var s=t.links[o],l=s.source.index,c=s.target.index;a[l]||(a[l]=[]),a[c]||(a[c]=[]),-1===a[l].indexOf(c)&&a[l].push(c)}var u=i(a);u.sort(function(t,e){return t.length-e.length});var h={};for(o=0;o<u.length;o++){for(var f=u[o],p=!1,d=0;d<f.length-1;d++)if(h[f[d]]||(h[f[d]]={}),h[f[d]]&&h[f[d]][f[d+1]]){p=!0;break}if(!p){var g=f.slice(-2);h[g[0]][g[1]]=!0}}t.links.forEach(function(t){var e=t.target.index,r=t.source.index;e===r||h[r]&&h[r][e]?(t.circular=!0,t.circularLinkID=n,n+=1):t.circular=!1})}else t.links.forEach(function(t){t.source[r]<t.target[r]?t.circular=!1:(t.circular=!0,t.circularLinkID=n,n+=1)})}(o,0,R),function(t){t.nodes.forEach(function(t){t.partOfCycle=!1,t.value=Math.max(e.sum(t.sourceLinks,f),e.sum(t.targetLinks,f)),t.sourceLinks.forEach(function(e){e.circular&&(t.partOfCycle=!0,t.circularLinkType=e.circularLinkType)}),t.targetLinks.forEach(function(e){e.circular&&(t.partOfCycle=!0,t.circularLinkType=e.circularLinkType)})})}(o),function(t){var e,r,n;for(e=t.nodes,r=[],n=0;e.length;++n,e=r,r=[])e.forEach(function(t){t.depth=n,t.sourceLinks.forEach(function(t){r.indexOf(t.target)<0&&!t.circular&&r.push(t.target)})});for(e=t.nodes,r=[],n=0;e.length;++n,e=r,r=[])e.forEach(function(t){t.height=n,t.targetLinks.forEach(function(t){r.indexOf(t.source)<0&&!t.circular&&r.push(t.source)})});t.nodes.forEach(function(t){t.column=Math.floor(z.call(null,t,n))})}(o),A(o,L),function(i,o,s){var l=r.nest().key(function(t){return t.column}).sortKeys(e.ascending).entries(i.nodes).map(function(t){return t.values});(function(r){if(n){var o=1/0;l.forEach(function(t){var e=S*n/(t.length+1);o=e<o?e:o}),t=o}var s=e.min(l,function(r){return(S-b-(r.length-1)*t)/e.sum(r,f)});s*=k,i.links.forEach(function(t){t.width=t.value*s});var c=function(t){var r=0,n=0,i=0,a=0,o=e.max(t.nodes,function(t){return t.column});return t.links.forEach(function(t){t.circular&&("top"==t.circularLinkType?r+=t.width:n+=t.width,0==t.target.column&&(a+=t.width),t.source.column==o&&(i+=t.width))}),{top:r=r>0?r+_+w:r,bottom:n=n>0?n+_+w:n,left:a=a>0?a+_+w:a,right:i=i>0?i+_+w:i}}(i),u=function(t,r){var n=e.max(t.nodes,function(t){return t.column}),i=M-a,o=S-b,s=i+r.right+r.left,l=o+r.top+r.bottom,c=i/s,u=o/l;return a=a*c+r.left,M=0==r.right?M:M*c,b=b*u+r.top,S*=u,t.nodes.forEach(function(t){t.x0=a+t.column*((M-a-E)/n),t.x1=t.x0+E}),u}(i,c);s*=u,i.links.forEach(function(t){t.width=t.value*s}),l.forEach(function(t){var e=t.length;t.forEach(function(t,n){t.depth==l.length-1&&1==e?(t.y0=S/2-t.value*s,t.y1=t.y0+t.value*s):0==t.depth&&1==e?(t.y0=S/2-t.value*s,t.y1=t.y0+t.value*s):t.partOfCycle?0==T(t,r)?(t.y0=S/2+n,t.y1=t.y0+t.value*s):"top"==t.circularLinkType?(t.y0=b+n,t.y1=t.y0+t.value*s):(t.y0=S-t.value*s-n,t.y1=t.y0+t.value*s):0==c.top||0==c.bottom?(t.y0=(S-b)/e*n,t.y1=t.y0+t.value*s):(t.y0=(S-b)/2-e/2+n,t.y1=t.y0+t.value*s)})})})(s),m();for(var c=1,u=o;u>0;--u)v(c*=.99,s),m();function v(t,r){var n=l.length;l.forEach(function(i){var a=i.length,o=i[0].depth;i.forEach(function(i){var s;if(i.sourceLinks.length||i.targetLinks.length)if(i.partOfCycle&&T(i,r)>0);else if(0==o&&1==a)s=i.y1-i.y0,i.y0=S/2-s/2,i.y1=S/2+s/2;else if(o==n-1&&1==a)s=i.y1-i.y0,i.y0=S/2-s/2,i.y1=S/2+s/2;else{var l=e.mean(i.sourceLinks,g),c=e.mean(i.targetLinks,d),u=((l&&c?(l+c)/2:l||c)-p(i))*t;i.y0+=u,i.y1+=u}})})}function m(){l.forEach(function(e){var r,n,i,a=b,o=e.length;for(e.sort(h),i=0;i<o;++i)r=e[i],(n=a-r.y0)>0&&(r.y0+=n,r.y1+=n),a=r.y1+t;if((n=a-t-S)>0)for(a=r.y0-=n,r.y1-=n,i=o-2;i>=0;--i)r=e[i],(n=r.y1+t-a)>0&&(r.y0-=n,r.y1-=n),a=r.y0})}}(o,D,L),B(o);for(var s=0;s<4;s++)U(o,S,L),q(o,0,L),N(o,b,S,L),U(o,S,L),q(o,0,L);return function(t,r,n){var i=t.nodes,a=t.links,o=!1,s=!1;if(a.forEach(function(t){"top"==t.circularLinkType?o=!0:"bottom"==t.circularLinkType&&(s=!0)}),0==o||0==s){var l=e.min(i,function(t){return t.y0}),c=e.max(i,function(t){return t.y1}),u=c-l,h=n-r,f=h/u;i.forEach(function(t){var e=(t.y1-t.y0)*f;t.y0=(t.y0-l)*f,t.y1=t.y0+e}),a.forEach(function(t){t.y0=(t.y0-l)*f,t.y1=(t.y1-l)*f,t.width=t.width*f})}}(o,b,S),C(o,P,S,L),o}function B(t){t.nodes.forEach(function(t){t.sourceLinks.sort(u),t.targetLinks.sort(c)}),t.nodes.forEach(function(t){var e=t.y0,r=e,n=t.y1,i=n;t.sourceLinks.forEach(function(t){t.circular?(t.y0=n-t.width/2,n-=t.width):(t.y0=e+t.width/2,e+=t.width)}),t.targetLinks.forEach(function(t){t.circular?(t.y1=i-t.width/2,i-=t.width):(t.y1=r+t.width/2,r+=t.width)})})}return F.nodeId=function(t){return arguments.length?(L="function"==typeof t?t:s(t),F):L},F.nodeAlign=function(t){return arguments.length?(z="function"==typeof t?t:s(t),F):z},F.nodeWidth=function(t){return arguments.length?(E=+t,F):E},F.nodePadding=function(e){return arguments.length?(t=+e,F):t},F.nodes=function(t){return arguments.length?(O="function"==typeof t?t:s(t),F):O},F.links=function(t){return arguments.length?(I="function"==typeof t?t:s(t),F):I},F.size=function(t){return arguments.length?(a=b=0,M=+t[0],S=+t[1],F):[M-a,S-b]},F.extent=function(t){return arguments.length?(a=+t[0][0],M=+t[1][0],b=+t[0][1],S=+t[1][1],F):[[a,b],[M,S]]},F.iterations=function(t){return arguments.length?(D=+t,F):D},F.circularLinkGap=function(t){return arguments.length?(P=+t,F):P},F.nodePaddingRatio=function(t){return arguments.length?(n=+t,F):n},F.sortNodes=function(t){return arguments.length?(R=t,F):R},F.update=function(t){return A(t,L),B(t),t.links.forEach(function(t){t.circular&&(t.circularLinkType=t.y0+t.y1<S?"top":"bottom",t.source.circularLinkType=t.circularLinkType,t.target.circularLinkType=t.circularLinkType)}),U(t,S,L,!1),q(t,0,L),C(t,P,S,L),t},F},t.sankeyCenter=function(t){return t.targetLinks.length?t.depth:t.sourceLinks.length?e.min(t.sourceLinks,a)-1:0},t.sankeyLeft=function(t){return t.depth},t.sankeyRight=function(t,e){return e-1-t.height},t.sankeyJustify=o,Object.defineProperty(t,"__esModule",{value:!0})},"object"==typeof r&&"undefined"!=typeof e?i(r,t("d3-array"),t("d3-collection"),t("d3-shape"),t("elementary-circuits-directed-graph")):i(n.d3=n.d3||{},n.d3,n.d3,n.d3,null)},{"d3-array":140,"d3-collection":141,"d3-shape":149,"elementary-circuits-directed-graph":161}],149:[function(t,e,r){var n,i;n=this,i=function(t,e){"use strict";function r(t){return function(){return t}}var n=Math.abs,i=Math.atan2,a=Math.cos,o=Math.max,s=Math.min,l=Math.sin,c=Math.sqrt,u=1e-12,h=Math.PI,f=h/2,p=2*h;function d(t){return t>=1?f:t<=-1?-f:Math.asin(t)}function g(t){return t.innerRadius}function v(t){return t.outerRadius}function m(t){return t.startAngle}function y(t){return t.endAngle}function x(t){return t&&t.padAngle}function b(t,e,r,n,i,a,s){var l=t-r,u=e-n,h=(s?a:-a)/c(l*l+u*u),f=h*u,p=-h*l,d=t+f,g=e+p,v=r+f,m=n+p,y=(d+v)/2,x=(g+m)/2,b=v-d,_=m-g,w=b*b+_*_,k=i-a,A=d*m-v*g,M=(_<0?-1:1)*c(o(0,k*k*w-A*A)),T=(A*_-b*M)/w,S=(-A*b-_*M)/w,E=(A*_+b*M)/w,C=(-A*b+_*M)/w,L=T-y,z=S-x,O=E-y,I=C-x;return L*L+z*z>O*O+I*I&&(T=E,S=C),{cx:T,cy:S,x01:-f,y01:-p,x11:T*(i/k-1),y11:S*(i/k-1)}}function _(t){this._context=t}function w(t){return new _(t)}function k(t){return t[0]}function A(t){return t[1]}function M(){var t=k,n=A,i=r(!0),a=null,o=w,s=null;function l(r){var l,c,u,h=r.length,f=!1;for(null==a&&(s=o(u=e.path())),l=0;l<=h;++l)!(l<h&&i(c=r[l],l,r))===f&&((f=!f)?s.lineStart():s.lineEnd()),f&&s.point(+t(c,l,r),+n(c,l,r));if(u)return s=null,u+""||null}return l.x=function(e){return arguments.length?(t="function"==typeof e?e:r(+e),l):t},l.y=function(t){return arguments.length?(n="function"==typeof t?t:r(+t),l):n},l.defined=function(t){return arguments.length?(i="function"==typeof t?t:r(!!t),l):i},l.curve=function(t){return arguments.length?(o=t,null!=a&&(s=o(a)),l):o},l.context=function(t){return arguments.length?(null==t?a=s=null:s=o(a=t),l):a},l}function T(){var t=k,n=null,i=r(0),a=A,o=r(!0),s=null,l=w,c=null;function u(r){var u,h,f,p,d,g=r.length,v=!1,m=new Array(g),y=new Array(g);for(null==s&&(c=l(d=e.path())),u=0;u<=g;++u){if(!(u<g&&o(p=r[u],u,r))===v)if(v=!v)h=u,c.areaStart(),c.lineStart();else{for(c.lineEnd(),c.lineStart(),f=u-1;f>=h;--f)c.point(m[f],y[f]);c.lineEnd(),c.areaEnd()}v&&(m[u]=+t(p,u,r),y[u]=+i(p,u,r),c.point(n?+n(p,u,r):m[u],a?+a(p,u,r):y[u]))}if(d)return c=null,d+""||null}function h(){return M().defined(o).curve(l).context(s)}return u.x=function(e){return arguments.length?(t="function"==typeof e?e:r(+e),n=null,u):t},u.x0=function(e){return arguments.length?(t="function"==typeof e?e:r(+e),u):t},u.x1=function(t){return arguments.length?(n=null==t?null:"function"==typeof t?t:r(+t),u):n},u.y=function(t){return arguments.length?(i="function"==typeof t?t:r(+t),a=null,u):i},u.y0=function(t){return arguments.length?(i="function"==typeof t?t:r(+t),u):i},u.y1=function(t){return arguments.length?(a=null==t?null:"function"==typeof t?t:r(+t),u):a},u.lineX0=u.lineY0=function(){return h().x(t).y(i)},u.lineY1=function(){return h().x(t).y(a)},u.lineX1=function(){return h().x(n).y(i)},u.defined=function(t){return arguments.length?(o="function"==typeof t?t:r(!!t),u):o},u.curve=function(t){return arguments.length?(l=t,null!=s&&(c=l(s)),u):l},u.context=function(t){return arguments.length?(null==t?s=c=null:c=l(s=t),u):s},u}function S(t,e){return e<t?-1:e>t?1:e>=t?0:NaN}function E(t){return t}_.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:this._context.lineTo(t,e)}}};var C=z(w);function L(t){this._curve=t}function z(t){function e(e){return new L(t(e))}return e._curve=t,e}function O(t){var e=t.curve;return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t.curve=function(t){return arguments.length?e(z(t)):e()._curve},t}function I(){return O(M().curve(C))}function D(){var t=T().curve(C),e=t.curve,r=t.lineX0,n=t.lineX1,i=t.lineY0,a=t.lineY1;return t.angle=t.x,delete t.x,t.startAngle=t.x0,delete t.x0,t.endAngle=t.x1,delete t.x1,t.radius=t.y,delete t.y,t.innerRadius=t.y0,delete t.y0,t.outerRadius=t.y1,delete t.y1,t.lineStartAngle=function(){return O(r())},delete t.lineX0,t.lineEndAngle=function(){return O(n())},delete t.lineX1,t.lineInnerRadius=function(){return O(i())},delete t.lineY0,t.lineOuterRadius=function(){return O(a())},delete t.lineY1,t.curve=function(t){return arguments.length?e(z(t)):e()._curve},t}function P(t,e){return[(e=+e)*Math.cos(t-=Math.PI/2),e*Math.sin(t)]}L.prototype={areaStart:function(){this._curve.areaStart()},areaEnd:function(){this._curve.areaEnd()},lineStart:function(){this._curve.lineStart()},lineEnd:function(){this._curve.lineEnd()},point:function(t,e){this._curve.point(e*Math.sin(t),e*-Math.cos(t))}};var R=Array.prototype.slice;function F(t){return t.source}function B(t){return t.target}function N(t){var n=F,i=B,a=k,o=A,s=null;function l(){var r,l=R.call(arguments),c=n.apply(this,l),u=i.apply(this,l);if(s||(s=r=e.path()),t(s,+a.apply(this,(l[0]=c,l)),+o.apply(this,l),+a.apply(this,(l[0]=u,l)),+o.apply(this,l)),r)return s=null,r+""||null}return l.source=function(t){return arguments.length?(n=t,l):n},l.target=function(t){return arguments.length?(i=t,l):i},l.x=function(t){return arguments.length?(a="function"==typeof t?t:r(+t),l):a},l.y=function(t){return arguments.length?(o="function"==typeof t?t:r(+t),l):o},l.context=function(t){return arguments.length?(s=null==t?null:t,l):s},l}function j(t,e,r,n,i){t.moveTo(e,r),t.bezierCurveTo(e=(e+n)/2,r,e,i,n,i)}function V(t,e,r,n,i){t.moveTo(e,r),t.bezierCurveTo(e,r=(r+i)/2,n,r,n,i)}function U(t,e,r,n,i){var a=P(e,r),o=P(e,r=(r+i)/2),s=P(n,r),l=P(n,i);t.moveTo(a[0],a[1]),t.bezierCurveTo(o[0],o[1],s[0],s[1],l[0],l[1])}var q={draw:function(t,e){var r=Math.sqrt(e/h);t.moveTo(r,0),t.arc(0,0,r,0,p)}},H={draw:function(t,e){var r=Math.sqrt(e/5)/2;t.moveTo(-3*r,-r),t.lineTo(-r,-r),t.lineTo(-r,-3*r),t.lineTo(r,-3*r),t.lineTo(r,-r),t.lineTo(3*r,-r),t.lineTo(3*r,r),t.lineTo(r,r),t.lineTo(r,3*r),t.lineTo(-r,3*r),t.lineTo(-r,r),t.lineTo(-3*r,r),t.closePath()}},G=Math.sqrt(1/3),Y=2*G,W={draw:function(t,e){var r=Math.sqrt(e/Y),n=r*G;t.moveTo(0,-r),t.lineTo(n,0),t.lineTo(0,r),t.lineTo(-n,0),t.closePath()}},X=Math.sin(h/10)/Math.sin(7*h/10),Z=Math.sin(p/10)*X,$=-Math.cos(p/10)*X,J={draw:function(t,e){var r=Math.sqrt(.8908130915292852*e),n=Z*r,i=$*r;t.moveTo(0,-r),t.lineTo(n,i);for(var a=1;a<5;++a){var o=p*a/5,s=Math.cos(o),l=Math.sin(o);t.lineTo(l*r,-s*r),t.lineTo(s*n-l*i,l*n+s*i)}t.closePath()}},K={draw:function(t,e){var r=Math.sqrt(e),n=-r/2;t.rect(n,n,r,r)}},Q=Math.sqrt(3),tt={draw:function(t,e){var r=-Math.sqrt(e/(3*Q));t.moveTo(0,2*r),t.lineTo(-Q*r,-r),t.lineTo(Q*r,-r),t.closePath()}},et=-.5,rt=Math.sqrt(3)/2,nt=1/Math.sqrt(12),it=3*(nt/2+1),at={draw:function(t,e){var r=Math.sqrt(e/it),n=r/2,i=r*nt,a=n,o=r*nt+r,s=-a,l=o;t.moveTo(n,i),t.lineTo(a,o),t.lineTo(s,l),t.lineTo(et*n-rt*i,rt*n+et*i),t.lineTo(et*a-rt*o,rt*a+et*o),t.lineTo(et*s-rt*l,rt*s+et*l),t.lineTo(et*n+rt*i,et*i-rt*n),t.lineTo(et*a+rt*o,et*o-rt*a),t.lineTo(et*s+rt*l,et*l-rt*s),t.closePath()}},ot=[q,H,W,K,J,tt,at];function st(){}function lt(t,e,r){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+e)/6,(t._y0+4*t._y1+r)/6)}function ct(t){this._context=t}function ut(t){this._context=t}function ht(t){this._context=t}function ft(t,e){this._basis=new ct(t),this._beta=e}ct.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:lt(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:lt(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}},ut.prototype={areaStart:st,areaEnd:st,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x2,this._y2),this._context.closePath();break;case 2:this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break;case 3:this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4)}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x2=t,this._y2=e;break;case 1:this._point=2,this._x3=t,this._y3=e;break;case 2:this._point=3,this._x4=t,this._y4=e,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+e)/6);break;default:lt(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}},ht.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var r=(this._x0+4*this._x1+t)/6,n=(this._y0+4*this._y1+e)/6;this._line?this._context.lineTo(r,n):this._context.moveTo(r,n);break;case 3:this._point=4;default:lt(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}},ft.prototype={lineStart:function(){this._x=[],this._y=[],this._basis.lineStart()},lineEnd:function(){var t=this._x,e=this._y,r=t.length-1;if(r>0)for(var n,i=t[0],a=e[0],o=t[r]-i,s=e[r]-a,l=-1;++l<=r;)n=l/r,this._basis.point(this._beta*t[l]+(1-this._beta)*(i+n*o),this._beta*e[l]+(1-this._beta)*(a+n*s));this._x=this._y=null,this._basis.lineEnd()},point:function(t,e){this._x.push(+t),this._y.push(+e)}};var pt=function t(e){function r(t){return 1===e?new ct(t):new ft(t,e)}return r.beta=function(e){return t(+e)},r}(.85);function dt(t,e,r){t._context.bezierCurveTo(t._x1+t._k*(t._x2-t._x0),t._y1+t._k*(t._y2-t._y0),t._x2+t._k*(t._x1-e),t._y2+t._k*(t._y1-r),t._x2,t._y2)}function gt(t,e){this._context=t,this._k=(1-e)/6}gt.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:dt(this,this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2,this._x1=t,this._y1=e;break;case 2:this._point=3;default:dt(this,t,e)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};var vt=function t(e){function r(t){return new gt(t,e)}return r.tension=function(e){return t(+e)},r}(0);function mt(t,e){this._context=t,this._k=(1-e)/6}mt.prototype={areaStart:st,areaEnd:st,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x3=t,this._y3=e;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=e);break;case 2:this._point=3,this._x5=t,this._y5=e;break;default:dt(this,t,e)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};var yt=function t(e){function r(t){return new mt(t,e)}return r.tension=function(e){return t(+e)},r}(0);function xt(t,e){this._context=t,this._k=(1-e)/6}xt.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:dt(this,t,e)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};var bt=function t(e){function r(t){return new xt(t,e)}return r.tension=function(e){return t(+e)},r}(0);function _t(t,e,r){var n=t._x1,i=t._y1,a=t._x2,o=t._y2;if(t._l01_a>u){var s=2*t._l01_2a+3*t._l01_a*t._l12_a+t._l12_2a,l=3*t._l01_a*(t._l01_a+t._l12_a);n=(n*s-t._x0*t._l12_2a+t._x2*t._l01_2a)/l,i=(i*s-t._y0*t._l12_2a+t._y2*t._l01_2a)/l}if(t._l23_a>u){var c=2*t._l23_2a+3*t._l23_a*t._l12_a+t._l12_2a,h=3*t._l23_a*(t._l23_a+t._l12_a);a=(a*c+t._x1*t._l23_2a-e*t._l12_2a)/h,o=(o*c+t._y1*t._l23_2a-r*t._l12_2a)/h}t._context.bezierCurveTo(n,i,a,o,t._x2,t._y2)}function wt(t,e){this._context=t,this._alpha=e}wt.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){if(t=+t,e=+e,this._point){var r=this._x2-t,n=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(r*r+n*n,this._alpha))}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3;default:_t(this,t,e)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};var kt=function t(e){function r(t){return e?new wt(t,e):new gt(t,0)}return r.alpha=function(e){return t(+e)},r}(.5);function At(t,e){this._context=t,this._alpha=e}At.prototype={areaStart:st,areaEnd:st,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,e){if(t=+t,e=+e,this._point){var r=this._x2-t,n=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(r*r+n*n,this._alpha))}switch(this._point){case 0:this._point=1,this._x3=t,this._y3=e;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=e);break;case 2:this._point=3,this._x5=t,this._y5=e;break;default:_t(this,t,e)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};var Mt=function t(e){function r(t){return e?new At(t,e):new mt(t,0)}return r.alpha=function(e){return t(+e)},r}(.5);function Tt(t,e){this._context=t,this._alpha=e}Tt.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){if(t=+t,e=+e,this._point){var r=this._x2-t,n=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(r*r+n*n,this._alpha))}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:_t(this,t,e)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};var St=function t(e){function r(t){return e?new Tt(t,e):new xt(t,0)}return r.alpha=function(e){return t(+e)},r}(.5);function Et(t){this._context=t}function Ct(t){return t<0?-1:1}function Lt(t,e,r){var n=t._x1-t._x0,i=e-t._x1,a=(t._y1-t._y0)/(n||i<0&&-0),o=(r-t._y1)/(i||n<0&&-0),s=(a*i+o*n)/(n+i);return(Ct(a)+Ct(o))*Math.min(Math.abs(a),Math.abs(o),.5*Math.abs(s))||0}function zt(t,e){var r=t._x1-t._x0;return r?(3*(t._y1-t._y0)/r-e)/2:e}function Ot(t,e,r){var n=t._x0,i=t._y0,a=t._x1,o=t._y1,s=(a-n)/3;t._context.bezierCurveTo(n+s,i+s*e,a-s,o-s*r,a,o)}function It(t){this._context=t}function Dt(t){this._context=new Pt(t)}function Pt(t){this._context=t}function Rt(t){this._context=t}function Ft(t){var e,r,n=t.length-1,i=new Array(n),a=new Array(n),o=new Array(n);for(i[0]=0,a[0]=2,o[0]=t[0]+2*t[1],e=1;e<n-1;++e)i[e]=1,a[e]=4,o[e]=4*t[e]+2*t[e+1];for(i[n-1]=2,a[n-1]=7,o[n-1]=8*t[n-1]+t[n],e=1;e<n;++e)r=i[e]/a[e-1],a[e]-=r,o[e]-=r*o[e-1];for(i[n-1]=o[n-1]/a[n-1],e=n-2;e>=0;--e)i[e]=(o[e]-i[e+1])/a[e];for(a[n-1]=(t[n]+i[n-1])/2,e=0;e<n-1;++e)a[e]=2*t[e+1]-i[e+1];return[i,a]}function Bt(t,e){this._context=t,this._t=e}function Nt(t,e){if((i=t.length)>1)for(var r,n,i,a=1,o=t[e[0]],s=o.length;a<i;++a)for(n=o,o=t[e[a]],r=0;r<s;++r)o[r][1]+=o[r][0]=isNaN(n[r][1])?n[r][0]:n[r][1]}function jt(t){for(var e=t.length,r=new Array(e);--e>=0;)r[e]=e;return r}function Vt(t,e){return t[e]}function Ut(t){var e=t.map(qt);return jt(t).sort(function(t,r){return e[t]-e[r]})}function qt(t){for(var e,r=-1,n=0,i=t.length,a=-1/0;++r<i;)(e=+t[r][1])>a&&(a=e,n=r);return n}function Ht(t){var e=t.map(Gt);return jt(t).sort(function(t,r){return e[t]-e[r]})}function Gt(t){for(var e,r=0,n=-1,i=t.length;++n<i;)(e=+t[n][1])&&(r+=e);return r}Et.prototype={areaStart:st,areaEnd:st,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(t,e){t=+t,e=+e,this._point?this._context.lineTo(t,e):(this._point=1,this._context.moveTo(t,e))}},It.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:Ot(this,this._t0,zt(this,this._t0))}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){var r=NaN;if(e=+e,(t=+t)!==this._x1||e!==this._y1){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,Ot(this,zt(this,r=Lt(this,t,e)),r);break;default:Ot(this,this._t0,r=Lt(this,t,e))}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e,this._t0=r}}},(Dt.prototype=Object.create(It.prototype)).point=function(t,e){It.prototype.point.call(this,e,t)},Pt.prototype={moveTo:function(t,e){this._context.moveTo(e,t)},closePath:function(){this._context.closePath()},lineTo:function(t,e){this._context.lineTo(e,t)},bezierCurveTo:function(t,e,r,n,i,a){this._context.bezierCurveTo(e,t,n,r,a,i)}},Rt.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var t=this._x,e=this._y,r=t.length;if(r)if(this._line?this._context.lineTo(t[0],e[0]):this._context.moveTo(t[0],e[0]),2===r)this._context.lineTo(t[1],e[1]);else for(var n=Ft(t),i=Ft(e),a=0,o=1;o<r;++a,++o)this._context.bezierCurveTo(n[0][a],i[0][a],n[1][a],i[1][a],t[o],e[o]);(this._line||0!==this._line&&1===r)&&this._context.closePath(),this._line=1-this._line,this._x=this._y=null},point:function(t,e){this._x.push(+t),this._y.push(+e)}},Bt.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=this._y=NaN,this._point=0},lineEnd:function(){0<this._t&&this._t<1&&2===this._point&&this._context.lineTo(this._x,this._y),(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line>=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,e),this._context.lineTo(t,e);else{var r=this._x*(1-this._t)+t*this._t;this._context.lineTo(r,this._y),this._context.lineTo(r,e)}}this._x=t,this._y=e}},t.arc=function(){var t=g,o=v,_=r(0),w=null,k=m,A=y,M=x,T=null;function S(){var r,g,v,m=+t.apply(this,arguments),y=+o.apply(this,arguments),x=k.apply(this,arguments)-f,S=A.apply(this,arguments)-f,E=n(S-x),C=S>x;if(T||(T=r=e.path()),y<m&&(g=y,y=m,m=g),y>u)if(E>p-u)T.moveTo(y*a(x),y*l(x)),T.arc(0,0,y,x,S,!C),m>u&&(T.moveTo(m*a(S),m*l(S)),T.arc(0,0,m,S,x,C));else{var L,z,O=x,I=S,D=x,P=S,R=E,F=E,B=M.apply(this,arguments)/2,N=B>u&&(w?+w.apply(this,arguments):c(m*m+y*y)),j=s(n(y-m)/2,+_.apply(this,arguments)),V=j,U=j;if(N>u){var q=d(N/m*l(B)),H=d(N/y*l(B));(R-=2*q)>u?(D+=q*=C?1:-1,P-=q):(R=0,D=P=(x+S)/2),(F-=2*H)>u?(O+=H*=C?1:-1,I-=H):(F=0,O=I=(x+S)/2)}var G=y*a(O),Y=y*l(O),W=m*a(P),X=m*l(P);if(j>u){var Z,$=y*a(I),J=y*l(I),K=m*a(D),Q=m*l(D);if(E<h&&(Z=function(t,e,r,n,i,a,o,s){var l=r-t,c=n-e,h=o-i,f=s-a,p=f*l-h*c;if(!(p*p<u))return[t+(p=(h*(e-a)-f*(t-i))/p)*l,e+p*c]}(G,Y,K,Q,$,J,W,X))){var tt=G-Z[0],et=Y-Z[1],rt=$-Z[0],nt=J-Z[1],it=1/l(((v=(tt*rt+et*nt)/(c(tt*tt+et*et)*c(rt*rt+nt*nt)))>1?0:v<-1?h:Math.acos(v))/2),at=c(Z[0]*Z[0]+Z[1]*Z[1]);V=s(j,(m-at)/(it-1)),U=s(j,(y-at)/(it+1))}}F>u?U>u?(L=b(K,Q,G,Y,y,U,C),z=b($,J,W,X,y,U,C),T.moveTo(L.cx+L.x01,L.cy+L.y01),U<j?T.arc(L.cx,L.cy,U,i(L.y01,L.x01),i(z.y01,z.x01),!C):(T.arc(L.cx,L.cy,U,i(L.y01,L.x01),i(L.y11,L.x11),!C),T.arc(0,0,y,i(L.cy+L.y11,L.cx+L.x11),i(z.cy+z.y11,z.cx+z.x11),!C),T.arc(z.cx,z.cy,U,i(z.y11,z.x11),i(z.y01,z.x01),!C))):(T.moveTo(G,Y),T.arc(0,0,y,O,I,!C)):T.moveTo(G,Y),m>u&&R>u?V>u?(L=b(W,X,$,J,m,-V,C),z=b(G,Y,K,Q,m,-V,C),T.lineTo(L.cx+L.x01,L.cy+L.y01),V<j?T.arc(L.cx,L.cy,V,i(L.y01,L.x01),i(z.y01,z.x01),!C):(T.arc(L.cx,L.cy,V,i(L.y01,L.x01),i(L.y11,L.x11),!C),T.arc(0,0,m,i(L.cy+L.y11,L.cx+L.x11),i(z.cy+z.y11,z.cx+z.x11),C),T.arc(z.cx,z.cy,V,i(z.y11,z.x11),i(z.y01,z.x01),!C))):T.arc(0,0,m,P,D,C):T.lineTo(W,X)}else T.moveTo(0,0);if(T.closePath(),r)return T=null,r+""||null}return S.centroid=function(){var e=(+t.apply(this,arguments)+ +o.apply(this,arguments))/2,r=(+k.apply(this,arguments)+ +A.apply(this,arguments))/2-h/2;return[a(r)*e,l(r)*e]},S.innerRadius=function(e){return arguments.length?(t="function"==typeof e?e:r(+e),S):t},S.outerRadius=function(t){return arguments.length?(o="function"==typeof t?t:r(+t),S):o},S.cornerRadius=function(t){return arguments.length?(_="function"==typeof t?t:r(+t),S):_},S.padRadius=function(t){return arguments.length?(w=null==t?null:"function"==typeof t?t:r(+t),S):w},S.startAngle=function(t){return arguments.length?(k="function"==typeof t?t:r(+t),S):k},S.endAngle=function(t){return arguments.length?(A="function"==typeof t?t:r(+t),S):A},S.padAngle=function(t){return arguments.length?(M="function"==typeof t?t:r(+t),S):M},S.context=function(t){return arguments.length?(T=null==t?null:t,S):T},S},t.area=T,t.line=M,t.pie=function(){var t=E,e=S,n=null,i=r(0),a=r(p),o=r(0);function s(r){var s,l,c,u,h,f=r.length,d=0,g=new Array(f),v=new Array(f),m=+i.apply(this,arguments),y=Math.min(p,Math.max(-p,a.apply(this,arguments)-m)),x=Math.min(Math.abs(y)/f,o.apply(this,arguments)),b=x*(y<0?-1:1);for(s=0;s<f;++s)(h=v[g[s]=s]=+t(r[s],s,r))>0&&(d+=h);for(null!=e?g.sort(function(t,r){return e(v[t],v[r])}):null!=n&&g.sort(function(t,e){return n(r[t],r[e])}),s=0,c=d?(y-f*b)/d:0;s<f;++s,m=u)l=g[s],u=m+((h=v[l])>0?h*c:0)+b,v[l]={data:r[l],index:s,value:h,startAngle:m,endAngle:u,padAngle:x};return v}return s.value=function(e){return arguments.length?(t="function"==typeof e?e:r(+e),s):t},s.sortValues=function(t){return arguments.length?(e=t,n=null,s):e},s.sort=function(t){return arguments.length?(n=t,e=null,s):n},s.startAngle=function(t){return arguments.length?(i="function"==typeof t?t:r(+t),s):i},s.endAngle=function(t){return arguments.length?(a="function"==typeof t?t:r(+t),s):a},s.padAngle=function(t){return arguments.length?(o="function"==typeof t?t:r(+t),s):o},s},t.areaRadial=D,t.radialArea=D,t.lineRadial=I,t.radialLine=I,t.pointRadial=P,t.linkHorizontal=function(){return N(j)},t.linkVertical=function(){return N(V)},t.linkRadial=function(){var t=N(U);return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t},t.symbol=function(){var t=r(q),n=r(64),i=null;function a(){var r;if(i||(i=r=e.path()),t.apply(this,arguments).draw(i,+n.apply(this,arguments)),r)return i=null,r+""||null}return a.type=function(e){return arguments.length?(t="function"==typeof e?e:r(e),a):t},a.size=function(t){return arguments.length?(n="function"==typeof t?t:r(+t),a):n},a.context=function(t){return arguments.length?(i=null==t?null:t,a):i},a},t.symbols=ot,t.symbolCircle=q,t.symbolCross=H,t.symbolDiamond=W,t.symbolSquare=K,t.symbolStar=J,t.symbolTriangle=tt,t.symbolWye=at,t.curveBasisClosed=function(t){return new ut(t)},t.curveBasisOpen=function(t){return new ht(t)},t.curveBasis=function(t){return new ct(t)},t.curveBundle=pt,t.curveCardinalClosed=yt,t.curveCardinalOpen=bt,t.curveCardinal=vt,t.curveCatmullRomClosed=Mt,t.curveCatmullRomOpen=St,t.curveCatmullRom=kt,t.curveLinearClosed=function(t){return new Et(t)},t.curveLinear=w,t.curveMonotoneX=function(t){return new It(t)},t.curveMonotoneY=function(t){return new Dt(t)},t.curveNatural=function(t){return new Rt(t)},t.curveStep=function(t){return new Bt(t,.5)},t.curveStepAfter=function(t){return new Bt(t,1)},t.curveStepBefore=function(t){return new Bt(t,0)},t.stack=function(){var t=r([]),e=jt,n=Nt,i=Vt;function a(r){var a,o,s=t.apply(this,arguments),l=r.length,c=s.length,u=new Array(c);for(a=0;a<c;++a){for(var h,f=s[a],p=u[a]=new Array(l),d=0;d<l;++d)p[d]=h=[0,+i(r[d],f,d,r)],h.data=r[d];p.key=f}for(a=0,o=e(u);a<c;++a)u[o[a]].index=a;return n(u,o),u}return a.keys=function(e){return arguments.length?(t="function"==typeof e?e:r(R.call(e)),a):t},a.value=function(t){return arguments.length?(i="function"==typeof t?t:r(+t),a):i},a.order=function(t){return arguments.length?(e=null==t?jt:"function"==typeof t?t:r(R.call(t)),a):e},a.offset=function(t){return arguments.length?(n=null==t?Nt:t,a):n},a},t.stackOffsetExpand=function(t,e){if((n=t.length)>0){for(var r,n,i,a=0,o=t[0].length;a<o;++a){for(i=r=0;r<n;++r)i+=t[r][a][1]||0;if(i)for(r=0;r<n;++r)t[r][a][1]/=i}Nt(t,e)}},t.stackOffsetDiverging=function(t,e){if((s=t.length)>1)for(var r,n,i,a,o,s,l=0,c=t[e[0]].length;l<c;++l)for(a=o=0,r=0;r<s;++r)(i=(n=t[e[r]][l])[1]-n[0])>=0?(n[0]=a,n[1]=a+=i):i<0?(n[1]=o,n[0]=o+=i):n[0]=a},t.stackOffsetNone=Nt,t.stackOffsetSilhouette=function(t,e){if((r=t.length)>0){for(var r,n=0,i=t[e[0]],a=i.length;n<a;++n){for(var o=0,s=0;o<r;++o)s+=t[o][n][1]||0;i[n][1]+=i[n][0]=-s/2}Nt(t,e)}},t.stackOffsetWiggle=function(t,e){if((i=t.length)>0&&(n=(r=t[e[0]]).length)>0){for(var r,n,i,a=0,o=1;o<n;++o){for(var s=0,l=0,c=0;s<i;++s){for(var u=t[e[s]],h=u[o][1]||0,f=(h-(u[o-1][1]||0))/2,p=0;p<s;++p){var d=t[e[p]];f+=(d[o][1]||0)-(d[o-1][1]||0)}l+=h,c+=f*h}r[o-1][1]+=r[o-1][0]=a,l&&(a-=c/l)}r[o-1][1]+=r[o-1][0]=a,Nt(t,e)}},t.stackOrderAppearance=Ut,t.stackOrderAscending=Ht,t.stackOrderDescending=function(t){return Ht(t).reverse()},t.stackOrderInsideOut=function(t){var e,r,n=t.length,i=t.map(Gt),a=Ut(t),o=0,s=0,l=[],c=[];for(e=0;e<n;++e)r=a[e],o<s?(o+=i[r],l.push(r)):(s+=i[r],c.push(r));return c.reverse().concat(l)},t.stackOrderNone=jt,t.stackOrderReverse=function(t){return jt(t).reverse()},Object.defineProperty(t,"__esModule",{value:!0})},"object"==typeof r&&"undefined"!=typeof e?i(r,t("d3-path")):i(n.d3=n.d3||{},n.d3)},{"d3-path":146}],150:[function(t,e,r){var n;n=this,function(t){"use strict";var e,r,n=0,i=0,a=0,o=1e3,s=0,l=0,c=0,u="object"==typeof performance&&performance.now?performance:Date,h="object"==typeof window&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(t){setTimeout(t,17)};function f(){return l||(h(p),l=u.now()+c)}function p(){l=0}function d(){this._call=this._time=this._next=null}function g(t,e,r){var n=new d;return n.restart(t,e,r),n}function v(){f(),++n;for(var t,r=e;r;)(t=l-r._time)>=0&&r._call.call(null,t),r=r._next;--n}function m(){l=(s=u.now())+c,n=i=0;try{v()}finally{n=0,function(){var t,n,i=e,a=1/0;for(;i;)i._call?(a>i._time&&(a=i._time),t=i,i=i._next):(n=i._next,i._next=null,i=t?t._next=n:e=n);r=t,x(a)}(),l=0}}function y(){var t=u.now(),e=t-s;e>o&&(c-=e,s=t)}function x(t){n||(i&&(i=clearTimeout(i)),t-l>24?(t<1/0&&(i=setTimeout(m,t-u.now()-c)),a&&(a=clearInterval(a))):(a||(s=u.now(),a=setInterval(y,o)),n=1,h(m)))}d.prototype=g.prototype={constructor:d,restart:function(t,n,i){if("function"!=typeof t)throw new TypeError("callback is not a function");i=(null==i?f():+i)+(null==n?0:+n),this._next||r===this||(r?r._next=this:e=this,r=this),this._call=t,this._time=i,x()},stop:function(){this._call&&(this._call=null,this._time=1/0,x())}};t.now=f,t.timer=g,t.timerFlush=v,t.timeout=function(t,e,r){var n=new d;return e=null==e?0:+e,n.restart(function(r){n.stop(),t(r+e)},e,r),n},t.interval=function(t,e,r){var n=new d,i=e;return null==e?(n.restart(t,e,r),n):(e=+e,r=null==r?f():+r,n.restart(function a(o){o+=i,n.restart(a,i+=e,r),t(o)},e,r),n)},Object.defineProperty(t,"__esModule",{value:!0})}("object"==typeof r&&"undefined"!=typeof e?r:n.d3=n.d3||{})},{}],151:[function(t,e,r){!function(){var t={version:"3.5.17"},r=[].slice,n=function(t){return r.call(t)},i=this.document;function a(t){return t&&(t.ownerDocument||t.document||t).documentElement}function o(t){return t&&(t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView)}if(i)try{n(i.documentElement.childNodes)[0].nodeType}catch(t){n=function(t){for(var e=t.length,r=new Array(e);e--;)r[e]=t[e];return r}}if(Date.now||(Date.now=function(){return+new Date}),i)try{i.createElement("DIV").style.setProperty("opacity",0,"")}catch(t){var s=this.Element.prototype,l=s.setAttribute,c=s.setAttributeNS,u=this.CSSStyleDeclaration.prototype,h=u.setProperty;s.setAttribute=function(t,e){l.call(this,t,e+"")},s.setAttributeNS=function(t,e,r){c.call(this,t,e,r+"")},u.setProperty=function(t,e,r){h.call(this,t,e+"",r)}}function f(t,e){return t<e?-1:t>e?1:t>=e?0:NaN}function p(t){return null===t?NaN:+t}function d(t){return!isNaN(t)}function g(t){return{left:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);n<i;){var a=n+i>>>1;t(e[a],r)<0?n=a+1:i=a}return n},right:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);n<i;){var a=n+i>>>1;t(e[a],r)>0?i=a:n=a+1}return n}}}t.ascending=f,t.descending=function(t,e){return e<t?-1:e>t?1:e>=t?0:NaN},t.min=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i<a;)if(null!=(n=t[i])&&n>=n){r=n;break}for(;++i<a;)null!=(n=t[i])&&r>n&&(r=n)}else{for(;++i<a;)if(null!=(n=e.call(t,t[i],i))&&n>=n){r=n;break}for(;++i<a;)null!=(n=e.call(t,t[i],i))&&r>n&&(r=n)}return r},t.max=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i<a;)if(null!=(n=t[i])&&n>=n){r=n;break}for(;++i<a;)null!=(n=t[i])&&n>r&&(r=n)}else{for(;++i<a;)if(null!=(n=e.call(t,t[i],i))&&n>=n){r=n;break}for(;++i<a;)null!=(n=e.call(t,t[i],i))&&n>r&&(r=n)}return r},t.extent=function(t,e){var r,n,i,a=-1,o=t.length;if(1===arguments.length){for(;++a<o;)if(null!=(n=t[a])&&n>=n){r=i=n;break}for(;++a<o;)null!=(n=t[a])&&(r>n&&(r=n),i<n&&(i=n))}else{for(;++a<o;)if(null!=(n=e.call(t,t[a],a))&&n>=n){r=i=n;break}for(;++a<o;)null!=(n=e.call(t,t[a],a))&&(r>n&&(r=n),i<n&&(i=n))}return[r,i]},t.sum=function(t,e){var r,n=0,i=t.length,a=-1;if(1===arguments.length)for(;++a<i;)d(r=+t[a])&&(n+=r);else for(;++a<i;)d(r=+e.call(t,t[a],a))&&(n+=r);return n},t.mean=function(t,e){var r,n=0,i=t.length,a=-1,o=i;if(1===arguments.length)for(;++a<i;)d(r=p(t[a]))?n+=r:--o;else for(;++a<i;)d(r=p(e.call(t,t[a],a)))?n+=r:--o;if(o)return n/o},t.quantile=function(t,e){var r=(t.length-1)*e+1,n=Math.floor(r),i=+t[n-1],a=r-n;return a?i+a*(t[n]-i):i},t.median=function(e,r){var n,i=[],a=e.length,o=-1;if(1===arguments.length)for(;++o<a;)d(n=p(e[o]))&&i.push(n);else for(;++o<a;)d(n=p(r.call(e,e[o],o)))&&i.push(n);if(i.length)return t.quantile(i.sort(f),.5)},t.variance=function(t,e){var r,n,i=t.length,a=0,o=0,s=-1,l=0;if(1===arguments.length)for(;++s<i;)d(r=p(t[s]))&&(o+=(n=r-a)*(r-(a+=n/++l)));else for(;++s<i;)d(r=p(e.call(t,t[s],s)))&&(o+=(n=r-a)*(r-(a+=n/++l)));if(l>1)return o/(l-1)},t.deviation=function(){var e=t.variance.apply(this,arguments);return e?Math.sqrt(e):e};var v=g(f);function m(t){return t.length}t.bisectLeft=v.left,t.bisect=t.bisectRight=v.right,t.bisector=function(t){return g(1===t.length?function(e,r){return f(t(e),r)}:t)},t.shuffle=function(t,e,r){(a=arguments.length)<3&&(r=t.length,a<2&&(e=0));for(var n,i,a=r-e;a;)i=Math.random()*a--|0,n=t[a+e],t[a+e]=t[i+e],t[i+e]=n;return t},t.permute=function(t,e){for(var r=e.length,n=new Array(r);r--;)n[r]=t[e[r]];return n},t.pairs=function(t){for(var e=0,r=t.length-1,n=t[0],i=new Array(r<0?0:r);e<r;)i[e]=[n,n=t[++e]];return i},t.transpose=function(e){if(!(a=e.length))return[];for(var r=-1,n=t.min(e,m),i=new Array(n);++r<n;)for(var a,o=-1,s=i[r]=new Array(a);++o<a;)s[o]=e[o][r];return i},t.zip=function(){return t.transpose(arguments)},t.keys=function(t){var e=[];for(var r in t)e.push(r);return e},t.values=function(t){var e=[];for(var r in t)e.push(t[r]);return e},t.entries=function(t){var e=[];for(var r in t)e.push({key:r,value:t[r]});return e},t.merge=function(t){for(var e,r,n,i=t.length,a=-1,o=0;++a<i;)o+=t[a].length;for(r=new Array(o);--i>=0;)for(e=(n=t[i]).length;--e>=0;)r[--o]=n[e];return r};var y=Math.abs;function x(t,e){for(var r in e)Object.defineProperty(t.prototype,r,{value:e[r],enumerable:!1})}function b(){this._=Object.create(null)}t.range=function(t,e,r){if(arguments.length<3&&(r=1,arguments.length<2&&(e=t,t=0)),(e-t)/r==1/0)throw new Error("infinite range");var n,i=[],a=function(t){var e=1;for(;t*e%1;)e*=10;return e}(y(r)),o=-1;if(t*=a,e*=a,(r*=a)<0)for(;(n=t+r*++o)>e;)i.push(n/a);else for(;(n=t+r*++o)<e;)i.push(n/a);return i},t.map=function(t,e){var r=new b;if(t instanceof b)t.forEach(function(t,e){r.set(t,e)});else if(Array.isArray(t)){var n,i=-1,a=t.length;if(1===arguments.length)for(;++i<a;)r.set(i,t[i]);else for(;++i<a;)r.set(e.call(t,n=t[i],i),n)}else for(var o in t)r.set(o,t[o]);return r};var _="__proto__",w="\0";function k(t){return(t+="")===_||t[0]===w?w+t:t}function A(t){return(t+="")[0]===w?t.slice(1):t}function M(t){return k(t)in this._}function T(t){return(t=k(t))in this._&&delete this._[t]}function S(){var t=[];for(var e in this._)t.push(A(e));return t}function E(){var t=0;for(var e in this._)++t;return t}function C(){for(var t in this._)return!1;return!0}function L(){this._=Object.create(null)}function z(t){return t}function O(t,e,r){return function(){var n=r.apply(e,arguments);return n===e?t:n}}function I(t,e){if(e in t)return e;e=e.charAt(0).toUpperCase()+e.slice(1);for(var r=0,n=D.length;r<n;++r){var i=D[r]+e;if(i in t)return i}}x(b,{has:M,get:function(t){return this._[k(t)]},set:function(t,e){return this._[k(t)]=e},remove:T,keys:S,values:function(){var t=[];for(var e in this._)t.push(this._[e]);return t},entries:function(){var t=[];for(var e in this._)t.push({key:A(e),value:this._[e]});return t},size:E,empty:C,forEach:function(t){for(var e in this._)t.call(this,A(e),this._[e])}}),t.nest=function(){var e,r,n={},i=[],a=[];function o(t,a,s){if(s>=i.length)return r?r.call(n,a):e?a.sort(e):a;for(var l,c,u,h,f=-1,p=a.length,d=i[s++],g=new b;++f<p;)(h=g.get(l=d(c=a[f])))?h.push(c):g.set(l,[c]);return t?(c=t(),u=function(e,r){c.set(e,o(t,r,s))}):(c={},u=function(e,r){c[e]=o(t,r,s)}),g.forEach(u),c}return n.map=function(t,e){return o(e,t,0)},n.entries=function(e){return function t(e,r){if(r>=i.length)return e;var n=[],o=a[r++];return e.forEach(function(e,i){n.push({key:e,values:t(i,r)})}),o?n.sort(function(t,e){return o(t.key,e.key)}):n}(o(t.map,e,0),0)},n.key=function(t){return i.push(t),n},n.sortKeys=function(t){return a[i.length-1]=t,n},n.sortValues=function(t){return e=t,n},n.rollup=function(t){return r=t,n},n},t.set=function(t){var e=new L;if(t)for(var r=0,n=t.length;r<n;++r)e.add(t[r]);return e},x(L,{has:M,add:function(t){return this._[k(t+="")]=!0,t},remove:T,values:S,size:E,empty:C,forEach:function(t){for(var e in this._)t.call(this,A(e))}}),t.behavior={},t.rebind=function(t,e){for(var r,n=1,i=arguments.length;++n<i;)t[r=arguments[n]]=O(t,e,e[r]);return t};var D=["webkit","ms","moz","Moz","o","O"];function P(){}function R(){}function F(t){var e=[],r=new b;function n(){for(var r,n=e,i=-1,a=n.length;++i<a;)(r=n[i].on)&&r.apply(this,arguments);return t}return n.on=function(n,i){var a,o=r.get(n);return arguments.length<2?o&&o.on:(o&&(o.on=null,e=e.slice(0,a=e.indexOf(o)).concat(e.slice(a+1)),r.remove(n)),i&&e.push(r.set(n,{on:i})),t)},n}function B(){t.event.preventDefault()}function N(){for(var e,r=t.event;e=r.sourceEvent;)r=e;return r}function j(e){for(var r=new R,n=0,i=arguments.length;++n<i;)r[arguments[n]]=F(r);return r.of=function(n,i){return function(a){try{var o=a.sourceEvent=t.event;a.target=e,t.event=a,r[a.type].apply(n,i)}finally{t.event=o}}},r}t.dispatch=function(){for(var t=new R,e=-1,r=arguments.length;++e<r;)t[arguments[e]]=F(t);return t},R.prototype.on=function(t,e){var r=t.indexOf("."),n="";if(r>=0&&(n=t.slice(r+1),t=t.slice(0,r)),t)return arguments.length<2?this[t].on(n):this[t].on(n,e);if(2===arguments.length){if(null==e)for(t in this)this.hasOwnProperty(t)&&this[t].on(n,null);return this}},t.event=null,t.requote=function(t){return t.replace(V,"\\$&")};var V=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,U={}.__proto__?function(t,e){t.__proto__=e}:function(t,e){for(var r in e)t[r]=e[r]};function q(t){return U(t,W),t}var H=function(t,e){return e.querySelector(t)},G=function(t,e){return e.querySelectorAll(t)},Y=function(t,e){var r=t.matches||t[I(t,"matchesSelector")];return(Y=function(t,e){return r.call(t,e)})(t,e)};"function"==typeof Sizzle&&(H=function(t,e){return Sizzle(t,e)[0]||null},G=Sizzle,Y=Sizzle.matchesSelector),t.selection=function(){return t.select(i.documentElement)};var W=t.selection.prototype=[];function X(t){return"function"==typeof t?t:function(){return H(t,this)}}function Z(t){return"function"==typeof t?t:function(){return G(t,this)}}W.select=function(t){var e,r,n,i,a=[];t=X(t);for(var o=-1,s=this.length;++o<s;){a.push(e=[]),e.parentNode=(n=this[o]).parentNode;for(var l=-1,c=n.length;++l<c;)(i=n[l])?(e.push(r=t.call(i,i.__data__,l,o)),r&&"__data__"in i&&(r.__data__=i.__data__)):e.push(null)}return q(a)},W.selectAll=function(t){var e,r,i=[];t=Z(t);for(var a=-1,o=this.length;++a<o;)for(var s=this[a],l=-1,c=s.length;++l<c;)(r=s[l])&&(i.push(e=n(t.call(r,r.__data__,l,a))),e.parentNode=r);return q(i)};var $="http://www.w3.org/1999/xhtml",J={svg:"http://www.w3.org/2000/svg",xhtml:$,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function K(e,r){return e=t.ns.qualify(e),null==r?e.local?function(){this.removeAttributeNS(e.space,e.local)}:function(){this.removeAttribute(e)}:"function"==typeof r?e.local?function(){var t=r.apply(this,arguments);null==t?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,t)}:function(){var t=r.apply(this,arguments);null==t?this.removeAttribute(e):this.setAttribute(e,t)}:e.local?function(){this.setAttributeNS(e.space,e.local,r)}:function(){this.setAttribute(e,r)}}function Q(t){return t.trim().replace(/\s+/g," ")}function tt(e){return new RegExp("(?:^|\\s+)"+t.requote(e)+"(?:\\s+|$)","g")}function et(t){return(t+"").trim().split(/^|\s+/)}function rt(t,e){var r=(t=et(t).map(nt)).length;return"function"==typeof e?function(){for(var n=-1,i=e.apply(this,arguments);++n<r;)t[n](this,i)}:function(){for(var n=-1;++n<r;)t[n](this,e)}}function nt(t){var e=tt(t);return function(r,n){if(i=r.classList)return n?i.add(t):i.remove(t);var i=r.getAttribute("class")||"";n?(e.lastIndex=0,e.test(i)||r.setAttribute("class",Q(i+" "+t))):r.setAttribute("class",Q(i.replace(e," ")))}}function it(t,e,r){return null==e?function(){this.style.removeProperty(t)}:"function"==typeof e?function(){var n=e.apply(this,arguments);null==n?this.style.removeProperty(t):this.style.setProperty(t,n,r)}:function(){this.style.setProperty(t,e,r)}}function at(t,e){return null==e?function(){delete this[t]}:"function"==typeof e?function(){var r=e.apply(this,arguments);null==r?delete this[t]:this[t]=r}:function(){this[t]=e}}function ot(e){return"function"==typeof e?e:(e=t.ns.qualify(e)).local?function(){return this.ownerDocument.createElementNS(e.space,e.local)}:function(){var t=this.ownerDocument,r=this.namespaceURI;return r===$&&t.documentElement.namespaceURI===$?t.createElement(e):t.createElementNS(r,e)}}function st(){var t=this.parentNode;t&&t.removeChild(this)}function lt(t){return{__data__:t}}function ct(t){return function(){return Y(this,t)}}function ut(t,e){for(var r=0,n=t.length;r<n;r++)for(var i,a=t[r],o=0,s=a.length;o<s;o++)(i=a[o])&&e(i,o,r);return t}function ht(t){return U(t,ft),t}t.ns={prefix:J,qualify:function(t){var e=t.indexOf(":"),r=t;return e>=0&&"xmlns"!==(r=t.slice(0,e))&&(t=t.slice(e+1)),J.hasOwnProperty(r)?{space:J[r],local:t}:t}},W.attr=function(e,r){if(arguments.length<2){if("string"==typeof e){var n=this.node();return(e=t.ns.qualify(e)).local?n.getAttributeNS(e.space,e.local):n.getAttribute(e)}for(r in e)this.each(K(r,e[r]));return this}return this.each(K(e,r))},W.classed=function(t,e){if(arguments.length<2){if("string"==typeof t){var r=this.node(),n=(t=et(t)).length,i=-1;if(e=r.classList){for(;++i<n;)if(!e.contains(t[i]))return!1}else for(e=r.getAttribute("class");++i<n;)if(!tt(t[i]).test(e))return!1;return!0}for(e in t)this.each(rt(e,t[e]));return this}return this.each(rt(t,e))},W.style=function(t,e,r){var n=arguments.length;if(n<3){if("string"!=typeof t){for(r in n<2&&(e=""),t)this.each(it(r,t[r],e));return this}if(n<2){var i=this.node();return o(i).getComputedStyle(i,null).getPropertyValue(t)}r=""}return this.each(it(t,e,r))},W.property=function(t,e){if(arguments.length<2){if("string"==typeof t)return this.node()[t];for(e in t)this.each(at(e,t[e]));return this}return this.each(at(t,e))},W.text=function(t){return arguments.length?this.each("function"==typeof t?function(){var e=t.apply(this,arguments);this.textContent=null==e?"":e}:null==t?function(){this.textContent=""}:function(){this.textContent=t}):this.node().textContent},W.html=function(t){return arguments.length?this.each("function"==typeof t?function(){var e=t.apply(this,arguments);this.innerHTML=null==e?"":e}:null==t?function(){this.innerHTML=""}:function(){this.innerHTML=t}):this.node().innerHTML},W.append=function(t){return t=ot(t),this.select(function(){return this.appendChild(t.apply(this,arguments))})},W.insert=function(t,e){return t=ot(t),e=X(e),this.select(function(){return this.insertBefore(t.apply(this,arguments),e.apply(this,arguments)||null)})},W.remove=function(){return this.each(st)},W.data=function(t,e){var r,n,i=-1,a=this.length;if(!arguments.length){for(t=new Array(a=(r=this[0]).length);++i<a;)(n=r[i])&&(t[i]=n.__data__);return t}function o(t,r){var n,i,a,o=t.length,u=r.length,h=Math.min(o,u),f=new Array(u),p=new Array(u),d=new Array(o);if(e){var g,v=new b,m=new Array(o);for(n=-1;++n<o;)(i=t[n])&&(v.has(g=e.call(i,i.__data__,n))?d[n]=i:v.set(g,i),m[n]=g);for(n=-1;++n<u;)(i=v.get(g=e.call(r,a=r[n],n)))?!0!==i&&(f[n]=i,i.__data__=a):p[n]=lt(a),v.set(g,!0);for(n=-1;++n<o;)n in m&&!0!==v.get(m[n])&&(d[n]=t[n])}else{for(n=-1;++n<h;)i=t[n],a=r[n],i?(i.__data__=a,f[n]=i):p[n]=lt(a);for(;n<u;++n)p[n]=lt(r[n]);for(;n<o;++n)d[n]=t[n]}p.update=f,p.parentNode=f.parentNode=d.parentNode=t.parentNode,s.push(p),l.push(f),c.push(d)}var s=ht([]),l=q([]),c=q([]);if("function"==typeof t)for(;++i<a;)o(r=this[i],t.call(r,r.parentNode.__data__,i));else for(;++i<a;)o(r=this[i],t);return l.enter=function(){return s},l.exit=function(){return c},l},W.datum=function(t){return arguments.length?this.property("__data__",t):this.property("__data__")},W.filter=function(t){var e,r,n,i=[];"function"!=typeof t&&(t=ct(t));for(var a=0,o=this.length;a<o;a++){i.push(e=[]),e.parentNode=(r=this[a]).parentNode;for(var s=0,l=r.length;s<l;s++)(n=r[s])&&t.call(n,n.__data__,s,a)&&e.push(n)}return q(i)},W.order=function(){for(var t=-1,e=this.length;++t<e;)for(var r,n=this[t],i=n.length-1,a=n[i];--i>=0;)(r=n[i])&&(a&&a!==r.nextSibling&&a.parentNode.insertBefore(r,a),a=r);return this},W.sort=function(t){t=function(t){arguments.length||(t=f);return function(e,r){return e&&r?t(e.__data__,r.__data__):!e-!r}}.apply(this,arguments);for(var e=-1,r=this.length;++e<r;)this[e].sort(t);return this.order()},W.each=function(t){return ut(this,function(e,r,n){t.call(e,e.__data__,r,n)})},W.call=function(t){var e=n(arguments);return t.apply(e[0]=this,e),this},W.empty=function(){return!this.node()},W.node=function(){for(var t=0,e=this.length;t<e;t++)for(var r=this[t],n=0,i=r.length;n<i;n++){var a=r[n];if(a)return a}return null},W.size=function(){var t=0;return ut(this,function(){++t}),t};var ft=[];function pt(e,r,i){var a="__on"+e,o=e.indexOf("."),s=gt;o>0&&(e=e.slice(0,o));var l=dt.get(e);function c(){var t=this[a];t&&(this.removeEventListener(e,t,t.$),delete this[a])}return l&&(e=l,s=vt),o?r?function(){var t=s(r,n(arguments));c.call(this),this.addEventListener(e,this[a]=t,t.$=i),t._=r}:c:r?P:function(){var r,n=new RegExp("^__on([^.]+)"+t.requote(e)+"$");for(var i in this)if(r=i.match(n)){var a=this[i];this.removeEventListener(r[1],a,a.$),delete this[i]}}}t.selection.enter=ht,t.selection.enter.prototype=ft,ft.append=W.append,ft.empty=W.empty,ft.node=W.node,ft.call=W.call,ft.size=W.size,ft.select=function(t){for(var e,r,n,i,a,o=[],s=-1,l=this.length;++s<l;){n=(i=this[s]).update,o.push(e=[]),e.parentNode=i.parentNode;for(var c=-1,u=i.length;++c<u;)(a=i[c])?(e.push(n[c]=r=t.call(i.parentNode,a.__data__,c,s)),r.__data__=a.__data__):e.push(null)}return q(o)},ft.insert=function(t,e){var r,n,i;return arguments.length<2&&(r=this,e=function(t,e,a){var o,s=r[a].update,l=s.length;for(a!=i&&(i=a,n=0),e>=n&&(n=e+1);!(o=s[n])&&++n<l;);return o}),W.insert.call(this,t,e)},t.select=function(t){var e;return"string"==typeof t?(e=[H(t,i)]).parentNode=i.documentElement:(e=[t]).parentNode=a(t),q([e])},t.selectAll=function(t){var e;return"string"==typeof t?(e=n(G(t,i))).parentNode=i.documentElement:(e=n(t)).parentNode=null,q([e])},W.on=function(t,e,r){var n=arguments.length;if(n<3){if("string"!=typeof t){for(r in n<2&&(e=!1),t)this.each(pt(r,t[r],e));return this}if(n<2)return(n=this.node()["__on"+t])&&n._;r=!1}return this.each(pt(t,e,r))};var dt=t.map({mouseenter:"mouseover",mouseleave:"mouseout"});function gt(e,r){return function(n){var i=t.event;t.event=n,r[0]=this.__data__;try{e.apply(this,r)}finally{t.event=i}}}function vt(t,e){var r=gt(t,e);return function(t){var e=t.relatedTarget;e&&(e===this||8&e.compareDocumentPosition(this))||r.call(this,t)}}i&&dt.forEach(function(t){"on"+t in i&&dt.remove(t)});var mt,yt=0;function xt(e){var r=".dragsuppress-"+ ++yt,n="click"+r,i=t.select(o(e)).on("touchmove"+r,B).on("dragstart"+r,B).on("selectstart"+r,B);if(null==mt&&(mt=!("onselectstart"in e)&&I(e.style,"userSelect")),mt){var s=a(e).style,l=s[mt];s[mt]="none"}return function(t){if(i.on(r,null),mt&&(s[mt]=l),t){var e=function(){i.on(n,null)};i.on(n,function(){B(),e()},!0),setTimeout(e,0)}}}t.mouse=function(t){return _t(t,N())};var bt=this.navigator&&/WebKit/.test(this.navigator.userAgent)?-1:0;function _t(e,r){r.changedTouches&&(r=r.changedTouches[0]);var n=e.ownerSVGElement||e;if(n.createSVGPoint){var i=n.createSVGPoint();if(bt<0){var a=o(e);if(a.scrollX||a.scrollY){var s=(n=t.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important"))[0][0].getScreenCTM();bt=!(s.f||s.e),n.remove()}}return bt?(i.x=r.pageX,i.y=r.pageY):(i.x=r.clientX,i.y=r.clientY),[(i=i.matrixTransform(e.getScreenCTM().inverse())).x,i.y]}var l=e.getBoundingClientRect();return[r.clientX-l.left-e.clientLeft,r.clientY-l.top-e.clientTop]}function wt(){return t.event.changedTouches[0].identifier}t.touch=function(t,e,r){if(arguments.length<3&&(r=e,e=N().changedTouches),e)for(var n,i=0,a=e.length;i<a;++i)if((n=e[i]).identifier===r)return _t(t,n)},t.behavior.drag=function(){var e=j(a,"drag","dragstart","dragend"),r=null,n=s(P,t.mouse,o,"mousemove","mouseup"),i=s(wt,t.touch,z,"touchmove","touchend");function a(){this.on("mousedown.drag",n).on("touchstart.drag",i)}function s(n,i,a,o,s){return function(){var l,c=t.event.target.correspondingElement||t.event.target,u=this.parentNode,h=e.of(this,arguments),f=0,p=n(),d=".drag"+(null==p?"":"-"+p),g=t.select(a(c)).on(o+d,function(){var t,e,r=i(u,p);if(!r)return;t=r[0]-m[0],e=r[1]-m[1],f|=t|e,m=r,h({type:"drag",x:r[0]+l[0],y:r[1]+l[1],dx:t,dy:e})}).on(s+d,function(){if(!i(u,p))return;g.on(o+d,null).on(s+d,null),v(f),h({type:"dragend"})}),v=xt(c),m=i(u,p);l=r?[(l=r.apply(this,arguments)).x-m[0],l.y-m[1]]:[0,0],h({type:"dragstart"})}}return a.origin=function(t){return arguments.length?(r=t,a):r},t.rebind(a,e,"on")},t.touches=function(t,e){return arguments.length<2&&(e=N().touches),e?n(e).map(function(e){var r=_t(t,e);return r.identifier=e.identifier,r}):[]};var kt=1e-6,At=kt*kt,Mt=Math.PI,Tt=2*Mt,St=Tt-kt,Et=Mt/2,Ct=Mt/180,Lt=180/Mt;function zt(t){return t>0?1:t<0?-1:0}function Ot(t,e,r){return(e[0]-t[0])*(r[1]-t[1])-(e[1]-t[1])*(r[0]-t[0])}function It(t){return t>1?0:t<-1?Mt:Math.acos(t)}function Dt(t){return t>1?Et:t<-1?-Et:Math.asin(t)}function Pt(t){return((t=Math.exp(t))+1/t)/2}function Rt(t){return(t=Math.sin(t/2))*t}var Ft=Math.SQRT2;t.interpolateZoom=function(t,e){var r,n,i=t[0],a=t[1],o=t[2],s=e[0],l=e[1],c=e[2],u=s-i,h=l-a,f=u*u+h*h;if(f<At)n=Math.log(c/o)/Ft,r=function(t){return[i+t*u,a+t*h,o*Math.exp(Ft*t*n)]};else{var p=Math.sqrt(f),d=(c*c-o*o+4*f)/(2*o*2*p),g=(c*c-o*o-4*f)/(2*c*2*p),v=Math.log(Math.sqrt(d*d+1)-d),m=Math.log(Math.sqrt(g*g+1)-g);n=(m-v)/Ft,r=function(t){var e,r=t*n,s=Pt(v),l=o/(2*p)*(s*(e=Ft*r+v,((e=Math.exp(2*e))-1)/(e+1))-function(t){return((t=Math.exp(t))-1/t)/2}(v));return[i+l*u,a+l*h,o*s/Pt(Ft*r+v)]}}return r.duration=1e3*n,r},t.behavior.zoom=function(){var e,r,n,a,s,l,c,u,h,f={x:0,y:0,k:1},p=[960,500],d=jt,g=250,v=0,m="mousedown.zoom",y="mousemove.zoom",x="mouseup.zoom",b="touchstart.zoom",_=j(w,"zoomstart","zoom","zoomend");function w(t){t.on(m,z).on(Nt+".zoom",I).on("dblclick.zoom",D).on(b,O)}function k(t){return[(t[0]-f.x)/f.k,(t[1]-f.y)/f.k]}function A(t){f.k=Math.max(d[0],Math.min(d[1],t))}function M(t,e){e=function(t){return[t[0]*f.k+f.x,t[1]*f.k+f.y]}(e),f.x+=t[0]-e[0],f.y+=t[1]-e[1]}function T(e,n,i,a){e.__chart__={x:f.x,y:f.y,k:f.k},A(Math.pow(2,a)),M(r=n,i),e=t.select(e),g>0&&(e=e.transition().duration(g)),e.call(w.event)}function S(){c&&c.domain(l.range().map(function(t){return(t-f.x)/f.k}).map(l.invert)),h&&h.domain(u.range().map(function(t){return(t-f.y)/f.k}).map(u.invert))}function E(t){v++||t({type:"zoomstart"})}function C(t){S(),t({type:"zoom",scale:f.k,translate:[f.x,f.y]})}function L(t){--v||(t({type:"zoomend"}),r=null)}function z(){var e=this,r=_.of(e,arguments),n=0,i=t.select(o(e)).on(y,function(){n=1,M(t.mouse(e),a),C(r)}).on(x,function(){i.on(y,null).on(x,null),s(n),L(r)}),a=k(t.mouse(e)),s=xt(e);hs.call(e),E(r)}function O(){var e,r=this,n=_.of(r,arguments),i={},a=0,o=".zoom-"+t.event.changedTouches[0].identifier,l="touchmove"+o,c="touchend"+o,u=[],h=t.select(r),p=xt(r);function d(){var n=t.touches(r);return e=f.k,n.forEach(function(t){t.identifier in i&&(i[t.identifier]=k(t))}),n}function g(){var e=t.event.target;t.select(e).on(l,v).on(c,y),u.push(e);for(var n=t.event.changedTouches,o=0,h=n.length;o<h;++o)i[n[o].identifier]=null;var p=d(),g=Date.now();if(1===p.length){if(g-s<500){var m=p[0];T(r,m,i[m.identifier],Math.floor(Math.log(f.k)/Math.LN2)+1),B()}s=g}else if(p.length>1){m=p[0];var x=p[1],b=m[0]-x[0],_=m[1]-x[1];a=b*b+_*_}}function v(){var o,l,c,u,h=t.touches(r);hs.call(r);for(var f=0,p=h.length;f<p;++f,u=null)if(c=h[f],u=i[c.identifier]){if(l)break;o=c,l=u}if(u){var d=(d=c[0]-o[0])*d+(d=c[1]-o[1])*d,g=a&&Math.sqrt(d/a);o=[(o[0]+c[0])/2,(o[1]+c[1])/2],l=[(l[0]+u[0])/2,(l[1]+u[1])/2],A(g*e)}s=null,M(o,l),C(n)}function y(){if(t.event.touches.length){for(var e=t.event.changedTouches,r=0,a=e.length;r<a;++r)delete i[e[r].identifier];for(var s in i)return void d()}t.selectAll(u).on(o,null),h.on(m,z).on(b,O),p(),L(n)}g(),E(n),h.on(m,null).on(b,g)}function I(){var i=_.of(this,arguments);a?clearTimeout(a):(hs.call(this),e=k(r=n||t.mouse(this)),E(i)),a=setTimeout(function(){a=null,L(i)},50),B(),A(Math.pow(2,.002*Bt())*f.k),M(r,e),C(i)}function D(){var e=t.mouse(this),r=Math.log(f.k)/Math.LN2;T(this,e,k(e),t.event.shiftKey?Math.ceil(r)-1:Math.floor(r)+1)}return Nt||(Nt="onwheel"in i?(Bt=function(){return-t.event.deltaY*(t.event.deltaMode?120:1)},"wheel"):"onmousewheel"in i?(Bt=function(){return t.event.wheelDelta},"mousewheel"):(Bt=function(){return-t.event.detail},"MozMousePixelScroll")),w.event=function(e){e.each(function(){var e=_.of(this,arguments),n=f;ds?t.select(this).transition().each("start.zoom",function(){f=this.__chart__||{x:0,y:0,k:1},E(e)}).tween("zoom:zoom",function(){var i=p[0],a=p[1],o=r?r[0]:i/2,s=r?r[1]:a/2,l=t.interpolateZoom([(o-f.x)/f.k,(s-f.y)/f.k,i/f.k],[(o-n.x)/n.k,(s-n.y)/n.k,i/n.k]);return function(t){var r=l(t),n=i/r[2];this.__chart__=f={x:o-r[0]*n,y:s-r[1]*n,k:n},C(e)}}).each("interrupt.zoom",function(){L(e)}).each("end.zoom",function(){L(e)}):(this.__chart__=f,E(e),C(e),L(e))})},w.translate=function(t){return arguments.length?(f={x:+t[0],y:+t[1],k:f.k},S(),w):[f.x,f.y]},w.scale=function(t){return arguments.length?(f={x:f.x,y:f.y,k:null},A(+t),S(),w):f.k},w.scaleExtent=function(t){return arguments.length?(d=null==t?jt:[+t[0],+t[1]],w):d},w.center=function(t){return arguments.length?(n=t&&[+t[0],+t[1]],w):n},w.size=function(t){return arguments.length?(p=t&&[+t[0],+t[1]],w):p},w.duration=function(t){return arguments.length?(g=+t,w):g},w.x=function(t){return arguments.length?(c=t,l=t.copy(),f={x:0,y:0,k:1},w):c},w.y=function(t){return arguments.length?(h=t,u=t.copy(),f={x:0,y:0,k:1},w):h},t.rebind(w,_,"on")};var Bt,Nt,jt=[0,1/0];function Vt(){}function Ut(t,e,r){return this instanceof Ut?(this.h=+t,this.s=+e,void(this.l=+r)):arguments.length<2?t instanceof Ut?new Ut(t.h,t.s,t.l):ue(""+t,he,Ut):new Ut(t,e,r)}t.color=Vt,Vt.prototype.toString=function(){return this.rgb()+""},t.hsl=Ut;var qt=Ut.prototype=new Vt;function Ht(t,e,r){var n,i;function a(t){return Math.round(255*function(t){return t>360?t-=360:t<0&&(t+=360),t<60?n+(i-n)*t/60:t<180?i:t<240?n+(i-n)*(240-t)/60:n}(t))}return t=isNaN(t)?0:(t%=360)<0?t+360:t,e=isNaN(e)?0:e<0?0:e>1?1:e,n=2*(r=r<0?0:r>1?1:r)-(i=r<=.5?r*(1+e):r+e-r*e),new ae(a(t+120),a(t),a(t-120))}function Gt(e,r,n){return this instanceof Gt?(this.h=+e,this.c=+r,void(this.l=+n)):arguments.length<2?e instanceof Gt?new Gt(e.h,e.c,e.l):ee(e instanceof Xt?e.l:(e=fe((e=t.rgb(e)).r,e.g,e.b)).l,e.a,e.b):new Gt(e,r,n)}qt.brighter=function(t){return t=Math.pow(.7,arguments.length?t:1),new Ut(this.h,this.s,this.l/t)},qt.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),new Ut(this.h,this.s,t*this.l)},qt.rgb=function(){return Ht(this.h,this.s,this.l)},t.hcl=Gt;var Yt=Gt.prototype=new Vt;function Wt(t,e,r){return isNaN(t)&&(t=0),isNaN(e)&&(e=0),new Xt(r,Math.cos(t*=Ct)*e,Math.sin(t)*e)}function Xt(t,e,r){return this instanceof Xt?(this.l=+t,this.a=+e,void(this.b=+r)):arguments.length<2?t instanceof Xt?new Xt(t.l,t.a,t.b):t instanceof Gt?Wt(t.h,t.c,t.l):fe((t=ae(t)).r,t.g,t.b):new Xt(t,e,r)}Yt.brighter=function(t){return new Gt(this.h,this.c,Math.min(100,this.l+Zt*(arguments.length?t:1)))},Yt.darker=function(t){return new Gt(this.h,this.c,Math.max(0,this.l-Zt*(arguments.length?t:1)))},Yt.rgb=function(){return Wt(this.h,this.c,this.l).rgb()},t.lab=Xt;var Zt=18,$t=.95047,Jt=1,Kt=1.08883,Qt=Xt.prototype=new Vt;function te(t,e,r){var n=(t+16)/116,i=n+e/500,a=n-r/200;return new ae(ie(3.2404542*(i=re(i)*$t)-1.5371385*(n=re(n)*Jt)-.4985314*(a=re(a)*Kt)),ie(-.969266*i+1.8760108*n+.041556*a),ie(.0556434*i-.2040259*n+1.0572252*a))}function ee(t,e,r){return t>0?new Gt(Math.atan2(r,e)*Lt,Math.sqrt(e*e+r*r),t):new Gt(NaN,NaN,t)}function re(t){return t>.206893034?t*t*t:(t-4/29)/7.787037}function ne(t){return t>.008856?Math.pow(t,1/3):7.787037*t+4/29}function ie(t){return Math.round(255*(t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055))}function ae(t,e,r){return this instanceof ae?(this.r=~~t,this.g=~~e,void(this.b=~~r)):arguments.length<2?t instanceof ae?new ae(t.r,t.g,t.b):ue(""+t,ae,Ht):new ae(t,e,r)}function oe(t){return new ae(t>>16,t>>8&255,255&t)}function se(t){return oe(t)+""}Qt.brighter=function(t){return new Xt(Math.min(100,this.l+Zt*(arguments.length?t:1)),this.a,this.b)},Qt.darker=function(t){return new Xt(Math.max(0,this.l-Zt*(arguments.length?t:1)),this.a,this.b)},Qt.rgb=function(){return te(this.l,this.a,this.b)},t.rgb=ae;var le=ae.prototype=new Vt;function ce(t){return t<16?"0"+Math.max(0,t).toString(16):Math.min(255,t).toString(16)}function ue(t,e,r){var n,i,a,o=0,s=0,l=0;if(n=/([a-z]+)\((.*)\)/.exec(t=t.toLowerCase()))switch(i=n[2].split(","),n[1]){case"hsl":return r(parseFloat(i[0]),parseFloat(i[1])/100,parseFloat(i[2])/100);case"rgb":return e(de(i[0]),de(i[1]),de(i[2]))}return(a=ge.get(t))?e(a.r,a.g,a.b):(null==t||"#"!==t.charAt(0)||isNaN(a=parseInt(t.slice(1),16))||(4===t.length?(o=(3840&a)>>4,o|=o>>4,s=240&a,s|=s>>4,l=15&a,l|=l<<4):7===t.length&&(o=(16711680&a)>>16,s=(65280&a)>>8,l=255&a)),e(o,s,l))}function he(t,e,r){var n,i,a=Math.min(t/=255,e/=255,r/=255),o=Math.max(t,e,r),s=o-a,l=(o+a)/2;return s?(i=l<.5?s/(o+a):s/(2-o-a),n=t==o?(e-r)/s+(e<r?6:0):e==o?(r-t)/s+2:(t-e)/s+4,n*=60):(n=NaN,i=l>0&&l<1?0:n),new Ut(n,i,l)}function fe(t,e,r){var n=ne((.4124564*(t=pe(t))+.3575761*(e=pe(e))+.1804375*(r=pe(r)))/$t),i=ne((.2126729*t+.7151522*e+.072175*r)/Jt);return Xt(116*i-16,500*(n-i),200*(i-ne((.0193339*t+.119192*e+.9503041*r)/Kt)))}function pe(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function de(t){var e=parseFloat(t);return"%"===t.charAt(t.length-1)?Math.round(2.55*e):e}le.brighter=function(t){t=Math.pow(.7,arguments.length?t:1);var e=this.r,r=this.g,n=this.b,i=30;return e||r||n?(e&&e<i&&(e=i),r&&r<i&&(r=i),n&&n<i&&(n=i),new ae(Math.min(255,e/t),Math.min(255,r/t),Math.min(255,n/t))):new ae(i,i,i)},le.darker=function(t){return new ae((t=Math.pow(.7,arguments.length?t:1))*this.r,t*this.g,t*this.b)},le.hsl=function(){return he(this.r,this.g,this.b)},le.toString=function(){return"#"+ce(this.r)+ce(this.g)+ce(this.b)};var ge=t.map({aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074});function ve(t){return"function"==typeof t?t:function(){return t}}function me(t){return function(e,r,n){return 2===arguments.length&&"function"==typeof r&&(n=r,r=null),ye(e,r,t,n)}}function ye(e,r,i,a){var o={},s=t.dispatch("beforesend","progress","load","error"),l={},c=new XMLHttpRequest,u=null;function h(){var t,e=c.status;if(!e&&function(t){var e=t.responseType;return e&&"text"!==e?t.response:t.responseText}(c)||e>=200&&e<300||304===e){try{t=i.call(o,c)}catch(t){return void s.error.call(o,t)}s.load.call(o,t)}else s.error.call(o,c)}return!this.XDomainRequest||"withCredentials"in c||!/^(http(s)?:)?\/\//.test(e)||(c=new XDomainRequest),"onload"in c?c.onload=c.onerror=h:c.onreadystatechange=function(){c.readyState>3&&h()},c.onprogress=function(e){var r=t.event;t.event=e;try{s.progress.call(o,c)}finally{t.event=r}},o.header=function(t,e){return t=(t+"").toLowerCase(),arguments.length<2?l[t]:(null==e?delete l[t]:l[t]=e+"",o)},o.mimeType=function(t){return arguments.length?(r=null==t?null:t+"",o):r},o.responseType=function(t){return arguments.length?(u=t,o):u},o.response=function(t){return i=t,o},["get","post"].forEach(function(t){o[t]=function(){return o.send.apply(o,[t].concat(n(arguments)))}}),o.send=function(t,n,i){if(2===arguments.length&&"function"==typeof n&&(i=n,n=null),c.open(t,e,!0),null==r||"accept"in l||(l.accept=r+",*/*"),c.setRequestHeader)for(var a in l)c.setRequestHeader(a,l[a]);return null!=r&&c.overrideMimeType&&c.overrideMimeType(r),null!=u&&(c.responseType=u),null!=i&&o.on("error",i).on("load",function(t){i(null,t)}),s.beforesend.call(o,c),c.send(null==n?null:n),o},o.abort=function(){return c.abort(),o},t.rebind(o,s,"on"),null==a?o:o.get(function(t){return 1===t.length?function(e,r){t(null==e?r:null)}:t}(a))}ge.forEach(function(t,e){ge.set(t,oe(e))}),t.functor=ve,t.xhr=me(z),t.dsv=function(t,e){var r=new RegExp('["'+t+"\n]"),n=t.charCodeAt(0);function i(t,r,n){arguments.length<3&&(n=r,r=null);var i=ye(t,e,null==r?a:o(r),n);return i.row=function(t){return arguments.length?i.response(null==(r=t)?a:o(t)):r},i}function a(t){return i.parse(t.responseText)}function o(t){return function(e){return i.parse(e.responseText,t)}}function s(e){return e.map(l).join(t)}function l(t){return r.test(t)?'"'+t.replace(/\"/g,'""')+'"':t}return i.parse=function(t,e){var r;return i.parseRows(t,function(t,n){if(r)return r(t,n-1);var i=new Function("d","return {"+t.map(function(t,e){return JSON.stringify(t)+": d["+e+"]"}).join(",")+"}");r=e?function(t,r){return e(i(t),r)}:i})},i.parseRows=function(t,e){var r,i,a={},o={},s=[],l=t.length,c=0,u=0;function h(){if(c>=l)return o;if(i)return i=!1,a;var e=c;if(34===t.charCodeAt(e)){for(var r=e;r++<l;)if(34===t.charCodeAt(r)){if(34!==t.charCodeAt(r+1))break;++r}return c=r+2,13===(s=t.charCodeAt(r+1))?(i=!0,10===t.charCodeAt(r+2)&&++c):10===s&&(i=!0),t.slice(e+1,r).replace(/""/g,'"')}for(;c<l;){var s,u=1;if(10===(s=t.charCodeAt(c++)))i=!0;else if(13===s)i=!0,10===t.charCodeAt(c)&&(++c,++u);else if(s!==n)continue;return t.slice(e,c-u)}return t.slice(e)}for(;(r=h())!==o;){for(var f=[];r!==a&&r!==o;)f.push(r),r=h();e&&null==(f=e(f,u++))||s.push(f)}return s},i.format=function(e){if(Array.isArray(e[0]))return i.formatRows(e);var r=new L,n=[];return e.forEach(function(t){for(var e in t)r.has(e)||n.push(r.add(e))}),[n.map(l).join(t)].concat(e.map(function(e){return n.map(function(t){return l(e[t])}).join(t)})).join("\n")},i.formatRows=function(t){return t.map(s).join("\n")},i},t.csv=t.dsv(",","text/csv"),t.tsv=t.dsv("\t","text/tab-separated-values");var xe,be,_e,we,ke=this[I(this,"requestAnimationFrame")]||function(t){setTimeout(t,17)};function Ae(t,e,r){var n=arguments.length;n<2&&(e=0),n<3&&(r=Date.now());var i={c:t,t:r+e,n:null};return be?be.n=i:xe=i,be=i,_e||(we=clearTimeout(we),_e=1,ke(Me)),i}function Me(){var t=Te(),e=Se()-t;e>24?(isFinite(e)&&(clearTimeout(we),we=setTimeout(Me,e)),_e=0):(_e=1,ke(Me))}function Te(){for(var t=Date.now(),e=xe;e;)t>=e.t&&e.c(t-e.t)&&(e.c=null),e=e.n;return t}function Se(){for(var t,e=xe,r=1/0;e;)e.c?(e.t<r&&(r=e.t),e=(t=e).n):e=t?t.n=e.n:xe=e.n;return be=t,r}function Ee(t,e){return e-(t?Math.ceil(Math.log(t)/Math.LN10):1)}t.timer=function(){Ae.apply(this,arguments)},t.timer.flush=function(){Te(),Se()},t.round=function(t,e){return e?Math.round(t*(e=Math.pow(10,e)))/e:Math.round(t)};var Ce=["y","z","a","f","p","n","\xb5","m","","k","M","G","T","P","E","Z","Y"].map(function(t,e){var r=Math.pow(10,3*y(8-e));return{scale:e>8?function(t){return t/r}:function(t){return t*r},symbol:t}});t.formatPrefix=function(e,r){var n=0;return(e=+e)&&(e<0&&(e*=-1),r&&(e=t.round(e,Ee(e,r))),n=1+Math.floor(1e-12+Math.log(e)/Math.LN10),n=Math.max(-24,Math.min(24,3*Math.floor((n-1)/3)))),Ce[8+n/3]};var Le=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,ze=t.map({b:function(t){return t.toString(2)},c:function(t){return String.fromCharCode(t)},o:function(t){return t.toString(8)},x:function(t){return t.toString(16)},X:function(t){return t.toString(16).toUpperCase()},g:function(t,e){return t.toPrecision(e)},e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},r:function(e,r){return(e=t.round(e,Ee(e,r))).toFixed(Math.max(0,Math.min(20,Ee(e*(1+1e-15),r))))}});function Oe(t){return t+""}var Ie=t.time={},De=Date;function Pe(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}Pe.prototype={getDate:function(){return this._.getUTCDate()},getDay:function(){return this._.getUTCDay()},getFullYear:function(){return this._.getUTCFullYear()},getHours:function(){return this._.getUTCHours()},getMilliseconds:function(){return this._.getUTCMilliseconds()},getMinutes:function(){return this._.getUTCMinutes()},getMonth:function(){return this._.getUTCMonth()},getSeconds:function(){return this._.getUTCSeconds()},getTime:function(){return this._.getTime()},getTimezoneOffset:function(){return 0},valueOf:function(){return this._.valueOf()},setDate:function(){Re.setUTCDate.apply(this._,arguments)},setDay:function(){Re.setUTCDay.apply(this._,arguments)},setFullYear:function(){Re.setUTCFullYear.apply(this._,arguments)},setHours:function(){Re.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){Re.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){Re.setUTCMinutes.apply(this._,arguments)},setMonth:function(){Re.setUTCMonth.apply(this._,arguments)},setSeconds:function(){Re.setUTCSeconds.apply(this._,arguments)},setTime:function(){Re.setTime.apply(this._,arguments)}};var Re=Date.prototype;function Fe(t,e,r){function n(e){var r=t(e),n=a(r,1);return e-r<n-e?r:n}function i(r){return e(r=t(new De(r-1)),1),r}function a(t,r){return e(t=new De(+t),r),t}function o(t,n,a){var o=i(t),s=[];if(a>1)for(;o<n;)r(o)%a||s.push(new Date(+o)),e(o,1);else for(;o<n;)s.push(new Date(+o)),e(o,1);return s}t.floor=t,t.round=n,t.ceil=i,t.offset=a,t.range=o;var s=t.utc=Be(t);return s.floor=s,s.round=Be(n),s.ceil=Be(i),s.offset=Be(a),s.range=function(t,e,r){try{De=Pe;var n=new Pe;return n._=t,o(n,e,r)}finally{De=Date}},t}function Be(t){return function(e,r){try{De=Pe;var n=new Pe;return n._=e,t(n,r)._}finally{De=Date}}}Ie.year=Fe(function(t){return(t=Ie.day(t)).setMonth(0,1),t},function(t,e){t.setFullYear(t.getFullYear()+e)},function(t){return t.getFullYear()}),Ie.years=Ie.year.range,Ie.years.utc=Ie.year.utc.range,Ie.day=Fe(function(t){var e=new De(2e3,0);return e.setFullYear(t.getFullYear(),t.getMonth(),t.getDate()),e},function(t,e){t.setDate(t.getDate()+e)},function(t){return t.getDate()-1}),Ie.days=Ie.day.range,Ie.days.utc=Ie.day.utc.range,Ie.dayOfYear=function(t){var e=Ie.year(t);return Math.floor((t-e-6e4*(t.getTimezoneOffset()-e.getTimezoneOffset()))/864e5)},["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].forEach(function(t,e){e=7-e;var r=Ie[t]=Fe(function(t){return(t=Ie.day(t)).setDate(t.getDate()-(t.getDay()+e)%7),t},function(t,e){t.setDate(t.getDate()+7*Math.floor(e))},function(t){var r=Ie.year(t).getDay();return Math.floor((Ie.dayOfYear(t)+(r+e)%7)/7)-(r!==e)});Ie[t+"s"]=r.range,Ie[t+"s"].utc=r.utc.range,Ie[t+"OfYear"]=function(t){var r=Ie.year(t).getDay();return Math.floor((Ie.dayOfYear(t)+(r+e)%7)/7)}}),Ie.week=Ie.sunday,Ie.weeks=Ie.sunday.range,Ie.weeks.utc=Ie.sunday.utc.range,Ie.weekOfYear=Ie.sundayOfYear;var Ne={"-":"",_:" ",0:"0"},je=/^\s*\d+/,Ve=/^%/;function Ue(t,e,r){var n=t<0?"-":"",i=(n?-t:t)+"",a=i.length;return n+(a<r?new Array(r-a+1).join(e)+i:i)}function qe(e){return new RegExp("^(?:"+e.map(t.requote).join("|")+")","i")}function He(t){for(var e=new b,r=-1,n=t.length;++r<n;)e.set(t[r].toLowerCase(),r);return e}function Ge(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+1));return n?(t.w=+n[0],r+n[0].length):-1}function Ye(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r));return n?(t.U=+n[0],r+n[0].length):-1}function We(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r));return n?(t.W=+n[0],r+n[0].length):-1}function Xe(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+4));return n?(t.y=+n[0],r+n[0].length):-1}function Ze(t,e,r){je.lastIndex=0;var n,i=je.exec(e.slice(r,r+2));return i?(t.y=(n=+i[0])+(n>68?1900:2e3),r+i[0].length):-1}function $e(t,e,r){return/^[+-]\d{4}$/.test(e=e.slice(r,r+5))?(t.Z=-e,r+5):-1}function Je(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function Ke(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function Qe(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+3));return n?(t.j=+n[0],r+n[0].length):-1}function tr(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function er(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function rr(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function nr(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function ir(t){var e=t.getTimezoneOffset(),r=e>0?"-":"+",n=y(e)/60|0,i=y(e)%60;return r+Ue(n,"0",2)+Ue(i,"0",2)}function ar(t,e,r){Ve.lastIndex=0;var n=Ve.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function or(t){for(var e=t.length,r=-1;++r<e;)t[r][0]=this(t[r][0]);return function(e){for(var r=0,n=t[r];!n[1](e);)n=t[++r];return n[0](e)}}t.locale=function(e){return{numberFormat:function(e){var r=e.decimal,n=e.thousands,i=e.grouping,a=e.currency,o=i&&n?function(t,e){for(var r=t.length,a=[],o=0,s=i[0],l=0;r>0&&s>0&&(l+s+1>e&&(s=Math.max(1,e-l)),a.push(t.substring(r-=s,r+s)),!((l+=s+1)>e));)s=i[o=(o+1)%i.length];return a.reverse().join(n)}:z;return function(e){var n=Le.exec(e),i=n[1]||" ",s=n[2]||">",l=n[3]||"-",c=n[4]||"",u=n[5],h=+n[6],f=n[7],p=n[8],d=n[9],g=1,v="",m="",y=!1,x=!0;switch(p&&(p=+p.substring(1)),(u||"0"===i&&"="===s)&&(u=i="0",s="="),d){case"n":f=!0,d="g";break;case"%":g=100,m="%",d="f";break;case"p":g=100,m="%",d="r";break;case"b":case"o":case"x":case"X":"#"===c&&(v="0"+d.toLowerCase());case"c":x=!1;case"d":y=!0,p=0;break;case"s":g=-1,d="r"}"$"===c&&(v=a[0],m=a[1]),"r"!=d||p||(d="g"),null!=p&&("g"==d?p=Math.max(1,Math.min(21,p)):"e"!=d&&"f"!=d||(p=Math.max(0,Math.min(20,p)))),d=ze.get(d)||Oe;var b=u&&f;return function(e){var n=m;if(y&&e%1)return"";var a=e<0||0===e&&1/e<0?(e=-e,"-"):"-"===l?"":l;if(g<0){var c=t.formatPrefix(e,p);e=c.scale(e),n=c.symbol+m}else e*=g;var _,w,k=(e=d(e,p)).lastIndexOf(".");if(k<0){var A=x?e.lastIndexOf("e"):-1;A<0?(_=e,w=""):(_=e.substring(0,A),w=e.substring(A))}else _=e.substring(0,k),w=r+e.substring(k+1);!u&&f&&(_=o(_,1/0));var M=v.length+_.length+w.length+(b?0:a.length),T=M<h?new Array(M=h-M+1).join(i):"";return b&&(_=o(T+_,T.length?h-w.length:1/0)),a+=v,e=_+w,("<"===s?a+e+T:">"===s?T+a+e:"^"===s?T.substring(0,M>>=1)+a+e+T.substring(M):a+(b?e:T+e))+n}}}(e),timeFormat:function(e){var r=e.dateTime,n=e.date,i=e.time,a=e.periods,o=e.days,s=e.shortDays,l=e.months,c=e.shortMonths;function u(t){var e=t.length;function r(r){for(var n,i,a,o=[],s=-1,l=0;++s<e;)37===t.charCodeAt(s)&&(o.push(t.slice(l,s)),null!=(i=Ne[n=t.charAt(++s)])&&(n=t.charAt(++s)),(a=_[n])&&(n=a(r,null==i?"e"===n?" ":"0":i)),o.push(n),l=s+1);return o.push(t.slice(l,s)),o.join("")}return r.parse=function(e){var r={y:1900,m:0,d:1,H:0,M:0,S:0,L:0,Z:null};if(h(r,t,e,0)!=e.length)return null;"p"in r&&(r.H=r.H%12+12*r.p);var n=null!=r.Z&&De!==Pe,i=new(n?Pe:De);return"j"in r?i.setFullYear(r.y,0,r.j):"W"in r||"U"in r?("w"in r||(r.w="W"in r?1:0),i.setFullYear(r.y,0,1),i.setFullYear(r.y,0,"W"in r?(r.w+6)%7+7*r.W-(i.getDay()+5)%7:r.w+7*r.U-(i.getDay()+6)%7)):i.setFullYear(r.y,r.m,r.d),i.setHours(r.H+(r.Z/100|0),r.M+r.Z%100,r.S,r.L),n?i._:i},r.toString=function(){return t},r}function h(t,e,r,n){for(var i,a,o,s=0,l=e.length,c=r.length;s<l;){if(n>=c)return-1;if(37===(i=e.charCodeAt(s++))){if(o=e.charAt(s++),!(a=w[o in Ne?e.charAt(s++):o])||(n=a(t,r,n))<0)return-1}else if(i!=r.charCodeAt(n++))return-1}return n}u.utc=function(t){var e=u(t);function r(t){try{var r=new(De=Pe);return r._=t,e(r)}finally{De=Date}}return r.parse=function(t){try{De=Pe;var r=e.parse(t);return r&&r._}finally{De=Date}},r.toString=e.toString,r},u.multi=u.utc.multi=or;var f=t.map(),p=qe(o),d=He(o),g=qe(s),v=He(s),m=qe(l),y=He(l),x=qe(c),b=He(c);a.forEach(function(t,e){f.set(t.toLowerCase(),e)});var _={a:function(t){return s[t.getDay()]},A:function(t){return o[t.getDay()]},b:function(t){return c[t.getMonth()]},B:function(t){return l[t.getMonth()]},c:u(r),d:function(t,e){return Ue(t.getDate(),e,2)},e:function(t,e){return Ue(t.getDate(),e,2)},H:function(t,e){return Ue(t.getHours(),e,2)},I:function(t,e){return Ue(t.getHours()%12||12,e,2)},j:function(t,e){return Ue(1+Ie.dayOfYear(t),e,3)},L:function(t,e){return Ue(t.getMilliseconds(),e,3)},m:function(t,e){return Ue(t.getMonth()+1,e,2)},M:function(t,e){return Ue(t.getMinutes(),e,2)},p:function(t){return a[+(t.getHours()>=12)]},S:function(t,e){return Ue(t.getSeconds(),e,2)},U:function(t,e){return Ue(Ie.sundayOfYear(t),e,2)},w:function(t){return t.getDay()},W:function(t,e){return Ue(Ie.mondayOfYear(t),e,2)},x:u(n),X:u(i),y:function(t,e){return Ue(t.getFullYear()%100,e,2)},Y:function(t,e){return Ue(t.getFullYear()%1e4,e,4)},Z:ir,"%":function(){return"%"}},w={a:function(t,e,r){g.lastIndex=0;var n=g.exec(e.slice(r));return n?(t.w=v.get(n[0].toLowerCase()),r+n[0].length):-1},A:function(t,e,r){p.lastIndex=0;var n=p.exec(e.slice(r));return n?(t.w=d.get(n[0].toLowerCase()),r+n[0].length):-1},b:function(t,e,r){x.lastIndex=0;var n=x.exec(e.slice(r));return n?(t.m=b.get(n[0].toLowerCase()),r+n[0].length):-1},B:function(t,e,r){m.lastIndex=0;var n=m.exec(e.slice(r));return n?(t.m=y.get(n[0].toLowerCase()),r+n[0].length):-1},c:function(t,e,r){return h(t,_.c.toString(),e,r)},d:Ke,e:Ke,H:tr,I:tr,j:Qe,L:nr,m:Je,M:er,p:function(t,e,r){var n=f.get(e.slice(r,r+=2).toLowerCase());return null==n?-1:(t.p=n,r)},S:rr,U:Ye,w:Ge,W:We,x:function(t,e,r){return h(t,_.x.toString(),e,r)},X:function(t,e,r){return h(t,_.X.toString(),e,r)},y:Ze,Y:Xe,Z:$e,"%":ar};return u}(e)}};var sr=t.locale({decimal:".",thousands:",",grouping:[3],currency:["$",""],dateTime:"%a %b %e %X %Y",date:"%m/%d/%Y",time:"%H:%M:%S",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function lr(){}t.format=sr.numberFormat,t.geo={},lr.prototype={s:0,t:0,add:function(t){ur(t,this.t,cr),ur(cr.s,this.s,this),this.s?this.t+=cr.t:this.s=cr.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var cr=new lr;function ur(t,e,r){var n=r.s=t+e,i=n-t,a=n-i;r.t=t-a+(e-i)}function hr(t,e){t&&pr.hasOwnProperty(t.type)&&pr[t.type](t,e)}t.geo.stream=function(t,e){t&&fr.hasOwnProperty(t.type)?fr[t.type](t,e):hr(t,e)};var fr={Feature:function(t,e){hr(t.geometry,e)},FeatureCollection:function(t,e){for(var r=t.features,n=-1,i=r.length;++n<i;)hr(r[n].geometry,e)}},pr={Sphere:function(t,e){e.sphere()},Point:function(t,e){t=t.coordinates,e.point(t[0],t[1],t[2])},MultiPoint:function(t,e){for(var r=t.coordinates,n=-1,i=r.length;++n<i;)t=r[n],e.point(t[0],t[1],t[2])},LineString:function(t,e){dr(t.coordinates,e,0)},MultiLineString:function(t,e){for(var r=t.coordinates,n=-1,i=r.length;++n<i;)dr(r[n],e,0)},Polygon:function(t,e){gr(t.coordinates,e)},MultiPolygon:function(t,e){for(var r=t.coordinates,n=-1,i=r.length;++n<i;)gr(r[n],e)},GeometryCollection:function(t,e){for(var r=t.geometries,n=-1,i=r.length;++n<i;)hr(r[n],e)}};function dr(t,e,r){var n,i=-1,a=t.length-r;for(e.lineStart();++i<a;)n=t[i],e.point(n[0],n[1],n[2]);e.lineEnd()}function gr(t,e){var r=-1,n=t.length;for(e.polygonStart();++r<n;)dr(t[r],e,1);e.polygonEnd()}t.geo.area=function(e){return vr=0,t.geo.stream(e,Cr),vr};var vr,mr,yr,xr,br,_r,wr,kr,Ar,Mr,Tr,Sr,Er=new lr,Cr={sphere:function(){vr+=4*Mt},point:P,lineStart:P,lineEnd:P,polygonStart:function(){Er.reset(),Cr.lineStart=Lr},polygonEnd:function(){var t=2*Er;vr+=t<0?4*Mt+t:t,Cr.lineStart=Cr.lineEnd=Cr.point=P}};function Lr(){var t,e,r,n,i;function a(t,e){e=e*Ct/2+Mt/4;var a=(t*=Ct)-r,o=a>=0?1:-1,s=o*a,l=Math.cos(e),c=Math.sin(e),u=i*c,h=n*l+u*Math.cos(s),f=u*o*Math.sin(s);Er.add(Math.atan2(f,h)),r=t,n=l,i=c}Cr.point=function(o,s){Cr.point=a,r=(t=o)*Ct,n=Math.cos(s=(e=s)*Ct/2+Mt/4),i=Math.sin(s)},Cr.lineEnd=function(){a(t,e)}}function zr(t){var e=t[0],r=t[1],n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}function Or(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function Ir(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function Dr(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function Pr(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function Rr(t){var e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}function Fr(t){return[Math.atan2(t[1],t[0]),Dt(t[2])]}function Br(t,e){return y(t[0]-e[0])<kt&&y(t[1]-e[1])<kt}t.geo.bounds=function(){var e,r,n,i,a,o,s,l,c,u,h,f={point:p,lineStart:g,lineEnd:v,polygonStart:function(){f.point=m,f.lineStart=x,f.lineEnd=b,c=0,Cr.polygonStart()},polygonEnd:function(){Cr.polygonEnd(),f.point=p,f.lineStart=g,f.lineEnd=v,Er<0?(e=-(n=180),r=-(i=90)):c>kt?i=90:c<-kt&&(r=-90),h[0]=e,h[1]=n}};function p(t,a){u.push(h=[e=t,n=t]),a<r&&(r=a),a>i&&(i=a)}function d(t,o){var s=zr([t*Ct,o*Ct]);if(l){var c=Ir(l,s),u=Ir([c[1],-c[0],0],c);Rr(u),u=Fr(u);var h=t-a,f=h>0?1:-1,d=u[0]*Lt*f,g=y(h)>180;if(g^(f*a<d&&d<f*t))(v=u[1]*Lt)>i&&(i=v);else if(g^(f*a<(d=(d+360)%360-180)&&d<f*t)){var v;(v=-u[1]*Lt)<r&&(r=v)}else o<r&&(r=o),o>i&&(i=o);g?t<a?_(e,t)>_(e,n)&&(n=t):_(t,n)>_(e,n)&&(e=t):n>=e?(t<e&&(e=t),t>n&&(n=t)):t>a?_(e,t)>_(e,n)&&(n=t):_(t,n)>_(e,n)&&(e=t)}else p(t,o);l=s,a=t}function g(){f.point=d}function v(){h[0]=e,h[1]=n,f.point=p,l=null}function m(t,e){if(l){var r=t-a;c+=y(r)>180?r+(r>0?360:-360):r}else o=t,s=e;Cr.point(t,e),d(t,e)}function x(){Cr.lineStart()}function b(){m(o,s),Cr.lineEnd(),y(c)>kt&&(e=-(n=180)),h[0]=e,h[1]=n,l=null}function _(t,e){return(e-=t)<0?e+360:e}function w(t,e){return t[0]-e[0]}function k(t,e){return e[0]<=e[1]?e[0]<=t&&t<=e[1]:t<e[0]||e[1]<t}return function(a){if(i=n=-(e=r=1/0),u=[],t.geo.stream(a,f),c=u.length){u.sort(w);for(var o=1,s=[g=u[0]];o<c;++o)k((p=u[o])[0],g)||k(p[1],g)?(_(g[0],p[1])>_(g[0],g[1])&&(g[1]=p[1]),_(p[0],g[1])>_(g[0],g[1])&&(g[0]=p[0])):s.push(g=p);for(var l,c,p,d=-1/0,g=(o=0,s[c=s.length-1]);o<=c;g=p,++o)p=s[o],(l=_(g[1],p[0]))>d&&(d=l,e=p[0],n=g[1])}return u=h=null,e===1/0||r===1/0?[[NaN,NaN],[NaN,NaN]]:[[e,r],[n,i]]}}(),t.geo.centroid=function(e){mr=yr=xr=br=_r=wr=kr=Ar=Mr=Tr=Sr=0,t.geo.stream(e,Nr);var r=Mr,n=Tr,i=Sr,a=r*r+n*n+i*i;return a<At&&(r=wr,n=kr,i=Ar,yr<kt&&(r=xr,n=br,i=_r),(a=r*r+n*n+i*i)<At)?[NaN,NaN]:[Math.atan2(n,r)*Lt,Dt(i/Math.sqrt(a))*Lt]};var Nr={sphere:P,point:jr,lineStart:Ur,lineEnd:qr,polygonStart:function(){Nr.lineStart=Hr},polygonEnd:function(){Nr.lineStart=Ur}};function jr(t,e){t*=Ct;var r=Math.cos(e*=Ct);Vr(r*Math.cos(t),r*Math.sin(t),Math.sin(e))}function Vr(t,e,r){xr+=(t-xr)/++mr,br+=(e-br)/mr,_r+=(r-_r)/mr}function Ur(){var t,e,r;function n(n,i){n*=Ct;var a=Math.cos(i*=Ct),o=a*Math.cos(n),s=a*Math.sin(n),l=Math.sin(i),c=Math.atan2(Math.sqrt((c=e*l-r*s)*c+(c=r*o-t*l)*c+(c=t*s-e*o)*c),t*o+e*s+r*l);yr+=c,wr+=c*(t+(t=o)),kr+=c*(e+(e=s)),Ar+=c*(r+(r=l)),Vr(t,e,r)}Nr.point=function(i,a){i*=Ct;var o=Math.cos(a*=Ct);t=o*Math.cos(i),e=o*Math.sin(i),r=Math.sin(a),Nr.point=n,Vr(t,e,r)}}function qr(){Nr.point=jr}function Hr(){var t,e,r,n,i;function a(t,e){t*=Ct;var a=Math.cos(e*=Ct),o=a*Math.cos(t),s=a*Math.sin(t),l=Math.sin(e),c=n*l-i*s,u=i*o-r*l,h=r*s-n*o,f=Math.sqrt(c*c+u*u+h*h),p=r*o+n*s+i*l,d=f&&-It(p)/f,g=Math.atan2(f,p);Mr+=d*c,Tr+=d*u,Sr+=d*h,yr+=g,wr+=g*(r+(r=o)),kr+=g*(n+(n=s)),Ar+=g*(i+(i=l)),Vr(r,n,i)}Nr.point=function(o,s){t=o,e=s,Nr.point=a,o*=Ct;var l=Math.cos(s*=Ct);r=l*Math.cos(o),n=l*Math.sin(o),i=Math.sin(s),Vr(r,n,i)},Nr.lineEnd=function(){a(t,e),Nr.lineEnd=qr,Nr.point=jr}}function Gr(t,e){function r(r,n){return r=t(r,n),e(r[0],r[1])}return t.invert&&e.invert&&(r.invert=function(r,n){return(r=e.invert(r,n))&&t.invert(r[0],r[1])}),r}function Yr(){return!0}function Wr(t,e,r,n,i){var a=[],o=[];if(t.forEach(function(t){if(!((e=t.length-1)<=0)){var e,r=t[0],n=t[e];if(Br(r,n)){i.lineStart();for(var s=0;s<e;++s)i.point((r=t[s])[0],r[1]);i.lineEnd()}else{var l=new Zr(r,t,null,!0),c=new Zr(r,null,l,!1);l.o=c,a.push(l),o.push(c),l=new Zr(n,t,null,!1),c=new Zr(n,null,l,!0),l.o=c,a.push(l),o.push(c)}}}),o.sort(e),Xr(a),Xr(o),a.length){for(var s=0,l=r,c=o.length;s<c;++s)o[s].e=l=!l;for(var u,h,f=a[0];;){for(var p=f,d=!0;p.v;)if((p=p.n)===f)return;u=p.z,i.lineStart();do{if(p.v=p.o.v=!0,p.e){if(d)for(s=0,c=u.length;s<c;++s)i.point((h=u[s])[0],h[1]);else n(p.x,p.n.x,1,i);p=p.n}else{if(d)for(s=(u=p.p.z).length-1;s>=0;--s)i.point((h=u[s])[0],h[1]);else n(p.x,p.p.x,-1,i);p=p.p}u=(p=p.o).z,d=!d}while(!p.v);i.lineEnd()}}}function Xr(t){if(e=t.length){for(var e,r,n=0,i=t[0];++n<e;)i.n=r=t[n],r.p=i,i=r;i.n=r=t[0],r.p=i}}function Zr(t,e,r,n){this.x=t,this.z=e,this.o=r,this.e=n,this.v=!1,this.n=this.p=null}function $r(e,r,n,i){return function(a,o){var s,l=r(o),c=a.invert(i[0],i[1]),u={point:h,lineStart:p,lineEnd:d,polygonStart:function(){u.point=b,u.lineStart=_,u.lineEnd=w,s=[],g=[]},polygonEnd:function(){u.point=h,u.lineStart=p,u.lineEnd=d,s=t.merge(s);var e=function(t,e){var r=t[0],n=t[1],i=[Math.sin(r),-Math.cos(r),0],a=0,o=0;Er.reset();for(var s=0,l=e.length;s<l;++s){var c=e[s],u=c.length;if(u)for(var h=c[0],f=h[0],p=h[1]/2+Mt/4,d=Math.sin(p),g=Math.cos(p),v=1;;){v===u&&(v=0);var m=(t=c[v])[0],y=t[1]/2+Mt/4,x=Math.sin(y),b=Math.cos(y),_=m-f,w=_>=0?1:-1,k=w*_,A=k>Mt,M=d*x;if(Er.add(Math.atan2(M*w*Math.sin(k),g*b+M*Math.cos(k))),a+=A?_+w*Tt:_,A^f>=r^m>=r){var T=Ir(zr(h),zr(t));Rr(T);var S=Ir(i,T);Rr(S);var E=(A^_>=0?-1:1)*Dt(S[2]);(n>E||n===E&&(T[0]||T[1]))&&(o+=A^_>=0?1:-1)}if(!v++)break;f=m,d=x,g=b,h=t}}return(a<-kt||a<kt&&Er<-kt)^1&o}(c,g);s.length?(x||(o.polygonStart(),x=!0),Wr(s,Qr,e,n,o)):e&&(x||(o.polygonStart(),x=!0),o.lineStart(),n(null,null,1,o),o.lineEnd()),x&&(o.polygonEnd(),x=!1),s=g=null},sphere:function(){o.polygonStart(),o.lineStart(),n(null,null,1,o),o.lineEnd(),o.polygonEnd()}};function h(t,r){var n=a(t,r);e(t=n[0],r=n[1])&&o.point(t,r)}function f(t,e){var r=a(t,e);l.point(r[0],r[1])}function p(){u.point=f,l.lineStart()}function d(){u.point=h,l.lineEnd()}var g,v,m=Kr(),y=r(m),x=!1;function b(t,e){v.push([t,e]);var r=a(t,e);y.point(r[0],r[1])}function _(){y.lineStart(),v=[]}function w(){b(v[0][0],v[0][1]),y.lineEnd();var t,e=y.clean(),r=m.buffer(),n=r.length;if(v.pop(),g.push(v),v=null,n)if(1&e){var i,a=-1;if((n=(t=r[0]).length-1)>0){for(x||(o.polygonStart(),x=!0),o.lineStart();++a<n;)o.point((i=t[a])[0],i[1]);o.lineEnd()}}else n>1&&2&e&&r.push(r.pop().concat(r.shift())),s.push(r.filter(Jr))}return u}}function Jr(t){return t.length>1}function Kr(){var t,e=[];return{lineStart:function(){e.push(t=[])},point:function(e,r){t.push([e,r])},lineEnd:P,buffer:function(){var r=e;return e=[],t=null,r},rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))}}}function Qr(t,e){return((t=t.x)[0]<0?t[1]-Et-kt:Et-t[1])-((e=e.x)[0]<0?e[1]-Et-kt:Et-e[1])}var tn=$r(Yr,function(t){var e,r=NaN,n=NaN,i=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(a,o){var s=a>0?Mt:-Mt,l=y(a-r);y(l-Mt)<kt?(t.point(r,n=(n+o)/2>0?Et:-Et),t.point(i,n),t.lineEnd(),t.lineStart(),t.point(s,n),t.point(a,n),e=0):i!==s&&l>=Mt&&(y(r-i)<kt&&(r-=i*kt),y(a-s)<kt&&(a-=s*kt),n=function(t,e,r,n){var i,a,o=Math.sin(t-r);return y(o)>kt?Math.atan((Math.sin(e)*(a=Math.cos(n))*Math.sin(r)-Math.sin(n)*(i=Math.cos(e))*Math.sin(t))/(i*a*o)):(e+n)/2}(r,n,a,o),t.point(i,n),t.lineEnd(),t.lineStart(),t.point(s,n),e=0),t.point(r=a,n=o),i=s},lineEnd:function(){t.lineEnd(),r=n=NaN},clean:function(){return 2-e}}},function(t,e,r,n){var i;if(null==t)i=r*Et,n.point(-Mt,i),n.point(0,i),n.point(Mt,i),n.point(Mt,0),n.point(Mt,-i),n.point(0,-i),n.point(-Mt,-i),n.point(-Mt,0),n.point(-Mt,i);else if(y(t[0]-e[0])>kt){var a=t[0]<e[0]?Mt:-Mt;i=r*a/2,n.point(-a,i),n.point(0,i),n.point(a,i)}else n.point(e[0],e[1])},[-Mt,-Mt/2]);function en(t,e,r,n){return function(i){var a,o=i.a,s=i.b,l=o.x,c=o.y,u=0,h=1,f=s.x-l,p=s.y-c;if(a=t-l,f||!(a>0)){if(a/=f,f<0){if(a<u)return;a<h&&(h=a)}else if(f>0){if(a>h)return;a>u&&(u=a)}if(a=r-l,f||!(a<0)){if(a/=f,f<0){if(a>h)return;a>u&&(u=a)}else if(f>0){if(a<u)return;a<h&&(h=a)}if(a=e-c,p||!(a>0)){if(a/=p,p<0){if(a<u)return;a<h&&(h=a)}else if(p>0){if(a>h)return;a>u&&(u=a)}if(a=n-c,p||!(a<0)){if(a/=p,p<0){if(a>h)return;a>u&&(u=a)}else if(p>0){if(a<u)return;a<h&&(h=a)}return u>0&&(i.a={x:l+u*f,y:c+u*p}),h<1&&(i.b={x:l+h*f,y:c+h*p}),i}}}}}}var rn=1e9;function nn(e,r,n,i){return function(l){var c,u,h,f,p,d,g,v,m,y,x,b=l,_=Kr(),w=en(e,r,n,i),k={point:T,lineStart:function(){k.point=S,u&&u.push(h=[]);y=!0,m=!1,g=v=NaN},lineEnd:function(){c&&(S(f,p),d&&m&&_.rejoin(),c.push(_.buffer()));k.point=T,m&&l.lineEnd()},polygonStart:function(){l=_,c=[],u=[],x=!0},polygonEnd:function(){l=b,c=t.merge(c);var r=function(t){for(var e=0,r=u.length,n=t[1],i=0;i<r;++i)for(var a,o=1,s=u[i],l=s.length,c=s[0];o<l;++o)a=s[o],c[1]<=n?a[1]>n&&Ot(c,a,t)>0&&++e:a[1]<=n&&Ot(c,a,t)<0&&--e,c=a;return 0!==e}([e,i]),n=x&&r,a=c.length;(n||a)&&(l.polygonStart(),n&&(l.lineStart(),A(null,null,1,l),l.lineEnd()),a&&Wr(c,o,r,A,l),l.polygonEnd()),c=u=h=null}};function A(t,o,l,c){var u=0,h=0;if(null==t||(u=a(t,l))!==(h=a(o,l))||s(t,o)<0^l>0)do{c.point(0===u||3===u?e:n,u>1?i:r)}while((u=(u+l+4)%4)!==h);else c.point(o[0],o[1])}function M(t,a){return e<=t&&t<=n&&r<=a&&a<=i}function T(t,e){M(t,e)&&l.point(t,e)}function S(t,e){var r=M(t=Math.max(-rn,Math.min(rn,t)),e=Math.max(-rn,Math.min(rn,e)));if(u&&h.push([t,e]),y)f=t,p=e,d=r,y=!1,r&&(l.lineStart(),l.point(t,e));else if(r&&m)l.point(t,e);else{var n={a:{x:g,y:v},b:{x:t,y:e}};w(n)?(m||(l.lineStart(),l.point(n.a.x,n.a.y)),l.point(n.b.x,n.b.y),r||l.lineEnd(),x=!1):r&&(l.lineStart(),l.point(t,e),x=!1)}g=t,v=e,m=r}return k};function a(t,i){return y(t[0]-e)<kt?i>0?0:3:y(t[0]-n)<kt?i>0?2:1:y(t[1]-r)<kt?i>0?1:0:i>0?3:2}function o(t,e){return s(t.x,e.x)}function s(t,e){var r=a(t,1),n=a(e,1);return r!==n?r-n:0===r?e[1]-t[1]:1===r?t[0]-e[0]:2===r?t[1]-e[1]:e[0]-t[0]}}function an(t){var e=0,r=Mt/3,n=Cn(t),i=n(e,r);return i.parallels=function(t){return arguments.length?n(e=t[0]*Mt/180,r=t[1]*Mt/180):[e/Mt*180,r/Mt*180]},i}function on(t,e){var r=Math.sin(t),n=(r+Math.sin(e))/2,i=1+r*(2*n-r),a=Math.sqrt(i)/n;function o(t,e){var r=Math.sqrt(i-2*n*Math.sin(e))/n;return[r*Math.sin(t*=n),a-r*Math.cos(t)]}return o.invert=function(t,e){var r=a-e;return[Math.atan2(t,r)/n,Dt((i-(t*t+r*r)*n*n)/(2*n))]},o}t.geo.clipExtent=function(){var t,e,r,n,i,a,o={stream:function(t){return i&&(i.valid=!1),(i=a(t)).valid=!0,i},extent:function(s){return arguments.length?(a=nn(t=+s[0][0],e=+s[0][1],r=+s[1][0],n=+s[1][1]),i&&(i.valid=!1,i=null),o):[[t,e],[r,n]]}};return o.extent([[0,0],[960,500]])},(t.geo.conicEqualArea=function(){return an(on)}).raw=on,t.geo.albers=function(){return t.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},t.geo.albersUsa=function(){var e,r,n,i,a=t.geo.albers(),o=t.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),s=t.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),l={point:function(t,r){e=[t,r]}};function c(t){var a=t[0],o=t[1];return e=null,r(a,o),e||(n(a,o),e)||i(a,o),e}return c.invert=function(t){var e=a.scale(),r=a.translate(),n=(t[0]-r[0])/e,i=(t[1]-r[1])/e;return(i>=.12&&i<.234&&n>=-.425&&n<-.214?o:i>=.166&&i<.234&&n>=-.214&&n<-.115?s:a).invert(t)},c.stream=function(t){var e=a.stream(t),r=o.stream(t),n=s.stream(t);return{point:function(t,i){e.point(t,i),r.point(t,i),n.point(t,i)},sphere:function(){e.sphere(),r.sphere(),n.sphere()},lineStart:function(){e.lineStart(),r.lineStart(),n.lineStart()},lineEnd:function(){e.lineEnd(),r.lineEnd(),n.lineEnd()},polygonStart:function(){e.polygonStart(),r.polygonStart(),n.polygonStart()},polygonEnd:function(){e.polygonEnd(),r.polygonEnd(),n.polygonEnd()}}},c.precision=function(t){return arguments.length?(a.precision(t),o.precision(t),s.precision(t),c):a.precision()},c.scale=function(t){return arguments.length?(a.scale(t),o.scale(.35*t),s.scale(t),c.translate(a.translate())):a.scale()},c.translate=function(t){if(!arguments.length)return a.translate();var e=a.scale(),u=+t[0],h=+t[1];return r=a.translate(t).clipExtent([[u-.455*e,h-.238*e],[u+.455*e,h+.238*e]]).stream(l).point,n=o.translate([u-.307*e,h+.201*e]).clipExtent([[u-.425*e+kt,h+.12*e+kt],[u-.214*e-kt,h+.234*e-kt]]).stream(l).point,i=s.translate([u-.205*e,h+.212*e]).clipExtent([[u-.214*e+kt,h+.166*e+kt],[u-.115*e-kt,h+.234*e-kt]]).stream(l).point,c},c.scale(1070)};var sn,ln,cn,un,hn,fn,pn={point:P,lineStart:P,lineEnd:P,polygonStart:function(){ln=0,pn.lineStart=dn},polygonEnd:function(){pn.lineStart=pn.lineEnd=pn.point=P,sn+=y(ln/2)}};function dn(){var t,e,r,n;function i(t,e){ln+=n*t-r*e,r=t,n=e}pn.point=function(a,o){pn.point=i,t=r=a,e=n=o},pn.lineEnd=function(){i(t,e)}}var gn={point:function(t,e){t<cn&&(cn=t);t>hn&&(hn=t);e<un&&(un=e);e>fn&&(fn=e)},lineStart:P,lineEnd:P,polygonStart:P,polygonEnd:P};function vn(){var t=mn(4.5),e=[],r={point:n,lineStart:function(){r.point=i},lineEnd:o,polygonStart:function(){r.lineEnd=s},polygonEnd:function(){r.lineEnd=o,r.point=n},pointRadius:function(e){return t=mn(e),r},result:function(){if(e.length){var t=e.join("");return e=[],t}}};function n(r,n){e.push("M",r,",",n,t)}function i(t,n){e.push("M",t,",",n),r.point=a}function a(t,r){e.push("L",t,",",r)}function o(){r.point=n}function s(){e.push("Z")}return r}function mn(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}var yn,xn={point:bn,lineStart:_n,lineEnd:wn,polygonStart:function(){xn.lineStart=kn},polygonEnd:function(){xn.point=bn,xn.lineStart=_n,xn.lineEnd=wn}};function bn(t,e){xr+=t,br+=e,++_r}function _n(){var t,e;function r(r,n){var i=r-t,a=n-e,o=Math.sqrt(i*i+a*a);wr+=o*(t+r)/2,kr+=o*(e+n)/2,Ar+=o,bn(t=r,e=n)}xn.point=function(n,i){xn.point=r,bn(t=n,e=i)}}function wn(){xn.point=bn}function kn(){var t,e,r,n;function i(t,e){var i=t-r,a=e-n,o=Math.sqrt(i*i+a*a);wr+=o*(r+t)/2,kr+=o*(n+e)/2,Ar+=o,Mr+=(o=n*t-r*e)*(r+t),Tr+=o*(n+e),Sr+=3*o,bn(r=t,n=e)}xn.point=function(a,o){xn.point=i,bn(t=r=a,e=n=o)},xn.lineEnd=function(){i(t,e)}}function An(t){var e=4.5,r={point:n,lineStart:function(){r.point=i},lineEnd:o,polygonStart:function(){r.lineEnd=s},polygonEnd:function(){r.lineEnd=o,r.point=n},pointRadius:function(t){return e=t,r},result:P};function n(r,n){t.moveTo(r+e,n),t.arc(r,n,e,0,Tt)}function i(e,n){t.moveTo(e,n),r.point=a}function a(e,r){t.lineTo(e,r)}function o(){r.point=n}function s(){t.closePath()}return r}function Mn(t){var e=.5,r=Math.cos(30*Ct),n=16;function i(e){return(n?function(e){var r,i,o,s,l,c,u,h,f,p,d,g,v={point:m,lineStart:y,lineEnd:b,polygonStart:function(){e.polygonStart(),v.lineStart=_},polygonEnd:function(){e.polygonEnd(),v.lineStart=y}};function m(r,n){r=t(r,n),e.point(r[0],r[1])}function y(){h=NaN,v.point=x,e.lineStart()}function x(r,i){var o=zr([r,i]),s=t(r,i);a(h,f,u,p,d,g,h=s[0],f=s[1],u=r,p=o[0],d=o[1],g=o[2],n,e),e.point(h,f)}function b(){v.point=m,e.lineEnd()}function _(){y(),v.point=w,v.lineEnd=k}function w(t,e){x(r=t,e),i=h,o=f,s=p,l=d,c=g,v.point=x}function k(){a(h,f,u,p,d,g,i,o,r,s,l,c,n,e),v.lineEnd=b,b()}return v}:function(e){return Sn(e,function(r,n){r=t(r,n),e.point(r[0],r[1])})})(e)}function a(n,i,o,s,l,c,u,h,f,p,d,g,v,m){var x=u-n,b=h-i,_=x*x+b*b;if(_>4*e&&v--){var w=s+p,k=l+d,A=c+g,M=Math.sqrt(w*w+k*k+A*A),T=Math.asin(A/=M),S=y(y(A)-1)<kt||y(o-f)<kt?(o+f)/2:Math.atan2(k,w),E=t(S,T),C=E[0],L=E[1],z=C-n,O=L-i,I=b*z-x*O;(I*I/_>e||y((x*z+b*O)/_-.5)>.3||s*p+l*d+c*g<r)&&(a(n,i,o,s,l,c,C,L,S,w/=M,k/=M,A,v,m),m.point(C,L),a(C,L,S,w,k,A,u,h,f,p,d,g,v,m))}}return i.precision=function(t){return arguments.length?(n=(e=t*t)>0&&16,i):Math.sqrt(e)},i}function Tn(t){this.stream=t}function Sn(t,e){return{point:e,sphere:function(){t.sphere()},lineStart:function(){t.lineStart()},lineEnd:function(){t.lineEnd()},polygonStart:function(){t.polygonStart()},polygonEnd:function(){t.polygonEnd()}}}function En(t){return Cn(function(){return t})()}function Cn(e){var r,n,i,a,o,s,l=Mn(function(t,e){return[(t=r(t,e))[0]*c+a,o-t[1]*c]}),c=150,u=480,h=250,f=0,p=0,d=0,g=0,v=0,m=tn,x=z,b=null,_=null;function w(t){return[(t=i(t[0]*Ct,t[1]*Ct))[0]*c+a,o-t[1]*c]}function k(t){return(t=i.invert((t[0]-a)/c,(o-t[1])/c))&&[t[0]*Lt,t[1]*Lt]}function A(){i=Gr(n=In(d,g,v),r);var t=r(f,p);return a=u-t[0]*c,o=h+t[1]*c,M()}function M(){return s&&(s.valid=!1,s=null),w}return w.stream=function(t){return s&&(s.valid=!1),(s=Ln(m(n,l(x(t))))).valid=!0,s},w.clipAngle=function(t){return arguments.length?(m=null==t?(b=t,tn):function(t){var e=Math.cos(t),r=e>0,n=y(e)>kt;return $r(i,function(t){var e,s,l,c,u;return{lineStart:function(){c=l=!1,u=1},point:function(h,f){var p,d=[h,f],g=i(h,f),v=r?g?0:o(h,f):g?o(h+(h<0?Mt:-Mt),f):0;if(!e&&(c=l=g)&&t.lineStart(),g!==l&&(p=a(e,d),(Br(e,p)||Br(d,p))&&(d[0]+=kt,d[1]+=kt,g=i(d[0],d[1]))),g!==l)u=0,g?(t.lineStart(),p=a(d,e),t.point(p[0],p[1])):(p=a(e,d),t.point(p[0],p[1]),t.lineEnd()),e=p;else if(n&&e&&r^g){var m;v&s||!(m=a(d,e,!0))||(u=0,r?(t.lineStart(),t.point(m[0][0],m[0][1]),t.point(m[1][0],m[1][1]),t.lineEnd()):(t.point(m[1][0],m[1][1]),t.lineEnd(),t.lineStart(),t.point(m[0][0],m[0][1])))}!g||e&&Br(e,d)||t.point(d[0],d[1]),e=d,l=g,s=v},lineEnd:function(){l&&t.lineEnd(),e=null},clean:function(){return u|(c&&l)<<1}}},Fn(t,6*Ct),r?[0,-t]:[-Mt,t-Mt]);function i(t,r){return Math.cos(t)*Math.cos(r)>e}function a(t,r,n){var i=[1,0,0],a=Ir(zr(t),zr(r)),o=Or(a,a),s=a[0],l=o-s*s;if(!l)return!n&&t;var c=e*o/l,u=-e*s/l,h=Ir(i,a),f=Pr(i,c);Dr(f,Pr(a,u));var p=h,d=Or(f,p),g=Or(p,p),v=d*d-g*(Or(f,f)-1);if(!(v<0)){var m=Math.sqrt(v),x=Pr(p,(-d-m)/g);if(Dr(x,f),x=Fr(x),!n)return x;var b,_=t[0],w=r[0],k=t[1],A=r[1];w<_&&(b=_,_=w,w=b);var M=w-_,T=y(M-Mt)<kt;if(!T&&A<k&&(b=k,k=A,A=b),T||M<kt?T?k+A>0^x[1]<(y(x[0]-_)<kt?k:A):k<=x[1]&&x[1]<=A:M>Mt^(_<=x[0]&&x[0]<=w)){var S=Pr(p,(-d+m)/g);return Dr(S,f),[x,Fr(S)]}}}function o(e,n){var i=r?t:Mt-t,a=0;return e<-i?a|=1:e>i&&(a|=2),n<-i?a|=4:n>i&&(a|=8),a}}((b=+t)*Ct),M()):b},w.clipExtent=function(t){return arguments.length?(_=t,x=t?nn(t[0][0],t[0][1],t[1][0],t[1][1]):z,M()):_},w.scale=function(t){return arguments.length?(c=+t,A()):c},w.translate=function(t){return arguments.length?(u=+t[0],h=+t[1],A()):[u,h]},w.center=function(t){return arguments.length?(f=t[0]%360*Ct,p=t[1]%360*Ct,A()):[f*Lt,p*Lt]},w.rotate=function(t){return arguments.length?(d=t[0]%360*Ct,g=t[1]%360*Ct,v=t.length>2?t[2]%360*Ct:0,A()):[d*Lt,g*Lt,v*Lt]},t.rebind(w,l,"precision"),function(){return r=e.apply(this,arguments),w.invert=r.invert&&k,A()}}function Ln(t){return Sn(t,function(e,r){t.point(e*Ct,r*Ct)})}function zn(t,e){return[t,e]}function On(t,e){return[t>Mt?t-Tt:t<-Mt?t+Tt:t,e]}function In(t,e,r){return t?e||r?Gr(Pn(t),Rn(e,r)):Pn(t):e||r?Rn(e,r):On}function Dn(t){return function(e,r){return[(e+=t)>Mt?e-Tt:e<-Mt?e+Tt:e,r]}}function Pn(t){var e=Dn(t);return e.invert=Dn(-t),e}function Rn(t,e){var r=Math.cos(t),n=Math.sin(t),i=Math.cos(e),a=Math.sin(e);function o(t,e){var o=Math.cos(e),s=Math.cos(t)*o,l=Math.sin(t)*o,c=Math.sin(e),u=c*r+s*n;return[Math.atan2(l*i-u*a,s*r-c*n),Dt(u*i+l*a)]}return o.invert=function(t,e){var o=Math.cos(e),s=Math.cos(t)*o,l=Math.sin(t)*o,c=Math.sin(e),u=c*i-l*a;return[Math.atan2(l*i+c*a,s*r+u*n),Dt(u*r-s*n)]},o}function Fn(t,e){var r=Math.cos(t),n=Math.sin(t);return function(i,a,o,s){var l=o*e;null!=i?(i=Bn(r,i),a=Bn(r,a),(o>0?i<a:i>a)&&(i+=o*Tt)):(i=t+o*Tt,a=t-.5*l);for(var c,u=i;o>0?u>a:u<a;u-=l)s.point((c=Fr([r,-n*Math.cos(u),-n*Math.sin(u)]))[0],c[1])}}function Bn(t,e){var r=zr(e);r[0]-=t,Rr(r);var n=It(-r[1]);return((-r[2]<0?-n:n)+2*Math.PI-kt)%(2*Math.PI)}function Nn(e,r,n){var i=t.range(e,r-kt,n).concat(r);return function(t){return i.map(function(e){return[t,e]})}}function jn(e,r,n){var i=t.range(e,r-kt,n).concat(r);return function(t){return i.map(function(e){return[e,t]})}}function Vn(t){return t.source}function Un(t){return t.target}t.geo.path=function(){var e,r,n,i,a,o=4.5;function s(e){return e&&("function"==typeof o&&i.pointRadius(+o.apply(this,arguments)),a&&a.valid||(a=n(i)),t.geo.stream(e,a)),i.result()}function l(){return a=null,s}return s.area=function(e){return sn=0,t.geo.stream(e,n(pn)),sn},s.centroid=function(e){return xr=br=_r=wr=kr=Ar=Mr=Tr=Sr=0,t.geo.stream(e,n(xn)),Sr?[Mr/Sr,Tr/Sr]:Ar?[wr/Ar,kr/Ar]:_r?[xr/_r,br/_r]:[NaN,NaN]},s.bounds=function(e){return hn=fn=-(cn=un=1/0),t.geo.stream(e,n(gn)),[[cn,un],[hn,fn]]},s.projection=function(t){return arguments.length?(n=(e=t)?t.stream||(r=t,i=Mn(function(t,e){return r([t*Lt,e*Lt])}),function(t){return Ln(i(t))}):z,l()):e;var r,i},s.context=function(t){return arguments.length?(i=null==(r=t)?new vn:new An(t),"function"!=typeof o&&i.pointRadius(o),l()):r},s.pointRadius=function(t){return arguments.length?(o="function"==typeof t?t:(i.pointRadius(+t),+t),s):o},s.projection(t.geo.albersUsa()).context(null)},t.geo.transform=function(t){return{stream:function(e){var r=new Tn(e);for(var n in t)r[n]=t[n];return r}}},Tn.prototype={point:function(t,e){this.stream.point(t,e)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}},t.geo.projection=En,t.geo.projectionMutator=Cn,(t.geo.equirectangular=function(){return En(zn)}).raw=zn.invert=zn,t.geo.rotation=function(t){function e(e){return(e=t(e[0]*Ct,e[1]*Ct))[0]*=Lt,e[1]*=Lt,e}return t=In(t[0]%360*Ct,t[1]*Ct,t.length>2?t[2]*Ct:0),e.invert=function(e){return(e=t.invert(e[0]*Ct,e[1]*Ct))[0]*=Lt,e[1]*=Lt,e},e},On.invert=zn,t.geo.circle=function(){var t,e,r=[0,0],n=6;function i(){var t="function"==typeof r?r.apply(this,arguments):r,n=In(-t[0]*Ct,-t[1]*Ct,0).invert,i=[];return e(null,null,1,{point:function(t,e){i.push(t=n(t,e)),t[0]*=Lt,t[1]*=Lt}}),{type:"Polygon",coordinates:[i]}}return i.origin=function(t){return arguments.length?(r=t,i):r},i.angle=function(r){return arguments.length?(e=Fn((t=+r)*Ct,n*Ct),i):t},i.precision=function(r){return arguments.length?(e=Fn(t*Ct,(n=+r)*Ct),i):n},i.angle(90)},t.geo.distance=function(t,e){var r,n=(e[0]-t[0])*Ct,i=t[1]*Ct,a=e[1]*Ct,o=Math.sin(n),s=Math.cos(n),l=Math.sin(i),c=Math.cos(i),u=Math.sin(a),h=Math.cos(a);return Math.atan2(Math.sqrt((r=h*o)*r+(r=c*u-l*h*s)*r),l*u+c*h*s)},t.geo.graticule=function(){var e,r,n,i,a,o,s,l,c,u,h,f,p=10,d=p,g=90,v=360,m=2.5;function x(){return{type:"MultiLineString",coordinates:b()}}function b(){return t.range(Math.ceil(i/g)*g,n,g).map(h).concat(t.range(Math.ceil(l/v)*v,s,v).map(f)).concat(t.range(Math.ceil(r/p)*p,e,p).filter(function(t){return y(t%g)>kt}).map(c)).concat(t.range(Math.ceil(o/d)*d,a,d).filter(function(t){return y(t%v)>kt}).map(u))}return x.lines=function(){return b().map(function(t){return{type:"LineString",coordinates:t}})},x.outline=function(){return{type:"Polygon",coordinates:[h(i).concat(f(s).slice(1),h(n).reverse().slice(1),f(l).reverse().slice(1))]}},x.extent=function(t){return arguments.length?x.majorExtent(t).minorExtent(t):x.minorExtent()},x.majorExtent=function(t){return arguments.length?(i=+t[0][0],n=+t[1][0],l=+t[0][1],s=+t[1][1],i>n&&(t=i,i=n,n=t),l>s&&(t=l,l=s,s=t),x.precision(m)):[[i,l],[n,s]]},x.minorExtent=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],o=+t[0][1],a=+t[1][1],r>e&&(t=r,r=e,e=t),o>a&&(t=o,o=a,a=t),x.precision(m)):[[r,o],[e,a]]},x.step=function(t){return arguments.length?x.majorStep(t).minorStep(t):x.minorStep()},x.majorStep=function(t){return arguments.length?(g=+t[0],v=+t[1],x):[g,v]},x.minorStep=function(t){return arguments.length?(p=+t[0],d=+t[1],x):[p,d]},x.precision=function(t){return arguments.length?(m=+t,c=Nn(o,a,90),u=jn(r,e,m),h=Nn(l,s,90),f=jn(i,n,m),x):m},x.majorExtent([[-180,-90+kt],[180,90-kt]]).minorExtent([[-180,-80-kt],[180,80+kt]])},t.geo.greatArc=function(){var e,r,n=Vn,i=Un;function a(){return{type:"LineString",coordinates:[e||n.apply(this,arguments),r||i.apply(this,arguments)]}}return a.distance=function(){return t.geo.distance(e||n.apply(this,arguments),r||i.apply(this,arguments))},a.source=function(t){return arguments.length?(n=t,e="function"==typeof t?null:t,a):n},a.target=function(t){return arguments.length?(i=t,r="function"==typeof t?null:t,a):i},a.precision=function(){return arguments.length?a:0},a},t.geo.interpolate=function(t,e){return r=t[0]*Ct,n=t[1]*Ct,i=e[0]*Ct,a=e[1]*Ct,o=Math.cos(n),s=Math.sin(n),l=Math.cos(a),c=Math.sin(a),u=o*Math.cos(r),h=o*Math.sin(r),f=l*Math.cos(i),p=l*Math.sin(i),d=2*Math.asin(Math.sqrt(Rt(a-n)+o*l*Rt(i-r))),g=1/Math.sin(d),(v=d?function(t){var e=Math.sin(t*=d)*g,r=Math.sin(d-t)*g,n=r*u+e*f,i=r*h+e*p,a=r*s+e*c;return[Math.atan2(i,n)*Lt,Math.atan2(a,Math.sqrt(n*n+i*i))*Lt]}:function(){return[r*Lt,n*Lt]}).distance=d,v;var r,n,i,a,o,s,l,c,u,h,f,p,d,g,v},t.geo.length=function(e){return yn=0,t.geo.stream(e,qn),yn};var qn={sphere:P,point:P,lineStart:function(){var t,e,r;function n(n,i){var a=Math.sin(i*=Ct),o=Math.cos(i),s=y((n*=Ct)-t),l=Math.cos(s);yn+=Math.atan2(Math.sqrt((s=o*Math.sin(s))*s+(s=r*a-e*o*l)*s),e*a+r*o*l),t=n,e=a,r=o}qn.point=function(i,a){t=i*Ct,e=Math.sin(a*=Ct),r=Math.cos(a),qn.point=n},qn.lineEnd=function(){qn.point=qn.lineEnd=P}},lineEnd:P,polygonStart:P,polygonEnd:P};function Hn(t,e){function r(e,r){var n=Math.cos(e),i=Math.cos(r),a=t(n*i);return[a*i*Math.sin(e),a*Math.sin(r)]}return r.invert=function(t,r){var n=Math.sqrt(t*t+r*r),i=e(n),a=Math.sin(i),o=Math.cos(i);return[Math.atan2(t*a,n*o),Math.asin(n&&r*a/n)]},r}var Gn=Hn(function(t){return Math.sqrt(2/(1+t))},function(t){return 2*Math.asin(t/2)});(t.geo.azimuthalEqualArea=function(){return En(Gn)}).raw=Gn;var Yn=Hn(function(t){var e=Math.acos(t);return e&&e/Math.sin(e)},z);function Wn(t,e){var r=Math.cos(t),n=function(t){return Math.tan(Mt/4+t/2)},i=t===e?Math.sin(t):Math.log(r/Math.cos(e))/Math.log(n(e)/n(t)),a=r*Math.pow(n(t),i)/i;if(!i)return $n;function o(t,e){a>0?e<-Et+kt&&(e=-Et+kt):e>Et-kt&&(e=Et-kt);var r=a/Math.pow(n(e),i);return[r*Math.sin(i*t),a-r*Math.cos(i*t)]}return o.invert=function(t,e){var r=a-e,n=zt(i)*Math.sqrt(t*t+r*r);return[Math.atan2(t,r)/i,2*Math.atan(Math.pow(a/n,1/i))-Et]},o}function Xn(t,e){var r=Math.cos(t),n=t===e?Math.sin(t):(r-Math.cos(e))/(e-t),i=r/n+t;if(y(n)<kt)return zn;function a(t,e){var r=i-e;return[r*Math.sin(n*t),i-r*Math.cos(n*t)]}return a.invert=function(t,e){var r=i-e;return[Math.atan2(t,r)/n,i-zt(n)*Math.sqrt(t*t+r*r)]},a}(t.geo.azimuthalEquidistant=function(){return En(Yn)}).raw=Yn,(t.geo.conicConformal=function(){return an(Wn)}).raw=Wn,(t.geo.conicEquidistant=function(){return an(Xn)}).raw=Xn;var Zn=Hn(function(t){return 1/t},Math.atan);function $n(t,e){return[t,Math.log(Math.tan(Mt/4+e/2))]}function Jn(t){var e,r=En(t),n=r.scale,i=r.translate,a=r.clipExtent;return r.scale=function(){var t=n.apply(r,arguments);return t===r?e?r.clipExtent(null):r:t},r.translate=function(){var t=i.apply(r,arguments);return t===r?e?r.clipExtent(null):r:t},r.clipExtent=function(t){var o=a.apply(r,arguments);if(o===r){if(e=null==t){var s=Mt*n(),l=i();a([[l[0]-s,l[1]-s],[l[0]+s,l[1]+s]])}}else e&&(o=null);return o},r.clipExtent(null)}(t.geo.gnomonic=function(){return En(Zn)}).raw=Zn,$n.invert=function(t,e){return[t,2*Math.atan(Math.exp(e))-Et]},(t.geo.mercator=function(){return Jn($n)}).raw=$n;var Kn=Hn(function(){return 1},Math.asin);(t.geo.orthographic=function(){return En(Kn)}).raw=Kn;var Qn=Hn(function(t){return 1/(1+t)},function(t){return 2*Math.atan(t)});function ti(t,e){return[Math.log(Math.tan(Mt/4+e/2)),-t]}function ei(t){return t[0]}function ri(t){return t[1]}function ni(t){for(var e=t.length,r=[0,1],n=2,i=2;i<e;i++){for(;n>1&&Ot(t[r[n-2]],t[r[n-1]],t[i])<=0;)--n;r[n++]=i}return r.slice(0,n)}function ii(t,e){return t[0]-e[0]||t[1]-e[1]}(t.geo.stereographic=function(){return En(Qn)}).raw=Qn,ti.invert=function(t,e){return[-e,2*Math.atan(Math.exp(t))-Et]},(t.geo.transverseMercator=function(){var t=Jn(ti),e=t.center,r=t.rotate;return t.center=function(t){return t?e([-t[1],t[0]]):[(t=e())[1],-t[0]]},t.rotate=function(t){return t?r([t[0],t[1],t.length>2?t[2]+90:90]):[(t=r())[0],t[1],t[2]-90]},r([0,0,90])}).raw=ti,t.geom={},t.geom.hull=function(t){var e=ei,r=ri;if(arguments.length)return n(t);function n(t){if(t.length<3)return[];var n,i=ve(e),a=ve(r),o=t.length,s=[],l=[];for(n=0;n<o;n++)s.push([+i.call(this,t[n],n),+a.call(this,t[n],n),n]);for(s.sort(ii),n=0;n<o;n++)l.push([s[n][0],-s[n][1]]);var c=ni(s),u=ni(l),h=u[0]===c[0],f=u[u.length-1]===c[c.length-1],p=[];for(n=c.length-1;n>=0;--n)p.push(t[s[c[n]][2]]);for(n=+h;n<u.length-f;++n)p.push(t[s[u[n]][2]]);return p}return n.x=function(t){return arguments.length?(e=t,n):e},n.y=function(t){return arguments.length?(r=t,n):r},n},t.geom.polygon=function(t){return U(t,ai),t};var ai=t.geom.polygon.prototype=[];function oi(t,e,r){return(r[0]-e[0])*(t[1]-e[1])<(r[1]-e[1])*(t[0]-e[0])}function si(t,e,r,n){var i=t[0],a=r[0],o=e[0]-i,s=n[0]-a,l=t[1],c=r[1],u=e[1]-l,h=n[1]-c,f=(s*(l-c)-h*(i-a))/(h*o-s*u);return[i+f*o,l+f*u]}function li(t){var e=t[0],r=t[t.length-1];return!(e[0]-r[0]||e[1]-r[1])}ai.area=function(){for(var t,e=-1,r=this.length,n=this[r-1],i=0;++e<r;)t=n,n=this[e],i+=t[1]*n[0]-t[0]*n[1];return.5*i},ai.centroid=function(t){var e,r,n=-1,i=this.length,a=0,o=0,s=this[i-1];for(arguments.length||(t=-1/(6*this.area()));++n<i;)e=s,s=this[n],r=e[0]*s[1]-s[0]*e[1],a+=(e[0]+s[0])*r,o+=(e[1]+s[1])*r;return[a*t,o*t]},ai.clip=function(t){for(var e,r,n,i,a,o,s=li(t),l=-1,c=this.length-li(this),u=this[c-1];++l<c;){for(e=t.slice(),t.length=0,i=this[l],a=e[(n=e.length-s)-1],r=-1;++r<n;)oi(o=e[r],u,i)?(oi(a,u,i)||t.push(si(a,o,u,i)),t.push(o)):oi(a,u,i)&&t.push(si(a,o,u,i)),a=o;s&&t.push(t[0]),u=i}return t};var ci,ui,hi,fi,pi,di=[],gi=[];function vi(){Di(this),this.edge=this.site=this.circle=null}function mi(t){var e=di.pop()||new vi;return e.site=t,e}function yi(t){Si(t),hi.remove(t),di.push(t),Di(t)}function xi(t){var e=t.circle,r=e.x,n=e.cy,i={x:r,y:n},a=t.P,o=t.N,s=[t];yi(t);for(var l=a;l.circle&&y(r-l.circle.x)<kt&&y(n-l.circle.cy)<kt;)a=l.P,s.unshift(l),yi(l),l=a;s.unshift(l),Si(l);for(var c=o;c.circle&&y(r-c.circle.x)<kt&&y(n-c.circle.cy)<kt;)o=c.N,s.push(c),yi(c),c=o;s.push(c),Si(c);var u,h=s.length;for(u=1;u<h;++u)c=s[u],l=s[u-1],zi(c.edge,l.site,c.site,i);l=s[0],(c=s[h-1]).edge=Li(l.site,c.site,null,i),Ti(l),Ti(c)}function bi(t){for(var e,r,n,i,a=t.x,o=t.y,s=hi._;s;)if((n=_i(s,o)-a)>kt)s=s.L;else{if(!((i=a-wi(s,o))>kt)){n>-kt?(e=s.P,r=s):i>-kt?(e=s,r=s.N):e=r=s;break}if(!s.R){e=s;break}s=s.R}var l=mi(t);if(hi.insert(e,l),e||r){if(e===r)return Si(e),r=mi(e.site),hi.insert(l,r),l.edge=r.edge=Li(e.site,l.site),Ti(e),void Ti(r);if(r){Si(e),Si(r);var c=e.site,u=c.x,h=c.y,f=t.x-u,p=t.y-h,d=r.site,g=d.x-u,v=d.y-h,m=2*(f*v-p*g),y=f*f+p*p,x=g*g+v*v,b={x:(v*y-p*x)/m+u,y:(f*x-g*y)/m+h};zi(r.edge,c,d,b),l.edge=Li(c,t,null,b),r.edge=Li(t,d,null,b),Ti(e),Ti(r)}else l.edge=Li(e.site,l.site)}}function _i(t,e){var r=t.site,n=r.x,i=r.y,a=i-e;if(!a)return n;var o=t.P;if(!o)return-1/0;var s=(r=o.site).x,l=r.y,c=l-e;if(!c)return s;var u=s-n,h=1/a-1/c,f=u/c;return h?(-f+Math.sqrt(f*f-2*h*(u*u/(-2*c)-l+c/2+i-a/2)))/h+n:(n+s)/2}function wi(t,e){var r=t.N;if(r)return _i(r,e);var n=t.site;return n.y===e?n.x:1/0}function ki(t){this.site=t,this.edges=[]}function Ai(t,e){return e.angle-t.angle}function Mi(){Di(this),this.x=this.y=this.arc=this.site=this.cy=null}function Ti(t){var e=t.P,r=t.N;if(e&&r){var n=e.site,i=t.site,a=r.site;if(n!==a){var o=i.x,s=i.y,l=n.x-o,c=n.y-s,u=a.x-o,h=2*(l*(v=a.y-s)-c*u);if(!(h>=-At)){var f=l*l+c*c,p=u*u+v*v,d=(v*f-c*p)/h,g=(l*p-u*f)/h,v=g+s,m=gi.pop()||new Mi;m.arc=t,m.site=i,m.x=d+o,m.y=v+Math.sqrt(d*d+g*g),m.cy=v,t.circle=m;for(var y=null,x=pi._;x;)if(m.y<x.y||m.y===x.y&&m.x<=x.x){if(!x.L){y=x.P;break}x=x.L}else{if(!x.R){y=x;break}x=x.R}pi.insert(y,m),y||(fi=m)}}}}function Si(t){var e=t.circle;e&&(e.P||(fi=e.N),pi.remove(e),gi.push(e),Di(e),t.circle=null)}function Ei(t,e){var r=t.b;if(r)return!0;var n,i,a=t.a,o=e[0][0],s=e[1][0],l=e[0][1],c=e[1][1],u=t.l,h=t.r,f=u.x,p=u.y,d=h.x,g=h.y,v=(f+d)/2,m=(p+g)/2;if(g===p){if(v<o||v>=s)return;if(f>d){if(a){if(a.y>=c)return}else a={x:v,y:l};r={x:v,y:c}}else{if(a){if(a.y<l)return}else a={x:v,y:c};r={x:v,y:l}}}else if(i=m-(n=(f-d)/(g-p))*v,n<-1||n>1)if(f>d){if(a){if(a.y>=c)return}else a={x:(l-i)/n,y:l};r={x:(c-i)/n,y:c}}else{if(a){if(a.y<l)return}else a={x:(c-i)/n,y:c};r={x:(l-i)/n,y:l}}else if(p<g){if(a){if(a.x>=s)return}else a={x:o,y:n*o+i};r={x:s,y:n*s+i}}else{if(a){if(a.x<o)return}else a={x:s,y:n*s+i};r={x:o,y:n*o+i}}return t.a=a,t.b=r,!0}function Ci(t,e){this.l=t,this.r=e,this.a=this.b=null}function Li(t,e,r,n){var i=new Ci(t,e);return ci.push(i),r&&zi(i,t,e,r),n&&zi(i,e,t,n),ui[t.i].edges.push(new Oi(i,t,e)),ui[e.i].edges.push(new Oi(i,e,t)),i}function zi(t,e,r,n){t.a||t.b?t.l===r?t.b=n:t.a=n:(t.a=n,t.l=e,t.r=r)}function Oi(t,e,r){var n=t.a,i=t.b;this.edge=t,this.site=e,this.angle=r?Math.atan2(r.y-e.y,r.x-e.x):t.l===e?Math.atan2(i.x-n.x,n.y-i.y):Math.atan2(n.x-i.x,i.y-n.y)}function Ii(){this._=null}function Di(t){t.U=t.C=t.L=t.R=t.P=t.N=null}function Pi(t,e){var r=e,n=e.R,i=r.U;i?i.L===r?i.L=n:i.R=n:t._=n,n.U=i,r.U=n,r.R=n.L,r.R&&(r.R.U=r),n.L=r}function Ri(t,e){var r=e,n=e.L,i=r.U;i?i.L===r?i.L=n:i.R=n:t._=n,n.U=i,r.U=n,r.L=n.R,r.L&&(r.L.U=r),n.R=r}function Fi(t){for(;t.L;)t=t.L;return t}function Bi(t,e){var r,n,i,a=t.sort(Ni).pop();for(ci=[],ui=new Array(t.length),hi=new Ii,pi=new Ii;;)if(i=fi,a&&(!i||a.y<i.y||a.y===i.y&&a.x<i.x))a.x===r&&a.y===n||(ui[a.i]=new ki(a),bi(a),r=a.x,n=a.y),a=t.pop();else{if(!i)break;xi(i.arc)}e&&(function(t){for(var e,r=ci,n=en(t[0][0],t[0][1],t[1][0],t[1][1]),i=r.length;i--;)(!Ei(e=r[i],t)||!n(e)||y(e.a.x-e.b.x)<kt&&y(e.a.y-e.b.y)<kt)&&(e.a=e.b=null,r.splice(i,1))}(e),function(t){for(var e,r,n,i,a,o,s,l,c,u,h=t[0][0],f=t[1][0],p=t[0][1],d=t[1][1],g=ui,v=g.length;v--;)if((a=g[v])&&a.prepare())for(l=(s=a.edges).length,o=0;o<l;)n=(u=s[o].end()).x,i=u.y,e=(c=s[++o%l].start()).x,r=c.y,(y(n-e)>kt||y(i-r)>kt)&&(s.splice(o,0,new Oi((m=a.site,x=u,b=y(n-h)<kt&&d-i>kt?{x:h,y:y(e-h)<kt?r:d}:y(i-d)<kt&&f-n>kt?{x:y(r-d)<kt?e:f,y:d}:y(n-f)<kt&&i-p>kt?{x:f,y:y(e-f)<kt?r:p}:y(i-p)<kt&&n-h>kt?{x:y(r-p)<kt?e:h,y:p}:null,_=void 0,_=new Ci(m,null),_.a=x,_.b=b,ci.push(_),_),a.site,null)),++l);var m,x,b,_}(e));var o={cells:ui,edges:ci};return hi=pi=ci=ui=null,o}function Ni(t,e){return e.y-t.y||e.x-t.x}ki.prototype.prepare=function(){for(var t,e=this.edges,r=e.length;r--;)(t=e[r].edge).b&&t.a||e.splice(r,1);return e.sort(Ai),e.length},Oi.prototype={start:function(){return this.edge.l===this.site?this.edge.a:this.edge.b},end:function(){return this.edge.l===this.site?this.edge.b:this.edge.a}},Ii.prototype={insert:function(t,e){var r,n,i;if(t){if(e.P=t,e.N=t.N,t.N&&(t.N.P=e),t.N=e,t.R){for(t=t.R;t.L;)t=t.L;t.L=e}else t.R=e;r=t}else this._?(t=Fi(this._),e.P=null,e.N=t,t.P=t.L=e,r=t):(e.P=e.N=null,this._=e,r=null);for(e.L=e.R=null,e.U=r,e.C=!0,t=e;r&&r.C;)r===(n=r.U).L?(i=n.R)&&i.C?(r.C=i.C=!1,n.C=!0,t=n):(t===r.R&&(Pi(this,r),r=(t=r).U),r.C=!1,n.C=!0,Ri(this,n)):(i=n.L)&&i.C?(r.C=i.C=!1,n.C=!0,t=n):(t===r.L&&(Ri(this,r),r=(t=r).U),r.C=!1,n.C=!0,Pi(this,n)),r=t.U;this._.C=!1},remove:function(t){t.N&&(t.N.P=t.P),t.P&&(t.P.N=t.N),t.N=t.P=null;var e,r,n,i=t.U,a=t.L,o=t.R;if(r=a?o?Fi(o):a:o,i?i.L===t?i.L=r:i.R=r:this._=r,a&&o?(n=r.C,r.C=t.C,r.L=a,a.U=r,r!==o?(i=r.U,r.U=t.U,t=r.R,i.L=t,r.R=o,o.U=r):(r.U=i,i=r,t=r.R)):(n=t.C,t=r),t&&(t.U=i),!n)if(t&&t.C)t.C=!1;else{do{if(t===this._)break;if(t===i.L){if((e=i.R).C&&(e.C=!1,i.C=!0,Pi(this,i),e=i.R),e.L&&e.L.C||e.R&&e.R.C){e.R&&e.R.C||(e.L.C=!1,e.C=!0,Ri(this,e),e=i.R),e.C=i.C,i.C=e.R.C=!1,Pi(this,i),t=this._;break}}else if((e=i.L).C&&(e.C=!1,i.C=!0,Ri(this,i),e=i.L),e.L&&e.L.C||e.R&&e.R.C){e.L&&e.L.C||(e.R.C=!1,e.C=!0,Pi(this,e),e=i.L),e.C=i.C,i.C=e.L.C=!1,Ri(this,i),t=this._;break}e.C=!0,t=i,i=i.U}while(!t.C);t&&(t.C=!1)}}},t.geom.voronoi=function(t){var e=ei,r=ri,n=e,i=r,a=ji;if(t)return o(t);function o(t){var e=new Array(t.length),r=a[0][0],n=a[0][1],i=a[1][0],o=a[1][1];return Bi(s(t),a).cells.forEach(function(a,s){var l=a.edges,c=a.site;(e[s]=l.length?l.map(function(t){var e=t.start();return[e.x,e.y]}):c.x>=r&&c.x<=i&&c.y>=n&&c.y<=o?[[r,o],[i,o],[i,n],[r,n]]:[]).point=t[s]}),e}function s(t){return t.map(function(t,e){return{x:Math.round(n(t,e)/kt)*kt,y:Math.round(i(t,e)/kt)*kt,i:e}})}return o.links=function(t){return Bi(s(t)).edges.filter(function(t){return t.l&&t.r}).map(function(e){return{source:t[e.l.i],target:t[e.r.i]}})},o.triangles=function(t){var e=[];return Bi(s(t)).cells.forEach(function(r,n){for(var i,a,o,s,l=r.site,c=r.edges.sort(Ai),u=-1,h=c.length,f=c[h-1].edge,p=f.l===l?f.r:f.l;++u<h;)f,i=p,p=(f=c[u].edge).l===l?f.r:f.l,n<i.i&&n<p.i&&(o=i,s=p,((a=l).x-s.x)*(o.y-a.y)-(a.x-o.x)*(s.y-a.y)<0)&&e.push([t[n],t[i.i],t[p.i]])}),e},o.x=function(t){return arguments.length?(n=ve(e=t),o):e},o.y=function(t){return arguments.length?(i=ve(r=t),o):r},o.clipExtent=function(t){return arguments.length?(a=null==t?ji:t,o):a===ji?null:a},o.size=function(t){return arguments.length?o.clipExtent(t&&[[0,0],t]):a===ji?null:a&&a[1]},o};var ji=[[-1e6,-1e6],[1e6,1e6]];function Vi(t){return t.x}function Ui(t){return t.y}function qi(e,r){e=t.rgb(e),r=t.rgb(r);var n=e.r,i=e.g,a=e.b,o=r.r-n,s=r.g-i,l=r.b-a;return function(t){return"#"+ce(Math.round(n+o*t))+ce(Math.round(i+s*t))+ce(Math.round(a+l*t))}}function Hi(t,e){var r,n={},i={};for(r in t)r in e?n[r]=Zi(t[r],e[r]):i[r]=t[r];for(r in e)r in t||(i[r]=e[r]);return function(t){for(r in n)i[r]=n[r](t);return i}}function Gi(t,e){return t=+t,e=+e,function(r){return t*(1-r)+e*r}}function Yi(t,e){var r,n,i,a=Wi.lastIndex=Xi.lastIndex=0,o=-1,s=[],l=[];for(t+="",e+="";(r=Wi.exec(t))&&(n=Xi.exec(e));)(i=n.index)>a&&(i=e.slice(a,i),s[o]?s[o]+=i:s[++o]=i),(r=r[0])===(n=n[0])?s[o]?s[o]+=n:s[++o]=n:(s[++o]=null,l.push({i:o,x:Gi(r,n)})),a=Xi.lastIndex;return a<e.length&&(i=e.slice(a),s[o]?s[o]+=i:s[++o]=i),s.length<2?l[0]?(e=l[0].x,function(t){return e(t)+""}):function(){return e}:(e=l.length,function(t){for(var r,n=0;n<e;++n)s[(r=l[n]).i]=r.x(t);return s.join("")})}t.geom.delaunay=function(e){return t.geom.voronoi().triangles(e)},t.geom.quadtree=function(t,e,r,n,i){var a,o=ei,s=ri;if(a=arguments.length)return o=Vi,s=Ui,3===a&&(i=r,n=e,r=e=0),l(t);function l(t){var l,c,u,h,f,p,d,g,v,m=ve(o),x=ve(s);if(null!=e)p=e,d=r,g=n,v=i;else if(g=v=-(p=d=1/0),c=[],u=[],f=t.length,a)for(h=0;h<f;++h)(l=t[h]).x<p&&(p=l.x),l.y<d&&(d=l.y),l.x>g&&(g=l.x),l.y>v&&(v=l.y),c.push(l.x),u.push(l.y);else for(h=0;h<f;++h){var b=+m(l=t[h],h),_=+x(l,h);b<p&&(p=b),_<d&&(d=_),b>g&&(g=b),_>v&&(v=_),c.push(b),u.push(_)}var w=g-p,k=v-d;function A(t,e,r,n,i,a,o,s){if(!isNaN(r)&&!isNaN(n))if(t.leaf){var l=t.x,c=t.y;if(null!=l)if(y(l-r)+y(c-n)<.01)M(t,e,r,n,i,a,o,s);else{var u=t.point;t.x=t.y=t.point=null,M(t,u,l,c,i,a,o,s),M(t,e,r,n,i,a,o,s)}else t.x=r,t.y=n,t.point=e}else M(t,e,r,n,i,a,o,s)}function M(t,e,r,n,i,a,o,s){var l=.5*(i+o),c=.5*(a+s),u=r>=l,h=n>=c,f=h<<1|u;t.leaf=!1,u?i=l:o=l,h?a=c:s=c,A(t=t.nodes[f]||(t.nodes[f]={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){A(T,t,+m(t,++h),+x(t,h),p,d,g,v)}}),e,r,n,i,a,o,s)}w>k?v=d+w:g=p+k;var T={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){A(T,t,+m(t,++h),+x(t,h),p,d,g,v)}};if(T.visit=function(t){!function t(e,r,n,i,a,o){if(!e(r,n,i,a,o)){var s=.5*(n+a),l=.5*(i+o),c=r.nodes;c[0]&&t(e,c[0],n,i,s,l),c[1]&&t(e,c[1],s,i,a,l),c[2]&&t(e,c[2],n,l,s,o),c[3]&&t(e,c[3],s,l,a,o)}}(t,T,p,d,g,v)},T.find=function(t){return function(t,e,r,n,i,a,o){var s,l=1/0;return function t(c,u,h,f,p){if(!(u>a||h>o||f<n||p<i)){if(d=c.point){var d,g=e-c.x,v=r-c.y,m=g*g+v*v;if(m<l){var y=Math.sqrt(l=m);n=e-y,i=r-y,a=e+y,o=r+y,s=d}}for(var x=c.nodes,b=.5*(u+f),_=.5*(h+p),w=(r>=_)<<1|e>=b,k=w+4;w<k;++w)if(c=x[3&w])switch(3&w){case 0:t(c,u,h,b,_);break;case 1:t(c,b,h,f,_);break;case 2:t(c,u,_,b,p);break;case 3:t(c,b,_,f,p)}}}(t,n,i,a,o),s}(T,t[0],t[1],p,d,g,v)},h=-1,null==e){for(;++h<f;)A(T,t[h],c[h],u[h],p,d,g,v);--h}else t.forEach(T.add);return c=u=t=l=null,T}return l.x=function(t){return arguments.length?(o=t,l):o},l.y=function(t){return arguments.length?(s=t,l):s},l.extent=function(t){return arguments.length?(null==t?e=r=n=i=null:(e=+t[0][0],r=+t[0][1],n=+t[1][0],i=+t[1][1]),l):null==e?null:[[e,r],[n,i]]},l.size=function(t){return arguments.length?(null==t?e=r=n=i=null:(e=r=0,n=+t[0],i=+t[1]),l):null==e?null:[n-e,i-r]},l},t.interpolateRgb=qi,t.interpolateObject=Hi,t.interpolateNumber=Gi,t.interpolateString=Yi;var Wi=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Xi=new RegExp(Wi.source,"g");function Zi(e,r){for(var n,i=t.interpolators.length;--i>=0&&!(n=t.interpolators[i](e,r)););return n}function $i(t,e){var r,n=[],i=[],a=t.length,o=e.length,s=Math.min(t.length,e.length);for(r=0;r<s;++r)n.push(Zi(t[r],e[r]));for(;r<a;++r)i[r]=t[r];for(;r<o;++r)i[r]=e[r];return function(t){for(r=0;r<s;++r)i[r]=n[r](t);return i}}t.interpolate=Zi,t.interpolators=[function(t,e){var r=typeof e;return("string"===r?ge.has(e.toLowerCase())||/^(#|rgb\(|hsl\()/i.test(e)?qi:Yi:e instanceof Vt?qi:Array.isArray(e)?$i:"object"===r&&isNaN(e)?Hi:Gi)(t,e)}],t.interpolateArray=$i;var Ji=function(){return z},Ki=t.map({linear:Ji,poly:function(t){return function(e){return Math.pow(e,t)}},quad:function(){return ra},cubic:function(){return na},sin:function(){return aa},exp:function(){return oa},circle:function(){return sa},elastic:function(t,e){var r;arguments.length<2&&(e=.45);arguments.length?r=e/Tt*Math.asin(1/t):(t=1,r=e/4);return function(n){return 1+t*Math.pow(2,-10*n)*Math.sin((n-r)*Tt/e)}},back:function(t){t||(t=1.70158);return function(e){return e*e*((t+1)*e-t)}},bounce:function(){return la}}),Qi=t.map({in:z,out:ta,"in-out":ea,"out-in":function(t){return ea(ta(t))}});function ta(t){return function(e){return 1-t(1-e)}}function ea(t){return function(e){return.5*(e<.5?t(2*e):2-t(2-2*e))}}function ra(t){return t*t}function na(t){return t*t*t}function ia(t){if(t<=0)return 0;if(t>=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}function aa(t){return 1-Math.cos(t*Et)}function oa(t){return Math.pow(2,10*(t-1))}function sa(t){return 1-Math.sqrt(1-t*t)}function la(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375}function ca(t,e){return e-=t,function(r){return Math.round(t+e*r)}}function ua(t){var e,r,n,i=[t.a,t.b],a=[t.c,t.d],o=fa(i),s=ha(i,a),l=fa(((e=a)[0]+=(n=-s)*(r=i)[0],e[1]+=n*r[1],e))||0;i[0]*a[1]<a[0]*i[1]&&(i[0]*=-1,i[1]*=-1,o*=-1,s*=-1),this.rotate=(o?Math.atan2(i[1],i[0]):Math.atan2(-a[0],a[1]))*Lt,this.translate=[t.e,t.f],this.scale=[o,l],this.skew=l?Math.atan2(s,l)*Lt:0}function ha(t,e){return t[0]*e[0]+t[1]*e[1]}function fa(t){var e=Math.sqrt(ha(t,t));return e&&(t[0]/=e,t[1]/=e),e}t.ease=function(t){var e,n=t.indexOf("-"),i=n>=0?t.slice(0,n):t,a=n>=0?t.slice(n+1):"in";return i=Ki.get(i)||Ji,a=Qi.get(a)||z,e=a(i.apply(null,r.call(arguments,1))),function(t){return t<=0?0:t>=1?1:e(t)}},t.interpolateHcl=function(e,r){e=t.hcl(e),r=t.hcl(r);var n=e.h,i=e.c,a=e.l,o=r.h-n,s=r.c-i,l=r.l-a;isNaN(s)&&(s=0,i=isNaN(i)?r.c:i);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(t){return Wt(n+o*t,i+s*t,a+l*t)+""}},t.interpolateHsl=function(e,r){e=t.hsl(e),r=t.hsl(r);var n=e.h,i=e.s,a=e.l,o=r.h-n,s=r.s-i,l=r.l-a;isNaN(s)&&(s=0,i=isNaN(i)?r.s:i);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(t){return Ht(n+o*t,i+s*t,a+l*t)+""}},t.interpolateLab=function(e,r){e=t.lab(e),r=t.lab(r);var n=e.l,i=e.a,a=e.b,o=r.l-n,s=r.a-i,l=r.b-a;return function(t){return te(n+o*t,i+s*t,a+l*t)+""}},t.interpolateRound=ca,t.transform=function(e){var r=i.createElementNS(t.ns.prefix.svg,"g");return(t.transform=function(t){if(null!=t){r.setAttribute("transform",t);var e=r.transform.baseVal.consolidate()}return new ua(e?e.matrix:pa)})(e)},ua.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var pa={a:1,b:0,c:0,d:1,e:0,f:0};function da(t){return t.length?t.pop()+",":""}function ga(e,r){var n=[],i=[];return e=t.transform(e),r=t.transform(r),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var i=r.push("translate(",null,",",null,")");n.push({i:i-4,x:Gi(t[0],e[0])},{i:i-2,x:Gi(t[1],e[1])})}else(e[0]||e[1])&&r.push("translate("+e+")")}(e.translate,r.translate,n,i),function(t,e,r,n){t!==e?(t-e>180?e+=360:e-t>180&&(t+=360),n.push({i:r.push(da(r)+"rotate(",null,")")-2,x:Gi(t,e)})):e&&r.push(da(r)+"rotate("+e+")")}(e.rotate,r.rotate,n,i),function(t,e,r,n){t!==e?n.push({i:r.push(da(r)+"skewX(",null,")")-2,x:Gi(t,e)}):e&&r.push(da(r)+"skewX("+e+")")}(e.skew,r.skew,n,i),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var i=r.push(da(r)+"scale(",null,",",null,")");n.push({i:i-4,x:Gi(t[0],e[0])},{i:i-2,x:Gi(t[1],e[1])})}else 1===e[0]&&1===e[1]||r.push(da(r)+"scale("+e+")")}(e.scale,r.scale,n,i),e=r=null,function(t){for(var e,r=-1,a=i.length;++r<a;)n[(e=i[r]).i]=e.x(t);return n.join("")}}function va(t,e){return e=(e-=t=+t)||1/e,function(r){return(r-t)/e}}function ma(t,e){return e=(e-=t=+t)||1/e,function(r){return Math.max(0,Math.min(1,(r-t)/e))}}function ya(t){for(var e=t.source,r=t.target,n=function(t,e){if(t===e)return t;var r=xa(t),n=xa(e),i=r.pop(),a=n.pop(),o=null;for(;i===a;)o=i,i=r.pop(),a=n.pop();return o}(e,r),i=[e];e!==n;)e=e.parent,i.push(e);for(var a=i.length;r!==n;)i.splice(a,0,r),r=r.parent;return i}function xa(t){for(var e=[],r=t.parent;null!=r;)e.push(t),t=r,r=r.parent;return e.push(t),e}function ba(t){t.fixed|=2}function _a(t){t.fixed&=-7}function wa(t){t.fixed|=4,t.px=t.x,t.py=t.y}function ka(t){t.fixed&=-5}t.interpolateTransform=ga,t.layout={},t.layout.bundle=function(){return function(t){for(var e=[],r=-1,n=t.length;++r<n;)e.push(ya(t[r]));return e}},t.layout.chord=function(){var e,r,n,i,a,o,s,l={},c=0;function u(){var l,u,f,p,d,g={},v=[],m=t.range(i),y=[];for(e=[],r=[],l=0,p=-1;++p<i;){for(u=0,d=-1;++d<i;)u+=n[p][d];v.push(u),y.push(t.range(i)),l+=u}for(a&&m.sort(function(t,e){return a(v[t],v[e])}),o&&y.forEach(function(t,e){t.sort(function(t,r){return o(n[e][t],n[e][r])})}),l=(Tt-c*i)/l,u=0,p=-1;++p<i;){for(f=u,d=-1;++d<i;){var x=m[p],b=y[x][d],_=n[x][b],w=u,k=u+=_*l;g[x+"-"+b]={index:x,subindex:b,startAngle:w,endAngle:k,value:_}}r[x]={index:x,startAngle:f,endAngle:u,value:v[x]},u+=c}for(p=-1;++p<i;)for(d=p-1;++d<i;){var A=g[p+"-"+d],M=g[d+"-"+p];(A.value||M.value)&&e.push(A.value<M.value?{source:M,target:A}:{source:A,target:M})}s&&h()}function h(){e.sort(function(t,e){return s((t.source.value+t.target.value)/2,(e.source.value+e.target.value)/2)})}return l.matrix=function(t){return arguments.length?(i=(n=t)&&n.length,e=r=null,l):n},l.padding=function(t){return arguments.length?(c=t,e=r=null,l):c},l.sortGroups=function(t){return arguments.length?(a=t,e=r=null,l):a},l.sortSubgroups=function(t){return arguments.length?(o=t,e=null,l):o},l.sortChords=function(t){return arguments.length?(s=t,e&&h(),l):s},l.chords=function(){return e||u(),e},l.groups=function(){return r||u(),r},l},t.layout.force=function(){var e,r,n,i,a,o,s={},l=t.dispatch("start","tick","end"),c=[1,1],u=.9,h=Aa,f=Ma,p=-30,d=Ta,g=.1,v=.64,m=[],y=[];function x(t){return function(e,r,n,i){if(e.point!==t){var a=e.cx-t.x,o=e.cy-t.y,s=i-r,l=a*a+o*o;if(s*s/v<l){if(l<d){var c=e.charge/l;t.px-=a*c,t.py-=o*c}return!0}if(e.point&&l&&l<d){c=e.pointCharge/l;t.px-=a*c,t.py-=o*c}}return!e.charge}}function b(e){e.px=t.event.x,e.py=t.event.y,s.resume()}return s.tick=function(){if((n*=.99)<.005)return e=null,l.end({type:"end",alpha:n=0}),!0;var r,s,h,f,d,v,b,_,w,k=m.length,A=y.length;for(s=0;s<A;++s)f=(h=y[s]).source,(v=(_=(d=h.target).x-f.x)*_+(w=d.y-f.y)*w)&&(_*=v=n*a[s]*((v=Math.sqrt(v))-i[s])/v,w*=v,d.x-=_*(b=f.weight+d.weight?f.weight/(f.weight+d.weight):.5),d.y-=w*b,f.x+=_*(b=1-b),f.y+=w*b);if((b=n*g)&&(_=c[0]/2,w=c[1]/2,s=-1,b))for(;++s<k;)(h=m[s]).x+=(_-h.x)*b,h.y+=(w-h.y)*b;if(p)for(!function t(e,r,n){var i=0,a=0;e.charge=0;if(!e.leaf)for(var o,s=e.nodes,l=s.length,c=-1;++c<l;)null!=(o=s[c])&&(t(o,r,n),e.charge+=o.charge,i+=o.charge*o.cx,a+=o.charge*o.cy);if(e.point){e.leaf||(e.point.x+=Math.random()-.5,e.point.y+=Math.random()-.5);var u=r*n[e.point.index];e.charge+=e.pointCharge=u,i+=u*e.point.x,a+=u*e.point.y}e.cx=i/e.charge;e.cy=a/e.charge}(r=t.geom.quadtree(m),n,o),s=-1;++s<k;)(h=m[s]).fixed||r.visit(x(h));for(s=-1;++s<k;)(h=m[s]).fixed?(h.x=h.px,h.y=h.py):(h.x-=(h.px-(h.px=h.x))*u,h.y-=(h.py-(h.py=h.y))*u);l.tick({type:"tick",alpha:n})},s.nodes=function(t){return arguments.length?(m=t,s):m},s.links=function(t){return arguments.length?(y=t,s):y},s.size=function(t){return arguments.length?(c=t,s):c},s.linkDistance=function(t){return arguments.length?(h="function"==typeof t?t:+t,s):h},s.distance=s.linkDistance,s.linkStrength=function(t){return arguments.length?(f="function"==typeof t?t:+t,s):f},s.friction=function(t){return arguments.length?(u=+t,s):u},s.charge=function(t){return arguments.length?(p="function"==typeof t?t:+t,s):p},s.chargeDistance=function(t){return arguments.length?(d=t*t,s):Math.sqrt(d)},s.gravity=function(t){return arguments.length?(g=+t,s):g},s.theta=function(t){return arguments.length?(v=t*t,s):Math.sqrt(v)},s.alpha=function(t){return arguments.length?(t=+t,n?t>0?n=t:(e.c=null,e.t=NaN,e=null,l.end({type:"end",alpha:n=0})):t>0&&(l.start({type:"start",alpha:n=t}),e=Ae(s.tick)),s):n},s.start=function(){var t,e,r,n=m.length,l=y.length,u=c[0],d=c[1];for(t=0;t<n;++t)(r=m[t]).index=t,r.weight=0;for(t=0;t<l;++t)"number"==typeof(r=y[t]).source&&(r.source=m[r.source]),"number"==typeof r.target&&(r.target=m[r.target]),++r.source.weight,++r.target.weight;for(t=0;t<n;++t)r=m[t],isNaN(r.x)&&(r.x=g("x",u)),isNaN(r.y)&&(r.y=g("y",d)),isNaN(r.px)&&(r.px=r.x),isNaN(r.py)&&(r.py=r.y);if(i=[],"function"==typeof h)for(t=0;t<l;++t)i[t]=+h.call(this,y[t],t);else for(t=0;t<l;++t)i[t]=h;if(a=[],"function"==typeof f)for(t=0;t<l;++t)a[t]=+f.call(this,y[t],t);else for(t=0;t<l;++t)a[t]=f;if(o=[],"function"==typeof p)for(t=0;t<n;++t)o[t]=+p.call(this,m[t],t);else for(t=0;t<n;++t)o[t]=p;function g(r,i){if(!e){for(e=new Array(n),c=0;c<n;++c)e[c]=[];for(c=0;c<l;++c){var a=y[c];e[a.source.index].push(a.target),e[a.target.index].push(a.source)}}for(var o,s=e[t],c=-1,u=s.length;++c<u;)if(!isNaN(o=s[c][r]))return o;return Math.random()*i}return s.resume()},s.resume=function(){return s.alpha(.1)},s.stop=function(){return s.alpha(0)},s.drag=function(){if(r||(r=t.behavior.drag().origin(z).on("dragstart.force",ba).on("drag.force",b).on("dragend.force",_a)),!arguments.length)return r;this.on("mouseover.force",wa).on("mouseout.force",ka).call(r)},t.rebind(s,l,"on")};var Aa=20,Ma=1,Ta=1/0;function Sa(e,r){return t.rebind(e,r,"sort","children","value"),e.nodes=e,e.links=Ia,e}function Ea(t,e){for(var r=[t];null!=(t=r.pop());)if(e(t),(i=t.children)&&(n=i.length))for(var n,i;--n>=0;)r.push(i[n])}function Ca(t,e){for(var r=[t],n=[];null!=(t=r.pop());)if(n.push(t),(a=t.children)&&(i=a.length))for(var i,a,o=-1;++o<i;)r.push(a[o]);for(;null!=(t=n.pop());)e(t)}function La(t){return t.children}function za(t){return t.value}function Oa(t,e){return e.value-t.value}function Ia(e){return t.merge(e.map(function(t){return(t.children||[]).map(function(e){return{source:t,target:e}})}))}t.layout.hierarchy=function(){var t=Oa,e=La,r=za;function n(i){var a,o=[i],s=[];for(i.depth=0;null!=(a=o.pop());)if(s.push(a),(c=e.call(n,a,a.depth))&&(l=c.length)){for(var l,c,u;--l>=0;)o.push(u=c[l]),u.parent=a,u.depth=a.depth+1;r&&(a.value=0),a.children=c}else r&&(a.value=+r.call(n,a,a.depth)||0),delete a.children;return Ca(i,function(e){var n,i;t&&(n=e.children)&&n.sort(t),r&&(i=e.parent)&&(i.value+=e.value)}),s}return n.sort=function(e){return arguments.length?(t=e,n):t},n.children=function(t){return arguments.length?(e=t,n):e},n.value=function(t){return arguments.length?(r=t,n):r},n.revalue=function(t){return r&&(Ea(t,function(t){t.children&&(t.value=0)}),Ca(t,function(t){var e;t.children||(t.value=+r.call(n,t,t.depth)||0),(e=t.parent)&&(e.value+=t.value)})),t},n},t.layout.partition=function(){var e=t.layout.hierarchy(),r=[1,1];function n(t,n){var i=e.call(this,t,n);return function t(e,r,n,i){var a=e.children;if(e.x=r,e.y=e.depth*i,e.dx=n,e.dy=i,a&&(o=a.length)){var o,s,l,c=-1;for(n=e.value?n/e.value:0;++c<o;)t(s=a[c],r,l=s.value*n,i),r+=l}}(i[0],0,r[0],r[1]/function t(e){var r=e.children,n=0;if(r&&(i=r.length))for(var i,a=-1;++a<i;)n=Math.max(n,t(r[a]));return 1+n}(i[0])),i}return n.size=function(t){return arguments.length?(r=t,n):r},Sa(n,e)},t.layout.pie=function(){var e=Number,r=Da,n=0,i=Tt,a=0;function o(s){var l,c=s.length,u=s.map(function(t,r){return+e.call(o,t,r)}),h=+("function"==typeof n?n.apply(this,arguments):n),f=("function"==typeof i?i.apply(this,arguments):i)-h,p=Math.min(Math.abs(f)/c,+("function"==typeof a?a.apply(this,arguments):a)),d=p*(f<0?-1:1),g=t.sum(u),v=g?(f-c*d)/g:0,m=t.range(c),y=[];return null!=r&&m.sort(r===Da?function(t,e){return u[e]-u[t]}:function(t,e){return r(s[t],s[e])}),m.forEach(function(t){y[t]={data:s[t],value:l=u[t],startAngle:h,endAngle:h+=l*v+d,padAngle:p}}),y}return o.value=function(t){return arguments.length?(e=t,o):e},o.sort=function(t){return arguments.length?(r=t,o):r},o.startAngle=function(t){return arguments.length?(n=t,o):n},o.endAngle=function(t){return arguments.length?(i=t,o):i},o.padAngle=function(t){return arguments.length?(a=t,o):a},o};var Da={};function Pa(t){return t.x}function Ra(t){return t.y}function Fa(t,e,r){t.y0=e,t.y=r}t.layout.stack=function(){var e=z,r=ja,n=Va,i=Fa,a=Pa,o=Ra;function s(l,c){if(!(p=l.length))return l;var u=l.map(function(t,r){return e.call(s,t,r)}),h=u.map(function(t){return t.map(function(t,e){return[a.call(s,t,e),o.call(s,t,e)]})}),f=r.call(s,h,c);u=t.permute(u,f),h=t.permute(h,f);var p,d,g,v,m=n.call(s,h,c),y=u[0].length;for(g=0;g<y;++g)for(i.call(s,u[0][g],v=m[g],h[0][g][1]),d=1;d<p;++d)i.call(s,u[d][g],v+=h[d-1][g][1],h[d][g][1]);return l}return s.values=function(t){return arguments.length?(e=t,s):e},s.order=function(t){return arguments.length?(r="function"==typeof t?t:Ba.get(t)||ja,s):r},s.offset=function(t){return arguments.length?(n="function"==typeof t?t:Na.get(t)||Va,s):n},s.x=function(t){return arguments.length?(a=t,s):a},s.y=function(t){return arguments.length?(o=t,s):o},s.out=function(t){return arguments.length?(i=t,s):i},s};var Ba=t.map({"inside-out":function(e){var r,n,i=e.length,a=e.map(Ua),o=e.map(qa),s=t.range(i).sort(function(t,e){return a[t]-a[e]}),l=0,c=0,u=[],h=[];for(r=0;r<i;++r)n=s[r],l<c?(l+=o[n],u.push(n)):(c+=o[n],h.push(n));return h.reverse().concat(u)},reverse:function(e){return t.range(e.length).reverse()},default:ja}),Na=t.map({silhouette:function(t){var e,r,n,i=t.length,a=t[0].length,o=[],s=0,l=[];for(r=0;r<a;++r){for(e=0,n=0;e<i;e++)n+=t[e][r][1];n>s&&(s=n),o.push(n)}for(r=0;r<a;++r)l[r]=(s-o[r])/2;return l},wiggle:function(t){var e,r,n,i,a,o,s,l,c,u=t.length,h=t[0],f=h.length,p=[];for(p[0]=l=c=0,r=1;r<f;++r){for(e=0,i=0;e<u;++e)i+=t[e][r][1];for(e=0,a=0,s=h[r][0]-h[r-1][0];e<u;++e){for(n=0,o=(t[e][r][1]-t[e][r-1][1])/(2*s);n<e;++n)o+=(t[n][r][1]-t[n][r-1][1])/s;a+=o*t[e][r][1]}p[r]=l-=i?a/i*s:0,l<c&&(c=l)}for(r=0;r<f;++r)p[r]-=c;return p},expand:function(t){var e,r,n,i=t.length,a=t[0].length,o=1/i,s=[];for(r=0;r<a;++r){for(e=0,n=0;e<i;e++)n+=t[e][r][1];if(n)for(e=0;e<i;e++)t[e][r][1]/=n;else for(e=0;e<i;e++)t[e][r][1]=o}for(r=0;r<a;++r)s[r]=0;return s},zero:Va});function ja(e){return t.range(e.length)}function Va(t){for(var e=-1,r=t[0].length,n=[];++e<r;)n[e]=0;return n}function Ua(t){for(var e,r=1,n=0,i=t[0][1],a=t.length;r<a;++r)(e=t[r][1])>i&&(n=r,i=e);return n}function qa(t){return t.reduce(Ha,0)}function Ha(t,e){return t+e[1]}function Ga(t,e){return Ya(t,Math.ceil(Math.log(e.length)/Math.LN2+1))}function Ya(t,e){for(var r=-1,n=+t[0],i=(t[1]-n)/e,a=[];++r<=e;)a[r]=i*r+n;return a}function Wa(e){return[t.min(e),t.max(e)]}function Xa(t,e){return t.value-e.value}function Za(t,e){var r=t._pack_next;t._pack_next=e,e._pack_prev=t,e._pack_next=r,r._pack_prev=e}function $a(t,e){t._pack_next=e,e._pack_prev=t}function Ja(t,e){var r=e.x-t.x,n=e.y-t.y,i=t.r+e.r;return.999*i*i>r*r+n*n}function Ka(t){if((e=t.children)&&(l=e.length)){var e,r,n,i,a,o,s,l,c=1/0,u=-1/0,h=1/0,f=-1/0;if(e.forEach(Qa),(r=e[0]).x=-r.r,r.y=0,x(r),l>1&&((n=e[1]).x=n.r,n.y=0,x(n),l>2))for(eo(r,n,i=e[2]),x(i),Za(r,i),r._pack_prev=i,Za(i,n),n=r._pack_next,a=3;a<l;a++){eo(r,n,i=e[a]);var p=0,d=1,g=1;for(o=n._pack_next;o!==n;o=o._pack_next,d++)if(Ja(o,i)){p=1;break}if(1==p)for(s=r._pack_prev;s!==o._pack_prev&&!Ja(s,i);s=s._pack_prev,g++);p?(d<g||d==g&&n.r<r.r?$a(r,n=o):$a(r=s,n),a--):(Za(r,i),n=i,x(i))}var v=(c+u)/2,m=(h+f)/2,y=0;for(a=0;a<l;a++)(i=e[a]).x-=v,i.y-=m,y=Math.max(y,i.r+Math.sqrt(i.x*i.x+i.y*i.y));t.r=y,e.forEach(to)}function x(t){c=Math.min(t.x-t.r,c),u=Math.max(t.x+t.r,u),h=Math.min(t.y-t.r,h),f=Math.max(t.y+t.r,f)}}function Qa(t){t._pack_next=t._pack_prev=t}function to(t){delete t._pack_next,delete t._pack_prev}function eo(t,e,r){var n=t.r+r.r,i=e.x-t.x,a=e.y-t.y;if(n&&(i||a)){var o=e.r+r.r,s=i*i+a*a,l=.5+((n*=n)-(o*=o))/(2*s),c=Math.sqrt(Math.max(0,2*o*(n+s)-(n-=s)*n-o*o))/(2*s);r.x=t.x+l*i+c*a,r.y=t.y+l*a-c*i}else r.x=t.x+n,r.y=t.y}function ro(t,e){return t.parent==e.parent?1:2}function no(t){var e=t.children;return e.length?e[0]:t.t}function io(t){var e,r=t.children;return(e=r.length)?r[e-1]:t.t}function ao(t,e,r){var n=r/(e.i-t.i);e.c-=n,e.s+=r,t.c+=n,e.z+=r,e.m+=r}function oo(t,e,r){return t.a.parent===e.parent?t.a:r}function so(t){return{x:t.x,y:t.y,dx:t.dx,dy:t.dy}}function lo(t,e){var r=t.x+e[3],n=t.y+e[0],i=t.dx-e[1]-e[3],a=t.dy-e[0]-e[2];return i<0&&(r+=i/2,i=0),a<0&&(n+=a/2,a=0),{x:r,y:n,dx:i,dy:a}}function co(t){var e=t[0],r=t[t.length-1];return e<r?[e,r]:[r,e]}function uo(t){return t.rangeExtent?t.rangeExtent():co(t.range())}function ho(t,e,r,n){var i=r(t[0],t[1]),a=n(e[0],e[1]);return function(t){return a(i(t))}}function fo(t,e){var r,n=0,i=t.length-1,a=t[n],o=t[i];return o<a&&(r=n,n=i,i=r,r=a,a=o,o=r),t[n]=e.floor(a),t[i]=e.ceil(o),t}function po(t){return t?{floor:function(e){return Math.floor(e/t)*t},ceil:function(e){return Math.ceil(e/t)*t}}:go}t.layout.histogram=function(){var e=!0,r=Number,n=Wa,i=Ga;function a(a,o){for(var s,l,c=[],u=a.map(r,this),h=n.call(this,u,o),f=i.call(this,h,u,o),p=(o=-1,u.length),d=f.length-1,g=e?1:1/p;++o<d;)(s=c[o]=[]).dx=f[o+1]-(s.x=f[o]),s.y=0;if(d>0)for(o=-1;++o<p;)(l=u[o])>=h[0]&&l<=h[1]&&((s=c[t.bisect(f,l,1,d)-1]).y+=g,s.push(a[o]));return c}return a.value=function(t){return arguments.length?(r=t,a):r},a.range=function(t){return arguments.length?(n=ve(t),a):n},a.bins=function(t){return arguments.length?(i="number"==typeof t?function(e){return Ya(e,t)}:ve(t),a):i},a.frequency=function(t){return arguments.length?(e=!!t,a):e},a},t.layout.pack=function(){var e,r=t.layout.hierarchy().sort(Xa),n=0,i=[1,1];function a(t,a){var o=r.call(this,t,a),s=o[0],l=i[0],c=i[1],u=null==e?Math.sqrt:"function"==typeof e?e:function(){return e};if(s.x=s.y=0,Ca(s,function(t){t.r=+u(t.value)}),Ca(s,Ka),n){var h=n*(e?1:Math.max(2*s.r/l,2*s.r/c))/2;Ca(s,function(t){t.r+=h}),Ca(s,Ka),Ca(s,function(t){t.r-=h})}return function t(e,r,n,i){var a=e.children;e.x=r+=i*e.x;e.y=n+=i*e.y;e.r*=i;if(a)for(var o=-1,s=a.length;++o<s;)t(a[o],r,n,i)}(s,l/2,c/2,e?1:1/Math.max(2*s.r/l,2*s.r/c)),o}return a.size=function(t){return arguments.length?(i=t,a):i},a.radius=function(t){return arguments.length?(e=null==t||"function"==typeof t?t:+t,a):e},a.padding=function(t){return arguments.length?(n=+t,a):n},Sa(a,r)},t.layout.tree=function(){var e=t.layout.hierarchy().sort(null).value(null),r=ro,n=[1,1],i=null;function a(t,a){var c=e.call(this,t,a),u=c[0],h=function(t){var e,r={A:null,children:[t]},n=[r];for(;null!=(e=n.pop());)for(var i,a=e.children,o=0,s=a.length;o<s;++o)n.push((a[o]=i={_:a[o],parent:e,children:(i=a[o].children)&&i.slice()||[],A:null,a:null,z:0,m:0,c:0,s:0,t:null,i:o}).a=i);return r.children[0]}(u);if(Ca(h,o),h.parent.m=-h.z,Ea(h,s),i)Ea(u,l);else{var f=u,p=u,d=u;Ea(u,function(t){t.x<f.x&&(f=t),t.x>p.x&&(p=t),t.depth>d.depth&&(d=t)});var g=r(f,p)/2-f.x,v=n[0]/(p.x+r(p,f)/2+g),m=n[1]/(d.depth||1);Ea(u,function(t){t.x=(t.x+g)*v,t.y=t.depth*m})}return c}function o(t){var e=t.children,n=t.parent.children,i=t.i?n[t.i-1]:null;if(e.length){!function(t){var e,r=0,n=0,i=t.children,a=i.length;for(;--a>=0;)(e=i[a]).z+=r,e.m+=r,r+=e.s+(n+=e.c)}(t);var a=(e[0].z+e[e.length-1].z)/2;i?(t.z=i.z+r(t._,i._),t.m=t.z-a):t.z=a}else i&&(t.z=i.z+r(t._,i._));t.parent.A=function(t,e,n){if(e){for(var i,a=t,o=t,s=e,l=a.parent.children[0],c=a.m,u=o.m,h=s.m,f=l.m;s=io(s),a=no(a),s&&a;)l=no(l),(o=io(o)).a=t,(i=s.z+h-a.z-c+r(s._,a._))>0&&(ao(oo(s,t,n),t,i),c+=i,u+=i),h+=s.m,c+=a.m,f+=l.m,u+=o.m;s&&!io(o)&&(o.t=s,o.m+=h-u),a&&!no(l)&&(l.t=a,l.m+=c-f,n=t)}return n}(t,i,t.parent.A||n[0])}function s(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function l(t){t.x*=n[0],t.y=t.depth*n[1]}return a.separation=function(t){return arguments.length?(r=t,a):r},a.size=function(t){return arguments.length?(i=null==(n=t)?l:null,a):i?null:n},a.nodeSize=function(t){return arguments.length?(i=null==(n=t)?null:l,a):i?n:null},Sa(a,e)},t.layout.cluster=function(){var e=t.layout.hierarchy().sort(null).value(null),r=ro,n=[1,1],i=!1;function a(a,o){var s,l=e.call(this,a,o),c=l[0],u=0;Ca(c,function(e){var n=e.children;n&&n.length?(e.x=function(t){return t.reduce(function(t,e){return t+e.x},0)/t.length}(n),e.y=function(e){return 1+t.max(e,function(t){return t.y})}(n)):(e.x=s?u+=r(e,s):0,e.y=0,s=e)});var h=function t(e){var r=e.children;return r&&r.length?t(r[0]):e}(c),f=function t(e){var r,n=e.children;return n&&(r=n.length)?t(n[r-1]):e}(c),p=h.x-r(h,f)/2,d=f.x+r(f,h)/2;return Ca(c,i?function(t){t.x=(t.x-c.x)*n[0],t.y=(c.y-t.y)*n[1]}:function(t){t.x=(t.x-p)/(d-p)*n[0],t.y=(1-(c.y?t.y/c.y:1))*n[1]}),l}return a.separation=function(t){return arguments.length?(r=t,a):r},a.size=function(t){return arguments.length?(i=null==(n=t),a):i?null:n},a.nodeSize=function(t){return arguments.length?(i=null!=(n=t),a):i?n:null},Sa(a,e)},t.layout.treemap=function(){var e,r=t.layout.hierarchy(),n=Math.round,i=[1,1],a=null,o=so,s=!1,l="squarify",c=.5*(1+Math.sqrt(5));function u(t,e){for(var r,n,i=-1,a=t.length;++i<a;)n=(r=t[i]).value*(e<0?0:e),r.area=isNaN(n)||n<=0?0:n}function h(t){var e=t.children;if(e&&e.length){var r,n,i,a=o(t),s=[],c=e.slice(),f=1/0,g="slice"===l?a.dx:"dice"===l?a.dy:"slice-dice"===l?1&t.depth?a.dy:a.dx:Math.min(a.dx,a.dy);for(u(c,a.dx*a.dy/t.value),s.area=0;(i=c.length)>0;)s.push(r=c[i-1]),s.area+=r.area,"squarify"!==l||(n=p(s,g))<=f?(c.pop(),f=n):(s.area-=s.pop().area,d(s,g,a,!1),g=Math.min(a.dx,a.dy),s.length=s.area=0,f=1/0);s.length&&(d(s,g,a,!0),s.length=s.area=0),e.forEach(h)}}function f(t){var e=t.children;if(e&&e.length){var r,n=o(t),i=e.slice(),a=[];for(u(i,n.dx*n.dy/t.value),a.area=0;r=i.pop();)a.push(r),a.area+=r.area,null!=r.z&&(d(a,r.z?n.dx:n.dy,n,!i.length),a.length=a.area=0);e.forEach(f)}}function p(t,e){for(var r,n=t.area,i=0,a=1/0,o=-1,s=t.length;++o<s;)(r=t[o].area)&&(r<a&&(a=r),r>i&&(i=r));return e*=e,(n*=n)?Math.max(e*i*c/n,n/(e*a*c)):1/0}function d(t,e,r,i){var a,o=-1,s=t.length,l=r.x,c=r.y,u=e?n(t.area/e):0;if(e==r.dx){for((i||u>r.dy)&&(u=r.dy);++o<s;)(a=t[o]).x=l,a.y=c,a.dy=u,l+=a.dx=Math.min(r.x+r.dx-l,u?n(a.area/u):0);a.z=!0,a.dx+=r.x+r.dx-l,r.y+=u,r.dy-=u}else{for((i||u>r.dx)&&(u=r.dx);++o<s;)(a=t[o]).x=l,a.y=c,a.dx=u,c+=a.dy=Math.min(r.y+r.dy-c,u?n(a.area/u):0);a.z=!1,a.dy+=r.y+r.dy-c,r.x+=u,r.dx-=u}}function g(t){var n=e||r(t),a=n[0];return a.x=a.y=0,a.value?(a.dx=i[0],a.dy=i[1]):a.dx=a.dy=0,e&&r.revalue(a),u([a],a.dx*a.dy/a.value),(e?f:h)(a),s&&(e=n),n}return g.size=function(t){return arguments.length?(i=t,g):i},g.padding=function(t){if(!arguments.length)return a;function e(e){return lo(e,t)}var r;return o=null==(a=t)?so:"function"==(r=typeof t)?function(e){var r=t.call(g,e,e.depth);return null==r?so(e):lo(e,"number"==typeof r?[r,r,r,r]:r)}:"number"===r?(t=[t,t,t,t],e):e,g},g.round=function(t){return arguments.length?(n=t?Math.round:Number,g):n!=Number},g.sticky=function(t){return arguments.length?(s=t,e=null,g):s},g.ratio=function(t){return arguments.length?(c=t,g):c},g.mode=function(t){return arguments.length?(l=t+"",g):l},Sa(g,r)},t.random={normal:function(t,e){var r=arguments.length;return r<2&&(e=1),r<1&&(t=0),function(){var r,n,i;do{i=(r=2*Math.random()-1)*r+(n=2*Math.random()-1)*n}while(!i||i>1);return t+e*r*Math.sqrt(-2*Math.log(i)/i)}},logNormal:function(){var e=t.random.normal.apply(t,arguments);return function(){return Math.exp(e())}},bates:function(e){var r=t.random.irwinHall(e);return function(){return r()/e}},irwinHall:function(t){return function(){for(var e=0,r=0;r<t;r++)e+=Math.random();return e}}},t.scale={};var go={floor:z,ceil:z};function vo(e,r,n,i){var a=[],o=[],s=0,l=Math.min(e.length,r.length)-1;for(e[l]<e[0]&&(e=e.slice().reverse(),r=r.slice().reverse());++s<=l;)a.push(n(e[s-1],e[s])),o.push(i(r[s-1],r[s]));return function(r){var n=t.bisect(e,r,1,l)-1;return o[n](a[n](r))}}function mo(e,r){return t.rebind(e,r,"range","rangeRound","interpolate","clamp")}function yo(t,e){return fo(t,po(xo(t,e)[2])),fo(t,po(xo(t,e)[2])),t}function xo(t,e){null==e&&(e=10);var r=co(t),n=r[1]-r[0],i=Math.pow(10,Math.floor(Math.log(n/e)/Math.LN10)),a=e/n*i;return a<=.15?i*=10:a<=.35?i*=5:a<=.75&&(i*=2),r[0]=Math.ceil(r[0]/i)*i,r[1]=Math.floor(r[1]/i)*i+.5*i,r[2]=i,r}function bo(e,r){return t.range.apply(t,xo(e,r))}function _o(e,r,n){var i=xo(e,r);if(n){var a=Le.exec(n);if(a.shift(),"s"===a[8]){var o=t.formatPrefix(Math.max(y(i[0]),y(i[1])));return a[7]||(a[7]="."+ko(o.scale(i[2]))),a[8]="f",n=t.format(a.join("")),function(t){return n(o.scale(t))+o.symbol}}a[7]||(a[7]="."+function(t,e){var r=ko(e[2]);return t in wo?Math.abs(r-ko(Math.max(y(e[0]),y(e[1]))))+ +("e"!==t):r-2*("%"===t)}(a[8],i)),n=a.join("")}else n=",."+ko(i[2])+"f";return t.format(n)}t.scale.linear=function(){return function t(e,r,n,i){var a,o;function s(){var t=Math.min(e.length,r.length)>2?vo:ho,s=i?ma:va;return a=t(e,r,s,n),o=t(r,e,s,Zi),l}function l(t){return a(t)}l.invert=function(t){return o(t)};l.domain=function(t){return arguments.length?(e=t.map(Number),s()):e};l.range=function(t){return arguments.length?(r=t,s()):r};l.rangeRound=function(t){return l.range(t).interpolate(ca)};l.clamp=function(t){return arguments.length?(i=t,s()):i};l.interpolate=function(t){return arguments.length?(n=t,s()):n};l.ticks=function(t){return bo(e,t)};l.tickFormat=function(t,r){return _o(e,t,r)};l.nice=function(t){return yo(e,t),s()};l.copy=function(){return t(e,r,n,i)};return s()}([0,1],[0,1],Zi,!1)};var wo={s:1,g:1,p:1,r:1,e:1};function ko(t){return-Math.floor(Math.log(t)/Math.LN10+.01)}t.scale.log=function(){return function e(r,n,i,a){function o(t){return(i?Math.log(t<0?0:t):-Math.log(t>0?0:-t))/Math.log(n)}function s(t){return i?Math.pow(n,t):-Math.pow(n,-t)}function l(t){return r(o(t))}l.invert=function(t){return s(r.invert(t))};l.domain=function(t){return arguments.length?(i=t[0]>=0,r.domain((a=t.map(Number)).map(o)),l):a};l.base=function(t){return arguments.length?(n=+t,r.domain(a.map(o)),l):n};l.nice=function(){var t=fo(a.map(o),i?Math:Mo);return r.domain(t),a=t.map(s),l};l.ticks=function(){var t=co(a),e=[],r=t[0],l=t[1],c=Math.floor(o(r)),u=Math.ceil(o(l)),h=n%1?2:n;if(isFinite(u-c)){if(i){for(;c<u;c++)for(var f=1;f<h;f++)e.push(s(c)*f);e.push(s(c))}else for(e.push(s(c));c++<u;)for(var f=h-1;f>0;f--)e.push(s(c)*f);for(c=0;e[c]<r;c++);for(u=e.length;e[u-1]>l;u--);e=e.slice(c,u)}return e};l.tickFormat=function(e,r){if(!arguments.length)return Ao;arguments.length<2?r=Ao:"function"!=typeof r&&(r=t.format(r));var i=Math.max(1,n*e/l.ticks().length);return function(t){var e=t/s(Math.round(o(t)));return e*n<n-.5&&(e*=n),e<=i?r(t):""}};l.copy=function(){return e(r.copy(),n,i,a)};return mo(l,r)}(t.scale.linear().domain([0,1]),10,!0,[1,10])};var Ao=t.format(".0e"),Mo={floor:function(t){return-Math.ceil(-t)},ceil:function(t){return-Math.floor(-t)}};function To(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}t.scale.pow=function(){return function t(e,r,n){var i=To(r),a=To(1/r);function o(t){return e(i(t))}o.invert=function(t){return a(e.invert(t))};o.domain=function(t){return arguments.length?(e.domain((n=t.map(Number)).map(i)),o):n};o.ticks=function(t){return bo(n,t)};o.tickFormat=function(t,e){return _o(n,t,e)};o.nice=function(t){return o.domain(yo(n,t))};o.exponent=function(t){return arguments.length?(i=To(r=t),a=To(1/r),e.domain(n.map(i)),o):r};o.copy=function(){return t(e.copy(),r,n)};return mo(o,e)}(t.scale.linear(),1,[0,1])},t.scale.sqrt=function(){return t.scale.pow().exponent(.5)},t.scale.ordinal=function(){return function e(r,n){var i,a,o;function s(t){return a[((i.get(t)||("range"===n.t?i.set(t,r.push(t)):NaN))-1)%a.length]}function l(e,n){return t.range(r.length).map(function(t){return e+n*t})}s.domain=function(t){if(!arguments.length)return r;r=[],i=new b;for(var e,a=-1,o=t.length;++a<o;)i.has(e=t[a])||i.set(e,r.push(e));return s[n.t].apply(s,n.a)};s.range=function(t){return arguments.length?(a=t,o=0,n={t:"range",a:arguments},s):a};s.rangePoints=function(t,e){arguments.length<2&&(e=0);var i=t[0],c=t[1],u=r.length<2?(i=(i+c)/2,0):(c-i)/(r.length-1+e);return a=l(i+u*e/2,u),o=0,n={t:"rangePoints",a:arguments},s};s.rangeRoundPoints=function(t,e){arguments.length<2&&(e=0);var i=t[0],c=t[1],u=r.length<2?(i=c=Math.round((i+c)/2),0):(c-i)/(r.length-1+e)|0;return a=l(i+Math.round(u*e/2+(c-i-(r.length-1+e)*u)/2),u),o=0,n={t:"rangeRoundPoints",a:arguments},s};s.rangeBands=function(t,e,i){arguments.length<2&&(e=0),arguments.length<3&&(i=e);var c=t[1]<t[0],u=t[c-0],h=t[1-c],f=(h-u)/(r.length-e+2*i);return a=l(u+f*i,f),c&&a.reverse(),o=f*(1-e),n={t:"rangeBands",a:arguments},s};s.rangeRoundBands=function(t,e,i){arguments.length<2&&(e=0),arguments.length<3&&(i=e);var c=t[1]<t[0],u=t[c-0],h=t[1-c],f=Math.floor((h-u)/(r.length-e+2*i));return a=l(u+Math.round((h-u-(r.length-e)*f)/2),f),c&&a.reverse(),o=Math.round(f*(1-e)),n={t:"rangeRoundBands",a:arguments},s};s.rangeBand=function(){return o};s.rangeExtent=function(){return co(n.a[0])};s.copy=function(){return e(r,n)};return s.domain(r)}([],{t:"range",a:[[]]})},t.scale.category10=function(){return t.scale.ordinal().range(So)},t.scale.category20=function(){return t.scale.ordinal().range(Eo)},t.scale.category20b=function(){return t.scale.ordinal().range(Co)},t.scale.category20c=function(){return t.scale.ordinal().range(Lo)};var So=[2062260,16744206,2924588,14034728,9725885,9197131,14907330,8355711,12369186,1556175].map(se),Eo=[2062260,11454440,16744206,16759672,2924588,10018698,14034728,16750742,9725885,12955861,9197131,12885140,14907330,16234194,8355711,13092807,12369186,14408589,1556175,10410725].map(se),Co=[3750777,5395619,7040719,10264286,6519097,9216594,11915115,13556636,9202993,12426809,15186514,15190932,8666169,11356490,14049643,15177372,8077683,10834324,13528509,14589654].map(se),Lo=[3244733,7057110,10406625,13032431,15095053,16616764,16625259,16634018,3253076,7652470,10607003,13101504,7695281,10394312,12369372,14342891,6513507,9868950,12434877,14277081].map(se);function zo(){return 0}t.scale.quantile=function(){return function e(r,n){var i;function a(){var e=0,a=n.length;for(i=[];++e<a;)i[e-1]=t.quantile(r,e/a);return o}function o(e){if(!isNaN(e=+e))return n[t.bisect(i,e)]}o.domain=function(t){return arguments.length?(r=t.map(p).filter(d).sort(f),a()):r};o.range=function(t){return arguments.length?(n=t,a()):n};o.quantiles=function(){return i};o.invertExtent=function(t){return(t=n.indexOf(t))<0?[NaN,NaN]:[t>0?i[t-1]:r[0],t<i.length?i[t]:r[r.length-1]]};o.copy=function(){return e(r,n)};return a()}([],[])},t.scale.quantize=function(){return function t(e,r,n){var i,a;function o(t){return n[Math.max(0,Math.min(a,Math.floor(i*(t-e))))]}function s(){return i=n.length/(r-e),a=n.length-1,o}o.domain=function(t){return arguments.length?(e=+t[0],r=+t[t.length-1],s()):[e,r]};o.range=function(t){return arguments.length?(n=t,s()):n};o.invertExtent=function(t){return[t=(t=n.indexOf(t))<0?NaN:t/i+e,t+1/i]};o.copy=function(){return t(e,r,n)};return s()}(0,1,[0,1])},t.scale.threshold=function(){return function e(r,n){function i(e){if(e<=e)return n[t.bisect(r,e)]}i.domain=function(t){return arguments.length?(r=t,i):r};i.range=function(t){return arguments.length?(n=t,i):n};i.invertExtent=function(t){return t=n.indexOf(t),[r[t-1],r[t]]};i.copy=function(){return e(r,n)};return i}([.5],[0,1])},t.scale.identity=function(){return function t(e){function r(t){return+t}r.invert=r;r.domain=r.range=function(t){return arguments.length?(e=t.map(r),r):e};r.ticks=function(t){return bo(e,t)};r.tickFormat=function(t,r){return _o(e,t,r)};r.copy=function(){return t(e)};return r}([0,1])},t.svg={},t.svg.arc=function(){var t=Io,e=Do,r=zo,n=Oo,i=Po,a=Ro,o=Fo;function s(){var s=Math.max(0,+t.apply(this,arguments)),c=Math.max(0,+e.apply(this,arguments)),u=i.apply(this,arguments)-Et,h=a.apply(this,arguments)-Et,f=Math.abs(h-u),p=u>h?0:1;if(c<s&&(d=c,c=s,s=d),f>=St)return l(c,p)+(s?l(s,1-p):"")+"Z";var d,g,v,m,y,x,b,_,w,k,A,M,T=0,S=0,E=[];if((m=(+o.apply(this,arguments)||0)/2)&&(v=n===Oo?Math.sqrt(s*s+c*c):+n.apply(this,arguments),p||(S*=-1),c&&(S=Dt(v/c*Math.sin(m))),s&&(T=Dt(v/s*Math.sin(m)))),c){y=c*Math.cos(u+S),x=c*Math.sin(u+S),b=c*Math.cos(h-S),_=c*Math.sin(h-S);var C=Math.abs(h-u-2*S)<=Mt?0:1;if(S&&Bo(y,x,b,_)===p^C){var L=(u+h)/2;y=c*Math.cos(L),x=c*Math.sin(L),b=_=null}}else y=x=0;if(s){w=s*Math.cos(h-T),k=s*Math.sin(h-T),A=s*Math.cos(u+T),M=s*Math.sin(u+T);var z=Math.abs(u-h+2*T)<=Mt?0:1;if(T&&Bo(w,k,A,M)===1-p^z){var O=(u+h)/2;w=s*Math.cos(O),k=s*Math.sin(O),A=M=null}}else w=k=0;if(f>kt&&(d=Math.min(Math.abs(c-s)/2,+r.apply(this,arguments)))>.001){g=s<c^p?0:1;var I=d,D=d;if(f<Mt){var P=null==A?[w,k]:null==b?[y,x]:si([y,x],[A,M],[b,_],[w,k]),R=y-P[0],F=x-P[1],B=b-P[0],N=_-P[1],j=1/Math.sin(Math.acos((R*B+F*N)/(Math.sqrt(R*R+F*F)*Math.sqrt(B*B+N*N)))/2),V=Math.sqrt(P[0]*P[0]+P[1]*P[1]);D=Math.min(d,(s-V)/(j-1)),I=Math.min(d,(c-V)/(j+1))}if(null!=b){var U=No(null==A?[w,k]:[A,M],[y,x],c,I,p),q=No([b,_],[w,k],c,I,p);d===I?E.push("M",U[0],"A",I,",",I," 0 0,",g," ",U[1],"A",c,",",c," 0 ",1-p^Bo(U[1][0],U[1][1],q[1][0],q[1][1]),",",p," ",q[1],"A",I,",",I," 0 0,",g," ",q[0]):E.push("M",U[0],"A",I,",",I," 0 1,",g," ",q[0])}else E.push("M",y,",",x);if(null!=A){var H=No([y,x],[A,M],s,-D,p),G=No([w,k],null==b?[y,x]:[b,_],s,-D,p);d===D?E.push("L",G[0],"A",D,",",D," 0 0,",g," ",G[1],"A",s,",",s," 0 ",p^Bo(G[1][0],G[1][1],H[1][0],H[1][1]),",",1-p," ",H[1],"A",D,",",D," 0 0,",g," ",H[0]):E.push("L",G[0],"A",D,",",D," 0 0,",g," ",H[0])}else E.push("L",w,",",k)}else E.push("M",y,",",x),null!=b&&E.push("A",c,",",c," 0 ",C,",",p," ",b,",",_),E.push("L",w,",",k),null!=A&&E.push("A",s,",",s," 0 ",z,",",1-p," ",A,",",M);return E.push("Z"),E.join("")}function l(t,e){return"M0,"+t+"A"+t+","+t+" 0 1,"+e+" 0,"+-t+"A"+t+","+t+" 0 1,"+e+" 0,"+t}return s.innerRadius=function(e){return arguments.length?(t=ve(e),s):t},s.outerRadius=function(t){return arguments.length?(e=ve(t),s):e},s.cornerRadius=function(t){return arguments.length?(r=ve(t),s):r},s.padRadius=function(t){return arguments.length?(n=t==Oo?Oo:ve(t),s):n},s.startAngle=function(t){return arguments.length?(i=ve(t),s):i},s.endAngle=function(t){return arguments.length?(a=ve(t),s):a},s.padAngle=function(t){return arguments.length?(o=ve(t),s):o},s.centroid=function(){var r=(+t.apply(this,arguments)+ +e.apply(this,arguments))/2,n=(+i.apply(this,arguments)+ +a.apply(this,arguments))/2-Et;return[Math.cos(n)*r,Math.sin(n)*r]},s};var Oo="auto";function Io(t){return t.innerRadius}function Do(t){return t.outerRadius}function Po(t){return t.startAngle}function Ro(t){return t.endAngle}function Fo(t){return t&&t.padAngle}function Bo(t,e,r,n){return(t-r)*e-(e-n)*t>0?0:1}function No(t,e,r,n,i){var a=t[0]-e[0],o=t[1]-e[1],s=(i?n:-n)/Math.sqrt(a*a+o*o),l=s*o,c=-s*a,u=t[0]+l,h=t[1]+c,f=e[0]+l,p=e[1]+c,d=(u+f)/2,g=(h+p)/2,v=f-u,m=p-h,y=v*v+m*m,x=r-n,b=u*p-f*h,_=(m<0?-1:1)*Math.sqrt(Math.max(0,x*x*y-b*b)),w=(b*m-v*_)/y,k=(-b*v-m*_)/y,A=(b*m+v*_)/y,M=(-b*v+m*_)/y,T=w-d,S=k-g,E=A-d,C=M-g;return T*T+S*S>E*E+C*C&&(w=A,k=M),[[w-l,k-c],[w*r/x,k*r/x]]}function jo(t){var e=ei,r=ri,n=Yr,i=Uo,a=i.key,o=.7;function s(a){var s,l=[],c=[],u=-1,h=a.length,f=ve(e),p=ve(r);function d(){l.push("M",i(t(c),o))}for(;++u<h;)n.call(this,s=a[u],u)?c.push([+f.call(this,s,u),+p.call(this,s,u)]):c.length&&(d(),c=[]);return c.length&&d(),l.length?l.join(""):null}return s.x=function(t){return arguments.length?(e=t,s):e},s.y=function(t){return arguments.length?(r=t,s):r},s.defined=function(t){return arguments.length?(n=t,s):n},s.interpolate=function(t){return arguments.length?(a="function"==typeof t?i=t:(i=Vo.get(t)||Uo).key,s):a},s.tension=function(t){return arguments.length?(o=t,s):o},s}t.svg.line=function(){return jo(z)};var Vo=t.map({linear:Uo,"linear-closed":qo,step:function(t){var e=0,r=t.length,n=t[0],i=[n[0],",",n[1]];for(;++e<r;)i.push("H",(n[0]+(n=t[e])[0])/2,"V",n[1]);r>1&&i.push("H",n[0]);return i.join("")},"step-before":Ho,"step-after":Go,basis:Xo,"basis-open":function(t){if(t.length<4)return Uo(t);var e,r=[],n=-1,i=t.length,a=[0],o=[0];for(;++n<3;)e=t[n],a.push(e[0]),o.push(e[1]);r.push(Zo(Ko,a)+","+Zo(Ko,o)),--n;for(;++n<i;)e=t[n],a.shift(),a.push(e[0]),o.shift(),o.push(e[1]),Qo(r,a,o);return r.join("")},"basis-closed":function(t){var e,r,n=-1,i=t.length,a=i+4,o=[],s=[];for(;++n<4;)r=t[n%i],o.push(r[0]),s.push(r[1]);e=[Zo(Ko,o),",",Zo(Ko,s)],--n;for(;++n<a;)r=t[n%i],o.shift(),o.push(r[0]),s.shift(),s.push(r[1]),Qo(e,o,s);return e.join("")},bundle:function(t,e){var r=t.length-1;if(r)for(var n,i,a=t[0][0],o=t[0][1],s=t[r][0]-a,l=t[r][1]-o,c=-1;++c<=r;)n=t[c],i=c/r,n[0]=e*n[0]+(1-e)*(a+i*s),n[1]=e*n[1]+(1-e)*(o+i*l);return Xo(t)},cardinal:function(t,e){return t.length<3?Uo(t):t[0]+Yo(t,Wo(t,e))},"cardinal-open":function(t,e){return t.length<4?Uo(t):t[1]+Yo(t.slice(1,-1),Wo(t,e))},"cardinal-closed":function(t,e){return t.length<3?qo(t):t[0]+Yo((t.push(t[0]),t),Wo([t[t.length-2]].concat(t,[t[1]]),e))},monotone:function(t){return t.length<3?Uo(t):t[0]+Yo(t,function(t){var e,r,n,i,a=[],o=function(t){var e=0,r=t.length-1,n=[],i=t[0],a=t[1],o=n[0]=ts(i,a);for(;++e<r;)n[e]=(o+(o=ts(i=a,a=t[e+1])))/2;return n[e]=o,n}(t),s=-1,l=t.length-1;for(;++s<l;)e=ts(t[s],t[s+1]),y(e)<kt?o[s]=o[s+1]=0:(r=o[s]/e,n=o[s+1]/e,(i=r*r+n*n)>9&&(i=3*e/Math.sqrt(i),o[s]=i*r,o[s+1]=i*n));s=-1;for(;++s<=l;)i=(t[Math.min(l,s+1)][0]-t[Math.max(0,s-1)][0])/(6*(1+o[s]*o[s])),a.push([i||0,o[s]*i||0]);return a}(t))}});function Uo(t){return t.length>1?t.join("L"):t+"Z"}function qo(t){return t.join("L")+"Z"}function Ho(t){for(var e=0,r=t.length,n=t[0],i=[n[0],",",n[1]];++e<r;)i.push("V",(n=t[e])[1],"H",n[0]);return i.join("")}function Go(t){for(var e=0,r=t.length,n=t[0],i=[n[0],",",n[1]];++e<r;)i.push("H",(n=t[e])[0],"V",n[1]);return i.join("")}function Yo(t,e){if(e.length<1||t.length!=e.length&&t.length!=e.length+2)return Uo(t);var r=t.length!=e.length,n="",i=t[0],a=t[1],o=e[0],s=o,l=1;if(r&&(n+="Q"+(a[0]-2*o[0]/3)+","+(a[1]-2*o[1]/3)+","+a[0]+","+a[1],i=t[1],l=2),e.length>1){s=e[1],a=t[l],l++,n+="C"+(i[0]+o[0])+","+(i[1]+o[1])+","+(a[0]-s[0])+","+(a[1]-s[1])+","+a[0]+","+a[1];for(var c=2;c<e.length;c++,l++)a=t[l],s=e[c],n+="S"+(a[0]-s[0])+","+(a[1]-s[1])+","+a[0]+","+a[1]}if(r){var u=t[l];n+="Q"+(a[0]+2*s[0]/3)+","+(a[1]+2*s[1]/3)+","+u[0]+","+u[1]}return n}function Wo(t,e){for(var r,n=[],i=(1-e)/2,a=t[0],o=t[1],s=1,l=t.length;++s<l;)r=a,a=o,o=t[s],n.push([i*(o[0]-r[0]),i*(o[1]-r[1])]);return n}function Xo(t){if(t.length<3)return Uo(t);var e=1,r=t.length,n=t[0],i=n[0],a=n[1],o=[i,i,i,(n=t[1])[0]],s=[a,a,a,n[1]],l=[i,",",a,"L",Zo(Ko,o),",",Zo(Ko,s)];for(t.push(t[r-1]);++e<=r;)n=t[e],o.shift(),o.push(n[0]),s.shift(),s.push(n[1]),Qo(l,o,s);return t.pop(),l.push("L",n),l.join("")}function Zo(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]}Vo.forEach(function(t,e){e.key=t,e.closed=/-closed$/.test(t)});var $o=[0,2/3,1/3,0],Jo=[0,1/3,2/3,0],Ko=[0,1/6,2/3,1/6];function Qo(t,e,r){t.push("C",Zo($o,e),",",Zo($o,r),",",Zo(Jo,e),",",Zo(Jo,r),",",Zo(Ko,e),",",Zo(Ko,r))}function ts(t,e){return(e[1]-t[1])/(e[0]-t[0])}function es(t){for(var e,r,n,i=-1,a=t.length;++i<a;)r=(e=t[i])[0],n=e[1]-Et,e[0]=r*Math.cos(n),e[1]=r*Math.sin(n);return t}function rs(t){var e=ei,r=ei,n=0,i=ri,a=Yr,o=Uo,s=o.key,l=o,c="L",u=.7;function h(s){var h,f,p,d=[],g=[],v=[],m=-1,y=s.length,x=ve(e),b=ve(n),_=e===r?function(){return f}:ve(r),w=n===i?function(){return p}:ve(i);function k(){d.push("M",o(t(v),u),c,l(t(g.reverse()),u),"Z")}for(;++m<y;)a.call(this,h=s[m],m)?(g.push([f=+x.call(this,h,m),p=+b.call(this,h,m)]),v.push([+_.call(this,h,m),+w.call(this,h,m)])):g.length&&(k(),g=[],v=[]);return g.length&&k(),d.length?d.join(""):null}return h.x=function(t){return arguments.length?(e=r=t,h):r},h.x0=function(t){return arguments.length?(e=t,h):e},h.x1=function(t){return arguments.length?(r=t,h):r},h.y=function(t){return arguments.length?(n=i=t,h):i},h.y0=function(t){return arguments.length?(n=t,h):n},h.y1=function(t){return arguments.length?(i=t,h):i},h.defined=function(t){return arguments.length?(a=t,h):a},h.interpolate=function(t){return arguments.length?(s="function"==typeof t?o=t:(o=Vo.get(t)||Uo).key,l=o.reverse||o,c=o.closed?"M":"L",h):s},h.tension=function(t){return arguments.length?(u=t,h):u},h}function ns(t){return t.radius}function is(t){return[t.x,t.y]}function as(){return 64}function os(){return"circle"}function ss(t){var e=Math.sqrt(t/Mt);return"M0,"+e+"A"+e+","+e+" 0 1,1 0,"+-e+"A"+e+","+e+" 0 1,1 0,"+e+"Z"}t.svg.line.radial=function(){var t=jo(es);return t.radius=t.x,delete t.x,t.angle=t.y,delete t.y,t},Ho.reverse=Go,Go.reverse=Ho,t.svg.area=function(){return rs(z)},t.svg.area.radial=function(){var t=rs(es);return t.radius=t.x,delete t.x,t.innerRadius=t.x0,delete t.x0,t.outerRadius=t.x1,delete t.x1,t.angle=t.y,delete t.y,t.startAngle=t.y0,delete t.y0,t.endAngle=t.y1,delete t.y1,t},t.svg.chord=function(){var t=Vn,e=Un,r=ns,n=Po,i=Ro;function a(r,n){var i,a,c=o(this,t,r,n),u=o(this,e,r,n);return"M"+c.p0+s(c.r,c.p1,c.a1-c.a0)+(a=u,(i=c).a0==a.a0&&i.a1==a.a1?l(c.r,c.p1,c.r,c.p0):l(c.r,c.p1,u.r,u.p0)+s(u.r,u.p1,u.a1-u.a0)+l(u.r,u.p1,c.r,c.p0))+"Z"}function o(t,e,a,o){var s=e.call(t,a,o),l=r.call(t,s,o),c=n.call(t,s,o)-Et,u=i.call(t,s,o)-Et;return{r:l,a0:c,a1:u,p0:[l*Math.cos(c),l*Math.sin(c)],p1:[l*Math.cos(u),l*Math.sin(u)]}}function s(t,e,r){return"A"+t+","+t+" 0 "+ +(r>Mt)+",1 "+e}function l(t,e,r,n){return"Q 0,0 "+n}return a.radius=function(t){return arguments.length?(r=ve(t),a):r},a.source=function(e){return arguments.length?(t=ve(e),a):t},a.target=function(t){return arguments.length?(e=ve(t),a):e},a.startAngle=function(t){return arguments.length?(n=ve(t),a):n},a.endAngle=function(t){return arguments.length?(i=ve(t),a):i},a},t.svg.diagonal=function(){var t=Vn,e=Un,r=is;function n(n,i){var a=t.call(this,n,i),o=e.call(this,n,i),s=(a.y+o.y)/2,l=[a,{x:a.x,y:s},{x:o.x,y:s},o];return"M"+(l=l.map(r))[0]+"C"+l[1]+" "+l[2]+" "+l[3]}return n.source=function(e){return arguments.length?(t=ve(e),n):t},n.target=function(t){return arguments.length?(e=ve(t),n):e},n.projection=function(t){return arguments.length?(r=t,n):r},n},t.svg.diagonal.radial=function(){var e=t.svg.diagonal(),r=is,n=e.projection;return e.projection=function(t){return arguments.length?n(function(t){return function(){var e=t.apply(this,arguments),r=e[0],n=e[1]-Et;return[r*Math.cos(n),r*Math.sin(n)]}}(r=t)):r},e},t.svg.symbol=function(){var t=os,e=as;function r(r,n){return(ls.get(t.call(this,r,n))||ss)(e.call(this,r,n))}return r.type=function(e){return arguments.length?(t=ve(e),r):t},r.size=function(t){return arguments.length?(e=ve(t),r):e},r};var ls=t.map({circle:ss,cross:function(t){var e=Math.sqrt(t/5)/2;return"M"+-3*e+","+-e+"H"+-e+"V"+-3*e+"H"+e+"V"+-e+"H"+3*e+"V"+e+"H"+e+"V"+3*e+"H"+-e+"V"+e+"H"+-3*e+"Z"},diamond:function(t){var e=Math.sqrt(t/(2*us)),r=e*us;return"M0,"+-e+"L"+r+",0 0,"+e+" "+-r+",0Z"},square:function(t){var e=Math.sqrt(t)/2;return"M"+-e+","+-e+"L"+e+","+-e+" "+e+","+e+" "+-e+","+e+"Z"},"triangle-down":function(t){var e=Math.sqrt(t/cs),r=e*cs/2;return"M0,"+r+"L"+e+","+-r+" "+-e+","+-r+"Z"},"triangle-up":function(t){var e=Math.sqrt(t/cs),r=e*cs/2;return"M0,"+-r+"L"+e+","+r+" "+-e+","+r+"Z"}});t.svg.symbolTypes=ls.keys();var cs=Math.sqrt(3),us=Math.tan(30*Ct);W.transition=function(t){for(var e,r,n=ds||++ms,i=bs(t),a=[],o=gs||{time:Date.now(),ease:ia,delay:0,duration:250},s=-1,l=this.length;++s<l;){a.push(e=[]);for(var c=this[s],u=-1,h=c.length;++u<h;)(r=c[u])&&_s(r,u,i,n,o),e.push(r)}return ps(a,i,n)},W.interrupt=function(t){return this.each(null==t?hs:fs(bs(t)))};var hs=fs(bs());function fs(t){return function(){var e,r,n;(e=this[t])&&(n=e[r=e.active])&&(n.timer.c=null,n.timer.t=NaN,--e.count?delete e[r]:delete this[t],e.active+=.5,n.event&&n.event.interrupt.call(this,this.__data__,n.index))}}function ps(t,e,r){return U(t,vs),t.namespace=e,t.id=r,t}var ds,gs,vs=[],ms=0;function ys(t,e,r,n){var i=t.id,a=t.namespace;return ut(t,"function"==typeof r?function(t,o,s){t[a][i].tween.set(e,n(r.call(t,t.__data__,o,s)))}:(r=n(r),function(t){t[a][i].tween.set(e,r)}))}function xs(t){return null==t&&(t=""),function(){this.textContent=t}}function bs(t){return null==t?"__transition__":"__transition_"+t+"__"}function _s(t,e,r,n,i){var a,o,s,l,c,u=t[r]||(t[r]={active:0,count:0}),h=u[n];function f(r){var i=u.active,f=u[i];for(var d in f&&(f.timer.c=null,f.timer.t=NaN,--u.count,delete u[i],f.event&&f.event.interrupt.call(t,t.__data__,f.index)),u)if(+d<n){var g=u[d];g.timer.c=null,g.timer.t=NaN,--u.count,delete u[d]}o.c=p,Ae(function(){return o.c&&p(r||1)&&(o.c=null,o.t=NaN),1},0,a),u.active=n,h.event&&h.event.start.call(t,t.__data__,e),c=[],h.tween.forEach(function(r,n){(n=n.call(t,t.__data__,e))&&c.push(n)}),l=h.ease,s=h.duration}function p(i){for(var a=i/s,o=l(a),f=c.length;f>0;)c[--f].call(t,o);if(a>=1)return h.event&&h.event.end.call(t,t.__data__,e),--u.count?delete u[n]:delete t[r],1}h||(a=i.time,o=Ae(function(t){var e=h.delay;if(o.t=e+a,e<=t)return f(t-e);o.c=f},0,a),h=u[n]={tween:new b,time:a,timer:o,delay:i.delay,duration:i.duration,ease:i.ease,index:e},i=null,++u.count)}vs.call=W.call,vs.empty=W.empty,vs.node=W.node,vs.size=W.size,t.transition=function(e,r){return e&&e.transition?ds?e.transition(r):e:t.selection().transition(e)},t.transition.prototype=vs,vs.select=function(t){var e,r,n,i=this.id,a=this.namespace,o=[];t=X(t);for(var s=-1,l=this.length;++s<l;){o.push(e=[]);for(var c=this[s],u=-1,h=c.length;++u<h;)(n=c[u])&&(r=t.call(n,n.__data__,u,s))?("__data__"in n&&(r.__data__=n.__data__),_s(r,u,a,i,n[a][i]),e.push(r)):e.push(null)}return ps(o,a,i)},vs.selectAll=function(t){var e,r,n,i,a,o=this.id,s=this.namespace,l=[];t=Z(t);for(var c=-1,u=this.length;++c<u;)for(var h=this[c],f=-1,p=h.length;++f<p;)if(n=h[f]){a=n[s][o],r=t.call(n,n.__data__,f,c),l.push(e=[]);for(var d=-1,g=r.length;++d<g;)(i=r[d])&&_s(i,d,s,o,a),e.push(i)}return ps(l,s,o)},vs.filter=function(t){var e,r,n=[];"function"!=typeof t&&(t=ct(t));for(var i=0,a=this.length;i<a;i++){n.push(e=[]);for(var o,s=0,l=(o=this[i]).length;s<l;s++)(r=o[s])&&t.call(r,r.__data__,s,i)&&e.push(r)}return ps(n,this.namespace,this.id)},vs.tween=function(t,e){var r=this.id,n=this.namespace;return arguments.length<2?this.node()[n][r].tween.get(t):ut(this,null==e?function(e){e[n][r].tween.remove(t)}:function(i){i[n][r].tween.set(t,e)})},vs.attr=function(e,r){if(arguments.length<2){for(r in e)this.attr(r,e[r]);return this}var n="transform"==e?ga:Zi,i=t.ns.qualify(e);function a(){this.removeAttribute(i)}function o(){this.removeAttributeNS(i.space,i.local)}return ys(this,"attr."+e,r,i.local?function(t){return null==t?o:(t+="",function(){var e,r=this.getAttributeNS(i.space,i.local);return r!==t&&(e=n(r,t),function(t){this.setAttributeNS(i.space,i.local,e(t))})})}:function(t){return null==t?a:(t+="",function(){var e,r=this.getAttribute(i);return r!==t&&(e=n(r,t),function(t){this.setAttribute(i,e(t))})})})},vs.attrTween=function(e,r){var n=t.ns.qualify(e);return this.tween("attr."+e,n.local?function(t,e){var i=r.call(this,t,e,this.getAttributeNS(n.space,n.local));return i&&function(t){this.setAttributeNS(n.space,n.local,i(t))}}:function(t,e){var i=r.call(this,t,e,this.getAttribute(n));return i&&function(t){this.setAttribute(n,i(t))}})},vs.style=function(t,e,r){var n=arguments.length;if(n<3){if("string"!=typeof t){for(r in n<2&&(e=""),t)this.style(r,t[r],e);return this}r=""}function i(){this.style.removeProperty(t)}return ys(this,"style."+t,e,function(e){return null==e?i:(e+="",function(){var n,i=o(this).getComputedStyle(this,null).getPropertyValue(t);return i!==e&&(n=Zi(i,e),function(e){this.style.setProperty(t,n(e),r)})})})},vs.styleTween=function(t,e,r){return arguments.length<3&&(r=""),this.tween("style."+t,function(n,i){var a=e.call(this,n,i,o(this).getComputedStyle(this,null).getPropertyValue(t));return a&&function(e){this.style.setProperty(t,a(e),r)}})},vs.text=function(t){return ys(this,"text",t,xs)},vs.remove=function(){var t=this.namespace;return this.each("end.transition",function(){var e;this[t].count<2&&(e=this.parentNode)&&e.removeChild(this)})},vs.ease=function(e){var r=this.id,n=this.namespace;return arguments.length<1?this.node()[n][r].ease:("function"!=typeof e&&(e=t.ease.apply(t,arguments)),ut(this,function(t){t[n][r].ease=e}))},vs.delay=function(t){var e=this.id,r=this.namespace;return arguments.length<1?this.node()[r][e].delay:ut(this,"function"==typeof t?function(n,i,a){n[r][e].delay=+t.call(n,n.__data__,i,a)}:(t=+t,function(n){n[r][e].delay=t}))},vs.duration=function(t){var e=this.id,r=this.namespace;return arguments.length<1?this.node()[r][e].duration:ut(this,"function"==typeof t?function(n,i,a){n[r][e].duration=Math.max(1,t.call(n,n.__data__,i,a))}:(t=Math.max(1,t),function(n){n[r][e].duration=t}))},vs.each=function(e,r){var n=this.id,i=this.namespace;if(arguments.length<2){var a=gs,o=ds;try{ds=n,ut(this,function(t,r,a){gs=t[i][n],e.call(t,t.__data__,r,a)})}finally{gs=a,ds=o}}else ut(this,function(a){var o=a[i][n];(o.event||(o.event=t.dispatch("start","end","interrupt"))).on(e,r)});return this},vs.transition=function(){for(var t,e,r,n=this.id,i=++ms,a=this.namespace,o=[],s=0,l=this.length;s<l;s++){o.push(t=[]);for(var c,u=0,h=(c=this[s]).length;u<h;u++)(e=c[u])&&_s(e,u,a,i,{time:(r=e[a][n]).time,ease:r.ease,delay:r.delay+r.duration,duration:r.duration}),t.push(e)}return ps(o,a,i)},t.svg.axis=function(){var e,r=t.scale.linear(),i=ws,a=6,o=6,s=3,l=[10],c=null;function u(n){n.each(function(){var n,u=t.select(this),h=this.__chart__||r,f=this.__chart__=r.copy(),p=null==c?f.ticks?f.ticks.apply(f,l):f.domain():c,d=null==e?f.tickFormat?f.tickFormat.apply(f,l):z:e,g=u.selectAll(".tick").data(p,f),v=g.enter().insert("g",".domain").attr("class","tick").style("opacity",kt),m=t.transition(g.exit()).style("opacity",kt).remove(),y=t.transition(g.order()).style("opacity",1),x=Math.max(a,0)+s,b=uo(f),_=u.selectAll(".domain").data([0]),w=(_.enter().append("path").attr("class","domain"),t.transition(_));v.append("line"),v.append("text");var k,A,M,T,S=v.select("line"),E=y.select("line"),C=g.select("text").text(d),L=v.select("text"),O=y.select("text"),I="top"===i||"left"===i?-1:1;if("bottom"===i||"top"===i?(n=As,k="x",M="y",A="x2",T="y2",C.attr("dy",I<0?"0em":".71em").style("text-anchor","middle"),w.attr("d","M"+b[0]+","+I*o+"V0H"+b[1]+"V"+I*o)):(n=Ms,k="y",M="x",A="y2",T="x2",C.attr("dy",".32em").style("text-anchor",I<0?"end":"start"),w.attr("d","M"+I*o+","+b[0]+"H0V"+b[1]+"H"+I*o)),S.attr(T,I*a),L.attr(M,I*x),E.attr(A,0).attr(T,I*a),O.attr(k,0).attr(M,I*x),f.rangeBand){var D=f,P=D.rangeBand()/2;h=f=function(t){return D(t)+P}}else h.rangeBand?h=f:m.call(n,f,h);v.call(n,h,f),y.call(n,f,f)})}return u.scale=function(t){return arguments.length?(r=t,u):r},u.orient=function(t){return arguments.length?(i=t in ks?t+"":ws,u):i},u.ticks=function(){return arguments.length?(l=n(arguments),u):l},u.tickValues=function(t){return arguments.length?(c=t,u):c},u.tickFormat=function(t){return arguments.length?(e=t,u):e},u.tickSize=function(t){var e=arguments.length;return e?(a=+t,o=+arguments[e-1],u):a},u.innerTickSize=function(t){return arguments.length?(a=+t,u):a},u.outerTickSize=function(t){return arguments.length?(o=+t,u):o},u.tickPadding=function(t){return arguments.length?(s=+t,u):s},u.tickSubdivide=function(){return arguments.length&&u},u};var ws="bottom",ks={top:1,right:1,bottom:1,left:1};function As(t,e,r){t.attr("transform",function(t){var n=e(t);return"translate("+(isFinite(n)?n:r(t))+",0)"})}function Ms(t,e,r){t.attr("transform",function(t){var n=e(t);return"translate(0,"+(isFinite(n)?n:r(t))+")"})}t.svg.brush=function(){var e,r,n=j(f,"brushstart","brush","brushend"),i=null,a=null,s=[0,0],l=[0,0],c=!0,u=!0,h=Ss[0];function f(e){e.each(function(){var e=t.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",v).on("touchstart.brush",v),r=e.selectAll(".background").data([0]);r.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair"),e.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var n=e.selectAll(".resize").data(h,z);n.exit().remove(),n.enter().append("g").attr("class",function(t){return"resize "+t}).style("cursor",function(t){return Ts[t]}).append("rect").attr("x",function(t){return/[ew]$/.test(t)?-3:null}).attr("y",function(t){return/^[ns]/.test(t)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden"),n.style("display",f.empty()?"none":null);var o,s=t.transition(e),l=t.transition(r);i&&(o=uo(i),l.attr("x",o[0]).attr("width",o[1]-o[0]),d(s)),a&&(o=uo(a),l.attr("y",o[0]).attr("height",o[1]-o[0]),g(s)),p(s)})}function p(t){t.selectAll(".resize").attr("transform",function(t){return"translate("+s[+/e$/.test(t)]+","+l[+/^s/.test(t)]+")"})}function d(t){t.select(".extent").attr("x",s[0]),t.selectAll(".extent,.n>rect,.s>rect").attr("width",s[1]-s[0])}function g(t){t.select(".extent").attr("y",l[0]),t.selectAll(".extent,.e>rect,.w>rect").attr("height",l[1]-l[0])}function v(){var h,v,m=this,y=t.select(t.event.target),x=n.of(m,arguments),b=t.select(m),_=y.datum(),w=!/^(n|s)$/.test(_)&&i,k=!/^(e|w)$/.test(_)&&a,A=y.classed("extent"),M=xt(m),T=t.mouse(m),S=t.select(o(m)).on("keydown.brush",function(){32==t.event.keyCode&&(A||(h=null,T[0]-=s[1],T[1]-=l[1],A=2),B())}).on("keyup.brush",function(){32==t.event.keyCode&&2==A&&(T[0]+=s[1],T[1]+=l[1],A=0,B())});if(t.event.changedTouches?S.on("touchmove.brush",L).on("touchend.brush",O):S.on("mousemove.brush",L).on("mouseup.brush",O),b.interrupt().selectAll("*").interrupt(),A)T[0]=s[0]-T[0],T[1]=l[0]-T[1];else if(_){var E=+/w$/.test(_),C=+/^n/.test(_);v=[s[1-E]-T[0],l[1-C]-T[1]],T[0]=s[E],T[1]=l[C]}else t.event.altKey&&(h=T.slice());function L(){var e=t.mouse(m),r=!1;v&&(e[0]+=v[0],e[1]+=v[1]),A||(t.event.altKey?(h||(h=[(s[0]+s[1])/2,(l[0]+l[1])/2]),T[0]=s[+(e[0]<h[0])],T[1]=l[+(e[1]<h[1])]):h=null),w&&z(e,i,0)&&(d(b),r=!0),k&&z(e,a,1)&&(g(b),r=!0),r&&(p(b),x({type:"brush",mode:A?"move":"resize"}))}function z(t,n,i){var a,o,f=uo(n),p=f[0],d=f[1],g=T[i],v=i?l:s,m=v[1]-v[0];if(A&&(p-=g,d-=m+g),a=(i?u:c)?Math.max(p,Math.min(d,t[i])):t[i],A?o=(a+=g)+m:(h&&(g=Math.max(p,Math.min(d,2*h[i]-a))),g<a?(o=a,a=g):o=g),v[0]!=a||v[1]!=o)return i?r=null:e=null,v[0]=a,v[1]=o,!0}function O(){L(),b.style("pointer-events","all").selectAll(".resize").style("display",f.empty()?"none":null),t.select("body").style("cursor",null),S.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null),M(),x({type:"brushend"})}b.style("pointer-events","none").selectAll(".resize").style("display",null),t.select("body").style("cursor",y.style("cursor")),x({type:"brushstart"}),L()}return f.event=function(i){i.each(function(){var i=n.of(this,arguments),a={x:s,y:l,i:e,j:r},o=this.__chart__||a;this.__chart__=a,ds?t.select(this).transition().each("start.brush",function(){e=o.i,r=o.j,s=o.x,l=o.y,i({type:"brushstart"})}).tween("brush:brush",function(){var t=$i(s,a.x),n=$i(l,a.y);return e=r=null,function(e){s=a.x=t(e),l=a.y=n(e),i({type:"brush",mode:"resize"})}}).each("end.brush",function(){e=a.i,r=a.j,i({type:"brush",mode:"resize"}),i({type:"brushend"})}):(i({type:"brushstart"}),i({type:"brush",mode:"resize"}),i({type:"brushend"}))})},f.x=function(t){return arguments.length?(h=Ss[!(i=t)<<1|!a],f):i},f.y=function(t){return arguments.length?(h=Ss[!i<<1|!(a=t)],f):a},f.clamp=function(t){return arguments.length?(i&&a?(c=!!t[0],u=!!t[1]):i?c=!!t:a&&(u=!!t),f):i&&a?[c,u]:i?c:a?u:null},f.extent=function(t){var n,o,c,u,h;return arguments.length?(i&&(n=t[0],o=t[1],a&&(n=n[0],o=o[0]),e=[n,o],i.invert&&(n=i(n),o=i(o)),o<n&&(h=n,n=o,o=h),n==s[0]&&o==s[1]||(s=[n,o])),a&&(c=t[0],u=t[1],i&&(c=c[1],u=u[1]),r=[c,u],a.invert&&(c=a(c),u=a(u)),u<c&&(h=c,c=u,u=h),c==l[0]&&u==l[1]||(l=[c,u])),f):(i&&(e?(n=e[0],o=e[1]):(n=s[0],o=s[1],i.invert&&(n=i.invert(n),o=i.invert(o)),o<n&&(h=n,n=o,o=h))),a&&(r?(c=r[0],u=r[1]):(c=l[0],u=l[1],a.invert&&(c=a.invert(c),u=a.invert(u)),u<c&&(h=c,c=u,u=h))),i&&a?[[n,c],[o,u]]:i?[n,o]:a&&[c,u])},f.clear=function(){return f.empty()||(s=[0,0],l=[0,0],e=r=null),f},f.empty=function(){return!!i&&s[0]==s[1]||!!a&&l[0]==l[1]},t.rebind(f,n,"on")};var Ts={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},Ss=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]],Es=Ie.format=sr.timeFormat,Cs=Es.utc,Ls=Cs("%Y-%m-%dT%H:%M:%S.%LZ");function zs(t){return t.toISOString()}function Os(e,r,n){function i(t){return e(t)}function a(e,n){var i=(e[1]-e[0])/n,a=t.bisect(Ds,i);return a==Ds.length?[r.year,xo(e.map(function(t){return t/31536e6}),n)[2]]:a?r[i/Ds[a-1]<Ds[a]/i?a-1:a]:[Fs,xo(e,n)[2]]}return i.invert=function(t){return Is(e.invert(t))},i.domain=function(t){return arguments.length?(e.domain(t),i):e.domain().map(Is)},i.nice=function(t,e){var r=i.domain(),n=co(r),o=null==t?a(n,10):"number"==typeof t&&a(n,t);function s(r){return!isNaN(r)&&!t.range(r,Is(+r+1),e).length}return o&&(t=o[0],e=o[1]),i.domain(fo(r,e>1?{floor:function(e){for(;s(e=t.floor(e));)e=Is(e-1);return e},ceil:function(e){for(;s(e=t.ceil(e));)e=Is(+e+1);return e}}:t))},i.ticks=function(t,e){var r=co(i.domain()),n=null==t?a(r,10):"number"==typeof t?a(r,t):!t.range&&[{range:t},e];return n&&(t=n[0],e=n[1]),t.range(r[0],Is(+r[1]+1),e<1?1:e)},i.tickFormat=function(){return n},i.copy=function(){return Os(e.copy(),r,n)},mo(i,e)}function Is(t){return new Date(t)}Es.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?zs:Ls,zs.parse=function(t){var e=new Date(t);return isNaN(e)?null:e},zs.toString=Ls.toString,Ie.second=Fe(function(t){return new De(1e3*Math.floor(t/1e3))},function(t,e){t.setTime(t.getTime()+1e3*Math.floor(e))},function(t){return t.getSeconds()}),Ie.seconds=Ie.second.range,Ie.seconds.utc=Ie.second.utc.range,Ie.minute=Fe(function(t){return new De(6e4*Math.floor(t/6e4))},function(t,e){t.setTime(t.getTime()+6e4*Math.floor(e))},function(t){return t.getMinutes()}),Ie.minutes=Ie.minute.range,Ie.minutes.utc=Ie.minute.utc.range,Ie.hour=Fe(function(t){var e=t.getTimezoneOffset()/60;return new De(36e5*(Math.floor(t/36e5-e)+e))},function(t,e){t.setTime(t.getTime()+36e5*Math.floor(e))},function(t){return t.getHours()}),Ie.hours=Ie.hour.range,Ie.hours.utc=Ie.hour.utc.range,Ie.month=Fe(function(t){return(t=Ie.day(t)).setDate(1),t},function(t,e){t.setMonth(t.getMonth()+e)},function(t){return t.getMonth()}),Ie.months=Ie.month.range,Ie.months.utc=Ie.month.utc.range;var Ds=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Ps=[[Ie.second,1],[Ie.second,5],[Ie.second,15],[Ie.second,30],[Ie.minute,1],[Ie.minute,5],[Ie.minute,15],[Ie.minute,30],[Ie.hour,1],[Ie.hour,3],[Ie.hour,6],[Ie.hour,12],[Ie.day,1],[Ie.day,2],[Ie.week,1],[Ie.month,1],[Ie.month,3],[Ie.year,1]],Rs=Es.multi([[".%L",function(t){return t.getMilliseconds()}],[":%S",function(t){return t.getSeconds()}],["%I:%M",function(t){return t.getMinutes()}],["%I %p",function(t){return t.getHours()}],["%a %d",function(t){return t.getDay()&&1!=t.getDate()}],["%b %d",function(t){return 1!=t.getDate()}],["%B",function(t){return t.getMonth()}],["%Y",Yr]]),Fs={range:function(e,r,n){return t.range(Math.ceil(e/n)*n,+r,n).map(Is)},floor:z,ceil:z};Ps.year=Ie.year,Ie.scale=function(){return Os(t.scale.linear(),Ps,Rs)};var Bs=Ps.map(function(t){return[t[0].utc,t[1]]}),Ns=Cs.multi([[".%L",function(t){return t.getUTCMilliseconds()}],[":%S",function(t){return t.getUTCSeconds()}],["%I:%M",function(t){return t.getUTCMinutes()}],["%I %p",function(t){return t.getUTCHours()}],["%a %d",function(t){return t.getUTCDay()&&1!=t.getUTCDate()}],["%b %d",function(t){return 1!=t.getUTCDate()}],["%B",function(t){return t.getUTCMonth()}],["%Y",Yr]]);function js(t){return JSON.parse(t.responseText)}function Vs(t){var e=i.createRange();return e.selectNode(i.body),e.createContextualFragment(t.responseText)}Bs.year=Ie.year.utc,Ie.scale.utc=function(){return Os(t.scale.linear(),Bs,Ns)},t.text=me(function(t){return t.responseText}),t.json=function(t,e){return ye(t,"application/json",js,e)},t.html=function(t,e){return ye(t,"text/html",Vs,e)},t.xml=me(function(t){return t.responseXML}),"object"==typeof e&&e.exports?e.exports=t:this.d3=t}()},{}],152:[function(t,e,r){e.exports=function(){for(var t=0;t<arguments.length;t++)if(void 0!==arguments[t])return arguments[t]}},{}],153:[function(t,e,r){"use strict";var n=t("incremental-convex-hull"),i=t("uniq");function a(t,e){this.point=t,this.index=e}function o(t,e){for(var r=t.point,n=e.point,i=r.length,a=0;a<i;++a){var o=n[a]-r[a];if(o)return o}return 0}e.exports=function(t,e){var r=t.length;if(0===r)return[];var s=t[0].length;if(s<1)return[];if(1===s)return function(t,e,r){if(1===t)return r?[[-1,0]]:[];var n=e.map(function(t,e){return[t[0],e]});n.sort(function(t,e){return t[0]-e[0]});for(var i=new Array(t-1),a=1;a<t;++a){var o=n[a-1],s=n[a];i[a-1]=[o[1],s[1]]}r&&i.push([-1,i[0][1]],[i[t-1][1],-1]);return i}(r,t,e);for(var l=new Array(r),c=1,u=0;u<r;++u){for(var h=t[u],f=new Array(s+1),p=0,d=0;d<s;++d){var g=h[d];f[d]=g,p+=g*g}f[s]=p,l[u]=new a(f,u),c=Math.max(p,c)}i(l,o),r=l.length;for(var v=new Array(r+s+1),m=new Array(r+s+1),y=(s+1)*(s+1)*c,x=new Array(s+1),u=0;u<=s;++u)x[u]=0;x[s]=y,v[0]=x.slice(),m[0]=-1;for(var u=0;u<=s;++u){var f=x.slice();f[u]=1,v[u+1]=f,m[u+1]=-1}for(var u=0;u<r;++u){var b=l[u];v[u+s+1]=b.point,m[u+s+1]=b.index}var _=n(v,!1);_=e?_.filter(function(t){for(var e=0,r=0;r<=s;++r){var n=m[t[r]];if(n<0&&++e>=2)return!1;t[r]=n}return!0}):_.filter(function(t){for(var e=0;e<=s;++e){var r=m[t[e]];if(r<0)return!1;t[e]=r}return!0});if(1&s)for(var u=0;u<_.length;++u){var b=_[u],f=b[0];b[0]=b[1],b[1]=f}return _}},{"incremental-convex-hull":402,uniq:528}],154:[function(t,e,r){"use strict";e.exports=a;var n=(a.canvas=document.createElement("canvas")).getContext("2d"),i=o([32,126]);function a(t,e){Array.isArray(t)&&(t=t.join(", "));var r,a={},s=16,l=.05;e&&(2===e.length&&"number"==typeof e[0]?r=o(e):Array.isArray(e)?r=e:(e.o?r=o(e.o):e.pairs&&(r=e.pairs),e.fontSize&&(s=e.fontSize),null!=e.threshold&&(l=e.threshold))),r||(r=i),n.font=s+"px "+t;for(var c=0;c<r.length;c++){var u=r[c],h=n.measureText(u[0]).width+n.measureText(u[1]).width,f=n.measureText(u).width;if(Math.abs(h-f)>s*l){var p=(f-h)/s;a[u]=1e3*p}}return a}function o(t){for(var e=[],r=t[0];r<=t[1];r++)for(var n=String.fromCharCode(r),i=t[0];i<t[1];i++){var a=n+String.fromCharCode(i);e.push(a)}return e}a.createPairs=o,a.ascii=i},{}],155:[function(t,e,r){(function(t){var r=!1;if("undefined"!=typeof Float64Array){var n=new Float64Array(1),i=new Uint32Array(n.buffer);if(n[0]=1,r=!0,1072693248===i[1]){e.exports=function(t){return n[0]=t,[i[0],i[1]]},e.exports.pack=function(t,e){return i[0]=t,i[1]=e,n[0]},e.exports.lo=function(t){return n[0]=t,i[0]},e.exports.hi=function(t){return n[0]=t,i[1]}}else if(1072693248===i[0]){e.exports=function(t){return n[0]=t,[i[1],i[0]]},e.exports.pack=function(t,e){return i[1]=t,i[0]=e,n[0]},e.exports.lo=function(t){return n[0]=t,i[1]},e.exports.hi=function(t){return n[0]=t,i[0]}}else r=!1}if(!r){var a=new t(8);e.exports=function(t){return a.writeDoubleLE(t,0,!0),[a.readUInt32LE(0,!0),a.readUInt32LE(4,!0)]},e.exports.pack=function(t,e){return a.writeUInt32LE(t,0,!0),a.writeUInt32LE(e,4,!0),a.readDoubleLE(0,!0)},e.exports.lo=function(t){return a.writeDoubleLE(t,0,!0),a.readUInt32LE(0,!0)},e.exports.hi=function(t){return a.writeDoubleLE(t,0,!0),a.readUInt32LE(4,!0)}}e.exports.sign=function(t){return e.exports.hi(t)>>>31},e.exports.exponent=function(t){return(e.exports.hi(t)<<1>>>21)-1023},e.exports.fraction=function(t){var r=e.exports.lo(t),n=e.exports.hi(t),i=1048575&n;return 2146435072&n&&(i+=1<<20),[r,i]},e.exports.denormalized=function(t){return!(2146435072&e.exports.hi(t))}}).call(this,t("buffer").Buffer)},{buffer:93}],156:[function(t,e,r){var n=t("abs-svg-path"),i=t("normalize-svg-path"),a={M:"moveTo",C:"bezierCurveTo"};e.exports=function(t,e){t.beginPath(),i(n(e)).forEach(function(e){var r=e[0],n=e.slice(1);t[a[r]].apply(t,n)}),t.closePath()}},{"abs-svg-path":48,"normalize-svg-path":441}],157:[function(t,e,r){e.exports=function(t){switch(t){case"int8":return Int8Array;case"int16":return Int16Array;case"int32":return Int32Array;case"uint8":return Uint8Array;case"uint16":return Uint16Array;case"uint32":return Uint32Array;case"float32":return Float32Array;case"float64":return Float64Array;case"array":return Array;case"uint8_clamped":return Uint8ClampedArray}}},{}],158:[function(t,e,r){"use strict";e.exports=function(t,e){switch("undefined"==typeof e&&(e=0),typeof t){case"number":if(t>0)return function(t,e){var r,n;for(r=new Array(t),n=0;n<t;++n)r[n]=e;return r}(0|t,e);break;case"object":if("number"==typeof t.length)return function t(e,r,n){var i=0|e[n];if(i<=0)return[];var a,o=new Array(i);if(n===e.length-1)for(a=0;a<i;++a)o[a]=r;else for(a=0;a<i;++a)o[a]=t(e,r,n+1);return o}(t,e,0)}return[]}},{}],159:[function(t,e,r){"use strict";function n(t,e,r){r=r||2;var n,s,l,c,u,p,g,v=e&&e.length,m=v?e[0]*r:t.length,y=i(t,0,m,r,!0),x=[];if(!y)return x;if(v&&(y=function(t,e,r,n){var o,s,l,c,u,p=[];for(o=0,s=e.length;o<s;o++)l=e[o]*n,c=o<s-1?e[o+1]*n:t.length,(u=i(t,l,c,n,!1))===u.next&&(u.steiner=!0),p.push(d(u));for(p.sort(h),o=0;o<p.length;o++)f(p[o],r),r=a(r,r.next);return r}(t,e,y,r)),t.length>80*r){n=l=t[0],s=c=t[1];for(var b=r;b<m;b+=r)(u=t[b])<n&&(n=u),(p=t[b+1])<s&&(s=p),u>l&&(l=u),p>c&&(c=p);g=0!==(g=Math.max(l-n,c-s))?1/g:0}return o(y,x,r,n,s,g),x}function i(t,e,r,n,i){var a,o;if(i===M(t,e,r,n)>0)for(a=e;a<r;a+=n)o=w(a,t[a],t[a+1],o);else for(a=r-n;a>=e;a-=n)o=w(a,t[a],t[a+1],o);return o&&y(o,o.next)&&(k(o),o=o.next),o}function a(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!y(n,n.next)&&0!==m(n.prev,n,n.next))n=n.next;else{if(k(n),(n=e=n.prev)===n.next)break;r=!0}}while(r||n!==e);return e}function o(t,e,r,n,i,h,f){if(t){!f&&h&&function(t,e,r,n){var i=t;do{null===i.z&&(i.z=p(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,r,n,i,a,o,s,l,c=1;do{for(r=t,t=null,a=null,o=0;r;){for(o++,n=r,s=0,e=0;e<c&&(s++,n=n.nextZ);e++);for(l=c;s>0||l>0&&n;)0!==s&&(0===l||!n||r.z<=n.z)?(i=r,r=r.nextZ,s--):(i=n,n=n.nextZ,l--),a?a.nextZ=i:t=i,i.prevZ=a,a=i;r=n}a.nextZ=null,c*=2}while(o>1)}(i)}(t,n,i,h);for(var d,g,v=t;t.prev!==t.next;)if(d=t.prev,g=t.next,h?l(t,n,i,h):s(t))e.push(d.i/r),e.push(t.i/r),e.push(g.i/r),k(t),t=g.next,v=g.next;else if((t=g)===v){f?1===f?o(t=c(t,e,r),e,r,n,i,h,2):2===f&&u(t,e,r,n,i,h):o(a(t),e,r,n,i,h,1);break}}}function s(t){var e=t.prev,r=t,n=t.next;if(m(e,r,n)>=0)return!1;for(var i=t.next.next;i!==t.prev;){if(g(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&m(i.prev,i,i.next)>=0)return!1;i=i.next}return!0}function l(t,e,r,n){var i=t.prev,a=t,o=t.next;if(m(i,a,o)>=0)return!1;for(var s=i.x<a.x?i.x<o.x?i.x:o.x:a.x<o.x?a.x:o.x,l=i.y<a.y?i.y<o.y?i.y:o.y:a.y<o.y?a.y:o.y,c=i.x>a.x?i.x>o.x?i.x:o.x:a.x>o.x?a.x:o.x,u=i.y>a.y?i.y>o.y?i.y:o.y:a.y>o.y?a.y:o.y,h=p(s,l,e,r,n),f=p(c,u,e,r,n),d=t.prevZ,v=t.nextZ;d&&d.z>=h&&v&&v.z<=f;){if(d!==t.prev&&d!==t.next&&g(i.x,i.y,a.x,a.y,o.x,o.y,d.x,d.y)&&m(d.prev,d,d.next)>=0)return!1;if(d=d.prevZ,v!==t.prev&&v!==t.next&&g(i.x,i.y,a.x,a.y,o.x,o.y,v.x,v.y)&&m(v.prev,v,v.next)>=0)return!1;v=v.nextZ}for(;d&&d.z>=h;){if(d!==t.prev&&d!==t.next&&g(i.x,i.y,a.x,a.y,o.x,o.y,d.x,d.y)&&m(d.prev,d,d.next)>=0)return!1;d=d.prevZ}for(;v&&v.z<=f;){if(v!==t.prev&&v!==t.next&&g(i.x,i.y,a.x,a.y,o.x,o.y,v.x,v.y)&&m(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function c(t,e,r){var n=t;do{var i=n.prev,a=n.next.next;!y(i,a)&&x(i,n,n.next,a)&&b(i,a)&&b(a,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(a.i/r),k(n),k(n.next),n=t=a),n=n.next}while(n!==t);return n}function u(t,e,r,n,i,s){var l=t;do{for(var c=l.next.next;c!==l.prev;){if(l.i!==c.i&&v(l,c)){var u=_(l,c);return l=a(l,l.next),u=a(u,u.next),o(l,e,r,n,i,s),void o(u,e,r,n,i,s)}c=c.next}l=l.next}while(l!==t)}function h(t,e){return t.x-e.x}function f(t,e){if(e=function(t,e){var r,n=e,i=t.x,a=t.y,o=-1/0;do{if(a<=n.y&&a>=n.next.y&&n.next.y!==n.y){var s=n.x+(a-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(s<=i&&s>o){if(o=s,s===i){if(a===n.y)return n;if(a===n.next.y)return n.next}r=n.x<n.next.x?n:n.next}}n=n.next}while(n!==e);if(!r)return null;if(i===o)return r.prev;var l,c=r,u=r.x,h=r.y,f=1/0;n=r.next;for(;n!==c;)i>=n.x&&n.x>=u&&i!==n.x&&g(a<h?i:o,a,u,h,a<h?o:i,a,n.x,n.y)&&((l=Math.abs(a-n.y)/(i-n.x))<f||l===f&&n.x>r.x)&&b(n,t)&&(r=n,f=l),n=n.next;return r}(t,e)){var r=_(e,t);a(r,r.next)}}function p(t,e,r,n,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*i)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*i)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function d(t){var e=t,r=t;do{e.x<r.x&&(r=e),e=e.next}while(e!==t);return r}function g(t,e,r,n,i,a,o,s){return(i-o)*(e-s)-(t-o)*(a-s)>=0&&(t-o)*(n-s)-(r-o)*(e-s)>=0&&(r-o)*(a-s)-(i-o)*(n-s)>=0}function v(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&x(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}(t,e)&&b(t,e)&&b(e,t)&&function(t,e){var r=t,n=!1,i=(t.x+e.x)/2,a=(t.y+e.y)/2;do{r.y>a!=r.next.y>a&&r.next.y!==r.y&&i<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}(t,e)}function m(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function y(t,e){return t.x===e.x&&t.y===e.y}function x(t,e,r,n){return!!(y(t,e)&&y(r,n)||y(t,n)&&y(r,e))||m(t,e,r)>0!=m(t,e,n)>0&&m(r,n,t)>0!=m(r,n,e)>0}function b(t,e){return m(t.prev,t,t.next)<0?m(t,e,t.next)>=0&&m(t,t.prev,e)>=0:m(t,e,t.prev)<0||m(t,t.next,e)<0}function _(t,e){var r=new A(t.i,t.x,t.y),n=new A(e.i,e.x,e.y),i=t.next,a=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,a.next=n,n.prev=a,n}function w(t,e,r,n){var i=new A(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function k(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function A(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function M(t,e,r,n){for(var i=0,a=e,o=r-n;a<r;a+=n)i+=(t[o]-t[a])*(t[a+1]+t[o+1]),o=a;return i}e.exports=n,e.exports.default=n,n.deviation=function(t,e,r,n){var i=e&&e.length,a=i?e[0]*r:t.length,o=Math.abs(M(t,0,a,r));if(i)for(var s=0,l=e.length;s<l;s++){var c=e[s]*r,u=s<l-1?e[s+1]*r:t.length;o-=Math.abs(M(t,c,u,r))}var h=0;for(s=0;s<n.length;s+=3){var f=n[s]*r,p=n[s+1]*r,d=n[s+2]*r;h+=Math.abs((t[f]-t[d])*(t[p+1]-t[f+1])-(t[f]-t[p])*(t[d+1]-t[f+1]))}return 0===o&&0===h?0:Math.abs((h-o)/o)},n.flatten=function(t){for(var e=t[0][0].length,r={vertices:[],holes:[],dimensions:e},n=0,i=0;i<t.length;i++){for(var a=0;a<t[i].length;a++)for(var o=0;o<e;o++)r.vertices.push(t[i][a][o]);i>0&&(n+=t[i-1].length,r.holes.push(n))}return r}},{}],160:[function(t,e,r){"use strict";e.exports=function(t,e){var r=t.length;if("number"!=typeof e){e=0;for(var i=0;i<r;++i){var a=t[i];e=Math.max(e,a[0],a[1])}e=1+(0|e)}e|=0;for(var o=new Array(e),i=0;i<e;++i)o[i]=[];for(var i=0;i<r;++i){var a=t[i];o[a[0]].push(a[1]),o[a[1]].push(a[0])}for(var s=0;s<e;++s)n(o[s],function(t,e){return t-e});return o};var n=t("uniq")},{uniq:528}],161:[function(t,e,r){var n=t("strongly-connected-components");e.exports=function(t){var e,r=[],i=[],a=[],o={},s=[];function l(t){var r,n,u=!1;for(i.push(t),a[t]=!0,r=0;r<s[t].length;r++)(n=s[t][r])===e?(c(e,i),u=!0):a[n]||(u=l(n));if(u)!function t(e){a[e]=!1,o.hasOwnProperty(e)&&Object.keys(o[e]).forEach(function(r){delete o[e][r],a[r]&&t(r)})}(t);else for(r=0;r<s[t].length;r++){n=s[t][r];var h=o[n];h||(h={},o[n]=h),h[n]=!0}return i.pop(),u}function c(t,e){var n=[].concat(e).concat(t);r.push(n)}function u(e){!function(e){for(var r=0;r<t.length;r++)r<e&&(t[r]=[]),t[r]=t[r].filter(function(t){return t>=e})}(e);for(var r,i=n(t).components.filter(function(t){return t.length>1}),a=1/0,o=0;o<i.length;o++)for(var s=0;s<i[o].length;s++)i[o][s]<a&&(a=i[o][s],r=o);var l=i[r];return!!l&&{leastVertex:a,adjList:t.map(function(t,e){return-1===l.indexOf(e)?[]:t.filter(function(t){return-1!==l.indexOf(t)})})}}e=0;for(var h=t.length;e<h;){var f=u(e);if(e=f.leastVertex,s=f.adjList){for(var p=0;p<s.length;p++)for(var d=0;d<s[p].length;d++){var g=s[p][d];a[+g]=!1,o[g]={}}l(e),e+=1}else e=h}return r}},{"strongly-connected-components":511}],162:[function(t,e,r){"use strict";var n=t("../../object/valid-value");e.exports=function(){return n(this).length=0,this}},{"../../object/valid-value":194}],163:[function(t,e,r){"use strict";e.exports=t("./is-implemented")()?Array.from:t("./shim")},{"./is-implemented":164,"./shim":165}],164:[function(t,e,r){"use strict";e.exports=function(){var t,e,r=Array.from;return"function"==typeof r&&(e=r(t=["raz","dwa"]),Boolean(e&&e!==t&&"dwa"===e[1]))}},{}],165:[function(t,e,r){"use strict";var n=t("es6-symbol").iterator,i=t("../../function/is-arguments"),a=t("../../function/is-function"),o=t("../../number/to-pos-integer"),s=t("../../object/valid-callable"),l=t("../../object/valid-value"),c=t("../../object/is-value"),u=t("../../string/is-string"),h=Array.isArray,f=Function.prototype.call,p={configurable:!0,enumerable:!0,writable:!0,value:null},d=Object.defineProperty;e.exports=function(t){var e,r,g,v,m,y,x,b,_,w,k=arguments[1],A=arguments[2];if(t=Object(l(t)),c(k)&&s(k),this&&this!==Array&&a(this))e=this;else{if(!k){if(i(t))return 1!==(m=t.length)?Array.apply(null,t):((v=new Array(1))[0]=t[0],v);if(h(t)){for(v=new Array(m=t.length),r=0;r<m;++r)v[r]=t[r];return v}}v=[]}if(!h(t))if(void 0!==(_=t[n])){for(x=s(_).call(t),e&&(v=new e),b=x.next(),r=0;!b.done;)w=k?f.call(k,A,b.value,r):b.value,e?(p.value=w,d(v,r,p)):v[r]=w,b=x.next(),++r;m=r}else if(u(t)){for(m=t.length,e&&(v=new e),r=0,g=0;r<m;++r)w=t[r],r+1<m&&(y=w.charCodeAt(0))>=55296&&y<=56319&&(w+=t[++r]),w=k?f.call(k,A,w,g):w,e?(p.value=w,d(v,g,p)):v[g]=w,++g;m=g}if(void 0===m)for(m=o(t.length),e&&(v=new e(m)),r=0;r<m;++r)w=k?f.call(k,A,t[r],r):t[r],e?(p.value=w,d(v,r,p)):v[r]=w;return e&&(p.value=null,v.length=m),v}},{"../../function/is-arguments":166,"../../function/is-function":167,"../../number/to-pos-integer":173,"../../object/is-value":183,"../../object/valid-callable":192,"../../object/valid-value":194,"../../string/is-string":198,"es6-symbol":208}],166:[function(t,e,r){"use strict";var n=Object.prototype.toString,i=n.call(function(){return arguments}());e.exports=function(t){return n.call(t)===i}},{}],167:[function(t,e,r){"use strict";var n=Object.prototype.toString,i=n.call(t("./noop"));e.exports=function(t){return"function"==typeof t&&n.call(t)===i}},{"./noop":168}],168:[function(t,e,r){"use strict";e.exports=function(){}},{}],169:[function(t,e,r){"use strict";e.exports=t("./is-implemented")()?Math.sign:t("./shim")},{"./is-implemented":170,"./shim":171}],170:[function(t,e,r){"use strict";e.exports=function(){var t=Math.sign;return"function"==typeof t&&(1===t(10)&&-1===t(-20))}},{}],171:[function(t,e,r){"use strict";e.exports=function(t){return t=Number(t),isNaN(t)||0===t?t:t>0?1:-1}},{}],172:[function(t,e,r){"use strict";var n=t("../math/sign"),i=Math.abs,a=Math.floor;e.exports=function(t){return isNaN(t)?0:0!==(t=Number(t))&&isFinite(t)?n(t)*a(i(t)):t}},{"../math/sign":169}],173:[function(t,e,r){"use strict";var n=t("./to-integer"),i=Math.max;e.exports=function(t){return i(0,n(t))}},{"./to-integer":172}],174:[function(t,e,r){"use strict";var n=t("./valid-callable"),i=t("./valid-value"),a=Function.prototype.bind,o=Function.prototype.call,s=Object.keys,l=Object.prototype.propertyIsEnumerable;e.exports=function(t,e){return function(r,c){var u,h=arguments[2],f=arguments[3];return r=Object(i(r)),n(c),u=s(r),f&&u.sort("function"==typeof f?a.call(f,r):void 0),"function"!=typeof t&&(t=u[t]),o.call(t,u,function(t,n){return l.call(r,t)?o.call(c,h,r[t],t,r,n):e})}}},{"./valid-callable":192,"./valid-value":194}],175:[function(t,e,r){"use strict";e.exports=t("./is-implemented")()?Object.assign:t("./shim")},{"./is-implemented":176,"./shim":177}],176:[function(t,e,r){"use strict";e.exports=function(){var t,e=Object.assign;return"function"==typeof e&&(e(t={foo:"raz"},{bar:"dwa"},{trzy:"trzy"}),t.foo+t.bar+t.trzy==="razdwatrzy")}},{}],177:[function(t,e,r){"use strict";var n=t("../keys"),i=t("../valid-value"),a=Math.max;e.exports=function(t,e){var r,o,s,l=a(arguments.length,2);for(t=Object(i(t)),s=function(n){try{t[n]=e[n]}catch(t){r||(r=t)}},o=1;o<l;++o)e=arguments[o],n(e).forEach(s);if(void 0!==r)throw r;return t}},{"../keys":184,"../valid-value":194}],178:[function(t,e,r){"use strict";var n=t("../array/from"),i=t("./assign"),a=t("./valid-value");e.exports=function(t){var e=Object(a(t)),r=arguments[1],o=Object(arguments[2]);if(e!==t&&!r)return e;var s={};return r?n(r,function(e){(o.ensure||e in t)&&(s[e]=t[e])}):i(s,t),s}},{"../array/from":163,"./assign":175,"./valid-value":194}],179:[function(t,e,r){"use strict";var n,i,a,o,s=Object.create;t("./set-prototype-of/is-implemented")()||(n=t("./set-prototype-of/shim")),e.exports=n?1!==n.level?s:(i={},a={},o={configurable:!1,enumerable:!1,writable:!0,value:void 0},Object.getOwnPropertyNames(Object.prototype).forEach(function(t){a[t]="__proto__"!==t?o:{configurable:!0,enumerable:!1,writable:!0,value:void 0}}),Object.defineProperties(i,a),Object.defineProperty(n,"nullPolyfill",{configurable:!1,enumerable:!1,writable:!1,value:i}),function(t,e){return s(null===t?i:t,e)}):s},{"./set-prototype-of/is-implemented":190,"./set-prototype-of/shim":191}],180:[function(t,e,r){"use strict";e.exports=t("./_iterate")("forEach")},{"./_iterate":174}],181:[function(t,e,r){"use strict";e.exports=function(t){return"function"==typeof t}},{}],182:[function(t,e,r){"use strict";var n=t("./is-value"),i={function:!0,object:!0};e.exports=function(t){return n(t)&&i[typeof t]||!1}},{"./is-value":183}],183:[function(t,e,r){"use strict";var n=t("../function/noop")();e.exports=function(t){return t!==n&&null!==t}},{"../function/noop":168}],184:[function(t,e,r){"use strict";e.exports=t("./is-implemented")()?Object.keys:t("./shim")},{"./is-implemented":185,"./shim":186}],185:[function(t,e,r){"use strict";e.exports=function(){try{return Object.keys("primitive"),!0}catch(t){return!1}}},{}],186:[function(t,e,r){"use strict";var n=t("../is-value"),i=Object.keys;e.exports=function(t){return i(n(t)?Object(t):t)}},{"../is-value":183}],187:[function(t,e,r){"use strict";var n=t("./valid-callable"),i=t("./for-each"),a=Function.prototype.call;e.exports=function(t,e){var r={},o=arguments[2];return n(e),i(t,function(t,n,i,s){r[n]=a.call(e,o,t,n,i,s)}),r}},{"./for-each":180,"./valid-callable":192}],188:[function(t,e,r){"use strict";var n=t("./is-value"),i=Array.prototype.forEach,a=Object.create;e.exports=function(t){var e=a(null);return i.call(arguments,function(t){n(t)&&function(t,e){var r;for(r in t)e[r]=t[r]}(Object(t),e)}),e}},{"./is-value":183}],189:[function(t,e,r){"use strict";e.exports=t("./is-implemented")()?Object.setPrototypeOf:t("./shim")},{"./is-implemented":190,"./shim":191}],190:[function(t,e,r){"use strict";var n=Object.create,i=Object.getPrototypeOf,a={};e.exports=function(){var t=Object.setPrototypeOf,e=arguments[0]||n;return"function"==typeof t&&i(t(e(null),a))===a}},{}],191:[function(t,e,r){"use strict";var n,i,a,o,s=t("../is-object"),l=t("../valid-value"),c=Object.prototype.isPrototypeOf,u=Object.defineProperty,h={configurable:!0,enumerable:!1,writable:!0,value:void 0};n=function(t,e){if(l(t),null===e||s(e))return t;throw new TypeError("Prototype must be null or an object")},e.exports=(i=function(){var t,e=Object.create(null),r={},n=Object.getOwnPropertyDescriptor(Object.prototype,"__proto__");if(n){try{(t=n.set).call(e,r)}catch(t){}if(Object.getPrototypeOf(e)===r)return{set:t,level:2}}return e.__proto__=r,Object.getPrototypeOf(e)===r?{level:2}:((e={}).__proto__=r,Object.getPrototypeOf(e)===r&&{level:1})}())?(2===i.level?i.set?(o=i.set,a=function(t,e){return o.call(n(t,e),e),t}):a=function(t,e){return n(t,e).__proto__=e,t}:a=function t(e,r){var i;return n(e,r),(i=c.call(t.nullPolyfill,e))&&delete t.nullPolyfill.__proto__,null===r&&(r=t.nullPolyfill),e.__proto__=r,i&&u(t.nullPolyfill,"__proto__",h),e},Object.defineProperty(a,"level",{configurable:!1,enumerable:!1,writable:!1,value:i.level})):null,t("../create")},{"../create":179,"../is-object":182,"../valid-value":194}],192:[function(t,e,r){"use strict";e.exports=function(t){if("function"!=typeof t)throw new TypeError(t+" is not a function");return t}},{}],193:[function(t,e,r){"use strict";var n=t("./is-object");e.exports=function(t){if(!n(t))throw new TypeError(t+" is not an Object");return t}},{"./is-object":182}],194:[function(t,e,r){"use strict";var n=t("./is-value");e.exports=function(t){if(!n(t))throw new TypeError("Cannot use null or undefined");return t}},{"./is-value":183}],195:[function(t,e,r){"use strict";e.exports=t("./is-implemented")()?String.prototype.contains:t("./shim")},{"./is-implemented":196,"./shim":197}],196:[function(t,e,r){"use strict";var n="razdwatrzy";e.exports=function(){return"function"==typeof n.contains&&(!0===n.contains("dwa")&&!1===n.contains("foo"))}},{}],197:[function(t,e,r){"use strict";var n=String.prototype.indexOf;e.exports=function(t){return n.call(this,t,arguments[1])>-1}},{}],198:[function(t,e,r){"use strict";var n=Object.prototype.toString,i=n.call("");e.exports=function(t){return"string"==typeof t||t&&"object"==typeof t&&(t instanceof String||n.call(t)===i)||!1}},{}],199:[function(t,e,r){"use strict";var n=Object.create(null),i=Math.random;e.exports=function(){var t;do{t=i().toString(36).slice(2)}while(n[t]);return t}},{}],200:[function(t,e,r){"use strict";var n,i=t("es5-ext/object/set-prototype-of"),a=t("es5-ext/string/#/contains"),o=t("d"),s=t("es6-symbol"),l=t("./"),c=Object.defineProperty;n=e.exports=function(t,e){if(!(this instanceof n))throw new TypeError("Constructor requires 'new'");l.call(this,t),e=e?a.call(e,"key+value")?"key+value":a.call(e,"key")?"key":"value":"value",c(this,"__kind__",o("",e))},i&&i(n,l),delete n.prototype.constructor,n.prototype=Object.create(l.prototype,{_resolve:o(function(t){return"value"===this.__kind__?this.__list__[t]:"key+value"===this.__kind__?[t,this.__list__[t]]:t})}),c(n.prototype,s.toStringTag,o("c","Array Iterator"))},{"./":203,d:139,"es5-ext/object/set-prototype-of":189,"es5-ext/string/#/contains":195,"es6-symbol":208}],201:[function(t,e,r){"use strict";var n=t("es5-ext/function/is-arguments"),i=t("es5-ext/object/valid-callable"),a=t("es5-ext/string/is-string"),o=t("./get"),s=Array.isArray,l=Function.prototype.call,c=Array.prototype.some;e.exports=function(t,e){var r,u,h,f,p,d,g,v,m=arguments[2];if(s(t)||n(t)?r="array":a(t)?r="string":t=o(t),i(e),h=function(){f=!0},"array"!==r)if("string"!==r)for(u=t.next();!u.done;){if(l.call(e,m,u.value,h),f)return;u=t.next()}else for(d=t.length,p=0;p<d&&(g=t[p],p+1<d&&(v=g.charCodeAt(0))>=55296&&v<=56319&&(g+=t[++p]),l.call(e,m,g,h),!f);++p);else c.call(t,function(t){return l.call(e,m,t,h),f})}},{"./get":202,"es5-ext/function/is-arguments":166,"es5-ext/object/valid-callable":192,"es5-ext/string/is-string":198}],202:[function(t,e,r){"use strict";var n=t("es5-ext/function/is-arguments"),i=t("es5-ext/string/is-string"),a=t("./array"),o=t("./string"),s=t("./valid-iterable"),l=t("es6-symbol").iterator;e.exports=function(t){return"function"==typeof s(t)[l]?t[l]():n(t)?new a(t):i(t)?new o(t):new a(t)}},{"./array":200,"./string":205,"./valid-iterable":206,"es5-ext/function/is-arguments":166,"es5-ext/string/is-string":198,"es6-symbol":208}],203:[function(t,e,r){"use strict";var n,i=t("es5-ext/array/#/clear"),a=t("es5-ext/object/assign"),o=t("es5-ext/object/valid-callable"),s=t("es5-ext/object/valid-value"),l=t("d"),c=t("d/auto-bind"),u=t("es6-symbol"),h=Object.defineProperty,f=Object.defineProperties;e.exports=n=function(t,e){if(!(this instanceof n))throw new TypeError("Constructor requires 'new'");f(this,{__list__:l("w",s(t)),__context__:l("w",e),__nextIndex__:l("w",0)}),e&&(o(e.on),e.on("_add",this._onAdd),e.on("_delete",this._onDelete),e.on("_clear",this._onClear))},delete n.prototype.constructor,f(n.prototype,a({_next:l(function(){var t;if(this.__list__)return this.__redo__&&void 0!==(t=this.__redo__.shift())?t:this.__nextIndex__<this.__list__.length?this.__nextIndex__++:void this._unBind()}),next:l(function(){return this._createResult(this._next())}),_createResult:l(function(t){return void 0===t?{done:!0,value:void 0}:{done:!1,value:this._resolve(t)}}),_resolve:l(function(t){return this.__list__[t]}),_unBind:l(function(){this.__list__=null,delete this.__redo__,this.__context__&&(this.__context__.off("_add",this._onAdd),this.__context__.off("_delete",this._onDelete),this.__context__.off("_clear",this._onClear),this.__context__=null)}),toString:l(function(){return"[object "+(this[u.toStringTag]||"Object")+"]"})},c({_onAdd:l(function(t){t>=this.__nextIndex__||(++this.__nextIndex__,this.__redo__?(this.__redo__.forEach(function(e,r){e>=t&&(this.__redo__[r]=++e)},this),this.__redo__.push(t)):h(this,"__redo__",l("c",[t])))}),_onDelete:l(function(t){var e;t>=this.__nextIndex__||(--this.__nextIndex__,this.__redo__&&(-1!==(e=this.__redo__.indexOf(t))&&this.__redo__.splice(e,1),this.__redo__.forEach(function(e,r){e>t&&(this.__redo__[r]=--e)},this)))}),_onClear:l(function(){this.__redo__&&i.call(this.__redo__),this.__nextIndex__=0})}))),h(n.prototype,u.iterator,l(function(){return this}))},{d:139,"d/auto-bind":138,"es5-ext/array/#/clear":162,"es5-ext/object/assign":175,"es5-ext/object/valid-callable":192,"es5-ext/object/valid-value":194,"es6-symbol":208}],204:[function(t,e,r){"use strict";var n=t("es5-ext/function/is-arguments"),i=t("es5-ext/object/is-value"),a=t("es5-ext/string/is-string"),o=t("es6-symbol").iterator,s=Array.isArray;e.exports=function(t){return!!i(t)&&(!!s(t)||(!!a(t)||(!!n(t)||"function"==typeof t[o])))}},{"es5-ext/function/is-arguments":166,"es5-ext/object/is-value":183,"es5-ext/string/is-string":198,"es6-symbol":208}],205:[function(t,e,r){"use strict";var n,i=t("es5-ext/object/set-prototype-of"),a=t("d"),o=t("es6-symbol"),s=t("./"),l=Object.defineProperty;n=e.exports=function(t){if(!(this instanceof n))throw new TypeError("Constructor requires 'new'");t=String(t),s.call(this,t),l(this,"__length__",a("",t.length))},i&&i(n,s),delete n.prototype.constructor,n.prototype=Object.create(s.prototype,{_next:a(function(){if(this.__list__)return this.__nextIndex__<this.__length__?this.__nextIndex__++:void this._unBind()}),_resolve:a(function(t){var e,r=this.__list__[t];return this.__nextIndex__===this.__length__?r:(e=r.charCodeAt(0))>=55296&&e<=56319?r+this.__list__[this.__nextIndex__++]:r})}),l(n.prototype,o.toStringTag,a("c","String Iterator"))},{"./":203,d:139,"es5-ext/object/set-prototype-of":189,"es6-symbol":208}],206:[function(t,e,r){"use strict";var n=t("./is-iterable");e.exports=function(t){if(!n(t))throw new TypeError(t+" is not iterable");return t}},{"./is-iterable":204}],207:[function(t,e,r){(function(n,i){!function(t,n){"object"==typeof r&&"undefined"!=typeof e?e.exports=n():t.ES6Promise=n()}(this,function(){"use strict";function e(t){return"function"==typeof t}var r=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)},a=0,o=void 0,s=void 0,l=function(t,e){g[a]=t,g[a+1]=e,2===(a+=2)&&(s?s(v):_())};var c="undefined"!=typeof window?window:void 0,u=c||{},h=u.MutationObserver||u.WebKitMutationObserver,f="undefined"==typeof self&&"undefined"!=typeof n&&"[object process]"==={}.toString.call(n),p="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel;function d(){var t=setTimeout;return function(){return t(v,1)}}var g=new Array(1e3);function v(){for(var t=0;t<a;t+=2){(0,g[t])(g[t+1]),g[t]=void 0,g[t+1]=void 0}a=0}var m,y,x,b,_=void 0;function w(t,e){var r=arguments,n=this,i=new this.constructor(M);void 0===i[A]&&U(i);var a,o=n._state;return o?(a=r[o-1],l(function(){return j(o,i,a,n._result)})):R(n,i,t,e),i}function k(t){if(t&&"object"==typeof t&&t.constructor===this)return t;var e=new this(M);return O(e,t),e}f?_=function(){return n.nextTick(v)}:h?(y=0,x=new h(v),b=document.createTextNode(""),x.observe(b,{characterData:!0}),_=function(){b.data=y=++y%2}):p?((m=new MessageChannel).port1.onmessage=v,_=function(){return m.port2.postMessage(0)}):_=void 0===c&&"function"==typeof t?function(){try{var e=t("vertx");return o=e.runOnLoop||e.runOnContext,function(){o(v)}}catch(t){return d()}}():d();var A=Math.random().toString(36).substring(16);function M(){}var T=void 0,S=1,E=2,C=new B;function L(t){try{return t.then}catch(t){return C.error=t,C}}function z(t,r,n){r.constructor===t.constructor&&n===w&&r.constructor.resolve===k?function(t,e){e._state===S?D(t,e._result):e._state===E?P(t,e._result):R(e,void 0,function(e){return O(t,e)},function(e){return P(t,e)})}(t,r):n===C?P(t,C.error):void 0===n?D(t,r):e(n)?function(t,e,r){l(function(t){var n=!1,i=function(t,e,r,n){try{t.call(e,r,n)}catch(t){return t}}(r,e,function(r){n||(n=!0,e!==r?O(t,r):D(t,r))},function(e){n||(n=!0,P(t,e))},t._label);!n&&i&&(n=!0,P(t,i))},t)}(t,r,n):D(t,r)}function O(t,e){var r;t===e?P(t,new TypeError("You cannot resolve a promise with itself")):"function"==typeof(r=e)||"object"==typeof r&&null!==r?z(t,e,L(e)):D(t,e)}function I(t){t._onerror&&t._onerror(t._result),F(t)}function D(t,e){t._state===T&&(t._result=e,t._state=S,0!==t._subscribers.length&&l(F,t))}function P(t,e){t._state===T&&(t._state=E,t._result=e,l(I,t))}function R(t,e,r,n){var i=t._subscribers,a=i.length;t._onerror=null,i[a]=e,i[a+S]=r,i[a+E]=n,0===a&&t._state&&l(F,t)}function F(t){var e=t._subscribers,r=t._state;if(0!==e.length){for(var n=void 0,i=void 0,a=t._result,o=0;o<e.length;o+=3)n=e[o],i=e[o+r],n?j(r,n,i,a):i(a);t._subscribers.length=0}}function B(){this.error=null}var N=new B;function j(t,r,n,i){var a=e(n),o=void 0,s=void 0,l=void 0,c=void 0;if(a){if((o=function(t,e){try{return t(e)}catch(t){return N.error=t,N}}(n,i))===N?(c=!0,s=o.error,o=null):l=!0,r===o)return void P(r,new TypeError("A promises callback cannot return that same promise."))}else o=i,l=!0;r._state!==T||(a&&l?O(r,o):c?P(r,s):t===S?D(r,o):t===E&&P(r,o))}var V=0;function U(t){t[A]=V++,t._state=void 0,t._result=void 0,t._subscribers=[]}function q(t,e){this._instanceConstructor=t,this.promise=new t(M),this.promise[A]||U(this.promise),r(e)?(this._input=e,this.length=e.length,this._remaining=e.length,this._result=new Array(this.length),0===this.length?D(this.promise,this._result):(this.length=this.length||0,this._enumerate(),0===this._remaining&&D(this.promise,this._result))):P(this.promise,new Error("Array Methods must be provided an Array"))}function H(t){this[A]=V++,this._result=this._state=void 0,this._subscribers=[],M!==t&&("function"!=typeof t&&function(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}(),this instanceof H?function(t,e){try{e(function(e){O(t,e)},function(e){P(t,e)})}catch(e){P(t,e)}}(this,t):function(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}())}function G(){var t=void 0;if("undefined"!=typeof i)t=i;else if("undefined"!=typeof self)t=self;else try{t=Function("return this")()}catch(t){throw new Error("polyfill failed because global object is unavailable in this environment")}var e=t.Promise;if(e){var r=null;try{r=Object.prototype.toString.call(e.resolve())}catch(t){}if("[object Promise]"===r&&!e.cast)return}t.Promise=H}return q.prototype._enumerate=function(){for(var t=this.length,e=this._input,r=0;this._state===T&&r<t;r++)this._eachEntry(e[r],r)},q.prototype._eachEntry=function(t,e){var r=this._instanceConstructor,n=r.resolve;if(n===k){var i=L(t);if(i===w&&t._state!==T)this._settledAt(t._state,e,t._result);else if("function"!=typeof i)this._remaining--,this._result[e]=t;else if(r===H){var a=new r(M);z(a,t,i),this._willSettleAt(a,e)}else this._willSettleAt(new r(function(e){return e(t)}),e)}else this._willSettleAt(n(t),e)},q.prototype._settledAt=function(t,e,r){var n=this.promise;n._state===T&&(this._remaining--,t===E?P(n,r):this._result[e]=r),0===this._remaining&&D(n,this._result)},q.prototype._willSettleAt=function(t,e){var r=this;R(t,void 0,function(t){return r._settledAt(S,e,t)},function(t){return r._settledAt(E,e,t)})},H.all=function(t){return new q(this,t).promise},H.race=function(t){var e=this;return r(t)?new e(function(r,n){for(var i=t.length,a=0;a<i;a++)e.resolve(t[a]).then(r,n)}):new e(function(t,e){return e(new TypeError("You must pass an array to race."))})},H.resolve=k,H.reject=function(t){var e=new this(M);return P(e,t),e},H._setScheduler=function(t){s=t},H._setAsap=function(t){l=t},H._asap=l,H.prototype={constructor:H,then:w,catch:function(t){return this.then(null,t)}},G(),H.polyfill=G,H.Promise=H,H})}).call(this,t("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:471}],208:[function(t,e,r){"use strict";e.exports=t("./is-implemented")()?Symbol:t("./polyfill")},{"./is-implemented":209,"./polyfill":211}],209:[function(t,e,r){"use strict";var n={object:!0,symbol:!0};e.exports=function(){var t;if("function"!=typeof Symbol)return!1;t=Symbol("test symbol");try{String(t)}catch(t){return!1}return!!n[typeof Symbol.iterator]&&(!!n[typeof Symbol.toPrimitive]&&!!n[typeof Symbol.toStringTag])}},{}],210:[function(t,e,r){"use strict";e.exports=function(t){return!!t&&("symbol"==typeof t||!!t.constructor&&("Symbol"===t.constructor.name&&"Symbol"===t[t.constructor.toStringTag]))}},{}],211:[function(t,e,r){"use strict";var n,i,a,o,s=t("d"),l=t("./validate-symbol"),c=Object.create,u=Object.defineProperties,h=Object.defineProperty,f=Object.prototype,p=c(null);if("function"==typeof Symbol){n=Symbol;try{String(n()),o=!0}catch(t){}}var d,g=(d=c(null),function(t){for(var e,r,n=0;d[t+(n||"")];)++n;return d[t+=n||""]=!0,h(f,e="@@"+t,s.gs(null,function(t){r||(r=!0,h(this,e,s(t)),r=!1)})),e});a=function(t){if(this instanceof a)throw new TypeError("Symbol is not a constructor");return i(t)},e.exports=i=function t(e){var r;if(this instanceof t)throw new TypeError("Symbol is not a constructor");return o?n(e):(r=c(a.prototype),e=void 0===e?"":String(e),u(r,{__description__:s("",e),__name__:s("",g(e))}))},u(i,{for:s(function(t){return p[t]?p[t]:p[t]=i(String(t))}),keyFor:s(function(t){var e;for(e in l(t),p)if(p[e]===t)return e}),hasInstance:s("",n&&n.hasInstance||i("hasInstance")),isConcatSpreadable:s("",n&&n.isConcatSpreadable||i("isConcatSpreadable")),iterator:s("",n&&n.iterator||i("iterator")),match:s("",n&&n.match||i("match")),replace:s("",n&&n.replace||i("replace")),search:s("",n&&n.search||i("search")),species:s("",n&&n.species||i("species")),split:s("",n&&n.split||i("split")),toPrimitive:s("",n&&n.toPrimitive||i("toPrimitive")),toStringTag:s("",n&&n.toStringTag||i("toStringTag")),unscopables:s("",n&&n.unscopables||i("unscopables"))}),u(a.prototype,{constructor:s(i),toString:s("",function(){return this.__name__})}),u(i.prototype,{toString:s(function(){return"Symbol ("+l(this).__description__+")"}),valueOf:s(function(){return l(this)})}),h(i.prototype,i.toPrimitive,s("",function(){var t=l(this);return"symbol"==typeof t?t:t.toString()})),h(i.prototype,i.toStringTag,s("c","Symbol")),h(a.prototype,i.toStringTag,s("c",i.prototype[i.toStringTag])),h(a.prototype,i.toPrimitive,s("c",i.prototype[i.toPrimitive]))},{"./validate-symbol":212,d:139}],212:[function(t,e,r){"use strict";var n=t("./is-symbol");e.exports=function(t){if(!n(t))throw new TypeError(t+" is not a symbol");return t}},{"./is-symbol":210}],213:[function(t,e,r){"use strict";e.exports=t("./is-implemented")()?WeakMap:t("./polyfill")},{"./is-implemented":214,"./polyfill":216}],214:[function(t,e,r){"use strict";e.exports=function(){var t,e;if("function"!=typeof WeakMap)return!1;try{t=new WeakMap([[e={},"one"],[{},"two"],[{},"three"]])}catch(t){return!1}return"[object WeakMap]"===String(t)&&("function"==typeof t.set&&(t.set({},1)===t&&("function"==typeof t.delete&&("function"==typeof t.has&&"one"===t.get(e)))))}},{}],215:[function(t,e,r){"use strict";e.exports="function"==typeof WeakMap&&"[object WeakMap]"===Object.prototype.toString.call(new WeakMap)},{}],216:[function(t,e,r){"use strict";var n,i=t("es5-ext/object/set-prototype-of"),a=t("es5-ext/object/valid-object"),o=t("es5-ext/object/valid-value"),s=t("es5-ext/string/random-uniq"),l=t("d"),c=t("es6-iterator/get"),u=t("es6-iterator/for-of"),h=t("es6-symbol").toStringTag,f=t("./is-native-implemented"),p=Array.isArray,d=Object.defineProperty,g=Object.prototype.hasOwnProperty,v=Object.getPrototypeOf;e.exports=n=function(){var t,e=arguments[0];if(!(this instanceof n))throw new TypeError("Constructor requires 'new'");return t=f&&i&&WeakMap!==n?i(new WeakMap,v(this)):this,null!=e&&(p(e)||(e=c(e))),d(t,"__weakMapData__",l("c","$weakMap$"+s())),e?(u(e,function(e){o(e),t.set(e[0],e[1])}),t):t},f&&(i&&i(n,WeakMap),n.prototype=Object.create(WeakMap.prototype,{constructor:l(n)})),Object.defineProperties(n.prototype,{delete:l(function(t){return!!g.call(a(t),this.__weakMapData__)&&(delete t[this.__weakMapData__],!0)}),get:l(function(t){if(g.call(a(t),this.__weakMapData__))return t[this.__weakMapData__]}),has:l(function(t){return g.call(a(t),this.__weakMapData__)}),set:l(function(t,e){return d(a(t),this.__weakMapData__,l("c",e)),this}),toString:l(function(){return"[object WeakMap]"})}),d(n.prototype,h,l("c","WeakMap"))},{"./is-native-implemented":215,d:139,"es5-ext/object/set-prototype-of":189,"es5-ext/object/valid-object":193,"es5-ext/object/valid-value":194,"es5-ext/string/random-uniq":199,"es6-iterator/for-of":201,"es6-iterator/get":202,"es6-symbol":208}],217:[function(t,e,r){"use strict";e.exports=function(t,e,r){var n=e||0,i=r||1;return[[t[12]+t[0],t[13]+t[1],t[14]+t[2],t[15]+t[3]],[t[12]-t[0],t[13]-t[1],t[14]-t[2],t[15]-t[3]],[t[12]+t[4],t[13]+t[5],t[14]+t[6],t[15]+t[7]],[t[12]-t[4],t[13]-t[5],t[14]-t[6],t[15]-t[7]],[n*t[12]+t[8],n*t[13]+t[9],n*t[14]+t[10],n*t[15]+t[11]],[i*t[12]-t[8],i*t[13]-t[9],i*t[14]-t[10],i*t[15]-t[11]]]}},{}],218:[function(t,e,r){"use strict";var n=t("is-string-blank");e.exports=function(t){var e=typeof t;if("string"===e){var r=t;if(0===(t=+t)&&n(r))return!1}else if("number"!==e)return!1;return t-t<1}},{"is-string-blank":412}],219:[function(t,e,r){"use strict";e.exports=function(t,e,r){switch(arguments.length){case 0:return new o([0],[0],0);case 1:if("number"==typeof t){var n=l(t);return new o(n,n,0)}return new o(t,l(t.length),0);case 2:if("number"==typeof e){var n=l(t.length);return new o(t,n,+e)}r=0;case 3:if(t.length!==e.length)throw new Error("state and velocity lengths must match");return new o(t,e,r)}};var n=t("cubic-hermite"),i=t("binary-search-bounds");function a(t,e,r){return Math.min(e,Math.max(t,r))}function o(t,e,r){this.dimension=t.length,this.bounds=[new Array(this.dimension),new Array(this.dimension)];for(var n=0;n<this.dimension;++n)this.bounds[0][n]=-1/0,this.bounds[1][n]=1/0;this._state=t.slice().reverse(),this._velocity=e.slice().reverse(),this._time=[r],this._scratch=[t.slice(),t.slice(),t.slice(),t.slice(),t.slice()]}var s=o.prototype;function l(t){for(var e=new Array(t),r=0;r<t;++r)e[r]=0;return e}s.flush=function(t){var e=i.gt(this._time,t)-1;e<=0||(this._time.splice(0,e),this._state.splice(0,e*this.dimension),this._velocity.splice(0,e*this.dimension))},s.curve=function(t){var e=this._time,r=e.length,o=i.le(e,t),s=this._scratch[0],l=this._state,c=this._velocity,u=this.dimension,h=this.bounds;if(o<0)for(var f=u-1,p=0;p<u;++p,--f)s[p]=l[f];else if(o>=r-1){f=l.length-1;var d=t-e[r-1];for(p=0;p<u;++p,--f)s[p]=l[f]+d*c[f]}else{f=u*(o+1)-1;var g=e[o],v=e[o+1]-g||1,m=this._scratch[1],y=this._scratch[2],x=this._scratch[3],b=this._scratch[4],_=!0;for(p=0;p<u;++p,--f)m[p]=l[f],x[p]=c[f]*v,y[p]=l[f+u],b[p]=c[f+u]*v,_=_&&m[p]===y[p]&&x[p]===b[p]&&0===x[p];if(_)for(p=0;p<u;++p)s[p]=m[p];else n(m,x,y,b,(t-g)/v,s)}var w=h[0],k=h[1];for(p=0;p<u;++p)s[p]=a(w[p],k[p],s[p]);return s},s.dcurve=function(t){var e=this._time,r=e.length,a=i.le(e,t),o=this._scratch[0],s=this._state,l=this._velocity,c=this.dimension;if(a>=r-1)for(var u=s.length-1,h=(e[r-1],0);h<c;++h,--u)o[h]=l[u];else{u=c*(a+1)-1;var f=e[a],p=e[a+1]-f||1,d=this._scratch[1],g=this._scratch[2],v=this._scratch[3],m=this._scratch[4],y=!0;for(h=0;h<c;++h,--u)d[h]=s[u],v[h]=l[u]*p,g[h]=s[u+c],m[h]=l[u+c]*p,y=y&&d[h]===g[h]&&v[h]===m[h]&&0===v[h];if(y)for(h=0;h<c;++h)o[h]=0;else{n.derivative(d,v,g,m,(t-f)/p,o);for(h=0;h<c;++h)o[h]/=p}}return o},s.lastT=function(){var t=this._time;return t[t.length-1]},s.stable=function(){for(var t=this._velocity,e=t.length,r=this.dimension-1;r>=0;--r)if(t[--e])return!1;return!0},s.jump=function(t){var e=this.lastT(),r=this.dimension;if(!(t<e||arguments.length!==r+1)){var n=this._state,i=this._velocity,o=n.length-this.dimension,s=this.bounds,l=s[0],c=s[1];this._time.push(e,t);for(var u=0;u<2;++u)for(var h=0;h<r;++h)n.push(n[o++]),i.push(0);this._time.push(t);for(h=r;h>0;--h)n.push(a(l[h-1],c[h-1],arguments[h])),i.push(0)}},s.push=function(t){var e=this.lastT(),r=this.dimension;if(!(t<e||arguments.length!==r+1)){var n=this._state,i=this._velocity,o=n.length-this.dimension,s=t-e,l=this.bounds,c=l[0],u=l[1],h=s>1e-6?1/s:0;this._time.push(t);for(var f=r;f>0;--f){var p=a(c[f-1],u[f-1],arguments[f]);n.push(p),i.push((p-n[o++])*h)}}},s.set=function(t){var e=this.dimension;if(!(t<this.lastT()||arguments.length!==e+1)){var r=this._state,n=this._velocity,i=this.bounds,o=i[0],s=i[1];this._time.push(t);for(var l=e;l>0;--l)r.push(a(o[l-1],s[l-1],arguments[l])),n.push(0)}},s.move=function(t){var e=this.lastT(),r=this.dimension;if(!(t<=e||arguments.length!==r+1)){var n=this._state,i=this._velocity,o=n.length-this.dimension,s=this.bounds,l=s[0],c=s[1],u=t-e,h=u>1e-6?1/u:0;this._time.push(t);for(var f=r;f>0;--f){var p=arguments[f];n.push(a(l[f-1],c[f-1],n[o++]+p)),i.push(p*h)}}},s.idle=function(t){var e=this.lastT();if(!(t<e)){var r=this.dimension,n=this._state,i=this._velocity,o=n.length-r,s=this.bounds,l=s[0],c=s[1],u=t-e;this._time.push(t);for(var h=r-1;h>=0;--h)n.push(a(l[h],c[h],n[o]+u*i[o])),i.push(0),o+=1}}},{"binary-search-bounds":79,"cubic-hermite":133}],220:[function(t,e,r){var n=t("dtype");e.exports=function(t,e,r){if(!t)throw new TypeError("must specify data as first parameter");if(r=0|+(r||0),Array.isArray(t)&&t[0]&&"number"==typeof t[0][0]){var i,a,o,s,l=t[0].length,c=t.length*l;e&&"string"!=typeof e||(e=new(n(e||"float32"))(c+r));var u=e.length-r;if(c!==u)throw new Error("source length "+c+" ("+l+"x"+t.length+") does not match destination length "+u);for(i=0,o=r;i<t.length;i++)for(a=0;a<l;a++)e[o++]=null===t[i][a]?NaN:t[i][a]}else if(e&&"string"!=typeof e)e.set(t,r);else{var h=n(e||"float32");if(Array.isArray(t)||"array"===e)for(e=new h(t.length+r),i=0,o=r,s=e.length;o<s;o++,i++)e[o]=null===t[i]?NaN:t[i];else 0===r?e=new h(t):(e=new h(t.length+r)).set(t,r)}return e}},{dtype:157}],221:[function(t,e,r){"use strict";var n=t("css-font/stringify"),i=[32,126];e.exports=function(t){var e=(t=t||{}).shape?t.shape:t.canvas?[t.canvas.width,t.canvas.height]:[512,512],r=t.canvas||document.createElement("canvas"),a=t.font,o="number"==typeof t.step?[t.step,t.step]:t.step||[32,32],s=t.chars||i;a&&"string"!=typeof a&&(a=n(a));if(Array.isArray(s)){if(2===s.length&&"number"==typeof s[0]&&"number"==typeof s[1]){for(var l=[],c=s[0],u=0;c<=s[1];c++)l[u++]=String.fromCharCode(c);s=l}}else s=String(s).split("");e=e.slice(),r.width=e[0],r.height=e[1];var h=r.getContext("2d");h.fillStyle="#000",h.fillRect(0,0,r.width,r.height),h.font=a,h.textAlign="center",h.textBaseline="middle",h.fillStyle="#fff";for(var f=o[0]/2,p=o[1]/2,c=0;c<s.length;c++)h.fillText(s[c],f,p),(f+=o[0])>e[0]-o[0]/2&&(f=o[0]/2,p+=o[1]);return r}},{"css-font/stringify":130}],222:[function(t,e,r){"use strict";function n(t,e){e||(e={}),("string"==typeof t||Array.isArray(t))&&(e.family=t);var r=Array.isArray(e.family)?e.family.join(", "):e.family;if(!r)throw Error("`family` must be defined");var s=e.size||e.fontSize||e.em||48,l=e.weight||e.fontWeight||"",c=(t=[e.style||e.fontStyle||"",l,s].join(" ")+"px "+r,e.origin||"top");if(n.cache[r]&&s<=n.cache[r].em)return i(n.cache[r],c);var u=e.canvas||n.canvas,h=u.getContext("2d"),f={upper:void 0!==e.upper?e.upper:"H",lower:void 0!==e.lower?e.lower:"x",descent:void 0!==e.descent?e.descent:"p",ascent:void 0!==e.ascent?e.ascent:"h",tittle:void 0!==e.tittle?e.tittle:"i",overshoot:void 0!==e.overshoot?e.overshoot:"O"},p=Math.ceil(1.5*s);u.height=p,u.width=.5*p,h.font=t;var d={top:0};h.clearRect(0,0,p,p),h.textBaseline="top",h.fillStyle="black",h.fillText("H",0,0);var g=a(h.getImageData(0,0,p,p));h.clearRect(0,0,p,p),h.textBaseline="bottom",h.fillText("H",0,p);var v=a(h.getImageData(0,0,p,p));d.lineHeight=d.bottom=p-v+g,h.clearRect(0,0,p,p),h.textBaseline="alphabetic",h.fillText("H",0,p);var m=p-a(h.getImageData(0,0,p,p))-1+g;d.baseline=d.alphabetic=m,h.clearRect(0,0,p,p),h.textBaseline="middle",h.fillText("H",0,.5*p);var y=a(h.getImageData(0,0,p,p));d.median=d.middle=p-y-1+g-.5*p,h.clearRect(0,0,p,p),h.textBaseline="hanging",h.fillText("H",0,.5*p);var x=a(h.getImageData(0,0,p,p));d.hanging=p-x-1+g-.5*p,h.clearRect(0,0,p,p),h.textBaseline="ideographic",h.fillText("H",0,p);var b=a(h.getImageData(0,0,p,p));if(d.ideographic=p-b-1+g,f.upper&&(h.clearRect(0,0,p,p),h.textBaseline="top",h.fillText(f.upper,0,0),d.upper=a(h.getImageData(0,0,p,p)),d.capHeight=d.baseline-d.upper),f.lower&&(h.clearRect(0,0,p,p),h.textBaseline="top",h.fillText(f.lower,0,0),d.lower=a(h.getImageData(0,0,p,p)),d.xHeight=d.baseline-d.lower),f.tittle&&(h.clearRect(0,0,p,p),h.textBaseline="top",h.fillText(f.tittle,0,0),d.tittle=a(h.getImageData(0,0,p,p))),f.ascent&&(h.clearRect(0,0,p,p),h.textBaseline="top",h.fillText(f.ascent,0,0),d.ascent=a(h.getImageData(0,0,p,p))),f.descent&&(h.clearRect(0,0,p,p),h.textBaseline="top",h.fillText(f.descent,0,0),d.descent=o(h.getImageData(0,0,p,p))),f.overshoot){h.clearRect(0,0,p,p),h.textBaseline="top",h.fillText(f.overshoot,0,0);var _=o(h.getImageData(0,0,p,p));d.overshoot=_-m}for(var w in d)d[w]/=s;return d.em=s,n.cache[r]=d,i(d,c)}function i(t,e){var r={};for(var n in"string"==typeof e&&(e=t[e]),t)"em"!==n&&(r[n]=t[n]-e);return r}function a(t){for(var e=t.height,r=t.data,n=3;n<r.length;n+=4)if(0!==r[n])return Math.floor(.25*(n-3)/e)}function o(t){for(var e=t.height,r=t.data,n=r.length-1;n>0;n-=4)if(0!==r[n])return Math.floor(.25*(n-3)/e)}e.exports=n,n.canvas=document.createElement("canvas"),n.cache={}},{}],223:[function(t,e,r){"use strict";e.exports=function(t){return new c(t||d,null)};var n=0,i=1;function a(t,e,r,n,i,a){this._color=t,this.key=e,this.value=r,this.left=n,this.right=i,this._count=a}function o(t){return new a(t._color,t.key,t.value,t.left,t.right,t._count)}function s(t,e){return new a(t,e.key,e.value,e.left,e.right,e._count)}function l(t){t._count=1+(t.left?t.left._count:0)+(t.right?t.right._count:0)}function c(t,e){this._compare=t,this.root=e}var u=c.prototype;function h(t,e){this.tree=t,this._stack=e}Object.defineProperty(u,"keys",{get:function(){var t=[];return this.forEach(function(e,r){t.push(e)}),t}}),Object.defineProperty(u,"values",{get:function(){var t=[];return this.forEach(function(e,r){t.push(r)}),t}}),Object.defineProperty(u,"length",{get:function(){return this.root?this.root._count:0}}),u.insert=function(t,e){for(var r=this._compare,o=this.root,u=[],h=[];o;){var f=r(t,o.key);u.push(o),h.push(f),o=f<=0?o.left:o.right}u.push(new a(n,t,e,null,null,1));for(var p=u.length-2;p>=0;--p){o=u[p];h[p]<=0?u[p]=new a(o._color,o.key,o.value,u[p+1],o.right,o._count+1):u[p]=new a(o._color,o.key,o.value,o.left,u[p+1],o._count+1)}for(p=u.length-1;p>1;--p){var d=u[p-1];o=u[p];if(d._color===i||o._color===i)break;var g=u[p-2];if(g.left===d)if(d.left===o){if(!(v=g.right)||v._color!==n){if(g._color=n,g.left=d.right,d._color=i,d.right=g,u[p-2]=d,u[p-1]=o,l(g),l(d),p>=3)(m=u[p-3]).left===g?m.left=d:m.right=d;break}d._color=i,g.right=s(i,v),g._color=n,p-=1}else{if(!(v=g.right)||v._color!==n){if(d.right=o.left,g._color=n,g.left=o.right,o._color=i,o.left=d,o.right=g,u[p-2]=o,u[p-1]=d,l(g),l(d),l(o),p>=3)(m=u[p-3]).left===g?m.left=o:m.right=o;break}d._color=i,g.right=s(i,v),g._color=n,p-=1}else if(d.right===o){if(!(v=g.left)||v._color!==n){if(g._color=n,g.right=d.left,d._color=i,d.left=g,u[p-2]=d,u[p-1]=o,l(g),l(d),p>=3)(m=u[p-3]).right===g?m.right=d:m.left=d;break}d._color=i,g.left=s(i,v),g._color=n,p-=1}else{var v;if(!(v=g.left)||v._color!==n){var m;if(d.left=o.right,g._color=n,g.right=o.left,o._color=i,o.right=d,o.left=g,u[p-2]=o,u[p-1]=d,l(g),l(d),l(o),p>=3)(m=u[p-3]).right===g?m.right=o:m.left=o;break}d._color=i,g.left=s(i,v),g._color=n,p-=1}}return u[0]._color=i,new c(r,u[0])},u.forEach=function(t,e,r){if(this.root)switch(arguments.length){case 1:return function t(e,r){var n;if(r.left&&(n=t(e,r.left)))return n;return(n=e(r.key,r.value))||(r.right?t(e,r.right):void 0)}(t,this.root);case 2:return function t(e,r,n,i){if(r(e,i.key)<=0){var a;if(i.left&&(a=t(e,r,n,i.left)))return a;if(a=n(i.key,i.value))return a}if(i.right)return t(e,r,n,i.right)}(e,this._compare,t,this.root);case 3:if(this._compare(e,r)>=0)return;return function t(e,r,n,i,a){var o,s=n(e,a.key),l=n(r,a.key);if(s<=0){if(a.left&&(o=t(e,r,n,i,a.left)))return o;if(l>0&&(o=i(a.key,a.value)))return o}if(l>0&&a.right)return t(e,r,n,i,a.right)}(e,r,this._compare,t,this.root)}},Object.defineProperty(u,"begin",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.left;return new h(this,t)}}),Object.defineProperty(u,"end",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.right;return new h(this,t)}}),u.at=function(t){if(t<0)return new h(this,[]);for(var e=this.root,r=[];;){if(r.push(e),e.left){if(t<e.left._count){e=e.left;continue}t-=e.left._count}if(!t)return new h(this,r);if(t-=1,!e.right)break;if(t>=e.right._count)break;e=e.right}return new h(this,[])},u.ge=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a<=0&&(i=n.length),r=a<=0?r.left:r.right}return n.length=i,new h(this,n)},u.gt=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a<0&&(i=n.length),r=a<0?r.left:r.right}return n.length=i,new h(this,n)},u.lt=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a>0&&(i=n.length),r=a<=0?r.left:r.right}return n.length=i,new h(this,n)},u.le=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a>=0&&(i=n.length),r=a<0?r.left:r.right}return n.length=i,new h(this,n)},u.find=function(t){for(var e=this._compare,r=this.root,n=[];r;){var i=e(t,r.key);if(n.push(r),0===i)return new h(this,n);r=i<=0?r.left:r.right}return new h(this,[])},u.remove=function(t){var e=this.find(t);return e?e.remove():this},u.get=function(t){for(var e=this._compare,r=this.root;r;){var n=e(t,r.key);if(0===n)return r.value;r=n<=0?r.left:r.right}};var f=h.prototype;function p(t,e){t.key=e.key,t.value=e.value,t.left=e.left,t.right=e.right,t._color=e._color,t._count=e._count}function d(t,e){return t<e?-1:t>e?1:0}Object.defineProperty(f,"valid",{get:function(){return this._stack.length>0}}),Object.defineProperty(f,"node",{get:function(){return this._stack.length>0?this._stack[this._stack.length-1]:null},enumerable:!0}),f.clone=function(){return new h(this.tree,this._stack.slice())},f.remove=function(){var t=this._stack;if(0===t.length)return this.tree;var e=new Array(t.length),r=t[t.length-1];e[e.length-1]=new a(r._color,r.key,r.value,r.left,r.right,r._count);for(var u=t.length-2;u>=0;--u){(r=t[u]).left===t[u+1]?e[u]=new a(r._color,r.key,r.value,e[u+1],r.right,r._count):e[u]=new a(r._color,r.key,r.value,r.left,e[u+1],r._count)}if((r=e[e.length-1]).left&&r.right){var h=e.length;for(r=r.left;r.right;)e.push(r),r=r.right;var f=e[h-1];e.push(new a(r._color,f.key,f.value,r.left,r.right,r._count)),e[h-1].key=r.key,e[h-1].value=r.value;for(u=e.length-2;u>=h;--u)r=e[u],e[u]=new a(r._color,r.key,r.value,r.left,e[u+1],r._count);e[h-1].left=e[h]}if((r=e[e.length-1])._color===n){var d=e[e.length-2];d.left===r?d.left=null:d.right===r&&(d.right=null),e.pop();for(u=0;u<e.length;++u)e[u]._count--;return new c(this.tree._compare,e[0])}if(r.left||r.right){r.left?p(r,r.left):r.right&&p(r,r.right),r._color=i;for(u=0;u<e.length-1;++u)e[u]._count--;return new c(this.tree._compare,e[0])}if(1===e.length)return new c(this.tree._compare,null);for(u=0;u<e.length;++u)e[u]._count--;var g=e[e.length-2];return function(t){for(var e,r,a,c,u=t.length-1;u>=0;--u){if(e=t[u],0===u)return void(e._color=i);if((r=t[u-1]).left===e){if((a=r.right).right&&a.right._color===n)return c=(a=r.right=o(a)).right=o(a.right),r.right=a.left,a.left=r,a.right=c,a._color=r._color,e._color=i,r._color=i,c._color=i,l(r),l(a),u>1&&((h=t[u-2]).left===r?h.left=a:h.right=a),void(t[u-1]=a);if(a.left&&a.left._color===n)return c=(a=r.right=o(a)).left=o(a.left),r.right=c.left,a.left=c.right,c.left=r,c.right=a,c._color=r._color,r._color=i,a._color=i,e._color=i,l(r),l(a),l(c),u>1&&((h=t[u-2]).left===r?h.left=c:h.right=c),void(t[u-1]=c);if(a._color===i){if(r._color===n)return r._color=i,void(r.right=s(n,a));r.right=s(n,a);continue}a=o(a),r.right=a.left,a.left=r,a._color=r._color,r._color=n,l(r),l(a),u>1&&((h=t[u-2]).left===r?h.left=a:h.right=a),t[u-1]=a,t[u]=r,u+1<t.length?t[u+1]=e:t.push(e),u+=2}else{if((a=r.left).left&&a.left._color===n)return c=(a=r.left=o(a)).left=o(a.left),r.left=a.right,a.right=r,a.left=c,a._color=r._color,e._color=i,r._color=i,c._color=i,l(r),l(a),u>1&&((h=t[u-2]).right===r?h.right=a:h.left=a),void(t[u-1]=a);if(a.right&&a.right._color===n)return c=(a=r.left=o(a)).right=o(a.right),r.left=c.right,a.right=c.left,c.right=r,c.left=a,c._color=r._color,r._color=i,a._color=i,e._color=i,l(r),l(a),l(c),u>1&&((h=t[u-2]).right===r?h.right=c:h.left=c),void(t[u-1]=c);if(a._color===i){if(r._color===n)return r._color=i,void(r.left=s(n,a));r.left=s(n,a);continue}var h;a=o(a),r.left=a.right,a.right=r,a._color=r._color,r._color=n,l(r),l(a),u>1&&((h=t[u-2]).right===r?h.right=a:h.left=a),t[u-1]=a,t[u]=r,u+1<t.length?t[u+1]=e:t.push(e),u+=2}}}(e),g.left===r?g.left=null:g.right=null,new c(this.tree._compare,e[0])},Object.defineProperty(f,"key",{get:function(){if(this._stack.length>0)return this._stack[this._stack.length-1].key},enumerable:!0}),Object.defineProperty(f,"value",{get:function(){if(this._stack.length>0)return this._stack[this._stack.length-1].value},enumerable:!0}),Object.defineProperty(f,"index",{get:function(){var t=0,e=this._stack;if(0===e.length){var r=this.tree.root;return r?r._count:0}e[e.length-1].left&&(t=e[e.length-1].left._count);for(var n=e.length-2;n>=0;--n)e[n+1]===e[n].right&&(++t,e[n].left&&(t+=e[n].left._count));return t},enumerable:!0}),f.next=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.right)for(e=e.right;e;)t.push(e),e=e.left;else for(t.pop();t.length>0&&t[t.length-1].right===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(f,"hasNext",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].right)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].left===t[e])return!0;return!1}}),f.update=function(t){var e=this._stack;if(0===e.length)throw new Error("Can't update empty node!");var r=new Array(e.length),n=e[e.length-1];r[r.length-1]=new a(n._color,n.key,t,n.left,n.right,n._count);for(var i=e.length-2;i>=0;--i)(n=e[i]).left===e[i+1]?r[i]=new a(n._color,n.key,n.value,r[i+1],n.right,n._count):r[i]=new a(n._color,n.key,n.value,n.left,r[i+1],n._count);return new c(this.tree._compare,r[0])},f.prev=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.left)for(e=e.left;e;)t.push(e),e=e.right;else for(t.pop();t.length>0&&t[t.length-1].left===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(f,"hasPrev",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].left)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].right===t[e])return!0;return!1}})},{}],224:[function(t,e,r){var n=[.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-.13857109526572012,9984369578019572e-21,1.5056327351493116e-7],i=607/128,a=[.9999999999999971,57.15623566586292,-59.59796035547549,14.136097974741746,-.4919138160976202,3399464998481189e-20,4652362892704858e-20,-9837447530487956e-20,.0001580887032249125,-.00021026444172410488,.00021743961811521265,-.0001643181065367639,8441822398385275e-20,-26190838401581408e-21,36899182659531625e-22];function o(t){if(t<0)return Number("0/0");for(var e=a[0],r=a.length-1;r>0;--r)e+=a[r]/(t+r);var n=t+i+.5;return.5*Math.log(2*Math.PI)+(t+.5)*Math.log(n)-n+Math.log(e)-Math.log(t)}e.exports=function t(e){if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*t(1-e));if(e>100)return Math.exp(o(e));e-=1;for(var r=n[0],i=1;i<9;i++)r+=n[i]/(e+i);var a=e+7+.5;return Math.sqrt(2*Math.PI)*Math.pow(a,e+.5)*Math.exp(-a)*r},e.exports.log=o},{}],225:[function(t,e,r){e.exports=function(t,e){if("string"!=typeof t)throw new TypeError("must specify type string");if(e=e||{},"undefined"==typeof document&&!e.canvas)return null;var r=e.canvas||document.createElement("canvas");"number"==typeof e.width&&(r.width=e.width);"number"==typeof e.height&&(r.height=e.height);var n,i=e;try{var a=[t];0===t.indexOf("webgl")&&a.push("experimental-"+t);for(var o=0;o<a.length;o++)if(n=r.getContext(a[o],i))return n}catch(t){n=null}return n||null}},{}],226:[function(t,e,r){"use strict";e.exports=function(t,e){var r=new u(t);return r.update(e),r};var n=t("./lib/text.js"),i=t("./lib/lines.js"),a=t("./lib/background.js"),o=t("./lib/cube.js"),s=t("./lib/ticks.js"),l=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function c(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}function u(t){this.gl=t,this.pixelRatio=1,this.bounds=[[-10,-10,-10],[10,10,10]],this.ticks=[[],[],[]],this.autoTicks=!0,this.tickSpacing=[1,1,1],this.tickEnable=[!0,!0,!0],this.tickFont=["sans-serif","sans-serif","sans-serif"],this.tickSize=[12,12,12],this.tickAngle=[0,0,0],this.tickAlign=["auto","auto","auto"],this.tickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.tickPad=[10,10,10],this.lastCubeProps={cubeEdges:[0,0,0],axis:[0,0,0]},this.labels=["x","y","z"],this.labelEnable=[!0,!0,!0],this.labelFont="sans-serif",this.labelSize=[20,20,20],this.labelAngle=[0,0,0],this.labelAlign=["auto","auto","auto"],this.labelColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.labelPad=[10,10,10],this.lineEnable=[!0,!0,!0],this.lineMirror=[!1,!1,!1],this.lineWidth=[1,1,1],this.lineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.lineTickEnable=[!0,!0,!0],this.lineTickMirror=[!1,!1,!1],this.lineTickLength=[0,0,0],this.lineTickWidth=[1,1,1],this.lineTickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.gridEnable=[!0,!0,!0],this.gridWidth=[1,1,1],this.gridColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroEnable=[!0,!0,!0],this.zeroLineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroLineWidth=[2,2,2],this.backgroundEnable=[!1,!1,!1],this.backgroundColor=[[.8,.8,.8,.5],[.8,.8,.8,.5],[.8,.8,.8,.5]],this._firstInit=!0,this._text=null,this._lines=null,this._background=a(t)}var h=u.prototype;function f(){this.primalOffset=[0,0,0],this.primalMinor=[0,0,0],this.mirrorOffset=[0,0,0],this.mirrorMinor=[0,0,0]}h.update=function(t){function e(e,r,n){if(n in t){var i,a=t[n],o=this[n];(e?Array.isArray(a)&&Array.isArray(a[0]):Array.isArray(a))?this[n]=i=[r(a[0]),r(a[1]),r(a[2])]:this[n]=i=[r(a),r(a),r(a)];for(var s=0;s<3;++s)if(i[s]!==o[s])return!0}return!1}t=t||{};var r,a=e.bind(this,!1,Number),o=e.bind(this,!1,Boolean),l=e.bind(this,!1,String),c=e.bind(this,!0,function(t){if(Array.isArray(t)){if(3===t.length)return[+t[0],+t[1],+t[2],1];if(4===t.length)return[+t[0],+t[1],+t[2],+t[3]]}return[0,0,0,1]}),u=!1,h=!1;if("bounds"in t)for(var f=t.bounds,p=0;p<2;++p)for(var d=0;d<3;++d)f[p][d]!==this.bounds[p][d]&&(h=!0),this.bounds[p][d]=f[p][d];if("ticks"in t){r=t.ticks,u=!0,this.autoTicks=!1;for(p=0;p<3;++p)this.tickSpacing[p]=0}else a("tickSpacing")&&(this.autoTicks=!0,h=!0);if(this._firstInit&&("ticks"in t||"tickSpacing"in t||(this.autoTicks=!0),h=!0,u=!0,this._firstInit=!1),h&&this.autoTicks&&(r=s.create(this.bounds,this.tickSpacing),u=!0),u){for(p=0;p<3;++p)r[p].sort(function(t,e){return t.x-e.x});s.equal(r,this.ticks)?u=!1:this.ticks=r}o("tickEnable"),l("tickFont")&&(u=!0),a("tickSize"),a("tickAngle"),a("tickPad"),c("tickColor");var g=l("labels");l("labelFont")&&(g=!0),o("labelEnable"),a("labelSize"),a("labelPad"),c("labelColor"),o("lineEnable"),o("lineMirror"),a("lineWidth"),c("lineColor"),o("lineTickEnable"),o("lineTickMirror"),a("lineTickLength"),a("lineTickWidth"),c("lineTickColor"),o("gridEnable"),a("gridWidth"),c("gridColor"),o("zeroEnable"),c("zeroLineColor"),a("zeroLineWidth"),o("backgroundEnable"),c("backgroundColor"),this._text?this._text&&(g||u)&&this._text.update(this.bounds,this.labels,this.labelFont,this.ticks,this.tickFont):this._text=n(this.gl,this.bounds,this.labels,this.labelFont,this.ticks,this.tickFont),this._lines&&u&&(this._lines.dispose(),this._lines=null),this._lines||(this._lines=i(this.gl,this.bounds,this.ticks))};var p=[new f,new f,new f];function d(t,e,r,n,i){for(var a=t.primalOffset,o=t.primalMinor,s=t.mirrorOffset,l=t.mirrorMinor,c=n[e],u=0;u<3;++u)if(e!==u){var h=a,f=s,p=o,d=l;c&1<<u&&(h=s,f=a,p=l,d=o),h[u]=r[0][u],f[u]=r[1][u],i[u]>0?(p[u]=-1,d[u]=0):(p[u]=0,d[u]=1)}}var g=[0,0,0],v={model:l,view:l,projection:l,_ortho:!1};h.isOpaque=function(){return!0},h.isTransparent=function(){return!1},h.drawTransparent=function(t){};var m=[0,0,0],y=[0,0,0],x=[0,0,0];h.draw=function(t){t=t||v;for(var e=this.gl,r=t.model||l,n=t.view||l,i=t.projection||l,a=this.bounds,s=t._ortho||!1,u=o(r,n,i,a,s),h=u.cubeEdges,f=u.axis,b=n[12],_=n[13],w=n[14],k=n[15],A=(s?2:1)*this.pixelRatio*(i[3]*b+i[7]*_+i[11]*w+i[15]*k)/e.drawingBufferHeight,M=0;M<3;++M)this.lastCubeProps.cubeEdges[M]=h[M],this.lastCubeProps.axis[M]=f[M];var T=p;for(M=0;M<3;++M)d(p[M],M,this.bounds,h,f);e=this.gl;var S,E=g;for(M=0;M<3;++M)this.backgroundEnable[M]?E[M]=f[M]:E[M]=0;this._background.draw(r,n,i,a,E,this.backgroundColor),this._lines.bind(r,n,i,this);for(M=0;M<3;++M){var C=[0,0,0];f[M]>0?C[M]=a[1][M]:C[M]=a[0][M];for(var L=0;L<2;++L){var z=(M+1+L)%3,O=(M+1+(1^L))%3;this.gridEnable[z]&&this._lines.drawGrid(z,O,this.bounds,C,this.gridColor[z],this.gridWidth[z]*this.pixelRatio)}for(L=0;L<2;++L){z=(M+1+L)%3,O=(M+1+(1^L))%3;this.zeroEnable[O]&&Math.min(a[0][O],a[1][O])<=0&&Math.max(a[0][O],a[1][O])>=0&&this._lines.drawZero(z,O,this.bounds,C,this.zeroLineColor[O],this.zeroLineWidth[O]*this.pixelRatio)}}for(M=0;M<3;++M){this.lineEnable[M]&&this._lines.drawAxisLine(M,this.bounds,T[M].primalOffset,this.lineColor[M],this.lineWidth[M]*this.pixelRatio),this.lineMirror[M]&&this._lines.drawAxisLine(M,this.bounds,T[M].mirrorOffset,this.lineColor[M],this.lineWidth[M]*this.pixelRatio);var I=c(m,T[M].primalMinor),D=c(y,T[M].mirrorMinor),P=this.lineTickLength;for(L=0;L<3;++L){var R=A/r[5*L];I[L]*=P[L]*R,D[L]*=P[L]*R}this.lineTickEnable[M]&&this._lines.drawAxisTicks(M,T[M].primalOffset,I,this.lineTickColor[M],this.lineTickWidth[M]*this.pixelRatio),this.lineTickMirror[M]&&this._lines.drawAxisTicks(M,T[M].mirrorOffset,D,this.lineTickColor[M],this.lineTickWidth[M]*this.pixelRatio)}this._lines.unbind(),this._text.bind(r,n,i,this.pixelRatio);var F,B;function N(t){(B=[0,0,0])[t]=1}function j(t,e,r){var n=(t+1)%3,i=(t+2)%3,a=e[n],o=e[i],s=r[n],l=r[i];a>0&&l>0?N(n):a>0&&l<0?N(n):a<0&&l>0?N(n):a<0&&l<0?N(n):o>0&&s>0?N(i):o>0&&s<0?N(i):o<0&&s>0?N(i):o<0&&s<0&&N(i)}for(M=0;M<3;++M){var V=T[M].primalMinor,U=T[M].mirrorMinor,q=c(x,T[M].primalOffset);for(L=0;L<3;++L)this.lineTickEnable[M]&&(q[L]+=A*V[L]*Math.max(this.lineTickLength[L],0)/r[5*L]);var H=[0,0,0];if(H[M]=1,this.tickEnable[M]){-3600===this.tickAngle[M]?(this.tickAngle[M]=0,this.tickAlign[M]="auto"):this.tickAlign[M]=-1,F=1,"auto"===(S=[this.tickAlign[M],.5,F])[0]?S[0]=0:S[0]=parseInt(""+S[0]),B=[0,0,0],j(M,V,U);for(L=0;L<3;++L)q[L]+=A*V[L]*this.tickPad[L]/r[5*L];this._text.drawTicks(M,this.tickSize[M],this.tickAngle[M],q,this.tickColor[M],H,B,S)}if(this.labelEnable[M]){F=0,B=[0,0,0],this.labels[M].length>4&&(N(M),F=1),"auto"===(S=[this.labelAlign[M],.5,F])[0]?S[0]=0:S[0]=parseInt(""+S[0]);for(L=0;L<3;++L)q[L]+=A*V[L]*this.labelPad[L]/r[5*L];q[M]+=.5*(a[0][M]+a[1][M]),this._text.drawLabel(M,this.labelSize[M],this.labelAngle[M],q,this.labelColor[M],[0,0,0],B,S)}}this._text.unbind()},h.dispose=function(){this._text.dispose(),this._lines.dispose(),this._background.dispose(),this._lines=null,this._text=null,this._background=null,this.gl=null}},{"./lib/background.js":227,"./lib/cube.js":228,"./lib/lines.js":229,"./lib/text.js":231,"./lib/ticks.js":232}],227:[function(t,e,r){"use strict";e.exports=function(t){for(var e=[],r=[],s=0,l=0;l<3;++l)for(var c=(l+1)%3,u=(l+2)%3,h=[0,0,0],f=[0,0,0],p=-1;p<=1;p+=2){r.push(s,s+2,s+1,s+1,s+2,s+3),h[l]=p,f[l]=p;for(var d=-1;d<=1;d+=2){h[c]=d;for(var g=-1;g<=1;g+=2)h[u]=g,e.push(h[0],h[1],h[2],f[0],f[1],f[2]),s+=1}var v=c;c=u,u=v}var m=n(t,new Float32Array(e)),y=n(t,new Uint16Array(r),t.ELEMENT_ARRAY_BUFFER),x=i(t,[{buffer:m,type:t.FLOAT,size:3,offset:0,stride:24},{buffer:m,type:t.FLOAT,size:3,offset:12,stride:24}],y),b=a(t);return b.attributes.position.location=0,b.attributes.normal.location=1,new o(t,m,x,b)};var n=t("gl-buffer"),i=t("gl-vao"),a=t("./shaders").bg;function o(t,e,r,n){this.gl=t,this.buffer=e,this.vao=r,this.shader=n}var s=o.prototype;s.draw=function(t,e,r,n,i,a){for(var o=!1,s=0;s<3;++s)o=o||i[s];if(o){var l=this.gl;l.enable(l.POLYGON_OFFSET_FILL),l.polygonOffset(1,2),this.shader.bind(),this.shader.uniforms={model:t,view:e,projection:r,bounds:n,enable:i,colors:a},this.vao.bind(),this.vao.draw(this.gl.TRIANGLES,36),this.vao.unbind(),l.disable(l.POLYGON_OFFSET_FILL)}},s.dispose=function(){this.vao.dispose(),this.buffer.dispose(),this.shader.dispose()}},{"./shaders":230,"gl-buffer":234,"gl-vao":316}],228:[function(t,e,r){"use strict";e.exports=function(t,e,r,a,p){i(s,e,t),i(s,r,s);for(var y=0,x=0;x<2;++x){u[2]=a[x][2];for(var b=0;b<2;++b){u[1]=a[b][1];for(var _=0;_<2;++_)u[0]=a[_][0],f(l[y],u,s),y+=1}}for(var w=-1,x=0;x<8;++x){for(var k=l[x][3],A=0;A<3;++A)c[x][A]=l[x][A]/k;p&&(c[x][2]*=-1),k<0&&(w<0?w=x:c[x][2]<c[w][2]&&(w=x))}if(w<0){w=0;for(var M=0;M<3;++M){for(var T=(M+2)%3,S=(M+1)%3,E=-1,C=-1,L=0;L<2;++L){var z=L<<M,O=z+(L<<T)+(1-L<<S),I=z+(1-L<<T)+(L<<S);o(c[z],c[O],c[I],h)<0||(L?E=1:C=1)}if(E<0||C<0)C>E&&(w|=1<<M);else{for(var L=0;L<2;++L){var z=L<<M,O=z+(L<<T)+(1-L<<S),I=z+(1-L<<T)+(L<<S),D=d([l[z],l[O],l[I],l[z+(1<<T)+(1<<S)]]);L?E=D:C=D}C>E&&(w|=1<<M)}}}for(var P=7^w,R=-1,x=0;x<8;++x)x!==w&&x!==P&&(R<0?R=x:c[R][1]>c[x][1]&&(R=x));for(var F=-1,x=0;x<3;++x){var B=R^1<<x;if(B!==w&&B!==P){F<0&&(F=B);var S=c[B];S[0]<c[F][0]&&(F=B)}}for(var N=-1,x=0;x<3;++x){var B=R^1<<x;if(B!==w&&B!==P&&B!==F){N<0&&(N=B);var S=c[B];S[0]>c[N][0]&&(N=B)}}var j=g;j[0]=j[1]=j[2]=0,j[n.log2(F^R)]=R&F,j[n.log2(R^N)]=R&N;var V=7^N;V===w||V===P?(V=7^F,j[n.log2(N^V)]=V&N):j[n.log2(F^V)]=V&F;for(var U=v,q=w,M=0;M<3;++M)U[M]=q&1<<M?-1:1;return m};var n=t("bit-twiddle"),i=t("gl-mat4/multiply"),a=t("split-polygon"),o=t("robust-orientation"),s=new Array(16),l=new Array(8),c=new Array(8),u=new Array(3),h=[0,0,0];function f(t,e,r){for(var n=0;n<4;++n){t[n]=r[12+n];for(var i=0;i<3;++i)t[n]+=e[i]*r[4*i+n]}}!function(){for(var t=0;t<8;++t)l[t]=[1,1,1,1],c[t]=[1,1,1]}();var p=[[0,0,1,0,0],[0,0,-1,1,0],[0,-1,0,1,0],[0,1,0,1,0],[-1,0,0,1,0],[1,0,0,1,0]];function d(t){for(var e=0;e<p.length;++e)if((t=a.positive(t,p[e])).length<3)return 0;var r=t[0],n=r[0]/r[3],i=r[1]/r[3],o=0;for(e=1;e+1<t.length;++e){var s=t[e],l=t[e+1],c=s[0]/s[3]-n,u=s[1]/s[3]-i,h=l[0]/l[3]-n,f=l[1]/l[3]-i;o+=Math.abs(c*f-u*h)}return o}var g=[1,1,1],v=[0,0,0],m={cubeEdges:g,axis:v}},{"bit-twiddle":80,"gl-mat4/multiply":260,"robust-orientation":491,"split-polygon":508}],229:[function(t,e,r){"use strict";e.exports=function(t,e,r){var o=[],s=[0,0,0],l=[0,0,0],c=[0,0,0],u=[0,0,0];o.push(0,0,1,0,1,1,0,0,-1,0,0,-1,0,1,1,0,1,-1);for(var h=0;h<3;++h){for(var f=o.length/3|0,d=0;d<r[h].length;++d){var g=+r[h][d].x;o.push(g,0,1,g,1,1,g,0,-1,g,0,-1,g,1,1,g,1,-1)}var v=o.length/3|0;s[h]=f,l[h]=v-f;for(var f=o.length/3|0,m=0;m<r[h].length;++m){var g=+r[h][m].x;o.push(g,0,1,g,1,1,g,0,-1,g,0,-1,g,1,1,g,1,-1)}var v=o.length/3|0;c[h]=f,u[h]=v-f}var y=n(t,new Float32Array(o)),x=i(t,[{buffer:y,type:t.FLOAT,size:3,stride:0,offset:0}]),b=a(t);return b.attributes.position.location=0,new p(t,y,x,b,l,s,u,c)};var n=t("gl-buffer"),i=t("gl-vao"),a=t("./shaders").line,o=[0,0,0],s=[0,0,0],l=[0,0,0],c=[0,0,0],u=[1,1];function h(t){return t[0]=t[1]=t[2]=0,t}function f(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}function p(t,e,r,n,i,a,o,s){this.gl=t,this.vertBuffer=e,this.vao=r,this.shader=n,this.tickCount=i,this.tickOffset=a,this.gridCount=o,this.gridOffset=s}var d=p.prototype;d.bind=function(t,e,r){this.shader.bind(),this.shader.uniforms.model=t,this.shader.uniforms.view=e,this.shader.uniforms.projection=r,u[0]=this.gl.drawingBufferWidth,u[1]=this.gl.drawingBufferHeight,this.shader.uniforms.screenShape=u,this.vao.bind()},d.unbind=function(){this.vao.unbind()},d.drawAxisLine=function(t,e,r,n,i){var a=h(s);this.shader.uniforms.majorAxis=s,a[t]=e[1][t]-e[0][t],this.shader.uniforms.minorAxis=a;var o,u=f(c,r);u[t]+=e[0][t],this.shader.uniforms.offset=u,this.shader.uniforms.lineWidth=i,this.shader.uniforms.color=n,(o=h(l))[(t+2)%3]=1,this.shader.uniforms.screenAxis=o,this.vao.draw(this.gl.TRIANGLES,6),(o=h(l))[(t+1)%3]=1,this.shader.uniforms.screenAxis=o,this.vao.draw(this.gl.TRIANGLES,6)},d.drawAxisTicks=function(t,e,r,n,i){if(this.tickCount[t]){var a=h(o);a[t]=1,this.shader.uniforms.majorAxis=a,this.shader.uniforms.offset=e,this.shader.uniforms.minorAxis=r,this.shader.uniforms.color=n,this.shader.uniforms.lineWidth=i;var s=h(l);s[t]=1,this.shader.uniforms.screenAxis=s,this.vao.draw(this.gl.TRIANGLES,this.tickCount[t],this.tickOffset[t])}},d.drawGrid=function(t,e,r,n,i,a){if(this.gridCount[t]){var u=h(s);u[e]=r[1][e]-r[0][e],this.shader.uniforms.minorAxis=u;var p=f(c,n);p[e]+=r[0][e],this.shader.uniforms.offset=p;var d=h(o);d[t]=1,this.shader.uniforms.majorAxis=d;var g=h(l);g[t]=1,this.shader.uniforms.screenAxis=g,this.shader.uniforms.lineWidth=a,this.shader.uniforms.color=i,this.vao.draw(this.gl.TRIANGLES,this.gridCount[t],this.gridOffset[t])}},d.drawZero=function(t,e,r,n,i,a){var o=h(s);this.shader.uniforms.majorAxis=o,o[t]=r[1][t]-r[0][t],this.shader.uniforms.minorAxis=o;var u=f(c,n);u[t]+=r[0][t],this.shader.uniforms.offset=u;var p=h(l);p[e]=1,this.shader.uniforms.screenAxis=p,this.shader.uniforms.lineWidth=a,this.shader.uniforms.color=i,this.vao.draw(this.gl.TRIANGLES,6)},d.dispose=function(){this.vao.dispose(),this.vertBuffer.dispose(),this.shader.dispose()}},{"./shaders":230,"gl-buffer":234,"gl-vao":316}],230:[function(t,e,r){"use strict";var n=t("glslify"),i=t("gl-shader"),a=n(["#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, majorAxis, minorAxis, screenAxis;\nuniform float lineWidth;\nuniform vec2 screenShape;\n\nvec3 project(vec3 p) {\n  vec4 pp = projection * view * model * vec4(p, 1.0);\n  return pp.xyz / max(pp.w, 0.0001);\n}\n\nvoid main() {\n  vec3 major = position.x * majorAxis;\n  vec3 minor = position.y * minorAxis;\n\n  vec3 vPosition = major + minor + offset;\n  vec3 pPosition = project(vPosition);\n  vec3 offset = project(vPosition + screenAxis * position.z);\n\n  vec2 screen = normalize((offset - pPosition).xy * screenShape) / screenShape;\n\n  gl_Position = vec4(pPosition + vec3(0.5 * screen * lineWidth, 0), 1.0);\n}\n"]),o=n(["precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n  gl_FragColor = color;\n}"]);r.line=function(t){return i(t,a,o,null,[{name:"position",type:"vec3"}])};var s=n(["#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, axis, alignDir, alignOpt;\nuniform float scale, angle, pixelScale;\nuniform vec2 resolution;\n\nvec3 project(vec3 p) {\n  vec4 pp = projection * view * model * vec4(p, 1.0);\n  return pp.xyz / max(pp.w, 0.0001);\n}\n\nfloat computeViewAngle(vec3 a, vec3 b) {\n  vec3 A = project(a);\n  vec3 B = project(b);\n\n  return atan(\n    (B.y - A.y) * resolution.y,\n    (B.x - A.x) * resolution.x\n  );\n}\n\nconst float PI = 3.141592;\nconst float TWO_PI = 2.0 * PI;\nconst float HALF_PI = 0.5 * PI;\nconst float ONE_AND_HALF_PI = 1.5 * PI;\n\nint option = int(floor(alignOpt.x + 0.001));\nfloat hv_ratio =       alignOpt.y;\nbool enableAlign =    (alignOpt.z != 0.0);\n\nfloat mod_angle(float a) {\n  return mod(a, PI);\n}\n\nfloat positive_angle(float a) {\n  return mod_angle((a < 0.0) ?\n    a + TWO_PI :\n    a\n  );\n}\n\nfloat look_upwards(float a) {\n  float b = positive_angle(a);\n  return ((b > HALF_PI) && (b <= ONE_AND_HALF_PI)) ?\n    b - PI :\n    b;\n}\n\nfloat look_horizontal_or_vertical(float a, float ratio) {\n  // ratio controls the ratio between being horizontal to (vertical + horizontal)\n  // if ratio is set to 0.5 then it is 50%, 50%.\n  // when using a higher ratio e.g. 0.75 the result would\n  // likely be more horizontal than vertical.\n\n  float b = positive_angle(a);\n\n  return\n    (b < (      ratio) * HALF_PI) ? 0.0 :\n    (b < (2.0 - ratio) * HALF_PI) ? -HALF_PI :\n    (b < (2.0 + ratio) * HALF_PI) ? 0.0 :\n    (b < (4.0 - ratio) * HALF_PI) ? HALF_PI :\n                                    0.0;\n}\n\nfloat roundTo(float a, float b) {\n  return float(b * floor((a + 0.5 * b) / b));\n}\n\nfloat look_round_n_directions(float a, int n) {\n  float b = positive_angle(a);\n  float div = TWO_PI / float(n);\n  float c = roundTo(b, div);\n  return look_upwards(c);\n}\n\nfloat applyAlignOption(float rawAngle, float delta) {\n  return\n    (option >  2) ? look_round_n_directions(rawAngle + delta, option) :       // option 3-n: round to n directions\n    (option == 2) ? look_horizontal_or_vertical(rawAngle + delta, hv_ratio) : // horizontal or vertical\n    (option == 1) ? rawAngle + delta :       // use free angle, and flip to align with one direction of the axis\n    (option == 0) ? look_upwards(rawAngle) : // use free angle, and stay upwards\n    (option ==-1) ? 0.0 :                    // useful for backward compatibility, all texts remains horizontal\n                    rawAngle;                // otherwise return back raw input angle\n}\n\nbool isAxisTitle = (axis.x == 0.0) &&\n                   (axis.y == 0.0) &&\n                   (axis.z == 0.0);\n\nvoid main() {\n  //Compute world offset\n  float axisDistance = position.z;\n  vec3 dataPosition = axisDistance * axis + offset;\n\n  float beta = angle; // i.e. user defined attributes for each tick\n\n  float axisAngle;\n  float clipAngle;\n  float flip;\n\n  if (enableAlign) {\n    axisAngle = (isAxisTitle) ? HALF_PI :\n                      computeViewAngle(dataPosition, dataPosition + axis);\n    clipAngle = computeViewAngle(dataPosition, dataPosition + alignDir);\n\n    axisAngle += (sin(axisAngle) < 0.0) ? PI : 0.0;\n    clipAngle += (sin(clipAngle) < 0.0) ? PI : 0.0;\n\n    flip = (dot(vec2(cos(axisAngle), sin(axisAngle)),\n                vec2(sin(clipAngle),-cos(clipAngle))) > 0.0) ? 1.0 : 0.0;\n\n    beta += applyAlignOption(clipAngle, flip * PI);\n  }\n\n  //Compute plane offset\n  vec2 planeCoord = position.xy * pixelScale;\n\n  mat2 planeXform = scale * mat2(\n     cos(beta), sin(beta),\n    -sin(beta), cos(beta)\n  );\n\n  vec2 viewOffset = 2.0 * planeXform * planeCoord / resolution;\n\n  //Compute clip position\n  vec3 clipPosition = project(dataPosition);\n\n  //Apply text offset in clip coordinates\n  clipPosition += vec3(viewOffset, 0.0);\n\n  //Done\n  gl_Position = vec4(clipPosition, 1.0);\n}"]),l=n(["precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n  gl_FragColor = color;\n}"]);r.text=function(t){return i(t,s,l,null,[{name:"position",type:"vec3"}])};var c=n(["#define GLSLIFY 1\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection;\nuniform vec3 enable;\nuniform vec3 bounds[2];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n\n  vec3 signAxis = sign(bounds[1] - bounds[0]);\n\n  vec3 realNormal = signAxis * normal;\n\n  if(dot(realNormal, enable) > 0.0) {\n    vec3 minRange = min(bounds[0], bounds[1]);\n    vec3 maxRange = max(bounds[0], bounds[1]);\n    vec3 nPosition = mix(minRange, maxRange, 0.5 * (position + 1.0));\n    gl_Position = projection * view * model * vec4(nPosition, 1.0);\n  } else {\n    gl_Position = vec4(0,0,0,0);\n  }\n\n  colorChannel = abs(realNormal);\n}"]),u=n(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 colors[3];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n  gl_FragColor = colorChannel.x * colors[0] +\n                 colorChannel.y * colors[1] +\n                 colorChannel.z * colors[2];\n}"]);r.bg=function(t){return i(t,c,u,null,[{name:"position",type:"vec3"},{name:"normal",type:"vec3"}])}},{"gl-shader":294,glslify:398}],231:[function(t,e,r){(function(r){"use strict";e.exports=function(t,e,r,a,s,l){var u=n(t),h=i(t,[{buffer:u,size:3}]),f=o(t);f.attributes.position.location=0;var p=new c(t,f,u,h);return p.update(e,r,a,s,l),p};var n=t("gl-buffer"),i=t("gl-vao"),a=t("vectorize-text"),o=t("./shaders").text,s=window||r.global||{},l=s.__TEXT_CACHE||{};s.__TEXT_CACHE={};function c(t,e,r,n){this.gl=t,this.shader=e,this.buffer=r,this.vao=n,this.tickOffset=this.tickCount=this.labelOffset=this.labelCount=null}var u=c.prototype,h=[0,0];u.bind=function(t,e,r,n){this.vao.bind(),this.shader.bind();var i=this.shader.uniforms;i.model=t,i.view=e,i.projection=r,i.pixelScale=n,h[0]=this.gl.drawingBufferWidth,h[1]=this.gl.drawingBufferHeight,this.shader.uniforms.resolution=h},u.unbind=function(){this.vao.unbind()},u.update=function(t,e,r,n,i){var o=[];function s(t,e,r,n,i,s){var c=l[r];c||(c=l[r]={});var u=c[e];u||(u=c[e]=function(t,e){try{return a(t,e)}catch(e){return console.warn('error vectorizing text:"'+t+'" error:',e),{cells:[],positions:[]}}}(e,{triangles:!0,font:r,textAlign:"center",textBaseline:"middle",lineSpacing:i,styletags:s}));for(var h=(n||12)/12,f=u.positions,p=u.cells,d=0,g=p.length;d<g;++d)for(var v=p[d],m=2;m>=0;--m){var y=f[v[m]];o.push(h*y[0],-h*y[1],t)}}for(var c=[0,0,0],u=[0,0,0],h=[0,0,0],f=[0,0,0],p={breaklines:!0,bolds:!0,italics:!0,subscripts:!0,superscripts:!0},d=0;d<3;++d){h[d]=o.length/3|0,s(.5*(t[0][d]+t[1][d]),e[d],r[d],12,1.25,p),f[d]=(o.length/3|0)-h[d],c[d]=o.length/3|0;for(var g=0;g<n[d].length;++g)n[d][g].text&&s(n[d][g].x,n[d][g].text,n[d][g].font||i,n[d][g].fontSize||12,1.25,p);u[d]=(o.length/3|0)-c[d]}this.buffer.update(o),this.tickOffset=c,this.tickCount=u,this.labelOffset=h,this.labelCount=f},u.drawTicks=function(t,e,r,n,i,a,o,s){this.tickCount[t]&&(this.shader.uniforms.axis=a,this.shader.uniforms.color=i,this.shader.uniforms.angle=r,this.shader.uniforms.scale=e,this.shader.uniforms.offset=n,this.shader.uniforms.alignDir=o,this.shader.uniforms.alignOpt=s,this.vao.draw(this.gl.TRIANGLES,this.tickCount[t],this.tickOffset[t]))},u.drawLabel=function(t,e,r,n,i,a,o,s){this.labelCount[t]&&(this.shader.uniforms.axis=a,this.shader.uniforms.color=i,this.shader.uniforms.angle=r,this.shader.uniforms.scale=e,this.shader.uniforms.offset=n,this.shader.uniforms.alignDir=o,this.shader.uniforms.alignOpt=s,this.vao.draw(this.gl.TRIANGLES,this.labelCount[t],this.labelOffset[t]))},u.dispose=function(){this.shader.dispose(),this.vao.dispose(),this.buffer.dispose()}}).call(this,t("_process"))},{"./shaders":230,_process:471,"gl-buffer":234,"gl-vao":316,"vectorize-text":531}],232:[function(t,e,r){"use strict";function n(t,e){var r=t+"",n=r.indexOf("."),i=0;n>=0&&(i=r.length-n-1);var a=Math.pow(10,i),o=Math.round(t*e*a),s=o+"";if(s.indexOf("e")>=0)return s;var l=o/a,c=o%a;o<0?(l=0|-Math.ceil(l),c=0|-c):(l=0|Math.floor(l),c|=0);var u=""+l;if(o<0&&(u="-"+u),i){for(var h=""+c;h.length<i;)h="0"+h;return u+"."+h}return u}r.create=function(t,e){for(var r=[],i=0;i<3;++i){for(var a=[],o=(t[0][i],t[1][i],0);o*e[i]<=t[1][i];++o)a.push({x:o*e[i],text:n(e[i],o)});for(var o=-1;o*e[i]>=t[0][i];--o)a.push({x:o*e[i],text:n(e[i],o)});r.push(a)}return r},r.equal=function(t,e){for(var r=0;r<3;++r){if(t[r].length!==e[r].length)return!1;for(var n=0;n<t[r].length;++n){var i=t[r][n],a=e[r][n];if(i.x!==a.x||i.text!==a.text||i.font!==a.font||i.fontColor!==a.fontColor||i.fontSize!==a.fontSize||i.dx!==a.dx||i.dy!==a.dy)return!1}}return!0}},{}],233:[function(t,e,r){"use strict";e.exports=function(t,e,r,l,h){var f=e.model||c,p=e.view||c,m=e.projection||c,y=e._ortho||!1,x=t.bounds,b=(h=h||a(f,p,m,x,y)).axis;o(u,p,f),o(u,m,u);for(var _=g,w=0;w<3;++w)_[w].lo=1/0,_[w].hi=-1/0,_[w].pixelsPerDataUnit=1/0;var k=n(s(u,u));s(u,u);for(var A=0;A<3;++A){var M=(A+1)%3,T=(A+2)%3,S=v;t:for(var w=0;w<2;++w){var E=[];if(b[A]<0!=!!w){S[A]=x[w][A];for(var C=0;C<2;++C){S[M]=x[C^w][M];for(var L=0;L<2;++L)S[T]=x[L^C^w][T],E.push(S.slice())}for(var z=y?5:4,C=z;C===z;++C){if(0===E.length)continue t;E=i.positive(E,k[C])}for(var C=0;C<E.length;++C)for(var T=E[C],O=d(v,u,T,r,l),L=0;L<3;++L)_[L].lo=Math.min(_[L].lo,T[L]),_[L].hi=Math.max(_[L].hi,T[L]),L!==A&&(_[L].pixelsPerDataUnit=Math.min(_[L].pixelsPerDataUnit,Math.abs(O[L])))}}}return _};var n=t("extract-frustum-planes"),i=t("split-polygon"),a=t("./lib/cube.js"),o=t("gl-mat4/multiply"),s=t("gl-mat4/transpose"),l=t("gl-vec4/transformMat4"),c=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),u=new Float32Array(16);function h(t,e,r){this.lo=t,this.hi=e,this.pixelsPerDataUnit=r}var f=[0,0,0,1],p=[0,0,0,1];function d(t,e,r,n,i){for(var a=0;a<3;++a){for(var o=f,s=p,c=0;c<3;++c)s[c]=o[c]=r[c];s[3]=o[3]=1,s[a]+=1,l(s,s,e),s[3]<0&&(t[a]=1/0),o[a]-=1,l(o,o,e),o[3]<0&&(t[a]=1/0);var u=(o[0]/o[3]-s[0]/s[3])*n,h=(o[1]/o[3]-s[1]/s[3])*i;t[a]=.25*Math.sqrt(u*u+h*h)}return t}var g=[new h(1/0,-1/0,1/0),new h(1/0,-1/0,1/0),new h(1/0,-1/0,1/0)],v=[0,0,0]},{"./lib/cube.js":228,"extract-frustum-planes":217,"gl-mat4/multiply":260,"gl-mat4/transpose":269,"gl-vec4/transformMat4":387,"split-polygon":508}],234:[function(t,e,r){"use strict";var n=t("typedarray-pool"),i=t("ndarray-ops"),a=t("ndarray"),o=["uint8","uint8_clamped","uint16","uint32","int8","int16","int32","float32"];function s(t,e,r,n,i){this.gl=t,this.type=e,this.handle=r,this.length=n,this.usage=i}var l=s.prototype;function c(t,e,r,n,i,a){var o=i.length*i.BYTES_PER_ELEMENT;if(a<0)return t.bufferData(e,i,n),o;if(o+a>r)throw new Error("gl-buffer: If resizing buffer, must not specify offset");return t.bufferSubData(e,a,i),r}function u(t,e){for(var r=n.malloc(t.length,e),i=t.length,a=0;a<i;++a)r[a]=t[a];return r}l.bind=function(){this.gl.bindBuffer(this.type,this.handle)},l.unbind=function(){this.gl.bindBuffer(this.type,null)},l.dispose=function(){this.gl.deleteBuffer(this.handle)},l.update=function(t,e){if("number"!=typeof e&&(e=-1),this.bind(),"object"==typeof t&&"undefined"!=typeof t.shape){var r=t.dtype;if(o.indexOf(r)<0&&(r="float32"),this.type===this.gl.ELEMENT_ARRAY_BUFFER)r=gl.getExtension("OES_element_index_uint")&&"uint16"!==r?"uint32":"uint16";if(r===t.dtype&&function(t,e){for(var r=1,n=e.length-1;n>=0;--n){if(e[n]!==r)return!1;r*=t[n]}return!0}(t.shape,t.stride))0===t.offset&&t.data.length===t.shape[0]?this.length=c(this.gl,this.type,this.length,this.usage,t.data,e):this.length=c(this.gl,this.type,this.length,this.usage,t.data.subarray(t.offset,t.shape[0]),e);else{var s=n.malloc(t.size,r),l=a(s,t.shape);i.assign(l,t),this.length=c(this.gl,this.type,this.length,this.usage,e<0?s:s.subarray(0,t.size),e),n.free(s)}}else if(Array.isArray(t)){var h;h=this.type===this.gl.ELEMENT_ARRAY_BUFFER?u(t,"uint16"):u(t,"float32"),this.length=c(this.gl,this.type,this.length,this.usage,e<0?h:h.subarray(0,t.length),e),n.free(h)}else if("object"==typeof t&&"number"==typeof t.length)this.length=c(this.gl,this.type,this.length,this.usage,t,e);else{if("number"!=typeof t&&void 0!==t)throw new Error("gl-buffer: Invalid data type");if(e>=0)throw new Error("gl-buffer: Cannot specify offset when resizing buffer");(t|=0)<=0&&(t=1),this.gl.bufferData(this.type,0|t,this.usage),this.length=t}},e.exports=function(t,e,r,n){if(r=r||t.ARRAY_BUFFER,n=n||t.DYNAMIC_DRAW,r!==t.ARRAY_BUFFER&&r!==t.ELEMENT_ARRAY_BUFFER)throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER");if(n!==t.DYNAMIC_DRAW&&n!==t.STATIC_DRAW&&n!==t.STREAM_DRAW)throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW");var i=t.createBuffer(),a=new s(t,r,i,0,n);return a.update(e),a}},{ndarray:439,"ndarray-ops":433,"typedarray-pool":526}],235:[function(t,e,r){"use strict";var n=t("gl-vec3"),i=function(t,e){for(var r=0;r<t.length;r++)if(t[r]>=e)return r-1;return r},a=n.create(),o=n.create(),s=function(t,e,r){return t<e?e:t>r?r:t},l=function(t,e,r,l){var c=t[0],u=t[1],h=t[2],f=r[0].length,p=r[1].length,d=r[2].length,g=i(r[0],c),v=i(r[1],u),m=i(r[2],h),y=g+1,x=v+1,b=m+1;if(l&&(g=s(g,0,f-1),y=s(y,0,f-1),v=s(v,0,p-1),x=s(x,0,p-1),m=s(m,0,d-1),b=s(b,0,d-1)),g<0||v<0||m<0||y>=f||x>=p||b>=d)return n.create();var _=(c-r[0][g])/(r[0][y]-r[0][g]),w=(u-r[1][v])/(r[1][x]-r[1][v]),k=(h-r[2][m])/(r[2][b]-r[2][m]);(_<0||_>1||isNaN(_))&&(_=0),(w<0||w>1||isNaN(w))&&(w=0),(k<0||k>1||isNaN(k))&&(k=0);var A=m*f*p,M=b*f*p,T=v*f,S=x*f,E=g,C=y,L=e[T+A+E],z=e[T+A+C],O=e[S+A+E],I=e[S+A+C],D=e[T+M+E],P=e[T+M+C],R=e[S+M+E],F=e[S+M+C],B=n.create();return n.lerp(B,L,z,_),n.lerp(a,O,I,_),n.lerp(B,B,a,w),n.lerp(a,D,P,_),n.lerp(o,R,F,_),n.lerp(a,a,o,w),n.lerp(B,B,a,k),B};e.exports=function(t,e){var r;r=t.positions?t.positions:function(t){for(var e=t[0],r=t[1],n=t[2],i=[],a=0;a<n.length;a++)for(var o=0;o<r.length;o++)for(var s=0;s<e.length;s++)i.push([n[a],r[o],e[s]]);return i}(t.meshgrid);var i=t.meshgrid,a=t.vectors,o={positions:[],vertexIntensity:[],vertexIntensityBounds:t.vertexIntensityBounds,vertexNormals:[],vectors:[],cells:[],coneOffset:t.coneOffset,colormap:t.colormap};if(0===t.positions.length)return e&&(e[0]=[0,0,0],e[1]=[0,0,0]),o;for(var s=0,c=1/0,u=-1/0,h=1/0,f=-1/0,p=1/0,d=-1/0,g=null,v=null,m=[],y=1/0,x=0;x<r.length;x++){var b,_=r[x];c=Math.min(_[0],c),u=Math.max(_[0],u),h=Math.min(_[1],h),f=Math.max(_[1],f),p=Math.min(_[2],p),d=Math.max(_[2],d),b=i?l(_,a,i,!0):a[x],n.length(b)>s&&(s=n.length(b)),x&&(y=Math.min(y,2*n.distance(g,_)/(n.length(v)+n.length(b)))),g=_,v=b,m.push(b)}var w=[c,h,p],k=[u,f,d];e&&(e[0]=w,e[1]=k),0===s&&(s=1);var A=1/s;isFinite(y)&&!isNaN(y)||(y=1),o.vectorScale=y;var M=function(t,e,r){var i=n.create();return void 0!==t&&n.set(i,t,e,r),i}(0,1,0),T=t.coneSize||.5;t.absoluteConeSize&&(T=t.absoluteConeSize*A),o.coneScale=T;x=0;for(var S=0;x<r.length;x++)for(var E=(_=r[x])[0],C=_[1],L=_[2],z=m[x],O=n.length(z)*A,I=0;I<8;I++){o.positions.push([E,C,L,S++]),o.positions.push([E,C,L,S++]),o.positions.push([E,C,L,S++]),o.positions.push([E,C,L,S++]),o.positions.push([E,C,L,S++]),o.positions.push([E,C,L,S++]),o.vectors.push(z),o.vectors.push(z),o.vectors.push(z),o.vectors.push(z),o.vectors.push(z),o.vectors.push(z),o.vertexIntensity.push(O,O,O),o.vertexIntensity.push(O,O,O),o.vertexNormals.push(M,M,M),o.vertexNormals.push(M,M,M);var D=o.positions.length;o.cells.push([D-6,D-5,D-4],[D-3,D-2,D-1])}return o},e.exports.createConeMesh=t("./lib/conemesh")},{"./lib/conemesh":236,"gl-vec3":335}],236:[function(t,e,r){"use strict";var n=t("gl-shader"),i=t("gl-buffer"),a=t("gl-vao"),o=t("gl-texture2d"),s=t("normals"),l=t("gl-mat4/multiply"),c=t("gl-mat4/invert"),u=t("ndarray"),h=t("colormap"),f=t("simplicial-complex-contour"),p=t("typedarray-pool"),d=t("./shaders"),g=d.meshShader,v=d.pickShader,m=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function y(t,e,r,n,i,a,o,s,l,c,u,h,f,p,d,g,v,y,x,b,_,w,k,A){this.gl=t,this.pixelRatio=1,this.cells=[],this.positions=[],this.intensity=[],this.texture=e,this.dirty=!0,this.triShader=r,this.pickShader=n,this.trianglePositions=i,this.triangleVectors=a,this.triangleColors=s,this.triangleNormals=c,this.triangleUVs=l,this.triangleIds=o,this.triangleVAO=u,this.triangleCount=0,this.lineWidth=1,this.edgePositions=h,this.edgeColors=p,this.edgeUVs=d,this.edgeIds=f,this.edgeVAO=g,this.edgeCount=0,this.pointPositions=v,this.pointColors=x,this.pointUVs=b,this.pointSizes=_,this.pointIds=y,this.pointVAO=w,this.pointCount=0,this.contourLineWidth=1,this.contourPositions=k,this.contourVAO=A,this.contourCount=0,this.contourColor=[0,0,0],this.contourEnable=!0,this.pickId=1,this.bounds=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]],this.clipBounds=[[-1/0,-1/0,-1/0],[1/0,1/0,1/0]],this.lightPosition=[1e5,1e5,0],this.ambientLight=.8,this.diffuseLight=.8,this.specularLight=2,this.roughness=.5,this.fresnel=1.5,this.opacity=1,this.coneScale=2,this.vectorScale=1,this.coneOffset=.25,this._model=m,this._view=m,this._projection=m,this._resolution=[1,1]}var x=y.prototype;function b(t){var e=n(t,v.vertex,v.fragment,null,v.attributes);return e.attributes.position.location=0,e.attributes.id.location=1,e.attributes.vector.location=5,e}x.isOpaque=function(){return this.opacity>=1},x.isTransparent=function(){return this.opacity<1},x.pickSlots=1,x.setPickBase=function(t){this.pickId=t},x.highlight=function(t){if(t&&this.contourEnable){for(var e=f(this.cells,this.intensity,t.intensity),r=e.cells,n=e.vertexIds,i=e.vertexWeights,a=r.length,o=p.mallocFloat32(6*a),s=0,l=0;l<a;++l)for(var c=r[l],u=0;u<2;++u){var h=c[0];2===c.length&&(h=c[u]);for(var d=n[h][0],g=n[h][1],v=i[h],m=1-v,y=this.positions[d],x=this.positions[g],b=0;b<3;++b)o[s++]=v*y[b]+m*x[b]}this.contourCount=s/3|0,this.contourPositions.update(o.subarray(0,s)),p.free(o)}else this.contourCount=0},x.update=function(t){t=t||{};var e=this.gl;this.dirty=!0,"contourEnable"in t&&(this.contourEnable=t.contourEnable),"contourColor"in t&&(this.contourColor=t.contourColor),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"lightPosition"in t&&(this.lightPosition=t.lightPosition),"opacity"in t&&(this.opacity=t.opacity),"ambient"in t&&(this.ambientLight=t.ambient),"diffuse"in t&&(this.diffuseLight=t.diffuse),"specular"in t&&(this.specularLight=t.specular),"roughness"in t&&(this.roughness=t.roughness),"fresnel"in t&&(this.fresnel=t.fresnel),void 0!==t.vectorScale&&(this.vectorScale=t.vectorScale),void 0!==t.coneScale&&(this.coneScale=t.coneScale),void 0!==t.coneOffset&&(this.coneOffset=t.coneOffset),t.texture?(this.texture.dispose(),this.texture=o(e,t.texture)):t.colormap&&(this.texture.shape=[256,256],this.texture.minFilter=e.LINEAR_MIPMAP_LINEAR,this.texture.magFilter=e.LINEAR,this.texture.setPixels(function(t){for(var e=h({colormap:t,nshades:256,format:"rgba"}),r=new Uint8Array(1024),n=0;n<256;++n){for(var i=e[n],a=0;a<3;++a)r[4*n+a]=i[a];r[4*n+3]=255*i[3]}return u(r,[256,256,4],[4,0,1])}(t.colormap)),this.texture.generateMipmap());var r=t.cells,n=t.positions,i=t.vectors;if(n&&r&&i){var a=[],l=[],c=[],f=[],p=[],d=[],g=[],v=[],m=[],y=[],x=[],b=[],_=[],w=[],k=[];this.cells=r,this.positions=n;var A=t.vertexNormals,M=t.cellNormals,T=void 0===t.vertexNormalsEpsilon?1e-6:t.vertexNormalsEpsilon,S=void 0===t.faceNormalsEpsilon?1e-6:t.faceNormalsEpsilon;t.useFacetNormals&&!M&&(M=s.faceNormals(r,n,S)),M||A||(A=s.vertexNormals(r,n,T));var E=t.vertexColors,C=t.cellColors,L=t.meshColor||[1,1,1,1],z=t.vertexUVs,O=t.vertexIntensity,I=t.cellUVs,D=t.cellIntensity,P=1/0,R=-1/0;if(!z&&!I)if(O)if(t.vertexIntensityBounds)P=+t.vertexIntensityBounds[0],R=+t.vertexIntensityBounds[1];else for(var F=0;F<O.length;++F){var B=O[F];P=Math.min(P,B),R=Math.max(R,B)}else if(D)for(F=0;F<D.length;++F){B=D[F];P=Math.min(P,B),R=Math.max(R,B)}else for(F=0;F<n.length;++F){B=n[F][2];P=Math.min(P,B),R=Math.max(R,B)}this.intensity=O||(D?function(t,e,r){for(var n=new Array(e),i=0;i<e;++i)n[i]=0;var a=t.length;for(i=0;i<a;++i)for(var o=t[i],s=0;s<o.length;++s)n[o[s]]=r[i];return n}(r,n.length,D):function(t){for(var e=t.length,r=new Array(e),n=0;n<e;++n)r[n]=t[n][2];return r}(n));var N=t.pointSizes,j=t.pointSize||1;this.bounds=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]];for(F=0;F<n.length;++F)for(var V=n[F],U=0;U<3;++U)!isNaN(V[U])&&isFinite(V[U])&&(this.bounds[0][U]=Math.min(this.bounds[0][U],V[U]),this.bounds[1][U]=Math.max(this.bounds[1][U],V[U]));var q=0,H=0,G=0;t:for(F=0;F<r.length;++F){var Y=r[F];switch(Y.length){case 1:for(V=n[X=Y[0]],U=0;U<3;++U)if(isNaN(V[U])||!isFinite(V[U]))continue t;x.push(V[0],V[1],V[2],V[3]),3===(Z=E?E[X]:C?C[F]:L).length?b.push(Z[0],Z[1],Z[2],1):b.push(Z[0],Z[1],Z[2],Z[3]),$=z?z[X]:O?[(O[X]-P)/(R-P),0]:I?I[F]:D?[(D[F]-P)/(R-P),0]:[(V[2]-P)/(R-P),0],_.push($[0],$[1]),N?w.push(N[X]):w.push(j),k.push(F),G+=1;break;case 2:for(U=0;U<2;++U){V=n[X=Y[U]];for(var W=0;W<3;++W)if(isNaN(V[W])||!isFinite(V[W]))continue t}for(U=0;U<2;++U){V=n[X=Y[U]];g.push(V[0],V[1],V[2]),3===(Z=E?E[X]:C?C[F]:L).length?v.push(Z[0],Z[1],Z[2],1):v.push(Z[0],Z[1],Z[2],Z[3]),$=z?z[X]:O?[(O[X]-P)/(R-P),0]:I?I[F]:D?[(D[F]-P)/(R-P),0]:[(V[2]-P)/(R-P),0],m.push($[0],$[1]),y.push(F)}H+=1;break;case 3:for(U=0;U<3;++U)for(V=n[X=Y[U]],W=0;W<3;++W)if(isNaN(V[W])||!isFinite(V[W]))continue t;for(U=0;U<3;++U){var X;V=n[X=Y[2-U]];a.push(V[0],V[1],V[2],V[3]);var Z,$,J,K=i[X];l.push(K[0],K[1],K[2]),3===(Z=E?E[X]:C?C[F]:L).length?c.push(Z[0],Z[1],Z[2],1):c.push(Z[0],Z[1],Z[2],Z[3]),$=z?z[X]:O?[(O[X]-P)/(R-P),0]:I?I[F]:D?[(D[F]-P)/(R-P),0]:[(V[2]-P)/(R-P),0],p.push($[0],$[1]),J=A?A[X]:M[F],f.push(J[0],J[1],J[2]),d.push(F)}q+=1}}this.pointCount=G,this.edgeCount=H,this.triangleCount=q,this.pointPositions.update(x),this.pointColors.update(b),this.pointUVs.update(_),this.pointSizes.update(w),this.pointIds.update(new Uint32Array(k)),this.edgePositions.update(g),this.edgeColors.update(v),this.edgeUVs.update(m),this.edgeIds.update(new Uint32Array(y)),this.trianglePositions.update(a),this.triangleVectors.update(l),this.triangleColors.update(c),this.triangleUVs.update(p),this.triangleNormals.update(f),this.triangleIds.update(new Uint32Array(d))}},x.drawTransparent=x.draw=function(t){t=t||{};for(var e=this.gl,r=t.model||m,n=t.view||m,i=t.projection||m,a=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],o=0;o<3;++o)a[0][o]=Math.max(a[0][o],this.clipBounds[0][o]),a[1][o]=Math.min(a[1][o],this.clipBounds[1][o]);var s={model:r,view:n,projection:i,inverseModel:m.slice(),clipBounds:a,kambient:this.ambientLight,kdiffuse:this.diffuseLight,kspecular:this.specularLight,roughness:this.roughness,fresnel:this.fresnel,eyePosition:[0,0,0],lightPosition:[0,0,0],opacity:this.opacity,vectorScale:this.vectorScale,coneScale:this.coneScale,coneOffset:this.coneOffset,contourColor:this.contourColor,texture:0};s.inverseModel=c(s.inverseModel,s.model),e.disable(e.CULL_FACE),this.texture.bind(0);var u=new Array(16);l(u,s.view,s.model),l(u,s.projection,u),c(u,u);for(o=0;o<3;++o)s.eyePosition[o]=u[12+o]/u[15];var h=u[15];for(o=0;o<3;++o)h+=this.lightPosition[o]*u[4*o+3];for(o=0;o<3;++o){for(var f=u[12+o],p=0;p<3;++p)f+=u[4*p+o]*this.lightPosition[p];s.lightPosition[o]=f/h}if(this.triangleCount>0){var d=this.triShader;d.bind(),d.uniforms=s,this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind()}},x.drawPick=function(t){t=t||{};for(var e=this.gl,r=t.model||m,n=t.view||m,i=t.projection||m,a=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],o=0;o<3;++o)a[0][o]=Math.max(a[0][o],this.clipBounds[0][o]),a[1][o]=Math.min(a[1][o],this.clipBounds[1][o]);this._model=[].slice.call(r),this._view=[].slice.call(n),this._projection=[].slice.call(i),this._resolution=[e.drawingBufferWidth,e.drawingBufferHeight];var s={model:r,view:n,projection:i,clipBounds:a,vectorScale:this.vectorScale,coneScale:this.coneScale,coneOffset:this.coneOffset,pickId:this.pickId/255},l=this.pickShader;l.bind(),l.uniforms=s,this.triangleCount>0&&(this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind()),this.edgeCount>0&&(this.edgeVAO.bind(),e.lineWidth(this.lineWidth*this.pixelRatio),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind())},x.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=t.value[0]+256*t.value[1]+65536*t.value[2],r=this.cells[e],n=this.positions[r[1]].slice(0,3);return{index:Math.floor(r[1]/48),position:n,dataCoordinate:n}},x.dispose=function(){this.texture.dispose(),this.triShader.dispose(),this.pickShader.dispose(),this.triangleVAO.dispose(),this.trianglePositions.dispose(),this.triangleVectors.dispose(),this.triangleColors.dispose(),this.triangleUVs.dispose(),this.triangleNormals.dispose(),this.triangleIds.dispose(),this.edgeVAO.dispose(),this.edgePositions.dispose(),this.edgeColors.dispose(),this.edgeUVs.dispose(),this.edgeIds.dispose(),this.pointVAO.dispose(),this.pointPositions.dispose(),this.pointColors.dispose(),this.pointUVs.dispose(),this.pointSizes.dispose(),this.pointIds.dispose(),this.contourVAO.dispose(),this.contourPositions.dispose()},e.exports=function(t,e){1===arguments.length&&(t=(e=t).gl);var r=e.triShader||function(t){var e=n(t,g.vertex,g.fragment,null,g.attributes);return e.attributes.position.location=0,e.attributes.color.location=2,e.attributes.uv.location=3,e.attributes.vector.location=5,e}(t),s=b(t),l=o(t,u(new Uint8Array([255,255,255,255]),[1,1,4]));l.generateMipmap(),l.minFilter=t.LINEAR_MIPMAP_LINEAR,l.magFilter=t.LINEAR;var c=i(t),h=i(t),f=i(t),p=i(t),d=i(t),v=i(t),m=a(t,[{buffer:c,type:t.FLOAT,size:4},{buffer:v,type:t.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:f,type:t.FLOAT,size:4},{buffer:p,type:t.FLOAT,size:2},{buffer:d,type:t.FLOAT,size:3},{buffer:h,type:t.FLOAT,size:3}]),x=i(t),_=i(t),w=i(t),k=i(t),A=a(t,[{buffer:x,type:t.FLOAT,size:3},{buffer:k,type:t.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:_,type:t.FLOAT,size:4},{buffer:w,type:t.FLOAT,size:2}]),M=i(t),T=i(t),S=i(t),E=i(t),C=i(t),L=a(t,[{buffer:M,type:t.FLOAT,size:3},{buffer:C,type:t.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:T,type:t.FLOAT,size:4},{buffer:S,type:t.FLOAT,size:2},{buffer:E,type:t.FLOAT,size:1}]),z=i(t),O=new y(t,l,r,s,c,h,v,f,p,d,m,x,k,_,w,A,M,C,T,S,E,L,z,a(t,[{buffer:z,type:t.FLOAT,size:3}]));return O.update(e),O}},{"./shaders":237,colormap:114,"gl-buffer":234,"gl-mat4/invert":258,"gl-mat4/multiply":260,"gl-shader":294,"gl-texture2d":311,"gl-vao":316,ndarray:439,normals:442,"simplicial-complex-contour":499,"typedarray-pool":526}],237:[function(t,e,r){var n=t("glslify"),i=n(["precision mediump float;\n#define GLSLIFY 1\n\nvec3 getOrthogonalVector(vec3 v) {\n  // Return up-vector for only-z vector.\n  // Return ax + by + cz = 0, a point that lies on the plane that has v as a normal and that isn't (0,0,0).\n  // From the above if-statement we have ||a|| > 0  U  ||b|| > 0.\n  // Assign z = 0, x = -b, y = a:\n  // a*-b + b*a + c*0 = -ba + ba + 0 = 0\n  if (v.x*v.x > v.z*v.z || v.y*v.y > v.z*v.z) {\n    return normalize(vec3(-v.y, v.x, 0.0));\n  } else {\n    return normalize(vec3(0.0, v.z, -v.y));\n  }\n}\n\n// Calculate the cone vertex and normal at the given index.\n//\n// The returned vertex is for a cone with its top at origin and height of 1.0,\n// pointing in the direction of the vector attribute.\n//\n// Each cone is made up of a top vertex, a center base vertex and base perimeter vertices.\n// These vertices are used to make up the triangles of the cone by the following:\n//   segment + 0 top vertex\n//   segment + 1 perimeter vertex a+1\n//   segment + 2 perimeter vertex a\n//   segment + 3 center base vertex\n//   segment + 4 perimeter vertex a\n//   segment + 5 perimeter vertex a+1\n// Where segment is the number of the radial segment * 6 and a is the angle at that radial segment.\n// To go from index to segment, floor(index / 6)\n// To go from segment to angle, 2*pi * (segment/segmentCount)\n// To go from index to segment index, index - (segment*6)\n//\nvec3 getConePosition(vec3 d, float rawIndex, float coneOffset, out vec3 normal) {\n\n  const float segmentCount = 8.0;\n\n  float index = rawIndex - floor(rawIndex /\n    (segmentCount * 6.0)) *\n    (segmentCount * 6.0);\n\n  float segment = floor(0.001 + index/6.0);\n  float segmentIndex = index - (segment*6.0);\n\n  normal = -normalize(d);\n\n  if (segmentIndex > 2.99 && segmentIndex < 3.01) {\n    return mix(vec3(0.0), -d, coneOffset);\n  }\n\n  float nextAngle = (\n    (segmentIndex > 0.99 &&  segmentIndex < 1.01) ||\n    (segmentIndex > 4.99 &&  segmentIndex < 5.01)\n  ) ? 1.0 : 0.0;\n  float angle = 2.0 * 3.14159 * ((segment + nextAngle) / segmentCount);\n\n  vec3 v1 = mix(d, vec3(0.0), coneOffset);\n  vec3 v2 = v1 - d;\n\n  vec3 u = getOrthogonalVector(d);\n  vec3 v = normalize(cross(u, d));\n\n  vec3 x = u * cos(angle) * length(d)*0.25;\n  vec3 y = v * sin(angle) * length(d)*0.25;\n  vec3 v3 = v2 + x + y;\n  if (segmentIndex < 3.0) {\n    vec3 tx = u * sin(angle);\n    vec3 ty = v * -cos(angle);\n    vec3 tangent = tx + ty;\n    normal = normalize(cross(v3 - v1, tangent));\n  }\n\n  if (segmentIndex == 0.0) {\n    return mix(d, vec3(0.0), coneOffset);\n  }\n  return v3;\n}\n\nattribute vec3 vector;\nattribute vec4 color, position;\nattribute vec2 uv;\nuniform float vectorScale;\nuniform float coneScale;\n\nuniform float coneOffset;\n\nuniform mat4 model\n           , view\n           , projection\n           , inverseModel;\nuniform vec3 eyePosition\n           , lightPosition;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data\n           , f_position;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  // Scale the vector magnitude to stay constant with\n  // model & view changes.\n  vec3 normal;\n  vec3 XYZ = getConePosition(mat3(model) * ((vectorScale * coneScale) * vector), position.w, coneOffset, normal);\n  vec4 conePosition = model * vec4(position.xyz, 1.0) + vec4(XYZ, 0.0);\n\n  //Lighting geometry parameters\n  vec4 cameraCoordinate = view * conePosition;\n  cameraCoordinate.xyz /= cameraCoordinate.w;\n  f_lightDirection = lightPosition - cameraCoordinate.xyz;\n  f_eyeDirection   = eyePosition - cameraCoordinate.xyz;\n  f_normal = normalize((vec4(normal,0.0) * inverseModel).xyz);\n\n  // vec4 m_position  = model * vec4(conePosition, 1.0);\n  vec4 t_position  = view * conePosition;\n  gl_Position      = projection * t_position;\n\n  f_color          = color;\n  f_data           = conePosition.xyz;\n  f_position       = position.xyz;\n  f_uv             = uv;\n}\n"]),a=n(["#extension GL_OES_standard_derivatives : enable\n\nprecision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution(float x, float roughness) {\n  float NdotH = max(x, 0.0001);\n  float cos2Alpha = NdotH * NdotH;\n  float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n  float roughness2 = roughness * roughness;\n  float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n  return exp(tan2Alpha / roughness2) / denom;\n}\n\nfloat cookTorranceSpecular(\n  vec3 lightDirection,\n  vec3 viewDirection,\n  vec3 surfaceNormal,\n  float roughness,\n  float fresnel) {\n\n  float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n  float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n  //Half angle vector\n  vec3 H = normalize(lightDirection + viewDirection);\n\n  //Geometric term\n  float NdotH = max(dot(surfaceNormal, H), 0.0);\n  float VdotH = max(dot(viewDirection, H), 0.000001);\n  float LdotH = max(dot(lightDirection, H), 0.000001);\n  float G1 = (2.0 * NdotH * VdotN) / VdotH;\n  float G2 = (2.0 * NdotH * LdotN) / LdotH;\n  float G = min(1.0, min(G1, G2));\n  \n  //Distribution term\n  float D = beckmannDistribution(NdotH, roughness);\n\n  //Fresnel term\n  float F = pow(1.0 - VdotN, fresnel);\n\n  //Multiply terms and done\n  return  G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n            , fresnel\n            , kambient\n            , kdiffuse\n            , kspecular\n            , opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data\n           , f_position;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n  vec3 N = normalize(f_normal);\n  vec3 L = normalize(f_lightDirection);\n  vec3 V = normalize(f_eyeDirection);\n\n  if(gl_FrontFacing) {\n    N = -N;\n  }\n\n  float specular = min(1.0, max(0.0, cookTorranceSpecular(L, V, N, roughness, fresnel)));\n  float diffuse  = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n  vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n  vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular,  1.0);\n\n  gl_FragColor = litColor * opacity;\n}\n"]),o=n(["precision mediump float;\n#define GLSLIFY 1\n\nvec3 getOrthogonalVector(vec3 v) {\n  // Return up-vector for only-z vector.\n  // Return ax + by + cz = 0, a point that lies on the plane that has v as a normal and that isn't (0,0,0).\n  // From the above if-statement we have ||a|| > 0  U  ||b|| > 0.\n  // Assign z = 0, x = -b, y = a:\n  // a*-b + b*a + c*0 = -ba + ba + 0 = 0\n  if (v.x*v.x > v.z*v.z || v.y*v.y > v.z*v.z) {\n    return normalize(vec3(-v.y, v.x, 0.0));\n  } else {\n    return normalize(vec3(0.0, v.z, -v.y));\n  }\n}\n\n// Calculate the cone vertex and normal at the given index.\n//\n// The returned vertex is for a cone with its top at origin and height of 1.0,\n// pointing in the direction of the vector attribute.\n//\n// Each cone is made up of a top vertex, a center base vertex and base perimeter vertices.\n// These vertices are used to make up the triangles of the cone by the following:\n//   segment + 0 top vertex\n//   segment + 1 perimeter vertex a+1\n//   segment + 2 perimeter vertex a\n//   segment + 3 center base vertex\n//   segment + 4 perimeter vertex a\n//   segment + 5 perimeter vertex a+1\n// Where segment is the number of the radial segment * 6 and a is the angle at that radial segment.\n// To go from index to segment, floor(index / 6)\n// To go from segment to angle, 2*pi * (segment/segmentCount)\n// To go from index to segment index, index - (segment*6)\n//\nvec3 getConePosition(vec3 d, float rawIndex, float coneOffset, out vec3 normal) {\n\n  const float segmentCount = 8.0;\n\n  float index = rawIndex - floor(rawIndex /\n    (segmentCount * 6.0)) *\n    (segmentCount * 6.0);\n\n  float segment = floor(0.001 + index/6.0);\n  float segmentIndex = index - (segment*6.0);\n\n  normal = -normalize(d);\n\n  if (segmentIndex > 2.99 && segmentIndex < 3.01) {\n    return mix(vec3(0.0), -d, coneOffset);\n  }\n\n  float nextAngle = (\n    (segmentIndex > 0.99 &&  segmentIndex < 1.01) ||\n    (segmentIndex > 4.99 &&  segmentIndex < 5.01)\n  ) ? 1.0 : 0.0;\n  float angle = 2.0 * 3.14159 * ((segment + nextAngle) / segmentCount);\n\n  vec3 v1 = mix(d, vec3(0.0), coneOffset);\n  vec3 v2 = v1 - d;\n\n  vec3 u = getOrthogonalVector(d);\n  vec3 v = normalize(cross(u, d));\n\n  vec3 x = u * cos(angle) * length(d)*0.25;\n  vec3 y = v * sin(angle) * length(d)*0.25;\n  vec3 v3 = v2 + x + y;\n  if (segmentIndex < 3.0) {\n    vec3 tx = u * sin(angle);\n    vec3 ty = v * -cos(angle);\n    vec3 tangent = tx + ty;\n    normal = normalize(cross(v3 - v1, tangent));\n  }\n\n  if (segmentIndex == 0.0) {\n    return mix(d, vec3(0.0), coneOffset);\n  }\n  return v3;\n}\n\nattribute vec3 vector;\nattribute vec4 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\n\nuniform float vectorScale;\nuniform float coneScale;\nuniform float coneOffset;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  vec3 normal;\n  vec3 XYZ = getConePosition(mat3(model) * ((vectorScale * coneScale) * vector), position.w, coneOffset, normal);\n  vec4 conePosition = model * vec4(position.xyz, 1.0) + vec4(XYZ, 0.0);\n  gl_Position = projection * view * conePosition;\n  f_id        = id;\n  f_position  = position.xyz;\n}\n"]),s=n(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3  clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n\n  gl_FragColor = vec4(pickId, f_id.xyz);\n}"]);r.meshShader={vertex:i,fragment:a,attributes:[{name:"position",type:"vec4"},{name:"normal",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"},{name:"vector",type:"vec3"}]},r.pickShader={vertex:o,fragment:s,attributes:[{name:"position",type:"vec4"},{name:"id",type:"vec4"},{name:"vector",type:"vec3"}]}},{glslify:398}],238:[function(t,e,r){e.exports={0:"NONE",1:"ONE",2:"LINE_LOOP",3:"LINE_STRIP",4:"TRIANGLES",5:"TRIANGLE_STRIP",6:"TRIANGLE_FAN",256:"DEPTH_BUFFER_BIT",512:"NEVER",513:"LESS",514:"EQUAL",515:"LEQUAL",516:"GREATER",517:"NOTEQUAL",518:"GEQUAL",519:"ALWAYS",768:"SRC_COLOR",769:"ONE_MINUS_SRC_COLOR",770:"SRC_ALPHA",771:"ONE_MINUS_SRC_ALPHA",772:"DST_ALPHA",773:"ONE_MINUS_DST_ALPHA",774:"DST_COLOR",775:"ONE_MINUS_DST_COLOR",776:"SRC_ALPHA_SATURATE",1024:"STENCIL_BUFFER_BIT",1028:"FRONT",1029:"BACK",1032:"FRONT_AND_BACK",1280:"INVALID_ENUM",1281:"INVALID_VALUE",1282:"INVALID_OPERATION",1285:"OUT_OF_MEMORY",1286:"INVALID_FRAMEBUFFER_OPERATION",2304:"CW",2305:"CCW",2849:"LINE_WIDTH",2884:"CULL_FACE",2885:"CULL_FACE_MODE",2886:"FRONT_FACE",2928:"DEPTH_RANGE",2929:"DEPTH_TEST",2930:"DEPTH_WRITEMASK",2931:"DEPTH_CLEAR_VALUE",2932:"DEPTH_FUNC",2960:"STENCIL_TEST",2961:"STENCIL_CLEAR_VALUE",2962:"STENCIL_FUNC",2963:"STENCIL_VALUE_MASK",2964:"STENCIL_FAIL",2965:"STENCIL_PASS_DEPTH_FAIL",2966:"STENCIL_PASS_DEPTH_PASS",2967:"STENCIL_REF",2968:"STENCIL_WRITEMASK",2978:"VIEWPORT",3024:"DITHER",3042:"BLEND",3088:"SCISSOR_BOX",3089:"SCISSOR_TEST",3106:"COLOR_CLEAR_VALUE",3107:"COLOR_WRITEMASK",3317:"UNPACK_ALIGNMENT",3333:"PACK_ALIGNMENT",3379:"MAX_TEXTURE_SIZE",3386:"MAX_VIEWPORT_DIMS",3408:"SUBPIXEL_BITS",3410:"RED_BITS",3411:"GREEN_BITS",3412:"BLUE_BITS",3413:"ALPHA_BITS",3414:"DEPTH_BITS",3415:"STENCIL_BITS",3553:"TEXTURE_2D",4352:"DONT_CARE",4353:"FASTEST",4354:"NICEST",5120:"BYTE",5121:"UNSIGNED_BYTE",5122:"SHORT",5123:"UNSIGNED_SHORT",5124:"INT",5125:"UNSIGNED_INT",5126:"FLOAT",5386:"INVERT",5890:"TEXTURE",6401:"STENCIL_INDEX",6402:"DEPTH_COMPONENT",6406:"ALPHA",6407:"RGB",6408:"RGBA",6409:"LUMINANCE",6410:"LUMINANCE_ALPHA",7680:"KEEP",7681:"REPLACE",7682:"INCR",7683:"DECR",7936:"VENDOR",7937:"RENDERER",7938:"VERSION",9728:"NEAREST",9729:"LINEAR",9984:"NEAREST_MIPMAP_NEAREST",9985:"LINEAR_MIPMAP_NEAREST",9986:"NEAREST_MIPMAP_LINEAR",9987:"LINEAR_MIPMAP_LINEAR",10240:"TEXTURE_MAG_FILTER",10241:"TEXTURE_MIN_FILTER",10242:"TEXTURE_WRAP_S",10243:"TEXTURE_WRAP_T",10497:"REPEAT",10752:"POLYGON_OFFSET_UNITS",16384:"COLOR_BUFFER_BIT",32769:"CONSTANT_COLOR",32770:"ONE_MINUS_CONSTANT_COLOR",32771:"CONSTANT_ALPHA",32772:"ONE_MINUS_CONSTANT_ALPHA",32773:"BLEND_COLOR",32774:"FUNC_ADD",32777:"BLEND_EQUATION_RGB",32778:"FUNC_SUBTRACT",32779:"FUNC_REVERSE_SUBTRACT",32819:"UNSIGNED_SHORT_4_4_4_4",32820:"UNSIGNED_SHORT_5_5_5_1",32823:"POLYGON_OFFSET_FILL",32824:"POLYGON_OFFSET_FACTOR",32854:"RGBA4",32855:"RGB5_A1",32873:"TEXTURE_BINDING_2D",32926:"SAMPLE_ALPHA_TO_COVERAGE",32928:"SAMPLE_COVERAGE",32936:"SAMPLE_BUFFERS",32937:"SAMPLES",32938:"SAMPLE_COVERAGE_VALUE",32939:"SAMPLE_COVERAGE_INVERT",32968:"BLEND_DST_RGB",32969:"BLEND_SRC_RGB",32970:"BLEND_DST_ALPHA",32971:"BLEND_SRC_ALPHA",33071:"CLAMP_TO_EDGE",33170:"GENERATE_MIPMAP_HINT",33189:"DEPTH_COMPONENT16",33306:"DEPTH_STENCIL_ATTACHMENT",33635:"UNSIGNED_SHORT_5_6_5",33648:"MIRRORED_REPEAT",33901:"ALIASED_POINT_SIZE_RANGE",33902:"ALIASED_LINE_WIDTH_RANGE",33984:"TEXTURE0",33985:"TEXTURE1",33986:"TEXTURE2",33987:"TEXTURE3",33988:"TEXTURE4",33989:"TEXTURE5",33990:"TEXTURE6",33991:"TEXTURE7",33992:"TEXTURE8",33993:"TEXTURE9",33994:"TEXTURE10",33995:"TEXTURE11",33996:"TEXTURE12",33997:"TEXTURE13",33998:"TEXTURE14",33999:"TEXTURE15",34000:"TEXTURE16",34001:"TEXTURE17",34002:"TEXTURE18",34003:"TEXTURE19",34004:"TEXTURE20",34005:"TEXTURE21",34006:"TEXTURE22",34007:"TEXTURE23",34008:"TEXTURE24",34009:"TEXTURE25",34010:"TEXTURE26",34011:"TEXTURE27",34012:"TEXTURE28",34013:"TEXTURE29",34014:"TEXTURE30",34015:"TEXTURE31",34016:"ACTIVE_TEXTURE",34024:"MAX_RENDERBUFFER_SIZE",34041:"DEPTH_STENCIL",34055:"INCR_WRAP",34056:"DECR_WRAP",34067:"TEXTURE_CUBE_MAP",34068:"TEXTURE_BINDING_CUBE_MAP",34069:"TEXTURE_CUBE_MAP_POSITIVE_X",34070:"TEXTURE_CUBE_MAP_NEGATIVE_X",34071:"TEXTURE_CUBE_MAP_POSITIVE_Y",34072:"TEXTURE_CUBE_MAP_NEGATIVE_Y",34073:"TEXTURE_CUBE_MAP_POSITIVE_Z",34074:"TEXTURE_CUBE_MAP_NEGATIVE_Z",34076:"MAX_CUBE_MAP_TEXTURE_SIZE",34338:"VERTEX_ATTRIB_ARRAY_ENABLED",34339:"VERTEX_ATTRIB_ARRAY_SIZE",34340:"VERTEX_ATTRIB_ARRAY_STRIDE",34341:"VERTEX_ATTRIB_ARRAY_TYPE",34342:"CURRENT_VERTEX_ATTRIB",34373:"VERTEX_ATTRIB_ARRAY_POINTER",34466:"NUM_COMPRESSED_TEXTURE_FORMATS",34467:"COMPRESSED_TEXTURE_FORMATS",34660:"BUFFER_SIZE",34661:"BUFFER_USAGE",34816:"STENCIL_BACK_FUNC",34817:"STENCIL_BACK_FAIL",34818:"STENCIL_BACK_PASS_DEPTH_FAIL",34819:"STENCIL_BACK_PASS_DEPTH_PASS",34877:"BLEND_EQUATION_ALPHA",34921:"MAX_VERTEX_ATTRIBS",34922:"VERTEX_ATTRIB_ARRAY_NORMALIZED",34930:"MAX_TEXTURE_IMAGE_UNITS",34962:"ARRAY_BUFFER",34963:"ELEMENT_ARRAY_BUFFER",34964:"ARRAY_BUFFER_BINDING",34965:"ELEMENT_ARRAY_BUFFER_BINDING",34975:"VERTEX_ATTRIB_ARRAY_BUFFER_BINDING",35040:"STREAM_DRAW",35044:"STATIC_DRAW",35048:"DYNAMIC_DRAW",35632:"FRAGMENT_SHADER",35633:"VERTEX_SHADER",35660:"MAX_VERTEX_TEXTURE_IMAGE_UNITS",35661:"MAX_COMBINED_TEXTURE_IMAGE_UNITS",35663:"SHADER_TYPE",35664:"FLOAT_VEC2",35665:"FLOAT_VEC3",35666:"FLOAT_VEC4",35667:"INT_VEC2",35668:"INT_VEC3",35669:"INT_VEC4",35670:"BOOL",35671:"BOOL_VEC2",35672:"BOOL_VEC3",35673:"BOOL_VEC4",35674:"FLOAT_MAT2",35675:"FLOAT_MAT3",35676:"FLOAT_MAT4",35678:"SAMPLER_2D",35680:"SAMPLER_CUBE",35712:"DELETE_STATUS",35713:"COMPILE_STATUS",35714:"LINK_STATUS",35715:"VALIDATE_STATUS",35716:"INFO_LOG_LENGTH",35717:"ATTACHED_SHADERS",35718:"ACTIVE_UNIFORMS",35719:"ACTIVE_UNIFORM_MAX_LENGTH",35720:"SHADER_SOURCE_LENGTH",35721:"ACTIVE_ATTRIBUTES",35722:"ACTIVE_ATTRIBUTE_MAX_LENGTH",35724:"SHADING_LANGUAGE_VERSION",35725:"CURRENT_PROGRAM",36003:"STENCIL_BACK_REF",36004:"STENCIL_BACK_VALUE_MASK",36005:"STENCIL_BACK_WRITEMASK",36006:"FRAMEBUFFER_BINDING",36007:"RENDERBUFFER_BINDING",36048:"FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE",36049:"FRAMEBUFFER_ATTACHMENT_OBJECT_NAME",36050:"FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL",36051:"FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE",36053:"FRAMEBUFFER_COMPLETE",36054:"FRAMEBUFFER_INCOMPLETE_ATTACHMENT",36055:"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT",36057:"FRAMEBUFFER_INCOMPLETE_DIMENSIONS",36061:"FRAMEBUFFER_UNSUPPORTED",36064:"COLOR_ATTACHMENT0",36096:"DEPTH_ATTACHMENT",36128:"STENCIL_ATTACHMENT",36160:"FRAMEBUFFER",36161:"RENDERBUFFER",36162:"RENDERBUFFER_WIDTH",36163:"RENDERBUFFER_HEIGHT",36164:"RENDERBUFFER_INTERNAL_FORMAT",36168:"STENCIL_INDEX8",36176:"RENDERBUFFER_RED_SIZE",36177:"RENDERBUFFER_GREEN_SIZE",36178:"RENDERBUFFER_BLUE_SIZE",36179:"RENDERBUFFER_ALPHA_SIZE",36180:"RENDERBUFFER_DEPTH_SIZE",36181:"RENDERBUFFER_STENCIL_SIZE",36194:"RGB565",36336:"LOW_FLOAT",36337:"MEDIUM_FLOAT",36338:"HIGH_FLOAT",36339:"LOW_INT",36340:"MEDIUM_INT",36341:"HIGH_INT",36346:"SHADER_COMPILER",36347:"MAX_VERTEX_UNIFORM_VECTORS",36348:"MAX_VARYING_VECTORS",36349:"MAX_FRAGMENT_UNIFORM_VECTORS",37440:"UNPACK_FLIP_Y_WEBGL",37441:"UNPACK_PREMULTIPLY_ALPHA_WEBGL",37442:"CONTEXT_LOST_WEBGL",37443:"UNPACK_COLORSPACE_CONVERSION_WEBGL",37444:"BROWSER_DEFAULT_WEBGL"}},{}],239:[function(t,e,r){var n=t("./1.0/numbers");e.exports=function(t){return n[t]}},{"./1.0/numbers":238}],240:[function(t,e,r){"use strict";e.exports=function(t){var e=t.gl,r=n(e),o=i(e,[{buffer:r,type:e.FLOAT,size:3,offset:0,stride:40},{buffer:r,type:e.FLOAT,size:4,offset:12,stride:40},{buffer:r,type:e.FLOAT,size:3,offset:28,stride:40}]),l=a(e);l.attributes.position.location=0,l.attributes.color.location=1,l.attributes.offset.location=2;var c=new s(e,r,o,l);return c.update(t),c};var n=t("gl-buffer"),i=t("gl-vao"),a=t("./shaders/index"),o=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function s(t,e,r,n){this.gl=t,this.shader=n,this.buffer=e,this.vao=r,this.pixelRatio=1,this.bounds=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]],this.clipBounds=[[-1/0,-1/0,-1/0],[1/0,1/0,1/0]],this.lineWidth=[1,1,1],this.capSize=[10,10,10],this.lineCount=[0,0,0],this.lineOffset=[0,0,0],this.opacity=1,this.hasAlpha=!1}var l=s.prototype;function c(t,e){for(var r=0;r<3;++r)t[0][r]=Math.min(t[0][r],e[r]),t[1][r]=Math.max(t[1][r],e[r])}l.isOpaque=function(){return!this.hasAlpha},l.isTransparent=function(){return this.hasAlpha},l.drawTransparent=l.draw=function(t){var e=this.gl,r=this.shader.uniforms;this.shader.bind();var n=r.view=t.view||o,i=r.projection=t.projection||o;r.model=t.model||o,r.clipBounds=this.clipBounds,r.opacity=this.opacity;var a=n[12],s=n[13],l=n[14],c=n[15],u=(t._ortho||!1?2:1)*this.pixelRatio*(i[3]*a+i[7]*s+i[11]*l+i[15]*c)/e.drawingBufferHeight;this.vao.bind();for(var h=0;h<3;++h)e.lineWidth(this.lineWidth[h]*this.pixelRatio),r.capSize=this.capSize[h]*u,this.lineCount[h]&&e.drawArrays(e.LINES,this.lineOffset[h],this.lineCount[h]);this.vao.unbind()};var u=function(){for(var t=new Array(3),e=0;e<3;++e){for(var r=[],n=1;n<=2;++n)for(var i=-1;i<=1;i+=2){var a=[0,0,0];a[(n+e)%3]=i,r.push(a)}t[e]=r}return t}();function h(t,e,r,n){for(var i=u[n],a=0;a<i.length;++a){var o=i[a];t.push(e[0],e[1],e[2],r[0],r[1],r[2],r[3],o[0],o[1],o[2])}return i.length}l.update=function(t){"lineWidth"in(t=t||{})&&(this.lineWidth=t.lineWidth,Array.isArray(this.lineWidth)||(this.lineWidth=[this.lineWidth,this.lineWidth,this.lineWidth])),"capSize"in t&&(this.capSize=t.capSize,Array.isArray(this.capSize)||(this.capSize=[this.capSize,this.capSize,this.capSize])),this.hasAlpha=!1,"opacity"in t&&(this.opacity=+t.opacity,this.opacity<1&&(this.hasAlpha=!0));var e=t.color||[[0,0,0],[0,0,0],[0,0,0]],r=t.position,n=t.error;if(Array.isArray(e[0])||(e=[e,e,e]),r&&n){var i=[],a=r.length,o=0;this.bounds=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]],this.lineCount=[0,0,0];for(var s=0;s<3;++s){this.lineOffset[s]=o;t:for(var l=0;l<a;++l){for(var u=r[l],f=0;f<3;++f)if(isNaN(u[f])||!isFinite(u[f]))continue t;var p=n[l],d=e[s];if(Array.isArray(d[0])&&(d=e[l]),3===d.length?d=[d[0],d[1],d[2],1]:4===d.length&&(d=[d[0],d[1],d[2],d[3]],!this.hasAlpha&&d[3]<1&&(this.hasAlpha=!0)),!isNaN(p[0][s])&&!isNaN(p[1][s])){var g;if(p[0][s]<0)(g=u.slice())[s]+=p[0][s],i.push(u[0],u[1],u[2],d[0],d[1],d[2],d[3],0,0,0,g[0],g[1],g[2],d[0],d[1],d[2],d[3],0,0,0),c(this.bounds,g),o+=2+h(i,g,d,s);if(p[1][s]>0)(g=u.slice())[s]+=p[1][s],i.push(u[0],u[1],u[2],d[0],d[1],d[2],d[3],0,0,0,g[0],g[1],g[2],d[0],d[1],d[2],d[3],0,0,0),c(this.bounds,g),o+=2+h(i,g,d,s)}}this.lineCount[s]=o-this.lineOffset[s]}this.buffer.update(i)}},l.dispose=function(){this.shader.dispose(),this.buffer.dispose(),this.vao.dispose()}},{"./shaders/index":241,"gl-buffer":234,"gl-vao":316}],241:[function(t,e,r){"use strict";var n=t("glslify"),i=t("gl-shader"),a=n(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, offset;\nattribute vec4 color;\nuniform mat4 model, view, projection;\nuniform float capSize;\nvarying vec4 fragColor;\nvarying vec3 fragPosition;\n\nvoid main() {\n  vec4 worldPosition  = model * vec4(position, 1.0);\n  worldPosition       = (worldPosition / worldPosition.w) + vec4(capSize * offset, 0.0);\n  gl_Position         = projection * view * worldPosition;\n  fragColor           = color;\n  fragPosition        = position;\n}"]),o=n(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform float opacity;\nvarying vec3 fragPosition;\nvarying vec4 fragColor;\n\nvoid main() {\n  if (\n    outOfRange(clipBounds[0], clipBounds[1], fragPosition) ||\n    fragColor.a * opacity == 0.\n  ) discard;\n\n  gl_FragColor = opacity * fragColor;\n}"]);e.exports=function(t){return i(t,a,o,null,[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"offset",type:"vec3"}])}},{"gl-shader":294,glslify:398}],242:[function(t,e,r){"use strict";var n=t("gl-texture2d");e.exports=function(t,e,r,n){i||(i=t.FRAMEBUFFER_UNSUPPORTED,a=t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT,o=t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS,s=t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT);var c=t.getExtension("WEBGL_draw_buffers");!l&&c&&function(t,e){var r=t.getParameter(e.MAX_COLOR_ATTACHMENTS_WEBGL);l=new Array(r+1);for(var n=0;n<=r;++n){for(var i=new Array(r),a=0;a<n;++a)i[a]=t.COLOR_ATTACHMENT0+a;for(var a=n;a<r;++a)i[a]=t.NONE;l[n]=i}}(t,c);Array.isArray(e)&&(n=r,r=0|e[1],e=0|e[0]);if("number"!=typeof e)throw new Error("gl-fbo: Missing shape parameter");var u=t.getParameter(t.MAX_RENDERBUFFER_SIZE);if(e<0||e>u||r<0||r>u)throw new Error("gl-fbo: Parameters are too large for FBO");var h=1;if("color"in(n=n||{})){if((h=Math.max(0|n.color,0))<0)throw new Error("gl-fbo: Must specify a nonnegative number of colors");if(h>1){if(!c)throw new Error("gl-fbo: Multiple draw buffer extension not supported");if(h>t.getParameter(c.MAX_COLOR_ATTACHMENTS_WEBGL))throw new Error("gl-fbo: Context does not support "+h+" draw buffers")}}var f=t.UNSIGNED_BYTE,p=t.getExtension("OES_texture_float");if(n.float&&h>0){if(!p)throw new Error("gl-fbo: Context does not support floating point textures");f=t.FLOAT}else n.preferFloat&&h>0&&p&&(f=t.FLOAT);var g=!0;"depth"in n&&(g=!!n.depth);var v=!1;"stencil"in n&&(v=!!n.stencil);return new d(t,e,r,f,h,g,v,c)};var i,a,o,s,l=null;function c(t){return[t.getParameter(t.FRAMEBUFFER_BINDING),t.getParameter(t.RENDERBUFFER_BINDING),t.getParameter(t.TEXTURE_BINDING_2D)]}function u(t,e){t.bindFramebuffer(t.FRAMEBUFFER,e[0]),t.bindRenderbuffer(t.RENDERBUFFER,e[1]),t.bindTexture(t.TEXTURE_2D,e[2])}function h(t){switch(t){case i:throw new Error("gl-fbo: Framebuffer unsupported");case a:throw new Error("gl-fbo: Framebuffer incomplete attachment");case o:throw new Error("gl-fbo: Framebuffer incomplete dimensions");case s:throw new Error("gl-fbo: Framebuffer incomplete missing attachment");default:throw new Error("gl-fbo: Framebuffer failed for unspecified reason")}}function f(t,e,r,i,a,o){if(!i)return null;var s=n(t,e,r,a,i);return s.magFilter=t.NEAREST,s.minFilter=t.NEAREST,s.mipSamples=1,s.bind(),t.framebufferTexture2D(t.FRAMEBUFFER,o,t.TEXTURE_2D,s.handle,0),s}function p(t,e,r,n,i){var a=t.createRenderbuffer();return t.bindRenderbuffer(t.RENDERBUFFER,a),t.renderbufferStorage(t.RENDERBUFFER,n,e,r),t.framebufferRenderbuffer(t.FRAMEBUFFER,i,t.RENDERBUFFER,a),a}function d(t,e,r,n,i,a,o,s){this.gl=t,this._shape=[0|e,0|r],this._destroyed=!1,this._ext=s,this.color=new Array(i);for(var d=0;d<i;++d)this.color[d]=null;this._color_rb=null,this.depth=null,this._depth_rb=null,this._colorType=n,this._useDepth=a,this._useStencil=o;var g=this,v=[0|e,0|r];Object.defineProperties(v,{0:{get:function(){return g._shape[0]},set:function(t){return g.width=t}},1:{get:function(){return g._shape[1]},set:function(t){return g.height=t}}}),this._shapeVector=v,function(t){var e=c(t.gl),r=t.gl,n=t.handle=r.createFramebuffer(),i=t._shape[0],a=t._shape[1],o=t.color.length,s=t._ext,d=t._useStencil,g=t._useDepth,v=t._colorType;r.bindFramebuffer(r.FRAMEBUFFER,n);for(var m=0;m<o;++m)t.color[m]=f(r,i,a,v,r.RGBA,r.COLOR_ATTACHMENT0+m);0===o?(t._color_rb=p(r,i,a,r.RGBA4,r.COLOR_ATTACHMENT0),s&&s.drawBuffersWEBGL(l[0])):o>1&&s.drawBuffersWEBGL(l[o]);var y=r.getExtension("WEBGL_depth_texture");y?d?t.depth=f(r,i,a,y.UNSIGNED_INT_24_8_WEBGL,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):g&&(t.depth=f(r,i,a,r.UNSIGNED_SHORT,r.DEPTH_COMPONENT,r.DEPTH_ATTACHMENT)):g&&d?t._depth_rb=p(r,i,a,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):g?t._depth_rb=p(r,i,a,r.DEPTH_COMPONENT16,r.DEPTH_ATTACHMENT):d&&(t._depth_rb=p(r,i,a,r.STENCIL_INDEX,r.STENCIL_ATTACHMENT));var x=r.checkFramebufferStatus(r.FRAMEBUFFER);if(x!==r.FRAMEBUFFER_COMPLETE){for(t._destroyed=!0,r.bindFramebuffer(r.FRAMEBUFFER,null),r.deleteFramebuffer(t.handle),t.handle=null,t.depth&&(t.depth.dispose(),t.depth=null),t._depth_rb&&(r.deleteRenderbuffer(t._depth_rb),t._depth_rb=null),m=0;m<t.color.length;++m)t.color[m].dispose(),t.color[m]=null;t._color_rb&&(r.deleteRenderbuffer(t._color_rb),t._color_rb=null),u(r,e),h(x)}u(r,e)}(this)}var g=d.prototype;function v(t,e,r){if(t._destroyed)throw new Error("gl-fbo: Can't resize destroyed FBO");if(t._shape[0]!==e||t._shape[1]!==r){var n=t.gl,i=n.getParameter(n.MAX_RENDERBUFFER_SIZE);if(e<0||e>i||r<0||r>i)throw new Error("gl-fbo: Can't resize FBO, invalid dimensions");t._shape[0]=e,t._shape[1]=r;for(var a=c(n),o=0;o<t.color.length;++o)t.color[o].shape=t._shape;t._color_rb&&(n.bindRenderbuffer(n.RENDERBUFFER,t._color_rb),n.renderbufferStorage(n.RENDERBUFFER,n.RGBA4,t._shape[0],t._shape[1])),t.depth&&(t.depth.shape=t._shape),t._depth_rb&&(n.bindRenderbuffer(n.RENDERBUFFER,t._depth_rb),t._useDepth&&t._useStencil?n.renderbufferStorage(n.RENDERBUFFER,n.DEPTH_STENCIL,t._shape[0],t._shape[1]):t._useDepth?n.renderbufferStorage(n.RENDERBUFFER,n.DEPTH_COMPONENT16,t._shape[0],t._shape[1]):t._useStencil&&n.renderbufferStorage(n.RENDERBUFFER,n.STENCIL_INDEX,t._shape[0],t._shape[1])),n.bindFramebuffer(n.FRAMEBUFFER,t.handle);var s=n.checkFramebufferStatus(n.FRAMEBUFFER);s!==n.FRAMEBUFFER_COMPLETE&&(t.dispose(),u(n,a),h(s)),u(n,a)}}Object.defineProperties(g,{shape:{get:function(){return this._destroyed?[0,0]:this._shapeVector},set:function(t){if(Array.isArray(t)||(t=[0|t,0|t]),2!==t.length)throw new Error("gl-fbo: Shape vector must be length 2");var e=0|t[0],r=0|t[1];return v(this,e,r),[e,r]},enumerable:!1},width:{get:function(){return this._destroyed?0:this._shape[0]},set:function(t){return v(this,t|=0,this._shape[1]),t},enumerable:!1},height:{get:function(){return this._destroyed?0:this._shape[1]},set:function(t){return t|=0,v(this,this._shape[0],t),t},enumerable:!1}}),g.bind=function(){if(!this._destroyed){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.handle),t.viewport(0,0,this._shape[0],this._shape[1])}},g.dispose=function(){if(!this._destroyed){this._destroyed=!0;var t=this.gl;t.deleteFramebuffer(this.handle),this.handle=null,this.depth&&(this.depth.dispose(),this.depth=null),this._depth_rb&&(t.deleteRenderbuffer(this._depth_rb),this._depth_rb=null);for(var e=0;e<this.color.length;++e)this.color[e].dispose(),this.color[e]=null;this._color_rb&&(t.deleteRenderbuffer(this._color_rb),this._color_rb=null)}}},{"gl-texture2d":311}],243:[function(t,e,r){var n=t("sprintf-js").sprintf,i=t("gl-constants/lookup"),a=t("glsl-shader-name"),o=t("add-line-numbers");e.exports=function(t,e,r){"use strict";var s=a(e)||"of unknown name (see npm glsl-shader-name)",l="unknown type";void 0!==r&&(l=r===i.FRAGMENT_SHADER?"fragment":"vertex");for(var c=n("Error compiling %s shader %s:\n",l,s),u=n("%s%s",c,t),h=t.split("\n"),f={},p=0;p<h.length;p++){var d=h[p];if(""!==d&&"\0"!==d){var g=parseInt(d.split(":")[2]);if(isNaN(g))throw new Error(n("Could not parse error: %s",d));f[g]=d}}for(var v=o(e).split("\n"),p=0;p<v.length;p++)if(f[p+3]||f[p+2]||f[p+1]){var m=v[p];if(c+=m+"\n",f[p+1]){var y=f[p+1];y=y.substr(y.split(":",3).join(":").length+1).trim(),c+=n("^^^ %s\n\n",y)}}return{long:c.trim(),short:u.trim()}}},{"add-line-numbers":49,"gl-constants/lookup":239,"glsl-shader-name":390,"sprintf-js":509}],244:[function(t,e,r){"use strict";e.exports=function(t,e){var r=t.gl,n=o(r,l.vertex,l.fragment),i=o(r,l.pickVertex,l.pickFragment),a=s(r),u=s(r),h=s(r),f=s(r),p=new c(t,n,i,a,u,h,f);return p.update(e),t.addObject(p),p};var n=t("binary-search-bounds"),i=t("iota-array"),a=t("typedarray-pool"),o=t("gl-shader"),s=t("gl-buffer"),l=t("./lib/shaders");function c(t,e,r,n,i,a,o){this.plot=t,this.shader=e,this.pickShader=r,this.positionBuffer=n,this.weightBuffer=i,this.colorBuffer=a,this.idBuffer=o,this.xData=[],this.yData=[],this.shape=[0,0],this.bounds=[1/0,1/0,-1/0,-1/0],this.pickOffset=0}var u,h=c.prototype,f=[0,0,1,0,0,1,1,0,1,1,0,1];h.draw=(u=[1,0,0,0,1,0,0,0,1],function(){var t=this.plot,e=this.shader,r=this.bounds,n=this.numVertices;if(!(n<=0)){var i=t.gl,a=t.dataBox,o=r[2]-r[0],s=r[3]-r[1],l=a[2]-a[0],c=a[3]-a[1];u[0]=2*o/l,u[4]=2*s/c,u[6]=2*(r[0]-a[0])/l-1,u[7]=2*(r[1]-a[1])/c-1,e.bind();var h=e.uniforms;h.viewTransform=u,h.shape=this.shape;var f=e.attributes;this.positionBuffer.bind(),f.position.pointer(),this.weightBuffer.bind(),f.weight.pointer(i.UNSIGNED_BYTE,!1),this.colorBuffer.bind(),f.color.pointer(i.UNSIGNED_BYTE,!0),i.drawArrays(i.TRIANGLES,0,n)}}),h.drawPick=function(){var t=[1,0,0,0,1,0,0,0,1],e=[0,0,0,0];return function(r){var n=this.plot,i=this.pickShader,a=this.bounds,o=this.numVertices;if(!(o<=0)){var s=n.gl,l=n.dataBox,c=a[2]-a[0],u=a[3]-a[1],h=l[2]-l[0],f=l[3]-l[1];t[0]=2*c/h,t[4]=2*u/f,t[6]=2*(a[0]-l[0])/h-1,t[7]=2*(a[1]-l[1])/f-1;for(var p=0;p<4;++p)e[p]=r>>8*p&255;this.pickOffset=r,i.bind();var d=i.uniforms;d.viewTransform=t,d.pickOffset=e,d.shape=this.shape;var g=i.attributes;return this.positionBuffer.bind(),g.position.pointer(),this.weightBuffer.bind(),g.weight.pointer(s.UNSIGNED_BYTE,!1),this.idBuffer.bind(),g.pickId.pointer(s.UNSIGNED_BYTE,!1),s.drawArrays(s.TRIANGLES,0,o),r+this.shape[0]*this.shape[1]}}}(),h.pick=function(t,e,r){var n=this.pickOffset,i=this.shape[0]*this.shape[1];if(r<n||r>=n+i)return null;var a=r-n,o=this.xData,s=this.yData;return{object:this,pointId:a,dataCoord:[o[a%this.shape[0]],s[a/this.shape[0]|0]]}},h.update=function(t){var e=(t=t||{}).shape||[0,0],r=t.x||i(e[0]),o=t.y||i(e[1]),s=t.z||new Float32Array(e[0]*e[1]);this.xData=r,this.yData=o;var l=t.colorLevels||[0],c=t.colorValues||[0,0,0,1],u=l.length,h=this.bounds,p=h[0]=r[0],d=h[1]=o[0],g=1/((h[2]=r[r.length-1])-p),v=1/((h[3]=o[o.length-1])-d),m=e[0],y=e[1];this.shape=[m,y];var x=(m-1)*(y-1)*(f.length>>>1);this.numVertices=x;for(var b=a.mallocUint8(4*x),_=a.mallocFloat32(2*x),w=a.mallocUint8(2*x),k=a.mallocUint32(x),A=0,M=0;M<y-1;++M)for(var T=v*(o[M]-d),S=v*(o[M+1]-d),E=0;E<m-1;++E)for(var C=g*(r[E]-p),L=g*(r[E+1]-p),z=0;z<f.length;z+=2){var O,I,D,P,R=f[z],F=f[z+1],B=s[(M+F)*m+(E+R)],N=n.le(l,B);if(N<0)O=c[0],I=c[1],D=c[2],P=c[3];else if(N===u-1)O=c[4*u-4],I=c[4*u-3],D=c[4*u-2],P=c[4*u-1];else{var j=(B-l[N])/(l[N+1]-l[N]),V=1-j,U=4*N,q=4*(N+1);O=V*c[U]+j*c[q],I=V*c[U+1]+j*c[q+1],D=V*c[U+2]+j*c[q+2],P=V*c[U+3]+j*c[q+3]}b[4*A]=255*O,b[4*A+1]=255*I,b[4*A+2]=255*D,b[4*A+3]=255*P,_[2*A]=.5*C+.5*L,_[2*A+1]=.5*T+.5*S,w[2*A]=R,w[2*A+1]=F,k[A]=M*m+E,A+=1}this.positionBuffer.update(_),this.weightBuffer.update(w),this.colorBuffer.update(b),this.idBuffer.update(k),a.free(_),a.free(b),a.free(w),a.free(k)},h.dispose=function(){this.shader.dispose(),this.pickShader.dispose(),this.positionBuffer.dispose(),this.weightBuffer.dispose(),this.colorBuffer.dispose(),this.idBuffer.dispose(),this.plot.removeObject(this)}},{"./lib/shaders":245,"binary-search-bounds":246,"gl-buffer":234,"gl-shader":294,"iota-array":405,"typedarray-pool":526}],245:[function(t,e,r){"use strict";var n=t("glslify");e.exports={fragment:n(["precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n  gl_FragColor = vec4(fragColor.rgb * fragColor.a, fragColor.a);\n}\n"]),vertex:n(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 color;\nattribute vec2 weight;\n\nuniform vec2 shape;\nuniform mat3 viewTransform;\n\nvarying vec4 fragColor;\n\nvoid main() {\n  vec3 vPosition = viewTransform * vec3( position + (weight-.5)/(shape-1.) , 1.0);\n  fragColor = color;\n  gl_Position = vec4(vPosition.xy, 0, vPosition.z);\n}\n"]),pickFragment:n(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragId;\nvarying vec2 vWeight;\n\nuniform vec2 shape;\nuniform vec4 pickOffset;\n\nvoid main() {\n  vec2 d = step(.5, vWeight);\n  vec4 id = fragId + pickOffset;\n  id.x += d.x + d.y*shape.x;\n\n  id.y += floor(id.x / 256.0);\n  id.x -= floor(id.x / 256.0) * 256.0;\n\n  id.z += floor(id.y / 256.0);\n  id.y -= floor(id.y / 256.0) * 256.0;\n\n  id.w += floor(id.z / 256.0);\n  id.z -= floor(id.z / 256.0) * 256.0;\n\n  gl_FragColor = id/255.;\n}\n"]),pickVertex:n(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 pickId;\nattribute vec2 weight;\n\nuniform vec2 shape;\nuniform mat3 viewTransform;\n\nvarying vec4 fragId;\nvarying vec2 vWeight;\n\nvoid main() {\n  vWeight = weight;\n\n  fragId = pickId;\n\n  vec3 vPosition = viewTransform * vec3( position + (weight-.5)/(shape-1.) , 1.0);\n  gl_Position = vec4(vPosition.xy, 0, vPosition.z);\n}\n"])}},{glslify:398}],246:[function(t,e,r){arguments[4][99][0].apply(r,arguments)},{dup:99}],247:[function(t,e,r){var n=t("glslify"),i=t("gl-shader"),a=n(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, nextPosition;\nattribute float arcLength, lineWidth;\nattribute vec4 color;\n\nuniform vec2 screenShape;\nuniform float pixelRatio;\nuniform mat4 model, view, projection;\n\nvarying vec4 fragColor;\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\n\nvec4 project(vec3 p) {\n  return projection * view * model * vec4(p, 1.0);\n}\n\nvoid main() {\n  vec4 startPoint = project(position);\n  vec4 endPoint   = project(nextPosition);\n\n  vec2 A = startPoint.xy / startPoint.w;\n  vec2 B =   endPoint.xy /   endPoint.w;\n\n  float clipAngle = atan(\n    (B.y - A.y) * screenShape.y,\n    (B.x - A.x) * screenShape.x\n  );\n\n  vec2 offset = 0.5 * pixelRatio * lineWidth * vec2(\n    sin(clipAngle),\n    -cos(clipAngle)\n  ) / screenShape;\n\n  gl_Position = vec4(startPoint.xy + startPoint.w * offset, startPoint.zw);\n\n  worldPosition = position;\n  pixelArcLength = arcLength;\n  fragColor = color;\n}\n"]),o=n(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3      clipBounds[2];\nuniform sampler2D dashTexture;\nuniform float     dashScale;\nuniform float     opacity;\n\nvarying vec3    worldPosition;\nvarying float   pixelArcLength;\nvarying vec4    fragColor;\n\nvoid main() {\n  if (\n    outOfRange(clipBounds[0], clipBounds[1], worldPosition) ||\n    fragColor.a * opacity == 0.\n  ) discard;\n\n  float dashWeight = texture2D(dashTexture, vec2(dashScale * pixelArcLength, 0)).r;\n  if(dashWeight < 0.5) {\n    discard;\n  }\n  gl_FragColor = fragColor * opacity;\n}\n"]),s=n(["precision mediump float;\n#define GLSLIFY 1\n\n#define FLOAT_MAX  1.70141184e38\n#define FLOAT_MIN  1.17549435e-38\n\nlowp vec4 encode_float_1540259130(highp float v) {\n  highp float av = abs(v);\n\n  //Handle special cases\n  if(av < FLOAT_MIN) {\n    return vec4(0.0, 0.0, 0.0, 0.0);\n  } else if(v > FLOAT_MAX) {\n    return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n  } else if(v < -FLOAT_MAX) {\n    return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n  }\n\n  highp vec4 c = vec4(0,0,0,0);\n\n  //Compute exponent and mantissa\n  highp float e = floor(log2(av));\n  highp float m = av * pow(2.0, -e) - 1.0;\n  \n  //Unpack mantissa\n  c[1] = floor(128.0 * m);\n  m -= c[1] / 128.0;\n  c[2] = floor(32768.0 * m);\n  m -= c[2] / 32768.0;\n  c[3] = floor(8388608.0 * m);\n  \n  //Unpack exponent\n  highp float ebias = e + 127.0;\n  c[0] = floor(ebias / 2.0);\n  ebias -= c[0] * 2.0;\n  c[1] += floor(ebias) * 128.0; \n\n  //Unpack sign bit\n  c[0] += 128.0 * step(0.0, -v);\n\n  //Scale back to range\n  return c / 255.0;\n}\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], worldPosition)) discard;\n\n  gl_FragColor = vec4(pickId/255.0, encode_float_1540259130(pixelArcLength).xyz);\n}"]),l=[{name:"position",type:"vec3"},{name:"nextPosition",type:"vec3"},{name:"arcLength",type:"float"},{name:"lineWidth",type:"float"},{name:"color",type:"vec4"}];r.createShader=function(t){return i(t,a,o,null,l)},r.createPickShader=function(t){return i(t,a,s,null,l)}},{"gl-shader":294,glslify:398}],248:[function(t,e,r){"use strict";e.exports=function(t){var e=t.gl||t.scene&&t.scene.gl,r=u(e);r.attributes.position.location=0,r.attributes.nextPosition.location=1,r.attributes.arcLength.location=2,r.attributes.lineWidth.location=3,r.attributes.color.location=4;var o=h(e);o.attributes.position.location=0,o.attributes.nextPosition.location=1,o.attributes.arcLength.location=2,o.attributes.lineWidth.location=3,o.attributes.color.location=4;for(var s=n(e),c=i(e,[{buffer:s,size:3,offset:0,stride:48},{buffer:s,size:3,offset:12,stride:48},{buffer:s,size:1,offset:24,stride:48},{buffer:s,size:1,offset:28,stride:48},{buffer:s,size:4,offset:32,stride:48}]),f=l(new Array(1024),[256,1,4]),p=0;p<1024;++p)f.data[p]=255;var d=a(e,f);d.wrap=e.REPEAT;var g=new v(e,r,o,s,c,d);return g.update(t),g};var n=t("gl-buffer"),i=t("gl-vao"),a=t("gl-texture2d"),o=t("glsl-read-float"),s=t("binary-search-bounds"),l=t("ndarray"),c=t("./lib/shaders"),u=c.createShader,h=c.createPickShader,f=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function p(t,e){for(var r=0,n=0;n<3;++n){var i=t[n]-e[n];r+=i*i}return Math.sqrt(r)}function d(t){for(var e=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],r=0;r<3;++r)e[0][r]=Math.max(t[0][r],e[0][r]),e[1][r]=Math.min(t[1][r],e[1][r]);return e}function g(t,e,r,n){this.arcLength=t,this.position=e,this.index=r,this.dataCoordinate=n}function v(t,e,r,n,i,a){this.gl=t,this.shader=e,this.pickShader=r,this.buffer=n,this.vao=i,this.clipBounds=[[-1/0,-1/0,-1/0],[1/0,1/0,1/0]],this.points=[],this.arcLength=[],this.vertexCount=0,this.bounds=[[0,0,0],[0,0,0]],this.pickId=0,this.lineWidth=1,this.texture=a,this.dashScale=1,this.opacity=1,this.hasAlpha=!1,this.dirty=!0,this.pixelRatio=1}var m=v.prototype;m.isTransparent=function(){return this.hasAlpha},m.isOpaque=function(){return!this.hasAlpha},m.pickSlots=1,m.setPickBase=function(t){this.pickId=t},m.drawTransparent=m.draw=function(t){if(this.vertexCount){var e=this.gl,r=this.shader,n=this.vao;r.bind(),r.uniforms={model:t.model||f,view:t.view||f,projection:t.projection||f,clipBounds:d(this.clipBounds),dashTexture:this.texture.bind(),dashScale:this.dashScale/this.arcLength[this.arcLength.length-1],opacity:this.opacity,screenShape:[e.drawingBufferWidth,e.drawingBufferHeight],pixelRatio:this.pixelRatio},n.bind(),n.draw(e.TRIANGLE_STRIP,this.vertexCount),n.unbind()}},m.drawPick=function(t){if(this.vertexCount){var e=this.gl,r=this.pickShader,n=this.vao;r.bind(),r.uniforms={model:t.model||f,view:t.view||f,projection:t.projection||f,pickId:this.pickId,clipBounds:d(this.clipBounds),screenShape:[e.drawingBufferWidth,e.drawingBufferHeight],pixelRatio:this.pixelRatio},n.bind(),n.draw(e.TRIANGLE_STRIP,this.vertexCount),n.unbind()}},m.update=function(t){var e,r;this.dirty=!0;var n=!!t.connectGaps;"dashScale"in t&&(this.dashScale=t.dashScale),this.hasAlpha=!1,"opacity"in t&&(this.opacity=+t.opacity,this.opacity<1&&(this.hasAlpha=!0));var i=[],a=[],o=[],c=0,u=0,h=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]],f=t.position||t.positions;if(f){var d=t.color||t.colors||[0,0,0,1],g=t.lineWidth||1,v=!1;t:for(e=1;e<f.length;++e){var m,y,x,b=f[e-1],_=f[e];for(a.push(c),o.push(b.slice()),r=0;r<3;++r){if(isNaN(b[r])||isNaN(_[r])||!isFinite(b[r])||!isFinite(_[r])){if(!n&&i.length>0){for(var w=0;w<24;++w)i.push(i[i.length-12]);u+=2,v=!0}continue t}h[0][r]=Math.min(h[0][r],b[r],_[r]),h[1][r]=Math.max(h[1][r],b[r],_[r])}Array.isArray(d[0])?(m=d.length>e-1?d[e-1]:d.length>0?d[d.length-1]:[0,0,0,1],y=d.length>e?d[e]:d.length>0?d[d.length-1]:[0,0,0,1]):m=y=d,3===m.length&&(m=[m[0],m[1],m[2],1]),3===y.length&&(y=[y[0],y[1],y[2],1]),!this.hasAlpha&&m[3]<1&&(this.hasAlpha=!0),x=Array.isArray(g)?g.length>e-1?g[e-1]:g.length>0?g[g.length-1]:[0,0,0,1]:g;var k=c;if(c+=p(b,_),v){for(r=0;r<2;++r)i.push(b[0],b[1],b[2],_[0],_[1],_[2],k,x,m[0],m[1],m[2],m[3]);u+=2,v=!1}i.push(b[0],b[1],b[2],_[0],_[1],_[2],k,x,m[0],m[1],m[2],m[3],b[0],b[1],b[2],_[0],_[1],_[2],k,-x,m[0],m[1],m[2],m[3],_[0],_[1],_[2],b[0],b[1],b[2],c,-x,y[0],y[1],y[2],y[3],_[0],_[1],_[2],b[0],b[1],b[2],c,x,y[0],y[1],y[2],y[3]),u+=4}}if(this.buffer.update(i),a.push(c),o.push(f[f.length-1].slice()),this.bounds=h,this.vertexCount=u,this.points=o,this.arcLength=a,"dashes"in t){var A=t.dashes.slice();for(A.unshift(0),e=1;e<A.length;++e)A[e]=A[e-1]+A[e];var M=l(new Array(1024),[256,1,4]);for(e=0;e<256;++e){for(r=0;r<4;++r)M.set(e,0,r,0);1&s.le(A,A[A.length-1]*e/255)?M.set(e,0,0,0):M.set(e,0,0,255)}this.texture.setPixels(M)}},m.dispose=function(){this.shader.dispose(),this.vao.dispose(),this.buffer.dispose()},m.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=o(t.value[0],t.value[1],t.value[2],0),r=s.le(this.arcLength,e);if(r<0)return null;if(r===this.arcLength.length-1)return new g(this.arcLength[this.arcLength.length-1],this.points[this.points.length-1].slice(),r);for(var n=this.points[r],i=this.points[Math.min(r+1,this.points.length-1)],a=(e-this.arcLength[r])/(this.arcLength[r+1]-this.arcLength[r]),l=1-a,c=[0,0,0],u=0;u<3;++u)c[u]=l*n[u]+a*i[u];var h=Math.min(a<.5?r:r+1,this.points.length-1);return new g(e,c,h,this.points[h])}},{"./lib/shaders":247,"binary-search-bounds":249,"gl-buffer":234,"gl-texture2d":311,"gl-vao":316,"glsl-read-float":389,ndarray:439}],249:[function(t,e,r){arguments[4][99][0].apply(r,arguments)},{dup:99}],250:[function(t,e,r){e.exports=function(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=r*a-i*n;return o?(o=1/o,t[0]=a*o,t[1]=-n*o,t[2]=-i*o,t[3]=r*o,t):null}},{}],251:[function(t,e,r){e.exports=function(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],l=e[6],c=e[7],u=e[8],h=u*o-s*c,f=-u*a+s*l,p=c*a-o*l,d=r*h+n*f+i*p;return d?(d=1/d,t[0]=h*d,t[1]=(-u*n+i*c)*d,t[2]=(s*n-i*o)*d,t[3]=f*d,t[4]=(u*r-i*l)*d,t[5]=(-s*r+i*a)*d,t[6]=p*d,t[7]=(-c*r+n*l)*d,t[8]=(o*r-n*a)*d,t):null}},{}],252:[function(t,e,r){e.exports=function(t){var e=new Float32Array(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}},{}],253:[function(t,e,r){e.exports=function(){var t=new Float32Array(16);return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}},{}],254:[function(t,e,r){e.exports=function(t){var e=t[0],r=t[1],n=t[2],i=t[3],a=t[4],o=t[5],s=t[6],l=t[7],c=t[8],u=t[9],h=t[10],f=t[11],p=t[12],d=t[13],g=t[14],v=t[15];return(e*o-r*a)*(h*v-f*g)-(e*s-n*a)*(u*v-f*d)+(e*l-i*a)*(u*g-h*d)+(r*s-n*o)*(c*v-f*p)-(r*l-i*o)*(c*g-h*p)+(n*l-i*s)*(c*d-u*p)}},{}],255:[function(t,e,r){e.exports=function(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=r+r,s=n+n,l=i+i,c=r*o,u=n*o,h=n*s,f=i*o,p=i*s,d=i*l,g=a*o,v=a*s,m=a*l;return t[0]=1-h-d,t[1]=u+m,t[2]=f-v,t[3]=0,t[4]=u-m,t[5]=1-c-d,t[6]=p+g,t[7]=0,t[8]=f+v,t[9]=p-g,t[10]=1-c-h,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}},{}],256:[function(t,e,r){e.exports=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=n+n,l=i+i,c=a+a,u=n*s,h=n*l,f=n*c,p=i*l,d=i*c,g=a*c,v=o*s,m=o*l,y=o*c;return t[0]=1-(p+g),t[1]=h+y,t[2]=f-m,t[3]=0,t[4]=h-y,t[5]=1-(u+g),t[6]=d+v,t[7]=0,t[8]=f+m,t[9]=d-v,t[10]=1-(u+p),t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}},{}],257:[function(t,e,r){e.exports=function(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}},{}],258:[function(t,e,r){e.exports=function(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],l=e[6],c=e[7],u=e[8],h=e[9],f=e[10],p=e[11],d=e[12],g=e[13],v=e[14],m=e[15],y=r*s-n*o,x=r*l-i*o,b=r*c-a*o,_=n*l-i*s,w=n*c-a*s,k=i*c-a*l,A=u*g-h*d,M=u*v-f*d,T=u*m-p*d,S=h*v-f*g,E=h*m-p*g,C=f*m-p*v,L=y*C-x*E+b*S+_*T-w*M+k*A;if(!L)return null;return L=1/L,t[0]=(s*C-l*E+c*S)*L,t[1]=(i*E-n*C-a*S)*L,t[2]=(g*k-v*w+m*_)*L,t[3]=(f*w-h*k-p*_)*L,t[4]=(l*T-o*C-c*M)*L,t[5]=(r*C-i*T+a*M)*L,t[6]=(v*b-d*k-m*x)*L,t[7]=(u*k-f*b+p*x)*L,t[8]=(o*E-s*T+c*A)*L,t[9]=(n*T-r*E-a*A)*L,t[10]=(d*w-g*b+m*y)*L,t[11]=(h*b-u*w-p*y)*L,t[12]=(s*M-o*S-l*A)*L,t[13]=(r*S-n*M+i*A)*L,t[14]=(g*x-d*_-v*y)*L,t[15]=(u*_-h*x+f*y)*L,t}},{}],259:[function(t,e,r){var n=t("./identity");e.exports=function(t,e,r,i){var a,o,s,l,c,u,h,f,p,d,g=e[0],v=e[1],m=e[2],y=i[0],x=i[1],b=i[2],_=r[0],w=r[1],k=r[2];if(Math.abs(g-_)<1e-6&&Math.abs(v-w)<1e-6&&Math.abs(m-k)<1e-6)return n(t);h=g-_,f=v-w,p=m-k,d=1/Math.sqrt(h*h+f*f+p*p),a=x*(p*=d)-b*(f*=d),o=b*(h*=d)-y*p,s=y*f-x*h,(d=Math.sqrt(a*a+o*o+s*s))?(a*=d=1/d,o*=d,s*=d):(a=0,o=0,s=0);l=f*s-p*o,c=p*a-h*s,u=h*o-f*a,(d=Math.sqrt(l*l+c*c+u*u))?(l*=d=1/d,c*=d,u*=d):(l=0,c=0,u=0);return t[0]=a,t[1]=l,t[2]=h,t[3]=0,t[4]=o,t[5]=c,t[6]=f,t[7]=0,t[8]=s,t[9]=u,t[10]=p,t[11]=0,t[12]=-(a*g+o*v+s*m),t[13]=-(l*g+c*v+u*m),t[14]=-(h*g+f*v+p*m),t[15]=1,t}},{"./identity":257}],260:[function(t,e,r){e.exports=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],l=e[5],c=e[6],u=e[7],h=e[8],f=e[9],p=e[10],d=e[11],g=e[12],v=e[13],m=e[14],y=e[15],x=r[0],b=r[1],_=r[2],w=r[3];return t[0]=x*n+b*s+_*h+w*g,t[1]=x*i+b*l+_*f+w*v,t[2]=x*a+b*c+_*p+w*m,t[3]=x*o+b*u+_*d+w*y,x=r[4],b=r[5],_=r[6],w=r[7],t[4]=x*n+b*s+_*h+w*g,t[5]=x*i+b*l+_*f+w*v,t[6]=x*a+b*c+_*p+w*m,t[7]=x*o+b*u+_*d+w*y,x=r[8],b=r[9],_=r[10],w=r[11],t[8]=x*n+b*s+_*h+w*g,t[9]=x*i+b*l+_*f+w*v,t[10]=x*a+b*c+_*p+w*m,t[11]=x*o+b*u+_*d+w*y,x=r[12],b=r[13],_=r[14],w=r[15],t[12]=x*n+b*s+_*h+w*g,t[13]=x*i+b*l+_*f+w*v,t[14]=x*a+b*c+_*p+w*m,t[15]=x*o+b*u+_*d+w*y,t}},{}],261:[function(t,e,r){e.exports=function(t,e,r,n,i,a,o){var s=1/(e-r),l=1/(n-i),c=1/(a-o);return t[0]=-2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*l,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*c,t[11]=0,t[12]=(e+r)*s,t[13]=(i+n)*l,t[14]=(o+a)*c,t[15]=1,t}},{}],262:[function(t,e,r){e.exports=function(t,e,r,n,i){var a=1/Math.tan(e/2),o=1/(n-i);return t[0]=a/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=(i+n)*o,t[11]=-1,t[12]=0,t[13]=0,t[14]=2*i*n*o,t[15]=0,t}},{}],263:[function(t,e,r){e.exports=function(t,e,r,n){var i,a,o,s,l,c,u,h,f,p,d,g,v,m,y,x,b,_,w,k,A,M,T,S,E=n[0],C=n[1],L=n[2],z=Math.sqrt(E*E+C*C+L*L);if(Math.abs(z)<1e-6)return null;E*=z=1/z,C*=z,L*=z,i=Math.sin(r),a=Math.cos(r),o=1-a,s=e[0],l=e[1],c=e[2],u=e[3],h=e[4],f=e[5],p=e[6],d=e[7],g=e[8],v=e[9],m=e[10],y=e[11],x=E*E*o+a,b=C*E*o+L*i,_=L*E*o-C*i,w=E*C*o-L*i,k=C*C*o+a,A=L*C*o+E*i,M=E*L*o+C*i,T=C*L*o-E*i,S=L*L*o+a,t[0]=s*x+h*b+g*_,t[1]=l*x+f*b+v*_,t[2]=c*x+p*b+m*_,t[3]=u*x+d*b+y*_,t[4]=s*w+h*k+g*A,t[5]=l*w+f*k+v*A,t[6]=c*w+p*k+m*A,t[7]=u*w+d*k+y*A,t[8]=s*M+h*T+g*S,t[9]=l*M+f*T+v*S,t[10]=c*M+p*T+m*S,t[11]=u*M+d*T+y*S,e!==t&&(t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]);return t}},{}],264:[function(t,e,r){e.exports=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[4],o=e[5],s=e[6],l=e[7],c=e[8],u=e[9],h=e[10],f=e[11];e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]);return t[4]=a*i+c*n,t[5]=o*i+u*n,t[6]=s*i+h*n,t[7]=l*i+f*n,t[8]=c*i-a*n,t[9]=u*i-o*n,t[10]=h*i-s*n,t[11]=f*i-l*n,t}},{}],265:[function(t,e,r){e.exports=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],l=e[3],c=e[8],u=e[9],h=e[10],f=e[11];e!==t&&(t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]);return t[0]=a*i-c*n,t[1]=o*i-u*n,t[2]=s*i-h*n,t[3]=l*i-f*n,t[8]=a*n+c*i,t[9]=o*n+u*i,t[10]=s*n+h*i,t[11]=l*n+f*i,t}},{}],266:[function(t,e,r){e.exports=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],l=e[3],c=e[4],u=e[5],h=e[6],f=e[7];e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]);return t[0]=a*i+c*n,t[1]=o*i+u*n,t[2]=s*i+h*n,t[3]=l*i+f*n,t[4]=c*i-a*n,t[5]=u*i-o*n,t[6]=h*i-s*n,t[7]=f*i-l*n,t}},{}],267:[function(t,e,r){e.exports=function(t,e,r){var n=r[0],i=r[1],a=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*a,t[9]=e[9]*a,t[10]=e[10]*a,t[11]=e[11]*a,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}},{}],268:[function(t,e,r){e.exports=function(t,e,r){var n,i,a,o,s,l,c,u,h,f,p,d,g=r[0],v=r[1],m=r[2];e===t?(t[12]=e[0]*g+e[4]*v+e[8]*m+e[12],t[13]=e[1]*g+e[5]*v+e[9]*m+e[13],t[14]=e[2]*g+e[6]*v+e[10]*m+e[14],t[15]=e[3]*g+e[7]*v+e[11]*m+e[15]):(n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],l=e[5],c=e[6],u=e[7],h=e[8],f=e[9],p=e[10],d=e[11],t[0]=n,t[1]=i,t[2]=a,t[3]=o,t[4]=s,t[5]=l,t[6]=c,t[7]=u,t[8]=h,t[9]=f,t[10]=p,t[11]=d,t[12]=n*g+s*v+h*m+e[12],t[13]=i*g+l*v+f*m+e[13],t[14]=a*g+c*v+p*m+e[14],t[15]=o*g+u*v+d*m+e[15]);return t}},{}],269:[function(t,e,r){e.exports=function(t,e){if(t===e){var r=e[1],n=e[2],i=e[3],a=e[6],o=e[7],s=e[11];t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=r,t[6]=e[9],t[7]=e[13],t[8]=n,t[9]=a,t[11]=e[14],t[12]=i,t[13]=o,t[14]=s}else t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15];return t}},{}],270:[function(t,e,r){"use strict";e.exports=function(t,e){switch(e.length){case 0:break;case 1:t[0]=1/e[0];break;case 4:n(t,e);break;case 9:i(t,e);break;case 16:a(t,e);break;default:throw new Error("currently supports matrices up to 4x4")}return t};var n=t("gl-mat2/invert"),i=t("gl-mat3/invert"),a=t("gl-mat4/invert")},{"gl-mat2/invert":250,"gl-mat3/invert":251,"gl-mat4/invert":258}],271:[function(t,e,r){"use strict";var n=t("barycentric"),i=t("polytope-closest-point/lib/closest_point_2d.js");function a(t,e){for(var r=[0,0,0,0],n=0;n<4;++n)for(var i=0;i<4;++i)r[i]+=t[4*n+i]*e[n];return r}function o(t,e,r,n,i){for(var o=a(n,a(r,a(e,[t[0],t[1],t[2],1]))),s=0;s<3;++s)o[s]/=o[3];return[.5*i[0]*(1+o[0]),.5*i[1]*(1-o[1])]}e.exports=function(t,e,r,a,s,l){if(1===t.length)return[0,t[0].slice()];for(var c=new Array(t.length),u=0;u<t.length;++u)c[u]=o(t[u],r,a,s,l);for(var h=0,f=1/0,u=0;u<c.length;++u){for(var p=0,d=0;d<2;++d)p+=Math.pow(c[u][d]-e[d],2);p<f&&(f=p,h=u)}for(var g=function(t,e){if(2===t.length){for(var r=0,a=0,o=0;o<2;++o)r+=Math.pow(e[o]-t[0][o],2),a+=Math.pow(e[o]-t[1][o],2);return r=Math.sqrt(r),a=Math.sqrt(a),r+a<1e-6?[1,0]:[a/(r+a),r/(a+r)]}if(3===t.length){var s=[0,0];return i(t[0],t[1],t[2],e,s),n(t,s)}return[]}(c,e),v=0,u=0;u<3;++u){if(g[u]<-.001||g[u]>1.0001)return null;v+=g[u]}if(Math.abs(v-1)>.001)return null;return[h,function(t,e){for(var r=[0,0,0],n=0;n<t.length;++n)for(var i=t[n],a=e[n],o=0;o<3;++o)r[o]+=a*i[o];return r}(t,g),g]}},{barycentric:61,"polytope-closest-point/lib/closest_point_2d.js":470}],272:[function(t,e,r){var n=t("glslify"),i=n(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, normal;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model\n           , view\n           , projection\n           , inverseModel;\nuniform vec3 eyePosition\n           , lightPosition;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvec4 project(vec3 p) {\n  return projection * view * model * vec4(p, 1.0);\n}\n\nvoid main() {\n  gl_Position      = project(position);\n\n  //Lighting geometry parameters\n  vec4 cameraCoordinate = view * vec4(position , 1.0);\n  cameraCoordinate.xyz /= cameraCoordinate.w;\n  f_lightDirection = lightPosition - cameraCoordinate.xyz;\n  f_eyeDirection   = eyePosition - cameraCoordinate.xyz;\n  f_normal  = normalize((vec4(normal,0) * inverseModel).xyz);\n\n  f_color          = color;\n  f_data           = position;\n  f_uv             = uv;\n}\n"]),a=n(["#extension GL_OES_standard_derivatives : enable\n\nprecision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution(float x, float roughness) {\n  float NdotH = max(x, 0.0001);\n  float cos2Alpha = NdotH * NdotH;\n  float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n  float roughness2 = roughness * roughness;\n  float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n  return exp(tan2Alpha / roughness2) / denom;\n}\n\nfloat cookTorranceSpecular(\n  vec3 lightDirection,\n  vec3 viewDirection,\n  vec3 surfaceNormal,\n  float roughness,\n  float fresnel) {\n\n  float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n  float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n  //Half angle vector\n  vec3 H = normalize(lightDirection + viewDirection);\n\n  //Geometric term\n  float NdotH = max(dot(surfaceNormal, H), 0.0);\n  float VdotH = max(dot(viewDirection, H), 0.000001);\n  float LdotH = max(dot(lightDirection, H), 0.000001);\n  float G1 = (2.0 * NdotH * VdotN) / VdotH;\n  float G2 = (2.0 * NdotH * LdotN) / LdotH;\n  float G = min(1.0, min(G1, G2));\n  \n  //Distribution term\n  float D = beckmannDistribution(NdotH, roughness);\n\n  //Fresnel term\n  float F = pow(1.0 - VdotN, fresnel);\n\n  //Multiply terms and done\n  return  G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\n//#pragma glslify: beckmann = require(glsl-specular-beckmann) // used in gl-surface3d\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n            , fresnel\n            , kambient\n            , kdiffuse\n            , kspecular\n            , opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_data)) discard;\n\n  vec3 N = normalize(f_normal);\n  vec3 L = normalize(f_lightDirection);\n  vec3 V = normalize(f_eyeDirection);\n\n  if(gl_FrontFacing) {\n    N = -N;\n  }\n\n  float specular = min(1.0, max(0.0, cookTorranceSpecular(L, V, N, roughness, fresnel)));\n  //float specular = max(0.0, beckmann(L, V, N, roughness)); // used in gl-surface3d\n\n  float diffuse  = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n  vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n  vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular,  1.0);\n\n  gl_FragColor = litColor * opacity;\n}\n"]),o=n(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model, view, projection;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n  gl_Position = projection * view * model * vec4(position, 1.0);\n  f_color = color;\n  f_data  = position;\n  f_uv    = uv;\n}"]),s=n(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_data)) discard;\n\n  gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}"]),l=n(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\nattribute float pointSize;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    gl_Position = projection * view * model * vec4(position, 1.0);\n  }\n  gl_PointSize = pointSize;\n  f_color = color;\n  f_uv = uv;\n}"]),c=n(["precision mediump float;\n#define GLSLIFY 1\n\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  vec2 pointR = gl_PointCoord.xy - vec2(0.5,0.5);\n  if(dot(pointR, pointR) > 0.25) {\n    discard;\n  }\n  gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}"]),u=n(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  gl_Position = projection * view * model * vec4(position, 1.0);\n  f_id        = id;\n  f_position  = position;\n}"]),h=n(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3  clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n\n  gl_FragColor = vec4(pickId, f_id.xyz);\n}"]),f=n(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3  position;\nattribute float pointSize;\nattribute vec4  id;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    gl_Position  = projection * view * model * vec4(position, 1.0);\n    gl_PointSize = pointSize;\n  }\n  f_id         = id;\n  f_position   = position;\n}"]),p=n(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\n\nvoid main() {\n  gl_Position = projection * view * model * vec4(position, 1.0);\n}"]),d=n(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n  gl_FragColor = vec4(contourColor,1);\n}\n"]);r.meshShader={vertex:i,fragment:a,attributes:[{name:"position",type:"vec3"},{name:"normal",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"}]},r.wireShader={vertex:o,fragment:s,attributes:[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"}]},r.pointShader={vertex:l,fragment:c,attributes:[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"},{name:"pointSize",type:"float"}]},r.pickShader={vertex:u,fragment:h,attributes:[{name:"position",type:"vec3"},{name:"id",type:"vec4"}]},r.pointPickShader={vertex:f,fragment:h,attributes:[{name:"position",type:"vec3"},{name:"pointSize",type:"float"},{name:"id",type:"vec4"}]},r.contourShader={vertex:p,fragment:d,attributes:[{name:"position",type:"vec3"}]}},{glslify:398}],273:[function(t,e,r){"use strict";var n=t("gl-shader"),i=t("gl-buffer"),a=t("gl-vao"),o=t("gl-texture2d"),s=t("normals"),l=t("gl-mat4/multiply"),c=t("gl-mat4/invert"),u=t("ndarray"),h=t("colormap"),f=t("simplicial-complex-contour"),p=t("typedarray-pool"),d=t("./lib/shaders"),g=t("./lib/closest-point"),v=d.meshShader,m=d.wireShader,y=d.pointShader,x=d.pickShader,b=d.pointPickShader,_=d.contourShader,w=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function k(t,e,r,n,i,a,o,s,l,c,u,h,f,p,d,g,v,m,y,x,b,_,k,A,M,T,S){this.gl=t,this.pixelRatio=1,this.cells=[],this.positions=[],this.intensity=[],this.texture=e,this.dirty=!0,this.triShader=r,this.lineShader=n,this.pointShader=i,this.pickShader=a,this.pointPickShader=o,this.contourShader=s,this.trianglePositions=l,this.triangleColors=u,this.triangleNormals=f,this.triangleUVs=h,this.triangleIds=c,this.triangleVAO=p,this.triangleCount=0,this.lineWidth=1,this.edgePositions=d,this.edgeColors=v,this.edgeUVs=m,this.edgeIds=g,this.edgeVAO=y,this.edgeCount=0,this.pointPositions=x,this.pointColors=_,this.pointUVs=k,this.pointSizes=A,this.pointIds=b,this.pointVAO=M,this.pointCount=0,this.contourLineWidth=1,this.contourPositions=T,this.contourVAO=S,this.contourCount=0,this.contourColor=[0,0,0],this.contourEnable=!0,this.pickId=1,this.bounds=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]],this.clipBounds=[[-1/0,-1/0,-1/0],[1/0,1/0,1/0]],this.lightPosition=[1e5,1e5,0],this.ambientLight=.8,this.diffuseLight=.8,this.specularLight=2,this.roughness=.5,this.fresnel=1.5,this.opacity=1,this._model=w,this._view=w,this._projection=w,this._resolution=[1,1]}var A=k.prototype;function M(t){var e=n(t,y.vertex,y.fragment);return e.attributes.position.location=0,e.attributes.color.location=2,e.attributes.uv.location=3,e.attributes.pointSize.location=4,e}function T(t){var e=n(t,x.vertex,x.fragment);return e.attributes.position.location=0,e.attributes.id.location=1,e}function S(t){var e=n(t,b.vertex,b.fragment);return e.attributes.position.location=0,e.attributes.id.location=1,e.attributes.pointSize.location=4,e}function E(t){var e=n(t,_.vertex,_.fragment);return e.attributes.position.location=0,e}A.isOpaque=function(){return this.opacity>=1},A.isTransparent=function(){return this.opacity<1},A.pickSlots=1,A.setPickBase=function(t){this.pickId=t},A.highlight=function(t){if(t&&this.contourEnable){for(var e=f(this.cells,this.intensity,t.intensity),r=e.cells,n=e.vertexIds,i=e.vertexWeights,a=r.length,o=p.mallocFloat32(6*a),s=0,l=0;l<a;++l)for(var c=r[l],u=0;u<2;++u){var h=c[0];2===c.length&&(h=c[u]);for(var d=n[h][0],g=n[h][1],v=i[h],m=1-v,y=this.positions[d],x=this.positions[g],b=0;b<3;++b)o[s++]=v*y[b]+m*x[b]}this.contourCount=s/3|0,this.contourPositions.update(o.subarray(0,s)),p.free(o)}else this.contourCount=0},A.update=function(t){t=t||{};var e=this.gl;this.dirty=!0,"contourEnable"in t&&(this.contourEnable=t.contourEnable),"contourColor"in t&&(this.contourColor=t.contourColor),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"lightPosition"in t&&(this.lightPosition=t.lightPosition),"opacity"in t&&(this.opacity=t.opacity),"ambient"in t&&(this.ambientLight=t.ambient),"diffuse"in t&&(this.diffuseLight=t.diffuse),"specular"in t&&(this.specularLight=t.specular),"roughness"in t&&(this.roughness=t.roughness),"fresnel"in t&&(this.fresnel=t.fresnel),t.texture?(this.texture.dispose(),this.texture=o(e,t.texture)):t.colormap&&(this.texture.shape=[256,256],this.texture.minFilter=e.LINEAR_MIPMAP_LINEAR,this.texture.magFilter=e.LINEAR,this.texture.setPixels(function(t){for(var e=h({colormap:t,nshades:256,format:"rgba"}),r=new Uint8Array(1024),n=0;n<256;++n){for(var i=e[n],a=0;a<3;++a)r[4*n+a]=i[a];r[4*n+3]=255*i[3]}return u(r,[256,256,4],[4,0,1])}(t.colormap)),this.texture.generateMipmap());var r=t.cells,n=t.positions;if(n&&r){var i=[],a=[],l=[],c=[],f=[],p=[],d=[],g=[],v=[],m=[],y=[],x=[],b=[],_=[];this.cells=r,this.positions=n;var w=t.vertexNormals,k=t.cellNormals,A=void 0===t.vertexNormalsEpsilon?1e-6:t.vertexNormalsEpsilon,M=void 0===t.faceNormalsEpsilon?1e-6:t.faceNormalsEpsilon;t.useFacetNormals&&!k&&(k=s.faceNormals(r,n,M)),k||w||(w=s.vertexNormals(r,n,A));var T=t.vertexColors,S=t.cellColors,E=t.meshColor||[1,1,1,1],C=t.vertexUVs,L=t.vertexIntensity,z=t.cellUVs,O=t.cellIntensity,I=1/0,D=-1/0;if(!C&&!z)if(L)if(t.vertexIntensityBounds)I=+t.vertexIntensityBounds[0],D=+t.vertexIntensityBounds[1];else for(var P=0;P<L.length;++P){var R=L[P];I=Math.min(I,R),D=Math.max(D,R)}else if(O)for(P=0;P<O.length;++P){R=O[P];I=Math.min(I,R),D=Math.max(D,R)}else for(P=0;P<n.length;++P){R=n[P][2];I=Math.min(I,R),D=Math.max(D,R)}this.intensity=L||(O?function(t,e,r){for(var n=new Array(e),i=0;i<e;++i)n[i]=0;var a=t.length;for(i=0;i<a;++i)for(var o=t[i],s=0;s<o.length;++s)n[o[s]]=r[i];return n}(r,n.length,O):function(t){for(var e=t.length,r=new Array(e),n=0;n<e;++n)r[n]=t[n][2];return r}(n));var F=t.pointSizes,B=t.pointSize||1;this.bounds=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]];for(P=0;P<n.length;++P)for(var N=n[P],j=0;j<3;++j)!isNaN(N[j])&&isFinite(N[j])&&(this.bounds[0][j]=Math.min(this.bounds[0][j],N[j]),this.bounds[1][j]=Math.max(this.bounds[1][j],N[j]));var V=0,U=0,q=0;t:for(P=0;P<r.length;++P){var H=r[P];switch(H.length){case 1:for(N=n[Y=H[0]],j=0;j<3;++j)if(isNaN(N[j])||!isFinite(N[j]))continue t;m.push(N[0],N[1],N[2]),3===(W=T?T[Y]:S?S[P]:E).length?y.push(W[0],W[1],W[2],1):y.push(W[0],W[1],W[2],W[3]),X=C?C[Y]:L?[(L[Y]-I)/(D-I),0]:z?z[P]:O?[(O[P]-I)/(D-I),0]:[(N[2]-I)/(D-I),0],x.push(X[0],X[1]),F?b.push(F[Y]):b.push(B),_.push(P),q+=1;break;case 2:for(j=0;j<2;++j){N=n[Y=H[j]];for(var G=0;G<3;++G)if(isNaN(N[G])||!isFinite(N[G]))continue t}for(j=0;j<2;++j){N=n[Y=H[j]];p.push(N[0],N[1],N[2]),3===(W=T?T[Y]:S?S[P]:E).length?d.push(W[0],W[1],W[2],1):d.push(W[0],W[1],W[2],W[3]),X=C?C[Y]:L?[(L[Y]-I)/(D-I),0]:z?z[P]:O?[(O[P]-I)/(D-I),0]:[(N[2]-I)/(D-I),0],g.push(X[0],X[1]),v.push(P)}U+=1;break;case 3:for(j=0;j<3;++j)for(N=n[Y=H[j]],G=0;G<3;++G)if(isNaN(N[G])||!isFinite(N[G]))continue t;for(j=0;j<3;++j){var Y,W,X,Z;N=n[Y=H[2-j]];i.push(N[0],N[1],N[2]),3===(W=T?T[Y]:S?S[P]:E).length?a.push(W[0],W[1],W[2],1):a.push(W[0],W[1],W[2],W[3]),X=C?C[Y]:L?[(L[Y]-I)/(D-I),0]:z?z[P]:O?[(O[P]-I)/(D-I),0]:[(N[2]-I)/(D-I),0],c.push(X[0],X[1]),Z=w?w[Y]:k[P],l.push(Z[0],Z[1],Z[2]),f.push(P)}V+=1}}this.pointCount=q,this.edgeCount=U,this.triangleCount=V,this.pointPositions.update(m),this.pointColors.update(y),this.pointUVs.update(x),this.pointSizes.update(b),this.pointIds.update(new Uint32Array(_)),this.edgePositions.update(p),this.edgeColors.update(d),this.edgeUVs.update(g),this.edgeIds.update(new Uint32Array(v)),this.trianglePositions.update(i),this.triangleColors.update(a),this.triangleUVs.update(c),this.triangleNormals.update(l),this.triangleIds.update(new Uint32Array(f))}},A.drawTransparent=A.draw=function(t){t=t||{};for(var e=this.gl,r=t.model||w,n=t.view||w,i=t.projection||w,a=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],o=0;o<3;++o)a[0][o]=Math.max(a[0][o],this.clipBounds[0][o]),a[1][o]=Math.min(a[1][o],this.clipBounds[1][o]);var s={model:r,view:n,projection:i,inverseModel:w.slice(),clipBounds:a,kambient:this.ambientLight,kdiffuse:this.diffuseLight,kspecular:this.specularLight,roughness:this.roughness,fresnel:this.fresnel,eyePosition:[0,0,0],lightPosition:[0,0,0],opacity:this.opacity,contourColor:this.contourColor,texture:0};s.inverseModel=c(s.inverseModel,s.model),e.disable(e.CULL_FACE),this.texture.bind(0);var u=new Array(16);l(u,s.view,s.model),l(u,s.projection,u),c(u,u);for(o=0;o<3;++o)s.eyePosition[o]=u[12+o]/u[15];var h,f=u[15];for(o=0;o<3;++o)f+=this.lightPosition[o]*u[4*o+3];for(o=0;o<3;++o){for(var p=u[12+o],d=0;d<3;++d)p+=u[4*d+o]*this.lightPosition[d];s.lightPosition[o]=p/f}this.triangleCount>0&&((h=this.triShader).bind(),h.uniforms=s,this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind());this.edgeCount>0&&this.lineWidth>0&&((h=this.lineShader).bind(),h.uniforms=s,this.edgeVAO.bind(),e.lineWidth(this.lineWidth*this.pixelRatio),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind());this.pointCount>0&&((h=this.pointShader).bind(),h.uniforms=s,this.pointVAO.bind(),e.drawArrays(e.POINTS,0,this.pointCount),this.pointVAO.unbind());this.contourEnable&&this.contourCount>0&&this.contourLineWidth>0&&((h=this.contourShader).bind(),h.uniforms=s,this.contourVAO.bind(),e.drawArrays(e.LINES,0,this.contourCount),this.contourVAO.unbind())},A.drawPick=function(t){t=t||{};for(var e=this.gl,r=t.model||w,n=t.view||w,i=t.projection||w,a=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],o=0;o<3;++o)a[0][o]=Math.max(a[0][o],this.clipBounds[0][o]),a[1][o]=Math.min(a[1][o],this.clipBounds[1][o]);this._model=[].slice.call(r),this._view=[].slice.call(n),this._projection=[].slice.call(i),this._resolution=[e.drawingBufferWidth,e.drawingBufferHeight];var s,l={model:r,view:n,projection:i,clipBounds:a,pickId:this.pickId/255};((s=this.pickShader).bind(),s.uniforms=l,this.triangleCount>0&&(this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind()),this.edgeCount>0&&(this.edgeVAO.bind(),e.lineWidth(this.lineWidth*this.pixelRatio),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind()),this.pointCount>0)&&((s=this.pointPickShader).bind(),s.uniforms=l,this.pointVAO.bind(),e.drawArrays(e.POINTS,0,this.pointCount),this.pointVAO.unbind())},A.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;for(var e=t.value[0]+256*t.value[1]+65536*t.value[2],r=this.cells[e],n=this.positions,i=new Array(r.length),a=0;a<r.length;++a)i[a]=n[r[a]];var o=g(i,[t.coord[0],this._resolution[1]-t.coord[1]],this._model,this._view,this._projection,this._resolution);if(!o)return null;var s=o[2],l=0;for(a=0;a<r.length;++a)l+=s[a]*this.intensity[r[a]];return{position:o[1],index:r[o[0]],cell:r,cellId:e,intensity:l,dataCoordinate:this.positions[r[o[0]]]}},A.dispose=function(){this.texture.dispose(),this.triShader.dispose(),this.lineShader.dispose(),this.pointShader.dispose(),this.pickShader.dispose(),this.pointPickShader.dispose(),this.triangleVAO.dispose(),this.trianglePositions.dispose(),this.triangleColors.dispose(),this.triangleUVs.dispose(),this.triangleNormals.dispose(),this.triangleIds.dispose(),this.edgeVAO.dispose(),this.edgePositions.dispose(),this.edgeColors.dispose(),this.edgeUVs.dispose(),this.edgeIds.dispose(),this.pointVAO.dispose(),this.pointPositions.dispose(),this.pointColors.dispose(),this.pointUVs.dispose(),this.pointSizes.dispose(),this.pointIds.dispose(),this.contourVAO.dispose(),this.contourPositions.dispose(),this.contourShader.dispose()},e.exports=function(t,e){if(1===arguments.length&&(t=(e=t).gl),!(t.getExtension("OES_standard_derivatives")||t.getExtension("MOZ_OES_standard_derivatives")||t.getExtension("WEBKIT_OES_standard_derivatives")))throw new Error("derivatives not supported");var r=function(t){var e=n(t,v.vertex,v.fragment);return e.attributes.position.location=0,e.attributes.color.location=2,e.attributes.uv.location=3,e.attributes.normal.location=4,e}(t),s=function(t){var e=n(t,m.vertex,m.fragment);return e.attributes.position.location=0,e.attributes.color.location=2,e.attributes.uv.location=3,e}(t),l=M(t),c=T(t),h=S(t),f=E(t),p=o(t,u(new Uint8Array([255,255,255,255]),[1,1,4]));p.generateMipmap(),p.minFilter=t.LINEAR_MIPMAP_LINEAR,p.magFilter=t.LINEAR;var d=i(t),g=i(t),y=i(t),x=i(t),b=i(t),_=a(t,[{buffer:d,type:t.FLOAT,size:3},{buffer:b,type:t.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:g,type:t.FLOAT,size:4},{buffer:y,type:t.FLOAT,size:2},{buffer:x,type:t.FLOAT,size:3}]),w=i(t),A=i(t),C=i(t),L=i(t),z=a(t,[{buffer:w,type:t.FLOAT,size:3},{buffer:L,type:t.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:A,type:t.FLOAT,size:4},{buffer:C,type:t.FLOAT,size:2}]),O=i(t),I=i(t),D=i(t),P=i(t),R=i(t),F=a(t,[{buffer:O,type:t.FLOAT,size:3},{buffer:R,type:t.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:I,type:t.FLOAT,size:4},{buffer:D,type:t.FLOAT,size:2},{buffer:P,type:t.FLOAT,size:1}]),B=i(t),N=new k(t,p,r,s,l,c,h,f,d,b,g,y,x,_,w,L,A,C,z,O,R,I,D,P,F,B,a(t,[{buffer:B,type:t.FLOAT,size:3}]));return N.update(e),N}},{"./lib/closest-point":271,"./lib/shaders":272,colormap:114,"gl-buffer":234,"gl-mat4/invert":258,"gl-mat4/multiply":260,"gl-shader":294,"gl-texture2d":311,"gl-vao":316,ndarray:439,normals:442,"simplicial-complex-contour":499,"typedarray-pool":526}],274:[function(t,e,r){"use strict";e.exports=function(t){var e=t.gl,r=n(e,[0,0,0,1,1,0,1,1]),s=i(e,a.boxVert,a.lineFrag);return new o(t,r,s)};var n=t("gl-buffer"),i=t("gl-shader"),a=t("./shaders");function o(t,e,r){this.plot=t,this.vbo=e,this.shader=r}var s,l,c=o.prototype;c.bind=function(){var t=this.shader;this.vbo.bind(),this.shader.bind(),t.attributes.coord.pointer(),t.uniforms.screenBox=this.plot.screenBox},c.drawBox=(s=[0,0],l=[0,0],function(t,e,r,n,i){var a=this.plot,o=this.shader,c=a.gl;s[0]=t,s[1]=e,l[0]=r,l[1]=n,o.uniforms.lo=s,o.uniforms.hi=l,o.uniforms.color=i,c.drawArrays(c.TRIANGLE_STRIP,0,4)}),c.dispose=function(){this.vbo.dispose(),this.shader.dispose()}},{"./shaders":277,"gl-buffer":234,"gl-shader":294}],275:[function(t,e,r){"use strict";e.exports=function(t){var e=t.gl,r=n(e),a=i(e,o.gridVert,o.gridFrag),l=i(e,o.tickVert,o.gridFrag);return new s(t,r,a,l)};var n=t("gl-buffer"),i=t("gl-shader"),a=t("binary-search-bounds"),o=t("./shaders");function s(t,e,r,n){this.plot=t,this.vbo=e,this.shader=r,this.tickShader=n,this.ticks=[[],[]]}function l(t,e){return t-e}var c,u,h,f,p,d=s.prototype;d.draw=(c=[0,0],u=[0,0],h=[0,0],function(){for(var t=this.plot,e=this.vbo,r=this.shader,n=this.ticks,i=t.gl,a=t._tickBounds,o=t.dataBox,s=t.viewBox,l=t.gridLineWidth,f=t.gridLineColor,p=t.gridLineEnable,d=t.pixelRatio,g=0;g<2;++g){var v=a[g],m=a[g+2]-v,y=.5*(o[g+2]+o[g]),x=o[g+2]-o[g];u[g]=2*m/x,c[g]=2*(v-y)/x}r.bind(),e.bind(),r.attributes.dataCoord.pointer(),r.uniforms.dataShift=c,r.uniforms.dataScale=u;var b=0;for(g=0;g<2;++g){h[0]=h[1]=0,h[g]=1,r.uniforms.dataAxis=h,r.uniforms.lineWidth=l[g]/(s[g+2]-s[g])*d,r.uniforms.color=f[g];var _=6*n[g].length;p[g]&&_&&i.drawArrays(i.TRIANGLES,b,_),b+=_}}),d.drawTickMarks=function(){var t=[0,0],e=[0,0],r=[1,0],n=[0,1],i=[0,0],o=[0,0];return function(){for(var s=this.plot,c=this.vbo,u=this.tickShader,h=this.ticks,f=s.gl,p=s._tickBounds,d=s.dataBox,g=s.viewBox,v=s.pixelRatio,m=s.screenBox,y=m[2]-m[0],x=m[3]-m[1],b=g[2]-g[0],_=g[3]-g[1],w=0;w<2;++w){var k=p[w],A=p[w+2]-k,M=.5*(d[w+2]+d[w]),T=d[w+2]-d[w];e[w]=2*A/T,t[w]=2*(k-M)/T}e[0]*=b/y,t[0]*=b/y,e[1]*=_/x,t[1]*=_/x,u.bind(),c.bind(),u.attributes.dataCoord.pointer();var S=u.uniforms;S.dataShift=t,S.dataScale=e;var E=s.tickMarkLength,C=s.tickMarkWidth,L=s.tickMarkColor,z=6*h[0].length,O=Math.min(a.ge(h[0],(d[0]-p[0])/(p[2]-p[0]),l),h[0].length),I=Math.min(a.gt(h[0],(d[2]-p[0])/(p[2]-p[0]),l),h[0].length),D=0+6*O,P=6*Math.max(0,I-O),R=Math.min(a.ge(h[1],(d[1]-p[1])/(p[3]-p[1]),l),h[1].length),F=Math.min(a.gt(h[1],(d[3]-p[1])/(p[3]-p[1]),l),h[1].length),B=z+6*R,N=6*Math.max(0,F-R);i[0]=2*(g[0]-E[1])/y-1,i[1]=(g[3]+g[1])/x-1,o[0]=E[1]*v/y,o[1]=C[1]*v/x,N&&(S.color=L[1],S.tickScale=o,S.dataAxis=n,S.screenOffset=i,f.drawArrays(f.TRIANGLES,B,N)),i[0]=(g[2]+g[0])/y-1,i[1]=2*(g[1]-E[0])/x-1,o[0]=C[0]*v/y,o[1]=E[0]*v/x,P&&(S.color=L[0],S.tickScale=o,S.dataAxis=r,S.screenOffset=i,f.drawArrays(f.TRIANGLES,D,P)),i[0]=2*(g[2]+E[3])/y-1,i[1]=(g[3]+g[1])/x-1,o[0]=E[3]*v/y,o[1]=C[3]*v/x,N&&(S.color=L[3],S.tickScale=o,S.dataAxis=n,S.screenOffset=i,f.drawArrays(f.TRIANGLES,B,N)),i[0]=(g[2]+g[0])/y-1,i[1]=2*(g[3]+E[2])/x-1,o[0]=C[2]*v/y,o[1]=E[2]*v/x,P&&(S.color=L[2],S.tickScale=o,S.dataAxis=r,S.screenOffset=i,f.drawArrays(f.TRIANGLES,D,P))}}(),d.update=(f=[1,1,-1,-1,1,-1],p=[1,-1,1,1,-1,-1],function(t){for(var e=t.ticks,r=t.bounds,n=new Float32Array(18*(e[0].length+e[1].length)),i=(this.plot.zeroLineEnable,0),a=[[],[]],o=0;o<2;++o)for(var s=a[o],l=e[o],c=r[o],u=r[o+2],h=0;h<l.length;++h){var d=(l[h].x-c)/(u-c);s.push(d);for(var g=0;g<6;++g)n[i++]=d,n[i++]=f[g],n[i++]=p[g]}this.ticks=a,this.vbo.update(n)}),d.dispose=function(){this.vbo.dispose(),this.shader.dispose(),this.tickShader.dispose()}},{"./shaders":277,"binary-search-bounds":279,"gl-buffer":234,"gl-shader":294}],276:[function(t,e,r){"use strict";e.exports=function(t){var e=t.gl,r=n(e,[-1,-1,-1,1,1,-1,1,1]),s=i(e,a.lineVert,a.lineFrag);return new o(t,r,s)};var n=t("gl-buffer"),i=t("gl-shader"),a=t("./shaders");function o(t,e,r){this.plot=t,this.vbo=e,this.shader=r}var s,l,c=o.prototype;c.bind=function(){var t=this.shader;this.vbo.bind(),this.shader.bind(),t.attributes.coord.pointer(),t.uniforms.screenBox=this.plot.screenBox},c.drawLine=(s=[0,0],l=[0,0],function(t,e,r,n,i,a){var o=this.plot,c=this.shader,u=o.gl;s[0]=t,s[1]=e,l[0]=r,l[1]=n,c.uniforms.start=s,c.uniforms.end=l,c.uniforms.width=i*o.pixelRatio,c.uniforms.color=a,u.drawArrays(u.TRIANGLE_STRIP,0,4)}),c.dispose=function(){this.vbo.dispose(),this.shader.dispose()}},{"./shaders":277,"gl-buffer":234,"gl-shader":294}],277:[function(t,e,r){"use strict";var n=t("glslify"),i=n(["precision lowp float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n  gl_FragColor = vec4(color.xyz * color.w, color.w);\n}\n"]);e.exports={lineVert:n(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 start, end;\nuniform float width;\n\nvec2 perp(vec2 v) {\n  return vec2(v.y, -v.x);\n}\n\nvec2 screen(vec2 v) {\n  return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n  vec2 delta = normalize(perp(start - end));\n  vec2 offset = mix(start, end, 0.5 * (coord.y+1.0));\n  gl_Position = vec4(screen(offset + 0.5 * width * delta * coord.x), 0, 1);\n}\n"]),lineFrag:i,textVert:n(["#define GLSLIFY 1\nattribute vec3 textCoordinate;\n\nuniform vec2 dataScale, dataShift, dataAxis, screenOffset, textScale;\nuniform float angle;\n\nvoid main() {\n  float dataOffset  = textCoordinate.z;\n  vec2 glyphOffset  = textCoordinate.xy;\n  mat2 glyphMatrix = mat2(cos(angle), sin(angle), -sin(angle), cos(angle));\n  vec2 screenCoordinate = dataAxis * (dataScale * dataOffset + dataShift) +\n    glyphMatrix * glyphOffset * textScale + screenOffset;\n  gl_Position = vec4(screenCoordinate, 0, 1);\n}\n"]),textFrag:i,gridVert:n(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale;\nuniform float lineWidth;\n\nvoid main() {\n  vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n  pos += 10.0 * dataCoord.y * vec2(dataAxis.y, -dataAxis.x) + dataCoord.z * lineWidth;\n  gl_Position = vec4(pos, 0, 1);\n}\n"]),gridFrag:i,boxVert:n(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 lo, hi;\n\nvec2 screen(vec2 v) {\n  return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n  gl_Position = vec4(screen(mix(lo, hi, coord)), 0, 1);\n}\n"]),tickVert:n(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale, screenOffset, tickScale;\n\nvoid main() {\n  vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n  gl_Position = vec4(pos + tickScale*dataCoord.yz + screenOffset, 0, 1);\n}\n"])}},{glslify:398}],278:[function(t,e,r){"use strict";e.exports=function(t){var e=t.gl,r=n(e),a=i(e,s.textVert,s.textFrag);return new l(t,r,a)};var n=t("gl-buffer"),i=t("gl-shader"),a=t("text-cache"),o=t("binary-search-bounds"),s=t("./shaders");function l(t,e,r){this.plot=t,this.vbo=e,this.shader=r,this.tickOffset=[[],[]],this.tickX=[[],[]],this.labelOffset=[0,0],this.labelCount=[0,0]}var c,u,h,f,p,d,g=l.prototype;g.drawTicks=(c=[0,0],u=[0,0],h=[0,0],function(t){var e=this.plot,r=this.shader,n=this.tickX[t],i=this.tickOffset[t],a=e.gl,s=e.viewBox,l=e.dataBox,f=e.screenBox,p=e.pixelRatio,d=e.tickEnable,g=e.tickPad,v=e.tickColor,m=e.tickAngle,y=e.labelEnable,x=e.labelPad,b=e.labelColor,_=e.labelAngle,w=this.labelOffset[t],k=this.labelCount[t],A=o.lt(n,l[t]),M=o.le(n,l[t+2]);c[0]=c[1]=0,c[t]=1,u[t]=(s[2+t]+s[t])/(f[2+t]-f[t])-1;var T=2/f[2+(1^t)]-f[1^t];u[1^t]=T*s[1^t]-1,d[t]&&(u[1^t]-=T*p*g[t],A<M&&i[M]>i[A]&&(r.uniforms.dataAxis=c,r.uniforms.screenOffset=u,r.uniforms.color=v[t],r.uniforms.angle=m[t],a.drawArrays(a.TRIANGLES,i[A],i[M]-i[A]))),y[t]&&k&&(u[1^t]-=T*p*x[t],r.uniforms.dataAxis=h,r.uniforms.screenOffset=u,r.uniforms.color=b[t],r.uniforms.angle=_[t],a.drawArrays(a.TRIANGLES,w,k)),u[1^t]=T*s[2+(1^t)]-1,d[t+2]&&(u[1^t]+=T*p*g[t+2],A<M&&i[M]>i[A]&&(r.uniforms.dataAxis=c,r.uniforms.screenOffset=u,r.uniforms.color=v[t+2],r.uniforms.angle=m[t+2],a.drawArrays(a.TRIANGLES,i[A],i[M]-i[A]))),y[t+2]&&k&&(u[1^t]+=T*p*x[t+2],r.uniforms.dataAxis=h,r.uniforms.screenOffset=u,r.uniforms.color=b[t+2],r.uniforms.angle=_[t+2],a.drawArrays(a.TRIANGLES,w,k))}),g.drawTitle=function(){var t=[0,0],e=[0,0];return function(){var r=this.plot,n=this.shader,i=r.gl,a=r.screenBox,o=r.titleCenter,s=r.titleAngle,l=r.titleColor,c=r.pixelRatio;if(this.titleCount){for(var u=0;u<2;++u)e[u]=2*(o[u]*c-a[u])/(a[2+u]-a[u])-1;n.bind(),n.uniforms.dataAxis=t,n.uniforms.screenOffset=e,n.uniforms.angle=s,n.uniforms.color=l,i.drawArrays(i.TRIANGLES,this.titleOffset,this.titleCount)}}}(),g.bind=(f=[0,0],p=[0,0],d=[0,0],function(){var t=this.plot,e=this.shader,r=t._tickBounds,n=t.dataBox,i=t.screenBox,a=t.viewBox;e.bind();for(var o=0;o<2;++o){var s=r[o],l=r[o+2]-s,c=.5*(n[o+2]+n[o]),u=n[o+2]-n[o],h=a[o],g=a[o+2]-h,v=i[o],m=i[o+2]-v;p[o]=2*l/u*g/m,f[o]=2*(s-c)/u*g/m}d[1]=2*t.pixelRatio/(i[3]-i[1]),d[0]=d[1]*(i[3]-i[1])/(i[2]-i[0]),e.uniforms.dataScale=p,e.uniforms.dataShift=f,e.uniforms.textScale=d,this.vbo.bind(),e.attributes.textCoordinate.pointer()}),g.update=function(t){var e,r,n,i,o,s=[],l=t.ticks,c=t.bounds;for(o=0;o<2;++o){var u=[Math.floor(s.length/3)],h=[-1/0],f=l[o];for(e=0;e<f.length;++e){var p=f[e],d=p.x,g=p.text,v=p.font||"sans-serif";i=p.fontSize||12;for(var m=1/(c[o+2]-c[o]),y=c[o],x=g.split("\n"),b=0;b<x.length;b++)for(n=a(v,x[b]).data,r=0;r<n.length;r+=2)s.push(n[r]*i,-n[r+1]*i-b*i*1.2,(d-y)*m);u.push(Math.floor(s.length/3)),h.push(d)}this.tickOffset[o]=u,this.tickX[o]=h}for(o=0;o<2;++o){for(this.labelOffset[o]=Math.floor(s.length/3),n=a(t.labelFont[o],t.labels[o],{textAlign:"center"}).data,i=t.labelSize[o],e=0;e<n.length;e+=2)s.push(n[e]*i,-n[e+1]*i,0);this.labelCount[o]=Math.floor(s.length/3)-this.labelOffset[o]}for(this.titleOffset=Math.floor(s.length/3),n=a(t.titleFont,t.title).data,i=t.titleSize,e=0;e<n.length;e+=2)s.push(n[e]*i,-n[e+1]*i,0);this.titleCount=Math.floor(s.length/3)-this.titleOffset,this.vbo.update(s)},g.dispose=function(){this.vbo.dispose(),this.shader.dispose()}},{"./shaders":277,"binary-search-bounds":279,"gl-buffer":234,"gl-shader":294,"text-cache":517}],279:[function(t,e,r){arguments[4][99][0].apply(r,arguments)},{dup:99}],280:[function(t,e,r){"use strict";e.exports=function(t){var e=t.gl,r=n(e,[e.drawingBufferWidth,e.drawingBufferHeight]),c=new l(e,r);return c.grid=i(c),c.text=a(c),c.line=o(c),c.box=s(c),c.update(t),c};var n=t("gl-select-static"),i=t("./lib/grid"),a=t("./lib/text"),o=t("./lib/line"),s=t("./lib/box");function l(t,e){this.gl=t,this.pickBuffer=e,this.screenBox=[0,0,t.drawingBufferWidth,t.drawingBufferHeight],this.viewBox=[0,0,0,0],this.dataBox=[-10,-10,10,10],this.gridLineEnable=[!0,!0],this.gridLineWidth=[1,1],this.gridLineColor=[[0,0,0,1],[0,0,0,1]],this.pixelRatio=1,this.tickMarkLength=[0,0,0,0],this.tickMarkWidth=[0,0,0,0],this.tickMarkColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.tickPad=[15,15,15,15],this.tickAngle=[0,0,0,0],this.tickEnable=[!0,!0,!0,!0],this.tickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.labelPad=[15,15,15,15],this.labelAngle=[0,Math.PI/2,0,3*Math.PI/2],this.labelEnable=[!0,!0,!0,!0],this.labelColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.titleCenter=[0,0],this.titleEnable=!0,this.titleAngle=0,this.titleColor=[0,0,0,1],this.borderColor=[0,0,0,0],this.backgroundColor=[0,0,0,0],this.zeroLineEnable=[!0,!0],this.zeroLineWidth=[4,4],this.zeroLineColor=[[0,0,0,1],[0,0,0,1]],this.borderLineEnable=[!0,!0,!0,!0],this.borderLineWidth=[2,2,2,2],this.borderLineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.grid=null,this.text=null,this.line=null,this.box=null,this.objects=[],this.overlays=[],this._tickBounds=[1/0,1/0,-1/0,-1/0],this.static=!1,this.dirty=!1,this.pickDirty=!1,this.pickDelay=120,this.pickRadius=10,this._pickTimeout=null,this._drawPick=this.drawPick.bind(this),this._depthCounter=0}var c=l.prototype;function u(t){for(var e=t.slice(),r=0;r<e.length;++r)e[r]=e[r].slice();return e}function h(t,e){return t.x-e.x}c.setDirty=function(){this.dirty=this.pickDirty=!0},c.setOverlayDirty=function(){this.dirty=!0},c.nextDepthValue=function(){return this._depthCounter++/65536},c.draw=function(){var t=this.gl,e=this.screenBox,r=this.viewBox,n=this.dataBox,i=this.pixelRatio,a=this.grid,o=this.line,s=this.text,l=this.objects;if(this._depthCounter=0,this.pickDirty&&(this._pickTimeout&&clearTimeout(this._pickTimeout),this.pickDirty=!1,this._pickTimeout=setTimeout(this._drawPick,this.pickDelay)),this.dirty){if(this.dirty=!1,t.bindFramebuffer(t.FRAMEBUFFER,null),t.enable(t.SCISSOR_TEST),t.disable(t.DEPTH_TEST),t.depthFunc(t.LESS),t.depthMask(!1),t.enable(t.BLEND),t.blendEquation(t.FUNC_ADD,t.FUNC_ADD),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA),this.borderColor){t.scissor(e[0],e[1],e[2]-e[0],e[3]-e[1]);var c=this.borderColor;t.clearColor(c[0]*c[3],c[1]*c[3],c[2]*c[3],c[3]),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT)}t.scissor(r[0],r[1],r[2]-r[0],r[3]-r[1]),t.viewport(r[0],r[1],r[2]-r[0],r[3]-r[1]);var u=this.backgroundColor;t.clearColor(u[0]*u[3],u[1]*u[3],u[2]*u[3],u[3]),t.clear(t.COLOR_BUFFER_BIT),a.draw();var h=this.zeroLineEnable,f=this.zeroLineColor,p=this.zeroLineWidth;if(h[0]||h[1]){o.bind();for(var d=0;d<2;++d)if(h[d]&&n[d]<=0&&n[d+2]>=0){var g=e[d]-n[d]*(e[d+2]-e[d])/(n[d+2]-n[d]);0===d?o.drawLine(g,e[1],g,e[3],p[d],f[d]):o.drawLine(e[0],g,e[2],g,p[d],f[d])}}for(d=0;d<l.length;++d)l[d].draw();t.viewport(e[0],e[1],e[2]-e[0],e[3]-e[1]),t.scissor(e[0],e[1],e[2]-e[0],e[3]-e[1]),this.grid.drawTickMarks(),o.bind();var v=this.borderLineEnable,m=this.borderLineWidth,y=this.borderLineColor;for(v[1]&&o.drawLine(r[0],r[1]-.5*m[1]*i,r[0],r[3]+.5*m[3]*i,m[1],y[1]),v[0]&&o.drawLine(r[0]-.5*m[0]*i,r[1],r[2]+.5*m[2]*i,r[1],m[0],y[0]),v[3]&&o.drawLine(r[2],r[1]-.5*m[1]*i,r[2],r[3]+.5*m[3]*i,m[3],y[3]),v[2]&&o.drawLine(r[0]-.5*m[0]*i,r[3],r[2]+.5*m[2]*i,r[3],m[2],y[2]),s.bind(),d=0;d<2;++d)s.drawTicks(d);this.titleEnable&&s.drawTitle();var x=this.overlays;for(d=0;d<x.length;++d)x[d].draw();t.disable(t.SCISSOR_TEST),t.disable(t.BLEND),t.depthMask(!0)}},c.drawPick=function(){if(!this.static){var t=this.pickBuffer;this.gl;this._pickTimeout=null,t.begin();for(var e=1,r=this.objects,n=0;n<r.length;++n)e=r[n].drawPick(e);t.end()}},c.pick=function(t,e){if(!this.static){var r=this.pixelRatio,n=this.pickPixelRatio,i=this.viewBox,a=0|Math.round((t-i[0]/r)*n),o=0|Math.round((e-i[1]/r)*n),s=this.pickBuffer.query(a,o,this.pickRadius);if(!s)return null;for(var l=s.id+(s.value[0]<<8)+(s.value[1]<<16)+(s.value[2]<<24),c=this.objects,u=0;u<c.length;++u){var h=c[u].pick(a,o,l);if(h)return h}return null}},c.setScreenBox=function(t){var e=this.screenBox,r=this.pixelRatio;e[0]=0|Math.round(t[0]*r),e[1]=0|Math.round(t[1]*r),e[2]=0|Math.round(t[2]*r),e[3]=0|Math.round(t[3]*r),this.setDirty()},c.setDataBox=function(t){var e=this.dataBox;(e[0]!==t[0]||e[1]!==t[1]||e[2]!==t[2]||e[3]!==t[3])&&(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],this.setDirty())},c.setViewBox=function(t){var e=this.pixelRatio,r=this.viewBox;r[0]=0|Math.round(t[0]*e),r[1]=0|Math.round(t[1]*e),r[2]=0|Math.round(t[2]*e),r[3]=0|Math.round(t[3]*e);var n=this.pickPixelRatio;this.pickBuffer.shape=[0|Math.round((t[2]-t[0])*n),0|Math.round((t[3]-t[1])*n)],this.setDirty()},c.update=function(t){t=t||{};var e=this.gl;this.pixelRatio=t.pixelRatio||1;var r=this.pixelRatio;this.pickPixelRatio=Math.max(r,1),this.setScreenBox(t.screenBox||[0,0,e.drawingBufferWidth/r,e.drawingBufferHeight/r]);this.screenBox;this.setViewBox(t.viewBox||[.125*(this.screenBox[2]-this.screenBox[0])/r,.125*(this.screenBox[3]-this.screenBox[1])/r,.875*(this.screenBox[2]-this.screenBox[0])/r,.875*(this.screenBox[3]-this.screenBox[1])/r]);var n=this.viewBox,i=(n[2]-n[0])/(n[3]-n[1]);this.setDataBox(t.dataBox||[-10,-10/i,10,10/i]),this.borderColor=!1!==t.borderColor&&(t.borderColor||[0,0,0,0]).slice(),this.backgroundColor=(t.backgroundColor||[0,0,0,0]).slice(),this.gridLineEnable=(t.gridLineEnable||[!0,!0]).slice(),this.gridLineWidth=(t.gridLineWidth||[1,1]).slice(),this.gridLineColor=u(t.gridLineColor||[[.5,.5,.5,1],[.5,.5,.5,1]]),this.zeroLineEnable=(t.zeroLineEnable||[!0,!0]).slice(),this.zeroLineWidth=(t.zeroLineWidth||[4,4]).slice(),this.zeroLineColor=u(t.zeroLineColor||[[0,0,0,1],[0,0,0,1]]),this.tickMarkLength=(t.tickMarkLength||[0,0,0,0]).slice(),this.tickMarkWidth=(t.tickMarkWidth||[0,0,0,0]).slice(),this.tickMarkColor=u(t.tickMarkColor||[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]),this.titleCenter=(t.titleCenter||[.5*(n[0]+n[2])/r,(n[3]+120)/r]).slice(),this.titleEnable=!("titleEnable"in t&&!t.titleEnable),this.titleAngle=t.titleAngle||0,this.titleColor=(t.titleColor||[0,0,0,1]).slice(),this.labelPad=(t.labelPad||[15,15,15,15]).slice(),this.labelAngle=(t.labelAngle||[0,Math.PI/2,0,3*Math.PI/2]).slice(),this.labelEnable=(t.labelEnable||[!0,!0,!0,!0]).slice(),this.labelColor=u(t.labelColor||[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]),this.tickPad=(t.tickPad||[15,15,15,15]).slice(),this.tickAngle=(t.tickAngle||[0,0,0,0]).slice(),this.tickEnable=(t.tickEnable||[!0,!0,!0,!0]).slice(),this.tickColor=u(t.tickColor||[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]),this.borderLineEnable=(t.borderLineEnable||[!0,!0,!0,!0]).slice(),this.borderLineWidth=(t.borderLineWidth||[2,2,2,2]).slice(),this.borderLineColor=u(t.borderLineColor||[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]);var a=t.ticks||[[],[]],o=this._tickBounds;o[0]=o[1]=1/0,o[2]=o[3]=-1/0;for(var s=0;s<2;++s){var l=a[s].slice(0);0!==l.length&&(l.sort(h),o[s]=Math.min(o[s],l[0].x),o[s+2]=Math.max(o[s+2],l[l.length-1].x))}this.grid.update({bounds:o,ticks:a}),this.text.update({bounds:o,ticks:a,labels:t.labels||["x","y"],labelSize:t.labelSize||[12,12],labelFont:t.labelFont||["sans-serif","sans-serif"],title:t.title||"",titleSize:t.titleSize||18,titleFont:t.titleFont||"sans-serif"}),this.static=!!t.static,this.setDirty()},c.dispose=function(){this.box.dispose(),this.grid.dispose(),this.text.dispose(),this.line.dispose();for(var t=this.objects.length-1;t>=0;--t)this.objects[t].dispose();this.objects.length=0;for(t=this.overlays.length-1;t>=0;--t)this.overlays[t].dispose();this.overlays.length=0,this.gl=null},c.addObject=function(t){this.objects.indexOf(t)<0&&(this.objects.push(t),this.setDirty())},c.removeObject=function(t){for(var e=this.objects,r=0;r<e.length;++r)if(e[r]===t){e.splice(r,1),this.setDirty();break}},c.addOverlay=function(t){this.overlays.indexOf(t)<0&&(this.overlays.push(t),this.setOverlayDirty())},c.removeOverlay=function(t){for(var e=this.overlays,r=0;r<e.length;++r)if(e[r]===t){e.splice(r,1),this.setOverlayDirty();break}}},{"./lib/box":274,"./lib/grid":275,"./lib/line":276,"./lib/text":278,"gl-select-static":293}],281:[function(t,e,r){"use strict";e.exports=function(t,e){t=t||document.body,e=e||{};var r=[.01,1/0];"distanceLimits"in e&&(r[0]=e.distanceLimits[0],r[1]=e.distanceLimits[1]);"zoomMin"in e&&(r[0]=e.zoomMin);"zoomMax"in e&&(r[1]=e.zoomMax);var c=i({center:e.center||[0,0,0],up:e.up||[0,1,0],eye:e.eye||[0,0,10],mode:e.mode||"orbit",distanceLimits:r}),u=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],h=0,f=t.clientWidth,p=t.clientHeight,d={keyBindingMode:"rotate",enableWheel:!0,view:c,element:t,delay:e.delay||16,rotateSpeed:e.rotateSpeed||1,zoomSpeed:e.zoomSpeed||1,translateSpeed:e.translateSpeed||1,flipX:!!e.flipX,flipY:!!e.flipY,modes:c.modes,_ortho:e._ortho||e.projection&&"orthographic"===e.projection.type||!1,tick:function(){var e=n(),r=this.delay,i=e-2*r;c.idle(e-r),c.recalcMatrix(i),c.flush(e-(100+2*r));for(var a=!0,o=c.computedMatrix,s=0;s<16;++s)a=a&&u[s]===o[s],u[s]=o[s];var l=t.clientWidth===f&&t.clientHeight===p;return f=t.clientWidth,p=t.clientHeight,a?!l:(h=Math.exp(c.computedRadius[0]),!0)},lookAt:function(t,e,r){c.lookAt(c.lastT(),t,e,r)},rotate:function(t,e,r){c.rotate(c.lastT(),t,e,r)},pan:function(t,e,r){c.pan(c.lastT(),t,e,r)},translate:function(t,e,r){c.translate(c.lastT(),t,e,r)}};Object.defineProperties(d,{matrix:{get:function(){return c.computedMatrix},set:function(t){return c.setMatrix(c.lastT(),t),c.computedMatrix},enumerable:!0},mode:{get:function(){return c.getMode()},set:function(t){var e=c.computedUp.slice(),r=c.computedEye.slice(),i=c.computedCenter.slice();if(c.setMode(t),"turntable"===t){var a=n();c._active.lookAt(a,r,i,e),c._active.lookAt(a+500,r,i,[0,0,1]),c._active.flush(a)}return c.getMode()},enumerable:!0},center:{get:function(){return c.computedCenter},set:function(t){return c.lookAt(c.lastT(),null,t),c.computedCenter},enumerable:!0},eye:{get:function(){return c.computedEye},set:function(t){return c.lookAt(c.lastT(),t),c.computedEye},enumerable:!0},up:{get:function(){return c.computedUp},set:function(t){return c.lookAt(c.lastT(),null,null,t),c.computedUp},enumerable:!0},distance:{get:function(){return h},set:function(t){return c.setDistance(c.lastT(),t),t},enumerable:!0},distanceLimits:{get:function(){return c.getDistanceLimits(r)},set:function(t){return c.setDistanceLimits(t),t},enumerable:!0}}),t.addEventListener("contextmenu",function(t){return t.preventDefault(),!1});var g=0,v=0,m={shift:!1,control:!1,alt:!1,meta:!1};function y(e,r,i,a){var o=d.keyBindingMode;if(!1!==o){var s="rotate"===o,l="pan"===o,u="zoom"===o,f=!!a.control,p=!!a.alt,y=!!a.shift,x=!!(1&e),b=!!(2&e),_=!!(4&e),w=1/t.clientHeight,k=w*(r-g),A=w*(i-v),M=d.flipX?1:-1,T=d.flipY?1:-1,S=Math.PI*d.rotateSpeed,E=n();if((s&&x&&!f&&!p&&!y||x&&!f&&!p&&y)&&c.rotate(E,M*S*k,-T*S*A,0),(l&&x&&!f&&!p&&!y||b||x&&f&&!p&&!y)&&c.pan(E,-d.translateSpeed*k*h,d.translateSpeed*A*h,0),u&&x&&!f&&!p&&!y||_||x&&!f&&p&&!y){var C=-d.zoomSpeed*A/window.innerHeight*(E-c.lastT())*100;c.pan(E,0,0,h*(Math.exp(C)-1))}return g=r,v=i,m=a,!0}}return d.mouseListener=a(t,y),t.addEventListener("touchstart",function(e){var r=s(e.changedTouches[0],t);y(0,r[0],r[1],m),y(1,r[0],r[1],m),e.preventDefault()},!!l&&{passive:!1}),t.addEventListener("touchmove",function(e){var r=s(e.changedTouches[0],t);y(1,r[0],r[1],m),e.preventDefault()},!!l&&{passive:!1}),t.addEventListener("touchend",function(t){y(0,g,v,m),t.preventDefault()},!!l&&{passive:!1}),d.wheelListener=o(t,function(t,e){if(!1!==d.keyBindingMode&&d.enableWheel){var r=d.flipX?1:-1,i=d.flipY?1:-1,a=n();if(Math.abs(t)>Math.abs(e))c.rotate(a,0,0,-t*r*Math.PI*d.rotateSpeed/window.innerWidth);else{var o=-d.zoomSpeed*i*e/window.innerHeight*(a-c.lastT())/20;c.pan(a,0,0,h*(Math.exp(o)-1))}}},!0),d};var n=t("right-now"),i=t("3d-view"),a=t("mouse-change"),o=t("mouse-wheel"),s=t("mouse-event-offset"),l=t("has-passive-events")},{"3d-view":45,"has-passive-events":400,"mouse-change":424,"mouse-event-offset":425,"mouse-wheel":427,"right-now":485}],282:[function(t,e,r){var n=t("glslify"),i=t("gl-shader"),a=n(["precision mediump float;\n#define GLSLIFY 1\nattribute vec2 position;\nvarying vec2 uv;\nvoid main() {\n  uv = position;\n  gl_Position = vec4(position, 0, 1);\n}"]),o=n(["precision mediump float;\n#define GLSLIFY 1\n\nuniform sampler2D accumBuffer;\nvarying vec2 uv;\n\nvoid main() {\n  vec4 accum = texture2D(accumBuffer, 0.5 * (uv + 1.0));\n  gl_FragColor = min(vec4(1,1,1,1), accum);\n}"]);e.exports=function(t){return i(t,a,o,null,[{name:"position",type:"vec2"}])}},{"gl-shader":294,glslify:398}],283:[function(t,e,r){"use strict";var n=t("./camera.js"),i=t("gl-axes3d"),a=t("gl-axes3d/properties"),o=t("gl-spikes3d"),s=t("gl-select-static"),l=t("gl-fbo"),c=t("a-big-triangle"),u=t("mouse-change"),h=t("gl-mat4/perspective"),f=t("gl-mat4/ortho"),p=t("./lib/shader"),d=t("is-mobile")({tablet:!0});function g(){this.mouse=[-1,-1],this.screen=null,this.distance=1/0,this.index=null,this.dataCoordinate=null,this.dataPosition=null,this.object=null,this.data=null}function v(t){var e=Math.round(Math.log(Math.abs(t))/Math.log(10));if(e<0){var r=Math.round(Math.pow(10,-e));return Math.ceil(t*r)/r}if(e>0){r=Math.round(Math.pow(10,e));return Math.ceil(t/r)*r}return Math.ceil(t)}function m(t){return"boolean"!=typeof t||t}e.exports={createScene:function(t){var e=!1,r=(t=t||{}).canvas;if(!r)if(r=document.createElement("canvas"),t.container){var y=t.container;y.appendChild(r)}else document.body.appendChild(r);var x=t.gl;x||(x=function(t,e){var r=null;try{(r=t.getContext("webgl",e))||(r=t.getContext("experimental-webgl",e))}catch(t){return null}return r}(r,t.glOptions||{premultipliedAlpha:!0,antialias:!0,preserveDrawingBuffer:d}));if(!x)throw new Error("webgl not supported");var b=t.bounds||[[-10,-10,-10],[10,10,10]],_=new g,w=l(x,[x.drawingBufferWidth,x.drawingBufferHeight],{preferFloat:!d}),k=p(x),A={eye:t.camera.eye||[2,0,0],center:t.camera.center||[0,0,0],up:t.camera.up||[0,1,0],zoomMin:t.camera.zoomMax||.1,zoomMax:t.camera.zoomMin||100,mode:t.camera.mode||"turntable",_ortho:t.camera.projection&&"orthographic"===t.camera.projection.type||!1},M=t.axes||{},T=i(x,M);T.enable=!M.disable;var S=t.spikes||{},E=o(x,S),C=[],L=[],z=[],O=[],I=!0,D=!0,P=new Array(16),R=new Array(16),F={view:null,projection:P,model:R,_ortho:!1},D=!0,B=[x.drawingBufferWidth,x.drawingBufferHeight],N=n(r,A),j={gl:x,contextLost:!1,pixelRatio:t.pixelRatio||1,canvas:r,selection:_,camera:N,axes:T,axesPixels:null,spikes:E,bounds:b,objects:C,shape:B,aspect:t.aspectRatio||[1,1,1],pickRadius:t.pickRadius||10,zNear:t.zNear||.01,zFar:t.zFar||1e3,fovy:t.fovy||Math.PI/4,clearColor:t.clearColor||[0,0,0,0],autoResize:m(t.autoResize),autoBounds:m(t.autoBounds),autoScale:!!t.autoScale,autoCenter:m(t.autoCenter),clipToBounds:m(t.clipToBounds),snapToData:!!t.snapToData,onselect:t.onselect||null,onrender:t.onrender||null,onclick:t.onclick||null,cameraParams:F,oncontextloss:null,mouseListener:null},V=[x.drawingBufferWidth/j.pixelRatio|0,x.drawingBufferHeight/j.pixelRatio|0];function U(){if(!e&&j.autoResize){var t=r.parentNode,n=1,i=1;t&&t!==document.body?(n=t.clientWidth,i=t.clientHeight):(n=window.innerWidth,i=window.innerHeight);var a=0|Math.ceil(n*j.pixelRatio),o=0|Math.ceil(i*j.pixelRatio);if(a!==r.width||o!==r.height){r.width=a,r.height=o;var s=r.style;s.position=s.position||"absolute",s.left="0px",s.top="0px",s.width=n+"px",s.height=i+"px",I=!0}}}j.autoResize&&U();function q(){for(var t=C.length,e=O.length,r=0;r<e;++r)z[r]=0;t:for(var r=0;r<t;++r){var n=C[r],i=n.pickSlots;if(i){for(var a=0;a<e;++a)if(z[a]+i<255){L[r]=a,n.setPickBase(z[a]+1),z[a]+=i;continue t}var o=s(x,B);L[r]=e,O.push(o),z.push(i),n.setPickBase(1),e+=1}else L[r]=-1}for(;e>0&&0===z[e-1];)z.pop(),O.pop().dispose()}window.addEventListener("resize",U),j.update=function(t){e||(t=t||{},I=!0,D=!0)},j.add=function(t){e||(t.axes=T,C.push(t),L.push(-1),I=!0,D=!0,q())},j.remove=function(t){if(!e){var r=C.indexOf(t);r<0||(C.splice(r,1),L.pop(),I=!0,D=!0,q())}},j.dispose=function(){if(!e&&(e=!0,window.removeEventListener("resize",U),r.removeEventListener("webglcontextlost",Y),j.mouseListener.enabled=!1,!j.contextLost)){T.dispose(),E.dispose();for(var t=0;t<C.length;++t)C[t].dispose();w.dispose();for(var t=0;t<O.length;++t)O[t].dispose();k.dispose(),x=null,T=null,E=null,C=[]}};var H=!1,G=0;function Y(){if(j.contextLost)return!0;x.isContextLost()&&(j.contextLost=!0,j.mouseListener.enabled=!1,j.selection.object=null,j.oncontextloss&&j.oncontextloss())}j.mouseListener=u(r,function(t,r,n){if(!e){var i=O.length,a=C.length,o=_.object;_.distance=1/0,_.mouse[0]=r,_.mouse[1]=n,_.object=null,_.screen=null,_.dataCoordinate=_.dataPosition=null;var s=!1;if(t&&G)H=!0;else{H&&(D=!0),H=!1;for(var l=0;l<i;++l){var c=O[l].query(r,V[1]-n-1,j.pickRadius);if(c){if(c.distance>_.distance)continue;for(var u=0;u<a;++u){var h=C[u];if(L[u]===l){var f=h.pick(c);f&&(_.buttons=t,_.screen=c.coord,_.distance=c.distance,_.object=h,_.index=f.distance,_.dataPosition=f.position,_.dataCoordinate=f.dataCoordinate,_.data=f,s=!0)}}}}}o&&o!==_.object&&(o.highlight&&o.highlight(null),I=!0),_.object&&(_.object.highlight&&_.object.highlight(_.data),I=!0),(s=s||_.object!==o)&&j.onselect&&j.onselect(_),1&t&&!(1&G)&&j.onclick&&j.onclick(_),G=t}}),r.addEventListener("webglcontextlost",Y);var W=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]],X=[W[0].slice(),W[1].slice()];function Z(){if(!Y()){U();var t=j.camera.tick();F.view=j.camera.matrix,I=I||t,D=D||t,T.pixelRatio=j.pixelRatio,E.pixelRatio=j.pixelRatio;var e=C.length,r=W[0],n=W[1];r[0]=r[1]=r[2]=1/0,n[0]=n[1]=n[2]=-1/0;for(var i=0;i<e;++i){var o=C[i];o.pixelRatio=j.pixelRatio,o.axes=j.axes,I=I||!!o.dirty,D=D||!!o.dirty;var s=o.bounds;if(s)for(var l=s[0],u=s[1],p=0;p<3;++p)r[p]=Math.min(r[p],l[p]),n[p]=Math.max(n[p],u[p])}var d=j.bounds;if(j.autoBounds)for(var p=0;p<3;++p){if(n[p]<r[p])r[p]=-1,n[p]=1;else{r[p]===n[p]&&(r[p]-=1,n[p]+=1);var g=.05*(n[p]-r[p]);r[p]=r[p]-g,n[p]=n[p]+g}d[0][p]=r[p],d[1][p]=n[p]}for(var m=!1,p=0;p<3;++p)m=m||X[0][p]!==d[0][p]||X[1][p]!==d[1][p],X[0][p]=d[0][p],X[1][p]=d[1][p];if(D=D||m,I=I||m){if(m){for(var y=[0,0,0],i=0;i<3;++i)y[i]=v((d[1][i]-d[0][i])/10);T.autoTicks?T.update({bounds:d,tickSpacing:y}):T.update({bounds:d})}var b=x.drawingBufferWidth,M=x.drawingBufferHeight;B[0]=b,B[1]=M,V[0]=0|Math.max(b/j.pixelRatio,1),V[1]=0|Math.max(M/j.pixelRatio,1),!0===A._ortho?(f(P,-b/M,b/M,-1,1,j.zNear,j.zFar),F._ortho=!0):(h(P,j.fovy,b/M,j.zNear,j.zFar),F._ortho=!1);for(var i=0;i<16;++i)R[i]=0;R[15]=1;for(var S=0,i=0;i<3;++i)S=Math.max(S,d[1][i]-d[0][i]);for(var i=0;i<3;++i)j.autoScale?R[5*i]=j.aspect[i]/(d[1][i]-d[0][i]):R[5*i]=1/S,j.autoCenter&&(R[12+i]=.5*-R[5*i]*(d[0][i]+d[1][i]));for(var i=0;i<e;++i){var o=C[i];o.axesBounds=d,j.clipToBounds&&(o.clipBounds=d)}_.object&&(j.snapToData?E.position=_.dataCoordinate:E.position=_.dataPosition,E.bounds=d),D&&(D=!1,function(){if(Y())return;x.colorMask(!0,!0,!0,!0),x.depthMask(!0),x.disable(x.BLEND),x.enable(x.DEPTH_TEST);for(var t=C.length,e=O.length,r=0;r<e;++r){var n=O[r];n.shape=V,n.begin();for(var i=0;i<t;++i)if(L[i]===r){var a=C[i];a.drawPick&&(a.pixelRatio=1,a.drawPick(F))}n.end()}}()),j.axesPixels=a(j.axes,F,b,M),j.onrender&&j.onrender(),x.bindFramebuffer(x.FRAMEBUFFER,null),x.viewport(0,0,b,M);var z=j.clearColor;x.clearColor(z[0],z[1],z[2],z[3]),x.clear(x.COLOR_BUFFER_BIT|x.DEPTH_BUFFER_BIT),x.depthMask(!0),x.colorMask(!0,!0,!0,!0),x.enable(x.DEPTH_TEST),x.depthFunc(x.LEQUAL),x.disable(x.BLEND),x.disable(x.CULL_FACE);var N=!1;T.enable&&(N=N||T.isTransparent(),T.draw(F)),E.axes=T,_.object&&E.draw(F),x.disable(x.CULL_FACE);for(var i=0;i<e;++i){var o=C[i];o.axes=T,o.pixelRatio=j.pixelRatio,o.isOpaque&&o.isOpaque()&&o.draw(F),o.isTransparent&&o.isTransparent()&&(N=!0)}if(N){w.shape=B,w.bind(),x.clear(x.DEPTH_BUFFER_BIT),x.colorMask(!1,!1,!1,!1),x.depthMask(!0),x.depthFunc(x.LESS),T.enable&&T.isTransparent()&&T.drawTransparent(F);for(var i=0;i<e;++i){var o=C[i];o.isOpaque&&o.isOpaque()&&o.draw(F)}x.enable(x.BLEND),x.blendEquation(x.FUNC_ADD),x.blendFunc(x.ONE,x.ONE_MINUS_SRC_ALPHA),x.colorMask(!0,!0,!0,!0),x.depthMask(!1),x.clearColor(0,0,0,0),x.clear(x.COLOR_BUFFER_BIT),T.isTransparent()&&T.drawTransparent(F);for(var i=0;i<e;++i){var o=C[i];o.isTransparent&&o.isTransparent()&&o.drawTransparent(F)}x.bindFramebuffer(x.FRAMEBUFFER,null),x.blendFunc(x.ONE,x.ONE_MINUS_SRC_ALPHA),x.disable(x.DEPTH_TEST),k.bind(),w.color[0].bind(0),k.uniforms.accumBuffer=0,c(x),x.disable(x.BLEND)}I=!1;for(var i=0;i<e;++i)C[i].dirty=!1}}}return function t(){e||j.contextLost||(Z(),requestAnimationFrame(t))}(),j.redraw=function(){e||(I=!0,Z())},j},createCamera:n}},{"./camera.js":281,"./lib/shader":282,"a-big-triangle":47,"gl-axes3d":226,"gl-axes3d/properties":233,"gl-fbo":242,"gl-mat4/ortho":261,"gl-mat4/perspective":262,"gl-select-static":293,"gl-spikes3d":303,"is-mobile":409,"mouse-change":424}],284:[function(t,e,r){var n=t("glslify");r.pointVertex=n(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform float pointCloud;\n\nhighp float rand(vec2 co) {\n  highp float a = 12.9898;\n  highp float b = 78.233;\n  highp float c = 43758.5453;\n  highp float d = dot(co.xy, vec2(a, b));\n  highp float e = mod(d, 3.14);\n  return fract(sin(e) * c);\n}\n\nvoid main() {\n  vec3 hgPosition = matrix * vec3(position, 1);\n  gl_Position  = vec4(hgPosition.xy, 0, hgPosition.z);\n    // if we don't jitter the point size a bit, overall point cloud\n    // saturation 'jumps' on zooming, which is disturbing and confusing\n  gl_PointSize = pointSize * ((19.5 + rand(position)) / 20.0);\n  if(pointCloud != 0.0) { // pointCloud is truthy\n    // get the same square surface as circle would be\n    gl_PointSize *= 0.886;\n  }\n}"]),r.pointFragment=n(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color, borderColor;\nuniform float centerFraction;\nuniform float pointCloud;\n\nvoid main() {\n  float radius;\n  vec4 baseColor;\n  if(pointCloud != 0.0) { // pointCloud is truthy\n    if(centerFraction == 1.0) {\n      gl_FragColor = color;\n    } else {\n      gl_FragColor = mix(borderColor, color, centerFraction);\n    }\n  } else {\n    radius = length(2.0 * gl_PointCoord.xy - 1.0);\n    if(radius > 1.0) {\n      discard;\n    }\n    baseColor = mix(borderColor, color, step(radius, centerFraction));\n    gl_FragColor = vec4(baseColor.rgb * baseColor.a, baseColor.a);\n  }\n}\n"]),r.pickVertex=n(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 pickId;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform vec4 pickOffset;\n\nvarying vec4 fragId;\n\nvoid main() {\n  vec3 hgPosition = matrix * vec3(position, 1);\n  gl_Position  = vec4(hgPosition.xy, 0, hgPosition.z);\n  gl_PointSize = pointSize;\n\n  vec4 id = pickId + pickOffset;\n  id.y += floor(id.x / 256.0);\n  id.x -= floor(id.x / 256.0) * 256.0;\n\n  id.z += floor(id.y / 256.0);\n  id.y -= floor(id.y / 256.0) * 256.0;\n\n  id.w += floor(id.z / 256.0);\n  id.z -= floor(id.z / 256.0) * 256.0;\n\n  fragId = id;\n}\n"]),r.pickFragment=n(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragId;\n\nvoid main() {\n  float radius = length(2.0 * gl_PointCoord.xy - 1.0);\n  if(radius > 1.0) {\n    discard;\n  }\n  gl_FragColor = fragId / 255.0;\n}\n"])},{glslify:398}],285:[function(t,e,r){"use strict";var n=t("gl-shader"),i=t("gl-buffer"),a=t("typedarray-pool"),o=t("./lib/shader");function s(t,e,r,n,i){this.plot=t,this.offsetBuffer=e,this.pickBuffer=r,this.shader=n,this.pickShader=i,this.sizeMin=.5,this.sizeMinCap=2,this.sizeMax=20,this.areaRatio=1,this.pointCount=0,this.color=[1,0,0,1],this.borderColor=[0,0,0,1],this.blend=!1,this.pickOffset=0,this.points=null}e.exports=function(t,e){var r=t.gl,a=i(r),l=i(r),c=n(r,o.pointVertex,o.pointFragment),u=n(r,o.pickVertex,o.pickFragment),h=new s(t,a,l,c,u);return h.update(e),t.addObject(h),h};var l,c,u=s.prototype;u.dispose=function(){this.shader.dispose(),this.pickShader.dispose(),this.offsetBuffer.dispose(),this.pickBuffer.dispose(),this.plot.removeObject(this)},u.update=function(t){var e;function r(e,r){return e in t?t[e]:r}t=t||{},this.sizeMin=r("sizeMin",.5),this.sizeMax=r("sizeMax",20),this.color=r("color",[1,0,0,1]).slice(),this.areaRatio=r("areaRatio",1),this.borderColor=r("borderColor",[0,0,0,1]).slice(),this.blend=r("blend",!1);var n=t.positions.length>>>1,i=t.positions instanceof Float32Array,o=t.idToIndex instanceof Int32Array&&t.idToIndex.length>=n,s=t.positions,l=i?s:a.mallocFloat32(s.length),c=o?t.idToIndex:a.mallocInt32(n);if(i||l.set(s),!o)for(l.set(s),e=0;e<n;e++)c[e]=e;this.points=s,this.offsetBuffer.update(l),this.pickBuffer.update(c),i||a.free(l),o||a.free(c),this.pointCount=n,this.pickOffset=0},u.unifiedDraw=(l=[1,0,0,0,1,0,0,0,1],c=[0,0,0,0],function(t){var e=void 0!==t,r=e?this.pickShader:this.shader,n=this.plot.gl,i=this.plot.dataBox;if(0===this.pointCount)return t;var a=i[2]-i[0],o=i[3]-i[1],s=function(t,e){var r,n=0,i=t.length>>>1;for(r=0;r<i;r++){var a=t[2*r],o=t[2*r+1];a>=e[0]&&a<=e[2]&&o>=e[1]&&o<=e[3]&&n++}return n}(this.points,i),u=this.plot.pickPixelRatio*Math.max(Math.min(this.sizeMinCap,this.sizeMin),Math.min(this.sizeMax,this.sizeMax/Math.pow(s,.33333)));l[0]=2/a,l[4]=2/o,l[6]=-2*i[0]/a-1,l[7]=-2*i[1]/o-1,this.offsetBuffer.bind(),r.bind(),r.attributes.position.pointer(),r.uniforms.matrix=l,r.uniforms.color=this.color,r.uniforms.borderColor=this.borderColor,r.uniforms.pointCloud=u<5,r.uniforms.pointSize=u,r.uniforms.centerFraction=Math.min(1,Math.max(0,Math.sqrt(1-this.areaRatio))),e&&(c[0]=255&t,c[1]=t>>8&255,c[2]=t>>16&255,c[3]=t>>24&255,this.pickBuffer.bind(),r.attributes.pickId.pointer(n.UNSIGNED_BYTE),r.uniforms.pickOffset=c,this.pickOffset=t);var h=n.getParameter(n.BLEND),f=n.getParameter(n.DITHER);return h&&!this.blend&&n.disable(n.BLEND),f&&n.disable(n.DITHER),n.drawArrays(n.POINTS,0,this.pointCount),h&&!this.blend&&n.enable(n.BLEND),f&&n.enable(n.DITHER),t+this.pointCount}),u.draw=u.unifiedDraw,u.drawPick=u.unifiedDraw,u.pick=function(t,e,r){var n=this.pickOffset,i=this.pointCount;if(r<n||r>=n+i)return null;var a=r-n,o=this.points;return{object:this,pointId:a,dataCoord:[o[2*a],o[2*a+1]]}}},{"./lib/shader":284,"gl-buffer":234,"gl-shader":294,"typedarray-pool":526}],286:[function(t,e,r){e.exports=function(t,e,r,n){var i,a,o,s,l,c=e[0],u=e[1],h=e[2],f=e[3],p=r[0],d=r[1],g=r[2],v=r[3];(a=c*p+u*d+h*g+f*v)<0&&(a=-a,p=-p,d=-d,g=-g,v=-v);1-a>1e-6?(i=Math.acos(a),o=Math.sin(i),s=Math.sin((1-n)*i)/o,l=Math.sin(n*i)/o):(s=1-n,l=n);return t[0]=s*c+l*p,t[1]=s*u+l*d,t[2]=s*h+l*g,t[3]=s*f+l*v,t}},{}],287:[function(t,e,r){"use strict";e.exports=function(t){return t||0===t?t.toString():""}},{}],288:[function(t,e,r){"use strict";var n=t("vectorize-text");e.exports=function(t,e,r){var a=i[e];a||(a=i[e]={});if(t in a)return a[t];var o={textAlign:"center",textBaseline:"middle",lineHeight:1,font:e,lineSpacing:1.25,styletags:{breaklines:!0,bolds:!0,italics:!0,subscripts:!0,superscripts:!0},triangles:!0},s=n(t,o);o.triangles=!1;var l,c,u=n(t,o);if(r&&1!==r){for(l=0;l<s.positions.length;++l)for(c=0;c<s.positions[l].length;++c)s.positions[l][c]/=r;for(l=0;l<u.positions.length;++l)for(c=0;c<u.positions[l].length;++c)u.positions[l][c]/=r}var h=[[1/0,1/0],[-1/0,-1/0]],f=u.positions.length;for(l=0;l<f;++l){var p=u.positions[l];for(c=0;c<2;++c)h[0][c]=Math.min(h[0][c],p[c]),h[1][c]=Math.max(h[1][c],p[c])}return a[t]=[s,u,h]};var i={}},{"vectorize-text":531}],289:[function(t,e,r){var n=t("gl-shader"),i=t("glslify"),a=i(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform vec4 highlightId;\nuniform float highlightScale;\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    float scale = 1.0;\n    if(distance(highlightId, id) < 0.0001) {\n      scale = highlightScale;\n    }\n\n    vec4 worldPosition = model * vec4(position, 1);\n    vec4 viewPosition = view * worldPosition;\n    viewPosition = viewPosition / viewPosition.w;\n    vec4 clipPosition = projection * (viewPosition + scale * vec4(glyph.x, -glyph.y, 0, 0));\n\n    gl_Position = clipPosition;\n    interpColor = color;\n    pickId = id;\n    dataCoordinate = position;\n  }\n}"]),o=i(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float highlightScale, pixelRatio;\nuniform vec4 highlightId;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    float scale = pixelRatio;\n    if(distance(highlightId.bgr, id.bgr) < 0.001) {\n      scale *= highlightScale;\n    }\n\n    vec4 worldPosition = model * vec4(position, 1.0);\n    vec4 viewPosition = view * worldPosition;\n    vec4 clipPosition = projection * viewPosition;\n    clipPosition /= clipPosition.w;\n\n    gl_Position = clipPosition + vec4(screenSize * scale * vec2(glyph.x, -glyph.y), 0.0, 0.0);\n    interpColor = color;\n    pickId = id;\n    dataCoordinate = position;\n  }\n}"]),s=i(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform float highlightScale;\nuniform vec4 highlightId;\nuniform vec3 axes[2];\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float scale, pixelRatio;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    float lscale = pixelRatio * scale;\n    if(distance(highlightId, id) < 0.0001) {\n      lscale *= highlightScale;\n    }\n\n    vec4 clipCenter   = projection * view * model * vec4(position, 1);\n    vec3 dataPosition = position + 0.5*lscale*(axes[0] * glyph.x + axes[1] * glyph.y) * clipCenter.w * screenSize.y;\n    vec4 clipPosition = projection * view * model * vec4(dataPosition, 1);\n\n    gl_Position = clipPosition;\n    interpColor = color;\n    pickId = id;\n    dataCoordinate = dataPosition;\n  }\n}\n"]),l=i(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 fragClipBounds[2];\nuniform float opacity;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if (\n    outOfRange(fragClipBounds[0], fragClipBounds[1], dataCoordinate) ||\n    interpColor.a * opacity == 0.\n  ) discard;\n  gl_FragColor = interpColor * opacity;\n}\n"]),c=i(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 fragClipBounds[2];\nuniform float pickGroup;\n\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if (outOfRange(fragClipBounds[0], fragClipBounds[1], dataCoordinate)) discard;\n\n  gl_FragColor = vec4(pickGroup, pickId.bgr);\n}"]),u=[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"glyph",type:"vec2"},{name:"id",type:"vec4"}],h={vertex:a,fragment:l,attributes:u},f={vertex:o,fragment:l,attributes:u},p={vertex:s,fragment:l,attributes:u},d={vertex:a,fragment:c,attributes:u},g={vertex:o,fragment:c,attributes:u},v={vertex:s,fragment:c,attributes:u};function m(t,e){var r=n(t,e),i=r.attributes;return i.position.location=0,i.color.location=1,i.glyph.location=2,i.id.location=3,r}r.createPerspective=function(t){return m(t,h)},r.createOrtho=function(t){return m(t,f)},r.createProject=function(t){return m(t,p)},r.createPickPerspective=function(t){return m(t,d)},r.createPickOrtho=function(t){return m(t,g)},r.createPickProject=function(t){return m(t,v)}},{"gl-shader":294,glslify:398}],290:[function(t,e,r){"use strict";var n=t("is-string-blank"),i=t("gl-buffer"),a=t("gl-vao"),o=t("typedarray-pool"),s=t("gl-mat4/multiply"),l=t("./lib/shaders"),c=t("./lib/glyphs"),u=t("./lib/get-simple-string"),h=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function f(t,e){var r=t[0],n=t[1],i=t[2],a=t[3];return t[0]=e[0]*r+e[4]*n+e[8]*i+e[12]*a,t[1]=e[1]*r+e[5]*n+e[9]*i+e[13]*a,t[2]=e[2]*r+e[6]*n+e[10]*i+e[14]*a,t[3]=e[3]*r+e[7]*n+e[11]*i+e[15]*a,t}function p(t,e,r,n){return f(n,n),f(n,n),f(n,n)}function d(t,e){this.index=t,this.dataCoordinate=this.position=e}function g(t){return!0===t?1:t>1?1:t}function v(t,e,r,n,i,a,o,s,l,c,u,h){this.gl=t,this.pixelRatio=1,this.shader=e,this.orthoShader=r,this.projectShader=n,this.pointBuffer=i,this.colorBuffer=a,this.glyphBuffer=o,this.idBuffer=s,this.vao=l,this.vertexCount=0,this.lineVertexCount=0,this.opacity=1,this.hasAlpha=!1,this.lineWidth=0,this.projectScale=[2/3,2/3,2/3],this.projectOpacity=[1,1,1],this.projectHasAlpha=!1,this.pickId=0,this.pickPerspectiveShader=c,this.pickOrthoShader=u,this.pickProjectShader=h,this.points=[],this._selectResult=new d(0,[0,0,0]),this.useOrtho=!0,this.bounds=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]],this.axesProject=[!0,!0,!0],this.axesBounds=[[-1/0,-1/0,-1/0],[1/0,1/0,1/0]],this.highlightId=[1,1,1,1],this.highlightScale=2,this.clipBounds=[[-1/0,-1/0,-1/0],[1/0,1/0,1/0]],this.dirty=!0}e.exports=function(t){var e=t.gl,r=l.createPerspective(e),n=l.createOrtho(e),o=l.createProject(e),s=l.createPickPerspective(e),c=l.createPickOrtho(e),u=l.createPickProject(e),h=i(e),f=i(e),p=i(e),d=i(e),g=a(e,[{buffer:h,size:3,type:e.FLOAT},{buffer:f,size:4,type:e.FLOAT},{buffer:p,size:2,type:e.FLOAT},{buffer:d,size:4,type:e.UNSIGNED_BYTE,normalized:!0}]),m=new v(e,r,n,o,h,f,p,d,g,s,c,u);return m.update(t),m};var m=v.prototype;m.pickSlots=1,m.setPickBase=function(t){this.pickId=t},m.isTransparent=function(){if(this.hasAlpha)return!0;for(var t=0;t<3;++t)if(this.axesProject[t]&&this.projectHasAlpha)return!0;return!1},m.isOpaque=function(){if(!this.hasAlpha)return!0;for(var t=0;t<3;++t)if(this.axesProject[t]&&!this.projectHasAlpha)return!0;return!1};var y=[0,0],x=[0,0,0],b=[0,0,0],_=[0,0,0,1],w=[0,0,0,1],k=h.slice(),A=[0,0,0],M=[[0,0,0],[0,0,0]];function T(t){return t[0]=t[1]=t[2]=0,t}function S(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t}function E(t,e,r,n){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[r]=n,t}function C(t,e,r,n){var i,a=e.axesProject,o=e.gl,l=t.uniforms,c=r.model||h,u=r.view||h,f=r.projection||h,d=e.axesBounds,g=function(t){for(var e=M,r=0;r<2;++r)for(var n=0;n<3;++n)e[r][n]=Math.max(Math.min(t[r][n],1e8),-1e8);return e}(e.clipBounds);i=e.axes&&e.axes.lastCubeProps?e.axes.lastCubeProps.axis:[1,1,1],y[0]=2/o.drawingBufferWidth,y[1]=2/o.drawingBufferHeight,t.bind(),l.view=u,l.projection=f,l.screenSize=y,l.highlightId=e.highlightId,l.highlightScale=e.highlightScale,l.clipBounds=g,l.pickGroup=e.pickId/255,l.pixelRatio=n;for(var v=0;v<3;++v)if(a[v]){l.scale=e.projectScale[v],l.opacity=e.projectOpacity[v];for(var m=k,C=0;C<16;++C)m[C]=0;for(C=0;C<4;++C)m[5*C]=1;m[5*v]=0,i[v]<0?m[12+v]=d[0][v]:m[12+v]=d[1][v],s(m,c,m),l.model=m;var L=(v+1)%3,z=(v+2)%3,O=T(x),I=T(b);O[L]=1,I[z]=1;var D=p(0,0,0,S(_,O)),P=p(0,0,0,S(w,I));if(Math.abs(D[1])>Math.abs(P[1])){var R=D;D=P,P=R,R=O,O=I,I=R;var F=L;L=z,z=F}D[0]<0&&(O[L]=-1),P[1]>0&&(I[z]=-1);var B=0,N=0;for(C=0;C<4;++C)B+=Math.pow(c[4*L+C],2),N+=Math.pow(c[4*z+C],2);O[L]/=Math.sqrt(B),I[z]/=Math.sqrt(N),l.axes[0]=O,l.axes[1]=I,l.fragClipBounds[0]=E(A,g[0],v,-1e8),l.fragClipBounds[1]=E(A,g[1],v,1e8),e.vao.bind(),e.vao.draw(o.TRIANGLES,e.vertexCount),e.lineWidth>0&&(o.lineWidth(e.lineWidth*n),e.vao.draw(o.LINES,e.lineVertexCount,e.vertexCount)),e.vao.unbind()}}var L=[[-1e8,-1e8,-1e8],[1e8,1e8,1e8]];function z(t,e,r,n,i,a,o){var s=r.gl;if((a===r.projectHasAlpha||o)&&C(e,r,n,i),a===r.hasAlpha||o){t.bind();var l=t.uniforms;l.model=n.model||h,l.view=n.view||h,l.projection=n.projection||h,y[0]=2/s.drawingBufferWidth,y[1]=2/s.drawingBufferHeight,l.screenSize=y,l.highlightId=r.highlightId,l.highlightScale=r.highlightScale,l.fragClipBounds=L,l.clipBounds=r.axes.bounds,l.opacity=r.opacity,l.pickGroup=r.pickId/255,l.pixelRatio=i,r.vao.bind(),r.vao.draw(s.TRIANGLES,r.vertexCount),r.lineWidth>0&&(s.lineWidth(r.lineWidth*i),r.vao.draw(s.LINES,r.lineVertexCount,r.vertexCount)),r.vao.unbind()}}function O(t,e,r,i){var a;a=Array.isArray(t)?e<t.length?t[e]:void 0:t,a=u(a);var o=!0;n(a)&&(a="\u25bc",o=!1);var s=c(a,r,i);return{mesh:s[0],lines:s[1],bounds:s[2],visible:o}}m.draw=function(t){z(this.useOrtho?this.orthoShader:this.shader,this.projectShader,this,t,this.pixelRatio,!1,!1)},m.drawTransparent=function(t){z(this.useOrtho?this.orthoShader:this.shader,this.projectShader,this,t,this.pixelRatio,!0,!1)},m.drawPick=function(t){z(this.useOrtho?this.pickOrthoShader:this.pickPerspectiveShader,this.pickProjectShader,this,t,1,!0,!0)},m.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=t.value[2]+(t.value[1]<<8)+(t.value[0]<<16);if(e>=this.pointCount||e<0)return null;var r=this.points[e],n=this._selectResult;n.index=e;for(var i=0;i<3;++i)n.position[i]=n.dataCoordinate[i]=r[i];return n},m.highlight=function(t){if(t){var e=t.index,r=255&e,n=e>>8&255,i=e>>16&255;this.highlightId=[r/255,n/255,i/255,0]}else this.highlightId=[1,1,1,1]},m.update=function(t){if("perspective"in(t=t||{})&&(this.useOrtho=!t.perspective),"orthographic"in t&&(this.useOrtho=!!t.orthographic),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"project"in t)if(Array.isArray(t.project))this.axesProject=t.project;else{var e=!!t.project;this.axesProject=[e,e,e]}if("projectScale"in t)if(Array.isArray(t.projectScale))this.projectScale=t.projectScale.slice();else{var r=+t.projectScale;this.projectScale=[r,r,r]}if(this.projectHasAlpha=!1,"projectOpacity"in t){if(Array.isArray(t.projectOpacity))this.projectOpacity=t.projectOpacity.slice();else{r=+t.projectOpacity;this.projectOpacity=[r,r,r]}for(var n=0;n<3;++n)this.projectOpacity[n]=g(this.projectOpacity[n]),this.projectOpacity[n]<1&&(this.projectHasAlpha=!0)}this.hasAlpha=!1,"opacity"in t&&(this.opacity=g(t.opacity),this.opacity<1&&(this.hasAlpha=!0)),this.dirty=!0;var i,a,s=t.position,l=t.font||"normal",c=t.alignment||[0,0];if(2===c.length)i=c[0],a=c[1];else{i=[],a=[];for(n=0;n<c.length;++n)i[n]=c[n][0],a[n]=c[n][1]}var u=[1/0,1/0,1/0],h=[-1/0,-1/0,-1/0],f=t.glyph,p=t.color,d=t.size,v=t.angle,m=t.lineColor,y=-1,x=0,b=0,_=0;if(s.length){_=s.length;t:for(n=0;n<_;++n){for(var w=s[n],k=0;k<3;++k)if(isNaN(w[k])||!isFinite(w[k]))continue t;var A=(N=O(f,n,l,this.pixelRatio)).mesh,M=N.lines,T=N.bounds;x+=3*A.cells.length,b+=2*M.edges.length}}var S=x+b,E=o.mallocFloat(3*S),C=o.mallocFloat(4*S),L=o.mallocFloat(2*S),z=o.mallocUint32(S);if(S>0){var I=0,D=x,P=[0,0,0,1],R=[0,0,0,1],F=Array.isArray(p)&&Array.isArray(p[0]),B=Array.isArray(m)&&Array.isArray(m[0]);t:for(n=0;n<_;++n){y+=1;for(w=s[n],k=0;k<3;++k){if(isNaN(w[k])||!isFinite(w[k]))continue t;h[k]=Math.max(h[k],w[k]),u[k]=Math.min(u[k],w[k])}A=(N=O(f,n,l,this.pixelRatio)).mesh,M=N.lines,T=N.bounds;var N,j=N.visible;if(j)if(Array.isArray(p)){if(3===(V=F?n<p.length?p[n]:[0,0,0,0]:p).length){for(k=0;k<3;++k)P[k]=V[k];P[3]=1}else if(4===V.length){for(k=0;k<4;++k)P[k]=V[k];!this.hasAlpha&&V[3]<1&&(this.hasAlpha=!0)}}else P[0]=P[1]=P[2]=0,P[3]=1;else P=[1,1,1,0];if(j)if(Array.isArray(m)){var V;if(3===(V=B?n<m.length?m[n]:[0,0,0,0]:m).length){for(k=0;k<3;++k)R[k]=V[k];R[k]=1}else if(4===V.length){for(k=0;k<4;++k)R[k]=V[k];!this.hasAlpha&&V[3]<1&&(this.hasAlpha=!0)}}else R[0]=R[1]=R[2]=0,R[3]=1;else R=[1,1,1,0];var U=.5;j?Array.isArray(d)?U=n<d.length?+d[n]:12:d?U=+d:this.useOrtho&&(U=12):U=0;var q=0;Array.isArray(v)?q=n<v.length?+v[n]:0:v&&(q=+v);var H=Math.cos(q),G=Math.sin(q);for(w=s[n],k=0;k<3;++k)h[k]=Math.max(h[k],w[k]),u[k]=Math.min(u[k],w[k]);var Y=i,W=a;Y=0;Array.isArray(i)?Y=n<i.length?i[n]:0:i&&(Y=i);W=0;Array.isArray(a)?W=n<a.length?a[n]:0:a&&(W=a);var X=[Y*=Y>0?1-T[0][0]:Y<0?1+T[1][0]:1,W*=W>0?1-T[0][1]:W<0?1+T[1][1]:1],Z=A.cells||[],$=A.positions||[];for(k=0;k<Z.length;++k)for(var J=Z[k],K=0;K<3;++K){for(var Q=0;Q<3;++Q)E[3*I+Q]=w[Q];for(Q=0;Q<4;++Q)C[4*I+Q]=P[Q];z[I]=y;var tt=$[J[K]];L[2*I]=U*(H*tt[0]-G*tt[1]+X[0]),L[2*I+1]=U*(G*tt[0]+H*tt[1]+X[1]),I+=1}for(Z=M.edges,$=M.positions,k=0;k<Z.length;++k)for(J=Z[k],K=0;K<2;++K){for(Q=0;Q<3;++Q)E[3*D+Q]=w[Q];for(Q=0;Q<4;++Q)C[4*D+Q]=R[Q];z[D]=y;tt=$[J[K]];L[2*D]=U*(H*tt[0]-G*tt[1]+X[0]),L[2*D+1]=U*(G*tt[0]+H*tt[1]+X[1]),D+=1}}}this.bounds=[u,h],this.points=s,this.pointCount=s.length,this.vertexCount=x,this.lineVertexCount=b,this.pointBuffer.update(E),this.colorBuffer.update(C),this.glyphBuffer.update(L),this.idBuffer.update(z),o.free(E),o.free(C),o.free(L),o.free(z)},m.dispose=function(){this.shader.dispose(),this.orthoShader.dispose(),this.pickPerspectiveShader.dispose(),this.pickOrthoShader.dispose(),this.vao.dispose(),this.pointBuffer.dispose(),this.colorBuffer.dispose(),this.glyphBuffer.dispose(),this.idBuffer.dispose()}},{"./lib/get-simple-string":287,"./lib/glyphs":288,"./lib/shaders":289,"gl-buffer":234,"gl-mat4/multiply":260,"gl-vao":316,"is-string-blank":412,"typedarray-pool":526}],291:[function(t,e,r){"use strict";var n=t("glslify");r.boxVertex=n(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 vertex;\n\nuniform vec2 cornerA, cornerB;\n\nvoid main() {\n  gl_Position = vec4(mix(cornerA, cornerB, vertex), 0, 1);\n}\n"]),r.boxFragment=n(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n  gl_FragColor = color;\n}\n"])},{glslify:398}],292:[function(t,e,r){"use strict";var n=t("gl-shader"),i=t("gl-buffer"),a=t("./lib/shaders");function o(t,e,r){this.plot=t,this.boxBuffer=e,this.boxShader=r,this.enabled=!0,this.selectBox=[1/0,1/0,-1/0,-1/0],this.borderColor=[0,0,0,1],this.innerFill=!1,this.innerColor=[0,0,0,.25],this.outerFill=!0,this.outerColor=[0,0,0,.5],this.borderWidth=10}e.exports=function(t,e){var r=t.gl,s=i(r,[0,0,0,1,1,0,1,1]),l=n(r,a.boxVertex,a.boxFragment),c=new o(t,s,l);return c.update(e),t.addOverlay(c),c};var s=o.prototype;s.draw=function(){if(this.enabled){var t=this.plot,e=this.selectBox,r=this.borderWidth,n=(this.innerFill,this.innerColor),i=(this.outerFill,this.outerColor),a=this.borderColor,o=t.box,s=t.screenBox,l=t.dataBox,c=t.viewBox,u=t.pixelRatio,h=(e[0]-l[0])*(c[2]-c[0])/(l[2]-l[0])+c[0],f=(e[1]-l[1])*(c[3]-c[1])/(l[3]-l[1])+c[1],p=(e[2]-l[0])*(c[2]-c[0])/(l[2]-l[0])+c[0],d=(e[3]-l[1])*(c[3]-c[1])/(l[3]-l[1])+c[1];if(h=Math.max(h,c[0]),f=Math.max(f,c[1]),p=Math.min(p,c[2]),d=Math.min(d,c[3]),!(p<h||d<f)){o.bind();var g=s[2]-s[0],v=s[3]-s[1];if(this.outerFill&&(o.drawBox(0,0,g,f,i),o.drawBox(0,f,h,d,i),o.drawBox(0,d,g,v,i),o.drawBox(p,f,g,d,i)),this.innerFill&&o.drawBox(h,f,p,d,n),r>0){var m=r*u;o.drawBox(h-m,f-m,p+m,f+m,a),o.drawBox(h-m,d-m,p+m,d+m,a),o.drawBox(h-m,f-m,h+m,d+m,a),o.drawBox(p-m,f-m,p+m,d+m,a)}}}},s.update=function(t){t=t||{},this.innerFill=!!t.innerFill,this.outerFill=!!t.outerFill,this.innerColor=(t.innerColor||[0,0,0,.5]).slice(),this.outerColor=(t.outerColor||[0,0,0,.5]).slice(),this.borderColor=(t.borderColor||[0,0,0,1]).slice(),this.borderWidth=t.borderWidth||0,this.selectBox=(t.selectBox||this.selectBox).slice()},s.dispose=function(){this.boxBuffer.dispose(),this.boxShader.dispose(),this.plot.removeOverlay(this)}},{"./lib/shaders":291,"gl-buffer":234,"gl-shader":294}],293:[function(t,e,r){"use strict";e.exports=function(t,e){var r=n(t,e),a=i.mallocUint8(e[0]*e[1]*4);return new c(t,r,a)};var n=t("gl-fbo"),i=t("typedarray-pool"),a=t("ndarray"),o=t("bit-twiddle").nextPow2,s=t("cwise/lib/wrapper")({args:["array",{offset:[0,0,1],array:0},{offset:[0,0,2],array:0},{offset:[0,0,3],array:0},"scalar","scalar","index"],pre:{body:"{this_closestD2=1e8,this_closestX=-1,this_closestY=-1}",args:[],thisVars:["this_closestD2","this_closestX","this_closestY"],localVars:[]},body:{body:"{if(_inline_16_arg0_<255||_inline_16_arg1_<255||_inline_16_arg2_<255||_inline_16_arg3_<255){var _inline_16_l=_inline_16_arg4_-_inline_16_arg6_[0],_inline_16_a=_inline_16_arg5_-_inline_16_arg6_[1],_inline_16_f=_inline_16_l*_inline_16_l+_inline_16_a*_inline_16_a;_inline_16_f<this_closestD2&&(this_closestD2=_inline_16_f,this_closestX=_inline_16_arg6_[0],this_closestY=_inline_16_arg6_[1])}}",args:[{name:"_inline_16_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_16_arg1_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_16_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_16_arg3_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_16_arg4_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_16_arg5_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_16_arg6_",lvalue:!1,rvalue:!0,count:4}],thisVars:["this_closestD2","this_closestX","this_closestY"],localVars:["_inline_16_a","_inline_16_f","_inline_16_l"]},post:{body:"{return[this_closestX,this_closestY,this_closestD2]}",args:[],thisVars:["this_closestD2","this_closestX","this_closestY"],localVars:[]},debug:!1,funcName:"cwise",blockSize:64});function l(t,e,r,n,i){this.coord=[t,e],this.id=r,this.value=n,this.distance=i}function c(t,e,r){this.gl=t,this.fbo=e,this.buffer=r,this._readTimeout=null;var n=this;this._readCallback=function(){n.gl&&(e.bind(),t.readPixels(0,0,e.shape[0],e.shape[1],t.RGBA,t.UNSIGNED_BYTE,n.buffer),n._readTimeout=null)}}var u=c.prototype;Object.defineProperty(u,"shape",{get:function(){return this.gl?this.fbo.shape.slice():[0,0]},set:function(t){if(this.gl){this.fbo.shape=t;var e=this.fbo.shape[0],r=this.fbo.shape[1];if(r*e*4>this.buffer.length){i.free(this.buffer);for(var n=this.buffer=i.mallocUint8(o(r*e*4)),a=0;a<r*e*4;++a)n[a]=255}return t}}}),u.begin=function(){var t=this.gl;this.shape;t&&(this.fbo.bind(),t.clearColor(1,1,1,1),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT))},u.end=function(){var t=this.gl;t&&(t.bindFramebuffer(t.FRAMEBUFFER,null),this._readTimeout||clearTimeout(this._readTimeout),this._readTimeout=setTimeout(this._readCallback,1))},u.query=function(t,e,r){if(!this.gl)return null;var n=this.fbo.shape.slice();t|=0,e|=0,"number"!=typeof r&&(r=1);var i=0|Math.min(Math.max(t-r,0),n[0]),o=0|Math.min(Math.max(t+r,0),n[0]),c=0|Math.min(Math.max(e-r,0),n[1]),u=0|Math.min(Math.max(e+r,0),n[1]);if(o<=i||u<=c)return null;var h=[o-i,u-c],f=a(this.buffer,[h[0],h[1],4],[4,4*n[0],1],4*(i+n[0]*c)),p=s(f.hi(h[0],h[1],1),r,r),d=p[0],g=p[1];return d<0||Math.pow(this.radius,2)<p[2]?null:new l(d+i|0,g+c|0,f.get(d,g,0),[f.get(d,g,1),f.get(d,g,2),f.get(d,g,3)],Math.sqrt(p[2]))},u.dispose=function(){this.gl&&(this.fbo.dispose(),i.free(this.buffer),this.gl=null,this._readTimeout&&clearTimeout(this._readTimeout))}},{"bit-twiddle":80,"cwise/lib/wrapper":137,"gl-fbo":242,ndarray:439,"typedarray-pool":526}],294:[function(t,e,r){"use strict";var n=t("./lib/create-uniforms"),i=t("./lib/create-attributes"),a=t("./lib/reflect"),o=t("./lib/shader-cache"),s=t("./lib/runtime-reflect"),l=t("./lib/GLError");function c(t){this.gl=t,this.gl.lastAttribCount=0,this._vref=this._fref=this._relink=this.vertShader=this.fragShader=this.program=this.attributes=this.uniforms=this.types=null}var u=c.prototype;function h(t,e){return t.name<e.name?-1:1}u.bind=function(){var t;this.program||this._relink();var e=this.gl.getProgramParameter(this.program,this.gl.ACTIVE_ATTRIBUTES),r=this.gl.lastAttribCount;if(e>r)for(t=r;t<e;t++)this.gl.enableVertexAttribArray(t);else if(r>e)for(t=e;t<r;t++)this.gl.disableVertexAttribArray(t);this.gl.lastAttribCount=e,this.gl.useProgram(this.program)},u.dispose=function(){for(var t=this.gl.lastAttribCount,e=0;e<t;e++)this.gl.disableVertexAttribArray(e);this.gl.lastAttribCount=0,this._fref&&this._fref.dispose(),this._vref&&this._vref.dispose(),this.attributes=this.types=this.vertShader=this.fragShader=this.program=this._relink=this._fref=this._vref=null},u.update=function(t,e,r,c){if(!e||1===arguments.length){var u=t;t=u.vertex,e=u.fragment,r=u.uniforms,c=u.attributes}var f=this,p=f.gl,d=f._vref;f._vref=o.shader(p,p.VERTEX_SHADER,t),d&&d.dispose(),f.vertShader=f._vref.shader;var g=this._fref;if(f._fref=o.shader(p,p.FRAGMENT_SHADER,e),g&&g.dispose(),f.fragShader=f._fref.shader,!r||!c){var v=p.createProgram();if(p.attachShader(v,f.fragShader),p.attachShader(v,f.vertShader),p.linkProgram(v),!p.getProgramParameter(v,p.LINK_STATUS)){var m=p.getProgramInfoLog(v);throw new l(m,"Error linking program:"+m)}r=r||s.uniforms(p,v),c=c||s.attributes(p,v),p.deleteProgram(v)}(c=c.slice()).sort(h);var y,x=[],b=[],_=[];for(y=0;y<c.length;++y){var w=c[y];if(w.type.indexOf("mat")>=0){for(var k=0|w.type.charAt(w.type.length-1),A=new Array(k),M=0;M<k;++M)A[M]=_.length,b.push(w.name+"["+M+"]"),"number"==typeof w.location?_.push(w.location+M):Array.isArray(w.location)&&w.location.length===k&&"number"==typeof w.location[M]?_.push(0|w.location[M]):_.push(-1);x.push({name:w.name,type:w.type,locations:A})}else x.push({name:w.name,type:w.type,locations:[_.length]}),b.push(w.name),"number"==typeof w.location?_.push(0|w.location):_.push(-1)}var T=0;for(y=0;y<_.length;++y)if(_[y]<0){for(;_.indexOf(T)>=0;)T+=1;_[y]=T}var S=new Array(r.length);function E(){f.program=o.program(p,f._vref,f._fref,b,_);for(var t=0;t<r.length;++t)S[t]=p.getUniformLocation(f.program,r[t].name)}E(),f._relink=E,f.types={uniforms:a(r),attributes:a(c)},f.attributes=i(p,f,x,_),Object.defineProperty(f,"uniforms",n(p,f,r,S))},e.exports=function(t,e,r,n,i){var a=new c(t);return a.update(e,r,n,i),a}},{"./lib/GLError":295,"./lib/create-attributes":296,"./lib/create-uniforms":297,"./lib/reflect":298,"./lib/runtime-reflect":299,"./lib/shader-cache":300}],295:[function(t,e,r){function n(t,e,r){this.shortMessage=e||"",this.longMessage=r||"",this.rawError=t||"",this.message="gl-shader: "+(e||t||"")+(r?"\n"+r:""),this.stack=(new Error).stack}n.prototype=new Error,n.prototype.name="GLError",n.prototype.constructor=n,e.exports=n},{}],296:[function(t,e,r){"use strict";e.exports=function(t,e,r,i){for(var a={},l=0,c=r.length;l<c;++l){var u=r[l],h=u.name,f=u.type,p=u.locations;switch(f){case"bool":case"int":case"float":o(t,e,p[0],i,1,a,h);break;default:if(f.indexOf("vec")>=0){var d=f.charCodeAt(f.length-1)-48;if(d<2||d>4)throw new n("","Invalid data type for attribute "+h+": "+f);o(t,e,p[0],i,d,a,h)}else{if(!(f.indexOf("mat")>=0))throw new n("","Unknown data type for attribute "+h+": "+f);var d=f.charCodeAt(f.length-1)-48;if(d<2||d>4)throw new n("","Invalid data type for attribute "+h+": "+f);s(t,e,p,i,d,a,h)}}}return a};var n=t("./GLError");function i(t,e,r,n,i,a){this._gl=t,this._wrapper=e,this._index=r,this._locations=n,this._dimension=i,this._constFunc=a}var a=i.prototype;function o(t,e,r,n,a,o,s){for(var l=["gl","v"],c=[],u=0;u<a;++u)l.push("x"+u),c.push("x"+u);l.push("if(x0.length===void 0){return gl.vertexAttrib"+a+"f(v,"+c.join()+")}else{return gl.vertexAttrib"+a+"fv(v,x0)}");var h=Function.apply(null,l),f=new i(t,e,r,n,a,h);Object.defineProperty(o,s,{set:function(e){return t.disableVertexAttribArray(n[r]),h(t,n[r],e),e},get:function(){return f},enumerable:!0})}function s(t,e,r,n,i,a,s){for(var l=new Array(i),c=new Array(i),u=0;u<i;++u)o(t,e,r[u],n,i,l,u),c[u]=l[u];Object.defineProperty(l,"location",{set:function(t){if(Array.isArray(t))for(var e=0;e<i;++e)c[e].location=t[e];else for(e=0;e<i;++e)c[e].location=t+e;return t},get:function(){for(var t=new Array(i),e=0;e<i;++e)t[e]=n[r[e]];return t},enumerable:!0}),l.pointer=function(e,a,o,s){e=e||t.FLOAT,a=!!a,o=o||i*i,s=s||0;for(var l=0;l<i;++l){var c=n[r[l]];t.vertexAttribPointer(c,i,e,a,o,s+l*i),t.enableVertexAttribArray(c)}};var h=new Array(i),f=t["vertexAttrib"+i+"fv"];Object.defineProperty(a,s,{set:function(e){for(var a=0;a<i;++a){var o=n[r[a]];if(t.disableVertexAttribArray(o),Array.isArray(e[0]))f.call(t,o,e[a]);else{for(var s=0;s<i;++s)h[s]=e[i*a+s];f.call(t,o,h)}}return e},get:function(){return l},enumerable:!0})}a.pointer=function(t,e,r,n){var i=this._gl,a=this._locations[this._index];i.vertexAttribPointer(a,this._dimension,t||i.FLOAT,!!e,r||0,n||0),i.enableVertexAttribArray(a)},a.set=function(t,e,r,n){return this._constFunc(this._locations[this._index],t,e,r,n)},Object.defineProperty(a,"location",{get:function(){return this._locations[this._index]},set:function(t){return t!==this._locations[this._index]&&(this._locations[this._index]=0|t,this._wrapper.program=null),0|t}})},{"./GLError":295}],297:[function(t,e,r){"use strict";var n=t("./reflect"),i=t("./GLError");function a(t){return new Function("y","return function(){return y}")(t)}function o(t,e){for(var r=new Array(t),n=0;n<t;++n)r[n]=e;return r}e.exports=function(t,e,r,s){function l(t,e,r){switch(r){case"bool":case"int":case"sampler2D":case"samplerCube":return"gl.uniform1i(locations["+e+"],obj"+t+")";case"float":return"gl.uniform1f(locations["+e+"],obj"+t+")";default:var n=r.indexOf("vec");if(!(0<=n&&n<=1&&r.length===4+n)){if(0===r.indexOf("mat")&&4===r.length){var a=r.charCodeAt(r.length-1)-48;if(a<2||a>4)throw new i("","Invalid uniform dimension type for matrix "+name+": "+r);return"gl.uniformMatrix"+a+"fv(locations["+e+"],false,obj"+t+")"}throw new i("","Unknown uniform data type for "+name+": "+r)}var a=r.charCodeAt(r.length-1)-48;if(a<2||a>4)throw new i("","Invalid data type");switch(r.charAt(0)){case"b":case"i":return"gl.uniform"+a+"iv(locations["+e+"],obj"+t+")";case"v":return"gl.uniform"+a+"fv(locations["+e+"],obj"+t+")";default:throw new i("","Unrecognized data type for vector "+name+": "+r)}}}function c(e){for(var n=["return function updateProperty(obj){"],i=function t(e,r){if("object"!=typeof r)return[[e,r]];var n=[];for(var i in r){var a=r[i],o=e;parseInt(i)+""===i?o+="["+i+"]":o+="."+i,"object"==typeof a?n.push.apply(n,t(o,a)):n.push([o,a])}return n}("",e),a=0;a<i.length;++a){var o=i[a],c=o[0],u=o[1];s[u]&&n.push(l(c,u,r[u].type))}n.push("return obj}");var h=new Function("gl","locations",n.join("\n"));return h(t,s)}function u(n,l,u){if("object"==typeof u){var f=h(u);Object.defineProperty(n,l,{get:a(f),set:c(u),enumerable:!0,configurable:!1})}else s[u]?Object.defineProperty(n,l,{get:(p=u,new Function("gl","wrapper","locations","return function(){return gl.getUniform(wrapper.program,locations["+p+"])}")(t,e,s)),set:c(u),enumerable:!0,configurable:!1}):n[l]=function(t){switch(t){case"bool":return!1;case"int":case"sampler2D":case"samplerCube":case"float":return 0;default:var e=t.indexOf("vec");if(0<=e&&e<=1&&t.length===4+e){var r=t.charCodeAt(t.length-1)-48;if(r<2||r>4)throw new i("","Invalid data type");return"b"===t.charAt(0)?o(r,!1):o(r,0)}if(0===t.indexOf("mat")&&4===t.length){var r=t.charCodeAt(t.length-1)-48;if(r<2||r>4)throw new i("","Invalid uniform dimension type for matrix "+name+": "+t);return o(r*r,0)}throw new i("","Unknown uniform data type for "+name+": "+t)}}(r[u].type);var p}function h(t){var e;if(Array.isArray(t)){e=new Array(t.length);for(var r=0;r<t.length;++r)u(e,r,t[r])}else for(var n in e={},t)u(e,n,t[n]);return e}var f=n(r,!0);return{get:a(h(f)),set:c(f),enumerable:!0,configurable:!0}}},{"./GLError":295,"./reflect":298}],298:[function(t,e,r){"use strict";e.exports=function(t,e){for(var r={},n=0;n<t.length;++n)for(var i=t[n].name,a=i.split("."),o=r,s=0;s<a.length;++s){var l=a[s].split("[");if(l.length>1){l[0]in o||(o[l[0]]=[]),o=o[l[0]];for(var c=1;c<l.length;++c){var u=parseInt(l[c]);c<l.length-1||s<a.length-1?(u in o||(c<l.length-1?o[u]=[]:o[u]={}),o=o[u]):o[u]=e?n:t[n].type}}else s<a.length-1?(l[0]in o||(o[l[0]]={}),o=o[l[0]]):o[l[0]]=e?n:t[n].type}return r}},{}],299:[function(t,e,r){"use strict";r.uniforms=function(t,e){for(var r=t.getProgramParameter(e,t.ACTIVE_UNIFORMS),n=[],i=0;i<r;++i){var o=t.getActiveUniform(e,i);if(o){var s=a(t,o.type);if(o.size>1)for(var l=0;l<o.size;++l)n.push({name:o.name.replace("[0]","["+l+"]"),type:s});else n.push({name:o.name,type:s})}}return n},r.attributes=function(t,e){for(var r=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES),n=[],i=0;i<r;++i){var o=t.getActiveAttrib(e,i);o&&n.push({name:o.name,type:a(t,o.type)})}return n};var n={FLOAT:"float",FLOAT_VEC2:"vec2",FLOAT_VEC3:"vec3",FLOAT_VEC4:"vec4",INT:"int",INT_VEC2:"ivec2",INT_VEC3:"ivec3",INT_VEC4:"ivec4",BOOL:"bool",BOOL_VEC2:"bvec2",BOOL_VEC3:"bvec3",BOOL_VEC4:"bvec4",FLOAT_MAT2:"mat2",FLOAT_MAT3:"mat3",FLOAT_MAT4:"mat4",SAMPLER_2D:"sampler2D",SAMPLER_CUBE:"samplerCube"},i=null;function a(t,e){if(!i){var r=Object.keys(n);i={};for(var a=0;a<r.length;++a){var o=r[a];i[t[o]]=n[o]}}return i[e]}},{}],300:[function(t,e,r){"use strict";r.shader=function(t,e,r){return u(t).getShaderReference(e,r)},r.program=function(t,e,r,n,i){return u(t).getProgram(e,r,n,i)};var n=t("./GLError"),i=t("gl-format-compiler-error"),a=new("undefined"==typeof WeakMap?t("weakmap-shim"):WeakMap),o=0;function s(t,e,r,n,i,a,o){this.id=t,this.src=e,this.type=r,this.shader=n,this.count=a,this.programs=[],this.cache=o}function l(t){this.gl=t,this.shaders=[{},{}],this.programs={}}s.prototype.dispose=function(){if(0==--this.count){for(var t=this.cache,e=t.gl,r=this.programs,n=0,i=r.length;n<i;++n){var a=t.programs[r[n]];a&&(delete t.programs[n],e.deleteProgram(a))}e.deleteShader(this.shader),delete t.shaders[this.type===e.FRAGMENT_SHADER|0][this.src]}};var c=l.prototype;function u(t){var e=a.get(t);return e||(e=new l(t),a.set(t,e)),e}c.getShaderReference=function(t,e){var r=this.gl,a=this.shaders[t===r.FRAGMENT_SHADER|0],l=a[e];if(l&&r.isShader(l.shader))l.count+=1;else{var c=function(t,e,r){var a=t.createShader(e);if(t.shaderSource(a,r),t.compileShader(a),!t.getShaderParameter(a,t.COMPILE_STATUS)){var o=t.getShaderInfoLog(a);try{var s=i(o,r,e)}catch(t){throw console.warn("Failed to format compiler error: "+t),new n(o,"Error compiling shader:\n"+o)}throw new n(o,s.short,s.long)}return a}(r,t,e);l=a[e]=new s(o++,e,t,c,[],1,this)}return l},c.getProgram=function(t,e,r,i){var a=[t.id,e.id,r.join(":"),i.join(":")].join("@"),o=this.programs[a];return o&&this.gl.isProgram(o)||(this.programs[a]=o=function(t,e,r,i,a){var o=t.createProgram();t.attachShader(o,e),t.attachShader(o,r);for(var s=0;s<i.length;++s)t.bindAttribLocation(o,a[s],i[s]);if(t.linkProgram(o),!t.getProgramParameter(o,t.LINK_STATUS)){var l=t.getProgramInfoLog(o);throw new n(l,"Error linking program: "+l)}return o}(this.gl,t.shader,e.shader,r,i),t.programs.push(a),e.programs.push(a)),o}},{"./GLError":295,"gl-format-compiler-error":243,"weakmap-shim":536}],301:[function(t,e,r){"use strict";function n(t){this.plot=t,this.enable=[!0,!0,!1,!1],this.width=[1,1,1,1],this.color=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.center=[1/0,1/0]}e.exports=function(t,e){var r=new n(t);return r.update(e),t.addOverlay(r),r};var i=n.prototype;i.update=function(t){t=t||{},this.enable=(t.enable||[!0,!0,!1,!1]).slice(),this.width=(t.width||[1,1,1,1]).slice(),this.color=(t.color||[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]).map(function(t){return t.slice()}),this.center=(t.center||[1/0,1/0]).slice(),this.plot.setOverlayDirty()},i.draw=function(){var t=this.enable,e=this.width,r=this.color,n=this.center,i=this.plot,a=i.line,o=i.dataBox,s=i.viewBox;if(a.bind(),o[0]<=n[0]&&n[0]<=o[2]&&o[1]<=n[1]&&n[1]<=o[3]){var l=s[0]+(n[0]-o[0])/(o[2]-o[0])*(s[2]-s[0]),c=s[1]+(n[1]-o[1])/(o[3]-o[1])*(s[3]-s[1]);t[0]&&a.drawLine(l,c,s[0],c,e[0],r[0]),t[1]&&a.drawLine(l,c,l,s[1],e[1],r[1]),t[2]&&a.drawLine(l,c,s[2],c,e[2],r[2]),t[3]&&a.drawLine(l,c,l,s[3],e[3],r[3])}},i.dispose=function(){this.plot.removeOverlay(this)}},{}],302:[function(t,e,r){"use strict";var n=t("glslify"),i=t("gl-shader"),a=n(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, color;\nattribute float weight;\n\nuniform mat4 model, view, projection;\nuniform vec3 coordinates[3];\nuniform vec4 colors[3];\nuniform vec2 screenShape;\nuniform float lineWidth;\n\nvarying vec4 fragColor;\n\nvoid main() {\n  vec3 vertexPosition = mix(coordinates[0],\n    mix(coordinates[2], coordinates[1], 0.5 * (position + 1.0)), abs(position));\n\n  vec4 clipPos = projection * view * model * vec4(vertexPosition, 1.0);\n  vec2 clipOffset = (projection * view * model * vec4(color, 0.0)).xy;\n  vec2 delta = weight * clipOffset * screenShape;\n  vec2 lineOffset = normalize(vec2(delta.y, -delta.x)) / screenShape;\n\n  gl_Position   = vec4(clipPos.xy + clipPos.w * 0.5 * lineWidth * lineOffset, clipPos.z, clipPos.w);\n  fragColor     = color.x * colors[0] + color.y * colors[1] + color.z * colors[2];\n}\n"]),o=n(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n  gl_FragColor = fragColor;\n}"]);e.exports=function(t){return i(t,a,o,null,[{name:"position",type:"vec3"},{name:"color",type:"vec3"},{name:"weight",type:"float"}])}},{"gl-shader":294,glslify:398}],303:[function(t,e,r){"use strict";var n=t("gl-buffer"),i=t("gl-vao"),a=t("./shaders/index");e.exports=function(t,e){var r=[];function o(t,e,n,i,a,o){var s=[t,e,n,0,0,0,1];s[i+3]=1,s[i]=a,r.push.apply(r,s),s[6]=-1,r.push.apply(r,s),s[i]=o,r.push.apply(r,s),r.push.apply(r,s),s[6]=1,r.push.apply(r,s),s[i]=a,r.push.apply(r,s)}o(0,0,0,0,0,1),o(0,0,0,1,0,1),o(0,0,0,2,0,1),o(1,0,0,1,-1,1),o(1,0,0,2,-1,1),o(0,1,0,0,-1,1),o(0,1,0,2,-1,1),o(0,0,1,0,-1,1),o(0,0,1,1,-1,1);var l=n(t,r),c=i(t,[{type:t.FLOAT,buffer:l,size:3,offset:0,stride:28},{type:t.FLOAT,buffer:l,size:3,offset:12,stride:28},{type:t.FLOAT,buffer:l,size:1,offset:24,stride:28}]),u=a(t);u.attributes.position.location=0,u.attributes.color.location=1,u.attributes.weight.location=2;var h=new s(t,l,c,u);return h.update(e),h};var o=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function s(t,e,r,n){this.gl=t,this.buffer=e,this.vao=r,this.shader=n,this.pixelRatio=1,this.bounds=[[-1e3,-1e3,-1e3],[1e3,1e3,1e3]],this.position=[0,0,0],this.lineWidth=[2,2,2],this.colors=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.enabled=[!0,!0,!0],this.drawSides=[!0,!0,!0],this.axes=null}var l=s.prototype,c=[0,0,0],u=[0,0,0],h=[0,0];l.isTransparent=function(){return!1},l.drawTransparent=function(t){},l.draw=function(t){var e=this.gl,r=this.vao,n=this.shader;r.bind(),n.bind();var i,a=t.model||o,s=t.view||o,l=t.projection||o;this.axes&&(i=this.axes.lastCubeProps.axis);for(var f=c,p=u,d=0;d<3;++d)i&&i[d]<0?(f[d]=this.bounds[0][d],p[d]=this.bounds[1][d]):(f[d]=this.bounds[1][d],p[d]=this.bounds[0][d]);h[0]=e.drawingBufferWidth,h[1]=e.drawingBufferHeight,n.uniforms.model=a,n.uniforms.view=s,n.uniforms.projection=l,n.uniforms.coordinates=[this.position,f,p],n.uniforms.colors=this.colors,n.uniforms.screenShape=h;for(d=0;d<3;++d)n.uniforms.lineWidth=this.lineWidth[d]*this.pixelRatio,this.enabled[d]&&(r.draw(e.TRIANGLES,6,6*d),this.drawSides[d]&&r.draw(e.TRIANGLES,12,18+12*d));r.unbind()},l.update=function(t){t&&("bounds"in t&&(this.bounds=t.bounds),"position"in t&&(this.position=t.position),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"colors"in t&&(this.colors=t.colors),"enabled"in t&&(this.enabled=t.enabled),"drawSides"in t&&(this.drawSides=t.drawSides))},l.dispose=function(){this.vao.dispose(),this.buffer.dispose(),this.shader.dispose()}},{"./shaders/index":302,"gl-buffer":234,"gl-vao":316}],304:[function(t,e,r){var n=t("glslify"),i=n(["precision mediump float;\n#define GLSLIFY 1\n\nvec3 getOrthogonalVector(vec3 v) {\n  // Return up-vector for only-z vector.\n  // Return ax + by + cz = 0, a point that lies on the plane that has v as a normal and that isn't (0,0,0).\n  // From the above if-statement we have ||a|| > 0  U  ||b|| > 0.\n  // Assign z = 0, x = -b, y = a:\n  // a*-b + b*a + c*0 = -ba + ba + 0 = 0\n  if (v.x*v.x > v.z*v.z || v.y*v.y > v.z*v.z) {\n    return normalize(vec3(-v.y, v.x, 0.0));\n  } else {\n    return normalize(vec3(0.0, v.z, -v.y));\n  }\n}\n\n// Calculate the tube vertex and normal at the given index.\n//\n// The returned vertex is for a tube ring with its center at origin, radius of length(d), pointing in the direction of d.\n//\n// Each tube segment is made up of a ring of vertices.\n// These vertices are used to make up the triangles of the tube by connecting them together in the vertex array.\n// The indexes of tube segments run from 0 to 8.\n//\nvec3 getTubePosition(vec3 d, float index, out vec3 normal) {\n  float segmentCount = 8.0;\n\n  float angle = 2.0 * 3.14159 * (index / segmentCount);\n\n  vec3 u = getOrthogonalVector(d);\n  vec3 v = normalize(cross(u, d));\n\n  vec3 x = u * cos(angle) * length(d);\n  vec3 y = v * sin(angle) * length(d);\n  vec3 v3 = x + y;\n\n  normal = normalize(v3);\n\n  return v3;\n}\n\nattribute vec4 vector;\nattribute vec4 color, position;\nattribute vec2 uv;\nuniform float vectorScale;\nuniform float tubeScale;\n\nuniform mat4 model\n           , view\n           , projection\n           , inverseModel;\nuniform vec3 eyePosition\n           , lightPosition;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data\n           , f_position;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  // Scale the vector magnitude to stay constant with\n  // model & view changes.\n  vec3 normal;\n  vec3 XYZ = getTubePosition(mat3(model) * (tubeScale * vector.w * normalize(vector.xyz)), position.w, normal);\n  vec4 tubePosition = model * vec4(position.xyz, 1.0) + vec4(XYZ, 0.0);\n\n  //Lighting geometry parameters\n  vec4 cameraCoordinate = view * tubePosition;\n  cameraCoordinate.xyz /= cameraCoordinate.w;\n  f_lightDirection = lightPosition - cameraCoordinate.xyz;\n  f_eyeDirection   = eyePosition - cameraCoordinate.xyz;\n  f_normal = normalize((vec4(normal,0.0) * inverseModel).xyz);\n\n  // vec4 m_position  = model * vec4(tubePosition, 1.0);\n  vec4 t_position  = view * tubePosition;\n  gl_Position      = projection * t_position;\n\n  f_color          = color;\n  f_data           = tubePosition.xyz;\n  f_position       = position.xyz;\n  f_uv             = uv;\n}\n"]),a=n(["#extension GL_OES_standard_derivatives : enable\n\nprecision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution(float x, float roughness) {\n  float NdotH = max(x, 0.0001);\n  float cos2Alpha = NdotH * NdotH;\n  float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n  float roughness2 = roughness * roughness;\n  float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n  return exp(tan2Alpha / roughness2) / denom;\n}\n\nfloat cookTorranceSpecular(\n  vec3 lightDirection,\n  vec3 viewDirection,\n  vec3 surfaceNormal,\n  float roughness,\n  float fresnel) {\n\n  float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n  float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n  //Half angle vector\n  vec3 H = normalize(lightDirection + viewDirection);\n\n  //Geometric term\n  float NdotH = max(dot(surfaceNormal, H), 0.0);\n  float VdotH = max(dot(viewDirection, H), 0.000001);\n  float LdotH = max(dot(lightDirection, H), 0.000001);\n  float G1 = (2.0 * NdotH * VdotN) / VdotH;\n  float G2 = (2.0 * NdotH * LdotN) / LdotH;\n  float G = min(1.0, min(G1, G2));\n  \n  //Distribution term\n  float D = beckmannDistribution(NdotH, roughness);\n\n  //Fresnel term\n  float F = pow(1.0 - VdotN, fresnel);\n\n  //Multiply terms and done\n  return  G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n            , fresnel\n            , kambient\n            , kdiffuse\n            , kspecular\n            , opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data\n           , f_position;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n  vec3 N = normalize(f_normal);\n  vec3 L = normalize(f_lightDirection);\n  vec3 V = normalize(f_eyeDirection);\n\n  if(gl_FrontFacing) {\n    N = -N;\n  }\n\n  float specular = min(1.0, max(0.0, cookTorranceSpecular(L, V, N, roughness, fresnel)));\n  float diffuse  = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n  vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n  vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular,  1.0);\n\n  gl_FragColor = litColor * opacity;\n}\n"]),o=n(["precision mediump float;\n#define GLSLIFY 1\n\nvec3 getOrthogonalVector(vec3 v) {\n  // Return up-vector for only-z vector.\n  // Return ax + by + cz = 0, a point that lies on the plane that has v as a normal and that isn't (0,0,0).\n  // From the above if-statement we have ||a|| > 0  U  ||b|| > 0.\n  // Assign z = 0, x = -b, y = a:\n  // a*-b + b*a + c*0 = -ba + ba + 0 = 0\n  if (v.x*v.x > v.z*v.z || v.y*v.y > v.z*v.z) {\n    return normalize(vec3(-v.y, v.x, 0.0));\n  } else {\n    return normalize(vec3(0.0, v.z, -v.y));\n  }\n}\n\n// Calculate the tube vertex and normal at the given index.\n//\n// The returned vertex is for a tube ring with its center at origin, radius of length(d), pointing in the direction of d.\n//\n// Each tube segment is made up of a ring of vertices.\n// These vertices are used to make up the triangles of the tube by connecting them together in the vertex array.\n// The indexes of tube segments run from 0 to 8.\n//\nvec3 getTubePosition(vec3 d, float index, out vec3 normal) {\n  float segmentCount = 8.0;\n\n  float angle = 2.0 * 3.14159 * (index / segmentCount);\n\n  vec3 u = getOrthogonalVector(d);\n  vec3 v = normalize(cross(u, d));\n\n  vec3 x = u * cos(angle) * length(d);\n  vec3 y = v * sin(angle) * length(d);\n  vec3 v3 = x + y;\n\n  normal = normalize(v3);\n\n  return v3;\n}\n\nattribute vec4 vector;\nattribute vec4 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform float tubeScale;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  vec3 normal;\n  vec3 XYZ = getTubePosition(mat3(model) * (tubeScale * vector.w * normalize(vector.xyz)), position.w, normal);\n  vec4 tubePosition = model * vec4(position.xyz, 1.0) + vec4(XYZ, 0.0);\n\n  gl_Position = projection * view * tubePosition;\n  f_id        = id;\n  f_position  = position.xyz;\n}\n"]),s=n(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3  clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n\n  gl_FragColor = vec4(pickId, f_id.xyz);\n}"]);r.meshShader={vertex:i,fragment:a,attributes:[{name:"position",type:"vec4"},{name:"normal",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"},{name:"vector",type:"vec4"}]},r.pickShader={vertex:o,fragment:s,attributes:[{name:"position",type:"vec4"},{name:"id",type:"vec4"},{name:"vector",type:"vec4"}]}},{glslify:398}],305:[function(t,e,r){"use strict";var n=t("gl-shader"),i=t("gl-buffer"),a=t("gl-vao"),o=t("gl-texture2d"),s=t("normals"),l=t("gl-mat4/multiply"),c=t("gl-mat4/invert"),u=t("ndarray"),h=t("colormap"),f=t("simplicial-complex-contour"),p=t("typedarray-pool"),d=t("./shaders"),g=d.meshShader,v=d.pickShader,m=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function y(t,e,r,n,i,a,o,s,l,c,u,h,f,p,d,g,v,y,x,b,_,w,k,A){this.gl=t,this.cells=[],this.positions=[],this.intensity=[],this.texture=e,this.dirty=!0,this.triShader=r,this.pickShader=n,this.trianglePositions=i,this.triangleVectors=a,this.triangleColors=s,this.triangleNormals=c,this.triangleUVs=l,this.triangleIds=o,this.triangleVAO=u,this.triangleCount=0,this.lineWidth=1,this.edgePositions=h,this.edgeColors=p,this.edgeUVs=d,this.edgeIds=f,this.edgeVAO=g,this.edgeCount=0,this.pointPositions=v,this.pointColors=x,this.pointUVs=b,this.pointSizes=_,this.pointIds=y,this.pointVAO=w,this.pointCount=0,this.contourLineWidth=1,this.contourPositions=k,this.contourVAO=A,this.contourCount=0,this.contourColor=[0,0,0],this.contourEnable=!1,this.pickId=1,this.bounds=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]],this.clipBounds=[[-1/0,-1/0,-1/0],[1/0,1/0,1/0]],this.lightPosition=[1e5,1e5,0],this.ambientLight=.8,this.diffuseLight=.8,this.specularLight=2,this.roughness=.5,this.fresnel=1.5,this.opacity=1,this.tubeScale=1,this._model=m,this._view=m,this._projection=m,this._resolution=[1,1],this.pixelRatio=1}var x=y.prototype;function b(t){var e=n(t,v.vertex,v.fragment,null,v.attributes);return e.attributes.position.location=0,e.attributes.id.location=1,e.attributes.vector.location=5,e}x.isOpaque=function(){return this.opacity>=1},x.isTransparent=function(){return this.opacity<1},x.pickSlots=1,x.setPickBase=function(t){this.pickId=t},x.highlight=function(t){if(t&&this.contourEnable){for(var e=f(this.cells,this.intensity,t.intensity),r=e.cells,n=e.vertexIds,i=e.vertexWeights,a=r.length,o=p.mallocFloat32(6*a),s=0,l=0;l<a;++l)for(var c=r[l],u=0;u<2;++u){var h=c[0];2===c.length&&(h=c[u]);for(var d=n[h][0],g=n[h][1],v=i[h],m=1-v,y=this.positions[d],x=this.positions[g],b=0;b<3;++b)o[s++]=v*y[b]+m*x[b]}this.contourCount=s/3|0,this.contourPositions.update(o.subarray(0,s)),p.free(o)}else this.contourCount=0},x.update=function(t){t=t||{};var e=this.gl;this.dirty=!0,"contourEnable"in t&&(this.contourEnable=t.contourEnable),"contourColor"in t&&(this.contourColor=t.contourColor),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"lightPosition"in t&&(this.lightPosition=t.lightPosition),"opacity"in t&&(this.opacity=t.opacity),"ambient"in t&&(this.ambientLight=t.ambient),"diffuse"in t&&(this.diffuseLight=t.diffuse),"specular"in t&&(this.specularLight=t.specular),"roughness"in t&&(this.roughness=t.roughness),"fresnel"in t&&(this.fresnel=t.fresnel),t.texture?(this.texture.dispose(),this.texture=o(e,t.texture)):t.colormap&&(this.texture.shape=[256,256],this.texture.minFilter=e.LINEAR_MIPMAP_LINEAR,this.texture.magFilter=e.LINEAR,this.texture.setPixels(function(t){for(var e=h({colormap:t,nshades:256,format:"rgba"}),r=new Uint8Array(1024),n=0;n<256;++n){for(var i=e[n],a=0;a<3;++a)r[4*n+a]=i[a];r[4*n+3]=255*i[3]}return u(r,[256,256,4],[4,0,1])}(t.colormap)),this.texture.generateMipmap());var r=t.cells,n=t.positions,i=t.vectors;if(n&&r&&i){void 0!==t.tubeScale&&(this.tubeScale=t.tubeScale);var a=[],l=[],c=[],f=[],p=[],d=[],g=[],v=[],m=[],y=[],x=[],b=[],_=[],w=[],k=[];this.cells=r,this.positions=n,this.vectors=i;var A=t.vertexNormals,M=t.cellNormals,T=void 0===t.vertexNormalsEpsilon?1e-6:t.vertexNormalsEpsilon,S=void 0===t.faceNormalsEpsilon?1e-6:t.faceNormalsEpsilon;t.useFacetNormals&&!M&&(M=s.faceNormals(r,n,S)),M||A||(A=s.vertexNormals(r,n,T));var E=t.vertexColors,C=t.cellColors,L=t.meshColor||[1,1,1,1],z=t.vertexUVs,O=t.vertexIntensity,I=t.cellUVs,D=t.cellIntensity,P=1/0,R=-1/0;if(!z&&!I)if(O)if(t.vertexIntensityBounds)P=+t.vertexIntensityBounds[0],R=+t.vertexIntensityBounds[1];else for(var F=0;F<O.length;++F){var B=O[F];P=Math.min(P,B),R=Math.max(R,B)}else if(D)for(F=0;F<D.length;++F){B=D[F];P=Math.min(P,B),R=Math.max(R,B)}else for(F=0;F<n.length;++F){B=n[F][2];P=Math.min(P,B),R=Math.max(R,B)}this.intensity=O||(D?function(t,e,r){for(var n=new Array(e),i=0;i<e;++i)n[i]=0;var a=t.length;for(i=0;i<a;++i)for(var o=t[i],s=0;s<o.length;++s)n[o[s]]=r[i];return n}(r,n.length,D):function(t){for(var e=t.length,r=new Array(e),n=0;n<e;++n)r[n]=t[n][2];return r}(n));var N=t.pointSizes,j=t.pointSize||1;this.bounds=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]];for(F=0;F<n.length;++F)for(var V=n[F],U=0;U<3;++U)!isNaN(V[U])&&isFinite(V[U])&&(this.bounds[0][U]=Math.min(this.bounds[0][U],V[U]),this.bounds[1][U]=Math.max(this.bounds[1][U],V[U]));var q=0,H=0,G=0;t:for(F=0;F<r.length;++F){var Y=r[F];switch(Y.length){case 1:for(V=n[X=Y[0]],U=0;U<3;++U)if(isNaN(V[U])||!isFinite(V[U]))continue t;x.push(V[0],V[1],V[2],V[3]),3===(Z=E?E[X]:C?C[F]:L).length?b.push(Z[0],Z[1],Z[2],1):b.push(Z[0],Z[1],Z[2],Z[3]),$=z?z[X]:O?[(O[X]-P)/(R-P),0]:I?I[F]:D?[(D[F]-P)/(R-P),0]:[(V[2]-P)/(R-P),0],_.push($[0],$[1]),N?w.push(N[X]):w.push(j),k.push(F),G+=1;break;case 2:for(U=0;U<2;++U){V=n[X=Y[U]];for(var W=0;W<3;++W)if(isNaN(V[W])||!isFinite(V[W]))continue t}for(U=0;U<2;++U){V=n[X=Y[U]];g.push(V[0],V[1],V[2]),3===(Z=E?E[X]:C?C[F]:L).length?v.push(Z[0],Z[1],Z[2],1):v.push(Z[0],Z[1],Z[2],Z[3]),$=z?z[X]:O?[(O[X]-P)/(R-P),0]:I?I[F]:D?[(D[F]-P)/(R-P),0]:[(V[2]-P)/(R-P),0],m.push($[0],$[1]),y.push(F)}H+=1;break;case 3:for(U=0;U<3;++U)for(V=n[X=Y[U]],W=0;W<3;++W)if(isNaN(V[W])||!isFinite(V[W]))continue t;for(U=0;U<3;++U){var X;V=n[X=Y[2-U]];a.push(V[0],V[1],V[2],V[3]);var Z,$,J,K=i[X];l.push(K[0],K[1],K[2],K[3]),3===(Z=E?E[X]:C?C[F]:L).length?c.push(Z[0],Z[1],Z[2],1):c.push(Z[0],Z[1],Z[2],Z[3]),$=z?z[X]:O?[(O[X]-P)/(R-P),0]:I?I[F]:D?[(D[F]-P)/(R-P),0]:[(V[2]-P)/(R-P),0],p.push($[0],$[1]),J=A?A[X]:M[F],f.push(J[0],J[1],J[2]),d.push(F)}q+=1}}this.pointCount=G,this.edgeCount=H,this.triangleCount=q,this.pointPositions.update(x),this.pointColors.update(b),this.pointUVs.update(_),this.pointSizes.update(w),this.pointIds.update(new Uint32Array(k)),this.edgePositions.update(g),this.edgeColors.update(v),this.edgeUVs.update(m),this.edgeIds.update(new Uint32Array(y)),this.trianglePositions.update(a),this.triangleVectors.update(l),this.triangleColors.update(c),this.triangleUVs.update(p),this.triangleNormals.update(f),this.triangleIds.update(new Uint32Array(d))}},x.drawTransparent=x.draw=function(t){t=t||{};for(var e=this.gl,r=t.model||m,n=t.view||m,i=t.projection||m,a=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],o=0;o<3;++o)a[0][o]=Math.max(a[0][o],this.clipBounds[0][o]),a[1][o]=Math.min(a[1][o],this.clipBounds[1][o]);var s={model:r,view:n,projection:i,inverseModel:m.slice(),clipBounds:a,kambient:this.ambientLight,kdiffuse:this.diffuseLight,kspecular:this.specularLight,roughness:this.roughness,fresnel:this.fresnel,eyePosition:[0,0,0],lightPosition:[0,0,0],opacity:this.opacity,tubeScale:this.tubeScale,contourColor:this.contourColor,texture:0};s.inverseModel=c(s.inverseModel,s.model),e.disable(e.CULL_FACE),this.texture.bind(0);var u=new Array(16);l(u,s.view,s.model),l(u,s.projection,u),c(u,u);for(o=0;o<3;++o)s.eyePosition[o]=u[12+o]/u[15];var h=u[15];for(o=0;o<3;++o)h+=this.lightPosition[o]*u[4*o+3];for(o=0;o<3;++o){for(var f=u[12+o],p=0;p<3;++p)f+=u[4*p+o]*this.lightPosition[p];s.lightPosition[o]=f/h}if(this.triangleCount>0){var d=this.triShader;d.bind(),d.uniforms=s,this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind()}},x.drawPick=function(t){t=t||{};for(var e=this.gl,r=t.model||m,n=t.view||m,i=t.projection||m,a=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],o=0;o<3;++o)a[0][o]=Math.max(a[0][o],this.clipBounds[0][o]),a[1][o]=Math.min(a[1][o],this.clipBounds[1][o]);this._model=[].slice.call(r),this._view=[].slice.call(n),this._projection=[].slice.call(i),this._resolution=[e.drawingBufferWidth,e.drawingBufferHeight];var s={model:r,view:n,projection:i,clipBounds:a,tubeScale:this.tubeScale,pickId:this.pickId/255},l=this.pickShader;l.bind(),l.uniforms=s,this.triangleCount>0&&(this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind()),this.edgeCount>0&&(this.edgeVAO.bind(),e.lineWidth(this.lineWidth*this.pixelRatio),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind())},x.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=t.value[0]+256*t.value[1]+65536*t.value[2],r=this.cells[e],n=this.positions[r[1]].slice(0,3);return{index:e,position:n,intensity:this.intensity[r[1]],velocity:this.vectors[r[1]].slice(0,3),divergence:this.vectors[r[1]][3],dataCoordinate:n}},x.dispose=function(){this.texture.dispose(),this.triShader.dispose(),this.pickShader.dispose(),this.triangleVAO.dispose(),this.trianglePositions.dispose(),this.triangleVectors.dispose(),this.triangleColors.dispose(),this.triangleUVs.dispose(),this.triangleNormals.dispose(),this.triangleIds.dispose(),this.edgeVAO.dispose(),this.edgePositions.dispose(),this.edgeColors.dispose(),this.edgeUVs.dispose(),this.edgeIds.dispose(),this.pointVAO.dispose(),this.pointPositions.dispose(),this.pointColors.dispose(),this.pointUVs.dispose(),this.pointSizes.dispose(),this.pointIds.dispose(),this.contourVAO.dispose(),this.contourPositions.dispose()},e.exports=function(t,e){1===arguments.length&&(t=(e=t).gl);var r=e.triShader||function(t){var e=n(t,g.vertex,g.fragment,null,g.attributes);return e.attributes.position.location=0,e.attributes.color.location=2,e.attributes.uv.location=3,e.attributes.vector.location=5,e}(t),s=b(t),l=o(t,u(new Uint8Array([255,255,255,255]),[1,1,4]));l.generateMipmap(),l.minFilter=t.LINEAR_MIPMAP_LINEAR,l.magFilter=t.LINEAR;var c=i(t),h=i(t),f=i(t),p=i(t),d=i(t),v=i(t),m=a(t,[{buffer:c,type:t.FLOAT,size:4},{buffer:v,type:t.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:f,type:t.FLOAT,size:4},{buffer:p,type:t.FLOAT,size:2},{buffer:d,type:t.FLOAT,size:3},{buffer:h,type:t.FLOAT,size:4}]),x=i(t),_=i(t),w=i(t),k=i(t),A=a(t,[{buffer:x,type:t.FLOAT,size:3},{buffer:k,type:t.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:_,type:t.FLOAT,size:4},{buffer:w,type:t.FLOAT,size:2}]),M=i(t),T=i(t),S=i(t),E=i(t),C=i(t),L=a(t,[{buffer:M,type:t.FLOAT,size:3},{buffer:C,type:t.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:T,type:t.FLOAT,size:4},{buffer:S,type:t.FLOAT,size:2},{buffer:E,type:t.FLOAT,size:1}]),z=i(t),O=new y(t,l,r,s,c,h,v,f,p,d,m,x,k,_,w,A,M,C,T,S,E,L,z,a(t,[{buffer:z,type:t.FLOAT,size:3}]));return O.update(e),O}},{"./shaders":304,colormap:114,"gl-buffer":234,"gl-mat4/invert":258,"gl-mat4/multiply":260,"gl-shader":294,"gl-texture2d":311,"gl-vao":316,ndarray:439,normals:442,"simplicial-complex-contour":499,"typedarray-pool":526}],306:[function(t,e,r){"use strict";var n=t("gl-vec3"),i=t("gl-vec4"),a=function(t,e,r,a){for(var o=0,s=0;s<t.length;s++)for(var l=t[s].velocities,c=0;c<l.length;c++){var u=n.length(l[c]);u>o&&(o=u)}var h=t.map(function(t){return function(t,e,r,a){var o,s,l,c=t.points,u=t.velocities,h=t.divergences;n.set(n.create(),0,1,0),n.create(),n.create();n.create();for(var f=[],p=[],d=[],g=[],v=[],m=[],y=0,x=0,b=i.create(),_=i.create(),w=0;w<c.length;w++){o=c[w],s=u[w],l=h[w],0===e&&(l=.05*r),x=n.length(s)/a,b=i.create(),n.copy(b,s),b[3]=l;for(var k=0;k<8;k++)v[k]=[o[0],o[1],o[2],k];if(g.length>0)for(k=0;k<8;k++){var A=(k+1)%8;f.push(g[k],v[k],v[A],v[A],g[A],g[k]),d.push(_,b,b,b,_,_),m.push(y,x,x,x,y,y),p.push([f.length-6,f.length-5,f.length-4],[f.length-3,f.length-2,f.length-1])}var M=g;g=v,v=M,M=_,_=b,b=M,M=y,y=x,x=M}return{positions:f,cells:p,vectors:d,vertexIntensity:m}}(t,r,a,o)}),f=[],p=[],d=[],g=[];for(s=0;s<h.length;s++){var v=h[s],m=f.length;f=f.concat(v.positions),d=d.concat(v.vectors),g=g.concat(v.vertexIntensity);for(c=0;c<v.cells.length;c++){var y=v.cells[c],x=[];p.push(x);for(var b=0;b<y.length;b++)x.push(y[b]+m)}}return{positions:f,cells:p,vectors:d,vertexIntensity:g,colormap:e}},o=function(t,e){var r=n.create(),i=1e-4;n.add(r,t,[i,0,0]);var a=this.getVelocity(r);n.subtract(a,a,e),n.scale(a,a,1e4),n.add(r,t,[0,i,0]);var o=this.getVelocity(r);n.subtract(o,o,e),n.scale(o,o,1e4),n.add(r,t,[0,0,i]);var s=this.getVelocity(r);return n.subtract(s,s,e),n.scale(s,s,1e4),n.add(r,a,o),n.add(r,r,s),r},s=function(t){return f(t,this.vectors,this.meshgrid,this.clampBorders)},l=function(t,e){for(var r=0;r<t.length;r++){var n=t[r];if(n===e)return r;if(n>e)return r-1}return r},c=n.create(),u=n.create(),h=function(t,e,r){return t<e?e:t>r?r:t},f=function(t,e,r,i){var a=t[0],o=t[1],s=t[2],f=r[0].length,p=r[1].length,d=r[2].length,g=l(r[0],a),v=l(r[1],o),m=l(r[2],s),y=g+1,x=v+1,b=m+1;if(r[0][g]===a&&(y=g),r[1][v]===o&&(x=v),r[2][m]===s&&(b=m),i&&(g=h(g,0,f-1),y=h(y,0,f-1),v=h(v,0,p-1),x=h(x,0,p-1),m=h(m,0,d-1),b=h(b,0,d-1)),g<0||v<0||m<0||y>=f||x>=p||b>=d)return n.create();var _=(a-r[0][g])/(r[0][y]-r[0][g]),w=(o-r[1][v])/(r[1][x]-r[1][v]),k=(s-r[2][m])/(r[2][b]-r[2][m]);(_<0||_>1||isNaN(_))&&(_=0),(w<0||w>1||isNaN(w))&&(w=0),(k<0||k>1||isNaN(k))&&(k=0);var A=m*f*p,M=b*f*p,T=v*f,S=x*f,E=g,C=y,L=e[T+A+E],z=e[T+A+C],O=e[S+A+E],I=e[S+A+C],D=e[T+M+E],P=e[T+M+C],R=e[S+M+E],F=e[S+M+C],B=n.create();return n.lerp(B,L,z,_),n.lerp(c,O,I,_),n.lerp(B,B,c,w),n.lerp(c,D,P,_),n.lerp(u,R,F,_),n.lerp(c,c,u,w),n.lerp(B,B,c,k),B},p=function(t){var e=1/0;t.sort(function(t,e){return t-e});for(var r=1;r<t.length;r++){var n=Math.abs(t[r]-t[r-1]);n<e&&(e=n)}return e};e.exports=function(t,e){var r=t.startingPositions,i=t.maxLength||1e3,l=t.tubeSize||1,c=t.absoluteTubeSize;t.getDivergence||(t.getDivergence=o),t.getVelocity||(t.getVelocity=s),void 0===t.clampBorders&&(t.clampBorders=!0);var u=[],h=e[0][0],f=e[0][1],d=e[0][2],g=e[1][0],v=e[1][1],m=e[1][2],y=function(t,e){var r=e[0],n=e[1],i=e[2];return r>=h&&r<=g&&n>=f&&n<=v&&i>=d&&i<=m},x=10*n.distance(e[0],e[1])/i,b=x*x,_=1,w=0;n.create();r.length>=2&&(_=function(t){for(var e=[],r=[],n=[],i={},a={},o={},s=0;s<t.length;s++){var l=t[s],c=l[0],u=l[1],h=l[2];i[c]||(e.push(c),i[c]=!0),a[u]||(r.push(u),a[u]=!0),o[h]||(n.push(h),o[h]=!0)}var f=p(e),d=p(r),g=p(n),v=Math.min(f,d,g);return isFinite(v)?v:1}(r));for(var k=0;k<r.length;k++){var A=n.create();n.copy(A,r[k]);var M=[A],T=[],S=t.getVelocity(A),E=A;T.push(S);var C=[],L=t.getDivergence(A,S);(D=n.length(L))>w&&!isNaN(D)&&isFinite(D)&&(w=D),C.push(D),u.push({points:M,velocities:T,divergences:C});for(var z=0;z<100*i&&M.length<i&&y(0,A);){z++;var O=n.clone(S),I=n.squaredLength(O);if(0===I)break;if(I>b&&n.scale(O,O,x/Math.sqrt(I)),n.add(O,O,A),S=t.getVelocity(O),n.squaredDistance(E,O)-b>-1e-4*b){M.push(O),E=O,T.push(S);L=t.getDivergence(O,S);(D=n.length(L))>w&&!isNaN(D)&&isFinite(D)&&(w=D),C.push(D)}A=O}}for(k=0;k<C.length;k++){var D=C[k];!isNaN(D)&&isFinite(D)||(C[k]=w)}var P=a(u,t.colormap,w,_);return c?P.tubeScale=c:(0===w&&(w=1),P.tubeScale=.5*l*_/w),P},e.exports.createTubeMesh=t("./lib/tubemesh")},{"./lib/tubemesh":305,"gl-vec3":335,"gl-vec4":371}],307:[function(t,e,r){var n=t("gl-shader"),i=t("glslify"),a=i(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute vec3 f;\nattribute vec3 normal;\n\nuniform vec3 objectOffset;\nuniform mat4 model, view, projection, inverseModel;\nuniform vec3 lightPosition, eyePosition;\nuniform sampler2D colormap;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\nvarying vec4 vColor;\n\nvoid main() {\n  vec3 localCoordinate = vec3(uv.zw, f.x);\n  worldCoordinate = objectOffset + localCoordinate;\n  vec4 worldPosition = model * vec4(worldCoordinate, 1.0);\n  vec4 clipPosition = projection * view * worldPosition;\n  gl_Position = clipPosition;\n  kill = f.y;\n  value = f.z;\n  planeCoordinate = uv.xy;\n\n  vColor = texture2D(colormap, vec2(value, value));\n\n  //Lighting geometry parameters\n  vec4 cameraCoordinate = view * worldPosition;\n  cameraCoordinate.xyz /= cameraCoordinate.w;\n  lightDirection = lightPosition - cameraCoordinate.xyz;\n  eyeDirection   = eyePosition - cameraCoordinate.xyz;\n  surfaceNormal  = normalize((vec4(normal,0) * inverseModel).xyz);\n}\n"]),o=i(["precision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution(float x, float roughness) {\n  float NdotH = max(x, 0.0001);\n  float cos2Alpha = NdotH * NdotH;\n  float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n  float roughness2 = roughness * roughness;\n  float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n  return exp(tan2Alpha / roughness2) / denom;\n}\n\nfloat beckmannSpecular(\n  vec3 lightDirection,\n  vec3 viewDirection,\n  vec3 surfaceNormal,\n  float roughness) {\n  return beckmannDistribution(dot(surfaceNormal, normalize(lightDirection + viewDirection)), roughness);\n}\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 lowerBound, upperBound;\nuniform float contourTint;\nuniform vec4 contourColor;\nuniform sampler2D colormap;\nuniform vec3 clipBounds[2];\nuniform float roughness, fresnel, kambient, kdiffuse, kspecular, opacity;\nuniform float vertexColor;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\nvarying vec4 vColor;\n\nvoid main() {\n  if ((kill > 0.0) ||\n      (outOfRange(clipBounds[0], clipBounds[1], worldCoordinate))) discard;\n\n  vec3 N = normalize(surfaceNormal);\n  vec3 V = normalize(eyeDirection);\n  vec3 L = normalize(lightDirection);\n\n  if(gl_FrontFacing) {\n    N = -N;\n  }\n\n  float specular = max(beckmannSpecular(L, V, N, roughness), 0.);\n  float diffuse  = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n  //decide how to interpolate color \u2014 in vertex or in fragment\n  vec4 surfaceColor =\n    step(vertexColor, .5) * texture2D(colormap, vec2(value, value)) +\n    step(.5, vertexColor) * vColor;\n\n  vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular,  1.0);\n\n  gl_FragColor = mix(litColor, contourColor, contourTint) * opacity;\n}\n"]),s=i(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute float f;\n\nuniform vec3 objectOffset;\nuniform mat3 permutation;\nuniform mat4 model, view, projection;\nuniform float height, zOffset;\nuniform sampler2D colormap;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\nvarying vec4 vColor;\n\nvoid main() {\n  vec3 dataCoordinate = permutation * vec3(uv.xy, height);\n  worldCoordinate = objectOffset + dataCoordinate;\n  vec4 worldPosition = model * vec4(worldCoordinate, 1.0);\n\n  vec4 clipPosition = projection * view * worldPosition;\n  clipPosition.z += zOffset;\n\n  gl_Position = clipPosition;\n  value = f + objectOffset.z;\n  kill = -1.0;\n  planeCoordinate = uv.zw;\n\n  vColor = texture2D(colormap, vec2(value, value));\n\n  //Don't do lighting for contours\n  surfaceNormal   = vec3(1,0,0);\n  eyeDirection    = vec3(0,1,0);\n  lightDirection  = vec3(0,0,1);\n}\n"]),l=i(["precision mediump float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec2 shape;\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 surfaceNormal;\n\nvec2 splitFloat(float v) {\n  float vh = 255.0 * v;\n  float upper = floor(vh);\n  float lower = fract(vh);\n  return vec2(upper / 255.0, floor(lower * 16.0) / 16.0);\n}\n\nvoid main() {\n  if ((kill > 0.0) ||\n      (outOfRange(clipBounds[0], clipBounds[1], worldCoordinate))) discard;\n\n  vec2 ux = splitFloat(planeCoordinate.x / shape.x);\n  vec2 uy = splitFloat(planeCoordinate.y / shape.y);\n  gl_FragColor = vec4(pickId, ux.x, uy.x, ux.y + (uy.y/16.0));\n}\n"]);r.createShader=function(t){var e=n(t,a,o,null,[{name:"uv",type:"vec4"},{name:"f",type:"vec3"},{name:"normal",type:"vec3"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e.attributes.normal.location=2,e},r.createPickShader=function(t){var e=n(t,a,l,null,[{name:"uv",type:"vec4"},{name:"f",type:"vec3"},{name:"normal",type:"vec3"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e.attributes.normal.location=2,e},r.createContourShader=function(t){var e=n(t,s,o,null,[{name:"uv",type:"vec4"},{name:"f",type:"float"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e},r.createPickContourShader=function(t){var e=n(t,s,l,null,[{name:"uv",type:"vec4"},{name:"f",type:"float"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e}},{"gl-shader":294,glslify:398}],308:[function(t,e,r){arguments[4][99][0].apply(r,arguments)},{dup:99}],309:[function(t,e,r){"use strict";e.exports=function(t){var e=t.gl,r=y(e),n=b(e),s=x(e),l=_(e),c=i(e),u=a(e,[{buffer:c,size:4,stride:w,offset:0},{buffer:c,size:3,stride:w,offset:16},{buffer:c,size:3,stride:w,offset:28}]),h=i(e),f=a(e,[{buffer:h,size:4,stride:20,offset:0},{buffer:h,size:1,stride:20,offset:16}]),p=i(e),d=a(e,[{buffer:p,size:2,type:e.FLOAT}]),g=o(e,1,S,e.RGBA,e.UNSIGNED_BYTE);g.minFilter=e.LINEAR,g.magFilter=e.LINEAR;var v=new E(e,[0,0],[[0,0,0],[0,0,0]],r,n,c,u,g,s,l,h,f,p,d,[0,0,0]),m={levels:[[],[],[]]};for(var k in t)m[k]=t[k];return m.colormap=m.colormap||"jet",v.update(m),v};var n=t("bit-twiddle"),i=t("gl-buffer"),a=t("gl-vao"),o=t("gl-texture2d"),s=t("typedarray-pool"),l=t("colormap"),c=t("ndarray-ops"),u=t("ndarray-pack"),h=t("ndarray"),f=t("surface-nets"),p=t("gl-mat4/multiply"),d=t("gl-mat4/invert"),g=t("binary-search-bounds"),v=t("ndarray-gradient"),m=t("./lib/shaders"),y=m.createShader,x=m.createContourShader,b=m.createPickShader,_=m.createPickContourShader,w=40,k=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],A=[[0,0],[0,1],[1,0],[1,1],[1,0],[0,1]],M=[[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]];function T(t,e,r,n,i){this.position=t,this.index=e,this.uv=r,this.level=n,this.dataCoordinate=i}!function(){for(var t=0;t<3;++t){var e=M[t],r=(t+2)%3;e[(t+1)%3+0]=1,e[r+3]=1,e[t+6]=1}}();var S=256;function E(t,e,r,n,i,a,o,l,c,u,f,p,d,g,v){this.gl=t,this.shape=e,this.bounds=r,this.objectOffset=v,this.intensityBounds=[],this._shader=n,this._pickShader=i,this._coordinateBuffer=a,this._vao=o,this._colorMap=l,this._contourShader=c,this._contourPickShader=u,this._contourBuffer=f,this._contourVAO=p,this._contourOffsets=[[],[],[]],this._contourCounts=[[],[],[]],this._vertexCount=0,this._pickResult=new T([0,0,0],[0,0],[0,0],[0,0,0],[0,0,0]),this._dynamicBuffer=d,this._dynamicVAO=g,this._dynamicOffsets=[0,0,0],this._dynamicCounts=[0,0,0],this.contourWidth=[1,1,1],this.contourLevels=[[1],[1],[1]],this.contourTint=[0,0,0],this.contourColor=[[.5,.5,.5,1],[.5,.5,.5,1],[.5,.5,.5,1]],this.showContour=!0,this.showSurface=!0,this.enableHighlight=[!0,!0,!0],this.highlightColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.highlightTint=[1,1,1],this.highlightLevel=[-1,-1,-1],this.enableDynamic=[!0,!0,!0],this.dynamicLevel=[NaN,NaN,NaN],this.dynamicColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.dynamicTint=[1,1,1],this.dynamicWidth=[1,1,1],this.axesBounds=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]],this.surfaceProject=[!1,!1,!1],this.contourProject=[[!1,!1,!1],[!1,!1,!1],[!1,!1,!1]],this.colorBounds=[!1,!1],this._field=[h(s.mallocFloat(1024),[0,0]),h(s.mallocFloat(1024),[0,0]),h(s.mallocFloat(1024),[0,0])],this.pickId=1,this.clipBounds=[[-1/0,-1/0,-1/0],[1/0,1/0,1/0]],this.snapToData=!1,this.pixelRatio=1,this.opacity=1,this.lightPosition=[10,1e4,0],this.ambientLight=.8,this.diffuseLight=.8,this.specularLight=2,this.roughness=.5,this.fresnel=1.5,this.vertexColor=0,this.dirty=!0}var C=E.prototype;C.isTransparent=function(){return this.opacity<1},C.isOpaque=function(){if(this.opacity>=1)return!0;for(var t=0;t<3;++t)if(this._contourCounts[t].length>0||this._dynamicCounts[t]>0)return!0;return!1},C.pickSlots=1,C.setPickBase=function(t){this.pickId=t};var L=[0,0,0],z={showSurface:!1,showContour:!1,projections:[k.slice(),k.slice(),k.slice()],clipBounds:[[[0,0,0],[0,0,0]],[[0,0,0],[0,0,0]],[[0,0,0],[0,0,0]]]};function O(t,e){var r,n,i,a=e.axes&&e.axes.lastCubeProps.axis||L,o=e.showSurface,s=e.showContour;for(r=0;r<3;++r)for(o=o||e.surfaceProject[r],n=0;n<3;++n)s=s||e.contourProject[r][n];for(r=0;r<3;++r){var l=z.projections[r];for(n=0;n<16;++n)l[n]=0;for(n=0;n<4;++n)l[5*n]=1;l[5*r]=0,l[12+r]=e.axesBounds[+(a[r]>0)][r],p(l,t.model,l);var c=z.clipBounds[r];for(i=0;i<2;++i)for(n=0;n<3;++n)c[i][n]=t.clipBounds[i][n];c[0][r]=-1e8,c[1][r]=1e8}return z.showSurface=o,z.showContour=s,z}var I={model:k,view:k,projection:k,inverseModel:k.slice(),lowerBound:[0,0,0],upperBound:[0,0,0],colorMap:0,clipBounds:[[0,0,0],[0,0,0]],height:0,contourTint:0,contourColor:[0,0,0,1],permutation:[1,0,0,0,1,0,0,0,1],zOffset:-1e-4,objectOffset:[0,0,0],kambient:1,kdiffuse:1,kspecular:1,lightPosition:[1e3,1e3,1e3],eyePosition:[0,0,0],roughness:1,fresnel:1,opacity:1,vertexColor:0},D=k.slice(),P=[1,0,0,0,1,0,0,0,1];function R(t,e){t=t||{};var r=this.gl;r.disable(r.CULL_FACE),this._colorMap.bind(0);var n=I;n.model=t.model||k,n.view=t.view||k,n.projection=t.projection||k,n.lowerBound=[this.bounds[0][0],this.bounds[0][1],this.colorBounds[0]||this.bounds[0][2]],n.upperBound=[this.bounds[1][0],this.bounds[1][1],this.colorBounds[1]||this.bounds[1][2]],n.objectOffset=this.objectOffset,n.contourColor=this.contourColor[0],n.inverseModel=d(n.inverseModel,n.model);for(var i=0;i<2;++i)for(var a=n.clipBounds[i],o=0;o<3;++o)a[o]=Math.min(Math.max(this.clipBounds[i][o],-1e8),1e8);n.kambient=this.ambientLight,n.kdiffuse=this.diffuseLight,n.kspecular=this.specularLight,n.roughness=this.roughness,n.fresnel=this.fresnel,n.opacity=this.opacity,n.height=0,n.permutation=P,n.vertexColor=this.vertexColor;var s=D;for(p(s,n.view,n.model),p(s,n.projection,s),d(s,s),i=0;i<3;++i)n.eyePosition[i]=s[12+i]/s[15];var l=s[15];for(i=0;i<3;++i)l+=this.lightPosition[i]*s[4*i+3];for(i=0;i<3;++i){var c=s[12+i];for(o=0;o<3;++o)c+=s[4*o+i]*this.lightPosition[o];n.lightPosition[i]=c/l}var u=O(n,this);if(u.showSurface&&e===this.opacity<1){for(this._shader.bind(),this._shader.uniforms=n,this._vao.bind(),this.showSurface&&this._vertexCount&&this._vao.draw(r.TRIANGLES,this._vertexCount),i=0;i<3;++i)this.surfaceProject[i]&&this.vertexCount&&(this._shader.uniforms.model=u.projections[i],this._shader.uniforms.clipBounds=u.clipBounds[i],this._vao.draw(r.TRIANGLES,this._vertexCount));this._vao.unbind()}if(u.showContour&&!e){var h=this._contourShader;n.kambient=1,n.kdiffuse=0,n.kspecular=0,n.opacity=1,h.bind(),h.uniforms=n;var f=this._contourVAO;for(f.bind(),i=0;i<3;++i)for(h.uniforms.permutation=M[i],r.lineWidth(this.contourWidth[i]*this.pixelRatio),o=0;o<this.contourLevels[i].length;++o)o===this.highlightLevel[i]?(h.uniforms.contourColor=this.highlightColor[i],h.uniforms.contourTint=this.highlightTint[i]):0!==o&&o-1!==this.highlightLevel[i]||(h.uniforms.contourColor=this.contourColor[i],h.uniforms.contourTint=this.contourTint[i]),this._contourCounts[i][o]&&(h.uniforms.height=this.contourLevels[i][o],f.draw(r.LINES,this._contourCounts[i][o],this._contourOffsets[i][o]));for(i=0;i<3;++i)for(h.uniforms.model=u.projections[i],h.uniforms.clipBounds=u.clipBounds[i],o=0;o<3;++o)if(this.contourProject[i][o]){h.uniforms.permutation=M[o],r.lineWidth(this.contourWidth[o]*this.pixelRatio);for(var g=0;g<this.contourLevels[o].length;++g)g===this.highlightLevel[o]?(h.uniforms.contourColor=this.highlightColor[o],h.uniforms.contourTint=this.highlightTint[o]):0!==g&&g-1!==this.highlightLevel[o]||(h.uniforms.contourColor=this.contourColor[o],h.uniforms.contourTint=this.contourTint[o]),h.uniforms.height=this.contourLevels[o][g],f.draw(r.LINES,this._contourCounts[o][g],this._contourOffsets[o][g])}for(f.unbind(),(f=this._dynamicVAO).bind(),i=0;i<3;++i)if(0!==this._dynamicCounts[i])for(h.uniforms.model=n.model,h.uniforms.clipBounds=n.clipBounds,h.uniforms.permutation=M[i],r.lineWidth(this.dynamicWidth[i]*this.pixelRatio),h.uniforms.contourColor=this.dynamicColor[i],h.uniforms.contourTint=this.dynamicTint[i],h.uniforms.height=this.dynamicLevel[i],f.draw(r.LINES,this._dynamicCounts[i],this._dynamicOffsets[i]),o=0;o<3;++o)this.contourProject[o][i]&&(h.uniforms.model=u.projections[o],h.uniforms.clipBounds=u.clipBounds[o],f.draw(r.LINES,this._dynamicCounts[i],this._dynamicOffsets[i]));f.unbind()}}C.draw=function(t){return R.call(this,t,!1)},C.drawTransparent=function(t){return R.call(this,t,!0)};var F={model:k,view:k,projection:k,inverseModel:k,clipBounds:[[0,0,0],[0,0,0]],height:0,shape:[0,0],pickId:0,lowerBound:[0,0,0],upperBound:[0,0,0],zOffset:0,objectOffset:[0,0,0],permutation:[1,0,0,0,1,0,0,0,1],lightPosition:[0,0,0],eyePosition:[0,0,0]};function B(t,e){return Array.isArray(t)?[e(t[0]),e(t[1]),e(t[2])]:[e(t),e(t),e(t)]}function N(t){return Array.isArray(t)?3===t.length?[t[0],t[1],t[2],1]:[t[0],t[1],t[2],t[3]]:[0,0,0,1]}function j(t){if(Array.isArray(t)){if(Array.isArray(t))return[N(t[0]),N(t[1]),N(t[2])];var e=N(t);return[e.slice(),e.slice(),e.slice()]}}C.drawPick=function(t){t=t||{};var e=this.gl;e.disable(e.CULL_FACE);var r=F;r.model=t.model||k,r.view=t.view||k,r.projection=t.projection||k,r.shape=this._field[2].shape,r.pickId=this.pickId/255,r.lowerBound=this.bounds[0],r.upperBound=this.bounds[1],r.objectOffset=this.objectOffset,r.permutation=P;for(var n=0;n<2;++n)for(var i=r.clipBounds[n],a=0;a<3;++a)i[a]=Math.min(Math.max(this.clipBounds[n][a],-1e8),1e8);var o=O(r,this);if(o.showSurface){for(this._pickShader.bind(),this._pickShader.uniforms=r,this._vao.bind(),this._vao.draw(e.TRIANGLES,this._vertexCount),n=0;n<3;++n)this.surfaceProject[n]&&(this._pickShader.uniforms.model=o.projections[n],this._pickShader.uniforms.clipBounds=o.clipBounds[n],this._vao.draw(e.TRIANGLES,this._vertexCount));this._vao.unbind()}if(o.showContour){var s=this._contourPickShader;s.bind(),s.uniforms=r;var l=this._contourVAO;for(l.bind(),a=0;a<3;++a)for(e.lineWidth(this.contourWidth[a]*this.pixelRatio),s.uniforms.permutation=M[a],n=0;n<this.contourLevels[a].length;++n)this._contourCounts[a][n]&&(s.uniforms.height=this.contourLevels[a][n],l.draw(e.LINES,this._contourCounts[a][n],this._contourOffsets[a][n]));for(n=0;n<3;++n)for(s.uniforms.model=o.projections[n],s.uniforms.clipBounds=o.clipBounds[n],a=0;a<3;++a)if(this.contourProject[n][a]){s.uniforms.permutation=M[a],e.lineWidth(this.contourWidth[a]);for(var c=0;c<this.contourLevels[a].length;++c)this._contourCounts[a][c]&&(s.uniforms.height=this.contourLevels[a][c],l.draw(e.LINES,this._contourCounts[a][c],this._contourOffsets[a][c]))}l.unbind()}},C.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=this._field[2].shape,r=this._pickResult,n=e[0]*(t.value[0]+(t.value[2]>>4)/16)/255,i=Math.floor(n),a=n-i,o=e[1]*(t.value[1]+(15&t.value[2])/16)/255,s=Math.floor(o),l=o-s;i+=1,s+=1;var c=r.position;c[0]=c[1]=c[2]=0;for(var u=0;u<2;++u)for(var h=u?a:1-a,f=0;f<2;++f)for(var p=i+u,d=s+f,v=h*(f?l:1-l),m=0;m<3;++m)c[m]+=this._field[m].get(p,d)*v;for(var y=this._pickResult.level,x=0;x<3;++x)if(y[x]=g.le(this.contourLevels[x],c[x]),y[x]<0)this.contourLevels[x].length>0&&(y[x]=0);else if(y[x]<this.contourLevels[x].length-1){var b=this.contourLevels[x][y[x]],_=this.contourLevels[x][y[x]+1];Math.abs(b-c[x])>Math.abs(_-c[x])&&(y[x]+=1)}for(r.index[0]=a<.5?i:i+1,r.index[1]=l<.5?s:s+1,r.uv[0]=n/e[0],r.uv[1]=o/e[1],m=0;m<3;++m)r.dataCoordinate[m]=this._field[m].get(r.index[0],r.index[1]);return r},C.padField=function(t,e){var r=e.shape.slice(),n=t.shape.slice();c.assign(t.lo(1,1).hi(r[0],r[1]),e),c.assign(t.lo(1).hi(r[0],1),e.hi(r[0],1)),c.assign(t.lo(1,n[1]-1).hi(r[0],1),e.lo(0,r[1]-1).hi(r[0],1)),c.assign(t.lo(0,1).hi(1,r[1]),e.hi(1)),c.assign(t.lo(n[0]-1,1).hi(1,r[1]),e.lo(r[0]-1)),t.set(0,0,e.get(0,0)),t.set(0,n[1]-1,e.get(0,r[1]-1)),t.set(n[0]-1,0,e.get(r[0]-1,0)),t.set(n[0]-1,n[1]-1,e.get(r[0]-1,r[1]-1))},C.update=function(t){t=t||{},this.objectOffset=t.objectOffset||this.objectOffset,this.dirty=!0,"contourWidth"in t&&(this.contourWidth=B(t.contourWidth,Number)),"showContour"in t&&(this.showContour=B(t.showContour,Boolean)),"showSurface"in t&&(this.showSurface=!!t.showSurface),"contourTint"in t&&(this.contourTint=B(t.contourTint,Boolean)),"contourColor"in t&&(this.contourColor=j(t.contourColor)),"contourProject"in t&&(this.contourProject=B(t.contourProject,function(t){return B(t,Boolean)})),"surfaceProject"in t&&(this.surfaceProject=t.surfaceProject),"dynamicColor"in t&&(this.dynamicColor=j(t.dynamicColor)),"dynamicTint"in t&&(this.dynamicTint=B(t.dynamicTint,Number)),"dynamicWidth"in t&&(this.dynamicWidth=B(t.dynamicWidth,Number)),"opacity"in t&&(this.opacity=t.opacity),"colorBounds"in t&&(this.colorBounds=t.colorBounds),"vertexColor"in t&&(this.vertexColor=t.vertexColor?1:0);var e=t.field||t.coords&&t.coords[2]||null,r=!1;if(e||(e=this._field[2].shape[0]||this._field[2].shape[2]?this._field[2].lo(1,1).hi(this._field[2].shape[0]-2,this._field[2].shape[1]-2):this._field[2].hi(0,0)),"field"in t||"coords"in t){var i=(e.shape[0]+2)*(e.shape[1]+2);i>this._field[2].data.length&&(s.freeFloat(this._field[2].data),this._field[2].data=s.mallocFloat(n.nextPow2(i))),this._field[2]=h(this._field[2].data,[e.shape[0]+2,e.shape[1]+2]),this.padField(this._field[2],e),this.shape=e.shape.slice();for(var a=this.shape,o=0;o<2;++o)this._field[2].size>this._field[o].data.length&&(s.freeFloat(this._field[o].data),this._field[o].data=s.mallocFloat(this._field[2].size)),this._field[o]=h(this._field[o].data,[a[0]+2,a[1]+2]);if(t.coords){var p=t.coords;if(!Array.isArray(p)||3!==p.length)throw new Error("gl-surface: invalid coordinates for x/y");for(o=0;o<2;++o){var d=p[o];for(b=0;b<2;++b)if(d.shape[b]!==a[b])throw new Error("gl-surface: coords have incorrect shape");this.padField(this._field[o],d)}}else if(t.ticks){var g=t.ticks;if(!Array.isArray(g)||2!==g.length)throw new Error("gl-surface: invalid ticks");for(o=0;o<2;++o){var m=g[o];if((Array.isArray(m)||m.length)&&(m=h(m)),m.shape[0]!==a[o])throw new Error("gl-surface: invalid tick length");var y=h(m.data,a);y.stride[o]=m.stride[0],y.stride[1^o]=0,this.padField(this._field[o],y)}}else{for(o=0;o<2;++o){var x=[0,0];x[o]=1,this._field[o]=h(this._field[o].data,[a[0]+2,a[1]+2],x,0)}this._field[0].set(0,0,0);for(var b=0;b<a[0];++b)this._field[0].set(b+1,0,b);for(this._field[0].set(a[0]+1,0,a[0]-1),this._field[1].set(0,0,0),b=0;b<a[1];++b)this._field[1].set(0,b+1,b);this._field[1].set(0,a[1]+1,a[1]-1)}var _=this._field,w=h(s.mallocFloat(3*_[2].size*2),[3,a[0]+2,a[1]+2,2]);for(o=0;o<3;++o)v(w.pick(o),_[o],"mirror");var k=h(s.mallocFloat(3*_[2].size),[a[0]+2,a[1]+2,3]);for(o=0;o<a[0]+2;++o)for(b=0;b<a[1]+2;++b){var M=w.get(0,o,b,0),T=w.get(0,o,b,1),E=w.get(1,o,b,0),C=w.get(1,o,b,1),L=w.get(2,o,b,0),z=w.get(2,o,b,1),O=E*z-C*L,I=L*T-z*M,D=M*C-T*E,P=Math.sqrt(O*O+I*I+D*D);P<1e-8?(P=Math.max(Math.abs(O),Math.abs(I),Math.abs(D)))<1e-8?(D=1,I=O=0,P=1):P=1/P:P=1/Math.sqrt(P),k.set(o,b,0,O*P),k.set(o,b,1,I*P),k.set(o,b,2,D*P)}s.free(w.data);var R=[1/0,1/0,1/0],F=[-1/0,-1/0,-1/0],N=1/0,V=-1/0,U=(a[0]-1)*(a[1]-1)*6,q=s.mallocFloat(n.nextPow2(10*U)),H=0,G=0;for(o=0;o<a[0]-1;++o)t:for(b=0;b<a[1]-1;++b){for(var Y=0;Y<2;++Y)for(var W=0;W<2;++W)for(var X=0;X<3;++X){var Z=this._field[X].get(1+o+Y,1+b+W);if(isNaN(Z)||!isFinite(Z))continue t}for(X=0;X<6;++X){var $=o+A[X][0],J=b+A[X][1],K=this._field[0].get($+1,J+1),Q=this._field[1].get($+1,J+1);Z=this._field[2].get($+1,J+1),O=k.get($+1,J+1,0),I=k.get($+1,J+1,1),D=k.get($+1,J+1,2),t.intensity&&(tt=t.intensity.get($,J));var tt=t.intensity?t.intensity.get($,J):Z+this.objectOffset[2];q[H++]=$,q[H++]=J,q[H++]=K,q[H++]=Q,q[H++]=Z,q[H++]=0,q[H++]=tt,q[H++]=O,q[H++]=I,q[H++]=D,R[0]=Math.min(R[0],K+this.objectOffset[0]),R[1]=Math.min(R[1],Q+this.objectOffset[1]),R[2]=Math.min(R[2],Z+this.objectOffset[2]),N=Math.min(N,tt),F[0]=Math.max(F[0],K+this.objectOffset[0]),F[1]=Math.max(F[1],Q+this.objectOffset[1]),F[2]=Math.max(F[2],Z+this.objectOffset[2]),V=Math.max(V,tt),G+=1}}for(t.intensityBounds&&(N=+t.intensityBounds[0],V=+t.intensityBounds[1]),o=6;o<H;o+=10)q[o]=(q[o]-N)/(V-N);this._vertexCount=G,this._coordinateBuffer.update(q.subarray(0,H)),s.freeFloat(q),s.free(k.data),this.bounds=[R,F],this.intensity=t.intensity||this._field[2],this.intensityBounds[0]===N&&this.intensityBounds[1]===V||(r=!0),this.intensityBounds=[N,V]}if("levels"in t){var et=t.levels;for(et=Array.isArray(et[0])?et.slice():[[],[],et],o=0;o<3;++o)et[o]=et[o].slice(),et.sort(function(t,e){return t-e});for(o=0;o<3;++o)for(b=0;b<et[o].length;++b)et[o][b]-=this.objectOffset[o];t:for(o=0;o<3;++o){if(et[o].length!==this.contourLevels[o].length){r=!0;break}for(b=0;b<et[o].length;++b)if(et[o][b]!==this.contourLevels[o][b]){r=!0;break t}}this.contourLevels=et}if(r){_=this._field,a=this.shape;for(var rt=[],nt=0;nt<3;++nt){et=this.contourLevels[nt];var it=[],at=[],ot=[0,0,0];for(o=0;o<et.length;++o){var st=f(this._field[nt],et[o]);it.push(rt.length/5|0),G=0;t:for(b=0;b<st.cells.length;++b){var lt=st.cells[b];for(X=0;X<2;++X){var ct=st.positions[lt[X]],ut=ct[0],ht=0|Math.floor(ut),ft=ut-ht,pt=ct[1],dt=0|Math.floor(pt),gt=pt-dt,vt=!1;e:for(var mt=0;mt<3;++mt){ot[mt]=0;var yt=(nt+mt+1)%3;for(Y=0;Y<2;++Y){var xt=Y?ft:1-ft;for($=0|Math.min(Math.max(ht+Y,0),a[0]),W=0;W<2;++W){var bt=W?gt:1-gt;if(J=0|Math.min(Math.max(dt+W,0),a[1]),Z=mt<2?this._field[yt].get($,J):(this.intensity.get($,J)-this.intensityBounds[0])/(this.intensityBounds[1]-this.intensityBounds[0]),!isFinite(Z)||isNaN(Z)){vt=!0;break e}var _t=xt*bt;ot[mt]+=_t*Z}}}if(vt){if(X>0){for(var wt=0;wt<5;++wt)rt.pop();G-=1}continue t}rt.push(ot[0],ot[1],ct[0],ct[1],ot[2]),G+=1}}at.push(G)}this._contourOffsets[nt]=it,this._contourCounts[nt]=at}var kt=s.mallocFloat(rt.length);for(o=0;o<rt.length;++o)kt[o]=rt[o];this._contourBuffer.update(kt),s.freeFloat(kt)}t.colormap&&this._colorMap.setPixels(function(t){var e=u([l({colormap:t,nshades:S,format:"rgba"}).map(function(t){return[t[0],t[1],t[2],255*t[3]]})]);return c.divseq(e,255),e}(t.colormap))},C.dispose=function(){this._shader.dispose(),this._vao.dispose(),this._coordinateBuffer.dispose(),this._colorMap.dispose(),this._contourBuffer.dispose(),this._contourVAO.dispose(),this._contourShader.dispose(),this._contourPickShader.dispose(),this._dynamicBuffer.dispose(),this._dynamicVAO.dispose();for(var t=0;t<3;++t)s.freeFloat(this._field[t].data)},C.highlight=function(t){var e,r;if(!t)return this._dynamicCounts=[0,0,0],this.dyanamicLevel=[NaN,NaN,NaN],void(this.highlightLevel=[-1,-1,-1]);for(e=0;e<3;++e)this.enableHighlight[e]?this.highlightLevel[e]=t.level[e]:this.highlightLevel[e]=-1;for(r=this.snapToData?t.dataCoordinate:t.position,e=0;e<3;++e)r[e]-=this.objectOffset[e];if(this.enableDynamic[0]&&r[0]!==this.dynamicLevel[0]||this.enableDynamic[1]&&r[1]!==this.dynamicLevel[1]||this.enableDynamic[2]&&r[2]!==this.dynamicLevel[2]){for(var n=0,i=this.shape,a=s.mallocFloat(12*i[0]*i[1]),o=0;o<3;++o)if(this.enableDynamic[o]){this.dynamicLevel[o]=r[o];var l=(o+1)%3,c=(o+2)%3,u=this._field[o],h=this._field[l],p=this._field[c],d=f(u,r[o]),g=d.cells,v=d.positions;for(this._dynamicOffsets[o]=n,e=0;e<g.length;++e)for(var m=g[e],y=0;y<2;++y){var x=v[m[y]],b=+x[0],_=0|b,w=0|Math.min(_+1,i[0]),k=b-_,A=1-k,M=+x[1],T=0|M,S=0|Math.min(T+1,i[1]),E=M-T,C=1-E,L=A*C,z=A*E,O=k*C,I=k*E,D=L*h.get(_,T)+z*h.get(_,S)+O*h.get(w,T)+I*h.get(w,S),P=L*p.get(_,T)+z*p.get(_,S)+O*p.get(w,T)+I*p.get(w,S);if(isNaN(D)||isNaN(P)){y&&(n-=1);break}a[2*n+0]=D,a[2*n+1]=P,n+=1}this._dynamicCounts[o]=n-this._dynamicOffsets[o]}else this.dynamicLevel[o]=NaN,this._dynamicCounts[o]=0;this._dynamicBuffer.update(a.subarray(0,2*n)),s.freeFloat(a)}}},{"./lib/shaders":307,"binary-search-bounds":308,"bit-twiddle":80,colormap:114,"gl-buffer":234,"gl-mat4/invert":258,"gl-mat4/multiply":260,"gl-texture2d":311,"gl-vao":316,ndarray:439,"ndarray-gradient":430,"ndarray-ops":433,"ndarray-pack":434,"surface-nets":512,"typedarray-pool":526}],310:[function(t,e,r){"use strict";var n=t("css-font"),i=t("pick-by-alias"),a=t("regl"),o=t("gl-util/context"),s=t("es6-weak-map"),l=t("color-normalize"),c=t("font-atlas"),u=t("typedarray-pool"),h=t("parse-rect"),f=t("is-plain-obj"),p=t("parse-unit"),d=t("to-px"),g=t("detect-kerning"),v=t("object-assign"),m=t("font-measure"),y=t("flatten-vertex-data"),x=t("bit-twiddle").nextPow2,b=new s,_=!1;if(document.body){var w=document.body.appendChild(document.createElement("div"));w.style.font="italic small-caps bold condensed 16px/2 cursive",getComputedStyle(w).fontStretch&&(_=!0),document.body.removeChild(w)}var k=function(t){!function(t){return"function"==typeof t&&t._gl&&t.prop&&t.texture&&t.buffer}(t)?this.gl=o(t):(t={regl:t},this.gl=t.regl._gl),this.shader=b.get(this.gl),this.shader?this.regl=this.shader.regl:this.regl=t.regl||a({gl:this.gl}),this.charBuffer=this.regl.buffer({type:"uint8",usage:"stream"}),this.sizeBuffer=this.regl.buffer({type:"float",usage:"stream"}),this.shader||(this.shader=this.createShader(),b.set(this.gl,this.shader)),this.batch=[],this.fontSize=[],this.font=[],this.fontAtlas=[],this.draw=this.shader.draw.bind(this),this.render=function(){this.regl._refresh(),this.draw(this.batch)},this.canvas=this.gl.canvas,this.update(f(t)?t:{})};k.prototype.createShader=function(){var t=this.regl,e=t({blend:{enable:!0,color:[0,0,0,1],func:{srcRGB:"src alpha",dstRGB:"one minus src alpha",srcAlpha:"one minus dst alpha",dstAlpha:"one"}},stencil:{enable:!1},depth:{enable:!1},count:t.prop("count"),offset:t.prop("offset"),attributes:{charOffset:{offset:4,stride:8,buffer:t.this("sizeBuffer")},width:{offset:0,stride:8,buffer:t.this("sizeBuffer")},char:t.this("charBuffer"),position:t.this("position")},uniforms:{atlasSize:function(t,e){return[e.atlas.width,e.atlas.height]},atlasDim:function(t,e){return[e.atlas.cols,e.atlas.rows]},atlas:function(t,e){return e.atlas.texture},charStep:function(t,e){return e.atlas.step},em:function(t,e){return e.atlas.em},color:t.prop("color"),opacity:t.prop("opacity"),viewport:t.this("viewportArray"),scale:t.this("scale"),align:t.prop("align"),baseline:t.prop("baseline"),translate:t.this("translate"),positionOffset:t.prop("positionOffset")},primitive:"points",viewport:t.this("viewport"),vert:"\n\t\t\tprecision highp float;\n\t\t\tattribute float width, charOffset, char;\n\t\t\tattribute vec2 position;\n\t\t\tuniform float fontSize, charStep, em, align, baseline;\n\t\t\tuniform vec4 viewport;\n\t\t\tuniform vec4 color;\n\t\t\tuniform vec2 atlasSize, atlasDim, scale, translate, positionOffset;\n\t\t\tvarying vec2 charCoord, charId;\n\t\t\tvarying float charWidth;\n\t\t\tvarying vec4 fontColor;\n\t\t\tvoid main () {\n\t\t\t\t"+(k.normalViewport?"":"vec2 positionOffset = vec2(positionOffset.x,- positionOffset.y);")+"\n\n\t\t\t\tvec2 offset = floor(em * (vec2(align + charOffset, baseline)\n\t\t\t\t\t+ positionOffset))\n\t\t\t\t\t/ (viewport.zw * scale.xy);\n\n\t\t\t\tvec2 position = (position + translate) * scale;\n\t\t\t\tposition += offset * scale;\n\n\t\t\t\t"+(k.normalViewport?"position.y = 1. - position.y;":"")+"\n\n\t\t\t\tcharCoord = position * viewport.zw + viewport.xy;\n\n\t\t\t\tgl_Position = vec4(position * 2. - 1., 0, 1);\n\n\t\t\t\tgl_PointSize = charStep;\n\n\t\t\t\tcharId.x = mod(char, atlasDim.x);\n\t\t\t\tcharId.y = floor(char / atlasDim.x);\n\n\t\t\t\tcharWidth = width * em;\n\n\t\t\t\tfontColor = color / 255.;\n\t\t\t}",frag:"\n\t\t\tprecision highp float;\n\t\t\tuniform sampler2D atlas;\n\t\t\tuniform float fontSize, charStep, opacity;\n\t\t\tuniform vec2 atlasSize;\n\t\t\tuniform vec4 viewport;\n\t\t\tvarying vec4 fontColor;\n\t\t\tvarying vec2 charCoord, charId;\n\t\t\tvarying float charWidth;\n\n\t\t\tfloat lightness(vec4 color) {\n\t\t\t\treturn color.r * 0.299 + color.g * 0.587 + color.b * 0.114;\n\t\t\t}\n\n\t\t\tvoid main () {\n\t\t\t\tvec2 uv = gl_FragCoord.xy - charCoord + charStep * .5;\n\t\t\t\tfloat halfCharStep = floor(charStep * .5 + .5);\n\n\t\t\t\t// invert y and shift by 1px (FF expecially needs that)\n\t\t\t\tuv.y = charStep - uv.y;\n\n\t\t\t\t// ignore points outside of character bounding box\n\t\t\t\tfloat halfCharWidth = ceil(charWidth * .5);\n\t\t\t\tif (floor(uv.x) > halfCharStep + halfCharWidth ||\n\t\t\t\t\tfloor(uv.x) < halfCharStep - halfCharWidth) return;\n\n\t\t\t\tuv += charId * charStep;\n\t\t\t\tuv = uv / atlasSize;\n\n\t\t\t\tvec4 color = fontColor;\n\t\t\t\tvec4 mask = texture2D(atlas, uv);\n\n\t\t\t\tfloat maskY = lightness(mask);\n\t\t\t\t// float colorY = lightness(color);\n\t\t\t\tcolor.a *= maskY;\n\t\t\t\tcolor.a *= opacity;\n\n\t\t\t\t// color.a += .1;\n\n\t\t\t\t// antialiasing, see yiq color space y-channel formula\n\t\t\t\t// color.rgb += (1. - color.rgb) * (1. - mask.rgb);\n\n\t\t\t\tgl_FragColor = color;\n\t\t\t}"});return{regl:t,draw:e,atlas:{}}},k.prototype.update=function(t){var e=this;if("string"==typeof t)t={text:t};else if(!t)return;null!=(t=i(t,{position:"position positions coord coords coordinates",font:"font fontFace fontface typeface cssFont css-font family fontFamily",fontSize:"fontSize fontsize size font-size",text:"text texts chars characters value values symbols",align:"align alignment textAlign textbaseline",baseline:"baseline textBaseline textbaseline",direction:"dir direction textDirection",color:"color colour fill fill-color fillColor textColor textcolor",kerning:"kerning kern",range:"range dataBox",viewport:"vp viewport viewBox viewbox viewPort",opacity:"opacity alpha transparency visible visibility opaque",offset:"offset positionOffset padding shift indent indentation"},!0)).opacity&&(Array.isArray(t.opacity)?this.opacity=t.opacity.map(function(t){return parseFloat(t)}):this.opacity=parseFloat(t.opacity)),null!=t.viewport&&(this.viewport=h(t.viewport),k.normalViewport&&(this.viewport.y=this.canvas.height-this.viewport.y-this.viewport.height),this.viewportArray=[this.viewport.x,this.viewport.y,this.viewport.width,this.viewport.height]),null==this.viewport&&(this.viewport={x:0,y:0,width:this.gl.drawingBufferWidth,height:this.gl.drawingBufferHeight},this.viewportArray=[this.viewport.x,this.viewport.y,this.viewport.width,this.viewport.height]),null!=t.kerning&&(this.kerning=t.kerning),null!=t.offset&&("number"==typeof t.offset&&(t.offset=[t.offset,0]),this.positionOffset=y(t.offset)),t.direction&&(this.direction=t.direction),t.range&&(this.range=t.range,this.scale=[1/(t.range[2]-t.range[0]),1/(t.range[3]-t.range[1])],this.translate=[-t.range[0],-t.range[1]]),t.scale&&(this.scale=t.scale),t.translate&&(this.translate=t.translate),this.scale||(this.scale=[1/this.viewport.width,1/this.viewport.height]),this.translate||(this.translate=[0,0]),this.font.length||t.font||(t.font=k.baseFontSize+"px sans-serif");var r,a=!1,o=!1;if(t.font&&(Array.isArray(t.font)?t.font:[t.font]).forEach(function(t,r){if("string"==typeof t)try{t=n.parse(t)}catch(e){t=n.parse(k.baseFontSize+"px "+t)}else t=n.parse(n.stringify(t));var i=n.stringify({size:k.baseFontSize,family:t.family,stretch:_?t.stretch:void 0,variant:t.variant,weight:t.weight,style:t.style}),s=p(t.size),l=Math.round(s[0]*d(s[1]));if(l!==e.fontSize[r]&&(o=!0,e.fontSize[r]=l),!(e.font[r]&&i==e.font[r].baseString||(a=!0,e.font[r]=k.fonts[i],e.font[r]))){var c=t.family.join(", "),u=[t.style];t.style!=t.variant&&u.push(t.variant),t.variant!=t.weight&&u.push(t.weight),_&&t.weight!=t.stretch&&u.push(t.stretch),e.font[r]={baseString:i,family:c,weight:t.weight,stretch:t.stretch,style:t.style,variant:t.variant,width:{},kerning:{},metrics:m(c,{origin:"top",fontSize:k.baseFontSize,fontStyle:u.join(" ")})},k.fonts[i]=e.font[r]}}),(a||o)&&this.font.forEach(function(r,i){var a=n.stringify({size:e.fontSize[i],family:r.family,stretch:_?r.stretch:void 0,variant:r.variant,weight:r.weight,style:r.style});if(e.fontAtlas[i]=e.shader.atlas[a],!e.fontAtlas[i]){var o=r.metrics;e.shader.atlas[a]=e.fontAtlas[i]={fontString:a,step:2*Math.ceil(e.fontSize[i]*o.bottom*.5),em:e.fontSize[i],cols:0,rows:0,height:0,width:0,chars:[],ids:{},texture:e.regl.texture()}}null==t.text&&(t.text=e.text)}),"string"==typeof t.text&&t.position&&t.position.length>2){for(var s=Array(.5*t.position.length),f=0;f<s.length;f++)s[f]=t.text;t.text=s}if(null!=t.text||a){if(this.textOffsets=[0],Array.isArray(t.text)){this.count=t.text[0].length,this.counts=[this.count];for(var b=1;b<t.text.length;b++)e.textOffsets[b]=e.textOffsets[b-1]+t.text[b-1].length,e.count+=t.text[b].length,e.counts.push(t.text[b].length);this.text=t.text.join("")}else this.text=t.text,this.count=this.text.length,this.counts=[this.count];r=[],this.font.forEach(function(t,n){k.atlasContext.font=t.baseString;for(var i=e.fontAtlas[n],a=0;a<e.text.length;a++){var o=e.text.charAt(a);if(null==i.ids[o]&&(i.ids[o]=i.chars.length,i.chars.push(o),r.push(o)),null==t.width[o]&&(t.width[o]=k.atlasContext.measureText(o).width/k.baseFontSize,e.kerning)){var s=[];for(var l in t.width)s.push(l+o,o+l);v(t.kerning,g(t.family,{pairs:s}))}}})}if(t.position)if(t.position.length>2){for(var w=!t.position[0].length,A=u.mallocFloat(2*this.count),M=0,T=0;M<this.counts.length;M++){var S=e.counts[M];if(w)for(var E=0;E<S;E++)A[T++]=t.position[2*M],A[T++]=t.position[2*M+1];else for(var C=0;C<S;C++)A[T++]=t.position[M][0],A[T++]=t.position[M][1]}this.position.call?this.position({type:"float",data:A}):this.position=this.regl.buffer({type:"float",data:A}),u.freeFloat(A)}else this.position.destroy&&this.position.destroy(),this.position={constant:t.position};if(t.text||a){var L=u.mallocUint8(this.count),z=u.mallocFloat(2*this.count);this.textWidth=[];for(var O=0,I=0;O<this.counts.length;O++){for(var D=e.counts[O],P=e.font[O]||e.font[0],R=e.fontAtlas[O]||e.fontAtlas[0],F=0;F<D;F++){var B=e.text.charAt(I),N=e.text.charAt(I-1);if(L[I]=R.ids[B],z[2*I]=P.width[B],F){var j=z[2*I-2],V=z[2*I],U=z[2*I-1]+.5*j+.5*V;if(e.kerning){var q=P.kerning[N+B];q&&(U+=.001*q)}z[2*I+1]=U}else z[2*I+1]=.5*z[2*I];I++}e.textWidth.push(z.length?.5*z[2*I-2]+z[2*I-1]:0)}t.align||(t.align=this.align),this.charBuffer({data:L,type:"uint8",usage:"stream"}),this.sizeBuffer({data:z,type:"float",usage:"stream"}),u.freeUint8(L),u.freeFloat(z),r.length&&this.font.forEach(function(t,r){var n=e.fontAtlas[r],i=n.step,a=Math.floor(k.maxAtlasSize/i),o=Math.min(a,n.chars.length),s=Math.ceil(n.chars.length/o),l=x(o*i),u=x(s*i);n.width=l,n.height=u,n.rows=s,n.cols=o,n.em&&n.texture({data:c({canvas:k.atlasCanvas,font:n.fontString,chars:n.chars,shape:[l,u],step:[i,i]})})})}if(t.align&&(this.align=t.align,this.alignOffset=this.textWidth.map(function(t,r){var n=Array.isArray(e.align)?e.align.length>1?e.align[r]:e.align[0]:e.align;if("number"==typeof n)return n;switch(n){case"right":case"end":return-t;case"center":case"centre":case"middle":return.5*-t}return 0})),null==this.baseline&&null==t.baseline&&(t.baseline=0),null!=t.baseline&&(this.baseline=t.baseline,Array.isArray(this.baseline)||(this.baseline=[this.baseline]),this.baselineOffset=this.baseline.map(function(t,r){var n=(e.font[r]||e.font[0]).metrics,i=0;return i+=.5*n.bottom,i+="number"==typeof t?t-n.baseline:-n[t],k.normalViewport||(i*=-1),i})),null!=t.color)if(t.color||(t.color="transparent"),"string"!=typeof t.color&&isNaN(t.color)){var H;if("number"==typeof t.color[0]&&t.color.length>this.counts.length){var G=t.color.length;H=u.mallocUint8(G);for(var Y=(t.color.subarray||t.color.slice).bind(t.color),W=0;W<G;W+=4)H.set(l(Y(W,W+4),"uint8"),W)}else{var X=t.color.length;H=u.mallocUint8(4*X);for(var Z=0;Z<X;Z++)H.set(l(t.color[Z]||0,"uint8"),4*Z)}this.color=H}else this.color=l(t.color,"uint8");if(t.position||t.text||t.color||t.baseline||t.align||t.font||t.offset||t.opacity)if(this.color.length>4||this.baselineOffset.length>1||this.align&&this.align.length>1||this.fontAtlas.length>1||this.positionOffset.length>2){var $=Math.max(.5*this.position.length||0,.25*this.color.length||0,this.baselineOffset.length||0,this.alignOffset.length||0,this.font.length||0,this.opacity.length||0,.5*this.positionOffset.length||0);this.batch=Array($);for(var J=0;J<this.batch.length;J++)e.batch[J]={count:e.counts.length>1?e.counts[J]:e.counts[0],offset:e.textOffsets.length>1?e.textOffsets[J]:e.textOffsets[0],color:e.color?e.color.length<=4?e.color:e.color.subarray(4*J,4*J+4):[0,0,0,255],opacity:Array.isArray(e.opacity)?e.opacity[J]:e.opacity,baseline:null!=e.baselineOffset[J]?e.baselineOffset[J]:e.baselineOffset[0],align:e.align?null!=e.alignOffset[J]?e.alignOffset[J]:e.alignOffset[0]:0,atlas:e.fontAtlas[J]||e.fontAtlas[0],positionOffset:e.positionOffset.length>2?e.positionOffset.subarray(2*J,2*J+2):e.positionOffset}}else this.count?this.batch=[{count:this.count,offset:0,color:this.color||[0,0,0,255],opacity:Array.isArray(this.opacity)?this.opacity[0]:this.opacity,baseline:this.baselineOffset[0],align:this.alignOffset?this.alignOffset[0]:0,atlas:this.fontAtlas[0],positionOffset:this.positionOffset}]:this.batch=[]},k.prototype.destroy=function(){},k.prototype.kerning=!0,k.prototype.position={constant:new Float32Array(2)},k.prototype.translate=null,k.prototype.scale=null,k.prototype.font=null,k.prototype.text="",k.prototype.positionOffset=[0,0],k.prototype.opacity=1,k.prototype.color=new Uint8Array([0,0,0,255]),k.prototype.alignOffset=[0,0],k.normalViewport=!1,k.maxAtlasSize=1024,k.atlasCanvas=document.createElement("canvas"),k.atlasContext=k.atlasCanvas.getContext("2d",{alpha:!1}),k.baseFontSize=64,k.fonts={},e.exports=k},{"bit-twiddle":80,"color-normalize":108,"css-font":127,"detect-kerning":154,"es6-weak-map":213,"flatten-vertex-data":220,"font-atlas":221,"font-measure":222,"gl-util/context":312,"is-plain-obj":411,"object-assign":443,"parse-rect":448,"parse-unit":450,"pick-by-alias":454,regl:483,"to-px":520,"typedarray-pool":526}],311:[function(t,e,r){"use strict";var n=t("ndarray"),i=t("ndarray-ops"),a=t("typedarray-pool");e.exports=function(t){if(arguments.length<=1)throw new Error("gl-texture2d: Missing arguments for texture2d constructor");o||function(t){o=[t.LINEAR,t.NEAREST_MIPMAP_LINEAR,t.LINEAR_MIPMAP_NEAREST,t.LINEAR_MIPMAP_NEAREST],s=[t.NEAREST,t.LINEAR,t.NEAREST_MIPMAP_NEAREST,t.NEAREST_MIPMAP_LINEAR,t.LINEAR_MIPMAP_NEAREST,t.LINEAR_MIPMAP_LINEAR],l=[t.REPEAT,t.CLAMP_TO_EDGE,t.MIRRORED_REPEAT]}(t);if("number"==typeof arguments[1])return v(t,arguments[1],arguments[2],arguments[3]||t.RGBA,arguments[4]||t.UNSIGNED_BYTE);if(Array.isArray(arguments[1]))return v(t,0|arguments[1][0],0|arguments[1][1],arguments[2]||t.RGBA,arguments[3]||t.UNSIGNED_BYTE);if("object"==typeof arguments[1]){var e=arguments[1],r=c(e)?e:e.raw;if(r)return function(t,e,r,n,i,a){var o=g(t);return t.texImage2D(t.TEXTURE_2D,0,i,i,a,e),new f(t,o,r,n,i,a)}(t,r,0|e.width,0|e.height,arguments[2]||t.RGBA,arguments[3]||t.UNSIGNED_BYTE);if(e.shape&&e.data&&e.stride)return function(t,e){var r=e.dtype,o=e.shape.slice(),s=t.getParameter(t.MAX_TEXTURE_SIZE);if(o[0]<0||o[0]>s||o[1]<0||o[1]>s)throw new Error("gl-texture2d: Invalid texture size");var l=d(o,e.stride.slice()),c=0;"float32"===r?c=t.FLOAT:"float64"===r?(c=t.FLOAT,l=!1,r="float32"):"uint8"===r?c=t.UNSIGNED_BYTE:(c=t.UNSIGNED_BYTE,l=!1,r="uint8");var h,p,v=0;if(2===o.length)v=t.LUMINANCE,o=[o[0],o[1],1],e=n(e.data,o,[e.stride[0],e.stride[1],1],e.offset);else{if(3!==o.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===o[2])v=t.ALPHA;else if(2===o[2])v=t.LUMINANCE_ALPHA;else if(3===o[2])v=t.RGB;else{if(4!==o[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");v=t.RGBA}}c!==t.FLOAT||t.getExtension("OES_texture_float")||(c=t.UNSIGNED_BYTE,l=!1);var m=e.size;if(l)h=0===e.offset&&e.data.length===m?e.data:e.data.subarray(e.offset,e.offset+m);else{var y=[o[2],o[2]*o[0],1];p=a.malloc(m,r);var x=n(p,o,y,0);"float32"!==r&&"float64"!==r||c!==t.UNSIGNED_BYTE?i.assign(x,e):u(x,e),h=p.subarray(0,m)}var b=g(t);t.texImage2D(t.TEXTURE_2D,0,v,o[0],o[1],0,v,c,h),l||a.free(p);return new f(t,b,o[0],o[1],v,c)}(t,e)}throw new Error("gl-texture2d: Invalid arguments for texture2d constructor")};var o=null,s=null,l=null;function c(t){return"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement||"undefined"!=typeof ImageData&&t instanceof ImageData}var u=function(t,e){i.muls(t,e,255)};function h(t,e,r){var n=t.gl,i=n.getParameter(n.MAX_TEXTURE_SIZE);if(e<0||e>i||r<0||r>i)throw new Error("gl-texture2d: Invalid texture size");return t._shape=[e,r],t.bind(),n.texImage2D(n.TEXTURE_2D,0,t.format,e,r,0,t.format,t.type,null),t._mipLevels=[0],t}function f(t,e,r,n,i,a){this.gl=t,this.handle=e,this.format=i,this.type=a,this._shape=[r,n],this._mipLevels=[0],this._magFilter=t.NEAREST,this._minFilter=t.NEAREST,this._wrapS=t.CLAMP_TO_EDGE,this._wrapT=t.CLAMP_TO_EDGE,this._anisoSamples=1;var o=this,s=[this._wrapS,this._wrapT];Object.defineProperties(s,[{get:function(){return o._wrapS},set:function(t){return o.wrapS=t}},{get:function(){return o._wrapT},set:function(t){return o.wrapT=t}}]),this._wrapVector=s;var l=[this._shape[0],this._shape[1]];Object.defineProperties(l,[{get:function(){return o._shape[0]},set:function(t){return o.width=t}},{get:function(){return o._shape[1]},set:function(t){return o.height=t}}]),this._shapeVector=l}var p=f.prototype;function d(t,e){return 3===t.length?1===e[2]&&e[1]===t[0]*t[2]&&e[0]===t[2]:1===e[0]&&e[1]===t[0]}function g(t){var e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e}function v(t,e,r,n,i){var a=t.getParameter(t.MAX_TEXTURE_SIZE);if(e<0||e>a||r<0||r>a)throw new Error("gl-texture2d: Invalid texture shape");if(i===t.FLOAT&&!t.getExtension("OES_texture_float"))throw new Error("gl-texture2d: Floating point textures not supported on this platform");var o=g(t);return t.texImage2D(t.TEXTURE_2D,0,n,e,r,0,n,i,null),new f(t,o,e,r,n,i)}Object.defineProperties(p,{minFilter:{get:function(){return this._minFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&o.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),s.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t),this._minFilter=t}},magFilter:{get:function(){return this._magFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&o.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),s.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t),this._magFilter=t}},mipSamples:{get:function(){return this._anisoSamples},set:function(t){var e=this._anisoSamples;if(this._anisoSamples=0|Math.max(t,1),e!==this._anisoSamples){var r=this.gl.getExtension("EXT_texture_filter_anisotropic");r&&this.gl.texParameterf(this.gl.TEXTURE_2D,r.TEXTURE_MAX_ANISOTROPY_EXT,this._anisoSamples)}return this._anisoSamples}},wrapS:{get:function(){return this._wrapS},set:function(t){if(this.bind(),l.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,t),this._wrapS=t}},wrapT:{get:function(){return this._wrapT},set:function(t){if(this.bind(),l.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,t),this._wrapT=t}},wrap:{get:function(){return this._wrapVector},set:function(t){if(Array.isArray(t)||(t=[t,t]),2!==t.length)throw new Error("gl-texture2d: Must specify wrap mode for rows and columns");for(var e=0;e<2;++e)if(l.indexOf(t[e])<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);this._wrapS=t[0],this._wrapT=t[1];var r=this.gl;return this.bind(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,this._wrapS),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,this._wrapT),t}},shape:{get:function(){return this._shapeVector},set:function(t){if(Array.isArray(t)){if(2!==t.length)throw new Error("gl-texture2d: Invalid texture shape")}else t=[0|t,0|t];return h(this,0|t[0],0|t[1]),[0|t[0],0|t[1]]}},width:{get:function(){return this._shape[0]},set:function(t){return h(this,t|=0,this._shape[1]),t}},height:{get:function(){return this._shape[1]},set:function(t){return t|=0,h(this,this._shape[0],t),t}}}),p.bind=function(t){var e=this.gl;return void 0!==t&&e.activeTexture(e.TEXTURE0+(0|t)),e.bindTexture(e.TEXTURE_2D,this.handle),void 0!==t?0|t:e.getParameter(e.ACTIVE_TEXTURE)-e.TEXTURE0},p.dispose=function(){this.gl.deleteTexture(this.handle)},p.generateMipmap=function(){this.bind(),this.gl.generateMipmap(this.gl.TEXTURE_2D);for(var t=Math.min(this._shape[0],this._shape[1]),e=0;t>0;++e,t>>>=1)this._mipLevels.indexOf(e)<0&&this._mipLevels.push(e)},p.setPixels=function(t,e,r,o){var s=this.gl;this.bind(),Array.isArray(e)?(o=r,r=0|e[1],e=0|e[0]):(e=e||0,r=r||0),o=o||0;var l=c(t)?t:t.raw;if(l){this._mipLevels.indexOf(o)<0?(s.texImage2D(s.TEXTURE_2D,0,this.format,this.format,this.type,l),this._mipLevels.push(o)):s.texSubImage2D(s.TEXTURE_2D,o,e,r,this.format,this.type,l)}else{if(!(t.shape&&t.stride&&t.data))throw new Error("gl-texture2d: Unsupported data type");if(t.shape.length<2||e+t.shape[1]>this._shape[1]>>>o||r+t.shape[0]>this._shape[0]>>>o||e<0||r<0)throw new Error("gl-texture2d: Texture dimensions are out of bounds");!function(t,e,r,o,s,l,c,h){var f=h.dtype,p=h.shape.slice();if(p.length<2||p.length>3)throw new Error("gl-texture2d: Invalid ndarray, must be 2d or 3d");var g=0,v=0,m=d(p,h.stride.slice());"float32"===f?g=t.FLOAT:"float64"===f?(g=t.FLOAT,m=!1,f="float32"):"uint8"===f?g=t.UNSIGNED_BYTE:(g=t.UNSIGNED_BYTE,m=!1,f="uint8");if(2===p.length)v=t.LUMINANCE,p=[p[0],p[1],1],h=n(h.data,p,[h.stride[0],h.stride[1],1],h.offset);else{if(3!==p.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===p[2])v=t.ALPHA;else if(2===p[2])v=t.LUMINANCE_ALPHA;else if(3===p[2])v=t.RGB;else{if(4!==p[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");v=t.RGBA}p[2]}v!==t.LUMINANCE&&v!==t.ALPHA||s!==t.LUMINANCE&&s!==t.ALPHA||(v=s);if(v!==s)throw new Error("gl-texture2d: Incompatible texture format for setPixels");var y=h.size,x=c.indexOf(o)<0;x&&c.push(o);if(g===l&&m)0===h.offset&&h.data.length===y?x?t.texImage2D(t.TEXTURE_2D,o,s,p[0],p[1],0,s,l,h.data):t.texSubImage2D(t.TEXTURE_2D,o,e,r,p[0],p[1],s,l,h.data):x?t.texImage2D(t.TEXTURE_2D,o,s,p[0],p[1],0,s,l,h.data.subarray(h.offset,h.offset+y)):t.texSubImage2D(t.TEXTURE_2D,o,e,r,p[0],p[1],s,l,h.data.subarray(h.offset,h.offset+y));else{var b;b=l===t.FLOAT?a.mallocFloat32(y):a.mallocUint8(y);var _=n(b,p,[p[2],p[2]*p[0],1]);g===t.FLOAT&&l===t.UNSIGNED_BYTE?u(_,h):i.assign(_,h),x?t.texImage2D(t.TEXTURE_2D,o,s,p[0],p[1],0,s,l,b.subarray(0,y)):t.texSubImage2D(t.TEXTURE_2D,o,e,r,p[0],p[1],s,l,b.subarray(0,y)),l===t.FLOAT?a.freeFloat32(b):a.freeUint8(b)}}(s,e,r,o,this.format,this.type,this._mipLevels,t)}}},{ndarray:439,"ndarray-ops":433,"typedarray-pool":526}],312:[function(t,e,r){"use strict";var n=t("pick-by-alias");function i(t){if(t.container)if(t.container==document.body)document.body.style.width||(t.canvas.width=t.width||t.pixelRatio*window.innerWidth),document.body.style.height||(t.canvas.height=t.height||t.pixelRatio*window.innerHeight);else{var e=t.container.getBoundingClientRect();t.canvas.width=t.width||e.right-e.left,t.canvas.height=t.height||e.bottom-e.top}}function a(t){return"function"==typeof t.getContext&&"width"in t&&"height"in t}e.exports=function(t){var e;if(t?"string"==typeof t&&(t={container:t}):t={},a(t)?t={container:t}:t="string"==typeof(e=t).nodeName&&"function"==typeof e.appendChild&&"function"==typeof e.getBoundingClientRect?{container:t}:function(t){return"function"==typeof t.drawArrays||"function"==typeof t.drawElements}(t)?{gl:t}:n(t,{container:"container target element el canvas holder parent parentNode wrapper use ref root node",gl:"gl context webgl glContext",attrs:"attributes attrs contextAttributes",pixelRatio:"pixelRatio pxRatio px ratio pxratio pixelratio"},!0),t.pixelRatio||(t.pixelRatio=window.pixelRatio||1),t.gl)return t.gl;if(t.canvas&&(t.container=t.canvas.parentNode),t.container){if("string"==typeof t.container){var r=document.querySelector(t.container);if(!r)throw Error("Element "+t.container+" is not found");t.container=r}a(t.container)?(t.canvas=t.container,t.container=t.canvas.parentNode):t.canvas||(t.canvas=document.createElement("canvas"),t.container.appendChild(t.canvas),i(t))}else t.canvas||(t.container=document.body||document.documentElement,t.canvas=document.createElement("canvas"),t.canvas.style.position="absolute",t.canvas.style.top=0,t.canvas.style.left=0,t.container.appendChild(t.canvas),i(t));if(!t.gl)try{t.gl=t.canvas.getContext("webgl",t.attrs)}catch(e){try{t.gl=t.canvas.getContext("experimental-webgl",t.attrs)}catch(e){t.gl=t.canvas.getContext("webgl-experimental",t.attrs)}}return t.gl}},{"pick-by-alias":454}],313:[function(t,e,r){"use strict";e.exports=function(t,e,r){e?e.bind():t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null);var n=0|t.getParameter(t.MAX_VERTEX_ATTRIBS);if(r){if(r.length>n)throw new Error("gl-vao: Too many vertex attributes");for(var i=0;i<r.length;++i){var a=r[i];if(a.buffer){var o=a.buffer,s=a.size||4,l=a.type||t.FLOAT,c=!!a.normalized,u=a.stride||0,h=a.offset||0;o.bind(),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,s,l,c,u,h)}else{if("number"==typeof a)t.vertexAttrib1f(i,a);else if(1===a.length)t.vertexAttrib1f(i,a[0]);else if(2===a.length)t.vertexAttrib2f(i,a[0],a[1]);else if(3===a.length)t.vertexAttrib3f(i,a[0],a[1],a[2]);else{if(4!==a.length)throw new Error("gl-vao: Invalid vertex attribute");t.vertexAttrib4f(i,a[0],a[1],a[2],a[3])}t.disableVertexAttribArray(i)}}for(;i<n;++i)t.disableVertexAttribArray(i)}else for(t.bindBuffer(t.ARRAY_BUFFER,null),i=0;i<n;++i)t.disableVertexAttribArray(i)}},{}],314:[function(t,e,r){"use strict";var n=t("./do-bind.js");function i(t){this.gl=t,this._elements=null,this._attributes=null,this._elementsType=t.UNSIGNED_SHORT}i.prototype.bind=function(){n(this.gl,this._elements,this._attributes)},i.prototype.update=function(t,e,r){this._elements=e,this._attributes=t,this._elementsType=r||this.gl.UNSIGNED_SHORT},i.prototype.dispose=function(){},i.prototype.unbind=function(){},i.prototype.draw=function(t,e,r){r=r||0;var n=this.gl;this._elements?n.drawElements(t,e,this._elementsType,r):n.drawArrays(t,r,e)},e.exports=function(t){return new i(t)}},{"./do-bind.js":313}],315:[function(t,e,r){"use strict";var n=t("./do-bind.js");function i(t,e,r,n,i,a){this.location=t,this.dimension=e,this.a=r,this.b=n,this.c=i,this.d=a}function a(t,e,r){this.gl=t,this._ext=e,this.handle=r,this._attribs=[],this._useElements=!1,this._elementsType=t.UNSIGNED_SHORT}i.prototype.bind=function(t){switch(this.dimension){case 1:t.vertexAttrib1f(this.location,this.a);break;case 2:t.vertexAttrib2f(this.location,this.a,this.b);break;case 3:t.vertexAttrib3f(this.location,this.a,this.b,this.c);break;case 4:t.vertexAttrib4f(this.location,this.a,this.b,this.c,this.d)}},a.prototype.bind=function(){this._ext.bindVertexArrayOES(this.handle);for(var t=0;t<this._attribs.length;++t)this._attribs[t].bind(this.gl)},a.prototype.unbind=function(){this._ext.bindVertexArrayOES(null)},a.prototype.dispose=function(){this._ext.deleteVertexArrayOES(this.handle)},a.prototype.update=function(t,e,r){if(this.bind(),n(this.gl,e,t),this.unbind(),this._attribs.length=0,t)for(var a=0;a<t.length;++a){var o=t[a];"number"==typeof o?this._attribs.push(new i(a,1,o)):Array.isArray(o)&&this._attribs.push(new i(a,o.length,o[0],o[1],o[2],o[3]))}this._useElements=!!e,this._elementsType=r||this.gl.UNSIGNED_SHORT},a.prototype.draw=function(t,e,r){r=r||0;var n=this.gl;this._useElements?n.drawElements(t,e,this._elementsType,r):n.drawArrays(t,r,e)},e.exports=function(t,e){return new a(t,e,e.createVertexArrayOES())}},{"./do-bind.js":313}],316:[function(t,e,r){"use strict";var n=t("./lib/vao-native.js"),i=t("./lib/vao-emulated.js");function a(t){this.bindVertexArrayOES=t.bindVertexArray.bind(t),this.createVertexArrayOES=t.createVertexArray.bind(t),this.deleteVertexArrayOES=t.deleteVertexArray.bind(t)}e.exports=function(t,e,r,o){var s,l=t.createVertexArray?new a(t):t.getExtension("OES_vertex_array_object");return(s=l?n(t,l):i(t)).update(e,r,o),s}},{"./lib/vao-emulated.js":314,"./lib/vao-native.js":315}],317:[function(t,e,r){e.exports=function(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t}},{}],318:[function(t,e,r){e.exports=function(t,e){var r=n(t[0],t[1],t[2]),o=n(e[0],e[1],e[2]);i(r,r),i(o,o);var s=a(r,o);return s>1?0:Math.acos(s)};var n=t("./fromValues"),i=t("./normalize"),a=t("./dot")},{"./dot":328,"./fromValues":334,"./normalize":345}],319:[function(t,e,r){e.exports=function(t,e){return t[0]=Math.ceil(e[0]),t[1]=Math.ceil(e[1]),t[2]=Math.ceil(e[2]),t}},{}],320:[function(t,e,r){e.exports=function(t){var e=new Float32Array(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e}},{}],321:[function(t,e,r){e.exports=function(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}},{}],322:[function(t,e,r){e.exports=function(){var t=new Float32Array(3);return t[0]=0,t[1]=0,t[2]=0,t}},{}],323:[function(t,e,r){e.exports=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=r[0],s=r[1],l=r[2];return t[0]=i*l-a*s,t[1]=a*o-n*l,t[2]=n*s-i*o,t}},{}],324:[function(t,e,r){e.exports=t("./distance")},{"./distance":325}],325:[function(t,e,r){e.exports=function(t,e){var r=e[0]-t[0],n=e[1]-t[1],i=e[2]-t[2];return Math.sqrt(r*r+n*n+i*i)}},{}],326:[function(t,e,r){e.exports=t("./divide")},{"./divide":327}],327:[function(t,e,r){e.exports=function(t,e,r){return t[0]=e[0]/r[0],t[1]=e[1]/r[1],t[2]=e[2]/r[2],t}},{}],328:[function(t,e,r){e.exports=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}},{}],329:[function(t,e,r){e.exports=1e-6},{}],330:[function(t,e,r){e.exports=function(t,e){var r=t[0],i=t[1],a=t[2],o=e[0],s=e[1],l=e[2];return Math.abs(r-o)<=n*Math.max(1,Math.abs(r),Math.abs(o))&&Math.abs(i-s)<=n*Math.max(1,Math.abs(i),Math.abs(s))&&Math.abs(a-l)<=n*Math.max(1,Math.abs(a),Math.abs(l))};var n=t("./epsilon")},{"./epsilon":329}],331:[function(t,e,r){e.exports=function(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]}},{}],332:[function(t,e,r){e.exports=function(t,e){return t[0]=Math.floor(e[0]),t[1]=Math.floor(e[1]),t[2]=Math.floor(e[2]),t}},{}],333:[function(t,e,r){e.exports=function(t,e,r,i,a,o){var s,l;e||(e=3);r||(r=0);l=i?Math.min(i*e+r,t.length):t.length;for(s=r;s<l;s+=e)n[0]=t[s],n[1]=t[s+1],n[2]=t[s+2],a(n,n,o),t[s]=n[0],t[s+1]=n[1],t[s+2]=n[2];return t};var n=t("./create")()},{"./create":322}],334:[function(t,e,r){e.exports=function(t,e,r){var n=new Float32Array(3);return n[0]=t,n[1]=e,n[2]=r,n}},{}],335:[function(t,e,r){e.exports={EPSILON:t("./epsilon"),create:t("./create"),clone:t("./clone"),angle:t("./angle"),fromValues:t("./fromValues"),copy:t("./copy"),set:t("./set"),equals:t("./equals"),exactEquals:t("./exactEquals"),add:t("./add"),subtract:t("./subtract"),sub:t("./sub"),multiply:t("./multiply"),mul:t("./mul"),divide:t("./divide"),div:t("./div"),min:t("./min"),max:t("./max"),floor:t("./floor"),ceil:t("./ceil"),round:t("./round"),scale:t("./scale"),scaleAndAdd:t("./scaleAndAdd"),distance:t("./distance"),dist:t("./dist"),squaredDistance:t("./squaredDistance"),sqrDist:t("./sqrDist"),length:t("./length"),len:t("./len"),squaredLength:t("./squaredLength"),sqrLen:t("./sqrLen"),negate:t("./negate"),inverse:t("./inverse"),normalize:t("./normalize"),dot:t("./dot"),cross:t("./cross"),lerp:t("./lerp"),random:t("./random"),transformMat4:t("./transformMat4"),transformMat3:t("./transformMat3"),transformQuat:t("./transformQuat"),rotateX:t("./rotateX"),rotateY:t("./rotateY"),rotateZ:t("./rotateZ"),forEach:t("./forEach")}},{"./add":317,"./angle":318,"./ceil":319,"./clone":320,"./copy":321,"./create":322,"./cross":323,"./dist":324,"./distance":325,"./div":326,"./divide":327,"./dot":328,"./epsilon":329,"./equals":330,"./exactEquals":331,"./floor":332,"./forEach":333,"./fromValues":334,"./inverse":336,"./len":337,"./length":338,"./lerp":339,"./max":340,"./min":341,"./mul":342,"./multiply":343,"./negate":344,"./normalize":345,"./random":346,"./rotateX":347,"./rotateY":348,"./rotateZ":349,"./round":350,"./scale":351,"./scaleAndAdd":352,"./set":353,"./sqrDist":354,"./sqrLen":355,"./squaredDistance":356,"./squaredLength":357,"./sub":358,"./subtract":359,"./transformMat3":360,"./transformMat4":361,"./transformQuat":362}],336:[function(t,e,r){e.exports=function(t,e){return t[0]=1/e[0],t[1]=1/e[1],t[2]=1/e[2],t}},{}],337:[function(t,e,r){e.exports=t("./length")},{"./length":338}],338:[function(t,e,r){e.exports=function(t){var e=t[0],r=t[1],n=t[2];return Math.sqrt(e*e+r*r+n*n)}},{}],339:[function(t,e,r){e.exports=function(t,e,r,n){var i=e[0],a=e[1],o=e[2];return t[0]=i+n*(r[0]-i),t[1]=a+n*(r[1]-a),t[2]=o+n*(r[2]-o),t}},{}],340:[function(t,e,r){e.exports=function(t,e,r){return t[0]=Math.max(e[0],r[0]),t[1]=Math.max(e[1],r[1]),t[2]=Math.max(e[2],r[2]),t}},{}],341:[function(t,e,r){e.exports=function(t,e,r){return t[0]=Math.min(e[0],r[0]),t[1]=Math.min(e[1],r[1]),t[2]=Math.min(e[2],r[2]),t}},{}],342:[function(t,e,r){e.exports=t("./multiply")},{"./multiply":343}],343:[function(t,e,r){e.exports=function(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t}},{}],344:[function(t,e,r){e.exports=function(t,e){return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t}},{}],345:[function(t,e,r){e.exports=function(t,e){var r=e[0],n=e[1],i=e[2],a=r*r+n*n+i*i;a>0&&(a=1/Math.sqrt(a),t[0]=e[0]*a,t[1]=e[1]*a,t[2]=e[2]*a);return t}},{}],346:[function(t,e,r){e.exports=function(t,e){e=e||1;var r=2*Math.random()*Math.PI,n=2*Math.random()-1,i=Math.sqrt(1-n*n)*e;return t[0]=Math.cos(r)*i,t[1]=Math.sin(r)*i,t[2]=n*e,t}},{}],347:[function(t,e,r){e.exports=function(t,e,r,n){var i=r[1],a=r[2],o=e[1]-i,s=e[2]-a,l=Math.sin(n),c=Math.cos(n);return t[0]=e[0],t[1]=i+o*c-s*l,t[2]=a+o*l+s*c,t}},{}],348:[function(t,e,r){e.exports=function(t,e,r,n){var i=r[0],a=r[2],o=e[0]-i,s=e[2]-a,l=Math.sin(n),c=Math.cos(n);return t[0]=i+s*l+o*c,t[1]=e[1],t[2]=a+s*c-o*l,t}},{}],349:[function(t,e,r){e.exports=function(t,e,r,n){var i=r[0],a=r[1],o=e[0]-i,s=e[1]-a,l=Math.sin(n),c=Math.cos(n);return t[0]=i+o*c-s*l,t[1]=a+o*l+s*c,t[2]=e[2],t}},{}],350:[function(t,e,r){e.exports=function(t,e){return t[0]=Math.round(e[0]),t[1]=Math.round(e[1]),t[2]=Math.round(e[2]),t}},{}],351:[function(t,e,r){e.exports=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t}},{}],352:[function(t,e,r){e.exports=function(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t}},{}],353:[function(t,e,r){e.exports=function(t,e,r,n){return t[0]=e,t[1]=r,t[2]=n,t}},{}],354:[function(t,e,r){e.exports=t("./squaredDistance")},{"./squaredDistance":356}],355:[function(t,e,r){e.exports=t("./squaredLength")},{"./squaredLength":357}],356:[function(t,e,r){e.exports=function(t,e){var r=e[0]-t[0],n=e[1]-t[1],i=e[2]-t[2];return r*r+n*n+i*i}},{}],357:[function(t,e,r){e.exports=function(t){var e=t[0],r=t[1],n=t[2];return e*e+r*r+n*n}},{}],358:[function(t,e,r){e.exports=t("./subtract")},{"./subtract":359}],359:[function(t,e,r){e.exports=function(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t}},{}],360:[function(t,e,r){e.exports=function(t,e,r){var n=e[0],i=e[1],a=e[2];return t[0]=n*r[0]+i*r[3]+a*r[6],t[1]=n*r[1]+i*r[4]+a*r[7],t[2]=n*r[2]+i*r[5]+a*r[8],t}},{}],361:[function(t,e,r){e.exports=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=r[3]*n+r[7]*i+r[11]*a+r[15];return o=o||1,t[0]=(r[0]*n+r[4]*i+r[8]*a+r[12])/o,t[1]=(r[1]*n+r[5]*i+r[9]*a+r[13])/o,t[2]=(r[2]*n+r[6]*i+r[10]*a+r[14])/o,t}},{}],362:[function(t,e,r){e.exports=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=r[0],s=r[1],l=r[2],c=r[3],u=c*n+s*a-l*i,h=c*i+l*n-o*a,f=c*a+o*i-s*n,p=-o*n-s*i-l*a;return t[0]=u*c+p*-o+h*-l-f*-s,t[1]=h*c+p*-s+f*-o-u*-l,t[2]=f*c+p*-l+u*-s-h*-o,t}},{}],363:[function(t,e,r){e.exports=function(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t[3]=e[3]+r[3],t}},{}],364:[function(t,e,r){e.exports=function(t){var e=new Float32Array(4);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e}},{}],365:[function(t,e,r){e.exports=function(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t}},{}],366:[function(t,e,r){e.exports=function(){var t=new Float32Array(4);return t[0]=0,t[1]=0,t[2]=0,t[3]=0,t}},{}],367:[function(t,e,r){e.exports=function(t,e){var r=e[0]-t[0],n=e[1]-t[1],i=e[2]-t[2],a=e[3]-t[3];return Math.sqrt(r*r+n*n+i*i+a*a)}},{}],368:[function(t,e,r){e.exports=function(t,e,r){return t[0]=e[0]/r[0],t[1]=e[1]/r[1],t[2]=e[2]/r[2],t[3]=e[3]/r[3],t}},{}],369:[function(t,e,r){e.exports=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]}},{}],370:[function(t,e,r){e.exports=function(t,e,r,n){var i=new Float32Array(4);return i[0]=t,i[1]=e,i[2]=r,i[3]=n,i}},{}],371:[function(t,e,r){e.exports={create:t("./create"),clone:t("./clone"),fromValues:t("./fromValues"),copy:t("./copy"),set:t("./set"),add:t("./add"),subtract:t("./subtract"),multiply:t("./multiply"),divide:t("./divide"),min:t("./min"),max:t("./max"),scale:t("./scale"),scaleAndAdd:t("./scaleAndAdd"),distance:t("./distance"),squaredDistance:t("./squaredDistance"),length:t("./length"),squaredLength:t("./squaredLength"),negate:t("./negate"),inverse:t("./inverse"),normalize:t("./normalize"),dot:t("./dot"),lerp:t("./lerp"),random:t("./random"),transformMat4:t("./transformMat4"),transformQuat:t("./transformQuat")}},{"./add":363,"./clone":364,"./copy":365,"./create":366,"./distance":367,"./divide":368,"./dot":369,"./fromValues":370,"./inverse":372,"./length":373,"./lerp":374,"./max":375,"./min":376,"./multiply":377,"./negate":378,"./normalize":379,"./random":380,"./scale":381,"./scaleAndAdd":382,"./set":383,"./squaredDistance":384,"./squaredLength":385,"./subtract":386,"./transformMat4":387,"./transformQuat":388}],372:[function(t,e,r){e.exports=function(t,e){return t[0]=1/e[0],t[1]=1/e[1],t[2]=1/e[2],t[3]=1/e[3],t}},{}],373:[function(t,e,r){e.exports=function(t){var e=t[0],r=t[1],n=t[2],i=t[3];return Math.sqrt(e*e+r*r+n*n+i*i)}},{}],374:[function(t,e,r){e.exports=function(t,e,r,n){var i=e[0],a=e[1],o=e[2],s=e[3];return t[0]=i+n*(r[0]-i),t[1]=a+n*(r[1]-a),t[2]=o+n*(r[2]-o),t[3]=s+n*(r[3]-s),t}},{}],375:[function(t,e,r){e.exports=function(t,e,r){return t[0]=Math.max(e[0],r[0]),t[1]=Math.max(e[1],r[1]),t[2]=Math.max(e[2],r[2]),t[3]=Math.max(e[3],r[3]),t}},{}],376:[function(t,e,r){e.exports=function(t,e,r){return t[0]=Math.min(e[0],r[0]),t[1]=Math.min(e[1],r[1]),t[2]=Math.min(e[2],r[2]),t[3]=Math.min(e[3],r[3]),t}},{}],377:[function(t,e,r){e.exports=function(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t[3]=e[3]*r[3],t}},{}],378:[function(t,e,r){e.exports=function(t,e){return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t}},{}],379:[function(t,e,r){e.exports=function(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=r*r+n*n+i*i+a*a;o>0&&(o=1/Math.sqrt(o),t[0]=r*o,t[1]=n*o,t[2]=i*o,t[3]=a*o);return t}},{}],380:[function(t,e,r){var n=t("./normalize"),i=t("./scale");e.exports=function(t,e){return e=e||1,t[0]=Math.random(),t[1]=Math.random(),t[2]=Math.random(),t[3]=Math.random(),n(t,t),i(t,t,e),t}},{"./normalize":379,"./scale":381}],381:[function(t,e,r){e.exports=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t}},{}],382:[function(t,e,r){e.exports=function(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t[3]=e[3]+r[3]*n,t}},{}],383:[function(t,e,r){e.exports=function(t,e,r,n,i){return t[0]=e,t[1]=r,t[2]=n,t[3]=i,t}},{}],384:[function(t,e,r){e.exports=function(t,e){var r=e[0]-t[0],n=e[1]-t[1],i=e[2]-t[2],a=e[3]-t[3];return r*r+n*n+i*i+a*a}},{}],385:[function(t,e,r){e.exports=function(t){var e=t[0],r=t[1],n=t[2],i=t[3];return e*e+r*r+n*n+i*i}},{}],386:[function(t,e,r){e.exports=function(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t[3]=e[3]-r[3],t}},{}],387:[function(t,e,r){e.exports=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*a+r[12]*o,t[1]=r[1]*n+r[5]*i+r[9]*a+r[13]*o,t[2]=r[2]*n+r[6]*i+r[10]*a+r[14]*o,t[3]=r[3]*n+r[7]*i+r[11]*a+r[15]*o,t}},{}],388:[function(t,e,r){e.exports=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=r[0],s=r[1],l=r[2],c=r[3],u=c*n+s*a-l*i,h=c*i+l*n-o*a,f=c*a+o*i-s*n,p=-o*n-s*i-l*a;return t[0]=u*c+p*-o+h*-l-f*-s,t[1]=h*c+p*-s+f*-o-u*-l,t[2]=f*c+p*-l+u*-s-h*-o,t[3]=e[3],t}},{}],389:[function(t,e,r){e.exports=function(t,e,r,a){return n[0]=a,n[1]=r,n[2]=e,n[3]=t,i[0]};var n=new Uint8Array(4),i=new Float32Array(n.buffer)},{}],390:[function(t,e,r){var n=t("glsl-tokenizer"),i=t("atob-lite");e.exports=function(t){for(var e=Array.isArray(t)?t:n(t),r=0;r<e.length;r++){var a=e[r];if("preprocessor"===a.type){var o=a.data.match(/\#define\s+SHADER_NAME(_B64)?\s+(.+)$/);if(o&&o[2]){var s=o[1],l=o[2];return(s?i(l):l).trim()}}}}},{"atob-lite":60,"glsl-tokenizer":397}],391:[function(t,e,r){e.exports=function(t){var e,r,k,A=0,M=0,T=l,S=[],E=[],C=1,L=0,z=0,O=!1,I=!1,D="",P=a,R=n;"300 es"===(t=t||{}).version&&(P=s,R=o);return function(t){return E=[],null!==t?function(t){var r;A=0,k=(D+=t).length;for(;e=D[A],A<k;){switch(r=A,T){case u:A=V();break;case h:case f:A=j();break;case p:A=U();break;case d:A=G();break;case _:A=H();break;case g:A=Y();break;case c:A=W();break;case x:A=N();break;case l:A=B()}if(r!==A)switch(D[r]){case"\n":L=0,++C;break;default:++L}}return M+=A,D=D.slice(A),E}(t.replace?t.replace(/\r\n/g,"\n"):t):function(t){S.length&&F(S.join(""));return T=b,F("(eof)"),E}()};function F(t){t.length&&E.push({type:w[T],data:t,position:z,line:C,column:L})}function B(){return S=S.length?[]:S,"/"===r&&"*"===e?(z=M+A-1,T=u,r=e,A+1):"/"===r&&"/"===e?(z=M+A-1,T=h,r=e,A+1):"#"===e?(T=f,z=M+A,A):/\s/.test(e)?(T=x,z=M+A,A):(O=/\d/.test(e),I=/[^\w_]/.test(e),z=M+A,T=O?d:I?p:c,A)}function N(){return/[^\s]/g.test(e)?(F(S.join("")),T=l,A):(S.push(e),r=e,A+1)}function j(){return"\r"!==e&&"\n"!==e||"\\"===r?(S.push(e),r=e,A+1):(F(S.join("")),T=l,A)}function V(){return"/"===e&&"*"===r?(S.push(e),F(S.join("")),T=l,A+1):(S.push(e),r=e,A+1)}function U(){if("."===r&&/\d/.test(e))return T=g,A;if("/"===r&&"*"===e)return T=u,A;if("/"===r&&"/"===e)return T=h,A;if("."===e&&S.length){for(;q(S););return T=g,A}if(";"===e||")"===e||"("===e){if(S.length)for(;q(S););return F(e),T=l,A+1}var t=2===S.length&&"="!==e;if(/[\w_\d\s]/.test(e)||t){for(;q(S););return T=l,A}return S.push(e),r=e,A+1}function q(t){for(var e,r,n=0;;){if(e=i.indexOf(t.slice(0,t.length+n).join("")),r=i[e],-1===e){if(n--+t.length>0)continue;r=t.slice(0,1).join("")}return F(r),z+=r.length,(S=S.slice(r.length)).length}}function H(){return/[^a-fA-F0-9]/.test(e)?(F(S.join("")),T=l,A):(S.push(e),r=e,A+1)}function G(){return"."===e?(S.push(e),T=g,r=e,A+1):/[eE]/.test(e)?(S.push(e),T=g,r=e,A+1):"x"===e&&1===S.length&&"0"===S[0]?(T=_,S.push(e),r=e,A+1):/[^\d]/.test(e)?(F(S.join("")),T=l,A):(S.push(e),r=e,A+1)}function Y(){return"f"===e&&(S.push(e),r=e,A+=1),/[eE]/.test(e)?(S.push(e),r=e,A+1):"-"===e&&/[eE]/.test(r)?(S.push(e),r=e,A+1):/[^\d]/.test(e)?(F(S.join("")),T=l,A):(S.push(e),r=e,A+1)}function W(){if(/[^\d\w_]/.test(e)){var t=S.join("");return T=R.indexOf(t)>-1?y:P.indexOf(t)>-1?m:v,F(S.join("")),T=l,A}return S.push(e),r=e,A+1}};var n=t("./lib/literals"),i=t("./lib/operators"),a=t("./lib/builtins"),o=t("./lib/literals-300es"),s=t("./lib/builtins-300es"),l=999,c=9999,u=0,h=1,f=2,p=3,d=4,g=5,v=6,m=7,y=8,x=9,b=10,_=11,w=["block-comment","line-comment","preprocessor","operator","integer","float","ident","builtin","keyword","whitespace","eof","integer"]},{"./lib/builtins":393,"./lib/builtins-300es":392,"./lib/literals":395,"./lib/literals-300es":394,"./lib/operators":396}],392:[function(t,e,r){var n=t("./builtins");n=n.slice().filter(function(t){return!/^(gl\_|texture)/.test(t)}),e.exports=n.concat(["gl_VertexID","gl_InstanceID","gl_Position","gl_PointSize","gl_FragCoord","gl_FrontFacing","gl_FragDepth","gl_PointCoord","gl_MaxVertexAttribs","gl_MaxVertexUniformVectors","gl_MaxVertexOutputVectors","gl_MaxFragmentInputVectors","gl_MaxVertexTextureImageUnits","gl_MaxCombinedTextureImageUnits","gl_MaxTextureImageUnits","gl_MaxFragmentUniformVectors","gl_MaxDrawBuffers","gl_MinProgramTexelOffset","gl_MaxProgramTexelOffset","gl_DepthRangeParameters","gl_DepthRange","trunc","round","roundEven","isnan","isinf","floatBitsToInt","floatBitsToUint","intBitsToFloat","uintBitsToFloat","packSnorm2x16","unpackSnorm2x16","packUnorm2x16","unpackUnorm2x16","packHalf2x16","unpackHalf2x16","outerProduct","transpose","determinant","inverse","texture","textureSize","textureProj","textureLod","textureOffset","texelFetch","texelFetchOffset","textureProjOffset","textureLodOffset","textureProjLod","textureProjLodOffset","textureGrad","textureGradOffset","textureProjGrad","textureProjGradOffset"])},{"./builtins":393}],393:[function(t,e,r){e.exports=["abs","acos","all","any","asin","atan","ceil","clamp","cos","cross","dFdx","dFdy","degrees","distance","dot","equal","exp","exp2","faceforward","floor","fract","gl_BackColor","gl_BackLightModelProduct","gl_BackLightProduct","gl_BackMaterial","gl_BackSecondaryColor","gl_ClipPlane","gl_ClipVertex","gl_Color","gl_DepthRange","gl_DepthRangeParameters","gl_EyePlaneQ","gl_EyePlaneR","gl_EyePlaneS","gl_EyePlaneT","gl_Fog","gl_FogCoord","gl_FogFragCoord","gl_FogParameters","gl_FragColor","gl_FragCoord","gl_FragData","gl_FragDepth","gl_FragDepthEXT","gl_FrontColor","gl_FrontFacing","gl_FrontLightModelProduct","gl_FrontLightProduct","gl_FrontMaterial","gl_FrontSecondaryColor","gl_LightModel","gl_LightModelParameters","gl_LightModelProducts","gl_LightProducts","gl_LightSource","gl_LightSourceParameters","gl_MaterialParameters","gl_MaxClipPlanes","gl_MaxCombinedTextureImageUnits","gl_MaxDrawBuffers","gl_MaxFragmentUniformComponents","gl_MaxLights","gl_MaxTextureCoords","gl_MaxTextureImageUnits","gl_MaxTextureUnits","gl_MaxVaryingFloats","gl_MaxVertexAttribs","gl_MaxVertexTextureImageUnits","gl_MaxVertexUniformComponents","gl_ModelViewMatrix","gl_ModelViewMatrixInverse","gl_ModelViewMatrixInverseTranspose","gl_ModelViewMatrixTranspose","gl_ModelViewProjectionMatrix","gl_ModelViewProjectionMatrixInverse","gl_ModelViewProjectionMatrixInverseTranspose","gl_ModelViewProjectionMatrixTranspose","gl_MultiTexCoord0","gl_MultiTexCoord1","gl_MultiTexCoord2","gl_MultiTexCoord3","gl_MultiTexCoord4","gl_MultiTexCoord5","gl_MultiTexCoord6","gl_MultiTexCoord7","gl_Normal","gl_NormalMatrix","gl_NormalScale","gl_ObjectPlaneQ","gl_ObjectPlaneR","gl_ObjectPlaneS","gl_ObjectPlaneT","gl_Point","gl_PointCoord","gl_PointParameters","gl_PointSize","gl_Position","gl_ProjectionMatrix","gl_ProjectionMatrixInverse","gl_ProjectionMatrixInverseTranspose","gl_ProjectionMatrixTranspose","gl_SecondaryColor","gl_TexCoord","gl_TextureEnvColor","gl_TextureMatrix","gl_TextureMatrixInverse","gl_TextureMatrixInverseTranspose","gl_TextureMatrixTranspose","gl_Vertex","greaterThan","greaterThanEqual","inversesqrt","length","lessThan","lessThanEqual","log","log2","matrixCompMult","max","min","mix","mod","normalize","not","notEqual","pow","radians","reflect","refract","sign","sin","smoothstep","sqrt","step","tan","texture2D","texture2DLod","texture2DProj","texture2DProjLod","textureCube","textureCubeLod","texture2DLodEXT","texture2DProjLodEXT","textureCubeLodEXT","texture2DGradEXT","texture2DProjGradEXT","textureCubeGradEXT"]},{}],394:[function(t,e,r){var n=t("./literals");e.exports=n.slice().concat(["layout","centroid","smooth","case","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4","uint","uvec2","uvec3","uvec4","samplerCubeShadow","sampler2DArray","sampler2DArrayShadow","isampler2D","isampler3D","isamplerCube","isampler2DArray","usampler2D","usampler3D","usamplerCube","usampler2DArray","coherent","restrict","readonly","writeonly","resource","atomic_uint","noperspective","patch","sample","subroutine","common","partition","active","filter","image1D","image2D","image3D","imageCube","iimage1D","iimage2D","iimage3D","iimageCube","uimage1D","uimage2D","uimage3D","uimageCube","image1DArray","image2DArray","iimage1DArray","iimage2DArray","uimage1DArray","uimage2DArray","image1DShadow","image2DShadow","image1DArrayShadow","image2DArrayShadow","imageBuffer","iimageBuffer","uimageBuffer","sampler1DArray","sampler1DArrayShadow","isampler1D","isampler1DArray","usampler1D","usampler1DArray","isampler2DRect","usampler2DRect","samplerBuffer","isamplerBuffer","usamplerBuffer","sampler2DMS","isampler2DMS","usampler2DMS","sampler2DMSArray","isampler2DMSArray","usampler2DMSArray"])},{"./literals":395}],395:[function(t,e,r){e.exports=["precision","highp","mediump","lowp","attribute","const","uniform","varying","break","continue","do","for","while","if","else","in","out","inout","float","int","void","bool","true","false","discard","return","mat2","mat3","mat4","vec2","vec3","vec4","ivec2","ivec3","ivec4","bvec2","bvec3","bvec4","sampler1D","sampler2D","sampler3D","samplerCube","sampler1DShadow","sampler2DShadow","struct","asm","class","union","enum","typedef","template","this","packed","goto","switch","default","inline","noinline","volatile","public","static","extern","external","interface","long","short","double","half","fixed","unsigned","input","output","hvec2","hvec3","hvec4","dvec2","dvec3","dvec4","fvec2","fvec3","fvec4","sampler2DRect","sampler3DRect","sampler2DRectShadow","sizeof","cast","namespace","using"]},{}],396:[function(t,e,r){e.exports=["<<=",">>=","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^^","^=","|=","(",")","[","]",".","!","~","*","/","%","+","-","<",">","&","^","|","?",":","=",",",";","{","}"]},{}],397:[function(t,e,r){var n=t("./index");e.exports=function(t,e){var r=n(e),i=[];return i=(i=i.concat(r(t))).concat(r(null))}},{"./index":391}],398:[function(t,e,r){e.exports=function(t){"string"==typeof t&&(t=[t]);for(var e=[].slice.call(arguments,1),r=[],n=0;n<t.length-1;n++)r.push(t[n],e[n]||"");return r.push(t[n]),r.join("")}},{}],399:[function(t,e,r){(function(r){"use strict";var n,i=t("is-browser");n="function"==typeof r.matchMedia?!r.matchMedia("(hover: none)").matches:i,e.exports=n}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"is-browser":406}],400:[function(t,e,r){"use strict";var n=t("is-browser");e.exports=n&&function(){var t=!1;try{var e=Object.defineProperty({},"passive",{get:function(){t=!0}});window.addEventListener("test",null,e),window.removeEventListener("test",null,e)}catch(e){t=!1}return t}()},{"is-browser":406}],401:[function(t,e,r){r.read=function(t,e,r,n,i){var a,o,s=8*i-n-1,l=(1<<s)-1,c=l>>1,u=-7,h=r?i-1:0,f=r?-1:1,p=t[e+h];for(h+=f,a=p&(1<<-u)-1,p>>=-u,u+=s;u>0;a=256*a+t[e+h],h+=f,u-=8);for(o=a&(1<<-u)-1,a>>=-u,u+=n;u>0;o=256*o+t[e+h],h+=f,u-=8);if(0===a)a=1-c;else{if(a===l)return o?NaN:1/0*(p?-1:1);o+=Math.pow(2,n),a-=c}return(p?-1:1)*o*Math.pow(2,a-n)},r.write=function(t,e,r,n,i,a){var o,s,l,c=8*a-i-1,u=(1<<c)-1,h=u>>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:a-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=u):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),(e+=o+h>=1?f/l:f*Math.pow(2,1-h))*l>=2&&(o++,l/=2),o+h>=u?(s=0,o=u):o+h>=1?(s=(e*l-1)*Math.pow(2,i),o+=h):(s=e*Math.pow(2,h-1)*Math.pow(2,i),o=0));i>=8;t[r+p]=255&s,p+=d,s/=256,i-=8);for(o=o<<i|s,c+=i;c>0;t[r+p]=255&o,p+=d,o/=256,c-=8);t[r+p-d]|=128*g}},{}],402:[function(t,e,r){"use strict";e.exports=function(t,e){var r=t.length;if(0===r)throw new Error("Must have at least d+1 points");var i=t[0].length;if(r<=i)throw new Error("Must input at least d+1 points");var o=t.slice(0,i+1),s=n.apply(void 0,o);if(0===s)throw new Error("Input not in general position");for(var l=new Array(i+1),u=0;u<=i;++u)l[u]=u;s<0&&(l[0]=1,l[1]=0);for(var h=new a(l,new Array(i+1),!1),f=h.adjacent,p=new Array(i+2),u=0;u<=i;++u){for(var d=l.slice(),g=0;g<=i;++g)g===u&&(d[g]=-1);var v=d[0];d[0]=d[1],d[1]=v;var m=new a(d,new Array(i+1),!0);f[u]=m,p[u]=m}p[i+1]=h;for(var u=0;u<=i;++u)for(var d=f[u].vertices,y=f[u].adjacent,g=0;g<=i;++g){var x=d[g];if(x<0)y[g]=h;else for(var b=0;b<=i;++b)f[b].vertices.indexOf(x)<0&&(y[g]=f[b])}for(var _=new c(i,o,p),w=!!e,u=i+1;u<r;++u)_.insert(t[u],w);return _.boundary()};var n=t("robust-orientation"),i=t("simplicial-complex").compareCells;function a(t,e,r){this.vertices=t,this.adjacent=e,this.boundary=r,this.lastVisited=-1}function o(t,e,r){this.vertices=t,this.cell=e,this.index=r}function s(t,e){return i(t.vertices,e.vertices)}a.prototype.flip=function(){var t=this.vertices[0];this.vertices[0]=this.vertices[1],this.vertices[1]=t;var e=this.adjacent[0];this.adjacent[0]=this.adjacent[1],this.adjacent[1]=e};var l=[];function c(t,e,r){this.dimension=t,this.vertices=e,this.simplices=r,this.interior=r.filter(function(t){return!t.boundary}),this.tuple=new Array(t+1);for(var i=0;i<=t;++i)this.tuple[i]=this.vertices[i];var a=l[t];a||(a=l[t]=function(t){for(var e=["function orient(){var tuple=this.tuple;return test("],r=0;r<=t;++r)r>0&&e.push(","),e.push("tuple[",r,"]");e.push(")}return orient");var i=new Function("test",e.join("")),a=n[t+1];return a||(a=n),i(a)}(t)),this.orient=a}var u=c.prototype;u.handleBoundaryDegeneracy=function(t,e){var r=this.dimension,n=this.vertices.length-1,i=this.tuple,a=this.vertices,o=[t];for(t.lastVisited=-n;o.length>0;){(t=o.pop()).vertices;for(var s=t.adjacent,l=0;l<=r;++l){var c=s[l];if(c.boundary&&!(c.lastVisited<=-n)){for(var u=c.vertices,h=0;h<=r;++h){var f=u[h];i[h]=f<0?e:a[f]}var p=this.orient();if(p>0)return c;c.lastVisited=-n,0===p&&o.push(c)}}}return null},u.walk=function(t,e){var r=this.vertices.length-1,n=this.dimension,i=this.vertices,a=this.tuple,o=e?this.interior.length*Math.random()|0:this.interior.length-1,s=this.interior[o];t:for(;!s.boundary;){for(var l=s.vertices,c=s.adjacent,u=0;u<=n;++u)a[u]=i[l[u]];s.lastVisited=r;for(u=0;u<=n;++u){var h=c[u];if(!(h.lastVisited>=r)){var f=a[u];a[u]=t;var p=this.orient();if(a[u]=f,p<0){s=h;continue t}h.boundary?h.lastVisited=-r:h.lastVisited=r}}return}return s},u.addPeaks=function(t,e){var r=this.vertices.length-1,n=this.dimension,i=this.vertices,l=this.tuple,c=this.interior,u=this.simplices,h=[e];e.lastVisited=r,e.vertices[e.vertices.indexOf(-1)]=r,e.boundary=!1,c.push(e);for(var f=[];h.length>0;){var p=(e=h.pop()).vertices,d=e.adjacent,g=p.indexOf(r);if(!(g<0))for(var v=0;v<=n;++v)if(v!==g){var m=d[v];if(m.boundary&&!(m.lastVisited>=r)){var y=m.vertices;if(m.lastVisited!==-r){for(var x=0,b=0;b<=n;++b)y[b]<0?(x=b,l[b]=t):l[b]=i[y[b]];if(this.orient()>0){y[x]=r,m.boundary=!1,c.push(m),h.push(m),m.lastVisited=r;continue}m.lastVisited=-r}var _=m.adjacent,w=p.slice(),k=d.slice(),A=new a(w,k,!0);u.push(A);var M=_.indexOf(e);if(!(M<0)){_[M]=A,k[g]=m,w[v]=-1,k[v]=e,d[v]=A,A.flip();for(b=0;b<=n;++b){var T=w[b];if(!(T<0||T===r)){for(var S=new Array(n-1),E=0,C=0;C<=n;++C){var L=w[C];L<0||C===b||(S[E++]=L)}f.push(new o(S,A,b))}}}}}}f.sort(s);for(v=0;v+1<f.length;v+=2){var z=f[v],O=f[v+1],I=z.index,D=O.index;I<0||D<0||(z.cell.adjacent[z.index]=O.cell,O.cell.adjacent[O.index]=z.cell)}},u.insert=function(t,e){var r=this.vertices;r.push(t);var n=this.walk(t,e);if(n){for(var i=this.dimension,a=this.tuple,o=0;o<=i;++o){var s=n.vertices[o];a[o]=s<0?t:r[s]}var l=this.orient(a);l<0||(0!==l||(n=this.handleBoundaryDegeneracy(n,t)))&&this.addPeaks(t,n)}},u.boundary=function(){for(var t=this.dimension,e=[],r=this.simplices,n=r.length,i=0;i<n;++i){var a=r[i];if(a.boundary){for(var o=new Array(t),s=a.vertices,l=0,c=0,u=0;u<=t;++u)s[u]>=0?o[l++]=s[u]:c=1&u;if(c===(1&t)){var h=o[0];o[0]=o[1],o[1]=h}e.push(o)}}return e}},{"robust-orientation":491,"simplicial-complex":501}],403:[function(t,e,r){"use strict";var n=t("binary-search-bounds"),i=0,a=1;function o(t,e,r,n,i){this.mid=t,this.left=e,this.right=r,this.leftPoints=n,this.rightPoints=i,this.count=(e?e.count:0)+(r?r.count:0)+n.length}e.exports=function(t){if(!t||0===t.length)return new x(null);return new x(y(t))};var s=o.prototype;function l(t,e){t.mid=e.mid,t.left=e.left,t.right=e.right,t.leftPoints=e.leftPoints,t.rightPoints=e.rightPoints,t.count=e.count}function c(t,e){var r=y(e);t.mid=r.mid,t.left=r.left,t.right=r.right,t.leftPoints=r.leftPoints,t.rightPoints=r.rightPoints,t.count=r.count}function u(t,e){var r=t.intervals([]);r.push(e),c(t,r)}function h(t,e){var r=t.intervals([]),n=r.indexOf(e);return n<0?i:(r.splice(n,1),c(t,r),a)}function f(t,e,r){for(var n=0;n<t.length&&t[n][0]<=e;++n){var i=r(t[n]);if(i)return i}}function p(t,e,r){for(var n=t.length-1;n>=0&&t[n][1]>=e;--n){var i=r(t[n]);if(i)return i}}function d(t,e){for(var r=0;r<t.length;++r){var n=e(t[r]);if(n)return n}}function g(t,e){return t-e}function v(t,e){var r=t[0]-e[0];return r||t[1]-e[1]}function m(t,e){var r=t[1]-e[1];return r||t[0]-e[0]}function y(t){if(0===t.length)return null;for(var e=[],r=0;r<t.length;++r)e.push(t[r][0],t[r][1]);e.sort(g);var n=e[e.length>>1],i=[],a=[],s=[];for(r=0;r<t.length;++r){var l=t[r];l[1]<n?i.push(l):n<l[0]?a.push(l):s.push(l)}var c=s,u=s.slice();return c.sort(v),u.sort(m),new o(n,y(i),y(a),c,u)}function x(t){this.root=t}s.intervals=function(t){return t.push.apply(t,this.leftPoints),this.left&&this.left.intervals(t),this.right&&this.right.intervals(t),t},s.insert=function(t){var e=this.count-this.leftPoints.length;if(this.count+=1,t[1]<this.mid)this.left?4*(this.left.count+1)>3*(e+1)?u(this,t):this.left.insert(t):this.left=y([t]);else if(t[0]>this.mid)this.right?4*(this.right.count+1)>3*(e+1)?u(this,t):this.right.insert(t):this.right=y([t]);else{var r=n.ge(this.leftPoints,t,v),i=n.ge(this.rightPoints,t,m);this.leftPoints.splice(r,0,t),this.rightPoints.splice(i,0,t)}},s.remove=function(t){var e=this.count-this.leftPoints;if(t[1]<this.mid)return this.left?4*(this.right?this.right.count:0)>3*(e-1)?h(this,t):2===(c=this.left.remove(t))?(this.left=null,this.count-=1,a):(c===a&&(this.count-=1),c):i;if(t[0]>this.mid)return this.right?4*(this.left?this.left.count:0)>3*(e-1)?h(this,t):2===(c=this.right.remove(t))?(this.right=null,this.count-=1,a):(c===a&&(this.count-=1),c):i;if(1===this.count)return this.leftPoints[0]===t?2:i;if(1===this.leftPoints.length&&this.leftPoints[0]===t){if(this.left&&this.right){for(var r=this,o=this.left;o.right;)r=o,o=o.right;if(r===this)o.right=this.right;else{var s=this.left,c=this.right;r.count-=o.count,r.right=o.left,o.left=s,o.right=c}l(this,o),this.count=(this.left?this.left.count:0)+(this.right?this.right.count:0)+this.leftPoints.length}else this.left?l(this,this.left):l(this,this.right);return a}for(s=n.ge(this.leftPoints,t,v);s<this.leftPoints.length&&this.leftPoints[s][0]===t[0];++s)if(this.leftPoints[s]===t){this.count-=1,this.leftPoints.splice(s,1);for(c=n.ge(this.rightPoints,t,m);c<this.rightPoints.length&&this.rightPoints[c][1]===t[1];++c)if(this.rightPoints[c]===t)return this.rightPoints.splice(c,1),a}return i},s.queryPoint=function(t,e){if(t<this.mid){if(this.left)if(r=this.left.queryPoint(t,e))return r;return f(this.leftPoints,t,e)}if(t>this.mid){var r;if(this.right)if(r=this.right.queryPoint(t,e))return r;return p(this.rightPoints,t,e)}return d(this.leftPoints,e)},s.queryInterval=function(t,e,r){var n;if(t<this.mid&&this.left&&(n=this.left.queryInterval(t,e,r)))return n;if(e>this.mid&&this.right&&(n=this.right.queryInterval(t,e,r)))return n;return e<this.mid?f(this.leftPoints,e,r):t>this.mid?p(this.rightPoints,t,r):d(this.leftPoints,r)};var b=x.prototype;b.insert=function(t){this.root?this.root.insert(t):this.root=new o(t[0],null,null,[t],[t])},b.remove=function(t){if(this.root){var e=this.root.remove(t);return 2===e&&(this.root=null),e!==i}return!1},b.queryPoint=function(t,e){if(this.root)return this.root.queryPoint(t,e)},b.queryInterval=function(t,e,r){if(t<=e&&this.root)return this.root.queryInterval(t,e,r)},Object.defineProperty(b,"count",{get:function(){return this.root?this.root.count:0}}),Object.defineProperty(b,"intervals",{get:function(){return this.root?this.root.intervals([]):[]}})},{"binary-search-bounds":79}],404:[function(t,e,r){"use strict";e.exports=function(t,e){e=e||new Array(t.length);for(var r=0;r<t.length;++r)e[t[r]]=r;return e}},{}],405:[function(t,e,r){"use strict";e.exports=function(t){for(var e=new Array(t),r=0;r<t;++r)e[r]=r;return e}},{}],406:[function(t,e,r){e.exports=!0},{}],407:[function(t,e,r){function n(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}e.exports=function(t){return null!=t&&(n(t)||function(t){return"function"==typeof t.readFloatLE&&"function"==typeof t.slice&&n(t.slice(0,0))}(t)||!!t._isBuffer)}},{}],408:[function(t,e,r){"use strict";e.exports="undefined"!=typeof navigator&&(/MSIE/.test(navigator.userAgent)||/Trident\//.test(navigator.appVersion))},{}],409:[function(t,e,r){"use strict";e.exports=a,e.exports.isMobile=a;var n=/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i,i=/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino|android|ipad|playbook|silk/i;function a(t){t||(t={});var e=t.ua;return e||"undefined"==typeof navigator||(e=navigator.userAgent),e&&e.headers&&"string"==typeof e.headers["user-agent"]&&(e=e.headers["user-agent"]),"string"==typeof e&&(t.tablet?i.test(e):n.test(e))}},{}],410:[function(t,e,r){"use strict";e.exports=function(t){var e=typeof t;return null!==t&&("object"===e||"function"===e)}},{}],411:[function(t,e,r){"use strict";var n=Object.prototype.toString;e.exports=function(t){var e;return"[object Object]"===n.call(t)&&(null===(e=Object.getPrototypeOf(t))||e===Object.getPrototypeOf({}))}},{}],412:[function(t,e,r){"use strict";e.exports=function(t){for(var e,r=t.length,n=0;n<r;n++)if(((e=t.charCodeAt(n))<9||e>13)&&32!==e&&133!==e&&160!==e&&5760!==e&&6158!==e&&(e<8192||e>8205)&&8232!==e&&8233!==e&&8239!==e&&8287!==e&&8288!==e&&12288!==e&&65279!==e)return!1;return!0}},{}],413:[function(t,e,r){"use strict";e.exports=function(t){return"string"==typeof t&&(t=t.trim(),!!(/^[mzlhvcsqta]\s*[-+.0-9][^mlhvzcsqta]+/i.test(t)&&/[\dz]$/i.test(t)&&t.length>4))}},{}],414:[function(t,e,r){e.exports=function(t,e,r){return t*(1-r)+e*r}},{}],415:[function(t,e,r){(function(t){!function(t,n){"object"==typeof r&&"undefined"!=typeof e?e.exports=n():t.mapboxgl=n()}(this,function(){"use strict";var e,r,n;function i(t,i){if(e)if(r){var a="var sharedChunk = {}; ("+e+")(sharedChunk); ("+r+")(sharedChunk);",o={};e(o),(n=i(o)).workerUrl=window.URL.createObjectURL(new Blob([a],{type:"text/javascript"}))}else r=i;else e=i}return i(0,function(e){var r="undefined"!=typeof window?window:"undefined"!=typeof t?t:"undefined"!=typeof self?self:{};function n(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function i(t,e){return t(e={exports:{}},e.exports),e.exports}var a=o;function o(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=n,this.p2x=r,this.p2y=n}o.prototype.sampleCurveX=function(t){return((this.ax*t+this.bx)*t+this.cx)*t},o.prototype.sampleCurveY=function(t){return((this.ay*t+this.by)*t+this.cy)*t},o.prototype.sampleCurveDerivativeX=function(t){return(3*this.ax*t+2*this.bx)*t+this.cx},o.prototype.solveCurveX=function(t,e){var r,n,i,a,o;for(void 0===e&&(e=1e-6),i=t,o=0;o<8;o++){if(a=this.sampleCurveX(i)-t,Math.abs(a)<e)return i;var s=this.sampleCurveDerivativeX(i);if(Math.abs(s)<1e-6)break;i-=a/s}if((i=t)<(r=0))return r;if(i>(n=1))return n;for(;r<n;){if(a=this.sampleCurveX(i),Math.abs(a-t)<e)return i;t>a?r=i:n=i,i=.5*(n-r)+r}return i},o.prototype.solve=function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))};var s=function(t,e,r){this.column=t,this.row=e,this.zoom=r};s.prototype.clone=function(){return new s(this.column,this.row,this.zoom)},s.prototype.zoomTo=function(t){return this.clone()._zoomTo(t)},s.prototype.sub=function(t){return this.clone()._sub(t)},s.prototype._zoomTo=function(t){var e=Math.pow(2,t-this.zoom);return this.column*=e,this.row*=e,this.zoom=t,this},s.prototype._sub=function(t){return t=t.zoomTo(this.zoom),this.column-=t.column,this.row-=t.row,this};var l=c;function c(t,e){this.x=t,this.y=e}function u(t,e,r,n){var i=new a(t,e,r,n);return function(t){return i.solve(t)}}c.prototype={clone:function(){return new c(this.x,this.y)},add:function(t){return this.clone()._add(t)},sub:function(t){return this.clone()._sub(t)},multByPoint:function(t){return this.clone()._multByPoint(t)},divByPoint:function(t){return this.clone()._divByPoint(t)},mult:function(t){return this.clone()._mult(t)},div:function(t){return this.clone()._div(t)},rotate:function(t){return this.clone()._rotate(t)},rotateAround:function(t,e){return this.clone()._rotateAround(t,e)},matMult:function(t){return this.clone()._matMult(t)},unit:function(){return this.clone()._unit()},perp:function(){return this.clone()._perp()},round:function(){return this.clone()._round()},mag:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals:function(t){return this.x===t.x&&this.y===t.y},dist:function(t){return Math.sqrt(this.distSqr(t))},distSqr:function(t){var e=t.x-this.x,r=t.y-this.y;return e*e+r*r},angle:function(){return Math.atan2(this.y,this.x)},angleTo:function(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith:function(t){return this.angleWithSep(t.x,t.y)},angleWithSep:function(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult:function(t){var e=t[0]*this.x+t[1]*this.y,r=t[2]*this.x+t[3]*this.y;return this.x=e,this.y=r,this},_add:function(t){return this.x+=t.x,this.y+=t.y,this},_sub:function(t){return this.x-=t.x,this.y-=t.y,this},_mult:function(t){return this.x*=t,this.y*=t,this},_div:function(t){return this.x/=t,this.y/=t,this},_multByPoint:function(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint:function(t){return this.x/=t.x,this.y/=t.y,this},_unit:function(){return this._div(this.mag()),this},_perp:function(){var t=this.y;return this.y=this.x,this.x=-t,this},_rotate:function(t){var e=Math.cos(t),r=Math.sin(t),n=e*this.x-r*this.y,i=r*this.x+e*this.y;return this.x=n,this.y=i,this},_rotateAround:function(t,e){var r=Math.cos(t),n=Math.sin(t),i=e.x+r*(this.x-e.x)-n*(this.y-e.y),a=e.y+n*(this.x-e.x)+r*(this.y-e.y);return this.x=i,this.y=a,this},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}},c.convert=function(t){return t instanceof c?t:Array.isArray(t)?new c(t[0],t[1]):t};var h=u(.25,.1,.25,1);function f(t,e,r){return Math.min(r,Math.max(e,t))}function p(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];for(var n=0,i=e;n<i.length;n+=1){var a=i[n];for(var o in a)t[o]=a[o]}return t}var d=1;function g(t,e){t.forEach(function(t){e[t]&&(e[t]=e[t].bind(e))})}function v(t,e){return-1!==t.indexOf(e,t.length-e.length)}function m(t,e,r){var n={};for(var i in t)n[i]=e.call(r||this,t[i],i,t);return n}function y(t,e,r){var n={};for(var i in t)e.call(r||this,t[i],i,t)&&(n[i]=t[i]);return n}function x(t){return Array.isArray(t)?t.map(x):"object"==typeof t&&t?m(t,x):t}var b={};function _(t){b[t]||("undefined"!=typeof console&&console.warn(t),b[t]=!0)}function w(t,e,r){return(r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)}function k(t){for(var e=0,r=0,n=t.length,i=n-1,a=void 0,o=void 0;r<n;i=r++)a=t[r],e+=((o=t[i]).x-a.x)*(a.y+o.y);return e}var A={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Image:"Image"};"function"==typeof Object.freeze&&Object.freeze(A);var M=function(t){function e(e,r,n){t.call(this,e),this.status=r,this.url=n,this.name=this.constructor.name,this.message=e}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.toString=function(){return this.name+": "+this.message+" ("+this.status+"): "+this.url},e}(Error);function T(t){var e=new self.XMLHttpRequest;for(var r in e.open("GET",t.url,!0),t.headers)e.setRequestHeader(r,t.headers[r]);return e.withCredentials="include"===t.credentials,e}var S=function(t,e){var r=T(t);return r.responseType="arraybuffer",r.onerror=function(){e(new Error(r.statusText))},r.onload=function(){var n=r.response;if(0===n.byteLength&&200===r.status)return e(new Error("http status 200 returned without content."));r.status>=200&&r.status<300&&r.response?e(null,{data:n,cacheControl:r.getResponseHeader("Cache-Control"),expires:r.getResponseHeader("Expires")}):e(new M(r.statusText,r.status,t.url))},r.send(),r};function E(t,e,r){r[t]=r[t]||[],r[t].push(e)}function C(t,e,r){if(r&&r[t]){var n=r[t].indexOf(e);-1!==n&&r[t].splice(n,1)}}var L=function(t,e){void 0===e&&(e={}),p(this,e),this.type=t},z=function(t){function e(e,r){void 0===r&&(r={}),t.call(this,"error",p({error:e},r))}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(L),O=function(){};O.prototype.on=function(t,e){return this._listeners=this._listeners||{},E(t,e,this._listeners),this},O.prototype.off=function(t,e){return C(t,e,this._listeners),C(t,e,this._oneTimeListeners),this},O.prototype.once=function(t,e){return this._oneTimeListeners=this._oneTimeListeners||{},E(t,e,this._oneTimeListeners),this},O.prototype.fire=function(t){"string"==typeof t&&(t=new L(t,arguments[1]||{}));var e=t.type;if(this.listens(e)){t.target=this;for(var r=0,n=this._listeners&&this._listeners[e]?this._listeners[e].slice():[];r<n.length;r+=1)n[r].call(this,t);for(var i=0,a=this._oneTimeListeners&&this._oneTimeListeners[e]?this._oneTimeListeners[e].slice():[];i<a.length;i+=1){var o=a[i];C(e,o,this._oneTimeListeners),o.call(this,t)}var s=this._eventedParent;s&&(p(t,"function"==typeof this._eventedParentData?this._eventedParentData():this._eventedParentData),s.fire(t))}else v(e,"error")?console.error(t&&t.error||t||"Empty error event"):v(e,"warning")&&console.warn(t&&t.warning||t||"Empty warning event");return this},O.prototype.listens=function(t){return this._listeners&&this._listeners[t]&&this._listeners[t].length>0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)},O.prototype.setEventedParent=function(t,e){return this._eventedParent=t,this._eventedParentData=e,this};var I={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},light:{type:"light"},sources:{required:!0,type:"sources"},sprite:{type:"string"},glyphs:{type:"string"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:!0,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.0511,180,85.0511]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},"*":{type:"*"}},source_raster:{type:{required:!0,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.0511,180,85.0511]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},"*":{type:"*"}},source_raster_dem:{type:{required:!0,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.0511,180,85.0511]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{}},default:"mapbox"},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:{geojson:{}}},data:{type:"*"},maxzoom:{type:"number",default:18},buffer:{type:"number",default:128,maximum:512,minimum:0},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},lineMetrics:{type:"boolean",default:!1}},source_video:{type:{required:!0,type:"enum",values:{video:{}}},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:{image:{}}},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},background:{}},required:!0},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},layout_fill:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},layout_circle:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},layout_line:{"line-cap":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{butt:{},round:{},square:{}},default:"butt"},"line-join":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:{bevel:{},round:{},miter:{}},default:"miter"},"line-miter-limit":{type:"number",default:2,function:"interpolated","zoom-function":!0,requires:[{"line-join":"miter"}]},"line-round-limit":{type:"number",default:1.05,function:"interpolated","zoom-function":!0,requires:[{"line-join":"round"}]},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},layout_symbol:{"symbol-placement":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{point:{},line:{}},default:"point"},"symbol-spacing":{type:"number",default:250,minimum:1,function:"interpolated","zoom-function":!0,units:"pixels",requires:[{"symbol-placement":"line"}]},"symbol-avoid-edges":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1},"icon-allow-overlap":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1,requires:["icon-image"]},"icon-ignore-placement":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1,requires:["icon-image"]},"icon-optional":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1,requires:["icon-image","text-field"]},"icon-rotation-alignment":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"]},"icon-size":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,units:"factor of the original icon size",requires:["icon-image"]},"icon-text-fit":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"]},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",function:"interpolated","zoom-function":!0,requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}]},"icon-image":{type:"string",function:"piecewise-constant","zoom-function":!0,"property-function":!0,tokens:!0},"icon-rotate":{type:"number",default:0,period:360,function:"interpolated","zoom-function":!0,"property-function":!0,units:"degrees",requires:["icon-image"]},"icon-padding":{type:"number",default:2,minimum:0,function:"interpolated","zoom-function":!0,units:"pixels",requires:["icon-image"]},"icon-keep-upright":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":"line"}]},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,"property-function":!0,requires:["icon-image"]},"icon-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"]},"icon-pitch-alignment":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"]},"text-pitch-alignment":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"]},"text-rotation-alignment":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"]},"text-field":{type:"string",function:"piecewise-constant","zoom-function":!0,"property-function":!0,default:"",tokens:!0},"text-font":{type:"array",value:"string",function:"piecewise-constant","zoom-function":!0,"property-function":!0,default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"]},"text-size":{type:"number",default:16,minimum:0,units:"pixels",function:"interpolated","zoom-function":!0,"property-function":!0,requires:["text-field"]},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",function:"interpolated","zoom-function":!0,"property-function":!0,requires:["text-field"]},"text-line-height":{type:"number",default:1.2,units:"ems",function:"interpolated","zoom-function":!0,requires:["text-field"]},"text-letter-spacing":{type:"number",default:0,units:"ems",function:"interpolated","zoom-function":!0,"property-function":!0,requires:["text-field"]},"text-justify":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:{left:{},center:{},right:{}},default:"center",requires:["text-field"]},"text-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field"]},"text-max-angle":{type:"number",default:45,units:"degrees",function:"interpolated","zoom-function":!0,requires:["text-field",{"symbol-placement":"line"}]},"text-rotate":{type:"number",default:0,period:360,units:"degrees",function:"interpolated","zoom-function":!0,"property-function":!0,requires:["text-field"]},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",function:"interpolated","zoom-function":!0,requires:["text-field"]},"text-keep-upright":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":"line"}]},"text-transform":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"]},"text-offset":{type:"array",value:"number",units:"ems",function:"interpolated","zoom-function":!0,"property-function":!0,length:2,default:[0,0],requires:["text-field"]},"text-allow-overlap":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1,requires:["text-field"]},"text-ignore-placement":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1,requires:["text-field"]},"text-optional":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!1,requires:["text-field","icon-image"]},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},filter:{type:"array",value:"*"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function_stop:{type:"array",minimum:0,maximum:22,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},expression_name:{type:"enum",values:{let:{group:"Variable binding"},var:{group:"Variable binding"},literal:{group:"Types"},array:{group:"Types"},at:{group:"Lookup"},case:{group:"Decision"},match:{group:"Decision"},coalesce:{group:"Decision"},step:{group:"Ramps, scales, curves"},interpolate:{group:"Ramps, scales, curves"},ln2:{group:"Math"},pi:{group:"Math"},e:{group:"Math"},typeof:{group:"Types"},string:{group:"Types"},number:{group:"Types"},boolean:{group:"Types"},object:{group:"Types"},collator:{group:"Types"},"to-string":{group:"Types"},"to-number":{group:"Types"},"to-boolean":{group:"Types"},"to-rgba":{group:"Color"},"to-color":{group:"Types"},rgb:{group:"Color"},rgba:{group:"Color"},get:{group:"Lookup"},has:{group:"Lookup"},length:{group:"Lookup"},properties:{group:"Feature data"},"geometry-type":{group:"Feature data"},id:{group:"Feature data"},zoom:{group:"Zoom"},"heatmap-density":{group:"Heatmap"},"line-progress":{group:"Heatmap"},"+":{group:"Math"},"*":{group:"Math"},"-":{group:"Math"},"/":{group:"Math"},"%":{group:"Math"},"^":{group:"Math"},sqrt:{group:"Math"},log10:{group:"Math"},ln:{group:"Math"},log2:{group:"Math"},sin:{group:"Math"},cos:{group:"Math"},tan:{group:"Math"},asin:{group:"Math"},acos:{group:"Math"},atan:{group:"Math"},min:{group:"Math"},max:{group:"Math"},round:{group:"Math"},abs:{group:"Math"},ceil:{group:"Math"},floor:{group:"Math"},"==":{group:"Decision"},"!=":{group:"Decision"},">":{group:"Decision"},"<":{group:"Decision"},">=":{group:"Decision"},"<=":{group:"Decision"},all:{group:"Decision"},any:{group:"Decision"},"!":{group:"Decision"},"is-supported-script":{group:"String"},upcase:{group:"String"},downcase:{group:"String"},concat:{group:"String"},"resolved-locale":{group:"String"}}},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},transition:!1,"zoom-function":!0,"property-function":!1,function:"piecewise-constant"},position:{type:"array",default:[1.15,210,30],length:3,value:"number",transition:!0,function:"interpolated","zoom-function":!0,"property-function":!1},color:{type:"color",default:"#ffffff",function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0},intensity:{type:"number",default:.5,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!0},"fill-opacity":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:1,minimum:0,maximum:1,transition:!0},"fill-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"fill-pattern"}]},"fill-outline-color":{type:"color",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}]},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"fill-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["fill-translate"]},"fill-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0}},paint_line:{"line-opacity":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:1,minimum:0,maximum:1,transition:!0},"line-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"line-pattern"}]},"line-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"line-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["line-translate"]},"line-width":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-gap-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-offset":{type:"number",default:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-dasharray":{type:"array",value:"number",function:"piecewise-constant","zoom-function":!0,minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}]},"line-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0},"line-gradient":{type:"color",function:"interpolated","zoom-function":!1,"property-function":!1,transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}]}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"circle-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-blur":{type:"number",default:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"circle-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["circle-translate"]},"circle-pitch-scale":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map"},"circle-pitch-alignment":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"viewport"},"circle-stroke-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"circle-stroke-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"heatmap-weight":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!1},"heatmap-intensity":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],function:"interpolated","zoom-function":!1,"property-function":!1,transition:!1},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-halo-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-halo-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"]},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-halo-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-halo-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"]}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-hue-rotate":{type:"number",default:0,period:360,function:"interpolated","zoom-function":!0,transition:!0,units:"degrees"},"raster-brightness-min":{type:"number",function:"interpolated","zoom-function":!0,default:0,minimum:0,maximum:1,transition:!0},"raster-brightness-max":{type:"number",function:"interpolated","zoom-function":!0,default:1,minimum:0,maximum:1,transition:!0},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-fade-duration":{type:"number",default:300,minimum:0,function:"interpolated","zoom-function":!0,transition:!1,units:"milliseconds"}},paint_hillshade:{"hillshade-illumination-direction":{type:"number",default:335,minimum:0,maximum:359,function:"interpolated","zoom-function":!0,transition:!1},"hillshade-illumination-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"viewport"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"hillshade-shadow-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,transition:!0},"hillshade-highlight-color":{type:"color",default:"#FFFFFF",function:"interpolated","zoom-function":!0,transition:!0},"hillshade-accent-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,transition:!0}},paint_background:{"background-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,transition:!0,requires:[{"!":"background-pattern"}]},"background-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,transition:!0}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible"}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!1,default:1,minimum:0,maximum:1,transition:!0},"fill-extrusion-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"fill-extrusion-pattern"}]},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"fill-extrusion-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"]},"fill-extrusion-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0},"fill-extrusion-height":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:0,minimum:0,units:"meters",transition:!0},"fill-extrusion-base":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"]}}},D=function(t,e,r,n){this.message=(t?t+": ":"")+r,n&&(this.identifier=n),null!=e&&e.__line__&&(this.line=e.__line__)};function P(t){var e=t.key,r=t.value;return r?[new D(e,r,"constants have been deprecated as of v8")]:[]}function R(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];for(var n=0,i=e;n<i.length;n+=1){var a=i[n];for(var o in a)t[o]=a[o]}return t}function F(t){return t instanceof Number||t instanceof String||t instanceof Boolean?t.valueOf():t}function B(t){return Array.isArray(t)?t.map(B):F(t)}var N=function(t){function e(e,r){t.call(this,r),this.message=r,this.key=e}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(Error),j=function(t,e){void 0===e&&(e=[]),this.parent=t,this.bindings={};for(var r=0,n=e;r<n.length;r+=1){var i=n[r],a=i[0],o=i[1];this.bindings[a]=o}};j.prototype.concat=function(t){return new j(this,t)},j.prototype.get=function(t){if(this.bindings[t])return this.bindings[t];if(this.parent)return this.parent.get(t);throw new Error(t+" not found in scope.")},j.prototype.has=function(t){return!!this.bindings[t]||!!this.parent&&this.parent.has(t)};var V={kind:"null"},U={kind:"number"},q={kind:"string"},H={kind:"boolean"},G={kind:"color"},Y={kind:"object"},W={kind:"value"},X={kind:"collator"};function Z(t,e){return{kind:"array",itemType:t,N:e}}function $(t){if("array"===t.kind){var e=$(t.itemType);return"number"==typeof t.N?"array<"+e+", "+t.N+">":"value"===t.itemType.kind?"array":"array<"+e+">"}return t.kind}var J=[V,U,q,H,G,Y,Z(W)];function K(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&!K(t.itemType,e.itemType)&&("number"!=typeof t.N||t.N===e.N))return null}else{if(t.kind===e.kind)return null;if("value"===t.kind)for(var r=0,n=J;r<n.length;r+=1)if(!K(n[r],e))return null}return"Expected "+$(t)+" but found "+$(e)+" instead."}var Q=i(function(t,e){var r={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],rebeccapurple:[102,51,153,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function n(t){return(t=Math.round(t))<0?0:t>255?255:t}function i(t){return t<0?0:t>1?1:t}function a(t){return"%"===t[t.length-1]?n(parseFloat(t)/100*255):n(parseInt(t))}function o(t){return"%"===t[t.length-1]?i(parseFloat(t)/100):i(parseFloat(t))}function s(t,e,r){return r<0?r+=1:r>1&&(r-=1),6*r<1?t+(e-t)*r*6:2*r<1?e:3*r<2?t+(e-t)*(2/3-r)*6:t}try{e.parseCSSColor=function(t){var e,i=t.replace(/ /g,"").toLowerCase();if(i in r)return r[i].slice();if("#"===i[0])return 4===i.length?(e=parseInt(i.substr(1),16))>=0&&e<=4095?[(3840&e)>>4|(3840&e)>>8,240&e|(240&e)>>4,15&e|(15&e)<<4,1]:null:7===i.length&&(e=parseInt(i.substr(1),16))>=0&&e<=16777215?[(16711680&e)>>16,(65280&e)>>8,255&e,1]:null;var l=i.indexOf("("),c=i.indexOf(")");if(-1!==l&&c+1===i.length){var u=i.substr(0,l),h=i.substr(l+1,c-(l+1)).split(","),f=1;switch(u){case"rgba":if(4!==h.length)return null;f=o(h.pop());case"rgb":return 3!==h.length?null:[a(h[0]),a(h[1]),a(h[2]),f];case"hsla":if(4!==h.length)return null;f=o(h.pop());case"hsl":if(3!==h.length)return null;var p=(parseFloat(h[0])%360+360)%360/360,d=o(h[1]),g=o(h[2]),v=g<=.5?g*(d+1):g+d-g*d,m=2*g-v;return[n(255*s(m,v,p+1/3)),n(255*s(m,v,p)),n(255*s(m,v,p-1/3)),f];default:return null}}return null}}catch(t){}}).parseCSSColor,tt=function(t,e,r,n){void 0===n&&(n=1),this.r=t,this.g=e,this.b=r,this.a=n};tt.parse=function(t){if(t){if(t instanceof tt)return t;if("string"==typeof t){var e=Q(t);if(e)return new tt(e[0]/255*e[3],e[1]/255*e[3],e[2]/255*e[3],e[3])}}},tt.prototype.toString=function(){var t=this.toArray(),e=t[0],r=t[1],n=t[2],i=t[3];return"rgba("+Math.round(e)+","+Math.round(r)+","+Math.round(n)+","+i+")"},tt.prototype.toArray=function(){var t=this.r,e=this.g,r=this.b,n=this.a;return 0===n?[0,0,0,0]:[255*t/n,255*e/n,255*r/n,n]},tt.black=new tt(0,0,0,1),tt.white=new tt(1,1,1,1),tt.transparent=new tt(0,0,0,0);var et=function(t,e,r){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=r,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})};et.prototype.compare=function(t,e){return this.collator.compare(t,e)},et.prototype.resolvedLocale=function(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale};var rt=function(t,e,r){this.type=X,this.locale=r,this.caseSensitive=t,this.diacriticSensitive=e};function nt(t,e,r,n){return"number"==typeof t&&t>=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:"Invalid rgba value ["+[t,e,r,n].join(", ")+"]: 'a' must be between 0 and 1.":"Invalid rgba value ["+("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")+"]: 'r', 'g', and 'b' must be between 0 and 255."}function it(t){if(null===t)return V;if("string"==typeof t)return q;if("boolean"==typeof t)return H;if("number"==typeof t)return U;if(t instanceof tt)return G;if(t instanceof et)return X;if(Array.isArray(t)){for(var e,r=t.length,n=0,i=t;n<i.length;n+=1){var a=it(i[n]);if(e){if(e===a)continue;e=W;break}e=a}return Z(e||W,r)}return Y}rt.parse=function(t,e){if(2!==t.length)return e.error("Expected one argument.");var r=t[1];if("object"!=typeof r||Array.isArray(r))return e.error("Collator options argument must be an object.");var n=e.parse(void 0!==r["case-sensitive"]&&r["case-sensitive"],1,H);if(!n)return null;var i=e.parse(void 0!==r["diacritic-sensitive"]&&r["diacritic-sensitive"],1,H);if(!i)return null;var a=null;return r.locale&&!(a=e.parse(r.locale,1,q))?null:new rt(n,i,a)},rt.prototype.evaluate=function(t){return new et(this.caseSensitive.evaluate(t),this.diacriticSensitive.evaluate(t),this.locale?this.locale.evaluate(t):null)},rt.prototype.eachChild=function(t){t(this.caseSensitive),t(this.diacriticSensitive),this.locale&&t(this.locale)},rt.prototype.possibleOutputs=function(){return[void 0]},rt.prototype.serialize=function(){var t={};return t["case-sensitive"]=this.caseSensitive.serialize(),t["diacritic-sensitive"]=this.diacriticSensitive.serialize(),this.locale&&(t.locale=this.locale.serialize()),["collator",t]};var at=function(t,e){this.type=t,this.value=e};at.parse=function(t,e){if(2!==t.length)return e.error("'literal' expression requires exactly one argument, but found "+(t.length-1)+" instead.");if(!function t(e){if(null===e)return!0;if("string"==typeof e)return!0;if("boolean"==typeof e)return!0;if("number"==typeof e)return!0;if(e instanceof tt)return!0;if(e instanceof et)return!0;if(Array.isArray(e)){for(var r=0,n=e;r<n.length;r+=1)if(!t(n[r]))return!1;return!0}if("object"==typeof e){for(var i in e)if(!t(e[i]))return!1;return!0}return!1}(t[1]))return e.error("invalid value");var r=t[1],n=it(r),i=e.expectedType;return"array"!==n.kind||0!==n.N||!i||"array"!==i.kind||"number"==typeof i.N&&0!==i.N||(n=i),new at(n,r)},at.prototype.evaluate=function(){return this.value},at.prototype.eachChild=function(){},at.prototype.possibleOutputs=function(){return[this.value]},at.prototype.serialize=function(){return"array"===this.type.kind||"object"===this.type.kind?["literal",this.value]:this.value instanceof tt?["rgba"].concat(this.value.toArray()):this.value};var ot=function(t){this.name="ExpressionEvaluationError",this.message=t};ot.prototype.toJSON=function(){return this.message};var st={string:q,number:U,boolean:H,object:Y},lt=function(t,e){this.type=t,this.args=e};lt.parse=function(t,e){if(t.length<2)return e.error("Expected at least one argument.");for(var r=t[0],n=st[r],i=[],a=1;a<t.length;a++){var o=e.parse(t[a],a,W);if(!o)return null;i.push(o)}return new lt(n,i)},lt.prototype.evaluate=function(t){for(var e=0;e<this.args.length;e++){var r=this.args[e].evaluate(t);if(!K(this.type,it(r)))return r;if(e===this.args.length-1)throw new ot("Expected value to be of type "+$(this.type)+", but found "+$(it(r))+" instead.")}return null},lt.prototype.eachChild=function(t){this.args.forEach(t)},lt.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.args.map(function(t){return t.possibleOutputs()}));var t},lt.prototype.serialize=function(){return[this.type.kind].concat(this.args.map(function(t){return t.serialize()}))};var ct={string:q,number:U,boolean:H},ut=function(t,e){this.type=t,this.input=e};ut.parse=function(t,e){if(t.length<2||t.length>4)return e.error("Expected 1, 2, or 3 arguments, but found "+(t.length-1)+" instead.");var r,n;if(t.length>2){var i=t[1];if("string"!=typeof i||!(i in ct))return e.error('The item type argument of "array" must be one of string, number, boolean',1);r=ct[i]}else r=W;if(t.length>3){if("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2]))return e.error('The length argument to "array" must be a positive integer literal',2);n=t[2]}var a=Z(r,n),o=e.parse(t[t.length-1],t.length-1,W);return o?new ut(a,o):null},ut.prototype.evaluate=function(t){var e=this.input.evaluate(t);if(K(this.type,it(e)))throw new ot("Expected value to be of type "+$(this.type)+", but found "+$(it(e))+" instead.");return e},ut.prototype.eachChild=function(t){t(this.input)},ut.prototype.possibleOutputs=function(){return this.input.possibleOutputs()},ut.prototype.serialize=function(){var t=["array"],e=this.type.itemType;if("string"===e.kind||"number"===e.kind||"boolean"===e.kind){t.push(e.kind);var r=this.type.N;"number"==typeof r&&t.push(r)}return t.push(this.input.serialize()),t};var ht={"to-number":U,"to-color":G},ft=function(t,e){this.type=t,this.args=e};ft.parse=function(t,e){if(t.length<2)return e.error("Expected at least one argument.");for(var r=t[0],n=ht[r],i=[],a=1;a<t.length;a++){var o=e.parse(t[a],a,W);if(!o)return null;i.push(o)}return new ft(n,i)},ft.prototype.evaluate=function(t){if("color"===this.type.kind){for(var e,r,n=0,i=this.args;n<i.length;n+=1)if(r=null,"string"==typeof(e=i[n].evaluate(t))){var a=t.parseColor(e);if(a)return a}else if(Array.isArray(e)&&!(r=e.length<3||e.length>4?"Invalid rbga value "+JSON.stringify(e)+": expected an array containing either three or four numeric values.":nt(e[0],e[1],e[2],e[3])))return new tt(e[0]/255,e[1]/255,e[2]/255,e[3]);throw new ot(r||"Could not parse color from value '"+("string"==typeof e?e:JSON.stringify(e))+"'")}for(var o=null,s=0,l=this.args;s<l.length;s+=1)if(null!==(o=l[s].evaluate(t))){var c=Number(o);if(!isNaN(c))return c}throw new ot("Could not convert "+JSON.stringify(o)+" to number.")},ft.prototype.eachChild=function(t){this.args.forEach(t)},ft.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.args.map(function(t){return t.possibleOutputs()}));var t},ft.prototype.serialize=function(){var t=["to-"+this.type.kind];return this.eachChild(function(e){t.push(e.serialize())}),t};var pt=["Unknown","Point","LineString","Polygon"],dt=function(){this._parseColorCache={}};dt.prototype.id=function(){return this.feature&&"id"in this.feature?this.feature.id:null},dt.prototype.geometryType=function(){return this.feature?"number"==typeof this.feature.type?pt[this.feature.type]:this.feature.type:null},dt.prototype.properties=function(){return this.feature&&this.feature.properties||{}},dt.prototype.parseColor=function(t){var e=this._parseColorCache[t];return e||(e=this._parseColorCache[t]=tt.parse(t)),e};var gt=function(t,e,r,n){this.name=t,this.type=e,this._evaluate=r,this.args=n};function vt(t){if(t instanceof gt){if("get"===t.name&&1===t.args.length)return!1;if("has"===t.name&&1===t.args.length)return!1;if("properties"===t.name||"geometry-type"===t.name||"id"===t.name)return!1;if(/^filter-/.test(t.name))return!1}var e=!0;return t.eachChild(function(t){e&&!vt(t)&&(e=!1)}),e}function mt(t,e){if(t instanceof gt&&e.indexOf(t.name)>=0)return!1;var r=!0;return t.eachChild(function(t){r&&!mt(t,e)&&(r=!1)}),r}gt.prototype.evaluate=function(t){return this._evaluate(t,this.args)},gt.prototype.eachChild=function(t){this.args.forEach(t)},gt.prototype.possibleOutputs=function(){return[void 0]},gt.prototype.serialize=function(){return[this.name].concat(this.args.map(function(t){return t.serialize()}))},gt.parse=function(t,e){var r=t[0],n=gt.definitions[r];if(!n)return e.error('Unknown expression "'+r+'". If you wanted a literal array, use ["literal", [...]].',0);for(var i=Array.isArray(n)?n[0]:n.type,a=Array.isArray(n)?[[n[1],n[2]]]:n.overloads,o=a.filter(function(e){var r=e[0];return!Array.isArray(r)||r.length===t.length-1}),s=[],l=1;l<t.length;l++){var c=t[l],u=void 0;if(1===o.length){var h=o[0][0];u=Array.isArray(h)?h[l-1]:h.type}var f=e.parse(c,1+s.length,u);if(!f)return null;s.push(f)}for(var p=null,d=0,g=o;d<g.length;d+=1){var v=g[d],m=v[0],y=v[1];if(p=new xt(e.registry,e.path,null,e.scope),Array.isArray(m)&&m.length!==s.length)p.error("Expected "+m.length+" arguments, but found "+s.length+" instead.");else{for(var x=0;x<s.length;x++){var b=Array.isArray(m)?m[x]:m.type,_=s[x];p.concat(x+1).checkSubtype(b,_.type)}if(0===p.errors.length)return new gt(r,i,y,s)}}if(1===o.length)e.errors.push.apply(e.errors,p.errors);else{var w=(o.length?o:a).map(function(t){var e;return e=t[0],Array.isArray(e)?"("+e.map($).join(", ")+")":"("+$(e.type)+"...)"}).join(" | "),k=s.map(function(t){return $(t.type)}).join(", ");e.error("Expected arguments of type "+w+", but found ("+k+") instead.")}return null},gt.register=function(t,e){for(var r in gt.definitions=e,e)t[r]=gt};var yt=function(t,e){this.type=e.type,this.name=t,this.boundExpression=e};yt.parse=function(t,e){if(2!==t.length||"string"!=typeof t[1])return e.error("'var' expression requires exactly one string literal argument.");var r=t[1];return e.scope.has(r)?new yt(r,e.scope.get(r)):e.error('Unknown variable "'+r+'". Make sure "'+r+'" has been bound in an enclosing "let" expression before using it.',1)},yt.prototype.evaluate=function(t){return this.boundExpression.evaluate(t)},yt.prototype.eachChild=function(){},yt.prototype.possibleOutputs=function(){return[void 0]},yt.prototype.serialize=function(){return["var",this.name]};var xt=function(t,e,r,n,i){void 0===e&&(e=[]),void 0===n&&(n=new j),void 0===i&&(i=[]),this.registry=t,this.path=e,this.key=e.map(function(t){return"["+t+"]"}).join(""),this.scope=n,this.errors=i,this.expectedType=r};function bt(t,e){for(var r,n,i=0,a=t.length-1,o=0;i<=a;){if(r=t[o=Math.floor((i+a)/2)],n=t[o+1],e===r||e>r&&e<n)return o;if(r<e)i=o+1;else{if(!(r>e))throw new ot("Input is not a number.");a=o-1}}return Math.max(o-1,0)}xt.prototype.parse=function(t,e,r,n,i){return void 0===i&&(i={}),e?this.concat(e,r,n)._parse(t,i):this._parse(t,i)},xt.prototype._parse=function(t,e){if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');var r=t[0];if("string"!=typeof r)return this.error("Expression name must be a string, but found "+typeof r+' instead. If you wanted a literal array, use ["literal", [...]].',0),null;var n=this.registry[r];if(n){var i=n.parse(t,this);if(!i)return null;if(this.expectedType){var a=this.expectedType,o=i.type;if("string"!==a.kind&&"number"!==a.kind&&"boolean"!==a.kind&&"object"!==a.kind||"value"!==o.kind)if("array"===a.kind&&"value"===o.kind)e.omitTypeAnnotations||(i=new ut(a,i));else if("color"!==a.kind||"value"!==o.kind&&"string"!==o.kind){if(this.checkSubtype(this.expectedType,i.type))return null}else e.omitTypeAnnotations||(i=new ft(a,[i]));else e.omitTypeAnnotations||(i=new lt(a,[i]))}if(!(i instanceof at)&&function t(e){if(e instanceof yt)return t(e.boundExpression);if(e instanceof gt&&"error"===e.name)return!1;if(e instanceof rt)return!1;var r=e instanceof ft||e instanceof lt||e instanceof ut,n=!0;return e.eachChild(function(e){n=r?n&&t(e):n&&e instanceof at}),!!n&&(vt(e)&&mt(e,["zoom","heatmap-density","line-progress","is-supported-script"]))}(i)){var s=new dt;try{i=new at(i.type,i.evaluate(s))}catch(t){return this.error(t.message),null}}return i}return this.error('Unknown expression "'+r+'". If you wanted a literal array, use ["literal", [...]].',0)}return void 0===t?this.error("'undefined' value invalid. Use null instead."):"object"==typeof t?this.error('Bare objects invalid. Use ["literal", {...}] instead.'):this.error("Expected an array, but found "+typeof t+" instead.")},xt.prototype.concat=function(t,e,r){var n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new xt(this.registry,n,e||null,i,this.errors)},xt.prototype.error=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];var n=""+this.key+e.map(function(t){return"["+t+"]"}).join("");this.errors.push(new N(n,t))},xt.prototype.checkSubtype=function(t,e){var r=K(t,e);return r&&this.error(r),r};var _t=function(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(var n=0,i=r;n<i.length;n+=1){var a=i[n],o=a[0],s=a[1];this.labels.push(o),this.outputs.push(s)}};function wt(t,e,r){return t*(1-r)+e*r}_t.parse=function(t,e){var r=t[1],n=t.slice(2);if(t.length-1<4)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(!(r=e.parse(r,1,U)))return null;var i=[],a=null;e.expectedType&&"value"!==e.expectedType.kind&&(a=e.expectedType),n.unshift(-1/0);for(var o=0;o<n.length;o+=2){var s=n[o],l=n[o+1],c=o+1,u=o+2;if("number"!=typeof s)return e.error('Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values.',c);if(i.length&&i[i.length-1][0]>=s)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',c);var h=e.parse(l,u,a);if(!h)return null;a=a||h.type,i.push([s,h])}return new _t(a,r,i)},_t.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var i=e.length;return n>=e[i-1]?r[i-1].evaluate(t):r[bt(e,n)].evaluate(t)},_t.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;e<r.length;e+=1)t(r[e])},_t.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.outputs.map(function(t){return t.possibleOutputs()}));var t},_t.prototype.serialize=function(){for(var t=["step",this.input.serialize()],e=0;e<this.labels.length;e++)e>0&&t.push(this.labels[e]),t.push(this.outputs[e].serialize());return t};var kt=Object.freeze({number:wt,color:function(t,e,r){return new tt(wt(t.r,e.r,r),wt(t.g,e.g,r),wt(t.b,e.b,r),wt(t.a,e.a,r))},array:function(t,e,r){return t.map(function(t,n){return wt(t,e[n],r)})}}),At=function(t,e,r,n){this.type=t,this.interpolation=e,this.input=r,this.labels=[],this.outputs=[];for(var i=0,a=n;i<a.length;i+=1){var o=a[i],s=o[0],l=o[1];this.labels.push(s),this.outputs.push(l)}};function Mt(t,e,r,n){var i=n-r,a=t-r;return 0===i?0:1===e?a/i:(Math.pow(e,a)-1)/(Math.pow(e,i)-1)}At.interpolationFactor=function(t,e,r,n){var i=0;if("exponential"===t.name)i=Mt(e,t.base,r,n);else if("linear"===t.name)i=Mt(e,1,r,n);else if("cubic-bezier"===t.name){var o=t.controlPoints;i=new a(o[0],o[1],o[2],o[3]).solve(Mt(e,1,r,n))}return i},At.parse=function(t,e){var r=t[1],n=t[2],i=t.slice(3);if(!Array.isArray(r)||0===r.length)return e.error("Expected an interpolation type expression.",1);if("linear"===r[0])r={name:"linear"};else if("exponential"===r[0]){var a=r[1];if("number"!=typeof a)return e.error("Exponential interpolation requires a numeric base.",1,1);r={name:"exponential",base:a}}else{if("cubic-bezier"!==r[0])return e.error("Unknown interpolation type "+String(r[0]),1,0);var o=r.slice(1);if(4!==o.length||o.some(function(t){return"number"!=typeof t||t<0||t>1}))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);r={name:"cubic-bezier",controlPoints:o}}if(t.length-1<4)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(!(n=e.parse(n,2,U)))return null;var s=[],l=null;e.expectedType&&"value"!==e.expectedType.kind&&(l=e.expectedType);for(var c=0;c<i.length;c+=2){var u=i[c],h=i[c+1],f=c+3,p=c+4;if("number"!=typeof u)return e.error('Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.',f);if(s.length&&s[s.length-1][0]>=u)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',f);var d=e.parse(h,p,l);if(!d)return null;l=l||d.type,s.push([u,d])}return"number"===l.kind||"color"===l.kind||"array"===l.kind&&"number"===l.itemType.kind&&"number"==typeof l.N?new At(l,r,n,s):e.error("Type "+$(l)+" is not interpolatable.")},At.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);var a=bt(e,n),o=e[a],s=e[a+1],l=At.interpolationFactor(this.interpolation,n,o,s),c=r[a].evaluate(t),u=r[a+1].evaluate(t);return kt[this.type.kind.toLowerCase()](c,u,l)},At.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;e<r.length;e+=1)t(r[e])},At.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.outputs.map(function(t){return t.possibleOutputs()}));var t},At.prototype.serialize=function(){for(var t=["interpolate","linear"===this.interpolation.name?["linear"]:"exponential"===this.interpolation.name?1===this.interpolation.base?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier"].concat(this.interpolation.controlPoints),this.input.serialize()],e=0;e<this.labels.length;e++)t.push(this.labels[e],this.outputs[e].serialize());return t};var Tt=function(t,e){this.type=t,this.args=e};Tt.parse=function(t,e){if(t.length<2)return e.error("Expectected at least one argument.");var r=null,n=e.expectedType;n&&"value"!==n.kind&&(r=n);for(var i=[],a=0,o=t.slice(1);a<o.length;a+=1){var s=o[a],l=e.parse(s,1+i.length,r,void 0,{omitTypeAnnotations:!0});if(!l)return null;r=r||l.type,i.push(l)}var c=n&&i.some(function(t){return K(n,t.type)});return new Tt(c?W:r,i)},Tt.prototype.evaluate=function(t){for(var e=null,r=0,n=this.args;r<n.length&&null===(e=n[r].evaluate(t));r+=1);return e},Tt.prototype.eachChild=function(t){this.args.forEach(t)},Tt.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.args.map(function(t){return t.possibleOutputs()}));var t},Tt.prototype.serialize=function(){var t=["coalesce"];return this.eachChild(function(e){t.push(e.serialize())}),t};var St=function(t,e){this.type=e.type,this.bindings=[].concat(t),this.result=e};St.prototype.evaluate=function(t){return this.result.evaluate(t)},St.prototype.eachChild=function(t){for(var e=0,r=this.bindings;e<r.length;e+=1)t(r[e][1]);t(this.result)},St.parse=function(t,e){if(t.length<4)return e.error("Expected at least 3 arguments, but found "+(t.length-1)+" instead.");for(var r=[],n=1;n<t.length-1;n+=2){var i=t[n];if("string"!=typeof i)return e.error("Expected string, but found "+typeof i+" instead.",n);if(/[^a-zA-Z0-9_]/.test(i))return e.error("Variable names must contain only alphanumeric characters or '_'.",n);var a=e.parse(t[n+1],n+1);if(!a)return null;r.push([i,a])}var o=e.parse(t[t.length-1],t.length-1,void 0,r);return o?new St(r,o):null},St.prototype.possibleOutputs=function(){return this.result.possibleOutputs()},St.prototype.serialize=function(){for(var t=["let"],e=0,r=this.bindings;e<r.length;e+=1){var n=r[e],i=n[0],a=n[1];t.push(i,a.serialize())}return t.push(this.result.serialize()),t};var Et=function(t,e,r){this.type=t,this.index=e,this.input=r};Et.parse=function(t,e){if(3!==t.length)return e.error("Expected 2 arguments, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1,U),n=e.parse(t[2],2,Z(e.expectedType||W));if(!r||!n)return null;var i=n.type;return new Et(i.itemType,r,n)},Et.prototype.evaluate=function(t){var e=this.index.evaluate(t),r=this.input.evaluate(t);if(e<0)throw new ot("Array index out of bounds: "+e+" < 0.");if(e>=r.length)throw new ot("Array index out of bounds: "+e+" > "+(r.length-1)+".");if(e!==Math.floor(e))throw new ot("Array index must be an integer, but found "+e+" instead.");return r[e]},Et.prototype.eachChild=function(t){t(this.index),t(this.input)},Et.prototype.possibleOutputs=function(){return[void 0]},Et.prototype.serialize=function(){return["at",this.index.serialize(),this.input.serialize()]};var Ct=function(t,e,r,n,i,a){this.inputType=t,this.type=e,this.input=r,this.cases=n,this.outputs=i,this.otherwise=a};Ct.parse=function(t,e){if(t.length<5)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if(t.length%2!=1)return e.error("Expected an even number of arguments.");var r,n;e.expectedType&&"value"!==e.expectedType.kind&&(n=e.expectedType);for(var i={},a=[],o=2;o<t.length-1;o+=2){var s=t[o],l=t[o+1];Array.isArray(s)||(s=[s]);var c=e.concat(o);if(0===s.length)return c.error("Expected at least one branch label.");for(var u=0,h=s;u<h.length;u+=1){var f=h[u];if("number"!=typeof f&&"string"!=typeof f)return c.error("Branch labels must be numbers or strings.");if("number"==typeof f&&Math.abs(f)>Number.MAX_SAFE_INTEGER)return c.error("Branch labels must be integers no larger than "+Number.MAX_SAFE_INTEGER+".");if("number"==typeof f&&Math.floor(f)!==f)return c.error("Numeric branch labels must be integer values.");if(r){if(c.checkSubtype(r,it(f)))return null}else r=it(f);if(void 0!==i[String(f)])return c.error("Branch labels must be unique.");i[String(f)]=a.length}var p=e.parse(l,o,n);if(!p)return null;n=n||p.type,a.push(p)}var d=e.parse(t[1],1,r);if(!d)return null;var g=e.parse(t[t.length-1],t.length-1,n);return g?new Ct(r,n,d,i,a,g):null},Ct.prototype.evaluate=function(t){var e=this.input.evaluate(t);return(this.outputs[this.cases[e]]||this.otherwise).evaluate(t)},Ct.prototype.eachChild=function(t){t(this.input),this.outputs.forEach(t),t(this.otherwise)},Ct.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.outputs.map(function(t){return t.possibleOutputs()})).concat(this.otherwise.possibleOutputs());var t},Ct.prototype.serialize=function(){for(var t=this,e=["match",this.input.serialize()],r=[],n={},i=0,a=Object.keys(this.cases).sort();i<a.length;i+=1){var o=a[i],s=n[t.cases[o]];void 0===s?(n[t.cases[o]]=r.length,r.push([t.cases[o],[o]])):r[s][1].push(o)}for(var l=function(e){return"number"===t.input.type.kind?Number(e):e},c=0,u=r;c<u.length;c+=1){var h=u[c],f=h[0],p=h[1];1===p.length?e.push(l(p[0])):e.push(p.map(l)),e.push(t.outputs[f].serialize())}return e.push(this.otherwise.serialize()),e};var Lt=function(t,e,r){this.type=t,this.branches=e,this.otherwise=r};function zt(t){return"string"===t.kind||"number"===t.kind||"boolean"===t.kind||"null"===t.kind}function Ot(t,e){return function(){function r(t,e,r){this.type=H,this.lhs=t,this.rhs=e,this.collator=r}return r.parse=function(t,e){if(3!==t.length&&4!==t.length)return e.error("Expected two or three arguments.");var n=e.parse(t[1],1,W);if(!n)return null;var i=e.parse(t[2],2,W);if(!i)return null;if(!zt(n.type)&&!zt(i.type))return e.error("Expected at least one argument to be a string, number, boolean, or null, but found ("+$(n.type)+", "+$(i.type)+") instead.");if(n.type.kind!==i.type.kind&&"value"!==n.type.kind&&"value"!==i.type.kind)return e.error("Cannot compare "+$(n.type)+" and "+$(i.type)+".");var a=null;if(4===t.length){if("string"!==n.type.kind&&"string"!==i.type.kind)return e.error("Cannot use collator to compare non-string types.");if(!(a=e.parse(t[3],3,X)))return null}return new r(n,i,a)},r.prototype.evaluate=function(t){var r=this.collator?0===this.collator.evaluate(t).compare(this.lhs.evaluate(t),this.rhs.evaluate(t)):this.lhs.evaluate(t)===this.rhs.evaluate(t);return e?!r:r},r.prototype.eachChild=function(t){t(this.lhs),t(this.rhs),this.collator&&t(this.collator)},r.prototype.possibleOutputs=function(){return[!0,!1]},r.prototype.serialize=function(){var e=[t];return this.eachChild(function(t){e.push(t.serialize())}),e},r}()}Lt.parse=function(t,e){if(t.length<4)return e.error("Expected at least 3 arguments, but found only "+(t.length-1)+".");if(t.length%2!=0)return e.error("Expected an odd number of arguments.");var r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);for(var n=[],i=1;i<t.length-1;i+=2){var a=e.parse(t[i],i,H);if(!a)return null;var o=e.parse(t[i+1],i+1,r);if(!o)return null;n.push([a,o]),r=r||o.type}var s=e.parse(t[t.length-1],t.length-1,r);return s?new Lt(r,n,s):null},Lt.prototype.evaluate=function(t){for(var e=0,r=this.branches;e<r.length;e+=1){var n=r[e],i=n[0],a=n[1];if(i.evaluate(t))return a.evaluate(t)}return this.otherwise.evaluate(t)},Lt.prototype.eachChild=function(t){for(var e=0,r=this.branches;e<r.length;e+=1){var n=r[e],i=n[0],a=n[1];t(i),t(a)}t(this.otherwise)},Lt.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.branches.map(function(t){return t[0],t[1].possibleOutputs()})).concat(this.otherwise.possibleOutputs());var t},Lt.prototype.serialize=function(){var t=["case"];return this.eachChild(function(e){t.push(e.serialize())}),t};var It=Ot("==",!1),Dt=Ot("!=",!0),Pt=function(t){this.type=U,this.input=t};Pt.parse=function(t,e){if(2!==t.length)return e.error("Expected 1 argument, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1);return r?"array"!==r.type.kind&&"string"!==r.type.kind&&"value"!==r.type.kind?e.error("Expected argument of type string or array, but found "+$(r.type)+" instead."):new Pt(r):null},Pt.prototype.evaluate=function(t){var e=this.input.evaluate(t);if("string"==typeof e)return e.length;if(Array.isArray(e))return e.length;throw new ot("Expected value to be of type string or array, but found "+$(it(e))+" instead.")},Pt.prototype.eachChild=function(t){t(this.input)},Pt.prototype.possibleOutputs=function(){return[void 0]},Pt.prototype.serialize=function(){var t=["length"];return this.eachChild(function(e){t.push(e.serialize())}),t};var Rt={"==":It,"!=":Dt,array:ut,at:Et,boolean:lt,case:Lt,coalesce:Tt,collator:rt,interpolate:At,length:Pt,let:St,literal:at,match:Ct,number:lt,object:lt,step:_t,string:lt,"to-color":ft,"to-number":ft,var:yt};function Ft(t,e){var r=e[0],n=e[1],i=e[2],a=e[3];r=r.evaluate(t),n=n.evaluate(t),i=i.evaluate(t);var o=a?a.evaluate(t):1,s=nt(r,n,i,o);if(s)throw new ot(s);return new tt(r/255*o,n/255*o,i/255*o,o)}function Bt(t,e){return t in e}function Nt(t,e){var r=e[t];return void 0===r?null:r}function jt(t,e){var r=e[0],n=e[1];return r.evaluate(t)<n.evaluate(t)}function Vt(t,e){var r=e[0],n=e[1];return r.evaluate(t)>n.evaluate(t)}function Ut(t,e){var r=e[0],n=e[1];return r.evaluate(t)<=n.evaluate(t)}function qt(t,e){var r=e[0],n=e[1];return r.evaluate(t)>=n.evaluate(t)}function Ht(t){return{type:t}}function Gt(t){return{result:"success",value:t}}function Yt(t){return{result:"error",value:t}}gt.register(Rt,{error:[{kind:"error"},[q],function(t,e){var r=e[0];throw new ot(r.evaluate(t))}],typeof:[q,[W],function(t,e){return $(it(e[0].evaluate(t)))}],"to-string":[q,[W],function(t,e){var r=e[0],n=typeof(r=r.evaluate(t));return null===r?"":"string"===n||"number"===n||"boolean"===n?String(r):r instanceof tt?r.toString():JSON.stringify(r)}],"to-boolean":[H,[W],function(t,e){var r=e[0];return Boolean(r.evaluate(t))}],"to-rgba":[Z(U,4),[G],function(t,e){return e[0].evaluate(t).toArray()}],rgb:[G,[U,U,U],Ft],rgba:[G,[U,U,U,U],Ft],has:{type:H,overloads:[[[q],function(t,e){return Bt(e[0].evaluate(t),t.properties())}],[[q,Y],function(t,e){var r=e[0],n=e[1];return Bt(r.evaluate(t),n.evaluate(t))}]]},get:{type:W,overloads:[[[q],function(t,e){return Nt(e[0].evaluate(t),t.properties())}],[[q,Y],function(t,e){var r=e[0],n=e[1];return Nt(r.evaluate(t),n.evaluate(t))}]]},properties:[Y,[],function(t){return t.properties()}],"geometry-type":[q,[],function(t){return t.geometryType()}],id:[W,[],function(t){return t.id()}],zoom:[U,[],function(t){return t.globals.zoom}],"heatmap-density":[U,[],function(t){return t.globals.heatmapDensity||0}],"line-progress":[U,[],function(t){return t.globals.lineProgress||0}],"+":[U,Ht(U),function(t,e){for(var r=0,n=0,i=e;n<i.length;n+=1)r+=i[n].evaluate(t);return r}],"*":[U,Ht(U),function(t,e){for(var r=1,n=0,i=e;n<i.length;n+=1)r*=i[n].evaluate(t);return r}],"-":{type:U,overloads:[[[U,U],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)-n.evaluate(t)}],[[U],function(t,e){return-e[0].evaluate(t)}]]},"/":[U,[U,U],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)/n.evaluate(t)}],"%":[U,[U,U],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)%n.evaluate(t)}],ln2:[U,[],function(){return Math.LN2}],pi:[U,[],function(){return Math.PI}],e:[U,[],function(){return Math.E}],"^":[U,[U,U],function(t,e){var r=e[0],n=e[1];return Math.pow(r.evaluate(t),n.evaluate(t))}],sqrt:[U,[U],function(t,e){var r=e[0];return Math.sqrt(r.evaluate(t))}],log10:[U,[U],function(t,e){var r=e[0];return Math.log10(r.evaluate(t))}],ln:[U,[U],function(t,e){var r=e[0];return Math.log(r.evaluate(t))}],log2:[U,[U],function(t,e){var r=e[0];return Math.log2(r.evaluate(t))}],sin:[U,[U],function(t,e){var r=e[0];return Math.sin(r.evaluate(t))}],cos:[U,[U],function(t,e){var r=e[0];return Math.cos(r.evaluate(t))}],tan:[U,[U],function(t,e){var r=e[0];return Math.tan(r.evaluate(t))}],asin:[U,[U],function(t,e){var r=e[0];return Math.asin(r.evaluate(t))}],acos:[U,[U],function(t,e){var r=e[0];return Math.acos(r.evaluate(t))}],atan:[U,[U],function(t,e){var r=e[0];return Math.atan(r.evaluate(t))}],min:[U,Ht(U),function(t,e){return Math.min.apply(Math,e.map(function(e){return e.evaluate(t)}))}],max:[U,Ht(U),function(t,e){return Math.max.apply(Math,e.map(function(e){return e.evaluate(t)}))}],abs:[U,[U],function(t,e){var r=e[0];return Math.abs(r.evaluate(t))}],round:[U,[U],function(t,e){var r=e[0].evaluate(t);return r<0?-Math.round(-r):Math.round(r)}],floor:[U,[U],function(t,e){var r=e[0];return Math.floor(r.evaluate(t))}],ceil:[U,[U],function(t,e){var r=e[0];return Math.ceil(r.evaluate(t))}],"filter-==":[H,[q,W],function(t,e){var r=e[0],n=e[1];return t.properties()[r.value]===n.value}],"filter-id-==":[H,[W],function(t,e){var r=e[0];return t.id()===r.value}],"filter-type-==":[H,[q],function(t,e){var r=e[0];return t.geometryType()===r.value}],"filter-<":[H,[q,W],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i<a}],"filter-id-<":[H,[W],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n<i}],"filter->":[H,[q,W],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i>a}],"filter-id->":[H,[W],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>i}],"filter-<=":[H,[q,W],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i<=a}],"filter-id-<=":[H,[W],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n<=i}],"filter->=":[H,[q,W],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i>=a}],"filter-id->=":[H,[W],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>=i}],"filter-has":[H,[W],function(t,e){return e[0].value in t.properties()}],"filter-has-id":[H,[],function(t){return null!==t.id()}],"filter-type-in":[H,[Z(q)],function(t,e){return e[0].value.indexOf(t.geometryType())>=0}],"filter-id-in":[H,[Z(W)],function(t,e){return e[0].value.indexOf(t.id())>=0}],"filter-in-small":[H,[q,Z(W)],function(t,e){var r=e[0];return e[1].value.indexOf(t.properties()[r.value])>=0}],"filter-in-large":[H,[q,Z(W)],function(t,e){var r=e[0],n=e[1];return function(t,e,r,n){for(;r<=n;){var i=r+n>>1;if(e[i]===t)return!0;e[i]>t?n=i-1:r=i+1}return!1}(t.properties()[r.value],n.value,0,n.value.length-1)}],">":{type:H,overloads:[[[U,U],Vt],[[q,q],Vt],[[q,q,X],function(t,e){var r=e[0],n=e[1];return e[2].evaluate(t).compare(r.evaluate(t),n.evaluate(t))>0}]]},"<":{type:H,overloads:[[[U,U],jt],[[q,q],jt],[[q,q,X],function(t,e){var r=e[0],n=e[1];return e[2].evaluate(t).compare(r.evaluate(t),n.evaluate(t))<0}]]},">=":{type:H,overloads:[[[U,U],qt],[[q,q],qt],[[q,q,X],function(t,e){var r=e[0],n=e[1];return e[2].evaluate(t).compare(r.evaluate(t),n.evaluate(t))>=0}]]},"<=":{type:H,overloads:[[[U,U],Ut],[[q,q],Ut],[[q,q,X],function(t,e){var r=e[0],n=e[1];return e[2].evaluate(t).compare(r.evaluate(t),n.evaluate(t))<=0}]]},all:{type:H,overloads:[[[H,H],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)&&n.evaluate(t)}],[Ht(H),function(t,e){for(var r=0,n=e;r<n.length;r+=1)if(!n[r].evaluate(t))return!1;return!0}]]},any:{type:H,overloads:[[[H,H],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)||n.evaluate(t)}],[Ht(H),function(t,e){for(var r=0,n=e;r<n.length;r+=1)if(n[r].evaluate(t))return!0;return!1}]]},"!":[H,[H],function(t,e){return!e[0].evaluate(t)}],"is-supported-script":[H,[q],function(t,e){var r=e[0],n=t.globals&&t.globals.isSupportedScript;return!n||n(r.evaluate(t))}],upcase:[q,[q],function(t,e){return e[0].evaluate(t).toUpperCase()}],downcase:[q,[q],function(t,e){return e[0].evaluate(t).toLowerCase()}],concat:[q,Ht(q),function(t,e){return e.map(function(e){return e.evaluate(t)}).join("")}],"resolved-locale":[q,[X],function(t,e){return e[0].evaluate(t).resolvedLocale()}]});var Wt=.95047,Xt=1,Zt=1.08883,$t=4/29,Jt=6/29,Kt=3*Jt*Jt,Qt=Jt*Jt*Jt,te=Math.PI/180,ee=180/Math.PI;function re(t){return t>Qt?Math.pow(t,1/3):t/Kt+$t}function ne(t){return t>Jt?t*t*t:Kt*(t-$t)}function ie(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function ae(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function oe(t){var e=ae(t.r),r=ae(t.g),n=ae(t.b),i=re((.4124564*e+.3575761*r+.1804375*n)/Wt),a=re((.2126729*e+.7151522*r+.072175*n)/Xt);return{l:116*a-16,a:500*(i-a),b:200*(a-re((.0193339*e+.119192*r+.9503041*n)/Zt)),alpha:t.a}}function se(t){var e=(t.l+16)/116,r=isNaN(t.a)?e:e+t.a/500,n=isNaN(t.b)?e:e-t.b/200;return e=Xt*ne(e),r=Wt*ne(r),n=Zt*ne(n),new tt(ie(3.2404542*r-1.5371385*e-.4985314*n),ie(-.969266*r+1.8760108*e+.041556*n),ie(.0556434*r-.2040259*e+1.0572252*n),t.alpha)}var le={forward:oe,reverse:se,interpolate:function(t,e,r){return{l:wt(t.l,e.l,r),a:wt(t.a,e.a,r),b:wt(t.b,e.b,r),alpha:wt(t.alpha,e.alpha,r)}}},ce={forward:function(t){var e=oe(t),r=e.l,n=e.a,i=e.b,a=Math.atan2(i,n)*ee;return{h:a<0?a+360:a,c:Math.sqrt(n*n+i*i),l:r,alpha:t.a}},reverse:function(t){var e=t.h*te,r=t.c;return se({l:t.l,a:Math.cos(e)*r,b:Math.sin(e)*r,alpha:t.alpha})},interpolate:function(t,e,r){return{h:function(t,e,r){var n=e-t;return t+r*(n>180||n<-180?n-360*Math.round(n/360):n)}(t.h,e.h,r),c:wt(t.c,e.c,r),l:wt(t.l,e.l,r),alpha:wt(t.alpha,e.alpha,r)}}},ue=Object.freeze({lab:le,hcl:ce});function he(t){return t instanceof Number?"number":t instanceof String?"string":t instanceof Boolean?"boolean":Array.isArray(t)?"array":null===t?"null":typeof t}function fe(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function pe(t){return t}function de(t,e,r){return void 0!==t?t:void 0!==e?e:void 0!==r?r:void 0}function ge(t,e,r,n,i){return de(typeof r===i?n[r]:void 0,t.default,e.default)}function ve(t,e,r){if("number"!==he(r))return de(t.default,e.default);var n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];var i=xe(t.stops,r);return t.stops[i][1]}function me(t,e,r){var n=void 0!==t.base?t.base:1;if("number"!==he(r))return de(t.default,e.default);var i=t.stops.length;if(1===i)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[i-1][0])return t.stops[i-1][1];var a=xe(t.stops,r),o=function(t,e,r,n){var i=n-r,a=t-r;return 0===i?0:1===e?a/i:(Math.pow(e,a)-1)/(Math.pow(e,i)-1)}(r,n,t.stops[a][0],t.stops[a+1][0]),s=t.stops[a][1],l=t.stops[a+1][1],c=kt[e.type]||pe;if(t.colorSpace&&"rgb"!==t.colorSpace){var u=ue[t.colorSpace];c=function(t,e){return u.reverse(u.interpolate(u.forward(t),u.forward(e),o))}}return"function"==typeof s.evaluate?{evaluate:function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];var r=s.evaluate.apply(void 0,t),n=l.evaluate.apply(void 0,t);if(void 0!==r&&void 0!==n)return c(r,n,o)}}:c(s,l,o)}function ye(t,e,r){return"color"===e.type?r=tt.parse(r):he(r)===e.type||"enum"===e.type&&e.values[r]||(r=void 0),de(r,t.default,e.default)}function xe(t,e){for(var r,n,i=0,a=t.length-1,o=0;i<=a;){if(r=t[o=Math.floor((i+a)/2)][0],n=t[o+1][0],e===r||e>r&&e<n)return o;r<e?i=o+1:r>e&&(a=o-1)}return Math.max(o-1,0)}var be=function(t,e){var r;this.expression=t,this._warningHistory={},this._defaultValue="color"===(r=e).type&&fe(r.default)?new tt(0,0,0,0):"color"===r.type?tt.parse(r.default)||null:void 0===r.default?null:r.default,"enum"===e.type&&(this._enumValues=e.values)};function _e(t){return Array.isArray(t)&&t.length>0&&"string"==typeof t[0]&&t[0]in Rt}function we(t,e){var r=new xt(Rt,[],function(t){var e={color:G,string:q,number:U,enum:q,boolean:H};return"array"===t.type?Z(e[t.value]||W,t.length):e[t.type]||null}(e)),n=r.parse(t);return n?Gt(new be(n,e)):Yt(r.errors)}be.prototype.evaluateWithoutErrorHandling=function(t,e){return this._evaluator||(this._evaluator=new dt),this._evaluator.globals=t,this._evaluator.feature=e,this.expression.evaluate(this._evaluator)},be.prototype.evaluate=function(t,e){this._evaluator||(this._evaluator=new dt),this._evaluator.globals=t,this._evaluator.feature=e;try{var r=this.expression.evaluate(this._evaluator);if(null==r)return this._defaultValue;if(this._enumValues&&!(r in this._enumValues))throw new ot("Expected value to be one of "+Object.keys(this._enumValues).map(function(t){return JSON.stringify(t)}).join(", ")+", but found "+JSON.stringify(r)+" instead.");return r}catch(t){return this._warningHistory[t.message]||(this._warningHistory[t.message]=!0,"undefined"!=typeof console&&console.warn(t.message)),this._defaultValue}};var ke=function(t,e){this.kind=t,this._styleExpression=e};ke.prototype.evaluateWithoutErrorHandling=function(t,e){return this._styleExpression.evaluateWithoutErrorHandling(t,e)},ke.prototype.evaluate=function(t,e){return this._styleExpression.evaluate(t,e)};var Ae=function(t,e,r){this.kind=t,this.zoomStops=r.labels,this._styleExpression=e,r instanceof At&&(this._interpolationType=r.interpolation)};function Me(t,e){if("error"===(t=we(t,e)).result)return t;var r=t.value.expression,n=vt(r);if(!n&&!e["property-function"])return Yt([new N("","property expressions not supported")]);var i=mt(r,["zoom"]);if(!i&&!1===e["zoom-function"])return Yt([new N("","zoom expressions not supported")]);var a=function t(e){var r=null;if(e instanceof St)r=t(e.result);else if(e instanceof Tt)for(var n=0,i=e.args;n<i.length;n+=1){var a=i[n];if(r=t(a))break}else(e instanceof _t||e instanceof At)&&e.input instanceof gt&&"zoom"===e.input.name&&(r=e);return r instanceof N?r:(e.eachChild(function(e){var n=t(e);n instanceof N?r=n:!r&&n?r=new N("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):r&&n&&r!==n&&(r=new N("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),r)}(r);return a||i?a instanceof N?Yt([a]):a instanceof At&&"piecewise-constant"===e.function?Yt([new N("",'"interpolate" expressions cannot be used with this property')]):Gt(a?new Ae(n?"camera":"composite",t.value,a):new ke(n?"constant":"source",t.value)):Yt([new N("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}Ae.prototype.evaluateWithoutErrorHandling=function(t,e){return this._styleExpression.evaluateWithoutErrorHandling(t,e)},Ae.prototype.evaluate=function(t,e){return this._styleExpression.evaluate(t,e)},Ae.prototype.interpolationFactor=function(t,e,r){return this._interpolationType?At.interpolationFactor(this._interpolationType,t,e,r):0};var Te=function(t,e){this._parameters=t,this._specification=e,R(this,function t(e,r){var n,i,a,o="color"===r.type,s=e.stops&&"object"==typeof e.stops[0][0],l=s||void 0!==e.property,c=s||!l,u=e.type||("interpolated"===r.function?"exponential":"interval");if(o&&((e=R({},e)).stops&&(e.stops=e.stops.map(function(t){return[t[0],tt.parse(t[1])]})),e.default?e.default=tt.parse(e.default):e.default=tt.parse(r.default)),e.colorSpace&&"rgb"!==e.colorSpace&&!ue[e.colorSpace])throw new Error("Unknown color space: "+e.colorSpace);if("exponential"===u)n=me;else if("interval"===u)n=ve;else if("categorical"===u){n=ge,i=Object.create(null);for(var h=0,f=e.stops;h<f.length;h+=1){var p=f[h];i[p[0]]=p[1]}a=typeof e.stops[0][0]}else{if("identity"!==u)throw new Error('Unknown function type "'+u+'"');n=ye}if(s){for(var d={},g=[],v=0;v<e.stops.length;v++){var m=e.stops[v],y=m[0].zoom;void 0===d[y]&&(d[y]={zoom:y,type:e.type,property:e.property,default:e.default,stops:[]},g.push(y)),d[y].stops.push([m[0].value,m[1]])}for(var x=[],b=0,_=g;b<_.length;b+=1){var w=_[b];x.push([d[w].zoom,t(d[w],r)])}return{kind:"composite",interpolationFactor:At.interpolationFactor.bind(void 0,{name:"linear"}),zoomStops:x.map(function(t){return t[0]}),evaluate:function(t,n){var i=t.zoom;return me({stops:x,base:e.base},r,i).evaluate(i,n)}}}return c?{kind:"camera",interpolationFactor:"exponential"===u?At.interpolationFactor.bind(void 0,{name:"exponential",base:void 0!==e.base?e.base:1}):function(){return 0},zoomStops:e.stops.map(function(t){return t[0]}),evaluate:function(t){var o=t.zoom;return n(e,r,o,i,a)}}:{kind:"source",evaluate:function(t,o){var s=o&&o.properties?o.properties[e.property]:void 0;return void 0===s?de(e.default,r.default):n(e,r,s,i,a)}}}(this._parameters,this._specification))};function Se(t,e){if(fe(t))return new Te(t,e);if(_e(t)){var r=Me(t,e);if("error"===r.result)throw new Error(r.value.map(function(t){return t.key+": "+t.message}).join(", "));return r.value}var n=t;return"string"==typeof t&&"color"===e.type&&(n=tt.parse(t)),{kind:"constant",evaluate:function(){return n}}}function Ee(t){var e=t.key,r=t.value,n=t.valueSpec||{},i=t.objectElementValidators||{},a=t.style,o=t.styleSpec,s=[],l=he(r);if("object"!==l)return[new D(e,r,"object expected, "+l+" found")];for(var c in r){var u=c.split(".")[0],h=n[u]||n["*"],f=void 0;if(i[u])f=i[u];else if(n[u])f=Ke;else if(i["*"])f=i["*"];else{if(!n["*"]){s.push(new D(e,r[c],'unknown property "'+c+'"'));continue}f=Ke}s=s.concat(f({key:(e?e+".":e)+c,value:r[c],valueSpec:h,style:a,styleSpec:o,object:r,objectKey:c},r))}for(var p in n)i[p]||n[p].required&&void 0===n[p].default&&void 0===r[p]&&s.push(new D(e,r,'missing required property "'+p+'"'));return s}function Ce(t){var e=t.value,r=t.valueSpec,n=t.style,i=t.styleSpec,a=t.key,o=t.arrayElementValidator||Ke;if("array"!==he(e))return[new D(a,e,"array expected, "+he(e)+" found")];if(r.length&&e.length!==r.length)return[new D(a,e,"array length "+r.length+" expected, length "+e.length+" found")];if(r["min-length"]&&e.length<r["min-length"])return[new D(a,e,"array length at least "+r["min-length"]+" expected, length "+e.length+" found")];var s={type:r.value};i.$version<7&&(s.function=r.function),"object"===he(r.value)&&(s=r.value);for(var l=[],c=0;c<e.length;c++)l=l.concat(o({array:e,arrayIndex:c,value:e[c],valueSpec:s,style:n,styleSpec:i,key:a+"["+c+"]"}));return l}function Le(t){var e=t.key,r=t.value,n=t.valueSpec,i=he(r);return"number"!==i?[new D(e,r,"number expected, "+i+" found")]:"minimum"in n&&r<n.minimum?[new D(e,r,r+" is less than the minimum value "+n.minimum)]:"maximum"in n&&r>n.maximum?[new D(e,r,r+" is greater than the maximum value "+n.maximum)]:[]}function ze(t){var e,r,n,i=t.valueSpec,a=F(t.value.type),o={},s="categorical"!==a&&void 0===t.value.property,l=!s,c="array"===he(t.value.stops)&&"array"===he(t.value.stops[0])&&"object"===he(t.value.stops[0][0]),u=Ee({key:t.key,value:t.value,valueSpec:t.styleSpec.function,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{stops:function(t){if("identity"===a)return[new D(t.key,t.value,'identity function may not have a "stops" property')];var e=[],r=t.value;return e=e.concat(Ce({key:t.key,value:r,valueSpec:t.valueSpec,style:t.style,styleSpec:t.styleSpec,arrayElementValidator:h})),"array"===he(r)&&0===r.length&&e.push(new D(t.key,r,"array must have at least one stop")),e},default:function(t){return Ke({key:t.key,value:t.value,valueSpec:i,style:t.style,styleSpec:t.styleSpec})}}});return"identity"===a&&s&&u.push(new D(t.key,t.value,'missing required property "property"')),"identity"===a||t.value.stops||u.push(new D(t.key,t.value,'missing required property "stops"')),"exponential"===a&&"piecewise-constant"===t.valueSpec.function&&u.push(new D(t.key,t.value,"exponential functions not supported")),t.styleSpec.$version>=8&&(l&&!t.valueSpec["property-function"]?u.push(new D(t.key,t.value,"property functions not supported")):s&&!t.valueSpec["zoom-function"]&&"heatmap-color"!==t.objectKey&&"line-gradient"!==t.objectKey&&u.push(new D(t.key,t.value,"zoom functions not supported"))),"categorical"!==a&&!c||void 0!==t.value.property||u.push(new D(t.key,t.value,'"property" property is required')),u;function h(t){var e=[],a=t.value,s=t.key;if("array"!==he(a))return[new D(s,a,"array expected, "+he(a)+" found")];if(2!==a.length)return[new D(s,a,"array length 2 expected, length "+a.length+" found")];if(c){if("object"!==he(a[0]))return[new D(s,a,"object expected, "+he(a[0])+" found")];if(void 0===a[0].zoom)return[new D(s,a,"object stop key must have zoom")];if(void 0===a[0].value)return[new D(s,a,"object stop key must have value")];if(n&&n>F(a[0].zoom))return[new D(s,a[0].zoom,"stop zoom values must appear in ascending order")];F(a[0].zoom)!==n&&(n=F(a[0].zoom),r=void 0,o={}),e=e.concat(Ee({key:s+"[0]",value:a[0],valueSpec:{zoom:{}},style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:Le,value:f}}))}else e=e.concat(f({key:s+"[0]",value:a[0],valueSpec:{},style:t.style,styleSpec:t.styleSpec},a));return e.concat(Ke({key:s+"[1]",value:a[1],valueSpec:i,style:t.style,styleSpec:t.styleSpec}))}function f(t,n){var s=he(t.value),l=F(t.value),c=null!==t.value?t.value:n;if(e){if(s!==e)return[new D(t.key,c,s+" stop domain type must match previous stop domain type "+e)]}else e=s;if("number"!==s&&"string"!==s&&"boolean"!==s)return[new D(t.key,c,"stop domain value must be a number, string, or boolean")];if("number"!==s&&"categorical"!==a){var u="number expected, "+s+" found";return i["property-function"]&&void 0===a&&(u+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new D(t.key,c,u)]}return"categorical"!==a||"number"!==s||isFinite(l)&&Math.floor(l)===l?"categorical"!==a&&"number"===s&&void 0!==r&&l<r?[new D(t.key,c,"stop domain values must appear in ascending order")]:(r=l,"categorical"===a&&l in o?[new D(t.key,c,"stop domain values must be unique")]:(o[l]=!0,[])):[new D(t.key,c,"integer expected, found "+l)]}}function Oe(t){var e=("property"===t.expressionContext?Me:we)(B(t.value),t.valueSpec);return"error"===e.result?e.value.map(function(e){return new D(""+t.key+e.key,t.value,e.message)}):"property"===t.expressionContext&&"text-font"===t.propertyKey&&-1!==e.value._styleExpression.expression.possibleOutputs().indexOf(void 0)?[new D(t.key,t.value,'Invalid data expression for "text-font". Output values must be contained as literals within the expression.')]:[]}function Ie(t){var e=t.key,r=t.value,n=t.valueSpec,i=[];return Array.isArray(n.values)?-1===n.values.indexOf(F(r))&&i.push(new D(e,r,"expected one of ["+n.values.join(", ")+"], "+JSON.stringify(r)+" found")):-1===Object.keys(n.values).indexOf(F(r))&&i.push(new D(e,r,"expected one of ["+Object.keys(n.values).join(", ")+"], "+JSON.stringify(r)+" found")),i}function De(t){if(!Array.isArray(t)||0===t.length)return!1;switch(t[0]){case"has":return t.length>=2&&"$id"!==t[1]&&"$type"!==t[1];case"in":case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return 3===t.length&&(Array.isArray(t[1])||Array.isArray(t[2]));case"any":case"all":for(var e=0,r=t.slice(1);e<r.length;e+=1){var n=r[e];if(!De(n)&&"boolean"!=typeof n)return!1}return!0;default:return!0}}Te.deserialize=function(t){return new Te(t._parameters,t._specification)},Te.serialize=function(t){return{_parameters:t._parameters,_specification:t._specification}};var Pe={type:"boolean",default:!1,function:!0,"property-function":!0,"zoom-function":!0};function Re(t){if(!t)return function(){return!0};De(t)||(t=Be(t));var e=we(t,Pe);if("error"===e.result)throw new Error(e.value.map(function(t){return t.key+": "+t.message}).join(", "));return function(t,r){return e.value.evaluate(t,r)}}function Fe(t,e){return t<e?-1:t>e?1:0}function Be(t){if(!t)return!0;var e,r=t[0];return t.length<=1?"any"!==r:"=="===r?Ne(t[1],t[2],"=="):"!="===r?Ue(Ne(t[1],t[2],"==")):"<"===r||">"===r||"<="===r||">="===r?Ne(t[1],t[2],r):"any"===r?(e=t.slice(1),["any"].concat(e.map(Be))):"all"===r?["all"].concat(t.slice(1).map(Be)):"none"===r?["all"].concat(t.slice(1).map(Be).map(Ue)):"in"===r?je(t[1],t.slice(2)):"!in"===r?Ue(je(t[1],t.slice(2))):"has"===r?Ve(t[1]):"!has"!==r||Ue(Ve(t[1]))}function Ne(t,e,r){switch(t){case"$type":return["filter-type-"+r,e];case"$id":return["filter-id-"+r,e];default:return["filter-"+r,t,e]}}function je(t,e){if(0===e.length)return!1;switch(t){case"$type":return["filter-type-in",["literal",e]];case"$id":return["filter-id-in",["literal",e]];default:return e.length>200&&!e.some(function(t){return typeof t!=typeof e[0]})?["filter-in-large",t,["literal",e.sort(Fe)]]:["filter-in-small",t,["literal",e]]}}function Ve(t){switch(t){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",t]}}function Ue(t){return["!",t]}function qe(t){return De(B(t.value))?Oe(R({},t,{expressionContext:"filter",valueSpec:{value:"boolean"}})):function t(e){var r=e.value,n=e.key;if("array"!==he(r))return[new D(n,r,"array expected, "+he(r)+" found")];var i,a=e.styleSpec,o=[];if(r.length<1)return[new D(n,r,"filter array must have at least 1 element")];switch(o=o.concat(Ie({key:n+"[0]",value:r[0],valueSpec:a.filter_operator,style:e.style,styleSpec:e.styleSpec})),F(r[0])){case"<":case"<=":case">":case">=":r.length>=2&&"$type"===F(r[1])&&o.push(new D(n,r,'"$type" cannot be use with operator "'+r[0]+'"'));case"==":case"!=":3!==r.length&&o.push(new D(n,r,'filter array for operator "'+r[0]+'" must have 3 elements'));case"in":case"!in":r.length>=2&&"string"!==(i=he(r[1]))&&o.push(new D(n+"[1]",r[1],"string expected, "+i+" found"));for(var s=2;s<r.length;s++)i=he(r[s]),"$type"===F(r[1])?o=o.concat(Ie({key:n+"["+s+"]",value:r[s],valueSpec:a.geometry_type,style:e.style,styleSpec:e.styleSpec})):"string"!==i&&"number"!==i&&"boolean"!==i&&o.push(new D(n+"["+s+"]",r[s],"string, number, or boolean expected, "+i+" found"));break;case"any":case"all":case"none":for(var l=1;l<r.length;l++)o=o.concat(t({key:n+"["+l+"]",value:r[l],style:e.style,styleSpec:e.styleSpec}));break;case"has":case"!has":i=he(r[1]),2!==r.length?o.push(new D(n,r,'filter array for "'+r[0]+'" operator must have 2 elements')):"string"!==i&&o.push(new D(n+"[1]",r[1],"string expected, "+i+" found"))}return o}(t)}function He(t,e){var r=t.key,n=t.style,i=t.styleSpec,a=t.value,o=t.objectKey,s=i[e+"_"+t.layerType];if(!s)return[];var l=o.match(/^(.*)-transition$/);if("paint"===e&&l&&s[l[1]]&&s[l[1]].transition)return Ke({key:r,value:a,valueSpec:i.transition,style:n,styleSpec:i});var c,u=t.valueSpec||s[o];if(!u)return[new D(r,a,'unknown property "'+o+'"')];if("string"===he(a)&&u["property-function"]&&!u.tokens&&(c=/^{([^}]+)}$/.exec(a)))return[new D(r,a,'"'+o+'" does not support interpolation syntax\nUse an identity property function instead: `{ "type": "identity", "property": '+JSON.stringify(c[1])+" }`.")];var h=[];return"symbol"===t.layerType&&("text-field"===o&&n&&!n.glyphs&&h.push(new D(r,a,'use of "text-field" requires a style "glyphs" property')),"text-font"===o&&fe(B(a))&&"identity"===F(a.type)&&h.push(new D(r,a,'"text-font" does not support identity functions'))),h.concat(Ke({key:t.key,value:a,valueSpec:u,style:n,styleSpec:i,expressionContext:"property",propertyKey:o}))}function Ge(t){return He(t,"paint")}function Ye(t){return He(t,"layout")}function We(t){var e=[],r=t.value,n=t.key,i=t.style,a=t.styleSpec;r.type||r.ref||e.push(new D(n,r,'either "type" or "ref" is required'));var o,s=F(r.type),l=F(r.ref);if(r.id)for(var c=F(r.id),u=0;u<t.arrayIndex;u++){var h=i.layers[u];F(h.id)===c&&e.push(new D(n,r.id,'duplicate layer id "'+r.id+'", previously used at line '+h.id.__line__))}if("ref"in r)["type","source","source-layer","filter","layout"].forEach(function(t){t in r&&e.push(new D(n,r[t],'"'+t+'" is prohibited for ref layers'))}),i.layers.forEach(function(t){F(t.id)===l&&(o=t)}),o?o.ref?e.push(new D(n,r.ref,"ref cannot reference another ref layer")):s=F(o.type):e.push(new D(n,r.ref,'ref layer "'+l+'" not found'));else if("background"!==s)if(r.source){var f=i.sources&&i.sources[r.source],p=f&&F(f.type);f?"vector"===p&&"raster"===s?e.push(new D(n,r.source,'layer "'+r.id+'" requires a raster source')):"raster"===p&&"raster"!==s?e.push(new D(n,r.source,'layer "'+r.id+'" requires a vector source')):"vector"!==p||r["source-layer"]?"raster-dem"===p&&"hillshade"!==s?e.push(new D(n,r.source,"raster-dem source can only be used with layer type 'hillshade'.")):"line"!==s||!r.paint||!r.paint["line-gradient"]||"geojson"===p&&f.lineMetrics||e.push(new D(n,r,'layer "'+r.id+'" specifies a line-gradient, which requires a GeoJSON source with `lineMetrics` enabled.')):e.push(new D(n,r,'layer "'+r.id+'" must specify a "source-layer"')):e.push(new D(n,r.source,'source "'+r.source+'" not found'))}else e.push(new D(n,r,'missing required property "source"'));return e=e.concat(Ee({key:n,value:r,valueSpec:a.layer,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{"*":function(){return[]},type:function(){return Ke({key:n+".type",value:r.type,valueSpec:a.layer.type,style:t.style,styleSpec:t.styleSpec,object:r,objectKey:"type"})},filter:qe,layout:function(t){return Ee({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{"*":function(t){return Ye(R({layerType:s},t))}}})},paint:function(t){return Ee({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{"*":function(t){return Ge(R({layerType:s},t))}}})}}}))}function Xe(t){var e=t.value,r=t.key,n=t.styleSpec,i=t.style;if(!e.type)return[new D(r,e,'"type" is required')];var a=F(e.type),o=[];switch(a){case"vector":case"raster":case"raster-dem":if(o=o.concat(Ee({key:r,value:e,valueSpec:n["source_"+a.replace("-","_")],style:t.style,styleSpec:n})),"url"in e)for(var s in e)["type","url","tileSize"].indexOf(s)<0&&o.push(new D(r+"."+s,e[s],'a source with a "url" property may not include a "'+s+'" property'));return o;case"geojson":return Ee({key:r,value:e,valueSpec:n.source_geojson,style:i,styleSpec:n});case"video":return Ee({key:r,value:e,valueSpec:n.source_video,style:i,styleSpec:n});case"image":return Ee({key:r,value:e,valueSpec:n.source_image,style:i,styleSpec:n});case"canvas":return o.push(new D(r,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")),o;default:return Ie({key:r+".type",value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]},style:i,styleSpec:n})}}function Ze(t){var e=t.value,r=t.styleSpec,n=r.light,i=t.style,a=[],o=he(e);if(void 0===e)return a;if("object"!==o)return a.concat([new D("light",e,"object expected, "+o+" found")]);for(var s in e){var l=s.match(/^(.*)-transition$/);a=l&&n[l[1]]&&n[l[1]].transition?a.concat(Ke({key:s,value:e[s],valueSpec:r.transition,style:i,styleSpec:r})):n[s]?a.concat(Ke({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r})):a.concat([new D(s,e[s],'unknown property "'+s+'"')])}return a}function $e(t){var e=t.value,r=t.key,n=he(e);return"string"!==n?[new D(r,e,"string expected, "+n+" found")]:[]}var Je={"*":function(){return[]},array:Ce,boolean:function(t){var e=t.value,r=t.key,n=he(e);return"boolean"!==n?[new D(r,e,"boolean expected, "+n+" found")]:[]},number:Le,color:function(t){var e=t.key,r=t.value,n=he(r);return"string"!==n?[new D(e,r,"color expected, "+n+" found")]:null===Q(r)?[new D(e,r,'color expected, "'+r+'" found')]:[]},constants:P,enum:Ie,filter:qe,function:ze,layer:We,object:Ee,source:Xe,light:Ze,string:$e};function Ke(t){var e=t.value,r=t.valueSpec,n=t.styleSpec;return r.function&&fe(F(e))?ze(t):r.function&&_e(B(e))?Oe(t):r.type&&Je[r.type]?Je[r.type](t):Ee(R({},t,{valueSpec:r.type?n[r.type]:r}))}function Qe(t){var e=t.value,r=t.key,n=$e(t);return n.length?n:(-1===e.indexOf("{fontstack}")&&n.push(new D(r,e,'"glyphs" url must include a "{fontstack}" token')),-1===e.indexOf("{range}")&&n.push(new D(r,e,'"glyphs" url must include a "{range}" token')),n)}function tr(t,e){e=e||I;var r=[];return r=r.concat(Ke({key:"",value:t,valueSpec:e.$root,styleSpec:e,style:t,objectElementValidators:{glyphs:Qe,"*":function(){return[]}}})),t.constants&&(r=r.concat(P({key:"constants",value:t.constants,style:t,styleSpec:e}))),er(r)}function er(t){return[].concat(t).sort(function(t,e){return t.line-e.line})}function rr(t){return function(){return er(t.apply(this,arguments))}}tr.source=rr(Xe),tr.light=rr(Ze),tr.layer=rr(We),tr.filter=rr(qe),tr.paintProperty=rr(Ge),tr.layoutProperty=rr(Ye);var nr=tr,ir=tr.light,ar=tr.paintProperty,or=tr.layoutProperty;function sr(t,e){var r=!1;if(e&&e.length)for(var n=0,i=e;n<i.length;n+=1){var a=i[n];t.fire(new z(new Error(a.message))),r=!0}return r}var lr=ur,cr=3;function ur(t,e,r){var n=this.cells=[];if(t instanceof ArrayBuffer){this.arrayBuffer=t;var i=new Int32Array(this.arrayBuffer);t=i[0],e=i[1],r=i[2],this.d=e+2*r;for(var a=0;a<this.d*this.d;a++){var o=i[cr+a],s=i[cr+a+1];n.push(o===s?null:i.subarray(o,s))}var l=i[cr+n.length],c=i[cr+n.length+1];this.keys=i.subarray(l,c),this.bboxes=i.subarray(c),this.insert=this._insertReadonly}else{this.d=e+2*r;for(var u=0;u<this.d*this.d;u++)n.push([]);this.keys=[],this.bboxes=[]}this.n=e,this.extent=t,this.padding=r,this.scale=e/t,this.uid=0;var h=r/e*t;this.min=-h,this.max=t+h}ur.prototype.insert=function(t,e,r,n,i){this._forEachCell(e,r,n,i,this._insertCell,this.uid++),this.keys.push(t),this.bboxes.push(e),this.bboxes.push(r),this.bboxes.push(n),this.bboxes.push(i)},ur.prototype._insertReadonly=function(){throw"Cannot insert into a GridIndex created from an ArrayBuffer."},ur.prototype._insertCell=function(t,e,r,n,i,a){this.cells[i].push(a)},ur.prototype.query=function(t,e,r,n){var i=this.min,a=this.max;if(t<=i&&e<=i&&a<=r&&a<=n)return Array.prototype.slice.call(this.keys);var o=[];return this._forEachCell(t,e,r,n,this._queryCell,o,{}),o},ur.prototype._queryCell=function(t,e,r,n,i,a,o){var s=this.cells[i];if(null!==s)for(var l=this.keys,c=this.bboxes,u=0;u<s.length;u++){var h=s[u];if(void 0===o[h]){var f=4*h;t<=c[f+2]&&e<=c[f+3]&&r>=c[f+0]&&n>=c[f+1]?(o[h]=!0,a.push(l[h])):o[h]=!1}}},ur.prototype._forEachCell=function(t,e,r,n,i,a,o){for(var s=this._convertToCellCoord(t),l=this._convertToCellCoord(e),c=this._convertToCellCoord(r),u=this._convertToCellCoord(n),h=s;h<=c;h++)for(var f=l;f<=u;f++){var p=this.d*f+h;if(i.call(this,t,e,r,n,p,a,o))return}},ur.prototype._convertToCellCoord=function(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))},ur.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var t=this.cells,e=cr+this.cells.length+1+1,r=0,n=0;n<this.cells.length;n++)r+=this.cells[n].length;var i=new Int32Array(e+r+this.keys.length+this.bboxes.length);i[0]=this.extent,i[1]=this.n,i[2]=this.padding;for(var a=e,o=0;o<t.length;o++){var s=t[o];i[cr+o]=a,i.set(s,a),a+=s.length}return i[cr+t.length]=a,i.set(this.keys,a),a+=this.keys.length,i[cr+t.length+1]=a,i.set(this.bboxes,a),a+=this.bboxes.length,i.buffer};var hr=self.ImageData,fr={};function pr(t,e,r){void 0===r&&(r={}),Object.defineProperty(e,"_classRegistryKey",{value:t,writeable:!1}),fr[t]={klass:e,omit:r.omit||[],shallow:r.shallow||[]}}for(var dr in pr("Object",Object),lr.serialize=function(t,e){var r=t.toArrayBuffer();return e&&e.push(r),r},lr.deserialize=function(t){return new lr(t)},pr("Grid",lr),pr("Color",tt),pr("Error",Error),pr("StylePropertyFunction",Te),pr("StyleExpression",be,{omit:["_evaluator"]}),pr("ZoomDependentExpression",Ae),pr("ZoomConstantExpression",ke),pr("CompoundExpression",gt,{omit:["_evaluate"]}),Rt)Rt[dr]._classRegistryKey||pr("Expression_"+dr,Rt[dr]);function gr(t,e){if(null==t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||t instanceof Boolean||t instanceof Number||t instanceof String||t instanceof Date||t instanceof RegExp)return t;if(t instanceof ArrayBuffer)return e&&e.push(t),t;if(ArrayBuffer.isView(t)){var r=t;return e&&e.push(r.buffer),r}if(t instanceof hr)return e&&e.push(t.data.buffer),t;if(Array.isArray(t)){for(var n=[],i=0,a=t;i<a.length;i+=1){var o=a[i];n.push(gr(o,e))}return n}if("object"==typeof t){var s=t.constructor,l=s._classRegistryKey;if(!l)throw new Error("can't serialize object of unregistered class");var c={};if(s.serialize)c._serialized=s.serialize(t,e);else{for(var u in t)if(t.hasOwnProperty(u)&&!(fr[l].omit.indexOf(u)>=0)){var h=t[u];c[u]=fr[l].shallow.indexOf(u)>=0?h:gr(h,e)}t instanceof Error&&(c.message=t.message)}return{name:l,properties:c}}throw new Error("can't serialize object of type "+typeof t)}function vr(t){if(null==t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||t instanceof Boolean||t instanceof Number||t instanceof String||t instanceof Date||t instanceof RegExp||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||t instanceof hr)return t;if(Array.isArray(t))return t.map(function(t){return vr(t)});if("object"==typeof t){var e=t,r=e.name,n=e.properties;if(!r)throw new Error("can't deserialize object of anonymous class");var i=fr[r].klass;if(!i)throw new Error("can't deserialize unregistered class "+r);if(i.deserialize)return i.deserialize(n._serialized);for(var a=Object.create(i.prototype),o=0,s=Object.keys(n);o<s.length;o+=1){var l=s[o];a[l]=fr[r].shallow.indexOf(l)>=0?n[l]:vr(n[l])}return a}throw new Error("can't deserialize object of type "+typeof t)}var mr=function(){this.first=!0};mr.prototype.update=function(t,e){var r=Math.floor(t);return this.first?(this.first=!1,this.lastIntegerZoom=r,this.lastIntegerZoomTime=0,this.lastZoom=t,this.lastFloorZoom=r,!0):(this.lastFloorZoom>r?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoom<r&&(this.lastIntegerZoom=r,this.lastIntegerZoomTime=e),t!==this.lastZoom&&(this.lastZoom=t,this.lastFloorZoom=r,!0))};var yr={"Latin-1 Supplement":function(t){return t>=128&&t<=255},Arabic:function(t){return t>=1536&&t<=1791},"Arabic Supplement":function(t){return t>=1872&&t<=1919},"Arabic Extended-A":function(t){return t>=2208&&t<=2303},"Hangul Jamo":function(t){return t>=4352&&t<=4607},"Unified Canadian Aboriginal Syllabics":function(t){return t>=5120&&t<=5759},Khmer:function(t){return t>=6016&&t<=6143},"Unified Canadian Aboriginal Syllabics Extended":function(t){return t>=6320&&t<=6399},"General Punctuation":function(t){return t>=8192&&t<=8303},"Letterlike Symbols":function(t){return t>=8448&&t<=8527},"Number Forms":function(t){return t>=8528&&t<=8591},"Miscellaneous Technical":function(t){return t>=8960&&t<=9215},"Control Pictures":function(t){return t>=9216&&t<=9279},"Optical Character Recognition":function(t){return t>=9280&&t<=9311},"Enclosed Alphanumerics":function(t){return t>=9312&&t<=9471},"Geometric Shapes":function(t){return t>=9632&&t<=9727},"Miscellaneous Symbols":function(t){return t>=9728&&t<=9983},"Miscellaneous Symbols and Arrows":function(t){return t>=11008&&t<=11263},"CJK Radicals Supplement":function(t){return t>=11904&&t<=12031},"Kangxi Radicals":function(t){return t>=12032&&t<=12255},"Ideographic Description Characters":function(t){return t>=12272&&t<=12287},"CJK Symbols and Punctuation":function(t){return t>=12288&&t<=12351},Hiragana:function(t){return t>=12352&&t<=12447},Katakana:function(t){return t>=12448&&t<=12543},Bopomofo:function(t){return t>=12544&&t<=12591},"Hangul Compatibility Jamo":function(t){return t>=12592&&t<=12687},Kanbun:function(t){return t>=12688&&t<=12703},"Bopomofo Extended":function(t){return t>=12704&&t<=12735},"CJK Strokes":function(t){return t>=12736&&t<=12783},"Katakana Phonetic Extensions":function(t){return t>=12784&&t<=12799},"Enclosed CJK Letters and Months":function(t){return t>=12800&&t<=13055},"CJK Compatibility":function(t){return t>=13056&&t<=13311},"CJK Unified Ideographs Extension A":function(t){return t>=13312&&t<=19903},"Yijing Hexagram Symbols":function(t){return t>=19904&&t<=19967},"CJK Unified Ideographs":function(t){return t>=19968&&t<=40959},"Yi Syllables":function(t){return t>=40960&&t<=42127},"Yi Radicals":function(t){return t>=42128&&t<=42191},"Hangul Jamo Extended-A":function(t){return t>=43360&&t<=43391},"Hangul Syllables":function(t){return t>=44032&&t<=55215},"Hangul Jamo Extended-B":function(t){return t>=55216&&t<=55295},"Private Use Area":function(t){return t>=57344&&t<=63743},"CJK Compatibility Ideographs":function(t){return t>=63744&&t<=64255},"Arabic Presentation Forms-A":function(t){return t>=64336&&t<=65023},"Vertical Forms":function(t){return t>=65040&&t<=65055},"CJK Compatibility Forms":function(t){return t>=65072&&t<=65103},"Small Form Variants":function(t){return t>=65104&&t<=65135},"Arabic Presentation Forms-B":function(t){return t>=65136&&t<=65279},"Halfwidth and Fullwidth Forms":function(t){return t>=65280&&t<=65519}};function xr(t){for(var e=0,r=t;e<r.length;e+=1)if(_r(r[e].charCodeAt(0)))return!0;return!1}function br(t){return!(yr.Arabic(t)||yr["Arabic Supplement"](t)||yr["Arabic Extended-A"](t)||yr["Arabic Presentation Forms-A"](t)||yr["Arabic Presentation Forms-B"](t))}function _r(t){return!!(746===t||747===t||!(t<4352)&&(yr["Bopomofo Extended"](t)||yr.Bopomofo(t)||yr["CJK Compatibility Forms"](t)&&!(t>=65097&&t<=65103)||yr["CJK Compatibility Ideographs"](t)||yr["CJK Compatibility"](t)||yr["CJK Radicals Supplement"](t)||yr["CJK Strokes"](t)||!(!yr["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||yr["CJK Unified Ideographs Extension A"](t)||yr["CJK Unified Ideographs"](t)||yr["Enclosed CJK Letters and Months"](t)||yr["Hangul Compatibility Jamo"](t)||yr["Hangul Jamo Extended-A"](t)||yr["Hangul Jamo Extended-B"](t)||yr["Hangul Jamo"](t)||yr["Hangul Syllables"](t)||yr.Hiragana(t)||yr["Ideographic Description Characters"](t)||yr.Kanbun(t)||yr["Kangxi Radicals"](t)||yr["Katakana Phonetic Extensions"](t)||yr.Katakana(t)&&12540!==t||!(!yr["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||!(!yr["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||yr["Unified Canadian Aboriginal Syllabics"](t)||yr["Unified Canadian Aboriginal Syllabics Extended"](t)||yr["Vertical Forms"](t)||yr["Yijing Hexagram Symbols"](t)||yr["Yi Syllables"](t)||yr["Yi Radicals"](t)))}function wr(t){return!(_r(t)||function(t){return!!(yr["Latin-1 Supplement"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||yr["General Punctuation"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||yr["Letterlike Symbols"](t)||yr["Number Forms"](t)||yr["Miscellaneous Technical"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||yr["Control Pictures"](t)&&9251!==t||yr["Optical Character Recognition"](t)||yr["Enclosed Alphanumerics"](t)||yr["Geometric Shapes"](t)||yr["Miscellaneous Symbols"](t)&&!(t>=9754&&t<=9759)||yr["Miscellaneous Symbols and Arrows"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||yr["CJK Symbols and Punctuation"](t)||yr.Katakana(t)||yr["Private Use Area"](t)||yr["CJK Compatibility Forms"](t)||yr["Small Form Variants"](t)||yr["Halfwidth and Fullwidth Forms"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)}(t))}function kr(t,e){return!(!e&&(t>=1424&&t<=2303||yr["Arabic Presentation Forms-A"](t)||yr["Arabic Presentation Forms-B"](t))||t>=2304&&t<=3583||t>=3840&&t<=4255||yr.Khmer(t))}var Ar,Mr=!1,Tr=null,Sr=!1,Er=new O,Cr={applyArabicShaping:null,processBidirectionalText:null,isLoaded:function(){return Sr||null!=Cr.applyArabicShaping}},Lr=function(t,e){this.zoom=t,e?(this.now=e.now,this.fadeDuration=e.fadeDuration,this.zoomHistory=e.zoomHistory,this.transition=e.transition):(this.now=0,this.fadeDuration=0,this.zoomHistory=new mr,this.transition={})};Lr.prototype.isSupportedScript=function(t){return function(t,e){for(var r=0,n=t;r<n.length;r+=1)if(!kr(n[r].charCodeAt(0),e))return!1;return!0}(t,Cr.isLoaded())},Lr.prototype.crossFadingFactor=function(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)};var zr=function(t,e){this.property=t,this.value=e,this.expression=Se(void 0===e?t.specification.default:e,t.specification)};zr.prototype.isDataDriven=function(){return"source"===this.expression.kind||"composite"===this.expression.kind},zr.prototype.possiblyEvaluate=function(t){return this.property.possiblyEvaluate(this,t)};var Or=function(t){this.property=t,this.value=new zr(t,void 0)};Or.prototype.transitioned=function(t,e){return new Dr(this.property,this.value,e,p({},t.transition,this.transition),t.now)},Or.prototype.untransitioned=function(){return new Dr(this.property,this.value,null,{},0)};var Ir=function(t){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues)};Ir.prototype.getValue=function(t){return x(this._values[t].value.value)},Ir.prototype.setValue=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new Or(this._values[t].property)),this._values[t].value=new zr(this._values[t].property,null===e?void 0:x(e))},Ir.prototype.getTransition=function(t){return x(this._values[t].transition)},Ir.prototype.setTransition=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new Or(this._values[t].property)),this._values[t].transition=x(e)||void 0},Ir.prototype.serialize=function(){for(var t={},e=0,r=Object.keys(this._values);e<r.length;e+=1){var n=r[e],i=this.getValue(n);void 0!==i&&(t[n]=i);var a=this.getTransition(n);void 0!==a&&(t[n+"-transition"]=a)}return t},Ir.prototype.transitioned=function(t,e){for(var r=new Pr(this._properties),n=0,i=Object.keys(this._values);n<i.length;n+=1){var a=i[n];r._values[a]=this._values[a].transitioned(t,e._values[a])}return r},Ir.prototype.untransitioned=function(){for(var t=new Pr(this._properties),e=0,r=Object.keys(this._values);e<r.length;e+=1){var n=r[e];t._values[n]=this._values[n].untransitioned()}return t};var Dr=function(t,e,r,n,i){this.property=t,this.value=e,this.begin=i+n.delay||0,this.end=this.begin+n.duration||0,t.specification.transition&&(n.delay||n.duration)&&(this.prior=r)};Dr.prototype.possiblyEvaluate=function(t){var e=t.now||0,r=this.value.possiblyEvaluate(t),n=this.prior;if(n){if(e>this.end)return this.prior=null,r;if(this.value.isDataDriven())return this.prior=null,r;if(e<this.begin)return n.possiblyEvaluate(t);var i=(e-this.begin)/(this.end-this.begin);return this.property.interpolate(n.possiblyEvaluate(t),r,function(t){if(i<=0)return 0;if(i>=1)return 1;var e=i*i,r=e*i;return 4*(i<.5?r:3*(i-e)+r-.75)}())}return r};var Pr=function(t){this._properties=t,this._values=Object.create(t.defaultTransitioningPropertyValues)};Pr.prototype.possiblyEvaluate=function(t){for(var e=new Br(this._properties),r=0,n=Object.keys(this._values);r<n.length;r+=1){var i=n[r];e._values[i]=this._values[i].possiblyEvaluate(t)}return e},Pr.prototype.hasTransition=function(){for(var t=0,e=Object.keys(this._values);t<e.length;t+=1){var r=e[t];if(this._values[r].prior)return!0}return!1};var Rr=function(t){this._properties=t,this._values=Object.create(t.defaultPropertyValues)};Rr.prototype.getValue=function(t){return x(this._values[t].value)},Rr.prototype.setValue=function(t,e){this._values[t]=new zr(this._values[t].property,null===e?void 0:x(e))},Rr.prototype.serialize=function(){for(var t={},e=0,r=Object.keys(this._values);e<r.length;e+=1){var n=r[e],i=this.getValue(n);void 0!==i&&(t[n]=i)}return t},Rr.prototype.possiblyEvaluate=function(t){for(var e=new Br(this._properties),r=0,n=Object.keys(this._values);r<n.length;r+=1){var i=n[r];e._values[i]=this._values[i].possiblyEvaluate(t)}return e};var Fr=function(t,e,r){this.property=t,this.value=e,this.globals=r};Fr.prototype.isConstant=function(){return"constant"===this.value.kind},Fr.prototype.constantOr=function(t){return"constant"===this.value.kind?this.value.value:t},Fr.prototype.evaluate=function(t){return this.property.evaluate(this.value,this.globals,t)};var Br=function(t){this._properties=t,this._values=Object.create(t.defaultPossiblyEvaluatedValues)};Br.prototype.get=function(t){return this._values[t]};var Nr=function(t){this.specification=t};Nr.prototype.possiblyEvaluate=function(t,e){return t.expression.evaluate(e)},Nr.prototype.interpolate=function(t,e,r){var n=kt[this.specification.type];return n?n(t,e,r):t};var jr=function(t){this.specification=t};jr.prototype.possiblyEvaluate=function(t,e){return"constant"===t.expression.kind||"camera"===t.expression.kind?new Fr(this,{kind:"constant",value:t.expression.evaluate(e)},e):new Fr(this,t.expression,e)},jr.prototype.interpolate=function(t,e,r){if("constant"!==t.value.kind||"constant"!==e.value.kind)return t;if(void 0===t.value.value||void 0===e.value.value)return new Fr(this,{kind:"constant",value:void 0},t.globals);var n=kt[this.specification.type];return n?new Fr(this,{kind:"constant",value:n(t.value.value,e.value.value,r)},t.globals):t},jr.prototype.evaluate=function(t,e,r){return"constant"===t.kind?t.value:t.evaluate(e,r)};var Vr=function(t){this.specification=t};Vr.prototype.possiblyEvaluate=function(t,e){if(void 0!==t.value){if("constant"===t.expression.kind){var r=t.expression.evaluate(e);return this._calculate(r,r,r,e)}return this._calculate(t.expression.evaluate(new Lr(Math.floor(e.zoom-1),e)),t.expression.evaluate(new Lr(Math.floor(e.zoom),e)),t.expression.evaluate(new Lr(Math.floor(e.zoom+1),e)),e)}},Vr.prototype._calculate=function(t,e,r,n){var i=n.zoom,a=i-Math.floor(i),o=n.crossFadingFactor();return i>n.zoomHistory.lastIntegerZoom?{from:t,to:e,fromScale:2,toScale:1,t:a+(1-a)*o}:{from:r,to:e,fromScale:.5,toScale:1,t:1-(1-o)*a}},Vr.prototype.interpolate=function(t){return t};var Ur=function(t){this.specification=t};Ur.prototype.possiblyEvaluate=function(t,e){return!!t.expression.evaluate(e)},Ur.prototype.interpolate=function(){return!1};var qr=function(t){for(var e in this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},t){var r=t[e],n=this.defaultPropertyValues[e]=new zr(r,void 0),i=this.defaultTransitionablePropertyValues[e]=new Or(r);this.defaultTransitioningPropertyValues[e]=i.untransitioned(),this.defaultPossiblyEvaluatedValues[e]=n.possiblyEvaluate({})}};pr("DataDrivenProperty",jr),pr("DataConstantProperty",Nr),pr("CrossFadedProperty",Vr),pr("ColorRampProperty",Ur);var Hr=function(t){function e(e,r){for(var n in t.call(this),this.id=e.id,this.metadata=e.metadata,this.type=e.type,this.minzoom=e.minzoom,this.maxzoom=e.maxzoom,this.visibility="visible","background"!==e.type&&(this.source=e.source,this.sourceLayer=e["source-layer"],this.filter=e.filter),this._featureFilter=function(){return!0},r.layout&&(this._unevaluatedLayout=new Rr(r.layout)),this._transitionablePaint=new Ir(r.paint),e.paint)this.setPaintProperty(n,e.paint[n],{validate:!1});for(var i in e.layout)this.setLayoutProperty(i,e.layout[i],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned()}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getLayoutProperty=function(t){return"visibility"===t?this.visibility:this._unevaluatedLayout.getValue(t)},e.prototype.setLayoutProperty=function(t,e,r){if(null!=e){var n="layers."+this.id+".layout."+t;if(this._validate(or,n,t,e,r))return}"visibility"!==t?this._unevaluatedLayout.setValue(t,e):this.visibility="none"===e?e:"visible"},e.prototype.getPaintProperty=function(t){return v(t,"-transition")?this._transitionablePaint.getTransition(t.slice(0,-"-transition".length)):this._transitionablePaint.getValue(t)},e.prototype.setPaintProperty=function(t,e,r){if(null!=e){var n="layers."+this.id+".paint."+t;if(this._validate(ar,n,t,e,r))return}v(t,"-transition")?this._transitionablePaint.setTransition(t.slice(0,-"-transition".length),e||void 0):this._transitionablePaint.setValue(t,e)},e.prototype.isHidden=function(t){return!!(this.minzoom&&t<this.minzoom)||!!(this.maxzoom&&t>=this.maxzoom)||"none"===this.visibility},e.prototype.updateTransitions=function(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint)},e.prototype.hasTransition=function(){return this._transitioningPaint.hasTransition()},e.prototype.recalculate=function(t){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t)),this.paint=this._transitioningPaint.possiblyEvaluate(t)},e.prototype.serialize=function(){var t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return"none"===this.visibility&&(t.layout=t.layout||{},t.layout.visibility="none"),y(t,function(t,e){return!(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)})},e.prototype._validate=function(t,e,r,n,i){return(!i||!1!==i.validate)&&sr(this,t.call(nr,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:I,style:{glyphs:!0,sprite:!0}}))},e.prototype.hasOffscreenPass=function(){return!1},e.prototype.resize=function(){},e}(O),Gr={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array},Yr=function(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8},Wr=function(){this.isTransferred=!1,this.capacity=-1,this.resize(0)};function Xr(t,e){void 0===e&&(e=1);var r=0,n=0;return{members:t.map(function(t){var i,a=(i=t.type,Gr[i].BYTES_PER_ELEMENT),o=r=Zr(r,Math.max(e,a)),s=t.components||1;return n=Math.max(n,a),r+=a*s,{name:t.name,type:t.type,components:s,offset:o}}),size:Zr(r,Math.max(n,e)),alignment:e}}function Zr(t,e){return Math.ceil(t/e)*e}Wr.serialize=function(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}},Wr.deserialize=function(t){var e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e},Wr.prototype._trim=function(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews())},Wr.prototype.clear=function(){this.length=0},Wr.prototype.resize=function(t){this.reserve(t),this.length=t},Wr.prototype.reserve=function(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);var e=this.uint8;this._refreshViews(),e&&this.uint8.set(e)}},Wr.prototype._refreshViews=function(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")};var $r=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)},e.prototype.emplaceBack=function(t,e){var r=this.length;this.resize(r+1);var n=2*r;return this.int16[n+0]=t,this.int16[n+1]=e,r},e}(Wr);$r.prototype.bytesPerElement=4,pr("StructArrayLayout2i4",$r);var Jr=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)},e.prototype.emplaceBack=function(t,e,r,n){var i=this.length;this.resize(i+1);var a=4*i;return this.int16[a+0]=t,this.int16[a+1]=e,this.int16[a+2]=r,this.int16[a+3]=n,i},e}(Wr);Jr.prototype.bytesPerElement=8,pr("StructArrayLayout4i8",Jr);var Kr=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)},e.prototype.emplaceBack=function(t,e,r,n,i,a){var o=this.length;this.resize(o+1);var s=6*o;return this.int16[s+0]=t,this.int16[s+1]=e,this.int16[s+2]=r,this.int16[s+3]=n,this.int16[s+4]=i,this.int16[s+5]=a,o},e}(Wr);Kr.prototype.bytesPerElement=12,pr("StructArrayLayout2i4i12",Kr);var Qr=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s){var l=this.length;this.resize(l+1);var c=6*l,u=12*l;return this.int16[c+0]=t,this.int16[c+1]=e,this.int16[c+2]=r,this.int16[c+3]=n,this.uint8[u+8]=i,this.uint8[u+9]=a,this.uint8[u+10]=o,this.uint8[u+11]=s,l},e}(Wr);Qr.prototype.bytesPerElement=12,pr("StructArrayLayout4i4ub12",Qr);var tn=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s){var l=this.length;this.resize(l+1);var c=8*l;return this.int16[c+0]=t,this.int16[c+1]=e,this.int16[c+2]=r,this.int16[c+3]=n,this.uint16[c+4]=i,this.uint16[c+5]=a,this.uint16[c+6]=o,this.uint16[c+7]=s,l},e}(Wr);tn.prototype.bytesPerElement=16,pr("StructArrayLayout4i4ui16",tn);var en=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)},e.prototype.emplaceBack=function(t,e,r){var n=this.length;this.resize(n+1);var i=3*n;return this.float32[i+0]=t,this.float32[i+1]=e,this.float32[i+2]=r,n},e}(Wr);en.prototype.bytesPerElement=12,pr("StructArrayLayout3f12",en);var rn=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)},e.prototype.emplaceBack=function(t){var e=this.length;this.resize(e+1);var r=1*e;return this.uint32[r+0]=t,e},e}(Wr);rn.prototype.bytesPerElement=4,pr("StructArrayLayout1ul4",rn);var nn=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,l,c,u){var h=this.length;this.resize(h+1);var f=12*h,p=6*h;return this.int16[f+0]=t,this.int16[f+1]=e,this.int16[f+2]=r,this.int16[f+3]=n,this.int16[f+4]=i,this.int16[f+5]=a,this.uint32[p+3]=o,this.uint16[f+8]=s,this.uint16[f+9]=l,this.int16[f+10]=c,this.int16[f+11]=u,h},e}(Wr);nn.prototype.bytesPerElement=24,pr("StructArrayLayout6i1ul2ui2i24",nn);var an=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)},e.prototype.emplaceBack=function(t,e,r,n,i,a){var o=this.length;this.resize(o+1);var s=6*o;return this.int16[s+0]=t,this.int16[s+1]=e,this.int16[s+2]=r,this.int16[s+3]=n,this.int16[s+4]=i,this.int16[s+5]=a,o},e}(Wr);an.prototype.bytesPerElement=12,pr("StructArrayLayout2i2i2i12",an);var on=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer)},e.prototype.emplaceBack=function(t,e){var r=this.length;this.resize(r+1);var n=4*r;return this.uint8[n+0]=t,this.uint8[n+1]=e,r},e}(Wr);on.prototype.bytesPerElement=4,pr("StructArrayLayout2ub4",on);var sn=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,l,c,u,h,f,p){var d=this.length;this.resize(d+1);var g=20*d,v=10*d,m=40*d;return this.int16[g+0]=t,this.int16[g+1]=e,this.uint16[g+2]=r,this.uint16[g+3]=n,this.uint32[v+2]=i,this.uint32[v+3]=a,this.uint32[v+4]=o,this.uint16[g+10]=s,this.uint16[g+11]=l,this.uint16[g+12]=c,this.float32[v+7]=u,this.float32[v+8]=h,this.uint8[m+36]=f,this.uint8[m+37]=p,d},e}(Wr);sn.prototype.bytesPerElement=40,pr("StructArrayLayout2i2ui3ul3ui2f2ub40",sn);var ln=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)},e.prototype.emplaceBack=function(t){var e=this.length;this.resize(e+1);var r=1*e;return this.float32[r+0]=t,e},e}(Wr);ln.prototype.bytesPerElement=4,pr("StructArrayLayout1f4",ln);var cn=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)},e.prototype.emplaceBack=function(t,e,r){var n=this.length;this.resize(n+1);var i=3*n;return this.int16[i+0]=t,this.int16[i+1]=e,this.int16[i+2]=r,n},e}(Wr);cn.prototype.bytesPerElement=6,pr("StructArrayLayout3i6",cn);var un=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)},e.prototype.emplaceBack=function(t,e,r){var n=this.length;this.resize(n+1);var i=2*n,a=4*n;return this.uint32[i+0]=t,this.uint16[a+2]=e,this.uint16[a+3]=r,n},e}(Wr);un.prototype.bytesPerElement=8,pr("StructArrayLayout1ul2ui8",un);var hn=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)},e.prototype.emplaceBack=function(t,e,r){var n=this.length;this.resize(n+1);var i=3*n;return this.uint16[i+0]=t,this.uint16[i+1]=e,this.uint16[i+2]=r,n},e}(Wr);hn.prototype.bytesPerElement=6,pr("StructArrayLayout3ui6",hn);var fn=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)},e.prototype.emplaceBack=function(t,e){var r=this.length;this.resize(r+1);var n=2*r;return this.uint16[n+0]=t,this.uint16[n+1]=e,r},e}(Wr);fn.prototype.bytesPerElement=4,pr("StructArrayLayout2ui4",fn);var pn=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)},e.prototype.emplaceBack=function(t,e){var r=this.length;this.resize(r+1);var n=2*r;return this.float32[n+0]=t,this.float32[n+1]=e,r},e}(Wr);pn.prototype.bytesPerElement=8,pr("StructArrayLayout2f8",pn);var dn=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)},e.prototype.emplaceBack=function(t,e,r,n){var i=this.length;this.resize(i+1);var a=4*i;return this.float32[a+0]=t,this.float32[a+1]=e,this.float32[a+2]=r,this.float32[a+3]=n,i},e}(Wr);dn.prototype.bytesPerElement=16,pr("StructArrayLayout4f16",dn);var gn=function(t){function e(){t.apply(this,arguments)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={anchorPointX:{configurable:!0},anchorPointY:{configurable:!0},x1:{configurable:!0},y1:{configurable:!0},x2:{configurable:!0},y2:{configurable:!0},featureIndex:{configurable:!0},sourceLayerIndex:{configurable:!0},bucketIndex:{configurable:!0},radius:{configurable:!0},signedDistanceFromAnchor:{configurable:!0},anchorPoint:{configurable:!0}};return r.anchorPointX.get=function(){return this._structArray.int16[this._pos2+0]},r.anchorPointX.set=function(t){this._structArray.int16[this._pos2+0]=t},r.anchorPointY.get=function(){return this._structArray.int16[this._pos2+1]},r.anchorPointY.set=function(t){this._structArray.int16[this._pos2+1]=t},r.x1.get=function(){return this._structArray.int16[this._pos2+2]},r.x1.set=function(t){this._structArray.int16[this._pos2+2]=t},r.y1.get=function(){return this._structArray.int16[this._pos2+3]},r.y1.set=function(t){this._structArray.int16[this._pos2+3]=t},r.x2.get=function(){return this._structArray.int16[this._pos2+4]},r.x2.set=function(t){this._structArray.int16[this._pos2+4]=t},r.y2.get=function(){return this._structArray.int16[this._pos2+5]},r.y2.set=function(t){this._structArray.int16[this._pos2+5]=t},r.featureIndex.get=function(){return this._structArray.uint32[this._pos4+3]},r.featureIndex.set=function(t){this._structArray.uint32[this._pos4+3]=t},r.sourceLayerIndex.get=function(){return this._structArray.uint16[this._pos2+8]},r.sourceLayerIndex.set=function(t){this._structArray.uint16[this._pos2+8]=t},r.bucketIndex.get=function(){return this._structArray.uint16[this._pos2+9]},r.bucketIndex.set=function(t){this._structArray.uint16[this._pos2+9]=t},r.radius.get=function(){return this._structArray.int16[this._pos2+10]},r.radius.set=function(t){this._structArray.int16[this._pos2+10]=t},r.signedDistanceFromAnchor.get=function(){return this._structArray.int16[this._pos2+11]},r.signedDistanceFromAnchor.set=function(t){this._structArray.int16[this._pos2+11]=t},r.anchorPoint.get=function(){return new l(this.anchorPointX,this.anchorPointY)},Object.defineProperties(e.prototype,r),e}(Yr);gn.prototype.size=24;var vn=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.get=function(t){return new gn(this,t)},e}(nn);pr("CollisionBoxArray",vn);var mn=function(t){function e(){t.apply(this,arguments)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={anchorX:{configurable:!0},anchorY:{configurable:!0},glyphStartIndex:{configurable:!0},numGlyphs:{configurable:!0},vertexStartIndex:{configurable:!0},lineStartIndex:{configurable:!0},lineLength:{configurable:!0},segment:{configurable:!0},lowerSize:{configurable:!0},upperSize:{configurable:!0},lineOffsetX:{configurable:!0},lineOffsetY:{configurable:!0},writingMode:{configurable:!0},hidden:{configurable:!0}};return r.anchorX.get=function(){return this._structArray.int16[this._pos2+0]},r.anchorX.set=function(t){this._structArray.int16[this._pos2+0]=t},r.anchorY.get=function(){return this._structArray.int16[this._pos2+1]},r.anchorY.set=function(t){this._structArray.int16[this._pos2+1]=t},r.glyphStartIndex.get=function(){return this._structArray.uint16[this._pos2+2]},r.glyphStartIndex.set=function(t){this._structArray.uint16[this._pos2+2]=t},r.numGlyphs.get=function(){return this._structArray.uint16[this._pos2+3]},r.numGlyphs.set=function(t){this._structArray.uint16[this._pos2+3]=t},r.vertexStartIndex.get=function(){return this._structArray.uint32[this._pos4+2]},r.vertexStartIndex.set=function(t){this._structArray.uint32[this._pos4+2]=t},r.lineStartIndex.get=function(){return this._structArray.uint32[this._pos4+3]},r.lineStartIndex.set=function(t){this._structArray.uint32[this._pos4+3]=t},r.lineLength.get=function(){return this._structArray.uint32[this._pos4+4]},r.lineLength.set=function(t){this._structArray.uint32[this._pos4+4]=t},r.segment.get=function(){return this._structArray.uint16[this._pos2+10]},r.segment.set=function(t){this._structArray.uint16[this._pos2+10]=t},r.lowerSize.get=function(){return this._structArray.uint16[this._pos2+11]},r.lowerSize.set=function(t){this._structArray.uint16[this._pos2+11]=t},r.upperSize.get=function(){return this._structArray.uint16[this._pos2+12]},r.upperSize.set=function(t){this._structArray.uint16[this._pos2+12]=t},r.lineOffsetX.get=function(){return this._structArray.float32[this._pos4+7]},r.lineOffsetX.set=function(t){this._structArray.float32[this._pos4+7]=t},r.lineOffsetY.get=function(){return this._structArray.float32[this._pos4+8]},r.lineOffsetY.set=function(t){this._structArray.float32[this._pos4+8]=t},r.writingMode.get=function(){return this._structArray.uint8[this._pos1+36]},r.writingMode.set=function(t){this._structArray.uint8[this._pos1+36]=t},r.hidden.get=function(){return this._structArray.uint8[this._pos1+37]},r.hidden.set=function(t){this._structArray.uint8[this._pos1+37]=t},Object.defineProperties(e.prototype,r),e}(Yr);mn.prototype.size=40;var yn=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.get=function(t){return new mn(this,t)},e}(sn);pr("PlacedSymbolArray",yn);var xn=function(t){function e(){t.apply(this,arguments)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={offsetX:{configurable:!0}};return r.offsetX.get=function(){return this._structArray.float32[this._pos4+0]},r.offsetX.set=function(t){this._structArray.float32[this._pos4+0]=t},Object.defineProperties(e.prototype,r),e}(Yr);xn.prototype.size=4;var bn=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getoffsetX=function(t){return this.float32[1*t+0]},e.prototype.get=function(t){return new xn(this,t)},e}(ln);pr("GlyphOffsetArray",bn);var _n=function(t){function e(){t.apply(this,arguments)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={x:{configurable:!0},y:{configurable:!0},tileUnitDistanceFromAnchor:{configurable:!0}};return r.x.get=function(){return this._structArray.int16[this._pos2+0]},r.x.set=function(t){this._structArray.int16[this._pos2+0]=t},r.y.get=function(){return this._structArray.int16[this._pos2+1]},r.y.set=function(t){this._structArray.int16[this._pos2+1]=t},r.tileUnitDistanceFromAnchor.get=function(){return this._structArray.int16[this._pos2+2]},r.tileUnitDistanceFromAnchor.set=function(t){this._structArray.int16[this._pos2+2]=t},Object.defineProperties(e.prototype,r),e}(Yr);_n.prototype.size=6;var wn=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getx=function(t){return this.int16[3*t+0]},e.prototype.gety=function(t){return this.int16[3*t+1]},e.prototype.gettileUnitDistanceFromAnchor=function(t){return this.int16[3*t+2]},e.prototype.get=function(t){return new _n(this,t)},e}(cn);pr("SymbolLineVertexArray",wn);var kn=function(t){function e(){t.apply(this,arguments)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={featureIndex:{configurable:!0},sourceLayerIndex:{configurable:!0},bucketIndex:{configurable:!0}};return r.featureIndex.get=function(){return this._structArray.uint32[this._pos4+0]},r.featureIndex.set=function(t){this._structArray.uint32[this._pos4+0]=t},r.sourceLayerIndex.get=function(){return this._structArray.uint16[this._pos2+2]},r.sourceLayerIndex.set=function(t){this._structArray.uint16[this._pos2+2]=t},r.bucketIndex.get=function(){return this._structArray.uint16[this._pos2+3]},r.bucketIndex.set=function(t){this._structArray.uint16[this._pos2+3]=t},Object.defineProperties(e.prototype,r),e}(Yr);kn.prototype.size=8;var An=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.get=function(t){return new kn(this,t)},e}(un);pr("FeatureIndexArray",An);var Mn=Xr([{name:"a_pos",components:2,type:"Int16"}],4).members,Tn=function(t){void 0===t&&(t=[]),this.segments=t};Tn.prototype.prepareSegment=function(t,e,r){var n=this.segments[this.segments.length-1];return t>Tn.MAX_VERTEX_ARRAY_LENGTH&&_("Max vertices per segment is "+Tn.MAX_VERTEX_ARRAY_LENGTH+": bucket requested "+t),(!n||n.vertexLength+t>Tn.MAX_VERTEX_ARRAY_LENGTH)&&(n={vertexOffset:e.length,primitiveOffset:r.length,vertexLength:0,primitiveLength:0},this.segments.push(n)),n},Tn.prototype.get=function(){return this.segments},Tn.prototype.destroy=function(){for(var t=0,e=this.segments;t<e.length;t+=1){var r=e[t];for(var n in r.vaos)r.vaos[n].destroy()}},Tn.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,pr("SegmentVector",Tn);var Sn=function(t,e){return 256*(t=f(Math.floor(t),0,255))+f(Math.floor(e),0,255)};function En(t){return[Sn(255*t.r,255*t.g),Sn(255*t.b,255*t.a)]}var Cn=function(t,e,r){this.value=t,this.name=e,this.type=r,this.statistics={max:-1/0}};Cn.prototype.defines=function(){return["#define HAS_UNIFORM_u_"+this.name]},Cn.prototype.populatePaintArray=function(){},Cn.prototype.upload=function(){},Cn.prototype.destroy=function(){},Cn.prototype.setUniforms=function(t,e,r,n){var i=n.constantOr(this.value),a=t.gl;"color"===this.type?a.uniform4f(e.uniforms["u_"+this.name],i.r,i.g,i.b,i.a):a.uniform1f(e.uniforms["u_"+this.name],i)};var Ln=function(t,e,r){this.expression=t,this.name=e,this.type=r,this.statistics={max:-1/0};var n="color"===r?pn:ln;this.paintVertexAttributes=[{name:"a_"+e,type:"Float32",components:"color"===r?2:1,offset:0}],this.paintVertexArray=new n};Ln.prototype.defines=function(){return[]},Ln.prototype.populatePaintArray=function(t,e){var r=this.paintVertexArray,n=r.length;r.reserve(t);var i=this.expression.evaluate(new Lr(0),e);if("color"===this.type)for(var a=En(i),o=n;o<t;o++)r.emplaceBack(a[0],a[1]);else{for(var s=n;s<t;s++)r.emplaceBack(i);this.statistics.max=Math.max(this.statistics.max,i)}},Ln.prototype.upload=function(t){this.paintVertexArray&&(this.paintVertexBuffer=t.createVertexBuffer(this.paintVertexArray,this.paintVertexAttributes))},Ln.prototype.destroy=function(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy()},Ln.prototype.setUniforms=function(t,e){t.gl.uniform1f(e.uniforms["a_"+this.name+"_t"],0)};var zn=function(t,e,r,n,i){this.expression=t,this.name=e,this.type=r,this.useIntegerZoom=n,this.zoom=i,this.statistics={max:-1/0};var a="color"===r?dn:pn;this.paintVertexAttributes=[{name:"a_"+e,type:"Float32",components:"color"===r?4:2,offset:0}],this.paintVertexArray=new a};zn.prototype.defines=function(){return[]},zn.prototype.populatePaintArray=function(t,e){var r=this.paintVertexArray,n=r.length;r.reserve(t);var i=this.expression.evaluate(new Lr(this.zoom),e),a=this.expression.evaluate(new Lr(this.zoom+1),e);if("color"===this.type)for(var o=En(i),s=En(a),l=n;l<t;l++)r.emplaceBack(o[0],o[1],s[0],s[1]);else{for(var c=n;c<t;c++)r.emplaceBack(i,a);this.statistics.max=Math.max(this.statistics.max,i,a)}},zn.prototype.upload=function(t){this.paintVertexArray&&(this.paintVertexBuffer=t.createVertexBuffer(this.paintVertexArray,this.paintVertexAttributes))},zn.prototype.destroy=function(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy()},zn.prototype.interpolationFactor=function(t){return this.useIntegerZoom?this.expression.interpolationFactor(Math.floor(t),this.zoom,this.zoom+1):this.expression.interpolationFactor(t,this.zoom,this.zoom+1)},zn.prototype.setUniforms=function(t,e,r){t.gl.uniform1f(e.uniforms["a_"+this.name+"_t"],this.interpolationFactor(r.zoom))};var On=function(){this.binders={},this.cacheKey="",this._buffers=[]};On.createDynamic=function(t,e,r){var n=new On,i=[];for(var a in t.paint._values)if(r(a)){var o=t.paint.get(a);if(o instanceof Fr&&o.property.specification["property-function"]){var s=Dn(a,t.type),l=o.property.specification.type,c=o.property.useIntegerZoom;"constant"===o.value.kind?(n.binders[a]=new Cn(o.value,s,l),i.push("/u_"+s)):"source"===o.value.kind?(n.binders[a]=new Ln(o.value,s,l),i.push("/a_"+s)):(n.binders[a]=new zn(o.value,s,l,c,e),i.push("/z_"+s))}}return n.cacheKey=i.sort().join(""),n},On.prototype.populatePaintArrays=function(t,e){for(var r in this.binders)this.binders[r].populatePaintArray(t,e)},On.prototype.defines=function(){var t=[];for(var e in this.binders)t.push.apply(t,this.binders[e].defines());return t},On.prototype.setUniforms=function(t,e,r,n){for(var i in this.binders)this.binders[i].setUniforms(t,e,n,r.get(i))},On.prototype.getPaintVertexBuffers=function(){return this._buffers},On.prototype.upload=function(t){for(var e in this.binders)this.binders[e].upload(t);var r=[];for(var n in this.binders){var i=this.binders[n];(i instanceof Ln||i instanceof zn)&&i.paintVertexBuffer&&r.push(i.paintVertexBuffer)}this._buffers=r},On.prototype.destroy=function(){for(var t in this.binders)this.binders[t].destroy()};var In=function(t,e,r,n){void 0===n&&(n=function(){return!0}),this.programConfigurations={};for(var i=0,a=e;i<a.length;i+=1){var o=a[i];this.programConfigurations[o.id]=On.createDynamic(o,r,n),this.programConfigurations[o.id].layoutAttributes=t}};function Dn(t,e){return{"text-opacity":"opacity","icon-opacity":"opacity","text-color":"fill_color","icon-color":"fill_color","text-halo-color":"halo_color","icon-halo-color":"halo_color","text-halo-blur":"halo_blur","icon-halo-blur":"halo_blur","text-halo-width":"halo_width","icon-halo-width":"halo_width","line-gap-width":"gapwidth"}[t]||t.replace(e+"-","").replace(/-/g,"_")}In.prototype.populatePaintArrays=function(t,e){for(var r in this.programConfigurations)this.programConfigurations[r].populatePaintArrays(t,e)},In.prototype.get=function(t){return this.programConfigurations[t]},In.prototype.upload=function(t){for(var e in this.programConfigurations)this.programConfigurations[e].upload(t)},In.prototype.destroy=function(){for(var t in this.programConfigurations)this.programConfigurations[t].destroy()},pr("ConstantBinder",Cn),pr("SourceExpressionBinder",Ln),pr("CompositeExpressionBinder",zn),pr("ProgramConfiguration",On,{omit:["_buffers"]}),pr("ProgramConfigurationSet",In);var Pn=8192,Rn=(16,{min:-1*Math.pow(2,15),max:Math.pow(2,15)-1});function Fn(t){for(var e=Pn/t.extent,r=t.loadGeometry(),n=0;n<r.length;n++)for(var i=r[n],a=0;a<i.length;a++){var o=i[a];o.x=Math.round(o.x*e),o.y=Math.round(o.y*e),(o.x<Rn.min||o.x>Rn.max||o.y<Rn.min||o.y>Rn.max)&&_("Geometry exceeds allowed extent, reduce your vector tile buffer size")}return r}function Bn(t,e,r,n,i){t.emplaceBack(2*e+(n+1)/2,2*r+(i+1)/2)}var Nn=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new $r,this.indexArray=new hn,this.segments=new Tn,this.programConfigurations=new In(Mn,t.layers,t.zoom)};function jn(t,e,r){for(var n=0;n<t.length;n++){var i=t[n];if(Zn(i,e))return!0;if(Yn(e,i,r))return!0}return!1}function Vn(t,e){if(1===t.length&&1===t[0].length)return Xn(e,t[0][0]);for(var r=0;r<e.length;r++)for(var n=e[r],i=0;i<n.length;i++)if(Xn(t,n[i]))return!0;for(var a=0;a<t.length;a++){for(var o=t[a],s=0;s<o.length;s++)if(Xn(e,o[s]))return!0;for(var l=0;l<e.length;l++)if(Hn(o,e[l]))return!0}return!1}function Un(t,e,r){for(var n=0;n<e.length;n++)for(var i=e[n],a=0;a<t.length;a++){var o=t[a];if(o.length>=3)for(var s=0;s<i.length;s++)if(Zn(o,i[s]))return!0;if(qn(o,i,r))return!0}return!1}function qn(t,e,r){if(t.length>1){if(Hn(t,e))return!0;for(var n=0;n<e.length;n++)if(Yn(e[n],t,r))return!0}for(var i=0;i<t.length;i++)if(Yn(t[i],e,r))return!0;return!1}function Hn(t,e){if(0===t.length||0===e.length)return!1;for(var r=0;r<t.length-1;r++)for(var n=t[r],i=t[r+1],a=0;a<e.length-1;a++)if(Gn(n,i,e[a],e[a+1]))return!0;return!1}function Gn(t,e,r,n){return w(t,r,n)!==w(e,r,n)&&w(t,e,r)!==w(t,e,n)}function Yn(t,e,r){var n=r*r;if(1===e.length)return t.distSqr(e[0])<n;for(var i=1;i<e.length;i++)if(Wn(t,e[i-1],e[i])<n)return!0;return!1}function Wn(t,e,r){var n=e.distSqr(r);if(0===n)return t.distSqr(e);var i=((t.x-e.x)*(r.x-e.x)+(t.y-e.y)*(r.y-e.y))/n;return i<0?t.distSqr(e):i>1?t.distSqr(r):t.distSqr(r.sub(e)._mult(i)._add(e))}function Xn(t,e){for(var r,n,i,a=!1,o=0;o<t.length;o++)for(var s=0,l=(r=t[o]).length-1;s<r.length;l=s++)n=r[s],i=r[l],n.y>e.y!=i.y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(a=!a);return a}function Zn(t,e){for(var r=!1,n=0,i=t.length-1;n<t.length;i=n++){var a=t[n],o=t[i];a.y>e.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(r=!r)}return r}function $n(t,e,r){var n=e.paint.get(t).value;return"constant"===n.kind?n.value:r.programConfigurations.get(e.id).binders[t].statistics.max}function Jn(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])}function Kn(t,e,r,n,i){if(!e[0]&&!e[1])return t;var a=l.convert(e);"viewport"===r&&a._rotate(-n);for(var o=[],s=0;s<t.length;s++){for(var c=t[s],u=[],h=0;h<c.length;h++)u.push(c[h].sub(a._mult(i)));o.push(u)}return o}Nn.prototype.populate=function(t,e){for(var r=0,n=t;r<n.length;r+=1){var i=n[r],a=i.feature,o=i.index,s=i.sourceLayerIndex;if(this.layers[0]._featureFilter(new Lr(this.zoom),a)){var l=Fn(a);this.addFeature(a,l),e.featureIndex.insert(a,l,o,s,this.index)}}},Nn.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},Nn.prototype.upload=function(t){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Mn),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.programConfigurations.upload(t)},Nn.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())},Nn.prototype.addFeature=function(t,e){for(var r=0,n=e;r<n.length;r+=1)for(var i=0,a=n[r];i<a.length;i+=1){var o=a[i],s=o.x,l=o.y;if(!(s<0||s>=Pn||l<0||l>=Pn)){var c=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray),u=c.vertexLength;Bn(this.layoutVertexArray,s,l,-1,-1),Bn(this.layoutVertexArray,s,l,1,-1),Bn(this.layoutVertexArray,s,l,1,1),Bn(this.layoutVertexArray,s,l,-1,1),this.indexArray.emplaceBack(u,u+1,u+2),this.indexArray.emplaceBack(u,u+3,u+2),c.vertexLength+=4,c.primitiveLength+=2}}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t)},pr("CircleBucket",Nn,{omit:["layers"]});var Qn={paint:new qr({"circle-radius":new jr(I.paint_circle["circle-radius"]),"circle-color":new jr(I.paint_circle["circle-color"]),"circle-blur":new jr(I.paint_circle["circle-blur"]),"circle-opacity":new jr(I.paint_circle["circle-opacity"]),"circle-translate":new Nr(I.paint_circle["circle-translate"]),"circle-translate-anchor":new Nr(I.paint_circle["circle-translate-anchor"]),"circle-pitch-scale":new Nr(I.paint_circle["circle-pitch-scale"]),"circle-pitch-alignment":new Nr(I.paint_circle["circle-pitch-alignment"]),"circle-stroke-width":new jr(I.paint_circle["circle-stroke-width"]),"circle-stroke-color":new jr(I.paint_circle["circle-stroke-color"]),"circle-stroke-opacity":new jr(I.paint_circle["circle-stroke-opacity"])})},ti=i(function(t,e){var r;t.exports=((r=new Float32Array(3))[0]=0,r[1]=0,r[2]=0,function(){var t=new Float32Array(4);t[0]=0,t[1]=0,t[2]=0,t[3]=0}(),{vec3:{transformMat3:function(t,e,r){var n=e[0],i=e[1],a=e[2];return t[0]=n*r[0]+i*r[3]+a*r[6],t[1]=n*r[1]+i*r[4]+a*r[7],t[2]=n*r[2]+i*r[5]+a*r[8],t}},vec4:{transformMat4:function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*a+r[12]*o,t[1]=r[1]*n+r[5]*i+r[9]*a+r[13]*o,t[2]=r[2]*n+r[6]*i+r[10]*a+r[14]*o,t[3]=r[3]*n+r[7]*i+r[11]*a+r[15]*o,t}},mat2:{create:function(){var t=new Float32Array(4);return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t},rotate:function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=Math.sin(r),l=Math.cos(r);return t[0]=n*l+a*s,t[1]=i*l+o*s,t[2]=n*-s+a*l,t[3]=i*-s+o*l,t},scale:function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=r[0],l=r[1];return t[0]=n*s,t[1]=i*s,t[2]=a*l,t[3]=o*l,t}},mat3:{create:function(){var t=new Float32Array(9);return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t},fromRotation:function(t,e){var r=Math.sin(e),n=Math.cos(e);return t[0]=n,t[1]=r,t[2]=0,t[3]=-r,t[4]=n,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t}},mat4:{create:function(){var t=new Float32Array(16);return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},identity:function(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},translate:function(t,e,r){var n,i,a,o,s,l,c,u,h,f,p,d,g=r[0],v=r[1],m=r[2];return e===t?(t[12]=e[0]*g+e[4]*v+e[8]*m+e[12],t[13]=e[1]*g+e[5]*v+e[9]*m+e[13],t[14]=e[2]*g+e[6]*v+e[10]*m+e[14],t[15]=e[3]*g+e[7]*v+e[11]*m+e[15]):(n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],l=e[5],c=e[6],u=e[7],h=e[8],f=e[9],p=e[10],d=e[11],t[0]=n,t[1]=i,t[2]=a,t[3]=o,t[4]=s,t[5]=l,t[6]=c,t[7]=u,t[8]=h,t[9]=f,t[10]=p,t[11]=d,t[12]=n*g+s*v+h*m+e[12],t[13]=i*g+l*v+f*m+e[13],t[14]=a*g+c*v+p*m+e[14],t[15]=o*g+u*v+d*m+e[15]),t},scale:function(t,e,r){var n=r[0],i=r[1],a=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*a,t[9]=e[9]*a,t[10]=e[10]*a,t[11]=e[11]*a,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},multiply:function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],l=e[5],c=e[6],u=e[7],h=e[8],f=e[9],p=e[10],d=e[11],g=e[12],v=e[13],m=e[14],y=e[15],x=r[0],b=r[1],_=r[2],w=r[3];return t[0]=x*n+b*s+_*h+w*g,t[1]=x*i+b*l+_*f+w*v,t[2]=x*a+b*c+_*p+w*m,t[3]=x*o+b*u+_*d+w*y,x=r[4],b=r[5],_=r[6],w=r[7],t[4]=x*n+b*s+_*h+w*g,t[5]=x*i+b*l+_*f+w*v,t[6]=x*a+b*c+_*p+w*m,t[7]=x*o+b*u+_*d+w*y,x=r[8],b=r[9],_=r[10],w=r[11],t[8]=x*n+b*s+_*h+w*g,t[9]=x*i+b*l+_*f+w*v,t[10]=x*a+b*c+_*p+w*m,t[11]=x*o+b*u+_*d+w*y,x=r[12],b=r[13],_=r[14],w=r[15],t[12]=x*n+b*s+_*h+w*g,t[13]=x*i+b*l+_*f+w*v,t[14]=x*a+b*c+_*p+w*m,t[15]=x*o+b*u+_*d+w*y,t},perspective:function(t,e,r,n,i){var a=1/Math.tan(e/2),o=1/(n-i);return t[0]=a/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=(i+n)*o,t[11]=-1,t[12]=0,t[13]=0,t[14]=2*i*n*o,t[15]=0,t},rotateX:function(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[4],o=e[5],s=e[6],l=e[7],c=e[8],u=e[9],h=e[10],f=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=a*i+c*n,t[5]=o*i+u*n,t[6]=s*i+h*n,t[7]=l*i+f*n,t[8]=c*i-a*n,t[9]=u*i-o*n,t[10]=h*i-s*n,t[11]=f*i-l*n,t},rotateZ:function(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],l=e[3],c=e[4],u=e[5],h=e[6],f=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=a*i+c*n,t[1]=o*i+u*n,t[2]=s*i+h*n,t[3]=l*i+f*n,t[4]=c*i-a*n,t[5]=u*i-o*n,t[6]=h*i-s*n,t[7]=f*i-l*n,t},invert:function(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],l=e[6],c=e[7],u=e[8],h=e[9],f=e[10],p=e[11],d=e[12],g=e[13],v=e[14],m=e[15],y=r*s-n*o,x=r*l-i*o,b=r*c-a*o,_=n*l-i*s,w=n*c-a*s,k=i*c-a*l,A=u*g-h*d,M=u*v-f*d,T=u*m-p*d,S=h*v-f*g,E=h*m-p*g,C=f*m-p*v,L=y*C-x*E+b*S+_*T-w*M+k*A;return L?(L=1/L,t[0]=(s*C-l*E+c*S)*L,t[1]=(i*E-n*C-a*S)*L,t[2]=(g*k-v*w+m*_)*L,t[3]=(f*w-h*k-p*_)*L,t[4]=(l*T-o*C-c*M)*L,t[5]=(r*C-i*T+a*M)*L,t[6]=(v*b-d*k-m*x)*L,t[7]=(u*k-f*b+p*x)*L,t[8]=(o*E-s*T+c*A)*L,t[9]=(n*T-r*E-a*A)*L,t[10]=(d*w-g*b+m*y)*L,t[11]=(h*b-u*w-p*y)*L,t[12]=(s*M-o*S-l*A)*L,t[13]=(r*S-n*M+i*A)*L,t[14]=(g*x-d*_-v*y)*L,t[15]=(u*_-h*x+f*y)*L,t):null},ortho:function(t,e,r,n,i,a,o){var s=1/(e-r),l=1/(n-i),c=1/(a-o);return t[0]=-2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*l,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*c,t[11]=0,t[12]=(e+r)*s,t[13]=(i+n)*l,t[14]=(o+a)*c,t[15]=1,t}}})}),ei=(ti.vec3,ti.vec4),ri=(ti.mat2,ti.mat3,ti.mat4),ni=function(t){function e(e){t.call(this,e,Qn)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new Nn(t)},e.prototype.queryRadius=function(t){var e=t;return $n("circle-radius",this,e)+$n("circle-stroke-width",this,e)+Jn(this.paint.get("circle-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,a,o){for(var s=Kn(t,this.paint.get("circle-translate"),this.paint.get("circle-translate-anchor"),i.angle,a),l=this.paint.get("circle-radius").evaluate(e)+this.paint.get("circle-stroke-width").evaluate(e),c="map"===this.paint.get("circle-pitch-alignment"),u=c?s:function(t,e,r){return s.map(function(t){return t.map(function(t){return ii(t,e,r)})})}(0,o,i),h=c?l*a:l,f=0,p=r;f<p.length;f+=1)for(var d=0,g=p[f];d<g.length;d+=1){var v=g[d],m=c?v:ii(v,o,i),y=h,x=ei.transformMat4([],[v.x,v.y,0,1],o);if("viewport"===this.paint.get("circle-pitch-scale")&&"map"===this.paint.get("circle-pitch-alignment")?y*=x[3]/i.cameraToCenterDistance:"map"===this.paint.get("circle-pitch-scale")&&"viewport"===this.paint.get("circle-pitch-alignment")&&(y*=i.cameraToCenterDistance/x[3]),jn(u,m,y))return!0}return!1},e}(Hr);function ii(t,e,r){var n=ei.transformMat4([],[t.x,t.y,0,1],e);return new l((n[0]/n[3]+1)*r.width*.5,(n[1]/n[3]+1)*r.height*.5)}var ai=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(Nn);function oi(t,e,r,n){var i=e.width,a=e.height;if(n){if(n.length!==i*a*r)throw new RangeError("mismatched image size")}else n=new Uint8Array(i*a*r);return t.width=i,t.height=a,t.data=n,t}function si(t,e,r){var n=e.width,i=e.height;if(n!==t.width||i!==t.height){var a=oi({},{width:n,height:i},r);li(t,a,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,n),height:Math.min(t.height,i)},r),t.width=n,t.height=i,t.data=a.data}}function li(t,e,r,n,i,a){if(0===i.width||0===i.height)return e;if(i.width>t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");for(var o=t.data,s=e.data,l=0;l<i.height;l++)for(var c=((r.y+l)*t.width+r.x)*a,u=((n.y+l)*e.width+n.x)*a,h=0;h<i.width*a;h++)s[u+h]=o[c+h];return e}pr("HeatmapBucket",ai,{omit:["layers"]});var ci=function(t,e){oi(this,t,1,e)};ci.prototype.resize=function(t){si(this,t,1)},ci.prototype.clone=function(){return new ci({width:this.width,height:this.height},new Uint8Array(this.data))},ci.copy=function(t,e,r,n,i){li(t,e,r,n,i,1)};var ui=function(t,e){oi(this,t,4,e)};ui.prototype.resize=function(t){si(this,t,4)},ui.prototype.clone=function(){return new ui({width:this.width,height:this.height},new Uint8Array(this.data))},ui.copy=function(t,e,r,n,i){li(t,e,r,n,i,4)},pr("AlphaImage",ci),pr("RGBAImage",ui);var hi={paint:new qr({"heatmap-radius":new jr(I.paint_heatmap["heatmap-radius"]),"heatmap-weight":new jr(I.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new Nr(I.paint_heatmap["heatmap-intensity"]),"heatmap-color":new Ur(I.paint_heatmap["heatmap-color"]),"heatmap-opacity":new Nr(I.paint_heatmap["heatmap-opacity"])})};function fi(t,e){for(var r=new Uint8Array(1024),n={},i=0,a=0;i<256;i++,a+=4){n[e]=i/255;var o=t.evaluate(n);r[a+0]=Math.floor(255*o.r/o.a),r[a+1]=Math.floor(255*o.g/o.a),r[a+2]=Math.floor(255*o.b/o.a),r[a+3]=Math.floor(255*o.a)}return new ui({width:256,height:1},r)}var pi=function(t){function e(e){t.call(this,e,hi),this._updateColorRamp()}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new ai(t)},e.prototype.setPaintProperty=function(e,r,n){t.prototype.setPaintProperty.call(this,e,r,n),"heatmap-color"===e&&this._updateColorRamp()},e.prototype._updateColorRamp=function(){var t=this._transitionablePaint._values["heatmap-color"].value.expression;this.colorRamp=fi(t,"heatmapDensity"),this.colorRampTexture=null},e.prototype.resize=function(){this.heatmapFbo&&(this.heatmapFbo.destroy(),this.heatmapFbo=null)},e.prototype.queryRadius=function(){return 0},e.prototype.queryIntersectsFeature=function(){return!1},e.prototype.hasOffscreenPass=function(){return 0!==this.paint.get("heatmap-opacity")&&"none"!==this.visibility},e}(Hr),di={paint:new qr({"hillshade-illumination-direction":new Nr(I.paint_hillshade["hillshade-illumination-direction"]),"hillshade-illumination-anchor":new Nr(I.paint_hillshade["hillshade-illumination-anchor"]),"hillshade-exaggeration":new Nr(I.paint_hillshade["hillshade-exaggeration"]),"hillshade-shadow-color":new Nr(I.paint_hillshade["hillshade-shadow-color"]),"hillshade-highlight-color":new Nr(I.paint_hillshade["hillshade-highlight-color"]),"hillshade-accent-color":new Nr(I.paint_hillshade["hillshade-accent-color"])})},gi=function(t){function e(e){t.call(this,e,di)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.hasOffscreenPass=function(){return 0!==this.paint.get("hillshade-exaggeration")&&"none"!==this.visibility},e}(Hr),vi=Xr([{name:"a_pos",components:2,type:"Int16"}],4).members,mi=xi,yi=xi;function xi(t,e,r){r=r||2;var n,i,a,o,s,l,c,u=e&&e.length,h=u?e[0]*r:t.length,f=bi(t,0,h,r,!0),p=[];if(!f)return p;if(u&&(f=function(t,e,r,n){var i,a,o,s=[];for(i=0,a=e.length;i<a;i++)(o=bi(t,e[i]*n,i<a-1?e[i+1]*n:t.length,n,!1))===o.next&&(o.steiner=!0),s.push(Li(o));for(s.sort(Si),i=0;i<s.length;i++)Ei(s[i],r),r=_i(r,r.next);return r}(t,e,f,r)),t.length>80*r){n=a=t[0],i=o=t[1];for(var d=r;d<h;d+=r)(s=t[d])<n&&(n=s),(l=t[d+1])<i&&(i=l),s>a&&(a=s),l>o&&(o=l);c=0!==(c=Math.max(a-n,o-i))?1/c:0}return wi(f,p,r,n,i,c),p}function bi(t,e,r,n,i){var a,o;if(i===Vi(t,e,r,n)>0)for(a=e;a<r;a+=n)o=Bi(a,t[a],t[a+1],o);else for(a=r-n;a>=e;a-=n)o=Bi(a,t[a],t[a+1],o);return o&&Di(o,o.next)&&(Ni(o),o=o.next),o}function _i(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!Di(n,n.next)&&0!==Ii(n.prev,n,n.next))n=n.next;else{if(Ni(n),(n=e=n.prev)===n.next)break;r=!0}}while(r||n!==e);return e}function wi(t,e,r,n,i,a,o){if(t){!o&&a&&function(t,e,r,n){var i=t;do{null===i.z&&(i.z=Ci(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,r,n,i,a,o,s,l,c=1;do{for(r=t,t=null,a=null,o=0;r;){for(o++,n=r,s=0,e=0;e<c&&(s++,n=n.nextZ);e++);for(l=c;s>0||l>0&&n;)0!==s&&(0===l||!n||r.z<=n.z)?(i=r,r=r.nextZ,s--):(i=n,n=n.nextZ,l--),a?a.nextZ=i:t=i,i.prevZ=a,a=i;r=n}a.nextZ=null,c*=2}while(o>1)}(i)}(t,n,i,a);for(var s,l,c=t;t.prev!==t.next;)if(s=t.prev,l=t.next,a?Ai(t,n,i,a):ki(t))e.push(s.i/r),e.push(t.i/r),e.push(l.i/r),Ni(t),t=l.next,c=l.next;else if((t=l)===c){o?1===o?wi(t=Mi(t,e,r),e,r,n,i,a,2):2===o&&Ti(t,e,r,n,i,a):wi(_i(t),e,r,n,i,a,1);break}}}function ki(t){var e=t.prev,r=t,n=t.next;if(Ii(e,r,n)>=0)return!1;for(var i=t.next.next;i!==t.prev;){if(zi(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&Ii(i.prev,i,i.next)>=0)return!1;i=i.next}return!0}function Ai(t,e,r,n){var i=t.prev,a=t,o=t.next;if(Ii(i,a,o)>=0)return!1;for(var s=i.x<a.x?i.x<o.x?i.x:o.x:a.x<o.x?a.x:o.x,l=i.y<a.y?i.y<o.y?i.y:o.y:a.y<o.y?a.y:o.y,c=i.x>a.x?i.x>o.x?i.x:o.x:a.x>o.x?a.x:o.x,u=i.y>a.y?i.y>o.y?i.y:o.y:a.y>o.y?a.y:o.y,h=Ci(s,l,e,r,n),f=Ci(c,u,e,r,n),p=t.prevZ,d=t.nextZ;p&&p.z>=h&&d&&d.z<=f;){if(p!==t.prev&&p!==t.next&&zi(i.x,i.y,a.x,a.y,o.x,o.y,p.x,p.y)&&Ii(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,d!==t.prev&&d!==t.next&&zi(i.x,i.y,a.x,a.y,o.x,o.y,d.x,d.y)&&Ii(d.prev,d,d.next)>=0)return!1;d=d.nextZ}for(;p&&p.z>=h;){if(p!==t.prev&&p!==t.next&&zi(i.x,i.y,a.x,a.y,o.x,o.y,p.x,p.y)&&Ii(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;d&&d.z<=f;){if(d!==t.prev&&d!==t.next&&zi(i.x,i.y,a.x,a.y,o.x,o.y,d.x,d.y)&&Ii(d.prev,d,d.next)>=0)return!1;d=d.nextZ}return!0}function Mi(t,e,r){var n=t;do{var i=n.prev,a=n.next.next;!Di(i,a)&&Pi(i,n,n.next,a)&&Ri(i,a)&&Ri(a,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(a.i/r),Ni(n),Ni(n.next),n=t=a),n=n.next}while(n!==t);return n}function Ti(t,e,r,n,i,a){var o=t;do{for(var s=o.next.next;s!==o.prev;){if(o.i!==s.i&&Oi(o,s)){var l=Fi(o,s);return o=_i(o,o.next),l=_i(l,l.next),wi(o,e,r,n,i,a),void wi(l,e,r,n,i,a)}s=s.next}o=o.next}while(o!==t)}function Si(t,e){return t.x-e.x}function Ei(t,e){if(e=function(t,e){var r,n=e,i=t.x,a=t.y,o=-1/0;do{if(a<=n.y&&a>=n.next.y&&n.next.y!==n.y){var s=n.x+(a-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(s<=i&&s>o){if(o=s,s===i){if(a===n.y)return n;if(a===n.next.y)return n.next}r=n.x<n.next.x?n:n.next}}n=n.next}while(n!==e);if(!r)return null;if(i===o)return r.prev;var l,c=r,u=r.x,h=r.y,f=1/0;for(n=r.next;n!==c;)i>=n.x&&n.x>=u&&i!==n.x&&zi(a<h?i:o,a,u,h,a<h?o:i,a,n.x,n.y)&&((l=Math.abs(a-n.y)/(i-n.x))<f||l===f&&n.x>r.x)&&Ri(n,t)&&(r=n,f=l),n=n.next;return r}(t,e)){var r=Fi(e,t);_i(r,r.next)}}function Ci(t,e,r,n,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*i)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*i)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function Li(t){var e=t,r=t;do{e.x<r.x&&(r=e),e=e.next}while(e!==t);return r}function zi(t,e,r,n,i,a,o,s){return(i-o)*(e-s)-(t-o)*(a-s)>=0&&(t-o)*(n-s)-(r-o)*(e-s)>=0&&(r-o)*(a-s)-(i-o)*(n-s)>=0}function Oi(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&Pi(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}(t,e)&&Ri(t,e)&&Ri(e,t)&&function(t,e){var r=t,n=!1,i=(t.x+e.x)/2,a=(t.y+e.y)/2;do{r.y>a!=r.next.y>a&&r.next.y!==r.y&&i<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}(t,e)}function Ii(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function Di(t,e){return t.x===e.x&&t.y===e.y}function Pi(t,e,r,n){return!!(Di(t,e)&&Di(r,n)||Di(t,n)&&Di(r,e))||Ii(t,e,r)>0!=Ii(t,e,n)>0&&Ii(r,n,t)>0!=Ii(r,n,e)>0}function Ri(t,e){return Ii(t.prev,t,t.next)<0?Ii(t,e,t.next)>=0&&Ii(t,t.prev,e)>=0:Ii(t,e,t.prev)<0||Ii(t,t.next,e)<0}function Fi(t,e){var r=new ji(t.i,t.x,t.y),n=new ji(e.i,e.x,e.y),i=t.next,a=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,a.next=n,n.prev=a,n}function Bi(t,e,r,n){var i=new ji(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Ni(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function ji(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function Vi(t,e,r,n){for(var i=0,a=e,o=r-n;a<r;a+=n)i+=(t[o]-t[a])*(t[a+1]+t[o+1]),o=a;return i}xi.deviation=function(t,e,r,n){var i=e&&e.length,a=i?e[0]*r:t.length,o=Math.abs(Vi(t,0,a,r));if(i)for(var s=0,l=e.length;s<l;s++){var c=e[s]*r,u=s<l-1?e[s+1]*r:t.length;o-=Math.abs(Vi(t,c,u,r))}var h=0;for(s=0;s<n.length;s+=3){var f=n[s]*r,p=n[s+1]*r,d=n[s+2]*r;h+=Math.abs((t[f]-t[d])*(t[p+1]-t[f+1])-(t[f]-t[p])*(t[d+1]-t[f+1]))}return 0===o&&0===h?0:Math.abs((h-o)/o)},xi.flatten=function(t){for(var e=t[0][0].length,r={vertices:[],holes:[],dimensions:e},n=0,i=0;i<t.length;i++){for(var a=0;a<t[i].length;a++)for(var o=0;o<e;o++)r.vertices.push(t[i][a][o]);i>0&&(n+=t[i-1].length,r.holes.push(n))}return r},mi.default=yi;var Ui=Hi,qi=Hi;function Hi(t,e,r,n,i){!function t(e,r,n,i,a){for(;i>n;){if(i-n>600){var o=i-n+1,s=r-n+1,l=Math.log(o),c=.5*Math.exp(2*l/3),u=.5*Math.sqrt(l*c*(o-c)/o)*(s-o/2<0?-1:1);t(e,r,Math.max(n,Math.floor(r-s*c/o+u)),Math.min(i,Math.floor(r+(o-s)*c/o+u)),a)}var h=e[r],f=n,p=i;for(Gi(e,n,r),a(e[i],h)>0&&Gi(e,n,i);f<p;){for(Gi(e,f,p),f++,p--;a(e[f],h)<0;)f++;for(;a(e[p],h)>0;)p--}0===a(e[n],h)?Gi(e,n,p):Gi(e,++p,i),p<=r&&(n=p+1),r<=p&&(i=p-1)}}(t,e,r||0,n||t.length-1,i||Yi)}function Gi(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function Yi(t,e){return t<e?-1:t>e?1:0}function Wi(t,e){var r=t.length;if(r<=1)return[t];for(var n,i,a=[],o=0;o<r;o++){var s=k(t[o]);0!==s&&(t[o].area=Math.abs(s),void 0===i&&(i=s<0),i===s<0?(n&&a.push(n),n=[t[o]]):n.push(t[o]))}if(n&&a.push(n),e>1)for(var l=0;l<a.length;l++)a[l].length<=e||(Ui(a[l],e,1,a[l].length-1,Xi),a[l]=a[l].slice(0,e));return a}function Xi(t,e){return e.area-t.area}Ui.default=qi;var Zi=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new $r,this.indexArray=new hn,this.indexArray2=new fn,this.programConfigurations=new In(vi,t.layers,t.zoom),this.segments=new Tn,this.segments2=new Tn};Zi.prototype.populate=function(t,e){for(var r=0,n=t;r<n.length;r+=1){var i=n[r],a=i.feature,o=i.index,s=i.sourceLayerIndex;if(this.layers[0]._featureFilter(new Lr(this.zoom),a)){var l=Fn(a);this.addFeature(a,l),e.featureIndex.insert(a,l,o,s,this.index)}}},Zi.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},Zi.prototype.upload=function(t){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,vi),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.indexBuffer2=t.createIndexBuffer(this.indexArray2),this.programConfigurations.upload(t)},Zi.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy())},Zi.prototype.addFeature=function(t,e){for(var r=0,n=Wi(e,500);r<n.length;r+=1){for(var i=n[r],a=0,o=0,s=i;o<s.length;o+=1)a+=s[o].length;for(var l=this.segments.prepareSegment(a,this.layoutVertexArray,this.indexArray),c=l.vertexLength,u=[],h=[],f=0,p=i;f<p.length;f+=1){var d=p[f];if(0!==d.length){d!==i[0]&&h.push(u.length/2);var g=this.segments2.prepareSegment(d.length,this.layoutVertexArray,this.indexArray2),v=g.vertexLength;this.layoutVertexArray.emplaceBack(d[0].x,d[0].y),this.indexArray2.emplaceBack(v+d.length-1,v),u.push(d[0].x),u.push(d[0].y);for(var m=1;m<d.length;m++)this.layoutVertexArray.emplaceBack(d[m].x,d[m].y),this.indexArray2.emplaceBack(v+m-1,v+m),u.push(d[m].x),u.push(d[m].y);g.vertexLength+=d.length,g.primitiveLength+=d.length}}for(var y=mi(u,h),x=0;x<y.length;x+=3)this.indexArray.emplaceBack(c+y[x],c+y[x+1],c+y[x+2]);l.vertexLength+=a,l.primitiveLength+=y.length/3}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t)},pr("FillBucket",Zi,{omit:["layers"]});var $i={paint:new qr({"fill-antialias":new Nr(I.paint_fill["fill-antialias"]),"fill-opacity":new jr(I.paint_fill["fill-opacity"]),"fill-color":new jr(I.paint_fill["fill-color"]),"fill-outline-color":new jr(I.paint_fill["fill-outline-color"]),"fill-translate":new Nr(I.paint_fill["fill-translate"]),"fill-translate-anchor":new Nr(I.paint_fill["fill-translate-anchor"]),"fill-pattern":new Vr(I.paint_fill["fill-pattern"])})},Ji=function(t){function e(e){t.call(this,e,$i)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.recalculate=function(t){this.paint=this._transitioningPaint.possiblyEvaluate(t);var e=this.paint._values["fill-outline-color"];"constant"===e.value.kind&&void 0===e.value.value&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"])},e.prototype.createBucket=function(t){return new Zi(t)},e.prototype.queryRadius=function(){return Jn(this.paint.get("fill-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,a){return Vn(Kn(t,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),i.angle,a),r)},e}(Hr),Ki=Xr([{name:"a_pos",components:2,type:"Int16"},{name:"a_normal_ed",components:4,type:"Int16"}],4).members,Qi=Math.pow(2,13);function ta(t,e,r,n,i,a,o,s){t.emplaceBack(e,r,2*Math.floor(n*Qi)+o,i*Qi*2,a*Qi*2,Math.round(s))}var ea=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new Kr,this.indexArray=new hn,this.programConfigurations=new In(Ki,t.layers,t.zoom),this.segments=new Tn};function ra(t,e){return t.x===e.x&&(t.x<0||t.x>Pn)||t.y===e.y&&(t.y<0||t.y>Pn)}function na(t){return t.every(function(t){return t.x<0})||t.every(function(t){return t.x>Pn})||t.every(function(t){return t.y<0})||t.every(function(t){return t.y>Pn})}ea.prototype.populate=function(t,e){for(var r=0,n=t;r<n.length;r+=1){var i=n[r],a=i.feature,o=i.index,s=i.sourceLayerIndex;if(this.layers[0]._featureFilter(new Lr(this.zoom),a)){var l=Fn(a);this.addFeature(a,l),e.featureIndex.insert(a,l,o,s,this.index)}}},ea.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},ea.prototype.upload=function(t){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Ki),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.programConfigurations.upload(t)},ea.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())},ea.prototype.addFeature=function(t,e){for(var r=0,n=Wi(e,500);r<n.length;r+=1){for(var i=n[r],a=0,o=0,s=i;o<s.length;o+=1)a+=s[o].length;for(var l=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray),c=0,u=i;c<u.length;c+=1){var h=u[c];if(0!==h.length&&!na(h))for(var f=0,p=0;p<h.length;p++){var d=h[p];if(p>=1){var g=h[p-1];if(!ra(d,g)){l.vertexLength+4>Tn.MAX_VERTEX_ARRAY_LENGTH&&(l=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));var v=d.sub(g)._perp()._unit(),m=g.dist(d);f+m>32768&&(f=0),ta(this.layoutVertexArray,d.x,d.y,v.x,v.y,0,0,f),ta(this.layoutVertexArray,d.x,d.y,v.x,v.y,0,1,f),f+=m,ta(this.layoutVertexArray,g.x,g.y,v.x,v.y,0,0,f),ta(this.layoutVertexArray,g.x,g.y,v.x,v.y,0,1,f);var y=l.vertexLength;this.indexArray.emplaceBack(y,y+1,y+2),this.indexArray.emplaceBack(y+1,y+2,y+3),l.vertexLength+=4,l.primitiveLength+=2}}}}l.vertexLength+a>Tn.MAX_VERTEX_ARRAY_LENGTH&&(l=this.segments.prepareSegment(a,this.layoutVertexArray,this.indexArray));for(var x=[],b=[],_=l.vertexLength,w=0,k=i;w<k.length;w+=1){var A=k[w];if(0!==A.length){A!==i[0]&&b.push(x.length/2);for(var M=0;M<A.length;M++){var T=A[M];ta(this.layoutVertexArray,T.x,T.y,0,0,1,1,0),x.push(T.x),x.push(T.y)}}}for(var S=mi(x,b),E=0;E<S.length;E+=3)this.indexArray.emplaceBack(_+S[E],_+S[E+1],_+S[E+2]);l.primitiveLength+=S.length/3,l.vertexLength+=a}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t)},pr("FillExtrusionBucket",ea,{omit:["layers"]});var ia={paint:new qr({"fill-extrusion-opacity":new Nr(I["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new jr(I["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new Nr(I["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new Nr(I["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new Vr(I["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new jr(I["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new jr(I["paint_fill-extrusion"]["fill-extrusion-base"])})},aa=function(t){function e(e){t.call(this,e,ia)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new ea(t)},e.prototype.queryRadius=function(){return Jn(this.paint.get("fill-extrusion-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,a){return Vn(Kn(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),i.angle,a),r)},e.prototype.hasOffscreenPass=function(){return 0!==this.paint.get("fill-extrusion-opacity")&&"none"!==this.visibility},e.prototype.resize=function(){this.viewportFrame&&(this.viewportFrame.destroy(),this.viewportFrame=null)},e}(Hr),oa=Xr([{name:"a_pos_normal",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint8"}],4).members,sa=la;function la(t,e,r,n,i){this.properties={},this.extent=r,this.type=0,this._pbf=t,this._geometry=-1,this._keys=n,this._values=i,t.readFields(ca,this,e)}function ca(t,e,r){1==t?e.id=r.readVarint():2==t?function(t,e){for(var r=t.readVarint()+t.pos;t.pos<r;){var n=e._keys[t.readVarint()],i=e._values[t.readVarint()];e.properties[n]=i}}(r,e):3==t?e.type=r.readVarint():4==t&&(e._geometry=r.pos)}function ua(t){for(var e,r,n=0,i=0,a=t.length,o=a-1;i<a;o=i++)e=t[i],n+=((r=t[o]).x-e.x)*(e.y+r.y);return n}la.types=["Unknown","Point","LineString","Polygon"],la.prototype.loadGeometry=function(){var t=this._pbf;t.pos=this._geometry;for(var e,r=t.readVarint()+t.pos,n=1,i=0,a=0,o=0,s=[];t.pos<r;){if(i<=0){var c=t.readVarint();n=7&c,i=c>>3}if(i--,1===n||2===n)a+=t.readSVarint(),o+=t.readSVarint(),1===n&&(e&&s.push(e),e=[]),e.push(new l(a,o));else{if(7!==n)throw new Error("unknown command "+n);e&&e.push(e[0].clone())}}return e&&s.push(e),s},la.prototype.bbox=function(){var t=this._pbf;t.pos=this._geometry;for(var e=t.readVarint()+t.pos,r=1,n=0,i=0,a=0,o=1/0,s=-1/0,l=1/0,c=-1/0;t.pos<e;){if(n<=0){var u=t.readVarint();r=7&u,n=u>>3}if(n--,1===r||2===r)(i+=t.readSVarint())<o&&(o=i),i>s&&(s=i),(a+=t.readSVarint())<l&&(l=a),a>c&&(c=a);else if(7!==r)throw new Error("unknown command "+r)}return[o,l,s,c]},la.prototype.toGeoJSON=function(t,e,r){var n,i,a=this.extent*Math.pow(2,r),o=this.extent*t,s=this.extent*e,l=this.loadGeometry(),c=la.types[this.type];function u(t){for(var e=0;e<t.length;e++){var r=t[e],n=180-360*(r.y+s)/a;t[e]=[360*(r.x+o)/a-180,360/Math.PI*Math.atan(Math.exp(n*Math.PI/180))-90]}}switch(this.type){case 1:var h=[];for(n=0;n<l.length;n++)h[n]=l[n][0];u(l=h);break;case 2:for(n=0;n<l.length;n++)u(l[n]);break;case 3:for(l=function(t){var e=t.length;if(e<=1)return[t];for(var r,n,i=[],a=0;a<e;a++){var o=ua(t[a]);0!==o&&(void 0===n&&(n=o<0),n===o<0?(r&&i.push(r),r=[t[a]]):r.push(t[a]))}return r&&i.push(r),i}(l),n=0;n<l.length;n++)for(i=0;i<l[n].length;i++)u(l[n][i])}1===l.length?l=l[0]:c="Multi"+c;var f={type:"Feature",geometry:{type:c,coordinates:l},properties:this.properties};return"id"in this&&(f.id=this.id),f};var ha=fa;function fa(t,e){this.version=1,this.name=null,this.extent=4096,this.length=0,this._pbf=t,this._keys=[],this._values=[],this._features=[],t.readFields(pa,this,e),this.length=this._features.length}function pa(t,e,r){15===t?e.version=r.readVarint():1===t?e.name=r.readString():5===t?e.extent=r.readVarint():2===t?e._features.push(r.pos):3===t?e._keys.push(r.readString()):4===t&&e._values.push(function(t){for(var e=null,r=t.readVarint()+t.pos;t.pos<r;){var n=t.readVarint()>>3;e=1===n?t.readString():2===n?t.readFloat():3===n?t.readDouble():4===n?t.readVarint64():5===n?t.readVarint():6===n?t.readSVarint():7===n?t.readBoolean():null}return e}(r))}function da(t,e,r){if(3===t){var n=new ha(r,r.readVarint()+r.pos);n.length&&(e[n.name]=n)}}fa.prototype.feature=function(t){if(t<0||t>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];var e=this._pbf.readVarint()+this._pbf.pos;return new sa(this._pbf,e,this.extent,this._keys,this._values)};var ga={VectorTile:function(t,e){this.layers=t.readFields(da,{},e)},VectorTileFeature:sa,VectorTileLayer:ha},va=ga.VectorTileFeature.types,ma=63,ya=Math.cos(Math.PI/180*37.5),xa=.5,ba=Math.pow(2,14)/xa;function _a(t,e,r,n,i,a,o){t.emplaceBack(e.x,e.y,n?1:0,i?1:-1,Math.round(ma*r.x)+128,Math.round(ma*r.y)+128,1+(0===a?0:a<0?-1:1)|(o*xa&63)<<2,o*xa>>6)}var wa=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new Qr,this.indexArray=new hn,this.programConfigurations=new In(oa,t.layers,t.zoom),this.segments=new Tn};function ka(t,e){return(t/e.tileTotal*(e.end-e.start)+e.start)*(ba-1)}wa.prototype.populate=function(t,e){for(var r=0,n=t;r<n.length;r+=1){var i=n[r],a=i.feature,o=i.index,s=i.sourceLayerIndex;if(this.layers[0]._featureFilter(new Lr(this.zoom),a)){var l=Fn(a);this.addFeature(a,l),e.featureIndex.insert(a,l,o,s,this.index)}}},wa.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},wa.prototype.upload=function(t){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,oa),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.programConfigurations.upload(t)},wa.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())},wa.prototype.addFeature=function(t,e){for(var r=this.layers[0].layout,n=r.get("line-join").evaluate(t),i=r.get("line-cap"),a=r.get("line-miter-limit"),o=r.get("line-round-limit"),s=0,l=e;s<l.length;s+=1){var c=l[s];this.addLine(c,t,n,i,a,o)}},wa.prototype.addLine=function(t,e,r,n,i,a){var o=null;e.properties&&e.properties.hasOwnProperty("mapbox_clip_start")&&e.properties.hasOwnProperty("mapbox_clip_end")&&(o={start:e.properties.mapbox_clip_start,end:e.properties.mapbox_clip_end,tileTotal:void 0});for(var s="Polygon"===va[e.type],l=t.length;l>=2&&t[l-1].equals(t[l-2]);)l--;for(var c=0;c<l-1&&t[c].equals(t[c+1]);)c++;if(!(l<(s?3:2))){o&&(o.tileTotal=function(t,e,r){for(var n,i,a=0,o=c;o<r-1;o++)n=t[o],i=t[o+1],a+=n.dist(i);return a}(t,0,l)),"bevel"===r&&(i=1.05);var u=Pn/(512*this.overscaling)*15,h=t[c],f=this.segments.prepareSegment(10*l,this.layoutVertexArray,this.indexArray);this.distance=0;var p,d,g,v=n,m=s?"butt":n,y=!0,x=void 0,b=void 0,_=void 0,w=void 0;this.e1=this.e2=this.e3=-1,s&&(p=t[l-2],w=h.sub(p)._unit()._perp());for(var k=c;k<l;k++)if(!(b=s&&k===l-1?t[c+1]:t[k+1])||!t[k].equals(b)){w&&(_=w),p&&(x=p),p=t[k],w=b?b.sub(p)._unit()._perp():_;var A=(_=_||w).add(w);0===A.x&&0===A.y||A._unit();var M=A.x*w.x+A.y*w.y,T=0!==M?1/M:1/0,S=M<ya&&x&&b;if(S&&k>c){var E=p.dist(x);if(E>2*u){var C=p.sub(p.sub(x)._mult(u/E)._round());this.distance+=C.dist(x),this.addCurrentVertex(C,this.distance,_.mult(1),0,0,!1,f,o),x=C}}var L=x&&b,z=L?r:b?v:m;if(L&&"round"===z&&(T<a?z="miter":T<=2&&(z="fakeround")),"miter"===z&&T>i&&(z="bevel"),"bevel"===z&&(T>2&&(z="flipbevel"),T<i&&(z="miter")),x&&(this.distance+=p.dist(x)),"miter"===z)A._mult(T),this.addCurrentVertex(p,this.distance,A,0,0,!1,f,o);else if("flipbevel"===z){if(T>100)A=w.clone().mult(-1);else{var O=_.x*w.y-_.y*w.x>0?-1:1,I=T*_.add(w).mag()/_.sub(w).mag();A._perp()._mult(I*O)}this.addCurrentVertex(p,this.distance,A,0,0,!1,f,o),this.addCurrentVertex(p,this.distance,A.mult(-1),0,0,!1,f,o)}else if("bevel"===z||"fakeround"===z){var D=_.x*w.y-_.y*w.x>0,P=-Math.sqrt(T*T-1);if(D?(g=0,d=P):(d=0,g=P),y||this.addCurrentVertex(p,this.distance,_,d,g,!1,f,o),"fakeround"===z){for(var R=Math.floor(8*(.5-(M-.5))),F=void 0,B=0;B<R;B++)F=w.mult((B+1)/(R+1))._add(_)._unit(),this.addPieSliceVertex(p,this.distance,F,D,f,o);this.addPieSliceVertex(p,this.distance,A,D,f,o);for(var N=R-1;N>=0;N--)F=_.mult((N+1)/(R+1))._add(w)._unit(),this.addPieSliceVertex(p,this.distance,F,D,f,o)}b&&this.addCurrentVertex(p,this.distance,w,-d,-g,!1,f,o)}else"butt"===z?(y||this.addCurrentVertex(p,this.distance,_,0,0,!1,f,o),b&&this.addCurrentVertex(p,this.distance,w,0,0,!1,f,o)):"square"===z?(y||(this.addCurrentVertex(p,this.distance,_,1,1,!1,f,o),this.e1=this.e2=-1),b&&this.addCurrentVertex(p,this.distance,w,-1,-1,!1,f,o)):"round"===z&&(y||(this.addCurrentVertex(p,this.distance,_,0,0,!1,f,o),this.addCurrentVertex(p,this.distance,_,1,1,!0,f,o),this.e1=this.e2=-1),b&&(this.addCurrentVertex(p,this.distance,w,-1,-1,!0,f,o),this.addCurrentVertex(p,this.distance,w,0,0,!1,f,o)));if(S&&k<l-1){var j=p.dist(b);if(j>2*u){var V=p.add(b.sub(p)._mult(u/j)._round());this.distance+=V.dist(p),this.addCurrentVertex(V,this.distance,w.mult(1),0,0,!1,f,o),p=V}}y=!1}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,e)}},wa.prototype.addCurrentVertex=function(t,e,r,n,i,a,o,s){var l,c=this.layoutVertexArray,u=this.indexArray;s&&(e=ka(e,s)),l=r.clone(),n&&l._sub(r.perp()._mult(n)),_a(c,t,l,a,!1,n,e),this.e3=o.vertexLength++,this.e1>=0&&this.e2>=0&&(u.emplaceBack(this.e1,this.e2,this.e3),o.primitiveLength++),this.e1=this.e2,this.e2=this.e3,l=r.mult(-1),i&&l._sub(r.perp()._mult(i)),_a(c,t,l,a,!0,-i,e),this.e3=o.vertexLength++,this.e1>=0&&this.e2>=0&&(u.emplaceBack(this.e1,this.e2,this.e3),o.primitiveLength++),this.e1=this.e2,this.e2=this.e3,e>ba/2&&!s&&(this.distance=0,this.addCurrentVertex(t,this.distance,r,n,i,a,o))},wa.prototype.addPieSliceVertex=function(t,e,r,n,i,a){r=r.mult(n?-1:1);var o=this.layoutVertexArray,s=this.indexArray;a&&(e=ka(e,a)),_a(o,t,r,!1,n,0,e),this.e3=i.vertexLength++,this.e1>=0&&this.e2>=0&&(s.emplaceBack(this.e1,this.e2,this.e3),i.primitiveLength++),n?this.e2=this.e3:this.e1=this.e3},pr("LineBucket",wa,{omit:["layers"]});var Aa=new qr({"line-cap":new Nr(I.layout_line["line-cap"]),"line-join":new jr(I.layout_line["line-join"]),"line-miter-limit":new Nr(I.layout_line["line-miter-limit"]),"line-round-limit":new Nr(I.layout_line["line-round-limit"])}),Ma={paint:new qr({"line-opacity":new jr(I.paint_line["line-opacity"]),"line-color":new jr(I.paint_line["line-color"]),"line-translate":new Nr(I.paint_line["line-translate"]),"line-translate-anchor":new Nr(I.paint_line["line-translate-anchor"]),"line-width":new jr(I.paint_line["line-width"]),"line-gap-width":new jr(I.paint_line["line-gap-width"]),"line-offset":new jr(I.paint_line["line-offset"]),"line-blur":new jr(I.paint_line["line-blur"]),"line-dasharray":new Vr(I.paint_line["line-dasharray"]),"line-pattern":new Vr(I.paint_line["line-pattern"]),"line-gradient":new Ur(I.paint_line["line-gradient"])}),layout:Aa},Ta=new(function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.possiblyEvaluate=function(e,r){return r=new Lr(Math.floor(r.zoom),{now:r.now,fadeDuration:r.fadeDuration,zoomHistory:r.zoomHistory,transition:r.transition}),t.prototype.possiblyEvaluate.call(this,e,r)},e.prototype.evaluate=function(e,r,n){return r=p({},r,{zoom:Math.floor(r.zoom)}),t.prototype.evaluate.call(this,e,r,n)},e}(jr))(Ma.paint.properties["line-width"].specification);Ta.useIntegerZoom=!0;var Sa=function(t){function e(e){t.call(this,e,Ma)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.setPaintProperty=function(e,r,n){t.prototype.setPaintProperty.call(this,e,r,n),"line-gradient"===e&&this._updateGradient()},e.prototype._updateGradient=function(){var t=this._transitionablePaint._values["line-gradient"].value.expression;this.gradient=fi(t,"lineProgress"),this.gradientTexture=null},e.prototype.recalculate=function(e){t.prototype.recalculate.call(this,e),this.paint._values["line-floorwidth"]=Ta.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,e)},e.prototype.createBucket=function(t){return new wa(t)},e.prototype.queryRadius=function(t){var e=t,r=Ea($n("line-width",this,e),$n("line-gap-width",this,e)),n=$n("line-offset",this,e);return r/2+Math.abs(n)+Jn(this.paint.get("line-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,a){var o=Kn(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),i.angle,a),s=a/2*Ea(this.paint.get("line-width").evaluate(e),this.paint.get("line-gap-width").evaluate(e)),c=this.paint.get("line-offset").evaluate(e);return c&&(r=function(t,e){for(var r=[],n=new l(0,0),i=0;i<t.length;i++){for(var a=t[i],o=[],s=0;s<a.length;s++){var c=a[s-1],u=a[s],h=a[s+1],f=0===s?n:u.sub(c)._unit()._perp(),p=s===a.length-1?n:h.sub(u)._unit()._perp(),d=f._add(p)._unit(),g=d.x*p.x+d.y*p.y;d._mult(1/g),o.push(d._mult(e)._add(u))}r.push(o)}return r}(r,c*a)),Un(o,r,s)},e}(Hr);function Ea(t,e){return e>0?e+2*t:t}var Ca=Xr([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"}]),La=Xr([{name:"a_projected_pos",components:3,type:"Float32"}],4),za=(Xr([{name:"a_fade_opacity",components:1,type:"Uint32"}],4),Xr([{name:"a_placed",components:2,type:"Uint8"}],4)),Oa=(Xr([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"},{type:"Int16",name:"radius"},{type:"Int16",name:"signedDistanceFromAnchor"}]),Xr([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4)),Ia=Xr([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4);function Da(t,e,r){var n=e.layout.get("text-transform").evaluate(r);return"uppercase"===n?t=t.toLocaleUpperCase():"lowercase"===n&&(t=t.toLocaleLowerCase()),Cr.applyArabicShaping&&(t=Cr.applyArabicShaping(t)),t}Xr([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"hidden"}]),Xr([{type:"Float32",name:"offsetX"}]),Xr([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]);var Pa={"!":"\ufe15","#":"\uff03",$:"\uff04","%":"\uff05","&":"\uff06","(":"\ufe35",")":"\ufe36","*":"\uff0a","+":"\uff0b",",":"\ufe10","-":"\ufe32",".":"\u30fb","/":"\uff0f",":":"\ufe13",";":"\ufe14","<":"\ufe3f","=":"\uff1d",">":"\ufe40","?":"\ufe16","@":"\uff20","[":"\ufe47","\\":"\uff3c","]":"\ufe48","^":"\uff3e",_:"\ufe33","`":"\uff40","{":"\ufe37","|":"\u2015","}":"\ufe38","~":"\uff5e","\xa2":"\uffe0","\xa3":"\uffe1","\xa5":"\uffe5","\xa6":"\uffe4","\xac":"\uffe2","\xaf":"\uffe3","\u2013":"\ufe32","\u2014":"\ufe31","\u2018":"\ufe43","\u2019":"\ufe44","\u201c":"\ufe41","\u201d":"\ufe42","\u2026":"\ufe19","\u2027":"\u30fb","\u20a9":"\uffe6","\u3001":"\ufe11","\u3002":"\ufe12","\u3008":"\ufe3f","\u3009":"\ufe40","\u300a":"\ufe3d","\u300b":"\ufe3e","\u300c":"\ufe41","\u300d":"\ufe42","\u300e":"\ufe43","\u300f":"\ufe44","\u3010":"\ufe3b","\u3011":"\ufe3c","\u3014":"\ufe39","\u3015":"\ufe3a","\u3016":"\ufe17","\u3017":"\ufe18","\uff01":"\ufe15","\uff08":"\ufe35","\uff09":"\ufe36","\uff0c":"\ufe10","\uff0d":"\ufe32","\uff0e":"\u30fb","\uff1a":"\ufe13","\uff1b":"\ufe14","\uff1c":"\ufe3f","\uff1e":"\ufe40","\uff1f":"\ufe16","\uff3b":"\ufe47","\uff3d":"\ufe48","\uff3f":"\ufe33","\uff5b":"\ufe37","\uff5c":"\u2015","\uff5d":"\ufe38","\uff5f":"\ufe35","\uff60":"\ufe36","\uff61":"\ufe12","\uff62":"\ufe41","\uff63":"\ufe42"},Ra=function(t){function e(e,r,n,i){t.call(this,e,r),this.angle=n,void 0!==i&&(this.segment=i)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.clone=function(){return new e(this.x,this.y,this.angle,this.segment)},e}(l);function Fa(t,e){var r=e.expression;if("constant"===r.kind)return{functionType:"constant",layoutSize:r.evaluate(new Lr(t+1))};if("source"===r.kind)return{functionType:"source"};for(var n=r.zoomStops,i=0;i<n.length&&n[i]<=t;)i++;for(var a=i=Math.max(0,i-1);a<n.length&&n[a]<t+1;)a++;a=Math.min(n.length-1,a);var o={min:n[i],max:n[a]};return"composite"===r.kind?{functionType:"composite",zoomRange:o,propertyValue:e.value}:{functionType:"camera",layoutSize:r.evaluate(new Lr(t+1)),zoomRange:o,sizeRange:{min:r.evaluate(new Lr(o.min)),max:r.evaluate(new Lr(o.max))},propertyValue:e.value}}pr("Anchor",Ra);var Ba=ga.VectorTileFeature.types,Na=[{name:"a_fade_opacity",components:1,type:"Uint8",offset:0}];function ja(t,e,r,n,i,a,o,s){t.emplaceBack(e,r,Math.round(32*n),Math.round(32*i),a,o,s?s[0]:0,s?s[1]:0)}function Va(t,e,r){t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r)}var Ua=function(t){this.layoutVertexArray=new tn,this.indexArray=new hn,this.programConfigurations=t,this.segments=new Tn,this.dynamicLayoutVertexArray=new en,this.opacityVertexArray=new rn,this.placedSymbolArray=new yn};Ua.prototype.upload=function(t,e){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Ca.members),this.indexBuffer=t.createIndexBuffer(this.indexArray,e),this.programConfigurations.upload(t),this.dynamicLayoutVertexBuffer=t.createVertexBuffer(this.dynamicLayoutVertexArray,La.members,!0),this.opacityVertexBuffer=t.createVertexBuffer(this.opacityVertexArray,Na,!0),this.opacityVertexBuffer.itemSize=1},Ua.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.dynamicLayoutVertexBuffer.destroy(),this.opacityVertexBuffer.destroy())},pr("SymbolBuffers",Ua);var qa=function(t,e,r){this.layoutVertexArray=new t,this.layoutAttributes=e,this.indexArray=new r,this.segments=new Tn,this.collisionVertexArray=new on};qa.prototype.upload=function(t){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=t.createVertexBuffer(this.collisionVertexArray,za.members,!0)},qa.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy())},pr("CollisionBuffers",qa);var Ha=function(t){this.collisionBoxArray=t.collisionBoxArray,this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.pixelRatio=t.pixelRatio,this.sourceLayerIndex=t.sourceLayerIndex;var e=this.layers[0]._unevaluatedLayout._values;this.textSizeData=Fa(this.zoom,e["text-size"]),this.iconSizeData=Fa(this.zoom,e["icon-size"]);var r=this.layers[0].layout;this.sortFeaturesByY=r.get("text-allow-overlap")||r.get("icon-allow-overlap")||r.get("text-ignore-placement")||r.get("icon-ignore-placement")};Ha.prototype.createArrays=function(){this.text=new Ua(new In(Ca.members,this.layers,this.zoom,function(t){return/^text/.test(t)})),this.icon=new Ua(new In(Ca.members,this.layers,this.zoom,function(t){return/^icon/.test(t)})),this.collisionBox=new qa(an,Oa.members,fn),this.collisionCircle=new qa(an,Ia.members,hn),this.glyphOffsetArray=new bn,this.lineVertexArray=new wn},Ha.prototype.populate=function(t,e){var r=this.layers[0],n=r.layout,i=n.get("text-font"),a=n.get("text-field"),o=n.get("icon-image"),s=("constant"!==a.value.kind||a.value.value.length>0)&&("constant"!==i.value.kind||i.value.value.length>0),l="constant"!==o.value.kind||o.value.value&&o.value.value.length>0;if(this.features=[],s||l){for(var c=e.iconDependencies,u=e.glyphDependencies,h=new Lr(this.zoom),f=0,p=t;f<p.length;f+=1){var d=p[f],g=d.feature,v=d.index,m=d.sourceLayerIndex;if(r._featureFilter(h,g)){var y=void 0;s&&(y=Da(y=r.getValueAndResolveTokens("text-field",g),r,g));var x=void 0;if(l&&(x=r.getValueAndResolveTokens("icon-image",g)),y||x){var b={text:y,icon:x,index:v,sourceLayerIndex:m,geometry:Fn(g),properties:g.properties,type:Ba[g.type]};if(void 0!==g.id&&(b.id=g.id),this.features.push(b),x&&(c[x]=!0),y)for(var _=i.evaluate(g).join(","),w=u[_]=u[_]||{},k="map"===n.get("text-rotation-alignment")&&"line"===n.get("symbol-placement"),A=xr(y),M=0;M<y.length;M++)if(w[y.charCodeAt(M)]=!0,k&&A){var T=Pa[y.charAt(M)];T&&(w[T.charCodeAt(0)]=!0)}}}}"line"===n.get("symbol-placement")&&(this.features=function(t){var e={},r={},n=[],i=0;function a(e){n.push(t[e]),i++}function o(t,e,i){var a=r[t];return delete r[t],r[e]=a,n[a].geometry[0].pop(),n[a].geometry[0]=n[a].geometry[0].concat(i[0]),a}function s(t,r,i){var a=e[r];return delete e[r],e[t]=a,n[a].geometry[0].shift(),n[a].geometry[0]=i[0].concat(n[a].geometry[0]),a}function l(t,e,r){var n=r?e[0][e[0].length-1]:e[0][0];return t+":"+n.x+":"+n.y}for(var c=0;c<t.length;c++){var u=t[c],h=u.geometry,f=u.text;if(f){var p=l(f,h),d=l(f,h,!0);if(p in r&&d in e&&r[p]!==e[d]){var g=s(p,d,h),v=o(p,d,n[g].geometry);delete e[p],delete r[d],r[l(f,n[v].geometry,!0)]=v,n[g].geometry=null}else p in r?o(p,d,h):d in e?s(p,d,h):(a(c),e[p]=i-1,r[d]=i-1)}else a(c)}return n.filter(function(t){return t.geometry})}(this.features))}},Ha.prototype.isEmpty=function(){return 0===this.symbolInstances.length},Ha.prototype.upload=function(t){this.text.upload(t,this.sortFeaturesByY),this.icon.upload(t,this.sortFeaturesByY),this.collisionBox.upload(t),this.collisionCircle.upload(t)},Ha.prototype.destroy=function(){this.text.destroy(),this.icon.destroy(),this.collisionBox.destroy(),this.collisionCircle.destroy()},Ha.prototype.addToLineVertexArray=function(t,e){var r=this.lineVertexArray.length;if(void 0!==t.segment){for(var n=t.dist(e[t.segment+1]),i=t.dist(e[t.segment]),a={},o=t.segment+1;o<e.length;o++)a[o]={x:e[o].x,y:e[o].y,tileUnitDistanceFromAnchor:n},o<e.length-1&&(n+=e[o+1].dist(e[o]));for(var s=t.segment||0;s>=0;s--)a[s]={x:e[s].x,y:e[s].y,tileUnitDistanceFromAnchor:i},s>0&&(i+=e[s-1].dist(e[s]));for(var l=0;l<e.length;l++){var c=a[l];this.lineVertexArray.emplaceBack(c.x,c.y,c.tileUnitDistanceFromAnchor)}}return{lineStartIndex:r,lineLength:this.lineVertexArray.length-r}},Ha.prototype.addSymbols=function(t,e,r,n,i,a,o,s,l,c){for(var u=t.indexArray,h=t.layoutVertexArray,f=t.dynamicLayoutVertexArray,p=t.segments.prepareSegment(4*e.length,t.layoutVertexArray,t.indexArray),d=this.glyphOffsetArray.length,g=p.vertexLength,v=0,m=e;v<m.length;v+=1){var y=m[v],x=y.tl,b=y.tr,_=y.bl,w=y.br,k=y.tex,A=p.vertexLength,M=y.glyphOffset[1];ja(h,s.x,s.y,x.x,M+x.y,k.x,k.y,r),ja(h,s.x,s.y,b.x,M+b.y,k.x+k.w,k.y,r),ja(h,s.x,s.y,_.x,M+_.y,k.x,k.y+k.h,r),ja(h,s.x,s.y,w.x,M+w.y,k.x+k.w,k.y+k.h,r),Va(f,s,0),u.emplaceBack(A,A+1,A+2),u.emplaceBack(A+1,A+2,A+3),p.vertexLength+=4,p.primitiveLength+=2,this.glyphOffsetArray.emplaceBack(y.glyphOffset[0])}t.placedSymbolArray.emplaceBack(s.x,s.y,d,this.glyphOffsetArray.length-d,g,l,c,s.segment,r?r[0]:0,r?r[1]:0,n[0],n[1],o,!1),t.programConfigurations.populatePaintArrays(t.layoutVertexArray.length,a)},Ha.prototype._addCollisionDebugVertex=function(t,e,r,n,i){return e.emplaceBack(0,0),t.emplaceBack(r.x,r.y,n.x,n.y,Math.round(i.x),Math.round(i.y))},Ha.prototype.addCollisionDebugVertices=function(t,e,r,n,i,a,o,s){var c=i.segments.prepareSegment(4,i.layoutVertexArray,i.indexArray),u=c.vertexLength,h=i.layoutVertexArray,f=i.collisionVertexArray;if(this._addCollisionDebugVertex(h,f,a,o.anchor,new l(t,e)),this._addCollisionDebugVertex(h,f,a,o.anchor,new l(r,e)),this._addCollisionDebugVertex(h,f,a,o.anchor,new l(r,n)),this._addCollisionDebugVertex(h,f,a,o.anchor,new l(t,n)),c.vertexLength+=4,s){var p=i.indexArray;p.emplaceBack(u,u+1,u+2),p.emplaceBack(u,u+2,u+3),c.primitiveLength+=2}else{var d=i.indexArray;d.emplaceBack(u,u+1),d.emplaceBack(u+1,u+2),d.emplaceBack(u+2,u+3),d.emplaceBack(u+3,u),c.primitiveLength+=4}},Ha.prototype.generateCollisionDebugBuffers=function(){for(var t=0,e=this.symbolInstances;t<e.length;t+=1){var r=e[t];r.textCollisionFeature={boxStartIndex:r.textBoxStartIndex,boxEndIndex:r.textBoxEndIndex},r.iconCollisionFeature={boxStartIndex:r.iconBoxStartIndex,boxEndIndex:r.iconBoxEndIndex};for(var n=0;n<2;n++){var i=r[0===n?"textCollisionFeature":"iconCollisionFeature"];if(i)for(var a=i.boxStartIndex;a<i.boxEndIndex;a++){var o=this.collisionBoxArray.get(a),s=o.x1,l=o.y1,c=o.x2,u=o.y2,h=o.radius>0;this.addCollisionDebugVertices(s,l,c,u,h?this.collisionCircle:this.collisionBox,o.anchorPoint,r,h)}}}},Ha.prototype.deserializeCollisionBoxes=function(t,e,r,n,i){for(var a={},o=e;o<r;o++){var s=t.get(o);if(0===s.radius){a.textBox={x1:s.x1,y1:s.y1,x2:s.x2,y2:s.y2,anchorPointX:s.anchorPointX,anchorPointY:s.anchorPointY},a.textFeatureIndex=s.featureIndex;break}a.textCircles||(a.textCircles=[],a.textFeatureIndex=s.featureIndex),a.textCircles.push(s.anchorPointX,s.anchorPointY,s.radius,s.signedDistanceFromAnchor,1)}for(var l=n;l<i;l++){var c=t.get(l);if(0===c.radius){a.iconBox={x1:c.x1,y1:c.y1,x2:c.x2,y2:c.y2,anchorPointX:c.anchorPointX,anchorPointY:c.anchorPointY},a.iconFeatureIndex=c.featureIndex;break}}return a},Ha.prototype.hasTextData=function(){return this.text.segments.get().length>0},Ha.prototype.hasIconData=function(){return this.icon.segments.get().length>0},Ha.prototype.hasCollisionBoxData=function(){return this.collisionBox.segments.get().length>0},Ha.prototype.hasCollisionCircleData=function(){return this.collisionCircle.segments.get().length>0},Ha.prototype.sortFeatures=function(t){var e=this;if(this.sortFeaturesByY&&this.sortedAngle!==t&&(this.sortedAngle=t,!(this.text.segments.get().length>1||this.icon.segments.get().length>1))){for(var r=[],n=0;n<this.symbolInstances.length;n++)r.push(n);var i=Math.sin(t),a=Math.cos(t);r.sort(function(t,r){var n=e.symbolInstances[t],o=e.symbolInstances[r];return(i*n.anchor.x+a*n.anchor.y|0)-(i*o.anchor.x+a*o.anchor.y|0)||o.featureIndex-n.featureIndex}),this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(var o=0,s=r;o<s.length;o+=1){var l=s[o],c=e.symbolInstances[l];e.featureSortOrder.push(c.featureIndex);for(var u=0,h=c.placedTextSymbolIndices;u<h.length;u+=1)for(var f=h[u],p=e.text.placedSymbolArray.get(f),d=p.vertexStartIndex+4*p.numGlyphs,g=p.vertexStartIndex;g<d;g+=4)e.text.indexArray.emplaceBack(g,g+1,g+2),e.text.indexArray.emplaceBack(g+1,g+2,g+3);var v=e.icon.placedSymbolArray.get(l);if(v.numGlyphs){var m=v.vertexStartIndex;e.icon.indexArray.emplaceBack(m,m+1,m+2),e.icon.indexArray.emplaceBack(m+1,m+2,m+3)}}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}},pr("SymbolBucket",Ha,{omit:["layers","collisionBoxArray","features","compareText"],shallow:["symbolInstances"]}),Ha.MAX_GLYPHS=65535,Ha.addDynamicAttributes=Va;var Ga=new qr({"symbol-placement":new Nr(I.layout_symbol["symbol-placement"]),"symbol-spacing":new Nr(I.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new Nr(I.layout_symbol["symbol-avoid-edges"]),"icon-allow-overlap":new Nr(I.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new Nr(I.layout_symbol["icon-ignore-placement"]),"icon-optional":new Nr(I.layout_symbol["icon-optional"]),"icon-rotation-alignment":new Nr(I.layout_symbol["icon-rotation-alignment"]),"icon-size":new jr(I.layout_symbol["icon-size"]),"icon-text-fit":new Nr(I.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new Nr(I.layout_symbol["icon-text-fit-padding"]),"icon-image":new jr(I.layout_symbol["icon-image"]),"icon-rotate":new jr(I.layout_symbol["icon-rotate"]),"icon-padding":new Nr(I.layout_symbol["icon-padding"]),"icon-keep-upright":new Nr(I.layout_symbol["icon-keep-upright"]),"icon-offset":new jr(I.layout_symbol["icon-offset"]),"icon-anchor":new jr(I.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new Nr(I.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new Nr(I.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new Nr(I.layout_symbol["text-rotation-alignment"]),"text-field":new jr(I.layout_symbol["text-field"]),"text-font":new jr(I.layout_symbol["text-font"]),"text-size":new jr(I.layout_symbol["text-size"]),"text-max-width":new jr(I.layout_symbol["text-max-width"]),"text-line-height":new Nr(I.layout_symbol["text-line-height"]),"text-letter-spacing":new jr(I.layout_symbol["text-letter-spacing"]),"text-justify":new jr(I.layout_symbol["text-justify"]),"text-anchor":new jr(I.layout_symbol["text-anchor"]),"text-max-angle":new Nr(I.layout_symbol["text-max-angle"]),"text-rotate":new jr(I.layout_symbol["text-rotate"]),"text-padding":new Nr(I.layout_symbol["text-padding"]),"text-keep-upright":new Nr(I.layout_symbol["text-keep-upright"]),"text-transform":new jr(I.layout_symbol["text-transform"]),"text-offset":new jr(I.layout_symbol["text-offset"]),"text-allow-overlap":new Nr(I.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new Nr(I.layout_symbol["text-ignore-placement"]),"text-optional":new Nr(I.layout_symbol["text-optional"])}),Ya={paint:new qr({"icon-opacity":new jr(I.paint_symbol["icon-opacity"]),"icon-color":new jr(I.paint_symbol["icon-color"]),"icon-halo-color":new jr(I.paint_symbol["icon-halo-color"]),"icon-halo-width":new jr(I.paint_symbol["icon-halo-width"]),"icon-halo-blur":new jr(I.paint_symbol["icon-halo-blur"]),"icon-translate":new Nr(I.paint_symbol["icon-translate"]),"icon-translate-anchor":new Nr(I.paint_symbol["icon-translate-anchor"]),"text-opacity":new jr(I.paint_symbol["text-opacity"]),"text-color":new jr(I.paint_symbol["text-color"]),"text-halo-color":new jr(I.paint_symbol["text-halo-color"]),"text-halo-width":new jr(I.paint_symbol["text-halo-width"]),"text-halo-blur":new jr(I.paint_symbol["text-halo-blur"]),"text-translate":new Nr(I.paint_symbol["text-translate"]),"text-translate-anchor":new Nr(I.paint_symbol["text-translate-anchor"])}),layout:Ga},Wa=function(t){function e(e){t.call(this,e,Ya)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.recalculate=function(e){t.prototype.recalculate.call(this,e),"auto"===this.layout.get("icon-rotation-alignment")&&("line"===this.layout.get("symbol-placement")?this.layout._values["icon-rotation-alignment"]="map":this.layout._values["icon-rotation-alignment"]="viewport"),"auto"===this.layout.get("text-rotation-alignment")&&("line"===this.layout.get("symbol-placement")?this.layout._values["text-rotation-alignment"]="map":this.layout._values["text-rotation-alignment"]="viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]=this.layout.get("text-rotation-alignment")),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment"))},e.prototype.getValueAndResolveTokens=function(t,e){var r,n=this.layout.get(t).evaluate(e),i=this._unevaluatedLayout._values[t];return i.isDataDriven()||_e(i.value)?n:(r=e.properties,n.replace(/{([^{}]+)}/g,function(t,e){return e in r?String(r[e]):""}))},e.prototype.createBucket=function(t){return new Ha(t)},e.prototype.queryRadius=function(){return 0},e.prototype.queryIntersectsFeature=function(){return!1},e}(Hr),Xa={paint:new qr({"background-color":new Nr(I.paint_background["background-color"]),"background-pattern":new Vr(I.paint_background["background-pattern"]),"background-opacity":new Nr(I.paint_background["background-opacity"])})},Za=function(t){function e(e){t.call(this,e,Xa)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(Hr),$a={paint:new qr({"raster-opacity":new Nr(I.paint_raster["raster-opacity"]),"raster-hue-rotate":new Nr(I.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new Nr(I.paint_raster["raster-brightness-min"]),"raster-brightness-max":new Nr(I.paint_raster["raster-brightness-max"]),"raster-saturation":new Nr(I.paint_raster["raster-saturation"]),"raster-contrast":new Nr(I.paint_raster["raster-contrast"]),"raster-fade-duration":new Nr(I.paint_raster["raster-fade-duration"])})},Ja={circle:ni,heatmap:pi,hillshade:gi,fill:Ji,"fill-extrusion":aa,line:Sa,symbol:Wa,background:Za,raster:function(t){function e(e){t.call(this,e,$a)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(Hr)},Ka=i(function(t,e){t.exports=function(){function t(t,e,r){r=r||{},this.w=t||64,this.h=e||64,this.autoResize=!!r.autoResize,this.shelves=[],this.freebins=[],this.stats={},this.bins={},this.maxId=0}function e(t,e,r){this.x=0,this.y=t,this.w=this.free=e,this.h=r}return t.prototype.pack=function(t,e){t=[].concat(t),e=e||{};for(var r,n,i,a,o=[],s=0;s<t.length;s++)if(r=t[s].w||t[s].width,n=t[s].h||t[s].height,i=t[s].id,r&&n){if(!(a=this.packOne(r,n,i)))continue;e.inPlace&&(t[s].x=a.x,t[s].y=a.y,t[s].id=a.id),o.push(a)}return this.shrink(),o},t.prototype.packOne=function(t,r,n){var i,a,o,s,l,c,u,h,f={freebin:-1,shelf:-1,waste:1/0},p=0;if("string"==typeof n||"number"==typeof n){if(i=this.getBin(n))return this.ref(i),i;"number"==typeof n&&(this.maxId=Math.max(n,this.maxId))}else n=++this.maxId;for(s=0;s<this.freebins.length;s++){if(r===(i=this.freebins[s]).maxh&&t===i.maxw)return this.allocFreebin(s,t,r,n);r>i.maxh||t>i.maxw||r<=i.maxh&&t<=i.maxw&&(o=i.maxw*i.maxh-t*r)<f.waste&&(f.waste=o,f.freebin=s)}for(s=0;s<this.shelves.length;s++)if(p+=(a=this.shelves[s]).h,!(t>a.free)){if(r===a.h)return this.allocShelf(s,t,r,n);r>a.h||r<a.h&&(o=(a.h-r)*t)<f.waste&&(f.freebin=-1,f.waste=o,f.shelf=s)}return-1!==f.freebin?this.allocFreebin(f.freebin,t,r,n):-1!==f.shelf?this.allocShelf(f.shelf,t,r,n):r<=this.h-p&&t<=this.w?(a=new e(p,this.w,r),this.allocShelf(this.shelves.push(a)-1,t,r,n)):this.autoResize?(l=c=this.h,((u=h=this.w)<=l||t>u)&&(h=2*Math.max(t,u)),(l<u||r>l)&&(c=2*Math.max(r,l)),this.resize(h,c),this.packOne(t,r,n)):null},t.prototype.allocFreebin=function(t,e,r,n){var i=this.freebins.splice(t,1)[0];return i.id=n,i.w=e,i.h=r,i.refcount=0,this.bins[n]=i,this.ref(i),i},t.prototype.allocShelf=function(t,e,r,n){var i=this.shelves[t].alloc(e,r,n);return this.bins[n]=i,this.ref(i),i},t.prototype.shrink=function(){if(this.shelves.length>0){for(var t=0,e=0,r=0;r<this.shelves.length;r++){var n=this.shelves[r];e+=n.h,t=Math.max(n.w-n.free,t)}this.resize(t,e)}},t.prototype.getBin=function(t){return this.bins[t]},t.prototype.ref=function(t){if(1==++t.refcount){var e=t.h;this.stats[e]=1+(0|this.stats[e])}return t.refcount},t.prototype.unref=function(t){return 0===t.refcount?0:(0==--t.refcount&&(this.stats[t.h]--,delete this.bins[t.id],this.freebins.push(t)),t.refcount)},t.prototype.clear=function(){this.shelves=[],this.freebins=[],this.stats={},this.bins={},this.maxId=0},t.prototype.resize=function(t,e){this.w=t,this.h=e;for(var r=0;r<this.shelves.length;r++)this.shelves[r].resize(t);return!0},e.prototype.alloc=function(t,e,r){if(t>this.free||e>this.h)return null;var n=this.x;return this.x+=t,this.free-=t,new function(t,e,r,n,i,a,o){this.id=t,this.x=e,this.y=r,this.w=n,this.h=i,this.maxw=a||n,this.maxh=o||i,this.refcount=0}(r,n,this.y,t,e,t,this.h)},e.prototype.resize=function(t){return this.free+=t-this.w,this.w=t,!0},t}()}),Qa=function(t,e){var r=e.pixelRatio;this.paddedRect=t,this.pixelRatio=r},to={tl:{configurable:!0},br:{configurable:!0},displaySize:{configurable:!0}};to.tl.get=function(){return[this.paddedRect.x+1,this.paddedRect.y+1]},to.br.get=function(){return[this.paddedRect.x+this.paddedRect.w-1,this.paddedRect.y+this.paddedRect.h-1]},to.displaySize.get=function(){return[(this.paddedRect.w-2)/this.pixelRatio,(this.paddedRect.h-2)/this.pixelRatio]},Object.defineProperties(Qa.prototype,to);var eo=function(t){var e=new ui({width:0,height:0}),r={},n=new Ka(0,0,{autoResize:!0});for(var i in t){var a=t[i],o=n.packOne(a.data.width+2,a.data.height+2);e.resize({width:n.w,height:n.h}),ui.copy(a.data,e,{x:0,y:0},{x:o.x+1,y:o.y+1},a.data),r[i]=new Qa(o,a)}n.shrink(),e.resize({width:n.w,height:n.h}),this.image=e,this.positions=r};pr("ImagePosition",Qa),pr("ImageAtlas",eo);var ro=function(t,e,r,n,i){var a,o,s=8*i-n-1,l=(1<<s)-1,c=l>>1,u=-7,h=r?i-1:0,f=r?-1:1,p=t[e+h];for(h+=f,a=p&(1<<-u)-1,p>>=-u,u+=s;u>0;a=256*a+t[e+h],h+=f,u-=8);for(o=a&(1<<-u)-1,a>>=-u,u+=n;u>0;o=256*o+t[e+h],h+=f,u-=8);if(0===a)a=1-c;else{if(a===l)return o?NaN:1/0*(p?-1:1);o+=Math.pow(2,n),a-=c}return(p?-1:1)*o*Math.pow(2,a-n)},no=function(t,e,r,n,i,a){var o,s,l,c=8*a-i-1,u=(1<<c)-1,h=u>>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:a-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=u):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),(e+=o+h>=1?f/l:f*Math.pow(2,1-h))*l>=2&&(o++,l/=2),o+h>=u?(s=0,o=u):o+h>=1?(s=(e*l-1)*Math.pow(2,i),o+=h):(s=e*Math.pow(2,h-1)*Math.pow(2,i),o=0));i>=8;t[r+p]=255&s,p+=d,s/=256,i-=8);for(o=o<<i|s,c+=i;c>0;t[r+p]=255&o,p+=d,o/=256,c-=8);t[r+p-d]|=128*g},io=ao;function ao(t){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(t)?t:new Uint8Array(t||0),this.pos=0,this.type=0,this.length=this.buf.length}function oo(t){return t.type===ao.Bytes?t.readVarint()+t.pos:t.pos+1}function so(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function lo(t,e,r){var n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.ceil(Math.log(e)/(7*Math.LN2));r.realloc(n);for(var i=r.pos-1;i>=t;i--)r.buf[i+n]=r.buf[i]}function co(t,e){for(var r=0;r<t.length;r++)e.writeVarint(t[r])}function uo(t,e){for(var r=0;r<t.length;r++)e.writeSVarint(t[r])}function ho(t,e){for(var r=0;r<t.length;r++)e.writeFloat(t[r])}function fo(t,e){for(var r=0;r<t.length;r++)e.writeDouble(t[r])}function po(t,e){for(var r=0;r<t.length;r++)e.writeBoolean(t[r])}function go(t,e){for(var r=0;r<t.length;r++)e.writeFixed32(t[r])}function vo(t,e){for(var r=0;r<t.length;r++)e.writeSFixed32(t[r])}function mo(t,e){for(var r=0;r<t.length;r++)e.writeFixed64(t[r])}function yo(t,e){for(var r=0;r<t.length;r++)e.writeSFixed64(t[r])}function xo(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16)+16777216*t[e+3]}function bo(t,e,r){t[r]=e,t[r+1]=e>>>8,t[r+2]=e>>>16,t[r+3]=e>>>24}function _o(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16)+(t[e+3]<<24)}ao.Varint=0,ao.Fixed64=1,ao.Bytes=2,ao.Fixed32=5,ao.prototype={destroy:function(){this.buf=null},readFields:function(t,e,r){for(r=r||this.length;this.pos<r;){var n=this.readVarint(),i=n>>3,a=this.pos;this.type=7&n,t(i,e,this),this.pos===a&&this.skip(n)}return e},readMessage:function(t,e){return this.readFields(t,e,this.readVarint()+this.pos)},readFixed32:function(){var t=xo(this.buf,this.pos);return this.pos+=4,t},readSFixed32:function(){var t=_o(this.buf,this.pos);return this.pos+=4,t},readFixed64:function(){var t=xo(this.buf,this.pos)+4294967296*xo(this.buf,this.pos+4);return this.pos+=8,t},readSFixed64:function(){var t=xo(this.buf,this.pos)+4294967296*_o(this.buf,this.pos+4);return this.pos+=8,t},readFloat:function(){var t=ro(this.buf,this.pos,!0,23,4);return this.pos+=4,t},readDouble:function(){var t=ro(this.buf,this.pos,!0,52,8);return this.pos+=8,t},readVarint:function(t){var e,r,n=this.buf;return e=127&(r=n[this.pos++]),r<128?e:(e|=(127&(r=n[this.pos++]))<<7,r<128?e:(e|=(127&(r=n[this.pos++]))<<14,r<128?e:(e|=(127&(r=n[this.pos++]))<<21,r<128?e:function(t,e,r){var n,i,a=r.buf;if(n=(112&(i=a[r.pos++]))>>4,i<128)return so(t,n,e);if(n|=(127&(i=a[r.pos++]))<<3,i<128)return so(t,n,e);if(n|=(127&(i=a[r.pos++]))<<10,i<128)return so(t,n,e);if(n|=(127&(i=a[r.pos++]))<<17,i<128)return so(t,n,e);if(n|=(127&(i=a[r.pos++]))<<24,i<128)return so(t,n,e);if(n|=(1&(i=a[r.pos++]))<<31,i<128)return so(t,n,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(r=n[this.pos]))<<28,t,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var t=this.readVarint();return t%2==1?(t+1)/-2:t/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var t=this.readVarint()+this.pos,e=function(t,e,r){for(var n="",i=e;i<r;){var a,o,s,l=t[i],c=null,u=l>239?4:l>223?3:l>191?2:1;if(i+u>r)break;1===u?l<128&&(c=l):2===u?128==(192&(a=t[i+1]))&&(c=(31&l)<<6|63&a)<=127&&(c=null):3===u?(a=t[i+1],o=t[i+2],128==(192&a)&&128==(192&o)&&((c=(15&l)<<12|(63&a)<<6|63&o)<=2047||c>=55296&&c<=57343)&&(c=null)):4===u&&(a=t[i+1],o=t[i+2],s=t[i+3],128==(192&a)&&128==(192&o)&&128==(192&s)&&((c=(15&l)<<18|(63&a)<<12|(63&o)<<6|63&s)<=65535||c>=1114112)&&(c=null)),null===c?(c=65533,u=1):c>65535&&(c-=65536,n+=String.fromCharCode(c>>>10&1023|55296),c=56320|1023&c),n+=String.fromCharCode(c),i+=u}return n}(this.buf,this.pos,t);return this.pos=t,e},readBytes:function(){var t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e},readPackedVarint:function(t,e){var r=oo(this);for(t=t||[];this.pos<r;)t.push(this.readVarint(e));return t},readPackedSVarint:function(t){var e=oo(this);for(t=t||[];this.pos<e;)t.push(this.readSVarint());return t},readPackedBoolean:function(t){var e=oo(this);for(t=t||[];this.pos<e;)t.push(this.readBoolean());return t},readPackedFloat:function(t){var e=oo(this);for(t=t||[];this.pos<e;)t.push(this.readFloat());return t},readPackedDouble:function(t){var e=oo(this);for(t=t||[];this.pos<e;)t.push(this.readDouble());return t},readPackedFixed32:function(t){var e=oo(this);for(t=t||[];this.pos<e;)t.push(this.readFixed32());return t},readPackedSFixed32:function(t){var e=oo(this);for(t=t||[];this.pos<e;)t.push(this.readSFixed32());return t},readPackedFixed64:function(t){var e=oo(this);for(t=t||[];this.pos<e;)t.push(this.readFixed64());return t},readPackedSFixed64:function(t){var e=oo(this);for(t=t||[];this.pos<e;)t.push(this.readSFixed64());return t},skip:function(t){var e=7&t;if(e===ao.Varint)for(;this.buf[this.pos++]>127;);else if(e===ao.Bytes)this.pos=this.readVarint()+this.pos;else if(e===ao.Fixed32)this.pos+=4;else{if(e!==ao.Fixed64)throw new Error("Unimplemented type: "+e);this.pos+=8}},writeTag:function(t,e){this.writeVarint(t<<3|e)},realloc:function(t){for(var e=this.length||16;e<this.pos+t;)e*=2;if(e!==this.length){var r=new Uint8Array(e);r.set(this.buf),this.buf=r,this.length=e}},finish:function(){return this.length=this.pos,this.pos=0,this.buf.subarray(0,this.length)},writeFixed32:function(t){this.realloc(4),bo(this.buf,t,this.pos),this.pos+=4},writeSFixed32:function(t){this.realloc(4),bo(this.buf,t,this.pos),this.pos+=4},writeFixed64:function(t){this.realloc(8),bo(this.buf,-1&t,this.pos),bo(this.buf,Math.floor(t*(1/4294967296)),this.pos+4),this.pos+=8},writeSFixed64:function(t){this.realloc(8),bo(this.buf,-1&t,this.pos),bo(this.buf,Math.floor(t*(1/4294967296)),this.pos+4),this.pos+=8},writeVarint:function(t){(t=+t||0)>268435455||t<0?function(t,e){var r,n;if(t>=0?(r=t%4294967296|0,n=t/4294967296|0):(n=~(-t/4294967296),4294967295^(r=~(-t%4294967296))?r=r+1|0:(r=0,n=n+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos]=127&t}(r,0,e),function(t,e){var r=(7&t)<<4;e.buf[e.pos++]|=r|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t)))))}(n,e)}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))))},writeSVarint:function(t){this.writeVarint(t<0?2*-t-1:2*t)},writeBoolean:function(t){this.writeVarint(Boolean(t))},writeString:function(t){t=String(t),this.realloc(4*t.length),this.pos++;var e=this.pos;this.pos=function(t,e,r){for(var n,i,a=0;a<e.length;a++){if((n=e.charCodeAt(a))>55295&&n<57344){if(!i){n>56319||a+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128)}return r}(this.buf,t,this.pos);var r=this.pos-e;r>=128&&lo(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r},writeFloat:function(t){this.realloc(4),no(this.buf,t,this.pos,!0,23,4),this.pos+=4},writeDouble:function(t){this.realloc(8),no(this.buf,t,this.pos,!0,52,8),this.pos+=8},writeBytes:function(t){var e=t.length;this.writeVarint(e),this.realloc(e);for(var r=0;r<e;r++)this.buf[this.pos++]=t[r]},writeRawMessage:function(t,e){this.pos++;var r=this.pos;t(e,this);var n=this.pos-r;n>=128&&lo(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n},writeMessage:function(t,e,r){this.writeTag(t,ao.Bytes),this.writeRawMessage(e,r)},writePackedVarint:function(t,e){this.writeMessage(t,co,e)},writePackedSVarint:function(t,e){this.writeMessage(t,uo,e)},writePackedBoolean:function(t,e){this.writeMessage(t,po,e)},writePackedFloat:function(t,e){this.writeMessage(t,ho,e)},writePackedDouble:function(t,e){this.writeMessage(t,fo,e)},writePackedFixed32:function(t,e){this.writeMessage(t,go,e)},writePackedSFixed32:function(t,e){this.writeMessage(t,vo,e)},writePackedFixed64:function(t,e){this.writeMessage(t,mo,e)},writePackedSFixed64:function(t,e){this.writeMessage(t,yo,e)},writeBytesField:function(t,e){this.writeTag(t,ao.Bytes),this.writeBytes(e)},writeFixed32Field:function(t,e){this.writeTag(t,ao.Fixed32),this.writeFixed32(e)},writeSFixed32Field:function(t,e){this.writeTag(t,ao.Fixed32),this.writeSFixed32(e)},writeFixed64Field:function(t,e){this.writeTag(t,ao.Fixed64),this.writeFixed64(e)},writeSFixed64Field:function(t,e){this.writeTag(t,ao.Fixed64),this.writeSFixed64(e)},writeVarintField:function(t,e){this.writeTag(t,ao.Varint),this.writeVarint(e)},writeSVarintField:function(t,e){this.writeTag(t,ao.Varint),this.writeSVarint(e)},writeStringField:function(t,e){this.writeTag(t,ao.Bytes),this.writeString(e)},writeFloatField:function(t,e){this.writeTag(t,ao.Fixed32),this.writeFloat(e)},writeDoubleField:function(t,e){this.writeTag(t,ao.Fixed64),this.writeDouble(e)},writeBooleanField:function(t,e){this.writeVarintField(t,Boolean(e))}};var wo=3;function ko(t,e,r){1===t&&r.readMessage(Ao,e)}function Ao(t,e,r){if(3===t){var n=r.readMessage(Mo,{}),i=n.id,a=n.bitmap,o=n.width,s=n.height,l=n.left,c=n.top,u=n.advance;e.push({id:i,bitmap:new ci({width:o+2*wo,height:s+2*wo},a),metrics:{width:o,height:s,left:l,top:c,advance:u}})}}function Mo(t,e,r){1===t?e.id=r.readVarint():2===t?e.bitmap=r.readBytes():3===t?e.width=r.readVarint():4===t?e.height=r.readVarint():5===t?e.left=r.readSVarint():6===t?e.top=r.readSVarint():7===t&&(e.advance=r.readVarint())}var To=wo,So=function(t,e,r){this.target=t,this.parent=e,this.mapId=r,this.callbacks={},this.callbackID=0,g(["receive"],this),this.target.addEventListener("message",this.receive,!1)};So.prototype.send=function(t,e,r,n){var i=r?this.mapId+":"+this.callbackID++:null;r&&(this.callbacks[i]=r);var a=[];this.target.postMessage({targetMapId:n,sourceMapId:this.mapId,type:t,id:String(i),data:gr(e,a)},a)},So.prototype.receive=function(t){var e,r=this,n=t.data,i=n.id;if(!n.targetMapId||this.mapId===n.targetMapId){var a=function(t,e){var n=[];r.target.postMessage({sourceMapId:r.mapId,type:"<response>",id:String(i),error:t?gr(t):null,data:gr(e,n)},n)};if("<response>"===n.type)e=this.callbacks[n.id],delete this.callbacks[n.id],e&&n.error?e(vr(n.error)):e&&e(null,vr(n.data));else if(void 0!==n.id&&this.parent[n.type])this.parent[n.type](n.sourceMapId,vr(n.data),a);else if(void 0!==n.id&&this.parent.getWorkerSource){var o=n.type.split(".");this.parent.getWorkerSource(n.sourceMapId,o[0],o[1])[o[2]](vr(n.data),a)}else this.parent[n.type](vr(n.data))}},So.prototype.remove=function(){this.target.removeEventListener("message",this.receive,!1)};var Eo=n(i(function(t,e){!function(t){function e(t,e,n){var i=r(256*t,256*(e=Math.pow(2,n)-e-1),n),a=r(256*(t+1),256*(e+1),n);return i[0]+","+i[1]+","+a[0]+","+a[1]}function r(t,e,r){var n=2*Math.PI*6378137/256/Math.pow(2,r);return[t*n-2*Math.PI*6378137/2,e*n-2*Math.PI*6378137/2]}t.getURL=function(t,r,n,i,a,o){return o=o||{},t+"?"+["bbox="+e(n,i,a),"format="+(o.format||"image/png"),"service="+(o.service||"WMS"),"version="+(o.version||"1.1.1"),"request="+(o.request||"GetMap"),"srs="+(o.srs||"EPSG:3857"),"width="+(o.width||256),"height="+(o.height||256),"layers="+r].join("&")},t.getTileBBox=e,t.getMercCoords=r,Object.defineProperty(t,"__esModule",{value:!0})}(e)})),Co=function(t,e,r){this.z=t,this.x=e,this.y=r,this.key=Oo(0,t,e,r)};Co.prototype.equals=function(t){return this.z===t.z&&this.x===t.x&&this.y===t.y},Co.prototype.url=function(t,e){var r=Eo.getTileBBox(this.x,this.y,this.z),n=function(t,e,r){for(var n,i="",a=t;a>0;a--)i+=(e&(n=1<<a-1)?1:0)+(r&n?2:0);return i}(this.z,this.x,this.y);return t[(this.x+this.y)%t.length].replace("{prefix}",(this.x%16).toString(16)+(this.y%16).toString(16)).replace("{z}",String(this.z)).replace("{x}",String(this.x)).replace("{y}",String("tms"===e?Math.pow(2,this.z)-this.y-1:this.y)).replace("{quadkey}",n).replace("{bbox-epsg-3857}",r)};var Lo=function(t,e){this.wrap=t,this.canonical=e,this.key=Oo(t,e.z,e.x,e.y)},zo=function(t,e,r,n,i){this.overscaledZ=t,this.wrap=e,this.canonical=new Co(r,+n,+i),this.key=Oo(e,t,n,i)};function Oo(t,e,r,n){(t*=2)<0&&(t=-1*t-1);var i=1<<e;return 32*(i*i*t+i*n+r)+e}zo.prototype.equals=function(t){return this.overscaledZ===t.overscaledZ&&this.wrap===t.wrap&&this.canonical.equals(t.canonical)},zo.prototype.scaledTo=function(t){var e=this.canonical.z-t;return t>this.canonical.z?new zo(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new zo(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)},zo.prototype.isChildOf=function(t){var e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ<this.overscaledZ&&t.canonical.x===this.canonical.x>>e&&t.canonical.y===this.canonical.y>>e},zo.prototype.children=function(t){if(this.overscaledZ>=t)return[new zo(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];var e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return[new zo(e,this.wrap,e,r,n),new zo(e,this.wrap,e,r+1,n),new zo(e,this.wrap,e,r,n+1),new zo(e,this.wrap,e,r+1,n+1)]},zo.prototype.isLessThan=function(t){return this.wrap<t.wrap||!(this.wrap>t.wrap)&&(this.overscaledZ<t.overscaledZ||!(this.overscaledZ>t.overscaledZ)&&(this.canonical.x<t.canonical.x||!(this.canonical.x>t.canonical.x)&&this.canonical.y<t.canonical.y))},zo.prototype.wrapped=function(){return new zo(this.overscaledZ,0,this.canonical.z,this.canonical.x,this.canonical.y)},zo.prototype.unwrapTo=function(t){return new zo(this.overscaledZ,t,this.canonical.z,this.canonical.x,this.canonical.y)},zo.prototype.overscaleFactor=function(){return Math.pow(2,this.overscaledZ-this.canonical.z)},zo.prototype.toUnwrapped=function(){return new Lo(this.wrap,this.canonical)},zo.prototype.toString=function(){return this.overscaledZ+"/"+this.canonical.x+"/"+this.canonical.y},zo.prototype.toCoordinate=function(){return new s(this.canonical.x+Math.pow(2,this.wrap),this.canonical.y,this.canonical.z)},pr("CanonicalTileID",Co),pr("OverscaledTileID",zo,{omit:["posMatrix"]});var Io=function(t,e,r){if(t<=0)throw new RangeError("Level must have positive dimension");this.dim=t,this.border=e,this.stride=this.dim+2*this.border,this.data=r||new Int32Array((this.dim+2*this.border)*(this.dim+2*this.border))};Io.prototype.set=function(t,e,r){this.data[this._idx(t,e)]=r+65536},Io.prototype.get=function(t,e){return this.data[this._idx(t,e)]-65536},Io.prototype._idx=function(t,e){if(t<-this.border||t>=this.dim+this.border||e<-this.border||e>=this.dim+this.border)throw new RangeError("out of range source coordinates for DEM data");return(e+this.border)*this.stride+(t+this.border)},pr("Level",Io);var Do=function(t,e,r){this.uid=t,this.scale=e||1,this.level=r||new Io(256,512),this.loaded=!!r};Do.prototype.loadFromImage=function(t,e){if(t.height!==t.width)throw new RangeError("DEM tiles must be square");if(e&&"mapbox"!==e&&"terrarium"!==e)return _('"'+e+'" is not a valid encoding type. Valid types include "mapbox" and "terrarium".');var r=this.level=new Io(t.width,t.width/2),n=t.data;this._unpackData(r,n,e||"mapbox");for(var i=0;i<r.dim;i++)r.set(-1,i,r.get(0,i)),r.set(r.dim,i,r.get(r.dim-1,i)),r.set(i,-1,r.get(i,0)),r.set(i,r.dim,r.get(i,r.dim-1));r.set(-1,-1,r.get(0,0)),r.set(r.dim,-1,r.get(r.dim-1,0)),r.set(-1,r.dim,r.get(0,r.dim-1)),r.set(r.dim,r.dim,r.get(r.dim-1,r.dim-1)),this.loaded=!0},Do.prototype._unpackMapbox=function(t,e,r){return(256*t*256+256*e+r)/10-1e4},Do.prototype._unpackTerrarium=function(t,e,r){return 256*t+e+r/256-32768},Do.prototype._unpackData=function(t,e,r){for(var n={mapbox:this._unpackMapbox,terrarium:this._unpackTerrarium}[r],i=0;i<t.dim;i++)for(var a=0;a<t.dim;a++){var o=4*(i*t.dim+a);t.set(a,i,this.scale*n(e[o],e[o+1],e[o+2]))}},Do.prototype.getPixels=function(){return new ui({width:this.level.dim+2*this.level.border,height:this.level.dim+2*this.level.border},new Uint8Array(this.level.data.buffer))},Do.prototype.backfillBorder=function(t,e,r){var n=this.level,i=t.level;if(n.dim!==i.dim)throw new Error("level mismatch (dem dimension)");var a=e*n.dim,o=e*n.dim+n.dim,s=r*n.dim,l=r*n.dim+n.dim;switch(e){case-1:a=o-1;break;case 1:o=a+1}switch(r){case-1:s=l-1;break;case 1:l=s+1}for(var c=f(a,-n.border,n.dim+n.border),u=f(o,-n.border,n.dim+n.border),h=f(s,-n.border,n.dim+n.border),p=f(l,-n.border,n.dim+n.border),d=-e*n.dim,g=-r*n.dim,v=h;v<p;v++)for(var m=c;m<u;m++)n.set(m,v,i.get(m+d,v+g))},pr("DEMData",Do);var Po=function(t){this._stringToNumber={},this._numberToString=[];for(var e=0;e<t.length;e++){var r=t[e];this._stringToNumber[r]=e,this._numberToString[e]=r}};Po.prototype.encode=function(t){return this._stringToNumber[t]},Po.prototype.decode=function(t){return this._numberToString[t]};var Ro=function(t,e,r,n){this.type="Feature",this._vectorTileFeature=t,t._z=e,t._x=r,t._y=n,this.properties=t.properties,null!=t.id&&(this.id=t.id)},Fo={geometry:{configurable:!0}};Fo.geometry.get=function(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry},Fo.geometry.set=function(t){this._geometry=t},Ro.prototype.toJSON=function(){var t={geometry:this.geometry};for(var e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&(t[e]=this[e]);return t},Object.defineProperties(Ro.prototype,Fo);var Bo=function(t,e,r){this.tileID=t,this.x=t.canonical.x,this.y=t.canonical.y,this.z=t.canonical.z,this.grid=e||new lr(Pn,16,0),this.featureIndexArray=r||new An};function No(t,e){return e-t}Bo.prototype.insert=function(t,e,r,n,i){var a=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(r,n,i);for(var o=0;o<e.length;o++){for(var s=e[o],l=[1/0,1/0,-1/0,-1/0],c=0;c<s.length;c++){var u=s[c];l[0]=Math.min(l[0],u.x),l[1]=Math.min(l[1],u.y),l[2]=Math.max(l[2],u.x),l[3]=Math.max(l[3],u.y)}l[0]<Pn&&l[1]<Pn&&l[2]>=0&&l[3]>=0&&this.grid.insert(a,l[0],l[1],l[2],l[3])}},Bo.prototype.loadVTLayers=function(){return this.vtLayers||(this.vtLayers=new ga.VectorTile(new io(this.rawTileData)).layers,this.sourceLayerCoder=new Po(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])),this.vtLayers},Bo.prototype.query=function(t,e){var r=this;this.loadVTLayers();for(var n=t.params||{},i=Pn/t.tileSize/t.scale,a=Re(n.filter),o=t.queryGeometry,s=t.queryPadding*i,l=1/0,c=1/0,u=-1/0,h=-1/0,f=0;f<o.length;f++)for(var p=o[f],d=0;d<p.length;d++){var g=p[d];l=Math.min(l,g.x),c=Math.min(c,g.y),u=Math.max(u,g.x),h=Math.max(h,g.y)}var v=this.grid.query(l-s,c-s,u+s,h+s);v.sort(No);for(var m,y={},x=function(s){var l=v[s];if(l!==m){m=l;var c=r.featureIndexArray.get(l),u=null;r.loadMatchingFeature(y,c.bucketIndex,c.sourceLayerIndex,c.featureIndex,a,n.layers,e,function(e,n){return u||(u=Fn(e)),n.queryIntersectsFeature(o,e,u,r.z,t.transform,i,t.posMatrix)})}},b=0;b<v.length;b++)x(b);return y},Bo.prototype.loadMatchingFeature=function(t,e,r,n,i,a,o,s){var l=this.bucketLayerIDs[e];if(!a||function(t,e){for(var r=0;r<t.length;r++)if(e.indexOf(t[r])>=0)return!0;return!1}(a,l)){var c=this.sourceLayerCoder.decode(r),u=this.vtLayers[c].feature(n);if(i(new Lr(this.tileID.overscaledZ),u))for(var h=0;h<l.length;h++){var f=l[h];if(!(a&&a.indexOf(f)<0)){var p=o[f];if(p&&(!s||s(u,p))){var d=new Ro(u,this.z,this.x,this.y);d.layer=p.serialize();var g=t[f];void 0===g&&(g=t[f]=[]),g.push({featureIndex:n,feature:d})}}}}},Bo.prototype.lookupSymbolFeatures=function(t,e,r,n,i,a){var o={};this.loadVTLayers();for(var s=Re(n),l=0,c=t;l<c.length;l+=1){var u=c[l];this.loadMatchingFeature(o,e,r,u,s,i,a)}return o},Bo.prototype.hasLayer=function(t){for(var e=0,r=this.bucketLayerIDs;e<r.length;e+=1)for(var n=0,i=r[e];n<i.length;n+=1)if(t===i[n])return!0;return!1},pr("FeatureIndex",Bo,{omit:["rawTileData","sourceLayerCoder"]});var jo={horizontal:1,vertical:2,horizontalOnly:3},Vo={9:!0,10:!0,11:!0,12:!0,13:!0,32:!0},Uo={};function qo(t,e,r,n){var i=Math.pow(t-e,2);return n?t<e?i/2:2*i:i+Math.abs(r)*r}function Ho(t,e){var r=0;return 10===t&&(r-=1e4),40!==t&&65288!==t||(r+=50),41!==e&&65289!==e||(r+=50),r}function Go(t,e,r,n,i,a){for(var o=null,s=qo(e,r,i,a),l=0,c=n;l<c.length;l+=1){var u=c[l],h=qo(e-u.x,r,i,a)+u.badness;h<=s&&(o=u,s=h)}return{index:t,x:e,priorBreak:o,badness:s}}function Yo(t,e,r,n){if(!r)return[];if(!t)return[];for(var i,a=[],o=function(t,e,r,n){for(var i=0,a=0;a<t.length;a++){var o=n[t.charCodeAt(a)];o&&(i+=o.metrics.advance+e)}return i/Math.max(1,Math.ceil(i/r))}(t,e,r,n),s=0,l=0;l<t.length;l++){var c=t.charCodeAt(l),u=n[c];u&&!Vo[c]&&(s+=u.metrics.advance+e),l<t.length-1&&(Uo[c]||!((i=c)<11904)&&(yr["Bopomofo Extended"](i)||yr.Bopomofo(i)||yr["CJK Compatibility Forms"](i)||yr["CJK Compatibility Ideographs"](i)||yr["CJK Compatibility"](i)||yr["CJK Radicals Supplement"](i)||yr["CJK Strokes"](i)||yr["CJK Symbols and Punctuation"](i)||yr["CJK Unified Ideographs Extension A"](i)||yr["CJK Unified Ideographs"](i)||yr["Enclosed CJK Letters and Months"](i)||yr["Halfwidth and Fullwidth Forms"](i)||yr.Hiragana(i)||yr["Ideographic Description Characters"](i)||yr["Kangxi Radicals"](i)||yr["Katakana Phonetic Extensions"](i)||yr.Katakana(i)||yr["Vertical Forms"](i)||yr["Yi Radicals"](i)||yr["Yi Syllables"](i)))&&a.push(Go(l+1,s,o,a,Ho(c,t.charCodeAt(l+1)),!1))}return function t(e){return e?t(e.priorBreak).concat(e.index):[]}(Go(t.length,s,o,a,0,!0))}function Wo(t){var e=.5,r=.5;switch(t){case"right":case"top-right":case"bottom-right":e=1;break;case"left":case"top-left":case"bottom-left":e=0}switch(t){case"bottom":case"bottom-right":case"bottom-left":r=1;break;case"top":case"top-right":case"top-left":r=0}return{horizontalAlign:e,verticalAlign:r}}function Xo(t,e,r,n,i){if(i){var a=e[t[n].glyph];if(a)for(var o=a.metrics.advance,s=(t[n].x+o)*i,l=r;l<=n;l++)t[l].x-=s}}Uo[10]=!0,Uo[32]=!0,Uo[38]=!0,Uo[40]=!0,Uo[41]=!0,Uo[43]=!0,Uo[45]=!0,Uo[47]=!0,Uo[173]=!0,Uo[183]=!0,Uo[8203]=!0,Uo[8208]=!0,Uo[8211]=!0,Uo[8231]=!0,e.commonjsGlobal=r,e.unwrapExports=n,e.createCommonjsModule=i,e.default=self,e.default$1=l,e.getJSON=function(t,e){var r=T(t);return r.setRequestHeader("Accept","application/json"),r.onerror=function(){e(new Error(r.statusText))},r.onload=function(){if(r.status>=200&&r.status<300&&r.response){var n;try{n=JSON.parse(r.response)}catch(t){return e(t)}e(null,n)}else 401===r.status&&t.url.match(/mapbox.com/)?e(new M(r.statusText+": you may have provided an invalid Mapbox access token. See https://www.mapbox.com/api-documentation/#access-tokens",r.status,t.url)):e(new M(r.statusText,r.status,t.url))},r.send(),r},e.getImage=function(t,e){return S(t,function(t,r){if(t)e(t);else if(r){var n=new self.Image,i=self.URL||self.webkitURL;n.onload=function(){e(null,n),i.revokeObjectURL(n.src)};var a=new self.Blob([new Uint8Array(r.data)],{type:"image/png"});n.cacheControl=r.cacheControl,n.expires=r.expires,n.src=r.data.byteLength?i.createObjectURL(a):"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII="}})},e.ResourceType=A,e.RGBAImage=ui,e.default$2=Ka,e.ImagePosition=Qa,e.getArrayBuffer=S,e.default$3=function(t){return new io(t).readFields(ko,[])},e.default$4=yr,e.asyncAll=function(t,e,r){if(!t.length)return r(null,[]);var n=t.length,i=new Array(t.length),a=null;t.forEach(function(t,o){e(t,function(t,e){t&&(a=t),i[o]=e,0==--n&&r(a,i)})})},e.AlphaImage=ci,e.default$5=I,e.endsWith=v,e.extend=p,e.sphericalToCartesian=function(t){var e=t[0],r=t[1],n=t[2];return r+=90,r*=Math.PI/180,n*=Math.PI/180,{x:e*Math.cos(r)*Math.sin(n),y:e*Math.sin(r)*Math.sin(n),z:e*Math.cos(n)}},e.Evented=O,e.validateStyle=nr,e.validateLight=ir,e.emitValidationErrors=sr,e.default$6=tt,e.number=wt,e.Properties=qr,e.Transitionable=Ir,e.Transitioning=Pr,e.PossiblyEvaluated=Br,e.DataConstantProperty=Nr,e.warnOnce=_,e.uniqueId=function(){return d++},e.default$7=So,e.pick=function(t,e){for(var r={},n=0;n<e.length;n++){var i=e[n];i in t&&(r[i]=t[i])}return r},e.wrap=function(t,e,r){var n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i},e.clamp=f,e.Event=L,e.ErrorEvent=z,e.OverscaledTileID=zo,e.default$8=Pn,e.createLayout=Xr,e.getCoordinatesCenter=function(t){for(var e=1/0,r=1/0,n=-1/0,i=-1/0,a=0;a<t.length;a++)e=Math.min(e,t[a].column),r=Math.min(r,t[a].row),n=Math.max(n,t[a].column),i=Math.max(i,t[a].row);var o=n-e,l=i-r,c=Math.max(o,l),u=Math.max(0,Math.floor(-Math.log(c)/Math.LN2));return new s((e+n)/2,(r+i)/2,0).zoomTo(u)},e.CanonicalTileID=Co,e.RasterBoundsArray=Jr,e.getVideo=function(t,e){var r,n,i=self.document.createElement("video");i.onloadstart=function(){e(null,i)};for(var a=0;a<t.length;a++){var o=self.document.createElement("source");r=t[a],n=void 0,(n=self.document.createElement("a")).href=r,(n.protocol!==self.document.location.protocol||n.host!==self.document.location.host)&&(i.crossOrigin="Anonymous"),o.src=t[a],i.appendChild(o)}return i},e.default$9=D,e.bindAll=g,e.default$10=function t(e,r){if(Array.isArray(e)){if(!Array.isArray(r)||e.length!==r.length)return!1;for(var n=0;n<e.length;n++)if(!t(e[n],r[n]))return!1;return!0}if("object"==typeof e&&null!==e&&null!==r){if("object"!=typeof r)return!1;if(Object.keys(e).length!==Object.keys(r).length)return!1;for(var i in e)if(!t(e[i],r[i]))return!1;return!0}return e===r},e.parseCacheControl=function(t){var e={};if(t.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,function(t,r,n,i){var a=n||i;return e[r]=!a||a.toLowerCase(),""}),e["max-age"]){var r=parseInt(e["max-age"],10);isNaN(r)?delete e["max-age"]:e["max-age"]=r}return e},e.default$11=Bo,e.default$12=Ro,e.default$13=Re,e.default$14=Ha,e.CollisionBoxArray=vn,e.default$15=Tn,e.TriangleIndexArray=hn,e.default$16=Lr,e.default$17=s,e.keysDifference=function(t,e){var r=[];for(var n in t)n in e||r.push(n);return r},e.default$18=["type","source","source-layer","minzoom","maxzoom","filter","layout"],e.mat4=ri,e.vec4=ei,e.getSizeData=Fa,e.evaluateSizeForFeature=function(t,e,r){var n=e;return"source"===t.functionType?r.lowerSize/10:"composite"===t.functionType?wt(r.lowerSize/10,r.upperSize/10,n.uSizeT):n.uSize},e.evaluateSizeForZoom=function(t,e,r){if("constant"===t.functionType)return{uSizeT:0,uSize:t.layoutSize};if("source"===t.functionType)return{uSizeT:0,uSize:0};if("camera"===t.functionType){var n=t.propertyValue,i=t.zoomRange,a=t.sizeRange,o=f(Se(n,r.specification).interpolationFactor(e,i.min,i.max),0,1);return{uSizeT:0,uSize:a.min+o*(a.max-a.min)}}var s=t.propertyValue,l=t.zoomRange;return{uSizeT:f(Se(s,r.specification).interpolationFactor(e,l.min,l.max),0,1),uSize:0}},e.addDynamicAttributes=Va,e.default$19=Ya,e.WritingMode=jo,e.multiPolygonIntersectsBufferedPoint=jn,e.multiPolygonIntersectsMultiPolygon=Vn,e.multiPolygonIntersectsBufferedMultiLine=Un,e.polygonIntersectsPolygon=function(t,e){for(var r=0;r<t.length;r++)if(Zn(e,t[r]))return!0;for(var n=0;n<e.length;n++)if(Zn(t,e[n]))return!0;return!!Hn(t,e)},e.distToSegmentSquared=Wn,e.default$20=ti,e.default$21=Hr,e.default$22=function(t){return new Ja[t.type](t)},e.clone=x,e.filterObject=y,e.mapObject=m,e.registerForPluginAvailability=function(t){return Tr?t({pluginURL:Tr,completionCallback:Ar}):Er.once("pluginAvailable",t),t},e.evented=Er,e.default$23=mr,e.default$24=On,e.PosArray=$r,e.UnwrappedTileID=Lo,e.ease=h,e.bezier=u,e.setRTLTextPlugin=function(t,e){if(Mr)throw new Error("setRTLTextPlugin cannot be called multiple times.");Mr=!0,Tr=t,Ar=function(t){t?(Mr=!1,Tr=null,e&&e(t)):Sr=!0},Er.fire(new L("pluginAvailable",{pluginURL:Tr,completionCallback:Ar}))},e.values=function(t){var e=[];for(var r in t)e.push(t[r]);return e},e.default$25=Ra,e.register=pr,e.GLYPH_PBF_BORDER=To,e.shapeText=function(t,e,r,n,i,a,o,s,l,c){var u=t.trim();c===jo.vertical&&(u=function(t){for(var e="",r=0;r<t.length;r++){var n=t.charCodeAt(r+1)||null,i=t.charCodeAt(r-1)||null;n&&wr(n)&&!Pa[t[r+1]]||i&&wr(i)&&!Pa[t[r-1]]||!Pa[t[r]]?e+=t[r]:e+=Pa[t[r]]}return e}(u));var h=[],f={positionedGlyphs:h,text:u,top:s[1],bottom:s[1],left:s[0],right:s[0],writingMode:c},p=Cr.processBidirectionalText;return function(t,e,r,n,i,a,o,s,l){for(var c=0,u=-17,h=0,f=t.positionedGlyphs,p="right"===a?1:"left"===a?0:.5,d=0,g=r;d<g.length;d+=1){var v=g[d];if((v=v.trim()).length){for(var m=f.length,y=0;y<v.length;y++){var x=v.charCodeAt(y),b=e[x];b&&(_r(x)&&o!==jo.horizontal?(f.push({glyph:x,x:c,y:0,vertical:!0}),c+=l+s):(f.push({glyph:x,x:c,y:u,vertical:!1}),c+=b.metrics.advance+s))}if(f.length!==m){var _=c-s;h=Math.max(_,h),Xo(f,e,m,f.length-1,p)}c=0,u+=n}else u+=n}var w=Wo(i),k=w.horizontalAlign,A=w.verticalAlign;!function(t,e,r,n,i,a,o){for(var s=(e-r)*i,l=(-n*o+.5)*a,c=0;c<t.length;c++)t[c].x+=s,t[c].y+=l}(f,p,k,A,h,n,r.length);var M=r.length*n;t.top+=-A*M,t.bottom=t.top+M,t.left+=-k*h,t.right=t.left+h}(f,e,p?p(u,Yo(u,o,r,e)):function(t,e){for(var r=[],n=0,i=0,a=e;i<a.length;i+=1){var o=a[i];r.push(t.substring(n,o)),n=o}return n<t.length&&r.push(t.substring(n,t.length)),r}(u,Yo(u,o,r,e)),n,i,a,c,o,l),!!h.length&&f},e.shapeIcon=function(t,e,r){var n=Wo(r),i=n.horizontalAlign,a=n.verticalAlign,o=e[0],s=e[1],l=o-t.displaySize[0]*i,c=l+t.displaySize[0],u=s-t.displaySize[1]*a;return{image:t,top:u,bottom:u+t.displaySize[1],left:l,right:c}},e.allowsVerticalWritingMode=xr,e.allowsLetterSpacing=function(t){for(var e=0,r=t;e<r.length;e+=1)if(!br(r[e].charCodeAt(0)))return!1;return!0},e.default$26=Wi,e.default$27=Po,e.default$28=eo,e.default$29=ga,e.default$30=io,e.default$31=Do,e.__moduleExports=ga,e.default$32=l,e.__moduleExports$1=io,e.plugin=Cr}),i(0,function(t){function e(t){var r=typeof t;if("number"===r||"boolean"===r||"string"===r||null==t)return JSON.stringify(t);if(Array.isArray(t)){for(var n="[",i=0,a=t;i<a.length;i+=1)n+=e(a[i])+",";return n+"]"}for(var o=Object.keys(t).sort(),s="{",l=0;l<o.length;l++)s+=JSON.stringify(o[l])+":"+e(t[o[l]])+",";return s+"}"}function r(r){for(var n="",i=0,a=t.default$18;i<a.length;i+=1)n+="/"+e(r[a[i]]);return n}var n=function(t){t&&this.replace(t)};function i(t,e,r,n,i){if(void 0===e.segment)return!0;for(var a=e,o=e.segment+1,s=0;s>-r/2;){if(--o<0)return!1;s-=t[o].dist(a),a=t[o]}s+=t[o].dist(t[o+1]),o++;for(var l=[],c=0;s<r/2;){var u=t[o-1],h=t[o],f=t[o+1];if(!f)return!1;var p=u.angleTo(h)-h.angleTo(f);for(p=Math.abs((p+3*Math.PI)%(2*Math.PI)-Math.PI),l.push({distance:s,angleDelta:p}),c+=p;s-l[0].distance>n;)c-=l.shift().angleDelta;if(c>i)return!1;o++,s+=h.dist(f)}return!0}function a(e,r,n,a,o,s,l,c,u){var h=a?.6*s*l:0,f=Math.max(a?a.right-a.left:0,o?o.right-o.left:0),p=0===e[0].x||e[0].x===u||0===e[0].y||e[0].y===u;return r-f*l<r/4&&(r=f*l+r/4),function e(r,n,a,o,s,l,c,u,h){for(var f=l/2,p=0,d=0;d<r.length-1;d++)p+=r[d].dist(r[d+1]);for(var g=0,v=n-a,m=[],y=0;y<r.length-1;y++){for(var x=r[y],b=r[y+1],_=x.dist(b),w=b.angleTo(x);v+a<g+_;){var k=((v+=a)-g)/_,A=t.number(x.x,b.x,k),M=t.number(x.y,b.y,k);if(A>=0&&A<h&&M>=0&&M<h&&v-f>=0&&v+f<=p){var T=new t.default$25(A,M,w,y);T._round(),o&&!i(r,T,l,o,s)||m.push(T)}}g+=_}return u||m.length||c||(m=e(r,g/2,a,o,s,l,c,!0,h)),m}(e,p?r/2*c%r:(f/2+2*s)*l*c%r,r,h,n,f*l,p,!1,u)}n.prototype.replace=function(t){this._layerConfigs={},this._layers={},this.update(t,[])},n.prototype.update=function(e,n){for(var i=this,a=0,o=e;a<o.length;a+=1){var s=o[a];i._layerConfigs[s.id]=s;var l=i._layers[s.id]=t.default$22(s);l._featureFilter=t.default$13(l.filter)}for(var c=0,u=n;c<u.length;c+=1){var h=u[c];delete i._layerConfigs[h],delete i._layers[h]}this.familiesBySource={};for(var f=0,p=function(t){for(var e={},n=0;n<t.length;n++){var i=r(t[n]),a=e[i];a||(a=e[i]=[]),a.push(t[n])}var o=[];for(var s in e)o.push(e[s]);return o}(t.values(this._layerConfigs));f<p.length;f+=1){var d=p[f].map(function(t){return i._layers[t.id]}),g=d[0];if("none"!==g.visibility){var v=g.source||"",m=i.familiesBySource[v];m||(m=i.familiesBySource[v]={});var y=g.sourceLayer||"_geojsonTileLayer",x=m[y];x||(x=m[y]=[]),x.push(d)}}};var o=function(){this.opacity=0,this.targetOpacity=0,this.time=0};o.prototype.clone=function(){var t=new o;return t.opacity=this.opacity,t.targetOpacity=this.targetOpacity,t.time=this.time,t},t.register("OpacityState",o);var s=function(t,e,r,n,i,a,o,s,l,c,u){var h=o.top*s-l,f=o.bottom*s+l,p=o.left*s-l,d=o.right*s+l;if(this.boxStartIndex=t.length,c){var g=f-h,v=d-p;g>0&&(g=Math.max(10*s,g),this._addLineCollisionCircles(t,e,r,r.segment,v,g,n,i,a,u))}else t.emplaceBack(r.x,r.y,p,h,d,f,n,i,a,0,0);this.boxEndIndex=t.length};s.prototype._addLineCollisionCircles=function(t,e,r,n,i,a,o,s,l,c){var u=a/2,h=Math.floor(i/u),f=1+.4*Math.log(c)/Math.LN2,p=Math.floor(h*f/2),d=-a/2,g=r,v=n+1,m=d,y=-i/2,x=y-i/4;do{if(--v<0){if(m>y)return;v=0;break}m-=e[v].dist(g),g=e[v]}while(m>x);for(var b=e[v].dist(e[v+1]),_=-p;_<h+p;_++){var w=_*u,k=y+w;if(w<0&&(k+=w),w>i&&(k+=w-i),!(k<m)){for(;m+b<k;){if(m+=b,++v+1>=e.length)return;b=e[v].dist(e[v+1])}var A=k-m,M=e[v],T=e[v+1].sub(M)._unit()._mult(A)._add(M)._round(),S=Math.abs(k-d)<u?0:.8*(k-d);t.emplaceBack(T.x,T.y,-a/2,-a/2,a/2,a/2,o,s,l,a/2,S)}}};var l=u,c=u;function u(t,e){if(!(this instanceof u))return new u(t,e);if(this.data=t||[],this.length=this.data.length,this.compare=e||h,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r)}function h(t,e){return t<e?-1:t>e?1:0}function f(e,r,n){void 0===r&&(r=1),void 0===n&&(n=!1);for(var i=1/0,a=1/0,o=-1/0,s=-1/0,c=e[0],u=0;u<c.length;u++){var h=c[u];(!u||h.x<i)&&(i=h.x),(!u||h.y<a)&&(a=h.y),(!u||h.x>o)&&(o=h.x),(!u||h.y>s)&&(s=h.y)}var f=o-i,g=s-a,v=Math.min(f,g),m=v/2,y=new l(null,p);if(0===v)return new t.default$1(i,a);for(var x=i;x<o;x+=v)for(var b=a;b<s;b+=v)y.push(new d(x+m,b+m,m,e));for(var _=function(t){for(var e=0,r=0,n=0,i=t[0],a=0,o=i.length,s=o-1;a<o;s=a++){var l=i[a],c=i[s],u=l.x*c.y-c.x*l.y;r+=(l.x+c.x)*u,n+=(l.y+c.y)*u,e+=3*u}return new d(r/e,n/e,0,t)}(e),w=y.length;y.length;){var k=y.pop();(k.d>_.d||!_.d)&&(_=k,n&&console.log("found best %d after %d probes",Math.round(1e4*k.d)/1e4,w)),k.max-_.d<=r||(m=k.h/2,y.push(new d(k.p.x-m,k.p.y-m,m,e)),y.push(new d(k.p.x+m,k.p.y-m,m,e)),y.push(new d(k.p.x-m,k.p.y+m,m,e)),y.push(new d(k.p.x+m,k.p.y+m,m,e)),w+=4)}return n&&(console.log("num probes: "+w),console.log("best distance: "+_.d)),_.p}function p(t,e){return e.max-t.max}function d(e,r,n,i){this.p=new t.default$1(e,r),this.h=n,this.d=function(e,r){for(var n=!1,i=1/0,a=0;a<r.length;a++)for(var o=r[a],s=0,l=o.length,c=l-1;s<l;c=s++){var u=o[s],h=o[c];u.y>e.y!=h.y>e.y&&e.x<(h.x-u.x)*(e.y-u.y)/(h.y-u.y)+u.x&&(n=!n),i=Math.min(i,t.distToSegmentSquared(e,u,h))}return(n?1:-1)*Math.sqrt(i)}(this.p,i),this.max=this.d+this.h*Math.SQRT2}function g(e,r,n,i,a,o){e.createArrays(),e.symbolInstances=[];var s=512*e.overscaling;e.tilePixelRatio=t.default$8/s,e.compareText={},e.iconsNeedLinear=!1;var l=e.layers[0].layout,c=e.layers[0]._unevaluatedLayout._values,u={};if("composite"===e.textSizeData.functionType){var h=e.textSizeData.zoomRange,f=h.min,p=h.max;u.compositeTextSizes=[c["text-size"].possiblyEvaluate(new t.default$16(f)),c["text-size"].possiblyEvaluate(new t.default$16(p))]}if("composite"===e.iconSizeData.functionType){var d=e.iconSizeData.zoomRange,g=d.min,m=d.max;u.compositeIconSizes=[c["icon-size"].possiblyEvaluate(new t.default$16(g)),c["icon-size"].possiblyEvaluate(new t.default$16(m))]}u.layoutTextSize=c["text-size"].possiblyEvaluate(new t.default$16(e.zoom+1)),u.layoutIconSize=c["icon-size"].possiblyEvaluate(new t.default$16(e.zoom+1)),u.textMaxSize=c["text-size"].possiblyEvaluate(new t.default$16(18));for(var y=24*l.get("text-line-height"),x="map"===l.get("text-rotation-alignment")&&"line"===l.get("symbol-placement"),b=l.get("text-keep-upright"),_=0,w=e.features;_<w.length;_+=1){var k=w[_],A=l.get("text-font").evaluate(k).join(","),M=r[A]||{},T=n[A]||{},S={},E=k.text;if(E){var C=l.get("text-offset").evaluate(k).map(function(t){return 24*t}),L=24*l.get("text-letter-spacing").evaluate(k),z=t.allowsLetterSpacing(E)?L:0,O=l.get("text-anchor").evaluate(k),I=l.get("text-justify").evaluate(k),D="line"!==l.get("symbol-placement")?24*l.get("text-max-width").evaluate(k):0;S.horizontal=t.shapeText(E,M,D,y,O,I,z,C,24,t.WritingMode.horizontal),t.allowsVerticalWritingMode(E)&&x&&b&&(S.vertical=t.shapeText(E,M,D,y,O,I,z,C,24,t.WritingMode.vertical))}var P=void 0;if(k.icon){var R=i[k.icon];R&&(P=t.shapeIcon(a[k.icon],l.get("icon-offset").evaluate(k),l.get("icon-anchor").evaluate(k)),void 0===e.sdfIcons?e.sdfIcons=R.sdf:e.sdfIcons!==R.sdf&&t.warnOnce("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"),R.pixelRatio!==e.pixelRatio?e.iconsNeedLinear=!0:0!==l.get("icon-rotate").constantOr(1)&&(e.iconsNeedLinear=!0))}(S.horizontal||P)&&v(e,k,S,P,T,u)}o&&e.generateCollisionDebugBuffers()}function v(e,r,n,i,l,c){var u=c.layoutTextSize.evaluate(r),h=c.layoutIconSize.evaluate(r),p=c.textMaxSize.evaluate(r);void 0===p&&(p=u);var d=e.layers[0].layout,g=d.get("text-offset").evaluate(r),v=d.get("icon-offset").evaluate(r),x=u/24,b=e.tilePixelRatio*x,_=e.tilePixelRatio*p/24,w=e.tilePixelRatio*h,k=e.tilePixelRatio*d.get("symbol-spacing"),A=d.get("text-padding")*e.tilePixelRatio,M=d.get("icon-padding")*e.tilePixelRatio,T=d.get("text-max-angle")/180*Math.PI,S="map"===d.get("text-rotation-alignment")&&"line"===d.get("symbol-placement"),E="map"===d.get("icon-rotation-alignment")&&"line"===d.get("symbol-placement"),C=k/2,L=function(a,u){u.x<0||u.x>=t.default$8||u.y<0||u.y>=t.default$8||e.symbolInstances.push(function(e,r,n,i,a,l,c,u,h,f,p,d,g,v,y,x,b,_,w,k,A){var M,T,S=e.addToLineVertexArray(r,n),E=0,C=0,L=0,z=i.horizontal?i.horizontal.text:"",O=[];i.horizontal&&(M=new s(c,n,r,u,h,f,i.horizontal,p,d,g,e.overscaling),C+=m(e,r,i.horizontal,l,g,w,v,S,i.vertical?t.WritingMode.horizontal:t.WritingMode.horizontalOnly,O,k,A),i.vertical&&(L+=m(e,r,i.vertical,l,g,w,v,S,t.WritingMode.vertical,O,k,A)));var I=M?M.boxStartIndex:e.collisionBoxArray.length,D=M?M.boxEndIndex:e.collisionBoxArray.length;if(a){var P=function(e,r,n,i,a,o){var s,l,c,u,h=r.image,f=n.layout,p=r.top-1/h.pixelRatio,d=r.left-1/h.pixelRatio,g=r.bottom+1/h.pixelRatio,v=r.right+1/h.pixelRatio;if("none"!==f.get("icon-text-fit")&&a){var m=v-d,y=g-p,x=f.get("text-size").evaluate(o)/24,b=a.left*x,_=a.right*x,w=a.top*x,k=_-b,A=a.bottom*x-w,M=f.get("icon-text-fit-padding")[0],T=f.get("icon-text-fit-padding")[1],S=f.get("icon-text-fit-padding")[2],E=f.get("icon-text-fit-padding")[3],C="width"===f.get("icon-text-fit")?.5*(A-y):0,L="height"===f.get("icon-text-fit")?.5*(k-m):0,z="width"===f.get("icon-text-fit")||"both"===f.get("icon-text-fit")?k:m,O="height"===f.get("icon-text-fit")||"both"===f.get("icon-text-fit")?A:y;s=new t.default$1(b+L-E,w+C-M),l=new t.default$1(b+L+T+z,w+C-M),c=new t.default$1(b+L+T+z,w+C+S+O),u=new t.default$1(b+L-E,w+C+S+O)}else s=new t.default$1(d,p),l=new t.default$1(v,p),c=new t.default$1(v,g),u=new t.default$1(d,g);var I=n.layout.get("icon-rotate").evaluate(o)*Math.PI/180;if(I){var D=Math.sin(I),P=Math.cos(I),R=[P,-D,D,P];s._matMult(R),l._matMult(R),u._matMult(R),c._matMult(R)}return[{tl:s,tr:l,bl:u,br:c,tex:h.paddedRect,writingMode:void 0,glyphOffset:[0,0]}]}(0,a,l,0,i.horizontal,w);T=new s(c,n,r,u,h,f,a,y,x,!1,e.overscaling),E=4*P.length;var R=e.iconSizeData,F=null;"source"===R.functionType?F=[10*l.layout.get("icon-size").evaluate(w)]:"composite"===R.functionType&&(F=[10*A.compositeIconSizes[0].evaluate(w),10*A.compositeIconSizes[1].evaluate(w)]),e.addSymbols(e.icon,P,F,_,b,w,!1,r,S.lineStartIndex,S.lineLength)}var B=T?T.boxStartIndex:e.collisionBoxArray.length,N=T?T.boxEndIndex:e.collisionBoxArray.length;return e.glyphOffsetArray.length>=t.default$14.MAX_GLYPHS&&t.warnOnce("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),{key:z,textBoxStartIndex:I,textBoxEndIndex:D,iconBoxStartIndex:B,iconBoxEndIndex:N,textOffset:v,iconOffset:_,anchor:r,line:n,featureIndex:u,feature:w,numGlyphVertices:C,numVerticalGlyphVertices:L,numIconVertices:E,textOpacityState:new o,iconOpacityState:new o,isDuplicate:!1,placedTextSymbolIndices:O,crossTileID:0}}(e,u,a,n,i,e.layers[0],e.collisionBoxArray,r.index,r.sourceLayerIndex,e.index,b,A,S,g,w,M,E,v,r,l,c))};if("line"===d.get("symbol-placement"))for(var z=0,O=function(e,r,n,i,a){for(var o=[],s=0;s<e.length;s++)for(var l=e[s],c=void 0,u=0;u<l.length-1;u++){var h=l[u],f=l[u+1];h.x<0&&f.x<0||(h.x<0?h=new t.default$1(0,h.y+(f.y-h.y)*((0-h.x)/(f.x-h.x)))._round():f.x<0&&(f=new t.default$1(0,h.y+(f.y-h.y)*((0-h.x)/(f.x-h.x)))._round()),h.y<0&&f.y<0||(h.y<0?h=new t.default$1(h.x+(f.x-h.x)*((0-h.y)/(f.y-h.y)),0)._round():f.y<0&&(f=new t.default$1(h.x+(f.x-h.x)*((0-h.y)/(f.y-h.y)),0)._round()),h.x>=i&&f.x>=i||(h.x>=i?h=new t.default$1(i,h.y+(f.y-h.y)*((i-h.x)/(f.x-h.x)))._round():f.x>=i&&(f=new t.default$1(i,h.y+(f.y-h.y)*((i-h.x)/(f.x-h.x)))._round()),h.y>=a&&f.y>=a||(h.y>=a?h=new t.default$1(h.x+(f.x-h.x)*((a-h.y)/(f.y-h.y)),a)._round():f.y>=a&&(f=new t.default$1(h.x+(f.x-h.x)*((a-h.y)/(f.y-h.y)),a)._round()),c&&h.equals(c[c.length-1])||(c=[h],o.push(c)),c.push(f)))))}return o}(r.geometry,0,0,t.default$8,t.default$8);z<O.length;z+=1)for(var I=O[z],D=0,P=a(I,k,T,n.vertical||n.horizontal,i,24,_,e.overscaling,t.default$8);D<P.length;D+=1){var R=P[D],F=n.horizontal;F&&y(e,F.text,C,R)||L(I,R)}else if("Polygon"===r.type)for(var B=0,N=t.default$26(r.geometry,0);B<N.length;B+=1){var j=N[B],V=f(j,16);L(j[0],new t.default$25(V.x,V.y,0))}else if("LineString"===r.type)for(var U=0,q=r.geometry;U<q.length;U+=1){var H=q[U];L(H,new t.default$25(H[0].x,H[0].y,0))}else if("Point"===r.type)for(var G=0,Y=r.geometry;G<Y.length;G+=1)for(var W=0,X=Y[G];W<X.length;W+=1){var Z=X[W];L([Z],new t.default$25(Z.x,Z.y,0))}}function m(e,r,n,i,a,o,s,l,c,u,h,f){var p=function(e,r,n,i,a,o){for(var s=n.layout.get("text-rotate").evaluate(a)*Math.PI/180,l=n.layout.get("text-offset").evaluate(a).map(function(t){return 24*t}),c=r.positionedGlyphs,u=[],h=0;h<c.length;h++){var f=c[h],p=o[f.glyph];if(p){var d=p.rect;if(d){var g=t.GLYPH_PBF_BORDER+1,v=p.metrics.advance/2,m=i?[f.x+v,f.y]:[0,0],y=i?[0,0]:[f.x+v+l[0],f.y+l[1]],x=p.metrics.left-g-v+y[0],b=-p.metrics.top-g+y[1],_=x+d.w,w=b+d.h,k=new t.default$1(x,b),A=new t.default$1(_,b),M=new t.default$1(x,w),T=new t.default$1(_,w);if(i&&f.vertical){var S=new t.default$1(-v,v),E=-Math.PI/2,C=new t.default$1(5,0);k._rotateAround(E,S)._add(C),A._rotateAround(E,S)._add(C),M._rotateAround(E,S)._add(C),T._rotateAround(E,S)._add(C)}if(s){var L=Math.sin(s),z=Math.cos(s),O=[z,-L,L,z];k._matMult(O),A._matMult(O),M._matMult(O),T._matMult(O)}u.push({tl:k,tr:A,bl:M,br:T,tex:d,writingMode:r.writingMode,glyphOffset:m})}}}return u}(0,n,i,a,o,h),d=e.textSizeData,g=null;return"source"===d.functionType?g=[10*i.layout.get("text-size").evaluate(o)]:"composite"===d.functionType&&(g=[10*f.compositeTextSizes[0].evaluate(o),10*f.compositeTextSizes[1].evaluate(o)]),e.addSymbols(e.text,p,g,s,a,o,c,r,l.lineStartIndex,l.lineLength),u.push(e.text.placedSymbolArray.length-1),4*p.length}function y(t,e,r,n){var i=t.compareText;if(e in i){for(var a=i[e],o=a.length-1;o>=0;o--)if(n.dist(a[o])<r)return!0}else i[e]=[];return i[e].push(n),!1}u.prototype={push:function(t){this.data.push(t),this.length++,this._up(this.length-1)},pop:function(){if(0!==this.length){var t=this.data[0];return this.length--,this.length>0&&(this.data[0]=this.data[this.length],this._down(0)),this.data.pop(),t}},peek:function(){return this.data[0]},_up:function(t){for(var e=this.data,r=this.compare,n=e[t];t>0;){var i=t-1>>1,a=e[i];if(r(n,a)>=0)break;e[t]=a,t=i}e[t]=n},_down:function(t){for(var e=this.data,r=this.compare,n=this.length>>1,i=e[t];t<n;){var a=1+(t<<1),o=a+1,s=e[a];if(o<this.length&&r(e[o],s)<0&&(a=o,s=e[o]),r(s,i)>=0)break;e[t]=s,t=a}e[t]=i}},l.default=c;var x=function(e){var r=new t.AlphaImage({width:0,height:0}),n={},i=new t.default$2(0,0,{autoResize:!0});for(var a in e){var o=e[a],s=n[a]={};for(var l in o){var c=o[+l];if(c&&0!==c.bitmap.width&&0!==c.bitmap.height){var u=i.packOne(c.bitmap.width+2,c.bitmap.height+2);r.resize({width:i.w,height:i.h}),t.AlphaImage.copy(c.bitmap,r,{x:0,y:0},{x:u.x+1,y:u.y+1},c.bitmap),s[l]={rect:u,metrics:c.metrics}}}}i.shrink(),r.resize({width:i.w,height:i.h}),this.image=r,this.positions=n};t.register("GlyphAtlas",x);var b=function(e){this.tileID=new t.OverscaledTileID(e.tileID.overscaledZ,e.tileID.wrap,e.tileID.canonical.z,e.tileID.canonical.x,e.tileID.canonical.y),this.uid=e.uid,this.zoom=e.zoom,this.pixelRatio=e.pixelRatio,this.tileSize=e.tileSize,this.source=e.source,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=e.showCollisionBoxes,this.collectResourceTiming=!!e.collectResourceTiming};function _(e,r){for(var n=new t.default$16(r),i=0,a=e;i<a.length;i+=1)a[i].recalculate(n)}b.prototype.parse=function(e,r,n,i){var a=this;this.status="parsing",this.data=e,this.collisionBoxArray=new t.CollisionBoxArray;var o=new t.default$27(Object.keys(e.layers).sort()),s=new t.default$11(this.tileID);s.bucketLayerIDs=[];var l,c,u,h={},f={featureIndex:s,iconDependencies:{},glyphDependencies:{}},p=r.familiesBySource[this.source];for(var d in p){var v=e.layers[d];if(v){1===v.version&&t.warnOnce('Vector tile source "'+a.source+'" layer "'+d+'" does not use vector tile spec v2 and therefore may have some rendering errors.');for(var m=o.encode(d),y=[],b=0;b<v.length;b++){var w=v.feature(b);y.push({feature:w,index:b,sourceLayerIndex:m})}for(var k=0,A=p[d];k<A.length;k+=1){var M=A[k],T=M[0];T.minzoom&&a.zoom<Math.floor(T.minzoom)||T.maxzoom&&a.zoom>=T.maxzoom||"none"!==T.visibility&&(_(M,a.zoom),(h[T.id]=T.createBucket({index:s.bucketLayerIDs.length,layers:M,zoom:a.zoom,pixelRatio:a.pixelRatio,overscaling:a.overscaling,collisionBoxArray:a.collisionBoxArray,sourceLayerIndex:m})).populate(y,f),s.bucketLayerIDs.push(M.map(function(t){return t.id})))}}}var S=t.mapObject(f.glyphDependencies,function(t){return Object.keys(t).map(Number)});Object.keys(S).length?n.send("getGlyphs",{uid:this.uid,stacks:S},function(t,e){l||(l=t,c=e,C.call(a))}):c={};var E=Object.keys(f.iconDependencies);function C(){if(l)return i(l);if(c&&u){var e=new x(c),r=new t.default$28(u);for(var n in h){var a=h[n];a instanceof t.default$14&&(_(a.layers,this.zoom),g(a,c,e.positions,u,r.positions,this.showCollisionBoxes))}this.status="done",i(null,{buckets:t.values(h).filter(function(t){return!t.isEmpty()}),featureIndex:s,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:e.image,iconAtlasImage:r.image})}}E.length?n.send("getImages",{icons:E},function(t,e){l||(l=t,u=e,C.call(a))}):u={},C.call(this)};var w=function(t){return!(!performance||!performance.getEntriesByName)&&performance.getEntriesByName(t)};function k(e,r){var n=t.getArrayBuffer(e.request,function(e,n){e?r(e):n&&r(null,{vectorTile:new t.default$29.VectorTile(new t.default$30(n.data)),rawData:n.data,cacheControl:n.cacheControl,expires:n.expires})});return function(){n.abort(),r()}}var A=function(t,e,r){this.actor=t,this.layerIndex=e,this.loadVectorData=r||k,this.loading={},this.loaded={}};A.prototype.loadTile=function(e,r){var n=this,i=e.uid;this.loading||(this.loading={});var a=this.loading[i]=new b(e);a.abort=this.loadVectorData(e,function(o,s){if(delete n.loading[i],o||!s)return r(o);var l=s.rawData,c={};s.expires&&(c.expires=s.expires),s.cacheControl&&(c.cacheControl=s.cacheControl);var u={};if(e.request&&e.request.collectResourceTiming){var h=w(e.request.url);h&&(u.resourceTiming=JSON.parse(JSON.stringify(h)))}a.vectorTile=s.vectorTile,a.parse(s.vectorTile,n.layerIndex,n.actor,function(e,n){if(e||!n)return r(e);r(null,t.extend({rawTileData:l.slice(0)},n,c,u))}),n.loaded=n.loaded||{},n.loaded[i]=a})},A.prototype.reloadTile=function(t,e){var r=this.loaded,n=t.uid,i=this;if(r&&r[n]){var a=r[n];a.showCollisionBoxes=t.showCollisionBoxes;var o=function(t,r){var n=a.reloadCallback;n&&(delete a.reloadCallback,a.parse(a.vectorTile,i.layerIndex,i.actor,n)),e(t,r)};"parsing"===a.status?a.reloadCallback=o:"done"===a.status&&a.parse(a.vectorTile,this.layerIndex,this.actor,o)}},A.prototype.abortTile=function(t,e){var r=this.loading,n=t.uid;r&&r[n]&&r[n].abort&&(r[n].abort(),delete r[n]),e()},A.prototype.removeTile=function(t,e){var r=this.loaded,n=t.uid;r&&r[n]&&delete r[n],e()};var M=function(){this.loading={},this.loaded={}};M.prototype.loadTile=function(e,r){var n=e.uid,i=e.encoding,a=new t.default$31(n);this.loading[n]=a,a.loadFromImage(e.rawImageData,i),delete this.loading[n],this.loaded=this.loaded||{},this.loaded[n]=a,r(null,a)},M.prototype.removeTile=function(t){var e=this.loaded,r=t.uid;e&&e[r]&&delete e[r]};var T={RADIUS:6378137,FLATTENING:1/298.257223563,POLAR_RADIUS:6356752.3142};function S(t){var e=0;if(t&&t.length>0){e+=Math.abs(E(t[0]));for(var r=1;r<t.length;r++)e-=Math.abs(E(t[r]))}return e}function E(t){var e,r,n,i,a,o,s=0,l=t.length;if(l>2){for(o=0;o<l;o++)o===l-2?(n=l-2,i=l-1,a=0):o===l-1?(n=l-1,i=0,a=1):(n=o,i=o+1,a=o+2),e=t[n],r=t[i],s+=(C(t[a][0])-C(e[0]))*Math.sin(C(r[1]));s=s*T.RADIUS*T.RADIUS/2}return s}function C(t){return t*Math.PI/180}var L={geometry:function t(e){var r,n=0;switch(e.type){case"Polygon":return S(e.coordinates);case"MultiPolygon":for(r=0;r<e.coordinates.length;r++)n+=S(e.coordinates[r]);return n;case"Point":case"MultiPoint":case"LineString":case"MultiLineString":return 0;case"GeometryCollection":for(r=0;r<e.geometries.length;r++)n+=t(e.geometries[r]);return n}},ring:E};function z(t,e){return function(r){return t(r,e)}}function O(t,e){e=!!e,t[0]=I(t[0],e);for(var r=1;r<t.length;r++)t[r]=I(t[r],!e);return t}function I(t,e){return function(t){return L.ring(t)>=0}(t)===e?t:t.reverse()}var D=t.default$29.VectorTileFeature.prototype.toGeoJSON,P=function(e){this._feature=e,this.extent=t.default$8,this.type=e.type,this.properties=e.tags,"id"in e&&!isNaN(e.id)&&(this.id=parseInt(e.id,10))};P.prototype.loadGeometry=function(){if(1===this._feature.type){for(var e=[],r=0,n=this._feature.geometry;r<n.length;r+=1){var i=n[r];e.push([new t.default$1(i[0],i[1])])}return e}for(var a=[],o=0,s=this._feature.geometry;o<s.length;o+=1){for(var l=[],c=0,u=s[o];c<u.length;c+=1){var h=u[c];l.push(new t.default$1(h[0],h[1]))}a.push(l)}return a},P.prototype.toGeoJSON=function(t,e,r){return D.call(this,t,e,r)};var R=function(e){this.layers={_geojsonTileLayer:this},this.name="_geojsonTileLayer",this.extent=t.default$8,this.length=e.length,this._features=e};R.prototype.feature=function(t){return new P(this._features[t])};var F=t.__moduleExports.VectorTileFeature,B=N;function N(t,e){this.options=e||{},this.features=t,this.length=t.length}function j(t,e){this.id="number"==typeof t.id?t.id:void 0,this.type=t.type,this.rawGeometry=1===t.type?[t.geometry]:t.geometry,this.properties=t.tags,this.extent=e||4096}N.prototype.feature=function(t){return new j(this.features[t],this.options.extent)},j.prototype.loadGeometry=function(){var e=this.rawGeometry;this.geometry=[];for(var r=0;r<e.length;r++){for(var n=e[r],i=[],a=0;a<n.length;a++)i.push(new t.default$32(n[a][0],n[a][1]));this.geometry.push(i)}return this.geometry},j.prototype.bbox=function(){this.geometry||this.loadGeometry();for(var t=this.geometry,e=1/0,r=-1/0,n=1/0,i=-1/0,a=0;a<t.length;a++)for(var o=t[a],s=0;s<o.length;s++){var l=o[s];e=Math.min(e,l.x),r=Math.max(r,l.x),n=Math.min(n,l.y),i=Math.max(i,l.y)}return[e,n,r,i]},j.prototype.toGeoJSON=F.prototype.toGeoJSON;var V=H,U=H,q=B;function H(e){var r=new t.__moduleExports$1;return function(t,e){for(var r in t.layers)e.writeMessage(3,G,t.layers[r])}(e,r),r.finish()}function G(t,e){var r;e.writeVarintField(15,t.version||1),e.writeStringField(1,t.name||""),e.writeVarintField(5,t.extent||4096);var n={keys:[],values:[],keycache:{},valuecache:{}};for(r=0;r<t.length;r++)n.feature=t.feature(r),e.writeMessage(2,Y,n);var i=n.keys;for(r=0;r<i.length;r++)e.writeStringField(3,i[r]);var a=n.values;for(r=0;r<a.length;r++)e.writeMessage(4,J,a[r])}function Y(t,e){var r=t.feature;void 0!==r.id&&e.writeVarintField(1,r.id),e.writeMessage(2,W,t),e.writeVarintField(3,r.type),e.writeMessage(4,$,r)}function W(t,e){var r=t.feature,n=t.keys,i=t.values,a=t.keycache,o=t.valuecache;for(var s in r.properties){var l=a[s];void 0===l&&(n.push(s),l=n.length-1,a[s]=l),e.writeVarint(l);var c=r.properties[s],u=typeof c;"string"!==u&&"boolean"!==u&&"number"!==u&&(c=JSON.stringify(c));var h=u+":"+c,f=o[h];void 0===f&&(i.push(c),f=i.length-1,o[h]=f),e.writeVarint(f)}}function X(t,e){return(e<<3)+(7&t)}function Z(t){return t<<1^t>>31}function $(t,e){for(var r=t.loadGeometry(),n=t.type,i=0,a=0,o=r.length,s=0;s<o;s++){var l=r[s],c=1;1===n&&(c=l.length),e.writeVarint(X(1,c));for(var u=3===n?l.length-1:l.length,h=0;h<u;h++){1===h&&1!==n&&e.writeVarint(X(2,u-1));var f=l[h].x-i,p=l[h].y-a;e.writeVarint(Z(f)),e.writeVarint(Z(p)),i+=f,a+=p}3===n&&e.writeVarint(X(7,0))}}function J(t,e){var r=typeof t;"string"===r?e.writeStringField(1,t):"boolean"===r?e.writeBooleanField(7,t):"number"===r&&(t%1!=0?e.writeDoubleField(3,t):t<0?e.writeSVarintField(6,t):e.writeVarintField(5,t))}V.fromVectorTileJs=U,V.fromGeojsonVt=function(t,e){e=e||{};var r={};for(var n in t)r[n]=new B(t[n].features,e),r[n].name=n,r[n].version=e.version,r[n].extent=e.extent;return H({layers:r})},V.GeoJSONWrapper=q;var K=function t(e,r,n,i,a,o){if(!(a-i<=n)){var s=Math.floor((i+a)/2);!function t(e,r,n,i,a,o){for(;a>i;){if(a-i>600){var s=a-i+1,l=n-i+1,c=Math.log(s),u=.5*Math.exp(2*c/3),h=.5*Math.sqrt(c*u*(s-u)/s)*(l-s/2<0?-1:1);t(e,r,n,Math.max(i,Math.floor(n-l*u/s+h)),Math.min(a,Math.floor(n+(s-l)*u/s+h)),o)}var f=r[2*n+o],p=i,d=a;for(Q(e,r,i,n),r[2*a+o]>f&&Q(e,r,i,a);p<d;){for(Q(e,r,p,d),p++,d--;r[2*p+o]<f;)p++;for(;r[2*d+o]>f;)d--}r[2*i+o]===f?Q(e,r,i,d):Q(e,r,++d,a),d<=n&&(i=d+1),n<=d&&(a=d-1)}}(e,r,s,i,a,o%2),t(e,r,n,i,s-1,o+1),t(e,r,n,s+1,a,o+1)}};function Q(t,e,r,n){tt(t,r,n),tt(e,2*r,2*n),tt(e,2*r+1,2*n+1)}function tt(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function et(t,e,r,n){var i=t-r,a=e-n;return i*i+a*a}var rt=function(t,e,r,n,i){return new nt(t,e,r,n,i)};function nt(t,e,r,n,i){e=e||it,r=r||at,i=i||Array,this.nodeSize=n||64,this.points=t,this.ids=new i(t.length),this.coords=new i(2*t.length);for(var a=0;a<t.length;a++)this.ids[a]=a,this.coords[2*a]=e(t[a]),this.coords[2*a+1]=r(t[a]);K(this.ids,this.coords,this.nodeSize,0,this.ids.length-1,0)}function it(t){return t[0]}function at(t){return t[1]}nt.prototype={range:function(t,e,r,n){return function(t,e,r,n,i,a,o){for(var s,l,c=[0,t.length-1,0],u=[];c.length;){var h=c.pop(),f=c.pop(),p=c.pop();if(f-p<=o)for(var d=p;d<=f;d++)s=e[2*d],l=e[2*d+1],s>=r&&s<=i&&l>=n&&l<=a&&u.push(t[d]);else{var g=Math.floor((p+f)/2);s=e[2*g],l=e[2*g+1],s>=r&&s<=i&&l>=n&&l<=a&&u.push(t[g]);var v=(h+1)%2;(0===h?r<=s:n<=l)&&(c.push(p),c.push(g-1),c.push(v)),(0===h?i>=s:a>=l)&&(c.push(g+1),c.push(f),c.push(v))}}return u}(this.ids,this.coords,t,e,r,n,this.nodeSize)},within:function(t,e,r){return function(t,e,r,n,i,a){for(var o=[0,t.length-1,0],s=[],l=i*i;o.length;){var c=o.pop(),u=o.pop(),h=o.pop();if(u-h<=a)for(var f=h;f<=u;f++)et(e[2*f],e[2*f+1],r,n)<=l&&s.push(t[f]);else{var p=Math.floor((h+u)/2),d=e[2*p],g=e[2*p+1];et(d,g,r,n)<=l&&s.push(t[p]);var v=(c+1)%2;(0===c?r-i<=d:n-i<=g)&&(o.push(h),o.push(p-1),o.push(v)),(0===c?r+i>=d:n+i>=g)&&(o.push(p+1),o.push(u),o.push(v))}}return s}(this.ids,this.coords,t,e,r,this.nodeSize)}};function ot(t){this.options=pt(Object.create(this.options),t),this.trees=new Array(this.options.maxZoom+1)}function st(t,e,r,n,i){return{x:t,y:e,zoom:1/0,id:n,properties:i,parentId:-1,numPoints:r}}function lt(t,e){var r=t.geometry.coordinates;return{x:ht(r[0]),y:ft(r[1]),zoom:1/0,id:e,parentId:-1}}function ct(t){return{type:"Feature",properties:ut(t),geometry:{type:"Point",coordinates:[(n=t.x,360*(n-.5)),(e=t.y,r=(180-360*e)*Math.PI/180,360*Math.atan(Math.exp(r))/Math.PI-90)]}};var e,r,n}function ut(t){var e=t.numPoints,r=e>=1e4?Math.round(e/1e3)+"k":e>=1e3?Math.round(e/100)/10+"k":e;return pt(pt({},t.properties),{cluster:!0,cluster_id:t.id,point_count:e,point_count_abbreviated:r})}function ht(t){return t/360+.5}function ft(t){var e=Math.sin(t*Math.PI/180),r=.5-.25*Math.log((1+e)/(1-e))/Math.PI;return r<0?0:r>1?1:r}function pt(t,e){for(var r in e)t[r]=e[r];return t}function dt(t){return t.x}function gt(t){return t.y}function vt(t,e,r,n,i,a){var o=i-r,s=a-n;if(0!==o||0!==s){var l=((t-r)*o+(e-n)*s)/(o*o+s*s);l>1?(r=i,n=a):l>0&&(r+=o*l,n+=s*l)}return(o=t-r)*o+(s=e-n)*s}function mt(t,e,r,n){var i={id:t||null,type:e,geometry:r,tags:n,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};return function(t){var e=t.geometry,r=t.type;if("Point"===r||"MultiPoint"===r||"LineString"===r)yt(t,e);else if("Polygon"===r||"MultiLineString"===r)for(var n=0;n<e.length;n++)yt(t,e[n]);else if("MultiPolygon"===r)for(n=0;n<e.length;n++)for(var i=0;i<e[n].length;i++)yt(t,e[n][i])}(i),i}function yt(t,e){for(var r=0;r<e.length;r+=3)t.minX=Math.min(t.minX,e[r]),t.minY=Math.min(t.minY,e[r+1]),t.maxX=Math.max(t.maxX,e[r]),t.maxY=Math.max(t.maxY,e[r+1])}function xt(t,e,r){if(e.geometry){var n=e.geometry.coordinates,i=e.geometry.type,a=Math.pow(r.tolerance/((1<<r.maxZoom)*r.extent),2),o=[];if("Point"===i)bt(n,o);else if("MultiPoint"===i)for(var s=0;s<n.length;s++)bt(n[s],o);else if("LineString"===i)_t(n,o,a,!1);else if("MultiLineString"===i)if(r.lineMetrics)for(s=0;s<n.length;s++)return o=[],_t(n[s],o,a,!1),void t.push(mt(e.id,"LineString",o,e.properties));else wt(n,o,a,!1);else if("Polygon"===i)wt(n,o,a,!0);else{if("MultiPolygon"!==i){if("GeometryCollection"===i){for(s=0;s<e.geometry.geometries.length;s++)xt(t,{id:e.id,geometry:e.geometry.geometries[s],properties:e.properties},r);return}throw new Error("Input data is not a valid GeoJSON object.")}for(s=0;s<n.length;s++){var l=[];wt(n[s],l,a,!0),o.push(l)}}t.push(mt(e.id,i,o,e.properties))}}function bt(t,e){e.push(kt(t[0])),e.push(At(t[1])),e.push(0)}function _t(t,e,r,n){for(var i,a,o=0,s=0;s<t.length;s++){var l=kt(t[s][0]),c=At(t[s][1]);e.push(l),e.push(c),e.push(0),s>0&&(o+=n?(i*c-l*a)/2:Math.sqrt(Math.pow(l-i,2)+Math.pow(c-a,2))),i=l,a=c}var u=e.length-3;e[2]=1,function t(e,r,n,i){for(var a,o=i,s=e[r],l=e[r+1],c=e[n],u=e[n+1],h=r+3;h<n;h+=3){var f=vt(e[h],e[h+1],s,l,c,u);f>o&&(a=h,o=f)}o>i&&(a-r>3&&t(e,r,a,i),e[a+2]=o,n-a>3&&t(e,a,n,i))}(e,0,u,r),e[u+2]=1,e.size=Math.abs(o),e.start=0,e.end=e.size}function wt(t,e,r,n){for(var i=0;i<t.length;i++){var a=[];_t(t[i],a,r,n),e.push(a)}}function kt(t){return t/360+.5}function At(t){var e=Math.sin(t*Math.PI/180),r=.5-.25*Math.log((1+e)/(1-e))/Math.PI;return r<0?0:r>1?1:r}function Mt(t,e,r,n,i,a,o,s){if(n/=e,a>=(r/=e)&&o<=n)return t;if(a>n||o<r)return null;for(var l=[],c=0;c<t.length;c++){var u=t[c],h=u.geometry,f=u.type,p=0===i?u.minX:u.minY,d=0===i?u.maxX:u.maxY;if(p>=r&&d<=n)l.push(u);else if(!(p>n||d<r)){var g=[];if("Point"===f||"MultiPoint"===f)Tt(h,g,r,n,i);else if("LineString"===f)St(h,g,r,n,i,!1,s.lineMetrics);else if("MultiLineString"===f)Ct(h,g,r,n,i,!1);else if("Polygon"===f)Ct(h,g,r,n,i,!0);else if("MultiPolygon"===f)for(var v=0;v<h.length;v++){var m=[];Ct(h[v],m,r,n,i,!0),m.length&&g.push(m)}if(g.length){if(s.lineMetrics&&"LineString"===f){for(v=0;v<g.length;v++)l.push(mt(u.id,f,g[v],u.tags));continue}"LineString"!==f&&"MultiLineString"!==f||(1===g.length?(f="LineString",g=g[0]):f="MultiLineString"),"Point"!==f&&"MultiPoint"!==f||(f=3===g.length?"Point":"MultiPoint"),l.push(mt(u.id,f,g,u.tags))}}}return l.length?l:null}function Tt(t,e,r,n,i){for(var a=0;a<t.length;a+=3){var o=t[a+i];o>=r&&o<=n&&(e.push(t[a]),e.push(t[a+1]),e.push(t[a+2]))}}function St(t,e,r,n,i,a,o){for(var s,l,c=Et(t),u=0===i?zt:Ot,h=t.start,f=0;f<t.length-3;f+=3){var p=t[f],d=t[f+1],g=t[f+2],v=t[f+3],m=t[f+4],y=0===i?p:d,x=0===i?v:m,b=!1;o&&(s=Math.sqrt(Math.pow(p-v,2)+Math.pow(d-m,2))),y<r?x>=r&&(l=u(c,p,d,v,m,r),o&&(c.start=h+s*l)):y>n?x<=n&&(l=u(c,p,d,v,m,n),o&&(c.start=h+s*l)):Lt(c,p,d,g),x<r&&y>=r&&(l=u(c,p,d,v,m,r),b=!0),x>n&&y<=n&&(l=u(c,p,d,v,m,n),b=!0),!a&&b&&(o&&(c.end=h+s*l),e.push(c),c=Et(t)),o&&(h+=s)}var _=t.length-3;p=t[_],d=t[_+1],g=t[_+2],(y=0===i?p:d)>=r&&y<=n&&Lt(c,p,d,g),_=c.length-3,a&&_>=3&&(c[_]!==c[0]||c[_+1]!==c[1])&&Lt(c,c[0],c[1],c[2]),c.length&&e.push(c)}function Et(t){var e=[];return e.size=t.size,e.start=t.start,e.end=t.end,e}function Ct(t,e,r,n,i,a){for(var o=0;o<t.length;o++)St(t[o],e,r,n,i,a,!1)}function Lt(t,e,r,n){t.push(e),t.push(r),t.push(n)}function zt(t,e,r,n,i,a){var o=(a-e)/(n-e);return t.push(a),t.push(r+(i-r)*o),t.push(1),o}function Ot(t,e,r,n,i,a){var o=(a-r)/(i-r);return t.push(e+(n-e)*o),t.push(a),t.push(1),o}function It(t,e){for(var r=[],n=0;n<t.length;n++){var i,a=t[n],o=a.type;if("Point"===o||"MultiPoint"===o||"LineString"===o)i=Dt(a.geometry,e);else if("MultiLineString"===o||"Polygon"===o){i=[];for(var s=0;s<a.geometry.length;s++)i.push(Dt(a.geometry[s],e))}else if("MultiPolygon"===o)for(i=[],s=0;s<a.geometry.length;s++){for(var l=[],c=0;c<a.geometry[s].length;c++)l.push(Dt(a.geometry[s][c],e));i.push(l)}r.push(mt(a.id,o,i,a.tags))}return r}function Dt(t,e){var r=[];r.size=t.size,void 0!==t.start&&(r.start=t.start,r.end=t.end);for(var n=0;n<t.length;n+=3)r.push(t[n]+e,t[n+1],t[n+2]);return r}function Pt(t,e){if(t.transformed)return t;var r,n,i,a=1<<t.z,o=t.x,s=t.y;for(r=0;r<t.features.length;r++){var l=t.features[r],c=l.geometry,u=l.type;if(l.geometry=[],1===u)for(n=0;n<c.length;n+=2)l.geometry.push(Rt(c[n],c[n+1],e,a,o,s));else for(n=0;n<c.length;n++){var h=[];for(i=0;i<c[n].length;i+=2)h.push(Rt(c[n][i],c[n][i+1],e,a,o,s));l.geometry.push(h)}}return t.transformed=!0,t}function Rt(t,e,r,n,i,a){return[Math.round(r*(t*n-i)),Math.round(r*(e*n-a))]}function Ft(t,e,r,n,i){for(var a=e===i.maxZoom?0:i.tolerance/((1<<e)*i.extent),o={features:[],numPoints:0,numSimplified:0,numFeatures:0,source:null,x:r,y:n,z:e,transformed:!1,minX:2,minY:1,maxX:-1,maxY:0},s=0;s<t.length;s++){o.numFeatures++,Bt(o,t[s],a,i);var l=t[s].minX,c=t[s].minY,u=t[s].maxX,h=t[s].maxY;l<o.minX&&(o.minX=l),c<o.minY&&(o.minY=c),u>o.maxX&&(o.maxX=u),h>o.maxY&&(o.maxY=h)}return o}function Bt(t,e,r,n){var i=e.geometry,a=e.type,o=[];if("Point"===a||"MultiPoint"===a)for(var s=0;s<i.length;s+=3)o.push(i[s]),o.push(i[s+1]),t.numPoints++,t.numSimplified++;else if("LineString"===a)Nt(o,i,t,r,!1,!1);else if("MultiLineString"===a||"Polygon"===a)for(s=0;s<i.length;s++)Nt(o,i[s],t,r,"Polygon"===a,0===s);else if("MultiPolygon"===a)for(var l=0;l<i.length;l++){var c=i[l];for(s=0;s<c.length;s++)Nt(o,c[s],t,r,!0,0===s)}if(o.length){var u=e.tags||null;if("LineString"===a&&n.lineMetrics){for(var h in u={},e.tags)u[h]=e.tags[h];u.mapbox_clip_start=i.start/i.size,u.mapbox_clip_end=i.end/i.size}var f={geometry:o,type:"Polygon"===a||"MultiPolygon"===a?3:"LineString"===a||"MultiLineString"===a?2:1,tags:u};null!==e.id&&(f.id=e.id),t.features.push(f)}}function Nt(t,e,r,n,i,a){var o=n*n;if(n>0&&e.size<(i?o:n))r.numPoints+=e.length/3;else{for(var s=[],l=0;l<e.length;l+=3)(0===n||e[l+2]>o)&&(r.numSimplified++,s.push(e[l]),s.push(e[l+1])),r.numPoints++;i&&function(t,e){for(var r=0,n=0,i=t.length,a=i-2;n<i;a=n,n+=2)r+=(t[n]-t[a])*(t[n+1]+t[a+1]);if(r>0===e)for(n=0,i=t.length;n<i/2;n+=2){var o=t[n],s=t[n+1];t[n]=t[i-2-n],t[n+1]=t[i-1-n],t[i-2-n]=o,t[i-1-n]=s}}(s,a),t.push(s)}}function jt(t,e){var r=(e=this.options=function(t,e){for(var r in e)t[r]=e[r];return t}(Object.create(this.options),e)).debug;if(r&&console.time("preprocess data"),e.maxZoom<0||e.maxZoom>24)throw new Error("maxZoom should be in the 0-24 range");var n=function(t,e){var r=[];if("FeatureCollection"===t.type)for(var n=0;n<t.features.length;n++)xt(r,t.features[n],e);else"Feature"===t.type?xt(r,t,e):xt(r,{geometry:t},e);return r}(t,e);this.tiles={},this.tileCoords=[],r&&(console.timeEnd("preprocess data"),console.log("index: maxZoom: %d, maxPoints: %d",e.indexMaxZoom,e.indexMaxPoints),console.time("generate tiles"),this.stats={},this.total=0),(n=function(t,e){var r=e.buffer/e.extent,n=t,i=Mt(t,1,-1-r,r,0,-1,2,e),a=Mt(t,1,1-r,2+r,0,-1,2,e);return(i||a)&&(n=Mt(t,1,-r,1+r,0,-1,2,e)||[],i&&(n=It(i,1).concat(n)),a&&(n=n.concat(It(a,-1)))),n}(n,e)).length&&this.splitTile(n,0,0,0),r&&(n.length&&console.log("features: %d, points: %d",this.tiles[0].numFeatures,this.tiles[0].numPoints),console.timeEnd("generate tiles"),console.log("tiles generated:",this.total,JSON.stringify(this.stats)))}function Vt(t,e,r){return 32*((1<<t)*r+e)+t}function Ut(t,e){var r=t.tileID.canonical;if(!this._geoJSONIndex)return e(null,null);var n=this._geoJSONIndex.getTile(r.z,r.x,r.y);if(!n)return e(null,null);var i=new R(n.features),a=V(i);0===a.byteOffset&&a.byteLength===a.buffer.byteLength||(a=new Uint8Array(a)),e(null,{vectorTile:i,rawData:a.buffer})}ot.prototype={options:{minZoom:0,maxZoom:16,radius:40,extent:512,nodeSize:64,log:!1,reduce:null,initial:function(){return{}},map:function(t){return t}},load:function(t){var e=this.options.log;e&&console.time("total time");var r="prepare "+t.length+" points";e&&console.time(r),this.points=t;var n=t.map(lt);e&&console.timeEnd(r);for(var i=this.options.maxZoom;i>=this.options.minZoom;i--){var a=+Date.now();this.trees[i+1]=rt(n,dt,gt,this.options.nodeSize,Float32Array),n=this._cluster(n,i),e&&console.log("z%d: %d clusters in %dms",i,n.length,+Date.now()-a)}return this.trees[this.options.minZoom]=rt(n,dt,gt,this.options.nodeSize,Float32Array),e&&console.timeEnd("total time"),this},getClusters:function(t,e){for(var r=this.trees[this._limitZoom(e)],n=r.range(ht(t[0]),ft(t[3]),ht(t[2]),ft(t[1])),i=[],a=0;a<n.length;a++){var o=r.points[n[a]];i.push(o.numPoints?ct(o):this.points[o.id])}return i},getChildren:function(t,e){for(var r=this.trees[e+1].points[t],n=this.options.radius/(this.options.extent*Math.pow(2,e)),i=this.trees[e+1].within(r.x,r.y,n),a=[],o=0;o<i.length;o++){var s=this.trees[e+1].points[i[o]];s.parentId===t&&a.push(s.numPoints?ct(s):this.points[s.id])}return a},getLeaves:function(t,e,r,n){r=r||10,n=n||0;var i=[];return this._appendLeaves(i,t,e,r,n,0),i},getTile:function(t,e,r){var n=this.trees[this._limitZoom(t)],i=Math.pow(2,t),a=this.options.extent,o=this.options.radius/a,s=(r-o)/i,l=(r+1+o)/i,c={features:[]};return this._addTileFeatures(n.range((e-o)/i,s,(e+1+o)/i,l),n.points,e,r,i,c),0===e&&this._addTileFeatures(n.range(1-o/i,s,1,l),n.points,i,r,i,c),e===i-1&&this._addTileFeatures(n.range(0,s,o/i,l),n.points,-1,r,i,c),c.features.length?c:null},getClusterExpansionZoom:function(t,e){for(;e<this.options.maxZoom;){var r=this.getChildren(t,e);if(e++,1!==r.length)break;t=r[0].properties.cluster_id}return e},_appendLeaves:function(t,e,r,n,i,a){for(var o=this.getChildren(e,r),s=0;s<o.length;s++){var l=o[s].properties;if(l.cluster?a+l.point_count<=i?a+=l.point_count:a=this._appendLeaves(t,l.cluster_id,r+1,n,i,a):a<i?a++:t.push(o[s]),t.length===n)break}return a},_addTileFeatures:function(t,e,r,n,i,a){for(var o=0;o<t.length;o++){var s=e[t[o]];a.features.push({type:1,geometry:[[Math.round(this.options.extent*(s.x*i-r)),Math.round(this.options.extent*(s.y*i-n))]],tags:s.numPoints?ut(s):this.points[s.id].properties})}},_limitZoom:function(t){return Math.max(this.options.minZoom,Math.min(t,this.options.maxZoom+1))},_cluster:function(t,e){for(var r=[],n=this.options.radius/(this.options.extent*Math.pow(2,e)),i=0;i<t.length;i++){var a=t[i];if(!(a.zoom<=e)){a.zoom=e;var o=this.trees[e+1],s=o.within(a.x,a.y,n),l=a.numPoints||1,c=a.x*l,u=a.y*l,h=null;this.options.reduce&&(h=this.options.initial(),this._accumulate(h,a));for(var f=0;f<s.length;f++){var p=o.points[s[f]];if(e<p.zoom){var d=p.numPoints||1;p.zoom=e,c+=p.x*d,u+=p.y*d,l+=d,p.parentId=i,this.options.reduce&&this._accumulate(h,p)}}1===l?r.push(a):(a.parentId=i,r.push(st(c/l,u/l,l,i,h)))}}return r},_accumulate:function(t,e){var r=e.numPoints?e.properties:this.options.map(this.points[e.id].properties);this.options.reduce(t,r)}},jt.prototype.options={maxZoom:14,indexMaxZoom:5,indexMaxPoints:1e5,tolerance:3,extent:4096,buffer:64,lineMetrics:!1,debug:0},jt.prototype.splitTile=function(t,e,r,n,i,a,o){for(var s=[t,e,r,n],l=this.options,c=l.debug;s.length;){n=s.pop(),r=s.pop(),e=s.pop(),t=s.pop();var u=1<<e,h=Vt(e,r,n),f=this.tiles[h];if(!f&&(c>1&&console.time("creation"),f=this.tiles[h]=Ft(t,e,r,n,l),this.tileCoords.push({z:e,x:r,y:n}),c)){c>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",e,r,n,f.numFeatures,f.numPoints,f.numSimplified),console.timeEnd("creation"));var p="z"+e;this.stats[p]=(this.stats[p]||0)+1,this.total++}if(f.source=t,i){if(e===l.maxZoom||e===i)continue;var d=1<<i-e;if(r!==Math.floor(a/d)||n!==Math.floor(o/d))continue}else if(e===l.indexMaxZoom||f.numPoints<=l.indexMaxPoints)continue;if(f.source=null,0!==t.length){c>1&&console.time("clipping");var g,v,m,y,x,b,_=.5*l.buffer/l.extent,w=.5-_,k=.5+_,A=1+_;g=v=m=y=null,x=Mt(t,u,r-_,r+k,0,f.minX,f.maxX,l),b=Mt(t,u,r+w,r+A,0,f.minX,f.maxX,l),t=null,x&&(g=Mt(x,u,n-_,n+k,1,f.minY,f.maxY,l),v=Mt(x,u,n+w,n+A,1,f.minY,f.maxY,l),x=null),b&&(m=Mt(b,u,n-_,n+k,1,f.minY,f.maxY,l),y=Mt(b,u,n+w,n+A,1,f.minY,f.maxY,l),b=null),c>1&&console.timeEnd("clipping"),s.push(g||[],e+1,2*r,2*n),s.push(v||[],e+1,2*r,2*n+1),s.push(m||[],e+1,2*r+1,2*n),s.push(y||[],e+1,2*r+1,2*n+1)}}},jt.prototype.getTile=function(t,e,r){var n=this.options,i=n.extent,a=n.debug;if(t<0||t>24)return null;var o=1<<t,s=Vt(t,e=(e%o+o)%o,r);if(this.tiles[s])return Pt(this.tiles[s],i);a>1&&console.log("drilling down to z%d-%d-%d",t,e,r);for(var l,c=t,u=e,h=r;!l&&c>0;)c--,u=Math.floor(u/2),h=Math.floor(h/2),l=this.tiles[Vt(c,u,h)];return l&&l.source?(a>1&&console.log("found parent tile z%d-%d-%d",c,u,h),a>1&&console.time("drilling down"),this.splitTile(l.source,c,u,h,t,e,r),a>1&&console.timeEnd("drilling down"),this.tiles[s]?Pt(this.tiles[s],i):null):null};var qt=function(e){function r(t,r,n){e.call(this,t,r,Ut),n&&(this.loadGeoJSON=n)}return e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r,r.prototype.loadData=function(t,e){this._pendingCallback&&this._pendingCallback(null,{abandoned:!0}),this._pendingCallback=e,this._pendingLoadDataParams=t,this._state&&"Idle"!==this._state?this._state="NeedsLoadData":(this._state="Coalescing",this._loadData())},r.prototype._loadData=function(){var t=this;if(this._pendingCallback&&this._pendingLoadDataParams){var e=this._pendingCallback,r=this._pendingLoadDataParams;delete this._pendingCallback,delete this._pendingLoadDataParams,this.loadGeoJSON(r,function(n,i){if(n||!i)return e(n);if("object"!=typeof i)return e(new Error("Input data is not a valid GeoJSON object."));!function t(e,r){switch(e&&e.type||null){case"FeatureCollection":return e.features=e.features.map(z(t,r)),e;case"Feature":return e.geometry=t(e.geometry,r),e;case"Polygon":case"MultiPolygon":return function(t,e){return"Polygon"===t.type?t.coordinates=O(t.coordinates,e):"MultiPolygon"===t.type&&(t.coordinates=t.coordinates.map(z(O,e))),t}(e,r);default:return e}}(i,!0);try{t._geoJSONIndex=r.cluster?function(t){return new ot(t)}(r.superclusterOptions).load(i.features):new jt(i,r.geojsonVtOptions)}catch(n){return e(n)}t.loaded={};var a={};if(r.request&&r.request.collectResourceTiming){var o=w(r.request.url);o&&(a.resourceTiming={},a.resourceTiming[r.source]=JSON.parse(JSON.stringify(o)))}e(null,a)})}},r.prototype.coalesce=function(){"Coalescing"===this._state?this._state="Idle":"NeedsLoadData"===this._state&&(this._state="Coalescing",this._loadData())},r.prototype.reloadTile=function(t,r){var n=this.loaded,i=t.uid;return n&&n[i]?e.prototype.reloadTile.call(this,t,r):this.loadTile(t,r)},r.prototype.loadGeoJSON=function(e,r){if(e.request)t.getJSON(e.request,r);else{if("string"!=typeof e.data)return r(new Error("Input data is not a valid GeoJSON object."));try{return r(null,JSON.parse(e.data))}catch(t){return r(new Error("Input data is not a valid GeoJSON object."))}}},r.prototype.removeSource=function(t,e){this._pendingCallback&&this._pendingCallback(null,{abandoned:!0}),e()},r}(A),Ht=function(e){var r=this;this.self=e,this.actor=new t.default$7(e,this),this.layerIndexes={},this.workerSourceTypes={vector:A,geojson:qt},this.workerSources={},this.demWorkerSources={},this.self.registerWorkerSource=function(t,e){if(r.workerSourceTypes[t])throw new Error('Worker source with name "'+t+'" already registered.');r.workerSourceTypes[t]=e},this.self.registerRTLTextPlugin=function(e){if(t.plugin.isLoaded())throw new Error("RTL text plugin already registered.");t.plugin.applyArabicShaping=e.applyArabicShaping,t.plugin.processBidirectionalText=e.processBidirectionalText}};return Ht.prototype.setLayers=function(t,e,r){this.getLayerIndex(t).replace(e),r()},Ht.prototype.updateLayers=function(t,e,r){this.getLayerIndex(t).update(e.layers,e.removedIds),r()},Ht.prototype.loadTile=function(t,e,r){this.getWorkerSource(t,e.type,e.source).loadTile(e,r)},Ht.prototype.loadDEMTile=function(t,e,r){this.getDEMWorkerSource(t,e.source).loadTile(e,r)},Ht.prototype.reloadTile=function(t,e,r){this.getWorkerSource(t,e.type,e.source).reloadTile(e,r)},Ht.prototype.abortTile=function(t,e,r){this.getWorkerSource(t,e.type,e.source).abortTile(e,r)},Ht.prototype.removeTile=function(t,e,r){this.getWorkerSource(t,e.type,e.source).removeTile(e,r)},Ht.prototype.removeDEMTile=function(t,e){this.getDEMWorkerSource(t,e.source).removeTile(e)},Ht.prototype.removeSource=function(t,e,r){if(this.workerSources[t]&&this.workerSources[t][e.type]&&this.workerSources[t][e.type][e.source]){var n=this.workerSources[t][e.type][e.source];delete this.workerSources[t][e.type][e.source],void 0!==n.removeSource?n.removeSource(e,r):r()}},Ht.prototype.loadWorkerSource=function(t,e,r){try{this.self.importScripts(e.url),r()}catch(t){r(t.toString())}},Ht.prototype.loadRTLTextPlugin=function(e,r,n){try{t.plugin.isLoaded()||(this.self.importScripts(r),n(t.plugin.isLoaded()?null:new Error("RTL Text Plugin failed to import scripts from "+r)))}catch(t){n(t.toString())}},Ht.prototype.getLayerIndex=function(t){var e=this.layerIndexes[t];return e||(e=this.layerIndexes[t]=new n),e},Ht.prototype.getWorkerSource=function(t,e,r){var n=this;if(this.workerSources[t]||(this.workerSources[t]={}),this.workerSources[t][e]||(this.workerSources[t][e]={}),!this.workerSources[t][e][r]){var i={send:function(e,r,i){n.actor.send(e,r,i,t)}};this.workerSources[t][e][r]=new this.workerSourceTypes[e](i,this.getLayerIndex(t))}return this.workerSources[t][e][r]},Ht.prototype.getDEMWorkerSource=function(t,e){return this.demWorkerSources[t]||(this.demWorkerSources[t]={}),this.demWorkerSources[t][e]||(this.demWorkerSources[t][e]=new M),this.demWorkerSources[t][e]},"undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof self&&self instanceof WorkerGlobalScope&&new Ht(self),Ht}),i(0,function(t){var e=t.createCommonjsModule(function(t){function e(t){return!!("undefined"!=typeof window&&"undefined"!=typeof document&&Array.prototype&&Array.prototype.every&&Array.prototype.filter&&Array.prototype.forEach&&Array.prototype.indexOf&&Array.prototype.lastIndexOf&&Array.prototype.map&&Array.prototype.some&&Array.prototype.reduce&&Array.prototype.reduceRight&&Array.isArray&&Function.prototype&&Function.prototype.bind&&Object.keys&&Object.create&&Object.getPrototypeOf&&Object.getOwnPropertyNames&&Object.isSealed&&Object.isFrozen&&Object.isExtensible&&Object.getOwnPropertyDescriptor&&Object.defineProperty&&Object.defineProperties&&Object.seal&&Object.freeze&&Object.preventExtensions&&"JSON"in window&&"parse"in JSON&&"stringify"in JSON&&function(){if(!("Worker"in window&&"Blob"in window&&"URL"in window))return!1;var t,e,r=new Blob([""],{type:"text/javascript"}),n=URL.createObjectURL(r);try{e=new Worker(n),t=!0}catch(e){t=!1}return e&&e.terminate(),URL.revokeObjectURL(n),t}()&&"Uint8ClampedArray"in window&&function(t){return void 0===r[t]&&(r[t]=function(t){var r=document.createElement("canvas"),n=Object.create(e.webGLContextAttributes);return n.failIfMajorPerformanceCaveat=t,r.probablySupportsContext?r.probablySupportsContext("webgl",n)||r.probablySupportsContext("experimental-webgl",n):r.supportsContext?r.supportsContext("webgl",n)||r.supportsContext("experimental-webgl",n):r.getContext("webgl",n)||r.getContext("experimental-webgl",n)}(t)),r[t]}(t&&t.failIfMajorPerformanceCaveat))}t.exports?t.exports=e:window&&(window.mapboxgl=window.mapboxgl||{},window.mapboxgl.supported=e);var r={};e.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0}}),r=t.default.performance&&t.default.performance.now?t.default.performance.now.bind(t.default.performance):Date.now.bind(Date),n=t.default.requestAnimationFrame||t.default.mozRequestAnimationFrame||t.default.webkitRequestAnimationFrame||t.default.msRequestAnimationFrame,i=t.default.cancelAnimationFrame||t.default.mozCancelAnimationFrame||t.default.webkitCancelAnimationFrame||t.default.msCancelAnimationFrame,a={now:r,frame:function(t){return n(t)},cancelFrame:function(t){return i(t)},getImageData:function(e){var r=t.default.document.createElement("canvas"),n=r.getContext("2d");if(!n)throw new Error("failed to create canvas 2d context");return r.width=e.width,r.height=e.height,n.drawImage(e,0,0,e.width,e.height),n.getImageData(0,0,e.width,e.height)},hardwareConcurrency:t.default.navigator.hardwareConcurrency||4,get devicePixelRatio(){return t.default.devicePixelRatio},supportsWebp:!1};if(t.default.document){var o=t.default.document.createElement("img");o.onload=function(){a.supportsWebp=!0},o.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA="}var s={create:function(e,r,n){var i=t.default.document.createElement(e);return r&&(i.className=r),n&&n.appendChild(i),i},createNS:function(e,r){return t.default.document.createElementNS(e,r)}},l=t.default.document?t.default.document.documentElement.style:null;function c(t){if(!l)return null;for(var e=0;e<t.length;e++)if(t[e]in l)return t[e];return t[0]}var u,h=c(["userSelect","MozUserSelect","WebkitUserSelect","msUserSelect"]);s.disableDrag=function(){l&&h&&(u=l[h],l[h]="none")},s.enableDrag=function(){l&&h&&(l[h]=u)};var f=c(["transform","WebkitTransform"]);s.setTransform=function(t,e){t.style[f]=e};var p=!1;try{var d=Object.defineProperty({},"passive",{get:function(){p=!0}});t.default.addEventListener("test",d,d),t.default.removeEventListener("test",d,d)}catch(t){p=!1}s.addEventListener=function(t,e,r,n){void 0===n&&(n={}),"passive"in n&&p?t.addEventListener(e,r,n):t.addEventListener(e,r,n.capture)},s.removeEventListener=function(t,e,r,n){void 0===n&&(n={}),"passive"in n&&p?t.removeEventListener(e,r,n):t.removeEventListener(e,r,n.capture)};var g=function(e){e.preventDefault(),e.stopPropagation(),t.default.removeEventListener("click",g,!0)};s.suppressClick=function(){t.default.addEventListener("click",g,!0),t.default.setTimeout(function(){t.default.removeEventListener("click",g,!0)},0)},s.mousePos=function(e,r){var n=e.getBoundingClientRect();return r=r.touches?r.touches[0]:r,new t.default$1(r.clientX-n.left-e.clientLeft,r.clientY-n.top-e.clientTop)},s.touchPos=function(e,r){for(var n=e.getBoundingClientRect(),i=[],a="touchend"===r.type?r.changedTouches:r.touches,o=0;o<a.length;o++)i.push(new t.default$1(a[o].clientX-n.left-e.clientLeft,a[o].clientY-n.top-e.clientTop));return i},s.mouseButton=function(e){return void 0!==t.default.InstallTrigger&&2===e.button&&e.ctrlKey&&t.default.navigator.platform.toUpperCase().indexOf("MAC")>=0?0:e.button},s.remove=function(t){t.parentNode&&t.parentNode.removeChild(t)};var v={API_URL:"https://api.mapbox.com",REQUIRE_ACCESS_TOKEN:!0,ACCESS_TOKEN:null},m="See https://www.mapbox.com/api-documentation/#access-tokens";function y(t,e){var r=M(v.API_URL);if(t.protocol=r.protocol,t.authority=r.authority,"/"!==r.path&&(t.path=""+r.path+t.path),!v.REQUIRE_ACCESS_TOKEN)return T(t);if(!(e=e||v.ACCESS_TOKEN))throw new Error("An API access token is required to use Mapbox GL. "+m);if("s"===e[0])throw new Error("Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). "+m);return t.params.push("access_token="+e),T(t)}function x(t){return 0===t.indexOf("mapbox:")}var b=function(t,e){if(!x(t))return t;var r=M(t);return r.path="/v4/"+r.authority+".json",r.params.push("secure"),y(r,e)},_=function(t,e,r,n){var i=M(t);return x(t)?(i.path="/styles/v1"+i.path+"/sprite"+e+r,y(i,n)):(i.path+=""+e+r,T(i))},w=/(\.(png|jpg)\d*)(?=$)/,k=function(t,e,r){if(!e||!x(e))return t;var n=M(t),i=a.devicePixelRatio>=2||512===r?"@2x":"",o=a.supportsWebp?".webp":"$1";return n.path=n.path.replace(w,""+i+o),function(t){for(var e=0;e<t.length;e++)0===t[e].indexOf("access_token=tk.")&&(t[e]="access_token="+(v.ACCESS_TOKEN||""))}(n.params),T(n)},A=/^(\w+):\/\/([^\/?]*)(\/[^?]+)?\??(.+)?/;function M(t){var e=t.match(A);if(!e)throw new Error("Unable to parse URL object");return{protocol:e[1],authority:e[2],path:e[3]||"/",params:e[4]?e[4].split("&"):[]}}function T(t){var e=t.params.length?"?"+t.params.join("&"):"";return t.protocol+"://"+t.authority+t.path+e}var S=t.default.HTMLImageElement,E=t.default.HTMLCanvasElement,C=t.default.HTMLVideoElement,L=t.default.ImageData,z=function(t,e,r,n){this.context=t,this.format=r,this.texture=t.gl.createTexture(),this.update(e,n)};z.prototype.update=function(t,e){var r=t.width,n=t.height,i=!this.size||this.size[0]!==r||this.size[1]!==n,a=this.context,o=a.gl;this.useMipmap=Boolean(e&&e.useMipmap),o.bindTexture(o.TEXTURE_2D,this.texture),i?(this.size=[r,n],a.pixelStoreUnpack.set(1),this.format!==o.RGBA||e&&!1===e.premultiply||a.pixelStoreUnpackPremultiplyAlpha.set(!0),t instanceof S||t instanceof E||t instanceof C||t instanceof L?o.texImage2D(o.TEXTURE_2D,0,this.format,this.format,o.UNSIGNED_BYTE,t):o.texImage2D(o.TEXTURE_2D,0,this.format,r,n,0,this.format,o.UNSIGNED_BYTE,t.data)):t instanceof S||t instanceof E||t instanceof C||t instanceof L?o.texSubImage2D(o.TEXTURE_2D,0,0,0,o.RGBA,o.UNSIGNED_BYTE,t):o.texSubImage2D(o.TEXTURE_2D,0,0,0,r,n,o.RGBA,o.UNSIGNED_BYTE,t.data),this.useMipmap&&this.isSizePowerOfTwo()&&o.generateMipmap(o.TEXTURE_2D)},z.prototype.bind=function(t,e,r){var n=this.context.gl;n.bindTexture(n.TEXTURE_2D,this.texture),r!==n.LINEAR_MIPMAP_NEAREST||this.isSizePowerOfTwo()||(r=n.LINEAR),t!==this.filter&&(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,t),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,r||t),this.filter=t),e!==this.wrap&&(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,e),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,e),this.wrap=e)},z.prototype.isSizePowerOfTwo=function(){return this.size[0]===this.size[1]&&Math.log(this.size[0])/Math.LN2%1==0},z.prototype.destroy=function(){this.context.gl.deleteTexture(this.texture),this.texture=null};var O=function(){this.images={},this.loaded=!1,this.requestors=[],this.shelfPack=new t.default$2(64,64,{autoResize:!0}),this.patterns={},this.atlasImage=new t.RGBAImage({width:64,height:64}),this.dirty=!0};O.prototype.isLoaded=function(){return this.loaded},O.prototype.setLoaded=function(t){if(this.loaded!==t&&(this.loaded=t,t)){for(var e=0,r=this.requestors;e<r.length;e+=1){var n=r[e],i=n.ids,a=n.callback;this._notify(i,a)}this.requestors=[]}},O.prototype.getImage=function(t){return this.images[t]},O.prototype.addImage=function(t,e){this.images[t]=e},O.prototype.removeImage=function(t){delete this.images[t];var e=this.patterns[t];e&&(this.shelfPack.unref(e.bin),delete this.patterns[t])},O.prototype.getImages=function(t,e){var r=!0;if(!this.isLoaded())for(var n=0,i=t;n<i.length;n+=1){var a=i[n];this.images[a]||(r=!1)}this.isLoaded()||r?this._notify(t,e):this.requestors.push({ids:t,callback:e})},O.prototype._notify=function(t,e){for(var r={},n=0,i=t;n<i.length;n+=1){var a=i[n],o=this.images[a];o&&(r[a]={data:o.data.clone(),pixelRatio:o.pixelRatio,sdf:o.sdf})}e(null,r)},O.prototype.getPixelSize=function(){return{width:this.shelfPack.w,height:this.shelfPack.h}},O.prototype.getPattern=function(e){var r=this.patterns[e];if(r)return r.position;var n=this.getImage(e);if(!n)return null;var i=n.data.width+2,a=n.data.height+2,o=this.shelfPack.packOne(i,a);if(!o)return null;this.atlasImage.resize(this.getPixelSize());var s=n.data,l=this.atlasImage,c=o.x+1,u=o.y+1,h=s.width,f=s.height;t.RGBAImage.copy(s,l,{x:0,y:0},{x:c,y:u},{width:h,height:f}),t.RGBAImage.copy(s,l,{x:0,y:f-1},{x:c,y:u-1},{width:h,height:1}),t.RGBAImage.copy(s,l,{x:0,y:0},{x:c,y:u+f},{width:h,height:1}),t.RGBAImage.copy(s,l,{x:h-1,y:0},{x:c-1,y:u},{width:1,height:f}),t.RGBAImage.copy(s,l,{x:0,y:0},{x:c+h,y:u},{width:1,height:f}),this.dirty=!0;var p=new t.ImagePosition(o,n);return this.patterns[e]={bin:o,position:p},p},O.prototype.bind=function(t){var e=t.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=!1):this.atlasTexture=new z(t,this.atlasImage,e.RGBA),this.atlasTexture.bind(e.LINEAR,e.CLAMP_TO_EDGE)};var I=P,D=1e20;function P(t,e,r,n,i,a){this.fontSize=t||24,this.buffer=void 0===e?3:e,this.cutoff=n||.25,this.fontFamily=i||"sans-serif",this.fontWeight=a||"normal",this.radius=r||8;var o=this.size=this.fontSize+2*this.buffer;this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=o,this.ctx=this.canvas.getContext("2d"),this.ctx.font=this.fontWeight+" "+this.fontSize+"px "+this.fontFamily,this.ctx.textBaseline="middle",this.ctx.fillStyle="black",this.gridOuter=new Float64Array(o*o),this.gridInner=new Float64Array(o*o),this.f=new Float64Array(o),this.d=new Float64Array(o),this.z=new Float64Array(o+1),this.v=new Int16Array(o),this.middle=Math.round(o/2*(navigator.userAgent.indexOf("Gecko/")>=0?1.2:1))}function R(t,e,r,n,i,a,o){for(var s=0;s<e;s++){for(var l=0;l<r;l++)n[l]=t[l*e+s];for(F(n,i,a,o,r),l=0;l<r;l++)t[l*e+s]=i[l]}for(l=0;l<r;l++){for(s=0;s<e;s++)n[s]=t[l*e+s];for(F(n,i,a,o,e),s=0;s<e;s++)t[l*e+s]=Math.sqrt(i[s])}}function F(t,e,r,n,i){r[0]=0,n[0]=-D,n[1]=+D;for(var a=1,o=0;a<i;a++){for(var s=(t[a]+a*a-(t[r[o]]+r[o]*r[o]))/(2*a-2*r[o]);s<=n[o];)o--,s=(t[a]+a*a-(t[r[o]]+r[o]*r[o]))/(2*a-2*r[o]);r[++o]=a,n[o]=s,n[o+1]=+D}for(a=0,o=0;a<i;a++){for(;n[o+1]<a;)o++;e[a]=(a-r[o])*(a-r[o])+t[r[o]]}}P.prototype.draw=function(t){this.ctx.clearRect(0,0,this.size,this.size),this.ctx.fillText(t,this.buffer,this.middle);for(var e=this.ctx.getImageData(0,0,this.size,this.size),r=new Uint8ClampedArray(this.size*this.size),n=0;n<this.size*this.size;n++){var i=e.data[4*n+3]/255;this.gridOuter[n]=1===i?0:0===i?D:Math.pow(Math.max(0,.5-i),2),this.gridInner[n]=1===i?D:0===i?0:Math.pow(Math.max(0,i-.5),2)}for(R(this.gridOuter,this.size,this.size,this.f,this.d,this.v,this.z),R(this.gridInner,this.size,this.size,this.f,this.d,this.v,this.z),n=0;n<this.size*this.size;n++){var a=this.gridOuter[n]-this.gridInner[n];r[n]=Math.max(0,Math.min(255,Math.round(255-255*(a/this.radius+this.cutoff))))}return r};var B=function(t,e){this.requestTransform=t,this.localIdeographFontFamily=e,this.entries={}};B.prototype.setURL=function(t){this.url=t},B.prototype.getGlyphs=function(e,r){var n=this,i=[];for(var a in e)for(var o=0,s=e[a];o<s.length;o+=1){var l=s[o];i.push({stack:a,id:l})}t.asyncAll(i,function(t,e){var r=t.stack,i=t.id,a=n.entries[r];a||(a=n.entries[r]={glyphs:{},requests:{}});var o=a.glyphs[i];if(void 0===o)if(o=n._tinySDF(a,r,i))e(null,{stack:r,id:i,glyph:o});else{var s=Math.floor(i/256);if(256*s>65535)e(new Error("glyphs > 65535 not supported"));else{var l=a.requests[s];l||(l=a.requests[s]=[],B.loadGlyphRange(r,s,n.url,n.requestTransform,function(t,e){if(e)for(var r in e)a.glyphs[+r]=e[+r];for(var n=0,i=l;n<i.length;n+=1)(0,i[n])(t,e);delete a.requests[s]})),l.push(function(t,n){t?e(t):n&&e(null,{stack:r,id:i,glyph:n[i]||null})})}}else e(null,{stack:r,id:i,glyph:o})},function(t,e){if(t)r(t);else if(e){for(var n={},i=0,a=e;i<a.length;i+=1){var o=a[i],s=o.stack,l=o.id,c=o.glyph;(n[s]||(n[s]={}))[l]=c&&{id:c.id,bitmap:c.bitmap.clone(),metrics:c.metrics}}r(null,n)}})},B.prototype._tinySDF=function(e,r,n){var i=this.localIdeographFontFamily;if(i&&(t.default$4["CJK Unified Ideographs"](n)||t.default$4["Hangul Syllables"](n))){var a=e.tinySDF;if(!a){var o="400";/bold/i.test(r)?o="900":/medium/i.test(r)?o="500":/light/i.test(r)&&(o="200"),a=e.tinySDF=new B.TinySDF(24,3,8,.25,i,o)}return{id:n,bitmap:new t.AlphaImage({width:30,height:30},a.draw(String.fromCharCode(n))),metrics:{width:24,height:24,left:0,top:-8,advance:24}}}},B.loadGlyphRange=function(e,r,n,i,a){var o=256*r,s=o+255,l=i(function(t,e){if(!x(t))return t;var r=M(t);return r.path="/fonts/v1"+r.path,y(r,e)}(n).replace("{fontstack}",e).replace("{range}",o+"-"+s),t.ResourceType.Glyphs);t.getArrayBuffer(l,function(e,r){if(e)a(e);else if(r){for(var n={},i=0,o=t.default$3(r.data);i<o.length;i+=1){var s=o[i];n[s.id]=s}a(null,n)}})},B.TinySDF=I;var N=function(){this.specification=t.default$5.light.position};N.prototype.possiblyEvaluate=function(e,r){return t.sphericalToCartesian(e.expression.evaluate(r))},N.prototype.interpolate=function(e,r,n){return{x:t.number(e.x,r.x,n),y:t.number(e.y,r.y,n),z:t.number(e.z,r.z,n)}};var j=new t.Properties({anchor:new t.DataConstantProperty(t.default$5.light.anchor),position:new N,color:new t.DataConstantProperty(t.default$5.light.color),intensity:new t.DataConstantProperty(t.default$5.light.intensity)}),V=function(e){function r(r){e.call(this),this._transitionable=new t.Transitionable(j),this.setLight(r),this._transitioning=this._transitionable.untransitioned()}return e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r,r.prototype.getLight=function(){return this._transitionable.serialize()},r.prototype.setLight=function(e){if(!this._validate(t.validateLight,e))for(var r in e){var n=e[r];t.endsWith(r,"-transition")?this._transitionable.setTransition(r.slice(0,-"-transition".length),n):this._transitionable.setValue(r,n)}},r.prototype.updateTransitions=function(t){this._transitioning=this._transitionable.transitioned(t,this._transitioning)},r.prototype.hasTransition=function(){return this._transitioning.hasTransition()},r.prototype.recalculate=function(t){this.properties=this._transitioning.possiblyEvaluate(t)},r.prototype._validate=function(e,r){return t.emitValidationErrors(this,e.call(t.validateStyle,t.extend({value:r,style:{glyphs:!0,sprite:!0},styleSpec:t.default$5})))},r}(t.Evented),U=function(t,e){this.width=t,this.height=e,this.nextRow=0,this.bytes=4,this.data=new Uint8Array(this.width*this.height*this.bytes),this.positions={}};U.prototype.getDash=function(t,e){var r=t.join(",")+String(e);return this.positions[r]||(this.positions[r]=this.addDash(t,e)),this.positions[r]},U.prototype.addDash=function(e,r){var n=r?7:0,i=2*n+1;if(this.nextRow+i>this.height)return t.warnOnce("LineAtlas out of space"),null;for(var a=0,o=0;o<e.length;o++)a+=e[o];for(var s=this.width/a,l=s/2,c=e.length%2==1,u=-n;u<=n;u++)for(var h=this.nextRow+n+u,f=this.width*h,p=c?-e[e.length-1]:0,d=e[0],g=1,v=0;v<this.width;v++){for(;d<v/s;)p=d,d+=e[g],c&&g===e.length-1&&(d+=e[0]),g++;var m=Math.abs(v-p*s),y=Math.abs(v-d*s),x=Math.min(m,y),b=g%2==1,_=void 0;if(r){var w=n?u/n*(l+1):0;if(b){var k=l-Math.abs(w);_=Math.sqrt(x*x+k*k)}else _=l-Math.sqrt(x*x+w*w)}else _=(b?1:-1)*x;this.data[3+4*(f+v)]=Math.max(0,Math.min(255,_+128))}var A={y:(this.nextRow+n+.5)/this.height,height:2*n/this.height,width:a};return this.nextRow+=i,this.dirty=!0,A},U.prototype.bind=function(t){var e=t.gl;this.texture?(e.bindTexture(e.TEXTURE_2D,this.texture),this.dirty&&(this.dirty=!1,e.texSubImage2D(e.TEXTURE_2D,0,0,0,this.width,this.height,e.RGBA,e.UNSIGNED_BYTE,this.data))):(this.texture=e.createTexture(),e.bindTexture(e.TEXTURE_2D,this.texture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,this.width,this.height,0,e.RGBA,e.UNSIGNED_BYTE,this.data))};var q=function e(r,n){this.workerPool=r,this.actors=[],this.currentActor=0,this.id=t.uniqueId();for(var i=this.workerPool.acquire(this.id),a=0;a<i.length;a++){var o=i[a],s=new e.Actor(o,n,this.id);s.name="Worker "+a,this.actors.push(s)}};function H(e,r,n){var i=function(e,r){if(e)return n(e);if(r){var i=t.pick(r,["tiles","minzoom","maxzoom","attribution","mapbox_logo","bounds"]);r.vector_layers&&(i.vectorLayers=r.vector_layers,i.vectorLayerIds=i.vectorLayers.map(function(t){return t.id})),n(null,i)}};e.url?t.getJSON(r(b(e.url),t.ResourceType.Source),i):a.frame(function(){return i(null,e)})}q.prototype.broadcast=function(e,r,n){n=n||function(){},t.asyncAll(this.actors,function(t,n){t.send(e,r,n)},n)},q.prototype.send=function(t,e,r,n){return("number"!=typeof n||isNaN(n))&&(n=this.currentActor=(this.currentActor+1)%this.actors.length),this.actors[n].send(t,e,r),n},q.prototype.remove=function(){this.actors.forEach(function(t){t.remove()}),this.actors=[],this.workerPool.release(this.id)},q.Actor=t.default$7;var G=function(t,e){if(isNaN(t)||isNaN(e))throw new Error("Invalid LngLat object: ("+t+", "+e+")");if(this.lng=+t,this.lat=+e,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")};G.prototype.wrap=function(){return new G(t.wrap(this.lng,-180,180),this.lat)},G.prototype.toArray=function(){return[this.lng,this.lat]},G.prototype.toString=function(){return"LngLat("+this.lng+", "+this.lat+")"},G.prototype.toBounds=function(t){var e=360*t/40075017,r=e/Math.cos(Math.PI/180*this.lat);return new Y(new G(this.lng-r,this.lat-e),new G(this.lng+r,this.lat+e))},G.convert=function(t){if(t instanceof G)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new G(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new G(Number(t.lng),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: <lng>, lat: <lat>}, or an array of [<lng>, <lat>]")};var Y=function(t,e){t&&(e?this.setSouthWest(t).setNorthEast(e):4===t.length?this.setSouthWest([t[0],t[1]]).setNorthEast([t[2],t[3]]):this.setSouthWest(t[0]).setNorthEast(t[1]))};Y.prototype.setNorthEast=function(t){return this._ne=t instanceof G?new G(t.lng,t.lat):G.convert(t),this},Y.prototype.setSouthWest=function(t){return this._sw=t instanceof G?new G(t.lng,t.lat):G.convert(t),this},Y.prototype.extend=function(t){var e,r,n=this._sw,i=this._ne;if(t instanceof G)e=t,r=t;else{if(!(t instanceof Y))return Array.isArray(t)?t.every(Array.isArray)?this.extend(Y.convert(t)):this.extend(G.convert(t)):this;if(e=t._sw,r=t._ne,!e||!r)return this}return n||i?(n.lng=Math.min(e.lng,n.lng),n.lat=Math.min(e.lat,n.lat),i.lng=Math.max(r.lng,i.lng),i.lat=Math.max(r.lat,i.lat)):(this._sw=new G(e.lng,e.lat),this._ne=new G(r.lng,r.lat)),this},Y.prototype.getCenter=function(){return new G((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)},Y.prototype.getSouthWest=function(){return this._sw},Y.prototype.getNorthEast=function(){return this._ne},Y.prototype.getNorthWest=function(){return new G(this.getWest(),this.getNorth())},Y.prototype.getSouthEast=function(){return new G(this.getEast(),this.getSouth())},Y.prototype.getWest=function(){return this._sw.lng},Y.prototype.getSouth=function(){return this._sw.lat},Y.prototype.getEast=function(){return this._ne.lng},Y.prototype.getNorth=function(){return this._ne.lat},Y.prototype.toArray=function(){return[this._sw.toArray(),this._ne.toArray()]},Y.prototype.toString=function(){return"LngLatBounds("+this._sw.toString()+", "+this._ne.toString()+")"},Y.prototype.isEmpty=function(){return!(this._sw&&this._ne)},Y.convert=function(t){return!t||t instanceof Y?t:new Y(t)};var W=function(t,e,r){this.bounds=Y.convert(this.validateBounds(t)),this.minzoom=e||0,this.maxzoom=r||24};W.prototype.validateBounds=function(t){return Array.isArray(t)&&4===t.length?[Math.max(-180,t[0]),Math.max(-90,t[1]),Math.min(180,t[2]),Math.min(90,t[3])]:[-180,-90,180,90]},W.prototype.contains=function(t){var e=Math.floor(this.lngX(this.bounds.getWest(),t.z)),r=Math.floor(this.latY(this.bounds.getNorth(),t.z)),n=Math.ceil(this.lngX(this.bounds.getEast(),t.z)),i=Math.ceil(this.latY(this.bounds.getSouth(),t.z));return t.x>=e&&t.x<n&&t.y>=r&&t.y<i},W.prototype.lngX=function(t,e){return(t+180)*(Math.pow(2,e)/360)},W.prototype.latY=function(e,r){var n=t.clamp(Math.sin(Math.PI/180*e),-.9999,.9999),i=Math.pow(2,r)/(2*Math.PI);return Math.pow(2,r-1)+.5*Math.log((1+n)/(1-n))*-i};var X=function(e){function r(r,n,i,a){if(e.call(this),this.id=r,this.dispatcher=i,this.type="vector",this.minzoom=0,this.maxzoom=22,this.scheme="xyz",this.tileSize=512,this.reparseOverscaled=!0,this.isTileClipped=!0,t.extend(this,t.pick(n,["url","scheme","tileSize"])),this._options=t.extend({type:"vector"},n),this._collectResourceTiming=n.collectResourceTiming,512!==this.tileSize)throw new Error("vector tile sources must have a tileSize of 512");this.setEventedParent(a)}return e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r,r.prototype.load=function(){var e=this;this.fire(new t.Event("dataloading",{dataType:"source"})),H(this._options,this.map._transformRequest,function(r,n){r?e.fire(new t.ErrorEvent(r)):n&&(t.extend(e,n),n.bounds&&(e.tileBounds=new W(n.bounds,e.minzoom,e.maxzoom)),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"content"})))})},r.prototype.hasTile=function(t){return!this.tileBounds||this.tileBounds.contains(t.canonical)},r.prototype.onAdd=function(t){this.map=t,this.load()},r.prototype.serialize=function(){return t.extend({},this._options)},r.prototype.loadTile=function(e,r){var n=k(e.tileID.canonical.url(this.tiles,this.scheme),this.url),i={request:this.map._transformRequest(n,t.ResourceType.Tile),uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,tileSize:this.tileSize*e.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:a.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes};function o(t,n){return e.aborted?r(null):t?r(t):(n&&n.resourceTiming&&(e.resourceTiming=n.resourceTiming),this.map._refreshExpiredTiles&&e.setExpiryData(n),e.loadVectorData(n,this.map.painter),r(null),void(e.reloadCallback&&(this.loadTile(e,e.reloadCallback),e.reloadCallback=null)))}i.request.collectResourceTiming=this._collectResourceTiming,void 0===e.workerID||"expired"===e.state?e.workerID=this.dispatcher.send("loadTile",i,o.bind(this)):"loading"===e.state?e.reloadCallback=r:this.dispatcher.send("reloadTile",i,o.bind(this),e.workerID)},r.prototype.abortTile=function(t){this.dispatcher.send("abortTile",{uid:t.uid,type:this.type,source:this.id},void 0,t.workerID)},r.prototype.unloadTile=function(t){t.unloadVectorData(),this.dispatcher.send("removeTile",{uid:t.uid,type:this.type,source:this.id},void 0,t.workerID)},r.prototype.hasTransition=function(){return!1},r}(t.Evented),Z=function(e){function r(r,n,i,a){e.call(this),this.id=r,this.dispatcher=i,this.setEventedParent(a),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=t.extend({},n),t.extend(this,t.pick(n,["url","scheme","tileSize"]))}return e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r,r.prototype.load=function(){var e=this;this.fire(new t.Event("dataloading",{dataType:"source"})),H(this._options,this.map._transformRequest,function(r,n){r?e.fire(new t.ErrorEvent(r)):n&&(t.extend(e,n),n.bounds&&(e.tileBounds=new W(n.bounds,e.minzoom,e.maxzoom)),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"content"})))})},r.prototype.onAdd=function(t){this.map=t,this.load()},r.prototype.serialize=function(){return t.extend({},this._options)},r.prototype.hasTile=function(t){return!this.tileBounds||this.tileBounds.contains(t.canonical)},r.prototype.loadTile=function(e,r){var n=this,i=k(e.tileID.canonical.url(this.tiles,this.scheme),this.url,this.tileSize);e.request=t.getImage(this.map._transformRequest(i,t.ResourceType.Tile),function(t,i){if(delete e.request,e.aborted)e.state="unloaded",r(null);else if(t)e.state="errored",r(t);else if(i){n.map._refreshExpiredTiles&&e.setExpiryData(i),delete i.cacheControl,delete i.expires;var a=n.map.painter.context,o=a.gl;e.texture=n.map.painter.getTileTexture(i.width),e.texture?e.texture.update(i,{useMipmap:!0}):(e.texture=new z(a,i,o.RGBA,{useMipmap:!0}),e.texture.bind(o.LINEAR,o.CLAMP_TO_EDGE,o.LINEAR_MIPMAP_NEAREST),a.extTextureFilterAnisotropic&&o.texParameterf(o.TEXTURE_2D,a.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,a.extTextureFilterAnisotropicMax)),e.state="loaded",r(null)}})},r.prototype.abortTile=function(t,e){t.request&&(t.request.abort(),delete t.request),e()},r.prototype.unloadTile=function(t,e){t.texture&&this.map.painter.saveTileTexture(t.texture),e()},r.prototype.hasTransition=function(){return!1},r}(t.Evented),$=function(e){function r(r,n,i,a){e.call(this,r,n,i,a),this.type="raster-dem",this.maxzoom=22,this._options=t.extend({},n),this.encoding=n.encoding||"mapbox"}return e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r,r.prototype.serialize=function(){return{type:"raster-dem",url:this.url,tileSize:this.tileSize,tiles:this.tiles,bounds:this.bounds,encoding:this.encoding}},r.prototype.loadTile=function(e,r){var n=k(e.tileID.canonical.url(this.tiles,this.scheme),this.url,this.tileSize);e.request=t.getImage(this.map._transformRequest(n,t.ResourceType.Tile),function(t,n){if(delete e.request,e.aborted)e.state="unloaded",r(null);else if(t)e.state="errored",r(t);else if(n){this.map._refreshExpiredTiles&&e.setExpiryData(n),delete n.cacheControl,delete n.expires;var i=a.getImageData(n),o={uid:e.uid,coord:e.tileID,source:this.id,rawImageData:i,encoding:this.encoding};e.workerID&&"expired"!==e.state||(e.workerID=this.dispatcher.send("loadDEMTile",o,function(t,n){t&&(e.state="errored",r(t)),n&&(e.dem=n,e.needsHillshadePrepare=!0,e.state="loaded",r(null))}.bind(this)))}}.bind(this)),e.neighboringTiles=this._getNeighboringTiles(e.tileID)},r.prototype._getNeighboringTiles=function(e){var r=e.canonical,n=Math.pow(2,r.z),i=(r.x-1+n)%n,a=0===r.x?e.wrap-1:e.wrap,o=(r.x+1+n)%n,s=r.x+1===n?e.wrap+1:e.wrap,l={};return l[new t.OverscaledTileID(e.overscaledZ,a,r.z,i,r.y).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,s,r.z,o,r.y).key]={backfilled:!1},r.y>0&&(l[new t.OverscaledTileID(e.overscaledZ,a,r.z,i,r.y-1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,e.wrap,r.z,r.x,r.y-1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,s,r.z,o,r.y-1).key]={backfilled:!1}),r.y+1<n&&(l[new t.OverscaledTileID(e.overscaledZ,a,r.z,i,r.y+1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,e.wrap,r.z,r.x,r.y+1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,s,r.z,o,r.y+1).key]={backfilled:!1}),l},r.prototype.unloadTile=function(t){t.demTexture&&this.map.painter.saveTileTexture(t.demTexture),t.fbo&&(t.fbo.destroy(),delete t.fbo),t.dem&&delete t.dem,delete t.neighboringTiles,t.state="unloaded",this.dispatcher.send("removeDEMTile",{uid:t.uid,source:this.id},void 0,t.workerID)},r}(Z),J=function(e){function r(r,n,i,a){e.call(this),this.id=r,this.type="geojson",this.minzoom=0,this.maxzoom=18,this.tileSize=512,this.isTileClipped=!0,this.reparseOverscaled=!0,this._removed=!1,this.dispatcher=i,this.setEventedParent(a),this._data=n.data,this._options=t.extend({},n),this._collectResourceTiming=n.collectResourceTiming,this._resourceTiming=[],void 0!==n.maxzoom&&(this.maxzoom=n.maxzoom),n.type&&(this.type=n.type);var o=t.default$8/this.tileSize;this.workerOptions=t.extend({source:this.id,cluster:n.cluster||!1,geojsonVtOptions:{buffer:(void 0!==n.buffer?n.buffer:128)*o,tolerance:(void 0!==n.tolerance?n.tolerance:.375)*o,extent:t.default$8,maxZoom:this.maxzoom,lineMetrics:n.lineMetrics||!1},superclusterOptions:{maxZoom:void 0!==n.clusterMaxZoom?Math.min(n.clusterMaxZoom,this.maxzoom-1):this.maxzoom-1,extent:t.default$8,radius:(n.clusterRadius||50)*o,log:!1}},n.workerOptions)}return e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r,r.prototype.load=function(){var e=this;this.fire(new t.Event("dataloading",{dataType:"source"})),this._updateWorkerData(function(r){if(r)e.fire(new t.ErrorEvent(r));else{var n={dataType:"source",sourceDataType:"metadata"};e._collectResourceTiming&&e._resourceTiming&&e._resourceTiming.length>0&&(n.resourceTiming=e._resourceTiming,e._resourceTiming=[]),e.fire(new t.Event("data",n))}})},r.prototype.onAdd=function(t){this.map=t,this.load()},r.prototype.setData=function(e){var r=this;return this._data=e,this.fire(new t.Event("dataloading",{dataType:"source"})),this._updateWorkerData(function(e){if(e)return r.fire(new t.ErrorEvent(e));var n={dataType:"source",sourceDataType:"content"};r._collectResourceTiming&&r._resourceTiming&&r._resourceTiming.length>0&&(n.resourceTiming=r._resourceTiming,r._resourceTiming=[]),r.fire(new t.Event("data",n))}),this},r.prototype._updateWorkerData=function(e){var r,n,i=this,a=t.extend({},this.workerOptions),o=this._data;"string"==typeof o?(a.request=this.map._transformRequest((r=o,(n=t.default.document.createElement("a")).href=r,n.href),t.ResourceType.Source),a.request.collectResourceTiming=this._collectResourceTiming):a.data=JSON.stringify(o),this.workerID=this.dispatcher.send(this.type+"."+a.source+".loadData",a,function(t,r){i._removed||r&&r.abandoned||(i._loaded=!0,r&&r.resourceTiming&&r.resourceTiming[i.id]&&(i._resourceTiming=r.resourceTiming[i.id].slice(0)),i.dispatcher.send(i.type+"."+a.source+".coalesce",null,null,i.workerID),e(t))},this.workerID)},r.prototype.loadTile=function(t,e){var r=this,n=void 0===t.workerID?"loadTile":"reloadTile",i={type:this.type,uid:t.uid,tileID:t.tileID,zoom:t.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:a.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes};t.workerID=this.dispatcher.send(n,i,function(i,a){return t.unloadVectorData(),t.aborted?e(null):i?e(i):(t.loadVectorData(a,r.map.painter,"reloadTile"===n),e(null))},this.workerID)},r.prototype.abortTile=function(t){t.aborted=!0},r.prototype.unloadTile=function(t){t.unloadVectorData(),this.dispatcher.send("removeTile",{uid:t.uid,type:this.type,source:this.id},null,t.workerID)},r.prototype.onRemove=function(){this._removed=!0,this.dispatcher.send("removeSource",{type:this.type,source:this.id},null,this.workerID)},r.prototype.serialize=function(){return t.extend({},this._options,{type:this.type,data:this._data})},r.prototype.hasTransition=function(){return!1},r}(t.Evented),K=t.createLayout([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]),Q=function(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null};Q.prototype.bind=function(t,e,r,n,i,a,o,s){this.context=t;for(var l=this.boundPaintVertexBuffers.length!==n.length,c=0;!l&&c<n.length;c++)this.boundPaintVertexBuffers[c]!==n[c]&&(l=!0);var u=!this.vao||this.boundProgram!==e||this.boundLayoutVertexBuffer!==r||l||this.boundIndexBuffer!==i||this.boundVertexOffset!==a||this.boundDynamicVertexBuffer!==o||this.boundDynamicVertexBuffer2!==s;!t.extVertexArrayObject||u?this.freshBind(e,r,n,i,a,o,s):(t.bindVertexArrayOES.set(this.vao),o&&o.bind(),i&&i.dynamicDraw&&i.bind(),s&&s.bind())},Q.prototype.freshBind=function(t,e,r,n,i,a,o){var s,l=t.numAttributes,c=this.context,u=c.gl;if(c.extVertexArrayObject)this.vao&&this.destroy(),this.vao=c.extVertexArrayObject.createVertexArrayOES(),c.bindVertexArrayOES.set(this.vao),s=0,this.boundProgram=t,this.boundLayoutVertexBuffer=e,this.boundPaintVertexBuffers=r,this.boundIndexBuffer=n,this.boundVertexOffset=i,this.boundDynamicVertexBuffer=a,this.boundDynamicVertexBuffer2=o;else{s=c.currentNumAttributes||0;for(var h=l;h<s;h++)u.disableVertexAttribArray(h)}e.enableAttributes(u,t);for(var f=0,p=r;f<p.length;f+=1)p[f].enableAttributes(u,t);a&&a.enableAttributes(u,t),o&&o.enableAttributes(u,t),e.bind(),e.setVertexAttribPointers(u,t,i);for(var d=0,g=r;d<g.length;d+=1){var v=g[d];v.bind(),v.setVertexAttribPointers(u,t,i)}a&&(a.bind(),a.setVertexAttribPointers(u,t,i)),n&&n.bind(),o&&(o.bind(),o.setVertexAttribPointers(u,t,i)),c.currentNumAttributes=l},Q.prototype.destroy=function(){this.vao&&(this.context.extVertexArrayObject.deleteVertexArrayOES(this.vao),this.vao=null)};var tt=function(e){function r(t,r,n,i){e.call(this),this.id=t,this.dispatcher=n,this.coordinates=r.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this.setEventedParent(i),this.options=r}return e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r,r.prototype.load=function(){var e=this;this.fire(new t.Event("dataloading",{dataType:"source"})),this.url=this.options.url,t.getImage(this.map._transformRequest(this.url,t.ResourceType.Image),function(r,n){r?e.fire(new t.ErrorEvent(r)):n&&(e.image=a.getImageData(n),e._finishLoading())})},r.prototype._finishLoading=function(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})))},r.prototype.onAdd=function(t){this.map=t,this.load()},r.prototype.setCoordinates=function(e){this.coordinates=e;var r=this.map,n=e.map(function(t){return r.transform.locationCoordinate(G.convert(t)).zoomTo(0)}),i=this.centerCoord=t.getCoordinatesCenter(n);i.column=Math.floor(i.column),i.row=Math.floor(i.row),this.tileID=new t.CanonicalTileID(i.zoom,i.column,i.row),this.minzoom=this.maxzoom=i.zoom;var a=n.map(function(e){var r=e.zoomTo(i.zoom);return new t.default$1(Math.round((r.column-i.column)*t.default$8),Math.round((r.row-i.row)*t.default$8))});return this._boundsArray=new t.RasterBoundsArray,this._boundsArray.emplaceBack(a[0].x,a[0].y,0,0),this._boundsArray.emplaceBack(a[1].x,a[1].y,t.default$8,0),this._boundsArray.emplaceBack(a[3].x,a[3].y,0,t.default$8),this._boundsArray.emplaceBack(a[2].x,a[2].y,t.default$8,t.default$8),this.boundsBuffer&&(this.boundsBuffer.destroy(),delete this.boundsBuffer),this.fire(new t.Event("data",{dataType:"source",sourceDataType:"content"})),this},r.prototype.prepare=function(){if(0!==Object.keys(this.tiles).length&&this.image){var t=this.map.painter.context,e=t.gl;for(var r in this.boundsBuffer||(this.boundsBuffer=t.createVertexBuffer(this._boundsArray,K.members)),this.boundsVAO||(this.boundsVAO=new Q),this.texture||(this.texture=new z(t,this.image,e.RGBA),this.texture.bind(e.LINEAR,e.CLAMP_TO_EDGE)),this.tiles){var n=this.tiles[r];"loaded"!==n.state&&(n.state="loaded",n.texture=this.texture)}}},r.prototype.loadTile=function(t,e){this.tileID&&this.tileID.equals(t.tileID.canonical)?(this.tiles[String(t.tileID.wrap)]=t,t.buckets={},e(null)):(t.state="errored",e(null))},r.prototype.serialize=function(){return{type:"image",url:this.options.url,coordinates:this.coordinates}},r.prototype.hasTransition=function(){return!1},r}(t.Evented),et=function(e){function r(t,r,n,i){e.call(this,t,r,n,i),this.roundZoom=!0,this.type="video",this.options=r}return e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r,r.prototype.load=function(){var e=this,r=this.options;this.urls=[];for(var n=0,i=r.urls;n<i.length;n+=1){var a=i[n];e.urls.push(e.map._transformRequest(a,t.ResourceType.Source).url)}t.getVideo(this.urls,function(r,n){r?e.fire(new t.ErrorEvent(r)):n&&(e.video=n,e.video.loop=!0,e.video.addEventListener("playing",function(){e.map._rerender()}),e.map&&e.video.play(),e._finishLoading())})},r.prototype.getVideo=function(){return this.video},r.prototype.onAdd=function(t){this.map||(this.map=t,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)))},r.prototype.prepare=function(){if(!(0===Object.keys(this.tiles).length||this.video.readyState<2)){var t=this.map.painter.context,e=t.gl;for(var r in this.boundsBuffer||(this.boundsBuffer=t.createVertexBuffer(this._boundsArray,K.members)),this.boundsVAO||(this.boundsVAO=new Q),this.texture?this.video.paused||(this.texture.bind(e.LINEAR,e.CLAMP_TO_EDGE),e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,this.video)):(this.texture=new z(t,this.video,e.RGBA),this.texture.bind(e.LINEAR,e.CLAMP_TO_EDGE)),this.tiles){var n=this.tiles[r];"loaded"!==n.state&&(n.state="loaded",n.texture=this.texture)}}},r.prototype.serialize=function(){return{type:"video",urls:this.urls,coordinates:this.coordinates}},r.prototype.hasTransition=function(){return this.video&&!this.video.paused},r}(tt),rt=function(e){function r(r,n,i,a){e.call(this,r,n,i,a),n.coordinates?Array.isArray(n.coordinates)&&4===n.coordinates.length&&!n.coordinates.some(function(t){return!Array.isArray(t)||2!==t.length||t.some(function(t){return"number"!=typeof t})})||this.fire(new t.ErrorEvent(new t.default$9("sources."+r,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new t.ErrorEvent(new t.default$9("sources."+r,null,'missing required property "coordinates"'))),n.animate&&"boolean"!=typeof n.animate&&this.fire(new t.ErrorEvent(new t.default$9("sources."+r,null,'optional "animate" property must be a boolean value'))),n.canvas?"string"==typeof n.canvas||n.canvas instanceof t.default.HTMLCanvasElement||this.fire(new t.ErrorEvent(new t.default$9("sources."+r,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new t.ErrorEvent(new t.default$9("sources."+r,null,'missing required property "canvas"'))),this.options=n,this.animate=void 0===n.animate||n.animate}return e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r,r.prototype.load=function(){this.canvas||(this.canvas=this.options.canvas instanceof t.default.HTMLCanvasElement?this.options.canvas:t.default.document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new t.ErrorEvent(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map._rerender()},this.pause=function(){this._playing=!1},this._finishLoading())},r.prototype.getCanvas=function(){return this.canvas},r.prototype.onAdd=function(t){this.map=t,this.load(),this.canvas&&this.animate&&this.play()},r.prototype.onRemove=function(){this.pause()},r.prototype.prepare=function(){var t=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,t=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,t=!0),!this._hasInvalidDimensions()&&0!==Object.keys(this.tiles).length){var e=this.map.painter.context,r=e.gl;for(var n in this.boundsBuffer||(this.boundsBuffer=e.createVertexBuffer(this._boundsArray,K.members)),this.boundsVAO||(this.boundsVAO=new Q),this.texture?t?this.texture.update(this.canvas):this._playing&&(this.texture.bind(r.LINEAR,r.CLAMP_TO_EDGE),r.texSubImage2D(r.TEXTURE_2D,0,0,0,r.RGBA,r.UNSIGNED_BYTE,this.canvas)):(this.texture=new z(e,this.canvas,r.RGBA),this.texture.bind(r.LINEAR,r.CLAMP_TO_EDGE)),this.tiles){var i=this.tiles[n];"loaded"!==i.state&&(i.state="loaded",i.texture=this.texture)}}},r.prototype.serialize=function(){return{type:"canvas",coordinates:this.coordinates}},r.prototype.hasTransition=function(){return this._playing},r.prototype._hasInvalidDimensions=function(){for(var t=0,e=[this.canvas.width,this.canvas.height];t<e.length;t+=1){var r=e[t];if(isNaN(r)||r<=0)return!0}return!1},r}(tt),nt={vector:X,raster:Z,"raster-dem":$,geojson:J,video:et,image:tt,canvas:rt},it=function(e,r,n,i){var a=new nt[r.type](e,r,n,i);if(a.id!==e)throw new Error("Expected Source id to be "+e+" instead of "+a.id);return t.bindAll(["load","abort","unload","serialize","prepare"],a),a};function at(t,e,r,n,i){var a=i.maxPitchScaleFactor(),o=t.tilesIn(r,a);o.sort(ot);for(var s=[],l=0,c=o;l<c.length;l+=1){var u=c[l];s.push({wrappedTileID:u.tileID.wrapped().key,queryResults:u.tile.queryRenderedFeatures(e,u.queryGeometry,u.scale,n,i,a,t.transform.calculatePosMatrix(u.tileID.toUnwrapped()))})}return function(t){for(var e={},r={},n=0,i=t;n<i.length;n+=1){var a=i[n],o=a.queryResults,s=a.wrappedTileID,l=r[s]=r[s]||{};for(var c in o)for(var u=o[c],h=l[c]=l[c]||{},f=e[c]=e[c]||[],p=0,d=u;p<d.length;p+=1){var g=d[p];h[g.featureIndex]||(h[g.featureIndex]=!0,f.push(g.feature))}}return e}(s)}function ot(t,e){var r=t.tileID,n=e.tileID;return r.overscaledZ-n.overscaledZ||r.canonical.y-n.canonical.y||r.wrap-n.wrap||r.canonical.x-n.canonical.x}var st=function(e,r){this.tileID=e,this.uid=t.uniqueId(),this.uses=0,this.tileSize=r,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.expiredRequestCount=0,this.state="loading"};st.prototype.registerFadeDuration=function(t){var e=t+this.timeAdded;e<a.now()||this.fadeEndTime&&e<this.fadeEndTime||(this.fadeEndTime=e)},st.prototype.wasRequested=function(){return"errored"===this.state||"loaded"===this.state||"reloading"===this.state},st.prototype.loadVectorData=function(e,r,n){if(this.hasData()&&this.unloadVectorData(),this.state="loaded",e){if(e.featureIndex&&(this.latestFeatureIndex=e.featureIndex,e.rawTileData?(this.latestRawTileData=e.rawTileData,this.latestFeatureIndex.rawTileData=e.rawTileData):this.latestRawTileData&&(this.latestFeatureIndex.rawTileData=this.latestRawTileData)),this.collisionBoxArray=e.collisionBoxArray,this.buckets=function(t,e){var r={};if(!e)return r;for(var n=0,i=t;n<i.length;n+=1){var a=i[n],o=a.layerIds.map(function(t){return e.getLayer(t)}).filter(Boolean);if(0!==o.length){a.layers=o;for(var s=0,l=o;s<l.length;s+=1)r[l[s].id]=a}}return r}(e.buckets,r.style),n)for(var i in this.buckets){var a=this.buckets[i];a instanceof t.default$14&&(a.justReloaded=!0)}for(var o in this.queryPadding=0,this.buckets){var s=this.buckets[o];this.queryPadding=Math.max(this.queryPadding,r.style.getLayer(s.layerIds[0]).queryRadius(s))}e.iconAtlasImage&&(this.iconAtlasImage=e.iconAtlasImage),e.glyphAtlasImage&&(this.glyphAtlasImage=e.glyphAtlasImage)}else this.collisionBoxArray=new t.CollisionBoxArray},st.prototype.unloadVectorData=function(){for(var t in this.buckets)this.buckets[t].destroy();this.buckets={},this.iconAtlasTexture&&this.iconAtlasTexture.destroy(),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.latestFeatureIndex=null,this.state="unloaded"},st.prototype.unloadDEMData=function(){this.dem=null,this.neighboringTiles=null,this.state="unloaded"},st.prototype.getBucket=function(t){return this.buckets[t.id]},st.prototype.upload=function(t){for(var e in this.buckets){var r=this.buckets[e];r.uploaded||(r.upload(t),r.uploaded=!0)}var n=t.gl;this.iconAtlasImage&&(this.iconAtlasTexture=new z(t,this.iconAtlasImage,n.RGBA),this.iconAtlasImage=null),this.glyphAtlasImage&&(this.glyphAtlasTexture=new z(t,this.glyphAtlasImage,n.ALPHA),this.glyphAtlasImage=null)},st.prototype.queryRenderedFeatures=function(t,e,r,n,i,a,o){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({queryGeometry:e,scale:r,tileSize:this.tileSize,posMatrix:o,transform:i,params:n,queryPadding:this.queryPadding*a},t):{}},st.prototype.querySourceFeatures=function(e,r){if(this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData){var n=this.latestFeatureIndex.loadVTLayers(),i=r?r.sourceLayer:"",a=n._geojsonTileLayer||n[i];if(a)for(var o=t.default$13(r&&r.filter),s={z:this.tileID.overscaledZ,x:this.tileID.canonical.x,y:this.tileID.canonical.y},l=0;l<a.length;l++){var c=a.feature(l);if(o(new t.default$16(this.tileID.overscaledZ),c)){var u=new t.default$12(c,s.z,s.x,s.y);u.tile=s,e.push(u)}}}},st.prototype.clearMask=function(){this.segments&&(this.segments.destroy(),delete this.segments),this.maskedBoundsBuffer&&(this.maskedBoundsBuffer.destroy(),delete this.maskedBoundsBuffer),this.maskedIndexBuffer&&(this.maskedIndexBuffer.destroy(),delete this.maskedIndexBuffer)},st.prototype.setMask=function(e,r){if(!t.default$10(this.mask,e)&&(this.mask=e,this.clearMask(),!t.default$10(e,{0:!0}))){var n=new t.RasterBoundsArray,i=new t.TriangleIndexArray;this.segments=new t.default$15,this.segments.prepareSegment(0,n,i);for(var a=Object.keys(e),o=0;o<a.length;o++){var s=e[a[o]],l=t.default$8>>s.z,c=new t.default$1(s.x*l,s.y*l),u=new t.default$1(c.x+l,c.y+l),h=this.segments.prepareSegment(4,n,i);n.emplaceBack(c.x,c.y,c.x,c.y),n.emplaceBack(u.x,c.y,u.x,c.y),n.emplaceBack(c.x,u.y,c.x,u.y),n.emplaceBack(u.x,u.y,u.x,u.y);var f=h.vertexLength;i.emplaceBack(f,f+1,f+2),i.emplaceBack(f+1,f+2,f+3),h.vertexLength+=4,h.primitiveLength+=2}this.maskedBoundsBuffer=r.createVertexBuffer(n,K.members),this.maskedIndexBuffer=r.createIndexBuffer(i)}},st.prototype.hasData=function(){return"loaded"===this.state||"reloading"===this.state||"expired"===this.state},st.prototype.setExpiryData=function(e){var r=this.expirationTime;if(e.cacheControl){var n=t.parseCacheControl(e.cacheControl);n["max-age"]&&(this.expirationTime=Date.now()+1e3*n["max-age"])}else e.expires&&(this.expirationTime=new Date(e.expires).getTime());if(this.expirationTime){var i=Date.now(),a=!1;if(this.expirationTime>i)a=!1;else if(r)if(this.expirationTime<r)a=!0;else{var o=this.expirationTime-r;o?this.expirationTime=i+Math.max(o,3e4):a=!0}else a=!0;a?(this.expiredRequestCount++,this.state="expired"):this.expiredRequestCount=0}},st.prototype.getExpiryTimeout=function(){if(this.expirationTime)return this.expiredRequestCount?1e3*(1<<Math.min(this.expiredRequestCount-1,31)):Math.min(this.expirationTime-(new Date).getTime(),Math.pow(2,31)-1)};var lt=function(t,e){this.max=t,this.onRemove=e,this.reset()};lt.prototype.reset=function(){for(var t in this.data)for(var e=0,r=this.data[t];e<r.length;e+=1){var n=r[e];n.timeout&&clearTimeout(n.timeout),this.onRemove(n.value)}return this.data={},this.order=[],this},lt.prototype.add=function(t,e,r){var n=this,i=t.wrapped().key;void 0===this.data[i]&&(this.data[i]=[]);var a={value:e,timeout:void 0};if(void 0!==r&&(a.timeout=setTimeout(function(){n.remove(t,a)},r)),this.data[i].push(a),this.order.push(i),this.order.length>this.max){var o=this._getAndRemoveByKey(this.order[0]);o&&this.onRemove(o)}return this},lt.prototype.has=function(t){return t.wrapped().key in this.data},lt.prototype.getAndRemove=function(t){return this.has(t)?this._getAndRemoveByKey(t.wrapped().key):null},lt.prototype._getAndRemoveByKey=function(t){var e=this.data[t].shift();return e.timeout&&clearTimeout(e.timeout),0===this.data[t].length&&delete this.data[t],this.order.splice(this.order.indexOf(t),1),e.value},lt.prototype.get=function(t){return this.has(t)?this.data[t.wrapped().key][0].value:null},lt.prototype.remove=function(t,e){if(!this.has(t))return this;var r=t.wrapped().key,n=void 0===e?0:this.data[r].indexOf(e),i=this.data[r][n];return this.data[r].splice(n,1),i.timeout&&clearTimeout(i.timeout),0===this.data[r].length&&delete this.data[r],this.onRemove(i.value),this.order.splice(this.order.indexOf(r),1),this},lt.prototype.setMaxSize=function(t){for(this.max=t;this.order.length>this.max;){var e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e)}return this};var ct=function(t,e,r){this.context=t;var n=t.gl;this.buffer=n.createBuffer(),this.dynamicDraw=Boolean(r),this.unbindVAO(),t.bindElementBuffer.set(this.buffer),n.bufferData(n.ELEMENT_ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?n.DYNAMIC_DRAW:n.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer};ct.prototype.unbindVAO=function(){this.context.extVertexArrayObject&&this.context.bindVertexArrayOES.set(null)},ct.prototype.bind=function(){this.context.bindElementBuffer.set(this.buffer)},ct.prototype.updateData=function(t){var e=this.context.gl;this.unbindVAO(),this.bind(),e.bufferSubData(e.ELEMENT_ARRAY_BUFFER,0,t.arrayBuffer)},ct.prototype.destroy=function(){var t=this.context.gl;this.buffer&&(t.deleteBuffer(this.buffer),delete this.buffer)};var ut={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"},ht=function(t,e,r,n){this.length=e.length,this.attributes=r,this.itemSize=e.bytesPerElement,this.dynamicDraw=n,this.context=t;var i=t.gl;this.buffer=i.createBuffer(),t.bindVertexBuffer.set(this.buffer),i.bufferData(i.ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?i.DYNAMIC_DRAW:i.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer};ht.prototype.bind=function(){this.context.bindVertexBuffer.set(this.buffer)},ht.prototype.updateData=function(t){var e=this.context.gl;this.bind(),e.bufferSubData(e.ARRAY_BUFFER,0,t.arrayBuffer)},ht.prototype.enableAttributes=function(t,e){for(var r=0;r<this.attributes.length;r++){var n=this.attributes[r],i=e.attributes[n.name];void 0!==i&&t.enableVertexAttribArray(i)}},ht.prototype.setVertexAttribPointers=function(t,e,r){for(var n=0;n<this.attributes.length;n++){var i=this.attributes[n],a=e.attributes[i.name];void 0!==a&&t.vertexAttribPointer(a,i.components,t[ut[i.type]],!1,this.itemSize,i.offset+this.itemSize*(r||0))}},ht.prototype.destroy=function(){var t=this.context.gl;this.buffer&&(t.deleteBuffer(this.buffer),delete this.buffer)};var ft=function(e){this.context=e,this.current=t.default$6.transparent};ft.prototype.get=function(){return this.current},ft.prototype.set=function(t){var e=this.current;t.r===e.r&&t.g===e.g&&t.b===e.b&&t.a===e.a||(this.context.gl.clearColor(t.r,t.g,t.b,t.a),this.current=t)};var pt=function(t){this.context=t,this.current=1};pt.prototype.get=function(){return this.current},pt.prototype.set=function(t){this.current!==t&&(this.context.gl.clearDepth(t),this.current=t)};var dt=function(t){this.context=t,this.current=0};dt.prototype.get=function(){return this.current},dt.prototype.set=function(t){this.current!==t&&(this.context.gl.clearStencil(t),this.current=t)};var gt=function(t){this.context=t,this.current=[!0,!0,!0,!0]};gt.prototype.get=function(){return this.current},gt.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(this.context.gl.colorMask(t[0],t[1],t[2],t[3]),this.current=t)};var vt=function(t){this.context=t,this.current=!0};vt.prototype.get=function(){return this.current},vt.prototype.set=function(t){this.current!==t&&(this.context.gl.depthMask(t),this.current=t)};var mt=function(t){this.context=t,this.current=255};mt.prototype.get=function(){return this.current},mt.prototype.set=function(t){this.current!==t&&(this.context.gl.stencilMask(t),this.current=t)};var yt=function(t){this.context=t,this.current={func:t.gl.ALWAYS,ref:0,mask:255}};yt.prototype.get=function(){return this.current},yt.prototype.set=function(t){var e=this.current;t.func===e.func&&t.ref===e.ref&&t.mask===e.mask||(this.context.gl.stencilFunc(t.func,t.ref,t.mask),this.current=t)};var xt=function(t){this.context=t;var e=this.context.gl;this.current=[e.KEEP,e.KEEP,e.KEEP]};xt.prototype.get=function(){return this.current},xt.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]||(this.context.gl.stencilOp(t[0],t[1],t[2]),this.current=t)};var bt=function(t){this.context=t,this.current=!1};bt.prototype.get=function(){return this.current},bt.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;t?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this.current=t}};var _t=function(t){this.context=t,this.current=[0,1]};_t.prototype.get=function(){return this.current},_t.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]||(this.context.gl.depthRange(t[0],t[1]),this.current=t)};var wt=function(t){this.context=t,this.current=!1};wt.prototype.get=function(){return this.current},wt.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;t?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this.current=t}};var kt=function(t){this.context=t,this.current=t.gl.LESS};kt.prototype.get=function(){return this.current},kt.prototype.set=function(t){this.current!==t&&(this.context.gl.depthFunc(t),this.current=t)};var At=function(t){this.context=t,this.current=!1};At.prototype.get=function(){return this.current},At.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;t?e.enable(e.BLEND):e.disable(e.BLEND),this.current=t}};var Mt=function(t){this.context=t;var e=this.context.gl;this.current=[e.ONE,e.ZERO]};Mt.prototype.get=function(){return this.current},Mt.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]||(this.context.gl.blendFunc(t[0],t[1]),this.current=t)};var Tt=function(e){this.context=e,this.current=t.default$6.transparent};Tt.prototype.get=function(){return this.current},Tt.prototype.set=function(t){var e=this.current;t.r===e.r&&t.g===e.g&&t.b===e.b&&t.a===e.a||(this.context.gl.blendColor(t.r,t.g,t.b,t.a),this.current=t)};var St=function(t){this.context=t,this.current=null};St.prototype.get=function(){return this.current},St.prototype.set=function(t){this.current!==t&&(this.context.gl.useProgram(t),this.current=t)};var Et=function(t){this.context=t,this.current=1};Et.prototype.get=function(){return this.current},Et.prototype.set=function(e){var r=this.context.lineWidthRange,n=t.clamp(e,r[0],r[1]);this.current!==n&&(this.context.gl.lineWidth(n),this.current=e)};var Ct=function(t){this.context=t,this.current=t.gl.TEXTURE0};Ct.prototype.get=function(){return this.current},Ct.prototype.set=function(t){this.current!==t&&(this.context.gl.activeTexture(t),this.current=t)};var Lt=function(t){this.context=t;var e=this.context.gl;this.current=[0,0,e.drawingBufferWidth,e.drawingBufferHeight]};Lt.prototype.get=function(){return this.current},Lt.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(this.context.gl.viewport(t[0],t[1],t[2],t[3]),this.current=t)};var zt=function(t){this.context=t,this.current=null};zt.prototype.get=function(){return this.current},zt.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindFramebuffer(e.FRAMEBUFFER,t),this.current=t}};var Ot=function(t){this.context=t,this.current=null};Ot.prototype.get=function(){return this.current},Ot.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindRenderbuffer(e.RENDERBUFFER,t),this.current=t}};var It=function(t){this.context=t,this.current=null};It.prototype.get=function(){return this.current},It.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindTexture(e.TEXTURE_2D,t),this.current=t}};var Dt=function(t){this.context=t,this.current=null};Dt.prototype.get=function(){return this.current},Dt.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindBuffer(e.ARRAY_BUFFER,t),this.current=t}};var Pt=function(t){this.context=t,this.current=null};Pt.prototype.get=function(){return this.current},Pt.prototype.set=function(t){var e=this.context.gl;e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t),this.current=t};var Rt=function(t){this.context=t,this.current=null};Rt.prototype.get=function(){return this.current},Rt.prototype.set=function(t){this.current!==t&&this.context.extVertexArrayObject&&(this.context.extVertexArrayObject.bindVertexArrayOES(t),this.current=t)};var Ft=function(t){this.context=t,this.current=4};Ft.prototype.get=function(){return this.current},Ft.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.pixelStorei(e.UNPACK_ALIGNMENT,t),this.current=t}};var Bt=function(t){this.context=t,this.current=!1};Bt.prototype.get=function(){return this.current},Bt.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t),this.current=t}};var Nt=function(t,e){this.context=t,this.current=null,this.parent=e};Nt.prototype.get=function(){return this.current};var jt=function(t){function e(e,r){t.call(this,e,r),this.dirty=!1}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.set=function(t){if(this.dirty||this.current!==t){var e=this.context.gl;this.context.bindFramebuffer.set(this.parent),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.current=t,this.dirty=!1}},e.prototype.setDirty=function(){this.dirty=!0},e}(Nt),Vt=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;this.context.bindFramebuffer.set(this.parent),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,t),this.current=t}},e}(Nt),Ut=function(t,e,r){this.context=t,this.width=e,this.height=r;var n=t.gl,i=this.framebuffer=n.createFramebuffer();this.colorAttachment=new jt(t,i),this.depthAttachment=new Vt(t,i)};Ut.prototype.destroy=function(){var t=this.context.gl,e=this.colorAttachment.get();e&&t.deleteTexture(e);var r=this.depthAttachment.get();r&&t.deleteRenderbuffer(r),t.deleteFramebuffer(this.framebuffer)};var qt=function(t,e,r){this.func=t,this.mask=e,this.range=r};qt.ReadOnly=!1,qt.ReadWrite=!0,qt.disabled=new qt(519,qt.ReadOnly,[0,1]);var Ht=function(t,e,r,n,i,a){this.test=t,this.ref=e,this.mask=r,this.fail=n,this.depthFail=i,this.pass=a};Ht.disabled=new Ht({func:519,mask:0},0,0,7680,7680,7680);var Gt=function(t,e,r){this.blendFunction=t,this.blendColor=e,this.mask=r};Gt.disabled=new Gt(Gt.Replace=[1,0],t.default$6.transparent,[!1,!1,!1,!1]),Gt.unblended=new Gt(Gt.Replace,t.default$6.transparent,[!0,!0,!0,!0]),Gt.alphaBlended=new Gt([1,771],t.default$6.transparent,[!0,!0,!0,!0]);var Yt=function(t){this.gl=t,this.extVertexArrayObject=this.gl.getExtension("OES_vertex_array_object"),this.lineWidthRange=t.getParameter(t.ALIASED_LINE_WIDTH_RANGE),this.clearColor=new ft(this),this.clearDepth=new pt(this),this.clearStencil=new dt(this),this.colorMask=new gt(this),this.depthMask=new vt(this),this.stencilMask=new mt(this),this.stencilFunc=new yt(this),this.stencilOp=new xt(this),this.stencilTest=new bt(this),this.depthRange=new _t(this),this.depthTest=new wt(this),this.depthFunc=new kt(this),this.blend=new At(this),this.blendFunc=new Mt(this),this.blendColor=new Tt(this),this.program=new St(this),this.lineWidth=new Et(this),this.activeTexture=new Ct(this),this.viewport=new Lt(this),this.bindFramebuffer=new zt(this),this.bindRenderbuffer=new Ot(this),this.bindTexture=new It(this),this.bindVertexBuffer=new Dt(this),this.bindElementBuffer=new Pt(this),this.bindVertexArrayOES=this.extVertexArrayObject&&new Rt(this),this.pixelStoreUnpack=new Ft(this),this.pixelStoreUnpackPremultiplyAlpha=new Bt(this),this.extTextureFilterAnisotropic=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=t.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT)),this.extTextureHalfFloat=t.getExtension("OES_texture_half_float"),this.extTextureHalfFloat&&t.getExtension("OES_texture_half_float_linear")};Yt.prototype.createIndexBuffer=function(t,e){return new ct(this,t,e)},Yt.prototype.createVertexBuffer=function(t,e,r){return new ht(this,t,e,r)},Yt.prototype.createRenderbuffer=function(t,e,r){var n=this.gl,i=n.createRenderbuffer();return this.bindRenderbuffer.set(i),n.renderbufferStorage(n.RENDERBUFFER,t,e,r),this.bindRenderbuffer.set(null),i},Yt.prototype.createFramebuffer=function(t,e){return new Ut(this,t,e)},Yt.prototype.clear=function(t){var e=t.color,r=t.depth,n=this.gl,i=0;e&&(i|=n.COLOR_BUFFER_BIT,this.clearColor.set(e),this.colorMask.set([!0,!0,!0,!0])),void 0!==r&&(i|=n.DEPTH_BUFFER_BIT,this.clearDepth.set(r),this.depthMask.set(!0)),n.clear(i)},Yt.prototype.setDepthMode=function(t){t.func!==this.gl.ALWAYS||t.mask?(this.depthTest.set(!0),this.depthFunc.set(t.func),this.depthMask.set(t.mask),this.depthRange.set(t.range)):this.depthTest.set(!1)},Yt.prototype.setStencilMode=function(t){t.test.func!==this.gl.ALWAYS||t.mask?(this.stencilTest.set(!0),this.stencilMask.set(t.mask),this.stencilOp.set([t.fail,t.depthFail,t.pass]),this.stencilFunc.set({func:t.test.func,ref:t.ref,mask:t.test.mask})):this.stencilTest.set(!1)},Yt.prototype.setColorMode=function(e){t.default$10(e.blendFunction,Gt.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(e.blendFunction),this.blendColor.set(e.blendColor)),this.colorMask.set(e.mask)};var Wt=function(e){function r(t,r,n){var i=this;e.call(this),this.id=t,this.dispatcher=n,this.on("data",function(t){"source"===t.dataType&&"metadata"===t.sourceDataType&&(i._sourceLoaded=!0),i._sourceLoaded&&!i._paused&&"source"===t.dataType&&"content"===t.sourceDataType&&(i.reload(),i.transform&&i.update(i.transform))}),this.on("error",function(){i._sourceErrored=!0}),this._source=it(t,r,n,this),this._tiles={},this._cache=new lt(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._maxTileCacheSize=null,this._isIdRenderable=this._isIdRenderable.bind(this),this._coveredTiles={}}return e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r,r.prototype.onAdd=function(t){this.map=t,this._maxTileCacheSize=t?t._maxTileCacheSize:null,this._source&&this._source.onAdd&&this._source.onAdd(t)},r.prototype.onRemove=function(t){this._source&&this._source.onRemove&&this._source.onRemove(t)},r.prototype.loaded=function(){if(this._sourceErrored)return!0;if(!this._sourceLoaded)return!1;for(var t in this._tiles){var e=this._tiles[t];if("loaded"!==e.state&&"errored"!==e.state)return!1}return!0},r.prototype.getSource=function(){return this._source},r.prototype.pause=function(){this._paused=!0},r.prototype.resume=function(){if(this._paused){var t=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,t&&this.reload(),this.transform&&this.update(this.transform)}},r.prototype._loadTile=function(t,e){return this._source.loadTile(t,e)},r.prototype._unloadTile=function(t){if(this._source.unloadTile)return this._source.unloadTile(t,function(){})},r.prototype._abortTile=function(t){if(this._source.abortTile)return this._source.abortTile(t,function(){})},r.prototype.serialize=function(){return this._source.serialize()},r.prototype.prepare=function(t){for(var e in this._source.prepare&&this._source.prepare(),this._tiles)this._tiles[e].upload(t)},r.prototype.getIds=function(){var e=this;return Object.keys(this._tiles).map(Number).sort(function(r,n){var i=e._tiles[r].tileID,a=e._tiles[n].tileID,o=new t.default$1(i.canonical.x,i.canonical.y).rotate(e.transform.angle),s=new t.default$1(a.canonical.x,a.canonical.y).rotate(e.transform.angle);return i.overscaledZ-a.overscaledZ||s.y-o.y||s.x-o.x})},r.prototype.getRenderableIds=function(){return this.getIds().filter(this._isIdRenderable)},r.prototype.hasRenderableParent=function(t){var e=this.findLoadedParent(t,0,{});return!!e&&this._isIdRenderable(e.tileID.key)},r.prototype._isIdRenderable=function(t){return this._tiles[t]&&this._tiles[t].hasData()&&!this._coveredTiles[t]},r.prototype.reload=function(){if(this._paused)this._shouldReloadOnResume=!0;else for(var t in this._cache.reset(),this._tiles)this._reloadTile(t,"reloading")},r.prototype._reloadTile=function(t,e){var r=this._tiles[t];r&&("loading"!==r.state&&(r.state=e),this._loadTile(r,this._tileLoaded.bind(this,r,t,e)))},r.prototype._tileLoaded=function(e,r,n,i){if(i)return e.state="errored",void(404!==i.status?this._source.fire(new t.ErrorEvent(i,{tile:e})):this.update(this.transform));e.timeAdded=a.now(),"expired"===n&&(e.refreshedUponExpiration=!0),this._setTileReloadTimer(r,e),"raster-dem"===this.getSource().type&&e.dem&&this._backfillDEM(e),this._source.fire(new t.Event("data",{dataType:"source",tile:e,coord:e.tileID})),this.map&&(this.map.painter.tileExtentVAO.vao=null)},r.prototype._backfillDEM=function(t){for(var e=this.getRenderableIds(),r=0;r<e.length;r++){var n=e[r];if(t.neighboringTiles&&t.neighboringTiles[n]){var i=this.getTileByID(n);a(t,i),a(i,t)}}function a(t,e){t.needsHillshadePrepare=!0;var r=e.tileID.canonical.x-t.tileID.canonical.x,n=e.tileID.canonical.y-t.tileID.canonical.y,i=Math.pow(2,t.tileID.canonical.z),a=e.tileID.key;0===r&&0===n||Math.abs(n)>1||(Math.abs(r)>1&&(1===Math.abs(r+i)?r+=i:1===Math.abs(r-i)&&(r-=i)),e.dem&&t.dem&&(t.dem.backfillBorder(e.dem,r,n),t.neighboringTiles&&t.neighboringTiles[a]&&(t.neighboringTiles[a].backfilled=!0)))}},r.prototype.getTile=function(t){return this.getTileByID(t.key)},r.prototype.getTileByID=function(t){return this._tiles[t]},r.prototype.getZoom=function(t){return t.zoom+t.scaleZoom(t.tileSize/this._source.tileSize)},r.prototype._findLoadedChildren=function(t,e,r){var n=!1;for(var i in this._tiles){var a=this._tiles[i];if(!(r[i]||!a.hasData()||a.tileID.overscaledZ<=t.overscaledZ||a.tileID.overscaledZ>e)){var o=Math.pow(2,a.tileID.canonical.z-t.canonical.z);if(Math.floor(a.tileID.canonical.x/o)===t.canonical.x&&Math.floor(a.tileID.canonical.y/o)===t.canonical.y)for(r[i]=a.tileID,n=!0;a&&a.tileID.overscaledZ-1>t.overscaledZ;){var s=a.tileID.scaledTo(a.tileID.overscaledZ-1);if(!s)break;(a=this._tiles[s.key])&&a.hasData()&&(delete r[i],r[s.key]=s)}}}return n},r.prototype.findLoadedParent=function(t,e,r){for(var n=t.overscaledZ-1;n>=e;n--){var i=t.scaledTo(n);if(!i)return;var a=String(i.key),o=this._tiles[a];if(o&&o.hasData())return r[a]=i,o;if(this._cache.has(i))return r[a]=i,this._cache.get(i)}},r.prototype.updateCacheSize=function(t){var e=(Math.ceil(t.width/this._source.tileSize)+1)*(Math.ceil(t.height/this._source.tileSize)+1),r=Math.floor(5*e),n="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,r):r;this._cache.setMaxSize(n)},r.prototype.handleWrapJump=function(t){var e=(t-(void 0===this._prevLng?t:this._prevLng))/360,r=Math.round(e);if(this._prevLng=t,r){var n={};for(var i in this._tiles){var a=this._tiles[i];a.tileID=a.tileID.unwrapTo(a.tileID.wrap+r),n[a.tileID.key]=a}for(var o in this._tiles=n,this._timers)clearTimeout(this._timers[o]),delete this._timers[o];for(var s in this._tiles){var l=this._tiles[s];this._setTileReloadTimer(s,l)}}},r.prototype.update=function(e){var n=this;if(this.transform=e,this._sourceLoaded&&!this._paused){var i;this.updateCacheSize(e),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used?this._source.tileID?i=e.getVisibleUnwrappedCoordinates(this._source.tileID).map(function(e){return new t.OverscaledTileID(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y)}):(i=e.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}),this._source.hasTile&&(i=i.filter(function(t){return n._source.hasTile(t)}))):i=[];var o,s=(this._source.roundZoom?Math.round:Math.floor)(this.getZoom(e)),l=Math.max(s-r.maxOverzooming,this._source.minzoom),c=Math.max(s+r.maxUnderzooming,this._source.minzoom),u=this._updateRetainedTiles(i,s),h={};if(Zt(this._source.type))for(var f=Object.keys(u),p=0;p<f.length;p++){var d=f[p],g=u[d],v=n._tiles[d];if(v&&(void 0===v.fadeEndTime||v.fadeEndTime>=a.now())){n._findLoadedChildren(g,c,u)&&(u[d]=g);var m=n.findLoadedParent(g,l,h);m&&n._addTile(m.tileID)}}for(o in h)u[o]||(n._coveredTiles[o]=!0);for(o in h)u[o]=h[o];for(var y=t.keysDifference(this._tiles,u),x=0;x<y.length;x++)n._removeTile(y[x])}},r.prototype._updateRetainedTiles=function(t,e){for(var n={},i={},a=Math.max(e-r.maxOverzooming,this._source.minzoom),o=Math.max(e+r.maxUnderzooming,this._source.minzoom),s=0;s<t.length;s++){var l=t[s],c=this._addTile(l),u=!1;if(c.hasData())n[l.key]=l;else{u=c.wasRequested(),n[l.key]=l;var h=!0;if(e+1>this._source.maxzoom){var f=l.children(this._source.maxzoom)[0],p=this.getTile(f);p&&p.hasData()?n[f.key]=f:h=!1}else{this._findLoadedChildren(l,o,n);for(var d=l.children(this._source.maxzoom),g=0;g<d.length;g++)if(!n[d[g].key]){h=!1;break}}if(!h)for(var v=l.overscaledZ-1;v>=a;--v){var m=l.scaledTo(v);if(i[m.key])break;if(i[m.key]=!0,!(c=this.getTile(m))&&u&&(c=this._addTile(m)),c&&(n[m.key]=m,u=c.wasRequested(),c.hasData()))break}}}return n},r.prototype._addTile=function(e){var r=this._tiles[e.key];if(r)return r;(r=this._cache.getAndRemove(e))&&(this._setTileReloadTimer(e.key,r),r.tileID=e);var n=Boolean(r);return n||(r=new st(e,this._source.tileSize*e.overscaleFactor()),this._loadTile(r,this._tileLoaded.bind(this,r,e.key,r.state))),r?(r.uses++,this._tiles[e.key]=r,n||this._source.fire(new t.Event("dataloading",{tile:r,coord:r.tileID,dataType:"source"})),r):null},r.prototype._setTileReloadTimer=function(t,e){var r=this;t in this._timers&&(clearTimeout(this._timers[t]),delete this._timers[t]);var n=e.getExpiryTimeout();n&&(this._timers[t]=setTimeout(function(){r._reloadTile(t,"expired"),delete r._timers[t]},n))},r.prototype._removeTile=function(t){var e=this._tiles[t];e&&(e.uses--,delete this._tiles[t],this._timers[t]&&(clearTimeout(this._timers[t]),delete this._timers[t]),e.uses>0||(e.hasData()?this._cache.add(e.tileID,e,e.getExpiryTimeout()):(e.aborted=!0,this._abortTile(e),this._unloadTile(e))))},r.prototype.clearTiles=function(){for(var t in this._shouldReloadOnResume=!1,this._paused=!1,this._tiles)this._removeTile(t);this._cache.reset()},r.prototype.tilesIn=function(e,r){for(var n=[],i=this.getIds(),a=1/0,o=1/0,s=-1/0,l=-1/0,c=e[0].zoom,u=0;u<e.length;u++){var h=e[u];a=Math.min(a,h.column),o=Math.min(o,h.row),s=Math.max(s,h.column),l=Math.max(l,h.row)}for(var f=0;f<i.length;f++){var p=this._tiles[i[f]],d=p.tileID,g=Math.pow(2,this.transform.zoom-p.tileID.overscaledZ),v=r*p.queryPadding*t.default$8/p.tileSize/g,m=[Xt(d,new t.default$17(a,o,c)),Xt(d,new t.default$17(s,l,c))];if(m[0].x-v<t.default$8&&m[0].y-v<t.default$8&&m[1].x+v>=0&&m[1].y+v>=0){for(var y=[],x=0;x<e.length;x++)y.push(Xt(d,e[x]));n.push({tile:p,tileID:d,queryGeometry:[y],scale:g})}}return n},r.prototype.getVisibleCoordinates=function(){for(var t=this,e=this.getRenderableIds().map(function(e){return t._tiles[e].tileID}),r=0,n=e;r<n.length;r+=1){var i=n[r];i.posMatrix=t.transform.calculatePosMatrix(i.toUnwrapped())}return e},r.prototype.hasTransition=function(){if(this._source.hasTransition())return!0;if(Zt(this._source.type))for(var t in this._tiles){var e=this._tiles[t];if(void 0!==e.fadeEndTime&&e.fadeEndTime>=a.now())return!0}return!1},r}(t.Evented);function Xt(e,r){var n=r.zoomTo(e.canonical.z);return new t.default$1((n.column-(e.canonical.x+e.wrap*Math.pow(2,e.canonical.z)))*t.default$8,(n.row-e.canonical.y)*t.default$8)}function Zt(t){return"raster"===t||"image"===t||"video"===t}function $t(){return new t.default.Worker(En.workerUrl)}Wt.maxOverzooming=10,Wt.maxUnderzooming=3;var Jt,Kt=function(){this.active={}};function Qt(e,r){var n={};for(var i in e)"ref"!==i&&(n[i]=e[i]);return t.default$18.forEach(function(t){t in r&&(n[t]=r[t])}),n}function te(t){t=t.slice();for(var e=Object.create(null),r=0;r<t.length;r++)e[t[r].id]=t[r];for(var n=0;n<t.length;n++)"ref"in t[n]&&(t[n]=Qt(t[n],e[t[n].ref]));return t}Kt.prototype.acquire=function(t){if(!this.workers){var e=En.workerCount;for(this.workers=[];this.workers.length<e;)this.workers.push(new $t)}return this.active[t]=!0,this.workers.slice()},Kt.prototype.release=function(t){delete this.active[t],0===Object.keys(this.active).length&&(this.workers.forEach(function(t){t.terminate()}),this.workers=null)};var ee={setStyle:"setStyle",addLayer:"addLayer",removeLayer:"removeLayer",setPaintProperty:"setPaintProperty",setLayoutProperty:"setLayoutProperty",setFilter:"setFilter",addSource:"addSource",removeSource:"removeSource",setGeoJSONSourceData:"setGeoJSONSourceData",setLayerZoomRange:"setLayerZoomRange",setLayerProperty:"setLayerProperty",setCenter:"setCenter",setZoom:"setZoom",setBearing:"setBearing",setPitch:"setPitch",setSprite:"setSprite",setGlyphs:"setGlyphs",setTransition:"setTransition",setLight:"setLight"};function re(t,e,r){r.push({command:ee.addSource,args:[t,e[t]]})}function ne(t,e,r){e.push({command:ee.removeSource,args:[t]}),r[t]=!0}function ie(t,e,r,n){ne(t,r,n),re(t,e,r)}function ae(e,r,n){var i;for(i in e[n])if(e[n].hasOwnProperty(i)&&"data"!==i&&!t.default$10(e[n][i],r[n][i]))return!1;for(i in r[n])if(r[n].hasOwnProperty(i)&&"data"!==i&&!t.default$10(e[n][i],r[n][i]))return!1;return!0}function oe(e,r,n,i,a,o){var s;for(s in r=r||{},e=e||{})e.hasOwnProperty(s)&&(t.default$10(e[s],r[s])||n.push({command:o,args:[i,s,r[s],a]}));for(s in r)r.hasOwnProperty(s)&&!e.hasOwnProperty(s)&&(t.default$10(e[s],r[s])||n.push({command:o,args:[i,s,r[s],a]}))}function se(t){return t.id}function le(t,e){return t[e.id]=e,t}var ce=function(t,e,r){var n=this.boxCells=[],i=this.circleCells=[];this.xCellCount=Math.ceil(t/r),this.yCellCount=Math.ceil(e/r);for(var a=0;a<this.xCellCount*this.yCellCount;a++)n.push([]),i.push([]);this.circleKeys=[],this.boxKeys=[],this.bboxes=[],this.circles=[],this.width=t,this.height=e,this.xScale=this.xCellCount/t,this.yScale=this.yCellCount/e,this.boxUid=0,this.circleUid=0};ce.prototype.keysLength=function(){return this.boxKeys.length+this.circleKeys.length},ce.prototype.insert=function(t,e,r,n,i){this._forEachCell(e,r,n,i,this._insertBoxCell,this.boxUid++),this.boxKeys.push(t),this.bboxes.push(e),this.bboxes.push(r),this.bboxes.push(n),this.bboxes.push(i)},ce.prototype.insertCircle=function(t,e,r,n){this._forEachCell(e-n,r-n,e+n,r+n,this._insertCircleCell,this.circleUid++),this.circleKeys.push(t),this.circles.push(e),this.circles.push(r),this.circles.push(n)},ce.prototype._insertBoxCell=function(t,e,r,n,i,a){this.boxCells[i].push(a)},ce.prototype._insertCircleCell=function(t,e,r,n,i,a){this.circleCells[i].push(a)},ce.prototype._query=function(t,e,r,n,i){if(r<0||t>this.width||n<0||e>this.height)return!i&&[];var a=[];if(t<=0&&e<=0&&this.width<=r&&this.height<=n){if(i)return!0;for(var o=0;o<this.boxKeys.length;o++)a.push({key:this.boxKeys[o],x1:this.bboxes[4*o],y1:this.bboxes[4*o+1],x2:this.bboxes[4*o+2],y2:this.bboxes[4*o+3]});for(var s=0;s<this.circleKeys.length;s++){var l=this.circles[3*s],c=this.circles[3*s+1],u=this.circles[3*s+2];a.push({key:this.circleKeys[s],x1:l-u,y1:c-u,x2:l+u,y2:c+u})}}else{var h={hitTest:i,seenUids:{box:{},circle:{}}};this._forEachCell(t,e,r,n,this._queryCell,a,h)}return i?a.length>0:a},ce.prototype._queryCircle=function(t,e,r,n){var i=t-r,a=t+r,o=e-r,s=e+r;if(a<0||i>this.width||s<0||o>this.height)return!n&&[];var l=[],c={hitTest:n,circle:{x:t,y:e,radius:r},seenUids:{box:{},circle:{}}};return this._forEachCell(i,o,a,s,this._queryCellCircle,l,c),n?l.length>0:l},ce.prototype.query=function(t,e,r,n){return this._query(t,e,r,n,!1)},ce.prototype.hitTest=function(t,e,r,n){return this._query(t,e,r,n,!0)},ce.prototype.hitTestCircle=function(t,e,r){return this._queryCircle(t,e,r,!0)},ce.prototype._queryCell=function(t,e,r,n,i,a,o){var s=o.seenUids,l=this.boxCells[i];if(null!==l)for(var c=this.bboxes,u=0,h=l;u<h.length;u+=1){var f=h[u];if(!s.box[f]){s.box[f]=!0;var p=4*f;if(t<=c[p+2]&&e<=c[p+3]&&r>=c[p+0]&&n>=c[p+1]){if(o.hitTest)return a.push(!0),!0;a.push({key:this.boxKeys[f],x1:c[p],y1:c[p+1],x2:c[p+2],y2:c[p+3]})}}}var d=this.circleCells[i];if(null!==d)for(var g=this.circles,v=0,m=d;v<m.length;v+=1){var y=m[v];if(!s.circle[y]){s.circle[y]=!0;var x=3*y;if(this._circleAndRectCollide(g[x],g[x+1],g[x+2],t,e,r,n)){if(o.hitTest)return a.push(!0),!0;var b=g[x],_=g[x+1],w=g[x+2];a.push({key:this.circleKeys[y],x1:b-w,y1:_-w,x2:b+w,y2:_+w})}}}},ce.prototype._queryCellCircle=function(t,e,r,n,i,a,o){var s=o.circle,l=o.seenUids,c=this.boxCells[i];if(null!==c)for(var u=this.bboxes,h=0,f=c;h<f.length;h+=1){var p=f[h];if(!l.box[p]){l.box[p]=!0;var d=4*p;if(this._circleAndRectCollide(s.x,s.y,s.radius,u[d+0],u[d+1],u[d+2],u[d+3]))return a.push(!0),!0}}var g=this.circleCells[i];if(null!==g)for(var v=this.circles,m=0,y=g;m<y.length;m+=1){var x=y[m];if(!l.circle[x]){l.circle[x]=!0;var b=3*x;if(this._circlesCollide(v[b],v[b+1],v[b+2],s.x,s.y,s.radius))return a.push(!0),!0}}},ce.prototype._forEachCell=function(t,e,r,n,i,a,o){for(var s=this._convertToXCellCoord(t),l=this._convertToYCellCoord(e),c=this._convertToXCellCoord(r),u=this._convertToYCellCoord(n),h=s;h<=c;h++)for(var f=l;f<=u;f++){var p=this.xCellCount*f+h;if(i.call(this,t,e,r,n,p,a,o))return}},ce.prototype._convertToXCellCoord=function(t){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(t*this.xScale)))},ce.prototype._convertToYCellCoord=function(t){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(t*this.yScale)))},ce.prototype._circlesCollide=function(t,e,r,n,i,a){var o=n-t,s=i-e,l=r+a;return l*l>o*o+s*s},ce.prototype._circleAndRectCollide=function(t,e,r,n,i,a,o){var s=(a-n)/2,l=Math.abs(t-(n+s));if(l>s+r)return!1;var c=(o-i)/2,u=Math.abs(e-(i+c));if(u>c+r)return!1;if(l<=s||u<=c)return!0;var h=l-s,f=u-c;return h*h+f*f<=r*r};var ue=t.default$19.layout;function he(e,r,n,i,a){var o=t.mat4.identity(new Float32Array(16));return r?(t.mat4.identity(o),t.mat4.scale(o,o,[1/a,1/a,1]),n||t.mat4.rotateZ(o,o,i.angle)):(t.mat4.scale(o,o,[i.width/2,-i.height/2,1]),t.mat4.translate(o,o,[1,-1,0]),t.mat4.multiply(o,o,e)),o}function fe(e,r,n,i,a){var o=t.mat4.identity(new Float32Array(16));return r?(t.mat4.multiply(o,o,e),t.mat4.scale(o,o,[a,a,1]),n||t.mat4.rotateZ(o,o,-i.angle)):(t.mat4.scale(o,o,[1,-1,1]),t.mat4.translate(o,o,[-1,-1,0]),t.mat4.scale(o,o,[2/i.width,2/i.height,1])),o}function pe(e,r){var n=[e.x,e.y,0,1];ke(n,n,r);var i=n[3];return{point:new t.default$1(n[0]/i,n[1]/i),signedDistanceFromCamera:i}}function de(t,e){var r=t[0]/t[3],n=t[1]/t[3];return r>=-e[0]&&r<=e[0]&&n>=-e[1]&&n<=e[1]}function ge(e,r,n,i,a,o,s,l){var c=i?e.textSizeData:e.iconSizeData,u=t.evaluateSizeForZoom(c,n.transform.zoom,ue.properties[i?"text-size":"icon-size"]),h=[256/n.width*2+1,256/n.height*2+1],f=i?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;f.clear();for(var p=e.lineVertexArray,d=i?e.text.placedSymbolArray:e.icon.placedSymbolArray,g=n.transform.width/n.transform.height,v=!1,m=0;m<d.length;m++){var y=d.get(m);if(y.hidden||y.writingMode===t.WritingMode.vertical&&!v)we(y.numGlyphs,f);else{v=!1;var x=[y.anchorX,y.anchorY,0,1];if(t.vec4.transformMat4(x,x,r),de(x,h)){var b=.5+x[3]/n.transform.cameraToCenterDistance*.5,_=t.evaluateSizeForFeature(c,u,y),w=s?_*b:_/b,k=new t.default$1(y.anchorX,y.anchorY),A=pe(k,a).point,M={},T=ye(y,w,!1,l,r,a,o,e.glyphOffsetArray,p,f,A,k,M,g);v=T.useVertical,(T.notEnoughRoom||v||T.needsFlipping&&ye(y,w,!0,l,r,a,o,e.glyphOffsetArray,p,f,A,k,M,g).notEnoughRoom)&&we(y.numGlyphs,f)}else we(y.numGlyphs,f)}}i?e.text.dynamicLayoutVertexBuffer.updateData(f):e.icon.dynamicLayoutVertexBuffer.updateData(f)}function ve(t,e,r,n,i,a,o,s,l,c,u,h){var f=s.glyphStartIndex+s.numGlyphs,p=s.lineStartIndex,d=s.lineStartIndex+s.lineLength,g=e.getoffsetX(s.glyphStartIndex),v=e.getoffsetX(f-1),m=be(t*g,r,n,i,a,o,s.segment,p,d,l,c,u,h);if(!m)return null;var y=be(t*v,r,n,i,a,o,s.segment,p,d,l,c,u,h);return y?{first:m,last:y}:null}function me(e,r,n,i){return e===t.WritingMode.horizontal&&Math.abs(n.y-r.y)>Math.abs(n.x-r.x)*i?{useVertical:!0}:(e===t.WritingMode.vertical?r.y<n.y:r.x>n.x)?{needsFlipping:!0}:null}function ye(e,r,n,i,a,o,s,l,c,u,h,f,p,d){var g,v=r/24,m=e.lineOffsetX*r,y=e.lineOffsetY*r;if(e.numGlyphs>1){var x=e.glyphStartIndex+e.numGlyphs,b=e.lineStartIndex,_=e.lineStartIndex+e.lineLength,w=ve(v,l,m,y,n,h,f,e,c,o,p,!1);if(!w)return{notEnoughRoom:!0};var k=pe(w.first.point,s).point,A=pe(w.last.point,s).point;if(i&&!n){var M=me(e.writingMode,k,A,d);if(M)return M}g=[w.first];for(var T=e.glyphStartIndex+1;T<x-1;T++)g.push(be(v*l.getoffsetX(T),m,y,n,h,f,e.segment,b,_,c,o,p,!1));g.push(w.last)}else{if(i&&!n){var S=pe(f,a).point,E=e.lineStartIndex+e.segment+1,C=new t.default$1(c.getx(E),c.gety(E)),L=pe(C,a),z=L.signedDistanceFromCamera>0?L.point:xe(f,C,S,1,a),O=me(e.writingMode,S,z,d);if(O)return O}var I=be(v*l.getoffsetX(e.glyphStartIndex),m,y,n,h,f,e.segment,e.lineStartIndex,e.lineStartIndex+e.lineLength,c,o,p,!1);if(!I)return{notEnoughRoom:!0};g=[I]}for(var D=0,P=g;D<P.length;D+=1){var R=P[D];t.addDynamicAttributes(u,R.point,R.angle)}return{}}function xe(t,e,r,n,i){var a=pe(t.add(t.sub(e)._unit()),i).point,o=r.sub(a);return r.add(o._mult(n/o.mag()))}function be(e,r,n,i,a,o,s,l,c,u,h,f,p){var d=i?e-r:e+r,g=d>0?1:-1,v=0;i&&(g*=-1,v=Math.PI),g<0&&(v+=Math.PI);for(var m=g>0?l+s:l+s+1,y=m,x=a,b=a,_=0,w=0,k=Math.abs(d);_+w<=k;){if((m+=g)<l||m>=c)return null;if(b=x,void 0===(x=f[m])){var A=new t.default$1(u.getx(m),u.gety(m)),M=pe(A,h);if(M.signedDistanceFromCamera>0)x=f[m]=M.point;else{var T=m-g;x=xe(0===_?o:new t.default$1(u.getx(T),u.gety(T)),A,b,k-_+1,h)}}_+=w,w=b.dist(x)}var S=(k-_)/w,E=x.sub(b),C=E.mult(S)._add(b);return C._add(E._unit()._perp()._mult(n*g)),{point:C,angle:v+Math.atan2(x.y-b.y,x.x-b.x),tileDistance:p?{prevTileDistance:m-g===y?0:u.gettileUnitDistanceFromAnchor(m-g),lastSegmentViewportDistance:k-_}:null}}var _e=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function we(t,e){for(var r=0;r<t;r++){var n=e.length;e.resize(n+4),e.float32.set(_e,3*n)}}function ke(t,e,r){var n=e[0],i=e[1];return t[0]=r[0]*n+r[4]*i+r[12],t[1]=r[1]*n+r[5]*i+r[13],t[3]=r[3]*n+r[7]*i+r[15],t}t.default$20.mat4;var Ae=function(t,e,r){void 0===e&&(e=new ce(t.width+200,t.height+200,25)),void 0===r&&(r=new ce(t.width+200,t.height+200,25)),this.transform=t,this.grid=e,this.ignoredGrid=r,this.pitchfactor=Math.cos(t._pitch)*t.cameraToCenterDistance,this.screenRightBoundary=t.width+100,this.screenBottomBoundary=t.height+100};function Me(t,e,r){t[e+4]=r?1:0}function Te(e,r,n){return r*(t.default$8/(e.tileSize*Math.pow(2,n-e.tileID.overscaledZ)))}Ae.prototype.placeCollisionBox=function(t,e,r,n){var i=this.projectAndGetPerspectiveRatio(n,t.anchorPointX,t.anchorPointY),a=r*i.perspectiveRatio,o=t.x1*a+i.point.x,s=t.y1*a+i.point.y,l=t.x2*a+i.point.x,c=t.y2*a+i.point.y;return!e&&this.grid.hitTest(o,s,l,c)?{box:[],offscreen:!1}:{box:[o,s,l,c],offscreen:this.isOffscreen(o,s,l,c)}},Ae.prototype.approximateTileDistance=function(t,e,r,n,i){var a=i?1:n/this.pitchfactor,o=t.lastSegmentViewportDistance*r;return t.prevTileDistance+o+(a-1)*o*Math.abs(Math.sin(e))},Ae.prototype.placeCollisionCircles=function(e,r,n,i,a,o,s,l,c,u,h,f,p){var d=[],g=this.projectAnchor(u,o.anchorX,o.anchorY),v=c/24,m=o.lineOffsetX*c,y=o.lineOffsetY*c,x=new t.default$1(o.anchorX,o.anchorY),b=ve(v,l,m,y,!1,pe(x,h).point,x,o,s,h,{},!0),_=!1,w=!0,k=g.perspectiveRatio*i,A=1/(i*n),M=0,T=0;b&&(M=this.approximateTileDistance(b.first.tileDistance,b.first.angle,A,g.cameraDistance,p),T=this.approximateTileDistance(b.last.tileDistance,b.last.angle,A,g.cameraDistance,p));for(var S=0;S<e.length;S+=5){var E=e[S],C=e[S+1],L=e[S+2],z=e[S+3];if(!b||z<-M||z>T)Me(e,S,!1);else{var O=this.projectPoint(u,E,C),I=L*k;if(d.length>0){var D=O.x-d[d.length-4],P=O.y-d[d.length-3];if(I*I*2>D*D+P*P&&S+8<e.length){var R=e[S+8];if(R>-M&&R<T){Me(e,S,!1);continue}}}var F=S/5;if(d.push(O.x,O.y,I,F),Me(e,S,!0),w=w&&this.isOffscreen(O.x-I,O.y-I,O.x+I,O.y+I),!r&&this.grid.hitTestCircle(O.x,O.y,I)){if(!f)return{circles:[],offscreen:!1};_=!0}}}return{circles:_?[]:d,offscreen:w}},Ae.prototype.queryRenderedSymbols=function(e){if(0===e.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return{};for(var r=[],n=1/0,i=1/0,a=-1/0,o=-1/0,s=0,l=e;s<l.length;s+=1){var c=l[s],u=new t.default$1(c.x+100,c.y+100);n=Math.min(n,u.x),i=Math.min(i,u.y),a=Math.max(a,u.x),o=Math.max(o,u.y),r.push(u)}for(var h={},f={},p=0,d=this.grid.query(n,i,a,o).concat(this.ignoredGrid.query(n,i,a,o));p<d.length;p+=1){var g=d[p],v=g.key;if(void 0===h[v.bucketInstanceId]&&(h[v.bucketInstanceId]={}),!h[v.bucketInstanceId][v.featureIndex]){var m=[new t.default$1(g.x1,g.y1),new t.default$1(g.x2,g.y1),new t.default$1(g.x2,g.y2),new t.default$1(g.x1,g.y2)];t.polygonIntersectsPolygon(r,m)&&(h[v.bucketInstanceId][v.featureIndex]=!0,void 0===f[v.bucketInstanceId]&&(f[v.bucketInstanceId]=[]),f[v.bucketInstanceId].push(v.featureIndex))}}return f},Ae.prototype.insertCollisionBox=function(t,e,r,n){var i={bucketInstanceId:r,featureIndex:n};(e?this.ignoredGrid:this.grid).insert(i,t[0],t[1],t[2],t[3])},Ae.prototype.insertCollisionCircles=function(t,e,r,n){for(var i=e?this.ignoredGrid:this.grid,a={bucketInstanceId:r,featureIndex:n},o=0;o<t.length;o+=4)i.insertCircle(a,t[o],t[o+1],t[o+2])},Ae.prototype.projectAnchor=function(t,e,r){var n=[e,r,0,1];return ke(n,n,t),{perspectiveRatio:.5+this.transform.cameraToCenterDistance/n[3]*.5,cameraDistance:n[3]}},Ae.prototype.projectPoint=function(e,r,n){var i=[r,n,0,1];return ke(i,i,e),new t.default$1((i[0]/i[3]+1)/2*this.transform.width+100,(-i[1]/i[3]+1)/2*this.transform.height+100)},Ae.prototype.projectAndGetPerspectiveRatio=function(e,r,n){var i=[r,n,0,1];return ke(i,i,e),{point:new t.default$1((i[0]/i[3]+1)/2*this.transform.width+100,(-i[1]/i[3]+1)/2*this.transform.height+100),perspectiveRatio:.5+this.transform.cameraToCenterDistance/i[3]*.5}},Ae.prototype.isOffscreen=function(t,e,r,n){return r<100||t>=this.screenRightBoundary||n<100||e>this.screenBottomBoundary};var Se=t.default$19.layout,Ee=function(t,e,r,n){this.opacity=t?Math.max(0,Math.min(1,t.opacity+(t.placed?e:-e))):n&&r?1:0,this.placed=r};Ee.prototype.isHidden=function(){return 0===this.opacity&&!this.placed};var Ce=function(t,e,r,n,i){this.text=new Ee(t?t.text:null,e,r,i),this.icon=new Ee(t?t.icon:null,e,n,i)};Ce.prototype.isHidden=function(){return this.text.isHidden()&&this.icon.isHidden()};var Le=function(t,e,r){this.text=t,this.icon=e,this.skipFade=r},ze=function(t,e){this.transform=t.clone(),this.collisionIndex=new Ae(this.transform),this.placements={},this.opacities={},this.stale=!1,this.fadeDuration=e,this.retainedQueryData={}};function Oe(t,e,r){t.emplaceBack(e?1:0,r?1:0),t.emplaceBack(e?1:0,r?1:0),t.emplaceBack(e?1:0,r?1:0),t.emplaceBack(e?1:0,r?1:0)}ze.prototype.placeLayerTile=function(e,r,n,i){var a=r.getBucket(e),o=r.latestFeatureIndex;if(a&&o&&e.id===a.layerIds[0]){var s=r.collisionBoxArray,l=a.layers[0].layout,c=Math.pow(2,this.transform.zoom-r.tileID.overscaledZ),u=r.tileSize/t.default$8,h=this.transform.calculatePosMatrix(r.tileID.toUnwrapped()),f=he(h,"map"===l.get("text-pitch-alignment"),"map"===l.get("text-rotation-alignment"),this.transform,Te(r,1,this.transform.zoom)),p=he(h,"map"===l.get("icon-pitch-alignment"),"map"===l.get("icon-rotation-alignment"),this.transform,Te(r,1,this.transform.zoom));this.retainedQueryData[a.bucketInstanceId]=new function(t,e,r,n,i){this.bucketInstanceId=t,this.featureIndex=e,this.sourceLayerIndex=r,this.bucketIndex=n,this.tileID=i}(a.bucketInstanceId,o,a.sourceLayerIndex,a.index,r.tileID),this.placeLayerBucket(a,h,f,p,c,u,n,i,s)}},ze.prototype.placeLayerBucket=function(e,r,n,i,a,o,s,l,c){for(var u=e.layers[0].layout,h=t.evaluateSizeForZoom(e.textSizeData,this.transform.zoom,Se.properties["text-size"]),f=!e.hasTextData()||u.get("text-optional"),p=!e.hasIconData()||u.get("icon-optional"),d=0,g=e.symbolInstances;d<g.length;d+=1){var v=g[d];if(!l[v.crossTileID]){var m=void 0!==v.feature.text,y=void 0!==v.feature.icon,x=!0,b=null,_=null,w=null,k=0,A=0;v.collisionArrays||(v.collisionArrays=e.deserializeCollisionBoxes(c,v.textBoxStartIndex,v.textBoxEndIndex,v.iconBoxStartIndex,v.iconBoxEndIndex)),v.collisionArrays.textFeatureIndex&&(k=v.collisionArrays.textFeatureIndex),v.collisionArrays.textBox&&(m=(b=this.collisionIndex.placeCollisionBox(v.collisionArrays.textBox,u.get("text-allow-overlap"),o,r)).box.length>0,x=x&&b.offscreen);var M=v.collisionArrays.textCircles;if(M){var T=e.text.placedSymbolArray.get(v.placedTextSymbolIndices[0]),S=t.evaluateSizeForFeature(e.textSizeData,h,T);_=this.collisionIndex.placeCollisionCircles(M,u.get("text-allow-overlap"),a,o,v.key,T,e.lineVertexArray,e.glyphOffsetArray,S,r,n,s,"map"===u.get("text-pitch-alignment")),m=u.get("text-allow-overlap")||_.circles.length>0,x=x&&_.offscreen}v.collisionArrays.iconFeatureIndex&&(A=v.collisionArrays.iconFeatureIndex),v.collisionArrays.iconBox&&(y=(w=this.collisionIndex.placeCollisionBox(v.collisionArrays.iconBox,u.get("icon-allow-overlap"),o,r)).box.length>0,x=x&&w.offscreen),f||p?p?f||(y=y&&m):m=y&&m:y=m=y&&m,m&&b&&this.collisionIndex.insertCollisionBox(b.box,u.get("text-ignore-placement"),e.bucketInstanceId,k),y&&w&&this.collisionIndex.insertCollisionBox(w.box,u.get("icon-ignore-placement"),e.bucketInstanceId,A),m&&_&&this.collisionIndex.insertCollisionCircles(_.circles,u.get("text-ignore-placement"),e.bucketInstanceId,k),this.placements[v.crossTileID]=new Le(m,y,x||e.justReloaded),l[v.crossTileID]=!0}}e.justReloaded=!1},ze.prototype.commit=function(t,e){this.commitTime=e;var r=!1,n=t&&0!==this.fadeDuration?(this.commitTime-t.commitTime)/this.fadeDuration:1,i=t?t.opacities:{};for(var a in this.placements){var o=this.placements[a],s=i[a];s?(this.opacities[a]=new Ce(s,n,o.text,o.icon),r=r||o.text!==s.text.placed||o.icon!==s.icon.placed):(this.opacities[a]=new Ce(null,n,o.text,o.icon,o.skipFade),r=r||o.text||o.icon)}for(var l in i){var c=i[l];if(!this.opacities[l]){var u=new Ce(c,n,!1,!1);u.isHidden()||(this.opacities[l]=u,r=r||c.text.placed||c.icon.placed)}}r?this.lastPlacementChangeTime=e:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=t?t.lastPlacementChangeTime:e)},ze.prototype.updateLayerOpacities=function(t,e){for(var r={},n=0,i=e;n<i.length;n+=1){var a=i[n],o=a.getBucket(t);o&&a.latestFeatureIndex&&t.id===o.layerIds[0]&&this.updateBucketOpacities(o,r,a.collisionBoxArray)}},ze.prototype.updateBucketOpacities=function(t,e,r){t.hasTextData()&&t.text.opacityVertexArray.clear(),t.hasIconData()&&t.icon.opacityVertexArray.clear(),t.hasCollisionBoxData()&&t.collisionBox.collisionVertexArray.clear(),t.hasCollisionCircleData()&&t.collisionCircle.collisionVertexArray.clear();for(var n=t.layers[0].layout,i=new Ce(null,0,!1,!1,!0),a=new Ce(null,0,n.get("text-allow-overlap"),n.get("icon-allow-overlap"),!0),o=0;o<t.symbolInstances.length;o++){var s=t.symbolInstances[o],l=e[s.crossTileID],c=this.opacities[s.crossTileID];l?c=i:c||(c=a,this.opacities[s.crossTileID]=c),e[s.crossTileID]=!0;var u=s.numGlyphVertices>0||s.numVerticalGlyphVertices>0,h=s.numIconVertices>0;if(u){for(var f=je(c.text),p=(s.numGlyphVertices+s.numVerticalGlyphVertices)/4,d=0;d<p;d++)t.text.opacityVertexArray.emplaceBack(f);for(var g=0,v=s.placedTextSymbolIndices;g<v.length;g+=1){var m=v[g];t.text.placedSymbolArray.get(m).hidden=c.text.isHidden()}}if(h){for(var y=je(c.icon),x=0;x<s.numIconVertices/4;x++)t.icon.opacityVertexArray.emplaceBack(y);t.icon.placedSymbolArray.get(o).hidden=c.icon.isHidden()}s.collisionArrays||(s.collisionArrays=t.deserializeCollisionBoxes(r,s.textBoxStartIndex,s.textBoxEndIndex,s.iconBoxStartIndex,s.iconBoxEndIndex));var b=s.collisionArrays;if(b){b.textBox&&t.hasCollisionBoxData()&&Oe(t.collisionBox.collisionVertexArray,c.text.placed,!1),b.iconBox&&t.hasCollisionBoxData()&&Oe(t.collisionBox.collisionVertexArray,c.icon.placed,!1);var _=b.textCircles;if(_&&t.hasCollisionCircleData())for(var w=0;w<_.length;w+=5){var k=l||0===_[w+4];Oe(t.collisionCircle.collisionVertexArray,c.text.placed,k)}}}t.sortFeatures(this.transform.angle),this.retainedQueryData[t.bucketInstanceId]&&(this.retainedQueryData[t.bucketInstanceId].featureSortOrder=t.featureSortOrder),t.hasTextData()&&t.text.opacityVertexBuffer&&t.text.opacityVertexBuffer.updateData(t.text.opacityVertexArray),t.hasIconData()&&t.icon.opacityVertexBuffer&&t.icon.opacityVertexBuffer.updateData(t.icon.opacityVertexArray),t.hasCollisionBoxData()&&t.collisionBox.collisionVertexBuffer&&t.collisionBox.collisionVertexBuffer.updateData(t.collisionBox.collisionVertexArray),t.hasCollisionCircleData()&&t.collisionCircle.collisionVertexBuffer&&t.collisionCircle.collisionVertexBuffer.updateData(t.collisionCircle.collisionVertexArray)},ze.prototype.symbolFadeChange=function(t){return 0===this.fadeDuration?1:(t-this.commitTime)/this.fadeDuration},ze.prototype.hasTransitions=function(t){return this.stale||t-this.lastPlacementChangeTime<this.fadeDuration},ze.prototype.stillRecent=function(t){return"undefined"!==this.commitTime&&this.commitTime+this.fadeDuration>t},ze.prototype.setStale=function(){this.stale=!0};var Ie=Math.pow(2,25),De=Math.pow(2,24),Pe=Math.pow(2,17),Re=Math.pow(2,16),Fe=Math.pow(2,9),Be=Math.pow(2,8),Ne=Math.pow(2,1);function je(t){if(0===t.opacity&&!t.placed)return 0;if(1===t.opacity&&t.placed)return 4294967295;var e=t.placed?1:0,r=Math.floor(127*t.opacity);return r*Ie+e*De+r*Pe+e*Re+r*Fe+e*Be+r*Ne+e}var Ve=function(){this._currentTileIndex=0,this._seenCrossTileIDs={}};Ve.prototype.continuePlacement=function(t,e,r,n,i){for(;this._currentTileIndex<t.length;){var a=t[this._currentTileIndex];if(e.placeLayerTile(n,a,r,this._seenCrossTileIDs),this._currentTileIndex++,i())return!0}};var Ue=function(t,e,r,n,i){this.placement=new ze(t,i),this._currentPlacementIndex=e.length-1,this._forceFullPlacement=r,this._showCollisionBoxes=n,this._done=!1};Ue.prototype.isDone=function(){return this._done},Ue.prototype.continuePlacement=function(t,e,r){for(var n=this,i=a.now(),o=function(){var t=a.now()-i;return!n._forceFullPlacement&&t>2};this._currentPlacementIndex>=0;){var s=e[t[n._currentPlacementIndex]],l=n.placement.collisionIndex.transform.zoom;if("symbol"===s.type&&(!s.minzoom||s.minzoom<=l)&&(!s.maxzoom||s.maxzoom>l)){if(n._inProgressLayer||(n._inProgressLayer=new Ve),n._inProgressLayer.continuePlacement(r[s.source],n.placement,n._showCollisionBoxes,s,o))return;delete n._inProgressLayer}n._currentPlacementIndex--}this._done=!0},Ue.prototype.commit=function(t,e){return this.placement.commit(t,e),this.placement};var qe=512/t.default$8/2,He=function(t,e,r){this.tileID=t,this.indexedSymbolInstances={},this.bucketInstanceId=r;for(var n=0,i=e;n<i.length;n+=1){var a=i[n],o=a.key;this.indexedSymbolInstances[o]||(this.indexedSymbolInstances[o]=[]),this.indexedSymbolInstances[o].push({crossTileID:a.crossTileID,coord:this.getScaledCoordinates(a,t)})}};He.prototype.getScaledCoordinates=function(e,r){var n=r.canonical.z-this.tileID.canonical.z,i=qe/Math.pow(2,n),a=e.anchor;return{x:Math.floor((r.canonical.x*t.default$8+a.x)*i),y:Math.floor((r.canonical.y*t.default$8+a.y)*i)}},He.prototype.findMatches=function(t,e,r){for(var n=this.tileID.canonical.z<e.canonical.z?1:Math.pow(2,this.tileID.canonical.z-e.canonical.z),i=0,a=t;i<a.length;i+=1){var o=a[i];if(!o.crossTileID){var s=this.indexedSymbolInstances[o.key];if(s)for(var l=this.getScaledCoordinates(o,e),c=0,u=s;c<u.length;c+=1){var h=u[c];if(Math.abs(h.coord.x-l.x)<=n&&Math.abs(h.coord.y-l.y)<=n&&!r[h.crossTileID]){r[h.crossTileID]=!0,o.crossTileID=h.crossTileID;break}}}}};var Ge=function(){this.maxCrossTileID=0};Ge.prototype.generate=function(){return++this.maxCrossTileID};var Ye=function(){this.indexes={},this.usedCrossTileIDs={},this.lng=0};Ye.prototype.handleWrapJump=function(t){var e=Math.round((t-this.lng)/360);if(0!==e)for(var r in this.indexes){var n=this.indexes[r],i={};for(var a in n){var o=n[a];o.tileID=o.tileID.unwrapTo(o.tileID.wrap+e),i[o.tileID.key]=o}this.indexes[r]=i}this.lng=t},Ye.prototype.addBucket=function(t,e,r){if(this.indexes[t.overscaledZ]&&this.indexes[t.overscaledZ][t.key]){if(this.indexes[t.overscaledZ][t.key].bucketInstanceId===e.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(t.overscaledZ,this.indexes[t.overscaledZ][t.key])}for(var n=0,i=e.symbolInstances;n<i.length;n+=1)i[n].crossTileID=0;this.usedCrossTileIDs[t.overscaledZ]||(this.usedCrossTileIDs[t.overscaledZ]={});var a=this.usedCrossTileIDs[t.overscaledZ];for(var o in this.indexes){var s=this.indexes[o];if(Number(o)>t.overscaledZ)for(var l in s){var c=s[l];c.tileID.isChildOf(t)&&c.findMatches(e.symbolInstances,t,a)}else{var u=s[t.scaledTo(Number(o)).key];u&&u.findMatches(e.symbolInstances,t,a)}}for(var h=0,f=e.symbolInstances;h<f.length;h+=1){var p=f[h];p.crossTileID||(p.crossTileID=r.generate(),a[p.crossTileID]=!0)}return void 0===this.indexes[t.overscaledZ]&&(this.indexes[t.overscaledZ]={}),this.indexes[t.overscaledZ][t.key]=new He(t,e.symbolInstances,e.bucketInstanceId),!0},Ye.prototype.removeBucketCrossTileIDs=function(t,e){for(var r in e.indexedSymbolInstances)for(var n=0,i=e.indexedSymbolInstances[r];n<i.length;n+=1){var a=i[n];delete this.usedCrossTileIDs[t][a.crossTileID]}},Ye.prototype.removeStaleBuckets=function(t){var e=!1;for(var r in this.indexes){var n=this.indexes[r];for(var i in n)t[n[i].bucketInstanceId]||(this.removeBucketCrossTileIDs(r,n[i]),delete n[i],e=!0)}return e};var We=function(){this.layerIndexes={},this.crossTileIDs=new Ge,this.maxBucketInstanceId=0,this.bucketsInCurrentPlacement={}};We.prototype.addLayer=function(t,e,r){var n=this.layerIndexes[t.id];void 0===n&&(n=this.layerIndexes[t.id]=new Ye);var i=!1,a={};n.handleWrapJump(r);for(var o=0,s=e;o<s.length;o+=1){var l=s[o],c=l.getBucket(t);c&&t.id===c.layerIds[0]&&(c.bucketInstanceId||(c.bucketInstanceId=++this.maxBucketInstanceId),n.addBucket(l.tileID,c,this.crossTileIDs)&&(i=!0),a[c.bucketInstanceId]=!0)}return n.removeStaleBuckets(a)&&(i=!0),i},We.prototype.pruneUnusedLayers=function(t){var e={};for(var r in t.forEach(function(t){e[t]=!0}),this.layerIndexes)e[r]||delete this.layerIndexes[r]};var Xe=function(e,r){return t.emitValidationErrors(e,r&&r.filter(function(t){return"source.canvas"!==t.identifier}))},Ze=t.pick(ee,["addLayer","removeLayer","setPaintProperty","setLayoutProperty","setFilter","addSource","removeSource","setLayerZoomRange","setLight","setTransition","setGeoJSONSourceData"]),$e=t.pick(ee,["setCenter","setZoom","setBearing","setPitch"]),Je=function(e){function r(n,i){var a=this;void 0===i&&(i={}),e.call(this),this.map=n,this.dispatcher=new q((Jt||(Jt=new Kt),Jt),this),this.imageManager=new O,this.glyphManager=new B(n._transformRequest,i.localIdeographFontFamily),this.lineAtlas=new U(256,512),this.crossTileSymbolIndex=new We,this._layers={},this._order=[],this.sourceCaches={},this.zoomHistory=new t.default$23,this._loaded=!1,this._resetUpdates();var o=this;this._rtlTextPluginCallback=r.registerForPluginAvailability(function(t){for(var e in o.dispatcher.broadcast("loadRTLTextPlugin",t.pluginURL,t.completionCallback),o.sourceCaches)o.sourceCaches[e].reload()}),this.on("data",function(t){if("source"===t.dataType&&"metadata"===t.sourceDataType){var e=a.sourceCaches[t.sourceId];if(e){var r=e.getSource();if(r&&r.vectorLayerIds)for(var n in a._layers){var i=a._layers[n];i.source===r.id&&a._validateLayer(i)}}}})}return e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r,r.prototype.loadURL=function(e,r){var n=this;void 0===r&&(r={}),this.fire(new t.Event("dataloading",{dataType:"style"}));var i="boolean"==typeof r.validate?r.validate:!x(e);e=function(t,e){if(!x(t))return t;var r=M(t);return r.path="/styles/v1"+r.path,y(r,e)}(e,r.accessToken);var a=this.map._transformRequest(e,t.ResourceType.Style);t.getJSON(a,function(e,r){e?n.fire(new t.ErrorEvent(e)):r&&n._load(r,i)})},r.prototype.loadJSON=function(e,r){var n=this;void 0===r&&(r={}),this.fire(new t.Event("dataloading",{dataType:"style"})),a.frame(function(){n._load(e,!1!==r.validate)})},r.prototype._load=function(e,r){var n=this;if(!r||!Xe(this,t.validateStyle(e))){for(var i in this._loaded=!0,this.stylesheet=e,e.sources)n.addSource(i,e.sources[i],{validate:!1});e.sprite?function(e,r,n){var i,o,s,l=a.devicePixelRatio>1?"@2x":"";function c(){if(s)n(s);else if(i&&o){var e=a.getImageData(o),r={};for(var l in i){var c=i[l],u=c.width,h=c.height,f=c.x,p=c.y,d=c.sdf,g=c.pixelRatio,v=new t.RGBAImage({width:u,height:h});t.RGBAImage.copy(e,v,{x:f,y:p},{x:0,y:0},{width:u,height:h}),r[l]={data:v,pixelRatio:g,sdf:d}}n(null,r)}}t.getJSON(r(_(e,l,".json"),t.ResourceType.SpriteJSON),function(t,e){s||(s=t,i=e,c())}),t.getImage(r(_(e,l,".png"),t.ResourceType.SpriteImage),function(t,e){s||(s=t,o=e,c())})}(e.sprite,this.map._transformRequest,function(e,r){if(e)n.fire(new t.ErrorEvent(e));else if(r)for(var i in r)n.imageManager.addImage(i,r[i]);n.imageManager.setLoaded(!0),n.fire(new t.Event("data",{dataType:"style"}))}):this.imageManager.setLoaded(!0),this.glyphManager.setURL(e.glyphs);var o=te(this.stylesheet.layers);this._order=o.map(function(t){return t.id}),this._layers={};for(var s=0,l=o;s<l.length;s+=1){var c=l[s];(c=t.default$22(c)).setEventedParent(n,{layer:{id:c.id}}),n._layers[c.id]=c}this.dispatcher.broadcast("setLayers",this._serializeLayers(this._order)),this.light=new V(this.stylesheet.light),this.fire(new t.Event("data",{dataType:"style"})),this.fire(new t.Event("style.load"))}},r.prototype._validateLayer=function(e){var r=this.sourceCaches[e.source];if(r){var n=e.sourceLayer;if(n){var i=r.getSource();("geojson"===i.type||i.vectorLayerIds&&-1===i.vectorLayerIds.indexOf(n))&&this.fire(new t.ErrorEvent(new Error('Source layer "'+n+'" does not exist on source "'+i.id+'" as specified by style layer "'+e.id+'"')))}}},r.prototype.loaded=function(){if(!this._loaded)return!1;if(Object.keys(this._updatedSources).length)return!1;for(var t in this.sourceCaches)if(!this.sourceCaches[t].loaded())return!1;return!!this.imageManager.isLoaded()},r.prototype._serializeLayers=function(t){var e=this;return t.map(function(t){return e._layers[t].serialize()})},r.prototype.hasTransitions=function(){if(this.light&&this.light.hasTransition())return!0;for(var t in this.sourceCaches)if(this.sourceCaches[t].hasTransition())return!0;for(var e in this._layers)if(this._layers[e].hasTransition())return!0;return!1},r.prototype._checkLoaded=function(){if(!this._loaded)throw new Error("Style is not done loading")},r.prototype.update=function(e){if(this._loaded){if(this._changed){var r=Object.keys(this._updatedLayers),n=Object.keys(this._removedLayers);for(var i in(r.length||n.length)&&this._updateWorkerLayers(r,n),this._updatedSources){var a=this._updatedSources[i];"reload"===a?this._reloadSource(i):"clear"===a&&this._clearSource(i)}for(var o in this._updatedPaintProps)this._layers[o].updateTransitions(e);this.light.updateTransitions(e),this._resetUpdates(),this.fire(new t.Event("data",{dataType:"style"}))}for(var s in this.sourceCaches)this.sourceCaches[s].used=!1;for(var l=0,c=this._order;l<c.length;l+=1){var u=c[l],h=this._layers[u];h.recalculate(e),!h.isHidden(e.zoom)&&h.source&&(this.sourceCaches[h.source].used=!0)}this.light.recalculate(e),this.z=e.zoom}},r.prototype._updateWorkerLayers=function(t,e){this.dispatcher.broadcast("updateLayers",{layers:this._serializeLayers(t),removedIds:e})},r.prototype._resetUpdates=function(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={}},r.prototype.setState=function(e){var r=this;if(this._checkLoaded(),Xe(this,t.validateStyle(e)))return!1;(e=t.clone(e)).layers=te(e.layers);var n=function(e,r){if(!e)return[{command:ee.setStyle,args:[r]}];var n=[];try{if(!t.default$10(e.version,r.version))return[{command:ee.setStyle,args:[r]}];t.default$10(e.center,r.center)||n.push({command:ee.setCenter,args:[r.center]}),t.default$10(e.zoom,r.zoom)||n.push({command:ee.setZoom,args:[r.zoom]}),t.default$10(e.bearing,r.bearing)||n.push({command:ee.setBearing,args:[r.bearing]}),t.default$10(e.pitch,r.pitch)||n.push({command:ee.setPitch,args:[r.pitch]}),t.default$10(e.sprite,r.sprite)||n.push({command:ee.setSprite,args:[r.sprite]}),t.default$10(e.glyphs,r.glyphs)||n.push({command:ee.setGlyphs,args:[r.glyphs]}),t.default$10(e.transition,r.transition)||n.push({command:ee.setTransition,args:[r.transition]}),t.default$10(e.light,r.light)||n.push({command:ee.setLight,args:[r.light]});var i={},a=[];!function(e,r,n,i){var a;for(a in r=r||{},e=e||{})e.hasOwnProperty(a)&&(r.hasOwnProperty(a)||ne(a,n,i));for(a in r)r.hasOwnProperty(a)&&(e.hasOwnProperty(a)?t.default$10(e[a],r[a])||("geojson"===e[a].type&&"geojson"===r[a].type&&ae(e,r,a)?n.push({command:ee.setGeoJSONSourceData,args:[a,r[a].data]}):ie(a,r,n,i)):re(a,r,n))}(e.sources,r.sources,a,i);var o=[];e.layers&&e.layers.forEach(function(t){i[t.source]?n.push({command:ee.removeLayer,args:[t.id]}):o.push(t)}),n=n.concat(a),function(e,r,n){r=r||[];var i,a,o,s,l,c,u,h=(e=e||[]).map(se),f=r.map(se),p=e.reduce(le,{}),d=r.reduce(le,{}),g=h.slice(),v=Object.create(null);for(i=0,a=0;i<h.length;i++)o=h[i],d.hasOwnProperty(o)?a++:(n.push({command:ee.removeLayer,args:[o]}),g.splice(g.indexOf(o,a),1));for(i=0,a=0;i<f.length;i++)o=f[f.length-1-i],g[g.length-1-i]!==o&&(p.hasOwnProperty(o)?(n.push({command:ee.removeLayer,args:[o]}),g.splice(g.lastIndexOf(o,g.length-a),1)):a++,c=g[g.length-i],n.push({command:ee.addLayer,args:[d[o],c]}),g.splice(g.length-i,0,o),v[o]=!0);for(i=0;i<f.length;i++)if(s=p[o=f[i]],l=d[o],!v[o]&&!t.default$10(s,l))if(t.default$10(s.source,l.source)&&t.default$10(s["source-layer"],l["source-layer"])&&t.default$10(s.type,l.type)){for(u in oe(s.layout,l.layout,n,o,null,ee.setLayoutProperty),oe(s.paint,l.paint,n,o,null,ee.setPaintProperty),t.default$10(s.filter,l.filter)||n.push({command:ee.setFilter,args:[o,l.filter]}),t.default$10(s.minzoom,l.minzoom)&&t.default$10(s.maxzoom,l.maxzoom)||n.push({command:ee.setLayerZoomRange,args:[o,l.minzoom,l.maxzoom]}),s)s.hasOwnProperty(u)&&"layout"!==u&&"paint"!==u&&"filter"!==u&&"metadata"!==u&&"minzoom"!==u&&"maxzoom"!==u&&(0===u.indexOf("paint.")?oe(s[u],l[u],n,o,u.slice(6),ee.setPaintProperty):t.default$10(s[u],l[u])||n.push({command:ee.setLayerProperty,args:[o,u,l[u]]}));for(u in l)l.hasOwnProperty(u)&&!s.hasOwnProperty(u)&&"layout"!==u&&"paint"!==u&&"filter"!==u&&"metadata"!==u&&"minzoom"!==u&&"maxzoom"!==u&&(0===u.indexOf("paint.")?oe(s[u],l[u],n,o,u.slice(6),ee.setPaintProperty):t.default$10(s[u],l[u])||n.push({command:ee.setLayerProperty,args:[o,u,l[u]]}))}else n.push({command:ee.removeLayer,args:[o]}),c=g[g.lastIndexOf(o)+1],n.push({command:ee.addLayer,args:[l,c]})}(o,r.layers,n)}catch(t){console.warn("Unable to compute style diff:",t),n=[{command:ee.setStyle,args:[r]}]}return n}(this.serialize(),e).filter(function(t){return!(t.command in $e)});if(0===n.length)return!1;var i=n.filter(function(t){return!(t.command in Ze)});if(i.length>0)throw new Error("Unimplemented: "+i.map(function(t){return t.command}).join(", ")+".");return n.forEach(function(t){"setTransition"!==t.command&&r[t.command].apply(r,t.args)}),this.stylesheet=e,!0},r.prototype.addImage=function(e,r){if(this.getImage(e))return this.fire(new t.ErrorEvent(new Error("An image with this name already exists.")));this.imageManager.addImage(e,r),this.fire(new t.Event("data",{dataType:"style"}))},r.prototype.getImage=function(t){return this.imageManager.getImage(t)},r.prototype.removeImage=function(e){if(!this.getImage(e))return this.fire(new t.ErrorEvent(new Error("No image with this name exists.")));this.imageManager.removeImage(e),this.fire(new t.Event("data",{dataType:"style"}))},r.prototype.addSource=function(e,r,n){var i=this;if(this._checkLoaded(),void 0!==this.sourceCaches[e])throw new Error("There is already a source with this ID");if(!r.type)throw new Error("The type property must be defined, but the only the following properties were given: "+Object.keys(r).join(", ")+".");if(!(["vector","raster","geojson","video","image"].indexOf(r.type)>=0&&this._validate(t.validateStyle.source,"sources."+e,r,null,n))){this.map&&this.map._collectResourceTiming&&(r.collectResourceTiming=!0);var a=this.sourceCaches[e]=new Wt(e,r,this.dispatcher);a.style=this,a.setEventedParent(this,function(){return{isSourceLoaded:i.loaded(),source:a.serialize(),sourceId:e}}),a.onAdd(this.map),this._changed=!0}},r.prototype.removeSource=function(e){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error("There is no source with this ID");for(var r in this._layers)if(this._layers[r].source===e)return this.fire(new t.ErrorEvent(new Error('Source "'+e+'" cannot be removed while layer "'+r+'" is using it.')));var n=this.sourceCaches[e];delete this.sourceCaches[e],delete this._updatedSources[e],n.fire(new t.Event("data",{sourceDataType:"metadata",dataType:"source",sourceId:e})),n.setEventedParent(null),n.clearTiles(),n.onRemove&&n.onRemove(this.map),this._changed=!0},r.prototype.setGeoJSONSourceData=function(t,e){this._checkLoaded(),this.sourceCaches[t].getSource().setData(e),this._changed=!0},r.prototype.getSource=function(t){return this.sourceCaches[t]&&this.sourceCaches[t].getSource()},r.prototype.addLayer=function(e,r,n){this._checkLoaded();var i=e.id;if(this.getLayer(i))this.fire(new t.ErrorEvent(new Error('Layer with id "'+i+'" already exists on this map')));else if("object"==typeof e.source&&(this.addSource(i,e.source),e=t.clone(e),e=t.extend(e,{source:i})),!this._validate(t.validateStyle.layer,"layers."+i,e,{arrayIndex:-1},n)){var a=t.default$22(e);this._validateLayer(a),a.setEventedParent(this,{layer:{id:i}});var o=r?this._order.indexOf(r):this._order.length;if(r&&-1===o)this.fire(new t.ErrorEvent(new Error('Layer with id "'+r+'" does not exist on this map.')));else{if(this._order.splice(o,0,i),this._layerOrderChanged=!0,this._layers[i]=a,this._removedLayers[i]&&a.source){var s=this._removedLayers[i];delete this._removedLayers[i],s.type!==a.type?this._updatedSources[a.source]="clear":(this._updatedSources[a.source]="reload",this.sourceCaches[a.source].pause())}this._updateLayer(a)}}},r.prototype.moveLayer=function(e,r){if(this._checkLoaded(),this._changed=!0,this._layers[e]){if(e!==r){var n=this._order.indexOf(e);this._order.splice(n,1);var i=r?this._order.indexOf(r):this._order.length;r&&-1===i?this.fire(new t.ErrorEvent(new Error('Layer with id "'+r+'" does not exist on this map.'))):(this._order.splice(i,0,e),this._layerOrderChanged=!0)}}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be moved.")))},r.prototype.removeLayer=function(e){this._checkLoaded();var r=this._layers[e];if(r){r.setEventedParent(null);var n=this._order.indexOf(e);this._order.splice(n,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[e]=r,delete this._layers[e],delete this._updatedLayers[e],delete this._updatedPaintProps[e]}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be removed.")))},r.prototype.getLayer=function(t){return this._layers[t]},r.prototype.setLayerZoomRange=function(e,r,n){this._checkLoaded();var i=this.getLayer(e);i?i.minzoom===r&&i.maxzoom===n||(null!=r&&(i.minzoom=r),null!=n&&(i.maxzoom=n),this._updateLayer(i)):this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot have zoom extent.")))},r.prototype.setFilter=function(e,r){this._checkLoaded();var n=this.getLayer(e);if(n){if(!t.default$10(n.filter,r))return null==r?(n.filter=void 0,void this._updateLayer(n)):void(this._validate(t.validateStyle.filter,"layers."+n.id+".filter",r)||(n.filter=t.clone(r),this._updateLayer(n)))}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be filtered.")))},r.prototype.getFilter=function(e){return t.clone(this.getLayer(e).filter)},r.prototype.setLayoutProperty=function(e,r,n){this._checkLoaded();var i=this.getLayer(e);i?t.default$10(i.getLayoutProperty(r),n)||(i.setLayoutProperty(r,n),this._updateLayer(i)):this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be styled.")))},r.prototype.getLayoutProperty=function(t,e){return this.getLayer(t).getLayoutProperty(e)},r.prototype.setPaintProperty=function(e,r,n){this._checkLoaded();var i=this.getLayer(e);if(i){if(!t.default$10(i.getPaintProperty(r),n)){var a=i._transitionablePaint._values[r].value.isDataDriven();i.setPaintProperty(r,n),(i._transitionablePaint._values[r].value.isDataDriven()||a)&&this._updateLayer(i),this._changed=!0,this._updatedPaintProps[e]=!0}}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be styled.")))},r.prototype.getPaintProperty=function(t,e){return this.getLayer(t).getPaintProperty(e)},r.prototype.getTransition=function(){return t.extend({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)},r.prototype.serialize=function(){var e=this;return t.filterObject({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,light:this.stylesheet.light,center:this.stylesheet.center,zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,sources:t.mapObject(this.sourceCaches,function(t){return t.serialize()}),layers:this._order.map(function(t){return e._layers[t].serialize()})},function(t){return void 0!==t})},r.prototype._updateLayer=function(t){this._updatedLayers[t.id]=!0,t.source&&!this._updatedSources[t.source]&&(this._updatedSources[t.source]="reload",this.sourceCaches[t.source].pause()),this._changed=!0},r.prototype._flattenRenderedFeatures=function(t){for(var e=[],r=this._order.length-1;r>=0;r--)for(var n=this._order[r],i=0,a=t;i<a.length;i+=1){var o=a[i][n];if(o)for(var s=0,l=o;s<l.length;s+=1){var c=l[s];e.push(c)}}return e},r.prototype.queryRenderedFeatures=function(e,r,n){r&&r.filter&&this._validate(t.validateStyle.filter,"queryRenderedFeatures.filter",r.filter);var i={};if(r&&r.layers){if(!Array.isArray(r.layers))return this.fire(new t.ErrorEvent(new Error("parameters.layers must be an Array."))),[];for(var a=0,o=r.layers;a<o.length;a+=1){var s=o[a],l=this._layers[s];if(!l)return this.fire(new t.ErrorEvent(new Error("The layer '"+s+"' does not exist in the map's style and cannot be queried for features."))),[];i[l.source]=!0}}var c=[];for(var u in this.sourceCaches)r.layers&&!i[u]||c.push(at(this.sourceCaches[u],this._layers,e.worldCoordinate,r,n));return this.placement&&c.push(function(t,e,r,n,i){for(var a={},o=n.queryRenderedSymbols(e),s=[],l=0,c=Object.keys(o).map(Number);l<c.length;l+=1){var u=c[l];s.push(i[u])}s.sort(ot);for(var h=function(){var e=p[f],n=e.featureIndex.lookupSymbolFeatures(o[e.bucketInstanceId],e.bucketIndex,e.sourceLayerIndex,r.filter,r.layers,t);for(var i in n){var s=a[i]=a[i]||[],l=n[i];l.sort(function(t,r){var n=e.featureSortOrder;if(n){var i=n.indexOf(t.featureIndex);return n.indexOf(r.featureIndex)-i}return r.featureIndex-t.featureIndex});for(var c=0,u=l;c<u.length;c+=1){var h=u[c];s.push(h.feature)}}},f=0,p=s;f<p.length;f+=1)h();return a}(this._layers,e.viewport,r,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenRenderedFeatures(c)},r.prototype.querySourceFeatures=function(e,r){r&&r.filter&&this._validate(t.validateStyle.filter,"querySourceFeatures.filter",r.filter);var n=this.sourceCaches[e];return n?function(t,e){for(var r=t.getRenderableIds().map(function(e){return t.getTileByID(e)}),n=[],i={},a=0;a<r.length;a++){var o=r[a],s=o.tileID.canonical.key;i[s]||(i[s]=!0,o.querySourceFeatures(n,e))}return n}(n,r):[]},r.prototype.addSourceType=function(t,e,n){return r.getSourceType(t)?n(new Error('A source type called "'+t+'" already exists.')):(r.setSourceType(t,e),e.workerSourceURL?void this.dispatcher.broadcast("loadWorkerSource",{name:t,url:e.workerSourceURL},n):n(null,null))},r.prototype.getLight=function(){return this.light.getLight()},r.prototype.setLight=function(e){this._checkLoaded();var r=this.light.getLight(),n=!1;for(var i in e)if(!t.default$10(e[i],r[i])){n=!0;break}if(n){var o={now:a.now(),transition:t.extend({duration:300,delay:0},this.stylesheet.transition)};this.light.setLight(e),this.light.updateTransitions(o)}},r.prototype._validate=function(e,r,n,i,a){return(!a||!1!==a.validate)&&Xe(this,e.call(t.validateStyle,t.extend({key:r,style:this.serialize(),value:n,styleSpec:t.default$5},i)))},r.prototype._remove=function(){for(var e in t.evented.off("pluginAvailable",this._rtlTextPluginCallback),this.sourceCaches)this.sourceCaches[e].clearTiles();this.dispatcher.remove()},r.prototype._clearSource=function(t){this.sourceCaches[t].clearTiles()},r.prototype._reloadSource=function(t){this.sourceCaches[t].resume(),this.sourceCaches[t].reload()},r.prototype._updateSources=function(t){for(var e in this.sourceCaches)this.sourceCaches[e].update(t)},r.prototype._generateCollisionBoxes=function(){for(var t in this.sourceCaches)this._reloadSource(t)},r.prototype._updatePlacement=function(t,e,r){for(var n=!1,i=!1,o={},s=0,l=this._order;s<l.length;s+=1){var c=l[s],u=this._layers[c];if("symbol"===u.type){if(!o[u.source]){var h=this.sourceCaches[u.source];o[u.source]=h.getRenderableIds().map(function(t){return h.getTileByID(t)}).sort(function(t,e){return e.tileID.overscaledZ-t.tileID.overscaledZ||(t.tileID.isLessThan(e.tileID)?-1:1)})}var f=this.crossTileSymbolIndex.addLayer(u,o[u.source],t.center.lng);n=n||f}}this.crossTileSymbolIndex.pruneUnusedLayers(this._order);var p=this._layerOrderChanged;if((p||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(a.now()))&&(this.pauseablePlacement=new Ue(t,this._order,p,e,r),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,o),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(this.placement,a.now()),i=!0),n&&this.pauseablePlacement.placement.setStale()),i||n)for(var d=0,g=this._order;d<g.length;d+=1){var v=g[d],m=this._layers[v];"symbol"===m.type&&this.placement.updateLayerOpacities(m,o[m.source])}return!this.pauseablePlacement.isDone()||this.placement.hasTransitions(a.now())},r.prototype.getImages=function(t,e,r){this.imageManager.getImages(e.icons,r)},r.prototype.getGlyphs=function(t,e,r){this.glyphManager.getGlyphs(e.stacks,r)},r}(t.Evented);Je.getSourceType=function(t){return nt[t]},Je.setSourceType=function(t,e){nt[t]=e},Je.registerForPluginAvailability=t.registerForPluginAvailability;var Ke=t.createLayout([{name:"a_pos",type:"Int16",components:2}]),Qe={prelude:{fragmentSource:"#ifdef GL_ES\nprecision mediump float;\n#else\n\n#if !defined(lowp)\n#define lowp\n#endif\n\n#if !defined(mediump)\n#define mediump\n#endif\n\n#if !defined(highp)\n#define highp\n#endif\n\n#endif\n",vertexSource:"#ifdef GL_ES\nprecision highp float;\n#else\n\n#if !defined(lowp)\n#define lowp\n#endif\n\n#if !defined(mediump)\n#define mediump\n#endif\n\n#if !defined(highp)\n#define highp\n#endif\n\n#endif\n\n// Unpack a pair of values that have been packed into a single float.\n// The packed values are assumed to be 8-bit unsigned integers, and are\n// packed like so:\n// packedValue = floor(input[0]) * 256 + input[1],\nvec2 unpack_float(const float packedValue) {\n    int packedIntValue = int(packedValue);\n    int v0 = packedIntValue / 256;\n    return vec2(v0, packedIntValue - v0 * 256);\n}\n\nvec2 unpack_opacity(const float packedOpacity) {\n    int intOpacity = int(packedOpacity) / 2;\n    return vec2(float(intOpacity) / 127.0, mod(packedOpacity, 2.0));\n}\n\n// To minimize the number of attributes needed, we encode a 4-component\n// color into a pair of floats (i.e. a vec2) as follows:\n// [ floor(color.r * 255) * 256 + color.g * 255,\n//   floor(color.b * 255) * 256 + color.g * 255 ]\nvec4 decode_color(const vec2 encodedColor) {\n    return vec4(\n        unpack_float(encodedColor[0]) / 255.0,\n        unpack_float(encodedColor[1]) / 255.0\n    );\n}\n\n// Unpack a pair of paint values and interpolate between them.\nfloat unpack_mix_vec2(const vec2 packedValue, const float t) {\n    return mix(packedValue[0], packedValue[1], t);\n}\n\n// Unpack a pair of paint values and interpolate between them.\nvec4 unpack_mix_vec4(const vec4 packedColors, const float t) {\n    vec4 minColor = decode_color(vec2(packedColors[0], packedColors[1]));\n    vec4 maxColor = decode_color(vec2(packedColors[2], packedColors[3]));\n    return mix(minColor, maxColor, t);\n}\n\n// The offset depends on how many pixels are between the world origin and the edge of the tile:\n// vec2 offset = mod(pixel_coord, size)\n//\n// At high zoom levels there are a ton of pixels between the world origin and the edge of the tile.\n// The glsl spec only guarantees 16 bits of precision for highp floats. We need more than that.\n//\n// The pixel_coord is passed in as two 16 bit values:\n// pixel_coord_upper = floor(pixel_coord / 2^16)\n// pixel_coord_lower = mod(pixel_coord, 2^16)\n//\n// The offset is calculated in a series of steps that should preserve this precision:\nvec2 get_pattern_pos(const vec2 pixel_coord_upper, const vec2 pixel_coord_lower,\n    const vec2 pattern_size, const float tile_units_to_pixels, const vec2 pos) {\n\n    vec2 offset = mod(mod(mod(pixel_coord_upper, pattern_size) * 256.0, pattern_size) * 256.0 + pixel_coord_lower, pattern_size);\n    return (tile_units_to_pixels * pos + offset) / pattern_size;\n}\n"},background:{fragmentSource:"uniform vec4 u_color;\nuniform float u_opacity;\n\nvoid main() {\n    gl_FragColor = u_color * u_opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n"},backgroundPattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\nuniform float u_opacity;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\nvoid main() {\n    vec2 imagecoord = mod(v_pos_a, 1.0);\n    vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n    vec4 color1 = texture2D(u_image, pos);\n\n    vec2 imagecoord_b = mod(v_pos_b, 1.0);\n    vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n    vec4 color2 = texture2D(u_image, pos2);\n\n    gl_FragColor = mix(color1, color2, u_mix) * u_opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n\n    v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, a_pos);\n    v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, a_pos);\n}\n"},circle:{fragmentSource:"#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\n\nvarying vec3 v_data;\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize mediump float radius\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize highp vec4 stroke_color\n    #pragma mapbox: initialize mediump float stroke_width\n    #pragma mapbox: initialize lowp float stroke_opacity\n\n    vec2 extrude = v_data.xy;\n    float extrude_length = length(extrude);\n\n    lowp float antialiasblur = v_data.z;\n    float antialiased_blur = -max(blur, antialiasblur);\n\n    float opacity_t = smoothstep(0.0, antialiased_blur, extrude_length - 1.0);\n\n    float color_t = stroke_width < 0.01 ? 0.0 : smoothstep(\n        antialiased_blur,\n        0.0,\n        extrude_length - radius / (radius + stroke_width)\n    );\n\n    gl_FragColor = opacity_t * mix(color * opacity, stroke_color * stroke_opacity, color_t);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform bool u_scale_with_map;\nuniform bool u_pitch_with_map;\nuniform vec2 u_extrude_scale;\nuniform highp float u_camera_to_center_distance;\n\nattribute vec2 a_pos;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\n\nvarying vec3 v_data;\n\nvoid main(void) {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize mediump float radius\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize highp vec4 stroke_color\n    #pragma mapbox: initialize mediump float stroke_width\n    #pragma mapbox: initialize lowp float stroke_opacity\n\n    // unencode the extrusion vector that we snuck into the a_pos vector\n    vec2 extrude = vec2(mod(a_pos, 2.0) * 2.0 - 1.0);\n\n    // multiply a_pos by 0.5, since we had it * 2 in order to sneak\n    // in extrusion data\n    vec2 circle_center = floor(a_pos * 0.5);\n    if (u_pitch_with_map) {\n        vec2 corner_position = circle_center;\n        if (u_scale_with_map) {\n            corner_position += extrude * (radius + stroke_width) * u_extrude_scale;\n        } else {\n            // Pitching the circle with the map effectively scales it with the map\n            // To counteract the effect for pitch-scale: viewport, we rescale the\n            // whole circle based on the pitch scaling effect at its central point\n            vec4 projected_center = u_matrix * vec4(circle_center, 0, 1);\n            corner_position += extrude * (radius + stroke_width) * u_extrude_scale * (projected_center.w / u_camera_to_center_distance);\n        }\n\n        gl_Position = u_matrix * vec4(corner_position, 0, 1);\n    } else {\n        gl_Position = u_matrix * vec4(circle_center, 0, 1);\n\n        if (u_scale_with_map) {\n            gl_Position.xy += extrude * (radius + stroke_width) * u_extrude_scale * u_camera_to_center_distance;\n        } else {\n            gl_Position.xy += extrude * (radius + stroke_width) * u_extrude_scale * gl_Position.w;\n        }\n    }\n\n    // This is a minimum blur distance that serves as a faux-antialiasing for\n    // the circle. since blur is a ratio of the circle's size and the intent is\n    // to keep the blur at roughly 1px, the two are inversely related.\n    lowp float antialiasblur = 1.0 / DEVICE_PIXEL_RATIO / (radius + stroke_width);\n\n    v_data = vec3(extrude.x, extrude.y, antialiasblur);\n}\n"},clippingMask:{fragmentSource:"void main() {\n    gl_FragColor = vec4(1.0);\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n"},heatmap:{fragmentSource:"#pragma mapbox: define highp float weight\n\nuniform highp float u_intensity;\nvarying vec2 v_extrude;\n\n// Gaussian kernel coefficient: 1 / sqrt(2 * PI)\n#define GAUSS_COEF 0.3989422804014327\n\nvoid main() {\n    #pragma mapbox: initialize highp float weight\n\n    // Kernel density estimation with a Gaussian kernel of size 5x5\n    float d = -0.5 * 3.0 * 3.0 * dot(v_extrude, v_extrude);\n    float val = weight * u_intensity * GAUSS_COEF * exp(d);\n\n    gl_FragColor = vec4(val, 1.0, 1.0, 1.0);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\n\nuniform mat4 u_matrix;\nuniform float u_extrude_scale;\nuniform float u_opacity;\nuniform float u_intensity;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_extrude;\n\n// Effective \"0\" in the kernel density texture to adjust the kernel size to;\n// this empirically chosen number minimizes artifacts on overlapping kernels\n// for typical heatmap cases (assuming clustered source)\nconst highp float ZERO = 1.0 / 255.0 / 16.0;\n\n// Gaussian kernel coefficient: 1 / sqrt(2 * PI)\n#define GAUSS_COEF 0.3989422804014327\n\nvoid main(void) {\n    #pragma mapbox: initialize highp float weight\n    #pragma mapbox: initialize mediump float radius\n\n    // unencode the extrusion vector that we snuck into the a_pos vector\n    vec2 unscaled_extrude = vec2(mod(a_pos, 2.0) * 2.0 - 1.0);\n\n    // This 'extrude' comes in ranging from [-1, -1], to [1, 1].  We'll use\n    // it to produce the vertices of a square mesh framing the point feature\n    // we're adding to the kernel density texture.  We'll also pass it as\n    // a varying, so that the fragment shader can determine the distance of\n    // each fragment from the point feature.\n    // Before we do so, we need to scale it up sufficiently so that the\n    // kernel falls effectively to zero at the edge of the mesh.\n    // That is, we want to know S such that\n    // weight * u_intensity * GAUSS_COEF * exp(-0.5 * 3.0^2 * S^2) == ZERO\n    // Which solves to:\n    // S = sqrt(-2.0 * log(ZERO / (weight * u_intensity * GAUSS_COEF))) / 3.0\n    float S = sqrt(-2.0 * log(ZERO / weight / u_intensity / GAUSS_COEF)) / 3.0;\n\n    // Pass the varying in units of radius\n    v_extrude = S * unscaled_extrude;\n\n    // Scale by radius and the zoom-based scale factor to produce actual\n    // mesh position\n    vec2 extrude = v_extrude * radius * u_extrude_scale;\n\n    // multiply a_pos by 0.5, since we had it * 2 in order to sneak\n    // in extrusion data\n    vec4 pos = vec4(floor(a_pos * 0.5) + extrude, 0, 1);\n\n    gl_Position = u_matrix * pos;\n}\n"},heatmapTexture:{fragmentSource:"uniform sampler2D u_image;\nuniform sampler2D u_color_ramp;\nuniform float u_opacity;\nvarying vec2 v_pos;\n\nvoid main() {\n    float t = texture2D(u_image, v_pos).r;\n    vec4 color = texture2D(u_color_ramp, vec2(t, 0.5));\n    gl_FragColor = color * u_opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(0.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_world;\nattribute vec2 a_pos;\nvarying vec2 v_pos;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos * u_world, 0, 1);\n\n    v_pos.x = a_pos.x;\n    v_pos.y = 1.0 - a_pos.y;\n}\n"},collisionBox:{fragmentSource:"\nvarying float v_placed;\nvarying float v_notUsed;\n\nvoid main() {\n\n    float alpha = 0.5;\n\n    // Red = collision, hide label\n    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0) * alpha;\n\n    // Blue = no collision, label is showing\n    if (v_placed > 0.5) {\n        gl_FragColor = vec4(0.0, 0.0, 1.0, 0.5) * alpha;\n    }\n\n    if (v_notUsed > 0.5) {\n        // This box not used, fade it out\n        gl_FragColor *= .1;\n    }\n}",vertexSource:"attribute vec2 a_pos;\nattribute vec2 a_anchor_pos;\nattribute vec2 a_extrude;\nattribute vec2 a_placed;\n\nuniform mat4 u_matrix;\nuniform vec2 u_extrude_scale;\nuniform float u_camera_to_center_distance;\n\nvarying float v_placed;\nvarying float v_notUsed;\n\nvoid main() {\n    vec4 projectedPoint = u_matrix * vec4(a_anchor_pos, 0, 1);\n    highp float camera_to_anchor_distance = projectedPoint.w;\n    highp float collision_perspective_ratio = clamp(\n        0.5 + 0.5 * (u_camera_to_center_distance / camera_to_anchor_distance),\n        0.0, // Prevents oversized near-field boxes in pitched/overzoomed tiles\n        4.0);\n\n    gl_Position = u_matrix * vec4(a_pos, 0.0, 1.0);\n    gl_Position.xy += a_extrude * u_extrude_scale * gl_Position.w * collision_perspective_ratio;\n\n    v_placed = a_placed.x;\n    v_notUsed = a_placed.y;\n}\n"},collisionCircle:{fragmentSource:"uniform float u_overscale_factor;\n\nvarying float v_placed;\nvarying float v_notUsed;\nvarying float v_radius;\nvarying vec2 v_extrude;\nvarying vec2 v_extrude_scale;\n\nvoid main() {\n    float alpha = 0.5;\n\n    // Red = collision, hide label\n    vec4 color = vec4(1.0, 0.0, 0.0, 1.0) * alpha;\n\n    // Blue = no collision, label is showing\n    if (v_placed > 0.5) {\n        color = vec4(0.0, 0.0, 1.0, 0.5) * alpha;\n    }\n\n    if (v_notUsed > 0.5) {\n        // This box not used, fade it out\n        color *= .2;\n    }\n\n    float extrude_scale_length = length(v_extrude_scale);\n    float extrude_length = length(v_extrude) * extrude_scale_length;\n    float stroke_width = 15.0 * extrude_scale_length / u_overscale_factor;\n    float radius = v_radius * extrude_scale_length;\n\n    float distance_to_edge = abs(extrude_length - radius);\n    float opacity_t = smoothstep(-stroke_width, 0.0, -distance_to_edge);\n\n    gl_FragColor = opacity_t * color;\n}\n",vertexSource:"attribute vec2 a_pos;\nattribute vec2 a_anchor_pos;\nattribute vec2 a_extrude;\nattribute vec2 a_placed;\n\nuniform mat4 u_matrix;\nuniform vec2 u_extrude_scale;\nuniform float u_camera_to_center_distance;\n\nvarying float v_placed;\nvarying float v_notUsed;\nvarying float v_radius;\n\nvarying vec2 v_extrude;\nvarying vec2 v_extrude_scale;\n\nvoid main() {\n    vec4 projectedPoint = u_matrix * vec4(a_anchor_pos, 0, 1);\n    highp float camera_to_anchor_distance = projectedPoint.w;\n    highp float collision_perspective_ratio = clamp(\n        0.5 + 0.5 * (u_camera_to_center_distance / camera_to_anchor_distance),\n        0.0, // Prevents oversized near-field circles in pitched/overzoomed tiles\n        4.0);\n\n    gl_Position = u_matrix * vec4(a_pos, 0.0, 1.0);\n\n    highp float padding_factor = 1.2; // Pad the vertices slightly to make room for anti-alias blur\n    gl_Position.xy += a_extrude * u_extrude_scale * padding_factor * gl_Position.w * collision_perspective_ratio;\n\n    v_placed = a_placed.x;\n    v_notUsed = a_placed.y;\n    v_radius = abs(a_extrude.y); // We don't pitch the circles, so both units of the extrusion vector are equal in magnitude to the radius\n\n    v_extrude = a_extrude * padding_factor;\n    v_extrude_scale = u_extrude_scale * u_camera_to_center_distance * collision_perspective_ratio;\n}\n"},debug:{fragmentSource:"uniform highp vec4 u_color;\n\nvoid main() {\n    gl_FragColor = u_color;\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n"},fill:{fragmentSource:"#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float opacity\n\n    gl_FragColor = color * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float opacity\n\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n"},fillOutline:{fragmentSource:"#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_pos;\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 outline_color\n    #pragma mapbox: initialize lowp float opacity\n\n    float dist = length(v_pos - gl_FragCoord.xy);\n    float alpha = 1.0 - smoothstep(0.0, 1.0, dist);\n    gl_FragColor = outline_color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\nuniform vec2 u_world;\n\nvarying vec2 v_pos;\n\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 outline_color\n    #pragma mapbox: initialize lowp float opacity\n\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n    v_pos = (gl_Position.xy / gl_Position.w + 1.0) / 2.0 * u_world;\n}\n"},fillOutlinePattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec2 v_pos;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    vec2 imagecoord = mod(v_pos_a, 1.0);\n    vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n    vec4 color1 = texture2D(u_image, pos);\n\n    vec2 imagecoord_b = mod(v_pos_b, 1.0);\n    vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n    vec4 color2 = texture2D(u_image, pos2);\n\n    // find distance to outline for alpha interpolation\n\n    float dist = length(v_pos - gl_FragCoord.xy);\n    float alpha = 1.0 - smoothstep(0.0, 1.0, dist);\n\n\n    gl_FragColor = mix(color1, color2, u_mix) * alpha * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_world;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec2 v_pos;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n\n    v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, a_pos);\n    v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, a_pos);\n\n    v_pos = (gl_Position.xy / gl_Position.w + 1.0) / 2.0 * u_world;\n}\n"},fillPattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    vec2 imagecoord = mod(v_pos_a, 1.0);\n    vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n    vec4 color1 = texture2D(u_image, pos);\n\n    vec2 imagecoord_b = mod(v_pos_b, 1.0);\n    vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n    vec4 color2 = texture2D(u_image, pos2);\n\n    gl_FragColor = mix(color1, color2, u_mix) * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n\n    v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, a_pos);\n    v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, a_pos);\n}\n"},fillExtrusion:{fragmentSource:"varying vec4 v_color;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define highp vec4 color\n\nvoid main() {\n    #pragma mapbox: initialize lowp float base\n    #pragma mapbox: initialize lowp float height\n    #pragma mapbox: initialize highp vec4 color\n\n    gl_FragColor = v_color;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec3 u_lightcolor;\nuniform lowp vec3 u_lightpos;\nuniform lowp float u_lightintensity;\n\nattribute vec2 a_pos;\nattribute vec4 a_normal_ed;\n\nvarying vec4 v_color;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\n#pragma mapbox: define highp vec4 color\n\nvoid main() {\n    #pragma mapbox: initialize lowp float base\n    #pragma mapbox: initialize lowp float height\n    #pragma mapbox: initialize highp vec4 color\n\n    vec3 normal = a_normal_ed.xyz;\n\n    base = max(0.0, base);\n    height = max(0.0, height);\n\n    float t = mod(normal.x, 2.0);\n\n    gl_Position = u_matrix * vec4(a_pos, t > 0.0 ? height : base, 1);\n\n    // Relative luminance (how dark/bright is the surface color?)\n    float colorvalue = color.r * 0.2126 + color.g * 0.7152 + color.b * 0.0722;\n\n    v_color = vec4(0.0, 0.0, 0.0, 1.0);\n\n    // Add slight ambient lighting so no extrusions are totally black\n    vec4 ambientlight = vec4(0.03, 0.03, 0.03, 1.0);\n    color += ambientlight;\n\n    // Calculate cos(theta), where theta is the angle between surface normal and diffuse light ray\n    float directional = clamp(dot(normal / 16384.0, u_lightpos), 0.0, 1.0);\n\n    // Adjust directional so that\n    // the range of values for highlight/shading is narrower\n    // with lower light intensity\n    // and with lighter/brighter surface colors\n    directional = mix((1.0 - u_lightintensity), max((1.0 - colorvalue + u_lightintensity), 1.0), directional);\n\n    // Add gradient along z axis of side surfaces\n    if (normal.y != 0.0) {\n        directional *= clamp((t + base) * pow(height / 150.0, 0.5), mix(0.7, 0.98, 1.0 - u_lightintensity), 1.0);\n    }\n\n    // Assign final color based on surface + ambient light color, diffuse light directional, and light color\n    // with lower bounds adjusted to hue of light\n    // so that shading is tinted with the complementary (opposite) color to the light color\n    v_color.r += clamp(color.r * directional * u_lightcolor.r, mix(0.0, 0.3, 1.0 - u_lightcolor.r), 1.0);\n    v_color.g += clamp(color.g * directional * u_lightcolor.g, mix(0.0, 0.3, 1.0 - u_lightcolor.g), 1.0);\n    v_color.b += clamp(color.b * directional * u_lightcolor.b, mix(0.0, 0.3, 1.0 - u_lightcolor.b), 1.0);\n}\n"},fillExtrusionPattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec4 v_lighting;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\nvoid main() {\n    #pragma mapbox: initialize lowp float base\n    #pragma mapbox: initialize lowp float height\n\n    vec2 imagecoord = mod(v_pos_a, 1.0);\n    vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n    vec4 color1 = texture2D(u_image, pos);\n\n    vec2 imagecoord_b = mod(v_pos_b, 1.0);\n    vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n    vec4 color2 = texture2D(u_image, pos2);\n\n    vec4 mixedColor = mix(color1, color2, u_mix);\n\n    gl_FragColor = mixedColor * v_lighting;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\nuniform float u_height_factor;\n\nuniform vec3 u_lightcolor;\nuniform lowp vec3 u_lightpos;\nuniform lowp float u_lightintensity;\n\nattribute vec2 a_pos;\nattribute vec4 a_normal_ed;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec4 v_lighting;\nvarying float v_directional;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\nvoid main() {\n    #pragma mapbox: initialize lowp float base\n    #pragma mapbox: initialize lowp float height\n\n    vec3 normal = a_normal_ed.xyz;\n    float edgedistance = a_normal_ed.w;\n\n    base = max(0.0, base);\n    height = max(0.0, height);\n\n    float t = mod(normal.x, 2.0);\n    float z = t > 0.0 ? height : base;\n\n    gl_Position = u_matrix * vec4(a_pos, z, 1);\n\n    vec2 pos = normal.x == 1.0 && normal.y == 0.0 && normal.z == 16384.0\n        ? a_pos // extrusion top\n        : vec2(edgedistance, z * u_height_factor); // extrusion side\n\n    v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, pos);\n    v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, pos);\n\n    v_lighting = vec4(0.0, 0.0, 0.0, 1.0);\n    float directional = clamp(dot(normal / 16383.0, u_lightpos), 0.0, 1.0);\n    directional = mix((1.0 - u_lightintensity), max((0.5 + u_lightintensity), 1.0), directional);\n\n    if (normal.y != 0.0) {\n        directional *= clamp((t + base) * pow(height / 150.0, 0.5), mix(0.7, 0.98, 1.0 - u_lightintensity), 1.0);\n    }\n\n    v_lighting.rgb += clamp(directional * u_lightcolor, mix(vec3(0.0), vec3(0.3), 1.0 - u_lightcolor), vec3(1.0));\n}\n"},extrusionTexture:{fragmentSource:"uniform sampler2D u_image;\nuniform float u_opacity;\nvarying vec2 v_pos;\n\nvoid main() {\n    gl_FragColor = texture2D(u_image, v_pos) * u_opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(0.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_world;\nattribute vec2 a_pos;\nvarying vec2 v_pos;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos * u_world, 0, 1);\n\n    v_pos.x = a_pos.x;\n    v_pos.y = 1.0 - a_pos.y;\n}\n"},hillshadePrepare:{fragmentSource:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D u_image;\nvarying vec2 v_pos;\nuniform vec2 u_dimension;\nuniform float u_zoom;\nuniform float u_maxzoom;\n\nfloat getElevation(vec2 coord, float bias) {\n    // Convert encoded elevation value to meters\n    vec4 data = texture2D(u_image, coord) * 255.0;\n    return (data.r + data.g * 256.0 + data.b * 256.0 * 256.0) / 4.0;\n}\n\nvoid main() {\n    vec2 epsilon = 1.0 / u_dimension;\n\n    // queried pixels:\n    // +-----------+\n    // |   |   |   |\n    // | a | b | c |\n    // |   |   |   |\n    // +-----------+\n    // |   |   |   |\n    // | d | e | f |\n    // |   |   |   |\n    // +-----------+\n    // |   |   |   |\n    // | g | h | i |\n    // |   |   |   |\n    // +-----------+\n\n    float a = getElevation(v_pos + vec2(-epsilon.x, -epsilon.y), 0.0);\n    float b = getElevation(v_pos + vec2(0, -epsilon.y), 0.0);\n    float c = getElevation(v_pos + vec2(epsilon.x, -epsilon.y), 0.0);\n    float d = getElevation(v_pos + vec2(-epsilon.x, 0), 0.0);\n    float e = getElevation(v_pos, 0.0);\n    float f = getElevation(v_pos + vec2(epsilon.x, 0), 0.0);\n    float g = getElevation(v_pos + vec2(-epsilon.x, epsilon.y), 0.0);\n    float h = getElevation(v_pos + vec2(0, epsilon.y), 0.0);\n    float i = getElevation(v_pos + vec2(epsilon.x, epsilon.y), 0.0);\n\n    // here we divide the x and y slopes by 8 * pixel size\n    // where pixel size (aka meters/pixel) is:\n    // circumference of the world / (pixels per tile * number of tiles)\n    // which is equivalent to: 8 * 40075016.6855785 / (512 * pow(2, u_zoom))\n    // which can be reduced to: pow(2, 19.25619978527 - u_zoom)\n    // we want to vertically exaggerate the hillshading though, because otherwise\n    // it is barely noticeable at low zooms. to do this, we multiply this by some\n    // scale factor pow(2, (u_zoom - u_maxzoom) * a) where a is an arbitrary value\n    // Here we use a=0.3 which works out to the expression below. see \n    // nickidlugash's awesome breakdown for more info\n    // https://github.com/mapbox/mapbox-gl-js/pull/5286#discussion_r148419556\n    float exaggeration = u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;\n\n    vec2 deriv = vec2(\n        (c + f + f + i) - (a + d + d + g),\n        (g + h + h + i) - (a + b + b + c)\n    ) /  pow(2.0, (u_zoom - u_maxzoom) * exaggeration + 19.2562 - u_zoom);\n\n    gl_FragColor = clamp(vec4(\n        deriv.x / 2.0 + 0.5,\n        deriv.y / 2.0 + 0.5,\n        1.0,\n        1.0), 0.0, 1.0);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n    v_pos = (a_texture_pos / 8192.0) / 2.0 + 0.25;\n}\n"},hillshade:{fragmentSource:"uniform sampler2D u_image;\nvarying vec2 v_pos;\n\nuniform vec2 u_latrange;\nuniform vec2 u_light;\nuniform vec4 u_shadow;\nuniform vec4 u_highlight;\nuniform vec4 u_accent;\n\n#define PI 3.141592653589793\n\nvoid main() {\n    vec4 pixel = texture2D(u_image, v_pos);\n\n    vec2 deriv = ((pixel.rg * 2.0) - 1.0);\n\n    // We divide the slope by a scale factor based on the cosin of the pixel's approximate latitude\n    // to account for mercator projection distortion. see #4807 for details\n    float scaleFactor = cos(radians((u_latrange[0] - u_latrange[1]) * (1.0 - v_pos.y) + u_latrange[1]));\n    // We also multiply the slope by an arbitrary z-factor of 1.25\n    float slope = atan(1.25 * length(deriv) / scaleFactor);\n    float aspect = deriv.x != 0.0 ? atan(deriv.y, -deriv.x) : PI / 2.0 * (deriv.y > 0.0 ? 1.0 : -1.0);\n\n    float intensity = u_light.x;\n    // We add PI to make this property match the global light object, which adds PI/2 to the light's azimuthal\n    // position property to account for 0deg corresponding to north/the top of the viewport in the style spec\n    // and the original shader was written to accept (-illuminationDirection - 90) as the azimuthal.\n    float azimuth = u_light.y + PI;\n\n    // We scale the slope exponentially based on intensity, using a calculation similar to\n    // the exponential interpolation function in the style spec:\n    // https://github.com/mapbox/mapbox-gl-js/blob/master/src/style-spec/expression/definitions/interpolate.js#L217-L228\n    // so that higher intensity values create more opaque hillshading.\n    float base = 1.875 - intensity * 1.75;\n    float maxValue = 0.5 * PI;\n    float scaledSlope = intensity != 0.5 ? ((pow(base, slope) - 1.0) / (pow(base, maxValue) - 1.0)) * maxValue : slope;\n\n    // The accent color is calculated with the cosine of the slope while the shade color is calculated with the sine\n    // so that the accent color's rate of change eases in while the shade color's eases out.\n    float accent = cos(scaledSlope);\n    // We multiply both the accent and shade color by a clamped intensity value\n    // so that intensities >= 0.5 do not additionally affect the color values\n    // while intensity values < 0.5 make the overall color more transparent.\n    vec4 accent_color = (1.0 - accent) * u_accent * clamp(intensity * 2.0, 0.0, 1.0);\n    float shade = abs(mod((aspect + azimuth) / PI + 0.5, 2.0) - 1.0);\n    vec4 shade_color = mix(u_shadow, u_highlight, shade) * sin(scaledSlope) * clamp(intensity * 2.0, 0.0, 1.0);\n    gl_FragColor = accent_color * (1.0 - shade_color.a) + shade_color;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n    v_pos = a_texture_pos / 8192.0;\n}\n"},line:{fragmentSource:"#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_width2;\nvarying vec2 v_normal;\nvarying float v_gamma_scale;\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n\n    // Calculate the distance of the pixel from the line in pixels.\n    float dist = length(v_normal) * v_width2.s;\n\n    // Calculate the antialiasing fade factor. This is either when fading in\n    // the line in case of an offset line (v_width2.t) or when fading out\n    // (v_width2.s)\n    float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n    float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n    gl_FragColor = color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\n// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_gamma_scale;\nvarying highp float v_linesofar;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize mediump float gapwidth\n    #pragma mapbox: initialize lowp float offset\n    #pragma mapbox: initialize mediump float width\n\n    vec2 a_extrude = a_data.xy - 128.0;\n    float a_direction = mod(a_data.z, 4.0) - 1.0;\n\n    v_linesofar = (floor(a_data.z / 4.0) + a_data.w * 64.0) * 2.0;\n\n    vec2 pos = a_pos_normal.xy;\n\n    // x is 1 if it's a round cap, 0 otherwise\n    // y is 1 if the normal points up, and -1 if it points down\n    mediump vec2 normal = a_pos_normal.zw;\n    v_normal = normal;\n\n    // these transformations used to be applied in the JS and native code bases.\n    // moved them into the shader for clarity and simplicity.\n    gapwidth = gapwidth / 2.0;\n    float halfwidth = width / 2.0;\n    offset = -1.0 * offset;\n\n    float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n    float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n    // Scale the extrusion vector down to a normal and then up by the line width\n    // of this vertex.\n    mediump vec2 dist = outset * a_extrude * scale;\n\n    // Calculate the offset when drawing a line that is to the side of the actual line.\n    // We do this by creating a vector that points towards the extrude, but rotate\n    // it when we're drawing round end points (a_direction = -1 or 1) since their\n    // extrude vector points in another direction.\n    mediump float u = 0.5 * a_direction;\n    mediump float t = 1.0 - abs(u);\n    mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n    vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n    gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n    // calculate how much the perspective view squishes or stretches the extrude\n    float extrude_length_without_perspective = length(dist);\n    float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n    v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n    v_width2 = vec2(outset, inset);\n}\n"},lineGradient:{fragmentSource:"\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n\nuniform sampler2D u_image;\n\nvarying vec2 v_width2;\nvarying vec2 v_normal;\nvarying float v_gamma_scale;\nvarying highp float v_lineprogress;\n\nvoid main() {\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n\n    // Calculate the distance of the pixel from the line in pixels.\n    float dist = length(v_normal) * v_width2.s;\n\n    // Calculate the antialiasing fade factor. This is either when fading in\n    // the line in case of an offset line (v_width2.t) or when fading out\n    // (v_width2.s)\n    float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n    float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n    // For gradient lines, v_lineprogress is the ratio along the entire line,\n    // scaled to [0, 2^15), and the gradient ramp is stored in a texture.\n    vec4 color = texture2D(u_image, vec2(v_lineprogress, 0.5));\n\n    gl_FragColor = color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"\n// the attribute conveying progress along a line is scaled to [0, 2^15)\n#define MAX_LINE_DISTANCE 32767.0\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\n// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_gamma_scale;\nvarying highp float v_lineprogress;\n\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n\nvoid main() {\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize mediump float gapwidth\n    #pragma mapbox: initialize lowp float offset\n    #pragma mapbox: initialize mediump float width\n\n    vec2 a_extrude = a_data.xy - 128.0;\n    float a_direction = mod(a_data.z, 4.0) - 1.0;\n\n    v_lineprogress = (floor(a_data.z / 4.0) + a_data.w * 64.0) * 2.0 / MAX_LINE_DISTANCE;\n\n    vec2 pos = a_pos_normal.xy;\n\n    // x is 1 if it's a round cap, 0 otherwise\n    // y is 1 if the normal points up, and -1 if it points down\n    mediump vec2 normal = a_pos_normal.zw;\n    v_normal = normal;\n\n    // these transformations used to be applied in the JS and native code bases.\n    // moved them into the shader for clarity and simplicity.\n    gapwidth = gapwidth / 2.0;\n    float halfwidth = width / 2.0;\n    offset = -1.0 * offset;\n\n    float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n    float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n    // Scale the extrusion vector down to a normal and then up by the line width\n    // of this vertex.\n    mediump vec2 dist = outset * a_extrude * scale;\n\n    // Calculate the offset when drawing a line that is to the side of the actual line.\n    // We do this by creating a vector that points towards the extrude, but rotate\n    // it when we're drawing round end points (a_direction = -1 or 1) since their\n    // extrude vector points in another direction.\n    mediump float u = 0.5 * a_direction;\n    mediump float t = 1.0 - abs(u);\n    mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n    vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n    gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n    // calculate how much the perspective view squishes or stretches the extrude\n    float extrude_length_without_perspective = length(dist);\n    float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n    v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n    v_width2 = vec2(outset, inset);\n}\n"},linePattern:{fragmentSource:"uniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_fade;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_linesofar;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n\n    // Calculate the distance of the pixel from the line in pixels.\n    float dist = length(v_normal) * v_width2.s;\n\n    // Calculate the antialiasing fade factor. This is either when fading in\n    // the line in case of an offset line (v_width2.t) or when fading out\n    // (v_width2.s)\n    float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n    float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n    float x_a = mod(v_linesofar / u_pattern_size_a.x, 1.0);\n    float x_b = mod(v_linesofar / u_pattern_size_b.x, 1.0);\n\n    // v_normal.y is 0 at the midpoint of the line, -1 at the lower edge, 1 at the upper edge\n    // we clamp the line width outset to be between 0 and half the pattern height plus padding (2.0)\n    // to ensure we don't sample outside the designated symbol on the sprite sheet.\n    // 0.5 is added to shift the component to be bounded between 0 and 1 for interpolation of\n    // the texture coordinate\n    float y_a = 0.5 + (v_normal.y * clamp(v_width2.s, 0.0, (u_pattern_size_a.y + 2.0) / 2.0) / u_pattern_size_a.y);\n    float y_b = 0.5 + (v_normal.y * clamp(v_width2.s, 0.0, (u_pattern_size_b.y + 2.0) / 2.0) / u_pattern_size_b.y);\n    vec2 pos_a = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, vec2(x_a, y_a));\n    vec2 pos_b = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, vec2(x_b, y_b));\n\n    vec4 color = mix(texture2D(u_image, pos_a), texture2D(u_image, pos_b), u_fade);\n\n    gl_FragColor = color * alpha * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\n// We scale the distance before adding it to the buffers so that we can store\n// long distances for long segments. Use this value to unscale the distance.\n#define LINE_DISTANCE_SCALE 2.0\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_linesofar;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n\nvoid main() {\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize lowp float offset\n    #pragma mapbox: initialize mediump float gapwidth\n    #pragma mapbox: initialize mediump float width\n\n    vec2 a_extrude = a_data.xy - 128.0;\n    float a_direction = mod(a_data.z, 4.0) - 1.0;\n    float a_linesofar = (floor(a_data.z / 4.0) + a_data.w * 64.0) * LINE_DISTANCE_SCALE;\n\n    vec2 pos = a_pos_normal.xy;\n\n    // x is 1 if it's a round cap, 0 otherwise\n    // y is 1 if the normal points up, and -1 if it points down\n    mediump vec2 normal = a_pos_normal.zw;\n    v_normal = normal;\n\n    // these transformations used to be applied in the JS and native code bases.\n    // moved them into the shader for clarity and simplicity.\n    gapwidth = gapwidth / 2.0;\n    float halfwidth = width / 2.0;\n    offset = -1.0 * offset;\n\n    float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n    float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n    // Scale the extrusion vector down to a normal and then up by the line width\n    // of this vertex.\n    mediump vec2 dist = outset * a_extrude * scale;\n\n    // Calculate the offset when drawing a line that is to the side of the actual line.\n    // We do this by creating a vector that points towards the extrude, but rotate\n    // it when we're drawing round end points (a_direction = -1 or 1) since their\n    // extrude vector points in another direction.\n    mediump float u = 0.5 * a_direction;\n    mediump float t = 1.0 - abs(u);\n    mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n    vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n    gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n    // calculate how much the perspective view squishes or stretches the extrude\n    float extrude_length_without_perspective = length(dist);\n    float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n    v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n    v_linesofar = a_linesofar;\n    v_width2 = vec2(outset, inset);\n}\n"},lineSDF:{fragmentSource:"\nuniform sampler2D u_image;\nuniform float u_sdfgamma;\nuniform float u_mix;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying vec2 v_tex_a;\nvarying vec2 v_tex_b;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize mediump float width\n    #pragma mapbox: initialize lowp float floorwidth\n\n    // Calculate the distance of the pixel from the line in pixels.\n    float dist = length(v_normal) * v_width2.s;\n\n    // Calculate the antialiasing fade factor. This is either when fading in\n    // the line in case of an offset line (v_width2.t) or when fading out\n    // (v_width2.s)\n    float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n    float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n    float sdfdist_a = texture2D(u_image, v_tex_a).a;\n    float sdfdist_b = texture2D(u_image, v_tex_b).a;\n    float sdfdist = mix(sdfdist_a, sdfdist_b, u_mix);\n    alpha *= smoothstep(0.5 - u_sdfgamma / floorwidth, 0.5 + u_sdfgamma / floorwidth, sdfdist);\n\n    gl_FragColor = color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\n// We scale the distance before adding it to the buffers so that we can store\n// long distances for long segments. Use this value to unscale the distance.\n#define LINE_DISTANCE_SCALE 2.0\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_patternscale_a;\nuniform float u_tex_y_a;\nuniform vec2 u_patternscale_b;\nuniform float u_tex_y_b;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying vec2 v_tex_a;\nvarying vec2 v_tex_b;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize mediump float gapwidth\n    #pragma mapbox: initialize lowp float offset\n    #pragma mapbox: initialize mediump float width\n    #pragma mapbox: initialize lowp float floorwidth\n\n    vec2 a_extrude = a_data.xy - 128.0;\n    float a_direction = mod(a_data.z, 4.0) - 1.0;\n    float a_linesofar = (floor(a_data.z / 4.0) + a_data.w * 64.0) * LINE_DISTANCE_SCALE;\n\n    vec2 pos = a_pos_normal.xy;\n\n    // x is 1 if it's a round cap, 0 otherwise\n    // y is 1 if the normal points up, and -1 if it points down\n    mediump vec2 normal = a_pos_normal.zw;\n    v_normal = normal;\n\n    // these transformations used to be applied in the JS and native code bases.\n    // moved them into the shader for clarity and simplicity.\n    gapwidth = gapwidth / 2.0;\n    float halfwidth = width / 2.0;\n    offset = -1.0 * offset;\n\n    float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n    float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n    // Scale the extrusion vector down to a normal and then up by the line width\n    // of this vertex.\n    mediump vec2 dist =outset * a_extrude * scale;\n\n    // Calculate the offset when drawing a line that is to the side of the actual line.\n    // We do this by creating a vector that points towards the extrude, but rotate\n    // it when we're drawing round end points (a_direction = -1 or 1) since their\n    // extrude vector points in another direction.\n    mediump float u = 0.5 * a_direction;\n    mediump float t = 1.0 - abs(u);\n    mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n    vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n    gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n    // calculate how much the perspective view squishes or stretches the extrude\n    float extrude_length_without_perspective = length(dist);\n    float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n    v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n    v_tex_a = vec2(a_linesofar * u_patternscale_a.x / floorwidth, normal.y * u_patternscale_a.y + u_tex_y_a);\n    v_tex_b = vec2(a_linesofar * u_patternscale_b.x / floorwidth, normal.y * u_patternscale_b.y + u_tex_y_b);\n\n    v_width2 = vec2(outset, inset);\n}\n"},raster:{fragmentSource:"uniform float u_fade_t;\nuniform float u_opacity;\nuniform sampler2D u_image0;\nuniform sampler2D u_image1;\nvarying vec2 v_pos0;\nvarying vec2 v_pos1;\n\nuniform float u_brightness_low;\nuniform float u_brightness_high;\n\nuniform float u_saturation_factor;\nuniform float u_contrast_factor;\nuniform vec3 u_spin_weights;\n\nvoid main() {\n\n    // read and cross-fade colors from the main and parent tiles\n    vec4 color0 = texture2D(u_image0, v_pos0);\n    vec4 color1 = texture2D(u_image1, v_pos1);\n    if (color0.a > 0.0) {\n        color0.rgb = color0.rgb / color0.a;\n    }\n    if (color1.a > 0.0) {\n        color1.rgb = color1.rgb / color1.a;\n    }\n    vec4 color = mix(color0, color1, u_fade_t);\n    color.a *= u_opacity;\n    vec3 rgb = color.rgb;\n\n    // spin\n    rgb = vec3(\n        dot(rgb, u_spin_weights.xyz),\n        dot(rgb, u_spin_weights.zxy),\n        dot(rgb, u_spin_weights.yzx));\n\n    // saturation\n    float average = (color.r + color.g + color.b) / 3.0;\n    rgb += (average - rgb) * u_saturation_factor;\n\n    // contrast\n    rgb = (rgb - 0.5) * u_contrast_factor + 0.5;\n\n    // brightness\n    vec3 u_high_vec = vec3(u_brightness_low, u_brightness_low, u_brightness_low);\n    vec3 u_low_vec = vec3(u_brightness_high, u_brightness_high, u_brightness_high);\n\n    gl_FragColor = vec4(mix(u_high_vec, u_low_vec, rgb) * color.a, color.a);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_tl_parent;\nuniform float u_scale_parent;\nuniform float u_buffer_scale;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos0;\nvarying vec2 v_pos1;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n    // We are using Int16 for texture position coordinates to give us enough precision for\n    // fractional coordinates. We use 8192 to scale the texture coordinates in the buffer\n    // as an arbitrarily high number to preserve adequate precision when rendering.\n    // This is also the same value as the EXTENT we are using for our tile buffer pos coordinates,\n    // so math for modifying either is consistent.\n    v_pos0 = (((a_texture_pos / 8192.0) - 0.5) / u_buffer_scale ) + 0.5;\n    v_pos1 = (v_pos0 * u_scale_parent) + u_tl_parent;\n}\n"},symbolIcon:{fragmentSource:"uniform sampler2D u_texture;\n\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_tex;\nvarying float v_fade_opacity;\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    lowp float alpha = opacity * v_fade_opacity;\n    gl_FragColor = texture2D(u_texture, v_tex) * alpha;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"const float PI = 3.141592653589793;\n\nattribute vec4 a_pos_offset;\nattribute vec4 a_data;\nattribute vec3 a_projected_pos;\nattribute float a_fade_opacity;\n\nuniform bool u_is_size_zoom_constant;\nuniform bool u_is_size_feature_constant;\nuniform highp float u_size_t; // used to interpolate between zoom stops when size is a composite function\nuniform highp float u_size; // used when size is both zoom and feature constant\nuniform highp float u_camera_to_center_distance;\nuniform highp float u_pitch;\nuniform bool u_rotate_symbol;\nuniform highp float u_aspect_ratio;\nuniform float u_fade_change;\n\n#pragma mapbox: define lowp float opacity\n\nuniform mat4 u_matrix;\nuniform mat4 u_label_plane_matrix;\nuniform mat4 u_gl_coord_matrix;\n\nuniform bool u_is_text;\nuniform bool u_pitch_with_map;\n\nuniform vec2 u_texsize;\n\nvarying vec2 v_tex;\nvarying float v_fade_opacity;\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    vec2 a_pos = a_pos_offset.xy;\n    vec2 a_offset = a_pos_offset.zw;\n\n    vec2 a_tex = a_data.xy;\n    vec2 a_size = a_data.zw;\n\n    highp float segment_angle = -a_projected_pos[2];\n\n    float size;\n    if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {\n        size = mix(a_size[0], a_size[1], u_size_t) / 10.0;\n    } else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {\n        size = a_size[0] / 10.0;\n    } else if (!u_is_size_zoom_constant && u_is_size_feature_constant) {\n        size = u_size;\n    } else {\n        size = u_size;\n    }\n\n    vec4 projectedPoint = u_matrix * vec4(a_pos, 0, 1);\n    highp float camera_to_anchor_distance = projectedPoint.w;\n    // See comments in symbol_sdf.vertex\n    highp float distance_ratio = u_pitch_with_map ?\n        camera_to_anchor_distance / u_camera_to_center_distance :\n        u_camera_to_center_distance / camera_to_anchor_distance;\n    highp float perspective_ratio = clamp(\n            0.5 + 0.5 * distance_ratio,\n            0.0, // Prevents oversized near-field symbols in pitched/overzoomed tiles\n            4.0);\n\n    size *= perspective_ratio;\n\n    float fontScale = u_is_text ? size / 24.0 : size;\n\n    highp float symbol_rotation = 0.0;\n    if (u_rotate_symbol) {\n        // See comments in symbol_sdf.vertex\n        vec4 offsetProjectedPoint = u_matrix * vec4(a_pos + vec2(1, 0), 0, 1);\n\n        vec2 a = projectedPoint.xy / projectedPoint.w;\n        vec2 b = offsetProjectedPoint.xy / offsetProjectedPoint.w;\n\n        symbol_rotation = atan((b.y - a.y) / u_aspect_ratio, b.x - a.x);\n    }\n\n    highp float angle_sin = sin(segment_angle + symbol_rotation);\n    highp float angle_cos = cos(segment_angle + symbol_rotation);\n    mat2 rotation_matrix = mat2(angle_cos, -1.0 * angle_sin, angle_sin, angle_cos);\n\n    vec4 projected_pos = u_label_plane_matrix * vec4(a_projected_pos.xy, 0.0, 1.0);\n    gl_Position = u_gl_coord_matrix * vec4(projected_pos.xy / projected_pos.w + rotation_matrix * (a_offset / 32.0 * fontScale), 0.0, 1.0);\n\n    v_tex = a_tex / u_texsize;\n    vec2 fade_opacity = unpack_opacity(a_fade_opacity);\n    float fade_change = fade_opacity[1] > 0.5 ? u_fade_change : -u_fade_change;\n    v_fade_opacity = max(0.0, min(1.0, fade_opacity[0] + fade_change));\n}\n"},symbolSDF:{fragmentSource:"#define SDF_PX 8.0\n#define EDGE_GAMMA 0.105/DEVICE_PIXEL_RATIO\n\nuniform bool u_is_halo;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\n\nuniform sampler2D u_texture;\nuniform highp float u_gamma_scale;\nuniform bool u_is_text;\n\nvarying vec2 v_data0;\nvarying vec3 v_data1;\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 fill_color\n    #pragma mapbox: initialize highp vec4 halo_color\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize lowp float halo_width\n    #pragma mapbox: initialize lowp float halo_blur\n\n    vec2 tex = v_data0.xy;\n    float gamma_scale = v_data1.x;\n    float size = v_data1.y;\n    float fade_opacity = v_data1[2];\n\n    float fontScale = u_is_text ? size / 24.0 : size;\n\n    lowp vec4 color = fill_color;\n    highp float gamma = EDGE_GAMMA / (fontScale * u_gamma_scale);\n    lowp float buff = (256.0 - 64.0) / 256.0;\n    if (u_is_halo) {\n        color = halo_color;\n        gamma = (halo_blur * 1.19 / SDF_PX + EDGE_GAMMA) / (fontScale * u_gamma_scale);\n        buff = (6.0 - halo_width / fontScale) / SDF_PX;\n    }\n\n    lowp float dist = texture2D(u_texture, tex).a;\n    highp float gamma_scaled = gamma * gamma_scale;\n    highp float alpha = smoothstep(buff - gamma_scaled, buff + gamma_scaled, dist);\n\n    gl_FragColor = color * (alpha * opacity * fade_opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"const float PI = 3.141592653589793;\n\nattribute vec4 a_pos_offset;\nattribute vec4 a_data;\nattribute vec3 a_projected_pos;\nattribute float a_fade_opacity;\n\n// contents of a_size vary based on the type of property value\n// used for {text,icon}-size.\n// For constants, a_size is disabled.\n// For source functions, we bind only one value per vertex: the value of {text,icon}-size evaluated for the current feature.\n// For composite functions:\n// [ text-size(lowerZoomStop, feature),\n//   text-size(upperZoomStop, feature) ]\nuniform bool u_is_size_zoom_constant;\nuniform bool u_is_size_feature_constant;\nuniform highp float u_size_t; // used to interpolate between zoom stops when size is a composite function\nuniform highp float u_size; // used when size is both zoom and feature constant\n\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\n\nuniform mat4 u_matrix;\nuniform mat4 u_label_plane_matrix;\nuniform mat4 u_gl_coord_matrix;\n\nuniform bool u_is_text;\nuniform bool u_pitch_with_map;\nuniform highp float u_pitch;\nuniform bool u_rotate_symbol;\nuniform highp float u_aspect_ratio;\nuniform highp float u_camera_to_center_distance;\nuniform float u_fade_change;\n\nuniform vec2 u_texsize;\n\nvarying vec2 v_data0;\nvarying vec3 v_data1;\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 fill_color\n    #pragma mapbox: initialize highp vec4 halo_color\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize lowp float halo_width\n    #pragma mapbox: initialize lowp float halo_blur\n\n    vec2 a_pos = a_pos_offset.xy;\n    vec2 a_offset = a_pos_offset.zw;\n\n    vec2 a_tex = a_data.xy;\n    vec2 a_size = a_data.zw;\n\n    highp float segment_angle = -a_projected_pos[2];\n    float size;\n\n    if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {\n        size = mix(a_size[0], a_size[1], u_size_t) / 10.0;\n    } else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {\n        size = a_size[0] / 10.0;\n    } else if (!u_is_size_zoom_constant && u_is_size_feature_constant) {\n        size = u_size;\n    } else {\n        size = u_size;\n    }\n\n    vec4 projectedPoint = u_matrix * vec4(a_pos, 0, 1);\n    highp float camera_to_anchor_distance = projectedPoint.w;\n    // If the label is pitched with the map, layout is done in pitched space,\n    // which makes labels in the distance smaller relative to viewport space.\n    // We counteract part of that effect by multiplying by the perspective ratio.\n    // If the label isn't pitched with the map, we do layout in viewport space,\n    // which makes labels in the distance larger relative to the features around\n    // them. We counteract part of that effect by dividing by the perspective ratio.\n    highp float distance_ratio = u_pitch_with_map ?\n        camera_to_anchor_distance / u_camera_to_center_distance :\n        u_camera_to_center_distance / camera_to_anchor_distance;\n    highp float perspective_ratio = clamp(\n        0.5 + 0.5 * distance_ratio,\n        0.0, // Prevents oversized near-field symbols in pitched/overzoomed tiles\n        4.0);\n\n    size *= perspective_ratio;\n\n    float fontScale = u_is_text ? size / 24.0 : size;\n\n    highp float symbol_rotation = 0.0;\n    if (u_rotate_symbol) {\n        // Point labels with 'rotation-alignment: map' are horizontal with respect to tile units\n        // To figure out that angle in projected space, we draw a short horizontal line in tile\n        // space, project it, and measure its angle in projected space.\n        vec4 offsetProjectedPoint = u_matrix * vec4(a_pos + vec2(1, 0), 0, 1);\n\n        vec2 a = projectedPoint.xy / projectedPoint.w;\n        vec2 b = offsetProjectedPoint.xy / offsetProjectedPoint.w;\n\n        symbol_rotation = atan((b.y - a.y) / u_aspect_ratio, b.x - a.x);\n    }\n\n    highp float angle_sin = sin(segment_angle + symbol_rotation);\n    highp float angle_cos = cos(segment_angle + symbol_rotation);\n    mat2 rotation_matrix = mat2(angle_cos, -1.0 * angle_sin, angle_sin, angle_cos);\n\n    vec4 projected_pos = u_label_plane_matrix * vec4(a_projected_pos.xy, 0.0, 1.0);\n    gl_Position = u_gl_coord_matrix * vec4(projected_pos.xy / projected_pos.w + rotation_matrix * (a_offset / 32.0 * fontScale), 0.0, 1.0);\n    float gamma_scale = gl_Position.w;\n\n    vec2 tex = a_tex / u_texsize;\n    vec2 fade_opacity = unpack_opacity(a_fade_opacity);\n    float fade_change = fade_opacity[1] > 0.5 ? u_fade_change : -u_fade_change;\n    float interpolated_fade_opacity = max(0.0, min(1.0, fade_opacity[0] + fade_change));\n\n    v_data0 = vec2(tex.x, tex.y);\n    v_data1 = vec3(gamma_scale, size, interpolated_fade_opacity);\n}\n"}},tr=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,er=function(t){var e=Qe[t],r={};e.fragmentSource=e.fragmentSource.replace(tr,function(t,e,n,i,a){return r[a]=!0,"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nvarying "+n+" "+i+" "+a+";\n#else\nuniform "+n+" "+i+" u_"+a+";\n#endif\n":"\n#ifdef HAS_UNIFORM_u_"+a+"\n    "+n+" "+i+" "+a+" = u_"+a+";\n#endif\n"}),e.vertexSource=e.vertexSource.replace(tr,function(t,e,n,i,a){var o="float"===i?"vec2":"vec4";return r[a]?"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nuniform lowp float a_"+a+"_t;\nattribute "+n+" "+o+" a_"+a+";\nvarying "+n+" "+i+" "+a+";\n#else\nuniform "+n+" "+i+" u_"+a+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+a+"\n    "+a+" = unpack_mix_"+o+"(a_"+a+", a_"+a+"_t);\n#else\n    "+n+" "+i+" "+a+" = u_"+a+";\n#endif\n":"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nuniform lowp float a_"+a+"_t;\nattribute "+n+" "+o+" a_"+a+";\n#else\nuniform "+n+" "+i+" u_"+a+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+a+"\n    "+n+" "+i+" "+a+" = unpack_mix_"+o+"(a_"+a+", a_"+a+"_t);\n#else\n    "+n+" "+i+" "+a+" = u_"+a+";\n#endif\n"})};for(var rr in Qe)er(rr);var nr=Qe,ir=function(t,e,r,n){var i=t.gl;this.program=i.createProgram();var o=r.defines().concat("#define DEVICE_PIXEL_RATIO "+a.devicePixelRatio.toFixed(1));n&&o.push("#define OVERDRAW_INSPECTOR;");var s=o.concat(nr.prelude.fragmentSource,e.fragmentSource).join("\n"),l=o.concat(nr.prelude.vertexSource,e.vertexSource).join("\n"),c=i.createShader(i.FRAGMENT_SHADER);i.shaderSource(c,s),i.compileShader(c),i.attachShader(this.program,c);var u=i.createShader(i.VERTEX_SHADER);i.shaderSource(u,l),i.compileShader(u),i.attachShader(this.program,u);for(var h=r.layoutAttributes||[],f=0;f<h.length;f++)i.bindAttribLocation(this.program,f,h[f].name);i.linkProgram(this.program),this.numAttributes=i.getProgramParameter(this.program,i.ACTIVE_ATTRIBUTES),this.attributes={},this.uniforms={};for(var p=0;p<this.numAttributes;p++){var d=i.getActiveAttrib(this.program,p);d&&(this.attributes[d.name]=i.getAttribLocation(this.program,d.name))}for(var g=i.getProgramParameter(this.program,i.ACTIVE_UNIFORMS),v=0;v<g;v++){var m=i.getActiveUniform(this.program,v);m&&(this.uniforms[m.name]=i.getUniformLocation(this.program,m.name))}};function ar(e,r,n,i,a){for(var o=0;o<n.length;o++){var s=n[o];if(i.isLessThan(s.tileID))break;if(r.key===s.tileID.key)return;if(s.tileID.isChildOf(r)){for(var l=r.children(1/0),c=0;c<l.length;c++)ar(e,l[c],n.slice(o),i,a);return}}var u=r.overscaledZ-e.overscaledZ,h=new t.CanonicalTileID(u,r.canonical.x-(e.canonical.x<<u),r.canonical.y-(e.canonical.y<<u));a[h.key]=a[h.key]||h}function or(t,e,r,n,i){var a=t.context,o=a.gl,s=i?t.useProgram("collisionCircle"):t.useProgram("collisionBox");a.setDepthMode(qt.disabled),a.setStencilMode(Ht.disabled),a.setColorMode(t.colorModeForRenderPass());for(var l=0;l<n.length;l++){var c=n[l],u=e.getTile(c),h=u.getBucket(r);if(h){var f=i?h.collisionCircle:h.collisionBox;if(f){o.uniformMatrix4fv(s.uniforms.u_matrix,!1,c.posMatrix),i||a.lineWidth.set(1),o.uniform1f(s.uniforms.u_camera_to_center_distance,t.transform.cameraToCenterDistance);var p=Te(u,1,t.transform.zoom),d=Math.pow(2,t.transform.zoom-u.tileID.overscaledZ);o.uniform1f(s.uniforms.u_pixels_to_tile_units,p),o.uniform2f(s.uniforms.u_extrude_scale,t.transform.pixelsToGLUnits[0]/(p*d),t.transform.pixelsToGLUnits[1]/(p*d)),o.uniform1f(s.uniforms.u_overscale_factor,u.tileID.overscaleFactor()),s.draw(a,i?o.TRIANGLES:o.LINES,r.id,f.layoutVertexBuffer,f.indexBuffer,f.segments,null,f.collisionVertexBuffer,null)}}}}ir.prototype.draw=function(t,e,r,n,i,a,o,s,l){for(var c,u=t.gl,h=(c={},c[u.LINES]=2,c[u.TRIANGLES]=3,c)[e],f=0,p=a.get();f<p.length;f+=1){var d=p[f],g=d.vaos||(d.vaos={});(g[r]||(g[r]=new Q)).bind(t,this,n,o?o.getPaintVertexBuffers():[],i,d.vertexOffset,s,l),u.drawElements(e,d.primitiveLength*h,u.UNSIGNED_SHORT,d.primitiveOffset*h*2)}};var sr=t.mat4.identity(new Float32Array(16)),lr=t.default$19.layout;function cr(t,e,r,n,i,a,o,s,l,c){var u,h=t.context,f=h.gl,p=t.transform,d="map"===s,g="map"===l,v=d&&"line"===r.layout.get("symbol-placement"),m=d&&!g&&!v,y=g;h.setDepthMode(y?t.depthModeForSublayer(0,qt.ReadOnly):qt.disabled);for(var x=0,b=n;x<b.length;x+=1){var _=b[x],w=e.getTile(_),k=w.getBucket(r);if(k){var A=i?k.text:k.icon;if(A&&A.segments.get().length){var M=A.programConfigurations.get(r.id),T=i||k.sdfIcons,S=i?k.textSizeData:k.iconSizeData;if(u||(u=t.useProgram(T?"symbolSDF":"symbolIcon",M),M.setUniforms(t.context,u,r.paint,{zoom:t.transform.zoom}),ur(u,t,r,i,m,g,S)),h.activeTexture.set(f.TEXTURE0),f.uniform1i(u.uniforms.u_texture,0),i)w.glyphAtlasTexture.bind(f.LINEAR,f.CLAMP_TO_EDGE),f.uniform2fv(u.uniforms.u_texsize,w.glyphAtlasTexture.size);else{var E=1!==r.layout.get("icon-size").constantOr(0)||k.iconsNeedLinear,C=g||0!==p.pitch;w.iconAtlasTexture.bind(T||t.options.rotating||t.options.zooming||E||C?f.LINEAR:f.NEAREST,f.CLAMP_TO_EDGE),f.uniform2fv(u.uniforms.u_texsize,w.iconAtlasTexture.size)}f.uniformMatrix4fv(u.uniforms.u_matrix,!1,t.translatePosMatrix(_.posMatrix,w,a,o));var L=Te(w,1,t.transform.zoom),z=he(_.posMatrix,g,d,t.transform,L),O=fe(_.posMatrix,g,d,t.transform,L);f.uniformMatrix4fv(u.uniforms.u_gl_coord_matrix,!1,t.translatePosMatrix(O,w,a,o,!0)),v?(f.uniformMatrix4fv(u.uniforms.u_label_plane_matrix,!1,sr),ge(k,_.posMatrix,t,i,z,O,g,c)):f.uniformMatrix4fv(u.uniforms.u_label_plane_matrix,!1,z),f.uniform1f(u.uniforms.u_fade_change,t.options.fadeDuration?t.symbolFadeChange:1),hr(u,M,t,r,w,A,i,T,g)}}}}function ur(e,r,n,i,a,o,s){var l=r.context.gl,c=r.transform;l.uniform1i(e.uniforms.u_pitch_with_map,o?1:0),l.uniform1f(e.uniforms.u_is_text,i?1:0),l.uniform1f(e.uniforms.u_pitch,c.pitch/360*2*Math.PI);var u="constant"===s.functionType||"source"===s.functionType,h="constant"===s.functionType||"camera"===s.functionType;l.uniform1i(e.uniforms.u_is_size_zoom_constant,u?1:0),l.uniform1i(e.uniforms.u_is_size_feature_constant,h?1:0),l.uniform1f(e.uniforms.u_camera_to_center_distance,c.cameraToCenterDistance);var f=t.evaluateSizeForZoom(s,c.zoom,lr.properties[i?"text-size":"icon-size"]);void 0!==f.uSizeT&&l.uniform1f(e.uniforms.u_size_t,f.uSizeT),void 0!==f.uSize&&l.uniform1f(e.uniforms.u_size,f.uSize),l.uniform1f(e.uniforms.u_aspect_ratio,c.width/c.height),l.uniform1i(e.uniforms.u_rotate_symbol,a?1:0)}function hr(t,e,r,n,i,a,o,s,l){var c=r.context,u=c.gl,h=r.transform;if(s){var f=0!==n.paint.get(o?"text-halo-width":"icon-halo-width").constantOr(1),p=l?Math.cos(h._pitch)*h.cameraToCenterDistance:1;u.uniform1f(t.uniforms.u_gamma_scale,p),f&&(u.uniform1f(t.uniforms.u_is_halo,1),fr(a,n,c,t)),u.uniform1f(t.uniforms.u_is_halo,0)}fr(a,n,c,t)}function fr(t,e,r,n){n.draw(r,r.gl.TRIANGLES,e.id,t.layoutVertexBuffer,t.indexBuffer,t.segments,t.programConfigurations.get(e.id),t.dynamicLayoutVertexBuffer,t.opacityVertexBuffer)}function pr(t,e,r,n,i,o,s,l,c){var u,h,f,p,d=e.context,g=d.gl,v=i.paint.get("line-dasharray"),m=i.paint.get("line-pattern");if(l||c){var y=1/Te(r,1,e.transform.tileZoom);if(v){u=e.lineAtlas.getDash(v.from,"round"===i.layout.get("line-cap")),h=e.lineAtlas.getDash(v.to,"round"===i.layout.get("line-cap"));var x=u.width*v.fromScale,b=h.width*v.toScale;g.uniform2f(t.uniforms.u_patternscale_a,y/x,-u.height/2),g.uniform2f(t.uniforms.u_patternscale_b,y/b,-h.height/2),g.uniform1f(t.uniforms.u_sdfgamma,e.lineAtlas.width/(256*Math.min(x,b)*a.devicePixelRatio)/2)}else if(m){if(f=e.imageManager.getPattern(m.from),p=e.imageManager.getPattern(m.to),!f||!p)return;g.uniform2f(t.uniforms.u_pattern_size_a,f.displaySize[0]*m.fromScale/y,f.displaySize[1]),g.uniform2f(t.uniforms.u_pattern_size_b,p.displaySize[0]*m.toScale/y,p.displaySize[1]);var _=e.imageManager.getPixelSize(),w=_.width,k=_.height;g.uniform2fv(t.uniforms.u_texsize,[w,k])}g.uniform2f(t.uniforms.u_gl_units_to_pixels,1/e.transform.pixelsToGLUnits[0],1/e.transform.pixelsToGLUnits[1])}l&&(v?(g.uniform1i(t.uniforms.u_image,0),d.activeTexture.set(g.TEXTURE0),e.lineAtlas.bind(d),g.uniform1f(t.uniforms.u_tex_y_a,u.y),g.uniform1f(t.uniforms.u_tex_y_b,h.y),g.uniform1f(t.uniforms.u_mix,v.t)):m&&(g.uniform1i(t.uniforms.u_image,0),d.activeTexture.set(g.TEXTURE0),e.imageManager.bind(d),g.uniform2fv(t.uniforms.u_pattern_tl_a,f.tl),g.uniform2fv(t.uniforms.u_pattern_br_a,f.br),g.uniform2fv(t.uniforms.u_pattern_tl_b,p.tl),g.uniform2fv(t.uniforms.u_pattern_br_b,p.br),g.uniform1f(t.uniforms.u_fade,m.t))),d.setStencilMode(e.stencilModeForClipping(o));var A=e.translatePosMatrix(o.posMatrix,r,i.paint.get("line-translate"),i.paint.get("line-translate-anchor"));if(g.uniformMatrix4fv(t.uniforms.u_matrix,!1,A),g.uniform1f(t.uniforms.u_ratio,1/Te(r,1,e.transform.zoom)),i.paint.get("line-gradient")){d.activeTexture.set(g.TEXTURE0);var M=i.gradientTexture;if(!i.gradient)return;M||(M=i.gradientTexture=new z(d,i.gradient,g.RGBA)),M.bind(g.LINEAR,g.CLAMP_TO_EDGE),g.uniform1i(t.uniforms.u_image,0)}t.draw(d,g.TRIANGLES,i.id,n.layoutVertexBuffer,n.indexBuffer,n.segments,s)}var dr=function(t,e){if(!t)return!1;var r=e.imageManager.getPattern(t.from),n=e.imageManager.getPattern(t.to);return!r||!n},gr=function(t,e,r){var n=e.context,i=n.gl,a=e.imageManager.getPattern(t.from),o=e.imageManager.getPattern(t.to);i.uniform1i(r.uniforms.u_image,0),i.uniform2fv(r.uniforms.u_pattern_tl_a,a.tl),i.uniform2fv(r.uniforms.u_pattern_br_a,a.br),i.uniform2fv(r.uniforms.u_pattern_tl_b,o.tl),i.uniform2fv(r.uniforms.u_pattern_br_b,o.br);var s=e.imageManager.getPixelSize(),l=s.width,c=s.height;i.uniform2fv(r.uniforms.u_texsize,[l,c]),i.uniform1f(r.uniforms.u_mix,t.t),i.uniform2fv(r.uniforms.u_pattern_size_a,a.displaySize),i.uniform2fv(r.uniforms.u_pattern_size_b,o.displaySize),i.uniform1f(r.uniforms.u_scale_a,t.fromScale),i.uniform1f(r.uniforms.u_scale_b,t.toScale),n.activeTexture.set(i.TEXTURE0),e.imageManager.bind(e.context)},vr=function(t,e,r){var n=e.context.gl;n.uniform1f(r.uniforms.u_tile_units_to_pixels,1/Te(t,1,e.transform.tileZoom));var i=Math.pow(2,t.tileID.overscaledZ),a=t.tileSize*Math.pow(2,e.transform.tileZoom)/i,o=a*(t.tileID.canonical.x+t.tileID.wrap*i),s=a*t.tileID.canonical.y;n.uniform2f(r.uniforms.u_pixel_coord_upper,o>>16,s>>16),n.uniform2f(r.uniforms.u_pixel_coord_lower,65535&o,65535&s)};function mr(t,e,r,n,i){if(!dr(r.paint.get("fill-pattern"),t))for(var a=!0,o=0,s=n;o<s.length;o+=1){var l=s[o],c=e.getTile(l),u=c.getBucket(r);u&&(t.context.setStencilMode(t.stencilModeForClipping(l)),i(t,e,r,c,l,u,a),a=!1)}}function yr(t,e,r,n,i,a,o){var s=t.context.gl,l=a.programConfigurations.get(r.id);br("fill",r.paint.get("fill-pattern"),t,l,r,n,i,o).draw(t.context,s.TRIANGLES,r.id,a.layoutVertexBuffer,a.indexBuffer,a.segments,l)}function xr(t,e,r,n,i,a,o){var s=t.context.gl,l=a.programConfigurations.get(r.id),c=br("fillOutline",r.getPaintProperty("fill-outline-color")?null:r.paint.get("fill-pattern"),t,l,r,n,i,o);s.uniform2f(c.uniforms.u_world,s.drawingBufferWidth,s.drawingBufferHeight),c.draw(t.context,s.LINES,r.id,a.layoutVertexBuffer,a.indexBuffer2,a.segments2,l)}function br(t,e,r,n,i,a,o,s){var l,c=r.context.program.get();return e?(l=r.useProgram(t+"Pattern",n),(s||l.program!==c)&&(n.setUniforms(r.context,l,i.paint,{zoom:r.transform.zoom}),gr(e,r,l)),vr(a,r,l)):(l=r.useProgram(t,n),(s||l.program!==c)&&n.setUniforms(r.context,l,i.paint,{zoom:r.transform.zoom})),r.context.gl.uniformMatrix4fv(l.uniforms.u_matrix,!1,r.translatePosMatrix(o.posMatrix,a,i.paint.get("fill-translate"),i.paint.get("fill-translate-anchor"))),l}var _r=t.default$20.mat3,wr=t.default$20.mat4,kr=t.default$20.vec3;function Ar(t,e,r,n,i,a,o){var s=t.context,l=s.gl,c=r.paint.get("fill-extrusion-pattern"),u=t.context.program.get(),h=a.programConfigurations.get(r.id),f=t.useProgram(c?"fillExtrusionPattern":"fillExtrusion",h);if((o||f.program!==u)&&h.setUniforms(s,f,r.paint,{zoom:t.transform.zoom}),c){if(dr(c,t))return;gr(c,t,f),vr(n,t,f),l.uniform1f(f.uniforms.u_height_factor,-Math.pow(2,i.overscaledZ)/n.tileSize/8)}t.context.gl.uniformMatrix4fv(f.uniforms.u_matrix,!1,t.translatePosMatrix(i.posMatrix,n,r.paint.get("fill-extrusion-translate"),r.paint.get("fill-extrusion-translate-anchor"))),function(t,e){var r=e.context.gl,n=e.style.light,i=n.properties.get("position"),a=[i.x,i.y,i.z],o=_r.create();"viewport"===n.properties.get("anchor")&&_r.fromRotation(o,-e.transform.angle),kr.transformMat3(a,a,o);var s=n.properties.get("color");r.uniform3fv(t.uniforms.u_lightpos,a),r.uniform1f(t.uniforms.u_lightintensity,n.properties.get("intensity")),r.uniform3f(t.uniforms.u_lightcolor,s.r,s.g,s.b)}(f,t),f.draw(s,l.TRIANGLES,r.id,a.layoutVertexBuffer,a.indexBuffer,a.segments,h)}function Mr(e,r,n){var i=e.context,a=i.gl,o=r.fbo;if(o){var s=e.useProgram("hillshade"),l=e.transform.calculatePosMatrix(r.tileID.toUnwrapped(),!0);!function(t,e,r){var n=r.paint.get("hillshade-illumination-direction")*(Math.PI/180);"viewport"===r.paint.get("hillshade-illumination-anchor")&&(n-=e.transform.angle),e.context.gl.uniform2f(t.uniforms.u_light,r.paint.get("hillshade-exaggeration"),n)}(s,e,n);var c=function(e,r){var n=r.toCoordinate(),i=new t.default$17(n.column,n.row+1,n.zoom);return[e.transform.coordinateLocation(n).lat,e.transform.coordinateLocation(i).lat]}(e,r.tileID);i.activeTexture.set(a.TEXTURE0),a.bindTexture(a.TEXTURE_2D,o.colorAttachment.get()),a.uniformMatrix4fv(s.uniforms.u_matrix,!1,l),a.uniform2fv(s.uniforms.u_latrange,c),a.uniform1i(s.uniforms.u_image,0);var u=n.paint.get("hillshade-shadow-color");a.uniform4f(s.uniforms.u_shadow,u.r,u.g,u.b,u.a);var h=n.paint.get("hillshade-highlight-color");a.uniform4f(s.uniforms.u_highlight,h.r,h.g,h.b,h.a);var f=n.paint.get("hillshade-accent-color");if(a.uniform4f(s.uniforms.u_accent,f.r,f.g,f.b,f.a),r.maskedBoundsBuffer&&r.maskedIndexBuffer&&r.segments)s.draw(i,a.TRIANGLES,n.id,r.maskedBoundsBuffer,r.maskedIndexBuffer,r.segments);else{var p=e.rasterBoundsBuffer;e.rasterBoundsVAO.bind(i,s,p,[]),a.drawArrays(a.TRIANGLE_STRIP,0,p.length)}}}function Tr(e,r,n){var i=e.context,a=i.gl;if(r.dem&&r.dem.level){var o=r.dem.level.dim,s=r.dem.getPixels();if(i.activeTexture.set(a.TEXTURE1),i.pixelStoreUnpackPremultiplyAlpha.set(!1),r.demTexture=r.demTexture||e.getTileTexture(r.tileSize),r.demTexture){var l=r.demTexture;l.update(s,{premultiply:!1}),l.bind(a.NEAREST,a.CLAMP_TO_EDGE)}else r.demTexture=new z(i,s,a.RGBA,{premultiply:!1}),r.demTexture.bind(a.NEAREST,a.CLAMP_TO_EDGE);i.activeTexture.set(a.TEXTURE0);var c=r.fbo;if(!c){var u=new z(i,{width:o,height:o,data:null},a.RGBA);u.bind(a.LINEAR,a.CLAMP_TO_EDGE),(c=r.fbo=i.createFramebuffer(o,o)).colorAttachment.set(u.texture)}i.bindFramebuffer.set(c.framebuffer),i.viewport.set([0,0,o,o]);var h=t.mat4.create();t.mat4.ortho(h,0,t.default$8,-t.default$8,0,0,1),t.mat4.translate(h,h,[0,-t.default$8,0]);var f=e.useProgram("hillshadePrepare");a.uniformMatrix4fv(f.uniforms.u_matrix,!1,h),a.uniform1f(f.uniforms.u_zoom,r.tileID.overscaledZ),a.uniform2fv(f.uniforms.u_dimension,[2*o,2*o]),a.uniform1i(f.uniforms.u_image,1),a.uniform1f(f.uniforms.u_maxzoom,n);var p=e.rasterBoundsBuffer;e.rasterBoundsVAO.bind(i,f,p,[]),a.drawArrays(a.TRIANGLE_STRIP,0,p.length),r.needsHillshadePrepare=!1}}function Sr(e,r,n,i,o){var s=i.paint.get("raster-fade-duration");if(s>0){var l=a.now(),c=(l-e.timeAdded)/s,u=r?(l-r.timeAdded)/s:-1,h=n.getSource(),f=o.coveringZoomLevel({tileSize:h.tileSize,roundZoom:h.roundZoom}),p=!r||Math.abs(r.tileID.overscaledZ-f)>Math.abs(e.tileID.overscaledZ-f),d=p&&e.refreshedUponExpiration?1:t.clamp(p?c:1-u,0,1);return e.refreshedUponExpiration&&c>=1&&(e.refreshedUponExpiration=!1),r?{opacity:1,mix:1-d}:{opacity:d,mix:0}}return{opacity:1,mix:0}}function Er(e,r,n){var i=e.context,o=i.gl;i.lineWidth.set(1*a.devicePixelRatio);var s=n.posMatrix,l=e.useProgram("debug");i.setDepthMode(qt.disabled),i.setStencilMode(Ht.disabled),i.setColorMode(e.colorModeForRenderPass()),o.uniformMatrix4fv(l.uniforms.u_matrix,!1,s),o.uniform4f(l.uniforms.u_color,1,0,0,1),e.debugVAO.bind(i,l,e.debugBuffer,[]),o.drawArrays(o.LINE_STRIP,0,e.debugBuffer.length);for(var c=function(t,e,r,n){n=n||1;var i,a,o,s,l,c,u,h,f=[];for(i=0,a=t.length;i<a;i++)if(l=Cr[t[i]]){for(h=null,o=0,s=l[1].length;o<s;o+=2)-1===l[1][o]&&-1===l[1][o+1]?h=null:(c=e+l[1][o]*n,u=200-l[1][o+1]*n,h&&f.push(h.x,h.y,c,u),h={x:c,y:u});e+=l[0]*n}return f}(n.toString(),50,0,5),u=new t.PosArray,h=0;h<c.length;h+=2)u.emplaceBack(c[h],c[h+1]);var f=i.createVertexBuffer(u,Ke.members);(new Q).bind(i,l,f,[]),o.uniform4f(l.uniforms.u_color,1,1,1,1);for(var p=r.getTile(n).tileSize,d=t.default$8/(Math.pow(2,e.transform.zoom-n.overscaledZ)*p),g=[[-1,-1],[-1,1],[1,-1],[1,1]],v=0;v<g.length;v++){var m=g[v];o.uniformMatrix4fv(l.uniforms.u_matrix,!1,t.mat4.translate([],s,[d*m[0],d*m[1],0])),o.drawArrays(o.LINES,0,f.length)}o.uniform4f(l.uniforms.u_color,0,0,0,1),o.uniformMatrix4fv(l.uniforms.u_matrix,!1,s),o.drawArrays(o.LINES,0,f.length)}var Cr={" ":[16,[]],"!":[10,[5,21,5,7,-1,-1,5,2,4,1,5,0,6,1,5,2]],'"':[16,[4,21,4,14,-1,-1,12,21,12,14]],"#":[21,[11,25,4,-7,-1,-1,17,25,10,-7,-1,-1,4,12,18,12,-1,-1,3,6,17,6]],$:[20,[8,25,8,-4,-1,-1,12,25,12,-4,-1,-1,17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3]],"%":[24,[21,21,3,0,-1,-1,8,21,10,19,10,17,9,15,7,14,5,14,3,16,3,18,4,20,6,21,8,21,10,20,13,19,16,19,19,20,21,21,-1,-1,17,7,15,6,14,4,14,2,16,0,18,0,20,1,21,3,21,5,19,7,17,7]],"&":[26,[23,12,23,13,22,14,21,14,20,13,19,11,17,6,15,3,13,1,11,0,7,0,5,1,4,2,3,4,3,6,4,8,5,9,12,13,13,14,14,16,14,18,13,20,11,21,9,20,8,18,8,16,9,13,11,10,16,3,18,1,20,0,22,0,23,1,23,2]],"'":[10,[5,19,4,20,5,21,6,20,6,18,5,16,4,15]],"(":[14,[11,25,9,23,7,20,5,16,4,11,4,7,5,2,7,-2,9,-5,11,-7]],")":[14,[3,25,5,23,7,20,9,16,10,11,10,7,9,2,7,-2,5,-5,3,-7]],"*":[16,[8,21,8,9,-1,-1,3,18,13,12,-1,-1,13,18,3,12]],"+":[26,[13,18,13,0,-1,-1,4,9,22,9]],",":[10,[6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4]],"-":[26,[4,9,22,9]],".":[10,[5,2,4,1,5,0,6,1,5,2]],"/":[22,[20,25,2,-7]],0:[20,[9,21,6,20,4,17,3,12,3,9,4,4,6,1,9,0,11,0,14,1,16,4,17,9,17,12,16,17,14,20,11,21,9,21]],1:[20,[6,17,8,18,11,21,11,0]],2:[20,[4,16,4,17,5,19,6,20,8,21,12,21,14,20,15,19,16,17,16,15,15,13,13,10,3,0,17,0]],3:[20,[5,21,16,21,10,13,13,13,15,12,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4]],4:[20,[13,21,3,7,18,7,-1,-1,13,21,13,0]],5:[20,[15,21,5,21,4,12,5,13,8,14,11,14,14,13,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4]],6:[20,[16,18,15,20,12,21,10,21,7,20,5,17,4,12,4,7,5,3,7,1,10,0,11,0,14,1,16,3,17,6,17,7,16,10,14,12,11,13,10,13,7,12,5,10,4,7]],7:[20,[17,21,7,0,-1,-1,3,21,17,21]],8:[20,[8,21,5,20,4,18,4,16,5,14,7,13,11,12,14,11,16,9,17,7,17,4,16,2,15,1,12,0,8,0,5,1,4,2,3,4,3,7,4,9,6,11,9,12,13,13,15,14,16,16,16,18,15,20,12,21,8,21]],9:[20,[16,14,15,11,13,9,10,8,9,8,6,9,4,11,3,14,3,15,4,18,6,20,9,21,10,21,13,20,15,18,16,14,16,9,15,4,13,1,10,0,8,0,5,1,4,3]],":":[10,[5,14,4,13,5,12,6,13,5,14,-1,-1,5,2,4,1,5,0,6,1,5,2]],";":[10,[5,14,4,13,5,12,6,13,5,14,-1,-1,6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4]],"<":[24,[20,18,4,9,20,0]],"=":[26,[4,12,22,12,-1,-1,4,6,22,6]],">":[24,[4,18,20,9,4,0]],"?":[18,[3,16,3,17,4,19,5,20,7,21,11,21,13,20,14,19,15,17,15,15,14,13,13,12,9,10,9,7,-1,-1,9,2,8,1,9,0,10,1,9,2]],"@":[27,[18,13,17,15,15,16,12,16,10,15,9,14,8,11,8,8,9,6,11,5,14,5,16,6,17,8,-1,-1,12,16,10,14,9,11,9,8,10,6,11,5,-1,-1,18,16,17,8,17,6,19,5,21,5,23,7,24,10,24,12,23,15,22,17,20,19,18,20,15,21,12,21,9,20,7,19,5,17,4,15,3,12,3,9,4,6,5,4,7,2,9,1,12,0,15,0,18,1,20,2,21,3,-1,-1,19,16,18,8,18,6,19,5]],A:[18,[9,21,1,0,-1,-1,9,21,17,0,-1,-1,4,7,14,7]],B:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,-1,-1,4,11,13,11,16,10,17,9,18,7,18,4,17,2,16,1,13,0,4,0]],C:[21,[18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5]],D:[21,[4,21,4,0,-1,-1,4,21,11,21,14,20,16,18,17,16,18,13,18,8,17,5,16,3,14,1,11,0,4,0]],E:[19,[4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11,-1,-1,4,0,17,0]],F:[18,[4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11]],G:[21,[18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,18,8,-1,-1,13,8,18,8]],H:[22,[4,21,4,0,-1,-1,18,21,18,0,-1,-1,4,11,18,11]],I:[8,[4,21,4,0]],J:[16,[12,21,12,5,11,2,10,1,8,0,6,0,4,1,3,2,2,5,2,7]],K:[21,[4,21,4,0,-1,-1,18,21,4,7,-1,-1,9,12,18,0]],L:[17,[4,21,4,0,-1,-1,4,0,16,0]],M:[24,[4,21,4,0,-1,-1,4,21,12,0,-1,-1,20,21,12,0,-1,-1,20,21,20,0]],N:[22,[4,21,4,0,-1,-1,4,21,18,0,-1,-1,18,21,18,0]],O:[22,[9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21]],P:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,14,17,12,16,11,13,10,4,10]],Q:[22,[9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,-1,-1,12,4,18,-2]],R:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,4,11,-1,-1,11,11,18,0]],S:[20,[17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3]],T:[16,[8,21,8,0,-1,-1,1,21,15,21]],U:[22,[4,21,4,6,5,3,7,1,10,0,12,0,15,1,17,3,18,6,18,21]],V:[18,[1,21,9,0,-1,-1,17,21,9,0]],W:[24,[2,21,7,0,-1,-1,12,21,7,0,-1,-1,12,21,17,0,-1,-1,22,21,17,0]],X:[20,[3,21,17,0,-1,-1,17,21,3,0]],Y:[18,[1,21,9,11,9,0,-1,-1,17,21,9,11]],Z:[20,[17,21,3,0,-1,-1,3,21,17,21,-1,-1,3,0,17,0]],"[":[14,[4,25,4,-7,-1,-1,5,25,5,-7,-1,-1,4,25,11,25,-1,-1,4,-7,11,-7]],"\\":[14,[0,21,14,-3]],"]":[14,[9,25,9,-7,-1,-1,10,25,10,-7,-1,-1,3,25,10,25,-1,-1,3,-7,10,-7]],"^":[16,[6,15,8,18,10,15,-1,-1,3,12,8,17,13,12,-1,-1,8,17,8,0]],_:[16,[0,-2,16,-2]],"`":[10,[6,21,5,20,4,18,4,16,5,15,6,16,5,17]],a:[19,[15,14,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],b:[19,[4,21,4,0,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3]],c:[18,[15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],d:[19,[15,21,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],e:[18,[3,8,15,8,15,10,14,12,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],f:[12,[10,21,8,21,6,20,5,17,5,0,-1,-1,2,14,9,14]],g:[19,[15,14,15,-2,14,-5,13,-6,11,-7,8,-7,6,-6,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],h:[19,[4,21,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0]],i:[8,[3,21,4,20,5,21,4,22,3,21,-1,-1,4,14,4,0]],j:[10,[5,21,6,20,7,21,6,22,5,21,-1,-1,6,14,6,-3,5,-6,3,-7,1,-7]],k:[17,[4,21,4,0,-1,-1,14,14,4,4,-1,-1,8,8,15,0]],l:[8,[4,21,4,0]],m:[30,[4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,15,10,18,13,20,14,23,14,25,13,26,10,26,0]],n:[19,[4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0]],o:[19,[8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,16,6,16,8,15,11,13,13,11,14,8,14]],p:[19,[4,14,4,-7,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3]],q:[19,[15,14,15,-7,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],r:[13,[4,14,4,0,-1,-1,4,8,5,11,7,13,9,14,12,14]],s:[17,[14,11,13,13,10,14,7,14,4,13,3,11,4,9,6,8,11,7,13,6,14,4,14,3,13,1,10,0,7,0,4,1,3,3]],t:[12,[5,21,5,4,6,1,8,0,10,0,-1,-1,2,14,9,14]],u:[19,[4,14,4,4,5,1,7,0,10,0,12,1,15,4,-1,-1,15,14,15,0]],v:[16,[2,14,8,0,-1,-1,14,14,8,0]],w:[22,[3,14,7,0,-1,-1,11,14,7,0,-1,-1,11,14,15,0,-1,-1,19,14,15,0]],x:[17,[3,14,14,0,-1,-1,14,14,3,0]],y:[16,[2,14,8,0,-1,-1,14,14,8,0,6,-4,4,-6,2,-7,1,-7]],z:[17,[14,14,3,0,-1,-1,3,14,14,14,-1,-1,3,0,14,0]],"{":[14,[9,25,7,24,6,23,5,21,5,19,6,17,7,16,8,14,8,12,6,10,-1,-1,7,24,6,22,6,20,7,18,8,17,9,15,9,13,8,11,4,9,8,7,9,5,9,3,8,1,7,0,6,-2,6,-4,7,-6,-1,-1,6,8,8,6,8,4,7,2,6,1,5,-1,5,-3,6,-5,7,-6,9,-7]],"|":[8,[4,25,4,-7]],"}":[14,[5,25,7,24,8,23,9,21,9,19,8,17,7,16,6,14,6,12,8,10,-1,-1,7,24,8,22,8,20,7,18,6,17,5,15,5,13,6,11,10,9,6,7,5,5,5,3,6,1,7,0,8,-2,8,-4,7,-6,-1,-1,8,8,6,6,6,4,7,2,8,1,9,-1,9,-3,8,-5,7,-6,5,-7]],"~":[24,[3,6,3,8,4,11,6,12,8,12,10,11,14,8,16,7,18,7,20,8,21,10,-1,-1,3,8,4,10,6,11,8,11,10,10,14,7,16,6,18,6,20,7,21,10,21,12]]},Lr={symbol:function(t,e,r,n){if("translucent"===t.renderPass){var i=t.context;i.setStencilMode(Ht.disabled),i.setColorMode(t.colorModeForRenderPass()),0!==r.paint.get("icon-opacity").constantOr(1)&&cr(t,e,r,n,!1,r.paint.get("icon-translate"),r.paint.get("icon-translate-anchor"),r.layout.get("icon-rotation-alignment"),r.layout.get("icon-pitch-alignment"),r.layout.get("icon-keep-upright")),0!==r.paint.get("text-opacity").constantOr(1)&&cr(t,e,r,n,!0,r.paint.get("text-translate"),r.paint.get("text-translate-anchor"),r.layout.get("text-rotation-alignment"),r.layout.get("text-pitch-alignment"),r.layout.get("text-keep-upright")),e.map.showCollisionBoxes&&function(t,e,r,n){or(t,e,r,n,!1),or(t,e,r,n,!0)}(t,e,r,n)}},circle:function(t,e,r,n){if("translucent"===t.renderPass){var i=r.paint.get("circle-opacity"),a=r.paint.get("circle-stroke-width"),o=r.paint.get("circle-stroke-opacity");if(0!==i.constantOr(1)||0!==a.constantOr(1)&&0!==o.constantOr(1)){var s=t.context,l=s.gl;s.setDepthMode(t.depthModeForSublayer(0,qt.ReadOnly)),s.setStencilMode(Ht.disabled),s.setColorMode(t.colorModeForRenderPass());for(var c=!0,u=0;u<n.length;u++){var h=n[u],f=e.getTile(h),p=f.getBucket(r);if(p){var d=t.context.program.get(),g=p.programConfigurations.get(r.id),v=t.useProgram("circle",g);if((c||v.program!==d)&&(g.setUniforms(s,v,r.paint,{zoom:t.transform.zoom}),c=!1),l.uniform1f(v.uniforms.u_camera_to_center_distance,t.transform.cameraToCenterDistance),l.uniform1i(v.uniforms.u_scale_with_map,"map"===r.paint.get("circle-pitch-scale")?1:0),"map"===r.paint.get("circle-pitch-alignment")){l.uniform1i(v.uniforms.u_pitch_with_map,1);var m=Te(f,1,t.transform.zoom);l.uniform2f(v.uniforms.u_extrude_scale,m,m)}else l.uniform1i(v.uniforms.u_pitch_with_map,0),l.uniform2fv(v.uniforms.u_extrude_scale,t.transform.pixelsToGLUnits);l.uniformMatrix4fv(v.uniforms.u_matrix,!1,t.translatePosMatrix(h.posMatrix,f,r.paint.get("circle-translate"),r.paint.get("circle-translate-anchor"))),v.draw(s,l.TRIANGLES,r.id,p.layoutVertexBuffer,p.indexBuffer,p.segments,g)}}}}},heatmap:function(e,r,n,i){if(0!==n.paint.get("heatmap-opacity"))if("offscreen"===e.renderPass){var a=e.context,o=a.gl;a.setDepthMode(e.depthModeForSublayer(0,qt.ReadOnly)),a.setStencilMode(Ht.disabled),function(t,e,r){var n=t.gl;t.activeTexture.set(n.TEXTURE1),t.viewport.set([0,0,e.width/4,e.height/4]);var i=r.heatmapFbo;if(i)n.bindTexture(n.TEXTURE_2D,i.colorAttachment.get()),t.bindFramebuffer.set(i.framebuffer);else{var a=n.createTexture();n.bindTexture(n.TEXTURE_2D,a),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),i=r.heatmapFbo=t.createFramebuffer(e.width/4,e.height/4),function t(e,r,n,i){var a=e.gl;a.texImage2D(a.TEXTURE_2D,0,a.RGBA,r.width/4,r.height/4,0,a.RGBA,e.extTextureHalfFloat?e.extTextureHalfFloat.HALF_FLOAT_OES:a.UNSIGNED_BYTE,null),i.colorAttachment.set(n),e.extTextureHalfFloat&&a.checkFramebufferStatus(a.FRAMEBUFFER)!==a.FRAMEBUFFER_COMPLETE&&(e.extTextureHalfFloat=null,i.colorAttachment.setDirty(),t(e,r,n,i))}(t,e,a,i)}}(a,e,n),a.clear({color:t.default$6.transparent}),a.setColorMode(new Gt([o.ONE,o.ONE],t.default$6.transparent,[!0,!0,!0,!0]));for(var s=!0,l=0;l<i.length;l++){var c=i[l];if(!r.hasRenderableParent(c)){var u=r.getTile(c),h=u.getBucket(n);if(h){var f=e.context.program.get(),p=h.programConfigurations.get(n.id),d=e.useProgram("heatmap",p),g=e.transform.zoom;(s||d.program!==f)&&(p.setUniforms(e.context,d,n.paint,{zoom:g}),s=!1),o.uniform1f(d.uniforms.u_extrude_scale,Te(u,1,g)),o.uniform1f(d.uniforms.u_intensity,n.paint.get("heatmap-intensity")),o.uniformMatrix4fv(d.uniforms.u_matrix,!1,c.posMatrix),d.draw(a,o.TRIANGLES,n.id,h.layoutVertexBuffer,h.indexBuffer,h.segments,p)}}}a.viewport.set([0,0,e.width,e.height])}else"translucent"===e.renderPass&&(e.context.setColorMode(e.colorModeForRenderPass()),function(e,r){var n=e.context,i=n.gl,a=r.heatmapFbo;if(a){n.activeTexture.set(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,a.colorAttachment.get()),n.activeTexture.set(i.TEXTURE1);var o=r.colorRampTexture;o||(o=r.colorRampTexture=new z(n,r.colorRamp,i.RGBA)),o.bind(i.LINEAR,i.CLAMP_TO_EDGE),n.setDepthMode(qt.disabled);var s=e.useProgram("heatmapTexture"),l=r.paint.get("heatmap-opacity");i.uniform1f(s.uniforms.u_opacity,l),i.uniform1i(s.uniforms.u_image,0),i.uniform1i(s.uniforms.u_color_ramp,1);var c=t.mat4.create();t.mat4.ortho(c,0,e.width,e.height,0,0,1),i.uniformMatrix4fv(s.uniforms.u_matrix,!1,c),i.uniform2f(s.uniforms.u_world,i.drawingBufferWidth,i.drawingBufferHeight),e.viewportVAO.bind(e.context,s,e.viewportBuffer,[]),i.drawArrays(i.TRIANGLE_STRIP,0,4)}}(e,n))},line:function(t,e,r,n){if("translucent"===t.renderPass&&0!==r.paint.get("line-opacity").constantOr(1)){var i=t.context;i.setDepthMode(t.depthModeForSublayer(0,qt.ReadOnly)),i.setColorMode(t.colorModeForRenderPass());for(var a,o=r.paint.get("line-dasharray")?"lineSDF":r.paint.get("line-pattern")?"linePattern":r.paint.get("line-gradient")?"lineGradient":"line",s=!0,l=0,c=n;l<c.length;l+=1){var u=c[l],h=e.getTile(u),f=h.getBucket(r);if(f){var p=f.programConfigurations.get(r.id),d=t.context.program.get(),g=t.useProgram(o,p),v=s||g.program!==d,m=a!==h.tileID.overscaledZ;v&&p.setUniforms(t.context,g,r.paint,{zoom:t.transform.zoom}),pr(g,t,h,f,r,u,p,v,m),a=h.tileID.overscaledZ,s=!1}}}},fill:function(e,r,n,i){var a=n.paint.get("fill-color"),o=n.paint.get("fill-opacity");if(0!==o.constantOr(1)){var s=e.context;s.setColorMode(e.colorModeForRenderPass());var l=n.paint.get("fill-pattern")||1!==a.constantOr(t.default$6.transparent).a||1!==o.constantOr(0)?"translucent":"opaque";e.renderPass===l&&(s.setDepthMode(e.depthModeForSublayer(1,"opaque"===e.renderPass?qt.ReadWrite:qt.ReadOnly)),mr(e,r,n,i,yr)),"translucent"===e.renderPass&&n.paint.get("fill-antialias")&&(s.lineWidth.set(2),s.setDepthMode(e.depthModeForSublayer(n.getPaintProperty("fill-outline-color")?2:0,qt.ReadOnly)),mr(e,r,n,i,xr))}},"fill-extrusion":function(e,r,n,i){if(0!==n.paint.get("fill-extrusion-opacity"))if("offscreen"===e.renderPass){!function(e,r){var n=e.context,i=n.gl,a=r.viewportFrame;if(e.depthRboNeedsClear&&e.setupOffscreenDepthRenderbuffer(),!a){var o=new z(n,{width:e.width,height:e.height,data:null},i.RGBA);o.bind(i.LINEAR,i.CLAMP_TO_EDGE),(a=r.viewportFrame=n.createFramebuffer(e.width,e.height)).colorAttachment.set(o.texture)}n.bindFramebuffer.set(a.framebuffer),a.depthAttachment.set(e.depthRbo),e.depthRboNeedsClear&&(n.clear({depth:1}),e.depthRboNeedsClear=!1),n.clear({color:t.default$6.transparent}),n.setStencilMode(Ht.disabled),n.setDepthMode(new qt(i.LEQUAL,qt.ReadWrite,[0,1])),n.setColorMode(e.colorModeForRenderPass())}(e,n);for(var a=!0,o=0,s=i;o<s.length;o+=1){var l=s[o],c=r.getTile(l),u=c.getBucket(n);u&&(Ar(e,0,n,c,l,u,a),a=!1)}}else"translucent"===e.renderPass&&function(t,e){var r=e.viewportFrame;if(r){var n=t.context,i=n.gl,a=t.useProgram("extrusionTexture");n.setStencilMode(Ht.disabled),n.setDepthMode(qt.disabled),n.setColorMode(t.colorModeForRenderPass()),n.activeTexture.set(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,r.colorAttachment.get()),i.uniform1f(a.uniforms.u_opacity,e.paint.get("fill-extrusion-opacity")),i.uniform1i(a.uniforms.u_image,0);var o=wr.create();wr.ortho(o,0,t.width,t.height,0,0,1),i.uniformMatrix4fv(a.uniforms.u_matrix,!1,o),i.uniform2f(a.uniforms.u_world,i.drawingBufferWidth,i.drawingBufferHeight),t.viewportVAO.bind(n,a,t.viewportBuffer,[]),i.drawArrays(i.TRIANGLE_STRIP,0,4)}}(e,n)},hillshade:function(t,e,r,n){if("offscreen"===t.renderPass||"translucent"===t.renderPass){var i=t.context,a=e.getSource().maxzoom;i.setDepthMode(t.depthModeForSublayer(0,qt.ReadOnly)),i.setStencilMode(Ht.disabled),i.setColorMode(t.colorModeForRenderPass());for(var o=0,s=n;o<s.length;o+=1){var l=s[o],c=e.getTile(l);c.needsHillshadePrepare&&"offscreen"===t.renderPass?Tr(t,c,a):"translucent"===t.renderPass&&Mr(t,c,r)}i.viewport.set([0,0,t.width,t.height])}},raster:function(t,e,r,n){if("translucent"===t.renderPass&&0!==r.paint.get("raster-opacity")){var i,a,o=t.context,s=o.gl,l=e.getSource(),c=t.useProgram("raster");o.setStencilMode(Ht.disabled),o.setColorMode(t.colorModeForRenderPass()),s.uniform1f(c.uniforms.u_brightness_low,r.paint.get("raster-brightness-min")),s.uniform1f(c.uniforms.u_brightness_high,r.paint.get("raster-brightness-max")),s.uniform1f(c.uniforms.u_saturation_factor,(i=r.paint.get("raster-saturation"))>0?1-1/(1.001-i):-i),s.uniform1f(c.uniforms.u_contrast_factor,(a=r.paint.get("raster-contrast"))>0?1/(1-a):1+a),s.uniform3fv(c.uniforms.u_spin_weights,function(t){t*=Math.PI/180;var e=Math.sin(t),r=Math.cos(t);return[(2*r+1)/3,(-Math.sqrt(3)*e-r+1)/3,(Math.sqrt(3)*e-r+1)/3]}(r.paint.get("raster-hue-rotate"))),s.uniform1f(c.uniforms.u_buffer_scale,1),s.uniform1i(c.uniforms.u_image0,0),s.uniform1i(c.uniforms.u_image1,1);for(var u=n.length&&n[0].overscaledZ,h=0,f=n;h<f.length;h+=1){var p=f[h];o.setDepthMode(t.depthModeForSublayer(p.overscaledZ-u,1===r.paint.get("raster-opacity")?qt.ReadWrite:qt.ReadOnly,s.LESS));var d=e.getTile(p),g=t.transform.calculatePosMatrix(p.toUnwrapped(),!0);d.registerFadeDuration(r.paint.get("raster-fade-duration")),s.uniformMatrix4fv(c.uniforms.u_matrix,!1,g);var v=e.findLoadedParent(p,0,{}),m=Sr(d,v,e,r,t.transform),y=void 0,x=void 0;if(o.activeTexture.set(s.TEXTURE0),d.texture.bind(s.LINEAR,s.CLAMP_TO_EDGE,s.LINEAR_MIPMAP_NEAREST),o.activeTexture.set(s.TEXTURE1),v?(v.texture.bind(s.LINEAR,s.CLAMP_TO_EDGE,s.LINEAR_MIPMAP_NEAREST),y=Math.pow(2,v.tileID.overscaledZ-d.tileID.overscaledZ),x=[d.tileID.canonical.x*y%1,d.tileID.canonical.y*y%1]):d.texture.bind(s.LINEAR,s.CLAMP_TO_EDGE,s.LINEAR_MIPMAP_NEAREST),s.uniform2fv(c.uniforms.u_tl_parent,x||[0,0]),s.uniform1f(c.uniforms.u_scale_parent,y||1),s.uniform1f(c.uniforms.u_fade_t,m.mix),s.uniform1f(c.uniforms.u_opacity,m.opacity*r.paint.get("raster-opacity")),l instanceof tt){var b=l.boundsBuffer;l.boundsVAO.bind(o,c,b,[]),s.drawArrays(s.TRIANGLE_STRIP,0,b.length)}else if(d.maskedBoundsBuffer&&d.maskedIndexBuffer&&d.segments)c.draw(o,s.TRIANGLES,r.id,d.maskedBoundsBuffer,d.maskedIndexBuffer,d.segments);else{var _=t.rasterBoundsBuffer;t.rasterBoundsVAO.bind(o,c,_,[]),s.drawArrays(s.TRIANGLE_STRIP,0,_.length)}}}},background:function(t,e,r){var n=r.paint.get("background-color"),i=r.paint.get("background-opacity");if(0!==i){var a=t.context,o=a.gl,s=t.transform,l=s.tileSize,c=r.paint.get("background-pattern"),u=c||1!==n.a||1!==i?"translucent":"opaque";if(t.renderPass===u){var h;if(a.setStencilMode(Ht.disabled),a.setDepthMode(t.depthModeForSublayer(0,"opaque"===u?qt.ReadWrite:qt.ReadOnly)),a.setColorMode(t.colorModeForRenderPass()),c){if(dr(c,t))return;h=t.useProgram("backgroundPattern"),gr(c,t,h),t.tileExtentPatternVAO.bind(a,h,t.tileExtentBuffer,[])}else h=t.useProgram("background"),o.uniform4fv(h.uniforms.u_color,[n.r,n.g,n.b,n.a]),t.tileExtentVAO.bind(a,h,t.tileExtentBuffer,[]);o.uniform1f(h.uniforms.u_opacity,i);for(var f=0,p=s.coveringTiles({tileSize:l});f<p.length;f+=1){var d=p[f];c&&vr({tileID:d,tileSize:l},t,h),o.uniformMatrix4fv(h.uniforms.u_matrix,!1,t.transform.calculatePosMatrix(d.toUnwrapped())),o.drawArrays(o.TRIANGLE_STRIP,0,t.tileExtentBuffer.length)}}}},debug:function(t,e,r){for(var n=0;n<r.length;n++)Er(t,e,r[n])}},zr=function(e,r){this.context=new Yt(e),this.transform=r,this._tileTextures={},this.setup(),this.numSublayers=Wt.maxUnderzooming+Wt.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.depthRboNeedsClear=!0,this.emptyProgramConfiguration=new t.default$24,this.crossTileSymbolIndex=new We};function Or(t,e){if(t.row>e.row){var r=t;t=e,e=r}return{x0:t.column,y0:t.row,x1:e.column,y1:e.row,dx:e.column-t.column,dy:e.row-t.row}}function Ir(t,e,r,n,i){var a=Math.max(r,Math.floor(e.y0)),o=Math.min(n,Math.ceil(e.y1));if(t.x0===e.x0&&t.y0===e.y0?t.x0+e.dy/t.dy*t.dx<e.x1:t.x1-e.dy/t.dy*t.dx<e.x0){var s=t;t=e,e=s}for(var l=t.dx/t.dy,c=e.dx/e.dy,u=t.dx>0,h=e.dx<0,f=a;f<o;f++){var p=l*Math.max(0,Math.min(t.dy,f+u-t.y0))+t.x0,d=c*Math.max(0,Math.min(e.dy,f+h-e.y0))+e.x0;i(Math.floor(d),Math.ceil(p),f)}}function Dr(t,e,r,n,i,a){var o,s=Or(t,e),l=Or(e,r),c=Or(r,t);s.dy>l.dy&&(o=s,s=l,l=o),s.dy>c.dy&&(o=s,s=c,c=o),l.dy>c.dy&&(o=l,l=c,c=o),s.dy&&Ir(c,s,n,i,a),l.dy&&Ir(c,l,n,i,a)}zr.prototype.resize=function(t,e){var r=this.context.gl;if(this.width=t*a.devicePixelRatio,this.height=e*a.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(var n=0,i=this.style._order;n<i.length;n+=1){var o=i[n];this.style._layers[o].resize()}this.depthRbo&&(r.deleteRenderbuffer(this.depthRbo),this.depthRbo=null)},zr.prototype.setup=function(){var e=this.context,r=new t.PosArray;r.emplaceBack(0,0),r.emplaceBack(t.default$8,0),r.emplaceBack(0,t.default$8),r.emplaceBack(t.default$8,t.default$8),this.tileExtentBuffer=e.createVertexBuffer(r,Ke.members),this.tileExtentVAO=new Q,this.tileExtentPatternVAO=new Q;var n=new t.PosArray;n.emplaceBack(0,0),n.emplaceBack(t.default$8,0),n.emplaceBack(t.default$8,t.default$8),n.emplaceBack(0,t.default$8),n.emplaceBack(0,0),this.debugBuffer=e.createVertexBuffer(n,Ke.members),this.debugVAO=new Q;var i=new t.RasterBoundsArray;i.emplaceBack(0,0,0,0),i.emplaceBack(t.default$8,0,t.default$8,0),i.emplaceBack(0,t.default$8,0,t.default$8),i.emplaceBack(t.default$8,t.default$8,t.default$8,t.default$8),this.rasterBoundsBuffer=e.createVertexBuffer(i,K.members),this.rasterBoundsVAO=new Q;var a=new t.PosArray;a.emplaceBack(0,0),a.emplaceBack(1,0),a.emplaceBack(0,1),a.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(a,Ke.members),this.viewportVAO=new Q},zr.prototype.clearStencil=function(){var e=this.context,r=e.gl;e.setColorMode(Gt.disabled),e.setDepthMode(qt.disabled),e.setStencilMode(new Ht({func:r.ALWAYS,mask:0},0,255,r.ZERO,r.ZERO,r.ZERO));var n=t.mat4.create();t.mat4.ortho(n,0,this.width,this.height,0,0,1),t.mat4.scale(n,n,[r.drawingBufferWidth,r.drawingBufferHeight,0]);var i=this.useProgram("clippingMask");r.uniformMatrix4fv(i.uniforms.u_matrix,!1,n),this.viewportVAO.bind(e,i,this.viewportBuffer,[]),r.drawArrays(r.TRIANGLE_STRIP,0,4)},zr.prototype._renderTileClippingMasks=function(t){var e=this.context,r=e.gl;e.setColorMode(Gt.disabled),e.setDepthMode(qt.disabled);var n=1;this._tileClippingMaskIDs={};for(var i=0,a=t;i<a.length;i+=1){var o=a[i],s=this._tileClippingMaskIDs[o.key]=n++;e.setStencilMode(new Ht({func:r.ALWAYS,mask:0},s,255,r.KEEP,r.KEEP,r.REPLACE));var l=this.useProgram("clippingMask");r.uniformMatrix4fv(l.uniforms.u_matrix,!1,o.posMatrix),this.tileExtentVAO.bind(this.context,l,this.tileExtentBuffer,[]),r.drawArrays(r.TRIANGLE_STRIP,0,this.tileExtentBuffer.length)}},zr.prototype.stencilModeForClipping=function(t){var e=this.context.gl;return new Ht({func:e.EQUAL,mask:255},this._tileClippingMaskIDs[t.key],0,e.KEEP,e.KEEP,e.REPLACE)},zr.prototype.colorModeForRenderPass=function(){var e=this.context.gl;return this._showOverdrawInspector?new Gt([e.CONSTANT_COLOR,e.ONE],new t.default$6(1/8,1/8,1/8,0),[!0,!0,!0,!0]):"opaque"===this.renderPass?Gt.unblended:Gt.alphaBlended},zr.prototype.depthModeForSublayer=function(t,e,r){var n=1-((1+this.currentLayer)*this.numSublayers+t)*this.depthEpsilon,i=n-1+this.depthRange;return new qt(r||this.context.gl.LEQUAL,e,[i,n])},zr.prototype.render=function(e,r){var n=this;for(var i in this.style=e,this.options=r,this.lineAtlas=e.lineAtlas,this.imageManager=e.imageManager,this.glyphManager=e.glyphManager,this.symbolFadeChange=e.placement.symbolFadeChange(a.now()),e.sourceCaches){var o=n.style.sourceCaches[i];o.used&&o.prepare(n.context)}var s=this.style._order,l=t.filterObject(this.style.sourceCaches,function(t){return"raster"===t.getSource().type||"raster-dem"===t.getSource().type}),c=function(e){var r=l[e];!function(e,r){for(var n=e.sort(function(t,e){return t.tileID.isLessThan(e.tileID)?-1:e.tileID.isLessThan(t.tileID)?1:0}),i=0;i<n.length;i++){var a={},o=n[i],s=n.slice(i+1);ar(o.tileID.wrapped(),o.tileID,s,new t.OverscaledTileID(0,o.tileID.wrap+1,0,0,0),a),o.setMask(a,r)}}(r.getVisibleCoordinates().map(function(t){return r.getTile(t)}),n.context)};for(var u in l)c(u);this.renderPass="offscreen";var h,f=[];this.depthRboNeedsClear=!0;for(var p=0;p<s.length;p++){var d=n.style._layers[s[p]];d.hasOffscreenPass()&&!d.isHidden(n.transform.zoom)&&(d.source!==(h&&h.id)&&(f=[],(h=n.style.sourceCaches[d.source])&&(f=h.getVisibleCoordinates()).reverse()),f.length&&n.renderLayer(n,h,d,f))}this.context.bindFramebuffer.set(null),this.context.clear({color:r.showOverdrawInspector?t.default$6.black:t.default$6.transparent,depth:1}),this._showOverdrawInspector=r.showOverdrawInspector,this.depthRange=(e._order.length+2)*this.numSublayers*this.depthEpsilon,this.renderPass="opaque";var g,v=[];for(this.currentLayer=s.length-1,this.currentLayer;this.currentLayer>=0;this.currentLayer--){var m=n.style._layers[s[n.currentLayer]];m.source!==(g&&g.id)&&(v=[],(g=n.style.sourceCaches[m.source])&&(n.clearStencil(),v=g.getVisibleCoordinates(),g.getSource().isTileClipped&&n._renderTileClippingMasks(v))),n.renderLayer(n,g,m,v)}this.renderPass="translucent";var y,x=[];for(this.currentLayer=0,this.currentLayer;this.currentLayer<s.length;this.currentLayer++){var b=n.style._layers[s[n.currentLayer]];b.source!==(y&&y.id)&&(x=[],(y=n.style.sourceCaches[b.source])&&(n.clearStencil(),x=y.getVisibleCoordinates(),y.getSource().isTileClipped&&n._renderTileClippingMasks(x)),x.reverse()),n.renderLayer(n,y,b,x)}if(this.options.showTileBoundaries){var _=this.style.sourceCaches[Object.keys(this.style.sourceCaches)[0]];_&&Lr.debug(this,_,_.getVisibleCoordinates())}},zr.prototype.setupOffscreenDepthRenderbuffer=function(){var t=this.context;this.depthRbo||(this.depthRbo=t.createRenderbuffer(t.gl.DEPTH_COMPONENT16,this.width,this.height))},zr.prototype.renderLayer=function(t,e,r,n){r.isHidden(this.transform.zoom)||("background"===r.type||n.length)&&(this.id=r.id,Lr[r.type](t,e,r,n))},zr.prototype.translatePosMatrix=function(e,r,n,i,a){if(!n[0]&&!n[1])return e;var o=a?"map"===i?this.transform.angle:0:"viewport"===i?-this.transform.angle:0;if(o){var s=Math.sin(o),l=Math.cos(o);n=[n[0]*l-n[1]*s,n[0]*s+n[1]*l]}var c=[a?n[0]:Te(r,n[0],this.transform.zoom),a?n[1]:Te(r,n[1],this.transform.zoom),0],u=new Float32Array(16);return t.mat4.translate(u,e,c),u},zr.prototype.saveTileTexture=function(t){var e=this._tileTextures[t.size[0]];e?e.push(t):this._tileTextures[t.size[0]]=[t]},zr.prototype.getTileTexture=function(t){var e=this._tileTextures[t];return e&&e.length>0?e.pop():null},zr.prototype._createProgramCached=function(t,e){this.cache=this.cache||{};var r=""+t+(e.cacheKey||"")+(this._showOverdrawInspector?"/overdraw":"");return this.cache[r]||(this.cache[r]=new ir(this.context,nr[t],e,this._showOverdrawInspector)),this.cache[r]},zr.prototype.useProgram=function(t,e){var r=this._createProgramCached(t,e||this.emptyProgramConfiguration);return this.context.program.set(r.program),r};var Pr=t.default$20.vec4,Rr=t.default$20.mat4,Fr=t.default$20.mat2,Br=function(t,e,r){this.tileSize=512,this._renderWorldCopies=void 0===r||r,this._minZoom=t||0,this._maxZoom=e||22,this.latRange=[-85.05113,85.05113],this.width=0,this.height=0,this._center=new G(0,0),this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._unmodified=!0,this._posMatrixCache={},this._alignedPosMatrixCache={}},Nr={minZoom:{configurable:!0},maxZoom:{configurable:!0},renderWorldCopies:{configurable:!0},worldSize:{configurable:!0},centerPoint:{configurable:!0},size:{configurable:!0},bearing:{configurable:!0},pitch:{configurable:!0},fov:{configurable:!0},zoom:{configurable:!0},center:{configurable:!0},unmodified:{configurable:!0},x:{configurable:!0},y:{configurable:!0},point:{configurable:!0}};Br.prototype.clone=function(){var t=new Br(this._minZoom,this._maxZoom,this._renderWorldCopies);return t.tileSize=this.tileSize,t.latRange=this.latRange,t.width=this.width,t.height=this.height,t._center=this._center,t.zoom=this.zoom,t.angle=this.angle,t._fov=this._fov,t._pitch=this._pitch,t._unmodified=this._unmodified,t._calcMatrices(),t},Nr.minZoom.get=function(){return this._minZoom},Nr.minZoom.set=function(t){this._minZoom!==t&&(this._minZoom=t,this.zoom=Math.max(this.zoom,t))},Nr.maxZoom.get=function(){return this._maxZoom},Nr.maxZoom.set=function(t){this._maxZoom!==t&&(this._maxZoom=t,this.zoom=Math.min(this.zoom,t))},Nr.renderWorldCopies.get=function(){return this._renderWorldCopies},Nr.renderWorldCopies.set=function(t){void 0===t?t=!0:null===t&&(t=!1),this._renderWorldCopies=t},Nr.worldSize.get=function(){return this.tileSize*this.scale},Nr.centerPoint.get=function(){return this.size._div(2)},Nr.size.get=function(){return new t.default$1(this.width,this.height)},Nr.bearing.get=function(){return-this.angle/Math.PI*180},Nr.bearing.set=function(e){var r=-t.wrap(e,-180,180)*Math.PI/180;this.angle!==r&&(this._unmodified=!1,this.angle=r,this._calcMatrices(),this.rotationMatrix=Fr.create(),Fr.rotate(this.rotationMatrix,this.rotationMatrix,this.angle))},Nr.pitch.get=function(){return this._pitch/Math.PI*180},Nr.pitch.set=function(e){var r=t.clamp(e,0,60)/180*Math.PI;this._pitch!==r&&(this._unmodified=!1,this._pitch=r,this._calcMatrices())},Nr.fov.get=function(){return this._fov/Math.PI*180},Nr.fov.set=function(t){t=Math.max(.01,Math.min(60,t)),this._fov!==t&&(this._unmodified=!1,this._fov=t/180*Math.PI,this._calcMatrices())},Nr.zoom.get=function(){return this._zoom},Nr.zoom.set=function(t){var e=Math.min(Math.max(t,this.minZoom),this.maxZoom);this._zoom!==e&&(this._unmodified=!1,this._zoom=e,this.scale=this.zoomScale(e),this.tileZoom=Math.floor(e),this.zoomFraction=e-this.tileZoom,this._constrain(),this._calcMatrices())},Nr.center.get=function(){return this._center},Nr.center.set=function(t){t.lat===this._center.lat&&t.lng===this._center.lng||(this._unmodified=!1,this._center=t,this._constrain(),this._calcMatrices())},Br.prototype.coveringZoomLevel=function(t){return(t.roundZoom?Math.round:Math.floor)(this.zoom+this.scaleZoom(this.tileSize/t.tileSize))},Br.prototype.getVisibleUnwrappedCoordinates=function(e){var r=this.pointCoordinate(new t.default$1(0,0),0),n=this.pointCoordinate(new t.default$1(this.width,0),0),i=Math.floor(r.column),a=Math.floor(n.column),o=[new t.UnwrappedTileID(0,e)];if(this._renderWorldCopies)for(var s=i;s<=a;s++)0!==s&&o.push(new t.UnwrappedTileID(s,e));return o},Br.prototype.coveringTiles=function(e){var r=this.coveringZoomLevel(e),n=r;if(void 0!==e.minzoom&&r<e.minzoom)return[];void 0!==e.maxzoom&&r>e.maxzoom&&(r=e.maxzoom);var i=this.pointCoordinate(this.centerPoint,r),a=new t.default$1(i.column-.5,i.row-.5);return function(e,r,n,i){void 0===i&&(i=!0);var a=1<<e,o={};function s(r,s,l){var c,u,h,f;if(l>=0&&l<=a)for(c=r;c<s;c++)u=Math.floor(c/a),h=(c%a+a)%a,0!==u&&!0!==i||(f=new t.OverscaledTileID(n,u,e,h,l),o[f.key]=f)}return Dr(r[0],r[1],r[2],0,a,s),Dr(r[2],r[3],r[0],0,a,s),Object.keys(o).map(function(t){return o[t]})}(r,[this.pointCoordinate(new t.default$1(0,0),r),this.pointCoordinate(new t.default$1(this.width,0),r),this.pointCoordinate(new t.default$1(this.width,this.height),r),this.pointCoordinate(new t.default$1(0,this.height),r)],e.reparseOverscaled?n:r,this._renderWorldCopies).sort(function(t,e){return a.dist(t.canonical)-a.dist(e.canonical)})},Br.prototype.resize=function(t,e){this.width=t,this.height=e,this.pixelsToGLUnits=[2/t,-2/e],this._constrain(),this._calcMatrices()},Nr.unmodified.get=function(){return this._unmodified},Br.prototype.zoomScale=function(t){return Math.pow(2,t)},Br.prototype.scaleZoom=function(t){return Math.log(t)/Math.LN2},Br.prototype.project=function(e){return new t.default$1(this.lngX(e.lng),this.latY(e.lat))},Br.prototype.unproject=function(t){return new G(this.xLng(t.x),this.yLat(t.y))},Nr.x.get=function(){return this.lngX(this.center.lng)},Nr.y.get=function(){return this.latY(this.center.lat)},Nr.point.get=function(){return new t.default$1(this.x,this.y)},Br.prototype.lngX=function(t){return(180+t)*this.worldSize/360},Br.prototype.latY=function(t){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))*this.worldSize/360},Br.prototype.xLng=function(t){return 360*t/this.worldSize-180},Br.prototype.yLat=function(t){var e=180-360*t/this.worldSize;return 360/Math.PI*Math.atan(Math.exp(e*Math.PI/180))-90},Br.prototype.setLocationAtPoint=function(t,e){var r=this.pointCoordinate(e)._sub(this.pointCoordinate(this.centerPoint));this.center=this.coordinateLocation(this.locationCoordinate(t)._sub(r)),this._renderWorldCopies&&(this.center=this.center.wrap())},Br.prototype.locationPoint=function(t){return this.coordinatePoint(this.locationCoordinate(t))},Br.prototype.pointLocation=function(t){return this.coordinateLocation(this.pointCoordinate(t))},Br.prototype.locationCoordinate=function(e){return new t.default$17(this.lngX(e.lng)/this.tileSize,this.latY(e.lat)/this.tileSize,this.zoom).zoomTo(this.tileZoom)},Br.prototype.coordinateLocation=function(t){var e=t.zoomTo(this.zoom);return new G(this.xLng(e.column*this.tileSize),this.yLat(e.row*this.tileSize))},Br.prototype.pointCoordinate=function(e,r){void 0===r&&(r=this.tileZoom);var n=[e.x,e.y,0,1],i=[e.x,e.y,1,1];Pr.transformMat4(n,n,this.pixelMatrixInverse),Pr.transformMat4(i,i,this.pixelMatrixInverse);var a=n[3],o=i[3],s=n[0]/a,l=i[0]/o,c=n[1]/a,u=i[1]/o,h=n[2]/a,f=i[2]/o,p=h===f?0:(0-h)/(f-h);return new t.default$17(t.number(s,l,p)/this.tileSize,t.number(c,u,p)/this.tileSize,this.zoom)._zoomTo(r)},Br.prototype.coordinatePoint=function(e){var r=e.zoomTo(this.zoom),n=[r.column*this.tileSize,r.row*this.tileSize,0,1];return Pr.transformMat4(n,n,this.pixelMatrix),new t.default$1(n[0]/n[3],n[1]/n[3])},Br.prototype.calculatePosMatrix=function(e,r){void 0===r&&(r=!1);var n=e.key,i=r?this._alignedPosMatrixCache:this._posMatrixCache;if(i[n])return i[n];var a=e.canonical,o=this.worldSize/this.zoomScale(a.z),s=a.x+Math.pow(2,a.z)*e.wrap,l=Rr.identity(new Float64Array(16));return Rr.translate(l,l,[s*o,a.y*o,0]),Rr.scale(l,l,[o/t.default$8,o/t.default$8,1]),Rr.multiply(l,r?this.alignedProjMatrix:this.projMatrix,l),i[n]=new Float32Array(l),i[n]},Br.prototype._constrain=function(){if(this.center&&this.width&&this.height&&!this._constraining){this._constraining=!0;var e,r,n,i,a=-90,o=90,s=-180,l=180,c=this.size,u=this._unmodified;if(this.latRange){var h=this.latRange;a=this.latY(h[1]),e=(o=this.latY(h[0]))-a<c.y?c.y/(o-a):0}if(this.lngRange){var f=this.lngRange;s=this.lngX(f[0]),r=(l=this.lngX(f[1]))-s<c.x?c.x/(l-s):0}var p=Math.max(r||0,e||0);if(p)return this.center=this.unproject(new t.default$1(r?(l+s)/2:this.x,e?(o+a)/2:this.y)),this.zoom+=this.scaleZoom(p),this._unmodified=u,void(this._constraining=!1);if(this.latRange){var d=this.y,g=c.y/2;d-g<a&&(i=a+g),d+g>o&&(i=o-g)}if(this.lngRange){var v=this.x,m=c.x/2;v-m<s&&(n=s+m),v+m>l&&(n=l-m)}void 0===n&&void 0===i||(this.center=this.unproject(new t.default$1(void 0!==n?n:this.x,void 0!==i?i:this.y))),this._unmodified=u,this._constraining=!1}},Br.prototype._calcMatrices=function(){if(this.height){this.cameraToCenterDistance=.5/Math.tan(this._fov/2)*this.height;var t=this._fov/2,e=Math.PI/2+this._pitch,r=Math.sin(t)*this.cameraToCenterDistance/Math.sin(Math.PI-e-t),n=this.x,i=this.y,a=1.01*(Math.cos(Math.PI/2-this._pitch)*r+this.cameraToCenterDistance),o=new Float64Array(16);Rr.perspective(o,this._fov,this.width/this.height,1,a),Rr.scale(o,o,[1,-1,1]),Rr.translate(o,o,[0,0,-this.cameraToCenterDistance]),Rr.rotateX(o,o,this._pitch),Rr.rotateZ(o,o,this.angle),Rr.translate(o,o,[-n,-i,0]);var s=this.worldSize/(2*Math.PI*6378137*Math.abs(Math.cos(this.center.lat*(Math.PI/180))));Rr.scale(o,o,[1,1,s,1]),this.projMatrix=o;var l=this.width%2/2,c=this.height%2/2,u=Math.cos(this.angle),h=Math.sin(this.angle),f=n-Math.round(n)+u*l+h*c,p=i-Math.round(i)+u*c+h*l,d=new Float64Array(o);if(Rr.translate(d,d,[f>.5?f-1:f,p>.5?p-1:p,0]),this.alignedProjMatrix=d,o=Rr.create(),Rr.scale(o,o,[this.width/2,-this.height/2,1]),Rr.translate(o,o,[1,-1,0]),this.pixelMatrix=Rr.multiply(new Float64Array(16),o,this.projMatrix),!(o=Rr.invert(new Float64Array(16),this.pixelMatrix)))throw new Error("failed to invert matrix");this.pixelMatrixInverse=o,this._posMatrixCache={},this._alignedPosMatrixCache={}}},Br.prototype.maxPitchScaleFactor=function(){if(!this.pixelMatrixInverse)return 1;var e=this.pointCoordinate(new t.default$1(0,0)).zoomTo(this.zoom),r=[e.column*this.tileSize,e.row*this.tileSize,0,1];return Pr.transformMat4(r,r,this.pixelMatrix)[3]/this.cameraToCenterDistance},Object.defineProperties(Br.prototype,Nr);var jr=function(){var e,r,n,i;t.bindAll(["_onHashChange","_updateHash"],this),this._updateHash=(e=this._updateHashUnthrottled.bind(this),300,r=!1,n=0,i=function(){n=0,r&&(e(),n=setTimeout(i,300),r=!1)},function(){return r=!0,n||i(),n})};jr.prototype.addTo=function(e){return this._map=e,t.default.addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this},jr.prototype.remove=function(){return t.default.removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),delete this._map,this},jr.prototype.getHashString=function(t){var e=this._map.getCenter(),r=Math.round(100*this._map.getZoom())/100,n=Math.ceil((r*Math.LN2+Math.log(512/360/.5))/Math.LN10),i=Math.pow(10,n),a=Math.round(e.lng*i)/i,o=Math.round(e.lat*i)/i,s=this._map.getBearing(),l=this._map.getPitch(),c="";return c+=t?"#/"+a+"/"+o+"/"+r:"#"+r+"/"+o+"/"+a,(s||l)&&(c+="/"+Math.round(10*s)/10),l&&(c+="/"+Math.round(l)),c},jr.prototype._onHashChange=function(){var e=t.default.location.hash.replace("#","").split("/");return e.length>=3&&(this._map.jumpTo({center:[+e[2],+e[1]],zoom:+e[0],bearing:+(e[3]||0),pitch:+(e[4]||0)}),!0)},jr.prototype._updateHashUnthrottled=function(){var e=this.getHashString();t.default.history.replaceState(t.default.history.state,"",e)};var Vr=function(e){function r(r,n,i,a){void 0===a&&(a={});var o=s.mousePos(n.getCanvasContainer(),i),l=n.unproject(o);e.call(this,r,t.extend({point:o,lngLat:l,originalEvent:i},a)),this._defaultPrevented=!1,this.target=n}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var n={defaultPrevented:{configurable:!0}};return r.prototype.preventDefault=function(){this._defaultPrevented=!0},n.defaultPrevented.get=function(){return this._defaultPrevented},Object.defineProperties(r.prototype,n),r}(t.Event),Ur=function(e){function r(r,n,i){var a=s.touchPos(n.getCanvasContainer(),i),o=a.map(function(t){return n.unproject(t)}),l=a.reduce(function(t,e,r,n){return t.add(e.div(n.length))},new t.default$1(0,0)),c=n.unproject(l);e.call(this,r,{points:a,point:l,lngLats:o,lngLat:c,originalEvent:i}),this._defaultPrevented=!1}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var n={defaultPrevented:{configurable:!0}};return r.prototype.preventDefault=function(){this._defaultPrevented=!0},n.defaultPrevented.get=function(){return this._defaultPrevented},Object.defineProperties(r.prototype,n),r}(t.Event),qr=function(t){function e(e,r,n){t.call(this,e,{originalEvent:n}),this._defaultPrevented=!1}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={defaultPrevented:{configurable:!0}};return e.prototype.preventDefault=function(){this._defaultPrevented=!0},r.defaultPrevented.get=function(){return this._defaultPrevented},Object.defineProperties(e.prototype,r),e}(t.Event),Hr=function(e){this._map=e,this._el=e.getCanvasContainer(),this._delta=0,t.bindAll(["_onWheel","_onTimeout","_onScrollFrame","_onScrollFinished"],this)};Hr.prototype.isEnabled=function(){return!!this._enabled},Hr.prototype.isActive=function(){return!!this._active},Hr.prototype.enable=function(t){this.isEnabled()||(this._enabled=!0,this._aroundCenter=t&&"center"===t.around)},Hr.prototype.disable=function(){this.isEnabled()&&(this._enabled=!1)},Hr.prototype.onWheel=function(e){if(this.isEnabled()){var r=e.deltaMode===t.default.WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY,n=a.now(),i=n-(this._lastWheelEventTime||0);this._lastWheelEventTime=n,0!==r&&r%4.000244140625==0?this._type="wheel":0!==r&&Math.abs(r)<4?this._type="trackpad":i>400?(this._type=null,this._lastValue=r,this._timeout=setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(i*r)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,r+=this._lastValue)),e.shiftKey&&r&&(r/=4),this._type&&(this._lastWheelEvent=e,this._delta-=r,this.isActive()||this._start(e)),e.preventDefault()}},Hr.prototype._onTimeout=function(t){this._type="wheel",this._delta-=this._lastValue,this.isActive()||this._start(t)},Hr.prototype._start=function(e){if(this._delta){this._frameId&&(this._map._cancelRenderFrame(this._frameId),this._frameId=null),this._active=!0,this._map.fire(new t.Event("movestart",{originalEvent:e})),this._map.fire(new t.Event("zoomstart",{originalEvent:e})),this._finishTimeout&&clearTimeout(this._finishTimeout);var r=s.mousePos(this._el,e);this._around=G.convert(this._aroundCenter?this._map.getCenter():this._map.unproject(r)),this._aroundPoint=this._map.transform.locationPoint(this._around),this._frameId||(this._frameId=this._map._requestRenderFrame(this._onScrollFrame))}},Hr.prototype._onScrollFrame=function(){var e=this;if(this._frameId=null,this.isActive()){var r=this._map.transform;if(0!==this._delta){var n="wheel"===this._type&&Math.abs(this._delta)>4.000244140625?1/450:.01,i=2/(1+Math.exp(-Math.abs(this._delta*n)));this._delta<0&&0!==i&&(i=1/i);var o="number"==typeof this._targetZoom?r.zoomScale(this._targetZoom):r.scale;this._targetZoom=Math.min(r.maxZoom,Math.max(r.minZoom,r.scaleZoom(o*i))),"wheel"===this._type&&(this._startZoom=r.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0}var s=!1;if("wheel"===this._type){var l=Math.min((a.now()-this._lastWheelEventTime)/200,1),c=this._easing(l);r.zoom=t.number(this._startZoom,this._targetZoom,c),l<1?this._frameId||(this._frameId=this._map._requestRenderFrame(this._onScrollFrame)):s=!0}else r.zoom=this._targetZoom,s=!0;r.setLocationAtPoint(this._around,this._aroundPoint),this._map.fire(new t.Event("move",{originalEvent:this._lastWheelEvent})),this._map.fire(new t.Event("zoom",{originalEvent:this._lastWheelEvent})),s&&(this._active=!1,this._finishTimeout=setTimeout(function(){e._map.fire(new t.Event("zoomend",{originalEvent:e._lastWheelEvent})),e._map.fire(new t.Event("moveend",{originalEvent:e._lastWheelEvent})),delete e._targetZoom},200))}},Hr.prototype._smoothOutEasing=function(e){var r=t.ease;if(this._prevEase){var n=this._prevEase,i=(a.now()-n.start)/n.duration,o=n.easing(i+.01)-n.easing(i),s=.27/Math.sqrt(o*o+1e-4)*.01,l=Math.sqrt(.0729-s*s);r=t.bezier(s,l,.25,1)}return this._prevEase={start:a.now(),duration:e,easing:r},r};var Gr=function(e){this._map=e,this._el=e.getCanvasContainer(),this._container=e.getContainer(),t.bindAll(["_onMouseMove","_onMouseUp","_onKeyDown"],this)};Gr.prototype.isEnabled=function(){return!!this._enabled},Gr.prototype.isActive=function(){return!!this._active},Gr.prototype.enable=function(){this.isEnabled()||(this._enabled=!0)},Gr.prototype.disable=function(){this.isEnabled()&&(this._enabled=!1)},Gr.prototype.onMouseDown=function(e){this.isEnabled()&&e.shiftKey&&0===e.button&&(t.default.document.addEventListener("mousemove",this._onMouseMove,!1),t.default.document.addEventListener("keydown",this._onKeyDown,!1),t.default.document.addEventListener("mouseup",this._onMouseUp,!1),s.disableDrag(),this._startPos=s.mousePos(this._el,e),this._active=!0)},Gr.prototype._onMouseMove=function(t){var e=this._startPos,r=s.mousePos(this._el,t);this._box||(this._box=s.create("div","mapboxgl-boxzoom",this._container),this._container.classList.add("mapboxgl-crosshair"),this._fireEvent("boxzoomstart",t));var n=Math.min(e.x,r.x),i=Math.max(e.x,r.x),a=Math.min(e.y,r.y),o=Math.max(e.y,r.y);s.setTransform(this._box,"translate("+n+"px,"+a+"px)"),this._box.style.width=i-n+"px",this._box.style.height=o-a+"px"},Gr.prototype._onMouseUp=function(e){if(0===e.button){var r=this._startPos,n=s.mousePos(this._el,e),i=(new Y).extend(this._map.unproject(r)).extend(this._map.unproject(n));this._finish(),s.suppressClick(),r.x===n.x&&r.y===n.y?this._fireEvent("boxzoomcancel",e):this._map.fitBounds(i,{linear:!0}).fire(new t.Event("boxzoomend",{originalEvent:e,boxZoomBounds:i}))}},Gr.prototype._onKeyDown=function(t){27===t.keyCode&&(this._finish(),this._fireEvent("boxzoomcancel",t))},Gr.prototype._finish=function(){this._active=!1,t.default.document.removeEventListener("mousemove",this._onMouseMove,!1),t.default.document.removeEventListener("keydown",this._onKeyDown,!1),t.default.document.removeEventListener("mouseup",this._onMouseUp,!1),this._container.classList.remove("mapboxgl-crosshair"),this._box&&(s.remove(this._box),this._box=null),s.enableDrag()},Gr.prototype._fireEvent=function(e,r){return this._map.fire(new t.Event(e,{originalEvent:r}))};var Yr=t.bezier(0,0,.25,1),Wr=function(e,r){this._map=e,this._el=r.element||e.getCanvasContainer(),this._state="disabled",this._button=r.button||"right",this._bearingSnap=r.bearingSnap||0,this._pitchWithRotate=!1!==r.pitchWithRotate,t.bindAll(["_onMouseMove","_onMouseUp","_onBlur","_onDragFrame"],this)};Wr.prototype.isEnabled=function(){return"disabled"!==this._state},Wr.prototype.isActive=function(){return"active"===this._state},Wr.prototype.enable=function(){this.isEnabled()||(this._state="enabled")},Wr.prototype.disable=function(){if(this.isEnabled())switch(this._state){case"active":this._state="disabled",this._unbind(),this._deactivate(),this._fireEvent("rotateend"),this._pitchWithRotate&&this._fireEvent("pitchend"),this._fireEvent("moveend");break;case"pending":this._state="disabled",this._unbind();break;default:this._state="disabled"}},Wr.prototype.onMouseDown=function(e){if("enabled"===this._state){if("right"===this._button){if(this._eventButton=s.mouseButton(e),this._eventButton!==(e.ctrlKey?0:2))return}else{if(e.ctrlKey||0!==s.mouseButton(e))return;this._eventButton=0}s.disableDrag(),t.default.document.addEventListener("mousemove",this._onMouseMove,{capture:!0}),t.default.document.addEventListener("mouseup",this._onMouseUp),t.default.addEventListener("blur",this._onBlur),this._state="pending",this._inertia=[[a.now(),this._map.getBearing()]],this._previousPos=s.mousePos(this._el,e),this._center=this._map.transform.centerPoint,e.preventDefault()}},Wr.prototype._onMouseMove=function(t){this._lastMoveEvent=t,this._pos=s.mousePos(this._el,t),"pending"===this._state&&(this._state="active",this._fireEvent("rotatestart",t),this._fireEvent("movestart",t),this._pitchWithRotate&&this._fireEvent("pitchstart",t)),this._frameId||(this._frameId=this._map._requestRenderFrame(this._onDragFrame))},Wr.prototype._onDragFrame=function(){this._frameId=null;var t=this._lastMoveEvent;if(t){var e=this._map.transform,r=this._previousPos,n=this._pos,i=.8*(r.x-n.x),o=-.5*(r.y-n.y),s=e.bearing-i,l=e.pitch-o,c=this._inertia,u=c[c.length-1];this._drainInertiaBuffer(),c.push([a.now(),this._map._normalizeBearing(s,u[1])]),e.bearing=s,this._pitchWithRotate&&(this._fireEvent("pitch",t),e.pitch=l),this._fireEvent("rotate",t),this._fireEvent("move",t),delete this._lastMoveEvent,this._previousPos=this._pos}},Wr.prototype._onMouseUp=function(t){if(s.mouseButton(t)===this._eventButton)switch(this._state){case"active":this._state="enabled",s.suppressClick(),this._unbind(),this._deactivate(),this._inertialRotate(t);break;case"pending":this._state="enabled",this._unbind()}},Wr.prototype._onBlur=function(t){switch(this._state){case"active":this._state="enabled",this._unbind(),this._deactivate(),this._fireEvent("rotateend",t),this._pitchWithRotate&&this._fireEvent("pitchend",t),this._fireEvent("moveend",t);break;case"pending":this._state="enabled",this._unbind()}},Wr.prototype._unbind=function(){t.default.document.removeEventListener("mousemove",this._onMouseMove,{capture:!0}),t.default.document.removeEventListener("mouseup",this._onMouseUp),t.default.removeEventListener("blur",this._onBlur),s.enableDrag()},Wr.prototype._deactivate=function(){this._frameId&&(this._map._cancelRenderFrame(this._frameId),this._frameId=null),delete this._lastMoveEvent,delete this._previousPos},Wr.prototype._inertialRotate=function(t){var e=this;this._fireEvent("rotateend",t),this._drainInertiaBuffer();var r=this._map,n=r.getBearing(),i=this._inertia,a=function(){Math.abs(n)<e._bearingSnap?r.resetNorth({noMoveStart:!0},{originalEvent:t}):e._fireEvent("moveend",t),e._pitchWithRotate&&e._fireEvent("pitchend",t)};if(i.length<2)a();else{var o=i[0],s=i[i.length-1],l=i[i.length-2],c=r._normalizeBearing(n,l[1]),u=s[1]-o[1],h=u<0?-1:1,f=(s[0]-o[0])/1e3;if(0!==u&&0!==f){var p=Math.abs(u*(.25/f));p>180&&(p=180);var d=p/180;c+=h*p*(d/2),Math.abs(r._normalizeBearing(c,0))<this._bearingSnap&&(c=r._normalizeBearing(0,c)),r.rotateTo(c,{duration:1e3*d,easing:Yr,noMoveStart:!0},{originalEvent:t})}else a()}},Wr.prototype._fireEvent=function(e,r){return this._map.fire(new t.Event(e,r?{originalEvent:r}:{}))},Wr.prototype._drainInertiaBuffer=function(){for(var t=this._inertia,e=a.now();t.length>0&&e-t[0][0]>160;)t.shift()};var Xr=t.bezier(0,0,.3,1),Zr=function(e){this._map=e,this._el=e.getCanvasContainer(),this._state="disabled",t.bindAll(["_onMove","_onMouseUp","_onTouchEnd","_onBlur","_onDragFrame"],this)};Zr.prototype.isEnabled=function(){return"disabled"!==this._state},Zr.prototype.isActive=function(){return"active"===this._state},Zr.prototype.enable=function(){this.isEnabled()||(this._el.classList.add("mapboxgl-touch-drag-pan"),this._state="enabled")},Zr.prototype.disable=function(){if(this.isEnabled())switch(this._el.classList.remove("mapboxgl-touch-drag-pan"),this._state){case"active":this._state="disabled",this._unbind(),this._deactivate(),this._fireEvent("dragend"),this._fireEvent("moveend");break;case"pending":this._state="disabled",this._unbind();break;default:this._state="disabled"}},Zr.prototype.onMouseDown=function(e){"enabled"===this._state&&(e.ctrlKey||0!==s.mouseButton(e)||(s.addEventListener(t.default.document,"mousemove",this._onMove,{capture:!0}),s.addEventListener(t.default.document,"mouseup",this._onMouseUp),this._start(e)))},Zr.prototype.onTouchStart=function(e){"enabled"===this._state&&(e.touches.length>1||(s.addEventListener(t.default.document,"touchmove",this._onMove,{capture:!0,passive:!1}),s.addEventListener(t.default.document,"touchend",this._onTouchEnd),this._start(e)))},Zr.prototype._start=function(e){t.default.addEventListener("blur",this._onBlur),this._state="pending",this._previousPos=s.mousePos(this._el,e),this._inertia=[[a.now(),this._previousPos]]},Zr.prototype._onMove=function(t){this._lastMoveEvent=t,t.preventDefault(),this._pos=s.mousePos(this._el,t),this._drainInertiaBuffer(),this._inertia.push([a.now(),this._pos]),"pending"===this._state&&(this._state="active",this._fireEvent("dragstart",t),this._fireEvent("movestart",t)),this._frameId||(this._frameId=this._map._requestRenderFrame(this._onDragFrame))},Zr.prototype._onDragFrame=function(){this._frameId=null;var t=this._lastMoveEvent;if(t){var e=this._map.transform;e.setLocationAtPoint(e.pointLocation(this._previousPos),this._pos),this._fireEvent("drag",t),this._fireEvent("move",t),this._previousPos=this._pos,delete this._lastMoveEvent}},Zr.prototype._onMouseUp=function(t){if(0===s.mouseButton(t))switch(this._state){case"active":this._state="enabled",s.suppressClick(),this._unbind(),this._deactivate(),this._inertialPan(t);break;case"pending":this._state="enabled",this._unbind()}},Zr.prototype._onTouchEnd=function(t){switch(this._state){case"active":this._state="enabled",this._unbind(),this._deactivate(),this._inertialPan(t);break;case"pending":this._state="enabled",this._unbind()}},Zr.prototype._onBlur=function(t){switch(this._state){case"active":this._state="enabled",this._unbind(),this._deactivate(),this._fireEvent("dragend",t),this._fireEvent("moveend",t);break;case"pending":this._state="enabled",this._unbind()}},Zr.prototype._unbind=function(){s.removeEventListener(t.default.document,"touchmove",this._onMove,{capture:!0,passive:!1}),s.removeEventListener(t.default.document,"touchend",this._onTouchEnd),s.removeEventListener(t.default.document,"mousemove",this._onMove,{capture:!0}),s.removeEventListener(t.default.document,"mouseup",this._onMouseUp),s.removeEventListener(t.default,"blur",this._onBlur)},Zr.prototype._deactivate=function(){this._frameId&&(this._map._cancelRenderFrame(this._frameId),this._frameId=null),delete this._lastMoveEvent,delete this._previousPos,delete this._pos},Zr.prototype._inertialPan=function(t){this._fireEvent("dragend",t),this._drainInertiaBuffer();var e=this._inertia;if(e.length<2)this._fireEvent("moveend",t);else{var r=e[e.length-1],n=e[0],i=r[1].sub(n[1]),a=(r[0]-n[0])/1e3;if(0===a||r[1].equals(n[1]))this._fireEvent("moveend",t);else{var o=i.mult(.3/a),s=o.mag();s>1400&&(s=1400,o._unit()._mult(s));var l=s/750,c=o.mult(-l/2);this._map.panBy(c,{duration:1e3*l,easing:Xr,noMoveStart:!0},{originalEvent:t})}}},Zr.prototype._fireEvent=function(e,r){return this._map.fire(new t.Event(e,r?{originalEvent:r}:{}))},Zr.prototype._drainInertiaBuffer=function(){for(var t=this._inertia,e=a.now();t.length>0&&e-t[0][0]>160;)t.shift()};var $r=function(e){this._map=e,this._el=e.getCanvasContainer(),t.bindAll(["_onKeyDown"],this)};function Jr(t){return t*(2-t)}$r.prototype.isEnabled=function(){return!!this._enabled},$r.prototype.enable=function(){this.isEnabled()||(this._el.addEventListener("keydown",this._onKeyDown,!1),this._enabled=!0)},$r.prototype.disable=function(){this.isEnabled()&&(this._el.removeEventListener("keydown",this._onKeyDown),this._enabled=!1)},$r.prototype._onKeyDown=function(t){if(!(t.altKey||t.ctrlKey||t.metaKey)){var e=0,r=0,n=0,i=0,a=0;switch(t.keyCode){case 61:case 107:case 171:case 187:e=1;break;case 189:case 109:case 173:e=-1;break;case 37:t.shiftKey?r=-1:(t.preventDefault(),i=-1);break;case 39:t.shiftKey?r=1:(t.preventDefault(),i=1);break;case 38:t.shiftKey?n=1:(t.preventDefault(),a=-1);break;case 40:t.shiftKey?n=-1:(a=1,t.preventDefault());break;default:return}var o=this._map,s=o.getZoom(),l={duration:300,delayEndEvents:500,easing:Jr,zoom:e?Math.round(s)+e*(t.shiftKey?2:1):s,bearing:o.getBearing()+15*r,pitch:o.getPitch()+10*n,offset:[100*-i,100*-a],center:o.getCenter()};o.easeTo(l,{originalEvent:t})}};var Kr=function(e){this._map=e,t.bindAll(["_onDblClick","_onZoomEnd"],this)};Kr.prototype.isEnabled=function(){return!!this._enabled},Kr.prototype.isActive=function(){return!!this._active},Kr.prototype.enable=function(){this.isEnabled()||(this._enabled=!0)},Kr.prototype.disable=function(){this.isEnabled()&&(this._enabled=!1)},Kr.prototype.onTouchStart=function(t){var e=this;this.isEnabled()&&(t.points.length>1||(this._tapped?(clearTimeout(this._tapped),this._tapped=null,this._zoom(t)):this._tapped=setTimeout(function(){e._tapped=null},300)))},Kr.prototype.onDblClick=function(t){this.isEnabled()&&(t.originalEvent.preventDefault(),this._zoom(t))},Kr.prototype._zoom=function(t){this._active=!0,this._map.on("zoomend",this._onZoomEnd),this._map.zoomTo(this._map.getZoom()+(t.originalEvent.shiftKey?-1:1),{around:t.lngLat},t)},Kr.prototype._onZoomEnd=function(){this._active=!1,this._map.off("zoomend",this._onZoomEnd)};var Qr=t.bezier(0,0,.15,1),tn=function(e){this._map=e,this._el=e.getCanvasContainer(),t.bindAll(["_onMove","_onEnd","_onTouchFrame"],this)};tn.prototype.isEnabled=function(){return!!this._enabled},tn.prototype.enable=function(t){this.isEnabled()||(this._el.classList.add("mapboxgl-touch-zoom-rotate"),this._enabled=!0,this._aroundCenter=!!t&&"center"===t.around)},tn.prototype.disable=function(){this.isEnabled()&&(this._el.classList.remove("mapboxgl-touch-zoom-rotate"),this._enabled=!1)},tn.prototype.disableRotation=function(){this._rotationDisabled=!0},tn.prototype.enableRotation=function(){this._rotationDisabled=!1},tn.prototype.onStart=function(e){if(this.isEnabled()&&2===e.touches.length){var r=s.mousePos(this._el,e.touches[0]),n=s.mousePos(this._el,e.touches[1]);this._startVec=r.sub(n),this._gestureIntent=void 0,this._inertia=[],s.addEventListener(t.default.document,"touchmove",this._onMove,{passive:!1}),s.addEventListener(t.default.document,"touchend",this._onEnd)}},tn.prototype._getTouchEventData=function(t){var e=s.mousePos(this._el,t.touches[0]),r=s.mousePos(this._el,t.touches[1]),n=e.sub(r);return{vec:n,center:e.add(r).div(2),scale:n.mag()/this._startVec.mag(),bearing:this._rotationDisabled?0:180*n.angleWith(this._startVec)/Math.PI}},tn.prototype._onMove=function(e){if(2===e.touches.length){var r=this._getTouchEventData(e),n=r.vec,i=r.scale,a=r.bearing;if(!this._gestureIntent){var o=Math.abs(1-i)>.15;Math.abs(a)>10?this._gestureIntent="rotate":o&&(this._gestureIntent="zoom"),this._gestureIntent&&(this._map.fire(new t.Event(this._gestureIntent+"start",{originalEvent:e})),this._map.fire(new t.Event("movestart",{originalEvent:e})),this._startVec=n)}this._lastTouchEvent=e,this._frameId||(this._frameId=this._map._requestRenderFrame(this._onTouchFrame)),e.preventDefault()}},tn.prototype._onTouchFrame=function(){this._frameId=null;var e=this._gestureIntent;if(e){var r=this._map.transform;this._startScale||(this._startScale=r.scale,this._startBearing=r.bearing);var n=this._getTouchEventData(this._lastTouchEvent),i=n.center,o=n.bearing,s=n.scale,l=r.pointLocation(i),c=r.locationPoint(l);"rotate"===e&&(r.bearing=this._startBearing+o),r.zoom=r.scaleZoom(this._startScale*s),r.setLocationAtPoint(l,c),this._map.fire(new t.Event(e,{originalEvent:this._lastTouchEvent})),this._map.fire(new t.Event("move",{originalEvent:this._lastTouchEvent})),this._drainInertiaBuffer(),this._inertia.push([a.now(),s,i])}},tn.prototype._onEnd=function(e){s.removeEventListener(t.default.document,"touchmove",this._onMove,{passive:!1}),s.removeEventListener(t.default.document,"touchend",this._onEnd);var r=this._gestureIntent,n=this._startScale;if(this._frameId&&(this._map._cancelRenderFrame(this._frameId),this._frameId=null),delete this._gestureIntent,delete this._startScale,delete this._startBearing,delete this._lastTouchEvent,r){this._map.fire(new t.Event(r+"end",{originalEvent:e})),this._drainInertiaBuffer();var i=this._inertia,a=this._map;if(i.length<2)a.snapToNorth({},{originalEvent:e});else{var o=i[i.length-1],l=i[0],c=a.transform.scaleZoom(n*o[1]),u=a.transform.scaleZoom(n*l[1]),h=c-u,f=(o[0]-l[0])/1e3,p=o[2];if(0!==f&&c!==u){var d=.15*h/f;Math.abs(d)>2.5&&(d=d>0?2.5:-2.5);var g=1e3*Math.abs(d/(12*.15)),v=c+d*g/2e3;v<0&&(v=0),a.easeTo({zoom:v,duration:g,easing:Qr,around:this._aroundCenter?a.getCenter():a.unproject(p),noMoveStart:!0},{originalEvent:e})}else a.snapToNorth({},{originalEvent:e})}}},tn.prototype._drainInertiaBuffer=function(){for(var t=this._inertia,e=a.now();t.length>2&&e-t[0][0]>160;)t.shift()};var en={scrollZoom:Hr,boxZoom:Gr,dragRotate:Wr,dragPan:Zr,keyboard:$r,doubleClickZoom:Kr,touchZoomRotate:tn},rn=function(e){function r(r,n){e.call(this),this._moving=!1,this._zooming=!1,this.transform=r,this._bearingSnap=n.bearingSnap,t.bindAll(["_renderFrameCallback"],this)}return e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r,r.prototype.getCenter=function(){return this.transform.center},r.prototype.setCenter=function(t,e){return this.jumpTo({center:t},e)},r.prototype.panBy=function(e,r,n){return e=t.default$1.convert(e).mult(-1),this.panTo(this.transform.center,t.extend({offset:e},r),n)},r.prototype.panTo=function(e,r,n){return this.easeTo(t.extend({center:e},r),n)},r.prototype.getZoom=function(){return this.transform.zoom},r.prototype.setZoom=function(t,e){return this.jumpTo({zoom:t},e),this},r.prototype.zoomTo=function(e,r,n){return this.easeTo(t.extend({zoom:e},r),n)},r.prototype.zoomIn=function(t,e){return this.zoomTo(this.getZoom()+1,t,e),this},r.prototype.zoomOut=function(t,e){return this.zoomTo(this.getZoom()-1,t,e),this},r.prototype.getBearing=function(){return this.transform.bearing},r.prototype.setBearing=function(t,e){return this.jumpTo({bearing:t},e),this},r.prototype.rotateTo=function(e,r,n){return this.easeTo(t.extend({bearing:e},r),n)},r.prototype.resetNorth=function(e,r){return this.rotateTo(0,t.extend({duration:1e3},e),r),this},r.prototype.snapToNorth=function(t,e){return Math.abs(this.getBearing())<this._bearingSnap?this.resetNorth(t,e):this},r.prototype.getPitch=function(){return this.transform.pitch},r.prototype.setPitch=function(t,e){return this.jumpTo({pitch:t},e),this},r.prototype.fitBounds=function(e,r,n){if("number"==typeof(r=t.extend({padding:{top:0,bottom:0,right:0,left:0},offset:[0,0],maxZoom:this.transform.maxZoom},r)).padding){var i=r.padding;r.padding={top:i,bottom:i,right:i,left:i}}if(!t.default$10(Object.keys(r.padding).sort(function(t,e){return t<e?-1:t>e?1:0}),["bottom","left","right","top"]))return t.warnOnce("options.padding must be a positive number, or an Object with keys 'bottom', 'left', 'right', 'top'"),this;e=Y.convert(e);var a=[(r.padding.left-r.padding.right)/2,(r.padding.top-r.padding.bottom)/2],o=Math.min(r.padding.right,r.padding.left),s=Math.min(r.padding.top,r.padding.bottom);r.offset=[r.offset[0]+a[0],r.offset[1]+a[1]];var l=t.default$1.convert(r.offset),c=this.transform,u=c.project(e.getNorthWest()),h=c.project(e.getSouthEast()),f=h.sub(u),p=(c.width-2*o-2*Math.abs(l.x))/f.x,d=(c.height-2*s-2*Math.abs(l.y))/f.y;return d<0||p<0?(t.warnOnce("Map cannot fit within canvas with the given bounds, padding, and/or offset."),this):(r.center=c.unproject(u.add(h).div(2)),r.zoom=Math.min(c.scaleZoom(c.scale*Math.min(p,d)),r.maxZoom),r.bearing=0,r.linear?this.easeTo(r,n):this.flyTo(r,n))},r.prototype.jumpTo=function(e,r){this.stop();var n=this.transform,i=!1,a=!1,o=!1;return"zoom"in e&&n.zoom!==+e.zoom&&(i=!0,n.zoom=+e.zoom),void 0!==e.center&&(n.center=G.convert(e.center)),"bearing"in e&&n.bearing!==+e.bearing&&(a=!0,n.bearing=+e.bearing),"pitch"in e&&n.pitch!==+e.pitch&&(o=!0,n.pitch=+e.pitch),this.fire(new t.Event("movestart",r)).fire(new t.Event("move",r)),i&&this.fire(new t.Event("zoomstart",r)).fire(new t.Event("zoom",r)).fire(new t.Event("zoomend",r)),a&&this.fire(new t.Event("rotatestart",r)).fire(new t.Event("rotate",r)).fire(new t.Event("rotateend",r)),o&&this.fire(new t.Event("pitchstart",r)).fire(new t.Event("pitch",r)).fire(new t.Event("pitchend",r)),this.fire(new t.Event("moveend",r))},r.prototype.easeTo=function(e,r){var n=this;this.stop(),!1===(e=t.extend({offset:[0,0],duration:500,easing:t.ease},e)).animate&&(e.duration=0);var i=this.transform,a=this.getZoom(),o=this.getBearing(),s=this.getPitch(),l="zoom"in e?+e.zoom:a,c="bearing"in e?this._normalizeBearing(e.bearing,o):o,u="pitch"in e?+e.pitch:s,h=i.centerPoint.add(t.default$1.convert(e.offset)),f=i.pointLocation(h),p=G.convert(e.center||f);this._normalizeCenter(p);var d,g,v=i.project(f),m=i.project(p).sub(v),y=i.zoomScale(l-a);return e.around&&(d=G.convert(e.around),g=i.locationPoint(d)),this._zooming=l!==a,this._rotating=o!==c,this._pitching=u!==s,this._prepareEase(r,e.noMoveStart),clearTimeout(this._easeEndTimeoutID),this._ease(function(e){if(n._zooming&&(i.zoom=t.number(a,l,e)),n._rotating&&(i.bearing=t.number(o,c,e)),n._pitching&&(i.pitch=t.number(s,u,e)),d)i.setLocationAtPoint(d,g);else{var f=i.zoomScale(i.zoom-a),p=l>a?Math.min(2,y):Math.max(.5,y),x=Math.pow(p,1-e),b=i.unproject(v.add(m.mult(e*x)).mult(f));i.setLocationAtPoint(i.renderWorldCopies?b.wrap():b,h)}n._fireMoveEvents(r)},function(){e.delayEndEvents?n._easeEndTimeoutID=setTimeout(function(){return n._afterEase(r)},e.delayEndEvents):n._afterEase(r)},e),this},r.prototype._prepareEase=function(e,r){this._moving=!0,r||this.fire(new t.Event("movestart",e)),this._zooming&&this.fire(new t.Event("zoomstart",e)),this._rotating&&this.fire(new t.Event("rotatestart",e)),this._pitching&&this.fire(new t.Event("pitchstart",e))},r.prototype._fireMoveEvents=function(e){this.fire(new t.Event("move",e)),this._zooming&&this.fire(new t.Event("zoom",e)),this._rotating&&this.fire(new t.Event("rotate",e)),this._pitching&&this.fire(new t.Event("pitch",e))},r.prototype._afterEase=function(e){var r=this._zooming,n=this._rotating,i=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,r&&this.fire(new t.Event("zoomend",e)),n&&this.fire(new t.Event("rotateend",e)),i&&this.fire(new t.Event("pitchend",e)),this.fire(new t.Event("moveend",e))},r.prototype.flyTo=function(e,r){var n=this;this.stop(),e=t.extend({offset:[0,0],speed:1.2,curve:1.42,easing:t.ease},e);var i=this.transform,a=this.getZoom(),o=this.getBearing(),s=this.getPitch(),l="zoom"in e?t.clamp(+e.zoom,i.minZoom,i.maxZoom):a,c="bearing"in e?this._normalizeBearing(e.bearing,o):o,u="pitch"in e?+e.pitch:s,h=i.zoomScale(l-a),f=i.centerPoint.add(t.default$1.convert(e.offset)),p=i.pointLocation(f),d=G.convert(e.center||p);this._normalizeCenter(d);var g=i.project(p),v=i.project(d).sub(g),m=e.curve,y=Math.max(i.width,i.height),x=y/h,b=v.mag();if("minZoom"in e){var _=t.clamp(Math.min(e.minZoom,a,l),i.minZoom,i.maxZoom),w=y/i.zoomScale(_-a);m=Math.sqrt(w/b*2)}var k=m*m;function A(t){var e=(x*x-y*y+(t?-1:1)*k*k*b*b)/(2*(t?x:y)*k*b);return Math.log(Math.sqrt(e*e+1)-e)}function M(t){return(Math.exp(t)-Math.exp(-t))/2}function T(t){return(Math.exp(t)+Math.exp(-t))/2}var S=A(0),E=function(t){return T(S)/T(S+m*t)},C=function(t){return y*((T(S)*(M(e=S+m*t)/T(e))-M(S))/k)/b;var e},L=(A(1)-S)/m;if(Math.abs(b)<1e-6||!isFinite(L)){if(Math.abs(y-x)<1e-6)return this.easeTo(e,r);var z=x<y?-1:1;L=Math.abs(Math.log(x/y))/m,C=function(){return 0},E=function(t){return Math.exp(z*m*t)}}if("duration"in e)e.duration=+e.duration;else{var O="screenSpeed"in e?+e.screenSpeed/m:+e.speed;e.duration=1e3*L/O}return e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0),this._zooming=!0,this._rotating=o!==c,this._pitching=u!==s,this._prepareEase(r,!1),this._ease(function(e){var l=e*L,h=1/E(l);i.zoom=a+i.scaleZoom(h),n._rotating&&(i.bearing=t.number(o,c,e)),n._pitching&&(i.pitch=t.number(s,u,e));var p=i.unproject(g.add(v.mult(C(l))).mult(h));i.setLocationAtPoint(i.renderWorldCopies?p.wrap():p,f),n._fireMoveEvents(r)},function(){return n._afterEase(r)},e),this},r.prototype.isEasing=function(){return!!this._easeFrameId},r.prototype.stop=function(){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){var t=this._onEaseEnd;delete this._onEaseEnd,t.call(this)}return this},r.prototype._ease=function(t,e,r){!1===r.animate||0===r.duration?(t(1),e()):(this._easeStart=a.now(),this._easeOptions=r,this._onEaseFrame=t,this._onEaseEnd=e,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))},r.prototype._renderFrameCallback=function(){var t=Math.min((a.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(t)),t<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()},r.prototype._normalizeBearing=function(e,r){e=t.wrap(e,-180,180);var n=Math.abs(e-r);return Math.abs(e-360-r)<n&&(e-=360),Math.abs(e+360-r)<n&&(e+=360),e},r.prototype._normalizeCenter=function(t){var e=this.transform;if(e.renderWorldCopies&&!e.lngRange){var r=t.lng-e.center.lng;t.lng+=r>180?-360:r<-180?360:0}},r}(t.Evented),nn=function(e){void 0===e&&(e={}),this.options=e,t.bindAll(["_updateEditLink","_updateData","_updateCompact"],this)};nn.prototype.getDefaultPosition=function(){return"bottom-right"},nn.prototype.onAdd=function(t){var e=this.options&&this.options.compact;return this._map=t,this._container=s.create("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),e&&this._container.classList.add("mapboxgl-compact"),this._updateAttributions(),this._updateEditLink(),this._map.on("sourcedata",this._updateData),this._map.on("moveend",this._updateEditLink),void 0===e&&(this._map.on("resize",this._updateCompact),this._updateCompact()),this._container},nn.prototype.onRemove=function(){s.remove(this._container),this._map.off("sourcedata",this._updateData),this._map.off("moveend",this._updateEditLink),this._map.off("resize",this._updateCompact),this._map=void 0},nn.prototype._updateEditLink=function(){var t=this._editLink;t||(t=this._editLink=this._container.querySelector(".mapbox-improve-map"));var e=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:v.ACCESS_TOKEN}];if(t){var r=e.reduce(function(t,r,n){return r.value&&(t+=r.key+"="+r.value+(n<e.length-1?"&":"")),t},"?");t.href="https://www.mapbox.com/feedback/"+r+(this._map._hash?this._map._hash.getHashString(!0):"")}},nn.prototype._updateData=function(t){t&&"metadata"===t.sourceDataType&&(this._updateAttributions(),this._updateEditLink())},nn.prototype._updateAttributions=function(){if(this._map.style){var t=[];if(this._map.style.stylesheet){var e=this._map.style.stylesheet;this.styleOwner=e.owner,this.styleId=e.id}var r=this._map.style.sourceCaches;for(var n in r){var i=r[n].getSource();i.attribution&&t.indexOf(i.attribution)<0&&t.push(i.attribution)}t.sort(function(t,e){return t.length-e.length}),(t=t.filter(function(e,r){for(var n=r+1;n<t.length;n++)if(t[n].indexOf(e)>=0)return!1;return!0})).length?(this._container.innerHTML=t.join(" | "),this._container.classList.remove("mapboxgl-attrib-empty")):this._container.classList.add("mapboxgl-attrib-empty"),this._editLink=null}},nn.prototype._updateCompact=function(){this._map.getCanvasContainer().offsetWidth<=640?this._container.classList.add("mapboxgl-compact"):this._container.classList.remove("mapboxgl-compact")};var an=function(){t.bindAll(["_updateLogo"],this)};an.prototype.onAdd=function(t){this._map=t,this._container=s.create("div","mapboxgl-ctrl");var e=s.create("a","mapboxgl-ctrl-logo");return e.target="_blank",e.href="https://www.mapbox.com/",e.setAttribute("aria-label","Mapbox logo"),this._container.appendChild(e),this._container.style.display="none",this._map.on("sourcedata",this._updateLogo),this._updateLogo(),this._container},an.prototype.onRemove=function(){s.remove(this._container),this._map.off("sourcedata",this._updateLogo)},an.prototype.getDefaultPosition=function(){return"bottom-left"},an.prototype._updateLogo=function(t){t&&"metadata"!==t.sourceDataType||(this._container.style.display=this._logoRequired()?"block":"none")},an.prototype._logoRequired=function(){if(this._map.style){var t=this._map.style.sourceCaches;for(var e in t)if(t[e].getSource().mapbox_logo)return!0;return!1}};var on=function(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1};on.prototype.add=function(t){var e=++this._id;return this._queue.push({callback:t,id:e,cancelled:!1}),e},on.prototype.remove=function(t){for(var e=this._currentlyRunning,r=0,n=e?this._queue.concat(e):this._queue;r<n.length;r+=1){var i=n[r];if(i.id===t)return void(i.cancelled=!0)}},on.prototype.run=function(){var t=this._currentlyRunning=this._queue;this._queue=[];for(var e=0,r=t;e<r.length;e+=1){var n=r[e];if(!n.cancelled&&(n.callback(),this._cleared))break}this._cleared=!1,this._currentlyRunning=!1},on.prototype.clear=function(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]};var sn=t.default.HTMLImageElement,ln=t.default.HTMLElement,cn={center:[0,0],zoom:0,bearing:0,pitch:0,minZoom:0,maxZoom:22,interactive:!0,scrollZoom:!0,boxZoom:!0,dragRotate:!0,dragPan:!0,keyboard:!0,doubleClickZoom:!0,touchZoomRotate:!0,bearingSnap:7,hash:!1,attributionControl:!0,failIfMajorPerformanceCaveat:!1,preserveDrawingBuffer:!1,trackResize:!0,renderWorldCopies:!0,refreshExpiredTiles:!0,maxTileCacheSize:null,transformRequest:null,fadeDuration:300},un=function(r){function n(e){if(null!=(e=t.extend({},cn,e)).minZoom&&null!=e.maxZoom&&e.minZoom>e.maxZoom)throw new Error("maxZoom must be greater than minZoom");var n=new Br(e.minZoom,e.maxZoom,e.renderWorldCopies);r.call(this,n,e),this._interactive=e.interactive,this._maxTileCacheSize=e.maxTileCacheSize,this._failIfMajorPerformanceCaveat=e.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=e.preserveDrawingBuffer,this._trackResize=e.trackResize,this._bearingSnap=e.bearingSnap,this._refreshExpiredTiles=e.refreshExpiredTiles,this._fadeDuration=e.fadeDuration,this._crossFadingFactor=1,this._collectResourceTiming=e.collectResourceTiming,this._renderTaskQueue=new on;var i=e.transformRequest;if(this._transformRequest=i?function(t,e){return i(t,e)||{url:t}}:function(t){return{url:t}},"string"==typeof e.container){var a=t.default.document.getElementById(e.container);if(!a)throw new Error("Container '"+e.container+"' not found.");this._container=a}else{if(!(e.container instanceof ln))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=e.container}e.maxBounds&&this.setMaxBounds(e.maxBounds),t.bindAll(["_onWindowOnline","_onWindowResize","_contextLost","_contextRestored","_update","_render","_onData","_onDataLoading"],this),this._setupContainer(),this._setupPainter(),this.on("move",this._update.bind(this,!1)),this.on("zoom",this._update.bind(this,!0)),void 0!==t.default&&(t.default.addEventListener("online",this._onWindowOnline,!1),t.default.addEventListener("resize",this._onWindowResize,!1)),function(t,e){var r=t.getCanvasContainer(),n=null,i=!1;for(var a in en)t[a]=new en[a](t,e),e.interactive&&e[a]&&t[a].enable(e[a]);s.addEventListener(r,"mouseout",function(e){t.fire(new Vr("mouseout",t,e))}),s.addEventListener(r,"mousedown",function(r){i=!0;var n=new Vr("mousedown",t,r);t.fire(n),n.defaultPrevented||(e.interactive&&!t.doubleClickZoom.isActive()&&t.stop(),t.boxZoom.onMouseDown(r),t.boxZoom.isActive()||t.dragPan.isActive()||t.dragRotate.onMouseDown(r),t.boxZoom.isActive()||t.dragRotate.isActive()||t.dragPan.onMouseDown(r))}),s.addEventListener(r,"mouseup",function(e){var r=t.dragRotate.isActive();n&&!r&&t.fire(new Vr("contextmenu",t,n)),n=null,i=!1,t.fire(new Vr("mouseup",t,e))}),s.addEventListener(r,"mousemove",function(e){if(!t.dragPan.isActive()&&!t.dragRotate.isActive()){for(var n=e.toElement||e.target;n&&n!==r;)n=n.parentNode;n===r&&t.fire(new Vr("mousemove",t,e))}}),s.addEventListener(r,"mouseover",function(e){for(var n=e.toElement||e.target;n&&n!==r;)n=n.parentNode;n===r&&t.fire(new Vr("mouseover",t,e))}),s.addEventListener(r,"touchstart",function(r){var n=new Ur("touchstart",t,r);t.fire(n),n.defaultPrevented||(e.interactive&&t.stop(),t.boxZoom.isActive()||t.dragRotate.isActive()||t.dragPan.onTouchStart(r),t.touchZoomRotate.onStart(r),t.doubleClickZoom.onTouchStart(n))},{passive:!1}),s.addEventListener(r,"touchmove",function(e){t.fire(new Ur("touchmove",t,e))},{passive:!1}),s.addEventListener(r,"touchend",function(e){t.fire(new Ur("touchend",t,e))}),s.addEventListener(r,"touchcancel",function(e){t.fire(new Ur("touchcancel",t,e))}),s.addEventListener(r,"click",function(e){t.fire(new Vr("click",t,e))}),s.addEventListener(r,"dblclick",function(e){var r=new Vr("dblclick",t,e);t.fire(r),r.defaultPrevented||t.doubleClickZoom.onDblClick(r)}),s.addEventListener(r,"contextmenu",function(e){var r=t.dragRotate.isActive();i||r?i&&(n=e):t.fire(new Vr("contextmenu",t,e)),e.preventDefault()}),s.addEventListener(r,"wheel",function(e){var r=new qr("wheel",t,e);t.fire(r),r.defaultPrevented||t.scrollZoom.onWheel(e)},{passive:!1})}(this,e),this._hash=e.hash&&(new jr).addTo(this),this._hash&&this._hash._onHashChange()||this.jumpTo({center:e.center,zoom:e.zoom,bearing:e.bearing,pitch:e.pitch}),this.resize(),e.style&&this.setStyle(e.style,{localIdeographFontFamily:e.localIdeographFontFamily}),e.attributionControl&&this.addControl(new nn),this.addControl(new an,e.logoPosition),this.on("style.load",function(){this.transform.unmodified&&this.jumpTo(this.style.stylesheet)}),this.on("data",this._onData),this.on("dataloading",this._onDataLoading)}r&&(n.__proto__=r),n.prototype=Object.create(r&&r.prototype),n.prototype.constructor=n;var i={showTileBoundaries:{configurable:!0},showCollisionBoxes:{configurable:!0},showOverdrawInspector:{configurable:!0},repaint:{configurable:!0},vertices:{configurable:!0}};return n.prototype.addControl=function(t,e){void 0===e&&t.getDefaultPosition&&(e=t.getDefaultPosition()),void 0===e&&(e="top-right");var r=t.onAdd(this),n=this._controlPositions[e];return-1!==e.indexOf("bottom")?n.insertBefore(r,n.firstChild):n.appendChild(r),this},n.prototype.removeControl=function(t){return t.onRemove(this),this},n.prototype.resize=function(e){var r=this._containerDimensions(),n=r[0],i=r[1];return this._resizeCanvas(n,i),this.transform.resize(n,i),this.painter.resize(n,i),this.fire(new t.Event("movestart",e)).fire(new t.Event("move",e)).fire(new t.Event("resize",e)).fire(new t.Event("moveend",e))},n.prototype.getBounds=function(){var e=new Y(this.transform.pointLocation(new t.default$1(0,this.transform.height)),this.transform.pointLocation(new t.default$1(this.transform.width,0)));return(this.transform.angle||this.transform.pitch)&&(e.extend(this.transform.pointLocation(new t.default$1(this.transform.size.x,0))),e.extend(this.transform.pointLocation(new t.default$1(0,this.transform.size.y)))),e},n.prototype.getMaxBounds=function(){return this.transform.latRange&&2===this.transform.latRange.length&&this.transform.lngRange&&2===this.transform.lngRange.length?new Y([this.transform.lngRange[0],this.transform.latRange[0]],[this.transform.lngRange[1],this.transform.latRange[1]]):null},n.prototype.setMaxBounds=function(t){if(t){var e=Y.convert(t);this.transform.lngRange=[e.getWest(),e.getEast()],this.transform.latRange=[e.getSouth(),e.getNorth()],this.transform._constrain(),this._update()}else null==t&&(this.transform.lngRange=null,this.transform.latRange=null,this._update());return this},n.prototype.setMinZoom=function(t){if((t=null==t?0:t)>=0&&t<=this.transform.maxZoom)return this.transform.minZoom=t,this._update(),this.getZoom()<t&&this.setZoom(t),this;throw new Error("minZoom must be between 0 and the current maxZoom, inclusive")},n.prototype.getMinZoom=function(){return this.transform.minZoom},n.prototype.setMaxZoom=function(t){if((t=null==t?22:t)>=this.transform.minZoom)return this.transform.maxZoom=t,this._update(),this.getZoom()>t&&this.setZoom(t),this;throw new Error("maxZoom must be greater than the current minZoom")},n.prototype.getRenderWorldCopies=function(){return this.transform.renderWorldCopies},n.prototype.setRenderWorldCopies=function(t){return this.transform.renderWorldCopies=t,this._update(),this},n.prototype.getMaxZoom=function(){return this.transform.maxZoom},n.prototype.project=function(t){return this.transform.locationPoint(G.convert(t))},n.prototype.unproject=function(e){return this.transform.pointLocation(t.default$1.convert(e))},n.prototype.isMoving=function(){return this._moving||this.dragPan.isActive()||this.dragRotate.isActive()||this.scrollZoom.isActive()},n.prototype.isZooming=function(){return this._zooming||this.scrollZoom.isActive()},n.prototype.isRotating=function(){return this._rotating||this.dragRotate.isActive()},n.prototype.on=function(t,e,n){var i,a=this;if(void 0===n)return r.prototype.on.call(this,t,e);var o=function(){if("mouseenter"===t||"mouseover"===t){var r=!1;return{layer:e,listener:n,delegates:{mousemove:function(i){var o=a.getLayer(e)?a.queryRenderedFeatures(i.point,{layers:[e]}):[];o.length?r||(r=!0,n.call(a,new Vr(t,a,i.originalEvent,{features:o}))):r=!1},mouseout:function(){r=!1}}}}if("mouseleave"===t||"mouseout"===t){var o=!1;return{layer:e,listener:n,delegates:{mousemove:function(r){(a.getLayer(e)?a.queryRenderedFeatures(r.point,{layers:[e]}):[]).length?o=!0:o&&(o=!1,n.call(a,new Vr(t,a,r.originalEvent)))},mouseout:function(e){o&&(o=!1,n.call(a,new Vr(t,a,e.originalEvent)))}}}}return{layer:e,listener:n,delegates:(i={},i[t]=function(t){var r=a.getLayer(e)?a.queryRenderedFeatures(t.point,{layers:[e]}):[];r.length&&(t.features=r,n.call(a,t),delete t.features)},i)}}();for(var s in this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[t]=this._delegatedListeners[t]||[],this._delegatedListeners[t].push(o),o.delegates)a.on(s,o.delegates[s]);return this},n.prototype.off=function(t,e,n){if(void 0===n)return r.prototype.off.call(this,t,e);if(this._delegatedListeners&&this._delegatedListeners[t])for(var i=this._delegatedListeners[t],a=0;a<i.length;a++){var o=i[a];if(o.layer===e&&o.listener===n){for(var s in o.delegates)this.off(s,o.delegates[s]);return i.splice(a,1),this}}return this},n.prototype.queryRenderedFeatures=function(e,r){var n;return 2===arguments.length?(e=arguments[0],r=arguments[1]):1===arguments.length&&((n=arguments[0])instanceof t.default$1||Array.isArray(n))?(e=arguments[0],r={}):1===arguments.length?(e=void 0,r=arguments[0]):(e=void 0,r={}),this.style?this.style.queryRenderedFeatures(this._makeQueryGeometry(e),r,this.transform):[]},n.prototype._makeQueryGeometry=function(e){var r,n=this;if(void 0===e&&(e=[t.default$1.convert([0,0]),t.default$1.convert([this.transform.width,this.transform.height])]),e instanceof t.default$1||"number"==typeof e[0])r=[t.default$1.convert(e)];else{var i=[t.default$1.convert(e[0]),t.default$1.convert(e[1])];r=[i[0],new t.default$1(i[1].x,i[0].y),i[1],new t.default$1(i[0].x,i[1].y),i[0]]}return{viewport:r,worldCoordinate:r.map(function(t){return n.transform.pointCoordinate(t)})}},n.prototype.querySourceFeatures=function(t,e){return this.style.querySourceFeatures(t,e)},n.prototype.setStyle=function(e,r){if((!r||!1!==r.diff&&!r.localIdeographFontFamily)&&this.style&&e&&"object"==typeof e)try{return this.style.setState(e)&&this._update(!0),this}catch(e){t.warnOnce("Unable to perform style diff: "+(e.message||e.error||e)+".  Rebuilding the style from scratch.")}return this.style&&(this.style.setEventedParent(null),this.style._remove()),e?(this.style=new Je(this,r||{}),this.style.setEventedParent(this,{style:this.style}),"string"==typeof e?this.style.loadURL(e):this.style.loadJSON(e),this):(delete this.style,this)},n.prototype.getStyle=function(){if(this.style)return this.style.serialize()},n.prototype.isStyleLoaded=function(){return this.style?this.style.loaded():t.warnOnce("There is no style added to the map.")},n.prototype.addSource=function(t,e){return this.style.addSource(t,e),this._update(!0),this},n.prototype.isSourceLoaded=function(e){var r=this.style&&this.style.sourceCaches[e];if(void 0!==r)return r.loaded();this.fire(new t.ErrorEvent(new Error("There is no source with ID '"+e+"'")))},n.prototype.areTilesLoaded=function(){var t=this.style&&this.style.sourceCaches;for(var e in t){var r=t[e]._tiles;for(var n in r){var i=r[n];if("loaded"!==i.state&&"errored"!==i.state)return!1}}return!0},n.prototype.addSourceType=function(t,e,r){return this.style.addSourceType(t,e,r)},n.prototype.removeSource=function(t){return this.style.removeSource(t),this._update(!0),this},n.prototype.getSource=function(t){return this.style.getSource(t)},n.prototype.addImage=function(e,r,n){void 0===n&&(n={});var i=n.pixelRatio;void 0===i&&(i=1);var o=n.sdf;if(void 0===o&&(o=!1),r instanceof sn){var s=a.getImageData(r),l=s.width,c=s.height,u=s.data;this.style.addImage(e,{data:new t.RGBAImage({width:l,height:c},u),pixelRatio:i,sdf:o})}else{if(void 0===r.width||void 0===r.height)return this.fire(new t.ErrorEvent(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));var h=r.width,f=r.height,p=r.data;this.style.addImage(e,{data:new t.RGBAImage({width:h,height:f},p.slice(0)),pixelRatio:i,sdf:o})}},n.prototype.hasImage=function(e){return e?!!this.style.getImage(e):(this.fire(new t.ErrorEvent(new Error("Missing required image id"))),!1)},n.prototype.removeImage=function(t){this.style.removeImage(t)},n.prototype.loadImage=function(e,r){t.getImage(this._transformRequest(e,t.ResourceType.Image),r)},n.prototype.addLayer=function(t,e){return this.style.addLayer(t,e),this._update(!0),this},n.prototype.moveLayer=function(t,e){return this.style.moveLayer(t,e),this._update(!0),this},n.prototype.removeLayer=function(t){return this.style.removeLayer(t),this._update(!0),this},n.prototype.getLayer=function(t){return this.style.getLayer(t)},n.prototype.setFilter=function(t,e){return this.style.setFilter(t,e),this._update(!0),this},n.prototype.setLayerZoomRange=function(t,e,r){return this.style.setLayerZoomRange(t,e,r),this._update(!0),this},n.prototype.getFilter=function(t){return this.style.getFilter(t)},n.prototype.setPaintProperty=function(t,e,r){return this.style.setPaintProperty(t,e,r),this._update(!0),this},n.prototype.getPaintProperty=function(t,e){return this.style.getPaintProperty(t,e)},n.prototype.setLayoutProperty=function(t,e,r){return this.style.setLayoutProperty(t,e,r),this._update(!0),this},n.prototype.getLayoutProperty=function(t,e){return this.style.getLayoutProperty(t,e)},n.prototype.setLight=function(t){return this.style.setLight(t),this._update(!0),this},n.prototype.getLight=function(){return this.style.getLight()},n.prototype.getContainer=function(){return this._container},n.prototype.getCanvasContainer=function(){return this._canvasContainer},n.prototype.getCanvas=function(){return this._canvas},n.prototype._containerDimensions=function(){var t=0,e=0;return this._container&&(t=this._container.offsetWidth||400,e=this._container.offsetHeight||300),[t,e]},n.prototype._setupContainer=function(){var t=this._container;t.classList.add("mapboxgl-map"),(this._missingCSSContainer=s.create("div","mapboxgl-missing-css",t)).innerHTML="Missing Mapbox GL JS CSS";var e=this._canvasContainer=s.create("div","mapboxgl-canvas-container",t);this._interactive&&e.classList.add("mapboxgl-interactive"),this._canvas=s.create("canvas","mapboxgl-canvas",e),this._canvas.style.position="absolute",this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("tabindex","0"),this._canvas.setAttribute("aria-label","Map");var r=this._containerDimensions();this._resizeCanvas(r[0],r[1]);var n=this._controlContainer=s.create("div","mapboxgl-control-container",t),i=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach(function(t){i[t]=s.create("div","mapboxgl-ctrl-"+t,n)})},n.prototype._resizeCanvas=function(e,r){var n=t.default.devicePixelRatio||1;this._canvas.width=n*e,this._canvas.height=n*r,this._canvas.style.width=e+"px",this._canvas.style.height=r+"px"},n.prototype._setupPainter=function(){var r=t.extend({failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer},e.webGLContextAttributes),n=this._canvas.getContext("webgl",r)||this._canvas.getContext("experimental-webgl",r);n?this.painter=new zr(n,this.transform):this.fire(new t.ErrorEvent(new Error("Failed to initialize WebGL")))},n.prototype._contextLost=function(e){e.preventDefault(),this._frameId&&(a.cancelFrame(this._frameId),this._frameId=null),this.fire(new t.Event("webglcontextlost",{originalEvent:e}))},n.prototype._contextRestored=function(e){this._setupPainter(),this.resize(),this._update(),this.fire(new t.Event("webglcontextrestored",{originalEvent:e}))},n.prototype.loaded=function(){return!this._styleDirty&&!this._sourcesDirty&&!(!this.style||!this.style.loaded())},n.prototype._update=function(t){this.style&&(this._styleDirty=this._styleDirty||t,this._sourcesDirty=!0,this._rerender())},n.prototype._requestRenderFrame=function(t){return this._update(),this._renderTaskQueue.add(t)},n.prototype._cancelRenderFrame=function(t){this._renderTaskQueue.remove(t)},n.prototype._render=function(){this._renderTaskQueue.run();var e=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;var r=this.transform.zoom,n=a.now();this.style.zoomHistory.update(r,n);var i=new t.default$16(r,{now:n,fadeDuration:this._fadeDuration,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),o=i.crossFadingFactor();1===o&&o===this._crossFadingFactor||(e=!0,this._crossFadingFactor=o),this.style.update(i)}return this.style&&this._sourcesDirty&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this._placementDirty=this.style&&this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,this._fadeDuration),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),fadeDuration:this._fadeDuration}),this.fire(new t.Event("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,this.fire(new t.Event("load"))),this.style&&(this.style.hasTransitions()||e)&&(this._styleDirty=!0),(this._sourcesDirty||this._repaint||this._styleDirty||this._placementDirty)&&this._rerender(),this},n.prototype.remove=function(){this._hash&&this._hash.remove(),a.cancelFrame(this._frameId),this._renderTaskQueue.clear(),this._frameId=null,this.setStyle(null),void 0!==t.default&&(t.default.removeEventListener("resize",this._onWindowResize,!1),t.default.removeEventListener("online",this._onWindowOnline,!1));var e=this.painter.context.gl.getExtension("WEBGL_lose_context");e&&e.loseContext(),hn(this._canvasContainer),hn(this._controlContainer),hn(this._missingCSSContainer),this._container.classList.remove("mapboxgl-map"),this.fire(new t.Event("remove"))},n.prototype._rerender=function(){var t=this;this.style&&!this._frameId&&(this._frameId=a.frame(function(){t._frameId=null,t._render()}))},n.prototype._onWindowOnline=function(){this._update()},n.prototype._onWindowResize=function(){this._trackResize&&this.stop().resize()._update()},i.showTileBoundaries.get=function(){return!!this._showTileBoundaries},i.showTileBoundaries.set=function(t){this._showTileBoundaries!==t&&(this._showTileBoundaries=t,this._update())},i.showCollisionBoxes.get=function(){return!!this._showCollisionBoxes},i.showCollisionBoxes.set=function(t){this._showCollisionBoxes!==t&&(this._showCollisionBoxes=t,t?this.style._generateCollisionBoxes():this._update())},i.showOverdrawInspector.get=function(){return!!this._showOverdrawInspector},i.showOverdrawInspector.set=function(t){this._showOverdrawInspector!==t&&(this._showOverdrawInspector=t,this._update())},i.repaint.get=function(){return!!this._repaint},i.repaint.set=function(t){this._repaint=t,this._update()},i.vertices.get=function(){return!!this._vertices},i.vertices.set=function(t){this._vertices=t,this._update()},n.prototype._onData=function(e){this._update("style"===e.dataType),this.fire(new t.Event(e.dataType+"data",e))},n.prototype._onDataLoading=function(e){this.fire(new t.Event(e.dataType+"dataloading",e))},Object.defineProperties(n.prototype,i),n}(rn);function hn(t){t.parentNode&&t.parentNode.removeChild(t)}var fn={showCompass:!0,showZoom:!0},pn=function(e){var r=this;this.options=t.extend({},fn,e),this._container=s.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",function(t){return t.preventDefault()}),this.options.showZoom&&(this._zoomInButton=this._createButton("mapboxgl-ctrl-icon mapboxgl-ctrl-zoom-in","Zoom In",function(){return r._map.zoomIn()}),this._zoomOutButton=this._createButton("mapboxgl-ctrl-icon mapboxgl-ctrl-zoom-out","Zoom Out",function(){return r._map.zoomOut()})),this.options.showCompass&&(t.bindAll(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-icon mapboxgl-ctrl-compass","Reset North",function(){return r._map.resetNorth()}),this._compassArrow=s.create("span","mapboxgl-ctrl-compass-arrow",this._compass))};function dn(t,e,r){if(t=new G(t.lng,t.lat),e){var n=new G(t.lng-360,t.lat),i=new G(t.lng+360,t.lat),a=r.locationPoint(t).distSqr(e);r.locationPoint(n).distSqr(e)<a?t=n:r.locationPoint(i).distSqr(e)<a&&(t=i)}for(;Math.abs(t.lng-r.center.lng)>180;){var o=r.locationPoint(t);if(o.x>=0&&o.y>=0&&o.x<=r.width&&o.y<=r.height)break;t.lng>r.center.lng?t.lng-=360:t.lng+=360}return t}pn.prototype._rotateCompassArrow=function(){var t="rotate("+this._map.transform.angle*(180/Math.PI)+"deg)";this._compassArrow.style.transform=t},pn.prototype.onAdd=function(t){return this._map=t,this.options.showCompass&&(this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new Wr(t,{button:"left",element:this._compass}),this._handler.enable()),this._container},pn.prototype.onRemove=function(){s.remove(this._container),this.options.showCompass&&(this._map.off("rotate",this._rotateCompassArrow),this._handler.disable(),delete this._handler),delete this._map},pn.prototype._createButton=function(t,e,r){var n=s.create("button",t,this._container);return n.type="button",n.setAttribute("aria-label",e),n.addEventListener("click",r),n};var gn={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function vn(t,e,r){var n=t.classList;for(var i in gn)n.remove("mapboxgl-"+r+"-anchor-"+i);n.add("mapboxgl-"+r+"-anchor-"+e)}var mn=function(e){if((arguments[0]instanceof t.default.HTMLElement||2===arguments.length)&&(e=t.extend({element:e},arguments[1])),t.bindAll(["_update","_onMapClick"],this),this._anchor=e&&e.anchor||"center",this._color=e&&e.color||"#3FB1CE",e&&e.element)this._element=e.element,this._offset=t.default$1.convert(e&&e.offset||[0,0]);else{this._defaultMarker=!0,this._element=s.create("div");var r=s.createNS("http://www.w3.org/2000/svg","svg");r.setAttributeNS(null,"height","41px"),r.setAttributeNS(null,"width","27px"),r.setAttributeNS(null,"viewBox","0 0 27 41");var n=s.createNS("http://www.w3.org/2000/svg","g");n.setAttributeNS(null,"stroke","none"),n.setAttributeNS(null,"stroke-width","1"),n.setAttributeNS(null,"fill","none"),n.setAttributeNS(null,"fill-rule","evenodd");var i=s.createNS("http://www.w3.org/2000/svg","g");i.setAttributeNS(null,"fill-rule","nonzero");var a=s.createNS("http://www.w3.org/2000/svg","g");a.setAttributeNS(null,"transform","translate(3.0, 29.0)"),a.setAttributeNS(null,"fill","#000000");for(var o=0,l=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];o<l.length;o+=1){var c=l[o],u=s.createNS("http://www.w3.org/2000/svg","ellipse");u.setAttributeNS(null,"opacity","0.04"),u.setAttributeNS(null,"cx","10.5"),u.setAttributeNS(null,"cy","5.80029008"),u.setAttributeNS(null,"rx",c.rx),u.setAttributeNS(null,"ry",c.ry),a.appendChild(u)}var h=s.createNS("http://www.w3.org/2000/svg","g");h.setAttributeNS(null,"fill",this._color);var f=s.createNS("http://www.w3.org/2000/svg","path");f.setAttributeNS(null,"d","M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z"),h.appendChild(f);var p=s.createNS("http://www.w3.org/2000/svg","g");p.setAttributeNS(null,"opacity","0.25"),p.setAttributeNS(null,"fill","#000000");var d=s.createNS("http://www.w3.org/2000/svg","path");d.setAttributeNS(null,"d","M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z"),p.appendChild(d);var g=s.createNS("http://www.w3.org/2000/svg","g");g.setAttributeNS(null,"transform","translate(6.0, 7.0)"),g.setAttributeNS(null,"fill","#FFFFFF");var v=s.createNS("http://www.w3.org/2000/svg","g");v.setAttributeNS(null,"transform","translate(8.0, 8.0)");var m=s.createNS("http://www.w3.org/2000/svg","circle");m.setAttributeNS(null,"fill","#000000"),m.setAttributeNS(null,"opacity","0.25"),m.setAttributeNS(null,"cx","5.5"),m.setAttributeNS(null,"cy","5.5"),m.setAttributeNS(null,"r","5.4999962");var y=s.createNS("http://www.w3.org/2000/svg","circle");y.setAttributeNS(null,"fill","#FFFFFF"),y.setAttributeNS(null,"cx","5.5"),y.setAttributeNS(null,"cy","5.5"),y.setAttributeNS(null,"r","5.4999962"),v.appendChild(m),v.appendChild(y),i.appendChild(a),i.appendChild(h),i.appendChild(p),i.appendChild(g),i.appendChild(v),r.appendChild(i),this._element.appendChild(r),this._offset=t.default$1.convert(e&&e.offset||[0,-14])}this._element.classList.add("mapboxgl-marker"),this._popup=null};mn.prototype.addTo=function(t){return this.remove(),this._map=t,t.getCanvasContainer().appendChild(this._element),t.on("move",this._update),t.on("moveend",this._update),this._update(),this._map.on("click",this._onMapClick),this},mn.prototype.remove=function(){return this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),delete this._map),s.remove(this._element),this._popup&&this._popup.remove(),this},mn.prototype.getLngLat=function(){return this._lngLat},mn.prototype.setLngLat=function(t){return this._lngLat=G.convert(t),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this},mn.prototype.getElement=function(){return this._element},mn.prototype.setPopup=function(t){if(this._popup&&(this._popup.remove(),this._popup=null),t){if(!("offset"in t.options)){var e=Math.sqrt(Math.pow(13.5,2)/2);t.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[e,-1*(24.6+e)],"bottom-right":[-e,-1*(24.6+e)],left:[13.5,-24.6],right:[-13.5,-24.6]}:this._offset}this._popup=t,this._lngLat&&this._popup.setLngLat(this._lngLat)}return this},mn.prototype._onMapClick=function(t){var e=t.originalEvent.target,r=this._element;this._popup&&(e===r||r.contains(e))&&this.togglePopup()},mn.prototype.getPopup=function(){return this._popup},mn.prototype.togglePopup=function(){var t=this._popup;return t?(t.isOpen()?t.remove():t.addTo(this._map),this):this},mn.prototype._update=function(t){this._map&&(this._map.transform.renderWorldCopies&&(this._lngLat=dn(this._lngLat,this._pos,this._map.transform)),this._pos=this._map.project(this._lngLat)._add(this._offset),t&&"moveend"!==t.type||(this._pos=this._pos.round()),s.setTransform(this._element,gn[this._anchor]+" translate("+this._pos.x+"px, "+this._pos.y+"px)"),vn(this._element,this._anchor,"marker"))},mn.prototype.getOffset=function(){return this._offset},mn.prototype.setOffset=function(e){return this._offset=t.default$1.convert(e),this._update(),this};var yn,xn={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showUserLocation:!0},bn=function(e){function r(r){e.call(this),this.options=t.extend({},xn,r),t.bindAll(["_onSuccess","_onError","_finish","_setupUI","_updateCamera","_updateMarker"],this)}return e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r,r.prototype.onAdd=function(e){var r;return this._map=e,this._container=s.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),r=this._setupUI,void 0!==yn?r(yn):void 0!==t.default.navigator.permissions?t.default.navigator.permissions.query({name:"geolocation"}).then(function(t){yn="denied"!==t.state,r(yn)}):(yn=!!t.default.navigator.geolocation,r(yn)),this._container},r.prototype.onRemove=function(){void 0!==this._geolocationWatchID&&(t.default.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker.remove(),s.remove(this._container),this._map=void 0},r.prototype._onSuccess=function(e){if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background")}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove("mapboxgl-user-location-dot-stale"),this.fire(new t.Event("geolocate",e)),this._finish()},r.prototype._updateCamera=function(t){var e=new G(t.coords.longitude,t.coords.latitude),r=t.coords.accuracy;this._map.fitBounds(e.toBounds(r),this.options.fitBoundsOptions,{geolocateSource:!0})},r.prototype._updateMarker=function(t){t?this._userLocationDotMarker.setLngLat([t.coords.longitude,t.coords.latitude]).addTo(this._map):this._userLocationDotMarker.remove()},r.prototype._onError=function(e){if(this.options.trackUserLocation)if(1===e.code)this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),void 0!==this._geolocationWatchID&&this._clearWatch();else switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting")}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("mapboxgl-user-location-dot-stale"),this.fire(new t.Event("error",e)),this._finish()},r.prototype._finish=function(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0},r.prototype._setupUI=function(e){var r=this;!1!==e&&(this._container.addEventListener("contextmenu",function(t){return t.preventDefault()}),this._geolocateButton=s.create("button","mapboxgl-ctrl-icon mapboxgl-ctrl-geolocate",this._container),this._geolocateButton.type="button",this._geolocateButton.setAttribute("aria-label","Geolocate"),this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=s.create("div","mapboxgl-user-location-dot"),this._userLocationDotMarker=new mn(this._dotElement),this.options.trackUserLocation&&(this._watchState="OFF")),this._geolocateButton.addEventListener("click",this.trigger.bind(this)),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",function(e){e.geolocateSource||"ACTIVE_LOCK"!==r._watchState||(r._watchState="BACKGROUND",r._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),r._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),r.fire(new t.Event("trackuserlocationend")))}))},r.prototype.trigger=function(){if(!this._setup)return t.warnOnce("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new t.Event("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this.fire(new t.Event("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new t.Event("trackuserlocationstart"))}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"BACKGROUND":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");break;case"BACKGROUND_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error")}"OFF"===this._watchState&&void 0!==this._geolocationWatchID?this._clearWatch():void 0===this._geolocationWatchID&&(this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),this._geolocationWatchID=t.default.navigator.geolocation.watchPosition(this._onSuccess,this._onError,this.options.positionOptions))}else t.default.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return!0},r.prototype._clearWatch=function(){t.default.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)},r}(t.Evented),_n={maxWidth:100,unit:"metric"},wn=function(e){this.options=t.extend({},_n,e),t.bindAll(["_onMove","setUnit"],this)};function kn(t,e,r){var n,i,a,o,s,l,c=r&&r.maxWidth||100,u=t._container.clientHeight/2,h=(n=t.unproject([0,u]),i=t.unproject([c,u]),a=Math.PI/180,o=n.lat*a,s=i.lat*a,l=Math.sin(o)*Math.sin(s)+Math.cos(o)*Math.cos(s)*Math.cos((i.lng-n.lng)*a),6371e3*Math.acos(Math.min(l,1)));if(r&&"imperial"===r.unit){var f=3.2808*h;f>5280?An(e,c,f/5280,"mi"):An(e,c,f,"ft")}else r&&"nautical"===r.unit?An(e,c,h/1852,"nm"):An(e,c,h,"m")}function An(t,e,r,n){var i,a,o,s=(i=r,(a=Math.pow(10,(""+Math.floor(i)).length-1))*(o=(o=i/a)>=10?10:o>=5?5:o>=3?3:o>=2?2:1)),l=s/r;"m"===n&&s>=1e3&&(s/=1e3,n="km"),t.style.width=e*l+"px",t.innerHTML=s+n}wn.prototype.getDefaultPosition=function(){return"bottom-left"},wn.prototype._onMove=function(){kn(this._map,this._container,this.options)},wn.prototype.onAdd=function(t){return this._map=t,this._container=s.create("div","mapboxgl-ctrl mapboxgl-ctrl-scale",t.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container},wn.prototype.onRemove=function(){s.remove(this._container),this._map.off("move",this._onMove),this._map=void 0},wn.prototype.setUnit=function(t){this.options.unit=t,kn(this._map,this._container,this.options)};var Mn=function(){this._fullscreen=!1,t.bindAll(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in t.default.document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in t.default.document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in t.default.document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in t.default.document&&(this._fullscreenchange="MSFullscreenChange"),this._className="mapboxgl-ctrl"};Mn.prototype.onAdd=function(e){return this._map=e,this._mapContainer=this._map.getContainer(),this._container=s.create("div",this._className+" mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._container.style.display="none",t.warnOnce("This device does not support fullscreen mode.")),this._container},Mn.prototype.onRemove=function(){s.remove(this._container),this._map=null,t.default.document.removeEventListener(this._fullscreenchange,this._changeIcon)},Mn.prototype._checkFullscreenSupport=function(){return!!(t.default.document.fullscreenEnabled||t.default.document.mozFullScreenEnabled||t.default.document.msFullscreenEnabled||t.default.document.webkitFullscreenEnabled)},Mn.prototype._setupUI=function(){var e=this._fullscreenButton=s.create("button",this._className+"-icon "+this._className+"-fullscreen",this._container);e.setAttribute("aria-label","Toggle fullscreen"),e.type="button",this._fullscreenButton.addEventListener("click",this._onClickFullscreen),t.default.document.addEventListener(this._fullscreenchange,this._changeIcon)},Mn.prototype._isFullscreen=function(){return this._fullscreen},Mn.prototype._changeIcon=function(){(t.default.document.fullscreenElement||t.default.document.mozFullScreenElement||t.default.document.webkitFullscreenElement||t.default.document.msFullscreenElement)===this._mapContainer!==this._fullscreen&&(this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle(this._className+"-shrink"),this._fullscreenButton.classList.toggle(this._className+"-fullscreen"))},Mn.prototype._onClickFullscreen=function(){this._isFullscreen()?t.default.document.exitFullscreen?t.default.document.exitFullscreen():t.default.document.mozCancelFullScreen?t.default.document.mozCancelFullScreen():t.default.document.msExitFullscreen?t.default.document.msExitFullscreen():t.default.document.webkitCancelFullScreen&&t.default.document.webkitCancelFullScreen():this._mapContainer.requestFullscreen?this._mapContainer.requestFullscreen():this._mapContainer.mozRequestFullScreen?this._mapContainer.mozRequestFullScreen():this._mapContainer.msRequestFullscreen?this._mapContainer.msRequestFullscreen():this._mapContainer.webkitRequestFullscreen&&this._mapContainer.webkitRequestFullscreen()};var Tn={closeButton:!0,closeOnClick:!0},Sn=function(e){function r(r){e.call(this),this.options=t.extend(Object.create(Tn),r),t.bindAll(["_update","_onClickClose"],this)}return e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r,r.prototype.addTo=function(e){return this._map=e,this._map.on("move",this._update),this.options.closeOnClick&&this._map.on("click",this._onClickClose),this._update(),this.fire(new t.Event("open")),this},r.prototype.isOpen=function(){return!!this._map},r.prototype.remove=function(){return this._content&&s.remove(this._content),this._container&&(s.remove(this._container),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("click",this._onClickClose),delete this._map),this.fire(new t.Event("close")),this},r.prototype.getLngLat=function(){return this._lngLat},r.prototype.setLngLat=function(t){return this._lngLat=G.convert(t),this._pos=null,this._update(),this},r.prototype.setText=function(e){return this.setDOMContent(t.default.document.createTextNode(e))},r.prototype.setHTML=function(e){var r,n=t.default.document.createDocumentFragment(),i=t.default.document.createElement("body");for(i.innerHTML=e;r=i.firstChild;)n.appendChild(r);return this.setDOMContent(n)},r.prototype.setDOMContent=function(t){return this._createContent(),this._content.appendChild(t),this._update(),this},r.prototype._createContent=function(){this._content&&s.remove(this._content),this._content=s.create("div","mapboxgl-popup-content",this._container),this.options.closeButton&&(this._closeButton=s.create("button","mapboxgl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.setAttribute("aria-label","Close popup"),this._closeButton.innerHTML="&#215;",this._closeButton.addEventListener("click",this._onClickClose))},r.prototype._update=function(){if(this._map&&this._lngLat&&this._content){this._container||(this._container=s.create("div","mapboxgl-popup",this._map.getContainer()),this._tip=s.create("div","mapboxgl-popup-tip",this._container),this._container.appendChild(this._content)),this._map.transform.renderWorldCopies&&(this._lngLat=dn(this._lngLat,this._pos,this._map.transform));var e=this._pos=this._map.project(this._lngLat),r=this.options.anchor,n=function e(r){if(r){if("number"==typeof r){var n=Math.round(Math.sqrt(.5*Math.pow(r,2)));return{center:new t.default$1(0,0),top:new t.default$1(0,r),"top-left":new t.default$1(n,n),"top-right":new t.default$1(-n,n),bottom:new t.default$1(0,-r),"bottom-left":new t.default$1(n,-n),"bottom-right":new t.default$1(-n,-n),left:new t.default$1(r,0),right:new t.default$1(-r,0)}}if(r instanceof t.default$1||Array.isArray(r)){var i=t.default$1.convert(r);return{center:i,top:i,"top-left":i,"top-right":i,bottom:i,"bottom-left":i,"bottom-right":i,left:i,right:i}}return{center:t.default$1.convert(r.center||[0,0]),top:t.default$1.convert(r.top||[0,0]),"top-left":t.default$1.convert(r["top-left"]||[0,0]),"top-right":t.default$1.convert(r["top-right"]||[0,0]),bottom:t.default$1.convert(r.bottom||[0,0]),"bottom-left":t.default$1.convert(r["bottom-left"]||[0,0]),"bottom-right":t.default$1.convert(r["bottom-right"]||[0,0]),left:t.default$1.convert(r.left||[0,0]),right:t.default$1.convert(r.right||[0,0])}}return e(new t.default$1(0,0))}(this.options.offset);if(!r){var i,a=this._container.offsetWidth,o=this._container.offsetHeight;i=e.y+n.bottom.y<o?["top"]:e.y>this._map.transform.height-o?["bottom"]:[],e.x<a/2?i.push("left"):e.x>this._map.transform.width-a/2&&i.push("right"),r=0===i.length?"bottom":i.join("-")}var l=e.add(n[r]).round();s.setTransform(this._container,gn[r]+" translate("+l.x+"px,"+l.y+"px)"),vn(this._container,r,"popup")}},r.prototype._onClickClose=function(){this.remove()},r}(t.Evented),En={version:"0.45.0",supported:e,workerCount:Math.max(Math.floor(a.hardwareConcurrency/2),1),setRTLTextPlugin:t.setRTLTextPlugin,Map:un,NavigationControl:pn,GeolocateControl:bn,AttributionControl:nn,ScaleControl:wn,FullscreenControl:Mn,Popup:Sn,Marker:mn,Style:Je,LngLat:G,LngLatBounds:Y,Point:t.default$1,Evented:t.Evented,config:v,get accessToken(){return v.ACCESS_TOKEN},set accessToken(t){v.ACCESS_TOKEN=t},workerUrl:""};return En}),n})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],416:[function(t,e,r){"use strict";e.exports=function(t){for(var e=1<<t+1,r=new Array(e),n=0;n<e;++n)r[n]=a(t,n);return r};var n=t("convex-hull");function i(t,e,r){for(var n=new Array(t),i=0;i<t;++i)n[i]=0,i===e&&(n[i]+=.5),i===r&&(n[i]+=.5);return n}function a(t,e){if(0===e||e===(1<<t+1)-1)return[];for(var r=[],a=[],o=0;o<=t;++o)if(e&1<<o){r.push(i(t,o-1,o-1)),a.push(null);for(var s=0;s<=t;++s)~e&1<<s&&(r.push(i(t,o-1,s-1)),a.push([o,s]))}var l=n(r),c=[];t:for(o=0;o<l.length;++o){var u=l[o],h=[];for(s=0;s<u.length;++s){if(!a[u[s]])continue t;h.push(a[u[s]].slice())}c.push(h)}return c}},{"convex-hull":118}],417:[function(t,e,r){var n=t("./normalize"),i=t("gl-mat4/create"),a=t("gl-mat4/clone"),o=t("gl-mat4/determinant"),s=t("gl-mat4/invert"),l=t("gl-mat4/transpose"),c={length:t("gl-vec3/length"),normalize:t("gl-vec3/normalize"),dot:t("gl-vec3/dot"),cross:t("gl-vec3/cross")},u=i(),h=i(),f=[0,0,0,0],p=[[0,0,0],[0,0,0],[0,0,0]],d=[0,0,0];function g(t,e,r,n,i){t[0]=e[0]*n+r[0]*i,t[1]=e[1]*n+r[1]*i,t[2]=e[2]*n+r[2]*i}e.exports=function(t,e,r,i,v,m){if(e||(e=[0,0,0]),r||(r=[0,0,0]),i||(i=[0,0,0]),v||(v=[0,0,0,1]),m||(m=[0,0,0,1]),!n(u,t))return!1;if(a(h,u),h[3]=0,h[7]=0,h[11]=0,h[15]=1,Math.abs(o(h)<1e-8))return!1;var y,x,b,_,w,k,A,M=u[3],T=u[7],S=u[11],E=u[12],C=u[13],L=u[14],z=u[15];if(0!==M||0!==T||0!==S){if(f[0]=M,f[1]=T,f[2]=S,f[3]=z,!s(h,h))return!1;l(h,h),y=v,b=h,_=(x=f)[0],w=x[1],k=x[2],A=x[3],y[0]=b[0]*_+b[4]*w+b[8]*k+b[12]*A,y[1]=b[1]*_+b[5]*w+b[9]*k+b[13]*A,y[2]=b[2]*_+b[6]*w+b[10]*k+b[14]*A,y[3]=b[3]*_+b[7]*w+b[11]*k+b[15]*A}else v[0]=v[1]=v[2]=0,v[3]=1;if(e[0]=E,e[1]=C,e[2]=L,function(t,e){t[0][0]=e[0],t[0][1]=e[1],t[0][2]=e[2],t[1][0]=e[4],t[1][1]=e[5],t[1][2]=e[6],t[2][0]=e[8],t[2][1]=e[9],t[2][2]=e[10]}(p,u),r[0]=c.length(p[0]),c.normalize(p[0],p[0]),i[0]=c.dot(p[0],p[1]),g(p[1],p[1],p[0],1,-i[0]),r[1]=c.length(p[1]),c.normalize(p[1],p[1]),i[0]/=r[1],i[1]=c.dot(p[0],p[2]),g(p[2],p[2],p[0],1,-i[1]),i[2]=c.dot(p[1],p[2]),g(p[2],p[2],p[1],1,-i[2]),r[2]=c.length(p[2]),c.normalize(p[2],p[2]),i[1]/=r[2],i[2]/=r[2],c.cross(d,p[1],p[2]),c.dot(p[0],d)<0)for(var O=0;O<3;O++)r[O]*=-1,p[O][0]*=-1,p[O][1]*=-1,p[O][2]*=-1;return m[0]=.5*Math.sqrt(Math.max(1+p[0][0]-p[1][1]-p[2][2],0)),m[1]=.5*Math.sqrt(Math.max(1-p[0][0]+p[1][1]-p[2][2],0)),m[2]=.5*Math.sqrt(Math.max(1-p[0][0]-p[1][1]+p[2][2],0)),m[3]=.5*Math.sqrt(Math.max(1+p[0][0]+p[1][1]+p[2][2],0)),p[2][1]>p[1][2]&&(m[0]=-m[0]),p[0][2]>p[2][0]&&(m[1]=-m[1]),p[1][0]>p[0][1]&&(m[2]=-m[2]),!0}},{"./normalize":418,"gl-mat4/clone":252,"gl-mat4/create":253,"gl-mat4/determinant":254,"gl-mat4/invert":258,"gl-mat4/transpose":269,"gl-vec3/cross":323,"gl-vec3/dot":328,"gl-vec3/length":338,"gl-vec3/normalize":345}],418:[function(t,e,r){e.exports=function(t,e){var r=e[15];if(0===r)return!1;for(var n=1/r,i=0;i<16;i++)t[i]=e[i]*n;return!0}},{}],419:[function(t,e,r){var n=t("gl-vec3/lerp"),i=t("mat4-recompose"),a=t("mat4-decompose"),o=t("gl-mat4/determinant"),s=t("quat-slerp"),l=h(),c=h(),u=h();function h(){return{translate:f(),scale:f(1),skew:f(),perspective:[0,0,0,1],quaternion:[0,0,0,1]}}function f(t){return[t||0,t||0,t||0]}e.exports=function(t,e,r,h){if(0===o(e)||0===o(r))return!1;var f=a(e,l.translate,l.scale,l.skew,l.perspective,l.quaternion),p=a(r,c.translate,c.scale,c.skew,c.perspective,c.quaternion);return!(!f||!p||(n(u.translate,l.translate,c.translate,h),n(u.skew,l.skew,c.skew,h),n(u.scale,l.scale,c.scale,h),n(u.perspective,l.perspective,c.perspective,h),s(u.quaternion,l.quaternion,c.quaternion,h),i(t,u.translate,u.scale,u.skew,u.perspective,u.quaternion),0))}},{"gl-mat4/determinant":254,"gl-vec3/lerp":339,"mat4-decompose":417,"mat4-recompose":420,"quat-slerp":472}],420:[function(t,e,r){var n={identity:t("gl-mat4/identity"),translate:t("gl-mat4/translate"),multiply:t("gl-mat4/multiply"),create:t("gl-mat4/create"),scale:t("gl-mat4/scale"),fromRotationTranslation:t("gl-mat4/fromRotationTranslation")},i=(n.create(),n.create());e.exports=function(t,e,r,a,o,s){return n.identity(t),n.fromRotationTranslation(t,s,e),t[3]=o[0],t[7]=o[1],t[11]=o[2],t[15]=o[3],n.identity(i),0!==a[2]&&(i[9]=a[2],n.multiply(t,t,i)),0!==a[1]&&(i[9]=0,i[8]=a[1],n.multiply(t,t,i)),0!==a[0]&&(i[8]=0,i[4]=a[0],n.multiply(t,t,i)),n.scale(t,t,r),t}},{"gl-mat4/create":253,"gl-mat4/fromRotationTranslation":256,"gl-mat4/identity":257,"gl-mat4/multiply":260,"gl-mat4/scale":267,"gl-mat4/translate":268}],421:[function(t,e,r){"use strict";e.exports=Math.log2||function(t){return Math.log(t)*Math.LOG2E}},{}],422:[function(t,e,r){"use strict";var n=t("binary-search-bounds"),i=t("mat4-interpolate"),a=t("gl-mat4/invert"),o=t("gl-mat4/rotateX"),s=t("gl-mat4/rotateY"),l=t("gl-mat4/rotateZ"),c=t("gl-mat4/lookAt"),u=t("gl-mat4/translate"),h=(t("gl-mat4/scale"),t("gl-vec3/normalize")),f=[0,0,0];function p(t){this._components=t.slice(),this._time=[0],this.prevMatrix=t.slice(),this.nextMatrix=t.slice(),this.computedMatrix=t.slice(),this.computedInverse=t.slice(),this.computedEye=[0,0,0],this.computedUp=[0,0,0],this.computedCenter=[0,0,0],this.computedRadius=[0],this._limits=[-1/0,1/0]}e.exports=function(t){return new p((t=t||{}).matrix||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])};var d=p.prototype;d.recalcMatrix=function(t){var e=this._time,r=n.le(e,t),o=this.computedMatrix;if(!(r<0)){var s=this._components;if(r===e.length-1)for(var l=16*r,c=0;c<16;++c)o[c]=s[l++];else{var u=e[r+1]-e[r],f=(l=16*r,this.prevMatrix),p=!0;for(c=0;c<16;++c)f[c]=s[l++];var d=this.nextMatrix;for(c=0;c<16;++c)d[c]=s[l++],p=p&&f[c]===d[c];if(u<1e-6||p)for(c=0;c<16;++c)o[c]=f[c];else i(o,f,d,(t-e[r])/u)}var g=this.computedUp;g[0]=o[1],g[1]=o[5],g[2]=o[9],h(g,g);var v=this.computedInverse;a(v,o);var m=this.computedEye,y=v[15];m[0]=v[12]/y,m[1]=v[13]/y,m[2]=v[14]/y;var x=this.computedCenter,b=Math.exp(this.computedRadius[0]);for(c=0;c<3;++c)x[c]=m[c]-o[2+4*c]*b}},d.idle=function(t){if(!(t<this.lastT())){for(var e=this._components,r=e.length-16,n=0;n<16;++n)e.push(e[r++]);this._time.push(t)}},d.flush=function(t){var e=n.gt(this._time,t)-2;e<0||(this._time.splice(0,e),this._components.splice(0,16*e))},d.lastT=function(){return this._time[this._time.length-1]},d.lookAt=function(t,e,r,n){this.recalcMatrix(t),e=e||this.computedEye,r=r||f,n=n||this.computedUp,this.setMatrix(t,c(this.computedMatrix,e,r,n));for(var i=0,a=0;a<3;++a)i+=Math.pow(r[a]-e[a],2);i=Math.log(Math.sqrt(i)),this.computedRadius[0]=i},d.rotate=function(t,e,r,n){this.recalcMatrix(t);var i=this.computedInverse;e&&s(i,i,e),r&&o(i,i,r),n&&l(i,i,n),this.setMatrix(t,a(this.computedMatrix,i))};var g=[0,0,0];d.pan=function(t,e,r,n){g[0]=-(e||0),g[1]=-(r||0),g[2]=-(n||0),this.recalcMatrix(t);var i=this.computedInverse;u(i,i,g),this.setMatrix(t,a(i,i))},d.translate=function(t,e,r,n){g[0]=e||0,g[1]=r||0,g[2]=n||0,this.recalcMatrix(t);var i=this.computedMatrix;u(i,i,g),this.setMatrix(t,i)},d.setMatrix=function(t,e){if(!(t<this.lastT())){this._time.push(t);for(var r=0;r<16;++r)this._components.push(e[r])}},d.setDistance=function(t,e){this.computedRadius[0]=e},d.setDistanceLimits=function(t,e){var r=this._limits;r[0]=t,r[1]=e},d.getDistanceLimits=function(t){var e=this._limits;return t?(t[0]=e[0],t[1]=e[1],t):e}},{"binary-search-bounds":79,"gl-mat4/invert":258,"gl-mat4/lookAt":259,"gl-mat4/rotateX":264,"gl-mat4/rotateY":265,"gl-mat4/rotateZ":266,"gl-mat4/scale":267,"gl-mat4/translate":268,"gl-vec3/normalize":345,"mat4-interpolate":419}],423:[function(t,e,r){"use strict";e.exports=function(t){var e=t.length;if(e<3){for(var r=new Array(e),i=0;i<e;++i)r[i]=i;return 2===e&&t[0][0]===t[1][0]&&t[0][1]===t[1][1]?[0]:r}for(var a=new Array(e),i=0;i<e;++i)a[i]=i;a.sort(function(e,r){var n=t[e][0]-t[r][0];return n||t[e][1]-t[r][1]});for(var o=[a[0],a[1]],s=[a[0],a[1]],i=2;i<e;++i){for(var l=a[i],c=t[l],u=o.length;u>1&&n(t[o[u-2]],t[o[u-1]],c)<=0;)u-=1,o.pop();for(o.push(l),u=s.length;u>1&&n(t[s[u-2]],t[s[u-1]],c)>=0;)u-=1,s.pop();s.push(l)}for(var r=new Array(s.length+o.length-2),h=0,i=0,f=o.length;i<f;++i)r[h++]=o[i];for(var p=s.length-2;p>0;--p)r[h++]=s[p];return r};var n=t("robust-orientation")[3]},{"robust-orientation":491}],424:[function(t,e,r){"use strict";e.exports=function(t,e){e||(e=t,t=window);var r=0,i=0,a=0,o={shift:!1,alt:!1,control:!1,meta:!1},s=!1;function l(t){var e=!1;return"altKey"in t&&(e=e||t.altKey!==o.alt,o.alt=!!t.altKey),"shiftKey"in t&&(e=e||t.shiftKey!==o.shift,o.shift=!!t.shiftKey),"ctrlKey"in t&&(e=e||t.ctrlKey!==o.control,o.control=!!t.ctrlKey),"metaKey"in t&&(e=e||t.metaKey!==o.meta,o.meta=!!t.metaKey),e}function c(t,s){var c=n.x(s),u=n.y(s);"buttons"in s&&(t=0|s.buttons),(t!==r||c!==i||u!==a||l(s))&&(r=0|t,i=c||0,a=u||0,e&&e(r,i,a,o))}function u(t){c(0,t)}function h(){(r||i||a||o.shift||o.alt||o.meta||o.control)&&(i=a=0,r=0,o.shift=o.alt=o.control=o.meta=!1,e&&e(0,0,0,o))}function f(t){l(t)&&e&&e(r,i,a,o)}function p(t){0===n.buttons(t)?c(0,t):c(r,t)}function d(t){c(r|n.buttons(t),t)}function g(t){c(r&~n.buttons(t),t)}function v(){s||(s=!0,t.addEventListener("mousemove",p),t.addEventListener("mousedown",d),t.addEventListener("mouseup",g),t.addEventListener("mouseleave",u),t.addEventListener("mouseenter",u),t.addEventListener("mouseout",u),t.addEventListener("mouseover",u),t.addEventListener("blur",h),t.addEventListener("keyup",f),t.addEventListener("keydown",f),t.addEventListener("keypress",f),t!==window&&(window.addEventListener("blur",h),window.addEventListener("keyup",f),window.addEventListener("keydown",f),window.addEventListener("keypress",f)))}v();var m={element:t};return Object.defineProperties(m,{enabled:{get:function(){return s},set:function(e){e?v():s&&(s=!1,t.removeEventListener("mousemove",p),t.removeEventListener("mousedown",d),t.removeEventListener("mouseup",g),t.removeEventListener("mouseleave",u),t.removeEventListener("mouseenter",u),t.removeEventListener("mouseout",u),t.removeEventListener("mouseover",u),t.removeEventListener("blur",h),t.removeEventListener("keyup",f),t.removeEventListener("keydown",f),t.removeEventListener("keypress",f),t!==window&&(window.removeEventListener("blur",h),window.removeEventListener("keyup",f),window.removeEventListener("keydown",f),window.removeEventListener("keypress",f)))},enumerable:!0},buttons:{get:function(){return r},enumerable:!0},x:{get:function(){return i},enumerable:!0},y:{get:function(){return a},enumerable:!0},mods:{get:function(){return o},enumerable:!0}}),m};var n=t("mouse-event")},{"mouse-event":426}],425:[function(t,e,r){var n={left:0,top:0};e.exports=function(t,e,r){e=e||t.currentTarget||t.srcElement,Array.isArray(r)||(r=[0,0]);var i=t.clientX||0,a=t.clientY||0,o=(s=e,s===window||s===document||s===document.body?n:s.getBoundingClientRect());var s;return r[0]=i-o.left,r[1]=a-o.top,r}},{}],426:[function(t,e,r){"use strict";function n(t){return t.target||t.srcElement||window}r.buttons=function(t){if("object"==typeof t){if("buttons"in t)return t.buttons;if("which"in t){if(2===(e=t.which))return 4;if(3===e)return 2;if(e>0)return 1<<e-1}else if("button"in t){var e;if(1===(e=t.button))return 4;if(2===e)return 2;if(e>=0)return 1<<e}}return 0},r.element=n,r.x=function(t){if("object"==typeof t){if("offsetX"in t)return t.offsetX;var e=n(t).getBoundingClientRect();return t.clientX-e.left}return 0},r.y=function(t){if("object"==typeof t){if("offsetY"in t)return t.offsetY;var e=n(t).getBoundingClientRect();return t.clientY-e.top}return 0}},{}],427:[function(t,e,r){"use strict";var n=t("to-px");e.exports=function(t,e,r){"function"==typeof t&&(r=!!e,e=t,t=window);var i=n("ex",t),a=function(t){r&&t.preventDefault();var n=t.deltaX||0,a=t.deltaY||0,o=t.deltaZ||0,s=t.deltaMode,l=1;switch(s){case 1:l=i;break;case 2:l=window.innerHeight}if(a*=l,o*=l,(n*=l)||a||o)return e(n,a,o,t)};return t.addEventListener("wheel",a),a}},{"to-px":520}],428:[function(t,e,r){"use strict";var n=t("typedarray-pool");function i(t){return"a"+t}function a(t){return"d"+t}function o(t,e){return"c"+t+"_"+e}function s(t){return"s"+t}function l(t,e){return"t"+t+"_"+e}function c(t){return"o"+t}function u(t){return"x"+t}function h(t){return"p"+t}function f(t,e){return"d"+t+"_"+e}function p(t){return"i"+t}function d(t,e){return"u"+t+"_"+e}function g(t){return"b"+t}function v(t){return"y"+t}function m(t){return"e"+t}function y(t){return"v"+t}e.exports=function(t){function e(t){throw new Error("ndarray-extract-contour: "+t)}"object"!=typeof t&&e("Must specify arguments");var r=t.order;Array.isArray(r)||e("Must specify order");var T=t.arrayArguments||1;T<1&&e("Must have at least one array argument");var S=t.scalarArguments||0;S<0&&e("Scalar arg count must be > 0");"function"!=typeof t.vertex&&e("Must specify vertex creation function");"function"!=typeof t.cell&&e("Must specify cell creation function");"function"!=typeof t.phase&&e("Must specify phase function");for(var E=t.getters||[],C=new Array(T),L=0;L<T;++L)E.indexOf(L)>=0?C[L]=!0:C[L]=!1;return function(t,e,r,T,S,E){var C=E.length,L=S.length;if(L<2)throw new Error("ndarray-extract-contour: Dimension must be at least 2");for(var z="extractContour"+S.join("_"),O=[],I=[],D=[],P=0;P<C;++P)D.push(i(P));for(var P=0;P<T;++P)D.push(u(P));for(var P=0;P<L;++P)I.push(s(P)+"="+i(0)+".shape["+P+"]|0");for(var P=0;P<C;++P){I.push(a(P)+"="+i(P)+".data",c(P)+"="+i(P)+".offset|0");for(var R=0;R<L;++R)I.push(l(P,R)+"="+i(P)+".stride["+R+"]|0")}for(var P=0;P<C;++P){I.push(h(P)+"="+c(P)),I.push(o(P,0));for(var R=1;R<1<<L;++R){for(var F=[],B=0;B<L;++B)R&1<<B&&F.push("-"+l(P,B));I.push(f(P,R)+"=("+F.join("")+")|0"),I.push(o(P,R)+"=0")}}for(var P=0;P<C;++P)for(var R=0;R<L;++R){var N=[l(P,S[R])];R>0&&N.push(l(P,S[R-1])+"*"+s(S[R-1])),I.push(d(P,S[R])+"=("+N.join("-")+")|0")}for(var P=0;P<L;++P)I.push(p(P)+"=0");I.push(_+"=0");for(var j=["2"],P=L-2;P>=0;--P)j.push(s(S[P]));I.push(w+"=("+j.join("*")+")|0",b+"=mallocUint32("+w+")",x+"=mallocUint32("+w+")",k+"=0"),I.push(g(0)+"=0");for(var R=1;R<1<<L;++R){for(var V=[],U=[],B=0;B<L;++B)R&1<<B&&(0===U.length?V.push("1"):V.unshift(U.join("*"))),U.push(s(S[B]));var q="";V[0].indexOf(s(S[L-2]))<0&&(q="-");var H=M(L,R,S);I.push(m(H)+"=(-"+V.join("-")+")|0",v(H)+"=("+q+V.join("-")+")|0",g(H)+"=0")}function G(t,e){O.push("for(",p(S[t]),"=",e,";",p(S[t]),"<",s(S[t]),";","++",p(S[t]),"){")}function Y(t){for(var e=0;e<C;++e)O.push(h(e),"+=",d(e,S[t]),";");O.push("}")}function W(){for(var t=1;t<1<<L;++t)O.push(A,"=",m(t),";",m(t),"=",v(t),";",v(t),"=",A,";")}I.push(y(0)+"=0",A+"=0"),function t(e,r){if(e<0)return void function(t){for(var e=0;e<C;++e)E[e]?O.push(o(e,0),"=",a(e),".get(",h(e),");"):O.push(o(e,0),"=",a(e),"[",h(e),"];");for(var r=[],e=0;e<C;++e)r.push(o(e,0));for(var e=0;e<T;++e)r.push(u(e));O.push(g(0),"=",b,"[",k,"]=phase(",r.join(),");");for(var n=1;n<1<<L;++n)O.push(g(n),"=",b,"[",k,"+",m(n),"];");for(var i=[],n=1;n<1<<L;++n)i.push("("+g(0)+"!=="+g(n)+")");O.push("if(",i.join("||"),"){");for(var s=[],e=0;e<L;++e)s.push(p(e));for(var e=0;e<C;++e){s.push(o(e,0));for(var n=1;n<1<<L;++n)E[e]?O.push(o(e,n),"=",a(e),".get(",h(e),"+",f(e,n),");"):O.push(o(e,n),"=",a(e),"[",h(e),"+",f(e,n),"];"),s.push(o(e,n))}for(var e=0;e<1<<L;++e)s.push(g(e));for(var e=0;e<T;++e)s.push(u(e));O.push("vertex(",s.join(),");",y(0),"=",x,"[",k,"]=",_,"++;");for(var l=(1<<L)-1,c=g(l),n=0;n<L;++n)if(0==(t&~(1<<n))){for(var d=l^1<<n,v=g(d),w=[],A=d;A>0;A=A-1&d)w.push(x+"["+k+"+"+m(A)+"]");w.push(y(0));for(var A=0;A<C;++A)1&n?w.push(o(A,l),o(A,d)):w.push(o(A,d),o(A,l));1&n?w.push(c,v):w.push(v,c);for(var A=0;A<T;++A)w.push(u(A));O.push("if(",c,"!==",v,"){","face(",w.join(),")}")}O.push("}",k,"+=1;")}(r);!function(t){for(var e=t-1;e>=0;--e)G(e,0);for(var r=[],e=0;e<C;++e)E[e]?r.push(a(e)+".get("+h(e)+")"):r.push(a(e)+"["+h(e)+"]");for(var e=0;e<T;++e)r.push(u(e));O.push(b,"[",k,"++]=phase(",r.join(),");");for(var e=0;e<t;++e)Y(e);for(var n=0;n<C;++n)O.push(h(n),"+=",d(n,S[t]),";")}(e);O.push("if(",s(S[e]),">0){",p(S[e]),"=1;");t(e-1,r|1<<S[e]);for(var n=0;n<C;++n)O.push(h(n),"+=",d(n,S[e]),";");e===L-1&&(O.push(k,"=0;"),W());G(e,2);t(e-1,r);e===L-1&&(O.push("if(",p(S[L-1]),"&1){",k,"=0;}"),W());Y(e);O.push("}")}(L-1,0),O.push("freeUint32(",x,");freeUint32(",b,");");var X=["'use strict';","function ",z,"(",D.join(),"){","var ",I.join(),";",O.join(""),"}","return ",z].join("");return new Function("vertex","face","phase","mallocUint32","freeUint32",X)(t,e,r,n.mallocUint32,n.freeUint32)}(t.vertex,t.cell,t.phase,S,r,C)};var x="V",b="P",_="N",w="Q",k="X",A="T";function M(t,e,r){for(var n=0,i=0;i<t;++i)e&1<<i&&(n|=1<<r[i]);return n}},{"typedarray-pool":526}],429:[function(t,e,r){"use strict";var n=t("cwise/lib/wrapper")({args:["index","array","scalar"],pre:{body:"{}",args:[],thisVars:[],localVars:[]},body:{body:"{_inline_1_arg1_=_inline_1_arg2_.apply(void 0,_inline_1_arg0_)}",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg1_",lvalue:!0,rvalue:!1,count:1},{name:"_inline_1_arg2_",lvalue:!1,rvalue:!0,count:1}],thisVars:[],localVars:[]},post:{body:"{}",args:[],thisVars:[],localVars:[]},debug:!1,funcName:"cwise",blockSize:64});e.exports=function(t,e){return n(t,e),t}},{"cwise/lib/wrapper":137}],430:[function(t,e,r){"use strict";e.exports=function(t,e,r){if(Array.isArray(r)){if(r.length!==e.dimension)throw new Error("ndarray-gradient: invalid boundary conditions")}else r=n(e.dimension,"string"==typeof r?r:"clamp");if(t.dimension!==e.dimension+1)throw new Error("ndarray-gradient: output dimension must be +1 input dimension");if(t.shape[e.dimension]!==e.dimension)throw new Error("ndarray-gradient: output shape must match input shape");for(var i=0;i<e.dimension;++i)if(t.shape[i]!==e.shape[i])throw new Error("ndarray-gradient: shape mismatch");if(0===e.size)return t;if(e.dimension<=0)return t.set(0),t;return function(t){var e=t.join();if(m=o[e])return m;var r=t.length,n=["function gradient(dst,src){var s=src.shape.slice();"];function i(e){for(var i=r-e.length,a=[],o=[],s=[],l=0;l<r;++l)e.indexOf(l+1)>=0?s.push("0"):e.indexOf(-(l+1))>=0?s.push("s["+l+"]-1"):(s.push("-1"),a.push("1"),o.push("s["+l+"]-2"));var c=".lo("+a.join()+").hi("+o.join()+")";if(0===a.length&&(c=""),i>0){n.push("if(1");for(var l=0;l<r;++l)e.indexOf(l+1)>=0||e.indexOf(-(l+1))>=0||n.push("&&s[",l,"]>2");n.push("){grad",i,"(src.pick(",s.join(),")",c);for(var l=0;l<r;++l)e.indexOf(l+1)>=0||e.indexOf(-(l+1))>=0||n.push(",dst.pick(",s.join(),",",l,")",c);n.push(");")}for(var l=0;l<e.length;++l){var u=Math.abs(e[l])-1,h="dst.pick("+s.join()+","+u+")"+c;switch(t[u]){case"clamp":var f=s.slice(),p=s.slice();e[l]<0?f[u]="s["+u+"]-2":p[u]="1",0===i?n.push("if(s[",u,"]>1){dst.set(",s.join(),",",u,",0.5*(src.get(",f.join(),")-src.get(",p.join(),")))}else{dst.set(",s.join(),",",u,",0)};"):n.push("if(s[",u,"]>1){diff(",h,",src.pick(",f.join(),")",c,",src.pick(",p.join(),")",c,");}else{zero(",h,");};");break;case"mirror":0===i?n.push("dst.set(",s.join(),",",u,",0);"):n.push("zero(",h,");");break;case"wrap":var d=s.slice(),g=s.slice();e[l]<0?(d[u]="s["+u+"]-2",g[u]="0"):(d[u]="s["+u+"]-1",g[u]="1"),0===i?n.push("if(s[",u,"]>2){dst.set(",s.join(),",",u,",0.5*(src.get(",d.join(),")-src.get(",g.join(),")))}else{dst.set(",s.join(),",",u,",0)};"):n.push("if(s[",u,"]>2){diff(",h,",src.pick(",d.join(),")",c,",src.pick(",g.join(),")",c,");}else{zero(",h,");};");break;default:throw new Error("ndarray-gradient: Invalid boundary condition")}}i>0&&n.push("};")}for(var s=0;s<1<<r;++s){for(var h=[],f=0;f<r;++f)s&1<<f&&h.push(f+1);for(var p=0;p<1<<h.length;++p){for(var d=h.slice(),f=0;f<h.length;++f)p&1<<f&&(d[f]=-d[f]);i(d)}}n.push("return dst;};return gradient");for(var g=["diff","zero"],v=[l,c],s=1;s<=r;++s)g.push("grad"+s),v.push(u(s));g.push(n.join(""));var m=Function.apply(void 0,g).apply(void 0,v);return a[e]=m,m}(r)(t,e)};var n=t("dup"),i=t("cwise-compiler"),a={},o={},s={body:"",args:[],thisVars:[],localVars:[]},l=i({args:["array","array","array"],pre:s,post:s,body:{args:[{name:"out",lvalue:!0,rvalue:!1,count:1},{name:"left",lvalue:!1,rvalue:!0,count:1},{name:"right",lvalue:!1,rvalue:!0,count:1}],body:"out=0.5*(left-right)",thisVars:[],localVars:[]},funcName:"cdiff"}),c=i({args:["array"],pre:s,post:s,body:{args:[{name:"out",lvalue:!0,rvalue:!1,count:1}],body:"out=0",thisVars:[],localVars:[]},funcName:"zero"});function u(t){if(t in a)return a[t];for(var e=[],r=0;r<t;++r)e.push("out",r,"s=0.5*(inp",r,"l-inp",r,"r);");var o=["array"],l=["junk"];for(r=0;r<t;++r){o.push("array"),l.push("out"+r+"s");var c=n(t);c[r]=-1,o.push({array:0,offset:c.slice()}),c[r]=1,o.push({array:0,offset:c.slice()}),l.push("inp"+r+"l","inp"+r+"r")}return a[t]=i({args:o,pre:s,post:s,body:{body:e.join(""),args:l.map(function(t){return{name:t,lvalue:0===t.indexOf("out"),rvalue:0===t.indexOf("inp"),count:"junk"!==t|0}}),thisVars:[],localVars:[]},funcName:"fdTemplate"+t})}},{"cwise-compiler":134,dup:158}],431:[function(t,e,r){"use strict";var n=t("ndarray-warp"),i=t("gl-matrix-invert");e.exports=function(t,e,r){var a=e.dimension,o=i([],r);return n(t,e,function(t,e){for(var r=0;r<a;++r){t[r]=o[(a+1)*a+r];for(var n=0;n<a;++n)t[r]+=o[(a+1)*n+r]*e[n]}var i=o[(a+1)*(a+1)-1];for(n=0;n<a;++n)i+=o[(a+1)*n+a]*e[n];var s=1/i;for(r=0;r<a;++r)t[r]*=s;return t}),t}},{"gl-matrix-invert":270,"ndarray-warp":438}],432:[function(t,e,r){"use strict";function n(t,e){var r=Math.floor(e),n=e-r,i=0<=r&&r<t.shape[0],a=0<=r+1&&r+1<t.shape[0];return(1-n)*(i?+t.get(r):0)+n*(a?+t.get(r+1):0)}function i(t,e,r){var n=Math.floor(e),i=e-n,a=0<=n&&n<t.shape[0],o=0<=n+1&&n+1<t.shape[0],s=Math.floor(r),l=r-s,c=0<=s&&s<t.shape[1],u=0<=s+1&&s+1<t.shape[1],h=a&&c?t.get(n,s):0,f=a&&u?t.get(n,s+1):0;return(1-l)*((1-i)*h+i*(o&&c?t.get(n+1,s):0))+l*((1-i)*f+i*(o&&u?t.get(n+1,s+1):0))}function a(t,e,r,n){var i=Math.floor(e),a=e-i,o=0<=i&&i<t.shape[0],s=0<=i+1&&i+1<t.shape[0],l=Math.floor(r),c=r-l,u=0<=l&&l<t.shape[1],h=0<=l+1&&l+1<t.shape[1],f=Math.floor(n),p=n-f,d=0<=f&&f<t.shape[2],g=0<=f+1&&f+1<t.shape[2],v=o&&u&&d?t.get(i,l,f):0,m=o&&h&&d?t.get(i,l+1,f):0,y=s&&u&&d?t.get(i+1,l,f):0,x=s&&h&&d?t.get(i+1,l+1,f):0,b=o&&u&&g?t.get(i,l,f+1):0,_=o&&h&&g?t.get(i,l+1,f+1):0;return(1-p)*((1-c)*((1-a)*v+a*y)+c*((1-a)*m+a*x))+p*((1-c)*((1-a)*b+a*(s&&u&&g?t.get(i+1,l,f+1):0))+c*((1-a)*_+a*(s&&h&&g?t.get(i+1,l+1,f+1):0)))}e.exports=function(t,e,r,o){switch(t.shape.length){case 0:return 0;case 1:return n(t,e);case 2:return i(t,e,r);case 3:return a(t,e,r,o);default:return function(t){var e,r,n=0|t.shape.length,i=new Array(n),a=new Array(n),o=new Array(n),s=new Array(n);for(e=0;e<n;++e)r=+arguments[e+1],i[e]=Math.floor(r),a[e]=r-i[e],o[e]=0<=i[e]&&i[e]<t.shape[e],s[e]=0<=i[e]+1&&i[e]+1<t.shape[e];var l,c,u,h=0;t:for(e=0;e<1<<n;++e){for(c=1,u=t.offset,l=0;l<n;++l)if(e&1<<l){if(!s[l])continue t;c*=a[l],u+=t.stride[l]*(i[l]+1)}else{if(!o[l])continue t;c*=1-a[l],u+=t.stride[l]*i[l]}h+=c*t.data[u]}return h}.apply(void 0,arguments)}},e.exports.d1=n,e.exports.d2=i,e.exports.d3=a},{}],433:[function(t,e,r){"use strict";var n=t("cwise-compiler"),i={body:"",args:[],thisVars:[],localVars:[]};function a(t){if(!t)return i;for(var e=0;e<t.args.length;++e){var r=t.args[e];t.args[e]=0===e?{name:r,lvalue:!0,rvalue:!!t.rvalue,count:t.count||1}:{name:r,lvalue:!1,rvalue:!0,count:1}}return t.thisVars||(t.thisVars=[]),t.localVars||(t.localVars=[]),t}function o(t){for(var e=[],r=0;r<t.args.length;++r)e.push("a"+r);return new Function("P",["return function ",t.funcName,"_ndarrayops(",e.join(","),") {P(",e.join(","),");return a0}"].join(""))(function(t){return n({args:t.args,pre:a(t.pre),body:a(t.body),post:a(t.proc),funcName:t.funcName})}(t))}var s={add:"+",sub:"-",mul:"*",div:"/",mod:"%",band:"&",bor:"|",bxor:"^",lshift:"<<",rshift:">>",rrshift:">>>"};!function(){for(var t in s){var e=s[t];r[t]=o({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),r[t+"eq"]=o({args:["array","array"],body:{args:["a","b"],body:"a"+e+"=b"},rvalue:!0,funcName:t+"eq"}),r[t+"s"]=o({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),r[t+"seq"]=o({args:["array","scalar"],body:{args:["a","s"],body:"a"+e+"=s"},rvalue:!0,funcName:t+"seq"})}}();var l={not:"!",bnot:"~",neg:"-",recip:"1.0/"};!function(){for(var t in l){var e=l[t];r[t]=o({args:["array","array"],body:{args:["a","b"],body:"a="+e+"b"},funcName:t}),r[t+"eq"]=o({args:["array"],body:{args:["a"],body:"a="+e+"a"},rvalue:!0,count:2,funcName:t+"eq"})}}();var c={and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">="};!function(){for(var t in c){var e=c[t];r[t]=o({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),r[t+"s"]=o({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),r[t+"eq"]=o({args:["array","array"],body:{args:["a","b"],body:"a=a"+e+"b"},rvalue:!0,count:2,funcName:t+"eq"}),r[t+"seq"]=o({args:["array","scalar"],body:{args:["a","s"],body:"a=a"+e+"s"},rvalue:!0,count:2,funcName:t+"seq"})}}();var u=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan"];!function(){for(var t=0;t<u.length;++t){var e=u[t];r[e]=o({args:["array","array"],pre:{args:[],body:"this_f=Math."+e,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(b)",thisVars:["this_f"]},funcName:e}),r[e+"eq"]=o({args:["array"],pre:{args:[],body:"this_f=Math."+e,thisVars:["this_f"]},body:{args:["a"],body:"a=this_f(a)",thisVars:["this_f"]},rvalue:!0,count:2,funcName:e+"eq"})}}();var h=["max","min","atan2","pow"];!function(){for(var t=0;t<h.length;++t){var e=h[t];r[e]=o({args:["array","array","array"],pre:{args:[],body:"this_f=Math."+e,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(b,c)",thisVars:["this_f"]},funcName:e}),r[e+"s"]=o({args:["array","array","scalar"],pre:{args:[],body:"this_f=Math."+e,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(b,c)",thisVars:["this_f"]},funcName:e+"s"}),r[e+"eq"]=o({args:["array","array"],pre:{args:[],body:"this_f=Math."+e,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(a,b)",thisVars:["this_f"]},rvalue:!0,count:2,funcName:e+"eq"}),r[e+"seq"]=o({args:["array","scalar"],pre:{args:[],body:"this_f=Math."+e,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(a,b)",thisVars:["this_f"]},rvalue:!0,count:2,funcName:e+"seq"})}}();var f=["atan2","pow"];!function(){for(var t=0;t<f.length;++t){var e=f[t];r[e+"op"]=o({args:["array","array","array"],pre:{args:[],body:"this_f=Math."+e,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(c,b)",thisVars:["this_f"]},funcName:e+"op"}),r[e+"ops"]=o({args:["array","array","scalar"],pre:{args:[],body:"this_f=Math."+e,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(c,b)",thisVars:["this_f"]},funcName:e+"ops"}),r[e+"opeq"]=o({args:["array","array"],pre:{args:[],body:"this_f=Math."+e,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(b,a)",thisVars:["this_f"]},rvalue:!0,count:2,funcName:e+"opeq"}),r[e+"opseq"]=o({args:["array","scalar"],pre:{args:[],body:"this_f=Math."+e,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(b,a)",thisVars:["this_f"]},rvalue:!0,count:2,funcName:e+"opseq"})}}(),r.any=n({args:["array"],pre:i,body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:1}],body:"if(a){return true}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return false"},funcName:"any"}),r.all=n({args:["array"],pre:i,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1}],body:"if(!x){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"all"}),r.sum=n({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:1}],body:"this_s+=a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"sum"}),r.prod=n({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=1"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:1}],body:"this_s*=a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"prod"}),r.norm2squared=n({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:2}],body:"this_s+=a*a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norm2squared"}),r.norm2=n({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:2}],body:"this_s+=a*a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return Math.sqrt(this_s)"},funcName:"norm2"}),r.norminf=n({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:4}],body:"if(-a>this_s){this_s=-a}else if(a>this_s){this_s=a}",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norminf"}),r.norm1=n({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:3}],body:"this_s+=a<0?-a:a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norm1"}),r.sup=n({args:["array"],pre:{body:"this_h=-Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}}),r.inf=n({args:["array"],pre:{body:"this_h=Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_<this_h)this_h=_inline_1_arg0_",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}}),r.argmin=n({args:["index","array","shape"],pre:{body:"{this_v=Infinity;this_i=_inline_0_arg2_.slice(0)}",args:[{name:"_inline_0_arg0_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg1_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg2_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_i","this_v"],localVars:[]},body:{body:"{if(_inline_1_arg1_<this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}}),r.argmax=n({args:["index","array","shape"],pre:{body:"{this_v=-Infinity;this_i=_inline_0_arg2_.slice(0)}",args:[{name:"_inline_0_arg0_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg1_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg2_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_i","this_v"],localVars:[]},body:{body:"{if(_inline_1_arg1_>this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}}),r.random=o({args:["array"],pre:{args:[],body:"this_f=Math.random",thisVars:["this_f"]},body:{args:["a"],body:"a=this_f()",thisVars:["this_f"]},funcName:"random"}),r.assign=o({args:["array","array"],body:{args:["a","b"],body:"a=b"},funcName:"assign"}),r.assigns=o({args:["array","scalar"],body:{args:["a","b"],body:"a=b"},funcName:"assigns"}),r.equals=n({args:["array","array"],pre:i,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1},{name:"y",lvalue:!1,rvalue:!0,count:1}],body:"if(x!==y){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"equals"})},{"cwise-compiler":134}],434:[function(t,e,r){"use strict";var n=t("ndarray"),i=t("./doConvert.js");e.exports=function(t,e){for(var r=[],a=t,o=1;Array.isArray(a);)r.push(a.length),o*=a.length,a=a[0];return 0===r.length?n():(e||(e=n(new Float64Array(o),r)),i(e,t),e)}},{"./doConvert.js":435,ndarray:439}],435:[function(t,e,r){e.exports=t("cwise-compiler")({args:["array","scalar","index"],pre:{body:"{}",args:[],thisVars:[],localVars:[]},body:{body:"{\nvar _inline_1_v=_inline_1_arg1_,_inline_1_i\nfor(_inline_1_i=0;_inline_1_i<_inline_1_arg2_.length-1;++_inline_1_i) {\n_inline_1_v=_inline_1_v[_inline_1_arg2_[_inline_1_i]]\n}\n_inline_1_arg0_=_inline_1_v[_inline_1_arg2_[_inline_1_arg2_.length-1]]\n}",args:[{name:"_inline_1_arg0_",lvalue:!0,rvalue:!1,count:1},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg2_",lvalue:!1,rvalue:!0,count:4}],thisVars:[],localVars:["_inline_1_i","_inline_1_v"]},post:{body:"{}",args:[],thisVars:[],localVars:[]},funcName:"convert",blockSize:64})},{"cwise-compiler":134}],436:[function(t,e,r){"use strict";var n=t("typedarray-pool"),i=32;function a(t){switch(t){case"uint8":return[n.mallocUint8,n.freeUint8];case"uint16":return[n.mallocUint16,n.freeUint16];case"uint32":return[n.mallocUint32,n.freeUint32];case"int8":return[n.mallocInt8,n.freeInt8];case"int16":return[n.mallocInt16,n.freeInt16];case"int32":return[n.mallocInt32,n.freeInt32];case"float32":return[n.mallocFloat,n.freeFloat];case"float64":return[n.mallocDouble,n.freeDouble];default:return null}}function o(t){for(var e=[],r=0;r<t;++r)e.push("s"+r);for(r=0;r<t;++r)e.push("n"+r);for(r=1;r<t;++r)e.push("d"+r);for(r=1;r<t;++r)e.push("e"+r);for(r=1;r<t;++r)e.push("f"+r);return e}e.exports=function(t,e){var r=["'use strict'"],n=["ndarraySortWrapper",t.join("d"),e].join("");r.push(["function ",n,"(",["array"].join(","),"){"].join(""));for(var s=["data=array.data,offset=array.offset|0,shape=array.shape,stride=array.stride"],l=0;l<t.length;++l)s.push(["s",l,"=stride[",l,"]|0,n",l,"=shape[",l,"]|0"].join(""));var c=new Array(t.length),u=[];for(l=0;l<t.length;++l)0!==(p=t[l])&&(0===u.length?c[p]="1":c[p]=u.join("*"),u.push("n"+p));var h=-1,f=-1;for(l=0;l<t.length;++l){var p,d=t[l];0!==d&&(h>0?s.push(["d",d,"=s",d,"-d",h,"*n",h].join("")):s.push(["d",d,"=s",d].join("")),h=d),0!=(p=t.length-1-l)&&(f>0?s.push(["e",p,"=s",p,"-e",f,"*n",f,",f",p,"=",c[p],"-f",f,"*n",f].join("")):s.push(["e",p,"=s",p,",f",p,"=",c[p]].join("")),f=p)}r.push("var "+s.join(","));var g=["0","n0-1","data","offset"].concat(o(t.length));r.push(["if(n0<=",i,"){","insertionSort(",g.join(","),")}else{","quickSort(",g.join(","),")}"].join("")),r.push("}return "+n);var v=new Function("insertionSort","quickSort",r.join("\n")),m=function(t,e){var r=["'use strict'"],n=["ndarrayInsertionSort",t.join("d"),e].join(""),i=["left","right","data","offset"].concat(o(t.length)),s=a(e),l=["i,j,cptr,ptr=left*s0+offset"];if(t.length>1){for(var c=[],u=1;u<t.length;++u)l.push("i"+u),c.push("n"+u);s?l.push("scratch=malloc("+c.join("*")+")"):l.push("scratch=new Array("+c.join("*")+")"),l.push("dptr","sptr","a","b")}else l.push("scratch");function h(t){return"generic"===e?["data.get(",t,")"].join(""):["data[",t,"]"].join("")}function f(t,r){return"generic"===e?["data.set(",t,",",r,")"].join(""):["data[",t,"]=",r].join("")}if(r.push(["function ",n,"(",i.join(","),"){var ",l.join(",")].join(""),"for(i=left+1;i<=right;++i){","j=i;ptr+=s0","cptr=ptr"),t.length>1){for(r.push("dptr=0;sptr=ptr"),u=t.length-1;u>=0;--u)0!==(p=t[u])&&r.push(["for(i",p,"=0;i",p,"<n",p,";++i",p,"){"].join(""));for(r.push("scratch[dptr++]=",h("sptr")),u=0;u<t.length;++u)0!==(p=t[u])&&r.push("sptr+=d"+p,"}");for(r.push("__g:while(j--\x3eleft){","dptr=0","sptr=cptr-s0"),u=1;u<t.length;++u)1===u&&r.push("__l:"),r.push(["for(i",u,"=0;i",u,"<n",u,";++i",u,"){"].join(""));for(r.push(["a=",h("sptr"),"\nb=scratch[dptr]\nif(a<b){break __g}\nif(a>b){break __l}"].join("")),u=t.length-1;u>=1;--u)r.push("sptr+=e"+u,"dptr+=f"+u,"}");for(r.push("dptr=cptr;sptr=cptr-s0"),u=t.length-1;u>=0;--u)0!==(p=t[u])&&r.push(["for(i",p,"=0;i",p,"<n",p,";++i",p,"){"].join(""));for(r.push(f("dptr",h("sptr"))),u=0;u<t.length;++u)0!==(p=t[u])&&r.push(["dptr+=d",p,";sptr+=d",p].join(""),"}");for(r.push("cptr-=s0\n}"),r.push("dptr=cptr;sptr=0"),u=t.length-1;u>=0;--u)0!==(p=t[u])&&r.push(["for(i",p,"=0;i",p,"<n",p,";++i",p,"){"].join(""));for(r.push(f("dptr","scratch[sptr++]")),u=0;u<t.length;++u){var p;0!==(p=t[u])&&r.push("dptr+=d"+p,"}")}}else r.push("scratch="+h("ptr"),"while((j--\x3eleft)&&("+h("cptr-s0")+">scratch)){",f("cptr",h("cptr-s0")),"cptr-=s0","}",f("cptr","scratch"));return r.push("}"),t.length>1&&s&&r.push("free(scratch)"),r.push("} return "+n),s?new Function("malloc","free",r.join("\n"))(s[0],s[1]):new Function(r.join("\n"))()}(t,e),y=function(t,e,r){var n=["'use strict'"],s=["ndarrayQuickSort",t.join("d"),e].join(""),l=["left","right","data","offset"].concat(o(t.length)),c=a(e),u=0;n.push(["function ",s,"(",l.join(","),"){"].join(""));var h=["sixth=((right-left+1)/6)|0","index1=left+sixth","index5=right-sixth","index3=(left+right)>>1","index2=index3-sixth","index4=index3+sixth","el1=index1","el2=index2","el3=index3","el4=index4","el5=index5","less=left+1","great=right-1","pivots_are_equal=true","tmp","tmp0","x","y","z","k","ptr0","ptr1","ptr2","comp_pivot1=0","comp_pivot2=0","comp=0"];if(t.length>1){for(var f=[],p=1;p<t.length;++p)f.push("n"+p),h.push("i"+p);for(p=0;p<8;++p)h.push("b_ptr"+p);h.push("ptr3","ptr4","ptr5","ptr6","ptr7","pivot_ptr","ptr_shift","elementSize="+f.join("*")),c?h.push("pivot1=malloc(elementSize)","pivot2=malloc(elementSize)"):h.push("pivot1=new Array(elementSize),pivot2=new Array(elementSize)")}else h.push("pivot1","pivot2");function d(t){return["(offset+",t,"*s0)"].join("")}function g(t){return"generic"===e?["data.get(",t,")"].join(""):["data[",t,"]"].join("")}function v(t,r){return"generic"===e?["data.set(",t,",",r,")"].join(""):["data[",t,"]=",r].join("")}function m(e,r,i){if(1===e.length)n.push("ptr0="+d(e[0]));else for(var a=0;a<e.length;++a)n.push(["b_ptr",a,"=s0*",e[a]].join(""));for(r&&n.push("pivot_ptr=0"),n.push("ptr_shift=offset"),a=t.length-1;a>=0;--a)0!==(o=t[a])&&n.push(["for(i",o,"=0;i",o,"<n",o,";++i",o,"){"].join(""));if(e.length>1)for(a=0;a<e.length;++a)n.push(["ptr",a,"=b_ptr",a,"+ptr_shift"].join(""));for(n.push(i),r&&n.push("++pivot_ptr"),a=0;a<t.length;++a){var o;0!==(o=t[a])&&(e.length>1?n.push("ptr_shift+=d"+o):n.push("ptr0+=d"+o),n.push("}"))}}function y(e,r,i,a){if(1===r.length)n.push("ptr0="+d(r[0]));else{for(var o=0;o<r.length;++o)n.push(["b_ptr",o,"=s0*",r[o]].join(""));n.push("ptr_shift=offset")}for(i&&n.push("pivot_ptr=0"),e&&n.push(e+":"),o=1;o<t.length;++o)n.push(["for(i",o,"=0;i",o,"<n",o,";++i",o,"){"].join(""));if(r.length>1)for(o=0;o<r.length;++o)n.push(["ptr",o,"=b_ptr",o,"+ptr_shift"].join(""));for(n.push(a),o=t.length-1;o>=1;--o)i&&n.push("pivot_ptr+=f"+o),r.length>1?n.push("ptr_shift+=e"+o):n.push("ptr0+=e"+o),n.push("}")}function x(){t.length>1&&c&&n.push("free(pivot1)","free(pivot2)")}function b(e,r){var i="el"+e,a="el"+r;if(t.length>1){var o="__l"+ ++u;y(o,[i,a],!1,["comp=",g("ptr0"),"-",g("ptr1"),"\n","if(comp>0){tmp0=",i,";",i,"=",a,";",a,"=tmp0;break ",o,"}\n","if(comp<0){break ",o,"}"].join(""))}else n.push(["if(",g(d(i)),">",g(d(a)),"){tmp0=",i,";",i,"=",a,";",a,"=tmp0}"].join(""))}function _(e,r){t.length>1?m([e,r],!1,v("ptr0",g("ptr1"))):n.push(v(d(e),g(d(r))))}function w(e,r,i){if(t.length>1){var a="__l"+ ++u;y(a,[r],!0,[e,"=",g("ptr0"),"-pivot",i,"[pivot_ptr]\n","if(",e,"!==0){break ",a,"}"].join(""))}else n.push([e,"=",g(d(r)),"-pivot",i].join(""))}function k(e,r){t.length>1?m([e,r],!1,["tmp=",g("ptr0"),"\n",v("ptr0",g("ptr1")),"\n",v("ptr1","tmp")].join("")):n.push(["ptr0=",d(e),"\n","ptr1=",d(r),"\n","tmp=",g("ptr0"),"\n",v("ptr0",g("ptr1")),"\n",v("ptr1","tmp")].join(""))}function A(e,r,i){t.length>1?(m([e,r,i],!1,["tmp=",g("ptr0"),"\n",v("ptr0",g("ptr1")),"\n",v("ptr1",g("ptr2")),"\n",v("ptr2","tmp")].join("")),n.push("++"+r,"--"+i)):n.push(["ptr0=",d(e),"\n","ptr1=",d(r),"\n","ptr2=",d(i),"\n","++",r,"\n","--",i,"\n","tmp=",g("ptr0"),"\n",v("ptr0",g("ptr1")),"\n",v("ptr1",g("ptr2")),"\n",v("ptr2","tmp")].join(""))}function M(t,e){k(t,e),n.push("--"+e)}function T(e,r,i){t.length>1?m([e,r],!0,[v("ptr0",g("ptr1")),"\n",v("ptr1",["pivot",i,"[pivot_ptr]"].join(""))].join("")):n.push(v(d(e),g(d(r))),v(d(r),"pivot"+i))}function S(e,r){n.push(["if((",r,"-",e,")<=",i,"){\n","insertionSort(",e,",",r,",data,offset,",o(t.length).join(","),")\n","}else{\n",s,"(",e,",",r,",data,offset,",o(t.length).join(","),")\n","}"].join(""))}function E(e,r,i){t.length>1?(n.push(["__l",++u,":while(true){"].join("")),m([e],!0,["if(",g("ptr0"),"!==pivot",r,"[pivot_ptr]){break __l",u,"}"].join("")),n.push(i,"}")):n.push(["while(",g(d(e)),"===pivot",r,"){",i,"}"].join(""))}return n.push("var "+h.join(",")),b(1,2),b(4,5),b(1,3),b(2,3),b(1,4),b(3,4),b(2,5),b(2,3),b(4,5),t.length>1?m(["el1","el2","el3","el4","el5","index1","index3","index5"],!0,["pivot1[pivot_ptr]=",g("ptr1"),"\n","pivot2[pivot_ptr]=",g("ptr3"),"\n","pivots_are_equal=pivots_are_equal&&(pivot1[pivot_ptr]===pivot2[pivot_ptr])\n","x=",g("ptr0"),"\n","y=",g("ptr2"),"\n","z=",g("ptr4"),"\n",v("ptr5","x"),"\n",v("ptr6","y"),"\n",v("ptr7","z")].join("")):n.push(["pivot1=",g(d("el2")),"\n","pivot2=",g(d("el4")),"\n","pivots_are_equal=pivot1===pivot2\n","x=",g(d("el1")),"\n","y=",g(d("el3")),"\n","z=",g(d("el5")),"\n",v(d("index1"),"x"),"\n",v(d("index3"),"y"),"\n",v(d("index5"),"z")].join("")),_("index2","left"),_("index4","right"),n.push("if(pivots_are_equal){"),n.push("for(k=less;k<=great;++k){"),w("comp","k",1),n.push("if(comp===0){continue}"),n.push("if(comp<0){"),n.push("if(k!==less){"),k("k","less"),n.push("}"),n.push("++less"),n.push("}else{"),n.push("while(true){"),w("comp","great",1),n.push("if(comp>0){"),n.push("great--"),n.push("}else if(comp<0){"),A("k","less","great"),n.push("break"),n.push("}else{"),M("k","great"),n.push("break"),n.push("}"),n.push("}"),n.push("}"),n.push("}"),n.push("}else{"),n.push("for(k=less;k<=great;++k){"),w("comp_pivot1","k",1),n.push("if(comp_pivot1<0){"),n.push("if(k!==less){"),k("k","less"),n.push("}"),n.push("++less"),n.push("}else{"),w("comp_pivot2","k",2),n.push("if(comp_pivot2>0){"),n.push("while(true){"),w("comp","great",2),n.push("if(comp>0){"),n.push("if(--great<k){break}"),n.push("continue"),n.push("}else{"),w("comp","great",1),n.push("if(comp<0){"),A("k","less","great"),n.push("}else{"),M("k","great"),n.push("}"),n.push("break"),n.push("}"),n.push("}"),n.push("}"),n.push("}"),n.push("}"),n.push("}"),T("left","(less-1)",1),T("right","(great+1)",2),S("left","(less-2)"),S("(great+2)","right"),n.push("if(pivots_are_equal){"),x(),n.push("return"),n.push("}"),n.push("if(less<index1&&great>index5){"),E("less",1,"++less"),E("great",2,"--great"),n.push("for(k=less;k<=great;++k){"),w("comp_pivot1","k",1),n.push("if(comp_pivot1===0){"),n.push("if(k!==less){"),k("k","less"),n.push("}"),n.push("++less"),n.push("}else{"),w("comp_pivot2","k",2),n.push("if(comp_pivot2===0){"),n.push("while(true){"),w("comp","great",2),n.push("if(comp===0){"),n.push("if(--great<k){break}"),n.push("continue"),n.push("}else{"),w("comp","great",1),n.push("if(comp<0){"),A("k","less","great"),n.push("}else{"),M("k","great"),n.push("}"),n.push("break"),n.push("}"),n.push("}"),n.push("}"),n.push("}"),n.push("}"),n.push("}"),x(),S("less","great"),n.push("}return "+s),t.length>1&&c?new Function("insertionSort","malloc","free",n.join("\n"))(r,c[0],c[1]):new Function("insertionSort",n.join("\n"))(r)}(t,e,m);return v(m,y)}},{"typedarray-pool":526}],437:[function(t,e,r){"use strict";var n=t("./lib/compile_sort.js"),i={};e.exports=function(t){var e=t.order,r=t.dtype,a=[e,r].join(":"),o=i[a];return o||(i[a]=o=n(e,r)),o(t),t}},{"./lib/compile_sort.js":436}],438:[function(t,e,r){"use strict";var n=t("ndarray-linear-interpolate"),i=t("cwise/lib/wrapper")({args:["index","array","scalar","scalar","scalar"],pre:{body:"{this_warped=new Array(_inline_3_arg4_)}",args:[{name:"_inline_3_arg0_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_3_arg1_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_3_arg2_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_3_arg3_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_3_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_warped"],localVars:[]},body:{body:"{_inline_4_arg2_(this_warped,_inline_4_arg0_),_inline_4_arg1_=_inline_4_arg3_.apply(void 0,this_warped)}",args:[{name:"_inline_4_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_4_arg1_",lvalue:!0,rvalue:!1,count:1},{name:"_inline_4_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_4_arg3_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_4_arg4_",lvalue:!1,rvalue:!1,count:0}],thisVars:["this_warped"],localVars:[]},post:{body:"{}",args:[],thisVars:[],localVars:[]},debug:!1,funcName:"warpND",blockSize:64}),a=t("cwise/lib/wrapper")({args:["index","array","scalar","scalar","scalar"],pre:{body:"{this_warped=[0]}",args:[],thisVars:["this_warped"],localVars:[]},body:{body:"{_inline_7_arg2_(this_warped,_inline_7_arg0_),_inline_7_arg1_=_inline_7_arg3_(_inline_7_arg4_,this_warped[0])}",args:[{name:"_inline_7_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_7_arg1_",lvalue:!0,rvalue:!1,count:1},{name:"_inline_7_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_7_arg3_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_7_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_warped"],localVars:[]},post:{body:"{}",args:[],thisVars:[],localVars:[]},debug:!1,funcName:"warp1D",blockSize:64}),o=t("cwise/lib/wrapper")({args:["index","array","scalar","scalar","scalar"],pre:{body:"{this_warped=[0,0]}",args:[],thisVars:["this_warped"],localVars:[]},body:{body:"{_inline_10_arg2_(this_warped,_inline_10_arg0_),_inline_10_arg1_=_inline_10_arg3_(_inline_10_arg4_,this_warped[0],this_warped[1])}",args:[{name:"_inline_10_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_10_arg1_",lvalue:!0,rvalue:!1,count:1},{name:"_inline_10_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_10_arg3_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_10_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_warped"],localVars:[]},post:{body:"{}",args:[],thisVars:[],localVars:[]},debug:!1,funcName:"warp2D",blockSize:64}),s=t("cwise/lib/wrapper")({args:["index","array","scalar","scalar","scalar"],pre:{body:"{this_warped=[0,0,0]}",args:[],thisVars:["this_warped"],localVars:[]},body:{body:"{_inline_13_arg2_(this_warped,_inline_13_arg0_),_inline_13_arg1_=_inline_13_arg3_(_inline_13_arg4_,this_warped[0],this_warped[1],this_warped[2])}",args:[{name:"_inline_13_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_13_arg1_",lvalue:!0,rvalue:!1,count:1},{name:"_inline_13_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_13_arg3_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_13_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_warped"],localVars:[]},post:{body:"{}",args:[],thisVars:[],localVars:[]},debug:!1,funcName:"warp3D",blockSize:64});e.exports=function(t,e,r){switch(e.shape.length){case 1:a(t,r,n.d1,e);break;case 2:o(t,r,n.d2,e);break;case 3:s(t,r,n.d3,e);break;default:i(t,r,n.bind(void 0,e),e.shape.length)}return t}},{"cwise/lib/wrapper":137,"ndarray-linear-interpolate":432}],439:[function(t,e,r){var n=t("iota-array"),i=t("is-buffer"),a="undefined"!=typeof Float64Array;function o(t,e){return t[0]-e[0]}function s(){var t,e=this.stride,r=new Array(e.length);for(t=0;t<r.length;++t)r[t]=[Math.abs(e[t]),t];r.sort(o);var n=new Array(r.length);for(t=0;t<n.length;++t)n[t]=r[t][1];return n}function l(t,e){var r=["View",e,"d",t].join("");e<0&&(r="View_Nil"+t);var i="generic"===t;if(-1===e){var a="function "+r+"(a){this.data=a;};var proto="+r+".prototype;proto.dtype='"+t+"';proto.index=function(){return -1};proto.size=0;proto.dimension=-1;proto.shape=proto.stride=proto.order=[];proto.lo=proto.hi=proto.transpose=proto.step=function(){return new "+r+"(this.data);};proto.get=proto.set=function(){};proto.pick=function(){return null};return function construct_"+r+"(a){return new "+r+"(a);}";return new Function(a)()}if(0===e){a="function "+r+"(a,d) {this.data = a;this.offset = d};var proto="+r+".prototype;proto.dtype='"+t+"';proto.index=function(){return this.offset};proto.dimension=0;proto.size=1;proto.shape=proto.stride=proto.order=[];proto.lo=proto.hi=proto.transpose=proto.step=function "+r+"_copy() {return new "+r+"(this.data,this.offset)};proto.pick=function "+r+"_pick(){return TrivialArray(this.data);};proto.valueOf=proto.get=function "+r+"_get(){return "+(i?"this.data.get(this.offset)":"this.data[this.offset]")+"};proto.set=function "+r+"_set(v){return "+(i?"this.data.set(this.offset,v)":"this.data[this.offset]=v")+"};return function construct_"+r+"(a,b,c,d){return new "+r+"(a,d)}";return new Function("TrivialArray",a)(c[t][0])}a=["'use strict'"];var o=n(e),l=o.map(function(t){return"i"+t}),u="this.offset+"+o.map(function(t){return"this.stride["+t+"]*i"+t}).join("+"),h=o.map(function(t){return"b"+t}).join(","),f=o.map(function(t){return"c"+t}).join(",");a.push("function "+r+"(a,"+h+","+f+",d){this.data=a","this.shape=["+h+"]","this.stride=["+f+"]","this.offset=d|0}","var proto="+r+".prototype","proto.dtype='"+t+"'","proto.dimension="+e),a.push("Object.defineProperty(proto,'size',{get:function "+r+"_size(){return "+o.map(function(t){return"this.shape["+t+"]"}).join("*"),"}})"),1===e?a.push("proto.order=[0]"):(a.push("Object.defineProperty(proto,'order',{get:"),e<4?(a.push("function "+r+"_order(){"),2===e?a.push("return (Math.abs(this.stride[0])>Math.abs(this.stride[1]))?[1,0]:[0,1]}})"):3===e&&a.push("var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);if(s0>s1){if(s1>s2){return [2,1,0];}else if(s0>s2){return [1,2,0];}else{return [1,0,2];}}else if(s0>s2){return [2,0,1];}else if(s2>s1){return [0,1,2];}else{return [0,2,1];}}})")):a.push("ORDER})")),a.push("proto.set=function "+r+"_set("+l.join(",")+",v){"),i?a.push("return this.data.set("+u+",v)}"):a.push("return this.data["+u+"]=v}"),a.push("proto.get=function "+r+"_get("+l.join(",")+"){"),i?a.push("return this.data.get("+u+")}"):a.push("return this.data["+u+"]}"),a.push("proto.index=function "+r+"_index(",l.join(),"){return "+u+"}"),a.push("proto.hi=function "+r+"_hi("+l.join(",")+"){return new "+r+"(this.data,"+o.map(function(t){return["(typeof i",t,"!=='number'||i",t,"<0)?this.shape[",t,"]:i",t,"|0"].join("")}).join(",")+","+o.map(function(t){return"this.stride["+t+"]"}).join(",")+",this.offset)}");var p=o.map(function(t){return"a"+t+"=this.shape["+t+"]"}),d=o.map(function(t){return"c"+t+"=this.stride["+t+"]"});a.push("proto.lo=function "+r+"_lo("+l.join(",")+"){var b=this.offset,d=0,"+p.join(",")+","+d.join(","));for(var g=0;g<e;++g)a.push("if(typeof i"+g+"==='number'&&i"+g+">=0){d=i"+g+"|0;b+=c"+g+"*d;a"+g+"-=d}");a.push("return new "+r+"(this.data,"+o.map(function(t){return"a"+t}).join(",")+","+o.map(function(t){return"c"+t}).join(",")+",b)}"),a.push("proto.step=function "+r+"_step("+l.join(",")+"){var "+o.map(function(t){return"a"+t+"=this.shape["+t+"]"}).join(",")+","+o.map(function(t){return"b"+t+"=this.stride["+t+"]"}).join(",")+",c=this.offset,d=0,ceil=Math.ceil");for(g=0;g<e;++g)a.push("if(typeof i"+g+"==='number'){d=i"+g+"|0;if(d<0){c+=b"+g+"*(a"+g+"-1);a"+g+"=ceil(-a"+g+"/d)}else{a"+g+"=ceil(a"+g+"/d)}b"+g+"*=d}");a.push("return new "+r+"(this.data,"+o.map(function(t){return"a"+t}).join(",")+","+o.map(function(t){return"b"+t}).join(",")+",c)}");var v=new Array(e),m=new Array(e);for(g=0;g<e;++g)v[g]="a[i"+g+"]",m[g]="b[i"+g+"]";a.push("proto.transpose=function "+r+"_transpose("+l+"){"+l.map(function(t,e){return t+"=("+t+"===undefined?"+e+":"+t+"|0)"}).join(";"),"var a=this.shape,b=this.stride;return new "+r+"(this.data,"+v.join(",")+","+m.join(",")+",this.offset)}"),a.push("proto.pick=function "+r+"_pick("+l+"){var a=[],b=[],c=this.offset");for(g=0;g<e;++g)a.push("if(typeof i"+g+"==='number'&&i"+g+">=0){c=(c+this.stride["+g+"]*i"+g+")|0}else{a.push(this.shape["+g+"]);b.push(this.stride["+g+"])}");return a.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}"),a.push("return function construct_"+r+"(data,shape,stride,offset){return new "+r+"(data,"+o.map(function(t){return"shape["+t+"]"}).join(",")+","+o.map(function(t){return"stride["+t+"]"}).join(",")+",offset)}"),new Function("CTOR_LIST","ORDER",a.join("\n"))(c[t],s)}var c={float32:[],float64:[],int8:[],int16:[],int32:[],uint8:[],uint16:[],uint32:[],array:[],uint8_clamped:[],buffer:[],generic:[]};e.exports=function(t,e,r,n){if(void 0===t)return(0,c.array[0])([]);"number"==typeof t&&(t=[t]),void 0===e&&(e=[t.length]);var o=e.length;if(void 0===r){r=new Array(o);for(var s=o-1,u=1;s>=0;--s)r[s]=u,u*=e[s]}if(void 0===n)for(n=0,s=0;s<o;++s)r[s]<0&&(n-=(e[s]-1)*r[s]);for(var h=function(t){if(i(t))return"buffer";if(a)switch(Object.prototype.toString.call(t)){case"[object Float64Array]":return"float64";case"[object Float32Array]":return"float32";case"[object Int8Array]":return"int8";case"[object Int16Array]":return"int16";case"[object Int32Array]":return"int32";case"[object Uint8Array]":return"uint8";case"[object Uint16Array]":return"uint16";case"[object Uint32Array]":return"uint32";case"[object Uint8ClampedArray]":return"uint8_clamped"}return Array.isArray(t)?"array":"generic"}(t),f=c[h];f.length<=o+1;)f.push(l(h,f.length-1));return(0,f[o+1])(t,e,r,n)}},{"iota-array":405,"is-buffer":407}],440:[function(t,e,r){"use strict";var n=t("double-bits"),i=Math.pow(2,-1074),a=-1>>>0;e.exports=function(t,e){if(isNaN(t)||isNaN(e))return NaN;if(t===e)return t;if(0===t)return e<0?-i:i;var r=n.hi(t),o=n.lo(t);e>t==t>0?o===a?(r+=1,o=0):o+=1:0===o?(o=a,r-=1):o-=1;return n.pack(o,r)}},{"double-bits":155}],441:[function(t,e,r){var n=Math.PI,i=c(120);function a(t,e,r,n){return["C",t,e,r,n,r,n]}function o(t,e,r,n,i,a){return["C",t/3+2/3*r,e/3+2/3*n,i/3+2/3*r,a/3+2/3*n,i,a]}function s(t,e,r,a,o,c,u,h,f,p){if(p)k=p[0],A=p[1],_=p[2],w=p[3];else{var d=l(t,e,-o);t=d.x,e=d.y;var g=(t-(h=(d=l(h,f,-o)).x))/2,v=(e-(f=d.y))/2,m=g*g/(r*r)+v*v/(a*a);m>1&&(r*=m=Math.sqrt(m),a*=m);var y=r*r,x=a*a,b=(c==u?-1:1)*Math.sqrt(Math.abs((y*x-y*v*v-x*g*g)/(y*v*v+x*g*g)));b==1/0&&(b=1);var _=b*r*v/a+(t+h)/2,w=b*-a*g/r+(e+f)/2,k=Math.asin(((e-w)/a).toFixed(9)),A=Math.asin(((f-w)/a).toFixed(9));(k=t<_?n-k:k)<0&&(k=2*n+k),(A=h<_?n-A:A)<0&&(A=2*n+A),u&&k>A&&(k-=2*n),!u&&A>k&&(A-=2*n)}if(Math.abs(A-k)>i){var M=A,T=h,S=f;A=k+i*(u&&A>k?1:-1);var E=s(h=_+r*Math.cos(A),f=w+a*Math.sin(A),r,a,o,0,u,T,S,[A,M,_,w])}var C=Math.tan((A-k)/4),L=4/3*r*C,z=4/3*a*C,O=[2*t-(t+L*Math.sin(k)),2*e-(e-z*Math.cos(k)),h+L*Math.sin(A),f-z*Math.cos(A),h,f];if(p)return O;E&&(O=O.concat(E));for(var I=0;I<O.length;){var D=l(O[I],O[I+1],o);O[I++]=D.x,O[I++]=D.y}return O}function l(t,e,r){return{x:t*Math.cos(r)-e*Math.sin(r),y:t*Math.sin(r)+e*Math.cos(r)}}function c(t){return t*(n/180)}e.exports=function(t){for(var e,r=[],n=0,i=0,l=0,u=0,h=null,f=null,p=0,d=0,g=0,v=t.length;g<v;g++){var m=t[g],y=m[0];switch(y){case"M":l=m[1],u=m[2];break;case"A":(m=s(p,d,m[1],m[2],c(m[3]),m[4],m[5],m[6],m[7])).unshift("C"),m.length>7&&(r.push(m.splice(0,7)),m.unshift("C"));break;case"S":var x=p,b=d;"C"!=e&&"S"!=e||(x+=x-n,b+=b-i),m=["C",x,b,m[1],m[2],m[3],m[4]];break;case"T":"Q"==e||"T"==e?(h=2*p-h,f=2*d-f):(h=p,f=d),m=o(p,d,h,f,m[1],m[2]);break;case"Q":h=m[1],f=m[2],m=o(p,d,m[1],m[2],m[3],m[4]);break;case"L":m=a(p,d,m[1],m[2]);break;case"H":m=a(p,d,m[1],d);break;case"V":m=a(p,d,p,m[1]);break;case"Z":m=a(p,d,l,u)}e=y,p=m[m.length-2],d=m[m.length-1],m.length>4?(n=m[m.length-4],i=m[m.length-3]):(n=p,i=d),r.push(m)}return r}},{}],442:[function(t,e,r){r.vertexNormals=function(t,e,r){for(var n=e.length,i=new Array(n),a=void 0===r?1e-6:r,o=0;o<n;++o)i[o]=[0,0,0];for(o=0;o<t.length;++o)for(var s=t[o],l=0,c=s[s.length-1],u=s[0],h=0;h<s.length;++h){l=c,c=u,u=s[(h+1)%s.length];for(var f=e[l],p=e[c],d=e[u],g=new Array(3),v=0,m=new Array(3),y=0,x=0;x<3;++x)g[x]=f[x]-p[x],v+=g[x]*g[x],m[x]=d[x]-p[x],y+=m[x]*m[x];if(v*y>a){var b=i[c],_=1/Math.sqrt(v*y);for(x=0;x<3;++x){var w=(x+1)%3,k=(x+2)%3;b[x]+=_*(m[w]*g[k]-m[k]*g[w])}}}for(o=0;o<n;++o){b=i[o];var A=0;for(x=0;x<3;++x)A+=b[x]*b[x];if(A>a)for(_=1/Math.sqrt(A),x=0;x<3;++x)b[x]*=_;else for(x=0;x<3;++x)b[x]=0}return i},r.faceNormals=function(t,e,r){for(var n=t.length,i=new Array(n),a=void 0===r?1e-6:r,o=0;o<n;++o){for(var s=t[o],l=new Array(3),c=0;c<3;++c)l[c]=e[s[c]];var u=new Array(3),h=new Array(3);for(c=0;c<3;++c)u[c]=l[1][c]-l[0][c],h[c]=l[2][c]-l[0][c];var f=new Array(3),p=0;for(c=0;c<3;++c){var d=(c+1)%3,g=(c+2)%3;f[c]=u[d]*h[g]-u[g]*h[d],p+=f[c]*f[c]}p=p>a?1/Math.sqrt(p):0;for(c=0;c<3;++c)f[c]*=p;i[o]=f}return i}},{}],443:[function(t,e,r){"use strict";var n=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable;e.exports=function(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de","5"===Object.getOwnPropertyNames(t)[0])return!1;for(var e={},r=0;r<10;r++)e["_"+String.fromCharCode(r)]=r;if("0123456789"!==Object.getOwnPropertyNames(e).map(function(t){return e[t]}).join(""))return!1;var n={};return"abcdefghijklmnopqrst".split("").forEach(function(t){n[t]=t}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},n)).join("")}catch(t){return!1}}()?Object.assign:function(t,e){for(var r,o,s=function(t){if(null==t)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}(t),l=1;l<arguments.length;l++){for(var c in r=Object(arguments[l]))i.call(r,c)&&(s[c]=r[c]);if(n){o=n(r);for(var u=0;u<o.length;u++)a.call(r,o[u])&&(s[o[u]]=r[o[u]])}}return s}},{}],444:[function(t,e,r){"use strict";e.exports=function(t,e,r,n,i,a,o,s,l,c){var u=e+a+c;if(h>0){var h=Math.sqrt(u+1);t[0]=.5*(o-l)/h,t[1]=.5*(s-n)/h,t[2]=.5*(r-a)/h,t[3]=.5*h}else{var f=Math.max(e,a,c),h=Math.sqrt(2*f-u+1);e>=f?(t[0]=.5*h,t[1]=.5*(i+r)/h,t[2]=.5*(s+n)/h,t[3]=.5*(o-l)/h):a>=f?(t[0]=.5*(r+i)/h,t[1]=.5*h,t[2]=.5*(l+o)/h,t[3]=.5*(s-n)/h):(t[0]=.5*(n+s)/h,t[1]=.5*(o+l)/h,t[2]=.5*h,t[3]=.5*(r-i)/h)}return t}},{}],445:[function(t,e,r){"use strict";e.exports=function(t){var e=(t=t||{}).center||[0,0,0],r=t.rotation||[0,0,0,1],n=t.radius||1;e=[].slice.call(e,0,3),u(r=[].slice.call(r,0,4),r);var i=new h(r,e,Math.log(n));i.setDistanceLimits(t.zoomMin,t.zoomMax),("eye"in t||"up"in t)&&i.lookAt(0,t.eye,t.center,t.up);return i};var n=t("filtered-vector"),i=t("gl-mat4/lookAt"),a=t("gl-mat4/fromQuat"),o=t("gl-mat4/invert"),s=t("./lib/quatFromFrame");function l(t,e,r){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2))}function c(t,e,r,n){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2)+Math.pow(n,2))}function u(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=c(r,n,i,a);o>1e-6?(t[0]=r/o,t[1]=n/o,t[2]=i/o,t[3]=a/o):(t[0]=t[1]=t[2]=0,t[3]=1)}function h(t,e,r){this.radius=n([r]),this.center=n(e),this.rotation=n(t),this.computedRadius=this.radius.curve(0),this.computedCenter=this.center.curve(0),this.computedRotation=this.rotation.curve(0),this.computedUp=[.1,0,0],this.computedEye=[.1,0,0],this.computedMatrix=[.1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.recalcMatrix(0)}var f=h.prototype;f.lastT=function(){return Math.max(this.radius.lastT(),this.center.lastT(),this.rotation.lastT())},f.recalcMatrix=function(t){this.radius.curve(t),this.center.curve(t),this.rotation.curve(t);var e=this.computedRotation;u(e,e);var r=this.computedMatrix;a(r,e);var n=this.computedCenter,i=this.computedEye,o=this.computedUp,s=Math.exp(this.computedRadius[0]);i[0]=n[0]+s*r[2],i[1]=n[1]+s*r[6],i[2]=n[2]+s*r[10],o[0]=r[1],o[1]=r[5],o[2]=r[9];for(var l=0;l<3;++l){for(var c=0,h=0;h<3;++h)c+=r[l+4*h]*i[h];r[12+l]=-c}},f.getMatrix=function(t,e){this.recalcMatrix(t);var r=this.computedMatrix;if(e){for(var n=0;n<16;++n)e[n]=r[n];return e}return r},f.idle=function(t){this.center.idle(t),this.radius.idle(t),this.rotation.idle(t)},f.flush=function(t){this.center.flush(t),this.radius.flush(t),this.rotation.flush(t)},f.pan=function(t,e,r,n){e=e||0,r=r||0,n=n||0,this.recalcMatrix(t);var i=this.computedMatrix,a=i[1],o=i[5],s=i[9],c=l(a,o,s);a/=c,o/=c,s/=c;var u=i[0],h=i[4],f=i[8],p=u*a+h*o+f*s,d=l(u-=a*p,h-=o*p,f-=s*p);u/=d,h/=d,f/=d;var g=i[2],v=i[6],m=i[10],y=g*a+v*o+m*s,x=g*u+v*h+m*f,b=l(g-=y*a+x*u,v-=y*o+x*h,m-=y*s+x*f);g/=b,v/=b,m/=b;var _=u*e+a*r,w=h*e+o*r,k=f*e+s*r;this.center.move(t,_,w,k);var A=Math.exp(this.computedRadius[0]);A=Math.max(1e-4,A+n),this.radius.set(t,Math.log(A))},f.rotate=function(t,e,r,n){this.recalcMatrix(t),e=e||0,r=r||0;var i=this.computedMatrix,a=i[0],o=i[4],s=i[8],u=i[1],h=i[5],f=i[9],p=i[2],d=i[6],g=i[10],v=e*a+r*u,m=e*o+r*h,y=e*s+r*f,x=-(d*y-g*m),b=-(g*v-p*y),_=-(p*m-d*v),w=Math.sqrt(Math.max(0,1-Math.pow(x,2)-Math.pow(b,2)-Math.pow(_,2))),k=c(x,b,_,w);k>1e-6?(x/=k,b/=k,_/=k,w/=k):(x=b=_=0,w=1);var A=this.computedRotation,M=A[0],T=A[1],S=A[2],E=A[3],C=M*w+E*x+T*_-S*b,L=T*w+E*b+S*x-M*_,z=S*w+E*_+M*b-T*x,O=E*w-M*x-T*b-S*_;if(n){x=p,b=d,_=g;var I=Math.sin(n)/l(x,b,_);x*=I,b*=I,_*=I,O=O*(w=Math.cos(e))-(C=C*w+O*x+L*_-z*b)*x-(L=L*w+O*b+z*x-C*_)*b-(z=z*w+O*_+C*b-L*x)*_}var D=c(C,L,z,O);D>1e-6?(C/=D,L/=D,z/=D,O/=D):(C=L=z=0,O=1),this.rotation.set(t,C,L,z,O)},f.lookAt=function(t,e,r,n){this.recalcMatrix(t),r=r||this.computedCenter,e=e||this.computedEye,n=n||this.computedUp;var a=this.computedMatrix;i(a,e,r,n);var o=this.computedRotation;s(o,a[0],a[1],a[2],a[4],a[5],a[6],a[8],a[9],a[10]),u(o,o),this.rotation.set(t,o[0],o[1],o[2],o[3]);for(var l=0,c=0;c<3;++c)l+=Math.pow(r[c]-e[c],2);this.radius.set(t,.5*Math.log(Math.max(l,1e-6))),this.center.set(t,r[0],r[1],r[2])},f.translate=function(t,e,r,n){this.center.move(t,e||0,r||0,n||0)},f.setMatrix=function(t,e){var r=this.computedRotation;s(r,e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]),u(r,r),this.rotation.set(t,r[0],r[1],r[2],r[3]);var n=this.computedMatrix;o(n,e);var i=n[15];if(Math.abs(i)>1e-6){var a=n[12]/i,l=n[13]/i,c=n[14]/i;this.recalcMatrix(t);var h=Math.exp(this.computedRadius[0]);this.center.set(t,a-n[2]*h,l-n[6]*h,c-n[10]*h),this.radius.idle(t)}else this.center.idle(t),this.radius.idle(t)},f.setDistance=function(t,e){e>0&&this.radius.set(t,Math.log(e))},f.setDistanceLimits=function(t,e){t=t>0?Math.log(t):-1/0,e=e>0?Math.log(e):1/0,e=Math.max(e,t),this.radius.bounds[0][0]=t,this.radius.bounds[1][0]=e},f.getDistanceLimits=function(t){var e=this.radius.bounds;return t?(t[0]=Math.exp(e[0][0]),t[1]=Math.exp(e[1][0]),t):[Math.exp(e[0][0]),Math.exp(e[1][0])]},f.toJSON=function(){return this.recalcMatrix(this.lastT()),{center:this.computedCenter.slice(),rotation:this.computedRotation.slice(),distance:Math.log(this.computedRadius[0]),zoomMin:this.radius.bounds[0][0],zoomMax:this.radius.bounds[1][0]}},f.fromJSON=function(t){var e=this.lastT(),r=t.center;r&&this.center.set(e,r[0],r[1],r[2]);var n=t.rotation;n&&this.rotation.set(e,n[0],n[1],n[2],n[3]);var i=t.distance;i&&i>0&&this.radius.set(e,Math.log(i)),this.setDistanceLimits(t.zoomMin,t.zoomMax)}},{"./lib/quatFromFrame":444,"filtered-vector":219,"gl-mat4/fromQuat":255,"gl-mat4/invert":258,"gl-mat4/lookAt":259}],446:[function(t,e,r){"use strict";var n=t("repeat-string");e.exports=function(t,e,r){return n(r="undefined"!=typeof r?r+"":" ",e)+t}},{"repeat-string":484}],447:[function(t,e,r){"use strict";function n(t,e){if("string"!=typeof t)return[t];var r=[t];"string"==typeof e||Array.isArray(e)?e={brackets:e}:e||(e={});var n=e.brackets?Array.isArray(e.brackets)?e.brackets:[e.brackets]:["{}","[]","()"],i=e.escape||"___",a=!!e.flat;n.forEach(function(t){var e=new RegExp(["\\",t[0],"[^\\",t[0],"\\",t[1],"]*\\",t[1]].join("")),n=[];function a(e,a,o){var s=r.push(e.slice(t[0].length,-t[1].length))-1;return n.push(s),i+s}r.forEach(function(t,n){for(var i,o=0;t!=i;)if(i=t,t=t.replace(e,a),o++>1e4)throw Error("References have circular dependency. Please, check them.");r[n]=t}),n=n.reverse(),r=r.map(function(e){return n.forEach(function(r){e=e.replace(new RegExp("(\\"+i+r+"(?![0-9]))","g"),t[0]+"$1"+t[1])}),e})});var o=new RegExp("\\"+i+"([0-9]+)");return a?r:function t(e,r,n){for(var i,a=[],s=0;i=o.exec(e);){if(s++>1e4)throw Error("Circular references in parenthesis");a.push(e.slice(0,i.index)),a.push(t(r[i[1]],r)),e=e.slice(i.index+i[0].length)}return a.push(e),a}(r[0],r)}function i(t,e){if(e&&e.flat){var r,n=e&&e.escape||"___",i=t[0];if(!i)return"";for(var a=new RegExp("\\"+n+"([0-9]+)"),o=0;i!=r;){if(o++>1e4)throw Error("Circular references in "+t);r=i,i=i.replace(a,s)}return i}return t.reduce(function t(e,r){return Array.isArray(r)&&(r=r.reduce(t,"")),e+r},"");function s(e,r){if(null==t[r])throw Error("Reference "+r+"is undefined");return t[r]}}function a(t,e){return Array.isArray(t)?i(t,e):n(t,e)}a.parse=n,a.stringify=i,e.exports=a},{}],448:[function(t,e,r){"use strict";var n=t("pick-by-alias");e.exports=function(t){var e;arguments.length>1&&(t=arguments);"string"==typeof t?t=t.split(/\s/).map(parseFloat):"number"==typeof t&&(t=[t]);t.length&&"number"==typeof t[0]?e=1===t.length?{width:t[0],height:t[0],x:0,y:0}:2===t.length?{width:t[0],height:t[1],x:0,y:0}:{x:t[0],y:t[1],width:t[2]-t[0]||0,height:t[3]-t[1]||0}:t&&(t=n(t,{left:"x l left Left",top:"y t top Top",width:"w width W Width",height:"h height W Width",bottom:"b bottom Bottom",right:"r right Right"}),e={x:t.left||0,y:t.top||0},null==t.width?t.right?e.width=t.right-e.x:e.width=0:e.width=t.width,null==t.height?t.bottom?e.height=t.bottom-e.y:e.height=0:e.height=t.height);return e}},{"pick-by-alias":454}],449:[function(t,e,r){e.exports=function(t){var e=[];return t.replace(i,function(t,r,i){var o=r.toLowerCase();for(i=function(t){var e=t.match(a);return e?e.map(Number):[]}(i),"m"==o&&i.length>2&&(e.push([r].concat(i.splice(0,2))),o="l",r="m"==r?"l":"L");;){if(i.length==n[o])return i.unshift(r),e.push(i);if(i.length<n[o])throw new Error("malformed path data");e.push([r].concat(i.splice(0,n[o])))}}),e};var n={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},i=/([astvzqmhlc])([^astvzqmhlc]*)/gi;var a=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/gi},{}],450:[function(t,e,r){e.exports=function(t,e){e||(e=[0,""]),t=String(t);var r=parseFloat(t,10);return e[0]=r,e[1]=t.match(/[\d.\-\+]*\s*(.*)/)[1]||"",e}},{}],451:[function(t,e,r){(function(t){(function(){var r,n,i,a,o,s;"undefined"!=typeof performance&&null!==performance&&performance.now?e.exports=function(){return performance.now()}:"undefined"!=typeof t&&null!==t&&t.hrtime?(e.exports=function(){return(r()-o)/1e6},n=t.hrtime,a=(r=function(){var t;return 1e9*(t=n())[0]+t[1]})(),s=1e9*t.uptime(),o=a-s):Date.now?(e.exports=function(){return Date.now()-i},i=Date.now()):(e.exports=function(){return(new Date).getTime()-i},i=(new Date).getTime())}).call(this)}).call(this,t("_process"))},{_process:471}],452:[function(t,e,r){"use strict";e.exports=function(t){var e=t.length;if(e<n){for(var r=1,a=0;a<e;++a)for(var o=0;o<a;++o)if(t[a]<t[o])r=-r;else if(t[a]===t[o])return 0;return r}for(var s=i.mallocUint8(e),a=0;a<e;++a)s[a]=0;for(var r=1,a=0;a<e;++a)if(!s[a]){var l=1;s[a]=1;for(var o=t[a];o!==a;o=t[o]){if(s[o])return i.freeUint8(s),0;l+=1,s[o]=1}1&l||(r=-r)}return i.freeUint8(s),r};var n=32,i=t("typedarray-pool")},{"typedarray-pool":526}],453:[function(t,e,r){"use strict";var n=t("typedarray-pool"),i=t("invert-permutation");r.rank=function(t){var e=t.length;switch(e){case 0:case 1:return 0;case 2:return t[1]}var r,a,o,s=n.mallocUint32(e),l=n.mallocUint32(e),c=0;for(i(t,l),o=0;o<e;++o)s[o]=t[o];for(o=e-1;o>0;--o)a=l[o],r=s[o],s[o]=s[a],s[a]=r,l[o]=l[r],l[r]=a,c=(c+r)*o;return n.freeUint32(l),n.freeUint32(s),c},r.unrank=function(t,e,r){switch(t){case 0:return r||[];case 1:return r?(r[0]=0,r):[0];case 2:return r?(e?(r[0]=0,r[1]=1):(r[0]=1,r[1]=0),r):e?[0,1]:[1,0]}var n,i,a,o=1;for((r=r||new Array(t))[0]=0,a=1;a<t;++a)r[a]=a,o=o*a|0;for(a=t-1;a>0;--a)e=e-(n=e/o|0)*o|0,o=o/a|0,i=0|r[a],r[a]=0|r[n],r[n]=0|i;return r}},{"invert-permutation":404,"typedarray-pool":526}],454:[function(t,e,r){"use strict";e.exports=function(t,e,r){var n,a,o={};if("string"==typeof e&&(e=i(e)),Array.isArray(e)){var s={};for(a=0;a<e.length;a++)s[e[a]]=!0;e=s}for(n in e)e[n]=i(e[n]);var l={};for(n in e){var c=e[n];if(Array.isArray(c))for(a=0;a<c.length;a++){var u=c[a];if(r&&(l[u]=!0),u in t){if(o[n]=t[u],r)for(var h=a;h<c.length;h++)l[c[h]]=!0;break}}else n in t&&(e[n]&&(o[n]=t[n]),r&&(l[n]=!0))}if(r)for(n in t)l[n]||(o[n]=t[n]);return o};var n={};function i(t){return n[t]?n[t]:("string"==typeof t&&(t=n[t]=t.split(/\s*,\s*|\s+/)),t)}},{}],455:[function(t,e,r){"use strict";e.exports=function(t,e){for(var r=0|e.length,i=t.length,a=[new Array(r),new Array(r)],o=0;o<r;++o)a[0][o]=[],a[1][o]=[];for(var o=0;o<i;++o){var s=t[o];a[0][s[0]].push(s),a[1][s[1]].push(s)}for(var l=[],o=0;o<r;++o)a[0][o].length+a[1][o].length===0&&l.push([o]);function c(t,e){var r=a[e][t[e]];r.splice(r.indexOf(t),1)}function u(t,r,i){for(var o,s,l,u=0;u<2;++u)if(a[u][r].length>0){o=a[u][r][0],l=u;break}s=o[1^l];for(var h=0;h<2;++h)for(var f=a[h][r],p=0;p<f.length;++p){var d=f[p],g=d[1^h],v=n(e[t],e[r],e[s],e[g]);v>0&&(o=d,s=g,l=h)}return i?s:(o&&c(o,l),s)}function h(t,r){var i=a[r][t][0],o=[t];c(i,r);for(var s=i[1^r];;){for(;s!==t;)o.push(s),s=u(o[o.length-2],s,!1);if(a[0][t].length+a[1][t].length===0)break;var l=o[o.length-1],h=t,f=o[1],p=u(l,h,!0);if(n(e[l],e[h],e[f],e[p])<0)break;o.push(t),s=u(l,h)}return o}function f(t,e){return e[1]===e[e.length-1]}for(var o=0;o<r;++o)for(var p=0;p<2;++p){for(var d=[];a[p][o].length>0;){a[0][o].length;var g=h(o,p);f(d,g)?d.push.apply(d,g):(d.length>0&&l.push(d),d=g)}d.length>0&&l.push(d)}return l};var n=t("compare-angle")},{"compare-angle":115}],456:[function(t,e,r){"use strict";e.exports=function(t,e){for(var r=n(t,e.length),i=new Array(e.length),a=new Array(e.length),o=[],s=0;s<e.length;++s){var l=r[s].length;a[s]=l,i[s]=!0,l<=1&&o.push(s)}for(;o.length>0;){var c=o.pop();i[c]=!1;for(var u=r[c],s=0;s<u.length;++s){var h=u[s];0==--a[h]&&o.push(h)}}for(var f=new Array(e.length),p=[],s=0;s<e.length;++s)if(i[s]){var c=p.length;f[s]=c,p.push(e[s])}else f[s]=-1;for(var d=[],s=0;s<t.length;++s){var g=t[s];i[g[0]]&&i[g[1]]&&d.push([f[g[0]],f[g[1]]])}return[d,p]};var n=t("edges-to-adjacency-list")},{"edges-to-adjacency-list":160}],457:[function(t,e,r){"use strict";e.exports=function(t,e){var r=c(t,e);t=r[0];for(var h=(e=r[1]).length,f=(t.length,n(t,e.length)),p=0;p<h;++p)if(f[p].length%2==1)throw new Error("planar-graph-to-polyline: graph must be manifold");var d=i(t,e);for(var g=(d=d.filter(function(t){for(var r=t.length,n=[0],i=0;i<r;++i){var a=e[t[i]],l=e[t[(i+1)%r]],c=o(-a[0],a[1]),u=o(-a[0],l[1]),h=o(l[0],a[1]),f=o(l[0],l[1]);n=s(n,s(s(c,u),s(h,f)))}return n[n.length-1]>0})).length,v=new Array(g),m=new Array(g),p=0;p<g;++p){v[p]=p;var y=new Array(g),x=d[p].map(function(t){return e[t]}),b=a([x]),_=0;t:for(var w=0;w<g;++w)if(y[w]=0,p!==w){for(var k=d[w],A=k.length,M=0;M<A;++M){var T=b(e[k[M]]);if(0!==T){T<0&&(y[w]=1,_+=1);continue t}}y[w]=1,_+=1}m[p]=[_,p,y]}m.sort(function(t,e){return e[0]-t[0]});for(var p=0;p<g;++p)for(var y=m[p],S=y[1],E=y[2],w=0;w<g;++w)E[w]&&(v[w]=S);for(var C=function(t){for(var e=new Array(t),r=0;r<t;++r)e[r]=[];return e}(g),p=0;p<g;++p)C[p].push(v[p]),C[v[p]].push(p);for(var L={},z=u(h,!1),p=0;p<g;++p)for(var k=d[p],A=k.length,w=0;w<A;++w){var O=k[w],I=k[(w+1)%A],D=Math.min(O,I)+":"+Math.max(O,I);if(D in L){var P=L[D];C[P].push(p),C[p].push(P),z[O]=z[I]=!0}else L[D]=p}function R(t){for(var e=t.length,r=0;r<e;++r)if(!z[t[r]])return!1;return!0}for(var F=[],B=u(g,-1),p=0;p<g;++p)v[p]!==p||R(d[p])?B[p]=-1:(F.push(p),B[p]=0);var r=[];for(;F.length>0;){var N=F.pop(),j=C[N];l(j,function(t,e){return t-e});var V,U=j.length,q=B[N];if(0===q){var k=d[N];V=[k]}for(var p=0;p<U;++p){var H=j[p];if(!(B[H]>=0)&&(B[H]=1^q,F.push(H),0===q)){var k=d[H];R(k)||(k.reverse(),V.push(k))}}0===q&&r.push(V)}return r};var n=t("edges-to-adjacency-list"),i=t("planar-dual"),a=t("point-in-big-polygon"),o=t("two-product"),s=t("robust-sum"),l=t("uniq"),c=t("./lib/trim-leaves");function u(t,e){for(var r=new Array(t),n=0;n<t;++n)r[n]=e;return r}},{"./lib/trim-leaves":456,"edges-to-adjacency-list":160,"planar-dual":455,"point-in-big-polygon":461,"robust-sum":496,"two-product":524,uniq:528}],458:[function(t,e,r){"use strict";e.exports=t("./quad")},{"./quad":460}],459:[function(t,e,r){arguments[4][99][0].apply(r,arguments)},{dup:99}],460:[function(t,e,r){"use strict";var n=t("binary-search-bounds"),i=t("clamp"),a=t("parse-rect"),o=t("array-bounds"),s=t("pick-by-alias"),l=t("defined"),c=t("flatten-vertex-data"),u=t("is-obj"),h=t("dtype"),f=t("math-log2");function p(t,e){for(var r=e[0],n=e[1],a=1/(e[2]-r),o=1/(e[3]-n),s=new Array(t.length),l=0,c=t.length/2;l<c;l++)s[2*l]=i((t[2*l]-r)*a,0,1),s[2*l+1]=i((t[2*l+1]-n)*o,0,1);return s}e.exports=function(t,e){e||(e={}),t=c(t,"float64"),e=s(e,{bounds:"range bounds dataBox databox",maxDepth:"depth maxDepth maxdepth level maxLevel maxlevel levels",dtype:"type dtype format out dst output destination"});var r=l(e.maxDepth,255),i=l(e.bounds,o(t,2));i[0]===i[2]&&i[2]++,i[1]===i[3]&&i[3]++;var d,g=p(t,i),v=t.length>>>1;e.dtype||(e.dtype="array"),"string"==typeof e.dtype?d=new(h(e.dtype))(v):e.dtype&&(d=e.dtype,Array.isArray(d)&&(d.length=v));for(var m=0;m<v;++m)d[m]=m;var y=[],x=[],b=[],_=[];!function t(e,n,i,a,o,s){if(!a.length)return null;var l=y[o]||(y[o]=[]);var c=b[o]||(b[o]=[]);var u=x[o]||(x[o]=[]);var h=l.length;o++;if(o>r){for(var f=0;f<a.length;f++)l.push(a[f]),c.push(s),u.push(null,null,null,null);return h}l.push(a[0]);c.push(s);if(a.length<=1)return u.push(null,null,null,null),h;var p=.5*i;var d=e+p,v=n+p;var m=[],_=[],w=[],k=[];for(var A=1,M=a.length;A<M;A++){var T=a[A],S=g[2*T],E=g[2*T+1];S<d?E<v?m.push(T):_.push(T):E<v?w.push(T):k.push(T)}s<<=2;u.push(t(e,n,p,m,o,s),t(e,v,p,_,o,s+1),t(d,n,p,w,o,s+2),t(d,v,p,k,o,s+3));return h}(0,0,1,d,0,1);for(var w=0,k=0;k<y.length;k++){var A=y[k];if(d.set)d.set(A,w);else for(var M=0,T=A.length;M<T;M++)d[M+w]=A[M];var S=w+y[k].length;_[k]=[w,S],w=S}return d.range=function(){var e,r=[],o=arguments.length;for(;o--;)r[o]=arguments[o];if(u(r[r.length-1])){var c=r.pop();r.length||null==c.x&&null==c.l&&null==c.left||(r=[c],e={}),e=s(c,{level:"level maxLevel",d:"d diam diameter r radius px pxSize pixel pixelSize maxD size minSize",lod:"lod details ranges offsets"})}else e={};r.length||(r=i);var h=a.apply(void 0,r),d=[Math.min(h.x,h.x+h.width),Math.min(h.y,h.y+h.height),Math.max(h.x,h.x+h.width),Math.max(h.y,h.y+h.height)],g=d[0],v=d[1],m=d[2],w=d[3],k=p([g,v,m,w],i),A=k[0],M=k[1],T=k[2],S=k[3],C=l(e.level,y.length);if(null!=e.d){var L;"number"==typeof e.d?L=[e.d,e.d]:e.d.length&&(L=e.d),C=Math.min(Math.max(Math.ceil(-f(Math.abs(L[0])/(i[2]-i[0]))),Math.ceil(-f(Math.abs(L[1])/(i[3]-i[1])))),C)}if(C=Math.min(C,y.length),e.lod)return function(t,e,r,i,a){for(var o=[],s=0;s<a;s++){var l=b[s],c=_[s][0],u=E(t,e,s),h=E(r,i,s),f=n.ge(l,u),p=n.gt(l,h,f,l.length-1);o[s]=[f+c,p+c]}return o}(A,M,T,S,C);var z=[];return function e(r,n,i,a,o,s){if(null!==o&&null!==s){var l=r+i,c=n+i;if(!(A>l||M>c||T<r||S<n||a>=C||o===s)){var u=y[a];void 0===s&&(s=u.length);for(var h=o;h<s;h++){var f=u[h],p=t[2*f],d=t[2*f+1];p>=g&&p<=m&&d>=v&&d<=w&&z.push(f)}var b=x[a],_=b[4*o+0],k=b[4*o+1],E=b[4*o+2],L=b[4*o+3],O=function(t,e){for(var r=null,n=0;null===r;)if(r=t[4*e+n],++n>t.length)return null;return r}(b,o+1),I=.5*i,D=a+1;e(r,n,I,D,_,k||E||L||O),e(r,n+I,I,D,k,E||L||O),e(r+I,n,I,D,E,L||O),e(r+I,n+I,I,D,L,O)}}}(0,0,1,0,0,1),z},d;function E(t,e,r){for(var n=1,i=.5,a=.5,o=.5,s=0;s<r;s++)n<<=2,n+=t<i?e<a?0:1:e<a?2:3,o*=.5,i+=t<i?-o:o,a+=e<a?-o:o;return n}}},{"array-bounds":53,"binary-search-bounds":459,clamp:103,defined:152,dtype:157,"flatten-vertex-data":220,"is-obj":410,"math-log2":421,"parse-rect":448,"pick-by-alias":454}],461:[function(t,e,r){e.exports=function(t){for(var e=t.length,r=[],a=[],s=0;s<e;++s)for(var u=t[s],h=u.length,f=h-1,p=0;p<h;f=p++){var d=u[f],g=u[p];d[0]===g[0]?a.push([d,g]):r.push([d,g])}if(0===r.length)return 0===a.length?c:(v=l(a),function(t){return v(t[0],t[1])?0:1});var v;var m=i(r),y=function(t,e){return function(r){var i=o.le(e,r[0]);if(i<0)return 1;var a=t[i];if(!a){if(!(i>0&&e[i]===r[0]))return 1;a=t[i-1]}for(var s=1;a;){var l=a.key,c=n(r,l[0],l[1]);if(l[0][0]<l[1][0])if(c<0)a=a.left;else{if(!(c>0))return 0;s=-1,a=a.right}else if(c>0)a=a.left;else{if(!(c<0))return 0;s=1,a=a.right}}return s}}(m.slabs,m.coordinates);return 0===a.length?y:function(t,e){return function(r){return t(r[0],r[1])?0:e(r)}}(l(a),y)};var n=t("robust-orientation")[3],i=t("slab-decomposition"),a=t("interval-tree-1d"),o=t("binary-search-bounds");function s(){return!0}function l(t){for(var e={},r=0;r<t.length;++r){var n=t[r],i=n[0][0],o=n[0][1],l=n[1][1],c=[Math.min(o,l),Math.max(o,l)];i in e?e[i].push(c):e[i]=[c]}var u={},h=Object.keys(e);for(r=0;r<h.length;++r){var f=e[h[r]];u[h[r]]=a(f)}return function(t){return function(e,r){var n=t[e];return!!n&&!!n.queryPoint(r,s)}}(u)}function c(t){return 1}},{"binary-search-bounds":79,"interval-tree-1d":403,"robust-orientation":491,"slab-decomposition":507}],462:[function(t,e,r){var n,i=t("./lib/build-log"),a=t("./lib/epsilon"),o=t("./lib/intersecter"),s=t("./lib/segment-chainer"),l=t("./lib/segment-selector"),c=t("./lib/geojson"),u=!1,h=a();function f(t,e,r){var i=n.segments(t),a=n.segments(e),o=r(n.combine(i,a));return n.polygon(o)}n={buildLog:function(t){return!0===t?u=i():!1===t&&(u=!1),!1!==u&&u.list},epsilon:function(t){return h.epsilon(t)},segments:function(t){var e=o(!0,h,u);return t.regions.forEach(e.addRegion),{segments:e.calculate(t.inverted),inverted:t.inverted}},combine:function(t,e){return{combined:o(!1,h,u).calculate(t.segments,t.inverted,e.segments,e.inverted),inverted1:t.inverted,inverted2:e.inverted}},selectUnion:function(t){return{segments:l.union(t.combined,u),inverted:t.inverted1||t.inverted2}},selectIntersect:function(t){return{segments:l.intersect(t.combined,u),inverted:t.inverted1&&t.inverted2}},selectDifference:function(t){return{segments:l.difference(t.combined,u),inverted:t.inverted1&&!t.inverted2}},selectDifferenceRev:function(t){return{segments:l.differenceRev(t.combined,u),inverted:!t.inverted1&&t.inverted2}},selectXor:function(t){return{segments:l.xor(t.combined,u),inverted:t.inverted1!==t.inverted2}},polygon:function(t){return{regions:s(t.segments,h,u),inverted:t.inverted}},polygonFromGeoJSON:function(t){return c.toPolygon(n,t)},polygonToGeoJSON:function(t){return c.fromPolygon(n,h,t)},union:function(t,e){return f(t,e,n.selectUnion)},intersect:function(t,e){return f(t,e,n.selectIntersect)},difference:function(t,e){return f(t,e,n.selectDifference)},differenceRev:function(t,e){return f(t,e,n.selectDifferenceRev)},xor:function(t,e){return f(t,e,n.selectXor)}},"object"==typeof window&&(window.PolyBool=n),e.exports=n},{"./lib/build-log":463,"./lib/epsilon":464,"./lib/geojson":465,"./lib/intersecter":466,"./lib/segment-chainer":468,"./lib/segment-selector":469}],463:[function(t,e,r){e.exports=function(){var t,e=0,r=!1;function n(e,r){return t.list.push({type:e,data:r?JSON.parse(JSON.stringify(r)):void 0}),t}return t={list:[],segmentId:function(){return e++},checkIntersection:function(t,e){return n("check",{seg1:t,seg2:e})},segmentChop:function(t,e){return n("div_seg",{seg:t,pt:e}),n("chop",{seg:t,pt:e})},statusRemove:function(t){return n("pop_seg",{seg:t})},segmentUpdate:function(t){return n("seg_update",{seg:t})},segmentNew:function(t,e){return n("new_seg",{seg:t,primary:e})},segmentRemove:function(t){return n("rem_seg",{seg:t})},tempStatus:function(t,e,r){return n("temp_status",{seg:t,above:e,below:r})},rewind:function(t){return n("rewind",{seg:t})},status:function(t,e,r){return n("status",{seg:t,above:e,below:r})},vert:function(e){return e===r?t:(r=e,n("vert",{x:e}))},log:function(t){return"string"!=typeof t&&(t=JSON.stringify(t,!1,"  ")),n("log",{txt:t})},reset:function(){return n("reset")},selected:function(t){return n("selected",{segs:t})},chainStart:function(t){return n("chain_start",{seg:t})},chainRemoveHead:function(t,e){return n("chain_rem_head",{index:t,pt:e})},chainRemoveTail:function(t,e){return n("chain_rem_tail",{index:t,pt:e})},chainNew:function(t,e){return n("chain_new",{pt1:t,pt2:e})},chainMatch:function(t){return n("chain_match",{index:t})},chainClose:function(t){return n("chain_close",{index:t})},chainAddHead:function(t,e){return n("chain_add_head",{index:t,pt:e})},chainAddTail:function(t,e){return n("chain_add_tail",{index:t,pt:e})},chainConnect:function(t,e){return n("chain_con",{index1:t,index2:e})},chainReverse:function(t){return n("chain_rev",{index:t})},chainJoin:function(t,e){return n("chain_join",{index1:t,index2:e})},done:function(){return n("done")}}}},{}],464:[function(t,e,r){e.exports=function(t){"number"!=typeof t&&(t=1e-10);var e={epsilon:function(e){return"number"==typeof e&&(t=e),t},pointAboveOrOnLine:function(e,r,n){var i=r[0],a=r[1],o=n[0],s=n[1],l=e[0];return(o-i)*(e[1]-a)-(s-a)*(l-i)>=-t},pointBetween:function(e,r,n){var i=e[1]-r[1],a=n[0]-r[0],o=e[0]-r[0],s=n[1]-r[1],l=o*a+i*s;return!(l<t||l-(a*a+s*s)>-t)},pointsSameX:function(e,r){return Math.abs(e[0]-r[0])<t},pointsSameY:function(e,r){return Math.abs(e[1]-r[1])<t},pointsSame:function(t,r){return e.pointsSameX(t,r)&&e.pointsSameY(t,r)},pointsCompare:function(t,r){return e.pointsSameX(t,r)?e.pointsSameY(t,r)?0:t[1]<r[1]?-1:1:t[0]<r[0]?-1:1},pointsCollinear:function(e,r,n){var i=e[0]-r[0],a=e[1]-r[1],o=r[0]-n[0],s=r[1]-n[1];return Math.abs(i*s-o*a)<t},linesIntersect:function(e,r,n,i){var a=r[0]-e[0],o=r[1]-e[1],s=i[0]-n[0],l=i[1]-n[1],c=a*l-o*s;if(Math.abs(c)<t)return!1;var u=e[0]-n[0],h=e[1]-n[1],f=(s*h-l*u)/c,p=(a*h-o*u)/c,d={alongA:0,alongB:0,pt:[e[0]+f*a,e[1]+f*o]};return d.alongA=f<=-t?-2:f<t?-1:f-1<=-t?0:f-1<t?1:2,d.alongB=p<=-t?-2:p<t?-1:p-1<=-t?0:p-1<t?1:2,d},pointInsideRegion:function(e,r){for(var n=e[0],i=e[1],a=r[r.length-1][0],o=r[r.length-1][1],s=!1,l=0;l<r.length;l++){var c=r[l][0],u=r[l][1];u-i>t!=o-i>t&&(a-c)*(i-u)/(o-u)+c-n>t&&(s=!s),a=c,o=u}return s}};return e}},{}],465:[function(t,e,r){var n={toPolygon:function(t,e){function r(e){if(e.length<=0)return t.segments({inverted:!1,regions:[]});function r(e){var r=e.slice(0,e.length-1);return t.segments({inverted:!1,regions:[r]})}for(var n=r(e[0]),i=1;i<e.length;i++)n=t.selectDifference(t.combine(n,r(e[i])));return n}if("Polygon"===e.type)return t.polygon(r(e.coordinates));if("MultiPolygon"===e.type){for(var n=t.segments({inverted:!1,regions:[]}),i=0;i<e.coordinates.length;i++)n=t.selectUnion(t.combine(n,r(e.coordinates[i])));return t.polygon(n)}throw new Error("PolyBool: Cannot convert GeoJSON object to PolyBool polygon")},fromPolygon:function(t,e,r){function n(t,r){return e.pointInsideRegion([.5*(t[0][0]+t[1][0]),.5*(t[0][1]+t[1][1])],r)}function i(t){return{region:t,children:[]}}r=t.polygon(t.segments(r));var a=i(null);function o(t,e){for(var r=0;r<t.children.length;r++){if(n(e,(s=t.children[r]).region))return void o(s,e)}var a=i(e);for(r=0;r<t.children.length;r++){var s;n((s=t.children[r]).region,e)&&(a.children.push(s),t.children.splice(r,1),r--)}t.children.push(a)}for(var s=0;s<r.regions.length;s++){var l=r.regions[s];l.length<3||o(a,l)}function c(t,e){for(var r=0,n=t[t.length-1][0],i=t[t.length-1][1],a=[],o=0;o<t.length;o++){var s=t[o][0],l=t[o][1];a.push([s,l]),r+=l*n-s*i,n=s,i=l}return r<0!==e&&a.reverse(),a.push([a[0][0],a[0][1]]),a}var u=[];function h(t){var e=[c(t.region,!1)];u.push(e);for(var r=0;r<t.children.length;r++)e.push(f(t.children[r]))}function f(t){for(var e=0;e<t.children.length;e++)h(t.children[e]);return c(t.region,!0)}for(s=0;s<a.children.length;s++)h(a.children[s]);return u.length<=0?{type:"Polygon",coordinates:[]}:1==u.length?{type:"Polygon",coordinates:u[0]}:{type:"MultiPolygon",coordinates:u}}};e.exports=n},{}],466:[function(t,e,r){var n=t("./linked-list");e.exports=function(t,e,r){function i(t,e,n){return{id:r?r.segmentId():-1,start:t,end:e,myFill:{above:n.myFill.above,below:n.myFill.below},otherFill:null}}var a=n.create();function o(t,r){a.insertBefore(t,function(n){return function(t,r,n,i,a,o){var s=e.pointsCompare(r,a);return 0!==s?s:e.pointsSame(n,o)?0:t!==i?t?1:-1:e.pointAboveOrOnLine(n,i?a:o,i?o:a)?1:-1}(t.isStart,t.pt,r,n.isStart,n.pt,n.other.pt)<0})}function s(t,e){var r=function(t,e){var r=n.node({isStart:!0,pt:t.start,seg:t,primary:e,other:null,status:null});return o(r,t.end),r}(t,e);return function(t,e,r){var i=n.node({isStart:!1,pt:e.end,seg:e,primary:r,other:t,status:null});t.other=i,o(i,t.pt)}(r,t,e),r}function l(t,e){var n=i(e,t.seg.end,t.seg);return function(t,e){r&&r.segmentChop(t.seg,e),t.other.remove(),t.seg.end=e,t.other.pt=e,o(t.other,t.pt)}(t,e),s(n,t.primary)}function c(i,o){var s=n.create();function c(t){return s.findTransition(function(r){var n,i,a,o,s,l;return n=t,i=r.ev,a=n.seg.start,o=n.seg.end,s=i.seg.start,l=i.seg.end,(e.pointsCollinear(a,s,l)?e.pointsCollinear(o,s,l)?1:e.pointAboveOrOnLine(o,s,l)?1:-1:e.pointAboveOrOnLine(a,s,l)?1:-1)>0})}function u(t,n){var i=t.seg,a=n.seg,o=i.start,s=i.end,c=a.start,u=a.end;r&&r.checkIntersection(i,a);var h=e.linesIntersect(o,s,c,u);if(!1===h){if(!e.pointsCollinear(o,s,c))return!1;if(e.pointsSame(o,u)||e.pointsSame(s,c))return!1;var f=e.pointsSame(o,c),p=e.pointsSame(s,u);if(f&&p)return n;var d=!f&&e.pointBetween(o,c,u),g=!p&&e.pointBetween(s,c,u);if(f)return g?l(n,s):l(t,u),n;d&&(p||(g?l(n,s):l(t,u)),l(n,o))}else 0===h.alongA&&(-1===h.alongB?l(t,c):0===h.alongB?l(t,h.pt):1===h.alongB&&l(t,u)),0===h.alongB&&(-1===h.alongA?l(n,o):0===h.alongA?l(n,h.pt):1===h.alongA&&l(n,s));return!1}for(var h=[];!a.isEmpty();){var f=a.getHead();if(r&&r.vert(f.pt[0]),f.isStart){r&&r.segmentNew(f.seg,f.primary);var p=c(f),d=p.before?p.before.ev:null,g=p.after?p.after.ev:null;function v(){if(d){var t=u(f,d);if(t)return t}return!!g&&u(f,g)}r&&r.tempStatus(f.seg,!!d&&d.seg,!!g&&g.seg);var m,y,x=v();if(x)t?(y=null===f.seg.myFill.below||f.seg.myFill.above!==f.seg.myFill.below)&&(x.seg.myFill.above=!x.seg.myFill.above):x.seg.otherFill=f.seg.myFill,r&&r.segmentUpdate(x.seg),f.other.remove(),f.remove();if(a.getHead()!==f){r&&r.rewind(f.seg);continue}t?(y=null===f.seg.myFill.below||f.seg.myFill.above!==f.seg.myFill.below,f.seg.myFill.below=g?g.seg.myFill.above:i,f.seg.myFill.above=y?!f.seg.myFill.below:f.seg.myFill.below):null===f.seg.otherFill&&(m=g?f.primary===g.primary?g.seg.otherFill.above:g.seg.myFill.above:f.primary?o:i,f.seg.otherFill={above:m,below:m}),r&&r.status(f.seg,!!d&&d.seg,!!g&&g.seg),f.other.status=p.insert(n.node({ev:f}))}else{var b=f.status;if(null===b)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");if(s.exists(b.prev)&&s.exists(b.next)&&u(b.prev.ev,b.next.ev),r&&r.statusRemove(b.ev.seg),b.remove(),!f.primary){var _=f.seg.myFill;f.seg.myFill=f.seg.otherFill,f.seg.otherFill=_}h.push(f.seg)}a.getHead().remove()}return r&&r.done(),h}return t?{addRegion:function(t){for(var n,i,a,o=t[t.length-1],l=0;l<t.length;l++){n=o,o=t[l];var c=e.pointsCompare(n,o);0!==c&&s((i=c<0?n:o,a=c<0?o:n,{id:r?r.segmentId():-1,start:i,end:a,myFill:{above:null,below:null},otherFill:null}),!0)}},calculate:function(t){return c(t,!1)}}:{calculate:function(t,e,r,n){return t.forEach(function(t){s(i(t.start,t.end,t),!0)}),r.forEach(function(t){s(i(t.start,t.end,t),!1)}),c(e,n)}}}},{"./linked-list":467}],467:[function(t,e,r){e.exports={create:function(){var t={root:{root:!0,next:null},exists:function(e){return null!==e&&e!==t.root},isEmpty:function(){return null===t.root.next},getHead:function(){return t.root.next},insertBefore:function(e,r){for(var n=t.root,i=t.root.next;null!==i;){if(r(i))return e.prev=i.prev,e.next=i,i.prev.next=e,void(i.prev=e);n=i,i=i.next}n.next=e,e.prev=n,e.next=null},findTransition:function(e){for(var r=t.root,n=t.root.next;null!==n&&!e(n);)r=n,n=n.next;return{before:r===t.root?null:r,after:n,insert:function(t){return t.prev=r,t.next=n,r.next=t,null!==n&&(n.prev=t),t}}}};return t},node:function(t){return t.prev=null,t.next=null,t.remove=function(){t.prev.next=t.next,t.next&&(t.next.prev=t.prev),t.prev=null,t.next=null},t}}},{}],468:[function(t,e,r){e.exports=function(t,e,r){var n=[],i=[];return t.forEach(function(t){var a=t.start,o=t.end;if(e.pointsSame(a,o))console.warn("PolyBool: Warning: Zero-length segment detected; your epsilon is probably too small or too large");else{r&&r.chainStart(t);for(var s={index:0,matches_head:!1,matches_pt1:!1},l={index:0,matches_head:!1,matches_pt1:!1},c=s,u=0;u<n.length;u++){var h=(v=n[u])[0],f=(v[1],v[v.length-1]);if(v[v.length-2],e.pointsSame(h,a)){if(A(u,!0,!0))break}else if(e.pointsSame(h,o)){if(A(u,!0,!1))break}else if(e.pointsSame(f,a)){if(A(u,!1,!0))break}else if(e.pointsSame(f,o)&&A(u,!1,!1))break}if(c===s)return n.push([a,o]),void(r&&r.chainNew(a,o));if(c===l){r&&r.chainMatch(s.index);var p=s.index,d=s.matches_pt1?o:a,g=s.matches_head,v=n[p],m=g?v[0]:v[v.length-1],y=g?v[1]:v[v.length-2],x=g?v[v.length-1]:v[0],b=g?v[v.length-2]:v[1];return e.pointsCollinear(y,m,d)&&(g?(r&&r.chainRemoveHead(s.index,d),v.shift()):(r&&r.chainRemoveTail(s.index,d),v.pop()),m=y),e.pointsSame(x,d)?(n.splice(p,1),e.pointsCollinear(b,x,m)&&(g?(r&&r.chainRemoveTail(s.index,m),v.pop()):(r&&r.chainRemoveHead(s.index,m),v.shift())),r&&r.chainClose(s.index),void i.push(v)):void(g?(r&&r.chainAddHead(s.index,d),v.unshift(d)):(r&&r.chainAddTail(s.index,d),v.push(d)))}var _=s.index,w=l.index;r&&r.chainConnect(_,w);var k=n[_].length<n[w].length;s.matches_head?l.matches_head?k?(M(_),T(_,w)):(M(w),T(w,_)):T(w,_):l.matches_head?T(_,w):k?(M(_),T(w,_)):(M(w),T(_,w))}function A(t,e,r){return c.index=t,c.matches_head=e,c.matches_pt1=r,c===s?(c=l,!1):(c=null,!0)}function M(t){r&&r.chainReverse(t),n[t].reverse()}function T(t,i){var a=n[t],o=n[i],s=a[a.length-1],l=a[a.length-2],c=o[0],u=o[1];e.pointsCollinear(l,s,c)&&(r&&r.chainRemoveTail(t,s),a.pop(),s=l),e.pointsCollinear(s,c,u)&&(r&&r.chainRemoveHead(i,c),o.shift()),r&&r.chainJoin(t,i),n[t]=a.concat(o),n.splice(i,1)}}),i}},{}],469:[function(t,e,r){function n(t,e,r){var n=[];return t.forEach(function(t){var i=(t.myFill.above?8:0)+(t.myFill.below?4:0)+(t.otherFill&&t.otherFill.above?2:0)+(t.otherFill&&t.otherFill.below?1:0);0!==e[i]&&n.push({id:r?r.segmentId():-1,start:t.start,end:t.end,myFill:{above:1===e[i],below:2===e[i]},otherFill:null})}),r&&r.selected(n),n}var i={union:function(t,e){return n(t,[0,2,1,0,2,2,0,0,1,0,1,0,0,0,0,0],e)},intersect:function(t,e){return n(t,[0,0,0,0,0,2,0,2,0,0,1,1,0,2,1,0],e)},difference:function(t,e){return n(t,[0,0,0,0,2,0,2,0,1,1,0,0,0,1,2,0],e)},differenceRev:function(t,e){return n(t,[0,2,1,0,0,0,1,1,0,2,0,2,0,0,0,0],e)},xor:function(t,e){return n(t,[0,2,1,0,2,0,0,1,1,0,0,2,0,1,2,0],e)}};e.exports=i},{}],470:[function(t,e,r){"use strict";var n=new Float64Array(4),i=new Float64Array(4),a=new Float64Array(4);e.exports=function(t,e,r,o,s){n.length<o.length&&(n=new Float64Array(o.length),i=new Float64Array(o.length),a=new Float64Array(o.length));for(var l=0;l<o.length;++l)n[l]=t[l]-o[l],i[l]=e[l]-t[l],a[l]=r[l]-t[l];var c=0,u=0,h=0,f=0,p=0,d=0;for(l=0;l<o.length;++l){var g=i[l],v=a[l],m=n[l];c+=g*g,u+=g*v,h+=v*v,f+=m*g,p+=m*v,d+=m*m}var y,x,b,_,w,k=Math.abs(c*h-u*u),A=u*p-h*f,M=u*f-c*p;if(A+M<=k)if(A<0)M<0&&f<0?(M=0,-f>=c?(A=1,y=c+2*f+d):y=f*(A=-f/c)+d):(A=0,p>=0?(M=0,y=d):-p>=h?(M=1,y=h+2*p+d):y=p*(M=-p/h)+d);else if(M<0)M=0,f>=0?(A=0,y=d):-f>=c?(A=1,y=c+2*f+d):y=f*(A=-f/c)+d;else{var T=1/k;y=(A*=T)*(c*A+u*(M*=T)+2*f)+M*(u*A+h*M+2*p)+d}else A<0?(b=h+p)>(x=u+f)?(_=b-x)>=(w=c-2*u+h)?(A=1,M=0,y=c+2*f+d):y=(A=_/w)*(c*A+u*(M=1-A)+2*f)+M*(u*A+h*M+2*p)+d:(A=0,b<=0?(M=1,y=h+2*p+d):p>=0?(M=0,y=d):y=p*(M=-p/h)+d):M<0?(b=c+f)>(x=u+p)?(_=b-x)>=(w=c-2*u+h)?(M=1,A=0,y=h+2*p+d):y=(A=1-(M=_/w))*(c*A+u*M+2*f)+M*(u*A+h*M+2*p)+d:(M=0,b<=0?(A=1,y=c+2*f+d):f>=0?(A=0,y=d):y=f*(A=-f/c)+d):(_=h+p-u-f)<=0?(A=0,M=1,y=h+2*p+d):_>=(w=c-2*u+h)?(A=1,M=0,y=c+2*f+d):y=(A=_/w)*(c*A+u*(M=1-A)+2*f)+M*(u*A+h*M+2*p)+d;var S=1-A-M;for(l=0;l<o.length;++l)s[l]=S*t[l]+A*e[l]+M*r[l];return y<0?0:y}},{}],471:[function(t,e,r){var n,i,a=e.exports={};function o(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function l(t){if(n===setTimeout)return setTimeout(t,0);if((n===o||!n)&&setTimeout)return n=setTimeout,setTimeout(t,0);try{return n(t,0)}catch(e){try{return n.call(null,t,0)}catch(e){return n.call(this,t,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:o}catch(t){n=o}try{i="function"==typeof clearTimeout?clearTimeout:s}catch(t){i=s}}();var c,u=[],h=!1,f=-1;function p(){h&&c&&(h=!1,c.length?u=c.concat(u):f=-1,u.length&&d())}function d(){if(!h){var t=l(p);h=!0;for(var e=u.length;e;){for(c=u,u=[];++f<e;)c&&c[f].run();f=-1,e=u.length}c=null,h=!1,function(t){if(i===clearTimeout)return clearTimeout(t);if((i===s||!i)&&clearTimeout)return i=clearTimeout,clearTimeout(t);try{i(t)}catch(e){try{return i.call(null,t)}catch(e){return i.call(this,t)}}}(t)}}function g(t,e){this.fun=t,this.array=e}function v(){}a.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)e[r-1]=arguments[r];u.push(new g(t,e)),1!==u.length||h||l(d)},g.prototype.run=function(){this.fun.apply(null,this.array)},a.title="browser",a.browser=!0,a.env={},a.argv=[],a.version="",a.versions={},a.on=v,a.addListener=v,a.once=v,a.off=v,a.removeListener=v,a.removeAllListeners=v,a.emit=v,a.prependListener=v,a.prependOnceListener=v,a.listeners=function(t){return[]},a.binding=function(t){throw new Error("process.binding is not supported")},a.cwd=function(){return"/"},a.chdir=function(t){throw new Error("process.chdir is not supported")},a.umask=function(){return 0}},{}],472:[function(t,e,r){e.exports=t("gl-quat/slerp")},{"gl-quat/slerp":286}],473:[function(t,e,r){(function(r){for(var n=t("performance-now"),i="undefined"==typeof window?r:window,a=["moz","webkit"],o="AnimationFrame",s=i["request"+o],l=i["cancel"+o]||i["cancelRequest"+o],c=0;!s&&c<a.length;c++)s=i[a[c]+"Request"+o],l=i[a[c]+"Cancel"+o]||i[a[c]+"CancelRequest"+o];if(!s||!l){var u=0,h=0,f=[];s=function(t){if(0===f.length){var e=n(),r=Math.max(0,1e3/60-(e-u));u=r+e,setTimeout(function(){var t=f.slice(0);f.length=0;for(var e=0;e<t.length;e++)if(!t[e].cancelled)try{t[e].callback(u)}catch(t){setTimeout(function(){throw t},0)}},Math.round(r))}return f.push({handle:++h,callback:t,cancelled:!1}),h},l=function(t){for(var e=0;e<f.length;e++)f[e].handle===t&&(f[e].cancelled=!0)}}e.exports=function(t){return s.call(i,t)},e.exports.cancel=function(){l.apply(i,arguments)},e.exports.polyfill=function(t){t||(t=i),t.requestAnimationFrame=s,t.cancelAnimationFrame=l}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"performance-now":451}],474:[function(t,e,r){"use strict";var n=t("big-rat/add");e.exports=function(t,e){for(var r=t.length,i=new Array(r),a=0;a<r;++a)i[a]=n(t[a],e[a]);return i}},{"big-rat/add":63}],475:[function(t,e,r){"use strict";e.exports=function(t){for(var e=new Array(t.length),r=0;r<t.length;++r)e[r]=n(t[r]);return e};var n=t("big-rat")},{"big-rat":66}],476:[function(t,e,r){"use strict";var n=t("big-rat"),i=t("big-rat/mul");e.exports=function(t,e){for(var r=n(e),a=t.length,o=new Array(a),s=0;s<a;++s)o[s]=i(t[s],r);return o}},{"big-rat":66,"big-rat/mul":75}],477:[function(t,e,r){"use strict";var n=t("big-rat/sub");e.exports=function(t,e){for(var r=t.length,i=new Array(r),a=0;a<r;++a)i[a]=n(t[a],e[a]);return i}},{"big-rat/sub":77}],478:[function(t,e,r){"use strict";var n=t("compare-cell"),i=t("compare-oriented-cell"),a=t("cell-orientation");e.exports=function(t){t.sort(i);for(var e=t.length,r=0,o=0;o<e;++o){var s=t[o],l=a(s);if(0!==l){if(r>0){var c=t[r-1];if(0===n(s,c)&&a(c)!==l){r-=1;continue}}t[r++]=s}}return t.length=r,t}},{"cell-orientation":100,"compare-cell":116,"compare-oriented-cell":117}],479:[function(t,e,r){"use strict";var n=t("array-bounds"),i=t("color-normalize"),a=t("update-diff"),o=t("pick-by-alias"),s=t("object-assign"),l=t("flatten-vertex-data"),c=t("to-float32"),u=c.float32,h=c.fract32;e.exports=function(t,e){"function"==typeof t?(e||(e={}),e.regl=t):e=t;e.length&&(e.positions=e);if(!(t=e.regl).hasExtension("ANGLE_instanced_arrays"))throw Error("regl-error2d: `ANGLE_instanced_arrays` extension should be enabled");var r,c,p,d,g,v,m=t._gl,y={color:"black",capSize:5,lineWidth:1,opacity:1,viewport:null,range:null,offset:0,count:0,bounds:null,positions:[],errors:[]},x=[];return d=t.buffer({usage:"dynamic",type:"uint8",data:new Uint8Array(0)}),c=t.buffer({usage:"dynamic",type:"float",data:new Uint8Array(0)}),p=t.buffer({usage:"dynamic",type:"float",data:new Uint8Array(0)}),g=t.buffer({usage:"dynamic",type:"float",data:new Uint8Array(0)}),v=t.buffer({usage:"static",type:"float",data:f}),k(e),r=t({vert:"\n\t\tprecision highp float;\n\n\t\tattribute vec2 position, positionFract;\n\t\tattribute vec4 error;\n\t\tattribute vec4 color;\n\n\t\tattribute vec2 direction, lineOffset, capOffset;\n\n\t\tuniform vec4 viewport;\n\t\tuniform float lineWidth, capSize;\n\t\tuniform vec2 scale, scaleFract, translate, translateFract;\n\n\t\tvarying vec4 fragColor;\n\n\t\tvoid main() {\n\t\t\tfragColor = color / 255.;\n\n\t\t\tvec2 pixelOffset = lineWidth * lineOffset + (capSize + lineWidth) * capOffset;\n\n\t\t\tvec2 dxy = -step(.5, direction.xy) * error.xz + step(direction.xy, vec2(-.5)) * error.yw;\n\n\t\t\tvec2 position = position + dxy;\n\n\t\t\tvec2 pos = (position + translate) * scale\n\t\t\t\t+ (positionFract + translateFract) * scale\n\t\t\t\t+ (position + translate) * scaleFract\n\t\t\t\t+ (positionFract + translateFract) * scaleFract;\n\n\t\t\tpos += pixelOffset / viewport.zw;\n\n\t\t\tgl_Position = vec4(pos * 2. - 1., 0, 1);\n\t\t}\n\t\t",frag:"\n\t\tprecision mediump float;\n\n\t\tvarying vec4 fragColor;\n\n\t\tuniform float opacity;\n\n\t\tvoid main() {\n\t\t\tgl_FragColor = fragColor;\n\t\t\tgl_FragColor.a *= opacity;\n\t\t}\n\t\t",uniforms:{range:t.prop("range"),lineWidth:t.prop("lineWidth"),capSize:t.prop("capSize"),opacity:t.prop("opacity"),scale:t.prop("scale"),translate:t.prop("translate"),scaleFract:t.prop("scaleFract"),translateFract:t.prop("translateFract"),viewport:function(t,e){return[e.viewport.x,e.viewport.y,t.viewportWidth,t.viewportHeight]}},attributes:{color:{buffer:d,offset:function(t,e){return 4*e.offset},divisor:1},position:{buffer:c,offset:function(t,e){return 8*e.offset},divisor:1},positionFract:{buffer:p,offset:function(t,e){return 8*e.offset},divisor:1},error:{buffer:g,offset:function(t,e){return 16*e.offset},divisor:1},direction:{buffer:v,stride:24,offset:0},lineOffset:{buffer:v,stride:24,offset:8},capOffset:{buffer:v,stride:24,offset:16}},primitive:"triangles",blend:{enable:!0,color:[0,0,0,0],equation:{rgb:"add",alpha:"add"},func:{srcRGB:"src alpha",dstRGB:"one minus src alpha",srcAlpha:"one minus dst alpha",dstAlpha:"one"}},depth:{enable:!1},scissor:{enable:!0,box:t.prop("viewport")},viewport:t.prop("viewport"),stencil:!1,instances:t.prop("count"),count:f.length}),s(b,{update:k,draw:_,destroy:A,regl:t,gl:m,canvas:m.canvas,groups:x}),b;function b(t){t?k(t):null===t&&A(),_()}function _(e){if("number"==typeof e)return w(e);e&&!Array.isArray(e)&&(e=[e]),t._refresh(),x.forEach(function(t,r){t&&(e&&(e[r]?t.draw=!0:t.draw=!1),t.draw?w(r):t.draw=!0)})}function w(t){"number"==typeof t&&(t=x[t]),null!=t&&t&&t.count&&t.color&&t.opacity&&t.positions&&t.positions.length>1&&(t.scaleRatio=[t.scale[0]*t.viewport.width,t.scale[1]*t.viewport.height],r(t),t.after&&t.after(t))}function k(t){if(t){null!=t.length?"number"==typeof t[0]&&(t=[{positions:t}]):Array.isArray(t)||(t=[t]);var e=0,r=0;if(b.groups=x=t.map(function(t,c){var u=x[c];return t?("function"==typeof t?t={after:t}:"number"==typeof t[0]&&(t={positions:t}),t=o(t,{color:"color colors fill",capSize:"capSize cap capsize cap-size",lineWidth:"lineWidth line-width width line thickness",opacity:"opacity alpha",range:"range dataBox",viewport:"viewport viewBox",errors:"errors error",positions:"positions position data points"}),u||(x[c]=u={id:c,scale:null,translate:null,scaleFract:null,translateFract:null,draw:!0},t=s({},y,t)),a(u,t,[{lineWidth:function(t){return.5*+t},capSize:function(t){return.5*+t},opacity:parseFloat,errors:function(t){return t=l(t),r+=t.length,t},positions:function(t,r){return t=l(t,"float64"),r.count=Math.floor(t.length/2),r.bounds=n(t,2),r.offset=e,e+=r.count,t}},{color:function(t,e){var r=e.count;if(t||(t="transparent"),!Array.isArray(t)||"number"==typeof t[0]){var n=t;t=Array(r);for(var a=0;a<r;a++)t[a]=n}if(t.length<r)throw Error("Not enough colors");for(var o=new Uint8Array(4*r),s=0;s<r;s++){var l=i(t[s],"uint8");o.set(l,4*s)}return o},range:function(t,e,r){var n=e.bounds;return t||(t=n),e.scale=[1/(t[2]-t[0]),1/(t[3]-t[1])],e.translate=[-t[0],-t[1]],e.scaleFract=h(e.scale),e.translateFract=h(e.translate),t},viewport:function(t){var e;return Array.isArray(t)?e={x:t[0],y:t[1],width:t[2]-t[0],height:t[3]-t[1]}:t?(e={x:t.x||t.left||0,y:t.y||t.top||0},t.right?e.width=t.right-e.x:e.width=t.w||t.width||0,t.bottom?e.height=t.bottom-e.y:e.height=t.h||t.height||0):e={x:0,y:0,width:m.drawingBufferWidth,height:m.drawingBufferHeight},e}}]),u):u}),e||r){var f=x.reduce(function(t,e,r){return t+(e?e.count:0)},0),v=new Float64Array(2*f),_=new Uint8Array(4*f),w=new Float32Array(4*f);x.forEach(function(t,e){if(t){var r=t.positions,n=t.count,i=t.offset,a=t.color,o=t.errors;n&&(_.set(a,4*i),w.set(o,4*i),v.set(r,2*i))}}),c(u(v)),p(h(v)),d(_),g(w)}}}function A(){c.destroy(),p.destroy(),d.destroy(),g.destroy(),v.destroy()}};var f=[[1,0,0,1,0,0],[1,0,0,-1,0,0],[-1,0,0,-1,0,0],[-1,0,0,-1,0,0],[-1,0,0,1,0,0],[1,0,0,1,0,0],[1,0,-1,0,0,1],[1,0,-1,0,0,-1],[1,0,1,0,0,-1],[1,0,1,0,0,-1],[1,0,1,0,0,1],[1,0,-1,0,0,1],[-1,0,-1,0,0,1],[-1,0,-1,0,0,-1],[-1,0,1,0,0,-1],[-1,0,1,0,0,-1],[-1,0,1,0,0,1],[-1,0,-1,0,0,1],[0,1,1,0,0,0],[0,1,-1,0,0,0],[0,-1,-1,0,0,0],[0,-1,-1,0,0,0],[0,1,1,0,0,0],[0,-1,1,0,0,0],[0,1,0,-1,1,0],[0,1,0,-1,-1,0],[0,1,0,1,-1,0],[0,1,0,1,1,0],[0,1,0,-1,1,0],[0,1,0,1,-1,0],[0,-1,0,-1,1,0],[0,-1,0,-1,-1,0],[0,-1,0,1,-1,0],[0,-1,0,1,1,0],[0,-1,0,-1,1,0],[0,-1,0,1,-1,0]]},{"array-bounds":53,"color-normalize":108,"flatten-vertex-data":220,"object-assign":443,"pick-by-alias":454,"to-float32":519,"update-diff":530}],480:[function(t,e,r){"use strict";var n=t("color-normalize"),i=t("array-bounds"),a=t("object-assign"),o=t("glslify"),s=t("pick-by-alias"),l=t("flatten-vertex-data"),c=t("earcut"),u=t("array-normalize"),h=t("to-float32"),f=h.float32,p=h.fract32,d=t("es6-weak-map"),g=t("parse-rect");function v(t,e){if(!(this instanceof v))return new v(t,e);if("function"==typeof t?(e||(e={}),e.regl=t):e=t,e.length&&(e.positions=e),!(t=e.regl).hasExtension("ANGLE_instanced_arrays"))throw Error("regl-error2d: `ANGLE_instanced_arrays` extension should be enabled");this.gl=t._gl,this.regl=t,this.passes=[],this.shaders=v.shaders.has(t)?v.shaders.get(t):v.shaders.set(t,v.createShaders(t)).get(t),this.update(e)}e.exports=v,v.dashMult=2,v.maxPatternLength=256,v.precisionThreshold=3e6,v.maxPoints=1e4,v.maxLines=2048,v.shaders=new d,v.createShaders=function(t){var e,r=t.buffer({usage:"static",type:"float",data:[0,1,0,0,1,1,1,0]}),n={primitive:"triangle strip",instances:t.prop("count"),count:4,offset:0,uniforms:{miterMode:function(t,e){return"round"===e.join?2:1},miterLimit:t.prop("miterLimit"),scale:t.prop("scale"),scaleFract:t.prop("scaleFract"),translateFract:t.prop("translateFract"),translate:t.prop("translate"),thickness:t.prop("thickness"),dashPattern:t.prop("dashTexture"),opacity:t.prop("opacity"),pixelRatio:t.context("pixelRatio"),id:t.prop("id"),dashSize:t.prop("dashLength"),viewport:function(t,e){return[e.viewport.x,e.viewport.y,t.viewportWidth,t.viewportHeight]},depth:t.prop("depth")},blend:{enable:!0,color:[0,0,0,0],equation:{rgb:"add",alpha:"add"},func:{srcRGB:"src alpha",dstRGB:"one minus src alpha",srcAlpha:"one minus dst alpha",dstAlpha:"one"}},depth:{enable:function(t,e){return!e.overlay}},stencil:{enable:!1},scissor:{enable:!0,box:t.prop("viewport")},viewport:t.prop("viewport")},i=t(a({vert:o(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, aCoordFract, bCoordFract;\nattribute vec4 color;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float thickness, pixelRatio, id, depth;\nuniform vec4 viewport;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nvec2 project(vec2 position, vec2 positionFract, vec2 scale, vec2 scaleFract, vec2 translate, vec2 translateFract) {\n\t// the order is important\n\treturn position * scale + translate\n       + positionFract * scale + translateFract\n       + position * scaleFract\n       + positionFract * scaleFract;\n}\n\nvoid main() {\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineOffset = lineTop * 2. - 1.;\n\n\tvec2 diff = (bCoord + bCoordFract - aCoord - aCoordFract);\n\ttangent = normalize(diff * scale * viewport.zw);\n\tvec2 normal = vec2(-tangent.y, tangent.x);\n\n\tvec2 position = project(aCoord, aCoordFract, scale, scaleFract, translate, translateFract) * lineStart\n\t\t+ project(bCoord, bCoordFract, scale, scaleFract, translate, translateFract) * lineEnd\n\n\t\t+ thickness * normal * .5 * lineOffset / viewport.zw;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n}\n"]),frag:o(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\n\nuniform float dashSize, pixelRatio, thickness, opacity, id;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nvoid main() {\n\tfloat alpha = 1.;\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashSize) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t, .5)).r;\n\n\tgl_FragColor = fragColor;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]),attributes:{lineEnd:{buffer:r,divisor:0,stride:8,offset:0},lineTop:{buffer:r,divisor:0,stride:8,offset:4},aCoord:{buffer:t.prop("positionBuffer"),stride:8,offset:8,divisor:1},bCoord:{buffer:t.prop("positionBuffer"),stride:8,offset:16,divisor:1},aCoordFract:{buffer:t.prop("positionFractBuffer"),stride:8,offset:8,divisor:1},bCoordFract:{buffer:t.prop("positionFractBuffer"),stride:8,offset:16,divisor:1},color:{buffer:t.prop("colorBuffer"),stride:4,offset:0,divisor:1}}},n));try{e=t(a({cull:{enable:!0,face:"back"},vert:o(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, nextCoord, prevCoord;\nattribute vec4 aColor, bColor;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, translate;\nuniform float thickness, pixelRatio, id, depth;\nuniform vec4 viewport;\nuniform float miterLimit, miterMode;\n\nvarying vec4 fragColor;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 tangent;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nconst float REVERSE_THRESHOLD = -.875;\nconst float MIN_DIFF = 1e-6;\n\n// TODO: possible optimizations: avoid overcalculating all for vertices and calc just one instead\n// TODO: precalculate dot products, normalize things beforehead etc.\n// TODO: refactor to rectangular algorithm\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nbool isNaN( float val ){\n  return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true;\n}\n\nvoid main() {\n\tvec2 aCoord = aCoord, bCoord = bCoord, prevCoord = prevCoord, nextCoord = nextCoord;\n\n  vec2 adjustedScale;\n  adjustedScale.x = (abs(scale.x) < MIN_DIFF) ? MIN_DIFF : scale.x;\n  adjustedScale.y = (abs(scale.y) < MIN_DIFF) ? MIN_DIFF : scale.y;\n\n  vec2 scaleRatio = adjustedScale * viewport.zw;\n\tvec2 normalWidth = thickness / scaleRatio;\n\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineBot = 1. - lineTop;\n\n\tfragColor = (lineStart * aColor + lineEnd * bColor) / 255.;\n\n\tif (isNaN(aCoord.x) || isNaN(aCoord.y) || isNaN(bCoord.x) || isNaN(bCoord.y)) return;\n\n\tif (aCoord == prevCoord) prevCoord = aCoord + normalize(bCoord - aCoord);\n\tif (bCoord == nextCoord) nextCoord = bCoord - normalize(bCoord - aCoord);\n\n\tvec2 prevDiff = aCoord - prevCoord;\n\tvec2 currDiff = bCoord - aCoord;\n\tvec2 nextDiff = nextCoord - bCoord;\n\n\tvec2 prevTangent = normalize(prevDiff * scaleRatio);\n\tvec2 currTangent = normalize(currDiff * scaleRatio);\n\tvec2 nextTangent = normalize(nextDiff * scaleRatio);\n\n\tvec2 prevNormal = vec2(-prevTangent.y, prevTangent.x);\n\tvec2 currNormal = vec2(-currTangent.y, currTangent.x);\n\tvec2 nextNormal = vec2(-nextTangent.y, nextTangent.x);\n\n\tvec2 startJoinDirection = normalize(prevTangent - currTangent);\n\tvec2 endJoinDirection = normalize(currTangent - nextTangent);\n\n\t// collapsed/unidirectional segment cases\n\t// FIXME: there should be more elegant solution\n\tvec2 prevTanDiff = abs(prevTangent - currTangent);\n\tvec2 nextTanDiff = abs(nextTangent - currTangent);\n\tif (max(prevTanDiff.x, prevTanDiff.y) < MIN_DIFF) {\n\t\tstartJoinDirection = currNormal;\n\t}\n\tif (max(nextTanDiff.x, nextTanDiff.y) < MIN_DIFF) {\n\t\tendJoinDirection = currNormal;\n\t}\n\tif (aCoord == bCoord) {\n\t\tendJoinDirection = startJoinDirection;\n\t\tcurrNormal = prevNormal;\n\t\tcurrTangent = prevTangent;\n\t}\n\n\ttangent = currTangent;\n\n\t//calculate join shifts relative to normals\n\tfloat startJoinShift = dot(currNormal, startJoinDirection);\n\tfloat endJoinShift = dot(currNormal, endJoinDirection);\n\n\tfloat startMiterRatio = abs(1. / startJoinShift);\n\tfloat endMiterRatio = abs(1. / endJoinShift);\n\n\tvec2 startJoin = startJoinDirection * startMiterRatio;\n\tvec2 endJoin = endJoinDirection * endMiterRatio;\n\n\tvec2 startTopJoin, startBotJoin, endTopJoin, endBotJoin;\n\tstartTopJoin = sign(startJoinShift) * startJoin * .5;\n\tstartBotJoin = -startTopJoin;\n\n\tendTopJoin = sign(endJoinShift) * endJoin * .5;\n\tendBotJoin = -endTopJoin;\n\n\tvec2 aTopCoord = aCoord + normalWidth * startTopJoin;\n\tvec2 bTopCoord = bCoord + normalWidth * endTopJoin;\n\tvec2 aBotCoord = aCoord + normalWidth * startBotJoin;\n\tvec2 bBotCoord = bCoord + normalWidth * endBotJoin;\n\n\t//miter anti-clipping\n\tfloat baClipping = distToLine(bCoord, aCoord, aBotCoord) / dot(normalize(normalWidth * endBotJoin), normalize(normalWidth.yx * vec2(-startBotJoin.y, startBotJoin.x)));\n\tfloat abClipping = distToLine(aCoord, bCoord, bTopCoord) / dot(normalize(normalWidth * startBotJoin), normalize(normalWidth.yx * vec2(-endBotJoin.y, endBotJoin.x)));\n\n\t//prevent close to reverse direction switch\n\tbool prevReverse = dot(currTangent, prevTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, prevNormal)) * min(length(prevDiff), length(currDiff)) <  length(normalWidth * currNormal);\n\tbool nextReverse = dot(currTangent, nextTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, nextNormal)) * min(length(nextDiff), length(currDiff)) <  length(normalWidth * currNormal);\n\n\tif (prevReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * startJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / startMiterRatio, 1.);\n\t\taBotCoord = aCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\taTopCoord = aCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!nextReverse && baClipping > 0. && baClipping < length(normalWidth * endBotJoin)) {\n\t\t//handle miter clipping\n\t\tbTopCoord -= normalWidth * endTopJoin;\n\t\tbTopCoord += normalize(endTopJoin * normalWidth) * baClipping;\n\t}\n\n\tif (nextReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * endJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / endMiterRatio, 1.);\n\t\tbBotCoord = bCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\tbTopCoord = bCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!prevReverse && abClipping > 0. && abClipping < length(normalWidth * startBotJoin)) {\n\t\t//handle miter clipping\n\t\taBotCoord -= normalWidth * startBotJoin;\n\t\taBotCoord += normalize(startBotJoin * normalWidth) * abClipping;\n\t}\n\n\tvec2 aTopPosition = (aTopCoord) * adjustedScale + translate;\n\tvec2 aBotPosition = (aBotCoord) * adjustedScale + translate;\n\n\tvec2 bTopPosition = (bTopCoord) * adjustedScale + translate;\n\tvec2 bBotPosition = (bBotCoord) * adjustedScale + translate;\n\n\t//position is normalized 0..1 coord on the screen\n\tvec2 position = (aTopPosition * lineTop + aBotPosition * lineBot) * lineStart + (bTopPosition * lineTop + bBotPosition * lineBot) * lineEnd;\n\n\tstartCoord = aCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\tendCoord = bCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\n\tgl_Position = vec4(position  * 2.0 - 1.0, depth, 1);\n\n\tenableStartMiter = step(dot(currTangent, prevTangent), .5);\n\tenableEndMiter = step(dot(currTangent, nextTangent), .5);\n\n\t//bevel miter cutoffs\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * miterLimit * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * miterLimit * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x)  / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n\n\t//round miter cutoffs\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * abs(dot(startJoinDirection, currNormal)) * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * abs(dot(endJoinDirection, currNormal)) * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x)  / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n}\n"]),frag:o(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\nuniform float dashSize, pixelRatio, thickness, opacity, id, miterMode;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nvoid main() {\n\tfloat alpha = 1., distToStart, distToEnd;\n\tfloat cutoff = thickness * .5;\n\n\t//bevel miter\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToStart + 1., 0.), 1.);\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToEnd + 1., 0.), 1.);\n\t\t}\n\t}\n\n\t// round miter\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - startCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - endCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\t}\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashSize) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t, .5)).r;\n\n\tgl_FragColor = fragColor;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]),attributes:{lineEnd:{buffer:r,divisor:0,stride:8,offset:0},lineTop:{buffer:r,divisor:0,stride:8,offset:4},aColor:{buffer:t.prop("colorBuffer"),stride:4,offset:0,divisor:1},bColor:{buffer:t.prop("colorBuffer"),stride:4,offset:4,divisor:1},prevCoord:{buffer:t.prop("positionBuffer"),stride:8,offset:0,divisor:1},aCoord:{buffer:t.prop("positionBuffer"),stride:8,offset:8,divisor:1},bCoord:{buffer:t.prop("positionBuffer"),stride:8,offset:16,divisor:1},nextCoord:{buffer:t.prop("positionBuffer"),stride:8,offset:24,divisor:1}}},n))}catch(t){e=i}return{fill:t({primitive:"triangle",elements:function(t,e){return e.triangles},offset:0,vert:o(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\n\nuniform vec4 color;\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio, id;\nuniform vec4 viewport;\nuniform float opacity;\n\nvarying vec4 fragColor;\n\nconst float MAX_LINES = 256.;\n\nvoid main() {\n\tfloat depth = (MAX_LINES - 4. - id) / (MAX_LINES);\n\n\tvec2 position = position * scale + translate\n       + positionFract * scale + translateFract\n       + position * scaleFract\n       + positionFract * scaleFract;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n\tfragColor.a *= opacity;\n}\n"]),frag:o(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n\tgl_FragColor = fragColor;\n}\n"]),uniforms:{scale:t.prop("scale"),color:t.prop("fill"),scaleFract:t.prop("scaleFract"),translateFract:t.prop("translateFract"),translate:t.prop("translate"),opacity:t.prop("opacity"),pixelRatio:t.context("pixelRatio"),id:t.prop("id"),viewport:function(t,e){return[e.viewport.x,e.viewport.y,t.viewportWidth,t.viewportHeight]}},attributes:{position:{buffer:t.prop("positionBuffer"),stride:8,offset:8},positionFract:{buffer:t.prop("positionFractBuffer"),stride:8,offset:8}},blend:n.blend,depth:{enable:!1},scissor:n.scissor,stencil:n.stencil,viewport:n.viewport}),rect:i,miter:e}},v.defaults={dashes:null,join:"miter",miterLimit:1,thickness:10,cap:"square",color:"black",opacity:1,overlay:!1,viewport:null,range:null,close:!1,fill:null},v.prototype.render=function(){for(var t,e=[],r=arguments.length;r--;)e[r]=arguments[r];e.length&&(t=this).update.apply(t,e),this.draw()},v.prototype.draw=function(){for(var t=this,e=[],r=arguments.length;r--;)e[r]=arguments[r];return(e.length?e:this.passes).forEach(function(e,r){var n;if(e&&Array.isArray(e))return(n=t).draw.apply(n,e);"number"==typeof e&&(e=t.passes[e]),e&&e.count>1&&e.opacity&&(t.regl._refresh(),e.fill&&e.triangles&&e.triangles.length>2&&t.shaders.fill(e),e.thickness&&(e.scale[0]*e.viewport.width>v.precisionThreshold||e.scale[1]*e.viewport.height>v.precisionThreshold?t.shaders.rect(e):"rect"===e.join||!e.join&&(e.thickness<=2||e.count>=v.maxPoints)?t.shaders.rect(e):t.shaders.miter(e)))}),this},v.prototype.update=function(t){var e=this;if(t){null!=t.length?"number"==typeof t[0]&&(t=[{positions:t}]):Array.isArray(t)||(t=[t]);var r=this.regl,o=this.gl;if(t.forEach(function(t,h){var d=e.passes[h];if(void 0!==t)if(null!==t){if("number"==typeof t[0]&&(t={positions:t}),t=s(t,{positions:"positions points data coords",thickness:"thickness lineWidth lineWidths line-width linewidth width stroke-width strokewidth strokeWidth",join:"lineJoin linejoin join type mode",miterLimit:"miterlimit miterLimit",dashes:"dash dashes dasharray dash-array dashArray",color:"color colour stroke colors colours stroke-color strokeColor",fill:"fill fill-color fillColor",opacity:"alpha opacity",overlay:"overlay crease overlap intersect",close:"closed close closed-path closePath",range:"range dataBox",viewport:"viewport viewBox",hole:"holes hole hollow"}),d||(e.passes[h]=d={id:h,scale:null,scaleFract:null,translate:null,translateFract:null,count:0,hole:[],depth:0,dashLength:1,dashTexture:r.texture({channels:1,data:new Uint8Array([255]),width:1,height:1,mag:"linear",min:"linear"}),colorBuffer:r.buffer({usage:"dynamic",type:"uint8",data:new Uint8Array}),positionBuffer:r.buffer({usage:"dynamic",type:"float",data:new Uint8Array}),positionFractBuffer:r.buffer({usage:"dynamic",type:"float",data:new Uint8Array})},t=a({},v.defaults,t)),null!=t.thickness&&(d.thickness=parseFloat(t.thickness)),null!=t.opacity&&(d.opacity=parseFloat(t.opacity)),null!=t.miterLimit&&(d.miterLimit=parseFloat(t.miterLimit)),null!=t.overlay&&(d.overlay=!!t.overlay,h<v.maxLines&&(d.depth=2*(v.maxLines-1-h%v.maxLines)/v.maxLines-1)),null!=t.join&&(d.join=t.join),null!=t.hole&&(d.hole=t.hole),null!=t.fill&&(d.fill=t.fill?n(t.fill,"uint8"):null),null!=t.viewport&&(d.viewport=g(t.viewport)),d.viewport||(d.viewport=g([o.drawingBufferWidth,o.drawingBufferHeight])),null!=t.close&&(d.close=t.close),null===t.positions&&(t.positions=[]),t.positions){var m,y;if(t.positions.x&&t.positions.y){var x=t.positions.x,b=t.positions.y;y=d.count=Math.max(x.length,b.length),m=new Float64Array(2*y);for(var _=0;_<y;_++)m[2*_]=x[_],m[2*_+1]=b[_]}else m=l(t.positions,"float64"),y=d.count=Math.floor(m.length/2);var w=d.bounds=i(m,2);if(d.fill){for(var k=[],A={},M=0,T=0,S=0,E=d.count;T<E;T++){var C=m[2*T],L=m[2*T+1];isNaN(C)||isNaN(L)||null==C||null==L?(C=m[2*M],L=m[2*M+1],A[T]=M):M=T,k[S++]=C,k[S++]=L}for(var z=c(k,d.hole||[]),O=0,I=z.length;O<I;O++)null!=A[z[O]]&&(z[O]=A[z[O]]);d.triangles=z}var D=new Float64Array(m);u(D,2,w);var P=new Float64Array(2*y+6);d.close?m[0]===m[2*y-2]&&m[1]===m[2*y-1]?(P[0]=D[2*y-4],P[1]=D[2*y-3]):(P[0]=D[2*y-2],P[1]=D[2*y-1]):(P[0]=D[0],P[1]=D[1]),P.set(D,2),d.close?m[0]===m[2*y-2]&&m[1]===m[2*y-1]?(P[2*y+2]=D[2],P[2*y+3]=D[3],d.count-=1):(P[2*y+2]=D[0],P[2*y+3]=D[1],P[2*y+4]=D[2],P[2*y+5]=D[3]):(P[2*y+2]=D[2*y-2],P[2*y+3]=D[2*y-1],P[2*y+4]=D[2*y-2],P[2*y+5]=D[2*y-1]),d.positionBuffer(f(P)),d.positionFractBuffer(p(P))}if(t.range?d.range=t.range:d.range||(d.range=d.bounds),(t.range||t.positions)&&d.count){var R=d.bounds,F=R[2]-R[0],B=R[3]-R[1],N=d.range[2]-d.range[0],j=d.range[3]-d.range[1];d.scale=[F/N,B/j],d.translate=[-d.range[0]/N+R[0]/N||0,-d.range[1]/j+R[1]/j||0],d.scaleFract=p(d.scale),d.translateFract=p(d.translate)}if(t.dashes){var V,U=0;if(!t.dashes||t.dashes.length<2)U=1,V=new Uint8Array([255,255,255,255,255,255,255,255]);else{U=0;for(var q=0;q<t.dashes.length;++q)U+=t.dashes[q];V=new Uint8Array(U*v.dashMult);for(var H=0,G=255,Y=0;Y<2;Y++)for(var W=0;W<t.dashes.length;++W){for(var X=0,Z=t.dashes[W]*v.dashMult*.5;X<Z;++X)V[H++]=G;G^=255}}d.dashLength=U,d.dashTexture({channels:1,data:V,width:V.length,height:1,mag:"linear",min:"linear"},0,0)}if(t.color){var $=d.count,J=t.color;J||(J="transparent");var K=new Uint8Array(4*$+4);if(Array.isArray(J)&&"number"!=typeof J[0]){for(var Q=0;Q<$;Q++){var tt=n(J[Q],"uint8");K.set(tt,4*Q)}K.set(n(J[0],"uint8"),4*$)}else for(var et=n(J,"uint8"),rt=0;rt<$+1;rt++)K.set(et,4*rt);d.colorBuffer({usage:"dynamic",type:"uint8",data:K})}}else e.passes[h]=null}),t.length<this.passes.length){for(var h=t.length;h<this.passes.length;h++){var d=e.passes[h];d&&(d.colorBuffer.destroy(),d.positionBuffer.destroy(),d.dashTexture.destroy())}this.passes.length=t.length}for(var m=[],y=0;y<this.passes.length;y++)null!==e.passes[y]&&m.push(e.passes[y]);return this.passes=m,this}},v.prototype.destroy=function(){return this.passes.forEach(function(t){t.colorBuffer.destroy(),t.positionBuffer.destroy(),t.dashTexture.destroy()}),this.passes.length=0,this}},{"array-bounds":53,"array-normalize":54,"color-normalize":108,earcut:159,"es6-weak-map":213,"flatten-vertex-data":220,glslify:398,"object-assign":443,"parse-rect":448,"pick-by-alias":454,"to-float32":519}],481:[function(t,e,r){"use strict";function n(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var r=[],n=!0,i=!1,a=void 0;try{for(var o,s=t[Symbol.iterator]();!(n=(o=s.next()).done)&&(r.push(o.value),!e||r.length!==e);n=!0);}catch(t){i=!0,a=t}finally{try{n||null==s.return||s.return()}finally{if(i)throw a}}return r}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function i(t){return function(t){if(Array.isArray(t)){for(var e=0,r=new Array(t.length);e<t.length;e++)r[e]=t[e];return r}}(t)||function(t){if(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t))return Array.from(t)}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}var a=t("color-normalize"),o=t("array-bounds"),s=t("color-id"),l=t("point-cluster"),c=t("object-assign"),u=t("glslify"),h=t("pick-by-alias"),f=t("update-diff"),p=t("flatten-vertex-data"),d=t("is-iexplorer"),g=t("to-float32"),v=t("parse-rect"),m=y;function y(t,e){var r=this;if(!(this instanceof y))return new y(t,e);"function"==typeof t?(e||(e={}),e.regl=t):(e=t,t=null),e&&e.length&&(e.positions=e);var n,i=(t=e.regl)._gl,a=[];this.tooManyColors=d,n=t.texture({data:new Uint8Array(1020),width:255,height:1,type:"uint8",format:"rgba",wrapS:"clamp",wrapT:"clamp",mag:"nearest",min:"nearest"}),c(this,{regl:t,gl:i,groups:[],markerCache:[null],markerTextures:[null],palette:a,paletteIds:{},paletteTexture:n,maxColors:255,maxSize:100,canvas:i.canvas}),this.update(e);var o={uniforms:{pixelRatio:t.context("pixelRatio"),palette:n,paletteSize:function(t,e){return[r.tooManyColors?0:255,n.height]},scale:t.prop("scale"),scaleFract:t.prop("scaleFract"),translate:t.prop("translate"),translateFract:t.prop("translateFract"),opacity:t.prop("opacity"),marker:t.prop("markerTexture")},attributes:{x:function(t,e){return e.xAttr||{buffer:e.positionBuffer,stride:8,offset:0}},y:function(t,e){return e.yAttr||{buffer:e.positionBuffer,stride:8,offset:4}},xFract:function(t,e){return e.xAttr?{constant:[0,0]}:{buffer:e.positionFractBuffer,stride:8,offset:0}},yFract:function(t,e){return e.yAttr?{constant:[0,0]}:{buffer:e.positionFractBuffer,stride:8,offset:4}},size:function(t,e){return e.size.length?{buffer:e.sizeBuffer,stride:2,offset:0}:{constant:[Math.round(255*e.size/r.maxSize)]}},borderSize:function(t,e){return e.borderSize.length?{buffer:e.sizeBuffer,stride:2,offset:1}:{constant:[Math.round(255*e.borderSize/r.maxSize)]}},colorId:function(t,e){return e.color.length?{buffer:e.colorBuffer,stride:r.tooManyColors?8:4,offset:0}:{constant:r.tooManyColors?a.slice(4*e.color,4*e.color+4):[e.color]}},borderColorId:function(t,e){return e.borderColor.length?{buffer:e.colorBuffer,stride:r.tooManyColors?8:4,offset:r.tooManyColors?4:2}:{constant:r.tooManyColors?a.slice(4*e.borderColor,4*e.borderColor+4):[e.borderColor]}},isActive:function(t,e){return!0===e.activation?{constant:[1]}:e.activation?e.activation:{constant:[0]}}},blend:{enable:!0,color:[0,0,0,1],func:{srcRGB:"src alpha",dstRGB:"one minus src alpha",srcAlpha:"one minus dst alpha",dstAlpha:"one"}},scissor:{enable:!0,box:t.prop("viewport")},viewport:t.prop("viewport"),stencil:{enable:!1},depth:{enable:!1},elements:t.prop("elements"),count:t.prop("count"),offset:t.prop("offset"),primitive:"points"},s=c({},o);s.frag=u(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragWidth, fragBorderColorLevel, fragColorLevel;\n\nuniform sampler2D marker;\nuniform float pixelRatio, opacity;\n\nfloat smoothStep(float x, float y) {\n  return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n  float dist = texture2D(marker, gl_PointCoord).r, delta = fragWidth;\n\n  // max-distance alpha\n  if (dist < 0.003) discard;\n\n  // null-border case\n  if (fragBorderColorLevel == fragColorLevel || fragBorderColor.a == 0.) {\n    float colorAmt = smoothstep(.5 - delta, .5 + delta, dist);\n    gl_FragColor = vec4(fragColor.rgb, colorAmt * fragColor.a * opacity);\n  }\n  else {\n    float borderColorAmt = smoothstep(fragBorderColorLevel - delta, fragBorderColorLevel + delta, dist);\n    float colorAmt = smoothstep(fragColorLevel - delta, fragColorLevel + delta, dist);\n\n    vec4 color = fragBorderColor;\n    color.a *= borderColorAmt;\n    color = mix(color, fragColor, colorAmt);\n    color.a *= opacity;\n\n    gl_FragColor = color;\n  }\n\n}\n"]),s.vert=u(["precision mediump float;\n#define GLSLIFY 1\n\nattribute float x, y, xFract, yFract;\nattribute float size, borderSize;\nattribute vec4 colorId, borderColorId;\nattribute float isActive;\n\nuniform vec2 scale, scaleFract, translate, translateFract, paletteSize;\nuniform float pixelRatio;\nuniform sampler2D palette;\n\nconst float maxSize = 100.;\nconst float borderLevel = .5;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragPointSize, fragBorderRadius, fragWidth, fragBorderColorLevel, fragColorLevel;\n\nbool isDirect = (paletteSize.x < 1.);\n\nvec4 getColor(vec4 id) {\n  return isDirect ? id / 255. : texture2D(palette,\n    vec2(\n      (id.x + .5) / paletteSize.x,\n      (id.y + .5) / paletteSize.y\n    )\n  );\n}\n\nvoid main() {\n  if (isActive == 0.) return;\n\n  vec2 position = vec2(x, y);\n  vec2 positionFract = vec2(xFract, yFract);\n\n  vec4 color = getColor(colorId);\n  vec4 borderColor = getColor(borderColorId);\n\n  float size = size * maxSize / 255.;\n  float borderSize = borderSize * maxSize / 255.;\n\n  gl_PointSize = 2. * size * pixelRatio;\n  fragPointSize = size * pixelRatio;\n\n  vec2 pos = (position + translate) * scale\n      + (positionFract + translateFract) * scale\n      + (position + translate) * scaleFract\n      + (positionFract + translateFract) * scaleFract;\n\n  gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n  fragColor = color;\n  fragBorderColor = borderColor;\n  fragWidth = 1. / gl_PointSize;\n\n  fragBorderColorLevel = clamp(borderLevel - borderLevel * borderSize / size, 0., 1.);\n  fragColorLevel = clamp(borderLevel + (1. - borderLevel) * borderSize / size, 0., 1.);\n}"]),this.drawMarker=t(s);var l=c({},o);l.frag=u(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\n\nuniform float opacity;\nvarying float fragBorderRadius, fragWidth;\n\nfloat smoothStep(float edge0, float edge1, float x) {\n\tfloat t;\n\tt = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);\n\treturn t * t * (3.0 - 2.0 * t);\n}\n\nvoid main() {\n\tfloat radius, alpha = 1.0, delta = fragWidth;\n\n\tradius = length(2.0 * gl_PointCoord.xy - 1.0);\n\n\tif (radius > 1.0 + delta) {\n\t\tdiscard;\n\t}\n\n\talpha -= smoothstep(1.0 - delta, 1.0 + delta, radius);\n\n\tfloat borderRadius = fragBorderRadius;\n\tfloat ratio = smoothstep(borderRadius - delta, borderRadius + delta, radius);\n\tvec4 color = mix(fragColor, fragBorderColor, ratio);\n\tcolor.a *= alpha * opacity;\n\tgl_FragColor = color;\n}\n"]),l.vert=u(["precision highp float;\n#define GLSLIFY 1\n\nattribute float x, y, xFract, yFract;\nattribute float size, borderSize;\nattribute vec4 colorId, borderColorId;\nattribute float isActive;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio;\nuniform sampler2D palette;\nuniform vec2 paletteSize;\n\nconst float maxSize = 100.;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth;\n\nbool isDirect = (paletteSize.x < 1.);\n\nvec4 getColor(vec4 id) {\n  return isDirect ? id / 255. : texture2D(palette,\n    vec2(\n      (id.x + .5) / paletteSize.x,\n      (id.y + .5) / paletteSize.y\n    )\n  );\n}\n\nvoid main() {\n  // ignore inactive points\n  if (isActive == 0.) return;\n\n  vec2 position = vec2(x, y);\n  vec2 positionFract = vec2(xFract, yFract);\n\n  vec4 color = getColor(colorId);\n  vec4 borderColor = getColor(borderColorId);\n\n  float size = size * maxSize / 255.;\n  float borderSize = borderSize * maxSize / 255.;\n\n  gl_PointSize = (size + borderSize) * pixelRatio;\n\n  vec2 pos = (position + translate) * scale\n      + (positionFract + translateFract) * scale\n      + (position + translate) * scaleFract\n      + (positionFract + translateFract) * scaleFract;\n\n  gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n  fragBorderRadius = 1. - 2. * borderSize / (size + borderSize);\n  fragColor = color;\n  fragBorderColor = borderColor.a == 0. || borderSize == 0. ? vec4(color.rgb, 0.) : borderColor;\n  fragWidth = 1. / gl_PointSize;\n}\n"]),d&&(l.frag=l.frag.replace("smoothstep","smoothStep"),s.frag=s.frag.replace("smoothstep","smoothStep")),this.drawCircle=t(l)}y.defaults={color:"black",borderColor:"transparent",borderSize:0,size:12,opacity:1,marker:void 0,viewport:null,range:null,pixelSize:null,count:0,offset:0,bounds:null,positions:[],snap:1e4},y.prototype.render=function(){return arguments.length&&this.update.apply(this,arguments),this.draw(),this},y.prototype.draw=function(){for(var t=this,e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];var i=this.groups;if(1===r.length&&Array.isArray(r[0])&&(null===r[0][0]||Array.isArray(r[0][0]))&&(r=r[0]),this.regl._refresh(),r.length)for(var a=0;a<r.length;a++)this.drawItem(a,r[a]);else i.forEach(function(e,r){t.drawItem(r)});return this},y.prototype.drawItem=function(t,e){var r=this.groups,n=r[t];if("number"==typeof e&&(t=e,n=r[e],e=null),n&&n.count&&n.opacity){n.activation[0]&&this.drawCircle(this.getMarkerDrawOptions(0,n,e));for(var a=[],o=1;o<n.activation.length;o++)n.activation[o]&&(!0===n.activation[o]||n.activation[o].data.length)&&a.push.apply(a,i(this.getMarkerDrawOptions(o,n,e)));a.length&&this.drawMarker(a)}},y.prototype.getMarkerDrawOptions=function(t,e,r){var i=e.range,a=e.tree,o=e.viewport,s=e.activation,l=e.selectionBuffer,u=e.count;this.regl;if(!a)return r?[c({},e,{markerTexture:this.markerTextures[t],activation:s[t],count:r.length,elements:r,offset:0})]:[c({},e,{markerTexture:this.markerTextures[t],activation:s[t],offset:0})];var h=[],f=a.range(i,{lod:!0,px:[(i[2]-i[0])/o.width,(i[3]-i[1])/o.height]});if(r){for(var p=s[t].data,d=new Uint8Array(u),g=0;g<r.length;g++){var v=r[g];d[v]=p?p[v]:1}l.subdata(d)}for(var m=f.length;m--;){var y=n(f[m],2),x=y[0],b=y[1];h.push(c({},e,{markerTexture:this.markerTextures[t],activation:r?l:s[t],offset:x,count:b-x}))}return h},y.prototype.update=function(){for(var t=this,e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];if(r.length){1===r.length&&Array.isArray(r[0])&&(r=r[0]);var i=this.groups,a=this.gl,s=this.regl,u=this.maxSize,d=this.maxColors,m=this.palette;this.groups=i=r.map(function(e,r){var n=i[r];if(void 0===e)return n;null===e?e={positions:null}:"function"==typeof e?e={ondraw:e}:"number"==typeof e[0]&&(e={positions:e}),null===(e=h(e,{positions:"positions data points",snap:"snap cluster lod tree",size:"sizes size radius",borderSize:"borderSizes borderSize border-size bordersize borderWidth borderWidths border-width borderwidth stroke-width strokeWidth strokewidth outline",color:"colors color fill fill-color fillColor",borderColor:"borderColors borderColor stroke stroke-color strokeColor",marker:"markers marker shape",range:"range dataBox databox",viewport:"viewport viewPort viewBox viewbox",opacity:"opacity alpha transparency",bounds:"bound bounds boundaries limits",tooManyColors:"tooManyColors palette paletteMode optimizePalette enablePalette"})).positions&&(e.positions=[]),null!=e.tooManyColors&&(t.tooManyColors=e.tooManyColors),n||(i[r]=n={id:r,scale:null,translate:null,scaleFract:null,translateFract:null,activation:[],selectionBuffer:s.buffer({data:new Uint8Array(0),usage:"stream",type:"uint8"}),sizeBuffer:s.buffer({data:new Uint8Array(0),usage:"dynamic",type:"uint8"}),colorBuffer:s.buffer({data:new Uint8Array(0),usage:"dynamic",type:"uint8"}),positionBuffer:s.buffer({data:new Uint8Array(0),usage:"dynamic",type:"float"}),positionFractBuffer:s.buffer({data:new Uint8Array(0),usage:"dynamic",type:"float"})},e=c({},y.defaults,e)),!e.positions||"marker"in e||(e.marker=n.marker,delete n.marker),!e.marker||"positions"in e||(e.positions=n.positions,delete n.positions);var x=0,b=0;if(f(n,e,[{snap:!0,size:function(t,e){return null==t&&(t=y.defaults.size),x+=t&&t.length?1:0,t},borderSize:function(t,e){return null==t&&(t=y.defaults.borderSize),x+=t&&t.length?1:0,t},opacity:parseFloat,color:function(e,r){return null==e&&(e=y.defaults.color),e=t.updateColor(e),b++,e},borderColor:function(e,r){return null==e&&(e=y.defaults.borderColor),e=t.updateColor(e),b++,e},bounds:function(t,e,r){return"range"in r||(r.range=null),t},positions:function(t,e,r){var n=e.snap,i=e.positionBuffer,a=e.positionFractBuffer,c=e.selectionBuffer;if(t.x||t.y)return t.x.length?e.xAttr={buffer:s.buffer(t.x),offset:0,stride:4,count:t.x.length}:e.xAttr={buffer:t.x.buffer,offset:4*t.x.offset||0,stride:4*(t.x.stride||1),count:t.x.count},t.y.length?e.yAttr={buffer:s.buffer(t.y),offset:0,stride:4,count:t.y.length}:e.yAttr={buffer:t.y.buffer,offset:4*t.y.offset||0,stride:4*(t.y.stride||1),count:t.y.count},e.count=Math.max(e.xAttr.count,e.yAttr.count),t;t=p(t,"float64");var u=e.count=Math.floor(t.length/2),h=e.bounds=u?o(t,2):null;if(r.range||e.range||(delete e.range,r.range=h),r.marker||e.marker||(delete e.marker,r.marker=null),n&&(!0===n||u>n)?e.tree=l(t,{bounds:h}):n&&n.length&&(e.tree=n),e.tree){var f={primitive:"points",usage:"static",data:e.tree,type:"uint32"};e.elements?e.elements(f):e.elements=s.elements(f)}return i({data:g.float(t),usage:"dynamic"}),a({data:g.fract(t),usage:"dynamic"}),c({data:new Uint8Array(u),type:"uint8",usage:"stream"}),t}},{marker:function(e,r,n){var i=r.activation;if(i.forEach(function(t){return t&&t.destroy&&t.destroy()}),i.length=0,e&&"number"!=typeof e[0]){for(var a=[],o=0,l=Math.min(e.length,r.count);o<l;o++){var c=t.addMarker(e[o]);a[c]||(a[c]=new Uint8Array(r.count)),a[c][o]=1}for(var u=0;u<a.length;u++)if(a[u]){var h={data:a[u],type:"uint8",usage:"static"};i[u]?i[u](h):i[u]=s.buffer(h),i[u].data=a[u]}}else{i[t.addMarker(e)]=!0}return e},range:function(t,e,r){var n=e.bounds;if(n)return t||(t=n),e.scale=[1/(t[2]-t[0]),1/(t[3]-t[1])],e.translate=[-t[0],-t[1]],e.scaleFract=g.fract(e.scale),e.translateFract=g.fract(e.translate),t},viewport:function(t){return v(t||[a.drawingBufferWidth,a.drawingBufferHeight])}}]),x){var _=n,w=_.count,k=_.size,A=_.borderSize,M=_.sizeBuffer,T=new Uint8Array(2*w);if(k.length||A.length)for(var S=0;S<w;S++)T[2*S]=Math.round(255*(null==k[S]?k:k[S])/u),T[2*S+1]=Math.round(255*(null==A[S]?A:A[S])/u);M({data:T,usage:"dynamic"})}if(b){var E,C=n,L=C.count,z=C.color,O=C.borderColor,I=C.colorBuffer;if(t.tooManyColors){if(z.length||O.length){E=new Uint8Array(8*L);for(var D=0;D<L;D++){var P=z[D];E[8*D]=m[4*P],E[8*D+1]=m[4*P+1],E[8*D+2]=m[4*P+2],E[8*D+3]=m[4*P+3];var R=O[D];E[8*D+4]=m[4*R],E[8*D+5]=m[4*R+1],E[8*D+6]=m[4*R+2],E[8*D+7]=m[4*R+3]}}}else if(z.length||O.length){E=new Uint8Array(4*L+2);for(var F=0;F<L;F++)null!=z[F]&&(E[4*F]=z[F]%d,E[4*F+1]=Math.floor(z[F]/d)),null!=O[F]&&(E[4*F+2]=O[F]%d,E[4*F+3]=Math.floor(O[F]/d))}I({data:E||new Uint8Array(0),type:"uint8",usage:"dynamic"})}return n})}},y.prototype.addMarker=function(t){var e,r=this.markerTextures,n=this.regl,i=this.markerCache,a=null==t?0:i.indexOf(t);if(a>=0)return a;if(t instanceof Uint8Array||t instanceof Uint8ClampedArray)e=t;else{e=new Uint8Array(t.length);for(var o=0,s=t.length;o<s;o++)e[o]=255*t[o]}var l=Math.floor(Math.sqrt(e.length));return a=r.length,i.push(t),r.push(n.texture({channels:1,data:e,radius:l,mag:"linear",min:"linear"})),a},y.prototype.updateColor=function(t){var e=this.paletteIds,r=this.palette,n=this.maxColors;Array.isArray(t)||(t=[t]);var i=[];if("number"==typeof t[0]){var o=[];if(Array.isArray(t))for(var l=0;l<t.length;l+=4)o.push(t.slice(l,l+4));else for(var c=0;c<t.length;c+=4)o.push(t.subarray(c,c+4));t=o}for(var u=0;u<t.length;u++){var h=t[u];h=a(h,"uint8");var f=s(h,!1);if(null==e[f]){var p=r.length;e[f]=Math.floor(p/4),r[p]=h[0],r[p+1]=h[1],r[p+2]=h[2],r[p+3]=h[3]}i[u]=e[f]}return!this.tooManyColors&&r.length>4*n&&(this.tooManyColors=!0),this.updatePalette(r),1===i.length?i[0]:i},y.prototype.updatePalette=function(t){if(!this.tooManyColors){var e=this.maxColors,r=this.paletteTexture,n=Math.ceil(.25*t.length/e);if(n>1)for(var i=.25*(t=t.slice()).length%e;i<n*e;i++)t.push(0,0,0,0);r.height<n&&r.resize(e,n),r.subimage({width:Math.min(.25*t.length,e),height:n,data:t},0,0)}},y.prototype.destroy=function(){return this.groups.forEach(function(t){t.sizeBuffer.destroy(),t.positionBuffer.destroy(),t.positionFractBuffer.destroy(),t.colorBuffer.destroy(),t.activation.forEach(function(t){return t&&t.destroy&&t.destroy()}),t.selectionBuffer.destroy(),t.elements&&t.elements.destroy()}),this.groups.length=0,this.paletteTexture.destroy(),this.markerTextures.forEach(function(t){return t&&t.destroy&&t.destroy()}),this};var x=t("object-assign");e.exports=function(t,e){var r=new m(t,e),n=r.render.bind(r);return x(n,{render:n,update:r.update.bind(r),draw:r.draw.bind(r),destroy:r.destroy.bind(r),regl:r.regl,gl:r.gl,canvas:r.gl.canvas,groups:r.groups,markers:r.markerCache,palette:r.palette}),n}},{"array-bounds":53,"color-id":106,"color-normalize":108,"flatten-vertex-data":220,glslify:398,"is-iexplorer":408,"object-assign":443,"parse-rect":448,"pick-by-alias":454,"point-cluster":458,"to-float32":519,"update-diff":530}],482:[function(t,e,r){"use strict";var n=t("regl-scatter2d"),i=t("pick-by-alias"),a=t("array-bounds"),o=t("raf"),s=t("array-range"),l=t("parse-rect"),c=t("flatten-vertex-data");function u(t,e){if(!(this instanceof u))return new u(t,e);this.traces=[],this.passes={},this.regl=t,this.scatter=n(t),this.canvas=this.scatter.canvas}function h(t,e,r){return(null!=t.id?t.id:t)<<16|(255&e)<<8|255&r}function f(t,e,r){var n,i,a,o,s=t[e],l=t[r];return s.length>2?(s[0],s[2],n=s[1],i=s[3]):s.length?(n=s[0],i=s[1]):(s.x,n=s.y,s.x+s.width,i=s.y+s.height),l.length>2?(a=l[0],o=l[2],l[1],l[3]):l.length?(a=l[0],o=l[1]):(a=l.x,l.y,o=l.x+l.width,l.y+l.height),[a,n,o,i]}function p(t){if("number"==typeof t)return[t,t,t,t];if(2===t.length)return[t[0],t[1],t[0],t[1]];var e=l(t);return[e.x,e.y,e.x+e.width,e.y+e.height]}e.exports=u,u.prototype.render=function(){for(var t,e=this,r=[],n=arguments.length;n--;)r[n]=arguments[n];return r.length&&(t=this).update.apply(t,r),this.regl.attributes.preserveDrawingBuffer?this.draw():(this.dirty?null==this.planned&&(this.planned=o(function(){e.draw(),e.dirty=!0,e.planned=null})):(this.draw(),this.dirty=!0,o(function(){e.dirty=!1})),this)},u.prototype.update=function(){for(var t,e=[],r=arguments.length;r--;)e[r]=arguments[r];if(e.length){for(var n=0;n<e.length;n++)this.updateItem(n,e[n]);this.traces=this.traces.filter(Boolean);for(var i=[],a=0,o=0;o<this.traces.length;o++){for(var s=this.traces[o],l=this.traces[o].passes,c=0;c<l.length;c++)i.push(this.passes[l[c]]);s.passOffset=a,a+=s.passes.length}return(t=this.scatter).update.apply(t,i),this}},u.prototype.updateItem=function(t,e){var r=this.regl;if(null===e)return this.traces[t]=null,this;if(!e)return this;var n,o=i(e,{data:"data items columns rows values dimensions samples x",snap:"snap cluster",size:"sizes size radius",color:"colors color fill fill-color fillColor",opacity:"opacity alpha transparency opaque",borderSize:"borderSizes borderSize border-size bordersize borderWidth borderWidths border-width borderwidth stroke-width strokeWidth strokewidth outline",borderColor:"borderColors borderColor bordercolor stroke stroke-color strokeColor",marker:"markers marker shape",range:"range ranges databox dataBox",viewport:"viewport viewBox viewbox",domain:"domain domains area areas",padding:"pad padding paddings pads margin margins",transpose:"transpose transposed",diagonal:"diagonal diag showDiagonal",upper:"upper up top upperhalf upperHalf showupperhalf showUpper showUpperHalf",lower:"lower low bottom lowerhalf lowerHalf showlowerhalf showLowerHalf showLower"}),s=this.traces[t]||(this.traces[t]={id:t,buffer:r.buffer({usage:"dynamic",type:"float",data:new Uint8Array}),color:"black",marker:null,size:12,borderColor:"transparent",borderSize:1,viewport:l([r._gl.drawingBufferWidth,r._gl.drawingBufferHeight]),padding:[0,0,0,0],opacity:1,diagonal:!0,upper:!0,lower:!0});if(null!=o.color&&(s.color=o.color),null!=o.size&&(s.size=o.size),null!=o.marker&&(s.marker=o.marker),null!=o.borderColor&&(s.borderColor=o.borderColor),null!=o.borderSize&&(s.borderSize=o.borderSize),null!=o.opacity&&(s.opacity=o.opacity),o.viewport&&(s.viewport=l(o.viewport)),null!=o.diagonal&&(s.diagonal=o.diagonal),null!=o.upper&&(s.upper=o.upper),null!=o.lower&&(s.lower=o.lower),o.data){s.buffer(c(o.data)),s.columns=o.data.length,s.count=o.data[0].length,s.bounds=[];for(var u=0;u<s.columns;u++)s.bounds[u]=a(o.data[u],1)}o.range&&(s.range=o.range,n=s.range&&"number"!=typeof s.range[0]),o.domain&&(s.domain=o.domain);var d=!1;null!=o.padding&&(Array.isArray(o.padding)&&o.padding.length===s.columns&&"number"==typeof o.padding[o.padding.length-1]?(s.padding=o.padding.map(p),d=!0):s.padding=p(o.padding));var g=s.columns,v=s.count,m=s.viewport.width,y=s.viewport.height,x=s.viewport.x,b=s.viewport.y,_=m/g,w=y/g;s.passes=[];for(var k=0;k<g;k++)for(var A=0;A<g;A++)if((s.diagonal||A!==k)&&(s.upper||!(k>A))&&(s.lower||!(k<A))){var M=h(s.id,k,A),T=this.passes[M]||(this.passes[M]={});if(o.data&&(o.transpose?T.positions={x:{buffer:s.buffer,offset:A,count:v,stride:g},y:{buffer:s.buffer,offset:k,count:v,stride:g}}:T.positions={x:{buffer:s.buffer,offset:A*v,count:v},y:{buffer:s.buffer,offset:k*v,count:v}},T.bounds=f(s.bounds,k,A)),o.domain||o.viewport||o.data){var S=d?f(s.padding,k,A):s.padding;if(s.domain){var E=f(s.domain,k,A),C=E[0],L=E[1],z=E[2],O=E[3];T.viewport=[x+C*m+S[0],b+L*y+S[1],x+z*m-S[2],b+O*y-S[3]]}else T.viewport=[x+A*_+_*S[0],b+k*w+w*S[1],x+(A+1)*_-_*S[2],b+(k+1)*w-w*S[3]]}o.color&&(T.color=s.color),o.size&&(T.size=s.size),o.marker&&(T.marker=s.marker),o.borderSize&&(T.borderSize=s.borderSize),o.borderColor&&(T.borderColor=s.borderColor),o.opacity&&(T.opacity=s.opacity),o.range&&(T.range=n?f(s.range,k,A):s.range||T.bounds),s.passes.push(M)}return this},u.prototype.draw=function(){for(var t,e=[],r=arguments.length;r--;)e[r]=arguments[r];if(e.length){for(var n=[],i=0;i<e.length;i++)if("number"==typeof e[i]){var a=this.traces[e[i]],o=a.passes,l=a.passOffset;n.push.apply(n,s(l,l+o.length))}else if(e[i].length){var c=e[i],u=this.traces[i],h=u.passes,f=u.passOffset;h=h.map(function(t,e){n[f+e]=c})}(t=this.scatter).draw.apply(t,n)}else this.scatter.draw();return this},u.prototype.destroy=function(){return this.traces.forEach(function(t){t.buffer&&t.buffer.destroy&&t.buffer.destroy()}),this.traces=null,this.passes=null,this.scatter.destroy(),this}},{"array-bounds":53,"array-range":55,"flatten-vertex-data":220,"parse-rect":448,"pick-by-alias":454,raf:473,"regl-scatter2d":481}],483:[function(t,e,r){var n,i;n=this,i=function(){function t(t,e){this.id=V++,this.type=t,this.data=e}function e(t){return"["+function t(e){if(0===e.length)return[];var r=e.charAt(0),n=e.charAt(e.length-1);if(1<e.length&&r===n&&('"'===r||"'"===r))return['"'+e.substr(1,e.length-2).replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'];if(r=/\[(false|true|null|\d+|'[^']*'|"[^"]*")\]/.exec(e))return t(e.substr(0,r.index)).concat(t(r[1])).concat(t(e.substr(r.index+r[0].length)));if(1===(r=e.split(".")).length)return['"'+e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'];for(e=[],n=0;n<r.length;++n)e=e.concat(t(r[n]));return e}(t).join("][")+"]"}function r(t){return"string"==typeof t?t.split():t}function n(t){return"string"==typeof t?document.querySelector(t):t}function i(t){var e,i,a,o,s=t||{};t={};var l=[],c=[],u="undefined"==typeof window?1:window.devicePixelRatio,h=!1,f=function(t){},p=function(){};if("string"==typeof s?e=document.querySelector(s):"object"==typeof s&&("string"==typeof s.nodeName&&"function"==typeof s.appendChild&&"function"==typeof s.getBoundingClientRect?e=s:"function"==typeof s.drawArrays||"function"==typeof s.drawElements?a=(o=s).canvas:("gl"in s?o=s.gl:"canvas"in s?a=n(s.canvas):"container"in s&&(i=n(s.container)),"attributes"in s&&(t=s.attributes),"extensions"in s&&(l=r(s.extensions)),"optionalExtensions"in s&&(c=r(s.optionalExtensions)),"onDone"in s&&(f=s.onDone),"profile"in s&&(h=!!s.profile),"pixelRatio"in s&&(u=+s.pixelRatio))),e&&("canvas"===e.nodeName.toLowerCase()?a=e:i=e),!o){if(!a){if(!(e=function(t,e,r){function n(){var e=window.innerWidth,n=window.innerHeight;t!==document.body&&(e=(n=t.getBoundingClientRect()).right-n.left,n=n.bottom-n.top),i.width=r*e,i.height=r*n,j(i.style,{width:e+"px",height:n+"px"})}var i=document.createElement("canvas");return j(i.style,{border:0,margin:0,padding:0,top:0,left:0}),t.appendChild(i),t===document.body&&(i.style.position="absolute",j(t.style,{margin:0,padding:0})),window.addEventListener("resize",n,!1),n(),{canvas:i,onDestroy:function(){window.removeEventListener("resize",n),t.removeChild(i)}}}(i||document.body,0,u)))return null;a=e.canvas,p=e.onDestroy}o=function(t,e){function r(r){try{return t.getContext(r,e)}catch(t){return null}}return r("webgl")||r("experimental-webgl")||r("webgl-experimental")}(a,t)}return o?{gl:o,canvas:a,container:i,extensions:l,optionalExtensions:c,pixelRatio:u,profile:h,onDone:f,onDestroy:p}:(p(),f("webgl not supported, try upgrading your browser or graphics drivers http://get.webgl.org"),null)}function a(t,e){for(var r=Array(t),n=0;n<t;++n)r[n]=e(n);return r}function o(t){var e,r;return e=(65535<t)<<4,e|=r=(255<(t>>>=e))<<3,(e|=r=(15<(t>>>=r))<<2)|(r=(3<(t>>>=r))<<1)|t>>>r>>1}function s(){function t(t){t:{for(var e=16;268435456>=e;e*=16)if(t<=e){t=e;break t}t=0}return 0<(e=r[o(t)>>2]).length?e.pop():new ArrayBuffer(t)}function e(t){r[o(t.byteLength)>>2].push(t)}var r=a(8,function(){return[]});return{alloc:t,free:e,allocType:function(e,r){var n=null;switch(e){case 5120:n=new Int8Array(t(r),0,r);break;case 5121:n=new Uint8Array(t(r),0,r);break;case 5122:n=new Int16Array(t(2*r),0,r);break;case 5123:n=new Uint16Array(t(2*r),0,r);break;case 5124:n=new Int32Array(t(4*r),0,r);break;case 5125:n=new Uint32Array(t(4*r),0,r);break;case 5126:n=new Float32Array(t(4*r),0,r);break;default:return null}return n.length!==r?n.subarray(0,r):n},freeType:function(t){e(t.buffer)}}}function l(t){return!!t&&"object"==typeof t&&Array.isArray(t.shape)&&Array.isArray(t.stride)&&"number"==typeof t.offset&&t.shape.length===t.stride.length&&(Array.isArray(t.data)||W(t.data))}function c(t,e,r,n,i,a){for(var o=0;o<e;++o)for(var s=t[o],l=0;l<r;++l)for(var c=s[l],u=0;u<n;++u)i[a++]=c[u]}function u(t){return 0|$[Object.prototype.toString.call(t)]}function h(t,e){for(var r=0;r<e.length;++r)t[r]=e[r]}function f(t,e,r,n,i,a,o){for(var s=0,l=0;l<r;++l)for(var c=0;c<n;++c)t[s++]=e[i*l+a*c+o]}function p(t,e,r,n){function i(e){this.id=c++,this.buffer=t.createBuffer(),this.type=e,this.usage=35044,this.byteLength=0,this.dimension=1,this.dtype=5121,this.persistentData=null,r.profile&&(this.stats={size:0})}function a(e,r,n){e.byteLength=r.byteLength,t.bufferData(e.type,r,n)}function o(t,e,r,n,i,o){if(t.usage=r,Array.isArray(e)){if(t.dtype=n||5126,0<e.length)if(Array.isArray(e[0])){i=tt(e);for(var s=n=1;s<i.length;++s)n*=i[s];t.dimension=n,a(t,e=Q(e,i,t.dtype),r),o?t.persistentData=e:G.freeType(e)}else"number"==typeof e[0]?(t.dimension=i,h(i=G.allocType(t.dtype,e.length),e),a(t,i,r),o?t.persistentData=i:G.freeType(i)):W(e[0])&&(t.dimension=e[0].length,t.dtype=n||u(e[0])||5126,a(t,e=Q(e,[e.length,e[0].length],t.dtype),r),o?t.persistentData=e:G.freeType(e))}else if(W(e))t.dtype=n||u(e),t.dimension=i,a(t,e,r),o&&(t.persistentData=new Uint8Array(new Uint8Array(e.buffer)));else if(l(e)){i=e.shape;var c=e.stride,p=(s=e.offset,0),d=0,g=0,v=0;1===i.length?(p=i[0],d=1,g=c[0],v=0):2===i.length&&(p=i[0],d=i[1],g=c[0],v=c[1]),t.dtype=n||u(e.data)||5126,t.dimension=d,f(i=G.allocType(t.dtype,p*d),e.data,p,d,g,v,s),a(t,i,r),o?t.persistentData=i:G.freeType(i)}}function s(r){e.bufferCount--;for(var i=0;i<n.state.length;++i){var a=n.state[i];a.buffer===r&&(t.disableVertexAttribArray(i),a.buffer=null)}t.deleteBuffer(r.buffer),r.buffer=null,delete p[r.id]}var c=0,p={};i.prototype.bind=function(){t.bindBuffer(this.type,this.buffer)},i.prototype.destroy=function(){s(this)};var d=[];return r.profile&&(e.getTotalBufferSize=function(){var t=0;return Object.keys(p).forEach(function(e){t+=p[e].stats.size}),t}),{create:function(n,a,c,d){function g(e){var n=35044,i=null,a=0,s=0,c=1;return Array.isArray(e)||W(e)||l(e)?i=e:"number"==typeof e?a=0|e:e&&("data"in e&&(i=e.data),"usage"in e&&(n=K[e.usage]),"type"in e&&(s=J[e.type]),"dimension"in e&&(c=0|e.dimension),"length"in e&&(a=0|e.length)),v.bind(),i?o(v,i,n,s,c,d):(a&&t.bufferData(v.type,a,n),v.dtype=s||5121,v.usage=n,v.dimension=c,v.byteLength=a),r.profile&&(v.stats.size=v.byteLength*et[v.dtype]),g}e.bufferCount++;var v=new i(a);return p[v.id]=v,c||g(n),g._reglType="buffer",g._buffer=v,g.subdata=function(e,r){var n,i=0|(r||0);if(v.bind(),W(e))t.bufferSubData(v.type,i,e);else if(Array.isArray(e)){if(0<e.length)if("number"==typeof e[0]){var a=G.allocType(v.dtype,e.length);h(a,e),t.bufferSubData(v.type,i,a),G.freeType(a)}else(Array.isArray(e[0])||W(e[0]))&&(n=tt(e),a=Q(e,n,v.dtype),t.bufferSubData(v.type,i,a),G.freeType(a))}else if(l(e)){n=e.shape;var o=e.stride,s=a=0,c=0,p=0;1===n.length?(a=n[0],s=1,c=o[0],p=0):2===n.length&&(a=n[0],s=n[1],c=o[0],p=o[1]),n=Array.isArray(e.data)?v.dtype:u(e.data),f(n=G.allocType(n,a*s),e.data,a,s,c,p,e.offset),t.bufferSubData(v.type,i,n),G.freeType(n)}return g},r.profile&&(g.stats=v.stats),g.destroy=function(){s(v)},g},createStream:function(t,e){var r=d.pop();return r||(r=new i(t)),r.bind(),o(r,e,35040,0,1,!1),r},destroyStream:function(t){d.push(t)},clear:function(){X(p).forEach(s),d.forEach(s)},getBuffer:function(t){return t&&t._buffer instanceof i?t._buffer:null},restore:function(){X(p).forEach(function(e){e.buffer=t.createBuffer(),t.bindBuffer(e.type,e.buffer),t.bufferData(e.type,e.persistentData||e.byteLength,e.usage)})},_initBuffer:o}}function d(t,e,r,n){function i(t){this.id=c++,s[this.id]=this,this.buffer=t,this.primType=4,this.type=this.vertCount=0}function a(n,i,a,o,s,c,u){if(n.buffer.bind(),i){var h=u;u||W(i)&&(!l(i)||W(i.data))||(h=e.oes_element_index_uint?5125:5123),r._initBuffer(n.buffer,i,a,h,3)}else t.bufferData(34963,c,a),n.buffer.dtype=h||5121,n.buffer.usage=a,n.buffer.dimension=3,n.buffer.byteLength=c;if(h=u,!u){switch(n.buffer.dtype){case 5121:case 5120:h=5121;break;case 5123:case 5122:h=5123;break;case 5125:case 5124:h=5125}n.buffer.dtype=h}n.type=h,0>(i=s)&&(i=n.buffer.byteLength,5123===h?i>>=1:5125===h&&(i>>=2)),n.vertCount=i,i=o,0>o&&(i=4,1===(o=n.buffer.dimension)&&(i=0),2===o&&(i=1),3===o&&(i=4)),n.primType=i}function o(t){n.elementsCount--,delete s[t.id],t.buffer.destroy(),t.buffer=null}var s={},c=0,u={uint8:5121,uint16:5123};e.oes_element_index_uint&&(u.uint32=5125),i.prototype.bind=function(){this.buffer.bind()};var h=[];return{create:function(t,e){function s(t){if(t)if("number"==typeof t)c(t),h.primType=4,h.vertCount=0|t,h.type=5121;else{var e=null,r=35044,n=-1,i=-1,o=0,f=0;Array.isArray(t)||W(t)||l(t)?e=t:("data"in t&&(e=t.data),"usage"in t&&(r=K[t.usage]),"primitive"in t&&(n=rt[t.primitive]),"count"in t&&(i=0|t.count),"type"in t&&(f=u[t.type]),"length"in t?o=0|t.length:(o=i,5123===f||5122===f?o*=2:5125!==f&&5124!==f||(o*=4))),a(h,e,r,n,i,o,f)}else c(),h.primType=4,h.vertCount=0,h.type=5121;return s}var c=r.create(null,34963,!0),h=new i(c._buffer);return n.elementsCount++,s(t),s._reglType="elements",s._elements=h,s.subdata=function(t,e){return c.subdata(t,e),s},s.destroy=function(){o(h)},s},createStream:function(t){var e=h.pop();return e||(e=new i(r.create(null,34963,!0,!1)._buffer)),a(e,t,35040,-1,-1,0,0),e},destroyStream:function(t){h.push(t)},getElements:function(t){return"function"==typeof t&&t._elements instanceof i?t._elements:null},clear:function(){X(s).forEach(o)}}}function g(t){for(var e=G.allocType(5123,t.length),r=0;r<t.length;++r)if(isNaN(t[r]))e[r]=65535;else if(1/0===t[r])e[r]=31744;else if(-1/0===t[r])e[r]=64512;else{nt[0]=t[r];var n=(a=it[0])>>>31<<15,i=(a<<1>>>24)-127,a=a>>13&1023;e[r]=-24>i?n:-14>i?n+(a+1024>>-14-i):15<i?n+31744:n+(i+15<<10)+a}return e}function v(t){return Array.isArray(t)||W(t)}function m(t){return"[object "+t+"]"}function y(t){return Array.isArray(t)&&(0===t.length||"number"==typeof t[0])}function x(t){return!(!Array.isArray(t)||0===t.length||!v(t[0]))}function b(t){return Object.prototype.toString.call(t)}function _(t){if(!t)return!1;var e=b(t);return 0<=pt.indexOf(e)||(y(t)||x(t)||l(t))}function w(t,e){36193===t.type?(t.data=g(e),G.freeType(e)):t.data=e}function k(t,e,r,n,i,a){if(t="undefined"!=typeof gt[t]?gt[t]:st[t]*dt[e],a&&(t*=6),i){for(n=0;1<=r;)n+=t*r*r,r/=2;return n}return t*r*n}function A(t,e,r,n,i,a,o){function s(){this.format=this.internalformat=6408,this.type=5121,this.flipY=this.premultiplyAlpha=this.compressed=!1,this.unpackAlignment=1,this.colorSpace=37444,this.channels=this.height=this.width=0}function c(t,e){t.internalformat=e.internalformat,t.format=e.format,t.type=e.type,t.compressed=e.compressed,t.premultiplyAlpha=e.premultiplyAlpha,t.flipY=e.flipY,t.unpackAlignment=e.unpackAlignment,t.colorSpace=e.colorSpace,t.width=e.width,t.height=e.height,t.channels=e.channels}function u(t,e){if("object"==typeof e&&e){"premultiplyAlpha"in e&&(t.premultiplyAlpha=e.premultiplyAlpha),"flipY"in e&&(t.flipY=e.flipY),"alignment"in e&&(t.unpackAlignment=e.alignment),"colorSpace"in e&&(t.colorSpace=q[e.colorSpace]),"type"in e&&(t.type=H[e.type]);var r=t.width,n=t.height,i=t.channels,a=!1;"shape"in e?(r=e.shape[0],n=e.shape[1],3===e.shape.length&&(i=e.shape[2],a=!0)):("radius"in e&&(r=n=e.radius),"width"in e&&(r=e.width),"height"in e&&(n=e.height),"channels"in e&&(i=e.channels,a=!0)),t.width=0|r,t.height=0|n,t.channels=0|i,r=!1,"format"in e&&(r=e.format,n=t.internalformat=Y[r],t.format=pt[n],r in H&&!("type"in e)&&(t.type=H[r]),r in J&&(t.compressed=!0),r=!0),!a&&r?t.channels=st[t.format]:a&&!r&&t.channels!==ot[t.format]&&(t.format=t.internalformat=ot[t.channels])}}function h(e){t.pixelStorei(37440,e.flipY),t.pixelStorei(37441,e.premultiplyAlpha),t.pixelStorei(37443,e.colorSpace),t.pixelStorei(3317,e.unpackAlignment)}function f(){s.call(this),this.yOffset=this.xOffset=0,this.data=null,this.needsFree=!1,this.element=null,this.needsCopy=!1}function p(t,e){var r=null;if(_(e)?r=e:e&&(u(t,e),"x"in e&&(t.xOffset=0|e.x),"y"in e&&(t.yOffset=0|e.y),_(e.data)&&(r=e.data)),e.copy){var n=i.viewportWidth,a=i.viewportHeight;t.width=t.width||n-t.xOffset,t.height=t.height||a-t.yOffset,t.needsCopy=!0}else if(r){if(W(r))t.channels=t.channels||4,t.data=r,"type"in e||5121!==t.type||(t.type=0|$[Object.prototype.toString.call(r)]);else if(y(r)){switch(t.channels=t.channels||4,a=(n=r).length,t.type){case 5121:case 5123:case 5125:case 5126:(a=G.allocType(t.type,a)).set(n),t.data=a;break;case 36193:t.data=g(n)}t.alignment=1,t.needsFree=!0}else if(l(r)){n=r.data,Array.isArray(n)||5121!==t.type||(t.type=0|$[Object.prototype.toString.call(n)]);a=r.shape;var o,s,c,h,f=r.stride;3===a.length?(c=a[2],h=f[2]):h=c=1,o=a[0],s=a[1],a=f[0],f=f[1],t.alignment=1,t.width=o,t.height=s,t.channels=c,t.format=t.internalformat=ot[c],t.needsFree=!0,o=h,r=r.offset,c=t.width,h=t.height,s=t.channels;for(var p=G.allocType(36193===t.type?5126:t.type,c*h*s),d=0,m=0;m<h;++m)for(var k=0;k<c;++k)for(var A=0;A<s;++A)p[d++]=n[a*k+f*m+o*A+r];w(t,p)}else if(b(r)===lt||b(r)===ct)b(r)===lt?t.element=r:t.element=r.canvas,t.width=t.element.width,t.height=t.element.height,t.channels=4;else if(b(r)===ut)t.element=r,t.width=r.width,t.height=r.height,t.channels=4;else if(b(r)===ht)t.element=r,t.width=r.naturalWidth,t.height=r.naturalHeight,t.channels=4;else if(b(r)===ft)t.element=r,t.width=r.videoWidth,t.height=r.videoHeight,t.channels=4;else if(x(r)){for(n=t.width||r[0].length,a=t.height||r.length,f=t.channels,f=v(r[0][0])?f||r[0][0].length:f||1,o=Z.shape(r),c=1,h=0;h<o.length;++h)c*=o[h];c=G.allocType(36193===t.type?5126:t.type,c),Z.flatten(r,o,"",c),w(t,c),t.alignment=1,t.width=n,t.height=a,t.channels=f,t.format=t.internalformat=ot[f],t.needsFree=!0}}else t.width=t.width||1,t.height=t.height||1,t.channels=t.channels||4}function d(e,r,i,a,o){var s=e.element,l=e.data,c=e.internalformat,u=e.format,f=e.type,p=e.width,d=e.height;h(e),s?t.texSubImage2D(r,o,i,a,u,f,s):e.compressed?t.compressedTexSubImage2D(r,o,i,a,c,p,d,l):e.needsCopy?(n(),t.copyTexSubImage2D(r,o,i,a,e.xOffset,e.yOffset,p,d)):t.texSubImage2D(r,o,i,a,p,d,u,f,l)}function m(){return dt.pop()||new f}function A(t){t.needsFree&&G.freeType(t.data),f.call(t),dt.push(t)}function M(){s.call(this),this.genMipmaps=!1,this.mipmapHint=4352,this.mipmask=0,this.images=Array(16)}function T(t,e,r){var n=t.images[0]=m();t.mipmask=1,n.width=t.width=e,n.height=t.height=r,n.channels=t.channels=4}function S(t,e){var r=null;if(_(e))c(r=t.images[0]=m(),t),p(r,e),t.mipmask=1;else if(u(t,e),Array.isArray(e.mipmap))for(var n=e.mipmap,i=0;i<n.length;++i)c(r=t.images[i]=m(),t),r.width>>=i,r.height>>=i,p(r,n[i]),t.mipmask|=1<<i;else c(r=t.images[0]=m(),t),p(r,e),t.mipmask=1;c(t,t.images[0])}function E(e,r){for(var i=e.images,a=0;a<i.length&&i[a];++a){var o=i[a],s=r,l=a,c=o.element,u=o.data,f=o.internalformat,p=o.format,d=o.type,g=o.width,v=o.height,m=o.channels;h(o),c?t.texImage2D(s,l,p,p,d,c):o.compressed?t.compressedTexImage2D(s,l,f,g,v,0,u):o.needsCopy?(n(),t.copyTexImage2D(s,l,p,o.xOffset,o.yOffset,g,v,0)):((o=!u)&&(u=G.zero.allocType(d,g*v*m)),t.texImage2D(s,l,p,g,v,0,p,d,u),o&&u&&G.zero.freeType(u))}}function C(){var t=gt.pop()||new M;s.call(t);for(var e=t.mipmask=0;16>e;++e)t.images[e]=null;return t}function L(t){for(var e=t.images,r=0;r<e.length;++r)e[r]&&A(e[r]),e[r]=null;gt.push(t)}function z(){this.magFilter=this.minFilter=9728,this.wrapT=this.wrapS=33071,this.anisotropic=1,this.genMipmaps=!1,this.mipmapHint=4352}function O(t,e){"min"in e&&(t.minFilter=U[e.min],0<=at.indexOf(t.minFilter)&&!("faces"in e)&&(t.genMipmaps=!0)),"mag"in e&&(t.magFilter=V[e.mag]);var r=t.wrapS,n=t.wrapT;if("wrap"in e){var i=e.wrap;"string"==typeof i?r=n=N[i]:Array.isArray(i)&&(r=N[i[0]],n=N[i[1]])}else"wrapS"in e&&(r=N[e.wrapS]),"wrapT"in e&&(n=N[e.wrapT]);if(t.wrapS=r,t.wrapT=n,"anisotropic"in e&&(t.anisotropic=e.anisotropic),"mipmap"in e){switch(r=!1,typeof e.mipmap){case"string":t.mipmapHint=B[e.mipmap],r=t.genMipmaps=!0;break;case"boolean":r=t.genMipmaps=e.mipmap;break;case"object":t.genMipmaps=!1,r=!0}!r||"min"in e||(t.minFilter=9984)}}function I(r,n){t.texParameteri(n,10241,r.minFilter),t.texParameteri(n,10240,r.magFilter),t.texParameteri(n,10242,r.wrapS),t.texParameteri(n,10243,r.wrapT),e.ext_texture_filter_anisotropic&&t.texParameteri(n,34046,r.anisotropic),r.genMipmaps&&(t.hint(33170,r.mipmapHint),t.generateMipmap(n))}function D(e){s.call(this),this.mipmask=0,this.internalformat=6408,this.id=vt++,this.refCount=1,this.target=e,this.texture=t.createTexture(),this.unit=-1,this.bindCount=0,this.texInfo=new z,o.profile&&(this.stats={size:0})}function P(e){t.activeTexture(33984),t.bindTexture(e.target,e.texture)}function R(){var e=xt[0];e?t.bindTexture(e.target,e.texture):t.bindTexture(3553,null)}function F(e){var r=e.texture,n=e.unit,i=e.target;0<=n&&(t.activeTexture(33984+n),t.bindTexture(i,null),xt[n]=null),t.deleteTexture(r),e.texture=null,e.params=null,e.pixels=null,e.refCount=0,delete mt[e.id],a.textureCount--}var B={"don't care":4352,"dont care":4352,nice:4354,fast:4353},N={repeat:10497,clamp:33071,mirror:33648},V={nearest:9728,linear:9729},U=j({mipmap:9987,"nearest mipmap nearest":9984,"linear mipmap nearest":9985,"nearest mipmap linear":9986,"linear mipmap linear":9987},V),q={none:0,browser:37444},H={uint8:5121,rgba4:32819,rgb565:33635,"rgb5 a1":32820},Y={alpha:6406,luminance:6409,"luminance alpha":6410,rgb:6407,rgba:6408,rgba4:32854,"rgb5 a1":32855,rgb565:36194},J={};e.ext_srgb&&(Y.srgb=35904,Y.srgba=35906),e.oes_texture_float&&(H.float32=H.float=5126),e.oes_texture_half_float&&(H.float16=H["half float"]=36193),e.webgl_depth_texture&&(j(Y,{depth:6402,"depth stencil":34041}),j(H,{uint16:5123,uint32:5125,"depth stencil":34042})),e.webgl_compressed_texture_s3tc&&j(J,{"rgb s3tc dxt1":33776,"rgba s3tc dxt1":33777,"rgba s3tc dxt3":33778,"rgba s3tc dxt5":33779}),e.webgl_compressed_texture_atc&&j(J,{"rgb atc":35986,"rgba atc explicit alpha":35987,"rgba atc interpolated alpha":34798}),e.webgl_compressed_texture_pvrtc&&j(J,{"rgb pvrtc 4bppv1":35840,"rgb pvrtc 2bppv1":35841,"rgba pvrtc 4bppv1":35842,"rgba pvrtc 2bppv1":35843}),e.webgl_compressed_texture_etc1&&(J["rgb etc1"]=36196);var K=Array.prototype.slice.call(t.getParameter(34467));Object.keys(J).forEach(function(t){var e=J[t];0<=K.indexOf(e)&&(Y[t]=e)});var Q=Object.keys(Y);r.textureFormats=Q;var tt=[];Object.keys(Y).forEach(function(t){tt[Y[t]]=t});var et=[];Object.keys(H).forEach(function(t){et[H[t]]=t});var rt=[];Object.keys(V).forEach(function(t){rt[V[t]]=t});var nt=[];Object.keys(U).forEach(function(t){nt[U[t]]=t});var it=[];Object.keys(N).forEach(function(t){it[N[t]]=t});var pt=Q.reduce(function(t,e){var r=Y[e];return 6409===r||6406===r||6409===r||6410===r||6402===r||34041===r?t[r]=r:32855===r||0<=e.indexOf("rgba")?t[r]=6408:t[r]=6407,t},{}),dt=[],gt=[],vt=0,mt={},yt=r.maxTextureUnits,xt=Array(yt).map(function(){return null});return j(D.prototype,{bind:function(){this.bindCount+=1;var e=this.unit;if(0>e){for(var r=0;r<yt;++r){var n=xt[r];if(n){if(0<n.bindCount)continue;n.unit=-1}xt[r]=this,e=r;break}o.profile&&a.maxTextureUnits<e+1&&(a.maxTextureUnits=e+1),this.unit=e,t.activeTexture(33984+e),t.bindTexture(this.target,this.texture)}return e},unbind:function(){--this.bindCount},decRef:function(){0>=--this.refCount&&F(this)}}),o.profile&&(a.getTotalTextureSize=function(){var t=0;return Object.keys(mt).forEach(function(e){t+=mt[e].stats.size}),t}),{create2D:function(e,r){function n(t,e){var r=i.texInfo;z.call(r);var a=C();return"number"==typeof t?T(a,0|t,"number"==typeof e?0|e:0|t):t?(O(r,t),S(a,t)):T(a,1,1),r.genMipmaps&&(a.mipmask=(a.width<<1)-1),i.mipmask=a.mipmask,c(i,a),i.internalformat=a.internalformat,n.width=a.width,n.height=a.height,P(i),E(a,3553),I(r,3553),R(),L(a),o.profile&&(i.stats.size=k(i.internalformat,i.type,a.width,a.height,r.genMipmaps,!1)),n.format=tt[i.internalformat],n.type=et[i.type],n.mag=rt[r.magFilter],n.min=nt[r.minFilter],n.wrapS=it[r.wrapS],n.wrapT=it[r.wrapT],n}var i=new D(3553);return mt[i.id]=i,a.textureCount++,n(e,r),n.subimage=function(t,e,r,a){e|=0,r|=0,a|=0;var o=m();return c(o,i),o.width=0,o.height=0,p(o,t),o.width=o.width||(i.width>>a)-e,o.height=o.height||(i.height>>a)-r,P(i),d(o,3553,e,r,a),R(),A(o),n},n.resize=function(e,r){var a=0|e,s=0|r||a;if(a===i.width&&s===i.height)return n;n.width=i.width=a,n.height=i.height=s,P(i);for(var l,c=i.channels,u=i.type,h=0;i.mipmask>>h;++h){var f=a>>h,p=s>>h;if(!f||!p)break;l=G.zero.allocType(u,f*p*c),t.texImage2D(3553,h,i.format,f,p,0,i.format,i.type,l),l&&G.zero.freeType(l)}return R(),o.profile&&(i.stats.size=k(i.internalformat,i.type,a,s,!1,!1)),n},n._reglType="texture2d",n._texture=i,o.profile&&(n.stats=i.stats),n.destroy=function(){i.decRef()},n},createCube:function(e,r,n,i,s,l){function h(t,e,r,n,i,a){var s,l=f.texInfo;for(z.call(l),s=0;6>s;++s)g[s]=C();if("number"!=typeof t&&t){if("object"==typeof t)if(e)S(g[0],t),S(g[1],e),S(g[2],r),S(g[3],n),S(g[4],i),S(g[5],a);else if(O(l,t),u(f,t),"faces"in t)for(t=t.faces,s=0;6>s;++s)c(g[s],f),S(g[s],t[s]);else for(s=0;6>s;++s)S(g[s],t)}else for(t=0|t||1,s=0;6>s;++s)T(g[s],t,t);for(c(f,g[0]),f.mipmask=l.genMipmaps?(g[0].width<<1)-1:g[0].mipmask,f.internalformat=g[0].internalformat,h.width=g[0].width,h.height=g[0].height,P(f),s=0;6>s;++s)E(g[s],34069+s);for(I(l,34067),R(),o.profile&&(f.stats.size=k(f.internalformat,f.type,h.width,h.height,l.genMipmaps,!0)),h.format=tt[f.internalformat],h.type=et[f.type],h.mag=rt[l.magFilter],h.min=nt[l.minFilter],h.wrapS=it[l.wrapS],h.wrapT=it[l.wrapT],s=0;6>s;++s)L(g[s]);return h}var f=new D(34067);mt[f.id]=f,a.cubeCount++;var g=Array(6);return h(e,r,n,i,s,l),h.subimage=function(t,e,r,n,i){r|=0,n|=0,i|=0;var a=m();return c(a,f),a.width=0,a.height=0,p(a,e),a.width=a.width||(f.width>>i)-r,a.height=a.height||(f.height>>i)-n,P(f),d(a,34069+t,r,n,i),R(),A(a),h},h.resize=function(e){if((e|=0)!==f.width){h.width=f.width=e,h.height=f.height=e,P(f);for(var r=0;6>r;++r)for(var n=0;f.mipmask>>n;++n)t.texImage2D(34069+r,n,f.format,e>>n,e>>n,0,f.format,f.type,null);return R(),o.profile&&(f.stats.size=k(f.internalformat,f.type,h.width,h.height,!1,!0)),h}},h._reglType="textureCube",h._texture=f,o.profile&&(h.stats=f.stats),h.destroy=function(){f.decRef()},h},clear:function(){for(var e=0;e<yt;++e)t.activeTexture(33984+e),t.bindTexture(3553,null),xt[e]=null;X(mt).forEach(F),a.cubeCount=0,a.textureCount=0},getTexture:function(t){return null},restore:function(){for(var e=0;e<yt;++e){var r=xt[e];r&&(r.bindCount=0,r.unit=-1,xt[e]=null)}X(mt).forEach(function(e){e.texture=t.createTexture(),t.bindTexture(e.target,e.texture);for(var r=0;32>r;++r)if(0!=(e.mipmask&1<<r))if(3553===e.target)t.texImage2D(3553,r,e.internalformat,e.width>>r,e.height>>r,0,e.internalformat,e.type,null);else for(var n=0;6>n;++n)t.texImage2D(34069+n,r,e.internalformat,e.width>>r,e.height>>r,0,e.internalformat,e.type,null);I(e.texInfo,e.target)})}}}function M(t,e,r,n,i,a){function o(t,e,r){this.target=t,this.texture=e,this.renderbuffer=r;var n=t=0;e?(t=e.width,n=e.height):r&&(t=r.width,n=r.height),this.width=t,this.height=n}function s(t){t&&(t.texture&&t.texture._texture.decRef(),t.renderbuffer&&t.renderbuffer._renderbuffer.decRef())}function l(t,e,r){t&&(t.texture?t.texture._texture.refCount+=1:t.renderbuffer._renderbuffer.refCount+=1)}function c(e,r){r&&(r.texture?t.framebufferTexture2D(36160,e,r.target,r.texture._texture.texture,0):t.framebufferRenderbuffer(36160,e,36161,r.renderbuffer._renderbuffer.renderbuffer))}function u(t){var e=3553,r=null,n=null,i=t;return"object"==typeof t&&(i=t.data,"target"in t&&(e=0|t.target)),"texture2d"===(t=i._reglType)?r=i:"textureCube"===t?r=i:"renderbuffer"===t&&(n=i,e=36161),new o(e,r,n)}function h(t,e,r,a,s){return r?((t=n.create2D({width:t,height:e,format:a,type:s}))._texture.refCount=0,new o(3553,t,null)):((t=i.create({width:t,height:e,format:a}))._renderbuffer.refCount=0,new o(36161,null,t))}function f(t){return t&&(t.texture||t.renderbuffer)}function p(t,e,r){t&&(t.texture?t.texture.resize(e,r):t.renderbuffer&&t.renderbuffer.resize(e,r),t.width=e,t.height=r)}function d(){this.id=k++,A[this.id]=this,this.framebuffer=t.createFramebuffer(),this.height=this.width=0,this.colorAttachments=[],this.depthStencilAttachment=this.stencilAttachment=this.depthAttachment=null}function g(t){t.colorAttachments.forEach(s),s(t.depthAttachment),s(t.stencilAttachment),s(t.depthStencilAttachment)}function v(e){t.deleteFramebuffer(e.framebuffer),e.framebuffer=null,a.framebufferCount--,delete A[e.id]}function m(e){var n;t.bindFramebuffer(36160,e.framebuffer);var i=e.colorAttachments;for(n=0;n<i.length;++n)c(36064+n,i[n]);for(n=i.length;n<r.maxColorAttachments;++n)t.framebufferTexture2D(36160,36064+n,3553,null,0);t.framebufferTexture2D(36160,33306,3553,null,0),t.framebufferTexture2D(36160,36096,3553,null,0),t.framebufferTexture2D(36160,36128,3553,null,0),c(36096,e.depthAttachment),c(36128,e.stencilAttachment),c(33306,e.depthStencilAttachment),t.checkFramebufferStatus(36160),t.isContextLost(),t.bindFramebuffer(36160,x.next?x.next.framebuffer:null),x.cur=x.next,t.getError()}function y(t,e){function r(t,e){var i,a=0,o=0,s=!0,c=!0;i=null;var p=!0,d="rgba",v="uint8",y=1,x=null,w=null,k=null,A=!1;"number"==typeof t?(a=0|t,o=0|e||a):t?("shape"in t?(a=(o=t.shape)[0],o=o[1]):("radius"in t&&(a=o=t.radius),"width"in t&&(a=t.width),"height"in t&&(o=t.height)),("color"in t||"colors"in t)&&(i=t.color||t.colors,Array.isArray(i)),i||("colorCount"in t&&(y=0|t.colorCount),"colorTexture"in t&&(p=!!t.colorTexture,d="rgba4"),"colorType"in t&&(v=t.colorType,!p)&&("half float"===v||"float16"===v?d="rgba16f":"float"!==v&&"float32"!==v||(d="rgba32f")),"colorFormat"in t&&(d=t.colorFormat,0<=b.indexOf(d)?p=!0:0<=_.indexOf(d)&&(p=!1))),("depthTexture"in t||"depthStencilTexture"in t)&&(A=!(!t.depthTexture&&!t.depthStencilTexture)),"depth"in t&&("boolean"==typeof t.depth?s=t.depth:(x=t.depth,c=!1)),"stencil"in t&&("boolean"==typeof t.stencil?c=t.stencil:(w=t.stencil,s=!1)),"depthStencil"in t&&("boolean"==typeof t.depthStencil?s=c=t.depthStencil:(k=t.depthStencil,c=s=!1))):a=o=1;var M=null,T=null,S=null,E=null;if(Array.isArray(i))M=i.map(u);else if(i)M=[u(i)];else for(M=Array(y),i=0;i<y;++i)M[i]=h(a,o,p,d,v);for(a=a||M[0].width,o=o||M[0].height,x?T=u(x):s&&!c&&(T=h(a,o,A,"depth","uint32")),w?S=u(w):c&&!s&&(S=h(a,o,!1,"stencil","uint8")),k?E=u(k):!x&&!w&&c&&s&&(E=h(a,o,A,"depth stencil","depth stencil")),s=null,i=0;i<M.length;++i)l(M[i]),M[i]&&M[i].texture&&(c=yt[M[i].texture._texture.format]*xt[M[i].texture._texture.type],null===s&&(s=c));return l(T),l(S),l(E),g(n),n.width=a,n.height=o,n.colorAttachments=M,n.depthAttachment=T,n.stencilAttachment=S,n.depthStencilAttachment=E,r.color=M.map(f),r.depth=f(T),r.stencil=f(S),r.depthStencil=f(E),r.width=n.width,r.height=n.height,m(n),r}var n=new d;return a.framebufferCount++,r(t,e),j(r,{resize:function(t,e){var i=Math.max(0|t,1),a=Math.max(0|e||i,1);if(i===n.width&&a===n.height)return r;for(var o=n.colorAttachments,s=0;s<o.length;++s)p(o[s],i,a);return p(n.depthAttachment,i,a),p(n.stencilAttachment,i,a),p(n.depthStencilAttachment,i,a),n.width=r.width=i,n.height=r.height=a,m(n),r},_reglType:"framebuffer",_framebuffer:n,destroy:function(){v(n),g(n)},use:function(t){x.setFBO({framebuffer:r},t)}})}var x={cur:null,next:null,dirty:!1,setFBO:null},b=["rgba"],_=["rgba4","rgb565","rgb5 a1"];e.ext_srgb&&_.push("srgba"),e.ext_color_buffer_half_float&&_.push("rgba16f","rgb16f"),e.webgl_color_buffer_float&&_.push("rgba32f");var w=["uint8"];e.oes_texture_half_float&&w.push("half float","float16"),e.oes_texture_float&&w.push("float","float32");var k=0,A={};return j(x,{getFramebuffer:function(t){return"function"==typeof t&&"framebuffer"===t._reglType&&(t=t._framebuffer)instanceof d?t:null},create:y,createCube:function(t){function e(t){var i,a={color:null},o=0,s=null;i="rgba";var l="uint8",c=1;if("number"==typeof t?o=0|t:t?("shape"in t?o=t.shape[0]:("radius"in t&&(o=0|t.radius),"width"in t?o=0|t.width:"height"in t&&(o=0|t.height)),("color"in t||"colors"in t)&&(s=t.color||t.colors,Array.isArray(s)),s||("colorCount"in t&&(c=0|t.colorCount),"colorType"in t&&(l=t.colorType),"colorFormat"in t&&(i=t.colorFormat)),"depth"in t&&(a.depth=t.depth),"stencil"in t&&(a.stencil=t.stencil),"depthStencil"in t&&(a.depthStencil=t.depthStencil)):o=1,s)if(Array.isArray(s))for(t=[],i=0;i<s.length;++i)t[i]=s[i];else t=[s];else for(t=Array(c),s={radius:o,format:i,type:l},i=0;i<c;++i)t[i]=n.createCube(s);for(a.color=Array(t.length),i=0;i<t.length;++i)c=t[i],o=o||c.width,a.color[i]={target:34069,data:t[i]};for(i=0;6>i;++i){for(c=0;c<t.length;++c)a.color[c].target=34069+i;0<i&&(a.depth=r[0].depth,a.stencil=r[0].stencil,a.depthStencil=r[0].depthStencil),r[i]?r[i](a):r[i]=y(a)}return j(e,{width:o,height:o,color:t})}var r=Array(6);return e(t),j(e,{faces:r,resize:function(t){var n=0|t;if(n===e.width)return e;var i=e.color;for(t=0;t<i.length;++t)i[t].resize(n);for(t=0;6>t;++t)r[t].resize(n);return e.width=e.height=n,e},_reglType:"framebufferCube",destroy:function(){r.forEach(function(t){t.destroy()})}})},clear:function(){X(A).forEach(v)},restore:function(){x.cur=null,x.next=null,x.dirty=!0,X(A).forEach(function(e){e.framebuffer=t.createFramebuffer(),m(e)})}})}function T(){this.w=this.z=this.y=this.x=this.state=0,this.buffer=null,this.size=0,this.normalized=!1,this.type=5126,this.divisor=this.stride=this.offset=0}function S(t,e,r,n){function i(t,e,r,n){this.name=t,this.id=e,this.location=r,this.info=n}function a(t,e){for(var r=0;r<t.length;++r)if(t[r].id===e.id)return void(t[r].location=e.location);t.push(e)}function o(r,n,i){if(!(o=(i=35632===r?c:u)[n])){var a=e.str(n),o=t.createShader(r);t.shaderSource(o,a),t.compileShader(o),i[n]=o}return o}function s(t,e){this.id=p++,this.fragId=t,this.vertId=e,this.program=null,this.uniforms=[],this.attributes=[],n.profile&&(this.stats={uniformsCount:0,attributesCount:0})}function l(r,s){var l,c;l=o(35632,r.fragId),c=o(35633,r.vertId);var u=r.program=t.createProgram();t.attachShader(u,l),t.attachShader(u,c),t.linkProgram(u);var h=t.getProgramParameter(u,35718);n.profile&&(r.stats.uniformsCount=h);var f=r.uniforms;for(l=0;l<h;++l)if(c=t.getActiveUniform(u,l))if(1<c.size)for(var p=0;p<c.size;++p){var d=c.name.replace("[0]","["+p+"]");a(f,new i(d,e.id(d),t.getUniformLocation(u,d),c))}else a(f,new i(c.name,e.id(c.name),t.getUniformLocation(u,c.name),c));for(h=t.getProgramParameter(u,35721),n.profile&&(r.stats.attributesCount=h),f=r.attributes,l=0;l<h;++l)(c=t.getActiveAttrib(u,l))&&a(f,new i(c.name,e.id(c.name),t.getAttribLocation(u,c.name),c))}var c={},u={},h={},f=[],p=0;return n.profile&&(r.getMaxUniformsCount=function(){var t=0;return f.forEach(function(e){e.stats.uniformsCount>t&&(t=e.stats.uniformsCount)}),t},r.getMaxAttributesCount=function(){var t=0;return f.forEach(function(e){e.stats.attributesCount>t&&(t=e.stats.attributesCount)}),t}),{clear:function(){var e=t.deleteShader.bind(t);X(c).forEach(e),c={},X(u).forEach(e),u={},f.forEach(function(e){t.deleteProgram(e.program)}),f.length=0,h={},r.shaderCount=0},program:function(t,e,n){var i=h[e];i||(i=h[e]={});var a=i[t];return a||(a=new s(e,t),r.shaderCount++,l(a),i[t]=a,f.push(a)),a},restore:function(){c={},u={};for(var t=0;t<f.length;++t)l(f[t])},shader:o,frag:-1,vert:-1}}function E(t,e,r,n,i,a,o){function s(i){var a;a=null===e.next?5121:e.next.colorAttachments[0].texture._texture.type;var o=0,s=0,l=n.framebufferWidth,c=n.framebufferHeight,u=null;return W(i)?u=i:i&&(o=0|i.x,s=0|i.y,l=0|(i.width||n.framebufferWidth-o),c=0|(i.height||n.framebufferHeight-s),u=i.data||null),r(),i=l*c*4,u||(5121===a?u=new Uint8Array(i):5126===a&&(u=u||new Float32Array(i))),t.pixelStorei(3333,4),t.readPixels(o,s,l,c,6408,a,u),u}return function(t){return t&&"framebuffer"in t?function(t){var r;return e.setFBO({framebuffer:t.framebuffer},function(){r=s(t)}),r}(t):s(t)}}function C(t){return Array.prototype.slice.call(t)}function L(t){return C(t).join("")}function z(){function t(){var t=[],e=[];return j(function(){t.push.apply(t,C(arguments))},{def:function(){var n="v"+r++;return e.push(n),0<arguments.length&&(t.push(n,"="),t.push.apply(t,C(arguments)),t.push(";")),n},toString:function(){return L([0<e.length?"var "+e+";":"",L(t)])}})}function e(){function e(t,e){n(t,e,"=",r.def(t,e),";")}var r=t(),n=t(),i=r.toString,a=n.toString;return j(function(){r.apply(r,C(arguments))},{def:r.def,entry:r,exit:n,save:e,set:function(t,n,i){e(t,n),r(t,n,"=",i,";")},toString:function(){return i()+a()}})}var r=0,n=[],i=[],a=t(),o={};return{global:a,link:function(t){for(var e=0;e<i.length;++e)if(i[e]===t)return n[e];return e="g"+r++,n.push(e),i.push(t),e},block:t,proc:function(t,r){function n(){var t="a"+i.length;return i.push(t),t}var i=[];r=r||0;for(var a=0;a<r;++a)n();var s=(a=e()).toString;return o[t]=j(a,{arg:n,toString:function(){return L(["function(",i.join(),"){",s(),"}"])}})},scope:e,cond:function(){var t=L(arguments),r=e(),n=e(),i=r.toString,a=n.toString;return j(r,{then:function(){return r.apply(r,C(arguments)),this},else:function(){return n.apply(n,C(arguments)),this},toString:function(){var e=a();return e&&(e="else{"+e+"}"),L(["if(",t,"){",i(),"}",e])}})},compile:function(){var t=['"use strict";',a,"return {"];Object.keys(o).forEach(function(e){t.push('"',e,'":',o[e].toString(),",")}),t.push("}");var e=L(t).replace(/;/g,";\n").replace(/}/g,"}\n").replace(/{/g,"{\n");return Function.apply(null,n.concat(e)).apply(null,i)}}}function O(t){return Array.isArray(t)||W(t)||l(t)}function I(t){return t.sort(function(t,e){return"viewport"===t?-1:"viewport"===e?1:t<e?-1:1})}function D(t,e,r,n){this.thisDep=t,this.contextDep=e,this.propDep=r,this.append=n}function P(t){return t&&!(t.thisDep||t.contextDep||t.propDep)}function R(t){return new D(!1,!1,!1,t)}function F(t,e){var r=t.type;return 0===r?new D(!0,1<=(r=t.data.length),2<=r,e):4===r?new D((r=t.data).thisDep,r.contextDep,r.propDep,e):new D(3===r,2===r,1===r,e)}function B(t,e,r,n,i,o,s,l,c,u,h,f,p,d,g){function m(t){return t.replace(".","_")}function y(t,e,r){var n=m(t);nt.push(t),et[n]=tt[n]=!!r,it[n]=e}function x(t,e,r){var n=m(t);nt.push(t),Array.isArray(r)?(tt[n]=r.slice(),et[n]=r.slice()):tt[n]=et[n]=r,at[n]=e}function b(){var t=z(),r=t.link,n=t.global;t.id=lt++,t.batchId="0";var i=r(ot),a=t.shared={props:"a0"};Object.keys(ot).forEach(function(t){a[t]=n.def(i,".",t)});var o=t.next={},s=t.current={};Object.keys(at).forEach(function(t){Array.isArray(tt[t])&&(o[t]=n.def(a.next,".",t),s[t]=n.def(a.current,".",t))});var l=t.constants={};Object.keys(st).forEach(function(t){l[t]=n.def(JSON.stringify(st[t]))}),t.invoke=function(e,n){switch(n.type){case 0:var i=["this",a.context,a.props,t.batchId];return e.def(r(n.data),".call(",i.slice(0,Math.max(n.data.length+1,4)),")");case 1:return e.def(a.props,n.data);case 2:return e.def(a.context,n.data);case 3:return e.def("this",n.data);case 4:return n.data.append(t,e),n.data.ref}},t.attribCache={};var c={};return t.scopeAttrib=function(t){if((t=e.id(t))in c)return c[t];var n=u.scope[t];return n||(n=u.scope[t]=new Z),c[t]=r(n)},t}function _(t,e){var r=t.static,n=t.dynamic;if("framebuffer"in r){var i=r.framebuffer;return i?(i=l.getFramebuffer(i),R(function(t,e){var r=t.link(i),n=t.shared;return e.set(n.framebuffer,".next",r),n=n.context,e.set(n,".framebufferWidth",r+".width"),e.set(n,".framebufferHeight",r+".height"),r})):R(function(t,e){var r=t.shared;return e.set(r.framebuffer,".next","null"),r=r.context,e.set(r,".framebufferWidth",r+".drawingBufferWidth"),e.set(r,".framebufferHeight",r+".drawingBufferHeight"),"null"})}if("framebuffer"in n){var a=n.framebuffer;return F(a,function(t,e){var r=t.invoke(e,a),n=t.shared,i=n.framebuffer;r=e.def(i,".getFramebuffer(",r,")");return e.set(i,".next",r),n=n.context,e.set(n,".framebufferWidth",r+"?"+r+".width:"+n+".drawingBufferWidth"),e.set(n,".framebufferHeight",r+"?"+r+".height:"+n+".drawingBufferHeight"),r})}return null}function w(t){function r(t){if(t in n){var r=e.id(n[t]);return(t=R(function(){return r})).id=r,t}if(t in i){var a=i[t];return F(a,function(t,e){var r=t.invoke(e,a);return e.def(t.shared.strings,".id(",r,")")})}return null}var n=t.static,i=t.dynamic,a=r("frag"),o=r("vert"),s=null;return P(a)&&P(o)?(s=h.program(o.id,a.id),t=R(function(t,e){return t.link(s)})):t=new D(a&&a.thisDep||o&&o.thisDep,a&&a.contextDep||o&&o.contextDep,a&&a.propDep||o&&o.propDep,function(t,e){var r,n,i=t.shared.shader;return r=a?a.append(t,e):e.def(i,".","frag"),n=o?o.append(t,e):e.def(i,".","vert"),e.def(i+".program("+n+","+r+")")}),{frag:a,vert:o,progVar:t,program:s}}function k(t,e){function r(t,e){if(t in n){var r=0|n[t];return R(function(t,n){return e&&(t.OFFSET=r),r})}if(t in i){var o=i[t];return F(o,function(t,r){var n=t.invoke(r,o);return e&&(t.OFFSET=n),n})}return e&&a?R(function(t,e){return t.OFFSET="0",0}):null}var n=t.static,i=t.dynamic,a=function(){if("elements"in n){var t=n.elements;O(t)?t=o.getElements(o.create(t,!0)):t&&(t=o.getElements(t));var e=R(function(e,r){if(t){var n=e.link(t);return e.ELEMENTS=n}return e.ELEMENTS=null});return e.value=t,e}if("elements"in i){var r=i.elements;return F(r,function(t,e){var n=(i=t.shared).isBufferArgs,i=i.elements,a=t.invoke(e,r),o=e.def("null");n=e.def(n,"(",a,")"),a=t.cond(n).then(o,"=",i,".createStream(",a,");").else(o,"=",i,".getElements(",a,");");return e.entry(a),e.exit(t.cond(n).then(i,".destroyStream(",o,");")),t.ELEMENTS=o})}return null}(),s=r("offset",!0);return{elements:a,primitive:function(){if("primitive"in n){var t=n.primitive;return R(function(e,r){return rt[t]})}if("primitive"in i){var e=i.primitive;return F(e,function(t,r){var n=t.constants.primTypes,i=t.invoke(r,e);return r.def(n,"[",i,"]")})}return a?P(a)?a.value?R(function(t,e){return e.def(t.ELEMENTS,".primType")}):R(function(){return 4}):new D(a.thisDep,a.contextDep,a.propDep,function(t,e){var r=t.ELEMENTS;return e.def(r,"?",r,".primType:",4)}):null}(),count:function(){if("count"in n){var t=0|n.count;return R(function(){return t})}if("count"in i){var e=i.count;return F(e,function(t,r){return t.invoke(r,e)})}return a?P(a)?a?s?new D(s.thisDep,s.contextDep,s.propDep,function(t,e){return e.def(t.ELEMENTS,".vertCount-",t.OFFSET)}):R(function(t,e){return e.def(t.ELEMENTS,".vertCount")}):R(function(){return-1}):new D(a.thisDep||s.thisDep,a.contextDep||s.contextDep,a.propDep||s.propDep,function(t,e){var r=t.ELEMENTS;return t.OFFSET?e.def(r,"?",r,".vertCount-",t.OFFSET,":-1"):e.def(r,"?",r,".vertCount:-1")}):null}(),instances:r("instances",!1),offset:s}}function A(t,r){var n=t.static,a=t.dynamic,o={};return Object.keys(n).forEach(function(t){var r=n[t],a=e.id(t),s=new Z;if(O(r))s.state=1,s.buffer=i.getBuffer(i.create(r,34962,!1,!0)),s.type=0;else if(c=i.getBuffer(r))s.state=1,s.buffer=c,s.type=0;else if("constant"in r){var l=r.constant;s.buffer="null",s.state=2,"number"==typeof l?s.x=l:bt.forEach(function(t,e){e<l.length&&(s[t]=l[e])})}else{var c=O(r.buffer)?i.getBuffer(i.create(r.buffer,34962,!1,!0)):i.getBuffer(r.buffer),u=0|r.offset,h=0|r.stride,f=0|r.size,p=!!r.normalized,d=0;"type"in r&&(d=J[r.type]),r=0|r.divisor,s.buffer=c,s.state=1,s.size=f,s.normalized=p,s.type=d||c.dtype,s.offset=u,s.stride=h,s.divisor=r}o[t]=R(function(t,e){var r=t.attribCache;if(a in r)return r[a];var n={isStream:!1};return Object.keys(s).forEach(function(t){n[t]=s[t]}),s.buffer&&(n.buffer=t.link(s.buffer),n.type=n.type||n.buffer+".dtype"),r[a]=n})}),Object.keys(a).forEach(function(t){var e=a[t];o[t]=F(e,function(t,r){function n(t){r(l[t],"=",i,".",t,"|0;")}var i=t.invoke(r,e),a=t.shared,o=a.isBufferArgs,s=a.buffer,l={isStream:r.def(!1)},c=new Z;c.state=1,Object.keys(c).forEach(function(t){l[t]=r.def(""+c[t])});var u=l.buffer,h=l.type;return r("if(",o,"(",i,")){",l.isStream,"=true;",u,"=",s,".createStream(",34962,",",i,");",h,"=",u,".dtype;","}else{",u,"=",s,".getBuffer(",i,");","if(",u,"){",h,"=",u,".dtype;",'}else if("constant" in ',i,"){",l.state,"=",2,";","if(typeof "+i+'.constant === "number"){',l[bt[0]],"=",i,".constant;",bt.slice(1).map(function(t){return l[t]}).join("="),"=0;","}else{",bt.map(function(t,e){return l[t]+"="+i+".constant.length>"+e+"?"+i+".constant["+e+"]:0;"}).join(""),"}}else{","if(",o,"(",i,".buffer)){",u,"=",s,".createStream(",34962,",",i,".buffer);","}else{",u,"=",s,".getBuffer(",i,".buffer);","}",h,'="type" in ',i,"?",a.glTypes,"[",i,".type]:",u,".dtype;",l.normalized,"=!!",i,".normalized;"),n("size"),n("offset"),n("stride"),n("divisor"),r("}}"),r.exit("if(",l.isStream,"){",s,".destroyStream(",u,");","}"),l})}),o}function M(t,e,r,n,i){var o=_(t),s=function(t,e,r){function n(t){if(t in i){var r=i[t];t=!0;var n,o,s=0|r.x,l=0|r.y;return"width"in r?n=0|r.width:t=!1,"height"in r?o=0|r.height:t=!1,new D(!t&&e&&e.thisDep,!t&&e&&e.contextDep,!t&&e&&e.propDep,function(t,e){var i=t.shared.context,a=n;"width"in r||(a=e.def(i,".","framebufferWidth","-",s));var c=o;return"height"in r||(c=e.def(i,".","framebufferHeight","-",l)),[s,l,a,c]})}if(t in a){var c=a[t];return t=F(c,function(t,e){var r=t.invoke(e,c),n=t.shared.context,i=e.def(r,".x|0"),a=e.def(r,".y|0");return[i,a,e.def('"width" in ',r,"?",r,".width|0:","(",n,".","framebufferWidth","-",i,")"),r=e.def('"height" in ',r,"?",r,".height|0:","(",n,".","framebufferHeight","-",a,")")]}),e&&(t.thisDep=t.thisDep||e.thisDep,t.contextDep=t.contextDep||e.contextDep,t.propDep=t.propDep||e.propDep),t}return e?new D(e.thisDep,e.contextDep,e.propDep,function(t,e){var r=t.shared.context;return[0,0,e.def(r,".","framebufferWidth"),e.def(r,".","framebufferHeight")]}):null}var i=t.static,a=t.dynamic;if(t=n("viewport")){var o=t;t=new D(t.thisDep,t.contextDep,t.propDep,function(t,e){var r=o.append(t,e),n=t.shared.context;return e.set(n,".viewportWidth",r[2]),e.set(n,".viewportHeight",r[3]),r})}return{viewport:t,scissor_box:n("scissor.box")}}(t,o),l=k(t),c=function(t,e){var r=t.static,n=t.dynamic,i={};return nt.forEach(function(t){function e(e,a){if(t in r){var s=e(r[t]);i[o]=R(function(){return s})}else if(t in n){var l=n[t];i[o]=F(l,function(t,e){return a(t,e,t.invoke(e,l))})}}var o=m(t);switch(t){case"cull.enable":case"blend.enable":case"dither":case"stencil.enable":case"depth.enable":case"scissor.enable":case"polygonOffset.enable":case"sample.alpha":case"sample.enable":case"depth.mask":return e(function(t){return t},function(t,e,r){return r});case"depth.func":return e(function(t){return kt[t]},function(t,e,r){return e.def(t.constants.compareFuncs,"[",r,"]")});case"depth.range":return e(function(t){return t},function(t,e,r){return[e.def("+",r,"[0]"),e=e.def("+",r,"[1]")]});case"blend.func":return e(function(t){return[wt["srcRGB"in t?t.srcRGB:t.src],wt["dstRGB"in t?t.dstRGB:t.dst],wt["srcAlpha"in t?t.srcAlpha:t.src],wt["dstAlpha"in t?t.dstAlpha:t.dst]]},function(t,e,r){function n(t,n){return e.def('"',t,n,'" in ',r,"?",r,".",t,n,":",r,".",t)}t=t.constants.blendFuncs;var i=n("src","RGB"),a=n("dst","RGB"),o=(i=e.def(t,"[",i,"]"),e.def(t,"[",n("src","Alpha"),"]"));return[i,a=e.def(t,"[",a,"]"),o,t=e.def(t,"[",n("dst","Alpha"),"]")]});case"blend.equation":return e(function(t){return"string"==typeof t?[$[t],$[t]]:"object"==typeof t?[$[t.rgb],$[t.alpha]]:void 0},function(t,e,r){var n=t.constants.blendEquations,i=e.def(),a=e.def();return(t=t.cond("typeof ",r,'==="string"')).then(i,"=",a,"=",n,"[",r,"];"),t.else(i,"=",n,"[",r,".rgb];",a,"=",n,"[",r,".alpha];"),e(t),[i,a]});case"blend.color":return e(function(t){return a(4,function(e){return+t[e]})},function(t,e,r){return a(4,function(t){return e.def("+",r,"[",t,"]")})});case"stencil.mask":return e(function(t){return 0|t},function(t,e,r){return e.def(r,"|0")});case"stencil.func":return e(function(t){return[kt[t.cmp||"keep"],t.ref||0,"mask"in t?t.mask:-1]},function(t,e,r){return[t=e.def('"cmp" in ',r,"?",t.constants.compareFuncs,"[",r,".cmp]",":",7680),e.def(r,".ref|0"),e=e.def('"mask" in ',r,"?",r,".mask|0:-1")]});case"stencil.opFront":case"stencil.opBack":return e(function(e){return["stencil.opBack"===t?1029:1028,At[e.fail||"keep"],At[e.zfail||"keep"],At[e.zpass||"keep"]]},function(e,r,n){function i(t){return r.def('"',t,'" in ',n,"?",a,"[",n,".",t,"]:",7680)}var a=e.constants.stencilOps;return["stencil.opBack"===t?1029:1028,i("fail"),i("zfail"),i("zpass")]});case"polygonOffset.offset":return e(function(t){return[0|t.factor,0|t.units]},function(t,e,r){return[e.def(r,".factor|0"),e=e.def(r,".units|0")]});case"cull.face":return e(function(t){var e=0;return"front"===t?e=1028:"back"===t&&(e=1029),e},function(t,e,r){return e.def(r,'==="front"?',1028,":",1029)});case"lineWidth":return e(function(t){return t},function(t,e,r){return r});case"frontFace":return e(function(t){return Mt[t]},function(t,e,r){return e.def(r+'==="cw"?2304:2305')});case"colorMask":return e(function(t){return t.map(function(t){return!!t})},function(t,e,r){return a(4,function(t){return"!!"+r+"["+t+"]"})});case"sample.coverage":return e(function(t){return["value"in t?t.value:1,!!t.invert]},function(t,e,r){return[e.def('"value" in ',r,"?+",r,".value:1"),e=e.def("!!",r,".invert")]})}}),i}(t),u=w(t),h=s.viewport;return h&&(c.viewport=h),(s=s[h=m("scissor.box")])&&(c[h]=s),(o={framebuffer:o,draw:l,shader:u,state:c,dirty:s=0<Object.keys(c).length}).profile=function(t){var e,r=t.static;if(t=t.dynamic,"profile"in r){var n=!!r.profile;(e=R(function(t,e){return n})).enable=n}else if("profile"in t){var i=t.profile;e=F(i,function(t,e){return t.invoke(e,i)})}return e}(t),o.uniforms=function(t,e){var r=t.static,n=t.dynamic,i={};return Object.keys(r).forEach(function(t){var e,n=r[t];if("number"==typeof n||"boolean"==typeof n)e=R(function(){return n});else if("function"==typeof n){var o=n._reglType;"texture2d"===o||"textureCube"===o?e=R(function(t){return t.link(n)}):"framebuffer"!==o&&"framebufferCube"!==o||(e=R(function(t){return t.link(n.color[0])}))}else v(n)&&(e=R(function(t){return t.global.def("[",a(n.length,function(t){return n[t]}),"]")}));e.value=n,i[t]=e}),Object.keys(n).forEach(function(t){var e=n[t];i[t]=F(e,function(t,r){return t.invoke(r,e)})}),i}(r),o.attributes=A(e),o.context=function(t){var e=t.static,r=t.dynamic,n={};return Object.keys(e).forEach(function(t){var r=e[t];n[t]=R(function(t,e){return"number"==typeof r||"boolean"==typeof r?""+r:t.link(r)})}),Object.keys(r).forEach(function(t){var e=r[t];n[t]=F(e,function(t,r){return t.invoke(r,e)})}),n}(n),o}function T(t,e,r){var n=t.shared.context,i=t.scope();Object.keys(r).forEach(function(a){e.save(n,"."+a),i(n,".",a,"=",r[a].append(t,e),";")}),e(i)}function S(t,e,r,n){var i,a=(s=t.shared).gl,o=s.framebuffer;Q&&(i=e.def(s.extensions,".webgl_draw_buffers"));var s=(l=t.constants).drawBuffer,l=l.backBuffer;t=r?r.append(t,e):e.def(o,".next"),n||e("if(",t,"!==",o,".cur){"),e("if(",t,"){",a,".bindFramebuffer(",36160,",",t,".framebuffer);"),Q&&e(i,".drawBuffersWEBGL(",s,"[",t,".colorAttachments.length]);"),e("}else{",a,".bindFramebuffer(",36160,",null);"),Q&&e(i,".drawBuffersWEBGL(",l,");"),e("}",o,".cur=",t,";"),n||e("}")}function E(t,e,r){var n=t.shared,i=n.gl,o=t.current,s=t.next,l=n.current,c=n.next,u=t.cond(l,".dirty");nt.forEach(function(e){var n,h;if(!((e=m(e))in r.state))if(e in s){n=s[e],h=o[e];var f=a(tt[e].length,function(t){return u.def(n,"[",t,"]")});u(t.cond(f.map(function(t,e){return t+"!=="+h+"["+e+"]"}).join("||")).then(i,".",at[e],"(",f,");",f.map(function(t,e){return h+"["+e+"]="+t}).join(";"),";"))}else n=u.def(c,".",e),f=t.cond(n,"!==",l,".",e),u(f),e in it?f(t.cond(n).then(i,".enable(",it[e],");").else(i,".disable(",it[e],");"),l,".",e,"=",n,";"):f(i,".",at[e],"(",n,");",l,".",e,"=",n,";")}),0===Object.keys(r.state).length&&u(l,".dirty=false;"),e(u)}function C(t,e,r,n){var i=t.shared,a=t.current,o=i.current,s=i.gl;I(Object.keys(r)).forEach(function(i){var l=r[i];if(!n||n(l)){var c=l.append(t,e);if(it[i]){var u=it[i];P(l)?e(s,c?".enable(":".disable(",u,");"):e(t.cond(c).then(s,".enable(",u,");").else(s,".disable(",u,");")),e(o,".",i,"=",c,";")}else if(v(c)){var h=a[i];e(s,".",at[i],"(",c,");",c.map(function(t,e){return h+"["+e+"]="+t}).join(";"),";")}else e(s,".",at[i],"(",c,");",o,".",i,"=",c,";")}})}function L(t,e){K&&(t.instancing=e.def(t.shared.extensions,".angle_instanced_arrays"))}function B(t,e,r,n,i){function a(){return"undefined"==typeof performance?"Date.now()":"performance.now()"}function o(t){t(c=e.def(),"=",a(),";"),"string"==typeof i?t(f,".count+=",i,";"):t(f,".count++;"),d&&(n?t(u=e.def(),"=",g,".getNumPendingQueries();"):t(g,".beginQuery(",f,");"))}function s(t){t(f,".cpuTime+=",a(),"-",c,";"),d&&(n?t(g,".pushScopeStats(",u,",",g,".getNumPendingQueries(),",f,");"):t(g,".endQuery();"))}function l(t){var r=e.def(p,".profile");e(p,".profile=",t,";"),e.exit(p,".profile=",r,";")}var c,u,h=t.shared,f=t.stats,p=h.current,g=h.timer;if(r=r.profile){if(P(r))return void(r.enable?(o(e),s(e.exit),l("true")):l("false"));l(r=r.append(t,e))}else r=e.def(p,".profile");o(h=t.block()),e("if(",r,"){",h,"}"),s(t=t.block()),e.exit("if(",r,"){",t,"}")}function N(t,e,r,n,i){function a(r,n,i){function a(){e("if(!",u,".buffer){",l,".enableVertexAttribArray(",c,");}");var r,a=i.type;r=i.size?e.def(i.size,"||",n):n,e("if(",u,".type!==",a,"||",u,".size!==",r,"||",p.map(function(t){return u+"."+t+"!=="+i[t]}).join("||"),"){",l,".bindBuffer(",34962,",",h,".buffer);",l,".vertexAttribPointer(",[c,r,a,i.normalized,i.stride,i.offset],");",u,".type=",a,";",u,".size=",r,";",p.map(function(t){return u+"."+t+"="+i[t]+";"}).join(""),"}"),K&&(a=i.divisor,e("if(",u,".divisor!==",a,"){",t.instancing,".vertexAttribDivisorANGLE(",[c,a],");",u,".divisor=",a,";}"))}function s(){e("if(",u,".buffer){",l,".disableVertexAttribArray(",c,");","}if(",bt.map(function(t,e){return u+"."+t+"!=="+f[e]}).join("||"),"){",l,".vertexAttrib4f(",c,",",f,");",bt.map(function(t,e){return u+"."+t+"="+f[e]+";"}).join(""),"}")}var l=o.gl,c=e.def(r,".location"),u=e.def(o.attributes,"[",c,"]");r=i.state;var h=i.buffer,f=[i.x,i.y,i.z,i.w],p=["buffer","normalized","offset","stride"];1===r?a():2===r?s():(e("if(",r,"===",1,"){"),a(),e("}else{"),s(),e("}"))}var o=t.shared;n.forEach(function(n){var o,s=n.name,l=r.attributes[s];if(l){if(!i(l))return;o=l.append(t,e)}else{if(!i(Tt))return;var c=t.scopeAttrib(s);o={},Object.keys(new Z).forEach(function(t){o[t]=e.def(c,".",t)})}a(t.link(n),function(t){switch(t){case 35664:case 35667:case 35671:return 2;case 35665:case 35668:case 35672:return 3;case 35666:case 35669:case 35673:return 4;default:return 1}}(n.info.type),o)})}function j(t,r,n,i,o){for(var s,l=t.shared,c=l.gl,u=0;u<i.length;++u){var h,f=(g=i[u]).name,p=g.info.type,d=n.uniforms[f],g=t.link(g)+".location";if(d){if(!o(d))continue;if(P(d)){if(f=d.value,35678===p||35680===p)r(c,".uniform1i(",g,",",(p=t.link(f._texture||f.color[0]._texture))+".bind());"),r.exit(p,".unbind();");else if(35674===p||35675===p||35676===p)d=2,35675===p?d=3:35676===p&&(d=4),r(c,".uniformMatrix",d,"fv(",g,",false,",f=t.global.def("new Float32Array(["+Array.prototype.slice.call(f)+"])"),");");else{switch(p){case 5126:s="1f";break;case 35664:s="2f";break;case 35665:s="3f";break;case 35666:s="4f";break;case 35670:case 5124:s="1i";break;case 35671:case 35667:s="2i";break;case 35672:case 35668:s="3i";break;case 35673:s="4i";break;case 35669:s="4i"}r(c,".uniform",s,"(",g,",",v(f)?Array.prototype.slice.call(f):f,");")}continue}h=d.append(t,r)}else{if(!o(Tt))continue;h=r.def(l.uniforms,"[",e.id(f),"]")}switch(35678===p?r("if(",h,"&&",h,'._reglType==="framebuffer"){',h,"=",h,".color[0];","}"):35680===p&&r("if(",h,"&&",h,'._reglType==="framebufferCube"){',h,"=",h,".color[0];","}"),f=1,p){case 35678:case 35680:p=r.def(h,"._texture"),r(c,".uniform1i(",g,",",p,".bind());"),r.exit(p,".unbind();");continue;case 5124:case 35670:s="1i";break;case 35667:case 35671:s="2i",f=2;break;case 35668:case 35672:s="3i",f=3;break;case 35669:case 35673:s="4i",f=4;break;case 5126:s="1f";break;case 35664:s="2f",f=2;break;case 35665:s="3f",f=3;break;case 35666:s="4f",f=4;break;case 35674:s="Matrix2fv";break;case 35675:s="Matrix3fv";break;case 35676:s="Matrix4fv"}if(r(c,".uniform",s,"(",g,","),"M"===s.charAt(0)){g=Math.pow(p-35674+2,2);var m=t.global.def("new Float32Array(",g,")");r("false,(Array.isArray(",h,")||",h," instanceof Float32Array)?",h,":(",a(g,function(t){return m+"["+t+"]="+h+"["+t+"]"}),",",m,")")}else r(1<f?a(f,function(t){return h+"["+t+"]"}):h);r(");")}}function V(t,e,r,n){function i(i){var a=f[i];return a?a.contextDep&&n.contextDynamic||a.propDep?a.append(t,r):a.append(t,e):e.def(h,".",i)}function a(){function t(){r(l,".drawElementsInstancedANGLE(",[d,v,m,g+"<<(("+m+"-5121)>>1)",s],");")}function e(){r(l,".drawArraysInstancedANGLE(",[d,g,v,s],");")}p?y?t():(r("if(",p,"){"),t(),r("}else{"),e(),r("}")):e()}function o(){function t(){r(u+".drawElements("+[d,v,m,g+"<<(("+m+"-5121)>>1)"]+");")}function e(){r(u+".drawArrays("+[d,g,v]+");")}p?y?t():(r("if(",p,"){"),t(),r("}else{"),e(),r("}")):e()}var s,l,c=t.shared,u=c.gl,h=c.draw,f=n.draw,p=function(){var i=f.elements,a=e;return i?((i.contextDep&&n.contextDynamic||i.propDep)&&(a=r),i=i.append(t,a)):i=a.def(h,".","elements"),i&&a("if("+i+")"+u+".bindBuffer(34963,"+i+".buffer.buffer);"),i}(),d=i("primitive"),g=i("offset"),v=function(){var i=f.count,a=e;return i?((i.contextDep&&n.contextDynamic||i.propDep)&&(a=r),i=i.append(t,a)):i=a.def(h,".","count"),i}();if("number"==typeof v){if(0===v)return}else r("if(",v,"){"),r.exit("}");K&&(s=i("instances"),l=t.instancing);var m=p+".type",y=f.elements&&P(f.elements);K&&("number"!=typeof s||0<=s)?"string"==typeof s?(r("if(",s,">0){"),a(),r("}else if(",s,"<0){"),o(),r("}")):a():o()}function q(t,e,r,n,i){return i=(e=b()).proc("body",i),K&&(e.instancing=i.def(e.shared.extensions,".angle_instanced_arrays")),t(e,i,r,n),e.compile().body}function H(t,e,r,n){L(t,e),N(t,e,r,n.attributes,function(){return!0}),j(t,e,r,n.uniforms,function(){return!0}),V(t,e,e,r)}function G(t,e,r,n){function i(){return!0}t.batchId="a1",L(t,e),N(t,e,r,n.attributes,i),j(t,e,r,n.uniforms,i),V(t,e,e,r)}function Y(t,e,r,n){function i(t){return t.contextDep&&o||t.propDep}function a(t){return!i(t)}L(t,e);var o=r.contextDep,s=e.def(),l=e.def();t.shared.props=l,t.batchId=s;var c=t.scope(),u=t.scope();e(c.entry,"for(",s,"=0;",s,"<","a1",";++",s,"){",l,"=","a0","[",s,"];",u,"}",c.exit),r.needsContext&&T(t,u,r.context),r.needsFramebuffer&&S(t,u,r.framebuffer),C(t,u,r.state,i),r.profile&&i(r.profile)&&B(t,u,r,!1,!0),n?(N(t,c,r,n.attributes,a),N(t,u,r,n.attributes,i),j(t,c,r,n.uniforms,a),j(t,u,r,n.uniforms,i),V(t,c,u,r)):(e=t.global.def("{}"),n=r.shader.progVar.append(t,u),l=u.def(n,".id"),c=u.def(e,"[",l,"]"),u(t.shared.gl,".useProgram(",n,".program);","if(!",c,"){",c,"=",e,"[",l,"]=",t.link(function(e){return q(G,t,r,e,2)}),"(",n,");}",c,".call(this,a0[",s,"],",s,");"))}function W(t,r){function n(e){var n=r.shader[e];n&&i.set(a.shader,"."+e,n.append(t,i))}var i=t.proc("scope",3);t.batchId="a2";var a=t.shared,o=a.current;T(t,i,r.context),r.framebuffer&&r.framebuffer.append(t,i),I(Object.keys(r.state)).forEach(function(e){var n=r.state[e].append(t,i);v(n)?n.forEach(function(r,n){i.set(t.next[e],"["+n+"]",r)}):i.set(a.next,"."+e,n)}),B(t,i,r,!0,!0),["elements","offset","count","instances","primitive"].forEach(function(e){var n=r.draw[e];n&&i.set(a.draw,"."+e,""+n.append(t,i))}),Object.keys(r.uniforms).forEach(function(n){i.set(a.uniforms,"["+e.id(n)+"]",r.uniforms[n].append(t,i))}),Object.keys(r.attributes).forEach(function(e){var n=r.attributes[e].append(t,i),a=t.scopeAttrib(e);Object.keys(new Z).forEach(function(t){i.set(a,"."+t,n[t])})}),n("vert"),n("frag"),0<Object.keys(r.state).length&&(i(o,".dirty=true;"),i.exit(o,".dirty=true;")),i("a1(",t.shared.context,",a0,",t.batchId,");")}function X(t,e,r){var n=e.static[r];if(n&&function(t){if("object"==typeof t&&!v(t)){for(var e=Object.keys(t),r=0;r<e.length;++r)if(U.isDynamic(t[e[r]]))return!0;return!1}}(n)){var i=t.global,a=Object.keys(n),o=!1,s=!1,l=!1,c=t.global.def("{}");a.forEach(function(e){var r=n[e];if(U.isDynamic(r))"function"==typeof r&&(r=n[e]=U.unbox(r)),e=F(r,null),o=o||e.thisDep,l=l||e.propDep,s=s||e.contextDep;else{switch(i(c,".",e,"="),typeof r){case"number":i(r);break;case"string":i('"',r,'"');break;case"object":Array.isArray(r)&&i("[",r.join(),"]");break;default:i(t.link(r))}i(";")}}),e.dynamic[r]=new U.DynamicVariable(4,{thisDep:o,contextDep:s,propDep:l,ref:c,append:function(t,e){a.forEach(function(r){var i=n[r];U.isDynamic(i)&&(i=t.invoke(e,i),e(c,".",r,"=",i,";"))})}}),delete e.static[r]}}var Z=u.Record,$={add:32774,subtract:32778,"reverse subtract":32779};r.ext_blend_minmax&&($.min=32775,$.max=32776);var K=r.angle_instanced_arrays,Q=r.webgl_draw_buffers,tt={dirty:!0,profile:g.profile},et={},nt=[],it={},at={};y("dither",3024),y("blend.enable",3042),x("blend.color","blendColor",[0,0,0,0]),x("blend.equation","blendEquationSeparate",[32774,32774]),x("blend.func","blendFuncSeparate",[1,0,1,0]),y("depth.enable",2929,!0),x("depth.func","depthFunc",513),x("depth.range","depthRange",[0,1]),x("depth.mask","depthMask",!0),x("colorMask","colorMask",[!0,!0,!0,!0]),y("cull.enable",2884),x("cull.face","cullFace",1029),x("frontFace","frontFace",2305),x("lineWidth","lineWidth",1),y("polygonOffset.enable",32823),x("polygonOffset.offset","polygonOffset",[0,0]),y("sample.alpha",32926),y("sample.enable",32928),x("sample.coverage","sampleCoverage",[1,!1]),y("stencil.enable",2960),x("stencil.mask","stencilMask",-1),x("stencil.func","stencilFunc",[519,0,-1]),x("stencil.opFront","stencilOpSeparate",[1028,7680,7680,7680]),x("stencil.opBack","stencilOpSeparate",[1029,7680,7680,7680]),y("scissor.enable",3089),x("scissor.box","scissor",[0,0,t.drawingBufferWidth,t.drawingBufferHeight]),x("viewport","viewport",[0,0,t.drawingBufferWidth,t.drawingBufferHeight]);var ot={gl:t,context:p,strings:e,next:et,current:tt,draw:f,elements:o,buffer:i,shader:h,attributes:u.state,uniforms:c,framebuffer:l,extensions:r,timer:d,isBufferArgs:O},st={primTypes:rt,compareFuncs:kt,blendFuncs:wt,blendEquations:$,stencilOps:At,glTypes:J,orientationType:Mt};Q&&(st.backBuffer=[1029],st.drawBuffer=a(n.maxDrawbuffers,function(t){return 0===t?[0]:a(t,function(t){return 36064+t})}));var lt=0;return{next:et,current:tt,procs:function(){var t=b(),e=t.proc("poll"),r=t.proc("refresh"),i=t.block();e(i),r(i);var o,s=t.shared,l=s.gl,c=s.next,u=s.current;i(u,".dirty=false;"),S(t,e),S(t,r,null,!0),K&&(o=t.link(K));for(var h=0;h<n.maxAttributes;++h){var f=r.def(s.attributes,"[",h,"]"),p=t.cond(f,".buffer");p.then(l,".enableVertexAttribArray(",h,");",l,".bindBuffer(",34962,",",f,".buffer.buffer);",l,".vertexAttribPointer(",h,",",f,".size,",f,".type,",f,".normalized,",f,".stride,",f,".offset);").else(l,".disableVertexAttribArray(",h,");",l,".vertexAttrib4f(",h,",",f,".x,",f,".y,",f,".z,",f,".w);",f,".buffer=null;"),r(p),K&&r(o,".vertexAttribDivisorANGLE(",h,",",f,".divisor);")}return Object.keys(it).forEach(function(n){var a=it[n],o=i.def(c,".",n),s=t.block();s("if(",o,"){",l,".enable(",a,")}else{",l,".disable(",a,")}",u,".",n,"=",o,";"),r(s),e("if(",o,"!==",u,".",n,"){",s,"}")}),Object.keys(at).forEach(function(n){var o,s,h=at[n],f=tt[n],p=t.block();p(l,".",h,"("),v(f)?(h=f.length,o=t.global.def(c,".",n),s=t.global.def(u,".",n),p(a(h,function(t){return o+"["+t+"]"}),");",a(h,function(t){return s+"["+t+"]="+o+"["+t+"];"}).join("")),e("if(",a(h,function(t){return o+"["+t+"]!=="+s+"["+t+"]"}).join("||"),"){",p,"}")):(o=i.def(c,".",n),s=i.def(u,".",n),p(o,");",u,".",n,"=",o,";"),e("if(",o,"!==",s,"){",p,"}")),r(p)}),t.compile()}(),compile:function(t,e,r,n,i){var a=b();return a.stats=a.link(i),Object.keys(e.static).forEach(function(t){X(a,e,t)}),_t.forEach(function(e){X(a,t,e)}),r=M(t,e,r,n),function(t,e){var r=t.proc("draw",1);L(t,r),T(t,r,e.context),S(t,r,e.framebuffer),E(t,r,e),C(t,r,e.state),B(t,r,e,!1,!0);var n=e.shader.progVar.append(t,r);if(r(t.shared.gl,".useProgram(",n,".program);"),e.shader.program)H(t,r,e,e.shader.program);else{var i=t.global.def("{}"),a=r.def(n,".id"),o=r.def(i,"[",a,"]");r(t.cond(o).then(o,".call(this,a0);").else(o,"=",i,"[",a,"]=",t.link(function(r){return q(H,t,e,r,1)}),"(",n,");",o,".call(this,a0);"))}0<Object.keys(e.state).length&&r(t.shared.current,".dirty=true;")}(a,r),W(a,r),function(t,e){function r(t){return t.contextDep&&i||t.propDep}var n=t.proc("batch",2);t.batchId="0",L(t,n);var i=!1,a=!0;Object.keys(e.context).forEach(function(t){i=i||e.context[t].propDep}),i||(T(t,n,e.context),a=!1);var o=!1;if((s=e.framebuffer)?(s.propDep?i=o=!0:s.contextDep&&i&&(o=!0),o||S(t,n,s)):S(t,n,null),e.state.viewport&&e.state.viewport.propDep&&(i=!0),E(t,n,e),C(t,n,e.state,function(t){return!r(t)}),e.profile&&r(e.profile)||B(t,n,e,!1,"a1"),e.contextDep=i,e.needsContext=a,e.needsFramebuffer=o,(a=e.shader.progVar).contextDep&&i||a.propDep)Y(t,n,e,null);else if(a=a.append(t,n),n(t.shared.gl,".useProgram(",a,".program);"),e.shader.program)Y(t,n,e,e.shader.program);else{var s=t.global.def("{}"),l=(o=n.def(a,".id"),n.def(s,"[",o,"]"));n(t.cond(l).then(l,".call(this,a0,a1);").else(l,"=",s,"[",o,"]=",t.link(function(r){return q(Y,t,e,r,2)}),"(",a,");",l,".call(this,a0,a1);"))}0<Object.keys(e.state).length&&n(t.shared.current,".dirty=true;")}(a,r),a.compile()}}}function N(t,e){for(var r=0;r<t.length;++r)if(t[r]===e)return r;return-1}var j=function(t,e){for(var r=Object.keys(e),n=0;n<r.length;++n)t[r[n]]=e[r[n]];return t},V=0,U={DynamicVariable:t,define:function(r,n){return new t(r,e(n+""))},isDynamic:function(e){return"function"==typeof e&&!e._reglType||e instanceof t},unbox:function(e,r){return"function"==typeof e?new t(0,e):e},accessor:e},q={next:"function"==typeof requestAnimationFrame?function(t){return requestAnimationFrame(t)}:function(t){return setTimeout(t,16)},cancel:"function"==typeof cancelAnimationFrame?function(t){return cancelAnimationFrame(t)}:clearTimeout},H="undefined"!=typeof performance&&performance.now?function(){return performance.now()}:function(){return+new Date},G=s();G.zero=s();var Y=function(t,e){var r=1;e.ext_texture_filter_anisotropic&&(r=t.getParameter(34047));var n=1,i=1;e.webgl_draw_buffers&&(n=t.getParameter(34852),i=t.getParameter(36063));var a=!!e.oes_texture_float;if(a){a=t.createTexture(),t.bindTexture(3553,a),t.texImage2D(3553,0,6408,1,1,0,6408,5126,null);var o=t.createFramebuffer();if(t.bindFramebuffer(36160,o),t.framebufferTexture2D(36160,36064,3553,a,0),t.bindTexture(3553,null),36053!==t.checkFramebufferStatus(36160))a=!1;else{t.viewport(0,0,1,1),t.clearColor(1,0,0,1),t.clear(16384);var s=G.allocType(5126,4);t.readPixels(0,0,1,1,6408,5126,s),t.getError()?a=!1:(t.deleteFramebuffer(o),t.deleteTexture(a),a=1===s[0]),G.freeType(s)}}return s=!0,"undefined"!=typeof navigator&&(/MSIE/.test(navigator.userAgent)||/Trident\//.test(navigator.appVersion)||/Edge/.test(navigator.userAgent))||(s=t.createTexture(),o=G.allocType(5121,36),t.activeTexture(33984),t.bindTexture(34067,s),t.texImage2D(34069,0,6408,3,3,0,6408,5121,o),G.freeType(o),t.bindTexture(34067,null),t.deleteTexture(s),s=!t.getError()),{colorBits:[t.getParameter(3410),t.getParameter(3411),t.getParameter(3412),t.getParameter(3413)],depthBits:t.getParameter(3414),stencilBits:t.getParameter(3415),subpixelBits:t.getParameter(3408),extensions:Object.keys(e).filter(function(t){return!!e[t]}),maxAnisotropic:r,maxDrawbuffers:n,maxColorAttachments:i,pointSizeDims:t.getParameter(33901),lineWidthDims:t.getParameter(33902),maxViewportDims:t.getParameter(3386),maxCombinedTextureUnits:t.getParameter(35661),maxCubeMapSize:t.getParameter(34076),maxRenderbufferSize:t.getParameter(34024),maxTextureUnits:t.getParameter(34930),maxTextureSize:t.getParameter(3379),maxAttributes:t.getParameter(34921),maxVertexUniforms:t.getParameter(36347),maxVertexTextureUnits:t.getParameter(35660),maxVaryingVectors:t.getParameter(36348),maxFragmentUniforms:t.getParameter(36349),glsl:t.getParameter(35724),renderer:t.getParameter(7937),vendor:t.getParameter(7936),version:t.getParameter(7938),readFloat:a,npotTextureCube:s}},W=function(t){return t instanceof Uint8Array||t instanceof Uint16Array||t instanceof Uint32Array||t instanceof Int8Array||t instanceof Int16Array||t instanceof Int32Array||t instanceof Float32Array||t instanceof Float64Array||t instanceof Uint8ClampedArray},X=function(t){return Object.keys(t).map(function(e){return t[e]})},Z={shape:function(t){for(var e=[];t.length;t=t[0])e.push(t.length);return e},flatten:function(t,e,r,n){var i=1;if(e.length)for(var a=0;a<e.length;++a)i*=e[a];else i=0;switch(r=n||G.allocType(r,i),e.length){case 0:break;case 1:for(n=e[0],e=0;e<n;++e)r[e]=t[e];break;case 2:for(n=e[0],e=e[1],a=i=0;a<n;++a)for(var o=t[a],s=0;s<e;++s)r[i++]=o[s];break;case 3:c(t,e[0],e[1],e[2],r,0);break;default:!function t(e,r,n,i,a){for(var o=1,s=n+1;s<r.length;++s)o*=r[s];var l=r[n];if(4==r.length-n){var u=r[n+1],h=r[n+2];for(r=r[n+3],s=0;s<l;++s)c(e[s],u,h,r,i,a),a+=o}else for(s=0;s<l;++s)t(e[s],r,n+1,i,a),a+=o}(t,e,0,r,0)}return r}},$={"[object Int8Array]":5120,"[object Int16Array]":5122,"[object Int32Array]":5124,"[object Uint8Array]":5121,"[object Uint8ClampedArray]":5121,"[object Uint16Array]":5123,"[object Uint32Array]":5125,"[object Float32Array]":5126,"[object Float64Array]":5121,"[object ArrayBuffer]":5121},J={int8:5120,int16:5122,int32:5124,uint8:5121,uint16:5123,uint32:5125,float:5126,float32:5126},K={dynamic:35048,stream:35040,static:35044},Q=Z.flatten,tt=Z.shape,et=[];et[5120]=1,et[5122]=2,et[5124]=4,et[5121]=1,et[5123]=2,et[5125]=4,et[5126]=4;var rt={points:0,point:0,lines:1,line:1,triangles:4,triangle:4,"line loop":2,"line strip":3,"triangle strip":5,"triangle fan":6},nt=new Float32Array(1),it=new Uint32Array(nt.buffer),at=[9984,9986,9985,9987],ot=[0,6409,6410,6407,6408],st={};st[6409]=st[6406]=st[6402]=1,st[34041]=st[6410]=2,st[6407]=st[35904]=3,st[6408]=st[35906]=4;var lt=m("HTMLCanvasElement"),ct=m("CanvasRenderingContext2D"),ut=m("ImageBitmap"),ht=m("HTMLImageElement"),ft=m("HTMLVideoElement"),pt=Object.keys($).concat([lt,ct,ut,ht,ft]),dt=[];dt[5121]=1,dt[5126]=4,dt[36193]=2,dt[5123]=2,dt[5125]=4;var gt=[];gt[32854]=2,gt[32855]=2,gt[36194]=2,gt[34041]=4,gt[33776]=.5,gt[33777]=.5,gt[33778]=1,gt[33779]=1,gt[35986]=.5,gt[35987]=1,gt[34798]=1,gt[35840]=.5,gt[35841]=.25,gt[35842]=.5,gt[35843]=.25,gt[36196]=.5;var vt=[];vt[32854]=2,vt[32855]=2,vt[36194]=2,vt[33189]=2,vt[36168]=1,vt[34041]=4,vt[35907]=4,vt[34836]=16,vt[34842]=8,vt[34843]=6;var mt=function(t,e,r,n,i){function a(t){this.id=c++,this.refCount=1,this.renderbuffer=t,this.format=32854,this.height=this.width=0,i.profile&&(this.stats={size:0})}function o(e){var r=e.renderbuffer;t.bindRenderbuffer(36161,null),t.deleteRenderbuffer(r),e.renderbuffer=null,e.refCount=0,delete u[e.id],n.renderbufferCount--}var s={rgba4:32854,rgb565:36194,"rgb5 a1":32855,depth:33189,stencil:36168,"depth stencil":34041};e.ext_srgb&&(s.srgba=35907),e.ext_color_buffer_half_float&&(s.rgba16f=34842,s.rgb16f=34843),e.webgl_color_buffer_float&&(s.rgba32f=34836);var l=[];Object.keys(s).forEach(function(t){l[s[t]]=t});var c=0,u={};return a.prototype.decRef=function(){0>=--this.refCount&&o(this)},i.profile&&(n.getTotalRenderbufferSize=function(){var t=0;return Object.keys(u).forEach(function(e){t+=u[e].stats.size}),t}),{create:function(e,r){function o(e,r){var n=0,a=0,u=32854;if("object"==typeof e&&e?("shape"in e?(n=0|(a=e.shape)[0],a=0|a[1]):("radius"in e&&(n=a=0|e.radius),"width"in e&&(n=0|e.width),"height"in e&&(a=0|e.height)),"format"in e&&(u=s[e.format])):"number"==typeof e?(n=0|e,a="number"==typeof r?0|r:n):e||(n=a=1),n!==c.width||a!==c.height||u!==c.format)return o.width=c.width=n,o.height=c.height=a,c.format=u,t.bindRenderbuffer(36161,c.renderbuffer),t.renderbufferStorage(36161,u,n,a),i.profile&&(c.stats.size=vt[c.format]*c.width*c.height),o.format=l[c.format],o}var c=new a(t.createRenderbuffer());return u[c.id]=c,n.renderbufferCount++,o(e,r),o.resize=function(e,r){var n=0|e,a=0|r||n;return n===c.width&&a===c.height?o:(o.width=c.width=n,o.height=c.height=a,t.bindRenderbuffer(36161,c.renderbuffer),t.renderbufferStorage(36161,c.format,n,a),i.profile&&(c.stats.size=vt[c.format]*c.width*c.height),o)},o._reglType="renderbuffer",o._renderbuffer=c,i.profile&&(o.stats=c.stats),o.destroy=function(){c.decRef()},o},clear:function(){X(u).forEach(o)},restore:function(){X(u).forEach(function(e){e.renderbuffer=t.createRenderbuffer(),t.bindRenderbuffer(36161,e.renderbuffer),t.renderbufferStorage(36161,e.format,e.width,e.height)}),t.bindRenderbuffer(36161,null)}}},yt=[];yt[6408]=4,yt[6407]=3;var xt=[];xt[5121]=1,xt[5126]=4,xt[36193]=2;var bt=["x","y","z","w"],_t="blend.func blend.equation stencil.func stencil.opFront stencil.opBack sample.coverage viewport scissor.box polygonOffset.offset".split(" "),wt={0:0,1:1,zero:0,one:1,"src color":768,"one minus src color":769,"src alpha":770,"one minus src alpha":771,"dst color":774,"one minus dst color":775,"dst alpha":772,"one minus dst alpha":773,"constant color":32769,"one minus constant color":32770,"constant alpha":32771,"one minus constant alpha":32772,"src alpha saturate":776},kt={never:512,less:513,"<":513,equal:514,"=":514,"==":514,"===":514,lequal:515,"<=":515,greater:516,">":516,notequal:517,"!=":517,"!==":517,gequal:518,">=":518,always:519},At={0:0,zero:0,keep:7680,replace:7681,increment:7682,decrement:7683,"increment wrap":34055,"decrement wrap":34056,invert:5386},Mt={cw:2304,ccw:2305},Tt=new D(!1,!1,!1,function(){});return function(t){function e(){if(0===Z.length)w&&w.update(),Q=null;else{Q=q.next(e),h();for(var t=Z.length-1;0<=t;--t){var r=Z[t];r&&r(z,null,0)}v.flush(),w&&w.update()}}function r(){!Q&&0<Z.length&&(Q=q.next(e))}function n(){Q&&(q.cancel(e),Q=null)}function a(t){t.preventDefault(),n(),$.forEach(function(t){t()})}function o(t){v.getError(),y.restore(),P.restore(),I.restore(),R.restore(),F.restore(),V.restore(),w&&w.restore(),G.procs.refresh(),r(),J.forEach(function(t){t()})}function s(t){function e(t){var e={},r={};return Object.keys(t).forEach(function(n){var i=t[n];U.isDynamic(i)?r[n]=U.unbox(i,n):e[n]=i}),{dynamic:r,static:e}}var r=e(t.context||{}),n=e(t.uniforms||{}),i=e(t.attributes||{}),a=e(function(t){function e(t){if(t in r){var e=r[t];delete r[t],Object.keys(e).forEach(function(n){r[t+"."+n]=e[n]})}}var r=j({},t);return delete r.uniforms,delete r.attributes,delete r.context,"stencil"in r&&r.stencil.op&&(r.stencil.opBack=r.stencil.opFront=r.stencil.op,delete r.stencil.op),e("blend"),e("depth"),e("cull"),e("stencil"),e("polygonOffset"),e("scissor"),e("sample"),r}(t));t={gpuTime:0,cpuTime:0,count:0};var o=(r=G.compile(a,i,n,r,t)).draw,s=r.batch,l=r.scope,c=[];return j(function(t,e){var r;if("function"==typeof t)return l.call(this,null,t,0);if("function"==typeof e)if("number"==typeof t)for(r=0;r<t;++r)l.call(this,null,e,r);else{if(!Array.isArray(t))return l.call(this,t,e,0);for(r=0;r<t.length;++r)l.call(this,t[r],e,r)}else if("number"==typeof t){if(0<t)return s.call(this,function(t){for(;c.length<t;)c.push(null);return c}(0|t),0|t)}else{if(!Array.isArray(t))return o.call(this,t);if(t.length)return s.call(this,t,t.length)}},{stats:t})}function l(t,e){var r=0;G.procs.poll();var n=e.color;n&&(v.clearColor(+n[0]||0,+n[1]||0,+n[2]||0,+n[3]||0),r|=16384),"depth"in e&&(v.clearDepth(+e.depth),r|=256),"stencil"in e&&(v.clearStencil(0|e.stencil),r|=1024),v.clear(r)}function c(t){return Z.push(t),r(),{cancel:function(){var e=N(Z,t);Z[e]=function t(){var e=N(Z,t);Z[e]=Z[Z.length-1],--Z.length,0>=Z.length&&n()}}}}function u(){var t=W.viewport,e=W.scissor_box;t[0]=t[1]=e[0]=e[1]=0,z.viewportWidth=z.framebufferWidth=z.drawingBufferWidth=t[2]=e[2]=v.drawingBufferWidth,z.viewportHeight=z.framebufferHeight=z.drawingBufferHeight=t[3]=e[3]=v.drawingBufferHeight}function h(){z.tick+=1,z.time=g(),u(),G.procs.poll()}function f(){u(),G.procs.refresh(),w&&w.update()}function g(){return(H()-k)/1e3}if(!(t=i(t)))return null;var v=t.gl,m=v.getContextAttributes();v.isContextLost();var y=function(t,e){function r(e){var r;e=e.toLowerCase();try{r=n[e]=t.getExtension(e)}catch(t){}return!!r}for(var n={},i=0;i<e.extensions.length;++i){var a=e.extensions[i];if(!r(a))return e.onDestroy(),e.onDone('"'+a+'" extension is not supported by the current WebGL context, try upgrading your system or a different browser'),null}return e.optionalExtensions.forEach(r),{extensions:n,restore:function(){Object.keys(n).forEach(function(t){if(n[t]&&!r(t))throw Error("(regl): error restoring extension "+t)})}}}(v,t);if(!y)return null;var x=function(){var t={"":0},e=[""];return{id:function(r){var n=t[r];return n||(n=t[r]=e.length,e.push(r),n)},str:function(t){return e[t]}}}(),b={bufferCount:0,elementsCount:0,framebufferCount:0,shaderCount:0,textureCount:0,cubeCount:0,renderbufferCount:0,maxTextureUnits:0},_=y.extensions,w=function(t,e){function r(){this.endQueryIndex=this.startQueryIndex=-1,this.sum=0,this.stats=null}function n(t,e,n){var i=o.pop()||new r;i.startQueryIndex=t,i.endQueryIndex=e,i.sum=0,i.stats=n,s.push(i)}if(!e.ext_disjoint_timer_query)return null;var i=[],a=[],o=[],s=[],l=[],c=[];return{beginQuery:function(t){var r=i.pop()||e.ext_disjoint_timer_query.createQueryEXT();e.ext_disjoint_timer_query.beginQueryEXT(35007,r),a.push(r),n(a.length-1,a.length,t)},endQuery:function(){e.ext_disjoint_timer_query.endQueryEXT(35007)},pushScopeStats:n,update:function(){var t,r;if(0!==(t=a.length)){c.length=Math.max(c.length,t+1),l.length=Math.max(l.length,t+1),l[0]=0;var n=c[0]=0;for(r=t=0;r<a.length;++r){var u=a[r];e.ext_disjoint_timer_query.getQueryObjectEXT(u,34919)?(n+=e.ext_disjoint_timer_query.getQueryObjectEXT(u,34918),i.push(u)):a[t++]=u,l[r+1]=n,c[r+1]=t}for(a.length=t,r=t=0;r<s.length;++r){var h=(n=s[r]).startQueryIndex;u=n.endQueryIndex,n.sum+=l[u]-l[h],h=c[h],(u=c[u])===h?(n.stats.gpuTime+=n.sum/1e6,o.push(n)):(n.startQueryIndex=h,n.endQueryIndex=u,s[t++]=n)}s.length=t}},getNumPendingQueries:function(){return a.length},clear:function(){i.push.apply(i,a);for(var t=0;t<i.length;t++)e.ext_disjoint_timer_query.deleteQueryEXT(i[t]);a.length=0,i.length=0},restore:function(){a.length=0,i.length=0}}}(0,_),k=H(),C=v.drawingBufferWidth,L=v.drawingBufferHeight,z={tick:0,time:0,viewportWidth:C,viewportHeight:L,framebufferWidth:C,framebufferHeight:L,drawingBufferWidth:C,drawingBufferHeight:L,pixelRatio:t.pixelRatio},O=Y(v,_),I=(C=function(t,e,r,n){for(t=r.maxAttributes,e=Array(t),r=0;r<t;++r)e[r]=new T;return{Record:T,scope:{},state:e}}(v,_,O),p(v,b,t,C)),D=d(v,_,I,b),P=S(v,x,b,t),R=A(v,_,O,function(){G.procs.poll()},z,b,t),F=mt(v,_,0,b,t),V=M(v,_,O,R,F,b),G=B(v,x,_,O,I,D,0,V,{},C,P,{elements:null,primitive:4,count:-1,offset:0,instances:-1},z,w,t),W=(x=E(v,V,G.procs.poll,z),G.next),X=v.canvas,Z=[],$=[],J=[],K=[t.onDestroy],Q=null;X&&(X.addEventListener("webglcontextlost",a,!1),X.addEventListener("webglcontextrestored",o,!1));var tt=V.setFBO=s({framebuffer:U.define.call(null,1,"framebuffer")});return f(),m=j(s,{clear:function(t){if("framebuffer"in t)if(t.framebuffer&&"framebufferCube"===t.framebuffer_reglType)for(var e=0;6>e;++e)tt(j({framebuffer:t.framebuffer.faces[e]},t),l);else tt(t,l);else l(0,t)},prop:U.define.bind(null,1),context:U.define.bind(null,2),this:U.define.bind(null,3),draw:s({}),buffer:function(t){return I.create(t,34962,!1,!1)},elements:function(t){return D.create(t,!1)},texture:R.create2D,cube:R.createCube,renderbuffer:F.create,framebuffer:V.create,framebufferCube:V.createCube,attributes:m,frame:c,on:function(t,e){var r;switch(t){case"frame":return c(e);case"lost":r=$;break;case"restore":r=J;break;case"destroy":r=K}return r.push(e),{cancel:function(){for(var t=0;t<r.length;++t)if(r[t]===e){r[t]=r[r.length-1],r.pop();break}}}},limits:O,hasExtension:function(t){return 0<=O.extensions.indexOf(t.toLowerCase())},read:x,destroy:function(){Z.length=0,n(),X&&(X.removeEventListener("webglcontextlost",a),X.removeEventListener("webglcontextrestored",o)),P.clear(),V.clear(),F.clear(),R.clear(),D.clear(),I.clear(),w&&w.clear(),K.forEach(function(t){t()})},_gl:v,_refresh:f,poll:function(){h(),w&&w.update()},now:g,stats:b}),t.onDone(null,m),m}},"object"==typeof r&&"undefined"!=typeof e?e.exports=i():n.createREGL=i()},{}],484:[function(t,e,r){"use strict";var n,i="";e.exports=function(t,e){if("string"!=typeof t)throw new TypeError("expected a string");if(1===e)return t;if(2===e)return t+t;var r=t.length*e;if(n!==t||"undefined"==typeof n)n=t,i="";else if(i.length>=r)return i.substr(0,r);for(;r>i.length&&e>1;)1&e&&(i+=t),e>>=1,t+=t;return i=(i+=t).substr(0,r)}},{}],485:[function(t,e,r){(function(t){e.exports=t.performance&&t.performance.now?function(){return performance.now()}:Date.now||function(){return+new Date}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],486:[function(t,e,r){"use strict";e.exports=function(t){for(var e=t.length,r=t[t.length-1],n=e,i=e-2;i>=0;--i){var a=r,o=t[i],s=(r=a+o)-a,l=o-s;l&&(t[--n]=r,r=l)}for(var c=0,i=n;i<e;++i){var a=t[i],o=r,s=(r=a+o)-a,l=o-s;l&&(t[c++]=l)}return t[c++]=r,t.length=c,t}},{}],487:[function(t,e,r){"use strict";var n=t("two-product"),i=t("robust-sum"),a=t("robust-scale"),o=t("robust-compress"),s=6;function l(t,e){for(var r=new Array(t.length-1),n=1;n<t.length;++n)for(var i=r[n-1]=new Array(t.length-1),a=0,o=0;a<t.length;++a)a!==e&&(i[o++]=t[n][a]);return r}function c(t){if(2===t.length)return["sum(prod(",t[0][0],",",t[1][1],"),prod(-",t[0][1],",",t[1][0],"))"].join("");for(var e=[],r=0;r<t.length;++r)e.push(["scale(",c(l(t,r)),",",(n=r,1&n?"-":""),t[0][r],")"].join(""));return function t(e){if(1===e.length)return e[0];if(2===e.length)return["sum(",e[0],",",e[1],")"].join("");var r=e.length>>1;return["sum(",t(e.slice(0,r)),",",t(e.slice(r)),")"].join("")}(e);var n}function u(t){return new Function("sum","scale","prod","compress",["function robustDeterminant",t,"(m){return compress(",c(function(t){for(var e=new Array(t),r=0;r<t;++r){e[r]=new Array(t);for(var n=0;n<t;++n)e[r][n]=["m[",r,"][",n,"]"].join("")}return e}(t)),")};return robustDeterminant",t].join(""))(i,a,n,o)}var h=[function(){return[0]},function(t){return[t[0][0]]}];!function(){for(;h.length<s;)h.push(u(h.length));for(var t=[],r=["function robustDeterminant(m){switch(m.length){"],n=0;n<s;++n)t.push("det"+n),r.push("case ",n,":return det",n,"(m);");r.push("}var det=CACHE[m.length];if(!det)det=CACHE[m.length]=gen(m.length);return det(m);}return robustDeterminant"),t.push("CACHE","gen",r.join(""));var i=Function.apply(void 0,t);for(e.exports=i.apply(void 0,h.concat([h,u])),n=0;n<h.length;++n)e.exports[n]=h[n]}()},{"robust-compress":486,"robust-scale":493,"robust-sum":496,"two-product":524}],488:[function(t,e,r){"use strict";var n=t("two-product"),i=t("robust-sum");e.exports=function(t,e){for(var r=n(t[0],e[0]),a=1;a<t.length;++a)r=i(r,n(t[a],e[a]));return r}},{"robust-sum":496,"two-product":524}],489:[function(t,e,r){"use strict";var n=t("two-product"),i=t("robust-sum"),a=t("robust-subtract"),o=t("robust-scale"),s=6;function l(t,e){for(var r=new Array(t.length-1),n=1;n<t.length;++n)for(var i=r[n-1]=new Array(t.length-1),a=0,o=0;a<t.length;++a)a!==e&&(i[o++]=t[n][a]);return r}function c(t){if(1===t.length)return t[0];if(2===t.length)return["sum(",t[0],",",t[1],")"].join("");var e=t.length>>1;return["sum(",c(t.slice(0,e)),",",c(t.slice(e)),")"].join("")}function u(t,e){if("m"===t.charAt(0)){if("w"===e.charAt(0)){var r=t.split("[");return["w",e.substr(1),"m",r[0].substr(1)].join("")}return["prod(",t,",",e,")"].join("")}return u(e,t)}function h(t){if(2===t.length)return[["diff(",u(t[0][0],t[1][1]),",",u(t[1][0],t[0][1]),")"].join("")];for(var e=[],r=0;r<t.length;++r)e.push(["scale(",c(h(l(t,r))),",",(n=r,!0&n?"-":""),t[0][r],")"].join(""));return e;var n}function f(t,e){for(var r=[],n=0;n<e-2;++n)r.push(["prod(m",t,"[",n,"],m",t,"[",n,"])"].join(""));return c(r)}function p(t){for(var e=[],r=[],s=function(t){for(var e=new Array(t),r=0;r<t;++r){e[r]=new Array(t);for(var n=0;n<t;++n)e[r][n]=["m",n,"[",t-r-2,"]"].join("")}return e}(t),u=0;u<t;++u)s[0][u]="1",s[t-1][u]="w"+u;for(u=0;u<t;++u)0==(1&u)?e.push.apply(e,h(l(s,u))):r.push.apply(r,h(l(s,u)));var p=c(e),d=c(r),g="exactInSphere"+t,v=[];for(u=0;u<t;++u)v.push("m"+u);var m=["function ",g,"(",v.join(),"){"];for(u=0;u<t;++u){m.push("var w",u,"=",f(u,t),";");for(var y=0;y<t;++y)y!==u&&m.push("var w",u,"m",y,"=scale(w",u,",m",y,"[0]);")}return m.push("var p=",p,",n=",d,",d=diff(p,n);return d[d.length-1];}return ",g),new Function("sum","diff","prod","scale",m.join(""))(i,a,n,o)}var d=[function(){return 0},function(){return 0},function(){return 0}];!function(){for(;d.length<=s;)d.push(p(d.length));for(var t=[],r=["slow"],n=0;n<=s;++n)t.push("a"+n),r.push("o"+n);var i=["function testInSphere(",t.join(),"){switch(arguments.length){case 0:case 1:return 0;"];for(n=2;n<=s;++n)i.push("case ",n,":return o",n,"(",t.slice(0,n).join(),");");i.push("}var s=new Array(arguments.length);for(var i=0;i<arguments.length;++i){s[i]=arguments[i]};return slow(s);}return testInSphere"),r.push(i.join(""));var a=Function.apply(void 0,r);for(e.exports=a.apply(void 0,[function(t){var e=d[t.length];return e||(e=d[t.length]=p(t.length)),e.apply(void 0,t)}].concat(d)),n=0;n<=s;++n)e.exports[n]=d[n]}()},{"robust-scale":493,"robust-subtract":495,"robust-sum":496,"two-product":524}],490:[function(t,e,r){"use strict";var n=t("robust-determinant"),i=6;function a(t){for(var e="robustLinearSolve"+t+"d",r=["function ",e,"(A,b){return ["],i=0;i<t;++i){r.push("det([");for(var a=0;a<t;++a){a>0&&r.push(","),r.push("[");for(var o=0;o<t;++o)o>0&&r.push(","),o===i?r.push("+b[",a,"]"):r.push("+A[",a,"][",o,"]");r.push("]")}r.push("]),")}r.push("det(A)]}return ",e);var s=new Function("det",r.join(""));return s(t<6?n[t]:n)}var o=[function(){return[0]},function(t,e){return[[e[0]],[t[0][0]]]}];!function(){for(;o.length<i;)o.push(a(o.length));for(var t=[],r=["function dispatchLinearSolve(A,b){switch(A.length){"],n=0;n<i;++n)t.push("s"+n),r.push("case ",n,":return s",n,"(A,b);");r.push("}var s=CACHE[A.length];if(!s)s=CACHE[A.length]=g(A.length);return s(A,b)}return dispatchLinearSolve"),t.push("CACHE","g",r.join(""));var s=Function.apply(void 0,t);for(e.exports=s.apply(void 0,o.concat([o,a])),n=0;n<i;++n)e.exports[n]=o[n]}()},{"robust-determinant":487}],491:[function(t,e,r){"use strict";var n=t("two-product"),i=t("robust-sum"),a=t("robust-scale"),o=t("robust-subtract"),s=5;function l(t,e){for(var r=new Array(t.length-1),n=1;n<t.length;++n)for(var i=r[n-1]=new Array(t.length-1),a=0,o=0;a<t.length;++a)a!==e&&(i[o++]=t[n][a]);return r}function c(t){if(1===t.length)return t[0];if(2===t.length)return["sum(",t[0],",",t[1],")"].join("");var e=t.length>>1;return["sum(",c(t.slice(0,e)),",",c(t.slice(e)),")"].join("")}function u(t){if(2===t.length)return[["sum(prod(",t[0][0],",",t[1][1],"),prod(-",t[0][1],",",t[1][0],"))"].join("")];for(var e=[],r=0;r<t.length;++r)e.push(["scale(",c(u(l(t,r))),",",(n=r,1&n?"-":""),t[0][r],")"].join(""));return e;var n}function h(t){for(var e=[],r=[],s=function(t){for(var e=new Array(t),r=0;r<t;++r){e[r]=new Array(t);for(var n=0;n<t;++n)e[r][n]=["m",n,"[",t-r-1,"]"].join("")}return e}(t),h=[],f=0;f<t;++f)0==(1&f)?e.push.apply(e,u(l(s,f))):r.push.apply(r,u(l(s,f))),h.push("m"+f);var p=c(e),d=c(r),g="orientation"+t+"Exact",v=["function ",g,"(",h.join(),"){var p=",p,",n=",d,",d=sub(p,n);return d[d.length-1];};return ",g].join("");return new Function("sum","prod","scale","sub",v)(i,n,a,o)}var f=h(3),p=h(4),d=[function(){return 0},function(){return 0},function(t,e){return e[0]-t[0]},function(t,e,r){var n,i=(t[1]-r[1])*(e[0]-r[0]),a=(t[0]-r[0])*(e[1]-r[1]),o=i-a;if(i>0){if(a<=0)return o;n=i+a}else{if(!(i<0))return o;if(a>=0)return o;n=-(i+a)}var s=3.3306690738754716e-16*n;return o>=s||o<=-s?o:f(t,e,r)},function(t,e,r,n){var i=t[0]-n[0],a=e[0]-n[0],o=r[0]-n[0],s=t[1]-n[1],l=e[1]-n[1],c=r[1]-n[1],u=t[2]-n[2],h=e[2]-n[2],f=r[2]-n[2],d=a*c,g=o*l,v=o*s,m=i*c,y=i*l,x=a*s,b=u*(d-g)+h*(v-m)+f*(y-x),_=7.771561172376103e-16*((Math.abs(d)+Math.abs(g))*Math.abs(u)+(Math.abs(v)+Math.abs(m))*Math.abs(h)+(Math.abs(y)+Math.abs(x))*Math.abs(f));return b>_||-b>_?b:p(t,e,r,n)}];!function(){for(;d.length<=s;)d.push(h(d.length));for(var t=[],r=["slow"],n=0;n<=s;++n)t.push("a"+n),r.push("o"+n);var i=["function getOrientation(",t.join(),"){switch(arguments.length){case 0:case 1:return 0;"];for(n=2;n<=s;++n)i.push("case ",n,":return o",n,"(",t.slice(0,n).join(),");");i.push("}var s=new Array(arguments.length);for(var i=0;i<arguments.length;++i){s[i]=arguments[i]};return slow(s);}return getOrientation"),r.push(i.join(""));var a=Function.apply(void 0,r);for(e.exports=a.apply(void 0,[function(t){var e=d[t.length];return e||(e=d[t.length]=h(t.length)),e.apply(void 0,t)}].concat(d)),n=0;n<=s;++n)e.exports[n]=d[n]}()},{"robust-scale":493,"robust-subtract":495,"robust-sum":496,"two-product":524}],492:[function(t,e,r){"use strict";var n=t("robust-sum"),i=t("robust-scale");e.exports=function(t,e){if(1===t.length)return i(e,t[0]);if(1===e.length)return i(t,e[0]);if(0===t.length||0===e.length)return[0];var r=[0];if(t.length<e.length)for(var a=0;a<t.length;++a)r=n(r,i(e,t[a]));else for(var a=0;a<e.length;++a)r=n(r,i(t,e[a]));return r}},{"robust-scale":493,"robust-sum":496}],493:[function(t,e,r){"use strict";var n=t("two-product"),i=t("two-sum");e.exports=function(t,e){var r=t.length;if(1===r){var a=n(t[0],e);return a[0]?a:[a[1]]}var o=new Array(2*r),s=[.1,.1],l=[.1,.1],c=0;n(t[0],e,s),s[0]&&(o[c++]=s[0]);for(var u=1;u<r;++u){n(t[u],e,l);var h=s[1];i(h,l[0],s),s[0]&&(o[c++]=s[0]);var f=l[1],p=s[1],d=f+p,g=d-f,v=p-g;s[1]=d,v&&(o[c++]=v)}s[1]&&(o[c++]=s[1]);0===c&&(o[c++]=0);return o.length=c,o}},{"two-product":524,"two-sum":525}],494:[function(t,e,r){"use strict";e.exports=function(t,e,r,i){var a=n(t,r,i),o=n(e,r,i);if(a>0&&o>0||a<0&&o<0)return!1;var s=n(r,t,e),l=n(i,t,e);if(s>0&&l>0||s<0&&l<0)return!1;if(0===a&&0===o&&0===s&&0===l)return function(t,e,r,n){for(var i=0;i<2;++i){var a=t[i],o=e[i],s=Math.min(a,o),l=Math.max(a,o),c=r[i],u=n[i],h=Math.min(c,u),f=Math.max(c,u);if(f<s||l<h)return!1}return!0}(t,e,r,i);return!0};var n=t("robust-orientation")[3]},{"robust-orientation":491}],495:[function(t,e,r){"use strict";e.exports=function(t,e){var r=0|t.length,n=0|e.length;if(1===r&&1===n)return function(t,e){var r=t+e,n=r-t,i=t-(r-n)+(e-n);if(i)return[i,r];return[r]}(t[0],-e[0]);var i,a,o=new Array(r+n),s=0,l=0,c=0,u=Math.abs,h=t[l],f=u(h),p=-e[c],d=u(p);f<d?(a=h,(l+=1)<r&&(h=t[l],f=u(h))):(a=p,(c+=1)<n&&(p=-e[c],d=u(p)));l<r&&f<d||c>=n?(i=h,(l+=1)<r&&(h=t[l],f=u(h))):(i=p,(c+=1)<n&&(p=-e[c],d=u(p)));var g,v,m=i+a,y=m-i,x=a-y,b=x,_=m;for(;l<r&&c<n;)f<d?(i=h,(l+=1)<r&&(h=t[l],f=u(h))):(i=p,(c+=1)<n&&(p=-e[c],d=u(p))),(x=(a=b)-(y=(m=i+a)-i))&&(o[s++]=x),b=_-((g=_+m)-(v=g-_))+(m-v),_=g;for(;l<r;)(x=(a=b)-(y=(m=(i=h)+a)-i))&&(o[s++]=x),b=_-((g=_+m)-(v=g-_))+(m-v),_=g,(l+=1)<r&&(h=t[l]);for(;c<n;)(x=(a=b)-(y=(m=(i=p)+a)-i))&&(o[s++]=x),b=_-((g=_+m)-(v=g-_))+(m-v),_=g,(c+=1)<n&&(p=-e[c]);b&&(o[s++]=b);_&&(o[s++]=_);s||(o[s++]=0);return o.length=s,o}},{}],496:[function(t,e,r){"use strict";e.exports=function(t,e){var r=0|t.length,n=0|e.length;if(1===r&&1===n)return function(t,e){var r=t+e,n=r-t,i=t-(r-n)+(e-n);if(i)return[i,r];return[r]}(t[0],e[0]);var i,a,o=new Array(r+n),s=0,l=0,c=0,u=Math.abs,h=t[l],f=u(h),p=e[c],d=u(p);f<d?(a=h,(l+=1)<r&&(h=t[l],f=u(h))):(a=p,(c+=1)<n&&(p=e[c],d=u(p)));l<r&&f<d||c>=n?(i=h,(l+=1)<r&&(h=t[l],f=u(h))):(i=p,(c+=1)<n&&(p=e[c],d=u(p)));var g,v,m=i+a,y=m-i,x=a-y,b=x,_=m;for(;l<r&&c<n;)f<d?(i=h,(l+=1)<r&&(h=t[l],f=u(h))):(i=p,(c+=1)<n&&(p=e[c],d=u(p))),(x=(a=b)-(y=(m=i+a)-i))&&(o[s++]=x),b=_-((g=_+m)-(v=g-_))+(m-v),_=g;for(;l<r;)(x=(a=b)-(y=(m=(i=h)+a)-i))&&(o[s++]=x),b=_-((g=_+m)-(v=g-_))+(m-v),_=g,(l+=1)<r&&(h=t[l]);for(;c<n;)(x=(a=b)-(y=(m=(i=p)+a)-i))&&(o[s++]=x),b=_-((g=_+m)-(v=g-_))+(m-v),_=g,(c+=1)<n&&(p=e[c]);b&&(o[s++]=b);_&&(o[s++]=_);s||(o[s++]=0);return o.length=s,o}},{}],497:[function(t,e,r){"use strict";e.exports=function(t){return t<0?-1:t>0?1:0}},{}],498:[function(t,e,r){"use strict";e.exports=function(t){return i(n(t))};var n=t("boundary-cells"),i=t("reduce-simplicial-complex")},{"boundary-cells":83,"reduce-simplicial-complex":478}],499:[function(t,e,r){"use strict";e.exports=function(t,e,r,s){r=r||0,"undefined"==typeof s&&(s=function(t){for(var e=t.length,r=0,n=0;n<e;++n)r=0|Math.max(r,t[n].length);return r-1}(t));if(0===t.length||s<1)return{cells:[],vertexIds:[],vertexWeights:[]};var l=function(t,e){for(var r=t.length,n=i.mallocUint8(r),a=0;a<r;++a)n[a]=t[a]<e|0;return n}(e,+r),c=function(t,e){for(var r=t.length,o=e*(e+1)/2*r|0,s=i.mallocUint32(2*o),l=0,c=0;c<r;++c)for(var u=t[c],e=u.length,h=0;h<e;++h)for(var f=0;f<h;++f){var p=u[f],d=u[h];s[l++]=0|Math.min(p,d),s[l++]=0|Math.max(p,d)}a(n(s,[l/2|0,2]));for(var g=2,c=2;c<l;c+=2)s[c-2]===s[c]&&s[c-1]===s[c+1]||(s[g++]=s[c],s[g++]=s[c+1]);return n(s,[g/2|0,2])}(t,s),u=function(t,e,r,a){for(var o=t.data,s=t.shape[0],l=i.mallocDouble(s),c=0,u=0;u<s;++u){var h=o[2*u],f=o[2*u+1];if(r[h]!==r[f]){var p=e[h],d=e[f];o[2*c]=h,o[2*c+1]=f,l[c++]=(d-a)/(d-p)}}return t.shape[0]=c,n(l,[c])}(c,e,l,+r),h=function(t,e){var r=i.mallocInt32(2*e),n=t.shape[0],a=t.data;r[0]=0;for(var o=0,s=0;s<n;++s){var l=a[2*s];if(l!==o){for(r[2*o+1]=s;++o<l;)r[2*o]=s,r[2*o+1]=s;r[2*o]=s}}r[2*o+1]=n;for(;++o<e;)r[2*o]=r[2*o+1]=n;return r}(c,0|e.length),f=o(s)(t,c.data,h,l),p=function(t){for(var e=0|t.shape[0],r=t.data,n=new Array(e),i=0;i<e;++i)n[i]=[r[2*i],r[2*i+1]];return n}(c),d=[].slice.call(u.data,0,u.shape[0]);return i.free(l),i.free(c.data),i.free(u.data),i.free(h),{cells:f,vertexIds:p,vertexWeights:d}};var n=t("ndarray"),i=t("typedarray-pool"),a=t("ndarray-sort"),o=t("./lib/codegen")},{"./lib/codegen":500,ndarray:439,"ndarray-sort":437,"typedarray-pool":526}],500:[function(t,e,r){"use strict";e.exports=function(t){var e=a[t];e||(e=a[t]=function(t){var e=0,r=new Array(t+1);r[0]=[[]];for(var a=1;a<=t;++a)for(var o=r[a]=i(a),s=0;s<o.length;++s)e=Math.max(e,o[a].length);var l=["function B(C,E,i,j){","var a=Math.min(i,j)|0,b=Math.max(i,j)|0,l=C[2*a],h=C[2*a+1];","while(l<h){","var m=(l+h)>>1,v=E[2*m+1];","if(v===b){return m}","if(b<v){h=m}else{l=m+1}","}","return l;","};","function getContour",t,"d(F,E,C,S){","var n=F.length,R=[];","for(var i=0;i<n;++i){var c=F[i],l=c.length;"];function c(t){if(!(t.length<=0)){l.push("R.push(");for(var e=0;e<t.length;++e){var r=t[e];e>0&&l.push(","),l.push("[");for(var n=0;n<r.length;++n){var i=r[n];n>0&&l.push(","),l.push("B(C,E,c[",i[0],"],c[",i[1],"])")}l.push("]")}l.push(");")}}for(var a=t+1;a>1;--a){a<t+1&&l.push("else "),l.push("if(l===",a,"){");for(var u=[],s=0;s<a;++s)u.push("(S[c["+s+"]]<<"+s+")");l.push("var M=",u.join("+"),";if(M===0||M===",(1<<a)-1,"){continue}switch(M){");for(var o=r[a-1],s=0;s<o.length;++s)l.push("case ",s,":"),c(o[s]),l.push("break;");l.push("}}")}return l.push("}return R;};return getContour",t,"d"),new Function("pool",l.join(""))(n)}(t));return e};var n=t("typedarray-pool"),i=t("marching-simplex-table"),a={}},{"marching-simplex-table":416,"typedarray-pool":526}],501:[function(t,e,r){"use strict";var n=t("bit-twiddle"),i=t("union-find");function a(t,e){var r=t.length,n=t.length-e.length,i=Math.min;if(n)return n;switch(r){case 0:return 0;case 1:return t[0]-e[0];case 2:return(s=t[0]+t[1]-e[0]-e[1])||i(t[0],t[1])-i(e[0],e[1]);case 3:var a=t[0]+t[1],o=e[0]+e[1];if(s=a+t[2]-(o+e[2]))return s;var s,l=i(t[0],t[1]),c=i(e[0],e[1]);return(s=i(l,t[2])-i(c,e[2]))||i(l+t[2],a)-i(c+e[2],o);default:var u=t.slice(0);u.sort();var h=e.slice(0);h.sort();for(var f=0;f<r;++f)if(n=u[f]-h[f])return n;return 0}}function o(t,e){return a(t[0],e[0])}function s(t,e){if(e){for(var r=t.length,n=new Array(r),i=0;i<r;++i)n[i]=[t[i],e[i]];n.sort(o);for(i=0;i<r;++i)t[i]=n[i][0],e[i]=n[i][1];return t}return t.sort(a),t}function l(t){if(0===t.length)return[];for(var e=1,r=t.length,n=1;n<r;++n){var i=t[n];if(a(i,t[n-1])){if(n===e){e++;continue}t[e++]=i}}return t.length=e,t}function c(t,e){for(var r=0,n=t.length-1,i=-1;r<=n;){var o=r+n>>1,s=a(t[o],e);s<=0?(0===s&&(i=o),r=o+1):s>0&&(n=o-1)}return i}function u(t,e){for(var r=new Array(t.length),i=0,o=r.length;i<o;++i)r[i]=[];for(var s=[],l=(i=0,e.length);i<l;++i)for(var u=e[i],h=u.length,f=1,p=1<<h;f<p;++f){s.length=n.popCount(f);for(var d=0,g=0;g<h;++g)f&1<<g&&(s[d++]=u[g]);var v=c(t,s);if(!(v<0))for(;r[v++].push(i),!(v>=t.length||0!==a(t[v],s)););}return r}function h(t,e){if(e<0)return[];for(var r=[],i=(1<<e+1)-1,a=0;a<t.length;++a)for(var o=t[a],l=i;l<1<<o.length;l=n.nextCombination(l)){for(var c=new Array(e+1),u=0,h=0;h<o.length;++h)l&1<<h&&(c[u++]=o[h]);r.push(c)}return s(r)}r.dimension=function(t){for(var e=0,r=Math.max,n=0,i=t.length;n<i;++n)e=r(e,t[n].length);return e-1},r.countVertices=function(t){for(var e=-1,r=Math.max,n=0,i=t.length;n<i;++n)for(var a=t[n],o=0,s=a.length;o<s;++o)e=r(e,a[o]);return e+1},r.cloneCells=function(t){for(var e=new Array(t.length),r=0,n=t.length;r<n;++r)e[r]=t[r].slice(0);return e},r.compareCells=a,r.normalize=s,r.unique=l,r.findCell=c,r.incidence=u,r.dual=function(t,e){if(!e)return u(l(h(t,0)),t);for(var r=new Array(e),n=0;n<e;++n)r[n]=[];n=0;for(var i=t.length;n<i;++n)for(var a=t[n],o=0,s=a.length;o<s;++o)r[a[o]].push(n);return r},r.explode=function(t){for(var e=[],r=0,n=t.length;r<n;++r)for(var i=t[r],a=0|i.length,o=1,l=1<<a;o<l;++o){for(var c=[],u=0;u<a;++u)o>>>u&1&&c.push(i[u]);e.push(c)}return s(e)},r.skeleton=h,r.boundary=function(t){for(var e=[],r=0,n=t.length;r<n;++r)for(var i=t[r],a=0,o=i.length;a<o;++a){for(var l=new Array(i.length-1),c=0,u=0;c<o;++c)c!==a&&(l[u++]=i[c]);e.push(l)}return s(e)},r.connectedComponents=function(t,e){return e?function(t,e){for(var r=new i(e),n=0;n<t.length;++n)for(var a=t[n],o=0;o<a.length;++o)for(var s=o+1;s<a.length;++s)r.link(a[o],a[s]);var l=[],c=r.ranks;for(n=0;n<c.length;++n)c[n]=-1;for(n=0;n<t.length;++n){var u=r.find(t[n][0]);c[u]<0?(c[u]=l.length,l.push([t[n].slice(0)])):l[c[u]].push(t[n].slice(0))}return l}(t,e):function(t){for(var e=l(s(h(t,0))),r=new i(e.length),n=0;n<t.length;++n)for(var a=t[n],o=0;o<a.length;++o)for(var u=c(e,[a[o]]),f=o+1;f<a.length;++f)r.link(u,c(e,[a[f]]));var p=[],d=r.ranks;for(n=0;n<d.length;++n)d[n]=-1;for(n=0;n<t.length;++n){var g=r.find(c(e,[t[n][0]]));d[g]<0?(d[g]=p.length,p.push([t[n].slice(0)])):p[d[g]].push(t[n].slice(0))}return p}(t)}},{"bit-twiddle":80,"union-find":527}],502:[function(t,e,r){arguments[4][80][0].apply(r,arguments)},{dup:80}],503:[function(t,e,r){arguments[4][501][0].apply(r,arguments)},{"bit-twiddle":502,dup:501,"union-find":504}],504:[function(t,e,r){"use strict";function n(t){this.roots=new Array(t),this.ranks=new Array(t);for(var e=0;e<t;++e)this.roots[e]=e,this.ranks[e]=0}e.exports=n,n.prototype.length=function(){return this.roots.length},n.prototype.makeSet=function(){var t=this.roots.length;return this.roots.push(t),this.ranks.push(0),t},n.prototype.find=function(t){for(var e=this.roots;e[t]!==t;){var r=e[t];e[t]=e[r],t=r}return t},n.prototype.link=function(t,e){var r=this.find(t),n=this.find(e);if(r!==n){var i=this.ranks,a=this.roots,o=i[r],s=i[n];o<s?a[r]=n:s<o?a[n]=r:(a[n]=r,++i[r])}}},{}],505:[function(t,e,r){"use strict";e.exports=function(t,e,r){for(var a=e.length,o=t.length,s=new Array(a),l=new Array(a),c=new Array(a),u=new Array(a),h=0;h<a;++h)s[h]=l[h]=-1,c[h]=1/0,u[h]=!1;for(var h=0;h<o;++h){var f=t[h];if(2!==f.length)throw new Error("Input must be a graph");var p=f[1],d=f[0];-1!==l[d]?l[d]=-2:l[d]=p,-1!==s[p]?s[p]=-2:s[p]=d}function g(t){if(u[t])return 1/0;var r,i,a,o,c,h=s[t],f=l[t];return h<0||f<0?1/0:(r=e[t],i=e[h],a=e[f],o=Math.abs(n(r,i,a)),c=Math.sqrt(Math.pow(i[0]-a[0],2)+Math.pow(i[1]-a[1],2)),o/c)}function v(t,e){var r=A[t],n=A[e];A[t]=n,A[e]=r,M[r]=e,M[n]=t}function m(t){return c[A[t]]}function y(t){return 1&t?t-1>>1:(t>>1)-1}function x(t){for(var e=m(t);;){var r=e,n=2*t+1,i=2*(t+1),a=t;if(n<S){var o=m(n);o<r&&(a=n,r=o)}if(i<S){var s=m(i);s<r&&(a=i)}if(a===t)return t;v(t,a),t=a}}function b(t){for(var e=m(t);t>0;){var r=y(t);if(r>=0){var n=m(r);if(e<n){v(t,r),t=r;continue}}return t}}function _(){if(S>0){var t=A[0];return v(0,S-1),S-=1,x(0),t}return-1}function w(t,e){var r=A[t];return c[r]===e?t:(c[r]=-1/0,b(t),_(),c[r]=e,b((S+=1)-1))}function k(t){if(!u[t]){u[t]=!0;var e=s[t],r=l[t];s[r]>=0&&(s[r]=e),l[e]>=0&&(l[e]=r),M[e]>=0&&w(M[e],g(e)),M[r]>=0&&w(M[r],g(r))}}for(var A=[],M=new Array(a),h=0;h<a;++h){var T=c[h]=g(h);T<1/0?(M[h]=A.length,A.push(h)):M[h]=-1}for(var S=A.length,h=S>>1;h>=0;--h)x(h);for(;;){var E=_();if(E<0||c[E]>r)break;k(E)}for(var C=[],h=0;h<a;++h)u[h]||(M[h]=C.length,C.push(e[h].slice()));C.length;function L(t,e){if(t[e]<0)return e;var r=e,n=e;do{var i=t[n];if(!u[n]||i<0||i===n)break;if(i=t[n=i],!u[n]||i<0||i===n)break;n=i,r=t[r]}while(r!==n);for(var a=e;a!==n;a=t[a])t[a]=n;return n}var z=[];return t.forEach(function(t){var e=L(s,t[0]),r=L(l,t[1]);if(e>=0&&r>=0&&e!==r){var n=M[e],i=M[r];n!==i&&z.push([n,i])}}),i.unique(i.normalize(z)),{positions:C,edges:z}};var n=t("robust-orientation"),i=t("simplicial-complex")},{"robust-orientation":491,"simplicial-complex":503}],506:[function(t,e,r){"use strict";e.exports=function(t,e){var r,a,o,s;if(e[0][0]<e[1][0])r=e[0],a=e[1];else{if(!(e[0][0]>e[1][0]))return i(e,t);r=e[1],a=e[0]}if(t[0][0]<t[1][0])o=t[0],s=t[1];else{if(!(t[0][0]>t[1][0]))return-i(t,e);o=t[1],s=t[0]}var l=n(r,a,s),c=n(r,a,o);if(l<0){if(c<=0)return l}else if(l>0){if(c>=0)return l}else if(c)return c;if(l=n(s,o,a),c=n(s,o,r),l<0){if(c<=0)return l}else if(l>0){if(c>=0)return l}else if(c)return c;return a[0]-s[0]};var n=t("robust-orientation");function i(t,e){var r,i,a,o;if(e[0][0]<e[1][0])r=e[0],i=e[1];else{if(!(e[0][0]>e[1][0])){var s=Math.min(t[0][1],t[1][1]),l=Math.max(t[0][1],t[1][1]),c=Math.min(e[0][1],e[1][1]),u=Math.max(e[0][1],e[1][1]);return l<c?l-c:s>u?s-u:l-u}r=e[1],i=e[0]}t[0][1]<t[1][1]?(a=t[0],o=t[1]):(a=t[1],o=t[0]);var h=n(i,r,a);return h||((h=n(i,r,o))||o-i)}},{"robust-orientation":491}],507:[function(t,e,r){"use strict";e.exports=function(t){for(var e=t.length,r=2*e,n=new Array(r),a=0;a<e;++a){var l=t[a],c=l[0][0]<l[1][0];n[2*a]=new h(l[0][0],l,c,a),n[2*a+1]=new h(l[1][0],l,!c,a)}n.sort(function(t,e){var r=t.x-e.x;return r||((r=t.create-e.create)||Math.min(t.segment[0][1],t.segment[1][1])-Math.min(e.segment[0][1],e.segment[1][1]))});for(var f=i(o),p=[],d=[],g=[],a=0;a<r;){for(var v=n[a].x,m=[];a<r;){var y=n[a];if(y.x!==v)break;a+=1,y.segment[0][0]===y.x&&y.segment[1][0]===y.x?y.create&&(y.segment[0][1]<y.segment[1][1]?(m.push(new u(y.segment[0][1],y.index,!0,!0)),m.push(new u(y.segment[1][1],y.index,!1,!1))):(m.push(new u(y.segment[1][1],y.index,!0,!1)),m.push(new u(y.segment[0][1],y.index,!1,!0)))):f=y.create?f.insert(y.segment,y.index):f.remove(y.segment)}p.push(f.root),d.push(v),g.push(m)}return new s(p,d,g)};var n=t("binary-search-bounds"),i=t("functional-red-black-tree"),a=t("robust-orientation"),o=t("./lib/order-segments");function s(t,e,r){this.slabs=t,this.coordinates=e,this.horizontal=r}function l(t,e){return t.y-e}function c(t,e){for(var r=null;t;){var n,i,o=t.key;o[0][0]<o[1][0]?(n=o[0],i=o[1]):(n=o[1],i=o[0]);var s=a(n,i,e);if(s<0)t=t.left;else if(s>0)if(e[0]!==o[1][0])r=t,t=t.right;else{if(l=c(t.right,e))return l;t=t.left}else{if(e[0]!==o[1][0])return t;var l;if(l=c(t.right,e))return l;t=t.left}}return r}function u(t,e,r,n){this.y=t,this.index=e,this.start=r,this.closed=n}function h(t,e,r,n){this.x=t,this.segment=e,this.create=r,this.index=n}s.prototype.castUp=function(t){var e=n.le(this.coordinates,t[0]);if(e<0)return-1;this.slabs[e];var r=c(this.slabs[e],t),i=-1;if(r&&(i=r.value),this.coordinates[e]===t[0]){var s=null;if(r&&(s=r.key),e>0){var u=c(this.slabs[e-1],t);u&&(s?o(u.key,s)>0&&(s=u.key,i=u.value):(i=u.value,s=u.key))}var h=this.horizontal[e];if(h.length>0){var f=n.ge(h,t[1],l);if(f<h.length){var p=h[f];if(t[1]===p.y){if(p.closed)return p.index;for(;f<h.length-1&&h[f+1].y===t[1];)if((p=h[f+=1]).closed)return p.index;if(p.y===t[1]&&!p.start){if((f+=1)>=h.length)return i;p=h[f]}}if(p.start)if(s){var d=a(s[0],s[1],[t[0],p.y]);s[0][0]>s[1][0]&&(d=-d),d>0&&(i=p.index)}else i=p.index;else p.y!==t[1]&&(i=p.index)}}}return i}},{"./lib/order-segments":506,"binary-search-bounds":79,"functional-red-black-tree":223,"robust-orientation":491}],508:[function(t,e,r){"use strict";var n=t("robust-dot-product"),i=t("robust-sum");function a(t,e){var r=i(n(t,e),[e[e.length-1]]);return r[r.length-1]}function o(t,e,r,n){var i=-e/(n-e);i<0?i=0:i>1&&(i=1);for(var a=1-i,o=t.length,s=new Array(o),l=0;l<o;++l)s[l]=i*t[l]+a*r[l];return s}e.exports=function(t,e){for(var r=[],n=[],i=a(t[t.length-1],e),s=t[t.length-1],l=t[0],c=0;c<t.length;++c,s=l){var u=a(l=t[c],e);if(i<0&&u>0||i>0&&u<0){var h=o(s,u,l,i);r.push(h),n.push(h.slice())}u<0?n.push(l.slice()):u>0?r.push(l.slice()):(r.push(l.slice()),n.push(l.slice())),i=u}return{positive:r,negative:n}},e.exports.positive=function(t,e){for(var r=[],n=a(t[t.length-1],e),i=t[t.length-1],s=t[0],l=0;l<t.length;++l,i=s){var c=a(s=t[l],e);(n<0&&c>0||n>0&&c<0)&&r.push(o(i,c,s,n)),c>=0&&r.push(s.slice()),n=c}return r},e.exports.negative=function(t,e){for(var r=[],n=a(t[t.length-1],e),i=t[t.length-1],s=t[0],l=0;l<t.length;++l,i=s){var c=a(s=t[l],e);(n<0&&c>0||n>0&&c<0)&&r.push(o(i,c,s,n)),c<=0&&r.push(s.slice()),n=c}return r}},{"robust-dot-product":488,"robust-sum":496}],509:[function(t,e,r){!function(){"use strict";var t={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function e(r){return function(r,n){var i,a,o,s,l,c,u,h,f,p=1,d=r.length,g="";for(a=0;a<d;a++)if("string"==typeof r[a])g+=r[a];else if("object"==typeof r[a]){if((s=r[a]).keys)for(i=n[p],o=0;o<s.keys.length;o++){if(null==i)throw new Error(e('[sprintf] Cannot access property "%s" of undefined value "%s"',s.keys[o],s.keys[o-1]));i=i[s.keys[o]]}else i=s.param_no?n[s.param_no]:n[p++];if(t.not_type.test(s.type)&&t.not_primitive.test(s.type)&&i instanceof Function&&(i=i()),t.numeric_arg.test(s.type)&&"number"!=typeof i&&isNaN(i))throw new TypeError(e("[sprintf] expecting number but found %T",i));switch(t.number.test(s.type)&&(h=i>=0),s.type){case"b":i=parseInt(i,10).toString(2);break;case"c":i=String.fromCharCode(parseInt(i,10));break;case"d":case"i":i=parseInt(i,10);break;case"j":i=JSON.stringify(i,null,s.width?parseInt(s.width):0);break;case"e":i=s.precision?parseFloat(i).toExponential(s.precision):parseFloat(i).toExponential();break;case"f":i=s.precision?parseFloat(i).toFixed(s.precision):parseFloat(i);break;case"g":i=s.precision?String(Number(i.toPrecision(s.precision))):parseFloat(i);break;case"o":i=(parseInt(i,10)>>>0).toString(8);break;case"s":i=String(i),i=s.precision?i.substring(0,s.precision):i;break;case"t":i=String(!!i),i=s.precision?i.substring(0,s.precision):i;break;case"T":i=Object.prototype.toString.call(i).slice(8,-1).toLowerCase(),i=s.precision?i.substring(0,s.precision):i;break;case"u":i=parseInt(i,10)>>>0;break;case"v":i=i.valueOf(),i=s.precision?i.substring(0,s.precision):i;break;case"x":i=(parseInt(i,10)>>>0).toString(16);break;case"X":i=(parseInt(i,10)>>>0).toString(16).toUpperCase()}t.json.test(s.type)?g+=i:(!t.number.test(s.type)||h&&!s.sign?f="":(f=h?"+":"-",i=i.toString().replace(t.sign,"")),c=s.pad_char?"0"===s.pad_char?"0":s.pad_char.charAt(1):" ",u=s.width-(f+i).length,l=s.width&&u>0?c.repeat(u):"",g+=s.align?f+i+l:"0"===c?f+l+i:l+f+i)}return g}(function(e){if(i[e])return i[e];var r,n=e,a=[],o=0;for(;n;){if(null!==(r=t.text.exec(n)))a.push(r[0]);else if(null!==(r=t.modulo.exec(n)))a.push("%");else{if(null===(r=t.placeholder.exec(n)))throw new SyntaxError("[sprintf] unexpected placeholder");if(r[2]){o|=1;var s=[],l=r[2],c=[];if(null===(c=t.key.exec(l)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(s.push(c[1]);""!==(l=l.substring(c[0].length));)if(null!==(c=t.key_access.exec(l)))s.push(c[1]);else{if(null===(c=t.index_access.exec(l)))throw new SyntaxError("[sprintf] failed to parse named argument key");s.push(c[1])}r[2]=s}else o|=2;if(3===o)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");a.push({placeholder:r[0],param_no:r[1],keys:r[2],sign:r[3],pad_char:r[4],align:r[5],width:r[6],precision:r[7],type:r[8]})}n=n.substring(r[0].length)}return i[e]=a}(r),arguments)}function n(t,r){return e.apply(null,[t].concat(r||[]))}var i=Object.create(null);"undefined"!=typeof r&&(r.sprintf=e,r.vsprintf=n),"undefined"!=typeof window&&(window.sprintf=e,window.vsprintf=n)}()},{}],510:[function(t,e,r){"use strict";var n=t("parenthesis");e.exports=function(t,e,r){if(null==t)throw Error("First argument should be a string");if(null==e)throw Error("Separator should be a string or a RegExp");r?("string"==typeof r||Array.isArray(r))&&(r={ignore:r}):r={},null==r.escape&&(r.escape=!0),null==r.ignore?r.ignore=["[]","()","{}","<>",'""',"''","``","\u201c\u201d","\xab\xbb"]:("string"==typeof r.ignore&&(r.ignore=[r.ignore]),r.ignore=r.ignore.map(function(t){return 1===t.length&&(t+=t),t}));var i=n.parse(t,{flat:!0,brackets:r.ignore}),a=i[0].split(e);if(r.escape){for(var o=[],s=0;s<a.length;s++){var l=a[s],c=a[s+1];"\\"===l[l.length-1]&&"\\"!==l[l.length-2]?(o.push(l+e+c),s++):o.push(l)}a=o}for(s=0;s<a.length;s++)i[0]=a[s],a[s]=n.stringify(i,{flat:!0});return a}},{parenthesis:447}],511:[function(t,e,r){"use strict";e.exports=function(t){for(var e=t.length,r=new Array(e),n=new Array(e),i=new Array(e),a=new Array(e),o=new Array(e),s=new Array(e),l=0;l<e;++l)r[l]=-1,n[l]=0,i[l]=!1,a[l]=0,o[l]=-1,s[l]=[];var c,u=0,h=[],f=[];function p(e){var l=[e],c=[e];for(r[e]=n[e]=u,i[e]=!0,u+=1;c.length>0;){e=c[c.length-1];var p=t[e];if(a[e]<p.length){for(var d=a[e];d<p.length;++d){var g=p[d];if(r[g]<0){r[g]=n[g]=u,i[g]=!0,u+=1,l.push(g),c.push(g);break}i[g]&&(n[e]=0|Math.min(n[e],n[g])),o[g]>=0&&s[e].push(o[g])}a[e]=d}else{if(n[e]===r[e]){for(var v=[],m=[],y=0,d=l.length-1;d>=0;--d){var x=l[d];if(i[x]=!1,v.push(x),m.push(s[x]),y+=s[x].length,o[x]=h.length,x===e){l.length=d;break}}h.push(v);for(var b=new Array(y),d=0;d<m.length;d++)for(var _=0;_<m[d].length;_++)b[--y]=m[d][_];f.push(b)}c.pop()}}}for(var l=0;l<e;++l)r[l]<0&&p(l);for(var l=0;l<f.length;l++){var d=f[l];if(0!==d.length){d.sort(function(t,e){return t-e}),c=[d[0]];for(var g=1;g<d.length;g++)d[g]!==d[g-1]&&c.push(d[g]);f[l]=c}}return{components:h,adjacencyList:f}}},{}],512:[function(t,e,r){"use strict";e.exports=function(t,e){if(t.dimension<=0)return{positions:[],cells:[]};if(1===t.dimension)return function(t,e){for(var r=a(t,e),n=r.length,i=new Array(n),o=new Array(n),s=0;s<n;++s)i[s]=[r[s]],o[s]=[s];return{positions:i,cells:o}}(t,e);var r=t.order.join()+"-"+t.dtype,s=o[r],e=+e||0;s||(s=o[r]=function(t,e){var r=t.length,a=["'use strict';"],o="surfaceNets"+t.join("_")+"d"+e;a.push("var contour=genContour({","order:[",t.join(),"],","scalarArguments: 3,","phase:function phaseFunc(p,a,b,c) { return (p > c)|0 },"),"generic"===e&&a.push("getters:[0],");for(var s=[],l=[],c=0;c<r;++c)s.push("d"+c),l.push("d"+c);for(var c=0;c<1<<r;++c)s.push("v"+c),l.push("v"+c);for(var c=0;c<1<<r;++c)s.push("p"+c),l.push("p"+c);s.push("a","b","c"),l.push("a","c"),a.push("vertex:function vertexFunc(",s.join(),"){");for(var u=[],c=0;c<1<<r;++c)u.push("(p"+c+"<<"+c+")");a.push("var m=(",u.join("+"),")|0;if(m===0||m===",(1<<(1<<r))-1,"){return}");var h=[],f=[];1<<(1<<r)<=128?(a.push("switch(m){"),f=a):a.push("switch(m>>>7){");for(var c=0;c<1<<(1<<r);++c){if(1<<(1<<r)>128&&c%128==0){h.length>0&&f.push("}}");var p="vExtra"+h.length;a.push("case ",c>>>7,":",p,"(m&0x7f,",l.join(),");break;"),f=["function ",p,"(m,",l.join(),"){switch(m){"],h.push(f)}f.push("case ",127&c,":");for(var d=new Array(r),g=new Array(r),v=new Array(r),m=new Array(r),y=0,x=0;x<r;++x)d[x]=[],g[x]=[],v[x]=0,m[x]=0;for(var x=0;x<1<<r;++x)for(var b=0;b<r;++b){var _=x^1<<b;if(!(_>x)&&!(c&1<<_)!=!(c&1<<x)){var w=1;c&1<<_?g[b].push("v"+_+"-v"+x):(g[b].push("v"+x+"-v"+_),w=-w),w<0?(d[b].push("-v"+x+"-v"+_),v[b]+=2):(d[b].push("v"+x+"+v"+_),v[b]-=2),y+=1;for(var k=0;k<r;++k)k!==b&&(_&1<<k?m[k]+=1:m[k]-=1)}}for(var A=[],b=0;b<r;++b)if(0===d[b].length)A.push("d"+b+"-0.5");else{var M="";v[b]<0?M=v[b]+"*c":v[b]>0&&(M="+"+v[b]+"*c");var T=d[b].length/y*.5,S=.5+m[b]/y*.5;A.push("d"+b+"-"+S+"-"+T+"*("+d[b].join("+")+M+")/("+g[b].join("+")+")")}f.push("a.push([",A.join(),"]);","break;")}a.push("}},"),h.length>0&&f.push("}}");for(var E=[],c=0;c<1<<r-1;++c)E.push("v"+c);E.push("c0","c1","p0","p1","a","b","c"),a.push("cell:function cellFunc(",E.join(),"){");var C=i(r-1);a.push("if(p0){b.push(",C.map(function(t){return"["+t.map(function(t){return"v"+t})+"]"}).join(),")}else{b.push(",C.map(function(t){var e=t.slice();return e.reverse(),"["+e.map(function(t){return"v"+t})+"]"}).join(),")}}});function ",o,"(array,level){var verts=[],cells=[];contour(array,verts,cells,level);return {positions:verts,cells:cells};} return ",o,";");for(var c=0;c<h.length;++c)a.push(h[c].join(""));return new Function("genContour",a.join(""))(n)}(t.order,t.dtype));return s(t,e)};var n=t("ndarray-extract-contour"),i=t("triangulate-hypercube"),a=t("zero-crossings");var o={}},{"ndarray-extract-contour":428,"triangulate-hypercube":522,"zero-crossings":555}],513:[function(t,e,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=function(){return function(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return function(t,e){var r=[],n=!0,i=!1,a=void 0;try{for(var o,s=t[Symbol.iterator]();!(n=(o=s.next()).done)&&(r.push(o.value),!e||r.length!==e);n=!0);}catch(t){i=!0,a=t}finally{try{!n&&s.return&&s.return()}finally{if(i)throw a}}return r}(t,e);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),i=2*Math.PI,a=function(t,e,r,n,i,a,o){var s=t.x,l=t.y;return{x:n*(s*=e)-i*(l*=r)+a,y:i*s+n*l+o}},o=function(t,e){var r=.551915024494,n=Math.cos(t),i=Math.sin(t),a=Math.cos(t+e),o=Math.sin(t+e);return[{x:n-i*r,y:i+n*r},{x:a+o*r,y:o-a*r},{x:a,y:o}]},s=function(t,e,r,n){var i=t*n-e*r<0?-1:1,a=(t*r+e*n)/(Math.sqrt(t*t+e*e)*Math.sqrt(t*t+e*e));return a>1&&(a=1),a<-1&&(a=-1),i*Math.acos(a)};r.default=function(t){var e=t.px,r=t.py,l=t.cx,c=t.cy,u=t.rx,h=t.ry,f=t.xAxisRotation,p=void 0===f?0:f,d=t.largeArcFlag,g=void 0===d?0:d,v=t.sweepFlag,m=void 0===v?0:v,y=[];if(0===u||0===h)return[];var x=Math.sin(p*i/360),b=Math.cos(p*i/360),_=b*(e-l)/2+x*(r-c)/2,w=-x*(e-l)/2+b*(r-c)/2;if(0===_&&0===w)return[];u=Math.abs(u),h=Math.abs(h);var k=Math.pow(_,2)/Math.pow(u,2)+Math.pow(w,2)/Math.pow(h,2);k>1&&(u*=Math.sqrt(k),h*=Math.sqrt(k));var A=function(t,e,r,n,a,o,l,c,u,h,f,p){var d=Math.pow(a,2),g=Math.pow(o,2),v=Math.pow(f,2),m=Math.pow(p,2),y=d*g-d*m-g*v;y<0&&(y=0),y/=d*m+g*v;var x=(y=Math.sqrt(y)*(l===c?-1:1))*a/o*p,b=y*-o/a*f,_=h*x-u*b+(t+r)/2,w=u*x+h*b+(e+n)/2,k=(f-x)/a,A=(p-b)/o,M=(-f-x)/a,T=(-p-b)/o,S=s(1,0,k,A),E=s(k,A,M,T);return 0===c&&E>0&&(E-=i),1===c&&E<0&&(E+=i),[_,w,S,E]}(e,r,l,c,u,h,g,m,x,b,_,w),M=n(A,4),T=M[0],S=M[1],E=M[2],C=M[3],L=Math.abs(C)/(i/4);Math.abs(1-L)<1e-7&&(L=1);var z=Math.max(Math.ceil(L),1);C/=z;for(var O=0;O<z;O++)y.push(o(E,C)),E+=C;return y.map(function(t){var e=a(t[0],u,h,b,x,T,S),r=e.x,n=e.y,i=a(t[1],u,h,b,x,T,S),o=i.x,s=i.y,l=a(t[2],u,h,b,x,T,S);return{x1:r,y1:n,x2:o,y2:s,x:l.x,y:l.y}})},e.exports=r.default},{}],514:[function(t,e,r){"use strict";var n=t("parse-svg-path"),i=t("abs-svg-path"),a=t("normalize-svg-path"),o=t("is-svg-path"),s=t("assert");e.exports=function(t){Array.isArray(t)&&1===t.length&&"string"==typeof t[0]&&(t=t[0]);"string"==typeof t&&(s(o(t),"String is not an SVG path."),t=n(t));if(s(Array.isArray(t),"Argument should be a string or an array of path segments."),t=i(t),!(t=a(t)).length)return[0,0,0,0];for(var e=[1/0,1/0,-1/0,-1/0],r=0,l=t.length;r<l;r++)for(var c=t[r].slice(1),u=0;u<c.length;u+=2)c[u+0]<e[0]&&(e[0]=c[u+0]),c[u+1]<e[1]&&(e[1]=c[u+1]),c[u+0]>e[2]&&(e[2]=c[u+0]),c[u+1]>e[3]&&(e[3]=c[u+1]);return e}},{"abs-svg-path":48,assert:56,"is-svg-path":413,"normalize-svg-path":515,"parse-svg-path":449}],515:[function(t,e,r){"use strict";e.exports=function(t){for(var e,r=[],o=0,s=0,l=0,c=0,u=null,h=null,f=0,p=0,d=0,g=t.length;d<g;d++){var v=t[d],m=v[0];switch(m){case"M":l=v[1],c=v[2];break;case"A":var y=n({px:f,py:p,cx:v[6],cy:v[7],rx:v[1],ry:v[2],xAxisRotation:v[3],largeArcFlag:v[4],sweepFlag:v[5]});if(!y.length)continue;for(var x,b=0;b<y.length;b++)x=y[b],v=["C",x.x1,x.y1,x.x2,x.y2,x.x,x.y],b<y.length-1&&r.push(v);break;case"S":var _=f,w=p;"C"!=e&&"S"!=e||(_+=_-o,w+=w-s),v=["C",_,w,v[1],v[2],v[3],v[4]];break;case"T":"Q"==e||"T"==e?(u=2*f-u,h=2*p-h):(u=f,h=p),v=a(f,p,u,h,v[1],v[2]);break;case"Q":u=v[1],h=v[2],v=a(f,p,v[1],v[2],v[3],v[4]);break;case"L":v=i(f,p,v[1],v[2]);break;case"H":v=i(f,p,v[1],p);break;case"V":v=i(f,p,f,v[1]);break;case"Z":v=i(f,p,l,c)}e=m,f=v[v.length-2],p=v[v.length-1],v.length>4?(o=v[v.length-4],s=v[v.length-3]):(o=f,s=p),r.push(v)}return r};var n=t("svg-arc-to-cubic-bezier");function i(t,e,r,n){return["C",t,e,r,n,r,n]}function a(t,e,r,n,i,a){return["C",t/3+2/3*r,e/3+2/3*n,i/3+2/3*r,a/3+2/3*n,i,a]}},{"svg-arc-to-cubic-bezier":513}],516:[function(t,e,r){"use strict";var n,i=t("svg-path-bounds"),a=t("parse-svg-path"),o=t("draw-svg-path"),s=t("is-svg-path"),l=t("bitmap-sdf"),c=document.createElement("canvas"),u=c.getContext("2d");e.exports=function(t,e){if(!s(t))throw Error("Argument should be valid svg path string");e||(e={});var r,h;e.shape?(r=e.shape[0],h=e.shape[1]):(r=c.width=e.w||e.width||200,h=c.height=e.h||e.height||200);var f=Math.min(r,h),p=e.stroke||0,d=e.viewbox||e.viewBox||i(t),g=[r/(d[2]-d[0]),h/(d[3]-d[1])],v=Math.min(g[0]||0,g[1]||0)/2;u.fillStyle="black",u.fillRect(0,0,r,h),u.fillStyle="white",p&&("number"!=typeof p&&(p=1),u.strokeStyle=p>0?"white":"black",u.lineWidth=Math.abs(p));if(u.translate(.5*r,.5*h),u.scale(v,v),function(){if(null!=n)return n;var t=document.createElement("canvas").getContext("2d");if(t.canvas.width=t.canvas.height=1,!window.Path2D)return n=!1;var e=new Path2D("M0,0h1v1h-1v-1Z");t.fillStyle="black",t.fill(e);var r=t.getImageData(0,0,1,1);return n=r&&r.data&&255===r.data[3]}()){var m=new Path2D(t);u.fill(m),p&&u.stroke(m)}else{var y=a(t);o(u,y),u.fill(),p&&u.stroke()}return u.setTransform(1,0,0,1,0,0),l(u,{cutoff:null!=e.cutoff?e.cutoff:.5,radius:null!=e.radius?e.radius:.5*f})}},{"bitmap-sdf":81,"draw-svg-path":156,"is-svg-path":413,"parse-svg-path":449,"svg-path-bounds":514}],517:[function(t,e,r){(function(r){"use strict";e.exports=function t(e,r,i){var i=i||{};var o=a[e];o||(o=a[e]={" ":{data:new Float32Array(0),shape:.2}});var s=o[r];if(!s)if(r.length<=1||!/\d/.test(r))s=o[r]=function(t){for(var e=t.cells,r=t.positions,n=new Float32Array(6*e.length),i=0,a=0,o=0;o<e.length;++o)for(var s=e[o],l=0;l<3;++l){var c=r[s[l]];n[i++]=c[0],n[i++]=c[1]+1.4,a=Math.max(c[0],a)}return{data:n,shape:a}}(n(r,{triangles:!0,font:e,textAlign:i.textAlign||"left",textBaseline:"alphabetic",styletags:{breaklines:!0,bolds:!0,italics:!0,subscripts:!0,superscripts:!0}}));else{for(var l=r.split(/(\d|\s)/),c=new Array(l.length),u=0,h=0,f=0;f<l.length;++f)c[f]=t(e,l[f]),u+=c[f].data.length,h+=c[f].shape,f>0&&(h+=.02);for(var p=new Float32Array(u),d=0,g=-.5*h,f=0;f<c.length;++f){for(var v=c[f].data,m=0;m<v.length;m+=2)p[d++]=v[m]+g,p[d++]=v[m+1];g+=c[f].shape+.02}s=o[r]={data:p,shape:h}}return s};var n=t("vectorize-text"),i=window||r.global||{},a=i.__TEXT_CACHE||{};i.__TEXT_CACHE={}}).call(this,t("_process"))},{_process:471,"vectorize-text":531}],518:[function(t,e,r){!function(t){var r=/^\s+/,n=/\s+$/,i=0,a=t.round,o=t.min,s=t.max,l=t.random;function c(e,l){if(l=l||{},(e=e||"")instanceof c)return e;if(!(this instanceof c))return new c(e,l);var u=function(e){var i={r:0,g:0,b:0},a=1,l=null,c=null,u=null,h=!1,f=!1;"string"==typeof e&&(e=function(t){t=t.replace(r,"").replace(n,"").toLowerCase();var e,i=!1;if(S[t])t=S[t],i=!0;else if("transparent"==t)return{r:0,g:0,b:0,a:0,format:"name"};if(e=j.rgb.exec(t))return{r:e[1],g:e[2],b:e[3]};if(e=j.rgba.exec(t))return{r:e[1],g:e[2],b:e[3],a:e[4]};if(e=j.hsl.exec(t))return{h:e[1],s:e[2],l:e[3]};if(e=j.hsla.exec(t))return{h:e[1],s:e[2],l:e[3],a:e[4]};if(e=j.hsv.exec(t))return{h:e[1],s:e[2],v:e[3]};if(e=j.hsva.exec(t))return{h:e[1],s:e[2],v:e[3],a:e[4]};if(e=j.hex8.exec(t))return{r:O(e[1]),g:O(e[2]),b:O(e[3]),a:R(e[4]),format:i?"name":"hex8"};if(e=j.hex6.exec(t))return{r:O(e[1]),g:O(e[2]),b:O(e[3]),format:i?"name":"hex"};if(e=j.hex4.exec(t))return{r:O(e[1]+""+e[1]),g:O(e[2]+""+e[2]),b:O(e[3]+""+e[3]),a:R(e[4]+""+e[4]),format:i?"name":"hex8"};if(e=j.hex3.exec(t))return{r:O(e[1]+""+e[1]),g:O(e[2]+""+e[2]),b:O(e[3]+""+e[3]),format:i?"name":"hex"};return!1}(e));"object"==typeof e&&(V(e.r)&&V(e.g)&&V(e.b)?(p=e.r,d=e.g,g=e.b,i={r:255*L(p,255),g:255*L(d,255),b:255*L(g,255)},h=!0,f="%"===String(e.r).substr(-1)?"prgb":"rgb"):V(e.h)&&V(e.s)&&V(e.v)?(l=D(e.s),c=D(e.v),i=function(e,r,n){e=6*L(e,360),r=L(r,100),n=L(n,100);var i=t.floor(e),a=e-i,o=n*(1-r),s=n*(1-a*r),l=n*(1-(1-a)*r),c=i%6;return{r:255*[n,s,o,o,l,n][c],g:255*[l,n,n,s,o,o][c],b:255*[o,o,l,n,n,s][c]}}(e.h,l,c),h=!0,f="hsv"):V(e.h)&&V(e.s)&&V(e.l)&&(l=D(e.s),u=D(e.l),i=function(t,e,r){var n,i,a;function o(t,e,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?t+6*(e-t)*r:r<.5?e:r<2/3?t+(e-t)*(2/3-r)*6:t}if(t=L(t,360),e=L(e,100),r=L(r,100),0===e)n=i=a=r;else{var s=r<.5?r*(1+e):r+e-r*e,l=2*r-s;n=o(l,s,t+1/3),i=o(l,s,t),a=o(l,s,t-1/3)}return{r:255*n,g:255*i,b:255*a}}(e.h,l,u),h=!0,f="hsl"),e.hasOwnProperty("a")&&(a=e.a));var p,d,g;return a=C(a),{ok:h,format:e.format||f,r:o(255,s(i.r,0)),g:o(255,s(i.g,0)),b:o(255,s(i.b,0)),a:a}}(e);this._originalInput=e,this._r=u.r,this._g=u.g,this._b=u.b,this._a=u.a,this._roundA=a(100*this._a)/100,this._format=l.format||u.format,this._gradientType=l.gradientType,this._r<1&&(this._r=a(this._r)),this._g<1&&(this._g=a(this._g)),this._b<1&&(this._b=a(this._b)),this._ok=u.ok,this._tc_id=i++}function u(t,e,r){t=L(t,255),e=L(e,255),r=L(r,255);var n,i,a=s(t,e,r),l=o(t,e,r),c=(a+l)/2;if(a==l)n=i=0;else{var u=a-l;switch(i=c>.5?u/(2-a-l):u/(a+l),a){case t:n=(e-r)/u+(e<r?6:0);break;case e:n=(r-t)/u+2;break;case r:n=(t-e)/u+4}n/=6}return{h:n,s:i,l:c}}function h(t,e,r){t=L(t,255),e=L(e,255),r=L(r,255);var n,i,a=s(t,e,r),l=o(t,e,r),c=a,u=a-l;if(i=0===a?0:u/a,a==l)n=0;else{switch(a){case t:n=(e-r)/u+(e<r?6:0);break;case e:n=(r-t)/u+2;break;case r:n=(t-e)/u+4}n/=6}return{h:n,s:i,v:c}}function f(t,e,r,n){var i=[I(a(t).toString(16)),I(a(e).toString(16)),I(a(r).toString(16))];return n&&i[0].charAt(0)==i[0].charAt(1)&&i[1].charAt(0)==i[1].charAt(1)&&i[2].charAt(0)==i[2].charAt(1)?i[0].charAt(0)+i[1].charAt(0)+i[2].charAt(0):i.join("")}function p(t,e,r,n){return[I(P(n)),I(a(t).toString(16)),I(a(e).toString(16)),I(a(r).toString(16))].join("")}function d(t,e){e=0===e?0:e||10;var r=c(t).toHsl();return r.s-=e/100,r.s=z(r.s),c(r)}function g(t,e){e=0===e?0:e||10;var r=c(t).toHsl();return r.s+=e/100,r.s=z(r.s),c(r)}function v(t){return c(t).desaturate(100)}function m(t,e){e=0===e?0:e||10;var r=c(t).toHsl();return r.l+=e/100,r.l=z(r.l),c(r)}function y(t,e){e=0===e?0:e||10;var r=c(t).toRgb();return r.r=s(0,o(255,r.r-a(-e/100*255))),r.g=s(0,o(255,r.g-a(-e/100*255))),r.b=s(0,o(255,r.b-a(-e/100*255))),c(r)}function x(t,e){e=0===e?0:e||10;var r=c(t).toHsl();return r.l-=e/100,r.l=z(r.l),c(r)}function b(t,e){var r=c(t).toHsl(),n=(r.h+e)%360;return r.h=n<0?360+n:n,c(r)}function _(t){var e=c(t).toHsl();return e.h=(e.h+180)%360,c(e)}function w(t){var e=c(t).toHsl(),r=e.h;return[c(t),c({h:(r+120)%360,s:e.s,l:e.l}),c({h:(r+240)%360,s:e.s,l:e.l})]}function k(t){var e=c(t).toHsl(),r=e.h;return[c(t),c({h:(r+90)%360,s:e.s,l:e.l}),c({h:(r+180)%360,s:e.s,l:e.l}),c({h:(r+270)%360,s:e.s,l:e.l})]}function A(t){var e=c(t).toHsl(),r=e.h;return[c(t),c({h:(r+72)%360,s:e.s,l:e.l}),c({h:(r+216)%360,s:e.s,l:e.l})]}function M(t,e,r){e=e||6,r=r||30;var n=c(t).toHsl(),i=360/r,a=[c(t)];for(n.h=(n.h-(i*e>>1)+720)%360;--e;)n.h=(n.h+i)%360,a.push(c(n));return a}function T(t,e){e=e||6;for(var r=c(t).toHsv(),n=r.h,i=r.s,a=r.v,o=[],s=1/e;e--;)o.push(c({h:n,s:i,v:a})),a=(a+s)%1;return o}c.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},getLuminance:function(){var e,r,n,i=this.toRgb();return e=i.r/255,r=i.g/255,n=i.b/255,.2126*(e<=.03928?e/12.92:t.pow((e+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:t.pow((r+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:t.pow((n+.055)/1.055,2.4))},setAlpha:function(t){return this._a=C(t),this._roundA=a(100*this._a)/100,this},toHsv:function(){var t=h(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=h(this._r,this._g,this._b),e=a(360*t.h),r=a(100*t.s),n=a(100*t.v);return 1==this._a?"hsv("+e+", "+r+"%, "+n+"%)":"hsva("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var t=u(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=u(this._r,this._g,this._b),e=a(360*t.h),r=a(100*t.s),n=a(100*t.l);return 1==this._a?"hsl("+e+", "+r+"%, "+n+"%)":"hsla("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHex:function(t){return f(this._r,this._g,this._b,t)},toHexString:function(t){return"#"+this.toHex(t)},toHex8:function(t){return function(t,e,r,n,i){var o=[I(a(t).toString(16)),I(a(e).toString(16)),I(a(r).toString(16)),I(P(n))];if(i&&o[0].charAt(0)==o[0].charAt(1)&&o[1].charAt(0)==o[1].charAt(1)&&o[2].charAt(0)==o[2].charAt(1)&&o[3].charAt(0)==o[3].charAt(1))return o[0].charAt(0)+o[1].charAt(0)+o[2].charAt(0)+o[3].charAt(0);return o.join("")}(this._r,this._g,this._b,this._a,t)},toHex8String:function(t){return"#"+this.toHex8(t)},toRgb:function(){return{r:a(this._r),g:a(this._g),b:a(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+a(this._r)+", "+a(this._g)+", "+a(this._b)+")":"rgba("+a(this._r)+", "+a(this._g)+", "+a(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:a(100*L(this._r,255))+"%",g:a(100*L(this._g,255))+"%",b:a(100*L(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+a(100*L(this._r,255))+"%, "+a(100*L(this._g,255))+"%, "+a(100*L(this._b,255))+"%)":"rgba("+a(100*L(this._r,255))+"%, "+a(100*L(this._g,255))+"%, "+a(100*L(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(E[f(this._r,this._g,this._b,!0)]||!1)},toFilter:function(t){var e="#"+p(this._r,this._g,this._b,this._a),r=e,n=this._gradientType?"GradientType = 1, ":"";if(t){var i=c(t);r="#"+p(i._r,i._g,i._b,i._a)}return"progid:DXImageTransform.Microsoft.gradient("+n+"startColorstr="+e+",endColorstr="+r+")"},toString:function(t){var e=!!t;t=t||this._format;var r=!1,n=this._a<1&&this._a>=0;return e||!n||"hex"!==t&&"hex6"!==t&&"hex3"!==t&&"hex4"!==t&&"hex8"!==t&&"name"!==t?("rgb"===t&&(r=this.toRgbString()),"prgb"===t&&(r=this.toPercentageRgbString()),"hex"!==t&&"hex6"!==t||(r=this.toHexString()),"hex3"===t&&(r=this.toHexString(!0)),"hex4"===t&&(r=this.toHex8String(!0)),"hex8"===t&&(r=this.toHex8String()),"name"===t&&(r=this.toName()),"hsl"===t&&(r=this.toHslString()),"hsv"===t&&(r=this.toHsvString()),r||this.toHexString()):"name"===t&&0===this._a?this.toName():this.toRgbString()},clone:function(){return c(this.toString())},_applyModification:function(t,e){var r=t.apply(null,[this].concat([].slice.call(e)));return this._r=r._r,this._g=r._g,this._b=r._b,this.setAlpha(r._a),this},lighten:function(){return this._applyModification(m,arguments)},brighten:function(){return this._applyModification(y,arguments)},darken:function(){return this._applyModification(x,arguments)},desaturate:function(){return this._applyModification(d,arguments)},saturate:function(){return this._applyModification(g,arguments)},greyscale:function(){return this._applyModification(v,arguments)},spin:function(){return this._applyModification(b,arguments)},_applyCombination:function(t,e){return t.apply(null,[this].concat([].slice.call(e)))},analogous:function(){return this._applyCombination(M,arguments)},complement:function(){return this._applyCombination(_,arguments)},monochromatic:function(){return this._applyCombination(T,arguments)},splitcomplement:function(){return this._applyCombination(A,arguments)},triad:function(){return this._applyCombination(w,arguments)},tetrad:function(){return this._applyCombination(k,arguments)}},c.fromRatio=function(t,e){if("object"==typeof t){var r={};for(var n in t)t.hasOwnProperty(n)&&(r[n]="a"===n?t[n]:D(t[n]));t=r}return c(t,e)},c.equals=function(t,e){return!(!t||!e)&&c(t).toRgbString()==c(e).toRgbString()},c.random=function(){return c.fromRatio({r:l(),g:l(),b:l()})},c.mix=function(t,e,r){r=0===r?0:r||50;var n=c(t).toRgb(),i=c(e).toRgb(),a=r/100;return c({r:(i.r-n.r)*a+n.r,g:(i.g-n.g)*a+n.g,b:(i.b-n.b)*a+n.b,a:(i.a-n.a)*a+n.a})},c.readability=function(e,r){var n=c(e),i=c(r);return(t.max(n.getLuminance(),i.getLuminance())+.05)/(t.min(n.getLuminance(),i.getLuminance())+.05)},c.isReadable=function(t,e,r){var n,i,a=c.readability(t,e);switch(i=!1,(n=function(t){var e,r;e=((t=t||{level:"AA",size:"small"}).level||"AA").toUpperCase(),r=(t.size||"small").toLowerCase(),"AA"!==e&&"AAA"!==e&&(e="AA");"small"!==r&&"large"!==r&&(r="small");return{level:e,size:r}}(r)).level+n.size){case"AAsmall":case"AAAlarge":i=a>=4.5;break;case"AAlarge":i=a>=3;break;case"AAAsmall":i=a>=7}return i},c.mostReadable=function(t,e,r){var n,i,a,o,s=null,l=0;i=(r=r||{}).includeFallbackColors,a=r.level,o=r.size;for(var u=0;u<e.length;u++)(n=c.readability(t,e[u]))>l&&(l=n,s=c(e[u]));return c.isReadable(t,s,{level:a,size:o})||!i?s:(r.includeFallbackColors=!1,c.mostReadable(t,["#fff","#000"],r))};var S=c.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"f0f",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},E=c.hexNames=function(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[t[r]]=r);return e}(S);function C(t){return t=parseFloat(t),(isNaN(t)||t<0||t>1)&&(t=1),t}function L(e,r){(function(t){return"string"==typeof t&&-1!=t.indexOf(".")&&1===parseFloat(t)})(e)&&(e="100%");var n=function(t){return"string"==typeof t&&-1!=t.indexOf("%")}(e);return e=o(r,s(0,parseFloat(e))),n&&(e=parseInt(e*r,10)/100),t.abs(e-r)<1e-6?1:e%r/parseFloat(r)}function z(t){return o(1,s(0,t))}function O(t){return parseInt(t,16)}function I(t){return 1==t.length?"0"+t:""+t}function D(t){return t<=1&&(t=100*t+"%"),t}function P(e){return t.round(255*parseFloat(e)).toString(16)}function R(t){return O(t)/255}var F,B,N,j=(B="[\\s|\\(]+("+(F="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+F+")[,|\\s]+("+F+")\\s*\\)?",N="[\\s|\\(]+("+F+")[,|\\s]+("+F+")[,|\\s]+("+F+")[,|\\s]+("+F+")\\s*\\)?",{CSS_UNIT:new RegExp(F),rgb:new RegExp("rgb"+B),rgba:new RegExp("rgba"+N),hsl:new RegExp("hsl"+B),hsla:new RegExp("hsla"+N),hsv:new RegExp("hsv"+B),hsva:new RegExp("hsva"+N),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/});function V(t){return!!j.CSS_UNIT.exec(t)}"undefined"!=typeof e&&e.exports?e.exports=c:window.tinycolor=c}(Math)},{}],519:[function(t,e,r){"use strict";e.exports=i,e.exports.float32=e.exports.float=i,e.exports.fract32=e.exports.fract=function(t){if(t.length){for(var e=i(t),r=0,n=e.length;r<n;r++)e[r]=t[r]-e[r];return e}return i(t-i(t))};var n=new Float32Array(1);function i(t){if(t.length){if(t instanceof Float32Array)return t;var e=new Float32Array(t);return e.set(t),e}return n[0]=t,n[0]}},{}],520:[function(t,e,r){"use strict";var n=t("parse-unit");e.exports=o;var i=96;function a(t,e){var r=n(getComputedStyle(t).getPropertyValue(e));return r[0]*o(r[1],t)}function o(t,e){switch(e=e||document.body,t=(t||"px").trim().toLowerCase(),e!==window&&e!==document||(e=document.body),t){case"%":return e.clientHeight/100;case"ch":case"ex":return function(t,e){var r=document.createElement("div");r.style["font-size"]="128"+t,e.appendChild(r);var n=a(r,"font-size")/128;return e.removeChild(r),n}(t,e);case"em":return a(e,"font-size");case"rem":return a(document.body,"font-size");case"vw":return window.innerWidth/100;case"vh":return window.innerHeight/100;case"vmin":return Math.min(window.innerWidth,window.innerHeight)/100;case"vmax":return Math.max(window.innerWidth,window.innerHeight)/100;case"in":return i;case"cm":return i/2.54;case"mm":return i/25.4;case"pt":return i/72;case"pc":return i/6}return 1}},{"parse-unit":450}],521:[function(t,e,r){var n;n=this,function(t){"use strict";var e=function(t){return t},r=function(t){if(null==(r=t.transform))return e;var r,n,i,a=r.scale[0],o=r.scale[1],s=r.translate[0],l=r.translate[1];return function(t,e){return e||(n=i=0),t[0]=(n+=t[0])*a+s,t[1]=(i+=t[1])*o+l,t}},n=function(t){var e=t.bbox;function n(t){l[0]=t[0],l[1]=t[1],s(l),l[0]<c&&(c=l[0]),l[0]>h&&(h=l[0]),l[1]<u&&(u=l[1]),l[1]>f&&(f=l[1])}function i(t){switch(t.type){case"GeometryCollection":t.geometries.forEach(i);break;case"Point":n(t.coordinates);break;case"MultiPoint":t.coordinates.forEach(n)}}if(!e){var a,o,s=r(t),l=new Array(2),c=1/0,u=c,h=-c,f=-c;for(o in t.arcs.forEach(function(t){for(var e=-1,r=t.length;++e<r;)a=t[e],l[0]=a[0],l[1]=a[1],s(l,e),l[0]<c&&(c=l[0]),l[0]>h&&(h=l[0]),l[1]<u&&(u=l[1]),l[1]>f&&(f=l[1])}),t.objects)i(t.objects[o]);e=t.bbox=[c,u,h,f]}return e},i=function(t,e){for(var r,n=t.length,i=n-e;i<--n;)r=t[i],t[i++]=t[n],t[n]=r};function a(t,e){var r=e.id,n=e.bbox,i=null==e.properties?{}:e.properties,a=o(t,e);return null==r&&null==n?{type:"Feature",properties:i,geometry:a}:null==n?{type:"Feature",id:r,properties:i,geometry:a}:{type:"Feature",id:r,bbox:n,properties:i,geometry:a}}function o(t,e){var n=r(t),a=t.arcs;function o(t,e){e.length&&e.pop();for(var r=a[t<0?~t:t],o=0,s=r.length;o<s;++o)e.push(n(r[o].slice(),o));t<0&&i(e,s)}function s(t){return n(t.slice())}function l(t){for(var e=[],r=0,n=t.length;r<n;++r)o(t[r],e);return e.length<2&&e.push(e[0].slice()),e}function c(t){for(var e=l(t);e.length<4;)e.push(e[0].slice());return e}function u(t){return t.map(c)}return function t(e){var r,n=e.type;switch(n){case"GeometryCollection":return{type:n,geometries:e.geometries.map(t)};case"Point":r=s(e.coordinates);break;case"MultiPoint":r=e.coordinates.map(s);break;case"LineString":r=l(e.arcs);break;case"MultiLineString":r=e.arcs.map(l);break;case"Polygon":r=u(e.arcs);break;case"MultiPolygon":r=e.arcs.map(u);break;default:return null}return{type:n,coordinates:r}}(e)}var s=function(t,e){var r={},n={},i={},a=[],o=-1;function s(t,e){for(var n in t){var i=t[n];delete e[i.start],delete i.start,delete i.end,i.forEach(function(t){r[t<0?~t:t]=1}),a.push(i)}}return e.forEach(function(r,n){var i,a=t.arcs[r<0?~r:r];a.length<3&&!a[1][0]&&!a[1][1]&&(i=e[++o],e[o]=r,e[n]=i)}),e.forEach(function(e){var r,a,o=function(e){var r,n=t.arcs[e<0?~e:e],i=n[0];t.transform?(r=[0,0],n.forEach(function(t){r[0]+=t[0],r[1]+=t[1]})):r=n[n.length-1];return e<0?[r,i]:[i,r]}(e),s=o[0],l=o[1];if(r=i[s])if(delete i[r.end],r.push(e),r.end=l,a=n[l]){delete n[a.start];var c=a===r?r:r.concat(a);n[c.start=r.start]=i[c.end=a.end]=c}else n[r.start]=i[r.end]=r;else if(r=n[l])if(delete n[r.start],r.unshift(e),r.start=s,a=i[s]){delete i[a.end];var u=a===r?r:a.concat(r);n[u.start=a.start]=i[u.end=r.end]=u}else n[r.start]=i[r.end]=r;else n[(r=[e]).start=s]=i[r.end=l]=r}),s(i,n),s(n,i),e.forEach(function(t){r[t<0?~t:t]||a.push([t])}),a};function l(t,e,r){var n,i,a;if(arguments.length>1)n=function(t,e,r){var n,i=[],a=[];function o(t){var e=t<0?~t:t;(a[e]||(a[e]=[])).push({i:t,g:n})}function s(t){t.forEach(o)}function l(t){t.forEach(s)}return function t(e){switch(n=e,e.type){case"GeometryCollection":e.geometries.forEach(t);break;case"LineString":s(e.arcs);break;case"MultiLineString":case"Polygon":l(e.arcs);break;case"MultiPolygon":e.arcs.forEach(l)}}(e),a.forEach(null==r?function(t){i.push(t[0].i)}:function(t){r(t[0].g,t[t.length-1].g)&&i.push(t[0].i)}),i}(0,e,r);else for(i=0,n=new Array(a=t.arcs.length);i<a;++i)n[i]=i;return{type:"MultiLineString",arcs:s(t,n)}}function c(t,e){var r={},n=[],i=[];function a(t){t.forEach(function(e){e.forEach(function(e){(r[e=e<0?~e:e]||(r[e]=[])).push(t)})}),n.push(t)}function l(e){return function(t){for(var e,r=-1,n=t.length,i=t[n-1],a=0;++r<n;)e=i,i=t[r],a+=e[0]*i[1]-e[1]*i[0];return Math.abs(a)}(o(t,{type:"Polygon",arcs:[e]}).coordinates[0])}return e.forEach(function t(e){switch(e.type){case"GeometryCollection":e.geometries.forEach(t);break;case"Polygon":a(e.arcs);break;case"MultiPolygon":e.arcs.forEach(a)}}),n.forEach(function(t){if(!t._){var e=[],n=[t];for(t._=1,i.push(e);t=n.pop();)e.push(t),t.forEach(function(t){t.forEach(function(t){r[t<0?~t:t].forEach(function(t){t._||(t._=1,n.push(t))})})})}}),n.forEach(function(t){delete t._}),{type:"MultiPolygon",arcs:i.map(function(e){var n,i=[];if(e.forEach(function(t){t.forEach(function(t){t.forEach(function(t){r[t<0?~t:t].length<2&&i.push(t)})})}),(n=(i=s(t,i)).length)>1)for(var a,o,c=1,u=l(i[0]);c<n;++c)(a=l(i[c]))>u&&(o=i[0],i[0]=i[c],i[c]=o,u=a);return i})}}var u=function(t,e){for(var r=0,n=t.length;r<n;){var i=r+n>>>1;t[i]<e?r=i+1:n=i}return r};t.bbox=n,t.feature=function(t,e){return"GeometryCollection"===e.type?{type:"FeatureCollection",features:e.geometries.map(function(e){return a(t,e)})}:a(t,e)},t.mesh=function(t){return o(t,l.apply(this,arguments))},t.meshArcs=l,t.merge=function(t){return o(t,c.apply(this,arguments))},t.mergeArcs=c,t.neighbors=function(t){var e={},r=t.map(function(){return[]});function n(t,r){t.forEach(function(t){t<0&&(t=~t);var n=e[t];n?n.push(r):e[t]=[r]})}function i(t,e){t.forEach(function(t){n(t,e)})}var a={LineString:n,MultiLineString:i,Polygon:i,MultiPolygon:function(t,e){t.forEach(function(t){i(t,e)})}};for(var o in t.forEach(function t(e,r){"GeometryCollection"===e.type?e.geometries.forEach(function(e){t(e,r)}):e.type in a&&a[e.type](e.arcs,r)}),e)for(var s=e[o],l=s.length,c=0;c<l;++c)for(var h=c+1;h<l;++h){var f,p=s[c],d=s[h];(f=r[p])[o=u(f,d)]!==d&&f.splice(o,0,d),(f=r[d])[o=u(f,p)]!==p&&f.splice(o,0,p)}return r},t.quantize=function(t,e){if(!((e=Math.floor(e))>=2))throw new Error("n must be \u22652");if(t.transform)throw new Error("already quantized");var r,i=n(t),a=i[0],o=(i[2]-a)/(e-1)||1,s=i[1],l=(i[3]-s)/(e-1)||1;function c(t){t[0]=Math.round((t[0]-a)/o),t[1]=Math.round((t[1]-s)/l)}function u(t){switch(t.type){case"GeometryCollection":t.geometries.forEach(u);break;case"Point":c(t.coordinates);break;case"MultiPoint":t.coordinates.forEach(c)}}for(r in t.arcs.forEach(function(t){for(var e,r,n,i=1,c=1,u=t.length,h=t[0],f=h[0]=Math.round((h[0]-a)/o),p=h[1]=Math.round((h[1]-s)/l);i<u;++i)h=t[i],r=Math.round((h[0]-a)/o),n=Math.round((h[1]-s)/l),r===f&&n===p||((e=t[c++])[0]=r-f,f=r,e[1]=n-p,p=n);c<2&&((e=t[c++])[0]=0,e[1]=0),t.length=c}),t.objects)u(t.objects[r]);return t.transform={scale:[o,l],translate:[a,s]},t},t.transform=r,t.untransform=function(t){if(null==(r=t.transform))return e;var r,n,i,a=r.scale[0],o=r.scale[1],s=r.translate[0],l=r.translate[1];return function(t,e){e||(n=i=0);var r=Math.round((t[0]-s)/a),c=Math.round((t[1]-l)/o);return t[0]=r-n,n=r,t[1]=c-i,i=c,t}},Object.defineProperty(t,"__esModule",{value:!0})}("object"==typeof r&&"undefined"!=typeof e?r:n.topojson=n.topojson||{})},{}],522:[function(t,e,r){"use strict";e.exports=function(t){if(t<0)return[];if(0===t)return[[0]];for(var e=0|Math.round(a(t+1)),r=[],o=0;o<e;++o){for(var s=n.unrank(t,o),l=[0],c=0,u=0;u<s.length;++u)c+=1<<s[u],l.push(c);i(s)<1&&(l[0]=c,l[t]=0),r.push(l)}return r};var n=t("permutation-rank"),i=t("permutation-parity"),a=t("gamma")},{gamma:224,"permutation-parity":452,"permutation-rank":453}],523:[function(t,e,r){"use strict";e.exports=function(t){var e=(t=t||{}).center||[0,0,0],r=t.up||[0,1,0],n=t.right||h(r),i=t.radius||1,a=t.theta||0,u=t.phi||0;if(e=[].slice.call(e,0,3),r=[].slice.call(r,0,3),s(r,r),n=[].slice.call(n,0,3),s(n,n),"eye"in t){var p=t.eye,d=[p[0]-e[0],p[1]-e[1],p[2]-e[2]];o(n,d,r),c(n[0],n[1],n[2])<1e-6?n=h(r):s(n,n),i=c(d[0],d[1],d[2]);var g=l(r,d)/i,v=l(n,d)/i;u=Math.acos(g),a=Math.acos(v)}return i=Math.log(i),new f(t.zoomMin,t.zoomMax,e,r,n,i,a,u)};var n=t("filtered-vector"),i=t("gl-mat4/invert"),a=t("gl-mat4/rotate"),o=t("gl-vec3/cross"),s=t("gl-vec3/normalize"),l=t("gl-vec3/dot");function c(t,e,r){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2))}function u(t){return Math.min(1,Math.max(-1,t))}function h(t){var e=Math.abs(t[0]),r=Math.abs(t[1]),n=Math.abs(t[2]),i=[0,0,0];e>Math.max(r,n)?i[2]=1:r>Math.max(e,n)?i[0]=1:i[1]=1;for(var a=0,o=0,l=0;l<3;++l)a+=t[l]*t[l],o+=i[l]*t[l];for(l=0;l<3;++l)i[l]-=o/a*t[l];return s(i,i),i}function f(t,e,r,i,a,o,s,l){this.center=n(r),this.up=n(i),this.right=n(a),this.radius=n([o]),this.angle=n([s,l]),this.angle.bounds=[[-1/0,-Math.PI/2],[1/0,Math.PI/2]],this.setDistanceLimits(t,e),this.computedCenter=this.center.curve(0),this.computedUp=this.up.curve(0),this.computedRight=this.right.curve(0),this.computedRadius=this.radius.curve(0),this.computedAngle=this.angle.curve(0),this.computedToward=[0,0,0],this.computedEye=[0,0,0],this.computedMatrix=new Array(16);for(var c=0;c<16;++c)this.computedMatrix[c]=.5;this.recalcMatrix(0)}var p=f.prototype;p.setDistanceLimits=function(t,e){t=t>0?Math.log(t):-1/0,e=e>0?Math.log(e):1/0,e=Math.max(e,t),this.radius.bounds[0][0]=t,this.radius.bounds[1][0]=e},p.getDistanceLimits=function(t){var e=this.radius.bounds[0];return t?(t[0]=Math.exp(e[0][0]),t[1]=Math.exp(e[1][0]),t):[Math.exp(e[0][0]),Math.exp(e[1][0])]},p.recalcMatrix=function(t){this.center.curve(t),this.up.curve(t),this.right.curve(t),this.radius.curve(t),this.angle.curve(t);for(var e=this.computedUp,r=this.computedRight,n=0,i=0,a=0;a<3;++a)i+=e[a]*r[a],n+=e[a]*e[a];var l=Math.sqrt(n),u=0;for(a=0;a<3;++a)r[a]-=e[a]*i/n,u+=r[a]*r[a],e[a]/=l;var h=Math.sqrt(u);for(a=0;a<3;++a)r[a]/=h;var f=this.computedToward;o(f,e,r),s(f,f);var p=Math.exp(this.computedRadius[0]),d=this.computedAngle[0],g=this.computedAngle[1],v=Math.cos(d),m=Math.sin(d),y=Math.cos(g),x=Math.sin(g),b=this.computedCenter,_=v*y,w=m*y,k=x,A=-v*x,M=-m*x,T=y,S=this.computedEye,E=this.computedMatrix;for(a=0;a<3;++a){var C=_*r[a]+w*f[a]+k*e[a];E[4*a+1]=A*r[a]+M*f[a]+T*e[a],E[4*a+2]=C,E[4*a+3]=0}var L=E[1],z=E[5],O=E[9],I=E[2],D=E[6],P=E[10],R=z*P-O*D,F=O*I-L*P,B=L*D-z*I,N=c(R,F,B);R/=N,F/=N,B/=N,E[0]=R,E[4]=F,E[8]=B;for(a=0;a<3;++a)S[a]=b[a]+E[2+4*a]*p;for(a=0;a<3;++a){u=0;for(var j=0;j<3;++j)u+=E[a+4*j]*S[j];E[12+a]=-u}E[15]=1},p.getMatrix=function(t,e){this.recalcMatrix(t);var r=this.computedMatrix;if(e){for(var n=0;n<16;++n)e[n]=r[n];return e}return r};var d=[0,0,0];p.rotate=function(t,e,r,n){if(this.angle.move(t,e,r),n){this.recalcMatrix(t);var i=this.computedMatrix;d[0]=i[2],d[1]=i[6],d[2]=i[10];for(var o=this.computedUp,s=this.computedRight,l=this.computedToward,c=0;c<3;++c)i[4*c]=o[c],i[4*c+1]=s[c],i[4*c+2]=l[c];a(i,i,n,d);for(c=0;c<3;++c)o[c]=i[4*c],s[c]=i[4*c+1];this.up.set(t,o[0],o[1],o[2]),this.right.set(t,s[0],s[1],s[2])}},p.pan=function(t,e,r,n){e=e||0,r=r||0,n=n||0,this.recalcMatrix(t);var i=this.computedMatrix,a=(Math.exp(this.computedRadius[0]),i[1]),o=i[5],s=i[9],l=c(a,o,s);a/=l,o/=l,s/=l;var u=i[0],h=i[4],f=i[8],p=u*a+h*o+f*s,d=c(u-=a*p,h-=o*p,f-=s*p),g=(u/=d)*e+a*r,v=(h/=d)*e+o*r,m=(f/=d)*e+s*r;this.center.move(t,g,v,m);var y=Math.exp(this.computedRadius[0]);y=Math.max(1e-4,y+n),this.radius.set(t,Math.log(y))},p.translate=function(t,e,r,n){this.center.move(t,e||0,r||0,n||0)},p.setMatrix=function(t,e,r,n){var a=1;"number"==typeof r&&(a=0|r),(a<0||a>3)&&(a=1);var o=(a+2)%3;e||(this.recalcMatrix(t),e=this.computedMatrix);var s=e[a],l=e[a+4],h=e[a+8];if(n){var f=Math.abs(s),p=Math.abs(l),d=Math.abs(h),g=Math.max(f,p,d);f===g?(s=s<0?-1:1,l=h=0):d===g?(h=h<0?-1:1,s=l=0):(l=l<0?-1:1,s=h=0)}else{var v=c(s,l,h);s/=v,l/=v,h/=v}var m,y,x=e[o],b=e[o+4],_=e[o+8],w=x*s+b*l+_*h,k=c(x-=s*w,b-=l*w,_-=h*w),A=l*(_/=k)-h*(b/=k),M=h*(x/=k)-s*_,T=s*b-l*x,S=c(A,M,T);if(A/=S,M/=S,T/=S,this.center.jump(t,H,G,Y),this.radius.idle(t),this.up.jump(t,s,l,h),this.right.jump(t,x,b,_),2===a){var E=e[1],C=e[5],L=e[9],z=E*x+C*b+L*_,O=E*A+C*M+L*T;m=R<0?-Math.PI/2:Math.PI/2,y=Math.atan2(O,z)}else{var I=e[2],D=e[6],P=e[10],R=I*s+D*l+P*h,F=I*x+D*b+P*_,B=I*A+D*M+P*T;m=Math.asin(u(R)),y=Math.atan2(B,F)}this.angle.jump(t,y,m),this.recalcMatrix(t);var N=e[2],j=e[6],V=e[10],U=this.computedMatrix;i(U,e);var q=U[15],H=U[12]/q,G=U[13]/q,Y=U[14]/q,W=Math.exp(this.computedRadius[0]);this.center.jump(t,H-N*W,G-j*W,Y-V*W)},p.lastT=function(){return Math.max(this.center.lastT(),this.up.lastT(),this.right.lastT(),this.radius.lastT(),this.angle.lastT())},p.idle=function(t){this.center.idle(t),this.up.idle(t),this.right.idle(t),this.radius.idle(t),this.angle.idle(t)},p.flush=function(t){this.center.flush(t),this.up.flush(t),this.right.flush(t),this.radius.flush(t),this.angle.flush(t)},p.setDistance=function(t,e){e>0&&this.radius.set(t,Math.log(e))},p.lookAt=function(t,e,r,n){this.recalcMatrix(t),e=e||this.computedEye,r=r||this.computedCenter;var i=(n=n||this.computedUp)[0],a=n[1],o=n[2],s=c(i,a,o);if(!(s<1e-6)){i/=s,a/=s,o/=s;var l=e[0]-r[0],h=e[1]-r[1],f=e[2]-r[2],p=c(l,h,f);if(!(p<1e-6)){l/=p,h/=p,f/=p;var d=this.computedRight,g=d[0],v=d[1],m=d[2],y=i*g+a*v+o*m,x=c(g-=y*i,v-=y*a,m-=y*o);if(!(x<.01&&(x=c(g=a*f-o*h,v=o*l-i*f,m=i*h-a*l))<1e-6)){g/=x,v/=x,m/=x,this.up.set(t,i,a,o),this.right.set(t,g,v,m),this.center.set(t,r[0],r[1],r[2]),this.radius.set(t,Math.log(p));var b=a*m-o*v,_=o*g-i*m,w=i*v-a*g,k=c(b,_,w),A=i*l+a*h+o*f,M=g*l+v*h+m*f,T=(b/=k)*l+(_/=k)*h+(w/=k)*f,S=Math.asin(u(A)),E=Math.atan2(T,M),C=this.angle._state,L=C[C.length-1],z=C[C.length-2];L%=2*Math.PI;var O=Math.abs(L+2*Math.PI-E),I=Math.abs(L-E),D=Math.abs(L-2*Math.PI-E);O<I&&(L+=2*Math.PI),D<I&&(L-=2*Math.PI),this.angle.jump(this.angle.lastT(),L,z),this.angle.set(t,E,S)}}}}},{"filtered-vector":219,"gl-mat4/invert":258,"gl-mat4/rotate":263,"gl-vec3/cross":323,"gl-vec3/dot":328,"gl-vec3/normalize":345}],524:[function(t,e,r){"use strict";e.exports=function(t,e,r){var i=t*e,a=n*t,o=a-(a-t),s=t-o,l=n*e,c=l-(l-e),u=e-c,h=s*u-(i-o*c-s*c-o*u);if(r)return r[0]=h,r[1]=i,r;return[h,i]};var n=+(Math.pow(2,27)+1)},{}],525:[function(t,e,r){"use strict";e.exports=function(t,e,r){var n=t+e,i=n-t,a=e-i,o=t-(n-i);if(r)return r[0]=o+a,r[1]=n,r;return[o+a,n]}},{}],526:[function(t,e,r){(function(e,n){"use strict";var i=t("bit-twiddle"),a=t("dup");e.__TYPEDARRAY_POOL||(e.__TYPEDARRAY_POOL={UINT8:a([32,0]),UINT16:a([32,0]),UINT32:a([32,0]),INT8:a([32,0]),INT16:a([32,0]),INT32:a([32,0]),FLOAT:a([32,0]),DOUBLE:a([32,0]),DATA:a([32,0]),UINT8C:a([32,0]),BUFFER:a([32,0])});var o="undefined"!=typeof Uint8ClampedArray,s=e.__TYPEDARRAY_POOL;s.UINT8C||(s.UINT8C=a([32,0])),s.BUFFER||(s.BUFFER=a([32,0]));var l=s.DATA,c=s.BUFFER;function u(t){if(t){var e=t.length||t.byteLength,r=i.log2(e);l[r].push(t)}}function h(t){t=i.nextPow2(t);var e=i.log2(t),r=l[e];return r.length>0?r.pop():new ArrayBuffer(t)}function f(t){return new Uint8Array(h(t),0,t)}function p(t){return new Uint16Array(h(2*t),0,t)}function d(t){return new Uint32Array(h(4*t),0,t)}function g(t){return new Int8Array(h(t),0,t)}function v(t){return new Int16Array(h(2*t),0,t)}function m(t){return new Int32Array(h(4*t),0,t)}function y(t){return new Float32Array(h(4*t),0,t)}function x(t){return new Float64Array(h(8*t),0,t)}function b(t){return o?new Uint8ClampedArray(h(t),0,t):f(t)}function _(t){return new DataView(h(t),0,t)}function w(t){t=i.nextPow2(t);var e=i.log2(t),r=c[e];return r.length>0?r.pop():new n(t)}r.free=function(t){if(n.isBuffer(t))c[i.log2(t.length)].push(t);else{if("[object ArrayBuffer]"!==Object.prototype.toString.call(t)&&(t=t.buffer),!t)return;var e=t.length||t.byteLength,r=0|i.log2(e);l[r].push(t)}},r.freeUint8=r.freeUint16=r.freeUint32=r.freeInt8=r.freeInt16=r.freeInt32=r.freeFloat32=r.freeFloat=r.freeFloat64=r.freeDouble=r.freeUint8Clamped=r.freeDataView=function(t){u(t.buffer)},r.freeArrayBuffer=u,r.freeBuffer=function(t){c[i.log2(t.length)].push(t)},r.malloc=function(t,e){if(void 0===e||"arraybuffer"===e)return h(t);switch(e){case"uint8":return f(t);case"uint16":return p(t);case"uint32":return d(t);case"int8":return g(t);case"int16":return v(t);case"int32":return m(t);case"float":case"float32":return y(t);case"double":case"float64":return x(t);case"uint8_clamped":return b(t);case"buffer":return w(t);case"data":case"dataview":return _(t);default:return null}return null},r.mallocArrayBuffer=h,r.mallocUint8=f,r.mallocUint16=p,r.mallocUint32=d,r.mallocInt8=g,r.mallocInt16=v,r.mallocInt32=m,r.mallocFloat32=r.mallocFloat=y,r.mallocFloat64=r.mallocDouble=x,r.mallocUint8Clamped=b,r.mallocDataView=_,r.mallocBuffer=w,r.clearCache=function(){for(var t=0;t<32;++t)s.UINT8[t].length=0,s.UINT16[t].length=0,s.UINT32[t].length=0,s.INT8[t].length=0,s.INT16[t].length=0,s.INT32[t].length=0,s.FLOAT[t].length=0,s.DOUBLE[t].length=0,s.UINT8C[t].length=0,l[t].length=0,c[t].length=0}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},t("buffer").Buffer)},{"bit-twiddle":80,buffer:93,dup:158}],527:[function(t,e,r){"use strict";function n(t){this.roots=new Array(t),this.ranks=new Array(t);for(var e=0;e<t;++e)this.roots[e]=e,this.ranks[e]=0}e.exports=n;var i=n.prototype;Object.defineProperty(i,"length",{get:function(){return this.roots.length}}),i.makeSet=function(){var t=this.roots.length;return this.roots.push(t),this.ranks.push(0),t},i.find=function(t){for(var e=t,r=this.roots;r[t]!==t;)t=r[t];for(;r[e]!==t;){var n=r[e];r[e]=t,e=n}return t},i.link=function(t,e){var r=this.find(t),n=this.find(e);if(r!==n){var i=this.ranks,a=this.roots,o=i[r],s=i[n];o<s?a[r]=n:s<o?a[n]=r:(a[n]=r,++i[r])}}},{}],528:[function(t,e,r){"use strict";e.exports=function(t,e,r){return 0===t.length?t:e?(r||t.sort(e),function(t,e){for(var r=1,n=t.length,i=t[0],a=t[0],o=1;o<n;++o)if(a=i,e(i=t[o],a)){if(o===r){r++;continue}t[r++]=i}return t.length=r,t}(t,e)):(r||t.sort(),function(t){for(var e=1,r=t.length,n=t[0],i=t[0],a=1;a<r;++a,i=n)if(i=n,(n=t[a])!==i){if(a===e){e++;continue}t[e++]=n}return t.length=e,t}(t))}},{}],529:[function(t,e,r){var n=/[\'\"]/;e.exports=function(t){return t?(n.test(t.charAt(0))&&(t=t.substr(1)),n.test(t.charAt(t.length-1))&&(t=t.substr(0,t.length-1)),t):""}},{}],530:[function(t,e,r){"use strict";e.exports=function(t,e,r){Array.isArray(r)||(r=[].slice.call(arguments,2));for(var n=0,i=r.length;n<i;n++){var a=r[n];for(var o in a)if((void 0===e[o]||Array.isArray(e[o])||t[o]!==e[o])&&o in e){var s;if(!0===a[o])s=e[o];else{if(!1===a[o])continue;if("function"==typeof a[o]&&void 0===(s=a[o](e[o],t,e)))continue}t[o]=s}}return t}},{}],531:[function(t,e,r){"use strict";e.exports=function(t,e){"object"==typeof e&&null!==e||(e={});return n(t,e.canvas||i,e.context||a,e)};var n=t("./lib/vtext"),i=null,a=null;"undefined"!=typeof document&&((i=document.createElement("canvas")).width=8192,i.height=1024,a=i.getContext("2d"))},{"./lib/vtext":532}],532:[function(t,e,r){e.exports=function(t,e,r,n){var a=64,o=1.25,s={breaklines:!1,bolds:!1,italics:!1,subscripts:!1,superscripts:!1};n&&(n.size&&n.size>0&&(a=n.size),n.lineSpacing&&n.lineSpacing>0&&(o=n.lineSpacing),n.styletags&&n.styletags.breaklines&&(s.breaklines=!!n.styletags.breaklines),n.styletags&&n.styletags.bolds&&(s.bolds=!!n.styletags.bolds),n.styletags&&n.styletags.italics&&(s.italics=!!n.styletags.italics),n.styletags&&n.styletags.subscripts&&(s.subscripts=!!n.styletags.subscripts),n.styletags&&n.styletags.superscripts&&(s.superscripts=!!n.styletags.superscripts));return r.font=[n.fontStyle,n.fontVariant,n.fontWeight,a+"px",n.font].filter(function(t){return t}).join(" "),r.textAlign="start",r.textBaseline="alphabetic",r.direction="ltr",w(function(t,e,r,n,a,o){r=r.replace(/\n/g,""),r=!0===o.breaklines?r.replace(/\<br\>/g,"\n"):r.replace(/\<br\>/g," ");var s="",l=[];for(k=0;k<r.length;++k)l[k]=s;!0===o.bolds&&(l=x(c,u,r,l)),!0===o.italics&&(l=x(h,f,r,l)),!0===o.superscripts&&(l=x(p,g,r,l)),!0===o.subscripts&&(l=x(v,y,r,l));var b=[],_="";for(k=0;k<r.length;++k)null!==l[k]&&(_+=r[k],b.push(l[k]));var w,k,A,M,T,S=_.split("\n"),E=S.length,C=Math.round(a*n),L=n,z=2*n,O=0,I=E*C+z;t.height<I&&(t.height=I),e.fillStyle="#000",e.fillRect(0,0,t.width,t.height),e.fillStyle="#fff";var D=0,P="";function R(){if(""!==P){var t=e.measureText(P).width;e.fillText(P,L+A,z+M),A+=t}}function F(){return Math.round(T)+"px "}function B(t,r){var n=""+e.font;if(!0===o.subscripts){var i=t.indexOf(m),a=r.indexOf(m),s=i>-1?parseInt(t[1+i]):0,l=a>-1?parseInt(r[1+a]):0;s!==l&&(n=n.replace(F(),"?px "),T*=Math.pow(.75,l-s),n=n.replace("?px ",F())),M+=.25*C*(l-s)}if(!0===o.superscripts){var c=t.indexOf(d),h=r.indexOf(d),p=c>-1?parseInt(t[1+c]):0,g=h>-1?parseInt(r[1+h]):0;p!==g&&(n=n.replace(F(),"?px "),T*=Math.pow(.75,g-p),n=n.replace("?px ",F())),M-=.25*C*(g-p)}if(!0===o.bolds){var v=t.indexOf(u)>-1,y=r.indexOf(u)>-1;!v&&y&&(n=x?n.replace("italic ","italic bold "):"bold "+n),v&&!y&&(n=n.replace("bold ",""))}if(!0===o.italics){var x=t.indexOf(f)>-1,b=r.indexOf(f)>-1;!x&&b&&(n="italic "+n),x&&!b&&(n=n.replace("italic ",""))}e.font=n}for(w=0;w<E;++w){var N=S[w]+"\n";for(A=0,M=w*C,T=n,P="",k=0;k<N.length;++k){var j=k+D<b.length?b[k+D]:b[b.length-1];s===j?P+=N[k]:(R(),P=N[k],void 0!==j&&(B(s,j),s=j))}R(),D+=N.length;var V=0|Math.round(A+2*L);O<V&&(O=V)}var U=O,q=z+C*E;return i(e.getImageData(0,0,U,q).data,[q,U,4]).pick(-1,-1,0).transpose(1,0)}(e,r,t,a,o,s),n,a)},e.exports.processPixels=w;var n=t("surface-nets"),i=t("ndarray"),a=t("simplify-planar-graph"),o=t("clean-pslg"),s=t("cdt2d"),l=t("planar-graph-to-polyline"),c="b",u="b|",h="i",f="i|",p="sup",d="+",g="+1",v="sub",m="-",y="-1";function x(t,e,r,n){for(var i="<"+t+">",a="</"+t+">",o=i.length,s=a.length,l=e[0]===d||e[0]===m,c=0,u=-s;c>-1&&-1!==(c=r.indexOf(i,c))&&-1!==(u=r.indexOf(a,c+o))&&!(u<=c);){for(var h=c;h<u+s;++h)if(h<c+o||h>=u)n[h]=null,r=r.substr(0,h)+" "+r.substr(h+1);else if(null!==n[h]){var f=n[h].indexOf(e[0]);-1===f?n[h]+=e:l&&(n[h]=n[h].substr(0,f+1)+(1+parseInt(n[h][f+1]))+n[h].substr(f+2))}var p=c+o,g=r.substr(p,u-p).indexOf(i);c=-1!==g?g:u+s}return n}function b(t,e){var r=n(t,128);return e?a(r.cells,r.positions,.25):{edges:r.cells,positions:r.positions}}function _(t,e,r,n){var i=b(t,n),a=function(t,e,r){for(var n=e.textAlign||"start",i=e.textBaseline||"alphabetic",a=[1<<30,1<<30],o=[0,0],s=t.length,l=0;l<s;++l)for(var c=t[l],u=0;u<2;++u)a[u]=0|Math.min(a[u],c[u]),o[u]=0|Math.max(o[u],c[u]);var h=0;switch(n){case"center":h=-.5*(a[0]+o[0]);break;case"right":case"end":h=-o[0];break;case"left":case"start":h=-a[0];break;default:throw new Error("vectorize-text: Unrecognized textAlign: '"+n+"'")}var f=0;switch(i){case"hanging":case"top":f=-a[1];break;case"middle":f=-.5*(a[1]+o[1]);break;case"alphabetic":case"ideographic":f=-3*r;break;case"bottom":f=-o[1];break;default:throw new Error("vectorize-text: Unrecoginized textBaseline: '"+i+"'")}var p=1/r;return"lineHeight"in e?p*=+e.lineHeight:"width"in e?p=e.width/(o[0]-a[0]):"height"in e&&(p=e.height/(o[1]-a[1])),t.map(function(t){return[p*(t[0]+h),p*(t[1]+f)]})}(i.positions,e,r),c=i.edges,u="ccw"===e.orientation;if(o(a,c),e.polygons||e.polygon||e.polyline){for(var h=l(c,a),f=new Array(h.length),p=0;p<h.length;++p){for(var d=h[p],g=new Array(d.length),v=0;v<d.length;++v){for(var m=d[v],y=new Array(m.length),x=0;x<m.length;++x)y[x]=a[m[x]].slice();u&&y.reverse(),g[v]=y}f[p]=g}return f}return e.triangles||e.triangulate||e.triangle?{cells:s(a,c,{delaunay:!1,exterior:!1,interior:!0}),positions:a}:{edges:c,positions:a}}function w(t,e,r){try{return _(t,e,r,!0)}catch(t){}try{return _(t,e,r,!1)}catch(t){}return e.polygons||e.polyline||e.polygon?[]:e.triangles||e.triangulate||e.triangle?{cells:[],positions:[]}:{edges:[],positions:[]}}},{cdt2d:94,"clean-pslg":104,ndarray:439,"planar-graph-to-polyline":457,"simplify-planar-graph":505,"surface-nets":512}],533:[function(t,e,r){!function(){"use strict";if("undefined"==typeof ses||!ses.ok||ses.ok()){"undefined"!=typeof ses&&(ses.weakMapPermitHostObjects=v);var t=!1;if("function"==typeof WeakMap){var r=WeakMap;if("undefined"!=typeof navigator&&/Firefox/.test(navigator.userAgent));else{var n=new r,i=Object.freeze({});if(n.set(i,1),1===n.get(i))return void(e.exports=WeakMap);t=!0}}Object.prototype.hasOwnProperty;var a=Object.getOwnPropertyNames,o=Object.defineProperty,s=Object.isExtensible,l="weakmap:",c=l+"ident:"+Math.random()+"___";if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues&&"function"==typeof ArrayBuffer&&"function"==typeof Uint8Array){var u=new ArrayBuffer(25),h=new Uint8Array(u);crypto.getRandomValues(h),c=l+"rand:"+Array.prototype.map.call(h,function(t){return(t%36).toString(36)}).join("")+"___"}if(o(Object,"getOwnPropertyNames",{value:function(t){return a(t).filter(m)}}),"getPropertyNames"in Object){var f=Object.getPropertyNames;o(Object,"getPropertyNames",{value:function(t){return f(t).filter(m)}})}!function(){var t=Object.freeze;o(Object,"freeze",{value:function(e){return y(e),t(e)}});var e=Object.seal;o(Object,"seal",{value:function(t){return y(t),e(t)}});var r=Object.preventExtensions;o(Object,"preventExtensions",{value:function(t){return y(t),r(t)}})}();var p=!1,d=0,g=function(){this instanceof g||b();var t=[],e=[],r=d++;return Object.create(g.prototype,{get___:{value:x(function(n,i){var a,o=y(n);return o?r in o?o[r]:i:(a=t.indexOf(n))>=0?e[a]:i})},has___:{value:x(function(e){var n=y(e);return n?r in n:t.indexOf(e)>=0})},set___:{value:x(function(n,i){var a,o=y(n);return o?o[r]=i:(a=t.indexOf(n))>=0?e[a]=i:(a=t.length,e[a]=i,t[a]=n),this})},delete___:{value:x(function(n){var i,a,o=y(n);return o?r in o&&delete o[r]:!((i=t.indexOf(n))<0||(a=t.length-1,t[i]=void 0,e[i]=e[a],t[i]=t[a],t.length=a,e.length=a,0))})}})};g.prototype=Object.create(Object.prototype,{get:{value:function(t,e){return this.get___(t,e)},writable:!0,configurable:!0},has:{value:function(t){return this.has___(t)},writable:!0,configurable:!0},set:{value:function(t,e){return this.set___(t,e)},writable:!0,configurable:!0},delete:{value:function(t){return this.delete___(t)},writable:!0,configurable:!0}}),"function"==typeof r?function(){function n(){this instanceof g||b();var e,n=new r,i=void 0,a=!1;return e=t?function(t,e){return n.set(t,e),n.has(t)||(i||(i=new g),i.set(t,e)),this}:function(t,e){if(a)try{n.set(t,e)}catch(r){i||(i=new g),i.set___(t,e)}else n.set(t,e);return this},Object.create(g.prototype,{get___:{value:x(function(t,e){return i?n.has(t)?n.get(t):i.get___(t,e):n.get(t,e)})},has___:{value:x(function(t){return n.has(t)||!!i&&i.has___(t)})},set___:{value:x(e)},delete___:{value:x(function(t){var e=!!n.delete(t);return i&&i.delete___(t)||e})},permitHostObjects___:{value:x(function(t){if(t!==v)throw new Error("bogus call to permitHostObjects___");a=!0})}})}t&&"undefined"!=typeof Proxy&&(Proxy=void 0),n.prototype=g.prototype,e.exports=n,Object.defineProperty(WeakMap.prototype,"constructor",{value:WeakMap,enumerable:!1,configurable:!0,writable:!0})}():("undefined"!=typeof Proxy&&(Proxy=void 0),e.exports=g)}function v(t){t.permitHostObjects___&&t.permitHostObjects___(v)}function m(t){return!(t.substr(0,l.length)==l&&"___"===t.substr(t.length-3))}function y(t){if(t!==Object(t))throw new TypeError("Not an object: "+t);var e=t[c];if(e&&e.key===t)return e;if(s(t)){e={key:t};try{return o(t,c,{value:e,writable:!1,enumerable:!1,configurable:!1}),e}catch(t){return}}}function x(t){return t.prototype=null,Object.freeze(t)}function b(){p||"undefined"==typeof console||(p=!0,console.warn("WeakMap should be invoked as new WeakMap(), not WeakMap(). This will be an error in the future."))}}()},{}],534:[function(t,e,r){var n=t("./hidden-store.js");e.exports=function(){var t={};return function(e){if(("object"!=typeof e||null===e)&&"function"!=typeof e)throw new Error("Weakmap-shim: Key must be object");var r=e.valueOf(t);return r&&r.identity===t?r:n(e,t)}}},{"./hidden-store.js":535}],535:[function(t,e,r){e.exports=function(t,e){var r={identity:e},n=t.valueOf;return Object.defineProperty(t,"valueOf",{value:function(t){return t!==e?n.apply(this,arguments):r},writable:!0}),r}},{}],536:[function(t,e,r){var n=t("./create-store.js");e.exports=function(){var t=n();return{get:function(e,r){var n=t(e);return n.hasOwnProperty("value")?n.value:r},set:function(e,r){return t(e).value=r,this},has:function(e){return"value"in t(e)},delete:function(e){return delete t(e).value}}}},{"./create-store.js":534}],537:[function(t,e,r){var n=t("get-canvas-context");e.exports=function(t){return n("webgl",t)}},{"get-canvas-context":225}],538:[function(t,e,r){var n=t("../main"),i=t("object-assign"),a=n.instance();function o(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}o.prototype=new n.baseCalendar,i(o.prototype,{name:"Chinese",jdEpoch:1721425.5,hasYearZero:!1,minMonth:0,firstMonth:0,minDay:1,regionalOptions:{"":{name:"Chinese",epochs:["BEC","EC"],monthNumbers:function(t,e){if("string"==typeof t){var r=t.match(l);return r?r[0]:""}var n=this._validateYear(t),i=t.month(),a=""+this.toChineseMonth(n,i);return e&&a.length<2&&(a="0"+a),this.isIntercalaryMonth(n,i)&&(a+="i"),a},monthNames:function(t){if("string"==typeof t){var e=t.match(c);return e?e[0]:""}var r=this._validateYear(t),n=t.month(),i=["\u4e00\u6708","\u4e8c\u6708","\u4e09\u6708","\u56db\u6708","\u4e94\u6708","\u516d\u6708","\u4e03\u6708","\u516b\u6708","\u4e5d\u6708","\u5341\u6708","\u5341\u4e00\u6708","\u5341\u4e8c\u6708"][this.toChineseMonth(r,n)-1];return this.isIntercalaryMonth(r,n)&&(i="\u95f0"+i),i},monthNamesShort:function(t){if("string"==typeof t){var e=t.match(u);return e?e[0]:""}var r=this._validateYear(t),n=t.month(),i=["\u4e00","\u4e8c","\u4e09","\u56db","\u4e94","\u516d","\u4e03","\u516b","\u4e5d","\u5341","\u5341\u4e00","\u5341\u4e8c"][this.toChineseMonth(r,n)-1];return this.isIntercalaryMonth(r,n)&&(i="\u95f0"+i),i},parseMonth:function(t,e){t=this._validateYear(t);var r,n=parseInt(e);if(isNaN(n))"\u95f0"===e[0]&&(r=!0,e=e.substring(1)),"\u6708"===e[e.length-1]&&(e=e.substring(0,e.length-1)),n=1+["\u4e00","\u4e8c","\u4e09","\u56db","\u4e94","\u516d","\u4e03","\u516b","\u4e5d","\u5341","\u5341\u4e00","\u5341\u4e8c"].indexOf(e);else{var i=e[e.length-1];r="i"===i||"I"===i}return this.toMonthIndex(t,n,r)},dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],digits:null,dateFormat:"yyyy/mm/dd",firstDay:1,isRTL:!1}},_validateYear:function(t,e){if(t.year&&(t=t.year()),"number"!=typeof t||t<1888||t>2111)throw e.replace(/\{0\}/,this.local.name);return t},toMonthIndex:function(t,e,r){var i=this.intercalaryMonth(t);if(r&&e!==i||e<1||e>12)throw n.local.invalidMonth.replace(/\{0\}/,this.local.name);return i?!r&&e<=i?e-1:e:e-1},toChineseMonth:function(t,e){t.year&&(e=(t=t.year()).month());var r=this.intercalaryMonth(t);if(e<0||e>(r?12:11))throw n.local.invalidMonth.replace(/\{0\}/,this.local.name);return r?e<r?e+1:e:e+1},intercalaryMonth:function(t){return t=this._validateYear(t),h[t-h[0]]>>13},isIntercalaryMonth:function(t,e){t.year&&(e=(t=t.year()).month());var r=this.intercalaryMonth(t);return!!r&&r===e},leapYear:function(t){return 0!==this.intercalaryMonth(t)},weekOfYear:function(t,e,r){var i,o=this._validateYear(t,n.local.invalidyear),s=f[o-f[0]],l=s>>9&4095,c=s>>5&15,u=31&s;(i=a.newDate(l,c,u)).add(4-(i.dayOfWeek()||7),"d");var h=this.toJD(t,e,r)-i.toJD();return 1+Math.floor(h/7)},monthsInYear:function(t){return this.leapYear(t)?13:12},daysInMonth:function(t,e){t.year&&(e=t.month(),t=t.year()),t=this._validateYear(t);var r=h[t-h[0]];if(e>(r>>13?12:11))throw n.local.invalidMonth.replace(/\{0\}/,this.local.name);return r&1<<12-e?30:29},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var i=this._validate(t,s,r,n.local.invalidDate);t=this._validateYear(i.year()),e=i.month(),r=i.day();var o=this.isIntercalaryMonth(t,e),s=this.toChineseMonth(t,e),l=function(t,e,r,n,i){var a,o,s;if("object"==typeof t)o=t,a=e||{};else{var l="number"==typeof t&&t>=1888&&t<=2111;if(!l)throw new Error("Lunar year outside range 1888-2111");var c="number"==typeof e&&e>=1&&e<=12;if(!c)throw new Error("Lunar month outside range 1 - 12");var u,p="number"==typeof r&&r>=1&&r<=30;if(!p)throw new Error("Lunar day outside range 1 - 30");"object"==typeof n?(u=!1,a=n):(u=!!n,a=i||{}),o={year:t,month:e,day:r,isIntercalary:u}}s=o.day-1;var d,g=h[o.year-h[0]],v=g>>13;d=v?o.month>v?o.month:o.isIntercalary?o.month:o.month-1:o.month-1;for(var m=0;m<d;m++){var y=g&1<<12-m?30:29;s+=y}var x=f[o.year-f[0]],b=new Date(x>>9&4095,(x>>5&15)-1,(31&x)+s);return a.year=b.getFullYear(),a.month=1+b.getMonth(),a.day=b.getDate(),a}(t,s,r,o);return a.toJD(l.year,l.month,l.day)},fromJD:function(t){var e=a.fromJD(t),r=function(t,e,r,n){var i,a;if("object"==typeof t)i=t,a=e||{};else{var o="number"==typeof t&&t>=1888&&t<=2111;if(!o)throw new Error("Solar year outside range 1888-2111");var s="number"==typeof e&&e>=1&&e<=12;if(!s)throw new Error("Solar month outside range 1 - 12");var l="number"==typeof r&&r>=1&&r<=31;if(!l)throw new Error("Solar day outside range 1 - 31");i={year:t,month:e,day:r},a=n||{}}var c=f[i.year-f[0]],u=i.year<<9|i.month<<5|i.day;a.year=u>=c?i.year:i.year-1,c=f[a.year-f[0]];var p,d=new Date(c>>9&4095,(c>>5&15)-1,31&c),g=new Date(i.year,i.month-1,i.day);p=Math.round((g-d)/864e5);var v,m=h[a.year-h[0]];for(v=0;v<13;v++){var y=m&1<<12-v?30:29;if(p<y)break;p-=y}var x=m>>13;!x||v<x?(a.isIntercalary=!1,a.month=1+v):v===x?(a.isIntercalary=!0,a.month=v):(a.isIntercalary=!1,a.month=v);return a.day=1+p,a}(e.year(),e.month(),e.day()),n=this.toMonthIndex(r.year,r.month,r.isIntercalary);return this.newDate(r.year,n,r.day)},fromString:function(t){var e=t.match(s),r=this._validateYear(+e[1]),n=+e[2],i=!!e[3],a=this.toMonthIndex(r,n,i),o=+e[4];return this.newDate(r,a,o)},add:function(t,e,r){var n=t.year(),i=t.month(),a=this.isIntercalaryMonth(n,i),s=this.toChineseMonth(n,i),l=Object.getPrototypeOf(o.prototype).add.call(this,t,e,r);if("y"===r){var c=l.year(),u=l.month(),h=this.isIntercalaryMonth(c,s),f=a&&h?this.toMonthIndex(c,s,!0):this.toMonthIndex(c,s,!1);f!==u&&l.month(f)}return l}});var s=/^\s*(-?\d\d\d\d|\d\d)[-\/](\d?\d)([iI]?)[-\/](\d?\d)/m,l=/^\d?\d[iI]?/m,c=/^\u95f0?\u5341?[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d]?\u6708/m,u=/^\u95f0?\u5341?[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d]?/m;n.calendars.chinese=o;var h=[1887,5780,5802,19157,2742,50359,1198,2646,46378,7466,3412,30122,5482,67949,2396,5294,43597,6732,6954,36181,2772,4954,18781,2396,54427,5274,6730,47781,5800,6868,21210,4790,59703,2350,5270,46667,3402,3496,38325,1388,4782,18735,2350,52374,6804,7498,44457,2906,1388,29294,4700,63789,6442,6804,56138,5802,2772,38235,1210,4698,22827,5418,63125,3476,5802,43701,2484,5302,27223,2646,70954,7466,3412,54698,5482,2412,38062,5294,2636,32038,6954,60245,2772,4826,43357,2394,5274,39501,6730,72357,5800,5844,53978,4790,2358,38039,5270,87627,3402,3496,54708,5484,4782,43311,2350,3222,27978,7498,68965,2904,5484,45677,4700,6444,39573,6804,6986,19285,2772,62811,1210,4698,47403,5418,5780,38570,5546,76469,2420,5302,51799,2646,5414,36501,3412,5546,18869,2412,54446,5276,6732,48422,6822,2900,28010,4826,92509,2394,5274,55883,6730,6820,47956,5812,2778,18779,2358,62615,5270,5450,46757,3492,5556,27318,4718,67887,2350,3222,52554,7498,3428,38252,5468,4700,31022,6444,64149,6804,6986,43861,2772,5338,35421,2650,70955,5418,5780,54954,5546,2740,38074,5302,2646,29991,3366,61011,3412,5546,43445,2412,5294,35406,6732,72998,6820,6996,52586,2778,2396,38045,5274,6698,23333,6820,64338,5812,2746,43355,2358,5270,39499,5450,79525,3492,5548],f=[1887,966732,967231,967733,968265,968766,969297,969798,970298,970829,971330,971830,972362,972863,973395,973896,974397,974928,975428,975929,976461,976962,977462,977994,978494,979026,979526,980026,980558,981059,981559,982091,982593,983124,983624,984124,984656,985157,985656,986189,986690,987191,987722,988222,988753,989254,989754,990286,990788,991288,991819,992319,992851,993352,993851,994383,994885,995385,995917,996418,996918,997450,997949,998481,998982,999483,1000014,1000515,1001016,1001548,1002047,1002578,1003080,1003580,1004111,1004613,1005113,1005645,1006146,1006645,1007177,1007678,1008209,1008710,1009211,1009743,1010243,1010743,1011275,1011775,1012306,1012807,1013308,1013840,1014341,1014841,1015373,1015874,1016404,1016905,1017405,1017937,1018438,1018939,1019471,1019972,1020471,1021002,1021503,1022035,1022535,1023036,1023568,1024069,1024568,1025100,1025601,1026102,1026633,1027133,1027666,1028167,1028666,1029198,1029699,1030199,1030730,1031231,1031763,1032264,1032764,1033296,1033797,1034297,1034828,1035329,1035830,1036362,1036861,1037393,1037894,1038394,1038925,1039427,1039927,1040459,1040959,1041491,1041992,1042492,1043023,1043524,1044024,1044556,1045057,1045558,1046090,1046590,1047121,1047622,1048122,1048654,1049154,1049655,1050187,1050689,1051219,1051720,1052220,1052751,1053252,1053752,1054284,1054786,1055285,1055817,1056317,1056849,1057349,1057850,1058382,1058883,1059383,1059915,1060415,1060947,1061447,1061947,1062479,1062981,1063480,1064012,1064514,1065014,1065545,1066045,1066577,1067078,1067578,1068110,1068611,1069112,1069642,1070142,1070674,1071175,1071675,1072207,1072709,1073209,1073740,1074241,1074741,1075273,1075773,1076305,1076807,1077308,1077839,1078340,1078840,1079372,1079871,1080403,1080904]},{"../main":552,"object-assign":443}],539:[function(t,e,r){var n=t("../main"),i=t("object-assign");function a(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}a.prototype=new n.baseCalendar,i(a.prototype,{name:"Coptic",jdEpoch:1825029.5,daysPerMonth:[30,30,30,30,30,30,30,30,30,30,30,30,5],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Coptic",epochs:["BAM","AM"],monthNames:["Thout","Paopi","Hathor","Koiak","Tobi","Meshir","Paremhat","Paremoude","Pashons","Paoni","Epip","Mesori","Pi Kogi Enavot"],monthNamesShort:["Tho","Pao","Hath","Koi","Tob","Mesh","Pat","Pad","Pash","Pao","Epi","Meso","PiK"],dayNames:["Tkyriaka","Pesnau","Pshoment","Peftoou","Ptiou","Psoou","Psabbaton"],dayNamesShort:["Tky","Pes","Psh","Pef","Pti","Pso","Psa"],dayNamesMin:["Tk","Pes","Psh","Pef","Pt","Pso","Psa"],digits:null,dateFormat:"dd/mm/yyyy",firstDay:0,isRTL:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear);return(t=e.year()+(e.year()<0?1:0))%4==3||t%4==-1},monthsInYear:function(t){return this._validate(t,this.minMonth,this.minDay,n.local.invalidYear||n.regionalOptions[""].invalidYear),13},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-n.dayOfWeek(),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,n.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(13===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);return(t=i.year())<0&&t++,i.day()+30*(i.month()-1)+365*(t-1)+Math.floor(t/4)+this.jdEpoch-1},fromJD:function(t){var e=Math.floor(t)+.5-this.jdEpoch,r=Math.floor((e-Math.floor((e+366)/1461))/365)+1;r<=0&&r--,e=Math.floor(t)+.5-this.newDate(r,1,1).toJD();var n=Math.floor(e/30)+1,i=e-30*(n-1)+1;return this.newDate(r,n,i)}}),n.calendars.coptic=a},{"../main":552,"object-assign":443}],540:[function(t,e,r){var n=t("../main"),i=t("object-assign");function a(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}a.prototype=new n.baseCalendar,i(a.prototype,{name:"Discworld",jdEpoch:1721425.5,daysPerMonth:[16,32,32,32,32,32,32,32,32,32,32,32,32],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Discworld",epochs:["BUC","UC"],monthNames:["Ick","Offle","February","March","April","May","June","Grune","August","Spune","Sektober","Ember","December"],monthNamesShort:["Ick","Off","Feb","Mar","Apr","May","Jun","Gru","Aug","Spu","Sek","Emb","Dec"],dayNames:["Sunday","Octeday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Oct","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Oc","Mo","Tu","We","Th","Fr","Sa"],digits:null,dateFormat:"yyyy/mm/dd",firstDay:2,isRTL:!1}},leapYear:function(t){return this._validate(t,this.minMonth,this.minDay,n.local.invalidYear),!1},monthsInYear:function(t){return this._validate(t,this.minMonth,this.minDay,n.local.invalidYear),13},daysInYear:function(t){return this._validate(t,this.minMonth,this.minDay,n.local.invalidYear),400},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-n.dayOfWeek(),"d"),Math.floor((n.dayOfYear()-1)/8)+1},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,n.local.invalidMonth);return this.daysPerMonth[r.month()-1]},daysInWeek:function(){return 8},dayOfWeek:function(t,e,r){return(this._validate(t,e,r,n.local.invalidDate).day()+1)%8},weekDay:function(t,e,r){var n=this.dayOfWeek(t,e,r);return n>=2&&n<=6},extraInfo:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);return{century:o[Math.floor((i.year()-1)/100)+1]||""}},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);return t=i.year()+(i.year()<0?1:0),e=i.month(),(r=i.day())+(e>1?16:0)+(e>2?32*(e-2):0)+400*(t-1)+this.jdEpoch-1},fromJD:function(t){t=Math.floor(t+.5)-Math.floor(this.jdEpoch)-1;var e=Math.floor(t/400)+1;t-=400*(e-1),t+=t>15?16:0;var r=Math.floor(t/32)+1,n=t-32*(r-1)+1;return this.newDate(e<=0?e-1:e,r,n)}});var o={20:"Fruitbat",21:"Anchovy"};n.calendars.discworld=a},{"../main":552,"object-assign":443}],541:[function(t,e,r){var n=t("../main"),i=t("object-assign");function a(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}a.prototype=new n.baseCalendar,i(a.prototype,{name:"Ethiopian",jdEpoch:1724220.5,daysPerMonth:[30,30,30,30,30,30,30,30,30,30,30,30,5],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Ethiopian",epochs:["BEE","EE"],monthNames:["Meskerem","Tikemet","Hidar","Tahesas","Tir","Yekatit","Megabit","Miazia","Genbot","Sene","Hamle","Nehase","Pagume"],monthNamesShort:["Mes","Tik","Hid","Tah","Tir","Yek","Meg","Mia","Gen","Sen","Ham","Neh","Pag"],dayNames:["Ehud","Segno","Maksegno","Irob","Hamus","Arb","Kidame"],dayNamesShort:["Ehu","Seg","Mak","Iro","Ham","Arb","Kid"],dayNamesMin:["Eh","Se","Ma","Ir","Ha","Ar","Ki"],digits:null,dateFormat:"dd/mm/yyyy",firstDay:0,isRTL:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear);return(t=e.year()+(e.year()<0?1:0))%4==3||t%4==-1},monthsInYear:function(t){return this._validate(t,this.minMonth,this.minDay,n.local.invalidYear||n.regionalOptions[""].invalidYear),13},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-n.dayOfWeek(),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,n.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(13===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);return(t=i.year())<0&&t++,i.day()+30*(i.month()-1)+365*(t-1)+Math.floor(t/4)+this.jdEpoch-1},fromJD:function(t){var e=Math.floor(t)+.5-this.jdEpoch,r=Math.floor((e-Math.floor((e+366)/1461))/365)+1;r<=0&&r--,e=Math.floor(t)+.5-this.newDate(r,1,1).toJD();var n=Math.floor(e/30)+1,i=e-30*(n-1)+1;return this.newDate(r,n,i)}}),n.calendars.ethiopian=a},{"../main":552,"object-assign":443}],542:[function(t,e,r){var n=t("../main"),i=t("object-assign");function a(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}function o(t,e){return t-e*Math.floor(t/e)}a.prototype=new n.baseCalendar,i(a.prototype,{name:"Hebrew",jdEpoch:347995.5,daysPerMonth:[30,29,30,29,30,29,30,29,30,29,30,29,29],hasYearZero:!1,minMonth:1,firstMonth:7,minDay:1,regionalOptions:{"":{name:"Hebrew",epochs:["BAM","AM"],monthNames:["Nisan","Iyar","Sivan","Tammuz","Av","Elul","Tishrei","Cheshvan","Kislev","Tevet","Shevat","Adar","Adar II"],monthNamesShort:["Nis","Iya","Siv","Tam","Av","Elu","Tis","Che","Kis","Tev","She","Ada","Ad2"],dayNames:["Yom Rishon","Yom Sheni","Yom Shlishi","Yom Revi'i","Yom Chamishi","Yom Shishi","Yom Shabbat"],dayNamesShort:["Ris","She","Shl","Rev","Cha","Shi","Sha"],dayNamesMin:["Ri","She","Shl","Re","Ch","Shi","Sha"],digits:null,dateFormat:"dd/mm/yyyy",firstDay:0,isRTL:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear);return this._leapYear(e.year())},_leapYear:function(t){return o(7*(t=t<0?t+1:t)+1,19)<7},monthsInYear:function(t){return this._validate(t,this.minMonth,this.minDay,n.local.invalidYear),this._leapYear(t.year?t.year():t)?13:12},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-n.dayOfWeek(),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInYear:function(t){return t=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear).year(),this.toJD(-1===t?1:t+1,7,1)-this.toJD(t,7,1)},daysInMonth:function(t,e){return t.year&&(e=t.month(),t=t.year()),this._validate(t,e,this.minDay,n.local.invalidMonth),12===e&&this.leapYear(t)?30:8===e&&5===o(this.daysInYear(t),10)?30:9===e&&3===o(this.daysInYear(t),10)?29:this.daysPerMonth[e-1]},weekDay:function(t,e,r){return 6!==this.dayOfWeek(t,e,r)},extraInfo:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);return{yearType:(this.leapYear(i)?"embolismic":"common")+" "+["deficient","regular","complete"][this.daysInYear(i)%10-3]}},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);t=i.year(),e=i.month(),r=i.day();var a=t<=0?t+1:t,o=this.jdEpoch+this._delay1(a)+this._delay2(a)+r+1;if(e<7){for(var s=7;s<=this.monthsInYear(t);s++)o+=this.daysInMonth(t,s);for(s=1;s<e;s++)o+=this.daysInMonth(t,s)}else for(s=7;s<e;s++)o+=this.daysInMonth(t,s);return o},_delay1:function(t){var e=Math.floor((235*t-234)/19),r=12084+13753*e,n=29*e+Math.floor(r/25920);return o(3*(n+1),7)<3&&n++,n},_delay2:function(t){var e=this._delay1(t-1),r=this._delay1(t);return this._delay1(t+1)-r==356?2:r-e==382?1:0},fromJD:function(t){t=Math.floor(t)+.5;for(var e=Math.floor(98496*(t-this.jdEpoch)/35975351)-1;t>=this.toJD(-1===e?1:e+1,7,1);)e++;for(var r=t<this.toJD(e,1,1)?7:1;t>this.toJD(e,r,this.daysInMonth(e,r));)r++;var n=t-this.toJD(e,r,1)+1;return this.newDate(e,r,n)}}),n.calendars.hebrew=a},{"../main":552,"object-assign":443}],543:[function(t,e,r){var n=t("../main"),i=t("object-assign");function a(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}a.prototype=new n.baseCalendar,i(a.prototype,{name:"Islamic",jdEpoch:1948439.5,daysPerMonth:[30,29,30,29,30,29,30,29,30,29,30,29],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Islamic",epochs:["BH","AH"],monthNames:["Muharram","Safar","Rabi' al-awwal","Rabi' al-thani","Jumada al-awwal","Jumada al-thani","Rajab","Sha'aban","Ramadan","Shawwal","Dhu al-Qi'dah","Dhu al-Hijjah"],monthNamesShort:["Muh","Saf","Rab1","Rab2","Jum1","Jum2","Raj","Sha'","Ram","Shaw","DhuQ","DhuH"],dayNames:["Yawm al-ahad","Yawm al-ithnayn","Yawm ath-thulaathaa'","Yawm al-arbi'aa'","Yawm al-kham\u012bs","Yawm al-jum'a","Yawm as-sabt"],dayNamesShort:["Aha","Ith","Thu","Arb","Kha","Jum","Sab"],dayNamesMin:["Ah","It","Th","Ar","Kh","Ju","Sa"],digits:null,dateFormat:"yyyy/mm/dd",firstDay:6,isRTL:!1}},leapYear:function(t){return(11*this._validate(t,this.minMonth,this.minDay,n.local.invalidYear).year()+14)%30<11},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-n.dayOfWeek(),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInYear:function(t){return this.leapYear(t)?355:354},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,n.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(12===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return 5!==this.dayOfWeek(t,e,r)},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);return t=i.year(),e=i.month(),t=t<=0?t+1:t,(r=i.day())+Math.ceil(29.5*(e-1))+354*(t-1)+Math.floor((3+11*t)/30)+this.jdEpoch-1},fromJD:function(t){t=Math.floor(t)+.5;var e=Math.floor((30*(t-this.jdEpoch)+10646)/10631);e=e<=0?e-1:e;var r=Math.min(12,Math.ceil((t-29-this.toJD(e,1,1))/29.5)+1),n=t-this.toJD(e,r,1)+1;return this.newDate(e,r,n)}}),n.calendars.islamic=a},{"../main":552,"object-assign":443}],544:[function(t,e,r){var n=t("../main"),i=t("object-assign");function a(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}a.prototype=new n.baseCalendar,i(a.prototype,{name:"Julian",jdEpoch:1721423.5,daysPerMonth:[31,28,31,30,31,30,31,31,30,31,30,31],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Julian",epochs:["BC","AD"],monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],digits:null,dateFormat:"mm/dd/yyyy",firstDay:0,isRTL:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear);return(t=e.year()<0?e.year()+1:e.year())%4==0},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(4-(n.dayOfWeek()||7),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,n.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(2===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);return t=i.year(),e=i.month(),r=i.day(),t<0&&t++,e<=2&&(t--,e+=12),Math.floor(365.25*(t+4716))+Math.floor(30.6001*(e+1))+r-1524.5},fromJD:function(t){var e=Math.floor(t+.5)+1524,r=Math.floor((e-122.1)/365.25),n=Math.floor(365.25*r),i=Math.floor((e-n)/30.6001),a=i-Math.floor(i<14?1:13),o=r-Math.floor(a>2?4716:4715),s=e-n-Math.floor(30.6001*i);return o<=0&&o--,this.newDate(o,a,s)}}),n.calendars.julian=a},{"../main":552,"object-assign":443}],545:[function(t,e,r){var n=t("../main"),i=t("object-assign");function a(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}function o(t,e){return t-e*Math.floor(t/e)}function s(t,e){return o(t-1,e)+1}a.prototype=new n.baseCalendar,i(a.prototype,{name:"Mayan",jdEpoch:584282.5,hasYearZero:!0,minMonth:0,firstMonth:0,minDay:0,regionalOptions:{"":{name:"Mayan",epochs:["",""],monthNames:["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17"],monthNamesShort:["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17"],dayNames:["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19"],dayNamesShort:["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19"],dayNamesMin:["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19"],digits:null,dateFormat:"YYYY.m.d",firstDay:0,isRTL:!1,haabMonths:["Pop","Uo","Zip","Zotz","Tzec","Xul","Yaxkin","Mol","Chen","Yax","Zac","Ceh","Mac","Kankin","Muan","Pax","Kayab","Cumku","Uayeb"],tzolkinMonths:["Imix","Ik","Akbal","Kan","Chicchan","Cimi","Manik","Lamat","Muluc","Oc","Chuen","Eb","Ben","Ix","Men","Cib","Caban","Etznab","Cauac","Ahau"]}},leapYear:function(t){return this._validate(t,this.minMonth,this.minDay,n.local.invalidYear),!1},formatYear:function(t){t=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear).year();var e=Math.floor(t/400);return t%=400,t+=t<0?400:0,e+"."+Math.floor(t/20)+"."+t%20},forYear:function(t){if((t=t.split(".")).length<3)throw"Invalid Mayan year";for(var e=0,r=0;r<t.length;r++){var n=parseInt(t[r],10);if(Math.abs(n)>19||r>0&&n<0)throw"Invalid Mayan year";e=20*e+n}return e},monthsInYear:function(t){return this._validate(t,this.minMonth,this.minDay,n.local.invalidYear),18},weekOfYear:function(t,e,r){return this._validate(t,e,r,n.local.invalidDate),0},daysInYear:function(t){return this._validate(t,this.minMonth,this.minDay,n.local.invalidYear),360},daysInMonth:function(t,e){return this._validate(t,e,this.minDay,n.local.invalidMonth),20},daysInWeek:function(){return 5},dayOfWeek:function(t,e,r){return this._validate(t,e,r,n.local.invalidDate).day()},weekDay:function(t,e,r){return this._validate(t,e,r,n.local.invalidDate),!0},extraInfo:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate).toJD(),a=this._toHaab(i),o=this._toTzolkin(i);return{haabMonthName:this.local.haabMonths[a[0]-1],haabMonth:a[0],haabDay:a[1],tzolkinDayName:this.local.tzolkinMonths[o[0]-1],tzolkinDay:o[0],tzolkinTrecena:o[1]}},_toHaab:function(t){var e=o((t-=this.jdEpoch)+8+340,365);return[Math.floor(e/20)+1,o(e,20)]},_toTzolkin:function(t){return[s((t-=this.jdEpoch)+20,20),s(t+4,13)]},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);return i.day()+20*i.month()+360*i.year()+this.jdEpoch},fromJD:function(t){t=Math.floor(t)+.5-this.jdEpoch;var e=Math.floor(t/360);t%=360,t+=t<0?360:0;var r=Math.floor(t/20),n=t%20;return this.newDate(e,r,n)}}),n.calendars.mayan=a},{"../main":552,"object-assign":443}],546:[function(t,e,r){var n=t("../main"),i=t("object-assign");function a(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}a.prototype=new n.baseCalendar;var o=n.instance("gregorian");i(a.prototype,{name:"Nanakshahi",jdEpoch:2257673.5,daysPerMonth:[31,31,31,31,31,30,30,30,30,30,30,30],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Nanakshahi",epochs:["BN","AN"],monthNames:["Chet","Vaisakh","Jeth","Harh","Sawan","Bhadon","Assu","Katak","Maghar","Poh","Magh","Phagun"],monthNamesShort:["Che","Vai","Jet","Har","Saw","Bha","Ass","Kat","Mgr","Poh","Mgh","Pha"],dayNames:["Somvaar","Mangalvar","Budhvaar","Veervaar","Shukarvaar","Sanicharvaar","Etvaar"],dayNamesShort:["Som","Mangal","Budh","Veer","Shukar","Sanichar","Et"],dayNamesMin:["So","Ma","Bu","Ve","Sh","Sa","Et"],digits:null,dateFormat:"dd-mm-yyyy",firstDay:0,isRTL:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear||n.regionalOptions[""].invalidYear);return o.leapYear(e.year()+(e.year()<1?1:0)+1469)},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(1-(n.dayOfWeek()||7),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,n.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(12===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidMonth);(t=i.year())<0&&t++;for(var a=i.day(),s=1;s<i.month();s++)a+=this.daysPerMonth[s-1];return a+o.toJD(t+1468,3,13)},fromJD:function(t){t=Math.floor(t+.5);for(var e=Math.floor((t-(this.jdEpoch-1))/366);t>=this.toJD(e+1,1,1);)e++;for(var r=t-Math.floor(this.toJD(e,1,1)+.5)+1,n=1;r>this.daysInMonth(e,n);)r-=this.daysInMonth(e,n),n++;return this.newDate(e,n,r)}}),n.calendars.nanakshahi=a},{"../main":552,"object-assign":443}],547:[function(t,e,r){var n=t("../main"),i=t("object-assign");function a(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}a.prototype=new n.baseCalendar,i(a.prototype,{name:"Nepali",jdEpoch:1700709.5,daysPerMonth:[31,31,32,32,31,30,30,29,30,29,30,30],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,daysPerYear:365,regionalOptions:{"":{name:"Nepali",epochs:["BBS","ABS"],monthNames:["Baisakh","Jestha","Ashadh","Shrawan","Bhadra","Ashwin","Kartik","Mangsir","Paush","Mangh","Falgun","Chaitra"],monthNamesShort:["Bai","Je","As","Shra","Bha","Ash","Kar","Mang","Pau","Ma","Fal","Chai"],dayNames:["Aaitabaar","Sombaar","Manglbaar","Budhabaar","Bihibaar","Shukrabaar","Shanibaar"],dayNamesShort:["Aaita","Som","Mangl","Budha","Bihi","Shukra","Shani"],dayNamesMin:["Aai","So","Man","Bu","Bi","Shu","Sha"],digits:null,dateFormat:"dd/mm/yyyy",firstDay:1,isRTL:!1}},leapYear:function(t){return this.daysInYear(t)!==this.daysPerYear},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-n.dayOfWeek(),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInYear:function(t){if(t=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear).year(),"undefined"==typeof this.NEPALI_CALENDAR_DATA[t])return this.daysPerYear;for(var e=0,r=this.minMonth;r<=12;r++)e+=this.NEPALI_CALENDAR_DATA[t][r];return e},daysInMonth:function(t,e){return t.year&&(e=t.month(),t=t.year()),this._validate(t,e,this.minDay,n.local.invalidMonth),"undefined"==typeof this.NEPALI_CALENDAR_DATA[t]?this.daysPerMonth[e-1]:this.NEPALI_CALENDAR_DATA[t][e]},weekDay:function(t,e,r){return 6!==this.dayOfWeek(t,e,r)},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);t=i.year(),e=i.month(),r=i.day();var a=n.instance(),o=0,s=e,l=t;this._createMissingCalendarData(t);var c=t-(s>9||9===s&&r>=this.NEPALI_CALENDAR_DATA[l][0]?56:57);for(9!==e&&(o=r,s--);9!==s;)s<=0&&(s=12,l--),o+=this.NEPALI_CALENDAR_DATA[l][s],s--;return 9===e?(o+=r-this.NEPALI_CALENDAR_DATA[l][0])<0&&(o+=a.daysInYear(c)):o+=this.NEPALI_CALENDAR_DATA[l][9]-this.NEPALI_CALENDAR_DATA[l][0],a.newDate(c,1,1).add(o,"d").toJD()},fromJD:function(t){var e=n.instance().fromJD(t),r=e.year(),i=e.dayOfYear(),a=r+56;this._createMissingCalendarData(a);for(var o=9,s=this.NEPALI_CALENDAR_DATA[a][0],l=this.NEPALI_CALENDAR_DATA[a][o]-s+1;i>l;)++o>12&&(o=1,a++),l+=this.NEPALI_CALENDAR_DATA[a][o];var c=this.NEPALI_CALENDAR_DATA[a][o]-(l-i);return this.newDate(a,o,c)},_createMissingCalendarData:function(t){var e=this.daysPerMonth.slice(0);e.unshift(17);for(var r=t-1;r<t+2;r++)"undefined"==typeof this.NEPALI_CALENDAR_DATA[r]&&(this.NEPALI_CALENDAR_DATA[r]=e)},NEPALI_CALENDAR_DATA:{1970:[18,31,31,32,31,31,31,30,29,30,29,30,30],1971:[18,31,31,32,31,32,30,30,29,30,29,30,30],1972:[17,31,32,31,32,31,30,30,30,29,29,30,30],1973:[19,30,32,31,32,31,30,30,30,29,30,29,31],1974:[19,31,31,32,30,31,31,30,29,30,29,30,30],1975:[18,31,31,32,32,30,31,30,29,30,29,30,30],1976:[17,31,32,31,32,31,30,30,30,29,29,30,31],1977:[18,31,32,31,32,31,31,29,30,29,30,29,31],1978:[18,31,31,32,31,31,31,30,29,30,29,30,30],1979:[18,31,31,32,32,31,30,30,29,30,29,30,30],1980:[17,31,32,31,32,31,30,30,30,29,29,30,31],1981:[18,31,31,31,32,31,31,29,30,30,29,30,30],1982:[18,31,31,32,31,31,31,30,29,30,29,30,30],1983:[18,31,31,32,32,31,30,30,29,30,29,30,30],1984:[17,31,32,31,32,31,30,30,30,29,29,30,31],1985:[18,31,31,31,32,31,31,29,30,30,29,30,30],1986:[18,31,31,32,31,31,31,30,29,30,29,30,30],1987:[18,31,32,31,32,31,30,30,29,30,29,30,30],1988:[17,31,32,31,32,31,30,30,30,29,29,30,31],1989:[18,31,31,31,32,31,31,30,29,30,29,30,30],1990:[18,31,31,32,31,31,31,30,29,30,29,30,30],1991:[18,31,32,31,32,31,30,30,29,30,29,30,30],1992:[17,31,32,31,32,31,30,30,30,29,30,29,31],1993:[18,31,31,31,32,31,31,30,29,30,29,30,30],1994:[18,31,31,32,31,31,31,30,29,30,29,30,30],1995:[17,31,32,31,32,31,30,30,30,29,29,30,30],1996:[17,31,32,31,32,31,30,30,30,29,30,29,31],1997:[18,31,31,32,31,31,31,30,29,30,29,30,30],1998:[18,31,31,32,31,31,31,30,29,30,29,30,30],1999:[17,31,32,31,32,31,30,30,30,29,29,30,31],2000:[17,30,32,31,32,31,30,30,30,29,30,29,31],2001:[18,31,31,32,31,31,31,30,29,30,29,30,30],2002:[18,31,31,32,32,31,30,30,29,30,29,30,30],2003:[17,31,32,31,32,31,30,30,30,29,29,30,31],2004:[17,30,32,31,32,31,30,30,30,29,30,29,31],2005:[18,31,31,32,31,31,31,30,29,30,29,30,30],2006:[18,31,31,32,32,31,30,30,29,30,29,30,30],2007:[17,31,32,31,32,31,30,30,30,29,29,30,31],2008:[17,31,31,31,32,31,31,29,30,30,29,29,31],2009:[18,31,31,32,31,31,31,30,29,30,29,30,30],2010:[18,31,31,32,32,31,30,30,29,30,29,30,30],2011:[17,31,32,31,32,31,30,30,30,29,29,30,31],2012:[17,31,31,31,32,31,31,29,30,30,29,30,30],2013:[18,31,31,32,31,31,31,30,29,30,29,30,30],2014:[18,31,31,32,32,31,30,30,29,30,29,30,30],2015:[17,31,32,31,32,31,30,30,30,29,29,30,31],2016:[17,31,31,31,32,31,31,29,30,30,29,30,30],2017:[18,31,31,32,31,31,31,30,29,30,29,30,30],2018:[18,31,32,31,32,31,30,30,29,30,29,30,30],2019:[17,31,32,31,32,31,30,30,30,29,30,29,31],2020:[17,31,31,31,32,31,31,30,29,30,29,30,30],2021:[18,31,31,32,31,31,31,30,29,30,29,30,30],2022:[17,31,32,31,32,31,30,30,30,29,29,30,30],2023:[17,31,32,31,32,31,30,30,30,29,30,29,31],2024:[17,31,31,31,32,31,31,30,29,30,29,30,30],2025:[18,31,31,32,31,31,31,30,29,30,29,30,30],2026:[17,31,32,31,32,31,30,30,30,29,29,30,31],2027:[17,30,32,31,32,31,30,30,30,29,30,29,31],2028:[17,31,31,32,31,31,31,30,29,30,29,30,30],2029:[18,31,31,32,31,32,30,30,29,30,29,30,30],2030:[17,31,32,31,32,31,30,30,30,30,30,30,31],2031:[17,31,32,31,32,31,31,31,31,31,31,31,31],2032:[17,32,32,32,32,32,32,32,32,32,32,32,32],2033:[18,31,31,32,32,31,30,30,29,30,29,30,30],2034:[17,31,32,31,32,31,30,30,30,29,29,30,31],2035:[17,30,32,31,32,31,31,29,30,30,29,29,31],2036:[17,31,31,32,31,31,31,30,29,30,29,30,30],2037:[18,31,31,32,32,31,30,30,29,30,29,30,30],2038:[17,31,32,31,32,31,30,30,30,29,29,30,31],2039:[17,31,31,31,32,31,31,29,30,30,29,30,30],2040:[17,31,31,32,31,31,31,30,29,30,29,30,30],2041:[18,31,31,32,32,31,30,30,29,30,29,30,30],2042:[17,31,32,31,32,31,30,30,30,29,29,30,31],2043:[17,31,31,31,32,31,31,29,30,30,29,30,30],2044:[17,31,31,32,31,31,31,30,29,30,29,30,30],2045:[18,31,32,31,32,31,30,30,29,30,29,30,30],2046:[17,31,32,31,32,31,30,30,30,29,29,30,31],2047:[17,31,31,31,32,31,31,30,29,30,29,30,30],2048:[17,31,31,32,31,31,31,30,29,30,29,30,30],2049:[17,31,32,31,32,31,30,30,30,29,29,30,30],2050:[17,31,32,31,32,31,30,30,30,29,30,29,31],2051:[17,31,31,31,32,31,31,30,29,30,29,30,30],2052:[17,31,31,32,31,31,31,30,29,30,29,30,30],2053:[17,31,32,31,32,31,30,30,30,29,29,30,30],2054:[17,31,32,31,32,31,30,30,30,29,30,29,31],2055:[17,31,31,32,31,31,31,30,29,30,30,29,30],2056:[17,31,31,32,31,32,30,30,29,30,29,30,30],2057:[17,31,32,31,32,31,30,30,30,29,29,30,31],2058:[17,30,32,31,32,31,30,30,30,29,30,29,31],2059:[17,31,31,32,31,31,31,30,29,30,29,30,30],2060:[17,31,31,32,32,31,30,30,29,30,29,30,30],2061:[17,31,32,31,32,31,30,30,30,29,29,30,31],2062:[17,30,32,31,32,31,31,29,30,29,30,29,31],2063:[17,31,31,32,31,31,31,30,29,30,29,30,30],2064:[17,31,31,32,32,31,30,30,29,30,29,30,30],2065:[17,31,32,31,32,31,30,30,30,29,29,30,31],2066:[17,31,31,31,32,31,31,29,30,30,29,29,31],2067:[17,31,31,32,31,31,31,30,29,30,29,30,30],2068:[17,31,31,32,32,31,30,30,29,30,29,30,30],2069:[17,31,32,31,32,31,30,30,30,29,29,30,31],2070:[17,31,31,31,32,31,31,29,30,30,29,30,30],2071:[17,31,31,32,31,31,31,30,29,30,29,30,30],2072:[17,31,32,31,32,31,30,30,29,30,29,30,30],2073:[17,31,32,31,32,31,30,30,30,29,29,30,31],2074:[17,31,31,31,32,31,31,30,29,30,29,30,30],2075:[17,31,31,32,31,31,31,30,29,30,29,30,30],2076:[16,31,32,31,32,31,30,30,30,29,29,30,30],2077:[17,31,32,31,32,31,30,30,30,29,30,29,31],2078:[17,31,31,31,32,31,31,30,29,30,29,30,30],2079:[17,31,31,32,31,31,31,30,29,30,29,30,30],2080:[16,31,32,31,32,31,30,30,30,29,29,30,30],2081:[17,31,31,32,32,31,30,30,30,29,30,30,30],2082:[17,31,32,31,32,31,30,30,30,29,30,30,30],2083:[17,31,31,32,31,31,30,30,30,29,30,30,30],2084:[17,31,31,32,31,31,30,30,30,29,30,30,30],2085:[17,31,32,31,32,31,31,30,30,29,30,30,30],2086:[17,31,32,31,32,31,30,30,30,29,30,30,30],2087:[16,31,31,32,31,31,31,30,30,29,30,30,30],2088:[16,30,31,32,32,30,31,30,30,29,30,30,30],2089:[17,31,32,31,32,31,30,30,30,29,30,30,30],2090:[17,31,32,31,32,31,30,30,30,29,30,30,30],2091:[16,31,31,32,31,31,31,30,30,29,30,30,30],2092:[16,31,31,32,32,31,30,30,30,29,30,30,30],2093:[17,31,32,31,32,31,30,30,30,29,30,30,30],2094:[17,31,31,32,31,31,30,30,30,29,30,30,30],2095:[17,31,31,32,31,31,31,30,29,30,30,30,30],2096:[17,30,31,32,32,31,30,30,29,30,29,30,30],2097:[17,31,32,31,32,31,30,30,30,29,30,30,30],2098:[17,31,31,32,31,31,31,29,30,29,30,30,31],2099:[17,31,31,32,31,31,31,30,29,29,30,30,30],2100:[17,31,32,31,32,30,31,30,29,30,29,30,30]}}),n.calendars.nepali=a},{"../main":552,"object-assign":443}],548:[function(t,e,r){var n=t("../main"),i=t("object-assign");function a(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}function o(t,e){return t-e*Math.floor(t/e)}a.prototype=new n.baseCalendar,i(a.prototype,{name:"Persian",jdEpoch:1948320.5,daysPerMonth:[31,31,31,31,31,31,30,30,30,30,30,29],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Persian",epochs:["BP","AP"],monthNames:["Farvardin","Ordibehesht","Khordad","Tir","Mordad","Shahrivar","Mehr","Aban","Azar","Day","Bahman","Esfand"],monthNamesShort:["Far","Ord","Kho","Tir","Mor","Sha","Meh","Aba","Aza","Day","Bah","Esf"],dayNames:["Yekshambe","Doshambe","Seshambe","Ch\xe6harshambe","Panjshambe","Jom'e","Shambe"],dayNamesShort:["Yek","Do","Se","Ch\xe6","Panj","Jom","Sha"],dayNamesMin:["Ye","Do","Se","Ch","Pa","Jo","Sh"],digits:null,dateFormat:"yyyy/mm/dd",firstDay:6,isRTL:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear);return 682*((e.year()-(e.year()>0?474:473))%2820+474+38)%2816<682},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-(n.dayOfWeek()+1)%7,"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,n.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(12===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return 5!==this.dayOfWeek(t,e,r)},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);t=i.year(),e=i.month(),r=i.day();var a=t-(t>=0?474:473),s=474+o(a,2820);return r+(e<=7?31*(e-1):30*(e-1)+6)+Math.floor((682*s-110)/2816)+365*(s-1)+1029983*Math.floor(a/2820)+this.jdEpoch-1},fromJD:function(t){var e=(t=Math.floor(t)+.5)-this.toJD(475,1,1),r=Math.floor(e/1029983),n=o(e,1029983),i=2820;if(1029982!==n){var a=Math.floor(n/366),s=o(n,366);i=Math.floor((2134*a+2816*s+2815)/1028522)+a+1}var l=i+2820*r+474;l=l<=0?l-1:l;var c=t-this.toJD(l,1,1)+1,u=c<=186?Math.ceil(c/31):Math.ceil((c-6)/30),h=t-this.toJD(l,u,1)+1;return this.newDate(l,u,h)}}),n.calendars.persian=a,n.calendars.jalali=a},{"../main":552,"object-assign":443}],549:[function(t,e,r){var n=t("../main"),i=t("object-assign"),a=n.instance();function o(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}o.prototype=new n.baseCalendar,i(o.prototype,{name:"Taiwan",jdEpoch:2419402.5,yearsOffset:1911,daysPerMonth:[31,28,31,30,31,30,31,31,30,31,30,31],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Taiwan",epochs:["BROC","ROC"],monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],digits:null,dateFormat:"yyyy/mm/dd",firstDay:1,isRTL:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear);t=this._t2gYear(e.year());return a.leapYear(t)},weekOfYear:function(t,e,r){var i=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear);t=this._t2gYear(i.year());return a.weekOfYear(t,i.month(),i.day())},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,n.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(2===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);t=this._t2gYear(i.year());return a.toJD(t,i.month(),i.day())},fromJD:function(t){var e=a.fromJD(t),r=this._g2tYear(e.year());return this.newDate(r,e.month(),e.day())},_t2gYear:function(t){return t+this.yearsOffset+(t>=-this.yearsOffset&&t<=-1?1:0)},_g2tYear:function(t){return t-this.yearsOffset-(t>=1&&t<=this.yearsOffset?1:0)}}),n.calendars.taiwan=o},{"../main":552,"object-assign":443}],550:[function(t,e,r){var n=t("../main"),i=t("object-assign"),a=n.instance();function o(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}o.prototype=new n.baseCalendar,i(o.prototype,{name:"Thai",jdEpoch:1523098.5,yearsOffset:543,daysPerMonth:[31,28,31,30,31,30,31,31,30,31,30,31],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Thai",epochs:["BBE","BE"],monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],digits:null,dateFormat:"dd/mm/yyyy",firstDay:0,isRTL:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear);t=this._t2gYear(e.year());return a.leapYear(t)},weekOfYear:function(t,e,r){var i=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear);t=this._t2gYear(i.year());return a.weekOfYear(t,i.month(),i.day())},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,n.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(2===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);t=this._t2gYear(i.year());return a.toJD(t,i.month(),i.day())},fromJD:function(t){var e=a.fromJD(t),r=this._g2tYear(e.year());return this.newDate(r,e.month(),e.day())},_t2gYear:function(t){return t-this.yearsOffset-(t>=1&&t<=this.yearsOffset?1:0)},_g2tYear:function(t){return t+this.yearsOffset+(t>=-this.yearsOffset&&t<=-1?1:0)}}),n.calendars.thai=o},{"../main":552,"object-assign":443}],551:[function(t,e,r){var n=t("../main"),i=t("object-assign");function a(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}a.prototype=new n.baseCalendar,i(a.prototype,{name:"UmmAlQura",hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Umm al-Qura",epochs:["BH","AH"],monthNames:["Al-Muharram","Safar","Rabi' al-awwal","Rabi' Al-Thani","Jumada Al-Awwal","Jumada Al-Thani","Rajab","Sha'aban","Ramadan","Shawwal","Dhu al-Qi'dah","Dhu al-Hijjah"],monthNamesShort:["Muh","Saf","Rab1","Rab2","Jum1","Jum2","Raj","Sha'","Ram","Shaw","DhuQ","DhuH"],dayNames:["Yawm al-Ahad","Yawm al-Ithnain","Yawm al-Thal\u0101th\u0101\u2019","Yawm al-Arba\u2018\u0101\u2019","Yawm al-Kham\u012bs","Yawm al-Jum\u2018a","Yawm al-Sabt"],dayNamesMin:["Ah","Ith","Th","Ar","Kh","Ju","Sa"],digits:null,dateFormat:"yyyy/mm/dd",firstDay:6,isRTL:!0}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear);return 355===this.daysInYear(e.year())},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-n.dayOfWeek(),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInYear:function(t){for(var e=0,r=1;r<=12;r++)e+=this.daysInMonth(t,r);return e},daysInMonth:function(t,e){for(var r=this._validate(t,e,this.minDay,n.local.invalidMonth).toJD()-24e5+.5,i=0,a=0;a<o.length;a++){if(o[a]>r)return o[i]-o[i-1];i++}return 30},weekDay:function(t,e,r){return 5!==this.dayOfWeek(t,e,r)},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate),a=12*(i.year()-1)+i.month()-15292;return i.day()+o[a-1]-1+24e5-.5},fromJD:function(t){for(var e=t-24e5+.5,r=0,n=0;n<o.length&&!(o[n]>e);n++)r++;var i=r+15292,a=Math.floor((i-1)/12),s=a+1,l=i-12*a,c=e-o[r-1]+1;return this.newDate(s,l,c)},isValid:function(t,e,r){var i=n.baseCalendar.prototype.isValid.apply(this,arguments);return i&&(i=(t=null!=t.year?t.year:t)>=1276&&t<=1500),i},_validate:function(t,e,r,i){var a=n.baseCalendar.prototype._validate.apply(this,arguments);if(a.year<1276||a.year>1500)throw i.replace(/\{0\}/,this.local.name);return a}}),n.calendars.ummalqura=a;var o=[20,50,79,109,138,168,197,227,256,286,315,345,374,404,433,463,492,522,551,581,611,641,670,700,729,759,788,818,847,877,906,936,965,995,1024,1054,1083,1113,1142,1172,1201,1231,1260,1290,1320,1350,1379,1409,1438,1468,1497,1527,1556,1586,1615,1645,1674,1704,1733,1763,1792,1822,1851,1881,1910,1940,1969,1999,2028,2058,2087,2117,2146,2176,2205,2235,2264,2294,2323,2353,2383,2413,2442,2472,2501,2531,2560,2590,2619,2649,2678,2708,2737,2767,2796,2826,2855,2885,2914,2944,2973,3003,3032,3062,3091,3121,3150,3180,3209,3239,3268,3298,3327,3357,3386,3416,3446,3476,3505,3535,3564,3594,3623,3653,3682,3712,3741,3771,3800,3830,3859,3889,3918,3948,3977,4007,4036,4066,4095,4125,4155,4185,4214,4244,4273,4303,4332,4362,4391,4421,4450,4480,4509,4539,4568,4598,4627,4657,4686,4716,4745,4775,4804,4834,4863,4893,4922,4952,4981,5011,5040,5070,5099,5129,5158,5188,5218,5248,5277,5307,5336,5366,5395,5425,5454,5484,5513,5543,5572,5602,5631,5661,5690,5720,5749,5779,5808,5838,5867,5897,5926,5956,5985,6015,6044,6074,6103,6133,6162,6192,6221,6251,6281,6311,6340,6370,6399,6429,6458,6488,6517,6547,6576,6606,6635,6665,6694,6724,6753,6783,6812,6842,6871,6901,6930,6960,6989,7019,7048,7078,7107,7137,7166,7196,7225,7255,7284,7314,7344,7374,7403,7433,7462,7492,7521,7551,7580,7610,7639,7669,7698,7728,7757,7787,7816,7846,7875,7905,7934,7964,7993,8023,8053,8083,8112,8142,8171,8201,8230,8260,8289,8319,8348,8378,8407,8437,8466,8496,8525,8555,8584,8614,8643,8673,8702,8732,8761,8791,8821,8850,8880,8909,8938,8968,8997,9027,9056,9086,9115,9145,9175,9205,9234,9264,9293,9322,9352,9381,9410,9440,9470,9499,9529,9559,9589,9618,9648,9677,9706,9736,9765,9794,9824,9853,9883,9913,9943,9972,10002,10032,10061,10090,10120,10149,10178,10208,10237,10267,10297,10326,10356,10386,10415,10445,10474,10504,10533,10562,10592,10621,10651,10680,10710,10740,10770,10799,10829,10858,10888,10917,10947,10976,11005,11035,11064,11094,11124,11153,11183,11213,11242,11272,11301,11331,11360,11389,11419,11448,11478,11507,11537,11567,11596,11626,11655,11685,11715,11744,11774,11803,11832,11862,11891,11921,11950,11980,12010,12039,12069,12099,12128,12158,12187,12216,12246,12275,12304,12334,12364,12393,12423,12453,12483,12512,12542,12571,12600,12630,12659,12688,12718,12747,12777,12807,12837,12866,12896,12926,12955,12984,13014,13043,13072,13102,13131,13161,13191,13220,13250,13280,13310,13339,13368,13398,13427,13456,13486,13515,13545,13574,13604,13634,13664,13693,13723,13752,13782,13811,13840,13870,13899,13929,13958,13988,14018,14047,14077,14107,14136,14166,14195,14224,14254,14283,14313,14342,14372,14401,14431,14461,14490,14520,14550,14579,14609,14638,14667,14697,14726,14756,14785,14815,14844,14874,14904,14933,14963,14993,15021,15051,15081,15110,15140,15169,15199,15228,15258,15287,15317,15347,15377,15406,15436,15465,15494,15524,15553,15582,15612,15641,15671,15701,15731,15760,15790,15820,15849,15878,15908,15937,15966,15996,16025,16055,16085,16114,16144,16174,16204,16233,16262,16292,16321,16350,16380,16409,16439,16468,16498,16528,16558,16587,16617,16646,16676,16705,16734,16764,16793,16823,16852,16882,16912,16941,16971,17001,17030,17060,17089,17118,17148,17177,17207,17236,17266,17295,17325,17355,17384,17414,17444,17473,17502,17532,17561,17591,17620,17650,17679,17709,17738,17768,17798,17827,17857,17886,17916,17945,17975,18004,18034,18063,18093,18122,18152,18181,18211,18241,18270,18300,18330,18359,18388,18418,18447,18476,18506,18535,18565,18595,18625,18654,18684,18714,18743,18772,18802,18831,18860,18890,18919,18949,18979,19008,19038,19068,19098,19127,19156,19186,19215,19244,19274,19303,19333,19362,19392,19422,19452,19481,19511,19540,19570,19599,19628,19658,19687,19717,19746,19776,19806,19836,19865,19895,19924,19954,19983,20012,20042,20071,20101,20130,20160,20190,20219,20249,20279,20308,20338,20367,20396,20426,20455,20485,20514,20544,20573,20603,20633,20662,20692,20721,20751,20780,20810,20839,20869,20898,20928,20957,20987,21016,21046,21076,21105,21135,21164,21194,21223,21253,21282,21312,21341,21371,21400,21430,21459,21489,21519,21548,21578,21607,21637,21666,21696,21725,21754,21784,21813,21843,21873,21902,21932,21962,21991,22021,22050,22080,22109,22138,22168,22197,22227,22256,22286,22316,22346,22375,22405,22434,22464,22493,22522,22552,22581,22611,22640,22670,22700,22730,22759,22789,22818,22848,22877,22906,22936,22965,22994,23024,23054,23083,23113,23143,23173,23202,23232,23261,23290,23320,23349,23379,23408,23438,23467,23497,23527,23556,23586,23616,23645,23674,23704,23733,23763,23792,23822,23851,23881,23910,23940,23970,23999,24029,24058,24088,24117,24147,24176,24206,24235,24265,24294,24324,24353,24383,24413,24442,24472,24501,24531,24560,24590,24619,24648,24678,24707,24737,24767,24796,24826,24856,24885,24915,24944,24974,25003,25032,25062,25091,25121,25150,25180,25210,25240,25269,25299,25328,25358,25387,25416,25446,25475,25505,25534,25564,25594,25624,25653,25683,25712,25742,25771,25800,25830,25859,25888,25918,25948,25977,26007,26037,26067,26096,26126,26155,26184,26214,26243,26272,26302,26332,26361,26391,26421,26451,26480,26510,26539,26568,26598,26627,26656,26686,26715,26745,26775,26805,26834,26864,26893,26923,26952,26982,27011,27041,27070,27099,27129,27159,27188,27218,27248,27277,27307,27336,27366,27395,27425,27454,27484,27513,27542,27572,27602,27631,27661,27691,27720,27750,27779,27809,27838,27868,27897,27926,27956,27985,28015,28045,28074,28104,28134,28163,28193,28222,28252,28281,28310,28340,28369,28399,28428,28458,28488,28517,28547,28577,28607,28636,28665,28695,28724,28754,28783,28813,28843,28872,28901,28931,28960,28990,29019,29049,29078,29108,29137,29167,29196,29226,29255,29285,29315,29345,29375,29404,29434,29463,29492,29522,29551,29580,29610,29640,29669,29699,29729,29759,29788,29818,29847,29876,29906,29935,29964,29994,30023,30053,30082,30112,30141,30171,30200,30230,30259,30289,30318,30348,30378,30408,30437,30467,30496,30526,30555,30585,30614,30644,30673,30703,30732,30762,30791,30821,30850,30880,30909,30939,30968,30998,31027,31057,31086,31116,31145,31175,31204,31234,31263,31293,31322,31352,31381,31411,31441,31471,31500,31530,31559,31589,31618,31648,31676,31706,31736,31766,31795,31825,31854,31884,31913,31943,31972,32002,32031,32061,32090,32120,32150,32180,32209,32239,32268,32298,32327,32357,32386,32416,32445,32475,32504,32534,32563,32593,32622,32652,32681,32711,32740,32770,32799,32829,32858,32888,32917,32947,32976,33006,33035,33065,33094,33124,33153,33183,33213,33243,33272,33302,33331,33361,33390,33420,33450,33479,33509,33539,33568,33598,33627,33657,33686,33716,33745,33775,33804,33834,33863,33893,33922,33952,33981,34011,34040,34069,34099,34128,34158,34187,34217,34247,34277,34306,34336,34365,34395,34424,34454,34483,34512,34542,34571,34601,34631,34660,34690,34719,34749,34778,34808,34837,34867,34896,34926,34955,34985,35015,35044,35074,35103,35133,35162,35192,35222,35251,35280,35310,35340,35370,35399,35429,35458,35488,35517,35547,35576,35605,35635,35665,35694,35723,35753,35782,35811,35841,35871,35901,35930,35960,35989,36019,36048,36078,36107,36136,36166,36195,36225,36254,36284,36314,36343,36373,36403,36433,36462,36492,36521,36551,36580,36610,36639,36669,36698,36728,36757,36786,36816,36845,36875,36904,36934,36963,36993,37022,37052,37081,37111,37141,37170,37200,37229,37259,37288,37318,37347,37377,37406,37436,37465,37495,37524,37554,37584,37613,37643,37672,37701,37731,37760,37790,37819,37849,37878,37908,37938,37967,37997,38027,38056,38085,38115,38144,38174,38203,38233,38262,38292,38322,38351,38381,38410,38440,38469,38499,38528,38558,38587,38617,38646,38676,38705,38735,38764,38794,38823,38853,38882,38912,38941,38971,39001,39030,39059,39089,39118,39148,39178,39208,39237,39267,39297,39326,39355,39385,39414,39444,39473,39503,39532,39562,39592,39621,39650,39680,39709,39739,39768,39798,39827,39857,39886,39916,39946,39975,40005,40035,40064,40094,40123,40153,40182,40212,40241,40271,40300,40330,40359,40389,40418,40448,40477,40507,40536,40566,40595,40625,40655,40685,40714,40744,40773,40803,40832,40862,40892,40921,40951,40980,41009,41039,41068,41098,41127,41157,41186,41216,41245,41275,41304,41334,41364,41393,41422,41452,41481,41511,41540,41570,41599,41629,41658,41688,41718,41748,41777,41807,41836,41865,41894,41924,41953,41983,42012,42042,42072,42102,42131,42161,42190,42220,42249,42279,42308,42337,42367,42397,42426,42456,42485,42515,42545,42574,42604,42633,42662,42692,42721,42751,42780,42810,42839,42869,42899,42929,42958,42988,43017,43046,43076,43105,43135,43164,43194,43223,43253,43283,43312,43342,43371,43401,43430,43460,43489,43519,43548,43578,43607,43637,43666,43696,43726,43755,43785,43814,43844,43873,43903,43932,43962,43991,44021,44050,44080,44109,44139,44169,44198,44228,44258,44287,44317,44346,44375,44405,44434,44464,44493,44523,44553,44582,44612,44641,44671,44700,44730,44759,44788,44818,44847,44877,44906,44936,44966,44996,45025,45055,45084,45114,45143,45172,45202,45231,45261,45290,45320,45350,45380,45409,45439,45468,45498,45527,45556,45586,45615,45644,45674,45704,45733,45763,45793,45823,45852,45882,45911,45940,45970,45999,46028,46058,46088,46117,46147,46177,46206,46236,46265,46295,46324,46354,46383,46413,46442,46472,46501,46531,46560,46590,46620,46649,46679,46708,46738,46767,46797,46826,46856,46885,46915,46944,46974,47003,47033,47063,47092,47122,47151,47181,47210,47240,47269,47298,47328,47357,47387,47417,47446,47476,47506,47535,47565,47594,47624,47653,47682,47712,47741,47771,47800,47830,47860,47890,47919,47949,47978,48008,48037,48066,48096,48125,48155,48184,48214,48244,48273,48303,48333,48362,48392,48421,48450,48480,48509,48538,48568,48598,48627,48657,48687,48717,48746,48776,48805,48834,48864,48893,48922,48952,48982,49011,49041,49071,49100,49130,49160,49189,49218,49248,49277,49306,49336,49365,49395,49425,49455,49484,49514,49543,49573,49602,49632,49661,49690,49720,49749,49779,49809,49838,49868,49898,49927,49957,49986,50016,50045,50075,50104,50133,50163,50192,50222,50252,50281,50311,50340,50370,50400,50429,50459,50488,50518,50547,50576,50606,50635,50665,50694,50724,50754,50784,50813,50843,50872,50902,50931,50960,50990,51019,51049,51078,51108,51138,51167,51197,51227,51256,51286,51315,51345,51374,51403,51433,51462,51492,51522,51552,51582,51611,51641,51670,51699,51729,51758,51787,51816,51846,51876,51906,51936,51965,51995,52025,52054,52083,52113,52142,52171,52200,52230,52260,52290,52319,52349,52379,52408,52438,52467,52497,52526,52555,52585,52614,52644,52673,52703,52733,52762,52792,52822,52851,52881,52910,52939,52969,52998,53028,53057,53087,53116,53146,53176,53205,53235,53264,53294,53324,53353,53383,53412,53441,53471,53500,53530,53559,53589,53619,53648,53678,53708,53737,53767,53796,53825,53855,53884,53913,53943,53973,54003,54032,54062,54092,54121,54151,54180,54209,54239,54268,54297,54327,54357,54387,54416,54446,54476,54505,54535,54564,54593,54623,54652,54681,54711,54741,54770,54800,54830,54859,54889,54919,54948,54977,55007,55036,55066,55095,55125,55154,55184,55213,55243,55273,55302,55332,55361,55391,55420,55450,55479,55508,55538,55567,55597,55627,55657,55686,55716,55745,55775,55804,55834,55863,55892,55922,55951,55981,56011,56040,56070,56100,56129,56159,56188,56218,56247,56276,56306,56335,56365,56394,56424,56454,56483,56513,56543,56572,56601,56631,56660,56690,56719,56749,56778,56808,56837,56867,56897,56926,56956,56985,57015,57044,57074,57103,57133,57162,57192,57221,57251,57280,57310,57340,57369,57399,57429,57458,57487,57517,57546,57576,57605,57634,57664,57694,57723,57753,57783,57813,57842,57871,57901,57930,57959,57989,58018,58048,58077,58107,58137,58167,58196,58226,58255,58285,58314,58343,58373,58402,58432,58461,58491,58521,58551,58580,58610,58639,58669,58698,58727,58757,58786,58816,58845,58875,58905,58934,58964,58994,59023,59053,59082,59111,59141,59170,59200,59229,59259,59288,59318,59348,59377,59407,59436,59466,59495,59525,59554,59584,59613,59643,59672,59702,59731,59761,59791,59820,59850,59879,59909,59939,59968,59997,60027,60056,60086,60115,60145,60174,60204,60234,60264,60293,60323,60352,60381,60411,60440,60469,60499,60528,60558,60588,60618,60648,60677,60707,60736,60765,60795,60824,60853,60883,60912,60942,60972,61002,61031,61061,61090,61120,61149,61179,61208,61237,61267,61296,61326,61356,61385,61415,61445,61474,61504,61533,61563,61592,61621,61651,61680,61710,61739,61769,61799,61828,61858,61888,61917,61947,61976,62006,62035,62064,62094,62123,62153,62182,62212,62242,62271,62301,62331,62360,62390,62419,62448,62478,62507,62537,62566,62596,62625,62655,62685,62715,62744,62774,62803,62832,62862,62891,62921,62950,62980,63009,63039,63069,63099,63128,63157,63187,63216,63246,63275,63305,63334,63363,63393,63423,63453,63482,63512,63541,63571,63600,63630,63659,63689,63718,63747,63777,63807,63836,63866,63895,63925,63955,63984,64014,64043,64073,64102,64131,64161,64190,64220,64249,64279,64309,64339,64368,64398,64427,64457,64486,64515,64545,64574,64603,64633,64663,64692,64722,64752,64782,64811,64841,64870,64899,64929,64958,64987,65017,65047,65076,65106,65136,65166,65195,65225,65254,65283,65313,65342,65371,65401,65431,65460,65490,65520,65549,65579,65608,65638,65667,65697,65726,65755,65785,65815,65844,65874,65903,65933,65963,65992,66022,66051,66081,66110,66140,66169,66199,66228,66258,66287,66317,66346,66376,66405,66435,66465,66494,66524,66553,66583,66612,66641,66671,66700,66730,66760,66789,66819,66849,66878,66908,66937,66967,66996,67025,67055,67084,67114,67143,67173,67203,67233,67262,67292,67321,67351,67380,67409,67439,67468,67497,67527,67557,67587,67617,67646,67676,67705,67735,67764,67793,67823,67852,67882,67911,67941,67971,68e3,68030,68060,68089,68119,68148,68177,68207,68236,68266,68295,68325,68354,68384,68414,68443,68473,68502,68532,68561,68591,68620,68650,68679,68708,68738,68768,68797,68827,68857,68886,68916,68946,68975,69004,69034,69063,69092,69122,69152,69181,69211,69240,69270,69300,69330,69359,69388,69418,69447,69476,69506,69535,69565,69595,69624,69654,69684,69713,69743,69772,69802,69831,69861,69890,69919,69949,69978,70008,70038,70067,70097,70126,70156,70186,70215,70245,70274,70303,70333,70362,70392,70421,70451,70481,70510,70540,70570,70599,70629,70658,70687,70717,70746,70776,70805,70835,70864,70894,70924,70954,70983,71013,71042,71071,71101,71130,71159,71189,71218,71248,71278,71308,71337,71367,71397,71426,71455,71485,71514,71543,71573,71602,71632,71662,71691,71721,71751,71781,71810,71839,71869,71898,71927,71957,71986,72016,72046,72075,72105,72135,72164,72194,72223,72253,72282,72311,72341,72370,72400,72429,72459,72489,72518,72548,72577,72607,72637,72666,72695,72725,72754,72784,72813,72843,72872,72902,72931,72961,72991,73020,73050,73080,73109,73139,73168,73197,73227,73256,73286,73315,73345,73375,73404,73434,73464,73493,73523,73552,73581,73611,73640,73669,73699,73729,73758,73788,73818,73848,73877,73907,73936,73965,73995,74024,74053,74083,74113,74142,74172,74202,74231,74261,74291,74320,74349,74379,74408,74437,74467,74497,74526,74556,74586,74615,74645,74675,74704,74733,74763,74792,74822,74851,74881,74910,74940,74969,74999,75029,75058,75088,75117,75147,75176,75206,75235,75264,75294,75323,75353,75383,75412,75442,75472,75501,75531,75560,75590,75619,75648,75678,75707,75737,75766,75796,75826,75856,75885,75915,75944,75974,76003,76032,76062,76091,76121,76150,76180,76210,76239,76269,76299,76328,76358,76387,76416,76446,76475,76505,76534,76564,76593,76623,76653,76682,76712,76741,76771,76801,76830,76859,76889,76918,76948,76977,77007,77036,77066,77096,77125,77155,77185,77214,77243,77273,77302,77332,77361,77390,77420,77450,77479,77509,77539,77569,77598,77627,77657,77686,77715,77745,77774,77804,77833,77863,77893,77923,77952,77982,78011,78041,78070,78099,78129,78158,78188,78217,78247,78277,78307,78336,78366,78395,78425,78454,78483,78513,78542,78572,78601,78631,78661,78690,78720,78750,78779,78808,78838,78867,78897,78926,78956,78985,79015,79044,79074,79104,79133,79163,79192,79222,79251,79281,79310,79340,79369,79399,79428,79458,79487,79517,79546,79576,79606,79635,79665,79695,79724,79753,79783,79812,79841,79871,79900,79930,79960,79990]},{"../main":552,"object-assign":443}],552:[function(t,e,r){var n=t("object-assign");function i(){this.regionalOptions=[],this.regionalOptions[""]={invalidCalendar:"Calendar {0} not found",invalidDate:"Invalid {0} date",invalidMonth:"Invalid {0} month",invalidYear:"Invalid {0} year",differentCalendars:"Cannot mix {0} and {1} dates"},this.local=this.regionalOptions[""],this.calendars={},this._localCals={}}function a(t,e,r,n){if(this._calendar=t,this._year=e,this._month=r,this._day=n,0===this._calendar._validateLevel&&!this._calendar.isValid(this._year,this._month,this._day))throw(c.local.invalidDate||c.regionalOptions[""].invalidDate).replace(/\{0\}/,this._calendar.local.name)}function o(t,e){return"000000".substring(0,e-(t=""+t).length)+t}function s(){this.shortYearCutoff="+10"}function l(t){this.local=this.regionalOptions[t]||this.regionalOptions[""]}n(i.prototype,{instance:function(t,e){t=(t||"gregorian").toLowerCase(),e=e||"";var r=this._localCals[t+"-"+e];if(!r&&this.calendars[t]&&(r=new this.calendars[t](e),this._localCals[t+"-"+e]=r),!r)throw(this.local.invalidCalendar||this.regionalOptions[""].invalidCalendar).replace(/\{0\}/,t);return r},newDate:function(t,e,r,n,i){return(n=(null!=t&&t.year?t.calendar():"string"==typeof n?this.instance(n,i):n)||this.instance()).newDate(t,e,r)},substituteDigits:function(t){return function(e){return(e+"").replace(/[0-9]/g,function(e){return t[e]})}},substituteChineseDigits:function(t,e){return function(r){for(var n="",i=0;r>0;){var a=r%10;n=(0===a?"":t[a]+e[i])+n,i++,r=Math.floor(r/10)}return 0===n.indexOf(t[1]+e[1])&&(n=n.substr(1)),n||t[0]}}}),n(a.prototype,{newDate:function(t,e,r){return this._calendar.newDate(null==t?this:t,e,r)},year:function(t){return 0===arguments.length?this._year:this.set(t,"y")},month:function(t){return 0===arguments.length?this._month:this.set(t,"m")},day:function(t){return 0===arguments.length?this._day:this.set(t,"d")},date:function(t,e,r){if(!this._calendar.isValid(t,e,r))throw(c.local.invalidDate||c.regionalOptions[""].invalidDate).replace(/\{0\}/,this._calendar.local.name);return this._year=t,this._month=e,this._day=r,this},leapYear:function(){return this._calendar.leapYear(this)},epoch:function(){return this._calendar.epoch(this)},formatYear:function(){return this._calendar.formatYear(this)},monthOfYear:function(){return this._calendar.monthOfYear(this)},weekOfYear:function(){return this._calendar.weekOfYear(this)},daysInYear:function(){return this._calendar.daysInYear(this)},dayOfYear:function(){return this._calendar.dayOfYear(this)},daysInMonth:function(){return this._calendar.daysInMonth(this)},dayOfWeek:function(){return this._calendar.dayOfWeek(this)},weekDay:function(){return this._calendar.weekDay(this)},extraInfo:function(){return this._calendar.extraInfo(this)},add:function(t,e){return this._calendar.add(this,t,e)},set:function(t,e){return this._calendar.set(this,t,e)},compareTo:function(t){if(this._calendar.name!==t._calendar.name)throw(c.local.differentCalendars||c.regionalOptions[""].differentCalendars).replace(/\{0\}/,this._calendar.local.name).replace(/\{1\}/,t._calendar.local.name);var e=this._year!==t._year?this._year-t._year:this._month!==t._month?this.monthOfYear()-t.monthOfYear():this._day-t._day;return 0===e?0:e<0?-1:1},calendar:function(){return this._calendar},toJD:function(){return this._calendar.toJD(this)},fromJD:function(t){return this._calendar.fromJD(t)},toJSDate:function(){return this._calendar.toJSDate(this)},fromJSDate:function(t){return this._calendar.fromJSDate(t)},toString:function(){return(this.year()<0?"-":"")+o(Math.abs(this.year()),4)+"-"+o(this.month(),2)+"-"+o(this.day(),2)}}),n(s.prototype,{_validateLevel:0,newDate:function(t,e,r){return null==t?this.today():(t.year&&(this._validate(t,e,r,c.local.invalidDate||c.regionalOptions[""].invalidDate),r=t.day(),e=t.month(),t=t.year()),new a(this,t,e,r))},today:function(){return this.fromJSDate(new Date)},epoch:function(t){return this._validate(t,this.minMonth,this.minDay,c.local.invalidYear||c.regionalOptions[""].invalidYear).year()<0?this.local.epochs[0]:this.local.epochs[1]},formatYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,c.local.invalidYear||c.regionalOptions[""].invalidYear);return(e.year()<0?"-":"")+o(Math.abs(e.year()),4)},monthsInYear:function(t){return this._validate(t,this.minMonth,this.minDay,c.local.invalidYear||c.regionalOptions[""].invalidYear),12},monthOfYear:function(t,e){var r=this._validate(t,e,this.minDay,c.local.invalidMonth||c.regionalOptions[""].invalidMonth);return(r.month()+this.monthsInYear(r)-this.firstMonth)%this.monthsInYear(r)+this.minMonth},fromMonthOfYear:function(t,e){var r=(e+this.firstMonth-2*this.minMonth)%this.monthsInYear(t)+this.minMonth;return this._validate(t,r,this.minDay,c.local.invalidMonth||c.regionalOptions[""].invalidMonth),r},daysInYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,c.local.invalidYear||c.regionalOptions[""].invalidYear);return this.leapYear(e)?366:365},dayOfYear:function(t,e,r){var n=this._validate(t,e,r,c.local.invalidDate||c.regionalOptions[""].invalidDate);return n.toJD()-this.newDate(n.year(),this.fromMonthOfYear(n.year(),this.minMonth),this.minDay).toJD()+1},daysInWeek:function(){return 7},dayOfWeek:function(t,e,r){var n=this._validate(t,e,r,c.local.invalidDate||c.regionalOptions[""].invalidDate);return(Math.floor(this.toJD(n))+2)%this.daysInWeek()},extraInfo:function(t,e,r){return this._validate(t,e,r,c.local.invalidDate||c.regionalOptions[""].invalidDate),{}},add:function(t,e,r){return this._validate(t,this.minMonth,this.minDay,c.local.invalidDate||c.regionalOptions[""].invalidDate),this._correctAdd(t,this._add(t,e,r),e,r)},_add:function(t,e,r){if(this._validateLevel++,"d"===r||"w"===r){var n=t.toJD()+e*("w"===r?this.daysInWeek():1),i=t.calendar().fromJD(n);return this._validateLevel--,[i.year(),i.month(),i.day()]}try{var a=t.year()+("y"===r?e:0),o=t.monthOfYear()+("m"===r?e:0);i=t.day();"y"===r?(t.month()!==this.fromMonthOfYear(a,o)&&(o=this.newDate(a,t.month(),this.minDay).monthOfYear()),o=Math.min(o,this.monthsInYear(a)),i=Math.min(i,this.daysInMonth(a,this.fromMonthOfYear(a,o)))):"m"===r&&(!function(t){for(;o<t.minMonth;)a--,o+=t.monthsInYear(a);for(var e=t.monthsInYear(a);o>e-1+t.minMonth;)a++,o-=e,e=t.monthsInYear(a)}(this),i=Math.min(i,this.daysInMonth(a,this.fromMonthOfYear(a,o))));var s=[a,this.fromMonthOfYear(a,o),i];return this._validateLevel--,s}catch(t){throw this._validateLevel--,t}},_correctAdd:function(t,e,r,n){if(!(this.hasYearZero||"y"!==n&&"m"!==n||0!==e[0]&&t.year()>0==e[0]>0)){var i={y:[1,1,"y"],m:[1,this.monthsInYear(-1),"m"],w:[this.daysInWeek(),this.daysInYear(-1),"d"],d:[1,this.daysInYear(-1),"d"]}[n],a=r<0?-1:1;e=this._add(t,r*i[0]+a*i[1],i[2])}return t.date(e[0],e[1],e[2])},set:function(t,e,r){this._validate(t,this.minMonth,this.minDay,c.local.invalidDate||c.regionalOptions[""].invalidDate);var n="y"===r?e:t.year(),i="m"===r?e:t.month(),a="d"===r?e:t.day();return"y"!==r&&"m"!==r||(a=Math.min(a,this.daysInMonth(n,i))),t.date(n,i,a)},isValid:function(t,e,r){this._validateLevel++;var n=this.hasYearZero||0!==t;if(n){var i=this.newDate(t,e,this.minDay);n=e>=this.minMonth&&e-this.minMonth<this.monthsInYear(i)&&r>=this.minDay&&r-this.minDay<this.daysInMonth(i)}return this._validateLevel--,n},toJSDate:function(t,e,r){var n=this._validate(t,e,r,c.local.invalidDate||c.regionalOptions[""].invalidDate);return c.instance().fromJD(this.toJD(n)).toJSDate()},fromJSDate:function(t){return this.fromJD(c.instance().fromJSDate(t).toJD())},_validate:function(t,e,r,n){if(t.year){if(0===this._validateLevel&&this.name!==t.calendar().name)throw(c.local.differentCalendars||c.regionalOptions[""].differentCalendars).replace(/\{0\}/,this.local.name).replace(/\{1\}/,t.calendar().local.name);return t}try{if(this._validateLevel++,1===this._validateLevel&&!this.isValid(t,e,r))throw n.replace(/\{0\}/,this.local.name);var i=this.newDate(t,e,r);return this._validateLevel--,i}catch(t){throw this._validateLevel--,t}}}),l.prototype=new s,n(l.prototype,{name:"Gregorian",jdEpoch:1721425.5,daysPerMonth:[31,28,31,30,31,30,31,31,30,31,30,31],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Gregorian",epochs:["BCE","CE"],monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],digits:null,dateFormat:"mm/dd/yyyy",firstDay:0,isRTL:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,c.local.invalidYear||c.regionalOptions[""].invalidYear);return(t=e.year()+(e.year()<0?1:0))%4==0&&(t%100!=0||t%400==0)},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(4-(n.dayOfWeek()||7),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,c.local.invalidMonth||c.regionalOptions[""].invalidMonth);return this.daysPerMonth[r.month()-1]+(2===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var n=this._validate(t,e,r,c.local.invalidDate||c.regionalOptions[""].invalidDate);t=n.year(),e=n.month(),r=n.day(),t<0&&t++,e<3&&(e+=12,t--);var i=Math.floor(t/100),a=2-i+Math.floor(i/4);return Math.floor(365.25*(t+4716))+Math.floor(30.6001*(e+1))+r+a-1524.5},fromJD:function(t){var e=Math.floor(t+.5),r=Math.floor((e-1867216.25)/36524.25),n=(r=e+1+r-Math.floor(r/4))+1524,i=Math.floor((n-122.1)/365.25),a=Math.floor(365.25*i),o=Math.floor((n-a)/30.6001),s=n-a-Math.floor(30.6001*o),l=o-(o>13.5?13:1),c=i-(l>2.5?4716:4715);return c<=0&&c--,this.newDate(c,l,s)},toJSDate:function(t,e,r){var n=this._validate(t,e,r,c.local.invalidDate||c.regionalOptions[""].invalidDate),i=new Date(n.year(),n.month()-1,n.day());return i.setHours(0),i.setMinutes(0),i.setSeconds(0),i.setMilliseconds(0),i.setHours(i.getHours()>12?i.getHours()+2:0),i},fromJSDate:function(t){return this.newDate(t.getFullYear(),t.getMonth()+1,t.getDate())}});var c=e.exports=new i;c.cdate=a,c.baseCalendar=s,c.calendars.gregorian=l},{"object-assign":443}],553:[function(t,e,r){var n=t("object-assign"),i=t("./main");n(i.regionalOptions[""],{invalidArguments:"Invalid arguments",invalidFormat:"Cannot format a date from another calendar",missingNumberAt:"Missing number at position {0}",unknownNameAt:"Unknown name at position {0}",unexpectedLiteralAt:"Unexpected literal at position {0}",unexpectedText:"Additional text found at end"}),i.local=i.regionalOptions[""],n(i.cdate.prototype,{formatDate:function(t,e){return"string"!=typeof t&&(e=t,t=""),this._calendar.formatDate(t||"",this,e)}}),n(i.baseCalendar.prototype,{UNIX_EPOCH:i.instance().newDate(1970,1,1).toJD(),SECS_PER_DAY:86400,TICKS_EPOCH:i.instance().jdEpoch,TICKS_PER_DAY:864e9,ATOM:"yyyy-mm-dd",COOKIE:"D, dd M yyyy",FULL:"DD, MM d, yyyy",ISO_8601:"yyyy-mm-dd",JULIAN:"J",RFC_822:"D, d M yy",RFC_850:"DD, dd-M-yy",RFC_1036:"D, d M yy",RFC_1123:"D, d M yyyy",RFC_2822:"D, d M yyyy",RSS:"D, d M yy",TICKS:"!",TIMESTAMP:"@",W3C:"yyyy-mm-dd",formatDate:function(t,e,r){if("string"!=typeof t&&(r=e,e=t,t=""),!e)return"";if(e.calendar()!==this)throw i.local.invalidFormat||i.regionalOptions[""].invalidFormat;t=t||this.local.dateFormat;for(var n,a,o,s,l=(r=r||{}).dayNamesShort||this.local.dayNamesShort,c=r.dayNames||this.local.dayNames,u=r.monthNumbers||this.local.monthNumbers,h=r.monthNamesShort||this.local.monthNamesShort,f=r.monthNames||this.local.monthNames,p=(r.calculateWeek||this.local.calculateWeek,function(e,r){for(var n=1;w+n<t.length&&t.charAt(w+n)===e;)n++;return w+=n-1,Math.floor(n/(r||1))>1}),d=function(t,e,r,n){var i=""+e;if(p(t,n))for(;i.length<r;)i="0"+i;return i},g=this,v=function(t){return"function"==typeof u?u.call(g,t,p("m")):x(d("m",t.month(),2))},m=function(t,e){return e?"function"==typeof f?f.call(g,t):f[t.month()-g.minMonth]:"function"==typeof h?h.call(g,t):h[t.month()-g.minMonth]},y=this.local.digits,x=function(t){return r.localNumbers&&y?y(t):t},b="",_=!1,w=0;w<t.length;w++)if(_)"'"!==t.charAt(w)||p("'")?b+=t.charAt(w):_=!1;else switch(t.charAt(w)){case"d":b+=x(d("d",e.day(),2));break;case"D":b+=(n="D",a=e.dayOfWeek(),o=l,s=c,p(n)?s[a]:o[a]);break;case"o":b+=d("o",e.dayOfYear(),3);break;case"w":b+=d("w",e.weekOfYear(),2);break;case"m":b+=v(e);break;case"M":b+=m(e,p("M"));break;case"y":b+=p("y",2)?e.year():(e.year()%100<10?"0":"")+e.year()%100;break;case"Y":p("Y",2),b+=e.formatYear();break;case"J":b+=e.toJD();break;case"@":b+=(e.toJD()-this.UNIX_EPOCH)*this.SECS_PER_DAY;break;case"!":b+=(e.toJD()-this.TICKS_EPOCH)*this.TICKS_PER_DAY;break;case"'":p("'")?b+="'":_=!0;break;default:b+=t.charAt(w)}return b},parseDate:function(t,e,r){if(null==e)throw i.local.invalidArguments||i.regionalOptions[""].invalidArguments;if(""===(e="object"==typeof e?e.toString():e+""))return null;t=t||this.local.dateFormat;var n=(r=r||{}).shortYearCutoff||this.shortYearCutoff;n="string"!=typeof n?n:this.today().year()%100+parseInt(n,10);for(var a=r.dayNamesShort||this.local.dayNamesShort,o=r.dayNames||this.local.dayNames,s=r.parseMonth||this.local.parseMonth,l=r.monthNumbers||this.local.monthNumbers,c=r.monthNamesShort||this.local.monthNamesShort,u=r.monthNames||this.local.monthNames,h=-1,f=-1,p=-1,d=-1,g=-1,v=!1,m=!1,y=function(e,r){for(var n=1;T+n<t.length&&t.charAt(T+n)===e;)n++;return T+=n-1,Math.floor(n/(r||1))>1},x=function(t,r){var n=y(t,r),a=[2,3,n?4:2,n?4:2,10,11,20]["oyYJ@!".indexOf(t)+1],o=new RegExp("^-?\\d{1,"+a+"}"),s=e.substring(M).match(o);if(!s)throw(i.local.missingNumberAt||i.regionalOptions[""].missingNumberAt).replace(/\{0\}/,M);return M+=s[0].length,parseInt(s[0],10)},b=this,_=function(){if("function"==typeof l){y("m");var t=l.call(b,e.substring(M));return M+=t.length,t}return x("m")},w=function(t,r,n,a){for(var o=y(t,a)?n:r,s=0;s<o.length;s++)if(e.substr(M,o[s].length).toLowerCase()===o[s].toLowerCase())return M+=o[s].length,s+b.minMonth;throw(i.local.unknownNameAt||i.regionalOptions[""].unknownNameAt).replace(/\{0\}/,M)},k=function(){if("function"==typeof u){var t=y("M")?u.call(b,e.substring(M)):c.call(b,e.substring(M));return M+=t.length,t}return w("M",c,u)},A=function(){if(e.charAt(M)!==t.charAt(T))throw(i.local.unexpectedLiteralAt||i.regionalOptions[""].unexpectedLiteralAt).replace(/\{0\}/,M);M++},M=0,T=0;T<t.length;T++)if(m)"'"!==t.charAt(T)||y("'")?A():m=!1;else switch(t.charAt(T)){case"d":d=x("d");break;case"D":w("D",a,o);break;case"o":g=x("o");break;case"w":x("w");break;case"m":p=_();break;case"M":p=k();break;case"y":var S=T;v=!y("y",2),T=S,f=x("y",2);break;case"Y":f=x("Y",2);break;case"J":h=x("J")+.5,"."===e.charAt(M)&&(M++,x("J"));break;case"@":h=x("@")/this.SECS_PER_DAY+this.UNIX_EPOCH;break;case"!":h=x("!")/this.TICKS_PER_DAY+this.TICKS_EPOCH;break;case"*":M=e.length;break;case"'":y("'")?A():m=!0;break;default:A()}if(M<e.length)throw i.local.unexpectedText||i.regionalOptions[""].unexpectedText;if(-1===f?f=this.today().year():f<100&&v&&(f+=-1===n?1900:this.today().year()-this.today().year()%100-(f<=n?0:100)),"string"==typeof p&&(p=s.call(this,f,p)),g>-1){p=1,d=g;for(var E=this.daysInMonth(f,p);d>E;E=this.daysInMonth(f,p))p++,d-=E}return h>-1?this.fromJD(h):this.newDate(f,p,d)},determineDate:function(t,e,r,n,i){r&&"object"!=typeof r&&(i=n,n=r,r=null),"string"!=typeof n&&(i=n,n="");var a=this;return e=e?e.newDate():null,t=null==t?e:"string"==typeof t?function(t){try{return a.parseDate(n,t,i)}catch(t){}for(var e=((t=t.toLowerCase()).match(/^c/)&&r?r.newDate():null)||a.today(),o=/([+-]?[0-9]+)\s*(d|w|m|y)?/g,s=o.exec(t);s;)e.add(parseInt(s[1],10),s[2]||"d"),s=o.exec(t);return e}(t):"number"==typeof t?isNaN(t)||t===1/0||t===-1/0?e:a.today().add(t,"d"):a.newDate(t)}})},{"./main":552,"object-assign":443}],554:[function(t,e,r){e.exports=t("cwise-compiler")({args:["array",{offset:[1],array:0},"scalar","scalar","index"],pre:{body:"{}",args:[],thisVars:[],localVars:[]},post:{body:"{}",args:[],thisVars:[],localVars:[]},body:{body:"{\n        var _inline_1_da = _inline_1_arg0_ - _inline_1_arg3_\n        var _inline_1_db = _inline_1_arg1_ - _inline_1_arg3_\n        if((_inline_1_da >= 0) !== (_inline_1_db >= 0)) {\n          _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n        }\n      }",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg3_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:[],localVars:["_inline_1_da","_inline_1_db"]},funcName:"zeroCrossings"})},{"cwise-compiler":134}],555:[function(t,e,r){"use strict";e.exports=function(t,e){var r=[];return e=+e||0,n(t.hi(t.shape[0]-1),r,e),r};var n=t("./lib/zc-core")},{"./lib/zc-core":554}],556:[function(t,e,r){"use strict";e.exports=[{path:"",backoff:0},{path:"M-2.4,-3V3L0.6,0Z",backoff:.6},{path:"M-3.7,-2.5V2.5L1.3,0Z",backoff:1.3},{path:"M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z",backoff:1.55},{path:"M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z",backoff:1.6},{path:"M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z",backoff:2},{path:"M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z",backoff:0,noRotate:!0},{path:"M2,2V-2H-2V2Z",backoff:0,noRotate:!0}]},{}],557:[function(t,e,r){"use strict";var n=t("./arrow_paths"),i=t("../../plots/font_attributes"),a=t("../../plots/cartesian/constants"),o=t("../../plot_api/plot_template").templatedArray;e.exports=o("annotation",{visible:{valType:"boolean",dflt:!0,editType:"calc+arraydraw"},text:{valType:"string",editType:"calc+arraydraw"},textangle:{valType:"angle",dflt:0,editType:"calc+arraydraw"},font:i({editType:"calc+arraydraw",colorEditType:"arraydraw"}),width:{valType:"number",min:1,dflt:null,editType:"calc+arraydraw"},height:{valType:"number",min:1,dflt:null,editType:"calc+arraydraw"},opacity:{valType:"number",min:0,max:1,dflt:1,editType:"arraydraw"},align:{valType:"enumerated",values:["left","center","right"],dflt:"center",editType:"arraydraw"},valign:{valType:"enumerated",values:["top","middle","bottom"],dflt:"middle",editType:"arraydraw"},bgcolor:{valType:"color",dflt:"rgba(0,0,0,0)",editType:"arraydraw"},bordercolor:{valType:"color",dflt:"rgba(0,0,0,0)",editType:"arraydraw"},borderpad:{valType:"number",min:0,dflt:1,editType:"calc+arraydraw"},borderwidth:{valType:"number",min:0,dflt:1,editType:"calc+arraydraw"},showarrow:{valType:"boolean",dflt:!0,editType:"calc+arraydraw"},arrowcolor:{valType:"color",editType:"arraydraw"},arrowhead:{valType:"integer",min:0,max:n.length,dflt:1,editType:"arraydraw"},startarrowhead:{valType:"integer",min:0,max:n.length,dflt:1,editType:"arraydraw"},arrowside:{valType:"flaglist",flags:["end","start"],extras:["none"],dflt:"end",editType:"arraydraw"},arrowsize:{valType:"number",min:.3,dflt:1,editType:"calc+arraydraw"},startarrowsize:{valType:"number",min:.3,dflt:1,editType:"calc+arraydraw"},arrowwidth:{valType:"number",min:.1,editType:"calc+arraydraw"},standoff:{valType:"number",min:0,dflt:0,editType:"calc+arraydraw"},startstandoff:{valType:"number",min:0,dflt:0,editType:"calc+arraydraw"},ax:{valType:"any",editType:"calc+arraydraw"},ay:{valType:"any",editType:"calc+arraydraw"},axref:{valType:"enumerated",dflt:"pixel",values:["pixel",a.idRegex.x.toString()],editType:"calc"},ayref:{valType:"enumerated",dflt:"pixel",values:["pixel",a.idRegex.y.toString()],editType:"calc"},xref:{valType:"enumerated",values:["paper",a.idRegex.x.toString()],editType:"calc"},x:{valType:"any",editType:"calc+arraydraw"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"auto",editType:"calc+arraydraw"},xshift:{valType:"number",dflt:0,editType:"calc+arraydraw"},yref:{valType:"enumerated",values:["paper",a.idRegex.y.toString()],editType:"calc"},y:{valType:"any",editType:"calc+arraydraw"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"auto",editType:"calc+arraydraw"},yshift:{valType:"number",dflt:0,editType:"calc+arraydraw"},clicktoshow:{valType:"enumerated",values:[!1,"onoff","onout"],dflt:!1,editType:"arraydraw"},xclick:{valType:"any",editType:"arraydraw"},yclick:{valType:"any",editType:"arraydraw"},hovertext:{valType:"string",editType:"arraydraw"},hoverlabel:{bgcolor:{valType:"color",editType:"arraydraw"},bordercolor:{valType:"color",editType:"arraydraw"},font:i({editType:"arraydraw"}),editType:"arraydraw"},captureevents:{valType:"boolean",editType:"arraydraw"},editType:"calc",_deprecated:{ref:{valType:"string",editType:"calc"}}})},{"../../plot_api/plot_template":735,"../../plots/cartesian/constants":751,"../../plots/font_attributes":771,"./arrow_paths":556}],558:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/cartesian/axes"),a=t("./draw").draw;function o(t){var e=t._fullLayout;n.filterVisible(e.annotations).forEach(function(e){var r=i.getFromId(t,e.xref),n=i.getFromId(t,e.yref);e._extremes={},r&&s(e,r),n&&s(e,n)})}function s(t,e){var r,n=e._id,a=n.charAt(0),o=t[a],s=t["a"+a],l=t[a+"ref"],c=t["a"+a+"ref"],u=t["_"+a+"padplus"],h=t["_"+a+"padminus"],f={x:1,y:-1}[a]*t[a+"shift"],p=3*t.arrowsize*t.arrowwidth||0,d=p+f,g=p-f,v=3*t.startarrowsize*t.arrowwidth||0,m=v+f,y=v-f;if(c===l){var x=i.findExtremes(e,[e.r2c(o)],{ppadplus:d,ppadminus:g}),b=i.findExtremes(e,[e.r2c(s)],{ppadplus:Math.max(u,m),ppadminus:Math.max(h,y)});r={min:[x.min[0],b.min[0]],max:[x.max[0],b.max[0]]}}else m=s?m+s:m,y=s?y-s:y,r=i.findExtremes(e,[e.r2c(o)],{ppadplus:Math.max(u,d,m),ppadminus:Math.max(h,g,y)});t._extremes[n]=r}e.exports=function(t){var e=t._fullLayout;if(n.filterVisible(e.annotations).length&&t._fullData.length)return n.syncOrAsync([a,o],t)}},{"../../lib":697,"../../plots/cartesian/axes":745,"./draw":563}],559:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../registry"),a=t("../../plot_api/plot_template").arrayEditor;function o(t,e){var r,n,i,a,o,l,c,u=t._fullLayout.annotations,h=[],f=[],p=[],d=(e||[]).length;for(r=0;r<u.length;r++)if(a=(i=u[r]).clicktoshow){for(n=0;n<d;n++)if(l=(o=e[n]).xaxis,c=o.yaxis,l._id===i.xref&&c._id===i.yref&&l.d2r(o.x)===s(i._xclick,l)&&c.d2r(o.y)===s(i._yclick,c)){(i.visible?"onout"===a?f:p:h).push(r);break}n===d&&i.visible&&"onout"===a&&f.push(r)}return{on:h,off:f,explicitOff:p}}function s(t,e){return"log"===e.type?e.l2r(t):e.d2r(t)}e.exports={hasClickToShow:function(t,e){var r=o(t,e);return r.on.length>0||r.explicitOff.length>0},onClick:function(t,e){var r,s,l=o(t,e),c=l.on,u=l.off.concat(l.explicitOff),h={},f=t._fullLayout.annotations;if(!c.length&&!u.length)return;for(r=0;r<c.length;r++)(s=a(t.layout,"annotations",f[c[r]])).modifyItem("visible",!0),n.extendFlat(h,s.getUpdateObj());for(r=0;r<u.length;r++)(s=a(t.layout,"annotations",f[u[r]])).modifyItem("visible",!1),n.extendFlat(h,s.getUpdateObj());return i.call("update",t,{},h)}}},{"../../lib":697,"../../plot_api/plot_template":735,"../../registry":826}],560:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../color");e.exports=function(t,e,r,a){a("opacity");var o=a("bgcolor"),s=a("bordercolor"),l=i.opacity(s);a("borderpad");var c=a("borderwidth"),u=a("showarrow");if(a("text",u?" ":r._dfltTitle.annotation),a("textangle"),n.coerceFont(a,"font",r.font),a("width"),a("align"),a("height")&&a("valign"),u){var h,f,p=a("arrowside");-1!==p.indexOf("end")&&(h=a("arrowhead"),f=a("arrowsize")),-1!==p.indexOf("start")&&(a("startarrowhead",h),a("startarrowsize",f)),a("arrowcolor",l?e.bordercolor:i.defaultLine),a("arrowwidth",2*(l&&c||1)),a("standoff"),a("startstandoff")}var d=a("hovertext"),g=r.hoverlabel||{};if(d){var v=a("hoverlabel.bgcolor",g.bgcolor||(i.opacity(o)?i.rgb(o):i.defaultLine)),m=a("hoverlabel.bordercolor",g.bordercolor||i.contrast(v));n.coerceFont(a,"hoverlabel.font",{family:g.font.family,size:g.font.size,color:g.font.color||m})}a("captureevents",!!d)}},{"../../lib":697,"../color":574}],561:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib/to_log_range");e.exports=function(t,e,r,a){e=e||{};var o="log"===r&&"linear"===e.type,s="linear"===r&&"log"===e.type;if(o||s)for(var l,c,u=t._fullLayout.annotations,h=e._id.charAt(0),f=0;f<u.length;f++)l=u[f],c="annotations["+f+"].",l[h+"ref"]===e._id&&p(h),l["a"+h+"ref"]===e._id&&p("a"+h);function p(t){var r=l[t],s=null;s=o?i(r,e.range):Math.pow(10,r),n(s)||(s=null),a(c+t,s)}}},{"../../lib/to_log_range":723,"fast-isnumeric":218}],562:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/cartesian/axes"),a=t("../../plots/array_container_defaults"),o=t("./common_defaults"),s=t("./attributes");function l(t,e,r){function a(r,i){return n.coerce(t,e,s,r,i)}var l=a("visible"),c=a("clicktoshow");if(l||c){o(t,e,r,a);for(var u=e.showarrow,h=["x","y"],f=[-10,-30],p={_fullLayout:r},d=0;d<2;d++){var g=h[d],v=i.coerceRef(t,e,p,g,"","paper");if("paper"!==v)i.getFromId(p,v)._annIndices.push(e._index);if(i.coercePosition(e,p,a,v,g,.5),u){var m="a"+g,y=i.coerceRef(t,e,p,m,"pixel");"pixel"!==y&&y!==v&&(y=e[m]="pixel");var x="pixel"===y?f[d]:.4;i.coercePosition(e,p,a,y,m,x)}a(g+"anchor"),a(g+"shift")}if(n.noneOrAll(t,e,["x","y"]),u&&n.noneOrAll(t,e,["ax","ay"]),c){var b=a("xclick"),_=a("yclick");e._xclick=void 0===b?e.x:i.cleanPosition(b,p,e.xref),e._yclick=void 0===_?e.y:i.cleanPosition(_,p,e.yref)}}}e.exports=function(t,e){a(t,e,{name:"annotations",handleItemDefaults:l})}},{"../../lib":697,"../../plots/array_container_defaults":741,"../../plots/cartesian/axes":745,"./attributes":557,"./common_defaults":560}],563:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../registry"),a=t("../../plots/plots"),o=t("../../lib"),s=t("../../plots/cartesian/axes"),l=t("../color"),c=t("../drawing"),u=t("../fx"),h=t("../../lib/svg_text_utils"),f=t("../../lib/setcursor"),p=t("../dragelement"),d=t("../../plot_api/plot_template").arrayEditor,g=t("./draw_arrow_head");function v(t,e){var r=t._fullLayout.annotations[e]||{},n=s.getFromId(t,r.xref),i=s.getFromId(t,r.yref);n&&n.setScale(),i&&i.setScale(),m(t,r,e,!1,n,i)}function m(t,e,r,a,s,v){var m,y,x=t._fullLayout,b=t._fullLayout._size,_=t._context.edits;a?(m="annotation-"+a,y=a+".annotations"):(m="annotation",y="annotations");var w=d(t.layout,y,e),k=w.modifyBase,A=w.modifyItem,M=w.getUpdateObj;x._infolayer.selectAll("."+m+'[data-index="'+r+'"]').remove();var T="clip"+x._uid+"_ann"+r;if(e._input&&!1!==e.visible){var S={x:{},y:{}},E=+e.textangle||0,C=x._infolayer.append("g").classed(m,!0).attr("data-index",String(r)).style("opacity",e.opacity),L=C.append("g").classed("annotation-text-g",!0),z=_[e.showarrow?"annotationTail":"annotationPosition"],O=e.captureevents||_.annotationText||z,I=L.append("g").style("pointer-events",O?"all":null).call(f,"pointer").on("click",function(){t._dragging=!1;var i={index:r,annotation:e._input,fullAnnotation:e,event:n.event};a&&(i.subplotId=a),t.emit("plotly_clickannotation",i)});e.hovertext&&I.on("mouseover",function(){var r=e.hoverlabel,n=r.font,i=this.getBoundingClientRect(),a=t.getBoundingClientRect();u.loneHover({x0:i.left-a.left,x1:i.right-a.left,y:(i.top+i.bottom)/2-a.top,text:e.hovertext,color:r.bgcolor,borderColor:r.bordercolor,fontFamily:n.family,fontSize:n.size,fontColor:n.color},{container:x._hoverlayer.node(),outerContainer:x._paper.node(),gd:t})}).on("mouseout",function(){u.loneUnhover(x._hoverlayer.node())});var D=e.borderwidth,P=e.borderpad,R=D+P,F=I.append("rect").attr("class","bg").style("stroke-width",D+"px").call(l.stroke,e.bordercolor).call(l.fill,e.bgcolor),B=e.width||e.height,N=x._topclips.selectAll("#"+T).data(B?[0]:[]);N.enter().append("clipPath").classed("annclip",!0).attr("id",T).append("rect"),N.exit().remove();var j=e.font,V=x.meta?o.templateString(e.text,{meta:x.meta}):e.text,U=I.append("text").classed("annotation-text",!0).text(V);_.annotationText?U.call(h.makeEditable,{delegate:I,gd:t}).call(q).on("edit",function(r){e.text=r,this.call(q),A("text",r),s&&s.autorange&&k(s._name+".autorange",!0),v&&v.autorange&&k(v._name+".autorange",!0),i.call("_guiRelayout",t,M())}):U.call(q)}else n.selectAll("#"+T).remove();function q(r){return r.call(c.font,j).attr({"text-anchor":{left:"start",right:"end"}[e.align]||"middle"}),h.convertToTspans(r,t,H),r}function H(){var r=U.selectAll("a");1===r.size()&&r.text()===U.text()&&I.insert("a",":first-child").attr({"xlink:xlink:href":r.attr("xlink:href"),"xlink:xlink:show":r.attr("xlink:show")}).style({cursor:"pointer"}).node().appendChild(F.node());var n=I.select(".annotation-text-math-group"),u=!n.empty(),d=c.bBox((u?n:U).node()),m=d.width,y=d.height,w=e.width||m,O=e.height||y,P=Math.round(w+2*R),j=Math.round(O+2*R);function V(t,e){return"auto"===e&&(e=t<1/3?"left":t>2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[e]}for(var q=!1,H=["x","y"],G=0;G<H.length;G++){var Y,W,X,Z,$,J=H[G],K=e[J+"ref"]||J,Q=e["a"+J+"ref"],tt={x:s,y:v}[J],et=(E+("x"===J?0:-90))*Math.PI/180,rt=P*Math.cos(et),nt=j*Math.sin(et),it=Math.abs(rt)+Math.abs(nt),at=e[J+"anchor"],ot=e[J+"shift"]*("x"===J?1:-1),st=S[J];if(tt){var lt=tt.r2fraction(e[J]);(lt<0||lt>1)&&(Q===K?((lt=tt.r2fraction(e["a"+J]))<0||lt>1)&&(q=!0):q=!0),Y=tt._offset+tt.r2p(e[J]),Z=.5}else"x"===J?(X=e[J],Y=b.l+b.w*X):(X=1-e[J],Y=b.t+b.h*X),Z=e.showarrow?.5:X;if(e.showarrow){st.head=Y;var ct=e["a"+J];$=rt*V(.5,e.xanchor)-nt*V(.5,e.yanchor),Q===K?(st.tail=tt._offset+tt.r2p(ct),W=$):(st.tail=Y+ct,W=$+ct),st.text=st.tail+$;var ut=x["x"===J?"width":"height"];if("paper"===K&&(st.head=o.constrain(st.head,1,ut-1)),"pixel"===Q){var ht=-Math.max(st.tail-3,st.text),ft=Math.min(st.tail+3,st.text)-ut;ht>0?(st.tail+=ht,st.text+=ht):ft>0&&(st.tail-=ft,st.text-=ft)}st.tail+=ot,st.head+=ot}else W=$=it*V(Z,at),st.text=Y+$;st.text+=ot,$+=ot,W+=ot,e["_"+J+"padplus"]=it/2+W,e["_"+J+"padminus"]=it/2-W,e["_"+J+"size"]=it,e["_"+J+"shift"]=$}if(t._dragging||!q){var pt=0,dt=0;if("left"!==e.align&&(pt=(w-m)*("center"===e.align?.5:1)),"top"!==e.valign&&(dt=(O-y)*("middle"===e.valign?.5:1)),u)n.select("svg").attr({x:R+pt-1,y:R+dt}).call(c.setClipUrl,B?T:null,t);else{var gt=R+dt-d.top,vt=R+pt-d.left;U.call(h.positionText,vt,gt).call(c.setClipUrl,B?T:null,t)}N.select("rect").call(c.setRect,R,R,w,O),F.call(c.setRect,D/2,D/2,P-D,j-D),I.call(c.setTranslate,Math.round(S.x.text-P/2),Math.round(S.y.text-j/2)),L.attr({transform:"rotate("+E+","+S.x.text+","+S.y.text+")"});var mt,yt=function(r,n){C.selectAll(".annotation-arrow-g").remove();var u=S.x.head,h=S.y.head,f=S.x.tail+r,d=S.y.tail+n,m=S.x.text+r,y=S.y.text+n,x=o.rotationXYMatrix(E,m,y),w=o.apply2DTransform(x),T=o.apply2DTransform2(x),z=+F.attr("width"),O=+F.attr("height"),D=m-.5*z,P=D+z,R=y-.5*O,B=R+O,N=[[D,R,D,B],[D,B,P,B],[P,B,P,R],[P,R,D,R]].map(T);if(!N.reduce(function(t,e){return t^!!o.segmentsIntersect(u,h,u+1e6,h+1e6,e[0],e[1],e[2],e[3])},!1)){N.forEach(function(t){var e=o.segmentsIntersect(f,d,u,h,t[0],t[1],t[2],t[3]);e&&(f=e.x,d=e.y)});var j=e.arrowwidth,V=e.arrowcolor,U=e.arrowside,q=C.append("g").style({opacity:l.opacity(V)}).classed("annotation-arrow-g",!0),H=q.append("path").attr("d","M"+f+","+d+"L"+u+","+h).style("stroke-width",j+"px").call(l.stroke,l.rgb(V));if(g(H,U,e),_.annotationPosition&&H.node().parentNode&&!a){var G=u,Y=h;if(e.standoff){var W=Math.sqrt(Math.pow(u-f,2)+Math.pow(h-d,2));G+=e.standoff*(f-u)/W,Y+=e.standoff*(d-h)/W}var X,Z,$=q.append("path").classed("annotation-arrow",!0).classed("anndrag",!0).classed("cursor-move",!0).attr({d:"M3,3H-3V-3H3ZM0,0L"+(f-G)+","+(d-Y),transform:"translate("+G+","+Y+")"}).style("stroke-width",j+6+"px").call(l.stroke,"rgba(0,0,0,0)").call(l.fill,"rgba(0,0,0,0)");p.init({element:$.node(),gd:t,prepFn:function(){var t=c.getTranslate(I);X=t.x,Z=t.y,s&&s.autorange&&k(s._name+".autorange",!0),v&&v.autorange&&k(v._name+".autorange",!0)},moveFn:function(t,r){var n=w(X,Z),i=n[0]+t,a=n[1]+r;I.call(c.setTranslate,i,a),A("x",s?s.p2r(s.r2p(e.x)+t):e.x+t/b.w),A("y",v?v.p2r(v.r2p(e.y)+r):e.y-r/b.h),e.axref===e.xref&&A("ax",s.p2r(s.r2p(e.ax)+t)),e.ayref===e.yref&&A("ay",v.p2r(v.r2p(e.ay)+r)),q.attr("transform","translate("+t+","+r+")"),L.attr({transform:"rotate("+E+","+i+","+a+")"})},doneFn:function(){i.call("_guiRelayout",t,M());var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}};if(e.showarrow&&yt(0,0),z)p.init({element:I.node(),gd:t,prepFn:function(){mt=L.attr("transform")},moveFn:function(t,r){var n="pointer";if(e.showarrow)e.axref===e.xref?A("ax",s.p2r(s.r2p(e.ax)+t)):A("ax",e.ax+t),e.ayref===e.yref?A("ay",v.p2r(v.r2p(e.ay)+r)):A("ay",e.ay+r),yt(t,r);else{if(a)return;var i,o;if(s)i=s.p2r(s.r2p(e.x)+t);else{var l=e._xsize/b.w,c=e.x+(e._xshift-e.xshift)/b.w-l/2;i=p.align(c+t/b.w,l,0,1,e.xanchor)}if(v)o=v.p2r(v.r2p(e.y)+r);else{var u=e._ysize/b.h,h=e.y-(e._yshift+e.yshift)/b.h-u/2;o=p.align(h-r/b.h,u,0,1,e.yanchor)}A("x",i),A("y",o),s&&v||(n=p.getCursor(s?.5:i,v?.5:o,e.xanchor,e.yanchor))}L.attr({transform:"translate("+t+","+r+")"+mt}),f(I,n)},doneFn:function(){f(I),i.call("_guiRelayout",t,M());var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}else I.remove()}}e.exports={draw:function(t){var e=t._fullLayout;e._infolayer.selectAll(".annotation").remove();for(var r=0;r<e.annotations.length;r++)e.annotations[r].visible&&v(t,r);return a.previousPromises(t)},drawOne:v,drawRaw:m}},{"../../lib":697,"../../lib/setcursor":717,"../../lib/svg_text_utils":721,"../../plot_api/plot_template":735,"../../plots/cartesian/axes":745,"../../plots/plots":807,"../../registry":826,"../color":574,"../dragelement":592,"../drawing":595,"../fx":613,"./draw_arrow_head":564,d3:151}],564:[function(t,e,r){"use strict";var n=t("d3"),i=t("../color"),a=t("./arrow_paths");e.exports=function(t,e,r){var o,s,l,c,u=t.node(),h=a[r.arrowhead||0],f=a[r.startarrowhead||0],p=(r.arrowwidth||1)*(r.arrowsize||1),d=(r.arrowwidth||1)*(r.startarrowsize||1),g=e.indexOf("start")>=0,v=e.indexOf("end")>=0,m=h.backoff*p+r.standoff,y=f.backoff*d+r.startstandoff;if("line"===u.nodeName){o={x:+t.attr("x1"),y:+t.attr("y1")},s={x:+t.attr("x2"),y:+t.attr("y2")};var x=o.x-s.x,b=o.y-s.y;if(c=(l=Math.atan2(b,x))+Math.PI,m&&y&&m+y>Math.sqrt(x*x+b*b))return void z();if(m){if(m*m>x*x+b*b)return void z();var _=m*Math.cos(l),w=m*Math.sin(l);s.x+=_,s.y+=w,t.attr({x2:s.x,y2:s.y})}if(y){if(y*y>x*x+b*b)return void z();var k=y*Math.cos(l),A=y*Math.sin(l);o.x-=k,o.y-=A,t.attr({x1:o.x,y1:o.y})}}else if("path"===u.nodeName){var M=u.getTotalLength(),T="";if(M<m+y)return void z();var S=u.getPointAtLength(0),E=u.getPointAtLength(.1);l=Math.atan2(S.y-E.y,S.x-E.x),o=u.getPointAtLength(Math.min(y,M)),T="0px,"+y+"px,";var C=u.getPointAtLength(M),L=u.getPointAtLength(M-.1);c=Math.atan2(C.y-L.y,C.x-L.x),s=u.getPointAtLength(Math.max(0,M-m)),T+=M-(T?y+m:m)+"px,"+M+"px",t.style("stroke-dasharray",T)}function z(){t.style("stroke-dasharray","0px,100px")}function O(e,a,o,s){e.path&&(e.noRotate&&(o=0),n.select(u.parentNode).append("path").attr({class:t.attr("class"),d:e.path,transform:"translate("+a.x+","+a.y+")"+(o?"rotate("+180*o/Math.PI+")":"")+"scale("+s+")"}).style({fill:i.rgb(r.arrowcolor),"stroke-width":0}))}g&&O(f,o,l,d),v&&O(h,s,c,p)}},{"../color":574,"./arrow_paths":556,d3:151}],565:[function(t,e,r){"use strict";var n=t("./draw"),i=t("./click");e.exports={moduleType:"component",name:"annotations",layoutAttributes:t("./attributes"),supplyLayoutDefaults:t("./defaults"),includeBasePlot:t("../../plots/cartesian/include_components")("annotations"),calcAutorange:t("./calc_autorange"),draw:n.draw,drawOne:n.drawOne,drawRaw:n.drawRaw,hasClickToShow:i.hasClickToShow,onClick:i.onClick,convertCoords:t("./convert_coords")}},{"../../plots/cartesian/include_components":755,"./attributes":557,"./calc_autorange":558,"./click":559,"./convert_coords":561,"./defaults":562,"./draw":563}],566:[function(t,e,r){"use strict";var n=t("../annotations/attributes"),i=t("../../plot_api/edit_types").overrideAll,a=t("../../plot_api/plot_template").templatedArray;e.exports=i(a("annotation",{visible:n.visible,x:{valType:"any"},y:{valType:"any"},z:{valType:"any"},ax:{valType:"number"},ay:{valType:"number"},xanchor:n.xanchor,xshift:n.xshift,yanchor:n.yanchor,yshift:n.yshift,text:n.text,textangle:n.textangle,font:n.font,width:n.width,height:n.height,opacity:n.opacity,align:n.align,valign:n.valign,bgcolor:n.bgcolor,bordercolor:n.bordercolor,borderpad:n.borderpad,borderwidth:n.borderwidth,showarrow:n.showarrow,arrowcolor:n.arrowcolor,arrowhead:n.arrowhead,startarrowhead:n.startarrowhead,arrowside:n.arrowside,arrowsize:n.arrowsize,startarrowsize:n.startarrowsize,arrowwidth:n.arrowwidth,standoff:n.standoff,startstandoff:n.startstandoff,hovertext:n.hovertext,hoverlabel:n.hoverlabel,captureevents:n.captureevents}),"calc","from-root")},{"../../plot_api/edit_types":728,"../../plot_api/plot_template":735,"../annotations/attributes":557}],567:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/cartesian/axes");function a(t,e){var r=e.fullSceneLayout.domain,a=e.fullLayout._size,o={pdata:null,type:"linear",autorange:!1,range:[-1/0,1/0]};t._xa={},n.extendFlat(t._xa,o),i.setConvert(t._xa),t._xa._offset=a.l+r.x[0]*a.w,t._xa.l2p=function(){return.5*(1+t._pdata[0]/t._pdata[3])*a.w*(r.x[1]-r.x[0])},t._ya={},n.extendFlat(t._ya,o),i.setConvert(t._ya),t._ya._offset=a.t+(1-r.y[1])*a.h,t._ya.l2p=function(){return.5*(1-t._pdata[1]/t._pdata[3])*a.h*(r.y[1]-r.y[0])}}e.exports=function(t){for(var e=t.fullSceneLayout.annotations,r=0;r<e.length;r++)a(e[r],t);t.fullLayout._infolayer.selectAll(".annotation-"+t.id).remove()}},{"../../lib":697,"../../plots/cartesian/axes":745}],568:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/cartesian/axes"),a=t("../../plots/array_container_defaults"),o=t("../annotations/common_defaults"),s=t("./attributes");function l(t,e,r,a){function l(r,i){return n.coerce(t,e,s,r,i)}function c(t){var n=t+"axis",a={_fullLayout:{}};return a._fullLayout[n]=r[n],i.coercePosition(e,a,l,t,t,.5)}l("visible")&&(o(t,e,a.fullLayout,l),c("x"),c("y"),c("z"),n.noneOrAll(t,e,["x","y","z"]),e.xref="x",e.yref="y",e.zref="z",l("xanchor"),l("yanchor"),l("xshift"),l("yshift"),e.showarrow&&(e.axref="pixel",e.ayref="pixel",l("ax",-10),l("ay",-30),n.noneOrAll(t,e,["ax","ay"])))}e.exports=function(t,e,r){a(t,e,{name:"annotations",handleItemDefaults:l,fullLayout:r.fullLayout})}},{"../../lib":697,"../../plots/array_container_defaults":741,"../../plots/cartesian/axes":745,"../annotations/common_defaults":560,"./attributes":566}],569:[function(t,e,r){"use strict";var n=t("../annotations/draw").drawRaw,i=t("../../plots/gl3d/project"),a=["x","y","z"];e.exports=function(t){for(var e=t.fullSceneLayout,r=t.dataScale,o=e.annotations,s=0;s<o.length;s++){for(var l=o[s],c=!1,u=0;u<3;u++){var h=a[u],f=l[h],p=e[h+"axis"].r2fraction(f);if(p<0||p>1){c=!0;break}}c?t.fullLayout._infolayer.select(".annotation-"+t.id+'[data-index="'+s+'"]').remove():(l._pdata=i(t.glplot.cameraParams,[e.xaxis.r2l(l.x)*r[0],e.yaxis.r2l(l.y)*r[1],e.zaxis.r2l(l.z)*r[2]]),n(t.graphDiv,l,s,t.id,l._xa,l._ya))}}},{"../../plots/gl3d/project":795,"../annotations/draw":563}],570:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("../../lib");e.exports={moduleType:"component",name:"annotations3d",schema:{subplots:{scene:{annotations:t("./attributes")}}},layoutAttributes:t("./attributes"),handleDefaults:t("./defaults"),includeBasePlot:function(t,e){var r=n.subplotsRegistry.gl3d;if(!r)return;for(var a=r.attrRegex,o=Object.keys(t),s=0;s<o.length;s++){var l=o[s];a.test(l)&&(t[l].annotations||[]).length&&(i.pushUnique(e._basePlotModules,r),i.pushUnique(e._subplots.gl3d,l))}},convert:t("./convert"),draw:t("./draw")}},{"../../lib":697,"../../registry":826,"./attributes":566,"./convert":567,"./defaults":568,"./draw":569}],571:[function(t,e,r){"use strict";e.exports=t("world-calendars/dist/main"),t("world-calendars/dist/plus"),t("world-calendars/dist/calendars/chinese"),t("world-calendars/dist/calendars/coptic"),t("world-calendars/dist/calendars/discworld"),t("world-calendars/dist/calendars/ethiopian"),t("world-calendars/dist/calendars/hebrew"),t("world-calendars/dist/calendars/islamic"),t("world-calendars/dist/calendars/julian"),t("world-calendars/dist/calendars/mayan"),t("world-calendars/dist/calendars/nanakshahi"),t("world-calendars/dist/calendars/nepali"),t("world-calendars/dist/calendars/persian"),t("world-calendars/dist/calendars/taiwan"),t("world-calendars/dist/calendars/thai"),t("world-calendars/dist/calendars/ummalqura")},{"world-calendars/dist/calendars/chinese":538,"world-calendars/dist/calendars/coptic":539,"world-calendars/dist/calendars/discworld":540,"world-calendars/dist/calendars/ethiopian":541,"world-calendars/dist/calendars/hebrew":542,"world-calendars/dist/calendars/islamic":543,"world-calendars/dist/calendars/julian":544,"world-calendars/dist/calendars/mayan":545,"world-calendars/dist/calendars/nanakshahi":546,"world-calendars/dist/calendars/nepali":547,"world-calendars/dist/calendars/persian":548,"world-calendars/dist/calendars/taiwan":549,"world-calendars/dist/calendars/thai":550,"world-calendars/dist/calendars/ummalqura":551,"world-calendars/dist/main":552,"world-calendars/dist/plus":553}],572:[function(t,e,r){"use strict";var n=t("./calendars"),i=t("../../lib"),a=t("../../constants/numerical"),o=a.EPOCHJD,s=a.ONEDAY,l={valType:"enumerated",values:Object.keys(n.calendars),editType:"calc",dflt:"gregorian"},c=function(t,e,r,n){var a={};return a[r]=l,i.coerce(t,e,a,r,n)},u="##",h={d:{0:"dd","-":"d"},e:{0:"d","-":"d"},a:{0:"D","-":"D"},A:{0:"DD","-":"DD"},j:{0:"oo","-":"o"},W:{0:"ww","-":"w"},m:{0:"mm","-":"m"},b:{0:"M","-":"M"},B:{0:"MM","-":"MM"},y:{0:"yy","-":"yy"},Y:{0:"yyyy","-":"yyyy"},U:u,w:u,c:{0:"D M d %X yyyy","-":"D M d %X yyyy"},x:{0:"mm/dd/yyyy","-":"mm/dd/yyyy"}};var f={};function p(t){var e=f[t];return e||(e=f[t]=n.instance(t))}function d(t){return i.extendFlat({},l,{description:t})}function g(t){return"Sets the calendar system to use with `"+t+"` date data."}var v={xcalendar:d(g("x"))},m=i.extendFlat({},v,{ycalendar:d(g("y"))}),y=i.extendFlat({},m,{zcalendar:d(g("z"))}),x=d(["Sets the calendar system to use for `range` and `tick0`","if this is a date axis. This does not set the calendar for","interpreting data on this axis, that's specified in the trace","or via the global `layout.calendar`"].join(" "));e.exports={moduleType:"component",name:"calendars",schema:{traces:{scatter:m,bar:m,box:m,heatmap:m,contour:m,histogram:m,histogram2d:m,histogram2dcontour:m,scatter3d:y,surface:y,mesh3d:y,scattergl:m,ohlc:v,candlestick:v},layout:{calendar:d(["Sets the default calendar system to use for interpreting and","displaying dates throughout the plot."].join(" "))},subplots:{xaxis:{calendar:x},yaxis:{calendar:x},scene:{xaxis:{calendar:x},yaxis:{calendar:x},zaxis:{calendar:x}},polar:{radialaxis:{calendar:x}}},transforms:{filter:{valuecalendar:d(["Sets the calendar system to use for `value`, if it is a date."].join(" ")),targetcalendar:d(["Sets the calendar system to use for `target`, if it is an","array of dates. If `target` is a string (eg *x*) we use the","corresponding trace attribute (eg `xcalendar`) if it exists,","even if `targetcalendar` is provided."].join(" "))}}},layoutAttributes:l,handleDefaults:c,handleTraceDefaults:function(t,e,r,n){for(var i=0;i<r.length;i++)c(t,e,r[i]+"calendar",n.calendar)},CANONICAL_SUNDAY:{chinese:"2000-01-02",coptic:"2000-01-03",discworld:"2000-01-03",ethiopian:"2000-01-05",hebrew:"5000-01-01",islamic:"1000-01-02",julian:"2000-01-03",mayan:"5000-01-01",nanakshahi:"1000-01-05",nepali:"2000-01-05",persian:"1000-01-01",jalali:"1000-01-01",taiwan:"1000-01-04",thai:"2000-01-04",ummalqura:"1400-01-06"},CANONICAL_TICK:{chinese:"2000-01-01",coptic:"2000-01-01",discworld:"2000-01-01",ethiopian:"2000-01-01",hebrew:"5000-01-01",islamic:"1000-01-01",julian:"2000-01-01",mayan:"5000-01-01",nanakshahi:"1000-01-01",nepali:"2000-01-01",persian:"1000-01-01",jalali:"1000-01-01",taiwan:"1000-01-01",thai:"2000-01-01",ummalqura:"1400-01-01"},DFLTRANGE:{chinese:["2000-01-01","2001-01-01"],coptic:["1700-01-01","1701-01-01"],discworld:["1800-01-01","1801-01-01"],ethiopian:["2000-01-01","2001-01-01"],hebrew:["5700-01-01","5701-01-01"],islamic:["1400-01-01","1401-01-01"],julian:["2000-01-01","2001-01-01"],mayan:["5200-01-01","5201-01-01"],nanakshahi:["0500-01-01","0501-01-01"],nepali:["2000-01-01","2001-01-01"],persian:["1400-01-01","1401-01-01"],jalali:["1400-01-01","1401-01-01"],taiwan:["0100-01-01","0101-01-01"],thai:["2500-01-01","2501-01-01"],ummalqura:["1400-01-01","1401-01-01"]},getCal:p,worldCalFmt:function(t,e,r){for(var n,i,a,l,c,f=Math.floor((e+.05)/s)+o,d=p(r).fromJD(f),g=0;-1!==(g=t.indexOf("%",g));)"0"===(n=t.charAt(g+1))||"-"===n||"_"===n?(a=3,i=t.charAt(g+2),"_"===n&&(n="-")):(i=n,n="0",a=2),(l=h[i])?(c=l===u?u:d.formatDate(l[n]),t=t.substr(0,g)+c+t.substr(g+a),g+=c.length):g+=a;return t}}},{"../../constants/numerical":674,"../../lib":697,"./calendars":571}],573:[function(t,e,r){"use strict";r.defaults=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],r.defaultLine="#444",r.lightLine="#eee",r.background="#fff",r.borderLine="#BEC8D9",r.lightFraction=1e3/11},{}],574:[function(t,e,r){"use strict";var n=t("tinycolor2"),i=t("fast-isnumeric"),a=e.exports={},o=t("./attributes");a.defaults=o.defaults;var s=a.defaultLine=o.defaultLine;a.lightLine=o.lightLine;var l=a.background=o.background;function c(t){if(i(t)||"string"!=typeof t)return t;var e=t.trim();if("rgb"!==e.substr(0,3))return t;var r=e.match(/^rgba?\s*\(([^()]*)\)$/);if(!r)return t;var n=r[1].trim().split(/\s*[\s,]\s*/),a="a"===e.charAt(3)&&4===n.length;if(!a&&3!==n.length)return t;for(var o=0;o<n.length;o++){if(!n[o].length)return t;if(n[o]=Number(n[o]),!(n[o]>=0))return t;if(3===o)n[o]>1&&(n[o]=1);else if(n[o]>=1)return t}var s=Math.round(255*n[0])+", "+Math.round(255*n[1])+", "+Math.round(255*n[2]);return a?"rgba("+s+", "+n[3]+")":"rgb("+s+")"}a.tinyRGB=function(t){var e=t.toRgb();return"rgb("+Math.round(e.r)+", "+Math.round(e.g)+", "+Math.round(e.b)+")"},a.rgb=function(t){return a.tinyRGB(n(t))},a.opacity=function(t){return t?n(t).getAlpha():0},a.addOpacity=function(t,e){var r=n(t).toRgb();return"rgba("+Math.round(r.r)+", "+Math.round(r.g)+", "+Math.round(r.b)+", "+e+")"},a.combine=function(t,e){var r=n(t).toRgb();if(1===r.a)return n(t).toRgbString();var i=n(e||l).toRgb(),a=1===i.a?i:{r:255*(1-i.a)+i.r*i.a,g:255*(1-i.a)+i.g*i.a,b:255*(1-i.a)+i.b*i.a},o={r:a.r*(1-r.a)+r.r*r.a,g:a.g*(1-r.a)+r.g*r.a,b:a.b*(1-r.a)+r.b*r.a};return n(o).toRgbString()},a.contrast=function(t,e,r){var i=n(t);return 1!==i.getAlpha()&&(i=n(a.combine(t,l))),(i.isDark()?e?i.lighten(e):l:r?i.darken(r):s).toString()},a.stroke=function(t,e){var r=n(e);t.style({stroke:a.tinyRGB(r),"stroke-opacity":r.getAlpha()})},a.fill=function(t,e){var r=n(e);t.style({fill:a.tinyRGB(r),"fill-opacity":r.getAlpha()})},a.clean=function(t){if(t&&"object"==typeof t){var e,r,n,i,o=Object.keys(t);for(e=0;e<o.length;e++)if(i=t[n=o[e]],"color"===n.substr(n.length-5))if(Array.isArray(i))for(r=0;r<i.length;r++)i[r]=c(i[r]);else t[n]=c(i);else if("colorscale"===n.substr(n.length-10)&&Array.isArray(i))for(r=0;r<i.length;r++)Array.isArray(i[r])&&(i[r][1]=c(i[r][1]));else if(Array.isArray(i)){var s=i[0];if(!Array.isArray(s)&&s&&"object"==typeof s)for(r=0;r<i.length;r++)a.clean(i[r])}else i&&"object"==typeof i&&a.clean(i)}}},{"./attributes":573,"fast-isnumeric":218,tinycolor2:518}],575:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/layout_attributes"),i=t("../../plots/font_attributes"),a=t("../../lib/extend").extendFlat,o=t("../../plot_api/edit_types").overrideAll;e.exports=o({thicknessmode:{valType:"enumerated",values:["fraction","pixels"],dflt:"pixels"},thickness:{valType:"number",min:0,dflt:30},lenmode:{valType:"enumerated",values:["fraction","pixels"],dflt:"fraction"},len:{valType:"number",min:0,dflt:1},x:{valType:"number",dflt:1.02,min:-2,max:3},xanchor:{valType:"enumerated",values:["left","center","right"],dflt:"left"},xpad:{valType:"number",min:0,dflt:10},y:{valType:"number",dflt:.5,min:-2,max:3},yanchor:{valType:"enumerated",values:["top","middle","bottom"],dflt:"middle"},ypad:{valType:"number",min:0,dflt:10},outlinecolor:n.linecolor,outlinewidth:n.linewidth,bordercolor:n.linecolor,borderwidth:{valType:"number",min:0,dflt:0},bgcolor:{valType:"color",dflt:"rgba(0,0,0,0)"},tickmode:n.tickmode,nticks:n.nticks,tick0:n.tick0,dtick:n.dtick,tickvals:n.tickvals,ticktext:n.ticktext,ticks:a({},n.ticks,{dflt:""}),ticklen:n.ticklen,tickwidth:n.tickwidth,tickcolor:n.tickcolor,showticklabels:n.showticklabels,tickfont:i({}),tickangle:n.tickangle,tickformat:n.tickformat,tickformatstops:n.tickformatstops,tickprefix:n.tickprefix,showtickprefix:n.showtickprefix,ticksuffix:n.ticksuffix,showticksuffix:n.showticksuffix,separatethousands:n.separatethousands,exponentformat:n.exponentformat,showexponent:n.showexponent,title:{text:{valType:"string"},font:i({}),side:{valType:"enumerated",values:["right","top","bottom"],dflt:"top"}},_deprecated:{title:{valType:"string"},titlefont:i({}),titleside:{valType:"enumerated",values:["right","top","bottom"],dflt:"top"}}},"colorbars","from-root")},{"../../lib/extend":687,"../../plot_api/edit_types":728,"../../plots/cartesian/layout_attributes":757,"../../plots/font_attributes":771}],576:[function(t,e,r){"use strict";var n=t("./draw"),i=t("../colorscale/helpers").flipScale;e.exports=function(t,e,r){if("function"==typeof r)return r(t,e);var a=e[0].trace,o="cb"+a.uid;r=Array.isArray(r)?r:[r];for(var s=0;s<r.length;s++){var l=r[s].container,c=l?a[l]:a;if(t._fullLayout._infolayer.selectAll("."+o).remove(),c&&c.showscale){var u=e[0].t.cb=n(t,o),h=c.reversescale?i(c.colorscale):c.colorscale;return void u.fillgradient(h).zrange([c[r[s].min],c[r[s].max]]).options(c.colorbar)()}}}},{"../colorscale/helpers":585,"./draw":579}],577:[function(t,e,r){"use strict";e.exports={cn:{colorbar:"colorbar",cbbg:"cbbg",cbfill:"cbfill",cbfills:"cbfills",cbline:"cbline",cblines:"cblines",cbaxis:"cbaxis",cbtitleunshift:"cbtitleunshift",cbtitle:"cbtitle",cboutline:"cboutline",crisp:"crisp",jsPlaceholder:"js-placeholder"}}},{}],578:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plot_api/plot_template"),a=t("../../plots/cartesian/tick_value_defaults"),o=t("../../plots/cartesian/tick_mark_defaults"),s=t("../../plots/cartesian/tick_label_defaults"),l=t("./attributes");e.exports=function(t,e,r){var c=i.newContainer(e,"colorbar"),u=t.colorbar||{};function h(t,e){return n.coerce(u,c,l,t,e)}var f=h("thicknessmode");h("thickness","fraction"===f?30/(r.width-r.margin.l-r.margin.r):30);var p=h("lenmode");h("len","fraction"===p?1:r.height-r.margin.t-r.margin.b),h("x"),h("xanchor"),h("xpad"),h("y"),h("yanchor"),h("ypad"),n.noneOrAll(u,c,["x","y"]),h("outlinecolor"),h("outlinewidth"),h("bordercolor"),h("borderwidth"),h("bgcolor"),a(u,c,h,"linear");var d={outerTicks:!1,font:r.font};s(u,c,h,"linear",d),o(u,c,h,"linear",d),h("title.text",r._dfltTitle.colorbar),n.coerceFont(h,"title.font",r.font),h("title.side")}},{"../../lib":697,"../../plot_api/plot_template":735,"../../plots/cartesian/tick_label_defaults":764,"../../plots/cartesian/tick_mark_defaults":765,"../../plots/cartesian/tick_value_defaults":766,"./attributes":575}],579:[function(t,e,r){"use strict";var n=t("d3"),i=t("tinycolor2"),a=t("../../plots/plots"),o=t("../../registry"),s=t("../../plots/cartesian/axes"),l=t("../dragelement"),c=t("../../lib"),u=t("../../lib/extend").extendFlat,h=t("../../lib/setcursor"),f=t("../drawing"),p=t("../color"),d=t("../titles"),g=t("../../lib/svg_text_utils"),v=t("../../constants/alignment"),m=v.LINE_SPACING,y=v.FROM_TL,x=v.FROM_BR,b=t("../../plots/cartesian/axis_defaults"),_=t("../../plots/cartesian/position_defaults"),w=t("../../plots/cartesian/layout_attributes"),k=t("./attributes"),A=t("./constants").cn;e.exports=function(t,e){var r={};for(var v in k)r[v]=null;function M(){var v=t._fullLayout,k=v._size;if("function"==typeof r.fillcolor||"function"==typeof r.line.color||r.fillgradient){var E,C,L=r.zrange||n.extent(("function"==typeof r.fillcolor?r.fillcolor:r.line.color).domain()),z=[],O=[],I="function"==typeof r.line.color?r.line.color:function(){return r.line.color},D="function"==typeof r.fillcolor?r.fillcolor:function(){return r.fillcolor},P=r.levels.end+r.levels.size/100,R=r.levels.size,F=1.001*L[0]-.001*L[1],B=1.001*L[1]-.001*L[0];for(C=0;C<1e5&&(E=r.levels.start+C*R,!(R>0?E>=P:E<=P));C++)E>F&&E<B&&z.push(E);if(r.fillgradient)O=[0];else if("function"==typeof r.fillcolor)if(r.filllevels)for(P=r.filllevels.end+r.filllevels.size/100,R=r.filllevels.size,C=0;C<1e5&&(E=r.filllevels.start+C*R,!(R>0?E>=P:E<=P));C++)E>L[0]&&E<L[1]&&O.push(E);else(O=z.map(function(t){return t-r.levels.size/2})).push(O[O.length-1]+r.levels.size);else r.fillcolor&&"string"==typeof r.fillcolor&&(O=[0]);r.levels.size<0&&(z.reverse(),O.reverse());var N,j=k.h,V=k.w,U=Math.round(r.thickness*("fraction"===r.thicknessmode?V:1)),q=U/k.w,H=Math.round(r.len*("fraction"===r.lenmode?j:1)),G=H/k.h,Y=r.xpad/k.w,W=(r.borderwidth+r.outlinewidth)/2,X=r.ypad/k.h,Z=Math.round(r.x*k.w+r.xpad),$=r.x-q*({middle:.5,right:1}[r.xanchor]||0),J=r.y+G*(({top:-.5,bottom:.5}[r.yanchor]||0)-.5),K=Math.round(k.h*(1-J)),Q=K-H,tt={type:"linear",range:L,tickmode:r.tickmode,nticks:r.nticks,tick0:r.tick0,dtick:r.dtick,tickvals:r.tickvals,ticktext:r.ticktext,ticks:r.ticks,ticklen:r.ticklen,tickwidth:r.tickwidth,tickcolor:r.tickcolor,showticklabels:r.showticklabels,tickfont:r.tickfont,tickangle:r.tickangle,tickformat:r.tickformat,exponentformat:r.exponentformat,separatethousands:r.separatethousands,showexponent:r.showexponent,showtickprefix:r.showtickprefix,tickprefix:r.tickprefix,showticksuffix:r.showticksuffix,ticksuffix:r.ticksuffix,title:r.title,showline:!0,anchor:"free",side:"right",position:1},et={type:"linear",_id:"y"+e},rt={letter:"y",font:v.font,noHover:!0,noTickson:!0,calendar:v.calendar};if(b(tt,et,yt,rt,v),_(tt,et,yt,rt),et.position=r.x+Y+q,M.axis=et,-1!==["top","bottom"].indexOf(r.title.side)&&(et.title.side=r.title.side,et.titlex=r.x+Y,et.titley=J+("top"===r.title.side?G-X:X)),r.line.color&&"auto"===r.tickmode){et.tickmode="linear",et.tick0=r.levels.start;var nt=r.levels.size,it=c.constrain((K-Q)/50,4,15)+1,at=(L[1]-L[0])/((r.nticks||it)*nt);if(at>1){var ot=Math.pow(10,Math.floor(Math.log(at)/Math.LN10));nt*=ot*c.roundUp(at/ot,[2,5,10]),(Math.abs(r.levels.start)/r.levels.size+1e-6)%1<2e-6&&(et.tick0=0)}et.dtick=nt}et.domain=[J+X,J+G-X],et.setScale();var st=c.ensureSingle(v._infolayer,"g",e,function(t){t.classed(A.colorbar,!0).each(function(){var t=n.select(this);t.append("rect").classed(A.cbbg,!0),t.append("g").classed(A.cbfills,!0),t.append("g").classed(A.cblines,!0),t.append("g").classed(A.cbaxis,!0).classed(A.crisp,!0),t.append("g").classed(A.cbtitleunshift,!0).append("g").classed(A.cbtitle,!0),t.append("rect").classed(A.cboutline,!0),t.select(".cbtitle").datum(0)})});st.attr("transform","translate("+Math.round(k.l)+","+Math.round(k.t)+")");var lt=st.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(k.l)+",-"+Math.round(k.t)+")"),ct=st.select(".cbaxis"),ut=0;if(-1!==["top","bottom"].indexOf(r.title.side)){var ht,ft=k.l+(r.x+Y)*k.w,pt=et.title.font.size;ht="top"===r.title.side?(1-(J+G-X))*k.h+k.t+3+.75*pt:(1-(J+X))*k.h+k.t-3-.25*pt,xt(et._id+"title",{attributes:{x:ft,y:ht,"text-anchor":"start"}})}var dt,gt,vt,mt=c.syncOrAsync([a.previousPromises,function(){if(-1!==["top","bottom"].indexOf(r.title.side)){var a=st.select(".cbtitle"),o=a.select("text"),l=[-r.outlinewidth/2,r.outlinewidth/2],u=a.select(".h"+et._id+"title-math-group").node(),h=15.6;if(o.node()&&(h=parseInt(o.node().style.fontSize,10)*m),u?(ut=f.bBox(u).height)>h&&(l[1]-=(ut-h)/2):o.node()&&!o.classed(A.jsPlaceholder)&&(ut=f.bBox(o.node()).height),ut){if(ut+=5,"top"===r.title.side)et.domain[1]-=ut/k.h,l[1]*=-1;else{et.domain[0]+=ut/k.h;var p=g.lineCount(o);l[1]+=(1-p)*h}a.attr("transform","translate("+l+")"),et.setScale()}}st.selectAll(".cbfills,.cblines").attr("transform","translate(0,"+Math.round(k.h*(1-et.domain[1]))+")"),ct.attr("transform","translate(0,"+Math.round(-k.t)+")");var d=st.select(".cbfills").selectAll("rect.cbfill").data(O);d.enter().append("rect").classed(A.cbfill,!0).style("stroke","none"),d.exit().remove();var y=L.map(et.c2p).map(Math.round).sort(function(t,e){return t-e});d.each(function(a,o){var s=[0===o?L[0]:(O[o]+O[o-1])/2,o===O.length-1?L[1]:(O[o]+O[o+1])/2].map(et.c2p).map(Math.round);s[1]=c.constrain(s[1]+(s[1]>s[0])?1:-1,y[0],y[1]);var l=n.select(this).attr({x:Z,width:Math.max(U,2),y:n.min(s),height:Math.max(n.max(s)-n.min(s),2)});if(r.fillgradient)f.gradient(l,t,e,"vertical",r.fillgradient,"fill");else{var u=D(a).replace("e-","");l.attr("fill",i(u).toHexString())}});var x=st.select(".cblines").selectAll("path.cbline").data(r.line.color&&r.line.width?z:[]);return x.enter().append("path").classed(A.cbline,!0),x.exit().remove(),x.each(function(t){n.select(this).attr("d","M"+Z+","+(Math.round(et.c2p(t))+r.line.width/2%1)+"h"+U).call(f.lineGroupStyle,r.line.width,I(t),r.line.dash)}),ct.selectAll("g."+et._id+"tick,path").remove(),c.syncOrAsync([function(){var e=Z+U+(r.outlinewidth||0)/2-("outside"===r.ticks?1:0),n=s.calcTicks(et),i=s.makeTransFn(et),a=s.getTickSigns(et)[2];return s.drawTicks(t,et,{vals:"inside"===et.ticks?s.clipEnds(et,n):n,layer:ct,path:s.makeTickPath(et,e,a),transFn:i}),s.drawLabels(t,et,{vals:n,layer:ct,transFn:i,labelFns:s.makeLabelFns(et,e)})},function(){if(-1===["top","bottom"].indexOf(r.title.side)){var e=et.title.font.size,i=et._offset+et._length/2,a=k.l+(et.position||0)*k.w+("right"===et.side?10+e*(et.showticklabels?1:.5):-10-e*(et.showticklabels?.5:0));xt("h"+et._id+"title",{avoid:{selection:n.select(t).selectAll("g."+et._id+"tick"),side:r.title.side,offsetLeft:k.l,offsetTop:0,maxShift:v.width},attributes:{x:a,y:i,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])},a.previousPromises,function(){var n=U+r.outlinewidth/2+f.bBox(ct.node()).width;if((N=lt.select("text")).node()&&!N.classed(A.jsPlaceholder)){var i,o=lt.select(".h"+et._id+"title-math-group").node();i=o&&-1!==["top","bottom"].indexOf(r.title.side)?f.bBox(o).width:f.bBox(lt.node()).right-Z-k.l,n=Math.max(n,i)}var s=2*r.xpad+n+r.borderwidth+r.outlinewidth/2,l=K-Q;st.select(".cbbg").attr({x:Z-r.xpad-(r.borderwidth+r.outlinewidth)/2,y:Q-W,width:Math.max(s,2),height:Math.max(l+2*W,2)}).call(p.fill,r.bgcolor).call(p.stroke,r.bordercolor).style({"stroke-width":r.borderwidth}),st.selectAll(".cboutline").attr({x:Z,y:Q+r.ypad+("top"===r.title.side?ut:0),width:Math.max(U,2),height:Math.max(l-2*r.ypad-ut,2)}).call(p.stroke,r.outlinecolor).style({fill:"None","stroke-width":r.outlinewidth});var c=({center:.5,right:1}[r.xanchor]||0)*s;st.attr("transform","translate("+(k.l-c)+","+k.t+")");var u={},h=y[r.yanchor],d=x[r.yanchor];"pixels"===r.lenmode?(u.y=r.y,u.t=l*h,u.b=l*d):(u.t=u.b=0,u.yt=r.y+r.len*h,u.yb=r.y-r.len*d);var g=y[r.xanchor],v=x[r.xanchor];if("pixels"===r.thicknessmode)u.x=r.x,u.l=s*g,u.r=s*v;else{var m=s-U;u.l=m*g,u.r=m*v,u.xl=r.x-r.thickness*g,u.xr=r.x+r.thickness*v}a.autoMargin(t,e,u)}],t);if(mt&&mt.then&&(t._promises||[]).push(mt),t._context.edits.colorbarPosition)l.init({element:st.node(),gd:t,prepFn:function(){dt=st.attr("transform"),h(st)},moveFn:function(t,e){st.attr("transform",dt+" translate("+t+","+e+")"),gt=l.align($+t/k.w,q,0,1,r.xanchor),vt=l.align(J-e/k.h,G,0,1,r.yanchor);var n=l.getCursor(gt,vt,r.xanchor,r.yanchor);h(st,n)},doneFn:function(){if(h(st),void 0!==gt&&void 0!==vt){var e={};e[S("x")]=gt,e[S("y")]=vt,o.call("_guiRestyle",t,e,T().index)}}});return mt}function yt(t,e){return c.coerce(tt,et,w,t,e)}function xt(e,r){var n={propContainer:et,propName:S("title"),traceIndex:T().index,placeholder:v._dfltTitle.colorbar,containerGroup:st.select(".cbtitle")},i="h"===e.charAt(0)?e.substr(1):"h"+e;st.selectAll("."+i+",."+i+"-math-group").remove(),d.draw(t,e,u(n,r||{}))}v._infolayer.selectAll("g."+e).remove()}function T(){for(var r=e.substr(2),n=0;n<t._fullData.length;n++){var i=t._fullData[n];if(i.uid===r)return i}}function S(t){var e="colorbar.",r=T()._module.colorbar.container;return r&&(e=r+"."+e),e+t}return r.fillcolor=null,r.line={color:null,width:null,dash:null},r.levels={start:null,end:null,size:null},r.filllevels=null,r.fillgradient=null,r.zrange=null,Object.keys(r).forEach(function(t){M[t]=function(e){return arguments.length?(r[t]=c.isPlainObject(r[t])?c.extendFlat(r[t],e):e,M):r[t]}}),M.options=function(t){for(var e in t)"function"==typeof M[e]&&M[e](t[e]);return M},M._opts=r,M}},{"../../constants/alignment":669,"../../lib":697,"../../lib/extend":687,"../../lib/setcursor":717,"../../lib/svg_text_utils":721,"../../plots/cartesian/axes":745,"../../plots/cartesian/axis_defaults":747,"../../plots/cartesian/layout_attributes":757,"../../plots/cartesian/position_defaults":760,"../../plots/plots":807,"../../registry":826,"../color":574,"../dragelement":592,"../drawing":595,"../titles":662,"./attributes":575,"./constants":577,d3:151,tinycolor2:518}],580:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t){return n.isPlainObject(t.colorbar)}},{"../../lib":697}],581:[function(t,e,r){"use strict";var n=t("./scales.js").scales;Object.keys(n);function i(t){return"`"+t+"`"}e.exports=function(t,e){t=t||"";var r,a=(e=e||{}).cLetter||"c",o=("onlyIfNumerical"in e?e.onlyIfNumerical:Boolean(t),"noScale"in e?e.noScale:"marker.line"===t),s="showScaleDflt"in e?e.showScaleDflt:"z"===a,l="string"==typeof e.colorscaleDflt?n[e.colorscaleDflt]:null,c=e.editTypeOverride||"",u=t?t+".":"";"colorAttr"in e?(r=e.colorAttr,e.colorAttr):i(u+(r={z:"z",c:"color"}[a]));var h=a+"auto",f=a+"min",p=a+"max",d=a+"mid",g=(i(u+h),i(u+f),i(u+p),{});g[f]=g[p]=void 0;var v={};v[h]=!1;var m={};return"color"===r&&(m.color={valType:"color",arrayOk:!0,editType:c||"style"},e.anim&&(m.color.anim=!0)),m[h]={valType:"boolean",dflt:!0,editType:"calc",impliedEdits:g},m[f]={valType:"number",dflt:null,editType:c||"plot",impliedEdits:v},m[p]={valType:"number",dflt:null,editType:c||"plot",impliedEdits:v},m[d]={valType:"number",dflt:null,editType:"calc",impliedEdits:g},m.colorscale={valType:"colorscale",editType:"calc",dflt:l,impliedEdits:{autocolorscale:!1}},m.autocolorscale={valType:"boolean",dflt:!1!==e.autoColorDflt,editType:"calc",impliedEdits:{colorscale:void 0}},m.reversescale={valType:"boolean",dflt:!1,editType:"plot"},o||(m.showscale={valType:"boolean",dflt:s,editType:"calc"}),m}},{"./scales.js":589}],582:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e,r){var i=t._fullLayout,a=r.vals,o=r.containerStr,s=r.cLetter,l=o?n.nestedProperty(e,o).get():e,c=s+"min",u=s+"max",h=s+"mid",f=l[s+"auto"],p=l[c],d=l[u],g=l[h],v=l.colorscale;!1===f&&void 0!==p||(p=n.aggNums(Math.min,null,a)),!1===f&&void 0!==d||(d=n.aggNums(Math.max,null,a)),!1!==f&&void 0!==g&&(d-g>g-p?p=g-(d-g):d-g<g-p&&(d=g+(g-p))),p===d&&(p-=.5,d+=.5),l["_"+c]=l[c]=p,l["_"+u]=l[u]=d,l.autocolorscale&&(v=p*d<0?i.colorscale.diverging:p>=0?i.colorscale.sequential:i.colorscale.sequentialminus,l._colorscale=l.colorscale=v)}},{"../../lib":697}],583:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./helpers").hasColorscale;e.exports=function(t){function e(t,e){var r=t["_"+e];void 0!==r&&(t[e]=r)}function r(t,r){var i=r.container?n.nestedProperty(t,r.container).get():t;if(i){var a=i.zauto||i.cauto,o=r.min,s=r.max;(a||void 0===i[o])&&e(i,o),(a||void 0===i[s])&&e(i,s),i.autocolorscale&&e(i,"colorscale")}}for(var a=0;a<t.length;a++){var o=t[a],s=o._module.colorbar;if(s)if(Array.isArray(s))for(var l=0;l<s.length;l++)r(o,s[l]);else r(o,s);i(o,"marker.line")&&r(o,{container:"marker.line",min:"cmin",max:"cmax"}),i(o,"line")&&r(o,{container:"line",min:"cmin",max:"cmax"})}}},{"../../lib":697,"./helpers":585}],584:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("../colorbar/has_colorbar"),o=t("../colorbar/defaults"),s=t("./scales").isValid;function l(t,e){var r=e.slice(0,e.length-1);return e?i.nestedProperty(t,r).get()||{}:t}e.exports=function(t,e,r,i,c){var u=c.prefix,h=c.cLetter,f=l(t,u),p=l(e,u),d=l(e._template||{},u)||{},g=f[h+"min"],v=f[h+"max"];i(u+h+"auto",!(n(g)&&n(v)&&g<v))?i(u+h+"mid"):(i(u+h+"min"),i(u+h+"max"));var m,y,x=f.colorscale,b=d.colorscale;(void 0!==x&&(m=!s(x)),void 0!==b&&(m=!s(b)),i(u+"autocolorscale",m),i(u+"colorscale"),i(u+"reversescale"),c.noScale||"marker.line."===u)||(u&&(y=a(f)),i(u+"showscale",y)&&o(f,p,r))}},{"../../lib":697,"../colorbar/defaults":578,"../colorbar/has_colorbar":580,"./scales":589,"fast-isnumeric":218}],585:[function(t,e,r){"use strict";var n=t("d3"),i=t("tinycolor2"),a=t("fast-isnumeric"),o=t("../../lib"),s=t("../color"),l=t("./scales").isValid;function c(t){for(var e=t.length,r=new Array(e),n=e-1,i=0;n>=0;n--,i++){var a=t[n];r[i]=[1-a[0],a[1]]}return r}function u(t){var e={r:t[0],g:t[1],b:t[2],a:t[3]};return i(e).toRgbString()}e.exports={hasColorscale:function(t,e){var r=e?o.nestedProperty(t,e).get()||{}:t,n=r.color,i=!1;if(o.isArrayOrTypedArray(n))for(var s=0;s<n.length;s++)if(a(n[s])){i=!0;break}return o.isPlainObject(r)&&(i||!0===r.showscale||a(r.cmin)&&a(r.cmax)||l(r.colorscale)||o.isPlainObject(r.colorbar))},extractScale:function(t,e){for(var r=e.cLetter,n=t.reversescale?c(t.colorscale):t.colorscale,i=t[r+"min"],a=t[r+"max"],o=n.length,s=new Array(o),l=new Array(o),u=0;u<o;u++){var h=n[u];s[u]=i+h[0]*(a-i),l[u]=h[1]}return{domain:s,range:l}},flipScale:c,makeColorScaleFunc:function(t,e){e=e||{};for(var r=t.domain,o=t.range,l=o.length,c=new Array(l),h=0;h<l;h++){var f=i(o[h]).toRgb();c[h]=[f.r,f.g,f.b,f.a]}var p,d=n.scale.linear().domain(r).range(c).clamp(!0),g=e.noNumericCheck,v=e.returnArray;return(p=g&&v?d:g?function(t){return u(d(t))}:v?function(t){return a(t)?d(t):i(t).isValid()?t:s.defaultLine}:function(t){return a(t)?u(d(t)):i(t).isValid()?t:s.defaultLine}).domain=d.domain,p.range=function(){return o},p}}},{"../../lib":697,"../color":574,"./scales":589,d3:151,"fast-isnumeric":218,tinycolor2:518}],586:[function(t,e,r){"use strict";var n=t("./scales"),i=t("./helpers");e.exports={moduleType:"component",name:"colorscale",attributes:t("./attributes"),layoutAttributes:t("./layout_attributes"),supplyLayoutDefaults:t("./layout_defaults"),handleDefaults:t("./defaults"),crossTraceDefaults:t("./cross_trace_defaults"),calc:t("./calc"),scales:n.scales,defaultScale:n.defaultScale,getScale:n.get,isValidScale:n.isValid,hasColorscale:i.hasColorscale,flipScale:i.flipScale,extractScale:i.extractScale,makeColorScaleFunc:i.makeColorScaleFunc}},{"./attributes":581,"./calc":582,"./cross_trace_defaults":583,"./defaults":584,"./helpers":585,"./layout_attributes":587,"./layout_defaults":588,"./scales":589}],587:[function(t,e,r){"use strict";var n=t("./scales").scales;e.exports={editType:"calc",sequential:{valType:"colorscale",dflt:n.Reds,editType:"calc"},sequentialminus:{valType:"colorscale",dflt:n.Blues,editType:"calc"},diverging:{valType:"colorscale",dflt:n.RdBu,editType:"calc"}}},{"./scales":589}],588:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./layout_attributes"),a=t("../../plot_api/plot_template");e.exports=function(t,e){var r=t.colorscale,o=a.newContainer(e,"colorscale");function s(t,e){return n.coerce(r,o,i,t,e)}s("sequential"),s("sequentialminus"),s("diverging")}},{"../../lib":697,"../../plot_api/plot_template":735,"./layout_attributes":587}],589:[function(t,e,r){"use strict";var n=t("tinycolor2"),i={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]],Cividis:[[0,"rgb(0,32,76)"],[.058824,"rgb(0,42,102)"],[.117647,"rgb(0,52,110)"],[.176471,"rgb(39,63,108)"],[.235294,"rgb(60,74,107)"],[.294118,"rgb(76,85,107)"],[.352941,"rgb(91,95,109)"],[.411765,"rgb(104,106,112)"],[.470588,"rgb(117,117,117)"],[.529412,"rgb(131,129,120)"],[.588235,"rgb(146,140,120)"],[.647059,"rgb(161,152,118)"],[.705882,"rgb(176,165,114)"],[.764706,"rgb(192,177,109)"],[.823529,"rgb(209,191,102)"],[.882353,"rgb(225,204,92)"],[.941176,"rgb(243,219,79)"],[1,"rgb(255,233,69)"]]},a=i.RdBu;function o(t){var e=0;if(!Array.isArray(t)||t.length<2)return!1;if(!t[0]||!t[t.length-1])return!1;if(0!=+t[0][0]||1!=+t[t.length-1][0])return!1;for(var r=0;r<t.length;r++){var i=t[r];if(2!==i.length||+i[0]<e||!n(i[1]).isValid())return!1;e=+i[0]}return!0}e.exports={scales:i,defaultScale:a,get:function(t,e){if(e||(e=a),!t)return e;function r(){try{t=i[t]||JSON.parse(t)}catch(r){t=e}}return"string"==typeof t&&(r(),"string"==typeof t&&r()),o(t)?t:e},isValid:function(t){return void 0!==i[t]||o(t)}}},{tinycolor2:518}],590:[function(t,e,r){"use strict";e.exports=function(t,e,r,n,i){var a=(t-r)/(n-r),o=a+e/(n-r),s=(a+o)/2;return"left"===i||"bottom"===i?a:"center"===i||"middle"===i?s:"right"===i||"top"===i?o:a<2/3-s?a:o>4/3-s?o:s}},{}],591:[function(t,e,r){"use strict";var n=t("../../lib"),i=[["sw-resize","s-resize","se-resize"],["w-resize","move","e-resize"],["nw-resize","n-resize","ne-resize"]];e.exports=function(t,e,r,a){return t="left"===r?0:"center"===r?1:"right"===r?2:n.constrain(Math.floor(3*t),0,2),e="bottom"===a?0:"middle"===a?1:"top"===a?2:n.constrain(Math.floor(3*e),0,2),i[e][t]}},{"../../lib":697}],592:[function(t,e,r){"use strict";var n=t("mouse-event-offset"),i=t("has-hover"),a=t("has-passive-events"),o=t("../../registry"),s=t("../../lib"),l=t("../../plots/cartesian/constants"),c=t("../../constants/interactions"),u=e.exports={};u.align=t("./align"),u.getCursor=t("./cursor");var h=t("./unhover");function f(){var t=document.createElement("div");t.className="dragcover";var e=t.style;return e.position="fixed",e.left=0,e.right=0,e.top=0,e.bottom=0,e.zIndex=999999999,e.background="none",document.body.appendChild(t),t}function p(t){return n(t.changedTouches?t.changedTouches[0]:t,document.body)}u.unhover=h.wrapped,u.unhoverRaw=h.raw,u.init=function(t){var e,r,n,h,d,g,v,m,y=t.gd,x=1,b=c.DBLCLICKDELAY,_=t.element;y._mouseDownTime||(y._mouseDownTime=0),_.style.pointerEvents="all",_.onmousedown=k,a?(_._ontouchstart&&_.removeEventListener("touchstart",_._ontouchstart),_._ontouchstart=k,_.addEventListener("touchstart",k,{passive:!1})):_.ontouchstart=k;var w=t.clampFn||function(t,e,r){return Math.abs(t)<r&&(t=0),Math.abs(e)<r&&(e=0),[t,e]};function k(a){y._dragged=!1,y._dragging=!0;var o=p(a);e=o[0],r=o[1],v=a.target,g=a,m=2===a.buttons||a.ctrlKey,"undefined"==typeof a.clientX&&"undefined"==typeof a.clientY&&(a.clientX=e,a.clientY=r),(n=(new Date).getTime())-y._mouseDownTime<b?x+=1:(x=1,y._mouseDownTime=n),t.prepFn&&t.prepFn(a,e,r),i&&!m?(d=f()).style.cursor=window.getComputedStyle(_).cursor:i||(d=document,h=window.getComputedStyle(document.documentElement).cursor,document.documentElement.style.cursor=window.getComputedStyle(_).cursor),document.addEventListener("mouseup",M),document.addEventListener("touchend",M),!1!==t.dragmode&&(a.preventDefault(),document.addEventListener("mousemove",A),document.addEventListener("touchmove",A))}function A(n){n.preventDefault();var i=p(n),a=t.minDrag||l.MINDRAG,o=w(i[0]-e,i[1]-r,a),s=o[0],c=o[1];(s||c)&&(y._dragged=!0,u.unhover(y)),y._dragged&&t.moveFn&&!m&&t.moveFn(s,c)}function M(e){if(!1!==t.dragmode&&(e.preventDefault(),document.removeEventListener("mousemove",A),document.removeEventListener("touchmove",A)),document.removeEventListener("mouseup",M),document.removeEventListener("touchend",M),i?s.removeElement(d):h&&(d.documentElement.style.cursor=h,h=null),y._dragging){if(y._dragging=!1,(new Date).getTime()-y._mouseDownTime>b&&(x=Math.max(x-1,1)),y._dragged)t.doneFn&&t.doneFn();else if(t.clickFn&&t.clickFn(x,g),!m){var r;try{r=new MouseEvent("click",e)}catch(t){var n=p(e);(r=document.createEvent("MouseEvents")).initMouseEvent("click",e.bubbles,e.cancelable,e.view,e.detail,e.screenX,e.screenY,n[0],n[1],e.ctrlKey,e.altKey,e.shiftKey,e.metaKey,e.button,e.relatedTarget)}v.dispatchEvent(r)}!function(t){t._dragging=!1,t._replotPending&&o.call("plot",t)}(y),y._dragged=!1}else y._dragged=!1}},u.coverSlip=f},{"../../constants/interactions":673,"../../lib":697,"../../plots/cartesian/constants":751,"../../registry":826,"./align":590,"./cursor":591,"./unhover":593,"has-hover":399,"has-passive-events":400,"mouse-event-offset":425}],593:[function(t,e,r){"use strict";var n=t("../../lib/events"),i=t("../../lib/throttle"),a=t("../../lib/get_graph_div"),o=t("../fx/constants"),s=e.exports={};s.wrapped=function(t,e,r){(t=a(t))._fullLayout&&i.clear(t._fullLayout._uid+o.HOVERID),s.raw(t,e,r)},s.raw=function(t,e){var r=t._fullLayout,i=t._hoverdata;e||(e={}),e.target&&!1===n.triggerHandler(t,"plotly_beforehover",e)||(r._hoverlayer.selectAll("g").remove(),r._hoverlayer.selectAll("line").remove(),r._hoverlayer.selectAll("circle").remove(),t._hoverdata=void 0,e.target&&i&&t.emit("plotly_unhover",{event:e,points:i}))}},{"../../lib/events":686,"../../lib/get_graph_div":693,"../../lib/throttle":722,"../fx/constants":607}],594:[function(t,e,r){"use strict";r.dash={valType:"string",values:["solid","dot","dash","longdash","dashdot","longdashdot"],dflt:"solid",editType:"style"}},{}],595:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("tinycolor2"),o=t("../../registry"),s=t("../color"),l=t("../colorscale"),c=t("../../lib"),u=t("../../lib/svg_text_utils"),h=t("../../constants/xmlns_namespaces"),f=t("../../constants/alignment").LINE_SPACING,p=t("../../constants/interactions").DESELECTDIM,d=t("../../traces/scatter/subtypes"),g=t("../../traces/scatter/make_bubble_size_func"),v=e.exports={};v.font=function(t,e,r,n){c.isPlainObject(e)&&(n=e.color,r=e.size,e=e.family),e&&t.style("font-family",e),r+1&&t.style("font-size",r+"px"),n&&t.call(s.fill,n)},v.setPosition=function(t,e,r){t.attr("x",e).attr("y",r)},v.setSize=function(t,e,r){t.attr("width",e).attr("height",r)},v.setRect=function(t,e,r,n,i){t.call(v.setPosition,e,r).call(v.setSize,n,i)},v.translatePoint=function(t,e,r,n){var a=r.c2p(t.x),o=n.c2p(t.y);return!!(i(a)&&i(o)&&e.node())&&("text"===e.node().nodeName?e.attr("x",a).attr("y",o):e.attr("transform","translate("+a+","+o+")"),!0)},v.translatePoints=function(t,e,r){t.each(function(t){var i=n.select(this);v.translatePoint(t,i,e,r)})},v.hideOutsideRangePoint=function(t,e,r,n,i,a){e.attr("display",r.isPtWithinRange(t,i)&&n.isPtWithinRange(t,a)?null:"none")},v.hideOutsideRangePoints=function(t,e){if(e._hasClipOnAxisFalse){var r=e.xaxis,i=e.yaxis;t.each(function(e){var a=e[0].trace,o=a.xcalendar,s=a.ycalendar,l="bar"===a.type?".bartext":".point,.textpoint";t.selectAll(l).each(function(t){v.hideOutsideRangePoint(t,n.select(this),r,i,o,s)})})}},v.crispRound=function(t,e,r){return e&&i(e)?t._context.staticPlot?e:e<1?1:Math.round(e):r||0},v.singleLineStyle=function(t,e,r,n,i){e.style("fill","none");var a=(((t||[])[0]||{}).trace||{}).line||{},o=r||a.width||0,l=i||a.dash||"";s.stroke(e,n||a.color),v.dashLine(e,l,o)},v.lineGroupStyle=function(t,e,r,i){t.style("fill","none").each(function(t){var a=(((t||[])[0]||{}).trace||{}).line||{},o=e||a.width||0,l=i||a.dash||"";n.select(this).call(s.stroke,r||a.color).call(v.dashLine,l,o)})},v.dashLine=function(t,e,r){r=+r||0,e=v.dashStyle(e,r),t.style({"stroke-dasharray":e,"stroke-width":r+"px"})},v.dashStyle=function(t,e){e=+e||1;var r=Math.max(e,3);return"solid"===t?t="":"dot"===t?t=r+"px,"+r+"px":"dash"===t?t=3*r+"px,"+3*r+"px":"longdash"===t?t=5*r+"px,"+5*r+"px":"dashdot"===t?t=3*r+"px,"+r+"px,"+r+"px,"+r+"px":"longdashdot"===t&&(t=5*r+"px,"+2*r+"px,"+r+"px,"+2*r+"px"),t},v.singleFillStyle=function(t){var e=(((n.select(t.node()).data()[0]||[])[0]||{}).trace||{}).fillcolor;e&&t.call(s.fill,e)},v.fillGroupStyle=function(t){t.style("stroke-width",0).each(function(t){var e=n.select(this);t[0].trace&&e.call(s.fill,t[0].trace.fillcolor)})};var m=t("./symbol_defs");v.symbolNames=[],v.symbolFuncs=[],v.symbolNeedLines={},v.symbolNoDot={},v.symbolNoFill={},v.symbolList=[],Object.keys(m).forEach(function(t){var e=m[t];v.symbolList=v.symbolList.concat([e.n,t,e.n+100,t+"-open"]),v.symbolNames[e.n]=t,v.symbolFuncs[e.n]=e.f,e.needLine&&(v.symbolNeedLines[e.n]=!0),e.noDot?v.symbolNoDot[e.n]=!0:v.symbolList=v.symbolList.concat([e.n+200,t+"-dot",e.n+300,t+"-open-dot"]),e.noFill&&(v.symbolNoFill[e.n]=!0)});var y=v.symbolNames.length,x="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";function b(t,e){var r=t%100;return v.symbolFuncs[r](e)+(t>=200?x:"")}v.symbolNumber=function(t){if("string"==typeof t){var e=0;t.indexOf("-open")>0&&(e=100,t=t.replace("-open","")),t.indexOf("-dot")>0&&(e+=200,t=t.replace("-dot","")),(t=v.symbolNames.indexOf(t))>=0&&(t+=e)}return t%100>=y||t>=400?0:Math.floor(Math.max(t,0))};var _={x1:1,x2:0,y1:0,y2:0},w={x1:0,x2:0,y1:1,y2:0},k=n.format("~.1f"),A={radial:{node:"radialGradient"},radialreversed:{node:"radialGradient",reversed:!0},horizontal:{node:"linearGradient",attrs:_},horizontalreversed:{node:"linearGradient",attrs:_,reversed:!0},vertical:{node:"linearGradient",attrs:w},verticalreversed:{node:"linearGradient",attrs:w,reversed:!0}};v.gradient=function(t,e,r,i,o,l){for(var u=o.length,h=A[i],f=new Array(u),p=0;p<u;p++)h.reversed?f[u-1-p]=[k(100*(1-o[p][0])),o[p][1]]:f[p]=[k(100*o[p][0]),o[p][1]];var d="g"+e._fullLayout._uid+"-"+r,g=e._fullLayout._defs.select(".gradients").selectAll("#"+d).data([i+f.join(";")],c.identity);g.exit().remove(),g.enter().append(h.node).each(function(){var t=n.select(this);h.attrs&&t.attr(h.attrs),t.attr("id",d);var e=t.selectAll("stop").data(f);e.exit().remove(),e.enter().append("stop"),e.each(function(t){var e=a(t[1]);n.select(this).attr({offset:t[0]+"%","stop-color":s.tinyRGB(e),"stop-opacity":e.getAlpha()})})}),t.style(l,"url(#"+d+")").style(l+"-opacity",null)},v.initGradients=function(t){c.ensureSingle(t._fullLayout._defs,"g","gradients").selectAll("linearGradient,radialGradient").remove()},v.pointStyle=function(t,e,r){if(t.size()){var i=v.makePointStyleFns(e);t.each(function(t){v.singlePointStyle(t,n.select(this),e,i,r)})}},v.singlePointStyle=function(t,e,r,n,i){var a=r.marker,o=a.line;if(e.style("opacity",n.selectedOpacityFn?n.selectedOpacityFn(t):void 0===t.mo?a.opacity:t.mo),n.ms2mrc){var l;l="various"===t.ms||"various"===a.size?3:n.ms2mrc(t.ms),t.mrc=l,n.selectedSizeFn&&(l=t.mrc=n.selectedSizeFn(t));var u=v.symbolNumber(t.mx||a.symbol)||0;t.om=u%200>=100,e.attr("d",b(u,l))}var h,f,p,d=!1;if(t.so)p=o.outlierwidth,f=o.outliercolor,h=a.outliercolor;else{var g=(o||{}).width;p=(t.mlw+1||g+1||(t.trace?(t.trace.marker.line||{}).width:0)+1)-1||0,f="mlc"in t?t.mlcc=n.lineScale(t.mlc):c.isArrayOrTypedArray(o.color)?s.defaultLine:o.color,c.isArrayOrTypedArray(a.color)&&(h=s.defaultLine,d=!0),h="mc"in t?t.mcc=n.markerScale(t.mc):a.color||"rgba(0,0,0,0)",n.selectedColorFn&&(h=n.selectedColorFn(t))}if(t.om)e.call(s.stroke,h).style({"stroke-width":(p||1)+"px",fill:"none"});else{e.style("stroke-width",p+"px");var m=a.gradient,y=t.mgt;if(y?d=!0:y=m&&m.type,Array.isArray(y)&&(y=y[0],A[y]||(y=0)),y&&"none"!==y){var x=t.mgc;x?d=!0:x=m.color;var _=r.uid;d&&(_+="-"+t.i),v.gradient(e,i,_,y,[[0,x],[1,h]],"fill")}else s.fill(e,h);p&&s.stroke(e,f)}},v.makePointStyleFns=function(t){var e={},r=t.marker;return e.markerScale=v.tryColorscale(r,""),e.lineScale=v.tryColorscale(r,"line"),o.traceIs(t,"symbols")&&(e.ms2mrc=d.isBubble(t)?g(t):function(){return(r.size||6)/2}),t.selectedpoints&&c.extendFlat(e,v.makeSelectedPointStyleFns(t)),e},v.makeSelectedPointStyleFns=function(t){var e={},r=t.selected||{},n=t.unselected||{},i=t.marker||{},a=r.marker||{},s=n.marker||{},l=i.opacity,u=a.opacity,h=s.opacity,f=void 0!==u,d=void 0!==h;(c.isArrayOrTypedArray(l)||f||d)&&(e.selectedOpacityFn=function(t){var e=void 0===t.mo?i.opacity:t.mo;return t.selected?f?u:e:d?h:p*e});var g=i.color,v=a.color,m=s.color;(v||m)&&(e.selectedColorFn=function(t){var e=t.mcc||g;return t.selected?v||e:m||e});var y=i.size,x=a.size,b=s.size,_=void 0!==x,w=void 0!==b;return o.traceIs(t,"symbols")&&(_||w)&&(e.selectedSizeFn=function(t){var e=t.mrc||y/2;return t.selected?_?x/2:e:w?b/2:e}),e},v.makeSelectedTextStyleFns=function(t){var e={},r=t.selected||{},n=t.unselected||{},i=t.textfont||{},a=r.textfont||{},o=n.textfont||{},l=i.color,c=a.color,u=o.color;return e.selectedTextColorFn=function(t){var e=t.tc||l;return t.selected?c||e:u||(c?e:s.addOpacity(e,p))},e},v.selectedPointStyle=function(t,e){if(t.size()&&e.selectedpoints){var r=v.makeSelectedPointStyleFns(e),i=e.marker||{},a=[];r.selectedOpacityFn&&a.push(function(t,e){t.style("opacity",r.selectedOpacityFn(e))}),r.selectedColorFn&&a.push(function(t,e){s.fill(t,r.selectedColorFn(e))}),r.selectedSizeFn&&a.push(function(t,e){var n=e.mx||i.symbol||0,a=r.selectedSizeFn(e);t.attr("d",b(v.symbolNumber(n),a)),e.mrc2=a}),a.length&&t.each(function(t){for(var e=n.select(this),r=0;r<a.length;r++)a[r](e,t)})}},v.tryColorscale=function(t,e){var r=e?c.nestedProperty(t,e).get():t;if(r){var n=r.colorscale,i=r.color;if(n&&c.isArrayOrTypedArray(i))return l.makeColorScaleFunc(l.extractScale(r,{cLetter:"c"}))}return c.identity};var M={start:1,end:-1,middle:0,bottom:1,top:-1};function T(t,e,r,i){var a=n.select(t.node().parentNode),o=-1!==e.indexOf("top")?"top":-1!==e.indexOf("bottom")?"bottom":"middle",s=-1!==e.indexOf("left")?"end":-1!==e.indexOf("right")?"start":"middle",l=i?i/.8+1:0,c=(u.lineCount(t)-1)*f+1,h=M[s]*l,p=.75*r+M[o]*l+(M[o]-1)*c*r/2;t.attr("text-anchor",s),a.attr("transform","translate("+h+","+p+")")}function S(t,e){var r=t.ts||e.textfont.size;return i(r)&&r>0?r:0}v.textPointStyle=function(t,e,r){if(t.size()){var i;if(e.selectedpoints){var a=v.makeSelectedTextStyleFns(e);i=a.selectedTextColorFn}t.each(function(t){var a=n.select(this),o=c.extractOption(t,e,"tx","text");if(o||0===o){var s=t.tp||e.textposition,l=S(t,e),h=i?i(t):t.tc||e.textfont.color;a.call(v.font,t.tf||e.textfont.family,l,h).text(o).call(u.convertToTspans,r).call(T,s,l,t.mrc)}else a.remove()})}},v.selectedTextStyle=function(t,e){if(t.size()&&e.selectedpoints){var r=v.makeSelectedTextStyleFns(e);t.each(function(t){var i=n.select(this),a=r.selectedTextColorFn(t),o=t.tp||e.textposition,l=S(t,e);s.fill(i,a),T(i,o,l,t.mrc2||t.mrc)})}};var E=.5;function C(t,e,r,i){var a=t[0]-e[0],o=t[1]-e[1],s=r[0]-e[0],l=r[1]-e[1],c=Math.pow(a*a+o*o,E/2),u=Math.pow(s*s+l*l,E/2),h=(u*u*a-c*c*s)*i,f=(u*u*o-c*c*l)*i,p=3*u*(c+u),d=3*c*(c+u);return[[n.round(e[0]+(p&&h/p),2),n.round(e[1]+(p&&f/p),2)],[n.round(e[0]-(d&&h/d),2),n.round(e[1]-(d&&f/d),2)]]}v.smoothopen=function(t,e){if(t.length<3)return"M"+t.join("L");var r,n="M"+t[0],i=[];for(r=1;r<t.length-1;r++)i.push(C(t[r-1],t[r],t[r+1],e));for(n+="Q"+i[0][0]+" "+t[1],r=2;r<t.length-1;r++)n+="C"+i[r-2][1]+" "+i[r-1][0]+" "+t[r];return n+="Q"+i[t.length-3][1]+" "+t[t.length-1]},v.smoothclosed=function(t,e){if(t.length<3)return"M"+t.join("L")+"Z";var r,n="M"+t[0],i=t.length-1,a=[C(t[i],t[0],t[1],e)];for(r=1;r<i;r++)a.push(C(t[r-1],t[r],t[r+1],e));for(a.push(C(t[i-1],t[i],t[0],e)),r=1;r<=i;r++)n+="C"+a[r-1][1]+" "+a[r][0]+" "+t[r];return n+="C"+a[i][1]+" "+a[0][0]+" "+t[0]+"Z"};var L={hv:function(t,e){return"H"+n.round(e[0],2)+"V"+n.round(e[1],2)},vh:function(t,e){return"V"+n.round(e[1],2)+"H"+n.round(e[0],2)},hvh:function(t,e){return"H"+n.round((t[0]+e[0])/2,2)+"V"+n.round(e[1],2)+"H"+n.round(e[0],2)},vhv:function(t,e){return"V"+n.round((t[1]+e[1])/2,2)+"H"+n.round(e[0],2)+"V"+n.round(e[1],2)}},z=function(t,e){return"L"+n.round(e[0],2)+","+n.round(e[1],2)};v.steps=function(t){var e=L[t]||z;return function(t){for(var r="M"+n.round(t[0][0],2)+","+n.round(t[0][1],2),i=1;i<t.length;i++)r+=e(t[i-1],t[i]);return r}},v.makeTester=function(){var t=c.ensureSingleById(n.select("body"),"svg","js-plotly-tester",function(t){t.attr(h.svgAttrs).style({position:"absolute",left:"-10000px",top:"-10000px",width:"9000px",height:"9000px","z-index":"1"})}),e=c.ensureSingle(t,"path","js-reference-point",function(t){t.attr("d","M0,0H1V1H0Z").style({"stroke-width":0,fill:"black"})});v.tester=t,v.testref=e},v.savedBBoxes={};var O=0;function I(t){var e=t.getAttribute("data-unformatted");if(null!==e)return e+t.getAttribute("data-math")+t.getAttribute("text-anchor")+t.getAttribute("style")}v.bBox=function(t,e,r){var i,a,o;if(r||(r=I(t)),r){if(i=v.savedBBoxes[r])return c.extendFlat({},i)}else if(1===t.childNodes.length){var s=t.childNodes[0];if(r=I(s)){var l=+s.getAttribute("x")||0,h=+s.getAttribute("y")||0,f=s.getAttribute("transform");if(!f){var p=v.bBox(s,!1,r);return l&&(p.left+=l,p.right+=l),h&&(p.top+=h,p.bottom+=h),p}if(r+="~"+l+"~"+h+"~"+f,i=v.savedBBoxes[r])return c.extendFlat({},i)}}e?a=t:(o=v.tester.node(),a=t.cloneNode(!0),o.appendChild(a)),n.select(a).attr("transform",null).call(u.positionText,0,0);var d=a.getBoundingClientRect(),g=v.testref.node().getBoundingClientRect();e||o.removeChild(a);var m={height:d.height,width:d.width,left:d.left-g.left,top:d.top-g.top,right:d.right-g.left,bottom:d.bottom-g.top};return O>=1e4&&(v.savedBBoxes={},O=0),r&&(v.savedBBoxes[r]=m),O++,c.extendFlat({},m)},v.setClipUrl=function(t,e,r){if(e){var n=r._context,i=n._exportedPlot?"":n._baseUrl||"";t.attr("clip-path","url("+i+"#"+e+")")}else t.attr("clip-path",null)},v.getTranslate=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||0,y:+e[1]||0}},v.setTranslate=function(t,e,r){var n=t.attr?"attr":"getAttribute",i=t.attr?"attr":"setAttribute",a=t[n]("transform")||"";return e=e||0,r=r||0,a=a.replace(/(\btranslate\(.*?\);?)/,"").trim(),a=(a+=" translate("+e+", "+r+")").trim(),t[i]("transform",a),a},v.getScale=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||1,y:+e[1]||1}},v.setScale=function(t,e,r){var n=t.attr?"attr":"getAttribute",i=t.attr?"attr":"setAttribute",a=t[n]("transform")||"";return e=e||1,r=r||1,a=a.replace(/(\bscale\(.*?\);?)/,"").trim(),a=(a+=" scale("+e+", "+r+")").trim(),t[i]("transform",a),a};var D=/\s*sc.*/;v.setPointGroupScale=function(t,e,r){if(e=e||1,r=r||1,t){var n=1===e&&1===r?"":" scale("+e+","+r+")";t.each(function(){var t=(this.getAttribute("transform")||"").replace(D,"");t=(t+=n).trim(),this.setAttribute("transform",t)})}};var P=/translate\([^)]*\)\s*$/;v.setTextPointsScale=function(t,e,r){t&&t.each(function(){var t,i=n.select(this),a=i.select("text");if(a.node()){var o=parseFloat(a.attr("x")||0),s=parseFloat(a.attr("y")||0),l=(i.attr("transform")||"").match(P);t=1===e&&1===r?[]:["translate("+o+","+s+")","scale("+e+","+r+")","translate("+-o+","+-s+")"],l&&t.push(l),i.attr("transform",t.join(" "))}})}},{"../../constants/alignment":669,"../../constants/interactions":673,"../../constants/xmlns_namespaces":675,"../../lib":697,"../../lib/svg_text_utils":721,"../../registry":826,"../../traces/scatter/make_bubble_size_func":1065,"../../traces/scatter/subtypes":1072,"../color":574,"../colorscale":586,"./symbol_defs":596,d3:151,"fast-isnumeric":218,tinycolor2:518}],596:[function(t,e,r){"use strict";var n=t("d3");e.exports={circle:{n:0,f:function(t){var e=n.round(t,2);return"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"}},square:{n:1,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"}},diamond:{n:2,f:function(t){var e=n.round(1.3*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"Z"}},cross:{n:3,f:function(t){var e=n.round(.4*t,2),r=n.round(1.2*t,2);return"M"+r+","+e+"H"+e+"V"+r+"H-"+e+"V"+e+"H-"+r+"V-"+e+"H-"+e+"V-"+r+"H"+e+"V-"+e+"H"+r+"Z"}},x:{n:4,f:function(t){var e=n.round(.8*t/Math.sqrt(2),2),r="l"+e+","+e,i="l"+e+",-"+e,a="l-"+e+",-"+e,o="l-"+e+","+e;return"M0,"+e+r+i+a+i+a+o+a+o+r+o+r+"Z"}},"triangle-up":{n:5,f:function(t){var e=n.round(2*t/Math.sqrt(3),2);return"M-"+e+","+n.round(t/2,2)+"H"+e+"L0,-"+n.round(t,2)+"Z"}},"triangle-down":{n:6,f:function(t){var e=n.round(2*t/Math.sqrt(3),2);return"M-"+e+",-"+n.round(t/2,2)+"H"+e+"L0,"+n.round(t,2)+"Z"}},"triangle-left":{n:7,f:function(t){var e=n.round(2*t/Math.sqrt(3),2);return"M"+n.round(t/2,2)+",-"+e+"V"+e+"L-"+n.round(t,2)+",0Z"}},"triangle-right":{n:8,f:function(t){var e=n.round(2*t/Math.sqrt(3),2);return"M-"+n.round(t/2,2)+",-"+e+"V"+e+"L"+n.round(t,2)+",0Z"}},"triangle-ne":{n:9,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M-"+r+",-"+e+"H"+e+"V"+r+"Z"}},"triangle-se":{n:10,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M"+e+",-"+r+"V"+e+"H-"+r+"Z"}},"triangle-sw":{n:11,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M"+r+","+e+"H-"+e+"V-"+r+"Z"}},"triangle-nw":{n:12,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M-"+e+","+r+"V-"+e+"H"+r+"Z"}},pentagon:{n:13,f:function(t){var e=n.round(.951*t,2),r=n.round(.588*t,2),i=n.round(-t,2),a=n.round(-.309*t,2);return"M"+e+","+a+"L"+r+","+n.round(.809*t,2)+"H-"+r+"L-"+e+","+a+"L0,"+i+"Z"}},hexagon:{n:14,f:function(t){var e=n.round(t,2),r=n.round(t/2,2),i=n.round(t*Math.sqrt(3)/2,2);return"M"+i+",-"+r+"V"+r+"L0,"+e+"L-"+i+","+r+"V-"+r+"L0,-"+e+"Z"}},hexagon2:{n:15,f:function(t){var e=n.round(t,2),r=n.round(t/2,2),i=n.round(t*Math.sqrt(3)/2,2);return"M-"+r+","+i+"H"+r+"L"+e+",0L"+r+",-"+i+"H-"+r+"L-"+e+",0Z"}},octagon:{n:16,f:function(t){var e=n.round(.924*t,2),r=n.round(.383*t,2);return"M-"+r+",-"+e+"H"+r+"L"+e+",-"+r+"V"+r+"L"+r+","+e+"H-"+r+"L-"+e+","+r+"V-"+r+"Z"}},star:{n:17,f:function(t){var e=1.4*t,r=n.round(.225*e,2),i=n.round(.951*e,2),a=n.round(.363*e,2),o=n.round(.588*e,2),s=n.round(-e,2),l=n.round(-.309*e,2),c=n.round(.118*e,2),u=n.round(.809*e,2);return"M"+r+","+l+"H"+i+"L"+a+","+c+"L"+o+","+u+"L0,"+n.round(.382*e,2)+"L-"+o+","+u+"L-"+a+","+c+"L-"+i+","+l+"H-"+r+"L0,"+s+"Z"}},hexagram:{n:18,f:function(t){var e=n.round(.66*t,2),r=n.round(.38*t,2),i=n.round(.76*t,2);return"M-"+i+",0l-"+r+",-"+e+"h"+i+"l"+r+",-"+e+"l"+r+","+e+"h"+i+"l-"+r+","+e+"l"+r+","+e+"h-"+i+"l-"+r+","+e+"l-"+r+",-"+e+"h-"+i+"Z"}},"star-triangle-up":{n:19,f:function(t){var e=n.round(t*Math.sqrt(3)*.8,2),r=n.round(.8*t,2),i=n.round(1.6*t,2),a=n.round(4*t,2),o="A "+a+","+a+" 0 0 1 ";return"M-"+e+","+r+o+e+","+r+o+"0,-"+i+o+"-"+e+","+r+"Z"}},"star-triangle-down":{n:20,f:function(t){var e=n.round(t*Math.sqrt(3)*.8,2),r=n.round(.8*t,2),i=n.round(1.6*t,2),a=n.round(4*t,2),o="A "+a+","+a+" 0 0 1 ";return"M"+e+",-"+r+o+"-"+e+",-"+r+o+"0,"+i+o+e+",-"+r+"Z"}},"star-square":{n:21,f:function(t){var e=n.round(1.1*t,2),r=n.round(2*t,2),i="A "+r+","+r+" 0 0 1 ";return"M-"+e+",-"+e+i+"-"+e+","+e+i+e+","+e+i+e+",-"+e+i+"-"+e+",-"+e+"Z"}},"star-diamond":{n:22,f:function(t){var e=n.round(1.4*t,2),r=n.round(1.9*t,2),i="A "+r+","+r+" 0 0 1 ";return"M-"+e+",0"+i+"0,"+e+i+e+",0"+i+"0,-"+e+i+"-"+e+",0Z"}},"diamond-tall":{n:23,f:function(t){var e=n.round(.7*t,2),r=n.round(1.4*t,2);return"M0,"+r+"L"+e+",0L0,-"+r+"L-"+e+",0Z"}},"diamond-wide":{n:24,f:function(t){var e=n.round(1.4*t,2),r=n.round(.7*t,2);return"M0,"+r+"L"+e+",0L0,-"+r+"L-"+e+",0Z"}},hourglass:{n:25,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"H-"+e+"L"+e+",-"+e+"H-"+e+"Z"},noDot:!0},bowtie:{n:26,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"V-"+e+"L-"+e+","+e+"V-"+e+"Z"},noDot:!0},"circle-cross":{n:27,f:function(t){var e=n.round(t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"},needLine:!0,noDot:!0},"circle-x":{n:28,f:function(t){var e=n.round(t,2),r=n.round(t/Math.sqrt(2),2);return"M"+r+","+r+"L-"+r+",-"+r+"M"+r+",-"+r+"L-"+r+","+r+"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"},needLine:!0,noDot:!0},"square-cross":{n:29,f:function(t){var e=n.round(t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"},needLine:!0,noDot:!0},"square-x":{n:30,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e+"M"+e+",-"+e+"L-"+e+","+e+"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"},needLine:!0,noDot:!0},"diamond-cross":{n:31,f:function(t){var e=n.round(1.3*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"ZM0,-"+e+"V"+e+"M-"+e+",0H"+e},needLine:!0,noDot:!0},"diamond-x":{n:32,f:function(t){var e=n.round(1.3*t,2),r=n.round(.65*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"ZM-"+r+",-"+r+"L"+r+","+r+"M-"+r+","+r+"L"+r+",-"+r},needLine:!0,noDot:!0},"cross-thin":{n:33,f:function(t){var e=n.round(1.4*t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e},needLine:!0,noDot:!0,noFill:!0},"x-thin":{n:34,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e+"M"+e+",-"+e+"L-"+e+","+e},needLine:!0,noDot:!0,noFill:!0},asterisk:{n:35,f:function(t){var e=n.round(1.2*t,2),r=n.round(.85*t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+r+","+r+"L-"+r+",-"+r+"M"+r+",-"+r+"L-"+r+","+r},needLine:!0,noDot:!0,noFill:!0},hash:{n:36,f:function(t){var e=n.round(t/2,2),r=n.round(t,2);return"M"+e+","+r+"V-"+r+"m-"+r+",0V"+r+"M"+r+","+e+"H-"+r+"m0,-"+r+"H"+r},needLine:!0,noFill:!0},"y-up":{n:37,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M-"+e+","+i+"L0,0M"+e+","+i+"L0,0M0,-"+r+"L0,0"},needLine:!0,noDot:!0,noFill:!0},"y-down":{n:38,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M-"+e+",-"+i+"L0,0M"+e+",-"+i+"L0,0M0,"+r+"L0,0"},needLine:!0,noDot:!0,noFill:!0},"y-left":{n:39,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M"+i+","+e+"L0,0M"+i+",-"+e+"L0,0M-"+r+",0L0,0"},needLine:!0,noDot:!0,noFill:!0},"y-right":{n:40,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M-"+i+","+e+"L0,0M-"+i+",-"+e+"L0,0M"+r+",0L0,0"},needLine:!0,noDot:!0,noFill:!0},"line-ew":{n:41,f:function(t){var e=n.round(1.4*t,2);return"M"+e+",0H-"+e},needLine:!0,noDot:!0,noFill:!0},"line-ns":{n:42,f:function(t){var e=n.round(1.4*t,2);return"M0,"+e+"V-"+e},needLine:!0,noDot:!0,noFill:!0},"line-ne":{n:43,f:function(t){var e=n.round(t,2);return"M"+e+",-"+e+"L-"+e+","+e},needLine:!0,noDot:!0,noFill:!0},"line-nw":{n:44,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e},needLine:!0,noDot:!0,noFill:!0}}},{d3:151}],597:[function(t,e,r){"use strict";e.exports={visible:{valType:"boolean",editType:"calc"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"],editType:"calc"},symmetric:{valType:"boolean",editType:"calc"},array:{valType:"data_array",editType:"calc"},arrayminus:{valType:"data_array",editType:"calc"},value:{valType:"number",min:0,dflt:10,editType:"calc"},valueminus:{valType:"number",min:0,dflt:10,editType:"calc"},traceref:{valType:"integer",min:0,dflt:0,editType:"style"},tracerefminus:{valType:"integer",min:0,dflt:0,editType:"style"},copy_ystyle:{valType:"boolean",editType:"plot"},copy_zstyle:{valType:"boolean",editType:"style"},color:{valType:"color",editType:"style"},thickness:{valType:"number",min:0,dflt:2,editType:"style"},width:{valType:"number",min:0,editType:"plot"},editType:"calc",_deprecated:{opacity:{valType:"number",editType:"style"}}}},{}],598:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../registry"),a=t("../../plots/cartesian/axes"),o=t("../../lib"),s=t("./compute_error");function l(t,e,r,i){var l=e["error_"+i]||{},c=[];if(l.visible&&-1!==["linear","log"].indexOf(r.type)){for(var u=s(l),h=0;h<t.length;h++){var f=t[h],p=f.i;if(void 0===p)p=h;else if(null===p)continue;var d=f[i];if(n(r.c2l(d))){var g=u(d,p);if(n(g[0])&&n(g[1])){var v=f[i+"s"]=d-g[0],m=f[i+"h"]=d+g[1];c.push(v,m)}}}var y=r._id,x=e._extremes[y],b=a.findExtremes(r,c,o.extendFlat({tozero:x.opts.tozero},{padded:!0}));x.min=x.min.concat(b.min),x.max=x.max.concat(b.max)}}e.exports=function(t){for(var e=t.calcdata,r=0;r<e.length;r++){var n=e[r],o=n[0].trace;if(!0===o.visible&&i.traceIs(o,"errorBarsOK")){var s=a.getFromId(t,o.xaxis),c=a.getFromId(t,o.yaxis);l(n,o,s,"x"),l(n,o,c,"y")}}}},{"../../lib":697,"../../plots/cartesian/axes":745,"../../registry":826,"./compute_error":599,"fast-isnumeric":218}],599:[function(t,e,r){"use strict";function n(t,e){return"percent"===t?function(t){return Math.abs(t*e/100)}:"constant"===t?function(){return Math.abs(e)}:"sqrt"===t?function(t){return Math.sqrt(Math.abs(t))}:void 0}e.exports=function(t){var e=t.type,r=t.symmetric;if("data"===e){var i=t.array||[];if(r)return function(t,e){var r=+i[e];return[r,r]};var a=t.arrayminus||[];return function(t,e){var r=+i[e],n=+a[e];return isNaN(r)&&isNaN(n)?[NaN,NaN]:[n||0,r||0]}}var o=n(e,t.value),s=n(e,t.valueminus);return r||void 0===t.valueminus?function(t){var e=o(t);return[e,e]}:function(t){return[s(t),o(t)]}}},{}],600:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../registry"),a=t("../../lib"),o=t("../../plot_api/plot_template"),s=t("./attributes");e.exports=function(t,e,r,l){var c="error_"+l.axis,u=o.newContainer(e,c),h=t[c]||{};function f(t,e){return a.coerce(h,u,s,t,e)}if(!1!==f("visible",void 0!==h.array||void 0!==h.value||"sqrt"===h.type)){var p=f("type","array"in h?"data":"percent"),d=!0;"sqrt"!==p&&(d=f("symmetric",!(("data"===p?"arrayminus":"valueminus")in h))),"data"===p?(f("array"),f("traceref"),d||(f("arrayminus"),f("tracerefminus"))):"percent"!==p&&"constant"!==p||(f("value"),d||f("valueminus"));var g="copy_"+l.inherit+"style";if(l.inherit)(e["error_"+l.inherit]||{}).visible&&f(g,!(h.color||n(h.thickness)||n(h.width)));l.inherit&&u[g]||(f("color",r),f("thickness"),f("width",i.traceIs(e,"gl3d")?0:4))}}},{"../../lib":697,"../../plot_api/plot_template":735,"../../registry":826,"./attributes":597,"fast-isnumeric":218}],601:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plot_api/edit_types").overrideAll,a=t("./attributes"),o={error_x:n.extendFlat({},a),error_y:n.extendFlat({},a)};delete o.error_x.copy_zstyle,delete o.error_y.copy_zstyle,delete o.error_y.copy_ystyle;var s={error_x:n.extendFlat({},a),error_y:n.extendFlat({},a),error_z:n.extendFlat({},a)};delete s.error_x.copy_ystyle,delete s.error_y.copy_ystyle,delete s.error_z.copy_ystyle,delete s.error_z.copy_zstyle,e.exports={moduleType:"component",name:"errorbars",schema:{traces:{scatter:o,bar:o,histogram:o,scatter3d:i(s,"calc","nested"),scattergl:i(o,"calc","nested")}},supplyDefaults:t("./defaults"),calc:t("./calc"),makeComputeError:t("./compute_error"),plot:t("./plot"),style:t("./style"),hoverInfo:function(t,e,r){(e.error_y||{}).visible&&(r.yerr=t.yh-t.y,e.error_y.symmetric||(r.yerrneg=t.y-t.ys));(e.error_x||{}).visible&&(r.xerr=t.xh-t.x,e.error_x.symmetric||(r.xerrneg=t.x-t.xs))}}},{"../../lib":697,"../../plot_api/edit_types":728,"./attributes":597,"./calc":598,"./compute_error":599,"./defaults":600,"./plot":602,"./style":603}],602:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../drawing"),o=t("../../traces/scatter/subtypes");e.exports=function(t,e,r,s){var l=r.xaxis,c=r.yaxis,u=s&&s.duration>0;e.each(function(e){var h,f=e[0].trace,p=f.error_x||{},d=f.error_y||{};f.ids&&(h=function(t){return t.id});var g=o.hasMarkers(f)&&f.marker.maxdisplayed>0;d.visible||p.visible||(e=[]);var v=n.select(this).selectAll("g.errorbar").data(e,h);if(v.exit().remove(),e.length){p.visible||v.selectAll("path.xerror").remove(),d.visible||v.selectAll("path.yerror").remove(),v.style("opacity",1);var m=v.enter().append("g").classed("errorbar",!0);u&&m.style("opacity",0).transition().duration(s.duration).style("opacity",1),a.setClipUrl(v,r.layerClipId,t),v.each(function(t){var e=n.select(this),r=function(t,e,r){var n={x:e.c2p(t.x),y:r.c2p(t.y)};void 0!==t.yh&&(n.yh=r.c2p(t.yh),n.ys=r.c2p(t.ys),i(n.ys)||(n.noYS=!0,n.ys=r.c2p(t.ys,!0)));void 0!==t.xh&&(n.xh=e.c2p(t.xh),n.xs=e.c2p(t.xs),i(n.xs)||(n.noXS=!0,n.xs=e.c2p(t.xs,!0)));return n}(t,l,c);if(!g||t.vis){var a,o=e.select("path.yerror");if(d.visible&&i(r.x)&&i(r.yh)&&i(r.ys)){var h=d.width;a="M"+(r.x-h)+","+r.yh+"h"+2*h+"m-"+h+",0V"+r.ys,r.noYS||(a+="m-"+h+",0h"+2*h),!o.size()?o=e.append("path").style("vector-effect","non-scaling-stroke").classed("yerror",!0):u&&(o=o.transition().duration(s.duration).ease(s.easing)),o.attr("d",a)}else o.remove();var f=e.select("path.xerror");if(p.visible&&i(r.y)&&i(r.xh)&&i(r.xs)){var v=(p.copy_ystyle?d:p).width;a="M"+r.xh+","+(r.y-v)+"v"+2*v+"m0,-"+v+"H"+r.xs,r.noXS||(a+="m0,-"+v+"v"+2*v),!f.size()?f=e.append("path").style("vector-effect","non-scaling-stroke").classed("xerror",!0):u&&(f=f.transition().duration(s.duration).ease(s.easing)),f.attr("d",a)}else f.remove()}})}})}},{"../../traces/scatter/subtypes":1072,"../drawing":595,d3:151,"fast-isnumeric":218}],603:[function(t,e,r){"use strict";var n=t("d3"),i=t("../color");e.exports=function(t){t.each(function(t){var e=t[0].trace,r=e.error_y||{},a=e.error_x||{},o=n.select(this);o.selectAll("path.yerror").style("stroke-width",r.thickness+"px").call(i.stroke,r.color),a.copy_ystyle&&(a=r),o.selectAll("path.xerror").style("stroke-width",a.thickness+"px").call(i.stroke,a.color)})}},{"../color":574,d3:151}],604:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes");e.exports={hoverlabel:{bgcolor:{valType:"color",arrayOk:!0,editType:"none"},bordercolor:{valType:"color",arrayOk:!0,editType:"none"},font:n({arrayOk:!0,editType:"none"}),namelength:{valType:"integer",min:-1,arrayOk:!0,editType:"none"},editType:"calc"}}},{"../../plots/font_attributes":771}],605:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../registry");function a(t,e,r,i){i=i||n.identity,Array.isArray(t)&&(e[0][r]=i(t))}e.exports=function(t){var e=t.calcdata,r=t._fullLayout;function o(t){return function(e){return n.coerceHoverinfo({hoverinfo:e},{_module:t._module},r)}}for(var s=0;s<e.length;s++){var l=e[s],c=l[0].trace;if(!i.traceIs(c,"pie")){var u=i.traceIs(c,"2dMap")?a:n.fillArray;u(c.hoverinfo,l,"hi",o(c)),c.hovertemplate&&u(c.hovertemplate,l,"ht"),c.hoverlabel&&(u(c.hoverlabel.bgcolor,l,"hbg"),u(c.hoverlabel.bordercolor,l,"hbc"),u(c.hoverlabel.font.size,l,"hts"),u(c.hoverlabel.font.color,l,"htc"),u(c.hoverlabel.font.family,l,"htf"),u(c.hoverlabel.namelength,l,"hnl"))}}}},{"../../lib":697,"../../registry":826}],606:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("./hover").hover;e.exports=function(t,e,r){var a=n.getComponentMethod("annotations","onClick")(t,t._hoverdata);function o(){t.emit("plotly_click",{points:t._hoverdata,event:e})}void 0!==r&&i(t,e,r,!0),t._hoverdata&&e&&e.target&&(a&&a.then?a.then(o):o(),e.stopImmediatePropagation&&e.stopImmediatePropagation())}},{"../../registry":826,"./hover":610}],607:[function(t,e,r){"use strict";e.exports={YANGLE:60,HOVERARROWSIZE:6,HOVERTEXTPAD:3,HOVERFONTSIZE:13,HOVERFONT:"Arial, sans-serif",HOVERMINTIME:50,HOVERID:"-hover"}},{}],608:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./attributes"),a=t("./hoverlabel_defaults");e.exports=function(t,e,r,o){a(t,e,function(r,a){return n.coerce(t,e,i,r,a)},o.hoverlabel)}},{"../../lib":697,"./attributes":604,"./hoverlabel_defaults":611}],609:[function(t,e,r){"use strict";var n=t("../../lib");r.getSubplot=function(t){return t.subplot||t.xaxis+t.yaxis||t.geo},r.isTraceInSubplots=function(t,e){if("splom"===t.type){for(var n=t.xaxes||[],i=t.yaxes||[],a=0;a<n.length;a++)for(var o=0;o<i.length;o++)if(-1!==e.indexOf(n[a]+i[o]))return!0;return!1}return-1!==e.indexOf(r.getSubplot(t))},r.flat=function(t,e){for(var r=new Array(t.length),n=0;n<t.length;n++)r[n]=e;return r},r.p2c=function(t,e){for(var r=new Array(t.length),n=0;n<t.length;n++)r[n]=t[n].p2c(e);return r},r.getDistanceFunction=function(t,e,n,i){return"closest"===t?i||r.quadrature(e,n):"x"===t?e:n},r.getClosest=function(t,e,r){if(!1!==r.index)r.index>=0&&r.index<t.length?r.distance=0:r.index=!1;else for(var n=0;n<t.length;n++){var i=e(t[n]);i<=r.distance&&(r.index=n,r.distance=i)}return r},r.inbox=function(t,e,r){return t*e<0||0===t?r:1/0},r.quadrature=function(t,e){return function(r){var n=t(r),i=e(r);return Math.sqrt(n*n+i*i)}},r.makeEventData=function(t,e,n){var i="index"in t?t.index:t.pointNumber,a={data:e._input,fullData:e,curveNumber:e.index,pointNumber:i};if(e._indexToPoints){var o=e._indexToPoints[i];1===o.length?a.pointIndex=o[0]:a.pointIndices=o}else a.pointIndex=i;return e._module.eventData?a=e._module.eventData(a,t,e,n,i):("xVal"in t?a.x=t.xVal:"x"in t&&(a.x=t.x),"yVal"in t?a.y=t.yVal:"y"in t&&(a.y=t.y),t.xa&&(a.xaxis=t.xa),t.ya&&(a.yaxis=t.ya),void 0!==t.zLabelVal&&(a.z=t.zLabelVal)),r.appendArrayPointValue(a,e,i),a},r.appendArrayPointValue=function(t,e,r){var i=e._arrayAttrs;if(i)for(var s=0;s<i.length;s++){var l=i[s],c=a(l);if(void 0===t[c]){var u=o(n.nestedProperty(e,l).get(),r);void 0!==u&&(t[c]=u)}}},r.appendArrayMultiPointValues=function(t,e,r){var i=e._arrayAttrs;if(i)for(var s=0;s<i.length;s++){var l=i[s],c=a(l);if(void 0===t[c]){for(var u=n.nestedProperty(e,l).get(),h=new Array(r.length),f=0;f<r.length;f++)h[f]=o(u,r[f]);t[c]=h}}};var i={ids:"id",locations:"location",labels:"label",values:"value","marker.colors":"color"};function a(t){return i[t]||t}function o(t,e){return Array.isArray(e)?Array.isArray(t)&&Array.isArray(t[e[0]])?t[e[0]][e[1]]:void 0:t[e]}},{"../../lib":697}],610:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("tinycolor2"),o=t("../../lib"),s=t("../../lib/events"),l=t("../../lib/svg_text_utils"),c=t("../../lib/override_cursor"),u=t("../drawing"),h=t("../color"),f=t("../dragelement"),p=t("../../plots/cartesian/axes"),d=t("../../registry"),g=t("./helpers"),v=t("./constants"),m=v.YANGLE,y=Math.PI*m/180,x=1/Math.sin(y),b=Math.cos(y),_=Math.sin(y),w=v.HOVERARROWSIZE,k=v.HOVERTEXTPAD;r.hover=function(t,e,r,a){t=o.getGraphDiv(t),o.throttle(t._fullLayout._uid+v.HOVERID,v.HOVERMINTIME,function(){!function(t,e,r,a){r||(r="xy");var l=Array.isArray(r)?r:[r],u=t._fullLayout,v=u._plots||[],m=v[r],y=u._has("cartesian");if(m){var b=m.overlays.map(function(t){return t.id});l=l.concat(b)}for(var _=l.length,w=new Array(_),k=new Array(_),A=!1,L=0;L<_;L++){var z=l[L],O=v[z];if(O)A=!0,w[L]=p.getFromId(t,O.xaxis._id),k[L]=p.getFromId(t,O.yaxis._id);else{var I=u[z]._subplot;w[L]=I.xaxis,k[L]=I.yaxis}}var D=e.hovermode||u.hovermode;D&&!A&&(D="closest");if(-1===["x","y","closest"].indexOf(D)||!t.calcdata||t.querySelector(".zoombox")||t._dragging)return f.unhoverRaw(t,e);var P,R,F,B,N,j,V,U,q,H,G,Y,W,X=-1===u.hoverdistance?1/0:u.hoverdistance,Z=-1===u.spikedistance?1/0:u.spikedistance,$=[],J=[],K={hLinePoint:null,vLinePoint:null},Q=!1;if(Array.isArray(e))for(D="array",F=0;F<e.length;F++)(N=t.calcdata[e[F].curveNumber||0])&&(j=N[0].trace,"skip"!==N[0].trace.hoverinfo&&(J.push(N),"h"===j.orientation&&(Q=!0)));else{for(B=0;B<t.calcdata.length;B++)N=t.calcdata[B],"skip"!==(j=N[0].trace).hoverinfo&&g.isTraceInSubplots(j,l)&&(J.push(N),"h"===j.orientation&&(Q=!0));var tt,et,rt=!e.target;if(rt)tt="xpx"in e?e.xpx:w[0]._length/2,et="ypx"in e?e.ypx:k[0]._length/2;else{if(!1===s.triggerHandler(t,"plotly_beforehover",e))return;var nt=e.target.getBoundingClientRect();if(tt=e.clientX-nt.left,et=e.clientY-nt.top,tt<0||tt>w[0]._length||et<0||et>k[0]._length)return f.unhoverRaw(t,e)}if(e.pointerX=tt+w[0]._offset,e.pointerY=et+k[0]._offset,P="xval"in e?g.flat(l,e.xval):g.p2c(w,tt),R="yval"in e?g.flat(l,e.yval):g.p2c(k,et),!i(P[0])||!i(R[0]))return o.warn("Fx.hover failed",e,t),f.unhoverRaw(t,e)}var it=1/0;for(B=0;B<J.length;B++)if((N=J[B])&&N[0]&&N[0].trace&&!0===N[0].trace.visible&&(j=N[0].trace,-1===["carpet","contourcarpet"].indexOf(j._module.name))){if("splom"===j.type?V=l[U=0]:(V=g.getSubplot(j),U=l.indexOf(V)),q=D,Y={cd:N,trace:j,xa:w[U],ya:k[U],maxHoverDistance:X,maxSpikeDistance:Z,index:!1,distance:Math.min(it,X),spikeDistance:1/0,xSpike:void 0,ySpike:void 0,color:h.defaultLine,name:j.name,x0:void 0,x1:void 0,y0:void 0,y1:void 0,xLabelVal:void 0,yLabelVal:void 0,zLabelVal:void 0,text:void 0},u[V]&&(Y.subplot=u[V]._subplot),u._splomScenes&&u._splomScenes[j.uid]&&(Y.scene=u._splomScenes[j.uid]),W=$.length,"array"===q){var at=e[B];"pointNumber"in at?(Y.index=at.pointNumber,q="closest"):(q="","xval"in at&&(H=at.xval,q="x"),"yval"in at&&(G=at.yval,q=q?"closest":"y"))}else H=P[U],G=R[U];if(0!==X)if(j._module&&j._module.hoverPoints){var ot=j._module.hoverPoints(Y,H,G,q,u._hoverlayer);if(ot)for(var st,lt=0;lt<ot.length;lt++)st=ot[lt],i(st.x0)&&i(st.y0)&&$.push(S(st,D))}else o.log("Unrecognized trace type in hover:",j);if("closest"===D&&$.length>W&&($.splice(0,W),it=$[0].distance),y&&0!==Z&&0===$.length){Y.distance=Z,Y.index=!1;var ct=j._module.hoverPoints(Y,H,G,"closest",u._hoverlayer);if(ct&&(ct=ct.filter(function(t){return t.spikeDistance<=Z})),ct&&ct.length){var ut,ht=ct.filter(function(t){return t.xa.showspikes});if(ht.length){var ft=ht[0];i(ft.x0)&&i(ft.y0)&&(ut=vt(ft),(!K.vLinePoint||K.vLinePoint.spikeDistance>ut.spikeDistance)&&(K.vLinePoint=ut))}var pt=ct.filter(function(t){return t.ya.showspikes});if(pt.length){var dt=pt[0];i(dt.x0)&&i(dt.y0)&&(ut=vt(dt),(!K.hLinePoint||K.hLinePoint.spikeDistance>ut.spikeDistance)&&(K.hLinePoint=ut))}}}}function gt(t,e){for(var r,n=null,i=1/0,a=0;a<t.length;a++)(r=t[a].spikeDistance)<i&&r<=e&&(n=t[a],i=r);return n}function vt(t){return t?{xa:t.xa,ya:t.ya,x:void 0!==t.xSpike?t.xSpike:(t.x0+t.x1)/2,y:void 0!==t.ySpike?t.ySpike:(t.y0+t.y1)/2,distance:t.distance,spikeDistance:t.spikeDistance,curveNumber:t.trace.index,color:t.color,pointNumber:t.index}:null}var mt={fullLayout:u,container:u._hoverlayer,outerContainer:u._paperdiv,event:e},yt=t._spikepoints,xt={vLinePoint:K.vLinePoint,hLinePoint:K.hLinePoint};if(t._spikepoints=xt,y&&0!==Z&&0!==$.length){var bt=$.filter(function(t){return t.ya.showspikes}),_t=gt(bt,Z);K.hLinePoint=vt(_t);var wt=$.filter(function(t){return t.xa.showspikes}),kt=gt(wt,Z);K.vLinePoint=vt(kt)}if(0===$.length){var At=f.unhoverRaw(t,e);return!y||null===K.hLinePoint&&null===K.vLinePoint||C(yt)&&E(K,mt),At}y&&C(yt)&&E(K,mt);$.sort(function(t,e){return t.distance-e.distance});var Mt=t._hoverdata,Tt=[];for(F=0;F<$.length;F++){var St=$[F],Et=g.makeEventData(St,St.trace,St.cd),Ct=!1;St.cd[St.index]&&St.cd[St.index].ht&&(Ct=St.cd[St.index].ht),$[F].hovertemplate=Ct||St.trace.hovertemplate||!1,$[F].eventData=[Et],Tt.push(Et)}t._hoverdata=Tt;var Lt="y"===D&&(J.length>1||$.length>1)||"closest"===D&&Q&&$.length>1,zt=h.combine(u.plot_bgcolor||h.background,u.paper_bgcolor),Ot={hovermode:D,rotateLabels:Lt,bgColor:zt,container:u._hoverlayer,outerContainer:u._paperdiv,commonLabelOpts:u.hoverlabel,hoverdistance:u.hoverdistance},It=M($,Ot,t);if(function(t,e,r){var n,i,a,o,s,l,c,u=0,h=1,f=t.map(function(t,n){var i=t[e],a="x"===i._id.charAt(0),o=i.range;return!n&&o&&o[0]>o[1]!==a&&(h=-1),[{i:n,traceIndex:t.trace.index,dp:0,pos:t.pos,posref:t.posref,size:t.by*(a?x:1)/2,pmin:0,pmax:a?r.width:r.height}]}).sort(function(t,e){return t[0].posref-e[0].posref||h*(e[0].traceIndex-t[0].traceIndex)});function p(t){var e=t[0],r=t[t.length-1];if(i=e.pmin-e.pos-e.dp+e.size,a=r.pos+r.dp+r.size-e.pmax,i>.01){for(s=t.length-1;s>=0;s--)t[s].dp+=i;n=!1}if(!(a<.01)){if(i<-.01){for(s=t.length-1;s>=0;s--)t[s].dp-=a;n=!1}if(n){var c=0;for(o=0;o<t.length;o++)(l=t[o]).pos+l.dp+l.size>e.pmax&&c++;for(o=t.length-1;o>=0&&!(c<=0);o--)(l=t[o]).pos>e.pmax-1&&(l.del=!0,c--);for(o=0;o<t.length&&!(c<=0);o++)if((l=t[o]).pos<e.pmin+1)for(l.del=!0,c--,a=2*l.size,s=t.length-1;s>=0;s--)t[s].dp-=a;for(o=t.length-1;o>=0&&!(c<=0);o--)(l=t[o]).pos+l.dp+l.size>e.pmax&&(l.del=!0,c--)}}}for(;!n&&u<=t.length;){for(u++,n=!0,o=0;o<f.length-1;){var d=f[o],g=f[o+1],v=d[d.length-1],m=g[0];if((i=v.pos+v.dp+v.size-m.pos-m.dp+m.size)>.01&&v.pmin===m.pmin&&v.pmax===m.pmax){for(s=g.length-1;s>=0;s--)g[s].dp+=i;for(d.push.apply(d,g),f.splice(o+1,1),c=0,s=d.length-1;s>=0;s--)c+=d[s].dp;for(a=c/d.length,s=d.length-1;s>=0;s--)d[s].dp-=a;n=!1}else o++}f.forEach(p)}for(o=f.length-1;o>=0;o--){var y=f[o];for(s=y.length-1;s>=0;s--){var b=y[s],_=t[b.i];_.offset=b.dp,_.del=b.del}}}($,Lt?"xa":"ya",u),T(It,Lt),e.target&&e.target.tagName){var Dt=d.getComponentMethod("annotations","hasClickToShow")(t,Tt);c(n.select(e.target),Dt?"pointer":"")}if(!e.target||a||!function(t,e,r){if(!r||r.length!==t._hoverdata.length)return!0;for(var n=r.length-1;n>=0;n--){var i=r[n],a=t._hoverdata[n];if(i.curveNumber!==a.curveNumber||String(i.pointNumber)!==String(a.pointNumber)||String(i.pointNumbers)!==String(a.pointNumbers))return!0}return!1}(t,0,Mt))return;Mt&&t.emit("plotly_unhover",{event:e,points:Mt});t.emit("plotly_hover",{event:e,points:t._hoverdata,xaxes:w,yaxes:k,xvals:P,yvals:R})}(t,e,r,a)})},r.loneHover=function(t,e){var r={color:t.color||h.defaultLine,x0:t.x0||t.x||0,x1:t.x1||t.x||0,y0:t.y0||t.y||0,y1:t.y1||t.y||0,xLabel:t.xLabel,yLabel:t.yLabel,zLabel:t.zLabel,text:t.text,name:t.name,idealAlign:t.idealAlign,borderColor:t.borderColor,fontFamily:t.fontFamily,fontSize:t.fontSize,fontColor:t.fontColor,trace:t.trace||{index:0,hoverinfo:""},xa:{_offset:0},ya:{_offset:0},index:0,hovertemplate:t.hovertemplate||!1,eventData:t.eventData||!1,hovertemplateLabels:t.hovertemplateLabels||!1},i=n.select(e.container),a=e.outerContainer?n.select(e.outerContainer):i,o={hovermode:"closest",rotateLabels:!1,bgColor:e.bgColor||h.background,container:i,outerContainer:a},s=M([r],o,e.gd);return T(s,o.rotateLabels),s.node()},r.multiHovers=function(t,e){Array.isArray(t)||(t=[t]);var r=t.map(function(t){return{color:t.color||h.defaultLine,x0:t.x0||t.x||0,x1:t.x1||t.x||0,y0:t.y0||t.y||0,y1:t.y1||t.y||0,xLabel:t.xLabel,yLabel:t.yLabel,zLabel:t.zLabel,text:t.text,name:t.name,idealAlign:t.idealAlign,borderColor:t.borderColor,fontFamily:t.fontFamily,fontSize:t.fontSize,fontColor:t.fontColor,trace:t.trace||{index:0,hoverinfo:""},xa:{_offset:0},ya:{_offset:0},index:0,hovertemplate:t.hovertemplate||!1,eventData:t.eventData||!1,hovertemplateLabels:t.hovertemplateLabels||!1}}),i=n.select(e.container),a=e.outerContainer?n.select(e.outerContainer):i,o={hovermode:"closest",rotateLabels:!1,bgColor:e.bgColor||h.background,container:i,outerContainer:a},s=M(r,o,e.gd),l=0;return s.sort(function(t,e){return t.y0-e.y0}).each(function(t){var e=t.y0-t.by/2;t.offset=e-5<l?l-e+5:0,l=e+t.by+t.offset}),T(s,o.rotateLabels),s.node()};var A=/<extra>([\s\S]*)<\/extra>/;function M(t,e,r){var i=r._fullLayout,a=e.hovermode,s=e.rotateLabels,c=e.bgColor,f=e.container,p=e.outerContainer,d=e.commonLabelOpts||{},g=e.fontFamily||v.HOVERFONT,y=e.fontSize||v.HOVERFONTSIZE,x=t[0],b=x.xa,_=x.ya,M="y"===a?"yLabel":"xLabel",T=x[M],S=(String(T)||"").split(" ")[0],E=p.node().getBoundingClientRect(),C=E.top,L=E.width,z=E.height,O=void 0!==T&&x.distance<=e.hoverdistance&&("x"===a||"y"===a);if(O){var I,D,P=!0;for(I=0;I<t.length;I++)if(P&&void 0===t[I].zLabel&&(P=!1),D=t[I].hoverinfo||t[I].trace.hoverinfo){var R=Array.isArray(D)?D:D.split("+");if(-1===R.indexOf("all")&&-1===R.indexOf(a)){O=!1;break}}P&&(O=!1)}var F=f.selectAll("g.axistext").data(O?[0]:[]);F.enter().append("g").classed("axistext",!0),F.exit().remove(),F.each(function(){var e=n.select(this),i=o.ensureSingle(e,"path","",function(t){t.style({"stroke-width":"1px"})}),s=o.ensureSingle(e,"text","",function(t){t.attr("data-notex",1)}),c=d.bgcolor||h.defaultLine,f=d.bordercolor||h.contrast(c),p=h.contrast(c);i.style({fill:c,stroke:f}),s.text(T).call(u.font,d.font.family||g,d.font.size||y,d.font.color||p).call(l.positionText,0,0).call(l.convertToTspans,r),e.attr("transform","");var v=s.node().getBoundingClientRect();if("x"===a){s.attr("text-anchor","middle").call(l.positionText,0,"top"===b.side?C-v.bottom-w-k:C-v.top+w+k);var m="top"===b.side?"-":"";i.attr("d","M0,0L"+w+","+m+w+"H"+(k+v.width/2)+"v"+m+(2*k+v.height)+"H-"+(k+v.width/2)+"V"+m+w+"H-"+w+"Z"),e.attr("transform","translate("+(b._offset+(x.x0+x.x1)/2)+","+(_._offset+("top"===b.side?0:_._length))+")")}else{s.attr("text-anchor","right"===_.side?"start":"end").call(l.positionText,("right"===_.side?1:-1)*(k+w),C-v.top-v.height/2);var A="right"===_.side?"":"-";i.attr("d","M0,0L"+A+w+","+w+"V"+(k+v.height/2)+"h"+A+(2*k+v.width)+"V-"+(k+v.height/2)+"H"+A+w+"V-"+w+"Z"),e.attr("transform","translate("+(b._offset+("right"===_.side?b._length:0))+","+(_._offset+(x.y0+x.y1)/2)+")")}t=t.filter(function(t){return void 0!==t.zLabelVal||(t[M]||"").split(" ")[0]===S})});var B=f.selectAll("g.hovertext").data(t,function(t){return[t.trace.index,t.index,t.x0,t.y0,t.name,t.attr,t.xa,t.ya||""].join(",")});return B.enter().append("g").classed("hovertext",!0).each(function(){var t=n.select(this);t.append("rect").call(h.fill,h.addOpacity(c,.8)),t.append("text").classed("name",!0),t.append("path").style("stroke-width","1px"),t.append("text").classed("nums",!0).call(u.font,g,y)}),B.exit().remove(),B.each(function(t){var e=n.select(this).attr("transform",""),f="",p="",d=t.bgcolor||t.color,v=h.combine(h.opacity(d)?d:h.defaultLine,c),x=h.combine(h.opacity(t.color)?t.color:h.defaultLine,c),b=t.borderColor||h.contrast(v);void 0!==t.nameOverride&&(t.name=t.nameOverride),t.name&&(i.meta&&(t.name=o.templateString(t.name,{meta:i.meta})),f=l.plainText(t.name||"",{len:t.nameLength,allowedTags:["br","sub","sup","b","i","em"]})),void 0!==t.zLabel?(void 0!==t.xLabel&&(p+="x: "+t.xLabel+"<br>"),void 0!==t.yLabel&&(p+="y: "+t.yLabel+"<br>"),p+=(p?"z: ":"")+t.zLabel):O&&t[a+"Label"]===T?p=t[("x"===a?"y":"x")+"Label"]||"":void 0===t.xLabel?void 0!==t.yLabel&&"scattercarpet"!==t.trace.type&&(p=t.yLabel):p=void 0===t.yLabel?t.xLabel:"("+t.xLabel+", "+t.yLabel+")",!t.text&&0!==t.text||Array.isArray(t.text)||(p+=(p?"<br>":"")+t.text),void 0!==t.extraText&&(p+=(p?"<br>":"")+t.extraText),""!==p||t.hovertemplate||(""===f&&e.remove(),p=f);var _=r._fullLayout._d3locale,M=t.hovertemplate||!1,S=t.hovertemplateLabels||t,E=t.eventData[0]||{};M&&(p=(p=o.hovertemplateString(M,S,_,E,{meta:i.meta})).replace(A,function(t,e){return f=e,""}));var I=e.select("text.nums").call(u.font,t.fontFamily||g,t.fontSize||y,t.fontColor||b).text(p).attr("data-notex",1).call(l.positionText,0,0).call(l.convertToTspans,r),D=e.select("text.name"),P=0,R=0;if(f&&f!==p){D.call(u.font,t.fontFamily||g,t.fontSize||y,x).text(f).attr("data-notex",1).call(l.positionText,0,0).call(l.convertToTspans,r);var F=D.node().getBoundingClientRect();P=F.width+2*k,R=F.height+2*k}else D.remove(),e.select("rect").remove();e.select("path").style({fill:v,stroke:b});var B,N,j=I.node().getBoundingClientRect(),V=t.xa._offset+(t.x0+t.x1)/2,U=t.ya._offset+(t.y0+t.y1)/2,q=Math.abs(t.x1-t.x0),H=Math.abs(t.y1-t.y0),G=j.width+w+k+P;t.ty0=C-j.top,t.bx=j.width+2*k,t.by=Math.max(j.height+2*k,R),t.anchor="start",t.txwidth=j.width,t.tx2width=P,t.offset=0,s?(t.pos=V,B=U+H/2+G<=z,N=U-H/2-G>=0,"top"!==t.idealAlign&&B||!N?B?(U+=H/2,t.anchor="start"):t.anchor="middle":(U-=H/2,t.anchor="end")):(t.pos=U,B=V+q/2+G<=L,N=V-q/2-G>=0,"left"!==t.idealAlign&&B||!N?B?(V+=q/2,t.anchor="start"):t.anchor="middle":(V-=q/2,t.anchor="end")),I.attr("text-anchor",t.anchor),P&&D.attr("text-anchor",t.anchor),e.attr("transform","translate("+V+","+U+")"+(s?"rotate("+m+")":""))}),B}function T(t,e){t.each(function(t){var r=n.select(this);if(t.del)r.remove();else{var i="end"===t.anchor?-1:1,a=r.select("text.nums"),o={start:1,end:-1,middle:0}[t.anchor],s=o*(w+k),c=s+o*(t.txwidth+k),h=0,f=t.offset;"middle"===t.anchor&&(s-=t.tx2width/2,c+=t.txwidth/2+k),e&&(f*=-_,h=t.offset*b),r.select("path").attr("d","middle"===t.anchor?"M-"+(t.bx/2+t.tx2width/2)+","+(f-t.by/2)+"h"+t.bx+"v"+t.by+"h-"+t.bx+"Z":"M0,0L"+(i*w+h)+","+(w+f)+"v"+(t.by/2-w)+"h"+i*t.bx+"v-"+t.by+"H"+(i*w+h)+"V"+(f-w)+"Z"),a.call(l.positionText,s+h,f+t.ty0-t.by/2+k),t.tx2width&&(r.select("text.name").call(l.positionText,c+o*k+h,f+t.ty0-t.by/2+k),r.select("rect").call(u.setRect,c+(o-1)*t.tx2width/2+h,f-t.by/2-1,t.tx2width,t.by+2))}})}function S(t,e){var r=t.index,n=t.trace||{},i=t.cd[0],a=t.cd[r]||{},s=Array.isArray(r)?function(t,e){return o.castOption(i,r,t)||o.extractOption({},n,"",e)}:function(t,e){return o.extractOption(a,n,t,e)};function l(e,r,n){var i=s(r,n);i&&(t[e]=i)}if(l("hoverinfo","hi","hoverinfo"),l("bgcolor","hbg","hoverlabel.bgcolor"),l("borderColor","hbc","hoverlabel.bordercolor"),l("fontFamily","htf","hoverlabel.font.family"),l("fontSize","hts","hoverlabel.font.size"),l("fontColor","htc","hoverlabel.font.color"),l("nameLength","hnl","hoverlabel.namelength"),t.posref="y"===e||"closest"===e&&"h"===n.orientation?t.xa._offset+(t.x0+t.x1)/2:t.ya._offset+(t.y0+t.y1)/2,t.x0=o.constrain(t.x0,0,t.xa._length),t.x1=o.constrain(t.x1,0,t.xa._length),t.y0=o.constrain(t.y0,0,t.ya._length),t.y1=o.constrain(t.y1,0,t.ya._length),void 0!==t.xLabelVal&&(t.xLabel="xLabel"in t?t.xLabel:p.hoverLabelText(t.xa,t.xLabelVal),t.xVal=t.xa.c2d(t.xLabelVal)),void 0!==t.yLabelVal&&(t.yLabel="yLabel"in t?t.yLabel:p.hoverLabelText(t.ya,t.yLabelVal),t.yVal=t.ya.c2d(t.yLabelVal)),void 0!==t.zLabelVal&&void 0===t.zLabel&&(t.zLabel=String(t.zLabelVal)),!(isNaN(t.xerr)||"log"===t.xa.type&&t.xerr<=0)){var c=p.tickText(t.xa,t.xa.c2l(t.xerr),"hover").text;void 0!==t.xerrneg?t.xLabel+=" +"+c+" / -"+p.tickText(t.xa,t.xa.c2l(t.xerrneg),"hover").text:t.xLabel+=" \xb1 "+c,"x"===e&&(t.distance+=1)}if(!(isNaN(t.yerr)||"log"===t.ya.type&&t.yerr<=0)){var u=p.tickText(t.ya,t.ya.c2l(t.yerr),"hover").text;void 0!==t.yerrneg?t.yLabel+=" +"+u+" / -"+p.tickText(t.ya,t.ya.c2l(t.yerrneg),"hover").text:t.yLabel+=" \xb1 "+u,"y"===e&&(t.distance+=1)}var h=t.hoverinfo||t.trace.hoverinfo;return h&&"all"!==h&&(-1===(h=Array.isArray(h)?h:h.split("+")).indexOf("x")&&(t.xLabel=void 0),-1===h.indexOf("y")&&(t.yLabel=void 0),-1===h.indexOf("z")&&(t.zLabel=void 0),-1===h.indexOf("text")&&(t.text=void 0),-1===h.indexOf("name")&&(t.name=void 0)),t}function E(t,e){var r,n,i=e.container,o=e.fullLayout,s=e.event,l=!!t.hLinePoint,c=!!t.vLinePoint;if(i.selectAll(".spikeline").remove(),c||l){var f=h.combine(o.plot_bgcolor,o.paper_bgcolor);if(l){var p,d,g=t.hLinePoint;r=g&&g.xa,"cursor"===(n=g&&g.ya).spikesnap?(p=s.pointerX,d=s.pointerY):(p=r._offset+g.x,d=n._offset+g.y);var v,m,y=a.readability(g.color,f)<1.5?h.contrast(f):g.color,x=n.spikemode,b=n.spikethickness,_=n.spikecolor||y,w=n._boundingBox,k=(w.left+w.right)/2<p?w.right:w.left;-1===x.indexOf("toaxis")&&-1===x.indexOf("across")||(-1!==x.indexOf("toaxis")&&(v=k,m=p),-1!==x.indexOf("across")&&(v=n._counterSpan[0],m=n._counterSpan[1]),i.insert("line",":first-child").attr({x1:v,x2:m,y1:d,y2:d,"stroke-width":b,stroke:_,"stroke-dasharray":u.dashStyle(n.spikedash,b)}).classed("spikeline",!0).classed("crisp",!0),i.insert("line",":first-child").attr({x1:v,x2:m,y1:d,y2:d,"stroke-width":b+2,stroke:f}).classed("spikeline",!0).classed("crisp",!0)),-1!==x.indexOf("marker")&&i.insert("circle",":first-child").attr({cx:k+("right"!==n.side?b:-b),cy:d,r:b,fill:_}).classed("spikeline",!0)}if(c){var A,M,T=t.vLinePoint;r=T&&T.xa,n=T&&T.ya,"cursor"===r.spikesnap?(A=s.pointerX,M=s.pointerY):(A=r._offset+T.x,M=n._offset+T.y);var S,E,C=a.readability(T.color,f)<1.5?h.contrast(f):T.color,L=r.spikemode,z=r.spikethickness,O=r.spikecolor||C,I=r._boundingBox,D=(I.top+I.bottom)/2<M?I.bottom:I.top;-1===L.indexOf("toaxis")&&-1===L.indexOf("across")||(-1!==L.indexOf("toaxis")&&(S=D,E=M),-1!==L.indexOf("across")&&(S=r._counterSpan[0],E=r._counterSpan[1]),i.insert("line",":first-child").attr({x1:A,x2:A,y1:S,y2:E,"stroke-width":z,stroke:O,"stroke-dasharray":u.dashStyle(r.spikedash,z)}).classed("spikeline",!0).classed("crisp",!0),i.insert("line",":first-child").attr({x1:A,x2:A,y1:S,y2:E,"stroke-width":z+2,stroke:f}).classed("spikeline",!0).classed("crisp",!0)),-1!==L.indexOf("marker")&&i.insert("circle",":first-child").attr({cx:A,cy:D-("top"!==r.side?z:-z),r:z,fill:O}).classed("spikeline",!0)}}}function C(t,e){return!e||(e.vLinePoint!==t._spikepoints.vLinePoint||e.hLinePoint!==t._spikepoints.hLinePoint)}},{"../../lib":697,"../../lib/events":686,"../../lib/override_cursor":708,"../../lib/svg_text_utils":721,"../../plots/cartesian/axes":745,"../../registry":826,"../color":574,"../dragelement":592,"../drawing":595,"./constants":607,"./helpers":609,d3:151,"fast-isnumeric":218,tinycolor2:518}],611:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e,r,i){r("hoverlabel.bgcolor",(i=i||{}).bgcolor),r("hoverlabel.bordercolor",i.bordercolor),r("hoverlabel.namelength",i.namelength),n.coerceFont(r,"hoverlabel.font",i.font)}},{"../../lib":697}],612:[function(t,e,r){"use strict";e.exports=function(t,e){t=t||{};(e=e||{}).description&&e.description;var r=e.keys||[];if(r.length>0){for(var n=[],i=0;i<r.length;i++)n[i]="`"+r[i]+"`";"Finally, the template string has access to ",1===r.length?"variable "+n[0]:"variables "+n.slice(0,-1).join(", ")+" and "+n.slice(-1)+"."}var a={valType:"string",dflt:"",editType:t.editType||"none"};return!1!==t.arrayOk&&(a.arrayOk=!0),a}},{}],613:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../lib"),a=t("../dragelement"),o=t("./helpers"),s=t("./layout_attributes"),l=t("./hover");e.exports={moduleType:"component",name:"fx",constants:t("./constants"),schema:{layout:s},attributes:t("./attributes"),layoutAttributes:s,supplyLayoutGlobalDefaults:t("./layout_global_defaults"),supplyDefaults:t("./defaults"),supplyLayoutDefaults:t("./layout_defaults"),calc:t("./calc"),getDistanceFunction:o.getDistanceFunction,getClosest:o.getClosest,inbox:o.inbox,quadrature:o.quadrature,appendArrayPointValue:o.appendArrayPointValue,castHoverOption:function(t,e,r){return i.castOption(t,e,"hoverlabel."+r)},castHoverinfo:function(t,e,r){return i.castOption(t,r,"hoverinfo",function(r){return i.coerceHoverinfo({hoverinfo:r},{_module:t._module},e)})},hover:l.hover,unhover:a.unhover,loneHover:l.loneHover,multiHovers:l.multiHovers,loneUnhover:function(t){var e=i.isD3Selection(t)?t:n.select(t);e.selectAll("g.hovertext").remove(),e.selectAll(".spikeline").remove()},click:t("./click")}},{"../../lib":697,"../dragelement":592,"./attributes":604,"./calc":605,"./click":606,"./constants":607,"./defaults":608,"./helpers":609,"./hover":610,"./layout_attributes":614,"./layout_defaults":615,"./layout_global_defaults":616,d3:151}],614:[function(t,e,r){"use strict";var n=t("./constants"),i=t("../../plots/font_attributes")({editType:"none"});i.family.dflt=n.HOVERFONT,i.size.dflt=n.HOVERFONTSIZE,e.exports={clickmode:{valType:"flaglist",flags:["event","select"],dflt:"event",editType:"plot",extras:["none"]},dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable",!1],dflt:"zoom",editType:"modebar"},hovermode:{valType:"enumerated",values:["x","y","closest",!1],editType:"modebar"},hoverdistance:{valType:"integer",min:-1,dflt:20,editType:"none"},spikedistance:{valType:"integer",min:-1,dflt:20,editType:"none"},hoverlabel:{bgcolor:{valType:"color",editType:"none"},bordercolor:{valType:"color",editType:"none"},font:i,namelength:{valType:"integer",min:-1,dflt:15,editType:"none"},editType:"none"},selectdirection:{valType:"enumerated",values:["h","v","d","any"],dflt:"any",editType:"none"}}},{"../../plots/font_attributes":771,"./constants":607}],615:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./layout_attributes");e.exports=function(t,e,r){function a(r,a){return n.coerce(t,e,i,r,a)}var o,s=a("clickmode");"select"===a("dragmode")&&a("selectdirection"),e._has("cartesian")?s.indexOf("select")>-1?o="closest":(e._isHoriz=function(t){for(var e=!0,r=0;r<t.length;r++){var n=t[r];if("h"!==n.orientation){e=!1;break}}return e}(r),o=e._isHoriz?"y":"x"):o="closest",a("hovermode",o)&&(a("hoverdistance"),a("spikedistance"));var l=e._has("mapbox"),c=e._has("geo"),u=e._basePlotModules.length;"zoom"===e.dragmode&&((l||c)&&1===u||l&&c&&2===u)&&(e.dragmode="pan")}},{"../../lib":697,"./layout_attributes":614}],616:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./hoverlabel_defaults"),a=t("./layout_attributes");e.exports=function(t,e){i(t,e,function(r,i){return n.coerce(t,e,a,r,i)})}},{"../../lib":697,"./hoverlabel_defaults":611,"./layout_attributes":614}],617:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../lib/regex").counter,a=t("../../plots/domain").attributes,o=t("../../plots/cartesian/constants").idRegex,s=t("../../plot_api/plot_template"),l={rows:{valType:"integer",min:1,editType:"plot"},roworder:{valType:"enumerated",values:["top to bottom","bottom to top"],dflt:"top to bottom",editType:"plot"},columns:{valType:"integer",min:1,editType:"plot"},subplots:{valType:"info_array",freeLength:!0,dimensions:2,items:{valType:"enumerated",values:[i("xy").toString(),""],editType:"plot"},editType:"plot"},xaxes:{valType:"info_array",freeLength:!0,items:{valType:"enumerated",values:[o.x.toString(),""],editType:"plot"},editType:"plot"},yaxes:{valType:"info_array",freeLength:!0,items:{valType:"enumerated",values:[o.y.toString(),""],editType:"plot"},editType:"plot"},pattern:{valType:"enumerated",values:["independent","coupled"],dflt:"coupled",editType:"plot"},xgap:{valType:"number",min:0,max:1,editType:"plot"},ygap:{valType:"number",min:0,max:1,editType:"plot"},domain:a({name:"grid",editType:"plot",noGridCell:!0},{}),xside:{valType:"enumerated",values:["bottom","bottom plot","top plot","top"],dflt:"bottom plot",editType:"plot"},yside:{valType:"enumerated",values:["left","left plot","right plot","right"],dflt:"left plot",editType:"plot"},editType:"plot"};function c(t,e,r){var n=e[r+"axes"],i=Object.keys((t._splomAxes||{})[r]||{});return Array.isArray(n)?n:i.length?i:void 0}function u(t,e,r,n,i,a){var o=e(t+"gap",r),s=e("domain."+t);e(t+"side",n);for(var l=new Array(i),c=s[0],u=(s[1]-c)/(i-o),h=u*(1-o),f=0;f<i;f++){var p=c+u*f;l[a?i-1-f:f]=[p,p+h]}return l}function h(t,e,r,n,i){var a,o=new Array(r);function s(t,r){-1!==e.indexOf(r)&&void 0===n[r]?(o[t]=r,n[r]=t):o[t]=""}if(Array.isArray(t))for(a=0;a<r;a++)s(a,t[a]);else for(s(0,i),a=1;a<r;a++)s(a,i+(a+1));return o}e.exports={moduleType:"component",name:"grid",schema:{layout:{grid:l}},layoutAttributes:l,sizeDefaults:function(t,e){var r=t.grid||{},i=c(e,r,"x"),a=c(e,r,"y");if(t.grid||i||a){var o,h,f=Array.isArray(r.subplots)&&Array.isArray(r.subplots[0]),p=Array.isArray(i),d=Array.isArray(a),g=p&&i!==r.xaxes&&d&&a!==r.yaxes;f?(o=r.subplots.length,h=r.subplots[0].length):(d&&(o=a.length),p&&(h=i.length));var v=s.newContainer(e,"grid"),m=A("rows",o),y=A("columns",h);if(m*y>1){f||p||d||"independent"===A("pattern")&&(f=!0),v._hasSubplotGrid=f;var x,b,_="top to bottom"===A("roworder"),w=f?.2:.1,k=f?.3:.1;g&&e._splomGridDflt&&(x=e._splomGridDflt.xside,b=e._splomGridDflt.yside),v._domains={x:u("x",A,w,x,y),y:u("y",A,k,b,m,_)}}else delete e.grid}function A(t,e){return n.coerce(r,v,l,t,e)}},contentDefaults:function(t,e){var r=e.grid;if(r&&r._domains){var n,i,a,o,s,l,u,f=t.grid||{},p=e._subplots,d=r._hasSubplotGrid,g=r.rows,v=r.columns,m="independent"===r.pattern,y=r._axisMap={};if(d){var x=f.subplots||[];l=r.subplots=new Array(g);var b=1;for(n=0;n<g;n++){var _=l[n]=new Array(v),w=x[n]||[];for(i=0;i<v;i++)if(m?(s=1===b?"xy":"x"+b+"y"+b,b++):s=w[i],_[i]="",-1!==p.cartesian.indexOf(s)){if(u=s.indexOf("y"),a=s.slice(0,u),o=s.slice(u),void 0!==y[a]&&y[a]!==i||void 0!==y[o]&&y[o]!==n)continue;_[i]=s,y[a]=i,y[o]=n}}}else{var k=c(e,f,"x"),A=c(e,f,"y");r.xaxes=h(k,p.xaxis,v,y,"x"),r.yaxes=h(A,p.yaxis,g,y,"y")}var M=r._anchors={},T="top to bottom"===r.roworder;for(var S in y){var E,C,L,z=S.charAt(0),O=r[z+"side"];if(O.length<8)M[S]="free";else if("x"===z){if("t"===O.charAt(0)===T?(E=0,C=1,L=g):(E=g-1,C=-1,L=-1),d){var I=y[S];for(n=E;n!==L;n+=C)if((s=l[n][I])&&(u=s.indexOf("y"),s.slice(0,u)===S)){M[S]=s.slice(u);break}}else for(n=E;n!==L;n+=C)if(o=r.yaxes[n],-1!==p.cartesian.indexOf(S+o)){M[S]=o;break}}else if("l"===O.charAt(0)?(E=0,C=1,L=v):(E=v-1,C=-1,L=-1),d){var D=y[S];for(n=E;n!==L;n+=C)if((s=l[D][n])&&(u=s.indexOf("y"),s.slice(u)===S)){M[S]=s.slice(0,u);break}}else for(n=E;n!==L;n+=C)if(a=r.xaxes[n],-1!==p.cartesian.indexOf(a+S)){M[S]=a;break}}}}}},{"../../lib":697,"../../lib/regex":713,"../../plot_api/plot_template":735,"../../plots/cartesian/constants":751,"../../plots/domain":770}],618:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/constants"),i=t("../../plot_api/plot_template").templatedArray;e.exports=i("image",{visible:{valType:"boolean",dflt:!0,editType:"arraydraw"},source:{valType:"string",editType:"arraydraw"},layer:{valType:"enumerated",values:["below","above"],dflt:"above",editType:"arraydraw"},sizex:{valType:"number",dflt:0,editType:"arraydraw"},sizey:{valType:"number",dflt:0,editType:"arraydraw"},sizing:{valType:"enumerated",values:["fill","contain","stretch"],dflt:"contain",editType:"arraydraw"},opacity:{valType:"number",min:0,max:1,dflt:1,editType:"arraydraw"},x:{valType:"any",dflt:0,editType:"arraydraw"},y:{valType:"any",dflt:0,editType:"arraydraw"},xanchor:{valType:"enumerated",values:["left","center","right"],dflt:"left",editType:"arraydraw"},yanchor:{valType:"enumerated",values:["top","middle","bottom"],dflt:"top",editType:"arraydraw"},xref:{valType:"enumerated",values:["paper",n.idRegex.x.toString()],dflt:"paper",editType:"arraydraw"},yref:{valType:"enumerated",values:["paper",n.idRegex.y.toString()],dflt:"paper",editType:"arraydraw"},editType:"arraydraw"})},{"../../plot_api/plot_template":735,"../../plots/cartesian/constants":751}],619:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib/to_log_range");e.exports=function(t,e,r,a){e=e||{};var o="log"===r&&"linear"===e.type,s="linear"===r&&"log"===e.type;if(o||s)for(var l,c,u=t._fullLayout.images,h=e._id.charAt(0),f=0;f<u.length;f++)if(c="images["+f+"].",(l=u[f])[h+"ref"]===e._id){var p=l[h],d=l["size"+h],g=null,v=null;if(o){g=i(p,e.range);var m=d/Math.pow(10,g)/2;v=2*Math.log(m+Math.sqrt(1+m*m))/Math.LN10}else v=(g=Math.pow(10,p))*(Math.pow(10,d/2)-Math.pow(10,-d/2));n(g)?n(v)||(v=null):(g=null,v=null),a(c+h,g),a(c+"size"+h,v)}}},{"../../lib/to_log_range":723,"fast-isnumeric":218}],620:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/cartesian/axes"),a=t("../../plots/array_container_defaults"),o=t("./attributes");function s(t,e,r){function a(r,i){return n.coerce(t,e,o,r,i)}var s=a("source");if(!a("visible",!!s))return e;a("layer"),a("xanchor"),a("yanchor"),a("sizex"),a("sizey"),a("sizing"),a("opacity");for(var l={_fullLayout:r},c=["x","y"],u=0;u<2;u++){var h=c[u],f=i.coerceRef(t,e,l,h,"paper");if("paper"!==f)i.getFromId(l,f)._imgIndices.push(e._index);i.coercePosition(e,l,a,f,h,0)}return e}e.exports=function(t,e){a(t,e,{name:"images",handleItemDefaults:s})}},{"../../lib":697,"../../plots/array_container_defaults":741,"../../plots/cartesian/axes":745,"./attributes":618}],621:[function(t,e,r){"use strict";var n=t("d3"),i=t("../drawing"),a=t("../../plots/cartesian/axes"),o=t("../../constants/xmlns_namespaces");e.exports=function(t){var e,r,s=t._fullLayout,l=[],c={},u=[];for(r=0;r<s.images.length;r++){var h=s.images[r];if(h.visible)if("below"===h.layer&&"paper"!==h.xref&&"paper"!==h.yref){e=h.xref+h.yref;var f=s._plots[e];if(!f){u.push(h);continue}f.mainplot&&(e=f.mainplot.id),c[e]||(c[e]=[]),c[e].push(h)}else"above"===h.layer?l.push(h):u.push(h)}var p={x:{left:{sizing:"xMin",offset:0},center:{sizing:"xMid",offset:-.5},right:{sizing:"xMax",offset:-1}},y:{top:{sizing:"YMin",offset:0},middle:{sizing:"YMid",offset:-.5},bottom:{sizing:"YMax",offset:-1}}};function d(e){var r=n.select(this);if(!this.img||this.img.src!==e.source){r.attr("xmlns",o.svg);var i=new Promise(function(t){var n=new Image;function i(){r.remove(),t()}this.img=n,n.setAttribute("crossOrigin","anonymous"),n.onerror=i,n.onload=function(){var e=document.createElement("canvas");e.width=this.width,e.height=this.height,e.getContext("2d").drawImage(this,0,0);var n=e.toDataURL("image/png");r.attr("xlink:href",n),t()},r.on("error",i),n.src=e.source}.bind(this));t._promises.push(i)}}function g(e){var r=n.select(this),o=a.getFromId(t,e.xref),l=a.getFromId(t,e.yref),c=s._size,u=o?Math.abs(o.l2p(e.sizex)-o.l2p(0)):e.sizex*c.w,h=l?Math.abs(l.l2p(e.sizey)-l.l2p(0)):e.sizey*c.h,f=u*p.x[e.xanchor].offset,d=h*p.y[e.yanchor].offset,g=p.x[e.xanchor].sizing+p.y[e.yanchor].sizing,v=(o?o.r2p(e.x)+o._offset:e.x*c.w+c.l)+f,m=(l?l.r2p(e.y)+l._offset:c.h-e.y*c.h+c.t)+d;switch(e.sizing){case"fill":g+=" slice";break;case"stretch":g="none"}r.attr({x:v,y:m,width:u,height:h,preserveAspectRatio:g,opacity:e.opacity});var y=(o?o._id:"")+(l?l._id:"");i.setClipUrl(r,y?"clip"+s._uid+y:null,t)}var v=s._imageLowerLayer.selectAll("image").data(u),m=s._imageUpperLayer.selectAll("image").data(l);v.enter().append("image"),m.enter().append("image"),v.exit().remove(),m.exit().remove(),v.each(function(t){d.bind(this)(t),g.bind(this)(t)}),m.each(function(t){d.bind(this)(t),g.bind(this)(t)});var y=Object.keys(s._plots);for(r=0;r<y.length;r++){e=y[r];var x=s._plots[e];if(x.imagelayer){var b=x.imagelayer.selectAll("image").data(c[e]||[]);b.enter().append("image"),b.exit().remove(),b.each(function(t){d.bind(this)(t),g.bind(this)(t)})}}}},{"../../constants/xmlns_namespaces":675,"../../plots/cartesian/axes":745,"../drawing":595,d3:151}],622:[function(t,e,r){"use strict";e.exports={moduleType:"component",name:"images",layoutAttributes:t("./attributes"),supplyLayoutDefaults:t("./defaults"),includeBasePlot:t("../../plots/cartesian/include_components")("images"),draw:t("./draw"),convertCoords:t("./convert_coords")}},{"../../plots/cartesian/include_components":755,"./attributes":618,"./convert_coords":619,"./defaults":620,"./draw":621}],623:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes"),i=t("../color/attributes");e.exports={bgcolor:{valType:"color",editType:"legend"},bordercolor:{valType:"color",dflt:i.defaultLine,editType:"legend"},borderwidth:{valType:"number",min:0,dflt:0,editType:"legend"},font:n({editType:"legend"}),orientation:{valType:"enumerated",values:["v","h"],dflt:"v",editType:"legend"},traceorder:{valType:"flaglist",flags:["reversed","grouped"],extras:["normal"],editType:"legend"},tracegroupgap:{valType:"number",min:0,dflt:10,editType:"legend"},x:{valType:"number",min:-2,max:3,dflt:1.02,editType:"legend"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left",editType:"legend"},y:{valType:"number",min:-2,max:3,dflt:1,editType:"legend"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"auto",editType:"legend"},uirevision:{valType:"any",editType:"none"},valign:{valType:"enumerated",values:["top","middle","bottom"],dflt:"middle",editType:"legend"},editType:"legend"}},{"../../plots/font_attributes":771,"../color/attributes":573}],624:[function(t,e,r){"use strict";e.exports={scrollBarWidth:6,scrollBarMinHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4,textOffsetX:40}},{}],625:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("../../lib"),a=t("../../plot_api/plot_template"),o=t("./attributes"),s=t("../../plots/layout_attributes"),l=t("./helpers");e.exports=function(t,e,r){for(var c,u,h,f,p=t.legend||{},d=0,g=!1,v="normal",m=0;m<r.length;m++){var y=r[m];y.visible&&((y.showlegend||y._dfltShowLegend)&&(d++,y.showlegend&&(g=!0,(n.traceIs(y,"pie")||!0===y._input.showlegend)&&d++)),(n.traceIs(y,"bar")&&"stack"===e.barmode||-1!==["tonextx","tonexty"].indexOf(y.fill))&&(v=l.isGrouped({traceorder:v})?"grouped+reversed":"reversed"),void 0!==y.legendgroup&&""!==y.legendgroup&&(v=l.isReversed({traceorder:v})?"reversed+grouped":"grouped"))}var x=i.coerce(t,e,s,"showlegend",g&&d>1);if(!1!==x||p.uirevision){var b=a.newContainer(e,"legend");if(w("uirevision",e.uirevision),!1!==x){if(w("bgcolor",e.paper_bgcolor),w("bordercolor"),w("borderwidth"),i.coerceFont(w,"font",e.font),w("orientation"),"h"===b.orientation){var _=t.xaxis;n.getComponentMethod("rangeslider","isVisible")(_)?(c=0,h="left",u=1.1,f="bottom"):(c=0,h="left",u=-.1,f="top")}w("traceorder",v),l.isGrouped(e.legend)&&w("tracegroupgap"),w("x",c),w("xanchor",h),w("y",u),w("yanchor",f),w("valign"),i.noneOrAll(p,b,["x","y"])}}function w(t,e){return i.coerce(p,b,o,t,e)}}},{"../../lib":697,"../../plot_api/plot_template":735,"../../plots/layout_attributes":798,"../../registry":826,"./attributes":623,"./helpers":629}],626:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../lib"),a=t("../../plots/plots"),o=t("../../registry"),s=t("../../lib/events"),l=t("../dragelement"),c=t("../drawing"),u=t("../color"),h=t("../../lib/svg_text_utils"),f=t("./handle_click"),p=t("./constants"),d=t("../../constants/interactions"),g=t("../../constants/alignment"),v=g.LINE_SPACING,m=g.FROM_TL,y=g.FROM_BR,x=t("./get_legend_data"),b=t("./style"),_=t("./helpers"),w=d.DBLCLICKDELAY;function k(t,e,r,n,i){var a=r.data()[0][0].trace,o={event:i,node:r.node(),curveNumber:a.index,expandedIndex:a._expandedIndex,data:t.data,layout:t.layout,frames:t._transitionData._frames,config:t._context,fullData:t._fullData,fullLayout:t._fullLayout};if(a._group&&(o.group=a._group),"pie"===a.type&&(o.label=r.datum()[0].label),!1!==s.triggerHandler(t,"plotly_legendclick",o))if(1===n)e._clickTimeout=setTimeout(function(){f(r,t,n)},w);else if(2===n){e._clickTimeout&&clearTimeout(e._clickTimeout),t._legendMouseDownTime=0,!1!==s.triggerHandler(t,"plotly_legenddoubleclick",o)&&f(r,t,n)}}function A(t,e,r){var n=t.data()[0][0],a=e._fullLayout,s=n.trace,l=o.traceIs(s,"pie"),u=s.index,f=e._context.edits.legendText&&!l,d=l?n.label:s.name;a.meta&&(d=i.templateString(d,{meta:a.meta}));var g=i.ensureSingle(t,"text","legendtext");function m(r){h.convertToTspans(r,e,function(){!function(t,e){var r=t.data()[0][0];if(!r.trace.showlegend)return void t.remove();var n,i,a=t.select("g[class*=math-group]"),o=a.node(),s=e._fullLayout.legend.font.size*v;if(o){var l=c.bBox(o);n=l.height,i=l.width,c.setTranslate(a,0,n/4)}else{var u=t.select(".legendtext"),f=h.lineCount(u),d=u.node();n=s*f,i=d?c.bBox(d).width:0;var g=s*(.3+(1-f)/2);h.positionText(u,p.textOffsetX,g)}r.lineHeight=s,r.height=Math.max(n,16)+3,r.width=i}(t,e)})}g.attr("text-anchor","start").classed("user-select-none",!0).call(c.font,a.legend.font).text(f?M(d,r):d),h.positionText(g,p.textOffsetX,0),f?g.call(h.makeEditable,{gd:e,text:d}).call(m).on("edit",function(t){this.text(M(t,r)).call(m);var a=n.trace._fullInput||{},s={};if(o.hasTransform(a,"groupby")){var l=o.getTransformIndices(a,"groupby"),c=l[l.length-1],h=i.keyedContainer(a,"transforms["+c+"].styles","target","value.name");h.set(n.trace._group,t),s=h.constructUpdate()}else s.name=t;return o.call("_guiRestyle",e,s,u)}):m(g)}function M(t,e){var r=Math.max(4,e);if(t&&t.trim().length>=r/2)return t;for(var n=r-(t=t||"").length;n>0;n--)t+=" ";return t}function T(t,e){var r,a=1,o=i.ensureSingle(t,"rect","legendtoggle",function(t){t.style("cursor","pointer").attr("pointer-events","all").call(u.fill,"rgba(0,0,0,0)")});o.on("mousedown",function(){(r=(new Date).getTime())-e._legendMouseDownTime<w?a+=1:(a=1,e._legendMouseDownTime=r)}),o.on("mouseup",function(){if(!e._dragged&&!e._editing){var r=e._fullLayout.legend;(new Date).getTime()-e._legendMouseDownTime>w&&(a=Math.max(a-1,1)),k(e,r,t,a,n.event)}})}function S(t,e,r){var i=t._fullLayout,a=i.legend,o=a.borderwidth,s=_.isGrouped(a),l=0;if(a._width=0,a._height=0,_.isVertical(a))s&&e.each(function(t,e){c.setTranslate(this,0,e*a.tracegroupgap)}),r.each(function(t){var e=t[0],r=e.height,n=e.width;c.setTranslate(this,o,5+o+a._height+r/2),a._height+=r,a._width=Math.max(a._width,n)}),a._width+=45+2*o,a._height+=10+2*o,s&&(a._height+=(a._lgroupsLength-1)*a.tracegroupgap),l=40;else if(s){for(var u=[a._width],h=e.data(),f=0,p=h.length;f<p;f++){var d=h[f].map(function(t){return t[0].width}),g=40+Math.max.apply(null,d);a._width+=a.tracegroupgap+g,u.push(a._width)}e.each(function(t,e){c.setTranslate(this,u[e],0)}),e.each(function(){var t=n.select(this).selectAll("g.traces"),e=0;t.each(function(t){var r=t[0].height;c.setTranslate(this,0,5+o+e+r/2),e+=r}),a._height=Math.max(a._height,e)}),a._height+=10+2*o,a._width+=2*o}else{var v=0,m=0,y=0,x=0,b=0,w=a.tracegroupgap||5;r.each(function(t){y=Math.max(40+t[0].width,y),b+=40+t[0].width+w});var k=i._size.w>o+b-w;r.each(function(t){var e=t[0],r=k?40+t[0].width:y;o+x+w+r>i._size.w&&(x=0,v+=m,a._height+=m,m=0),c.setTranslate(this,o+x,5+o+e.height/2+v),a._width+=w+r,x+=w+r,m=Math.max(e.height,m)}),k?a._height=m:a._height+=m,a._width+=2*o,a._height+=10+2*o}a._width=Math.ceil(a._width),a._height=Math.ceil(a._height);var A=t._context.edits.legendText||t._context.edits.legendPosition;r.each(function(t){var e=t[0],r=n.select(this).select(".legendtoggle");c.setRect(r,0,-e.height/2,(A?0:a._width)+l,e.height)})}function E(t){var e=t._fullLayout.legend,r="left";i.isRightAnchor(e)?r="right":i.isCenterAnchor(e)&&(r="center");var n="top";i.isBottomAnchor(e)?n="bottom":i.isMiddleAnchor(e)&&(n="middle"),a.autoMargin(t,"legend",{x:e.x,y:e.y,l:e._width*m[r],r:e._width*y[r],b:e._height*y[n],t:e._height*m[n]})}e.exports=function(t){var e=t._fullLayout,r="legend"+e._uid;if(e._infolayer&&t.calcdata){t._legendMouseDownTime||(t._legendMouseDownTime=0);var s=e.legend,h=e.showlegend&&x(t.calcdata,s),f=e.hiddenlabels||[];if(!e.showlegend||!h.length)return e._infolayer.selectAll(".legend").remove(),e._topdefs.select("#"+r).remove(),void a.autoMargin(t,"legend");for(var d=0,g=0;g<h.length;g++)for(var v=0;v<h[g].length;v++){var _=h[g][v][0],w=_.trace,M=o.traceIs(w,"pie")?_.label:w.name;d=Math.max(d,M&&M.length||0)}var C=!1,L=i.ensureSingle(e._infolayer,"g","legend",function(t){t.attr("pointer-events","all"),C=!0}),z=i.ensureSingleById(e._topdefs,"clipPath",r,function(t){t.append("rect")}),O=i.ensureSingle(L,"rect","bg",function(t){t.attr("shape-rendering","crispEdges")});O.call(u.stroke,s.bordercolor).call(u.fill,s.bgcolor).style("stroke-width",s.borderwidth+"px");var I=i.ensureSingle(L,"g","scrollbox"),D=i.ensureSingle(L,"rect","scrollbar",function(t){t.attr({rx:20,ry:3,width:0,height:0}).call(u.fill,"#808BA4")}),P=I.selectAll("g.groups").data(h);P.enter().append("g").attr("class","groups"),P.exit().remove();var R=P.selectAll("g.traces").data(i.identity);R.enter().append("g").attr("class","traces"),R.exit().remove(),R.style("opacity",function(t){var e=t[0].trace;return o.traceIs(e,"pie")?-1!==f.indexOf(t[0].label)?.5:1:"legendonly"===e.visible?.5:1}).each(function(){n.select(this).call(A,t,d).call(T,t)}).call(b,t),i.syncOrAsync([a.previousPromises,function(){C&&(S(t,P,R),E(t));var u=e.width,h=e.height;S(t,P,R),s._height>h?function(t){var e=t._fullLayout.legend,r="left";i.isRightAnchor(e)?r="right":i.isCenterAnchor(e)&&(r="center");a.autoMargin(t,"legend",{x:e.x,y:.5,l:e._width*m[r],r:e._width*y[r],b:0,t:0})}(t):E(t);var f=e._size,d=f.l+f.w*s.x,g=f.t+f.h*(1-s.y);i.isRightAnchor(s)?d-=s._width:i.isCenterAnchor(s)&&(d-=s._width/2),i.isBottomAnchor(s)?g-=s._height:i.isMiddleAnchor(s)&&(g-=s._height/2);var v=s._width,x=f.w;v>x?(d=f.l,v=x):(d+v>u&&(d=u-v),d<0&&(d=0),v=Math.min(u-d,s._width));var b,_,w,A,M=s._height,T=f.h;if(M>T?(g=f.t,M=T):(g+M>h&&(g=h-M),g<0&&(g=0),M=Math.min(h-g,s._height)),c.setTranslate(L,d,g),D.on(".drag",null),L.on("wheel",null),s._height<=M||t._context.staticPlot)O.attr({width:v-s.borderwidth,height:M-s.borderwidth,x:s.borderwidth/2,y:s.borderwidth/2}),c.setTranslate(I,0,0),z.select("rect").attr({width:v-2*s.borderwidth,height:M-2*s.borderwidth,x:s.borderwidth,y:s.borderwidth}),c.setClipUrl(I,r,t),c.setRect(D,0,0,0,0),delete s._scrollY;else{var F,B,N=Math.max(p.scrollBarMinHeight,M*M/s._height),j=M-N-2*p.scrollBarMargin,V=s._height-M,U=j/V,q=Math.min(s._scrollY||0,V);O.attr({width:v-2*s.borderwidth+p.scrollBarWidth+p.scrollBarMargin,height:M-s.borderwidth,x:s.borderwidth/2,y:s.borderwidth/2}),z.select("rect").attr({width:v-2*s.borderwidth+p.scrollBarWidth+p.scrollBarMargin,height:M-2*s.borderwidth,x:s.borderwidth,y:s.borderwidth+q}),c.setClipUrl(I,r,t),G(q,N,U),L.on("wheel",function(){G(q=i.constrain(s._scrollY+n.event.deltaY/j*V,0,V),N,U),0!==q&&q!==V&&n.event.preventDefault()});var H=n.behavior.drag().on("dragstart",function(){F=n.event.sourceEvent.clientY,B=q}).on("drag",function(){var t=n.event.sourceEvent;2===t.buttons||t.ctrlKey||G(q=i.constrain((t.clientY-F)/U+B,0,V),N,U)});D.call(H)}function G(e,r,n){s._scrollY=t._fullLayout.legend._scrollY=e,c.setTranslate(I,0,-e),c.setRect(D,v,p.scrollBarMargin+e*n,p.scrollBarWidth,r),z.select("rect").attr({y:s.borderwidth+e})}t._context.edits.legendPosition&&(L.classed("cursor-move",!0),l.init({element:L.node(),gd:t,prepFn:function(){var t=c.getTranslate(L);w=t.x,A=t.y},moveFn:function(t,e){var r=w+t,n=A+e;c.setTranslate(L,r,n),b=l.align(r,0,f.l,f.l+f.w,s.xanchor),_=l.align(n,0,f.t+f.h,f.t,s.yanchor)},doneFn:function(){void 0!==b&&void 0!==_&&o.call("_guiRelayout",t,{"legend.x":b,"legend.y":_})},clickFn:function(r,n){var i=e._infolayer.selectAll("g.traces").filter(function(){var t=this.getBoundingClientRect();return n.clientX>=t.left&&n.clientX<=t.right&&n.clientY>=t.top&&n.clientY<=t.bottom});i.size()>0&&k(t,L,i,r,n)}}))}],t)}}},{"../../constants/alignment":669,"../../constants/interactions":673,"../../lib":697,"../../lib/events":686,"../../lib/svg_text_utils":721,"../../plots/plots":807,"../../registry":826,"../color":574,"../dragelement":592,"../drawing":595,"./constants":624,"./get_legend_data":627,"./handle_click":628,"./helpers":629,"./style":631,d3:151}],627:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("./helpers");e.exports=function(t,e){var r,a,o={},s=[],l=!1,c={},u=0;function h(t,r){if(""!==t&&i.isGrouped(e))-1===s.indexOf(t)?(s.push(t),l=!0,o[t]=[[r]]):o[t].push([r]);else{var n="~~i"+u;s.push(n),o[n]=[[r]],u++}}for(r=0;r<t.length;r++){var f=t[r],p=f[0],d=p.trace,g=d.legendgroup;if(d.visible&&d.showlegend)if(n.traceIs(d,"pie"))for(c[g]||(c[g]={}),a=0;a<f.length;a++){var v=f[a].label;c[g][v]||(h(g,{label:v,color:f[a].color,i:f[a].i,trace:d,pts:f[a].pts}),c[g][v]=!0)}else h(g,p)}if(!s.length)return[];var m,y,x=s.length;if(l&&i.isGrouped(e))for(y=new Array(x),r=0;r<x;r++)m=o[s[r]],y[r]=i.isReversed(e)?m.reverse():m;else{for(y=[new Array(x)],r=0;r<x;r++)m=o[s[r]][0],y[0][i.isReversed(e)?x-r-1:r]=m;x=1}return e._lgroupsLength=x,y}},{"../../registry":826,"./helpers":629}],628:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../registry"),a=!0;e.exports=function(t,e,r){if(!e._dragged&&!e._editing){var o,s,l,c,u,h=e._fullLayout.hiddenlabels?e._fullLayout.hiddenlabels.slice():[],f=t.data()[0][0],p=e._fullData,d=f.trace,g=d.legendgroup,v={},m=[],y=[],x=[];if(1===r&&a&&e.data&&e._context.showTips?(n.notifier(n._(e,"Double-click on legend to isolate one trace"),"long"),a=!1):a=!1,i.traceIs(d,"pie")){var b=f.label,_=h.indexOf(b);1===r?-1===_?h.push(b):h.splice(_,1):2===r&&(h=[],e.calcdata[0].forEach(function(t){b!==t.label&&h.push(t.label)}),e._fullLayout.hiddenlabels&&e._fullLayout.hiddenlabels.length===h.length&&-1===_&&(h=[])),i.call("_guiRelayout",e,"hiddenlabels",h)}else{var w,k=g&&g.length,A=[];if(k)for(o=0;o<p.length;o++)(w=p[o]).visible&&w.legendgroup===g&&A.push(o);if(1===r){var M;switch(d.visible){case!0:M="legendonly";break;case!1:M=!1;break;case"legendonly":M=!0}if(k)for(o=0;o<p.length;o++)!1!==p[o].visible&&p[o].legendgroup===g&&O(p[o],M);else O(d,M)}else if(2===r){var T,S,E=!0;for(o=0;o<p.length;o++)if(!(p[o]===d)&&!(T=k&&p[o].legendgroup===g)&&!0===p[o].visible&&!i.traceIs(p[o],"notLegendIsolatable")){E=!1;break}for(o=0;o<p.length;o++)if(!1!==p[o].visible&&!i.traceIs(p[o],"notLegendIsolatable"))switch(d.visible){case"legendonly":O(p[o],!0);break;case!0:S=!!E||"legendonly",T=p[o]===d||k&&p[o].legendgroup===g,O(p[o],!!T||S)}}for(o=0;o<y.length;o++)if(l=y[o]){var C=l.constructUpdate(),L=Object.keys(C);for(s=0;s<L.length;s++)c=L[s],(v[c]=v[c]||[])[x[o]]=C[c]}for(u=Object.keys(v),o=0;o<u.length;o++)for(c=u[o],s=0;s<m.length;s++)v[c].hasOwnProperty(s)||(v[c][s]=void 0);i.call("_guiRestyle",e,v,m)}}function z(t,e,r){var n=m.indexOf(t),i=v[e];return i||(i=v[e]=[]),-1===m.indexOf(t)&&(m.push(t),n=m.length-1),i[n]=r,n}function O(t,e){var r=t._fullInput;if(i.hasTransform(r,"groupby")){var a=y[r.index];if(!a){var o=i.getTransformIndices(r,"groupby"),s=o[o.length-1];a=n.keyedContainer(r,"transforms["+s+"].styles","target","value.visible"),y[r.index]=a}var l=a.get(t._group);void 0===l&&(l=!0),!1!==l&&a.set(t._group,e),x[r.index]=z(r.index,"visible",!1!==r.visible)}else{var c=!1!==r.visible&&e;z(r.index,"visible",c)}}}},{"../../lib":697,"../../registry":826}],629:[function(t,e,r){"use strict";r.isGrouped=function(t){return-1!==(t.traceorder||"").indexOf("grouped")},r.isVertical=function(t){return"h"!==t.orientation},r.isReversed=function(t){return-1!==(t.traceorder||"").indexOf("reversed")}},{}],630:[function(t,e,r){"use strict";e.exports={moduleType:"component",name:"legend",layoutAttributes:t("./attributes"),supplyLayoutDefaults:t("./defaults"),draw:t("./draw"),style:t("./style")}},{"./attributes":623,"./defaults":625,"./draw":626,"./style":631}],631:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../registry"),a=t("../../lib"),o=t("../drawing"),s=t("../color"),l=t("../../traces/scatter/subtypes"),c=t("../../traces/pie/style_one");e.exports=function(t,e){t.each(function(t){var r=n.select(this),i=a.ensureSingle(r,"g","layers");i.style("opacity",t[0].trace.opacity);var o=e._fullLayout.legend.valign,s=t[0].lineHeight,l=t[0].height;if("middle"!==o&&s&&l){var c={top:1,bottom:-1}[o]*(.5*(s-l+3));i.attr("transform","translate(0,"+c+")")}else i.attr("transform",null);i.selectAll("g.legendfill").data([t]).enter().append("g").classed("legendfill",!0),i.selectAll("g.legendlines").data([t]).enter().append("g").classed("legendlines",!0);var u=i.selectAll("g.legendsymbols").data([t]);u.enter().append("g").classed("legendsymbols",!0),u.selectAll("g.legendpoints").data([t]).enter().append("g").classed("legendpoints",!0)}).each(function(t){var e=t[0].trace,r=e.marker||{},a=r.line||{},o=n.select(this).select("g.legendpoints").selectAll("path.legendbar").data(i.traceIs(e,"bar")?[t]:[]);o.enter().append("path").classed("legendbar",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),o.exit().remove(),o.each(function(t){var e=n.select(this),i=t[0],o=(i.mlw+1||a.width+1)-1;e.style("stroke-width",o+"px").call(s.fill,i.mc||r.color),o&&e.call(s.stroke,i.mlc||a.color)})}).each(function(t){var e=t[0].trace,r=n.select(this).select("g.legendpoints").selectAll("path.legendbox").data(i.traceIs(e,"box-violin")&&e.visible?[t]:[]);r.enter().append("path").classed("legendbox",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),r.exit().remove(),r.each(function(){var t=e.line.width,r=n.select(this);r.style("stroke-width",t+"px").call(s.fill,e.fillcolor),t&&s.stroke(r,e.line.color)})}).each(function(t){var e=t[0].trace,r=n.select(this).select("g.legendpoints").selectAll("path.legendpie").data(i.traceIs(e,"pie")&&e.visible?[t]:[]);r.enter().append("path").classed("legendpie",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),r.exit().remove(),r.size()&&r.call(c,t[0],e)}).each(function(t){var r=t[0].trace,i=r.visible&&r.fill&&"none"!==r.fill,a=l.hasLines(r),s=r.contours,c=!1,u=!1;if(s){var h=s.coloring;"lines"===h?c=!0:a="none"===h||"heatmap"===h||s.showlines,"constraint"===s.type?i="="!==s._operation:"fill"!==h&&"heatmap"!==h||(u=!0)}var f=l.hasMarkers(r)||l.hasText(r),p=i||u,d=a||c,g=f||!p?"M5,0":d?"M5,-2":"M5,-3",v=n.select(this),m=v.select(".legendfill").selectAll("path").data(i||u?[t]:[]);m.enter().append("path").classed("js-fill",!0),m.exit().remove(),m.attr("d",g+"h30v6h-30z").call(i?o.fillGroupStyle:function(t){if(t.size()){var n="legendfill-"+r.uid;o.gradient(t,e,n,"horizontalreversed",r.colorscale,"fill")}});var y=v.select(".legendlines").selectAll("path").data(a||c?[t]:[]);y.enter().append("path").classed("js-line",!0),y.exit().remove(),y.attr("d",g+(c?"l30,0.0001":"h30")).call(a?o.lineGroupStyle:function(t){if(t.size()){var n="legendline-"+r.uid;o.lineGroupStyle(t),o.gradient(t,e,n,"horizontalreversed",r.colorscale,"stroke")}})}).each(function(t){var r,i,s=t[0],c=s.trace,u=l.hasMarkers(c),h=l.hasText(c),f=l.hasLines(c);function p(t,e,r){var n=a.nestedProperty(c,t).get(),i=a.isArrayOrTypedArray(n)&&e?e(n):n;if(r){if(i<r[0])return r[0];if(i>r[1])return r[1]}return i}function d(t){return t[0]}if(u||h||f){var g={},v={};if(u){g.mc=p("marker.color",d),g.mx=p("marker.symbol",d),g.mo=p("marker.opacity",a.mean,[.2,1]),g.mlc=p("marker.line.color",d),g.mlw=p("marker.line.width",a.mean,[0,5]),v.marker={sizeref:1,sizemin:1,sizemode:"diameter"};var m=p("marker.size",a.mean,[2,16]);g.ms=m,v.marker.size=m}f&&(v.line={width:p("line.width",d,[0,10])}),h&&(g.tx="Aa",g.tp=p("textposition",d),g.ts=10,g.tc=p("textfont.color",d),g.tf=p("textfont.family",d)),r=[a.minExtend(s,g)],(i=a.minExtend(c,v)).selectedpoints=null}var y=n.select(this).select("g.legendpoints"),x=y.selectAll("path.scatterpts").data(u?r:[]);x.enter().insert("path",":first-child").classed("scatterpts",!0).attr("transform","translate(20,0)"),x.exit().remove(),x.call(o.pointStyle,i,e),u&&(r[0].mrc=3);var b=y.selectAll("g.pointtext").data(h?r:[]);b.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),b.exit().remove(),b.selectAll("text").call(o.textPointStyle,i,e)}).each(function(t){var e=t[0].trace,r=n.select(this).select("g.legendpoints").selectAll("path.legendcandle").data("candlestick"===e.type&&e.visible?[t,t]:[]);r.enter().append("path").classed("legendcandle",!0).attr("d",function(t,e){return e?"M-15,0H-8M-8,6V-6H8Z":"M15,0H8M8,-6V6H-8Z"}).attr("transform","translate(20,0)").style("stroke-miterlimit",1),r.exit().remove(),r.each(function(t,r){var i=e[r?"increasing":"decreasing"],a=i.line.width,o=n.select(this);o.style("stroke-width",a+"px").call(s.fill,i.fillcolor),a&&s.stroke(o,i.line.color)})}).each(function(t){var e=t[0].trace,r=n.select(this).select("g.legendpoints").selectAll("path.legendohlc").data("ohlc"===e.type&&e.visible?[t,t]:[]);r.enter().append("path").classed("legendohlc",!0).attr("d",function(t,e){return e?"M-15,0H0M-8,-6V0":"M15,0H0M8,6V0"}).attr("transform","translate(20,0)").style("stroke-miterlimit",1),r.exit().remove(),r.each(function(t,r){var i=e[r?"increasing":"decreasing"],a=i.line.width,l=n.select(this);l.style("fill","none").call(o.dashLine,i.line.dash,a),a&&s.stroke(l,i.line.color)})})}},{"../../lib":697,"../../registry":826,"../../traces/pie/style_one":1034,"../../traces/scatter/subtypes":1072,"../color":574,"../drawing":595,d3:151}],632:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("../../plots/plots"),a=t("../../plots/cartesian/axis_ids"),o=t("../../lib"),s=t("../../../build/ploticon"),l=o._,c=e.exports={};function u(t,e){var r,i,o=e.currentTarget,s=o.getAttribute("data-attr"),l=o.getAttribute("data-val")||!0,c=t._fullLayout,u={},h=a.list(t,null,!0),f="on";if("zoom"===s){var p,d="in"===l?.5:2,g=(1+d)/2,v=(1-d)/2;for(i=0;i<h.length;i++)if(!(r=h[i]).fixedrange)if(p=r._name,"auto"===l)u[p+".autorange"]=!0;else if("reset"===l){if(void 0===r._rangeInitial)u[p+".autorange"]=!0;else{var m=r._rangeInitial.slice();u[p+".range[0]"]=m[0],u[p+".range[1]"]=m[1]}void 0!==r._showSpikeInitial&&(u[p+".showspikes"]=r._showSpikeInitial,"on"!==f||r._showSpikeInitial||(f="off"))}else{var y=[r.r2l(r.range[0]),r.r2l(r.range[1])],x=[g*y[0]+v*y[1],g*y[1]+v*y[0]];u[p+".range[0]"]=r.l2r(x[0]),u[p+".range[1]"]=r.l2r(x[1])}c._cartesianSpikesEnabled=f}else{if("hovermode"!==s||"x"!==l&&"y"!==l){if("hovermode"===s&&"closest"===l){for(i=0;i<h.length;i++)r=h[i],"on"!==f||r.showspikes||(f="off");c._cartesianSpikesEnabled=f}}else l=c._isHoriz?"y":"x",o.setAttribute("data-val",l);u[s]=l}n.call("_guiRelayout",t,u)}function h(t,e){for(var r=e.currentTarget,i=r.getAttribute("data-attr"),a=r.getAttribute("data-val")||!0,o=t._fullLayout._subplots.gl3d,s={},l=i.split("."),c=0;c<o.length;c++)s[o[c]+"."+l[1]]=a;var u="pan"===a?a:"zoom";s.dragmode=u,n.call("_guiRelayout",t,s)}function f(t,e){for(var r=e.currentTarget.getAttribute("data-attr"),i=t._fullLayout,a=i._subplots.gl3d,o={},s=0;s<a.length;s++){var l=a[s],c=l+".camera",u=i[l]._scene;"resetLastSave"===r?(o[c+".up"]=u.viewInitial.up,o[c+".eye"]=u.viewInitial.eye,o[c+".center"]=u.viewInitial.center):"resetDefault"===r&&(o[c+".up"]=null,o[c+".eye"]=null,o[c+".center"]=null)}n.call("_guiRelayout",t,o)}function p(t,e){var r=e.currentTarget,n=r._previousVal,i=t._fullLayout,a=i._subplots.gl3d,o=["xaxis","yaxis","zaxis"],s={},l={};if(n)l=n,r._previousVal=null;else{for(var c=0;c<a.length;c++){var u=a[c],h=i[u],f=u+".hovermode";s[f]=h.hovermode,l[f]=!1;for(var p=0;p<3;p++){var d=o[p],g=u+"."+d+".showspikes";l[g]=!1,s[g]=h[d].showspikes}}r._previousVal=s}return l}function d(t,e){for(var r=e.currentTarget,i=r.getAttribute("data-attr"),a=r.getAttribute("data-val")||!0,o=t._fullLayout,s=o._subplots.geo,l=0;l<s.length;l++){var c=s[l],u=o[c];if("zoom"===i){var h=u.projection.scale,f="in"===a?2*h:.5*h;n.call("_guiRelayout",t,c+".projection.scale",f)}else"reset"===i&&m(t,"geo")}}function g(t){var e=t._fullLayout;return!e.hovermode&&(e._has("cartesian")?e._isHoriz?"y":"x":"closest")}function v(t){var e=g(t);n.call("_guiRelayout",t,"hovermode",e)}function m(t,e){for(var r=t._fullLayout,i=r._subplots[e],a={},o=0;o<i.length;o++)for(var s=i[o],l=r[s]._subplot.viewInitial,c=Object.keys(l),u=0;u<c.length;u++){var h=c[u];a[s+"."+h]=l[h]}n.call("_guiRelayout",t,a)}c.toImage={name:"toImage",title:function(t){var e=(t._context.toImageButtonOptions||{}).format||"png";return l(t,"png"===e?"Download plot as a png":"Download plot")},icon:s.camera,click:function(t){var e=t._context.toImageButtonOptions,r={format:e.format||"png"};o.notifier(l(t,"Taking snapshot - this may take a few seconds"),"long"),"svg"!==r.format&&o.isIE()&&(o.notifier(l(t,"IE only supports svg.  Changing format to svg."),"long"),r.format="svg"),["filename","width","height","scale"].forEach(function(t){e[t]&&(r[t]=e[t])}),n.call("downloadImage",t,r).then(function(e){o.notifier(l(t,"Snapshot succeeded")+" - "+e,"long")}).catch(function(){o.notifier(l(t,"Sorry, there was a problem downloading your snapshot!"),"long")})}},c.sendDataToCloud={name:"sendDataToCloud",title:function(t){return l(t,"Edit in Chart Studio")},icon:s.disk,click:function(t){i.sendDataToCloud(t)}},c.zoom2d={name:"zoom2d",title:function(t){return l(t,"Zoom")},attr:"dragmode",val:"zoom",icon:s.zoombox,click:u},c.pan2d={name:"pan2d",title:function(t){return l(t,"Pan")},attr:"dragmode",val:"pan",icon:s.pan,click:u},c.select2d={name:"select2d",title:function(t){return l(t,"Box Select")},attr:"dragmode",val:"select",icon:s.selectbox,click:u},c.lasso2d={name:"lasso2d",title:function(t){return l(t,"Lasso Select")},attr:"dragmode",val:"lasso",icon:s.lasso,click:u},c.zoomIn2d={name:"zoomIn2d",title:function(t){return l(t,"Zoom in")},attr:"zoom",val:"in",icon:s.zoom_plus,click:u},c.zoomOut2d={name:"zoomOut2d",title:function(t){return l(t,"Zoom out")},attr:"zoom",val:"out",icon:s.zoom_minus,click:u},c.autoScale2d={name:"autoScale2d",title:function(t){return l(t,"Autoscale")},attr:"zoom",val:"auto",icon:s.autoscale,click:u},c.resetScale2d={name:"resetScale2d",title:function(t){return l(t,"Reset axes")},attr:"zoom",val:"reset",icon:s.home,click:u},c.hoverClosestCartesian={name:"hoverClosestCartesian",title:function(t){return l(t,"Show closest data on hover")},attr:"hovermode",val:"closest",icon:s.tooltip_basic,gravity:"ne",click:u},c.hoverCompareCartesian={name:"hoverCompareCartesian",title:function(t){return l(t,"Compare data on hover")},attr:"hovermode",val:function(t){return t._fullLayout._isHoriz?"y":"x"},icon:s.tooltip_compare,gravity:"ne",click:u},c.zoom3d={name:"zoom3d",title:function(t){return l(t,"Zoom")},attr:"scene.dragmode",val:"zoom",icon:s.zoombox,click:h},c.pan3d={name:"pan3d",title:function(t){return l(t,"Pan")},attr:"scene.dragmode",val:"pan",icon:s.pan,click:h},c.orbitRotation={name:"orbitRotation",title:function(t){return l(t,"Orbital rotation")},attr:"scene.dragmode",val:"orbit",icon:s["3d_rotate"],click:h},c.tableRotation={name:"tableRotation",title:function(t){return l(t,"Turntable rotation")},attr:"scene.dragmode",val:"turntable",icon:s["z-axis"],click:h},c.resetCameraDefault3d={name:"resetCameraDefault3d",title:function(t){return l(t,"Reset camera to default")},attr:"resetDefault",icon:s.home,click:f},c.resetCameraLastSave3d={name:"resetCameraLastSave3d",title:function(t){return l(t,"Reset camera to last save")},attr:"resetLastSave",icon:s.movie,click:f},c.hoverClosest3d={name:"hoverClosest3d",title:function(t){return l(t,"Toggle show closest data on hover")},attr:"hovermode",val:null,toggle:!0,icon:s.tooltip_basic,gravity:"ne",click:function(t,e){var r=p(t,e);n.call("_guiRelayout",t,r)}},c.zoomInGeo={name:"zoomInGeo",title:function(t){return l(t,"Zoom in")},attr:"zoom",val:"in",icon:s.zoom_plus,click:d},c.zoomOutGeo={name:"zoomOutGeo",title:function(t){return l(t,"Zoom out")},attr:"zoom",val:"out",icon:s.zoom_minus,click:d},c.resetGeo={name:"resetGeo",title:function(t){return l(t,"Reset")},attr:"reset",val:null,icon:s.autoscale,click:d},c.hoverClosestGeo={name:"hoverClosestGeo",title:function(t){return l(t,"Toggle show closest data on hover")},attr:"hovermode",val:null,toggle:!0,icon:s.tooltip_basic,gravity:"ne",click:v},c.hoverClosestGl2d={name:"hoverClosestGl2d",title:function(t){return l(t,"Toggle show closest data on hover")},attr:"hovermode",val:null,toggle:!0,icon:s.tooltip_basic,gravity:"ne",click:v},c.hoverClosestPie={name:"hoverClosestPie",title:function(t){return l(t,"Toggle show closest data on hover")},attr:"hovermode",val:"closest",icon:s.tooltip_basic,gravity:"ne",click:v},c.toggleHover={name:"toggleHover",title:function(t){return l(t,"Toggle show closest data on hover")},attr:"hovermode",val:null,toggle:!0,icon:s.tooltip_basic,gravity:"ne",click:function(t,e){var r=p(t,e);r.hovermode=g(t),n.call("_guiRelayout",t,r)}},c.resetViews={name:"resetViews",title:function(t){return l(t,"Reset views")},icon:s.home,click:function(t,e){var r=e.currentTarget;r.setAttribute("data-attr","zoom"),r.setAttribute("data-val","reset"),u(t,e),r.setAttribute("data-attr","resetLastSave"),f(t,e),m(t,"geo"),m(t,"mapbox")}},c.toggleSpikelines={name:"toggleSpikelines",title:function(t){return l(t,"Toggle Spike Lines")},icon:s.spikeline,attr:"_cartesianSpikesEnabled",val:"on",click:function(t){var e=t._fullLayout;e._cartesianSpikesEnabled="on"===e._cartesianSpikesEnabled?"off":"on";var r=function(t){for(var e,r,n=t._fullLayout,i=a.list(t,null,!0),o={},s=0;s<i.length;s++)e=i[s],r=e._name,o[r+".showspikes"]="on"===n._cartesianSpikesEnabled||e._showSpikeInitial;return o}(t);n.call("_guiRelayout",t,r)}},c.resetViewMapbox={name:"resetViewMapbox",title:function(t){return l(t,"Reset view")},attr:"reset",icon:s.home,click:function(t){m(t,"mapbox")}}},{"../../../build/ploticon":2,"../../lib":697,"../../plots/cartesian/axis_ids":748,"../../plots/plots":807,"../../registry":826}],633:[function(t,e,r){"use strict";r.manage=t("./manage")},{"./manage":634}],634:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axis_ids"),i=t("../../traces/scatter/subtypes"),a=t("../../registry"),o=t("./modebar"),s=t("./buttons");e.exports=function(t){var e=t._fullLayout,r=t._context,l=e._modeBar;if(r.displayModeBar||r.watermark){if(!Array.isArray(r.modeBarButtonsToRemove))throw new Error(["*modeBarButtonsToRemove* configuration options","must be an array."].join(" "));if(!Array.isArray(r.modeBarButtonsToAdd))throw new Error(["*modeBarButtonsToAdd* configuration options","must be an array."].join(" "));var c,u=r.modeBarButtons;c=Array.isArray(u)&&u.length?function(t){for(var e=0;e<t.length;e++)for(var r=t[e],n=0;n<r.length;n++){var i=r[n];if("string"==typeof i){if(void 0===s[i])throw new Error(["*modeBarButtons* configuration options","invalid button name"].join(" "));t[e][n]=s[i]}}return t}(u):!r.displayModeBar&&r.watermark?[]:function(t,e,r,o){var l=t._fullLayout,c=t._fullData,u=l._has("cartesian"),h=l._has("gl3d"),f=l._has("geo"),p=l._has("pie"),d=l._has("gl2d"),g=l._has("ternary"),v=l._has("mapbox"),m=l._has("polar"),y=function(t){for(var e=n.list({_fullLayout:t},null,!0),r=0;r<e.length;r++)if(!e[r].fixedrange)return!1;return!0}(l),x=[];function b(t){if(t.length){for(var r=[],n=0;n<t.length;n++){var i=t[n];-1===e.indexOf(i)&&r.push(s[i])}x.push(r)}}var _=["toImage"];o&&_.push("sendDataToCloud");b(_);var w=[],k=[],A=[],M=[];(u||d||p||g)+f+h+v+m>1?(k=["toggleHover"],A=["resetViews"]):f?(w=["zoomInGeo","zoomOutGeo"],k=["hoverClosestGeo"],A=["resetGeo"]):h?(k=["hoverClosest3d"],A=["resetCameraDefault3d","resetCameraLastSave3d"]):v?(k=["toggleHover"],A=["resetViewMapbox"]):k=d?["hoverClosestGl2d"]:p?["hoverClosestPie"]:["toggleHover"];u&&(k=["toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian"]);!u&&!d||y||(w=["zoomIn2d","zoomOut2d","autoScale2d"],"resetViews"!==A[0]&&(A=["resetScale2d"]));h?M=["zoom3d","pan3d","orbitRotation","tableRotation"]:(u||d)&&!y||g?M=["zoom2d","pan2d"]:v||f?M=["pan2d"]:m&&(M=["zoom2d"]);(function(t){for(var e=!1,r=0;r<t.length&&!e;r++){var n=t[r];n._module&&n._module.selectPoints&&(a.traceIs(n,"scatter-like")?(i.hasMarkers(n)||i.hasText(n))&&(e=!0):a.traceIs(n,"box-violin")&&"all"!==n.boxpoints&&"all"!==n.points||(e=!0))}return e})(c)&&M.push("select2d","lasso2d");return b(M),b(w.concat(A)),b(k),function(t,e){if(e.length)if(Array.isArray(e[0]))for(var r=0;r<e.length;r++)t.push(e[r]);else t.push(e);return t}(x,r)}(t,r.modeBarButtonsToRemove,r.modeBarButtonsToAdd,r.showSendToCloud),l?l.update(t,c):e._modeBar=o(t,c)}else l&&(l.destroy(),delete e._modeBar)}},{"../../plots/cartesian/axis_ids":748,"../../registry":826,"../../traces/scatter/subtypes":1072,"./buttons":632,"./modebar":635}],635:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../../lib"),o=t("../../../build/ploticon"),s=new DOMParser;function l(t){this.container=t.container,this.element=document.createElement("div"),this.update(t.graphInfo,t.buttons),this.container.appendChild(this.element)}var c=l.prototype;c.update=function(t,e){this.graphInfo=t;var r=this.graphInfo._context,n=this.graphInfo._fullLayout,i="modebar-"+n._uid;this.element.setAttribute("id",i),this._uid=i,this.element.className="modebar","hover"===r.displayModeBar&&(this.element.className+=" modebar--hover ease-bg"),"v"===n.modebar.orientation&&(this.element.className+=" vertical",e=e.reverse());var o=n.modebar,s="hover"===r.displayModeBar?".js-plotly-plot .plotly:hover ":"";a.deleteRelatedStyleRule(i),a.addRelatedStyleRule(i,s+"#"+i+" .modebar-group","background-color: "+o.bgcolor),a.addRelatedStyleRule(i,"#"+i+" .modebar-btn .icon path","fill: "+o.color),a.addRelatedStyleRule(i,"#"+i+" .modebar-btn:hover .icon path","fill: "+o.activecolor),a.addRelatedStyleRule(i,"#"+i+" .modebar-btn.active .icon path","fill: "+o.activecolor);var l=!this.hasButtons(e),c=this.hasLogo!==r.displaylogo,u=this.locale!==r.locale;if(this.locale=r.locale,(l||c||u)&&(this.removeAllButtons(),this.updateButtons(e),r.watermark||r.displaylogo)){var h=this.getLogo();r.watermark&&(h.className=h.className+" watermark"),"v"===n.modebar.orientation?this.element.insertBefore(h,this.element.childNodes[0]):this.element.appendChild(h),this.hasLogo=!0}this.updateActiveButton()},c.updateButtons=function(t){var e=this;this.buttons=t,this.buttonElements=[],this.buttonsNames=[],this.buttons.forEach(function(t){var r=e.createGroup();t.forEach(function(t){var n=t.name;if(!n)throw new Error("must provide button 'name' in button config");if(-1!==e.buttonsNames.indexOf(n))throw new Error("button name '"+n+"' is taken");e.buttonsNames.push(n);var i=e.createButton(t);e.buttonElements.push(i),r.appendChild(i)}),e.element.appendChild(r)})},c.createGroup=function(){var t=document.createElement("div");return t.className="modebar-group",t},c.createButton=function(t){var e=this,r=document.createElement("a");r.setAttribute("rel","tooltip"),r.className="modebar-btn";var i=t.title;void 0===i?i=t.name:"function"==typeof i&&(i=i(this.graphInfo)),(i||0===i)&&r.setAttribute("data-title",i),void 0!==t.attr&&r.setAttribute("data-attr",t.attr);var a=t.val;if(void 0!==a&&("function"==typeof a&&(a=a(this.graphInfo)),r.setAttribute("data-val",a)),"function"!=typeof t.click)throw new Error("must provide button 'click' function in button config");r.addEventListener("click",function(r){t.click(e.graphInfo,r),e.updateActiveButton(r.currentTarget)}),r.setAttribute("data-toggle",t.toggle||!1),t.toggle&&n.select(r).classed("active",!0);var s=t.icon;return"function"==typeof s?r.appendChild(s()):r.appendChild(this.createIcon(s||o.question)),r.setAttribute("data-gravity",t.gravity||"n"),r},c.createIcon=function(t){var e,r=i(t.height)?Number(t.height):t.ascent-t.descent,n="http://www.w3.org/2000/svg";if(t.path){(e=document.createElementNS(n,"svg")).setAttribute("viewBox",[0,0,t.width,r].join(" ")),e.setAttribute("class","icon");var a=document.createElementNS(n,"path");a.setAttribute("d",t.path),t.transform?a.setAttribute("transform",t.transform):void 0!==t.ascent&&a.setAttribute("transform","matrix(1 0 0 -1 0 "+t.ascent+")"),e.appendChild(a)}t.svg&&(e=s.parseFromString(t.svg,"application/xml").childNodes[0]);return e.setAttribute("height","1em"),e.setAttribute("width","1em"),e},c.updateActiveButton=function(t){var e=this.graphInfo._fullLayout,r=void 0!==t?t.getAttribute("data-attr"):null;this.buttonElements.forEach(function(t){var i=t.getAttribute("data-val")||!0,o=t.getAttribute("data-attr"),s="true"===t.getAttribute("data-toggle"),l=n.select(t);if(s)o===r&&l.classed("active",!l.classed("active"));else{var c=null===o?o:a.nestedProperty(e,o).get();l.classed("active",c===i)}})},c.hasButtons=function(t){var e=this.buttons;if(!e)return!1;if(t.length!==e.length)return!1;for(var r=0;r<t.length;++r){if(t[r].length!==e[r].length)return!1;for(var n=0;n<t[r].length;n++)if(t[r][n].name!==e[r][n].name)return!1}return!0},c.getLogo=function(){var t=this.createGroup(),e=document.createElement("a");return e.href="https://plot.ly/",e.target="_blank",e.setAttribute("data-title",a._(this.graphInfo,"Produced with Plotly")),e.className="modebar-btn plotlyjsicon modebar-btn--logo",e.appendChild(this.createIcon(o.newplotlylogo)),t.appendChild(e),t},c.removeAllButtons=function(){for(;this.element.firstChild;)this.element.removeChild(this.element.firstChild);this.hasLogo=!1},c.destroy=function(){a.removeElement(this.container.querySelector(".modebar")),a.deleteRelatedStyleRule(this._uid)},e.exports=function(t,e){var r=t._fullLayout,i=new l({graphInfo:t,container:r._modebardiv.node(),buttons:e});return r._privateplot&&n.select(i.element).append("span").classed("badge-private float--left",!0).text("PRIVATE"),i}},{"../../../build/ploticon":2,"../../lib":697,d3:151,"fast-isnumeric":218}],636:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes"),i=t("../color/attributes"),a=(0,t("../../plot_api/plot_template").templatedArray)("button",{visible:{valType:"boolean",dflt:!0,editType:"plot"},step:{valType:"enumerated",values:["month","year","day","hour","minute","second","all"],dflt:"month",editType:"plot"},stepmode:{valType:"enumerated",values:["backward","todate"],dflt:"backward",editType:"plot"},count:{valType:"number",min:0,dflt:1,editType:"plot"},label:{valType:"string",editType:"plot"},editType:"plot"});e.exports={visible:{valType:"boolean",editType:"plot"},buttons:a,x:{valType:"number",min:-2,max:3,editType:"plot"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left",editType:"plot"},y:{valType:"number",min:-2,max:3,editType:"plot"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"bottom",editType:"plot"},font:n({editType:"plot"}),bgcolor:{valType:"color",dflt:i.lightLine,editType:"plot"},activecolor:{valType:"color",editType:"plot"},bordercolor:{valType:"color",dflt:i.defaultLine,editType:"plot"},borderwidth:{valType:"number",min:0,dflt:0,editType:"plot"},editType:"plot"}},{"../../plot_api/plot_template":735,"../../plots/font_attributes":771,"../color/attributes":573}],637:[function(t,e,r){"use strict";e.exports={yPad:.02,minButtonWidth:30,rx:3,ry:3,lightAmount:25,darkAmount:10}},{}],638:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../color"),a=t("../../plot_api/plot_template"),o=t("../../plots/array_container_defaults"),s=t("./attributes"),l=t("./constants");function c(t,e,r,i){var a=i.calendar;function o(r,i){return n.coerce(t,e,s.buttons,r,i)}if(o("visible")){var l=o("step");"all"!==l&&(!a||"gregorian"===a||"month"!==l&&"year"!==l?o("stepmode"):e.stepmode="backward",o("count")),o("label")}}e.exports=function(t,e,r,u,h){var f=t.rangeselector||{},p=a.newContainer(e,"rangeselector");function d(t,e){return n.coerce(f,p,s,t,e)}if(d("visible",o(f,p,{name:"buttons",handleItemDefaults:c,calendar:h}).length>0)){var g=function(t,e,r){for(var n=r.filter(function(r){return e[r].anchor===t._id}),i=0,a=0;a<n.length;a++){var o=e[n[a]].domain;o&&(i=Math.max(o[1],i))}return[t.domain[0],i+l.yPad]}(e,r,u);d("x",g[0]),d("y",g[1]),n.noneOrAll(t,e,["x","y"]),d("xanchor"),d("yanchor"),n.coerceFont(d,"font",r.font);var v=d("bgcolor");d("activecolor",i.contrast(v,l.lightAmount,l.darkAmount)),d("bordercolor"),d("borderwidth")}}},{"../../lib":697,"../../plot_api/plot_template":735,"../../plots/array_container_defaults":741,"../color":574,"./attributes":636,"./constants":637}],639:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../registry"),a=t("../../plots/plots"),o=t("../color"),s=t("../drawing"),l=t("../../lib"),c=t("../../lib/svg_text_utils"),u=t("../../plots/cartesian/axis_ids"),h=t("../../constants/alignment"),f=h.LINE_SPACING,p=h.FROM_TL,d=h.FROM_BR,g=t("./constants"),v=t("./get_update_object");function m(t){return t._id}function y(t,e,r){var n=l.ensureSingle(t,"rect","selector-rect",function(t){t.attr("shape-rendering","crispEdges")});n.attr({rx:g.rx,ry:g.ry}),n.call(o.stroke,e.bordercolor).call(o.fill,function(t,e){return e._isActive||e._isHovered?t.activecolor:t.bgcolor}(e,r)).style("stroke-width",e.borderwidth+"px")}function x(t,e,r,n){l.ensureSingle(t,"text","selector-text",function(t){t.classed("user-select-none",!0).attr("text-anchor","middle")}).call(s.font,e.font).text(function(t,e){if(t.label)return e?l.templateString(t.label,{meta:e}):t.label;return"all"===t.step?"all":t.count+t.step.charAt(0)}(r,n._fullLayout.meta)).call(function(t){c.convertToTspans(t,n)})}e.exports=function(t){var e=t._fullLayout._infolayer.selectAll(".rangeselector").data(function(t){for(var e=u.list(t,"x",!0),r=[],n=0;n<e.length;n++){var i=e[n];i.rangeselector&&i.rangeselector.visible&&r.push(i)}return r}(t),m);e.enter().append("g").classed("rangeselector",!0),e.exit().remove(),e.style({cursor:"pointer","pointer-events":"all"}),e.each(function(e){var r=n.select(this),o=e,u=o.rangeselector,h=r.selectAll("g.button").data(l.filterVisible(u.buttons));h.enter().append("g").classed("button",!0),h.exit().remove(),h.each(function(e){var r=n.select(this),a=v(o,e);e._isActive=function(t,e,r){if("all"===e.step)return!0===t.autorange;var n=Object.keys(r);return t.range[0]===r[n[0]]&&t.range[1]===r[n[1]]}(o,e,a),r.call(y,u,e),r.call(x,u,e,t),r.on("click",function(){t._dragged||i.call("_guiRelayout",t,a)}),r.on("mouseover",function(){e._isHovered=!0,r.call(y,u,e)}),r.on("mouseout",function(){e._isHovered=!1,r.call(y,u,e)})}),function(t,e,r,i,o){var u=0,h=0,v=r.borderwidth;e.each(function(){var t=n.select(this),e=t.select(".selector-text"),i=r.font.size*f,a=Math.max(i*c.lineCount(e),16)+3;h=Math.max(h,a)}),e.each(function(){var t=n.select(this),e=t.select(".selector-rect"),i=t.select(".selector-text"),a=i.node()&&s.bBox(i.node()).width,o=r.font.size*f,l=c.lineCount(i),p=Math.max(a+10,g.minButtonWidth);t.attr("transform","translate("+(v+u)+","+v+")"),e.attr({x:0,y:0,width:p,height:h}),c.positionText(i,p/2,h/2-(l-1)*o/2+3),u+=p+5});var m=t._fullLayout._size,y=m.l+m.w*r.x,x=m.t+m.h*(1-r.y),b="left";l.isRightAnchor(r)&&(y-=u,b="right");l.isCenterAnchor(r)&&(y-=u/2,b="center");var _="top";l.isBottomAnchor(r)&&(x-=h,_="bottom");l.isMiddleAnchor(r)&&(x-=h/2,_="middle");u=Math.ceil(u),h=Math.ceil(h),y=Math.round(y),x=Math.round(x),a.autoMargin(t,i+"-range-selector",{x:r.x,y:r.y,l:u*p[b],r:u*d[b],b:h*d[_],t:h*p[_]}),o.attr("transform","translate("+y+","+x+")")}(t,h,u,o._name,r)})}},{"../../constants/alignment":669,"../../lib":697,"../../lib/svg_text_utils":721,"../../plots/cartesian/axis_ids":748,"../../plots/plots":807,"../../registry":826,"../color":574,"../drawing":595,"./constants":637,"./get_update_object":640,d3:151}],640:[function(t,e,r){"use strict";var n=t("d3");e.exports=function(t,e){var r=t._name,i={};if("all"===e.step)i[r+".autorange"]=!0;else{var a=function(t,e){var r,i=t.range,a=new Date(t.r2l(i[1])),o=e.step,s=e.count;switch(e.stepmode){case"backward":r=t.l2r(+n.time[o].utc.offset(a,-s));break;case"todate":var l=n.time[o].utc.offset(a,-s);r=t.l2r(+n.time[o].utc.ceil(l))}var c=i[1];return[r,c]}(t,e);i[r+".range[0]"]=a[0],i[r+".range[1]"]=a[1]}return i}},{d3:151}],641:[function(t,e,r){"use strict";e.exports={moduleType:"component",name:"rangeselector",schema:{subplots:{xaxis:{rangeselector:t("./attributes")}}},layoutAttributes:t("./attributes"),handleDefaults:t("./defaults"),draw:t("./draw")}},{"./attributes":636,"./defaults":638,"./draw":639}],642:[function(t,e,r){"use strict";var n=t("../color/attributes");e.exports={bgcolor:{valType:"color",dflt:n.background,editType:"plot"},bordercolor:{valType:"color",dflt:n.defaultLine,editType:"plot"},borderwidth:{valType:"integer",dflt:0,min:0,editType:"plot"},autorange:{valType:"boolean",dflt:!0,editType:"calc",impliedEdits:{"range[0]":void 0,"range[1]":void 0}},range:{valType:"info_array",items:[{valType:"any",editType:"calc",impliedEdits:{"^autorange":!1}},{valType:"any",editType:"calc",impliedEdits:{"^autorange":!1}}],editType:"calc",impliedEdits:{autorange:!1}},thickness:{valType:"number",dflt:.15,min:0,max:1,editType:"plot"},visible:{valType:"boolean",dflt:!0,editType:"calc"},editType:"calc"}},{"../color/attributes":573}],643:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axis_ids").list,i=t("../../plots/cartesian/autorange").getAutoRange,a=t("./constants");e.exports=function(t){for(var e=n(t,"x",!0),r=0;r<e.length;r++){var o=e[r],s=o[a.name];s&&s.visible&&s.autorange&&(s._input.autorange=!0,s._input.range=s.range=i(t,o))}}},{"../../plots/cartesian/autorange":744,"../../plots/cartesian/axis_ids":748,"./constants":644}],644:[function(t,e,r){"use strict";e.exports={name:"rangeslider",containerClassName:"rangeslider-container",bgClassName:"rangeslider-bg",rangePlotClassName:"rangeslider-rangeplot",maskMinClassName:"rangeslider-mask-min",maskMaxClassName:"rangeslider-mask-max",slideBoxClassName:"rangeslider-slidebox",grabberMinClassName:"rangeslider-grabber-min",grabAreaMinClassName:"rangeslider-grabarea-min",handleMinClassName:"rangeslider-handle-min",grabberMaxClassName:"rangeslider-grabber-max",grabAreaMaxClassName:"rangeslider-grabarea-max",handleMaxClassName:"rangeslider-handle-max",maskMinOppAxisClassName:"rangeslider-mask-min-opp-axis",maskMaxOppAxisClassName:"rangeslider-mask-max-opp-axis",maskColor:"rgba(0,0,0,0.4)",maskOppAxisColor:"rgba(0,0,0,0.2)",slideBoxFill:"transparent",slideBoxCursor:"ew-resize",grabAreaFill:"transparent",grabAreaCursor:"col-resize",grabAreaWidth:10,handleWidth:4,handleRadius:1,handleStrokeWidth:1,extraPad:15}},{}],645:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plot_api/plot_template"),a=t("../../plots/cartesian/axis_ids"),o=t("./attributes"),s=t("./oppaxis_attributes");e.exports=function(t,e,r){var l=t[r],c=e[r];if(l.rangeslider||e._requestRangeslider[c._id]){n.isPlainObject(l.rangeslider)||(l.rangeslider={});var u,h,f=l.rangeslider,p=i.newContainer(c,"rangeslider");if(_("visible")){_("bgcolor",e.plot_bgcolor),_("bordercolor"),_("borderwidth"),_("thickness"),_("autorange",!c.isValidRange(f.range)),_("range");var d=e._subplots;if(d)for(var g=d.cartesian.filter(function(t){return t.substr(0,t.indexOf("y"))===a.name2id(r)}).map(function(t){return t.substr(t.indexOf("y"),t.length)}),v=n.simpleMap(g,a.id2name),m=0;m<v.length;m++){var y=v[m];u=f[y]||{},h=i.newContainer(p,y,"yaxis");var x,b=e[y];u.range&&b.isValidRange(u.range)&&(x="fixed"),"match"!==w("rangemode",x)&&w("range",b.range.slice())}p._input=f}}function _(t,e){return n.coerce(f,p,o,t,e)}function w(t,e){return n.coerce(u,h,s,t,e)}}},{"../../lib":697,"../../plot_api/plot_template":735,"../../plots/cartesian/axis_ids":748,"./attributes":642,"./oppaxis_attributes":649}],646:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../registry"),a=t("../../plots/plots"),o=t("../../lib"),s=t("../drawing"),l=t("../color"),c=t("../titles"),u=t("../../plots/cartesian"),h=t("../../plots/cartesian/axis_ids"),f=t("../dragelement"),p=t("../../lib/setcursor"),d=t("./constants");function g(t,e,r,n){var i=o.ensureSingle(t,"rect",d.bgClassName,function(t){t.attr({x:0,y:0,"shape-rendering":"crispEdges"})}),a=n.borderwidth%2==0?n.borderwidth:n.borderwidth-1,l=-n._offsetShift,c=s.crispRound(e,n.borderwidth);i.attr({width:n._width+a,height:n._height+a,transform:"translate("+l+","+l+")",fill:n.bgcolor,stroke:n.bordercolor,"stroke-width":c})}function v(t,e,r,n){var i=e._fullLayout;o.ensureSingleById(i._topdefs,"clipPath",n._clipId,function(t){t.append("rect").attr({x:0,y:0})}).select("rect").attr({width:n._width,height:n._height})}function m(t,e,r,i){var l,c=e.calcdata,f=t.selectAll("g."+d.rangePlotClassName).data(r._subplotsWith,o.identity);f.enter().append("g").attr("class",function(t){return d.rangePlotClassName+" "+t}).call(s.setClipUrl,i._clipId,e),f.order(),f.exit().remove(),f.each(function(t,o){var s=n.select(this),f=0===o,p=h.getFromId(e,t,"y"),d=p._name,g=i[d],v={data:[],layout:{xaxis:{type:r.type,domain:[0,1],range:i.range.slice(),calendar:r.calendar},width:i._width,height:i._height,margin:{t:0,b:0,l:0,r:0}},_context:e._context};v.layout[d]={type:p.type,domain:[0,1],range:"match"!==g.rangemode?g.range.slice():p.range.slice(),calendar:p.calendar},a.supplyDefaults(v);var m=v._fullLayout.xaxis,y=v._fullLayout[d];m.clearCalc(),m.setScale(),y.clearCalc(),y.setScale();var x={id:t,plotgroup:s,xaxis:m,yaxis:y,isRangePlot:!0};f?l=x:(x.mainplot="xy",x.mainplotinfo=l),u.rangePlot(e,x,function(t,e){for(var r=[],n=0;n<t.length;n++){var i=t[n],a=i[0].trace;a.xaxis+a.yaxis===e&&r.push(i)}return r}(c,t))})}function y(t,e,r,n,i){(o.ensureSingle(t,"rect",d.maskMinClassName,function(t){t.attr({x:0,y:0,"shape-rendering":"crispEdges"})}).attr("height",n._height).call(l.fill,d.maskColor),o.ensureSingle(t,"rect",d.maskMaxClassName,function(t){t.attr({y:0,"shape-rendering":"crispEdges"})}).attr("height",n._height).call(l.fill,d.maskColor),"match"!==i.rangemode)&&(o.ensureSingle(t,"rect",d.maskMinOppAxisClassName,function(t){t.attr({y:0,"shape-rendering":"crispEdges"})}).attr("width",n._width).call(l.fill,d.maskOppAxisColor),o.ensureSingle(t,"rect",d.maskMaxOppAxisClassName,function(t){t.attr({y:0,"shape-rendering":"crispEdges"})}).attr("width",n._width).style("border-top",d.maskOppBorder).call(l.fill,d.maskOppAxisColor))}function x(t,e,r,n){e._context.staticPlot||o.ensureSingle(t,"rect",d.slideBoxClassName,function(t){t.attr({y:0,cursor:d.slideBoxCursor,"shape-rendering":"crispEdges"})}).attr({height:n._height,fill:d.slideBoxFill})}function b(t,e,r,n){var i=o.ensureSingle(t,"g",d.grabberMinClassName),a=o.ensureSingle(t,"g",d.grabberMaxClassName),s={x:0,width:d.handleWidth,rx:d.handleRadius,fill:l.background,stroke:l.defaultLine,"stroke-width":d.handleStrokeWidth,"shape-rendering":"crispEdges"},c={y:Math.round(n._height/4),height:Math.round(n._height/2)};if(o.ensureSingle(i,"rect",d.handleMinClassName,function(t){t.attr(s)}).attr(c),o.ensureSingle(a,"rect",d.handleMaxClassName,function(t){t.attr(s)}).attr(c),!e._context.staticPlot){var u={width:d.grabAreaWidth,x:0,y:0,fill:d.grabAreaFill,cursor:d.grabAreaCursor};o.ensureSingle(i,"rect",d.grabAreaMinClassName,function(t){t.attr(u)}).attr("height",n._height),o.ensureSingle(a,"rect",d.grabAreaMaxClassName,function(t){t.attr(u)}).attr("height",n._height)}}e.exports=function(t){for(var e=t._fullLayout,r=e._rangeSliderData,a=0;a<r.length;a++){var s=r[a][d.name];s._clipId=s._id+"-"+e._uid}var l=e._infolayer.selectAll("g."+d.containerClassName).data(r,function(t){return t._name});l.exit().each(function(t){var r=t[d.name];e._topdefs.select("#"+r._clipId).remove()}).remove(),0!==r.length&&(l.enter().append("g").classed(d.containerClassName,!0).attr("pointer-events","all"),l.each(function(r){var a=n.select(this),s=r[d.name],l=e[h.id2name(r.anchor)],u=s[h.id2name(r.anchor)];if(s.range){var _,w=o.simpleMap(s.range,r.r2l),k=o.simpleMap(r.range,r.r2l);_=k[0]<k[1]?[Math.min(w[0],k[0]),Math.max(w[1],k[1])]:[Math.max(w[0],k[0]),Math.min(w[1],k[1])],s.range=s._input.range=o.simpleMap(_,r.l2r)}r.cleanRange("rangeslider.range");var A=e.margin,M=e._size,T=r.domain,S=s._tickHeight,E=s._oppBottom;s._width=M.w*(T[1]-T[0]);var C=Math.round(A.l+M.w*T[0]),L=Math.round(M.t+M.h*(1-E)+S+s._offsetShift+d.extraPad);a.attr("transform","translate("+C+","+L+")");var z=r.r2l(s.range[0]),O=r.r2l(s.range[1]),I=O-z;if(s.p2d=function(t){return t/s._width*I+z},s.d2p=function(t){return(t-z)/I*s._width},s._rl=[z,O],"match"!==u.rangemode){var D=l.r2l(u.range[0]),P=l.r2l(u.range[1])-D;s.d2pOppAxis=function(t){return(t-D)/P*s._height}}a.call(g,t,r,s).call(v,t,r,s).call(m,t,r,s).call(y,t,r,s,u).call(x,t,r,s).call(b,t,r,s),function(t,e,r,a){var s=t.select("rect."+d.slideBoxClassName).node(),l=t.select("rect."+d.grabAreaMinClassName).node(),c=t.select("rect."+d.grabAreaMaxClassName).node();t.on("mousedown",function(){var u=n.event,h=u.target,d=u.clientX,g=d-t.node().getBoundingClientRect().left,v=a.d2p(r._rl[0]),m=a.d2p(r._rl[1]),y=f.coverSlip();function x(t){var u,f,x,b=+t.clientX-d;switch(h){case s:x="ew-resize",u=v+b,f=m+b;break;case l:x="col-resize",u=v+b,f=m;break;case c:x="col-resize",u=v,f=m+b;break;default:x="ew-resize",u=g,f=g+b}if(f<u){var _=f;f=u,u=_}a._pixelMin=u,a._pixelMax=f,p(n.select(y),x),function(t,e,r,n){function a(t){return r.l2r(o.constrain(t,n._rl[0],n._rl[1]))}var s=a(n.p2d(n._pixelMin)),l=a(n.p2d(n._pixelMax));window.requestAnimationFrame(function(){i.call("_guiRelayout",e,r._name+".range",[s,l])})}(0,e,r,a)}y.addEventListener("mousemove",x),y.addEventListener("mouseup",function t(){y.removeEventListener("mousemove",x);y.removeEventListener("mouseup",t);o.removeElement(y)})})}(a,t,r,s),function(t,e,r,n,i,a){var s=d.handleWidth/2;function l(t){return o.constrain(t,0,n._width)}function c(t){return o.constrain(t,0,n._height)}function u(t){return o.constrain(t,-s,n._width+s)}var h=l(n.d2p(r._rl[0])),f=l(n.d2p(r._rl[1]));if(t.select("rect."+d.slideBoxClassName).attr("x",h).attr("width",f-h),t.select("rect."+d.maskMinClassName).attr("width",h),t.select("rect."+d.maskMaxClassName).attr("x",f).attr("width",n._width-f),"match"!==a.rangemode){var p=n._height-c(n.d2pOppAxis(i._rl[1])),g=n._height-c(n.d2pOppAxis(i._rl[0]));t.select("rect."+d.maskMinOppAxisClassName).attr("x",h).attr("height",p).attr("width",f-h),t.select("rect."+d.maskMaxOppAxisClassName).attr("x",h).attr("y",g).attr("height",n._height-g).attr("width",f-h),t.select("rect."+d.slideBoxClassName).attr("y",p).attr("height",g-p)}var v=Math.round(u(h-s))-.5,m=Math.round(u(f-s))+.5;t.select("g."+d.grabberMinClassName).attr("transform","translate("+v+",0.5)"),t.select("g."+d.grabberMaxClassName).attr("transform","translate("+m+",0.5)")}(a,0,r,s,l,u),"bottom"===r.side&&c.draw(t,r._id+"title",{propContainer:r,propName:r._name+".title",placeholder:e._dfltTitle.x,attributes:{x:r._offset+r._length/2,y:L+s._height+s._offsetShift+10+1.5*r.title.font.size,"text-anchor":"middle"}})}))}},{"../../lib":697,"../../lib/setcursor":717,"../../plots/cartesian":756,"../../plots/cartesian/axis_ids":748,"../../plots/plots":807,"../../registry":826,"../color":574,"../dragelement":592,"../drawing":595,"../titles":662,"./constants":644,d3:151}],647:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axis_ids"),i=t("./constants"),a=i.name;function o(t){var e=t&&t[a];return e&&e.visible}r.isVisible=o,r.makeData=function(t){var e=n.list({_fullLayout:t},"x",!0),r=t.margin,i=[];if(!t._has("gl2d"))for(var s=0;s<e.length;s++){var l=e[s];if(o(l)){i.push(l);var c=l[a];c._id=a+l._id,c._height=(t.height-r.b-r.t)*c.thickness,c._offsetShift=Math.floor(c.borderwidth/2)}}t._rangeSliderData=i},r.autoMarginOpts=function(t,e){for(var r=e[a],o=1/0,s=e._counterAxes,l=0;l<s.length;l++){var c=s[l],u=n.getFromId(t,c);o=Math.min(o,u.domain[0])}r._oppBottom=o;var h="bottom"===e.side&&e._boundingBox.height||0;return r._tickHeight=h,{x:0,y:o,l:0,r:0,t:0,b:r._height+t._fullLayout.margin.b+h,pad:i.extraPad+2*r._offsetShift}}},{"../../plots/cartesian/axis_ids":748,"./constants":644}],648:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./attributes"),a=t("./oppaxis_attributes"),o=t("./helpers");e.exports={moduleType:"component",name:"rangeslider",schema:{subplots:{xaxis:{rangeslider:n.extendFlat({},i,{yaxis:a})}}},layoutAttributes:t("./attributes"),handleDefaults:t("./defaults"),calcAutorange:t("./calc_autorange"),draw:t("./draw"),isVisible:o.isVisible,makeData:o.makeData,autoMarginOpts:o.autoMarginOpts}},{"../../lib":697,"./attributes":642,"./calc_autorange":643,"./defaults":645,"./draw":646,"./helpers":647,"./oppaxis_attributes":649}],649:[function(t,e,r){"use strict";e.exports={_isSubplotObj:!0,rangemode:{valType:"enumerated",values:["auto","fixed","match"],dflt:"match",editType:"calc"},range:{valType:"info_array",items:[{valType:"any",editType:"plot"},{valType:"any",editType:"plot"}],editType:"plot"},editType:"calc"}},{}],650:[function(t,e,r){"use strict";var n=t("../annotations/attributes"),i=t("../../traces/scatter/attributes").line,a=t("../drawing/attributes").dash,o=t("../../lib/extend").extendFlat,s=t("../../plot_api/plot_template").templatedArray;e.exports=s("shape",{visible:{valType:"boolean",dflt:!0,editType:"calc+arraydraw"},type:{valType:"enumerated",values:["circle","rect","path","line"],editType:"calc+arraydraw"},layer:{valType:"enumerated",values:["below","above"],dflt:"above",editType:"arraydraw"},xref:o({},n.xref,{}),xsizemode:{valType:"enumerated",values:["scaled","pixel"],dflt:"scaled",editType:"calc+arraydraw"},xanchor:{valType:"any",editType:"calc+arraydraw"},x0:{valType:"any",editType:"calc+arraydraw"},x1:{valType:"any",editType:"calc+arraydraw"},yref:o({},n.yref,{}),ysizemode:{valType:"enumerated",values:["scaled","pixel"],dflt:"scaled",editType:"calc+arraydraw"},yanchor:{valType:"any",editType:"calc+arraydraw"},y0:{valType:"any",editType:"calc+arraydraw"},y1:{valType:"any",editType:"calc+arraydraw"},path:{valType:"string",editType:"calc+arraydraw"},opacity:{valType:"number",min:0,max:1,dflt:1,editType:"arraydraw"},line:{color:o({},i.color,{editType:"arraydraw"}),width:o({},i.width,{editType:"calc+arraydraw"}),dash:o({},a,{editType:"arraydraw"}),editType:"calc+arraydraw"},fillcolor:{valType:"color",dflt:"rgba(0,0,0,0)",editType:"arraydraw"},editType:"arraydraw"})},{"../../lib/extend":687,"../../plot_api/plot_template":735,"../../traces/scatter/attributes":1048,"../annotations/attributes":557,"../drawing/attributes":594}],651:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/cartesian/axes"),a=t("./constants"),o=t("./helpers");function s(t){return c(t.line.width,t.xsizemode,t.x0,t.x1,t.path,!1)}function l(t){return c(t.line.width,t.ysizemode,t.y0,t.y1,t.path,!0)}function c(t,e,r,i,s,l){var c=t/2,u=l;if("pixel"===e){var h=s?o.extractPathCoords(s,l?a.paramIsY:a.paramIsX):[r,i],f=n.aggNums(Math.max,null,h),p=n.aggNums(Math.min,null,h),d=p<0?Math.abs(p)+c:c,g=f>0?f+c:c;return{ppad:c,ppadplus:u?d:g,ppadminus:u?g:d}}return{ppad:c}}function u(t,e,r,n,i){var s="category"===t.type||"multicategory"===t.type?t.r2c:t.d2c;if(void 0!==e)return[s(e),s(r)];if(n){var l,c,u,h,f=1/0,p=-1/0,d=n.match(a.segmentRE);for("date"===t.type&&(s=o.decodeDate(s)),l=0;l<d.length;l++)void 0!==(c=i[d[l].charAt(0)].drawn)&&(!(u=d[l].substr(1).match(a.paramRE))||u.length<c||((h=s(u[c]))<f&&(f=h),h>p&&(p=h)));return p>=f?[f,p]:void 0}}e.exports=function(t){var e=t._fullLayout,r=n.filterVisible(e.shapes);if(r.length&&t._fullData.length)for(var o=0;o<r.length;o++){var c,h,f=r[o];if(f._extremes={},"paper"!==f.xref){var p="pixel"===f.xsizemode?f.xanchor:f.x0,d="pixel"===f.xsizemode?f.xanchor:f.x1;(h=u(c=i.getFromId(t,f.xref),p,d,f.path,a.paramIsX))&&(f._extremes[c._id]=i.findExtremes(c,h,s(f)))}if("paper"!==f.yref){var g="pixel"===f.ysizemode?f.yanchor:f.y0,v="pixel"===f.ysizemode?f.yanchor:f.y1;(h=u(c=i.getFromId(t,f.yref),g,v,f.path,a.paramIsY))&&(f._extremes[c._id]=i.findExtremes(c,h,l(f)))}}}},{"../../lib":697,"../../plots/cartesian/axes":745,"./constants":652,"./helpers":655}],652:[function(t,e,r){"use strict";e.exports={segmentRE:/[MLHVQCTSZ][^MLHVQCTSZ]*/g,paramRE:/[^\s,]+/g,paramIsX:{M:{0:!0,drawn:0},L:{0:!0,drawn:0},H:{0:!0,drawn:0},V:{},Q:{0:!0,2:!0,drawn:2},C:{0:!0,2:!0,4:!0,drawn:4},T:{0:!0,drawn:0},S:{0:!0,2:!0,drawn:2},Z:{}},paramIsY:{M:{1:!0,drawn:1},L:{1:!0,drawn:1},H:{},V:{0:!0,drawn:0},Q:{1:!0,3:!0,drawn:3},C:{1:!0,3:!0,5:!0,drawn:5},T:{1:!0,drawn:1},S:{1:!0,3:!0,drawn:5},Z:{}},numParams:{M:2,L:2,H:1,V:1,Q:4,C:6,T:2,S:4,Z:0}}},{}],653:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/cartesian/axes"),a=t("../../plots/array_container_defaults"),o=t("./attributes"),s=t("./helpers");function l(t,e,r){function a(r,i){return n.coerce(t,e,o,r,i)}if(a("visible")){a("layer"),a("opacity"),a("fillcolor"),a("line.color"),a("line.width"),a("line.dash");for(var l=a("type",t.path?"path":"rect"),c=a("xsizemode"),u=a("ysizemode"),h=["x","y"],f=0;f<2;f++){var p,d,g,v=h[f],m=v+"anchor",y="x"===v?c:u,x={_fullLayout:r},b=i.coerceRef(t,e,x,v,"","paper");if("paper"!==b?((p=i.getFromId(x,b))._shapeIndices.push(e._index),g=s.rangeToShapePosition(p),d=s.shapePositionToRange(p)):d=g=n.identity,"path"!==l){var _=v+"0",w=v+"1",k=t[_],A=t[w];t[_]=d(t[_],!0),t[w]=d(t[w],!0),"pixel"===y?(a(_,0),a(w,10)):(i.coercePosition(e,x,a,b,_,.25),i.coercePosition(e,x,a,b,w,.75)),e[_]=g(e[_]),e[w]=g(e[w]),t[_]=k,t[w]=A}if("pixel"===y){var M=t[m];t[m]=d(t[m],!0),i.coercePosition(e,x,a,b,m,.25),e[m]=g(e[m]),t[m]=M}}"path"===l?a("path"):n.noneOrAll(t,e,["x0","x1","y0","y1"])}}e.exports=function(t,e){a(t,e,{name:"shapes",handleItemDefaults:l})}},{"../../lib":697,"../../plots/array_container_defaults":741,"../../plots/cartesian/axes":745,"./attributes":650,"./helpers":655}],654:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("../../lib"),a=t("../../plots/cartesian/axes"),o=t("../color"),s=t("../drawing"),l=t("../../plot_api/plot_template").arrayEditor,c=t("../dragelement"),u=t("../../lib/setcursor"),h=t("./constants"),f=t("./helpers");function p(t,e){t._fullLayout._paperdiv.selectAll('.shapelayer [data-index="'+e+'"]').remove();var r=t._fullLayout.shapes[e]||{};if(r._input&&!1!==r.visible)if("below"!==r.layer)m(t._fullLayout._shapeUpperLayer);else if("paper"===r.xref||"paper"===r.yref)m(t._fullLayout._shapeLowerLayer);else{var p=t._fullLayout._plots[r.xref+r.yref];if(p)m((p.mainplotinfo||p).shapelayer);else m(t._fullLayout._shapeLowerLayer)}function m(p){var m={"data-index":e,"fill-rule":"evenodd",d:g(t,r)},y=r.line.width?r.line.color:"rgba(0,0,0,0)",x=p.append("path").attr(m).style("opacity",r.opacity).call(o.stroke,y).call(o.fill,r.fillcolor).call(s.dashLine,r.line.dash,r.line.width);d(x,t,r),t._context.edits.shapePosition&&function(t,e,r,o,p){var m,y,x,b,_,w,k,A,M,T,S,E,C,L,z,O,I=10,D=10,P="pixel"===r.xsizemode,R="pixel"===r.ysizemode,F="line"===r.type,B="path"===r.type,N=l(t.layout,"shapes",r),j=N.modifyItem,V=a.getFromId(t,r.xref),U=a.getFromId(t,r.yref),q=f.getDataToPixel(t,V),H=f.getDataToPixel(t,U,!0),G=f.getPixelToData(t,V),Y=f.getPixelToData(t,U,!0),W=F?function(){var t=Math.max(r.line.width,10),n=p.append("g").attr("data-index",o);n.append("path").attr("d",e.attr("d")).style({cursor:"move","stroke-width":t,"stroke-opacity":"0"});var i={"fill-opacity":"0"},a=t/2>10?t/2:10;return n.append("circle").attr({"data-line-point":"start-point",cx:P?q(r.xanchor)+r.x0:q(r.x0),cy:R?H(r.yanchor)-r.y0:H(r.y0),r:a}).style(i).classed("cursor-grab",!0),n.append("circle").attr({"data-line-point":"end-point",cx:P?q(r.xanchor)+r.x1:q(r.x1),cy:R?H(r.yanchor)-r.y1:H(r.y1),r:a}).style(i).classed("cursor-grab",!0),n}():e,X={element:W.node(),gd:t,prepFn:function(n){P&&(_=q(r.xanchor));R&&(w=H(r.yanchor));"path"===r.type?z=r.path:(m=P?r.x0:q(r.x0),y=R?r.y0:H(r.y0),x=P?r.x1:q(r.x1),b=R?r.y1:H(r.y1));m<x?(M=m,C="x0",T=x,L="x1"):(M=x,C="x1",T=m,L="x0");!R&&y<b||R&&y>b?(k=y,S="y0",A=b,E="y1"):(k=b,S="y1",A=y,E="y0");Z(n),K(p,r),function(t,e,r){var n=e.xref,i=e.yref,o=a.getFromId(r,n),l=a.getFromId(r,i),c="";"paper"===n||o.autorange||(c+=n);"paper"===i||l.autorange||(c+=i);s.setClipUrl(t,c?"clip"+r._fullLayout._uid+c:null,r)}(e,r,t),X.moveFn="move"===O?$:J},doneFn:function(){u(e),Q(p),d(e,t,r),n.call("_guiRelayout",t,N.getUpdateObj())},clickFn:function(){Q(p)}};function Z(t){if(F)O="path"===t.target.tagName?"move":"start-point"===t.target.attributes["data-line-point"].value?"resize-over-start-point":"resize-over-end-point";else{var r=X.element.getBoundingClientRect(),n=r.right-r.left,i=r.bottom-r.top,a=t.clientX-r.left,o=t.clientY-r.top,s=!B&&n>I&&i>D&&!t.shiftKey?c.getCursor(a/n,1-o/i):"move";u(e,s),O=s.split("-")[0]}}function $(n,i){if("path"===r.type){var a=function(t){return t},o=a,s=a;P?j("xanchor",r.xanchor=G(_+n)):(o=function(t){return G(q(t)+n)},V&&"date"===V.type&&(o=f.encodeDate(o))),R?j("yanchor",r.yanchor=Y(w+i)):(s=function(t){return Y(H(t)+i)},U&&"date"===U.type&&(s=f.encodeDate(s))),j("path",r.path=v(z,o,s))}else P?j("xanchor",r.xanchor=G(_+n)):(j("x0",r.x0=G(m+n)),j("x1",r.x1=G(x+n))),R?j("yanchor",r.yanchor=Y(w+i)):(j("y0",r.y0=Y(y+i)),j("y1",r.y1=Y(b+i)));e.attr("d",g(t,r)),K(p,r)}function J(n,i){if(B){var a=function(t){return t},o=a,s=a;P?j("xanchor",r.xanchor=G(_+n)):(o=function(t){return G(q(t)+n)},V&&"date"===V.type&&(o=f.encodeDate(o))),R?j("yanchor",r.yanchor=Y(w+i)):(s=function(t){return Y(H(t)+i)},U&&"date"===U.type&&(s=f.encodeDate(s))),j("path",r.path=v(z,o,s))}else if(F){if("resize-over-start-point"===O){var l=m+n,c=R?y-i:y+i;j("x0",r.x0=P?l:G(l)),j("y0",r.y0=R?c:Y(c))}else if("resize-over-end-point"===O){var u=x+n,h=R?b-i:b+i;j("x1",r.x1=P?u:G(u)),j("y1",r.y1=R?h:Y(h))}}else{var d=~O.indexOf("n")?k+i:k,N=~O.indexOf("s")?A+i:A,W=~O.indexOf("w")?M+n:M,X=~O.indexOf("e")?T+n:T;~O.indexOf("n")&&R&&(d=k-i),~O.indexOf("s")&&R&&(N=A-i),(!R&&N-d>D||R&&d-N>D)&&(j(S,r[S]=R?d:Y(d)),j(E,r[E]=R?N:Y(N))),X-W>I&&(j(C,r[C]=P?W:G(W)),j(L,r[L]=P?X:G(X)))}e.attr("d",g(t,r)),K(p,r)}function K(t,e){(P||R)&&function(){var r="path"!==e.type,n=t.selectAll(".visual-cue").data([0]);n.enter().append("path").attr({fill:"#fff","fill-rule":"evenodd",stroke:"#000","stroke-width":1}).classed("visual-cue",!0);var a=q(P?e.xanchor:i.midRange(r?[e.x0,e.x1]:f.extractPathCoords(e.path,h.paramIsX))),o=H(R?e.yanchor:i.midRange(r?[e.y0,e.y1]:f.extractPathCoords(e.path,h.paramIsY)));if(a=f.roundPositionForSharpStrokeRendering(a,1),o=f.roundPositionForSharpStrokeRendering(o,1),P&&R){var s="M"+(a-1-1)+","+(o-1-1)+"h-8v2h8 v8h2v-8 h8v-2h-8 v-8h-2 Z";n.attr("d",s)}else if(P){var l="M"+(a-1-1)+","+(o-9-1)+"v18 h2 v-18 Z";n.attr("d",l)}else{var c="M"+(a-9-1)+","+(o-1-1)+"h18 v2 h-18 Z";n.attr("d",c)}}()}function Q(t){t.selectAll(".visual-cue").remove()}c.init(X),W.node().onmousemove=Z}(t,x,r,e,p)}}function d(t,e,r){var n=(r.xref+r.yref).replace(/paper/g,"");s.setClipUrl(t,n?"clip"+e._fullLayout._uid+n:null,e)}function g(t,e){var r,n,o,s,l,c,u,p,d=e.type,g=a.getFromId(t,e.xref),v=a.getFromId(t,e.yref),m=t._fullLayout._size;if(g?(r=f.shapePositionToRange(g),n=function(t){return g._offset+g.r2p(r(t,!0))}):n=function(t){return m.l+m.w*t},v?(o=f.shapePositionToRange(v),s=function(t){return v._offset+v.r2p(o(t,!0))}):s=function(t){return m.t+m.h*(1-t)},"path"===d)return g&&"date"===g.type&&(n=f.decodeDate(n)),v&&"date"===v.type&&(s=f.decodeDate(s)),function(t,e,r){var n=t.path,a=t.xsizemode,o=t.ysizemode,s=t.xanchor,l=t.yanchor;return n.replace(h.segmentRE,function(t){var n=0,c=t.charAt(0),u=h.paramIsX[c],f=h.paramIsY[c],p=h.numParams[c],d=t.substr(1).replace(h.paramRE,function(t){return u[n]?t="pixel"===a?e(s)+Number(t):e(t):f[n]&&(t="pixel"===o?r(l)-Number(t):r(t)),++n>p&&(t="X"),t});return n>p&&(d=d.replace(/[\s,]*X.*/,""),i.log("Ignoring extra params in segment "+t)),c+d})}(e,n,s);if("pixel"===e.xsizemode){var y=n(e.xanchor);l=y+e.x0,c=y+e.x1}else l=n(e.x0),c=n(e.x1);if("pixel"===e.ysizemode){var x=s(e.yanchor);u=x-e.y0,p=x-e.y1}else u=s(e.y0),p=s(e.y1);if("line"===d)return"M"+l+","+u+"L"+c+","+p;if("rect"===d)return"M"+l+","+u+"H"+c+"V"+p+"H"+l+"Z";var b=(l+c)/2,_=(u+p)/2,w=Math.abs(b-l),k=Math.abs(_-u),A="A"+w+","+k,M=b+w+","+_;return"M"+M+A+" 0 1,1 "+(b+","+(_-k))+A+" 0 0,1 "+M+"Z"}function v(t,e,r){return t.replace(h.segmentRE,function(t){var n=0,i=t.charAt(0),a=h.paramIsX[i],o=h.paramIsY[i],s=h.numParams[i];return i+t.substr(1).replace(h.paramRE,function(t){return n>=s?t:(a[n]?t=e(t):o[n]&&(t=r(t)),n++,t)})})}e.exports={draw:function(t){var e=t._fullLayout;for(var r in e._shapeUpperLayer.selectAll("path").remove(),e._shapeLowerLayer.selectAll("path").remove(),e._plots){var n=e._plots[r].shapelayer;n&&n.selectAll("path").remove()}for(var i=0;i<e.shapes.length;i++)e.shapes[i].visible&&p(t,i)},drawOne:p}},{"../../lib":697,"../../lib/setcursor":717,"../../plot_api/plot_template":735,"../../plots/cartesian/axes":745,"../../registry":826,"../color":574,"../dragelement":592,"../drawing":595,"./constants":652,"./helpers":655}],655:[function(t,e,r){"use strict";var n=t("./constants"),i=t("../../lib");r.rangeToShapePosition=function(t){return"log"===t.type?t.r2d:function(t){return t}},r.shapePositionToRange=function(t){return"log"===t.type?t.d2r:function(t){return t}},r.decodeDate=function(t){return function(e){return e.replace&&(e=e.replace("_"," ")),t(e)}},r.encodeDate=function(t){return function(e){return t(e).replace(" ","_")}},r.extractPathCoords=function(t,e){var r=[];return t.match(n.segmentRE).forEach(function(t){var a=e[t.charAt(0)].drawn;if(void 0!==a){var o=t.substr(1).match(n.paramRE);!o||o.length<a||r.push(i.cleanNumber(o[a]))}}),r},r.getDataToPixel=function(t,e,n){var i,a=t._fullLayout._size;if(e){var o=r.shapePositionToRange(e);i=function(t){return e._offset+e.r2p(o(t,!0))},"date"===e.type&&(i=r.decodeDate(i))}else i=n?function(t){return a.t+a.h*(1-t)}:function(t){return a.l+a.w*t};return i},r.getPixelToData=function(t,e,n){var i,a=t._fullLayout._size;if(e){var o=r.rangeToShapePosition(e);i=function(t){return o(e.p2r(t-e._offset))}}else i=n?function(t){return 1-(t-a.t)/a.h}:function(t){return(t-a.l)/a.w};return i},r.roundPositionForSharpStrokeRendering=function(t,e){var r=1===Math.round(e%2),n=Math.round(t);return r?n+.5:n}},{"../../lib":697,"./constants":652}],656:[function(t,e,r){"use strict";var n=t("./draw");e.exports={moduleType:"component",name:"shapes",layoutAttributes:t("./attributes"),supplyLayoutDefaults:t("./defaults"),includeBasePlot:t("../../plots/cartesian/include_components")("shapes"),calcAutorange:t("./calc_autorange"),draw:n.draw,drawOne:n.drawOne}},{"../../plots/cartesian/include_components":755,"./attributes":650,"./calc_autorange":651,"./defaults":653,"./draw":654}],657:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes"),i=t("../../plots/pad_attributes"),a=t("../../lib/extend").extendDeepAll,o=t("../../plot_api/edit_types").overrideAll,s=t("../../plots/animation_attributes"),l=t("../../plot_api/plot_template").templatedArray,c=t("./constants"),u=l("step",{visible:{valType:"boolean",dflt:!0},method:{valType:"enumerated",values:["restyle","relayout","animate","update","skip"],dflt:"restyle"},args:{valType:"info_array",freeLength:!0,items:[{valType:"any"},{valType:"any"},{valType:"any"}]},label:{valType:"string"},value:{valType:"string"},execute:{valType:"boolean",dflt:!0}});e.exports=o(l("slider",{visible:{valType:"boolean",dflt:!0},active:{valType:"number",min:0,dflt:0},steps:u,lenmode:{valType:"enumerated",values:["fraction","pixels"],dflt:"fraction"},len:{valType:"number",min:0,dflt:1},x:{valType:"number",min:-2,max:3,dflt:0},pad:a(i({editType:"arraydraw"}),{},{t:{dflt:20}}),xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left"},y:{valType:"number",min:-2,max:3,dflt:0},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"top"},transition:{duration:{valType:"number",min:0,dflt:150},easing:{valType:"enumerated",values:s.transition.easing.values,dflt:"cubic-in-out"}},currentvalue:{visible:{valType:"boolean",dflt:!0},xanchor:{valType:"enumerated",values:["left","center","right"],dflt:"left"},offset:{valType:"number",dflt:10},prefix:{valType:"string"},suffix:{valType:"string"},font:n({})},font:n({}),activebgcolor:{valType:"color",dflt:c.gripBgActiveColor},bgcolor:{valType:"color",dflt:c.railBgColor},bordercolor:{valType:"color",dflt:c.railBorderColor},borderwidth:{valType:"number",min:0,dflt:c.railBorderWidth},ticklen:{valType:"number",min:0,dflt:c.tickLength},tickcolor:{valType:"color",dflt:c.tickColor},tickwidth:{valType:"number",min:0,dflt:1},minorticklen:{valType:"number",min:0,dflt:c.minorTickLength}}),"arraydraw","from-root")},{"../../lib/extend":687,"../../plot_api/edit_types":728,"../../plot_api/plot_template":735,"../../plots/animation_attributes":740,"../../plots/font_attributes":771,"../../plots/pad_attributes":806,"./constants":658}],658:[function(t,e,r){"use strict";e.exports={name:"sliders",containerClassName:"slider-container",groupClassName:"slider-group",inputAreaClass:"slider-input-area",railRectClass:"slider-rail-rect",railTouchRectClass:"slider-rail-touch-rect",gripRectClass:"slider-grip-rect",tickRectClass:"slider-tick-rect",inputProxyClass:"slider-input-proxy",labelsClass:"slider-labels",labelGroupClass:"slider-label-group",labelClass:"slider-label",currentValueClass:"slider-current-value",railHeight:5,menuIndexAttrName:"slider-active-index",autoMarginIdRoot:"slider-",minWidth:30,minHeight:30,textPadX:40,arrowOffsetX:4,railRadius:2,railWidth:5,railBorder:4,railBorderWidth:1,railBorderColor:"#bec8d9",railBgColor:"#f8fafc",railInset:8,stepInset:10,gripRadius:10,gripWidth:20,gripHeight:20,gripBorder:20,gripBorderWidth:1,gripBorderColor:"#bec8d9",gripBgColor:"#f6f8fa",gripBgActiveColor:"#dbdde0",labelPadding:8,labelOffset:0,tickWidth:1,tickColor:"#333",tickOffset:25,tickLength:7,minorTickOffset:25,minorTickColor:"#333",minorTickLength:4,currentValuePadding:8,currentValueInset:0}},{}],659:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/array_container_defaults"),a=t("./attributes"),o=t("./constants").name,s=a.steps;function l(t,e,r){function o(r,i){return n.coerce(t,e,a,r,i)}for(var s=i(t,e,{name:"steps",handleItemDefaults:c}),l=0,u=0;u<s.length;u++)s[u].visible&&l++;if(l<2?e.visible=!1:o("visible")){e._stepCount=l;var h=e._visibleSteps=n.filterVisible(s);(s[o("active")]||{}).visible||(e.active=h[0]._index),o("x"),o("y"),n.noneOrAll(t,e,["x","y"]),o("xanchor"),o("yanchor"),o("len"),o("lenmode"),o("pad.t"),o("pad.r"),o("pad.b"),o("pad.l"),n.coerceFont(o,"font",r.font),o("currentvalue.visible")&&(o("currentvalue.xanchor"),o("currentvalue.prefix"),o("currentvalue.suffix"),o("currentvalue.offset"),n.coerceFont(o,"currentvalue.font",e.font)),o("transition.duration"),o("transition.easing"),o("bgcolor"),o("activebgcolor"),o("bordercolor"),o("borderwidth"),o("ticklen"),o("tickwidth"),o("tickcolor"),o("minorticklen")}}function c(t,e){function r(r,i){return n.coerce(t,e,s,r,i)}if("skip"===t.method||Array.isArray(t.args)?r("visible"):e.visible=!1){r("method"),r("args");var i=r("label","step-"+e._index);r("value",i),r("execute")}}e.exports=function(t,e){i(t,e,{name:o,handleItemDefaults:l})}},{"../../lib":697,"../../plots/array_container_defaults":741,"./attributes":657,"./constants":658}],660:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../plots/plots"),a=t("../color"),o=t("../drawing"),s=t("../../lib"),l=t("../../lib/svg_text_utils"),c=t("../../plot_api/plot_template").arrayEditor,u=t("./constants"),h=t("../../constants/alignment"),f=h.LINE_SPACING,p=h.FROM_TL,d=h.FROM_BR;function g(t){return u.autoMarginIdRoot+t._index}function v(t){return t._index}function m(t,e){var r=o.tester.selectAll("g."+u.labelGroupClass).data(e._visibleSteps);r.enter().append("g").classed(u.labelGroupClass,!0);var a=0,c=0;r.each(function(t){var r=b(n.select(this),{step:t},e).node();if(r){var i=o.bBox(r);c=Math.max(c,i.height),a=Math.max(a,i.width)}}),r.remove();var h=e._dims={};h.inputAreaWidth=Math.max(u.railWidth,u.gripHeight);var f=t._fullLayout._size;h.lx=f.l+f.w*e.x,h.ly=f.t+f.h*(1-e.y),"fraction"===e.lenmode?h.outerLength=Math.round(f.w*e.len):h.outerLength=e.len,h.inputAreaStart=0,h.inputAreaLength=Math.round(h.outerLength-e.pad.l-e.pad.r);var v=(h.inputAreaLength-2*u.stepInset)/(e._stepCount-1),m=a+u.labelPadding;if(h.labelStride=Math.max(1,Math.ceil(m/v)),h.labelHeight=c,h.currentValueMaxWidth=0,h.currentValueHeight=0,h.currentValueTotalHeight=0,h.currentValueMaxLines=1,e.currentvalue.visible){var x=o.tester.append("g");r.each(function(t){var r=y(x,e,t.label),n=r.node()&&o.bBox(r.node())||{width:0,height:0},i=l.lineCount(r);h.currentValueMaxWidth=Math.max(h.currentValueMaxWidth,Math.ceil(n.width)),h.currentValueHeight=Math.max(h.currentValueHeight,Math.ceil(n.height)),h.currentValueMaxLines=Math.max(h.currentValueMaxLines,i)}),h.currentValueTotalHeight=h.currentValueHeight+e.currentvalue.offset,x.remove()}h.height=h.currentValueTotalHeight+u.tickOffset+e.ticklen+u.labelOffset+h.labelHeight+e.pad.t+e.pad.b;var _="left";s.isRightAnchor(e)&&(h.lx-=h.outerLength,_="right"),s.isCenterAnchor(e)&&(h.lx-=h.outerLength/2,_="center");var w="top";s.isBottomAnchor(e)&&(h.ly-=h.height,w="bottom"),s.isMiddleAnchor(e)&&(h.ly-=h.height/2,w="middle"),h.outerLength=Math.ceil(h.outerLength),h.height=Math.ceil(h.height),h.lx=Math.round(h.lx),h.ly=Math.round(h.ly);var k={y:e.y,b:h.height*d[w],t:h.height*p[w]};"fraction"===e.lenmode?(k.l=0,k.xl=e.x-e.len*p[_],k.r=0,k.xr=e.x+e.len*d[_]):(k.x=e.x,k.l=h.outerLength*p[_],k.r=h.outerLength*d[_]),i.autoMargin(t,g(e),k)}function y(t,e,r){if(e.currentvalue.visible){var n,i,a=e._dims;switch(e.currentvalue.xanchor){case"right":n=a.inputAreaLength-u.currentValueInset-a.currentValueMaxWidth,i="left";break;case"center":n=.5*a.inputAreaLength,i="middle";break;default:n=u.currentValueInset,i="left"}var c=s.ensureSingle(t,"text",u.labelClass,function(t){t.classed("user-select-none",!0).attr({"text-anchor":i,"data-notex":1})}),h=e.currentvalue.prefix?e.currentvalue.prefix:"";if("string"==typeof r)h+=r;else{var p=e.steps[e.active].label,d=e._gd._fullLayout.meta;d&&(p=s.templateString(p,{meta:d})),h+=p}e.currentvalue.suffix&&(h+=e.currentvalue.suffix),c.call(o.font,e.currentvalue.font).text(h).call(l.convertToTspans,e._gd);var g=l.lineCount(c),v=(a.currentValueMaxLines+1-g)*e.currentvalue.font.size*f;return l.positionText(c,n,v),c}}function x(t,e,r){s.ensureSingle(t,"rect",u.gripRectClass,function(n){n.call(A,e,t,r).style("pointer-events","all")}).attr({width:u.gripWidth,height:u.gripHeight,rx:u.gripRadius,ry:u.gripRadius}).call(a.stroke,r.bordercolor).call(a.fill,r.bgcolor).style("stroke-width",r.borderwidth+"px")}function b(t,e,r){var n=s.ensureSingle(t,"text",u.labelClass,function(t){t.classed("user-select-none",!0).attr({"text-anchor":"middle","data-notex":1})}),i=e.step.label,a=r._gd._fullLayout.meta;return a&&(i=s.templateString(i,{meta:a})),n.call(o.font,r.font).text(i).call(l.convertToTspans,r._gd),n}function _(t,e){var r=s.ensureSingle(t,"g",u.labelsClass),i=e._dims,a=r.selectAll("g."+u.labelGroupClass).data(i.labelSteps);a.enter().append("g").classed(u.labelGroupClass,!0),a.exit().remove(),a.each(function(t){var r=n.select(this);r.call(b,t,e),o.setTranslate(r,S(e,t.fraction),u.tickOffset+e.ticklen+e.font.size*f+u.labelOffset+i.currentValueTotalHeight)})}function w(t,e,r,n,i){var a=Math.round(n*(r._stepCount-1)),o=r._visibleSteps[a]._index;o!==r.active&&k(t,e,r,o,!0,i)}function k(t,e,r,n,a,o){var s=r.active;r.active=n,c(t.layout,u.name,r).applyUpdate("active",n);var l=r.steps[r.active];e.call(T,r,o),e.call(y,r),t.emit("plotly_sliderchange",{slider:r,step:r.steps[r.active],interaction:a,previousActive:s}),l&&l.method&&a&&(e._nextMethod?(e._nextMethod.step=l,e._nextMethod.doCallback=a,e._nextMethod.doTransition=o):(e._nextMethod={step:l,doCallback:a,doTransition:o},e._nextMethodRaf=window.requestAnimationFrame(function(){var r=e._nextMethod.step;r.method&&(r.execute&&i.executeAPICommand(t,r.method,r.args),e._nextMethod=null,e._nextMethodRaf=null)})))}function A(t,e,r){var i=r.node(),o=n.select(e);function s(){return r.data()[0]}t.on("mousedown",function(){var t=s();e.emit("plotly_sliderstart",{slider:t});var l=r.select("."+u.gripRectClass);n.event.stopPropagation(),n.event.preventDefault(),l.call(a.fill,t.activebgcolor);var c=E(t,n.mouse(i)[0]);w(e,r,t,c,!0),t._dragging=!0,o.on("mousemove",function(){var t=s(),a=E(t,n.mouse(i)[0]);w(e,r,t,a,!1)}),o.on("mouseup",function(){var t=s();t._dragging=!1,l.call(a.fill,t.bgcolor),o.on("mouseup",null),o.on("mousemove",null),e.emit("plotly_sliderend",{slider:t,step:t.steps[t.active]})})})}function M(t,e){var r=t.selectAll("rect."+u.tickRectClass).data(e._visibleSteps),i=e._dims;r.enter().append("rect").classed(u.tickRectClass,!0),r.exit().remove(),r.attr({width:e.tickwidth+"px","shape-rendering":"crispEdges"}),r.each(function(t,r){var s=r%i.labelStride==0,l=n.select(this);l.attr({height:s?e.ticklen:e.minorticklen}).call(a.fill,e.tickcolor),o.setTranslate(l,S(e,r/(e._stepCount-1))-.5*e.tickwidth,(s?u.tickOffset:u.minorTickOffset)+i.currentValueTotalHeight)})}function T(t,e,r){for(var n=t.select("rect."+u.gripRectClass),i=0,a=0;a<e._stepCount;a++)if(e._visibleSteps[a]._index===e.active){i=a;break}var o=S(e,i/(e._stepCount-1));if(!e._invokingCommand){var s=n;r&&e.transition.duration>0&&(s=s.transition().duration(e.transition.duration).ease(e.transition.easing)),s.attr("transform","translate("+(o-.5*u.gripWidth)+","+e._dims.currentValueTotalHeight+")")}}function S(t,e){var r=t._dims;return r.inputAreaStart+u.stepInset+(r.inputAreaLength-2*u.stepInset)*Math.min(1,Math.max(0,e))}function E(t,e){var r=t._dims;return Math.min(1,Math.max(0,(e-u.stepInset-r.inputAreaStart)/(r.inputAreaLength-2*u.stepInset-2*r.inputAreaStart)))}function C(t,e,r){var n=r._dims,i=s.ensureSingle(t,"rect",u.railTouchRectClass,function(n){n.call(A,e,t,r).style("pointer-events","all")});i.attr({width:n.inputAreaLength,height:Math.max(n.inputAreaWidth,u.tickOffset+r.ticklen+n.labelHeight)}).call(a.fill,r.bgcolor).attr("opacity",0),o.setTranslate(i,0,n.currentValueTotalHeight)}function L(t,e){var r=e._dims,n=r.inputAreaLength-2*u.railInset,i=s.ensureSingle(t,"rect",u.railRectClass);i.attr({width:n,height:u.railWidth,rx:u.railRadius,ry:u.railRadius,"shape-rendering":"crispEdges"}).call(a.stroke,e.bordercolor).call(a.fill,e.bgcolor).style("stroke-width",e.borderwidth+"px"),o.setTranslate(i,u.railInset,.5*(r.inputAreaWidth-u.railWidth)+r.currentValueTotalHeight)}e.exports=function(t){var e=t._fullLayout,r=function(t,e){for(var r=t[u.name],n=[],i=0;i<r.length;i++){var a=r[i];a.visible&&(a._gd=e,n.push(a))}return n}(e,t),a=e._infolayer.selectAll("g."+u.containerClassName).data(r.length>0?[0]:[]);function s(e){e._commandObserver&&(e._commandObserver.remove(),delete e._commandObserver),i.autoMargin(t,g(e))}if(a.enter().append("g").classed(u.containerClassName,!0).style("cursor","ew-resize"),a.exit().each(function(){n.select(this).selectAll("g."+u.groupClassName).each(s)}).remove(),0!==r.length){var l=a.selectAll("g."+u.groupClassName).data(r,v);l.enter().append("g").classed(u.groupClassName,!0),l.exit().each(s).remove();for(var c=0;c<r.length;c++){var h=r[c];m(t,h)}l.each(function(e){var r=n.select(this);!function(t){var e=t._dims;e.labelSteps=[];for(var r=t._stepCount,n=0;n<r;n+=e.labelStride)e.labelSteps.push({fraction:n/(r-1),step:t._visibleSteps[n]})}(e),i.manageCommandObserver(t,e,e._visibleSteps,function(e){var n=r.data()[0];n.active!==e.index&&(n._dragging||k(t,r,n,e.index,!1,!0))}),function(t,e,r){(r.steps[r.active]||{}).visible||(r.active=r._visibleSteps[0]._index);e.call(y,r).call(L,r).call(_,r).call(M,r).call(C,t,r).call(x,t,r);var n=r._dims;o.setTranslate(e,n.lx+r.pad.l,n.ly+r.pad.t),e.call(T,r,!1),e.call(y,r)}(t,n.select(this),e)})}}},{"../../constants/alignment":669,"../../lib":697,"../../lib/svg_text_utils":721,"../../plot_api/plot_template":735,"../../plots/plots":807,"../color":574,"../drawing":595,"./constants":658,d3:151}],661:[function(t,e,r){"use strict";var n=t("./constants");e.exports={moduleType:"component",name:n.name,layoutAttributes:t("./attributes"),supplyLayoutDefaults:t("./defaults"),draw:t("./draw")}},{"./attributes":657,"./constants":658,"./defaults":659,"./draw":660}],662:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../../plots/plots"),o=t("../../registry"),s=t("../../lib"),l=t("../drawing"),c=t("../color"),u=t("../../lib/svg_text_utils"),h=t("../../constants/interactions");e.exports={draw:function(t,e,r){var p,d=r.propContainer,g=r.propName,v=r.placeholder,m=r.traceIndex,y=r.avoid||{},x=r.attributes,b=r.transform,_=r.containerGroup,w=t._fullLayout,k=1,A=!1,M=d.title,T=(M&&M.text?M.text:"").trim(),S=M&&M.font?M.font:{},E=S.family,C=S.size,L=S.color;"title.text"===g?p="titleText":-1!==g.indexOf("axis")?p="axisTitleText":g.indexOf(!0)&&(p="colorbarTitleText");var z=t._context.edits[p];""===T?k=0:T.replace(f," % ")===v.replace(f," % ")&&(k=.2,A=!0,z||(T=""));w.meta&&(T=s.templateString(T,{meta:w.meta}));var O=T||z;_||(_=s.ensureSingle(w._infolayer,"g","g-"+e));var I=_.selectAll("text").data(O?[0]:[]);if(I.enter().append("text"),I.text(T).attr("class",e),I.exit().remove(),!O)return _;function D(t){s.syncOrAsync([P,R],t)}function P(e){var r;return b?(r="",b.rotate&&(r+="rotate("+[b.rotate,x.x,x.y]+")"),b.offset&&(r+="translate(0, "+b.offset+")")):r=null,e.attr("transform",r),e.style({"font-family":E,"font-size":n.round(C,2)+"px",fill:c.rgb(L),opacity:k*c.opacity(L),"font-weight":a.fontWeight}).attr(x).call(u.convertToTspans,t),a.previousPromises(t)}function R(t){var e=n.select(t.node().parentNode);if(y&&y.selection&&y.side&&T){e.attr("transform",null);var r=0,a={left:"right",right:"left",top:"bottom",bottom:"top"}[y.side],o=-1!==["left","top"].indexOf(y.side)?-1:1,c=i(y.pad)?y.pad:2,u=l.bBox(e.node()),h={left:0,top:0,right:w.width,bottom:w.height},f=y.maxShift||(h[y.side]-u[y.side])*("left"===y.side||"top"===y.side?-1:1);if(f<0)r=f;else{var p=y.offsetLeft||0,d=y.offsetTop||0;u.left-=p,u.right-=p,u.top-=d,u.bottom-=d,y.selection.each(function(){var t=l.bBox(this);s.bBoxIntersect(u,t,c)&&(r=Math.max(r,o*(t[y.side]-u[a])+c))}),r=Math.min(f,r)}if(r>0||f<0){var g={left:[-r,0],right:[r,0],top:[0,-r],bottom:[0,r]}[y.side];e.attr("transform","translate("+g+")")}}}I.call(D),z&&(T?I.on(".opacity",null):(k=0,A=!0,I.text(v).on("mouseover.opacity",function(){n.select(this).transition().duration(h.SHOW_PLACEHOLDER).style("opacity",1)}).on("mouseout.opacity",function(){n.select(this).transition().duration(h.HIDE_PLACEHOLDER).style("opacity",0)})),I.call(u.makeEditable,{gd:t}).on("edit",function(e){void 0!==m?o.call("_guiRestyle",t,g,e,m):o.call("_guiRelayout",t,g,e)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(D)}).on("input",function(t){this.text(t||" ").call(u.positionText,x.x,x.y)}));return I.classed("js-placeholder",A),_}};var f=/ [XY][0-9]* /},{"../../constants/interactions":673,"../../lib":697,"../../lib/svg_text_utils":721,"../../plots/plots":807,"../../registry":826,"../color":574,"../drawing":595,d3:151,"fast-isnumeric":218}],663:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes"),i=t("../color/attributes"),a=t("../../lib/extend").extendFlat,o=t("../../plot_api/edit_types").overrideAll,s=t("../../plots/pad_attributes"),l=t("../../plot_api/plot_template").templatedArray,c=l("button",{visible:{valType:"boolean"},method:{valType:"enumerated",values:["restyle","relayout","animate","update","skip"],dflt:"restyle"},args:{valType:"info_array",freeLength:!0,items:[{valType:"any"},{valType:"any"},{valType:"any"}]},label:{valType:"string",dflt:""},execute:{valType:"boolean",dflt:!0}});e.exports=o(l("updatemenu",{_arrayAttrRegexps:[/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],visible:{valType:"boolean"},type:{valType:"enumerated",values:["dropdown","buttons"],dflt:"dropdown"},direction:{valType:"enumerated",values:["left","right","up","down"],dflt:"down"},active:{valType:"integer",min:-1,dflt:0},showactive:{valType:"boolean",dflt:!0},buttons:c,x:{valType:"number",min:-2,max:3,dflt:-.05},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"right"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"top"},pad:a(s({editType:"arraydraw"}),{}),font:n({}),bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:i.borderLine},borderwidth:{valType:"number",min:0,dflt:1,editType:"arraydraw"}}),"arraydraw","from-root")},{"../../lib/extend":687,"../../plot_api/edit_types":728,"../../plot_api/plot_template":735,"../../plots/font_attributes":771,"../../plots/pad_attributes":806,"../color/attributes":573}],664:[function(t,e,r){"use strict";e.exports={name:"updatemenus",containerClassName:"updatemenu-container",headerGroupClassName:"updatemenu-header-group",headerClassName:"updatemenu-header",headerArrowClassName:"updatemenu-header-arrow",dropdownButtonGroupClassName:"updatemenu-dropdown-button-group",dropdownButtonClassName:"updatemenu-dropdown-button",buttonClassName:"updatemenu-button",itemRectClassName:"updatemenu-item-rect",itemTextClassName:"updatemenu-item-text",menuIndexAttrName:"updatemenu-active-index",autoMarginIdRoot:"updatemenu-",blankHeaderOpts:{label:"  "},minWidth:30,minHeight:30,textPadX:24,arrowPadX:16,rx:2,ry:2,textOffsetX:12,textOffsetY:3,arrowOffsetX:4,gapButtonHeader:5,gapButton:2,activeColor:"#F4FAFF",hoverColor:"#F4FAFF",arrowSymbol:{left:"\u25c4",right:"\u25ba",up:"\u25b2",down:"\u25bc"}}},{}],665:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/array_container_defaults"),a=t("./attributes"),o=t("./constants").name,s=a.buttons;function l(t,e,r){function o(r,i){return n.coerce(t,e,a,r,i)}o("visible",i(t,e,{name:"buttons",handleItemDefaults:c}).length>0)&&(o("active"),o("direction"),o("type"),o("showactive"),o("x"),o("y"),n.noneOrAll(t,e,["x","y"]),o("xanchor"),o("yanchor"),o("pad.t"),o("pad.r"),o("pad.b"),o("pad.l"),n.coerceFont(o,"font",r.font),o("bgcolor",r.paper_bgcolor),o("bordercolor"),o("borderwidth"))}function c(t,e){function r(r,i){return n.coerce(t,e,s,r,i)}r("visible","skip"===t.method||Array.isArray(t.args))&&(r("method"),r("args"),r("label"),r("execute"))}e.exports=function(t,e){i(t,e,{name:o,handleItemDefaults:l})}},{"../../lib":697,"../../plots/array_container_defaults":741,"./attributes":663,"./constants":664}],666:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../plots/plots"),a=t("../color"),o=t("../drawing"),s=t("../../lib"),l=t("../../lib/svg_text_utils"),c=t("../../plot_api/plot_template").arrayEditor,u=t("../../constants/alignment").LINE_SPACING,h=t("./constants"),f=t("./scrollbox");function p(t){return t._index}function d(t,e){return+t.attr(h.menuIndexAttrName)===e._index}function g(t,e,r,n,i,a,o,s){e.active=o,c(t.layout,h.name,e).applyUpdate("active",o),"buttons"===e.type?m(t,n,null,null,e):"dropdown"===e.type&&(i.attr(h.menuIndexAttrName,"-1"),v(t,n,i,a,e),s||m(t,n,i,a,e))}function v(t,e,r,n,i){var a=s.ensureSingle(e,"g",h.headerClassName,function(t){t.style("pointer-events","all")}),l=i._dims,c=i.active,u=i.buttons[c]||h.blankHeaderOpts,f={y:i.pad.t,yPad:0,x:i.pad.l,xPad:0,index:0},p={width:l.headerWidth,height:l.headerHeight};a.call(y,i,u,t).call(T,i,f,p),s.ensureSingle(e,"text",h.headerArrowClassName,function(t){t.classed("user-select-none",!0).attr("text-anchor","end").call(o.font,i.font).text(h.arrowSymbol[i.direction])}).attr({x:l.headerWidth-h.arrowOffsetX+i.pad.l,y:l.headerHeight/2+h.textOffsetY+i.pad.t}),a.on("click",function(){r.call(S,String(d(r,i)?-1:i._index)),m(t,e,r,n,i)}),a.on("mouseover",function(){a.call(w)}),a.on("mouseout",function(){a.call(k,i)}),o.setTranslate(e,l.lx,l.ly)}function m(t,e,r,a,o){r||(r=e).attr("pointer-events","all");var l=function(t){return-1==+t.attr(h.menuIndexAttrName)}(r)&&"buttons"!==o.type?[]:o.buttons,c="dropdown"===o.type?h.dropdownButtonClassName:h.buttonClassName,u=r.selectAll("g."+c).data(s.filterVisible(l)),f=u.enter().append("g").classed(c,!0),p=u.exit();"dropdown"===o.type?(f.attr("opacity","0").transition().attr("opacity","1"),p.transition().attr("opacity","0").remove()):p.remove();var d=0,v=0,m=o._dims,x=-1!==["up","down"].indexOf(o.direction);"dropdown"===o.type&&(x?v=m.headerHeight+h.gapButtonHeader:d=m.headerWidth+h.gapButtonHeader),"dropdown"===o.type&&"up"===o.direction&&(v=-h.gapButtonHeader+h.gapButton-m.openHeight),"dropdown"===o.type&&"left"===o.direction&&(d=-h.gapButtonHeader+h.gapButton-m.openWidth);var b={x:m.lx+d+o.pad.l,y:m.ly+v+o.pad.t,yPad:h.gapButton,xPad:h.gapButton,index:0},A={l:b.x+o.borderwidth,t:b.y+o.borderwidth};u.each(function(s,l){var c=n.select(this);c.call(y,o,s,t).call(T,o,b),c.on("click",function(){n.event.defaultPrevented||(g(t,o,0,e,r,a,l),s.execute&&i.executeAPICommand(t,s.method,s.args),t.emit("plotly_buttonclicked",{menu:o,button:s,active:o.active}))}),c.on("mouseover",function(){c.call(w)}),c.on("mouseout",function(){c.call(k,o),u.call(_,o)})}),u.call(_,o),x?(A.w=Math.max(m.openWidth,m.headerWidth),A.h=b.y-A.t):(A.w=b.x-A.l,A.h=Math.max(m.openHeight,m.headerHeight)),A.direction=o.direction,a&&(u.size()?function(t,e,r,n,i,a){var o,s,l,c=i.direction,u="up"===c||"down"===c,f=i._dims,p=i.active;if(u)for(s=0,l=0;l<p;l++)s+=f.heights[l]+h.gapButton;else for(o=0,l=0;l<p;l++)o+=f.widths[l]+h.gapButton;n.enable(a,o,s),n.hbar&&n.hbar.attr("opacity","0").transition().attr("opacity","1");n.vbar&&n.vbar.attr("opacity","0").transition().attr("opacity","1")}(0,0,0,a,o,A):function(t){var e=!!t.hbar,r=!!t.vbar;e&&t.hbar.transition().attr("opacity","0").each("end",function(){e=!1,r||t.disable()});r&&t.vbar.transition().attr("opacity","0").each("end",function(){r=!1,e||t.disable()})}(a))}function y(t,e,r,n){t.call(x,e).call(b,e,r,n)}function x(t,e){s.ensureSingle(t,"rect",h.itemRectClassName,function(t){t.attr({rx:h.rx,ry:h.ry,"shape-rendering":"crispEdges"})}).call(a.stroke,e.bordercolor).call(a.fill,e.bgcolor).style("stroke-width",e.borderwidth+"px")}function b(t,e,r,n){var i=s.ensureSingle(t,"text",h.itemTextClassName,function(t){t.classed("user-select-none",!0).attr({"text-anchor":"start","data-notex":1})}),a=r.label,c=n._fullLayout.meta;c&&(a=s.templateString(a,{meta:c})),i.call(o.font,e.font).text(a).call(l.convertToTspans,n)}function _(t,e){var r=e.active;t.each(function(t,i){var o=n.select(this);i===r&&e.showactive&&o.select("rect."+h.itemRectClassName).call(a.fill,h.activeColor)})}function w(t){t.select("rect."+h.itemRectClassName).call(a.fill,h.hoverColor)}function k(t,e){t.select("rect."+h.itemRectClassName).call(a.fill,e.bgcolor)}function A(t,e){var r=e._dims={width1:0,height1:0,heights:[],widths:[],totalWidth:0,totalHeight:0,openWidth:0,openHeight:0,lx:0,ly:0},a=o.tester.selectAll("g."+h.dropdownButtonClassName).data(s.filterVisible(e.buttons));a.enter().append("g").classed(h.dropdownButtonClassName,!0);var c=-1!==["up","down"].indexOf(e.direction);a.each(function(i,a){var s=n.select(this);s.call(y,e,i,t);var f=s.select("."+h.itemTextClassName),p=f.node()&&o.bBox(f.node()).width,d=Math.max(p+h.textPadX,h.minWidth),g=e.font.size*u,v=l.lineCount(f),m=Math.max(g*v,h.minHeight)+h.textOffsetY;m=Math.ceil(m),d=Math.ceil(d),r.widths[a]=d,r.heights[a]=m,r.height1=Math.max(r.height1,m),r.width1=Math.max(r.width1,d),c?(r.totalWidth=Math.max(r.totalWidth,d),r.openWidth=r.totalWidth,r.totalHeight+=m+h.gapButton,r.openHeight+=m+h.gapButton):(r.totalWidth+=d+h.gapButton,r.openWidth+=d+h.gapButton,r.totalHeight=Math.max(r.totalHeight,m),r.openHeight=r.totalHeight)}),c?r.totalHeight-=h.gapButton:r.totalWidth-=h.gapButton,r.headerWidth=r.width1+h.arrowPadX,r.headerHeight=r.height1,"dropdown"===e.type&&(c?(r.width1+=h.arrowPadX,r.totalHeight=r.height1):r.totalWidth=r.width1,r.totalWidth+=h.arrowPadX),a.remove();var f=r.totalWidth+e.pad.l+e.pad.r,p=r.totalHeight+e.pad.t+e.pad.b,d=t._fullLayout._size;r.lx=d.l+d.w*e.x,r.ly=d.t+d.h*(1-e.y);var g="left";s.isRightAnchor(e)&&(r.lx-=f,g="right"),s.isCenterAnchor(e)&&(r.lx-=f/2,g="center");var v="top";s.isBottomAnchor(e)&&(r.ly-=p,v="bottom"),s.isMiddleAnchor(e)&&(r.ly-=p/2,v="middle"),r.totalWidth=Math.ceil(r.totalWidth),r.totalHeight=Math.ceil(r.totalHeight),r.lx=Math.round(r.lx),r.ly=Math.round(r.ly),i.autoMargin(t,M(e),{x:e.x,y:e.y,l:f*({right:1,center:.5}[g]||0),r:f*({left:1,center:.5}[g]||0),b:p*({top:1,middle:.5}[v]||0),t:p*({bottom:1,middle:.5}[v]||0)})}function M(t){return h.autoMarginIdRoot+t._index}function T(t,e,r,n){n=n||{};var i=t.select("."+h.itemRectClassName),a=t.select("."+h.itemTextClassName),s=e.borderwidth,c=r.index,f=e._dims;o.setTranslate(t,s+r.x,s+r.y);var p=-1!==["up","down"].indexOf(e.direction),d=n.height||(p?f.heights[c]:f.height1);i.attr({x:0,y:0,width:n.width||(p?f.width1:f.widths[c]),height:d});var g=e.font.size*u,v=(l.lineCount(a)-1)*g/2;l.positionText(a,h.textOffsetX,d/2-v+h.textOffsetY),p?r.y+=f.heights[c]+r.yPad:r.x+=f.widths[c]+r.xPad,r.index++}function S(t,e){t.attr(h.menuIndexAttrName,e||"-1").selectAll("g."+h.dropdownButtonClassName).remove()}e.exports=function(t){var e=t._fullLayout,r=s.filterVisible(e[h.name]);function a(e){i.autoMargin(t,M(e))}var o=e._menulayer.selectAll("g."+h.containerClassName).data(r.length>0?[0]:[]);if(o.enter().append("g").classed(h.containerClassName,!0).style("cursor","pointer"),o.exit().each(function(){n.select(this).selectAll("g."+h.headerGroupClassName).each(a)}).remove(),0!==r.length){var l=o.selectAll("g."+h.headerGroupClassName).data(r,p);l.enter().append("g").classed(h.headerGroupClassName,!0);for(var c=s.ensureSingle(o,"g",h.dropdownButtonGroupClassName,function(t){t.style("pointer-events","all")}),u=0;u<r.length;u++){var y=r[u];A(t,y)}var x="updatemenus"+e._uid,b=new f(t,c,x);l.enter().size()&&(c.node().parentNode.appendChild(c.node()),c.call(S)),l.exit().each(function(t){c.call(S),a(t)}).remove(),l.each(function(e){var r=n.select(this),a="dropdown"===e.type?c:null;i.manageCommandObserver(t,e,e.buttons,function(n){g(t,e,e.buttons[n.index],r,a,b,n.index,!0)}),"dropdown"===e.type?(v(t,r,c,b,e),d(c,e)&&m(t,r,c,b,e)):m(t,r,null,null,e)})}}},{"../../constants/alignment":669,"../../lib":697,"../../lib/svg_text_utils":721,"../../plot_api/plot_template":735,"../../plots/plots":807,"../color":574,"../drawing":595,"./constants":664,"./scrollbox":668,d3:151}],667:[function(t,e,r){arguments[4][661][0].apply(r,arguments)},{"./attributes":663,"./constants":664,"./defaults":665,"./draw":666,dup:661}],668:[function(t,e,r){"use strict";e.exports=s;var n=t("d3"),i=t("../color"),a=t("../drawing"),o=t("../../lib");function s(t,e,r){this.gd=t,this.container=e,this.id=r,this.position=null,this.translateX=null,this.translateY=null,this.hbar=null,this.vbar=null,this.bg=this.container.selectAll("rect.scrollbox-bg").data([0]),this.bg.exit().on(".drag",null).on("wheel",null).remove(),this.bg.enter().append("rect").classed("scrollbox-bg",!0).style("pointer-events","all").attr({opacity:0,x:0,y:0,width:0,height:0})}s.barWidth=2,s.barLength=20,s.barRadius=2,s.barPad=1,s.barColor="#808BA4",s.prototype.enable=function(t,e,r){var o=this.gd._fullLayout,l=o.width,c=o.height;this.position=t;var u,h,f,p,d=this.position.l,g=this.position.w,v=this.position.t,m=this.position.h,y=this.position.direction,x="down"===y,b="left"===y,_="up"===y,w=g,k=m;x||b||"right"===y||_||(this.position.direction="down",x=!0),x||_?(h=(u=d)+w,x?(f=v,k=(p=Math.min(f+k,c))-f):k=(p=v+k)-(f=Math.max(p-k,0))):(p=(f=v)+k,b?w=(h=d+w)-(u=Math.max(h-w,0)):(u=d,w=(h=Math.min(u+w,l))-u)),this._box={l:u,t:f,w:w,h:k};var A=g>w,M=s.barLength+2*s.barPad,T=s.barWidth+2*s.barPad,S=d,E=v+m;E+T>c&&(E=c-T);var C=this.container.selectAll("rect.scrollbar-horizontal").data(A?[0]:[]);C.exit().on(".drag",null).remove(),C.enter().append("rect").classed("scrollbar-horizontal",!0).call(i.fill,s.barColor),A?(this.hbar=C.attr({rx:s.barRadius,ry:s.barRadius,x:S,y:E,width:M,height:T}),this._hbarXMin=S+M/2,this._hbarTranslateMax=w-M):(delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax);var L=m>k,z=s.barWidth+2*s.barPad,O=s.barLength+2*s.barPad,I=d+g,D=v;I+z>l&&(I=l-z);var P=this.container.selectAll("rect.scrollbar-vertical").data(L?[0]:[]);P.exit().on(".drag",null).remove(),P.enter().append("rect").classed("scrollbar-vertical",!0).call(i.fill,s.barColor),L?(this.vbar=P.attr({rx:s.barRadius,ry:s.barRadius,x:I,y:D,width:z,height:O}),this._vbarYMin=D+O/2,this._vbarTranslateMax=k-O):(delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax);var R=this.id,F=u-.5,B=L?h+z+.5:h+.5,N=f-.5,j=A?p+T+.5:p+.5,V=o._topdefs.selectAll("#"+R).data(A||L?[0]:[]);if(V.exit().remove(),V.enter().append("clipPath").attr("id",R).append("rect"),A||L?(this._clipRect=V.select("rect").attr({x:Math.floor(F),y:Math.floor(N),width:Math.ceil(B)-Math.floor(F),height:Math.ceil(j)-Math.floor(N)}),this.container.call(a.setClipUrl,R,this.gd),this.bg.attr({x:d,y:v,width:g,height:m})):(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(a.setClipUrl,null),delete this._clipRect),A||L){var U=n.behavior.drag().on("dragstart",function(){n.event.sourceEvent.preventDefault()}).on("drag",this._onBoxDrag.bind(this));this.container.on("wheel",null).on("wheel",this._onBoxWheel.bind(this)).on(".drag",null).call(U);var q=n.behavior.drag().on("dragstart",function(){n.event.sourceEvent.preventDefault(),n.event.sourceEvent.stopPropagation()}).on("drag",this._onBarDrag.bind(this));A&&this.hbar.on(".drag",null).call(q),L&&this.vbar.on(".drag",null).call(q)}this.setTranslate(e,r)},s.prototype.disable=function(){(this.hbar||this.vbar)&&(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(a.setClipUrl,null),delete this._clipRect),this.hbar&&(this.hbar.on(".drag",null),this.hbar.remove(),delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax),this.vbar&&(this.vbar.on(".drag",null),this.vbar.remove(),delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax)},s.prototype._onBoxDrag=function(){var t=this.translateX,e=this.translateY;this.hbar&&(t-=n.event.dx),this.vbar&&(e-=n.event.dy),this.setTranslate(t,e)},s.prototype._onBoxWheel=function(){var t=this.translateX,e=this.translateY;this.hbar&&(t+=n.event.deltaY),this.vbar&&(e+=n.event.deltaY),this.setTranslate(t,e)},s.prototype._onBarDrag=function(){var t=this.translateX,e=this.translateY;if(this.hbar){var r=t+this._hbarXMin,i=r+this._hbarTranslateMax;t=(o.constrain(n.event.x,r,i)-r)/(i-r)*(this.position.w-this._box.w)}if(this.vbar){var a=e+this._vbarYMin,s=a+this._vbarTranslateMax;e=(o.constrain(n.event.y,a,s)-a)/(s-a)*(this.position.h-this._box.h)}this.setTranslate(t,e)},s.prototype.setTranslate=function(t,e){var r=this.position.w-this._box.w,n=this.position.h-this._box.h;if(t=o.constrain(t||0,0,r),e=o.constrain(e||0,0,n),this.translateX=t,this.translateY=e,this.container.call(a.setTranslate,this._box.l-this.position.l-t,this._box.t-this.position.t-e),this._clipRect&&this._clipRect.attr({x:Math.floor(this.position.l+t-.5),y:Math.floor(this.position.t+e-.5)}),this.hbar){var i=t/r;this.hbar.call(a.setTranslate,t+i*this._hbarTranslateMax,e)}if(this.vbar){var s=e/n;this.vbar.call(a.setTranslate,t,e+s*this._vbarTranslateMax)}}},{"../../lib":697,"../color":574,"../drawing":595,d3:151}],669:[function(t,e,r){"use strict";e.exports={FROM_BL:{left:0,center:.5,right:1,bottom:0,middle:.5,top:1},FROM_TL:{left:0,center:.5,right:1,bottom:1,middle:.5,top:0},FROM_BR:{left:1,center:.5,right:0,bottom:0,middle:.5,top:1},LINE_SPACING:1.3,CAP_SHIFT:.7,MID_SHIFT:.35,OPPOSITE_SIDE:{left:"right",right:"left",top:"bottom",bottom:"top"}}},{}],670:[function(t,e,r){"use strict";e.exports={COMPARISON_OPS:["=","!=","<",">=",">","<="],COMPARISON_OPS2:["=","<",">=",">","<="],INTERVAL_OPS:["[]","()","[)","(]","][",")(","](",")["],SET_OPS:["{}","}{"],CONSTRAINT_REDUCTION:{"=":"=","<":"<","<=":"<",">":">",">=":">","[]":"[]","()":"[]","[)":"[]","(]":"[]","][":"][",")(":"][","](":"][",")[":"]["}}},{}],671:[function(t,e,r){"use strict";e.exports={solid:[[],0],dot:[[.5,1],200],dash:[[.5,1],50],longdash:[[.5,1],10],dashdot:[[.5,.625,.875,1],50],longdashdot:[[.5,.7,.8,1],10]}},{}],672:[function(t,e,r){"use strict";e.exports={circle:"\u25cf","circle-open":"\u25cb",square:"\u25a0","square-open":"\u25a1",diamond:"\u25c6","diamond-open":"\u25c7",cross:"+",x:"\u274c"}},{}],673:[function(t,e,r){"use strict";e.exports={SHOW_PLACEHOLDER:100,HIDE_PLACEHOLDER:1e3,DBLCLICKDELAY:300,DESELECTDIM:.2}},{}],674:[function(t,e,r){"use strict";e.exports={BADNUM:void 0,FP_SAFE:Number.MAX_VALUE/1e4,ONEAVGYEAR:315576e5,ONEAVGMONTH:26298e5,ONEDAY:864e5,ONEHOUR:36e5,ONEMIN:6e4,ONESEC:1e3,EPOCHJD:2440587.5,ALMOST_EQUAL:1-1e-6,LOG_CLIP:10,MINUS_SIGN:"\u2212"}},{}],675:[function(t,e,r){"use strict";r.xmlns="http://www.w3.org/2000/xmlns/",r.svg="http://www.w3.org/2000/svg",r.xlink="http://www.w3.org/1999/xlink",r.svgAttrs={xmlns:r.svg,"xmlns:xlink":r.xlink}},{}],676:[function(t,e,r){"use strict";r.version="1.45.2",t("es6-promise").polyfill(),t("../build/plotcss"),t("./fonts/mathjax_config")();for(var n=t("./registry"),i=r.register=n.register,a=t("./plot_api"),o=Object.keys(a),s=0;s<o.length;s++){var l=o[s];"_"!==l.charAt(0)&&(r[l]=a[l]),i({moduleType:"apiMethod",name:l,fn:a[l]})}i(t("./traces/scatter")),i([t("./components/fx"),t("./components/legend"),t("./components/annotations"),t("./components/annotations3d"),t("./components/shapes"),t("./components/images"),t("./components/updatemenus"),t("./components/sliders"),t("./components/rangeslider"),t("./components/rangeselector"),t("./components/grid"),t("./components/errorbars"),t("./components/colorscale")]),i([t("./locale-en"),t("./locale-en-us")]),r.Icons=t("../build/ploticon"),r.Plots=t("./plots/plots"),r.Fx=t("./components/fx"),r.Snapshot=t("./snapshot"),r.PlotSchema=t("./plot_api/plot_schema"),r.Queue=t("./lib/queue"),r.d3=t("d3")},{"../build/plotcss":1,"../build/ploticon":2,"./components/annotations":565,"./components/annotations3d":570,"./components/colorscale":586,"./components/errorbars":601,"./components/fx":613,"./components/grid":617,"./components/images":622,"./components/legend":630,"./components/rangeselector":641,"./components/rangeslider":648,"./components/shapes":656,"./components/sliders":661,"./components/updatemenus":667,"./fonts/mathjax_config":677,"./lib/queue":712,"./locale-en":726,"./locale-en-us":725,"./plot_api":730,"./plot_api/plot_schema":734,"./plots/plots":807,"./registry":826,"./snapshot":831,"./traces/scatter":1060,d3:151,"es6-promise":207}],677:[function(t,e,r){"use strict";e.exports=function(){"undefined"!=typeof MathJax&&("local"!==(window.PlotlyConfig||{}).MathJaxConfig&&(MathJax.Hub.Config({messageStyle:"none",skipStartupTypeset:!0,displayAlign:"left",tex2jax:{inlineMath:[["$","$"],["\\(","\\)"]]}}),MathJax.Hub.Configured()))}},{}],678:[function(t,e,r){"use strict";r.isLeftAnchor=function(t){return"left"===t.xanchor||"auto"===t.xanchor&&t.x<=1/3},r.isCenterAnchor=function(t){return"center"===t.xanchor||"auto"===t.xanchor&&t.x>1/3&&t.x<2/3},r.isRightAnchor=function(t){return"right"===t.xanchor||"auto"===t.xanchor&&t.x>=2/3},r.isTopAnchor=function(t){return"top"===t.yanchor||"auto"===t.yanchor&&t.y>=2/3},r.isMiddleAnchor=function(t){return"middle"===t.yanchor||"auto"===t.yanchor&&t.y>1/3&&t.y<2/3},r.isBottomAnchor=function(t){return"bottom"===t.yanchor||"auto"===t.yanchor&&t.y<=1/3}},{}],679:[function(t,e,r){"use strict";var n=t("./mod"),i=n.mod,a=n.modHalf,o=Math.PI,s=2*o;function l(t){return Math.abs(t[1]-t[0])>s-1e-15}function c(t,e){return a(e-t,s)}function u(t,e){if(l(e))return!0;var r,n;e[0]<e[1]?(r=e[0],n=e[1]):(r=e[1],n=e[0]),(r=i(r,s))>(n=i(n,s))&&(n+=s);var a=i(t,s),o=a+s;return a>=r&&a<=n||o>=r&&o<=n}function h(t,e,r,n,i,a,c){i=i||0,a=a||0;var u,h,f,p,d,g=l([r,n]);function v(t,e){return[t*Math.cos(e)+i,a-t*Math.sin(e)]}g?(u=0,h=o,f=s):r<n?(u=r,f=n):(u=n,f=r),t<e?(p=t,d=e):(p=e,d=t);var m,y=Math.abs(f-u)<=o?0:1;function x(t,e,r){return"A"+[t,t]+" "+[0,y,r]+" "+v(t,e)}return g?m=null===p?"M"+v(d,u)+x(d,h,0)+x(d,f,0)+"Z":"M"+v(p,u)+x(p,h,0)+x(p,f,0)+"ZM"+v(d,u)+x(d,h,1)+x(d,f,1)+"Z":null===p?(m="M"+v(d,u)+x(d,f,0),c&&(m+="L0,0Z")):m="M"+v(p,u)+"L"+v(d,u)+x(d,f,0)+"L"+v(p,f)+x(p,u,1)+"Z",m}e.exports={deg2rad:function(t){return t/180*o},rad2deg:function(t){return t/o*180},angleDelta:c,angleDist:function(t,e){return Math.abs(c(t,e))},isFullCircle:l,isAngleInsideSector:u,isPtInsideSector:function(t,e,r,n){return!!u(e,n)&&(r[0]<r[1]?(i=r[0],a=r[1]):(i=r[1],a=r[0]),t>=i&&t<=a);var i,a},pathArc:function(t,e,r,n,i){return h(null,t,e,r,n,i,0)},pathSector:function(t,e,r,n,i){return h(null,t,e,r,n,i,1)},pathAnnulus:function(t,e,r,n,i,a){return h(t,e,r,n,i,a,1)}}},{"./mod":704}],680:[function(t,e,r){"use strict";var n=Array.isArray,i="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer:{isView:function(){return!1}},a="undefined"==typeof DataView?function(){}:DataView;function o(t){return i.isView(t)&&!(t instanceof a)}function s(t){return n(t)||o(t)}function l(t,e,r){if(s(t)){if(s(t[0])){for(var n=r,i=0;i<t.length;i++)n=e(n,t[i].length);return n}return t.length}return 0}r.isTypedArray=o,r.isArrayOrTypedArray=s,r.isArray1D=function(t){return!s(t[0])},r.ensureArray=function(t,e){return n(t)||(t=[]),t.length=e,t},r.concat=function(){var t,e,r,i,a,o,s,l,c=[],u=!0,h=0;for(r=0;r<arguments.length;r++)(o=(i=arguments[r]).length)&&(e?c.push(i):(e=i,a=o),n(i)?t=!1:(u=!1,h?t!==i.constructor&&(t=!1):t=i.constructor),h+=o);if(!h)return[];if(!c.length)return e;if(u)return e.concat.apply(e,c);if(t){for((s=new t(h)).set(e),r=0;r<c.length;r++)i=c[r],s.set(i,a),a+=i.length;return s}for(s=new Array(h),l=0;l<e.length;l++)s[l]=e[l];for(r=0;r<c.length;r++){for(i=c[r],l=0;l<i.length;l++)s[a+l]=i[l];a+=l}return s},r.maxRowLength=function(t){return l(t,Math.max,0)},r.minRowLength=function(t){return l(t,Math.min,1/0)}},{}],681:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../constants/numerical").BADNUM,a=/^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g;e.exports=function(t){return"string"==typeof t&&(t=t.replace(a,"")),n(t)?Number(t):i}},{"../constants/numerical":674,"fast-isnumeric":218}],682:[function(t,e,r){"use strict";e.exports=function(t){var e=t._fullLayout;e._glcanvas&&e._glcanvas.size()&&e._glcanvas.each(function(t){t.regl&&t.regl.clear({color:!0,depth:!0})})}},{}],683:[function(t,e,r){"use strict";e.exports=function(t){t._responsiveChartHandler&&(window.removeEventListener("resize",t._responsiveChartHandler),delete t._responsiveChartHandler)}},{}],684:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("tinycolor2"),a=t("../plots/attributes"),o=t("../components/colorscale/scales"),s=t("../constants/interactions").DESELECTDIM,l=t("./nested_property"),c=t("./regex").counter,u=t("./mod").modHalf,h=t("./array").isArrayOrTypedArray;function f(t,e){var n=r.valObjectMeta[e.valType];if(e.arrayOk&&h(t))return!0;if(n.validateFunction)return n.validateFunction(t,e);var i={},a=i,o={set:function(t){a=t}};return n.coerceFunction(t,o,i,e),a!==i}r.valObjectMeta={data_array:{coerceFunction:function(t,e,r){h(t)?e.set(t):void 0!==r&&e.set(r)}},enumerated:{coerceFunction:function(t,e,r,n){n.coerceNumber&&(t=+t),-1===n.values.indexOf(t)?e.set(r):e.set(t)},validateFunction:function(t,e){e.coerceNumber&&(t=+t);for(var r=e.values,n=0;n<r.length;n++){var i=String(r[n]);if("/"===i.charAt(0)&&"/"===i.charAt(i.length-1)){if(new RegExp(i.substr(1,i.length-2)).test(t))return!0}else if(t===r[n])return!0}return!1}},boolean:{coerceFunction:function(t,e,r){!0===t||!1===t?e.set(t):e.set(r)}},number:{coerceFunction:function(t,e,r,i){!n(t)||void 0!==i.min&&t<i.min||void 0!==i.max&&t>i.max?e.set(r):e.set(+t)}},integer:{coerceFunction:function(t,e,r,i){t%1||!n(t)||void 0!==i.min&&t<i.min||void 0!==i.max&&t>i.max?e.set(r):e.set(+t)}},string:{coerceFunction:function(t,e,r,n){if("string"!=typeof t){var i="number"==typeof t;!0!==n.strict&&i?e.set(String(t)):e.set(r)}else n.noBlank&&!t?e.set(r):e.set(t)}},color:{coerceFunction:function(t,e,r){i(t).isValid()?e.set(t):e.set(r)}},colorlist:{coerceFunction:function(t,e,r){Array.isArray(t)&&t.length&&t.every(function(t){return i(t).isValid()})?e.set(t):e.set(r)}},colorscale:{coerceFunction:function(t,e,r){e.set(o.get(t,r))}},angle:{coerceFunction:function(t,e,r){"auto"===t?e.set("auto"):n(t)?e.set(u(+t,360)):e.set(r)}},subplotid:{coerceFunction:function(t,e,r,n){var i=n.regex||c(r);"string"==typeof t&&i.test(t)?e.set(t):e.set(r)},validateFunction:function(t,e){var r=e.dflt;return t===r||"string"==typeof t&&!!c(r).test(t)}},flaglist:{coerceFunction:function(t,e,r,n){if("string"==typeof t)if(-1===(n.extras||[]).indexOf(t)){for(var i=t.split("+"),a=0;a<i.length;){var o=i[a];-1===n.flags.indexOf(o)||i.indexOf(o)<a?i.splice(a,1):a++}i.length?e.set(i.join("+")):e.set(r)}else e.set(t);else e.set(r)}},any:{coerceFunction:function(t,e,r){void 0===t?e.set(r):e.set(t)}},info_array:{coerceFunction:function(t,e,n,i){function a(t,e,n){var i,a={set:function(t){i=t}};return void 0===n&&(n=e.dflt),r.valObjectMeta[e.valType].coerceFunction(t,a,n,e),i}var o=2===i.dimensions||"1-2"===i.dimensions&&Array.isArray(t)&&Array.isArray(t[0]);if(Array.isArray(t)){var s,l,c,u,h,f,p=i.items,d=[],g=Array.isArray(p),v=g&&o&&Array.isArray(p[0]),m=o&&g&&!v,y=g&&!m?p.length:t.length;if(n=Array.isArray(n)?n:[],o)for(s=0;s<y;s++)for(d[s]=[],c=Array.isArray(t[s])?t[s]:[],h=m?p.length:g?p[s].length:c.length,l=0;l<h;l++)u=m?p[l]:g?p[s][l]:p,void 0!==(f=a(c[l],u,(n[s]||[])[l]))&&(d[s][l]=f);else for(s=0;s<y;s++)void 0!==(f=a(t[s],g?p[s]:p,n[s]))&&(d[s]=f);e.set(d)}else e.set(n)},validateFunction:function(t,e){if(!Array.isArray(t))return!1;var r=e.items,n=Array.isArray(r),i=2===e.dimensions;if(!e.freeLength&&t.length!==r.length)return!1;for(var a=0;a<t.length;a++)if(i){if(!Array.isArray(t[a])||!e.freeLength&&t[a].length!==r[a].length)return!1;for(var o=0;o<t[a].length;o++)if(!f(t[a][o],n?r[a][o]:r))return!1}else if(!f(t[a],n?r[a]:r))return!1;return!0}}},r.coerce=function(t,e,n,i,a){var o=l(n,i).get(),s=l(t,i),c=l(e,i),u=s.get(),p=e._template;if(void 0===u&&p&&(u=l(p,i).get(),p=0),void 0===a&&(a=o.dflt),o.arrayOk&&h(u))return c.set(u),u;var d=r.valObjectMeta[o.valType].coerceFunction;d(u,c,a,o);var g=c.get();return p&&g===a&&!f(u,o)&&(d(u=l(p,i).get(),c,a,o),g=c.get()),g},r.coerce2=function(t,e,n,i,a){var o=l(t,i),s=r.coerce(t,e,n,i,a),c=o.get();return null!=c&&s},r.coerceFont=function(t,e,r){var n={};return r=r||{},n.family=t(e+".family",r.family),n.size=t(e+".size",r.size),n.color=t(e+".color",r.color),n},r.coerceHoverinfo=function(t,e,n){var i,o=e._module.attributes,s=o.hoverinfo?o:a,l=s.hoverinfo;if(1===n._dataLength){var c="all"===l.dflt?l.flags.slice():l.dflt.split("+");c.splice(c.indexOf("name"),1),i=c.join("+")}return r.coerce(t,e,s,"hoverinfo",i)},r.coerceSelectionMarkerOpacity=function(t,e){if(t.marker){var r,n,i=t.marker.opacity;if(void 0!==i)h(i)||t.selected||t.unselected||(r=i,n=s*i),e("selected.marker.opacity",r),e("unselected.marker.opacity",n)}},r.validate=f},{"../components/colorscale/scales":589,"../constants/interactions":673,"../plots/attributes":742,"./array":680,"./mod":704,"./nested_property":705,"./regex":713,"fast-isnumeric":218,tinycolor2:518}],685:[function(t,e,r){"use strict";var n,i,a=t("d3"),o=t("fast-isnumeric"),s=t("./loggers"),l=t("./mod").mod,c=t("../constants/numerical"),u=c.BADNUM,h=c.ONEDAY,f=c.ONEHOUR,p=c.ONEMIN,d=c.ONESEC,g=c.EPOCHJD,v=t("../registry"),m=a.time.format.utc,y=/^\s*(-?\d\d\d\d|\d\d)(-(\d?\d)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d:?\d\d)?)?)?)?)?\s*$/m,x=/^\s*(-?\d\d\d\d|\d\d)(-(\d?\di?)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d:?\d\d)?)?)?)?)?\s*$/m,b=(new Date).getFullYear()-70;function _(t){return t&&v.componentsRegistry.calendars&&"string"==typeof t&&"gregorian"!==t}function w(t,e){return String(t+Math.pow(10,e)).substr(1)}r.dateTick0=function(t,e){return _(t)?e?v.getComponentMethod("calendars","CANONICAL_SUNDAY")[t]:v.getComponentMethod("calendars","CANONICAL_TICK")[t]:e?"2000-01-02":"2000-01-01"},r.dfltRange=function(t){return _(t)?v.getComponentMethod("calendars","DFLTRANGE")[t]:["2000-01-01","2001-01-01"]},r.isJSDate=function(t){return"object"==typeof t&&null!==t&&"function"==typeof t.getTime},r.dateTime2ms=function(t,e){if(r.isJSDate(t)){var a=t.getTimezoneOffset()*p,o=(t.getUTCMinutes()-t.getMinutes())*p+(t.getUTCSeconds()-t.getSeconds())*d+(t.getUTCMilliseconds()-t.getMilliseconds());if(o){var s=3*p;a=a-s/2+l(o-a+s/2,s)}return(t=Number(t)-a)>=n&&t<=i?t:u}if("string"!=typeof t&&"number"!=typeof t)return u;t=String(t);var c=_(e),m=t.charAt(0);!c||"G"!==m&&"g"!==m||(t=t.substr(1),e="");var w=c&&"chinese"===e.substr(0,7),k=t.match(w?x:y);if(!k)return u;var A=k[1],M=k[3]||"1",T=Number(k[5]||1),S=Number(k[7]||0),E=Number(k[9]||0),C=Number(k[11]||0);if(c){if(2===A.length)return u;var L;A=Number(A);try{var z=v.getComponentMethod("calendars","getCal")(e);if(w){var O="i"===M.charAt(M.length-1);M=parseInt(M,10),L=z.newDate(A,z.toMonthIndex(A,M,O),T)}else L=z.newDate(A,Number(M),T)}catch(t){return u}return L?(L.toJD()-g)*h+S*f+E*p+C*d:u}A=2===A.length?(Number(A)+2e3-b)%100+b:Number(A),M-=1;var I=new Date(Date.UTC(2e3,M,T,S,E));return I.setUTCFullYear(A),I.getUTCMonth()!==M?u:I.getUTCDate()!==T?u:I.getTime()+C*d},n=r.MIN_MS=r.dateTime2ms("-9999"),i=r.MAX_MS=r.dateTime2ms("9999-12-31 23:59:59.9999"),r.isDateTime=function(t,e){return r.dateTime2ms(t,e)!==u};var k=90*h,A=3*f,M=5*p;function T(t,e,r,n,i){if((e||r||n||i)&&(t+=" "+w(e,2)+":"+w(r,2),(n||i)&&(t+=":"+w(n,2),i))){for(var a=4;i%10==0;)a-=1,i/=10;t+="."+w(i,a)}return t}r.ms2DateTime=function(t,e,r){if("number"!=typeof t||!(t>=n&&t<=i))return u;e||(e=0);var a,o,s,c,y,x,b=Math.floor(10*l(t+.05,1)),w=Math.round(t-b/10);if(_(r)){var S=Math.floor(w/h)+g,E=Math.floor(l(t,h));try{a=v.getComponentMethod("calendars","getCal")(r).fromJD(S).formatDate("yyyy-mm-dd")}catch(t){a=m("G%Y-%m-%d")(new Date(w))}if("-"===a.charAt(0))for(;a.length<11;)a="-0"+a.substr(1);else for(;a.length<10;)a="0"+a;o=e<k?Math.floor(E/f):0,s=e<k?Math.floor(E%f/p):0,c=e<A?Math.floor(E%p/d):0,y=e<M?E%d*10+b:0}else x=new Date(w),a=m("%Y-%m-%d")(x),o=e<k?x.getUTCHours():0,s=e<k?x.getUTCMinutes():0,c=e<A?x.getUTCSeconds():0,y=e<M?10*x.getUTCMilliseconds()+b:0;return T(a,o,s,c,y)},r.ms2DateTimeLocal=function(t){if(!(t>=n+h&&t<=i-h))return u;var e=Math.floor(10*l(t+.05,1)),r=new Date(Math.round(t-e/10));return T(a.time.format("%Y-%m-%d")(r),r.getHours(),r.getMinutes(),r.getSeconds(),10*r.getUTCMilliseconds()+e)},r.cleanDate=function(t,e,n){if(t===u)return e;if(r.isJSDate(t)||"number"==typeof t&&isFinite(t)){if(_(n))return s.error("JS Dates and milliseconds are incompatible with world calendars",t),e;if(!(t=r.ms2DateTimeLocal(+t))&&void 0!==e)return e}else if(!r.isDateTime(t,n))return s.error("unrecognized date",t),e;return t};var S=/%\d?f/g;function E(t,e,r,n){t=t.replace(S,function(t){var r=Math.min(+t.charAt(1)||6,6);return(e/1e3%1+2).toFixed(r).substr(2).replace(/0+$/,"")||"0"});var i=new Date(Math.floor(e+.05));if(_(n))try{t=v.getComponentMethod("calendars","worldCalFmt")(t,e,n)}catch(t){return"Invalid"}return r(t)(i)}var C=[59,59.9,59.99,59.999,59.9999];r.formatDate=function(t,e,r,n,i,a){if(i=_(i)&&i,!e)if("y"===r)e=a.year;else if("m"===r)e=a.month;else{if("d"!==r)return function(t,e){var r=l(t+.05,h),n=w(Math.floor(r/f),2)+":"+w(l(Math.floor(r/p),60),2);if("M"!==e){o(e)||(e=0);var i=(100+Math.min(l(t/d,60),C[e])).toFixed(e).substr(1);e>0&&(i=i.replace(/0+$/,"").replace(/[\.]$/,"")),n+=":"+i}return n}(t,r)+"\n"+E(a.dayMonthYear,t,n,i);e=a.dayMonth+"\n"+a.year}return E(e,t,n,i)};var L=3*h;r.incrementMonth=function(t,e,r){r=_(r)&&r;var n=l(t,h);if(t=Math.round(t-n),r)try{var i=Math.round(t/h)+g,a=v.getComponentMethod("calendars","getCal")(r),o=a.fromJD(i);return e%12?a.add(o,e,"m"):a.add(o,e/12,"y"),(o.toJD()-g)*h+n}catch(e){s.error("invalid ms "+t+" in calendar "+r)}var c=new Date(t+L);return c.setUTCMonth(c.getUTCMonth()+e)+n-L},r.findExactDates=function(t,e){for(var r,n,i=0,a=0,s=0,l=0,c=_(e)&&v.getComponentMethod("calendars","getCal")(e),u=0;u<t.length;u++)if(n=t[u],o(n)){if(!(n%h))if(c)try{1===(r=c.fromJD(n/h+g)).day()?1===r.month()?i++:a++:s++}catch(t){}else 1===(r=new Date(n)).getUTCDate()?0===r.getUTCMonth()?i++:a++:s++}else l++;s+=a+=i;var f=t.length-l;return{exactYears:i/f,exactMonths:a/f,exactDays:s/f}}},{"../constants/numerical":674,"../registry":826,"./loggers":701,"./mod":704,d3:151,"fast-isnumeric":218}],686:[function(t,e,r){"use strict";var n=t("events").EventEmitter,i={init:function(t){if(t._ev instanceof n)return t;var e=new n,r=new n;return t._ev=e,t._internalEv=r,t.on=e.on.bind(e),t.once=e.once.bind(e),t.removeListener=e.removeListener.bind(e),t.removeAllListeners=e.removeAllListeners.bind(e),t._internalOn=r.on.bind(r),t._internalOnce=r.once.bind(r),t._removeInternalListener=r.removeListener.bind(r),t._removeAllInternalListeners=r.removeAllListeners.bind(r),t.emit=function(n,i){"undefined"!=typeof jQuery&&jQuery(t).trigger(n,i),e.emit(n,i),r.emit(n,i)},t},triggerHandler:function(t,e,r){var n,i;"undefined"!=typeof jQuery&&(n=jQuery(t).triggerHandler(e,r));var a=t._ev;if(!a)return n;var o,s=a._events[e];if(!s)return n;function l(t){return t.listener?(a.removeListener(e,t.listener),t.fired?void 0:(t.fired=!0,t.listener.apply(a,[r]))):t.apply(a,[r])}for(s=Array.isArray(s)?s:[s],o=0;o<s.length-1;o++)l(s[o]);return i=l(s[o]),void 0!==n?n:i},purge:function(t){return delete t._ev,delete t.on,delete t.once,delete t.removeListener,delete t.removeAllListeners,delete t.emit,delete t._ev,delete t._internalEv,delete t._internalOn,delete t._internalOnce,delete t._removeInternalListener,delete t._removeAllInternalListeners,t}};e.exports=i},{events:92}],687:[function(t,e,r){"use strict";var n=t("./is_plain_object.js"),i=Array.isArray;function a(t,e,r,o){var s,l,c,u,h,f,p=t[0],d=t.length;if(2===d&&i(p)&&i(t[1])&&0===p.length){if(function(t,e){var r,n;for(r=0;r<t.length;r++){if(null!==(n=t[r])&&"object"==typeof n)return!1;void 0!==n&&(e[r]=n)}return!0}(t[1],p))return p;p.splice(0,p.length)}for(var g=1;g<d;g++)for(l in s=t[g])c=p[l],u=s[l],o&&i(u)?p[l]=u:e&&u&&(n(u)||(h=i(u)))?(h?(h=!1,f=c&&i(c)?c:[]):f=c&&n(c)?c:{},p[l]=a([f,u],e,r,o)):("undefined"!=typeof u||r)&&(p[l]=u);return p}r.extendFlat=function(){return a(arguments,!1,!1,!1)},r.extendDeep=function(){return a(arguments,!0,!1,!1)},r.extendDeepAll=function(){return a(arguments,!0,!0,!1)},r.extendDeepNoArrays=function(){return a(arguments,!0,!1,!0)}},{"./is_plain_object.js":698}],688:[function(t,e,r){"use strict";e.exports=function(t){for(var e={},r=[],n=0,i=0;i<t.length;i++){var a=t[i];1!==e[a]&&(e[a]=1,r[n++]=a)}return r}},{}],689:[function(t,e,r){"use strict";function n(t){return!0===t.visible}function i(t){return!0===t[0].trace.visible}e.exports=function(t){for(var e,r=(e=t,Array.isArray(e)&&Array.isArray(e[0])&&e[0][0]&&e[0][0].trace?i:n),a=[],o=0;o<t.length;o++){var s=t[o];r(s)&&a.push(s)}return a}},{}],690:[function(t,e,r){"use strict";var n=t("country-regex"),i=t("../lib"),a=Object.keys(n),o={"ISO-3":i.identity,"USA-states":i.identity,"country names":function(t){for(var e=0;e<a.length;e++){var r=a[e],o=new RegExp(n[r]);if(o.test(t.trim().toLowerCase()))return r}return i.log("Unrecognized country name: "+t+"."),!1}};r.locationToFeature=function(t,e,r){if(!e||"string"!=typeof e)return!1;var n=function(t,e){return(0,o[t])(e)}(t,e);if(n){for(var a=0;a<r.length;a++){var s=r[a];if(s.id===n)return s}i.log(["Location with id",n,"does not have a matching topojson feature at this resolution."].join(" "))}return!1}},{"../lib":697,"country-regex":122}],691:[function(t,e,r){"use strict";var n=t("../constants/numerical").BADNUM;r.calcTraceToLineCoords=function(t){for(var e=t[0].trace.connectgaps,r=[],i=[],a=0;a<t.length;a++){var o=t[a].lonlat;o[0]!==n?i.push(o):!e&&i.length>0&&(r.push(i),i=[])}return i.length>0&&r.push(i),r},r.makeLine=function(t){return 1===t.length?{type:"LineString",coordinates:t[0]}:{type:"MultiLineString",coordinates:t}},r.makePolygon=function(t){if(1===t.length)return{type:"Polygon",coordinates:t};for(var e=new Array(t.length),r=0;r<t.length;r++)e[r]=[t[r]];return{type:"MultiPolygon",coordinates:e}},r.makeBlank=function(){return{type:"Point",coordinates:[]}}},{"../constants/numerical":674}],692:[function(t,e,r){"use strict";var n,i,a,o=t("./mod").mod;function s(t,e,r,n,i,a,o,s){var l=r-t,c=i-t,u=o-i,h=n-e,f=a-e,p=s-a,d=l*p-u*h;if(0===d)return null;var g=(c*p-u*f)/d,v=(c*h-l*f)/d;return v<0||v>1||g<0||g>1?null:{x:t+l*g,y:e+h*g}}function l(t,e,r,n,i){var a=n*t+i*e;if(a<0)return n*n+i*i;if(a>r){var o=n-t,s=i-e;return o*o+s*s}var l=n*e-i*t;return l*l/r}r.segmentsIntersect=s,r.segmentDistance=function(t,e,r,n,i,a,o,c){if(s(t,e,r,n,i,a,o,c))return 0;var u=r-t,h=n-e,f=o-i,p=c-a,d=u*u+h*h,g=f*f+p*p,v=Math.min(l(u,h,d,i-t,a-e),l(u,h,d,o-t,c-e),l(f,p,g,t-i,e-a),l(f,p,g,r-i,n-a));return Math.sqrt(v)},r.getTextLocation=function(t,e,r,s){if(t===i&&s===a||(n={},i=t,a=s),n[r])return n[r];var l=t.getPointAtLength(o(r-s/2,e)),c=t.getPointAtLength(o(r+s/2,e)),u=Math.atan((c.y-l.y)/(c.x-l.x)),h=t.getPointAtLength(o(r,e)),f={x:(4*h.x+l.x+c.x)/6,y:(4*h.y+l.y+c.y)/6,theta:u};return n[r]=f,f},r.clearLocationCache=function(){i=null},r.getVisibleSegment=function(t,e,r){var n,i,a=e.left,o=e.right,s=e.top,l=e.bottom,c=0,u=t.getTotalLength(),h=u;function f(e){var r=t.getPointAtLength(e);0===e?n=r:e===u&&(i=r);var c=r.x<a?a-r.x:r.x>o?r.x-o:0,h=r.y<s?s-r.y:r.y>l?r.y-l:0;return Math.sqrt(c*c+h*h)}for(var p=f(c);p;){if((c+=p+r)>h)return;p=f(c)}for(p=f(h);p;){if(c>(h-=p+r))return;p=f(h)}return{min:c,max:h,len:h-c,total:u,isClosed:0===c&&h===u&&Math.abs(n.x-i.x)<.1&&Math.abs(n.y-i.y)<.1}},r.findPointOnPath=function(t,e,r,n){for(var i,a,o,s=(n=n||{}).pathLength||t.getTotalLength(),l=n.tolerance||.001,c=n.iterationLimit||30,u=t.getPointAtLength(0)[r]>t.getPointAtLength(s)[r]?-1:1,h=0,f=0,p=s;h<c;){if(i=(f+p)/2,o=(a=t.getPointAtLength(i))[r]-e,Math.abs(o)<l)return a;u*o>0?p=i:f=i,h++}return a}},{"./mod":704}],693:[function(t,e,r){"use strict";e.exports=function(t){var e;if("string"==typeof t){if(null===(e=document.getElementById(t)))throw new Error("No DOM element with id '"+t+"' exists on the page.");return e}if(null==t)throw new Error("DOM element provided is null or undefined");return t}},{}],694:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("tinycolor2"),a=t("color-normalize"),o=t("../components/colorscale"),s=t("../components/color/attributes").defaultLine,l=t("./array").isArrayOrTypedArray,c=a(s),u=1;function h(t,e){var r=t;return r[3]*=e,r}function f(t){if(n(t))return c;var e=a(t);return e.length?e:c}function p(t){return n(t)?t:u}e.exports={formatColor:function(t,e,r){var n,i,s,d,g,v=t.color,m=l(v),y=l(e),x=[];if(n=void 0!==t.colorscale?o.makeColorScaleFunc(o.extractScale(t,{cLetter:"c"})):f,i=m?function(t,e){return void 0===t[e]?c:a(n(t[e]))}:f,s=y?function(t,e){return void 0===t[e]?u:p(t[e])}:p,m||y)for(var b=0;b<r;b++)d=i(v,b),g=s(e,b),x[b]=h(d,g);else x=h(a(v),e);return x},parseColorScale:function(t,e){return void 0===e&&(e=1),(t.reversescale?o.flipScale(t.colorscale):t.colorscale).map(function(t){var r=t[0],n=i(t[1]).toRgb();return{index:r,rgb:[n.r,n.g,n.b,e]}})}}},{"../components/color/attributes":573,"../components/colorscale":586,"./array":680,"color-normalize":108,"fast-isnumeric":218,tinycolor2:518}],695:[function(t,e,r){"use strict";var n=t("./identity");function i(t){return[t]}e.exports={keyFun:function(t){return t.key},repeat:i,descend:n,wrap:i,unwrap:function(t){return t[0]}}},{"./identity":696}],696:[function(t,e,r){"use strict";e.exports=function(t){return t}},{}],697:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../constants/numerical"),o=a.FP_SAFE,s=a.BADNUM,l=e.exports={};l.nestedProperty=t("./nested_property"),l.keyedContainer=t("./keyed_container"),l.relativeAttr=t("./relative_attr"),l.isPlainObject=t("./is_plain_object"),l.toLogRange=t("./to_log_range"),l.relinkPrivateKeys=t("./relink_private");var c=t("./array");l.isTypedArray=c.isTypedArray,l.isArrayOrTypedArray=c.isArrayOrTypedArray,l.isArray1D=c.isArray1D,l.ensureArray=c.ensureArray,l.concat=c.concat,l.maxRowLength=c.maxRowLength,l.minRowLength=c.minRowLength;var u=t("./mod");l.mod=u.mod,l.modHalf=u.modHalf;var h=t("./coerce");l.valObjectMeta=h.valObjectMeta,l.coerce=h.coerce,l.coerce2=h.coerce2,l.coerceFont=h.coerceFont,l.coerceHoverinfo=h.coerceHoverinfo,l.coerceSelectionMarkerOpacity=h.coerceSelectionMarkerOpacity,l.validate=h.validate;var f=t("./dates");l.dateTime2ms=f.dateTime2ms,l.isDateTime=f.isDateTime,l.ms2DateTime=f.ms2DateTime,l.ms2DateTimeLocal=f.ms2DateTimeLocal,l.cleanDate=f.cleanDate,l.isJSDate=f.isJSDate,l.formatDate=f.formatDate,l.incrementMonth=f.incrementMonth,l.dateTick0=f.dateTick0,l.dfltRange=f.dfltRange,l.findExactDates=f.findExactDates,l.MIN_MS=f.MIN_MS,l.MAX_MS=f.MAX_MS;var p=t("./search");l.findBin=p.findBin,l.sorterAsc=p.sorterAsc,l.sorterDes=p.sorterDes,l.distinctVals=p.distinctVals,l.roundUp=p.roundUp,l.sort=p.sort,l.findIndexOfMin=p.findIndexOfMin;var d=t("./stats");l.aggNums=d.aggNums,l.len=d.len,l.mean=d.mean,l.midRange=d.midRange,l.variance=d.variance,l.stdev=d.stdev,l.interp=d.interp;var g=t("./matrix");l.init2dArray=g.init2dArray,l.transposeRagged=g.transposeRagged,l.dot=g.dot,l.translationMatrix=g.translationMatrix,l.rotationMatrix=g.rotationMatrix,l.rotationXYMatrix=g.rotationXYMatrix,l.apply2DTransform=g.apply2DTransform,l.apply2DTransform2=g.apply2DTransform2;var v=t("./angles");l.deg2rad=v.deg2rad,l.rad2deg=v.rad2deg,l.angleDelta=v.angleDelta,l.angleDist=v.angleDist,l.isFullCircle=v.isFullCircle,l.isAngleInsideSector=v.isAngleInsideSector,l.isPtInsideSector=v.isPtInsideSector,l.pathArc=v.pathArc,l.pathSector=v.pathSector,l.pathAnnulus=v.pathAnnulus;var m=t("./anchor_utils");l.isLeftAnchor=m.isLeftAnchor,l.isCenterAnchor=m.isCenterAnchor,l.isRightAnchor=m.isRightAnchor,l.isTopAnchor=m.isTopAnchor,l.isMiddleAnchor=m.isMiddleAnchor,l.isBottomAnchor=m.isBottomAnchor;var y=t("./geometry2d");l.segmentsIntersect=y.segmentsIntersect,l.segmentDistance=y.segmentDistance,l.getTextLocation=y.getTextLocation,l.clearLocationCache=y.clearLocationCache,l.getVisibleSegment=y.getVisibleSegment,l.findPointOnPath=y.findPointOnPath;var x=t("./extend");l.extendFlat=x.extendFlat,l.extendDeep=x.extendDeep,l.extendDeepAll=x.extendDeepAll,l.extendDeepNoArrays=x.extendDeepNoArrays;var b=t("./loggers");l.log=b.log,l.warn=b.warn,l.error=b.error;var _=t("./regex");l.counterRegex=_.counter;var w=t("./throttle");function k(t){var e={};for(var r in t)for(var n=t[r],i=0;i<n.length;i++)e[n[i]]=+r;return e}l.throttle=w.throttle,l.throttleDone=w.done,l.clearThrottle=w.clear,l.getGraphDiv=t("./get_graph_div"),l.clearResponsive=t("./clear_responsive"),l.makeTraceGroups=t("./make_trace_groups"),l._=t("./localize"),l.notifier=t("./notifier"),l.filterUnique=t("./filter_unique"),l.filterVisible=t("./filter_visible"),l.pushUnique=t("./push_unique"),l.cleanNumber=t("./clean_number"),l.ensureNumber=function(t){return i(t)?(t=Number(t))<-o||t>o?s:i(t)?Number(t):s:s},l.isIndex=function(t,e){return!(void 0!==e&&t>=e)&&(i(t)&&t>=0&&t%1==0)},l.noop=t("./noop"),l.identity=t("./identity"),l.repeat=function(t,e){for(var r=new Array(e),n=0;n<e;n++)r[n]=t;return r},l.swapAttrs=function(t,e,r,n){r||(r="x"),n||(n="y");for(var i=0;i<e.length;i++){var a=e[i],o=l.nestedProperty(t,a.replace("?",r)),s=l.nestedProperty(t,a.replace("?",n)),c=o.get();o.set(s.get()),s.set(c)}},l.raiseToTop=function(t){t.parentNode.appendChild(t)},l.cancelTransition=function(t){return t.transition().duration(0)},l.constrain=function(t,e,r){return e>r?Math.max(r,Math.min(e,t)):Math.max(e,Math.min(r,t))},l.bBoxIntersect=function(t,e,r){return r=r||0,t.left<=e.right+r&&e.left<=t.right+r&&t.top<=e.bottom+r&&e.top<=t.bottom+r},l.simpleMap=function(t,e,r,n){for(var i=t.length,a=new Array(i),o=0;o<i;o++)a[o]=e(t[o],r,n);return a},l.randstr=function t(e,r,n,i){if(n||(n=16),void 0===r&&(r=24),r<=0)return"0";var a,o,s=Math.log(Math.pow(2,r))/Math.log(n),c="";for(a=2;s===1/0;a*=2)s=Math.log(Math.pow(2,r/a))/Math.log(n)*a;var u=s-Math.floor(s);for(a=0;a<Math.floor(s);a++)c=Math.floor(Math.random()*n).toString(n)+c;u&&(o=Math.pow(n,u),c=Math.floor(Math.random()*o).toString(n)+c);var h=parseInt(c,n);return e&&e[c]||h!==1/0&&h>=Math.pow(2,r)?i>10?(l.warn("randstr failed uniqueness"),c):t(e,r,n,(i||0)+1):c},l.OptionControl=function(t,e){t||(t={}),e||(e="opt");var r={optionList:[],_newoption:function(n){n[e]=t,r[n.name]=n,r.optionList.push(n)}};return r["_"+e]=t,r},l.smooth=function(t,e){if((e=Math.round(e)||0)<2)return t;var r,n,i,a,o=t.length,s=2*o,l=2*e-1,c=new Array(l),u=new Array(o);for(r=0;r<l;r++)c[r]=(1-Math.cos(Math.PI*(r+1)/e))/(2*e);for(r=0;r<o;r++){for(a=0,n=0;n<l;n++)(i=r+n+1-e)<-o?i-=s*Math.round(i/s):i>=s&&(i-=s*Math.floor(i/s)),i<0?i=-1-i:i>=o&&(i=s-1-i),a+=t[i]*c[n];u[r]=a}return u},l.syncOrAsync=function(t,e,r){var n;function i(){return l.syncOrAsync(t,e,r)}for(;t.length;)if((n=(0,t.splice(0,1)[0])(e))&&n.then)return n.then(i).then(void 0,l.promiseError);return r&&r(e)},l.stripTrailingSlash=function(t){return"/"===t.substr(-1)?t.substr(0,t.length-1):t},l.noneOrAll=function(t,e,r){if(t){var n,i=!1,a=!0;for(n=0;n<r.length;n++)null!=t[r[n]]?i=!0:a=!1;if(i&&!a)for(n=0;n<r.length;n++)t[r[n]]=e[r[n]]}},l.mergeArray=function(t,e,r){if(l.isArrayOrTypedArray(t))for(var n=Math.min(t.length,e.length),i=0;i<n;i++)e[i][r]=t[i]},l.fillArray=function(t,e,r,n){if(n=n||l.identity,l.isArrayOrTypedArray(t))for(var i=0;i<e.length;i++)e[i][r]=n(t[i])},l.castOption=function(t,e,r,n){n=n||l.identity;var i=l.nestedProperty(t,r).get();return l.isArrayOrTypedArray(i)?Array.isArray(e)&&l.isArrayOrTypedArray(i[e[0]])?n(i[e[0]][e[1]]):n(i[e]):i},l.extractOption=function(t,e,r,n){if(r in t)return t[r];var i=l.nestedProperty(e,n).get();return Array.isArray(i)?void 0:i},l.tagSelected=function(t,e,r){var n,i,a=e.selectedpoints,o=e._indexToPoints;o&&(n=k(o));for(var s=0;s<a.length;s++){var c=a[s];if(l.isIndex(c)){var u=n?n[c]:c,h=r?r[u]:u;void 0!==(i=h)&&i<t.length&&(t[h].selected=1)}}},l.selIndices2selPoints=function(t){var e=t.selectedpoints,r=t._indexToPoints;if(r){for(var n=k(r),i=[],a=0;a<e.length;a++){var o=e[a];if(l.isIndex(o)){var s=n[o];l.isIndex(s)&&i.push(s)}}return i}return e},l.getTargetArray=function(t,e){var r=e.target;if("string"==typeof r&&r){var n=l.nestedProperty(t,r).get();return!!Array.isArray(n)&&n}return!!Array.isArray(r)&&r},l.minExtend=function(t,e){var r={};"object"!=typeof e&&(e={});var n,i,a,o=Object.keys(t);for(n=0;n<o.length;n++)a=t[i=o[n]],"_"!==i.charAt(0)&&"function"!=typeof a&&("module"===i?r[i]=a:Array.isArray(a)?r[i]="colorscale"===i?a.slice():a.slice(0,3):r[i]=a&&"object"==typeof a?l.minExtend(t[i],e[i]):a);for(o=Object.keys(e),n=0;n<o.length;n++)"object"==typeof(a=e[i=o[n]])&&i in r&&"object"==typeof r[i]||(r[i]=a);return r},l.titleCase=function(t){return t.charAt(0).toUpperCase()+t.substr(1)},l.containsAny=function(t,e){for(var r=0;r<e.length;r++)if(-1!==t.indexOf(e[r]))return!0;return!1},l.isPlotDiv=function(t){var e=n.select(t);return e.node()instanceof HTMLElement&&e.size()&&e.classed("js-plotly-plot")},l.removeElement=function(t){var e=t&&t.parentNode;e&&e.removeChild(t)},l.addStyleRule=function(t,e){l.addRelatedStyleRule("global",t,e)},l.addRelatedStyleRule=function(t,e,r){var n="plotly.js-style-"+t,i=document.getElementById(n);i||((i=document.createElement("style")).setAttribute("id",n),i.appendChild(document.createTextNode("")),document.head.appendChild(i));var a=i.sheet;a.insertRule?a.insertRule(e+"{"+r+"}",0):a.addRule?a.addRule(e,r,0):l.warn("addStyleRule failed")},l.deleteRelatedStyleRule=function(t){var e="plotly.js-style-"+t,r=document.getElementById(e);r&&l.removeElement(r)},l.isIE=function(){return"undefined"!=typeof window.navigator.msSaveBlob},l.isD3Selection=function(t){return t&&"function"==typeof t.classed},l.ensureSingle=function(t,e,r,n){var i=t.select(e+(r?"."+r:""));if(i.size())return i;var a=t.append(e);return r&&a.classed(r,!0),n&&a.call(n),a},l.ensureSingleById=function(t,e,r,n){var i=t.select(e+"#"+r);if(i.size())return i;var a=t.append(e).attr("id",r);return n&&a.call(n),a},l.objectFromPath=function(t,e){for(var r,n=t.split("."),i=r={},a=0;a<n.length;a++){var o=n[a],s=null,l=n[a].match(/(.*)\[([0-9]+)\]/);l?(o=l[1],s=l[2],r=r[o]=[],a===n.length-1?r[s]=e:r[s]={},r=r[s]):(a===n.length-1?r[o]=e:r[o]={},r=r[o])}return i};var A=/^([^\[\.]+)\.(.+)?/,M=/^([^\.]+)\[([0-9]+)\](\.)?(.+)?/;l.expandObjectPaths=function(t){var e,r,n,i,a,o,s;if("object"==typeof t&&!Array.isArray(t))for(r in t)t.hasOwnProperty(r)&&((e=r.match(A))?(i=t[r],n=e[1],delete t[r],t[n]=l.extendDeepNoArrays(t[n]||{},l.objectFromPath(r,l.expandObjectPaths(i))[n])):(e=r.match(M))?(i=t[r],n=e[1],a=parseInt(e[2]),delete t[r],t[n]=t[n]||[],"."===e[3]?(s=e[4],o=t[n][a]=t[n][a]||{},l.extendDeepNoArrays(o,l.objectFromPath(s,l.expandObjectPaths(i)))):t[n][a]=l.expandObjectPaths(i)):t[r]=l.expandObjectPaths(t[r]));return t},l.numSeparate=function(t,e,r){if(r||(r=!1),"string"!=typeof e||0===e.length)throw new Error("Separator string required for formatting!");"number"==typeof t&&(t=String(t));var n=/(\d+)(\d{3})/,i=e.charAt(0),a=e.charAt(1),o=t.split("."),s=o[0],l=o.length>1?i+o[1]:"";if(a&&(o.length>1||s.length>4||r))for(;n.test(s);)s=s.replace(n,"$1"+a+"$2");return s+l},l.TEMPLATE_STRING_REGEX=/%{([^\s%{}:]*)(:[^}]*)?}/g;var T=/^\w*$/;l.templateString=function(t,e){var r={};return t.replace(l.TEMPLATE_STRING_REGEX,function(t,n){return T.test(n)?e[n]||"":(r[n]=r[n]||l.nestedProperty(e,n).get,r[n]()||"")})};var S=/^:/,E=0;l.hovertemplateString=function(t,e,r){var i=arguments,a={};return t.replace(l.TEMPLATE_STRING_REGEX,function(t,o,s){var c,u,h;for(h=3;h<i.length;h++){if((c=i[h]).hasOwnProperty(o)){u=c[o];break}if(T.test(o)||(u=a[o]||l.nestedProperty(c,o).get())&&(a[o]=u),void 0!==u)break}(void 0===u&&(E<10&&(l.warn("Variable '"+o+"' in hovertemplate could not be found!"),u=t),10===E&&l.warn("Too many hovertemplate warnings - additional warnings will be suppressed"),E++),s)?u=(r?r.numberFormat:n.format)(s.replace(S,""))(u):e.hasOwnProperty(o+"Label")&&(u=e[o+"Label"]);return u})};l.subplotSort=function(t,e){for(var r=Math.min(t.length,e.length)+1,n=0,i=0,a=0;a<r;a++){var o=t.charCodeAt(a)||0,s=e.charCodeAt(a)||0,l=o>=48&&o<=57,c=s>=48&&s<=57;if(l&&(n=10*n+o-48),c&&(i=10*i+s-48),!l||!c){if(n!==i)return n-i;if(o!==s)return o-s}}return i-n};var C=2e9;l.seedPseudoRandom=function(){C=2e9},l.pseudoRandom=function(){var t=C;return C=(69069*C+1)%4294967296,Math.abs(C-t)<429496729?l.pseudoRandom():C/4294967296}},{"../constants/numerical":674,"./anchor_utils":678,"./angles":679,"./array":680,"./clean_number":681,"./clear_responsive":683,"./coerce":684,"./dates":685,"./extend":687,"./filter_unique":688,"./filter_visible":689,"./geometry2d":692,"./get_graph_div":693,"./identity":696,"./is_plain_object":698,"./keyed_container":699,"./localize":700,"./loggers":701,"./make_trace_groups":702,"./matrix":703,"./mod":704,"./nested_property":705,"./noop":706,"./notifier":707,"./push_unique":711,"./regex":713,"./relative_attr":714,"./relink_private":715,"./search":716,"./stats":719,"./throttle":722,"./to_log_range":723,d3:151,"fast-isnumeric":218}],698:[function(t,e,r){"use strict";e.exports=function(t){return window&&window.process&&window.process.versions?"[object Object]"===Object.prototype.toString.call(t):"[object Object]"===Object.prototype.toString.call(t)&&Object.getPrototypeOf(t)===Object.prototype}},{}],699:[function(t,e,r){"use strict";var n=t("./nested_property"),i=/^\w*$/;e.exports=function(t,e,r,a){var o,s,l;r=r||"name",a=a||"value";var c={};e&&e.length?(l=n(t,e),s=l.get()):s=t,e=e||"";var u={};if(s)for(o=0;o<s.length;o++)u[s[o][r]]=o;var h=i.test(a),f={set:function(t,e){var i=null===e?4:0;if(!s){if(!l||4===i)return;s=[],l.set(s)}var o=u[t];if(void 0===o){if(4===i)return;i|=3,o=s.length,u[t]=o}else e!==(h?s[o][a]:n(s[o],a).get())&&(i|=2);var p=s[o]=s[o]||{};return p[r]=t,h?p[a]=e:n(p,a).set(e),null!==e&&(i&=-5),c[o]=c[o]|i,f},get:function(t){if(s){var e=u[t];return void 0===e?void 0:h?s[e][a]:n(s[e],a).get()}},rename:function(t,e){var n=u[t];return void 0===n?f:(c[n]=1|c[n],u[e]=n,delete u[t],s[n][r]=e,f)},remove:function(t){var e=u[t];if(void 0===e)return f;var i=s[e];if(Object.keys(i).length>2)return c[e]=2|c[e],f.set(t,null);if(h){for(o=e;o<s.length;o++)c[o]=3|c[o];for(o=e;o<s.length;o++)u[s[o][r]]--;s.splice(e,1),delete u[t]}else n(i,a).set(null),c[e]=6|c[e];return f},constructUpdate:function(){for(var t,i,o={},l=Object.keys(c),u=0;u<l.length;u++)i=l[u],t=e+"["+i+"]",s[i]?(1&c[i]&&(o[t+"."+r]=s[i][r]),2&c[i]&&(o[t+"."+a]=h?4&c[i]?null:s[i][a]:4&c[i]?null:n(s[i],a).get())):o[t]=null;return o}};return f}},{"./nested_property":705}],700:[function(t,e,r){"use strict";var n=t("../registry");e.exports=function(t,e){for(var r=t._context.locale,i=0;i<2;i++){for(var a=t._context.locales,o=0;o<2;o++){var s=(a[r]||{}).dictionary;if(s){var l=s[e];if(l)return l}a=n.localeRegistry}var c=r.split("-")[0];if(c===r)break;r=c}return e}},{"../registry":826}],701:[function(t,e,r){"use strict";var n=t("../plot_api/plot_config").dfltConfig,i=e.exports={};function a(t,e){if(t&&t.apply)try{return void t.apply(console,e)}catch(t){}for(var r=0;r<e.length;r++)try{t(e[r])}catch(t){console.log(e[r])}}i.log=function(){if(n.logging>1){for(var t=["LOG:"],e=0;e<arguments.length;e++)t.push(arguments[e]);a(console.trace||console.log,t)}},i.warn=function(){if(n.logging>0){for(var t=["WARN:"],e=0;e<arguments.length;e++)t.push(arguments[e]);a(console.trace||console.log,t)}},i.error=function(){if(n.logging>0){for(var t=["ERROR:"],e=0;e<arguments.length;e++)t.push(arguments[e]);a(console.error,t)}}},{"../plot_api/plot_config":733}],702:[function(t,e,r){"use strict";e.exports=function(t,e,r){var n=t.selectAll("g."+r.replace(/\s/g,".")).data(e,function(t){return t[0].trace.uid});return n.exit().remove(),n.enter().append("g").attr("class",r),n.order(),n}},{}],703:[function(t,e,r){"use strict";r.init2dArray=function(t,e){for(var r=new Array(t),n=0;n<t;n++)r[n]=new Array(e);return r},r.transposeRagged=function(t){var e,r,n=0,i=t.length;for(e=0;e<i;e++)n=Math.max(n,t[e].length);var a=new Array(n);for(e=0;e<n;e++)for(a[e]=new Array(i),r=0;r<i;r++)a[e][r]=t[r][e];return a},r.dot=function(t,e){if(!t.length||!e.length||t.length!==e.length)return null;var n,i,a=t.length;if(t[0].length)for(n=new Array(a),i=0;i<a;i++)n[i]=r.dot(t[i],e);else if(e[0].length){var o=r.transposeRagged(e);for(n=new Array(o.length),i=0;i<o.length;i++)n[i]=r.dot(t,o[i])}else for(n=0,i=0;i<a;i++)n+=t[i]*e[i];return n},r.translationMatrix=function(t,e){return[[1,0,t],[0,1,e],[0,0,1]]},r.rotationMatrix=function(t){var e=t*Math.PI/180;return[[Math.cos(e),-Math.sin(e),0],[Math.sin(e),Math.cos(e),0],[0,0,1]]},r.rotationXYMatrix=function(t,e,n){return r.dot(r.dot(r.translationMatrix(e,n),r.rotationMatrix(t)),r.translationMatrix(-e,-n))},r.apply2DTransform=function(t){return function(){var e=arguments;3===e.length&&(e=e[0]);var n=1===arguments.length?e[0]:[e[0],e[1]];return r.dot(t,[n[0],n[1],1]).slice(0,2)}},r.apply2DTransform2=function(t){var e=r.apply2DTransform(t);return function(t){return e(t.slice(0,2)).concat(e(t.slice(2,4)))}}},{}],704:[function(t,e,r){"use strict";e.exports={mod:function(t,e){var r=t%e;return r<0?r+e:r},modHalf:function(t,e){return Math.abs(t)>e/2?t-Math.round(t/e)*e:t}}},{}],705:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("./array").isArrayOrTypedArray;e.exports=function(t,e){if(n(e))e=String(e);else if("string"!=typeof e||"[-1]"===e.substr(e.length-4))throw"bad property string";for(var r,a,o,l=0,c=e.split(".");l<c.length;){if(r=String(c[l]).match(/^([^\[\]]*)((\[\-?[0-9]*\])+)$/)){if(r[1])c[l]=r[1];else{if(0!==l)throw"bad property string";c.splice(0,1)}for(a=r[2].substr(1,r[2].length-2).split("]["),o=0;o<a.length;o++)l++,c.splice(l,0,Number(a[o]))}l++}return"object"!=typeof t?function(t,e,r){return{set:function(){throw"bad container"},get:function(){},astr:e,parts:r,obj:t}}(t,e,c):{set:s(t,c,e),get:function t(e,r){return function(){var n,a,o,s,l,c=e;for(s=0;s<r.length-1;s++){if(-1===(n=r[s])){for(a=!0,o=[],l=0;l<c.length;l++)o[l]=t(c[l],r.slice(s+1))(),o[l]!==o[0]&&(a=!1);return a?o[0]:o}if("number"==typeof n&&!i(c))return;if("object"!=typeof(c=c[n])||null===c)return}if("object"==typeof c&&null!==c&&null!==(o=c[r[s]]))return o}}(t,c),astr:e,parts:c,obj:t}};var a=/(^|\.)args\[/;function o(t,e){return void 0===t||null===t&&!e.match(a)}function s(t,e,r){return function(n){var a,s,h=t,f="",p=[[t,f]],d=o(n,r);for(s=0;s<e.length-1;s++){if("number"==typeof(a=e[s])&&!i(h))throw"array index but container is not an array";if(-1===a){if(d=!c(h,e.slice(s+1),n,r))break;return}if(!u(h,a,e[s+1],d))break;if("object"!=typeof(h=h[a])||null===h)throw"container is not an object";f=l(f,a),p.push([h,f])}if(d){if(s===e.length-1&&(delete h[e[s]],Array.isArray(h)&&+e[s]==h.length-1))for(;h.length&&void 0===h[h.length-1];)h.pop()}else h[e[s]]=n}}function l(t,e){var r=e;return n(e)?r="["+e+"]":t&&(r="."+e),t+r}function c(t,e,r,n){var a,l=i(r),c=!0,h=r,f=n.replace("-1",0),p=!l&&o(r,f),d=e[0];for(a=0;a<t.length;a++)f=n.replace("-1",a),l&&(p=o(h=r[a%r.length],f)),p&&(c=!1),u(t,a,d,p)&&s(t[a],e,n.replace("-1",a))(h);return c}function u(t,e,r,n){if(void 0===t[e]){if(n)return!1;t[e]="number"==typeof r?[]:{}}return!0}},{"./array":680,"fast-isnumeric":218}],706:[function(t,e,r){"use strict";e.exports=function(){}},{}],707:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=[];e.exports=function(t,e){if(-1===a.indexOf(t)){a.push(t);var r=1e3;i(e)?r=e:"long"===e&&(r=3e3);var o=n.select("body").selectAll(".plotly-notifier").data([0]);o.enter().append("div").classed("plotly-notifier",!0),o.selectAll(".notifier-note").data(a).enter().append("div").classed("notifier-note",!0).style("opacity",0).each(function(t){var e=n.select(this);e.append("button").classed("notifier-close",!0).html("&times;").on("click",function(){e.transition().call(s)});for(var i=e.append("p"),a=t.split(/<br\s*\/?>/g),o=0;o<a.length;o++)o&&i.append("br"),i.append("span").text(a[o]);e.transition().duration(700).style("opacity",1).transition().delay(r).call(s)})}function s(t){t.duration(700).style("opacity",0).each("end",function(t){var e=a.indexOf(t);-1!==e&&a.splice(e,1),n.select(this).remove()})}}},{d3:151,"fast-isnumeric":218}],708:[function(t,e,r){"use strict";var n=t("./setcursor"),i="data-savedcursor";e.exports=function(t,e){var r=t.attr(i);if(e){if(!r){for(var a=(t.attr("class")||"").split(" "),o=0;o<a.length;o++){var s=a[o];0===s.indexOf("cursor-")&&t.attr(i,s.substr(7)).classed(s,!1)}t.attr(i)||t.attr(i,"!!")}n(t,e)}else r&&(t.attr(i,null),"!!"===r?n(t):n(t,r))}},{"./setcursor":717}],709:[function(t,e,r){"use strict";var n=t("./matrix").dot,i=t("../constants/numerical").BADNUM,a=e.exports={};a.tester=function(t){var e,r=t.slice(),n=r[0][0],a=n,o=r[0][1],s=o;for(r.push(r[0]),e=1;e<r.length;e++)n=Math.min(n,r[e][0]),a=Math.max(a,r[e][0]),o=Math.min(o,r[e][1]),s=Math.max(s,r[e][1]);var l,c=!1;5===r.length&&(r[0][0]===r[1][0]?r[2][0]===r[3][0]&&r[0][1]===r[3][1]&&r[1][1]===r[2][1]&&(c=!0,l=function(t){return t[0]===r[0][0]}):r[0][1]===r[1][1]&&r[2][1]===r[3][1]&&r[0][0]===r[3][0]&&r[1][0]===r[2][0]&&(c=!0,l=function(t){return t[1]===r[0][1]}));var u=!0,h=r[0];for(e=1;e<r.length;e++)if(h[0]!==r[e][0]||h[1]!==r[e][1]){u=!1;break}return{xmin:n,xmax:a,ymin:o,ymax:s,pts:r,contains:c?function(t,e){var r=t[0],c=t[1];return!(r===i||r<n||r>a||c===i||c<o||c>s||e&&l(t))}:function(t,e){var l=t[0],c=t[1];if(l===i||l<n||l>a||c===i||c<o||c>s)return!1;var u,h,f,p,d,g=r.length,v=r[0][0],m=r[0][1],y=0;for(u=1;u<g;u++)if(h=v,f=m,v=r[u][0],m=r[u][1],!(l<(p=Math.min(h,v))||l>Math.max(h,v)||c>Math.max(f,m)))if(c<Math.min(f,m))l!==p&&y++;else{if(c===(d=v===h?c:f+(l-h)*(m-f)/(v-h)))return 1!==u||!e;c<=d&&l!==p&&y++}return y%2==1},isRect:c,degenerate:u}};var o=a.isSegmentBent=function(t,e,r,i){var a,o,s,l=t[e],c=[t[r][0]-l[0],t[r][1]-l[1]],u=n(c,c),h=Math.sqrt(u),f=[-c[1]/h,c[0]/h];for(a=e+1;a<r;a++)if(o=[t[a][0]-l[0],t[a][1]-l[1]],(s=n(o,c))<0||s>u||Math.abs(n(o,f))>i)return!0;return!1};a.filter=function(t,e){var r=[t[0]],n=0,i=0;function a(a){t.push(a);var s=r.length,l=n;r.splice(i+1);for(var c=l+1;c<t.length;c++)(c===t.length-1||o(t,l,c+1,e))&&(r.push(t[c]),r.length<s-2&&(n=c,i=r.length-1),l=c)}t.length>1&&a(t.pop());return{addPt:a,raw:t,filtered:r}}},{"../constants/numerical":674,"./matrix":703}],710:[function(t,e,r){(function(r){"use strict";var n=t("./show_no_webgl_msg"),i=t("regl");e.exports=function(t,e){var a=t._fullLayout,o=!0;return a._glcanvas.each(function(n){if(!n.regl&&(!n.pick||a._has("parcoords"))){try{n.regl=i({canvas:this,attributes:{antialias:!n.pick,preserveDrawingBuffer:!0},pixelRatio:t._context.plotGlPixelRatio||r.devicePixelRatio,extensions:e||[]})}catch(t){o=!1}o&&this.addEventListener("webglcontextlost",function(e){t&&t.emit&&t.emit("plotly_webglcontextlost",{event:e,layer:n.key})},!1)}}),o||n({container:a._glcontainer.node()}),o}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./show_no_webgl_msg":718,regl:483}],711:[function(t,e,r){"use strict";e.exports=function(t,e){if(e instanceof RegExp){for(var r=e.toString(),n=0;n<t.length;n++)if(t[n]instanceof RegExp&&t[n].toString()===r)return t;t.push(e)}else!e&&0!==e||-1!==t.indexOf(e)||t.push(e);return t}},{}],712:[function(t,e,r){"use strict";var n=t("../lib"),i=t("../plot_api/plot_config").dfltConfig;var a={add:function(t,e,r,n,a){var o,s;t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},s=t.undoQueue.index,t.autoplay?t.undoQueue.inSequence||(t.autoplay=!1):(!t.undoQueue.sequence||t.undoQueue.beginSequence?(o={undo:{calls:[],args:[]},redo:{calls:[],args:[]}},t.undoQueue.queue.splice(s,t.undoQueue.queue.length-s,o),t.undoQueue.index+=1):o=t.undoQueue.queue[s-1],t.undoQueue.beginSequence=!1,o&&(o.undo.calls.unshift(e),o.undo.args.unshift(r),o.redo.calls.push(n),o.redo.args.push(a)),t.undoQueue.queue.length>i.queueLength&&(t.undoQueue.queue.shift(),t.undoQueue.index--))},startSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!0,t.undoQueue.beginSequence=!0},stopSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!1,t.undoQueue.beginSequence=!1},undo:function(t){var e,r;if(t.framework&&t.framework.isPolar)t.framework.undo();else if(!(void 0===t.undoQueue||isNaN(t.undoQueue.index)||t.undoQueue.index<=0)){for(t.undoQueue.index--,e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r<e.undo.calls.length;r++)a.plotDo(t,e.undo.calls[r],e.undo.args[r]);t.undoQueue.inSequence=!1,t.autoplay=!1}},redo:function(t){var e,r;if(t.framework&&t.framework.isPolar)t.framework.redo();else if(!(void 0===t.undoQueue||isNaN(t.undoQueue.index)||t.undoQueue.index>=t.undoQueue.queue.length)){for(e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r<e.redo.calls.length;r++)a.plotDo(t,e.redo.calls[r],e.redo.args[r]);t.undoQueue.inSequence=!1,t.autoplay=!1,t.undoQueue.index++}}};a.plotDo=function(t,e,r){t.autoplay=!0,r=function(t,e){for(var r,i=[],a=0;a<e.length;a++)r=e[a],i[a]=r===t?r:"object"==typeof r?Array.isArray(r)?n.extendDeep([],r):n.extendDeepAll({},r):r;return i}(t,r),e.apply(null,r)},e.exports=a},{"../lib":697,"../plot_api/plot_config":733}],713:[function(t,e,r){"use strict";r.counter=function(t,e,r,n){var i=(e||"")+(r?"":"$"),a=!1===n?"":"^";return"xy"===t?new RegExp(a+"x([2-9]|[1-9][0-9]+)?y([2-9]|[1-9][0-9]+)?"+i):new RegExp(a+t+"([2-9]|[1-9][0-9]+)?"+i)}},{}],714:[function(t,e,r){"use strict";var n=/^(.*)(\.[^\.\[\]]+|\[\d\])$/,i=/^[^\.\[\]]+$/;e.exports=function(t,e){for(;e;){var r=t.match(n);if(r)t=r[1];else{if(!t.match(i))throw new Error("bad relativeAttr call:"+[t,e]);t=""}if("^"!==e.charAt(0))break;e=e.slice(1)}return t&&"["!==e.charAt(0)?t+"."+e:t+e}},{}],715:[function(t,e,r){"use strict";var n=t("./array").isArrayOrTypedArray,i=t("./is_plain_object");e.exports=function t(e,r){for(var a in r){var o=r[a],s=e[a];if(s!==o)if("_"===a.charAt(0)||"function"==typeof o){if(a in e)continue;e[a]=o}else if(n(o)&&n(s)&&i(o[0])){if("customdata"===a||"ids"===a)continue;for(var l=Math.min(o.length,s.length),c=0;c<l;c++)s[c]!==o[c]&&i(o[c])&&i(s[c])&&t(s[c],o[c])}else i(o)&&i(s)&&(t(s,o),Object.keys(s).length||delete e[a])}}},{"./array":680,"./is_plain_object":698}],716:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("./loggers"),a=t("./identity");function o(t,e){return t<e}function s(t,e){return t<=e}function l(t,e){return t>e}function c(t,e){return t>=e}r.findBin=function(t,e,r){if(n(e.start))return r?Math.ceil((t-e.start)/e.size-1e-9)-1:Math.floor((t-e.start)/e.size+1e-9);var a,u,h=0,f=e.length,p=0,d=f>1?(e[f-1]-e[0])/(f-1):1;for(u=d>=0?r?o:s:r?c:l,t+=1e-9*d*(r?-1:1)*(d>=0?1:-1);h<f&&p++<100;)u(e[a=Math.floor((h+f)/2)],t)?h=a+1:f=a;return p>90&&i.log("Long binary search..."),h-1},r.sorterAsc=function(t,e){return t-e},r.sorterDes=function(t,e){return e-t},r.distinctVals=function(t){var e=t.slice();e.sort(r.sorterAsc);for(var n=e.length-1,i=e[n]-e[0]||1,a=i/(n||1)/1e4,o=[e[0]],s=0;s<n;s++)e[s+1]>e[s]+a&&(i=Math.min(i,e[s+1]-e[s]),o.push(e[s+1]));return{vals:o,minDiff:i}},r.roundUp=function(t,e,r){for(var n,i=0,a=e.length-1,o=0,s=r?0:1,l=r?1:0,c=r?Math.ceil:Math.floor;i<a&&o++<100;)e[n=c((i+a)/2)]<=t?i=n+s:a=n-l;return e[i]},r.sort=function(t,e){for(var r=0,n=0,i=1;i<t.length;i++){var a=e(t[i],t[i-1]);if(a<0?r=1:a>0&&(n=1),r&&n)return t.sort(e)}return n?t:t.reverse()},r.findIndexOfMin=function(t,e){e=e||a;for(var r,n=1/0,i=0;i<t.length;i++){var o=e(t[i]);o<n&&(n=o,r=i)}return r}},{"./identity":696,"./loggers":701,"fast-isnumeric":218}],717:[function(t,e,r){"use strict";e.exports=function(t,e){(t.attr("class")||"").split(" ").forEach(function(e){0===e.indexOf("cursor-")&&t.classed(e,!1)}),e&&t.classed("cursor-"+e,!0)}},{}],718:[function(t,e,r){"use strict";var n=t("../components/color"),i=function(){};e.exports=function(t){for(var e in t)"function"==typeof t[e]&&(t[e]=i);t.destroy=function(){t.container.parentNode.removeChild(t.container)};var r=document.createElement("div");r.className="no-webgl",r.style.cursor="pointer",r.style.fontSize="24px",r.style.color=n.defaults[0],r.style.position="absolute",r.style.left=r.style.top="0px",r.style.width=r.style.height="100%",r.style["background-color"]=n.lightLine,r.style["z-index"]=30;var a=document.createElement("p");return a.textContent="WebGL is not supported by your browser - visit https://get.webgl.org for more info",a.style.position="relative",a.style.top="50%",a.style.left="50%",a.style.height="30%",a.style.width="50%",a.style.margin="-15% 0 0 -25%",r.appendChild(a),t.container.appendChild(r),t.container.style.background="#FFFFFF",t.container.onclick=function(){window.open("https://get.webgl.org")},!1}},{"../components/color":574}],719:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("./array").isArrayOrTypedArray;r.aggNums=function(t,e,a,o){var s,l;if((!o||o>a.length)&&(o=a.length),n(e)||(e=!1),i(a[0])){for(l=new Array(o),s=0;s<o;s++)l[s]=r.aggNums(t,e,a[s]);a=l}for(s=0;s<o;s++)n(e)?n(a[s])&&(e=t(+e,+a[s])):e=a[s];return e},r.len=function(t){return r.aggNums(function(t){return t+1},0,t)},r.mean=function(t,e){return e||(e=r.len(t)),r.aggNums(function(t,e){return t+e},0,t)/e},r.midRange=function(t){if(void 0!==t&&0!==t.length)return(r.aggNums(Math.max,null,t)+r.aggNums(Math.min,null,t))/2},r.variance=function(t,e,i){return e||(e=r.len(t)),n(i)||(i=r.mean(t,e)),r.aggNums(function(t,e){return t+Math.pow(e-i,2)},0,t)/e},r.stdev=function(t,e,n){return Math.sqrt(r.variance(t,e,n))},r.interp=function(t,e){if(!n(e))throw"n should be a finite number";if((e=e*t.length-.5)<0)return t[0];if(e>t.length-1)return t[t.length-1];var r=e%1;return r*t[Math.ceil(e)]+(1-r)*t[Math.floor(e)]}},{"./array":680,"fast-isnumeric":218}],720:[function(t,e,r){"use strict";var n=t("color-normalize");e.exports=function(t){return t?n(t):[0,0,0,1]}},{"color-normalize":108}],721:[function(t,e,r){"use strict";var n=t("d3"),i=t("../lib"),a=t("../constants/xmlns_namespaces"),o=t("../constants/alignment").LINE_SPACING;function s(t,e){return t.node().getBoundingClientRect()[e]}var l=/([^$]*)([$]+[^$]*[$]+)([^$]*)/;r.convertToTspans=function(t,e,T){var S=t.text(),C=!t.attr("data-notex")&&"undefined"!=typeof MathJax&&S.match(l),L=n.select(t.node().parentNode);if(!L.empty()){var z=t.attr("class")?t.attr("class").split(" ")[0]:"text";return z+="-math",L.selectAll("svg."+z).remove(),L.selectAll("g."+z+"-group").remove(),t.style("display",null).attr({"data-unformatted":S,"data-math":"N"}),C?(e&&e._promises||[]).push(new Promise(function(e){t.style("display","none");var r=parseInt(t.node().style.fontSize,10),a={fontSize:r};!function(t,e,r){var a,o,s,l;MathJax.Hub.Queue(function(){return o=i.extendDeepAll({},MathJax.Hub.config),s=MathJax.Hub.processSectionDelay,void 0!==MathJax.Hub.processSectionDelay&&(MathJax.Hub.processSectionDelay=0),MathJax.Hub.Config({messageStyle:"none",tex2jax:{inlineMath:[["$","$"],["\\(","\\)"]]},displayAlign:"left"})},function(){if("SVG"!==(a=MathJax.Hub.config.menuSettings.renderer))return MathJax.Hub.setRenderer("SVG")},function(){var r="math-output-"+i.randstr({},64);return l=n.select("body").append("div").attr({id:r}).style({visibility:"hidden",position:"absolute"}).style({"font-size":e.fontSize+"px"}).text(t.replace(c,"\\lt ").replace(u,"\\gt ")),MathJax.Hub.Typeset(l.node())},function(){var e=n.select("body").select("#MathJax_SVG_glyphs");if(l.select(".MathJax_SVG").empty()||!l.select("svg").node())i.log("There was an error in the tex syntax.",t),r();else{var o=l.select("svg").node().getBoundingClientRect();r(l.select(".MathJax_SVG"),e,o)}if(l.remove(),"SVG"!==a)return MathJax.Hub.setRenderer(a)},function(){return void 0!==s&&(MathJax.Hub.processSectionDelay=s),MathJax.Hub.Config(o)})}(C[2],a,function(n,i,a){L.selectAll("svg."+z).remove(),L.selectAll("g."+z+"-group").remove();var o=n&&n.select("svg");if(!o||!o.node())return O(),void e();var l=L.append("g").classed(z+"-group",!0).attr({"pointer-events":"none","data-unformatted":S,"data-math":"Y"});l.node().appendChild(o.node()),i&&i.node()&&o.node().insertBefore(i.node().cloneNode(!0),o.node().firstChild),o.attr({class:z,height:a.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var c=t.node().style.fill||"black";o.select("g").attr({fill:c,stroke:c});var u=s(o,"width"),h=s(o,"height"),f=+t.attr("x")-u*{start:0,middle:.5,end:1}[t.attr("text-anchor")||"start"],p=-(r||s(t,"height"))/4;"y"===z[0]?(l.attr({transform:"rotate("+[-90,+t.attr("x"),+t.attr("y")]+") translate("+[-u/2,p-h/2]+")"}),o.attr({x:+t.attr("x"),y:+t.attr("y")})):"l"===z[0]?o.attr({x:t.attr("x"),y:p-h/2}):"a"===z[0]&&0!==z.indexOf("atitle")?o.attr({x:0,y:p}):o.attr({x:f,y:+t.attr("y")+p-h/2}),T&&T.call(t,l),e(l)})})):O(),t}function O(){L.empty()||(z=t.attr("class")+"-math",L.select("svg."+z).remove()),t.text("").style("white-space","pre"),function(t,e){e=e.replace(v," ");var r,s=!1,l=[],c=-1;function u(){c++;var e=document.createElementNS(a.svg,"tspan");n.select(e).attr({class:"line",dy:c*o+"em"}),t.appendChild(e),r=e;var i=l;if(l=[{node:e}],i.length>1)for(var s=1;s<i.length;s++)T(i[s])}function T(t){var e,i=t.type,o={};if("a"===i){e="a";var s=t.target,c=t.href,u=t.popup;c&&(o={"xlink:xlink:show":"_blank"===s||"_"!==s.charAt(0)?"new":"replace",target:s,"xlink:xlink:href":c},u&&(o.onclick='window.open(this.href.baseVal,this.target.baseVal,"'+u+'");return false;'))}else e="tspan";t.style&&(o.style=t.style);var h=document.createElementNS(a.svg,e);if("sup"===i||"sub"===i){S(r,d),r.appendChild(h);var g=document.createElementNS(a.svg,"tspan");S(g,d),n.select(g).attr("dy",p[i]),o.dy=f[i],r.appendChild(h),r.appendChild(g)}else r.appendChild(h);n.select(h).attr(o),r=t.node=h,l.push(t)}function S(t,e){t.appendChild(document.createTextNode(e))}function C(t){if(1!==l.length){var n=l.pop();t!==n.type&&i.log("Start tag <"+n.type+"> doesnt match end tag <"+t+">. Pretending it did match.",e),r=l[l.length-1].node}else i.log("Ignoring unexpected end tag </"+t+">.",e)}x.test(e)?u():(r=t,l=[{node:t}]);for(var L=e.split(m),z=0;z<L.length;z++){var O=L[z],I=O.match(y),D=I&&I[2].toLowerCase(),P=h[D];if("br"===D)u();else if(void 0===P)S(r,E(O));else if(I[1])C(D);else{var R=I[4],F={type:D},B=A(R,b);if(B?(B=B.replace(M,"$1 fill:"),P&&(B+=";"+P)):P&&(B=P),B&&(F.style=B),"a"===D){s=!0;var N=A(R,_);if(N){var j=document.createElement("a");j.href=N,-1!==g.indexOf(j.protocol)&&(F.href=encodeURI(decodeURI(N)),F.target=A(R,w)||"_blank",F.popup=A(R,k))}}T(F)}}return s}(t.node(),S)&&t.style("pointer-events","all"),r.positionText(t),T&&T.call(t)}};var c=/(<|&lt;|&#60;)/g,u=/(>|&gt;|&#62;)/g;var h={sup:"font-size:70%",sub:"font-size:70%",b:"font-weight:bold",i:"font-style:italic",a:"cursor:pointer",span:"",em:"font-style:italic;font-weight:bold"},f={sub:"0.3em",sup:"-0.6em"},p={sub:"-0.21em",sup:"0.42em"},d="\u200b",g=["http:","https:","mailto:","",void 0,":"],v=/(\r\n?|\n)/g,m=/(<[^<>]*>)/,y=/<(\/?)([^ >]*)(\s+(.*))?>/i,x=/<br(\s+.*)?>/i,b=/(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i,_=/(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i,w=/(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i,k=/(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;function A(t,e){if(!t)return null;var r=t.match(e),n=r&&(r[3]||r[4]);return n&&E(n)}var M=/(^|;)\s*color:/;r.plainText=function(t,e){for(var r=void 0!==(e=e||{}).len&&-1!==e.len?e.len:1/0,n=void 0!==e.allowedTags?e.allowedTags:["br"],i="...".length,a=t.split(m),o=[],s="",l=0,c=0;c<a.length;c++){var u=a[c],h=u.match(y),f=h&&h[2].toLowerCase();if(f)-1!==n.indexOf(f)&&(o.push(u),s=f);else{var p=u.length;if(l+p<r)o.push(u),l+=p;else if(l<r){var d=r-l;s&&("br"!==s||d<=i||p<=i)&&o.pop(),r>i?o.push(u.substr(0,d-i)+"..."):o.push(u.substr(0,d));break}s=""}}return o.join("")};var T={mu:"\u03bc",amp:"&",lt:"<",gt:">",nbsp:"\xa0",times:"\xd7",plusmn:"\xb1",deg:"\xb0"},S=/&(#\d+|#x[\da-fA-F]+|[a-z]+);/g;function E(t){return t.replace(S,function(t,e){return("#"===e.charAt(0)?function(t){if(t>1114111)return;var e=String.fromCodePoint;if(e)return e(t);var r=String.fromCharCode;return t<=65535?r(t):r(55232+(t>>10),t%1024+56320)}("x"===e.charAt(1)?parseInt(e.substr(2),16):parseInt(e.substr(1),10)):T[e])||t})}function C(t,e,r){var n,i,a,o=r.horizontalAlign,s=r.verticalAlign||"top",l=t.node().getBoundingClientRect(),c=e.node().getBoundingClientRect();return i="bottom"===s?function(){return l.bottom-n.height}:"middle"===s?function(){return l.top+(l.height-n.height)/2}:function(){return l.top},a="right"===o?function(){return l.right-n.width}:"center"===o?function(){return l.left+(l.width-n.width)/2}:function(){return l.left},function(){return n=this.node().getBoundingClientRect(),this.style({top:i()-c.top+"px",left:a()-c.left+"px","z-index":1e3}),this}}r.convertEntities=E,r.lineCount=function(t){return t.selectAll("tspan.line").size()||1},r.positionText=function(t,e,r){return t.each(function(){var t=n.select(this);function i(e,r){return void 0===r?null===(r=t.attr(e))&&(t.attr(e,0),r=0):t.attr(e,r),r}var a=i("x",e),o=i("y",r);"text"===this.nodeName&&t.selectAll("tspan.line").attr({x:a,y:o})})},r.makeEditable=function(t,e){var r=e.gd,i=e.delegate,a=n.dispatch("edit","input","cancel"),o=i||t;if(t.style({"pointer-events":i?"none":"all"}),1!==t.size())throw new Error("boo");function s(){!function(){var i=n.select(r).select(".svg-container"),o=i.append("div"),s=t.node().style,c=parseFloat(s.fontSize||12),u=e.text;void 0===u&&(u=t.attr("data-unformatted"));o.classed("plugin-editable editable",!0).style({position:"absolute","font-family":s.fontFamily||"Arial","font-size":c,color:e.fill||s.fill||"black",opacity:1,"background-color":e.background||"transparent",outline:"#ffffff33 1px solid",margin:[-c/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(u).call(C(t,i,e)).on("blur",function(){r._editing=!1,t.text(this.textContent).style({opacity:1});var e,i=n.select(this).attr("class");(e=i?"."+i.split(" ")[0]+"-math-group":"[class*=-math-group]")&&n.select(t.node().parentNode).select(e).style({opacity:0});var o=this.textContent;n.select(this).transition().duration(0).remove(),n.select(document).on("mouseup",null),a.edit.call(t,o)}).on("focus",function(){var t=this;r._editing=!0,n.select(document).on("mouseup",function(){if(n.event.target===t)return!1;document.activeElement===o.node()&&o.node().blur()})}).on("keyup",function(){27===n.event.which?(r._editing=!1,t.style({opacity:1}),n.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),a.cancel.call(t,this.textContent)):(a.input.call(t,this.textContent),n.select(this).call(C(t,i,e)))}).on("keydown",function(){13===n.event.which&&this.blur()}).call(l)}(),t.style({opacity:0});var i,s=o.attr("class");(i=s?"."+s.split(" ")[0]+"-math-group":"[class*=-math-group]")&&n.select(t.node().parentNode).select(i).style({opacity:0})}function l(t){var e=t.node(),r=document.createRange();r.selectNodeContents(e);var n=window.getSelection();n.removeAllRanges(),n.addRange(r),e.focus()}return e.immediate?s():o.on("click",s),n.rebind(t,a,"on")}},{"../constants/alignment":669,"../constants/xmlns_namespaces":675,"../lib":697,d3:151}],722:[function(t,e,r){"use strict";var n={};function i(t){t&&null!==t.timer&&(clearTimeout(t.timer),t.timer=null)}r.throttle=function(t,e,r){var a=n[t],o=Date.now();if(!a){for(var s in n)n[s].ts<o-6e4&&delete n[s];a=n[t]={ts:0,timer:null}}function l(){r(),a.ts=Date.now(),a.onDone&&(a.onDone(),a.onDone=null)}i(a),o>a.ts+e?l():a.timer=setTimeout(function(){l(),a.timer=null},e)},r.done=function(t){var e=n[t];return e&&e.timer?new Promise(function(t){var r=e.onDone;e.onDone=function(){r&&r(),t(),e.onDone=null}}):Promise.resolve()},r.clear=function(t){if(t)i(n[t]),delete n[t];else for(var e in n)r.clear(e)}},{}],723:[function(t,e,r){"use strict";var n=t("fast-isnumeric");e.exports=function(t,e){if(t>0)return Math.log(t)/Math.LN10;var r=Math.log(Math.min(e[0],e[1]))/Math.LN10;return n(r)||(r=Math.log(Math.max(e[0],e[1]))/Math.LN10-6),r}},{"fast-isnumeric":218}],724:[function(t,e,r){"use strict";var n=e.exports={},i=t("../plots/geo/constants").locationmodeToLayer,a=t("topojson-client").feature;n.getTopojsonName=function(t){return[t.scope.replace(/ /g,"-"),"_",t.resolution.toString(),"m"].join("")},n.getTopojsonPath=function(t,e){return t+e+".json"},n.getTopojsonFeatures=function(t,e){var r=i[t.locationmode],n=e.objects[r];return a(e,n).features}},{"../plots/geo/constants":773,"topojson-client":521}],725:[function(t,e,r){"use strict";e.exports={moduleType:"locale",name:"en-US",dictionary:{"Click to enter Colorscale title":"Click to enter Colorscale title"},format:{date:"%m/%d/%Y"}}},{}],726:[function(t,e,r){"use strict";e.exports={moduleType:"locale",name:"en",dictionary:{"Click to enter Colorscale title":"Click to enter Colourscale title"},format:{days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],periods:["AM","PM"],dateTime:"%a %b %e %X %Y",date:"%d/%m/%Y",time:"%H:%M:%S",decimal:".",thousands:",",grouping:[3],currency:["$",""],year:"%Y",month:"%b %Y",dayMonth:"%b %-d",dayMonthYear:"%b %-d, %Y"}}},{}],727:[function(t,e,r){"use strict";var n=t("../registry");e.exports=function(t){for(var e,r,i=n.layoutArrayContainers,a=n.layoutArrayRegexes,o=t.split("[")[0],s=0;s<a.length;s++)if((r=t.match(a[s]))&&0===r.index){e=r[0];break}if(e||(e=i[i.indexOf(o)]),!e)return!1;var l=t.substr(e.length);return l?!!(r=l.match(/^\[(0|[1-9][0-9]*)\](\.(.+))?$/))&&{array:e,index:Number(r[1]),property:r[3]||""}:{array:e,index:"",property:""}}},{"../registry":826}],728:[function(t,e,r){"use strict";var n=t("../lib"),i=n.extendFlat,a=n.isPlainObject,o={valType:"flaglist",extras:["none"],flags:["calc","clearAxisTypes","plot","style","markerSize","colorbars"]},s={valType:"flaglist",extras:["none"],flags:["calc","plot","legend","ticks","axrange","layoutstyle","modebar","camera","arraydraw"]},l=o.flags.slice().concat(["fullReplot"]),c=s.flags.slice().concat("layoutReplot");function u(t){for(var e={},r=0;r<t.length;r++)e[t[r]]=!1;return e}function h(t,e,r){var n=i({},t);for(var o in n){var s=n[o];a(s)&&(n[o]=f(s,e,r,o))}return"from-root"===r&&(n.editType=e),n}function f(t,e,r,n){if(t.valType){var a=i({},t);if(a.editType=e,Array.isArray(t.items)){a.items=new Array(t.items.length);for(var o=0;o<t.items.length;o++)a.items[o]=f(t.items[o],e,"from-root")}return a}return h(t,e,"_"===n.charAt(0)?"nested":"from-root")}e.exports={traces:o,layout:s,traceFlags:function(){return u(l)},layoutFlags:function(){return u(c)},update:function(t,e){var r=e.editType;if(r&&"none"!==r)for(var n=r.split("+"),i=0;i<n.length;i++)t[n[i]]=!0},overrideAll:h}},{"../lib":697}],729:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("gl-mat4/fromQuat"),a=t("../registry"),o=t("../lib"),s=t("../plots/plots"),l=t("../plots/cartesian/axis_ids"),c=l.cleanId,u=l.getFromTrace,h=t("../components/color");function f(t,e){var r=t[e],n=e.charAt(0);r&&"paper"!==r&&(t[e]=c(r,n))}function p(t){function e(e,r){var n=t[e],i=t.title&&t.title[r];n&&!i&&(t.title||(t.title={}),t.title[r]=t[e],delete t[e])}t&&("string"!=typeof t.title&&"number"!=typeof t.title||(t.title={text:t.title}),e("titlefont","font"),e("titleposition","position"),e("titleside","side"),e("titleoffset","offset"))}function d(t){if(!o.isPlainObject(t))return!1;var e=t.name;return delete t.name,delete t.showlegend,("string"==typeof e||"number"==typeof e)&&String(e)}function g(t,e,r,n){if(r&&!n)return t;if(n&&!r)return e;if(!t.trim())return e;if(!e.trim())return t;var i,a=Math.min(t.length,e.length);for(i=0;i<a&&t.charAt(i)===e.charAt(i);i++);return t.substr(0,i).trim()}function v(t){var e="middle",r="center";return"string"==typeof t&&(-1!==t.indexOf("top")?e="top":-1!==t.indexOf("bottom")&&(e="bottom"),-1!==t.indexOf("left")?r="left":-1!==t.indexOf("right")&&(r="right")),e+" "+r}function m(t,e){return e in t&&"object"==typeof t[e]&&0===Object.keys(t[e]).length}r.clearPromiseQueue=function(t){Array.isArray(t._promises)&&t._promises.length>0&&o.log("Clearing previous rejected promises from queue."),t._promises=[]},r.cleanLayout=function(t){var e,n;t||(t={}),t.xaxis1&&(t.xaxis||(t.xaxis=t.xaxis1),delete t.xaxis1),t.yaxis1&&(t.yaxis||(t.yaxis=t.yaxis1),delete t.yaxis1),t.scene1&&(t.scene||(t.scene=t.scene1),delete t.scene1);var a=(s.subplotsRegistry.cartesian||{}).attrRegex,l=(s.subplotsRegistry.polar||{}).attrRegex,u=(s.subplotsRegistry.ternary||{}).attrRegex,d=(s.subplotsRegistry.gl3d||{}).attrRegex,g=Object.keys(t);for(e=0;e<g.length;e++){var v=g[e];if(a&&a.test(v)){var y=t[v];y.anchor&&"free"!==y.anchor&&(y.anchor=c(y.anchor)),y.overlaying&&(y.overlaying=c(y.overlaying)),y.type||(y.isdate?y.type="date":y.islog?y.type="log":!1===y.isdate&&!1===y.islog&&(y.type="linear")),"withzero"!==y.autorange&&"tozero"!==y.autorange||(y.autorange=!0,y.rangemode="tozero"),delete y.islog,delete y.isdate,delete y.categories,m(y,"domain")&&delete y.domain,void 0!==y.autotick&&(void 0===y.tickmode&&(y.tickmode=y.autotick?"auto":"linear"),delete y.autotick),p(y)}else if(l&&l.test(v)){p(t[v].radialaxis)}else if(u&&u.test(v)){var x=t[v];p(x.aaxis),p(x.baxis),p(x.caxis)}else if(d&&d.test(v)){var b=t[v],_=b.cameraposition;if(Array.isArray(_)&&4===_[0].length){var w=_[0],k=_[1],A=_[2],M=i([],w),T=[];for(n=0;n<3;++n)T[n]=k[n]+A*M[2+4*n];b.camera={eye:{x:T[0],y:T[1],z:T[2]},center:{x:k[0],y:k[1],z:k[2]},up:{x:0,y:0,z:1}},delete b.cameraposition}p(b.xaxis),p(b.yaxis),p(b.zaxis)}}var S=Array.isArray(t.annotations)?t.annotations.length:0;for(e=0;e<S;e++){var E=t.annotations[e];o.isPlainObject(E)&&(E.ref&&("paper"===E.ref?(E.xref="paper",E.yref="paper"):"data"===E.ref&&(E.xref="x",E.yref="y"),delete E.ref),f(E,"xref"),f(E,"yref"))}var C=Array.isArray(t.shapes)?t.shapes.length:0;for(e=0;e<C;e++){var L=t.shapes[e];o.isPlainObject(L)&&(f(L,"xref"),f(L,"yref"))}var z=t.legend;return z&&(z.x>3?(z.x=1.02,z.xanchor="left"):z.x<-2&&(z.x=-.02,z.xanchor="right"),z.y>3?(z.y=1.02,z.yanchor="bottom"):z.y<-2&&(z.y=-.02,z.yanchor="top")),p(t),"rotate"===t.dragmode&&(t.dragmode="orbit"),h.clean(t),t.template&&t.template.layout&&r.cleanLayout(t.template.layout),t},r.cleanData=function(t){for(var e=0;e<t.length;e++){var n,i=t[e];if("histogramy"===i.type&&"xbins"in i&&!("ybins"in i)&&(i.ybins=i.xbins,delete i.xbins),i.error_y&&"opacity"in i.error_y){var l=h.defaults,u=i.error_y.color||(a.traceIs(i,"bar")?h.defaultLine:l[e%l.length]);i.error_y.color=h.addOpacity(h.rgb(u),h.opacity(u)*i.error_y.opacity),delete i.error_y.opacity}if("bardir"in i&&("h"!==i.bardir||!a.traceIs(i,"bar")&&"histogram"!==i.type.substr(0,9)||(i.orientation="h",r.swapXYData(i)),delete i.bardir),"histogramy"===i.type&&r.swapXYData(i),"histogramx"!==i.type&&"histogramy"!==i.type||(i.type="histogram"),"scl"in i&&!("colorscale"in i)&&(i.colorscale=i.scl,delete i.scl),"reversescl"in i&&!("reversescale"in i)&&(i.reversescale=i.reversescl,delete i.reversescl),i.xaxis&&(i.xaxis=c(i.xaxis,"x")),i.yaxis&&(i.yaxis=c(i.yaxis,"y")),a.traceIs(i,"gl3d")&&i.scene&&(i.scene=s.subplotsRegistry.gl3d.cleanId(i.scene)),!a.traceIs(i,"pie")&&!a.traceIs(i,"bar"))if(Array.isArray(i.textposition))for(n=0;n<i.textposition.length;n++)i.textposition[n]=v(i.textposition[n]);else i.textposition&&(i.textposition=v(i.textposition));var f=a.getModule(i);if(f&&f.colorbar){var y=f.colorbar.container,x=y?i[y]:i;x&&x.colorscale&&("YIGnBu"===x.colorscale&&(x.colorscale="YlGnBu"),"YIOrRd"===x.colorscale&&(x.colorscale="YlOrRd"))}if("surface"===i.type&&o.isPlainObject(i.contours)){var b=["x","y","z"];for(n=0;n<b.length;n++){var _=i.contours[b[n]];o.isPlainObject(_)&&(_.highlightColor&&(_.highlightcolor=_.highlightColor,delete _.highlightColor),_.highlightWidth&&(_.highlightwidth=_.highlightWidth,delete _.highlightWidth))}}if("candlestick"===i.type||"ohlc"===i.type){var w=!1!==(i.increasing||{}).showlegend,k=!1!==(i.decreasing||{}).showlegend,A=d(i.increasing),M=d(i.decreasing);if(!1!==A&&!1!==M){var T=g(A,M,w,k);T&&(i.name=T)}else!A&&!M||i.name||(i.name=A||M)}if(Array.isArray(i.transforms)){var S=i.transforms;for(n=0;n<S.length;n++){var E=S[n];if(o.isPlainObject(E))switch(E.type){case"filter":E.filtersrc&&(E.target=E.filtersrc,delete E.filtersrc),E.calendar&&(E.valuecalendar||(E.valuecalendar=E.calendar),delete E.calendar);break;case"groupby":if(E.styles=E.styles||E.style,E.styles&&!Array.isArray(E.styles)){var C=E.styles,L=Object.keys(C);E.styles=[];for(var z=0;z<L.length;z++)E.styles.push({target:L[z],value:C[L[z]]})}}}}m(i,"line")&&delete i.line,"marker"in i&&(m(i.marker,"line")&&delete i.marker.line,m(i,"marker")&&delete i.marker),h.clean(i),i.autobinx&&(delete i.autobinx,delete i.xbins),i.autobiny&&(delete i.autobiny,delete i.ybins),p(i),i.colorbar&&p(i.colorbar),i.marker&&i.marker.colorbar&&p(i.marker.colorbar),i.line&&i.line.colorbar&&p(i.line.colorbar),i.aaxis&&p(i.aaxis),i.baxis&&p(i.baxis)}},r.swapXYData=function(t){var e;if(o.swapAttrs(t,["?","?0","d?","?bins","nbins?","autobin?","?src","error_?"]),Array.isArray(t.z)&&Array.isArray(t.z[0])&&(t.transpose?delete t.transpose:t.transpose=!0),t.error_x&&t.error_y){var r=t.error_y,n="copy_ystyle"in r?r.copy_ystyle:!(r.color||r.thickness||r.width);o.swapAttrs(t,["error_?.copy_ystyle"]),n&&o.swapAttrs(t,["error_?.color","error_?.thickness","error_?.width"])}if("string"==typeof t.hoverinfo){var i=t.hoverinfo.split("+");for(e=0;e<i.length;e++)"x"===i[e]?i[e]="y":"y"===i[e]&&(i[e]="x");t.hoverinfo=i.join("+")}},r.coerceTraceIndices=function(t,e){if(n(e))return[e];if(!Array.isArray(e)||!e.length)return t.data.map(function(t,e){return e});if(Array.isArray(e)){for(var r=[],i=0;i<e.length;i++)o.isIndex(e[i],t.data.length)?r.push(e[i]):o.warn("trace index (",e[i],") is not a number or is out of bounds");return r}return e},r.manageArrayContainers=function(t,e,r){var i=t.obj,a=t.parts,s=a.length,l=a[s-1],c=n(l);if(c&&null===e){var u=a.slice(0,s-1).join(".");o.nestedProperty(i,u).get().splice(l,1)}else c&&void 0===t.get()?(void 0===t.get()&&(r[t.astr]=null),t.set(e)):t.set(e)};var y=/(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/;function x(t){var e=t.search(y);if(e>0)return t.substr(0,e)}r.hasParent=function(t,e){for(var r=x(e);r;){if(r in t)return!0;r=x(r)}return!1};var b=["x","y","z"];r.clearAxisTypes=function(t,e,r){for(var n=0;n<e.length;n++)for(var i=t._fullData[n],a=0;a<3;a++){var s=u(t,i,b[a]);if(s&&"log"!==s.type){var l=s._name,c=s._id.substr(1);if("scene"===c.substr(0,5)){if(void 0!==r[c])continue;l=c+"."+l}var h=l+".type";void 0===r[l]&&void 0===r[h]&&o.nestedProperty(t.layout,h).set(null)}}}},{"../components/color":574,"../lib":697,"../plots/cartesian/axis_ids":748,"../plots/plots":807,"../registry":826,"fast-isnumeric":218,"gl-mat4/fromQuat":255}],730:[function(t,e,r){"use strict";var n=t("./plot_api");r.plot=n.plot,r.newPlot=n.newPlot,r.restyle=n.restyle,r.relayout=n.relayout,r.redraw=n.redraw,r.update=n.update,r._guiRestyle=n._guiRestyle,r._guiRelayout=n._guiRelayout,r._guiUpdate=n._guiUpdate,r._storeDirectGUIEdit=n._storeDirectGUIEdit,r.react=n.react,r.extendTraces=n.extendTraces,r.prependTraces=n.prependTraces,r.addTraces=n.addTraces,r.deleteTraces=n.deleteTraces,r.moveTraces=n.moveTraces,r.purge=n.purge,r.addFrames=n.addFrames,r.deleteFrames=n.deleteFrames,r.animate=n.animate,r.setPlotConfig=n.setPlotConfig,r.toImage=t("./to_image"),r.validate=t("./validate"),r.downloadImage=t("../snapshot/download");var i=t("./template_api");r.makeTemplate=i.makeTemplate,r.validateTemplate=i.validateTemplate},{"../snapshot/download":828,"./plot_api":732,"./template_api":737,"./to_image":738,"./validate":739}],731:[function(t,e,r){"use strict";var n=t("../lib/is_plain_object"),i=t("../lib/noop"),a=t("../lib/loggers"),o=t("../lib/search").sorterAsc,s=t("../registry");r.containerArrayMatch=t("./container_array_match");var l=r.isAddVal=function(t){return"add"===t||n(t)},c=r.isRemoveVal=function(t){return null===t||"remove"===t};r.applyContainerArrayChanges=function(t,e,r,n,u){var h=e.astr,f=s.getComponentMethod(h,"supplyLayoutDefaults"),p=s.getComponentMethod(h,"draw"),d=s.getComponentMethod(h,"drawOne"),g=n.replot||n.recalc||f===i||p===i,v=t.layout,m=t._fullLayout;if(r[""]){Object.keys(r).length>1&&a.warn("Full array edits are incompatible with other edits",h);var y=r[""][""];if(c(y))e.set(null);else{if(!Array.isArray(y))return a.warn("Unrecognized full array edit value",h,y),!0;e.set(y)}return!g&&(f(v,m),p(t),!0)}var x,b,_,w,k,A,M,T,S=Object.keys(r).map(Number).sort(o),E=e.get(),C=E||[],L=u(m,h).get(),z=[],O=-1,I=C.length;for(x=0;x<S.length;x++)if(w=r[_=S[x]],k=Object.keys(w),A=w[""],M=l(A),_<0||_>C.length-(M?0:1))a.warn("index out of range",h,_);else if(void 0!==A)k.length>1&&a.warn("Insertion & removal are incompatible with edits to the same index.",h,_),c(A)?z.push(_):M?("add"===A&&(A={}),C.splice(_,0,A),L&&L.splice(_,0,{})):a.warn("Unrecognized full object edit value",h,_,A),-1===O&&(O=_);else for(b=0;b<k.length;b++)T=h+"["+_+"].",u(C[_],k[b],T).set(w[k[b]]);for(x=z.length-1;x>=0;x--)C.splice(z[x],1),L&&L.splice(z[x],1);if(C.length?E||e.set(C):e.set(null),g)return!1;if(f(v,m),d!==i){var D;if(-1===O)D=S;else{for(I=Math.max(C.length,I),D=[],x=0;x<S.length&&!((_=S[x])>=O);x++)D.push(_);for(x=O;x<I;x++)D.push(x)}for(x=0;x<D.length;x++)d(t,D[x])}else p(t);return!0}},{"../lib/is_plain_object":698,"../lib/loggers":701,"../lib/noop":706,"../lib/search":716,"../registry":826,"./container_array_match":727}],732:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("has-hover"),o=t("../lib"),s=o.nestedProperty,l=t("../lib/events"),c=t("../lib/queue"),u=t("../registry"),h=t("./plot_schema"),f=t("../plots/plots"),p=t("../plots/polar/legacy"),d=t("../plots/cartesian/axes"),g=t("../components/drawing"),v=t("../components/color"),m=t("../components/colorbar/connect"),y=t("../plots/cartesian/graph_interact").initInteractions,x=t("../constants/xmlns_namespaces"),b=t("../lib/svg_text_utils"),_=t("../plots/cartesian/select").clearSelect,w=t("./plot_config").dfltConfig,k=t("./manage_arrays"),A=t("./helpers"),M=t("./subroutines"),T=t("./edit_types"),S=t("../plots/cartesian/constants").AX_NAME_PATTERN,E=0;function C(t){var e=t._fullLayout;e._redrawFromAutoMarginCount?e._redrawFromAutoMarginCount--:t.emit("plotly_afterplot")}function L(t,e){try{t._fullLayout._paper.style("background",e)}catch(t){o.error(t)}}function z(t,e){L(t,v.combine(e,"white"))}function O(t,e){if(!t._context){t._context=o.extendDeep({},w);var r=n.select("base");t._context._baseUrl=r.size()&&r.attr("href")?window.location.href.split("#")[0]:""}var i,s,l,c=t._context;if(e){for(s=Object.keys(e),i=0;i<s.length;i++)"editable"!==(l=s[i])&&"edits"!==l&&l in c&&("setBackground"===l&&"opaque"===e[l]?c[l]=z:c[l]=e[l]);e.plot3dPixelRatio&&!c.plotGlPixelRatio&&(c.plotGlPixelRatio=c.plot3dPixelRatio);var u=e.editable;if(void 0!==u)for(c.editable=u,s=Object.keys(c.edits),i=0;i<s.length;i++)c.edits[s[i]]=u;if(e.edits)for(s=Object.keys(e.edits),i=0;i<s.length;i++)(l=s[i])in c.edits&&(c.edits[l]=e.edits[l]);c._exportedPlot=e._exportedPlot}c.staticPlot&&(c.editable=!1,c.edits={},c.autosizable=!1,c.scrollZoom=!1,c.doubleClick=!1,c.showTips=!1,c.showLink=!1,c.displayModeBar=!1),"hover"!==c.displayModeBar||a||(c.displayModeBar=!0),"transparent"!==c.setBackground&&"function"==typeof c.setBackground||(c.setBackground=L),c._hasZeroHeight=c._hasZeroHeight||0===t.clientHeight,c._hasZeroWidth=c._hasZeroWidth||0===t.clientWidth;var h=c.scrollZoom,f=c._scrollZoom={};if(!0===h)f.cartesian=1,f.gl3d=1,f.geo=1,f.mapbox=1;else if("string"==typeof h){var p=h.split("+");for(i=0;i<p.length;i++)f[p[i]]=1}else!1!==h&&(f.gl3d=1,f.geo=1,f.mapbox=1)}function I(t,e){var r,n,i=e+1,a=[];for(r=0;r<t.length;r++)(n=t[r])<0?a.push(i+n):a.push(n);return a}function D(t,e,r){var n,i;for(n=0;n<e.length;n++){if((i=e[n])!==parseInt(i,10))throw new Error("all values in "+r+" must be integers");if(i>=t.data.length||i<-t.data.length)throw new Error(r+" must be valid indices for gd.data.");if(e.indexOf(i,n+1)>-1||i>=0&&e.indexOf(-t.data.length+i)>-1||i<0&&e.indexOf(t.data.length+i)>-1)throw new Error("each index in "+r+" must be unique.")}}function P(t,e,r){if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if("undefined"==typeof e)throw new Error("currentIndices is a required argument.");if(Array.isArray(e)||(e=[e]),D(t,e,"currentIndices"),"undefined"==typeof r||Array.isArray(r)||(r=[r]),"undefined"!=typeof r&&D(t,r,"newIndices"),"undefined"!=typeof r&&e.length!==r.length)throw new Error("current and new indices must be of equal length.")}function R(t,e,r,n,a){!function(t,e,r,n){var i=o.isPlainObject(n);if(!Array.isArray(t.data))throw new Error("gd.data must be an array");if(!o.isPlainObject(e))throw new Error("update must be a key:value object");if("undefined"==typeof r)throw new Error("indices must be an integer or array of integers");for(var a in D(t,r,"indices"),e){if(!Array.isArray(e[a])||e[a].length!==r.length)throw new Error("attribute "+a+" must be an array of length equal to indices array length");if(i&&(!(a in n)||!Array.isArray(n[a])||n[a].length!==e[a].length))throw new Error("when maxPoints is set as a key:value object it must contain a 1:1 corrispondence with the keys and number of traces in the update object")}}(t,e,r,n);for(var l=function(t,e,r,n){var a,l,c,u,h,f=o.isPlainObject(n),p=[];for(var d in Array.isArray(r)||(r=[r]),r=I(r,t.data.length-1),e)for(var g=0;g<r.length;g++){if(a=t.data[r[g]],l=(c=s(a,d)).get(),u=e[d][g],!o.isArrayOrTypedArray(u))throw new Error("attribute: "+d+" index: "+g+" must be an array");if(!o.isArrayOrTypedArray(l))throw new Error("cannot extend missing or non-array attribute: "+d);if(l.constructor!==u.constructor)throw new Error("cannot extend array with an array of a different type: "+d);h=f?n[d][g]:n,i(h)||(h=-1),p.push({prop:c,target:l,insert:u,maxp:Math.floor(h)})}return p}(t,e,r,n),c={},u={},h=0;h<l.length;h++){var f=l[h].prop,p=l[h].maxp,d=a(l[h].target,l[h].insert,p);f.set(d[0]),Array.isArray(c[f.astr])||(c[f.astr]=[]),c[f.astr].push(d[1]),Array.isArray(u[f.astr])||(u[f.astr]=[]),u[f.astr].push(l[h].target.length)}return{update:c,maxPoints:u}}function F(t,e){var r=new t.constructor(t.length+e.length);return r.set(t),r.set(e,t.length),r}function B(t,e,n,i){t=o.getGraphDiv(t),A.clearPromiseQueue(t);var a={};if("string"==typeof e)a[e]=n;else{if(!o.isPlainObject(e))return o.warn("Restyle fail.",e,n,i),Promise.reject();a=o.extendFlat({},e),void 0===i&&(i=n)}Object.keys(a).length&&(t.changed=!0);var s=A.coerceTraceIndices(t,i),l=U(t,a,s),u=l.flags;u.calc&&(t.calcdata=void 0),u.clearAxisTypes&&A.clearAxisTypes(t,s,{});var h=[];u.fullReplot?h.push(r.plot):(h.push(f.previousPromises),f.supplyDefaults(t),u.markerSize&&(f.doCalcdata(t),Y(h)),u.style&&h.push(M.doTraceStyle),u.colorbars&&h.push(M.doColorBars),h.push(C)),h.push(f.rehover),c.add(t,B,[t,l.undoit,l.traces],B,[t,l.redoit,l.traces]);var p=o.syncOrAsync(h,t);return p&&p.then||(p=Promise.resolve()),p.then(function(){return t.emit("plotly_restyle",l.eventData),t})}function N(t){return void 0===t?null:t}function j(t,e){return e?function(e,r,n){var i=s(e,r),a=i.set;return i.set=function(e){V((n||"")+r,i.get(),e,t),a(e)},i}:s}function V(t,e,r,n){if(Array.isArray(e)||Array.isArray(r))for(var i=Array.isArray(e)?e:[],a=Array.isArray(r)?r:[],s=Math.max(i.length,a.length),l=0;l<s;l++)V(t+"["+l+"]",i[l],a[l],n);else if(o.isPlainObject(e)||o.isPlainObject(r)){var c=o.isPlainObject(e)?e:{},u=o.isPlainObject(r)?r:{},h=o.extendFlat({},c,u);for(var f in h)V(t+"."+f,c[f],u[f],n)}else void 0===n[t]&&(n[t]=N(e))}function U(t,e,r){var n,i=t._fullLayout,a=t._fullData,l=t.data,c=i._guiEditing,p=j(i._preGUI,c),g=o.extendDeepAll({},e);q(e);var v,m=T.traceFlags(),y={},x={};function b(){return r.map(function(){})}function _(t){var e=d.id2name(t);-1===v.indexOf(e)&&v.push(e)}function w(t){return"LAYOUT"+t+".autorange"}function k(t){return"LAYOUT"+t+".range"}function M(t){for(var e=t;e<a.length;e++)if(a[e]._input===l[t])return a[e]}function S(n,a,o){if(Array.isArray(n))n.forEach(function(t){S(t,a,o)});else if(!(n in e||A.hasParent(e,n))){var s;if("LAYOUT"===n.substr(0,6))s=p(t.layout,n.replace("LAYOUT",""));else{var u=r[o];s=j(i._tracePreGUI[M(u)._fullInput.uid],c)(l[u],n)}n in x||(x[n]=b()),void 0===x[n][o]&&(x[n][o]=N(s.get())),void 0!==a&&s.set(a)}}function E(t){return function(e){return a[e][t]}}function C(t){return function(e,n){return!1===e?a[r[n]][t]:null}}for(var L in e){if(A.hasParent(e,L))throw new Error("cannot set "+L+" and a parent attribute simultaneously");var z,O,I,D,P,R,F=e[L];if("autobinx"!==L&&"autobiny"!==L||(L=L.charAt(L.length-1)+"bins",F=Array.isArray(F)?F.map(C(L)):!1===F?r.map(E(L)):null),y[L]=F,"LAYOUT"!==L.substr(0,6)){for(x[L]=b(),n=0;n<r.length;n++){if(z=l[r[n]],O=M(r[n]),D=(I=j(i._tracePreGUI[O._fullInput.uid],c)(z,L)).get(),void 0!==(P=Array.isArray(F)?F[n%F.length]:F)){var B=I.parts[I.parts.length-1],V=L.substr(0,L.length-B.length-1),U=V?V+".":"",H=V?s(O,V).get():O;if((R=h.getTraceValObject(O,I.parts))&&R.impliedEdits&&null!==P)for(var G in R.impliedEdits)S(o.relativeAttr(L,G),R.impliedEdits[G],n);else if("thicknessmode"!==B&&"lenmode"!==B||D===P||"fraction"!==P&&"pixels"!==P||!H){if("type"===L&&"pie"===P!=("pie"===D)){var Y="x",W="y";"bar"!==P&&"bar"!==D||"h"!==z.orientation||(Y="y",W="x"),o.swapAttrs(z,["?","?src"],"labels",Y),o.swapAttrs(z,["d?","?0"],"label",Y),o.swapAttrs(z,["?","?src"],"values",W),"pie"===D?(s(z,"marker.color").set(s(z,"marker.colors").get()),i._pielayer.selectAll("g.trace").remove()):u.traceIs(z,"cartesian")&&s(z,"marker.colors").set(s(z,"marker.color").get())}}else{var X=i._size,Z=H.orient,$="top"===Z||"bottom"===Z;if("thicknessmode"===B){var J=$?X.h:X.w;S(U+"thickness",H.thickness*("fraction"===P?1/J:J),n)}else{var K=$?X.w:X.h;S(U+"len",H.len*("fraction"===P?1/K:K),n)}}x[L][n]=N(D);if(-1!==["swapxy","swapxyaxes","orientation","orientationaxes"].indexOf(L)){if("orientation"===L){I.set(P);var Q=z.x&&!z.y?"h":"v";if((I.get()||Q)===O.orientation)continue}else"orientationaxes"===L&&(z.orientation={v:"h",h:"v"}[O.orientation]);A.swapXYData(z),m.calc=m.clearAxisTypes=!0}else-1!==f.dataArrayContainers.indexOf(I.parts[0])?(A.manageArrayContainers(I,P,x),m.calc=!0):(R?R.arrayOk&&!u.traceIs(O,"regl")&&(o.isArrayOrTypedArray(P)||o.isArrayOrTypedArray(D))?m.calc=!0:T.update(m,R):m.calc=!0,I.set(P))}}if(-1!==["swapxyaxes","orientationaxes"].indexOf(L)&&d.swap(t,r),"orientationaxes"===L){var tt=s(t.layout,"hovermode");"x"===tt.get()?tt.set("y"):"y"===tt.get()&&tt.set("x")}if(-1!==["orientation","type"].indexOf(L)){for(v=[],n=0;n<r.length;n++){var et=l[r[n]];u.traceIs(et,"cartesian")&&(_(et.xaxis||"x"),_(et.yaxis||"y"))}S(v.map(w),!0,0),S(v.map(k),[0,1],0)}}else I=p(t.layout,L.replace("LAYOUT","")),x[L]=[N(I.get())],I.set(Array.isArray(F)?F[0]:F),m.calc=!0}return(m.calc||m.plot)&&(m.fullReplot=!0),{flags:m,undoit:x,redoit:y,traces:r,eventData:o.extendDeepNoArrays([],[g,r])}}function q(t){var e,r,n,i=o.counterRegex("axis",".title",!1,!1),a=/colorbar\.title$/,s=Object.keys(t);for(e=0;e<s.length;e++)r=s[e],n=t[r],"title"!==r&&!i.test(r)&&!a.test(r)||"string"!=typeof n&&"number"!=typeof n?r.indexOf("titlefont")>-1?l(r,r.replace("titlefont","title.font")):r.indexOf("titleposition")>-1?l(r,r.replace("titleposition","title.position")):r.indexOf("titleside")>-1?l(r,r.replace("titleside","title.side")):r.indexOf("titleoffset")>-1&&l(r,r.replace("titleoffset","title.offset")):l(r,r.replace("title","title.text"));function l(e,r){t[r]=t[e],delete t[e]}}function H(t,e,r){if(t=o.getGraphDiv(t),A.clearPromiseQueue(t),t.framework&&t.framework.isPolar)return Promise.resolve(t);var n={};if("string"==typeof e)n[e]=r;else{if(!o.isPlainObject(e))return o.warn("Relayout fail.",e,r),Promise.reject();n=o.extendFlat({},e)}Object.keys(n).length&&(t.changed=!0);var i=$(t,n),a=i.flags;a.calc&&(t.calcdata=void 0);var s=[f.previousPromises];a.layoutReplot?s.push(M.layoutReplot):Object.keys(n).length&&(G(t,a,i)||f.supplyDefaults(t),a.legend&&s.push(M.doLegend),a.layoutstyle&&s.push(M.layoutStyles),a.axrange&&Y(s,i.rangesAltered),a.ticks&&s.push(M.doTicksRelayout),a.modebar&&s.push(M.doModeBar),a.camera&&s.push(M.doCamera),s.push(C)),s.push(f.rehover),c.add(t,H,[t,i.undoit],H,[t,i.redoit]);var l=o.syncOrAsync(s,t);return l&&l.then||(l=Promise.resolve(t)),l.then(function(){return t.emit("plotly_relayout",i.eventData),t})}function G(t,e,r){var n=t._fullLayout;if(!e.axrange)return!1;for(var i in e)if("axrange"!==i&&e[i])return!1;for(var a in r.rangesAltered){var o=d.id2name(a),s=t.layout[o],l=n[o];if(l.autorange=s.autorange,l.range=s.range.slice(),l.cleanRange(),l._matchGroup)for(var c in l._matchGroup)if(c!==a){var u=n[d.id2name(c)];u.autorange=l.autorange,u.range=l.range.slice(),u._input.range=l.range.slice()}}return!0}function Y(t,e){var r=e?function(t){var r=[],n=!0;for(var i in e){var a=d.getFromId(t,i);if(r.push(i),a._matchGroup)for(var o in a._matchGroup)e[o]||r.push(o);a.automargin&&(n=!1)}return d.draw(t,r,{skipTitle:n})}:function(t){return d.draw(t,"redraw")};t.push(function(t){var e=t._fullLayout._zoomlayer;e&&_(e)},M.doAutoRangeAndConstraints,r,M.drawData,M.finalDraw)}r.plot=function(t,e,i,a){var s;if(t=o.getGraphDiv(t),l.init(t),o.isPlainObject(e)){var c=e;e=c.data,i=c.layout,a=c.config,s=c.frames}if(!1===l.triggerHandler(t,"plotly_beforeplot",[e,i,a]))return Promise.reject();e||i||o.isPlotDiv(t)||o.warn("Calling Plotly.plot as if redrawing but this container doesn't yet have a plot.",t),O(t,a),i||(i={}),n.select(t).classed("js-plotly-plot",!0),g.makeTester(),Array.isArray(t._promises)||(t._promises=[]);var h=0===(t.data||[]).length&&Array.isArray(e);if(Array.isArray(e)&&(A.cleanData(e),h?t.data=e:t.data.push.apply(t.data,e),t.empty=!1),t.layout&&!h||(t.layout=A.cleanLayout(i)),t._dragging&&!t._transitioning)return t._replotPending=!0,Promise.reject();t._replotPending=!1,f.supplyDefaults(t);var v=t._fullLayout,x=v._has("cartesian");if(!v._has("polar")&&e&&e[0]&&e[0].r)return o.log("Legacy polar charts are deprecated!"),function(t,e,r){var i=n.select(t).selectAll(".plot-container").data([0]);i.enter().insert("div",":first-child").classed("plot-container plotly",!0);var a=i.selectAll(".svg-container").data([0]);a.enter().append("div").classed("svg-container",!0).style("position","relative"),a.html(""),e&&(t.data=e);r&&(t.layout=r);p.manager.fillLayout(t),a.style({width:t._fullLayout.width+"px",height:t._fullLayout.height+"px"}),t.framework=p.manager.framework(t),t.framework({data:t.data,layout:t.layout},a.node()),t.framework.setUndoPoint();var s=t.framework.svg(),l=1,c=t._fullLayout.title?t._fullLayout.title.text:"";""!==c&&c||(l=0);var u=function(){this.call(b.convertToTspans,t)},h=s.select(".title-group text").call(u);if(t._context.edits.titleText){var d=o._(t,"Click to enter Plot title");c&&c!==d||(l=.2,h.attr({"data-unformatted":d}).text(d).style({opacity:l}).on("mouseover.opacity",function(){n.select(this).transition().duration(100).style("opacity",1)}).on("mouseout.opacity",function(){n.select(this).transition().duration(1e3).style("opacity",0)}));var g=function(){this.call(b.makeEditable,{gd:t}).on("edit",function(e){t.framework({layout:{title:{text:e}}}),this.text(e).call(u),this.call(g)}).on("cancel",function(){var t=this.attr("data-unformatted");this.text(t).call(u)})};h.call(g)}return t._context.setBackground(t,t._fullLayout.paper_bgcolor),f.addLinks(t),Promise.resolve()}(t,e,i);v._replotting=!0,h&&lt(t),t.framework!==lt&&(t.framework=lt,lt(t)),g.initGradients(t),h&&d.saveShowSpikeInitial(t);var _=!t.calcdata||t.calcdata.length!==(t._fullData||[]).length;_&&f.doCalcdata(t);for(var w=0;w<t.calcdata.length;w++)t.calcdata[w][0].trace=t._fullData[w];t._context.responsive?t._responsiveChartHandler||(t._responsiveChartHandler=function(){f.resize(t)},window.addEventListener("resize",t._responsiveChartHandler)):o.clearResponsive(t);var k=JSON.stringify(v._size),T=0;function S(){var e,r,n,i=t.calcdata;for(f.clearAutoMarginIds(t),M.drawMarginPushers(t),d.allowAutoMargin(t),e=0;e<i.length;e++){var a=(n=(r=i[e])[0].trace)._module.colorbar;!0===n.visible&&a?m(t,r,a):f.autoMargin(t,"cb"+n.uid)}return f.doAutoMargin(t),f.previousPromises(t)}function E(){t._transitioning||(M.doAutoRangeAndConstraints(t),h&&d.saveRangeInitial(t),u.getComponentMethod("rangeslider","calcAutorange")(t))}var L=[f.previousPromises,function(){if(s)return r.addFrames(t,s)},function e(){for(var r=v._basePlotModules,n=0;n<r.length;n++)r[n].drawFramework&&r[n].drawFramework(t);if(!v._glcanvas&&v._has("gl")&&(v._glcanvas=v._glcontainer.selectAll(".gl-canvas").data([{key:"contextLayer",context:!0,pick:!1},{key:"focusLayer",context:!1,pick:!1},{key:"pickLayer",context:!1,pick:!0}],function(t){return t.key}),v._glcanvas.enter().append("canvas").attr("class",function(t){return"gl-canvas gl-canvas-"+t.key.replace("Layer","")}).style({position:"absolute",top:0,left:0,overflow:"visible","pointer-events":"none"})),v._glcanvas){v._glcanvas.attr("width",v.width).attr("height",v.height);var i=v._glcanvas.data()[0].regl;if(i&&(Math.floor(v.width)!==i._gl.drawingBufferWidth||Math.floor(v.height)!==i._gl.drawingBufferHeight)){var a="WebGL context buffer and canvas dimensions do not match due to browser/WebGL bug.";if(!T)return o.log(a+" Clearing graph and plotting again."),f.cleanPlot([],{},t._fullData,v),f.supplyDefaults(t),v=t._fullLayout,f.doCalcdata(t),T++,e();o.error(a)}}return"h"===v.modebar.orientation?v._modebardiv.style("height",null).style("width","100%"):v._modebardiv.style("width",null).style("height",v.height+"px"),f.previousPromises(t)},S,function(){if(JSON.stringify(v._size)!==k)return o.syncOrAsync([S,M.layoutStyles],t)}];x&&L.push(function(){if(_)return o.syncOrAsync([u.getComponentMethod("shapes","calcAutorange"),u.getComponentMethod("annotations","calcAutorange"),E],t);E()}),L.push(M.layoutStyles),x&&L.push(function(){return d.draw(t,h?"":"redraw")}),L.push(M.drawData,M.finalDraw,y,f.addLinks,f.rehover,f.doAutoMargin,f.previousPromises);var z=o.syncOrAsync(L,t);return z&&z.then||(z=Promise.resolve()),z.then(function(){return C(t),t})},r.setPlotConfig=function(t){return o.extendFlat(w,t)},r.redraw=function(t){if(t=o.getGraphDiv(t),!o.isPlotDiv(t))throw new Error("This element is not a Plotly plot: "+t);return A.cleanData(t.data),A.cleanLayout(t.layout),t.calcdata=void 0,r.plot(t).then(function(){return t.emit("plotly_redraw"),t})},r.newPlot=function(t,e,n,i){return t=o.getGraphDiv(t),f.cleanPlot([],{},t._fullData||[],t._fullLayout||{}),f.purge(t),r.plot(t,e,n,i)},r.extendTraces=function t(e,n,i,a){var s=R(e=o.getGraphDiv(e),n,i,a,function(t,e,r){var n,i;if(o.isTypedArray(t))if(r<0){var a=new t.constructor(0),s=F(t,e);r<0?(n=s,i=a):(n=a,i=s)}else if(n=new t.constructor(r),i=new t.constructor(t.length+e.length-r),r===e.length)n.set(e),i.set(t);else if(r<e.length){var l=e.length-r;n.set(e.subarray(l)),i.set(t),i.set(e.subarray(0,l),t.length)}else{var c=r-e.length,u=t.length-c;n.set(t.subarray(u)),n.set(e,c),i.set(t.subarray(0,u))}else n=t.concat(e),i=r>=0&&r<n.length?n.splice(0,n.length-r):[];return[n,i]}),l=r.redraw(e),u=[e,s.update,i,s.maxPoints];return c.add(e,r.prependTraces,u,t,arguments),l},r.prependTraces=function t(e,n,i,a){var s=R(e=o.getGraphDiv(e),n,i,a,function(t,e,r){var n,i;if(o.isTypedArray(t))if(r<=0){var a=new t.constructor(0),s=F(e,t);r<0?(n=s,i=a):(n=a,i=s)}else if(n=new t.constructor(r),i=new t.constructor(t.length+e.length-r),r===e.length)n.set(e),i.set(t);else if(r<e.length){var l=e.length-r;n.set(e.subarray(0,l)),i.set(e.subarray(l)),i.set(t,l)}else{var c=r-e.length;n.set(e),n.set(t.subarray(0,c),e.length),i.set(t.subarray(c))}else n=e.concat(t),i=r>=0&&r<n.length?n.splice(r,n.length):[];return[n,i]}),l=r.redraw(e),u=[e,s.update,i,s.maxPoints];return c.add(e,r.extendTraces,u,t,arguments),l},r.addTraces=function t(e,n,i){e=o.getGraphDiv(e);var a,s,l=[],u=r.deleteTraces,h=t,f=[e,l],p=[e,n];for(function(t,e,r){var n,i;if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if("undefined"==typeof e)throw new Error("traces must be defined.");for(Array.isArray(e)||(e=[e]),n=0;n<e.length;n++)if("object"!=typeof(i=e[n])||Array.isArray(i)||null===i)throw new Error("all values in traces array must be non-array objects");if("undefined"==typeof r||Array.isArray(r)||(r=[r]),"undefined"!=typeof r&&r.length!==e.length)throw new Error("if indices is specified, traces.length must equal indices.length")}(e,n,i),Array.isArray(n)||(n=[n]),n=n.map(function(t){return o.extendFlat({},t)}),A.cleanData(n),a=0;a<n.length;a++)e.data.push(n[a]);for(a=0;a<n.length;a++)l.push(-n.length+a);if("undefined"==typeof i)return s=r.redraw(e),c.add(e,u,f,h,p),s;Array.isArray(i)||(i=[i]);try{P(e,l,i)}catch(t){throw e.data.splice(e.data.length-n.length,n.length),t}return c.startSequence(e),c.add(e,u,f,h,p),s=r.moveTraces(e,l,i),c.stopSequence(e),s},r.deleteTraces=function t(e,n){e=o.getGraphDiv(e);var i,a,s=[],l=r.addTraces,u=t,h=[e,s,n],f=[e,n];if("undefined"==typeof n)throw new Error("indices must be an integer or array of integers.");for(Array.isArray(n)||(n=[n]),D(e,n,"indices"),(n=I(n,e.data.length-1)).sort(o.sorterDes),i=0;i<n.length;i+=1)a=e.data.splice(n[i],1)[0],s.push(a);var p=r.redraw(e);return c.add(e,l,h,u,f),p},r.moveTraces=function t(e,n,i){var a,s=[],l=[],u=t,h=t,f=[e=o.getGraphDiv(e),i,n],p=[e,n,i];if(P(e,n,i),n=Array.isArray(n)?n:[n],"undefined"==typeof i)for(i=[],a=0;a<n.length;a++)i.push(-n.length+a);for(i=Array.isArray(i)?i:[i],n=I(n,e.data.length-1),i=I(i,e.data.length-1),a=0;a<e.data.length;a++)-1===n.indexOf(a)&&s.push(e.data[a]);for(a=0;a<n.length;a++)l.push({newIndex:i[a],trace:e.data[n[a]]});for(l.sort(function(t,e){return t.newIndex-e.newIndex}),a=0;a<l.length;a+=1)s.splice(l[a].newIndex,0,l[a].trace);e.data=s;var d=r.redraw(e);return c.add(e,u,f,h,p),d},r.restyle=B,r._storeDirectGUIEdit=function(t,e,r){for(var n in r){V(n,s(t,n).get(),r[n],e)}},r.relayout=H;var W=/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/,X=/^[xyz]axis[0-9]*\.autorange$/,Z=/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/;function $(t,e){var r,n,i,a=t.layout,l=t._fullLayout,c=l._guiEditing,f=j(l._preGUI,c),p=Object.keys(e),g=d.list(t),v=o.extendDeepAll({},e),m={};for(q(e),p=Object.keys(e),n=0;n<p.length;n++)if(0===p[n].indexOf("allaxes")){for(i=0;i<g.length;i++){var y=g[i]._id.substr(1),x=-1!==y.indexOf("scene")?y+".":"",b=p[n].replace("allaxes",x+g[i]._name);e[b]||(e[b]=e[p[n]])}delete e[p[n]]}var _=T.layoutFlags(),w={},M={};function E(t,r){if(Array.isArray(t))t.forEach(function(t){E(t,r)});else if(!(t in e||A.hasParent(e,t))){var n=f(a,t);t in M||(M[t]=N(n.get())),void 0!==r&&n.set(r)}}var C,L={};function z(t){var e=d.name2id(t.split(".")[0]);return L[e]=1,e}for(var O in e){if(A.hasParent(e,O))throw new Error("cannot set "+O+" and a parent attribute simultaneously");for(var I=f(a,O),D=e[O],P=I.parts.length-1;P>0&&"string"!=typeof I.parts[P];)P--;var R=I.parts[P],F=I.parts[P-1]+"."+R,B=I.parts.slice(0,P).join("."),V=s(t.layout,B).get(),U=s(l,B).get(),H=I.get();if(void 0!==D){w[O]=D,M[O]="reverse"===R?D:N(H);var G=h.getLayoutValObject(l,I.parts);if(G&&G.impliedEdits&&null!==D)for(var Y in G.impliedEdits)E(o.relativeAttr(O,Y),G.impliedEdits[Y]);if(-1!==["width","height"].indexOf(O))if(D){E("autosize",null);var $="height"===O?"width":"height";E($,l[$])}else l[O]=t._initialAutoSize[O];else if("autosize"===O)E("width",D?null:l.width),E("height",D?null:l.height);else if(F.match(W))z(F),s(l,B+"._inputRange").set(null);else if(F.match(X)){z(F),s(l,B+"._inputRange").set(null);var K=s(l,B).get();K._inputDomain&&(K._input.domain=K._inputDomain.slice())}else F.match(Z)&&s(l,B+"._inputDomain").set(null);if("type"===R){var Q=V,tt="linear"===U.type&&"log"===D,et="log"===U.type&&"linear"===D;if(tt||et){if(Q&&Q.range)if(U.autorange)tt&&(Q.range=Q.range[1]>Q.range[0]?[1,2]:[2,1]);else{var rt=Q.range[0],nt=Q.range[1];tt?(rt<=0&&nt<=0&&E(B+".autorange",!0),rt<=0?rt=nt/1e6:nt<=0&&(nt=rt/1e6),E(B+".range[0]",Math.log(rt)/Math.LN10),E(B+".range[1]",Math.log(nt)/Math.LN10)):(E(B+".range[0]",Math.pow(10,rt)),E(B+".range[1]",Math.pow(10,nt)))}else E(B+".autorange",!0);Array.isArray(l._subplots.polar)&&l._subplots.polar.length&&l[I.parts[0]]&&"radialaxis"===I.parts[1]&&delete l[I.parts[0]]._subplot.viewInitial["radialaxis.range"],u.getComponentMethod("annotations","convertCoords")(t,U,D,E),u.getComponentMethod("images","convertCoords")(t,U,D,E)}else E(B+".autorange",!0),E(B+".range",null);s(l,B+"._inputRange").set(null)}else if(R.match(S)){var it=s(l,O).get(),at=(D||{}).type;at&&"-"!==at||(at="linear"),u.getComponentMethod("annotations","convertCoords")(t,it,at,E),u.getComponentMethod("images","convertCoords")(t,it,at,E)}var ot=k.containerArrayMatch(O);if(ot){r=ot.array,n=ot.index;var st=ot.property,lt=G||{editType:"calc"};""!==n&&""===st&&(k.isAddVal(D)?M[O]=null:k.isRemoveVal(D)?M[O]=(s(a,r).get()||[])[n]:o.warn("unrecognized full object value",e)),T.update(_,lt),m[r]||(m[r]={});var ct=m[r][n];ct||(ct=m[r][n]={}),ct[st]=D,delete e[O]}else"reverse"===R?(V.range?V.range.reverse():(E(B+".autorange",!0),V.range=[1,0]),U.autorange?_.calc=!0:_.plot=!0):(l._has("scatter-like")&&l._has("regl")&&"dragmode"===O&&("lasso"===D||"select"===D)&&"lasso"!==H&&"select"!==H?_.plot=!0:G?T.update(_,G):_.calc=!0,I.set(D))}}for(r in m){k.applyContainerArrayChanges(t,f(a,r),m[r],_,f)||(_.plot=!0)}var ut=l._axisConstraintGroups||[];for(C in L)for(n=0;n<ut.length;n++){var ht=ut[n];if(ht[C])for(var ft in _.calc=!0,ht)L[ft]||(d.getFromId(t,ft)._constraintShrinkable=!0)}return(J(t)||e.height||e.width)&&(_.plot=!0),(_.plot||_.calc)&&(_.layoutReplot=!0),{flags:_,rangesAltered:L,undoit:M,redoit:w,eventData:v}}function J(t){var e=t._fullLayout,r=e.width,n=e.height;return t.layout.autosize&&f.plotAutoSize(t,t.layout,e),e.width!==r||e.height!==n}function K(t,e,n,i){if(t=o.getGraphDiv(t),A.clearPromiseQueue(t),t.framework&&t.framework.isPolar)return Promise.resolve(t);o.isPlainObject(e)||(e={}),o.isPlainObject(n)||(n={}),Object.keys(e).length&&(t.changed=!0),Object.keys(n).length&&(t.changed=!0);var a=A.coerceTraceIndices(t,i),s=U(t,o.extendFlat({},e),a),l=s.flags,u=$(t,o.extendFlat({},n)),h=u.flags;(l.calc||h.calc)&&(t.calcdata=void 0),l.clearAxisTypes&&A.clearAxisTypes(t,a,n);var p=[];if(l.fullReplot&&h.layoutReplot){var d=t.data,g=t.layout;t.data=void 0,t.layout=void 0,p.push(function(){return r.plot(t,d,g)})}else l.fullReplot?p.push(r.plot):h.layoutReplot?p.push(M.layoutReplot):(p.push(f.previousPromises),G(t,h,u)||f.supplyDefaults(t),l.style&&p.push(M.doTraceStyle),l.colorbars&&p.push(M.doColorBars),h.legend&&p.push(M.doLegend),h.layoutstyle&&p.push(M.layoutStyles),h.axrange&&Y(p,u.rangesAltered),h.ticks&&p.push(M.doTicksRelayout),h.modebar&&p.push(M.doModeBar),h.camera&&p.push(M.doCamera),p.push(C));p.push(f.rehover),c.add(t,K,[t,s.undoit,u.undoit,s.traces],K,[t,s.redoit,u.redoit,s.traces]);var v=o.syncOrAsync(p,t);return v&&v.then||(v=Promise.resolve(t)),v.then(function(){return t.emit("plotly_update",{data:s.eventData,layout:u.eventData}),t})}function Q(t){return function(e){e._fullLayout._guiEditing=!0;var r=t.apply(null,arguments);return e._fullLayout._guiEditing=!1,r}}r.update=K,r._guiRestyle=Q(B),r._guiRelayout=Q(H),r._guiUpdate=Q(K);var tt=[{pattern:/^hiddenlabels/,attr:"legend.uirevision"},{pattern:/^((x|y)axis\d*)\.((auto)?range|title\.text)/},{pattern:/axis\d*\.showspikes$/,attr:"modebar.uirevision"},{pattern:/(hover|drag)mode$/,attr:"modebar.uirevision"},{pattern:/^(scene\d*)\.camera/},{pattern:/^(geo\d*)\.(projection|center)/},{pattern:/^(ternary\d*\.[abc]axis)\.(min|title\.text)$/},{pattern:/^(polar\d*\.radialaxis)\.((auto)?range|angle|title\.text)/},{pattern:/^(polar\d*\.angularaxis)\.rotation/},{pattern:/^(mapbox\d*)\.(center|zoom|bearing|pitch)/},{pattern:/^legend\.(x|y)$/,attr:"editrevision"},{pattern:/^(shapes|annotations)/,attr:"editrevision"},{pattern:/^title\.text$/,attr:"editrevision"}],et=[{pattern:/^selectedpoints$/,attr:"selectionrevision"},{pattern:/(^|value\.)visible$/,attr:"legend.uirevision"},{pattern:/^dimensions\[\d+\]\.constraintrange/},{pattern:/(^|value\.)name$/},{pattern:/colorbar\.title\.text$/},{pattern:/colorbar\.(x|y)$/,attr:"editrevision"}];function rt(t,e){for(var r=0;r<e.length;r++){var n=e[r],i=t.match(n.pattern);if(i)return{head:i[1],attr:n.attr}}}function nt(t,e){var r=s(e,t).get();if(void 0!==r)return r;var n=t.split(".");for(n.pop();n.length>1;)if(n.pop(),void 0!==(r=s(e,n.join(".")+".uirevision").get()))return r;return e.uirevision}function it(t,e){for(var r=0;r<e.length;r++)if(e[r]._fullInput.uid===t)return r;return-1}function at(t,e,r){for(var n=0;n<e.length;n++)if(e[n].uid===t)return n;return!e[r]||e[r].uid?-1:r}function ot(t,e){var r=o.isPlainObject(t),n=Array.isArray(t);return r||n?(r&&o.isPlainObject(e)||n&&Array.isArray(e))&&JSON.stringify(t)===JSON.stringify(e):t===e}function st(t,e,r,n){var i,a,l,c=n.getValObject,u=n.flags,h=n.immutable,f=n.inArray,p=n.arrayIndex;function d(){var t=i.editType;f&&-1!==t.indexOf("arraydraw")?o.pushUnique(u.arrays[f],p):(T.update(u,i),"none"!==t&&u.nChanges++,n.transition&&i.anim&&u.nChangesAnim++,(W.test(l)||X.test(l))&&(u.rangesAltered[r[0]]=1),Z.test(l)&&s(e,"_inputDomain").set(null),"datarevision"===a&&(u.newDataRevision=1))}function g(t){return"data_array"===t.valType||t.arrayOk}for(a in t){if(u.calc&&!n.transition)return;var v=t[a],m=e[a],y=r.concat(a);if(l=y.join("."),"_"!==a.charAt(0)&&"function"!=typeof v&&v!==m){if(("tick0"===a||"dtick"===a)&&"geo"!==r[0]){var x=e.tickmode;if("auto"===x||"array"===x||!x)continue}if(("range"!==a||!e.autorange)&&("zmin"!==a&&"zmax"!==a||"contourcarpet"!==e.type)&&(i=c(y))&&(!i._compareAsJSON||JSON.stringify(v)!==JSON.stringify(m))){var b,_=i.valType,w=g(i),k=Array.isArray(v),A=Array.isArray(m);if(k&&A){var M="_input_"+a,S=t[M],E=e[M];if(Array.isArray(S)&&S===E)continue}if(void 0===m)w&&k?u.calc=!0:d();else if(i._isLinkedToArray){var C=[],L=!1;f||(u.arrays[a]=C);var z=Math.min(v.length,m.length),O=Math.max(v.length,m.length);if(z!==O){if("arraydraw"!==i.editType){d();continue}L=!0}for(b=0;b<z;b++)st(v[b],m[b],y.concat(b),o.extendFlat({inArray:a,arrayIndex:b},n));if(L)for(b=z;b<O;b++)C.push(b)}else!_&&o.isPlainObject(v)?st(v,m,y,n):w?k&&A?(h&&(u.calc=!0),(h||n.newDataRevision)&&d()):k!==A?u.calc=!0:d():k&&A&&v.length===m.length&&String(v)===String(m)||d()}}}for(a in e)if(!(a in t||"_"===a.charAt(0)||"function"==typeof e[a])){if(g(i=c(r.concat(a)))&&Array.isArray(e[a]))return void(u.calc=!0);d()}}function lt(t){var e=n.select(t),r=t._fullLayout;if(r._container=e.selectAll(".plot-container").data([0]),r._container.enter().insert("div",":first-child").classed("plot-container",!0).classed("plotly",!0),r._paperdiv=r._container.selectAll(".svg-container").data([0]),r._paperdiv.enter().append("div").classed("svg-container",!0).style("position","relative"),r._glcontainer=r._paperdiv.selectAll(".gl-container").data([{}]),r._glcontainer.enter().append("div").classed("gl-container",!0),r._paperdiv.selectAll(".main-svg").remove(),r._paper=r._paperdiv.insert("svg",":first-child").classed("main-svg",!0),r._toppaper=r._paperdiv.append("svg").classed("main-svg",!0),!r._uid){var i={};n.selectAll("defs").each(function(){this.id&&(i[this.id.split("-")[1]]=1)}),r._uid=o.randstr(i)}r._paperdiv.selectAll(".main-svg").attr(x.svgAttrs),r._defs=r._paper.append("defs").attr("id","defs-"+r._uid),r._clips=r._defs.append("g").classed("clips",!0),r._topdefs=r._toppaper.append("defs").attr("id","topdefs-"+r._uid),r._topclips=r._topdefs.append("g").classed("clips",!0),r._bgLayer=r._paper.append("g").classed("bglayer",!0),r._draggers=r._paper.append("g").classed("draglayer",!0);var a=r._paper.append("g").classed("layer-below",!0);r._imageLowerLayer=a.append("g").classed("imagelayer",!0),r._shapeLowerLayer=a.append("g").classed("shapelayer",!0),r._cartesianlayer=r._paper.append("g").classed("cartesianlayer",!0),r._polarlayer=r._paper.append("g").classed("polarlayer",!0),r._ternarylayer=r._paper.append("g").classed("ternarylayer",!0),r._geolayer=r._paper.append("g").classed("geolayer",!0),r._pielayer=r._paper.append("g").classed("pielayer",!0),r._glimages=r._paper.append("g").classed("glimages",!0);var s=r._toppaper.append("g").classed("layer-above",!0);r._imageUpperLayer=s.append("g").classed("imagelayer",!0),r._shapeUpperLayer=s.append("g").classed("shapelayer",!0),r._infolayer=r._toppaper.append("g").classed("infolayer",!0),r._menulayer=r._toppaper.append("g").classed("menulayer",!0),r._zoomlayer=r._toppaper.append("g").classed("zoomlayer",!0),r._hoverlayer=r._toppaper.append("g").classed("hoverlayer",!0),r._modebardiv=r._paperdiv.selectAll(".modebar-container").data([0]),r._modebardiv.enter().append("div").classed("modebar-container",!0).style("position","absolute").style("top","0px").style("right","0px"),t.emit("plotly_framework")}r.react=function(t,e,n,i){var a,l;var c=(t=o.getGraphDiv(t))._fullData,p=t._fullLayout;if(o.isPlotDiv(t)&&c&&p){if(o.isPlainObject(e)){var d=e;e=d.data,n=d.layout,i=d.config,a=d.frames}var g=!1;if(i){var v=o.extendDeep({},t._context);t._context=void 0,O(t,i),g=function t(e,r){var n;for(n in e)if("_"!==n.charAt(0)){var i=e[n],a=r[n];if(i!==a)if(o.isPlainObject(i)&&o.isPlainObject(a)){if(t(i,a))return!0}else{if(!Array.isArray(i)||!Array.isArray(a))return!0;if(i.length!==a.length)return!0;for(var s=0;s<i.length;s++)if(i[s]!==a[s]){if(!o.isPlainObject(i[s])||!o.isPlainObject(a[s]))return!0;if(t(i[s],a[s]))return!0}}}}(v,t._context)}t.data=e||[],A.cleanData(t.data),t.layout=n||{},A.cleanLayout(t.layout),function(t,e,r,n){var i,a,l,c,u,h,f,p,d=n._preGUI,g=[],v={};for(i in d){if(u=rt(i,tt)){if(a=u.attr||u.head+".uirevision",(c=(l=s(n,a).get())&&nt(a,e))&&c===l&&(null===(h=d[i])&&(h=void 0),ot(p=(f=s(e,i)).get(),h))){void 0===p&&"autorange"===i.substr(i.length-9)&&g.push(i.substr(0,i.length-10)),f.set(N(s(n,i).get()));continue}}else o.warn("unrecognized GUI edit: "+i);delete d[i],"range["===i.substr(i.length-8,6)&&(v[i.substr(0,i.length-9)]=1)}for(var m=0;m<g.length;m++){var y=g[m];if(v[y]){var x=s(e,y).get();x&&delete x.autorange}}var b=n._tracePreGUI;for(var _ in b){var w,k=b[_],A=null;for(i in k){if(!A){var M=it(_,r);if(M<0){delete b[_];break}var T=at(_,t,(w=r[M]._fullInput).index);if(T<0){delete b[_];break}A=t[T]}if(u=rt(i,et)){if(u.attr?c=(l=s(n,u.attr).get())&&nt(u.attr,e):(l=w.uirevision,void 0===(c=A.uirevision)&&(c=e.uirevision)),c&&c===l&&(null===(h=k[i])&&(h=void 0),ot(p=(f=s(A,i)).get(),h))){f.set(N(s(w,i).get()));continue}}else o.warn("unrecognized GUI edit: "+i+" in trace uid "+_);delete k[i]}}}(t.data,t.layout,c,p),f.supplyDefaults(t,{skipUpdateCalc:!0});var m=t._fullData,y=t._fullLayout,x=void 0===y.datarevision,b=y.transition,_=function(t,e,r,n,i){var a=T.layoutFlags();a.arrays={},a.rangesAltered={},a.nChanges=0,a.nChangesAnim=0,st(e,r,[],{getValObject:function(t){return h.getLayoutValObject(r,t)},flags:a,immutable:n,transition:i,gd:t}),(a.plot||a.calc)&&(a.layoutReplot=!0);i&&a.nChanges&&a.nChangesAnim&&(a.anim=a.nChanges===a.nChangesAnim?"all":"some");return a}(t,p,y,x,b),w=_.newDataRevision,k=function(t,e,r,n,i,a){var o=e.length===r.length;if(!i&&!o)return{fullReplot:!0,calc:!0};var s,l,c=T.traceFlags();c.arrays={},c.nChanges=0,c.nChangesAnim=0;var u={getValObject:function(t){return h.getTraceValObject(l,t)},flags:c,immutable:n,transition:i,newDataRevision:a,gd:t},p={};for(s=0;s<e.length;s++)if(r[s]){if(l=r[s]._fullInput,f.hasMakesDataTransform(l)&&(l=r[s]),p[l.uid])continue;p[l.uid]=1,st(e[s]._fullInput,l,[],u)}(c.calc||c.plot)&&(c.fullReplot=!0);i&&c.nChanges&&c.nChangesAnim&&(c.anim=c.nChanges===c.nChangesAnim&&o?"all":"some");return c}(t,c,m,x,b,w);J(t)&&(_.layoutReplot=!0),k.calc||_.calc?t.calcdata=void 0:f.supplyDefaultsUpdateCalc(t.calcdata,m);var S=[];if(a&&(t._transitionData={},f.createTransitionData(t),S.push(function(){return r.addFrames(t,a)})),y.transition&&!g&&(k.anim||_.anim))f.doCalcdata(t),M.doAutoRangeAndConstraints(t),S.push(function(){return f.transitionFromReact(t,k,_,p)});else if(k.fullReplot||_.layoutReplot||g)t._fullLayout._skipDefaults=!0,S.push(r.plot);else{for(var E in _.arrays){var L=_.arrays[E];if(L.length){var z=u.getComponentMethod(E,"drawOne");if(z!==o.noop)for(var I=0;I<L.length;I++)z(t,L[I]);else{var D=u.getComponentMethod(E,"draw");if(D===o.noop)throw new Error("cannot draw components: "+E);D(t)}}}S.push(f.previousPromises),k.style&&S.push(M.doTraceStyle),k.colorbars&&S.push(M.doColorBars),_.legend&&S.push(M.doLegend),_.layoutstyle&&S.push(M.layoutStyles),_.axrange&&Y(S),_.ticks&&S.push(M.doTicksRelayout),_.modebar&&S.push(M.doModeBar),_.camera&&S.push(M.doCamera),S.push(C)}S.push(f.rehover),(l=o.syncOrAsync(S,t))&&l.then||(l=Promise.resolve(t))}else l=r.newPlot(t,e,n,i);return l.then(function(){return t.emit("plotly_react",{data:e,layout:n}),t})},r.animate=function(t,e,r){if(t=o.getGraphDiv(t),!o.isPlotDiv(t))throw new Error("This element is not a Plotly plot: "+t+". It's likely that you've failed to create a plot before animating it. For more details, see https://plot.ly/javascript/animations/");var n=t._transitionData;n._frameQueue||(n._frameQueue=[]);var i=(r=f.supplyAnimationDefaults(r)).transition,a=r.frame;function s(t){return Array.isArray(i)?t>=i.length?i[0]:i[t]:i}function l(t){return Array.isArray(a)?t>=a.length?a[0]:a[t]:a}function c(t,e){var r=0;return function(){if(t&&++r===e)return t()}}return void 0===n._frameWaitingCnt&&(n._frameWaitingCnt=0),new Promise(function(a,u){function h(){n._currentFrame&&n._currentFrame.onComplete&&n._currentFrame.onComplete();var e=n._currentFrame=n._frameQueue.shift();if(e){var r=e.name?e.name.toString():null;t._fullLayout._currentFrame=r,n._lastFrameAt=Date.now(),n._timeToNext=e.frameOpts.duration,f.transition(t,e.frame.data,e.frame.layout,A.coerceTraceIndices(t,e.frame.traces),e.frameOpts,e.transitionOpts).then(function(){e.onComplete&&e.onComplete()}),t.emit("plotly_animatingframe",{name:r,frame:e.frame,animation:{frame:e.frameOpts,transition:e.transitionOpts}})}else t.emit("plotly_animated"),window.cancelAnimationFrame(n._animationRaf),n._animationRaf=null}function p(){t.emit("plotly_animating"),n._lastFrameAt=-1/0,n._timeToNext=0,n._runningTransitions=0,n._currentFrame=null;var e=function(){n._animationRaf=window.requestAnimationFrame(e),Date.now()-n._lastFrameAt>n._timeToNext&&h()};e()}var d,g,v=0;function m(t){return Array.isArray(i)?v>=i.length?t.transitionOpts=i[v]:t.transitionOpts=i[0]:t.transitionOpts=i,v++,t}var y=[],x=null==e,b=Array.isArray(e);if(!x&&!b&&o.isPlainObject(e))y.push({type:"object",data:m(o.extendFlat({},e))});else if(x||-1!==["string","number"].indexOf(typeof e))for(d=0;d<n._frames.length;d++)(g=n._frames[d])&&(x||String(g.group)===String(e))&&y.push({type:"byname",name:String(g.name),data:m({name:g.name})});else if(b)for(d=0;d<e.length;d++){var _=e[d];-1!==["number","string"].indexOf(typeof _)?(_=String(_),y.push({type:"byname",name:_,data:m({name:_})})):o.isPlainObject(_)&&y.push({type:"object",data:m(o.extendFlat({},_))})}for(d=0;d<y.length;d++)if("byname"===(g=y[d]).type&&!n._frameHash[g.data.name])return o.warn('animate failure: frame not found: "'+g.data.name+'"'),void u();-1!==["next","immediate"].indexOf(r.mode)&&function(){if(0!==n._frameQueue.length){for(;n._frameQueue.length;){var e=n._frameQueue.pop();e.onInterrupt&&e.onInterrupt()}t.emit("plotly_animationinterrupted",[])}}(),"reverse"===r.direction&&y.reverse();var w=t._fullLayout._currentFrame;if(w&&r.fromcurrent){var k=-1;for(d=0;d<y.length;d++)if("byname"===(g=y[d]).type&&g.name===w){k=d;break}if(k>0&&k<y.length-1){var M=[];for(d=0;d<y.length;d++)g=y[d],("byname"!==y[d].type||d>k)&&M.push(g);y=M}}y.length>0?function(e){if(0!==e.length){for(var i=0;i<e.length;i++){var o;o="byname"===e[i].type?f.computeFrame(t,e[i].name):e[i].data;var h=l(i),d=s(i);d.duration=Math.min(d.duration,h.duration);var g={frame:o,name:e[i].name,frameOpts:h,transitionOpts:d};i===e.length-1&&(g.onComplete=c(a,2),g.onInterrupt=u),n._frameQueue.push(g)}"immediate"===r.mode&&(n._lastFrameAt=-1/0),n._animationRaf||p()}}(y):(t.emit("plotly_animated"),a())})},r.addFrames=function(t,e,r){if(t=o.getGraphDiv(t),null==e)return Promise.resolve();if(!o.isPlotDiv(t))throw new Error("This element is not a Plotly plot: "+t+". It's likely that you've failed to create a plot before adding frames. For more details, see https://plot.ly/javascript/animations/");var n,i,a,s,l=t._transitionData._frames,u=t._transitionData._frameHash;if(!Array.isArray(e))throw new Error("addFrames failure: frameList must be an Array of frame definitions"+e);var h=l.length+2*e.length,p=[],d={};for(n=e.length-1;n>=0;n--)if(o.isPlainObject(e[n])){var g=e[n].name,v=(u[g]||d[g]||{}).name,m=e[n].name,y=u[v]||d[v];v&&m&&"number"==typeof m&&y&&E<5&&(E++,o.warn('addFrames: overwriting frame "'+(u[v]||d[v]).name+'" with a frame whose name of type "number" also equates to "'+v+'". This is valid but may potentially lead to unexpected behavior since all plotly.js frame names are stored internally as strings.'),5===E&&o.warn("addFrames: This API call has yielded too many of these warnings. For the rest of this call, further warnings about numeric frame names will be suppressed.")),d[g]={name:g},p.push({frame:f.supplyFrameDefaults(e[n]),index:r&&void 0!==r[n]&&null!==r[n]?r[n]:h+n})}p.sort(function(t,e){return t.index>e.index?-1:t.index<e.index?1:0});var x=[],b=[],_=l.length;for(n=p.length-1;n>=0;n--){if("number"==typeof(i=p[n].frame).name&&o.warn("Warning: addFrames accepts frames with numeric names, but the numbers areimplicitly cast to strings"),!i.name)for(;u[i.name="frame "+t._transitionData._counter++];);if(u[i.name]){for(a=0;a<l.length&&(l[a]||{}).name!==i.name;a++);x.push({type:"replace",index:a,value:i}),b.unshift({type:"replace",index:a,value:l[a]})}else s=Math.max(0,Math.min(p[n].index,_)),x.push({type:"insert",index:s,value:i}),b.unshift({type:"delete",index:s}),_++}var w=f.modifyFrames,k=f.modifyFrames,A=[t,b],M=[t,x];return c&&c.add(t,w,A,k,M),f.modifyFrames(t,x)},r.deleteFrames=function(t,e){if(t=o.getGraphDiv(t),!o.isPlotDiv(t))throw new Error("This element is not a Plotly plot: "+t);var r,n,i=t._transitionData._frames,a=[],s=[];if(!e)for(e=[],r=0;r<i.length;r++)e.push(r);for((e=e.slice(0)).sort(),r=e.length-1;r>=0;r--)n=e[r],a.push({type:"delete",index:n}),s.unshift({type:"insert",index:n,value:i[n]});var l=f.modifyFrames,u=f.modifyFrames,h=[t,s],p=[t,a];return c&&c.add(t,l,h,u,p),f.modifyFrames(t,a)},r.purge=function(t){var e=(t=o.getGraphDiv(t))._fullLayout||{},r=t._fullData||[];return f.cleanPlot([],{},r,e),f.purge(t),l.purge(t),e._container&&e._container.remove(),delete t._context,t}},{"../components/color":574,"../components/colorbar/connect":576,"../components/drawing":595,"../constants/xmlns_namespaces":675,"../lib":697,"../lib/events":686,"../lib/queue":712,"../lib/svg_text_utils":721,"../plots/cartesian/axes":745,"../plots/cartesian/constants":751,"../plots/cartesian/graph_interact":754,"../plots/cartesian/select":762,"../plots/plots":807,"../plots/polar/legacy":815,"../registry":826,"./edit_types":728,"./helpers":729,"./manage_arrays":731,"./plot_config":733,"./plot_schema":734,"./subroutines":736,d3:151,"fast-isnumeric":218,"has-hover":399}],733:[function(t,e,r){"use strict";var n={staticPlot:{valType:"boolean",dflt:!1},plotlyServerURL:{valType:"string",dflt:"https://plot.ly"},editable:{valType:"boolean",dflt:!1},edits:{annotationPosition:{valType:"boolean",dflt:!1},annotationTail:{valType:"boolean",dflt:!1},annotationText:{valType:"boolean",dflt:!1},axisTitleText:{valType:"boolean",dflt:!1},colorbarPosition:{valType:"boolean",dflt:!1},colorbarTitleText:{valType:"boolean",dflt:!1},legendPosition:{valType:"boolean",dflt:!1},legendText:{valType:"boolean",dflt:!1},shapePosition:{valType:"boolean",dflt:!1},titleText:{valType:"boolean",dflt:!1}},autosizable:{valType:"boolean",dflt:!1},responsive:{valType:"boolean",dflt:!1},fillFrame:{valType:"boolean",dflt:!1},frameMargins:{valType:"number",dflt:0,min:0,max:.5},scrollZoom:{valType:"flaglist",flags:["cartesian","gl3d","geo","mapbox"],extras:[!0,!1],dflt:"gl3d+geo+mapbox"},doubleClick:{valType:"enumerated",values:[!1,"reset","autosize","reset+autosize"],dflt:"reset+autosize"},showAxisDragHandles:{valType:"boolean",dflt:!0},showAxisRangeEntryBoxes:{valType:"boolean",dflt:!0},showTips:{valType:"boolean",dflt:!0},showLink:{valType:"boolean",dflt:!1},linkText:{valType:"string",dflt:"Edit chart",noBlank:!0},sendData:{valType:"boolean",dflt:!0},showSources:{valType:"any",dflt:!1},displayModeBar:{valType:"enumerated",values:["hover",!0,!1],dflt:"hover"},showSendToCloud:{valType:"boolean",dflt:!1},modeBarButtonsToRemove:{valType:"any",dflt:[]},modeBarButtonsToAdd:{valType:"any",dflt:[]},modeBarButtons:{valType:"any",dflt:!1},toImageButtonOptions:{valType:"any",dflt:{}},displaylogo:{valType:"boolean",dflt:!0},watermark:{valType:"boolean",dflt:!1},plotGlPixelRatio:{valType:"number",dflt:2,min:1,max:4},setBackground:{valType:"any",dflt:"transparent"},topojsonURL:{valType:"string",noBlank:!0,dflt:"https://cdn.plot.ly/"},mapboxAccessToken:{valType:"string",dflt:null},logging:{valType:"boolean",dflt:1},queueLength:{valType:"integer",min:0,dflt:0},globalTransforms:{valType:"any",dflt:[]},locale:{valType:"string",dflt:"en-US"},locales:{valType:"any",dflt:{}}},i={};!function t(e,r){for(var n in e){var i=e[n];i.valType?r[n]=i.dflt:(r[n]||(r[n]={}),t(i,r[n]))}}(n,i),e.exports={configAttributes:n,dfltConfig:i}},{}],734:[function(t,e,r){"use strict";var n=t("../registry"),i=t("../lib"),a=t("../plots/attributes"),o=t("../plots/layout_attributes"),s=t("../plots/frame_attributes"),l=t("../plots/animation_attributes"),c=t("./plot_config").configAttributes,u=t("../plots/polar/legacy/area_attributes"),h=t("../plots/polar/legacy/axis_attributes"),f=t("./edit_types"),p=i.extendFlat,d=i.extendDeepAll,g=i.isPlainObject,v="_isSubplotObj",m="_isLinkedToArray",y=[v,m,"_arrayAttrRegexps","_deprecated"];function x(t,e,r){if(!t)return!1;if(t._isLinkedToArray)if(b(e[r]))r++;else if(r<e.length)return!1;for(;r<e.length;r++){var n=t[e[r]];if(!g(n))break;if(t=n,r===e.length-1)break;if(t._isLinkedToArray){if(!b(e[++r]))return!1}else if("info_array"===t.valType){var i=e[++r];if(!b(i))return!1;var a=t.items;if(Array.isArray(a)){if(i>=a.length)return!1;if(2===t.dimensions){if(r++,e.length===r)return t;var o=e[r];if(!b(o))return!1;t=a[i][o]}else t=a[i]}else t=a}}return t}function b(t){return t===Math.round(t)&&t>=0}function _(t){return function(t){r.crawl(t,function(t,e,n){r.isValObject(t)?"data_array"===t.valType?(t.role="data",n[e+"src"]={valType:"string",editType:"none"}):!0===t.arrayOk&&(n[e+"src"]={valType:"string",editType:"none"}):g(t)&&(t.role="object")})}(t),function(t){r.crawl(t,function(t,e,r){if(!t)return;var n=t[m];if(!n)return;delete t[m],r[e]={items:{}},r[e].items[n]=t,r[e].role="object"})}(t),function(t){!function t(e){for(var r in e)if(g(e[r]))t(e[r]);else if(Array.isArray(e[r]))for(var n=0;n<e[r].length;n++)t(e[r][n]);else e[r]instanceof RegExp&&(e[r]=e[r].toString())}(t)}(t),t}function w(t,e,r){var n=i.nestedProperty(t,r),a=d({},e.layoutAttributes);a[v]=!0,n.set(a)}function k(t,e,r){var n=i.nestedProperty(t,r);n.set(d(n.get()||{},e))}r.IS_SUBPLOT_OBJ=v,r.IS_LINKED_TO_ARRAY=m,r.DEPRECATED="_deprecated",r.UNDERSCORE_ATTRS=y,r.get=function(){var t={};n.allTypes.concat("area").forEach(function(e){t[e]=function(t){var e,o;"area"===t?(e={attributes:u},o={}):(e=n.modules[t]._module,o=e.basePlotModule);var s={type:null},l=d({},a),c=d({},e.attributes);r.crawl(c,function(t,e,r,n,a){i.nestedProperty(l,a).set(void 0),void 0===t&&i.nestedProperty(c,a).set(void 0)}),d(s,l),d(s,c),o.attributes&&d(s,o.attributes);s.type=t;var h={meta:e.meta||{},attributes:_(s)};if(e.layoutAttributes){var f={};d(f,e.layoutAttributes),h.layoutAttributes=_(f)}return h}(e)});var e,g={};return Object.keys(n.transformsRegistry).forEach(function(t){g[t]=function(t){var e=n.transformsRegistry[t],r=d({},e.attributes);return Object.keys(n.componentsRegistry).forEach(function(e){var i=n.componentsRegistry[e];i.schema&&i.schema.transforms&&i.schema.transforms[t]&&Object.keys(i.schema.transforms[t]).forEach(function(e){k(r,i.schema.transforms[t][e],e)})}),{attributes:_(r)}}(t)}),{defs:{valObjects:i.valObjectMeta,metaKeys:y.concat(["description","role","editType","impliedEdits"]),editType:{traces:f.traces,layout:f.layout},impliedEdits:{}},traces:t,layout:function(){var t,e,r={};for(t in d(r,o),n.subplotsRegistry)if((e=n.subplotsRegistry[t]).layoutAttributes)if(Array.isArray(e.attr))for(var i=0;i<e.attr.length;i++)w(r,e,e.attr[i]);else{var a="subplot"===e.attr?e.name:e.attr;w(r,e,a)}for(t in r=function(t){return p(t,{radialaxis:h.radialaxis,angularaxis:h.angularaxis}),p(t,h.layout),t}(r),n.componentsRegistry){var s=(e=n.componentsRegistry[t]).schema;if(s&&(s.subplots||s.layout)){var l=s.subplots;if(l&&l.xaxis&&!l.yaxis)for(var c in l.xaxis)delete r.yaxis[c]}else e.layoutAttributes&&k(r,e.layoutAttributes,e.name)}return{layoutAttributes:_(r)}}(),transforms:g,frames:(e={frames:i.extendDeepAll({},s)},_(e),e.frames),animation:_(l),config:_(c)}},r.crawl=function(t,e,n,i){var a=n||0;i=i||"",Object.keys(t).forEach(function(n){var o=t[n];if(-1===y.indexOf(n)){var s=(i?i+".":"")+n;e(o,n,t,a,s),r.isValObject(o)||g(o)&&"impliedEdits"!==n&&r.crawl(o,e,a+1,s)}})},r.isValObject=function(t){return t&&void 0!==t.valType},r.findArrayAttributes=function(t){var e,n,o=[],s=[],l=[];function c(t,r,a,c){s=s.slice(0,c).concat([r]),l=l.slice(0,c).concat([t&&t._isLinkedToArray]),t&&("data_array"===t.valType||!0===t.arrayOk)&&!("colorbar"===s[c-1]&&("ticktext"===r||"tickvals"===r))&&function t(e,r,a){var c=e[s[r]];var u=a+s[r];if(r===s.length-1)i.isArrayOrTypedArray(c)&&o.push(n+u);else if(l[r]){if(Array.isArray(c))for(var h=0;h<c.length;h++)i.isPlainObject(c[h])&&t(c[h],r+1,u+"["+h+"].")}else i.isPlainObject(c)&&t(c,r+1,u+".")}(e,0,"")}e=t,n="",r.crawl(a,c),t._module&&t._module.attributes&&r.crawl(t._module.attributes,c);var u=t.transforms;if(u)for(var h=0;h<u.length;h++){var f=u[h],p=f._module;p&&(n="transforms["+h+"].",e=f,r.crawl(p.attributes,c))}return o},r.getTraceValObject=function(t,e){var r,i,o=e[0],s=1;if("transforms"===o){if(1===e.length)return a.transforms;var l=t.transforms;if(!Array.isArray(l)||!l.length)return!1;var c=e[1];if(!b(c)||c>=l.length)return!1;i=(r=(n.transformsRegistry[l[c].type]||{}).attributes)&&r[e[2]],s=3}else if("area"===t.type)i=u[o];else{var h=t._module;if(h||(h=(n.modules[t.type||a.type.dflt]||{})._module),!h)return!1;if(!(i=(r=h.attributes)&&r[o])){var f=h.basePlotModule;f&&f.attributes&&(i=f.attributes[o])}i||(i=a[o])}return x(i,e,s)},r.getLayoutValObject=function(t,e){return x(function(t,e){var r,i,a,s,l=t._basePlotModules;if(l){var c;for(r=0;r<l.length;r++){if((a=l[r]).attrRegex&&a.attrRegex.test(e)){if(a.layoutAttrOverrides)return a.layoutAttrOverrides;!c&&a.layoutAttributes&&(c=a.layoutAttributes)}var u=a.baseLayoutAttrOverrides;if(u&&e in u)return u[e]}if(c)return c}var f=t._modules;if(f)for(r=0;r<f.length;r++)if((s=f[r].layoutAttributes)&&e in s)return s[e];for(i in n.componentsRegistry)if(!(a=n.componentsRegistry[i]).schema&&e===a.name)return a.layoutAttributes;if(e in o)return o[e];if("radialaxis"===e||"angularaxis"===e)return h[e];return h.layout[e]||!1}(t,e[0]),e,1)}},{"../lib":697,"../plots/animation_attributes":740,"../plots/attributes":742,"../plots/frame_attributes":772,"../plots/layout_attributes":798,"../plots/polar/legacy/area_attributes":813,"../plots/polar/legacy/axis_attributes":814,"../registry":826,"./edit_types":728,"./plot_config":733}],735:[function(t,e,r){"use strict";var n=t("../lib"),i=t("../plots/attributes"),a="templateitemname",o={name:{valType:"string",editType:"none"}};function s(t){return t&&"string"==typeof t}function l(t){var e=t.length-1;return"s"!==t.charAt(e)&&n.warn("bad argument to arrayDefaultKey: "+t),t.substr(0,t.length-1)+"defaults"}o[a]={valType:"string",editType:"calc"},r.templatedArray=function(t,e){return e._isLinkedToArray=t,e.name=o.name,e[a]=o[a],e},r.traceTemplater=function(t){var e,r,a={};for(e in t)r=t[e],Array.isArray(r)&&r.length&&(a[e]=0);return{newTrace:function(o){var s={type:e=n.coerce(o,{},i,"type"),_template:null};if(e in a){r=t[e];var l=a[e]%r.length;a[e]++,s._template=r[l]}return s}}},r.newContainer=function(t,e,r){var i=t._template,a=i&&(i[e]||r&&i[r]);return n.isPlainObject(a)||(a=null),t[e]={_template:a}},r.arrayTemplater=function(t,e,r){var n=t._template,i=n&&n[l(e)],o=n&&n[e];Array.isArray(o)&&o.length||(o=[]);var c={};return{newItem:function(t){var e={name:t.name,_input:t},n=e[a]=t[a];if(!s(n))return e._template=i,e;for(var l=0;l<o.length;l++){var u=o[l];if(u.name===n)return c[n]=1,e._template=u,e}return e[r]=t[r]||!1,e._template=!1,e},defaultItems:function(){for(var t=[],e=0;e<o.length;e++){var r=o[e],n=r.name;if(s(n)&&!c[n]){var i={_template:r,name:n,_input:{_templateitemname:n}};i[a]=r[a],t.push(i),c[n]=1}}return t}}},r.arrayDefaultKey=l,r.arrayEditor=function(t,e,r){var i=(n.nestedProperty(t,e).get()||[]).length,o=r._index,s=o>=i&&(r._input||{})._templateitemname;s&&(o=i);var l,c=e+"["+o+"]";function u(){l={},s&&(l[c]={},l[c][a]=s)}function h(t,e){s?n.nestedProperty(l[c],t).set(e):l[c+"."+t]=e}function f(){var t=l;return u(),t}return u(),{modifyBase:function(t,e){l[t]=e},modifyItem:h,getUpdateObj:f,applyUpdate:function(e,r){e&&h(e,r);var i=f();for(var a in i)n.nestedProperty(t,a).set(i[a])}}}},{"../lib":697,"../plots/attributes":742}],736:[function(t,e,r){"use strict";var n=t("d3"),i=t("../registry"),a=t("../plots/plots"),o=t("../lib"),s=t("../lib/clear_gl_canvases"),l=t("../components/color"),c=t("../components/drawing"),u=t("../components/titles"),h=t("../components/modebar"),f=t("../plots/cartesian/axes"),p=t("../constants/alignment"),d=t("../plots/cartesian/constraints"),g=d.enforce,v=d.clean,m=t("../plots/cartesian/autorange").doAutoRange,y="start",x="middle",b="end";function _(t,e,r){for(var n=0;n<r.length;n++){var i=r[n][0],a=r[n][1];if(!(i[0]>=t[1]||i[1]<=t[0])&&(a[0]<e[1]&&a[1]>e[0]))return!0}return!1}function w(t){var e,i,a,s,u,d,g=t._fullLayout,v=g._size,m=v.p,y=f.list(t,"",!0);if(g._paperdiv.style({width:t._context.responsive&&g.autosize&&!t._context._hasZeroWidth&&!t.layout.width?"100%":g.width+"px",height:t._context.responsive&&g.autosize&&!t._context._hasZeroHeight&&!t.layout.height?"100%":g.height+"px"}).selectAll(".main-svg").call(c.setSize,g.width,g.height),t._context.setBackground(t,g.paper_bgcolor),r.drawMainTitle(t),h.manage(t),!g._has("cartesian"))return t._promises.length&&Promise.all(t._promises);function x(t,e,r){var n=t._lw/2;return"x"===t._id.charAt(0)?e?"top"===r?e._offset-m-n:e._offset+e._length+m+n:v.t+v.h*(1-(t.position||0))+n%1:e?"right"===r?e._offset+e._length+m+n:e._offset-m-n:v.l+v.w*(t.position||0)+n%1}for(e=0;e<y.length;e++){var b=(s=y[e])._anchorAxis;s._linepositions={},s._lw=c.crispRound(t,s.linewidth,1),s._mainLinePosition=x(s,b,s.side),s._mainMirrorPosition=s.mirror&&b?x(s,b,p.OPPOSITE_SIDE[s.side]):null}var w=[],A=[],T=[],S=1===l.opacity(g.paper_bgcolor)&&1===l.opacity(g.plot_bgcolor)&&g.paper_bgcolor===g.plot_bgcolor;for(i in g._plots)if((a=g._plots[i]).mainplot)a.bg&&a.bg.remove(),a.bg=void 0;else{var E=a.xaxis.domain,C=a.yaxis.domain,L=a.plotgroup;if(_(E,C,T)){var z=L.node(),O=a.bg=o.ensureSingle(L,"rect","bg");z.insertBefore(O.node(),z.childNodes[0]),A.push(i)}else L.select("rect.bg").remove(),T.push([E,C]),S||(w.push(i),A.push(i))}var I,D,P,R,F,B,N,j,V,U,q,H,G,Y=g._bgLayer.selectAll(".bg").data(w);for(Y.enter().append("rect").classed("bg",!0),Y.exit().remove(),Y.each(function(t){g._plots[t].bg=n.select(this)}),e=0;e<A.length;e++)a=g._plots[A[e]],u=a.xaxis,d=a.yaxis,a.bg&&a.bg.call(c.setRect,u._offset-m,d._offset-m,u._length+2*m,d._length+2*m).call(l.fill,g.plot_bgcolor).style("stroke-width",0);if(!g._hasOnlyLargeSploms)for(i in g._plots){a=g._plots[i],u=a.xaxis,d=a.yaxis;var W,X,Z=a.clipId="clip"+g._uid+i+"plot",$=o.ensureSingleById(g._clips,"clipPath",Z,function(t){t.classed("plotclip",!0).append("rect")});a.clipRect=$.select("rect").attr({width:u._length,height:d._length}),c.setTranslate(a.plot,u._offset,d._offset),a._hasClipOnAxisFalse?(W=null,X=Z):(W=Z,X=null),c.setClipUrl(a.plot,W,t),a.layerClipId=X}function J(t){return"M"+I+","+t+"H"+D}function K(t){return"M"+u._offset+","+t+"h"+u._length}function Q(t){return"M"+t+","+j+"V"+N}function tt(t){return"M"+t+","+d._offset+"v"+d._length}function et(t,e,r){if(!t.showline||i!==t._mainSubplot)return"";if(!t._anchorAxis)return r(t._mainLinePosition);var n=e(t._mainLinePosition);return t.mirror&&(n+=e(t._mainMirrorPosition)),n}for(i in g._plots){a=g._plots[i],u=a.xaxis,d=a.yaxis;var rt="M0,0";k(u,i)&&(F=M(u,"left",d,y),I=u._offset-(F?m+F:0),B=M(u,"right",d,y),D=u._offset+u._length+(B?m+B:0),P=x(u,d,"bottom"),R=x(u,d,"top"),!(G=!u._anchorAxis||i!==u._mainSubplot)||"allticks"!==u.mirror&&"all"!==u.mirror||(u._linepositions[i]=[P,R]),rt=et(u,J,K),G&&u.showline&&("all"===u.mirror||"allticks"===u.mirror)&&(rt+=J(P)+J(R)),a.xlines.style("stroke-width",u._lw+"px").call(l.stroke,u.showline?u.linecolor:"rgba(0,0,0,0)")),a.xlines.attr("d",rt);var nt="M0,0";k(d,i)&&(q=M(d,"bottom",u,y),N=d._offset+d._length+(q?m:0),H=M(d,"top",u,y),j=d._offset-(H?m:0),V=x(d,u,"left"),U=x(d,u,"right"),!(G=!d._anchorAxis||i!==d._mainSubplot)||"allticks"!==d.mirror&&"all"!==d.mirror||(d._linepositions[i]=[V,U]),nt=et(d,Q,tt),G&&d.showline&&("all"===d.mirror||"allticks"===d.mirror)&&(nt+=Q(V)+Q(U)),a.ylines.style("stroke-width",d._lw+"px").call(l.stroke,d.showline?d.linecolor:"rgba(0,0,0,0)")),a.ylines.attr("d",nt)}return f.makeClipPaths(t),t._promises.length&&Promise.all(t._promises)}function k(t,e){return(t.ticks||t.showline)&&(e===t._mainSubplot||"all"===t.mirror||"allticks"===t.mirror)}function A(t,e,r){if(!r.showline||!r._lw)return!1;if("all"===r.mirror||"allticks"===r.mirror)return!0;var n=r._anchorAxis;if(!n)return!1;var i=p.FROM_BL[e];return r.side===e?n.domain[i]===t.domain[i]:r.mirror&&n.domain[1-i]===t.domain[1-i]}function M(t,e,r,n){if(A(t,e,r))return r._lw;for(var i=0;i<n.length;i++){var a=n[i];if(a._mainAxis===r._mainAxis&&A(t,e,a))return a._lw}return 0}r.layoutStyles=function(t){return o.syncOrAsync([a.doAutoMargin,w],t)},r.drawMainTitle=function(t){var e=t._fullLayout,r=function(t){var e=t.title,r=x;o.isRightAnchor(e)?r=b:o.isLeftAnchor(e)&&(r=y);return r}(e),n=function(t){var e=t.title,r="0em";o.isTopAnchor(e)?r=p.CAP_SHIFT+"em":o.isMiddleAnchor(e)&&(r=p.MID_SHIFT+"em");return r}(e);u.draw(t,"gtitle",{propContainer:e,propName:"title.text",placeholder:e._dfltTitle.plot,attributes:{x:function(t,e){var r=t.title,n=t._size,i=0;e===y?i=r.pad.l:e===b&&(i=-r.pad.r);switch(r.xref){case"paper":return n.l+n.w*r.x+i;case"container":default:return t.width*r.x+i}}(e,r),y:function(t,e){var r=t.title,n=t._size,i=0;"0em"!==e&&e?e===p.CAP_SHIFT+"em"&&(i=r.pad.t):i=-r.pad.b;if("auto"===r.y)return n.t/2;switch(r.yref){case"paper":return n.t+n.h-n.h*r.y+i;case"container":default:return t.height-t.height*r.y+i}}(e,n),"text-anchor":r,dy:n}})},r.doTraceStyle=function(t){var e,n=t.calcdata,o=[];for(e=0;e<n.length;e++){var l=n[e],c=l[0]||{},u=c.trace||{},h=u._module||{},f=h.arraysToCalcdata;f&&f(l,u);var p=h.editStyle;p&&o.push({fn:p,cd0:c})}if(o.length){for(e=0;e<o.length;e++){var d=o[e];d.fn(t,d.cd0)}s(t),r.redrawReglTraces(t)}return a.style(t),i.getComponentMethod("legend","draw")(t),a.previousPromises(t)},r.doColorBars=function(t){for(var e=0;e<t.calcdata.length;e++){var r=t.calcdata[e][0];if((r.t||{}).cb){var n=r.trace,o=r.t.cb;i.traceIs(n,"contour")&&o.line({width:!1!==n.contours.showlines?n.line.width:0,dash:n.line.dash,color:"line"===n.contours.coloring?o._opts.line.color:n.line.color});var s=n._module.colorbar.container,l=(s?n[s]:n).colorbar;o.options(l)()}}return a.previousPromises(t)},r.layoutReplot=function(t){var e=t.layout;return t.layout=void 0,i.call("plot",t,"",e)},r.doLegend=function(t){return i.getComponentMethod("legend","draw")(t),a.previousPromises(t)},r.doTicksRelayout=function(t){return f.draw(t,"redraw"),t._fullLayout._hasOnlyLargeSploms&&(i.subplotsRegistry.splom.updateGrid(t),s(t),r.redrawReglTraces(t)),r.drawMainTitle(t),a.previousPromises(t)},r.doModeBar=function(t){var e=t._fullLayout;h.manage(t);for(var r=0;r<e._basePlotModules.length;r++){var n=e._basePlotModules[r].updateFx;n&&n(t)}return a.previousPromises(t)},r.doCamera=function(t){for(var e=t._fullLayout,r=e._subplots.gl3d,n=0;n<r.length;n++){var i=e[r[n]],a=i._scene,o=i.camera;a.setCamera(o)}},r.drawData=function(t){var e,n=t._fullLayout,o=t.calcdata;for(e=0;e<o.length;e++){var l=o[e][0].trace;!0===l.visible&&l._module.colorbar||n._infolayer.select(".cb"+l.uid).remove()}s(t);var c=n._basePlotModules;for(e=0;e<c.length;e++)c[e].plot(t);return r.redrawReglTraces(t),a.style(t),i.getComponentMethod("shapes","draw")(t),i.getComponentMethod("annotations","draw")(t),n._replotting=!1,a.previousPromises(t)},r.redrawReglTraces=function(t){var e=t._fullLayout;if(e._has("regl")){var r,n,i=t._fullData,a=[],s=[];for(e._hasOnlyLargeSploms&&e._splomGrid.draw(),r=0;r<i.length;r++){var l=i[r];!0===l.visible&&("splom"===l.type?e._splomScenes[l.uid].draw():"scattergl"===l.type?o.pushUnique(a,l.xaxis+l.yaxis):"scatterpolargl"===l.type&&o.pushUnique(s,l.subplot))}for(r=0;r<a.length;r++)(n=e._plots[a[r]])._scene&&n._scene.draw();for(r=0;r<s.length;r++)(n=e[s[r]]._subplot)._scene&&n._scene.draw()}},r.doAutoRangeAndConstraints=function(t){for(var e,r=t._fullLayout,n=f.list(t,"",!0),i=r._axisMatchGroups||[],a=0;a<n.length;a++)e=n[a],v(t,e),m(t,e);g(t);t:for(var o=0;o<i.length;o++){var s,l=i[o],c=null;for(s in l){if(!1===(e=f.getFromId(t,s)).autorange)continue t;c?c[0]<c[1]?(c[0]=Math.min(c[0],e.range[0]),c[1]=Math.max(c[1],e.range[1])):(c[0]=Math.max(c[0],e.range[0]),c[1]=Math.min(c[1],e.range[1])):c=e.range}for(s in l)(e=f.getFromId(t,s)).range=c.slice(),e._input.range=c.slice(),e.setScale()}},r.finalDraw=function(t){i.getComponentMethod("shapes","draw")(t),i.getComponentMethod("images","draw")(t),i.getComponentMethod("annotations","draw")(t),i.getComponentMethod("rangeslider","draw")(t),i.getComponentMethod("rangeselector","draw")(t)},r.drawMarginPushers=function(t){i.getComponentMethod("legend","draw")(t),i.getComponentMethod("rangeselector","draw")(t),i.getComponentMethod("sliders","draw")(t),i.getComponentMethod("updatemenus","draw")(t)}},{"../components/color":574,"../components/drawing":595,"../components/modebar":633,"../components/titles":662,"../constants/alignment":669,"../lib":697,"../lib/clear_gl_canvases":682,"../plots/cartesian/autorange":744,"../plots/cartesian/axes":745,"../plots/cartesian/constraints":752,"../plots/plots":807,"../registry":826,d3:151}],737:[function(t,e,r){"use strict";var n=t("../lib"),i=n.isPlainObject,a=t("./plot_schema"),o=t("../plots/plots"),s=t("../plots/attributes"),l=t("./plot_template"),c=t("./plot_config").dfltConfig;function u(t,e){t=n.extendDeep({},t);var r,a,o=Object.keys(t).sort();function s(e,r,n){if(i(r)&&i(e))u(e,r);else if(Array.isArray(r)&&Array.isArray(e)){var o=l.arrayTemplater({_template:t},n);for(a=0;a<r.length;a++){var s=r[a],c=o.newItem(s)._template;c&&u(c,s)}var h=o.defaultItems();for(a=0;a<h.length;a++)r.push(h[a]._template);for(a=0;a<r.length;a++)delete r[a].templateitemname}}for(r=0;r<o.length;r++){var c=o[r],f=t[c];if(c in e?s(f,e[c],c):e[c]=f,h(c)===c)for(var p in e){var d=h(p);p===d||d!==c||p in t||s(f,e[p],c)}}}function h(t){return t.replace(/[0-9]+$/,"")}function f(t,e,r,a,o){var s=o&&r(o);for(var c in t){var u=t[c],d=p(t,c,a),g=p(t,c,o),v=r(g);if(!v){var m=h(c);m!==c&&(v=r(g=p(t,m,o)))}if((!s||s!==v)&&!(!v||v._noTemplating||"data_array"===v.valType||v.arrayOk&&Array.isArray(u)))if(!v.valType&&i(u))f(u,e,r,d,g);else if(v._isLinkedToArray&&Array.isArray(u))for(var y=!1,x=0,b={},_=0;_<u.length;_++){var w=u[_];if(i(w)){var k=w.name;if(k)b[k]||(f(w,e,r,p(u,x,d),p(u,x,g)),x++,b[k]=1);else if(!y){var A=p(t,l.arrayDefaultKey(c),a),M=p(u,x,d);f(w,e,r,M,p(u,x,g));var T=n.nestedProperty(e,M);n.nestedProperty(e,A).set(T.get()),T.set(null),y=!0}}}else{n.nestedProperty(e,d).set(u)}}}function p(t,e,r){return r?Array.isArray(t)?r+"["+e+"]":r+"."+e:e}function d(t){for(var e=0;e<t.length;e++)if(i(t[e]))return!0}function g(t){var e;switch(t.code){case"data":e="The template has no key data.";break;case"layout":e="The template has no key layout.";break;case"missing":e=t.path?"There are no templates for item "+t.path+" with name "+t.templateitemname:"There are no templates for trace "+t.index+", of type "+t.traceType+".";break;case"unused":e=t.path?"The template item at "+t.path+" was not used in constructing the plot.":t.dataCount?"Some of the templates of type "+t.traceType+" were not used. The template has "+t.templateCount+" traces, the data only has "+t.dataCount+" of this type.":"The template has "+t.templateCount+" traces of type "+t.traceType+" but there are none in the data.";break;case"reused":e="Some of the templates of type "+t.traceType+" were used more than once. The template has "+t.templateCount+" traces, the data has "+t.dataCount+" of this type."}return t.msg=e,t}r.makeTemplate=function(t){t=n.isPlainObject(t)?t:n.getGraphDiv(t),t=n.extendDeep({_context:c},{data:t.data,layout:t.layout}),o.supplyDefaults(t);var e=t.data||[],r=t.layout||{};r._basePlotModules=t._fullLayout._basePlotModules,r._modules=t._fullLayout._modules;var l={data:{},layout:{}};e.forEach(function(t){var e={};f(t,e,function(t,e){return a.getTraceValObject(t,n.nestedProperty({},e).parts)}.bind(null,t));var r=n.coerce(t,{},s,"type"),i=l.data[r];i||(i=l.data[r]=[]),i.push(e)}),f(r,l.layout,function(t,e){return a.getLayoutValObject(t,n.nestedProperty({},e).parts)}.bind(null,r)),delete l.layout.template;var h=r.template;if(i(h)){var p,d,g,v,m,y,x=h.layout;i(x)&&u(x,l.layout);var b=h.data;if(i(b)){for(d in l.data)if(g=b[d],Array.isArray(g)){for(y=(m=l.data[d]).length,v=g.length,p=0;p<y;p++)u(g[p%v],m[p]);for(p=y;p<v;p++)m.push(n.extendDeep({},g[p]))}for(d in b)d in l.data||(l.data[d]=n.extendDeep([],b[d]))}}return l},r.validateTemplate=function(t,e){var r=n.extendDeep({},{_context:c,data:t.data,layout:t.layout}),a=r.layout||{};i(e)||(e=a.template||{});var s=e.layout,l=e.data,u=[];r.layout=a,r.layout.template=e,o.supplyDefaults(r);var f=r._fullLayout,v=r._fullData,m={};if(i(s)?(!function t(e,r){for(var n in e)if("_"!==n.charAt(0)&&i(e[n])){var a,o=h(n),s=[];for(a=0;a<r.length;a++)s.push(p(e,n,r[a])),o!==n&&s.push(p(e,o,r[a]));for(a=0;a<s.length;a++)m[s[a]]=1;t(e[n],s)}}(f,["layout"]),function t(e,r){for(var n in e)if(-1===n.indexOf("defaults")&&i(e[n])){var a=p(e,n,r);m[a]?t(e[n],a):u.push({code:"unused",path:a})}}(s,"layout")):u.push({code:"layout"}),i(l)){for(var y,x={},b=0;b<v.length;b++){var _=v[b];x[y=_.type]=(x[y]||0)+1,_._fullInput._template||u.push({code:"missing",index:_._fullInput.index,traceType:y})}for(y in l){var w=l[y].length,k=x[y]||0;w>k?u.push({code:"unused",traceType:y,templateCount:w,dataCount:k}):k>w&&u.push({code:"reused",traceType:y,templateCount:w,dataCount:k})}}else u.push({code:"data"});if(function t(e,r){for(var n in e)if("_"!==n.charAt(0)){var a=e[n],o=p(e,n,r);i(a)?(Array.isArray(e)&&!1===a._template&&a.templateitemname&&u.push({code:"missing",path:o,templateitemname:a.templateitemname}),t(a,o)):Array.isArray(a)&&d(a)&&t(a,o)}}({data:v,layout:f},""),u.length)return u.map(g)}},{"../lib":697,"../plots/attributes":742,"../plots/plots":807,"./plot_config":733,"./plot_schema":734,"./plot_template":735}],738:[function(t,e,r){"use strict";var n=t("./plot_api"),i=t("../lib"),a=t("../snapshot/helpers"),o=t("../snapshot/tosvg"),s=t("../snapshot/svgtoimg"),l={format:{valType:"enumerated",values:["png","jpeg","webp","svg"],dflt:"png"},width:{valType:"number",min:1},height:{valType:"number",min:1},scale:{valType:"number",min:0,dflt:1},setBackground:{valType:"any",dflt:!1},imageDataOnly:{valType:"boolean",dflt:!1}},c=/^data:image\/\w+;base64,/;e.exports=function(t,e){var r,u,h;function f(t){return!(t in e)||i.validate(e[t],l[t])}if(e=e||{},i.isPlainObject(t)?(r=t.data||[],u=t.layout||{},h=t.config||{}):(t=i.getGraphDiv(t),r=i.extendDeep([],t.data),u=i.extendDeep({},t.layout),h=t._context),!f("width")||!f("height"))throw new Error("Height and width should be pixel values.");if(!f("format"))throw new Error("Image format is not jpeg, png, svg or webp.");var p={};function d(t,r){return i.coerce(e,p,l,t,r)}var g=d("format"),v=d("width"),m=d("height"),y=d("scale"),x=d("setBackground"),b=d("imageDataOnly"),_=document.createElement("div");_.style.position="absolute",_.style.left="-5000px",document.body.appendChild(_);var w=i.extendFlat({},u);v&&(w.width=v),m&&(w.height=m);var k=i.extendFlat({},h,{_exportedPlot:!0,staticPlot:!0,setBackground:x}),A=a.getRedrawFunc(_);function M(){return new Promise(function(t){setTimeout(t,a.getDelay(_._fullLayout))})}function T(){return new Promise(function(t,e){var r=o(_,g,y),a=_._fullLayout.width,l=_._fullLayout.height;if(n.purge(_),document.body.removeChild(_),"svg"===g)return t(b?r:"data:image/svg+xml,"+encodeURIComponent(r));var c=document.createElement("canvas");c.id=i.randstr(),s({format:g,width:a,height:l,scale:y,canvas:c,svg:r,promise:!0}).then(t).catch(e)})}return new Promise(function(t,e){n.plot(_,r,w,k).then(A).then(M).then(T).then(function(e){t(function(t){return b?t.replace(c,""):t}(e))}).catch(function(t){e(t)})})}},{"../lib":697,"../snapshot/helpers":830,"../snapshot/svgtoimg":832,"../snapshot/tosvg":834,"./plot_api":732}],739:[function(t,e,r){"use strict";var n=t("../lib"),i=t("../plots/plots"),a=t("./plot_schema"),o=t("./plot_config").dfltConfig,s=n.isPlainObject,l=Array.isArray,c=n.isArrayOrTypedArray;function u(t,e,r,i,a,o){o=o||[];for(var h=Object.keys(t),f=0;f<h.length;f++){var v=h[f];if("transforms"!==v){var m=o.slice();m.push(v);var y=t[v],x=e[v],b=g(r,v),_="info_array"===(b||{}).valType,w="colorscale"===(b||{}).valType,k=(b||{}).items;if(d(r,v))if(s(y)&&s(x))u(y,x,b,i,a,m);else if(_&&l(y)){y.length>x.length&&i.push(p("unused",a,m.concat(x.length)));var A,M,T,S,E,C=x.length,L=Array.isArray(k);if(L&&(C=Math.min(C,k.length)),2===b.dimensions)for(M=0;M<C;M++)if(l(y[M])){y[M].length>x[M].length&&i.push(p("unused",a,m.concat(M,x[M].length)));var z=x[M].length;for(A=0;A<(L?Math.min(z,k[M].length):z);A++)T=L?k[M][A]:k,S=y[M][A],E=x[M][A],n.validate(S,T)?E!==S&&E!==+S&&i.push(p("dynamic",a,m.concat(M,A),S,E)):i.push(p("value",a,m.concat(M,A),S))}else i.push(p("array",a,m.concat(M),y[M]));else for(M=0;M<C;M++)T=L?k[M]:k,S=y[M],E=x[M],n.validate(S,T)?E!==S&&E!==+S&&i.push(p("dynamic",a,m.concat(M),S,E)):i.push(p("value",a,m.concat(M),S))}else if(b.items&&!_&&l(y)){var O,I,D=k[Object.keys(k)[0]],P=[];for(O=0;O<x.length;O++){var R=x[O]._index||O;if((I=m.slice()).push(R),s(y[R])&&s(x[O])){P.push(R);var F=y[R],B=x[O];s(F)&&!1!==F.visible&&!1===B.visible?i.push(p("invisible",a,I)):u(F,B,D,i,a,I)}}for(O=0;O<y.length;O++)(I=m.slice()).push(O),s(y[O])?-1===P.indexOf(O)&&i.push(p("unused",a,I)):i.push(p("object",a,I,y[O]))}else!s(y)&&s(x)?i.push(p("object",a,m,y)):c(y)||!c(x)||_||w?v in e?n.validate(y,b)?"enumerated"===b.valType&&(b.coerceNumber&&y!==+x||y!==x)&&i.push(p("dynamic",a,m,y,x)):i.push(p("value",a,m,y)):i.push(p("unused",a,m,y)):i.push(p("array",a,m,y));else i.push(p("schema",a,m))}}return i}e.exports=function(t,e){var r,c,h=a.get(),f=[],d={_context:n.extendFlat({},o)};l(t)?(d.data=n.extendDeep([],t),r=t):(d.data=[],r=[],f.push(p("array","data"))),s(e)?(d.layout=n.extendDeep({},e),c=e):(d.layout={},c={},arguments.length>1&&f.push(p("object","layout"))),i.supplyDefaults(d);for(var g=d._fullData,v=r.length,m=0;m<v;m++){var y=r[m],x=["data",m];if(s(y)){var b=g[m],_=b.type,w=h.traces[_].attributes;w.type={valType:"enumerated",values:[_]},!1===b.visible&&!1!==y.visible&&f.push(p("invisible",x)),u(y,b,w,f,x);var k=y.transforms,A=b.transforms;if(k){l(k)||f.push(p("array",x,["transforms"])),x.push("transforms");for(var M=0;M<k.length;M++){var T=["transforms",M],S=k[M].type;if(s(k[M])){var E=h.transforms[S]?h.transforms[S].attributes:{};E.type={valType:"enumerated",values:Object.keys(h.transforms)},u(k[M],A[M],E,f,x,T)}else f.push(p("object",x,T))}}}else f.push(p("object",x))}return u(c,d._fullLayout,function(t,e){for(var r=t.layout.layoutAttributes,i=0;i<e.length;i++){var a=e[i],o=t.traces[a.type],s=o.layoutAttributes;s&&(a.subplot?n.extendFlat(r[o.attributes.subplot.dflt],s):n.extendFlat(r,s))}return r}(h,g),f,"layout"),0===f.length?void 0:f};var h={object:function(t,e){return("layout"===t&&""===e?"The layout argument":"data"===t[0]&&""===e?"Trace "+t[1]+" in the data argument":f(t)+"key "+e)+" must be linked to an object container"},array:function(t,e){return("data"===t?"The data argument":f(t)+"key "+e)+" must be linked to an array container"},schema:function(t,e){return f(t)+"key "+e+" is not part of the schema"},unused:function(t,e,r){var n=s(r)?"container":"key";return f(t)+n+" "+e+" did not get coerced"},dynamic:function(t,e,r,n){return[f(t)+"key",e,"(set to '"+r+"')","got reset to","'"+n+"'","during defaults."].join(" ")},invisible:function(t,e){return(e?f(t)+"item "+e:"Trace "+t[1])+" got defaulted to be not visible"},value:function(t,e,r){return[f(t)+"key "+e,"is set to an invalid value ("+r+")"].join(" ")}};function f(t){return l(t)?"In data trace "+t[1]+", ":"In "+t+", "}function p(t,e,r,i,a){var o,s;r=r||"",l(e)?(o=e[0],s=e[1]):(o=e,s=null);var c=function(t){if(!l(t))return String(t);for(var e="",r=0;r<t.length;r++){var n=t[r];"number"==typeof n?e=e.substr(0,e.length-1)+"["+n+"]":e+=n,r<t.length-1&&(e+=".")}return e}(r),u=h[t](e,c,i,a);return n.log(u),{code:t,container:o,trace:s,path:r,astr:c,msg:u}}function d(t,e){var r=m(e),n=r.keyMinusId,i=r.id;return!!(n in t&&t[n]._isSubplotObj&&i)||e in t}function g(t,e){return e in t?t[e]:t[m(e).keyMinusId]}var v=n.counterRegex("([a-z]+)");function m(t){var e=t.match(v);return{keyMinusId:e&&e[1],id:e&&e[2]}}},{"../lib":697,"../plots/plots":807,"./plot_config":733,"./plot_schema":734}],740:[function(t,e,r){"use strict";e.exports={mode:{valType:"enumerated",dflt:"afterall",values:["immediate","next","afterall"]},direction:{valType:"enumerated",values:["forward","reverse"],dflt:"forward"},fromcurrent:{valType:"boolean",dflt:!1},frame:{duration:{valType:"number",min:0,dflt:500},redraw:{valType:"boolean",dflt:!0}},transition:{duration:{valType:"number",min:0,dflt:500,editType:"none"},easing:{valType:"enumerated",dflt:"cubic-in-out",values:["linear","quad","cubic","sin","exp","circle","elastic","back","bounce","linear-in","quad-in","cubic-in","sin-in","exp-in","circle-in","elastic-in","back-in","bounce-in","linear-out","quad-out","cubic-out","sin-out","exp-out","circle-out","elastic-out","back-out","bounce-out","linear-in-out","quad-in-out","cubic-in-out","sin-in-out","exp-in-out","circle-in-out","elastic-in-out","back-in-out","bounce-in-out"],editType:"none"},ordering:{valType:"enumerated",values:["layout first","traces first"],dflt:"layout first",editType:"none"}}}},{}],741:[function(t,e,r){"use strict";var n=t("../lib"),i=t("../plot_api/plot_template");e.exports=function(t,e,r){var a,o,s=r.name,l=r.inclusionAttr||"visible",c=e[s],u=n.isArrayOrTypedArray(t[s])?t[s]:[],h=e[s]=[],f=i.arrayTemplater(e,s,l);for(a=0;a<u.length;a++){var p=u[a];n.isPlainObject(p)?o=f.newItem(p):(o=f.newItem({}))[l]=!1,o._index=a,!1!==o[l]&&r.handleItemDefaults(p,o,e,r),h.push(o)}var d=f.defaultItems();for(a=0;a<d.length;a++)(o=d[a])._index=h.length,r.handleItemDefaults({},o,e,r,{}),h.push(o);if(n.isArrayOrTypedArray(c)){var g=Math.min(c.length,h.length);for(a=0;a<g;a++)n.relinkPrivateKeys(h[a],c[a])}return h}},{"../lib":697,"../plot_api/plot_template":735}],742:[function(t,e,r){"use strict";var n=t("../components/fx/attributes");e.exports={type:{valType:"enumerated",values:[],dflt:"scatter",editType:"calc+clearAxisTypes",_noTemplating:!0},visible:{valType:"enumerated",values:[!0,!1,"legendonly"],dflt:!0,editType:"calc"},showlegend:{valType:"boolean",dflt:!0,editType:"style"},legendgroup:{valType:"string",dflt:"",editType:"style"},opacity:{valType:"number",min:0,max:1,dflt:1,editType:"style"},name:{valType:"string",editType:"style"},uid:{valType:"string",editType:"plot",anim:!0},ids:{valType:"data_array",editType:"calc",anim:!0},customdata:{valType:"data_array",editType:"calc"},selectedpoints:{valType:"any",editType:"calc"},hoverinfo:{valType:"flaglist",flags:["x","y","z","text","name"],extras:["all","none","skip"],arrayOk:!0,dflt:"all",editType:"none"},hoverlabel:n.hoverlabel,stream:{token:{valType:"string",noBlank:!0,strict:!0,editType:"calc"},maxpoints:{valType:"number",min:0,max:1e4,dflt:500,editType:"calc"},editType:"calc"},transforms:{_isLinkedToArray:"transform",editType:"calc"},uirevision:{valType:"any",editType:"none"}}},{"../components/fx/attributes":604}],743:[function(t,e,r){"use strict";e.exports={xaxis:{valType:"subplotid",dflt:"x",editType:"calc+clearAxisTypes"},yaxis:{valType:"subplotid",dflt:"y",editType:"calc+clearAxisTypes"}}},{}],744:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("../../constants/numerical").FP_SAFE,o=t("../../registry");function s(t,e){var r,n,a=[],o=l(e),s=c(t,e),u=s.min,h=s.max;if(0===u.length||0===h.length)return i.simpleMap(e.range,e.r2l);var f=u[0].val,p=h[0].val;for(r=1;r<u.length&&f===p;r++)f=Math.min(f,u[r].val);for(r=1;r<h.length&&f===p;r++)p=Math.max(p,h[r].val);var d=!1;if(e.range){var g=i.simpleMap(e.range,e.r2l);d=g[1]<g[0]}"reversed"===e.autorange&&(d=!0,e.autorange=!0);var v,m,y,x,b,_,w=e.rangemode,k="tozero"===w,A="nonnegative"===w,M=e._length,T=M/10,S=0;for(r=0;r<u.length;r++)for(v=u[r],n=0;n<h.length;n++)(_=(m=h[n]).val-v.val)>0&&((b=M-o(v)-o(m))>T?_/b>S&&(y=v,x=m,S=_/b):_/M>S&&(y={val:v.val,pad:0},x={val:m.val,pad:0},S=_/M));if(f===p){var E=f-1,C=f+1;if(k)if(0===f)a=[0,1];else{var L=(f>0?h:u).reduce(function(t,e){return Math.max(t,o(e))},0),z=f/(1-Math.min(.5,L/M));a=f>0?[0,z]:[z,0]}else a=A?[Math.max(0,E),Math.max(1,C)]:[E,C]}else k?(y.val>=0&&(y={val:0,pad:0}),x.val<=0&&(x={val:0,pad:0})):A&&(y.val-S*o(y)<0&&(y={val:0,pad:0}),x.val<=0&&(x={val:1,pad:0})),S=(x.val-y.val)/(M-o(y)-o(x)),a=[y.val-S*o(y),x.val+S*o(x)];return d&&a.reverse(),i.simpleMap(a,e.l2r||Number)}function l(t){var e=t._length/20;return"domain"===t.constrain&&t._inputDomain&&(e*=(t._inputDomain[1]-t._inputDomain[0])/(t.domain[1]-t.domain[0])),function(t){return t.pad+(t.extrapad?e:0)}}function c(t,e){var r,n,i,a=e._id,o=t._fullData,s=t._fullLayout,l=[],c=[];function f(t,e){for(r=0;r<e.length;r++){var o=t[e[r]],s=(o._extremes||{})[a];if(!0===o.visible&&s){for(n=0;n<s.min.length;n++)i=s.min[n],u(l,i.val,i.pad,{extrapad:i.extrapad});for(n=0;n<s.max.length;n++)i=s.max[n],h(c,i.val,i.pad,{extrapad:i.extrapad})}}}return f(o,e._traceIndices),f(s.annotations||[],e._annIndices||[]),f(s.shapes||[],e._shapeIndices||[]),{min:l,max:c}}function u(t,e,r,n){f(t,e,r,n,d)}function h(t,e,r,n){f(t,e,r,n,g)}function f(t,e,r,n,i){for(var a=n.tozero,o=n.extrapad,s=!0,l=0;l<t.length&&s;l++){var c=t[l];if(i(c.val,e)&&c.pad>=r&&(c.extrapad||!o)){s=!1;break}i(e,c.val)&&c.pad<=r&&(o||!c.extrapad)&&(t.splice(l,1),l--)}if(s){var u=a&&0===e;t.push({val:e,pad:u?0:r,extrapad:!u&&o})}}function p(t){return n(t)&&Math.abs(t)<a}function d(t,e){return t<=e}function g(t,e){return t>=e}e.exports={getAutoRange:s,makePadFn:l,doAutoRange:function(t,e){if(e.setScale(),e.autorange){e.range=s(t,e),e._r=e.range.slice(),e._rl=i.simpleMap(e._r,e.r2l);var r=e._input,n={};n[e._attr+".range"]=e.range,n[e._attr+".autorange"]=e.autorange,o.call("_storeDirectGUIEdit",t.layout,t._fullLayout._preGUI,n),r.range=e.range.slice(),r.autorange=e.autorange}var a=e._anchorAxis;if(a&&a.rangeslider){var l=a.rangeslider[e._name];l&&"auto"===l.rangemode&&(l.range=s(t,e)),a._input.rangeslider[e._name]=i.extendFlat({},l)}},findExtremes:function(t,e,r){r||(r={});t._m||t.setScale();var i,o,s,l,c,f,d,g,v,m=[],y=[],x=e.length,b=r.padded||!1,_=r.tozero&&("linear"===t.type||"-"===t.type),w="log"===t.type,k=!1;function A(t){if(Array.isArray(t))return k=!0,function(e){return Math.max(Number(t[e]||0),0)};var e=Math.max(Number(t||0),0);return function(){return e}}var M=A((t._m>0?r.ppadplus:r.ppadminus)||r.ppad||0),T=A((t._m>0?r.ppadminus:r.ppadplus)||r.ppad||0),S=A(r.vpadplus||r.vpad),E=A(r.vpadminus||r.vpad);if(!k){if(g=1/0,v=-1/0,w)for(i=0;i<x;i++)(o=e[i])<g&&o>0&&(g=o),o>v&&o<a&&(v=o);else for(i=0;i<x;i++)(o=e[i])<g&&o>-a&&(g=o),o>v&&o<a&&(v=o);e=[g,v],x=2}var C={tozero:_,extrapad:b};function L(r){s=e[r],n(s)&&(f=M(r),d=T(r),g=s-E(r),v=s+S(r),w&&g<v/10&&(g=v/10),l=t.c2l(g),c=t.c2l(v),_&&(l=Math.min(0,l),c=Math.max(0,c)),p(l)&&u(m,l,d,C),p(c)&&h(y,c,f,C))}var z=Math.min(6,x);for(i=0;i<z;i++)L(i);for(i=x-1;i>=z;i--)L(i);return{min:m,max:y,opts:r}},concatExtremes:c}},{"../../constants/numerical":674,"../../lib":697,"../../registry":826,"fast-isnumeric":218}],745:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../../plots/plots"),o=t("../../registry"),s=t("../../lib"),l=t("../../lib/svg_text_utils"),c=t("../../components/titles"),u=t("../../components/color"),h=t("../../components/drawing"),f=t("./layout_attributes"),p=t("./clean_ticks"),d=t("../../constants/numerical"),g=d.ONEAVGYEAR,v=d.ONEAVGMONTH,m=d.ONEDAY,y=d.ONEHOUR,x=d.ONEMIN,b=d.ONESEC,_=d.MINUS_SIGN,w=d.BADNUM,k=t("../../constants/alignment").MID_SHIFT,A=t("../../constants/alignment").LINE_SPACING,M=e.exports={};M.setConvert=t("./set_convert");var T=t("./axis_autotype"),S=t("./axis_ids");M.id2name=S.id2name,M.name2id=S.name2id,M.cleanId=S.cleanId,M.list=S.list,M.listIds=S.listIds,M.getFromId=S.getFromId,M.getFromTrace=S.getFromTrace;var E=t("./autorange");M.getAutoRange=E.getAutoRange,M.findExtremes=E.findExtremes,M.coerceRef=function(t,e,r,n,i,a){var o=n.charAt(n.length-1),l=r._fullLayout._subplots[o+"axis"],c=n+"ref",u={};return i||(i=l[0]||a),a||(a=i),u[c]={valType:"enumerated",values:l.concat(a?[a]:[]),dflt:i},s.coerce(t,e,u,c)},M.coercePosition=function(t,e,r,n,i,a){var o,l;if("paper"===n||"pixel"===n)o=s.ensureNumber,l=r(i,a);else{var c=M.getFromId(e,n);l=r(i,a=c.fraction2r(a)),o=c.cleanPos}t[i]=o(l)},M.cleanPosition=function(t,e,r){return("paper"===r||"pixel"===r?s.ensureNumber:M.getFromId(e,r).cleanPos)(t)},M.redrawComponents=function(t,e){e=e||M.listIds(t);var r=t._fullLayout;function n(n,i,a,s){for(var l=o.getComponentMethod(n,i),c={},u=0;u<e.length;u++)for(var h=r[M.id2name(e[u])][a],f=0;f<h.length;f++){var p=h[f];if(!c[p]&&(l(t,p),c[p]=1,s))return}}n("annotations","drawOne","_annIndices"),n("shapes","drawOne","_shapeIndices"),n("images","draw","_imgIndices",!0)};var C=M.getDataConversions=function(t,e,r,n){var i,a="x"===r||"y"===r||"z"===r?r:n;if(Array.isArray(a)){if(i={type:T(n),_categories:[]},M.setConvert(i),"category"===i.type)for(var o=0;o<n.length;o++)i.d2c(n[o])}else i=M.getFromTrace(t,e,a);return i?{d2c:i.d2c,c2d:i.c2d}:"ids"===a?{d2c:z,c2d:z}:{d2c:L,c2d:L}};function L(t){return+t}function z(t){return String(t)}M.getDataToCoordFunc=function(t,e,r,n){return C(t,e,r,n).d2c},M.counterLetter=function(t){var e=t.charAt(0);return"x"===e?"y":"y"===e?"x":void 0},M.minDtick=function(t,e,r,n){-1===["log","category","multicategory"].indexOf(t.type)&&n?void 0===t._minDtick?(t._minDtick=e,t._forceTick0=r):t._minDtick&&((t._minDtick/e+1e-6)%1<2e-6&&((r-t._forceTick0)/e%1+1.000001)%1<2e-6?(t._minDtick=e,t._forceTick0=r):((e/t._minDtick+1e-6)%1>2e-6||((r-t._forceTick0)/t._minDtick%1+1.000001)%1>2e-6)&&(t._minDtick=0)):t._minDtick=0},M.saveRangeInitial=function(t,e){for(var r=M.list(t,"",!0),n=!1,i=0;i<r.length;i++){var a=r[i],o=void 0===a._rangeInitial,s=o||!(a.range[0]===a._rangeInitial[0]&&a.range[1]===a._rangeInitial[1]);(o&&!1===a.autorange||e&&s)&&(a._rangeInitial=a.range.slice(),n=!0)}return n},M.saveShowSpikeInitial=function(t,e){for(var r=M.list(t,"",!0),n=!1,i="on",a=0;a<r.length;a++){var o=r[a],s=void 0===o._showSpikeInitial,l=s||!(o.showspikes===o._showspikes);(s||e&&l)&&(o._showSpikeInitial=o.showspikes,n=!0),"on"!==i||o.showspikes||(i="off")}return t._fullLayout._cartesianSpikesEnabled=i,n},M.autoBin=function(t,e,r,n,a,o){var l,c=s.aggNums(Math.min,null,t),u=s.aggNums(Math.max,null,t);if("category"===e.type||"multicategory"===e.type)return{start:c-.5,end:u+.5,size:Math.max(1,Math.round(o)||1),_dataSpan:u-c};if(a||(a=e.calendar),l="log"===e.type?{type:"linear",range:[c,u]}:{type:e.type,range:s.simpleMap([c,u],e.c2r,0,a),calendar:a},M.setConvert(l),o=o&&p.dtick(o,l.type))l.dtick=o,l.tick0=p.tick0(void 0,l.type,a);else{var h;if(r)h=(u-c)/r;else{var f=s.distinctVals(t),d=Math.pow(10,Math.floor(Math.log(f.minDiff)/Math.LN10)),g=d*s.roundUp(f.minDiff/d,[.9,1.9,4.9,9.9],!0);h=Math.max(g,2*s.stdev(t)/Math.pow(t.length,n?.25:.4)),i(h)||(h=1)}M.autoTicks(l,h)}var v,y=l.dtick,x=M.tickIncrement(M.tickFirst(l),y,"reverse",a);if("number"==typeof y)v=(x=function(t,e,r,n,a){var o=0,s=0,l=0,c=0;function u(e){return(1+100*(e-t)/r.dtick)%100<2}for(var h=0;h<e.length;h++)e[h]%1==0?l++:i(e[h])||c++,u(e[h])&&o++,u(e[h]+r.dtick/2)&&s++;var f=e.length-c;if(l===f&&"date"!==r.type)r.dtick<1?t=n-.5*r.dtick:(t-=.5)+r.dtick<n&&(t+=r.dtick);else if(s<.1*f&&(o>.3*f||u(n)||u(a))){var p=r.dtick/2;t+=t+p<n?p:-p}return t}(x,t,l,c,u))+(1+Math.floor((u-x)/y))*y;else for("M"===l.dtick.charAt(0)&&(x=function(t,e,r,n,i){var a=s.findExactDates(e,i);if(a.exactDays>.8){var o=Number(r.substr(1));a.exactYears>.8&&o%12==0?t=M.tickIncrement(t,"M6","reverse")+1.5*m:a.exactMonths>.8?t=M.tickIncrement(t,"M1","reverse")+15.5*m:t-=m/2;var l=M.tickIncrement(t,r);if(l<=n)return l}return t}(x,t,y,c,a)),v=x,0;v<=u;)v=M.tickIncrement(v,y,!1,a),0;return{start:e.c2r(x,0,a),end:e.c2r(v,0,a),size:y,_dataSpan:u-c}},M.prepTicks=function(t){var e=s.simpleMap(t.range,t.r2l);if("auto"===t.tickmode||!t.dtick){var r,n=t.nticks;n||("category"===t.type||"multicategory"===t.type?(r=t.tickfont?1.2*(t.tickfont.size||12):15,n=t._length/r):(r="y"===t._id.charAt(0)?40:80,n=s.constrain(t._length/r,4,9)+1),"radialaxis"===t._name&&(n*=2)),"array"===t.tickmode&&(n*=100),M.autoTicks(t,Math.abs(e[1]-e[0])/n),t._minDtick>0&&t.dtick<2*t._minDtick&&(t.dtick=t._minDtick,t.tick0=t.l2r(t._forceTick0))}t.tick0||(t.tick0="date"===t.type?"2000-01-01":0),"date"===t.type&&t.dtick<.1&&(t.dtick=.1),j(t)},M.calcTicks=function(t){M.prepTicks(t);var e=s.simpleMap(t.range,t.r2l);if("array"===t.tickmode)return function(t){var e=t.tickvals,r=t.ticktext,n=new Array(e.length),i=s.simpleMap(t.range,t.r2l),a=1.0001*i[0]-1e-4*i[1],o=1.0001*i[1]-1e-4*i[0],l=Math.min(a,o),c=Math.max(a,o),u=0;Array.isArray(r)||(r=[]);var h="category"===t.type?t.d2l_noadd:t.d2l;"log"===t.type&&"L"!==String(t.dtick).charAt(0)&&(t.dtick="L"+Math.pow(10,Math.floor(Math.min(t.range[0],t.range[1]))-1));for(var f=0;f<e.length;f++){var p=h(e[f]);p>l&&p<c&&(void 0===r[f]?n[u]=M.tickText(t,p):n[u]=V(t,p,String(r[f])),u++)}u<e.length&&n.splice(u,e.length-u);return n}(t);t._tmin=M.tickFirst(t);var r=1.0001*e[0]-1e-4*e[1],n=1.0001*e[1]-1e-4*e[0],i=e[1]<e[0];if(t._tmin<r!==i)return[];var a=[];"category"!==t.type&&"multicategory"!==t.type||(n=i?Math.max(-.5,n):Math.min(t._categories.length-.5,n));for(var o=null,l=Math.max(1e3,t._length||0),c=t._tmin;(i?c>=n:c<=n)&&!(a.length>l||c===o);c=M.tickIncrement(c,t.dtick,i,t.calendar))o=c,a.push(c);rt(t)&&360===Math.abs(e[1]-e[0])&&a.pop(),t._tmax=a[a.length-1],t._prevDateHead="",t._inCalcTicks=!0;for(var u=new Array(a.length),h=0;h<a.length;h++)u[h]=M.tickText(t,a[h]);return t._inCalcTicks=!1,u};var O=[2,5,10],I=[1,2,3,6,12],D=[1,2,5,10,15,30],P=[1,2,3,7,14],R=[-.046,0,.301,.477,.602,.699,.778,.845,.903,.954,1],F=[-.301,0,.301,.699,1],B=[15,30,45,90,180];function N(t,e,r){return e*s.roundUp(t/e,r)}function j(t){var e=t.dtick;if(t._tickexponent=0,i(e)||"string"==typeof e||(e=1),"category"!==t.type&&"multicategory"!==t.type||(t._tickround=null),"date"===t.type){var r=t.r2l(t.tick0),n=t.l2r(r).replace(/(^-|i)/g,""),a=n.length;if("M"===String(e).charAt(0))a>10||"01-01"!==n.substr(5)?t._tickround="d":t._tickround=+e.substr(1)%12==0?"y":"m";else if(e>=m&&a<=10||e>=15*m)t._tickround="d";else if(e>=x&&a<=16||e>=y)t._tickround="M";else if(e>=b&&a<=19||e>=x)t._tickround="S";else{var o=t.l2r(r+e).replace(/^-/,"").length;t._tickround=Math.max(a,o)-20,t._tickround<0&&(t._tickround=4)}}else if(i(e)||"L"===e.charAt(0)){var s=t.range.map(t.r2d||Number);i(e)||(e=Number(e.substr(1))),t._tickround=2-Math.floor(Math.log(e)/Math.LN10+.01);var l=Math.max(Math.abs(s[0]),Math.abs(s[1])),c=Math.floor(Math.log(l)/Math.LN10+.01);Math.abs(c)>3&&(q(t.exponentformat)&&!H(c)?t._tickexponent=3*Math.round((c-1)/3):t._tickexponent=c)}else t._tickround=null}function V(t,e,r){var n=t.tickfont||{};return{x:e,dx:0,dy:0,text:r||"",fontSize:n.size,font:n.family,fontColor:n.color}}M.autoTicks=function(t,e){var r;function n(t){return Math.pow(t,Math.floor(Math.log(e)/Math.LN10))}if("date"===t.type){t.tick0=s.dateTick0(t.calendar);var a=2*e;a>g?(e/=g,r=n(10),t.dtick="M"+12*N(e,r,O)):a>v?(e/=v,t.dtick="M"+N(e,1,I)):a>m?(t.dtick=N(e,m,P),t.tick0=s.dateTick0(t.calendar,!0)):a>y?t.dtick=N(e,y,I):a>x?t.dtick=N(e,x,D):a>b?t.dtick=N(e,b,D):(r=n(10),t.dtick=N(e,r,O))}else if("log"===t.type){t.tick0=0;var o=s.simpleMap(t.range,t.r2l);if(e>.7)t.dtick=Math.ceil(e);else if(Math.abs(o[1]-o[0])<1){var l=1.5*Math.abs((o[1]-o[0])/e);e=Math.abs(Math.pow(10,o[1])-Math.pow(10,o[0]))/l,r=n(10),t.dtick="L"+N(e,r,O)}else t.dtick=e>.3?"D2":"D1"}else"category"===t.type||"multicategory"===t.type?(t.tick0=0,t.dtick=Math.ceil(Math.max(e,1))):rt(t)?(t.tick0=0,r=1,t.dtick=N(e,r,B)):(t.tick0=0,r=n(10),t.dtick=N(e,r,O));if(0===t.dtick&&(t.dtick=1),!i(t.dtick)&&"string"!=typeof t.dtick){var c=t.dtick;throw t.dtick=1,"ax.dtick error: "+String(c)}},M.tickIncrement=function(t,e,r,a){var o=r?-1:1;if(i(e))return t+o*e;var l=e.charAt(0),c=o*Number(e.substr(1));if("M"===l)return s.incrementMonth(t,c,a);if("L"===l)return Math.log(Math.pow(10,t)+c)/Math.LN10;if("D"===l){var u="D2"===e?F:R,h=t+.01*o,f=s.roundUp(s.mod(h,1),u,r);return Math.floor(h)+Math.log(n.round(Math.pow(10,f),1))/Math.LN10}throw"unrecognized dtick "+String(e)},M.tickFirst=function(t){var e=t.r2l||Number,r=s.simpleMap(t.range,e),a=r[1]<r[0],o=a?Math.floor:Math.ceil,l=1.0001*r[0]-1e-4*r[1],c=t.dtick,u=e(t.tick0);if(i(c)){var h=o((l-u)/c)*c+u;return"category"!==t.type&&"multicategory"!==t.type||(h=s.constrain(h,0,t._categories.length-1)),h}var f=c.charAt(0),p=Number(c.substr(1));if("M"===f){for(var d,g,v,m=0,y=u;m<10;){if(((d=M.tickIncrement(y,c,a,t.calendar))-l)*(y-l)<=0)return a?Math.min(y,d):Math.max(y,d);g=(l-(y+d)/2)/(d-y),v=f+(Math.abs(Math.round(g))||1)*p,y=M.tickIncrement(y,v,g<0?!a:a,t.calendar),m++}return s.error("tickFirst did not converge",t),y}if("L"===f)return Math.log(o((Math.pow(10,l)-u)/p)*p+u)/Math.LN10;if("D"===f){var x="D2"===c?F:R,b=s.roundUp(s.mod(l,1),x,a);return Math.floor(l)+Math.log(n.round(Math.pow(10,b),1))/Math.LN10}throw"unrecognized dtick "+String(c)},M.tickText=function(t,e,r){var n,a=V(t,e),o="array"===t.tickmode,l=r||o,c=t.type,u="category"===c?t.d2l_noadd:t.d2l;if(o&&Array.isArray(t.ticktext)){var h=s.simpleMap(t.range,t.r2l),f=Math.abs(h[1]-h[0])/1e4;for(n=0;n<t.ticktext.length&&!(Math.abs(e-u(t.tickvals[n]))<f);n++);if(n<t.ticktext.length)return a.text=String(t.ticktext[n]),a}function p(n){if(void 0===n)return!0;if(r)return"none"===n;var i={first:t._tmin,last:t._tmax}[n];return"all"!==n&&e!==i}var d=r?"never":"none"!==t.exponentformat&&p(t.showexponent)?"hide":"";if("date"===c?function(t,e,r,n){var a=t._tickround,o=r&&t.hoverformat||M.getTickFormat(t);n&&(a=i(a)?4:{y:"m",m:"d",d:"M",M:"S",S:4}[a]);var l,c=s.formatDate(e.x,o,a,t._dateFormat,t.calendar,t._extraFormat),u=c.indexOf("\n");-1!==u&&(l=c.substr(u+1),c=c.substr(0,u));n&&("00:00:00"===c||"00:00"===c?(c=l,l=""):8===c.length&&(c=c.replace(/:00$/,"")));l&&(r?"d"===a?c+=", "+l:c=l+(c?", "+c:""):t._inCalcTicks&&l===t._prevDateHead||(c+="<br>"+l,t._prevDateHead=l));e.text=c}(t,a,r,l):"log"===c?function(t,e,r,n,a){var o=t.dtick,l=e.x,c=t.tickformat,u="string"==typeof o&&o.charAt(0);"never"===a&&(a="");n&&"L"!==u&&(o="L3",u="L");if(c||"L"===u)e.text=G(Math.pow(10,l),t,a,n);else if(i(o)||"D"===u&&s.mod(l+.01,1)<.1){var h=Math.round(l),f=Math.abs(h),p=t.exponentformat;"power"===p||q(p)&&H(h)?(e.text=0===h?1:1===h?"10":"10<sup>"+(h>1?"":_)+f+"</sup>",e.fontSize*=1.25):("e"===p||"E"===p)&&f>2?e.text="1"+p+(h>0?"+":_)+f:(e.text=G(Math.pow(10,l),t,"","fakehover"),"D1"===o&&"y"===t._id.charAt(0)&&(e.dy-=e.fontSize/6))}else{if("D"!==u)throw"unrecognized dtick "+String(o);e.text=String(Math.round(Math.pow(10,s.mod(l,1)))),e.fontSize*=.75}if("D1"===t.dtick){var d=String(e.text).charAt(0);"0"!==d&&"1"!==d||("y"===t._id.charAt(0)?e.dx-=e.fontSize/4:(e.dy+=e.fontSize/2,e.dx+=(t.range[1]>t.range[0]?1:-1)*e.fontSize*(l<0?.5:.25)))}}(t,a,0,l,d):"category"===c?function(t,e){var r=t._categories[Math.round(e.x)];void 0===r&&(r="");e.text=String(r)}(t,a):"multicategory"===c?function(t,e,r){var n=Math.round(e.x),i=t._categories[n]||[],a=void 0===i[1]?"":String(i[1]),o=void 0===i[0]?"":String(i[0]);r?e.text=o+" - "+a:(e.text=a,e.text2=o)}(t,a,r):rt(t)?function(t,e,r,n,i){if("radians"!==t.thetaunit||r)e.text=G(e.x,t,i,n);else{var a=e.x/180;if(0===a)e.text="0";else{var o=function(t){function e(t,e){return Math.abs(t-e)<=1e-6}var r=function(t){var r=1;for(;!e(Math.round(t*r)/r,t);)r*=10;return r}(t),n=t*r,i=Math.abs(function t(r,n){return e(n,0)?r:t(n,r%n)}(n,r));return[Math.round(n/i),Math.round(r/i)]}(a);if(o[1]>=100)e.text=G(s.deg2rad(e.x),t,i,n);else{var l=e.x<0;1===o[1]?1===o[0]?e.text="\u03c0":e.text=o[0]+"\u03c0":e.text=["<sup>",o[0],"</sup>","\u2044","<sub>",o[1],"</sub>","\u03c0"].join(""),l&&(e.text=_+e.text)}}}}(t,a,r,l,d):function(t,e,r,n,i){"never"===i?i="":"all"===t.showexponent&&Math.abs(e.x/t.dtick)<1e-6&&(i="hide");e.text=G(e.x,t,i,n)}(t,a,0,l,d),t.tickprefix&&!p(t.showtickprefix)&&(a.text=t.tickprefix+a.text),t.ticksuffix&&!p(t.showticksuffix)&&(a.text+=t.ticksuffix),"boundaries"===t.tickson||t.showdividers){var g=function(e){var r=t.l2p(e);return r>=0&&r<=t._length?e:null};a.xbnd=[g(a.x-.5),g(a.x+t.dtick-.5)]}return a},M.hoverLabelText=function(t,e,r){if(r!==w&&r!==e)return M.hoverLabelText(t,e)+" - "+M.hoverLabelText(t,r);var n="log"===t.type&&e<=0,i=M.tickText(t,t.c2l(n?-e:e),"hover").text;return n?0===e?"0":_+i:i};var U=["f","p","n","\u03bc","m","","k","M","G","T"];function q(t){return"SI"===t||"B"===t}function H(t){return t>14||t<-15}function G(t,e,r,n){var a=t<0,o=e._tickround,l=r||e.exponentformat||"B",c=e._tickexponent,u=M.getTickFormat(e),h=e.separatethousands;if(n){var f={exponentformat:l,dtick:"none"===e.showexponent?e.dtick:i(t)&&Math.abs(t)||1,range:"none"===e.showexponent?e.range.map(e.r2d):[0,t||1]};j(f),o=(Number(f._tickround)||0)+4,c=f._tickexponent,e.hoverformat&&(u=e.hoverformat)}if(u)return e._numFormat(u)(t).replace(/-/g,_);var p,d=Math.pow(10,-o)/2;if("none"===l&&(c=0),(t=Math.abs(t))<d)t="0",a=!1;else{if(t+=d,c&&(t*=Math.pow(10,-c),o+=c),0===o)t=String(Math.floor(t));else if(o<0){t=(t=String(Math.round(t))).substr(0,t.length+o);for(var g=o;g<0;g++)t+="0"}else{var v=(t=String(t)).indexOf(".")+1;v&&(t=t.substr(0,v+o).replace(/\.?0+$/,""))}t=s.numSeparate(t,e._separators,h)}c&&"hide"!==l&&(q(l)&&H(c)&&(l="power"),p=c<0?_+-c:"power"!==l?"+"+c:String(c),"e"===l||"E"===l?t+=l+p:"power"===l?t+="\xd710<sup>"+p+"</sup>":"B"===l&&9===c?t+="B":q(l)&&(t+=U[c/3+5]));return a?_+t:t}function Y(t,e){var r=t._id.charAt(0),n=t._tickAngles[e]||0,i=s.deg2rad(n),a=Math.sin(i),o=Math.cos(i),l=0,c=0;return t._selections[e].each(function(){var t=$(this),e=h.bBox(t.node()),r=e.width,n=e.height;l=Math.max(l,o*r,a*n),c=Math.max(c,a*r,o*n)}),{x:c,y:l}[r]}function W(t){return[t.text,t.x,t.axInfo,t.font,t.fontSize,t.fontColor].join("_")}function X(t,e){var r,n=t._fullLayout._size,i=e._id.charAt(0),a=e.side;return"free"!==e.anchor?r=S.getFromId(t,e.anchor):"x"===i?r={_offset:n.t+(1-(e.position||0))*n.h,_length:0}:"y"===i&&(r={_offset:n.l+(e.position||0)*n.w,_length:0}),"top"===a||"left"===a?r._offset:"bottom"===a||"right"===a?r._offset+r._length:void 0}function Z(t,e){var r=t.l2p(e);return r>1&&r<t._length-1}function $(t){var e=n.select(t),r=e.select(".text-math-group");return r.empty()?e.select("text"):r}function J(t){return t._id+".automargin"}function K(t){return t._id+".rangeslider"}function Q(t,e){for(var r=0;r<e.length;r++)-1===t.indexOf(e[r])&&t.push(e[r])}function tt(t,e,r){var n,i,a=[],o=[],l=t.layout;for(n=0;n<e.length;n++)a.push(M.getFromId(t,e[n]));for(n=0;n<r.length;n++)o.push(M.getFromId(t,r[n]));var c=Object.keys(f),u=["anchor","domain","overlaying","position","side","tickangle","editType"],h=["linear","log"];for(n=0;n<c.length;n++){var p=c[n],d=a[0][p],g=o[0][p],v=!0,m=!1,y=!1;if("_"!==p.charAt(0)&&"function"!=typeof d&&-1===u.indexOf(p)){for(i=1;i<a.length&&v;i++){var x=a[i][p];"type"===p&&-1!==h.indexOf(d)&&-1!==h.indexOf(x)&&d!==x?m=!0:x!==d&&(v=!1)}for(i=1;i<o.length&&v;i++){var b=o[i][p];"type"===p&&-1!==h.indexOf(g)&&-1!==h.indexOf(b)&&g!==b?y=!0:o[i][p]!==g&&(v=!1)}v&&(m&&(l[a[0]._name].type="linear"),y&&(l[o[0]._name].type="linear"),et(l,p,a,o,t._fullLayout._dfltTitle))}}for(n=0;n<t._fullLayout.annotations.length;n++){var _=t._fullLayout.annotations[n];-1!==e.indexOf(_.xref)&&-1!==r.indexOf(_.yref)&&s.swapAttrs(l.annotations[n],["?"])}}function et(t,e,r,n,i){var a,o=s.nestedProperty,l=o(t[r[0]._name],e).get(),c=o(t[n[0]._name],e).get();for("title"===e&&(l&&l.text===i.x&&(l.text=i.y),c&&c.text===i.y&&(c.text=i.x)),a=0;a<r.length;a++)o(t,r[a]._name+"."+e).set(c);for(a=0;a<n.length;a++)o(t,n[a]._name+"."+e).set(l)}function rt(t){return"angularaxis"===t._id}M.getTickFormat=function(t){var e,r,n,i,a,o,s,l;function c(t){return"string"!=typeof t?t:Number(t.replace("M",""))*v}function u(t,e){var r=["L","D"];if(typeof t==typeof e){if("number"==typeof t)return t-e;var n=r.indexOf(t.charAt(0)),i=r.indexOf(e.charAt(0));return n===i?Number(t.replace(/(L|D)/g,""))-Number(e.replace(/(L|D)/g,"")):n-i}return"number"==typeof t?1:-1}function h(t,e){var r=null===e[0],n=null===e[1],i=u(t,e[0])>=0,a=u(t,e[1])<=0;return(r||i)&&(n||a)}if(t.tickformatstops&&t.tickformatstops.length>0)switch(t.type){case"date":case"linear":for(e=0;e<t.tickformatstops.length;e++)if((n=t.tickformatstops[e]).enabled&&(i=t.dtick,a=n.dtickrange,o=void 0,void 0,void 0,o=c||function(t){return t},s=a[0],l=a[1],(!s&&"number"!=typeof s||o(s)<=o(i))&&(!l&&"number"!=typeof l||o(l)>=o(i)))){r=n;break}break;case"log":for(e=0;e<t.tickformatstops.length;e++)if((n=t.tickformatstops[e]).enabled&&h(t.dtick,n.dtickrange)){r=n;break}}return r?r.value:t.tickformat},M.getSubplots=function(t,e){var r=t._fullLayout._subplots,n=r.cartesian.concat(r.gl2d||[]),i=e?M.findSubplotsWithAxis(n,e):n;return i.sort(function(t,e){var r=t.substr(1).split("y"),n=e.substr(1).split("y");return r[0]===n[0]?+r[1]-+n[1]:+r[0]-+n[0]}),i},M.findSubplotsWithAxis=function(t,e){for(var r=new RegExp("x"===e._id.charAt(0)?"^"+e._id+"y":e._id+"$"),n=[],i=0;i<t.length;i++){var a=t[i];r.test(a)&&n.push(a)}return n},M.makeClipPaths=function(t){var e=t._fullLayout;if(!e._hasOnlyLargeSploms){var r,i,a={_offset:0,_length:e.width,_id:""},o={_offset:0,_length:e.height,_id:""},s=M.list(t,"x",!0),l=M.list(t,"y",!0),c=[];for(r=0;r<s.length;r++)for(c.push({x:s[r],y:o}),i=0;i<l.length;i++)0===r&&c.push({x:a,y:l[i]}),c.push({x:s[r],y:l[i]});var u=e._clips.selectAll(".axesclip").data(c,function(t){return t.x._id+t.y._id});u.enter().append("clipPath").classed("axesclip",!0).attr("id",function(t){return"clip"+e._uid+t.x._id+t.y._id}).append("rect"),u.exit().remove(),u.each(function(t){n.select(this).select("rect").attr({x:t.x._offset||0,y:t.y._offset||0,width:t.x._length||1,height:t.y._length||1})})}},M.draw=function(t,e,r){var n=t._fullLayout;"redraw"===e&&n._paper.selectAll("g.subplot").each(function(t){var e=t[0],r=n._plots[e],i=r.xaxis,a=r.yaxis;r.xaxislayer.selectAll("."+i._id+"tick").remove(),r.yaxislayer.selectAll("."+a._id+"tick").remove(),r.xaxislayer.selectAll("."+i._id+"tick2").remove(),r.yaxislayer.selectAll("."+a._id+"tick2").remove(),r.xaxislayer.selectAll("."+i._id+"divider").remove(),r.yaxislayer.selectAll("."+a._id+"divider").remove(),r.gridlayer&&r.gridlayer.selectAll("path").remove(),r.zerolinelayer&&r.zerolinelayer.selectAll("path").remove(),n._infolayer.select(".g-"+i._id+"title").remove(),n._infolayer.select(".g-"+a._id+"title").remove()});var i=e&&"redraw"!==e?e:M.listIds(t);return s.syncOrAsync(i.map(function(e){return function(){if(e){var n=M.getFromId(t,e),i=M.drawOne(t,n,r);return n._r=n.range.slice(),n._rl=s.simpleMap(n._r,n.r2l),i}}}))},M.drawOne=function(t,e,r){var n,i,l;r=r||{},e.setScale();var f=t._fullLayout,p=e._id,d=p.charAt(0),g=M.counterLetter(p),v=e._mainSubplot,m=e._mainLinePosition,y=e._mainMirrorPosition,x=f._plots[v][d+"axislayer"],b=e._subplotsWith,_=e._vals=M.calcTicks(e),w=[e.mirror,m,y].join("_");for(n=0;n<_.length;n++)_[n].axInfo=w;if(e.visible){e._selections={},e._tickAngles={};var k,T,S=M.makeTransFn(e);if("boundaries"===e.tickson){var E=function(t,e){var r,n=[],i=function(t,e){var r=t.xbnd[e];null!==r&&n.push(s.extendFlat({},t,{x:r}))};if(e.length){for(r=0;r<e.length;r++)i(e[r],0);i(e[r-1],1)}return n}(0,_);T=M.clipEnds(e,E),k="inside"===e.ticks?T:E}else T=M.clipEnds(e,_),k="inside"===e.ticks?T:_;var C=e._gridVals=T,L=function(t,e){var r,n,i=[],a=function(t,e){var r=t.xbnd[e];null!==r&&i.push(s.extendFlat({},t,{x:r}))};if(t.showdividers&&e.length){for(r=0;r<e.length;r++){var o=e[r];o.text2!==n&&a(o,0),n=o.text2}a(e[r-1],1)}return i}(e,_);if(!f._hasOnlyLargeSploms){var z={};for(n=0;n<b.length;n++){i=b[n];var O=(l=f._plots[i])[g+"axis"],I=O._mainAxis._id;if(!z[I]){z[I]=1;var D="x"===d?"M0,"+O._offset+"v"+O._length:"M"+O._offset+",0h"+O._length;M.drawGrid(t,e,{vals:C,counterAxis:O,layer:l.gridlayer.select("."+p),path:D,transFn:S}),M.drawZeroLine(t,e,{counterAxis:O,layer:l.zerolinelayer,path:D,transFn:S})}}}var P=M.getTickSigns(e),R=[];if(e.ticks){var F,B,N,j=M.makeTickPath(e,m,P[2]);if(e._anchorAxis&&e.mirror&&!0!==e.mirror?(F=M.makeTickPath(e,y,P[3]),B=j+F):(F="",B=j),e.showdividers&&"outside"===e.ticks&&"boundaries"===e.tickson){var U={};for(n=0;n<L.length;n++)U[L[n].x]=1;N=function(t){return U[t.x]?F:B}}else N=B;M.drawTicks(t,e,{vals:k,layer:x,path:N,transFn:S}),R=Object.keys(e._linepositions||{})}for(n=0;n<R.length;n++){i=R[n],l=f._plots[i];var q=e._linepositions[i]||[],H=M.makeTickPath(e,q[0],P[0])+M.makeTickPath(e,q[1],P[1]);M.drawTicks(t,e,{vals:k,layer:l[d+"axislayer"],path:H,transFn:S})}var G=[];if(G.push(function(){return M.drawLabels(t,e,{vals:_,layer:x,transFn:S,labelFns:M.makeLabelFns(e,m)})}),"multicategory"===e.type){var Z=0,$={x:2,y:10}[d],Q=P[2]*("inside"===e.ticks?-1:1);G.push(function(){return Z+=Y(e,p+"tick")+$,Z+=e._tickAngles[p+"tick"]?e.tickfont.size*A:0,M.drawLabels(t,e,{vals:function(t,e){for(var r=[],n={},i=0;i<e.length;i++){var a=e[i];n[a.text2]?n[a.text2].push(a.x):n[a.text2]=[a.x]}for(var o in n)r.push(V(t,s.interp(n[o],.5),o));return r}(e,_),layer:x,cls:p+"tick2",repositionOnUpdate:!0,secondary:!0,transFn:S,labelFns:M.makeLabelFns(e,m+Z*Q)})}),G.push(function(){return Z+=Y(e,p+"tick2"),e._labelLength=Z,function(t,e,r){var n=e._id+"divider",i=r.vals,a=r.layer.selectAll("path."+n).data(i,W);a.exit().remove(),a.enter().insert("path",":first-child").classed(n,1).classed("crisp",1).call(u.stroke,e.dividercolor).style("stroke-width",h.crispRound(t,e.dividerwidth,1)+"px"),a.attr("transform",r.transFn).attr("d",r.path)}(t,e,{vals:L,layer:x,path:M.makeTickPath(e,m,Q,Z),transFn:S})})}var tt=o.getComponentMethod("rangeslider","isVisible")(e);return G.push(function(){if(e.showticklabels){var r=t.getBoundingClientRect(),n=x.node().getBoundingClientRect();e._boundingBox={width:n.width,height:n.height,left:n.left-r.left,right:n.right-r.left,top:n.top-r.top,bottom:n.bottom-r.top}}else{var i,a=f._size;"x"===d?(i="free"===e.anchor?a.t+a.h*(1-e.position):a.t+a.h*(1-e._anchorAxis.domain[{bottom:0,top:1}[e.side]]),e._boundingBox={top:i,bottom:i,left:e._offset,right:e._offset+e._length,width:e._length,height:0}):(i="free"===e.anchor?a.l+a.w*e.position:a.l+a.w*e._anchorAxis.domain[{left:0,right:1}[e.side]],e._boundingBox={left:i,right:i,bottom:e._offset+e._length,top:e._offset,height:e._length,width:0})}if(b){for(var o=e._counterSpan=[1/0,-1/0],s=0;s<b.length;s++){var l=f._plots[b[s]]["x"===d?"yaxis":"xaxis"];et(o,[l._offset,l._offset+l._length])}"free"===e.anchor&&et(o,"x"===d?[e._boundingBox.bottom,e._boundingBox.top]:[e._boundingBox.right,e._boundingBox.left])}},function(){var r,n,i=e.side.charAt(0);if(tt&&(n=o.getComponentMethod("rangeslider","autoMarginOpts")(t,e)),a.autoMargin(t,K(e),n),e.automargin&&(!tt||"b"!==i)){r={x:0,y:0,r:0,l:0,t:0,b:0};var s,l,c=e._boundingBox,u=X(t,e);switch(d+i){case"xb":s=0,l=c.top-u,r[i]=c.height;break;case"xt":s=1,l=u-c.bottom,r[i]=c.height;break;case"yl":s=0,l=u-c.right,r[i]=c.width;break;case"yr":s=1,l=c.left-u,r[i]=c.width}if(r[g]="free"===e.anchor?e.position:e._anchorAxis.domain[s],r[i]>0&&(r[i]+=l),e.title.text!==f._dfltTitle[d]&&(r[i]+=e.title.font.size),"x"===d&&c.width>0){var h=c.right-(e._offset+e._length);h>0&&(r.x=1,r.r=h);var p=e._offset-c.left;p>0&&(r.x=0,r.l=p)}else if("y"===d&&c.height>0){var v=c.bottom-(e._offset+e._length);v>0&&(r.y=0,r.b=v);var m=e._offset-c.top;m>0&&(r.y=1,r.t=m)}}a.autoMargin(t,J(e),r)}),r.skipTitle||tt&&e._boundingBox&&"bottom"===e.side||G.push(function(){return function(t,e){var r,n=t._fullLayout,i=e._id,a=i.charAt(0),o=e.title.font.size;if("multicategory"===e.type)r=e._labelLength;else{r=10+1.5*o+(e.linewidth?e.linewidth-1:0)}var s,l,u,f,p=X(t,e);"x"===a?(l=e._offset+e._length/2,u="top"===e.side?-r-o*(e.showticklabels?1:0):r+o*(e.showticklabels?1.5:.5),u+=p):(u=e._offset+e._length/2,l="right"===e.side?r+o*(e.showticklabels?1:.5):-r-o*(e.showticklabels?.5:0),l+=p,s={rotate:"-90",offset:0});if("multicategory"!==e.type){var d=e._selections[e._id+"tick"];if(f={selection:d,side:e.side},d&&d.node()&&d.node().parentNode){var g=h.getTranslate(d.node().parentNode);f.offsetLeft=g.x,f.offsetTop=g.y}}return c.draw(t,i+"title",{propContainer:e,propName:e._name+".title.text",placeholder:n._dfltTitle[a],avoid:f,transform:s,attributes:{x:l,y:u,"text-anchor":"middle"}})}(t,e)}),s.syncOrAsync(G)}function et(t,e){t[0]=Math.min(t[0],e[0]),t[1]=Math.max(t[1],e[1])}},M.getTickSigns=function(t){var e=t._id.charAt(0),r={x:"top",y:"right"}[e],n=t.side===r?1:-1,i=[-1,1,n,-n];return"inside"!==t.ticks==("x"===e)&&(i=i.map(function(t){return-t})),i},M.makeTransFn=function(t){var e=t._id.charAt(0),r=t._offset;return"x"===e?function(e){return"translate("+(r+t.l2p(e.x))+",0)"}:function(e){return"translate(0,"+(r+t.l2p(e.x))+")"}},M.makeTickPath=function(t,e,r,n){n=void 0!==n?n:t.ticklen;var i=t._id.charAt(0),a=(t.linewidth||1)/2;return"x"===i?"M0,"+(e+a*r)+"v"+n*r:"M"+(e+a*r)+",0h"+n*r},M.makeLabelFns=function(t,e,r){var n=t._id.charAt(0),a="boundaries"!==t.tickson&&"outside"===t.ticks,o=0,l=0;if(a&&(o+=t.ticklen),r&&"outside"===t.ticks){var c=s.deg2rad(r);o=t.ticklen*Math.cos(c)+1,l=t.ticklen*Math.sin(c)}t.showticklabels&&(a||t.showline)&&(o+=.2*t.tickfont.size);var u,h,f,p,d={labelStandoff:o+=(t.linewidth||1)/2,labelShift:l};return"x"===n?(p="bottom"===t.side?1:-1,u=l*p,h=e+o*p,f="bottom"===t.side?1:-.2,d.xFn=function(t){return t.dx+u},d.yFn=function(t){return t.dy+h+t.fontSize*f},d.anchorFn=function(t,e){return i(e)&&0!==e&&180!==e?e*p<0?"end":"start":"middle"},d.heightFn=function(e,r,n){return r<-60||r>60?-.5*n:"top"===t.side?-n:0}):"y"===n&&(p="right"===t.side?1:-1,u=o,h=-l*p,f=90===Math.abs(t.tickangle)?.5:0,d.xFn=function(t){return t.dx+e+(u+t.fontSize*f)*p},d.yFn=function(t){return t.dy+h+t.fontSize*k},d.anchorFn=function(e,r){return i(r)&&90===Math.abs(r)?"middle":"right"===t.side?"start":"end"},d.heightFn=function(e,r,n){return(r*="left"===t.side?1:-1)<-30?-n:r<30?-.5*n:0}),d},M.drawTicks=function(t,e,r){r=r||{};var n=e._id+"tick",i=r.layer.selectAll("path."+n).data(e.ticks?r.vals:[],W);i.exit().remove(),i.enter().append("path").classed(n,1).classed("ticks",1).classed("crisp",!1!==r.crisp).call(u.stroke,e.tickcolor).style("stroke-width",h.crispRound(t,e.tickwidth,1)+"px").attr("d",r.path),i.attr("transform",r.transFn)},M.drawGrid=function(t,e,r){r=r||{};var n=e._id+"grid",i=r.vals,a=r.counterAxis;if(!1===e.showgrid)i=[];else if(a&&M.shouldShowZeroLine(t,e,a))for(var o="array"===e.tickmode,s=0;s<i.length;s++){var l=i[s].x;if(o?!l:Math.abs(l)<e.dtick/100){if(i=i.slice(0,s).concat(i.slice(s+1)),!o)break;s--}}var c=r.layer.selectAll("path."+n).data(i,W);c.exit().remove(),c.enter().append("path").classed(n,1).classed("crisp",!1!==r.crisp),e._gw=h.crispRound(t,e.gridwidth,1),c.attr("transform",r.transFn).attr("d",r.path).call(u.stroke,e.gridcolor||"#ddd").style("stroke-width",e._gw+"px"),"function"==typeof r.path&&c.attr("d",r.path)},M.drawZeroLine=function(t,e,r){r=r||r;var n=e._id+"zl",i=M.shouldShowZeroLine(t,e,r.counterAxis),a=r.layer.selectAll("path."+n).data(i?[{x:0,id:e._id}]:[]);a.exit().remove(),a.enter().append("path").classed(n,1).classed("zl",1).classed("crisp",!1!==r.crisp).each(function(){r.layer.selectAll("path").sort(function(t,e){return S.idSort(t.id,e.id)})}),a.attr("transform",r.transFn).attr("d",r.path).call(u.stroke,e.zerolinecolor||u.defaultLine).style("stroke-width",h.crispRound(t,e.zerolinewidth,e._gw||1)+"px")},M.drawLabels=function(t,e,r){r=r||{};var a=e._id,o=a.charAt(0),c=r.cls||a+"tick",u=r.vals,f=r.labelFns,p=r.secondary?0:e.tickangle,d=(e._tickAngles||{})[c],g=r.layer.selectAll("g."+c).data(e.showticklabels?u:[],W),v=[];function m(t,e){t.each(function(t){var a=n.select(this),o=a.select(".text-math-group"),s=f.anchorFn(t,e),c=r.transFn.call(a.node(),t)+(i(e)&&0!=+e?" rotate("+e+","+f.xFn(t)+","+(f.yFn(t)-t.fontSize/2)+")":""),u=l.lineCount(a),p=A*t.fontSize,d=f.heightFn(t,i(e)?+e:0,(u-1)*p);if(d&&(c+=" translate(0, "+d+")"),o.empty())a.select("text").attr({transform:c,"text-anchor":s});else{var g=h.bBox(o.node()).width*{end:-.5,start:.5}[s];o.attr("transform",c+(g?"translate("+g+",0)":""))}})}g.enter().append("g").classed(c,1).append("text").attr("text-anchor","middle").each(function(e){var r=n.select(this),i=t._promises.length;r.call(l.positionText,f.xFn(e),f.yFn(e)).call(h.font,e.font,e.fontSize,e.fontColor).text(e.text).call(l.convertToTspans,t),t._promises[i]?v.push(t._promises.pop().then(function(){m(r,p)})):m(r,p)}),g.exit().remove(),r.repositionOnUpdate&&g.each(function(t){n.select(this).select("text").call(l.positionText,f.xFn(t),f.yFn(t))}),m(g,d||p),e._selections&&(e._selections[c]=g);var y=s.syncOrAsync([function(){return v.length&&Promise.all(v)},function(){m(g,p);var t=null;if(u.length&&"x"===o&&!i(p)&&("log"!==e.type||"D"!==String(e.dtick).charAt(0))){t=0;var n,a=0,l=[];if(g.each(function(t){a=Math.max(a,t.fontSize);var r=e.l2p(t.x),n=$(this),i=h.bBox(n.node());l.push({top:0,bottom:10,height:10,left:r-i.width/2,right:r+i.width/2+2,width:i.width+2})}),"boundaries"!==e.tickson&&!e.showdividers||r.secondary){var f=u.length,d=Math.abs((u[f-1].x-u[0].x)*e._m)/(f-1)<2.5*a||"multicategory"===e.type;for(n=0;n<l.length-1;n++)if(s.bBoxIntersect(l[n],l[n+1])){t=d?90:30;break}}else{var v=2;for(e.ticks&&(v+=e.tickwidth/2),n=0;n<l.length;n++){var y=u[n].xbnd,x=l[n];if(null!==y[0]&&x.left-e.l2p(y[0])<v||null!==y[1]&&e.l2p(y[1])-x.right<v){t=90;break}}}t&&m(g,t)}e._tickAngles&&(e._tickAngles[c]=null===t?i(p)?p:0:t)}]);return y&&y.then&&t._promises.push(y),y},M.shouldShowZeroLine=function(t,e,r){var n=s.simpleMap(e.range,e.r2l);return n[0]*n[1]<=0&&e.zeroline&&("linear"===e.type||"-"===e.type)&&e._gridVals.length&&(Z(e,0)||!function(t,e,r,n){var i=r._mainAxis;if(!i)return;var a=t._fullLayout,o=e._id.charAt(0),s=M.counterLetter(e._id),l=e._offset+(Math.abs(n[0])<Math.abs(n[1])==("x"===o)?0:e._length);function c(t){if(!t.showline||!t.linewidth)return!1;var r=Math.max((t.linewidth+e.zerolinewidth)/2,1);function n(t){return"number"==typeof t&&Math.abs(t-l)<r}if(n(t._mainLinePosition)||n(t._mainMirrorPosition))return!0;var i=t._linepositions||{};for(var a in i)if(n(i[a][0])||n(i[a][1]))return!0}var u=a._plots[r._mainSubplot];if(!(u.mainplotinfo||u).overlays.length)return c(r);for(var h=M.list(t,s),f=0;f<h.length;f++){var p=h[f];if(p._mainAxis===i&&c(p))return!0}}(t,e,r,n)||function(t,e){for(var r=t._fullData,n=e._mainSubplot,i=e._id.charAt(0),a=0;a<r.length;a++){var s=r[a];if(!0===s.visible&&s.xaxis+s.yaxis===n&&(o.traceIs(s,"bar")&&s.orientation==={x:"h",y:"v"}[i]||s.fill&&s.fill.charAt(s.fill.length-1)===i))return!0}return!1}(t,e))},M.clipEnds=function(t,e){return e.filter(function(e){return Z(t,e.x)})},M.allowAutoMargin=function(t){for(var e=M.list(t,"",!0),r=0;r<e.length;r++){var n=e[r];n.automargin&&a.allowAutoMargin(t,J(n)),o.getComponentMethod("rangeslider","isVisible")(n)&&a.allowAutoMargin(t,K(n))}},M.swap=function(t,e){for(var r=function(t,e){var r,n,i=[];for(r=0;r<e.length;r++){var a=[],o=t._fullData[e[r]].xaxis,s=t._fullData[e[r]].yaxis;if(o&&s){for(n=0;n<i.length;n++)-1===i[n].x.indexOf(o)&&-1===i[n].y.indexOf(s)||a.push(n);if(a.length){var l,c=i[a[0]];if(a.length>1)for(n=1;n<a.length;n++)l=i[a[n]],Q(c.x,l.x),Q(c.y,l.y);Q(c.x,[o]),Q(c.y,[s])}else i.push({x:[o],y:[s]})}}return i}(t,e),n=0;n<r.length;n++)tt(t,r[n].x,r[n].y)}},{"../../components/color":574,"../../components/drawing":595,"../../components/titles":662,"../../constants/alignment":669,"../../constants/numerical":674,"../../lib":697,"../../lib/svg_text_utils":721,"../../plots/plots":807,"../../registry":826,"./autorange":744,"./axis_autotype":746,"./axis_ids":748,"./clean_ticks":750,"./layout_attributes":757,"./set_convert":763,d3:151,"fast-isnumeric":218}],746:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("../../constants/numerical").BADNUM;e.exports=function(t,e,r){return!(r=r||{}).noMultiCategory&&(o=t,i.isArrayOrTypedArray(o[0])&&i.isArrayOrTypedArray(o[1]))?"multicategory":function(t,e){for(var r=Math.max(1,(t.length-1)/1e3),a=0,o=0,s={},l=0;l<t.length;l+=r){var c=t[Math.round(l)],u=String(c);s[u]||(s[u]=1,i.isDateTime(c,e)&&(a+=1),n(c)&&(o+=1))}return a>2*o}(t,e)?"date":function(t){for(var e=Math.max(1,(t.length-1)/1e3),r=0,n=0,o={},s=0;s<t.length;s+=e){var l=t[Math.round(s)],c=String(l);o[c]||(o[c]=1,"boolean"==typeof l?n++:i.cleanNumber(l)!==a?r++:"string"==typeof l&&n++)}return n>2*r}(t)?"category":function(t){if(!t)return!1;for(var e=0;e<t.length;e++)if(n(t[e]))return!0;return!1}(t)?"linear":"-";var o}},{"../../constants/numerical":674,"../../lib":697,"fast-isnumeric":218}],747:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("../../lib"),a=t("./layout_attributes"),o=t("./tick_value_defaults"),s=t("./tick_mark_defaults"),l=t("./tick_label_defaults"),c=t("./category_order_defaults"),u=t("./line_grid_defaults"),h=t("./set_convert");e.exports=function(t,e,r,f,p){var d=f.letter,g=f.font||{},v=f.splomStash||{},m=r("visible",!f.cheateronly),y=e.type;"date"===y&&n.getComponentMethod("calendars","handleDefaults")(t,e,"calendar",f.calendar);if(h(e,p),!r("autorange",!e.isValidRange(t.range))||"linear"!==y&&"-"!==y||r("rangemode"),r("range"),e.cleanRange(),c(t,e,r,f),"category"===y||f.noHover||r("hoverformat"),!m)return e;var x=r("color"),b=x!==a.color.dflt?x:g.color;r("title.text",v.label||p._dfltTitle[d]),i.coerceFont(r,"title.font",{family:g.family,size:Math.round(1.2*g.size),color:b}),o(t,e,r,y),l(t,e,r,y,f),s(t,e,r,f),u(t,e,r,{dfltColor:x,bgColor:f.bgColor,showGrid:f.showGrid,attributes:a}),(e.showline||e.ticks)&&r("mirror"),f.automargin&&r("automargin");var _,w="multicategory"===e.type;f.noTickson||"category"!==e.type&&!w||!e.ticks&&!e.showgrid||(w&&(_="boundaries"),r("tickson",_));w&&(r("showdividers")&&(r("dividercolor"),r("dividerwidth")));return e}},{"../../lib":697,"../../registry":826,"./category_order_defaults":749,"./layout_attributes":757,"./line_grid_defaults":759,"./set_convert":763,"./tick_label_defaults":764,"./tick_mark_defaults":765,"./tick_value_defaults":766}],748:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("./constants");r.id2name=function(t){if("string"==typeof t&&t.match(i.AX_ID_PATTERN)){var e=t.substr(1);return"1"===e&&(e=""),t.charAt(0)+"axis"+e}},r.name2id=function(t){if(t.match(i.AX_NAME_PATTERN)){var e=t.substr(5);return"1"===e&&(e=""),t.charAt(0)+e}},r.cleanId=function(t,e){if(t.match(i.AX_ID_PATTERN)&&(!e||t.charAt(0)===e)){var r=t.substr(1).replace(/^0+/,"");return"1"===r&&(r=""),t.charAt(0)+r}},r.list=function(t,e,n){var i=t._fullLayout;if(!i)return[];var a,o=r.listIds(t,e),s=new Array(o.length);for(a=0;a<o.length;a++){var l=o[a];s[a]=i[l.charAt(0)+"axis"+l.substr(1)]}if(!n){var c=i._subplots.gl3d||[];for(a=0;a<c.length;a++){var u=i[c[a]];e?s.push(u[e+"axis"]):s.push(u.xaxis,u.yaxis,u.zaxis)}}return s},r.listIds=function(t,e){var r=t._fullLayout;if(!r)return[];var n=r._subplots;return e?n[e+"axis"]:n.xaxis.concat(n.yaxis)},r.getFromId=function(t,e,n){var i=t._fullLayout;return"x"===n?e=e.replace(/y[0-9]*/,""):"y"===n&&(e=e.replace(/x[0-9]*/,"")),i[r.id2name(e)]},r.getFromTrace=function(t,e,i){var a=t._fullLayout,o=null;if(n.traceIs(e,"gl3d")){var s=e.scene;"scene"===s.substr(0,5)&&(o=a[s][i+"axis"])}else o=r.getFromId(t,e[i+"axis"]||i);return o},r.idSort=function(t,e){var r=t.charAt(0),n=e.charAt(0);return r!==n?r>n?1:-1:+(t.substr(1)||1)-+(e.substr(1)||1)},r.getAxisGroup=function(t,e){for(var r=t._axisMatchGroups,n=0;n<r.length;n++){if(r[n][e])return"g"+n}return e}},{"../../registry":826,"./constants":751}],749:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){if("category"===e.type){var i,a=t.categoryarray,o=Array.isArray(a)&&a.length>0;o&&(i="array");var s,l=r("categoryorder",i);"array"===l&&(s=r("categoryarray")),o||"array"!==l||(l=e.categoryorder="trace"),"trace"===l?e._initialCategories=[]:"array"===l?e._initialCategories=s.slice():(s=function(t,e){var r,n,i,a=e.dataAttr||t._id.charAt(0),o={};if(e.axData)r=e.axData;else for(r=[],n=0;n<e.data.length;n++){var s=e.data[n];s[a+"axis"]===t._id&&r.push(s)}for(n=0;n<r.length;n++){var l=r[n][a];for(i=0;i<l.length;i++){var c=l[i];null!=c&&(o[c]=1)}}return Object.keys(o)}(e,n).sort(),"category ascending"===l?e._initialCategories=s:"category descending"===l&&(e._initialCategories=s.reverse()))}}},{}],750:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("../../constants/numerical").ONEDAY;r.dtick=function(t,e){var r="log"===e,i="date"===e,o="category"===e,s=i?a:1;if(!t)return s;if(n(t))return(t=Number(t))<=0?s:o?Math.max(1,Math.round(t)):i?Math.max(.1,t):t;if("string"!=typeof t||!i&&!r)return s;var l=t.charAt(0),c=t.substr(1);return(c=n(c)?Number(c):0)<=0||!(i&&"M"===l&&c===Math.round(c)||r&&"L"===l||r&&"D"===l&&(1===c||2===c))?s:t},r.tick0=function(t,e,r,a){return"date"===e?i.cleanDate(t,i.dateTick0(r)):"D1"!==a&&"D2"!==a?n(t)?Number(t):0:void 0}},{"../../constants/numerical":674,"../../lib":697,"fast-isnumeric":218}],751:[function(t,e,r){"use strict";var n=t("../../lib/regex").counter;e.exports={idRegex:{x:n("x"),y:n("y")},attrRegex:n("[xy]axis"),xAxisMatch:n("xaxis"),yAxisMatch:n("yaxis"),AX_ID_PATTERN:/^[xyz][0-9]*$/,AX_NAME_PATTERN:/^[xyz]axis[0-9]*$/,SUBPLOT_PATTERN:/^x([0-9]*)y([0-9]*)$/,MINDRAG:8,MINSELECT:12,MINZOOM:20,DRAGGERSIZE:20,BENDPX:1.5,REDRAWDELAY:50,SELECTDELAY:100,SELECTID:"-select",DFLTRANGEX:[-1,6],DFLTRANGEY:[-1,4],traceLayerClasses:["heatmaplayer","contourcarpetlayer","contourlayer","barlayer","carpetlayer","violinlayer","boxlayer","ohlclayer","scattercarpetlayer","scatterlayer"],layerValue2layerClass:{"above traces":"above","below traces":"below"}}},{"../../lib/regex":713}],752:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./axis_ids").id2name,a=t("./scale_zoom"),o=t("./autorange").makePadFn,s=t("./autorange").concatExtremes,l=t("../../constants/numerical").ALMOST_EQUAL,c=t("../../constants/alignment").FROM_BL;function u(t,e,r,n,a){var o,s,l,c,u="range"!==a,h=n[i(e)].type,f=[];for(s=0;s<r.length;s++)if((l=r[s])!==e&&(c=n[i(l)]).type===h)if(c.fixedrange){if(u&&c.anchor){n[i(c.anchor)].fixedrange&&f.push(l)}}else f.push(l);for(o=0;o<t.length;o++)if(t[o][e]){var p=t[o],d=[];for(s=0;s<f.length;s++)p[l=f[s]]||d.push(l);return{linkableAxes:d,thisGroup:p}}return{linkableAxes:f,thisGroup:null}}function h(t,e,r,n,i){var a,o,s,l,c;null===e?((e={})[r]=1,c=t.length,t.push(e)):c=t.indexOf(e);var u=Object.keys(e);for(a=0;a<t.length;a++)if(s=t[a],a!==c&&s[n]){var h=s[n];for(o=0;o<u.length;o++)s[l=u[o]]=h*i*e[l];return void t.splice(c,1)}if(1!==i)for(o=0;o<u.length;o++)e[u[o]]*=i;e[n]=1}function f(t,e){var r=t._inputDomain,n=c[t.constraintoward],i=r[0]+(r[1]-r[0])*n;t.domain=t._input.domain=[i+(r[0]-i)/e,i+(r[1]-i)/e],t.setScale()}r.handleConstraintDefaults=function(t,e,r,i,a){var o,s,l,c,f=a._axisConstraintGroups,p=a._axisMatchGroups,d=e._id,g=d.charAt(0),v=((a._splomAxes||{})[g]||{})[d]||{},m=e._id,y=m.charAt(0),x=r("constrain");if(n.coerce(t,e,{constraintoward:{valType:"enumerated",values:"x"===y?["left","center","right"]:["bottom","middle","top"],dflt:"x"===y?"center":"middle"}},"constraintoward"),!t.matches&&!v.matches||e.fixedrange||(s=u(p,m,i,a),o=n.coerce(t,e,{matches:{valType:"enumerated",values:s.linkableAxes||[],dflt:v.matches}},"matches")),o||!t.scaleanchor||e.fixedrange&&"domain"!==x||(c=u(f,m,i,a,x),l=n.coerce(t,e,{scaleanchor:{valType:"enumerated",values:c.linkableAxes||[]}},"scaleanchor")),o?(delete e.constrain,h(p,s.thisGroup,m,o,1)):-1!==i.indexOf(t.matches)&&n.warn("ignored "+e._name+'.matches: "'+t.matches+'" to avoid either an infinite loop or because the target axis has fixed range.'),l){var b=r("scaleratio");b||(b=e.scaleratio=1),h(f,c.thisGroup,m,l,b)}else-1!==i.indexOf(t.scaleanchor)&&n.warn("ignored "+e._name+'.scaleanchor: "'+t.scaleanchor+'" to avoid either an infinite loop and possibly inconsistent scaleratios, or because the target axis has fixed range or this axis declares a *matches* constraint.')},r.enforce=function(t){var e,r,n,c,u,h,p,d=t._fullLayout,g=d._axisConstraintGroups||[];for(e=0;e<g.length;e++){var v=g[e],m=Object.keys(v),y=1/0,x=0,b=1/0,_={},w={},k=!1;for(r=0;r<m.length;r++)w[n=m[r]]=c=d[i(n)],c._inputDomain?c.domain=c._inputDomain.slice():c._inputDomain=c.domain.slice(),c._inputRange||(c._inputRange=c.range.slice()),c.setScale(),_[n]=u=Math.abs(c._m)/v[n],y=Math.min(y,u),"domain"!==c.constrain&&c._constraintShrinkable||(b=Math.min(b,u)),delete c._constraintShrinkable,x=Math.max(x,u),"domain"===c.constrain&&(k=!0);if(!(y>l*x)||k)for(r=0;r<m.length;r++)if(u=_[n=m[r]],h=(c=w[n]).constrain,u!==b||"domain"===h)if(p=u/b,"range"===h)a(c,p);else{var A=c._inputDomain,M=(c.domain[1]-c.domain[0])/(A[1]-A[0]),T=(c.r2l(c.range[1])-c.r2l(c.range[0]))/(c.r2l(c._inputRange[1])-c.r2l(c._inputRange[0]));if((p/=M)*T<1){c.domain=c._input.domain=A.slice(),a(c,p);continue}if(T<1&&(c.range=c._input.range=c._inputRange.slice(),p*=T),c.autorange){var S=c.r2l(c.range[0]),E=c.r2l(c.range[1]),C=(S+E)/2,L=C,z=C,O=Math.abs(E-C),I=C-O*p*1.0001,D=C+O*p*1.0001,P=o(c);f(c,p);var R,F,B=Math.abs(c._m),N=s(t,c),j=N.min,V=N.max;for(F=0;F<j.length;F++)(R=j[F].val-P(j[F])/B)>I&&R<L&&(L=R);for(F=0;F<V.length;F++)(R=V[F].val+P(V[F])/B)<D&&R>z&&(z=R);p/=(z-L)/(2*O),L=c.l2r(L),z=c.l2r(z),c.range=c._input.range=S<E?[L,z]:[z,L]}f(c,p)}}},r.clean=function(t,e){if(e._inputDomain){for(var r=!1,n=e._id,i=t._fullLayout._axisConstraintGroups,a=0;a<i.length;a++)if(i[a][n]){r=!0;break}r&&"domain"===e.constrain||(e._input.domain=e.domain=e._inputDomain,delete e._inputDomain)}}},{"../../constants/alignment":669,"../../constants/numerical":674,"../../lib":697,"./autorange":744,"./axis_ids":748,"./scale_zoom":761}],753:[function(t,e,r){"use strict";var n=t("d3"),i=t("tinycolor2"),a=t("has-passive-events"),o=t("../../registry"),s=t("../../lib"),l=t("../../lib/svg_text_utils"),c=t("../../components/color"),u=t("../../components/drawing"),h=t("../../components/fx"),f=t("./axes"),p=t("../../lib/setcursor"),d=t("../../components/dragelement"),g=t("../../constants/alignment").FROM_TL,v=t("../../lib/clear_gl_canvases"),m=t("../../plot_api/subroutines").redrawReglTraces,y=t("../plots"),x=t("./axis_ids").getFromId,b=t("./select").prepSelect,_=t("./select").clearSelect,w=t("./select").selectOnClick,k=t("./scale_zoom"),A=t("./constants"),M=A.MINDRAG,T=A.MINZOOM,S=!0;function E(t,e,r,n){var i=s.ensureSingle(t.draglayer,e,r,function(e){e.classed("drag",!0).style({fill:"transparent","stroke-width":0}).attr("data-subplot",t.id)});return i.call(p,n),i.node()}function C(t,e,r,i,a,o,s){var l=E(t,"rect",e,r);return n.select(l).call(u.setRect,i,a,o,s),l}function L(t,e){for(var r=0;r<t.length;r++)if(!t[r].fixedrange)return e;return""}function z(t,e,r,n,i){for(var a=0;a<t.length;a++){var o=t[a];if(!o.fixedrange){var s=o._rl[0],l=o._rl[1]-s;o.range=[o.l2r(s+l*e),o.l2r(s+l*r)],n[o._name+".range[0]"]=o.range[0],n[o._name+".range[1]"]=o.range[1]}}if(i&&i.length){var c=(e+(1-r))/2;z(i,c,1-c,n,[])}}function O(t,e){for(var r=0;r<t.length;r++){var n=t[r];n.fixedrange||(n.range=[n.l2r(n._rl[0]-e/n._m),n.l2r(n._rl[1]-e/n._m)])}}function I(t){return 1-(t>=0?Math.min(t,.9):1/(1/Math.max(t,-.3)+3.222))}function D(t,e,r,n,i){return t.append("path").attr("class","zoombox").style({fill:e>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+r+", "+n+")").attr("d",i+"Z")}function P(t,e,r){return t.append("path").attr("class","zoombox-corners").style({fill:c.background,stroke:c.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+e+", "+r+")").attr("d","M0,0Z")}function R(t,e,r,n,i,a){t.attr("d",n+"M"+r.l+","+r.t+"v"+r.h+"h"+r.w+"v-"+r.h+"h-"+r.w+"Z"),F(t,e,i,a)}function F(t,e,r,n){r||(t.transition().style("fill",n>.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),e.transition().style("opacity",1).duration(200))}function B(t){n.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}function N(t){S&&t.data&&t._context.showTips&&(s.notifier(s._(t,"Double-click to zoom back out"),"long"),S=!1)}function j(t){return"lasso"===t||"select"===t}function V(t){var e=Math.floor(Math.min(t.b-t.t,t.r-t.l,T)/2);return"M"+(t.l-3.5)+","+(t.t-.5+e)+"h3v"+-e+"h"+e+"v-3h-"+(e+3)+"ZM"+(t.r+3.5)+","+(t.t-.5+e)+"h-3v"+-e+"h"+-e+"v-3h"+(e+3)+"ZM"+(t.r+3.5)+","+(t.b+.5-e)+"h-3v"+e+"h"+-e+"v3h"+(e+3)+"ZM"+(t.l-3.5)+","+(t.b+.5-e)+"h3v"+e+"h"+e+"v3h-"+(e+3)+"Z"}function U(t,e,r,n){for(var i,a,o,l,c=!1,u={},h={},f=0;f<e.length;f++){var p=e[f];for(i in r)if(p[i]){for(o in p)("x"===o.charAt(0)?r:n)[o]||(u[o]=i);for(a in n)p[a]&&(c=!0)}for(a in n)if(p[a])for(l in p)("x"===l.charAt(0)?r:n)[l]||(h[l]=a)}c&&(s.extendFlat(u,h),h={});var d={},g=[];for(o in u){var v=x(t,o);g.push(v),d[v._id]=v}var m={},y=[];for(l in h){var b=x(t,l);y.push(b),m[b._id]=b}return{xaHash:d,yaHash:m,xaxes:g,yaxes:y,xLinks:u,yLinks:h,isSubplotConstrained:c}}function q(t,e){if(a){var r=void 0!==t.onwheel?"wheel":"mousewheel";t._onwheel&&t.removeEventListener(r,t._onwheel),t._onwheel=e,t.addEventListener(r,e,{passive:!1})}else void 0!==t.onwheel?t.onwheel=e:void 0!==t.onmousewheel&&(t.onmousewheel=e)}function H(t){var e=[];for(var r in t)e.push(t[r]);return e}e.exports={makeDragBox:function(t,e,r,a,c,p,S,E){var F,G,Y,W,X,Z,$,J,K,Q,tt,et,rt,nt,it,at,ot,st,lt,ct,ut,ht=t._fullLayout._zoomlayer,ft=S+E==="nsew",pt=1===(S+E).length;function dt(){if(F=e.xaxis,G=e.yaxis,K=F._length,Q=G._length,$=F._offset,J=G._offset,(Y={})[F._id]=F,(W={})[G._id]=G,S&&E)for(var r=e.overlays,n=0;n<r.length;n++){var i=r[n].xaxis;Y[i._id]=i;var a=r[n].yaxis;W[a._id]=a}X=H(Y),Z=H(W),rt=L(X,E),nt=L(Z,S),it=!nt&&!rt,tt=U(t,t._fullLayout._axisConstraintGroups,Y,W),et=U(t,t._fullLayout._axisMatchGroups,Y,W),at=E||tt.isSubplotConstrained||et.isSubplotConstrained,ot=S||tt.isSubplotConstrained||et.isSubplotConstrained;var o=t._fullLayout;st=o._has("scattergl"),lt=o._has("splom"),ct=o._has("svg")}dt();var gt=function(t,e,r){return t?"nsew"===t?r?"":"pan"===e?"move":"crosshair":t.toLowerCase()+"-resize":"pointer"}(nt+rt,t._fullLayout.dragmode,ft),vt=C(e,S+E+"drag",gt,r,a,c,p);if(it&&!ft)return vt.onmousedown=null,vt.style.pointerEvents="none",vt;var mt,yt,xt,bt,_t,wt,kt,At,Mt,Tt,St={element:vt,gd:t,plotinfo:e};function Et(){St.plotinfo.selection=!1,_(ht)}function Ct(r,i){var a=t._fullLayout.clickmode;if(B(t),2!==r||pt||function(){if(!t._transitioningWithDuration){var e=t._context.doubleClick,r=[];rt&&(r=r.concat(X)),nt&&(r=r.concat(Z)),et.xaxes&&(r=r.concat(et.xaxes)),et.yaxes&&(r=r.concat(et.yaxes));var n,i,a,s={};if("reset+autosize"===e)for(e="autosize",i=0;i<r.length;i++)if((n=r[i])._rangeInitial&&(n.range[0]!==n._rangeInitial[0]||n.range[1]!==n._rangeInitial[1])||!n._rangeInitial&&!n.autorange){e="reset";break}if("autosize"===e)for(i=0;i<r.length;i++)(n=r[i]).fixedrange||(s[n._name+".autorange"]=!0);else if("reset"===e)for((rt||tt.isSubplotConstrained)&&(r=r.concat(tt.xaxes)),nt&&!tt.isSubplotConstrained&&(r=r.concat(tt.yaxes)),tt.isSubplotConstrained&&(rt?nt||(r=r.concat(Z)):r=r.concat(X)),i=0;i<r.length;i++)(n=r[i]).fixedrange||(n._rangeInitial?(a=n._rangeInitial,s[n._name+".range[0]"]=a[0],s[n._name+".range[1]"]=a[1]):s[n._name+".autorange"]=!0);t.emit("plotly_doubleclick",null),o.call("_guiRelayout",t,s)}}(),ft)a.indexOf("select")>-1&&w(i,t,X,Z,e.id,St),a.indexOf("event")>-1&&h.click(t,i,e.id);else if(1===r&&pt){var s=S?G:F,c="s"===S||"w"===E?0:1,u=s._name+".range["+c+"]",f=function(t,e){var r,i=t.range[e],a=Math.abs(i-t.range[1-e]);return"date"===t.type?i:"log"===t.type?(r=Math.ceil(Math.max(0,-Math.log(a)/Math.LN10))+3,n.format("."+r+"g")(Math.pow(10,i))):(r=Math.floor(Math.log(Math.abs(i))/Math.LN10)-Math.floor(Math.log(a)/Math.LN10)+4,n.format("."+String(r)+"g")(i))}(s,c),p="left",d="middle";if(s.fixedrange)return;S?(d="n"===S?"top":"bottom","right"===s.side&&(p="right")):"e"===E&&(p="right"),t._context.showAxisRangeEntryBoxes&&n.select(vt).call(l.makeEditable,{gd:t,immediate:!0,background:t._fullLayout.paper_bgcolor,text:String(f),fill:s.tickfont?s.tickfont.color:"#444",horizontalAlign:p,verticalAlign:d}).on("edit",function(e){var r=s.d2r(e);void 0!==r&&o.call("_guiRelayout",t,u,r)})}}function Lt(e,r){if(t._transitioningWithDuration)return!1;var n=Math.max(0,Math.min(K,e+mt)),i=Math.max(0,Math.min(Q,r+yt)),a=Math.abs(n-mt),o=Math.abs(i-yt);function s(){kt="",xt.r=xt.l,xt.t=xt.b,Mt.attr("d","M0,0Z")}if(xt.l=Math.min(mt,n),xt.r=Math.max(mt,n),xt.t=Math.min(yt,i),xt.b=Math.max(yt,i),tt.isSubplotConstrained)a>T||o>T?(kt="xy",a/K>o/Q?(o=a*Q/K,yt>i?xt.t=yt-o:xt.b=yt+o):(a=o*K/Q,mt>n?xt.l=mt-a:xt.r=mt+a),Mt.attr("d",V(xt))):s();else if(et.isSubplotConstrained)if(a>T||o>T){kt="xy";var l=Math.min(xt.l/K,(Q-xt.b)/Q),c=Math.max(xt.r/K,(Q-xt.t)/Q);xt.l=l*K,xt.r=c*K,xt.b=(1-l)*Q,xt.t=(1-c)*Q,Mt.attr("d",V(xt))}else s();else!nt||o<Math.min(Math.max(.6*a,M),T)?a<M||!rt?s():(xt.t=0,xt.b=Q,kt="x",Mt.attr("d",function(t,e){return"M"+(t.l-.5)+","+(e-T-.5)+"h-3v"+(2*T+1)+"h3ZM"+(t.r+.5)+","+(e-T-.5)+"h3v"+(2*T+1)+"h-3Z"}(xt,yt))):!rt||a<Math.min(.6*o,T)?(xt.l=0,xt.r=K,kt="y",Mt.attr("d",function(t,e){return"M"+(e-T-.5)+","+(t.t-.5)+"v-3h"+(2*T+1)+"v3ZM"+(e-T-.5)+","+(t.b+.5)+"v3h"+(2*T+1)+"v-3Z"}(xt,mt))):(kt="xy",Mt.attr("d",V(xt)));xt.w=xt.r-xt.l,xt.h=xt.b-xt.t,kt&&(Tt=!0),t._dragged=Tt,R(At,Mt,xt,_t,wt,bt),wt=!0}function zt(){if(ut={},Math.min(xt.h,xt.w)<2*M)return B(t);"xy"!==kt&&"x"!==kt||(z(X,xt.l/K,xt.r/K,ut,tt.xaxes),Ft("x",ut)),"xy"!==kt&&"y"!==kt||(z(Z,(Q-xt.b)/Q,(Q-xt.t)/Q,ut,tt.yaxes),Ft("y",ut)),B(t),Nt(),N(t)}St.prepFn=function(e,r,n){var a=St.dragmode,o=t._fullLayout.dragmode;o!==a&&(St.dragmode=o),dt(),it||(ft?e.shiftKey?"pan"===o?o="zoom":j(o)||(o="pan"):e.ctrlKey&&(o="pan"):o="pan"),St.minDrag="lasso"===o?1:void 0,j(o)?(St.xaxes=X,St.yaxes=Z,b(e,r,n,St,o)):(St.clickFn=Ct,j(a)&&Et(),it||("zoom"===o?(St.moveFn=Lt,St.doneFn=zt,St.minDrag=1,function(e,r,n){var a=vt.getBoundingClientRect();mt=r-a.left,yt=n-a.top,xt={l:mt,r:mt,w:0,t:yt,b:yt,h:0},bt=t._hmpixcount?t._hmlumcount/t._hmpixcount:i(t._fullLayout.plot_bgcolor).getLuminance(),wt=!1,kt="xy",Tt=!1,At=D(ht,bt,$,J,_t="M0,0H"+K+"V"+Q+"H0V0"),Mt=P(ht,$,J)}(0,r,n)):"pan"===o&&(St.moveFn=Rt,St.doneFn=Nt)))},d.init(St);var Ot=[0,0,K,Q],It=null,Dt=A.REDRAWDELAY,Pt=e.mainplot?t._fullLayout._plots[e.mainplot]:e;function Rt(e,r){if(!t._transitioningWithDuration){if(t._fullLayout._replotting=!0,"ew"===rt||"ns"===nt)return rt&&(O(X,e),Ft("x")),nt&&(O(Z,r),Ft("y")),jt([rt?-e:0,nt?-r:0,K,Q]),void Bt();if(tt.isSubplotConstrained&&rt&&nt){var n="w"===rt==("n"===nt)?1:-1,i=(e/K+n*r/Q)/2;e=i*K,r=n*i*Q}"w"===rt?e=l(X,0,e):"e"===rt?e=l(X,1,-e):rt||(e=0),"n"===nt?r=l(Z,1,r):"s"===nt?r=l(Z,0,-r):nt||(r=0);var a="w"===rt?e:0,o="n"===nt?r:0;if(tt.isSubplotConstrained){var s;if(!rt&&1===nt.length){for(s=0;s<X.length;s++)X[s].range=X[s]._r.slice(),k(X[s],1-r/Q);a=(e=r*K/Q)/2}if(!nt&&1===rt.length){for(s=0;s<Z.length;s++)Z[s].range=Z[s]._r.slice(),k(Z[s],1-e/K);o=(r=e*Q/K)/2}}Ft("x"),Ft("y"),jt([a,o,K-e,Q-r]),Bt()}function l(t,e,r){for(var n,i,a=1-e,o=0;o<t.length;o++){var s=t[o];if(!s.fixedrange){n=s,i=s._rl[a]+(s._rl[e]-s._rl[a])/I(r/s._length);var l=s.l2r(i);!1!==l&&void 0!==l&&(s.range[e]=l)}}return n._length*(n._rl[e]-i)/(n._rl[e]-n._rl[a])}}function Ft(t,e){for(var r=et.isSubplotConstrained?{x:Z,y:X}[t]:et[t+"axes"],n=et.isSubplotConstrained?{x:X,y:Z}[t]:[],i=0;i<r.length;i++){var a=r[i],o=a._id,s=et.xLinks[o]||et.yLinks[o],l=n[0]||Y[s]||W[s];if(l){var c=l.range;e?(e[a._name+".range[0]"]=c[0],e[a._name+".range[1]"]=c[1]):a.range=c}}}function Bt(){var e,r=[];function n(t){for(e=0;e<t.length;e++)t[e].fixedrange||r.push(t[e]._id)}for(at&&(n(X),n(tt.xaxes),n(et.xaxes)),ot&&(n(Z),n(tt.yaxes),n(et.yaxes)),ut={},e=0;e<r.length;e++){var i=r[e],a=x(t,i);f.drawOne(t,a,{skipTitle:!0}),ut[a._name+".range[0]"]=a.range[0],ut[a._name+".range[1]"]=a.range[1]}f.redrawComponents(t,r)}function Nt(){jt([0,0,K,Q]),s.syncOrAsync([y.previousPromises,function(){t._fullLayout._replotting=!1,o.call("_guiRelayout",t,ut)}],t)}function jt(e){var r,n,i,a,l=t._fullLayout,c=l._plots,h=l._subplots.cartesian;if(lt&&o.subplotsRegistry.splom.drag(t),st)for(r=0;r<h.length;r++)if(i=(n=c[h[r]]).xaxis,a=n.yaxis,n._scene){var f=s.simpleMap(i.range,i.r2l),p=s.simpleMap(a.range,a.r2l);n._scene.update({range:[f[0],p[0],f[1],p[1]]})}if((lt||st)&&(v(t),m(t)),ct){var d=e[2]/F._length,g=e[3]/G._length;for(r=0;r<h.length;r++){i=(n=c[h[r]]).xaxis,a=n.yaxis;var y,x,b,_,w=at&&!i.fixedrange&&Y[i._id],k=ot&&!a.fixedrange&&W[a._id];if(w?(y=d,b=E?e[0]:qt(i,y)):et.xaHash[i._id]?(y=d,b=e[0]*i._length/F._length):et.yaHash[i._id]?(y=g,b="ns"===nt?-e[1]*i._length/G._length:qt(i,y,{n:"top",s:"bottom"}[nt])):b=Ut(i,y=Vt(i,d,g)),k?(x=g,_=S?e[1]:qt(a,x)):et.yaHash[a._id]?(x=g,_=e[1]*a._length/G._length):et.xaHash[a._id]?(x=d,_="ew"===rt?-e[0]*a._length/F._length:qt(a,x,{e:"right",w:"left"}[rt])):_=Ut(a,x=Vt(a,d,g)),y||x){y||(y=1),x||(x=1);var A=i._offset-b/y,M=a._offset-_/x;n.clipRect.call(u.setTranslate,b,_).call(u.setScale,y,x),n.plot.call(u.setTranslate,A,M).call(u.setScale,1/y,1/x),y===n.xScaleFactor&&x===n.yScaleFactor||(u.setPointGroupScale(n.zoomScalePts,y,x),u.setTextPointsScale(n.zoomScaleTxt,y,x)),u.hideOutsideRangePoints(n.clipOnAxisFalseTraces,n),n.xScaleFactor=y,n.yScaleFactor=x}}}}function Vt(t,e,r){return t.fixedrange?0:at&&tt.xaHash[t._id]?e:ot&&(tt.isSubplotConstrained?tt.xaHash:tt.yaHash)[t._id]?r:0}function Ut(t,e){return e?(t.range=t._r.slice(),k(t,e),qt(t,e)):0}function qt(t,e,r){return t._length*(1-e)*g[r||t.constraintoward||"middle"]}return S.length*E.length!=1&&q(vt,function(e){if(t._context._scrollZoom.cartesian||t._fullLayout._enablescrollzoom){if(Et(),t._transitioningWithDuration)return e.preventDefault(),void e.stopPropagation();dt(),clearTimeout(It);var r=-e.deltaY;if(isFinite(r)||(r=e.wheelDelta/10),isFinite(r)){var n,i=Math.exp(-Math.min(Math.max(r,-20),20)/200),a=Pt.draglayer.select(".nsewdrag").node().getBoundingClientRect(),o=(e.clientX-a.left)/a.width,l=(a.bottom-e.clientY)/a.height;if(at){for(E||(o=.5),n=0;n<X.length;n++)c(X[n],o,i);Ft("x"),Ot[2]*=i,Ot[0]+=Ot[2]*o*(1/i-1)}if(ot){for(S||(l=.5),n=0;n<Z.length;n++)c(Z[n],l,i);Ft("y"),Ot[3]*=i,Ot[1]+=Ot[3]*(1-l)*(1/i-1)}jt(Ot),Bt(),It=setTimeout(function(){Ot=[0,0,K,Q],Nt()},Dt),e.preventDefault()}else s.log("Did not find wheel motion attributes: ",e)}function c(t,e,r){if(!t.fixedrange){var n=s.simpleMap(t.range,t.r2l),i=n[0]+(n[1]-n[0])*e;t.range=n.map(function(e){return t.l2r(i+(e-i)*r)})}}}),vt},makeDragger:E,makeRectDragger:C,makeZoombox:D,makeCorners:P,updateZoombox:R,xyCorners:V,transitionZoombox:F,removeZoombox:B,showDoubleClickNotifier:N,attachWheelEventHandler:q}},{"../../components/color":574,"../../components/dragelement":592,"../../components/drawing":595,"../../components/fx":613,"../../constants/alignment":669,"../../lib":697,"../../lib/clear_gl_canvases":682,"../../lib/setcursor":717,"../../lib/svg_text_utils":721,"../../plot_api/subroutines":736,"../../registry":826,"../plots":807,"./axes":745,"./axis_ids":748,"./constants":751,"./scale_zoom":761,"./select":762,d3:151,"has-passive-events":400,tinycolor2:518}],754:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../components/fx"),a=t("../../components/dragelement"),o=t("../../lib/setcursor"),s=t("./dragbox").makeDragBox,l=t("./constants").DRAGGERSIZE;r.initInteractions=function(t){var e=t._fullLayout;if(t._context.staticPlot)n.select(t).selectAll(".drag").remove();else if(e._has("cartesian")||e._has("splom")){Object.keys(e._plots||{}).sort(function(t,r){if((e._plots[t].mainplot&&!0)===(e._plots[r].mainplot&&!0)){var n=t.split("y"),i=r.split("y");return n[0]===i[0]?Number(n[1]||1)-Number(i[1]||1):Number(n[0]||1)-Number(i[0]||1)}return e._plots[t].mainplot?1:-1}).forEach(function(r){var n=e._plots[r],o=n.xaxis,c=n.yaxis;if(!n.mainplot){var u=s(t,n,o._offset,c._offset,o._length,c._length,"ns","ew");u.onmousemove=function(e){t._fullLayout._rehover=function(){t._fullLayout._hoversubplot===r&&i.hover(t,e,r)},i.hover(t,e,r),t._fullLayout._lasthover=u,t._fullLayout._hoversubplot=r},u.onmouseout=function(e){t._dragging||(t._fullLayout._hoversubplot=null,a.unhover(t,e))},t._context.showAxisDragHandles&&(s(t,n,o._offset-l,c._offset-l,l,l,"n","w"),s(t,n,o._offset+o._length,c._offset-l,l,l,"n","e"),s(t,n,o._offset-l,c._offset+c._length,l,l,"s","w"),s(t,n,o._offset+o._length,c._offset+c._length,l,l,"s","e"))}if(t._context.showAxisDragHandles){if(r===o._mainSubplot){var h=o._mainLinePosition;"top"===o.side&&(h-=l),s(t,n,o._offset+.1*o._length,h,.8*o._length,l,"","ew"),s(t,n,o._offset,h,.1*o._length,l,"","w"),s(t,n,o._offset+.9*o._length,h,.1*o._length,l,"","e")}if(r===c._mainSubplot){var f=c._mainLinePosition;"right"!==c.side&&(f-=l),s(t,n,f,c._offset+.1*c._length,l,.8*c._length,"ns",""),s(t,n,f,c._offset+.9*c._length,l,.1*c._length,"s",""),s(t,n,f,c._offset,l,.1*c._length,"n","")}}});var o=e._hoverlayer.node();o.onmousemove=function(r){r.target=t._fullLayout._lasthover,i.hover(t,r,e._hoversubplot)},o.onclick=function(e){e.target=t._fullLayout._lasthover,i.click(t,e)},o.onmousedown=function(e){t._fullLayout._lasthover.onmousedown(e)},r.updateFx(t)}},r.updateFx=function(t){var e=t._fullLayout,r="pan"===e.dragmode?"move":"crosshair";o(e._draggers,r)}},{"../../components/dragelement":592,"../../components/fx":613,"../../lib/setcursor":717,"./constants":751,"./dragbox":753,d3:151}],755:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("../../lib");e.exports=function(t){return function(e,r){var a=e[t];if(Array.isArray(a))for(var o=n.subplotsRegistry.cartesian,s=o.idRegex,l=r._subplots,c=l.xaxis,u=l.yaxis,h=l.cartesian,f=r._has("cartesian")||r._has("gl2d"),p=0;p<a.length;p++){var d=a[p];if(i.isPlainObject(d)){var g=d.xref,v=d.yref,m=s.x.test(g),y=s.y.test(v);if(m||y){f||i.pushUnique(r._basePlotModules,o);var x=!1;m&&-1===c.indexOf(g)&&(c.push(g),x=!0),y&&-1===u.indexOf(v)&&(u.push(v),x=!0),x&&m&&y&&h.push(g+v)}}}}}},{"../../lib":697,"../../registry":826}],756:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../registry"),a=t("../../lib"),o=t("../plots"),s=t("../../components/drawing"),l=t("../get_data").getModuleCalcData,c=t("./axis_ids"),u=t("./constants"),h=t("../../constants/xmlns_namespaces"),f=a.ensureSingle;function p(t,e,r){return a.ensureSingle(t,e,r,function(t){t.datum(r)})}function d(t,e,r,a,o){for(var c,h,f,p=u.traceLayerClasses,d=t._fullLayout,g=d._modules,v=[],m=[],y=0;y<g.length;y++){var x=(c=g[y]).name,b=i.modules[x].categories;if(b.svg){var _=c.layerName||x+"layer",w=c.plot;f=(h=l(r,w))[0],r=h[1],f.length&&v.push({i:p.indexOf(_),className:_,plotMethod:w,cdModule:f}),b.zoomScale&&m.push("."+_)}}v.sort(function(t,e){return t.i-e.i});var k=e.plot.selectAll("g.mlayer").data(v,function(t){return t.className});if(k.enter().append("g").attr("class",function(t){return t.className}).classed("mlayer",!0),k.exit().remove(),k.order(),k.each(function(r){var i=n.select(this),l=r.className;r.plotMethod(t,e,r.cdModule,i,a,o),"scatterlayer"!==l&&"barlayer"!==l&&s.setClipUrl(i,e.layerClipId,t)}),d._has("scattergl")&&(c=i.getModule("scattergl"),f=l(r,c)[0],c.plot(t,e,f)),!t._context.staticPlot&&(e._hasClipOnAxisFalse&&(e.clipOnAxisFalseTraces=e.plot.selectAll(".scatterlayer, .barlayer").selectAll(".trace")),m.length)){var A=e.plot.selectAll(m.join(",")).selectAll(".trace");e.zoomScalePts=A.selectAll("path.point"),e.zoomScaleTxt=A.selectAll(".textpoint")}}function g(t,e){var r=e.plotgroup,n=e.id,i=u.layerValue2layerClass[e.xaxis.layer],a=u.layerValue2layerClass[e.yaxis.layer],o=t._fullLayout._hasOnlyLargeSploms;if(e.mainplot){var s=e.mainplotinfo,l=s.plotgroup,h=n+"-x",d=n+"-y";e.gridlayer=s.gridlayer,e.zerolinelayer=s.zerolinelayer,f(s.overlinesBelow,"path",h),f(s.overlinesBelow,"path",d),f(s.overaxesBelow,"g",h),f(s.overaxesBelow,"g",d),e.plot=f(s.overplot,"g",n),f(s.overlinesAbove,"path",h),f(s.overlinesAbove,"path",d),f(s.overaxesAbove,"g",h),f(s.overaxesAbove,"g",d),e.xlines=l.select(".overlines-"+i).select("."+h),e.ylines=l.select(".overlines-"+a).select("."+d),e.xaxislayer=l.select(".overaxes-"+i).select("."+h),e.yaxislayer=l.select(".overaxes-"+a).select("."+d)}else if(o)e.xlines=f(r,"path","xlines-above"),e.ylines=f(r,"path","ylines-above"),e.xaxislayer=f(r,"g","xaxislayer-above"),e.yaxislayer=f(r,"g","yaxislayer-above");else{var g=f(r,"g","layer-subplot");e.shapelayer=f(g,"g","shapelayer"),e.imagelayer=f(g,"g","imagelayer"),e.gridlayer=f(r,"g","gridlayer"),e.zerolinelayer=f(r,"g","zerolinelayer"),f(r,"path","xlines-below"),f(r,"path","ylines-below"),e.overlinesBelow=f(r,"g","overlines-below"),f(r,"g","xaxislayer-below"),f(r,"g","yaxislayer-below"),e.overaxesBelow=f(r,"g","overaxes-below"),e.plot=f(r,"g","plot"),e.overplot=f(r,"g","overplot"),e.xlines=f(r,"path","xlines-above"),e.ylines=f(r,"path","ylines-above"),e.overlinesAbove=f(r,"g","overlines-above"),f(r,"g","xaxislayer-above"),f(r,"g","yaxislayer-above"),e.overaxesAbove=f(r,"g","overaxes-above"),e.xlines=r.select(".xlines-"+i),e.ylines=r.select(".ylines-"+a),e.xaxislayer=r.select(".xaxislayer-"+i),e.yaxislayer=r.select(".yaxislayer-"+a)}o||(p(e.gridlayer,"g",e.xaxis._id),p(e.gridlayer,"g",e.yaxis._id),e.gridlayer.selectAll("g").map(function(t){return t[0]}).sort(c.idSort)),e.xlines.style("fill","none").classed("crisp",!0),e.ylines.style("fill","none").classed("crisp",!0)}function v(t,e){if(t){var r={};for(var i in t.each(function(t){var i=t[0];n.select(this).remove(),m(i,e),r[i]=!0}),e._plots)for(var a=e._plots[i].overlays||[],o=0;o<a.length;o++){var s=a[o];r[s.id]&&s.plot.selectAll(".trace").remove()}}}function m(t,e){e._draggers.selectAll("g."+t).remove(),e._defs.select("#clip"+e._uid+t+"plot").remove()}r.name="cartesian",r.attr=["xaxis","yaxis"],r.idRoot=["x","y"],r.idRegex=u.idRegex,r.attrRegex=u.attrRegex,r.attributes=t("./attributes"),r.layoutAttributes=t("./layout_attributes"),r.supplyLayoutDefaults=t("./layout_defaults"),r.transitionAxes=t("./transition_axes"),r.finalizeSubplots=function(t,e){var r,n,i,o=e._subplots,s=o.xaxis,l=o.yaxis,h=o.cartesian,f=h.concat(o.gl2d||[]),p={},d={};for(r=0;r<f.length;r++){var g=f[r].split("y");p[g[0]]=1,d["y"+g[1]]=1}for(r=0;r<s.length;r++)p[n=s[r]]||(i=(t[c.id2name(n)]||{}).anchor,u.idRegex.y.test(i)||(i="y"),h.push(n+i),f.push(n+i),d[i]||(d[i]=1,a.pushUnique(l,i)));for(r=0;r<l.length;r++)d[i=l[r]]||(n=(t[c.id2name(i)]||{}).anchor,u.idRegex.x.test(n)||(n="x"),h.push(n+i),f.push(n+i),p[n]||(p[n]=1,a.pushUnique(s,n)));if(!f.length){for(var v in n="",i="",t){if(u.attrRegex.test(v))"x"===v.charAt(0)?(!n||+v.substr(5)<+n.substr(5))&&(n=v):(!i||+v.substr(5)<+i.substr(5))&&(i=v)}n=n?c.name2id(n):"x",i=i?c.name2id(i):"y",s.push(n),l.push(i),h.push(n+i)}},r.plot=function(t,e,r,n){var i,a=t._fullLayout,o=a._subplots.cartesian,s=t.calcdata;if(null!==e){if(!Array.isArray(e))for(e=[],i=0;i<s.length;i++)e.push(i);for(i=0;i<o.length;i++){for(var l,c=o[i],u=a._plots[c],h=[],f=0;f<s.length;f++){var p=s[f],g=p[0].trace;g.xaxis+g.yaxis===c&&((-1!==e.indexOf(g.index)||g.carpet)&&(l&&l[0].trace.xaxis+l[0].trace.yaxis===c&&-1!==["tonextx","tonexty","tonext"].indexOf(g.fill)&&-1===h.indexOf(l)&&h.push(l),h.push(p)),l=p)}d(t,u,h,r,n)}}},r.clean=function(t,e,r,n){var i,a,o,s=n._plots||{},l=e._plots||{},u=n._subplots||{};if(n._hasOnlyLargeSploms&&!e._hasOnlyLargeSploms)for(o in s)(i=s[o]).plotgroup&&i.plotgroup.remove();var h=n._has&&n._has("gl"),f=e._has&&e._has("gl");if(h&&!f)for(o in s)(i=s[o])._scene&&i._scene.destroy();if(u.xaxis&&u.yaxis){var p=c.listIds({_fullLayout:n});for(a=0;a<p.length;a++){var d=p[a];e[c.id2name(d)]||n._infolayer.selectAll(".g-"+d+"title").remove()}}var g=n._has&&n._has("cartesian"),y=e._has&&e._has("cartesian");if(g&&!y)v(n._cartesianlayer.selectAll(".subplot"),n),n._defs.selectAll(".axesclip").remove(),delete n._axisConstraintGroups;else if(u.cartesian)for(a=0;a<u.cartesian.length;a++){var x=u.cartesian[a];if(!l[x]){var b="."+x+",."+x+"-x,."+x+"-y";n._cartesianlayer.selectAll(b).remove(),m(x,n)}}},r.drawFramework=function(t){var e=t._fullLayout,r=function(t){var e,r,n,i,a,o,s=t._fullLayout,l=s._subplots.cartesian,c=l.length,u=[],h=[];for(e=0;e<c;e++){n=l[e],i=s._plots[n],a=i.xaxis,o=i.yaxis;var f=a._mainAxis,p=o._mainAxis,d=f._id+p._id,g=s._plots[d];i.overlays=[],d!==n&&g?(i.mainplot=d,i.mainplotinfo=g,h.push(n)):(i.mainplot=void 0,i.mainPlotinfo=void 0,u.push(n))}for(e=0;e<h.length;e++)n=h[e],(i=s._plots[n]).mainplotinfo.overlays.push(i);var v=u.concat(h),m=new Array(c);for(e=0;e<c;e++){n=v[e],i=s._plots[n],a=i.xaxis,o=i.yaxis;var y=[n,a.layer,o.layer,a.overlaying||"",o.overlaying||""];for(r=0;r<i.overlays.length;r++)y.push(i.overlays[r].id);m[e]=y}return m}(t),i=e._cartesianlayer.selectAll(".subplot").data(r,String);i.enter().append("g").attr("class",function(t){return"subplot "+t[0]}),i.order(),i.exit().call(v,e),i.each(function(r){var i=r[0],a=e._plots[i];a.plotgroup=n.select(this),g(t,a),a.draglayer=f(e._draggers,"g",i)})},r.rangePlot=function(t,e,r){g(t,e),d(t,e,r),o.style(t)},r.toSVG=function(t){var e=t._fullLayout._glimages,r=n.select(t).selectAll(".svg-container");r.filter(function(t,e){return e===r.size()-1}).selectAll(".gl-canvas-context, .gl-canvas-focus").each(function(){var t=this.toDataURL("image/png");e.append("svg:image").attr({xmlns:h.svg,"xlink:href":t,preserveAspectRatio:"none",x:0,y:0,width:this.width,height:this.height})})},r.updateFx=t("./graph_interact").updateFx},{"../../components/drawing":595,"../../constants/xmlns_namespaces":675,"../../lib":697,"../../registry":826,"../get_data":781,"../plots":807,"./attributes":743,"./axis_ids":748,"./constants":751,"./graph_interact":754,"./layout_attributes":757,"./layout_defaults":758,"./transition_axes":767,d3:151}],757:[function(t,e,r){"use strict";var n=t("../font_attributes"),i=t("../../components/color/attributes"),a=t("../../components/drawing/attributes").dash,o=t("../../lib/extend").extendFlat,s=t("../../plot_api/plot_template").templatedArray,l=t("./constants");e.exports={visible:{valType:"boolean",editType:"plot"},color:{valType:"color",dflt:i.defaultLine,editType:"ticks"},title:{text:{valType:"string",editType:"ticks"},font:n({editType:"ticks"}),editType:"ticks"},type:{valType:"enumerated",values:["-","linear","log","date","category","multicategory"],dflt:"-",editType:"calc",_noTemplating:!0},autorange:{valType:"enumerated",values:[!0,!1,"reversed"],dflt:!0,editType:"axrange",impliedEdits:{"range[0]":void 0,"range[1]":void 0}},rangemode:{valType:"enumerated",values:["normal","tozero","nonnegative"],dflt:"normal",editType:"plot"},range:{valType:"info_array",items:[{valType:"any",editType:"axrange",impliedEdits:{"^autorange":!1},anim:!0},{valType:"any",editType:"axrange",impliedEdits:{"^autorange":!1},anim:!0}],editType:"axrange",impliedEdits:{autorange:!1},anim:!0},fixedrange:{valType:"boolean",dflt:!1,editType:"calc"},scaleanchor:{valType:"enumerated",values:[l.idRegex.x.toString(),l.idRegex.y.toString()],editType:"plot"},scaleratio:{valType:"number",min:0,dflt:1,editType:"plot"},constrain:{valType:"enumerated",values:["range","domain"],dflt:"range",editType:"plot"},constraintoward:{valType:"enumerated",values:["left","center","right","top","middle","bottom"],editType:"plot"},matches:{valType:"enumerated",values:[l.idRegex.x.toString(),l.idRegex.y.toString()],editType:"calc"},tickmode:{valType:"enumerated",values:["auto","linear","array"],editType:"ticks",impliedEdits:{tick0:void 0,dtick:void 0}},nticks:{valType:"integer",min:0,dflt:0,editType:"ticks"},tick0:{valType:"any",editType:"ticks",impliedEdits:{tickmode:"linear"}},dtick:{valType:"any",editType:"ticks",impliedEdits:{tickmode:"linear"}},tickvals:{valType:"data_array",editType:"ticks"},ticktext:{valType:"data_array",editType:"ticks"},ticks:{valType:"enumerated",values:["outside","inside",""],editType:"ticks"},tickson:{valType:"enumerated",values:["labels","boundaries"],dflt:"labels",editType:"ticks"},mirror:{valType:"enumerated",values:[!0,"ticks",!1,"all","allticks"],dflt:!1,editType:"ticks+layoutstyle"},ticklen:{valType:"number",min:0,dflt:5,editType:"ticks"},tickwidth:{valType:"number",min:0,dflt:1,editType:"ticks"},tickcolor:{valType:"color",dflt:i.defaultLine,editType:"ticks"},showticklabels:{valType:"boolean",dflt:!0,editType:"ticks"},automargin:{valType:"boolean",dflt:!1,editType:"ticks"},showspikes:{valType:"boolean",dflt:!1,editType:"modebar"},spikecolor:{valType:"color",dflt:null,editType:"none"},spikethickness:{valType:"number",dflt:3,editType:"none"},spikedash:o({},a,{dflt:"dash",editType:"none"}),spikemode:{valType:"flaglist",flags:["toaxis","across","marker"],dflt:"toaxis",editType:"none"},spikesnap:{valType:"enumerated",values:["data","cursor"],dflt:"data",editType:"none"},tickfont:n({editType:"ticks"}),tickangle:{valType:"angle",dflt:"auto",editType:"ticks"},tickprefix:{valType:"string",dflt:"",editType:"ticks"},showtickprefix:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks"},ticksuffix:{valType:"string",dflt:"",editType:"ticks"},showticksuffix:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks"},showexponent:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks"},exponentformat:{valType:"enumerated",values:["none","e","E","power","SI","B"],dflt:"B",editType:"ticks"},separatethousands:{valType:"boolean",dflt:!1,editType:"ticks"},tickformat:{valType:"string",dflt:"",editType:"ticks"},tickformatstops:s("tickformatstop",{enabled:{valType:"boolean",dflt:!0,editType:"ticks"},dtickrange:{valType:"info_array",items:[{valType:"any",editType:"ticks"},{valType:"any",editType:"ticks"}],editType:"ticks"},value:{valType:"string",dflt:"",editType:"ticks"},editType:"ticks"}),hoverformat:{valType:"string",dflt:"",editType:"none"},showline:{valType:"boolean",dflt:!1,editType:"ticks+layoutstyle"},linecolor:{valType:"color",dflt:i.defaultLine,editType:"layoutstyle"},linewidth:{valType:"number",min:0,dflt:1,editType:"ticks+layoutstyle"},showgrid:{valType:"boolean",editType:"ticks"},gridcolor:{valType:"color",dflt:i.lightLine,editType:"ticks"},gridwidth:{valType:"number",min:0,dflt:1,editType:"ticks"},zeroline:{valType:"boolean",editType:"ticks"},zerolinecolor:{valType:"color",dflt:i.defaultLine,editType:"ticks"},zerolinewidth:{valType:"number",dflt:1,editType:"ticks"},showdividers:{valType:"boolean",dflt:!0,editType:"ticks"},dividercolor:{valType:"color",dflt:i.defaultLine,editType:"ticks"},dividerwidth:{valType:"number",dflt:1,editType:"ticks"},anchor:{valType:"enumerated",values:["free",l.idRegex.x.toString(),l.idRegex.y.toString()],editType:"plot"},side:{valType:"enumerated",values:["top","bottom","left","right"],editType:"plot"},overlaying:{valType:"enumerated",values:["free",l.idRegex.x.toString(),l.idRegex.y.toString()],editType:"plot"},layer:{valType:"enumerated",values:["above traces","below traces"],dflt:"above traces",editType:"plot"},domain:{valType:"info_array",items:[{valType:"number",min:0,max:1,editType:"plot"},{valType:"number",min:0,max:1,editType:"plot"}],dflt:[0,1],editType:"plot"},position:{valType:"number",min:0,max:1,dflt:0,editType:"plot"},categoryorder:{valType:"enumerated",values:["trace","category ascending","category descending","array"],dflt:"trace",editType:"calc"},categoryarray:{valType:"data_array",editType:"calc"},uirevision:{valType:"any",editType:"none"},editType:"calc",_deprecated:{autotick:{valType:"boolean",editType:"ticks"},title:{valType:"string",editType:"ticks"},titlefont:n({editType:"ticks"})}}},{"../../components/color/attributes":573,"../../components/drawing/attributes":594,"../../lib/extend":687,"../../plot_api/plot_template":735,"../font_attributes":771,"./constants":751}],758:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/color"),a=t("../../plot_api/plot_template"),o=t("../layout_attributes"),s=t("./layout_attributes"),l=t("./type_defaults"),c=t("./axis_defaults"),u=t("./constraints").handleConstraintDefaults,h=t("./position_defaults"),f=t("./axis_ids"),p=f.id2name,d=f.name2id,g=t("../../registry"),v=g.traceIs,m=g.getComponentMethod;function y(t,e,r){Array.isArray(t[e])?t[e].push(r):t[e]=[r]}e.exports=function(t,e,r){var f,g,x={},b={},_={},w={},k={};for(f=0;f<r.length;f++){var A=r[f];if(v(A,"cartesian")||v(A,"gl2d")){var M,T;if(A.xaxis)y(x,M=p(A.xaxis),A);else if(A.xaxes)for(g=0;g<A.xaxes.length;g++)y(x,p(A.xaxes[g]),A);if(A.yaxis)y(x,T=p(A.yaxis),A);else if(A.yaxes)for(g=0;g<A.yaxes.length;g++)y(x,p(A.yaxes[g]),A);if(v(A,"carpet")&&("carpet"!==A.type||A._cheater)||M&&(_[M]=1),"carpet"===A.type&&A._cheater&&M&&(b[M]=1),v(A,"2dMap")&&(w[M]=1,w[T]=1),v(A,"oriented"))k["h"===A.orientation?T:M]=1}}var S=e._subplots,E=S.xaxis,C=S.yaxis,L=n.simpleMap(E,p),z=n.simpleMap(C,p),O=L.concat(z),I=i.background;E.length&&C.length&&(I=n.coerce(t,e,o,"plot_bgcolor"));var D,P,R,F,B=i.combine(I,e.paper_bgcolor);function N(t,e){return n.coerce(R,F,s,t,e)}function j(t,e){return n.coerce2(R,F,s,t,e)}function V(t){return"x"===t?C:E}var U={x:V("x"),y:V("y")},q=U.x.concat(U.y);function H(e,r){for(var n="x"===e?L:z,i=[],a=0;a<n.length;a++){var o=n[a];o===r||(t[o]||{}).overlaying||i.push(d(o))}return i}for(f=0;f<O.length;f++){P=(D=O[f]).charAt(0),n.isPlainObject(t[D])||(t[D]={}),R=t[D],F=a.newContainer(e,D,P+"axis");var G=x[D]||[];F._traceIndices=G.map(function(t){return t._expandedIndex}),F._annIndices=[],F._shapeIndices=[],F._imgIndices=[],F._subplotsWith=[],F._counterAxes=[],F._name=F._attr=D;var Y=F._id=d(D),W=H(P,D),X={letter:P,font:e.font,outerTicks:w[D],showGrid:!k[D],data:G,bgColor:B,calendar:e.calendar,automargin:!0,cheateronly:"x"===P&&b[D]&&!_[D],splomStash:((e._splomAxes||{})[P]||{})[Y]};N("uirevision",e.uirevision),l(R,F,N,X),c(R,F,N,X,e);var Z=j("spikecolor"),$=j("spikethickness"),J=j("spikedash"),K=j("spikemode"),Q=j("spikesnap");N("showspikes",!!(Z||$||J||K||Q))||(delete F.spikecolor,delete F.spikethickness,delete F.spikedash,delete F.spikemode,delete F.spikesnap),h(R,F,N,{letter:P,counterAxes:U[P],overlayableAxes:W,grid:e.grid}),F._input=R}var tt=m("rangeslider","handleDefaults"),et=m("rangeselector","handleDefaults");for(f=0;f<L.length;f++)D=L[f],R=t[D],F=e[D],tt(t,e,D),"date"===F.type&&et(R,F,e,z,F.calendar),N("fixedrange");for(f=0;f<z.length;f++){D=z[f],R=t[D],F=e[D];var rt=e[p(F.anchor)];N("fixedrange",m("rangeslider","isVisible")(rt))}var nt=e._axisConstraintGroups=[],it=e._axisMatchGroups=[];for(f=0;f<O.length;f++)P=(D=O[f]).charAt(0),R=t[D],F=e[D],u(R,F,N,q,e);for(f=0;f<it.length;f++){var at,ot=it[f],st=null,lt=null;for(at in ot)(F=e[p(at)]).matches||(st=F.range,lt=F.autorange);if(null===st||null===lt)for(at in ot){st=(F=e[p(at)]).range,lt=F.autorange;break}for(at in ot)(F=e[p(at)]).matches&&(F.range=st.slice(),F.autorange=lt),F._matchGroup=ot;if(nt.length)for(at in ot)for(g=0;g<nt.length;g++){var ct=nt[g];for(var ut in ct)at===ut&&(n.warn("Axis "+ut+" is set with both a *scaleanchor* and *matches* constraint; ignoring the scale constraint."),delete ct[ut],Object.keys(ct).length<2&&nt.splice(g,1))}}}},{"../../components/color":574,"../../lib":697,"../../plot_api/plot_template":735,"../../registry":826,"../layout_attributes":798,"./axis_defaults":747,"./axis_ids":748,"./constraints":752,"./layout_attributes":757,"./position_defaults":760,"./type_defaults":768}],759:[function(t,e,r){"use strict";var n=t("tinycolor2").mix,i=t("../../components/color/attributes").lightFraction,a=t("../../lib");e.exports=function(t,e,r,o){var s=(o=o||{}).dfltColor;function l(r,n){return a.coerce2(t,e,o.attributes,r,n)}var c=l("linecolor",s),u=l("linewidth");r("showline",o.showLine||!!c||!!u)||(delete e.linecolor,delete e.linewidth);var h=l("gridcolor",n(s,o.bgColor,o.blend||i).toRgbString()),f=l("gridwidth");if(r("showgrid",o.showGrid||!!h||!!f)||(delete e.gridcolor,delete e.gridwidth),!o.noZeroLine){var p=l("zerolinecolor",s),d=l("zerolinewidth");r("zeroline",o.showGrid||!!p||!!d)||(delete e.zerolinecolor,delete e.zerolinewidth)}}},{"../../components/color/attributes":573,"../../lib":697,tinycolor2:518}],760:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib");e.exports=function(t,e,r,a){var o,s,l,c,u=a.counterAxes||[],h=a.overlayableAxes||[],f=a.letter,p=a.grid;p&&(s=p._domains[f][p._axisMap[e._id]],o=p._anchors[e._id],s&&(l=p[f+"side"].split(" ")[0],c=p.domain[f]["right"===l||"top"===l?1:0])),s=s||[0,1],o=o||(n(t.position)?"free":u[0]||"free"),l=l||("x"===f?"bottom":"left"),c=c||0,"free"===i.coerce(t,e,{anchor:{valType:"enumerated",values:["free"].concat(u),dflt:o}},"anchor")&&r("position",c),i.coerce(t,e,{side:{valType:"enumerated",values:"x"===f?["bottom","top"]:["left","right"],dflt:l}},"side");var d=!1;if(h.length&&(d=i.coerce(t,e,{overlaying:{valType:"enumerated",values:[!1].concat(h),dflt:!1}},"overlaying")),!d){var g=r("domain",s);g[0]>g[1]-1/4096&&(e.domain=s),i.noneOrAll(t.domain,e.domain,s)}return r("layer"),e}},{"../../lib":697,"fast-isnumeric":218}],761:[function(t,e,r){"use strict";var n=t("../../constants/alignment").FROM_BL;e.exports=function(t,e,r){void 0===r&&(r=n[t.constraintoward||"center"]);var i=[t.r2l(t.range[0]),t.r2l(t.range[1])],a=i[0]+(i[1]-i[0])*r;t.range=t._input.range=[t.l2r(a+(i[0]-a)*e),t.l2r(a+(i[1]-a)*e)]}},{"../../constants/alignment":669}],762:[function(t,e,r){"use strict";var n=t("polybooljs"),i=t("../../registry"),a=t("../../components/color"),o=t("../../components/fx"),s=t("../../lib/polygon"),l=t("../../lib/throttle"),c=t("../../components/fx/helpers").makeEventData,u=t("./axis_ids").getFromId,h=t("../../lib/clear_gl_canvases"),f=t("../../plot_api/subroutines").redrawReglTraces,p=t("./constants"),d=p.MINSELECT,g=s.filter,v=s.tester;function m(t){return t._id}function y(t,e,r,n,i,a,o){var s,l,c,u,h,f,p,d,g,v=e._hoverdata,m=e._fullLayout.clickmode.indexOf("event")>-1,y=[];if(function(t){return t&&Array.isArray(t)&&!0!==t[0].hoverOnBox}(v)){w(t,e,a);var x=function(t,e){var r,n,i=t[0],a=-1,o=[];for(n=0;n<e.length;n++)if(r=e[n],i.fullData._expandedIndex===r.cd[0].trace._expandedIndex){if(!0===i.hoverOnBox)break;void 0!==i.pointNumber?a=i.pointNumber:void 0!==i.binNumber&&(a=i.binNumber,o=i.pointNumbers);break}return{pointNumber:a,pointNumbers:o,searchInfo:r}}(v,s=A(e,r,n,i));if(x.pointNumbers.length>0?function(t,e){var r,n,i,a=[];for(i=0;i<t.length;i++)(r=t[i]).cd[0].trace.selectedpoints&&r.cd[0].trace.selectedpoints.length>0&&a.push(r);if(1===a.length&&a[0]===e.searchInfo&&(n=e.searchInfo.cd[0].trace).selectedpoints.length===e.pointNumbers.length){for(i=0;i<e.pointNumbers.length;i++)if(n.selectedpoints.indexOf(e.pointNumbers[i])<0)return!1;return!0}return!1}(s,x):function(t){var e,r,n,i=0;for(n=0;n<t.length;n++)if(e=t[n],(r=e.cd[0].trace).selectedpoints){if(r.selectedpoints.length>1)return!1;if((i+=r.selectedpoints.length)>1)return!1}return 1===i}(s)&&(f=T(x))){for(o&&o.remove(),g=0;g<s.length;g++)(l=s[g])._module.selectPoints(l,!1);S(e,s),k(a),m&&e.emit("plotly_deselect",null)}else{for(p=t.shiftKey&&(void 0!==f?f:T(x)),c=function(t,e,r){return{pointNumber:t,searchInfo:e,subtract:r}}(x.pointNumber,x.searchInfo,p),u=_(a.selectionDefs.concat([c])),g=0;g<s.length;g++)if(h=E(s[g]._module.selectPoints(s[g],u),s[g]),y.length)for(var b=0;b<h.length;b++)y.push(h[b]);else y=h;S(e,s,d={points:y}),c&&a&&a.selectionDefs.push(c),o&&M(a.mergedPolygons,o),m&&e.emit("plotly_selected",d)}}}function x(t){return"pointNumber"in t&&"searchInfo"in t}function b(t){return{xmin:0,xmax:0,ymin:0,ymax:0,pts:[],contains:function(e,r,n,i){var a=t.searchInfo.cd[0].trace._expandedIndex;return i.cd[0].trace._expandedIndex===a&&n===t.pointNumber},isRect:!1,degenerate:!1,subtract:t.subtract}}function _(t){for(var e=[],r=x(t[0])?0:t[0][0][0],n=r,i=x(t[0])?0:t[0][0][1],a=i,o=0;o<t.length;o++)if(x(t[o]))e.push(b(t[o]));else{var l=s.tester(t[o]);l.subtract=t[o].subtract,e.push(l),r=Math.min(r,l.xmin),n=Math.max(n,l.xmax),i=Math.min(i,l.ymin),a=Math.max(a,l.ymax)}return{xmin:r,xmax:n,ymin:i,ymax:a,pts:[],contains:function(t,r,n,i){for(var a=!1,o=0;o<e.length;o++)e[o].contains(t,r,n,i)&&(a=!1===e[o].subtract);return a},isRect:!1,degenerate:!1}}function w(t,e,r){var n=e._fullLayout,i=n._zoomlayer,a=r.plotinfo,o=n._lastSelectedSubplot&&n._lastSelectedSubplot===a.id,s=t.shiftKey||t.altKey;o&&s&&a.selection&&a.selection.selectionDefs&&!r.selectionDefs?(r.selectionDefs=a.selection.selectionDefs,r.mergedPolygons=a.selection.mergedPolygons):s&&a.selection||k(r),o||(C(i),n._lastSelectedSubplot=a.id)}function k(t){var e=t.plotinfo;e.selection={},e.selection.selectionDefs=t.selectionDefs=[],e.selection.mergedPolygons=t.mergedPolygons=[]}function A(t,e,r,n){var i,a,o,s=[],l=e.map(m),c=r.map(m);for(o=0;o<t.calcdata.length;o++)if(!0===(a=(i=t.calcdata[o])[0].trace).visible&&a._module&&a._module.selectPoints)if(!n||a.subplot!==n&&a.geo!==n)if("splom"===a.type&&a._xaxes[l[0]]&&a._yaxes[c[0]]){var h=f(a._module,i,e[0],r[0]);h.scene=t._fullLayout._splomScenes[a.uid],s.push(h)}else{if(-1===l.indexOf(a.xaxis))continue;if(-1===c.indexOf(a.yaxis))continue;s.push(f(a._module,i,u(t,a.xaxis),u(t,a.yaxis)))}else s.push(f(a._module,i,e[0],r[0]));return s;function f(t,e,r,n){return{_module:t,cd:e,xaxis:r,yaxis:n}}}function M(t,e){var r,n,i=[];for(r=0;r<t.length;r++){var a=t[r];i.push(a.join("L")+"L"+a[0])}n=t.length>0?"M"+i.join("M")+"Z":"M0,0Z",e.attr("d",n)}function T(t){var e=t.searchInfo.cd[0].trace,r=t.pointNumber,n=t.pointNumbers,i=n.length>0?n[0]:r;return!!e.selectedpoints&&e.selectedpoints.indexOf(i)>-1}function S(t,e,r){var n,a,o,s;for(n=0;n<e.length;n++){var l=e[n].cd[0].trace._fullInput,c=t._fullLayout._tracePreGUI[l.uid];void 0===c.selectedpoints&&(c.selectedpoints=l._input.selectedpoints||null)}if(r){var u=r.points||[];for(n=0;n<e.length;n++)(s=e[n].cd[0].trace)._input.selectedpoints=s._fullInput.selectedpoints=[],s._fullInput!==s&&(s.selectedpoints=[]);for(n=0;n<u.length;n++){var p=u[n],d=p.data,g=p.fullData;p.pointIndices?([].push.apply(d.selectedpoints,p.pointIndices),s._fullInput!==s&&[].push.apply(g.selectedpoints,p.pointIndices)):(d.selectedpoints.push(p.pointIndex),s._fullInput!==s&&g.selectedpoints.push(p.pointIndex))}}else for(n=0;n<e.length;n++)delete(s=e[n].cd[0].trace).selectedpoints,delete s._input.selectedpoints,s._fullInput!==s&&delete s._fullInput.selectedpoints;var v=!1;for(n=0;n<e.length;n++){s=(o=(a=e[n]).cd)[0].trace,i.traceIs(s,"regl")&&(v=!0);var m=a._module,y=m.styleOnSelect||m.style;y&&y(t,o)}v&&(h(t),f(t))}function E(t,e){if(Array.isArray(t))for(var r=e.cd,n=e.cd[0].trace,i=0;i<t.length;i++)t[i]=c(t[i],n,r);return t}function C(t){t.selectAll(".select-outline").remove()}e.exports={prepSelect:function(t,e,r,i,s){var c,u,h,f,m,x,b,T=i.gd,C=T._fullLayout,L=C._zoomlayer,z=i.element.getBoundingClientRect(),O=i.plotinfo,I=O.xaxis._offset,D=O.yaxis._offset,P=e-z.left,R=r-z.top,F=P,B=R,N="M"+P+","+R,j=i.xaxes[0]._length,V=i.yaxes[0]._length,U=i.xaxes.concat(i.yaxes),q=t.altKey;w(t,T,i),"lasso"===s&&(c=g([[P,R]],p.BENDPX));var H=L.selectAll("path.select-outline-"+O.id).data([1,2]);H.enter().append("path").attr("class",function(t){return"select-outline select-outline-"+t+" select-outline-"+O.id}).attr("transform","translate("+I+", "+D+")").attr("d",N+"Z");var G,Y=L.append("path").attr("class","zoombox-corners").style({fill:a.background,stroke:a.defaultLine,"stroke-width":1}).attr("transform","translate("+I+", "+D+")").attr("d","M0,0Z"),W=C._uid+p.SELECTID,X=[],Z=A(T,i.xaxes,i.yaxes,i.subplot);function $(t){var e="y"===t._id.charAt(0)?1:0;return function(r){return t.p2d(r[e])}}function J(t,e){return t-e}G=O.fillRangeItems?O.fillRangeItems:"select"===s?function(t,e){var r=t.range={};for(m=0;m<U.length;m++){var n=U[m],i=n._id.charAt(0);r[n._id]=[n.p2d(e[i+"min"]),n.p2d(e[i+"max"])].sort(J)}}:function(t,e,r){var n=t.lassoPoints={};for(m=0;m<U.length;m++){var i=U[m];n[i._id]=r.filtered.map($(i))}},i.moveFn=function(t,e){F=Math.max(0,Math.min(j,t+P)),B=Math.max(0,Math.min(V,e+R));var r=Math.abs(F-P),a=Math.abs(B-R);if("select"===s){var o=C.selectdirection;"h"===(o="any"===C.selectdirection?a<Math.min(.6*r,d)?"h":r<Math.min(.6*a,d)?"v":"d":C.selectdirection)?((f=[[P,0],[P,V],[F,V],[F,0]]).xmin=Math.min(P,F),f.xmax=Math.max(P,F),f.ymin=Math.min(0,V),f.ymax=Math.max(0,V),Y.attr("d","M"+f.xmin+","+(R-d)+"h-4v"+2*d+"h4ZM"+(f.xmax-1)+","+(R-d)+"h4v"+2*d+"h-4Z")):"v"===o?((f=[[0,R],[0,B],[j,B],[j,R]]).xmin=Math.min(0,j),f.xmax=Math.max(0,j),f.ymin=Math.min(R,B),f.ymax=Math.max(R,B),Y.attr("d","M"+(P-d)+","+f.ymin+"v-4h"+2*d+"v4ZM"+(P-d)+","+(f.ymax-1)+"v4h"+2*d+"v-4Z")):"d"===o&&((f=[[P,R],[P,B],[F,B],[F,R]]).xmin=Math.min(P,F),f.xmax=Math.max(P,F),f.ymin=Math.min(R,B),f.ymax=Math.max(R,B),Y.attr("d","M0,0Z"))}else"lasso"===s&&(c.addPt([F,B]),f=c.filtered);i.selectionDefs&&i.selectionDefs.length?(h=function(t,e,r){return r?n.difference({regions:t,inverted:!1},{regions:[e],inverted:!1}).regions:n.union({regions:t,inverted:!1},{regions:[e],inverted:!1}).regions}(i.mergedPolygons,f,q),f.subtract=q,u=_(i.selectionDefs.concat([f]))):(h=[f],u=v(f)),M(h,H),l.throttle(W,p.SELECTDELAY,function(){var t;X=[];var e,r=[];for(m=0;m<Z.length;m++)if(e=(x=Z[m])._module.selectPoints(x,u),r.push(e),t=E(e,x),X.length)for(var n=0;n<t.length;n++)X.push(t[n]);else X=t;S(T,Z,b={points:X}),G(b,f,c),i.gd.emit("plotly_selecting",b)})},i.clickFn=function(t,e){var r=C.clickmode;Y.remove(),l.done(W).then(function(){if(l.clear(W),2===t){for(H.remove(),m=0;m<Z.length;m++)(x=Z[m])._module.selectPoints(x,!1);S(T,Z),k(i),T.emit("plotly_deselect",null)}else r.indexOf("select")>-1&&y(e,T,i.xaxes,i.yaxes,i.subplot,i,H),"event"===r&&T.emit("plotly_selected",void 0);o.click(T,e)})},i.doneFn=function(){Y.remove(),l.done(W).then(function(){l.clear(W),i.gd.emit("plotly_selected",b),f&&i.selectionDefs&&(f.subtract=q,i.selectionDefs.push(f),i.mergedPolygons.length=0,[].push.apply(i.mergedPolygons,h))})}},clearSelect:C,selectOnClick:y}},{"../../components/color":574,"../../components/fx":613,"../../components/fx/helpers":609,"../../lib/clear_gl_canvases":682,"../../lib/polygon":709,"../../lib/throttle":722,"../../plot_api/subroutines":736,"../../registry":826,"./axis_ids":748,"./constants":751,polybooljs:462}],763:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../../lib"),o=a.cleanNumber,s=a.ms2DateTime,l=a.dateTime2ms,c=a.ensureNumber,u=a.isArrayOrTypedArray,h=t("../../constants/numerical"),f=h.FP_SAFE,p=h.BADNUM,d=h.LOG_CLIP,g=t("./constants"),v=t("./axis_ids");function m(t){return Math.pow(10,t)}function y(t){return null!=t}e.exports=function(t,e){e=e||{};var r=t._id||"x",h=r.charAt(0);function x(e,r){if(e>0)return Math.log(e)/Math.LN10;if(e<=0&&r&&t.range&&2===t.range.length){var n=t.range[0],i=t.range[1];return.5*(n+i-2*d*Math.abs(n-i))}return p}function b(e,r,n){var o=l(e,n||t.calendar);if(o===p){if(!i(e))return p;e=+e;var s=Math.floor(10*a.mod(e+.05,1)),c=Math.round(e-s/10);o=l(new Date(c))+s/10}return o}function _(e,r,n){return s(e,r,n||t.calendar)}function w(e){return t._categories[Math.round(e)]}function k(e){if(y(e)){if(void 0===t._categoriesMap&&(t._categoriesMap={}),void 0!==t._categoriesMap[e])return t._categoriesMap[e];t._categories.push(e);var r=t._categories.length-1;return t._categoriesMap[e]=r,r}return p}function A(e){if(t._categoriesMap)return t._categoriesMap[e]}function M(t){var e=A(t);return void 0!==e?e:i(t)?+t:void 0}function T(e){return i(e)?n.round(t._b+t._m*e,2):p}function S(e){return(e-t._b)/t._m}t.c2l="log"===t.type?x:c,t.l2c="log"===t.type?m:c,t.l2p=T,t.p2l=S,t.c2p="log"===t.type?function(t,e){return T(x(t,e))}:T,t.p2c="log"===t.type?function(t){return m(S(t))}:S,-1!==["linear","-"].indexOf(t.type)?(t.d2r=t.r2d=t.d2c=t.r2c=t.d2l=t.r2l=o,t.c2d=t.c2r=t.l2d=t.l2r=c,t.d2p=t.r2p=function(e){return t.l2p(o(e))},t.p2d=t.p2r=S,t.cleanPos=c):"log"===t.type?(t.d2r=t.d2l=function(t,e){return x(o(t),e)},t.r2d=t.r2c=function(t){return m(o(t))},t.d2c=t.r2l=o,t.c2d=t.l2r=c,t.c2r=x,t.l2d=m,t.d2p=function(e,r){return t.l2p(t.d2r(e,r))},t.p2d=function(t){return m(S(t))},t.r2p=function(e){return t.l2p(o(e))},t.p2r=S,t.cleanPos=c):"date"===t.type?(t.d2r=t.r2d=a.identity,t.d2c=t.r2c=t.d2l=t.r2l=b,t.c2d=t.c2r=t.l2d=t.l2r=_,t.d2p=t.r2p=function(e,r,n){return t.l2p(b(e,0,n))},t.p2d=t.p2r=function(t,e,r){return _(S(t),e,r)},t.cleanPos=function(e){return a.cleanDate(e,p,t.calendar)}):"category"===t.type?(t.d2c=t.d2l=k,t.r2d=t.c2d=t.l2d=w,t.d2r=t.d2l_noadd=M,t.r2c=function(e){var r=M(e);return void 0!==r?r:t.fraction2r(.5)},t.l2r=t.c2r=c,t.r2l=M,t.d2p=function(e){return t.l2p(t.r2c(e))},t.p2d=function(t){return w(S(t))},t.r2p=t.d2p,t.p2r=S,t.cleanPos=function(t){return"string"==typeof t&&""!==t?t:c(t)}):"multicategory"===t.type&&(t.r2d=t.c2d=t.l2d=w,t.d2r=t.d2l_noadd=M,t.r2c=function(e){var r=M(e);return void 0!==r?r:t.fraction2r(.5)},t.r2c_just_indices=A,t.l2r=t.c2r=c,t.r2l=M,t.d2p=function(e){return t.l2p(t.r2c(e))},t.p2d=function(t){return w(S(t))},t.r2p=t.d2p,t.p2r=S,t.cleanPos=function(t){return Array.isArray(t)||"string"==typeof t&&""!==t?t:c(t)},t.setupMultiCategory=function(n){var i,o,s=t._traceIndices,l=e._axisMatchGroups;if(l&&l.length&&0===t._categories.length)for(i=0;i<l.length;i++){var c=l[i];if(c[r])for(var f in c)if(f!==r){var p=e[v.id2name(f)];s=s.concat(p._traceIndices)}}var d=[[0,{}],[0,{}]],g=[];for(i=0;i<s.length;i++){var m=n[s[i]];if(h in m){var x=m[h],b=m._length||a.minRowLength(x);if(u(x[0])&&u(x[1]))for(o=0;o<b;o++){var _=x[0][o],w=x[1][o];y(_)&&y(w)&&(g.push([_,w]),_ in d[0][1]||(d[0][1][_]=d[0][0]++),w in d[1][1]||(d[1][1][w]=d[1][0]++))}}}for(g.sort(function(t,e){var r=d[0][1],n=r[t[0]]-r[e[0]];if(n)return n;var i=d[1][1];return i[t[1]]-i[e[1]]}),i=0;i<g.length;i++)k(g[i])}),t.fraction2r=function(e){var r=t.r2l(t.range[0]),n=t.r2l(t.range[1]);return t.l2r(r+e*(n-r))},t.r2fraction=function(e){var r=t.r2l(t.range[0]),n=t.r2l(t.range[1]);return(t.r2l(e)-r)/(n-r)},t.cleanRange=function(e,r){r||(r={}),e||(e="range");var n,o,s=a.nestedProperty(t,e).get();if(o=(o="date"===t.type?a.dfltRange(t.calendar):"y"===h?g.DFLTRANGEY:r.dfltRange||g.DFLTRANGEX).slice(),s&&2===s.length)for("date"===t.type&&(s[0]=a.cleanDate(s[0],p,t.calendar),s[1]=a.cleanDate(s[1],p,t.calendar)),n=0;n<2;n++)if("date"===t.type){if(!a.isDateTime(s[n],t.calendar)){t[e]=o;break}if(t.r2l(s[0])===t.r2l(s[1])){var l=a.constrain(t.r2l(s[0]),a.MIN_MS+1e3,a.MAX_MS-1e3);s[0]=t.l2r(l-1e3),s[1]=t.l2r(l+1e3);break}}else{if(!i(s[n])){if(!i(s[1-n])){t[e]=o;break}s[n]=s[1-n]*(n?10:.1)}if(s[n]<-f?s[n]=-f:s[n]>f&&(s[n]=f),s[0]===s[1]){var c=Math.max(1,Math.abs(1e-6*s[0]));s[0]-=c,s[1]+=c}}else a.nestedProperty(t,e).set(o)},t.setScale=function(r){var n=e._size;if(t.overlaying){var i=v.getFromId({_fullLayout:e},t.overlaying);t.domain=i.domain}var a=r&&t._r?"_r":"range",o=t.calendar;t.cleanRange(a);var s=t.r2l(t[a][0],o),l=t.r2l(t[a][1],o);if("y"===h?(t._offset=n.t+(1-t.domain[1])*n.h,t._length=n.h*(t.domain[1]-t.domain[0]),t._m=t._length/(s-l),t._b=-t._m*l):(t._offset=n.l+t.domain[0]*n.w,t._length=n.w*(t.domain[1]-t.domain[0]),t._m=t._length/(l-s),t._b=-t._m*s),!isFinite(t._m)||!isFinite(t._b)||t._length<0)throw e._replotting=!1,new Error("Something went wrong with axis scaling")},t.makeCalcdata=function(e,r){var n,i,o,s,l=t.type,c="date"===l&&e[r+"calendar"];if(r in e){if(n=e[r],s=e._length||a.minRowLength(n),a.isTypedArray(n)&&("linear"===l||"log"===l)){if(s===n.length)return n;if(n.subarray)return n.subarray(0,s)}if("multicategory"===l)return function(t,e){for(var r=new Array(e),n=0;n<e;n++){var i=(t[0]||[])[n],a=(t[1]||[])[n];r[n]=A([i,a])}return r}(n,s);for(i=new Array(s),o=0;o<s;o++)i[o]=t.d2c(n[o],0,c)}else{var u=r+"0"in e?t.d2c(e[r+"0"],0,c):0,h=e["d"+r]?Number(e["d"+r]):1;for(n=e[{x:"y",y:"x"}[r]],s=e._length||n.length,i=new Array(s),o=0;o<s;o++)i[o]=u+o*h}return i},t.isValidRange=function(e){return Array.isArray(e)&&2===e.length&&i(t.r2l(e[0]))&&i(t.r2l(e[1]))},t.isPtWithinRange=function(e,r){var n=t.c2l(e[h],null,r),i=t.r2l(t.range[0]),a=t.r2l(t.range[1]);return i<a?i<=n&&n<=a:a<=n&&n<=i},t.clearCalc=function(){var n=function(){t._categories=[],t._categoriesMap={}},i=e._axisMatchGroups;if(i&&i.length){for(var a=!1,o=0;o<i.length;o++){var s=i[o];if(s[r]){a=!0;var l=null,c=null;for(var u in s){var h=e[v.id2name(u)];if(h._categories){l=h._categories,c=h._categoriesMap;break}}l&&c?(t._categories=l,t._categoriesMap=c):n();break}}a||n()}else n();if(t._initialCategories)for(var f=0;f<t._initialCategories.length;f++)k(t._initialCategories[f])};var E=e._d3locale;"date"===t.type&&(t._dateFormat=E?E.timeFormat.utc:n.time.format.utc,t._extraFormat=e._extraFormat),t._separators=e.separators,t._numFormat=E?E.numberFormat:n.format,delete t._minDtick,delete t._forceTick0}},{"../../constants/numerical":674,"../../lib":697,"./axis_ids":748,"./constants":751,d3:151,"fast-isnumeric":218}],764:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./layout_attributes"),a=t("../array_container_defaults");function o(t,e){function r(r,a){return n.coerce(t,e,i.tickformatstops,r,a)}r("enabled")&&(r("dtickrange"),r("value"))}e.exports=function(t,e,r,s,l){var c=function(t){var e=["showexponent","showtickprefix","showticksuffix"].filter(function(e){return void 0!==t[e]});if(e.every(function(r){return t[r]===t[e[0]]})||1===e.length)return t[e[0]]}(t);if(r("tickprefix")&&r("showtickprefix",c),r("ticksuffix",l.tickSuffixDflt)&&r("showticksuffix",c),r("showticklabels")){var u=l.font||{},h=e.color,f=h&&h!==i.color.dflt?h:u.color;if(n.coerceFont(r,"tickfont",{family:u.family,size:u.size,color:f}),r("tickangle"),"category"!==s){var p=r("tickformat"),d=t.tickformatstops;Array.isArray(d)&&d.length&&a(t,e,{name:"tickformatstops",inclusionAttr:"enabled",handleItemDefaults:o}),p||"date"===s||(r("showexponent",c),r("exponentformat"),r("separatethousands"))}}}},{"../../lib":697,"../array_container_defaults":741,"./layout_attributes":757}],765:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./layout_attributes");e.exports=function(t,e,r,a){var o=n.coerce2(t,e,i,"ticklen"),s=n.coerce2(t,e,i,"tickwidth"),l=n.coerce2(t,e,i,"tickcolor",e.color);r("ticks",a.outerTicks||o||s||l?"outside":"")||(delete e.ticklen,delete e.tickwidth,delete e.tickcolor)}},{"../../lib":697,"./layout_attributes":757}],766:[function(t,e,r){"use strict";var n=t("./clean_ticks");e.exports=function(t,e,r,i){var a;"array"!==t.tickmode||"log"!==i&&"date"!==i?a=r("tickmode",Array.isArray(t.tickvals)?"array":t.dtick?"linear":"auto"):a=e.tickmode="auto";if("auto"===a)r("nticks");else if("linear"===a){var o=e.dtick=n.dtick(t.dtick,i);e.tick0=n.tick0(t.tick0,i,e.calendar,o)}else if("multicategory"!==i){void 0===r("tickvals")?e.tickmode="auto":r("ticktext")}}},{"./clean_ticks":750}],767:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../registry"),a=t("../../components/drawing"),o=t("./axes");e.exports=function(t,e,r,s){var l=t._fullLayout;if(0!==e.length){var c,u,h,f;s&&(c=s());var p=n.ease(r.easing);return t._transitionData._interruptCallbacks.push(function(){return window.cancelAnimationFrame(f),f=null,function(){for(var r={},n=0;n<e.length;n++){var a=e[n];a.xr0&&(r[a.plotinfo.xaxis._name+".range"]=a.xr0.slice()),a.yr0&&(r[a.plotinfo.yaxis._name+".range"]=a.yr0.slice())}return i.call("relayout",t,r).then(function(){for(var t=0;t<e.length;t++)d(e[t].plotinfo)})}()}),u=Date.now(),f=window.requestAnimationFrame(function n(){h=Date.now();for(var a=Math.min(1,(h-u)/r.duration),o=p(a),s=0;s<e.length;s++)g(e[s],o);h-u>r.duration?(function(){for(var r={},n=0;n<e.length;n++){var a=e[n];a.xr1&&(r[a.plotinfo.xaxis._name+".range"]=a.xr1.slice()),a.yr1&&(r[a.plotinfo.yaxis._name+".range"]=a.yr1.slice())}c&&c(),i.call("relayout",t,r).then(function(){for(var t=0;t<e.length;t++)d(e[t].plotinfo)})}(),f=window.cancelAnimationFrame(n)):f=window.requestAnimationFrame(n)}),Promise.resolve()}function d(t){var e=t.xaxis,r=t.yaxis;l._defs.select("#"+t.clipId+"> rect").call(a.setTranslate,0,0).call(a.setScale,1,1),t.plot.call(a.setTranslate,e._offset,r._offset).call(a.setScale,1,1);var n=t.plot.selectAll(".scatterlayer .trace");n.selectAll(".point").call(a.setPointGroupScale,1,1),n.selectAll(".textpoint").call(a.setTextPointsScale,1,1),n.call(a.hideOutsideRangePoints,t)}function g(e,r){var n=e.plotinfo,i=n.xaxis,s=n.yaxis,l=e.xr0,c=e.xr1,u=i._length,h=e.yr0,f=e.yr1,p=s._length,d=!!c,g=!!f,v=[];if(d){var m=l[1]-l[0],y=c[1]-c[0];v[0]=(l[0]*(1-r)+r*c[0]-l[0])/(l[1]-l[0])*u,v[2]=u*(1-r+r*y/m),i.range[0]=l[0]*(1-r)+r*c[0],i.range[1]=l[1]*(1-r)+r*c[1]}else v[0]=0,v[2]=u;if(g){var x=h[1]-h[0],b=f[1]-f[0];v[1]=(h[1]*(1-r)+r*f[1]-h[1])/(h[0]-h[1])*p,v[3]=p*(1-r+r*b/x),s.range[0]=h[0]*(1-r)+r*f[0],s.range[1]=h[1]*(1-r)+r*f[1]}else v[1]=0,v[3]=p;o.drawOne(t,i,{skipTitle:!0}),o.drawOne(t,s,{skipTitle:!0}),o.redrawComponents(t,[i._id,s._id]);var _=d?u/v[2]:1,w=g?p/v[3]:1,k=d?v[0]:0,A=g?v[1]:0,M=d?v[0]/v[2]*u:0,T=g?v[1]/v[3]*p:0,S=i._offset-M,E=s._offset-T;n.clipRect.call(a.setTranslate,k,A).call(a.setScale,1/_,1/w),n.plot.call(a.setTranslate,S,E).call(a.setScale,_,w),a.setPointGroupScale(n.zoomScalePts,1/_,1/w),a.setTextPointsScale(n.zoomScaleTxt,1/_,1/w)}o.redrawComponents(t)}},{"../../components/drawing":595,"../../registry":826,"./axes":745,d3:151}],768:[function(t,e,r){"use strict";var n=t("../../registry").traceIs,i=t("./axis_autotype");function a(t){return{v:"x",h:"y"}[t.orientation||"v"]}function o(t,e){var r=a(t),i=n(t,"box-violin"),o=n(t._fullInput||{},"candlestick");return i&&!o&&e===r&&void 0===t[r]&&void 0===t[r+"0"]}e.exports=function(t,e,r,s){"-"===r("type",(s.splomStash||{}).type)&&(!function(t,e){if("-"!==t.type)return;var r=t._id,s=r.charAt(0);-1!==r.indexOf("scene")&&(r=s);var l=function(t,e,r){for(var n=0;n<t.length;n++){var i=t[n];if("splom"===i.type&&i._length>0&&(i["_"+r+"axes"]||{})[e])return i;if((i[r+"axis"]||r)===e){if(o(i,r))return i;if((i[r]||[]).length||i[r+"0"])return i}}}(e,r,s);if(!l)return;if("histogram"===l.type&&s==={v:"y",h:"x"}[l.orientation||"v"])return void(t.type="linear");var c,u=s+"calendar",h=l[u],f={noMultiCategory:!n(l,"cartesian")||n(l,"noMultiCategory")};if(o(l,s)){var p=a(l),d=[];for(c=0;c<e.length;c++){var g=e[c];n(g,"box-violin")&&(g[s+"axis"]||s)===r&&(void 0!==g[p]?d.push(g[p][0]):void 0!==g.name?d.push(g.name):d.push("text"),g[u]!==h&&(h=void 0))}t.type=i(d,h,f)}else if("splom"===l.type){var v=l.dimensions,m=l._diag;for(c=0;c<v.length;c++){var y=v[c];if(y.visible&&(m[c][0]===r||m[c][1]===r)){t.type=i(y.values,h,f);break}}}else t.type=i(l[s]||[l[s+"0"]],h,f)}(e,s.data),"-"===e.type?e.type="linear":t.type=e.type)}},{"../../registry":826,"./axis_autotype":746}],769:[function(t,e,r){"use strict";var n=t("../registry"),i=t("../lib");function a(t,e,r){var n,a,o,s=!1;if("data"===e.type)n=t._fullData[null!==e.traces?e.traces[0]:0];else{if("layout"!==e.type)return!1;n=t._fullLayout}return a=i.nestedProperty(n,e.prop).get(),(o=r[e.type]=r[e.type]||{}).hasOwnProperty(e.prop)&&o[e.prop]!==a&&(s=!0),o[e.prop]=a,{changed:s,value:a}}function o(t,e){var r=[],n=e[0],a={};if("string"==typeof n)a[n]=e[1];else{if(!i.isPlainObject(n))return r;a=n}return l(a,function(t,e,n){r.push({type:"layout",prop:t,value:n})},"",0),r}function s(t,e){var r,n,a,o,s=[];if(n=e[0],a=e[1],r=e[2],o={},"string"==typeof n)o[n]=a;else{if(!i.isPlainObject(n))return s;o=n,void 0===r&&(r=a)}return void 0===r&&(r=null),l(o,function(e,n,i){var a;if(Array.isArray(i)){var o=Math.min(i.length,t.data.length);r&&(o=Math.min(o,r.length)),a=[];for(var l=0;l<o;l++)a[l]=r?r[l]:l}else a=r?r.slice(0):null;if(null===a)Array.isArray(i)&&(i=i[0]);else if(Array.isArray(a)){if(!Array.isArray(i)){var c=i;i=[];for(var u=0;u<a.length;u++)i[u]=c}i.length=Math.min(a.length,i.length)}s.push({type:"data",prop:e,traces:a,value:i})},"",0),s}function l(t,e,r,n){Object.keys(t).forEach(function(a){var o=t[a];if("_"!==a[0]){var s=r+(n>0?".":"")+a;i.isPlainObject(o)?l(o,e,s,n+1):e(s,a,o)}})}r.manageCommandObserver=function(t,e,n,o){var s={},l=!0;e&&e._commandObserver&&(s=e._commandObserver),s.cache||(s.cache={}),s.lookupTable={};var c=r.hasSimpleAPICommandBindings(t,n,s.lookupTable);if(e&&e._commandObserver){if(c)return s;if(e._commandObserver.remove)return e._commandObserver.remove(),e._commandObserver=null,s}if(c){a(t,c,s.cache),s.check=function(){if(l){var e=a(t,c,s.cache);return e.changed&&o&&void 0!==s.lookupTable[e.value]&&(s.disable(),Promise.resolve(o({value:e.value,type:c.type,prop:c.prop,traces:c.traces,index:s.lookupTable[e.value]})).then(s.enable,s.enable)),e.changed}};for(var u=["plotly_relayout","plotly_redraw","plotly_restyle","plotly_update","plotly_animatingframe","plotly_afterplot"],h=0;h<u.length;h++)t._internalOn(u[h],s.check);s.remove=function(){for(var e=0;e<u.length;e++)t._removeInternalListener(u[e],s.check)}}else i.log("Unable to automatically bind plot updates to API command"),s.lookupTable={},s.remove=function(){};return s.disable=function(){l=!1},s.enable=function(){l=!0},e&&(e._commandObserver=s),s},r.hasSimpleAPICommandBindings=function(t,e,n){var i,a,o=e.length;for(i=0;i<o;i++){var s,l=e[i],c=l.method,u=l.args;if(Array.isArray(u)||(u=[]),!c)return!1;var h=r.computeAPICommandBindings(t,c,u);if(1!==h.length)return!1;if(a){if((s=h[0]).type!==a.type)return!1;if(s.prop!==a.prop)return!1;if(Array.isArray(a.traces)){if(!Array.isArray(s.traces))return!1;s.traces.sort();for(var f=0;f<a.traces.length;f++)if(a.traces[f]!==s.traces[f])return!1}else if(s.prop!==a.prop)return!1}else a=h[0],Array.isArray(a.traces)&&a.traces.sort();var p=(s=h[0]).value;if(Array.isArray(p)){if(1!==p.length)return!1;p=p[0]}n&&(n[p]=i)}return a},r.executeAPICommand=function(t,e,r){if("skip"===e)return Promise.resolve();var a=n.apiMethodRegistry[e],o=[t];Array.isArray(r)||(r=[]);for(var s=0;s<r.length;s++)o.push(r[s]);return a.apply(null,o).catch(function(t){return i.warn("API call to Plotly."+e+" rejected.",t),Promise.reject(t)})},r.computeAPICommandBindings=function(t,e,r){var n;switch(Array.isArray(r)||(r=[]),e){case"restyle":n=s(t,r);break;case"relayout":n=o(t,r);break;case"update":n=s(t,[r[0],r[2]]).concat(o(t,[r[1]]));break;case"animate":n=function(t,e){return Array.isArray(e[0])&&1===e[0].length&&-1!==["string","number"].indexOf(typeof e[0][0])?[{type:"layout",prop:"_currentFrame",value:e[0][0].toString()}]:[]}(0,r);break;default:n=[]}return n}},{"../lib":697,"../registry":826}],770:[function(t,e,r){"use strict";var n=t("../lib/extend").extendFlat;r.attributes=function(t,e){e=e||{};var r={valType:"info_array",editType:(t=t||{}).editType,items:[{valType:"number",min:0,max:1,editType:t.editType},{valType:"number",min:0,max:1,editType:t.editType}],dflt:[0,1]},i=(t.name&&t.name,t.trace,e.description&&e.description,{x:n({},r,{}),y:n({},r,{}),editType:t.editType});return t.noGridCell||(i.row={valType:"integer",min:0,dflt:0,editType:t.editType},i.column={valType:"integer",min:0,dflt:0,editType:t.editType}),i},r.defaults=function(t,e,r,n){var i=n&&n.x||[0,1],a=n&&n.y||[0,1],o=e.grid;if(o){var s=r("domain.column");void 0!==s&&(s<o.columns?i=o._domains.x[s]:delete t.domain.column);var l=r("domain.row");void 0!==l&&(l<o.rows?a=o._domains.y[l]:delete t.domain.row)}r("domain.x",i),r("domain.y",a)}},{"../lib/extend":687}],771:[function(t,e,r){"use strict";e.exports=function(t){var e=t.editType,r=t.colorEditType;void 0===r&&(r=e);var n={family:{valType:"string",noBlank:!0,strict:!0,editType:e},size:{valType:"number",min:1,editType:e},color:{valType:"color",editType:r},editType:e};return t.arrayOk&&(n.family.arrayOk=!0,n.size.arrayOk=!0,n.color.arrayOk=!0),n}},{}],772:[function(t,e,r){"use strict";e.exports={_isLinkedToArray:"frames_entry",group:{valType:"string"},name:{valType:"string"},traces:{valType:"any"},baseframe:{valType:"string"},data:{valType:"any"},layout:{valType:"any"}}},{}],773:[function(t,e,r){"use strict";r.projNames={equirectangular:"equirectangular",mercator:"mercator",orthographic:"orthographic","natural earth":"naturalEarth",kavrayskiy7:"kavrayskiy7",miller:"miller",robinson:"robinson",eckert4:"eckert4","azimuthal equal area":"azimuthalEqualArea","azimuthal equidistant":"azimuthalEquidistant","conic equal area":"conicEqualArea","conic conformal":"conicConformal","conic equidistant":"conicEquidistant",gnomonic:"gnomonic",stereographic:"stereographic",mollweide:"mollweide",hammer:"hammer","transverse mercator":"transverseMercator","albers usa":"albersUsa","winkel tripel":"winkel3",aitoff:"aitoff",sinusoidal:"sinusoidal"},r.axesNames=["lonaxis","lataxis"],r.lonaxisSpan={orthographic:180,"azimuthal equal area":360,"azimuthal equidistant":360,"conic conformal":180,gnomonic:160,stereographic:180,"transverse mercator":180,"*":360},r.lataxisSpan={"conic conformal":150,stereographic:179.5,"*":180},r.scopeDefaults={world:{lonaxisRange:[-180,180],lataxisRange:[-90,90],projType:"equirectangular",projRotate:[0,0,0]},usa:{lonaxisRange:[-180,-50],lataxisRange:[15,80],projType:"albers usa"},europe:{lonaxisRange:[-30,60],lataxisRange:[30,85],projType:"conic conformal",projRotate:[15,0,0],projParallels:[0,60]},asia:{lonaxisRange:[22,160],lataxisRange:[-15,55],projType:"mercator",projRotate:[0,0,0]},africa:{lonaxisRange:[-30,60],lataxisRange:[-40,40],projType:"mercator",projRotate:[0,0,0]},"north america":{lonaxisRange:[-180,-45],lataxisRange:[5,85],projType:"conic conformal",projRotate:[-100,0,0],projParallels:[29.5,45.5]},"south america":{lonaxisRange:[-100,-30],lataxisRange:[-60,15],projType:"mercator",projRotate:[0,0,0]}},r.clipPad=.001,r.precision=.1,r.landColor="#F0DC82",r.waterColor="#3399FF",r.locationmodeToLayer={"ISO-3":"countries","USA-states":"subunits","country names":"countries"},r.sphereSVG={type:"Sphere"},r.fillLayers={ocean:1,land:1,lakes:1},r.lineLayers={subunits:1,countries:1,coastlines:1,rivers:1,frame:1},r.layers=["bg","ocean","land","lakes","subunits","countries","coastlines","rivers","lataxis","lonaxis","frame","backplot","frontplot"],r.layersForChoropleth=["bg","ocean","land","subunits","countries","coastlines","lataxis","lonaxis","frame","backplot","rivers","lakes","frontplot"],r.layerNameToAdjective={ocean:"ocean",land:"land",lakes:"lake",subunits:"subunit",countries:"country",coastlines:"coastline",rivers:"river",frame:"frame"}},{}],774:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../registry"),a=t("../../lib"),o=t("../../components/color"),s=t("../../components/drawing"),l=t("../../components/fx"),c=t("../plots"),u=t("../cartesian/axes"),h=t("../../components/dragelement"),f=t("../cartesian/select").prepSelect,p=t("../cartesian/select").selectOnClick,d=t("./zoom"),g=t("./constants"),v=t("../../lib/topojson_utils"),m=t("topojson-client").feature;function y(t){this.id=t.id,this.graphDiv=t.graphDiv,this.container=t.container,this.topojsonURL=t.topojsonURL,this.isStatic=t.staticPlot,this.topojsonName=null,this.topojson=null,this.projection=null,this.viewInitial=null,this.fitScale=null,this.bounds=null,this.midPt=null,this.hasChoropleth=!1,this.traceHash={},this.layers={},this.basePaths={},this.dataPaths={},this.dataPoints={},this.clipDef=null,this.clipRect=null,this.bgRect=null,this.makeFramework()}t("./projections")(n);var x=y.prototype;e.exports=function(t){return new y(t)},x.plot=function(t,e,r){var n=this,i=e[this.id],a=v.getTopojsonName(i);null===n.topojson||a!==n.topojsonName?(n.topojsonName=a,void 0===PlotlyGeoAssets.topojson[n.topojsonName]?r.push(n.fetchTopojson().then(function(r){PlotlyGeoAssets.topojson[n.topojsonName]=r,n.topojson=r,n.update(t,e)})):(n.topojson=PlotlyGeoAssets.topojson[n.topojsonName],n.update(t,e))):n.update(t,e)},x.fetchTopojson=function(){var t=v.getTopojsonPath(this.topojsonURL,this.topojsonName);return new Promise(function(e,r){n.json(t,function(n,i){if(n)return 404===n.status?r(new Error(["plotly.js could not find topojson file at",t,".","Make sure the *topojsonURL* plot config option","is set properly."].join(" "))):r(new Error(["unexpected error while fetching topojson file at",t].join(" ")));e(i)})})},x.update=function(t,e){var r=e[this.id];if(!this.updateProjection(e,r)){this.hasChoropleth=!1;for(var n=0;n<t.length;n++)if("choropleth"===t[n][0].trace.type){this.hasChoropleth=!0;break}this.viewInitial||this.saveViewInitial(r),this.updateBaseLayers(e,r),this.updateDims(e,r),this.updateFx(e,r),c.generalUpdatePerTraceModule(this.graphDiv,this,t,r);var i=this.layers.frontplot.select(".scatterlayer");this.dataPoints.point=i.selectAll(".point"),this.dataPoints.text=i.selectAll("text"),this.dataPaths.line=i.selectAll(".js-line");var a=this.layers.backplot.select(".choroplethlayer");this.dataPaths.choropleth=a.selectAll("path"),this.render()}},x.updateProjection=function(t,e){var r=t._size,o=e.domain,s=e.projection,l=s.rotation||{},c=e.center||{},u=this.projection=function(t){for(var e=t.projection.type,r=n.geo[g.projNames[e]](),i=t._isClipped?g.lonaxisSpan[e]/2:null,a=["center","rotate","parallels","clipExtent"],o=function(t){return t?r:[]},s=0;s<a.length;s++){var l=a[s];"function"!=typeof r[l]&&(r[l]=o)}r.isLonLatOverEdges=function(t){if(null===r(t))return!0;if(i){var e=r.rotate();return n.geo.distance(t,[-e[0],-e[1]])>i*Math.PI/180}return!1},r.getPath=function(){return n.geo.path().projection(r)},r.getBounds=function(t){return r.getPath().bounds(t)},r.fitExtent=function(t,e){var n=t[1][0]-t[0][0],i=t[1][1]-t[0][1],a=r.clipExtent&&r.clipExtent();r.scale(150).translate([0,0]),a&&r.clipExtent(null);var o=r.getBounds(e),s=Math.min(n/(o[1][0]-o[0][0]),i/(o[1][1]-o[0][1])),l=+t[0][0]+(n-s*(o[1][0]+o[0][0]))/2,c=+t[0][1]+(i-s*(o[1][1]+o[0][1]))/2;return a&&r.clipExtent(a),r.scale(150*s).translate([l,c])},r.precision(g.precision),i&&r.clipAngle(i-g.clipPad);return r}(e);u.center([c.lon-l.lon,c.lat-l.lat]).rotate([-l.lon,-l.lat,l.roll]).parallels(s.parallels);var h=[[r.l+r.w*o.x[0],r.t+r.h*(1-o.y[1])],[r.l+r.w*o.x[1],r.t+r.h*(1-o.y[0])]],f=e.lonaxis,p=e.lataxis,d=function(t,e){var r=g.clipPad,n=t[0]+r,i=t[1]-r,a=e[0]+r,o=e[1]-r;n>0&&i<0&&(i+=360);var s=(i-n)/4;return{type:"Polygon",coordinates:[[[n,a],[n,o],[n+s,o],[n+2*s,o],[n+3*s,o],[i,o],[i,a],[i-s,a],[i-2*s,a],[i-3*s,a],[n,a]]]}}(f.range,p.range);u.fitExtent(h,d);var v=this.bounds=u.getBounds(d),m=this.fitScale=u.scale(),y=u.translate();if(!isFinite(v[0][0])||!isFinite(v[0][1])||!isFinite(v[1][0])||!isFinite(v[1][1])||isNaN(y[0])||isNaN(y[0])){for(var x=this.graphDiv,b=["projection.rotation","center","lonaxis.range","lataxis.range"],_="Invalid geo settings, relayout'ing to default view.",w={},k=0;k<b.length;k++)w[this.id+"."+b[k]]=null;return this.viewInitial=null,a.warn(_),x._promises.push(i.call("relayout",x,w)),_}var A=this.midPt=[(v[0][0]+v[1][0])/2,(v[0][1]+v[1][1])/2];if(u.scale(s.scale*m).translate([y[0]+(A[0]-y[0]),y[1]+(A[1]-y[1])]).clipExtent(v),e._isAlbersUsa){var M=u([c.lon,c.lat]),T=u.translate();u.translate([T[0]-(M[0]-T[0]),T[1]-(M[1]-T[1])])}},x.updateBaseLayers=function(t,e){var r=this,i=r.topojson,a=r.layers,l=r.basePaths;function c(t){return"lonaxis"===t||"lataxis"===t}function u(t){return Boolean(g.lineLayers[t])}function h(t){return Boolean(g.fillLayers[t])}var f=(this.hasChoropleth?g.layersForChoropleth:g.layers).filter(function(t){return u(t)||h(t)?e["show"+t]:!c(t)||e[t].showgrid}),p=r.framework.selectAll(".layer").data(f,String);p.exit().each(function(t){delete a[t],delete l[t],n.select(this).remove()}),p.enter().append("g").attr("class",function(t){return"layer "+t}).each(function(t){var e=a[t]=n.select(this);"bg"===t?r.bgRect=e.append("rect").style("pointer-events","all"):c(t)?l[t]=e.append("path").style("fill","none"):"backplot"===t?e.append("g").classed("choroplethlayer",!0):"frontplot"===t?e.append("g").classed("scatterlayer",!0):u(t)?l[t]=e.append("path").style("fill","none").style("stroke-miterlimit",2):h(t)&&(l[t]=e.append("path").style("stroke","none"))}),p.order(),p.each(function(t){var r=l[t],a=g.layerNameToAdjective[t];"frame"===t?r.datum(g.sphereSVG):u(t)||h(t)?r.datum(m(i,i.objects[t])):c(t)&&r.datum(function(t,e){var r=e[t].dtick,i=g.scopeDefaults[e.scope],a=i.lonaxisRange,o=i.lataxisRange,s="lonaxis"===t?[r]:[0,r];return n.geo.graticule().extent([[a[0],o[0]],[a[1],o[1]]]).step(s)}(t,e)).call(o.stroke,e[t].gridcolor).call(s.dashLine,"",e[t].gridwidth),u(t)?r.call(o.stroke,e[a+"color"]).call(s.dashLine,"",e[a+"width"]):h(t)&&r.call(o.fill,e[a+"color"])})},x.updateDims=function(t,e){var r=this.bounds,n=(e.framewidth||0)/2,i=r[0][0]-n,a=r[0][1]-n,l=r[1][0]-i+n,c=r[1][1]-a+n;s.setRect(this.clipRect,i,a,l,c),this.bgRect.call(s.setRect,i,a,l,c).call(o.fill,e.bgcolor),this.xaxis._offset=i,this.xaxis._length=l,this.yaxis._offset=a,this.yaxis._length=c},x.updateFx=function(t,e){var r=this,a=r.graphDiv,o=r.bgRect,s=t.dragmode,c=t.clickmode;if(!r.isStatic){var u;"select"===s?u=function(t,e){(t.range={})[r.id]=[v([e.xmin,e.ymin]),v([e.xmax,e.ymax])]}:"lasso"===s&&(u=function(t,e,n){(t.lassoPoints={})[r.id]=n.filtered.map(v)});var g={element:r.bgRect.node(),gd:a,plotinfo:{id:r.id,xaxis:r.xaxis,yaxis:r.yaxis,fillRangeItems:u},xaxes:[r.xaxis],yaxes:[r.yaxis],subplot:r.id,clickFn:function(e){2===e&&t._zoomlayer.selectAll(".select-outline").remove()}};"pan"===s?(o.node().onmousedown=null,o.call(d(r,e)),o.on("dblclick.zoom",function(){var t=r.viewInitial,e={};for(var n in t)e[r.id+"."+n]=t[n];i.call("_guiRelayout",a,e),a.emit("plotly_doubleclick",null)}),a._context._scrollZoom.geo||o.on("wheel.zoom",null)):"select"!==s&&"lasso"!==s||(o.on(".zoom",null),g.prepFn=function(t,e,r){f(t,e,r,g,s)},h.init(g)),o.on("mousemove",function(){var t=r.projection.invert(n.mouse(this));if(!t||isNaN(t[0])||isNaN(t[1]))return h.unhover(a,n.event);r.xaxis.p2c=function(){return t[0]},r.yaxis.p2c=function(){return t[1]},l.hover(a,n.event,r.id)}),o.on("mouseout",function(){a._dragging||h.unhover(a,n.event)}),o.on("click",function(){"select"!==s&&"lasso"!==s&&(c.indexOf("select")>-1&&p(n.event,a,[r.xaxis],[r.yaxis],r.id,g),c.indexOf("event")>-1&&l.click(a,n.event))})}function v(t){return r.projection.invert([t[0]+r.xaxis._offset,t[1]+r.yaxis._offset])}},x.makeFramework=function(){var t=this,e=t.graphDiv,r=e._fullLayout,i="clip"+r._uid+t.id;t.clipDef=r._clips.append("clipPath").attr("id",i),t.clipRect=t.clipDef.append("rect"),t.framework=n.select(t.container).append("g").attr("class","geo "+t.id).call(s.setClipUrl,i,e),t.project=function(e){var r=t.projection(e);return r?[r[0]-t.xaxis._offset,r[1]-t.yaxis._offset]:[null,null]},t.xaxis={_id:"x",c2p:function(e){return t.project(e)[0]}},t.yaxis={_id:"y",c2p:function(e){return t.project(e)[1]}},t.mockAxis={type:"linear",showexponent:"all",exponentformat:"B"},u.setConvert(t.mockAxis,r)},x.saveViewInitial=function(t){var e=t.center||{},r=t.projection,n=r.rotation||{};t._isScoped?this.viewInitial={"center.lon":e.lon,"center.lat":e.lat,"projection.scale":r.scale}:t._isClipped?this.viewInitial={"projection.scale":r.scale,"projection.rotation.lon":n.lon,"projection.rotation.lat":n.lat}:this.viewInitial={"center.lon":e.lon,"center.lat":e.lat,"projection.scale":r.scale,"projection.rotation.lon":n.lon}},x.render=function(){var t,e=this.projection,r=e.getPath();function n(t){var r=e(t.lonlat);return r?"translate("+r[0]+","+r[1]+")":null}function i(t){return e.isLonLatOverEdges(t.lonlat)?"none":null}for(t in this.basePaths)this.basePaths[t].attr("d",r);for(t in this.dataPaths)this.dataPaths[t].attr("d",function(t){return r(t.geojson)});for(t in this.dataPoints)this.dataPoints[t].attr("display",i).attr("transform",n)}},{"../../components/color":574,"../../components/dragelement":592,"../../components/drawing":595,"../../components/fx":613,"../../lib":697,"../../lib/topojson_utils":724,"../../registry":826,"../cartesian/axes":745,"../cartesian/select":762,"../plots":807,"./constants":773,"./projections":779,"./zoom":780,d3:151,"topojson-client":521}],775:[function(t,e,r){"use strict";var n=t("./geo"),i=t("../../plots/get_data").getSubplotCalcData,a=t("../../lib").counterRegex,o="geo";r.name=o,r.attr=o,r.idRoot=o,r.idRegex=r.attrRegex=a(o),r.attributes=t("./layout/attributes"),r.layoutAttributes=t("./layout/layout_attributes"),r.supplyLayoutDefaults=t("./layout/defaults"),r.plot=function(t){var e=t._fullLayout,r=t.calcdata,a=e._subplots.geo;void 0===window.PlotlyGeoAssets&&(window.PlotlyGeoAssets={topojson:{}});for(var s=0;s<a.length;s++){var l=a[s],c=i(r,o,l),u=e[l]._subplot;u||(u=n({id:l,graphDiv:t,container:e._geolayer.node(),topojsonURL:t._context.topojsonURL,staticPlot:t._context.staticPlot}),e[l]._subplot=u),u.plot(c,e,t._promises)}},r.clean=function(t,e,r,n){for(var i=n._subplots.geo||[],a=0;a<i.length;a++){var o=i[a],s=n[o]._subplot;!e[o]&&s&&(s.framework.remove(),s.clipDef.remove())}},r.updateFx=function(t){for(var e=t._fullLayout,r=e._subplots.geo,n=0;n<r.length;n++){var i=e[r[n]];i._subplot.updateFx(e,i)}}},{"../../lib":697,"../../plots/get_data":781,"./geo":774,"./layout/attributes":776,"./layout/defaults":777,"./layout/layout_attributes":778}],776:[function(t,e,r){"use strict";e.exports={geo:{valType:"subplotid",dflt:"geo",editType:"calc"}}},{}],777:[function(t,e,r){"use strict";var n=t("../../subplot_defaults"),i=t("../constants"),a=t("./layout_attributes"),o=i.axesNames;function s(t,e,r){var n=r("resolution"),a=r("scope"),s=i.scopeDefaults[a],l=r("projection.type",s.projType),c=e._isAlbersUsa="albers usa"===l;c&&(a=e.scope="usa");var u=e._isScoped="world"!==a,h=e._isConic=-1!==l.indexOf("conic");e._isClipped=!!i.lonaxisSpan[l];for(var f=0;f<o.length;f++){var p,d=o[f],g=[30,10][f];if(u)p=s[d+"Range"];else{var v=i[d+"Span"],m=(v[l]||v["*"])/2,y=r("projection.rotation."+d.substr(0,3),s.projRotate[f]);p=[y-m,y+m]}var x=r(d+".range",p);r(d+".tick0",x[0]),r(d+".dtick",g),r(d+".showgrid")&&(r(d+".gridcolor"),r(d+".gridwidth"))}var b=e.lonaxis.range,_=e.lataxis.range,w=b[0],k=b[1];w>0&&k<0&&(k+=360);var A,M,T,S=(w+k)/2;if(!c){var E=u?s.projRotate:[S,0,0];A=r("projection.rotation.lon",E[0]),r("projection.rotation.lat",E[1]),r("projection.rotation.roll",E[2]),r("showcoastlines",!u)&&(r("coastlinecolor"),r("coastlinewidth")),r("showocean")&&r("oceancolor")}(c?(M=-96.6,T=38.7):(M=u?S:A,T=(_[0]+_[1])/2),r("center.lon",M),r("center.lat",T),h)&&r("projection.parallels",s.projParallels||[0,60]);r("projection.scale"),r("showland")&&r("landcolor"),r("showlakes")&&r("lakecolor"),r("showrivers")&&(r("rivercolor"),r("riverwidth")),r("showcountries",u&&"usa"!==a)&&(r("countrycolor"),r("countrywidth")),("usa"===a||"north america"===a&&50===n)&&(r("showsubunits",!0),r("subunitcolor"),r("subunitwidth")),u||r("showframe",!0)&&(r("framecolor"),r("framewidth")),r("bgcolor")}e.exports=function(t,e,r){n(t,e,r,{type:"geo",attributes:a,handleDefaults:s,partition:"y"})}},{"../../subplot_defaults":821,"../constants":773,"./layout_attributes":778}],778:[function(t,e,r){"use strict";var n=t("../../../components/color/attributes"),i=t("../../domain").attributes,a=t("../constants"),o=t("../../../plot_api/edit_types").overrideAll,s={range:{valType:"info_array",items:[{valType:"number"},{valType:"number"}]},showgrid:{valType:"boolean",dflt:!1},tick0:{valType:"number"},dtick:{valType:"number"},gridcolor:{valType:"color",dflt:n.lightLine},gridwidth:{valType:"number",min:0,dflt:1}};(e.exports=o({domain:i({name:"geo"},{}),resolution:{valType:"enumerated",values:[110,50],dflt:110,coerceNumber:!0},scope:{valType:"enumerated",values:Object.keys(a.scopeDefaults),dflt:"world"},projection:{type:{valType:"enumerated",values:Object.keys(a.projNames)},rotation:{lon:{valType:"number"},lat:{valType:"number"},roll:{valType:"number"}},parallels:{valType:"info_array",items:[{valType:"number"},{valType:"number"}]},scale:{valType:"number",min:0,dflt:1}},center:{lon:{valType:"number"},lat:{valType:"number"}},showcoastlines:{valType:"boolean"},coastlinecolor:{valType:"color",dflt:n.defaultLine},coastlinewidth:{valType:"number",min:0,dflt:1},showland:{valType:"boolean",dflt:!1},landcolor:{valType:"color",dflt:a.landColor},showocean:{valType:"boolean",dflt:!1},oceancolor:{valType:"color",dflt:a.waterColor},showlakes:{valType:"boolean",dflt:!1},lakecolor:{valType:"color",dflt:a.waterColor},showrivers:{valType:"boolean",dflt:!1},rivercolor:{valType:"color",dflt:a.waterColor},riverwidth:{valType:"number",min:0,dflt:1},showcountries:{valType:"boolean"},countrycolor:{valType:"color",dflt:n.defaultLine},countrywidth:{valType:"number",min:0,dflt:1},showsubunits:{valType:"boolean"},subunitcolor:{valType:"color",dflt:n.defaultLine},subunitwidth:{valType:"number",min:0,dflt:1},showframe:{valType:"boolean"},framecolor:{valType:"color",dflt:n.defaultLine},framewidth:{valType:"number",min:0,dflt:1},bgcolor:{valType:"color",dflt:n.background},lonaxis:s,lataxis:s},"plot","from-root")).uirevision={valType:"any",editType:"none"}},{"../../../components/color/attributes":573,"../../../plot_api/edit_types":728,"../../domain":770,"../constants":773}],779:[function(t,e,r){"use strict";e.exports=function(t){function e(t,e){return{type:"Feature",id:t.id,properties:t.properties,geometry:r(t.geometry,e)}}function r(e,n){if(!e)return null;if("GeometryCollection"===e.type)return{type:"GeometryCollection",geometries:object.geometries.map(function(t){return r(t,n)})};if(!c.hasOwnProperty(e.type))return null;var i=c[e.type];return t.geo.stream(e,n(i)),i.result()}t.geo.project=function(t,e){var i=e.stream;if(!i)throw new Error("not yet supported");return(t&&n.hasOwnProperty(t.type)?n[t.type]:r)(t,i)};var n={Feature:e,FeatureCollection:function(t,r){return{type:"FeatureCollection",features:t.features.map(function(t){return e(t,r)})}}},i=[],a=[],o={point:function(t,e){i.push([t,e])},result:function(){var t=i.length?i.length<2?{type:"Point",coordinates:i[0]}:{type:"MultiPoint",coordinates:i}:null;return i=[],t}},s={lineStart:u,point:function(t,e){i.push([t,e])},lineEnd:function(){i.length&&(a.push(i),i=[])},result:function(){var t=a.length?a.length<2?{type:"LineString",coordinates:a[0]}:{type:"MultiLineString",coordinates:a}:null;return a=[],t}},l={polygonStart:u,lineStart:u,point:function(t,e){i.push([t,e])},lineEnd:function(){var t=i.length;if(t){do{i.push(i[0].slice())}while(++t<4);a.push(i),i=[]}},polygonEnd:u,result:function(){if(!a.length)return null;var t=[],e=[];return a.forEach(function(r){!function(t){if((e=t.length)<4)return!1;for(var e,r=0,n=t[e-1][1]*t[0][0]-t[e-1][0]*t[0][1];++r<e;)n+=t[r-1][1]*t[r][0]-t[r-1][0]*t[r][1];return n<=0}(r)?e.push(r):t.push([r])}),e.forEach(function(e){var r=e[0];t.some(function(t){if(function(t,e){for(var r=e[0],n=e[1],i=!1,a=0,o=t.length,s=o-1;a<o;s=a++){var l=t[a],c=l[0],u=l[1],h=t[s],f=h[0],p=h[1];u>n^p>n&&r<(f-c)*(n-u)/(p-u)+c&&(i=!i)}return i}(t[0],r))return t.push(e),!0})||t.push([e])}),a=[],t.length?t.length>1?{type:"MultiPolygon",coordinates:t}:{type:"Polygon",coordinates:t[0]}:null}},c={Point:o,MultiPoint:o,LineString:s,MultiLineString:s,Polygon:l,MultiPolygon:l,Sphere:l};function u(){}var h=1e-6,f=h*h,p=Math.PI,d=p/2,g=(Math.sqrt(p),p/180),v=180/p;function m(t){return t>1?d:t<-1?-d:Math.asin(t)}function y(t){return t>1?0:t<-1?p:Math.acos(t)}var x=t.geo.projection,b=t.geo.projectionMutator;function _(t,e){var r=(2+d)*Math.sin(e);e/=2;for(var n=0,i=1/0;n<10&&Math.abs(i)>h;n++){var a=Math.cos(e);e-=i=(e+Math.sin(e)*(a+2)-r)/(2*a*(1+a))}return[2/Math.sqrt(p*(4+p))*t*(1+Math.cos(e)),2*Math.sqrt(p/(4+p))*Math.sin(e)]}t.geo.interrupt=function(e){var r,n=[[[[-p,0],[0,d],[p,0]]],[[[-p,0],[0,-d],[p,0]]]];function i(t,r){for(var i=r<0?-1:1,a=n[+(r<0)],o=0,s=a.length-1;o<s&&t>a[o][2][0];++o);var l=e(t-a[o][1][0],r);return l[0]+=e(a[o][1][0],i*r>i*a[o][0][1]?a[o][0][1]:r)[0],l}e.invert&&(i.invert=function(t,a){for(var o=r[+(a<0)],s=n[+(a<0)],c=0,u=o.length;c<u;++c){var h=o[c];if(h[0][0]<=t&&t<h[1][0]&&h[0][1]<=a&&a<h[1][1]){var f=e.invert(t-e(s[c][1][0],0)[0],a);return f[0]+=s[c][1][0],l(i(f[0],f[1]),[t,a])?f:null}}});var a=t.geo.projection(i),o=a.stream;function s(t,e){for(var r,n,i,a=-1,o=t.length,s=t[0],l=[];++a<o;){n=((r=t[a])[0]-s[0])/e,i=(r[1]-s[1])/e;for(var c=0;c<e;++c)l.push([s[0]+c*n,s[1]+c*i]);s=r}return l.push(r),l}function l(t,e){return Math.abs(t[0]-e[0])<h&&Math.abs(t[1]-e[1])<h}return a.stream=function(e){var r=a.rotate(),i=o(e),l=(a.rotate([0,0]),o(e));return a.rotate(r),i.sphere=function(){t.geo.stream(function(){for(var e=1e-6,r=[],i=0,a=n[0].length;i<a;++i){var o=n[0][i],l=180*o[0][0]/p,c=180*o[0][1]/p,u=180*o[1][1]/p,h=180*o[2][0]/p,f=180*o[2][1]/p;r.push(s([[l+e,c+e],[l+e,u-e],[h-e,u-e],[h-e,f+e]],30))}for(var i=n[1].length-1;i>=0;--i){var o=n[1][i],l=180*o[0][0]/p,c=180*o[0][1]/p,u=180*o[1][1]/p,h=180*o[2][0]/p,f=180*o[2][1]/p;r.push(s([[h-e,f-e],[h-e,u+e],[l+e,u+e],[l+e,c-e]],30))}return{type:"Polygon",coordinates:[t.merge(r)]}}(),l)},i},a.lobes=function(t){return arguments.length?(n=t.map(function(t){return t.map(function(t){return[[t[0][0]*p/180,t[0][1]*p/180],[t[1][0]*p/180,t[1][1]*p/180],[t[2][0]*p/180,t[2][1]*p/180]]})}),r=n.map(function(t){return t.map(function(t){var r,n=e(t[0][0],t[0][1])[0],i=e(t[2][0],t[2][1])[0],a=e(t[1][0],t[0][1])[1],o=e(t[1][0],t[1][1])[1];return a>o&&(r=a,a=o,o=r),[[n,a],[i,o]]})}),a):n.map(function(t){return t.map(function(t){return[[180*t[0][0]/p,180*t[0][1]/p],[180*t[1][0]/p,180*t[1][1]/p],[180*t[2][0]/p,180*t[2][1]/p]]})})},a},_.invert=function(t,e){var r=.5*e*Math.sqrt((4+p)/p),n=m(r),i=Math.cos(n);return[t/(2/Math.sqrt(p*(4+p))*(1+i)),m((n+r*(i+2))/(2+d))]},(t.geo.eckert4=function(){return x(_)}).raw=_;var w=t.geo.azimuthalEqualArea.raw;function k(t,e){if(arguments.length<2&&(e=t),1===e)return w;if(e===1/0)return A;function r(r,n){var i=w(r/e,n);return i[0]*=t,i}return r.invert=function(r,n){var i=w.invert(r/t,n);return i[0]*=e,i},r}function A(t,e){return[t*Math.cos(e)/Math.cos(e/=2),2*Math.sin(e)]}function M(t,e){return[3*t/(2*p)*Math.sqrt(p*p/3-e*e),e]}function T(t,e){return[t,1.25*Math.log(Math.tan(p/4+.4*e))]}function S(t){return function(e){var r,n=t*Math.sin(e),i=30;do{e-=r=(e+Math.sin(e)-n)/(1+Math.cos(e))}while(Math.abs(r)>h&&--i>0);return e/2}}A.invert=function(t,e){var r=2*m(e/2);return[t*Math.cos(r/2)/Math.cos(r),r]},(t.geo.hammer=function(){var t=2,e=b(k),r=e(t);return r.coefficient=function(r){return arguments.length?e(t=+r):t},r}).raw=k,M.invert=function(t,e){return[2/3*p*t/Math.sqrt(p*p/3-e*e),e]},(t.geo.kavrayskiy7=function(){return x(M)}).raw=M,T.invert=function(t,e){return[t,2.5*Math.atan(Math.exp(.8*e))-.625*p]},(t.geo.miller=function(){return x(T)}).raw=T,S(p);var E=function(t,e,r){var n=S(r);function i(r,i){return[t*r*Math.cos(i=n(i)),e*Math.sin(i)]}return i.invert=function(n,i){var a=m(i/e);return[n/(t*Math.cos(a)),m((2*a+Math.sin(2*a))/r)]},i}(Math.SQRT2/d,Math.SQRT2,p);function C(t,e){var r=e*e,n=r*r;return[t*(.8707-.131979*r+n*(n*(.003971*r-.001529*n)-.013791)),e*(1.007226+r*(.015085+n*(.028874*r-.044475-.005916*n)))]}(t.geo.mollweide=function(){return x(E)}).raw=E,C.invert=function(t,e){var r,n=e,i=25;do{var a=n*n,o=a*a;n-=r=(n*(1.007226+a*(.015085+o*(.028874*a-.044475-.005916*o)))-e)/(1.007226+a*(.045255+o*(.259866*a-.311325-.005916*11*o)))}while(Math.abs(r)>h&&--i>0);return[t/(.8707+(a=n*n)*(a*(a*a*a*(.003971-.001529*a)-.013791)-.131979)),n]},(t.geo.naturalEarth=function(){return x(C)}).raw=C;var L=[[.9986,-.062],[1,0],[.9986,.062],[.9954,.124],[.99,.186],[.9822,.248],[.973,.31],[.96,.372],[.9427,.434],[.9216,.4958],[.8962,.5571],[.8679,.6176],[.835,.6769],[.7986,.7346],[.7597,.7903],[.7186,.8435],[.6732,.8936],[.6213,.9394],[.5722,.9761],[.5322,1]];function z(t,e){var r,n=Math.min(18,36*Math.abs(e)/p),i=Math.floor(n),a=n-i,o=(r=L[i])[0],s=r[1],l=(r=L[++i])[0],c=r[1],u=(r=L[Math.min(19,++i)])[0],h=r[1];return[t*(l+a*(u-o)/2+a*a*(u-2*l+o)/2),(e>0?d:-d)*(c+a*(h-s)/2+a*a*(h-2*c+s)/2)]}function O(t,e){return[t*Math.cos(e),e]}function I(t,e){var r,n=Math.cos(e),i=(r=y(n*Math.cos(t/=2)))?r/Math.sin(r):1;return[2*n*Math.sin(t)*i,Math.sin(e)*i]}function D(t,e){var r=I(t,e);return[(r[0]+t/d)/2,(r[1]+e)/2]}L.forEach(function(t){t[1]*=1.0144}),z.invert=function(t,e){var r=e/d,n=90*r,i=Math.min(18,Math.abs(n/5)),a=Math.max(0,Math.floor(i));do{var o=L[a][1],s=L[a+1][1],l=L[Math.min(19,a+2)][1],c=l-o,u=l-2*s+o,h=2*(Math.abs(r)-s)/c,p=u/c,m=h*(1-p*h*(1-2*p*h));if(m>=0||1===a){n=(e>=0?5:-5)*(m+i);var y,x=50;do{m=(i=Math.min(18,Math.abs(n)/5))-(a=Math.floor(i)),o=L[a][1],s=L[a+1][1],l=L[Math.min(19,a+2)][1],n-=(y=(e>=0?d:-d)*(s+m*(l-o)/2+m*m*(l-2*s+o)/2)-e)*v}while(Math.abs(y)>f&&--x>0);break}}while(--a>=0);var b=L[a][0],_=L[a+1][0],w=L[Math.min(19,a+2)][0];return[t/(_+m*(w-b)/2+m*m*(w-2*_+b)/2),n*g]},(t.geo.robinson=function(){return x(z)}).raw=z,O.invert=function(t,e){return[t/Math.cos(e),e]},(t.geo.sinusoidal=function(){return x(O)}).raw=O,I.invert=function(t,e){if(!(t*t+4*e*e>p*p+h)){var r=t,n=e,i=25;do{var a,o=Math.sin(r),s=Math.sin(r/2),l=Math.cos(r/2),c=Math.sin(n),u=Math.cos(n),f=Math.sin(2*n),d=c*c,g=u*u,v=s*s,m=1-g*l*l,x=m?y(u*l)*Math.sqrt(a=1/m):a=0,b=2*x*u*s-t,_=x*c-e,w=a*(g*v+x*u*l*d),k=a*(.5*o*f-2*x*c*s),A=.25*a*(f*s-x*c*g*o),M=a*(d*l+x*v*u),T=k*A-M*w;if(!T)break;var S=(_*k-b*M)/T,E=(b*A-_*w)/T;r-=S,n-=E}while((Math.abs(S)>h||Math.abs(E)>h)&&--i>0);return[r,n]}},(t.geo.aitoff=function(){return x(I)}).raw=I,D.invert=function(t,e){var r=t,n=e,i=25;do{var a,o=Math.cos(n),s=Math.sin(n),l=Math.sin(2*n),c=s*s,u=o*o,f=Math.sin(r),p=Math.cos(r/2),g=Math.sin(r/2),v=g*g,m=1-u*p*p,x=m?y(o*p)*Math.sqrt(a=1/m):a=0,b=.5*(2*x*o*g+r/d)-t,_=.5*(x*s+n)-e,w=.5*a*(u*v+x*o*p*c)+.5/d,k=a*(f*l/4-x*s*g),A=.125*a*(l*g-x*s*u*f),M=.5*a*(c*p+x*v*o)+.5,T=k*A-M*w,S=(_*k-b*M)/T,E=(b*A-_*w)/T;r-=S,n-=E}while((Math.abs(S)>h||Math.abs(E)>h)&&--i>0);return[r,n]},(t.geo.winkel3=function(){return x(D)}).raw=D}},{}],780:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../lib"),a=t("../../registry"),o=Math.PI/180,s=180/Math.PI,l={cursor:"pointer"},c={cursor:"auto"};function u(t,e){return n.behavior.zoom().translate(e.translate()).scale(e.scale())}function h(t,e,r){var n=t.id,o=t.graphDiv,s=o.layout,l=s[n],c=o._fullLayout,u=c[n],h={},f={};function p(t,e){h[n+"."+t]=i.nestedProperty(l,t).get(),a.call("_storeDirectGUIEdit",s,c._preGUI,h);var r=i.nestedProperty(u,t);r.get()!==e&&(r.set(e),i.nestedProperty(l,t).set(e),f[n+"."+t]=e)}r(p),p("projection.scale",e.scale()/t.fitScale),o.emit("plotly_relayout",f)}function f(t,e){var r=u(0,e);function i(r){var n=e.invert(t.midPt);r("center.lon",n[0]),r("center.lat",n[1])}return r.on("zoomstart",function(){n.select(this).style(l)}).on("zoom",function(){e.scale(n.event.scale).translate(n.event.translate),t.render()}).on("zoomend",function(){n.select(this).style(c),h(t,e,i)}),r}function p(t,e){var r,i,a,o,s,f,p,d,g,v=u(0,e),m=2;function y(t){return e.invert(t)}function x(r){var n=e.rotate(),i=e.invert(t.midPt);r("projection.rotation.lon",-n[0]),r("center.lon",i[0]),r("center.lat",i[1])}return v.on("zoomstart",function(){n.select(this).style(l),r=n.mouse(this),i=e.rotate(),a=e.translate(),o=i,s=y(r)}).on("zoom",function(){if(f=n.mouse(this),function(t){var r=y(t);if(!r)return!0;var n=e(r);return Math.abs(n[0]-t[0])>m||Math.abs(n[1]-t[1])>m}(r))return v.scale(e.scale()),void v.translate(e.translate());e.scale(n.event.scale),e.translate([a[0],n.event.translate[1]]),s?y(f)&&(d=y(f),p=[o[0]+(d[0]-s[0]),i[1],i[2]],e.rotate(p),o=p):s=y(r=f),g=!0,t.render()}).on("zoomend",function(){n.select(this).style(c),g&&h(t,e,x)}),v}function d(t,e){var r,i={r:e.rotate(),k:e.scale()},a=u(0,e),f=function(t){var e=0,r=arguments.length,i=[];for(;++e<r;)i.push(arguments[e]);var a=n.dispatch.apply(null,i);return a.of=function(e,r){return function(i){var o;try{o=i.sourceEvent=n.event,i.target=t,n.event=i,a[i.type].apply(e,r)}finally{n.event=o}}},a}(a,"zoomstart","zoom","zoomend"),p=0,d=a.on;function m(t){var r=e.rotate();t("projection.rotation.lon",-r[0]),t("projection.rotation.lat",-r[1])}return a.on("zoomstart",function(){n.select(this).style(l);var t,c,u,h,m,b,_,w,k,A,M,T=n.mouse(this),S=e.rotate(),E=S,C=e.translate(),L=(c=.5*(t=S)[0]*o,u=.5*t[1]*o,h=.5*t[2]*o,m=Math.sin(c),b=Math.cos(c),_=Math.sin(u),w=Math.cos(u),k=Math.sin(h),A=Math.cos(h),[b*w*A+m*_*k,m*w*A-b*_*k,b*_*A+m*w*k,b*w*k-m*_*A]);r=g(e,T),d.call(a,"zoom",function(){var t,a,o,l,c,u,h,p,d,m,b=n.mouse(this);if(e.scale(i.k=n.event.scale),r){if(g(e,b)){e.rotate(S).translate(C);var _=g(e,b),w=function(t,e){if(!t||!e)return;var r=function(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}(t,e),n=Math.sqrt(x(r,r)),i=.5*Math.acos(Math.max(-1,Math.min(1,x(t,e)))),a=Math.sin(i)/n;return n&&[Math.cos(i),r[2]*a,-r[1]*a,r[0]*a]}(r,_),k=function(t){return[Math.atan2(2*(t[0]*t[1]+t[2]*t[3]),1-2*(t[1]*t[1]+t[2]*t[2]))*s,Math.asin(Math.max(-1,Math.min(1,2*(t[0]*t[2]-t[3]*t[1]))))*s,Math.atan2(2*(t[0]*t[3]+t[1]*t[2]),1-2*(t[2]*t[2]+t[3]*t[3]))*s]}((a=w,o=(t=L)[0],l=t[1],c=t[2],u=t[3],h=a[0],p=a[1],d=a[2],m=a[3],[o*h-l*p-c*d-u*m,o*p+l*h+c*m-u*d,o*d-l*m+c*h+u*p,o*m+l*d-c*p+u*h])),A=i.r=function(t,e,r){var n=y(e,2,t[0]);n=y(n,1,t[1]),n=y(n,0,t[2]-r[2]);var i,a,o=e[0],l=e[1],c=e[2],u=n[0],h=n[1],f=n[2],p=Math.atan2(l,o)*s,d=Math.sqrt(o*o+l*l);Math.abs(h)>d?(a=(h>0?90:-90)-p,i=0):(a=Math.asin(h/d)*s-p,i=Math.sqrt(d*d-h*h));var g=180-a-2*p,m=(Math.atan2(f,u)-Math.atan2(c,i))*s,x=(Math.atan2(f,u)-Math.atan2(c,-i))*s,b=v(r[0],r[1],a,m),_=v(r[0],r[1],g,x);return b<=_?[a,m,r[2]]:[g,x,r[2]]}(k,r,E);isFinite(A[0])&&isFinite(A[1])&&isFinite(A[2])||(A=E),e.rotate(A),E=A}}else r=g(e,T=b);f.of(this,arguments)({type:"zoom"})}),M=f.of(this,arguments),p++||M({type:"zoomstart"})}).on("zoomend",function(){var r;n.select(this).style(c),d.call(a,"zoom",null),r=f.of(this,arguments),--p||r({type:"zoomend"}),h(t,e,m)}).on("zoom.redraw",function(){t.render()}),n.rebind(a,f,"on")}function g(t,e){var r=t.invert(e);return r&&isFinite(r[0])&&isFinite(r[1])&&function(t){var e=t[0]*o,r=t[1]*o,n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}(r)}function v(t,e,r,n){var i=m(r-t),a=m(n-e);return Math.sqrt(i*i+a*a)}function m(t){return(t%360+540)%360-180}function y(t,e,r){var n=r*o,i=t.slice(),a=0===e?1:0,s=2===e?1:2,l=Math.cos(n),c=Math.sin(n);return i[a]=t[a]*l-t[s]*c,i[s]=t[s]*l+t[a]*c,i}function x(t,e){for(var r=0,n=0,i=t.length;n<i;++n)r+=t[n]*e[n];return r}e.exports=function(t,e){var r=t.projection;return(e._isScoped?f:e._isClipped?d:p)(t,r)}},{"../../lib":697,"../../registry":826,d3:151}],781:[function(t,e,r){"use strict";var n=t("../registry"),i=t("./cartesian/constants").SUBPLOT_PATTERN;r.getSubplotCalcData=function(t,e,r){var i=n.subplotsRegistry[e];if(!i)return[];for(var a=i.attr,o=[],s=0;s<t.length;s++){var l=t[s];l[0].trace[a]===r&&o.push(l)}return o},r.getModuleCalcData=function(t,e){var r,i=[],a=[];if(!(r="string"==typeof e?n.getModule(e).plot:"function"==typeof e?e:e.plot))return[i,t];for(var o=0;o<t.length;o++){var s=t[o],l=s[0].trace;!0===l.visible&&(l._module.plot===r?i.push(s):a.push(s))}return[i,a]},r.getSubplotData=function(t,e,r){if(!n.subplotsRegistry[e])return[];var a,o,s,l=n.subplotsRegistry[e].attr,c=[];if("gl2d"===e){var u=r.match(i);o="x"+u[1],s="y"+u[2]}for(var h=0;h<t.length;h++)a=t[h],"gl2d"===e&&n.traceIs(a,"gl2d")?a[l[0]]===o&&a[l[1]]===s&&c.push(a):a[l]===r&&c.push(a);return c}},{"../registry":826,"./cartesian/constants":751}],782:[function(t,e,r){"use strict";var n=t("mouse-change"),i=t("mouse-wheel"),a=t("mouse-event-offset"),o=t("../cartesian/constants"),s=t("has-passive-events");function l(t,e){this.element=t,this.plot=e,this.mouseListener=null,this.wheelListener=null,this.lastInputTime=Date.now(),this.lastPos=[0,0],this.boxEnabled=!1,this.boxInited=!1,this.boxStart=[0,0],this.boxEnd=[0,0],this.dragStart=[0,0]}e.exports=function(t){var e=t.mouseContainer,r=t.glplot,c=new l(e,r);function u(){t.xaxis.autorange=!1,t.yaxis.autorange=!1}function h(e,n,i){var a,s,l=t.calcDataBox(),h=r.viewBox,f=c.lastPos[0],p=c.lastPos[1],d=o.MINDRAG*r.pixelRatio,g=o.MINZOOM*r.pixelRatio;function v(e,r,n){var i=Math.min(r,n),a=Math.max(r,n);i!==a?(l[e]=i,l[e+2]=a,c.dataBox=l,t.setRanges(l)):(t.selectBox.selectBox=[0,0,1,1],t.glplot.setDirty())}switch(n*=r.pixelRatio,i*=r.pixelRatio,i=h[3]-h[1]-i,t.fullLayout.dragmode){case"zoom":if(e){var m=n/(h[2]-h[0])*(l[2]-l[0])+l[0],y=i/(h[3]-h[1])*(l[3]-l[1])+l[1];c.boxInited||(c.boxStart[0]=m,c.boxStart[1]=y,c.dragStart[0]=n,c.dragStart[1]=i),c.boxEnd[0]=m,c.boxEnd[1]=y,c.boxInited=!0,c.boxEnabled||c.boxStart[0]===c.boxEnd[0]&&c.boxStart[1]===c.boxEnd[1]||(c.boxEnabled=!0);var x=Math.abs(c.dragStart[0]-n)<g,b=Math.abs(c.dragStart[1]-i)<g;if(!function(){for(var e=t.graphDiv._fullLayout._axisConstraintGroups,r=t.xaxis._id,n=t.yaxis._id,i=0;i<e.length;i++)if(-1!==e[i][r]){if(-1!==e[i][n])return!0;break}return!1}()||x&&b)x&&(c.boxEnd[0]=c.boxStart[0]),b&&(c.boxEnd[1]=c.boxStart[1]);else{a=c.boxEnd[0]-c.boxStart[0],s=c.boxEnd[1]-c.boxStart[1];var _=(l[3]-l[1])/(l[2]-l[0]);Math.abs(a*_)>Math.abs(s)?(c.boxEnd[1]=c.boxStart[1]+Math.abs(a)*_*(s>=0?1:-1),c.boxEnd[1]<l[1]?(c.boxEnd[1]=l[1],c.boxEnd[0]=c.boxStart[0]+(l[1]-c.boxStart[1])/Math.abs(_)):c.boxEnd[1]>l[3]&&(c.boxEnd[1]=l[3],c.boxEnd[0]=c.boxStart[0]+(l[3]-c.boxStart[1])/Math.abs(_))):(c.boxEnd[0]=c.boxStart[0]+Math.abs(s)/_*(a>=0?1:-1),c.boxEnd[0]<l[0]?(c.boxEnd[0]=l[0],c.boxEnd[1]=c.boxStart[1]+(l[0]-c.boxStart[0])*Math.abs(_)):c.boxEnd[0]>l[2]&&(c.boxEnd[0]=l[2],c.boxEnd[1]=c.boxStart[1]+(l[2]-c.boxStart[0])*Math.abs(_)))}}else c.boxEnabled?(a=c.boxStart[0]!==c.boxEnd[0],s=c.boxStart[1]!==c.boxEnd[1],a||s?(a&&(v(0,c.boxStart[0],c.boxEnd[0]),t.xaxis.autorange=!1),s&&(v(1,c.boxStart[1],c.boxEnd[1]),t.yaxis.autorange=!1),t.relayoutCallback()):t.glplot.setDirty(),c.boxEnabled=!1,c.boxInited=!1):c.boxInited&&(c.boxInited=!1);break;case"pan":c.boxEnabled=!1,c.boxInited=!1,e?(c.panning||(c.dragStart[0]=n,c.dragStart[1]=i),Math.abs(c.dragStart[0]-n)<d&&(n=c.dragStart[0]),Math.abs(c.dragStart[1]-i)<d&&(i=c.dragStart[1]),a=(f-n)*(l[2]-l[0])/(r.viewBox[2]-r.viewBox[0]),s=(p-i)*(l[3]-l[1])/(r.viewBox[3]-r.viewBox[1]),l[0]+=a,l[2]+=a,l[1]+=s,l[3]+=s,t.setRanges(l),c.panning=!0,c.lastInputTime=Date.now(),u(),t.cameraChanged(),t.handleAnnotations()):c.panning&&(c.panning=!1,t.relayoutCallback())}c.lastPos[0]=n,c.lastPos[1]=i}return c.mouseListener=n(e,h),e.addEventListener("touchstart",function(t){var r=a(t.changedTouches[0],e);h(0,r[0],r[1]),h(1,r[0],r[1]),t.preventDefault()},!!s&&{passive:!1}),e.addEventListener("touchmove",function(t){t.preventDefault();var r=a(t.changedTouches[0],e);h(1,r[0],r[1]),t.preventDefault()},!!s&&{passive:!1}),e.addEventListener("touchend",function(t){h(0,c.lastPos[0],c.lastPos[1]),t.preventDefault()},!!s&&{passive:!1}),c.wheelListener=i(e,function(e,n){if(!t.scrollZoom)return!1;var i=t.calcDataBox(),a=r.viewBox,o=c.lastPos[0],s=c.lastPos[1],l=Math.exp(5*n/(a[3]-a[1])),h=o/(a[2]-a[0])*(i[2]-i[0])+i[0],f=s/(a[3]-a[1])*(i[3]-i[1])+i[1];return i[0]=(i[0]-h)*l+h,i[2]=(i[2]-h)*l+h,i[1]=(i[1]-f)*l+f,i[3]=(i[3]-f)*l+f,t.setRanges(i),c.lastInputTime=Date.now(),u(),t.cameraChanged(),t.handleAnnotations(),t.relayoutCallback(),!0},!0),c}},{"../cartesian/constants":751,"has-passive-events":400,"mouse-change":424,"mouse-event-offset":425,"mouse-wheel":427}],783:[function(t,e,r){"use strict";var n=t("../cartesian/axes"),i=t("../../lib/str2rgbarray");function a(t){this.scene=t,this.gl=t.gl,this.pixelRatio=t.pixelRatio,this.screenBox=[0,0,1,1],this.viewBox=[0,0,1,1],this.dataBox=[-1,-1,1,1],this.borderLineEnable=[!1,!1,!1,!1],this.borderLineWidth=[1,1,1,1],this.borderLineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.ticks=[[],[]],this.tickEnable=[!0,!0,!1,!1],this.tickPad=[15,15,15,15],this.tickAngle=[0,0,0,0],this.tickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.tickMarkLength=[0,0,0,0],this.tickMarkWidth=[0,0,0,0],this.tickMarkColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.labels=["x","y"],this.labelEnable=[!0,!0,!1,!1],this.labelAngle=[0,Math.PI/2,0,3*Math.PI/2],this.labelPad=[15,15,15,15],this.labelSize=[12,12],this.labelFont=["sans-serif","sans-serif"],this.labelColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.title="",this.titleEnable=!0,this.titleCenter=[0,0,0,0],this.titleAngle=0,this.titleColor=[0,0,0,1],this.titleFont="sans-serif",this.titleSize=18,this.gridLineEnable=[!0,!0],this.gridLineColor=[[0,0,0,.5],[0,0,0,.5]],this.gridLineWidth=[1,1],this.zeroLineEnable=[!0,!0],this.zeroLineWidth=[1,1],this.zeroLineColor=[[0,0,0,1],[0,0,0,1]],this.borderColor=!1,this.backgroundColor=[0,0,0,0],this.static=this.scene.staticPlot}var o=a.prototype,s=["xaxis","yaxis"];o.merge=function(t){var e,r,n,a,o,l,c,u,h,f,p;for(this.titleEnable=!1,this.backgroundColor=i(t.plot_bgcolor),f=0;f<2;++f){var d=(e=s[f]).charAt(0);for(n=(r=t[this.scene[e]._name]).title.text===this.scene.fullLayout._dfltTitle[d]?"":r.title.text,p=0;p<=2;p+=2)this.labelEnable[f+p]=!1,this.labels[f+p]=n,this.labelColor[f+p]=i(r.title.font.color),this.labelFont[f+p]=r.title.font.family,this.labelSize[f+p]=r.title.font.size,this.labelPad[f+p]=this.getLabelPad(e,r),this.tickEnable[f+p]=!1,this.tickColor[f+p]=i((r.tickfont||{}).color),this.tickAngle[f+p]="auto"===r.tickangle?0:Math.PI*-r.tickangle/180,this.tickPad[f+p]=this.getTickPad(r),this.tickMarkLength[f+p]=0,this.tickMarkWidth[f+p]=r.tickwidth||0,this.tickMarkColor[f+p]=i(r.tickcolor),this.borderLineEnable[f+p]=!1,this.borderLineColor[f+p]=i(r.linecolor),this.borderLineWidth[f+p]=r.linewidth||0;c=this.hasSharedAxis(r),o=this.hasAxisInDfltPos(e,r)&&!c,l=this.hasAxisInAltrPos(e,r)&&!c,a=r.mirror||!1,u=c?-1!==String(a).indexOf("all"):!!a,h=c?"allticks"===a:-1!==String(a).indexOf("ticks"),o?this.labelEnable[f]=!0:l&&(this.labelEnable[f+2]=!0),o?this.tickEnable[f]=r.showticklabels:l&&(this.tickEnable[f+2]=r.showticklabels),(o||u)&&(this.borderLineEnable[f]=r.showline),(l||u)&&(this.borderLineEnable[f+2]=r.showline),(o||h)&&(this.tickMarkLength[f]=this.getTickMarkLength(r)),(l||h)&&(this.tickMarkLength[f+2]=this.getTickMarkLength(r)),this.gridLineEnable[f]=r.showgrid,this.gridLineColor[f]=i(r.gridcolor),this.gridLineWidth[f]=r.gridwidth,this.zeroLineEnable[f]=r.zeroline,this.zeroLineColor[f]=i(r.zerolinecolor),this.zeroLineWidth[f]=r.zerolinewidth}},o.hasSharedAxis=function(t){var e=this.scene,r=e.fullLayout._subplots.gl2d;return 0!==n.findSubplotsWithAxis(r,t).indexOf(e.id)},o.hasAxisInDfltPos=function(t,e){var r=e.side;return"xaxis"===t?"bottom"===r:"yaxis"===t?"left"===r:void 0},o.hasAxisInAltrPos=function(t,e){var r=e.side;return"xaxis"===t?"top"===r:"yaxis"===t?"right"===r:void 0},o.getLabelPad=function(t,e){var r=e.title.font.size,n=e.showticklabels;return"xaxis"===t?"top"===e.side?r*(1.5+(n?1:0))-10:r*(1.5+(n?.5:0))-10:"yaxis"===t?"right"===e.side?10+r*(1.5+(n?1:.5)):10+r*(1.5+(n?.5:0)):void 0},o.getTickPad=function(t){return"outside"===t.ticks?10+t.ticklen:15},o.getTickMarkLength=function(t){if(!t.ticks)return 0;var e=t.ticklen;return"inside"===t.ticks?-e:e},e.exports=function(t){return new a(t)}},{"../../lib/str2rgbarray":720,"../cartesian/axes":745}],784:[function(t,e,r){"use strict";var n=t("../../plot_api/edit_types").overrideAll,i=t("./scene2d"),a=t("../layout_attributes"),o=t("../../constants/xmlns_namespaces"),s=t("../cartesian/constants"),l=t("../cartesian"),c=t("../../components/fx/layout_attributes"),u=t("../get_data").getSubplotData;r.name="gl2d",r.attr=["xaxis","yaxis"],r.idRoot=["x","y"],r.idRegex=s.idRegex,r.attrRegex=s.attrRegex,r.attributes=t("../cartesian/attributes"),r.supplyLayoutDefaults=function(t,e,r){e._has("cartesian")||l.supplyLayoutDefaults(t,e,r)},r.layoutAttrOverrides=n(l.layoutAttributes,"plot","from-root"),r.baseLayoutAttrOverrides=n({plot_bgcolor:a.plot_bgcolor,hoverlabel:c.hoverlabel},"plot","nested"),r.plot=function(t){for(var e=t._fullLayout,r=t._fullData,n=e._subplots.gl2d,a=0;a<n.length;a++){var o=n[a],s=e._plots[o],l=u(r,"gl2d",o),c=s._scene2d;void 0===c&&(c=new i({id:o,graphDiv:t,container:t.querySelector(".gl-container"),staticPlot:t._context.staticPlot,plotGlPixelRatio:t._context.plotGlPixelRatio},e),s._scene2d=c),c.plot(l,t.calcdata,e,t.layout)}},r.clean=function(t,e,r,n){for(var i=n._subplots.gl2d||[],a=0;a<i.length;a++){var o=i[a],s=n._plots[o];if(s._scene2d)0===u(t,"gl2d",o).length&&(s._scene2d.destroy(),delete n._plots[o])}l.clean.apply(this,arguments)},r.drawFramework=function(t){t._context.staticPlot||l.drawFramework(t)},r.toSVG=function(t){for(var e=t._fullLayout,r=e._subplots.gl2d,n=0;n<r.length;n++){var i=e._plots[r[n]]._scene2d,a=i.toImage("png");e._glimages.append("svg:image").attr({xmlns:o.svg,"xlink:href":a,x:0,y:0,width:"100%",height:"100%",preserveAspectRatio:"none"}),i.destroy()}},r.updateFx=function(t){for(var e=t._fullLayout,r=e._subplots.gl2d,n=0;n<r.length;n++){e._plots[r[n]]._scene2d.updateFx(e.dragmode)}}},{"../../components/fx/layout_attributes":614,"../../constants/xmlns_namespaces":675,"../../plot_api/edit_types":728,"../cartesian":756,"../cartesian/attributes":743,"../cartesian/constants":751,"../get_data":781,"../layout_attributes":798,"./scene2d":785}],785:[function(t,e,r){"use strict";var n,i,a=t("../../registry"),o=t("../../plots/cartesian/axes"),s=t("../../components/fx"),l=t("gl-plot2d"),c=t("gl-spikes2d"),u=t("gl-select-box"),h=t("webgl-context"),f=t("./convert"),p=t("./camera"),d=t("../../lib/show_no_webgl_msg"),g=t("../cartesian/constraints"),v=g.enforce,m=g.clean,y=t("../cartesian/autorange").doAutoRange,x=["xaxis","yaxis"],b=t("../cartesian/constants").SUBPLOT_PATTERN;function _(t,e){this.container=t.container,this.graphDiv=t.graphDiv,this.pixelRatio=t.plotGlPixelRatio||window.devicePixelRatio,this.id=t.id,this.staticPlot=!!t.staticPlot,this.scrollZoom=this.graphDiv._context._scrollZoom.cartesian,this.fullData=null,this.updateRefs(e),this.makeFramework(),this.stopped||(this.glplotOptions=f(this),this.glplotOptions.merge(e),this.glplot=l(this.glplotOptions),this.camera=p(this),this.traces={},this.spikes=c(this.glplot),this.selectBox=u(this.glplot,{innerFill:!1,outerFill:!0}),this.lastButtonState=0,this.pickResult=null,this.isMouseOver=!0,this.stopped=!1,this.redraw=this.draw.bind(this),this.redraw())}e.exports=_;var w=_.prototype;w.makeFramework=function(){if(this.staticPlot){if(!(i||(n=document.createElement("canvas"),i=h({canvas:n,preserveDrawingBuffer:!1,premultipliedAlpha:!0,antialias:!0}))))throw new Error("Error creating static canvas/context for image server");this.canvas=n,this.gl=i}else{var t=this.container.querySelector(".gl-canvas-focus"),e=h({canvas:t,preserveDrawingBuffer:!0,premultipliedAlpha:!0});if(!e)return d(this),void(this.stopped=!0);this.canvas=t,this.gl=e}var r=this.canvas;r.style.width="100%",r.style.height="100%",r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style["pointer-events"]="none",this.updateSize(r),r.className+=" user-select-none";var a=this.svgContainer=document.createElementNS("http://www.w3.org/2000/svg","svg");a.style.position="absolute",a.style.top=a.style.left="0px",a.style.width=a.style.height="100%",a.style["z-index"]=20,a.style["pointer-events"]="none";var o=this.mouseContainer=document.createElement("div");o.style.position="absolute",o.style["pointer-events"]="auto",this.pickCanvas=this.container.querySelector(".gl-canvas-pick");var s=this.container;s.appendChild(a),s.appendChild(o);var l=this;o.addEventListener("mouseout",function(){l.isMouseOver=!1,l.unhover()}),o.addEventListener("mouseover",function(){l.isMouseOver=!0})},w.toImage=function(t){t||(t="png"),this.stopped=!0,this.staticPlot&&this.container.appendChild(n),this.updateSize(this.canvas);var e=this.glplot.gl,r=e.drawingBufferWidth,i=e.drawingBufferHeight;e.clearColor(1,1,1,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT),this.glplot.setDirty(),this.glplot.draw(),e.bindFramebuffer(e.FRAMEBUFFER,null);var a=new Uint8Array(r*i*4);e.readPixels(0,0,r,i,e.RGBA,e.UNSIGNED_BYTE,a);for(var o=0,s=i-1;o<s;++o,--s)for(var l=0;l<r;++l)for(var c=0;c<4;++c){var u=a[4*(r*o+l)+c];a[4*(r*o+l)+c]=a[4*(r*s+l)+c],a[4*(r*s+l)+c]=u}var h=document.createElement("canvas");h.width=r,h.height=i;var f,p=h.getContext("2d"),d=p.createImageData(r,i);switch(d.data.set(a),p.putImageData(d,0,0),t){case"jpeg":f=h.toDataURL("image/jpeg");break;case"webp":f=h.toDataURL("image/webp");break;default:f=h.toDataURL("image/png")}return this.staticPlot&&this.container.removeChild(n),f},w.updateSize=function(t){t||(t=this.canvas);var e=this.pixelRatio,r=this.fullLayout,n=r.width,i=r.height,a=0|Math.ceil(e*n),o=0|Math.ceil(e*i);return t.width===a&&t.height===o||(t.width=a,t.height=o),t},w.computeTickMarks=function(){this.xaxis.setScale(),this.yaxis.setScale();for(var t=[o.calcTicks(this.xaxis),o.calcTicks(this.yaxis)],e=0;e<2;++e)for(var r=0;r<t[e].length;++r)t[e][r].text=t[e][r].text+"";return t},w.updateRefs=function(t){this.fullLayout=t;var e=this.id.match(b),r="xaxis"+e[1],n="yaxis"+e[2];this.xaxis=this.fullLayout[r],this.yaxis=this.fullLayout[n]},w.relayoutCallback=function(){var t=this.graphDiv,e=this.xaxis,r=this.yaxis,n=t.layout,i={},o=i[e._name+".range"]=e.range.slice(),s=i[r._name+".range"]=r.range.slice();i[e._name+".autorange"]=e.autorange,i[r._name+".autorange"]=r.autorange,a.call("_storeDirectGUIEdit",t.layout,t._fullLayout._preGUI,i);var l=n[e._name];l.range=o,l.autorange=e.autorange;var c=n[r._name];c.range=s,c.autorange=r.autorange,i.lastInputTime=this.camera.lastInputTime,t.emit("plotly_relayout",i)},w.cameraChanged=function(){var t=this.camera;this.glplot.setDataBox(this.calcDataBox());var e=this.computeTickMarks();(function(t,e){for(var r=0;r<2;++r){var n=t[r],i=e[r];if(n.length!==i.length)return!0;for(var a=0;a<n.length;++a)if(n[a].x!==i[a].x)return!0}return!1})(e,this.glplotOptions.ticks)&&(this.glplotOptions.ticks=e,this.glplotOptions.dataBox=t.dataBox,this.glplot.update(this.glplotOptions),this.handleAnnotations())},w.handleAnnotations=function(){for(var t=this.graphDiv,e=this.fullLayout.annotations,r=0;r<e.length;r++){var n=e[r];n.xref===this.xaxis._id&&n.yref===this.yaxis._id&&a.getComponentMethod("annotations","drawOne")(t,r)}},w.destroy=function(){if(this.glplot){var t=this.traces;t&&Object.keys(t).map(function(e){t[e].dispose(),delete t[e]}),this.glplot.dispose(),this.container.removeChild(this.svgContainer),this.container.removeChild(this.mouseContainer),this.fullData=null,this.glplot=null,this.stopped=!0,this.camera.mouseListener.enabled=!1,this.mouseContainer.removeEventListener("wheel",this.camera.wheelListener),this.camera=null}},w.plot=function(t,e,r){var n=this.glplot;this.updateRefs(r),this.xaxis.clearCalc(),this.yaxis.clearCalc(),this.updateTraces(t,e),this.updateFx(r.dragmode);var i=r.width,a=r.height;this.updateSize(this.canvas);var o=this.glplotOptions;o.merge(r),o.screenBox=[0,0,i,a];var s={_fullLayout:{_axisConstraintGroups:this.graphDiv._fullLayout._axisConstraintGroups,xaxis:this.xaxis,yaxis:this.yaxis}};m(s,this.xaxis),m(s,this.yaxis);var l,c,u=r._size,h=this.xaxis.domain,f=this.yaxis.domain;for(o.viewBox=[u.l+h[0]*u.w,u.b+f[0]*u.h,i-u.r-(1-h[1])*u.w,a-u.t-(1-f[1])*u.h],this.mouseContainer.style.width=u.w*(h[1]-h[0])+"px",this.mouseContainer.style.height=u.h*(f[1]-f[0])+"px",this.mouseContainer.height=u.h*(f[1]-f[0]),this.mouseContainer.style.left=u.l+h[0]*u.w+"px",this.mouseContainer.style.top=u.t+(1-f[1])*u.h+"px",c=0;c<2;++c)(l=this[x[c]])._length=o.viewBox[c+2]-o.viewBox[c],y(this.graphDiv,l),l.setScale();v(s),o.ticks=this.computeTickMarks(),o.dataBox=this.calcDataBox(),o.merge(r),n.update(o),this.glplot.draw()},w.calcDataBox=function(){var t=this.xaxis,e=this.yaxis,r=t.range,n=e.range,i=t.r2l,a=e.r2l;return[i(r[0]),a(n[0]),i(r[1]),a(n[1])]},w.setRanges=function(t){var e=this.xaxis,r=this.yaxis,n=e.l2r,i=r.l2r;e.range=[n(t[0]),n(t[2])],r.range=[i(t[1]),i(t[3])]},w.updateTraces=function(t,e){var r,n,i,a=Object.keys(this.traces);this.fullData=t;t:for(r=0;r<a.length;r++){var o=a[r],s=this.traces[o];for(n=0;n<t.length;n++)if((i=t[n]).uid===o&&i.type===s.type)continue t;s.dispose(),delete this.traces[o]}for(r=0;r<t.length;r++){i=t[r];var l=e[r],c=this.traces[i.uid];c?c.update(i,l):(c=i._module.plot(this,i,l),this.traces[i.uid]=c)}this.glplot.objects.sort(function(t,e){return t._trace.index-e._trace.index})},w.updateFx=function(t){"lasso"===t||"select"===t?(this.pickCanvas.style["pointer-events"]="none",this.mouseContainer.style["pointer-events"]="none"):(this.pickCanvas.style["pointer-events"]="auto",this.mouseContainer.style["pointer-events"]="auto"),this.mouseContainer.style.cursor="pan"===t?"move":"zoom"===t?"crosshair":null},w.emitPointAction=function(t,e){for(var r,n=t.trace.uid,i=t.pointIndex,a=0;a<this.fullData.length;a++)this.fullData[a].uid===n&&(r=this.fullData[a]);var o={x:t.traceCoord[0],y:t.traceCoord[1],curveNumber:r.index,pointNumber:i,data:r._input,fullData:this.fullData,xaxis:this.xaxis,yaxis:this.yaxis};s.appendArrayPointValue(o,r,i),this.graphDiv.emit(e,{points:[o]})},w.draw=function(){if(!this.stopped){requestAnimationFrame(this.redraw);var t=this.glplot,e=this.camera,r=e.mouseListener,n=1===this.lastButtonState&&0===r.buttons,i=this.fullLayout;this.lastButtonState=r.buttons,this.cameraChanged();var a,o=r.x*t.pixelRatio,l=this.canvas.height-t.pixelRatio*r.y;if(e.boxEnabled&&"zoom"===i.dragmode){this.selectBox.enabled=!0;for(var c=this.selectBox.selectBox=[Math.min(e.boxStart[0],e.boxEnd[0]),Math.min(e.boxStart[1],e.boxEnd[1]),Math.max(e.boxStart[0],e.boxEnd[0]),Math.max(e.boxStart[1],e.boxEnd[1])],u=0;u<2;u++)e.boxStart[u]===e.boxEnd[u]&&(c[u]=t.dataBox[u],c[u+2]=t.dataBox[u+2]);t.setDirty()}else if(!e.panning&&this.isMouseOver){this.selectBox.enabled=!1;var h=i._size,f=this.xaxis.domain,p=this.yaxis.domain,d=(a=t.pick(o/t.pixelRatio+h.l+f[0]*h.w,l/t.pixelRatio-(h.t+(1-p[1])*h.h)))&&a.object._trace.handlePick(a);if(d&&n&&this.emitPointAction(d,"plotly_click"),a&&"skip"!==a.object._trace.hoverinfo&&i.hovermode&&d&&(!this.lastPickResult||this.lastPickResult.traceUid!==d.trace.uid||this.lastPickResult.dataCoord[0]!==d.dataCoord[0]||this.lastPickResult.dataCoord[1]!==d.dataCoord[1])){var g=d;this.lastPickResult={traceUid:d.trace?d.trace.uid:null,dataCoord:d.dataCoord.slice()},this.spikes.update({center:a.dataCoord}),g.screenCoord=[((t.viewBox[2]-t.viewBox[0])*(a.dataCoord[0]-t.dataBox[0])/(t.dataBox[2]-t.dataBox[0])+t.viewBox[0])/t.pixelRatio,(this.canvas.height-(t.viewBox[3]-t.viewBox[1])*(a.dataCoord[1]-t.dataBox[1])/(t.dataBox[3]-t.dataBox[1])-t.viewBox[1])/t.pixelRatio],this.emitPointAction(d,"plotly_hover");var v=this.fullData[g.trace.index]||{},m=g.pointIndex,y=s.castHoverinfo(v,i,m);if(y&&"all"!==y){var x=y.split("+");-1===x.indexOf("x")&&(g.traceCoord[0]=void 0),-1===x.indexOf("y")&&(g.traceCoord[1]=void 0),-1===x.indexOf("z")&&(g.traceCoord[2]=void 0),-1===x.indexOf("text")&&(g.textLabel=void 0),-1===x.indexOf("name")&&(g.name=void 0)}s.loneHover({x:g.screenCoord[0],y:g.screenCoord[1],xLabel:this.hoverFormatter("xaxis",g.traceCoord[0]),yLabel:this.hoverFormatter("yaxis",g.traceCoord[1]),zLabel:g.traceCoord[2],text:g.textLabel,name:g.name,color:s.castHoverOption(v,m,"bgcolor")||g.color,borderColor:s.castHoverOption(v,m,"bordercolor"),fontFamily:s.castHoverOption(v,m,"font.family"),fontSize:s.castHoverOption(v,m,"font.size"),fontColor:s.castHoverOption(v,m,"font.color")},{container:this.svgContainer,gd:this.graphDiv})}}a||this.unhover(),t.draw()}},w.unhover=function(){this.lastPickResult&&(this.spikes.update({}),this.lastPickResult=null,this.graphDiv.emit("plotly_unhover"),s.loneUnhover(this.svgContainer))},w.hoverFormatter=function(t,e){if(void 0!==e){var r=this[t];return o.tickText(r,r.c2l(e),"hover").text}}},{"../../components/fx":613,"../../lib/show_no_webgl_msg":718,"../../plots/cartesian/axes":745,"../../registry":826,"../cartesian/autorange":744,"../cartesian/constants":751,"../cartesian/constraints":752,"./camera":782,"./convert":783,"gl-plot2d":280,"gl-select-box":292,"gl-spikes2d":301,"webgl-context":537}],786:[function(t,e,r){"use strict";var n=t("../../plot_api/edit_types").overrideAll,i=t("../../components/fx/layout_attributes"),a=t("./scene"),o=t("../get_data").getSubplotData,s=t("../../lib"),l=t("../../constants/xmlns_namespaces");r.name="gl3d",r.attr="scene",r.idRoot="scene",r.idRegex=r.attrRegex=s.counterRegex("scene"),r.attributes=t("./layout/attributes"),r.layoutAttributes=t("./layout/layout_attributes"),r.baseLayoutAttrOverrides=n({hoverlabel:i.hoverlabel},"plot","nested"),r.supplyLayoutDefaults=t("./layout/defaults"),r.plot=function(t){for(var e=t._fullLayout,r=t._fullData,n=e._subplots.gl3d,i=0;i<n.length;i++){var s=n[i],l=o(r,"gl3d",s),c=e[s],u=c.camera,h=c._scene;h||(h=new a({id:s,graphDiv:t,container:t.querySelector(".gl-container"),staticPlot:t._context.staticPlot,plotGlPixelRatio:t._context.plotGlPixelRatio,camera:u},e),c._scene=h),h.viewInitial||(h.viewInitial={up:{x:u.up.x,y:u.up.y,z:u.up.z},eye:{x:u.eye.x,y:u.eye.y,z:u.eye.z},center:{x:u.center.x,y:u.center.y,z:u.center.z}}),h.plot(l,e,t.layout)}},r.clean=function(t,e,r,n){for(var i=n._subplots.gl3d||[],a=0;a<i.length;a++){var o=i[a];!e[o]&&n[o]._scene&&(n[o]._scene.destroy(),n._infolayer&&n._infolayer.selectAll(".annotation-"+o).remove())}},r.toSVG=function(t){for(var e=t._fullLayout,r=e._subplots.gl3d,n=e._size,i=0;i<r.length;i++){var a=e[r[i]],o=a.domain,s=a._scene,c=s.toImage("png");e._glimages.append("svg:image").attr({xmlns:l.svg,"xlink:href":c,x:n.l+n.w*o.x[0],y:n.t+n.h*(1-o.y[1]),width:n.w*(o.x[1]-o.x[0]),height:n.h*(o.y[1]-o.y[0]),preserveAspectRatio:"none"}),s.destroy()}},r.cleanId=function(t){if(t.match(/^scene[0-9]*$/)){var e=t.substr(5);return"1"===e&&(e=""),"scene"+e}},r.updateFx=function(t){for(var e=t._fullLayout,r=e._subplots.gl3d,n=0;n<r.length;n++){e[r[n]]._scene.updateFx(e.dragmode,e.hovermode)}}},{"../../components/fx/layout_attributes":614,"../../constants/xmlns_namespaces":675,"../../lib":697,"../../plot_api/edit_types":728,"../get_data":781,"./layout/attributes":787,"./layout/defaults":791,"./layout/layout_attributes":792,"./scene":796}],787:[function(t,e,r){"use strict";e.exports={scene:{valType:"subplotid",dflt:"scene",editType:"calc+clearAxisTypes"}}},{}],788:[function(t,e,r){"use strict";var n=t("../../../components/color"),i=t("../../cartesian/layout_attributes"),a=t("../../../lib/extend").extendFlat,o=t("../../../plot_api/edit_types").overrideAll;e.exports=o({visible:i.visible,showspikes:{valType:"boolean",dflt:!0},spikesides:{valType:"boolean",dflt:!0},spikethickness:{valType:"number",min:0,dflt:2},spikecolor:{valType:"color",dflt:n.defaultLine},showbackground:{valType:"boolean",dflt:!1},backgroundcolor:{valType:"color",dflt:"rgba(204, 204, 204, 0.5)"},showaxeslabels:{valType:"boolean",dflt:!0},color:i.color,categoryorder:i.categoryorder,categoryarray:i.categoryarray,title:i.title,type:a({},i.type,{values:["-","linear","log","date","category"]}),autorange:i.autorange,rangemode:i.rangemode,range:a({},i.range,{items:[{valType:"any",editType:"plot",impliedEdits:{"^autorange":!1}},{valType:"any",editType:"plot",impliedEdits:{"^autorange":!1}}],anim:!1}),tickmode:i.tickmode,nticks:i.nticks,tick0:i.tick0,dtick:i.dtick,tickvals:i.tickvals,ticktext:i.ticktext,ticks:i.ticks,mirror:i.mirror,ticklen:i.ticklen,tickwidth:i.tickwidth,tickcolor:i.tickcolor,showticklabels:i.showticklabels,tickfont:i.tickfont,tickangle:i.tickangle,tickprefix:i.tickprefix,showtickprefix:i.showtickprefix,ticksuffix:i.ticksuffix,showticksuffix:i.showticksuffix,showexponent:i.showexponent,exponentformat:i.exponentformat,separatethousands:i.separatethousands,tickformat:i.tickformat,tickformatstops:i.tickformatstops,hoverformat:i.hoverformat,showline:i.showline,linecolor:i.linecolor,linewidth:i.linewidth,showgrid:i.showgrid,gridcolor:a({},i.gridcolor,{dflt:"rgb(204, 204, 204)"}),gridwidth:i.gridwidth,zeroline:i.zeroline,zerolinecolor:i.zerolinecolor,zerolinewidth:i.zerolinewidth,_deprecated:{title:i._deprecated.title,titlefont:i._deprecated.titlefont}},"plot","from-root")},{"../../../components/color":574,"../../../lib/extend":687,"../../../plot_api/edit_types":728,"../../cartesian/layout_attributes":757}],789:[function(t,e,r){"use strict";var n=t("tinycolor2").mix,i=t("../../../lib"),a=t("../../../plot_api/plot_template"),o=t("./axis_attributes"),s=t("../../cartesian/type_defaults"),l=t("../../cartesian/axis_defaults"),c=["xaxis","yaxis","zaxis"];e.exports=function(t,e,r){var u,h;function f(t,e){return i.coerce(u,h,o,t,e)}for(var p=0;p<c.length;p++){var d=c[p];u=t[d]||{},(h=a.newContainer(e,d))._id=d[0]+r.scene,h._name=d,s(u,h,f,r),l(u,h,f,{font:r.font,letter:d[0],data:r.data,showGrid:!0,noTickson:!0,bgColor:r.bgColor,calendar:r.calendar},r.fullLayout),f("gridcolor",n(h.color,r.bgColor,13600/187).toRgbString()),f("title.text",d[0]),h.setScale=i.noop,f("showspikes")&&(f("spikesides"),f("spikethickness"),f("spikecolor",h.color)),f("showaxeslabels"),f("showbackground")&&f("backgroundcolor")}}},{"../../../lib":697,"../../../plot_api/plot_template":735,"../../cartesian/axis_defaults":747,"../../cartesian/type_defaults":768,"./axis_attributes":788,tinycolor2:518}],790:[function(t,e,r){"use strict";var n=t("../../../lib/str2rgbarray"),i=t("../../../lib"),a=["xaxis","yaxis","zaxis"];function o(){this.bounds=[[-10,-10,-10],[10,10,10]],this.ticks=[[],[],[]],this.tickEnable=[!0,!0,!0],this.tickFont=["sans-serif","sans-serif","sans-serif"],this.tickSize=[12,12,12],this.tickAngle=[0,0,0],this.tickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.tickPad=[18,18,18],this.labels=["x","y","z"],this.labelEnable=[!0,!0,!0],this.labelFont=["Open Sans","Open Sans","Open Sans"],this.labelSize=[20,20,20],this.labelColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.labelPad=[30,30,30],this.lineEnable=[!0,!0,!0],this.lineMirror=[!1,!1,!1],this.lineWidth=[1,1,1],this.lineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.lineTickEnable=[!0,!0,!0],this.lineTickMirror=[!1,!1,!1],this.lineTickLength=[10,10,10],this.lineTickWidth=[1,1,1],this.lineTickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.gridEnable=[!0,!0,!0],this.gridWidth=[1,1,1],this.gridColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroEnable=[!0,!0,!0],this.zeroLineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroLineWidth=[2,2,2],this.backgroundEnable=[!0,!0,!0],this.backgroundColor=[[.8,.8,.8,.5],[.8,.8,.8,.5],[.8,.8,.8,.5]],this._defaultTickPad=this.tickPad.slice(),this._defaultLabelPad=this.labelPad.slice(),this._defaultLineTickLength=this.lineTickLength.slice()}o.prototype.merge=function(t,e){for(var r=0;r<3;++r){var o=e[a[r]];o.visible?(this.labels[r]=t.meta?i.templateString(o.title.text,{meta:t.meta}):o.title.text,"font"in o.title&&(o.title.font.color&&(this.labelColor[r]=n(o.title.font.color)),o.title.font.family&&(this.labelFont[r]=o.title.font.family),o.title.font.size&&(this.labelSize[r]=o.title.font.size)),"showline"in o&&(this.lineEnable[r]=o.showline),"linecolor"in o&&(this.lineColor[r]=n(o.linecolor)),"linewidth"in o&&(this.lineWidth[r]=o.linewidth),"showgrid"in o&&(this.gridEnable[r]=o.showgrid),"gridcolor"in o&&(this.gridColor[r]=n(o.gridcolor)),"gridwidth"in o&&(this.gridWidth[r]=o.gridwidth),"log"===o.type?this.zeroEnable[r]=!1:"zeroline"in o&&(this.zeroEnable[r]=o.zeroline),"zerolinecolor"in o&&(this.zeroLineColor[r]=n(o.zerolinecolor)),"zerolinewidth"in o&&(this.zeroLineWidth[r]=o.zerolinewidth),"ticks"in o&&o.ticks?this.lineTickEnable[r]=!0:this.lineTickEnable[r]=!1,"ticklen"in o&&(this.lineTickLength[r]=this._defaultLineTickLength[r]=o.ticklen),"tickcolor"in o&&(this.lineTickColor[r]=n(o.tickcolor)),"tickwidth"in o&&(this.lineTickWidth[r]=o.tickwidth),"tickangle"in o&&(this.tickAngle[r]="auto"===o.tickangle?-3600:Math.PI*-o.tickangle/180),"showticklabels"in o&&(this.tickEnable[r]=o.showticklabels),"tickfont"in o&&(o.tickfont.color&&(this.tickColor[r]=n(o.tickfont.color)),o.tickfont.family&&(this.tickFont[r]=o.tickfont.family),o.tickfont.size&&(this.tickSize[r]=o.tickfont.size)),"mirror"in o?-1!==["ticks","all","allticks"].indexOf(o.mirror)?(this.lineTickMirror[r]=!0,this.lineMirror[r]=!0):!0===o.mirror?(this.lineTickMirror[r]=!1,this.lineMirror[r]=!0):(this.lineTickMirror[r]=!1,this.lineMirror[r]=!1):this.lineMirror[r]=!1,"showbackground"in o&&!1!==o.showbackground?(this.backgroundEnable[r]=!0,this.backgroundColor[r]=n(o.backgroundcolor)):this.backgroundEnable[r]=!1):(this.tickEnable[r]=!1,this.labelEnable[r]=!1,this.lineEnable[r]=!1,this.lineTickEnable[r]=!1,this.gridEnable[r]=!1,this.zeroEnable[r]=!1,this.backgroundEnable[r]=!1)}},e.exports=function(t,e){var r=new o;return r.merge(t,e),r}},{"../../../lib":697,"../../../lib/str2rgbarray":720}],791:[function(t,e,r){"use strict";var n=t("../../../lib"),i=t("../../../components/color"),a=t("../../../registry"),o=t("../../subplot_defaults"),s=t("./axis_defaults"),l=t("./layout_attributes"),c=t("../../get_data").getSubplotData,u="gl3d";function h(t,e,r,n){for(var o=r("bgcolor"),l=i.combine(o,n.paper_bgcolor),h=["up","center","eye"],f=0;f<h.length;f++)r("camera."+h[f]+".x"),r("camera."+h[f]+".y"),r("camera."+h[f]+".z");r("camera.projection.type");var p=!!r("aspectratio.x")&&!!r("aspectratio.y")&&!!r("aspectratio.z"),d=r("aspectmode",p?"manual":"auto");p||(t.aspectratio=e.aspectratio={x:1,y:1,z:1},"manual"===d&&(e.aspectmode="auto"),t.aspectmode=e.aspectmode);var g=c(n.fullData,u,n.id);s(t,e,{font:n.font,scene:n.id,data:g,bgColor:l,calendar:n.calendar,fullLayout:n.fullLayout}),a.getComponentMethod("annotations3d","handleDefaults")(t,e,n);var v=n.getDfltFromLayout("dragmode");if(!1!==v&&!v)if(v="orbit",t.camera&&t.camera.up){var m=t.camera.up.x,y=t.camera.up.y,x=t.camera.up.z;0!==x&&(m&&y&&x?x/Math.sqrt(m*m+y*y+x*x)>.999&&(v="turntable"):v="turntable")}else v="turntable";r("dragmode",v),r("hovermode",n.getDfltFromLayout("hovermode"))}e.exports=function(t,e,r){var i=e._basePlotModules.length>1;o(t,e,r,{type:u,attributes:l,handleDefaults:h,fullLayout:e,font:e.font,fullData:r,getDfltFromLayout:function(e){if(!i)return n.validate(t[e],l[e])?t[e]:void 0},paper_bgcolor:e.paper_bgcolor,calendar:e.calendar})}},{"../../../components/color":574,"../../../lib":697,"../../../registry":826,"../../get_data":781,"../../subplot_defaults":821,"./axis_defaults":789,"./layout_attributes":792}],792:[function(t,e,r){"use strict";var n=t("./axis_attributes"),i=t("../../domain").attributes,a=t("../../../lib/extend").extendFlat,o=t("../../../lib").counterRegex;function s(t,e,r){return{x:{valType:"number",dflt:t,editType:"camera"},y:{valType:"number",dflt:e,editType:"camera"},z:{valType:"number",dflt:r,editType:"camera"},editType:"camera"}}e.exports={_arrayAttrRegexps:[o("scene",".annotations",!0)],bgcolor:{valType:"color",dflt:"rgba(0,0,0,0)",editType:"plot"},camera:{up:a(s(0,0,1),{}),center:a(s(0,0,0),{}),eye:a(s(1.25,1.25,1.25),{}),projection:{type:{valType:"enumerated",values:["perspective","orthographic"],dflt:"perspective",editType:"calc"},editType:"calc"},editType:"camera"},domain:i({name:"scene",editType:"plot"}),aspectmode:{valType:"enumerated",values:["auto","cube","data","manual"],dflt:"auto",editType:"plot",impliedEdits:{"aspectratio.x":void 0,"aspectratio.y":void 0,"aspectratio.z":void 0}},aspectratio:{x:{valType:"number",min:0,editType:"plot",impliedEdits:{"^aspectmode":"manual"}},y:{valType:"number",min:0,editType:"plot",impliedEdits:{"^aspectmode":"manual"}},z:{valType:"number",min:0,editType:"plot",impliedEdits:{"^aspectmode":"manual"}},editType:"plot",impliedEdits:{aspectmode:"manual"}},xaxis:n,yaxis:n,zaxis:n,dragmode:{valType:"enumerated",values:["orbit","turntable","zoom","pan",!1],editType:"plot"},hovermode:{valType:"enumerated",values:["closest",!1],dflt:"closest",editType:"modebar"},uirevision:{valType:"any",editType:"none"},editType:"plot",_deprecated:{cameraposition:{valType:"info_array",editType:"camera"}}}},{"../../../lib":697,"../../../lib/extend":687,"../../domain":770,"./axis_attributes":788}],793:[function(t,e,r){"use strict";var n=t("../../../lib/str2rgbarray"),i=["xaxis","yaxis","zaxis"];function a(){this.enabled=[!0,!0,!0],this.colors=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.drawSides=[!0,!0,!0],this.lineWidth=[1,1,1]}a.prototype.merge=function(t){for(var e=0;e<3;++e){var r=t[i[e]];r.visible?(this.enabled[e]=r.showspikes,this.colors[e]=n(r.spikecolor),this.drawSides[e]=r.spikesides,this.lineWidth[e]=r.spikethickness):(this.enabled[e]=!1,this.drawSides[e]=!1)}},e.exports=function(t){var e=new a;return e.merge(t),e}},{"../../../lib/str2rgbarray":720}],794:[function(t,e,r){"use strict";e.exports=function(t){for(var e=t.axesOptions,r=t.glplot.axesPixels,s=t.fullSceneLayout,l=[[],[],[]],c=0;c<3;++c){var u=s[a[c]];if(u._length=(r[c].hi-r[c].lo)*r[c].pixelsPerDataUnit/t.dataScale[c],Math.abs(u._length)===1/0||isNaN(u._length))l[c]=[];else{u._input_range=u.range.slice(),u.range[0]=r[c].lo/t.dataScale[c],u.range[1]=r[c].hi/t.dataScale[c],u._m=1/(t.dataScale[c]*r[c].pixelsPerDataUnit),u.range[0]===u.range[1]&&(u.range[0]-=1,u.range[1]+=1);var h=u.tickmode;if("auto"===u.tickmode){u.tickmode="linear";var f=u.nticks||i.constrain(u._length/40,4,9);n.autoTicks(u,Math.abs(u.range[1]-u.range[0])/f)}for(var p=n.calcTicks(u),d=0;d<p.length;++d)p[d].x=p[d].x*t.dataScale[c],"date"===u.type&&(p[d].text=p[d].text.replace(/\<br\>/g," "));l[c]=p,u.tickmode=h}}e.ticks=l;for(var c=0;c<3;++c){o[c]=.5*(t.glplot.bounds[0][c]+t.glplot.bounds[1][c]);for(var d=0;d<2;++d)e.bounds[d][c]=t.glplot.bounds[d][c]}t.contourLevels=function(t){for(var e=new Array(3),r=0;r<3;++r){for(var n=t[r],i=new Array(n.length),a=0;a<n.length;++a)i[a]=n[a].x;e[r]=i}return e}(l)};var n=t("../../cartesian/axes"),i=t("../../../lib"),a=["xaxis","yaxis","zaxis"],o=[0,0,0]},{"../../../lib":697,"../../cartesian/axes":745}],795:[function(t,e,r){"use strict";function n(t,e){var r,n,i=[0,0,0,0];for(r=0;r<4;++r)for(n=0;n<4;++n)i[n]+=t[4*r+n]*e[r];return i}e.exports=function(t,e){return n(t.projection,n(t.view,n(t.model,[e[0],e[1],e[2],1])))}},{}],796:[function(t,e,r){"use strict";var n,i,a=t("gl-plot3d").createCamera,o=t("gl-plot3d").createScene,s=t("webgl-context"),l=t("has-passive-events"),c=t("../../registry"),u=t("../../lib"),h=t("../../plots/cartesian/axes"),f=t("../../components/fx"),p=t("../../lib/str2rgbarray"),d=t("../../lib/show_no_webgl_msg"),g=t("./project"),v=t("./layout/convert"),m=t("./layout/spikes"),y=t("./layout/tick_marks");function x(t,e,r,a,c){if(!function(t,e,r,a,l){var c={canvas:a,gl:l,container:t.container,axes:t.axesOptions,spikes:t.spikeOptions,pickRadius:10,snapToData:!0,autoScale:!0,autoBounds:!1,camera:e,pixelRatio:r};if(t.staticMode){if(!(i||(n=document.createElement("canvas"),i=s({canvas:n,preserveDrawingBuffer:!0,premultipliedAlpha:!0,antialias:!0}))))throw new Error("error creating static canvas/context for image server");c.pixelRatio=t.pixelRatio,c.gl=i,c.canvas=n}try{t.glplot=o(c)}catch(t){return!1}return!0}(t,e,r,a,c))return d(t);var p=t.graphDiv,v=function(t){if(!1!==t.fullSceneLayout.dragmode){var e={};e[t.id+".camera"]=A(t.camera),t.saveCamera(p.layout),t.graphDiv.emit("plotly_relayout",e)}};return t.glplot.canvas.addEventListener("mouseup",function(){v(t)}),t.glplot.canvas.addEventListener("wheel",function(){p._context._scrollZoom.gl3d&&v(t)},!!l&&{passive:!1}),t.staticMode||t.glplot.canvas.addEventListener("webglcontextlost",function(e){p&&p.emit&&p.emit("plotly_webglcontextlost",{event:e,layer:t.id})},!1),t.camera||t.initializeGLCamera(),t.glplot.camera=t.camera,t.glplot.oncontextloss=function(){t.recoverContext()},t.glplot.onrender=function(t){var e,r=t.svgContainer,n=t.container.getBoundingClientRect(),i=n.width,a=n.height;r.setAttributeNS(null,"viewBox","0 0 "+i+" "+a),r.setAttributeNS(null,"width",i),r.setAttributeNS(null,"height",a),y(t),t.glplot.axes.update(t.axesOptions);for(var o,s=Object.keys(t.traces),l=null,c=t.glplot.selection,p=0;p<s.length;++p)"skip"!==(e=t.traces[s[p]]).data.hoverinfo&&e.handlePick(c)&&(l=e),e.setContourLevels&&e.setContourLevels();function d(e,r){var n=t.fullSceneLayout[e];return h.tickText(n,n.d2l(r),"hover").text}if(null!==l){var v=g(t.glplot.cameraParams,c.dataCoordinate);e=l.data;var m,x=c.index,b={xLabel:d("xaxis",c.traceCoordinate[0]),yLabel:d("yaxis",c.traceCoordinate[1]),zLabel:d("zaxis",c.traceCoordinate[2])},_=f.castHoverinfo(e,t.fullLayout,x),w=(_||"").split("+"),k=_&&"all"===_;e.hovertemplate||k||(-1===w.indexOf("x")&&(b.xLabel=void 0),-1===w.indexOf("y")&&(b.yLabel=void 0),-1===w.indexOf("z")&&(b.zLabel=void 0),-1===w.indexOf("text")&&(c.textLabel=void 0),-1===w.indexOf("name")&&(l.name=void 0));var A=[];"cone"===e.type||"streamtube"===e.type?(b.uLabel=d("xaxis",c.traceCoordinate[3]),(k||-1!==w.indexOf("u"))&&A.push("u: "+b.uLabel),b.vLabel=d("yaxis",c.traceCoordinate[4]),(k||-1!==w.indexOf("v"))&&A.push("v: "+b.vLabel),b.wLabel=d("zaxis",c.traceCoordinate[5]),(k||-1!==w.indexOf("w"))&&A.push("w: "+b.wLabel),b.normLabel=c.traceCoordinate[6].toPrecision(3),(k||-1!==w.indexOf("norm"))&&A.push("norm: "+b.normLabel),"streamtube"===e.type&&(b.divergenceLabel=c.traceCoordinate[7].toPrecision(3),(k||-1!==w.indexOf("divergence"))&&A.push("divergence: "+b.divergenceLabel)),c.textLabel&&A.push(c.textLabel),m=A.join("<br>")):"isosurface"===e.type?(b.valueLabel=h.tickText(t.mockAxis,t.mockAxis.d2l(c.traceCoordinate[3]),"hover").text,A.push("value: "+b.valueLabel),c.textLabel&&A.push(c.textLabel),m=A.join("<br>")):m=c.textLabel;var M={x:c.traceCoordinate[0],y:c.traceCoordinate[1],z:c.traceCoordinate[2],data:e._input,fullData:e,curveNumber:e.index,pointNumber:x};f.appendArrayPointValue(M,e,x),e._module.eventData&&(M=e._module.eventData(M,c,e,{},x));var T={points:[M]};t.fullSceneLayout.hovermode&&f.loneHover({trace:e,x:(.5+.5*v[0]/v[3])*i,y:(.5-.5*v[1]/v[3])*a,xLabel:b.xLabel,yLabel:b.yLabel,zLabel:b.zLabel,text:m,name:l.name,color:f.castHoverOption(e,x,"bgcolor")||l.color,borderColor:f.castHoverOption(e,x,"bordercolor"),fontFamily:f.castHoverOption(e,x,"font.family"),fontSize:f.castHoverOption(e,x,"font.size"),fontColor:f.castHoverOption(e,x,"font.color"),hovertemplate:u.castOption(e,x,"hovertemplate"),hovertemplateLabels:u.extendFlat({},M,b),eventData:[M]},{container:r,gd:t.graphDiv}),c.buttons&&c.distance<5?t.graphDiv.emit("plotly_click",T):t.graphDiv.emit("plotly_hover",T),o=T}else f.loneUnhover(r),t.graphDiv.emit("plotly_unhover",o);t.drawAnnotations(t)}.bind(null,t),t.traces={},t.make4thDimension(),!0}function b(t,e){var r=document.createElement("div"),n=t.container;this.graphDiv=t.graphDiv;var i=document.createElementNS("http://www.w3.org/2000/svg","svg");i.style.position="absolute",i.style.top=i.style.left="0px",i.style.width=i.style.height="100%",i.style["z-index"]=20,i.style["pointer-events"]="none",r.appendChild(i),this.svgContainer=i,r.id=t.id,r.style.position="absolute",r.style.top=r.style.left="0px",r.style.width=r.style.height="100%",n.appendChild(r),this.fullLayout=e,this.id=t.id||"scene",this.fullSceneLayout=e[this.id],this.plotArgs=[[],{},{}],this.axesOptions=v(e,e[this.id]),this.spikeOptions=m(e[this.id]),this.container=r,this.staticMode=!!t.staticPlot,this.pixelRatio=this.pixelRatio||t.plotGlPixelRatio||2,this.dataScale=[1,1,1],this.contourLevels=[[],[],[]],this.convertAnnotations=c.getComponentMethod("annotations3d","convert"),this.drawAnnotations=c.getComponentMethod("annotations3d","draw"),x(this,e.scene.camera,this.pixelRatio)}var _=b.prototype;_.initializeGLCamera=function(){var t=this.fullSceneLayout.camera,e="orthographic"===t.projection.type;this.camera=a(this.container,{center:[t.center.x,t.center.y,t.center.z],eye:[t.eye.x,t.eye.y,t.eye.z],up:[t.up.x,t.up.y,t.up.z],_ortho:e,zoomMin:.01,zoomMax:100,mode:"orbit"})},_.recoverContext=function(){var t=this,e=this.glplot.gl,r=this.glplot.canvas,n=this.glplot.camera,i=this.glplot.pixelRatio;this.glplot.dispose(),requestAnimationFrame(function a(){e.isContextLost()?requestAnimationFrame(a):x(t,n,i,r,e)?t.plot.apply(t,t.plotArgs):u.error("Catastrophic and unrecoverable WebGL error. Context lost.")})};var w=["xaxis","yaxis","zaxis"];function k(t,e,r){for(var n=t.fullSceneLayout,i=0;i<3;i++){var a=w[i],o=a.charAt(0),s=n[a],l=e[o],c=e[o+"calendar"],h=e["_"+o+"length"];if(u.isArrayOrTypedArray(l))for(var f,p=0;p<(h||l.length);p++)if(u.isArrayOrTypedArray(l[p]))for(var d=0;d<l[p].length;++d)f=s.d2l(l[p][d],0,c),!isNaN(f)&&isFinite(f)&&(r[0][i]=Math.min(r[0][i],f),r[1][i]=Math.max(r[1][i],f));else f=s.d2l(l[p],0,c),!isNaN(f)&&isFinite(f)&&(r[0][i]=Math.min(r[0][i],f),r[1][i]=Math.max(r[1][i],f));else r[0][i]=Math.min(r[0][i],0),r[1][i]=Math.max(r[1][i],h-1)}}function A(t){return{up:{x:t.up[0],y:t.up[1],z:t.up[2]},center:{x:t.center[0],y:t.center[1],z:t.center[2]},eye:{x:t.eye[0],y:t.eye[1],z:t.eye[2]},projection:{type:!0===t._ortho?"orthographic":"perspective"}}}_.plot=function(t,e,r){if(this.plotArgs=[t,e,r],!this.glplot.contextLost){var n,i,a,o,s,l,c=e[this.id],u=r[this.id];c.bgcolor?this.glplot.clearColor=p(c.bgcolor):this.glplot.clearColor=[0,0,0,0],this.glplot.snapToData=!0,this.fullLayout=e,this.fullSceneLayout=c,this.glplotLayout=c,this.axesOptions.merge(e,c),this.spikeOptions.merge(c),this.setCamera(c.camera),this.updateFx(c.dragmode,c.hovermode),this.camera.enableWheel=this.graphDiv._context._scrollZoom.gl3d,this.glplot.update({}),this.setConvert(s),t?Array.isArray(t)||(t=[t]):t=[];var h=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]];for(a=0;a<t.length;++a)!0===(n=t[a]).visible&&k(this,n,h);!function(t,e){for(var r=t.fullSceneLayout,n=r.annotations||[],i=0;i<3;i++)for(var a=w[i],o=a.charAt(0),s=r[a],l=0;l<n.length;l++){var c=n[l];if(c.visible){var u=s.r2l(c[o]);!isNaN(u)&&isFinite(u)&&(e[0][i]=Math.min(e[0][i],u),e[1][i]=Math.max(e[1][i],u))}}}(this,h);var f=[1,1,1];for(o=0;o<3;++o)h[1][o]===h[0][o]?f[o]=1:f[o]=1/(h[1][o]-h[0][o]);for(this.dataScale=f,this.convertAnnotations(this),a=0;a<t.length;++a)!0===(n=t[a]).visible&&((i=this.traces[n.uid])?i.data.type===n.type?i.update(n):(i.dispose(),i=n._module.plot(this,n),this.traces[n.uid]=i):(i=n._module.plot(this,n),this.traces[n.uid]=i),i.name=n.name);var d=Object.keys(this.traces);t:for(a=0;a<d.length;++a){for(o=0;o<t.length;++o)if(t[o].uid===d[a]&&!0===t[o].visible)continue t;(i=this.traces[d[a]]).dispose(),delete this.traces[d[a]]}this.glplot.objects.sort(function(t,e){return t._trace.data.index-e._trace.data.index});var g=[[0,0,0],[0,0,0]],v=[],m={};for(a=0;a<3;++a){if((l=(s=c[w[a]]).type)in m?(m[l].acc*=f[a],m[l].count+=1):m[l]={acc:f[a],count:1},s.autorange){g[0][a]=1/0,g[1][a]=-1/0;var y=this.glplot.objects,x=this.fullSceneLayout.annotations||[],b=s._name.charAt(0);for(o=0;o<y.length;o++){var _=y[o],A=_.bounds,M=_._trace.data._pad||0;"ErrorBars"===_.constructor.name&&s._lowerLogErrorBound?g[0][a]=Math.min(g[0][a],s._lowerLogErrorBound):g[0][a]=Math.min(g[0][a],A[0][a]/f[a]-M),g[1][a]=Math.max(g[1][a],A[1][a]/f[a]+M)}for(o=0;o<x.length;o++){var T=x[o];if(T.visible){var S=s.r2l(T[b]);g[0][a]=Math.min(g[0][a],S),g[1][a]=Math.max(g[1][a],S)}}if("rangemode"in s&&"tozero"===s.rangemode&&(g[0][a]=Math.min(g[0][a],0),g[1][a]=Math.max(g[1][a],0)),g[0][a]>g[1][a])g[0][a]=-1,g[1][a]=1;else{var E=g[1][a]-g[0][a];g[0][a]-=E/32,g[1][a]+=E/32}if("reversed"===s.autorange){var C=g[0][a];g[0][a]=g[1][a],g[1][a]=C}}else{var L=s.range;g[0][a]=s.r2l(L[0]),g[1][a]=s.r2l(L[1])}g[0][a]===g[1][a]&&(g[0][a]-=1,g[1][a]+=1),v[a]=g[1][a]-g[0][a],this.glplot.bounds[0][a]=g[0][a]*f[a],this.glplot.bounds[1][a]=g[1][a]*f[a]}var z=[1,1,1];for(a=0;a<3;++a){var O=m[l=(s=c[w[a]]).type];z[a]=Math.pow(O.acc,1/O.count)/f[a]}var I;if("auto"===c.aspectmode)I=Math.max.apply(null,z)/Math.min.apply(null,z)<=4?z:[1,1,1];else if("cube"===c.aspectmode)I=[1,1,1];else if("data"===c.aspectmode)I=z;else{if("manual"!==c.aspectmode)throw new Error("scene.js aspectRatio was not one of the enumerated types");var D=c.aspectratio;I=[D.x,D.y,D.z]}c.aspectratio.x=u.aspectratio.x=I[0],c.aspectratio.y=u.aspectratio.y=I[1],c.aspectratio.z=u.aspectratio.z=I[2],this.glplot.aspect=I;var P=c.domain||null,R=e._size||null;if(P&&R){var F=this.container.style;F.position="absolute",F.left=R.l+P.x[0]*R.w+"px",F.top=R.t+(1-P.y[1])*R.h+"px",F.width=R.w*(P.x[1]-P.x[0])+"px",F.height=R.h*(P.y[1]-P.y[0])+"px"}this.glplot.redraw()}},_.destroy=function(){this.glplot&&(this.camera.mouseListener.enabled=!1,this.container.removeEventListener("wheel",this.camera.wheelListener),this.camera=this.glplot.camera=null,this.glplot.dispose(),this.container.parentNode.removeChild(this.container),this.glplot=null)},_.getCamera=function(){return this.glplot.camera.view.recalcMatrix(this.camera.view.lastT()),A(this.glplot.camera)},_.setCamera=function(t){var e;this.glplot.camera.lookAt.apply(this,[[(e=t).eye.x,e.eye.y,e.eye.z],[e.center.x,e.center.y,e.center.z],[e.up.x,e.up.y,e.up.z]]);var r="orthographic"===t.projection.type;if(r!==this.glplot.camera._ortho){this.glplot.redraw();var n=this.glplot.pixelRatio,i=this.glplot.clearColor;this.glplot.gl.clearColor(i[0],i[1],i[2],i[3]),this.glplot.gl.clear(this.glplot.gl.DEPTH_BUFFER_BIT|this.glplot.gl.COLOR_BUFFER_BIT),this.glplot.dispose(),x(this,t,n),this.glplot.camera._ortho=r}},_.saveCamera=function(t){var e=this.fullLayout,r=this.getCamera(),n=u.nestedProperty(t,this.id+".camera"),i=n.get(),a=!1;function o(t,e,r,n){var i=["up","center","eye"],a=["x","y","z"];return e[i[r]]&&t[i[r]][a[n]]===e[i[r]][a[n]]}if(void 0===i)a=!0;else{for(var s=0;s<3;s++)for(var l=0;l<3;l++)if(!o(r,i,s,l)){a=!0;break}(!i.projection||r.projection&&r.projection.type!==i.projection.type)&&(a=!0)}if(a){var h={};h[this.id+".camera"]=i,c.call("_storeDirectGUIEdit",t,e._preGUI,h),n.set(r),u.nestedProperty(e,this.id+".camera").set(r)}return a},_.updateFx=function(t,e){var r=this.camera;if(r)if("orbit"===t)r.mode="orbit",r.keyBindingMode="rotate";else if("turntable"===t){r.up=[0,0,1],r.mode="turntable",r.keyBindingMode="rotate";var n=this.graphDiv,i=n._fullLayout,a=this.fullSceneLayout.camera,o=a.up.x,s=a.up.y,l=a.up.z;if(l/Math.sqrt(o*o+s*s+l*l)>.999)return;var h=this.id+".camera.up",f={x:0,y:0,z:1},p={};p[h]=f;var d=n.layout;c.call("_storeDirectGUIEdit",d,i._preGUI,p),a.up=f,u.nestedProperty(d,h).set(f)}else r.keyBindingMode=t;this.fullSceneLayout.hovermode=e},_.toImage=function(t){t||(t="png"),this.staticMode&&this.container.appendChild(n),this.glplot.redraw();var e=this.glplot.gl,r=e.drawingBufferWidth,i=e.drawingBufferHeight;e.bindFramebuffer(e.FRAMEBUFFER,null);var a=new Uint8Array(r*i*4);e.readPixels(0,0,r,i,e.RGBA,e.UNSIGNED_BYTE,a);for(var o=0,s=i-1;o<s;++o,--s)for(var l=0;l<r;++l)for(var c=0;c<4;++c){var u=a[4*(r*o+l)+c];a[4*(r*o+l)+c]=a[4*(r*s+l)+c],a[4*(r*s+l)+c]=u}var h=document.createElement("canvas");h.width=r,h.height=i;var f,p=h.getContext("2d"),d=p.createImageData(r,i);switch(d.data.set(a),p.putImageData(d,0,0),t){case"jpeg":f=h.toDataURL("image/jpeg");break;case"webp":f=h.toDataURL("image/webp");break;default:f=h.toDataURL("image/png")}return this.staticMode&&this.container.removeChild(n),f},_.setConvert=function(){for(var t=0;t<3;t++){var e=this.fullSceneLayout[w[t]];h.setConvert(e,this.fullLayout),e.setScale=u.noop}},_.make4thDimension=function(){var t=this.graphDiv._fullLayout;this.mockAxis={type:"linear",showexponent:"all",exponentformat:"B"},h.setConvert(this.mockAxis,t)},e.exports=b},{"../../components/fx":613,"../../lib":697,"../../lib/show_no_webgl_msg":718,"../../lib/str2rgbarray":720,"../../plots/cartesian/axes":745,"../../registry":826,"./layout/convert":790,"./layout/spikes":793,"./layout/tick_marks":794,"./project":795,"gl-plot3d":283,"has-passive-events":400,"webgl-context":537}],797:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){n=n||t.length;for(var i=new Array(n),a=0;a<n;a++)i[a]=[t[a],e[a],r[a]];return i}},{}],798:[function(t,e,r){"use strict";var n=t("./font_attributes"),i=t("./animation_attributes"),a=t("../components/color/attributes"),o=t("../components/colorscale/layout_attributes"),s=t("./pad_attributes"),l=t("../lib/extend").extendFlat,c=n({editType:"calc"});c.family.dflt='"Open Sans", verdana, arial, sans-serif',c.size.dflt=12,c.color.dflt=a.defaultLine,e.exports={font:c,title:{text:{valType:"string",editType:"layoutstyle"},font:n({editType:"layoutstyle"}),xref:{valType:"enumerated",dflt:"container",values:["container","paper"],editType:"layoutstyle"},yref:{valType:"enumerated",dflt:"container",values:["container","paper"],editType:"layoutstyle"},x:{valType:"number",min:0,max:1,dflt:.5,editType:"layoutstyle"},y:{valType:"number",min:0,max:1,dflt:"auto",editType:"layoutstyle"},xanchor:{valType:"enumerated",dflt:"auto",values:["auto","left","center","right"],editType:"layoutstyle"},yanchor:{valType:"enumerated",dflt:"auto",values:["auto","top","middle","bottom"],editType:"layoutstyle"},pad:l(s({editType:"layoutstyle"}),{}),editType:"layoutstyle"},autosize:{valType:"boolean",dflt:!1,editType:"none"},width:{valType:"number",min:10,dflt:700,editType:"plot"},height:{valType:"number",min:10,dflt:450,editType:"plot"},margin:{l:{valType:"number",min:0,dflt:80,editType:"plot"},r:{valType:"number",min:0,dflt:80,editType:"plot"},t:{valType:"number",min:0,dflt:100,editType:"plot"},b:{valType:"number",min:0,dflt:80,editType:"plot"},pad:{valType:"number",min:0,dflt:0,editType:"plot"},autoexpand:{valType:"boolean",dflt:!0,editType:"plot"},editType:"plot"},paper_bgcolor:{valType:"color",dflt:a.background,editType:"plot"},plot_bgcolor:{valType:"color",dflt:a.background,editType:"layoutstyle"},separators:{valType:"string",editType:"plot"},hidesources:{valType:"boolean",dflt:!1,editType:"plot"},showlegend:{valType:"boolean",editType:"legend"},colorway:{valType:"colorlist",dflt:a.defaults,editType:"calc"},colorscale:o,datarevision:{valType:"any",editType:"calc"},uirevision:{valType:"any",editType:"none"},editrevision:{valType:"any",editType:"none"},selectionrevision:{valType:"any",editType:"none"},template:{valType:"any",editType:"calc"},modebar:{orientation:{valType:"enumerated",values:["v","h"],dflt:"h",editType:"modebar"},bgcolor:{valType:"color",editType:"modebar"},color:{valType:"color",editType:"modebar"},activecolor:{valType:"color",editType:"modebar"},uirevision:{valType:"any",editType:"none"},editType:"modebar"},meta:{valType:"data_array",editType:"plot"},transition:l({},i.transition,{editType:"none"}),_deprecated:{title:{valType:"string",editType:"layoutstyle"},titlefont:n({editType:"layoutstyle"})}}},{"../components/color/attributes":573,"../components/colorscale/layout_attributes":587,"../lib/extend":687,"./animation_attributes":740,"./font_attributes":771,"./pad_attributes":806}],799:[function(t,e,r){"use strict";e.exports={requiredVersion:"0.45.0",styleUrlPrefix:"mapbox://styles/mapbox/",styleUrlSuffix:"v9",controlContainerClassName:"mapboxgl-control-container",wrongVersionErrorMsg:["Your custom plotly.js bundle is not using the correct mapbox-gl version","Please install mapbox-gl@0.45.0."].join("\n"),noAccessTokenErrorMsg:["Missing Mapbox access token.","Mapbox trace type require a Mapbox access token to be registered.","For example:","  Plotly.plot(gd, data, layout, { mapboxAccessToken: 'my-access-token' });","More info here: https://www.mapbox.com/help/define-access-token/"].join("\n"),mapOnErrorMsg:"Mapbox error.",styleRules:{map:"overflow:hidden;position:relative;","missing-css":"display:none"}}},{}],800:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e){var r=t.split(" "),i=r[0],a=r[1],o=n.isArrayOrTypedArray(e)?n.mean(e):e,s=.5+o/100,l=1.5+o/100,c=["",""],u=[0,0];switch(i){case"top":c[0]="top",u[1]=-l;break;case"bottom":c[0]="bottom",u[1]=l}switch(a){case"left":c[1]="right",u[0]=-s;break;case"right":c[1]="left",u[0]=s}return{anchor:c[0]&&c[1]?c.join("-"):c[0]?c[0]:c[1]?c[1]:"center",offset:u}}},{"../../lib":697}],801:[function(t,e,r){"use strict";var n=t("mapbox-gl"),i=t("../../lib"),a=t("../../plots/get_data").getSubplotCalcData,o=t("../../constants/xmlns_namespaces"),s=t("./mapbox"),l=t("./constants");for(var c in l.styleRules)i.addStyleRule(".mapboxgl-"+c,l.styleRules[c]);r.name="mapbox",r.attr="subplot",r.idRoot="mapbox",r.idRegex=r.attrRegex=i.counterRegex("mapbox"),r.attributes={subplot:{valType:"subplotid",dflt:"mapbox",editType:"calc"}},r.layoutAttributes=t("./layout_attributes"),r.supplyLayoutDefaults=t("./layout_defaults"),r.plot=function(t){var e=t._fullLayout,r=t.calcdata,o=e._subplots.mapbox;if(n.version!==l.requiredVersion)throw new Error(l.wrongVersionErrorMsg);var c=function(t,e){var r=t._fullLayout;if(""===t._context.mapboxAccessToken)return"";for(var n=0;n<e.length;n++){var i=r[e[n]];if(i.accesstoken)return i.accesstoken}throw new Error(l.noAccessTokenErrorMsg)}(t,o);n.accessToken=c;for(var u=0;u<o.length;u++){var h=o[u],f=a(r,"mapbox",h),p=e[h],d=p._subplot;d||(d=s({gd:t,container:e._glcontainer.node(),id:h,fullLayout:e,staticPlot:t._context.staticPlot}),e[h]._subplot=d),d.viewInitial||(d.viewInitial={center:i.extendFlat({},p.center),zoom:p.zoom,bearing:p.bearing,pitch:p.pitch}),d.plot(f,e,t._promises)}},r.clean=function(t,e,r,n){for(var i=n._subplots.mapbox||[],a=0;a<i.length;a++){var o=i[a];!e[o]&&n[o]._subplot&&n[o]._subplot.destroy()}},r.toSVG=function(t){for(var e=t._fullLayout,r=e._subplots.mapbox,n=e._size,i=0;i<r.length;i++){var a=e[r[i]],s=a.domain,l=a._subplot,c=l.toImage("png");e._glimages.append("svg:image").attr({xmlns:o.svg,"xlink:href":c,x:n.l+n.w*s.x[0],y:n.t+n.h*(1-s.y[1]),width:n.w*(s.x[1]-s.x[0]),height:n.h*(s.y[1]-s.y[0]),preserveAspectRatio:"none"}),l.destroy()}},r.updateFx=function(t){for(var e=t._fullLayout,r=e._subplots.mapbox,n=0;n<r.length;n++){e[r[n]]._subplot.updateFx(e)}}},{"../../constants/xmlns_namespaces":675,"../../lib":697,"../../plots/get_data":781,"./constants":799,"./layout_attributes":803,"./layout_defaults":804,"./mapbox":805,"mapbox-gl":415}],802:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./convert_text_opts");function a(t,e){this.mapbox=t,this.map=t.map,this.uid=t.uid+"-layer"+e,this.idSource=this.uid+"-source",this.idLayer=this.uid+"-layer",this.sourceType=null,this.source=null,this.layerType=null,this.below=null,this.visible=!1}var o=a.prototype;function s(t){var e=t.source;return t.visible&&(n.isPlainObject(e)||"string"==typeof e&&e.length>0)}function l(t){var e={},r={};switch(t.type){case"circle":n.extendFlat(r,{"circle-radius":t.circle.radius,"circle-color":t.color,"circle-opacity":t.opacity});break;case"line":n.extendFlat(r,{"line-width":t.line.width,"line-color":t.color,"line-opacity":t.opacity,"line-dasharray":t.line.dash});break;case"fill":n.extendFlat(r,{"fill-color":t.color,"fill-outline-color":t.fill.outlinecolor,"fill-opacity":t.opacity});break;case"symbol":var a=t.symbol,o=i(a.textposition,a.iconsize);n.extendFlat(e,{"icon-image":a.icon+"-15","icon-size":a.iconsize/10,"text-field":a.text,"text-size":a.textfont.size,"text-anchor":o.anchor,"text-offset":o.offset,"symbol-placement":a.placement}),n.extendFlat(r,{"icon-color":t.color,"text-color":a.textfont.color,"text-opacity":t.opacity})}return{layout:e,paint:r}}o.update=function(t){this.visible?this.needsNewSource(t)?(this.removeLayer(),this.updateSource(t),this.updateLayer(t)):this.needsNewLayer(t)?this.updateLayer(t):this.updateStyle(t):(this.updateSource(t),this.updateLayer(t)),this.visible=s(t)},o.needsNewSource=function(t){return this.sourceType!==t.sourcetype||this.source!==t.source||this.layerType!==t.type},o.needsNewLayer=function(t){return this.layerType!==t.type||this.below!==t.below},o.updateSource=function(t){var e=this.map;if(e.getSource(this.idSource)&&e.removeSource(this.idSource),this.sourceType=t.sourcetype,this.source=t.source,s(t)){var r=function(t){var e,r=t.sourcetype,n=t.source,i={type:r};"geojson"===r?e="data":"vector"===r&&(e="string"==typeof n?"url":"tiles");return i[e]=n,i}(t);e.addSource(this.idSource,r)}},o.updateLayer=function(t){var e=this.map,r=l(t);this.removeLayer(),this.layerType=t.type,s(t)&&e.addLayer({id:this.idLayer,source:this.idSource,"source-layer":t.sourcelayer||"",type:t.type,minzoom:t.minzoom,maxzoom:t.maxzoom,layout:r.layout,paint:r.paint},t.below)},o.updateStyle=function(t){if(s(t)){var e=l(t);this.mapbox.setOptions(this.idLayer,"setLayoutProperty",e.layout),this.mapbox.setOptions(this.idLayer,"setPaintProperty",e.paint)}},o.removeLayer=function(){var t=this.map;t.getLayer(this.idLayer)&&t.removeLayer(this.idLayer)},o.dispose=function(){var t=this.map;t.removeLayer(this.idLayer),t.removeSource(this.idSource)},e.exports=function(t,e,r){var n=new a(t,e);return n.update(r),n}},{"../../lib":697,"./convert_text_opts":800}],803:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/color").defaultLine,a=t("../domain").attributes,o=t("../font_attributes"),s=t("../../traces/scatter/attributes").textposition,l=t("../../plot_api/edit_types").overrideAll,c=t("../../plot_api/plot_template").templatedArray,u=o({});u.family.dflt="Open Sans Regular, Arial Unicode MS Regular",(e.exports=l({_arrayAttrRegexps:[n.counterRegex("mapbox",".layers",!0)],domain:a({name:"mapbox"}),accesstoken:{valType:"string",noBlank:!0,strict:!0},style:{valType:"any",values:["basic","streets","outdoors","light","dark","satellite","satellite-streets"],dflt:"basic"},center:{lon:{valType:"number",dflt:0},lat:{valType:"number",dflt:0}},zoom:{valType:"number",dflt:1},bearing:{valType:"number",dflt:0},pitch:{valType:"number",dflt:0},layers:c("layer",{visible:{valType:"boolean",dflt:!0},sourcetype:{valType:"enumerated",values:["geojson","vector"],dflt:"geojson"},source:{valType:"any"},sourcelayer:{valType:"string",dflt:""},type:{valType:"enumerated",values:["circle","line","fill","symbol"],dflt:"circle"},below:{valType:"string",dflt:""},color:{valType:"color",dflt:i},opacity:{valType:"number",min:0,max:1,dflt:1},minzoom:{valType:"number",min:0,max:24,dflt:0},maxzoom:{valType:"number",min:0,max:24,dflt:24},circle:{radius:{valType:"number",dflt:15}},line:{width:{valType:"number",dflt:2},dash:{valType:"data_array"}},fill:{outlinecolor:{valType:"color",dflt:i}},symbol:{icon:{valType:"string",dflt:"marker"},iconsize:{valType:"number",dflt:10},text:{valType:"string",dflt:""},placement:{valType:"enumerated",values:["point","line","line-center"],dflt:"point"},textfont:u,textposition:n.extendFlat({},s,{arrayOk:!1})}})},"plot","from-root")).uirevision={valType:"any",editType:"none"}},{"../../components/color":574,"../../lib":697,"../../plot_api/edit_types":728,"../../plot_api/plot_template":735,"../../traces/scatter/attributes":1048,"../domain":770,"../font_attributes":771}],804:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../subplot_defaults"),a=t("../array_container_defaults"),o=t("./layout_attributes");function s(t,e,r,n){r("accesstoken",n.accessToken),r("style"),r("center.lon"),r("center.lat"),r("zoom"),r("bearing"),r("pitch"),a(t,e,{name:"layers",handleItemDefaults:l}),e._input=t}function l(t,e){function r(r,i){return n.coerce(t,e,o.layers,r,i)}if(r("visible")){var i=r("sourcetype");r("source"),"vector"===i&&r("sourcelayer");var a=r("type");r("below"),r("color"),r("opacity"),r("minzoom"),r("maxzoom"),"circle"===a&&r("circle.radius"),"line"===a&&(r("line.width"),r("line.dash")),"fill"===a&&r("fill.outlinecolor"),"symbol"===a&&(r("symbol.icon"),r("symbol.iconsize"),r("symbol.text"),n.coerceFont(r,"symbol.textfont"),r("symbol.textposition"),r("symbol.placement"))}}e.exports=function(t,e,r){i(t,e,r,{type:"mapbox",attributes:o,handleDefaults:s,partition:"y",accessToken:e._mapboxAccessToken})}},{"../../lib":697,"../array_container_defaults":741,"../subplot_defaults":821,"./layout_attributes":803}],805:[function(t,e,r){"use strict";var n=t("mapbox-gl"),i=t("../../components/fx"),a=t("../../lib"),o=t("../../registry"),s=t("../../components/dragelement"),l=t("../cartesian/select").prepSelect,c=t("../cartesian/select").selectOnClick,u=t("./constants"),h=t("./layout_attributes"),f=t("./layers");function p(t){this.id=t.id,this.gd=t.gd,this.container=t.container,this.isStatic=t.staticPlot;var e=t.fullLayout;this.uid=e._uid+"-"+this.id,this.div=null,this.xaxis=null,this.yaxis=null,this.createFramework(e),this.map=null,this.accessToken=null,this.styleObj=null,this.traceHash={},this.layerList=[]}var d=p.prototype;function g(t){var e=h.style.values,r=h.style.dflt,n={};return a.isPlainObject(t)?(n.id=t.id,n.style=t):"string"==typeof t?(n.id=t,n.style=-1!==e.indexOf(t)?v(t):t):(n.id=r,n.style=v(r)),n.transition={duration:0,delay:0},n}function v(t){return u.styleUrlPrefix+t+"-"+u.styleUrlSuffix}function m(t){return[t.lon,t.lat]}e.exports=function(t){return new p(t)},d.plot=function(t,e,r){var n,i=this,a=e[i.id];i.map&&a.accesstoken!==i.accessToken&&(i.map.remove(),i.map=null,i.styleObj=null,i.traceHash=[],i.layerList={}),n=i.map?new Promise(function(r,n){i.updateMap(t,e,r,n)}):new Promise(function(r,n){i.createMap(t,e,r,n)}),r.push(n)},d.createMap=function(t,e,r,a){var s=this,l=s.gd,h=e[s.id],f=s.styleObj=g(h.style);s.accessToken=h.accesstoken;var p=s.map=new n.Map({container:s.div,style:f.style,center:m(h.center),zoom:h.zoom,bearing:h.bearing,pitch:h.pitch,interactive:!s.isStatic,preserveDrawingBuffer:s.isStatic,doubleClickZoom:!1,boxZoom:!1}),d=u.controlContainerClassName,v=s.div.getElementsByClassName(d)[0];if(s.div.removeChild(v),p._canvas.style.left="0px",p._canvas.style.top="0px",s.rejectOnError(a),p.once("load",function(){s.updateData(t),s.updateLayout(e),s.resolveOnRender(r)}),!s.isStatic){var y=!1;p.on("moveend",function(t){if(s.map){if(t.originalEvent||y){var e=l._fullLayout[s.id];o.call("_storeDirectGUIEdit",l.layout,l._fullLayout._preGUI,s.getViewEdits(e));var r=s.getView();e._input.center=e.center=r.center,e._input.zoom=e.zoom=r.zoom,e._input.bearing=e.bearing=r.bearing,e._input.pitch=e.pitch=r.pitch,l.emit("plotly_relayout",s.getViewEdits(r))}y=!1}}),p.on("wheel",function(){y=!0}),p.on("mousemove",function(t){var e=s.div.getBoundingClientRect();t.clientX=t.point.x+e.left,t.clientY=t.point.y+e.top,t.target.getBoundingClientRect=function(){return e},s.xaxis.p2c=function(){return t.lngLat.lng},s.yaxis.p2c=function(){return t.lngLat.lat},i.hover(l,t,s.id)}),p.on("dragstart",x),p.on("zoomstart",x),p.on("dblclick",function(){var t=l._fullLayout[s.id];o.call("_storeDirectGUIEdit",l.layout,l._fullLayout._preGUI,s.getViewEdits(t));var e=s.viewInitial;p.setCenter(m(e.center)),p.setZoom(e.zoom),p.setBearing(e.bearing),p.setPitch(e.pitch);var r=s.getView();t._input.center=t.center=r.center,t._input.zoom=t.zoom=r.zoom,t._input.bearing=t.bearing=r.bearing,t._input.pitch=t.pitch=r.pitch,l.emit("plotly_doubleclick",null),l.emit("plotly_relayout",s.getViewEdits(r))}),s.clearSelect=function(){l._fullLayout._zoomlayer.selectAll(".select-outline").remove()},s.onClickInPanFn=function(t){return function(e){var r=l._fullLayout.clickmode;r.indexOf("select")>-1&&c(e.originalEvent,l,[s.xaxis],[s.yaxis],s.id,t),r.indexOf("event")>-1&&i.click(l,e.originalEvent)}}}function x(){i.loneUnhover(e._toppaper)}},d.updateMap=function(t,e,r,n){var i=this,a=i.map,o=e[this.id];i.rejectOnError(n);var s=g(o.style);i.styleObj.id!==s.id?(i.styleObj=s,a.setStyle(s.style),a.once("styledata",function(){i.traceHash={},i.updateData(t),i.updateLayout(e),i.resolveOnRender(r)})):(i.updateData(t),i.updateLayout(e),i.resolveOnRender(r)),this.gd._context._scrollZoom.mapbox?a.scrollZoom.enable():a.scrollZoom.disable()},d.updateData=function(t){var e,r,n,i,a=this.traceHash;for(n=0;n<t.length;n++){var o=t[n];(e=a[(r=o[0].trace).uid])?e.update(o):r._module&&(a[r.uid]=r._module.plot(this,o))}var s=Object.keys(a);t:for(n=0;n<s.length;n++){var l=s[n];for(i=0;i<t.length;i++)if(l===(r=t[i][0].trace).uid)continue t;(e=a[l]).dispose(),delete a[l]}},d.updateLayout=function(t){var e=this.map,r=t[this.id];e.setCenter(m(r.center)),e.setZoom(r.zoom),e.setBearing(r.bearing),e.setPitch(r.pitch),this.updateLayers(t),this.updateFramework(t),this.updateFx(t),this.map.resize()},d.resolveOnRender=function(t){var e=this.map;e.on("render",function r(){e.loaded()&&(e.off("render",r),setTimeout(t,0))})},d.rejectOnError=function(t){var e=this.map;function r(){t(new Error(u.mapOnErrorMsg))}e.once("error",r),e.once("style.error",r),e.once("source.error",r),e.once("tile.error",r),e.once("layer.error",r)},d.createFramework=function(t){var e=this,r=e.div=document.createElement("div");r.id=e.uid,r.style.position="absolute",e.container.appendChild(r),e.xaxis={_id:"x",c2p:function(t){return e.project(t).x}},e.yaxis={_id:"y",c2p:function(t){return e.project(t).y}},e.updateFramework(t)},d.updateFx=function(t){var e=this,r=e.map,n=e.gd;if(!e.isStatic){var i,o=t.dragmode;i="select"===o?function(t,r){(t.range={})[e.id]=[u([r.xmin,r.ymin]),u([r.xmax,r.ymax])]}:function(t,r,n){(t.lassoPoints={})[e.id]=n.filtered.map(u)};var c=e.dragOptions;e.dragOptions=a.extendDeep(c||{},{element:e.div,gd:n,plotinfo:{id:e.id,xaxis:e.xaxis,yaxis:e.yaxis,fillRangeItems:i},xaxes:[e.xaxis],yaxes:[e.yaxis],subplot:e.id}),r.off("click",e.onClickInPanHandler),"select"===o||"lasso"===o?(r.dragPan.disable(),r.on("zoomstart",e.clearSelect),e.dragOptions.prepFn=function(t,r,n){l(t,r,n,e.dragOptions,o)},s.init(e.dragOptions)):(r.dragPan.enable(),r.off("zoomstart",e.clearSelect),e.div.onmousedown=null,e.onClickInPanHandler=e.onClickInPanFn(e.dragOptions),r.on("click",e.onClickInPanHandler))}function u(t){var r=e.map.unproject(t);return[r.lng,r.lat]}},d.updateFramework=function(t){var e=t[this.id].domain,r=t._size,n=this.div.style;n.width=r.w*(e.x[1]-e.x[0])+"px",n.height=r.h*(e.y[1]-e.y[0])+"px",n.left=r.l+e.x[0]*r.w+"px",n.top=r.t+(1-e.y[1])*r.h+"px",this.xaxis._offset=r.l+e.x[0]*r.w,this.xaxis._length=r.w*(e.x[1]-e.x[0]),this.yaxis._offset=r.t+(1-e.y[1])*r.h,this.yaxis._length=r.h*(e.y[1]-e.y[0])},d.updateLayers=function(t){var e,r=t[this.id].layers,n=this.layerList;if(r.length!==n.length){for(e=0;e<n.length;e++)n[e].dispose();for(n=this.layerList=[],e=0;e<r.length;e++)n.push(f(this,e,r[e]))}else for(e=0;e<r.length;e++)n[e].update(r[e])},d.destroy=function(){this.map&&(this.map.remove(),this.map=null,this.container.removeChild(this.div))},d.toImage=function(){return this.map.stop(),this.map.getCanvas().toDataURL()},d.setOptions=function(t,e,r){for(var n in r)this.map[e](t,n,r[n])},d.project=function(t){return this.map.project(new n.LngLat(t[0],t[1]))},d.getView=function(){var t=this.map,e=t.getCenter();return{center:{lon:e.lng,lat:e.lat},zoom:t.getZoom(),bearing:t.getBearing(),pitch:t.getPitch()}},d.getViewEdits=function(t){for(var e=this.id,r=["center","zoom","bearing","pitch"],n={},i=0;i<r.length;i++){var a=r[i];n[e+"."+a]=t[a]}return n}},{"../../components/dragelement":592,"../../components/fx":613,"../../lib":697,"../../registry":826,"../cartesian/select":762,"./constants":799,"./layers":802,"./layout_attributes":803,"mapbox-gl":415}],806:[function(t,e,r){"use strict";e.exports=function(t){var e=t.editType;return{t:{valType:"number",dflt:0,editType:e},r:{valType:"number",dflt:0,editType:e},b:{valType:"number",dflt:0,editType:e},l:{valType:"number",dflt:0,editType:e},editType:e}}},{}],807:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../registry"),o=t("../plot_api/plot_schema"),s=t("../plot_api/plot_template"),l=t("../lib"),c=t("../components/color"),u=t("../constants/numerical").BADNUM,h=t("../plots/cartesian/axis_ids"),f=t("./animation_attributes"),p=t("./frame_attributes"),d=l.relinkPrivateKeys,g=l._,v=e.exports={};l.extendFlat(v,a),v.attributes=t("./attributes"),v.attributes.type.values=v.allTypes,v.fontAttrs=t("./font_attributes"),v.layoutAttributes=t("./layout_attributes"),v.fontWeight="normal";var m=v.transformsRegistry,y=t("./command");v.executeAPICommand=y.executeAPICommand,v.computeAPICommandBindings=y.computeAPICommandBindings,v.manageCommandObserver=y.manageCommandObserver,v.hasSimpleAPICommandBindings=y.hasSimpleAPICommandBindings,v.redrawText=function(t){if(!((t=l.getGraphDiv(t)).data&&t.data[0]&&t.data[0].r))return new Promise(function(e){setTimeout(function(){a.getComponentMethod("annotations","draw")(t),a.getComponentMethod("legend","draw")(t),(t.calcdata||[]).forEach(function(t){t[0]&&t[0].t&&t[0].t.cb&&t[0].t.cb()}),e(v.previousPromises(t))},300)})},v.resize=function(t){return t=l.getGraphDiv(t),new Promise(function(e,r){function n(t){var e=window.getComputedStyle(t).display;return!e||"none"===e}t&&!n(t)||r(new Error("Resize must be passed a displayed plot div element.")),t._redrawTimer&&clearTimeout(t._redrawTimer),t._redrawTimer=setTimeout(function(){if(!t.layout||t.layout.width&&t.layout.height||n(t))e(t);else{delete t.layout.width,delete t.layout.height;var r=t.changed;t.autoplay=!0,a.call("relayout",t,{autosize:!0}).then(function(){t.changed=r,e(t)})}},100)})},v.previousPromises=function(t){if((t._promises||[]).length)return Promise.all(t._promises).then(function(){t._promises=[]})},v.addLinks=function(t){if(t._context.showLink||t._context.showSources){var e=t._fullLayout,r=l.ensureSingle(e._paper,"text","js-plot-link-container",function(t){t.style({"font-family":'"Open Sans", Arial, sans-serif',"font-size":"12px",fill:c.defaultLine,"pointer-events":"all"}).each(function(){var t=n.select(this);t.append("tspan").classed("js-link-to-tool",!0),t.append("tspan").classed("js-link-spacer",!0),t.append("tspan").classed("js-sourcelinks",!0)})}),i=r.node(),a={y:e._paper.attr("height")-9};document.body.contains(i)&&i.getComputedTextLength()>=e.width-20?(a["text-anchor"]="start",a.x=5):(a["text-anchor"]="end",a.x=e._paper.attr("width")-7),r.attr(a);var o=r.select(".js-link-to-tool"),s=r.select(".js-link-spacer"),u=r.select(".js-sourcelinks");t._context.showSources&&t._context.showSources(t),t._context.showLink&&function(t,e){e.text("");var r=e.append("a").attr({"xlink:xlink:href":"#",class:"link--impt link--embedview","font-weight":"bold"}).text(t._context.linkText+" "+String.fromCharCode(187));if(t._context.sendData)r.on("click",function(){v.sendDataToCloud(t)});else{var n=window.location.pathname.split("/"),i=window.location.search;r.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+n[2].split(".")[0]+"/"+n[1]+i})}}(t,o),s.text(o.text()&&u.text()?" - ":"")}},v.sendDataToCloud=function(t){t.emit("plotly_beforeexport");var e=(window.PLOTLYENV||{}).BASE_URL||t._context.plotlyServerURL,r=n.select(t).append("div").attr("id","hiddenform").style("display","none"),i=r.append("form").attr({action:e+"/external",method:"post",target:"_blank"});return i.append("input").attr({type:"text",name:"data"}).node().value=v.graphJson(t,!1,"keepdata"),i.node().submit(),r.remove(),t.emit("plotly_afterexport"),!1};var x=["days","shortDays","months","shortMonths","periods","dateTime","date","time","decimal","thousands","grouping","currency"],b=["year","month","dayMonth","dayMonthYear"];function _(t,e){var r=t._context.locale,n=!1,i={};function o(t){for(var r=!0,a=0;a<e.length;a++){var o=e[a];i[o]||(t[o]?i[o]=t[o]:r=!1)}r&&(n=!0)}for(var s=0;s<2;s++){for(var l=t._context.locales,c=0;c<2;c++){var u=(l[r]||{}).format;if(u&&(o(u),n))break;l=a.localeRegistry}var h=r.split("-")[0];if(n||h===r)break;r=h}return n||o(a.localeRegistry.en.format),i}function w(t,e){var r={_fullLayout:e},n="x"===t._id.charAt(0),i=t._mainAxis._anchorAxis,a="",o="",s="";if(i&&(s=i._mainAxis._id,a=n?t._id+s:s+t._id),!a||!e._plots[a]){a="";for(var l=t._counterAxes,c=0;c<l.length;c++){var u=l[c],f=n?t._id+u:u+t._id;o||(o=f);var p=h.getFromId(r,u);if(s&&p.overlaying===s){a=f;break}}}return a||o}function k(t){var e=t.transforms;if(Array.isArray(e)&&e.length)for(var r=0;r<e.length;r++){var n=e[r],i=n._module||m[n.type];if(i&&i.makesData)return!0}return!1}function A(t,e,r,n){for(var i=t.transforms,a=[t],o=0;o<i.length;o++){var s=i[o],l=m[s.type];l&&l.transform&&(a=l.transform(a,{transform:s,fullTrace:t,fullData:e,layout:r,fullLayout:n,transformIndex:o}))}return a}function M(t){var e=t.margin;if(!t._size){var r=t._size={l:Math.round(e.l),r:Math.round(e.r),t:Math.round(e.t),b:Math.round(e.b),p:Math.round(e.pad)};r.w=Math.round(t.width)-r.l-r.r,r.h=Math.round(t.height)-r.t-r.b}t._pushmargin||(t._pushmargin={}),t._pushmarginIds||(t._pushmarginIds={})}function T(t,e,r){var n=!1;var i=[v.previousPromises,function(){if(t._transitionData)return t._transitioning=!1,function(t){var e=Promise.resolve();if(!t)return e;for(;t.length;)e=e.then(t.shift());return e}(t._transitionData._interruptCallbacks)},r.prepareFn,v.rehover,function(){return t.emit("plotly_transitioning",[]),new Promise(function(i){t._transitioning=!0,e.duration>0&&(t._transitioningWithDuration=!0),t._transitionData._interruptCallbacks.push(function(){n=!0}),r.redraw&&t._transitionData._interruptCallbacks.push(function(){return a.call("redraw",t)}),t._transitionData._interruptCallbacks.push(function(){t.emit("plotly_transitioninterrupted",[])});var o=0,s=0;function l(){return o++,function(){var e;s++,n||s!==o||(e=i,t._transitionData&&(function(t){if(t)for(;t.length;)t.shift()}(t._transitionData._interruptCallbacks),Promise.resolve().then(function(){if(r.redraw)return a.call("redraw",t)}).then(function(){t._transitioning=!1,t._transitioningWithDuration=!1,t.emit("plotly_transitioned",[])}).then(e)))}}r.runFn(l),setTimeout(l())})}],o=l.syncOrAsync(i,t);return o&&o.then||(o=Promise.resolve()),o.then(function(){return t})}function S(t,e){for(var r=0;r<t.length;r++){var n=t[r];n.clearCalc(),"multicategory"===n.type&&n.setupMultiCategory(e)}}v.supplyDefaults=function(t,e){var r=e&&e.skipUpdateCalc,i=t._fullLayout||{};if(i._skipDefaults)delete i._skipDefaults;else{var o,s=t._fullLayout={},c=t.layout||{},u=t._fullData||[],h=t._fullData=[],f=t.data||[],p=t.calcdata||[],m=t._context||{};t._transitionData||v.createTransitionData(t),s._dfltTitle={plot:g(t,"Click to enter Plot title"),x:g(t,"Click to enter X axis title"),y:g(t,"Click to enter Y axis title"),colorbar:g(t,"Click to enter Colorscale title"),annotation:g(t,"new text")},s._traceWord=g(t,"trace");var y=_(t,x);if(s._mapboxAccessToken=m.mapboxAccessToken,i._initialAutoSizeIsDone){var w=i.width,k=i.height;v.supplyLayoutGlobalDefaults(c,s,y),c.width||(s.width=w),c.height||(s.height=k),v.sanitizeMargins(s)}else{v.supplyLayoutGlobalDefaults(c,s,y);var A=!c.width||!c.height,T=s.autosize,S=m.autosizable;A&&(T||S)?v.plotAutoSize(t,c,s):A&&v.sanitizeMargins(s),!T&&A&&(c.width=s.width,c.height=s.height)}s._d3locale=function(t,e){return t.decimal=e.charAt(0),t.thousands=e.charAt(1),n.locale(t)}(y,s.separators),s._extraFormat=_(t,b),s._initialAutoSizeIsDone=!0,s._dataLength=f.length,s._modules=[],s._visibleModules=[],s._basePlotModules=[];var E=s._subplots=function(){var t,e,r=a.collectableSubplotTypes,n={};if(!r){r=[];var i=a.subplotsRegistry;for(var o in i){var s=i[o],c=s.attr;if(c&&(r.push(o),Array.isArray(c)))for(e=0;e<c.length;e++)l.pushUnique(r,c[e])}}for(t=0;t<r.length;t++)n[r[t]]=[];return n}(),C=s._splomAxes={x:{},y:{}},L=s._splomSubplots={};s._splomGridDflt={},s._scatterStackOpts={},s._firstScatter={},s._alignmentOpts={},s._requestRangeslider={},s._traceUids=function(t,e){var r,n,i=e.length,a=[];for(r=0;r<t.length;r++){var o=t[r]._fullInput;o!==n&&a.push(o),n=o}var s=a.length,c=new Array(i),u={};function h(t,e){c[e]=t,u[t]=1}function f(t,e){if(t&&"string"==typeof t&&!u[t])return h(t,e),!0}for(r=0;r<i;r++){var p=e[r].uid;"number"==typeof p&&(p=String(p)),f(p,r)||(r<s&&f(a[r].uid,r)||h(l.randstr(u),r))}return c}(u,f),s._globalTransforms=(t._context||{}).globalTransforms,v.supplyDataDefaults(f,h,c,s);var z=Object.keys(C.x),O=Object.keys(C.y);if(z.length>1&&O.length>1){for(a.getComponentMethod("grid","sizeDefaults")(c,s),o=0;o<z.length;o++)l.pushUnique(E.xaxis,z[o]);for(o=0;o<O.length;o++)l.pushUnique(E.yaxis,O[o]);for(var I in L)l.pushUnique(E.cartesian,I)}if(s._has=v._hasPlotType.bind(s),u.length===h.length)for(o=0;o<h.length;o++)d(h[o],u[o]);v.supplyLayoutModuleDefaults(c,s,h,t._transitionData);var D=s._visibleModules,P=[];for(o=0;o<D.length;o++){var R=D[o].crossTraceDefaults;R&&l.pushUnique(P,R)}for(o=0;o<P.length;o++)P[o](h,s);a.getComponentMethod("colorscale","crossTraceDefaults")(h,s),s._hasOnlyLargeSploms=1===s._basePlotModules.length&&"splom"===s._basePlotModules[0].name&&z.length>15&&O.length>15&&0===s.shapes.length&&0===s.images.length,s._hasCartesian=s._has("cartesian"),s._hasGeo=s._has("geo"),s._hasGL3D=s._has("gl3d"),s._hasGL2D=s._has("gl2d"),s._hasTernary=s._has("ternary"),s._hasPie=s._has("pie"),v.linkSubplots(h,s,u,i),v.cleanPlot(h,s,u,i),d(s,i),s._preGUI||(s._preGUI={}),s._tracePreGUI||(s._tracePreGUI={});var F,B=s._tracePreGUI,N={};for(F in B)N[F]="old";for(o=0;o<h.length;o++)N[F=h[o]._fullInput.uid]||(B[F]={}),N[F]="new";for(F in N)"old"===N[F]&&delete B[F];M(s),a.getComponentMethod("rangeslider","makeData")(s),r||p.length!==h.length||v.supplyDefaultsUpdateCalc(p,h)}},v.supplyDefaultsUpdateCalc=function(t,e){for(var r=0;r<e.length;r++){var n=e[r],i=(t[r]||[])[0];if(i&&i.trace){var a=i.trace;if(a._hasCalcTransform){var o,s,c,u=a._arrayAttrs;for(o=0;o<u.length;o++)s=u[o],c=l.nestedProperty(a,s).get().slice(),l.nestedProperty(n,s).set(c)}i.trace=n}}},v.createTransitionData=function(t){t._transitionData||(t._transitionData={}),t._transitionData._frames||(t._transitionData._frames=[]),t._transitionData._frameHash||(t._transitionData._frameHash={}),t._transitionData._counter||(t._transitionData._counter=0),t._transitionData._interruptCallbacks||(t._transitionData._interruptCallbacks=[])},v._hasPlotType=function(t){var e,r=this._basePlotModules||[];for(e=0;e<r.length;e++)if(r[e].name===t)return!0;var n=this._modules||[];for(e=0;e<n.length;e++){var i=n[e].name;if(i===t)return!0;var o=a.modules[i];if(o&&o.categories[t])return!0}return!1},v.cleanPlot=function(t,e,r,n){var i,a,o=n._basePlotModules||[];for(i=0;i<o.length;i++){var s=o[i];s.clean&&s.clean(t,e,r,n)}var l=n._has&&n._has("gl"),c=e._has&&e._has("gl");l&&!c&&void 0!==n._glcontainer&&(n._glcontainer.selectAll(".gl-canvas").remove(),n._glcontainer.selectAll(".no-webgl").remove(),n._glcanvas=null);var u=!!n._infolayer;t:for(i=0;i<r.length;i++){var h=r[i].uid;for(a=0;a<t.length;a++){if(h===t[a].uid)continue t}u&&n._infolayer.select(".cb"+h).remove()}n._zoomlayer&&n._zoomlayer.selectAll(".select-outline").remove()},v.linkSubplots=function(t,e,r,n){var i,a,o=n._plots||{},s=e._plots={},c=e._subplots,u={_fullData:t,_fullLayout:e},f=c.cartesian.concat(c.gl2d||[]);for(i=0;i<f.length;i++){var p,d=f[i],g=o[d],v=h.getFromId(u,d,"x"),m=h.getFromId(u,d,"y");for(g?p=s[d]=g:(p=s[d]={}).id=d,v._counterAxes.push(m._id),m._counterAxes.push(v._id),v._subplotsWith.push(d),m._subplotsWith.push(d),p.xaxis=v,p.yaxis=m,p._hasClipOnAxisFalse=!1,a=0;a<t.length;a++){var y=t[a];if(y.xaxis===p.xaxis._id&&y.yaxis===p.yaxis._id&&!1===y.cliponaxis){p._hasClipOnAxisFalse=!0;break}}}var x,b=h.list(u,null,!0);for(i=0;i<b.length;i++){var _=null;(x=b[i]).overlaying&&(_=h.getFromId(u,x.overlaying))&&_.overlaying&&(x.overlaying=!1,_=null),x._mainAxis=_||x,_&&(x.domain=_.domain.slice()),x._anchorAxis="free"===x.anchor?null:h.getFromId(u,x.anchor)}for(i=0;i<b.length;i++)(x=b[i])._counterAxes.sort(h.idSort),x._subplotsWith.sort(l.subplotSort),x._mainSubplot=w(x,e)},v.clearExpandedTraceDefaultColors=function(t){var e,r,n;for(r=[],(e=t._module._colorAttrs)||(t._module._colorAttrs=e=[],o.crawl(t._module.attributes,function(t,n,i,a){r[a]=n,r.length=a+1,"color"===t.valType&&void 0===t.dflt&&e.push(r.join("."))})),n=0;n<e.length;n++){l.nestedProperty(t,"_input."+e[n]).get()||l.nestedProperty(t,e[n]).set(null)}},v.supplyDataDefaults=function(t,e,r,n){var i,o,c,u=n._modules,h=n._visibleModules,f=n._basePlotModules,p=0,g=0;function m(t){e.push(t);var r=t._module;r&&(l.pushUnique(u,r),!0===t.visible&&l.pushUnique(h,r),l.pushUnique(f,t._module.basePlotModule),p++,!1!==t._input.visible&&g++)}n._transformModules=[];var y={},x=[],b=(r.template||{}).data||{},_=s.traceTemplater(b);for(i=0;i<t.length;i++){if(c=t[i],(o=_.newTrace(c)).uid=n._traceUids[i],v.supplyTraceDefaults(c,o,g,n,i),o.index=i,o._input=c,o._expandedIndex=p,o.transforms&&o.transforms.length)for(var w=!1!==c.visible&&!1===o.visible,k=A(o,e,r,n),M=0;M<k.length;M++){var T=k[M],S={_template:o._template,type:o.type,uid:o.uid+M};w&&!1===T.visible&&delete T.visible,v.supplyTraceDefaults(T,S,p,n,i),d(S,T),S.index=i,S._input=c,S._fullInput=o,S._expandedIndex=p,S._expandedInput=T,m(S)}else o._fullInput=o,o._expandedInput=o,m(o);a.traceIs(o,"carpetAxis")&&(y[o.carpet]=o),a.traceIs(o,"carpetDependent")&&x.push(i)}for(i=0;i<x.length;i++)if((o=e[x[i]]).visible){var E=y[o.carpet];o._carpet=E,E&&E.visible?(o.xaxis=E.xaxis,o.yaxis=E.yaxis):o.visible=!1}},v.supplyAnimationDefaults=function(t){var e;t=t||{};var r={};function n(e,n){return l.coerce(t||{},r,f,e,n)}if(n("mode"),n("direction"),n("fromcurrent"),Array.isArray(t.frame))for(r.frame=[],e=0;e<t.frame.length;e++)r.frame[e]=v.supplyAnimationFrameDefaults(t.frame[e]||{});else r.frame=v.supplyAnimationFrameDefaults(t.frame||{});if(Array.isArray(t.transition))for(r.transition=[],e=0;e<t.transition.length;e++)r.transition[e]=v.supplyAnimationTransitionDefaults(t.transition[e]||{});else r.transition=v.supplyAnimationTransitionDefaults(t.transition||{});return r},v.supplyAnimationFrameDefaults=function(t){var e={};function r(r,n){return l.coerce(t||{},e,f.frame,r,n)}return r("duration"),r("redraw"),e},v.supplyAnimationTransitionDefaults=function(t){var e={};function r(r,n){return l.coerce(t||{},e,f.transition,r,n)}return r("duration"),r("easing"),e},v.supplyFrameDefaults=function(t){var e={};function r(r,n){return l.coerce(t,e,p,r,n)}return r("group"),r("name"),r("traces"),r("baseframe"),r("data"),r("layout"),e},v.supplyTraceDefaults=function(t,e,r,n,i){var o,s=n.colorway||c.defaults,u=s[r%s.length];function h(r,n){return l.coerce(t,e,v.attributes,r,n)}var f=h("visible");h("type"),h("name",n._traceWord+" "+i),h("uirevision",n.uirevision);var p,d,g,m=v.getModule(e);if(e._module=m,m){var y=m.basePlotModule,x=y.attr,b=y.attributes;if(x&&b){var _=n._subplots,w="";if("gl2d"!==y.name||f){if(Array.isArray(x))for(o=0;o<x.length;o++){var k=x[o],A=l.coerce(t,e,b,k);_[k]&&l.pushUnique(_[k],A),w+=A}else w=l.coerce(t,e,b,x);_[y.name]&&l.pushUnique(_[y.name],w)}}}return f&&(h("customdata"),h("ids"),a.traceIs(e,"showLegend")?(e._dfltShowLegend=!0,h("showlegend"),h("legendgroup")):e._dfltShowLegend=!1,p="hoverlabel",d="",g=function(){a.getComponentMethod("fx","supplyDefaults")(t,e,u,n)},m&&p in m.attributes&&void 0===m.attributes[p]||(g&&"function"==typeof g?g():h(p,d)),m&&(m.supplyDefaults(t,e,u,n),e.hovertemplate||l.coerceHoverinfo(t,e,n)),a.traceIs(e,"noOpacity")||h("opacity"),a.traceIs(e,"notLegendIsolatable")&&(e.visible=!!e.visible),m&&m.selectPoints&&h("selectedpoints"),v.supplyTransformDefaults(t,e,n)),e},v.hasMakesDataTransform=k,v.supplyTransformDefaults=function(t,e,r){if(e._length||k(t)){var n=r._globalTransforms||[],i=r._transformModules||[];if(Array.isArray(t.transforms)||0!==n.length)for(var a=t.transforms||[],o=n.concat(a),s=e.transforms=[],c=0;c<o.length;c++){var u,h=o[c],f=h.type,p=m[f],d=!(h._module&&h._module===p),g=p&&"function"==typeof p.transform;p||l.warn("Unrecognized transform type "+f+"."),p&&p.supplyDefaults&&(d||g)?((u=p.supplyDefaults(h,e,r,t)).type=f,u._module=p,l.pushUnique(i,p)):u=l.extendFlat({},h),s.push(u)}}},v.supplyLayoutGlobalDefaults=function(t,e,r){function n(r,n){return l.coerce(t,e,v.layoutAttributes,r,n)}var i=t.template;l.isPlainObject(i)&&(e.template=i,e._template=i.layout,e._dataTemplate=i.data);var o=l.coerceFont(n,"font");n("title.text",e._dfltTitle.plot),l.coerceFont(n,"title.font",{family:o.family,size:Math.round(1.4*o.size),color:o.color}),n("title.xref"),n("title.yref"),n("title.x"),n("title.y"),n("title.xanchor"),n("title.yanchor"),n("title.pad.t"),n("title.pad.r"),n("title.pad.b"),n("title.pad.l"),n("autosize",!(t.width&&t.height)),n("width"),n("height"),n("margin.l"),n("margin.r"),n("margin.t"),n("margin.b"),n("margin.pad"),n("margin.autoexpand"),t.width&&t.height&&v.sanitizeMargins(e),a.getComponentMethod("grid","sizeDefaults")(t,e),n("paper_bgcolor"),n("separators",r.decimal+r.thousands),n("hidesources"),n("colorway"),n("datarevision");var s=n("uirevision");n("editrevision",s),n("selectionrevision",s),n("modebar.orientation"),n("modebar.bgcolor",c.addOpacity(e.paper_bgcolor,.5));var u=c.contrast(c.rgb(e.modebar.bgcolor));n("modebar.color",c.addOpacity(u,.3)),n("modebar.activecolor",c.addOpacity(u,.7)),n("modebar.uirevision",s),n("meta"),l.isPlainObject(t.transition)&&(n("transition.duration"),n("transition.easing"),n("transition.ordering")),a.getComponentMethod("calendars","handleDefaults")(t,e,"calendar"),a.getComponentMethod("fx","supplyLayoutGlobalDefaults")(t,e,n)},v.plotAutoSize=function(t,e,r){var n,a,o=t._context||{},s=o.frameMargins,c=l.isPlotDiv(t);if(c&&t.emit("plotly_autosize"),o.fillFrame)n=window.innerWidth,a=window.innerHeight,document.body.style.overflow="hidden";else{var u=c?window.getComputedStyle(t):{};if(n=parseFloat(u.width)||parseFloat(u.maxWidth)||r.width,a=parseFloat(u.height)||parseFloat(u.maxHeight)||r.height,i(s)&&s>0){var h=1-2*s;n=Math.round(h*n),a=Math.round(h*a)}}var f=v.layoutAttributes.width.min,p=v.layoutAttributes.height.min;n<f&&(n=f),a<p&&(a=p);var d=!e.width&&Math.abs(r.width-n)>1,g=!e.height&&Math.abs(r.height-a)>1;(g||d)&&(d&&(r.width=n),g&&(r.height=a)),t._initialAutoSize||(t._initialAutoSize={width:n,height:a}),v.sanitizeMargins(r)},v.supplyLayoutModuleDefaults=function(t,e,r,n){var i,o,s,c=a.componentsRegistry,u=e._basePlotModules,h=a.subplotsRegistry.cartesian;for(i in c)(s=c[i]).includeBasePlot&&s.includeBasePlot(t,e);for(var f in u.length||u.push(h),e._has("cartesian")&&(a.getComponentMethod("grid","contentDefaults")(t,e),h.finalizeSubplots(t,e)),e._subplots)e._subplots[f].sort(l.subplotSort);for(o=0;o<u.length;o++)(s=u[o]).supplyLayoutDefaults&&s.supplyLayoutDefaults(t,e,r);var p=e._modules;for(o=0;o<p.length;o++)(s=p[o]).supplyLayoutDefaults&&s.supplyLayoutDefaults(t,e,r);var d=e._transformModules;for(o=0;o<d.length;o++)(s=d[o]).supplyLayoutDefaults&&s.supplyLayoutDefaults(t,e,r,n);for(i in c)(s=c[i]).supplyLayoutDefaults&&s.supplyLayoutDefaults(t,e,r)},v.purge=function(t){var e=t._fullLayout||{};void 0!==e._glcontainer&&(e._glcontainer.selectAll(".gl-canvas").remove(),e._glcontainer.remove(),e._glcanvas=null),void 0!==e._geocontainer&&e._geocontainer.remove(),e._modeBar&&e._modeBar.destroy(),t._transitionData&&(t._transitionData._interruptCallbacks&&(t._transitionData._interruptCallbacks.length=0),t._transitionData._animationRaf&&window.cancelAnimationFrame(t._transitionData._animationRaf)),l.clearThrottle(),l.clearResponsive(t),delete t.data,delete t.layout,delete t._fullData,delete t._fullLayout,delete t.calcdata,delete t.framework,delete t.empty,delete t.fid,delete t.undoqueue,delete t.undonum,delete t.autoplay,delete t.changed,delete t._promises,delete t._redrawTimer,delete t._hmlumcount,delete t._hmpixcount,delete t._transitionData,delete t._transitioning,delete t._initialAutoSize,delete t._transitioningWithDuration,delete t._dragging,delete t._dragged,delete t._hoverdata,delete t._snapshotInProgress,delete t._editing,delete t._replotPending,delete t._mouseDownTime,delete t._legendMouseDownTime,t.removeAllListeners&&t.removeAllListeners()},v.style=function(t){var e,r=t._fullLayout._visibleModules,n=[];for(e=0;e<r.length;e++){var i=r[e];i.style&&l.pushUnique(n,i.style)}for(e=0;e<n.length;e++)n[e](t)},v.sanitizeMargins=function(t){if(t&&t.margin){var e,r=t.width,n=t.height,i=t.margin,a=r-(i.l+i.r),o=n-(i.t+i.b);a<0&&(e=(r-1)/(i.l+i.r),i.l=Math.floor(e*i.l),i.r=Math.floor(e*i.r)),o<0&&(e=(n-1)/(i.t+i.b),i.t=Math.floor(e*i.t),i.b=Math.floor(e*i.b))}},v.clearAutoMarginIds=function(t){t._fullLayout._pushmarginIds={}},v.allowAutoMargin=function(t,e){t._fullLayout._pushmarginIds[e]=1},v.autoMargin=function(t,e,r){var n=t._fullLayout,i=n._pushmargin,a=n._pushmarginIds;if(!1!==n.margin.autoexpand){if(r){var o=r.pad;if(void 0===o){var s=n.margin;o=Math.min(12,s.l,s.r,s.t,s.b)}r.l+r.r>.5*n.width&&(r.l=r.r=0),r.b+r.t>.5*n.height&&(r.b=r.t=0);var l=void 0!==r.xl?r.xl:r.x,c=void 0!==r.xr?r.xr:r.x,u=void 0!==r.yt?r.yt:r.y,h=void 0!==r.yb?r.yb:r.y;i[e]={l:{val:l,size:r.l+o},r:{val:c,size:r.r+o},b:{val:h,size:r.b+o},t:{val:u,size:r.t+o}},a[e]=1}else delete i[e],delete a[e];n._replotting||v.doAutoMargin(t)}},v.doAutoMargin=function(t){var e=t._fullLayout;e._size||(e._size={}),M(e);var r=e._size,n=JSON.stringify(r),o=e.margin,s=o.l,l=o.r,c=o.t,u=o.b,h=e.width,f=e.height,p=e._pushmargin,d=e._pushmarginIds;if(!1!==e.margin.autoexpand){for(var g in p)d[g]||delete p[g];for(var v in p.base={l:{val:0,size:s},r:{val:1,size:l},t:{val:1,size:c},b:{val:0,size:u}},p){var m=p[v].l||{},y=p[v].b||{},x=m.val,b=m.size,_=y.val,w=y.size;for(var k in p){if(i(b)&&p[k].r){var A=p[k].r.val,T=p[k].r.size;if(A>x){var S=(b*A+(T-h)*x)/(A-x),E=(T*(1-x)+(b-h)*(1-A))/(A-x);S>=0&&E>=0&&h-(S+E)>0&&S+E>s+l&&(s=S,l=E)}}if(i(w)&&p[k].t){var C=p[k].t.val,L=p[k].t.size;if(C>_){var z=(w*C+(L-f)*_)/(C-_),O=(L*(1-_)+(w-f)*(1-C))/(C-_);z>=0&&O>=0&&f-(O+z)>0&&z+O>u+c&&(u=z,c=O)}}}}}if(r.l=Math.round(s),r.r=Math.round(l),r.t=Math.round(c),r.b=Math.round(u),r.p=Math.round(o.pad),r.w=Math.round(h)-r.l-r.r,r.h=Math.round(f)-r.t-r.b,!e._replotting&&"{}"!==n&&n!==JSON.stringify(e._size))return"_redrawFromAutoMarginCount"in e?e._redrawFromAutoMarginCount++:e._redrawFromAutoMarginCount=1,a.call("plot",t)},v.graphJson=function(t,e,r,n,i){(i&&e&&!t._fullData||i&&!e&&!t._fullLayout)&&v.supplyDefaults(t);var a=i?t._fullData:t.data,o=i?t._fullLayout:t.layout,s=(t._transitionData||{})._frames;function c(t){if("function"==typeof t)return null;if(l.isPlainObject(t)){var e,n,i={};for(e in t)if("function"!=typeof t[e]&&-1===["_","["].indexOf(e.charAt(0))){if("keepdata"===r){if("src"===e.substr(e.length-3))continue}else if("keepstream"===r){if("string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0&&!l.isPlainObject(t.stream))continue}else if("keepall"!==r&&"string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0)continue;i[e]=c(t[e])}return i}return Array.isArray(t)?t.map(c):l.isTypedArray(t)?l.simpleMap(t,l.identity):l.isJSDate(t)?l.ms2DateTimeLocal(+t):t}var u={data:(a||[]).map(function(t){var r=c(t);return e&&delete r.fit,r})};return e||(u.layout=c(o)),t.framework&&t.framework.isPolar&&(u=t.framework.getConfig()),s&&(u.frames=c(s)),"object"===n?u:JSON.stringify(u)},v.modifyFrames=function(t,e){var r,n,i,a=t._transitionData._frames,o=t._transitionData._frameHash;for(r=0;r<e.length;r++)switch((n=e[r]).type){case"replace":i=n.value;var s=(a[n.index]||{}).name,l=i.name;a[n.index]=o[l]=i,l!==s&&(delete o[s],o[l]=i);break;case"insert":o[(i=n.value).name]=i,a.splice(n.index,0,i);break;case"delete":delete o[(i=a[n.index]).name],a.splice(n.index,1)}return Promise.resolve()},v.computeFrame=function(t,e){var r,n,i,a,o=t._transitionData._frameHash;if(!e)throw new Error("computeFrame must be given a string frame name");var s=o[e.toString()];if(!s)return!1;for(var l=[s],c=[s.name];s.baseframe&&(s=o[s.baseframe.toString()])&&-1===c.indexOf(s.name);)l.push(s),c.push(s.name);for(var u={};s=l.pop();)if(s.layout&&(u.layout=v.extendLayout(u.layout,s.layout)),s.data){if(u.data||(u.data=[]),!(n=s.traces))for(n=[],r=0;r<s.data.length;r++)n[r]=r;for(u.traces||(u.traces=[]),r=0;r<s.data.length;r++)null!=(i=n[r])&&(-1===(a=u.traces.indexOf(i))&&(a=u.data.length,u.traces[a]=i),u.data[a]=v.extendTrace(u.data[a],s.data[r]))}return u},v.recomputeFrameHash=function(t){for(var e=t._transitionData._frameHash={},r=t._transitionData._frames,n=0;n<r.length;n++){var i=r[n];i&&i.name&&(e[i.name]=i)}},v.extendObjectWithContainers=function(t,e,r){var n,i,a,o,s,c,u,h=l.extendDeepNoArrays({},e||{}),f=l.expandObjectPaths(h),p={};if(r&&r.length)for(a=0;a<r.length;a++)void 0===(i=(n=l.nestedProperty(f,r[a])).get())?l.nestedProperty(p,r[a]).set(null):(n.set(null),l.nestedProperty(p,r[a]).set(i));if(t=l.extendDeepNoArrays(t||{},f),r&&r.length)for(a=0;a<r.length;a++)if(c=l.nestedProperty(p,r[a]).get()){for(u=(s=l.nestedProperty(t,r[a])).get(),Array.isArray(u)||(u=[],s.set(u)),o=0;o<c.length;o++){var d=c[o];u[o]=null===d?null:v.extendObjectWithContainers(u[o],d)}s.set(u)}return t},v.dataArrayContainers=["transforms","dimensions"],v.layoutArrayContainers=a.layoutArrayContainers,v.extendTrace=function(t,e){return v.extendObjectWithContainers(t,e,v.dataArrayContainers)},v.extendLayout=function(t,e){return v.extendObjectWithContainers(t,e,v.layoutArrayContainers)},v.transition=function(t,e,r,n,i,a){var o={redraw:i.redraw},s=[],c=[];return o.prepareFn=function(){for(var i=Array.isArray(e)?e.length:0,a=n.slice(0,i),o=0;o<a.length;o++){var u=a[o],h=t._fullData[u]._module;h&&(h.animatable&&s.push(u),t.data[a[o]]=v.extendTrace(t.data[a[o]],e[o]))}var f=l.expandObjectPaths(l.extendDeepNoArrays({},r)),p=/^[xy]axis[0-9]*$/;for(var d in f)p.test(d)&&delete f[d].range;v.extendLayout(t.layout,f),delete t.calcdata,v.supplyDefaults(t),v.doCalcdata(t);var g=l.expandObjectPaths(r);if(g){var m=t._fullLayout._plots;for(var y in m){var x,b,_,w,k=m[y],A=k.xaxis,M=k.yaxis,T=A.range.slice(),S=M.range.slice();Array.isArray(g[A._name+".range"])?x=g[A._name+".range"].slice():Array.isArray((g[A._name]||{}).range)&&(x=g[A._name].range.slice()),Array.isArray(g[M._name+".range"])?b=g[M._name+".range"].slice():Array.isArray((g[M._name]||{}).range)&&(b=g[M._name].range.slice()),T&&x&&(T[0]!==x[0]||T[1]!==x[1])&&(_={xr0:T,xr1:x}),S&&b&&(S[0]!==b[0]||S[1]!==b[1])&&(w={yr0:S,yr1:b}),(_||w)&&c.push(l.extendFlat({plotinfo:k},_,w))}}return Promise.resolve()},o.runFn=function(e){var n,i,o=t._fullLayout._basePlotModules,u=c.length;if(r)for(i=0;i<o.length;i++)o[i].transitionAxes&&o[i].transitionAxes(t,c,a,e);for(u?((n=l.extendFlat({},a)).duration=0,s=null):n=a,i=0;i<o.length;i++)o[i].plot(t,s,n,e)},T(t,a,o)},v.transitionFromReact=function(t,e,r,n){var i=t._fullLayout,a=i.transition,o={},s=[];return o.prepareFn=function(){var t=i._plots;for(var a in o.redraw=!1,"some"===e.anim&&(o.redraw=!0),"some"===r.anim&&(o.redraw=!0),t){var c,u,h=t[a],f=h.xaxis,p=h.yaxis,d=n[f._name].range.slice(),g=n[p._name].range.slice(),v=f.range.slice(),m=p.range.slice();f.setScale(),p.setScale(),d[0]===v[0]&&d[1]===v[1]||(c={xr0:d,xr1:v}),g[0]===m[0]&&g[1]===m[1]||(u={yr0:g,yr1:m}),(c||u)&&s.push(l.extendFlat({plotinfo:h},c,u))}return Promise.resolve()},o.runFn=function(r){for(var n,i,o,c=t._fullData,u=t._fullLayout._basePlotModules,h=[],f=0;f<c.length;f++)h.push(f);function p(){for(var e=0;e<u.length;e++)u[e].transitionAxes&&u[e].transitionAxes(t,s,n,r)}function d(){for(var e=0;e<u.length;e++)u[e].plot(t,o,i,r)}s.length&&e.anim?"traces first"===a.ordering?(n=l.extendFlat({},a,{duration:0}),o=h,i=a,d(),setTimeout(p,a.duration)):(n=a,o=null,i=l.extendFlat({},a,{duration:0}),p(),d()):s.length?(n=a,p()):e.anim&&(o=h,i=a,d())},T(t,a,o)},v.doCalcdata=function(t,e){var r,n,i,s,c=h.list(t),f=t._fullData,p=t._fullLayout,d=new Array(f.length),g=(t.calcdata||[]).slice(0);for(t.calcdata=d,p._numBoxes=0,p._numViolins=0,p._violinScaleGroupStats={},t._hmpixcount=0,t._hmlumcount=0,p._piecolormap={},i=0;i<f.length;i++)Array.isArray(e)&&-1===e.indexOf(i)&&(d[i]=g[i]);for(i=0;i<f.length;i++)(r=f[i])._arrayAttrs=o.findArrayAttributes(r),r._extremes={};var v=p._subplots.polar||[];for(i=0;i<v.length;i++)c.push(p[v[i]].radialaxis,p[v[i]].angularaxis);S(c,f);var y=!1;for(i=0;i<f.length;i++)if(!0===(r=f[i]).visible&&r.transforms){if((n=r._module)&&n.calc){var x=n.calc(t,r);x[0]&&x[0].t&&x[0].t._scene&&delete x[0].t._scene.dirty}for(s=0;s<r.transforms.length;s++){var b=r.transforms[s];(n=m[b.type])&&n.calcTransform&&(r._hasCalcTransform=!0,y=!0,n.calcTransform(t,r,b))}}function _(e,i){if(r=f[e],!!(n=r._module).isContainer===i){var a=[];if(!0===r.visible){delete r._indexToPoints;var o=r.transforms||[];for(s=o.length-1;s>=0;s--)if(o[s].enabled){r._indexToPoints=o[s]._indexToPoints;break}n&&n.calc&&(a=n.calc(t,r))}Array.isArray(a)&&a[0]||(a=[{x:u,y:u}]),a[0].t||(a[0].t={}),a[0].trace=r,d[e]=a}}for(y&&S(c,f),i=0;i<f.length;i++)_(i,!0);for(i=0;i<f.length;i++)_(i,!1);!function(t){var e,r,n,i=t._fullLayout,a=i._visibleModules,o={};for(r=0;r<a.length;r++){var s=a[r],c=s.crossTraceCalc;if(c){var u=s.basePlotModule.name;o[u]?l.pushUnique(o[u],c):o[u]=[c]}}for(n in o){var h=o[n],f=i._subplots[n];if(Array.isArray(f))for(e=0;e<f.length;e++){var p=f[e],d="cartesian"===n?i._plots[p]:i[p];for(r=0;r<h.length;r++)h[r](t,d,p)}else for(r=0;r<h.length;r++)h[r](t)}}(t),a.getComponentMethod("fx","calc")(t),a.getComponentMethod("errorbars","calc")(t)},v.rehover=function(t){t._fullLayout._rehover&&t._fullLayout._rehover()},v.generalUpdatePerTraceModule=function(t,e,r,n){var i,a=e.traceHash,o={};for(i=0;i<r.length;i++){var s=r[i],c=s[0].trace;c.visible&&(o[c.type]=o[c.type]||[],o[c.type].push(s))}for(var u in a)if(!o[u]){var h=a[u][0];h[0].trace.visible=!1,o[u]=[h]}for(var f in o){var p=o[f];p[0][0].trace._module.plot(t,e,l.filterVisible(p),n)}e.traceHash=o}},{"../components/color":574,"../constants/numerical":674,"../lib":697,"../plot_api/plot_schema":734,"../plot_api/plot_template":735,"../plots/cartesian/axis_ids":748,"../registry":826,"./animation_attributes":740,"./attributes":742,"./command":769,"./font_attributes":771,"./frame_attributes":772,"./layout_attributes":798,d3:151,"fast-isnumeric":218}],808:[function(t,e,r){"use strict";e.exports={attr:"subplot",name:"polar",axisNames:["angularaxis","radialaxis"],axisName2dataArray:{angularaxis:"theta",radialaxis:"r"},layerNames:["draglayer","plotbg","backplot","angular-grid","radial-grid","frontplot","angular-line","radial-line","angular-axis","radial-axis"],radialDragBoxSize:50,angularDragBoxSize:30,cornerLen:25,cornerHalfWidth:2,MINDRAG:8,MINZOOM:20,OFFEDGE:20}},{}],809:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../lib/polygon").tester,a=n.findIndexOfMin,o=n.isAngleInsideSector,s=n.angleDelta,l=n.angleDist;function c(t,e,r,n){var i,a,o=n[0],s=n[1],l=h(Math.sin(e)-Math.sin(t)),c=h(Math.cos(e)-Math.cos(t)),u=Math.tan(r),f=h(1/u),p=l/c,d=s-p*o;return f?l&&c?a=u*(i=d/(u-p)):c?(i=s*f,a=s):(i=o,a=o*u):l&&c?(i=0,a=d):c?(i=0,a=s):i=a=NaN,[i,a]}function u(t,e,r,i){return n.isFullCircle([e,r])?function(t,e){var r,n=e.length,i=new Array(n+1);for(r=0;r<n;r++){var a=e[r];i[r]=[t*Math.cos(a),t*Math.sin(a)]}return i[r]=i[0].slice(),i}(t,i):function(t,e,r,i){var s,u,h=i.length,f=[];function p(e){return[t*Math.cos(e),t*Math.sin(e)]}function d(t,e,r){return c(t,e,r,p(t))}function g(t){return n.mod(t,h)}function v(t){return o(t,[e,r])}var m=a(i,function(t){return v(t)?l(t,e):1/0}),y=d(i[m],i[g(m-1)],e);for(f.push(y),s=m,u=0;u<h;s++,u++){var x=i[g(s)];if(!v(x))break;f.push(p(x))}var b=a(i,function(t){return v(t)?l(t,r):1/0}),_=d(i[b],i[g(b+1)],r);return f.push(_),f.push([0,0]),f.push(f[0].slice()),f}(t,e,r,i)}function h(t){return Math.abs(t)>1e-10?t:0}function f(t,e,r){e=e||0,r=r||0;for(var n=t.length,i=new Array(n),a=0;a<n;a++){var o=t[a];i[a]=[e+o[0],r-o[1]]}return i}e.exports={isPtInsidePolygon:function(t,e,r,n,a){if(!o(e,n))return!1;var s,l;r[0]<r[1]?(s=r[0],l=r[1]):(s=r[1],l=r[0]);var c=i(u(s,n[0],n[1],a)),h=i(u(l,n[0],n[1],a)),f=[t*Math.cos(e),t*Math.sin(e)];return h.contains(f)&&!c.contains(f)},findPolygonOffset:function(t,e,r,n){for(var i=1/0,a=1/0,o=u(t,e,r,n),s=0;s<o.length;s++){var l=o[s];i=Math.min(i,l[0]),a=Math.min(a,-l[1])}return[i,a]},findEnclosingVertexAngles:function(t,e){var r=a(e,function(e){var r=s(e,t);return r>0?r:1/0}),i=n.mod(r+1,e.length);return[e[r],e[i]]},findIntersectionXY:c,findXYatLength:function(t,e,r,n){var i=-e*r,a=e*e+1,o=2*(e*i-r),s=i*i+r*r-t*t,l=Math.sqrt(o*o-4*a*s),c=(-o+l)/(2*a),u=(-o-l)/(2*a);return[[c,e*c+i+n],[u,e*u+i+n]]},clampTiny:h,pathPolygon:function(t,e,r,n,i,a){return"M"+f(u(t,e,r,n),i,a).join("L")},pathPolygonAnnulus:function(t,e,r,n,i,a,o){var s,l;t<e?(s=t,l=e):(s=e,l=t);var c=f(u(s,r,n,i),a,o);return"M"+f(u(l,r,n,i),a,o).reverse().join("L")+"M"+c.join("L")}}},{"../../lib":697,"../../lib/polygon":709}],810:[function(t,e,r){"use strict";var n=t("../get_data").getSubplotCalcData,i=t("../../lib").counterRegex,a=t("./polar"),o=t("./constants"),s=o.attr,l=o.name,c=i(l),u={};u[s]={valType:"subplotid",dflt:l,editType:"calc"},e.exports={attr:s,name:l,idRoot:l,idRegex:c,attrRegex:c,attributes:u,layoutAttributes:t("./layout_attributes"),supplyLayoutDefaults:t("./layout_defaults"),plot:function(t){for(var e=t._fullLayout,r=t.calcdata,i=e._subplots[l],o=0;o<i.length;o++){var s=i[o],c=n(r,l,s),u=e[s]._subplot;u||(u=a(t,s),e[s]._subplot=u),u.plot(c,e,t._promises)}},clean:function(t,e,r,n){for(var i=n._subplots[l]||[],a=n._has&&n._has("gl"),o=e._has&&e._has("gl"),s=a&&!o,c=0;c<i.length;c++){var u=i[c],h=n[u]._subplot;if(!e[u]&&h)for(var f in h.framework.remove(),h.layers["radial-axis-title"].remove(),h.clipPaths)h.clipPaths[f].remove();s&&h._scene&&(h._scene.destroy(),h._scene=null)}},toSVG:t("../cartesian").toSVG}},{"../../lib":697,"../cartesian":756,"../get_data":781,"./constants":808,"./layout_attributes":811,"./layout_defaults":812,"./polar":819}],811:[function(t,e,r){"use strict";var n=t("../../components/color/attributes"),i=t("../cartesian/layout_attributes"),a=t("../domain").attributes,o=t("../../lib").extendFlat,s=t("../../plot_api/edit_types").overrideAll,l=s({color:i.color,showline:o({},i.showline,{dflt:!0}),linecolor:i.linecolor,linewidth:i.linewidth,showgrid:o({},i.showgrid,{dflt:!0}),gridcolor:i.gridcolor,gridwidth:i.gridwidth},"plot","from-root"),c=s({tickmode:i.tickmode,nticks:i.nticks,tick0:i.tick0,dtick:i.dtick,tickvals:i.tickvals,ticktext:i.ticktext,ticks:i.ticks,ticklen:i.ticklen,tickwidth:i.tickwidth,tickcolor:i.tickcolor,showticklabels:i.showticklabels,showtickprefix:i.showtickprefix,tickprefix:i.tickprefix,showticksuffix:i.showticksuffix,ticksuffix:i.ticksuffix,showexponent:i.showexponent,exponentformat:i.exponentformat,separatethousands:i.separatethousands,tickfont:i.tickfont,tickangle:i.tickangle,tickformat:i.tickformat,tickformatstops:i.tickformatstops,layer:i.layer},"plot","from-root"),u={visible:o({},i.visible,{dflt:!0}),type:o({},i.type,{values:["-","linear","log","date","category"]}),autorange:o({},i.autorange,{editType:"plot"}),rangemode:{valType:"enumerated",values:["tozero","nonnegative","normal"],dflt:"tozero",editType:"calc"},range:o({},i.range,{items:[{valType:"any",editType:"plot",impliedEdits:{"^autorange":!1}},{valType:"any",editType:"plot",impliedEdits:{"^autorange":!1}}],editType:"plot"}),categoryorder:i.categoryorder,categoryarray:i.categoryarray,angle:{valType:"angle",editType:"plot"},side:{valType:"enumerated",values:["clockwise","counterclockwise"],dflt:"clockwise",editType:"plot"},title:s(i.title,"plot","from-root"),hoverformat:i.hoverformat,uirevision:{valType:"any",editType:"none"},editType:"calc",_deprecated:{title:i._deprecated.title,titlefont:i._deprecated.titlefont}};u.title.text.dflt="",o(u,l,c);var h={visible:o({},i.visible,{dflt:!0}),type:{valType:"enumerated",values:["-","linear","category"],dflt:"-",editType:"calc",_noTemplating:!0},categoryorder:i.categoryorder,categoryarray:i.categoryarray,thetaunit:{valType:"enumerated",values:["radians","degrees"],dflt:"degrees",editType:"calc"},period:{valType:"number",editType:"calc",min:0},direction:{valType:"enumerated",values:["counterclockwise","clockwise"],dflt:"counterclockwise",editType:"calc"},rotation:{valType:"angle",editType:"calc"},hoverformat:i.hoverformat,uirevision:{valType:"any",editType:"none"},editType:"calc"};o(h,l,c),e.exports={domain:a({name:"polar",editType:"plot"}),sector:{valType:"info_array",items:[{valType:"number",editType:"plot"},{valType:"number",editType:"plot"}],dflt:[0,360],editType:"plot"},hole:{valType:"number",min:0,max:1,dflt:0,editType:"plot"},bgcolor:{valType:"color",editType:"plot",dflt:n.background},radialaxis:u,angularaxis:h,gridshape:{valType:"enumerated",values:["circular","linear"],dflt:"circular",editType:"plot"},uirevision:{valType:"any",editType:"none"},editType:"calc"}},{"../../components/color/attributes":573,"../../lib":697,"../../plot_api/edit_types":728,"../cartesian/layout_attributes":757,"../domain":770}],812:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/color"),a=t("../../plot_api/plot_template"),o=t("../subplot_defaults"),s=t("../get_data").getSubplotData,l=t("../cartesian/tick_value_defaults"),c=t("../cartesian/tick_mark_defaults"),u=t("../cartesian/tick_label_defaults"),h=t("../cartesian/category_order_defaults"),f=t("../cartesian/line_grid_defaults"),p=t("../cartesian/axis_autotype"),d=t("./layout_attributes"),g=t("./set_convert"),v=t("./constants"),m=v.axisNames;function y(t,e,r,o){var p=r("bgcolor");o.bgColor=i.combine(p,o.paper_bgcolor);var y=r("sector");r("hole");var b,_=s(o.fullData,v.name,o.id),w=o.layoutOut;function k(t,e){return r(b+"."+t,e)}for(var A=0;A<m.length;A++){b=m[A],n.isPlainObject(t[b])||(t[b]={});var M=t[b],T=a.newContainer(e,b);T._id=T._name=b,T._attr=o.id+"."+b,T._traceIndices=_.map(function(t){return t._expandedIndex});var S=v.axisName2dataArray[b],E=x(M,T,k,_,S);h(M,T,k,{axData:_,dataAttr:S});var C,L,z=k("visible");switch(g(T,e,w),k("uirevision",e.uirevision),z&&(L=(C=k("color"))===M.color?C:o.font.color),T._m=1,b){case"radialaxis":var O=k("autorange",!T.isValidRange(M.range));M.autorange=O,!O||"linear"!==E&&"-"!==E||k("rangemode"),"reversed"===O&&(T._m=-1),k("range"),T.cleanRange("range",{dfltRange:[0,1]}),z&&(k("side"),k("angle",y[0]),k("title.text"),n.coerceFont(k,"title.font",{family:o.font.family,size:Math.round(1.2*o.font.size),color:L}));break;case"angularaxis":if("date"===E){n.log("Polar plots do not support date angular axes yet.");for(var I=0;I<_.length;I++)_[I].visible=!1;E=M.type=T.type="linear"}k("linear"===E?"thetaunit":"period");var D=k("direction");k("rotation",{counterclockwise:0,clockwise:90}[D])}if(z)l(M,T,k,T.type),u(M,T,k,T.type,{tickSuffixDflt:"degrees"===T.thetaunit?"\xb0":void 0}),c(M,T,k,{outerTicks:!0}),k("showticklabels")&&(n.coerceFont(k,"tickfont",{family:o.font.family,size:o.font.size,color:L}),k("tickangle"),k("tickformat")),f(M,T,k,{dfltColor:C,bgColor:o.bgColor,blend:60,showLine:!0,showGrid:!0,noZeroLine:!0,attributes:d[b]}),k("layer");"category"!==E&&k("hoverformat"),T._input=M}"category"===e.angularaxis.type&&r("gridshape")}function x(t,e,r,n,i){if("-"===r("type")){for(var a,o=0;o<n.length;o++)if(n[o].visible){a=n[o];break}a&&a[i]&&(e.type=p(a[i],"gregorian")),"-"===e.type?e.type="linear":t.type=e.type}return e.type}e.exports=function(t,e,r){o(t,e,r,{type:v.name,attributes:d,handleDefaults:y,font:e.font,paper_bgcolor:e.paper_bgcolor,fullData:r,layoutOut:e})}},{"../../components/color":574,"../../lib":697,"../../plot_api/plot_template":735,"../cartesian/axis_autotype":746,"../cartesian/category_order_defaults":749,"../cartesian/line_grid_defaults":759,"../cartesian/tick_label_defaults":764,"../cartesian/tick_mark_defaults":765,"../cartesian/tick_value_defaults":766,"../get_data":781,"../subplot_defaults":821,"./constants":808,"./layout_attributes":811,"./set_convert":820}],813:[function(t,e,r){"use strict";var n=t("../../../traces/scatter/attributes"),i=n.marker,a=t("../../../lib/extend").extendFlat;["Area traces are deprecated!","Please switch to the *barpolar* trace type."].join(" ");e.exports={r:a({},n.r,{}),t:a({},n.t,{}),marker:{color:a({},i.color,{}),size:a({},i.size,{}),symbol:a({},i.symbol,{}),opacity:a({},i.opacity,{}),editType:"calc"}}},{"../../../lib/extend":687,"../../../traces/scatter/attributes":1048}],814:[function(t,e,r){"use strict";var n=t("../../cartesian/layout_attributes"),i=t("../../../lib/extend").extendFlat,a=t("../../../plot_api/edit_types").overrideAll,o=["Legacy polar charts are deprecated!","Please switch to *polar* subplots."].join(" "),s=i({},n.domain,{});function l(t,e){return i({},e,{showline:{valType:"boolean"},showticklabels:{valType:"boolean"},tickorientation:{valType:"enumerated",values:["horizontal","vertical"]},ticklen:{valType:"number",min:0},tickcolor:{valType:"color"},ticksuffix:{valType:"string"},endpadding:{valType:"number",description:o},visible:{valType:"boolean"}})}e.exports=a({radialaxis:l(0,{range:{valType:"info_array",items:[{valType:"number"},{valType:"number"}]},domain:s,orientation:{valType:"number"}}),angularaxis:l(0,{range:{valType:"info_array",items:[{valType:"number",dflt:0},{valType:"number",dflt:360}]},domain:s}),layout:{direction:{valType:"enumerated",values:["clockwise","counterclockwise"]},orientation:{valType:"angle"}}},"plot","nested")},{"../../../lib/extend":687,"../../../plot_api/edit_types":728,"../../cartesian/layout_attributes":757}],815:[function(t,e,r){"use strict";(e.exports=t("./micropolar")).manager=t("./micropolar_manager")},{"./micropolar":816,"./micropolar_manager":817}],816:[function(t,e,r){var n=t("d3"),i=t("../../../lib").extendDeepAll,a=t("../../../constants/alignment").MID_SHIFT,o=e.exports={version:"0.2.2"};o.Axis=function(){var t,e,r,s,l={data:[],layout:{}},c={},u={},h=n.dispatch("hover"),f={};return f.render=function(c){return function(c){e=c||e;var h=l.data,f=l.layout;("string"==typeof e||e.nodeName)&&(e=n.select(e)),e.datum(h).each(function(e,l){var c=e.slice();u={data:o.util.cloneJson(c),layout:o.util.cloneJson(f)};var h=0;c.forEach(function(t,e){t.color||(t.color=f.defaultColorRange[h],h=(h+1)%f.defaultColorRange.length),t.strokeColor||(t.strokeColor="LinePlot"===t.geometry?t.color:n.rgb(t.color).darker().toString()),u.data[e].color=t.color,u.data[e].strokeColor=t.strokeColor,u.data[e].strokeDash=t.strokeDash,u.data[e].strokeSize=t.strokeSize});var p=c.filter(function(t,e){var r=t.visible;return"undefined"==typeof r||!0===r}),d=!1,g=p.map(function(t,e){return d=d||"undefined"!=typeof t.groupId,t});if(d){var v=n.nest().key(function(t,e){return"undefined"!=typeof t.groupId?t.groupId:"unstacked"}).entries(g),m=[],y=v.map(function(t,e){if("unstacked"===t.key)return t.values;var r=t.values[0].r.map(function(t,e){return 0});return t.values.forEach(function(t,e,n){t.yStack=[r],m.push(r),r=o.util.sumArrays(t.r,r)}),t.values});p=n.merge(y)}p.forEach(function(t,e){t.t=Array.isArray(t.t[0])?t.t:[t.t],t.r=Array.isArray(t.r[0])?t.r:[t.r]});var x=Math.min(f.width-f.margin.left-f.margin.right,f.height-f.margin.top-f.margin.bottom)/2;x=Math.max(10,x);var b,_=[f.margin.left+x,f.margin.top+x];b=d?[0,n.max(o.util.sumArrays(o.util.arrayLast(p).r[0],o.util.arrayLast(m)))]:n.extent(o.util.flattenArray(p.map(function(t,e){return t.r}))),f.radialAxis.domain!=o.DATAEXTENT&&(b[0]=0),r=n.scale.linear().domain(f.radialAxis.domain!=o.DATAEXTENT&&f.radialAxis.domain?f.radialAxis.domain:b).range([0,x]),u.layout.radialAxis.domain=r.domain();var w,k=o.util.flattenArray(p.map(function(t,e){return t.t})),A="string"==typeof k[0];A&&(k=o.util.deduplicate(k),w=k.slice(),k=n.range(k.length),p=p.map(function(t,e){var r=t;return t.t=[k],d&&(r.yStack=t.yStack),r}));var M=p.filter(function(t,e){return"LinePlot"===t.geometry||"DotPlot"===t.geometry}).length===p.length,T=null===f.needsEndSpacing?A||!M:f.needsEndSpacing,S=f.angularAxis.domain&&f.angularAxis.domain!=o.DATAEXTENT&&!A&&f.angularAxis.domain[0]>=0?f.angularAxis.domain:n.extent(k),E=Math.abs(k[1]-k[0]);M&&!A&&(E=0);var C=S.slice();T&&A&&(C[1]+=E);var L=f.angularAxis.ticksCount||4;L>8&&(L=L/(L/8)+L%8),f.angularAxis.ticksStep&&(L=(C[1]-C[0])/L);var z=f.angularAxis.ticksStep||(C[1]-C[0])/(L*(f.minorTicks+1));w&&(z=Math.max(Math.round(z),1)),C[2]||(C[2]=z);var O=n.range.apply(this,C);if(O=O.map(function(t,e){return parseFloat(t.toPrecision(12))}),s=n.scale.linear().domain(C.slice(0,2)).range("clockwise"===f.direction?[0,360]:[360,0]),u.layout.angularAxis.domain=s.domain(),u.layout.angularAxis.endPadding=T?E:0,"undefined"==typeof(t=n.select(this).select("svg.chart-root"))||t.empty()){var I=(new DOMParser).parseFromString("<svg xmlns='http://www.w3.org/2000/svg' class='chart-root'>' + '<g class='outer-group'>' + '<g class='chart-group'>' + '<circle class='background-circle'></circle>' + '<g class='geometry-group'></g>' + '<g class='radial axis-group'>' + '<circle class='outside-circle'></circle>' + '</g>' + '<g class='angular axis-group'></g>' + '<g class='guides-group'><line></line><circle r='0'></circle></g>' + '</g>' + '<g class='legend-group'></g>' + '<g class='tooltips-group'></g>' + '<g class='title-group'><text></text></g>' + '</g>' + '</svg>","application/xml"),D=this.appendChild(this.ownerDocument.importNode(I.documentElement,!0));t=n.select(D)}t.select(".guides-group").style({"pointer-events":"none"}),t.select(".angular.axis-group").style({"pointer-events":"none"}),t.select(".radial.axis-group").style({"pointer-events":"none"});var P,R=t.select(".chart-group"),F={fill:"none",stroke:f.tickColor},B={"font-size":f.font.size,"font-family":f.font.family,fill:f.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(t,e){return" "+t+" 0 "+f.font.outlineColor}).join(",")};if(f.showLegend){P=t.select(".legend-group").attr({transform:"translate("+[x,f.margin.top]+")"}).style({display:"block"});var N=p.map(function(t,e){var r=o.util.cloneJson(t);return r.symbol="DotPlot"===t.geometry?t.dotType||"circle":"LinePlot"!=t.geometry?"square":"line",r.visibleInLegend="undefined"==typeof t.visibleInLegend||t.visibleInLegend,r.color="LinePlot"===t.geometry?t.strokeColor:t.color,r});o.Legend().config({data:p.map(function(t,e){return t.name||"Element"+e}),legendConfig:i({},o.Legend.defaultConfig().legendConfig,{container:P,elements:N,reverseOrder:f.legend.reverseOrder})})();var j=P.node().getBBox();x=Math.min(f.width-j.width-f.margin.left-f.margin.right,f.height-f.margin.top-f.margin.bottom)/2,x=Math.max(10,x),_=[f.margin.left+x,f.margin.top+x],r.range([0,x]),u.layout.radialAxis.domain=r.domain(),P.attr("transform","translate("+[_[0]+x,_[1]-x]+")")}else P=t.select(".legend-group").style({display:"none"});t.attr({width:f.width,height:f.height}).style({opacity:f.opacity}),R.attr("transform","translate("+_+")").style({cursor:"crosshair"});var V=[(f.width-(f.margin.left+f.margin.right+2*x+(j?j.width:0)))/2,(f.height-(f.margin.top+f.margin.bottom+2*x))/2];if(V[0]=Math.max(0,V[0]),V[1]=Math.max(0,V[1]),t.select(".outer-group").attr("transform","translate("+V+")"),f.title&&f.title.text){var U=t.select("g.title-group text").style(B).text(f.title.text),q=U.node().getBBox();U.attr({x:_[0]-q.width/2,y:_[1]-x-20})}var H=t.select(".radial.axis-group");if(f.radialAxis.gridLinesVisible){var G=H.selectAll("circle.grid-circle").data(r.ticks(5));G.enter().append("circle").attr({class:"grid-circle"}).style(F),G.attr("r",r),G.exit().remove()}H.select("circle.outside-circle").attr({r:x}).style(F);var Y=t.select("circle.background-circle").attr({r:x}).style({fill:f.backgroundColor,stroke:f.stroke});function W(t,e){return s(t)%360+f.orientation}if(f.radialAxis.visible){var X=n.svg.axis().scale(r).ticks(5).tickSize(5);H.call(X).attr({transform:"rotate("+f.radialAxis.orientation+")"}),H.selectAll(".domain").style(F),H.selectAll("g>text").text(function(t,e){return this.textContent+f.radialAxis.ticksSuffix}).style(B).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(t,e){return"horizontal"===f.radialAxis.tickOrientation?"rotate("+-f.radialAxis.orientation+") translate("+[0,B["font-size"]]+")":"translate("+[0,B["font-size"]]+")"}}),H.selectAll("g>line").style({stroke:"black"})}var Z=t.select(".angular.axis-group").selectAll("g.angular-tick").data(O),$=Z.enter().append("g").classed("angular-tick",!0);Z.attr({transform:function(t,e){return"rotate("+W(t)+")"}}).style({display:f.angularAxis.visible?"block":"none"}),Z.exit().remove(),$.append("line").classed("grid-line",!0).classed("major",function(t,e){return e%(f.minorTicks+1)==0}).classed("minor",function(t,e){return!(e%(f.minorTicks+1)==0)}).style(F),$.selectAll(".minor").style({stroke:f.minorTickColor}),Z.select("line.grid-line").attr({x1:f.tickLength?x-f.tickLength:0,x2:x}).style({display:f.angularAxis.gridLinesVisible?"block":"none"}),$.append("text").classed("axis-text",!0).style(B);var J=Z.select("text.axis-text").attr({x:x+f.labelOffset,dy:a+"em",transform:function(t,e){var r=W(t),n=x+f.labelOffset,i=f.angularAxis.tickOrientation;return"horizontal"==i?"rotate("+-r+" "+n+" 0)":"radial"==i?r<270&&r>90?"rotate(180 "+n+" 0)":null:"rotate("+(r<=180&&r>0?-90:90)+" "+n+" 0)"}}).style({"text-anchor":"middle",display:f.angularAxis.labelsVisible?"block":"none"}).text(function(t,e){return e%(f.minorTicks+1)!=0?"":w?w[t]+f.angularAxis.ticksSuffix:t+f.angularAxis.ticksSuffix}).style(B);f.angularAxis.rewriteTicks&&J.text(function(t,e){return e%(f.minorTicks+1)!=0?"":f.angularAxis.rewriteTicks(this.textContent,e)});var K=n.max(R.selectAll(".angular-tick text")[0].map(function(t,e){return t.getCTM().e+t.getBBox().width}));P.attr({transform:"translate("+[x+K,f.margin.top]+")"});var Q=t.select("g.geometry-group").selectAll("g").size()>0,tt=t.select("g.geometry-group").selectAll("g.geometry").data(p);if(tt.enter().append("g").attr({class:function(t,e){return"geometry geometry"+e}}),tt.exit().remove(),p[0]||Q){var et=[];p.forEach(function(t,e){var n={};n.radialScale=r,n.angularScale=s,n.container=tt.filter(function(t,r){return r==e}),n.geometry=t.geometry,n.orientation=f.orientation,n.direction=f.direction,n.index=e,et.push({data:t,geometryConfig:n})});var rt=n.nest().key(function(t,e){return"undefined"!=typeof t.data.groupId||"unstacked"}).entries(et),nt=[];rt.forEach(function(t,e){"unstacked"===t.key?nt=nt.concat(t.values.map(function(t,e){return[t]})):nt.push(t.values)}),nt.forEach(function(t,e){var r;r=Array.isArray(t)?t[0].geometryConfig.geometry:t.geometryConfig.geometry;var n=t.map(function(t,e){return i(o[r].defaultConfig(),t)});o[r]().config(n)()})}var it,at,ot=t.select(".guides-group"),st=t.select(".tooltips-group"),lt=o.tooltipPanel().config({container:st,fontSize:8})(),ct=o.tooltipPanel().config({container:st,fontSize:8})(),ut=o.tooltipPanel().config({container:st,hasTick:!0})();if(!A){var ht=ot.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});R.on("mousemove.angular-guide",function(t,e){var r=o.util.getMousePos(Y).angle;ht.attr({x2:-x,transform:"rotate("+r+")"}).style({opacity:.5});var n=(r+180+360-f.orientation)%360;it=s.invert(n);var i=o.util.convertToCartesian(x+12,r+180);lt.text(o.util.round(it)).move([i[0]+_[0],i[1]+_[1]])}).on("mouseout.angular-guide",function(t,e){ot.select("line").style({opacity:0})})}var ft=ot.select("circle").style({stroke:"grey",fill:"none"});R.on("mousemove.radial-guide",function(t,e){var n=o.util.getMousePos(Y).radius;ft.attr({r:n}).style({opacity:.5}),at=r.invert(o.util.getMousePos(Y).radius);var i=o.util.convertToCartesian(n,f.radialAxis.orientation);ct.text(o.util.round(at)).move([i[0]+_[0],i[1]+_[1]])}).on("mouseout.radial-guide",function(t,e){ft.style({opacity:0}),ut.hide(),lt.hide(),ct.hide()}),t.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(e,r){var i=n.select(this),a=this.style.fill,s="black",l=this.style.opacity||1;if(i.attr({"data-opacity":l}),a&&"none"!==a){i.attr({"data-fill":a}),s=n.hsl(a).darker().toString(),i.style({fill:s,opacity:1});var c={t:o.util.round(e[0]),r:o.util.round(e[1])};A&&(c.t=w[e[0]]);var u="t: "+c.t+", r: "+c.r,h=this.getBoundingClientRect(),f=t.node().getBoundingClientRect(),p=[h.left+h.width/2-V[0]-f.left,h.top+h.height/2-V[1]-f.top];ut.config({color:s}).text(u),ut.move(p)}else a=this.style.stroke||"black",i.attr({"data-stroke":a}),s=n.hsl(a).darker().toString(),i.style({stroke:s,opacity:1})}).on("mousemove.tooltip",function(t,e){if(0!=n.event.which)return!1;n.select(this).attr("data-fill")&&ut.show()}).on("mouseout.tooltip",function(t,e){ut.hide();var r=n.select(this),i=r.attr("data-fill");i?r.style({fill:i,opacity:r.attr("data-opacity")}):r.style({stroke:r.attr("data-stroke"),opacity:r.attr("data-opacity")})})})}(c),this},f.config=function(t){if(!arguments.length)return l;var e=o.util.cloneJson(t);return e.data.forEach(function(t,e){l.data[e]||(l.data[e]={}),i(l.data[e],o.Axis.defaultConfig().data[0]),i(l.data[e],t)}),i(l.layout,o.Axis.defaultConfig().layout),i(l.layout,e.layout),this},f.getLiveConfig=function(){return u},f.getinputConfig=function(){return c},f.radialScale=function(t){return r},f.angularScale=function(t){return s},f.svg=function(){return t},n.rebind(f,h,"on"),f},o.Axis.defaultConfig=function(t,e){return{data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:n.scale.category10().range(),title:null,height:450,width:500,margin:{top:40,right:40,bottom:40,left:40},font:{size:12,color:"gray",outlineColor:"white",family:"Tahoma, sans-serif"},direction:"clockwise",orientation:0,labelOffset:10,radialAxis:{domain:null,orientation:-45,ticksSuffix:"",visible:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}}},o.util={},o.DATAEXTENT="dataExtent",o.AREA="AreaChart",o.LINE="LinePlot",o.DOT="DotPlot",o.BAR="BarChart",o.util._override=function(t,e){for(var r in t)r in e&&(e[r]=t[r])},o.util._extend=function(t,e){for(var r in t)e[r]=t[r]},o.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},o.util.dataFromEquation2=function(t,e){var r=e||6;return n.range(0,360+r,r).map(function(e,r){var n=e*Math.PI/180;return[e,t(n)]})},o.util.dataFromEquation=function(t,e,r){var i=e||6,a=[],o=[];n.range(0,360+i,i).forEach(function(e,r){var n=e*Math.PI/180,i=t(n);a.push(e),o.push(i)});var s={t:a,r:o};return r&&(s.name=r),s},o.util.ensureArray=function(t,e){if("undefined"==typeof t)return null;var r=[].concat(t);return n.range(e).map(function(t,e){return r[e]||r[0]})},o.util.fillArrays=function(t,e,r){return e.forEach(function(e,n){t[e]=o.util.ensureArray(t[e],r)}),t},o.util.cloneJson=function(t){return JSON.parse(JSON.stringify(t))},o.util.validateKeys=function(t,e){"string"==typeof e&&(e=e.split("."));var r=e.shift();return t[r]&&(!e.length||objHasKeys(t[r],e))},o.util.sumArrays=function(t,e){return n.zip(t,e).map(function(t,e){return n.sum(t)})},o.util.arrayLast=function(t){return t[t.length-1]},o.util.arrayEqual=function(t,e){for(var r=Math.max(t.length,e.length,1);r-- >=0&&t[r]===e[r];);return-2===r},o.util.flattenArray=function(t){for(var e=[];!o.util.arrayEqual(e,t);)e=t,t=[].concat.apply([],t);return t},o.util.deduplicate=function(t){return t.filter(function(t,e,r){return r.indexOf(t)==e})},o.util.convertToCartesian=function(t,e){var r=e*Math.PI/180;return[t*Math.cos(r),t*Math.sin(r)]},o.util.round=function(t,e){var r=e||2,n=Math.pow(10,r);return Math.round(t*n)/n},o.util.getMousePos=function(t){var e=n.mouse(t.node()),r=e[0],i=e[1],a={};return a.x=r,a.y=i,a.pos=e,a.angle=180*(Math.atan2(i,r)+Math.PI)/Math.PI,a.radius=Math.sqrt(r*r+i*i),a},o.util.duplicatesCount=function(t){for(var e,r={},n={},i=0,a=t.length;i<a;i++)(e=t[i])in r?(r[e]++,n[e]=r[e]):r[e]=1;return n},o.util.duplicates=function(t){return Object.keys(o.util.duplicatesCount(t))},o.util.translator=function(t,e,r,n){if(n){var i=r.slice();r=e,e=i}var a=e.reduce(function(t,e){if("undefined"!=typeof t)return t[e]},t);"undefined"!=typeof a&&(e.reduce(function(t,r,n){if("undefined"!=typeof t)return n===e.length-1&&delete t[r],t[r]},t),r.reduce(function(t,e,n){return"undefined"==typeof t[e]&&(t[e]={}),n===r.length-1&&(t[e]=a),t[e]},t))},o.PolyChart=function(){var t=[o.PolyChart.defaultConfig()],e=n.dispatch("hover"),r={solid:"none",dash:[5,2],dot:[2,5]};function a(){var e=t[0].geometryConfig,i=e.container;"string"==typeof i&&(i=n.select(i)),i.datum(t).each(function(t,i){var a=!!t[0].data.yStack,o=t.map(function(t,e){return a?n.zip(t.data.t[0],t.data.r[0],t.data.yStack[0]):n.zip(t.data.t[0],t.data.r[0])}),s=e.angularScale,l=e.radialScale.domain()[0],c={bar:function(r,i,a){var o=t[a].data,l=e.radialScale(r[1])-e.radialScale(0),c=e.radialScale(r[2]||0),u=o.barWidth;n.select(this).attr({class:"mark bar",d:"M"+[[l+c,-u/2],[l+c,u/2],[c,u/2],[c,-u/2]].join("L")+"Z",transform:function(t,r){return"rotate("+(e.orientation+s(t[0]))+")"}})}};c.dot=function(r,i,a){var o=r[2]?[r[0],r[1]+r[2]]:r,s=n.svg.symbol().size(t[a].data.dotSize).type(t[a].data.dotType)(r,i);n.select(this).attr({class:"mark dot",d:s,transform:function(t,r){var n,i,a,s=(n=function(t,r){var n=e.radialScale(t[1]),i=(e.angularScale(t[0])+e.orientation)*Math.PI/180;return{r:n,t:i}}(o),i=n.r*Math.cos(n.t),a=n.r*Math.sin(n.t),{x:i,y:a});return"translate("+[s.x,s.y]+")"}})};var u=n.svg.line.radial().interpolate(t[0].data.lineInterpolation).radius(function(t){return e.radialScale(t[1])}).angle(function(t){return e.angularScale(t[0])*Math.PI/180});c.line=function(r,i,a){var s=r[2]?o[a].map(function(t,e){return[t[0],t[1]+t[2]]}):o[a];if(n.select(this).each(c.dot).style({opacity:function(e,r){return+t[a].data.dotVisible},fill:d.stroke(r,i,a)}).attr({class:"mark dot"}),!(i>0)){var l=n.select(this.parentNode).selectAll("path.line").data([0]);l.enter().insert("path"),l.attr({class:"line",d:u(s),transform:function(t,r){return"rotate("+(e.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(t,e){return d.fill(r,i,a)},"fill-opacity":0,stroke:function(t,e){return d.stroke(r,i,a)},"stroke-width":function(t,e){return d["stroke-width"](r,i,a)},"stroke-dasharray":function(t,e){return d["stroke-dasharray"](r,i,a)},opacity:function(t,e){return d.opacity(r,i,a)},display:function(t,e){return d.display(r,i,a)}})}};var h=e.angularScale.range(),f=Math.abs(h[1]-h[0])/o[0].length*Math.PI/180,p=n.svg.arc().startAngle(function(t){return-f/2}).endAngle(function(t){return f/2}).innerRadius(function(t){return e.radialScale(l+(t[2]||0))}).outerRadius(function(t){return e.radialScale(l+(t[2]||0))+e.radialScale(t[1])});c.arc=function(t,r,i){n.select(this).attr({class:"mark arc",d:p,transform:function(t,r){return"rotate("+(e.orientation+s(t[0])+90)+")"}})};var d={fill:function(e,r,n){return t[n].data.color},stroke:function(e,r,n){return t[n].data.strokeColor},"stroke-width":function(e,r,n){return t[n].data.strokeSize+"px"},"stroke-dasharray":function(e,n,i){return r[t[i].data.strokeDash]},opacity:function(e,r,n){return t[n].data.opacity},display:function(e,r,n){return"undefined"==typeof t[n].data.visible||t[n].data.visible?"block":"none"}},g=n.select(this).selectAll("g.layer").data(o);g.enter().append("g").attr({class:"layer"});var v=g.selectAll("path.mark").data(function(t,e){return t});v.enter().append("path").attr({class:"mark"}),v.style(d).each(c[e.geometryType]),v.exit().remove(),g.exit().remove()})}return a.config=function(e){return arguments.length?(e.forEach(function(e,r){t[r]||(t[r]={}),i(t[r],o.PolyChart.defaultConfig()),i(t[r],e)}),this):t},a.getColorScale=function(){},n.rebind(a,e,"on"),a},o.PolyChart.defaultConfig=function(){return{data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:n.scale.category20()}}},o.BarChart=function(){return o.PolyChart()},o.BarChart.defaultConfig=function(){return{geometryConfig:{geometryType:"bar"}}},o.AreaChart=function(){return o.PolyChart()},o.AreaChart.defaultConfig=function(){return{geometryConfig:{geometryType:"arc"}}},o.DotPlot=function(){return o.PolyChart()},o.DotPlot.defaultConfig=function(){return{geometryConfig:{geometryType:"dot",dotType:"circle"}}},o.LinePlot=function(){return o.PolyChart()},o.LinePlot.defaultConfig=function(){return{geometryConfig:{geometryType:"line"}}},o.Legend=function(){var t=o.Legend.defaultConfig(),e=n.dispatch("hover");function r(){var e=t.legendConfig,a=t.data.map(function(t,r){return[].concat(t).map(function(t,n){var a=i({},e.elements[r]);return a.name=t,a.color=[].concat(e.elements[r].color)[n],a})}),o=n.merge(a);o=o.filter(function(t,r){return e.elements[r]&&(e.elements[r].visibleInLegend||"undefined"==typeof e.elements[r].visibleInLegend)}),e.reverseOrder&&(o=o.reverse());var s=e.container;("string"==typeof s||s.nodeName)&&(s=n.select(s));var l=o.map(function(t,e){return t.color}),c=e.fontSize,u=null==e.isContinuous?"number"==typeof o[0]:e.isContinuous,h=u?e.height:c*o.length,f=s.classed("legend-group",!0).selectAll("svg").data([0]),p=f.enter().append("svg").attr({width:300,height:h+c,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});p.append("g").classed("legend-axis",!0),p.append("g").classed("legend-marks",!0);var d=n.range(o.length),g=n.scale[u?"linear":"ordinal"]().domain(d).range(l),v=n.scale[u?"linear":"ordinal"]().domain(d)[u?"range":"rangePoints"]([0,h]);if(u){var m=f.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(l);m.enter().append("stop"),m.attr({offset:function(t,e){return e/(l.length-1)*100+"%"}}).style({"stop-color":function(t,e){return t}}),f.append("rect").classed("legend-mark",!0).attr({height:e.height,width:e.colorBandWidth,fill:"url(#grad1)"})}else{var y=f.select(".legend-marks").selectAll("path.legend-mark").data(o);y.enter().append("path").classed("legend-mark",!0),y.attr({transform:function(t,e){return"translate("+[c/2,v(e)+c/2]+")"},d:function(t,e){var r,i,a,o=t.symbol;return a=3*(i=c),"line"===(r=o)?"M"+[[-i/2,-i/12],[i/2,-i/12],[i/2,i/12],[-i/2,i/12]]+"Z":-1!=n.svg.symbolTypes.indexOf(r)?n.svg.symbol().type(r).size(a)():n.svg.symbol().type("square").size(a)()},fill:function(t,e){return g(e)}}),y.exit().remove()}var x=n.svg.axis().scale(v).orient("right"),b=f.select("g.legend-axis").attr({transform:"translate("+[u?e.colorBandWidth:c,c/2]+")"}).call(x);return b.selectAll(".domain").style({fill:"none",stroke:"none"}),b.selectAll("line").style({fill:"none",stroke:u?e.textColor:"none"}),b.selectAll("text").style({fill:e.textColor,"font-size":e.fontSize}).text(function(t,e){return o[e].name}),r}return r.config=function(e){return arguments.length?(i(t,e),this):t},n.rebind(r,e,"on"),r},o.Legend.defaultConfig=function(t,e){return{data:["a","b","c"],legendConfig:{elements:[{symbol:"line",color:"red"},{symbol:"square",color:"yellow"},{symbol:"diamond",color:"limegreen"}],height:150,colorBandWidth:30,fontSize:12,container:"body",isContinuous:null,textColor:"grey",reverseOrder:!1}}},o.tooltipPanel=function(){var t,e,r,a={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},s="tooltip-"+o.tooltipPanel.uid++,l=10,c=function(){var n=(t=a.container.selectAll("g."+s).data([0])).enter().append("g").classed(s,!0).style({"pointer-events":"none",display:"none"});return r=n.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),e=n.append("text").attr({dx:a.padding+l,dy:.3*+a.fontSize}),c};return c.text=function(i){var o=n.hsl(a.color).l,s=o>=.5?"#aaa":"white",u=o>=.5?"black":"white",h=i||"";e.style({fill:u,"font-size":a.fontSize+"px"}).text(h);var f=a.padding,p=e.node().getBBox(),d={fill:a.color,stroke:s,"stroke-width":"2px"},g=p.width+2*f+l,v=p.height+2*f;return r.attr({d:"M"+[[l,-v/2],[l,-v/4],[a.hasTick?0:l,0],[l,v/4],[l,v/2],[g,v/2],[g,-v/2]].join("L")+"Z"}).style(d),t.attr({transform:"translate("+[l,-v/2+2*f]+")"}),t.style({display:"block"}),c},c.move=function(e){if(t)return t.attr({transform:"translate("+[e[0],e[1]]+")"}).style({display:"block"}),c},c.hide=function(){if(t)return t.style({display:"none"}),c},c.show=function(){if(t)return t.style({display:"block"}),c},c.config=function(t){return i(a,t),c},c},o.tooltipPanel.uid=1,o.adapter={},o.adapter.plotly=function(){var t={convert:function(t,e){var r={};if(t.data&&(r.data=t.data.map(function(t,r){var n=i({},t);return[[n,["marker","color"],["color"]],[n,["marker","opacity"],["opacity"]],[n,["marker","line","color"],["strokeColor"]],[n,["marker","line","dash"],["strokeDash"]],[n,["marker","line","width"],["strokeSize"]],[n,["marker","symbol"],["dotType"]],[n,["marker","size"],["dotSize"]],[n,["marker","barWidth"],["barWidth"]],[n,["line","interpolation"],["lineInterpolation"]],[n,["showlegend"],["visibleInLegend"]]].forEach(function(t,r){o.util.translator.apply(null,t.concat(e))}),e||delete n.marker,e&&delete n.groupId,e?("LinePlot"===n.geometry?(n.type="scatter",!0===n.dotVisible?(delete n.dotVisible,n.mode="lines+markers"):n.mode="lines"):"DotPlot"===n.geometry?(n.type="scatter",n.mode="markers"):"AreaChart"===n.geometry?n.type="area":"BarChart"===n.geometry&&(n.type="bar"),delete n.geometry):("scatter"===n.type?"lines"===n.mode?n.geometry="LinePlot":"markers"===n.mode?n.geometry="DotPlot":"lines+markers"===n.mode&&(n.geometry="LinePlot",n.dotVisible=!0):"area"===n.type?n.geometry="AreaChart":"bar"===n.type&&(n.geometry="BarChart"),delete n.mode,delete n.type),n}),!e&&t.layout&&"stack"===t.layout.barmode)){var a=o.util.duplicates(r.data.map(function(t,e){return t.geometry}));r.data.forEach(function(t,e){var n=a.indexOf(t.geometry);-1!=n&&(r.data[e].groupId=n)})}if(t.layout){var s=i({},t.layout);if([[s,["plot_bgcolor"],["backgroundColor"]],[s,["showlegend"],["showLegend"]],[s,["radialaxis"],["radialAxis"]],[s,["angularaxis"],["angularAxis"]],[s.angularaxis,["showline"],["gridLinesVisible"]],[s.angularaxis,["showticklabels"],["labelsVisible"]],[s.angularaxis,["nticks"],["ticksCount"]],[s.angularaxis,["tickorientation"],["tickOrientation"]],[s.angularaxis,["ticksuffix"],["ticksSuffix"]],[s.angularaxis,["range"],["domain"]],[s.angularaxis,["endpadding"],["endPadding"]],[s.radialaxis,["showline"],["gridLinesVisible"]],[s.radialaxis,["tickorientation"],["tickOrientation"]],[s.radialaxis,["ticksuffix"],["ticksSuffix"]],[s.radialaxis,["range"],["domain"]],[s.angularAxis,["showline"],["gridLinesVisible"]],[s.angularAxis,["showticklabels"],["labelsVisible"]],[s.angularAxis,["nticks"],["ticksCount"]],[s.angularAxis,["tickorientation"],["tickOrientation"]],[s.angularAxis,["ticksuffix"],["ticksSuffix"]],[s.angularAxis,["range"],["domain"]],[s.angularAxis,["endpadding"],["endPadding"]],[s.radialAxis,["showline"],["gridLinesVisible"]],[s.radialAxis,["tickorientation"],["tickOrientation"]],[s.radialAxis,["ticksuffix"],["ticksSuffix"]],[s.radialAxis,["range"],["domain"]],[s.font,["outlinecolor"],["outlineColor"]],[s.legend,["traceorder"],["reverseOrder"]],[s,["labeloffset"],["labelOffset"]],[s,["defaultcolorrange"],["defaultColorRange"]]].forEach(function(t,r){o.util.translator.apply(null,t.concat(e))}),e?("undefined"!=typeof s.tickLength&&(s.angularaxis.ticklen=s.tickLength,delete s.tickLength),s.tickColor&&(s.angularaxis.tickcolor=s.tickColor,delete s.tickColor)):(s.angularAxis&&"undefined"!=typeof s.angularAxis.ticklen&&(s.tickLength=s.angularAxis.ticklen),s.angularAxis&&"undefined"!=typeof s.angularAxis.tickcolor&&(s.tickColor=s.angularAxis.tickcolor)),s.legend&&"boolean"!=typeof s.legend.reverseOrder&&(s.legend.reverseOrder="normal"!=s.legend.reverseOrder),s.legend&&"boolean"==typeof s.legend.traceorder&&(s.legend.traceorder=s.legend.traceorder?"reversed":"normal",delete s.legend.reverseOrder),s.margin&&"undefined"!=typeof s.margin.t){var l=["t","r","b","l","pad"],c=["top","right","bottom","left","pad"],u={};n.entries(s.margin).forEach(function(t,e){u[c[l.indexOf(t.key)]]=t.value}),s.margin=u}e&&(delete s.needsEndSpacing,delete s.minorTickColor,delete s.minorTicks,delete s.angularaxis.ticksCount,delete s.angularaxis.ticksCount,delete s.angularaxis.ticksStep,delete s.angularaxis.rewriteTicks,delete s.angularaxis.nticks,delete s.radialaxis.ticksCount,delete s.radialaxis.ticksCount,delete s.radialaxis.ticksStep,delete s.radialaxis.rewriteTicks,delete s.radialaxis.nticks),r.layout=s}return r}};return t}},{"../../../constants/alignment":669,"../../../lib":697,d3:151}],817:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../../lib"),a=t("../../../components/color"),o=t("./micropolar"),s=t("./undo_manager"),l=i.extendDeepAll,c=e.exports={};c.framework=function(t){var e,r,i,a,u,h=new s;function f(r,s){return s&&(u=s),n.select(n.select(u).node().parentNode).selectAll(".svg-container>*:not(.chart-root)").remove(),e=e?l(e,r):r,i||(i=o.Axis()),a=o.adapter.plotly().convert(e),i.config(a).render(u),t.data=e.data,t.layout=e.layout,c.fillLayout(t),e}return f.isPolar=!0,f.svg=function(){return i.svg()},f.getConfig=function(){return e},f.getLiveConfig=function(){return o.adapter.plotly().convert(i.getLiveConfig(),!0)},f.getLiveScales=function(){return{t:i.angularScale(),r:i.radialScale()}},f.setUndoPoint=function(){var t,n,i=this,a=o.util.cloneJson(e);t=a,n=r,h.add({undo:function(){n&&i(n)},redo:function(){i(t)}}),r=o.util.cloneJson(a)},f.undo=function(){h.undo()},f.redo=function(){h.redo()},f},c.fillLayout=function(t){var e=n.select(t).selectAll(".plot-container"),r=e.selectAll(".svg-container"),i=t.framework&&t.framework.svg&&t.framework.svg(),o={width:800,height:600,paper_bgcolor:a.background,_container:e,_paperdiv:r,_paper:i};t._fullLayout=l(o,t.layout)}},{"../../../components/color":574,"../../../lib":697,"./micropolar":816,"./undo_manager":818,d3:151}],818:[function(t,e,r){"use strict";e.exports=function(){var t,e=[],r=-1,n=!1;function i(t,e){return t?(n=!0,t[e](),n=!1,this):this}return{add:function(t){return n?this:(e.splice(r+1,e.length-r),e.push(t),r=e.length-1,this)},setCallback:function(e){t=e},undo:function(){var n=e[r];return n?(i(n,"undo"),r-=1,t&&t(n.undo),this):this},redo:function(){var n=e[r+1];return n?(i(n,"redo"),r+=1,t&&t(n.redo),this):this},clear:function(){e=[],r=-1},hasUndo:function(){return-1!==r},hasRedo:function(){return r<e.length-1},getCommands:function(){return e},getPreviousCommand:function(){return e[r-1]},getIndex:function(){return r}}}},{}],819:[function(t,e,r){"use strict";var n=t("d3"),i=t("tinycolor2"),a=t("../../registry"),o=t("../../lib"),s=t("../../components/color"),l=t("../../components/drawing"),c=t("../plots"),u=t("../../plots/cartesian/axes"),h=t("../cartesian/set_convert"),f=t("./set_convert"),p=t("../cartesian/autorange").doAutoRange,d=t("../cartesian/dragbox"),g=t("../../components/dragelement"),v=t("../../components/fx"),m=t("../../components/titles"),y=t("../cartesian/select").prepSelect,x=t("../cartesian/select").selectOnClick,b=t("../cartesian/select").clearSelect,_=t("../../lib/setcursor"),w=t("../../lib/clear_gl_canvases"),k=t("../../plot_api/subroutines").redrawReglTraces,A=t("../../constants/alignment").MID_SHIFT,M=t("./constants"),T=t("./helpers"),S=o._,E=o.mod,C=o.deg2rad,L=o.rad2deg;function z(t,e){this.id=e,this.gd=t,this._hasClipOnAxisFalse=null,this.vangles=null,this.radialAxisAngle=null,this.traceHash={},this.layers={},this.clipPaths={},this.clipIds={},this.viewInitial={};var r=t._fullLayout,n="clip"+r._uid+e;this.clipIds.forTraces=n+"-for-traces",this.clipPaths.forTraces=r._clips.append("clipPath").attr("id",this.clipIds.forTraces),this.clipPaths.forTraces.append("path"),this.framework=r._polarlayer.append("g").attr("class",e),this.radialTickLayout=null,this.angularTickLayout=null}var O=z.prototype;function I(t){var e=t.ticks+String(t.ticklen)+String(t.showticklabels);return"side"in t&&(e+=t.side),e}function D(t,e){return e[o.findIndexOfMin(e,function(e){return o.angleDist(t,e)})]}function P(t,e,r){return e?(t.attr("display",null),t.attr(r)):t&&t.attr("display","none"),t}function R(t,e){return"translate("+t+","+e+")"}function F(t){return"rotate("+t+")"}e.exports=function(t,e){return new z(t,e)},O.plot=function(t,e){var r=e[this.id];this._hasClipOnAxisFalse=!1;for(var n=0;n<t.length;n++){if(!1===t[n][0].trace.cliponaxis){this._hasClipOnAxisFalse=!0;break}}this.updateLayers(e,r),this.updateLayout(e,r),c.generalUpdatePerTraceModule(this.gd,this,t,r),this.updateFx(e,r)},O.updateLayers=function(t,e){var r=this.layers,i=e.radialaxis,a=e.angularaxis,o=M.layerNames,s=o.indexOf("frontplot"),l=o.slice(0,s),c="below traces"===a.layer,u="below traces"===i.layer;c&&l.push("angular-line"),u&&l.push("radial-line"),c&&l.push("angular-axis"),u&&l.push("radial-axis"),l.push("frontplot"),c||l.push("angular-line"),u||l.push("radial-line"),c||l.push("angular-axis"),u||l.push("radial-axis");var h=this.framework.selectAll(".polarsublayer").data(l,String);h.enter().append("g").attr("class",function(t){return"polarsublayer "+t}).each(function(t){var e=r[t]=n.select(this);switch(t){case"frontplot":e.append("g").classed("barlayer",!0),e.append("g").classed("scatterlayer",!0);break;case"backplot":e.append("g").classed("maplayer",!0);break;case"plotbg":r.bg=e.append("path");break;case"radial-grid":case"angular-grid":e.style("fill","none");break;case"radial-line":e.append("line").style("fill","none");break;case"angular-line":e.append("path").style("fill","none")}}),h.order()},O.updateLayout=function(t,e){var r=this.layers,n=t._size,i=e.radialaxis,a=e.angularaxis,o=e.domain.x,c=e.domain.y;this.xOffset=n.l+n.w*o[0],this.yOffset=n.t+n.h*(1-c[1]);var u=this.xLength=n.w*(o[1]-o[0]),h=this.yLength=n.h*(c[1]-c[0]),f=e.sector;this.sectorInRad=f.map(C);var p,d,g,v,m,y=this.sectorBBox=function(t){var e,r,n,i,a=t[0],o=t[1]-a,s=E(a,360),l=s+o,c=Math.cos(C(s)),u=Math.sin(C(s)),h=Math.cos(C(l)),f=Math.sin(C(l));i=s<=90&&l>=90||s>90&&l>=450?1:u<=0&&f<=0?0:Math.max(u,f);e=s<=180&&l>=180||s>180&&l>=540?-1:c>=0&&h>=0?0:Math.min(c,h);r=s<=270&&l>=270||s>270&&l>=630?-1:u>=0&&f>=0?0:Math.min(u,f);n=l>=360?1:c<=0&&h<=0?0:Math.max(c,h);return[e,r,n,i]}(f),x=y[2]-y[0],b=y[3]-y[1],_=h/u,w=Math.abs(b/x);_>w?(p=u,m=(h-(d=u*w))/n.h/2,g=[o[0],o[1]],v=[c[0]+m,c[1]-m]):(d=h,m=(u-(p=h/w))/n.w/2,g=[o[0]+m,o[1]-m],v=[c[0],c[1]]),this.xLength2=p,this.yLength2=d,this.xDomain2=g,this.yDomain2=v;var k=this.xOffset2=n.l+n.w*g[0],A=this.yOffset2=n.t+n.h*(1-v[1]),M=this.radius=p/x,T=this.innerRadius=e.hole*M,S=this.cx=k-M*y[0],L=this.cy=A+M*y[3],z=this.cxx=S-k,O=this.cyy=L-A;this.radialAxis=this.mockAxis(t,e,i,{_id:"x",side:{counterclockwise:"top",clockwise:"bottom"}[i.side],domain:[T/n.w,M/n.w]}),this.angularAxis=this.mockAxis(t,e,a,{side:"right",domain:[0,Math.PI],autorange:!1}),this.doAutoRange(t,e),this.updateAngularAxis(t,e),this.updateRadialAxis(t,e),this.updateRadialAxisTitle(t,e),this.xaxis=this.mockCartesianAxis(t,e,{_id:"x",domain:g}),this.yaxis=this.mockCartesianAxis(t,e,{_id:"y",domain:v});var I=this.pathSubplot();this.clipPaths.forTraces.select("path").attr("d",I).attr("transform",R(z,O)),r.frontplot.attr("transform",R(k,A)).call(l.setClipUrl,this._hasClipOnAxisFalse?null:this.clipIds.forTraces,this.gd),r.bg.attr("d",I).attr("transform",R(S,L)).call(s.fill,e.bgcolor)},O.mockAxis=function(t,e,r,n){var i=o.extendFlat({anchor:"free",position:0},r,n);return f(i,e,t),i},O.mockCartesianAxis=function(t,e,r){var n=this,i=r._id,a=o.extendFlat({type:"linear"},r);h(a,t);var s={x:[0,2],y:[1,3]};return a.setRange=function(){var t=n.sectorBBox,r=s[i],o=n.radialAxis._rl,l=(o[1]-o[0])/(1-e.hole);a.range=[t[r[0]]*l,t[r[1]]*l]},a.isPtWithinRange="x"===i?function(t){return n.isPtInside(t)}:function(){return!0},a.setRange(),a.setScale(),a},O.doAutoRange=function(t,e){var r=this.gd,n=this.radialAxis,i=e.radialaxis;n.setScale(),p(r,n);var a=n.range;i.range=a.slice(),i._input.range=a.slice(),n._rl=[n.r2l(a[0],null,"gregorian"),n.r2l(a[1],null,"gregorian")]},O.updateRadialAxis=function(t,e){var r=this,n=r.gd,i=r.layers,a=r.radius,l=r.innerRadius,c=r.cx,h=r.cy,f=e.radialaxis,p=E(e.sector[0],360),d=r.radialAxis,g=l<a;r.fillViewInitialKey("radialaxis.angle",f.angle),r.fillViewInitialKey("radialaxis.range",d.range.slice()),d.setGeometry(),"auto"===d.tickangle&&p>90&&p<=270&&(d.tickangle=180);var v=function(t){return"translate("+(d.l2p(t.x)+l)+",0)"},m=I(f);if(r.radialTickLayout!==m&&(i["radial-axis"].selectAll(".xtick").remove(),r.radialTickLayout=m),g){d.setScale();var y=u.calcTicks(d),x=u.clipEnds(d,y),b=u.getTickSigns(d)[2];u.drawTicks(n,d,{vals:y,layer:i["radial-axis"],path:u.makeTickPath(d,0,b),transFn:v,crisp:!1}),u.drawGrid(n,d,{vals:x,layer:i["radial-grid"],path:function(t){return r.pathArc(d.r2p(t.x)+l)},transFn:o.noop,crisp:!1}),u.drawLabels(n,d,{vals:y,layer:i["radial-axis"],transFn:v,labelFns:u.makeLabelFns(d,0)})}var _=r.radialAxisAngle=r.vangles?L(D(C(f.angle),r.vangles)):f.angle,w=R(c,h),k=w+F(-_);P(i["radial-axis"],g&&(f.showticklabels||f.ticks),{transform:k}),P(i["radial-grid"],g&&f.showgrid,{transform:w}),P(i["radial-line"].select("line"),g&&f.showline,{x1:l,y1:0,x2:a,y2:0,transform:k}).attr("stroke-width",f.linewidth).call(s.stroke,f.linecolor)},O.updateRadialAxisTitle=function(t,e,r){var n=this.gd,i=this.radius,a=this.cx,o=this.cy,s=e.radialaxis,c=this.id+"title",u=void 0!==r?r:this.radialAxisAngle,h=C(u),f=Math.cos(h),p=Math.sin(h),d=0;if(s.title){var g=l.bBox(this.layers["radial-axis"].node()).height,v=s.title.font.size;d="counterclockwise"===s.side?-g-.4*v:g+.8*v}this.layers["radial-axis-title"]=m.draw(n,c,{propContainer:s,propName:this.id+".radialaxis.title",placeholder:S(n,"Click to enter radial axis title"),attributes:{x:a+i/2*f+d*p,y:o-i/2*p+d*f,"text-anchor":"middle"},transform:{rotate:-u}})},O.updateAngularAxis=function(t,e){var r=this,n=r.gd,i=r.layers,a=r.radius,l=r.innerRadius,c=r.cx,h=r.cy,f=e.angularaxis,p=r.angularAxis;r.fillViewInitialKey("angularaxis.rotation",f.rotation),p.setGeometry(),p.setScale();var d=function(t){return p.t2g(t.x)};"linear"===p.type&&"radians"===p.thetaunit&&(p.tick0=L(p.tick0),p.dtick=L(p.dtick));var g=function(t){return R(c+a*Math.cos(t),h-a*Math.sin(t))},v=u.makeLabelFns(p,0).labelStandoff,m={xFn:function(t){var e=d(t);return Math.cos(e)*v},yFn:function(t){var e=d(t),r=Math.sin(e)>0?.2:1;return-Math.sin(e)*(v+t.fontSize*r)+Math.abs(Math.cos(e))*(t.fontSize*A)},anchorFn:function(t){var e=d(t),r=Math.cos(e);return Math.abs(r)<.1?"middle":r>0?"start":"end"},heightFn:function(t,e,r){var n=d(t);return-.5*(1+Math.sin(n))*r}},y=I(f);r.angularTickLayout!==y&&(i["angular-axis"].selectAll("."+p._id+"tick").remove(),r.angularTickLayout=y);var x,b=u.calcTicks(p);if("linear"===e.gridshape?(x=b.map(d),o.angleDelta(x[0],x[1])<0&&(x=x.slice().reverse())):x=null,r.vangles=x,"category"===p.type&&(b=b.filter(function(t){return o.isAngleInsideSector(d(t),r.sectorInRad)})),p.visible){var _="inside"===p.ticks?-1:1,w=(p.linewidth||1)/2;u.drawTicks(n,p,{vals:b,layer:i["angular-axis"],path:"M"+_*w+",0h"+_*p.ticklen,transFn:function(t){var e=d(t);return g(e)+F(-L(e))},crisp:!1}),u.drawGrid(n,p,{vals:b,layer:i["angular-grid"],path:function(t){var e=d(t),r=Math.cos(e),n=Math.sin(e);return"M"+[c+l*r,h-l*n]+"L"+[c+a*r,h-a*n]},transFn:o.noop,crisp:!1}),u.drawLabels(n,p,{vals:b,layer:i["angular-axis"],repositionOnUpdate:!0,transFn:function(t){return g(d(t))},labelFns:m})}P(i["angular-line"].select("path"),f.showline,{d:r.pathSubplot(),transform:R(c,h)}).attr("stroke-width",f.linewidth).call(s.stroke,f.linecolor)},O.updateFx=function(t,e){this.gd._context.staticPlot||(this.updateAngularDrag(t),this.updateRadialDrag(t,e,0),this.updateRadialDrag(t,e,1),this.updateMainDrag(t))},O.updateMainDrag=function(t){var e=this,r=e.gd,o=e.layers,s=t._zoomlayer,l=M.MINZOOM,c=M.OFFEDGE,u=e.radius,h=e.innerRadius,f=e.cx,p=e.cy,m=e.cxx,_=e.cyy,w=e.sectorInRad,k=e.vangles,A=e.radialAxis,S=T.clampTiny,E=T.findXYatLength,C=T.findEnclosingVertexAngles,L=M.cornerHalfWidth,z=M.cornerLen/2,O=d.makeDragger(o,"path","maindrag","crosshair");n.select(O).attr("d",e.pathSubplot()).attr("transform",R(f,p));var I,D,P,F,B,N,j,V,U,q={element:O,gd:r,subplot:e.id,plotinfo:{id:e.id,xaxis:e.xaxis,yaxis:e.yaxis},xaxes:[e.xaxis],yaxes:[e.yaxis]};function H(t,e){return Math.sqrt(t*t+e*e)}function G(t,e){return H(t-m,e-_)}function Y(t,e){return Math.atan2(_-e,t-m)}function W(t,e){return[t*Math.cos(e),t*Math.sin(-e)]}function X(t,r){if(0===t)return e.pathSector(2*L);var n=z/t,i=r-n,a=r+n,o=Math.max(0,Math.min(t,u)),s=o-L,l=o+L;return"M"+W(s,i)+"A"+[s,s]+" 0,0,0 "+W(s,a)+"L"+W(l,a)+"A"+[l,l]+" 0,0,1 "+W(l,i)+"Z"}function Z(t,r,n){if(0===t)return e.pathSector(2*L);var i,a,o=W(t,r),s=W(t,n),l=S((o[0]+s[0])/2),c=S((o[1]+s[1])/2);if(l&&c){var u=c/l,h=-1/u,f=E(L,u,l,c);i=E(z,h,f[0][0],f[0][1]),a=E(z,h,f[1][0],f[1][1])}else{var p,d;c?(p=z,d=L):(p=L,d=z),i=[[l-p,c-d],[l+p,c-d]],a=[[l-p,c+d],[l+p,c+d]]}return"M"+i.join("L")+"L"+a.reverse().join("L")+"Z"}function $(t,e){return e=Math.max(Math.min(e,u),h),t<c?t=0:u-t<c?t=u:e<c?e=0:u-e<c&&(e=u),Math.abs(e-t)>l?(t<e?(P=t,F=e):(P=e,F=t),!0):(P=null,F=null,!1)}function J(t,e){t=t||B,e=e||"M0,0Z",V.attr("d",t),U.attr("d",e),d.transitionZoombox(V,U,N,j),N=!0}function K(t,r){var n,i,a=I+t,o=D+r,s=G(I,D),l=Math.min(G(a,o),u),c=Y(I,D);$(s,l)&&(n=B+e.pathSector(F),P&&(n+=e.pathSector(P)),i=X(P,c)+X(F,c)),J(n,i)}function Q(t,e,r,n){var i=T.findIntersectionXY(r,n,r,[t-m,_-e]);return H(i[0],i[1])}function tt(t,r){var n,i,a=I+t,o=D+r,s=Y(I,D),l=Y(a,o),c=C(s,k),h=C(l,k);$(Q(I,D,c[0],c[1]),Math.min(Q(a,o,h[0],h[1]),u))&&(n=B+e.pathSector(F),P&&(n+=e.pathSector(P)),i=[Z(P,c[0],c[1]),Z(F,c[0],c[1])].join(" ")),J(n,i)}function et(){if(d.removeZoombox(r),null!==P&&null!==F){d.showDoubleClickNotifier(r);var t=A._rl,n=(t[1]-t[0])/(1-h/u)/u,i=[t[0]+(P-h)*n,t[0]+(F-h)*n];a.call("_guiRelayout",r,e.id+".radialaxis.range",i)}}function rt(t,n){var i=r._fullLayout.clickmode;if(d.removeZoombox(r),2===t){var o={};for(var s in e.viewInitial)o[e.id+"."+s]=e.viewInitial[s];r.emit("plotly_doubleclick",null),a.call("_guiRelayout",r,o)}i.indexOf("select")>-1&&1===t&&x(n,r,[e.xaxis],[e.yaxis],e.id,q),i.indexOf("event")>-1&&v.click(r,n,e.id)}q.prepFn=function(t,n,a){var o=r._fullLayout.dragmode,l=O.getBoundingClientRect();if(I=n-l.left,D=a-l.top,k){var c=T.findPolygonOffset(u,w[0],w[1],k);I+=m+c[0],D+=_+c[1]}switch(o){case"zoom":q.moveFn=k?tt:K,q.clickFn=rt,q.doneFn=et,function(){P=null,F=null,B=e.pathSubplot(),N=!1;var t=r._fullLayout[e.id];j=i(t.bgcolor).getLuminance(),(V=d.makeZoombox(s,j,f,p,B)).attr("fill-rule","evenodd"),U=d.makeCorners(s,f,p),b(s)}();break;case"select":case"lasso":y(t,n,a,q,o)}},O.onmousemove=function(t){v.hover(r,t,e.id),r._fullLayout._lasthover=O,r._fullLayout._hoversubplot=e.id},O.onmouseout=function(t){r._dragging||g.unhover(r,t)},g.init(q)},O.updateRadialDrag=function(t,e,r){var i=this,s=i.gd,l=i.layers,c=i.radius,u=i.innerRadius,h=i.cx,f=i.cy,p=i.radialAxis,v=M.radialDragBoxSize,m=v/2;if(p.visible){var y,x,_,A=C(i.radialAxisAngle),T=p._rl,S=T[0],E=T[1],z=T[r],O=.75*(T[1]-T[0])/(1-e.hole)/c;r?(y=h+(c+m)*Math.cos(A),x=f-(c+m)*Math.sin(A),_="radialdrag"):(y=h+(u-m)*Math.cos(A),x=f-(u-m)*Math.sin(A),_="radialdrag-inner");var I,B,N,j=d.makeRectDragger(l,_,"crosshair",-m,-m,v,v),V={element:j,gd:s};P(n.select(j),p.visible&&u<c,{transform:R(y,x)}),V.prepFn=function(){I=null,B=null,N=null,V.moveFn=U,V.doneFn=q,b(t._zoomlayer)},V.clampFn=function(t,e){return Math.sqrt(t*t+e*e)<M.MINDRAG&&(t=0,e=0),[t,e]},g.init(V)}function U(t,e){if(I)I(t,e);else{var r=[t,-e],n=[Math.cos(A),Math.sin(A)],i=Math.abs(o.dot(r,n)/Math.sqrt(o.dot(r,r)));isNaN(i)||(I=i<.5?H:G)}}function q(){null!==B?a.call("_guiRelayout",s,i.id+".radialaxis.angle",B):null!==N&&a.call("_guiRelayout",s,i.id+".radialaxis.range["+r+"]",N)}function H(t,e){if(0!==r){var n=y+t,a=x+e;B=Math.atan2(f-a,n-h),i.vangles&&(B=D(B,i.vangles)),B=L(B);var o=R(h,f)+F(-B);l["radial-axis"].attr("transform",o),l["radial-line"].select("line").attr("transform",o);var s=i.gd._fullLayout,c=s[i.id];i.updateRadialAxisTitle(s,c,B)}}function G(t,e){var n=o.dot([t,-e],[Math.cos(A),Math.sin(A)]);if(N=z-O*n,O>0==(r?N>S:N<E)){var l=s._fullLayout,c=l[i.id];p.range[r]=N,p._rl[r]=N,i.updateRadialAxis(l,c),i.xaxis.setRange(),i.xaxis.setScale(),i.yaxis.setRange(),i.yaxis.setScale();var u=!1;for(var h in i.traceHash){var f=i.traceHash[h],d=o.filterVisible(f);f[0][0].trace._module.plot(s,i,d,c),a.traceIs(h,"gl")&&d.length&&(u=!0)}u&&(w(s),k(s))}else N=null}},O.updateAngularDrag=function(t){var e=this,r=e.gd,i=e.layers,s=e.radius,c=e.angularAxis,u=e.cx,h=e.cy,f=e.cxx,p=e.cyy,v=M.angularDragBoxSize,m=d.makeDragger(i,"path","angulardrag","move"),y={element:m,gd:r};function x(t,e){return Math.atan2(p+v-e,t-f-v)}n.select(m).attr("d",e.pathAnnulus(s,s+v)).attr("transform",R(u,h)).call(_,"move");var A,T,S,E,C,z,O=i.frontplot.select(".scatterlayer").selectAll(".trace"),I=O.selectAll(".point"),D=O.selectAll(".textpoint");function P(t,s){var d=e.gd._fullLayout,g=d[e.id],v=x(A+t,T+s),m=L(v-z);if(E=S+m,i.frontplot.attr("transform",R(e.xOffset2,e.yOffset2)+F([-m,f,p])),e.vangles){C=e.radialAxisAngle+m;var y=R(u,h)+F(-m),b=R(u,h)+F(-C);i.bg.attr("transform",y),i["radial-grid"].attr("transform",y),i["radial-axis"].attr("transform",b),i["radial-line"].select("line").attr("transform",b),e.updateRadialAxisTitle(d,g,C)}else e.clipPaths.forTraces.select("path").attr("transform",R(f,p)+F(m));I.each(function(){var t=n.select(this),e=l.getTranslate(t);t.attr("transform",R(e.x,e.y)+F([m]))}),D.each(function(){var t=n.select(this),e=t.select("text"),r=l.getTranslate(t);t.attr("transform",F([m,e.attr("x"),e.attr("y")])+R(r.x,r.y))}),c.rotation=o.modHalf(E,360),e.updateAngularAxis(d,g),e._hasClipOnAxisFalse&&!o.isFullCircle(e.sectorInRad)&&O.call(l.hideOutsideRangePoints,e);var _=!1;for(var M in e.traceHash)if(a.traceIs(M,"gl")){var P=e.traceHash[M],B=o.filterVisible(P);P[0][0].trace._module.plot(r,e,B,g),B.length&&(_=!0)}_&&(w(r),k(r))}function B(){D.select("text").attr("transform",null);var t={};t[e.id+".angularaxis.rotation"]=E,e.vangles&&(t[e.id+".radialaxis.angle"]=C),a.call("_guiRelayout",r,t)}y.prepFn=function(r,n,i){var a=t[e.id];S=a.angularaxis.rotation;var o=m.getBoundingClientRect();A=n-o.left,T=i-o.top,z=x(A,T),y.moveFn=P,y.doneFn=B,b(t._zoomlayer)},e.vangles&&!o.isFullCircle(e.sectorInRad)&&(y.prepFn=o.noop,_(n.select(m),null)),g.init(y)},O.isPtInside=function(t){var e=this.sectorInRad,r=this.vangles,n=this.angularAxis.c2g(t.theta),i=this.radialAxis,a=i.c2l(t.r),s=i._rl;return(r?T.isPtInsidePolygon:o.isPtInsideSector)(a,n,s,e,r)},O.pathArc=function(t){var e=this.sectorInRad,r=this.vangles;return(r?T.pathPolygon:o.pathArc)(t,e[0],e[1],r)},O.pathSector=function(t){var e=this.sectorInRad,r=this.vangles;return(r?T.pathPolygon:o.pathSector)(t,e[0],e[1],r)},O.pathAnnulus=function(t,e){var r=this.sectorInRad,n=this.vangles;return(n?T.pathPolygonAnnulus:o.pathAnnulus)(t,e,r[0],r[1],n)},O.pathSubplot=function(){var t=this.innerRadius,e=this.radius;return t?this.pathAnnulus(t,e):this.pathSector(e)},O.fillViewInitialKey=function(t,e){t in this.viewInitial||(this.viewInitial[t]=e)}},{"../../components/color":574,"../../components/dragelement":592,"../../components/drawing":595,"../../components/fx":613,"../../components/titles":662,"../../constants/alignment":669,"../../lib":697,"../../lib/clear_gl_canvases":682,"../../lib/setcursor":717,"../../plot_api/subroutines":736,"../../plots/cartesian/axes":745,"../../registry":826,"../cartesian/autorange":744,"../cartesian/dragbox":753,"../cartesian/select":762,"../cartesian/set_convert":763,"../plots":807,"./constants":808,"./helpers":809,"./set_convert":820,d3:151,tinycolor2:518}],820:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../cartesian/set_convert"),a=n.deg2rad,o=n.rad2deg;e.exports=function(t,e,r){switch(i(t,r),t._id){case"x":case"radialaxis":!function(t,e){var r=e._subplot;t.setGeometry=function(){var e=t._rl[0],n=t._rl[1],i=r.innerRadius,a=(r.radius-i)/(n-e),o=i/a,s=e>n?function(t){return t<=0}:function(t){return t>=0};t.c2g=function(r){var n=t.c2l(r)-e;return(s(n)?n:0)+o},t.g2c=function(r){return t.l2c(r+e-o)},t.g2p=function(t){return t*a},t.c2p=function(e){return t.g2p(t.c2g(e))}}}(t,e);break;case"angularaxis":!function(t,e){var r=t.type;if("linear"===r){var i=t.d2c,s=t.c2d;t.d2c=function(t,e){return function(t,e){return"degrees"===e?a(t):t}(i(t),e)},t.c2d=function(t,e){return s(function(t,e){return"degrees"===e?o(t):t}(t,e))}}t.makeCalcdata=function(e,i){var a,o,s=e[i],l=e._length,c=function(r){return t.d2c(r,e.thetaunit)};if(s){if(n.isTypedArray(s)&&"linear"===r){if(l===s.length)return s;if(s.subarray)return s.subarray(0,l)}for(a=new Array(l),o=0;o<l;o++)a[o]=c(s[o])}else{var u=i+"0",h="d"+i,f=u in e?c(e[u]):0,p=e[h]?c(e[h]):(t.period||2*Math.PI)/l;for(a=new Array(l),o=0;o<l;o++)a[o]=f+o*p}return a},t.setGeometry=function(){var i,s,l,c,u=e.sector,h=u.map(a),f={clockwise:-1,counterclockwise:1}[t.direction],p=a(t.rotation),d=function(t){return f*t+p},g=function(t){return(t-p)/f};switch(r){case"linear":s=i=n.identity,c=a,l=o,t.range=n.isFullCircle(h)?[u[0],u[0]+360]:h.map(g).map(o);break;case"category":var v=t._categories.length,m=t.period?Math.max(t.period,v):v;s=c=function(t){return 2*t*Math.PI/m},i=l=function(t){return t*m/Math.PI/2},t.range=[0,m]}t.c2g=function(t){return d(s(t))},t.g2c=function(t){return i(g(t))},t.t2g=function(t){return d(c(t))},t.g2t=function(t){return l(g(t))}}}(t,e)}}},{"../../lib":697,"../cartesian/set_convert":763}],821:[function(t,e,r){"use strict";var n=t("../lib"),i=t("../plot_api/plot_template"),a=t("./domain").defaults;e.exports=function(t,e,r,o){var s,l,c=o.type,u=o.attributes,h=o.handleDefaults,f=o.partition||"x",p=e._subplots[c],d=p.length,g=d&&p[0].replace(/\d+$/,"");function v(t,e){return n.coerce(s,l,u,t,e)}for(var m=0;m<d;m++){var y=p[m];s=t[y]?t[y]:t[y]={},l=i.newContainer(e,y,g),v("uirevision",e.uirevision);var x={};x[f]=[m/d,(m+1)/d],a(l,e,v,x),o.id=y,h(s,l,v,o)}}},{"../lib":697,"../plot_api/plot_template":735,"./domain":770}],822:[function(t,e,r){"use strict";var n=t("./ternary"),i=t("../../plots/get_data").getSubplotCalcData,a=t("../../lib").counterRegex;r.name="ternary";var o=r.attr="subplot";r.idRoot="ternary",r.idRegex=r.attrRegex=a("ternary"),(r.attributes={})[o]={valType:"subplotid",dflt:"ternary",editType:"calc"},r.layoutAttributes=t("./layout_attributes"),r.supplyLayoutDefaults=t("./layout_defaults"),r.plot=function(t){for(var e=t._fullLayout,r=t.calcdata,a=e._subplots.ternary,o=0;o<a.length;o++){var s=a[o],l=i(r,"ternary",s),c=e[s]._subplot;c||(c=new n({id:s,graphDiv:t,container:e._ternarylayer.node()},e),e[s]._subplot=c),c.plot(l,e,t._promises)}},r.clean=function(t,e,r,n){for(var i=n._subplots.ternary||[],a=0;a<i.length;a++){var o=i[a],s=n[o]._subplot;!e[o]&&s&&(s.plotContainer.remove(),s.clipDef.remove(),s.clipDefRelative.remove(),s.layers["a-title"].remove(),s.layers["b-title"].remove(),s.layers["c-title"].remove())}}},{"../../lib":697,"../../plots/get_data":781,"./layout_attributes":823,"./layout_defaults":824,"./ternary":825}],823:[function(t,e,r){"use strict";var n=t("../../components/color/attributes"),i=t("../domain").attributes,a=t("../cartesian/layout_attributes"),o=t("../../plot_api/edit_types").overrideAll,s=t("../../lib/extend").extendFlat,l={title:a.title,color:a.color,tickmode:a.tickmode,nticks:s({},a.nticks,{dflt:6,min:1}),tick0:a.tick0,dtick:a.dtick,tickvals:a.tickvals,ticktext:a.ticktext,ticks:a.ticks,ticklen:a.ticklen,tickwidth:a.tickwidth,tickcolor:a.tickcolor,showticklabels:a.showticklabels,showtickprefix:a.showtickprefix,tickprefix:a.tickprefix,showticksuffix:a.showticksuffix,ticksuffix:a.ticksuffix,showexponent:a.showexponent,exponentformat:a.exponentformat,separatethousands:a.separatethousands,tickfont:a.tickfont,tickangle:a.tickangle,tickformat:a.tickformat,tickformatstops:a.tickformatstops,hoverformat:a.hoverformat,showline:s({},a.showline,{dflt:!0}),linecolor:a.linecolor,linewidth:a.linewidth,showgrid:s({},a.showgrid,{dflt:!0}),gridcolor:a.gridcolor,gridwidth:a.gridwidth,layer:a.layer,min:{valType:"number",dflt:0,min:0},_deprecated:{title:a._deprecated.title,titlefont:a._deprecated.titlefont}},c=e.exports=o({domain:i({name:"ternary"}),bgcolor:{valType:"color",dflt:n.background},sum:{valType:"number",dflt:1,min:0},aaxis:l,baxis:l,caxis:l},"plot","from-root");c.uirevision={valType:"any",editType:"none"},c.aaxis.uirevision=c.baxis.uirevision=c.caxis.uirevision={valType:"any",editType:"none"}},{"../../components/color/attributes":573,"../../lib/extend":687,"../../plot_api/edit_types":728,"../cartesian/layout_attributes":757,"../domain":770}],824:[function(t,e,r){"use strict";var n=t("../../components/color"),i=t("../../plot_api/plot_template"),a=t("../../lib"),o=t("../subplot_defaults"),s=t("../cartesian/tick_label_defaults"),l=t("../cartesian/tick_mark_defaults"),c=t("../cartesian/tick_value_defaults"),u=t("../cartesian/line_grid_defaults"),h=t("./layout_attributes"),f=["aaxis","baxis","caxis"];function p(t,e,r,a){var o,s,l,c=r("bgcolor"),u=r("sum");a.bgColor=n.combine(c,a.paper_bgcolor);for(var h=0;h<f.length;h++)s=t[o=f[h]]||{},(l=i.newContainer(e,o))._name=o,d(s,l,a,e);var p=e.aaxis,g=e.baxis,v=e.caxis;p.min+g.min+v.min>=u&&(p.min=0,g.min=0,v.min=0,t.aaxis&&delete t.aaxis.min,t.baxis&&delete t.baxis.min,t.caxis&&delete t.caxis.min)}function d(t,e,r,n){var i=h[e._name];function o(r,n){return a.coerce(t,e,i,r,n)}o("uirevision",n.uirevision),e.type="linear";var f=o("color"),p=f!==i.color.dflt?f:r.font.color,d=e._name.charAt(0).toUpperCase(),g="Component "+d,v=o("title.text",g);e._hovertitle=v===g?v:d,a.coerceFont(o,"title.font",{family:r.font.family,size:Math.round(1.2*r.font.size),color:p}),o("min"),c(t,e,o,"linear"),s(t,e,o,"linear",{}),l(t,e,o,{outerTicks:!0}),o("showticklabels")&&(a.coerceFont(o,"tickfont",{family:r.font.family,size:r.font.size,color:p}),o("tickangle"),o("tickformat")),u(t,e,o,{dfltColor:f,bgColor:r.bgColor,blend:60,showLine:!0,showGrid:!0,noZeroLine:!0,attributes:i}),o("hoverformat"),o("layer")}e.exports=function(t,e,r){o(t,e,r,{type:"ternary",attributes:h,handleDefaults:p,font:e.font,paper_bgcolor:e.paper_bgcolor})}},{"../../components/color":574,"../../lib":697,"../../plot_api/plot_template":735,"../cartesian/line_grid_defaults":759,"../cartesian/tick_label_defaults":764,"../cartesian/tick_mark_defaults":765,"../cartesian/tick_value_defaults":766,"../subplot_defaults":821,"./layout_attributes":823}],825:[function(t,e,r){"use strict";var n=t("d3"),i=t("tinycolor2"),a=t("../../registry"),o=t("../../lib"),s=o._,l=t("../../components/color"),c=t("../../components/drawing"),u=t("../cartesian/set_convert"),h=t("../../lib/extend").extendFlat,f=t("../plots"),p=t("../cartesian/axes"),d=t("../../components/dragelement"),g=t("../../components/fx"),v=t("../../components/titles"),m=t("../cartesian/select").prepSelect,y=t("../cartesian/select").selectOnClick,x=t("../cartesian/select").clearSelect,b=t("../cartesian/constants");function _(t,e){this.id=t.id,this.graphDiv=t.graphDiv,this.init(e),this.makeFramework(e),this.aTickLayout=null,this.bTickLayout=null,this.cTickLayout=null}e.exports=_;var w=_.prototype;w.init=function(t){this.container=t._ternarylayer,this.defs=t._defs,this.layoutId=t._uid,this.traceHash={},this.layers={}},w.plot=function(t,e){var r=e[this.id],n=e._size;this._hasClipOnAxisFalse=!1;for(var i=0;i<t.length;i++){if(!1===t[i][0].trace.cliponaxis){this._hasClipOnAxisFalse=!0;break}}this.updateLayers(r),this.adjustLayout(r,n),f.generalUpdatePerTraceModule(this.graphDiv,this,t,r),this.layers.plotbg.select("path").call(l.fill,r.bgcolor)},w.makeFramework=function(t){var e=this.graphDiv,r=t[this.id],n=this.clipId="clip"+this.layoutId+this.id,i=this.clipIdRelative="clip-relative"+this.layoutId+this.id;this.clipDef=o.ensureSingleById(t._clips,"clipPath",n,function(t){t.append("path").attr("d","M0,0Z")}),this.clipDefRelative=o.ensureSingleById(t._clips,"clipPath",i,function(t){t.append("path").attr("d","M0,0Z")}),this.plotContainer=o.ensureSingle(this.container,"g",this.id),this.updateLayers(r),c.setClipUrl(this.layers.backplot,n,e),c.setClipUrl(this.layers.grids,n,e)},w.updateLayers=function(t){var e=this.layers,r=["draglayer","plotbg","backplot","grids"];"below traces"===t.aaxis.layer&&r.push("aaxis","aline"),"below traces"===t.baxis.layer&&r.push("baxis","bline"),"below traces"===t.caxis.layer&&r.push("caxis","cline"),r.push("frontplot"),"above traces"===t.aaxis.layer&&r.push("aaxis","aline"),"above traces"===t.baxis.layer&&r.push("baxis","bline"),"above traces"===t.caxis.layer&&r.push("caxis","cline");var i=this.plotContainer.selectAll("g.toplevel").data(r,String),a=["agrid","bgrid","cgrid"];i.enter().append("g").attr("class",function(t){return"toplevel "+t}).each(function(t){var r=n.select(this);e[t]=r,"frontplot"===t?r.append("g").classed("scatterlayer",!0):"backplot"===t?r.append("g").classed("maplayer",!0):"plotbg"===t?r.append("path").attr("d","M0,0Z"):"aline"===t||"bline"===t||"cline"===t?r.append("path"):"grids"===t&&a.forEach(function(t){e[t]=r.append("g").classed("grid "+t,!0)})}),i.order()};var k=Math.sqrt(4/3);w.adjustLayout=function(t,e){var r,n,i,a,o,s,f=this,p=t.domain,d=(p.x[0]+p.x[1])/2,g=(p.y[0]+p.y[1])/2,v=p.x[1]-p.x[0],m=p.y[1]-p.y[0],y=v*e.w,x=m*e.h,b=t.sum,_=t.aaxis.min,w=t.baxis.min,A=t.caxis.min;y>k*x?i=(a=x)*k:a=(i=y)/k,o=v*i/y,s=m*a/x,r=e.l+e.w*d-i/2,n=e.t+e.h*(1-g)-a/2,f.x0=r,f.y0=n,f.w=i,f.h=a,f.sum=b,f.xaxis={type:"linear",range:[_+2*A-b,b-_-2*w],domain:[d-o/2,d+o/2],_id:"x"},u(f.xaxis,f.graphDiv._fullLayout),f.xaxis.setScale(),f.xaxis.isPtWithinRange=function(t){return t.a>=f.aaxis.range[0]&&t.a<=f.aaxis.range[1]&&t.b>=f.baxis.range[1]&&t.b<=f.baxis.range[0]&&t.c>=f.caxis.range[1]&&t.c<=f.caxis.range[0]},f.yaxis={type:"linear",range:[_,b-w-A],domain:[g-s/2,g+s/2],_id:"y"},u(f.yaxis,f.graphDiv._fullLayout),f.yaxis.setScale(),f.yaxis.isPtWithinRange=function(){return!0};var M=f.yaxis.domain[0],T=f.aaxis=h({},t.aaxis,{range:[_,b-w-A],side:"left",tickangle:(+t.aaxis.tickangle||0)-30,domain:[M,M+s*k],anchor:"free",position:0,_id:"y",_length:i});u(T,f.graphDiv._fullLayout),T.setScale();var S=f.baxis=h({},t.baxis,{range:[b-_-A,w],side:"bottom",domain:f.xaxis.domain,anchor:"free",position:0,_id:"x",_length:i});u(S,f.graphDiv._fullLayout),S.setScale();var E=f.caxis=h({},t.caxis,{range:[b-_-w,A],side:"right",tickangle:(+t.caxis.tickangle||0)+30,domain:[M,M+s*k],anchor:"free",position:0,_id:"y",_length:i});u(E,f.graphDiv._fullLayout),E.setScale();var C="M"+r+","+(n+a)+"h"+i+"l-"+i/2+",-"+a+"Z";f.clipDef.select("path").attr("d",C),f.layers.plotbg.select("path").attr("d",C);var L="M0,"+a+"h"+i+"l-"+i/2+",-"+a+"Z";f.clipDefRelative.select("path").attr("d",L);var z="translate("+r+","+n+")";f.plotContainer.selectAll(".scatterlayer,.maplayer").attr("transform",z),f.clipDefRelative.select("path").attr("transform",null);var O="translate("+(r-S._offset)+","+(n+a)+")";f.layers.baxis.attr("transform",O),f.layers.bgrid.attr("transform",O);var I="translate("+(r+i/2)+","+n+")rotate(30)translate(0,"+-T._offset+")";f.layers.aaxis.attr("transform",I),f.layers.agrid.attr("transform",I);var D="translate("+(r+i/2)+","+n+")rotate(-30)translate(0,"+-E._offset+")";f.layers.caxis.attr("transform",D),f.layers.cgrid.attr("transform",D),f.drawAxes(!0),f.layers.aline.select("path").attr("d",T.showline?"M"+r+","+(n+a)+"l"+i/2+",-"+a:"M0,0").call(l.stroke,T.linecolor||"#000").style("stroke-width",(T.linewidth||0)+"px"),f.layers.bline.select("path").attr("d",S.showline?"M"+r+","+(n+a)+"h"+i:"M0,0").call(l.stroke,S.linecolor||"#000").style("stroke-width",(S.linewidth||0)+"px"),f.layers.cline.select("path").attr("d",E.showline?"M"+(r+i/2)+","+n+"l"+i/2+","+a:"M0,0").call(l.stroke,E.linecolor||"#000").style("stroke-width",(E.linewidth||0)+"px"),f.graphDiv._context.staticPlot||f.initInteractions(),c.setClipUrl(f.layers.frontplot,f._hasClipOnAxisFalse?null:f.clipId,f.graphDiv)},w.drawAxes=function(t){var e=this.graphDiv,r=this.id.substr(7)+"title",n=this.layers,i=this.aaxis,a=this.baxis,o=this.caxis;if(this.drawAx(i),this.drawAx(a),this.drawAx(o),t){var l=Math.max(i.showticklabels?i.tickfont.size/2:0,(o.showticklabels?.75*o.tickfont.size:0)+("outside"===o.ticks?.87*o.ticklen:0)),c=(a.showticklabels?a.tickfont.size:0)+("outside"===a.ticks?a.ticklen:0)+3;n["a-title"]=v.draw(e,"a"+r,{propContainer:i,propName:this.id+".aaxis.title",placeholder:s(e,"Click to enter Component A title"),attributes:{x:this.x0+this.w/2,y:this.y0-i.title.font.size/3-l,"text-anchor":"middle"}}),n["b-title"]=v.draw(e,"b"+r,{propContainer:a,propName:this.id+".baxis.title",placeholder:s(e,"Click to enter Component B title"),attributes:{x:this.x0-c,y:this.y0+this.h+.83*a.title.font.size+c,"text-anchor":"middle"}}),n["c-title"]=v.draw(e,"c"+r,{propContainer:o,propName:this.id+".caxis.title",placeholder:s(e,"Click to enter Component C title"),attributes:{x:this.x0+this.w+c,y:this.y0+this.h+.83*o.title.font.size+c,"text-anchor":"middle"}})}},w.drawAx=function(t){var e,r=this.graphDiv,n=t._name,i=n.charAt(0),a=t._id,s=this.layers[n],l=i+"tickLayout",c=(e=t).ticks+String(e.ticklen)+String(e.showticklabels);this[l]!==c&&(s.selectAll("."+a+"tick").remove(),this[l]=c),t.setScale();var u=p.calcTicks(t),h=p.clipEnds(t,u),f=p.makeTransFn(t),d=p.getTickSigns(t)[2],g=o.deg2rad(30),v=d*(t.linewidth||1)/2,m=d*t.ticklen,y=this.w,x=this.h,b="b"===i?"M0,"+v+"l"+Math.sin(g)*m+","+Math.cos(g)*m:"M"+v+",0l"+Math.cos(g)*m+","+-Math.sin(g)*m,_={a:"M0,0l"+x+",-"+y/2,b:"M0,0l-"+y/2+",-"+x,c:"M0,0l-"+x+","+y/2}[i];p.drawTicks(r,t,{vals:"inside"===t.ticks?h:u,layer:s,path:b,transFn:f,crisp:!1}),p.drawGrid(r,t,{vals:h,layer:this.layers[i+"grid"],path:_,transFn:f,crisp:!1}),p.drawLabels(r,t,{vals:u,layer:s,transFn:f,labelFns:p.makeLabelFns(t,0,30)})};var A=b.MINZOOM/2+.87,M="m-0.87,.5h"+A+"v3h-"+(A+5.2)+"l"+(A/2+2.6)+",-"+(.87*A+4.5)+"l2.6,1.5l-"+A/2+","+.87*A+"Z",T="m0.87,.5h-"+A+"v3h"+(A+5.2)+"l-"+(A/2+2.6)+",-"+(.87*A+4.5)+"l-2.6,1.5l"+A/2+","+.87*A+"Z",S="m0,1l"+A/2+","+.87*A+"l2.6,-1.5l-"+(A/2+2.6)+",-"+(.87*A+4.5)+"l-"+(A/2+2.6)+","+(.87*A+4.5)+"l2.6,1.5l"+A/2+",-"+.87*A+"Z",E="m0.5,0.5h5v-2h-5v-5h-2v5h-5v2h5v5h2Z",C=!0;function L(t){n.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}w.initInteractions=function(){var t,e,r,n,u,h,f,p,v,_,w=this,A=w.layers.plotbg.select("path").node(),z=w.graphDiv,O=z._fullLayout._zoomlayer,I={element:A,gd:z,plotinfo:{id:w.id,xaxis:w.xaxis,yaxis:w.yaxis},subplot:w.id,prepFn:function(a,o,s){I.xaxes=[w.xaxis],I.yaxes=[w.yaxis];var c=z._fullLayout.dragmode;I.minDrag="lasso"===c?1:void 0,"zoom"===c?(I.moveFn=N,I.clickFn=P,I.doneFn=j,function(a,o,s){var c=A.getBoundingClientRect();t=o-c.left,e=s-c.top,r={a:w.aaxis.range[0],b:w.baxis.range[1],c:w.caxis.range[1]},u=r,n=w.aaxis.range[1]-r.a,h=i(w.graphDiv._fullLayout[w.id].bgcolor).getLuminance(),f="M0,"+w.h+"L"+w.w/2+", 0L"+w.w+","+w.h+"Z",p=!1,v=O.append("path").attr("class","zoombox").attr("transform","translate("+w.x0+", "+w.y0+")").style({fill:h>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("d",f),_=O.append("path").attr("class","zoombox-corners").attr("transform","translate("+w.x0+", "+w.y0+")").style({fill:l.background,stroke:l.defaultLine,"stroke-width":1,opacity:0}).attr("d","M0,0Z"),x(O)}(0,o,s)):"pan"===c?(I.moveFn=V,I.clickFn=P,I.doneFn=U,r={a:w.aaxis.range[0],b:w.baxis.range[1],c:w.caxis.range[1]},u=r,x(O)):"select"!==c&&"lasso"!==c||m(a,o,s,I,c)}};function D(t){var e={};return e[w.id+".aaxis.min"]=t.a,e[w.id+".baxis.min"]=t.b,e[w.id+".caxis.min"]=t.c,e}function P(t,e){var r=z._fullLayout.clickmode;L(z),2===t&&(z.emit("plotly_doubleclick",null),a.call("_guiRelayout",z,D({a:0,b:0,c:0}))),r.indexOf("select")>-1&&1===t&&y(e,z,[w.xaxis],[w.yaxis],w.id,I),r.indexOf("event")>-1&&g.click(z,e,w.id)}function R(t,e){return 1-e/w.h}function F(t,e){return 1-(t+(w.h-e)/Math.sqrt(3))/w.w}function B(t,e){return(t-(w.h-e)/Math.sqrt(3))/w.w}function N(i,a){var o=t+i,s=e+a,l=Math.max(0,Math.min(1,R(0,e),R(0,s))),c=Math.max(0,Math.min(1,F(t,e),F(o,s))),d=Math.max(0,Math.min(1,B(t,e),B(o,s))),g=(l/2+d)*w.w,m=(1-l/2-c)*w.w,y=(g+m)/2,x=m-g,A=(1-l)*w.h,C=A-x/k;x<b.MINZOOM?(u=r,v.attr("d",f),_.attr("d","M0,0Z")):(u={a:r.a+l*n,b:r.b+c*n,c:r.c+d*n},v.attr("d",f+"M"+g+","+A+"H"+m+"L"+y+","+C+"L"+g+","+A+"Z"),_.attr("d","M"+t+","+e+E+"M"+g+","+A+M+"M"+m+","+A+T+"M"+y+","+C+S)),p||(v.transition().style("fill",h>.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),_.transition().style("opacity",1).duration(200),p=!0)}function j(){L(z),u!==r&&(a.call("_guiRelayout",z,D(u)),C&&z.data&&z._context.showTips&&(o.notifier(s(z,"Double-click to zoom back out"),"long"),C=!1))}function V(t,e){var n=t/w.xaxis._m,i=e/w.yaxis._m,a=[(u={a:r.a-i,b:r.b+(n+i)/2,c:r.c-(n-i)/2}).a,u.b,u.c].sort(),o=a.indexOf(u.a),s=a.indexOf(u.b),l=a.indexOf(u.c);a[0]<0&&(a[1]+a[0]/2<0?(a[2]+=a[0]+a[1],a[0]=a[1]=0):(a[2]+=a[0]/2,a[1]+=a[0]/2,a[0]=0),u={a:a[o],b:a[s],c:a[l]},e=(r.a-u.a)*w.yaxis._m,t=(r.c-u.c-r.b+u.b)*w.xaxis._m);var h="translate("+(w.x0+t)+","+(w.y0+e)+")";w.plotContainer.selectAll(".scatterlayer,.maplayer").attr("transform",h);var f="translate("+-t+","+-e+")";w.clipDefRelative.select("path").attr("transform",f),w.aaxis.range=[u.a,w.sum-u.b-u.c],w.baxis.range=[w.sum-u.a-u.c,u.b],w.caxis.range=[w.sum-u.a-u.b,u.c],w.drawAxes(!1),w._hasClipOnAxisFalse&&w.plotContainer.select(".scatterlayer").selectAll(".trace").call(c.hideOutsideRangePoints,w)}function U(){a.call("_guiRelayout",z,D(u))}A.onmousemove=function(t){g.hover(z,t,w.id),z._fullLayout._lasthover=A,z._fullLayout._hoversubplot=w.id},A.onmouseout=function(t){z._dragging||d.unhover(z,t)},d.init(I)}},{"../../components/color":574,"../../components/dragelement":592,"../../components/drawing":595,"../../components/fx":613,"../../components/titles":662,"../../lib":697,"../../lib/extend":687,"../../registry":826,"../cartesian/axes":745,"../cartesian/constants":751,"../cartesian/select":762,"../cartesian/set_convert":763,"../plots":807,d3:151,tinycolor2:518}],826:[function(t,e,r){"use strict";var n=t("./lib/loggers"),i=t("./lib/noop"),a=t("./lib/push_unique"),o=t("./lib/is_plain_object"),s=t("./lib/extend"),l=t("./plots/attributes"),c=t("./plots/layout_attributes"),u=s.extendFlat,h=s.extendDeepAll;function f(t){var e=t.name,i=t.categories,a=t.meta;if(r.modules[e])n.log("Type "+e+" already registered");else{r.subplotsRegistry[t.basePlotModule.name]||function(t){var e=t.name;if(r.subplotsRegistry[e])return void n.log("Plot type "+e+" already registered.");for(var i in v(t),r.subplotsRegistry[e]=t,r.componentsRegistry)x(i,t.name)}(t.basePlotModule);for(var o={},s=0;s<i.length;s++)o[i[s]]=!0,r.allCategories[i[s]]=!0;for(var l in r.modules[e]={_module:t,categories:o},a&&Object.keys(a).length&&(r.modules[e].meta=a),r.allTypes.push(e),r.componentsRegistry)m(l,e);t.layoutAttributes&&u(r.traceLayoutAttributes,t.layoutAttributes)}}function p(t){if("string"!=typeof t.name)throw new Error("Component module *name* must be a string.");var e=t.name;for(var n in r.componentsRegistry[e]=t,t.layoutAttributes&&(t.layoutAttributes._isLinkedToArray&&a(r.layoutArrayContainers,e),v(t)),r.modules)m(e,n);for(var i in r.subplotsRegistry)x(e,i);for(var o in r.transformsRegistry)y(e,o);t.schema&&t.schema.layout&&h(c,t.schema.layout)}function d(t){if("string"!=typeof t.name)throw new Error("Transform module *name* must be a string.");var e="Transform module "+t.name,i="function"==typeof t.transform,a="function"==typeof t.calcTransform;if(!i&&!a)throw new Error(e+" is missing a *transform* or *calcTransform* method.");for(var s in i&&a&&n.log([e+" has both a *transform* and *calcTransform* methods.","Please note that all *transform* methods are executed","before all *calcTransform* methods."].join(" ")),o(t.attributes)||n.log(e+" registered without an *attributes* object."),"function"!=typeof t.supplyDefaults&&n.log(e+" registered without a *supplyDefaults* method."),r.transformsRegistry[t.name]=t,r.componentsRegistry)y(s,t.name)}function g(t){var e=t.name,n=e.split("-")[0],i=t.dictionary,a=t.format,o=i&&Object.keys(i).length,s=a&&Object.keys(a).length,l=r.localeRegistry,c=l[e];if(c||(l[e]=c={}),n!==e){var u=l[n];u||(l[n]=u={}),o&&u.dictionary===c.dictionary&&(u.dictionary=i),s&&u.format===c.format&&(u.format=a)}o&&(c.dictionary=i),s&&(c.format=a)}function v(t){if(t.layoutAttributes){var e=t.layoutAttributes._arrayAttrRegexps;if(e)for(var n=0;n<e.length;n++)a(r.layoutArrayRegexes,e[n])}}function m(t,e){var n=r.componentsRegistry[t].schema;if(n&&n.traces){var i=n.traces[e];i&&h(r.modules[e]._module.attributes,i)}}function y(t,e){var n=r.componentsRegistry[t].schema;if(n&&n.transforms){var i=n.transforms[e];i&&h(r.transformsRegistry[e].attributes,i)}}function x(t,e){var n=r.componentsRegistry[t].schema;if(n&&n.subplots){var i=r.subplotsRegistry[e],a=i.layoutAttributes,o="subplot"===i.attr?i.name:i.attr;Array.isArray(o)&&(o=o[0]);var s=n.subplots[o];a&&s&&h(a,s)}}function b(t){return"object"==typeof t&&(t=t.type),t}r.modules={},r.allCategories={},r.allTypes=[],r.subplotsRegistry={},r.transformsRegistry={},r.componentsRegistry={},r.layoutArrayContainers=[],r.layoutArrayRegexes=[],r.traceLayoutAttributes={},r.localeRegistry={},r.apiMethodRegistry={},r.collectableSubplotTypes=null,r.register=function(t){if(r.collectableSubplotTypes=null,!t)throw new Error("No argument passed to Plotly.register.");t&&!Array.isArray(t)&&(t=[t]);for(var e=0;e<t.length;e++){var n=t[e];if(!n)throw new Error("Invalid module was attempted to be registered!");switch(n.moduleType){case"trace":f(n);break;case"transform":d(n);break;case"component":p(n);break;case"locale":g(n);break;case"apiMethod":var i=n.name;r.apiMethodRegistry[i]=n.fn;break;default:throw new Error("Invalid module was attempted to be registered!")}}},r.getModule=function(t){var e=r.modules[b(t)];return!!e&&e._module},r.traceIs=function(t,e){if("various"===(t=b(t)))return!1;var i=r.modules[t];return i||(t&&"area"!==t&&n.log("Unrecognized trace type "+t+"."),i=r.modules[l.type.dflt]),!!i.categories[e]},r.getTransformIndices=function(t,e){for(var r=[],n=t.transforms||[],i=0;i<n.length;i++)n[i].type===e&&r.push(i);return r},r.hasTransform=function(t,e){for(var r=t.transforms||[],n=0;n<r.length;n++)if(r[n].type===e)return!0;return!1},r.getComponentMethod=function(t,e){var n=r.componentsRegistry[t];return n&&n[e]||i},r.call=function(){var t=arguments[0],e=[].slice.call(arguments,1);return r.apiMethodRegistry[t].apply(null,e)}},{"./lib/extend":687,"./lib/is_plain_object":698,"./lib/loggers":701,"./lib/noop":706,"./lib/push_unique":711,"./plots/attributes":742,"./plots/layout_attributes":798}],827:[function(t,e,r){"use strict";var n=t("../lib"),i=n.extendFlat,a=n.extendDeep;function o(t){var e;switch(t){case"themes__thumb":e={autosize:!0,width:150,height:150,title:{text:""},showlegend:!1,margin:{l:5,r:5,t:5,b:5,pad:0},annotations:[]};break;case"thumbnail":e={title:{text:""},hidesources:!0,showlegend:!1,borderwidth:0,bordercolor:"",margin:{l:1,r:1,t:1,b:1,pad:0},annotations:[]};break;default:e={}}return e}e.exports=function(t,e){var r;t.framework&&t.framework.isPolar&&(t=t.framework.getConfig());var n,s=t.data,l=t.layout,c=a([],s),u=a({},l,o(e.tileClass)),h=t._context||{};if(e.width&&(u.width=e.width),e.height&&(u.height=e.height),"thumbnail"===e.tileClass||"themes__thumb"===e.tileClass){u.annotations=[];var f=Object.keys(u);for(r=0;r<f.length;r++)n=f[r],["xaxis","yaxis","zaxis"].indexOf(n.slice(0,5))>-1&&(u[f[r]].title={text:""});for(r=0;r<c.length;r++){var p=c[r];p.showscale=!1,p.marker&&(p.marker.showscale=!1),"pie"===p.type&&(p.textposition="none")}}if(Array.isArray(e.annotations))for(r=0;r<e.annotations.length;r++)u.annotations.push(e.annotations[r]);var d=Object.keys(u).filter(function(t){return t.match(/^scene\d*$/)});if(d.length){var g={};for("thumbnail"===e.tileClass&&(g={title:{text:""},showaxeslabels:!1,showticklabels:!1,linetickenable:!1}),r=0;r<d.length;r++){var v=u[d[r]];v.xaxis||(v.xaxis={}),v.yaxis||(v.yaxis={}),v.zaxis||(v.zaxis={}),i(v.xaxis,g),i(v.yaxis,g),i(v.zaxis,g),v._scene=null}}var m=document.createElement("div");e.tileClass&&(m.className=e.tileClass);var y={gd:m,td:m,layout:u,data:c,config:{staticPlot:void 0===e.staticPlot||e.staticPlot,plotGlPixelRatio:void 0===e.plotGlPixelRatio?2:e.plotGlPixelRatio,displaylogo:e.displaylogo||!1,showLink:e.showLink||!1,showTips:e.showTips||!1,mapboxAccessToken:h.mapboxAccessToken}};return"transparent"!==e.setBackground&&(y.config.setBackground=e.setBackground||"opaque"),y.gd.defaultLayout=o(e.tileClass),y}},{"../lib":697}],828:[function(t,e,r){"use strict";var n=t("../plot_api/to_image"),i=t("../lib"),a=t("./filesaver");e.exports=function(t,e){var r;return i.isPlainObject(t)||(r=i.getGraphDiv(t)),(e=e||{}).format=e.format||"png",new Promise(function(o,s){r&&r._snapshotInProgress&&s(new Error("Snapshotting already in progress.")),i.isIE()&&"svg"!==e.format&&s(new Error("Sorry IE does not support downloading from canvas. Try {format:'svg'} instead.")),r&&(r._snapshotInProgress=!0);var l=n(t,e),c=e.filename||t.fn||"newplot";c+="."+e.format,l.then(function(t){return r&&(r._snapshotInProgress=!1),a(t,c)}).then(function(t){o(t)}).catch(function(t){r&&(r._snapshotInProgress=!1),s(t)})})}},{"../lib":697,"../plot_api/to_image":738,"./filesaver":829}],829:[function(t,e,r){"use strict";e.exports=function(t,e){var r=document.createElement("a"),n="download"in r,i=/Version\/[\d\.]+.*Safari/.test(navigator.userAgent);return new Promise(function(a,o){if("undefined"!=typeof navigator&&/MSIE [1-9]\./.test(navigator.userAgent)&&o(new Error("IE < 10 unsupported")),i&&(document.location.href="data:application/octet-stream"+t.slice(t.search(/[,;]/)),a(e)),e||(e="download"),n&&(r.href=t,r.download=e,document.body.appendChild(r),r.click(),document.body.removeChild(r),a(e)),"undefined"!=typeof navigator&&navigator.msSaveBlob){var s=t.split(/^data:image\/svg\+xml,/)[1],l=decodeURIComponent(s);navigator.msSaveBlob(new Blob([l]),e),a(e)}o(new Error("download error"))})}},{}],830:[function(t,e,r){"use strict";r.getDelay=function(t){return t._has&&(t._has("gl3d")||t._has("gl2d")||t._has("mapbox"))?500:0},r.getRedrawFunc=function(t){var e=t._fullLayout||{};if(!(!(e._has&&e._has("polar"))&&t.data&&t.data[0]&&t.data[0].r))return function(){(t.calcdata||[]).forEach(function(t){t[0]&&t[0].t&&t[0].t.cb&&t[0].t.cb()})}}},{}],831:[function(t,e,r){"use strict";var n=t("./helpers"),i={getDelay:n.getDelay,getRedrawFunc:n.getRedrawFunc,clone:t("./cloneplot"),toSVG:t("./tosvg"),svgToImg:t("./svgtoimg"),toImage:t("./toimage"),downloadImage:t("./download")};e.exports=i},{"./cloneplot":827,"./download":828,"./helpers":830,"./svgtoimg":832,"./toimage":833,"./tosvg":834}],832:[function(t,e,r){"use strict";var n=t("../lib"),i=t("events").EventEmitter;e.exports=function(t){var e=t.emitter||new i,r=new Promise(function(i,a){var o=window.Image,s=t.svg,l=t.format||"png";if(n.isIE()&&"svg"!==l){var c=new Error("Sorry IE does not support downloading from canvas. Try {format:'svg'} instead.");return a(c),t.promise?r:e.emit("error",c)}var u=t.canvas,h=t.scale||1,f=t.width||300,p=t.height||150,d=h*f,g=h*p,v=u.getContext("2d"),m=new o,y="data:image/svg+xml,"+encodeURIComponent(s);u.width=d,u.height=g,m.onload=function(){var r;switch("svg"!==l&&v.drawImage(m,0,0,d,g),l){case"jpeg":r=u.toDataURL("image/jpeg");break;case"png":r=u.toDataURL("image/png");break;case"webp":r=u.toDataURL("image/webp");break;case"svg":r=y;break;default:var n="Image format is not jpeg, png, svg or webp.";if(a(new Error(n)),!t.promise)return e.emit("error",n)}i(r),t.promise||e.emit("success",r)},m.onerror=function(r){if(a(r),!t.promise)return e.emit("error",r)},m.src=y});return t.promise?r:e}},{"../lib":697,events:92}],833:[function(t,e,r){"use strict";var n=t("events").EventEmitter,i=t("../registry"),a=t("../lib"),o=t("./helpers"),s=t("./cloneplot"),l=t("./tosvg"),c=t("./svgtoimg");e.exports=function(t,e){var r=new n,u=s(t,{format:"png"}),h=u.gd;h.style.position="absolute",h.style.left="-5000px",document.body.appendChild(h);var f=o.getRedrawFunc(h);return i.call("plot",h,u.data,u.layout,u.config).then(f).then(function(){var t=o.getDelay(h._fullLayout);setTimeout(function(){var t=l(h),n=document.createElement("canvas");n.id=a.randstr(),(r=c({format:e.format,width:h._fullLayout.width,height:h._fullLayout.height,canvas:n,emitter:r,svg:t})).clean=function(){h&&document.body.removeChild(h)}},t)}).catch(function(t){r.emit("error",t)}),r}},{"../lib":697,"../registry":826,"./cloneplot":827,"./helpers":830,"./svgtoimg":832,"./tosvg":834,events:92}],834:[function(t,e,r){"use strict";var n=t("d3"),i=t("../lib"),a=t("../components/drawing"),o=t("../components/color"),s=t("../constants/xmlns_namespaces"),l=/"/g,c=new RegExp('("TOBESTRIPPED)|(TOBESTRIPPED")',"g");e.exports=function(t,e,r){var u,h=t._fullLayout,f=h._paper,p=h._toppaper,d=h.width,g=h.height;f.insert("rect",":first-child").call(a.setRect,0,0,d,g).call(o.fill,h.paper_bgcolor);var v=h._basePlotModules||[];for(u=0;u<v.length;u++){var m=v[u];m.toSVG&&m.toSVG(t)}if(p){var y=p.node().childNodes,x=Array.prototype.slice.call(y);for(u=0;u<x.length;u++){var b=x[u];b.childNodes.length&&f.node().appendChild(b)}}h._draggers&&h._draggers.remove(),f.node().style.background="",f.selectAll("text").attr({"data-unformatted":null,"data-math":null}).each(function(){var t=n.select(this);if("hidden"!==this.style.visibility&&"none"!==this.style.display){t.style({visibility:null,display:null});var e=this.style.fontFamily;e&&-1!==e.indexOf('"')&&t.style("font-family",e.replace(l,"TOBESTRIPPED"))}else t.remove()}),f.selectAll(".point, .scatterpts, .legendfill>path, .legendlines>path, .cbfill").each(function(){var t=n.select(this),e=this.style.fill;e&&-1!==e.indexOf("url(")&&t.style("fill",e.replace(l,"TOBESTRIPPED"));var r=this.style.stroke;r&&-1!==r.indexOf("url(")&&t.style("stroke",r.replace(l,"TOBESTRIPPED"))}),"pdf"!==e&&"eps"!==e||f.selectAll("#MathJax_SVG_glyphs path").attr("stroke-width",0),f.node().setAttributeNS(s.xmlns,"xmlns",s.svg),f.node().setAttributeNS(s.xmlns,"xmlns:xlink",s.xlink),"svg"===e&&r&&(f.attr("width",r*d),f.attr("height",r*g),f.attr("viewBox","0 0 "+d+" "+g));var _=(new window.XMLSerializer).serializeToString(f.node());return _=function(t){var e=n.select("body").append("div").style({display:"none"}).html(""),r=t.replace(/(&[^;]*;)/gi,function(t){return"&lt;"===t?"&#60;":"&rt;"===t?"&#62;":-1!==t.indexOf("<")||-1!==t.indexOf(">")?"":e.html(t).text()});return e.remove(),r}(_),_=(_=_.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&amp;")).replace(c,"'"),i.isIE()&&(_=(_=(_=_.replace(/"/gi,"'")).replace(/(\('#)([^']*)('\))/gi,'("#$2")')).replace(/(\\')/gi,'"')),_}},{"../components/color":574,"../components/drawing":595,"../constants/xmlns_namespaces":675,"../lib":697,d3:151}],835:[function(t,e,r){"use strict";var n=t("../../lib").mergeArray;e.exports=function(t,e){for(var r=0;r<t.length;r++)t[r].i=r;n(e.text,t,"tx"),n(e.hovertext,t,"htx");var i=e.marker;if(i){n(i.opacity,t,"mo"),n(i.color,t,"mc");var a=i.line;a&&(n(a.color,t,"mlc"),n(a.width,t,"mlw"))}}},{"../../lib":697}],836:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../components/fx/hovertemplate_attributes"),a=t("../../components/colorscale/attributes"),o=t("../../components/colorbar/attributes"),s=t("../../plots/font_attributes"),l=t("./constants.js"),c=t("../../lib/extend").extendFlat,u=s({editType:"calc",arrayOk:!0,colorEditType:"style"}),h=c({},n.marker.line.width,{dflt:0}),f=c({width:h,editType:"calc"},a("marker.line")),p=c({line:f,editType:"calc"},a("marker"),{colorbar:o,opacity:{valType:"number",arrayOk:!0,dflt:1,min:0,max:1,editType:"style"}});e.exports={x:n.x,x0:n.x0,dx:n.dx,y:n.y,y0:n.y0,dy:n.dy,text:n.text,hovertext:n.hovertext,hovertemplate:i({},{keys:l.eventDataKeys}),textposition:{valType:"enumerated",values:["inside","outside","auto","none"],dflt:"none",arrayOk:!0,editType:"calc"},textfont:c({},u,{}),insidetextfont:c({},u,{}),outsidetextfont:c({},u,{}),constraintext:{valType:"enumerated",values:["inside","outside","both","none"],dflt:"both",editType:"calc"},cliponaxis:c({},n.cliponaxis,{}),orientation:{valType:"enumerated",values:["v","h"],editType:"calc+clearAxisTypes"},base:{valType:"any",dflt:null,arrayOk:!0,editType:"calc"},offset:{valType:"number",dflt:null,arrayOk:!0,editType:"calc"},width:{valType:"number",dflt:null,min:0,arrayOk:!0,editType:"calc"},marker:p,offsetgroup:{valType:"string",dflt:"",editType:"calc"},alignmentgroup:{valType:"string",dflt:"",editType:"calc"},selected:{marker:{opacity:n.selected.marker.opacity,color:n.selected.marker.color,editType:"style"},textfont:n.selected.textfont,editType:"style"},unselected:{marker:{opacity:n.unselected.marker.opacity,color:n.unselected.marker.color,editType:"style"},textfont:n.unselected.textfont,editType:"style"},r:n.r,t:n.t,_deprecated:{bardir:{valType:"enumerated",editType:"calc",values:["v","h"]}}}},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plots/font_attributes":771,"../scatter/attributes":1048,"./constants.js":838}],837:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axes"),i=t("../../components/colorscale/helpers").hasColorscale,a=t("../../components/colorscale/calc"),o=t("./arrays_to_calcdata"),s=t("../scatter/calc_selection");e.exports=function(t,e){var r,l,c=n.getFromId(t,e.xaxis||"x"),u=n.getFromId(t,e.yaxis||"y");"h"===e.orientation?(r=c.makeCalcdata(e,"x"),l=u.makeCalcdata(e,"y")):(r=u.makeCalcdata(e,"y"),l=c.makeCalcdata(e,"x"));for(var h=Math.min(l.length,r.length),f=new Array(h),p=0;p<h;p++)f[p]={p:l[p],s:r[p]},e.ids&&(f[p].id=String(e.ids[p]));return i(e,"marker")&&a(t,e,{vals:e.marker.color,containerStr:"marker",cLetter:"c"}),i(e,"marker.line")&&a(t,e,{vals:e.marker.line.color,containerStr:"marker.line",cLetter:"c"}),o(f,e),s(f,e),f}},{"../../components/colorscale/calc":582,"../../components/colorscale/helpers":585,"../../plots/cartesian/axes":745,"../scatter/calc_selection":1050,"./arrays_to_calcdata":835}],838:[function(t,e,r){"use strict";e.exports={eventDataKeys:[]}},{}],839:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib").isArrayOrTypedArray,a=t("../../constants/numerical").BADNUM,o=t("../../registry"),s=t("../../plots/cartesian/axes"),l=t("../../plots/cartesian/axis_ids").getAxisGroup,c=t("./sieve.js");function u(t,e,r,o){if(o.length){var u,b,_,w,k=t._fullLayout.barmode,A="overlay"===k,M="group"===k;if(function(t,e,r,a){var o,s;for(o=0;o<a.length;o++){var l,c=a[o],u=c[0].trace,h=u.base,f="h"===u.orientation?u.xcalendar:u.ycalendar,p="category"===r.type||"multicategory"===r.type?function(){return null}:r.d2c;if(i(h)){for(s=0;s<Math.min(h.length,c.length);s++)l=p(h[s],0,f),n(l)?(c[s].b=+l,c[s].hasB=1):c[s].b=0;for(;s<c.length;s++)c[s].b=0}else{l=p(h,0,f);var d=n(l);for(l=d?l:0,s=0;s<c.length;s++)c[s].b=l,d&&(c[s].hasB=1)}}}(0,0,r,o),A)h(t,e,r,o);else if(M){for(u=[],b=[],_=0;_<o.length;_++)void 0===(w=o[_])[0].trace.offset?b.push(w):u.push(w);b.length&&function(t,e,r,n){var i=t._fullLayout.barnorm,a=new c(n,!1,!i);(function(t,e,r){for(var n=t._fullLayout,i=n.bargap,a=n.bargroupgap||0,o=r.positions,s=r.distinctPositions,c=r.minDiff,u=r.traces,h=u.length,f=o.length!==s.length,v=c*(1-i),m=l(n,e._id)+u[0][0].trace.orientation,y=n._alignmentOpts[m]||{},x=0;x<h;x++){var b,_,w=u[x],k=w[0].trace,A=y[k.alignmentgroup]||{},M=Object.keys(A.offsetGroups||{}).length,T=(b=M?v/M:f?v/h:v)*(1-a);_=M?((2*k._offsetIndex+1-M)*b-T)/2:f?((2*x+1-h)*b-T)/2:-T/2;var S=w[0].t;S.barwidth=T,S.poffset=_,S.bargroupwidth=v,S.bardelta=c}r.binWidth=u[0][0].t.barwidth/100,p(r),d(t,e,r),g(t,e,r,f)})(t,e,a),i?(m(t,r,a),y(t,r,a)):v(t,r,a)}(t,e,r,b),u.length&&h(t,e,r,u)}else{for(u=[],b=[],_=0;_<o.length;_++)void 0===(w=o[_])[0].trace.base?b.push(w):u.push(w);b.length&&function(t,e,r,n){var i=t._fullLayout,o=i.barmode,l="stack"===o,u="relative"===o,h=i.barnorm,p=new c(n,u,!(h||l||u));f(t,e,p),function(t,e,r){for(var n=t._fullLayout.barnorm,i=x(e),o=r.traces,l=0;l<o.length;l++){for(var c=o[l],u=c[0].trace,h=[],f=0;f<c.length;f++){var p=c[f];if(p.s!==a){var d=r.put(p.p,p.b+p.s),g=d+p.b+p.s;p.b=d,p[i]=g,n||(h.push(g),p.hasB&&h.push(d))}}n||(u._extremes[e._id]=s.findExtremes(e,h,{tozero:!0,padded:!0}))}}(t,r,p);for(var d=0;d<n.length;d++)for(var g=n[d],v=0;v<g.length;v++){var m=g[v];if(m.s!==a){var b=m.b+m.s===p.get(m.p,m.s);b&&(m._outmost=!0)}}h&&y(t,r,p)}(t,e,r,b),u.length&&h(t,e,r,u)}!function(t,e){var r,i,a,o=x(e),s={},l=1/0,c=-1/0;for(r=0;r<t.length;r++)for(a=t[r],i=0;i<a.length;i++){var u=a[i].p;n(u)&&(l=Math.min(l,u),c=Math.max(c,u))}var h=1e4/(c-l),f=s.round=function(t){return String(Math.round(h*(t-l)))};for(r=0;r<t.length;r++){(a=t[r])[0].t.extents=s;var p=a[0].t.poffset,d=Array.isArray(p);for(i=0;i<a.length;i++){var g=a[i],v=g[o]-g.w/2;if(n(v)){var m=g[o]+g.w/2,y=f(g.p);s[y]?s[y]=[Math.min(v,s[y][0]),Math.max(m,s[y][1])]:s[y]=[v,m]}g.p0=g.p+(d?p[i]:p),g.p1=g.p0+g.w,g.s0=g.b,g.s1=g.s0+g.s}}}(o,e)}}function h(t,e,r,n){for(var i=t._fullLayout.barnorm,a=!i,o=0;o<n.length;o++){var s=n[o],l=new c([s],!1,a);f(t,e,l),i?(m(t,r,l),y(t,r,l)):v(t,r,l)}}function f(t,e,r){for(var n=t._fullLayout,i=n.bargap,a=n.bargroupgap||0,o=r.minDiff,s=r.traces,l=o*(1-i),c=l*(1-a),u=-c/2,h=0;h<s.length;h++){var f=s[h][0].t;f.barwidth=c,f.poffset=u,f.bargroupwidth=l,f.bardelta=o}r.binWidth=s[0][0].t.barwidth/100,p(r),d(t,e,r),g(t,e,r)}function p(t){var e,r,a=t.traces;for(e=0;e<a.length;e++){var o,s=a[e],l=s[0],c=l.trace,u=l.t,h=c._offset||c.offset,f=u.poffset;if(i(h)){for(o=Array.prototype.slice.call(h,0,s.length),r=0;r<o.length;r++)n(o[r])||(o[r]=f);for(r=o.length;r<s.length;r++)o.push(f);u.poffset=o}else void 0!==h&&(u.poffset=h);var p=c._width||c.width,d=u.barwidth;if(i(p)){var g=Array.prototype.slice.call(p,0,s.length);for(r=0;r<g.length;r++)n(g[r])||(g[r]=d);for(r=g.length;r<s.length;r++)g.push(d);if(u.barwidth=g,void 0===h){for(o=[],r=0;r<s.length;r++)o.push(f+(d-g[r])/2);u.poffset=o}}else void 0!==p&&(u.barwidth=p,void 0===h&&(u.poffset=f+(d-p)/2))}}function d(t,e,r){for(var n=r.traces,i=x(e),a=0;a<n.length;a++)for(var o=n[a],s=o[0].t,l=s.poffset,c=Array.isArray(l),u=s.barwidth,h=Array.isArray(u),f=0;f<o.length;f++){var p=o[f],d=p.w=h?u[f]:u;p[i]=p.p+(c?l[f]:l)+d/2}}function g(t,e,r,n){var i=r.traces,a=r.minDiff/2;s.minDtick(e,r.minDiff,r.distinctPositions[0],n);for(var o=0;o<i.length;o++){var l,c,u,h,f=i[o],p=f[0],d=p.trace,g=[];for(h=0;h<f.length;h++)c=(l=f[h]).p-a,u=l.p+a,g.push(c,u);if(d.width||d.offset){var v=p.t,m=v.poffset,y=v.barwidth,x=Array.isArray(m),b=Array.isArray(y);for(h=0;h<f.length;h++){l=f[h];var _=x?m[h]:m,w=b?y[h]:y;u=(c=l.p+_)+w,g.push(c,u)}}d._extremes[e._id]=s.findExtremes(e,g,{padded:!1})}}function v(t,e,r){for(var n=r.traces,i=x(e),a=0;a<n.length;a++){for(var o=n[a],l=o[0].trace,c=[],u=!0,h=0;h<o.length;h++){var f=o[h],p=f.b,d=p+f.s;f[i]=d,c.push(d),f.hasB&&c.push(p),f.hasB&&f.b>0&&f.s>0||(u=!1)}l._extremes[e._id]=s.findExtremes(e,c,{tozero:!u,padded:!0})}}function m(t,e,r){for(var n=r.traces,i=0;i<n.length;i++)for(var o=n[i],s=0;s<o.length;s++){var l=o[s];l.s!==a&&r.put(l.p,l.b+l.s)}}function y(t,e,r){var i=t._fullLayout,o=r.traces,l=x(e),c="fraction"===i.barnorm?1:100,u=c/1e9,h=e.l2c(e.c2l(0)),f="stack"===i.barmode?c:h;function p(t){return n(e.c2l(t))&&(t<h-u||t>f+u||!n(h))}for(var d=0;d<o.length;d++){for(var g=o[d],v=g[0].trace,m=[],y=!0,b=!1,_=0;_<g.length;_++){var w=g[_];if(w.s!==a){var k=Math.abs(c/r.get(w.p,w.s));w.b*=k,w.s*=k;var A=w.b,M=A+w.s;w[l]=M,m.push(M),b=b||p(M),w.hasB&&(m.push(A),b=b||p(A)),w.hasB&&w.b>0&&w.s>0||(y=!1)}}v._extremes[e._id]=s.findExtremes(e,m,{tozero:!y,padded:b})}}function x(t){return t._id.charAt(0)}e.exports={crossTraceCalc:function(t,e){for(var r=e.xaxis,n=e.yaxis,i=t._fullData,a=t.calcdata,s=[],l=[],c=0;c<i.length;c++){var h=i[c];!0===h.visible&&o.traceIs(h,"bar")&&h.xaxis===r._id&&h.yaxis===n._id&&("h"===h.orientation?s.push(a[c]):l.push(a[c]))}u(t,r,n,l),u(t,n,r,s)},setGroupPositions:u}},{"../../constants/numerical":674,"../../lib":697,"../../plots/cartesian/axes":745,"../../plots/cartesian/axis_ids":748,"../../registry":826,"./sieve.js":848,"fast-isnumeric":218}],840:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/color"),a=t("../../registry"),o=t("../scatter/xy_defaults"),s=t("../bar/style_defaults"),l=t("../../plots/cartesian/axis_ids").getAxisGroup,c=t("./attributes");function u(t,e,r,n){var i=e.orientation,a=e[{v:"x",h:"y"}[i]+"axis"],o=l(r,a)+i,s=r._alignmentOpts||{},c=n("alignmentgroup"),u=s[o];u||(u=s[o]={});var h=u[c];h?h.traces.push(e):h=u[c]={traces:[e],alignmentIndex:Object.keys(u).length,offsetGroups:{}};var f=n("offsetgroup"),p=h.offsetGroups,d=p[f];f&&(d||(d=p[f]={offsetIndex:Object.keys(p).length}),e._offsetIndex=d.offsetIndex)}e.exports={supplyDefaults:function(t,e,r,l){function u(r,i){return n.coerce(t,e,c,r,i)}var h=n.coerceFont;if(o(t,e,l,u)){u("orientation",e.x&&!e.y?"h":"v"),u("base"),u("offset"),u("width"),u("text"),u("hovertext"),u("hovertemplate");var f=u("textposition"),p=Array.isArray(f)||"auto"===f,d=p||"outside"===f;if(p||"inside"===f||d){var g=h(u,"textfont",l.font),v=n.extendFlat({},g);!(t.textfont&&t.textfont.color)&&delete v.color,h(u,"insidetextfont",v),d&&h(u,"outsidetextfont",g),u("constraintext"),u("selected.textfont.color"),u("unselected.textfont.color"),u("cliponaxis")}s(t,e,u,r,l);var m=(e.marker.line||{}).color,y=a.getComponentMethod("errorbars","supplyDefaults");y(t,e,m||i.defaultLine,{axis:"y"}),y(t,e,m||i.defaultLine,{axis:"x",inherit:"y"}),n.coerceSelectionMarkerOpacity(e,u)}else e.visible=!1},crossTraceDefaults:function(t,e){var r;function i(t){return n.coerce(r._input,r,c,t)}for(var a=0;a<t.length;a++)"bar"===(r=t[a]).type&&(r._input,"group"===e.barmode&&u(0,r,e,i))},handleGroupingDefaults:u}},{"../../components/color":574,"../../lib":697,"../../plots/cartesian/axis_ids":748,"../../registry":826,"../bar/style_defaults":850,"../scatter/xy_defaults":1074,"./attributes":836}],841:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("tinycolor2");r.coerceString=function(t,e,r){if("string"==typeof e){if(e||!t.noBlank)return e}else if("number"==typeof e&&!t.strict)return String(e);return void 0!==r?r:t.dflt},r.coerceNumber=function(t,e,r){if(n(e)){e=+e;var i=t.min,a=t.max;if(!(void 0!==i&&e<i||void 0!==a&&e>a))return e}return void 0!==r?r:t.dflt},r.coerceColor=function(t,e,r){return i(e).isValid()?e:void 0!==r?r:t.dflt},r.coerceEnumerated=function(t,e,r){return t.coerceNumber&&(e=+e),-1!==t.values.indexOf(e)?e:void 0!==r?r:t.dflt},r.getValue=function(t,e){var r;return Array.isArray(t)?e<t.length&&(r=t[e]):r=t,r}},{"fast-isnumeric":218,tinycolor2:518}],842:[function(t,e,r){"use strict";var n=t("../../components/fx"),i=t("../../registry"),a=t("../../components/color"),o=t("../scatter/fill_hover_text");function s(t,e){var r=e.mcc||t.marker.color,n=e.mlcc||t.marker.line.color,i=e.mlw||t.marker.line.width;return a.opacity(r)?r:a.opacity(n)&&i?n:void 0}e.exports={hoverPoints:function(t,e,r,a){var l,c,u,h,f,p,d,g=t.cd,v=g[0].trace,m=g[0].t,y="closest"===a,x=t.maxHoverDistance,b=t.maxSpikeDistance;function _(t){return t[u]-t.w/2}function w(t){return t[u]+t.w/2}var k=y?_:function(t){return Math.min(_(t),t.p-m.bardelta/2)},A=y?w:function(t){return Math.max(w(t),t.p+m.bardelta/2)};function M(t,e){return n.inbox(t-l,e-l,x+Math.min(1,Math.abs(e-t)/d)-1)}function T(t){return M(k(t),A(t))}function S(t){return n.inbox(t.b-c,t[h]-c,x+(t[h]-c)/(t[h]-t.b)-1)}"h"===v.orientation?(l=r,c=e,u="y",h="x",f=S,p=T):(l=e,c=r,u="x",h="y",p=S,f=T);var E=t[u+"a"],C=t[h+"a"];d=Math.abs(E.r2c(E.range[1])-E.r2c(E.range[0]));var L=n.getDistanceFunction(a,f,p,function(t){return(f(t)+p(t))/2});if(n.getClosest(g,L,t),!1!==t.index){y||(k=function(t){return Math.min(_(t),t.p-m.bargroupwidth/2)},A=function(t){return Math.max(w(t),t.p+m.bargroupwidth/2)});var z=g[t.index],O=v.base?z.b+z.s:z.s;t[h+"0"]=t[h+"1"]=C.c2p(z[h],!0),t[h+"LabelVal"]=O;var I=m.extents[m.extents.round(z.p)];return t[u+"0"]=E.c2p(y?k(z):I[0],!0),t[u+"1"]=E.c2p(y?A(z):I[1],!0),t[u+"LabelVal"]=z.p,t.spikeDistance=(S(z)+function(t){return M(_(t),w(t))}(z))/2+b-x,t[u+"Spike"]=E.c2p(z.p,!0),t.color=s(v,z),o(z,v,t),i.getComponentMethod("errorbars","hoverInfo")(z,v,t),t.hovertemplate=v.hovertemplate,[t]}},getTraceColor:s}},{"../../components/color":574,"../../components/fx":613,"../../registry":826,"../scatter/fill_hover_text":1056}],843:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.layoutAttributes=t("./layout_attributes"),n.supplyDefaults=t("./defaults").supplyDefaults,n.crossTraceDefaults=t("./defaults").crossTraceDefaults,n.supplyLayoutDefaults=t("./layout_defaults"),n.calc=t("./calc"),n.crossTraceCalc=t("./cross_trace_calc").crossTraceCalc,n.colorbar=t("../scatter/marker_colorbar"),n.arraysToCalcdata=t("./arrays_to_calcdata"),n.plot=t("./plot"),n.style=t("./style").style,n.styleOnSelect=t("./style").styleOnSelect,n.hoverPoints=t("./hover").hoverPoints,n.selectPoints=t("./select"),n.moduleType="trace",n.name="bar",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","svg","bar","oriented","errorBarsOK","showLegend","zoomScale"],n.meta={},e.exports=n},{"../../plots/cartesian":756,"../scatter/marker_colorbar":1066,"./arrays_to_calcdata":835,"./attributes":836,"./calc":837,"./cross_trace_calc":839,"./defaults":840,"./hover":842,"./layout_attributes":844,"./layout_defaults":845,"./plot":846,"./select":847,"./style":849}],844:[function(t,e,r){"use strict";e.exports={barmode:{valType:"enumerated",values:["stack","group","overlay","relative"],dflt:"group",editType:"calc"},barnorm:{valType:"enumerated",values:["","fraction","percent"],dflt:"",editType:"calc"},bargap:{valType:"number",min:0,max:1,editType:"calc"},bargroupgap:{valType:"number",min:0,max:1,dflt:0,editType:"calc"}}},{}],845:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("../../plots/cartesian/axes"),a=t("../../lib"),o=t("./layout_attributes");e.exports=function(t,e,r){function s(r,n){return a.coerce(t,e,o,r,n)}for(var l=!1,c=!1,u=!1,h={},f=0;f<r.length;f++){var p=r[f];if(n.traceIs(p,"bar")&&p.visible){if(l=!0,"overlay"!==t.barmode&&"stack"!==t.barmode){var d=p.xaxis+p.yaxis;h[d]&&(u=!0),h[d]=!0}if(p.visible&&"histogram"===p.type)"category"!==i.getFromId({_fullLayout:e},p["v"===p.orientation?"xaxis":"yaxis"]).type&&(c=!0)}}l&&("overlay"!==s("barmode")&&s("barnorm"),s("bargap",c&&!u?0:.2),s("bargroupgap"))}},{"../../lib":697,"../../plots/cartesian/axes":745,"../../registry":826,"./layout_attributes":844}],846:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../../lib"),o=t("../../lib/svg_text_utils"),s=t("../../components/color"),l=t("../../components/drawing"),c=t("../../registry"),u=t("./attributes"),h=u.text,f=u.textposition,p=t("./helpers"),d=t("./style"),g=3;function v(t,e,r,n,i,a){var o;return i<1?o="scale("+i+") ":(i=1,o=""),"translate("+(r-i*t)+" "+(n-i*e)+")"+o+(a?"rotate("+a+" "+t+" "+e+") ":"")}e.exports=function(t,e,r,u){var m=e.xaxis,y=e.yaxis,x=t._fullLayout,b=a.makeTraceGroups(u,r,"trace bars").each(function(r){var c=n.select(this),u=r[0],b=u.trace;e.isRangePlot||(u.node3=c);var _=a.ensureSingle(c,"g","points").selectAll("g.point").data(a.identity);_.enter().append("g").classed("point",!0),_.exit().remove(),_.each(function(c,u){var _,w,k,A,M=n.select(this);if("h"===b.orientation?(k=y.c2p(c.p0,!0),A=y.c2p(c.p1,!0),_=m.c2p(c.s0,!0),w=m.c2p(c.s1,!0),c.ct=[w,(k+A)/2]):(_=m.c2p(c.p0,!0),w=m.c2p(c.p1,!0),k=y.c2p(c.s0,!0),A=y.c2p(c.s1,!0),c.ct=[(_+w)/2,A]),i(_)&&i(w)&&i(k)&&i(A)&&_!==w&&k!==A){var T=(c.mlw+1||b.marker.line.width+1||(c.trace?c.trace.marker.line.width:0)+1)-1,S=n.round(T/2%1,2);if(!t._context.staticPlot){var E=s.opacity(c.mc||b.marker.color)<1||T>.01?C:function(t,e){return Math.abs(t-e)>=2?C(t):t>e?Math.ceil(t):Math.floor(t)};_=E(_,w),w=E(w,_),k=E(k,A),A=E(A,k)}a.ensureSingle(M,"path").style("vector-effect","non-scaling-stroke").attr("d","M"+_+","+k+"V"+A+"H"+w+"V"+k+"Z").call(l.setClipUrl,e.layerClipId,t),function(t,e,r,n,i,s,c,u){var m;function y(e,r,n){var i=a.ensureSingle(e,"text").text(r).attr({class:"bartext bartext-"+m,transform:"","text-anchor":"middle","data-notex":1}).call(l.font,n).call(o.convertToTspans,t);return i}var x=r[0].trace,b=x.orientation,_=function(t,e){var r=p.getValue(t.text,e);return p.coerceString(h,r)}(x,n);if(m=function(t,e){var r=p.getValue(t.textposition,e);return p.coerceEnumerated(f,r)}(x,n),!_||"none"===m)return void e.select("text").remove();var w,k,A,M,T,S,E=t._fullLayout.font,C=d.getBarColor(r[n],x),L=d.getInsideTextFont(x,n,E,C),z=d.getOutsideTextFont(x,n,E),O=t._fullLayout.barmode,I="relative"===O,D="stack"===O||I,P=r[n],R=!D||P._outmost,F=Math.abs(s-i)-2*g,B=Math.abs(u-c)-2*g;"outside"===m&&(R||P.hasB||(m="inside"));if("auto"===m)if(R){m="inside",w=y(e,_,L),k=l.bBox(w.node()),A=k.width,M=k.height;var N=A>0&&M>0,j=A<=F&&M<=B,V=A<=B&&M<=F,U="h"===b?F>=A*(B/M):B>=M*(F/A);N&&(j||V||U)?m="inside":(m="outside",w.remove(),w=null)}else m="inside";if(!w&&(w=y(e,_,"outside"===m?z:L),k=l.bBox(w.node()),A=k.width,M=k.height,A<=0||M<=0))return void w.remove();"outside"===m?(S="both"===x.constraintext||"outside"===x.constraintext,T=function(t,e,r,n,i,a,o){var s,l="h"===a?Math.abs(n-r):Math.abs(e-t);l>2*g&&(s=g);var c=1;o&&(c="h"===a?Math.min(1,l/i.height):Math.min(1,l/i.width));var u,h,f,p,d=(i.left+i.right)/2,m=(i.top+i.bottom)/2;u=c*i.width,h=c*i.height,"h"===a?e<t?(f=e-s-u/2,p=(r+n)/2):(f=e+s+u/2,p=(r+n)/2):n>r?(f=(t+e)/2,p=n+s+h/2):(f=(t+e)/2,p=n-s-h/2);return v(d,m,f,p,c,!1)}(i,s,c,u,k,b,S)):(S="both"===x.constraintext||"inside"===x.constraintext,T=function(t,e,r,n,i,a,o){var s,l,c,u,h,f,p,d=i.width,m=i.height,y=(i.left+i.right)/2,x=(i.top+i.bottom)/2,b=Math.abs(e-t),_=Math.abs(n-r);b>2*g&&_>2*g?(b-=2*(h=g),_-=2*h):h=0;d<=b&&m<=_?(f=!1,p=1):d<=_&&m<=b?(f=!0,p=1):d<m==b<_?(f=!1,p=o?Math.min(b/d,_/m):1):(f=!0,p=o?Math.min(_/d,b/m):1);f&&(f=90);f?(s=p*m,l=p*d):(s=p*d,l=p*m);"h"===a?e<t?(c=e+h+s/2,u=(r+n)/2):(c=e-h-s/2,u=(r+n)/2):n>r?(c=(t+e)/2,u=n-h-l/2):(c=(t+e)/2,u=n+h+l/2);return v(y,x,c,u,p,f)}(i,s,c,u,k,b,S));w.attr("transform",T)}(t,M,r,u,_,w,k,A),e.layerClipId&&l.hideOutsideRangePoint(c,M.select("text"),m,y,b.xcalendar,b.ycalendar)}else M.remove();function C(t){return 0===x.bargap&&0===x.bargroupgap?n.round(Math.round(t)-S,2):t}});var w=!1===u.trace.cliponaxis;l.setClipUrl(c,w?null:e.layerClipId,t)});c.getComponentMethod("errorbars","plot")(t,b,e)}},{"../../components/color":574,"../../components/drawing":595,"../../lib":697,"../../lib/svg_text_utils":721,"../../registry":826,"./attributes":836,"./helpers":841,"./style":849,d3:151,"fast-isnumeric":218}],847:[function(t,e,r){"use strict";e.exports=function(t,e){var r,n=t.cd,i=t.xaxis,a=t.yaxis,o=[];if(!1===e)for(r=0;r<n.length;r++)n[r].selected=0;else for(r=0;r<n.length;r++){var s=n[r];e.contains(s.ct,!1,r,t)?(o.push({pointNumber:r,x:i.c2d(s.x),y:a.c2d(s.y)}),s.selected=1):s.selected=0}return o}},{}],848:[function(t,e,r){"use strict";e.exports=a;var n=t("../../lib"),i=t("../../constants/numerical").BADNUM;function a(t,e,r){this.traces=t,this.separateNegativeValues=e,this.dontMergeOverlappingData=r;for(var a=1/0,o=[],s=0;s<t.length;s++){for(var l=t[s],c=0;c<l.length;c++){var u=l[c];u.p!==i&&o.push(u.p)}l[0]&&l[0].width1&&(a=Math.min(l[0].width1,a))}this.positions=o;var h=n.distinctVals(o);this.distinctPositions=h.vals,1===h.vals.length&&a!==1/0?this.minDiff=a:this.minDiff=Math.min(h.minDiff,a),this.binWidth=this.minDiff,this.bins={}}a.prototype.put=function(t,e){var r=this.getLabel(t,e),n=this.bins[r]||0;return this.bins[r]=n+e,n},a.prototype.get=function(t,e){var r=this.getLabel(t,e);return this.bins[r]||0},a.prototype.getLabel=function(t,e){return(e<0&&this.separateNegativeValues?"v":"^")+(this.dontMergeOverlappingData?t:Math.round(t/this.binWidth))}},{"../../constants/numerical":674,"../../lib":697}],849:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../components/color"),a=t("../../components/drawing"),o=t("../../lib"),s=t("../../registry"),l=t("./attributes"),c=l.textfont,u=l.insidetextfont,h=l.outsidetextfont,f=t("./helpers");function p(t,e,r){var i=t.selectAll("path"),o=t.selectAll("text");a.pointStyle(i,e,r),o.each(function(t){var i=n.select(this),o=d(i,t,e,r);a.font(i,o)})}function d(t,e,r,n){var i=n._fullLayout.font,a=r.textfont;if(t.classed("bartext-inside")){var o=x(e,r);a=v(r,e.i,i,o)}else t.classed("bartext-outside")&&(a=m(r,e.i,i));return a}function g(t,e,r){return y(c,t.textfont,e,r)}function v(t,e,r,n){var a=g(t,e,r);return(void 0===t._input.textfont||void 0===t._input.textfont.color||Array.isArray(t.textfont.color)&&void 0===t.textfont.color[e])&&(a={color:i.contrast(n),family:a.family,size:a.size}),y(u,t.insidetextfont,e,a)}function m(t,e,r){var n=g(t,e,r);return y(h,t.outsidetextfont,e,n)}function y(t,e,r,n){e=e||{};var i=f.getValue(e.family,r),a=f.getValue(e.size,r),o=f.getValue(e.color,r);return{family:f.coerceString(t.family,i,n.family),size:f.coerceNumber(t.size,a,n.size),color:f.coerceColor(t.color,o,n.color)}}function x(t,e){return t.mc||e.marker.color}e.exports={style:function(t,e){var r=e?e[0].node3:n.select(t).selectAll("g.trace.bars"),i=r.size(),a=t._fullLayout;r.style("opacity",function(t){return t[0].trace.opacity}).each(function(t){("stack"===a.barmode&&i>1||0===a.bargap&&0===a.bargroupgap&&!t[0].trace.marker.line.width)&&n.select(this).attr("shape-rendering","crispEdges")}),r.selectAll("g.points").each(function(e){p(n.select(this),e[0].trace,t)}),s.getComponentMethod("errorbars","style")(r)},styleOnSelect:function(t,e){var r=e[0].node3,i=e[0].trace;i.selectedpoints?function(t,e,r){a.selectedPointStyle(t.selectAll("path"),e),function(t,e,r){t.each(function(t){var i,s=n.select(this);if(t.selected){i=o.extendFlat({},d(s,t,e,r));var l=e.selected.textfont&&e.selected.textfont.color;l&&(i.color=l),a.font(s,i)}else a.selectedTextStyle(s,e)})}(t.selectAll("text"),e,r)}(r,i,t):p(r,i,t)},getInsideTextFont:v,getOutsideTextFont:m,getBarColor:x}},{"../../components/color":574,"../../components/drawing":595,"../../lib":697,"../../registry":826,"./attributes":836,"./helpers":841,d3:151}],850:[function(t,e,r){"use strict";var n=t("../../components/color"),i=t("../../components/colorscale/helpers").hasColorscale,a=t("../../components/colorscale/defaults");e.exports=function(t,e,r,o,s){r("marker.color",o),i(t,"marker")&&a(t,e,s,r,{prefix:"marker.",cLetter:"c"}),r("marker.line.color",n.defaultLine),i(t,"marker.line")&&a(t,e,s,r,{prefix:"marker.line.",cLetter:"c"}),r("marker.line.width"),r("marker.opacity"),r("selected.marker.color"),r("unselected.marker.color")}},{"../../components/color":574,"../../components/colorscale/defaults":584,"../../components/colorscale/helpers":585}],851:[function(t,e,r){"use strict";var n=t("../../components/fx/hovertemplate_attributes"),i=t("../../lib/extend").extendFlat,a=t("../scatterpolar/attributes"),o=t("../bar/attributes");e.exports={r:a.r,theta:a.theta,r0:a.r0,dr:a.dr,theta0:a.theta0,dtheta:a.dtheta,thetaunit:a.thetaunit,base:i({},o.base,{}),offset:i({},o.offset,{}),width:i({},o.width,{}),text:i({},o.text,{}),hovertext:i({},o.hovertext,{}),marker:o.marker,hoverinfo:a.hoverinfo,hovertemplate:n(),selected:o.selected,unselected:o.unselected}},{"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../bar/attributes":836,"../scatterpolar/attributes":1110}],852:[function(t,e,r){"use strict";var n=t("../../components/colorscale/helpers").hasColorscale,i=t("../../components/colorscale/calc"),a=t("../bar/arrays_to_calcdata"),o=t("../bar/cross_trace_calc").setGroupPositions,s=t("../scatter/calc_selection"),l=t("../../registry").traceIs,c=t("../../lib").extendFlat;e.exports={calc:function(t,e){for(var r=t._fullLayout,o=e.subplot,l=r[o].radialaxis,c=r[o].angularaxis,u=l.makeCalcdata(e,"r"),h=c.makeCalcdata(e,"theta"),f=e._length,p=new Array(f),d=u,g=h,v=0;v<f;v++)p[v]={p:g[v],s:d[v]};function m(t){var r=e[t];void 0!==r&&(e["_"+t]=Array.isArray(r)?c.makeCalcdata(e,t):c.d2c(r,e.thetaunit))}return"linear"===c.type&&(m("width"),m("offset")),n(e,"marker")&&i(t,e,{vals:e.marker.color,containerStr:"marker",cLetter:"c"}),n(e,"marker.line")&&i(t,e,{vals:e.marker.line.color,containerStr:"marker.line",cLetter:"c"}),a(p,e),s(p,e),p},crossTraceCalc:function(t,e,r){for(var n=t.calcdata,i=[],a=0;a<n.length;a++){var s=n[a],u=s[0].trace;!0===u.visible&&l(u,"bar")&&u.subplot===r&&i.push(s)}var h=c({},e.radialaxis,{_id:"x"}),f=e.angularaxis;o({_fullLayout:e},f,h,i)}}},{"../../components/colorscale/calc":582,"../../components/colorscale/helpers":585,"../../lib":697,"../../registry":826,"../bar/arrays_to_calcdata":835,"../bar/cross_trace_calc":839,"../scatter/calc_selection":1050}],853:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../scatterpolar/defaults").handleRThetaDefaults,a=t("../bar/style_defaults"),o=t("./attributes");e.exports=function(t,e,r,s){function l(r,i){return n.coerce(t,e,o,r,i)}i(t,e,s,l)?(l("thetaunit"),l("base"),l("offset"),l("width"),l("text"),l("hovertext"),l("hovertemplate"),a(t,e,l,r,s),n.coerceSelectionMarkerOpacity(e,l)):e.visible=!1}},{"../../lib":697,"../bar/style_defaults":850,"../scatterpolar/defaults":1112,"./attributes":851}],854:[function(t,e,r){"use strict";var n=t("../../components/fx"),i=t("../../lib"),a=t("../bar/hover").getTraceColor,o=t("../scatter/fill_hover_text"),s=t("../scatterpolar/hover").makeHoverPointText,l=t("../../plots/polar/helpers").isPtInsidePolygon;e.exports=function(t,e,r){var c=t.cd,u=c[0].trace,h=t.subplot,f=h.radialAxis,p=h.angularAxis,d=h.vangles,g=d?l:i.isPtInsideSector,v=t.maxHoverDistance,m=p._period||2*Math.PI,y=Math.abs(f.g2p(Math.sqrt(e*e+r*r))),x=Math.atan2(r,e);f.range[0]>f.range[1]&&(x+=Math.PI);if(n.getClosest(c,function(t){return g(y,x,[t.rp0,t.rp1],[t.thetag0,t.thetag1],d)?v+Math.min(1,Math.abs(t.thetag1-t.thetag0)/m)-1+(t.rp1-y)/(t.rp1-t.rp0)-1:1/0},t),!1!==t.index){var b=c[t.index];t.x0=t.x1=b.ct[0],t.y0=t.y1=b.ct[1];var _=i.extendFlat({},b,{r:b.s,theta:b.p});return o(b,u,t),s(_,u,h,t),t.hovertemplate=u.hovertemplate,t.color=a(u,b),t.xLabelVal=t.yLabelVal=void 0,b.s<0&&(t.idealAlign="left"),[t]}}},{"../../components/fx":613,"../../lib":697,"../../plots/polar/helpers":809,"../bar/hover":842,"../scatter/fill_hover_text":1056,"../scatterpolar/hover":1113}],855:[function(t,e,r){"use strict";e.exports={moduleType:"trace",name:"barpolar",basePlotModule:t("../../plots/polar"),categories:["polar","bar","showLegend"],attributes:t("./attributes"),layoutAttributes:t("./layout_attributes"),supplyDefaults:t("./defaults"),supplyLayoutDefaults:t("./layout_defaults"),calc:t("./calc").calc,crossTraceCalc:t("./calc").crossTraceCalc,plot:t("./plot"),colorbar:t("../scatter/marker_colorbar"),style:t("../bar/style").style,hoverPoints:t("./hover"),selectPoints:t("../bar/select"),meta:{}}},{"../../plots/polar":810,"../bar/select":847,"../bar/style":849,"../scatter/marker_colorbar":1066,"./attributes":851,"./calc":852,"./defaults":853,"./hover":854,"./layout_attributes":856,"./layout_defaults":857,"./plot":858}],856:[function(t,e,r){"use strict";e.exports={barmode:{valType:"enumerated",values:["stack","overlay"],dflt:"stack",editType:"calc"},bargap:{valType:"number",dflt:.1,min:0,max:1,editType:"calc"}}},{}],857:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./layout_attributes");e.exports=function(t,e,r){var a,o={};function s(r,o){return n.coerce(t[a]||{},e[a],i,r,o)}for(var l=0;l<r.length;l++){var c=r[l];"barpolar"===c.type&&!0===c.visible&&(o[a=c.subplot]||(s("barmode"),s("bargap"),o[a]=1))}}},{"../../lib":697,"./layout_attributes":856}],858:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../../lib"),o=t("../../components/drawing"),s=t("../../plots/polar/helpers");e.exports=function(t,e,r){var l=e.xaxis,c=e.yaxis,u=e.radialAxis,h=e.angularAxis,f=function(t){var e=t.cxx,r=t.cyy;if(t.vangles)return function(n,i,o,l){var c,u;a.angleDelta(o,l)>0?(c=o,u=l):(c=l,u=o);var h=s.findEnclosingVertexAngles(c,t.vangles)[0],f=s.findEnclosingVertexAngles(u,t.vangles)[1],p=[h,(c+u)/2,f];return s.pathPolygonAnnulus(n,i,c,u,p,e,r)};return function(t,n,i,o){return a.pathAnnulus(t,n,i,o,e,r)}}(e),p=e.layers.frontplot.select("g.barlayer");a.makeTraceGroups(p,r,"trace bars").each(function(r){var s=r[0].node3=n.select(this),p=a.ensureSingle(s,"g","points").selectAll("g.point").data(a.identity);p.enter().append("g").style("vector-effect","non-scaling-stroke").style("stroke-miterlimit",2).classed("point",!0),p.exit().remove(),p.each(function(t){var e,r=n.select(this),o=t.rp0=u.c2p(t.s0),s=t.rp1=u.c2p(t.s1),p=t.thetag0=h.c2g(t.p0),d=t.thetag1=h.c2g(t.p1);if(i(o)&&i(s)&&i(p)&&i(d)&&o!==s&&p!==d){var g=u.c2g(t.s1),v=(p+d)/2;t.ct=[l.c2p(g*Math.cos(v)),c.c2p(g*Math.sin(v))],e=f(o,s,p,d)}else e="M0,0Z";a.ensureSingle(r,"path").attr("d",e)}),o.setClipUrl(s,e._hasClipOnAxisFalse?e.clipIds.forTraces:null,t)})}},{"../../components/drawing":595,"../../lib":697,"../../plots/polar/helpers":809,d3:151,"fast-isnumeric":218}],859:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../bar/attributes"),a=t("../../components/color/attributes"),o=t("../../lib/extend").extendFlat,s=n.marker,l=s.line;e.exports={y:{valType:"data_array",editType:"calc+clearAxisTypes"},x:{valType:"data_array",editType:"calc+clearAxisTypes"},x0:{valType:"any",editType:"calc+clearAxisTypes"},y0:{valType:"any",editType:"calc+clearAxisTypes"},name:{valType:"string",editType:"calc+clearAxisTypes"},text:o({},n.text,{}),hovertext:o({},n.hovertext,{}),whiskerwidth:{valType:"number",min:0,max:1,dflt:.5,editType:"calc"},notched:{valType:"boolean",editType:"calc"},notchwidth:{valType:"number",min:0,max:.5,dflt:.25,editType:"calc"},boxpoints:{valType:"enumerated",values:["all","outliers","suspectedoutliers",!1],dflt:"outliers",editType:"calc"},boxmean:{valType:"enumerated",values:[!0,"sd",!1],dflt:!1,editType:"calc"},jitter:{valType:"number",min:0,max:1,editType:"calc"},pointpos:{valType:"number",min:-2,max:2,editType:"calc"},orientation:{valType:"enumerated",values:["v","h"],editType:"calc+clearAxisTypes"},width:{valType:"number",min:0,dflt:0,editType:"calc"},marker:{outliercolor:{valType:"color",dflt:"rgba(0, 0, 0, 0)",editType:"style"},symbol:o({},s.symbol,{arrayOk:!1,editType:"plot"}),opacity:o({},s.opacity,{arrayOk:!1,dflt:1,editType:"style"}),size:o({},s.size,{arrayOk:!1,editType:"calc"}),color:o({},s.color,{arrayOk:!1,editType:"style"}),line:{color:o({},l.color,{arrayOk:!1,dflt:a.defaultLine,editType:"style"}),width:o({},l.width,{arrayOk:!1,dflt:0,editType:"style"}),outliercolor:{valType:"color",editType:"style"},outlierwidth:{valType:"number",min:0,dflt:1,editType:"style"},editType:"style"},editType:"plot"},line:{color:{valType:"color",editType:"style"},width:{valType:"number",min:0,dflt:2,editType:"style"},editType:"plot"},fillcolor:n.fillcolor,offsetgroup:i.offsetgroup,alignmentgroup:i.alignmentgroup,selected:{marker:n.selected.marker,editType:"style"},unselected:{marker:n.unselected.marker,editType:"style"},hoveron:{valType:"flaglist",flags:["boxes","points"],dflt:"boxes+points",editType:"style"}}},{"../../components/color/attributes":573,"../../lib/extend":687,"../bar/attributes":836,"../scatter/attributes":1048}],860:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=i._,o=t("../../plots/cartesian/axes");function s(t,e,r){var n={text:"tx",hovertext:"htx"};for(var i in n)Array.isArray(e[i])&&(t[n[i]]=e[i][r])}function l(t,e){return t.v-e.v}function c(t){return t.v}e.exports=function(t,e){var r,u,h,f,p,d=t._fullLayout,g=o.getFromId(t,e.xaxis||"x"),v=o.getFromId(t,e.yaxis||"y"),m=[],y="violin"===e.type?"_numViolins":"_numBoxes";"h"===e.orientation?(u=g,h="x",f=v,p="y"):(u=v,h="y",f=g,p="x");var x,b=u.makeCalcdata(e,h),_=function(t,e,r,a,o){if(e in t)return r.makeCalcdata(t,e);var s;s=e+"0"in t?t[e+"0"]:"name"in t&&("category"===r.type||n(t.name)&&-1!==["linear","log"].indexOf(r.type)||i.isDateTime(t.name)&&"date"===r.type)?t.name:o;var l="multicategory"===r.type?r.r2c_just_indices(s):r.d2c(s,0,t[e+"calendar"]);return a.map(function(){return l})}(e,p,f,b,d[y]),w=i.distinctVals(_),k=w.vals,A=w.minDiff/2,M=function(t,e){for(var r=t.length,n=new Array(r+1),i=0;i<r;i++)n[i]=t[i]-e;return n[r]=t[r-1]+e,n}(k,A),T=k.length,S=function(t){for(var e=new Array(t),r=0;r<t;r++)e[r]=[];return e}(T);for(r=0;r<e._length;r++){var E=b[r];if(n(E)){var C=i.findBin(_[r],M);if(C>=0&&C<T){var L={v:E,i:r};s(L,e,r),S[C].push(L)}}}var z="all"===(e.boxpoints||e.points)?i.identity:function(t){return t.v<x.lf||t.v>x.uf};for(r=0;r<T;r++)if(S[r].length>0){var O=S[r].sort(l),I=O.map(c),D=I.length;(x={}).pos=k[r],x.pts=O,x.min=I[0],x.max=I[D-1],x.mean=i.mean(I,D),x.sd=i.stdev(I,D,x.mean),x.q1=i.interp(I,.25),x.med=i.interp(I,.5),x.q3=i.interp(I,.75),x.lf=Math.min(x.q1,I[Math.min(i.findBin(2.5*x.q1-1.5*x.q3,I,!0)+1,D-1)]),x.uf=Math.max(x.q3,I[Math.max(i.findBin(2.5*x.q3-1.5*x.q1,I),0)]),x.lo=4*x.q1-3*x.q3,x.uo=4*x.q3-3*x.q1;var P=1.57*(x.q3-x.q1)/Math.sqrt(D);x.ln=x.med-P,x.un=x.med+P,x.pts2=O.filter(z),m.push(x)}!function(t,e){if(i.isArrayOrTypedArray(e.selectedpoints))for(var r=0;r<t.length;r++){for(var n=t[r].pts||[],a={},o=0;o<n.length;o++)a[n[o].i]=o;i.tagSelected(n,e,a)}}(m,e);var R=o.findExtremes(u,b,{padded:!0});return e._extremes[u._id]=R,m.length>0?(m[0].t={num:d[y],dPos:A,posLetter:p,valLetter:h,labels:{med:a(t,"median:"),min:a(t,"min:"),q1:a(t,"q1:"),q3:a(t,"q3:"),max:a(t,"max:"),mean:"sd"===e.boxmean?a(t,"mean \xb1 \u03c3:"):a(t,"mean:"),lf:a(t,"lower fence:"),uf:a(t,"upper fence:")}},d[y]++,m):[{t:{empty:!0}}]}},{"../../lib":697,"../../plots/cartesian/axes":745,"fast-isnumeric":218}],861:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axes"),i=t("../../lib"),a=t("../../plots/cartesian/axis_ids").getAxisGroup,o=["v","h"];function s(t,e,r,o){var s,l,c,u=e.calcdata,h=e._fullLayout,f=o._id,p=f.charAt(0),d=[],g=0;for(s=0;s<r.length;s++)for(c=u[r[s]],l=0;l<c.length;l++)d.push(c[l].pos),g+=(c[l].pts2||[]).length;if(d.length){var v=i.distinctVals(d),m=v.minDiff/2;n.minDtick(o,v.minDiff,v.vals[0],!0);var y=h["violin"===t?"_numViolins":"_numBoxes"],x="group"===h[t+"mode"]&&y>1,b=1-h[t+"gap"],_=1-h[t+"groupgap"];for(s=0;s<r.length;s++){var w,k,A,M,T,S,E=(c=u[r[s]])[0].trace,C=c[0].t,L=E.width,z=E.side;if(L)w=k=M=L/2,A=0;else if(w=m,x){var O=a(h,o._id)+E.orientation,I=(h._alignmentOpts[O]||{})[E.alignmentgroup]||{},D=Object.keys(I.offsetGroups||{}).length,P=D||y;k=w*b*_/P,A=2*w*(((D?E._offsetIndex:C.num)+.5)/P-.5)*b,M=w*b/P}else k=w*b*_,A=0,M=w;C.dPos=w,C.bPos=A,C.bdPos=k,C.wHover=M;var R,F,B,N,j,V,U=A+k;"positive"===z?(T=w*(L?1:.5),R=U,S=R=A):"negative"===z?(T=R=A,S=w*(L?1:.5),F=U):(T=S=w,R=F=U);var q=!1;if((E.boxpoints||E.points)&&g>0){var H=E.pointpos,G=E.jitter,Y=E.marker.size/2,W=0;H+G>=0&&((W=U*(H+G))>T?(q=!0,j=Y,B=W):W>R&&(j=Y,B=T)),W<=T&&(B=T);var X=0;H-G<=0&&((X=-U*(H-G))>S?(q=!0,V=Y,N=X):X>F&&(V=Y,N=S)),X<=S&&(N=S)}else B=T,N=S;var Z=new Array(c.length);for(l=0;l<c.length;l++)Z[l]=c[l].pos;E._extremes[f]=n.findExtremes(o,Z,{padded:q,vpadminus:N,vpadplus:B,ppadminus:{x:V,y:j}[p],ppadplus:{x:j,y:V}[p]})}}}e.exports={crossTraceCalc:function(t,e){for(var r=t.calcdata,n=e.xaxis,i=e.yaxis,a=0;a<o.length;a++){for(var l=o[a],c="h"===l?i:n,u=[],h=0;h<r.length;h++){var f=r[h],p=f[0].t,d=f[0].trace;!0!==d.visible||"box"!==d.type&&"candlestick"!==d.type||p.empty||(d.orientation||"v")!==l||d.xaxis!==n._id||d.yaxis!==i._id||u.push(h)}s("box",t,u,c)}},setPositionOffset:s}},{"../../lib":697,"../../plots/cartesian/axes":745,"../../plots/cartesian/axis_ids":748}],862:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../registry"),a=t("../../components/color"),o=t("../bar/defaults").handleGroupingDefaults,s=t("./attributes");function l(t,e,r,a){var o,s,l=r("y"),c=r("x"),u=c&&c.length;if(l&&l.length)o="v",u?s=Math.min(n.minRowLength(c),n.minRowLength(l)):(r("x0"),s=n.minRowLength(l));else{if(!u)return void(e.visible=!1);o="h",r("y0"),s=n.minRowLength(c)}e._length=s,i.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y"],a),r("orientation",o)}function c(t,e,r,i){var a=i.prefix,o=n.coerce2(t,e,s,"marker.outliercolor"),l=r("marker.line.outliercolor"),c=r(a+"points",o||l?"suspectedoutliers":void 0);c?(r("jitter","all"===c?.3:0),r("pointpos","all"===c?-1.5:0),r("marker.symbol"),r("marker.opacity"),r("marker.size"),r("marker.color",e.line.color),r("marker.line.color"),r("marker.line.width"),"suspectedoutliers"===c&&(r("marker.line.outliercolor",e.marker.color),r("marker.line.outlierwidth")),r("selected.marker.color"),r("unselected.marker.color"),r("selected.marker.size"),r("unselected.marker.size"),r("text"),r("hovertext")):delete e.marker,r("hoveron"),n.coerceSelectionMarkerOpacity(e,r)}e.exports={supplyDefaults:function(t,e,r,i){function o(r,i){return n.coerce(t,e,s,r,i)}l(t,e,o,i),!1!==e.visible&&(o("line.color",(t.marker||{}).color||r),o("line.width"),o("fillcolor",a.addOpacity(e.line.color,.5)),o("whiskerwidth"),o("boxmean"),o("width"),o("notched",void 0!==t.notchwidth)&&o("notchwidth"),c(t,e,o,{prefix:"box"}))},crossTraceDefaults:function(t,e){var r,i;function a(t){return n.coerce(i._input,i,s,t)}for(var l=0;l<t.length;l++){var c=(i=t[l]).type;"box"!==c&&"violin"!==c||(r=i._input,"group"===e[c+"mode"]&&o(r,i,e,a))}},handleSampleDefaults:l,handlePointsDefaults:c}},{"../../components/color":574,"../../lib":697,"../../registry":826,"../bar/defaults":840,"./attributes":859}],863:[function(t,e,r){"use strict";e.exports=function(t,e){return e.hoverOnBox&&(t.hoverOnBox=e.hoverOnBox),"xVal"in e&&(t.x=e.xVal),"yVal"in e&&(t.y=e.yVal),e.xa&&(t.xaxis=e.xa),e.ya&&(t.yaxis=e.ya),t}},{}],864:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axes"),i=t("../../lib"),a=t("../../components/fx"),o=t("../../components/color"),s=t("../scatter/fill_hover_text");function l(t,e,r,s){var l,c,u,h,f,p,d,g,v,m,y,x,b=t.cd,_=t.xa,w=t.ya,k=b[0].trace,A=b[0].t,M="violin"===k.type,T=[],S=A.bdPos,E=A.wHover,C=function(t){return t.pos+A.bPos-p};M&&"both"!==k.side?("positive"===k.side&&(v=function(t){var e=C(t);return a.inbox(e,e+E,m)}),"negative"===k.side&&(v=function(t){var e=C(t);return a.inbox(e-E,e,m)})):v=function(t){var e=C(t);return a.inbox(e-E,e+E,m)},x=M?function(t){return a.inbox(t.span[0]-f,t.span[1]-f,m)}:function(t){return a.inbox(t.min-f,t.max-f,m)},"h"===k.orientation?(f=e,p=r,d=x,g=v,l="y",u=w,c="x",h=_):(f=r,p=e,d=v,g=x,l="x",u=_,c="y",h=w);var L=Math.min(1,S/Math.abs(u.r2c(u.range[1])-u.r2c(u.range[0])));function z(t){return(d(t)+g(t))/2}m=t.maxHoverDistance-L,y=t.maxSpikeDistance-L;var O=a.getDistanceFunction(s,d,g,z);if(a.getClosest(b,O,t),!1===t.index)return[];var I=b[t.index],D=k.line.color,P=(k.marker||{}).color;o.opacity(D)&&k.line.width?t.color=D:o.opacity(P)&&k.boxpoints?t.color=P:t.color=k.fillcolor,t[l+"0"]=u.c2p(I.pos+A.bPos-S,!0),t[l+"1"]=u.c2p(I.pos+A.bPos+S,!0),t[l+"LabelVal"]=I.pos;var R=l+"Spike";t.spikeDistance=z(I)*y/m,t[R]=u.c2p(I.pos,!0);var F={},B=["med","min","q1","q3","max"];(k.boxmean||(k.meanline||{}).visible)&&B.push("mean"),(k.boxpoints||k.points)&&B.push("lf","uf");for(var N=0;N<B.length;N++){var j=B[N];if(j in I&&!(I[j]in F)){F[I[j]]=!0;var V=I[j],U=h.c2p(V,!0),q=i.extendFlat({},t);q[c+"0"]=q[c+"1"]=U,q[c+"LabelVal"]=V,q[c+"Label"]=(A.labels?A.labels[j]+" ":"")+n.hoverLabelText(h,V),q.hoverOnBox=!0,"mean"===j&&"sd"in I&&"sd"===k.boxmean&&(q[c+"err"]=I.sd),t.name="",t.spikeDistance=void 0,t[R]=void 0,T.push(q)}}return T}function c(t,e,r){for(var n,o,l,c=t.cd,u=t.xa,h=t.ya,f=c[0].trace,p=u.c2p(e),d=h.c2p(r),g=a.quadrature(function(t){var e=Math.max(3,t.mrc||0);return Math.max(Math.abs(u.c2p(t.x)-p)-e,1-3/e)},function(t){var e=Math.max(3,t.mrc||0);return Math.max(Math.abs(h.c2p(t.y)-d)-e,1-3/e)}),v=!1,m=0;m<c.length;m++){o=c[m];for(var y=0;y<(o.pts||[]).length;y++){var x=g(l=o.pts[y]);x<=t.distance&&(t.distance=x,v=[m,y])}}if(!v)return!1;l=(o=c[v[0]]).pts[v[1]];var b,_=u.c2p(l.x,!0),w=h.c2p(l.y,!0),k=l.mrc||1;return n=i.extendFlat({},t,{index:l.i,color:(f.marker||{}).color,name:f.name,x0:_-k,x1:_+k,y0:w-k,y1:w+k,spikeDistance:t.distance}),"h"===f.orientation?(b=h,n.xLabelVal=l.x,n.yLabelVal=o.pos):(b=u,n.xLabelVal=o.pos,n.yLabelVal=l.y),n[b._id.charAt(0)+"Spike"]=b.c2p(o.pos,!0),s(l,f,n),n}e.exports={hoverPoints:function(t,e,r,n){var i,a=t.cd[0].trace.hoveron,o=[];return-1!==a.indexOf("boxes")&&(o=o.concat(l(t,e,r,n))),-1!==a.indexOf("points")&&(i=c(t,e,r)),"closest"===n?i?[i]:o:i?(o.push(i),o):o},hoverOnBoxes:l,hoverOnPoints:c}},{"../../components/color":574,"../../components/fx":613,"../../lib":697,"../../plots/cartesian/axes":745,"../scatter/fill_hover_text":1056}],865:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.layoutAttributes=t("./layout_attributes"),n.supplyDefaults=t("./defaults").supplyDefaults,n.crossTraceDefaults=t("./defaults").crossTraceDefaults,n.supplyLayoutDefaults=t("./layout_defaults").supplyLayoutDefaults,n.calc=t("./calc"),n.crossTraceCalc=t("./cross_trace_calc").crossTraceCalc,n.plot=t("./plot").plot,n.style=t("./style").style,n.styleOnSelect=t("./style").styleOnSelect,n.hoverPoints=t("./hover").hoverPoints,n.eventData=t("./event_data"),n.selectPoints=t("./select"),n.moduleType="trace",n.name="box",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","svg","symbols","oriented","box-violin","showLegend","boxLayout","zoomScale"],n.meta={},e.exports=n},{"../../plots/cartesian":756,"./attributes":859,"./calc":860,"./cross_trace_calc":861,"./defaults":862,"./event_data":863,"./hover":864,"./layout_attributes":866,"./layout_defaults":867,"./plot":868,"./select":869,"./style":870}],866:[function(t,e,r){"use strict";e.exports={boxmode:{valType:"enumerated",values:["group","overlay"],dflt:"overlay",editType:"calc"},boxgap:{valType:"number",min:0,max:1,dflt:.3,editType:"calc"},boxgroupgap:{valType:"number",min:0,max:1,dflt:.3,editType:"calc"}}},{}],867:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("../../lib"),a=t("./layout_attributes");function o(t,e,r,i,a){for(var o=a+"Layout",s=!1,l=0;l<r.length;l++){var c=r[l];if(n.traceIs(c,o)){s=!0;break}}s&&(i(a+"mode"),i(a+"gap"),i(a+"groupgap"))}e.exports={supplyLayoutDefaults:function(t,e,r){o(0,0,r,function(r,n){return i.coerce(t,e,a,r,n)},"box")},_supply:o}},{"../../lib":697,"../../registry":826,"./layout_attributes":866}],868:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../lib"),a=t("../../components/drawing"),o=5,s=.01;function l(t,e,r,a){var o,s,l=e.pos,c=e.val,u=a.bPos,h=a.wdPos||0,f=a.bPosPxOffset||0,p=r.whiskerwidth||0,d=r.notched||!1,g=d?1-2*r.notchwidth:1;Array.isArray(a.bdPos)?(o=a.bdPos[0],s=a.bdPos[1]):(o=a.bdPos,s=a.bdPos);var v=t.selectAll("path.box").data("violin"!==r.type||r.box.visible?i.identity:[]);v.enter().append("path").style("vector-effect","non-scaling-stroke").attr("class","box"),v.exit().remove(),v.each(function(t){if(t.empty)return"M0,0Z";var e=t.pos,a=l.c2p(e+u,!0)+f,v=l.c2p(e+u-o,!0)+f,m=l.c2p(e+u+s,!0)+f,y=l.c2p(e+u-h,!0)+f,x=l.c2p(e+u+h,!0)+f,b=l.c2p(e+u-o*g,!0)+f,_=l.c2p(e+u+s*g,!0)+f,w=c.c2p(t.q1,!0),k=c.c2p(t.q3,!0),A=i.constrain(c.c2p(t.med,!0),Math.min(w,k)+1,Math.max(w,k)-1),M=void 0===t.lf||!1===r.boxpoints,T=c.c2p(M?t.min:t.lf,!0),S=c.c2p(M?t.max:t.uf,!0),E=c.c2p(t.ln,!0),C=c.c2p(t.un,!0);"h"===r.orientation?n.select(this).attr("d","M"+A+","+b+"V"+_+"M"+w+","+v+"V"+m+(d?"H"+E+"L"+A+","+_+"L"+C+","+m:"")+"H"+k+"V"+v+(d?"H"+C+"L"+A+","+b+"L"+E+","+v:"")+"ZM"+w+","+a+"H"+T+"M"+k+","+a+"H"+S+(0===p?"":"M"+T+","+y+"V"+x+"M"+S+","+y+"V"+x)):n.select(this).attr("d","M"+b+","+A+"H"+_+"M"+v+","+w+"H"+m+(d?"V"+E+"L"+_+","+A+"L"+m+","+C:"")+"V"+k+"H"+v+(d?"V"+C+"L"+b+","+A+"L"+v+","+E:"")+"ZM"+a+","+w+"V"+T+"M"+a+","+k+"V"+S+(0===p?"":"M"+y+","+T+"H"+x+"M"+y+","+S+"H"+x))})}function c(t,e,r,n){var l=e.x,c=e.y,u=n.bdPos,h=n.bPos,f=r.boxpoints||r.points;i.seedPseudoRandom();var p=t.selectAll("g.points").data(f?function(t){return t.forEach(function(t){t.t=n,t.trace=r}),t}:[]);p.enter().append("g").attr("class","points"),p.exit().remove();var d=p.selectAll("path").data(function(t){var e,n,a=t.pts2,l=Math.max((t.max-t.min)/10,t.q3-t.q1),c=1e-9*l,p=l*s,d=[],g=0;if(r.jitter){if(0===l)for(g=1,d=new Array(a.length),e=0;e<a.length;e++)d[e]=1;else for(e=0;e<a.length;e++){var v=Math.max(0,e-o),m=a[v].v,y=Math.min(a.length-1,e+o),x=a[y].v;"all"!==f&&(a[e].v<t.lf?x=Math.min(x,t.lf):m=Math.max(m,t.uf));var b=Math.sqrt(p*(y-v)/(x-m+c))||0;b=i.constrain(Math.abs(b),0,1),d.push(b),g=Math.max(b,g)}n=2*r.jitter/(g||1)}for(e=0;e<a.length;e++){var _=a[e],w=_.v,k=r.jitter?n*d[e]*(i.pseudoRandom()-.5):0,A=t.pos+h+u*(r.pointpos+k);"h"===r.orientation?(_.y=A,_.x=w):(_.x=A,_.y=w),"suspectedoutliers"===f&&w<t.uo&&w>t.lo&&(_.so=!0)}return a});d.enter().append("path").classed("point",!0),d.exit().remove(),d.call(a.translatePoints,l,c)}function u(t,e,r,a){var o,s,l=e.pos,c=e.val,u=a.bPos,h=a.bPosPxOffset||0,f=r.boxmean||(r.meanline||{}).visible;Array.isArray(a.bdPos)?(o=a.bdPos[0],s=a.bdPos[1]):(o=a.bdPos,s=a.bdPos);var p=t.selectAll("path.mean").data("box"===r.type&&r.boxmean||"violin"===r.type&&r.box.visible&&r.meanline.visible?i.identity:[]);p.enter().append("path").attr("class","mean").style({fill:"none","vector-effect":"non-scaling-stroke"}),p.exit().remove(),p.each(function(t){var e=l.c2p(t.pos+u,!0)+h,i=l.c2p(t.pos+u-o,!0)+h,a=l.c2p(t.pos+u+s,!0)+h,p=c.c2p(t.mean,!0),d=c.c2p(t.mean-t.sd,!0),g=c.c2p(t.mean+t.sd,!0);"h"===r.orientation?n.select(this).attr("d","M"+p+","+i+"V"+a+("sd"===f?"m0,0L"+d+","+e+"L"+p+","+i+"L"+g+","+e+"Z":"")):n.select(this).attr("d","M"+i+","+p+"H"+a+("sd"===f?"m0,0L"+e+","+d+"L"+i+","+p+"L"+e+","+g+"Z":""))})}e.exports={plot:function(t,e,r,a){var o=e.xaxis,s=e.yaxis;i.makeTraceGroups(a,r,"trace boxes").each(function(t){var r,i,a=n.select(this),h=t[0],f=h.t,p=h.trace;e.isRangePlot||(h.node3=a),f.wdPos=f.bdPos*p.whiskerwidth,!0!==p.visible||f.empty?a.remove():("h"===p.orientation?(r=s,i=o):(r=o,i=s),l(a,{pos:r,val:i},p,f),c(a,{x:o,y:s},p,f),u(a,{pos:r,val:i},p,f))})},plotBoxAndWhiskers:l,plotPoints:c,plotBoxMean:u}},{"../../components/drawing":595,"../../lib":697,d3:151}],869:[function(t,e,r){"use strict";e.exports=function(t,e){var r,n,i=t.cd,a=t.xaxis,o=t.yaxis,s=[];if(!1===e)for(r=0;r<i.length;r++)for(n=0;n<(i[r].pts||[]).length;n++)i[r].pts[n].selected=0;else for(r=0;r<i.length;r++)for(n=0;n<(i[r].pts||[]).length;n++){var l=i[r].pts[n],c=a.c2p(l.x),u=o.c2p(l.y);e.contains([c,u],null,l.i,t)?(s.push({pointNumber:l.i,x:a.c2d(l.x),y:o.c2d(l.y)}),l.selected=1):l.selected=0}return s}},{}],870:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../components/color"),a=t("../../components/drawing");e.exports={style:function(t,e){var r=e?e[0].node3:n.select(t).selectAll("g.trace.boxes");r.style("opacity",function(t){return t[0].trace.opacity}),r.each(function(e){var r=n.select(this),o=e[0].trace,s=o.line.width;function l(t,e,r,n){t.style("stroke-width",e+"px").call(i.stroke,r).call(i.fill,n)}var c=r.selectAll("path.box");if("candlestick"===o.type)c.each(function(t){if(!t.empty){var e=n.select(this),r=o[t.dir];l(e,r.line.width,r.line.color,r.fillcolor),e.style("opacity",o.selectedpoints&&!t.selected?.3:1)}});else{l(c,s,o.line.color,o.fillcolor),r.selectAll("path.mean").style({"stroke-width":s,"stroke-dasharray":2*s+"px,"+s+"px"}).call(i.stroke,o.line.color);var u=r.selectAll("path.point");a.pointStyle(u,o,t)}})},styleOnSelect:function(t,e){var r=e[0].node3,n=e[0].trace,i=r.selectAll("path.point");n.selectedpoints?a.selectedPointStyle(i,n):a.pointStyle(i,n,t)}}},{"../../components/color":574,"../../components/drawing":595,d3:151}],871:[function(t,e,r){"use strict";var n=t("../../lib").extendFlat,i=t("../ohlc/attributes"),a=t("../box/attributes");function o(t){return{line:{color:n({},a.line.color,{dflt:t}),width:a.line.width,editType:"style"},fillcolor:a.fillcolor,editType:"style"}}e.exports={x:i.x,open:i.open,high:i.high,low:i.low,close:i.close,line:{width:n({},a.line.width,{}),editType:"style"},increasing:o(i.increasing.line.color.dflt),decreasing:o(i.decreasing.line.color.dflt),text:i.text,hovertext:i.hovertext,whiskerwidth:n({},a.whiskerwidth,{dflt:0}),hoverlabel:i.hoverlabel}},{"../../lib":697,"../box/attributes":859,"../ohlc/attributes":996}],872:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/cartesian/axes"),a=t("../ohlc/calc").calcCommon;function o(t,e,r,n){return{min:r,q1:Math.min(t,n),med:n,q3:Math.max(t,n),max:e}}e.exports=function(t,e){var r=t._fullLayout,s=i.getFromId(t,e.xaxis),l=i.getFromId(t,e.yaxis),c=s.makeCalcdata(e,"x"),u=a(t,e,c,l,o);return u.length?(n.extendFlat(u[0].t,{num:r._numBoxes,dPos:n.distinctVals(c).minDiff/2,posLetter:"x",valLetter:"y"}),r._numBoxes++,u):[{t:{empty:!0}}]}},{"../../lib":697,"../../plots/cartesian/axes":745,"../ohlc/calc":997}],873:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/color"),a=t("../ohlc/ohlc_defaults"),o=t("./attributes");function s(t,e,r,n){var a=r(n+".line.color");r(n+".line.width",e.line.width),r(n+".fillcolor",i.addOpacity(a,.5))}e.exports=function(t,e,r,i){function l(r,i){return n.coerce(t,e,o,r,i)}a(t,e,l,i)?(l("line.width"),s(t,e,l,"increasing"),s(t,e,l,"decreasing"),l("text"),l("hovertext"),l("whiskerwidth"),i._requestRangeslider[e.xaxis]=!0):e.visible=!1}},{"../../components/color":574,"../../lib":697,"../ohlc/ohlc_defaults":1001,"./attributes":871}],874:[function(t,e,r){"use strict";e.exports={moduleType:"trace",name:"candlestick",basePlotModule:t("../../plots/cartesian"),categories:["cartesian","svg","showLegend","candlestick","boxLayout"],meta:{},attributes:t("./attributes"),layoutAttributes:t("../box/layout_attributes"),supplyLayoutDefaults:t("../box/layout_defaults").supplyLayoutDefaults,crossTraceCalc:t("../box/cross_trace_calc").crossTraceCalc,supplyDefaults:t("./defaults"),calc:t("./calc"),plot:t("../box/plot").plot,layerName:"boxlayer",style:t("../box/style").style,hoverPoints:t("../ohlc/hover").hoverPoints,selectPoints:t("../ohlc/select")}},{"../../plots/cartesian":756,"../box/cross_trace_calc":861,"../box/layout_attributes":866,"../box/layout_defaults":867,"../box/plot":868,"../box/style":870,"../ohlc/hover":999,"../ohlc/select":1003,"./attributes":871,"./calc":872,"./defaults":873}],875:[function(t,e,r){"use strict";var n=t("./axis_defaults"),i=t("../../plot_api/plot_template");e.exports=function(t,e,r,a,o){a("a")||(a("da"),a("a0")),a("b")||(a("db"),a("b0")),function(t,e,r,a){["aaxis","baxis"].forEach(function(o){var s=o.charAt(0),l=t[o]||{},c=i.newContainer(e,o),u={tickfont:"x",id:s+"axis",letter:s,font:e.font,name:o,data:t[s],calendar:e.calendar,dfltColor:a,bgColor:r.paper_bgcolor,fullLayout:r};n(l,c,u),c._categories=c._categories||[],t[o]||"-"===l.type||(t[o]={type:l.type})})}(t,e,r,o)}},{"../../plot_api/plot_template":735,"./axis_defaults":880}],876:[function(t,e,r){"use strict";var n=t("../../lib").isArrayOrTypedArray;e.exports=function(t){return function t(e,r){if(!n(e)||r>=10)return null;var i=1/0;var a=-1/0;var o=e.length;for(var s=0;s<o;s++){var l=e[s];if(n(l)){var c=t(l,r+1);c&&(i=Math.min(c[0],i),a=Math.max(c[1],a))}else i=Math.min(l,i),a=Math.max(l,a)}return[i,a]}(t,0)}},{"../../lib":697}],877:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes"),i=t("./axis_attributes"),a=t("../../components/color/attributes"),o=n({editType:"calc"});o.family.dflt='"Open Sans", verdana, arial, sans-serif',o.size.dflt=12,o.color.dflt=a.defaultLine,e.exports={carpet:{valType:"string",editType:"calc"},x:{valType:"data_array",editType:"calc+clearAxisTypes"},y:{valType:"data_array",editType:"calc+clearAxisTypes"},a:{valType:"data_array",editType:"calc"},a0:{valType:"number",dflt:0,editType:"calc"},da:{valType:"number",dflt:1,editType:"calc"},b:{valType:"data_array",editType:"calc"},b0:{valType:"number",dflt:0,editType:"calc"},db:{valType:"number",dflt:1,editType:"calc"},cheaterslope:{valType:"number",dflt:1,editType:"calc"},aaxis:i,baxis:i,font:o,color:{valType:"color",dflt:a.defaultLine,editType:"plot"},transforms:void 0}},{"../../components/color/attributes":573,"../../plots/font_attributes":771,"./axis_attributes":879}],878:[function(t,e,r){"use strict";var n=t("../../lib").isArrayOrTypedArray;e.exports=function(t,e,r,i){var a,o,s,l,c,u,h,f,p,d,g,v,m,y=n(r)?"a":"b",x=("a"===y?t.aaxis:t.baxis).smoothing,b="a"===y?t.a2i:t.b2j,_="a"===y?r:i,w="a"===y?i:r,k="a"===y?e.a.length:e.b.length,A="a"===y?e.b.length:e.a.length,M=Math.floor("a"===y?t.b2j(w):t.a2i(w)),T="a"===y?function(e){return t.evalxy([],e,M)}:function(e){return t.evalxy([],M,e)};x&&(s=Math.max(0,Math.min(A-2,M)),l=M-s,o="a"===y?function(e,r){return t.dxydi([],e,s,r,l)}:function(e,r){return t.dxydj([],s,e,l,r)});var S=b(_[0]),E=b(_[1]),C=S<E?1:-1,L=1e-8*(E-S),z=C>0?Math.floor:Math.ceil,O=C>0?Math.ceil:Math.floor,I=C>0?Math.min:Math.max,D=C>0?Math.max:Math.min,P=z(S+L),R=O(E-L),F=[[h=T(S)]];for(a=P;a*C<R*C;a+=C)c=[],g=D(S,a),m=(v=I(E,a+C))-g,u=Math.max(0,Math.min(k-2,Math.floor(.5*(g+v)))),f=T(v),x&&(p=o(u,g-u),d=o(u,v-u),c.push([h[0]+p[0]/3*m,h[1]+p[1]/3*m]),c.push([f[0]-d[0]/3*m,f[1]-d[1]/3*m])),c.push(f),F.push(c),h=f;return F}},{"../../lib":697}],879:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes"),i=t("../../components/color/attributes"),a=t("../../plots/cartesian/layout_attributes"),o=t("../../plot_api/edit_types").overrideAll;e.exports={color:{valType:"color",editType:"calc"},smoothing:{valType:"number",dflt:1,min:0,max:1.3,editType:"calc"},title:{text:{valType:"string",dflt:"",editType:"calc"},font:n({editType:"calc"}),offset:{valType:"number",dflt:10,editType:"calc"},editType:"calc"},type:{valType:"enumerated",values:["-","linear","date","category"],dflt:"-",editType:"calc"},autorange:{valType:"enumerated",values:[!0,!1,"reversed"],dflt:!0,editType:"calc"},rangemode:{valType:"enumerated",values:["normal","tozero","nonnegative"],dflt:"normal",editType:"calc"},range:{valType:"info_array",editType:"calc",items:[{valType:"any",editType:"calc"},{valType:"any",editType:"calc"}]},fixedrange:{valType:"boolean",dflt:!1,editType:"calc"},cheatertype:{valType:"enumerated",values:["index","value"],dflt:"value",editType:"calc"},tickmode:{valType:"enumerated",values:["linear","array"],dflt:"array",editType:"calc"},nticks:{valType:"integer",min:0,dflt:0,editType:"calc"},tickvals:{valType:"data_array",editType:"calc"},ticktext:{valType:"data_array",editType:"calc"},showticklabels:{valType:"enumerated",values:["start","end","both","none"],dflt:"start",editType:"calc"},tickfont:n({editType:"calc"}),tickangle:{valType:"angle",dflt:"auto",editType:"calc"},tickprefix:{valType:"string",dflt:"",editType:"calc"},showtickprefix:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"calc"},ticksuffix:{valType:"string",dflt:"",editType:"calc"},showticksuffix:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"calc"},showexponent:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"calc"},exponentformat:{valType:"enumerated",values:["none","e","E","power","SI","B"],dflt:"B",editType:"calc"},separatethousands:{valType:"boolean",dflt:!1,editType:"calc"},tickformat:{valType:"string",dflt:"",editType:"calc"},tickformatstops:o(a.tickformatstops,"calc","from-root"),categoryorder:{valType:"enumerated",values:["trace","category ascending","category descending","array"],dflt:"trace",editType:"calc"},categoryarray:{valType:"data_array",editType:"calc"},labelpadding:{valType:"integer",dflt:10,editType:"calc"},labelprefix:{valType:"string",editType:"calc"},labelsuffix:{valType:"string",dflt:"",editType:"calc"},showline:{valType:"boolean",dflt:!1,editType:"calc"},linecolor:{valType:"color",dflt:i.defaultLine,editType:"calc"},linewidth:{valType:"number",min:0,dflt:1,editType:"calc"},gridcolor:{valType:"color",editType:"calc"},gridwidth:{valType:"number",min:0,dflt:1,editType:"calc"},showgrid:{valType:"boolean",dflt:!0,editType:"calc"},minorgridcount:{valType:"integer",min:0,dflt:0,editType:"calc"},minorgridwidth:{valType:"number",min:0,dflt:1,editType:"calc"},minorgridcolor:{valType:"color",dflt:i.lightLine,editType:"calc"},startline:{valType:"boolean",editType:"calc"},startlinecolor:{valType:"color",editType:"calc"},startlinewidth:{valType:"number",dflt:1,editType:"calc"},endline:{valType:"boolean",editType:"calc"},endlinewidth:{valType:"number",dflt:1,editType:"calc"},endlinecolor:{valType:"color",editType:"calc"},tick0:{valType:"number",min:0,dflt:0,editType:"calc"},dtick:{valType:"number",min:0,dflt:1,editType:"calc"},arraytick0:{valType:"integer",min:0,dflt:0,editType:"calc"},arraydtick:{valType:"integer",min:1,dflt:1,editType:"calc"},_deprecated:{title:{valType:"string",editType:"calc"},titlefont:n({editType:"calc"}),titleoffset:{valType:"number",dflt:10,editType:"calc"}},editType:"calc"}},{"../../components/color/attributes":573,"../../plot_api/edit_types":728,"../../plots/cartesian/layout_attributes":757,"../../plots/font_attributes":771}],880:[function(t,e,r){"use strict";var n=t("./attributes"),i=t("../../components/color").addOpacity,a=t("../../registry"),o=t("../../lib"),s=t("../../plots/cartesian/tick_value_defaults"),l=t("../../plots/cartesian/tick_label_defaults"),c=t("../../plots/cartesian/category_order_defaults"),u=t("../../plots/cartesian/set_convert"),h=t("../../plots/cartesian/axis_autotype");e.exports=function(t,e,r){var f=r.letter,p=r.font||{},d=n[f+"axis"];function g(r,n){return o.coerce(t,e,d,r,n)}function v(r,n){return o.coerce2(t,e,d,r,n)}r.name&&(e._name=r.name,e._id=r.name);var m=g("type");("-"===m&&(r.data&&function(t,e){if("-"!==t.type)return;var r=t._id.charAt(0),n=t[r+"calendar"];t.type=h(e,n)}(e,r.data),"-"===e.type?e.type="linear":m=t.type=e.type),g("smoothing"),g("cheatertype"),g("showticklabels"),g("labelprefix",f+" = "),g("labelsuffix"),g("showtickprefix"),g("showticksuffix"),g("separatethousands"),g("tickformat"),g("exponentformat"),g("showexponent"),g("categoryorder"),g("tickmode"),g("tickvals"),g("ticktext"),g("tick0"),g("dtick"),"array"===e.tickmode&&(g("arraytick0"),g("arraydtick")),g("labelpadding"),e._hovertitle=f,"date"===m)&&a.getComponentMethod("calendars","handleDefaults")(t,e,"calendar",r.calendar);u(e,r.fullLayout),e.c2p=o.identity;var y=g("color",r.dfltColor),x=y===t.color?y:p.color;g("title.text")&&(o.coerceFont(g,"title.font",{family:p.family,size:Math.round(1.2*p.size),color:x}),g("title.offset")),g("tickangle"),g("autorange",!e.isValidRange(t.range))&&g("rangemode"),g("range"),e.cleanRange(),g("fixedrange"),s(t,e,g,m),l(t,e,g,m,r),c(t,e,g,{data:r.data,dataAttr:f});var b=v("gridcolor",i(y,.3)),_=v("gridwidth"),w=g("showgrid");w||(delete e.gridcolor,delete e.gridwidth);var k=v("startlinecolor",y),A=v("startlinewidth",_);g("startline",e.showgrid||!!k||!!A)||(delete e.startlinecolor,delete e.startlinewidth);var M=v("endlinecolor",y),T=v("endlinewidth",_);return g("endline",e.showgrid||!!M||!!T)||(delete e.endlinecolor,delete e.endlinewidth),w?(g("minorgridcount"),g("minorgridwidth",_),g("minorgridcolor",i(b,.06)),e.minorgridcount||(delete e.minorgridwidth,delete e.minorgridcolor)):(delete e.gridcolor,delete e.gridWidth),"none"===e.showticklabels&&(delete e.tickfont,delete e.tickangle,delete e.showexponent,delete e.exponentformat,delete e.tickformat,delete e.showticksuffix,delete e.showtickprefix),e.showticksuffix||delete e.ticksuffix,e.showtickprefix||delete e.tickprefix,g("tickmode"),e}},{"../../components/color":574,"../../lib":697,"../../plots/cartesian/axis_autotype":746,"../../plots/cartesian/category_order_defaults":749,"../../plots/cartesian/set_convert":763,"../../plots/cartesian/tick_label_defaults":764,"../../plots/cartesian/tick_value_defaults":766,"../../registry":826,"./attributes":877}],881:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axes"),i=t("../../lib").isArray1D,a=t("./cheater_basis"),o=t("./array_minmax"),s=t("./calc_gridlines"),l=t("./calc_labels"),c=t("./calc_clippath"),u=t("../heatmap/clean_2d_array"),h=t("./smooth_fill_2d_array"),f=t("../heatmap/convert_column_xyz"),p=t("./set_convert");e.exports=function(t,e){var r=n.getFromId(t,e.xaxis),d=n.getFromId(t,e.yaxis),g=e.aaxis,v=e.baxis,m=e.x,y=e.y,x=[];m&&i(m)&&x.push("x"),y&&i(y)&&x.push("y"),x.length&&f(e,g,v,"a","b",x);var b=e._a=e._a||e.a,_=e._b=e._b||e.b;m=e._x||e.x,y=e._y||e.y;var w={};if(e._cheater){var k="index"===g.cheatertype?b.length:b,A="index"===v.cheatertype?_.length:_;m=a(k,A,e.cheaterslope)}e._x=m=u(m),e._y=y=u(y),h(m,b,_),h(y,b,_),p(e),e.setScale();var M=o(m),T=o(y),S=.5*(M[1]-M[0]),E=.5*(M[1]+M[0]),C=.5*(T[1]-T[0]),L=.5*(T[1]+T[0]);return M=[E-1.3*S,E+1.3*S],T=[L-1.3*C,L+1.3*C],e._extremes[r._id]=n.findExtremes(r,M,{padded:!0}),e._extremes[d._id]=n.findExtremes(d,T,{padded:!0}),s(e,"a","b"),s(e,"b","a"),l(e,g),l(e,v),w.clipsegments=c(e._xctrl,e._yctrl,g,v),w.x=m,w.y=y,w.a=b,w.b=_,[w]}},{"../../lib":697,"../../plots/cartesian/axes":745,"../heatmap/clean_2d_array":947,"../heatmap/convert_column_xyz":949,"./array_minmax":876,"./calc_clippath":882,"./calc_gridlines":883,"./calc_labels":884,"./cheater_basis":886,"./set_convert":899,"./smooth_fill_2d_array":900}],882:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){var i,a,o,s=[],l=!!r.smoothing,c=!!n.smoothing,u=t[0].length-1,h=t.length-1;for(i=0,a=[],o=[];i<=u;i++)a[i]=t[0][i],o[i]=e[0][i];for(s.push({x:a,y:o,bicubic:l}),i=0,a=[],o=[];i<=h;i++)a[i]=t[i][u],o[i]=e[i][u];for(s.push({x:a,y:o,bicubic:c}),i=u,a=[],o=[];i>=0;i--)a[u-i]=t[h][i],o[u-i]=e[h][i];for(s.push({x:a,y:o,bicubic:l}),i=h,a=[],o=[];i>=0;i--)a[h-i]=t[i][0],o[h-i]=e[i][0];return s.push({x:a,y:o,bicubic:c}),s}},{}],883:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axes"),i=t("../../lib/extend").extendFlat;e.exports=function(t,e,r){var a,o,s,l,c,u,h,f,p,d,g,v,m,y,x=t["_"+e],b=t[e+"axis"],_=b._gridlines=[],w=b._minorgridlines=[],k=b._boundarylines=[],A=t["_"+r],M=t[r+"axis"];"array"===b.tickmode&&(b.tickvals=x.slice());var T=t._xctrl,S=t._yctrl,E=T[0].length,C=T.length,L=t._a.length,z=t._b.length;n.prepTicks(b),"array"===b.tickmode&&delete b.tickvals;var O=b.smoothing?3:1;function I(n){var i,a,o,s,l,c,u,h,p,d,g,v,m=[],y=[],x={};if("b"===e)for(a=t.b2j(n),o=Math.floor(Math.max(0,Math.min(z-2,a))),s=a-o,x.length=z,x.crossLength=L,x.xy=function(e){return t.evalxy([],e,a)},x.dxy=function(e,r){return t.dxydi([],e,o,r,s)},i=0;i<L;i++)c=Math.min(L-2,i),u=i-c,h=t.evalxy([],i,a),M.smoothing&&i>0&&(p=t.dxydi([],i-1,o,0,s),m.push(l[0]+p[0]/3),y.push(l[1]+p[1]/3),d=t.dxydi([],i-1,o,1,s),m.push(h[0]-d[0]/3),y.push(h[1]-d[1]/3)),m.push(h[0]),y.push(h[1]),l=h;else for(i=t.a2i(n),c=Math.floor(Math.max(0,Math.min(L-2,i))),u=i-c,x.length=L,x.crossLength=z,x.xy=function(e){return t.evalxy([],i,e)},x.dxy=function(e,r){return t.dxydj([],c,e,u,r)},a=0;a<z;a++)o=Math.min(z-2,a),s=a-o,h=t.evalxy([],i,a),M.smoothing&&a>0&&(g=t.dxydj([],c,a-1,u,0),m.push(l[0]+g[0]/3),y.push(l[1]+g[1]/3),v=t.dxydj([],c,a-1,u,1),m.push(h[0]-v[0]/3),y.push(h[1]-v[1]/3)),m.push(h[0]),y.push(h[1]),l=h;return x.axisLetter=e,x.axis=b,x.crossAxis=M,x.value=n,x.constvar=r,x.index=f,x.x=m,x.y=y,x.smoothing=M.smoothing,x}function D(n){var i,a,o,s,l,c=[],u=[],h={};if(h.length=x.length,h.crossLength=A.length,"b"===e)for(o=Math.max(0,Math.min(z-2,n)),l=Math.min(1,Math.max(0,n-o)),h.xy=function(e){return t.evalxy([],e,n)},h.dxy=function(e,r){return t.dxydi([],e,o,r,l)},i=0;i<E;i++)c[i]=T[n*O][i],u[i]=S[n*O][i];else for(a=Math.max(0,Math.min(L-2,n)),s=Math.min(1,Math.max(0,n-a)),h.xy=function(e){return t.evalxy([],n,e)},h.dxy=function(e,r){return t.dxydj([],a,e,s,r)},i=0;i<C;i++)c[i]=T[i][n*O],u[i]=S[i][n*O];return h.axisLetter=e,h.axis=b,h.crossAxis=M,h.value=x[n],h.constvar=r,h.index=n,h.x=c,h.y=u,h.smoothing=M.smoothing,h}if("array"===b.tickmode){for(l=5e-15,u=(c=[Math.floor((x.length-1-b.arraytick0)/b.arraydtick*(1+l)),Math.ceil(-b.arraytick0/b.arraydtick/(1+l))].sort(function(t,e){return t-e}))[0]-1,h=c[1]+1,f=u;f<h;f++)(o=b.arraytick0+b.arraydtick*f)<0||o>x.length-1||_.push(i(D(o),{color:b.gridcolor,width:b.gridwidth}));for(f=u;f<h;f++)if(s=b.arraytick0+b.arraydtick*f,g=Math.min(s+b.arraydtick,x.length-1),!(s<0||s>x.length-1||g<0||g>x.length-1))for(v=x[s],m=x[g],a=0;a<b.minorgridcount;a++)(y=g-s)<=0||(d=v+(m-v)*(a+1)/(b.minorgridcount+1)*(b.arraydtick/y))<x[0]||d>x[x.length-1]||w.push(i(I(d),{color:b.minorgridcolor,width:b.minorgridwidth}));b.startline&&k.push(i(D(0),{color:b.startlinecolor,width:b.startlinewidth})),b.endline&&k.push(i(D(x.length-1),{color:b.endlinecolor,width:b.endlinewidth}))}else{for(l=5e-15,u=(c=[Math.floor((x[x.length-1]-b.tick0)/b.dtick*(1+l)),Math.ceil((x[0]-b.tick0)/b.dtick/(1+l))].sort(function(t,e){return t-e}))[0],h=c[1],f=u;f<=h;f++)p=b.tick0+b.dtick*f,_.push(i(I(p),{color:b.gridcolor,width:b.gridwidth}));for(f=u-1;f<h+1;f++)for(p=b.tick0+b.dtick*f,a=0;a<b.minorgridcount;a++)(d=p+b.dtick*(a+1)/(b.minorgridcount+1))<x[0]||d>x[x.length-1]||w.push(i(I(d),{color:b.minorgridcolor,width:b.minorgridwidth}));b.startline&&k.push(i(I(x[0]),{color:b.startlinecolor,width:b.startlinewidth})),b.endline&&k.push(i(I(x[x.length-1]),{color:b.endlinecolor,width:b.endlinewidth}))}}},{"../../lib/extend":687,"../../plots/cartesian/axes":745}],884:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axes"),i=t("../../lib/extend").extendFlat;e.exports=function(t,e){var r,a,o,s=e._labels=[],l=e._gridlines;for(r=0;r<l.length;r++)o=l[r],-1!==["start","both"].indexOf(e.showticklabels)&&(a=n.tickText(e,o.value),i(a,{prefix:void 0,suffix:void 0,endAnchor:!0,xy:o.xy(0),dxy:o.dxy(0,0),axis:o.axis,length:o.crossAxis.length,font:o.axis.tickfont,isFirst:0===r,isLast:r===l.length-1}),s.push(a)),-1!==["end","both"].indexOf(e.showticklabels)&&(a=n.tickText(e,o.value),i(a,{endAnchor:!1,xy:o.xy(o.crossLength-1),dxy:o.dxy(o.crossLength-2,1),axis:o.axis,length:o.crossAxis.length,font:o.axis.tickfont,isFirst:0===r,isLast:r===l.length-1}),s.push(a))}},{"../../lib/extend":687,"../../plots/cartesian/axes":745}],885:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){var i=t[0]-e[0],a=t[1]-e[1],o=r[0]-e[0],s=r[1]-e[1],l=Math.pow(i*i+a*a,.25),c=Math.pow(o*o+s*s,.25),u=(c*c*i-l*l*o)*n,h=(c*c*a-l*l*s)*n,f=c*(l+c)*3,p=l*(l+c)*3;return[[e[0]+(f&&u/f),e[1]+(f&&h/f)],[e[0]-(p&&u/p),e[1]-(p&&h/p)]]}},{}],886:[function(t,e,r){"use strict";var n=t("../../lib").isArrayOrTypedArray;e.exports=function(t,e,r){var i,a,o,s,l,c,u=[],h=n(t)?t.length:t,f=n(e)?e.length:e,p=n(t)?t:null,d=n(e)?e:null;p&&(o=(p.length-1)/(p[p.length-1]-p[0])/(h-1)),d&&(s=(d.length-1)/(d[d.length-1]-d[0])/(f-1));var g=1/0,v=-1/0;for(a=0;a<f;a++)for(u[a]=[],l=d?(d[a]-d[0])*s:a/(f-1),i=0;i<h;i++)c=(p?(p[i]-p[0])*o:i/(h-1))-l*r,g=Math.min(c,g),v=Math.max(c,v),u[a][i]=c;var m=1/(v-g),y=-g*m;for(a=0;a<f;a++)for(i=0;i<h;i++)u[a][i]=m*u[a][i]+y;return u}},{"../../lib":697}],887:[function(t,e,r){"use strict";var n=t("./catmull_rom"),i=t("../../lib").ensureArray;function a(t,e,r){var n=-.5*r[0]+1.5*e[0],i=-.5*r[1]+1.5*e[1];return[(2*n+t[0])/3,(2*i+t[1])/3]}e.exports=function(t,e,r,o,s,l){var c,u,h,f,p,d,g,v,m,y,x=r[0].length,b=r.length,_=s?3*x-2:x,w=l?3*b-2:b;for(t=i(t,w),e=i(e,w),h=0;h<w;h++)t[h]=i(t[h],_),e[h]=i(e[h],_);for(u=0,f=0;u<b;u++,f+=l?3:1)for(p=t[f],d=e[f],g=r[u],v=o[u],c=0,h=0;c<x;c++,h+=s?3:1)p[h]=g[c],d[h]=v[c];if(s)for(u=0,f=0;u<b;u++,f+=l?3:1){for(c=1,h=3;c<x-1;c++,h+=3)m=n([r[u][c-1],o[u][c-1]],[r[u][c],o[u][c]],[r[u][c+1],o[u][c+1]],s),t[f][h-1]=m[0][0],e[f][h-1]=m[0][1],t[f][h+1]=m[1][0],e[f][h+1]=m[1][1];y=a([t[f][0],e[f][0]],[t[f][2],e[f][2]],[t[f][3],e[f][3]]),t[f][1]=y[0],e[f][1]=y[1],y=a([t[f][_-1],e[f][_-1]],[t[f][_-3],e[f][_-3]],[t[f][_-4],e[f][_-4]]),t[f][_-2]=y[0],e[f][_-2]=y[1]}if(l)for(h=0;h<_;h++){for(f=3;f<w-3;f+=3)m=n([t[f-3][h],e[f-3][h]],[t[f][h],e[f][h]],[t[f+3][h],e[f+3][h]],l),t[f-1][h]=m[0][0],e[f-1][h]=m[0][1],t[f+1][h]=m[1][0],e[f+1][h]=m[1][1];y=a([t[0][h],e[0][h]],[t[2][h],e[2][h]],[t[3][h],e[3][h]]),t[1][h]=y[0],e[1][h]=y[1],y=a([t[w-1][h],e[w-1][h]],[t[w-3][h],e[w-3][h]],[t[w-4][h],e[w-4][h]]),t[w-2][h]=y[0],e[w-2][h]=y[1]}if(s&&l)for(f=1;f<w;f+=(f+1)%3==0?2:1){for(h=3;h<_-3;h+=3)m=n([t[f][h-3],e[f][h-3]],[t[f][h],e[f][h]],[t[f][h+3],e[f][h+3]],s),t[f][h-1]=.5*(t[f][h-1]+m[0][0]),e[f][h-1]=.5*(e[f][h-1]+m[0][1]),t[f][h+1]=.5*(t[f][h+1]+m[1][0]),e[f][h+1]=.5*(e[f][h+1]+m[1][1]);y=a([t[f][0],e[f][0]],[t[f][2],e[f][2]],[t[f][3],e[f][3]]),t[f][1]=.5*(t[f][1]+y[0]),e[f][1]=.5*(e[f][1]+y[1]),y=a([t[f][_-1],e[f][_-1]],[t[f][_-3],e[f][_-3]],[t[f][_-4],e[f][_-4]]),t[f][_-2]=.5*(t[f][_-2]+y[0]),e[f][_-2]=.5*(e[f][_-2]+y[1])}return[t,e]}},{"../../lib":697,"./catmull_rom":885}],888:[function(t,e,r){"use strict";e.exports={RELATIVE_CULL_TOLERANCE:1e-6}},{}],889:[function(t,e,r){"use strict";e.exports=function(t,e,r){return e&&r?function(e,r,n,i,a){var o,s,l,c,u,h;e||(e=[]),r*=3,n*=3;var f=i*i,p=1-i,d=p*p,g=p*i*2,v=-3*d,m=3*(d-g),y=3*(g-f),x=3*f,b=a*a,_=b*a,w=1-a,k=w*w,A=k*w;for(h=0;h<t.length;h++)o=v*(u=t[h])[n][r]+m*u[n][r+1]+y*u[n][r+2]+x*u[n][r+3],s=v*u[n+1][r]+m*u[n+1][r+1]+y*u[n+1][r+2]+x*u[n+1][r+3],l=v*u[n+2][r]+m*u[n+2][r+1]+y*u[n+2][r+2]+x*u[n+2][r+3],c=v*u[n+3][r]+m*u[n+3][r+1]+y*u[n+3][r+2]+x*u[n+3][r+3],e[h]=A*o+3*(k*a*s+w*b*l)+_*c;return e}:e?function(e,r,n,i,a){var o,s,l,c;e||(e=[]),r*=3;var u=i*i,h=1-i,f=h*h,p=h*i*2,d=-3*f,g=3*(f-p),v=3*(p-u),m=3*u,y=1-a;for(l=0;l<t.length;l++)o=d*(c=t[l])[n][r]+g*c[n][r+1]+v*c[n][r+2]+m*c[n][r+3],s=d*c[n+1][r]+g*c[n+1][r+1]+v*c[n+1][r+2]+m*c[n+1][r+3],e[l]=y*o+a*s;return e}:r?function(e,r,n,i,a){var o,s,l,c,u,h;e||(e=[]),n*=3;var f=a*a,p=f*a,d=1-a,g=d*d,v=g*d;for(u=0;u<t.length;u++)o=(h=t[u])[n][r+1]-h[n][r],s=h[n+1][r+1]-h[n+1][r],l=h[n+2][r+1]-h[n+2][r],c=h[n+3][r+1]-h[n+3][r],e[u]=v*o+3*(g*a*s+d*f*l)+p*c;return e}:function(e,r,n,i,a){var o,s,l,c;e||(e=[]);var u=1-a;for(l=0;l<t.length;l++)o=(c=t[l])[n][r+1]-c[n][r],s=c[n+1][r+1]-c[n+1][r],e[l]=u*o+a*s;return e}}},{}],890:[function(t,e,r){"use strict";e.exports=function(t,e,r){return e&&r?function(e,r,n,i,a){var o,s,l,c,u,h;e||(e=[]),r*=3,n*=3;var f=i*i,p=f*i,d=1-i,g=d*d,v=g*d,m=a*a,y=1-a,x=y*y,b=y*a*2,_=-3*x,w=3*(x-b),k=3*(b-m),A=3*m;for(h=0;h<t.length;h++)o=_*(u=t[h])[n][r]+w*u[n+1][r]+k*u[n+2][r]+A*u[n+3][r],s=_*u[n][r+1]+w*u[n+1][r+1]+k*u[n+2][r+1]+A*u[n+3][r+1],l=_*u[n][r+2]+w*u[n+1][r+2]+k*u[n+2][r+2]+A*u[n+3][r+2],c=_*u[n][r+3]+w*u[n+1][r+3]+k*u[n+2][r+3]+A*u[n+3][r+3],e[h]=v*o+3*(g*i*s+d*f*l)+p*c;return e}:e?function(e,r,n,i,a){var o,s,l,c,u,h;e||(e=[]),r*=3;var f=a*a,p=f*a,d=1-a,g=d*d,v=g*d;for(u=0;u<t.length;u++)o=(h=t[u])[n+1][r]-h[n][r],s=h[n+1][r+1]-h[n][r+1],l=h[n+1][r+2]-h[n][r+2],c=h[n+1][r+3]-h[n][r+3],e[u]=v*o+3*(g*a*s+d*f*l)+p*c;return e}:r?function(e,r,n,i,a){var o,s,l,c;e||(e=[]),n*=3;var u=1-i,h=a*a,f=1-a,p=f*f,d=f*a*2,g=-3*p,v=3*(p-d),m=3*(d-h),y=3*h;for(l=0;l<t.length;l++)o=g*(c=t[l])[n][r]+v*c[n+1][r]+m*c[n+2][r]+y*c[n+3][r],s=g*c[n][r+1]+v*c[n+1][r+1]+m*c[n+2][r+1]+y*c[n+3][r+1],e[l]=u*o+i*s;return e}:function(e,r,n,i,a){var o,s,l,c;e||(e=[]);var u=1-i;for(l=0;l<t.length;l++)o=(c=t[l])[n+1][r]-c[n][r],s=c[n+1][r+1]-c[n][r+1],e[l]=u*o+i*s;return e}}},{}],891:[function(t,e,r){"use strict";e.exports=function(t,e,r,n,i){var a=e-2,o=r-2;return n&&i?function(e,r,n){var i,s,l,c,u,h;e||(e=[]);var f=Math.max(0,Math.min(Math.floor(r),a)),p=Math.max(0,Math.min(Math.floor(n),o)),d=Math.max(0,Math.min(1,r-f)),g=Math.max(0,Math.min(1,n-p));f*=3,p*=3;var v=d*d,m=v*d,y=1-d,x=y*y,b=x*y,_=g*g,w=_*g,k=1-g,A=k*k,M=A*k;for(h=0;h<t.length;h++)i=b*(u=t[h])[p][f]+3*(x*d*u[p][f+1]+y*v*u[p][f+2])+m*u[p][f+3],s=b*u[p+1][f]+3*(x*d*u[p+1][f+1]+y*v*u[p+1][f+2])+m*u[p+1][f+3],l=b*u[p+2][f]+3*(x*d*u[p+2][f+1]+y*v*u[p+2][f+2])+m*u[p+2][f+3],c=b*u[p+3][f]+3*(x*d*u[p+3][f+1]+y*v*u[p+3][f+2])+m*u[p+3][f+3],e[h]=M*i+3*(A*g*s+k*_*l)+w*c;return e}:n?function(e,r,n){e||(e=[]);var i,s,l,c,u,h,f=Math.max(0,Math.min(Math.floor(r),a)),p=Math.max(0,Math.min(Math.floor(n),o)),d=Math.max(0,Math.min(1,r-f)),g=Math.max(0,Math.min(1,n-p));f*=3;var v=d*d,m=v*d,y=1-d,x=y*y,b=x*y,_=1-g;for(u=0;u<t.length;u++)i=_*(h=t[u])[p][f]+g*h[p+1][f],s=_*h[p][f+1]+g*h[p+1][f+1],l=_*h[p][f+2]+g*h[p+1][f+1],c=_*h[p][f+3]+g*h[p+1][f+1],e[u]=b*i+3*(x*d*s+y*v*l)+m*c;return e}:i?function(e,r,n){e||(e=[]);var i,s,l,c,u,h,f=Math.max(0,Math.min(Math.floor(r),a)),p=Math.max(0,Math.min(Math.floor(n),o)),d=Math.max(0,Math.min(1,r-f)),g=Math.max(0,Math.min(1,n-p));p*=3;var v=g*g,m=v*g,y=1-g,x=y*y,b=x*y,_=1-d;for(u=0;u<t.length;u++)i=_*(h=t[u])[p][f]+d*h[p][f+1],s=_*h[p+1][f]+d*h[p+1][f+1],l=_*h[p+2][f]+d*h[p+2][f+1],c=_*h[p+3][f]+d*h[p+3][f+1],e[u]=b*i+3*(x*g*s+y*v*l)+m*c;return e}:function(e,r,n){e||(e=[]);var i,s,l,c,u=Math.max(0,Math.min(Math.floor(r),a)),h=Math.max(0,Math.min(Math.floor(n),o)),f=Math.max(0,Math.min(1,r-u)),p=Math.max(0,Math.min(1,n-h)),d=1-p,g=1-f;for(l=0;l<t.length;l++)i=g*(c=t[l])[h][u]+f*c[h][u+1],s=g*c[h+1][u]+f*c[h+1][u+1],e[l]=d*i+p*s;return e}}},{}],892:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./xy_defaults"),a=t("./ab_defaults"),o=t("./attributes"),s=t("../../components/color/attributes");e.exports=function(t,e,r,l){function c(r,i){return n.coerce(t,e,o,r,i)}e._clipPathId="clip"+e.uid+"carpet";var u=c("color",s.defaultLine);(n.coerceFont(c,"font"),c("carpet"),a(t,e,l,c,u),e.a&&e.b)?(e.a.length<3&&(e.aaxis.smoothing=0),e.b.length<3&&(e.baxis.smoothing=0),i(t,e,c)||(e.visible=!1),e._cheater&&c("cheaterslope")):e.visible=!1}},{"../../components/color/attributes":573,"../../lib":697,"./ab_defaults":875,"./attributes":877,"./xy_defaults":901}],893:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.plot=t("./plot"),n.calc=t("./calc"),n.animatable=!0,n.isContainer=!0,n.moduleType="trace",n.name="carpet",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","svg","carpet","carpetAxis","notLegendIsolatable","noMultiCategory"],n.meta={},e.exports=n},{"../../plots/cartesian":756,"./attributes":877,"./calc":881,"./defaults":892,"./plot":898}],894:[function(t,e,r){"use strict";e.exports=function(t,e){for(var r,n=t._fullData.length,i=0;i<n;i++){var a=t._fullData[i];if(a.index!==e.index&&("carpet"===a.type&&(r||(r=a),a.carpet===e.carpet)))return a}return r}},{}],895:[function(t,e,r){"use strict";e.exports=function(t,e,r){if(0===t.length)return"";var n,i=[],a=r?3:1;for(n=0;n<t.length;n+=a)i.push(t[n]+","+e[n]),r&&n<t.length-a&&(i.push("C"),i.push([t[n+1]+","+e[n+1],t[n+2]+","+e[n+2]+" "].join(" ")));return i.join(r?"":"L")}},{}],896:[function(t,e,r){"use strict";var n=t("../../lib").isArrayOrTypedArray;e.exports=function(t,e,r){var i;for(n(t)?t.length>e.length&&(t=t.slice(0,e.length)):t=[],i=0;i<e.length;i++)t[i]=r(e[i]);return t}},{"../../lib":697}],897:[function(t,e,r){"use strict";e.exports=function(t,e,r,n,i,a){var o=i[0]*t.dpdx(e),s=i[1]*t.dpdy(r),l=1,c=1;if(a){var u=Math.sqrt(i[0]*i[0]+i[1]*i[1]),h=Math.sqrt(a[0]*a[0]+a[1]*a[1]),f=(i[0]*a[0]+i[1]*a[1])/u/h;c=Math.max(0,f)}var p=180*Math.atan2(s,o)/Math.PI;return p<-90?(p+=180,l=-l):p>90&&(p-=180,l=-l),{angle:p,flip:l,p:t.c2p(n,e,r),offsetMultplier:c}}},{}],898:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../components/drawing"),a=t("./map_1d_array"),o=t("./makepath"),s=t("./orient_text"),l=t("../../lib/svg_text_utils"),c=t("../../lib"),u=t("../../constants/alignment");function h(t,e,r,i,s,l){var c="const-"+s+"-lines",u=r.selectAll("."+c).data(l);u.enter().append("path").classed(c,!0).style("vector-effect","non-scaling-stroke"),u.each(function(r){var i=r,s=i.x,l=i.y,c=a([],s,t.c2p),u=a([],l,e.c2p),h="M"+o(c,u,i.smoothing);n.select(this).attr("d",h).style("stroke-width",i.width).style("stroke",i.color).style("fill","none")}),u.exit().remove()}function f(t,e,r,a,o,c,u,h){var f=c.selectAll("text."+h).data(u);f.enter().append("text").classed(h,!0);var p=0,d={};return f.each(function(o,c){var u;if("auto"===o.axis.tickangle)u=s(a,e,r,o.xy,o.dxy);else{var h=(o.axis.tickangle+180)*Math.PI/180;u=s(a,e,r,o.xy,[Math.cos(h),Math.sin(h)])}c||(d={angle:u.angle,flip:u.flip});var f=(o.endAnchor?-1:1)*u.flip,g=n.select(this).attr({"text-anchor":f>0?"start":"end","data-notex":1}).call(i.font,o.font).text(o.text).call(l.convertToTspans,t),v=i.bBox(this);g.attr("transform","translate("+u.p[0]+","+u.p[1]+") rotate("+u.angle+")translate("+o.axis.labelpadding*f+","+.3*v.height+")"),p=Math.max(p,v.width+o.axis.labelpadding)}),f.exit().remove(),d.maxExtent=p,d}e.exports=function(t,e,r,i){var l=e.xaxis,u=e.yaxis,p=t._fullLayout._clips;c.makeTraceGroups(i,r,"trace").each(function(e){var r=n.select(this),i=e[0],d=i.trace,v=d.aaxis,m=d.baxis,y=c.ensureSingle(r,"g","minorlayer"),x=c.ensureSingle(r,"g","majorlayer"),b=c.ensureSingle(r,"g","boundarylayer"),_=c.ensureSingle(r,"g","labellayer");r.style("opacity",d.opacity),h(l,u,x,v,"a",v._gridlines),h(l,u,x,m,"b",m._gridlines),h(l,u,y,v,"a",v._minorgridlines),h(l,u,y,m,"b",m._minorgridlines),h(l,u,b,v,"a-boundary",v._boundarylines),h(l,u,b,m,"b-boundary",m._boundarylines);var w=f(t,l,u,d,i,_,v._labels,"a-label"),k=f(t,l,u,d,i,_,m._labels,"b-label");!function(t,e,r,n,i,a,o,l){var u,h,f,p;u=.5*(r.a[0]+r.a[r.a.length-1]),h=r.b[0],f=r.ab2xy(u,h,!0),p=r.dxyda_rough(u,h),void 0===o.angle&&c.extendFlat(o,s(r,i,a,f,r.dxydb_rough(u,h)));g(t,e,r,n,f,p,r.aaxis,i,a,o,"a-title"),u=r.a[0],h=.5*(r.b[0]+r.b[r.b.length-1]),f=r.ab2xy(u,h,!0),p=r.dxydb_rough(u,h),void 0===l.angle&&c.extendFlat(l,s(r,i,a,f,r.dxyda_rough(u,h)));g(t,e,r,n,f,p,r.baxis,i,a,l,"b-title")}(t,_,d,i,l,u,w,k),function(t,e,r,n,i){var s,l,u,h,f=r.select("#"+t._clipPathId);f.size()||(f=r.append("clipPath").classed("carpetclip",!0));var p=c.ensureSingle(f,"path","carpetboundary"),d=e.clipsegments,g=[];for(h=0;h<d.length;h++)s=d[h],l=a([],s.x,n.c2p),u=a([],s.y,i.c2p),g.push(o(l,u,s.bicubic));var v="M"+g.join("L")+"Z";f.attr("id",t._clipPathId),p.attr("d",v)}(d,i,p,l,u)})};var p=u.LINE_SPACING,d=(1-u.MID_SHIFT)/p+1;function g(t,e,r,a,o,c,u,h,f,g,v){var m=[];u.title.text&&m.push(u.title.text);var y=e.selectAll("text."+v).data(m),x=g.maxExtent;y.enter().append("text").classed(v,!0),y.each(function(){var e=s(r,h,f,o,c);-1===["start","both"].indexOf(u.showticklabels)&&(x=0);var a=u.title.font.size;x+=a+u.title.offset;var v=(g.angle+(g.flip<0?180:0)-e.angle+450)%360,m=v>90&&v<270,y=n.select(this);y.text(u.title.text).call(l.convertToTspans,t),m&&(x=(-l.lineCount(y)+d)*p*a-x),y.attr("transform","translate("+e.p[0]+","+e.p[1]+") rotate("+e.angle+") translate(0,"+x+")").classed("user-select-none",!0).attr("text-anchor","middle").call(i.font,u.title.font)}),y.exit().remove()}},{"../../components/drawing":595,"../../constants/alignment":669,"../../lib":697,"../../lib/svg_text_utils":721,"./makepath":895,"./map_1d_array":896,"./orient_text":897,d3:151}],899:[function(t,e,r){"use strict";var n=t("./constants"),i=t("../../lib/search").findBin,a=t("./compute_control_points"),o=t("./create_spline_evaluator"),s=t("./create_i_derivative_evaluator"),l=t("./create_j_derivative_evaluator");e.exports=function(t){var e=t._a,r=t._b,c=e.length,u=r.length,h=t.aaxis,f=t.baxis,p=e[0],d=e[c-1],g=r[0],v=r[u-1],m=e[e.length-1]-e[0],y=r[r.length-1]-r[0],x=m*n.RELATIVE_CULL_TOLERANCE,b=y*n.RELATIVE_CULL_TOLERANCE;p-=x,d+=x,g-=b,v+=b,t.isVisible=function(t,e){return t>p&&t<d&&e>g&&e<v},t.isOccluded=function(t,e){return t<p||t>d||e<g||e>v},t.setScale=function(){var e=t._x,r=t._y,n=a(t._xctrl,t._yctrl,e,r,h.smoothing,f.smoothing);t._xctrl=n[0],t._yctrl=n[1],t.evalxy=o([t._xctrl,t._yctrl],c,u,h.smoothing,f.smoothing),t.dxydi=s([t._xctrl,t._yctrl],h.smoothing,f.smoothing),t.dxydj=l([t._xctrl,t._yctrl],h.smoothing,f.smoothing)},t.i2a=function(t){var r=Math.max(0,Math.floor(t[0]),c-2),n=t[0]-r;return(1-n)*e[r]+n*e[r+1]},t.j2b=function(t){var e=Math.max(0,Math.floor(t[1]),c-2),n=t[1]-e;return(1-n)*r[e]+n*r[e+1]},t.ij2ab=function(e){return[t.i2a(e[0]),t.j2b(e[1])]},t.a2i=function(t){var r=Math.max(0,Math.min(i(t,e),c-2)),n=e[r],a=e[r+1];return Math.max(0,Math.min(c-1,r+(t-n)/(a-n)))},t.b2j=function(t){var e=Math.max(0,Math.min(i(t,r),u-2)),n=r[e],a=r[e+1];return Math.max(0,Math.min(u-1,e+(t-n)/(a-n)))},t.ab2ij=function(e){return[t.a2i(e[0]),t.b2j(e[1])]},t.i2c=function(e,r){return t.evalxy([],e,r)},t.ab2xy=function(n,i,a){if(!a&&(n<e[0]||n>e[c-1]|i<r[0]||i>r[u-1]))return[!1,!1];var o=t.a2i(n),s=t.b2j(i),l=t.evalxy([],o,s);if(a){var h,f,p,d,g=0,v=0,m=[];n<e[0]?(h=0,f=0,g=(n-e[0])/(e[1]-e[0])):n>e[c-1]?(h=c-2,f=1,g=(n-e[c-1])/(e[c-1]-e[c-2])):f=o-(h=Math.max(0,Math.min(c-2,Math.floor(o)))),i<r[0]?(p=0,d=0,v=(i-r[0])/(r[1]-r[0])):i>r[u-1]?(p=u-2,d=1,v=(i-r[u-1])/(r[u-1]-r[u-2])):d=s-(p=Math.max(0,Math.min(u-2,Math.floor(s)))),g&&(t.dxydi(m,h,p,f,d),l[0]+=m[0]*g,l[1]+=m[1]*g),v&&(t.dxydj(m,h,p,f,d),l[0]+=m[0]*v,l[1]+=m[1]*v)}return l},t.c2p=function(t,e,r){return[e.c2p(t[0]),r.c2p(t[1])]},t.p2x=function(t,e,r){return[e.p2c(t[0]),r.p2c(t[1])]},t.dadi=function(t){var r=Math.max(0,Math.min(e.length-2,t));return e[r+1]-e[r]},t.dbdj=function(t){var e=Math.max(0,Math.min(r.length-2,t));return r[e+1]-r[e]},t.dxyda=function(e,r,n,i){var a=t.dxydi(null,e,r,n,i),o=t.dadi(e,n);return[a[0]/o,a[1]/o]},t.dxydb=function(e,r,n,i){var a=t.dxydj(null,e,r,n,i),o=t.dbdj(r,i);return[a[0]/o,a[1]/o]},t.dxyda_rough=function(e,r,n){var i=m*(n||.1),a=t.ab2xy(e+i,r,!0),o=t.ab2xy(e-i,r,!0);return[.5*(a[0]-o[0])/i,.5*(a[1]-o[1])/i]},t.dxydb_rough=function(e,r,n){var i=y*(n||.1),a=t.ab2xy(e,r+i,!0),o=t.ab2xy(e,r-i,!0);return[.5*(a[0]-o[0])/i,.5*(a[1]-o[1])/i]},t.dpdx=function(t){return t._m},t.dpdy=function(t){return t._m}}},{"../../lib/search":716,"./compute_control_points":887,"./constants":888,"./create_i_derivative_evaluator":889,"./create_j_derivative_evaluator":890,"./create_spline_evaluator":891}],900:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e,r){var i,a,o,s=[],l=[],c=t[0].length,u=t.length;function h(e,r){var n,i=0,a=0;return e>0&&void 0!==(n=t[r][e-1])&&(a++,i+=n),e<c-1&&void 0!==(n=t[r][e+1])&&(a++,i+=n),r>0&&void 0!==(n=t[r-1][e])&&(a++,i+=n),r<u-1&&void 0!==(n=t[r+1][e])&&(a++,i+=n),i/Math.max(1,a)}var f,p,d,g,v,m,y,x,b,_,w,k=0;for(i=0;i<c;i++)for(a=0;a<u;a++)void 0===t[a][i]&&(s.push(i),l.push(a),t[a][i]=h(i,a)),k=Math.max(k,Math.abs(t[a][i]));if(!s.length)return t;var A=0,M=0,T=s.length;do{for(A=0,o=0;o<T;o++){i=s[o],a=l[o];var S,E,C,L,z,O,I=0,D=0;0===i?(C=e[z=Math.min(c-1,2)],L=e[1],S=t[a][z],D+=(E=t[a][1])+(E-S)*(e[0]-L)/(L-C),I++):i===c-1&&(C=e[z=Math.max(0,c-3)],L=e[c-2],S=t[a][z],D+=(E=t[a][c-2])+(E-S)*(e[c-1]-L)/(L-C),I++),(0===i||i===c-1)&&a>0&&a<u-1&&(f=r[a+1]-r[a],D+=((p=r[a]-r[a-1])*t[a+1][i]+f*t[a-1][i])/(p+f),I++),0===a?(C=r[O=Math.min(u-1,2)],L=r[1],S=t[O][i],D+=(E=t[1][i])+(E-S)*(r[0]-L)/(L-C),I++):a===u-1&&(C=r[O=Math.max(0,u-3)],L=r[u-2],S=t[O][i],D+=(E=t[u-2][i])+(E-S)*(r[u-1]-L)/(L-C),I++),(0===a||a===u-1)&&i>0&&i<c-1&&(f=e[i+1]-e[i],D+=((p=e[i]-e[i-1])*t[a][i+1]+f*t[a][i-1])/(p+f),I++),I?D/=I:(d=e[i+1]-e[i],g=e[i]-e[i-1],x=(v=r[a+1]-r[a])*(m=r[a]-r[a-1])*(v+m),D=((y=d*g*(d+g))*(m*t[a+1][i]+v*t[a-1][i])+x*(g*t[a][i+1]+d*t[a][i-1]))/(x*(g+d)+y*(m+v))),A+=(_=(b=D-t[a][i])/k)*_,w=I?0:.85,t[a][i]+=b*(1+w)}A=Math.sqrt(A)}while(M++<100&&A>1e-5);return n.log("Smoother converged to",A,"after",M,"iterations"),t}},{"../../lib":697}],901:[function(t,e,r){"use strict";var n=t("../../lib").isArray1D;e.exports=function(t,e,r){var i=r("x"),a=i&&i.length,o=r("y"),s=o&&o.length;if(!a&&!s)return!1;if(e._cheater=!i,a&&!n(i)||s&&!n(o))e._length=null;else{var l=a?i.length:1/0;s&&(l=Math.min(l,o.length)),e.a&&e.a.length&&(l=Math.min(l,e.a.length)),e.b&&e.b.length&&(l=Math.min(l,e.b.length)),e._length=l}return!0}},{"../../lib":697}],902:[function(t,e,r){"use strict";var n=t("../../components/fx/hovertemplate_attributes"),i=t("../scattergeo/attributes"),a=t("../../components/colorscale/attributes"),o=t("../../components/colorbar/attributes"),s=t("../../plots/attributes"),l=t("../../lib/extend").extendFlat,c=i.marker.line;e.exports=l({locations:{valType:"data_array",editType:"calc"},locationmode:i.locationmode,z:{valType:"data_array",editType:"calc"},text:l({},i.text,{}),hovertext:l({},i.hovertext,{}),marker:{line:{color:c.color,width:l({},c.width,{dflt:1}),editType:"calc"},opacity:{valType:"number",arrayOk:!0,min:0,max:1,dflt:1,editType:"style"},editType:"calc"},selected:{marker:{opacity:i.selected.marker.opacity,editType:"plot"},editType:"plot"},unselected:{marker:{opacity:i.unselected.marker.opacity,editType:"plot"},editType:"plot"},hoverinfo:l({},s.hoverinfo,{editType:"calc",flags:["location","z","text","name"]}),hovertemplate:n()},a("",{cLetter:"z",editTypeOverride:"calc"}),{colorbar:o})},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plots/attributes":742,"../scattergeo/attributes":1088}],903:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../constants/numerical").BADNUM,a=t("../../components/colorscale/calc"),o=t("../scatter/arrays_to_calcdata"),s=t("../scatter/calc_selection");e.exports=function(t,e){for(var r=e._length,l=new Array(r),c=0;c<r;c++){var u=l[c]={},h=e.locations[c],f=e.z[c];u.loc="string"==typeof h?h:null,u.z=n(f)?f:i}return o(l,e),a(t,e,{vals:e.z,containerStr:"",cLetter:"z"}),s(l,e),l}},{"../../components/colorscale/calc":582,"../../constants/numerical":674,"../scatter/arrays_to_calcdata":1047,"../scatter/calc_selection":1050,"fast-isnumeric":218}],904:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/colorscale/defaults"),a=t("./attributes");e.exports=function(t,e,r,o){function s(r,i){return n.coerce(t,e,a,r,i)}var l=s("locations"),c=s("z");l&&l.length&&n.isArrayOrTypedArray(c)&&c.length?(e._length=Math.min(l.length,c.length),s("locationmode"),s("text"),s("hovertext"),s("hovertemplate"),s("marker.line.color"),s("marker.line.width"),s("marker.opacity"),i(t,e,o,s,{prefix:"",cLetter:"z"}),n.coerceSelectionMarkerOpacity(e,s)):e.visible=!1}},{"../../components/colorscale/defaults":584,"../../lib":697,"./attributes":902}],905:[function(t,e,r){"use strict";e.exports=function(t,e){return t.location=e.location,t.z=e.z,t}},{}],906:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axes"),i=t("./attributes"),a=t("../scatter/fill_hover_text");e.exports=function(t,e,r){var o,s,l,c,u=t.cd,h=u[0].trace,f=t.subplot;for(s=0;s<u.length;s++)if(c=!1,(o=u[s])._polygons){for(l=0;l<o._polygons.length;l++)o._polygons[l].contains([e,r])&&(c=!c),o._polygons[l].contains([e+360,r])&&(c=!c);if(c)break}if(c&&o)return t.x0=t.x1=t.xa.c2p(o.ct),t.y0=t.y1=t.ya.c2p(o.ct),t.index=o.index,t.location=o.loc,t.z=o.z,t.hovertemplate=o.hovertemplate,function(t,e,r,o){if(e.hovertemplate)return;var s=r.hi||e.hoverinfo,l="all"===s?i.hoverinfo.flags:s.split("+"),c=-1!==l.indexOf("name"),u=-1!==l.indexOf("location"),h=-1!==l.indexOf("z"),f=-1!==l.indexOf("text"),p=[];!c&&u?t.nameOverride=r.loc:(c&&(t.nameOverride=e.name),u&&p.push(r.loc));h&&p.push((d=r.z,n.tickText(o,o.c2l(d),"hover").text));var d;f&&a(r,e,p);t.extraText=p.join("<br>")}(t,h,o,f.mockAxis),[t]}},{"../../plots/cartesian/axes":745,"../scatter/fill_hover_text":1056,"./attributes":902}],907:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../heatmap/colorbar"),n.calc=t("./calc"),n.plot=t("./plot"),n.style=t("./style").style,n.styleOnSelect=t("./style").styleOnSelect,n.hoverPoints=t("./hover"),n.eventData=t("./event_data"),n.selectPoints=t("./select"),n.moduleType="trace",n.name="choropleth",n.basePlotModule=t("../../plots/geo"),n.categories=["geo","noOpacity"],n.meta={},e.exports=n},{"../../plots/geo":775,"../heatmap/colorbar":948,"./attributes":902,"./calc":903,"./defaults":904,"./event_data":905,"./hover":906,"./plot":908,"./select":909,"./style":910}],908:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../lib"),a=t("../../lib/polygon"),o=t("../../lib/topojson_utils").getTopojsonFeatures,s=t("../../lib/geo_location_utils").locationToFeature,l=t("./style").style;function c(t,e){for(var r=t[0].trace,n=t.length,i=o(r,e),a=0;a<n;a++){var l=t[a],c=s(r.locationmode,l.loc,i);c?(l.geojson=c,l.ct=c.properties.ct,l.index=a,l._polygons=u(c)):l.geojson=null}}function u(t){var e,r,n,i,o=t.geometry,s=o.coordinates,l=t.id,c=[];function u(t){for(var e=0;e<t.length-1;e++)if(t[e][0]>0&&t[e+1][0]<0)return e;return null}switch(e="RUS"===l||"FJI"===l?function(t){var e;if(null===u(t))e=t;else for(e=new Array(t.length),i=0;i<t.length;i++)e[i]=[t[i][0]<0?t[i][0]+360:t[i][0],t[i][1]];c.push(a.tester(e))}:"ATA"===l?function(t){var e=u(t);if(null===e)return c.push(a.tester(t));var r=new Array(t.length+1),n=0;for(i=0;i<t.length;i++)i>e?r[n++]=[t[i][0]+360,t[i][1]]:i===e?(r[n++]=t[i],r[n++]=[t[i][0],-90]):r[n++]=t[i];var o=a.tester(r);o.pts.pop(),c.push(o)}:function(t){c.push(a.tester(t))},o.type){case"MultiPolygon":for(r=0;r<s.length;r++)for(n=0;n<s[r].length;n++)e(s[r][n]);break;case"Polygon":for(r=0;r<s.length;r++)e(s[r])}return c}e.exports=function(t,e,r){for(var a=0;a<r.length;a++)c(r[a],e.topojson);var o=e.layers.backplot.select(".choroplethlayer");i.makeTraceGroups(o,r,"trace choropleth").each(function(e){var r=(e[0].node3=n.select(this)).selectAll("path.choroplethlocation").data(i.identity);r.enter().append("path").classed("choroplethlocation",!0),r.exit().remove(),l(t,e)})}},{"../../lib":697,"../../lib/geo_location_utils":690,"../../lib/polygon":709,"../../lib/topojson_utils":724,"./style":910,d3:151}],909:[function(t,e,r){"use strict";e.exports=function(t,e){var r,n,i,a,o,s=t.cd,l=t.xaxis,c=t.yaxis,u=[];if(!1===e)for(r=0;r<s.length;r++)s[r].selected=0;else for(r=0;r<s.length;r++)(i=(n=s[r]).ct)&&(a=l.c2p(i),o=c.c2p(i),e.contains([a,o],null,r,t)?(u.push({pointNumber:r,lon:i[0],lat:i[1]}),n.selected=1):n.selected=0);return u}},{}],910:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../components/color"),a=t("../../components/drawing"),o=t("../../components/colorscale");function s(t,e){var r=e[0].trace,s=e[0].node3.selectAll(".choroplethlocation"),l=r.marker||{},c=l.line||{},u=o.makeColorScaleFunc(o.extractScale(r,{cLetter:"z"}));s.each(function(t){n.select(this).attr("fill",u(t.z)).call(i.stroke,t.mlc||c.color).call(a.dashLine,"",t.mlw||c.width||0).style("opacity",l.opacity)}),a.selectedPointStyle(s,r,t)}e.exports={style:function(t,e){e&&s(t,e)},styleOnSelect:function(t,e){var r=e[0].node3,n=e[0].trace;n.selectedpoints?a.selectedPointStyle(r.selectAll(".choroplethlocation"),n,t):s(t,e)}}},{"../../components/color":574,"../../components/colorscale":586,"../../components/drawing":595,d3:151}],911:[function(t,e,r){"use strict";var n=t("../../components/colorscale/attributes"),i=t("../../components/colorbar/attributes"),a=t("../../components/fx/hovertemplate_attributes"),o=t("../mesh3d/attributes"),s=t("../../plots/attributes"),l=t("../../lib/extend").extendFlat,c={x:{valType:"data_array",editType:"calc+clearAxisTypes"},y:{valType:"data_array",editType:"calc+clearAxisTypes"},z:{valType:"data_array",editType:"calc+clearAxisTypes"},u:{valType:"data_array",editType:"calc"},v:{valType:"data_array",editType:"calc"},w:{valType:"data_array",editType:"calc"},sizemode:{valType:"enumerated",values:["scaled","absolute"],editType:"calc",dflt:"scaled"},sizeref:{valType:"number",editType:"calc",min:0},anchor:{valType:"enumerated",editType:"calc",values:["tip","tail","cm","center"],dflt:"cm"},text:{valType:"string",dflt:"",arrayOk:!0,editType:"calc"},hovertext:{valType:"string",dflt:"",arrayOk:!0,editType:"calc"},hovertemplate:a({editType:"calc"},{keys:["norm"]})};l(c,n("",{colorAttr:"u/v/w norm",showScaleDflt:!0,editTypeOverride:"calc"}),{colorbar:i});["opacity","lightposition","lighting"].forEach(function(t){c[t]=o[t]}),c.hoverinfo=l({},s.hoverinfo,{editType:"calc",flags:["x","y","z","u","v","w","norm","text","name"],dflt:"x+y+z+norm+text+name"}),c.transforms=void 0,e.exports=c},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plots/attributes":742,"../mesh3d/attributes":991}],912:[function(t,e,r){"use strict";var n=t("../../components/colorscale/calc");e.exports=function(t,e){for(var r=e.u,i=e.v,a=e.w,o=Math.min(e.x.length,e.y.length,e.z.length,r.length,i.length,a.length),s=-1/0,l=1/0,c=0;c<o;c++){var u=r[c],h=i[c],f=a[c],p=Math.sqrt(u*u+h*h+f*f);s=Math.max(s,p),l=Math.min(l,p)}e._len=o,e._normMax=s,n(t,e,{vals:[l,s],containerStr:"",cLetter:"c"})}},{"../../components/colorscale/calc":582}],913:[function(t,e,r){"use strict";var n=t("gl-cone3d"),i=t("gl-cone3d").createConeMesh,a=t("../../lib").simpleMap,o=t("../../lib/gl_format_color").parseColorScale,s=t("../../plots/gl3d/zip3");function l(t,e){this.scene=t,this.uid=e,this.mesh=null,this.data=null}var c=l.prototype;c.handlePick=function(t){if(t.object===this.mesh){var e=t.index=t.data.index,r=this.data.x[e],n=this.data.y[e],i=this.data.z[e],a=this.data.u[e],o=this.data.v[e],s=this.data.w[e];t.traceCoordinate=[r,n,i,a,o,s,Math.sqrt(a*a+o*o+s*s)];var l=this.data.hovertext||this.data.text;return Array.isArray(l)&&void 0!==l[e]?t.textLabel=l[e]:l&&(t.textLabel=l),!0}};var u={xaxis:0,yaxis:1,zaxis:2},h={tip:1,tail:0,cm:.25,center:.5},f={tip:1,tail:1,cm:.75,center:.5};function p(t,e){var r=t.fullSceneLayout,i=t.dataScale,l={};function c(t,e){var n=r[e],o=i[u[e]];return a(t,function(t){return n.d2l(t)*o})}l.vectors=s(c(e.u,"xaxis"),c(e.v,"yaxis"),c(e.w,"zaxis"),e._len),l.positions=s(c(e.x,"xaxis"),c(e.y,"yaxis"),c(e.z,"zaxis"),e._len),l.colormap=o(e),l.vertexIntensityBounds=[e.cmin/e._normMax,e.cmax/e._normMax],l.coneOffset=h[e.anchor],"scaled"===e.sizemode?l.coneSize=e.sizeref||.5:l.coneSize=e.sizeref&&e._normMax?e.sizeref/e._normMax:.5;var p=n(l),d=e.lightposition;return p.lightPosition=[d.x,d.y,d.z],p.ambient=e.lighting.ambient,p.diffuse=e.lighting.diffuse,p.specular=e.lighting.specular,p.roughness=e.lighting.roughness,p.fresnel=e.lighting.fresnel,p.opacity=e.opacity,e._pad=f[e.anchor]*p.vectorScale*p.coneScale*e._normMax,p}c.update=function(t){this.data=t;var e=p(this.scene,t);this.mesh.update(e)},c.dispose=function(){this.scene.glplot.remove(this.mesh),this.mesh.dispose()},e.exports=function(t,e){var r=t.glplot.gl,n=p(t,e),a=i(r,n),o=new l(t,e.uid);return o.mesh=a,o.data=e,a._trace=o,t.glplot.add(a),o}},{"../../lib":697,"../../lib/gl_format_color":694,"../../plots/gl3d/zip3":797,"gl-cone3d":235}],914:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/colorscale/defaults"),a=t("./attributes");e.exports=function(t,e,r,o){function s(r,i){return n.coerce(t,e,a,r,i)}var l=s("u"),c=s("v"),u=s("w"),h=s("x"),f=s("y"),p=s("z");l&&l.length&&c&&c.length&&u&&u.length&&h&&h.length&&f&&f.length&&p&&p.length?(s("sizeref"),s("sizemode"),s("anchor"),s("lighting.ambient"),s("lighting.diffuse"),s("lighting.specular"),s("lighting.roughness"),s("lighting.fresnel"),s("lightposition.x"),s("lightposition.y"),s("lightposition.z"),i(t,e,o,s,{prefix:"",cLetter:"c"}),s("text"),s("hovertext"),s("hovertemplate"),e._length=null):e.visible=!1}},{"../../components/colorscale/defaults":584,"../../lib":697,"./attributes":911}],915:[function(t,e,r){"use strict";e.exports={moduleType:"trace",name:"cone",basePlotModule:t("../../plots/gl3d"),categories:["gl3d"],attributes:t("./attributes"),supplyDefaults:t("./defaults"),colorbar:{min:"cmin",max:"cmax"},calc:t("./calc"),plot:t("./convert"),eventData:function(t,e){return t.norm=e.traceCoordinate[6],t},meta:{}}},{"../../plots/gl3d":786,"./attributes":911,"./calc":912,"./convert":913,"./defaults":914}],916:[function(t,e,r){"use strict";var n=t("../heatmap/attributes"),i=t("../scatter/attributes"),a=t("../../components/colorscale/attributes"),o=t("../../components/colorbar/attributes"),s=t("../../components/drawing/attributes").dash,l=t("../../plots/font_attributes"),c=t("../../lib/extend").extendFlat,u=t("../../constants/filter_ops"),h=u.COMPARISON_OPS2,f=u.INTERVAL_OPS,p=i.line;e.exports=c({z:n.z,x:n.x,x0:n.x0,dx:n.dx,y:n.y,y0:n.y0,dy:n.dy,text:n.text,hovertext:n.hovertext,transpose:n.transpose,xtype:n.xtype,ytype:n.ytype,zhoverformat:n.zhoverformat,hovertemplate:n.hovertemplate,connectgaps:n.connectgaps,fillcolor:{valType:"color",editType:"calc"},autocontour:{valType:"boolean",dflt:!0,editType:"calc",impliedEdits:{"contours.start":void 0,"contours.end":void 0,"contours.size":void 0}},ncontours:{valType:"integer",dflt:15,min:1,editType:"calc"},contours:{type:{valType:"enumerated",values:["levels","constraint"],dflt:"levels",editType:"calc"},start:{valType:"number",dflt:null,editType:"plot",impliedEdits:{"^autocontour":!1}},end:{valType:"number",dflt:null,editType:"plot",impliedEdits:{"^autocontour":!1}},size:{valType:"number",dflt:null,min:0,editType:"plot",impliedEdits:{"^autocontour":!1}},coloring:{valType:"enumerated",values:["fill","heatmap","lines","none"],dflt:"fill",editType:"calc"},showlines:{valType:"boolean",dflt:!0,editType:"plot"},showlabels:{valType:"boolean",dflt:!1,editType:"plot"},labelfont:l({editType:"plot",colorEditType:"style"}),labelformat:{valType:"string",dflt:"",editType:"plot"},operation:{valType:"enumerated",values:[].concat(h).concat(f),dflt:"=",editType:"calc"},value:{valType:"any",dflt:0,editType:"calc"},editType:"calc",impliedEdits:{autocontour:!1}},line:{color:c({},p.color,{editType:"style+colorbars"}),width:c({},p.width,{editType:"style+colorbars"}),dash:s,smoothing:c({},p.smoothing,{}),editType:"plot"}},a("",{cLetter:"z",autoColorDflt:!1,editTypeOverride:"calc"}),{colorbar:o})},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/drawing/attributes":594,"../../constants/filter_ops":670,"../../lib/extend":687,"../../plots/font_attributes":771,"../heatmap/attributes":945,"../scatter/attributes":1048}],917:[function(t,e,r){"use strict";var n=t("../heatmap/calc"),i=t("./set_contours");e.exports=function(t,e){var r=n(t,e);return i(e),r}},{"../heatmap/calc":946,"./set_contours":935}],918:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){var i,a,o,s=t[0],l=s.x.length,c=s.y.length,u=s.z,h=n.contours,f=-1/0,p=1/0;for(i=0;i<c;i++)p=Math.min(p,u[i][0]),p=Math.min(p,u[i][l-1]),f=Math.max(f,u[i][0]),f=Math.max(f,u[i][l-1]);for(i=1;i<l-1;i++)p=Math.min(p,u[0][i]),p=Math.min(p,u[c-1][i]),f=Math.max(f,u[0][i]),f=Math.max(f,u[c-1][i]);switch(s.prefixBoundary=!1,e){case">":h.value>f&&(s.prefixBoundary=!0);break;case"<":h.value<p&&(s.prefixBoundary=!0);break;case"[]":a=Math.min.apply(null,h.value),((o=Math.max.apply(null,h.value))<p||a>f)&&(s.prefixBoundary=!0);break;case"][":a=Math.min.apply(null,h.value),o=Math.max.apply(null,h.value),a<p&&o>f&&(s.prefixBoundary=!0)}}},{}],919:[function(t,e,r){"use strict";var n=t("../../components/colorbar/draw"),i=t("./make_color_map"),a=t("./end_plus");e.exports=function(t,e){var r=e[0].trace,o="cb"+r.uid;if(t._fullLayout._infolayer.selectAll("."+o).remove(),r.showscale){var s=e[0].t.cb=n(t,o),l=r.contours,c=r.line,u=l.size||1,h=l.coloring,f=i(r,{isColorbar:!0});s.fillgradient("heatmap"===h?r.colorscale:"").zrange("heatmap"===h?[r.zmin,r.zmax]:"").fillcolor("fill"===h?f:"").line({color:"lines"===h?f:c.color,width:!1!==l.showlines?c.width:0,dash:c.dash}).levels({start:l.start,end:a(l),size:u}).options(r.colorbar)()}}},{"../../components/colorbar/draw":579,"./end_plus":927,"./make_color_map":932}],920:[function(t,e,r){"use strict";e.exports={BOTTOMSTART:[1,9,13,104,713],TOPSTART:[4,6,7,104,713],LEFTSTART:[8,12,14,208,1114],RIGHTSTART:[2,3,11,208,1114],NEWDELTA:[null,[-1,0],[0,-1],[-1,0],[1,0],null,[0,-1],[-1,0],[0,1],[0,1],null,[0,1],[1,0],[1,0],[0,-1]],CHOOSESADDLE:{104:[4,1],208:[2,8],713:[7,13],1114:[11,14]},SADDLEREMAINDER:{1:4,2:8,4:1,7:13,8:2,11:14,13:7,14:11},LABELDISTANCE:2,LABELINCREASE:10,LABELMIN:3,LABELMAX:10,LABELOPTIMIZER:{EDGECOST:1,ANGLECOST:1,NEIGHBORCOST:5,SAMELEVELFACTOR:10,SAMELEVELDISTANCE:5,MAXCOST:100,INITIALSEARCHPOINTS:10,ITERATIONS:5}}},{}],921:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("./label_defaults"),a=t("../../components/color"),o=a.addOpacity,s=a.opacity,l=t("../../constants/filter_ops"),c=l.CONSTRAINT_REDUCTION,u=l.COMPARISON_OPS2;e.exports=function(t,e,r,a,l,h){var f,p,d,g=e.contours,v=r("contours.operation");(g._operation=c[v],function(t,e){var r;-1===u.indexOf(e.operation)?(t("contours.value",[0,1]),Array.isArray(e.value)?e.value.length>2?e.value=e.value.slice(2):0===e.length?e.value=[0,1]:e.length<2?(r=parseFloat(e.value[0]),e.value=[r,r+1]):e.value=[parseFloat(e.value[0]),parseFloat(e.value[1])]:n(e.value)&&(r=parseFloat(e.value),e.value=[r,r+1])):(t("contours.value",0),n(e.value)||(Array.isArray(e.value)?e.value=parseFloat(e.value[0]):e.value=0))}(r,g),"="===v?f=g.showlines=!0:(f=r("contours.showlines"),d=r("fillcolor",o((t.line||{}).color||l,.5))),f)&&(p=r("line.color",d&&s(d)?o(e.fillcolor,1):l),r("line.width",2),r("line.dash"));r("line.smoothing"),i(r,a,p,h)}},{"../../components/color":574,"../../constants/filter_ops":670,"./label_defaults":931,"fast-isnumeric":218}],922:[function(t,e,r){"use strict";var n=t("../../constants/filter_ops"),i=t("fast-isnumeric");function a(t,e){var r,a=Array.isArray(e);function o(t){return i(t)?+t:null}return-1!==n.COMPARISON_OPS2.indexOf(t)?r=o(a?e[0]:e):-1!==n.INTERVAL_OPS.indexOf(t)?r=a?[o(e[0]),o(e[1])]:[o(e),o(e)]:-1!==n.SET_OPS.indexOf(t)&&(r=a?e.map(o):[o(e)]),r}function o(t){return function(e){e=a(t,e);var r=Math.min(e[0],e[1]),n=Math.max(e[0],e[1]);return{start:r,end:n,size:n-r}}}function s(t){return function(e){return{start:e=a(t,e),end:1/0,size:1/0}}}e.exports={"[]":o("[]"),"][":o("]["),">":s(">"),"<":s("<"),"=":s("=")}},{"../../constants/filter_ops":670,"fast-isnumeric":218}],923:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){var i=n("contours.start"),a=n("contours.end"),o=!1===i||!1===a,s=r("contours.size");!(o?e.autocontour=!0:r("autocontour",!1))&&s||r("ncontours")}},{}],924:[function(t,e,r){"use strict";var n=t("../../lib");function i(t){return n.extendFlat({},t,{edgepaths:n.extendDeep([],t.edgepaths),paths:n.extendDeep([],t.paths)})}e.exports=function(t,e){var r,a,o,s=function(t){return t.reverse()},l=function(t){return t};switch(e){case"=":case"<":return t;case">":for(1!==t.length&&n.warn("Contour data invalid for the specified inequality operation."),a=t[0],r=0;r<a.edgepaths.length;r++)a.edgepaths[r]=s(a.edgepaths[r]);for(r=0;r<a.paths.length;r++)a.paths[r]=s(a.paths[r]);return t;case"][":var c=s;s=l,l=c;case"[]":for(2!==t.length&&n.warn("Contour data invalid for the specified inequality range operation."),a=i(t[0]),o=i(t[1]),r=0;r<a.edgepaths.length;r++)a.edgepaths[r]=s(a.edgepaths[r]);for(r=0;r<a.paths.length;r++)a.paths[r]=s(a.paths[r]);for(;o.edgepaths.length;)a.edgepaths.push(l(o.edgepaths.shift()));for(;o.paths.length;)a.paths.push(l(o.paths.shift()));return[a]}}},{"../../lib":697}],925:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../heatmap/xyz_defaults"),a=t("./constraint_defaults"),o=t("./contours_defaults"),s=t("./style_defaults"),l=t("./attributes");e.exports=function(t,e,r,c){function u(r,i){return n.coerce(t,e,l,r,i)}if(i(t,e,u,c)){u("text"),u("hovertext"),u("hovertemplate");var h="constraint"===u("contours.type");u("connectgaps",n.isArray1D(e.z)),h?a(t,e,u,c,r):(o(t,e,u,function(r){return n.coerce2(t,e,l,r)}),s(t,e,u,c))}else e.visible=!1}},{"../../lib":697,"../heatmap/xyz_defaults":959,"./attributes":916,"./constraint_defaults":921,"./contours_defaults":923,"./style_defaults":937}],926:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./constraint_mapping"),a=t("./end_plus");e.exports=function(t,e,r){for(var o="constraint"===t.type?i[t._operation](t.value):t,s=o.size,l=[],c=a(o),u=r.trace._carpetTrace,h=u?{xaxis:u.aaxis,yaxis:u.baxis,x:r.a,y:r.b}:{xaxis:e.xaxis,yaxis:e.yaxis,x:r.x,y:r.y},f=o.start;f<c;f+=s)if(l.push(n.extendFlat({level:f,crossings:{},starts:[],edgepaths:[],paths:[],z:r.z,smoothing:r.trace.line.smoothing},h)),l.length>1e3){n.warn("Too many contours, clipping at 1000",t);break}return l}},{"../../lib":697,"./constraint_mapping":922,"./end_plus":927}],927:[function(t,e,r){"use strict";e.exports=function(t){return t.end+t.size/1e6}},{}],928:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./constants");function a(t,e,r,n){return Math.abs(t[0]-e[0])<r&&Math.abs(t[1]-e[1])<n}function o(t,e,r,o,l){var c,u=e.join(","),h=u,f=t.crossings[h],p=function(t,e,r){var n=0,a=0;t>20&&e?208===t||1114===t?n=0===r[0]?1:-1:a=0===r[1]?1:-1:-1!==i.BOTTOMSTART.indexOf(t)?a=1:-1!==i.LEFTSTART.indexOf(t)?n=1:-1!==i.TOPSTART.indexOf(t)?a=-1:n=-1;return[n,a]}(f,r,e),d=[s(t,e,[-p[0],-p[1]])],g=p.join(","),v=t.z.length,m=t.z[0].length;for(c=0;c<1e4;c++){if(f>20?(f=i.CHOOSESADDLE[f][(p[0]||p[1])<0?0:1],t.crossings[h]=i.SADDLEREMAINDER[f]):delete t.crossings[h],!(p=i.NEWDELTA[f])){n.log("Found bad marching index:",f,e,t.level);break}d.push(s(t,e,p)),e[0]+=p[0],e[1]+=p[1],a(d[d.length-1],d[d.length-2],o,l)&&d.pop(),h=e.join(",");var y=p[0]&&(e[0]<0||e[0]>m-2)||p[1]&&(e[1]<0||e[1]>v-2);if(h===u&&p.join(",")===g||r&&y)break;f=t.crossings[h]}1e4===c&&n.log("Infinite loop in contour?");var x,b,_,w,k,A,M,T,S,E,C,L,z,O,I,D=a(d[0],d[d.length-1],o,l),P=0,R=.2*t.smoothing,F=[],B=0;for(c=1;c<d.length;c++)L=d[c],z=d[c-1],void 0,void 0,O=L[2]-z[2],I=L[3]-z[3],P+=M=Math.sqrt(O*O+I*I),F.push(M);var N=P/F.length*R;function j(t){return d[t%d.length]}for(c=d.length-2;c>=B;c--)if((x=F[c])<N){for(_=0,b=c-1;b>=B&&x+F[b]<N;b--)x+=F[b];if(D&&c===d.length-2)for(_=0;_<b&&x+F[_]<N;_++)x+=F[_];k=c-b+_+1,A=Math.floor((c+b+_+2)/2),w=D||c!==d.length-2?D||-1!==b?k%2?j(A):[(j(A)[0]+j(A+1)[0])/2,(j(A)[1]+j(A+1)[1])/2]:d[0]:d[d.length-1],d.splice(b+1,c-b+1,w),c=b+1,_&&(B=_),D&&(c===d.length-2?d[_]=d[d.length-1]:0===c&&(d[d.length-1]=d[0]))}for(d.splice(0,B),c=0;c<d.length;c++)d[c].length=2;if(!(d.length<2))if(D)d.pop(),t.paths.push(d);else{r||n.log("Unclosed interior contour?",t.level,u,d.join("L"));var V=!1;for(T=0;T<t.edgepaths.length;T++)if(E=t.edgepaths[T],!V&&a(E[0],d[d.length-1],o,l)){d.pop(),V=!0;var U=!1;for(S=0;S<t.edgepaths.length;S++)if(a((C=t.edgepaths[S])[C.length-1],d[0],o,l)){U=!0,d.shift(),t.edgepaths.splice(T,1),S===T?t.paths.push(d.concat(C)):(S>T&&S--,t.edgepaths[S]=C.concat(d,E));break}U||(t.edgepaths[T]=d.concat(E))}for(T=0;T<t.edgepaths.length&&!V;T++)a((E=t.edgepaths[T])[E.length-1],d[0],o,l)&&(d.shift(),t.edgepaths[T]=E.concat(d),V=!0);V||t.edgepaths.push(d)}}function s(t,e,r){var n=e[0]+Math.max(r[0],0),i=e[1]+Math.max(r[1],0),a=t.z[i][n],o=t.xaxis,s=t.yaxis;if(r[1]){var l=(t.level-a)/(t.z[i][n+1]-a);return[o.c2p((1-l)*t.x[n]+l*t.x[n+1],!0),s.c2p(t.y[i],!0),n+l,i]}var c=(t.level-a)/(t.z[i+1][n]-a);return[o.c2p(t.x[n],!0),s.c2p((1-c)*t.y[i]+c*t.y[i+1],!0),n,i+c]}e.exports=function(t,e,r){var i,a,s,l;for(e=e||.01,r=r||.01,a=0;a<t.length;a++){for(s=t[a],l=0;l<s.starts.length;l++)o(s,s.starts[l],"edge",e,r);for(i=0;Object.keys(s.crossings).length&&i<1e4;)i++,o(s,Object.keys(s.crossings)[0].split(",").map(Number),void 0,e,r);1e4===i&&n.log("Infinite loop in contour?")}}},{"../../lib":697,"./constants":920}],929:[function(t,e,r){"use strict";var n=t("../../components/color"),i=t("../heatmap/hover");e.exports=function(t,e,r,a,o){var s=i(t,e,r,a,o,!0);return s&&s.forEach(function(t){var e=t.trace;"constraint"===e.contours.type&&(e.fillcolor&&n.opacity(e.fillcolor)?t.color=n.addOpacity(e.fillcolor,1):e.contours.showlines&&n.opacity(e.line.color)&&(t.color=n.addOpacity(e.line.color,1)))}),s}},{"../../components/color":574,"../heatmap/hover":952}],930:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("./calc"),n.plot=t("./plot").plot,n.style=t("./style"),n.colorbar=t("./colorbar"),n.hoverPoints=t("./hover"),n.moduleType="trace",n.name="contour",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","svg","2dMap","contour","showLegend"],n.meta={},e.exports=n},{"../../plots/cartesian":756,"./attributes":916,"./calc":917,"./colorbar":919,"./defaults":925,"./hover":929,"./plot":934,"./style":936}],931:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e,r,i){if(i||(i={}),t("contours.showlabels")){var a=e.font;n.coerceFont(t,"contours.labelfont",{family:a.family,size:a.size,color:r}),t("contours.labelformat")}!1!==i.hasHover&&t("zhoverformat")}},{"../../lib":697}],932:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../components/colorscale"),a=t("./end_plus");e.exports=function(t){var e=t.contours,r=e.start,o=a(e),s=e.size||1,l=Math.floor((o-r)/s)+1,c="lines"===e.coloring?0:1;isFinite(s)||(s=1,l=1);var u,h,f=t.reversescale?i.flipScale(t.colorscale):t.colorscale,p=f.length,d=new Array(p),g=new Array(p);if("heatmap"===e.coloring){for(t.zauto&&!1===t.autocontour&&(t.zmin=r-s/2,t.zmax=t.zmin+l*s),h=0;h<p;h++)u=f[h],d[h]=u[0]*(t.zmax-t.zmin)+t.zmin,g[h]=u[1];var v=n.extent([t.zmin,t.zmax,e.start,e.start+s*(l-1)]),m=v[t.zmin<t.zmax?0:1],y=v[t.zmin<t.zmax?1:0];m!==t.zmin&&(d.splice(0,0,m),g.splice(0,0,Range[0])),y!==t.zmax&&(d.push(y),g.push(g[g.length-1]))}else for(h=0;h<p;h++)u=f[h],d[h]=(u[0]*(l+c-1)-c/2)*s+r,g[h]=u[1];return i.makeColorScaleFunc({domain:d,range:g},{noNumericCheck:!0})}},{"../../components/colorscale":586,"./end_plus":927,d3:151}],933:[function(t,e,r){"use strict";var n=t("./constants");function i(t,e){var r=(e[0][0]>t?0:1)+(e[0][1]>t?0:2)+(e[1][1]>t?0:4)+(e[1][0]>t?0:8);return 5===r||10===r?t>(e[0][0]+e[0][1]+e[1][0]+e[1][1])/4?5===r?713:1114:5===r?104:208:15===r?0:r}e.exports=function(t){var e,r,a,o,s,l,c,u,h,f=t[0].z,p=f.length,d=f[0].length,g=2===p||2===d;for(r=0;r<p-1;r++)for(o=[],0===r&&(o=o.concat(n.BOTTOMSTART)),r===p-2&&(o=o.concat(n.TOPSTART)),e=0;e<d-1;e++)for(a=o.slice(),0===e&&(a=a.concat(n.LEFTSTART)),e===d-2&&(a=a.concat(n.RIGHTSTART)),s=e+","+r,l=[[f[r][e],f[r][e+1]],[f[r+1][e],f[r+1][e+1]]],h=0;h<t.length;h++)(c=i((u=t[h]).level,l))&&(u.crossings[s]=c,-1!==a.indexOf(c)&&(u.starts.push([e,r]),g&&-1!==a.indexOf(c,a.indexOf(c)+1)&&u.starts.push([e,r])))}},{"./constants":920}],934:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../lib"),a=t("../../components/drawing"),o=t("../../lib/svg_text_utils"),s=t("../../plots/cartesian/axes"),l=t("../../plots/cartesian/set_convert"),c=t("../heatmap/plot"),u=t("./make_crossings"),h=t("./find_all_paths"),f=t("./empty_pathinfo"),p=t("./convert_to_constraints"),d=t("./close_boundaries"),g=t("./constants"),v=g.LABELOPTIMIZER;function m(t,e){var r,n,o,s,l,c,u,h=function(t,e){var r=t.prefixBoundary;if(void 0===r){var n=Math.min(t.z[0][0],t.z[0][1]);r=!t.edgepaths.length&&n>t.level}return r?"M"+e.join("L")+"Z":""}(t,e),f=0,p=t.edgepaths.map(function(t,e){return e}),d=!0;function g(t){return Math.abs(t[1]-e[2][1])<.01}function v(t){return Math.abs(t[0]-e[0][0])<.01}function m(t){return Math.abs(t[0]-e[2][0])<.01}for(;p.length;){for(c=a.smoothopen(t.edgepaths[f],t.smoothing),h+=d?c:c.replace(/^M/,"L"),p.splice(p.indexOf(f),1),r=t.edgepaths[f][t.edgepaths[f].length-1],s=-1,o=0;o<4;o++){if(!r){i.log("Missing end?",f,t);break}for(u=r,Math.abs(u[1]-e[0][1])<.01&&!m(r)?n=e[1]:v(r)?n=e[0]:g(r)?n=e[3]:m(r)&&(n=e[2]),l=0;l<t.edgepaths.length;l++){var y=t.edgepaths[l][0];Math.abs(r[0]-n[0])<.01?Math.abs(r[0]-y[0])<.01&&(y[1]-r[1])*(n[1]-y[1])>=0&&(n=y,s=l):Math.abs(r[1]-n[1])<.01?Math.abs(r[1]-y[1])<.01&&(y[0]-r[0])*(n[0]-y[0])>=0&&(n=y,s=l):i.log("endpt to newendpt is not vert. or horz.",r,n,y)}if(r=n,s>=0)break;h+="L"+n}if(s===t.edgepaths.length){i.log("unclosed perimeter path");break}f=s,(d=-1===p.indexOf(f))&&(f=p[0],h+="Z")}for(f=0;f<t.paths.length;f++)h+=a.smoothclosed(t.paths[f],t.smoothing);return h}function y(t,e,r,n){var a=e.width/2,o=e.height/2,s=t.x,l=t.y,c=t.theta,u=Math.cos(c)*a,h=Math.sin(c)*a,f=(s>n.center?n.right-s:s-n.left)/(u+Math.abs(Math.sin(c)*o)),p=(l>n.middle?n.bottom-l:l-n.top)/(Math.abs(h)+Math.cos(c)*o);if(f<1||p<1)return 1/0;var d=v.EDGECOST*(1/(f-1)+1/(p-1));d+=v.ANGLECOST*c*c;for(var g=s-u,m=l-h,y=s+u,x=l+h,b=0;b<r.length;b++){var _=r[b],w=Math.cos(_.theta)*_.width/2,k=Math.sin(_.theta)*_.width/2,A=2*i.segmentDistance(g,m,y,x,_.x-w,_.y-k,_.x+w,_.y+k)/(e.height+_.height),M=_.level===e.level,T=M?v.SAMELEVELDISTANCE:1;if(A<=T)return 1/0;d+=v.NEIGHBORCOST*(M?v.SAMELEVELFACTOR:1)/(A-T)}return d}r.plot=function(t,e,o,s){var l=e.xaxis,v=e.yaxis;i.makeTraceGroups(s,o,"contour").each(function(o){var s=n.select(this),y=o[0],x=y.trace,b=y.x,_=y.y,w=x.contours,k=f(w,e,y),A=i.ensureSingle(s,"g","heatmapcoloring"),M=[];"heatmap"===w.coloring&&(x.zauto&&!1===x.autocontour&&(x._input.zmin=x.zmin=w.start-w.size/2,x._input.zmax=x.zmax=x.zmin+k.length*w.size),M=[o]),c(t,e,M,A),u(k),h(k);var T=l.c2p(b[0],!0),S=l.c2p(b[b.length-1],!0),E=v.c2p(_[0],!0),C=v.c2p(_[_.length-1],!0),L=[[T,C],[S,C],[S,E],[T,E]],z=k;"constraint"===w.type&&(z=p(k,w._operation),d(z,w._operation,L,x)),function(t,e,r){var n=i.ensureSingle(t,"g","contourbg").selectAll("path").data("fill"===r.coloring?[0]:[]);n.enter().append("path"),n.exit().remove(),n.attr("d","M"+e.join("L")+"Z").style("stroke","none")}(s,L,w),function(t,e,r,a){var o=i.ensureSingle(t,"g","contourfill").selectAll("path").data("fill"===a.coloring||"constraint"===a.type&&"="!==a._operation?e:[]);o.enter().append("path"),o.exit().remove(),o.each(function(t){var e=m(t,r);e?n.select(this).attr("d",e).style("stroke","none"):n.select(this).remove()})}(s,z,L,w),function(t,e,o,s,l,c){var u=i.ensureSingle(t,"g","contourlines"),h=!1!==l.showlines,f=l.showlabels,p=h&&f,d=r.createLines(u,h||f,e),v=r.createLineClip(u,p,o,s.trace.uid),m=t.selectAll("g.contourlabels").data(f?[0]:[]);if(m.exit().remove(),m.enter().append("g").classed("contourlabels",!0),f){var y=[],x=[];i.clearLocationCache();var b=r.labelFormatter(l,s.t.cb,o._fullLayout),_=a.tester.append("text").attr("data-notex",1).call(a.font,l.labelfont),w=e[0].xaxis,k=e[0].yaxis,A=w._length,M=k._length,T=w.range,S=k.range,E=Math.max(c[0][0],0),C=Math.min(c[2][0],A),L=Math.max(c[0][1],0),z=Math.min(c[2][1],M),O={};T[0]<T[1]?(O.left=E,O.right=C):(O.left=C,O.right=E),S[0]<S[1]?(O.top=L,O.bottom=z):(O.top=z,O.bottom=L),O.middle=(O.top+O.bottom)/2,O.center=(O.left+O.right)/2,y.push([[O.left,O.top],[O.right,O.top],[O.right,O.bottom],[O.left,O.bottom]]);var I=Math.sqrt(A*A+M*M),D=g.LABELDISTANCE*I/Math.max(1,e.length/g.LABELINCREASE);d.each(function(t){var e=r.calcTextOpts(t.level,b,_,o);n.select(this).selectAll("path").each(function(){var t=i.getVisibleSegment(this,O,e.height/2);if(t&&!(t.len<(e.width+e.height)*g.LABELMIN))for(var n=Math.min(Math.ceil(t.len/D),g.LABELMAX),a=0;a<n;a++){var o=r.findBestTextLocation(this,t,e,x,O);if(!o)break;r.addLabelData(o,e,x,y)}})}),_.remove(),r.drawLabels(m,x,o,v,p?y:null)}f&&!h&&d.remove()}(s,k,t,y,w,L),function(t,e,r,n,o){var s=r._fullLayout._clips,l="clip"+n.trace.uid,c=s.selectAll("#"+l).data(n.trace.connectgaps?[]:[0]);if(c.enter().append("clipPath").classed("contourclip",!0).attr("id",l),c.exit().remove(),!1===n.trace.connectgaps){var f={level:.9,crossings:{},starts:[],edgepaths:[],paths:[],xaxis:e.xaxis,yaxis:e.yaxis,x:n.x,y:n.y,z:function(t){var e,r,n=t.trace._emptypoints,i=[],a=t.z.length,o=t.z[0].length,s=[];for(e=0;e<o;e++)s.push(1);for(e=0;e<a;e++)i.push(s.slice());for(e=0;e<n.length;e++)r=n[e],i[r[0]][r[1]]=0;return t.zmask=i,i}(n),smoothing:0};u([f]),h([f]);var p=m(f,o),d=i.ensureSingle(c,"path","");d.attr("d",p)}else l=null;a.setClipUrl(t,l,r)}(s,e,t,y,L)})},r.createLines=function(t,e,r){var n=r[0].smoothing,i=t.selectAll("g.contourlevel").data(e?r:[]);if(i.exit().remove(),i.enter().append("g").classed("contourlevel",!0),e){var o=i.selectAll("path.openline").data(function(t){return t.pedgepaths||t.edgepaths});o.exit().remove(),o.enter().append("path").classed("openline",!0),o.attr("d",function(t){return a.smoothopen(t,n)}).style("stroke-miterlimit",1).style("vector-effect","non-scaling-stroke");var s=i.selectAll("path.closedline").data(function(t){return t.ppaths||t.paths});s.exit().remove(),s.enter().append("path").classed("closedline",!0),s.attr("d",function(t){return a.smoothclosed(t,n)}).style("stroke-miterlimit",1).style("vector-effect","non-scaling-stroke")}return i},r.createLineClip=function(t,e,r,n){var i=e?"clipline"+n:null,o=r._fullLayout._clips.selectAll("#"+i).data(e?[0]:[]);return o.exit().remove(),o.enter().append("clipPath").classed("contourlineclip",!0).attr("id",i),a.setClipUrl(t,i,r),o},r.labelFormatter=function(t,e,r){if(t.labelformat)return r._d3locale.numberFormat(t.labelformat);var n;if(e)n=e.axis;else{if(n={type:"linear",_id:"ycontour",showexponent:"all",exponentformat:"B"},"constraint"===t.type){var i=t.value;Array.isArray(i)?n.range=[i[0],i[i.length-1]]:n.range=[i,i]}else n.range=[t.start,t.end],n.nticks=(t.end-t.start)/t.size;n.range[0]===n.range[1]&&(n.range[1]+=n.range[0]||1),n.nticks||(n.nticks=1e3),l(n,r),s.prepTicks(n),n._tmin=null,n._tmax=null}return function(t){return s.tickText(n,t).text}},r.calcTextOpts=function(t,e,r,n){var i=e(t);r.text(i).call(o.convertToTspans,n);var s=a.bBox(r.node(),!0);return{text:i,width:s.width,height:s.height,level:t,dy:(s.top+s.bottom)/2}},r.findBestTextLocation=function(t,e,r,n,a){var o,s,l,c,u,h=r.width;e.isClosed?(s=e.len/v.INITIALSEARCHPOINTS,o=e.min+s/2,l=e.max):(s=(e.len-h)/(v.INITIALSEARCHPOINTS+1),o=e.min+s+h/2,l=e.max-(s+h)/2);for(var f=1/0,p=0;p<v.ITERATIONS;p++){for(var d=o;d<l;d+=s){var g=i.getTextLocation(t,e.total,d,h),m=y(g,r,n,a);m<f&&(f=m,u=g,c=d)}if(f>2*v.MAXCOST)break;p&&(s/=2),l=(o=c-s/2)+1.5*s}if(f<=v.MAXCOST)return u},r.addLabelData=function(t,e,r,n){var i=e.width/2,a=e.height/2,o=t.x,s=t.y,l=t.theta,c=Math.sin(l),u=Math.cos(l),h=i*u,f=a*c,p=i*c,d=-a*u,g=[[o-h-f,s-p-d],[o+h-f,s+p-d],[o+h+f,s+p+d],[o-h+f,s-p+d]];r.push({text:e.text,x:o,y:s,dy:e.dy,theta:l,level:e.level,width:e.width,height:e.height}),n.push(g)},r.drawLabels=function(t,e,r,a,s){var l=t.selectAll("text").data(e,function(t){return t.text+","+t.x+","+t.y+","+t.theta});if(l.exit().remove(),l.enter().append("text").attr({"data-notex":1,"text-anchor":"middle"}).each(function(t){var e=t.x+Math.sin(t.theta)*t.dy,i=t.y-Math.cos(t.theta)*t.dy;n.select(this).text(t.text).attr({x:e,y:i,transform:"rotate("+180*t.theta/Math.PI+" "+e+" "+i+")"}).call(o.convertToTspans,r)}),s){for(var c="",u=0;u<s.length;u++)c+="M"+s[u].join("L")+"Z";i.ensureSingle(a,"path","").attr("d",c)}}},{"../../components/drawing":595,"../../lib":697,"../../lib/svg_text_utils":721,"../../plots/cartesian/axes":745,"../../plots/cartesian/set_convert":763,"../heatmap/plot":956,"./close_boundaries":918,"./constants":920,"./convert_to_constraints":924,"./empty_pathinfo":926,"./find_all_paths":928,"./make_crossings":933,d3:151}],935:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axes"),i=t("../../lib");function a(t,e,r){var i={type:"linear",range:[t,e]};return n.autoTicks(i,(e-t)/(r||15)),i}e.exports=function(t){var e=t.contours;if(t.autocontour){var r=t.zmin,o=t.zmax;void 0!==r&&void 0!==o||(r=i.aggNums(Math.min,null,t._z),o=i.aggNums(Math.max,null,t._z));var s=a(r,o,t.ncontours);e.size=s.dtick,e.start=n.tickFirst(s),s.range.reverse(),e.end=n.tickFirst(s),e.start===r&&(e.start+=e.size),e.end===o&&(e.end-=e.size),e.start>e.end&&(e.start=e.end=(e.start+e.end)/2),t._input.contours||(t._input.contours={}),i.extendFlat(t._input.contours,{start:e.start,end:e.end,size:e.size}),t._input.autocontour=!0}else if("constraint"!==e.type){var l,c=e.start,u=e.end,h=t._input.contours;if(c>u&&(e.start=h.start=u,u=e.end=h.end=c,c=e.start),!(e.size>0))l=c===u?1:a(c,u,t.ncontours).dtick,h.size=e.size=l}}},{"../../lib":697,"../../plots/cartesian/axes":745}],936:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../components/drawing"),a=t("../heatmap/style"),o=t("./make_color_map");e.exports=function(t){var e=n.select(t).selectAll("g.contour");e.style("opacity",function(t){return t[0].trace.opacity}),e.each(function(t){var e=n.select(this),r=t[0].trace,a=r.contours,s=r.line,l=a.size||1,c=a.start,u="constraint"===a.type,h=!u&&"lines"===a.coloring,f=!u&&"fill"===a.coloring,p=h||f?o(r):null;e.selectAll("g.contourlevel").each(function(t){n.select(this).selectAll("path").call(i.lineGroupStyle,s.width,h?p(t.level):s.color,s.dash)});var d=a.labelfont;if(e.selectAll("g.contourlabels text").each(function(t){i.font(n.select(this),{family:d.family,size:d.size,color:d.color||(h?p(t.level):s.color)})}),u)e.selectAll("g.contourfill path").style("fill",r.fillcolor);else if(f){var g;e.selectAll("g.contourfill path").style("fill",function(t){return void 0===g&&(g=t.level),p(t.level+.5*l)}),void 0===g&&(g=c),e.selectAll("g.contourbg path").style("fill",p(g-.5*l))}}),a(t)}},{"../../components/drawing":595,"../heatmap/style":957,"./make_color_map":932,d3:151}],937:[function(t,e,r){"use strict";var n=t("../../components/colorscale/defaults"),i=t("./label_defaults");e.exports=function(t,e,r,a,o){var s,l=r("contours.coloring"),c="";"fill"===l&&(s=r("contours.showlines")),!1!==s&&("lines"!==l&&(c=r("line.color","#000")),r("line.width",.5),r("line.dash")),"none"!==l&&(!0!==t.showlegend&&(e.showlegend=!1),e._dfltShowLegend=!1,n(t,e,a,r,{prefix:"",cLetter:"z"})),r("line.smoothing"),i(r,a,c,o)}},{"../../components/colorscale/defaults":584,"./label_defaults":931}],938:[function(t,e,r){"use strict";var n=t("../heatmap/attributes"),i=t("../contour/attributes"),a=i.contours,o=t("../scatter/attributes"),s=t("../../components/colorscale/attributes"),l=t("../../components/colorbar/attributes"),c=t("../../lib/extend").extendFlat,u=o.line;e.exports=c({carpet:{valType:"string",editType:"calc"},z:n.z,a:n.x,a0:n.x0,da:n.dx,b:n.y,b0:n.y0,db:n.dy,text:n.text,hovertext:n.hovertext,transpose:n.transpose,atype:n.xtype,btype:n.ytype,fillcolor:i.fillcolor,autocontour:i.autocontour,ncontours:i.ncontours,contours:{type:a.type,start:a.start,end:a.end,size:a.size,coloring:{valType:"enumerated",values:["fill","lines","none"],dflt:"fill",editType:"calc"},showlines:a.showlines,showlabels:a.showlabels,labelfont:a.labelfont,labelformat:a.labelformat,operation:a.operation,value:a.value,editType:"calc",impliedEdits:{autocontour:!1}},line:{color:c({},u.color,{}),width:u.width,dash:u.dash,smoothing:c({},u.smoothing,{}),editType:"plot"},transforms:void 0},s("",{cLetter:"z",autoColorDflt:!1}),{colorbar:l})},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../lib/extend":687,"../contour/attributes":916,"../heatmap/attributes":945,"../scatter/attributes":1048}],939:[function(t,e,r){"use strict";var n=t("../../components/colorscale/calc"),i=t("../../lib"),a=t("../heatmap/convert_column_xyz"),o=t("../heatmap/clean_2d_array"),s=t("../heatmap/interp2d"),l=t("../heatmap/find_empties"),c=t("../heatmap/make_bound_array"),u=t("./defaults"),h=t("../carpet/lookup_carpetid"),f=t("../contour/set_contours");e.exports=function(t,e){var r=e._carpetTrace=h(t,e);if(r&&r.visible&&"legendonly"!==r.visible){if(!e.a||!e.b){var p=t.data[r.index],d=t.data[e.index];d.a||(d.a=p.a),d.b||(d.b=p.b),u(d,e,e._defaultColor,t._fullLayout)}var g=function(t,e){var r,u,h,f,p,d,g,v=e._carpetTrace,m=v.aaxis,y=v.baxis;m._minDtick=0,y._minDtick=0,i.isArray1D(e.z)&&a(e,m,y,"a","b",["z"]);r=e._a=e._a||e.a,f=e._b=e._b||e.b,r=r?m.makeCalcdata(e,"_a"):[],f=f?y.makeCalcdata(e,"_b"):[],u=e.a0||0,h=e.da||1,p=e.b0||0,d=e.db||1,g=e._z=o(e._z||e.z,e.transpose),e._emptypoints=l(g),s(g,e._emptypoints);var x=i.maxRowLength(g),b="scaled"===e.xtype?"":r,_=c(e,b,u,h,x,m),w="scaled"===e.ytype?"":f,k=c(e,w,p,d,g.length,y),A={a:_,b:k,z:g};"levels"===e.contours.type&&"none"!==e.contours.coloring&&n(t,e,{vals:g,containerStr:"",cLetter:"z"});return[A]}(t,e);return f(e),g}}},{"../../components/colorscale/calc":582,"../../lib":697,"../carpet/lookup_carpetid":894,"../contour/set_contours":935,"../heatmap/clean_2d_array":947,"../heatmap/convert_column_xyz":949,"../heatmap/find_empties":951,"../heatmap/interp2d":954,"../heatmap/make_bound_array":955,"./defaults":940}],940:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../heatmap/xyz_defaults"),a=t("./attributes"),o=t("../contour/constraint_defaults"),s=t("../contour/contours_defaults"),l=t("../contour/style_defaults");e.exports=function(t,e,r,c){function u(r,i){return n.coerce(t,e,a,r,i)}if(u("carpet"),t.a&&t.b){if(!i(t,e,u,c,"a","b"))return void(e.visible=!1);u("text"),"constraint"===u("contours.type")?o(t,e,u,c,r,{hasHover:!1}):(s(t,e,u,function(r){return n.coerce2(t,e,a,r)}),l(t,e,u,c,{hasHover:!1}))}else e._defaultColor=r,e._length=null}},{"../../lib":697,"../contour/constraint_defaults":921,"../contour/contours_defaults":923,"../contour/style_defaults":937,"../heatmap/xyz_defaults":959,"./attributes":938}],941:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../contour/colorbar"),n.calc=t("./calc"),n.plot=t("./plot"),n.style=t("../contour/style"),n.moduleType="trace",n.name="contourcarpet",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","svg","carpet","contour","symbols","showLegend","hasLines","carpetDependent"],n.meta={},e.exports=n},{"../../plots/cartesian":756,"../contour/colorbar":919,"../contour/style":936,"./attributes":938,"./calc":939,"./defaults":940,"./plot":944}],942:[function(t,e,r){"use strict";var n=t("../../components/drawing"),i=t("../carpet/axis_aligned_line"),a=t("../../lib");e.exports=function(t,e,r,o,s,l,c,u){var h,f,p,d,g,v,m,y="",x=e.edgepaths.map(function(t,e){return e}),b=!0,_=1e-4*Math.abs(r[0][0]-r[2][0]),w=1e-4*Math.abs(r[0][1]-r[2][1]);function k(t){return Math.abs(t[1]-r[0][1])<w}function A(t){return Math.abs(t[1]-r[2][1])<w}function M(t){return Math.abs(t[0]-r[0][0])<_}function T(t){return Math.abs(t[0]-r[2][0])<_}function S(t,e){var r,n,a,o,h="";for(k(t)&&!T(t)||A(t)&&!M(t)?(o=s.aaxis,a=i(s,l,[t[0],e[0]],.5*(t[1]+e[1]))):(o=s.baxis,a=i(s,l,.5*(t[0]+e[0]),[t[1],e[1]])),r=1;r<a.length;r++)for(h+=o.smoothing?"C":"L",n=0;n<a[r].length;n++){var f=a[r][n];h+=[c.c2p(f[0]),u.c2p(f[1])]+" "}return h}for(h=0,f=null;x.length;){var E=e.edgepaths[h][0];for(f&&(y+=S(f,E)),m=n.smoothopen(e.edgepaths[h].map(o),e.smoothing),y+=b?m:m.replace(/^M/,"L"),x.splice(x.indexOf(h),1),f=e.edgepaths[h][e.edgepaths[h].length-1],g=-1,d=0;d<4;d++){if(!f){a.log("Missing end?",h,e);break}for(k(f)&&!T(f)?p=r[1]:M(f)?p=r[0]:A(f)?p=r[3]:T(f)&&(p=r[2]),v=0;v<e.edgepaths.length;v++){var C=e.edgepaths[v][0];Math.abs(f[0]-p[0])<_?Math.abs(f[0]-C[0])<_&&(C[1]-f[1])*(p[1]-C[1])>=0&&(p=C,g=v):Math.abs(f[1]-p[1])<w?Math.abs(f[1]-C[1])<w&&(C[0]-f[0])*(p[0]-C[0])>=0&&(p=C,g=v):a.log("endpt to newendpt is not vert. or horz.",f,p,C)}if(g>=0)break;y+=S(f,p),f=p}if(g===e.edgepaths.length){a.log("unclosed perimeter path");break}h=g,(b=-1===x.indexOf(h))&&(h=x[0],y+=S(f,p)+"Z",f=null)}for(h=0;h<e.paths.length;h++)y+=n.smoothclosed(e.paths[h].map(o),e.smoothing);return y}},{"../../components/drawing":595,"../../lib":697,"../carpet/axis_aligned_line":878}],943:[function(t,e,r){"use strict";e.exports=function(t,e){var r,n,i,a,o,s,l,c,u;for(r=0;r<t.length;r++){for(o=(a=t[r]).pedgepaths=[],s=a.ppaths=[],n=0;n<a.edgepaths.length;n++){for(u=a.edgepaths[n],l=[],i=0;i<u.length;i++)l[i]=e(u[i]);o.push(l)}for(n=0;n<a.paths.length;n++){for(u=a.paths[n],c=[],i=0;i<u.length;i++)c[i]=e(u[i]);s.push(c)}}}},{}],944:[function(t,e,r){"use strict";var n=t("d3"),i=t("../carpet/map_1d_array"),a=t("../carpet/makepath"),o=t("../../components/drawing"),s=t("../../lib"),l=t("../contour/make_crossings"),c=t("../contour/find_all_paths"),u=t("../contour/plot"),h=t("../contour/constants"),f=t("../contour/convert_to_constraints"),p=t("./join_all_paths"),d=t("../contour/empty_pathinfo"),g=t("./map_pathinfo"),v=t("../carpet/lookup_carpetid"),m=t("../contour/close_boundaries");function y(t,e,r){var n=t.getPointAtLength(e),i=t.getPointAtLength(r),a=i.x-n.x,o=i.y-n.y,s=Math.sqrt(a*a+o*o);return[a/s,o/s]}function x(t){var e=Math.sqrt(t[0]*t[0]+t[1]*t[1]);return[t[0]/e,t[1]/e]}function b(t,e){var r=Math.abs(t[0]*e[0]+t[1]*e[1]);return Math.sqrt(1-r*r)/r}e.exports=function(t,e,r,_){var w=e.xaxis,k=e.yaxis;s.makeTraceGroups(_,r,"contour").each(function(r){var _=n.select(this),A=r[0],M=A.trace,T=M._carpetTrace=v(t,M),S=t.calcdata[T.index][0];if(T.visible&&"legendonly"!==T.visible){var E=A.a,C=A.b,L=M.contours,z=d(L,e,A),O="constraint"===L.type,I=L._operation,D=O?"="===I?"lines":"fill":L.coloring,P=[[E[0],C[C.length-1]],[E[E.length-1],C[C.length-1]],[E[E.length-1],C[0]],[E[0],C[0]]];l(z);var R=1e-8*(E[E.length-1]-E[0]),F=1e-8*(C[C.length-1]-C[0]);c(z,R,F);var B,N,j,V,U=z;"constraint"===L.type&&(U=f(z,I),m(U,I,P,M)),g(z,G);var q=[];for(V=S.clipsegments.length-1;V>=0;V--)B=S.clipsegments[V],N=i([],B.x,w.c2p),j=i([],B.y,k.c2p),N.reverse(),j.reverse(),q.push(a(N,j,B.bicubic));var H="M"+q.join("L")+"Z";!function(t,e,r,n,o,l){var c,u,h,f,p=s.ensureSingle(t,"g","contourbg").selectAll("path").data("fill"!==l||o?[]:[0]);p.enter().append("path"),p.exit().remove();var d=[];for(f=0;f<e.length;f++)c=e[f],u=i([],c.x,r.c2p),h=i([],c.y,n.c2p),d.push(a(u,h,c.bicubic));p.attr("d","M"+d.join("L")+"Z").style("stroke","none")}(_,S.clipsegments,w,k,O,D),function(t,e,r,i,a,o,l,c,u,h,f){var d=s.ensureSingle(e,"g","contourfill").selectAll("path").data("fill"===h?a:[]);d.enter().append("path"),d.exit().remove(),d.each(function(e){var a=p(t,e,o,l,c,u,r,i);e.prefixBoundary&&(a=f+a),a?n.select(this).attr("d",a).style("stroke","none"):n.select(this).remove()})}(M,_,w,k,U,P,G,T,S,D,H),function(t,e,r,i,a,l,c){var f=s.ensureSingle(t,"g","contourlines"),p=!1!==a.showlines,d=a.showlabels,g=p&&d,v=u.createLines(f,p||d,e),m=u.createLineClip(f,g,r,i.trace.uid),_=t.selectAll("g.contourlabels").data(d?[0]:[]);if(_.exit().remove(),_.enter().append("g").classed("contourlabels",!0),d){var w=l.xaxis,k=l.yaxis,A=w._length,M=k._length,T=[[[0,0],[A,0],[A,M],[0,M]]],S=[];s.clearLocationCache();var E=u.labelFormatter(a,i.t.cb,r._fullLayout),C=o.tester.append("text").attr("data-notex",1).call(o.font,a.labelfont),L={left:0,right:A,center:A/2,top:0,bottom:M,middle:M/2},z=Math.sqrt(A*A+M*M),O=h.LABELDISTANCE*z/Math.max(1,e.length/h.LABELINCREASE);v.each(function(t){var e=u.calcTextOpts(t.level,E,C,r);n.select(this).selectAll("path").each(function(r){var n=s.getVisibleSegment(this,L,e.height/2);if(n&&(function(t,e,r,n,i,a){for(var o,s=0;s<r.pedgepaths.length;s++)e===r.pedgepaths[s]&&(o=r.edgepaths[s]);if(!o)return;var l=i.a[0],c=i.a[i.a.length-1],u=i.b[0],h=i.b[i.b.length-1];function f(t,e){var r,n=0;return(Math.abs(t[0]-l)<.1||Math.abs(t[0]-c)<.1)&&(r=x(i.dxydb_rough(t[0],t[1],.1)),n=Math.max(n,a*b(e,r)/2)),(Math.abs(t[1]-u)<.1||Math.abs(t[1]-h)<.1)&&(r=x(i.dxyda_rough(t[0],t[1],.1)),n=Math.max(n,a*b(e,r)/2)),n}var p=y(t,0,1),d=y(t,n.total,n.total-1),g=f(o[0],p),v=n.total-f(o[o.length-1],d);n.min<g&&(n.min=g);n.max>v&&(n.max=v);n.len=n.max-n.min}(this,r,t,n,c,e.height),!(n.len<(e.width+e.height)*h.LABELMIN)))for(var i=Math.min(Math.ceil(n.len/O),h.LABELMAX),a=0;a<i;a++){var o=u.findBestTextLocation(this,n,e,S,L);if(!o)break;u.addLabelData(o,e,S,T)}})}),C.remove(),u.drawLabels(_,S,r,m,g?T:null)}d&&!p&&v.remove()}(_,z,t,A,L,e,T),o.setClipUrl(_,T._clipPathId,t)}function G(t){var e=T.ab2xy(t[0],t[1],!0);return[w.c2p(e[0]),k.c2p(e[1])]}})}},{"../../components/drawing":595,"../../lib":697,"../carpet/lookup_carpetid":894,"../carpet/makepath":895,"../carpet/map_1d_array":896,"../contour/close_boundaries":918,"../contour/constants":920,"../contour/convert_to_constraints":924,"../contour/empty_pathinfo":926,"../contour/find_all_paths":928,"../contour/make_crossings":933,"../contour/plot":934,"./join_all_paths":942,"./map_pathinfo":943,d3:151}],945:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../components/fx/hovertemplate_attributes"),a=t("../../components/colorscale/attributes"),o=t("../../components/colorbar/attributes"),s=t("../../lib/extend").extendFlat;e.exports=s({z:{valType:"data_array",editType:"calc"},x:s({},n.x,{impliedEdits:{xtype:"array"}}),x0:s({},n.x0,{impliedEdits:{xtype:"scaled"}}),dx:s({},n.dx,{impliedEdits:{xtype:"scaled"}}),y:s({},n.y,{impliedEdits:{ytype:"array"}}),y0:s({},n.y0,{impliedEdits:{ytype:"scaled"}}),dy:s({},n.dy,{impliedEdits:{ytype:"scaled"}}),text:{valType:"data_array",editType:"calc"},hovertext:{valType:"data_array",editType:"calc"},transpose:{valType:"boolean",dflt:!1,editType:"calc"},xtype:{valType:"enumerated",values:["array","scaled"],editType:"calc+clearAxisTypes"},ytype:{valType:"enumerated",values:["array","scaled"],editType:"calc+clearAxisTypes"},zsmooth:{valType:"enumerated",values:["fast","best",!1],dflt:!1,editType:"calc"},connectgaps:{valType:"boolean",dflt:!1,editType:"calc"},xgap:{valType:"number",dflt:0,min:0,editType:"plot"},ygap:{valType:"number",dflt:0,min:0,editType:"plot"},zhoverformat:{valType:"string",dflt:"",editType:"none"},hovertemplate:i()},{transforms:void 0},a("",{cLetter:"z",autoColorDflt:!1}),{colorbar:o})},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../scatter/attributes":1048}],946:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("../../lib"),a=t("../../plots/cartesian/axes"),o=t("../histogram2d/calc"),s=t("../../components/colorscale/calc"),l=t("./convert_column_xyz"),c=t("./clean_2d_array"),u=t("./interp2d"),h=t("./find_empties"),f=t("./make_bound_array");e.exports=function(t,e){var r,p,d,g,v,m,y,x,b,_=a.getFromId(t,e.xaxis||"x"),w=a.getFromId(t,e.yaxis||"y"),k=n.traceIs(e,"contour"),A=n.traceIs(e,"histogram"),M=n.traceIs(e,"gl2d"),T=k?"best":e.zsmooth;if(_._minDtick=0,w._minDtick=0,A)r=(b=o(t,e)).x,p=b.x0,d=b.dx,g=b.y,v=b.y0,m=b.dy,y=b.z;else{var S=e.z;i.isArray1D(S)?(l(e,_,w,"x","y",["z"]),r=e._x,g=e._y,S=e._z):(r=e.x?_.makeCalcdata(e,"x"):[],g=e.y?w.makeCalcdata(e,"y"):[]),p=e.x0||0,d=e.dx||1,v=e.y0||0,m=e.dy||1,y=c(S,e.transpose),(k||e.connectgaps)&&(e._emptypoints=h(y),u(y,e._emptypoints))}function E(t){T=e._input.zsmooth=e.zsmooth=!1,i.warn('cannot use zsmooth: "fast": '+t)}if("fast"===T)if("log"===_.type||"log"===w.type)E("log axis found");else if(!A){if(r.length){var C=(r[r.length-1]-r[0])/(r.length-1),L=Math.abs(C/100);for(x=0;x<r.length-1;x++)if(Math.abs(r[x+1]-r[x]-C)>L){E("x scale is not linear");break}}if(g.length&&"fast"===T){var z=(g[g.length-1]-g[0])/(g.length-1),O=Math.abs(z/100);for(x=0;x<g.length-1;x++)if(Math.abs(g[x+1]-g[x]-z)>O){E("y scale is not linear");break}}}var I=i.maxRowLength(y),D="scaled"===e.xtype?"":r,P=f(e,D,p,d,I,_),R="scaled"===e.ytype?"":g,F=f(e,R,v,m,y.length,w);M||(e._extremes[_._id]=a.findExtremes(_,P),e._extremes[w._id]=a.findExtremes(w,F));var B={x:P,y:F,z:y,text:e._text||e.text,hovertext:e._hovertext||e.hovertext};if(D&&D.length===P.length-1&&(B.xCenter=D),R&&R.length===F.length-1&&(B.yCenter=R),A&&(B.xRanges=b.xRanges,B.yRanges=b.yRanges,B.pts=b.pts),k&&"constraint"===e.contours.type||s(t,e,{vals:y,containerStr:"",cLetter:"z"}),k&&e.contours&&"heatmap"===e.contours.coloring){var N={type:"contour"===e.type?"heatmap":"histogram2d",xcalendar:e.xcalendar,ycalendar:e.ycalendar};B.xfill=f(N,D,p,d,I,_),B.yfill=f(N,R,v,m,y.length,w)}return[B]}},{"../../components/colorscale/calc":582,"../../lib":697,"../../plots/cartesian/axes":745,"../../registry":826,"../histogram2d/calc":977,"./clean_2d_array":947,"./convert_column_xyz":949,"./find_empties":951,"./interp2d":954,"./make_bound_array":955}],947:[function(t,e,r){"use strict";var n=t("fast-isnumeric");e.exports=function(t,e){var r,i,a,o,s,l;function c(t){if(n(t))return+t}if(e){for(r=0,s=0;s<t.length;s++)r=Math.max(r,t[s].length);if(0===r)return!1;a=function(t){return t.length},o=function(t,e,r){return t[r][e]}}else r=t.length,a=function(t,e){return t[e].length},o=function(t,e,r){return t[e][r]};var u=new Array(r);for(s=0;s<r;s++)for(i=a(t,s),u[s]=new Array(i),l=0;l<i;l++)u[s][l]=c(o(t,s,l));return u}},{"fast-isnumeric":218}],948:[function(t,e,r){"use strict";e.exports={min:"zmin",max:"zmax"}},{}],949:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../constants/numerical").BADNUM;e.exports=function(t,e,r,a,o,s){var l,c,u,h,f=t._length,p=e.makeCalcdata(t,a),d=r.makeCalcdata(t,o),g=t.text,v=void 0!==g&&n.isArray1D(g),m=t.hovertext,y=void 0!==m&&n.isArray1D(m),x=n.distinctVals(p),b=x.vals,_=n.distinctVals(d),w=_.vals,k=[];for(l=0;l<s.length;l++)k[l]=n.init2dArray(w.length,b.length);for(v&&(u=n.init2dArray(w.length,b.length)),y&&(h=n.init2dArray(w.length,b.length)),l=0;l<f;l++)if(p[l]!==i&&d[l]!==i){var A=n.findBin(p[l]+x.minDiff/2,b),M=n.findBin(d[l]+_.minDiff/2,w);for(c=0;c<s.length;c++){var T=t[s[c]];k[c][M][A]=T[l]}v&&(u[M][A]=g[l]),y&&(h[M][A]=m[l])}for(t["_"+a]=b,t["_"+o]=w,c=0;c<s.length;c++)t["_"+s[c]]=k[c];v&&(t._text=u),y&&(t._hovertext=h)}},{"../../constants/numerical":674,"../../lib":697}],950:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./xyz_defaults"),a=t("./style_defaults"),o=t("../../components/colorscale/defaults"),s=t("./attributes");e.exports=function(t,e,r,l){function c(r,i){return n.coerce(t,e,s,r,i)}i(t,e,c,l)?(c("text"),c("hovertext"),c("hovertemplate"),a(t,e,c,l),c("connectgaps",n.isArray1D(e.z)&&!1!==e.zsmooth),o(t,e,l,c,{prefix:"",cLetter:"z"})):e.visible=!1}},{"../../components/colorscale/defaults":584,"../../lib":697,"./attributes":945,"./style_defaults":958,"./xyz_defaults":959}],951:[function(t,e,r){"use strict";var n=t("../../lib").maxRowLength;e.exports=function(t){var e,r,i,a,o,s,l,c,u=[],h={},f=[],p=t[0],d=[],g=[0,0,0],v=n(t);for(r=0;r<t.length;r++)for(e=d,d=p,p=t[r+1]||[],i=0;i<v;i++)void 0===d[i]&&((s=(void 0!==d[i-1]?1:0)+(void 0!==d[i+1]?1:0)+(void 0!==e[i]?1:0)+(void 0!==p[i]?1:0))?(0===r&&s++,0===i&&s++,r===t.length-1&&s++,i===d.length-1&&s++,s<4&&(h[[r,i]]=[r,i,s]),u.push([r,i,s])):f.push([r,i]));for(;f.length;){for(l={},c=!1,o=f.length-1;o>=0;o--)(s=((h[[(r=(a=f[o])[0])-1,i=a[1]]]||g)[2]+(h[[r+1,i]]||g)[2]+(h[[r,i-1]]||g)[2]+(h[[r,i+1]]||g)[2])/20)&&(l[a]=[r,i,s],f.splice(o,1),c=!0);if(!c)throw"findEmpties iterated with no new neighbors";for(a in l)h[a]=l[a],u.push(l[a])}return u.sort(function(t,e){return e[2]-t[2]})}},{"../../lib":697}],952:[function(t,e,r){"use strict";var n=t("../../components/fx"),i=t("../../lib"),a=t("../../plots/cartesian/axes");e.exports=function(t,e,r,o,s,l){var c,u,h,f,p=t.cd[0],d=p.trace,g=t.xa,v=t.ya,m=p.x,y=p.y,x=p.z,b=p.xCenter,_=p.yCenter,w=p.zmask,k=[d.zmin,d.zmax],A=d.zhoverformat,M=m,T=y;if(!1!==t.index){try{h=Math.round(t.index[1]),f=Math.round(t.index[0])}catch(e){return void i.error("Error hovering on heatmap, pointNumber must be [row,col], found:",t.index)}if(h<0||h>=x[0].length||f<0||f>x.length)return}else{if(n.inbox(e-m[0],e-m[m.length-1],0)>0||n.inbox(r-y[0],r-y[y.length-1],0)>0)return;if(l){var S;for(M=[2*m[0]-m[1]],S=1;S<m.length;S++)M.push((m[S]+m[S-1])/2);for(M.push([2*m[m.length-1]-m[m.length-2]]),T=[2*y[0]-y[1]],S=1;S<y.length;S++)T.push((y[S]+y[S-1])/2);T.push([2*y[y.length-1]-y[y.length-2]])}h=Math.max(0,Math.min(M.length-2,i.findBin(e,M))),f=Math.max(0,Math.min(T.length-2,i.findBin(r,T)))}var E=g.c2p(m[h]),C=g.c2p(m[h+1]),L=v.c2p(y[f]),z=v.c2p(y[f+1]);l?(C=E,c=m[h],z=L,u=y[f]):(c=b?b[h]:(m[h]+m[h+1])/2,u=_?_[f]:(y[f]+y[f+1])/2,d.zsmooth&&(E=C=g.c2p(c),L=z=v.c2p(u)));var O,I,D=x[f][h];w&&!w[f][h]&&(D=void 0),Array.isArray(p.hovertext)&&Array.isArray(p.hovertext[f])?O=p.hovertext[f][h]:Array.isArray(p.text)&&Array.isArray(p.text[f])&&(O=p.text[f][h]);var P={type:"linear",range:k,hoverformat:A,_separators:g._separators,_numFormat:g._numFormat};return I=a.tickText(P,D,"hover").text,[i.extendFlat(t,{index:[f,h],distance:t.maxHoverDistance,spikeDistance:t.maxSpikeDistance,x0:E,x1:C,y0:L,y1:z,xLabelVal:c,yLabelVal:u,zLabelVal:D,zLabel:I,text:O})]}},{"../../components/fx":613,"../../lib":697,"../../plots/cartesian/axes":745}],953:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("./calc"),n.plot=t("./plot"),n.colorbar=t("./colorbar"),n.style=t("./style"),n.hoverPoints=t("./hover"),n.moduleType="trace",n.name="heatmap",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","svg","2dMap"],n.meta={},e.exports=n},{"../../plots/cartesian":756,"./attributes":945,"./calc":946,"./colorbar":948,"./defaults":950,"./hover":952,"./plot":956,"./style":957}],954:[function(t,e,r){"use strict";var n=t("../../lib"),i=[[-1,0],[1,0],[0,-1],[0,1]];function a(t){return.5-.25*Math.min(1,.5*t)}function o(t,e,r){var n,a,o,s,l,c,u,h,f,p,d,g,v,m=0;for(s=0;s<e.length;s++){for(a=(n=e[s])[0],o=n[1],d=t[a][o],p=0,f=0,l=0;l<4;l++)(u=t[a+(c=i[l])[0]])&&void 0!==(h=u[o+c[1]])&&(0===p?g=v=h:(g=Math.min(g,h),v=Math.max(v,h)),f++,p+=h);if(0===f)throw"iterateInterp2d order is wrong: no defined neighbors";t[a][o]=p/f,void 0===d?f<4&&(m=1):(t[a][o]=(1+r)*t[a][o]-r*d,v>g&&(m=Math.max(m,Math.abs(t[a][o]-d)/(v-g))))}return m}e.exports=function(t,e){var r,i=1;for(o(t,e),r=0;r<e.length&&!(e[r][2]<4);r++);for(e=e.slice(r),r=0;r<100&&i>.01;r++)i=o(t,e,a(i));return i>.01&&n.log("interp2d didn't converge quickly",i),t}},{"../../lib":697}],955:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("../../lib").isArrayOrTypedArray;e.exports=function(t,e,r,a,o,s){var l,c,u,h=[],f=n.traceIs(t,"contour"),p=n.traceIs(t,"histogram"),d=n.traceIs(t,"gl2d");if(i(e)&&e.length>1&&!p&&"category"!==s.type){var g=e.length;if(!(g<=o))return f?e.slice(0,o):e.slice(0,o+1);if(f||d)h=e.slice(0,o);else if(1===o)h=[e[0]-.5,e[0]+.5];else{for(h=[1.5*e[0]-.5*e[1]],u=1;u<g;u++)h.push(.5*(e[u-1]+e[u]));h.push(1.5*e[g-1]-.5*e[g-2])}if(g<o){var v=h[h.length-1],m=v-h[h.length-2];for(u=g;u<o;u++)v+=m,h.push(v)}}else{c=a||1;var y=t[s._id.charAt(0)+"calendar"];for(l=p||"category"===s.type||"multicategory"===s.type?s.r2c(r,0,y)||0:i(e)&&1===e.length?e[0]:void 0===r?0:s.d2c(r,0,y),u=f||d?0:-.5;u<o;u++)h.push(l+c*u)}return h}},{"../../lib":697,"../../registry":826}],956:[function(t,e,r){"use strict";var n=t("d3"),i=t("tinycolor2"),a=t("../../registry"),o=t("../../lib"),s=t("../../components/colorscale"),l=t("../../constants/xmlns_namespaces");function c(t,e){var r=e.length-2,n=o.constrain(o.findBin(t,e),0,r),i=e[n],a=e[n+1],s=o.constrain(n+(t-i)/(a-i)-.5,0,r),l=Math.round(s),c=Math.abs(s-l);return s&&s!==r&&c?{bin0:l,frac:c,bin1:Math.round(l+c/(s-l))}:{bin0:l,bin1:l,frac:0}}function u(t,e){var r=e.length-1,n=o.constrain(o.findBin(t,e),0,r),i=e[n],a=(t-i)/(e[n+1]-i)||0;return a<=0?{bin0:n,bin1:n,frac:0}:a<.5?{bin0:n,bin1:n+1,frac:a}:{bin0:n+1,bin1:n,frac:1-a}}function h(t,e,r){t[e]=r[0],t[e+1]=r[1],t[e+2]=r[2],t[e+3]=Math.round(255*r[3])}e.exports=function(t,e,r,f){var p=e.xaxis,d=e.yaxis;o.makeTraceGroups(f,r,"hm").each(function(e){var r,f,g,v,m,y,x=n.select(this),b=e[0],_=b.trace,w=b.z,k=b.x,A=b.y,M=b.xCenter,T=b.yCenter,S=a.traceIs(_,"contour"),E=S?"best":_.zsmooth,C=w.length,L=o.maxRowLength(w),z=!1,O=!1;for(y=0;void 0===r&&y<k.length-1;)r=p.c2p(k[y]),y++;for(y=k.length-1;void 0===f&&y>0;)f=p.c2p(k[y]),y--;for(f<r&&(g=f,f=r,r=g,z=!0),y=0;void 0===v&&y<A.length-1;)v=d.c2p(A[y]),y++;for(y=A.length-1;void 0===m&&y>0;)m=d.c2p(A[y]),y--;if(m<v&&(g=v,v=m,m=g,O=!0),S&&(M=k,T=A,k=b.xfill,A=b.yfill),"fast"!==E){var I="best"===E?0:.5;r=Math.max(-I*p._length,r),f=Math.min((1+I)*p._length,f),v=Math.max(-I*d._length,v),m=Math.min((1+I)*d._length,m)}var D=Math.round(f-r),P=Math.round(m-v);if(D<=0||P<=0){x.selectAll("image").data([]).exit().remove()}else{var R,F;"fast"===E?(R=L,F=C):(R=D,F=P);var B=document.createElement("canvas");B.width=R,B.height=F;var N,j,V=B.getContext("2d"),U=s.makeColorScaleFunc(s.extractScale(_,{cLetter:"z"}),{noNumericCheck:!0,returnArray:!0});"fast"===E?(N=z?function(t){return L-1-t}:o.identity,j=O?function(t){return C-1-t}:o.identity):(N=function(t){return o.constrain(Math.round(p.c2p(k[t])-r),0,D)},j=function(t){return o.constrain(Math.round(d.c2p(A[t])-v),0,P)});var q,H,G,Y,W,X=j(0),Z=[X,X],$=z?0:1,J=O?0:1,K=0,Q=0,tt=0,et=0;if(E){var rt,nt=0;try{rt=new Uint8Array(D*P*4)}catch(t){rt=new Array(D*P*4)}if("best"===E){var it,at,ot,st=M||k,lt=T||A,ct=new Array(st.length),ut=new Array(lt.length),ht=new Array(D),ft=M?u:c,pt=T?u:c;for(y=0;y<st.length;y++)ct[y]=Math.round(p.c2p(st[y])-r);for(y=0;y<lt.length;y++)ut[y]=Math.round(d.c2p(lt[y])-v);for(y=0;y<D;y++)ht[y]=ft(y,ct);for(H=0;H<P;H++)for(at=w[(it=pt(H,ut)).bin0],ot=w[it.bin1],y=0;y<D;y++,nt+=4)h(rt,nt,W=At(at,ot,ht[y],it))}else for(H=0;H<C;H++)for(Y=w[H],Z=j(H),y=0;y<D;y++)W=kt(Y[y],1),h(rt,nt=4*(Z*D+N(y)),W);var dt=V.createImageData(D,P);try{dt.data.set(rt)}catch(t){var gt=dt.data,vt=gt.length;for(H=0;H<vt;H++)gt[H]=rt[H]}V.putImageData(dt,0,0)}else{var mt=_.xgap,yt=_.ygap,xt=Math.floor(mt/2),bt=Math.floor(yt/2);for(H=0;H<C;H++)if(Y=w[H],Z.reverse(),Z[J]=j(H+1),Z[0]!==Z[1]&&void 0!==Z[0]&&void 0!==Z[1])for(q=[G=N(0),G],y=0;y<L;y++)q.reverse(),q[$]=N(y+1),q[0]!==q[1]&&void 0!==q[0]&&void 0!==q[1]&&(W=kt(Y[y],(q[1]-q[0])*(Z[1]-Z[0])),V.fillStyle="rgba("+W.join(",")+")",V.fillRect(q[0]+xt,Z[0]+bt,q[1]-q[0]-mt,Z[1]-Z[0]-yt))}Q=Math.round(Q/K),tt=Math.round(tt/K),et=Math.round(et/K);var _t=i("rgb("+Q+","+tt+","+et+")");t._hmpixcount=(t._hmpixcount||0)+K,t._hmlumcount=(t._hmlumcount||0)+K*_t.getLuminance();var wt=x.selectAll("image").data(e);wt.enter().append("svg:image").attr({xmlns:l.svg,preserveAspectRatio:"none"}),wt.attr({height:P,width:D,x:r,y:v,"xlink:href":B.toDataURL("image/png")})}function kt(t,e){if(void 0!==t){var r=U(t);return r[0]=Math.round(r[0]),r[1]=Math.round(r[1]),r[2]=Math.round(r[2]),K+=e,Q+=r[0]*e,tt+=r[1]*e,et+=r[2]*e,r}return[0,0,0,0]}function At(t,e,r,n){var i=t[r.bin0];if(void 0===i)return kt(void 0,1);var a,o=t[r.bin1],s=e[r.bin0],l=e[r.bin1],c=o-i||0,u=s-i||0;return a=void 0===o?void 0===l?0:void 0===s?2*(l-i):2*(2*l-s-i)/3:void 0===l?void 0===s?0:2*(2*i-o-s)/3:void 0===s?2*(2*l-o-i)/3:l+i-o-s,kt(i+r.frac*c+n.frac*(u+r.frac*a))}})}},{"../../components/colorscale":586,"../../constants/xmlns_namespaces":675,"../../lib":697,"../../registry":826,d3:151,tinycolor2:518}],957:[function(t,e,r){"use strict";var n=t("d3");e.exports=function(t){n.select(t).selectAll(".hm image").style("opacity",function(t){return t.trace.opacity})}},{d3:151}],958:[function(t,e,r){"use strict";e.exports=function(t,e,r){!1===r("zsmooth")&&(r("xgap"),r("ygap")),r("zhoverformat")}},{}],959:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("../../registry");function o(t,e){var r=e(t);return"scaled"===(r?e(t+"type","array"):"scaled")&&(e(t+"0"),e("d"+t)),r}e.exports=function(t,e,r,s,l,c){var u,h,f=r("z");if(l=l||"x",c=c||"y",void 0===f||!f.length)return 0;if(i.isArray1D(t.z)){u=r(l),h=r(c);var p=i.minRowLength(u),d=i.minRowLength(h);if(0===p||0===d)return 0;e._length=Math.min(p,d,f.length)}else{if(u=o(l,r),h=o(c,r),!function(t){for(var e,r=!0,a=!1,o=!1,s=0;s<t.length;s++){if(e=t[s],!i.isArrayOrTypedArray(e)){r=!1;break}e.length>0&&(a=!0);for(var l=0;l<e.length;l++)if(n(e[l])){o=!0;break}}return r&&a&&o}(f))return 0;r("transpose"),e._length=null}return a.getComponentMethod("calendars","handleTraceDefaults")(t,e,[l,c],s),!0}},{"../../lib":697,"../../registry":826,"fast-isnumeric":218}],960:[function(t,e,r){"use strict";for(var n=t("../heatmap/attributes"),i=t("../../components/colorscale/attributes"),a=t("../../components/colorbar/attributes"),o=t("../../lib/extend").extendFlat,s=t("../../plot_api/edit_types").overrideAll,l=["z","x","x0","dx","y","y0","dy","text","transpose","xtype","ytype"],c={},u=0;u<l.length;u++){var h=l[u];c[h]=n[h]}o(c,i("",{cLetter:"z",autoColorDflt:!1}),{colorbar:a}),e.exports=s(c,"calc","nested")},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../lib/extend":687,"../../plot_api/edit_types":728,"../heatmap/attributes":945}],961:[function(t,e,r){"use strict";var n=t("gl-heatmap2d"),i=t("../../plots/cartesian/axes"),a=t("../../lib/str2rgbarray");function o(t,e){this.scene=t,this.uid=e,this.type="heatmapgl",this.name="",this.hoverinfo="all",this.xData=[],this.yData=[],this.zData=[],this.textLabels=[],this.idToIndex=[],this.bounds=[0,0,0,0],this.options={z:[],x:[],y:[],shape:[0,0],colorLevels:[0],colorValues:[0,0,0,1]},this.heatmap=n(t.glplot,this.options),this.heatmap._trace=this}var s=o.prototype;s.handlePick=function(t){var e=this.options,r=e.shape,n=t.pointId,i=n%r[0],a=Math.floor(n/r[0]),o=n;return{trace:this,dataCoord:t.dataCoord,traceCoord:[e.x[i],e.y[a],e.z[o]],textLabel:this.textLabels[n],name:this.name,pointIndex:[a,i],hoverinfo:this.hoverinfo}},s.update=function(t,e){var r=e[0];this.index=t.index,this.name=t.name,this.hoverinfo=t.hoverinfo;var n=r.z;this.options.z=[].concat.apply([],n);var o=n[0].length,s=n.length;this.options.shape=[o,s],this.options.x=r.x,this.options.y=r.y;var l=function(t){for(var e=t.colorscale,r=t.zmin,n=t.zmax,i=e.length,o=new Array(i),s=new Array(4*i),l=0;l<i;l++){var c=e[l],u=a(c[1]);o[l]=r+c[0]*(n-r);for(var h=0;h<4;h++)s[4*l+h]=u[h]}return{colorLevels:o,colorValues:s}}(t);this.options.colorLevels=l.colorLevels,this.options.colorValues=l.colorValues,this.textLabels=[].concat.apply([],t.text),this.heatmap.update(this.options);var c=this.scene.xaxis,u=this.scene.yaxis;t._extremes[c._id]=i.findExtremes(c,r.x),t._extremes[u._id]=i.findExtremes(u,r.y)},s.dispose=function(){this.heatmap.dispose()},e.exports=function(t,e,r){var n=new o(t,e.uid);return n.update(e,r),n}},{"../../lib/str2rgbarray":720,"../../plots/cartesian/axes":745,"gl-heatmap2d":244}],962:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("../heatmap/defaults"),n.colorbar=t("../heatmap/colorbar"),n.calc=t("../heatmap/calc"),n.plot=t("./convert"),n.moduleType="trace",n.name="heatmapgl",n.basePlotModule=t("../../plots/gl2d"),n.categories=["gl","gl2d","2dMap"],n.meta={},e.exports=n},{"../../plots/gl2d":784,"../heatmap/calc":946,"../heatmap/colorbar":948,"../heatmap/defaults":950,"./attributes":960,"./convert":961}],963:[function(t,e,r){"use strict";var n=t("../bar/attributes"),i=t("../../components/fx/hovertemplate_attributes"),a=t("./bin_attributes"),o=t("./constants"),s=t("../../lib/extend").extendFlat;e.exports={x:{valType:"data_array",editType:"calc+clearAxisTypes"},y:{valType:"data_array",editType:"calc+clearAxisTypes"},text:s({},n.text,{}),hovertext:s({},n.hovertext,{}),orientation:n.orientation,histfunc:{valType:"enumerated",values:["count","sum","avg","min","max"],dflt:"count",editType:"calc"},histnorm:{valType:"enumerated",values:["","percent","probability","density","probability density"],dflt:"",editType:"calc"},cumulative:{enabled:{valType:"boolean",dflt:!1,editType:"calc"},direction:{valType:"enumerated",values:["increasing","decreasing"],dflt:"increasing",editType:"calc"},currentbin:{valType:"enumerated",values:["include","exclude","half"],dflt:"include",editType:"calc"},editType:"calc"},nbinsx:{valType:"integer",min:0,dflt:0,editType:"calc"},xbins:a("x",!0),nbinsy:{valType:"integer",min:0,dflt:0,editType:"calc"},ybins:a("y",!0),autobinx:{valType:"boolean",dflt:null,editType:"calc"},autobiny:{valType:"boolean",dflt:null,editType:"calc"},hovertemplate:i({},{keys:o.eventDataKeys}),marker:n.marker,offsetgroup:n.offsetgroup,alignmentgroup:n.alignmentgroup,selected:n.selected,unselected:n.unselected,_deprecated:{bardir:n._deprecated.bardir}}},{"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../bar/attributes":836,"./bin_attributes":965,"./constants":969}],964:[function(t,e,r){"use strict";e.exports=function(t,e){for(var r=t.length,n=0,i=0;i<r;i++)e[i]?(t[i]/=e[i],n+=t[i]):t[i]=null;return n}},{}],965:[function(t,e,r){"use strict";e.exports=function(t,e){return{start:{valType:"any",editType:"calc"},end:{valType:"any",editType:"calc"},size:{valType:"any",editType:"calc"},editType:"calc"}}},{}],966:[function(t,e,r){"use strict";var n=t("fast-isnumeric");e.exports={count:function(t,e,r){return r[t]++,1},sum:function(t,e,r,i){var a=i[e];return n(a)?(a=Number(a),r[t]+=a,a):0},avg:function(t,e,r,i,a){var o=i[e];return n(o)&&(o=Number(o),r[t]+=o,a[t]++),0},min:function(t,e,r,i){var a=i[e];if(n(a)){if(a=Number(a),!n(r[t]))return r[t]=a,a;if(r[t]>a){var o=a-r[t];return r[t]=a,o}}return 0},max:function(t,e,r,i){var a=i[e];if(n(a)){if(a=Number(a),!n(r[t]))return r[t]=a,a;if(r[t]<a){var o=a-r[t];return r[t]=a,o}}return 0}}},{"fast-isnumeric":218}],967:[function(t,e,r){"use strict";var n=t("../../constants/numerical"),i=n.ONEAVGYEAR,a=n.ONEAVGMONTH,o=n.ONEDAY,s=n.ONEHOUR,l=n.ONEMIN,c=n.ONESEC,u=t("../../plots/cartesian/axes").tickIncrement;function h(t,e,r,n){if(t*e<=0)return 1/0;for(var i=Math.abs(e-t),a="date"===r.type,o=f(i,a),s=0;s<10;s++){var l=f(80*o,a);if(o===l)break;if(!p(l,t,e,a,r,n))break;o=l}return o}function f(t,e){return e&&t>c?t>o?t>1.1*i?i:t>1.1*a?a:o:t>s?s:t>l?l:c:Math.pow(10,Math.floor(Math.log(t)/Math.LN10))}function p(t,e,r,n,a,s){if(n&&t>o){var l=d(e,a,s),c=d(r,a,s),u=t===i?0:1;return l[u]!==c[u]}return Math.floor(r/t)-Math.floor(e/t)>.1}function d(t,e,r){var n=e.c2d(t,i,r).split("-");return""===n[0]&&(n.unshift(),n[0]="-"+n[0]),n}e.exports=function(t,e,r,n,a){var s,l,c=-1.1*e,f=-.1*e,p=t-f,d=r[0],g=r[1],v=Math.min(h(d+f,d+p,n,a),h(g+f,g+p,n,a)),m=Math.min(h(d+c,d+f,n,a),h(g+c,g+f,n,a));if(v>m&&m<Math.abs(g-d)/4e3?(s=v,l=!1):(s=Math.min(v,m),l=!0),"date"===n.type&&s>o){var y=s===i?1:6,x=s===i?"M12":"M1";return function(e,r){var o=n.c2d(e,i,a),s=o.indexOf("-",y);s>0&&(o=o.substr(0,s));var c=n.d2c(o,0,a);if(c<e){var h=u(c,x,!1,a);(c+h)/2<e+t&&(c=h)}return r&&l?u(c,x,!0,a):c}}return function(e,r){var n=s*Math.round(e/s);return n+s/10<e&&n+.9*s<e+t&&(n+=s),r&&l&&(n-=s),n}}},{"../../constants/numerical":674,"../../plots/cartesian/axes":745}],968:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("../../plots/cartesian/axes"),o=t("../bar/arrays_to_calcdata"),s=t("./bin_functions"),l=t("./norm_functions"),c=t("./average"),u=t("./bin_label_vals");function h(t,e,r,o,s){var l,c,u,f,p,d,g,v=o+"bins",m=t._fullLayout,y="overlay"===m.barmode,x="date"===r.type?function(t){return t||0===t?i.cleanDate(t,null,r.calendar):null}:function(t){return n(t)?Number(t):null};function b(t,e,r){e[t+"Found"]?(e[t]=x(e[t]),null===e[t]&&(e[t]=r[t])):(d[t]=e[t]=r[t],i.nestedProperty(c[0],v+"."+t).set(r[t]))}var _=m._histogramBinOpts[e._groupName];if(e._autoBinFinished)delete e._autoBinFinished;else{c=_.traces;var w=_.sizeFound,k=[];d=c[0]._autoBin={};var A=!0;for(l=0;l<c.length;l++)(u=c[l]).visible&&(p=u._pos0=r.makeCalcdata(u,o),k=i.concat(k,p),delete u._autoBinFinished,!0===e.visible&&(A?A=!1:(delete u._autoBin,u._autoBinFinished=1)));f=c[0][o+"calendar"];var M=a.autoBin(k,r,_.nbins,!1,f,w&&_.size);if(y&&0===M._dataSpan&&"category"!==r.type&&"multicategory"!==r.type){if(s)return[M,p,!0];M=function(t,e,r,n,a){var o,s,l=function(t,e){for(var r=e.xaxis,n=e.yaxis,i=e.orientation,a=[],o=t._fullData,s=0;s<o.length;s++){var l=o[s];"histogram"===l.type&&!0===l.visible&&l.orientation===i&&l.xaxis===r&&l.yaxis===n&&a.push(l)}return a}(t,e),c=!1,u=1/0,f=[e];for(o=0;o<l.length;o++)if((s=l[o])===e)c=!0;else if(c){var p=h(t,s,r,n,!0),d=p[0],g=p[2];s._autoBinFinished=1,s._pos0=p[1],g?f.push(s):u=Math.min(u,d.size)}else u=Math.min(u,s[a].size);var v=new Array(f.length);for(o=0;o<f.length;o++)for(var m=f[o]._pos0,y=0;y<m.length;y++)if(void 0!==m[y]){v[o]=m[y];break}isFinite(u)||(u=i.distinctVals(v).minDiff);for(o=0;o<f.length;o++){var x=(s=f[o])[n+"calendar"];s._input[a]=s[a]={start:r.c2r(v[o]-u/2,0,x),end:r.c2r(v[o]+u/2,0,x),size:u}}return e[a]}(t,e,r,o,v)}(g=u.cumulative).enabled&&"include"!==g.currentbin&&("decreasing"===g.direction?M.start=r.c2r(a.tickIncrement(r.r2c(M.start,0,f),M.size,!0,f)):M.end=r.c2r(a.tickIncrement(r.r2c(M.end,0,f),M.size,!1,f))),_.size=M.size,w||(d.size=M.size,i.nestedProperty(c[0],v+".size").set(M.size)),b("start",_,M),b("end",_,M)}p=e._pos0,delete e._pos0;var T=e._input[v]||{},S=i.extendFlat({},_),E=_.start,C=r.r2l(T.start),L=void 0!==C;if((_.startFound||L)&&C!==r.r2l(E)){var z=L?C:i.aggNums(Math.min,null,p),O={type:"category"===r.type||"multicategory"===r.type?"linear":r.type,r2l:r.r2l,dtick:_.size,tick0:E,calendar:f,range:[z,a.tickIncrement(z,_.size,!1,f)].map(r.l2r)},I=a.tickFirst(O);I>r.r2l(z)&&(I=a.tickIncrement(I,_.size,!0,f)),S.start=r.l2r(I),L||i.nestedProperty(e,v+".start").set(S.start)}var D=_.end,P=r.r2l(T.end),R=void 0!==P;if((_.endFound||R)&&P!==r.r2l(D)){var F=R?P:i.aggNums(Math.max,null,p);S.end=r.l2r(F),R||i.nestedProperty(e,v+".start").set(S.end)}var B="autobin"+o;return!1===e._input[B]&&(e._input[v]=i.extendFlat({},e[v]||{}),delete e._input[B],delete e[B]),[S,p]}e.exports=function(t,e){if(!0===e.visible){var r,f,p,d,g=[],v=[],m=a.getFromId(t,"h"===e.orientation?e.yaxis||"y":e.xaxis||"x"),y="h"===e.orientation?"y":"x",x={x:"y",y:"x"}[y],b=e[y+"calendar"],_=e.cumulative,w=h(t,e,m,y),k=w[0],A=w[1],M="string"==typeof k.size,T=[],S=M?T:k,E=[],C=[],L=[],z=0,O=e.histnorm,I=e.histfunc,D=-1!==O.indexOf("density");_.enabled&&D&&(O=O.replace(/ ?density$/,""),D=!1);var P,R="max"===I||"min"===I?null:0,F=s.count,B=l[O],N=!1,j=function(t){return m.r2c(t,0,b)};for(i.isArrayOrTypedArray(e[x])&&"count"!==I&&(P=e[x],N="avg"===I,F=s[I]),r=j(k.start),p=j(k.end)+(r-a.tickIncrement(r,k.size,!1,b))/1e6;r<p&&g.length<1e6&&(f=a.tickIncrement(r,k.size,!1,b),g.push((r+f)/2),v.push(R),L.push([]),T.push(r),D&&E.push(1/(f-r)),N&&C.push(0),!(f<=r));)r=f;T.push(r),M||"date"!==m.type||(S={start:j(S.start),end:j(S.end),size:S.size});var V,U=v.length,q=!0,H=1/0,G=1/0,Y={};for(r=0;r<A.length;r++){var W=A[r];(d=i.findBin(W,S))>=0&&d<U&&(z+=F(d,r,v,P,C),q&&L[d].length&&W!==A[L[d][0]]&&(q=!1),L[d].push(r),Y[r]=d,H=Math.min(H,W-T[d]),G=Math.min(G,T[d+1]-W))}q||(V=u(H,G,T,m,b)),N&&(z=c(v,C)),B&&B(v,z,E),_.enabled&&function(t,e,r){var n,i,a;function o(e){a=t[e],t[e]/=2}function s(e){i=t[e],t[e]=a+i/2,a+=i}if("half"===r)if("increasing"===e)for(o(0),n=1;n<t.length;n++)s(n);else for(o(t.length-1),n=t.length-2;n>=0;n--)s(n);else if("increasing"===e){for(n=1;n<t.length;n++)t[n]+=t[n-1];"exclude"===r&&(t.unshift(0),t.pop())}else{for(n=t.length-2;n>=0;n--)t[n]+=t[n+1];"exclude"===r&&(t.push(0),t.shift())}}(v,_.direction,_.currentbin);var X=Math.min(g.length,v.length),Z=[],$=0,J=X-1;for(r=0;r<X;r++)if(v[r]){$=r;break}for(r=X-1;r>=$;r--)if(v[r]){J=r;break}for(r=$;r<=J;r++)if(n(g[r])&&n(v[r])){var K={p:g[r],s:v[r],b:0};_.enabled||(K.pts=L[r],q?K.ph0=K.ph1=L[r].length?A[L[r][0]]:g[r]:(K.ph0=V(T[r]),K.ph1=V(T[r+1],!0))),Z.push(K)}return 1===Z.length&&(Z[0].width1=a.tickIncrement(Z[0].p,k.size,!1,b)-Z[0].p),o(Z,e),i.isArrayOrTypedArray(e.selectedpoints)&&i.tagSelected(Z,e,Y),Z}}},{"../../lib":697,"../../plots/cartesian/axes":745,"../bar/arrays_to_calcdata":835,"./average":964,"./bin_functions":966,"./bin_label_vals":967,"./norm_functions":975,"fast-isnumeric":218}],969:[function(t,e,r){"use strict";e.exports={eventDataKeys:["binNumber"]}},{}],970:[function(t,e,r){"use strict";var n=t("../../lib"),i=n.nestedProperty,a=t("../bar/defaults").handleGroupingDefaults,o=t("../../plots/cartesian/axis_ids").getAxisGroup,s=t("./attributes"),l={x:[{aStr:"xbins.start",name:"start"},{aStr:"xbins.end",name:"end"},{aStr:"xbins.size",name:"size"},{aStr:"nbinsx",name:"nbins"}],y:[{aStr:"ybins.start",name:"start"},{aStr:"ybins.end",name:"end"},{aStr:"ybins.size",name:"size"},{aStr:"nbinsy",name:"nbins"}]};e.exports=function(t,e){var r,c,u,h,f,p,d,g=e._histogramBinOpts={},v="overlay"===e.barmode;function m(t){return n.coerce(u._input,u,s,t)}for(r=0;r<t.length;r++)"histogram"===(u=t[r]).type&&(delete u._autoBinFinished,f="v"===u.orientation?"x":"y",(d=g[p=u._groupName=v?u.uid:o(e,u.xaxis)+o(e,u.yaxis)+f])?d.traces.push(u):d=g[p]={traces:[u],direction:f},a(u._input,u,e,m));for(p in g){f=(d=g[p]).direction;var y=l[f];for(c=0;c<y.length;c++){var x=y[c],b=x.name;if("nbins"!==b||!d.sizeFound){var _=x.aStr;for(r=0;r<d.traces.length;r++){if(h=(u=d.traces[r])._input,void 0!==i(h,_).get()){d[b]=m(_),d[b+"Found"]=!0;break}var w=u._autoBin;w&&w[b]&&i(u,_).set(w[b])}if("start"===b||"end"===b)for(;r<d.traces.length;r++)m(_,((u=d.traces[r])._autoBin||{})[b]);"nbins"!==b||d.sizeFound||d.nbinsFound||(u=d.traces[0],d[b]=m(_))}}}}},{"../../lib":697,"../../plots/cartesian/axis_ids":748,"../bar/defaults":840,"./attributes":963}],971:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("../../lib"),a=t("../../components/color"),o=t("../bar/style_defaults"),s=t("./attributes");e.exports=function(t,e,r,l){function c(r,n){return i.coerce(t,e,s,r,n)}var u=c("x"),h=c("y");c("cumulative.enabled")&&(c("cumulative.direction"),c("cumulative.currentbin")),c("text"),c("hovertext"),c("hovertemplate");var f=c("orientation",h&&!u?"h":"v"),p="v"===f?"x":"y",d="v"===f?"y":"x",g=u&&h?Math.min(i.minRowLength(u)&&i.minRowLength(h)):i.minRowLength(e[p]||[]);if(g){e._length=g,n.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y"],l),e[d]&&c("histfunc"),c("histnorm"),c("autobin"+p),o(t,e,c,r,l),i.coerceSelectionMarkerOpacity(e,c);var v=(e.marker.line||{}).color,m=n.getComponentMethod("errorbars","supplyDefaults");m(t,e,v||a.defaultLine,{axis:"y"}),m(t,e,v||a.defaultLine,{axis:"x",inherit:"y"})}else e.visible=!1}},{"../../components/color":574,"../../lib":697,"../../registry":826,"../bar/style_defaults":850,"./attributes":963}],972:[function(t,e,r){"use strict";e.exports=function(t,e,r,n,i){if(t.x="xVal"in e?e.xVal:e.x,t.y="yVal"in e?e.yVal:e.y,"zLabelVal"in e&&(t.z=e.zLabelVal),e.xa&&(t.xaxis=e.xa),e.ya&&(t.yaxis=e.ya),!(r.cumulative||{}).enabled){var a,o=Array.isArray(i)?n[0].pts[i[0]][i[1]]:n[i].pts;if(t.pointNumbers=o,t.binNumber=t.pointNumber,delete t.pointNumber,delete t.pointIndex,r._indexToPoints){a=[];for(var s=0;s<o.length;s++)a=a.concat(r._indexToPoints[o[s]])}else a=o;t.pointIndices=a}return t}},{}],973:[function(t,e,r){"use strict";var n=t("../bar/hover").hoverPoints,i=t("../../plots/cartesian/axes").hoverLabelText;e.exports=function(t,e,r,a){var o=n(t,e,r,a);if(o){var s=(t=o[0]).cd[t.index],l=t.cd[0].trace;if(!l.cumulative.enabled){var c="h"===l.orientation?"y":"x";t[c+"Label"]=i(t[c+"a"],s.ph0,s.ph1)}return l.hovermplate&&(t.hovertemplate=l.hovertemplate),o}}},{"../../plots/cartesian/axes":745,"../bar/hover":842}],974:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.layoutAttributes=t("../bar/layout_attributes"),n.supplyDefaults=t("./defaults"),n.crossTraceDefaults=t("./cross_trace_defaults"),n.supplyLayoutDefaults=t("../bar/layout_defaults"),n.calc=t("./calc"),n.crossTraceCalc=t("../bar/cross_trace_calc").crossTraceCalc,n.plot=t("../bar/plot"),n.layerName="barlayer",n.style=t("../bar/style").style,n.styleOnSelect=t("../bar/style").styleOnSelect,n.colorbar=t("../scatter/marker_colorbar"),n.hoverPoints=t("./hover"),n.selectPoints=t("../bar/select"),n.eventData=t("./event_data"),n.moduleType="trace",n.name="histogram",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","svg","bar","histogram","oriented","errorBarsOK","showLegend"],n.meta={},e.exports=n},{"../../plots/cartesian":756,"../bar/cross_trace_calc":839,"../bar/layout_attributes":844,"../bar/layout_defaults":845,"../bar/plot":846,"../bar/select":847,"../bar/style":849,"../scatter/marker_colorbar":1066,"./attributes":963,"./calc":968,"./cross_trace_defaults":970,"./defaults":971,"./event_data":972,"./hover":973}],975:[function(t,e,r){"use strict";e.exports={percent:function(t,e){for(var r=t.length,n=100/e,i=0;i<r;i++)t[i]*=n},probability:function(t,e){for(var r=t.length,n=0;n<r;n++)t[n]/=e},density:function(t,e,r,n){var i=t.length;n=n||1;for(var a=0;a<i;a++)t[a]*=r[a]*n},"probability density":function(t,e,r,n){var i=t.length;n&&(e/=n);for(var a=0;a<i;a++)t[a]*=r[a]/e}}},{}],976:[function(t,e,r){"use strict";var n=t("../histogram/attributes"),i=t("../histogram/bin_attributes"),a=t("../heatmap/attributes"),o=t("../../components/fx/hovertemplate_attributes"),s=t("../../components/colorscale/attributes"),l=t("../../components/colorbar/attributes"),c=t("../../lib/extend").extendFlat;e.exports=c({x:n.x,y:n.y,z:{valType:"data_array",editType:"calc"},marker:{color:{valType:"data_array",editType:"calc"},editType:"calc"},histnorm:n.histnorm,histfunc:n.histfunc,nbinsx:n.nbinsx,xbins:i("x"),nbinsy:n.nbinsy,ybins:i("y"),autobinx:n.autobinx,autobiny:n.autobiny,xgap:a.xgap,ygap:a.ygap,zsmooth:a.zsmooth,zhoverformat:a.zhoverformat,hovertemplate:o({},{keys:"z"})},s("",{cLetter:"z",autoColorDflt:!1}),{colorbar:l})},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../heatmap/attributes":945,"../histogram/attributes":963,"../histogram/bin_attributes":965}],977:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/cartesian/axes"),a=t("../histogram/bin_functions"),o=t("../histogram/norm_functions"),s=t("../histogram/average"),l=t("../histogram/bin_label_vals");function c(t,e,r,a,o,s,l){var c=e+"bins",u=t[c];u||(u=t[c]={});var h=t._input[c]||{},f=t._autoBin={};h.size||delete u.size,void 0===h.start&&delete u.start,void 0===h.end&&delete u.end;var p=!u.size,d=void 0===u.start,g=void 0===u.end;if(p||d||g){var v=i.autoBin(r,a,t["nbins"+e],"2d",l,u.size);"histogram2dcontour"===t.type&&(d&&(v.start=s(i.tickIncrement(o(v.start),v.size,!0,l))),g&&(v.end=s(i.tickIncrement(o(v.end),v.size,!1,l)))),p&&(u.size=f.size=v.size),d&&(u.start=f.start=v.start),g&&(u.end=f.end=v.end)}var m="autobin"+e;!1===t._input[m]&&(t._input[c]=n.extendFlat({},u),delete t._input[m],delete t[m])}function u(t,e,r,n){var i,a=new Array(t);if(n)for(i=0;i<t;i++)a[i]=1/(e[i+1]-e[i]);else{var o=1/r;for(i=0;i<t;i++)a[i]=o}return a}function h(t,e){return{start:t(e.start),end:t(e.end),size:e.size}}function f(t,e,r,n,i,a){var o,s=t.length-1,c=new Array(s);if(e)for(o=0;o<s;o++)c[o]=[e[o],e[o]];else{var u=l(r,n,t,i,a);for(o=0;o<s;o++)c[o]=[u(t[o]),u(t[o+1],!0)]}return c}e.exports=function(t,e){var r,l,p,d,g=i.getFromId(t,e.xaxis||"x"),v=e.x?g.makeCalcdata(e,"x"):[],m=i.getFromId(t,e.yaxis||"y"),y=e.y?m.makeCalcdata(e,"y"):[],x=e.xcalendar,b=e.ycalendar,_=function(t){return g.r2c(t,0,x)},w=function(t){return m.r2c(t,0,b)},k=function(t){return g.c2r(t,0,x)},A=function(t){return m.c2r(t,0,b)},M=e._length;v.length>M&&v.splice(M,v.length-M),y.length>M&&y.splice(M,y.length-M),c(e,"x",v,g,_,k,x),c(e,"y",y,m,w,A,b);var T=[],S=[],E=[],C="string"==typeof e.xbins.size,L="string"==typeof e.ybins.size,z=[],O=[],I=C?z:e.xbins,D=L?O:e.ybins,P=0,R=[],F=[],B=e.histnorm,N=e.histfunc,j=-1!==B.indexOf("density"),V="max"===N||"min"===N?null:0,U=a.count,q=o[B],H=!1,G=[],Y=[],W="z"in e?e.z:"marker"in e&&Array.isArray(e.marker.color)?e.marker.color:"";W&&"count"!==N&&(H="avg"===N,U=a[N]);var X=e.xbins,Z=_(X.start),$=_(X.end)+(Z-i.tickIncrement(Z,X.size,!1,x))/1e6;for(r=Z;r<$;r=i.tickIncrement(r,X.size,!1,x))S.push(V),z.push(r),H&&E.push(0);z.push(r);var J=S.length,K=_(e.xbins.start),Q=(r-K)/J,tt=k(K+Q/2);for(Z=w((X=e.ybins).start),$=w(X.end)+(Z-i.tickIncrement(Z,X.size,!1,b))/1e6,r=Z;r<$;r=i.tickIncrement(r,X.size,!1,b)){T.push(S.slice()),O.push(r);var et=new Array(J);for(l=0;l<J;l++)et[l]=[];F.push(et),H&&R.push(E.slice())}O.push(r);var rt=T.length,nt=w(e.ybins.start),it=(r-nt)/rt,at=A(nt+it/2);j&&(G=u(S.length,I,Q,C),Y=u(T.length,D,it,L)),C||"date"!==g.type||(I=h(_,I)),L||"date"!==m.type||(D=h(w,D));var ot=!0,st=!0,lt=new Array(J),ct=new Array(rt),ut=1/0,ht=1/0,ft=1/0,pt=1/0;for(r=0;r<M;r++){var dt=v[r],gt=y[r];p=n.findBin(dt,I),d=n.findBin(gt,D),p>=0&&p<J&&d>=0&&d<rt&&(P+=U(p,r,T[d],W,R[d]),F[d][p].push(r),ot&&(void 0===lt[p]?lt[p]=dt:lt[p]!==dt&&(ot=!1)),st&&(void 0===ct[p]?ct[p]=gt:ct[p]!==gt&&(st=!1)),ut=Math.min(ut,dt-z[p]),ht=Math.min(ht,z[p+1]-dt),ft=Math.min(ft,gt-O[d]),pt=Math.min(pt,O[d+1]-gt))}if(H)for(d=0;d<rt;d++)P+=s(T[d],R[d]);if(q)for(d=0;d<rt;d++)q(T[d],P,G,Y[d]);return{x:v,xRanges:f(z,ot&&lt,ut,ht,g,x),x0:tt,dx:Q,y:y,yRanges:f(O,st&&ct,ft,pt,m,b),y0:at,dy:it,z:T,pts:F}}},{"../../lib":697,"../../plots/cartesian/axes":745,"../histogram/average":964,"../histogram/bin_functions":966,"../histogram/bin_label_vals":967,"../histogram/norm_functions":975}],978:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../constants/numerical").BADNUM,a=t("../../plots/cartesian/axis_ids"),o=t("../../lib"),s=t("./attributes"),l=["x","y"];function c(t,e,r,s){var l=r[a.id2name(t[e+"axis"])].type,c=e+"bins",u=t[c],h=t[e+"calendar"];u||(u=t[c]={});var f="date"===l?function(t,e){return t||0===t?o.cleanDate(t,i,h):e}:function(t,e){return n(t)?Number(t):e};u.start=f(u.start,s.start),u.end=f(u.end,s.end);var p=s.size,d=u.size;if(n(d))u.size=d>0?Number(d):p;else if("string"!=typeof d)u.size=p;else{var g=d.charAt(0),v=d.substr(1);((v=n(v)?Number(v):0)<=0||"date"!==l||"M"!==g||v!==Math.round(v))&&(u.size=p)}}e.exports=function(t,e){var r,n,i,a;function u(t){return o.coerce(i._input,i,s,t)}for(r=0;r<t.length;r++){var h=(i=t[r]).type;if("histogram2d"===h||"histogram2dcontour"===h)for(n=0;n<l.length;n++){var f=(a=l[n])+"bins",p=(i._autoBin||{})[a]||{};u(f+".start",p.start),u(f+".end",p.end),u(f+".size",p.size),c(i,a,e,p),(i[f]||{}).size||u("nbins"+a)}}}},{"../../constants/numerical":674,"../../lib":697,"../../plots/cartesian/axis_ids":748,"./attributes":976,"fast-isnumeric":218}],979:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./sample_defaults"),a=t("../heatmap/style_defaults"),o=t("../../components/colorscale/defaults"),s=t("./attributes");e.exports=function(t,e,r,l){function c(r,i){return n.coerce(t,e,s,r,i)}i(t,e,c,l),!1!==e.visible&&(a(t,e,c,l),o(t,e,l,c,{prefix:"",cLetter:"z"}),c("hovertemplate"))}},{"../../components/colorscale/defaults":584,"../../lib":697,"../heatmap/style_defaults":958,"./attributes":976,"./sample_defaults":982}],980:[function(t,e,r){"use strict";var n=t("../heatmap/hover"),i=t("../../plots/cartesian/axes").hoverLabelText;e.exports=function(t,e,r,a,o,s){var l=n(t,e,r,a,o,s);if(l){var c=(t=l[0]).index,u=c[0],h=c[1],f=t.cd[0],p=f.xRanges[h],d=f.yRanges[u];return t.xLabel=i(t.xa,p[0],p[1]),t.yLabel=i(t.ya,d[0],d[1]),l}}},{"../../plots/cartesian/axes":745,"../heatmap/hover":952}],981:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.crossTraceDefaults=t("./cross_trace_defaults"),n.calc=t("../heatmap/calc"),n.plot=t("../heatmap/plot"),n.layerName="heatmaplayer",n.colorbar=t("../heatmap/colorbar"),n.style=t("../heatmap/style"),n.hoverPoints=t("./hover"),n.eventData=t("../histogram/event_data"),n.moduleType="trace",n.name="histogram2d",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","svg","2dMap","histogram"],n.meta={},e.exports=n},{"../../plots/cartesian":756,"../heatmap/calc":946,"../heatmap/colorbar":948,"../heatmap/plot":956,"../heatmap/style":957,"../histogram/event_data":972,"./attributes":976,"./cross_trace_defaults":978,"./defaults":979,"./hover":980}],982:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("../../lib");e.exports=function(t,e,r,a){var o=r("x"),s=r("y"),l=i.minRowLength(o),c=i.minRowLength(s);l&&c?(e._length=Math.min(l,c),n.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y"],a),(r("z")||r("marker.color"))&&r("histfunc"),r("histnorm"),r("autobinx"),r("autobiny")):e.visible=!1}},{"../../lib":697,"../../registry":826}],983:[function(t,e,r){"use strict";var n=t("../histogram2d/attributes"),i=t("../contour/attributes"),a=t("../../components/colorscale/attributes"),o=t("../../components/colorbar/attributes"),s=t("../../lib/extend").extendFlat;e.exports=s({x:n.x,y:n.y,z:n.z,marker:n.marker,histnorm:n.histnorm,histfunc:n.histfunc,nbinsx:n.nbinsx,xbins:n.xbins,nbinsy:n.nbinsy,ybins:n.ybins,autobinx:n.autobinx,autobiny:n.autobiny,autocontour:i.autocontour,ncontours:i.ncontours,contours:i.contours,line:i.line,zhoverformat:n.zhoverformat,hovertemplate:n.hovertemplate},a("",{cLetter:"z",editTypeOverride:"calc"}),{colorbar:o})},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../lib/extend":687,"../contour/attributes":916,"../histogram2d/attributes":976}],984:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../histogram2d/sample_defaults"),a=t("../contour/contours_defaults"),o=t("../contour/style_defaults"),s=t("./attributes");e.exports=function(t,e,r,l){function c(r,i){return n.coerce(t,e,s,r,i)}i(t,e,c,l),!1!==e.visible&&(a(t,e,c,function(r){return n.coerce2(t,e,s,r)}),o(t,e,c,l),c("hovertemplate"))}},{"../../lib":697,"../contour/contours_defaults":923,"../contour/style_defaults":937,"../histogram2d/sample_defaults":982,"./attributes":983}],985:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.crossTraceDefaults=t("../histogram2d/cross_trace_defaults"),n.calc=t("../contour/calc"),n.plot=t("../contour/plot").plot,n.layerName="contourlayer",n.style=t("../contour/style"),n.colorbar=t("../contour/colorbar"),n.hoverPoints=t("../contour/hover"),n.moduleType="trace",n.name="histogram2dcontour",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","svg","2dMap","contour","histogram","showLegend"],n.meta={},e.exports=n},{"../../plots/cartesian":756,"../contour/calc":917,"../contour/colorbar":919,"../contour/hover":929,"../contour/plot":934,"../contour/style":936,"../histogram2d/cross_trace_defaults":978,"./attributes":983,"./defaults":984}],986:[function(t,e,r){"use strict";var n=t("../../components/colorscale/attributes"),i=t("../../components/colorbar/attributes"),a=t("../../components/fx/hovertemplate_attributes"),o=t("../mesh3d/attributes"),s=t("../../plots/attributes"),l=t("../../lib/extend").extendFlat,c=t("../../plot_api/edit_types").overrideAll;var u=e.exports=c(l({x:{valType:"data_array"},y:{valType:"data_array"},z:{valType:"data_array"},value:{valType:"data_array"},isomin:{valType:"number"},isomax:{valType:"number"},surface:{show:{valType:"boolean",dflt:!0},count:{valType:"integer",dflt:2,min:1},fill:{valType:"number",min:0,max:1,dflt:1},pattern:{valType:"flaglist",flags:["A","B","C","D","E"],extras:["all","odd","even"],dflt:"all"}},spaceframe:{show:{valType:"boolean",dflt:!1},fill:{valType:"number",min:0,max:1,dflt:.15}},slices:{x:{show:{valType:"boolean",dflt:!1},locations:{valType:"data_array",dflt:[]},fill:{valType:"number",min:0,max:1,dflt:1}},y:{show:{valType:"boolean",dflt:!1},locations:{valType:"data_array",dflt:[]},fill:{valType:"number",min:0,max:1,dflt:1}},z:{show:{valType:"boolean",dflt:!1},locations:{valType:"data_array",dflt:[]},fill:{valType:"number",min:0,max:1,dflt:1}}},caps:{x:{show:{valType:"boolean",dflt:!0},fill:{valType:"number",min:0,max:1,dflt:1}},y:{show:{valType:"boolean",dflt:!0},fill:{valType:"number",min:0,max:1,dflt:1}},z:{show:{valType:"boolean",dflt:!0},fill:{valType:"number",min:0,max:1,dflt:1}}},text:{valType:"string",dflt:"",arrayOk:!0},hovertext:{valType:"string",dflt:"",arrayOk:!0},hovertemplate:a()},n("",{colorAttr:"`value`",showScaleDflt:!0,editTypeOverride:"calc"}),{colorbar:i,opacity:o.opacity,lightposition:o.lightposition,lighting:o.lighting,flatshading:o.flatshading,contour:o.contour,hoverinfo:l({},s.hoverinfo)}),"calc","nested");u.flatshading.dflt=!0,u.lighting.facenormalsepsilon.dflt=0,u.x.editType=u.y.editType=u.z.editType=u.value.editType="calc+clearAxisTypes",u.transforms=void 0},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plot_api/edit_types":728,"../../plots/attributes":742,"../mesh3d/attributes":991}],987:[function(t,e,r){"use strict";var n=t("../../components/colorscale/calc");e.exports=function(t,e){e._len=Math.min(e.x.length,e.y.length,e.z.length,e.value.length);for(var r=1/0,i=-1/0,a=e.value.length,o=0;o<a;o++){var s=e.value[o];r=Math.min(r,s),i=Math.max(i,s)}e._minValues=r,e._maxValues=i,e._vMin=void 0===e.isomin||null===e.isomin?r:e.isomin,e._vMax=void 0===e.isomax||null===e.isomin?i:e.isomax,n(t,e,{vals:[e._vMin,e._vMax],containerStr:"",cLetter:"c"})}},{"../../components/colorscale/calc":582}],988:[function(t,e,r){"use strict";var n=t("gl-mesh3d"),i=t("../../lib/gl_format_color").parseColorScale,a=t("../../lib/str2rgbarray"),o=t("../../plots/gl3d/zip3"),s=t("../../lib");function l(t){return s.distinctVals(t).vals}function c(t,e,r){this.scene=t,this.uid=r,this.mesh=e,this.name="",this.data=null,this.showContour=!1}var u=c.prototype;function h(t,e){for(var r=e.length-1;r>0;r--){var n=Math.min(e[r],e[r-1]),i=Math.max(e[r],e[r-1]);if(i>n&&n<t&&t<=i)return{id:r,distRatio:(i-t)/(i-n)}}return{id:0,distRatio:0}}u.handlePick=function(t){if(t.object===this.mesh){var e=t.data.index,r=this.data._x[e],n=this.data._y[e],i=this.data._z[e],a=this.data._Ys.length,o=this.data._Zs.length,s=h(r,this.data._Xs).id,l=h(n,this.data._Ys).id,c=h(i,this.data._Zs).id,u=t.index=c+o*l+o*a*s;t.traceCoordinate=[this.data._x[u],this.data._y[u],this.data._z[u],this.data.value[u]];var f=this.data.hovertext||this.data.text;return Array.isArray(f)&&void 0!==f[u]?t.textLabel=f[u]:f&&(t.textLabel=f),!0}},u.update=function(t){var e=this.scene,r=e.fullSceneLayout;function n(t,e,r,n){return e.map(function(e){return t.d2l(e,0,n)*r})}this.data=function(t){t._i=[],t._j=[],t._k=[];var e,r,n=t.surface.show,i=t.spaceframe.show,a=t.surface.fill,o=t.spaceframe.fill,s=!1,c=!1,u=0,f=l(t.x.slice(0,t._len)),p=l(t.y.slice(0,t._len)),d=l(t.z.slice(0,t._len)),g=f.length,v=p.length,m=d.length;function y(t,e,r){return r+m*e+m*v*t}var x,b,_,w,k,A=t._minValues,M=t._maxValues,T=t._vMin,S=t._vMax;function E(t,e,n){for(var i=w.length,a=r;a<i;a++)if(t===x[a]&&e===b[a]&&n===_[a])return a;return-1}function C(){r=e}function L(){x=[],b=[],_=[],w=[],e=0,C()}function z(t,r,n,i){return x.push(t),b.push(r),_.push(n),w.push(i),++e-1}function O(e,r,n){return t._i.push(e),t._j.push(r),t._k.push(n),++u-1}function I(t,e,r){for(var n=[],i=0;i<t.length;i++)n[i]=t[i]*(1-r)+r*e[i];return n}function D(t){k=t}function P(t,e){return"all"===t||null===t||t.indexOf(e)>-1}function R(t,e){return null===t?e:t}function F(t,e,r){C();var n=[e],i=[r];if(k>=1)n=[e],i=[r];else if(k>0){var a=function(t,e){var r=t[0],n=t[1],i=t[2],a=function(t,e,r){for(var n=[],i=0;i<t.length;i++)n[i]=(t[i]+e[i]+r[i])/3;return n}(r,n,i),o=Math.sqrt(1-k),s=I(a,r,o),l=I(a,n,o),c=I(a,i,o),u=e[0],h=e[1],f=e[2];return{xyzv:[[r,n,l],[l,s,r],[n,i,c],[c,l,n],[i,r,s],[s,c,i]],abc:[[u,h,-1],[-1,-1,u],[h,f,-1],[-1,-1,h],[f,u,-1],[-1,-1,f]]}}(e,r);n=a.xyzv,i=a.abc}for(var o=0;o<n.length;o++){e=n[o],r=i[o];for(var s=[],l=0;l<3;l++){var c=e[l][0],u=e[l][1],h=e[l][2],f=e[l][3],p=r[l]>-1?r[l]:E(c,u,h);s[l]=p>-1?p:z(c,u,h,R(t,f))}O(s[0],s[1],s[2])}}function B(t,e,r,n){var i=t[3];i<r&&(i=r),i>n&&(i=n);for(var a=(t[3]-i)/(t[3]-e[3]+1e-9),o=[],s=0;s<4;s++)o[s]=(1-a)*t[s]+a*e[s];return o}function N(t,e,r){return t>=e&&t<=r}function j(t){var e=.001*(S-T);return t>=T-e&&t<=S+e}function V(e){for(var r=[],n=0;n<4;n++){var i=e[n];r.push([t.x[i],t.y[i],t.z[i],t.value[i]])}return r}var U=3;function q(t,e,r,n,i,a){a||(a=1),r=[-1,-1,-1];var o=!1,s=[N(e[0][3],n,i),N(e[1][3],n,i),N(e[2][3],n,i)];if(!s[0]&&!s[1]&&!s[2])return!1;var l=function(t,e,r){return j(e[0][3])&&j(e[1][3])&&j(e[2][3])?(F(t,e,r),!0):a<U&&q(t,e,r,T,S,++a)};if(s[0]&&s[1]&&s[2])return l(t,e,r)||o;var c=!1;return[[0,1,2],[2,0,1],[1,2,0]].forEach(function(a){if(s[a[0]]&&s[a[1]]&&!s[a[2]]){var u=e[a[0]],h=e[a[1]],f=e[a[2]],p=B(f,u,n,i),d=B(f,h,n,i);o=l(t,[d,p,u],[-1,-1,r[a[0]]])||o,o=l(t,[u,h,d],[r[a[0]],r[a[1]],-1])||o,c=!0}}),c?o:([[0,1,2],[1,2,0],[2,0,1]].forEach(function(a){if(s[a[0]]&&!s[a[1]]&&!s[a[2]]){var u=e[a[0]],h=e[a[1]],f=e[a[2]],p=B(h,u,n,i),d=B(f,u,n,i);o=l(t,[d,p,u],[-1,-1,r[a[0]]])||o,c=!0}}),o)}function H(t,e,r,n){var i=!1,a=V(e),o=[N(a[0][3],r,n),N(a[1][3],r,n),N(a[2][3],r,n),N(a[3][3],r,n)];if(!(o[0]||o[1]||o[2]||o[3]))return i;if(o[0]&&o[1]&&o[2]&&o[3])return c&&(i=function(t,e,r){var n=function(n,i,a){F(t,[e[n],e[i],e[a]],[r[n],r[i],r[a]])};n(0,1,2),n(3,0,1),n(2,3,0),n(1,2,3)}(t,a,e)||i),i;var s=!1;return[[0,1,2,3],[3,0,1,2],[2,3,0,1],[1,2,3,0]].forEach(function(l){if(o[l[0]]&&o[l[1]]&&o[l[2]]&&!o[l[3]]){var u=a[l[0]],h=a[l[1]],f=a[l[2]],p=a[l[3]];if(c)i=F(t,[u,h,f],[e[l[0]],e[l[1]],e[l[2]]])||i;else{var d=B(p,u,r,n),g=B(p,h,r,n),v=B(p,f,r,n);i=F(null,[d,g,v],[-1,-1,-1])||i}s=!0}}),s?i:([[0,1,2,3],[1,2,3,0],[2,3,0,1],[3,0,1,2],[0,2,3,1],[1,3,2,0]].forEach(function(l){if(o[l[0]]&&o[l[1]]&&!o[l[2]]&&!o[l[3]]){var u=a[l[0]],h=a[l[1]],f=a[l[2]],p=a[l[3]],d=B(f,u,r,n),g=B(f,h,r,n),v=B(p,h,r,n),m=B(p,u,r,n);c?(i=F(t,[u,m,d],[e[l[0]],-1,-1])||i,i=F(t,[h,g,v],[e[l[1]],-1,-1])||i):i=function(t,e,r){var n=function(n,i,a){F(t,[e[n],e[i],e[a]],[r[n],r[i],r[a]])};n(0,1,2),n(2,3,0)}(null,[d,g,v,m],[-1,-1,-1,-1])||i,s=!0}}),s?i:([[0,1,2,3],[1,2,3,0],[2,3,0,1],[3,0,1,2]].forEach(function(l){if(o[l[0]]&&!o[l[1]]&&!o[l[2]]&&!o[l[3]]){var u=a[l[0]],h=a[l[1]],f=a[l[2]],p=a[l[3]],d=B(h,u,r,n),g=B(f,u,r,n),v=B(p,u,r,n);c?(i=F(t,[u,d,g],[e[l[0]],-1,-1])||i,i=F(t,[u,g,v],[e[l[0]],-1,-1])||i,i=F(t,[u,v,d],[e[l[0]],-1,-1])||i):i=F(null,[d,g,v],[-1,-1,-1])||i,s=!0}}),i))}function G(t,e,r,n,i,a,o,l,u,h,f){var p=!1;return s&&(P(t,"A")&&(p=H(null,[e,r,n,a],h,f)||p),P(t,"B")&&(p=H(null,[r,n,i,u],h,f)||p),P(t,"C")&&(p=H(null,[r,a,o,u],h,f)||p),P(t,"D")&&(p=H(null,[n,a,l,u],h,f)||p),P(t,"E")&&(p=H(null,[r,n,a,u],h,f)||p)),c&&(p=H(t,[r,n,a,u],h,f)||p),p}function Y(t,e,r,n,i,a,o,s){return[!0===s[0]||q(t,V([e,r,n]),[e,r,n],a,o),!0===s[1]||q(t,V([n,i,e]),[n,i,e],a,o)]}function W(t,e,r,n,i,a,o,s,l){return s?Y(t,e,r,i,n,a,o,l):Y(t,r,i,n,e,a,o,l)}function X(t,e,r,n,i,a,o){var s,l,c,u,h=!1,f=function(){h=q(t,[s,l,c],[-1,-1,-1],i,a)||h,h=q(t,[c,u,s],[-1,-1,-1],i,a)||h},p=o[0],d=o[1],g=o[2];return p&&(s=I(V([y(e,r-0,n-0)])[0],V([y(e-1,r-0,n-0)])[0],p),l=I(V([y(e,r-0,n-1)])[0],V([y(e-1,r-0,n-1)])[0],p),c=I(V([y(e,r-1,n-1)])[0],V([y(e-1,r-1,n-1)])[0],p),u=I(V([y(e,r-1,n-0)])[0],V([y(e-1,r-1,n-0)])[0],p),f()),d&&(s=I(V([y(e-0,r,n-0)])[0],V([y(e-0,r-1,n-0)])[0],d),l=I(V([y(e-0,r,n-1)])[0],V([y(e-0,r-1,n-1)])[0],d),c=I(V([y(e-1,r,n-1)])[0],V([y(e-1,r-1,n-1)])[0],d),u=I(V([y(e-1,r,n-0)])[0],V([y(e-1,r-1,n-0)])[0],d),f()),g&&(s=I(V([y(e-0,r-0,n)])[0],V([y(e-0,r-0,n-1)])[0],g),l=I(V([y(e-0,r-1,n)])[0],V([y(e-0,r-1,n-1)])[0],g),c=I(V([y(e-1,r-1,n)])[0],V([y(e-1,r-1,n-1)])[0],g),u=I(V([y(e-1,r-0,n)])[0],V([y(e-1,r-0,n-1)])[0],g),f()),h}function Z(t,e,r,n,i,a,o,l,c,u,h,f){var p=t;return f?(s&&"even"===t&&(p=null),G(p,e,r,n,i,a,o,l,c,u,h)):(s&&"odd"===t&&(p=null),G(p,c,l,o,a,i,n,r,e,u,h))}function $(t,e,r,n,i){for(var a=[],o=0,s=0;s<e.length;s++)for(var l=e[s],c=1;c<m;c++)for(var u=1;u<v;u++)a.push(W(t,y(l,u-1,c-1),y(l,u-1,c),y(l,u,c-1),y(l,u,c),r,n,(l+u+c)%2,i&&i[o]?i[o]:[])),o++;return a}function J(t,e,r,n,i){for(var a=[],o=0,s=0;s<e.length;s++)for(var l=e[s],c=1;c<g;c++)for(var u=1;u<m;u++)a.push(W(t,y(c-1,l,u-1),y(c,l,u-1),y(c-1,l,u),y(c,l,u),r,n,(c+l+u)%2,i&&i[o]?i[o]:[])),o++;return a}function K(t,e,r,n,i){for(var a=[],o=0,s=0;s<e.length;s++)for(var l=e[s],c=1;c<v;c++)for(var u=1;u<g;u++)a.push(W(t,y(u-1,c-1,l),y(u-1,c,l),y(u,c-1,l),y(u,c,l),r,n,(u+c+l)%2,i&&i[o]?i[o]:[])),o++;return a}function Q(t,e,r){for(var n=1;n<m;n++)for(var i=1;i<v;i++)for(var a=1;a<g;a++)Z(t,y(a-1,i-1,n-1),y(a-1,i-1,n),y(a-1,i,n-1),y(a-1,i,n),y(a,i-1,n-1),y(a,i-1,n),y(a,i,n-1),y(a,i,n),e,r,(a+i+n)%2)}function tt(t,e,r){s=!0,Q(t,e,r),s=!1}function et(t,e,r,n,i,a){for(var o=[],s=0,l=0;l<e.length;l++)for(var c=e[l],u=1;u<m;u++)for(var h=1;h<v;h++)o.push(X(t,c,h,u,r,n,i[l],a&&a[s]&&a[s])),s++;return o}function rt(t,e,r,n,i,a){for(var o=[],s=0,l=0;l<e.length;l++)for(var c=e[l],u=1;u<g;u++)for(var h=1;h<m;h++)o.push(X(t,u,c,h,r,n,i[l],a&&a[s]&&a[s])),s++;return o}function nt(t,e,r,n,i,a){for(var o=[],s=0,l=0;l<e.length;l++)for(var c=e[l],u=1;u<v;u++)for(var h=1;h<g;h++)o.push(X(t,h,u,c,r,n,i[l],a&&a[s]&&a[s])),s++;return o}function it(t,e){for(var r=[],n=t;n<e;n++)r.push(n);return r}return function(){if(L(),function(){for(var e=0;e<g;e++)for(var r=0;r<v;r++)for(var n=0;n<m;n++){var i=y(e,r,n);z(t.x[i],t.y[i],t.z[i],t.value[i])}}(),i&&o&&(D(o),c=!0,Q(null,T,S),c=!1),n&&a){D(a);for(var e=t.surface.pattern,r=t.surface.count,s=0;s<r;s++){var l=1===r?.5:s/(r-1),k=(1-l)*T+l*S,E=Math.abs(k-A),C=Math.abs(k-M),O=E>C?[A,k]:[k,M];tt(e,O[0],O[1])}}var I=[[Math.min(T,M),Math.max(T,M)],[Math.min(A,S),Math.max(A,S)]];["x","y","z"].forEach(function(e){for(var r=[],n=0;n<I.length;n++){var i=0,a=I[n][0],o=I[n][1],s=t.slices[e];if(s.show&&s.fill){D(s.fill);var l=[],c=[],u=[];if(s.locations.length)for(var y=0;y<s.locations.length;y++){var x=h(s.locations[y],"x"===e?f:"y"===e?p:d);0===x.distRatio?l.push(x.id):x.id>0&&(c.push(x.id),"x"===e?u.push([x.distRatio,0,0]):"y"===e?u.push([0,x.distRatio,0]):u.push([0,0,x.distRatio]))}else l=it(1,"x"===e?g-1:"y"===e?v-1:m-1);c.length>0&&(r[i]="x"===e?et(null,c,a,o,u,r[i]):"y"===e?rt(null,c,a,o,u,r[i]):nt(null,c,a,o,u,r[i]),i++),l.length>0&&(r[i]="x"===e?$(null,l,a,o,r[i]):"y"===e?J(null,l,a,o,r[i]):K(null,l,a,o,r[i]),i++)}var b=t.caps[e];b.show&&b.fill&&(D(b.fill),r[i]="x"===e?$(null,[0,g-1],a,o,r[i]):"y"===e?J(null,[0,v-1],a,o,r[i]):K(null,[0,m-1],a,o,r[i]),i++)}}),0===u&&L(),t._x=x,t._y=b,t._z=_,t._intensity=w,t._Xs=f,t._Ys=p,t._Zs=d}(),t}(t);var s={positions:o(n(r.xaxis,t._x,e.dataScale[0],t.xcalendar),n(r.yaxis,t._y,e.dataScale[1],t.ycalendar),n(r.zaxis,t._z,e.dataScale[2],t.zcalendar)),cells:o(t._i,t._j,t._k),lightPosition:[t.lightposition.x,t.lightposition.y,t.lightposition.z],ambient:t.lighting.ambient,diffuse:t.lighting.diffuse,specular:t.lighting.specular,roughness:t.lighting.roughness,fresnel:t.lighting.fresnel,vertexNormalsEpsilon:t.lighting.vertexnormalsepsilon,faceNormalsEpsilon:t.lighting.facenormalsepsilon,opacity:t.opacity,contourEnable:t.contour.show,contourColor:a(t.contour.color).slice(0,3),contourWidth:t.contour.width,useFacetNormals:t.flatshading};s.vertexIntensity=t._intensity,s.vertexIntensityBounds=[t.cmin,t.cmax],s.colormap=i(t),this.mesh.update(s)},u.dispose=function(){this.scene.glplot.remove(this.mesh),this.mesh.dispose()},e.exports=function(t,e){var r=t.glplot.gl,i=n({gl:r}),a=new c(t,i,e.uid);return i._trace=a,a.update(e),t.glplot.add(i),a}},{"../../lib":697,"../../lib/gl_format_color":694,"../../lib/str2rgbarray":720,"../../plots/gl3d/zip3":797,"gl-mesh3d":273}],989:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("../../lib"),a=t("../../components/colorscale/defaults"),o=t("./attributes");e.exports=function(t,e,r,s){function l(r,n){return i.coerce(t,e,o,r,n)}var c=l("isomin"),u=l("isomax");null!=u&&null!=c&&c>u&&(e.isomin=null,e.isomax=null);var h=l("x"),f=l("y"),p=l("z"),d=l("value");h&&h.length&&f&&f.length&&p&&p.length&&d&&d.length?(n.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y","z"],s),["x","y","z"].forEach(function(t){var e="caps."+t;l(e+".show")&&l(e+".fill");var r="slices."+t;l(r+".show")&&(l(r+".fill"),l(r+".locations"))}),l("spaceframe.show")&&l("spaceframe.fill"),l("surface.show")&&(l("surface.count"),l("surface.fill"),l("surface.pattern")),l("contour.show")&&(l("contour.color"),l("contour.width")),["text","hovertext","hovertemplate","lighting.ambient","lighting.diffuse","lighting.specular","lighting.roughness","lighting.fresnel","lighting.vertexnormalsepsilon","lighting.facenormalsepsilon","lightposition.x","lightposition.y","lightposition.z","flatshading","opacity"].forEach(function(t){l(t)}),a(t,e,s,l,{prefix:"",cLetter:"c"}),e._length=null):e.visible=!1}},{"../../components/colorscale/defaults":584,"../../lib":697,"../../registry":826,"./attributes":986}],990:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("./calc"),n.colorbar={min:"cmin",max:"cmax"},n.plot=t("./convert"),n.moduleType="trace",n.name="isosurface",n.basePlotModule=t("../../plots/gl3d"),n.categories=["gl3d"],n.meta={},e.exports=n},{"../../plots/gl3d":786,"./attributes":986,"./calc":987,"./convert":988,"./defaults":989}],991:[function(t,e,r){"use strict";var n=t("../../components/colorscale/attributes"),i=t("../../components/colorbar/attributes"),a=t("../../components/fx/hovertemplate_attributes"),o=t("../surface/attributes"),s=t("../../plots/attributes"),l=t("../../lib/extend").extendFlat;e.exports=l({x:{valType:"data_array",editType:"calc+clearAxisTypes"},y:{valType:"data_array",editType:"calc+clearAxisTypes"},z:{valType:"data_array",editType:"calc+clearAxisTypes"},i:{valType:"data_array",editType:"calc"},j:{valType:"data_array",editType:"calc"},k:{valType:"data_array",editType:"calc"},text:{valType:"string",dflt:"",arrayOk:!0,editType:"calc"},hovertext:{valType:"string",dflt:"",arrayOk:!0,editType:"calc"},hovertemplate:a({editType:"calc"}),delaunayaxis:{valType:"enumerated",values:["x","y","z"],dflt:"z",editType:"calc"},alphahull:{valType:"number",dflt:-1,editType:"calc"},intensity:{valType:"data_array",editType:"calc"},color:{valType:"color",editType:"calc"},vertexcolor:{valType:"data_array",editType:"calc"},facecolor:{valType:"data_array",editType:"calc"},transforms:void 0},n("",{colorAttr:"`intensity`",showScaleDflt:!0,editTypeOverride:"calc"}),{colorbar:i,opacity:o.opacity,flatshading:{valType:"boolean",dflt:!1,editType:"calc"},contour:{show:l({},o.contours.x.show,{}),color:o.contours.x.color,width:o.contours.x.width,editType:"calc"},lightposition:{x:l({},o.lightposition.x,{dflt:1e5}),y:l({},o.lightposition.y,{dflt:1e5}),z:l({},o.lightposition.z,{dflt:0}),editType:"calc"},lighting:l({vertexnormalsepsilon:{valType:"number",min:0,max:1,dflt:1e-12,editType:"calc"},facenormalsepsilon:{valType:"number",min:0,max:1,dflt:1e-6,editType:"calc"},editType:"calc"},o.lighting),hoverinfo:l({},s.hoverinfo,{editType:"calc"})})},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plots/attributes":742,"../surface/attributes":1135}],992:[function(t,e,r){"use strict";var n=t("../../components/colorscale/calc");e.exports=function(t,e){e.intensity&&n(t,e,{vals:e.intensity,containerStr:"",cLetter:"c"})}},{"../../components/colorscale/calc":582}],993:[function(t,e,r){"use strict";var n=t("gl-mesh3d"),i=t("delaunay-triangulate"),a=t("alpha-shape"),o=t("convex-hull"),s=t("../../lib/gl_format_color").parseColorScale,l=t("../../lib/str2rgbarray"),c=t("../../plots/gl3d/zip3");function u(t,e,r){this.scene=t,this.uid=r,this.mesh=e,this.name="",this.color="#fff",this.data=null,this.showContour=!1}var h=u.prototype;function f(t){for(var e=[],r=t.length,n=0;n<r;n++)e[n]=l(t[n]);return e}function p(t,e,r,n){for(var i=[],a=e.length,o=0;o<a;o++)i[o]=t.d2l(e[o],0,n)*r;return i}function d(t){for(var e=[],r=t.length,n=0;n<r;n++)e[n]=Math.round(t[n]);return e}function g(t,e){for(var r=t.length,n=0;n<r;n++)if(t[n]<=-.5||t[n]>=e-.5)return!1;return!0}h.handlePick=function(t){if(t.object===this.mesh){var e=t.index=t.data.index;t.traceCoordinate=[this.data.x[e],this.data.y[e],this.data.z[e]];var r=this.data.hovertext||this.data.text;return Array.isArray(r)&&void 0!==r[e]?t.textLabel=r[e]:r&&(t.textLabel=r),!0}},h.update=function(t){var e=this.scene,r=e.fullSceneLayout;this.data=t;var n,u=t.x.length,h=c(p(r.xaxis,t.x,e.dataScale[0],t.xcalendar),p(r.yaxis,t.y,e.dataScale[1],t.ycalendar),p(r.zaxis,t.z,e.dataScale[2],t.zcalendar));if(t.i&&t.j&&t.k){if(t.i.length!==t.j.length||t.j.length!==t.k.length||!g(t.i,u)||!g(t.j,u)||!g(t.k,u))return;n=c(d(t.i),d(t.j),d(t.k))}else n=0===t.alphahull?o(h):t.alphahull>0?a(t.alphahull,h):function(t,e){for(var r=["x","y","z"].indexOf(t),n=[],a=e.length,o=0;o<a;o++)n[o]=[e[o][(r+1)%3],e[o][(r+2)%3]];return i(n)}(t.delaunayaxis,h);var v={positions:h,cells:n,lightPosition:[t.lightposition.x,t.lightposition.y,t.lightposition.z],ambient:t.lighting.ambient,diffuse:t.lighting.diffuse,specular:t.lighting.specular,roughness:t.lighting.roughness,fresnel:t.lighting.fresnel,vertexNormalsEpsilon:t.lighting.vertexnormalsepsilon,faceNormalsEpsilon:t.lighting.facenormalsepsilon,opacity:t.opacity,contourEnable:t.contour.show,contourColor:l(t.contour.color).slice(0,3),contourWidth:t.contour.width,useFacetNormals:t.flatshading};t.intensity?(this.color="#fff",v.vertexIntensity=t.intensity,v.vertexIntensityBounds=[t.cmin,t.cmax],v.colormap=s(t)):t.vertexcolor?(this.color=t.vertexcolor[0],v.vertexColors=f(t.vertexcolor)):t.facecolor?(this.color=t.facecolor[0],v.cellColors=f(t.facecolor)):(this.color=t.color,v.meshColor=l(t.color)),this.mesh.update(v)},h.dispose=function(){this.scene.glplot.remove(this.mesh),this.mesh.dispose()},e.exports=function(t,e){var r=t.glplot.gl,i=n({gl:r}),a=new u(t,i,e.uid);return i._trace=a,a.update(e),t.glplot.add(i),a}},{"../../lib/gl_format_color":694,"../../lib/str2rgbarray":720,"../../plots/gl3d/zip3":797,"alpha-shape":52,"convex-hull":118,"delaunay-triangulate":153,"gl-mesh3d":273}],994:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("../../lib"),a=t("../../components/colorscale/defaults"),o=t("./attributes");e.exports=function(t,e,r,s){function l(r,n){return i.coerce(t,e,o,r,n)}function c(t){var e=t.map(function(t){var e=l(t);return e&&i.isArrayOrTypedArray(e)?e:null});return e.every(function(t){return t&&t.length===e[0].length})&&e}c(["x","y","z"])?(c(["i","j","k"]),(!e.i||e.j&&e.k)&&(!e.j||e.k&&e.i)&&(!e.k||e.i&&e.j)?(n.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y","z"],s),["lighting.ambient","lighting.diffuse","lighting.specular","lighting.roughness","lighting.fresnel","lighting.vertexnormalsepsilon","lighting.facenormalsepsilon","lightposition.x","lightposition.y","lightposition.z","contour.show","contour.color","contour.width","colorscale","reversescale","flatshading","alphahull","delaunayaxis","opacity"].forEach(function(t){l(t)}),"intensity"in t?(l("intensity"),a(t,e,s,l,{prefix:"",cLetter:"c"})):(e.showscale=!1,"facecolor"in t?l("facecolor"):"vertexcolor"in t?l("vertexcolor"):l("color",r)),l("text"),l("hovertext"),l("hovertemplate"),e._length=null):e.visible=!1):e.visible=!1}},{"../../components/colorscale/defaults":584,"../../lib":697,"../../registry":826,"./attributes":991}],995:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("./calc"),n.colorbar={min:"cmin",max:"cmax"},n.plot=t("./convert"),n.moduleType="trace",n.name="mesh3d",n.basePlotModule=t("../../plots/gl3d"),n.categories=["gl3d"],n.meta={},e.exports=n},{"../../plots/gl3d":786,"./attributes":991,"./calc":992,"./convert":993,"./defaults":994}],996:[function(t,e,r){"use strict";var n=t("../../lib").extendFlat,i=t("../scatter/attributes"),a=t("../../components/drawing/attributes").dash,o=t("../../components/fx/attributes"),s=i.line;function l(t){return{line:{color:n({},s.color,{dflt:t}),width:s.width,dash:a,editType:"style"},editType:"style"}}e.exports={x:{valType:"data_array",editType:"calc+clearAxisTypes"},open:{valType:"data_array",editType:"calc"},high:{valType:"data_array",editType:"calc"},low:{valType:"data_array",editType:"calc"},close:{valType:"data_array",editType:"calc"},line:{width:n({},s.width,{}),dash:n({},a,{}),editType:"style"},increasing:l("#3D9970"),decreasing:l("#FF4136"),text:{valType:"string",dflt:"",arrayOk:!0,editType:"calc"},hovertext:{valType:"string",dflt:"",arrayOk:!0,editType:"calc"},tickwidth:{valType:"number",min:0,max:.5,dflt:.3,editType:"calc"},hoverlabel:n({},o.hoverlabel,{split:{valType:"boolean",dflt:!1,editType:"style"}})}},{"../../components/drawing/attributes":594,"../../components/fx/attributes":604,"../../lib":697,"../scatter/attributes":1048}],997:[function(t,e,r){"use strict";var n=t("../../lib"),i=n._,a=t("../../plots/cartesian/axes"),o=t("../../constants/numerical").BADNUM;function s(t,e,r,n){return{o:t,h:e,l:r,c:n}}function l(t,e,r,s,l){for(var c=s.makeCalcdata(e,"open"),u=s.makeCalcdata(e,"high"),h=s.makeCalcdata(e,"low"),f=s.makeCalcdata(e,"close"),p=Array.isArray(e.text),d=Array.isArray(e.hovertext),g=!0,v=null,m=[],y=0;y<r.length;y++){var x=r[y],b=c[y],_=u[y],w=h[y],k=f[y];if(x!==o&&b!==o&&_!==o&&w!==o&&k!==o){k===b?null!==v&&k!==v&&(g=k>v):g=k>b,v=k;var A=l(b,_,w,k);A.pos=x,A.yc=(b+k)/2,A.i=y,A.dir=g?"increasing":"decreasing",p&&(A.tx=e.text[y]),d&&(A.htx=e.hovertext[y]),m.push(A)}else m.push({pos:x,empty:!0})}return e._extremes[s._id]=a.findExtremes(s,n.concat(h,u),{padded:!0}),m.length&&(m[0].t={labels:{open:i(t,"open:")+" ",high:i(t,"high:")+" ",low:i(t,"low:")+" ",close:i(t,"close:")+" "}}),m}e.exports={calc:function(t,e){var r=a.getFromId(t,e.xaxis),i=a.getFromId(t,e.yaxis),o=function(t,e,r){var i=r._minDiff;if(!i){var a,o=t._fullData,s=[];for(i=1/0,a=0;a<o.length;a++){var l=o[a];if("ohlc"===l.type&&!0===l.visible&&l.xaxis===e._id){s.push(l);var c=e.makeCalcdata(l,"x");l._xcalc=c;var u=n.distinctVals(c).minDiff;u&&isFinite(u)&&(i=Math.min(i,u))}}for(i===1/0&&(i=1),a=0;a<s.length;a++)s[a]._minDiff=i}return i*r.tickwidth}(t,r,e),c=e._minDiff;e._minDiff=null;var u=e._xcalc;e._xcalc=null;var h=l(t,e,u,i,s);return e._extremes[r._id]=a.findExtremes(r,u,{vpad:c/2}),h.length?(n.extendFlat(h[0].t,{wHover:c/2,tickLen:o}),h):[{t:{empty:!0}}]},calcCommon:l}},{"../../constants/numerical":674,"../../lib":697,"../../plots/cartesian/axes":745}],998:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./ohlc_defaults"),a=t("./attributes");function o(t,e,r,n){r(n+".line.color"),r(n+".line.width",e.line.width),r(n+".line.dash",e.line.dash)}e.exports=function(t,e,r,s){function l(r,i){return n.coerce(t,e,a,r,i)}i(t,e,l,s)?(l("line.width"),l("line.dash"),o(t,e,l,"increasing"),o(t,e,l,"decreasing"),l("text"),l("hovertext"),l("tickwidth"),s._requestRangeslider[e.xaxis]=!0):e.visible=!1}},{"../../lib":697,"./attributes":996,"./ohlc_defaults":1001}],999:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axes"),i=t("../../lib"),a=t("../../components/fx"),o=t("../../components/color"),s=t("../scatter/fill_hover_text"),l={increasing:"\u25b2",decreasing:"\u25bc"};function c(t,e,r,n){var i,s,l=t.cd,c=t.xa,u=l[0].trace,h=l[0].t,f=u.type,p="ohlc"===f?"l":"min",d="ohlc"===f?"h":"max",g=h.bPos||0,v=function(t){return t.pos+g-e},m=h.bdPos||h.tickLen,y=h.wHover,x=Math.min(1,m/Math.abs(c.r2c(c.range[1])-c.r2c(c.range[0])));function b(t){var e=v(t);return a.inbox(e-y,e+y,i)}function _(t){var e=t[p],n=t[d];return e===n||a.inbox(e-r,n-r,i)}function w(t){return(b(t)+_(t))/2}i=t.maxHoverDistance-x,s=t.maxSpikeDistance-x;var k=a.getDistanceFunction(n,b,_,w);if(a.getClosest(l,k,t),!1===t.index)return null;var A=l[t.index];if(A.empty)return null;var M=u[A.dir],T=M.line.color;return o.opacity(T)&&M.line.width?t.color=T:t.color=M.fillcolor,t.x0=c.c2p(A.pos+g-m,!0),t.x1=c.c2p(A.pos+g+m,!0),t.xLabelVal=A.pos,t.spikeDistance=w(A)*s/i,t.xSpike=c.c2p(A.pos,!0),t}function u(t,e,r,a){var o=t.cd,s=t.ya,l=o[0].trace,u=o[0].t,h=[],f=c(t,e,r,a);if(!f)return[];var p=o[f.index].hi||l.hoverinfo,d=p.split("+");if(!("all"===p||-1!==d.indexOf("y")))return[];for(var g=["high","open","close","low"],v={},m=0;m<g.length;m++){var y,x=g[m],b=l[x][f.index],_=s.c2p(b,!0);b in v?(y=v[b]).yLabel+="<br>"+u.labels[x]+n.hoverLabelText(s,b):((y=i.extendFlat({},f)).y0=y.y1=_,y.yLabelVal=b,y.yLabel=u.labels[x]+n.hoverLabelText(s,b),y.name="",h.push(y),v[b]=y)}return h}function h(t,e,r,i){var a=t.cd,o=t.ya,u=a[0].trace,h=a[0].t,f=c(t,e,r,i);if(!f)return[];var p=a[f.index],d=f.index=p.i,g=p.dir;function v(t){return h.labels[t]+n.hoverLabelText(o,u[t][d])}var m=p.hi||u.hoverinfo,y=m.split("+"),x="all"===m,b=x||-1!==y.indexOf("y"),_=x||-1!==y.indexOf("text"),w=b?[v("open"),v("high"),v("low"),v("close")+"  "+l[g]]:[];return _&&s(p,u,w),f.extraText=w.join("<br>"),f.y0=f.y1=o.c2p(p.yc,!0),[f]}e.exports={hoverPoints:function(t,e,r,n){return t.cd[0].trace.hoverlabel.split?u(t,e,r,n):h(t,e,r,n)},hoverSplit:u,hoverOnPoints:h}},{"../../components/color":574,"../../components/fx":613,"../../lib":697,"../../plots/cartesian/axes":745,"../scatter/fill_hover_text":1056}],1000:[function(t,e,r){"use strict";e.exports={moduleType:"trace",name:"ohlc",basePlotModule:t("../../plots/cartesian"),categories:["cartesian","svg","showLegend"],meta:{},attributes:t("./attributes"),supplyDefaults:t("./defaults"),calc:t("./calc").calc,plot:t("./plot"),style:t("./style"),hoverPoints:t("./hover").hoverPoints,selectPoints:t("./select")}},{"../../plots/cartesian":756,"./attributes":996,"./calc":997,"./defaults":998,"./hover":999,"./plot":1002,"./select":1003,"./style":1004}],1001:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("../../lib");e.exports=function(t,e,r,a){var o=r("x"),s=r("open"),l=r("high"),c=r("low"),u=r("close");if(r("hoverlabel.split"),n.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x"],a),s&&l&&c&&u){var h=Math.min(s.length,l.length,c.length,u.length);return o&&(h=Math.min(h,i.minRowLength(o))),e._length=h,h}}},{"../../lib":697,"../../registry":826}],1002:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../lib");e.exports=function(t,e,r,a){var o=e.xaxis,s=e.yaxis;i.makeTraceGroups(a,r,"trace ohlc").each(function(t){var r=n.select(this),a=t[0],l=a.t,c=a.trace;if(e.isRangePlot||(a.node3=r),!0!==c.visible||l.empty)r.remove();else{var u=l.tickLen,h=r.selectAll("path").data(i.identity);h.enter().append("path"),h.exit().remove(),h.attr("d",function(t){if(t.empty)return"M0,0Z";var e=o.c2p(t.pos,!0),r=o.c2p(t.pos-u,!0),n=o.c2p(t.pos+u,!0);return"M"+r+","+s.c2p(t.o,!0)+"H"+e+"M"+e+","+s.c2p(t.h,!0)+"V"+s.c2p(t.l,!0)+"M"+n+","+s.c2p(t.c,!0)+"H"+e})}})}},{"../../lib":697,d3:151}],1003:[function(t,e,r){"use strict";e.exports=function(t,e){var r,n=t.cd,i=t.xaxis,a=t.yaxis,o=[],s=n[0].t.bPos||0;if(!1===e)for(r=0;r<n.length;r++)n[r].selected=0;else for(r=0;r<n.length;r++){var l=n[r];e.contains([i.c2p(l.pos+s),a.c2p(l.yc)],null,l.i,t)?(o.push({pointNumber:l.i,x:i.c2d(l.pos),y:a.c2d(l.yc)}),l.selected=1):l.selected=0}return o}},{}],1004:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../components/drawing"),a=t("../../components/color");e.exports=function(t,e){var r=e?e[0].node3:n.select(t).selectAll("g.ohlclayer").selectAll("g.trace");r.style("opacity",function(t){return t[0].trace.opacity}),r.each(function(t){var e=t[0].trace;n.select(this).selectAll("path").each(function(t){if(!t.empty){var r=e[t.dir].line;n.select(this).style("fill","none").call(a.stroke,r.color).call(i.dashLine,r.dash,r.width).style("opacity",e.selectedpoints&&!t.selected?.3:1)}})})}},{"../../components/color":574,"../../components/drawing":595,d3:151}],1005:[function(t,e,r){"use strict";var n=t("../../lib/extend").extendFlat,i=t("../../plots/attributes"),a=t("../../plots/font_attributes"),o=t("../../components/colorscale/attributes"),s=t("../../components/fx/hovertemplate_attributes"),l=t("../../plots/domain").attributes,c=t("../scatter/attributes").line,u=t("../../components/colorbar/attributes"),h=n({editType:"calc"},o("line",{editType:"calc"}),{showscale:c.showscale,colorbar:u,shape:{valType:"enumerated",values:["linear","hspline"],dflt:"linear",editType:"plot"},hovertemplate:s({editType:"plot",arrayOk:!1},{keys:["count","probability"]})});e.exports={domain:l({name:"parcats",trace:!0,editType:"calc"}),hoverinfo:n({},i.hoverinfo,{flags:["count","probability"],editType:"plot",arrayOk:!1}),hoveron:{valType:"enumerated",values:["category","color","dimension"],dflt:"category",editType:"plot"},hovertemplate:s({editType:"plot",arrayOk:!1},{keys:["count","probability","category","categorycount","colorcount","bandcolorcount"]}),arrangement:{valType:"enumerated",values:["perpendicular","freeform","fixed"],dflt:"perpendicular",editType:"plot"},bundlecolors:{valType:"boolean",dflt:!0,editType:"plot"},sortpaths:{valType:"enumerated",values:["forward","backward"],dflt:"forward",editType:"plot"},labelfont:a({editType:"calc"}),tickfont:a({editType:"calc"}),dimensions:{_isLinkedToArray:"dimension",label:{valType:"string",editType:"calc"},categoryorder:{valType:"enumerated",values:["trace","category ascending","category descending","array"],dflt:"trace",editType:"calc"},categoryarray:{valType:"data_array",editType:"calc"},ticktext:{valType:"data_array",editType:"calc"},values:{valType:"data_array",dflt:[],editType:"calc"},displayindex:{valType:"integer",editType:"calc"},editType:"calc",visible:{valType:"boolean",dflt:!0,editType:"calc"}},line:h,counts:{valType:"number",min:0,dflt:1,arrayOk:!0,editType:"calc"},customdata:void 0,hoverlabel:void 0,ids:void 0,legendgroup:void 0,opacity:void 0,selectedpoints:void 0,showlegend:void 0}},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plots/attributes":742,"../../plots/domain":770,"../../plots/font_attributes":771,"../scatter/attributes":1048}],1006:[function(t,e,r){"use strict";var n=t("../../plots/get_data").getModuleCalcData,i=t("./plot");r.name="parcats",r.plot=function(t,e,r,a){var o=n(t.calcdata,"parcats");if(o.length){var s=o[0];i(t,s,r,a)}},r.clean=function(t,e,r,n){var i=n._has&&n._has("parcats"),a=e._has&&e._has("parcats");i&&!a&&n._paperdiv.selectAll(".parcats").remove()}},{"../../plots/get_data":781,"./plot":1011}],1007:[function(t,e,r){"use strict";var n=t("../../lib/gup").wrap,i=t("../../components/colorscale/helpers").hasColorscale,a=t("../../components/colorscale/calc"),o=t("../../lib/filter_unique.js"),s=t("../../components/drawing"),l=t("../../lib");function c(t,e,r){t.valueInds.push(e),t.count+=r}function u(t,e,r){t.valueInds.push(e),t.count+=r}e.exports=function(t,e){var r=l.filterVisible(e.dimensions);if(0===r.length)return[];var h,f,p,d=r.map(function(t){var e;return"trace"===t.categoryorder?e=null:"array"===t.categoryorder?e=t.categoryarray:(e=o(t.values).sort(),"category descending"===t.categoryorder&&(e=e.reverse())),function(t,e){e=null==e?[]:e.map(function(t){return t});var r={},n={},i=[];e.forEach(function(t,e){r[t]=0,n[t]=e});for(var a=0;a<t.length;a++){var o,s=t[a];void 0===r[s]?(r[s]=1,o=e.push(s)-1,n[s]=o):(r[s]++,o=n[s]),i.push(o)}var l=e.map(function(t){return r[t]});return{uniqueValues:e,uniqueCounts:l,inds:i}}(t.values,e)});h=l.isArrayOrTypedArray(e.counts)?e.counts:[e.counts],function(t){var e;if(function(t){for(var e=new Array(t.length),r=0;r<t.length;r++){if(t[r]<0||t[r]>=t.length)return!1;if(void 0!==e[t[r]])return!1;e[t[r]]=!0}return!0}(t.map(function(t){return t.displayindex})))for(e=0;e<t.length;e++)t[e]._displayindex=t[e].displayindex;else for(e=0;e<t.length;e++)t[e]._displayindex=e}(r),r.forEach(function(t,e){!function(t,e){t._categoryarray=e.uniqueValues,null===t.ticktext||void 0===t.ticktext?t._ticktext=[]:t._ticktext=t.ticktext.slice();for(var r=t._ticktext.length;r<e.uniqueValues.length;r++)t._ticktext.push(e.uniqueValues[r])}(t,d[e])});var g,v=e.line;v?(i(e,"line")&&a(t,e,{vals:e.line.color,containerStr:"line",cLetter:"c"}),g=s.tryColorscale(v)):g=l.identity;var m,y,x,b,_=r[0].values.length,w={},k=d.map(function(t){return t.inds});for(p=0,m=0;m<_;m++){var A=[];for(y=0;y<k.length;y++)A.push(k[y][m]);f=h[m%h.length],p+=f;var M=(x=m,b=void 0,b=l.isArrayOrTypedArray(v.color)?v.color[x%v.color.length]:v.color,{color:g(b),rawColor:b}),T=A+"-"+M.rawColor;void 0===w[T]&&(w[T]={categoryInds:A,color:M.color,rawColor:M.rawColor,valueInds:[],count:0}),u(w[T],m,f)}var S,E=r.map(function(t,e){return r=e,n=t._index,i=t._displayindex,a=t.label,{dimensionInd:r,containerInd:n,displayInd:i,dimensionLabel:a,count:p,categories:[],dragX:null};var r,n,i,a});for(m=0;m<_;m++)for(f=h[m%h.length],y=0;y<E.length;y++){var C=E[y].containerInd,L=d[y].inds[m],z=E[y].categories;if(void 0===z[L]){var O=e.dimensions[C]._categoryarray[L],I=e.dimensions[C]._ticktext[L];z[L]={dimensionInd:y,categoryInd:S=L,categoryValue:O,displayInd:S,categoryLabel:I,valueInds:[],count:0,dragY:null}}c(z[L],m,f)}return n(function(t,e,r){var n=t.map(function(t){return t.categories.length}).reduce(function(t,e){return Math.max(t,e)});return{dimensions:t,paths:e,trace:void 0,maxCats:n,count:r}}(E,w,p))}},{"../../components/colorscale/calc":582,"../../components/colorscale/helpers":585,"../../components/drawing":595,"../../lib":697,"../../lib/filter_unique.js":688,"../../lib/gup":695}],1008:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/colorscale/helpers").hasColorscale,a=t("../../components/colorscale/defaults"),o=t("../../plots/domain").defaults,s=t("../../plots/array_container_defaults"),l=t("./attributes"),c=t("../parcoords/merge_length");function u(t,e){function r(r,i){return n.coerce(t,e,l.dimensions,r,i)}var i=r("values"),a=r("visible");if(i&&i.length||(a=e.visible=!1),a){r("label"),r("displayindex",e._index);var o,s=t.categoryarray,c=Array.isArray(s)&&s.length>0;c&&(o="array");var u=r("categoryorder",o);"array"===u?(r("categoryarray"),r("ticktext")):(delete t.categoryarray,delete t.ticktext),c||"array"!==u||(e.categoryorder="trace")}}e.exports=function(t,e,r,h){function f(r,i){return n.coerce(t,e,l,r,i)}var p=s(t,e,{name:"dimensions",handleItemDefaults:u}),d=function(t,e,r,o,s){s("line.shape"),s("line.hovertemplate");var l=s("line.color",o.colorway[0]);if(i(t,"line")&&n.isArrayOrTypedArray(l)){if(l.length)return s("line.colorscale"),a(t,e,o,s,{prefix:"line.",cLetter:"c"}),l.length;e.line.color=r}return 1/0}(t,e,r,h,f);o(e,h,f),Array.isArray(p)&&p.length||(e.visible=!1),c(e,p,"values",d),f("hoveron"),f("hovertemplate"),f("arrangement"),f("bundlecolors"),f("sortpaths"),f("counts");var g={family:h.font.family,size:Math.round(h.font.size),color:h.font.color};n.coerceFont(f,"labelfont",g);var v={family:h.font.family,size:Math.round(h.font.size/1.2),color:h.font.color};n.coerceFont(f,"tickfont",v)}},{"../../components/colorscale/defaults":584,"../../components/colorscale/helpers":585,"../../lib":697,"../../plots/array_container_defaults":741,"../../plots/domain":770,"../parcoords/merge_length":1020,"./attributes":1005}],1009:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("./calc"),n.plot=t("./plot"),n.colorbar={container:"line",min:"cmin",max:"cmax"},n.moduleType="trace",n.name="parcats",n.basePlotModule=t("./base_plot"),n.categories=["noOpacity"],n.meta={},e.exports=n},{"./attributes":1005,"./base_plot":1006,"./calc":1007,"./defaults":1008,"./plot":1011}],1010:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../plot_api/plot_api"),a=t("../../components/fx"),o=t("../../lib"),s=t("../../components/drawing"),l=t("tinycolor2"),c=t("../../lib/svg_text_utils");function u(t,e,r,i){var a=t.map(function(t,e,r){var n,i=r[0],a=e.margin||{l:80,r:80,t:100,b:80},o=i.trace,s=o.domain,l=e.width,c=e.height,u=Math.floor(l*(s.x[1]-s.x[0])),h=Math.floor(c*(s.y[1]-s.y[0])),f=s.x[0]*l+a.l,p=e.height-s.y[1]*e.height+a.t,d=o.line.shape;n="all"===o.hoverinfo?["count","probability"]:(o.hoverinfo||"").split("+");var g={trace:o,key:o.uid,model:i,x:f,y:p,width:u,height:h,hoveron:o.hoveron,hoverinfoItems:n,arrangement:o.arrangement,bundlecolors:o.bundlecolors,sortpaths:o.sortpaths,labelfont:o.labelfont,categorylabelfont:o.tickfont,pathShape:d,dragDimension:null,margin:a,paths:[],dimensions:[],graphDiv:t,traceSelection:null,pathSelection:null,dimensionSelection:null};i.dimensions&&(R(g),P(g));return g}.bind(0,e,r)),l=i.selectAll("g.parcatslayer").data([null]);l.enter().append("g").attr("class","parcatslayer").style("pointer-events","all");var u=l.selectAll("g.trace.parcats").data(a,h),v=u.enter().append("g").attr("class","trace parcats");u.attr("transform",function(t){return"translate("+t.x+", "+t.y+")"}),v.append("g").attr("class","paths");var x=u.select("g.paths").selectAll("path.path").data(function(t){return t.paths},h);x.attr("fill",function(t){return t.model.color});var w=x.enter().append("path").attr("class","path").attr("stroke-opacity",0).attr("fill",function(t){return t.model.color}).attr("fill-opacity",0);y(w),x.attr("d",function(t){return t.svgD}),w.empty()||x.sort(p),x.exit().remove(),x.on("mouseover",d).on("mouseout",g).on("click",m),v.append("g").attr("class","dimensions");var k=u.select("g.dimensions").selectAll("g.dimension").data(function(t){return t.dimensions},h);k.enter().append("g").attr("class","dimension"),k.attr("transform",function(t){return"translate("+t.x+", 0)"}),k.exit().remove();var A=k.selectAll("g.category").data(function(t){return t.categories},h),M=A.enter().append("g").attr("class","category");A.attr("transform",function(t){return"translate(0, "+t.y+")"}),M.append("rect").attr("class","catrect").attr("pointer-events","none"),A.select("rect.catrect").attr("fill","none").attr("width",function(t){return t.width}).attr("height",function(t){return t.height}),b(M);var z=A.selectAll("rect.bandrect").data(function(t){return t.bands},h);z.each(function(){o.raiseToTop(this)}),z.attr("fill",function(t){return t.color});var O=z.enter().append("rect").attr("class","bandrect").attr("stroke-opacity",0).attr("fill",function(t){return t.color}).attr("fill-opacity",0);z.attr("fill",function(t){return t.color}).attr("width",function(t){return t.width}).attr("height",function(t){return t.height}).attr("y",function(t){return t.y}).attr("cursor",function(t){return"fixed"===t.parcatsViewModel.arrangement?"default":"perpendicular"===t.parcatsViewModel.arrangement?"ns-resize":"move"}),_(O),z.exit().remove(),M.append("text").attr("class","catlabel").attr("pointer-events","none");var I=e._fullLayout.paper_bgcolor;A.select("text.catlabel").attr("text-anchor",function(t){return f(t)?"start":"end"}).attr("alignment-baseline","middle").style("text-shadow",I+" -1px  1px 2px, "+I+" 1px  1px 2px, "+I+"  1px -1px 2px, "+I+" -1px -1px 2px").style("fill","rgb(0, 0, 0)").attr("x",function(t){return f(t)?t.width+5:-5}).attr("y",function(t){return t.height/2}).text(function(t){return t.model.categoryLabel}).each(function(t){s.font(n.select(this),t.parcatsViewModel.categorylabelfont),c.convertToTspans(n.select(this),e)}),M.append("text").attr("class","dimlabel"),A.select("text.dimlabel").attr("text-anchor","middle").attr("alignment-baseline","baseline").attr("cursor",function(t){return"fixed"===t.parcatsViewModel.arrangement?"default":"ew-resize"}).attr("x",function(t){return t.width/2}).attr("y",-5).text(function(t,e){return 0===e?t.parcatsViewModel.model.dimensions[t.model.dimensionInd].dimensionLabel:null}).each(function(t){s.font(n.select(this),t.parcatsViewModel.labelfont)}),A.selectAll("rect.bandrect").on("mouseover",T).on("mouseout",S),A.exit().remove(),k.call(n.behavior.drag().origin(function(t){return{x:t.x,y:0}}).on("dragstart",E).on("drag",C).on("dragend",L)),u.each(function(t){t.traceSelection=n.select(this),t.pathSelection=n.select(this).selectAll("g.paths").selectAll("path.path"),t.dimensionSelection=n.select(this).selectAll("g.dimensions").selectAll("g.dimension")}),u.exit().remove()}function h(t){return t.key}function f(t){var e=t.parcatsViewModel.dimensions.length,r=t.parcatsViewModel.dimensions[e-1].model.dimensionInd;return t.model.dimensionInd===r}function p(t,e){return t.model.rawColor>e.model.rawColor?1:t.model.rawColor<e.model.rawColor?-1:0}function d(t){if(!t.parcatsViewModel.dragDimension&&-1===t.parcatsViewModel.hoverinfoItems.indexOf("skip")){o.raiseToTop(this),x(n.select(this));var e=v(t);if(t.parcatsViewModel.graphDiv.emit("plotly_hover",{points:e,event:n.event}),-1===t.parcatsViewModel.hoverinfoItems.indexOf("none")){var r,i,s,c=n.mouse(this)[0],u=t.parcatsViewModel.graphDiv,h=t.parcatsViewModel.trace,f=u._fullLayout,p=f._paperdiv.node().getBoundingClientRect(),d=t.parcatsViewModel.graphDiv.getBoundingClientRect();for(s=0;s<t.leftXs.length-1;s++)if(t.leftXs[s]+t.dimWidths[s]-2<=c&&c<=t.leftXs[s+1]+2){var g=t.parcatsViewModel.dimensions[s],m=t.parcatsViewModel.dimensions[s+1];r=(g.x+g.width+m.x)/2,i=(t.topYs[s]+t.topYs[s+1]+t.height)/2;break}var y=t.parcatsViewModel.x+r,b=t.parcatsViewModel.y+i,_=l.mostReadable(t.model.color,["black","white"]),w=t.model.count,k=w/t.parcatsViewModel.model.count,A={countLabel:w,probabilityLabel:k.toFixed(3)},M=[];-1!==t.parcatsViewModel.hoverinfoItems.indexOf("count")&&M.push(["Count:",A.countLabel].join(" ")),-1!==t.parcatsViewModel.hoverinfoItems.indexOf("probability")&&M.push(["P:",A.probabilityLabel].join(" "));var T=M.join("<br>"),S=n.mouse(u)[0];a.loneHover({trace:h,x:y-p.left+d.left,y:b-p.top+d.top,text:T,color:t.model.color,borderColor:"black",fontFamily:'Monaco, "Courier New", monospace',fontSize:10,fontColor:_,idealAlign:S<y?"right":"left",hovertemplate:(h.line||{}).hovertemplate,hovertemplateLabels:A,eventData:[{data:h._input,fullData:h,count:w,probability:k}]},{container:f._hoverlayer.node(),outerContainer:f._paper.node(),gd:u})}}}function g(t){if(!t.parcatsViewModel.dragDimension&&(y(n.select(this)),a.loneUnhover(t.parcatsViewModel.graphDiv._fullLayout._hoverlayer.node()),t.parcatsViewModel.pathSelection.sort(p),-1===t.parcatsViewModel.hoverinfoItems.indexOf("skip"))){var e=v(t);t.parcatsViewModel.graphDiv.emit("plotly_unhover",{points:e,event:n.event})}}function v(t){for(var e=[],r=z(t.parcatsViewModel),n=0;n<t.model.valueInds.length;n++){var i=t.model.valueInds[n];e.push({curveNumber:r,pointNumber:i})}return e}function m(t){if(-1===t.parcatsViewModel.hoverinfoItems.indexOf("skip")){var e=v(t);t.parcatsViewModel.graphDiv.emit("plotly_click",{points:e,event:n.event})}}function y(t){t.attr("fill",function(t){return t.model.color}).attr("fill-opacity",.6).attr("stroke","lightgray").attr("stroke-width",.2).attr("stroke-opacity",1)}function x(t){t.attr("fill-opacity",.8).attr("stroke",function(t){return l.mostReadable(t.model.color,["black","white"])}).attr("stroke-width",.3)}function b(t){t.select("rect.catrect").attr("stroke","black").attr("stroke-width",1).attr("stroke-opacity",1)}function _(t){t.attr("stroke","black").attr("stroke-width",.2).attr("stroke-opacity",1).attr("fill-opacity",1)}function w(t){var e=t.parcatsViewModel.pathSelection,r=t.categoryViewModel.model.dimensionInd,n=t.categoryViewModel.model.categoryInd;return e.filter(function(e){return e.model.categoryInds[r]===n&&e.model.color===t.color})}function k(t,e,r){var i=n.select(t).datum().parcatsViewModel.graphDiv,a=n.select(t.parentNode).selectAll("rect.bandrect"),o=[];a.each(function(t){w(t).each(function(t){Array.prototype.push.apply(o,v(t))})}),i.emit(e,{points:o,event:r})}function A(t,e,r){var i=n.select(t).datum(),a=i.parcatsViewModel.graphDiv,o=w(i),s=[];o.each(function(t){Array.prototype.push.apply(s,v(t))}),a.emit(e,{points:s,event:r})}function M(t,e){var r,i,a=n.select(e.parentNode).select("rect.catrect"),o=a.node().getBoundingClientRect(),s=a.datum(),l=s.parcatsViewModel,c=l.model.dimensions[s.model.dimensionInd],u=l.trace,h=o.top+o.height/2;l.dimensions.length>1&&c.displayInd===l.dimensions.length-1?(r=o.left,i="left"):(r=o.left+o.width,i="right");var f=s.model.count,p=s.model.categoryLabel,d=f/s.parcatsViewModel.model.count,g={countLabel:f,categoryLabel:p,probabilityLabel:d.toFixed(3)},v=[];-1!==s.parcatsViewModel.hoverinfoItems.indexOf("count")&&v.push(["Count:",g.countLabel].join(" ")),-1!==s.parcatsViewModel.hoverinfoItems.indexOf("probability")&&v.push(["P("+g.categoryLabel+"):",g.probabilityLabel].join(" "));var m=v.join("<br>");return{trace:u,x:r-t.left,y:h-t.top,text:m,color:"lightgray",borderColor:"black",fontFamily:'Monaco, "Courier New", monospace',fontSize:12,fontColor:"black",idealAlign:i,hovertemplate:u.hovertemplate,hovertemplateLabels:g,eventData:[{data:u._input,fullData:u,count:f,category:p,probability:d}]}}function T(t){if(!t.parcatsViewModel.dragDimension&&-1===t.parcatsViewModel.hoverinfoItems.indexOf("skip")){if(n.mouse(this)[1]<-1)return;var e,r=t.parcatsViewModel.graphDiv,i=r._fullLayout,s=i._paperdiv.node().getBoundingClientRect(),c=t.parcatsViewModel.hoveron;if("color"===c?(!function(t){var e=n.select(t).datum(),r=w(e);x(r),r.each(function(){o.raiseToTop(this)}),n.select(t.parentNode).selectAll("rect.bandrect").filter(function(t){return t.color===e.color}).each(function(){o.raiseToTop(this),n.select(this).attr("stroke","black").attr("stroke-width",1.5)})}(this),A(this,"plotly_hover",n.event)):(!function(t){n.select(t.parentNode).selectAll("rect.bandrect").each(function(t){var e=w(t);x(e),e.each(function(){o.raiseToTop(this)})}),n.select(t.parentNode).select("rect.catrect").attr("stroke","black").attr("stroke-width",2.5)}(this),k(this,"plotly_hover",n.event)),-1===t.parcatsViewModel.hoverinfoItems.indexOf("none"))"category"===c?e=M(s,this):"color"===c?e=function(t,e){var r,i,a=e.getBoundingClientRect(),o=n.select(e).datum(),s=o.categoryViewModel,c=s.parcatsViewModel,u=c.model.dimensions[s.model.dimensionInd],h=c.trace,f=a.y+a.height/2;c.dimensions.length>1&&u.displayInd===c.dimensions.length-1?(r=a.left,i="left"):(r=a.left+a.width,i="right");var p=s.model.categoryLabel,d=o.parcatsViewModel.model.count,g=0;o.categoryViewModel.bands.forEach(function(t){t.color===o.color&&(g+=t.count)});var v=s.model.count,m=0;c.pathSelection.each(function(t){t.model.color===o.color&&(m+=t.model.count)});var y=g/d,x=g/m,b=g/v,_={countLabel:d,categoryLabel:p,probabilityLabel:y.toFixed(3)},w=[];-1!==s.parcatsViewModel.hoverinfoItems.indexOf("count")&&w.push(["Count:",_.countLabel].join(" ")),-1!==s.parcatsViewModel.hoverinfoItems.indexOf("probability")&&(w.push("P(color \u2229 "+p+"): "+_.probabilityLabel),w.push("P("+p+" | color): "+x.toFixed(3)),w.push("P(color | "+p+"): "+b.toFixed(3)));var k=w.join("<br>"),A=l.mostReadable(o.color,["black","white"]);return{trace:h,x:r-t.left,y:f-t.top,text:k,color:o.color,borderColor:"black",fontFamily:'Monaco, "Courier New", monospace',fontColor:A,fontSize:10,idealAlign:i,hovertemplate:h.hovertemplate,hovertemplateLabels:_,eventData:[{data:h._input,fullData:h,category:p,count:d,probability:y,categorycount:v,colorcount:m,bandcolorcount:g}]}}(s,this):"dimension"===c&&(e=function(t,e){var r=[];return n.select(e.parentNode.parentNode).selectAll("g.category").select("rect.catrect").each(function(){r.push(M(t,this))}),r}(s,this)),e&&a.multiHovers(e,{container:i._hoverlayer.node(),outerContainer:i._paper.node(),gd:r})}}function S(t){var e=t.parcatsViewModel;if(!e.dragDimension&&(y(e.pathSelection),b(e.dimensionSelection.selectAll("g.category")),_(e.dimensionSelection.selectAll("g.category").selectAll("rect.bandrect")),a.loneUnhover(e.graphDiv._fullLayout._hoverlayer.node()),e.pathSelection.sort(p),-1===e.hoverinfoItems.indexOf("skip"))){"color"===t.parcatsViewModel.hoveron?A(this,"plotly_unhover",n.event):k(this,"plotly_unhover",n.event)}}function E(t){"fixed"!==t.parcatsViewModel.arrangement&&(t.dragDimensionDisplayInd=t.model.displayInd,t.initialDragDimensionDisplayInds=t.parcatsViewModel.model.dimensions.map(function(t){return t.displayInd}),t.dragHasMoved=!1,t.dragCategoryDisplayInd=null,n.select(this).selectAll("g.category").select("rect.catrect").each(function(e){var r=n.mouse(this)[0],i=n.mouse(this)[1];-2<=r&&r<=e.width+2&&-2<=i&&i<=e.height+2&&(t.dragCategoryDisplayInd=e.model.displayInd,t.initialDragCategoryDisplayInds=t.model.categories.map(function(t){return t.displayInd}),e.model.dragY=e.y,o.raiseToTop(this.parentNode),n.select(this.parentNode).selectAll("rect.bandrect").each(function(e){e.y<i&&i<=e.y+e.height&&(t.potentialClickBand=this)}))}),t.parcatsViewModel.dragDimension=t,a.loneUnhover(t.parcatsViewModel.graphDiv._fullLayout._hoverlayer.node()))}function C(t){if("fixed"!==t.parcatsViewModel.arrangement&&(t.dragHasMoved=!0,null!==t.dragDimensionDisplayInd)){var e=t.dragDimensionDisplayInd,r=e-1,i=e+1,a=t.parcatsViewModel.dimensions[e];if(null!==t.dragCategoryDisplayInd){var o=a.categories[t.dragCategoryDisplayInd];o.model.dragY+=n.event.dy;var s=o.model.dragY,l=o.model.displayInd,c=a.categories,u=c[l-1],h=c[l+1];void 0!==u&&s<u.y+u.height/2&&(o.model.displayInd=u.model.displayInd,u.model.displayInd=l),void 0!==h&&s+o.height>h.y+h.height/2&&(o.model.displayInd=h.model.displayInd,h.model.displayInd=l),t.dragCategoryDisplayInd=o.model.displayInd}if(null===t.dragCategoryDisplayInd||"freeform"===t.parcatsViewModel.arrangement){a.model.dragX=n.event.x;var f=t.parcatsViewModel.dimensions[r],p=t.parcatsViewModel.dimensions[i];void 0!==f&&a.model.dragX<f.x+f.width&&(a.model.displayInd=f.model.displayInd,f.model.displayInd=e),void 0!==p&&a.model.dragX+a.width>p.x&&(a.model.displayInd=p.model.displayInd,p.model.displayInd=t.dragDimensionDisplayInd),t.dragDimensionDisplayInd=a.model.displayInd}R(t.parcatsViewModel),P(t.parcatsViewModel),I(t.parcatsViewModel),O(t.parcatsViewModel)}}function L(t){if("fixed"!==t.parcatsViewModel.arrangement&&null!==t.dragDimensionDisplayInd){n.select(this).selectAll("text").attr("font-weight","normal");var e={},r=z(t.parcatsViewModel),a=t.parcatsViewModel.model.dimensions.map(function(t){return t.displayInd}),o=t.initialDragDimensionDisplayInds.some(function(t,e){return t!==a[e]});o&&a.forEach(function(r,n){var i=t.parcatsViewModel.model.dimensions[n].containerInd;e["dimensions["+i+"].displayindex"]=r});var s=!1;if(null!==t.dragCategoryDisplayInd){var l=t.model.categories.map(function(t){return t.displayInd});if(s=t.initialDragCategoryDisplayInds.some(function(t,e){return t!==l[e]})){var c=t.model.categories.slice().sort(function(t,e){return t.displayInd-e.displayInd}),u=c.map(function(t){return t.categoryValue}),h=c.map(function(t){return t.categoryLabel});e["dimensions["+t.model.containerInd+"].categoryarray"]=[u],e["dimensions["+t.model.containerInd+"].ticktext"]=[h],e["dimensions["+t.model.containerInd+"].categoryorder"]="array"}}if(-1===t.parcatsViewModel.hoverinfoItems.indexOf("skip")&&!t.dragHasMoved&&t.potentialClickBand&&("color"===t.parcatsViewModel.hoveron?A(t.potentialClickBand,"plotly_click",n.event.sourceEvent):k(t.potentialClickBand,"plotly_click",n.event.sourceEvent)),t.model.dragX=null,null!==t.dragCategoryDisplayInd)t.parcatsViewModel.dimensions[t.dragDimensionDisplayInd].categories[t.dragCategoryDisplayInd].model.dragY=null,t.dragCategoryDisplayInd=null;t.dragDimensionDisplayInd=null,t.parcatsViewModel.dragDimension=null,t.dragHasMoved=null,t.potentialClickBand=null,R(t.parcatsViewModel),P(t.parcatsViewModel),n.transition().duration(300).ease("cubic-in-out").each(function(){I(t.parcatsViewModel,!0),O(t.parcatsViewModel,!0)}).each("end",function(){(o||s)&&i.restyle(t.parcatsViewModel.graphDiv,e,[r])})}}function z(t){for(var e,r=t.graphDiv._fullData,n=0;n<r.length;n++)if(t.key===r[n].uid){e=n;break}return e}function O(t,e){var r;void 0===e&&(e=!1),t.pathSelection.data(function(t){return t.paths},h),(r=t.pathSelection,e?r.transition():r).attr("d",function(t){return t.svgD})}function I(t,e){function r(t){return e?t.transition():t}void 0===e&&(e=!1),t.dimensionSelection.data(function(t){return t.dimensions},h);var i=t.dimensionSelection.selectAll("g.category").data(function(t){return t.categories},h);r(t.dimensionSelection).attr("transform",function(t){return"translate("+t.x+", 0)"}),r(i).attr("transform",function(t){return"translate(0, "+t.y+")"}),i.select(".dimlabel").text(function(t,e){return 0===e?t.parcatsViewModel.model.dimensions[t.model.dimensionInd].dimensionLabel:null}),i.select(".catlabel").attr("text-anchor",function(t){return f(t)?"start":"end"}).attr("x",function(t){return f(t)?t.width+5:-5}).each(function(t){var e,r;f(t)?(e=t.width+5,r="start"):(e=-5,r="end"),n.select(this).selectAll("tspan").attr("x",e).attr("text-anchor",r)});var a=i.selectAll("rect.bandrect").data(function(t){return t.bands},h),s=a.enter().append("rect").attr("class","bandrect").attr("cursor","move").attr("stroke-opacity",0).attr("fill",function(t){return t.color}).attr("fill-opacity",0);a.attr("fill",function(t){return t.color}).attr("width",function(t){return t.width}).attr("height",function(t){return t.height}).attr("y",function(t){return t.y}),_(s),a.each(function(){o.raiseToTop(this)}),a.exit().remove()}function D(t,e,r,i,a){var o,s,l=[],c=[];for(s=0;s<r.length-1;s++)o=n.interpolateNumber(r[s]+t[s],t[s+1]),l.push(o(a)),c.push(o(1-a));var u="M "+t[0]+","+e[0];for(u+="l"+r[0]+",0 ",s=1;s<r.length;s++)u+="C"+l[s-1]+","+e[s-1]+" "+c[s-1]+","+e[s]+" "+t[s]+","+e[s],u+="l"+r[s]+",0 ";for(u+="l0,"+i+" ",u+="l -"+r[r.length-1]+",0 ",s=r.length-2;s>=0;s--)u+="C"+c[s]+","+(e[s+1]+i)+" "+l[s]+","+(e[s]+i)+" "+(t[s]+r[s])+","+(e[s]+i),u+="l-"+r[s]+",0 ";return u+="Z"}function P(t){var e=t.dimensions,r=t.model,n=e.map(function(t){return t.categories.map(function(t){return t.y})}),i=t.model.dimensions.map(function(t){return t.categories.map(function(t){return t.displayInd})}),a=t.model.dimensions.map(function(t){return t.displayInd}),o=t.dimensions.map(function(t){return t.model.dimensionInd}),s=e.map(function(t){return t.x}),l=e.map(function(t){return t.width}),c=[];for(var u in r.paths)r.paths.hasOwnProperty(u)&&c.push(r.paths[u]);function h(t){var e=t.categoryInds.map(function(t,e){return i[e][t]});return o.map(function(t){return e[t]})}c.sort(function(e,r){var n=h(e),i=h(r);return"backward"===t.sortpaths&&(n.reverse(),i.reverse()),n.push(e.valueInds[0]),i.push(r.valueInds[0]),t.bundlecolors&&(n.unshift(e.rawColor),i.unshift(r.rawColor)),n<i?-1:n>i?1:0});for(var f=new Array(c.length),p=e[0].model.count,d=e[0].categories.map(function(t){return t.height}).reduce(function(t,e){return t+e}),g=0;g<c.length;g++){var v,m=c[g];v=p>0?d*(m.count/p):0;for(var y,x=new Array(n.length),b=0;b<m.categoryInds.length;b++){var _=m.categoryInds[b],w=i[b][_],k=a[b];x[k]=n[k][w],n[k][w]+=v;var A=t.dimensions[k].categories[w],M=A.bands.length,T=A.bands[M-1];if(void 0===T||m.rawColor!==T.rawColor){var S=void 0===T?0:T.y+T.height;A.bands.push({key:S,color:m.color,rawColor:m.rawColor,height:v,width:A.width,count:m.count,y:S,categoryViewModel:A,parcatsViewModel:t})}else{var E=A.bands[M-1];E.height+=v,E.count+=m.count}}y="hspline"===t.pathShape?D(s,x,l,v,.5):D(s,x,l,v,0),f[g]={key:m.valueInds[0],model:m,height:v,leftXs:s,topYs:x,dimWidths:l,svgD:y,parcatsViewModel:t}}t.paths=f}function R(t){var e=t.model.dimensions.map(function(t){return{displayInd:t.displayInd,dimensionInd:t.dimensionInd}});e.sort(function(t,e){return t.displayInd-e.displayInd});var r=[];for(var n in e){var i=e[n].dimensionInd,a=t.model.dimensions[i];r.push(F(t,a))}t.dimensions=r}function F(t,e){var r,n=t.model.dimensions.length,i=e.displayInd;r=40+(n>1?(t.width-80-16)/(n-1):0)*i;var a,o,s,l,c,u=[],h=t.model.maxCats,f=e.categories.length,p=e.count,d=t.height-8*(h-1),g=8*(h-f)/2,v=e.categories.map(function(t){return{displayInd:t.displayInd,categoryInd:t.categoryInd}});for(v.sort(function(t,e){return t.displayInd-e.displayInd}),c=0;c<f;c++)l=v[c].categoryInd,o=e.categories[l],a=p>0?o.count/p*d:0,s={key:o.valueInds[0],model:o,width:16,height:a,y:null!==o.dragY?o.dragY:g,bands:[],parcatsViewModel:t},g=g+a+8,u.push(s);return{key:e.dimensionInd,x:null!==e.dragX?e.dragX:r,y:0,width:16,model:e,categories:u,parcatsViewModel:t,dragCategoryDisplayInd:null,dragDimensionDisplayInd:null,initialDragDimensionDisplayInds:null,initialDragCategoryDisplayInds:null,dragHasMoved:null,potentialClickBand:null}}e.exports=function(t,e,r,n){u(r,t,n,e)}},{"../../components/drawing":595,"../../components/fx":613,"../../lib":697,"../../lib/svg_text_utils":721,"../../plot_api/plot_api":732,d3:151,tinycolor2:518}],1011:[function(t,e,r){"use strict";var n=t("./parcats");e.exports=function(t,e,r,i){var a=t._fullLayout,o=a._paper,s=a._size;n(t,o,e,{width:s.w,height:s.h,margin:{t:s.t,r:s.r,b:s.b,l:s.l}},r,i)}},{"./parcats":1010}],1012:[function(t,e,r){"use strict";var n=t("../../components/colorscale/attributes"),i=t("../../components/colorbar/attributes"),a=t("../../plots/cartesian/layout_attributes"),o=t("../../plots/font_attributes"),s=t("../../plots/domain").attributes,l=t("../../lib/extend").extendFlat,c=t("../../plot_api/plot_template").templatedArray;e.exports={domain:s({name:"parcoords",trace:!0,editType:"calc"}),hoverlabel:void 0,labelfont:o({editType:"calc"}),tickfont:o({editType:"calc"}),rangefont:o({editType:"calc"}),dimensions:c("dimension",{label:{valType:"string",editType:"calc"},tickvals:l({},a.tickvals,{editType:"calc"}),ticktext:l({},a.ticktext,{editType:"calc"}),tickformat:{valType:"string",dflt:"3s",editType:"calc"},visible:{valType:"boolean",dflt:!0,editType:"calc"},range:{valType:"info_array",items:[{valType:"number",editType:"calc"},{valType:"number",editType:"calc"}],editType:"calc"},constraintrange:{valType:"info_array",freeLength:!0,dimensions:"1-2",items:[{valType:"number",editType:"calc"},{valType:"number",editType:"calc"}],editType:"calc"},multiselect:{valType:"boolean",dflt:!0,editType:"calc"},values:{valType:"data_array",editType:"calc"},editType:"calc"}),line:l(n("line",{colorscaleDflt:"Viridis",autoColorDflt:!1,editTypeOverride:"calc"}),{colorbar:i,editType:"calc"})}},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../lib/extend":687,"../../plot_api/plot_template":735,"../../plots/cartesian/layout_attributes":757,"../../plots/domain":770,"../../plots/font_attributes":771}],1013:[function(t,e,r){"use strict";var n=t("./constants"),i=t("d3"),a=t("../../lib/gup").keyFun,o=t("../../lib/gup").repeat,s=t("../../lib").sorterAsc,l=n.bar.snapRatio;function c(t,e){return t*(1-l)+e*l}var u=n.bar.snapClose;function h(t,e){return t*(1-u)+e*u}function f(t,e,r){if(d(e,r))return e;for(var n=t[0],i=n,a=1;a<t.length;a++){var o=t[a];if(e<h(n,o))return c(n,i);if(e<o||a===t.length-1)return c(o,n);i=n,n=o}}function p(t,e,r){if(d(e,r))return e;for(var n=t[t.length-1],i=n,a=t.length-2;a>=0;a--){var o=t[a];if(e>h(n,o))return c(n,i);if(e>o||a===t.length-1)return c(o,n);i=n,n=o}}function d(t,e){for(var r=0;r<e.length;r++)if(t>=e[r][0]&&t<=e[r][1])return!0;return!1}function g(t){t.attr("x",-n.bar.captureWidth/2).attr("width",n.bar.captureWidth)}function v(t){t.attr("visibility","visible").style("visibility","visible").attr("fill","yellow").attr("opacity",0)}function m(t){if(!t.brush.filterSpecified)return"0,"+t.height;for(var e,r,n,i=y(t.brush.filter.getConsolidated(),t.height),a=[0],o=i.length?i[0][0]:null,s=0;s<i.length;s++)r=(e=i[s])[1]-e[0],a.push(o),a.push(r),(n=s+1)<i.length&&(o=i[n][0]-e[1]);return a.push(t.height),a}function y(t,e){return t.map(function(t){return t.map(function(t){return t*e}).sort(s)})}function x(){i.select(document.body).style("cursor",null)}function b(t){t.attr("stroke-dasharray",m)}function _(t,e){var r=i.select(t).selectAll(".highlight, .highlight-shadow");b(e?r.transition().duration(n.bar.snapDuration).each("end",e):r)}function w(t,e){var r,i=t.brush,a=NaN,o={};if(i.filterSpecified){var s=t.height,l=i.filter.getConsolidated(),c=y(l,s),u=NaN,h=NaN,f=NaN;for(r=0;r<=c.length;r++){var p=c[r];if(p&&p[0]<=e&&e<=p[1]){u=r;break}if(h=r?r-1:NaN,p&&p[0]>e){f=r;break}}if(a=u,isNaN(a)&&(a=isNaN(h)||isNaN(f)?isNaN(h)?f:h:e-c[h][1]<c[f][0]-e?h:f),!isNaN(a)){var d=c[a],g=function(t,e){var r=n.bar.handleHeight;if(!(e>t[1]+r||e<t[0]-r))return e>=.9*t[1]+.1*t[0]?"n":e<=.9*t[0]+.1*t[1]?"s":"ns"}(d,e);g&&(o.interval=l[a],o.intervalPix=d,o.region=g)}}if(t.ordinal&&!o.region){var v=t.unitTickvals,m=t.unitToPaddedPx.invert(e);for(r=0;r<v.length;r++){var x=[.25*v[Math.max(r-1,0)]+.75*v[r],.25*v[Math.min(r+1,v.length-1)]+.75*v[r]];if(m>=x[0]&&m<=x[1]){o.clickableOrdinalRange=x;break}}}return o}function k(t){t.on("mousemove",function(t){if(i.event.preventDefault(),!t.parent.inBrushDrag){var e=w(t,t.height-i.mouse(this)[1]-2*n.verticalPadding),r="crosshair";e.clickableOrdinalRange?r="pointer":e.region&&(r=e.region+"-resize"),i.select(document.body).style("cursor",r)}}).on("mouseleave",function(t){t.parent.inBrushDrag||x()}).call(i.behavior.drag().on("dragstart",function(t){i.event.sourceEvent.stopPropagation();var e=t.height-i.mouse(this)[1]-2*n.verticalPadding,r=t.unitToPaddedPx.invert(e),a=t.brush,o=w(t,e),s=o.interval,l=a.svgBrush;if(l.wasDragged=!1,l.grabbingBar="ns"===o.region,l.grabbingBar){var c=s.map(t.unitToPaddedPx);l.grabPoint=e-c[0]-n.verticalPadding,l.barLength=c[1]-c[0]}l.clickableOrdinalRange=o.clickableOrdinalRange,l.stayingIntervals=t.multiselect&&a.filterSpecified?a.filter.getConsolidated():[],s&&(l.stayingIntervals=l.stayingIntervals.filter(function(t){return t[0]!==s[0]&&t[1]!==s[1]})),l.startExtent=o.region?s["s"===o.region?1:0]:r,t.parent.inBrushDrag=!0,l.brushStartCallback()}).on("drag",function(t){i.event.sourceEvent.stopPropagation();var e=t.height-i.mouse(this)[1]-2*n.verticalPadding,r=t.brush.svgBrush;r.wasDragged=!0,r.grabbingBar?r.newExtent=[e-r.grabPoint,e+r.barLength-r.grabPoint].map(t.unitToPaddedPx.invert):r.newExtent=[r.startExtent,t.unitToPaddedPx.invert(e)].sort(s);var a=Math.max(0,-r.newExtent[0]),o=Math.max(0,r.newExtent[1]-1);r.newExtent[0]+=a,r.newExtent[1]-=o,r.grabbingBar&&(r.newExtent[1]+=a,r.newExtent[0]-=o),t.brush.filterSpecified=!0,r.extent=r.stayingIntervals.concat([r.newExtent]),r.brushCallback(t),_(this.parentNode)}).on("dragend",function(t){i.event.sourceEvent.stopPropagation();var e=t.brush,r=e.filter,n=e.svgBrush,a=n.grabbingBar;if(n.grabbingBar=!1,n.grabLocation=void 0,t.parent.inBrushDrag=!1,x(),!n.wasDragged)return n.wasDragged=void 0,n.clickableOrdinalRange?e.filterSpecified&&t.multiselect?n.extent.push(n.clickableOrdinalRange):(n.extent=[n.clickableOrdinalRange],e.filterSpecified=!0):a?(n.extent=n.stayingIntervals,0===n.extent.length&&M(e)):M(e),n.brushCallback(t),_(this.parentNode),void n.brushEndCallback(e.filterSpecified?r.getConsolidated():[]);var o=function(){r.set(r.getConsolidated())};if(t.ordinal){var s=t.unitTickvals;s[s.length-1]<s[0]&&s.reverse(),n.newExtent=[f(s,n.newExtent[0],n.stayingIntervals),p(s,n.newExtent[1],n.stayingIntervals)];var l=n.newExtent[1]>n.newExtent[0];n.extent=n.stayingIntervals.concat(l?[n.newExtent]:[]),n.extent.length||M(e),n.brushCallback(t),l?_(this.parentNode,o):(o(),_(this.parentNode))}else o();n.brushEndCallback(e.filterSpecified?r.getConsolidated():[])}))}function A(t,e){return t[0]-e[0]}function M(t){t.filterSpecified=!1,t.svgBrush.extent=[[0,1]]}function T(t){for(var e,r=t.slice(),n=[],i=r.shift();i;){for(e=i.slice();(i=r.shift())&&i[0]<=e[1];)e[1]=Math.max(e[1],i[1]);n.push(e)}return n}e.exports={makeBrush:function(t,e,r,n,i,a){var o,l=function(){var t,e,r=[];return{set:function(n){r=n.map(function(t){return t.slice().sort(s)}).sort(A),t=T(r),e=r.reduce(function(t,e){return[Math.min(t[0],e[0]),Math.max(t[1],e[1])]},[1/0,-1/0])},get:function(){return r.slice()},getConsolidated:function(){return t},getBounds:function(){return e}}}();return l.set(r),{filter:l,filterSpecified:e,svgBrush:{extent:[],brushStartCallback:n,brushCallback:(o=i,function(t){var e=t.brush,r=function(t){return t.svgBrush.extent.map(function(t){return t.slice()})}(e).slice();e.filter.set(r),o()}),brushEndCallback:a}}},ensureAxisBrush:function(t){var e=t.selectAll("."+n.cn.axisBrush).data(o,a);e.enter().append("g").classed(n.cn.axisBrush,!0),function(t){var e=t.selectAll(".background").data(o);e.enter().append("rect").classed("background",!0).call(g).call(v).style("pointer-events","auto").attr("transform","translate(0 "+n.verticalPadding+")"),e.call(k).attr("height",function(t){return t.height-n.verticalPadding});var r=t.selectAll(".highlight-shadow").data(o);r.enter().append("line").classed("highlight-shadow",!0).attr("x",-n.bar.width/2).attr("stroke-width",n.bar.width+n.bar.strokeWidth).attr("stroke",n.bar.strokeColor).attr("opacity",n.bar.strokeOpacity).attr("stroke-linecap","butt"),r.attr("y1",function(t){return t.height}).call(b);var i=t.selectAll(".highlight").data(o);i.enter().append("line").classed("highlight",!0).attr("x",-n.bar.width/2).attr("stroke-width",n.bar.width-n.bar.strokeWidth).attr("stroke",n.bar.fillColor).attr("opacity",n.bar.fillOpacity).attr("stroke-linecap","butt"),i.attr("y1",function(t){return t.height}).call(b)}(e)},cleanRanges:function(t,e){if(Array.isArray(t[0])?(t=t.map(function(t){return t.sort(s)}),t=e.multiselect?T(t.sort(A)):[t[0]]):t=[t.sort(s)],e.tickvals){var r=e.tickvals.slice().sort(s);if(!(t=t.map(function(t){var e=[f(r,t[0],[]),p(r,t[1],[])];if(e[1]>e[0])return e}).filter(function(t){return t})).length)return}return t.length>1?t:t[0]}}},{"../../lib":697,"../../lib/gup":695,"./constants":1016,d3:151}],1014:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../plots/get_data").getModuleCalcData,a=t("./plot"),o=t("../../constants/xmlns_namespaces");r.name="parcoords",r.plot=function(t){var e=i(t.calcdata,"parcoords")[0];e.length&&a(t,e)},r.clean=function(t,e,r,n){var i=n._has&&n._has("parcoords"),a=e._has&&e._has("parcoords");i&&!a&&(n._paperdiv.selectAll(".parcoords").remove(),n._glimages.selectAll("*").remove())},r.toSVG=function(t){var e=t._fullLayout._glimages,r=n.select(t).selectAll(".svg-container");r.filter(function(t,e){return e===r.size()-1}).selectAll(".gl-canvas-context, .gl-canvas-focus").each(function(){var t=this.toDataURL("image/png");e.append("svg:image").attr({xmlns:o.svg,"xlink:href":t,preserveAspectRatio:"none",x:0,y:0,width:this.width,height:this.height})}),window.setTimeout(function(){n.selectAll("#filterBarPattern").attr("id","filterBarPattern")},60)}},{"../../constants/xmlns_namespaces":675,"../../plots/get_data":781,"./plot":1022,d3:151}],1015:[function(t,e,r){"use strict";var n=t("../../components/colorscale/helpers").hasColorscale,i=t("../../components/colorscale/calc"),a=t("../../lib"),o=t("../../lib/gup").wrap;function s(t){return a.isTypedArray(t)?Array.prototype.slice.call(t):t}e.exports=function(t,e){for(var r=0;r<e.dimensions.length;r++)e.dimensions[r].values=s(e.dimensions[r].values);e.line.color=s(e.line.color);var a=!!e.line.colorscale&&Array.isArray(e.line.color),l=a?e.line.color:function(t){for(var e=new Array(t),r=0;r<t;r++)e[r]=.5;return e}(e._length),c=a?e.line.colorscale:[[0,e.line.color],[1,e.line.color]];return n(e,"line")&&i(t,e,{vals:l,containerStr:"line",cLetter:"c"}),o({lineColor:l,cscale:c})}},{"../../components/colorscale/calc":582,"../../components/colorscale/helpers":585,"../../lib":697,"../../lib/gup":695}],1016:[function(t,e,r){"use strict";e.exports={maxDimensionCount:60,overdrag:45,verticalPadding:2,tickDistance:50,canvasPixelRatio:1,blockLineCount:5e3,layers:["contextLineLayer","focusLineLayer","pickLineLayer"],axisTitleOffset:28,axisExtentOffset:10,bar:{width:4,captureWidth:10,fillColor:"magenta",fillOpacity:1,snapDuration:150,snapRatio:.25,snapClose:.01,strokeColor:"white",strokeOpacity:1,strokeWidth:1,handleHeight:8,handleOpacity:1,handleOverlap:0},cn:{axisExtentText:"axis-extent-text",parcoordsLineLayers:"parcoords-line-layers",parcoordsLineLayer:"parcoords-lines",parcoords:"parcoords",parcoordsControlView:"parcoords-control-view",yAxis:"y-axis",axisOverlays:"axis-overlays",axis:"axis",axisHeading:"axis-heading",axisTitle:"axis-title",axisExtent:"axis-extent",axisExtentTop:"axis-extent-top",axisExtentTopText:"axis-extent-top-text",axisExtentBottom:"axis-extent-bottom",axisExtentBottomText:"axis-extent-bottom-text",axisBrush:"axis-brush"},id:{filterBarPattern:"filter-bar-pattern"}}},{}],1017:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/colorscale/helpers").hasColorscale,a=t("../../components/colorscale/defaults"),o=t("../../plots/domain").defaults,s=t("../../plots/array_container_defaults"),l=t("./attributes"),c=t("./axisbrush"),u=t("./constants").maxDimensionCount,h=t("./merge_length");function f(t,e){function r(r,i){return n.coerce(t,e,l.dimensions,r,i)}var i=r("values"),a=r("visible");if(i&&i.length||(a=e.visible=!1),a){r("label"),r("tickvals"),r("ticktext"),r("tickformat"),r("range"),r("multiselect");var o=r("constraintrange");o&&(e.constraintrange=c.cleanRanges(o,e))}}e.exports=function(t,e,r,c){function p(r,i){return n.coerce(t,e,l,r,i)}var d=t.dimensions;Array.isArray(d)&&d.length>u&&(n.log("parcoords traces support up to "+u+" dimensions at the moment"),d.splice(u));var g=s(t,e,{name:"dimensions",handleItemDefaults:f}),v=function(t,e,r,o,s){var l=s("line.color",r);if(i(t,"line")&&n.isArrayOrTypedArray(l)){if(l.length)return s("line.colorscale"),a(t,e,o,s,{prefix:"line.",cLetter:"c"}),l.length;e.line.color=r}return 1/0}(t,e,r,c,p);o(e,c,p),Array.isArray(g)&&g.length||(e.visible=!1),h(e,g,"values",v);var m={family:c.font.family,size:Math.round(c.font.size/1.2),color:c.font.color};n.coerceFont(p,"labelfont",m),n.coerceFont(p,"tickfont",m),n.coerceFont(p,"rangefont",m)}},{"../../components/colorscale/defaults":584,"../../components/colorscale/helpers":585,"../../lib":697,"../../plots/array_container_defaults":741,"../../plots/domain":770,"./attributes":1012,"./axisbrush":1013,"./constants":1016,"./merge_length":1020}],1018:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("./calc"),n.plot=t("./plot"),n.colorbar={container:"line",min:"cmin",max:"cmax"},n.moduleType="trace",n.name="parcoords",n.basePlotModule=t("./base_plot"),n.categories=["gl","regl","noOpacity"],n.meta={},e.exports=n},{"./attributes":1012,"./base_plot":1014,"./calc":1015,"./defaults":1017,"./plot":1022}],1019:[function(t,e,r){"use strict";var n=t("glslify"),i=n(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n               p4, p5, p6, p7,\n               p8, p9, pa, pb,\n               pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n             loA, hiA, loB, hiB, loC, hiC, loD, hiD;\n\nuniform vec2 resolution,\n             viewBoxPosition,\n             viewBoxSize;\n\nuniform sampler2D palette;\nuniform sampler2D mask;\nuniform float maskHeight;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec4 unit_1 = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n    return dot(matrixCompMult(p, v) * unit_1, unit_1);\n}\n\nfloat axisY(\n        float x,\n        mat4 d[4],\n        mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n    ) {\n\n    float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n    float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n    return y1 * (1.0 - x) + y2 * x;\n}\n\nconst int bitsPerByte = 8;\n\nint mod2(int a) {\n    return a - 2 * (a / 2);\n}\n\nint mod8(int a) {\n    return a - 8 * (a / 8);\n}\n\nvec4 zero = vec4(0, 0, 0, 0);\nvec4 unit_0 = vec4(1, 1, 1, 1);\nvec2 xyProjection = vec2(1, 1);\n\nmat4 mclamp(mat4 m, mat4 lo, mat4 hi) {\n    return mat4(clamp(m[0], lo[0], hi[0]),\n                clamp(m[1], lo[1], hi[1]),\n                clamp(m[2], lo[2], hi[2]),\n                clamp(m[3], lo[3], hi[3]));\n}\n\nbool mshow(mat4 p, mat4 lo, mat4 hi) {\n    return mclamp(p, lo, hi) == p;\n}\n\nbool withinBoundingBox(\n        mat4 d[4],\n        mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD\n    ) {\n\n    return mshow(d[0], loA, hiA) &&\n           mshow(d[1], loB, hiB) &&\n           mshow(d[2], loC, hiC) &&\n           mshow(d[3], loD, hiD);\n}\n\nbool withinRasterMask(mat4 d[4], sampler2D mask, float height) {\n    bool result = true;\n    int bitInByteStepper;\n    float valY, valueY, scaleX;\n    int hit, bitmask, valX;\n    for(int i = 0; i < 4; i++) {\n        for(int j = 0; j < 4; j++) {\n            for(int k = 0; k < 4; k++) {\n                bitInByteStepper = mod8(j * 4 + k);\n                valX = i * 2 + j / 2;\n                valY = d[i][j][k];\n                valueY = valY * (height - 1.0) + 0.5;\n                scaleX = (float(valX) + 0.5) / 8.0;\n                hit = int(texture2D(mask, vec2(scaleX, (valueY + 0.5) / height))[3] * 255.0) / int(pow(2.0, float(bitInByteStepper)));\n                result = result && mod2(hit) == 1;\n            }\n        }\n    }\n    return result;\n}\n\nvec4 position(\n        float depth,\n        vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n        mat4 dims[4],\n        float signum,\n        mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D,\n        mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD,\n        sampler2D mask, float maskHeight\n    ) {\n\n    float x = 0.5 * signum + 0.5;\n    float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n    float show = float(\n                            withinBoundingBox(dims, loA, hiA, loB, hiB, loC, hiC, loD, hiD)\n                         && withinRasterMask(dims, mask, maskHeight)\n                      );\n\n    vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n    float depthOrHide = depth + 2.0 * (1.0 - show);\n\n    return vec4(\n        xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n        depthOrHide,\n        1.0\n    );\n}\n\nvoid main() {\n\n    float prominence = abs(pf[3]);\n\n    mat4 p[4];\n    p[0] = mat4(p0, p1, p2, p3);\n    p[1] = mat4(p4, p5, p6, p7);\n    p[2] = mat4(p8, p9, pa, pb);\n    p[3] = mat4(pc, pd, pe, abs(pf));\n\n    gl_Position = position(\n        1.0 - prominence,\n        resolution, viewBoxPosition, viewBoxSize,\n        p,\n        sign(pf[3]),\n        dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n        loA, hiA, loB, hiB, loC, hiC, loD, hiD,\n        mask, maskHeight\n    );\n\n    float clampedColorIndex = clamp((prominence - colorClamp[0]) / (colorClamp[1] - colorClamp[0]), 0.0, 1.0);\n    fragColor = texture2D(palette, vec2((clampedColorIndex * 255.0 + 0.5) / 256.0, 0.5));\n}\n"]),a=n(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n               p4, p5, p6, p7,\n               p8, p9, pa, pb,\n               pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D;\n\nuniform vec2 resolution,\n             viewBoxPosition,\n             viewBoxSize;\n\nuniform sampler2D palette;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec2 xyProjection = vec2(1, 1);\n\nvec4 unit = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n    return dot(matrixCompMult(p, v) * unit, unit);\n}\n\nfloat axisY(\n        float x,\n        mat4 d[4],\n        mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n    ) {\n\n    float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n    float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n    return y1 * (1.0 - x) + y2 * x;\n}\n\nvec4 position(\n        float depth,\n        vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n        mat4 dims[4],\n        float signum,\n        mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n    ) {\n\n    float x = 0.5 * signum + 0.5;\n    float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n    vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n\n    return vec4(\n        xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n        depth,\n        1.0\n    );\n}\n\nvoid main() {\n\n    float prominence = abs(pf[3]);\n\n    mat4 p[4];\n    p[0] = mat4(p0, p1, p2, p3);\n    p[1] = mat4(p4, p5, p6, p7);\n    p[2] = mat4(p8, p9, pa, pb);\n    p[3] = mat4(pc, pd, pe, abs(pf));\n\n    gl_Position = position(\n        1.0 - prominence,\n        resolution, viewBoxPosition, viewBoxSize,\n        p,\n        sign(pf[3]),\n        dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D\n    );\n\n    float clampedColorIndex = clamp((prominence - colorClamp[0]) / (colorClamp[1] - colorClamp[0]), 0.0, 1.0);\n    fragColor = texture2D(palette, vec2((clampedColorIndex * 255.0 + 0.5) / 256.0, 0.5));\n}\n"]),o=n(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n               p4, p5, p6, p7,\n               p8, p9, pa, pb,\n               pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n             loA, hiA, loB, hiB, loC, hiC, loD, hiD;\n\nuniform vec2 resolution,\n             viewBoxPosition,\n             viewBoxSize;\n\nuniform sampler2D mask;\nuniform float maskHeight;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec4 unit_1 = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n    return dot(matrixCompMult(p, v) * unit_1, unit_1);\n}\n\nfloat axisY(\n        float x,\n        mat4 d[4],\n        mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n    ) {\n\n    float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n    float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n    return y1 * (1.0 - x) + y2 * x;\n}\n\nconst int bitsPerByte = 8;\n\nint mod2(int a) {\n    return a - 2 * (a / 2);\n}\n\nint mod8(int a) {\n    return a - 8 * (a / 8);\n}\n\nvec4 zero = vec4(0, 0, 0, 0);\nvec4 unit_0 = vec4(1, 1, 1, 1);\nvec2 xyProjection = vec2(1, 1);\n\nmat4 mclamp(mat4 m, mat4 lo, mat4 hi) {\n    return mat4(clamp(m[0], lo[0], hi[0]),\n                clamp(m[1], lo[1], hi[1]),\n                clamp(m[2], lo[2], hi[2]),\n                clamp(m[3], lo[3], hi[3]));\n}\n\nbool mshow(mat4 p, mat4 lo, mat4 hi) {\n    return mclamp(p, lo, hi) == p;\n}\n\nbool withinBoundingBox(\n        mat4 d[4],\n        mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD\n    ) {\n\n    return mshow(d[0], loA, hiA) &&\n           mshow(d[1], loB, hiB) &&\n           mshow(d[2], loC, hiC) &&\n           mshow(d[3], loD, hiD);\n}\n\nbool withinRasterMask(mat4 d[4], sampler2D mask, float height) {\n    bool result = true;\n    int bitInByteStepper;\n    float valY, valueY, scaleX;\n    int hit, bitmask, valX;\n    for(int i = 0; i < 4; i++) {\n        for(int j = 0; j < 4; j++) {\n            for(int k = 0; k < 4; k++) {\n                bitInByteStepper = mod8(j * 4 + k);\n                valX = i * 2 + j / 2;\n                valY = d[i][j][k];\n                valueY = valY * (height - 1.0) + 0.5;\n                scaleX = (float(valX) + 0.5) / 8.0;\n                hit = int(texture2D(mask, vec2(scaleX, (valueY + 0.5) / height))[3] * 255.0) / int(pow(2.0, float(bitInByteStepper)));\n                result = result && mod2(hit) == 1;\n            }\n        }\n    }\n    return result;\n}\n\nvec4 position(\n        float depth,\n        vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n        mat4 dims[4],\n        float signum,\n        mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D,\n        mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD,\n        sampler2D mask, float maskHeight\n    ) {\n\n    float x = 0.5 * signum + 0.5;\n    float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n    float show = float(\n                            withinBoundingBox(dims, loA, hiA, loB, hiB, loC, hiC, loD, hiD)\n                         && withinRasterMask(dims, mask, maskHeight)\n                      );\n\n    vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n    float depthOrHide = depth + 2.0 * (1.0 - show);\n\n    return vec4(\n        xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n        depthOrHide,\n        1.0\n    );\n}\n\nvoid main() {\n\n    float prominence = abs(pf[3]);\n\n    mat4 p[4];\n    p[0] = mat4(p0, p1, p2, p3);\n    p[1] = mat4(p4, p5, p6, p7);\n    p[2] = mat4(p8, p9, pa, pb);\n    p[3] = mat4(pc, pd, pe, abs(pf));\n\n    gl_Position = position(\n        1.0 - prominence,\n        resolution, viewBoxPosition, viewBoxSize,\n        p,\n        sign(pf[3]),\n        dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n        loA, hiA, loB, hiB, loC, hiC, loD, hiD,\n        mask, maskHeight\n    );\n\n    fragColor = vec4(pf.rgb, 1.0);\n}\n"]),s=n(["precision lowp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n    gl_FragColor = fragColor;\n}\n"]),l=t("../../lib"),c=1e-6,u=1e-7,h=2048,f=64,p=2,d=4,g=8,v=f/g,m=[119,119,119],y=new Uint8Array(4),x=new Uint8Array(4),b={shape:[256,1],format:"rgba",type:"uint8",mag:"nearest",min:"nearest"};function _(t,e,r,n,i){var a=t._gl;a.enable(a.SCISSOR_TEST),a.scissor(e,r,n,i),t.clear({color:[0,0,0,0],depth:1})}function w(t,e,r,n,i,a){var o=a.key;r.drawCompleted||(!function(t){t.read({x:0,y:0,width:1,height:1,data:y})}(t),r.drawCompleted=!0),function s(l){var c;c=Math.min(n,i-l*n),a.offset=p*l*n,a.count=p*c,0===l&&(window.cancelAnimationFrame(r.currentRafs[o]),delete r.currentRafs[o],_(t,a.scissorX,a.scissorY,a.scissorWidth,a.viewBoxSize[1])),r.clearOnly||(e(a),l*n+c<i&&(r.currentRafs[o]=window.requestAnimationFrame(function(){s(l+1)})),r.drawCompleted=!1)}(0)}function k(t,e){return(t>>>8*e)%256/255}function A(t,e,r){var n,i,a,o=[];for(i=0;i<t;i++)for(a=0;a<p;a++)for(n=0;n<d;n++)o.push(e[i*f+r*d+n]),r*d+n===f-1&&a%2==0&&(o[o.length-1]*=-1);return o}e.exports=function(t,e){var r,n,p,d,y,M=e.context,T=e.pick,S=e.regl,E={currentRafs:{},drawCompleted:!0,clearOnly:!1},C=function(t){for(var e={},r=0;r<16;r++)e["p"+r.toString(16)]=t.buffer({usage:"dynamic",type:"float",data:new Uint8Array(0)});return e}(S),L=S.texture(b);O(e);var z=S({profile:!1,blend:{enable:M,func:{srcRGB:"src alpha",dstRGB:"one minus src alpha",srcAlpha:1,dstAlpha:1},equation:{rgb:"add",alpha:"add"},color:[0,0,0,0]},depth:{enable:!M,mask:!0,func:"less",range:[0,1]},cull:{enable:!0,face:"back"},scissor:{enable:!0,box:{x:S.prop("scissorX"),y:S.prop("scissorY"),width:S.prop("scissorWidth"),height:S.prop("scissorHeight")}},viewport:{x:S.prop("viewportX"),y:S.prop("viewportY"),width:S.prop("viewportWidth"),height:S.prop("viewportHeight")},dither:!1,vert:T?o:M?a:i,frag:s,primitive:"lines",lineWidth:1,attributes:C,uniforms:{resolution:S.prop("resolution"),viewBoxPosition:S.prop("viewBoxPosition"),viewBoxSize:S.prop("viewBoxSize"),dim1A:S.prop("dim1A"),dim2A:S.prop("dim2A"),dim1B:S.prop("dim1B"),dim2B:S.prop("dim2B"),dim1C:S.prop("dim1C"),dim2C:S.prop("dim2C"),dim1D:S.prop("dim1D"),dim2D:S.prop("dim2D"),loA:S.prop("loA"),hiA:S.prop("hiA"),loB:S.prop("loB"),hiB:S.prop("hiB"),loC:S.prop("loC"),hiC:S.prop("hiC"),loD:S.prop("loD"),hiD:S.prop("hiD"),palette:L,mask:S.prop("maskTexture"),maskHeight:S.prop("maskHeight"),colorClamp:S.prop("colorClamp")},offset:S.prop("offset"),count:S.prop("count")});function O(t){r=t.model,n=t.viewModel,p=n.dimensions.slice(),d=p[0]?p[0].values.length:0;var e=r.lines,i=T?e.color.map(function(t,r){return r/e.color.length}):e.color,a=Math.max(1/255,Math.pow(1/i.length,1/3)),o=function(t,e,r){for(var n,i=e.length,a=[],o=0;o<t;o++)for(var s=0;s<f;s++)a.push(s<i?e[s].paddedUnitValues[o]:s===f-1?(n=r[o],Math.max(c,Math.min(1-c,n))):s>=f-4?k(o,f-2-s):.5);return a}(d,p,i);!function(t,e,r){for(var n=0;n<16;n++)t["p"+n.toString(16)](A(e,r,n))}(C,d,o),L=S.texture(l.extendFlat({data:function(t,e,r){for(var n=[],i=0;i<256;i++){var a=t(i/255);n.push((e?m:a).concat(r))}return n}(r.unitToColor,M,Math.round(255*(M?a:1)))},b))}var I=[0,1];var D=[];function P(t,e,n,i,a,o,s,c,u,h,f){var p,d,g,v,m=[t,e],y=[0,1].map(function(){return[0,1,2,3].map(function(){return new Float32Array(16)})});for(p=0;p<2;p++)for(v=m[p],d=0;d<4;d++)for(g=0;g<16;g++)y[p][d][g]=g+16*d===v?1:0;var x=r.lines.canvasOverdrag,b=r.domain,_=r.canvasWidth,w=r.canvasHeight;return l.extendFlat({key:s,resolution:[_,w],viewBoxPosition:[n+x,i],viewBoxSize:[a,o],i:t,ii:e,dim1A:y[0][0],dim1B:y[0][1],dim1C:y[0][2],dim1D:y[0][3],dim2A:y[1][0],dim2B:y[1][1],dim2C:y[1][2],dim2D:y[1][3],colorClamp:I,scissorX:(c===u?0:n+x)+(r.pad.l-x)+r.layoutWidth*b.x[0],scissorWidth:(c===h?_-n+x:a+.5)+(c===u?n+x:0),scissorY:i+r.pad.b+r.layoutHeight*b.y[0],scissorHeight:o,viewportX:r.pad.l-x+r.layoutWidth*b.x[0],viewportY:r.pad.b+r.layoutHeight*b.y[0],viewportWidth:_,viewportHeight:w},f)}return{setColorDomain:function(t){I[0]=t[0],I[1]=t[1]},render:function(t,e,n){var i,a,o,s=t.length,l=1/0,c=-1/0;for(i=0;i<s;i++)t[i].dim2.canvasX>c&&(c=t[i].dim2.canvasX,o=i),t[i].dim1.canvasX<l&&(l=t[i].dim1.canvasX,a=i);0===s&&_(S,0,0,r.canvasWidth,r.canvasHeight);var f=M?{}:function(){var t,e,r,n=[0,1].map(function(){return[0,1,2,3].map(function(){return new Float32Array(16)})});for(t=0;t<2;t++)for(e=0;e<4;e++)for(r=0;r<16;r++){var i,a=r+16*e;i=a<p.length?p[a].brush.filter.getBounds()[t]:t,n[t][e][r]=i+(2*t-1)*u}function o(t,e){var r=h-1;return[Math.max(0,Math.floor(e[0]*r)),Math.min(r,Math.ceil(e[1]*r))]}for(var s=Array.apply(null,new Array(h*v)).map(function(){return 255}),l=0;l<p.length;l++){var c=l%g,f=(l-c)/g,d=Math.pow(2,c),m=p[l],x=m.brush.filter.get();if(!(x.length<2))for(var b=o(0,x[0])[1],_=1;_<x.length;_++){for(var w=o(0,x[_]),k=b+1;k<w[0];k++)s[k*v+f]&=~d;b=Math.max(b,w[1])}}var A={shape:[v,h],format:"alpha",type:"uint8",mag:"nearest",min:"nearest",data:s};return y?y(A):y=S.texture(A),{maskTexture:y,maskHeight:h,loA:n[0][0],loB:n[0][1],loC:n[0][2],loD:n[0][3],hiA:n[1][0],hiB:n[1][1],hiC:n[1][2],hiD:n[1][3]}}();for(i=0;i<s;i++){var m=t[i],x=m.dim1,b=x.crossfilterDimensionIndex,k=m.canvasX,A=m.canvasY,T=m.dim2.crossfilterDimensionIndex,C=m.panelSizeX,L=m.panelSizeY,O=k+C;if(e||!D[b]||D[b][0]!==k||D[b][1]!==O){D[b]=[k,O];var I=P(b,T,k,A,C,L,x.crossfilterDimensionIndex,i,a,o,f);E.clearOnly=n,w(S,z,E,e?r.lines.blockLineCount:d,d,I)}}},readPixel:function(t,e){return S.read({x:t,y:e,width:1,height:1,data:x}),x},readPixels:function(t,e,r,n){var i=new Uint8Array(4*r*n);return S.read({x:t,y:e,width:r,height:n,data:i}),i},destroy:function(){for(var e in t.style["pointer-events"]="none",L.destroy(),y&&y.destroy(),C)C[e].destroy()},update:O}}},{"../../lib":697,glslify:398}],1020:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){var i,a;for(n||(n=1/0),i=0;i<e.length;i++)(a=e[i]).visible&&(n=Math.min(n,a[r].length));for(n===1/0&&(n=0),t._length=n,i=0;i<e.length;i++)(a=e[i]).visible&&(a._length=n);return n}},{}],1021:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../lib"),a=t("../../components/drawing"),o=t("../../components/colorscale"),s=t("../../lib/gup"),l=s.keyFun,c=s.repeat,u=s.unwrap,h=t("./constants"),f=t("./axisbrush"),p=t("./lines");function d(t){return!("visible"in t)||t.visible}function g(t){var e=t.range?t.range[0]:i.aggNums(Math.min,null,t.values,t._length),r=t.range?t.range[1]:i.aggNums(Math.max,null,t.values,t._length);return!isNaN(e)&&isFinite(e)||(e=0),!isNaN(r)&&isFinite(r)||(r=0),e===r&&(0===e?(e-=1,r+=1):(e*=.9,r*=1.1)),[e,r]}function v(t){return t.dimensions.some(function(t){return t.brush.filterSpecified})}function m(t,e,r){var a=u(e),s=a.trace,l=a.lineColor,c=s.line,f=c.reversescale?o.flipScale(a.cscale):a.cscale,p=s.domain,v=s.dimensions,m=t.width,y=s.labelfont,x=s.tickfont,b=s.rangefont,_=i.extendDeepNoArrays({},c,{color:l.map(n.scale.linear().domain(g({values:l,range:[c.cmin,c.cmax],_length:s._length}))),blockLineCount:h.blockLineCount,canvasOverdrag:h.overdrag*h.canvasPixelRatio}),w=Math.floor(m*(p.x[1]-p.x[0])),k=Math.floor(t.height*(p.y[1]-p.y[0])),A=t.margin||{l:80,r:80,t:100,b:80},M=w,T=k;return{key:r,colCount:v.filter(d).length,dimensions:v,tickDistance:h.tickDistance,unitToColor:function(t){var e=t.map(function(t){return t[0]}),r=t.map(function(t){return n.rgb(t[1])}),i="rgb".split("").map(function(t){return n.scale.linear().clamp(!0).domain(e).range(r.map((i=t,function(t){return t[i]})));var i});return function(t){return i.map(function(e){return e(t)})}}(f),lines:_,labelFont:y,tickFont:x,rangeFont:b,layoutWidth:m,layoutHeight:t.height,domain:p,translateX:p.x[0]*m,translateY:t.height-p.y[1]*t.height,pad:A,canvasWidth:M*h.canvasPixelRatio+2*_.canvasOverdrag,canvasHeight:T*h.canvasPixelRatio,width:M,height:T,canvasPixelRatio:h.canvasPixelRatio}}function y(t,e,r){var a=r.width,o=r.height,s=r.dimensions,l=r.canvasPixelRatio,c=function(t){return a*t/Math.max(1,r.colCount-1)},u=h.verticalPadding/o,p=function(t,e){return n.scale.linear().range([e,t-e])}(o,h.verticalPadding),m={key:r.key,xScale:c,model:r,inBrushDrag:!1},y={};return m.dimensions=s.filter(d).map(function(a,s){var d=function(t,e){return n.scale.linear().domain(g(t)).range([e,1-e])}(a,u),x=y[a.label];y[a.label]=(x||0)+1;var b=a.label+(x?"__"+x:""),_=a.constraintrange,w=_&&_.length;w&&!Array.isArray(_[0])&&(_=[_]);var k=w?_.map(function(t){return t.map(d)}):[[0,1]],A=a.values;A.length>a._length&&(A=A.slice(0,a._length));var M,T=a.tickvals;function S(t,e){return{val:t,text:M[e]}}function E(t,e){return t.val-e.val}if(Array.isArray(T)&&T.length){M=a.ticktext,Array.isArray(M)&&M.length?M.length>T.length?M=M.slice(0,T.length):T.length>M.length&&(T=T.slice(0,M.length)):M=T.map(n.format(a.tickformat));for(var C=1;C<T.length;C++)if(T[C]<T[C-1]){for(var L=T.map(S).sort(E),z=0;z<T.length;z++)T[z]=L[z].val,M[z]=L[z].text;break}}else T=void 0;return{key:b,label:a.label,tickFormat:a.tickformat,tickvals:T,ticktext:M,ordinal:!!T,multiselect:a.multiselect,xIndex:s,crossfilterDimensionIndex:s,visibleIndex:a._index,height:o,values:A,paddedUnitValues:A.map(d),unitTickvals:T&&T.map(d),xScale:c,x:c(s),canvasX:c(s)*l,unitToPaddedPx:p,domainScale:function(t,e,r,i,a){var o,s,l=g(r);return i?n.scale.ordinal().domain(i.map((o=n.format(r.tickformat),s=a,s?function(t,e){var r=s[e];return null==r?o(t):r}:o))).range(i.map(function(r){var n=(r-l[0])/(l[1]-l[0]);return t-e+n*(2*e-t)})):n.scale.linear().domain(l).range([t-e,e])}(o,h.verticalPadding,a,T,M),ordinalScale:function(t){if(t.tickvals){var e=g(t);return n.scale.ordinal().domain(t.tickvals).range(t.tickvals.map(function(t){return(t-e[0])/(e[1]-e[0])}))}}(a),parent:m,model:r,brush:f.makeBrush(t,w,k,function(){t.linePickActive(!1)},function(){var e=m;e.focusLayer&&e.focusLayer.render(e.panels,!0);var r=v(e);!t.contextShown()&&r?(e.contextLayer&&e.contextLayer.render(e.panels,!0),t.contextShown(!0)):t.contextShown()&&!r&&(e.contextLayer&&e.contextLayer.render(e.panels,!0,!0),t.contextShown(!1))},function(r){var n=m;if(n.focusLayer.render(n.panels,!0),n.pickLayer&&n.pickLayer.render(n.panels,!0),t.linePickActive(!0),e&&e.filterChanged){var o=d.invert,s=r.map(function(t){return t.map(o).sort(i.sorterAsc)}).sort(function(t,e){return t[0]-e[0]});e.filterChanged(n.key,a._index,s)}})}}),m}function x(t){t.classed(h.cn.axisExtentText,!0).attr("text-anchor","middle").style("cursor","default").style("user-select","none")}e.exports=function(t,e,r,o,s,d){var g,b,_=(g=!0,b=!1,{linePickActive:function(t){return arguments.length?g=!!t:g},contextShown:function(t){return arguments.length?b=!!t:b}}),w=o.filter(function(t){return u(t).trace.visible}).map(m.bind(0,s)).map(y.bind(0,_,d));r.each(function(t,e){return i.extendFlat(t,w[e])});var k=r.selectAll(".gl-canvas").each(function(t){t.viewModel=w[0],t.model=t.viewModel?t.viewModel.model:null}),A=null;k.filter(function(t){return t.pick}).style("pointer-events","auto").on("mousemove",function(t){if(_.linePickActive()&&t.lineLayer&&d&&d.hover){var e=n.event,r=this.width,i=this.height,a=n.mouse(this),o=a[0],s=a[1];if(o<0||s<0||o>=r||s>=i)return;var l=t.lineLayer.readPixel(o,i-1-s),c=0!==l[3],u=c?l[2]+256*(l[1]+256*l[0]):null,h={x:o,y:s,clientX:e.clientX,clientY:e.clientY,dataIndex:t.model.key,curveNumber:u};u!==A&&(c?d.hover(h):d.unhover&&d.unhover(h),A=u)}}),k.style("opacity",function(t){return t.pick?.01:1}),e.style("background","rgba(255, 255, 255, 0)");var M=e.selectAll("."+h.cn.parcoords).data(w,l);M.exit().remove(),M.enter().append("g").classed(h.cn.parcoords,!0).style("shape-rendering","crispEdges").style("pointer-events","none"),M.attr("transform",function(t){return"translate("+t.model.translateX+","+t.model.translateY+")"});var T=M.selectAll("."+h.cn.parcoordsControlView).data(c,l);T.enter().append("g").classed(h.cn.parcoordsControlView,!0),T.attr("transform",function(t){return"translate("+t.model.pad.l+","+t.model.pad.t+")"});var S=T.selectAll("."+h.cn.yAxis).data(function(t){return t.dimensions},l);function E(t,e){for(var r=e.panels||(e.panels=[]),n=t.data(),i=n.length-1,a=0;a<i;a++){var o=r[a]||(r[a]={}),s=n[a],l=n[a+1];o.dim1=s,o.dim2=l,o.canvasX=s.canvasX,o.panelSizeX=l.canvasX-s.canvasX,o.panelSizeY=e.model.canvasHeight,o.y=0,o.canvasY=0}}S.enter().append("g").classed(h.cn.yAxis,!0),T.each(function(t){E(S,t)}),k.each(function(t){if(t.viewModel){!t.lineLayer||d?t.lineLayer=p(this,t):t.lineLayer.update(t),(t.key||0===t.key)&&(t.viewModel[t.key]=t.lineLayer);var e=!t.context||d;t.lineLayer.render(t.viewModel.panels,e)}}),S.attr("transform",function(t){return"translate("+t.xScale(t.xIndex)+", 0)"}),S.call(n.behavior.drag().origin(function(t){return t}).on("drag",function(t){var e=t.parent;_.linePickActive(!1),t.x=Math.max(-h.overdrag,Math.min(t.model.width+h.overdrag,n.event.x)),t.canvasX=t.x*t.model.canvasPixelRatio,S.sort(function(t,e){return t.x-e.x}).each(function(e,r){e.xIndex=r,e.x=t===e?e.x:e.xScale(e.xIndex),e.canvasX=e.x*e.model.canvasPixelRatio}),E(S,e),S.filter(function(e){return 0!==Math.abs(t.xIndex-e.xIndex)}).attr("transform",function(t){return"translate("+t.xScale(t.xIndex)+", 0)"}),n.select(this).attr("transform","translate("+t.x+", 0)"),S.each(function(r,n,i){i===t.parent.key&&(e.dimensions[n]=r)}),e.contextLayer&&e.contextLayer.render(e.panels,!1,!v(e)),e.focusLayer.render&&e.focusLayer.render(e.panels)}).on("dragend",function(t){var e=t.parent;t.x=t.xScale(t.xIndex),t.canvasX=t.x*t.model.canvasPixelRatio,E(S,e),n.select(this).attr("transform",function(t){return"translate("+t.x+", 0)"}),e.contextLayer&&e.contextLayer.render(e.panels,!1,!v(e)),e.focusLayer&&e.focusLayer.render(e.panels),e.pickLayer&&e.pickLayer.render(e.panels,!0),_.linePickActive(!0),d&&d.axesMoved&&d.axesMoved(e.key,e.dimensions.map(function(t){return t.crossfilterDimensionIndex}))})),S.exit().remove();var C=S.selectAll("."+h.cn.axisOverlays).data(c,l);C.enter().append("g").classed(h.cn.axisOverlays,!0),C.selectAll("."+h.cn.axis).remove();var L=C.selectAll("."+h.cn.axis).data(c,l);L.enter().append("g").classed(h.cn.axis,!0),L.each(function(t){var e=t.model.height/t.model.tickDistance,r=t.domainScale,i=r.domain();n.select(this).call(n.svg.axis().orient("left").tickSize(4).outerTickSize(2).ticks(e,t.tickFormat).tickValues(t.ordinal?i:null).tickFormat(t.ordinal?function(t){return t}:null).scale(r)),a.font(L.selectAll("text"),t.model.tickFont)}),L.selectAll(".domain, .tick>line").attr("fill","none").attr("stroke","black").attr("stroke-opacity",.25).attr("stroke-width","1px"),L.selectAll("text").style("text-shadow","1px 1px 1px #fff, -1px -1px 1px #fff, 1px -1px 1px #fff, -1px 1px 1px #fff").style("cursor","default").style("user-select","none");var z=C.selectAll("."+h.cn.axisHeading).data(c,l);z.enter().append("g").classed(h.cn.axisHeading,!0);var O=z.selectAll("."+h.cn.axisTitle).data(c,l);O.enter().append("text").classed(h.cn.axisTitle,!0).attr("text-anchor","middle").style("cursor","ew-resize").style("user-select","none").style("pointer-events","auto"),O.attr("transform","translate(0,"+-h.axisTitleOffset+")").text(function(t){return t.label}).each(function(t){a.font(n.select(this),t.model.labelFont)});var I=C.selectAll("."+h.cn.axisExtent).data(c,l);I.enter().append("g").classed(h.cn.axisExtent,!0);var D=I.selectAll("."+h.cn.axisExtentTop).data(c,l);D.enter().append("g").classed(h.cn.axisExtentTop,!0),D.attr("transform","translate(0,"+-h.axisExtentOffset+")");var P=D.selectAll("."+h.cn.axisExtentTopText).data(c,l);function R(t,e){if(t.ordinal)return"";var r=t.domainScale.domain();return n.format(t.tickFormat)(r[e?r.length-1:0])}P.enter().append("text").classed(h.cn.axisExtentTopText,!0).call(x),P.text(function(t){return R(t,!0)}).each(function(t){a.font(n.select(this),t.model.rangeFont)});var F=I.selectAll("."+h.cn.axisExtentBottom).data(c,l);F.enter().append("g").classed(h.cn.axisExtentBottom,!0),F.attr("transform",function(t){return"translate(0,"+(t.model.height+h.axisExtentOffset)+")"});var B=F.selectAll("."+h.cn.axisExtentBottomText).data(c,l);B.enter().append("text").classed(h.cn.axisExtentBottomText,!0).attr("dy","0.75em").call(x),B.text(function(t){return R(t)}).each(function(t){a.font(n.select(this),t.model.rangeFont)}),f.ensureAxisBrush(C)}},{"../../components/colorscale":586,"../../components/drawing":595,"../../lib":697,"../../lib/gup":695,"./axisbrush":1013,"./constants":1016,"./lines":1019,d3:151}],1022:[function(t,e,r){"use strict";var n=t("./parcoords"),i=t("../../lib/prepare_regl");e.exports=function(t,e){var r=t._fullLayout,a=r._toppaper,o=r._paperdiv,s=r._glcontainer;if(i(t)){var l={},c={},u={},h={},f=r._size;e.forEach(function(e,r){var n=e[0].trace;u[r]=n.index;var i=h[r]=n._fullInput.index;l[r]=t.data[i].dimensions,c[r]=t.data[i].dimensions.slice()});n(o,a,s,e,{width:f.w,height:f.h,margin:{t:f.t,r:f.r,b:f.b,l:f.l}},{filterChanged:function(e,n,i){var a=c[e][n],o=i.map(function(t){return t.slice()}),s="dimensions["+n+"].constraintrange",l=r._tracePreGUI[t._fullData[u[e]]._fullInput.uid];if(void 0===l[s]){var f=a.constraintrange;l[s]=f||null}var p=t._fullData[u[e]].dimensions[n];o.length?(1===o.length&&(o=o[0]),a.constraintrange=o,p.constraintrange=o.slice(),o=[o]):(delete a.constraintrange,delete p.constraintrange,o=null);var d={};d[s]=o,t.emit("plotly_restyle",[d,[h[e]]])},hover:function(e){t.emit("plotly_hover",e)},unhover:function(e){t.emit("plotly_unhover",e)},axesMoved:function(e,r){function n(t){return!("visible"in t)||t.visible}function i(t,e,r){var n=e.indexOf(r),i=t.indexOf(n);return-1===i&&(i+=e.length),i}var a=function(t){return function(e,n){return i(r,t,e)-i(r,t,n)}}(c[e].filter(n));l[e].sort(a),c[e].filter(function(t){return!n(t)}).sort(function(t){return c[e].indexOf(t)}).forEach(function(t){l[e].splice(l[e].indexOf(t),1),l[e].splice(c[e].indexOf(t),0,t)}),t.emit("plotly_restyle",[{dimensions:[l[e]]},[h[e]]])}})}}},{"../../lib/prepare_regl":710,"./parcoords":1021}],1023:[function(t,e,r){"use strict";var n=t("../../components/color/attributes"),i=t("../../plots/font_attributes"),a=t("../../plots/attributes"),o=t("../../components/fx/hovertemplate_attributes"),s=t("../../plots/domain").attributes,l=t("../../lib/extend").extendFlat,c=i({editType:"calc",arrayOk:!0,colorEditType:"plot"});e.exports={labels:{valType:"data_array",editType:"calc"},label0:{valType:"number",dflt:0,editType:"calc"},dlabel:{valType:"number",dflt:1,editType:"calc"},values:{valType:"data_array",editType:"calc"},marker:{colors:{valType:"data_array",editType:"calc"},line:{color:{valType:"color",dflt:n.defaultLine,arrayOk:!0,editType:"style"},width:{valType:"number",min:0,dflt:0,arrayOk:!0,editType:"style"},editType:"calc"},editType:"calc"},text:{valType:"data_array",editType:"calc"},hovertext:{valType:"string",dflt:"",arrayOk:!0,editType:"style"},scalegroup:{valType:"string",dflt:"",editType:"calc"},textinfo:{valType:"flaglist",flags:["label","text","value","percent"],extras:["none"],editType:"calc"},hoverinfo:l({},a.hoverinfo,{flags:["label","text","value","percent","name"]}),hovertemplate:o({},{keys:["label","color","value","percent","text"]}),textposition:{valType:"enumerated",values:["inside","outside","auto","none"],dflt:"auto",arrayOk:!0,editType:"calc"},textfont:l({},c,{}),insidetextfont:l({},c,{}),outsidetextfont:l({},c,{}),title:{text:{valType:"string",dflt:"",editType:"calc"},font:l({},c,{}),position:{valType:"enumerated",values:["top left","top center","top right","middle center","bottom left","bottom center","bottom right"],editType:"calc"},editType:"calc"},domain:s({name:"pie",trace:!0,editType:"calc"}),hole:{valType:"number",min:0,max:1,dflt:0,editType:"calc"},sort:{valType:"boolean",dflt:!0,editType:"calc"},direction:{valType:"enumerated",values:["clockwise","counterclockwise"],dflt:"counterclockwise",editType:"calc"},rotation:{valType:"number",min:-360,max:360,dflt:0,editType:"calc"},pull:{valType:"number",min:0,max:1,dflt:0,arrayOk:!0,editType:"calc"},_deprecated:{title:{valType:"string",dflt:"",editType:"calc"},titlefont:l({},c,{}),titleposition:{valType:"enumerated",values:["top left","top center","top right","middle center","bottom left","bottom center","bottom right"],editType:"calc"}}}},{"../../components/color/attributes":573,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plots/attributes":742,"../../plots/domain":770,"../../plots/font_attributes":771}],1024:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("../../plots/get_data").getModuleCalcData;r.name="pie",r.plot=function(t){var e=n.getModule("pie"),r=i(t.calcdata,e)[0];r.length&&e.plot(t,r)},r.clean=function(t,e,r,n){var i=n._has&&n._has("pie"),a=e._has&&e._has("pie");i&&!a&&n._pielayer.selectAll("g.trace").remove()}},{"../../plots/get_data":781,"../../registry":826}],1025:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib").isArrayOrTypedArray,a=t("tinycolor2"),o=t("../../components/color"),s=t("./helpers");r.calc=function(t,e){var r,l,c,u,h,f=e.values,p=i(f)&&f.length,d=e.labels,g=e.marker.colors||[],v=[],m=t._fullLayout,y=m._piecolormap,x={},b=0,_=m.hiddenlabels||[];if(e.dlabel)for(d=new Array(f.length),r=0;r<f.length;r++)d[r]=String(e.label0+r*e.dlabel);function w(t,e){return!!t&&(!!(t=a(t)).isValid()&&(t=o.addOpacity(t,t.getAlpha()),y[e]||(y[e]=t),t))}var k=(p?f:d).length;for(r=0;r<k;r++){if(p){if(l=f[r],!n(l))continue;if((l=+l)<0)continue}else l=1;void 0!==(c=d[r])&&""!==c||(c=r);var A=x[c=String(c)];void 0===A?(x[c]=v.length,(u=-1!==_.indexOf(c))||(b+=l),v.push({v:l,label:c,color:w(g[r],c),i:r,pts:[r],hidden:u})):((h=v[A]).v+=l,h.pts.push(r),h.hidden||(b+=l),!1===h.color&&g[r]&&(h.color=w(g[r],c)))}if(e.sort&&v.sort(function(t,e){return e.v-t.v}),v[0]&&(v[0].vTotal=b),e.textinfo&&"none"!==e.textinfo){var M,T=-1!==e.textinfo.indexOf("label"),S=-1!==e.textinfo.indexOf("text"),E=-1!==e.textinfo.indexOf("value"),C=-1!==e.textinfo.indexOf("percent"),L=m.separators;for(r=0;r<v.length;r++){if(h=v[r],M=T?[h.label]:[],S){var z=s.getFirstFilled(e.text,h.pts);z&&M.push(z)}E&&M.push(s.formatPieValue(h.v,L)),C&&M.push(s.formatPiePercent(h.v/b,L)),h.text=M.join("<br>")}}return v},r.crossTraceCalc=function(t){var e=t._fullLayout,r=t.calcdata,n=e.piecolorway,i=e._piecolormap;e.extendpiecolors&&(n=function(t){var e,r=JSON.stringify(t),n=l[r];if(!n){for(n=t.slice(),e=0;e<t.length;e++)n.push(a(t[e]).lighten(20).toHexString());for(e=0;e<t.length;e++)n.push(a(t[e]).darken(20).toHexString());l[r]=n}return n}(n));var o,s,c,u,h=0;for(o=0;o<r.length;o++)if("pie"===(c=r[o])[0].trace.type)for(s=0;s<c.length;s++)!1===(u=c[s]).color&&(i[u.label]?u.color=i[u.label]:(i[u.label]=u.color=n[h%n.length],h++))};var l={}},{"../../components/color":574,"../../lib":697,"./helpers":1028,"fast-isnumeric":218,tinycolor2:518}],1026:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./attributes"),a=t("../../plots/domain").defaults;e.exports=function(t,e,r,o){function s(r,a){return n.coerce(t,e,i,r,a)}var l,c=n.coerceFont,u=s("values"),h=n.isArrayOrTypedArray(u),f=s("labels");if(Array.isArray(f)?(l=f.length,h&&(l=Math.min(l,u.length))):h&&(l=u.length,s("label0"),s("dlabel")),l){e._length=l,s("marker.line.width")&&s("marker.line.color"),s("marker.colors"),s("scalegroup");var p=s("text"),d=s("textinfo",Array.isArray(p)?"text+percent":"percent");if(s("hovertext"),s("hovertemplate"),d&&"none"!==d){var g=s("textposition"),v=Array.isArray(g)||"auto"===g,m=v||"inside"===g,y=v||"outside"===g;if(m||y){var x=c(s,"textfont",o.font);if(m){var b=n.extendFlat({},x);!(t.textfont&&t.textfont.color)&&delete b.color,c(s,"insidetextfont",b)}y&&c(s,"outsidetextfont",x)}}a(e,o,s);var _=s("hole");if(s("title.text")){var w=s("title.position",_?"middle center":"top center");_||"middle center"!==w||(e.title.position="top center"),c(s,"title.font",o.font)}s("sort"),s("direction"),s("rotation"),s("pull")}else e.visible=!1}},{"../../lib":697,"../../plots/domain":770,"./attributes":1023}],1027:[function(t,e,r){"use strict";var n=t("../../components/fx/helpers").appendArrayMultiPointValues;e.exports=function(t,e){var r={curveNumber:e.index,pointNumbers:t.pts,data:e._input,fullData:e,label:t.label,color:t.color,value:t.v,percent:t.percent,text:t.text,v:t.v};return 1===t.pts.length&&(r.pointNumber=r.i=t.pts[0]),n(r,e,t.pts),r}},{"../../components/fx/helpers":609}],1028:[function(t,e,r){"use strict";var n=t("../../lib");r.formatPiePercent=function(t,e){var r=(100*t).toPrecision(3);return-1!==r.lastIndexOf(".")&&(r=r.replace(/[.]?0+$/,"")),n.numSeparate(r,e)+"%"},r.formatPieValue=function(t,e){var r=t.toPrecision(10);return-1!==r.lastIndexOf(".")&&(r=r.replace(/[.]?0+$/,"")),n.numSeparate(r,e)},r.getFirstFilled=function(t,e){if(Array.isArray(t))for(var r=0;r<e.length;r++){var n=t[e[r]];if(n||0===n)return n}},r.castOption=function(t,e){return Array.isArray(t)?r.getFirstFilled(t,e):t||void 0}},{"../../lib":697}],1029:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.supplyLayoutDefaults=t("./layout_defaults"),n.layoutAttributes=t("./layout_attributes");var i=t("./calc");n.calc=i.calc,n.crossTraceCalc=i.crossTraceCalc,n.plot=t("./plot"),n.style=t("./style"),n.styleOne=t("./style_one"),n.moduleType="trace",n.name="pie",n.basePlotModule=t("./base_plot"),n.categories=["pie","showLegend"],n.meta={},e.exports=n},{"./attributes":1023,"./base_plot":1024,"./calc":1025,"./defaults":1026,"./layout_attributes":1030,"./layout_defaults":1031,"./plot":1032,"./style":1033,"./style_one":1034}],1030:[function(t,e,r){"use strict";e.exports={hiddenlabels:{valType:"data_array",editType:"calc"},piecolorway:{valType:"colorlist",editType:"calc"},extendpiecolors:{valType:"boolean",dflt:!0,editType:"calc"}}},{}],1031:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./layout_attributes");e.exports=function(t,e){function r(r,a){return n.coerce(t,e,i,r,a)}r("hiddenlabels"),r("piecolorway",e.colorway),r("extendpiecolors")}},{"../../lib":697,"./layout_attributes":1030}],1032:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../components/fx"),a=t("../../components/color"),o=t("../../components/drawing"),s=t("../../lib"),l=t("../../lib/svg_text_utils"),c=t("./helpers"),u=t("./event_data");function h(t,e){if(t.v===e.vTotal&&!e.trace.hole)return 1;var r=Math.PI*Math.min(t.v/e.vTotal,.5);return Math.min(1/(1+1/Math.sin(r)),(1-e.trace.hole)/2)}function f(t,e){var r=e.pxmid[0],n=e.pxmid[1],i=t.width/2,a=t.height/2;return r<0&&(i*=-1),n<0&&(a*=-1),{scale:1,rCenter:1,rotate:0,x:i+Math.abs(a)*(i>0?1:-1)/2,y:a/(1+r*r/(n*n)),outside:!0}}function p(t,e){var r=t.trace,n=e.h*(r.domain.y[1]-r.domain.y[0]);return Math.min(t.titleBox.height,n/2)}function d(t){var e,r=t.pull;if(Array.isArray(r))for(r=0,e=0;e<t.pull.length;e++)t.pull[e]>r&&(r=t.pull[e]);return r}e.exports=function(t,e){var r=t._fullLayout;!function(t,e){for(var r,n,i=e._fullLayout,a=0;a<t.length;a++)if(r=t[a][0],(n=r.trace).title.text){var c=i.meta?s.templateString(n.title.text,{meta:i.meta}):n.title.text,u=o.tester.append("text").attr("data-notex",1).text(c).call(o.font,n.title.font).call(l.convertToTspans,e),h=o.bBox(u.node(),!0);r.titleBox={width:h.width,height:h.height},u.remove()}}(e,t),function(t,e){var r,n,i,a,o,s,l,c,u,h=[];for(i=0;i<t.length;i++)o=t[i][0],s=o.trace,r=e.w*(s.domain.x[1]-s.domain.x[0]),n=e.h*(s.domain.y[1]-s.domain.y[0]),s.title.text&&"middle center"!==s.title.position&&(n-=p(o,e)),l=d(s),o.r=Math.min(r,n)/(2+2*l),o.cx=e.l+e.w*(s.domain.x[1]+s.domain.x[0])/2,o.cy=e.t+e.h*(1-s.domain.y[0])-n/2,s.title.text&&-1!==s.title.position.indexOf("bottom")&&(o.cy-=p(o,e)),s.scalegroup&&-1===h.indexOf(s.scalegroup)&&h.push(s.scalegroup);for(a=0;a<h.length;a++){for(u=1/0,c=h[a],i=0;i<t.length;i++)(o=t[i][0]).trace.scalegroup===c&&(u=Math.min(u,o.r*o.r/o.vTotal));for(i=0;i<t.length;i++)(o=t[i][0]).trace.scalegroup===c&&(o.r=Math.sqrt(u*o.vTotal))}}(e,r._size);var g=s.makeTraceGroups(r._pielayer,e,"trace").each(function(e){var g=n.select(this),v=e[0],m=v.trace;!function(t){var e,r,n,i=t[0],a=i.trace,o=a.rotation*Math.PI/180,s=2*Math.PI/i.vTotal,l="px0",c="px1";if("counterclockwise"===a.direction){for(e=0;e<t.length&&t[e].hidden;e++);if(e===t.length)return;o+=s*t[e].v,s*=-1,l="px1",c="px0"}function u(t){return[i.r*Math.sin(t),-i.r*Math.cos(t)]}for(n=u(o),e=0;e<t.length;e++)(r=t[e]).hidden||(r[l]=n,o+=s*r.v/2,r.pxmid=u(o),r.midangle=o,o+=s*r.v/2,n=u(o),r[c]=n,r.largeArc=r.v>i.vTotal/2?1:0)}(e),g.attr("stroke-linejoin","round"),g.each(function(){var g=n.select(this).selectAll("g.slice").data(e);g.enter().append("g").classed("slice",!0),g.exit().remove();var y=[[[],[]],[[],[]]],x=!1;g.each(function(e){if(e.hidden)n.select(this).selectAll("path,g").remove();else{e.pointNumber=e.i,e.curveNumber=m.index,y[e.pxmid[1]<0?0:1][e.pxmid[0]<0?0:1].push(e);var p=v.cx,d=v.cy,g=n.select(this),b=g.selectAll("path.surface").data([e]),_=!1,w=!1;if(b.enter().append("path").classed("surface",!0).style({"pointer-events":"all"}),g.select("path.textline").remove(),g.on("mouseover",function(){var a=t._fullLayout,o=t._fullData[m.index];if(!t._dragging&&!1!==a.hovermode){var s=o.hoverinfo;if(Array.isArray(s)&&(s=i.castHoverinfo({hoverinfo:[c.castOption(s,e.pts)],_module:m._module},a,0)),"all"===s&&(s="label+text+value+percent+name"),o.hovertemplate||"none"!==s&&"skip"!==s&&s){var l=h(e,v),f=p+e.pxmid[0]*(1-l),g=d+e.pxmid[1]*(1-l),y=r.separators,x=[];if(s&&-1!==s.indexOf("label")&&x.push(e.label),e.text=c.castOption(o.hovertext||o.text,e.pts),s&&-1!==s.indexOf("text")){var b=e.text;b&&x.push(b)}e.value=e.v,e.valueLabel=c.formatPieValue(e.v,y),s&&-1!==s.indexOf("value")&&x.push(e.valueLabel),e.percent=e.v/v.vTotal,e.percentLabel=c.formatPiePercent(e.percent,y),s&&-1!==s.indexOf("percent")&&x.push(e.percentLabel);var k=m.hoverlabel,A=k.font;i.loneHover({x0:f-l*v.r,x1:f+l*v.r,y:g,text:x.join("<br>"),name:o.hovertemplate||-1!==s.indexOf("name")?o.name:void 0,idealAlign:e.pxmid[0]<0?"left":"right",color:c.castOption(k.bgcolor,e.pts)||e.color,borderColor:c.castOption(k.bordercolor,e.pts),fontFamily:c.castOption(A.family,e.pts),fontSize:c.castOption(A.size,e.pts),fontColor:c.castOption(A.color,e.pts),trace:o,hovertemplate:c.castOption(o.hovertemplate,e.pts),hovertemplateLabels:e,eventData:[u(e,o)]},{container:a._hoverlayer.node(),outerContainer:a._paper.node(),gd:t}),_=!0}t.emit("plotly_hover",{points:[u(e,o)],event:n.event}),w=!0}}).on("mouseout",function(r){var a=t._fullLayout,o=t._fullData[m.index];w&&(r.originalEvent=n.event,t.emit("plotly_unhover",{points:[u(e,o)],event:n.event}),w=!1),_&&(i.loneUnhover(a._hoverlayer.node()),_=!1)}).on("click",function(){var r=t._fullLayout,a=t._fullData[m.index];t._dragging||!1===r.hovermode||(t._hoverdata=[u(e,a)],i.click(t,n.event))}),m.pull){var k=+c.castOption(m.pull,e.pts)||0;k>0&&(p+=k*e.pxmid[0],d+=k*e.pxmid[1])}e.cxFinal=p,e.cyFinal=d;var A=m.hole;if(e.v===v.vTotal){var M="M"+(p+e.px0[0])+","+(d+e.px0[1])+L(e.px0,e.pxmid,!0,1)+L(e.pxmid,e.px0,!0,1)+"Z";A?b.attr("d","M"+(p+A*e.px0[0])+","+(d+A*e.px0[1])+L(e.px0,e.pxmid,!1,A)+L(e.pxmid,e.px0,!1,A)+"Z"+M):b.attr("d",M)}else{var T=L(e.px0,e.px1,!0,1);if(A){var S=1-A;b.attr("d","M"+(p+A*e.px1[0])+","+(d+A*e.px1[1])+L(e.px1,e.px0,!1,A)+"l"+S*e.px0[0]+","+S*e.px0[1]+T+"Z")}else b.attr("d","M"+p+","+d+"l"+e.px0[0]+","+e.px0[1]+T+"Z")}var E=c.castOption(m.textposition,e.pts),C=g.selectAll("g.slicetext").data(e.text&&"none"!==E?[0]:[]);C.enter().append("g").classed("slicetext",!0),C.exit().remove(),C.each(function(){var r=s.ensureSingle(n.select(this),"text","",function(t){t.attr("data-notex",1)});r.text(e.text).attr({class:"slicetext",transform:"","text-anchor":"middle"}).call(o.font,"outside"===E?function(t,e,r){var n=c.castOption(t.outsidetextfont.color,e.pts)||c.castOption(t.textfont.color,e.pts)||r.color,i=c.castOption(t.outsidetextfont.family,e.pts)||c.castOption(t.textfont.family,e.pts)||r.family,a=c.castOption(t.outsidetextfont.size,e.pts)||c.castOption(t.textfont.size,e.pts)||r.size;return{color:n,family:i,size:a}}(m,e,t._fullLayout.font):function(t,e,r){var n=c.castOption(t.insidetextfont.color,e.pts);!n&&t._input.textfont&&(n=c.castOption(t._input.textfont.color,e.pts));var i=c.castOption(t.insidetextfont.family,e.pts)||c.castOption(t.textfont.family,e.pts)||r.family,o=c.castOption(t.insidetextfont.size,e.pts)||c.castOption(t.textfont.size,e.pts)||r.size;return{color:n||a.contrast(e.color),family:i,size:o}}(m,e,t._fullLayout.font)).call(l.convertToTspans,t);var i,u=o.bBox(r.node());"outside"===E?i=f(u,e):(i=function(t,e,r){var n=Math.sqrt(t.width*t.width+t.height*t.height),i=t.width/t.height,a=Math.PI*Math.min(e.v/r.vTotal,.5),o=1-r.trace.hole,s=h(e,r),l={scale:s*r.r*2/n,rCenter:1-s,rotate:0};if(l.scale>=1)return l;var c=i+1/(2*Math.tan(a)),u=r.r*Math.min(1/(Math.sqrt(c*c+.5)+c),o/(Math.sqrt(i*i+o/2)+i)),f={scale:2*u/t.height,rCenter:Math.cos(u/r.r)-u*i/r.r,rotate:(180/Math.PI*e.midangle+720)%180-90},p=1/i,d=p+1/(2*Math.tan(a)),g=r.r*Math.min(1/(Math.sqrt(d*d+.5)+d),o/(Math.sqrt(p*p+o/2)+p)),v={scale:2*g/t.width,rCenter:Math.cos(g/r.r)-g/i/r.r,rotate:(180/Math.PI*e.midangle+810)%180-90},m=v.scale>f.scale?v:f;return l.scale<1&&m.scale>l.scale?m:l}(u,e,v),"auto"===E&&i.scale<1&&(r.call(o.font,m.outsidetextfont),m.outsidetextfont.family===m.insidetextfont.family&&m.outsidetextfont.size===m.insidetextfont.size||(u=o.bBox(r.node())),i=f(u,e)));var g=p+e.pxmid[0]*i.rCenter+(i.x||0),y=d+e.pxmid[1]*i.rCenter+(i.y||0);i.outside&&(e.yLabelMin=y-u.height/2,e.yLabelMid=y,e.yLabelMax=y+u.height/2,e.labelExtraX=0,e.labelExtraY=0,x=!0),r.attr("transform","translate("+g+","+y+")"+(i.scale<1?"scale("+i.scale+")":"")+(i.rotate?"rotate("+i.rotate+")":"")+"translate("+-(u.left+u.right)/2+","+-(u.top+u.bottom)/2+")")})}function L(t,r,n,i){return"a"+i*v.r+","+i*v.r+" 0 "+e.largeArc+(n?" 1 ":" 0 ")+i*(r[0]-t[0])+","+i*(r[1]-t[1])}});var b=n.select(this).selectAll("g.titletext").data(m.title.text?[0]:[]);b.enter().append("g").classed("titletext",!0),b.exit().remove(),b.each(function(){var e,i=s.ensureSingle(n.select(this),"text","",function(t){t.attr("data-notex",1)}),a=r.meta?s.templateString(m.title.text,{meta:r.meta}):m.title.text;i.text(a).attr({class:"titletext",transform:"","text-anchor":"middle"}).call(o.font,m.title.font).call(l.convertToTspans,t),e="middle center"===m.title.position?function(t){var e=Math.sqrt(t.titleBox.width*t.titleBox.width+t.titleBox.height*t.titleBox.height);return{x:t.cx,y:t.cy,scale:t.trace.hole*t.r*2/e,tx:0,ty:-t.titleBox.height/2+t.trace.title.font.size}}(v):function(t,e){var r,n,i=1,a=1,o=t.trace,s={x:t.cx,y:t.cy},l={tx:0,ty:0};l.ty+=o.title.font.size,n=d(o),-1!==o.title.position.indexOf("top")?(s.y-=(1+n)*t.r,l.ty-=t.titleBox.height):-1!==o.title.position.indexOf("bottom")&&(s.y+=(1+n)*t.r);-1!==o.title.position.indexOf("left")?(r=e.w*(o.domain.x[1]-o.domain.x[0])/2+t.r,s.x-=(1+n)*t.r,l.tx+=t.titleBox.width/2):-1!==o.title.position.indexOf("center")?r=e.w*(o.domain.x[1]-o.domain.x[0]):-1!==o.title.position.indexOf("right")&&(r=e.w*(o.domain.x[1]-o.domain.x[0])/2+t.r,s.x+=(1+n)*t.r,l.tx-=t.titleBox.width/2);return i=r/t.titleBox.width,a=p(t,e)/t.titleBox.height,{x:s.x,y:s.y,scale:Math.min(i,a),tx:l.tx,ty:l.ty}}(v,r._size),i.attr("transform","translate("+e.x+","+e.y+")"+(e.scale<1?"scale("+e.scale+")":"")+"translate("+e.tx+","+e.ty+")")}),x&&function(t,e){var r,n,i,a,o,s,l,u,h,f,p,d,g;function v(t,e){return t.pxmid[1]-e.pxmid[1]}function m(t,e){return e.pxmid[1]-t.pxmid[1]}function y(t,r){r||(r={});var i,u,h,p,d,g,v=r.labelExtraY+(n?r.yLabelMax:r.yLabelMin),m=n?t.yLabelMin:t.yLabelMax,y=n?t.yLabelMax:t.yLabelMin,x=t.cyFinal+o(t.px0[1],t.px1[1]),b=v-m;if(b*l>0&&(t.labelExtraY=b),Array.isArray(e.pull))for(u=0;u<f.length;u++)(h=f[u])===t||(c.castOption(e.pull,t.pts)||0)>=(c.castOption(e.pull,h.pts)||0)||((t.pxmid[1]-h.pxmid[1])*l>0?(p=h.cyFinal+o(h.px0[1],h.px1[1]),(b=p-m-t.labelExtraY)*l>0&&(t.labelExtraY+=b)):(y+t.labelExtraY-x)*l>0&&(i=3*s*Math.abs(u-f.indexOf(t)),d=h.cxFinal+a(h.px0[0],h.px1[0]),(g=d+i-(t.cxFinal+t.pxmid[0])-t.labelExtraX)*s>0&&(t.labelExtraX+=g)))}for(n=0;n<2;n++)for(i=n?v:m,o=n?Math.max:Math.min,l=n?1:-1,r=0;r<2;r++){for(a=r?Math.max:Math.min,s=r?1:-1,(u=t[n][r]).sort(i),h=t[1-n][r],f=h.concat(u),d=[],p=0;p<u.length;p++)void 0!==u[p].yLabelMid&&d.push(u[p]);for(g=!1,p=0;n&&p<h.length;p++)if(void 0!==h[p].yLabelMid){g=h[p];break}for(p=0;p<d.length;p++){var x=p&&d[p-1];g&&!p&&(x=g),y(d[p],x)}}}(y,m),g.each(function(t){if(t.labelExtraX||t.labelExtraY){var e=n.select(this),r=e.select("g.slicetext text");r.attr("transform","translate("+t.labelExtraX+","+t.labelExtraY+")"+r.attr("transform"));var i=t.cxFinal+t.pxmid[0],o="M"+i+","+(t.cyFinal+t.pxmid[1]),s=(t.yLabelMax-t.yLabelMin)*(t.pxmid[0]<0?-1:1)/4;if(t.labelExtraX){var l=t.labelExtraX*t.pxmid[1]/t.pxmid[0],c=t.yLabelMid+t.labelExtraY-(t.cyFinal+t.pxmid[1]);Math.abs(l)>Math.abs(c)?o+="l"+c*t.pxmid[0]/t.pxmid[1]+","+c+"H"+(i+t.labelExtraX+s):o+="l"+t.labelExtraX+","+l+"v"+(c-l)+"h"+s}else o+="V"+(t.yLabelMid+t.labelExtraY)+"h"+s;e.append("path").classed("textline",!0).call(a.stroke,m.outsidetextfont.color).attr({"stroke-width":Math.min(2,m.outsidetextfont.size/8),d:o,fill:"none"})}})})});setTimeout(function(){g.selectAll("tspan").each(function(){var t=n.select(this);t.attr("dy")&&t.attr("dy",t.attr("dy"))})},0)}},{"../../components/color":574,"../../components/drawing":595,"../../components/fx":613,"../../lib":697,"../../lib/svg_text_utils":721,"./event_data":1027,"./helpers":1028,d3:151}],1033:[function(t,e,r){"use strict";var n=t("d3"),i=t("./style_one");e.exports=function(t){t._fullLayout._pielayer.selectAll(".trace").each(function(t){var e=t[0].trace,r=n.select(this);r.style({opacity:e.opacity}),r.selectAll("path.surface").each(function(t){n.select(this).call(i,t,e)})})}},{"./style_one":1034,d3:151}],1034:[function(t,e,r){"use strict";var n=t("../../components/color"),i=t("./helpers").castOption;e.exports=function(t,e,r){var a=r.marker.line,o=i(a.color,e.pts)||n.defaultLine,s=i(a.width,e.pts)||0;t.style({"stroke-width":s}).call(n.fill,e.color).call(n.stroke,o)}},{"../../components/color":574,"./helpers":1028}],1035:[function(t,e,r){"use strict";var n=t("../scatter/attributes");e.exports={x:n.x,y:n.y,xy:{valType:"data_array",editType:"calc"},indices:{valType:"data_array",editType:"calc"},xbounds:{valType:"data_array",editType:"calc"},ybounds:{valType:"data_array",editType:"calc"},text:n.text,marker:{color:{valType:"color",arrayOk:!1,editType:"calc"},opacity:{valType:"number",min:0,max:1,dflt:1,arrayOk:!1,editType:"calc"},blend:{valType:"boolean",dflt:null,editType:"calc"},sizemin:{valType:"number",min:.1,max:2,dflt:.5,editType:"calc"},sizemax:{valType:"number",min:.1,dflt:20,editType:"calc"},border:{color:{valType:"color",arrayOk:!1,editType:"calc"},arearatio:{valType:"number",min:0,max:1,dflt:0,editType:"calc"},editType:"calc"},editType:"calc"},transforms:void 0}},{"../scatter/attributes":1048}],1036:[function(t,e,r){"use strict";var n=t("gl-pointcloud2d"),i=t("../../lib/str2rgbarray"),a=t("../../plots/cartesian/autorange").findExtremes,o=t("../scatter/get_trace_color");function s(t,e){this.scene=t,this.uid=e,this.type="pointcloud",this.pickXData=[],this.pickYData=[],this.xData=[],this.yData=[],this.textLabels=[],this.color="rgb(0, 0, 0)",this.name="",this.hoverinfo="all",this.idToIndex=new Int32Array(0),this.bounds=[0,0,0,0],this.pointcloudOptions={positions:new Float32Array(0),idToIndex:this.idToIndex,sizemin:.5,sizemax:12,color:[0,0,0,1],areaRatio:1,borderColor:[0,0,0,1]},this.pointcloud=n(t.glplot,this.pointcloudOptions),this.pointcloud._trace=this}var l=s.prototype;l.handlePick=function(t){var e=this.idToIndex[t.pointId];return{trace:this,dataCoord:t.dataCoord,traceCoord:this.pickXYData?[this.pickXYData[2*e],this.pickXYData[2*e+1]]:[this.pickXData[e],this.pickYData[e]],textLabel:Array.isArray(this.textLabels)?this.textLabels[e]:this.textLabels,color:this.color,name:this.name,pointIndex:e,hoverinfo:this.hoverinfo}},l.update=function(t){this.index=t.index,this.textLabels=t.text,this.name=t.name,this.hoverinfo=t.hoverinfo,this.bounds=[1/0,1/0,-1/0,-1/0],this.updateFast(t),this.color=o(t,{})},l.updateFast=function(t){var e,r,n,o,s,l,c=this.xData=this.pickXData=t.x,u=this.yData=this.pickYData=t.y,h=this.pickXYData=t.xy,f=t.xbounds&&t.ybounds,p=t.indices,d=this.bounds;if(h){if(n=h,e=h.length>>>1,f)d[0]=t.xbounds[0],d[2]=t.xbounds[1],d[1]=t.ybounds[0],d[3]=t.ybounds[1];else for(l=0;l<e;l++)o=n[2*l],s=n[2*l+1],o<d[0]&&(d[0]=o),o>d[2]&&(d[2]=o),s<d[1]&&(d[1]=s),s>d[3]&&(d[3]=s);if(p)r=p;else for(r=new Int32Array(e),l=0;l<e;l++)r[l]=l}else for(e=c.length,n=new Float32Array(2*e),r=new Int32Array(e),l=0;l<e;l++)o=c[l],s=u[l],r[l]=l,n[2*l]=o,n[2*l+1]=s,o<d[0]&&(d[0]=o),o>d[2]&&(d[2]=o),s<d[1]&&(d[1]=s),s>d[3]&&(d[3]=s);this.idToIndex=r,this.pointcloudOptions.idToIndex=r,this.pointcloudOptions.positions=n;var g=i(t.marker.color),v=i(t.marker.border.color),m=t.opacity*t.marker.opacity;g[3]*=m,this.pointcloudOptions.color=g;var y=t.marker.blend;if(null===y){y=c.length<100||u.length<100}this.pointcloudOptions.blend=y,v[3]*=m,this.pointcloudOptions.borderColor=v;var x=t.marker.sizemin,b=Math.max(t.marker.sizemax,t.marker.sizemin);this.pointcloudOptions.sizeMin=x,this.pointcloudOptions.sizeMax=b,this.pointcloudOptions.areaRatio=t.marker.border.arearatio,this.pointcloud.update(this.pointcloudOptions);var _=this.scene.xaxis,w=this.scene.yaxis,k=b/2||.5;t._extremes[_._id]=a(_,[d[0],d[2]],{ppad:k}),t._extremes[w._id]=a(w,[d[1],d[3]],{ppad:k})},l.dispose=function(){this.pointcloud.dispose()},e.exports=function(t,e){var r=new s(t,e.uid);return r.update(e),r}},{"../../lib/str2rgbarray":720,"../../plots/cartesian/autorange":744,"../scatter/get_trace_color":1058,"gl-pointcloud2d":285}],1037:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./attributes");e.exports=function(t,e,r){function a(r,a){return n.coerce(t,e,i,r,a)}a("x"),a("y"),a("xbounds"),a("ybounds"),t.xy&&t.xy instanceof Float32Array&&(e.xy=t.xy),t.indices&&t.indices instanceof Int32Array&&(e.indices=t.indices),a("text"),a("marker.color",r),a("marker.opacity"),a("marker.blend"),a("marker.sizemin"),a("marker.sizemax"),a("marker.border.color",r),a("marker.border.arearatio"),e._length=null}},{"../../lib":697,"./attributes":1035}],1038:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("../scatter3d/calc"),n.plot=t("./convert"),n.moduleType="trace",n.name="pointcloud",n.basePlotModule=t("../../plots/gl2d"),n.categories=["gl","gl2d","showLegend"],n.meta={},e.exports=n},{"../../plots/gl2d":784,"../scatter3d/calc":1076,"./attributes":1035,"./convert":1036,"./defaults":1037}],1039:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes"),i=t("../../plots/attributes"),a=t("../../components/color/attributes"),o=t("../../components/fx/attributes"),s=t("../../plots/domain").attributes,l=t("../../components/fx/hovertemplate_attributes"),c=t("../../components/colorscale/attributes"),u=t("../../plot_api/plot_template").templatedArray,h=t("../../lib/extend").extendFlat,f=t("../../plot_api/edit_types").overrideAll;(e.exports=f({hoverinfo:h({},i.hoverinfo,{flags:[],arrayOk:!1}),hoverlabel:o.hoverlabel,domain:s({name:"sankey",trace:!0}),orientation:{valType:"enumerated",values:["v","h"],dflt:"h"},valueformat:{valType:"string",dflt:".3s"},valuesuffix:{valType:"string",dflt:""},arrangement:{valType:"enumerated",values:["snap","perpendicular","freeform","fixed"],dflt:"snap"},textfont:n({}),node:{label:{valType:"data_array",dflt:[]},groups:{valType:"info_array",dimensions:2,freeLength:!0,dflt:[],items:{valType:"number",editType:"calc"}},color:{valType:"color",arrayOk:!0},line:{color:{valType:"color",dflt:a.defaultLine,arrayOk:!0},width:{valType:"number",min:0,dflt:.5,arrayOk:!0}},pad:{valType:"number",arrayOk:!1,min:0,dflt:20},thickness:{valType:"number",arrayOk:!1,min:1,dflt:20},hoverinfo:{valType:"enumerated",values:["all","none","skip"],dflt:"all"},hoverlabel:o.hoverlabel,hovertemplate:l({},{keys:["value","label"]})},link:{label:{valType:"data_array",dflt:[]},color:{valType:"color",arrayOk:!0},line:{color:{valType:"color",dflt:a.defaultLine,arrayOk:!0},width:{valType:"number",min:0,dflt:0,arrayOk:!0}},source:{valType:"data_array",dflt:[]},target:{valType:"data_array",dflt:[]},value:{valType:"data_array",dflt:[]},hoverinfo:{valType:"enumerated",values:["all","none","skip"],dflt:"all"},hoverlabel:o.hoverlabel,hovertemplate:l({},{keys:["value","label"]}),colorscales:u("concentrationscales",{editType:"calc",label:{valType:"string",editType:"calc",dflt:""},cmax:{valType:"number",editType:"calc",dflt:1},cmin:{valType:"number",editType:"calc",dflt:0},colorscale:h(c().colorscale,{dflt:[[0,"white"],[1,"black"]]})})}},"calc","nested")).transforms=void 0},{"../../components/color/attributes":573,"../../components/colorscale/attributes":581,"../../components/fx/attributes":604,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plot_api/edit_types":728,"../../plot_api/plot_template":735,"../../plots/attributes":742,"../../plots/domain":770,"../../plots/font_attributes":771}],1040:[function(t,e,r){"use strict";var n=t("../../plot_api/edit_types").overrideAll,i=t("../../plots/get_data").getModuleCalcData,a=t("./plot"),o=t("../../components/fx/layout_attributes");r.name="sankey",r.baseLayoutAttrOverrides=n({hoverlabel:o.hoverlabel},"plot","nested"),r.plot=function(t){var e=i(t.calcdata,"sankey")[0];a(t,e)},r.clean=function(t,e,r,n){var i=n._has&&n._has("sankey"),a=e._has&&e._has("sankey");i&&!a&&n._paperdiv.selectAll(".sankey").remove()}},{"../../components/fx/layout_attributes":614,"../../plot_api/edit_types":728,"../../plots/get_data":781,"./plot":1045}],1041:[function(t,e,r){"use strict";var n=t("strongly-connected-components"),i=t("../../lib"),a=t("../../lib/gup").wrap,o=i.isArrayOrTypedArray,s=i.isIndex,l=t("../../components/colorscale");function c(t){var e,r=t.node,a=t.link,c=[],u=o(a.color),h={},f={},p=a.colorscales.length;for(e=0;e<p;e++){var d=a.colorscales[e],g=l.extractScale(d,{cLetter:"c"}),v=l.makeColorScaleFunc(g);f[d.label]=v}var m=0;for(e=0;e<a.value.length;e++)a.source[e]>m&&(m=a.source[e]),a.target[e]>m&&(m=a.target[e]);var y,x=m+1,b=t.node.groups,_={};for(e=0;e<b.length;e++){var w=b[e];for(y=0;y<w.length;y++){var k=w[y],A=x+e;_.hasOwnProperty(k)?i.warn("Node "+k+" is already part of a group."):_[k]=A}}var M={source:[],target:[]};for(e=0;e<a.value.length;e++){var T=a.value[e],S=a.source[e],E=a.target[e];if(T>0&&s(S,x)&&s(E,x)&&(!_.hasOwnProperty(S)||!_.hasOwnProperty(E)||_[S]!==_[E])){_.hasOwnProperty(E)&&(E=_[E]),_.hasOwnProperty(S)&&(S=_[S]),E=+E,h[S=+S]=h[E]=!0;var C="";a.label&&a.label[e]&&(C=a.label[e]);var L=null;C&&f.hasOwnProperty(C)&&(L=f[C]),c.push({pointNumber:e,label:C,color:u?a.color[e]:a.color,concentrationscale:L,source:S,target:E,value:+T}),M.source.push(S),M.target.push(E)}}var z=x+b.length,O=o(r.color),I=[];for(e=0;e<z;e++)if(h[e]){var D=r.label[e];I.push({group:e>x-1,childrenNodes:[],pointNumber:e,label:D,color:O?r.color[e]:r.color})}var P=!1;return function(t,e,r){for(var a=i.init2dArray(t,0),o=0;o<Math.min(e.length,r.length);o++)if(i.isIndex(e[o],t)&&i.isIndex(r[o],t)){if(e[o]===r[o])return!0;a[e[o]].push(r[o])}return n(a).components.some(function(t){return t.length>1})}(z,M.source,M.target)&&(P=!0),{circular:P,links:c,nodes:I,groups:b,groupLookup:_}}e.exports=function(t,e){var r=c(e);return a({circular:r.circular,_nodes:r.nodes,_links:r.links,_groups:r.groups,_groupLookup:r.groupLookup})}},{"../../components/colorscale":586,"../../lib":697,"../../lib/gup":695,"strongly-connected-components":511}],1042:[function(t,e,r){"use strict";e.exports={nodeTextOffsetHorizontal:4,nodeTextOffsetVertical:3,nodePadAcross:10,sankeyIterations:50,forceIterations:5,forceTicksPerFrame:10,duration:500,ease:"linear",cn:{sankey:"sankey",sankeyLinks:"sankey-links",sankeyLink:"sankey-link",sankeyNodeSet:"sankey-node-set",sankeyNode:"sankey-node",nodeRect:"node-rect",nodeCapture:"node-capture",nodeCentered:"node-entered",nodeLabelGuide:"node-label-guide",nodeLabel:"node-label",nodeLabelTextPath:"node-label-text-path"}}},{}],1043:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./attributes"),a=t("../../components/color"),o=t("tinycolor2"),s=t("../../plots/domain").defaults,l=t("../../components/fx/hoverlabel_defaults"),c=t("../../plot_api/plot_template"),u=t("../../plots/array_container_defaults");function h(t,e){function r(r,a){return n.coerce(t,e,i.link.colorscales,r,a)}r("label"),r("cmin"),r("cmax"),r("colorscale")}e.exports=function(t,e,r,f){function p(r,a){return n.coerce(t,e,i,r,a)}var d=n.extendDeep(f.hoverlabel,t.hoverlabel),g=t.node,v=c.newContainer(e,"node");function m(t,e){return n.coerce(g,v,i.node,t,e)}m("label"),m("groups"),m("pad"),m("thickness"),m("line.color"),m("line.width"),m("hoverinfo",t.hoverinfo),l(g,v,m,d),m("hovertemplate");var y=f.colorway;m("color",v.label.map(function(t,e){return a.addOpacity(function(t){return y[t%y.length]}(e),.8)}));var x=t.link||{},b=c.newContainer(e,"link");function _(t,e){return n.coerce(x,b,i.link,t,e)}_("label"),_("source"),_("target"),_("value"),_("line.color"),_("line.width"),_("hoverinfo",t.hoverinfo),l(x,b,_,d),_("hovertemplate");var w=o(f.paper_bgcolor).getLuminance()<.333?"rgba(255, 255, 255, 0.6)":"rgba(0, 0, 0, 0.2)";_("color",n.repeat(w,b.value.length)),u(x,b,{name:"colorscales",handleItemDefaults:h}),s(e,f,p),p("orientation"),p("valueformat"),p("valuesuffix"),p("arrangement"),n.coerceFont(p,"textfont",n.extendFlat({},f.font)),e._length=null}},{"../../components/color":574,"../../components/fx/hoverlabel_defaults":611,"../../lib":697,"../../plot_api/plot_template":735,"../../plots/array_container_defaults":741,"../../plots/domain":770,"./attributes":1039,tinycolor2:518}],1044:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("./calc"),n.plot=t("./plot"),n.moduleType="trace",n.name="sankey",n.basePlotModule=t("./base_plot"),n.categories=["noOpacity"],n.meta={},e.exports=n},{"./attributes":1039,"./base_plot":1040,"./calc":1041,"./defaults":1043,"./plot":1045}],1045:[function(t,e,r){"use strict";var n=t("d3"),i=t("./render"),a=t("../../components/fx"),o=t("../../components/color"),s=t("../../lib"),l=t("./constants").cn,c=s._;function u(t){return""!==t}function h(t,e){return t.filter(function(t){return t.key===e.traceId})}function f(t,e){n.select(t).select("path").style("fill-opacity",e),n.select(t).select("rect").style("fill-opacity",e)}function p(t){n.select(t).select("text.name").style("fill","black")}function d(t){return function(e){return-1!==t.node.sourceLinks.indexOf(e.link)||-1!==t.node.targetLinks.indexOf(e.link)}}function g(t){return function(e){return-1!==e.node.sourceLinks.indexOf(t.link)||-1!==e.node.targetLinks.indexOf(t.link)}}function v(t,e,r){e&&r&&h(r,e).selectAll("."+l.sankeyLink).filter(d(e)).call(y.bind(0,e,r,!1))}function m(t,e,r){e&&r&&h(r,e).selectAll("."+l.sankeyLink).filter(d(e)).call(x.bind(0,e,r,!1))}function y(t,e,r,n){var i=n.datum().link.label;n.style("fill-opacity",function(t){if(!t.link.concentrationscale)return.4}),i&&h(e,t).selectAll("."+l.sankeyLink).filter(function(t){return t.link.label===i}).style("fill-opacity",function(t){if(!t.link.concentrationscale)return.4}),r&&h(e,t).selectAll("."+l.sankeyNode).filter(g(t)).call(v)}function x(t,e,r,n){var i=n.datum().link.label;n.style("fill-opacity",function(t){return t.tinyColorAlpha}),i&&h(e,t).selectAll("."+l.sankeyLink).filter(function(t){return t.link.label===i}).style("fill-opacity",function(t){return t.tinyColorAlpha}),r&&h(e,t).selectAll(l.sankeyNode).filter(g(t)).call(m)}function b(t,e){var r=t.hoverlabel||{},n=s.nestedProperty(r,e).get();return!Array.isArray(n)&&n}e.exports=function(t,e){var r=t._fullLayout,s=r._paper,h=r._size,d=c(t,"source:")+" ",g=c(t,"target:")+" ",_=c(t,"concentration:")+" ",w=c(t,"incoming flow count:")+" ",k=c(t,"outgoing flow count:")+" ";i(t,s,e,{width:h.w,height:h.h,margin:{t:h.t,r:h.r,b:h.b,l:h.l}},{linkEvents:{hover:function(e,r,i){!1!==t._fullLayout.hovermode&&(n.select(e).call(y.bind(0,r,i,!0)),"skip"!==r.link.trace.link.hoverinfo&&(r.link.fullData=r.link.trace,t.emit("plotly_hover",{event:n.event,points:[r.link]})))},follow:function(e,i){if(!1!==t._fullLayout.hovermode){var s=i.link.trace.link;if("none"!==s.hoverinfo&&"skip"!==s.hoverinfo){var l,c,h=t._fullLayout._paperdiv.node().getBoundingClientRect();if(i.link.circular)l=(i.link.circularPathData.leftInnerExtent+i.link.circularPathData.rightInnerExtent)/2+i.parent.translateX,c=i.link.circularPathData.verticalFullExtent+i.parent.translateY;else{var v=e.getBoundingClientRect();l=v.left+v.width/2-h.left,c=v.top+v.height/2-h.top}var m={valueLabel:n.format(i.valueFormat)(i.link.value)+i.valueSuffix};i.link.fullData=i.link.trace;var y=a.loneHover({x:l,y:c,name:m.valueLabel,text:[i.link.label||"",d+i.link.source.label,g+i.link.target.label,i.link.concentrationscale?_+n.format("%0.2f")(i.link.flow.labelConcentration):""].filter(u).join("<br>"),color:b(s,"bgcolor")||o.addOpacity(i.tinyColorHue,1),borderColor:b(s,"bordercolor"),fontFamily:b(s,"font.family"),fontSize:b(s,"font.size"),fontColor:b(s,"font.color"),idealAlign:n.event.x<l?"right":"left",hovertemplate:s.hovertemplate,hovertemplateLabels:m,eventData:[i.link]},{container:r._hoverlayer.node(),outerContainer:r._paper.node(),gd:t});i.link.concentrationscale||f(y,.65),p(y)}}},unhover:function(e,i,o){!1!==t._fullLayout.hovermode&&(n.select(e).call(x.bind(0,i,o,!0)),"skip"!==i.link.trace.link.hoverinfo&&(i.link.fullData=i.link.trace,t.emit("plotly_unhover",{event:n.event,points:[i.link]})),a.loneUnhover(r._hoverlayer.node()))},select:function(e,r){var i=r.link;i.originalEvent=n.event,t._hoverdata=[i],a.click(t,{target:!0})}},nodeEvents:{hover:function(e,r,i){!1!==t._fullLayout.hovermode&&(n.select(e).call(v,r,i),"skip"!==r.node.trace.node.hoverinfo&&(r.node.fullData=r.node.trace,t.emit("plotly_hover",{event:n.event,points:[r.node]})))},follow:function(e,i){if(!1!==t._fullLayout.hovermode){var o=i.node.trace.node;if("none"!==o.hoverinfo&&"skip"!==o.hoverinfo){var s=n.select(e).select("."+l.nodeRect),c=t._fullLayout._paperdiv.node().getBoundingClientRect(),h=s.node().getBoundingClientRect(),d=h.left-2-c.left,g=h.right+2-c.left,v=h.top+h.height/4-c.top,m={valueLabel:n.format(i.valueFormat)(i.node.value)+i.valueSuffix};i.node.fullData=i.node.trace;var y=a.loneHover({x0:d,x1:g,y:v,name:n.format(i.valueFormat)(i.node.value)+i.valueSuffix,text:[i.node.label,w+i.node.targetLinks.length,k+i.node.sourceLinks.length].filter(u).join("<br>"),color:b(o,"bgcolor")||i.tinyColorHue,borderColor:b(o,"bordercolor"),fontFamily:b(o,"font.family"),fontSize:b(o,"font.size"),fontColor:b(o,"font.color"),idealAlign:"left",hovertemplate:o.hovertemplate,hovertemplateLabels:m,eventData:[i.node]},{container:r._hoverlayer.node(),outerContainer:r._paper.node(),gd:t});f(y,.85),p(y)}}},unhover:function(e,i,o){!1!==t._fullLayout.hovermode&&(n.select(e).call(m,i,o),"skip"!==i.node.trace.node.hoverinfo&&(i.node.fullData=i.node.trace,t.emit("plotly_unhover",{event:n.event,points:[i.node]})),a.loneUnhover(r._hoverlayer.node()))},select:function(e,r,i){var o=r.node;o.originalEvent=n.event,t._hoverdata=[o],n.select(e).call(m,r,i),a.click(t,{target:!0})}}})}},{"../../components/color":574,"../../components/fx":613,"../../lib":697,"./constants":1042,"./render":1046,d3:151}],1046:[function(t,e,r){"use strict";var n=t("./constants"),i=t("d3"),a=t("tinycolor2"),o=t("../../components/color"),s=t("../../components/drawing"),l=t("@plotly/d3-sankey"),c=t("d3-sankey-circular"),u=t("d3-force"),h=t("../../lib"),f=t("../../lib/gup"),p=f.keyFun,d=f.repeat,g=f.unwrap,v=t("d3-interpolate").interpolateNumber;function m(){var t=.5;return function(e){if(e.link.circular)return r=e.link,n=r.width/2,i=r.circularPathData,"top"===r.circularLinkType?"M "+i.targetX+" "+(i.targetY+n)+" L"+i.rightInnerExtent+" "+(i.targetY+n)+"A"+(i.rightLargeArcRadius+n)+" "+(i.rightSmallArcRadius+n)+" 0 0 1 "+(i.rightFullExtent-n)+" "+(i.targetY-i.rightSmallArcRadius)+"L"+(i.rightFullExtent-n)+" "+i.verticalRightInnerExtent+"A"+(i.rightLargeArcRadius+n)+" "+(i.rightLargeArcRadius+n)+" 0 0 1 "+i.rightInnerExtent+" "+(i.verticalFullExtent-n)+"L"+i.leftInnerExtent+" "+(i.verticalFullExtent-n)+"A"+(i.leftLargeArcRadius+n)+" "+(i.leftLargeArcRadius+n)+" 0 0 1 "+(i.leftFullExtent+n)+" "+i.verticalLeftInnerExtent+"L"+(i.leftFullExtent+n)+" "+(i.sourceY-i.leftSmallArcRadius)+"A"+(i.leftLargeArcRadius+n)+" "+(i.leftSmallArcRadius+n)+" 0 0 1 "+i.leftInnerExtent+" "+(i.sourceY+n)+"L"+i.sourceX+" "+(i.sourceY+n)+"L"+i.sourceX+" "+(i.sourceY-n)+"L"+i.leftInnerExtent+" "+(i.sourceY-n)+"A"+(i.leftLargeArcRadius-n)+" "+(i.leftSmallArcRadius-n)+" 0 0 0 "+(i.leftFullExtent-n)+" "+(i.sourceY-i.leftSmallArcRadius)+"L"+(i.leftFullExtent-n)+" "+i.verticalLeftInnerExtent+"A"+(i.leftLargeArcRadius-n)+" "+(i.leftLargeArcRadius-n)+" 0 0 0 "+i.leftInnerExtent+" "+(i.verticalFullExtent+n)+"L"+i.rightInnerExtent+" "+(i.verticalFullExtent+n)+"A"+(i.rightLargeArcRadius-n)+" "+(i.rightLargeArcRadius-n)+" 0 0 0 "+(i.rightFullExtent+n)+" "+i.verticalRightInnerExtent+"L"+(i.rightFullExtent+n)+" "+(i.targetY-i.rightSmallArcRadius)+"A"+(i.rightLargeArcRadius-n)+" "+(i.rightSmallArcRadius-n)+" 0 0 0 "+i.rightInnerExtent+" "+(i.targetY-n)+"L"+i.targetX+" "+(i.targetY-n)+"Z":"M "+i.targetX+" "+(i.targetY-n)+" L"+i.rightInnerExtent+" "+(i.targetY-n)+"A"+(i.rightLargeArcRadius+n)+" "+(i.rightSmallArcRadius+n)+" 0 0 0 "+(i.rightFullExtent-n)+" "+(i.targetY+i.rightSmallArcRadius)+"L"+(i.rightFullExtent-n)+" "+i.verticalRightInnerExtent+"A"+(i.rightLargeArcRadius+n)+" "+(i.rightLargeArcRadius+n)+" 0 0 0 "+i.rightInnerExtent+" "+(i.verticalFullExtent+n)+"L"+i.leftInnerExtent+" "+(i.verticalFullExtent+n)+"A"+(i.leftLargeArcRadius+n)+" "+(i.leftLargeArcRadius+n)+" 0 0 0 "+(i.leftFullExtent+n)+" "+i.verticalLeftInnerExtent+"L"+(i.leftFullExtent+n)+" "+(i.sourceY+i.leftSmallArcRadius)+"A"+(i.leftLargeArcRadius+n)+" "+(i.leftSmallArcRadius+n)+" 0 0 0 "+i.leftInnerExtent+" "+(i.sourceY-n)+"L"+i.sourceX+" "+(i.sourceY-n)+"L"+i.sourceX+" "+(i.sourceY+n)+"L"+i.leftInnerExtent+" "+(i.sourceY+n)+"A"+(i.leftLargeArcRadius-n)+" "+(i.leftSmallArcRadius-n)+" 0 0 1 "+(i.leftFullExtent-n)+" "+(i.sourceY+i.leftSmallArcRadius)+"L"+(i.leftFullExtent-n)+" "+i.verticalLeftInnerExtent+"A"+(i.leftLargeArcRadius-n)+" "+(i.leftLargeArcRadius-n)+" 0 0 1 "+i.leftInnerExtent+" "+(i.verticalFullExtent-n)+"L"+i.rightInnerExtent+" "+(i.verticalFullExtent-n)+"A"+(i.rightLargeArcRadius-n)+" "+(i.rightLargeArcRadius-n)+" 0 0 1 "+(i.rightFullExtent+n)+" "+i.verticalRightInnerExtent+"L"+(i.rightFullExtent+n)+" "+(i.targetY+i.rightSmallArcRadius)+"A"+(i.rightLargeArcRadius-n)+" "+(i.rightSmallArcRadius-n)+" 0 0 1 "+i.rightInnerExtent+" "+(i.targetY+n)+"L"+i.targetX+" "+(i.targetY+n)+"Z";var r,n,i,a=e.link.source.x1,o=e.link.target.x0,s=v(a,o),l=s(t),c=s(1-t),u=e.link.y0-e.link.width/2,h=e.link.y0+e.link.width/2,f=e.link.y1-e.link.width/2,p=e.link.y1+e.link.width/2;return"M"+a+","+u+"C"+l+","+u+" "+c+","+f+" "+o+","+f+"L"+o+","+p+"C"+c+","+p+" "+l+","+h+" "+a+","+h+"Z"}}function y(t){t.attr("transform",function(t){return"translate("+t.node.x0.toFixed(3)+", "+t.node.y0.toFixed(3)+")"})}function x(t){t.call(y)}function b(t,e){t.call(x),e.attr("d",m())}function _(t){t.attr("width",function(t){return t.node.x1-t.node.x0}).attr("height",function(t){return t.visibleHeight})}function w(t){return t.link.width>1||t.linkLineWidth>0}function k(t){return"translate("+t.translateX+","+t.translateY+")"+(t.horizontal?"matrix(1 0 0 1 0 0)":"matrix(0 1 1 0 0 0)")}function A(t){return"translate("+(t.horizontal?0:t.labelY)+" "+(t.horizontal?t.labelY:0)+")"}function M(t){return i.svg.line()([[t.horizontal?t.left?-t.sizeAcross:t.visibleWidth+n.nodeTextOffsetHorizontal:n.nodeTextOffsetHorizontal,0],[t.horizontal?t.left?-n.nodeTextOffsetHorizontal:t.sizeAcross:t.visibleHeight-n.nodeTextOffsetHorizontal,0]])}function T(t){return t.horizontal?"matrix(1 0 0 1 0 0)":"matrix(0 1 1 0 0 0)"}function S(t){return t.horizontal?"scale(1 1)":"scale(-1 1)"}function E(t){return t.darkBackground&&!t.horizontal?"rgb(255,255,255)":"rgb(0,0,0)"}function C(t){return t.horizontal&&t.left?"100%":"0%"}function L(t,e,r){t.on(".basic",null).on("mouseover.basic",function(t){t.interactionState.dragInProgress||t.partOfGroup||(r.hover(this,t,e),t.interactionState.hovered=[this,t])}).on("mousemove.basic",function(t){t.interactionState.dragInProgress||t.partOfGroup||(r.follow(this,t),t.interactionState.hovered=[this,t])}).on("mouseout.basic",function(t){t.interactionState.dragInProgress||t.partOfGroup||(r.unhover(this,t,e),t.interactionState.hovered=!1)}).on("click.basic",function(t){t.interactionState.hovered&&(r.unhover(this,t,e),t.interactionState.hovered=!1),t.interactionState.dragInProgress||t.partOfGroup||r.select(this,t,e)})}function z(t,e,r){var a=i.behavior.drag().origin(function(t){return{x:t.node.x0+t.visibleWidth/2,y:t.node.y0+t.visibleHeight/2}}).on("dragstart",function(i){if("fixed"!==i.arrangement&&(h.raiseToTop(this),i.interactionState.dragInProgress=i.node,O(i.node),i.interactionState.hovered&&(r.nodeEvents.unhover.apply(0,i.interactionState.hovered),i.interactionState.hovered=!1),"snap"===i.arrangement)){var a=i.traceId+"|"+i.key;i.forceLayouts[a]?i.forceLayouts[a].alpha(1):function(t,e,r){!function(t){for(var e=0;e<t.length;e++)t[e].y=t[e].y0+t[e].dy/2,t[e].x=t[e].x0+t[e].dx/2}(r.graph.nodes);var i=r.graph.nodes.filter(function(t){return t.originalX===r.node.originalX}).filter(function(t){return!t.partOfGroup});r.forceLayouts[e]=u.forceSimulation(i).alphaDecay(0).force("collide",u.forceCollide().radius(function(t){return t.dy/2+r.nodePad/2}).strength(1).iterations(n.forceIterations)).force("constrain",function(t,e,r,i){return function(){for(var t=0,a=0;a<r.length;a++){var o=r[a];o===i.interactionState.dragInProgress?(o.x=o.lastDraggedX,o.y=o.lastDraggedY):(o.vx=(o.originalX-o.x)/n.forceTicksPerFrame,o.y=Math.min(i.size-o.dy/2,Math.max(o.dy/2,o.y))),t=Math.max(t,Math.abs(o.vx),Math.abs(o.vy))}!i.interactionState.dragInProgress&&t<.1&&i.forceLayouts[e].alpha()>0&&i.forceLayouts[e].alpha(0)}}(0,e,i,r)).stop()}(0,a,i),function(t,e,r,i){window.requestAnimationFrame(function a(){var o;for(o=0;o<n.forceTicksPerFrame;o++)r.forceLayouts[i].tick();var s=r.graph.nodes;!function(t){for(var e=0;e<t.length;e++)t[e].y0=t[e].y-t[e].dy/2,t[e].y1=t[e].y0+t[e].dy,t[e].x0=t[e].x-t[e].dx/2,t[e].x1=t[e].x0+t[e].dx}(s),r.sankey.update(r.graph),b(t.filter(I(r)),e),r.forceLayouts[i].alpha()>0&&window.requestAnimationFrame(a)})}(t,e,i,a)}}).on("drag",function(r){if("fixed"!==r.arrangement){var n=i.event.x,a=i.event.y;"snap"===r.arrangement?(r.node.x0=n-r.visibleWidth/2,r.node.x1=n+r.visibleWidth/2,r.node.y0=a-r.visibleHeight/2,r.node.y1=a+r.visibleHeight/2):("freeform"===r.arrangement&&(r.node.x0=n-r.visibleWidth/2,r.node.x1=n+r.visibleWidth/2),r.node.y0=Math.max(0,Math.min(r.size-r.visibleHeight,a)),r.node.y1=r.node.y0+r.visibleHeight),O(r.node),"snap"!==r.arrangement&&(r.sankey.update(r.graph),b(t.filter(I(r)),e))}}).on("dragend",function(t){t.interactionState.dragInProgress=!1;for(var e=0;e<t.node.childrenNodes.length;e++)t.node.childrenNodes[e].x=t.node.x,t.node.childrenNodes[e].y=t.node.y});t.on(".drag",null).call(a)}function O(t){t.lastDraggedX=t.x0+t.dx/2,t.lastDraggedY=t.y0+t.dy/2}function I(t){return function(e){return e.node.originalX===t.node.originalX}}e.exports=function(t,e,r,i,u){var f=!1;h.ensureSingle(t._fullLayout._infolayer,"g","first-render",function(){f=!0});var v=r.filter(function(t){return g(t).trace.visible}).map(function(t,e,r){var i,a=g(e),o=a.trace,s=o.domain,u="h"===o.orientation,f=o.node.pad,p=o.node.thickness,d=t.width*(s.x[1]-s.x[0]),v=t.height*(s.y[1]-s.y[0]),m=a._nodes,y=a._links,x=a.circular;(i=x?c.sankeyCircular().circularLinkGap(0):l.sankey()).iterations(n.sankeyIterations).size(u?[d,v]:[v,d]).nodeWidth(p).nodePadding(f).nodeId(function(t){return t.pointNumber}).nodes(m).links(y);var b=i();for(var _ in i.nodePadding()<f&&h.warn("node.pad was reduced to ",i.nodePadding()," to fit within the figure."),a._groupLookup){for(var w,k=parseInt(a._groupLookup[_]),A=0;A<b.nodes.length;A++)if(b.nodes[A].pointNumber===k){w=b.nodes[A];break}if(w){var M={pointNumber:parseInt(_),x0:w.x0,x1:w.x1,y0:w.y0,y1:w.y1,partOfGroup:!0,sourceLinks:[],targetLinks:[]};b.nodes.unshift(M),w.childrenNodes.unshift(M)}}return function(){var t,e,r;for(t=0;t<b.nodes.length;t++){var n,i,a=b.nodes[t],o={};for(e=0;e<a.targetLinks.length;e++)n=(i=a.targetLinks[e]).source.pointNumber+":"+i.target.pointNumber,o.hasOwnProperty(n)||(o[n]=[]),o[n].push(i);var s=Object.keys(o);for(e=0;e<s.length;e++){var l=o[n=s[e]],c=0,u={};for(r=0;r<l.length;r++)u[(i=l[r]).label]||(u[i.label]=0),u[i.label]+=i.value,c+=i.value;for(r=0;r<l.length;r++)(i=l[r]).flow={value:c,labelConcentration:u[i.label]/c,concentration:i.value/c,links:l}}var h=0;for(e=0;e<a.sourceLinks.length;e++)h+=a.sourceLinks[e].value;for(e=0;e<a.sourceLinks.length;e++)(i=a.sourceLinks[e]).concentrationOut=i.value/h;var f=0;for(e=0;e<a.targetLinks.length;e++)f+=a.targetLinks[e].value;for(e=0;e<a.targetLinks.length;e++)(i=a.targetLinks[e]).concenrationIn=i.value/f}}(),{circular:x,key:r,trace:o,guid:h.randstr(),horizontal:u,width:d,height:v,nodePad:o.node.pad,nodeLineColor:o.node.line.color,nodeLineWidth:o.node.line.width,linkLineColor:o.link.line.color,linkLineWidth:o.link.line.width,valueFormat:o.valueformat,valueSuffix:o.valuesuffix,textFont:o.textfont,translateX:s.x[0]*t.width+t.margin.l,translateY:t.height-s.y[1]*t.height+t.margin.t,dragParallel:u?v:d,dragPerpendicular:u?d:v,arrangement:o.arrangement,sankey:i,graph:b,forceLayouts:{},interactionState:{dragInProgress:!1,hovered:!1}}}.bind(null,i)),x=e.selectAll("."+n.cn.sankey).data(v,p);x.exit().remove(),x.enter().append("g").classed(n.cn.sankey,!0).style("box-sizing","content-box").style("position","absolute").style("left",0).style("shape-rendering","geometricPrecision").style("pointer-events","auto").attr("transform",k),x.transition().ease(n.ease).duration(n.duration).attr("transform",k);var b=x.selectAll("."+n.cn.sankeyLinks).data(d,p);b.enter().append("g").classed(n.cn.sankeyLinks,!0).style("fill","none");var O=b.selectAll("."+n.cn.sankeyLink).data(function(t){return t.graph.links.filter(function(t){return t.value}).map(function(t,e,r){var n=a(e.color);e.concentrationscale&&(n=a(e.concentrationscale(e.flow.labelConcentration)));var i=e.source.label+"|"+e.target.label+"__"+r;return e.trace=t.trace,e.curveNumber=t.trace.index,{circular:t.circular,key:i,traceId:t.key,pointNumber:e.pointNumber,link:e,tinyColorHue:o.tinyRGB(n),tinyColorAlpha:n.getAlpha(),linkPath:m,linkLineColor:t.linkLineColor,linkLineWidth:t.linkLineWidth,valueFormat:t.valueFormat,valueSuffix:t.valueSuffix,sankey:t.sankey,parent:t,interactionState:t.interactionState,flow:e.flow}}.bind(null,t))},p);O.enter().append("path").classed(n.cn.sankeyLink,!0).call(L,x,u.linkEvents),O.style("stroke",function(t){return w(t)?o.tinyRGB(a(t.linkLineColor)):t.tinyColorHue}).style("stroke-opacity",function(t){return w(t)?o.opacity(t.linkLineColor):t.tinyColorAlpha}).style("fill",function(t){return t.tinyColorHue}).style("fill-opacity",function(t){return t.tinyColorAlpha}).style("stroke-width",function(t){return w(t)?t.linkLineWidth:1}).attr("d",m()),O.style("opacity",function(){return t._context.staticPlot||f?1:0}).transition().ease(n.ease).duration(n.duration).style("opacity",1),O.exit().transition().ease(n.ease).duration(n.duration).style("opacity",0).remove();var I=x.selectAll("."+n.cn.sankeyNodeSet).data(d,p);I.enter().append("g").classed(n.cn.sankeyNodeSet,!0),I.style("cursor",function(t){switch(t.arrangement){case"fixed":return"default";case"perpendicular":return"ns-resize";default:return"move"}});var D=I.selectAll("."+n.cn.sankeyNode).data(function(t){var e=t.graph.nodes;return function(t){var e,r=[];for(e=0;e<t.length;e++)t[e].originalX=(t[e].x0+t[e].x1)/2,t[e].originalY=(t[e].y0+t[e].y1)/2,-1===r.indexOf(t[e].originalX)&&r.push(t[e].originalX);for(r.sort(function(t,e){return t-e}),e=0;e<t.length;e++)t[e].originalLayerIndex=r.indexOf(t[e].originalX),t[e].originalLayer=t[e].originalLayerIndex/(r.length-1)}(e),e.map(function(t,e){var r=a(e.color),i=n.nodePadAcross,s=t.nodePad/2;e.dx=e.x1-e.x0,e.dy=e.y1-e.y0;var l=e.dx,c=Math.max(.5,e.dy),u="node_"+e.pointNumber;return e.group&&(u=h.randstr()),e.trace=t.trace,e.curveNumber=t.trace.index,{index:e.pointNumber,key:u,partOfGroup:e.partOfGroup||!1,group:e.group,traceId:t.key,node:e,nodePad:t.nodePad,nodeLineColor:t.nodeLineColor,nodeLineWidth:t.nodeLineWidth,textFont:t.textFont,size:t.horizontal?t.height:t.width,visibleWidth:Math.ceil(l),visibleHeight:c,zoneX:-i,zoneY:-s,zoneWidth:l+2*i,zoneHeight:c+2*s,labelY:t.horizontal?e.dy/2+1:e.dx/2+1,left:1===e.originalLayer,sizeAcross:t.width,forceLayouts:t.forceLayouts,horizontal:t.horizontal,darkBackground:r.getBrightness()<=128,tinyColorHue:o.tinyRGB(r),tinyColorAlpha:r.getAlpha(),valueFormat:t.valueFormat,valueSuffix:t.valueSuffix,sankey:t.sankey,graph:t.graph,arrangement:t.arrangement,uniqueNodeLabelPathId:[t.guid,t.key,u].join("_"),interactionState:t.interactionState}}.bind(null,t))},p);D.enter().append("g").classed(n.cn.sankeyNode,!0).call(y).style("opacity",function(e){return!t._context.staticPlot&&!f||e.partOfGroup?0:1}),D.call(L,x,u.nodeEvents).call(z,O,u),D.transition().ease(n.ease).duration(n.duration).call(y).style("opacity",function(t){return t.partOfGroup?0:1}),D.exit().transition().ease(n.ease).duration(n.duration).style("opacity",0).remove();var P=D.selectAll("."+n.cn.nodeRect).data(d);P.enter().append("rect").classed(n.cn.nodeRect,!0).call(_),P.style("stroke-width",function(t){return t.nodeLineWidth}).style("stroke",function(t){return o.tinyRGB(a(t.nodeLineColor))}).style("stroke-opacity",function(t){return o.opacity(t.nodeLineColor)}).style("fill",function(t){return t.tinyColorHue}).style("fill-opacity",function(t){return t.tinyColorAlpha}),P.transition().ease(n.ease).duration(n.duration).call(_);var R=D.selectAll("."+n.cn.nodeCapture).data(d);R.enter().append("rect").classed(n.cn.nodeCapture,!0).style("fill-opacity",0),R.attr("x",function(t){return t.zoneX}).attr("y",function(t){return t.zoneY}).attr("width",function(t){return t.zoneWidth}).attr("height",function(t){return t.zoneHeight});var F=D.selectAll("."+n.cn.nodeCentered).data(d);F.enter().append("g").classed(n.cn.nodeCentered,!0).attr("transform",A),F.transition().ease(n.ease).duration(n.duration).attr("transform",A);var B=F.selectAll("."+n.cn.nodeLabelGuide).data(d);B.enter().append("path").classed(n.cn.nodeLabelGuide,!0).attr("id",function(t){return t.uniqueNodeLabelPathId}).attr("d",M).attr("transform",T),B.transition().ease(n.ease).duration(n.duration).attr("d",M).attr("transform",T);var N=F.selectAll("."+n.cn.nodeLabel).data(d);N.enter().append("text").classed(n.cn.nodeLabel,!0).attr("transform",S).style("user-select","none").style("cursor","default").style("fill","black"),N.style("text-shadow",function(t){return t.horizontal?"-1px 1px 1px #fff, 1px 1px 1px #fff, 1px -1px 1px #fff, -1px -1px 1px #fff":"none"}).each(function(t){s.font(N,t.textFont)}),N.transition().ease(n.ease).duration(n.duration).attr("transform",S);var j=N.selectAll("."+n.cn.nodeLabelTextPath).data(d);j.enter().append("textPath").classed(n.cn.nodeLabelTextPath,!0).attr("alignment-baseline","middle").attr("xlink:href",function(t){return"#"+t.uniqueNodeLabelPathId}).attr("startOffset",C).style("fill",E),j.text(function(t){return t.horizontal||t.node.dy>5?t.node.label:""}).attr("text-anchor",function(t){return t.horizontal&&t.left?"end":"start"}),j.transition().ease(n.ease).duration(n.duration).attr("startOffset",C).style("fill",E)}},{"../../components/color":574,"../../components/drawing":595,"../../lib":697,"../../lib/gup":695,"./constants":1042,"@plotly/d3-sankey":46,d3:151,"d3-force":144,"d3-interpolate":145,"d3-sankey-circular":148,tinycolor2:518}],1047:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e){for(var r=0;r<t.length;r++)t[r].i=r;n.mergeArray(e.text,t,"tx"),n.mergeArray(e.hovertext,t,"htx"),n.mergeArray(e.customdata,t,"data"),n.mergeArray(e.textposition,t,"tp"),e.textfont&&(n.mergeArray(e.textfont.size,t,"ts"),n.mergeArray(e.textfont.color,t,"tc"),n.mergeArray(e.textfont.family,t,"tf"));var i=e.marker;if(i){n.mergeArray(i.size,t,"ms"),n.mergeArray(i.opacity,t,"mo"),n.mergeArray(i.symbol,t,"mx"),n.mergeArray(i.color,t,"mc");var a=i.line;i.line&&(n.mergeArray(a.color,t,"mlc"),n.mergeArray(a.width,t,"mlw"));var o=i.gradient;o&&"none"!==o.type&&(n.mergeArray(o.type,t,"mgt"),n.mergeArray(o.color,t,"mgc"))}}},{"../../lib":697}],1048:[function(t,e,r){"use strict";var n=t("../../components/fx/hovertemplate_attributes"),i=t("../../components/colorscale/attributes"),a=t("../../components/colorbar/attributes"),o=t("../../plots/font_attributes"),s=t("../../components/drawing/attributes").dash,l=t("../../components/drawing"),c=t("./constants"),u=t("../../lib/extend").extendFlat;e.exports={x:{valType:"data_array",editType:"calc+clearAxisTypes",anim:!0},x0:{valType:"any",dflt:0,editType:"calc+clearAxisTypes",anim:!0},dx:{valType:"number",dflt:1,editType:"calc",anim:!0},y:{valType:"data_array",editType:"calc+clearAxisTypes",anim:!0},y0:{valType:"any",dflt:0,editType:"calc+clearAxisTypes",anim:!0},dy:{valType:"number",dflt:1,editType:"calc",anim:!0},stackgroup:{valType:"string",dflt:"",editType:"calc"},orientation:{valType:"enumerated",values:["v","h"],editType:"calc"},groupnorm:{valType:"enumerated",values:["","fraction","percent"],dflt:"",editType:"calc"},stackgaps:{valType:"enumerated",values:["infer zero","interpolate"],dflt:"infer zero",editType:"calc"},text:{valType:"string",dflt:"",arrayOk:!0,editType:"calc"},hovertext:{valType:"string",dflt:"",arrayOk:!0,editType:"style"},mode:{valType:"flaglist",flags:["lines","markers","text"],extras:["none"],editType:"calc"},hoveron:{valType:"flaglist",flags:["points","fills"],editType:"style"},hovertemplate:n({},{keys:c.eventDataKeys}),line:{color:{valType:"color",editType:"style",anim:!0},width:{valType:"number",min:0,dflt:2,editType:"style",anim:!0},shape:{valType:"enumerated",values:["linear","spline","hv","vh","hvh","vhv"],dflt:"linear",editType:"plot"},smoothing:{valType:"number",min:0,max:1.3,dflt:1,editType:"plot"},dash:u({},s,{editType:"style"}),simplify:{valType:"boolean",dflt:!0,editType:"plot"},editType:"plot"},connectgaps:{valType:"boolean",dflt:!1,editType:"calc"},cliponaxis:{valType:"boolean",dflt:!0,editType:"plot"},fill:{valType:"enumerated",values:["none","tozeroy","tozerox","tonexty","tonextx","toself","tonext"],editType:"calc"},fillcolor:{valType:"color",editType:"style",anim:!0},marker:u({symbol:{valType:"enumerated",values:l.symbolList,dflt:"circle",arrayOk:!0,editType:"style"},opacity:{valType:"number",min:0,max:1,arrayOk:!0,editType:"style",anim:!0},size:{valType:"number",min:0,dflt:6,arrayOk:!0,editType:"calc",anim:!0},maxdisplayed:{valType:"number",min:0,dflt:0,editType:"plot"},sizeref:{valType:"number",dflt:1,editType:"calc"},sizemin:{valType:"number",min:0,dflt:0,editType:"calc"},sizemode:{valType:"enumerated",values:["diameter","area"],dflt:"diameter",editType:"calc"},colorbar:a,line:u({width:{valType:"number",min:0,arrayOk:!0,editType:"style",anim:!0},editType:"calc"},i("marker.line",{anim:!0})),gradient:{type:{valType:"enumerated",values:["radial","horizontal","vertical","none"],arrayOk:!0,dflt:"none",editType:"calc"},color:{valType:"color",arrayOk:!0,editType:"calc"},editType:"calc"},editType:"calc"},i("marker",{anim:!0})),selected:{marker:{opacity:{valType:"number",min:0,max:1,editType:"style"},color:{valType:"color",editType:"style"},size:{valType:"number",min:0,editType:"style"},editType:"style"},textfont:{color:{valType:"color",editType:"style"},editType:"style"},editType:"style"},unselected:{marker:{opacity:{valType:"number",min:0,max:1,editType:"style"},color:{valType:"color",editType:"style"},size:{valType:"number",min:0,editType:"style"},editType:"style"},textfont:{color:{valType:"color",editType:"style"},editType:"style"},editType:"style"},textposition:{valType:"enumerated",values:["top left","top center","top right","middle left","middle center","middle right","bottom left","bottom center","bottom right"],dflt:"middle center",arrayOk:!0,editType:"calc"},textfont:o({editType:"calc",colorEditType:"style",arrayOk:!0}),r:{valType:"data_array",editType:"calc"},t:{valType:"data_array",editType:"calc"}}},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/drawing":595,"../../components/drawing/attributes":594,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plots/font_attributes":771,"./constants":1052}],1049:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("../../plots/cartesian/axes"),o=t("../../constants/numerical").BADNUM,s=t("./subtypes"),l=t("./colorscale_calc"),c=t("./arrays_to_calcdata"),u=t("./calc_selection");function h(t,e,r,n,i,o,l){var c=e._length,u=t._fullLayout,h=r._id,f=n._id,p=u._firstScatter[d(e)]===e.uid,v=(g(e,u,r,n)||{}).orientation,m=e.fill;r._minDtick=0,n._minDtick=0;var y={padded:!0},x={padded:!0};l&&(y.ppad=x.ppad=l);var b=c<2||i[0]!==i[c-1]||o[0]!==o[c-1];b&&("tozerox"===m||"tonextx"===m&&(p||"h"===v))?y.tozero=!0:(e.error_y||{}).visible||"tonexty"!==m&&"tozeroy"!==m&&(s.hasMarkers(e)||s.hasText(e))||(y.padded=!1,y.ppad=0),b&&("tozeroy"===m||"tonexty"===m&&(p||"v"===v))?x.tozero=!0:"tonextx"!==m&&"tozerox"!==m||(x.padded=!1),h&&(e._extremes[h]=a.findExtremes(r,i,y)),f&&(e._extremes[f]=a.findExtremes(n,o,x))}function f(t,e){if(s.hasMarkers(t)){var r,n=t.marker,o=1.6*(t.marker.sizeref||1);if(r="area"===t.marker.sizemode?function(t){return Math.max(Math.sqrt((t||0)/o),3)}:function(t){return Math.max((t||0)/o,3)},i.isArrayOrTypedArray(n.size)){var l={type:"linear"};a.setConvert(l);for(var c=l.makeCalcdata(t.marker,"size"),u=new Array(e),h=0;h<e;h++)u[h]=r(c[h]);return u}return r(n.size)}}function p(t,e){var r=d(e),n=t._firstScatter;n[r]||(n[r]=e.uid)}function d(t){var e=t.stackgroup;return t.xaxis+t.yaxis+t.type+(e?"-"+e:"")}function g(t,e,r,n){var i=t.stackgroup;if(i){var a=e._scatterStackOpts[r._id+n._id][i],o="v"===a.orientation?n:r;return"linear"===o.type||"log"===o.type?a:void 0}}e.exports={calc:function(t,e){var r,s,d,v,m,y,x=t._fullLayout,b=a.getFromId(t,e.xaxis||"x"),_=a.getFromId(t,e.yaxis||"y"),w=b.makeCalcdata(e,"x"),k=_.makeCalcdata(e,"y"),A=e._length,M=new Array(A),T=e.ids,S=g(e,x,b,_),E=!1;p(x,e);var C,L="x",z="y";for(S?(S.traceIndices.push(e.index),(r="v"===S.orientation)?(z="s",C="x"):(L="s",C="y"),m="interpolate"===S.stackgaps):h(t,e,b,_,w,k,f(e,A)),s=0;s<A;s++){var O=M[s]={},I=n(w[s]),D=n(k[s]);I&&D?(O[L]=w[s],O[z]=k[s]):S&&(r?I:D)?(O[C]=r?w[s]:k[s],O.gap=!0,m?(O.s=o,E=!0):O.s=0):O[L]=O[z]=o,T&&(O.id=String(T[s]))}if(c(M,e),l(t,e),u(M,e),S){for(s=0;s<M.length;)M[s][C]===o?M.splice(s,1):s++;if(i.sort(M,function(t,e){return t[C]-e[C]||t.i-e.i}),E){for(s=0;s<M.length-1&&M[s].gap;)s++;for((y=M[s].s)||(y=M[s].s=0),d=0;d<s;d++)M[d].s=y;for(v=M.length-1;v>s&&M[v].gap;)v--;for(y=M[v].s,d=M.length-1;d>v;d--)M[d].s=y;for(;s<v;)if(M[++s].gap){for(d=s+1;M[d].gap;)d++;for(var P=M[s-1][C],R=M[s-1].s,F=(M[d].s-R)/(M[d][C]-P);s<d;)M[s].s=R+(M[s][C]-P)*F,s++}}}return M},calcMarkerSize:f,calcAxisExpansion:h,setFirstScatter:p,getStackOpts:g}},{"../../constants/numerical":674,"../../lib":697,"../../plots/cartesian/axes":745,"./arrays_to_calcdata":1047,"./calc_selection":1050,"./colorscale_calc":1051,"./subtypes":1072,"fast-isnumeric":218}],1050:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e){n.isArrayOrTypedArray(e.selectedpoints)&&n.tagSelected(t,e)}},{"../../lib":697}],1051:[function(t,e,r){"use strict";var n=t("../../components/colorscale/helpers").hasColorscale,i=t("../../components/colorscale/calc"),a=t("./subtypes");e.exports=function(t,e){a.hasLines(e)&&n(e,"line")&&i(t,e,{vals:e.line.color,containerStr:"line",cLetter:"c"}),a.hasMarkers(e)&&(n(e,"marker")&&i(t,e,{vals:e.marker.color,containerStr:"marker",cLetter:"c"}),n(e,"marker.line")&&i(t,e,{vals:e.marker.line.color,containerStr:"marker.line",cLetter:"c"}))}},{"../../components/colorscale/calc":582,"../../components/colorscale/helpers":585,"./subtypes":1072}],1052:[function(t,e,r){"use strict";e.exports={PTS_LINESONLY:20,minTolerance:.2,toleranceGrowth:10,maxScreensAway:20,eventDataKeys:[]}},{}],1053:[function(t,e,r){"use strict";var n=t("./calc");function i(t,e,r,n,i,a,o){i[n]=!0;var s={i:null,gap:!0,s:0};if(s[o]=r,t.splice(e,0,s),e&&r===t[e-1][o]){var l=t[e-1];s.s=l.s,s.i=l.i,s.gap=l.gap}else a&&(s.s=function(t,e,r,n){var i=t[e-1],a=t[e+1];return a?i?i.s+(a.s-i.s)*(r-i[n])/(a[n]-i[n]):a.s:i.s}(t,e,r,o));e||(t[0].t=t[1].t,t[0].trace=t[1].trace,delete t[1].t,delete t[1].trace)}e.exports=function(t,e){var r=e.xaxis,a=e.yaxis,o=r._id+a._id,s=t._fullLayout._scatterStackOpts[o];if(s){var l,c,u,h,f,p,d,g,v,m,y,x,b,_,w,k=t.calcdata;for(var A in s){var M=(m=s[A]).traceIndices;if(M.length){for(y="interpolate"===m.stackgaps,x=m.groupnorm,"v"===m.orientation?(b="x",_="y"):(b="y",_="x"),w=new Array(M.length),l=0;l<w.length;l++)w[l]=!1;p=k[M[0]];var T=new Array(p.length);for(l=0;l<p.length;l++)T[l]=p[l][b];for(l=1;l<M.length;l++){for(f=k[M[l]],c=u=0;c<f.length;c++){for(d=f[c][b];d>T[u]&&u<T.length;u++)i(f,c,T[u],l,w,y,b),c++;if(d!==T[u]){for(h=0;h<l;h++)i(k[M[h]],u,d,h,w,y,b);T.splice(u,0,d)}u++}for(;u<T.length;u++)i(f,c,T[u],l,w,y,b),c++}var S=T.length;for(c=0;c<p.length;c++){for(g=p[c][_]=p[c].s,l=1;l<M.length;l++)(f=k[M[l]])[0].trace._rawLength=f[0].trace._length,f[0].trace._length=S,g+=f[c].s,f[c][_]=g;if(x)for(v=("fraction"===x?g:g/100)||1,l=0;l<M.length;l++){var E=k[M[l]][c];E[_]/=v,E.sNorm=E.s/v}}for(l=0;l<M.length;l++){var C=(f=k[M[l]])[0].trace,L=n.calcMarkerSize(C,C._rawLength),z=Array.isArray(L);if(L&&w[l]||z){var O=L;for(L=new Array(S),c=0;c<S;c++)L[c]=f[c].gap?0:z?O[f[c].i]:O}var I=new Array(S),D=new Array(S);for(c=0;c<S;c++)I[c]=f[c].x,D[c]=f[c].y;n.calcAxisExpansion(t,C,r,a,I,D,L),f[0].t.orientation=m.orientation}}}}}},{"./calc":1049}],1054:[function(t,e,r){"use strict";e.exports=function(t){for(var e=0;e<t.length;e++){var r=t[e];if("scatter"===r.type){var n=r.fill;if("none"!==n&&"toself"!==n&&(r.opacity=void 0,"tonexty"===n||"tonextx"===n))for(var i=e-1;i>=0;i--){var a=t[i];if("scatter"===a.type&&a.xaxis===r.xaxis&&a.yaxis===r.yaxis){a.opacity=void 0;break}}}}}},{}],1055:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../registry"),a=t("./attributes"),o=t("./constants"),s=t("./subtypes"),l=t("./xy_defaults"),c=t("./stack_defaults"),u=t("./marker_defaults"),h=t("./line_defaults"),f=t("./line_shape_defaults"),p=t("./text_defaults"),d=t("./fillcolor_defaults");e.exports=function(t,e,r,g){function v(r,i){return n.coerce(t,e,a,r,i)}var m=l(t,e,g,v);if(m||(e.visible=!1),e.visible){var y=c(t,e,g,v),x=!y&&m<o.PTS_LINESONLY?"lines+markers":"lines";v("text"),v("hovertext"),v("mode",x),s.hasLines(e)&&(h(t,e,r,g,v),f(t,e,v),v("connectgaps"),v("line.simplify")),s.hasMarkers(e)&&u(t,e,r,g,v,{gradient:!0}),s.hasText(e)&&p(t,e,g,v);var b=[];(s.hasMarkers(e)||s.hasText(e))&&(v("cliponaxis"),v("marker.maxdisplayed"),b.push("points")),v("fill",y?y.fillDflt:"none"),"none"!==e.fill&&(d(t,e,r,v),s.hasLines(e)||f(t,e,v));var _=(e.line||{}).color,w=(e.marker||{}).color;"tonext"!==e.fill&&"toself"!==e.fill||b.push("fills"),v("hoveron",b.join("+")||"points"),"fills"!==e.hoveron&&v("hovertemplate");var k=i.getComponentMethod("errorbars","supplyDefaults");k(t,e,_||w||r,{axis:"y"}),k(t,e,_||w||r,{axis:"x",inherit:"y"}),n.coerceSelectionMarkerOpacity(e,v)}}},{"../../lib":697,"../../registry":826,"./attributes":1048,"./constants":1052,"./fillcolor_defaults":1057,"./line_defaults":1061,"./line_shape_defaults":1063,"./marker_defaults":1067,"./stack_defaults":1070,"./subtypes":1072,"./text_defaults":1073,"./xy_defaults":1074}],1056:[function(t,e,r){"use strict";var n=t("../../lib");function i(t){return t||0===t}e.exports=function(t,e,r){var a=Array.isArray(r)?function(t){r.push(t)}:function(t){r.text=t},o=n.extractOption(t,e,"htx","hovertext");if(i(o))return a(o);var s=n.extractOption(t,e,"tx","text");return i(s)?a(s):void 0}},{"../../lib":697}],1057:[function(t,e,r){"use strict";var n=t("../../components/color"),i=t("../../lib").isArrayOrTypedArray;e.exports=function(t,e,r,a){var o=!1;if(e.marker){var s=e.marker.color,l=(e.marker.line||{}).color;s&&!i(s)?o=s:l&&!i(l)&&(o=l)}a("fillcolor",n.addOpacity((e.line||{}).color||o||r,.5))}},{"../../components/color":574,"../../lib":697}],1058:[function(t,e,r){"use strict";var n=t("../../components/color"),i=t("./subtypes");e.exports=function(t,e){var r,a;if("lines"===t.mode)return(r=t.line.color)&&n.opacity(r)?r:t.fillcolor;if("none"===t.mode)return t.fill?t.fillcolor:"";var o=e.mcc||(t.marker||{}).color,s=e.mlcc||((t.marker||{}).line||{}).color;return(a=o&&n.opacity(o)?o:s&&n.opacity(s)&&(e.mlw||((t.marker||{}).line||{}).width)?s:"")?n.opacity(a)<.3?n.addOpacity(a,.3):a:(r=(t.line||{}).color)&&n.opacity(r)&&i.hasLines(t)&&t.line.width?r:t.fillcolor}},{"../../components/color":574,"./subtypes":1072}],1059:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/fx"),a=t("../../registry"),o=t("./get_trace_color"),s=t("../../components/color"),l=t("./fill_hover_text");e.exports=function(t,e,r,c){var u=t.cd,h=u[0].trace,f=t.xa,p=t.ya,d=f.c2p(e),g=p.c2p(r),v=[d,g],m=h.hoveron||"",y=-1!==h.mode.indexOf("markers")?3:.5;if(-1!==m.indexOf("points")){var x=function(t){var e=Math.max(y,t.mrc||0),r=f.c2p(t.x)-d,n=p.c2p(t.y)-g;return Math.max(Math.sqrt(r*r+n*n)-e,1-y/e)},b=i.getDistanceFunction(c,function(t){var e=Math.max(3,t.mrc||0),r=1-1/e,n=Math.abs(f.c2p(t.x)-d);return n<e?r*n/e:n-e+r},function(t){var e=Math.max(3,t.mrc||0),r=1-1/e,n=Math.abs(p.c2p(t.y)-g);return n<e?r*n/e:n-e+r},x);if(i.getClosest(u,b,t),!1!==t.index){var _=u[t.index],w=f.c2p(_.x,!0),k=p.c2p(_.y,!0),A=_.mrc||1;t.index=_.i;var M=u[0].t.orientation,T=M&&(_.sNorm||_.s),S="h"===M?T:_.x,E="v"===M?T:_.y;return n.extendFlat(t,{color:o(h,_),x0:w-A,x1:w+A,xLabelVal:S,y0:k-A,y1:k+A,yLabelVal:E,spikeDistance:x(_),hovertemplate:h.hovertemplate}),l(_,h,t),a.getComponentMethod("errorbars","hoverInfo")(_,h,t),[t]}}if(-1!==m.indexOf("fills")&&h._polygons){var C,L,z,O,I,D,P,R,F,B=h._polygons,N=[],j=!1,V=1/0,U=-1/0,q=1/0,H=-1/0;for(C=0;C<B.length;C++)(z=B[C]).contains(v)&&(j=!j,N.push(z),q=Math.min(q,z.ymin),H=Math.max(H,z.ymax));if(j){var G=((q=Math.max(q,0))+(H=Math.min(H,p._length)))/2;for(C=0;C<N.length;C++)for(O=N[C].pts,L=1;L<O.length;L++)(R=O[L-1][1])>G!=(F=O[L][1])>=G&&(D=O[L-1][0],P=O[L][0],F-R&&(I=D+(P-D)*(G-R)/(F-R),V=Math.min(V,I),U=Math.max(U,I)));V=Math.max(V,0),U=Math.min(U,f._length);var Y=s.defaultLine;return s.opacity(h.fillcolor)?Y=h.fillcolor:s.opacity((h.line||{}).color)&&(Y=h.line.color),n.extendFlat(t,{distance:t.maxHoverDistance,x0:V,x1:U,y0:G,y1:G,color:Y,hovertemplate:"%{name}"}),delete t.index,h.text&&!Array.isArray(h.text)?t.text=String(h.text):t.text=h.name,[t]}}}},{"../../components/color":574,"../../components/fx":613,"../../lib":697,"../../registry":826,"./fill_hover_text":1056,"./get_trace_color":1058}],1060:[function(t,e,r){"use strict";var n={},i=t("./subtypes");n.hasLines=i.hasLines,n.hasMarkers=i.hasMarkers,n.hasText=i.hasText,n.isBubble=i.isBubble,n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.crossTraceDefaults=t("./cross_trace_defaults"),n.calc=t("./calc").calc,n.crossTraceCalc=t("./cross_trace_calc"),n.arraysToCalcdata=t("./arrays_to_calcdata"),n.plot=t("./plot"),n.colorbar=t("./marker_colorbar"),n.style=t("./style").style,n.styleOnSelect=t("./style").styleOnSelect,n.hoverPoints=t("./hover"),n.selectPoints=t("./select"),n.animatable=!0,n.moduleType="trace",n.name="scatter",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","svg","symbols","errorBarsOK","showLegend","scatter-like","zoomScale"],n.meta={},e.exports=n},{"../../plots/cartesian":756,"./arrays_to_calcdata":1047,"./attributes":1048,"./calc":1049,"./cross_trace_calc":1053,"./cross_trace_defaults":1054,"./defaults":1055,"./hover":1059,"./marker_colorbar":1066,"./plot":1068,"./select":1069,"./style":1071,"./subtypes":1072}],1061:[function(t,e,r){"use strict";var n=t("../../lib").isArrayOrTypedArray,i=t("../../components/colorscale/helpers").hasColorscale,a=t("../../components/colorscale/defaults");e.exports=function(t,e,r,o,s,l){var c=(t.marker||{}).color;(s("line.color",r),i(t,"line"))?a(t,e,o,s,{prefix:"line.",cLetter:"c"}):s("line.color",!n(c)&&c||r);s("line.width"),(l||{}).noDash||s("line.dash")}},{"../../components/colorscale/defaults":584,"../../components/colorscale/helpers":585,"../../lib":697}],1062:[function(t,e,r){"use strict";var n=t("../../constants/numerical"),i=n.BADNUM,a=n.LOG_CLIP,o=a+.5,s=a-.5,l=t("../../lib"),c=l.segmentsIntersect,u=l.constrain,h=t("./constants");e.exports=function(t,e){var r,n,a,f,p,d,g,v,m,y,x,b,_,w,k,A,M,T,S=e.xaxis,E=e.yaxis,C="log"===S.type,L="log"===E.type,z=S._length,O=E._length,I=e.connectGaps,D=e.baseTolerance,P=e.shape,R="linear"===P,F=[],B=h.minTolerance,N=new Array(t.length),j=0;function V(e){var r=t[e];if(!r)return!1;var n=S.c2p(r.x),a=E.c2p(r.y);if(n===i){if(C&&(n=S.c2p(r.x,!0)),n===i)return!1;L&&a===i&&(n*=Math.abs(S._m*O*(S._m>0?o:s)/(E._m*z*(E._m>0?o:s)))),n*=1e3}if(a===i){if(L&&(a=E.c2p(r.y,!0)),a===i)return!1;a*=1e3}return[n,a]}function U(t,e,r,n){var i=r-t,a=n-e,o=.5-t,s=.5-e,l=i*i+a*a,c=i*o+a*s;if(c>0&&c<l){var u=o*a-s*i;if(u*u<l)return!0}}function q(t,e){var r=t[0]/z,n=t[1]/O,i=Math.max(0,-r,r-1,-n,n-1);return i&&void 0!==M&&U(r,n,M,T)&&(i=0),i&&e&&U(r,n,e[0]/z,e[1]/O)&&(i=0),(1+h.toleranceGrowth*i)*D}function H(t,e){var r=t[0]-e[0],n=t[1]-e[1];return Math.sqrt(r*r+n*n)}var G,Y,W,X,Z,$,J,K=h.maxScreensAway,Q=-z*K,tt=z*(1+K),et=-O*K,rt=O*(1+K),nt=[[Q,et,tt,et],[tt,et,tt,rt],[tt,rt,Q,rt],[Q,rt,Q,et]];function it(t){if(t[0]<Q||t[0]>tt||t[1]<et||t[1]>rt)return[u(t[0],Q,tt),u(t[1],et,rt)]}function at(t,e){return t[0]===e[0]&&(t[0]===Q||t[0]===tt)||(t[1]===e[1]&&(t[1]===et||t[1]===rt)||void 0)}function ot(t,e,r){return function(n,i){var a=it(n),o=it(i),s=[];if(a&&o&&at(a,o))return s;a&&s.push(a),o&&s.push(o);var c=2*l.constrain((n[t]+i[t])/2,e,r)-((a||n)[t]+(o||i)[t]);c&&((a&&o?c>0==a[t]>o[t]?a:o:a||o)[t]+=c);return s}}function st(t){var e=t[0],r=t[1],n=e===N[j-1][0],i=r===N[j-1][1];if(!n||!i)if(j>1){var a=e===N[j-2][0],o=r===N[j-2][1];n&&(e===Q||e===tt)&&a?o?j--:N[j-1]=t:i&&(r===et||r===rt)&&o?a?j--:N[j-1]=t:N[j++]=t}else N[j++]=t}function lt(t){N[j-1][0]!==t[0]&&N[j-1][1]!==t[1]&&st([W,X]),st(t),Z=null,W=X=0}function ct(t){if(M=t[0]/z,T=t[1]/O,G=t[0]<Q?Q:t[0]>tt?tt:0,Y=t[1]<et?et:t[1]>rt?rt:0,G||Y){if(j)if(Z){var e=J(Z,t);e.length>1&&(lt(e[0]),N[j++]=e[1])}else $=J(N[j-1],t)[0],N[j++]=$;else N[j++]=[G||t[0],Y||t[1]];var r=N[j-1];G&&Y&&(r[0]!==G||r[1]!==Y)?(Z&&(W!==G&&X!==Y?st(W&&X?(n=Z,a=(i=t)[0]-n[0],o=(i[1]-n[1])/a,(n[1]*i[0]-i[1]*n[0])/a>0?[o>0?Q:tt,rt]:[o>0?tt:Q,et]):[W||G,X||Y]):W&&X&&st([W,X])),st([G,Y])):W-G&&X-Y&&st([G||W,Y||X]),Z=t,W=G,X=Y}else Z&&lt(J(Z,t)[0]),N[j++]=t;var n,i,a,o}for("linear"===P||"spline"===P?J=function(t,e){for(var r=[],n=0,i=0;i<4;i++){var a=nt[i],o=c(t[0],t[1],e[0],e[1],a[0],a[1],a[2],a[3]);o&&(!n||Math.abs(o.x-r[0][0])>1||Math.abs(o.y-r[0][1])>1)&&(o=[o.x,o.y],n&&H(o,t)<H(r[0],t)?r.unshift(o):r.push(o),n++)}return r}:"hv"===P||"vh"===P?J=function(t,e){var r=[],n=it(t),i=it(e);return n&&i&&at(n,i)?r:(n&&r.push(n),i&&r.push(i),r)}:"hvh"===P?J=ot(0,Q,tt):"vhv"===P&&(J=ot(1,et,rt)),r=0;r<t.length;r++)if(n=V(r)){for(j=0,Z=null,ct(n),r++;r<t.length;r++){if(!(f=V(r))){if(I)continue;break}if(R&&e.simplify){var ut=V(r+1);if(!((y=H(f,n))<q(f,ut)*B)){for(v=[(f[0]-n[0])/y,(f[1]-n[1])/y],p=n,x=y,b=w=k=0,g=!1,a=f,r++;r<t.length;r++){if(d=ut,ut=V(r+1),!d){if(I)continue;break}if(A=(m=[d[0]-n[0],d[1]-n[1]])[0]*v[1]-m[1]*v[0],w=Math.min(w,A),(k=Math.max(k,A))-w>q(d,ut))break;a=d,(_=m[0]*v[0]+m[1]*v[1])>x?(x=_,f=d,g=!1):_<b&&(b=_,p=d,g=!0)}if(g?(ct(f),a!==p&&ct(p)):(p!==n&&ct(p),a!==f&&ct(f)),ct(a),r>=t.length||!d)break;ct(d),n=d}}else ct(f)}Z&&st([W||Z[0],X||Z[1]]),F.push(N.slice(0,j))}return F}},{"../../constants/numerical":674,"../../lib":697,"./constants":1052}],1063:[function(t,e,r){"use strict";e.exports=function(t,e,r){"spline"===r("line.shape")&&r("line.smoothing")}},{}],1064:[function(t,e,r){"use strict";var n={tonextx:1,tonexty:1,tonext:1};e.exports=function(t,e,r){var i,a,o,s,l,c={},u=!1,h=-1,f=0,p=-1;for(a=0;a<r.length;a++)(o=(i=r[a][0].trace).stackgroup||"")?o in c?l=c[o]:(l=c[o]=f,f++):i.fill in n&&p>=0?l=p:(l=p=f,f++),l<h&&(u=!0),i._groupIndex=h=l;var d=r.slice();u&&d.sort(function(t,e){var r=t[0].trace,n=e[0].trace;return r._groupIndex-n._groupIndex||r.index-n.index});var g={};for(a=0;a<d.length;a++)o=(i=d[a][0].trace).stackgroup||"",!0===i.visible?(i._nexttrace=null,i.fill in n&&(s=g[o],i._prevtrace=s||null,s&&(s._nexttrace=i)),i._ownfill=i.fill&&("tozero"===i.fill.substr(0,6)||"toself"===i.fill||"to"===i.fill.substr(0,2)&&!i._prevtrace),g[o]=i):i._prevtrace=i._nexttrace=i._ownfill=null;return d}},{}],1065:[function(t,e,r){"use strict";var n=t("fast-isnumeric");e.exports=function(t){var e=t.marker,r=e.sizeref||1,i=e.sizemin||0,a="area"===e.sizemode?function(t){return Math.sqrt(t/r)}:function(t){return t/r};return function(t){var e=a(t/2);return n(e)&&e>0?Math.max(e,i):0}}},{"fast-isnumeric":218}],1066:[function(t,e,r){"use strict";e.exports={container:"marker",min:"cmin",max:"cmax"}},{}],1067:[function(t,e,r){"use strict";var n=t("../../components/color"),i=t("../../components/colorscale/helpers").hasColorscale,a=t("../../components/colorscale/defaults"),o=t("./subtypes");e.exports=function(t,e,r,s,l,c){var u=o.isBubble(t),h=(t.line||{}).color;(c=c||{},h&&(r=h),l("marker.symbol"),l("marker.opacity",u?.7:1),l("marker.size"),l("marker.color",r),i(t,"marker")&&a(t,e,s,l,{prefix:"marker.",cLetter:"c"}),c.noSelect||(l("selected.marker.color"),l("unselected.marker.color"),l("selected.marker.size"),l("unselected.marker.size")),c.noLine||(l("marker.line.color",h&&!Array.isArray(h)&&e.marker.color!==h?h:u?n.background:n.defaultLine),i(t,"marker.line")&&a(t,e,s,l,{prefix:"marker.line.",cLetter:"c"}),l("marker.line.width",u?1:0)),u&&(l("marker.sizeref"),l("marker.sizemin"),l("marker.sizemode")),c.gradient)&&("none"!==l("marker.gradient.type")&&l("marker.gradient.color"))}},{"../../components/color":574,"../../components/colorscale/defaults":584,"../../components/colorscale/helpers":585,"./subtypes":1072}],1068:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../registry"),a=t("../../lib"),o=a.ensureSingle,s=a.identity,l=t("../../components/drawing"),c=t("./subtypes"),u=t("./line_points"),h=t("./link_traces"),f=t("../../lib/polygon").tester;function p(t,e,r,h,p,d,g){var v;!function(t,e,r,i,o){var s=r.xaxis,l=r.yaxis,u=n.extent(a.simpleMap(s.range,s.r2c)),h=n.extent(a.simpleMap(l.range,l.r2c)),f=i[0].trace;if(!c.hasMarkers(f))return;var p=f.marker.maxdisplayed;if(0===p)return;var d=i.filter(function(t){return t.x>=u[0]&&t.x<=u[1]&&t.y>=h[0]&&t.y<=h[1]}),g=Math.ceil(d.length/p),v=0;o.forEach(function(t,r){var n=t[0].trace;c.hasMarkers(n)&&n.marker.maxdisplayed>0&&r<e&&v++});var m=Math.round(v*g/3+Math.floor(v/3)*g/7.1);i.forEach(function(t){delete t.vis}),d.forEach(function(t,e){0===Math.round((e+m)%g)&&(t.vis=!0)})}(0,e,r,h,p);var m=!!g&&g.duration>0;function y(t){return m?t.transition():t}var x=r.xaxis,b=r.yaxis,_=h[0].trace,w=_.line,k=n.select(d),A=o(k,"g","errorbars"),M=o(k,"g","lines"),T=o(k,"g","points"),S=o(k,"g","text");if(i.getComponentMethod("errorbars","plot")(t,A,r,g),!0===_.visible){var E,C;y(k).style("opacity",_.opacity);var L=_.fill.charAt(_.fill.length-1);"x"!==L&&"y"!==L&&(L=""),r.isRangePlot||(h[0].node3=k);var z,O,I="",D=[],P=_._prevtrace;P&&(I=P._prevRevpath||"",C=P._nextFill,D=P._polygons);var R,F,B,N,j,V,U,q="",H="",G=[],Y=a.noop;if(E=_._ownFill,c.hasLines(_)||"none"!==_.fill){for(C&&C.datum(h),-1!==["hv","vh","hvh","vhv"].indexOf(w.shape)?(R=l.steps(w.shape),F=l.steps(w.shape.split("").reverse().join(""))):R=F="spline"===w.shape?function(t){var e=t[t.length-1];return t.length>1&&t[0][0]===e[0]&&t[0][1]===e[1]?l.smoothclosed(t.slice(1),w.smoothing):l.smoothopen(t,w.smoothing)}:function(t){return"M"+t.join("L")},B=function(t){return F(t.reverse())},G=u(h,{xaxis:x,yaxis:b,connectGaps:_.connectgaps,baseTolerance:Math.max(w.width||1,3)/4,shape:w.shape,simplify:w.simplify}),U=_._polygons=new Array(G.length),v=0;v<G.length;v++)_._polygons[v]=f(G[v]);G.length&&(N=G[0][0],V=(j=G[G.length-1])[j.length-1]),Y=function(t){return function(e){if(z=R(e),O=B(e),q?L?(q+="L"+z.substr(1),H=O+"L"+H.substr(1)):(q+="Z"+z,H=O+"Z"+H):(q=z,H=O),c.hasLines(_)&&e.length>1){var r=n.select(this);if(r.datum(h),t)y(r.style("opacity",0).attr("d",z).call(l.lineGroupStyle)).style("opacity",1);else{var i=y(r);i.attr("d",z),l.singleLineStyle(h,i)}}}}}var W=M.selectAll(".js-line").data(G);y(W.exit()).style("opacity",0).remove(),W.each(Y(!1)),W.enter().append("path").classed("js-line",!0).style("vector-effect","non-scaling-stroke").call(l.lineGroupStyle).each(Y(!0)),l.setClipUrl(W,r.layerClipId,t),G.length?(E?(E.datum(h),N&&V&&(L?("y"===L?N[1]=V[1]=b.c2p(0,!0):"x"===L&&(N[0]=V[0]=x.c2p(0,!0)),y(E).attr("d","M"+V+"L"+N+"L"+q.substr(1)).call(l.singleFillStyle)):y(E).attr("d",q+"Z").call(l.singleFillStyle))):C&&("tonext"===_.fill.substr(0,6)&&q&&I?("tonext"===_.fill?y(C).attr("d",q+"Z"+I+"Z").call(l.singleFillStyle):y(C).attr("d",q+"L"+I.substr(1)+"Z").call(l.singleFillStyle),_._polygons=_._polygons.concat(D)):(Z(C),_._polygons=null)),_._prevRevpath=H,_._prevPolygons=U):(E?Z(E):C&&Z(C),_._polygons=_._prevRevpath=_._prevPolygons=null),T.datum(h),S.datum(h),function(e,i,a){var o,u=a[0].trace,h=c.hasMarkers(u),f=c.hasText(u),p=tt(u),d=et,g=et;if(h||f){var v=s,_=u.stackgroup,w=_&&"infer zero"===t._fullLayout._scatterStackOpts[x._id+b._id][_].stackgaps;u.marker.maxdisplayed||u._needsCull?v=w?J:$:_&&!w&&(v=K),h&&(d=v),f&&(g=v)}var k,A=(o=e.selectAll("path.point").data(d,p)).enter().append("path").classed("point",!0);m&&A.call(l.pointStyle,u,t).call(l.translatePoints,x,b).style("opacity",0).transition().style("opacity",1),o.order(),h&&(k=l.makePointStyleFns(u)),o.each(function(e){var i=n.select(this),a=y(i);l.translatePoint(e,a,x,b)?(l.singlePointStyle(e,a,u,k,t),r.layerClipId&&l.hideOutsideRangePoint(e,a,x,b,u.xcalendar,u.ycalendar),u.customdata&&i.classed("plotly-customdata",null!==e.data&&void 0!==e.data)):a.remove()}),m?o.exit().transition().style("opacity",0).remove():o.exit().remove(),(o=i.selectAll("g").data(g,p)).enter().append("g").classed("textpoint",!0).append("text"),o.order(),o.each(function(t){var e=n.select(this),i=y(e.select("text"));l.translatePoint(t,i,x,b)?r.layerClipId&&l.hideOutsideRangePoint(t,e,x,b,u.xcalendar,u.ycalendar):e.remove()}),o.selectAll("text").call(l.textPointStyle,u,t).each(function(t){var e=x.c2p(t.x),r=b.c2p(t.y);n.select(this).selectAll("tspan.line").each(function(){y(n.select(this)).attr({x:e,y:r})})}),o.exit().remove()}(T,S,h);var X=!1===_.cliponaxis?null:r.layerClipId;l.setClipUrl(T,X,t),l.setClipUrl(S,X,t)}function Z(t){y(t).attr("d","M0,0Z")}function $(t){return t.filter(function(t){return!t.gap&&t.vis})}function J(t){return t.filter(function(t){return t.vis})}function K(t){return t.filter(function(t){return!t.gap})}function Q(t){return t.id}function tt(t){if(t.ids)return Q}function et(){return!1}}e.exports=function(t,e,r,i,a,c){var u,f,d=!a,g=!!a&&a.duration>0,v=h(t,e,r);((u=i.selectAll("g.trace").data(v,function(t){return t[0].trace.uid})).enter().append("g").attr("class",function(t){return"trace scatter trace"+t[0].trace.uid}).style("stroke-miterlimit",2),u.order(),function(t,e,r){e.each(function(e){var i=o(n.select(this),"g","fills");l.setClipUrl(i,r.layerClipId,t);var a=e[0].trace,c=[];a._ownfill&&c.push("_ownFill"),a._nexttrace&&c.push("_nextFill");var u=i.selectAll("g").data(c,s);u.enter().append("g"),u.exit().each(function(t){a[t]=null}).remove(),u.order().each(function(t){a[t]=o(n.select(this),"path","js-fill")})})}(t,u,e),g)?(c&&(f=c()),n.transition().duration(a.duration).ease(a.easing).each("end",function(){f&&f()}).each("interrupt",function(){f&&f()}).each(function(){i.selectAll("g.trace").each(function(r,n){p(t,n,e,r,v,this,a)})})):u.each(function(r,n){p(t,n,e,r,v,this,a)});d&&u.exit().remove(),i.selectAll("path:not([d])").remove()}},{"../../components/drawing":595,"../../lib":697,"../../lib/polygon":709,"../../registry":826,"./line_points":1062,"./link_traces":1064,"./subtypes":1072,d3:151}],1069:[function(t,e,r){"use strict";var n=t("./subtypes");e.exports=function(t,e){var r,i,a,o,s=t.cd,l=t.xaxis,c=t.yaxis,u=[],h=s[0].trace;if(!n.hasMarkers(h)&&!n.hasText(h))return[];if(!1===e)for(r=0;r<s.length;r++)s[r].selected=0;else for(r=0;r<s.length;r++)i=s[r],a=l.c2p(i.x),o=c.c2p(i.y),null!==i.i&&e.contains([a,o],!1,r,t)?(u.push({pointNumber:i.i,x:l.c2d(i.x),y:c.c2d(i.y)}),i.selected=1):i.selected=0;return u}},{"./subtypes":1072}],1070:[function(t,e,r){"use strict";var n=["orientation","groupnorm","stackgaps"];e.exports=function(t,e,r,i){var a=r._scatterStackOpts,o=i("stackgroup");if(o){var s=e.xaxis+e.yaxis,l=a[s];l||(l=a[s]={});var c=l[o],u=!1;c?c.traces.push(e):(c=l[o]={traceIndices:[],traces:[e]},u=!0);for(var h={orientation:e.x&&!e.y?"h":"v"},f=0;f<n.length;f++){var p=n[f],d=p+"Found";if(!c[d]){var g=void 0!==t[p],v="orientation"===p;if((g||u)&&(c[p]=i(p,h[p]),v&&(c.fillDflt="h"===c[p]?"tonextx":"tonexty"),g&&(c[d]=!0,!u&&(delete c.traces[0][p],v))))for(var m=0;m<c.traces.length-1;m++){var y=c.traces[m];y._input.fill!==y.fill&&(y.fill=c.fillDflt)}}}return c}}},{}],1071:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../components/drawing"),a=t("../../registry");function o(t,e,r){i.pointStyle(t.selectAll("path.point"),e,r)}function s(t,e,r){i.textPointStyle(t.selectAll("text"),e,r)}e.exports={style:function(t,e){var r=e?e[0].node3:n.select(t).selectAll("g.trace.scatter");r.style("opacity",function(t){return t[0].trace.opacity}),r.selectAll("g.points").each(function(e){o(n.select(this),e.trace||e[0].trace,t)}),r.selectAll("g.text").each(function(e){s(n.select(this),e.trace||e[0].trace,t)}),r.selectAll("g.trace path.js-line").call(i.lineGroupStyle),r.selectAll("g.trace path.js-fill").call(i.fillGroupStyle),a.getComponentMethod("errorbars","style")(r)},stylePoints:o,styleText:s,styleOnSelect:function(t,e){var r=e[0].node3,n=e[0].trace;n.selectedpoints?(i.selectedPointStyle(r.selectAll("path.point"),n),i.selectedTextStyle(r.selectAll("text"),n)):(o(r,n,t),s(r,n,t))}}},{"../../components/drawing":595,"../../registry":826,d3:151}],1072:[function(t,e,r){"use strict";var n=t("../../lib");e.exports={hasLines:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("lines")},hasMarkers:function(t){return t.visible&&(t.mode&&-1!==t.mode.indexOf("markers")||"splom"===t.type)},hasText:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("text")},isBubble:function(t){return n.isPlainObject(t.marker)&&n.isArrayOrTypedArray(t.marker.size)}}},{"../../lib":697}],1073:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e,r,i,a){a=a||{},i("textposition"),n.coerceFont(i,"textfont",r.font),a.noSelect||(i("selected.textfont.color"),i("unselected.textfont.color"))}},{"../../lib":697}],1074:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../registry");e.exports=function(t,e,r,a){var o,s=a("x"),l=a("y");if(i.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y"],r),s){var c=n.minRowLength(s);l?o=Math.min(c,n.minRowLength(l)):(o=c,a("y0"),a("dy"))}else{if(!l)return 0;o=n.minRowLength(l),a("x0"),a("dx")}return e._length=o,o}},{"../../lib":697,"../../registry":826}],1075:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../components/colorscale/attributes"),a=t("../../components/fx/hovertemplate_attributes"),o=t("../../plots/attributes"),s=t("../../constants/gl3d_dashes"),l=t("../../constants/gl3d_markers"),c=t("../../lib/extend").extendFlat,u=t("../../plot_api/edit_types").overrideAll,h=n.line,f=n.marker,p=f.line,d=c({width:h.width,dash:{valType:"enumerated",values:Object.keys(s),dflt:"solid"}},i("line"));var g=e.exports=u({x:n.x,y:n.y,z:{valType:"data_array"},text:c({},n.text,{}),hovertext:c({},n.hovertext,{}),hovertemplate:a(),mode:c({},n.mode,{dflt:"lines+markers"}),surfaceaxis:{valType:"enumerated",values:[-1,0,1,2],dflt:-1},surfacecolor:{valType:"color"},projection:{x:{show:{valType:"boolean",dflt:!1},opacity:{valType:"number",min:0,max:1,dflt:1},scale:{valType:"number",min:0,max:10,dflt:2/3}},y:{show:{valType:"boolean",dflt:!1},opacity:{valType:"number",min:0,max:1,dflt:1},scale:{valType:"number",min:0,max:10,dflt:2/3}},z:{show:{valType:"boolean",dflt:!1},opacity:{valType:"number",min:0,max:1,dflt:1},scale:{valType:"number",min:0,max:10,dflt:2/3}}},connectgaps:n.connectgaps,line:d,marker:c({symbol:{valType:"enumerated",values:Object.keys(l),dflt:"circle",arrayOk:!0},size:c({},f.size,{dflt:8}),sizeref:f.sizeref,sizemin:f.sizemin,sizemode:f.sizemode,opacity:c({},f.opacity,{arrayOk:!1}),colorbar:f.colorbar,line:c({width:c({},p.width,{arrayOk:!1})},i("marker.line"))},i("marker")),textposition:c({},n.textposition,{dflt:"top center"}),textfont:{color:n.textfont.color,size:n.textfont.size,family:c({},n.textfont.family,{arrayOk:!1})},hoverinfo:c({},o.hoverinfo)},"calc","nested");g.x.editType=g.y.editType=g.z.editType="calc+clearAxisTypes"},{"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../constants/gl3d_dashes":671,"../../constants/gl3d_markers":672,"../../lib/extend":687,"../../plot_api/edit_types":728,"../../plots/attributes":742,"../scatter/attributes":1048}],1076:[function(t,e,r){"use strict";var n=t("../scatter/arrays_to_calcdata"),i=t("../scatter/colorscale_calc");e.exports=function(t,e){var r=[{x:!1,y:!1,trace:e,t:{}}];return n(r,e),i(t,e),r}},{"../scatter/arrays_to_calcdata":1047,"../scatter/colorscale_calc":1051}],1077:[function(t,e,r){"use strict";var n=t("../../registry");function i(t,e,r,i){if(!e||!e.visible)return null;for(var a=n.getComponentMethod("errorbars","makeComputeError")(e),o=new Array(t.length),s=0;s<t.length;s++){var l=a(+t[s],s);if("log"===i.type){var c=i.c2l(t[s]),u=t[s]-l[0],h=t[s]+l[1];if(o[s]=[(i.c2l(u,!0)-c)*r,(i.c2l(h,!0)-c)*r],u>0){var f=i.c2l(u);i._lowerLogErrorBound||(i._lowerLogErrorBound=f),i._lowerErrorBound=Math.min(i._lowerLogErrorBound,f)}}else o[s]=[-l[0]*r,l[1]*r]}return o}e.exports=function(t,e,r){var n=[i(t.x,t.error_x,e[0],r.xaxis),i(t.y,t.error_y,e[1],r.yaxis),i(t.z,t.error_z,e[2],r.zaxis)],a=function(t){for(var e=0;e<t.length;e++)if(t[e])return t[e].length;return 0}(n);if(0===a)return null;for(var o=new Array(a),s=0;s<a;s++){for(var l=[[0,0,0],[0,0,0]],c=0;c<3;c++)if(n[c])for(var u=0;u<2;u++)l[u][c]=n[c][s][u];o[s]=l}return o}},{"../../registry":826}],1078:[function(t,e,r){"use strict";var n=t("gl-line3d"),i=t("gl-scatter3d"),a=t("gl-error3d"),o=t("gl-mesh3d"),s=t("delaunay-triangulate"),l=t("../../lib"),c=t("../../lib/str2rgbarray"),u=t("../../lib/gl_format_color").formatColor,h=t("../scatter/make_bubble_size_func"),f=t("../../constants/gl3d_dashes"),p=t("../../constants/gl3d_markers"),d=t("./calc_errors");function g(t,e){this.scene=t,this.uid=e,this.linePlot=null,this.scatterPlot=null,this.errorBars=null,this.textMarkers=null,this.delaunayMesh=null,this.color=null,this.mode="",this.dataPoints=[],this.axesBounds=[[-1/0,-1/0,-1/0],[1/0,1/0,1/0]],this.textLabels=null,this.data=null}var v=g.prototype;function m(t){return null==t?0:t.indexOf("left")>-1?-1:t.indexOf("right")>-1?1:0}function y(t){return null==t?0:t.indexOf("top")>-1?-1:t.indexOf("bottom")>-1?1:0}function x(t,e){return e(4*t)}function b(t){return p[t]}function _(t,e,r,n,i){var a=null;if(l.isArrayOrTypedArray(t)){a=[];for(var o=0;o<e;o++)void 0===t[o]?a[o]=n:a[o]=r(t[o],i)}else a=r(t,l.identity);return a}function w(t,e){var r,n,i,a,o,s,f=[],p=t.fullSceneLayout,g=t.dataScale,v=p.xaxis,w=p.yaxis,k=p.zaxis,A=e.marker,M=e.line,T=e.x||[],S=e.y||[],E=e.z||[],C=T.length,L=e.xcalendar,z=e.ycalendar,O=e.zcalendar;for(o=0;o<C;o++)r=v.d2l(T[o],0,L)*g[0],n=w.d2l(S[o],0,z)*g[1],i=k.d2l(E[o],0,O)*g[2],f[o]=[r,n,i];if(Array.isArray(e.text))s=e.text;else if(void 0!==e.text)for(s=new Array(C),o=0;o<C;o++)s[o]=e.text;if(a={position:f,mode:e.mode,text:s},"line"in e&&(a.lineColor=u(M,1,C),a.lineWidth=M.width,a.lineDashes=M.dash),"marker"in e){var I=h(e);a.scatterColor=u(A,1,C),a.scatterSize=_(A.size,C,x,20,I),a.scatterMarker=_(A.symbol,C,b,"\u25cf"),a.scatterLineWidth=A.line.width,a.scatterLineColor=u(A.line,1,C),a.scatterAngle=0}"textposition"in e&&(a.textOffset=function(t){var e=[0,0];if(Array.isArray(t))for(var r=0;r<t.length;r++)e[r]=[0,0],t[r]&&(e[r][0]=m(t[r]),e[r][1]=y(t[r]));else e[0]=m(t),e[1]=y(t);return e}(e.textposition),a.textColor=u(e.textfont,1,C),a.textSize=_(e.textfont.size,C,l.identity,12),a.textFont=e.textfont.family,a.textAngle=0);var D=["x","y","z"];for(a.project=[!1,!1,!1],a.projectScale=[1,1,1],a.projectOpacity=[1,1,1],o=0;o<3;++o){var P=e.projection[D[o]];(a.project[o]=P.show)&&(a.projectOpacity[o]=P.opacity,a.projectScale[o]=P.scale)}a.errorBounds=d(e,g,p);var R=function(t){for(var e=[0,0,0],r=[[0,0,0],[0,0,0],[0,0,0]],n=[1,1,1],i=0;i<3;i++){var a=t[i];a&&!1!==a.copy_zstyle&&!1!==t[2].visible&&(a=t[2]),a&&a.visible&&(e[i]=a.width/2,r[i]=c(a.color),n[i]=a.thickness)}return{capSize:e,color:r,lineWidth:n}}([e.error_x,e.error_y,e.error_z]);return a.errorColor=R.color,a.errorLineWidth=R.lineWidth,a.errorCapSize=R.capSize,a.delaunayAxis=e.surfaceaxis,a.delaunayColor=c(e.surfacecolor),a}function k(t){if(Array.isArray(t)){var e=t[0];return Array.isArray(e)&&(t=e),"rgb("+t.slice(0,3).map(function(t){return Math.round(255*t)})+")"}return null}v.handlePick=function(t){if(t.object&&(t.object===this.linePlot||t.object===this.delaunayMesh||t.object===this.textMarkers||t.object===this.scatterPlot)){var e=t.index=t.data.index;return t.object.highlight&&t.object.highlight(null),this.scatterPlot&&(t.object=this.scatterPlot,this.scatterPlot.highlight(t.data)),t.textLabel="",this.textLabels&&(Array.isArray(this.textLabels)?(this.textLabels[e]||0===this.textLabels[e])&&(t.textLabel=this.textLabels[e]):t.textLabel=this.textLabels),t.traceCoordinate=[this.data.x[e],this.data.y[e],this.data.z[e]],!0}},v.update=function(t){var e,r,l,c,u=this.scene.glplot.gl,h=f.solid;this.data=t;var p=w(this.scene,t);"mode"in p&&(this.mode=p.mode),"lineDashes"in p&&p.lineDashes in f&&(h=f[p.lineDashes]),this.color=k(p.scatterColor)||k(p.lineColor),this.dataPoints=p.position,e={gl:this.scene.glplot.gl,position:p.position,color:p.lineColor,lineWidth:p.lineWidth||1,dashes:h[0],dashScale:h[1],opacity:t.opacity,connectGaps:t.connectgaps},-1!==this.mode.indexOf("lines")?this.linePlot?this.linePlot.update(e):(this.linePlot=n(e),this.linePlot._trace=this,this.scene.glplot.add(this.linePlot)):this.linePlot&&(this.scene.glplot.remove(this.linePlot),this.linePlot.dispose(),this.linePlot=null);var d=t.opacity;if(t.marker&&t.marker.opacity&&(d*=t.marker.opacity),r={gl:this.scene.glplot.gl,position:p.position,color:p.scatterColor,size:p.scatterSize,glyph:p.scatterMarker,opacity:d,orthographic:!0,lineWidth:p.scatterLineWidth,lineColor:p.scatterLineColor,project:p.project,projectScale:p.projectScale,projectOpacity:p.projectOpacity},-1!==this.mode.indexOf("markers")?this.scatterPlot?this.scatterPlot.update(r):(this.scatterPlot=i(r),this.scatterPlot._trace=this,this.scatterPlot.highlightScale=1,this.scene.glplot.add(this.scatterPlot)):this.scatterPlot&&(this.scene.glplot.remove(this.scatterPlot),this.scatterPlot.dispose(),this.scatterPlot=null),c={gl:this.scene.glplot.gl,position:p.position,glyph:p.text,color:p.textColor,size:p.textSize,angle:p.textAngle,alignment:p.textOffset,font:p.textFont,orthographic:!0,lineWidth:0,project:!1,opacity:t.opacity},this.textLabels=t.hovertext||t.text,-1!==this.mode.indexOf("text")?this.textMarkers?this.textMarkers.update(c):(this.textMarkers=i(c),this.textMarkers._trace=this,this.textMarkers.highlightScale=1,this.scene.glplot.add(this.textMarkers)):this.textMarkers&&(this.scene.glplot.remove(this.textMarkers),this.textMarkers.dispose(),this.textMarkers=null),l={gl:this.scene.glplot.gl,position:p.position,color:p.errorColor,error:p.errorBounds,lineWidth:p.errorLineWidth,capSize:p.errorCapSize,opacity:t.opacity},this.errorBars?p.errorBounds?this.errorBars.update(l):(this.scene.glplot.remove(this.errorBars),this.errorBars.dispose(),this.errorBars=null):p.errorBounds&&(this.errorBars=a(l),this.errorBars._trace=this,this.scene.glplot.add(this.errorBars)),p.delaunayAxis>=0){var g=function(t,e,r){var n,i=(r+1)%3,a=(r+2)%3,o=[],l=[];for(n=0;n<t.length;++n){var c=t[n];!isNaN(c[i])&&isFinite(c[i])&&!isNaN(c[a])&&isFinite(c[a])&&(o.push([c[i],c[a]]),l.push(n))}var u=s(o);for(n=0;n<u.length;++n)for(var h=u[n],f=0;f<h.length;++f)h[f]=l[h[f]];return{positions:t,cells:u,meshColor:e}}(p.position,p.delaunayColor,p.delaunayAxis);g.opacity=t.opacity,this.delaunayMesh?this.delaunayMesh.update(g):(g.gl=u,this.delaunayMesh=o(g),this.delaunayMesh._trace=this,this.scene.glplot.add(this.delaunayMesh))}else this.delaunayMesh&&(this.scene.glplot.remove(this.delaunayMesh),this.delaunayMesh.dispose(),this.delaunayMesh=null)},v.dispose=function(){this.linePlot&&(this.scene.glplot.remove(this.linePlot),this.linePlot.dispose()),this.scatterPlot&&(this.scene.glplot.remove(this.scatterPlot),this.scatterPlot.dispose()),this.errorBars&&(this.scene.glplot.remove(this.errorBars),this.errorBars.dispose()),this.textMarkers&&(this.scene.glplot.remove(this.textMarkers),this.textMarkers.dispose()),this.delaunayMesh&&(this.scene.glplot.remove(this.delaunayMesh),this.delaunayMesh.dispose())},e.exports=function(t,e){var r=new g(t,e.uid);return r.update(e),r}},{"../../constants/gl3d_dashes":671,"../../constants/gl3d_markers":672,"../../lib":697,"../../lib/gl_format_color":694,"../../lib/str2rgbarray":720,"../scatter/make_bubble_size_func":1065,"./calc_errors":1077,"delaunay-triangulate":153,"gl-error3d":240,"gl-line3d":248,"gl-mesh3d":273,"gl-scatter3d":290}],1079:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("../../lib"),a=t("../scatter/subtypes"),o=t("../scatter/marker_defaults"),s=t("../scatter/line_defaults"),l=t("../scatter/text_defaults"),c=t("./attributes");e.exports=function(t,e,r,u){function h(r,n){return i.coerce(t,e,c,r,n)}if(function(t,e,r,i){var a=0,o=r("x"),s=r("y"),l=r("z");n.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y","z"],i),o&&s&&l&&(a=Math.min(o.length,s.length,l.length),e._length=e._xlength=e._ylength=e._zlength=a);return a}(t,e,h,u)){h("text"),h("hovertext"),h("hovertemplate"),h("mode"),a.hasLines(e)&&(h("connectgaps"),s(t,e,r,u,h)),a.hasMarkers(e)&&o(t,e,r,u,h,{noSelect:!0}),a.hasText(e)&&l(t,e,u,h,{noSelect:!0});var f=(e.line||{}).color,p=(e.marker||{}).color;h("surfaceaxis")>=0&&h("surfacecolor",f||p);for(var d=["x","y","z"],g=0;g<3;++g){var v="projection."+d[g];h(v+".show")&&(h(v+".opacity"),h(v+".scale"))}var m=n.getComponentMethod("errorbars","supplyDefaults");m(t,e,f||p||r,{axis:"z"}),m(t,e,f||p||r,{axis:"y",inherit:"z"}),m(t,e,f||p||r,{axis:"x",inherit:"z"})}else e.visible=!1}},{"../../lib":697,"../../registry":826,"../scatter/line_defaults":1061,"../scatter/marker_defaults":1067,"../scatter/subtypes":1072,"../scatter/text_defaults":1073,"./attributes":1075}],1080:[function(t,e,r){"use strict";var n={};n.plot=t("./convert"),n.attributes=t("./attributes"),n.markerSymbols=t("../../constants/gl3d_markers"),n.supplyDefaults=t("./defaults"),n.colorbar=[{container:"marker",min:"cmin",max:"cmax"},{container:"line",min:"cmin",max:"cmax"}],n.calc=t("./calc"),n.moduleType="trace",n.name="scatter3d",n.basePlotModule=t("../../plots/gl3d"),n.categories=["gl3d","symbols","showLegend"],n.meta={},e.exports=n},{"../../constants/gl3d_markers":672,"../../plots/gl3d":786,"./attributes":1075,"./calc":1076,"./convert":1078,"./defaults":1079}],1081:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../plots/attributes"),a=t("../../components/fx/hovertemplate_attributes"),o=t("../../components/colorscale/attributes"),s=t("../../components/colorbar/attributes"),l=t("../../lib/extend").extendFlat,c=n.marker,u=n.line,h=c.line;e.exports={carpet:{valType:"string",editType:"calc"},a:{valType:"data_array",editType:"calc"},b:{valType:"data_array",editType:"calc"},mode:l({},n.mode,{dflt:"markers"}),text:l({},n.text,{}),hovertext:l({},n.hovertext,{}),line:{color:u.color,width:u.width,dash:u.dash,shape:l({},u.shape,{values:["linear","spline"]}),smoothing:u.smoothing,editType:"calc"},connectgaps:n.connectgaps,fill:l({},n.fill,{values:["none","toself","tonext"],dflt:"none"}),fillcolor:n.fillcolor,marker:l({symbol:c.symbol,opacity:c.opacity,maxdisplayed:c.maxdisplayed,size:c.size,sizeref:c.sizeref,sizemin:c.sizemin,sizemode:c.sizemode,line:l({width:h.width,editType:"calc"},o("marker.line")),gradient:c.gradient,editType:"calc"},o("marker"),{colorbar:s}),textfont:n.textfont,textposition:n.textposition,selected:n.selected,unselected:n.unselected,hoverinfo:l({},i.hoverinfo,{flags:["a","b","text","name"]}),hoveron:n.hoveron,hovertemplate:a()}},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plots/attributes":742,"../scatter/attributes":1048}],1082:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../scatter/colorscale_calc"),a=t("../scatter/arrays_to_calcdata"),o=t("../scatter/calc_selection"),s=t("../scatter/calc").calcMarkerSize,l=t("../carpet/lookup_carpetid");e.exports=function(t,e){var r=e._carpetTrace=l(t,e);if(r&&r.visible&&"legendonly"!==r.visible){var c;e.xaxis=r.xaxis,e.yaxis=r.yaxis;var u,h,f=e._length,p=new Array(f),d=!1;for(c=0;c<f;c++)if(u=e.a[c],h=e.b[c],n(u)&&n(h)){var g=r.ab2xy(+u,+h,!0),v=r.isVisible(+u,+h);v||(d=!0),p[c]={x:g[0],y:g[1],a:u,b:h,vis:v}}else p[c]={x:!1,y:!1};return e._needsCull=d,p[0].carpet=r,p[0].trace=e,s(e,f),i(t,e),a(p,e),o(p,e),p}}},{"../carpet/lookup_carpetid":894,"../scatter/arrays_to_calcdata":1047,"../scatter/calc":1049,"../scatter/calc_selection":1050,"../scatter/colorscale_calc":1051,"fast-isnumeric":218}],1083:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../scatter/constants"),a=t("../scatter/subtypes"),o=t("../scatter/marker_defaults"),s=t("../scatter/line_defaults"),l=t("../scatter/line_shape_defaults"),c=t("../scatter/text_defaults"),u=t("../scatter/fillcolor_defaults"),h=t("./attributes");e.exports=function(t,e,r,f){function p(r,i){return n.coerce(t,e,h,r,i)}p("carpet"),e.xaxis="x",e.yaxis="y";var d=p("a"),g=p("b"),v=Math.min(d.length,g.length);if(v){e._length=v,p("text"),p("hovertext"),p("mode",v<i.PTS_LINESONLY?"lines+markers":"lines"),a.hasLines(e)&&(s(t,e,r,f,p),l(t,e,p),p("connectgaps")),a.hasMarkers(e)&&o(t,e,r,f,p,{gradient:!0}),a.hasText(e)&&c(t,e,f,p);var m=[];(a.hasMarkers(e)||a.hasText(e))&&(p("marker.maxdisplayed"),m.push("points")),p("fill"),"none"!==e.fill&&(u(t,e,r,p),a.hasLines(e)||l(t,e,p)),"tonext"!==e.fill&&"toself"!==e.fill||m.push("fills"),"fills"!==p("hoveron",m.join("+")||"points")&&p("hovertemplate"),n.coerceSelectionMarkerOpacity(e,p)}else e.visible=!1}},{"../../lib":697,"../scatter/constants":1052,"../scatter/fillcolor_defaults":1057,"../scatter/line_defaults":1061,"../scatter/line_shape_defaults":1063,"../scatter/marker_defaults":1067,"../scatter/subtypes":1072,"../scatter/text_defaults":1073,"./attributes":1081}],1084:[function(t,e,r){"use strict";e.exports=function(t,e,r,n,i){var a=n[i];return t.a=a.a,t.b=a.b,t.y=a.y,t}},{}],1085:[function(t,e,r){"use strict";var n=t("../scatter/hover"),i=t("../scatter/fill_hover_text");e.exports=function(t,e,r,a){var o=n(t,e,r,a);if(o&&!1!==o[0].index){var s=o[0];if(void 0===s.index){var l=1-s.y0/t.ya._length,c=t.xa._length,u=c*l/2,h=c-u;return s.x0=Math.max(Math.min(s.x0,h),u),s.x1=Math.max(Math.min(s.x1,h),u),o}var f=s.cd[s.index];s.a=f.a,s.b=f.b,s.xLabelVal=void 0,s.yLabelVal=void 0;var p=s.trace,d=p._carpet,g=d.ab2ij([f.a,f.b]),v=Math.floor(g[0]),m=g[0]-v,y=Math.floor(g[1]),x=g[1]-y,b=d.evalxy([],v,y,m,x);s.yLabel=b[1].toFixed(3),delete s.text;var _=[];if(!p.hovertemplate){var w=(f.hi||p.hoverinfo).split("+");-1!==w.indexOf("all")&&(w=["a","b","text"]),-1!==w.indexOf("a")&&k(d.aaxis,f.a),-1!==w.indexOf("b")&&k(d.baxis,f.b),_.push("y: "+s.yLabel),-1!==w.indexOf("text")&&i(f,p,_),s.extraText=_.join("<br>")}return o}function k(t,e){var r;r=t.labelprefix&&t.labelprefix.length>0?t.labelprefix.replace(/ = $/,""):t._hovertitle,_.push(r+": "+e.toFixed(3)+t.labelsuffix)}}},{"../scatter/fill_hover_text":1056,"../scatter/hover":1059}],1086:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../scatter/marker_colorbar"),n.calc=t("./calc"),n.plot=t("./plot"),n.style=t("../scatter/style").style,n.styleOnSelect=t("../scatter/style").styleOnSelect,n.hoverPoints=t("./hover"),n.selectPoints=t("../scatter/select"),n.eventData=t("./event_data"),n.moduleType="trace",n.name="scattercarpet",n.basePlotModule=t("../../plots/cartesian"),n.categories=["svg","carpet","symbols","showLegend","carpetDependent","zoomScale"],n.meta={},e.exports=n},{"../../plots/cartesian":756,"../scatter/marker_colorbar":1066,"../scatter/select":1069,"../scatter/style":1071,"./attributes":1081,"./calc":1082,"./defaults":1083,"./event_data":1084,"./hover":1085,"./plot":1087}],1087:[function(t,e,r){"use strict";var n=t("../scatter/plot"),i=t("../../plots/cartesian/axes"),a=t("../../components/drawing");e.exports=function(t,e,r,o){var s,l,c,u=r[0][0].carpet,h={xaxis:i.getFromId(t,u.xaxis||"x"),yaxis:i.getFromId(t,u.yaxis||"y"),plot:e.plot};for(n(t,h,r,o),s=0;s<r.length;s++)l=r[s][0].trace,c=o.selectAll("g.trace"+l.uid+" .js-line"),a.setClipUrl(c,r[s][0].carpet._clipPathId,t)}},{"../../components/drawing":595,"../../plots/cartesian/axes":745,"../scatter/plot":1068}],1088:[function(t,e,r){"use strict";var n=t("../../components/fx/hovertemplate_attributes"),i=t("../scatter/attributes"),a=t("../../plots/attributes"),o=t("../../components/colorscale/attributes"),s=t("../../components/drawing/attributes").dash,l=t("../../lib/extend").extendFlat,c=t("../../plot_api/edit_types").overrideAll,u=i.marker,h=i.line,f=u.line;e.exports=c({lon:{valType:"data_array"},lat:{valType:"data_array"},locations:{valType:"data_array"},locationmode:{valType:"enumerated",values:["ISO-3","USA-states","country names"],dflt:"ISO-3"},mode:l({},i.mode,{dflt:"markers"}),text:l({},i.text,{}),hovertext:l({},i.hovertext,{}),textfont:i.textfont,textposition:i.textposition,line:{color:h.color,width:h.width,dash:s},connectgaps:i.connectgaps,marker:l({symbol:u.symbol,opacity:u.opacity,size:u.size,sizeref:u.sizeref,sizemin:u.sizemin,sizemode:u.sizemode,colorbar:u.colorbar,line:l({width:f.width},o("marker.line")),gradient:u.gradient},o("marker")),fill:{valType:"enumerated",values:["none","toself"],dflt:"none"},fillcolor:i.fillcolor,selected:i.selected,unselected:i.unselected,hoverinfo:l({},a.hoverinfo,{flags:["lon","lat","location","text","name"]}),hovertemplate:n()},"calc","nested")},{"../../components/colorscale/attributes":581,"../../components/drawing/attributes":594,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plot_api/edit_types":728,"../../plots/attributes":742,"../scatter/attributes":1048}],1089:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../constants/numerical").BADNUM,a=t("../scatter/colorscale_calc"),o=t("../scatter/arrays_to_calcdata"),s=t("../scatter/calc_selection"),l=t("../../lib")._;e.exports=function(t,e){for(var r=Array.isArray(e.locations),c=r?e.locations.length:e._length,u=new Array(c),h=0;h<c;h++){var f=u[h]={};if(r){var p=e.locations[h];f.loc="string"==typeof p?p:null}else{var d=e.lon[h],g=e.lat[h];n(d)&&n(g)?f.lonlat=[+d,+g]:f.lonlat=[i,i]}}return o(u,e),a(t,e),s(u,e),c&&(u[0].t={labels:{lat:l(t,"lat:")+" ",lon:l(t,"lon:")+" "}}),u}},{"../../constants/numerical":674,"../../lib":697,"../scatter/arrays_to_calcdata":1047,"../scatter/calc_selection":1050,"../scatter/colorscale_calc":1051,"fast-isnumeric":218}],1090:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../scatter/subtypes"),a=t("../scatter/marker_defaults"),o=t("../scatter/line_defaults"),s=t("../scatter/text_defaults"),l=t("../scatter/fillcolor_defaults"),c=t("./attributes");e.exports=function(t,e,r,u){function h(r,i){return n.coerce(t,e,c,r,i)}!function(t,e,r){var n,i,a=0,o=r("locations");if(o)return r("locationmode"),a=o.length;return n=r("lon")||[],i=r("lat")||[],a=Math.min(n.length,i.length),e._length=a,a}(0,e,h)?e.visible=!1:(h("text"),h("hovertext"),h("hovertemplate"),h("mode"),i.hasLines(e)&&(o(t,e,r,u,h),h("connectgaps")),i.hasMarkers(e)&&a(t,e,r,u,h,{gradient:!0}),i.hasText(e)&&s(t,e,u,h),h("fill"),"none"!==e.fill&&l(t,e,r,h),n.coerceSelectionMarkerOpacity(e,h))}},{"../../lib":697,"../scatter/fillcolor_defaults":1057,"../scatter/line_defaults":1061,"../scatter/marker_defaults":1067,"../scatter/subtypes":1072,"../scatter/text_defaults":1073,"./attributes":1088}],1091:[function(t,e,r){"use strict";e.exports=function(t,e){return t.lon=e.lon,t.lat=e.lat,t.location=e.loc?e.loc:null,t}},{}],1092:[function(t,e,r){"use strict";var n=t("../../components/fx"),i=t("../../plots/cartesian/axes"),a=t("../../constants/numerical").BADNUM,o=t("../scatter/get_trace_color"),s=t("../scatter/fill_hover_text"),l=t("./attributes");e.exports=function(t,e,r){var c=t.cd,u=c[0].trace,h=t.xa,f=t.ya,p=t.subplot,d=p.projection.isLonLatOverEdges,g=p.project;if(n.getClosest(c,function(t){var n=t.lonlat;if(n[0]===a)return 1/0;if(d(n))return 1/0;var i=g(n),o=g([e,r]),s=Math.abs(i[0]-o[0]),l=Math.abs(i[1]-o[1]),c=Math.max(3,t.mrc||0);return Math.max(Math.sqrt(s*s+l*l)-c,1-3/c)},t),!1!==t.index){var v=c[t.index],m=v.lonlat,y=[h.c2p(m),f.c2p(m)],x=v.mrc||1;return t.x0=y[0]-x,t.x1=y[0]+x,t.y0=y[1]-x,t.y1=y[1]+x,t.loc=v.loc,t.lon=m[0],t.lat=m[1],t.color=o(u,v),t.extraText=function(t,e,r,n){if(t.hovertemplate)return;var a=e.hi||t.hoverinfo,o="all"===a?l.hoverinfo.flags:a.split("+"),c=-1!==o.indexOf("location")&&Array.isArray(t.locations),u=-1!==o.indexOf("lon"),h=-1!==o.indexOf("lat"),f=-1!==o.indexOf("text"),p=[];function d(t){return i.tickText(r,r.c2l(t),"hover").text+"\xb0"}c?p.push(e.loc):u&&h?p.push("("+d(e.lonlat[0])+", "+d(e.lonlat[1])+")"):u?p.push(n.lon+d(e.lonlat[0])):h&&p.push(n.lat+d(e.lonlat[1]));f&&s(e,t,p);return p.join("<br>")}(u,v,p.mockAxis,c[0].t.labels),t.hovertemplate=u.hovertemplate,[t]}}},{"../../components/fx":613,"../../constants/numerical":674,"../../plots/cartesian/axes":745,"../scatter/fill_hover_text":1056,"../scatter/get_trace_color":1058,"./attributes":1088}],1093:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../scatter/marker_colorbar"),n.calc=t("./calc"),n.plot=t("./plot"),n.style=t("./style"),n.styleOnSelect=t("../scatter/style").styleOnSelect,n.hoverPoints=t("./hover"),n.eventData=t("./event_data"),n.selectPoints=t("./select"),n.moduleType="trace",n.name="scattergeo",n.basePlotModule=t("../../plots/geo"),n.categories=["geo","symbols","showLegend","scatter-like"],n.meta={},e.exports=n},{"../../plots/geo":775,"../scatter/marker_colorbar":1066,"../scatter/style":1071,"./attributes":1088,"./calc":1089,"./defaults":1090,"./event_data":1091,"./hover":1092,"./plot":1094,"./select":1095,"./style":1096}],1094:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../lib"),a=t("../../constants/numerical").BADNUM,o=t("../../lib/topojson_utils").getTopojsonFeatures,s=t("../../lib/geo_location_utils").locationToFeature,l=t("../../lib/geojson_utils"),c=t("../scatter/subtypes"),u=t("./style");function h(t,e){var r=t[0].trace;if(Array.isArray(r.locations))for(var n=o(r,e),i=r.locationmode,l=0;l<t.length;l++){var c=t[l],u=s(i,c.loc,n);c.lonlat=u?u.properties.ct:[a,a]}}e.exports=function(t,e,r){for(var o=0;o<r.length;o++)h(r[o],e.topojson);function s(t,e){t.lonlat[0]===a&&n.select(e).remove()}var f=e.layers.frontplot.select(".scatterlayer"),p=i.makeTraceGroups(f,r,"trace scattergeo");p.selectAll("*").remove(),p.each(function(e){var r=e[0].node3=n.select(this),a=e[0].trace;if(c.hasLines(a)||"none"!==a.fill){var o=l.calcTraceToLineCoords(e),h="none"!==a.fill?l.makePolygon(o):l.makeLine(o);r.selectAll("path.js-line").data([{geojson:h,trace:a}]).enter().append("path").classed("js-line",!0).style("stroke-miterlimit",2)}c.hasMarkers(a)&&r.selectAll("path.point").data(i.identity).enter().append("path").classed("point",!0).each(function(t){s(t,this)}),c.hasText(a)&&r.selectAll("g").data(i.identity).enter().append("g").append("text").each(function(t){s(t,this)}),u(t,e)})}},{"../../constants/numerical":674,"../../lib":697,"../../lib/geo_location_utils":690,"../../lib/geojson_utils":691,"../../lib/topojson_utils":724,"../scatter/subtypes":1072,"./style":1096,d3:151}],1095:[function(t,e,r){"use strict";var n=t("../scatter/subtypes"),i=t("../../constants/numerical").BADNUM;e.exports=function(t,e){var r,a,o,s,l,c=t.cd,u=t.xaxis,h=t.yaxis,f=[],p=c[0].trace;if(!n.hasMarkers(p)&&!n.hasText(p))return[];if(!1===e)for(l=0;l<c.length;l++)c[l].selected=0;else for(l=0;l<c.length;l++)(a=(r=c[l]).lonlat)[0]!==i&&(o=u.c2p(a),s=h.c2p(a),e.contains([o,s],null,l,t)?(f.push({pointNumber:l,lon:a[0],lat:a[1]}),r.selected=1):r.selected=0);return f}},{"../../constants/numerical":674,"../scatter/subtypes":1072}],1096:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../components/drawing"),a=t("../../components/color"),o=t("../scatter/style"),s=o.stylePoints,l=o.styleText;e.exports=function(t,e){e&&function(t,e){var r=e[0].trace,o=e[0].node3;o.style("opacity",e[0].trace.opacity),s(o,r,t),l(o,r,t),o.selectAll("path.js-line").style("fill","none").each(function(t){var e=n.select(this),r=t.trace,o=r.line||{};e.call(a.stroke,o.color).call(i.dashLine,o.dash||"",o.width||0),"none"!==r.fill&&e.call(a.fill,r.fillcolor)})}(t,e)}},{"../../components/color":574,"../../components/drawing":595,"../scatter/style":1071,d3:151}],1097:[function(t,e,r){"use strict";var n=t("../../plots/attributes"),i=t("../scatter/attributes"),a=t("../../components/colorscale/attributes"),o=t("../../lib/extend").extendFlat,s=t("../../plot_api/edit_types").overrideAll,l=t("./constants").DASHES,c=i.line,u=i.marker,h=u.line,f=e.exports=s({x:i.x,x0:i.x0,dx:i.dx,y:i.y,y0:i.y0,dy:i.dy,text:i.text,hovertext:i.hovertext,textposition:i.textposition,textfont:i.textfont,mode:{valType:"flaglist",flags:["lines","markers","text"],extras:["none"]},line:{color:c.color,width:c.width,shape:{valType:"enumerated",values:["linear","hv","vh","hvh","vhv"],dflt:"linear",editType:"plot"},dash:{valType:"enumerated",values:Object.keys(l),dflt:"solid"}},marker:o({},a("marker"),{symbol:u.symbol,size:u.size,sizeref:u.sizeref,sizemin:u.sizemin,sizemode:u.sizemode,opacity:u.opacity,colorbar:u.colorbar,line:o({},a("marker.line"),{width:h.width})}),connectgaps:i.connectgaps,fill:o({},i.fill,{dflt:"none"}),fillcolor:i.fillcolor,selected:{marker:i.selected.marker,textfont:i.selected.textfont},unselected:{marker:i.unselected.marker,textfont:i.unselected.textfont},opacity:n.opacity},"calc","nested");f.x.editType=f.y.editType=f.x0.editType=f.y0.editType="calc+clearAxisTypes",f.hovertemplate=i.hovertemplate},{"../../components/colorscale/attributes":581,"../../lib/extend":687,"../../plot_api/edit_types":728,"../../plots/attributes":742,"../scatter/attributes":1048,"./constants":1098}],1098:[function(t,e,r){"use strict";e.exports={TOO_MANY_POINTS:1e5,SYMBOL_SDF_SIZE:200,SYMBOL_SIZE:20,SYMBOL_STROKE:1,DOT_RE:/-dot/,OPEN_RE:/-open/,DASHES:{solid:[1],dot:[1,1],dash:[4,1],longdash:[8,1],dashdot:[4,1,1,1],longdashdot:[8,1,1,1]}}},{}],1099:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("svg-path-sdf"),a=t("color-normalize"),o=t("../../registry"),s=t("../../lib"),l=t("../../components/drawing"),c=t("../../plots/cartesian/axis_ids"),u=t("../../lib/gl_format_color").formatColor,h=t("../scatter/subtypes"),f=t("../scatter/make_bubble_size_func"),p=t("./constants"),d=t("../../constants/interactions").DESELECTDIM,g={start:1,left:1,end:-1,right:-1,middle:0,center:0,bottom:1,top:-1};function v(t){var e,r=t._length,i=t.textfont,a=t.textposition,o=Array.isArray(a)?a:[a],s=i.color,l=i.size,c=i.family,u={};for(u.text=t.text,u.opacity=t.opacity,u.font={},u.align=[],u.baseline=[],e=0;e<o.length;e++){var h=o[e].split(/\s+/);switch(h[1]){case"left":u.align.push("right");break;case"right":u.align.push("left");break;default:u.align.push(h[1])}switch(h[0]){case"top":u.baseline.push("bottom");break;case"bottom":u.baseline.push("top");break;default:u.baseline.push(h[0])}}if(Array.isArray(s))for(u.color=new Array(r),e=0;e<r;e++)u.color[e]=s[e];else u.color=s;if(Array.isArray(l)||Array.isArray(c))for(u.font=new Array(r),e=0;e<r;e++){var f=u.font[e]={};f.size=Array.isArray(l)?n(l[e])?l[e]:0:l,f.family=Array.isArray(c)?c[e]:c}else u.font={size:l,family:c};return u}function m(t){var e,r,n=t._length,i=t.marker,o={},l=Array.isArray(i.symbol),c=s.isArrayOrTypedArray(i.color),h=s.isArrayOrTypedArray(i.line.color),d=s.isArrayOrTypedArray(i.opacity),g=s.isArrayOrTypedArray(i.size),v=s.isArrayOrTypedArray(i.line.width);if(l||(r=p.OPEN_RE.test(i.symbol)),l||c||h||d){o.colors=new Array(n),o.borderColors=new Array(n);var m=u(i,i.opacity,n),y=u(i.line,i.opacity,n);if(!Array.isArray(y[0])){var x=y;for(y=Array(n),e=0;e<n;e++)y[e]=x}if(!Array.isArray(m[0])){var b=m;for(m=Array(n),e=0;e<n;e++)m[e]=b}for(o.colors=m,o.borderColors=y,e=0;e<n;e++){if(l){var _=i.symbol[e];r=p.OPEN_RE.test(_)}r&&(y[e]=m[e].slice(),m[e]=m[e].slice(),m[e][3]=0)}o.opacity=t.opacity}else r?(o.color=a(i.color,"uint8"),o.color[3]=0,o.borderColor=a(i.color,"uint8")):(o.color=a(i.color,"uint8"),o.borderColor=a(i.line.color,"uint8")),o.opacity=t.opacity*i.opacity;if(l)for(o.markers=new Array(n),e=0;e<n;e++)o.markers[e]=T(i.symbol[e]);else o.marker=T(i.symbol);var w,k=f(t);if(g||v){var A,M=o.sizes=new Array(n),S=o.borderSizes=new Array(n),E=0;if(g){for(e=0;e<n;e++)M[e]=k(i.size[e]),E+=M[e];A=E/n}else for(w=k(i.size),e=0;e<n;e++)M[e]=w;if(v)for(e=0;e<n;e++)S[e]=i.line.width[e]/2;else for(w=i.line.width/2,e=0;e<n;e++)S[e]=w;o.sizeAvg=A}else o.size=k(i&&i.size||10),o.borderSizes=k(i.line.width);return o}function y(t,e){var r=t.marker,n={};return e?(e.marker&&e.marker.symbol?n=m(s.extendFlat({},r,e.marker)):e.marker&&(e.marker.size&&(n.size=e.marker.size/2),e.marker.color&&(n.colors=e.marker.color),void 0!==e.marker.opacity&&(n.opacity=e.marker.opacity)),n):n}function x(t,e){var r={};if(!e)return r;if(e.textfont){var n={opacity:1,text:t.text,textposition:t.textposition,textfont:s.extendFlat({},t.textfont)};e.textfont&&s.extendFlat(n.textfont,e.textfont),r=v(n)}return r}function b(t,e){var r={capSize:2*e.width,lineWidth:e.thickness,color:e.color};return e.copy_ystyle&&(r=t.error_y),r}var _=p.SYMBOL_SDF_SIZE,w=p.SYMBOL_SIZE,k=p.SYMBOL_STROKE,A={},M=l.symbolFuncs[0](.05*w);function T(t){if("circle"===t)return null;var e,r,n=l.symbolNumber(t),a=l.symbolFuncs[n%100],o=!!l.symbolNoDot[n%100],s=!!l.symbolNoFill[n%100],c=p.DOT_RE.test(t);return A[t]?A[t]:(e=c&&!o?a(1.1*w)+M:a(w),r=i(e,{w:_,h:_,viewBox:[-w,-w,w,w],stroke:s?k:-k}),A[t]=r,r||null)}e.exports={style:function(t,e){var r,n={marker:void 0,markerSel:void 0,markerUnsel:void 0,line:void 0,fill:void 0,errorX:void 0,errorY:void 0,text:void 0,textSel:void 0,textUnsel:void 0};if(!0!==e.visible)return n;if(h.hasText(e)&&(n.text=v(e),n.textSel=x(e,e.selected),n.textUnsel=x(e,e.unselected)),h.hasMarkers(e)&&(n.marker=m(e),n.markerSel=y(e,e.selected),n.markerUnsel=y(e,e.unselected),!e.unselected&&Array.isArray(e.marker.opacity))){var i=e.marker.opacity;for(n.markerUnsel.opacity=new Array(i.length),r=0;r<i.length;r++)n.markerUnsel.opacity[r]=d*i[r]}if(h.hasLines(e)){n.line={overlay:!0,thickness:e.line.width,color:e.line.color,opacity:e.opacity};var a=(p.DASHES[e.line.dash]||[1]).slice();for(r=0;r<a.length;++r)a[r]*=e.line.width;n.line.dashes=a}return e.error_x&&e.error_x.visible&&(n.errorX=b(e,e.error_x)),e.error_y&&e.error_y.visible&&(n.errorY=b(e,e.error_y)),e.fill&&"none"!==e.fill&&(n.fill={closed:!0,fill:e.fillcolor,thickness:0}),n},markerStyle:m,markerSelection:y,linePositions:function(t,e,r){var n,i,a=r.length,o=a/2;if(h.hasLines(e)&&o)if("hv"===e.line.shape){for(n=[],i=0;i<o-1;i++)isNaN(r[2*i])||isNaN(r[2*i+1])?n.push(NaN,NaN,NaN,NaN):(n.push(r[2*i],r[2*i+1]),isNaN(r[2*i+2])||isNaN(r[2*i+3])?n.push(NaN,NaN):n.push(r[2*i+2],r[2*i+1]));n.push(r[a-2],r[a-1])}else if("hvh"===e.line.shape){for(n=[],i=0;i<o-1;i++)if(isNaN(r[2*i])||isNaN(r[2*i+1])||isNaN(r[2*i+2])||isNaN(r[2*i+3]))isNaN(r[2*i])||isNaN(r[2*i+1])?n.push(NaN,NaN):n.push(r[2*i],r[2*i+1]),n.push(NaN,NaN);else{var s=(r[2*i]+r[2*i+2])/2;n.push(r[2*i],r[2*i+1],s,r[2*i+1],s,r[2*i+3])}n.push(r[a-2],r[a-1])}else if("vhv"===e.line.shape){for(n=[],i=0;i<o-1;i++)if(isNaN(r[2*i])||isNaN(r[2*i+1])||isNaN(r[2*i+2])||isNaN(r[2*i+3]))isNaN(r[2*i])||isNaN(r[2*i+1])?n.push(NaN,NaN):n.push(r[2*i],r[2*i+1]),n.push(NaN,NaN);else{var l=(r[2*i+1]+r[2*i+3])/2;n.push(r[2*i],r[2*i+1],r[2*i],l,r[2*i+2],l)}n.push(r[a-2],r[a-1])}else if("vh"===e.line.shape){for(n=[],i=0;i<o-1;i++)isNaN(r[2*i])||isNaN(r[2*i+1])?n.push(NaN,NaN,NaN,NaN):(n.push(r[2*i],r[2*i+1]),isNaN(r[2*i+2])||isNaN(r[2*i+3])?n.push(NaN,NaN):n.push(r[2*i],r[2*i+3]));n.push(r[a-2],r[a-1])}else n=r;var c=!1;for(i=0;i<n.length;i++)if(isNaN(n[i])){c=!0;break}var u=c||n.length>p.TOO_MANY_POINTS?"rect":h.hasMarkers(e)?"rect":"round";if(c&&e.connectgaps){var f=n[0],d=n[1];for(i=0;i<n.length;i+=2)isNaN(n[i])||isNaN(n[i+1])?(n[i]=f,n[i+1]=d):(f=n[i],d=n[i+1])}return{join:u,positions:n}},errorBarPositions:function(t,e,r,i,a){var s=o.getComponentMethod("errorbars","makeComputeError"),l=c.getFromId(t,e.xaxis),u=c.getFromId(t,e.yaxis),h=r.length/2,f={};function p(t,i){var a=i._id.charAt(0),o=e["error_"+a];if(o&&o.visible&&("linear"===i.type||"log"===i.type)){for(var l=s(o),c={x:0,y:1}[a],u={x:[0,1,2,3],y:[2,3,0,1]}[a],p=new Float64Array(4*h),d=1/0,g=-1/0,v=0,m=0;v<h;v++,m+=4){var y=t[v];if(n(y)){var x=r[2*v+c],b=l(y,v),_=b[0],w=b[1];if(n(_)&&n(w)){var k=y-_,A=y+w;p[m+u[0]]=x-i.c2l(k),p[m+u[1]]=i.c2l(A)-x,p[m+u[2]]=0,p[m+u[3]]=0,d=Math.min(d,y-_),g=Math.max(g,y+w)}}}f[a]={positions:r,errors:p,_bnds:[d,g]}}}return p(i,l),p(a,u),f},textPosition:function(t,e,r,n){var i,a=e._length,o={};if(h.hasMarkers(e)){var s=r.font,l=r.align,c=r.baseline;for(o.offset=new Array(a),i=0;i<a;i++){var u=n.sizes?n.sizes[i]:n.size,f=Array.isArray(s)?s[i].size:s.size,p=Array.isArray(l)?l.length>1?l[i]:l[0]:l,d=Array.isArray(c)?c.length>1?c[i]:c[0]:c,v=g[p],m=g[d],y=u?u/.8+1:0,x=-m*y-.5*m;o.offset[i]=[v*y/f,x/f]}}return o}}},{"../../components/drawing":595,"../../constants/interactions":673,"../../lib":697,"../../lib/gl_format_color":694,"../../plots/cartesian/axis_ids":748,"../../registry":826,"../scatter/make_bubble_size_func":1065,"../scatter/subtypes":1072,"./constants":1098,"color-normalize":108,"fast-isnumeric":218,"svg-path-sdf":516}],1100:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../registry"),a=t("./attributes"),o=t("../scatter/constants"),s=t("../scatter/subtypes"),l=t("../scatter/xy_defaults"),c=t("../scatter/marker_defaults"),u=t("../scatter/line_defaults"),h=t("../scatter/fillcolor_defaults"),f=t("../scatter/text_defaults");e.exports=function(t,e,r,p){function d(r,i){return n.coerce(t,e,a,r,i)}var g=!!t.marker&&/-open/.test(t.marker.symbol),v=s.isBubble(t),m=l(t,e,p,d);if(m){var y=m<o.PTS_LINESONLY?"lines+markers":"lines";d("text"),d("hovertext"),d("hovertemplate"),d("mode",y),s.hasLines(e)&&(d("connectgaps"),u(t,e,r,p,d),d("line.shape")),s.hasMarkers(e)&&(c(t,e,r,p,d),d("marker.line.width",g||v?1:0)),s.hasText(e)&&f(t,e,p,d);var x=(e.line||{}).color,b=(e.marker||{}).color;d("fill"),"none"!==e.fill&&h(t,e,r,d);var _=i.getComponentMethod("errorbars","supplyDefaults");_(t,e,x||b||r,{axis:"y"}),_(t,e,x||b||r,{axis:"x",inherit:"y"}),n.coerceSelectionMarkerOpacity(e,d)}else e.visible=!1}},{"../../lib":697,"../../registry":826,"../scatter/constants":1052,"../scatter/fillcolor_defaults":1057,"../scatter/line_defaults":1061,"../scatter/marker_defaults":1067,"../scatter/subtypes":1072,"../scatter/text_defaults":1073,"../scatter/xy_defaults":1074,"./attributes":1097}],1101:[function(t,e,r){"use strict";var n=t("regl-scatter2d"),i=t("regl-line2d"),a=t("regl-error2d"),o=t("point-cluster"),s=t("array-range"),l=t("gl-text"),c=t("../../registry"),u=t("../../lib"),h=t("../../lib/prepare_regl"),f=t("../../plots/cartesian/axis_ids"),p=t("../../plots/cartesian/autorange").findExtremes,d=t("../../components/color"),g=t("../scatter/subtypes"),v=t("../scatter/calc"),m=v.calcMarkerSize,y=v.calcAxisExpansion,x=v.setFirstScatter,b=t("../scatter/colorscale_calc"),_=t("../scatter/link_traces"),w=t("../scatter/get_trace_color"),k=t("../scatter/fill_hover_text"),A=t("./convert"),M=t("../../constants/numerical").BADNUM,T=t("./constants").TOO_MANY_POINTS,S=t("../../constants/interactions").DESELECTDIM;function E(t,e,r){var n=t._extremes[e._id],i=p(e,r._bnds,{padded:!0});n.min=n.min.concat(i.min),n.max=n.max.concat(i.max)}function C(t,e){var r=e._scene,n={count:0,dirty:!0,lineOptions:[],fillOptions:[],markerOptions:[],markerSelectedOptions:[],markerUnselectedOptions:[],errorXOptions:[],errorYOptions:[],textOptions:[],textSelectedOptions:[],textUnselectedOptions:[]},i={selectBatch:null,unselectBatch:null,fill2d:!1,scatter2d:!1,error2d:!1,line2d:!1,glText:!1,select2d:null};return e._scene||((r=e._scene={}).init=function(){u.extendFlat(r,i,n)},r.init(),r.update=function(t){var e=u.repeat(t,r.count);if(r.fill2d&&r.fill2d.update(e),r.scatter2d&&r.scatter2d.update(e),r.line2d&&r.line2d.update(e),r.error2d&&r.error2d.update(e.concat(e)),r.select2d&&r.select2d.update(e),r.glText)for(var n=0;n<r.count;n++)r.glText[n].update(t)},r.draw=function(){for(var t=r.count,e=r.fill2d,n=r.error2d,i=r.line2d,a=r.scatter2d,o=r.glText,s=r.select2d,l=r.selectBatch,c=r.unselectBatch,u=0;u<t;u++)e&&r.fillOrder[u]&&e.draw(r.fillOrder[u]),i&&r.lineOptions[u]&&i.draw(u),n&&(r.errorXOptions[u]&&n.draw(u),r.errorYOptions[u]&&n.draw(u+t)),!a||!r.markerOptions[u]||l&&l[u]||a.draw(u),o[u]&&r.textOptions[u]&&o[u].render();a&&s&&l&&(s.draw(l),a.draw(c)),r.dirty=!1},r.destroy=function(){r.fill2d&&r.fill2d.destroy&&r.fill2d.destroy(),r.scatter2d&&r.scatter2d.destroy&&r.scatter2d.destroy(),r.error2d&&r.error2d.destroy&&r.error2d.destroy(),r.line2d&&r.line2d.destroy&&r.line2d.destroy(),r.select2d&&r.select2d.destroy&&r.select2d.destroy(),r.glText&&r.glText.forEach(function(t){t.destroy&&t.destroy()}),r.lineOptions=null,r.fillOptions=null,r.markerOptions=null,r.markerSelectedOptions=null,r.markerUnselectedOptions=null,r.errorXOptions=null,r.errorYOptions=null,r.textOptions=null,r.textSelectedOptions=null,r.textUnselectedOptions=null,r.selectBatch=null,r.unselectBatch=null,e._scene=null}),r.dirty||u.extendFlat(r,n),r}function L(t,e,r,n){var i=t.xa,a=t.ya,o=t.distance,s=t.dxy,l=t.index,h={pointNumber:l,x:e[l],y:r[l]};h.tx=Array.isArray(n.text)?n.text[l]:n.text,h.htx=Array.isArray(n.hovertext)?n.hovertext[l]:n.hovertext,h.data=Array.isArray(n.customdata)?n.customdata[l]:n.customdata,h.tp=Array.isArray(n.textposition)?n.textposition[l]:n.textposition;var f=n.textfont;f&&(h.ts=Array.isArray(f.size)?f.size[l]:f.size,h.tc=Array.isArray(f.color)?f.color[l]:f.color,h.tf=Array.isArray(f.family)?f.family[l]:f.family);var p=n.marker;p&&(h.ms=u.isArrayOrTypedArray(p.size)?p.size[l]:p.size,h.mo=u.isArrayOrTypedArray(p.opacity)?p.opacity[l]:p.opacity,h.mx=Array.isArray(p.symbol)?p.symbol[l]:p.symbol,h.mc=u.isArrayOrTypedArray(p.color)?p.color[l]:p.color);var d=p&&p.line;d&&(h.mlc=Array.isArray(d.color)?d.color[l]:d.color,h.mlw=u.isArrayOrTypedArray(d.width)?d.width[l]:d.width);var g=p&&p.gradient;g&&"none"!==g.type&&(h.mgt=Array.isArray(g.type)?g.type[l]:g.type,h.mgc=Array.isArray(g.color)?g.color[l]:g.color);var v=i.c2p(h.x,!0),m=a.c2p(h.y,!0),y=h.mrc||1,x=n.hoverlabel;x&&(h.hbg=Array.isArray(x.bgcolor)?x.bgcolor[l]:x.bgcolor,h.hbc=Array.isArray(x.bordercolor)?x.bordercolor[l]:x.bordercolor,h.hts=Array.isArray(x.font.size)?x.font.size[l]:x.font.size,h.htc=Array.isArray(x.font.color)?x.font.color[l]:x.font.color,h.htf=Array.isArray(x.font.family)?x.font.family[l]:x.font.family,h.hnl=Array.isArray(x.namelength)?x.namelength[l]:x.namelength);var b=n.hoverinfo;b&&(h.hi=Array.isArray(b)?b[l]:b);var _=n.hovertemplate;_&&(h.ht=Array.isArray(_)?_[l]:_);var A={};return A[t.index]=h,u.extendFlat(t,{color:w(n,h),x0:v-y,x1:v+y,xLabelVal:h.x,y0:m-y,y1:m+y,yLabelVal:h.y,cd:A,distance:o,spikeDistance:s,hovertemplate:h.ht}),h.htx?t.text=h.htx:h.tx?t.text=h.tx:n.text&&(t.text=n.text),k(h,n,t),c.getComponentMethod("errorbars","hoverInfo")(h,n,t),t}function z(t){var e,r,n=t[0],i=n.trace,a=n.t,o=a._scene,s=a.index,l=o.selectBatch[s],c=o.unselectBatch[s],h=o.textOptions[s],f=o.textSelectedOptions[s]||{},p=o.textUnselectedOptions[s]||{},g=u.extendFlat({},h);if(l&&c){var v=f.color,m=p.color,y=h.color,x=Array.isArray(y);for(g.color=new Array(i._length),e=0;e<l.length;e++)r=l[e],g.color[r]=v||(x?y[r]:y);for(e=0;e<c.length;e++){r=c[e];var b=x?y[r]:y;g.color[r]=m||(v?b:d.addOpacity(b,S))}}o.glText[s].update(g)}e.exports={moduleType:"trace",name:"scattergl",basePlotModule:t("../../plots/cartesian"),categories:["gl","regl","cartesian","symbols","errorBarsOK","showLegend","scatter-like"],attributes:t("./attributes"),supplyDefaults:t("./defaults"),crossTraceDefaults:t("../scatter/cross_trace_defaults"),colorbar:t("../scatter/marker_colorbar"),calc:function(t,e){var r,n,i,a=t._fullLayout,s=f.getFromId(t,e.xaxis),l=f.getFromId(t,e.yaxis),c=a._plots[e.xaxis+e.yaxis],h=e._length,p=h>=T,d=2*h,g={},v=s.makeCalcdata(e,"x"),_=l.makeCalcdata(e,"y"),w=new Array(d);for(r=0;r<h;r++)n=v[r],i=_[r],w[2*r]=n===M?NaN:n,w[2*r+1]=i===M?NaN:i;if("log"===s.type)for(r=0;r<d;r+=2)w[r]=s.c2l(w[r]);if("log"===l.type)for(r=1;r<d;r+=2)w[r]=l.c2l(w[r]);if(p&&"log"!==s.type&&"log"!==l.type)g.tree=o(w);else{var k=g.ids=new Array(h);for(r=0;r<h;r++)k[r]=r}b(t,e);var S,L=function(t,e,r,n,i,a){var o=A.style(t,r);if(o.marker&&(o.marker.positions=n),o.line&&n.length>1&&u.extendFlat(o.line,A.linePositions(t,r,n)),o.errorX||o.errorY){var s=A.errorBarPositions(t,r,n,i,a);o.errorX&&u.extendFlat(o.errorX,s.x),o.errorY&&u.extendFlat(o.errorY,s.y)}return o.text&&(u.extendFlat(o.text,{positions:n},A.textPosition(t,r,o.text,o.marker)),u.extendFlat(o.textSel,{positions:n},A.textPosition(t,r,o.text,o.markerSel)),u.extendFlat(o.textUnsel,{positions:n},A.textPosition(t,r,o.text,o.markerUnsel))),o}(t,0,e,w,v,_),z=C(0,c);return x(a,e),p?L.marker&&(S=2*(L.marker.sizeAvg||Math.max(L.marker.size,3))):S=m(e,h),y(t,e,s,l,v,_,S),L.errorX&&E(e,s,L.errorX),L.errorY&&E(e,l,L.errorY),L.fill&&!z.fill2d&&(z.fill2d=!0),L.marker&&!z.scatter2d&&(z.scatter2d=!0),L.line&&!z.line2d&&(z.line2d=!0),!L.errorX&&!L.errorY||z.error2d||(z.error2d=!0),L.text&&!z.glText&&(z.glText=!0),L.marker&&(L.marker.snap=g.tree||T),z.lineOptions.push(L.line),z.errorXOptions.push(L.errorX),z.errorYOptions.push(L.errorY),z.fillOptions.push(L.fill),z.markerOptions.push(L.marker),z.markerSelectedOptions.push(L.markerSel),z.markerUnselectedOptions.push(L.markerUnsel),z.textOptions.push(L.text),z.textSelectedOptions.push(L.textSel),z.textUnselectedOptions.push(L.textUnsel),g._scene=z,g.index=z.count,g.x=v,g.y=_,g.positions=w,z.count++,[{x:!1,y:!1,t:g,trace:e}]},plot:function(t,e,r){if(r.length){var o,s,c=t._fullLayout,f=e._scene,p=e.xaxis,d=e.yaxis;if(f)if(h(t,["ANGLE_instanced_arrays","OES_element_index_uint"])){var v=c._glcanvas.data()[0].regl;if(_(t,e,r),f.dirty){if(!0===f.error2d&&(f.error2d=a(v)),!0===f.line2d&&(f.line2d=i(v)),!0===f.scatter2d&&(f.scatter2d=n(v)),!0===f.fill2d&&(f.fill2d=i(v)),!0===f.glText)for(f.glText=new Array(f.count),o=0;o<f.count;o++)f.glText[o]=new l(v);if(f.glText){if(f.count>f.glText.length){var m=f.count-f.glText.length;for(o=0;o<m;o++)f.glText.push(new l(v))}else if(f.count<f.glText.length){var y=f.glText.length-f.count;f.glText.splice(f.count,y).forEach(function(t){t.destroy()})}for(o=0;o<f.count;o++)f.glText[o].update(f.textOptions[o])}if(f.line2d&&(f.line2d.update(f.lineOptions),f.lineOptions=f.lineOptions.map(function(t){if(t&&t.positions){for(var e=t.positions,r=0;r<e.length&&(isNaN(e[r])||isNaN(e[r+1]));)r+=2;for(var n=e.length-2;n>r&&(isNaN(e[n])||isNaN(e[n+1]));)n-=2;t.positions=e.slice(r,n+2)}return t}),f.line2d.update(f.lineOptions)),f.error2d){var x=(f.errorXOptions||[]).concat(f.errorYOptions||[]);f.error2d.update(x)}f.scatter2d&&f.scatter2d.update(f.markerOptions),f.fillOrder=u.repeat(null,f.count),f.fill2d&&(f.fillOptions=f.fillOptions.map(function(t,e){var n=r[e];if(t&&n&&n[0]&&n[0].trace){var i,a,o=n[0],s=o.trace,l=o.t,c=f.lineOptions[e],u=[];s._ownfill&&u.push(e),s._nexttrace&&u.push(e+1),u.length&&(f.fillOrder[e]=u);var h,p,d=[],g=c&&c.positions||l.positions;if("tozeroy"===s.fill){for(h=0;h<g.length&&isNaN(g[h+1]);)h+=2;for(p=g.length-2;p>h&&isNaN(g[p+1]);)p-=2;0!==g[h+1]&&(d=[g[h],0]),d=d.concat(g.slice(h,p+2)),0!==g[p+1]&&(d=d.concat([g[p],0]))}else if("tozerox"===s.fill){for(h=0;h<g.length&&isNaN(g[h]);)h+=2;for(p=g.length-2;p>h&&isNaN(g[p]);)p-=2;0!==g[h]&&(d=[0,g[h+1]]),d=d.concat(g.slice(h,p+2)),0!==g[p]&&(d=d.concat([0,g[p+1]]))}else if("toself"===s.fill||"tonext"===s.fill){for(d=[],i=0,a=0;a<g.length;a+=2)(isNaN(g[a])||isNaN(g[a+1]))&&((d=d.concat(g.slice(i,a))).push(g[i],g[i+1]),i=a+2);d=d.concat(g.slice(i)),i&&d.push(g[i],g[i+1])}else{var v=s._nexttrace;if(v){var m=f.lineOptions[e+1];if(m){var y=m.positions;if("tonexty"===s.fill){for(d=g.slice(),e=Math.floor(y.length/2);e--;){var x=y[2*e],b=y[2*e+1];isNaN(x)||isNaN(b)||d.push(x,b)}t.fill=v.fillcolor}}}}if(s._prevtrace&&"tonext"===s._prevtrace.fill){var _=f.lineOptions[e-1].positions,w=d.length/2,k=[i=w];for(a=0;a<_.length;a+=2)(isNaN(_[a])||isNaN(_[a+1]))&&(k.push(a/2+w+1),i=a+2);d=d.concat(_),t.hole=k}return t.fillmode=s.fill,t.opacity=s.opacity,t.positions=d,t}}),f.fill2d.update(f.fillOptions))}f.selectBatch=null,f.unselectBatch=null;var b=c.dragmode,w="lasso"===b||"select"===b,k=c.clickmode.indexOf("select")>-1;for(o=0;o<r.length;o++){var A=r[o][0],M=A.trace,T=A.t,S=T.index,E=M._length,C=T.x,L=T.y;if(M.selectedpoints||w||k){if(w||(w=!0),f.selectBatch||(f.selectBatch=[],f.unselectBatch=[]),M.selectedpoints){var O=f.selectBatch[S]=u.selIndices2selPoints(M),I={};for(s=0;s<O.length;s++)I[O[s]]=1;var D=[];for(s=0;s<E;s++)I[s]||D.push(s);f.unselectBatch[S]=D}var P=T.xpx=new Array(E),R=T.ypx=new Array(E);for(s=0;s<E;s++)P[s]=p.c2p(C[s]),R[s]=d.c2p(L[s])}else T.xpx=T.ypx=null}w?(f.select2d||(f.select2d=n(c._glcanvas.data()[1].regl)),f.scatter2d&&f.selectBatch&&f.selectBatch.length&&f.scatter2d.update(f.markerUnselectedOptions.map(function(t,e){return f.selectBatch[e]?t:null})),f.select2d&&(f.select2d.update(f.markerOptions),f.select2d.update(f.markerSelectedOptions)),f.glText&&r.forEach(function(t){var e=((t||[])[0]||{}).trace||{};g.hasText(e)&&z(t)})):f.scatter2d&&f.scatter2d.update(f.markerOptions);var F={viewport:function(t,e,r){var n=t._size,i=t.width,a=t.height;return[n.l+e.domain[0]*n.w,n.b+r.domain[0]*n.h,i-n.r-(1-e.domain[1])*n.w,a-n.t-(1-r.domain[1])*n.h]}(c,p,d),range:[(p._rl||p.range)[0],(d._rl||d.range)[0],(p._rl||p.range)[1],(d._rl||d.range)[1]]},B=u.repeat(F,f.count);f.fill2d&&f.fill2d.update(B),f.line2d&&f.line2d.update(B),f.error2d&&f.error2d.update(B.concat(B)),f.scatter2d&&f.scatter2d.update(B),f.select2d&&f.select2d.update(B),f.glText&&f.glText.forEach(function(t){t.update(F)})}else f.init()}},hoverPoints:function(t,e,r,n){var i,a,o,s,l,c,u,h,f,p=t.cd,d=p[0].t,g=p[0].trace,v=t.xa,m=t.ya,y=d.x,x=d.y,b=v.c2p(e),_=m.c2p(r),w=t.distance;if(d.tree){var k=v.p2c(b-w),A=v.p2c(b+w),M=m.p2c(_-w),T=m.p2c(_+w);i="x"===n?d.tree.range(Math.min(k,A),Math.min(m._rl[0],m._rl[1]),Math.max(k,A),Math.max(m._rl[0],m._rl[1])):d.tree.range(Math.min(k,A),Math.min(M,T),Math.max(k,A),Math.max(M,T))}else{if(!d.ids)return[t];i=d.ids}var S=w;if("x"===n)for(l=0;l<i.length;l++)o=y[i[l]],(c=Math.abs(v.c2p(o)-b))<S&&(S=c,u=m.c2p(x[i[l]])-_,f=Math.sqrt(c*c+u*u),a=i[l]);else for(l=0;l<i.length;l++)o=y[i[l]],s=x[i[l]],c=v.c2p(o)-b,u=m.c2p(s)-_,(h=Math.sqrt(c*c+u*u))<S&&(S=f=h,a=i[l]);return t.index=a,t.distance=S,t.dxy=f,void 0===a?[t]:(L(t,y,x,g),[t])},selectPoints:function(t,e){var r=t.cd,n=[],i=r[0].trace,a=r[0].t,o=i._length,l=a.x,c=a.y,u=a._scene;if(!u)return n;var h=g.hasText(i),f=g.hasMarkers(i),p=!f&&!h;if(!0!==i.visible||p)return n;var d,v=null,m=null;if(!1===e||e.degenerate)m=s(o);else for(v=[],m=[],d=0;d<o;d++)e.contains([a.xpx[d],a.ypx[d]],!1,d,t)?(v.push(d),n.push({pointNumber:d,x:l[d],y:c[d]})):m.push(d);if(u.selectBatch||(u.selectBatch=[],u.unselectBatch=[]),!u.selectBatch[a.index]){for(d=0;d<u.count;d++)u.selectBatch[d]=[],u.unselectBatch[d]=[];f&&u.scatter2d.update(u.markerUnselectedOptions)}return u.selectBatch[a.index]=v,u.unselectBatch[a.index]=m,h&&z(r),n},sceneUpdate:C,calcHover:L,meta:{}}},{"../../components/color":574,"../../constants/interactions":673,"../../constants/numerical":674,"../../lib":697,"../../lib/prepare_regl":710,"../../plots/cartesian":756,"../../plots/cartesian/autorange":744,"../../plots/cartesian/axis_ids":748,"../../registry":826,"../scatter/calc":1049,"../scatter/colorscale_calc":1051,"../scatter/cross_trace_defaults":1054,"../scatter/fill_hover_text":1056,"../scatter/get_trace_color":1058,"../scatter/link_traces":1064,"../scatter/marker_colorbar":1066,"../scatter/subtypes":1072,"./attributes":1097,"./constants":1098,"./convert":1099,"./defaults":1100,"array-range":55,"gl-text":310,"point-cluster":458,"regl-error2d":479,"regl-line2d":480,"regl-scatter2d":481}],1102:[function(t,e,r){"use strict";var n=t("../../components/fx/hovertemplate_attributes"),i=t("../scattergeo/attributes"),a=t("../scatter/attributes"),o=t("../../plots/mapbox/layout_attributes"),s=t("../../plots/attributes"),l=t("../../components/colorbar/attributes"),c=t("../../lib/extend").extendFlat,u=t("../../plot_api/edit_types").overrideAll,h=i.line,f=i.marker;e.exports=u({lon:i.lon,lat:i.lat,mode:c({},a.mode,{dflt:"markers"}),text:c({},a.text,{}),hovertext:c({},a.hovertext,{}),line:{color:h.color,width:h.width},connectgaps:a.connectgaps,marker:{symbol:{valType:"string",dflt:"circle",arrayOk:!0},opacity:f.opacity,size:f.size,sizeref:f.sizeref,sizemin:f.sizemin,sizemode:f.sizemode,color:f.color,colorscale:f.colorscale,cauto:f.cauto,cmax:f.cmax,cmin:f.cmin,cmid:f.cmid,autocolorscale:f.autocolorscale,reversescale:f.reversescale,showscale:f.showscale,colorbar:l},fill:i.fill,fillcolor:a.fillcolor,textfont:o.layers.symbol.textfont,textposition:o.layers.symbol.textposition,selected:{marker:a.selected.marker},unselected:{marker:a.unselected.marker},hoverinfo:c({},s.hoverinfo,{flags:["lon","lat","text","name"]}),hovertemplate:n()},"calc","nested")},{"../../components/colorbar/attributes":575,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plot_api/edit_types":728,"../../plots/attributes":742,"../../plots/mapbox/layout_attributes":803,"../scatter/attributes":1048,"../scattergeo/attributes":1088}],1103:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("../../constants/numerical").BADNUM,o=t("../../lib/geojson_utils"),s=t("../../components/colorscale"),l=t("../../components/drawing"),c=t("../scatter/make_bubble_size_func"),u=t("../scatter/subtypes"),h=t("../../plots/mapbox/convert_text_opts");function f(){return{geojson:o.makeBlank(),layout:{visibility:"none"},paint:{}}}function p(t){return i.isArrayOrTypedArray(t)?function(t){return t}:t?function(){return t}:d}function d(){return""}function g(t){return t[0]===a}e.exports=function(t){var e,r=t[0].trace,a=!0===r.visible,v="none"!==r.fill,m=u.hasLines(r),y=u.hasMarkers(r),x=u.hasText(r),b=y&&"circle"===r.marker.symbol,_=y&&"circle"!==r.marker.symbol,w=f(),k=f(),A=f(),M=f(),T={fill:w,line:k,circle:A,symbol:M};if(!a)return T;if((v||m)&&(e=o.calcTraceToLineCoords(t)),v&&(w.geojson=o.makePolygon(e),w.layout.visibility="visible",i.extendFlat(w.paint,{"fill-color":r.fillcolor})),m&&(k.geojson=o.makeLine(e),k.layout.visibility="visible",i.extendFlat(k.paint,{"line-width":r.line.width,"line-color":r.line.color,"line-opacity":r.opacity})),b){var S=function(t){var e,r,a,o,u=t[0].trace,h=u.marker,f=u.selectedpoints,p=i.isArrayOrTypedArray(h.color),d=i.isArrayOrTypedArray(h.size),v=i.isArrayOrTypedArray(h.opacity);function m(t){return u.opacity*t}p&&(r=s.hasColorscale(u,"marker")?s.makeColorScaleFunc(s.extractScale(h,{cLetter:"c"})):i.identity);d&&(a=c(u));v&&(o=function(t){var e=n(t)?+i.constrain(t,0,1):0;return m(e)});var y,x=[];for(e=0;e<t.length;e++){var b=t[e],_=b.lonlat;if(!g(_)){var w={};r&&(w.mcc=b.mcc=r(b.mc)),a&&(w.mrc=b.mrc=a(b.ms)),o&&(w.mo=o(b.mo)),f&&(w.selected=b.selected||0),x.push({type:"Feature",geometry:{type:"Point",coordinates:_},properties:w})}}if(f)for(y=l.makeSelectedPointStyleFns(u),e=0;e<x.length;e++){var k=x[e].properties;y.selectedOpacityFn&&(k.mo=m(y.selectedOpacityFn(k))),y.selectedColorFn&&(k.mcc=y.selectedColorFn(k)),y.selectedSizeFn&&(k.mrc=y.selectedSizeFn(k))}return{geojson:{type:"FeatureCollection",features:x},mcc:p||y&&y.selectedColorFn?{type:"identity",property:"mcc"}:h.color,mrc:d||y&&y.selectedSizeFn?{type:"identity",property:"mrc"}:(A=h.size,A/2),mo:v||y&&y.selectedOpacityFn?{type:"identity",property:"mo"}:m(h.opacity)};var A}(t);A.geojson=S.geojson,A.layout.visibility="visible",i.extendFlat(A.paint,{"circle-color":S.mcc,"circle-radius":S.mrc,"circle-opacity":S.mo})}if((_||x)&&(M.geojson=function(t){for(var e=t[0].trace,r=(e.marker||{}).symbol,n=e.text,i="circle"!==r?p(r):d,a=u.hasText(e)?p(n):d,o=[],s=0;s<t.length;s++){var l=t[s];g(l.lonlat)||o.push({type:"Feature",geometry:{type:"Point",coordinates:l.lonlat},properties:{symbol:i(l.mx),text:a(l.tx)}})}return{type:"FeatureCollection",features:o}}(t),i.extendFlat(M.layout,{visibility:"visible","icon-image":"{symbol}-15","text-field":"{text}"}),_&&(i.extendFlat(M.layout,{"icon-size":r.marker.size/10}),i.extendFlat(M.paint,{"icon-opacity":r.opacity*r.marker.opacity,"icon-color":r.marker.color})),x)){var E=(r.marker||{}).size,C=h(r.textposition,E);i.extendFlat(M.layout,{"text-size":r.textfont.size,"text-anchor":C.anchor,"text-offset":C.offset}),i.extendFlat(M.paint,{"text-color":r.textfont.color,"text-opacity":r.opacity})}return T}},{"../../components/colorscale":586,"../../components/drawing":595,"../../constants/numerical":674,"../../lib":697,"../../lib/geojson_utils":691,"../../plots/mapbox/convert_text_opts":800,"../scatter/make_bubble_size_func":1065,"../scatter/subtypes":1072,"fast-isnumeric":218}],1104:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../scatter/subtypes"),a=t("../scatter/marker_defaults"),o=t("../scatter/line_defaults"),s=t("../scatter/text_defaults"),l=t("../scatter/fillcolor_defaults"),c=t("./attributes");e.exports=function(t,e,r,u){function h(r,i){return n.coerce(t,e,c,r,i)}if(function(t,e,r){var n=r("lon")||[],i=r("lat")||[],a=Math.min(n.length,i.length);return e._length=a,a}(0,e,h)){if(h("text"),h("hovertext"),h("hovertemplate"),h("mode"),i.hasLines(e)&&(o(t,e,r,u,h,{noDash:!0}),h("connectgaps")),i.hasMarkers(e)){a(t,e,r,u,h,{noLine:!0});var f=e.marker;"circle"!==f.symbol&&(n.isArrayOrTypedArray(f.size)&&(f.size=f.size[0]),n.isArrayOrTypedArray(f.color)&&(f.color=f.color[0]))}i.hasText(e)&&s(t,e,u,h,{noSelect:!0}),h("fill"),"none"!==e.fill&&l(t,e,r,h),n.coerceSelectionMarkerOpacity(e,h)}else e.visible=!1}},{"../../lib":697,"../scatter/fillcolor_defaults":1057,"../scatter/line_defaults":1061,"../scatter/marker_defaults":1067,"../scatter/subtypes":1072,"../scatter/text_defaults":1073,"./attributes":1102}],1105:[function(t,e,r){"use strict";e.exports=function(t,e){return t.lon=e.lon,t.lat=e.lat,t}},{}],1106:[function(t,e,r){"use strict";var n=t("../../components/fx"),i=t("../../lib"),a=t("../scatter/get_trace_color"),o=t("../scatter/fill_hover_text"),s=t("../../constants/numerical").BADNUM;e.exports=function(t,e,r){var l=t.cd,c=l[0].trace,u=t.xa,h=t.ya,f=t.subplot,p=360*(e>=0?Math.floor((e+180)/360):Math.ceil((e-180)/360)),d=e-p;if(n.getClosest(l,function(t){var e=t.lonlat;if(e[0]===s)return 1/0;var n=i.modHalf(e[0],360),a=e[1],o=f.project([n,a]),l=o.x-u.c2p([d,a]),c=o.y-h.c2p([n,r]),p=Math.max(3,t.mrc||0);return Math.max(Math.sqrt(l*l+c*c)-p,1-3/p)},t),!1!==t.index){var g=l[t.index],v=g.lonlat,m=[i.modHalf(v[0],360)+p,v[1]],y=u.c2p(m),x=h.c2p(m),b=g.mrc||1;return t.x0=y-b,t.x1=y+b,t.y0=x-b,t.y1=x+b,t.color=a(c,g),t.extraText=function(t,e,r){if(t.hovertemplate)return;var n=(e.hi||t.hoverinfo).split("+"),i=-1!==n.indexOf("all"),a=-1!==n.indexOf("lon"),s=-1!==n.indexOf("lat"),l=e.lonlat,c=[];function u(t){return t+"\xb0"}i||a&&s?c.push("("+u(l[0])+", "+u(l[1])+")"):a?c.push(r.lon+u(l[0])):s&&c.push(r.lat+u(l[1]));(i||-1!==n.indexOf("text"))&&o(e,t,c);return c.join("<br>")}(c,g,l[0].t.labels),t.hovertemplate=c.hovertemplate,[t]}}},{"../../components/fx":613,"../../constants/numerical":674,"../../lib":697,"../scatter/fill_hover_text":1056,"../scatter/get_trace_color":1058}],1107:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../scatter/marker_colorbar"),n.calc=t("../scattergeo/calc"),n.plot=t("./plot"),n.hoverPoints=t("./hover"),n.eventData=t("./event_data"),n.selectPoints=t("./select"),n.style=function(t,e){e&&e[0].trace._glTrace.update(e)},n.moduleType="trace",n.name="scattermapbox",n.basePlotModule=t("../../plots/mapbox"),n.categories=["mapbox","gl","symbols","showLegend","scatterlike"],n.meta={},e.exports=n},{"../../plots/mapbox":801,"../scatter/marker_colorbar":1066,"../scattergeo/calc":1089,"./attributes":1102,"./defaults":1104,"./event_data":1105,"./hover":1106,"./plot":1108,"./select":1109}],1108:[function(t,e,r){"use strict";var n=t("./convert");function i(t,e){this.subplot=t,this.uid=e,this.sourceIds={fill:e+"-source-fill",line:e+"-source-line",circle:e+"-source-circle",symbol:e+"-source-symbol"},this.layerIds={fill:e+"-layer-fill",line:e+"-layer-line",circle:e+"-layer-circle",symbol:e+"-layer-symbol"},this.order=["fill","line","circle","symbol"]}var a=i.prototype;a.addSource=function(t,e){this.subplot.map.addSource(this.sourceIds[t],{type:"geojson",data:e.geojson})},a.setSourceData=function(t,e){this.subplot.map.getSource(this.sourceIds[t]).setData(e.geojson)},a.addLayer=function(t,e){this.subplot.map.addLayer({type:t,id:this.layerIds[t],source:this.sourceIds[t],layout:e.layout,paint:e.paint})},a.update=function(t){for(var e=this.subplot,r=n(t),i=0;i<this.order.length;i++){var a=this.order[i],o=r[a];e.setOptions(this.layerIds[a],"setLayoutProperty",o.layout),"visible"===o.layout.visibility&&(this.setSourceData(a,o),e.setOptions(this.layerIds[a],"setPaintProperty",o.paint))}t[0].trace._glTrace=this},a.dispose=function(){for(var t=this.subplot.map,e=0;e<this.order.length;e++){var r=this.order[e];t.removeLayer(this.layerIds[r]),t.removeSource(this.sourceIds[r])}},e.exports=function(t,e){for(var r=new i(t,e[0].trace.uid),a=n(e),o=0;o<r.order.length;o++){var s=r.order[o],l=a[s];r.addSource(s,l),r.addLayer(s,l)}return e[0].trace._glTrace=r,r}},{"./convert":1103}],1109:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../scatter/subtypes"),a=t("../../constants/numerical").BADNUM;e.exports=function(t,e){var r,o=t.cd,s=t.xaxis,l=t.yaxis,c=[],u=o[0].trace;if(!i.hasMarkers(u))return[];if(!1===e)for(r=0;r<o.length;r++)o[r].selected=0;else for(r=0;r<o.length;r++){var h=o[r],f=h.lonlat;if(f[0]!==a){var p=[n.modHalf(f[0],360),f[1]],d=[s.c2p(p),l.c2p(p)];e.contains(d,null,r,t)?(c.push({pointNumber:r,lon:f[0],lat:f[1]}),h.selected=1):h.selected=0}}return c}},{"../../constants/numerical":674,"../../lib":697,"../scatter/subtypes":1072}],1110:[function(t,e,r){"use strict";var n=t("../../components/fx/hovertemplate_attributes"),i=t("../../lib/extend").extendFlat,a=t("../scatter/attributes"),o=t("../../plots/attributes"),s=a.line;e.exports={mode:a.mode,r:{valType:"data_array",editType:"calc+clearAxisTypes"},theta:{valType:"data_array",editType:"calc+clearAxisTypes"},r0:{valType:"any",dflt:0,editType:"calc+clearAxisTypes"},dr:{valType:"number",dflt:1,editType:"calc"},theta0:{valType:"any",dflt:0,editType:"calc+clearAxisTypes"},dtheta:{valType:"number",editType:"calc"},thetaunit:{valType:"enumerated",values:["radians","degrees","gradians"],dflt:"degrees",editType:"calc+clearAxisTypes"},text:a.text,hovertext:a.hovertext,line:{color:s.color,width:s.width,dash:s.dash,shape:i({},s.shape,{values:["linear","spline"]}),smoothing:s.smoothing,editType:"calc"},connectgaps:a.connectgaps,marker:a.marker,cliponaxis:i({},a.cliponaxis,{dflt:!1}),textposition:a.textposition,textfont:a.textfont,fill:i({},a.fill,{values:["none","toself","tonext"],dflt:"none"}),fillcolor:a.fillcolor,hoverinfo:i({},o.hoverinfo,{flags:["r","theta","text","name"]}),hoveron:a.hoveron,hovertemplate:n(),selected:a.selected,unselected:a.unselected}},{"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plots/attributes":742,"../scatter/attributes":1048}],1111:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../constants/numerical").BADNUM,a=t("../../plots/cartesian/axes"),o=t("../scatter/colorscale_calc"),s=t("../scatter/arrays_to_calcdata"),l=t("../scatter/calc_selection"),c=t("../scatter/calc").calcMarkerSize;e.exports=function(t,e){for(var r=t._fullLayout,u=e.subplot,h=r[u].radialaxis,f=r[u].angularaxis,p=h.makeCalcdata(e,"r"),d=f.makeCalcdata(e,"theta"),g=e._length,v=new Array(g),m=0;m<g;m++){var y=p[m],x=d[m],b=v[m]={};n(y)&&n(x)?(b.r=y,b.theta=x):b.r=i}var _=c(e,g);return e._extremes.x=a.findExtremes(h,p,{ppad:_}),o(t,e),s(v,e),l(v,e),v}},{"../../constants/numerical":674,"../../plots/cartesian/axes":745,"../scatter/arrays_to_calcdata":1047,"../scatter/calc":1049,"../scatter/calc_selection":1050,"../scatter/colorscale_calc":1051,"fast-isnumeric":218}],1112:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../scatter/subtypes"),a=t("../scatter/marker_defaults"),o=t("../scatter/line_defaults"),s=t("../scatter/line_shape_defaults"),l=t("../scatter/text_defaults"),c=t("../scatter/fillcolor_defaults"),u=t("../scatter/constants").PTS_LINESONLY,h=t("./attributes");function f(t,e,r,n){var i,a=n("r"),o=n("theta");if(a)o?i=Math.min(a.length,o.length):(i=a.length,n("theta0"),n("dtheta"));else{if(!o)return 0;i=e.theta.length,n("r0"),n("dr")}return e._length=i,i}e.exports={handleRThetaDefaults:f,supplyDefaults:function(t,e,r,p){function d(r,i){return n.coerce(t,e,h,r,i)}var g=f(0,e,0,d);if(g){d("thetaunit"),d("mode",g<u?"lines+markers":"lines"),d("text"),d("hovertext"),"fills"!==e.hoveron&&d("hovertemplate"),i.hasLines(e)&&(o(t,e,r,p,d),s(t,e,d),d("connectgaps")),i.hasMarkers(e)&&a(t,e,r,p,d,{gradient:!0}),i.hasText(e)&&l(t,e,p,d);var v=[];(i.hasMarkers(e)||i.hasText(e))&&(d("cliponaxis"),d("marker.maxdisplayed"),v.push("points")),d("fill"),"none"!==e.fill&&(c(t,e,r,d),i.hasLines(e)||s(t,e,d)),"tonext"!==e.fill&&"toself"!==e.fill||v.push("fills"),d("hoveron",v.join("+")||"points"),n.coerceSelectionMarkerOpacity(e,d)}else e.visible=!1}}},{"../../lib":697,"../scatter/constants":1052,"../scatter/fillcolor_defaults":1057,"../scatter/line_defaults":1061,"../scatter/line_shape_defaults":1063,"../scatter/marker_defaults":1067,"../scatter/subtypes":1072,"../scatter/text_defaults":1073,"./attributes":1110}],1113:[function(t,e,r){"use strict";var n=t("../scatter/hover"),i=t("../../plots/cartesian/axes"),a=t("../../lib");function o(t,e,r,n){var o=r.radialAxis,s=r.angularAxis;o._hovertitle="r",s._hovertitle="\u03b8";var l=t.hi||e.hoverinfo,c=[];function u(t,e){c.push(t._hovertitle+": "+i.tickText(t,e,"hover").text)}if(!e.hovertemplate){var h=l.split("+");if(-1!==h.indexOf("all")&&(h=["r","theta","text"]),-1!==h.indexOf("r")&&u(o,o.c2l(t.r)),-1!==h.indexOf("theta")){var f=t.theta;u(s,"degrees"===s.thetaunit?a.rad2deg(f):f)}-1!==h.indexOf("text")&&n.text&&(c.push(n.text),delete n.text),n.extraText=c.join("<br>")}}e.exports={hoverPoints:function(t,e,r,i){var a=n(t,e,r,i);if(a&&!1!==a[0].index){var s=a[0];if(void 0===s.index)return a;var l=t.subplot,c=s.cd[s.index],u=s.trace;if(l.isPtInside(c))return s.xLabelVal=void 0,s.yLabelVal=void 0,o(c,u,l,s),s.hovertemplate=u.hovertemplate,a}},makeHoverPointText:o}},{"../../lib":697,"../../plots/cartesian/axes":745,"../scatter/hover":1059}],1114:[function(t,e,r){"use strict";e.exports={moduleType:"trace",name:"scatterpolar",basePlotModule:t("../../plots/polar"),categories:["polar","symbols","showLegend","scatter-like"],attributes:t("./attributes"),supplyDefaults:t("./defaults").supplyDefaults,colorbar:t("../scatter/marker_colorbar"),calc:t("./calc"),plot:t("./plot"),style:t("../scatter/style").style,hoverPoints:t("./hover").hoverPoints,selectPoints:t("../scatter/select"),meta:{}}},{"../../plots/polar":810,"../scatter/marker_colorbar":1066,"../scatter/select":1069,"../scatter/style":1071,"./attributes":1110,"./calc":1111,"./defaults":1112,"./hover":1113,"./plot":1115}],1115:[function(t,e,r){"use strict";var n=t("../scatter/plot"),i=t("../../constants/numerical").BADNUM;e.exports=function(t,e,r){for(var a=e.layers.frontplot.select("g.scatterlayer"),o={xaxis:e.xaxis,yaxis:e.yaxis,plot:e.framework,layerClipId:e._hasClipOnAxisFalse?e.clipIds.forTraces:null},s=e.radialAxis,l=e.angularAxis,c=0;c<r.length;c++)for(var u=r[c],h=0;h<u.length;h++){var f=u[h],p=f.r;if(p===i)f.x=f.y=i;else{var d=s.c2g(p),g=l.c2g(f.theta);f.x=d*Math.cos(g),f.y=d*Math.sin(g)}}n(t,o,r,a)}},{"../../constants/numerical":674,"../scatter/plot":1068}],1116:[function(t,e,r){"use strict";var n=t("../scatterpolar/attributes"),i=t("../scattergl/attributes");e.exports={mode:n.mode,r:n.r,theta:n.theta,r0:n.r0,dr:n.dr,theta0:n.theta0,dtheta:n.dtheta,thetaunit:n.thetaunit,text:n.text,hovertext:n.hovertext,hovertemplate:n.hovertemplate,line:i.line,connectgaps:i.connectgaps,marker:i.marker,fill:i.fill,fillcolor:i.fillcolor,textposition:i.textposition,textfont:i.textfont,hoverinfo:n.hoverinfo,selected:n.selected,unselected:n.unselected}},{"../scattergl/attributes":1097,"../scatterpolar/attributes":1110}],1117:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../scatter/subtypes"),a=t("../scatterpolar/defaults").handleRThetaDefaults,o=t("../scatter/marker_defaults"),s=t("../scatter/line_defaults"),l=t("../scatter/text_defaults"),c=t("../scatter/fillcolor_defaults"),u=t("../scatter/constants").PTS_LINESONLY,h=t("./attributes");e.exports=function(t,e,r,f){function p(r,i){return n.coerce(t,e,h,r,i)}var d=a(t,e,f,p);d?(p("thetaunit"),p("mode",d<u?"lines+markers":"lines"),p("text"),p("hovertext"),"fills"!==e.hoveron&&p("hovertemplate"),i.hasLines(e)&&(s(t,e,r,f,p),p("connectgaps")),i.hasMarkers(e)&&o(t,e,r,f,p),i.hasText(e)&&l(t,e,f,p),p("fill"),"none"!==e.fill&&c(t,e,r,p),n.coerceSelectionMarkerOpacity(e,p)):e.visible=!1}},{"../../lib":697,"../scatter/constants":1052,"../scatter/fillcolor_defaults":1057,"../scatter/line_defaults":1061,"../scatter/marker_defaults":1067,"../scatter/subtypes":1072,"../scatter/text_defaults":1073,"../scatterpolar/defaults":1112,"./attributes":1116}],1118:[function(t,e,r){"use strict";var n=t("point-cluster"),i=t("fast-isnumeric"),a=t("../scattergl"),o=t("../scatter/colorscale_calc"),s=t("../scatter/calc").calcMarkerSize,l=t("../scattergl/convert"),c=t("../../lib"),u=t("../../plots/cartesian/axes"),h=t("../scatterpolar/hover").makeHoverPointText,f=t("../scattergl/constants").TOO_MANY_POINTS;e.exports={moduleType:"trace",name:"scatterpolargl",basePlotModule:t("../../plots/polar"),categories:["gl","regl","polar","symbols","showLegend","scatter-like"],attributes:t("./attributes"),supplyDefaults:t("./defaults"),colorbar:t("../scatter/marker_colorbar"),calc:function(t,e){var r=t._fullLayout,n=e.subplot,i=r[n].radialaxis,a=r[n].angularaxis,c=i.makeCalcdata(e,"r"),h=a.makeCalcdata(e,"theta"),p=e._length,d={};p<c.length&&(c=c.slice(0,p)),p<h.length&&(h=h.slice(0,p)),d.r=c,d.theta=h,o(t,e);var g,v=d.opts=l.style(t,e);return p<f?g=s(e,p):v.marker&&(g=2*(v.marker.sizeAvg||Math.max(v.marker.size,3))),e._extremes.x=u.findExtremes(i,c,{ppad:g}),[{x:!1,y:!1,t:d,trace:e}]},plot:function(t,e,r){if(r.length){var o=e.radialAxis,s=e.angularAxis,u=a.sceneUpdate(t,e);return r.forEach(function(r){if(r&&r[0]&&r[0].trace){var a,h=r[0],p=h.trace,d=h.t,g=p._length,v=d.r,m=d.theta,y=d.opts,x=v.slice(),b=m.slice();for(a=0;a<v.length;a++)e.isPtInside({r:v[a],theta:m[a]})||(x[a]=NaN,b[a]=NaN);var _=new Array(2*g),w=Array(g),k=Array(g);for(a=0;a<g;a++){var A,M,T=x[a];if(i(T)){var S=o.c2g(T),E=s.c2g(b[a],p.thetaunit);A=S*Math.cos(E),M=S*Math.sin(E)}else A=M=NaN;w[a]=_[2*a]=A,k[a]=_[2*a+1]=M}d.tree=n(_),y.marker&&g>=f&&(y.marker.cluster=d.tree),y.marker&&(y.markerSel.positions=y.markerUnsel.positions=y.marker.positions=_),y.line&&_.length>1&&c.extendFlat(y.line,l.linePositions(t,p,_)),y.text&&(c.extendFlat(y.text,{positions:_},l.textPosition(t,p,y.text,y.marker)),c.extendFlat(y.textSel,{positions:_},l.textPosition(t,p,y.text,y.markerSel)),c.extendFlat(y.textUnsel,{positions:_},l.textPosition(t,p,y.text,y.markerUnsel))),y.fill&&!u.fill2d&&(u.fill2d=!0),y.marker&&!u.scatter2d&&(u.scatter2d=!0),y.line&&!u.line2d&&(u.line2d=!0),y.text&&!u.glText&&(u.glText=!0),u.lineOptions.push(y.line),u.fillOptions.push(y.fill),u.markerOptions.push(y.marker),u.markerSelectedOptions.push(y.markerSel),u.markerUnselectedOptions.push(y.markerUnsel),u.textOptions.push(y.text),u.textSelectedOptions.push(y.textSel),u.textUnselectedOptions.push(y.textUnsel),d.x=w,d.y=k,d.rawx=w,d.rawy=k,d.r=v,d.theta=m,d.positions=_,d._scene=u,d.index=u.count,u.count++}}),a.plot(t,e,r)}},hoverPoints:function(t,e,r,n){var i=t.cd[0].t,o=i.r,s=i.theta,l=a.hoverPoints(t,e,r,n);if(l&&!1!==l[0].index){var c=l[0];if(void 0===c.index)return l;var u=t.subplot,f=c.cd[c.index],p=c.trace;if(f.r=o[c.index],f.theta=s[c.index],u.isPtInside(f))return c.xLabelVal=void 0,c.yLabelVal=void 0,h(f,p,u,c),l}},selectPoints:a.selectPoints,meta:{}}},{"../../lib":697,"../../plots/cartesian/axes":745,"../../plots/polar":810,"../scatter/calc":1049,"../scatter/colorscale_calc":1051,"../scatter/marker_colorbar":1066,"../scattergl":1101,"../scattergl/constants":1098,"../scattergl/convert":1099,"../scatterpolar/hover":1113,"./attributes":1116,"./defaults":1117,"fast-isnumeric":218,"point-cluster":458}],1119:[function(t,e,r){"use strict";var n=t("../../components/fx/hovertemplate_attributes"),i=t("../scatter/attributes"),a=t("../../plots/attributes"),o=t("../../components/colorscale/attributes"),s=t("../../components/colorbar/attributes"),l=t("../../components/drawing/attributes").dash,c=t("../../lib/extend").extendFlat,u=i.marker,h=i.line,f=u.line;e.exports={a:{valType:"data_array",editType:"calc"},b:{valType:"data_array",editType:"calc"},c:{valType:"data_array",editType:"calc"},sum:{valType:"number",dflt:0,min:0,editType:"calc"},mode:c({},i.mode,{dflt:"markers"}),text:c({},i.text,{}),hovertext:c({},i.hovertext,{}),line:{color:h.color,width:h.width,dash:l,shape:c({},h.shape,{values:["linear","spline"]}),smoothing:h.smoothing,editType:"calc"},connectgaps:i.connectgaps,cliponaxis:i.cliponaxis,fill:c({},i.fill,{values:["none","toself","tonext"],dflt:"none"}),fillcolor:i.fillcolor,marker:c({symbol:u.symbol,opacity:u.opacity,maxdisplayed:u.maxdisplayed,size:u.size,sizeref:u.sizeref,sizemin:u.sizemin,sizemode:u.sizemode,line:c({width:f.width,editType:"calc"},o("marker.line")),gradient:u.gradient,editType:"calc"},o("marker"),{colorbar:s}),textfont:i.textfont,textposition:i.textposition,selected:i.selected,unselected:i.unselected,hoverinfo:c({},a.hoverinfo,{flags:["a","b","c","text","name"]}),hoveron:i.hoveron,hovertemplate:n()}},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/drawing/attributes":594,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plots/attributes":742,"../scatter/attributes":1048}],1120:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../scatter/colorscale_calc"),a=t("../scatter/arrays_to_calcdata"),o=t("../scatter/calc_selection"),s=t("../scatter/calc").calcMarkerSize,l=["a","b","c"],c={a:["b","c"],b:["a","c"],c:["a","b"]};e.exports=function(t,e){var r,u,h,f,p,d,g=t._fullLayout[e.subplot].sum,v=e.sum||g,m={a:e.a,b:e.b,c:e.c};for(r=0;r<l.length;r++)if(!m[h=l[r]]){for(p=m[c[h][0]],d=m[c[h][1]],f=new Array(p.length),u=0;u<p.length;u++)f[u]=v-p[u]-d[u];m[h]=f}var y,x,b,_,w,k,A=e._length,M=new Array(A);for(r=0;r<A;r++)y=m.a[r],x=m.b[r],b=m.c[r],n(y)&&n(x)&&n(b)?(1!==(_=g/((y=+y)+(x=+x)+(b=+b)))&&(y*=_,x*=_,b*=_),k=y,w=b-x,M[r]={x:w,y:k,a:y,b:x,c:b}):M[r]={x:!1,y:!1};return s(e,A),i(t,e),a(M,e),o(M,e),M}},{"../scatter/arrays_to_calcdata":1047,"../scatter/calc":1049,"../scatter/calc_selection":1050,"../scatter/colorscale_calc":1051,"fast-isnumeric":218}],1121:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../scatter/constants"),a=t("../scatter/subtypes"),o=t("../scatter/marker_defaults"),s=t("../scatter/line_defaults"),l=t("../scatter/line_shape_defaults"),c=t("../scatter/text_defaults"),u=t("../scatter/fillcolor_defaults"),h=t("./attributes");e.exports=function(t,e,r,f){function p(r,i){return n.coerce(t,e,h,r,i)}var d,g=p("a"),v=p("b"),m=p("c");if(g?(d=g.length,v?(d=Math.min(d,v.length),m&&(d=Math.min(d,m.length))):d=m?Math.min(d,m.length):0):v&&m&&(d=Math.min(v.length,m.length)),d){e._length=d,p("sum"),p("text"),p("hovertext"),"fills"!==e.hoveron&&p("hovertemplate"),p("mode",d<i.PTS_LINESONLY?"lines+markers":"lines"),a.hasLines(e)&&(s(t,e,r,f,p),l(t,e,p),p("connectgaps")),a.hasMarkers(e)&&o(t,e,r,f,p,{gradient:!0}),a.hasText(e)&&c(t,e,f,p);var y=[];(a.hasMarkers(e)||a.hasText(e))&&(p("cliponaxis"),p("marker.maxdisplayed"),y.push("points")),p("fill"),"none"!==e.fill&&(u(t,e,r,p),a.hasLines(e)||l(t,e,p)),"tonext"!==e.fill&&"toself"!==e.fill||y.push("fills"),p("hoveron",y.join("+")||"points"),n.coerceSelectionMarkerOpacity(e,p)}else e.visible=!1}},{"../../lib":697,"../scatter/constants":1052,"../scatter/fillcolor_defaults":1057,"../scatter/line_defaults":1061,"../scatter/line_shape_defaults":1063,"../scatter/marker_defaults":1067,"../scatter/subtypes":1072,"../scatter/text_defaults":1073,"./attributes":1119}],1122:[function(t,e,r){"use strict";e.exports=function(t,e,r,n,i){if(e.xa&&(t.xaxis=e.xa),e.ya&&(t.yaxis=e.ya),n[i]){var a=n[i];t.a=a.a,t.b=a.b,t.c=a.c}else t.a=e.a,t.b=e.b,t.c=e.c;return t}},{}],1123:[function(t,e,r){"use strict";var n=t("../scatter/hover"),i=t("../../plots/cartesian/axes");e.exports=function(t,e,r,a){var o=n(t,e,r,a);if(o&&!1!==o[0].index){var s=o[0];if(void 0===s.index){var l=1-s.y0/t.ya._length,c=t.xa._length,u=c*l/2,h=c-u;return s.x0=Math.max(Math.min(s.x0,h),u),s.x1=Math.max(Math.min(s.x1,h),u),o}var f=s.cd[s.index];s.a=f.a,s.b=f.b,s.c=f.c,s.xLabelVal=void 0,s.yLabelVal=void 0;var p=s.trace,d=s.subplot,g=f.hi||p.hoverinfo,v=[];if(!p.hovertemplate){var m=g.split("+");-1!==m.indexOf("all")&&(m=["a","b","c"]),-1!==m.indexOf("a")&&y(d.aaxis,f.a),-1!==m.indexOf("b")&&y(d.baxis,f.b),-1!==m.indexOf("c")&&y(d.caxis,f.c)}return s.extraText=v.join("<br>"),s.hovertemplate=p.hovertemplate,o}function y(t,e){v.push(t._hovertitle+": "+i.tickText(t,e,"hover").text)}}},{"../../plots/cartesian/axes":745,"../scatter/hover":1059}],1124:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../scatter/marker_colorbar"),n.calc=t("./calc"),n.plot=t("./plot"),n.style=t("../scatter/style").style,n.styleOnSelect=t("../scatter/style").styleOnSelect,n.hoverPoints=t("./hover"),n.selectPoints=t("../scatter/select"),n.eventData=t("./event_data"),n.moduleType="trace",n.name="scatterternary",n.basePlotModule=t("../../plots/ternary"),n.categories=["ternary","symbols","showLegend","scatter-like"],n.meta={},e.exports=n},{"../../plots/ternary":822,"../scatter/marker_colorbar":1066,"../scatter/select":1069,"../scatter/style":1071,"./attributes":1119,"./calc":1120,"./defaults":1121,"./event_data":1122,"./hover":1123,"./plot":1125}],1125:[function(t,e,r){"use strict";var n=t("../scatter/plot");e.exports=function(t,e,r){var i=e.plotContainer;i.select(".scatterlayer").selectAll("*").remove();var a={xaxis:e.xaxis,yaxis:e.yaxis,plot:i,layerClipId:e._hasClipOnAxisFalse?e.clipIdRelative:null},o=e.layers.frontplot.select("g.scatterlayer");n(t,a,r,o)}},{"../scatter/plot":1068}],1126:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../components/colorscale/attributes"),a=t("../../components/fx/hovertemplate_attributes"),o=t("../scattergl/attributes"),s=t("../../plots/cartesian/constants").idRegex,l=t("../../plot_api/plot_template").templatedArray,c=t("../../lib/extend").extendFlat,u=n.marker,h=u.line,f=c(i("marker.line",{editTypeOverride:"calc"}),{width:c({},h.width,{editType:"calc"}),editType:"calc"}),p=c(i("marker"),{symbol:u.symbol,size:c({},u.size,{editType:"markerSize"}),sizeref:u.sizeref,sizemin:u.sizemin,sizemode:u.sizemode,opacity:u.opacity,colorbar:u.colorbar,line:f,editType:"calc"});function d(t){return{valType:"info_array",freeLength:!0,editType:"calc",items:{valType:"subplotid",regex:s[t],editType:"plot"}}}p.color.editType=p.cmin.editType=p.cmax.editType="style",e.exports={dimensions:l("dimension",{visible:{valType:"boolean",dflt:!0,editType:"calc"},label:{valType:"string",editType:"calc"},values:{valType:"data_array",editType:"calc+clearAxisTypes"},axis:{type:{valType:"enumerated",values:["linear","log","date","category"],editType:"calc+clearAxisTypes"},matches:{valType:"boolean",dflt:!1,editType:"calc"},editType:"calc+clearAxisTypes"},editType:"calc+clearAxisTypes"}),text:c({},o.text,{}),hovertext:c({},o.hovertext,{}),hovertemplate:a(),marker:p,xaxes:d("x"),yaxes:d("y"),diagonal:{visible:{valType:"boolean",dflt:!0,editType:"calc"},editType:"calc"},showupperhalf:{valType:"boolean",dflt:!0,editType:"calc"},showlowerhalf:{valType:"boolean",dflt:!0,editType:"calc"},selected:{marker:o.selected.marker,editType:"calc"},unselected:{marker:o.unselected.marker,editType:"calc"},opacity:o.opacity}},{"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plot_api/plot_template":735,"../../plots/cartesian/constants":751,"../scatter/attributes":1048,"../scattergl/attributes":1097}],1127:[function(t,e,r){"use strict";var n=t("regl-line2d"),i=t("../../registry"),a=t("../../lib/prepare_regl"),o=t("../../plots/get_data").getModuleCalcData,s=t("../../plots/cartesian"),l=t("../../plots/cartesian/axis_ids").getFromId,c=t("../../plots/cartesian/axes").shouldShowZeroLine,u="splom";function h(t,e,r){for(var n=r.matrixOptions.data.length,i=e._visibleDims,a=r.viewOpts.ranges=new Array(n),o=0;o<i.length;o++){var s=i[o],c=a[o]=new Array(4),u=l(t,e._diag[s][0]);u&&(c[0]=u.r2l(u.range[0]),c[2]=u.r2l(u.range[1]));var h=l(t,e._diag[s][1]);h&&(c[1]=h.r2l(h.range[0]),c[3]=h.r2l(h.range[1]))}r.selectBatch?r.matrix.update({ranges:a},{ranges:a}):r.matrix.update({ranges:a})}function f(t){var e=t._fullLayout,r=e._glcanvas.data()[0].regl,i=e._splomGrid;i||(i=e._splomGrid=n(r)),i.update(function(t){var e,r=t._fullLayout,n=r._size,i=[0,0,r.width,r.height],a={};function o(t,e,r,n,o,s){var l=e[t+"color"],c=e[t+"width"],u=String(l+c);u in a?a[u].data.push(NaN,NaN,r,n,o,s):a[u]={data:[r,n,o,s],join:"rect",thickness:c,color:l,viewport:i,range:i,overlay:!1}}for(e in r._splomSubplots){var s,l,u=r._plots[e],h=u.xaxis,f=u.yaxis,p=h._vals,d=f._vals,g=n.b+f.domain[0]*n.h,v=-f._m,m=-v*f.r2l(f.range[0],f.calendar);if(h.showgrid)for(e=0;e<p.length;e++)s=h._offset+h.l2p(p[e].x),o("grid",h,s,g,s,g+f._length);if(f.showgrid)for(e=0;e<d.length;e++)l=g+m+v*d[e].x,o("grid",f,h._offset,l,h._offset+h._length,l);c(t,h,f)&&(s=h._offset+h.l2p(0),o("zeroline",h,s,g,s,g+f._length)),c(t,f,h)&&(l=g+m+0,o("zeroline",f,h._offset,l,h._offset+h._length,l))}var y=[];for(e in a)y.push(a[e]);return y}(t))}e.exports={name:u,attr:s.attr,attrRegex:s.attrRegex,layoutAttributes:s.layoutAttributes,supplyLayoutDefaults:s.supplyLayoutDefaults,drawFramework:s.drawFramework,plot:function(t){var e=t._fullLayout,r=i.getModule(u),n=o(t.calcdata,r)[0];a(t,["ANGLE_instanced_arrays","OES_element_index_uint"])&&(e._hasOnlyLargeSploms&&f(t),r.plot(t,{},n))},drag:function(t){var e=t.calcdata,r=t._fullLayout;r._hasOnlyLargeSploms&&f(t);for(var n=0;n<e.length;n++){var i=e[n][0].trace,a=r._splomScenes[i.uid];"splom"===i.type&&a&&a.matrix&&h(t,i,a)}},updateGrid:f,clean:function(t,e,r,n){var i,a={};if(n._splomScenes){for(i=0;i<t.length;i++){var o=t[i];"splom"===o.type&&(a[o.uid]=1)}for(i=0;i<r.length;i++){var l=r[i];if(!a[l.uid]){var c=n._splomScenes[l.uid];c&&c.destroy&&c.destroy(),n._splomScenes[l.uid]=null,delete n._splomScenes[l.uid]}}}0===Object.keys(n._splomScenes||{}).length&&delete n._splomScenes,n._splomGrid&&!e._hasOnlyLargeSploms&&n._hasOnlyLargeSploms&&(n._splomGrid.destroy(),n._splomGrid=null,delete n._splomGrid),s.clean(t,e,r,n)},updateFx:function(t){s.updateFx(t);var e=t._fullLayout,r=e.dragmode;if("zoom"===r||"pan"===r)for(var n=t.calcdata,i=0;i<n.length;i++){var a=n[i][0].trace;if("splom"===a.type){var o=e._splomScenes[a.uid];null===o.selectBatch&&o.matrix.update(o.matrixOptions,null)}}},toSVG:s.toSVG}},{"../../lib/prepare_regl":710,"../../plots/cartesian":756,"../../plots/cartesian/axes":745,"../../plots/cartesian/axis_ids":748,"../../plots/get_data":781,"../../registry":826,"regl-line2d":480}],1128:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/array_container_defaults"),a=t("./attributes"),o=t("../scatter/subtypes"),s=t("../scatter/marker_defaults"),l=t("../parcoords/merge_length"),c=/-open/;function u(t,e){function r(r,i){return n.coerce(t,e,a.dimensions,r,i)}r("label");var i=r("values");i&&i.length?r("visible"):e.visible=!1,r("axis.type"),r("axis.matches")}e.exports=function(t,e,r,h){function f(r,i){return n.coerce(t,e,a,r,i)}var p=i(t,e,{name:"dimensions",handleItemDefaults:u}),d=f("diagonal.visible"),g=f("showupperhalf"),v=f("showlowerhalf");if(l(e,p,"values")&&(d||g||v)){f("text"),f("hovertext"),f("hovertemplate"),s(t,e,r,h,f);var m=c.test(e.marker.symbol),y=o.isBubble(e);f("marker.line.width",m||y?1:0),function(t,e,r,n){var i,a,o=e.dimensions,s=o.length,l=e.showupperhalf,c=e.showlowerhalf,u=e.diagonal.visible,h=new Array(s),f=new Array(s);for(i=0;i<s;i++){var p=i?i+1:"";h[i]="x"+p,f[i]="y"+p}var d=n("xaxes",h),g=n("yaxes",f),v=e._diag=new Array(s);e._xaxes={},e._yaxes={};var m=[],y=[];function x(t,n,i,a){if(t){var o=t.charAt(0),s=r._splomAxes[o];if(e["_"+o+"axes"][t]=1,a.push(t),!(t in s)){var l=s[t]={};i&&(l.label=i.label||"",i.visible&&i.axis&&(i.axis.type&&(l.type=i.axis.type),i.axis.matches&&(l.matches=n)))}}}var b=!u&&!c,_=!u&&!l;for(i=0;i<s;i++){var w=o[i],k=0===i,A=i===s-1,M=k&&b||A&&_?void 0:d[i],T=k&&_||A&&b?void 0:g[i];x(M,T,w,m),x(T,M,w,y),v[i]=[M,T]}for(i=0;i<m.length;i++)for(a=0;a<y.length;a++){var S=m[i]+y[a];i>a&&l?r._splomSubplots[S]=1:i<a&&c?r._splomSubplots[S]=1:i!==a||!u&&c&&l||(r._splomSubplots[S]=1)}(!c||!u&&l&&c)&&(r._splomGridDflt.xside="bottom",r._splomGridDflt.yside="left")}(0,e,h,f),n.coerceSelectionMarkerOpacity(e,f)}else e.visible=!1}},{"../../lib":697,"../../plots/array_container_defaults":741,"../parcoords/merge_length":1020,"../scatter/marker_defaults":1067,"../scatter/subtypes":1072,"./attributes":1126}],1129:[function(t,e,r){"use strict";var n=t("regl-splom"),i=t("array-range"),a=t("../../registry"),o=t("../../components/grid"),s=t("../../lib"),l=t("../../plots/cartesian/axis_ids"),c=t("../scatter/subtypes"),u=t("../scatter/calc").calcMarkerSize,h=t("../scatter/calc").calcAxisExpansion,f=t("../scatter/colorscale_calc"),p=t("../scattergl/convert").markerSelection,d=t("../scattergl/convert").markerStyle,g=t("../scattergl").calcHover,v=t("../../constants/numerical").BADNUM,m=t("../scattergl/constants").TOO_MANY_POINTS;function y(t,e){var r,i,a,o,c,u=t._fullLayout,h=u._size,f=e.trace,p=e.t,d=u._splomScenes[f.uid],g=d.matrixOptions,v=g.cdata,m=u._glcanvas.data()[0].regl,y=u.dragmode;if(0!==v.length){g.lower=f.showupperhalf,g.upper=f.showlowerhalf,g.diagonal=f.diagonal.visible;var x=f._visibleDims,b=v.length,_=d.viewOpts={};for(_.ranges=new Array(b),_.domains=new Array(b),c=0;c<x.length;c++){a=x[c];var w=_.ranges[c]=new Array(4),k=_.domains[c]=new Array(4);(r=l.getFromId(t,f._diag[a][0]))&&(w[0]=r._rl[0],w[2]=r._rl[1],k[0]=r.domain[0],k[2]=r.domain[1]),(i=l.getFromId(t,f._diag[a][1]))&&(w[1]=i._rl[0],w[3]=i._rl[1],k[1]=i.domain[0],k[3]=i.domain[1])}_.viewport=[h.l,h.b,h.w+h.l,h.h+h.b],!0===d.matrix&&(d.matrix=n(m));var A=u.clickmode.indexOf("select")>-1,M="lasso"===y||"select"===y||!!f.selectedpoints||A;if(d.selectBatch=null,d.unselectBatch=null,M){var T=f._length;if(d.selectBatch||(d.selectBatch=[],d.unselectBatch=[]),f.selectedpoints){d.selectBatch=f.selectedpoints;var S=f.selectedpoints,E={};for(a=0;a<S.length;a++)E[S[a]]=!0;var C=[];for(a=0;a<T;a++)E[a]||C.push(a);d.unselectBatch=C}var L=p.xpx=new Array(b),z=p.ypx=new Array(b);for(c=0;c<x.length;c++){if(a=x[c],r=l.getFromId(t,f._diag[a][0]))for(L[c]=new Array(T),o=0;o<T;o++)L[c][o]=r.c2p(v[c][o]);if(i=l.getFromId(t,f._diag[a][1]))for(z[c]=new Array(T),o=0;o<T;o++)z[c][o]=i.c2p(v[c][o])}d.selectBatch?(d.matrix.update(g,g),d.matrix.update(d.unselectedOptions,d.selectedOptions),d.matrix.update(_,_)):d.matrix.update(_,null)}else{var O=s.extendFlat({},g,_);d.matrix.update(O,null),p.xpx=p.ypx=null}}}function x(t,e){for(var r=e._id,n={x:0,y:1}[r.charAt(0)],i=t._visibleDims,a=0;a<i.length;a++){var o=i[a];if(t._diag[o][n]===r)return a}return!1}e.exports={moduleType:"trace",name:"splom",basePlotModule:t("./base_plot"),categories:["gl","regl","cartesian","symbols","showLegend","scatter-like"],attributes:t("./attributes"),supplyDefaults:t("./defaults"),colorbar:t("../scatter/marker_colorbar"),calc:function(t,e){var r,n,i,a,o,c,g=e.dimensions,y=e._length,x={},b=x.cdata=[],_=x.data=[],w=e._visibleDims=[];function k(t,r){for(var n=t.makeCalcdata({v:r.values,vcalendar:e.calendar},"v"),i=0;i<n.length;i++)n[i]=n[i]===v?NaN:n[i];b.push(n),_.push("log"===t.type?s.simpleMap(n,t.c2l):n)}for(r=0;r<g.length;r++)if((i=g[r]).visible){if(a=l.getFromId(t,e._diag[r][0]),o=l.getFromId(t,e._diag[r][1]),a&&o&&a.type!==o.type){s.log("Skipping splom dimension "+r+" with conflicting axis types");continue}a?(k(a,i),o&&"category"===o.type&&(o._categories=a._categories.slice())):k(o,i),w.push(r)}for(f(t,e),s.extendFlat(x,d(e)),c=b.length*y>m?2*(x.sizeAvg||Math.max(x.size,3)):u(e,y),n=0;n<w.length;n++)i=g[r=w[n]],a=l.getFromId(t,e._diag[r][0])||{},o=l.getFromId(t,e._diag[r][1])||{},h(t,e,a,o,b[n],b[n],c);var A=function(t,e){var r=t._fullLayout,n=e.uid,i=r._splomScenes;i||(i=r._splomScenes={});var a={dirty:!0},o=i[e.uid];return o||((o=i[n]=s.extendFlat({},a,{selectBatch:null,unselectBatch:null,matrix:!1,select:null})).draw=function(){o.matrix&&o.matrix.draw&&(o.selectBatch?o.matrix.draw(o.unselectBatch,o.selectBatch):o.matrix.draw()),o.dirty=!1},o.destroy=function(){o.matrix&&o.matrix.destroy&&o.matrix.destroy(),o.matrixOptions=null,o.selectBatch=null,o.unselectBatch=null,o=null}),o.dirty||s.extendFlat(o,a),o}(t,e);return A.matrix||(A.matrix=!0),A.matrixOptions=x,A.selectedOptions=p(e,e.selected),A.unselectedOptions=p(e,e.unselected),[{x:!1,y:!1,t:{},trace:e}]},plot:function(t,e,r){if(r.length)for(var n=0;n<r.length;n++)y(t,r[n][0])},hoverPoints:function(t,e,r){var n=t.cd[0].trace,i=t.scene.matrixOptions.cdata,a=t.xa,o=t.ya,s=a.c2p(e),l=o.c2p(r),c=t.distance,u=x(n,a),h=x(n,o);if(!1===u||!1===h)return[t];for(var f,p,d=i[u],v=i[h],m=c,y=0;y<d.length;y++){var b=d[y],_=v[y],w=a.c2p(b)-s,k=o.c2p(_)-l,A=Math.sqrt(w*w+k*k);A<m&&(m=p=A,f=y)}return t.index=f,t.distance=m,t.dxy=p,void 0===f?[t]:(g(t,d,v,n),[t])},selectPoints:function(t,e){var r,n=t.cd,a=n[0].trace,o=n[0].t,s=t.scene,l=s.matrixOptions.cdata,u=t.xaxis,h=t.yaxis,f=[];if(!s)return f;var p=!c.hasMarkers(a)&&!c.hasText(a);if(!0!==a.visible||p)return f;var d=x(a,u),g=x(a,h);if(!1===d||!1===g)return f;var v=o.xpx[d],m=o.ypx[g],y=l[d],b=l[g],_=null,w=null;if(!1===e||e.degenerate)w=i(o.count);else for(_=[],w=[],r=0;r<y.length;r++)e.contains([v[r],m[r]],null,r,t)?(_.push(r),f.push({pointNumber:r,x:y[r],y:b[r]})):w.push(r);if(s.selectBatch||(s.selectBatch=[],s.unselectBatch=[]),!s.selectBatch){for(r=0;r<s.count;r++)s.selectBatch=[],s.unselectBatch=[];s.matrix.update(s.unselectedOptions,s.selectedOptions)}return s.selectBatch=_,s.unselectBatch=w,f},editStyle:function(t,e){var r=e.trace,n=t._fullLayout._splomScenes[r.uid];if(n){f(t,r),s.extendFlat(n.matrixOptions,d(r));var i=s.extendFlat({},n.matrixOptions,n.viewOpts);n.matrix.update(i,null)}},meta:{}},a.register(o)},{"../../components/grid":617,"../../constants/numerical":674,"../../lib":697,"../../plots/cartesian/axis_ids":748,"../../registry":826,"../scatter/calc":1049,"../scatter/colorscale_calc":1051,"../scatter/marker_colorbar":1066,"../scatter/subtypes":1072,"../scattergl":1101,"../scattergl/constants":1098,"../scattergl/convert":1099,"./attributes":1126,"./base_plot":1127,"./defaults":1128,"array-range":55,"regl-splom":482}],1130:[function(t,e,r){"use strict";var n=t("../../components/colorscale/attributes"),i=t("../../components/colorbar/attributes"),a=t("../../components/fx/hovertemplate_attributes"),o=t("../mesh3d/attributes"),s=t("../../plots/attributes"),l=t("../../lib/extend").extendFlat,c={x:{valType:"data_array",editType:"calc+clearAxisTypes"},y:{valType:"data_array",editType:"calc+clearAxisTypes"},z:{valType:"data_array",editType:"calc+clearAxisTypes"},u:{valType:"data_array",editType:"calc"},v:{valType:"data_array",editType:"calc"},w:{valType:"data_array",editType:"calc"},starts:{x:{valType:"data_array",editType:"calc"},y:{valType:"data_array",editType:"calc"},z:{valType:"data_array",editType:"calc"},editType:"calc"},maxdisplayed:{valType:"integer",min:0,dflt:1e3,editType:"calc"},sizeref:{valType:"number",editType:"calc",min:0,dflt:1},text:{valType:"string",dflt:"",editType:"calc"},hovertext:{valType:"string",dflt:"",editType:"calc"},hovertemplate:a({editType:"calc"},{keys:["tubex","tubey","tubez","tubeu","tubev","tubew","norm","divergence"]})};l(c,n("",{colorAttr:"u/v/w norm",showScaleDflt:!0,editTypeOverride:"calc"}),{colorbar:i});["opacity","lightposition","lighting"].forEach(function(t){c[t]=o[t]}),c.hoverinfo=l({},s.hoverinfo,{editType:"calc",flags:["x","y","z","u","v","w","norm","divergence","text","name"],dflt:"x+y+z+norm+text+name"}),c.transforms=void 0,e.exports=c},{"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plots/attributes":742,"../mesh3d/attributes":991}],1131:[function(t,e,r){"use strict";var n=t("../../components/colorscale/calc");e.exports=function(t,e){var r,i,a,o,s=e.u,l=e.v,c=e.w,u=e.x,h=e.y,f=e.z,p=Math.min(u.length,h.length,f.length,s.length,l.length,c.length),d=0;e.starts&&(i=e.starts.x||[],a=e.starts.y||[],o=e.starts.z||[],d=Math.min(i.length,a.length,o.length));var g=0,v=1/0;for(r=0;r<p;r++){var m=s[r],y=l[r],x=c[r],b=Math.sqrt(m*m+y*y+x*x);g=Math.max(g,b),v=Math.min(v,b)}n(t,e,{vals:[v,g],containerStr:"",cLetter:"c"});var _=-1/0,w=1/0,k=-1/0,A=1/0,M=-1/0,T=1/0;for(r=0;r<p;r++){var S=u[r];_=Math.max(_,S),w=Math.min(w,S);var E=h[r];k=Math.max(k,E),A=Math.min(A,E);var C=f[r];M=Math.max(M,C),T=Math.min(T,C)}for(r=0;r<d;r++){var L=i[r];_=Math.max(_,L),w=Math.min(w,L);var z=a[r];k=Math.max(k,z),A=Math.min(A,z);var O=o[r];M=Math.max(M,O),T=Math.min(T,O)}e._len=p,e._slen=d,e._normMax=g,e._xbnds=[w,_],e._ybnds=[A,k],e._zbnds=[T,M]}},{"../../components/colorscale/calc":582}],1132:[function(t,e,r){"use strict";var n=t("gl-streamtube3d"),i=n.createTubeMesh,a=t("../../lib"),o=t("../../lib/gl_format_color").parseColorScale,s=t("../../plots/gl3d/zip3"),l={xaxis:0,yaxis:1,zaxis:2};function c(t,e){this.scene=t,this.uid=e,this.mesh=null,this.data=null}var u=c.prototype;function h(t){return a.distinctVals(t).vals}function f(t){var e=t.length;return e>2?t.slice(1,e-1):2===e?[(t[0]+t[1])/2]:t}function p(t){var e=t.length;return 1===e?[.5,.5]:[t[1]-t[0],t[e-1]-t[e-2]]}function d(t,e){var r=t.fullSceneLayout,i=t.dataScale,c=e._len,u={};function d(t,e){var n=r[e],o=i[l[e]];return a.simpleMap(t,function(t){return n.d2l(t)*o})}u.vectors=s(d(e.u,"xaxis"),d(e.v,"yaxis"),d(e.w,"zaxis"),c);var g=h(e.x.slice(0,c)),v=h(e.y.slice(0,c)),m=h(e.z.slice(0,c));if(g.length*v.length*m.length>c)return{positions:[],cells:[]};var y=d(g,"xaxis"),x=d(v,"yaxis"),b=d(m,"zaxis");if(u.meshgrid=[y,x,b],e.starts){var _=e._slen;u.startingPositions=s(d(e.starts.x.slice(0,_),"xaxis"),d(e.starts.y.slice(0,_),"yaxis"),d(e.starts.z.slice(0,_),"zaxis"))}else{for(var w=x[0],k=f(y),A=f(b),M=new Array(k.length*A.length),T=0,S=0;S<k.length;S++)for(var E=0;E<A.length;E++)M[T++]=[k[S],w,A[E]];u.startingPositions=M}u.colormap=o(e),u.tubeSize=e.sizeref,u.maxLength=e.maxdisplayed;var C=d(e._xbnds,"xaxis"),L=d(e._ybnds,"yaxis"),z=d(e._zbnds,"zaxis"),O=p(y),I=p(x),D=p(b),P=[[C[0]-O[0],L[0]-I[0],z[0]-D[0]],[C[1]+O[1],L[1]+I[1],z[1]+D[1]]],R=n(u,P);R.vertexIntensityBounds=[e.cmin/e._normMax,e.cmax/e._normMax];var F=e.lightposition;return R.lightPosition=[F.x,F.y,F.z],R.ambient=e.lighting.ambient,R.diffuse=e.lighting.diffuse,R.specular=e.lighting.specular,R.roughness=e.lighting.roughness,R.fresnel=e.lighting.fresnel,R.opacity=e.opacity,e._pad=R.tubeScale*e.sizeref*2,R}u.handlePick=function(t){var e=this.scene.fullSceneLayout,r=this.scene.dataScale;function n(t,n){var i=e[n],a=r[l[n]];return i.l2c(t)/a}if(t.object===this.mesh){var i=t.data.position,a=t.data.velocity;return t.traceCoordinate=[n(i[0],"xaxis"),n(i[1],"yaxis"),n(i[2],"zaxis"),n(a[0],"xaxis"),n(a[1],"yaxis"),n(a[2],"zaxis"),t.data.intensity*this.data._normMax,t.data.divergence],t.textLabel=this.data.hovertext||this.data.text,!0}},u.update=function(t){this.data=t;var e=d(this.scene,t);this.mesh.update(e)},u.dispose=function(){this.scene.glplot.remove(this.mesh),this.mesh.dispose()},e.exports=function(t,e){var r=t.glplot.gl,n=d(t,e),a=i(r,n),o=new c(t,e.uid);return o.mesh=a,o.data=e,a._trace=o,t.glplot.add(a),o}},{"../../lib":697,"../../lib/gl_format_color":694,"../../plots/gl3d/zip3":797,"gl-streamtube3d":306}],1133:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/colorscale/defaults"),a=t("./attributes");e.exports=function(t,e,r,o){function s(r,i){return n.coerce(t,e,a,r,i)}var l=s("u"),c=s("v"),u=s("w"),h=s("x"),f=s("y"),p=s("z");l&&l.length&&c&&c.length&&u&&u.length&&h&&h.length&&f&&f.length&&p&&p.length?(s("starts.x"),s("starts.y"),s("starts.z"),s("maxdisplayed"),s("sizeref"),s("lighting.ambient"),s("lighting.diffuse"),s("lighting.specular"),s("lighting.roughness"),s("lighting.fresnel"),s("lightposition.x"),s("lightposition.y"),s("lightposition.z"),i(t,e,o,s,{prefix:"",cLetter:"c"}),s("text"),s("hovertext"),s("hovertemplate"),e._length=null):e.visible=!1}},{"../../components/colorscale/defaults":584,"../../lib":697,"./attributes":1130}],1134:[function(t,e,r){"use strict";e.exports={moduleType:"trace",name:"streamtube",basePlotModule:t("../../plots/gl3d"),categories:["gl3d"],attributes:t("./attributes"),supplyDefaults:t("./defaults"),colorbar:{min:"cmin",max:"cmax"},calc:t("./calc"),plot:t("./convert"),eventData:function(t,e){return t.tubex=t.x,t.tubey=t.y,t.tubez=t.z,t.tubeu=e.traceCoordinate[3],t.tubev=e.traceCoordinate[4],t.tubew=e.traceCoordinate[5],t.norm=e.traceCoordinate[6],t.divergence=e.traceCoordinate[7],delete t.x,delete t.y,delete t.z,t},meta:{}}},{"../../plots/gl3d":786,"./attributes":1130,"./calc":1131,"./convert":1132,"./defaults":1133}],1135:[function(t,e,r){"use strict";var n=t("../../components/color"),i=t("../../components/colorscale/attributes"),a=t("../../components/colorbar/attributes"),o=t("../../components/fx/hovertemplate_attributes"),s=t("../../plots/attributes"),l=t("../../lib/extend").extendFlat,c=t("../../plot_api/edit_types").overrideAll;function u(t){return{show:{valType:"boolean",dflt:!1},project:{x:{valType:"boolean",dflt:!1},y:{valType:"boolean",dflt:!1},z:{valType:"boolean",dflt:!1}},color:{valType:"color",dflt:n.defaultLine},usecolormap:{valType:"boolean",dflt:!1},width:{valType:"number",min:1,max:16,dflt:2},highlight:{valType:"boolean",dflt:!0},highlightcolor:{valType:"color",dflt:n.defaultLine},highlightwidth:{valType:"number",min:1,max:16,dflt:2}}}var h=e.exports=c(l({z:{valType:"data_array"},x:{valType:"data_array"},y:{valType:"data_array"},text:{valType:"string",dflt:"",arrayOk:!0},hovertext:{valType:"string",dflt:"",arrayOk:!0},hovertemplate:o(),surfacecolor:{valType:"data_array"}},i("",{colorAttr:"z or surfacecolor",showScaleDflt:!0,autoColorDflt:!1,editTypeOverride:"calc"}),{colorbar:a,contours:{x:u(),y:u(),z:u()},hidesurface:{valType:"boolean",dflt:!1},lightposition:{x:{valType:"number",min:-1e5,max:1e5,dflt:10},y:{valType:"number",min:-1e5,max:1e5,dflt:1e4},z:{valType:"number",min:-1e5,max:1e5,dflt:0}},lighting:{ambient:{valType:"number",min:0,max:1,dflt:.8},diffuse:{valType:"number",min:0,max:1,dflt:.8},specular:{valType:"number",min:0,max:2,dflt:.05},roughness:{valType:"number",min:0,max:1,dflt:.5},fresnel:{valType:"number",min:0,max:5,dflt:.2}},opacity:{valType:"number",min:0,max:1,dflt:1},_deprecated:{zauto:l({},i.zauto,{}),zmin:l({},i.zmin,{}),zmax:l({},i.zmax,{})},hoverinfo:l({},s.hoverinfo)}),"calc","nested");h.x.editType=h.y.editType=h.z.editType="calc+clearAxisTypes",h.transforms=void 0},{"../../components/color":574,"../../components/colorbar/attributes":575,"../../components/colorscale/attributes":581,"../../components/fx/hovertemplate_attributes":612,"../../lib/extend":687,"../../plot_api/edit_types":728,"../../plots/attributes":742}],1136:[function(t,e,r){"use strict";var n=t("../../components/colorscale/calc");e.exports=function(t,e){e.surfacecolor?n(t,e,{vals:e.surfacecolor,containerStr:"",cLetter:"c"}):n(t,e,{vals:e.z,containerStr:"",cLetter:"c"})}},{"../../components/colorscale/calc":582}],1137:[function(t,e,r){"use strict";var n=t("gl-surface3d"),i=t("ndarray"),a=t("ndarray-homography"),o=t("ndarray-fill"),s=t("../../lib").isArrayOrTypedArray,l=t("../../lib/gl_format_color").parseColorScale,c=t("../../lib/str2rgbarray");function u(t,e,r){this.scene=t,this.uid=r,this.surface=e,this.data=null,this.showContour=[!1,!1,!1],this.minValues=[1/0,1/0,1/0],this.maxValues=[-1/0,-1/0,-1/0],this.dataScaleX=1,this.dataScaleY=1,this.refineData=!0}var h=u.prototype;h.getXat=function(t,e,r,n){var i=s(this.data.x)?s(this.data.x[0])?this.data.x[e][t]:this.data.x[t]:t;return void 0===r?i:n.d2l(i,0,r)},h.getYat=function(t,e,r,n){var i=s(this.data.y)?s(this.data.y[0])?this.data.y[e][t]:this.data.y[e]:e;return void 0===r?i:n.d2l(i,0,r)},h.getZat=function(t,e,r,n){var i=this.data.z[e][t];return void 0===r?i:n.d2l(i,0,r)},h.handlePick=function(t){if(t.object===this.surface){var e=(t.data.index[0]-1)/this.dataScaleX-1,r=(t.data.index[1]-1)/this.dataScaleY-1,n=Math.max(Math.min(Math.round(e),this.data.z[0].length-1),0),i=Math.max(Math.min(Math.round(r),this.data._ylength-1),0);t.index=[n,i],t.traceCoordinate=[this.getXat(n,i),this.getYat(n,i),this.getZat(n,i)],t.dataCoordinate=[this.getXat(n,i,this.data.xcalendar,this.scene.fullSceneLayout.xaxis),this.getYat(n,i,this.data.ycalendar,this.scene.fullSceneLayout.yaxis),this.getZat(n,i,this.data.zcalendar,this.scene.fullSceneLayout.zaxis)];for(var a=0;a<3;a++){var o=t.dataCoordinate[a];null!=o&&(t.dataCoordinate[a]*=this.scene.dataScale[a])}var s=this.data.hovertext||this.data.text;return Array.isArray(s)&&s[i]&&void 0!==s[i][n]?t.textLabel=s[i][n]:t.textLabel=s||"",t.data.dataCoordinate=t.dataCoordinate.slice(),this.surface.highlight(t.data),this.scene.glplot.spikes.position=t.dataCoordinate,!0}};var f=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997,1009,1013,1019,1021,1031,1033,1039,1049,1051,1061,1063,1069,1087,1091,1093,1097,1103,1109,1117,1123,1129,1151,1153,1163,1171,1181,1187,1193,1201,1213,1217,1223,1229,1231,1237,1249,1259,1277,1279,1283,1289,1291,1297,1301,1303,1307,1319,1321,1327,1361,1367,1373,1381,1399,1409,1423,1427,1429,1433,1439,1447,1451,1453,1459,1471,1481,1483,1487,1489,1493,1499,1511,1523,1531,1543,1549,1553,1559,1567,1571,1579,1583,1597,1601,1607,1609,1613,1619,1621,1627,1637,1657,1663,1667,1669,1693,1697,1699,1709,1721,1723,1733,1741,1747,1753,1759,1777,1783,1787,1789,1801,1811,1823,1831,1847,1861,1867,1871,1873,1877,1879,1889,1901,1907,1913,1931,1933,1949,1951,1973,1979,1987,1993,1997,1999,2003,2011,2017,2027,2029,2039,2053,2063,2069,2081,2083,2087,2089,2099,2111,2113,2129,2131,2137,2141,2143,2153,2161,2179,2203,2207,2213,2221,2237,2239,2243,2251,2267,2269,2273,2281,2287,2293,2297,2309,2311,2333,2339,2341,2347,2351,2357,2371,2377,2381,2383,2389,2393,2399,2411,2417,2423,2437,2441,2447,2459,2467,2473,2477,2503,2521,2531,2539,2543,2549,2551,2557,2579,2591,2593,2609,2617,2621,2633,2647,2657,2659,2663,2671,2677,2683,2687,2689,2693,2699,2707,2711,2713,2719,2729,2731,2741,2749,2753,2767,2777,2789,2791,2797,2801,2803,2819,2833,2837,2843,2851,2857,2861,2879,2887,2897,2903,2909,2917,2927,2939,2953,2957,2963,2969,2971,2999];function p(t,e){if(t<e)return 0;for(var r=0;0===Math.floor(t%e);)t/=e,r++;return r}function d(t){for(var e=[],r=0;r<f.length;r++){var n=f[r];e.push(p(t,n))}return e}function g(t){for(var e=d(t),r=t,n=0;n<f.length;n++)if(e[n]>0){r=f[n];break}return r}function v(t,e){if(!(t<1||e<1)){for(var r=d(t),n=d(e),i=1,a=0;a<f.length;a++)i*=Math.pow(f[a],Math.max(r[a],n[a]));return i}}h.calcXnums=function(t){var e,r=[];for(e=1;e<t;e++){var n=this.getXat(e-1,0),i=this.getXat(e,0);r[e-1]=i!==n&&null!=n&&null!=i?Math.abs(i-n):0}var a=0;for(e=1;e<t;e++)a+=r[e-1];for(e=1;e<t;e++)0===r[e-1]?r[e-1]=1:r[e-1]=Math.round(a/r[e-1]);return r},h.calcYnums=function(t){var e,r=[];for(e=1;e<t;e++){var n=this.getYat(0,e-1),i=this.getYat(0,e);r[e-1]=i!==n&&null!=n&&null!=i?Math.abs(i-n):0}var a=0;for(e=1;e<t;e++)a+=r[e-1];for(e=1;e<t;e++)0===r[e-1]?r[e-1]=1:r[e-1]=Math.round(a/r[e-1]);return r};var m=[1,2,4,6,12,24,36,48,60,120,180,240,360,720,840,1260],y=m[9],x=m[13];h.estimateScale=function(t,e){for(var r=1+function(t){if(0!==t.length){for(var e=1,r=0;r<t.length;r++)e=v(e,t[r]);return e}}(0===e?this.calcXnums(t):this.calcYnums(t));r<y;)r*=2;for(;r>x;)r--,r/=g(r),++r<y&&(r=x);var n=Math.round(r/t);return n>1?n:1},h.refineCoords=function(t){for(var e=this.dataScaleX,r=this.dataScaleY,n=t[0].shape[0],o=t[0].shape[1],s=0|Math.floor(t[0].shape[0]*e+1),l=0|Math.floor(t[0].shape[1]*r+1),c=1+n+1,u=1+o+1,h=i(new Float32Array(c*u),[c,u]),f=0;f<t.length;++f){this.surface.padField(h,t[f]);var p=i(new Float32Array(s*l),[s,l]);a(p,h,[e,0,0,0,r,0,0,0,1]),t[f]=p}},h.setContourLevels=function(){for(var t=[[],[],[]],e=!1,r=0;r<3;++r)this.showContour[r]&&(e=!0,t[r]=this.scene.contourLevels[r]);e&&this.surface.update({levels:t})},h.update=function(t){var e,r,n,a,s=this.scene,u=s.fullSceneLayout,h=this.surface,f=t.opacity,p=l(t,f),d=s.dataScale,g=t.z[0].length,v=t._ylength,m=s.contourLevels;this.data=t;var y=[];for(e=0;e<3;e++)for(y[e]=[],r=0;r<g;r++)y[e][r]=[];for(r=0;r<g;r++)for(n=0;n<v;n++)y[0][r][n]=this.getXat(r,n,t.xcalendar,u.xaxis),y[1][r][n]=this.getYat(r,n,t.ycalendar,u.yaxis),y[2][r][n]=this.getZat(r,n,t.zcalendar,u.zaxis);for(e=0;e<3;e++)for(r=0;r<g;r++)for(n=0;n<v;n++)null==(a=y[e][r][n])?y[e][r][n]=NaN:a=y[e][r][n]*=d[e];for(e=0;e<3;e++)for(r=0;r<g;r++)for(n=0;n<v;n++)null!=(a=y[e][r][n])&&(this.minValues[e]>a&&(this.minValues[e]=a),this.maxValues[e]<a&&(this.maxValues[e]=a));for(e=0;e<3;e++)t._objectOffset[e]=.5*(this.minValues[e]+this.maxValues[e]);for(e=0;e<3;e++)for(r=0;r<g;r++)for(n=0;n<v;n++)null!=(a=y[e][r][n])&&(y[e][r][n]-=t._objectOffset[e]);var b=[i(new Float32Array(g*v),[g,v]),i(new Float32Array(g*v),[g,v]),i(new Float32Array(g*v),[g,v])];o(b[0],function(t,e){return y[0][t][e]}),o(b[1],function(t,e){return y[1][t][e]}),o(b[2],function(t,e){return y[2][t][e]}),y=[];var _={colormap:p,levels:[[],[],[]],showContour:[!0,!0,!0],showSurface:!t.hidesurface,contourProject:[[!1,!1,!1],[!1,!1,!1],[!1,!1,!1]],contourWidth:[1,1,1],contourColor:[[1,1,1,1],[1,1,1,1],[1,1,1,1]],contourTint:[1,1,1],dynamicColor:[[1,1,1,1],[1,1,1,1],[1,1,1,1]],dynamicWidth:[1,1,1],dynamicTint:[1,1,1],opacity:t.opacity};if(_.intensityBounds=[t.cmin,t.cmax],t.surfacecolor){var w=i(new Float32Array(g*v),[g,v]);o(w,function(e,r){return t.surfacecolor[r][e]}),b.push(w)}else _.intensityBounds[0]*=d[2],_.intensityBounds[1]*=d[2];(x<b[0].shape[0]||x<b[0].shape[1])&&(this.refineData=!1),!0===this.refineData&&(this.dataScaleX=this.estimateScale(b[0].shape[0],0),this.dataScaleY=this.estimateScale(b[0].shape[1],1),1===this.dataScaleX&&1===this.dataScaleY||this.refineCoords(b)),t.surfacecolor&&(_.intensity=b.pop());var k=[!0,!0,!0],A=["x","y","z"];for(e=0;e<3;++e){var M=t.contours[A[e]];k[e]=M.highlight,_.showContour[e]=M.show||M.highlight,_.showContour[e]&&(_.contourProject[e]=[M.project.x,M.project.y,M.project.z],M.show?(this.showContour[e]=!0,_.levels[e]=m[e],h.highlightColor[e]=_.contourColor[e]=c(M.color),M.usecolormap?h.highlightTint[e]=_.contourTint[e]=0:h.highlightTint[e]=_.contourTint[e]=1,_.contourWidth[e]=M.width):this.showContour[e]=!1,M.highlight&&(_.dynamicColor[e]=c(M.highlightcolor),_.dynamicWidth[e]=M.highlightwidth))}(function(t){var e=t[0].rgb,r=t[t.length-1].rgb;return e[0]===r[0]&&e[1]===r[1]&&e[2]===r[2]&&e[3]===r[3]})(p)&&(_.vertexColor=!0),_.objectOffset=[t._objectOffset[0],t._objectOffset[1],t._objectOffset[2]],_.coords=b,h.update(_),h.visible=t.visible,h.enableDynamic=k,h.enableHighlight=k,h.snapToData=!0,"lighting"in t&&(h.ambientLight=t.lighting.ambient,h.diffuseLight=t.lighting.diffuse,h.specularLight=t.lighting.specular,h.roughness=t.lighting.roughness,h.fresnel=t.lighting.fresnel),"lightposition"in t&&(h.lightPosition=[t.lightposition.x,t.lightposition.y,t.lightposition.z]),f&&f<1&&(h.supportsTransparency=!0)},h.dispose=function(){this.scene.glplot.remove(this.surface),this.surface.dispose()},e.exports=function(t,e){var r=t.glplot.gl,i=n({gl:r}),a=new u(t,i,e.uid);return i._trace=a,a.update(e),t.glplot.add(i),a}},{"../../lib":697,"../../lib/gl_format_color":694,"../../lib/str2rgbarray":720,"gl-surface3d":309,ndarray:439,"ndarray-fill":429,"ndarray-homography":431}],1138:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("../../lib"),a=t("../../components/colorscale/defaults"),o=t("./attributes");function s(t,e,r){e in t&&!(r in t)&&(t[r]=t[e])}e.exports=function(t,e,r,l){var c,u;function h(r,n){return i.coerce(t,e,o,r,n)}var f=h("x"),p=h("y"),d=h("z");if(!d||!d.length||f&&f.length<1||p&&p.length<1)e.visible=!1;else{e._xlength=Array.isArray(f)&&i.isArrayOrTypedArray(f[0])?d.length:d[0].length,e._ylength=d.length,e._objectOffset=[0,0,0],n.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y","z"],l),h("text"),h("hovertext"),h("hovertemplate"),["lighting.ambient","lighting.diffuse","lighting.specular","lighting.roughness","lighting.fresnel","lightposition.x","lightposition.y","lightposition.z","hidesurface","opacity"].forEach(function(t){h(t)});var g=h("surfacecolor"),v=["x","y","z"];for(c=0;c<3;++c){var m="contours."+v[c],y=h(m+".show"),x=h(m+".highlight");if(y||x)for(u=0;u<3;++u)h(m+".project."+v[u]);y&&(h(m+".color"),h(m+".width"),h(m+".usecolormap")),x&&(h(m+".highlightcolor"),h(m+".highlightwidth"))}g||(s(t,"zmin","cmin"),s(t,"zmax","cmax"),s(t,"zauto","cauto")),a(t,e,l,h,{prefix:"",cLetter:"c"}),e._length=null}}},{"../../components/colorscale/defaults":584,"../../lib":697,"../../registry":826,"./attributes":1135}],1139:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar={min:"cmin",max:"cmax"},n.calc=t("./calc"),n.plot=t("./convert"),n.moduleType="trace",n.name="surface",n.basePlotModule=t("../../plots/gl3d"),n.categories=["gl3d","2dMap","noOpacity"],n.meta={},e.exports=n},{"../../plots/gl3d":786,"./attributes":1135,"./calc":1136,"./convert":1137,"./defaults":1138}],1140:[function(t,e,r){"use strict";var n=t("../../components/annotations/attributes"),i=t("../../lib/extend").extendFlat,a=t("../../plot_api/edit_types").overrideAll,o=t("../../plots/font_attributes"),s=t("../../plots/domain").attributes;(e.exports=a({domain:s({name:"table",trace:!0}),columnwidth:{valType:"number",arrayOk:!0,dflt:null},columnorder:{valType:"data_array"},header:{values:{valType:"data_array",dflt:[]},format:{valType:"data_array",dflt:[]},prefix:{valType:"string",arrayOk:!0,dflt:null},suffix:{valType:"string",arrayOk:!0,dflt:null},height:{valType:"number",dflt:28},align:i({},n.align,{arrayOk:!0}),line:{width:{valType:"number",arrayOk:!0,dflt:1},color:{valType:"color",arrayOk:!0,dflt:"grey"}},fill:{color:{valType:"color",arrayOk:!0,dflt:"white"}},font:i({},o({arrayOk:!0}))},cells:{values:{valType:"data_array",dflt:[]},format:{valType:"data_array",dflt:[]},prefix:{valType:"string",arrayOk:!0,dflt:null},suffix:{valType:"string",arrayOk:!0,dflt:null},height:{valType:"number",dflt:20},align:i({},n.align,{arrayOk:!0}),line:{width:{valType:"number",arrayOk:!0,dflt:1},color:{valType:"color",arrayOk:!0,dflt:"grey"}},fill:{color:{valType:"color",arrayOk:!0,dflt:"white"}},font:i({},o({arrayOk:!0}))}},"calc","from-root")).transforms=void 0},{"../../components/annotations/attributes":557,"../../lib/extend":687,"../../plot_api/edit_types":728,"../../plots/domain":770,"../../plots/font_attributes":771}],1141:[function(t,e,r){"use strict";var n=t("../../plots/get_data").getModuleCalcData,i=t("./plot");r.name="table",r.plot=function(t){var e=n(t.calcdata,"table")[0];e.length&&i(t,e)},r.clean=function(t,e,r,n){var i=n._has&&n._has("table"),a=e._has&&e._has("table");i&&!a&&n._paperdiv.selectAll(".table").remove()}},{"../../plots/get_data":781,"./plot":1148}],1142:[function(t,e,r){"use strict";var n=t("../../lib/gup").wrap;e.exports=function(){return n({})}},{"../../lib/gup":695}],1143:[function(t,e,r){"use strict";e.exports={cellPad:8,columnExtentOffset:10,columnTitleOffset:28,emptyHeaderHeight:16,latexCheck:/^\$.*\$$/,goldenRatio:1.618,lineBreaker:"<br>",maxDimensionCount:60,overdrag:45,releaseTransitionDuration:120,releaseTransitionEase:"cubic-out",scrollbarCaptureWidth:18,scrollbarHideDelay:1e3,scrollbarHideDuration:1e3,scrollbarOffset:5,scrollbarWidth:8,transitionDuration:100,transitionEase:"cubic-out",uplift:5,wrapSpacer:" ",wrapSplitCharacter:" ",cn:{table:"table",tableControlView:"table-control-view",scrollBackground:"scroll-background",yColumn:"y-column",columnBlock:"column-block",scrollAreaClip:"scroll-area-clip",scrollAreaClipRect:"scroll-area-clip-rect",columnBoundary:"column-boundary",columnBoundaryClippath:"column-boundary-clippath",columnBoundaryRect:"column-boundary-rect",columnCells:"column-cells",columnCell:"column-cell",cellRect:"cell-rect",cellText:"cell-text",cellTextHolder:"cell-text-holder",scrollbarKit:"scrollbar-kit",scrollbar:"scrollbar",scrollbarSlider:"scrollbar-slider",scrollbarGlyph:"scrollbar-glyph",scrollbarCaptureZone:"scrollbar-capture-zone"}}},{}],1144:[function(t,e,r){"use strict";var n=t("./constants"),i=t("../../lib/extend").extendFlat,a=t("fast-isnumeric");function o(t){if(Array.isArray(t)){for(var e=0,r=0;r<t.length;r++)e=Math.max(e,o(t[r]));return e}return t}function s(t,e){return t+e}function l(t){var e,r=t.slice(),n=1/0,i=0;for(e=0;e<r.length;e++)Array.isArray(r[e])||(r[e]=[r[e]]),n=Math.min(n,r[e].length),i=Math.max(i,r[e].length);if(n!==i)for(e=0;e<r.length;e++){var a=i-r[e].length;a&&(r[e]=r[e].concat(c(a)))}return r}function c(t){for(var e=new Array(t),r=0;r<t;r++)e[r]="";return e}function u(t){return t.calcdata.columns.reduce(function(e,r){return r.xIndex<t.xIndex?e+r.columnWidth:e},0)}function h(t,e){return Object.keys(t).map(function(r){return i({},t[r],{auxiliaryBlocks:e})})}function f(t,e){for(var r,n={},i=0,a=0,o={firstRowIndex:null,lastRowIndex:null,rows:[]},s=0,l=0,c=0;c<t.length;c++)r=t[c],o.rows.push({rowIndex:c,rowHeight:r}),((a+=r)>=e||c===t.length-1)&&(n[i]=o,o.key=l++,o.firstRowIndex=s,o.lastRowIndex=c,o={firstRowIndex:null,lastRowIndex:null,rows:[]},i+=a,s=c+1,a=0);return n}e.exports=function(t,e){var r=l(e.cells.values),p=function(t){return t.slice(e.header.values.length,t.length)},d=l(e.header.values);d.length&&!d[0].length&&(d[0]=[""],d=l(d));var g=d.concat(p(r).map(function(){return c((d[0]||[""]).length)})),v=e.domain,m=Math.floor(t._fullLayout._size.w*(v.x[1]-v.x[0])),y=Math.floor(t._fullLayout._size.h*(v.y[1]-v.y[0])),x=e.header.values.length?g[0].map(function(){return e.header.height}):[n.emptyHeaderHeight],b=r.length?r[0].map(function(){return e.cells.height}):[],_=x.reduce(s,0),w=f(b,y-_+n.uplift),k=h(f(x,_),[]),A=h(w,k),M={},T=e._fullInput.columnorder.concat(p(r.map(function(t,e){return e}))),S=g.map(function(t,r){var n=Array.isArray(e.columnwidth)?e.columnwidth[Math.min(r,e.columnwidth.length-1)]:e.columnwidth;return a(n)?Number(n):1}),E=S.reduce(s,0);S=S.map(function(t){return t/E*m});var C=Math.max(o(e.header.line.width),o(e.cells.line.width)),L={key:e.uid+t._context.staticPlot,translateX:v.x[0]*t._fullLayout._size.w,translateY:t._fullLayout._size.h*(1-v.y[1]),size:t._fullLayout._size,width:m,maxLineWidth:C,height:y,columnOrder:T,groupHeight:y,rowBlocks:A,headerRowBlocks:k,scrollY:0,cells:i({},e.cells,{values:r}),headerCells:i({},e.header,{values:g}),gdColumns:g.map(function(t){return t[0]}),gdColumnsOriginalOrder:g.map(function(t){return t[0]}),prevPages:[0,0],scrollbarState:{scrollbarScrollInProgress:!1},columns:g.map(function(t,e){var r=M[t];return M[t]=(r||0)+1,{key:t+"__"+M[t],label:t,specIndex:e,xIndex:T[e],xScale:u,x:void 0,calcdata:void 0,columnWidth:S[e]}})};return L.columns.forEach(function(t){t.calcdata=L,t.x=u(t)}),L}},{"../../lib/extend":687,"./constants":1143,"fast-isnumeric":218}],1145:[function(t,e,r){"use strict";var n=t("../../lib/extend").extendFlat;r.splitToPanels=function(t){var e=[0,0],r=n({},t,{key:"header",type:"header",page:0,prevPages:e,currentRepaint:[null,null],dragHandle:!0,values:t.calcdata.headerCells.values[t.specIndex],rowBlocks:t.calcdata.headerRowBlocks,calcdata:n({},t.calcdata,{cells:t.calcdata.headerCells})});return[n({},t,{key:"cells1",type:"cells",page:0,prevPages:e,currentRepaint:[null,null],dragHandle:!1,values:t.calcdata.cells.values[t.specIndex],rowBlocks:t.calcdata.rowBlocks}),n({},t,{key:"cells2",type:"cells",page:1,prevPages:e,currentRepaint:[null,null],dragHandle:!1,values:t.calcdata.cells.values[t.specIndex],rowBlocks:t.calcdata.rowBlocks}),r]},r.splitToCells=function(t){var e=function(t){var e=t.rowBlocks[t.page],r=e?e.rows[0].rowIndex:0,n=e?r+e.rows.length:0;return[r,n]}(t);return(t.values||[]).slice(e[0],e[1]).map(function(r,n){return{keyWithinBlock:n+("string"==typeof r&&r.match(/[<$&> ]/)?"_keybuster_"+Math.random():""),key:e[0]+n,column:t,calcdata:t.calcdata,page:t.page,rowBlocks:t.rowBlocks,value:r}})}},{"../../lib/extend":687}],1146:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./attributes"),a=t("../../plots/domain").defaults;e.exports=function(t,e,r,o){function s(r,a){return n.coerce(t,e,i,r,a)}a(e,o,s),s("columnwidth"),s("header.values"),s("header.format"),s("header.align"),s("header.prefix"),s("header.suffix"),s("header.height"),s("header.line.width"),s("header.line.color"),s("header.fill.color"),n.coerceFont(s,"header.font",n.extendFlat({},o.font)),function(t,e){for(var r=t.columnorder||[],n=t.header.values.length,i=r.slice(0,n),a=i.slice().sort(function(t,e){return t-e}),o=i.map(function(t){return a.indexOf(t)}),s=o.length;s<n;s++)o.push(s);e("columnorder",o)}(e,s),s("cells.values"),s("cells.format"),s("cells.align"),s("cells.prefix"),s("cells.suffix"),s("cells.height"),s("cells.line.width"),s("cells.line.color"),s("cells.fill.color"),n.coerceFont(s,"cells.font",n.extendFlat({},o.font)),e._length=null}},{"../../lib":697,"../../plots/domain":770,"./attributes":1140}],1147:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("./calc"),n.plot=t("./plot"),n.moduleType="trace",n.name="table",n.basePlotModule=t("./base_plot"),n.categories=["noOpacity"],n.meta={},e.exports=n},{"./attributes":1140,"./base_plot":1141,"./calc":1142,"./defaults":1146,"./plot":1148}],1148:[function(t,e,r){"use strict";var n=t("./constants"),i=t("d3"),a=t("../../lib/gup"),o=t("../../components/drawing"),s=t("../../lib/svg_text_utils"),l=t("../../lib").raiseToTop,c=t("../../lib").cancelTransition,u=t("./data_preparation_helper"),h=t("./data_split_helpers"),f=t("../../components/color");function p(t){return Math.ceil(t.calcdata.maxLineWidth/2)}function d(t,e){return"clip"+t._fullLayout._uid+"_scrollAreaBottomClip_"+e.key}function g(t,e){return"clip"+t._fullLayout._uid+"_columnBoundaryClippath_"+e.calcdata.key+"_"+e.specIndex}function v(t){return[].concat.apply([],t.map(function(t){return t})).map(function(t){return t.__data__})}function m(t,e,r){var o=t.selectAll("."+n.cn.scrollbarKit).data(a.repeat,a.keyFun);o.enter().append("g").classed(n.cn.scrollbarKit,!0).style("shape-rendering","geometricPrecision"),o.each(function(t){var e=t.scrollbarState;e.totalHeight=function(t){var e=t.rowBlocks;return I(e,e.length-1)+(e.length?D(e[e.length-1],1/0):1)}(t),e.scrollableAreaHeight=t.groupHeight-M(t),e.currentlyVisibleHeight=Math.min(e.totalHeight,e.scrollableAreaHeight),e.ratio=e.currentlyVisibleHeight/e.totalHeight,e.barLength=Math.max(e.ratio*e.currentlyVisibleHeight,n.goldenRatio*n.scrollbarWidth),e.barWiggleRoom=e.currentlyVisibleHeight-e.barLength,e.wiggleRoom=Math.max(0,e.totalHeight-e.scrollableAreaHeight),e.topY=0===e.barWiggleRoom?0:t.scrollY/e.wiggleRoom*e.barWiggleRoom,e.bottomY=e.topY+e.barLength,e.dragMultiplier=e.wiggleRoom/e.barWiggleRoom}).attr("transform",function(t){return"translate("+(t.width+n.scrollbarWidth/2+n.scrollbarOffset)+" "+M(t)+")"});var s=o.selectAll("."+n.cn.scrollbar).data(a.repeat,a.keyFun);s.enter().append("g").classed(n.cn.scrollbar,!0);var l=s.selectAll("."+n.cn.scrollbarSlider).data(a.repeat,a.keyFun);l.enter().append("g").classed(n.cn.scrollbarSlider,!0),l.attr("transform",function(t){return"translate(0 "+(t.scrollbarState.topY||0)+")"});var c=l.selectAll("."+n.cn.scrollbarGlyph).data(a.repeat,a.keyFun);c.enter().append("line").classed(n.cn.scrollbarGlyph,!0).attr("stroke","black").attr("stroke-width",n.scrollbarWidth).attr("stroke-linecap","round").attr("y1",n.scrollbarWidth/2),c.attr("y2",function(t){return t.scrollbarState.barLength-n.scrollbarWidth/2}).attr("stroke-opacity",function(t){return t.columnDragInProgress||!t.scrollbarState.barWiggleRoom||r?0:.4}),c.transition().delay(0).duration(0),c.transition().delay(n.scrollbarHideDelay).duration(n.scrollbarHideDuration).attr("stroke-opacity",0);var u=s.selectAll("."+n.cn.scrollbarCaptureZone).data(a.repeat,a.keyFun);u.enter().append("line").classed(n.cn.scrollbarCaptureZone,!0).attr("stroke","white").attr("stroke-opacity",.01).attr("stroke-width",n.scrollbarCaptureWidth).attr("stroke-linecap","butt").attr("y1",0).on("mousedown",function(r){var n=i.event.y,a=this.getBoundingClientRect(),o=r.scrollbarState,s=n-a.top,l=i.scale.linear().domain([0,o.scrollableAreaHeight]).range([0,o.totalHeight]).clamp(!0);o.topY<=s&&s<=o.bottomY||S(e,t,null,l(s-o.barLength/2))(r)}).call(i.behavior.drag().origin(function(t){return i.event.stopPropagation(),t.scrollbarState.scrollbarScrollInProgress=!0,t}).on("drag",S(e,t)).on("dragend",function(){})),u.attr("y2",function(t){return t.scrollbarState.scrollableAreaHeight}),e._context.staticPlot&&(c.remove(),u.remove())}function y(t,e,r,s){var l=function(t){var e=t.selectAll("."+n.cn.columnCell).data(h.splitToCells,function(t){return t.keyWithinBlock});return e.enter().append("g").classed(n.cn.columnCell,!0),e.exit().remove(),e}(function(t){var e=t.selectAll("."+n.cn.columnCells).data(a.repeat,a.keyFun);return e.enter().append("g").classed(n.cn.columnCells,!0),e.exit().remove(),e}(r));!function(t){t.each(function(t,e){var r=t.calcdata.cells.font,n=t.column.specIndex,i={size:_(r.size,n,e),color:_(r.color,n,e),family:_(r.family,n,e)};t.rowNumber=t.key,t.align=_(t.calcdata.cells.align,n,e),t.cellBorderWidth=_(t.calcdata.cells.line.width,n,e),t.font=i})}(l),function(t){t.attr("width",function(t){return t.column.columnWidth}).attr("stroke-width",function(t){return t.cellBorderWidth}).each(function(t){var e=i.select(this);f.stroke(e,_(t.calcdata.cells.line.color,t.column.specIndex,t.rowNumber)),f.fill(e,_(t.calcdata.cells.fill.color,t.column.specIndex,t.rowNumber))})}(function(t){var e=t.selectAll("."+n.cn.cellRect).data(a.repeat,function(t){return t.keyWithinBlock});return e.enter().append("rect").classed(n.cn.cellRect,!0),e}(l));var c=function(t){var e=t.selectAll("."+n.cn.cellText).data(a.repeat,function(t){return t.keyWithinBlock});return e.enter().append("text").classed(n.cn.cellText,!0).style("cursor",function(){return"auto"}).on("mousedown",function(){i.event.stopPropagation()}),e}(function(t){var e=t.selectAll("."+n.cn.cellTextHolder).data(a.repeat,function(t){return t.keyWithinBlock});return e.enter().append("g").classed(n.cn.cellTextHolder,!0).style("shape-rendering","geometricPrecision"),e}(l));!function(t){t.each(function(t){o.font(i.select(this),t.font)})}(c),x(c,e,s,t),O(l)}function x(t,e,r,a){t.text(function(t){var e=t.column.specIndex,r=t.rowNumber,a=t.value,o="string"==typeof a,s=o&&a.match(/<br>/i),l=!o||s;t.mayHaveMarkup=o&&a.match(/[<&>]/);var c,u="string"==typeof(c=a)&&c.match(n.latexCheck);t.latex=u;var h,f,p=u?"":_(t.calcdata.cells.prefix,e,r)||"",d=u?"":_(t.calcdata.cells.suffix,e,r)||"",g=u?null:_(t.calcdata.cells.format,e,r)||null,v=p+(g?i.format(g)(t.value):t.value)+d;if(t.wrappingNeeded=!t.wrapped&&!l&&!u&&(h=b(v)),t.cellHeightMayIncrease=s||u||t.mayHaveMarkup||(void 0===h?b(v):h),t.needsConvertToTspans=t.mayHaveMarkup||t.wrappingNeeded||t.latex,t.wrappingNeeded){var m=(" "===n.wrapSplitCharacter?v.replace(/<a href=/gi,"<a_href="):v).split(n.wrapSplitCharacter),y=" "===n.wrapSplitCharacter?m.map(function(t){return t.replace(/<a_href=/gi,"<a href=")}):m;t.fragments=y.map(function(t){return{text:t,width:null}}),t.fragments.push({fragment:n.wrapSpacer,width:null}),f=y.join(n.lineBreaker)+n.lineBreaker+n.wrapSpacer}else delete t.fragments,f=v;return f}).attr("dy",function(t){return t.needsConvertToTspans?0:"0.75em"}).each(function(t){var o=i.select(this),l=t.wrappingNeeded?C:L;t.needsConvertToTspans?s.convertToTspans(o,a,l(r,this,e,a,t)):i.select(this.parentNode).attr("transform",function(t){return"translate("+z(t)+" "+n.cellPad+")"}).attr("text-anchor",function(t){return{left:"start",center:"middle",right:"end"}[t.align]})})}function b(t){return-1!==t.indexOf(n.wrapSplitCharacter)}function _(t,e,r){if(Array.isArray(t)){var n=t[Math.min(e,t.length-1)];return Array.isArray(n)?n[Math.min(r,n.length-1)]:n}return t}function w(t,e,r){t.transition().ease(n.releaseTransitionEase).duration(n.releaseTransitionDuration).attr("transform","translate("+e.x+" "+r+")")}function k(t){return"cells"===t.type}function A(t){return"header"===t.type}function M(t){return(t.rowBlocks.length?t.rowBlocks[0].auxiliaryBlocks:[]).reduce(function(t,e){return t+D(e,1/0)},0)}function T(t,e,r){var n=v(e)[0];if(void 0!==n){var i=n.rowBlocks,a=n.calcdata,o=I(i,i.length),s=n.calcdata.groupHeight-M(n),l=a.scrollY=Math.max(0,Math.min(o-s,a.scrollY)),c=function(t,e,r){for(var n=[],i=0,a=0;a<t.length;a++){for(var o=t[a],s=o.rows,l=0,c=0;c<s.length;c++)l+=s[c].rowHeight;o.allRowsHeight=l,e<i+l&&e+r>i&&n.push(a),i+=l}return n}(i,l,s);1===c.length&&(c[0]===i.length-1?c.unshift(c[0]-1):c.push(c[0]+1)),c[0]%2&&c.reverse(),e.each(function(t,e){t.page=c[e],t.scrollY=l}),e.attr("transform",function(t){return"translate(0 "+(I(t.rowBlocks,t.page)-t.scrollY)+")"}),t&&(E(t,r,e,c,n.prevPages,n,0),E(t,r,e,c,n.prevPages,n,1),m(r,t))}}function S(t,e,r,a){return function(o){var s=o.calcdata?o.calcdata:o,l=e.filter(function(t){return s.key===t.key}),c=r||s.scrollbarState.dragMultiplier,u=s.scrollY;s.scrollY=void 0===a?s.scrollY+c*i.event.dy:a;var h=l.selectAll("."+n.cn.yColumn).selectAll("."+n.cn.columnBlock).filter(k);return T(t,h,l),s.scrollY===u}}function E(t,e,r,n,i,a,o){n[o]!==i[o]&&(clearTimeout(a.currentRepaint[o]),a.currentRepaint[o]=setTimeout(function(){var a=r.filter(function(t,e){return e===o&&n[e]!==i[e]});y(t,e,a,r),i[o]=n[o]}))}function C(t,e,r,a){return function(){var o=i.select(e.parentNode);o.each(function(t){var e=t.fragments;o.selectAll("tspan.line").each(function(t,r){e[r].width=this.getComputedTextLength()});var r,i,a=e[e.length-1].width,s=e.slice(0,-1),l=[],c=0,u=t.column.columnWidth-2*n.cellPad;for(t.value="";s.length;)c+(i=(r=s.shift()).width+a)>u&&(t.value+=l.join(n.wrapSpacer)+n.lineBreaker,l=[],c=0),l.push(r.text),c+=i;c&&(t.value+=l.join(n.wrapSpacer)),t.wrapped=!0}),o.selectAll("tspan.line").remove(),x(o.select("."+n.cn.cellText),r,t,a),i.select(e.parentNode.parentNode).call(O)}}function L(t,e,r,a,o){return function(){if(!o.settledY){var s=i.select(e.parentNode),l=R(o),c=o.key-l.firstRowIndex,u=l.rows[c].rowHeight,h=o.cellHeightMayIncrease?e.parentNode.getBoundingClientRect().height+2*n.cellPad:u,f=Math.max(h,u);f-l.rows[c].rowHeight&&(l.rows[c].rowHeight=f,t.selectAll("."+n.cn.columnCell).call(O),T(null,t.filter(k),0),m(r,a,!0)),s.attr("transform",function(){var t=this.parentNode.getBoundingClientRect(),e=i.select(this.parentNode).select("."+n.cn.cellRect).node().getBoundingClientRect(),r=this.transform.baseVal.consolidate(),a=e.top-t.top+(r?r.matrix.f:n.cellPad);return"translate("+z(o,i.select(this.parentNode).select("."+n.cn.cellTextHolder).node().getBoundingClientRect().width)+" "+a+")"}),o.settledY=!0}}}function z(t,e){switch(t.align){case"left":return n.cellPad;case"right":return t.column.columnWidth-(e||0)-n.cellPad;case"center":return(t.column.columnWidth-(e||0))/2;default:return n.cellPad}}function O(t){t.attr("transform",function(t){var e=t.rowBlocks[0].auxiliaryBlocks.reduce(function(t,e){return t+D(e,1/0)},0);return"translate(0 "+(D(R(t),t.key)+e)+")"}).selectAll("."+n.cn.cellRect).attr("height",function(t){return(e=R(t),r=t.key,e.rows[r-e.firstRowIndex]).rowHeight;var e,r})}function I(t,e){for(var r=0,n=e-1;n>=0;n--)r+=P(t[n]);return r}function D(t,e){for(var r=0,n=0;n<t.rows.length&&t.rows[n].rowIndex<e;n++)r+=t.rows[n].rowHeight;return r}function P(t){var e=t.allRowsHeight;if(void 0!==e)return e;for(var r=0,n=0;n<t.rows.length;n++)r+=t.rows[n].rowHeight;return t.allRowsHeight=r,r}function R(t){return t.rowBlocks[t.page]}e.exports=function(t,e){var r=!t._context.staticPlot,s=t._fullLayout._paper.selectAll("."+n.cn.table).data(e.map(function(e){var r=a.unwrap(e).trace;return u(t,r)}),a.keyFun);s.exit().remove(),s.enter().append("g").classed(n.cn.table,!0).attr("overflow","visible").style("box-sizing","content-box").style("position","absolute").style("left",0).style("overflow","visible").style("shape-rendering","crispEdges").style("pointer-events","all"),s.attr("width",function(t){return t.width+t.size.l+t.size.r}).attr("height",function(t){return t.height+t.size.t+t.size.b}).attr("transform",function(t){return"translate("+t.translateX+","+t.translateY+")"});var f=s.selectAll("."+n.cn.tableControlView).data(a.repeat,a.keyFun),x=f.enter().append("g").classed(n.cn.tableControlView,!0).style("box-sizing","content-box");r&&x.on("mousemove",function(e){f.filter(function(t){return e===t}).call(m,t)}).on("mousewheel",function(e){if(!e.scrollbarState.wheeling){e.scrollbarState.wheeling=!0;var r=e.scrollY+i.event.deltaY;S(t,f,null,r)(e)||(i.event.stopPropagation(),i.event.preventDefault()),e.scrollbarState.wheeling=!1}}).call(m,t,!0),f.attr("transform",function(t){return"translate("+t.size.l+" "+t.size.t+")"});var b=f.selectAll("."+n.cn.scrollBackground).data(a.repeat,a.keyFun);b.enter().append("rect").classed(n.cn.scrollBackground,!0).attr("fill","none"),b.attr("width",function(t){return t.width}).attr("height",function(t){return t.height}),f.each(function(e){o.setClipUrl(i.select(this),d(t,e),t)});var _=f.selectAll("."+n.cn.yColumn).data(function(t){return t.columns},a.keyFun);_.enter().append("g").classed(n.cn.yColumn,!0),_.exit().remove(),_.attr("transform",function(t){return"translate("+t.x+" 0)"}),r&&_.call(i.behavior.drag().origin(function(e){return w(i.select(this),e,-n.uplift),l(this),e.calcdata.columnDragInProgress=!0,m(f.filter(function(t){return e.calcdata.key===t.key}),t),e}).on("drag",function(t){var e=i.select(this),r=function(e){return(t===e?i.event.x:e.x)+e.columnWidth/2};t.x=Math.max(-n.overdrag,Math.min(t.calcdata.width+n.overdrag-t.columnWidth,i.event.x)),v(_).filter(function(e){return e.calcdata.key===t.calcdata.key}).sort(function(t,e){return r(t)-r(e)}).forEach(function(e,r){e.xIndex=r,e.x=t===e?e.x:e.xScale(e)}),_.filter(function(e){return t!==e}).transition().ease(n.transitionEase).duration(n.transitionDuration).attr("transform",function(t){return"translate("+t.x+" 0)"}),e.call(c).attr("transform","translate("+t.x+" -"+n.uplift+" )")}).on("dragend",function(e){var r=i.select(this),n=e.calcdata;e.x=e.xScale(e),e.calcdata.columnDragInProgress=!1,w(r,e,0),function(t,e,r){var n=e.gdColumnsOriginalOrder;e.gdColumns.sort(function(t,e){return r[n.indexOf(t)]-r[n.indexOf(e)]}),e.columnorder=r,t.emit("plotly_restyle")}(t,n,n.columns.map(function(t){return t.xIndex}))})),_.each(function(e){o.setClipUrl(i.select(this),g(t,e),t)});var M=_.selectAll("."+n.cn.columnBlock).data(h.splitToPanels,a.keyFun);M.enter().append("g").classed(n.cn.columnBlock,!0).attr("id",function(t){return t.key}),M.style("cursor",function(t){return t.dragHandle?"ew-resize":t.calcdata.scrollbarState.barWiggleRoom?"ns-resize":"default"});var E=M.filter(A),C=M.filter(k);r&&C.call(i.behavior.drag().origin(function(t){return i.event.stopPropagation(),t}).on("drag",S(t,f,-1)).on("dragend",function(){})),y(t,f,E,M),y(t,f,C,M);var L=f.selectAll("."+n.cn.scrollAreaClip).data(a.repeat,a.keyFun);L.enter().append("clipPath").classed(n.cn.scrollAreaClip,!0).attr("id",function(e){return d(t,e)});var z=L.selectAll("."+n.cn.scrollAreaClipRect).data(a.repeat,a.keyFun);z.enter().append("rect").classed(n.cn.scrollAreaClipRect,!0).attr("x",-n.overdrag).attr("y",-n.uplift).attr("fill","none"),z.attr("width",function(t){return t.width+2*n.overdrag}).attr("height",function(t){return t.height+n.uplift}),_.selectAll("."+n.cn.columnBoundary).data(a.repeat,a.keyFun).enter().append("g").classed(n.cn.columnBoundary,!0);var O=_.selectAll("."+n.cn.columnBoundaryClippath).data(a.repeat,a.keyFun);O.enter().append("clipPath").classed(n.cn.columnBoundaryClippath,!0),O.attr("id",function(e){return g(t,e)});var I=O.selectAll("."+n.cn.columnBoundaryRect).data(a.repeat,a.keyFun);I.enter().append("rect").classed(n.cn.columnBoundaryRect,!0).attr("fill","none"),I.attr("width",function(t){return t.columnWidth+2*p(t)}).attr("height",function(t){return t.calcdata.height+2*p(t)+n.uplift}).attr("x",function(t){return-p(t)}).attr("y",function(t){return-p(t)}),T(null,C,f)}},{"../../components/color":574,"../../components/drawing":595,"../../lib":697,"../../lib/gup":695,"../../lib/svg_text_utils":721,"./constants":1143,"./data_preparation_helper":1144,"./data_split_helpers":1145,d3:151}],1149:[function(t,e,r){"use strict";var n=t("../box/attributes"),i=t("../../lib/extend").extendFlat;e.exports={y:n.y,x:n.x,x0:n.x0,y0:n.y0,name:n.name,orientation:i({},n.orientation,{}),bandwidth:{valType:"number",min:0,editType:"calc"},scalegroup:{valType:"string",dflt:"",editType:"calc"},scalemode:{valType:"enumerated",values:["width","count"],dflt:"width",editType:"calc"},spanmode:{valType:"enumerated",values:["soft","hard","manual"],dflt:"soft",editType:"calc"},span:{valType:"info_array",items:[{valType:"any",editType:"calc"},{valType:"any",editType:"calc"}],editType:"calc"},line:{color:{valType:"color",editType:"style"},width:{valType:"number",min:0,dflt:2,editType:"style"},editType:"plot"},fillcolor:n.fillcolor,points:i({},n.boxpoints,{}),jitter:i({},n.jitter,{}),pointpos:i({},n.pointpos,{}),width:i({},n.width,{}),marker:n.marker,text:n.text,hovertext:n.hovertext,box:{visible:{valType:"boolean",dflt:!1,editType:"plot"},width:{valType:"number",min:0,max:1,dflt:.25,editType:"plot"},fillcolor:{valType:"color",editType:"style"},line:{color:{valType:"color",editType:"style"},width:{valType:"number",min:0,editType:"style"},editType:"style"},editType:"plot"},meanline:{visible:{valType:"boolean",dflt:!1,editType:"plot"},color:{valType:"color",editType:"style"},width:{valType:"number",min:0,editType:"style"},editType:"plot"},side:{valType:"enumerated",values:["both","positive","negative"],dflt:"both",editType:"calc"},offsetgroup:n.offsetgroup,alignmentgroup:n.alignmentgroup,selected:n.selected,unselected:n.unselected,hoveron:{valType:"flaglist",flags:["violins","points","kde"],dflt:"violins+points+kde",extras:["all"],editType:"style"}}},{"../../lib/extend":687,"../box/attributes":859}],1150:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/cartesian/axes"),a=t("../box/calc"),o=t("./helpers"),s=t("../../constants/numerical").BADNUM;function l(t,e,r){var i=e.max-e.min;if(!i)return 1;if(t.bandwidth)return Math.max(t.bandwidth,i/1e4);var a=r.length,o=n.stdev(r,a-1,e.mean);return Math.max(function(t,e,r){return 1.059*Math.min(e,r/1.349)*Math.pow(t,-.2)}(a,o,e.q3-e.q1),i/100)}function c(t,e,r,n){var a,o=t.spanmode,l=t.span||[],c=[e.min,e.max],u=[e.min-2*n,e.max+2*n];function h(n){var i=l[n],a="multicategory"===r.type?r.r2c(i):r.d2c(i,0,t[e.valLetter+"calendar"]);return a===s?u[n]:a}var f={type:"linear",range:a="soft"===o?u:"hard"===o?c:[h(0),h(1)]};return i.setConvert(f),f.cleanRange(),a}e.exports=function(t,e){var r=a(t,e);if(r[0].t.empty)return r;for(var s=t._fullLayout,u=i.getFromId(t,e["h"===e.orientation?"xaxis":"yaxis"]),h=1/0,f=-1/0,p=0,d=0,g=0;g<r.length;g++){var v=r[g],m=v.pts.map(o.extractVal),y=v.bandwidth=l(e,v,m),x=v.span=c(e,v,u,y),b=x[1]-x[0],_=Math.ceil(b/(y/3)),w=b/_;if(!isFinite(w)||!isFinite(_))return n.error("Something went wrong with computing the violin span"),r[0].t.empty=!0,r;var k=o.makeKDE(v,e,m);v.density=new Array(_);for(var A=0,M=x[0];M<x[1]+w/2;A++,M+=w){var T=k(M);v.density[A]={v:T,t:M},p=Math.max(p,T)}d=Math.max(d,m.length),h=Math.min(h,x[0]),f=Math.max(f,x[1])}var S=i.findExtremes(u,[h,f],{padded:!0});if(e._extremes[u._id]=S,e.width)r[0].t.maxKDE=p;else{var E=s._violinScaleGroupStats,C=e.scalegroup,L=E[C];L?(L.maxKDE=Math.max(L.maxKDE,p),L.maxCount=Math.max(L.maxCount,d)):E[C]={maxKDE:p,maxCount:d}}return r[0].t.labels.kde=n._(t,"kde:"),r}},{"../../constants/numerical":674,"../../lib":697,"../../plots/cartesian/axes":745,"../box/calc":860,"./helpers":1153}],1151:[function(t,e,r){"use strict";var n=t("../box/cross_trace_calc").setPositionOffset,i=["v","h"];e.exports=function(t,e){for(var r=t.calcdata,a=e.xaxis,o=e.yaxis,s=0;s<i.length;s++){for(var l=i[s],c="h"===l?o:a,u=[],h=0;h<r.length;h++){var f=r[h],p=f[0].t,d=f[0].trace;!0!==d.visible||"violin"!==d.type||p.empty||d.orientation!==l||d.xaxis!==a._id||d.yaxis!==o._id||u.push(h)}n("violin",t,u,c)}}},{"../box/cross_trace_calc":861}],1152:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/color"),a=t("../box/defaults"),o=t("./attributes");e.exports=function(t,e,r,s){function l(r,i){return n.coerce(t,e,o,r,i)}function c(r,i){return n.coerce2(t,e,o,r,i)}if(a.handleSampleDefaults(t,e,l,s),!1!==e.visible){l("bandwidth"),l("side"),l("width")||(l("scalegroup",e.name),l("scalemode"));var u,h=l("span");Array.isArray(h)&&(u="manual"),l("spanmode",u);var f=l("line.color",(t.marker||{}).color||r),p=l("line.width"),d=l("fillcolor",i.addOpacity(e.line.color,.5));a.handlePointsDefaults(t,e,l,{prefix:""});var g=c("box.width"),v=c("box.fillcolor",d),m=c("box.line.color",f),y=c("box.line.width",p);l("box.visible",Boolean(g||v||m||y))||(e.box={visible:!1});var x=c("meanline.color",f),b=c("meanline.width",p);l("meanline.visible",Boolean(x||b))||(e.meanline={visible:!1})}}},{"../../components/color":574,"../../lib":697,"../box/defaults":862,"./attributes":1149}],1153:[function(t,e,r){"use strict";var n=t("../../lib"),i=function(t){return 1/Math.sqrt(2*Math.PI)*Math.exp(-.5*t*t)};r.makeKDE=function(t,e,r){var n=r.length,a=i,o=t.bandwidth,s=1/(n*o);return function(t){for(var e=0,i=0;i<n;i++)e+=a((t-r[i])/o);return s*e}},r.getPositionOnKdePath=function(t,e,r){var i,a;"h"===e.orientation?(i="y",a="x"):(i="x",a="y");var o=n.findPointOnPath(t.path,r,a,{pathLength:t.pathLength}),s=t.posCenterPx,l=o[i];return[l,"both"===e.side?2*s-l:s]},r.getKdeValue=function(t,e,n){var i=t.pts.map(r.extractVal);return r.makeKDE(t,e,i)(n)/t.posDensityScale},r.extractVal=function(t){return t.v}},{"../../lib":697}],1154:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/cartesian/axes"),a=t("../box/hover"),o=t("./helpers");e.exports=function(t,e,r,s,l){var c,u,h=t.cd,f=h[0].trace,p=f.hoveron,d=-1!==p.indexOf("violins"),g=-1!==p.indexOf("kde"),v=[];if(d||g){var m=a.hoverOnBoxes(t,e,r,s);if(d&&(v=v.concat(m)),g&&m.length>0){var y,x,b,_,w,k=t.xa,A=t.ya;"h"===f.orientation?(w=e,y="y",b=A,x="x",_=k):(w=r,y="x",b=k,x="y",_=A);var M=h[t.index];if(w>=M.span[0]&&w<=M.span[1]){var T=n.extendFlat({},t),S=_.c2p(w,!0),E=o.getKdeValue(M,f,w),C=o.getPositionOnKdePath(M,f,S),L=b._offset,z=b._length;T[y+"0"]=C[0],T[y+"1"]=C[1],T[x+"0"]=T[x+"1"]=S,T[x+"Label"]=x+": "+i.hoverLabelText(_,w)+", "+h[0].t.labels.kde+" "+E.toFixed(3),T.spikeDistance=m[0].spikeDistance;var O=y+"Spike";T[O]=m[0][O],m[0].spikeDistance=void 0,m[0][O]=void 0,v.push(T),(u={stroke:t.color})[y+"1"]=n.constrain(L+C[0],L,L+z),u[y+"2"]=n.constrain(L+C[1],L,L+z),u[x+"1"]=u[x+"2"]=_._offset+S}}}-1!==p.indexOf("points")&&(c=a.hoverOnPoints(t,e,r));var I=l.selectAll(".violinline-"+f.uid).data(u?[0]:[]);return I.enter().append("line").classed("violinline-"+f.uid,!0).attr("stroke-width",1.5),I.exit().remove(),I.attr(u),"closest"===s?c?[c]:v:c?(v.push(c),v):v}},{"../../lib":697,"../../plots/cartesian/axes":745,"../box/hover":864,"./helpers":1153}],1155:[function(t,e,r){"use strict";e.exports={attributes:t("./attributes"),layoutAttributes:t("./layout_attributes"),supplyDefaults:t("./defaults"),crossTraceDefaults:t("../box/defaults").crossTraceDefaults,supplyLayoutDefaults:t("./layout_defaults"),calc:t("./calc"),crossTraceCalc:t("./cross_trace_calc"),plot:t("./plot"),style:t("./style"),styleOnSelect:t("../scatter/style").styleOnSelect,hoverPoints:t("./hover"),selectPoints:t("../box/select"),moduleType:"trace",name:"violin",basePlotModule:t("../../plots/cartesian"),categories:["cartesian","svg","symbols","oriented","box-violin","showLegend","violinLayout","zoomScale"],meta:{}}},{"../../plots/cartesian":756,"../box/defaults":862,"../box/select":869,"../scatter/style":1071,"./attributes":1149,"./calc":1150,"./cross_trace_calc":1151,"./defaults":1152,"./hover":1154,"./layout_attributes":1156,"./layout_defaults":1157,"./plot":1158,"./style":1159}],1156:[function(t,e,r){"use strict";var n=t("../box/layout_attributes"),i=t("../../lib").extendFlat;e.exports={violinmode:i({},n.boxmode,{}),violingap:i({},n.boxgap,{}),violingroupgap:i({},n.boxgroupgap,{})}},{"../../lib":697,"../box/layout_attributes":866}],1157:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./layout_attributes"),a=t("../box/layout_defaults");e.exports=function(t,e,r){a._supply(t,e,r,function(r,a){return n.coerce(t,e,i,r,a)},"violin")}},{"../../lib":697,"../box/layout_defaults":867,"./layout_attributes":1156}],1158:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../lib"),a=t("../../components/drawing"),o=t("../box/plot"),s=t("../scatter/line_points"),l=t("./helpers");e.exports=function(t,e,r,c){var u=t._fullLayout,h=e.xaxis,f=e.yaxis;function p(t){var e=s(t,{xaxis:h,yaxis:f,connectGaps:!0,baseTolerance:.75,shape:"spline",simplify:!0});return a.smoothopen(e[0],1)}i.makeTraceGroups(c,r,"trace violins").each(function(t){var r=n.select(this),a=t[0],s=a.t,c=a.trace;if(e.isRangePlot||(a.node3=r),!0!==c.visible||s.empty)r.remove();else{var d=s.bPos,g=s.bdPos,v=e[s.valLetter+"axis"],m=e[s.posLetter+"axis"],y="both"===c.side,x=y||"positive"===c.side,b=y||"negative"===c.side,_=r.selectAll("path.violin").data(i.identity);_.enter().append("path").style("vector-effect","non-scaling-stroke").attr("class","violin"),_.exit().remove(),_.each(function(t){var e,r,i,a,o,l,h,f,_=n.select(this),w=t.density,k=w.length,A=t.pos+d,M=m.c2p(A);if(c.width)e=s.maxKDE/g;else{var T=u._violinScaleGroupStats[c.scalegroup];e="count"===c.scalemode?T.maxKDE/g*(T.maxCount/t.pts.length):T.maxKDE/g}if(x){for(h=new Array(k),o=0;o<k;o++)(f=h[o]={})[s.posLetter]=A+w[o].v/e,f[s.valLetter]=w[o].t;r=p(h)}if(b){for(h=new Array(k),l=0,o=k-1;l<k;l++,o--)(f=h[l]={})[s.posLetter]=A-w[o].v/e,f[s.valLetter]=w[o].t;i=p(h)}if(y)a=r+"L"+i.substr(1)+"Z";else{var S=[M,v.c2p(w[0].t)],E=[M,v.c2p(w[k-1].t)];"h"===c.orientation&&(S.reverse(),E.reverse()),a=x?"M"+S+"L"+r.substr(1)+"L"+E:"M"+E+"L"+i.substr(1)+"L"+S}_.attr("d",a),t.posCenterPx=M,t.posDensityScale=e*g,t.path=_.node(),t.pathLength=t.path.getTotalLength()/(y?2:1)});var w,k,A,M=c.box,T=M.width,S=(M.line||{}).width;y?(w=g*T,k=0):x?(w=[0,g*T/2],k=-S):(w=[g*T/2,0],k=S),o.plotBoxAndWhiskers(r,{pos:m,val:v},c,{bPos:d,bdPos:w,bPosPxOffset:k}),o.plotBoxMean(r,{pos:m,val:v},c,{bPos:d,bdPos:w,bPosPxOffset:k}),!c.box.visible&&c.meanline.visible&&(A=i.identity);var E=r.selectAll("path.meanline").data(A||[]);E.enter().append("path").attr("class","meanline").style("fill","none").style("vector-effect","non-scaling-stroke"),E.exit().remove(),E.each(function(t){var e=v.c2p(t.mean,!0),r=l.getPositionOnKdePath(t,c,e);n.select(this).attr("d","h"===c.orientation?"M"+e+","+r[0]+"V"+r[1]:"M"+r[0]+","+e+"H"+r[1])}),o.plotPoints(r,{x:h,y:f},c,s)}})}},{"../../components/drawing":595,"../../lib":697,"../box/plot":868,"../scatter/line_points":1062,"./helpers":1153,d3:151}],1159:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../components/color"),a=t("../scatter/style").stylePoints;e.exports=function(t,e){var r=e?e[0].node3:n.select(t).selectAll("g.trace.violins");r.style("opacity",function(t){return t[0].trace.opacity}),r.each(function(e){var r=e[0].trace,o=n.select(this),s=r.box||{},l=s.line||{},c=r.meanline||{},u=c.width;o.selectAll("path.violin").style("stroke-width",r.line.width+"px").call(i.stroke,r.line.color).call(i.fill,r.fillcolor),o.selectAll("path.box").style("stroke-width",l.width+"px").call(i.stroke,l.color).call(i.fill,s.fillcolor);var h={"stroke-width":u+"px","stroke-dasharray":2*u+"px,"+u+"px"};o.selectAll("path.mean").style(h).call(i.stroke,c.color),o.selectAll("path.meanline").style(h).call(i.stroke,c.color),a(o,r,t)})}},{"../../components/color":574,"../scatter/style":1071,d3:151}],1160:[function(t,e,r){"use strict";var n=t("../plots/cartesian/axes"),i=t("../lib"),a=t("../plot_api/plot_schema"),o=t("./helpers").pointsAccessorFunction,s=t("../constants/numerical").BADNUM;r.moduleType="transform",r.name="aggregate";var l=r.attributes={enabled:{valType:"boolean",dflt:!0,editType:"calc"},groups:{valType:"string",strict:!0,noBlank:!0,arrayOk:!0,dflt:"x",editType:"calc"},aggregations:{_isLinkedToArray:"aggregation",target:{valType:"string",editType:"calc"},func:{valType:"enumerated",values:["count","sum","avg","median","mode","rms","stddev","min","max","first","last","change","range"],dflt:"first",editType:"calc"},funcmode:{valType:"enumerated",values:["sample","population"],dflt:"sample",editType:"calc"},enabled:{valType:"boolean",dflt:!0,editType:"calc"},editType:"calc"},editType:"calc"},c=l.aggregations;function u(t,e,r,a){if(a.enabled){for(var o=a.target,l=i.nestedProperty(e,o),c=l.get(),u=function(t,e){var r=t.func,n=e.d2c,i=e.c2d;switch(r){case"count":return h;case"first":return f;case"last":return p;case"sum":return function(t,e){for(var r=0,a=0;a<e.length;a++){var o=n(t[e[a]]);o!==s&&(r+=o)}return i(r)};case"avg":return function(t,e){for(var r=0,a=0,o=0;o<e.length;o++){var l=n(t[e[o]]);l!==s&&(r+=l,a++)}return a?i(r/a):s};case"min":return function(t,e){for(var r=1/0,a=0;a<e.length;a++){var o=n(t[e[a]]);o!==s&&(r=Math.min(r,o))}return r===1/0?s:i(r)};case"max":return function(t,e){for(var r=-1/0,a=0;a<e.length;a++){var o=n(t[e[a]]);o!==s&&(r=Math.max(r,o))}return r===-1/0?s:i(r)};case"range":return function(t,e){for(var r=1/0,a=-1/0,o=0;o<e.length;o++){var l=n(t[e[o]]);l!==s&&(r=Math.min(r,l),a=Math.max(a,l))}return a===-1/0||r===1/0?s:i(a-r)};case"change":return function(t,e){var r=n(t[e[0]]),a=n(t[e[e.length-1]]);return r===s||a===s?s:i(a-r)};case"median":return function(t,e){for(var r=[],a=0;a<e.length;a++){var o=n(t[e[a]]);o!==s&&r.push(o)}if(!r.length)return s;r.sort();var l=(r.length-1)/2;return i((r[Math.floor(l)]+r[Math.ceil(l)])/2)};case"mode":return function(t,e){for(var r={},a=0,o=s,l=0;l<e.length;l++){var c=n(t[e[l]]);if(c!==s){var u=r[c]=(r[c]||0)+1;u>a&&(a=u,o=c)}}return a?i(o):s};case"rms":return function(t,e){for(var r=0,a=0,o=0;o<e.length;o++){var l=n(t[e[o]]);l!==s&&(r+=l*l,a++)}return a?i(Math.sqrt(r/a)):s};case"stddev":return function(e,r){var i,a=0,o=0,l=1,c=s;for(i=0;i<r.length&&c===s;i++)c=n(e[r[i]]);if(c===s)return s;for(;i<r.length;i++){var u=n(e[r[i]]);if(u!==s){var h=u-c;a+=h,o+=h*h,l++}}var f="sample"===t.funcmode?l-1:l;return f?Math.sqrt((o-a*a/l)/f):0}}}(a,n.getDataConversions(t,e,o,c)),d=new Array(r.length),g=0;g<r.length;g++)d[g]=u(c,r[g]);l.set(d),"count"===a.func&&i.pushUnique(e._arrayAttrs,o)}}function h(t,e){return e.length}function f(t,e){return t[e[0]]}function p(t,e){return t[e[e.length-1]]}r.supplyDefaults=function(t,e){var r,n={};function o(e,r){return i.coerce(t,n,l,e,r)}if(!o("enabled"))return n;var s=a.findArrayAttributes(e),u={};for(r=0;r<s.length;r++)u[s[r]]=1;var h=o("groups");if(!Array.isArray(h)){if(!u[h])return n.enabled=!1,n;u[h]=0}var f,p=t.aggregations||[],d=n.aggregations=new Array(p.length);function g(t,e){return i.coerce(p[r],f,c,t,e)}for(r=0;r<p.length;r++){f={_index:r};var v=g("target"),m=g("func");g("enabled")&&v&&(u[v]||"count"===m&&void 0===u[v])?("stddev"===m&&g("funcmode"),u[v]=0,d[r]=f):d[r]={enabled:!1,_index:r}}for(r=0;r<s.length;r++)u[s[r]]&&d.push({target:s[r],func:c.func.dflt,enabled:!0,_index:-1});return n},r.calcTransform=function(t,e,r){if(r.enabled){var n=r.groups,a=i.getTargetArray(e,{target:n});if(a){var s,l,c,h,f={},p={},d=[],g=o(e.transforms,r),v=a.length;for(e._length&&(v=Math.min(v,e._length)),s=0;s<v;s++)void 0===(c=f[l=a[s]])?(f[l]=d.length,h=[s],d.push(h),p[f[l]]=g(s)):(d[c].push(s),p[f[l]]=(p[f[l]]||[]).concat(g(s)));r._indexToPoints=p;var m=r.aggregations;for(s=0;s<m.length;s++)u(t,e,d,m[s]);"string"==typeof n&&u(t,e,d,{target:n,func:"first",enabled:!0}),e._length=d.length}}}},{"../constants/numerical":674,"../lib":697,"../plot_api/plot_schema":734,"../plots/cartesian/axes":745,"./helpers":1163}],1161:[function(t,e,r){"use strict";var n=t("../lib"),i=t("../registry"),a=t("../plots/cartesian/axes"),o=t("./helpers").pointsAccessorFunction,s=t("../constants/filter_ops"),l=s.COMPARISON_OPS,c=s.INTERVAL_OPS,u=s.SET_OPS;r.moduleType="transform",r.name="filter",r.attributes={enabled:{valType:"boolean",dflt:!0,editType:"calc"},target:{valType:"string",strict:!0,noBlank:!0,arrayOk:!0,dflt:"x",editType:"calc"},operation:{valType:"enumerated",values:[].concat(l).concat(c).concat(u),dflt:"=",editType:"calc"},value:{valType:"any",dflt:0,editType:"calc"},preservegaps:{valType:"boolean",dflt:!1,editType:"calc"},editType:"calc"},r.supplyDefaults=function(t){var e={};function a(i,a){return n.coerce(t,e,r.attributes,i,a)}if(a("enabled")){a("preservegaps"),a("operation"),a("value"),a("target");var o=i.getComponentMethod("calendars","handleDefaults");o(t,e,"valuecalendar",null),o(t,e,"targetcalendar",null)}return e},r.calcTransform=function(t,e,r){if(r.enabled){var i=n.getTargetArray(e,r);if(i){var s=r.target,h=i.length;e._length&&(h=Math.min(h,e._length));var f=r.targetcalendar,p=e._arrayAttrs,d=r.preservegaps;if("string"==typeof s){var g=n.nestedProperty(e,s+"calendar").get();g&&(f=g)}var v,m,y=function(t,e,r){var n=t.operation,i=t.value,a=Array.isArray(i);function o(t){return-1!==t.indexOf(n)}var s,h=function(r){return e(r,0,t.valuecalendar)},f=function(t){return e(t,0,r)};o(l)?s=h(a?i[0]:i):o(c)?s=a?[h(i[0]),h(i[1])]:[h(i),h(i)]:o(u)&&(s=a?i.map(h):[h(i)]);switch(n){case"=":return function(t){return f(t)===s};case"!=":return function(t){return f(t)!==s};case"<":return function(t){return f(t)<s};case"<=":return function(t){return f(t)<=s};case">":return function(t){return f(t)>s};case">=":return function(t){return f(t)>=s};case"[]":return function(t){var e=f(t);return e>=s[0]&&e<=s[1]};case"()":return function(t){var e=f(t);return e>s[0]&&e<s[1]};case"[)":return function(t){var e=f(t);return e>=s[0]&&e<s[1]};case"(]":return function(t){var e=f(t);return e>s[0]&&e<=s[1]};case"][":return function(t){var e=f(t);return e<=s[0]||e>=s[1]};case")(":return function(t){var e=f(t);return e<s[0]||e>s[1]};case"](":return function(t){var e=f(t);return e<=s[0]||e>s[1]};case")[":return function(t){var e=f(t);return e<s[0]||e>=s[1]};case"{}":return function(t){return-1!==s.indexOf(f(t))};case"}{":return function(t){return-1===s.indexOf(f(t))}}}(r,a.getDataToCoordFunc(t,e,s,i),f),x={},b={},_=0;d?(v=function(t){x[t.astr]=n.extendDeep([],t.get()),t.set(new Array(h))},m=function(t,e){var r=x[t.astr][e];t.get()[e]=r}):(v=function(t){x[t.astr]=n.extendDeep([],t.get()),t.set([])},m=function(t,e){var r=x[t.astr][e];t.get().push(r)}),A(v);for(var w=o(e.transforms,r),k=0;k<h;k++){y(i[k])?(A(m,k),b[_++]=w(k)):d&&_++}r._indexToPoints=b,e._length=_}}function A(t,r){for(var i=0;i<p.length;i++){t(n.nestedProperty(e,p[i]),r)}}}},{"../constants/filter_ops":670,"../lib":697,"../plots/cartesian/axes":745,"../registry":826,"./helpers":1163}],1162:[function(t,e,r){"use strict";var n=t("../lib"),i=t("../plot_api/plot_schema"),a=t("../plots/plots"),o=t("./helpers").pointsAccessorFunction;function s(t,e){var r,s,l,c,u,h,f,p,d,g,v=e.transform,m=e.transformIndex,y=t.transforms[m].groups,x=o(t.transforms,v);if(!Array.isArray(y)||0===y.length)return[t];var b=n.filterUnique(y),_=new Array(b.length),w=y.length,k=i.findArrayAttributes(t),A=v.styles||[],M={};for(r=0;r<A.length;r++)M[A[r].target]=A[r].value;v.styles&&(g=n.keyedContainer(v,"styles","target","value.name"));var T={},S={};for(r=0;r<b.length;r++){T[h=b[r]]=r,S[h]=0,(f=_[r]=n.extendDeepNoArrays({},t))._group=h,f.transforms[m]._indexToPoints={};var E=null;for(g&&(E=g.get(h)),f.name=E||""===E?E:n.templateString(v.nameformat,{trace:t.name,group:h}),p=f.transforms,f.transforms=[],s=0;s<p.length;s++)f.transforms[s]=n.extendDeepNoArrays({},p[s]);for(s=0;s<k.length;s++)n.nestedProperty(f,k[s]).set([])}for(l=0;l<k.length;l++){for(c=k[l],s=0,d=[];s<b.length;s++)d[s]=n.nestedProperty(_[s],c).get();for(u=n.nestedProperty(t,c).get(),s=0;s<w;s++)d[T[y[s]]].push(u[s])}for(s=0;s<w;s++){(f=_[T[y[s]]]).transforms[m]._indexToPoints[S[y[s]]]=x(s),S[y[s]]++}for(r=0;r<b.length;r++)h=b[r],f=_[r],a.clearExpandedTraceDefaultColors(f),f=n.extendDeepNoArrays(f,M[h]||{});return _}r.moduleType="transform",r.name="groupby",r.attributes={enabled:{valType:"boolean",dflt:!0,editType:"calc"},groups:{valType:"data_array",dflt:[],editType:"calc"},nameformat:{valType:"string",editType:"calc"},styles:{_isLinkedToArray:"style",target:{valType:"string",editType:"calc"},value:{valType:"any",dflt:{},editType:"calc",_compareAsJSON:!0},editType:"calc"},editType:"calc"},r.supplyDefaults=function(t,e,i){var a,o={};function s(e,i){return n.coerce(t,o,r.attributes,e,i)}if(!s("enabled"))return o;s("groups"),s("nameformat",i._dataLength>1?"%{group} (%{trace})":"%{group}");var l=t.styles,c=o.styles=[];if(l)for(a=0;a<l.length;a++){var u=c[a]={};n.coerce(l[a],c[a],r.attributes.styles,"target");var h=n.coerce(l[a],c[a],r.attributes.styles,"value");n.isPlainObject(h)?u.value=n.extendDeep({},h):h&&delete u.value}return o},r.transform=function(t,e){var r,n,i,a=[];for(n=0;n<t.length;n++)for(r=s(t[n],e),i=0;i<r.length;i++)a.push(r[i]);return a}},{"../lib":697,"../plot_api/plot_schema":734,"../plots/plots":807,"./helpers":1163}],1163:[function(t,e,r){"use strict";r.pointsAccessorFunction=function(t,e){for(var r,n,i=0;i<t.length&&(r=t[i])!==e;i++)r._indexToPoints&&!1!==r.enabled&&(n=r._indexToPoints);return n?function(t){return n[t]}:function(t){return[t]}}},{}],1164:[function(t,e,r){"use strict";var n=t("../lib"),i=t("../plots/cartesian/axes"),a=t("./helpers").pointsAccessorFunction;r.moduleType="transform",r.name="sort",r.attributes={enabled:{valType:"boolean",dflt:!0,editType:"calc"},target:{valType:"string",strict:!0,noBlank:!0,arrayOk:!0,dflt:"x",editType:"calc"},order:{valType:"enumerated",values:["ascending","descending"],dflt:"ascending",editType:"calc"},editType:"calc"},r.supplyDefaults=function(t){var e={};function i(i,a){return n.coerce(t,e,r.attributes,i,a)}return i("enabled")&&(i("target"),i("order")),e},r.calcTransform=function(t,e,r){if(r.enabled){var o=n.getTargetArray(e,r);if(o){var s=r.target,l=o.length;e._length&&(l=Math.min(l,e._length));var c,u,h=e._arrayAttrs,f=function(t,e,r,n){var i,a=new Array(n),o=new Array(n);for(i=0;i<n;i++)a[i]={v:e[i],i:i};for(a.sort(function(t,e){switch(t.order){case"ascending":return function(t,r){return e(t.v)-e(r.v)};case"descending":return function(t,r){return e(r.v)-e(t.v)}}}(t,r)),i=0;i<n;i++)o[i]=a[i].i;return o}(r,o,i.getDataToCoordFunc(t,e,s,o),l),p=a(e.transforms,r),d={};for(c=0;c<h.length;c++){var g=n.nestedProperty(e,h[c]),v=g.get(),m=new Array(l);for(u=0;u<l;u++)m[u]=v[f[u]];g.set(m)}for(u=0;u<l;u++)d[u]=p(f[u]);r._indexToPoints=d,e._length=l}}}},{"../lib":697,"../plots/cartesian/axes":745,"./helpers":1163}]},{},[22])(22)});
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "nEUT":
/*!*************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/launcher/style/index.css ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n/* Private CSS variables */\n\n:root {\n  --jp-private-launcher-top-padding: 16px;\n  --jp-private-launcher-side-padding: 32px;\n  --jp-private-launcher-card-size: 100px;\n  --jp-private-launcher-card-label-height: 25px;\n  --jp-private-launcher-card-icon-height: 75px;\n  --jp-private-launcher-large-icon-size: 52px;\n  --jp-private-launcher-small-icon-size: 32px;\n}\n\n/* Launcher */\n\n.jp-Launcher {\n  margin: 0;\n  padding: 0;\n  outline: none;\n  background: var(--jp-layout-color0);\n  box-sizing: border-box;\n  min-width: 120px;\n  min-height: 120px;\n  /* This is needed so that all font sizing of children done in ems is\n   * relative to this base size */\n  font-size: var(--jp-ui-font-size1);\n}\n\n.jp-Launcher-body {\n  width: 100%;\n  height: 100%;\n  box-sizing: border-box;\n  overflow: auto;\n  display: flex;\n  justify-content: center;\n}\n\n.jp-Launcher-cwd h3 {\n  font-size: var(--jp-ui-font-size2);\n  font-weight: normal;\n  color: var(--jp-ui-font-color1);\n  margin: 1em 0px;\n}\n\n.jp-Launcher-content {\n  width: 85%;\n  height: 100%;\n  padding-top: var(--jp-private-launcher-top-padding);\n  padding-left: var(--jp-private-launcher-side-padding);\n  padding-right: var(--jp-private-launcher-side-padding);\n  box-sizing: border-box;\n}\n\n/* Launcher section */\n\n.jp-Launcher-section {\n  width: 100%;\n  box-sizing: border-box;\n  padding-bottom: 12px;\n}\n\n.jp-Launcher-sectionHeader {\n  display: flex;\n  flex-direction: row;\n  align-items: center;\n  box-sizing: border-box;\n  /* This is custom tuned to get the section header to align with the cards */\n  margin-left: 5px;\n  border-bottom: 1px solid var(--jp-border-color2);\n  padding-bottom: 0px;\n  margin-bottom: 8px;\n}\n\n.jp-Launcher-sectionHeader .jp-Launcher-sectionIcon {\n  box-sizing: border-box;\n  margin-right: 12px;\n  height: var(--jp-private-launcher-small-icon-size);\n  width: var(--jp-private-launcher-small-icon-size);\n  background-size: var(--jp-private-launcher-small-icon-size)\n    var(--jp-private-launcher-small-icon-size);\n}\n\n.jp-Launcher-sectionTitle {\n  font-size: var(--jp-ui-font-size2);\n  font-weight: normal;\n  color: var(--jp-ui-font-color1);\n  box-sizing: border-box;\n}\n\n/* Launcher cards */\n\n.jp-Launcher-cardContainer {\n  margin: 0;\n  padding: 0;\n  box-sizing: border-box;\n  display: flex;\n  flex-direction: row;\n  flex-wrap: wrap;\n}\n\n.jp-LauncherCard {\n  display: flex;\n  flex-direction: column;\n  cursor: pointer;\n  width: var(--jp-private-launcher-card-size);\n  height: var(--jp-private-launcher-card-size);\n  margin: 8px;\n  padding: 0px;\n  border: 1px solid var(--jp-border-color1);\n  background: var(--jp-layout-color1);\n  box-shadow: var(--jp-elevation-z2);\n  transition: 0.2s box-shadow;\n  border-radius: var(--jp-border-radius);\n}\n\n.jp-LauncherCard:hover {\n  box-shadow: var(--jp-elevation-z6);\n}\n\n.jp-LauncherCard-icon {\n  width: 100%;\n  height: var(--jp-private-launcher-card-icon-height);\n  box-sizing: border-box;\n  margin: 0px;\n  padding: 0px;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n}\n\n.jp-LauncherCard-noKernelIcon {\n  font-weight: normal;\n  font-size: var(--jp-private-launcher-large-icon-size);\n}\n\n.jp-LauncherCard[data-category='Notebook'] .jp-LauncherCard-noKernelIcon {\n  /* This color is copied from the notebook icon. */\n  color: #ef6c00;\n}\n\n.jp-LauncherCard[data-category='Console'] .jp-LauncherCard-noKernelIcon {\n  /* This color is copied from the console icon. */\n  color: #0288d1;\n}\n\n.jp-LauncherCard-label {\n  width: 100%;\n  height: var(--jp-private-launcher-card-label-height);\n  line-height: var(--jp-private-launcher-card-label-height);\n  font-size: var(--jp-ui-font-size1);\n  padding: 0 8px;\n  color: var(--jp-ui-font-color1);\n  box-sizing: border-box;\n  overflow: hidden;\n  white-space: nowrap;\n  text-overflow: ellipsis;\n  text-align: center;\n}\n\n/* Icons, kernel icons */\n\n.jp-Launcher-icon {\n  margin: 0px;\n  padding: 0px;\n  height: var(--jp-private-launcher-large-icon-size);\n  width: var(--jp-private-launcher-large-icon-size);\n  background-size: var(--jp-private-launcher-large-icon-size)\n    var(--jp-private-launcher-large-icon-size);\n  background-repeat: no-repeat;\n}\n\n.jp-Launcher-kernelIcon {\n  width: var(--jp-private-launcher-large-icon-size);\n  height: var(--jp-private-launcher-large-icon-size);\n  margin: 0px;\n  padding: 0px;\n}\n", ""]);

// exports


/***/ }),

/***/ "nFlj":
/*!**********************************************!*\
  !*** ./node_modules/querystringify/index.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var has = Object.prototype.hasOwnProperty
  , undef;

/**
 * Decode a URI encoded string.
 *
 * @param {String} input The URI encoded string.
 * @returns {String|Null} The decoded string.
 * @api private
 */
function decode(input) {
  try {
    return decodeURIComponent(input.replace(/\+/g, ' '));
  } catch (e) {
    return null;
  }
}

/**
 * Attempts to encode a given input.
 *
 * @param {String} input The string that needs to be encoded.
 * @returns {String|Null} The encoded string.
 * @api private
 */
function encode(input) {
  try {
    return encodeURIComponent(input);
  } catch (e) {
    return null;
  }
}

/**
 * Simple query string parser.
 *
 * @param {String} query The query string that needs to be parsed.
 * @returns {Object}
 * @api public
 */
function querystring(query) {
  var parser = /([^=?&]+)=?([^&]*)/g
    , result = {}
    , part;

  while (part = parser.exec(query)) {
    var key = decode(part[1])
      , value = decode(part[2]);

    //
    // Prevent overriding of existing properties. This ensures that build-in
    // methods like `toString` or __proto__ are not overriden by malicious
    // querystrings.
    //
    // In the case if failed decoding, we want to omit the key/value pairs
    // from the result.
    //
    if (key === null || value === null || key in result) continue;
    result[key] = value;
  }

  return result;
}

/**
 * Transform a query string to an object.
 *
 * @param {Object} obj Object that should be transformed.
 * @param {String} prefix Optional prefix.
 * @returns {String}
 * @api public
 */
function querystringify(obj, prefix) {
  prefix = prefix || '';

  var pairs = []
    , value
    , key;

  //
  // Optionally prefix with a '?' if needed
  //
  if ('string' !== typeof prefix) prefix = '?';

  for (key in obj) {
    if (has.call(obj, key)) {
      value = obj[key];

      //
      // Edge cases where we actually want to encode the value to an empty
      // string instead of the stringified value.
      //
      if (!value && (value === null || value === undef || isNaN(value))) {
        value = '';
      }

      key = encodeURIComponent(key);
      value = encodeURIComponent(value);

      //
      // If we failed to encode the strings, we should bail out as we don't
      // want to add invalid strings to the query.
      //
      if (key === null || value === null) continue;
      pairs.push(key +'='+ value);
    }
  }

  return pairs.length ? prefix + pairs.join('&') : '';
}

//
// Expose the module.
//
exports.stringify = querystringify;
exports.parse = querystring;


/***/ }),

/***/ "nFxz":
/*!********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/FoldEmpty.js ***!
  \********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var FoldEmpty = function (_Component) {
  _inherits(FoldEmpty, _Component);

  function FoldEmpty() {
    _classCallCheck(this, FoldEmpty);

    return _possibleConstructorReturn(this, (FoldEmpty.__proto__ || Object.getPrototypeOf(FoldEmpty)).apply(this, arguments));
  }

  _createClass(FoldEmpty, [{
    key: 'render',
    value: function render() {
      var _props = this.props,
          children = _props.children,
          Icon = _props.icon,
          messagePrimary = _props.messagePrimary,
          messageSecondary = _props.messageSecondary;


      return _react2.default.createElement(
        'div',
        { className: 'fold__content__empty' },
        Icon ? _react2.default.createElement(
          'div',
          { className: 'fold__content__empty__icon' },
          _react2.default.createElement(Icon, null)
        ) : null,
        messagePrimary ? _react2.default.createElement(
          'div',
          { className: 'fold__content__empty__message__primary' },
          messagePrimary
        ) : null,
        messageSecondary ? _react2.default.createElement(
          'div',
          { className: 'fold__content__empty__message__secondary' },
          messageSecondary
        ) : null,
        children ? children : null
      );
    }
  }]);

  return FoldEmpty;
}(_react.Component);

exports.default = FoldEmpty;


FoldEmpty.propTypes = {
  messagePrimary: _propTypes2.default.string,
  messageSecondary: _propTypes2.default.string,
  children: _propTypes2.default.node,
  icon: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func])
};
//# sourceMappingURL=FoldEmpty.js.map

/***/ }),

/***/ "nGDH":
/*!*********************************************************!*\
  !*** ./node_modules/@phosphor/datagrid/lib/datagrid.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var domutils_1 = __webpack_require__(/*! @phosphor/domutils */ "XWTc");
var dragdrop_1 = __webpack_require__(/*! @phosphor/dragdrop */ "v7cI");
var messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
var widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
var datamodel_1 = __webpack_require__(/*! ./datamodel */ "y5KU");
var graphicscontext_1 = __webpack_require__(/*! ./graphicscontext */ "8n10");
var renderermap_1 = __webpack_require__(/*! ./renderermap */ "gAjT");
var sectionlist_1 = __webpack_require__(/*! ./sectionlist */ "YmH9");
var textrenderer_1 = __webpack_require__(/*! ./textrenderer */ "XoP6");
/**
 * A widget which implements a high-performance tabular data grid.
 *
 * #### Notes
 * A data grid is implemented as a composition of child widgets. These
 * child widgets are considered an implementation detail. Manipulating
 * the child widgets of a data grid directly is undefined behavior.
 *
 * This class is not designed to be subclassed.
 */
var DataGrid = (function (_super) {
    __extends(DataGrid, _super);
    /**
     * Construct a new data grid.
     *
     * @param options - The options for initializing the data grid.
     */
    function DataGrid(options) {
        if (options === void 0) { options = {}; }
        var _this = _super.call(this) || this;
        _this._inPaint = false;
        _this._paintPending = false; // TODO: would like to get rid of this flag
        _this._pressData = null;
        _this._dpiRatio = Math.ceil(window.devicePixelRatio);
        _this._scrollX = 0;
        _this._scrollY = 0;
        _this._viewportWidth = 0;
        _this._viewportHeight = 0;
        _this._vScrollBarMinWidth = 0;
        _this._hScrollBarMinHeight = 0;
        _this._model = null;
        _this.addClass('p-DataGrid');
        // Parse the simple options.
        _this._style = options.style || DataGrid.defaultStyle;
        _this._headerVisibility = options.headerVisibility || 'all';
        _this._cellRenderers = options.cellRenderers || new renderermap_1.RendererMap();
        _this._defaultRenderer = options.defaultRenderer || new textrenderer_1.TextRenderer();
        // Connect to the renderer map changed signal
        _this._cellRenderers.changed.connect(_this._onRenderersChanged, _this);
        // Parse the base section sizes.
        var brs = 20;
        var bcs = 64;
        var brhs = 64;
        var bchs = 20;
        if (options.baseRowSize !== undefined) {
            brs = options.baseRowSize;
        }
        if (options.baseColumnSize !== undefined) {
            bcs = options.baseColumnSize;
        }
        if (options.baseRowHeaderSize !== undefined) {
            brhs = options.baseRowHeaderSize;
        }
        if (options.baseColumnHeaderSize !== undefined) {
            bchs = options.baseColumnHeaderSize;
        }
        // Set up the sections lists.
        _this._rowSections = new sectionlist_1.SectionList({ baseSize: brs });
        _this._columnSections = new sectionlist_1.SectionList({ baseSize: bcs });
        _this._rowHeaderSections = new sectionlist_1.SectionList({ baseSize: brhs });
        _this._columnHeaderSections = new sectionlist_1.SectionList({ baseSize: bchs });
        // Create the canvas and buffer objects.
        _this._canvas = Private.createCanvas();
        _this._buffer = Private.createCanvas();
        // Get the graphics contexts for the canvases.
        _this._canvasGC = _this._canvas.getContext('2d');
        _this._bufferGC = _this._buffer.getContext('2d');
        // Set up the on-screen canvas.
        _this._canvas.style.position = 'absolute';
        _this._canvas.style.top = '0px';
        _this._canvas.style.left = '0px';
        _this._canvas.style.width = '0px';
        _this._canvas.style.height = '0px';
        // Create the internal widgets for the data grid.
        // TODO - support custom scroll bars and scroll corner?
        _this._viewport = new widgets_1.Widget();
        _this._vScrollBar = new widgets_1.ScrollBar({ orientation: 'vertical' });
        _this._hScrollBar = new widgets_1.ScrollBar({ orientation: 'horizontal' });
        _this._scrollCorner = new widgets_1.Widget();
        // Add the extra class names to the child widgets.
        _this._viewport.addClass('p-DataGrid-viewport');
        _this._vScrollBar.addClass('p-DataGrid-scrollBar');
        _this._hScrollBar.addClass('p-DataGrid-scrollBar');
        _this._scrollCorner.addClass('p-DataGrid-scrollCorner');
        // Add the on-screen canvas to the viewport node.
        _this._viewport.node.appendChild(_this._canvas);
        // Install the message hook for the viewport.
        messaging_1.MessageLoop.installMessageHook(_this._viewport, _this);
        // Hide the scroll bars and corner from the outset.
        _this._vScrollBar.hide();
        _this._hScrollBar.hide();
        _this._scrollCorner.hide();
        // Connect to the scroll bar signals.
        _this._vScrollBar.thumbMoved.connect(_this._onThumbMoved, _this);
        _this._hScrollBar.thumbMoved.connect(_this._onThumbMoved, _this);
        _this._vScrollBar.pageRequested.connect(_this._onPageRequested, _this);
        _this._hScrollBar.pageRequested.connect(_this._onPageRequested, _this);
        _this._vScrollBar.stepRequested.connect(_this._onStepRequested, _this);
        _this._hScrollBar.stepRequested.connect(_this._onStepRequested, _this);
        // Set the layout cell config for the child widgets.
        widgets_1.GridLayout.setCellConfig(_this._viewport, { row: 0, column: 0 });
        widgets_1.GridLayout.setCellConfig(_this._vScrollBar, { row: 0, column: 1 });
        widgets_1.GridLayout.setCellConfig(_this._hScrollBar, { row: 1, column: 0 });
        widgets_1.GridLayout.setCellConfig(_this._scrollCorner, { row: 1, column: 1 });
        // Create the layout for the data grid.
        var layout = new widgets_1.GridLayout({
            rowCount: 2,
            columnCount: 2,
            rowSpacing: 0,
            columnSpacing: 0,
            fitPolicy: 'set-no-constraint'
        });
        // Set the stretch factors for the grid.
        layout.setRowStretch(0, 1);
        layout.setRowStretch(1, 0);
        layout.setColumnStretch(0, 1);
        layout.setColumnStretch(1, 0);
        // Add the child widgets to the layout.
        layout.addWidget(_this._viewport);
        layout.addWidget(_this._vScrollBar);
        layout.addWidget(_this._hScrollBar);
        layout.addWidget(_this._scrollCorner);
        // Install the layout on the data grid.
        _this.layout = layout;
        return _this;
    }
    /**
     * Dispose of the resources held by the widgets.
     */
    DataGrid.prototype.dispose = function () {
        this._releaseMouse();
        this._model = null;
        this._rowSections.clear();
        this._columnSections.clear();
        this._rowHeaderSections.clear();
        this._columnHeaderSections.clear();
        _super.prototype.dispose.call(this);
    };
    Object.defineProperty(DataGrid.prototype, "model", {
        /**
         * Get the data model for the data grid.
         */
        get: function () {
            return this._model;
        },
        /**
         * Set the data model for the data grid.
         */
        set: function (value) {
            // Do nothing if the model does not change.
            if (this._model === value) {
                return;
            }
            // Disconnect the change handler from the old model.
            if (this._model) {
                this._model.changed.disconnect(this._onModelChanged, this);
            }
            // Connect the change handler for the new model.
            if (value) {
                value.changed.connect(this._onModelChanged, this);
            }
            // Update the internal model reference.
            this._model = value;
            // Clear the section lists.
            this._rowSections.clear();
            this._columnSections.clear();
            this._rowHeaderSections.clear();
            this._columnHeaderSections.clear();
            // Populate the section lists.
            if (value) {
                this._rowSections.insertSections(0, value.rowCount('body'));
                this._columnSections.insertSections(0, value.columnCount('body'));
                this._rowHeaderSections.insertSections(0, value.columnCount('row-header'));
                this._columnHeaderSections.insertSections(0, value.rowCount('column-header'));
            }
            // Reset the scroll position.
            this._scrollX = 0;
            this._scrollY = 0;
            // Sync the viewport.
            this._syncViewport();
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DataGrid.prototype, "style", {
        /**
         * Get the style for the data grid.
         */
        get: function () {
            return this._style;
        },
        /**
         * Set the style for the data grid.
         */
        set: function (value) {
            // Bail if the style does not change.
            if (this._style === value) {
                return;
            }
            // Update the internal style.
            this._style = value;
            // Schedule a full repaint of the grid.
            this.repaint();
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DataGrid.prototype, "cellRenderers", {
        /**
         * Get the cell renderer map for the data grid.
         */
        get: function () {
            return this._cellRenderers;
        },
        /**
         * Set the cell renderer map for the data grid.
         */
        set: function (value) {
            // Bail if the renderer map does not change.
            if (this._cellRenderers === value) {
                return;
            }
            // Disconnect the old map.
            this._cellRenderers.changed.disconnect(this._onRenderersChanged, this);
            // Connect the new map.
            value.changed.connect(this._onRenderersChanged, this);
            // Update the internal renderer map.
            this._cellRenderers = value;
            // Schedule a full repaint of the grid.
            this.repaint();
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DataGrid.prototype, "defaultRenderer", {
        /**
         * Get the default cell renderer for the data grid.
         */
        get: function () {
            return this._defaultRenderer;
        },
        /**
         * Set the default cell renderer for the data grid.
         */
        set: function (value) {
            // Bail if the renderer does not change.
            if (this._defaultRenderer === value) {
                return;
            }
            // Update the internal renderer.
            this._defaultRenderer = value;
            // Schedule a full repaint of the grid.
            this.repaint();
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DataGrid.prototype, "headerVisibility", {
        /**
         * Get the header visibility for the data grid.
         */
        get: function () {
            return this._headerVisibility;
        },
        /**
         * Set the header visibility for the data grid.
         */
        set: function (value) {
            // Bail if the visibility does not change.
            if (this._headerVisibility === value) {
                return;
            }
            // Update the internal visibility.
            this._headerVisibility = value;
            // Sync the viewport.
            this._syncViewport();
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DataGrid.prototype, "scrollX", {
        /**
         * The scroll X offset of the viewport.
         */
        get: function () {
            return this._scrollX;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DataGrid.prototype, "scrollY", {
        /**
         * The scroll Y offset of the viewport.
         */
        get: function () {
            return this._scrollY;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DataGrid.prototype, "maxScrollX", {
        /**
         * The maximum scroll X position for the current grid dimensions.
         *
         * #### Notes
         * This value is `1px` less than the theoretical maximum to allow the
         * the right-most grid line to be clipped when the vertical scroll bar
         * is visible.
         */
        get: function () {
            return Math.max(0, this.bodyWidth - this.pageWidth - 1);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DataGrid.prototype, "maxScrollY", {
        /**
         * The maximum scroll Y position for the current grid dimensions.
         *
         * #### Notes
         * This value is `1px` less than the theoretical maximum to allow the
         * the bottom-most grid line to be clipped when the horizontal scroll
         * bar is visible.
         */
        get: function () {
            return Math.max(0, this.bodyHeight - this.pageHeight - 1);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DataGrid.prototype, "bodyWidth", {
        /**
         * The virtual width of the grid body.
         *
         * #### Notes
         * This value does not include the width of the row headers.
         */
        get: function () {
            return this._columnSections.totalSize;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DataGrid.prototype, "bodyHeight", {
        /**
         * The virtual height of the grid body.
         *
         * #### Notes
         * This value does not include the height of the column headers.
         */
        get: function () {
            return this._rowSections.totalSize;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DataGrid.prototype, "headerWidth", {
        /**
         * The virtual width of the row headers.
         *
         * #### Notes
         * This will be `0` if the row headers are hidden.
         */
        get: function () {
            if (this._headerVisibility === 'none') {
                return 0;
            }
            if (this._headerVisibility === 'column') {
                return 0;
            }
            return this._rowHeaderSections.totalSize;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DataGrid.prototype, "headerHeight", {
        /**
         * The virtual height of the column headers.
         *
         * #### Notes
         * This will be `0` if the column headers are hidden.
         */
        get: function () {
            if (this._headerVisibility === 'none') {
                return 0;
            }
            if (this._headerVisibility === 'row') {
                return 0;
            }
            return this._columnHeaderSections.totalSize;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DataGrid.prototype, "totalWidth", {
        /**
         * The total virtual width of the grid.
         *
         * #### Notes
         * If the grid widget is sized larger than this width, a horizontal
         * scroll bar will not be shown.
         */
        get: function () {
            return this.headerWidth + this.bodyWidth;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DataGrid.prototype, "totalHeight", {
        /**
         * The total virtual height of the grid.
         *
         * #### Notes
         * If the grid widget is sized larger than this height, a vertical
         * scroll bar will not be shown.
         */
        get: function () {
            return this.headerHeight + this.bodyHeight;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DataGrid.prototype, "viewportWidth", {
        /**
         * The width of the visible portion of the data grid.
         *
         * #### Notes
         * This value does not include the width of the scroll bar.
         */
        get: function () {
            return this._viewportWidth;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DataGrid.prototype, "viewportHeight", {
        /**
         * The height of the visible portion of the data grid.
         *
         * #### Notes
         * This value does not include the height of the scroll bar.
         */
        get: function () {
            return this._viewportHeight;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DataGrid.prototype, "pageWidth", {
        /**
         * The width of the visible portion of the body cells.
         *
         * #### Notes
         * This value does not include the width of the row headers.
         */
        get: function () {
            return Math.max(0, this._viewportWidth - this.headerWidth);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DataGrid.prototype, "pageHeight", {
        /**
         * The height of the visible portion of the body cells.
         *
         * #### Notes
         * This value does not include the height of the column headers.
         */
        get: function () {
            return Math.max(0, this._viewportHeight - this.headerHeight);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DataGrid.prototype, "baseRowSize", {
        /**
         * Get the base size of the body rows.
         *
         * #### Notes
         * This is the size of rows which have not been resized.
         */
        get: function () {
            return this._rowSections.baseSize;
        },
        /**
         * Set the base size of the body rows.
         *
         * #### Notes
         * This is the size of rows which have not been resized.
         */
        set: function (value) {
            this._setBaseSize(this._rowSections, value);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DataGrid.prototype, "baseColumnSize", {
        /**
         * Get the base size of the body columns.
         *
         * #### Notes
         * This is the size of columns which have not been resized.
         */
        get: function () {
            return this._columnSections.baseSize;
        },
        /**
         * Set the base size of the body columns.
         *
         * #### Notes
         * This is the size of columns which have not been resized.
         */
        set: function (value) {
            this._setBaseSize(this._columnSections, value);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DataGrid.prototype, "baseRowHeaderSize", {
        /**
         * Get the base size of the row headers.
         *
         * #### Notes
         * This is the size of row headers which have not been resized.
         */
        get: function () {
            return this._rowHeaderSections.baseSize;
        },
        /**
         * Set the base size of the row headers.
         *
         * #### Notes
         * This is the size of row headers which have not been resized.
         */
        set: function (value) {
            this._setBaseSize(this._rowHeaderSections, value);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DataGrid.prototype, "baseColumnHeaderSize", {
        /**
         * Get the base size of the column headers.
         *
         * #### Notes
         * This is the size of column headers which have not been resized.
         */
        get: function () {
            return this._columnHeaderSections.baseSize;
        },
        /**
         * Set the base size of the column headers.
         *
         * #### Notes
         * This is the size of column headers which have not been resized.
         */
        set: function (value) {
            this._setBaseSize(this._columnHeaderSections, value);
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Get the size of a section in the data grid.
     *
     * @param area - The grid area for the section of interest.
     *
     * @param index - The index of the section of interest.
     *
     * @return The size of the section, or `-1` if `index` is invalid.
     */
    DataGrid.prototype.sectionSize = function (area, index) {
        return this._getSectionList(area).sectionSize(index);
    };
    /**
     * Resize a section in the data grid.
     *
     * @param area - The grid area for the section of interest.
     *
     * @param index - The index of the section of interest.
     *
     * @param size - The new size for the section.
     *
     * #### Notes
     * This is a no-op if `index` is invalid.
     */
    DataGrid.prototype.resizeSection = function (area, index, size) {
        this._resizeSection(this._getSectionList(area), index, size);
    };
    /**
     * Reset sections in the data grid to their base size.
     *
     * @param area - The grid area for the sections of interest.
     */
    DataGrid.prototype.resetSections = function (area) {
        this._getSectionList(area).reset();
        this._syncViewport();
    };
    /**
     * Scroll the viewport by one page.
     *
     * @param - The desired direction of the scroll.
     */
    DataGrid.prototype.scrollByPage = function (dir) {
        var dx = 0;
        var dy = 0;
        switch (dir) {
            case 'up':
                dy = -this.pageHeight;
                break;
            case 'down':
                dy = this.pageHeight;
                break;
            case 'left':
                dx = -this.pageWidth;
                break;
            case 'right':
                dx = this.pageWidth;
                break;
            default:
                throw 'unreachable';
        }
        this.scrollBy(dx, dy);
    };
    /**
     * Scroll the viewport by one cell-aligned step.
     *
     * @param - The desired direction of the scroll.
     */
    DataGrid.prototype.scrollByStep = function (dir) {
        var r;
        var c;
        var x = this._scrollX;
        var y = this._scrollY;
        var rows = this._rowSections;
        var columns = this._columnSections;
        switch (dir) {
            case 'up':
                r = rows.sectionIndex(y - 1);
                y = r < 0 ? y : rows.sectionOffset(r);
                break;
            case 'down':
                r = rows.sectionIndex(y);
                y = r < 0 ? y : rows.sectionOffset(r) + rows.sectionSize(r);
                break;
            case 'left':
                c = columns.sectionIndex(x - 1);
                x = c < 0 ? x : columns.sectionOffset(c);
                break;
            case 'right':
                c = columns.sectionIndex(x);
                x = c < 0 ? x : columns.sectionOffset(c) + columns.sectionSize(c);
                break;
            default:
                throw 'unreachable';
        }
        this.scrollTo(x, y);
    };
    /**
     * Scroll the viewport by the specified delta.
     *
     * @param dx - The scroll X delta, in pixels.
     *
     * @param dy - The scroll Y delta, in pixels.
     */
    DataGrid.prototype.scrollBy = function (dx, dy) {
        this.scrollTo(this._scrollX + dx, this._scrollY + dy);
    };
    /**
     * Scroll to the specified offset position.
     *
     * @param x - The scroll X offset, in pixels.
     *
     * @param y - The scroll Y offset, in pixels.
     *
     * #### Notes
     * The scroll position will be clamped to the allowable range.
     *
     * Fractional values will be rounded to the nearest integer.
     */
    DataGrid.prototype.scrollTo = function (x, y) {
        // Floor and clamp the position to the allowable range.
        x = Math.max(0, Math.min(Math.floor(x), this.maxScrollX));
        y = Math.max(0, Math.min(Math.floor(y), this.maxScrollY));
        // Always synchronize the scroll bar values.
        this._hScrollBar.value = x;
        this._vScrollBar.value = y;
        // Compute the delta scroll amount.
        var dx = x - this._scrollX;
        var dy = y - this._scrollY;
        // Bail early if there is no effective scroll.
        if (dx === 0 && dy === 0) {
            return;
        }
        // If there is a paint pending, ensure it paints everything.
        if (this._paintPending) {
            this._scrollX = x;
            this._scrollY = y;
            this.repaint();
            return;
        }
        // Bail early if the viewport is not visible.
        if (!this._viewport.isVisible) {
            this._scrollX = x;
            this._scrollY = y;
            return;
        }
        // Get the current size of the viewport.
        var width = this._viewportWidth;
        var height = this._viewportHeight;
        // Bail early if the viewport is empty.
        if (width === 0 || height === 0) {
            this._scrollX = x;
            this._scrollY = y;
            return;
        }
        // Get the visible content origin.
        var contentX = this.headerWidth;
        var contentY = this.headerHeight;
        // Get the visible content dimensions.
        var contentWidth = width - contentX;
        var contentHeight = height - contentY;
        // Bail early if there is no content to draw.
        if (contentWidth <= 0 && contentHeight <= 0) {
            this._scrollX = x;
            this._scrollY = y;
            return;
        }
        // Compute the area which needs painting for the `dx` scroll.
        var dxArea = 0;
        if (dx !== 0 && contentWidth > 0) {
            if (Math.abs(dx) >= contentWidth) {
                dxArea = contentWidth * height;
            }
            else {
                dxArea = Math.abs(dx) * height;
            }
        }
        // Compute the area which needs painting for the `dy` scroll.
        var dyArea = 0;
        if (dy !== 0 && contentHeight > 0) {
            if (Math.abs(dy) >= contentHeight) {
                dyArea = width * contentHeight;
            }
            else {
                dyArea = width * Math.abs(dy);
            }
        }
        // If the area sum is larger than the total, paint everything.
        if ((dxArea + dyArea) >= (width * height)) {
            this._scrollX = x;
            this._scrollY = y;
            this._paint(0, 0, width, height);
            return;
        }
        // Update the internal Y scroll position.
        this._scrollY = y;
        // Scroll the Y axis if needed. If the scroll distance exceeds
        // the visible height, paint everything. Otherwise, blit the
        // valid content and paint the dirty region.
        if (dy !== 0 && contentHeight > 0) {
            if (Math.abs(dy) >= contentHeight) {
                this._paint(0, contentY, width, contentHeight);
            }
            else {
                var x_1 = 0;
                var y_1 = dy < 0 ? contentY : contentY + dy;
                var w = width;
                var h = contentHeight - Math.abs(dy);
                this._blit(this._canvas, x_1, y_1, w, h, x_1, y_1 - dy);
                this._paint(0, dy < 0 ? contentY : height - dy, width, Math.abs(dy));
            }
        }
        // Update the internal X scroll position.
        this._scrollX = x;
        // Scroll the X axis if needed. If the scroll distance exceeds
        // the visible width, paint everything. Otherwise, blit the
        // valid content and paint the dirty region.
        if (dx !== 0 && contentWidth > 0) {
            if (Math.abs(dx) >= contentWidth) {
                this._paint(contentX, 0, contentWidth, height);
            }
            else {
                var x_2 = dx < 0 ? contentX : contentX + dx;
                var y_2 = 0;
                var w = contentWidth - Math.abs(dx);
                var h = height;
                this._blit(this._canvas, x_2, y_2, w, h, x_2 - dx, y_2);
                this._paint(dx < 0 ? contentX : width - dx, 0, Math.abs(dx), height);
            }
        }
    };
    DataGrid.prototype.repaint = function () {
        // Parse the arguments.
        var x;
        var y;
        var w;
        var h;
        switch (arguments.length) {
            case 0:
                x = 0;
                y = 0;
                w = this._viewportWidth;
                h = this._viewportHeight;
                break;
            case 4:
                x = Math.floor(arguments[0]);
                y = Math.floor(arguments[1]);
                w = Math.floor(arguments[2]);
                h = Math.floor(arguments[3]);
                break;
            default:
                throw 'unreachable';
        }
        // Bail early if there is nothing to paint.
        if (w <= 0 || h <= 0) {
            return;
        }
        // Set the paint pending flag.
        this._paintPending = true;
        // Create the paint request message.
        var msg = new Private.PaintRequest(x, y, x + w - 1, y + h - 1);
        // Post the paint request to the viewport.
        messaging_1.MessageLoop.postMessage(this._viewport, msg);
    };
    /**
     * Process a message sent to the widget.
     *
     * @param msg - The message sent to the widget.
     */
    DataGrid.prototype.processMessage = function (msg) {
        // Ignore child show/hide messages. The data grid controls the
        // visibility of its children, and will manually dispatch the
        // fit-request messages as a result of visibility change.
        if (msg.type === 'child-shown' || msg.type === 'child-hidden') {
            return;
        }
        // Recompute the scroll bar minimums before the layout refits.
        if (msg.type === 'fit-request') {
            var vsbLimits = domutils_1.ElementExt.sizeLimits(this._vScrollBar.node);
            var hsbLimits = domutils_1.ElementExt.sizeLimits(this._hScrollBar.node);
            this._vScrollBarMinWidth = vsbLimits.minWidth;
            this._hScrollBarMinHeight = hsbLimits.minHeight;
        }
        // Process all other messages as normal.
        _super.prototype.processMessage.call(this, msg);
    };
    /**
     * Intercept a message sent to a message handler.
     *
     * @param handler - The target handler of the message.
     *
     * @param msg - The message to be sent to the handler.
     *
     * @returns `true` if the message should continue to be processed
     *   as normal, or `false` if processing should cease immediately.
     */
    DataGrid.prototype.messageHook = function (handler, msg) {
        if (handler === this._viewport) {
            this._processViewportMessage(msg);
        }
        return true;
    };
    /**
     * Handle the DOM events for the data grid.
     *
     * @param event - The DOM event sent to the data grid.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the data grid's DOM node. It
     * should not be called directly by user code.
     */
    DataGrid.prototype.handleEvent = function (event) {
        switch (event.type) {
            case 'mousedown':
                this._evtMouseDown(event);
                break;
            case 'mousemove':
                this._evtMouseMove(event);
                break;
            case 'mouseup':
                this._evtMouseUp(event);
                break;
            case 'wheel':
                this._evtWheel(event);
                break;
            case 'keydown':
                this._evtKeyDown(event);
                break;
            case 'contextmenu':
                event.preventDefault();
                event.stopPropagation();
                break;
            case 'resize':
                this._refreshDPI();
                break;
        }
    };
    /**
     * A message handler invoked on a `'before-attach'` message.
     */
    DataGrid.prototype.onBeforeAttach = function (msg) {
        window.addEventListener('resize', this);
        this.node.addEventListener('wheel', this);
        this.node.addEventListener('mousedown', this);
        this._viewport.node.addEventListener('mousemove', this);
        this.repaint(); // TODO actually need to fit the viewport ?
    };
    /**
     * A message handler invoked on an `'after-detach'` message.
     */
    DataGrid.prototype.onAfterDetach = function (msg) {
        window.removeEventListener('resize', this);
        this.node.removeEventListener('wheel', this);
        this.node.removeEventListener('mousedown', this);
        this._viewport.node.removeEventListener('mousemove', this);
        this._releaseMouse();
    };
    /**
     * A message handler invoked on a `'before-show'` message.
     */
    DataGrid.prototype.onBeforeShow = function (msg) {
        this.repaint(); // TODO actually need to fit the viewport ?
    };
    /**
     * A message handler invoked on a `'resize'` message.
     */
    DataGrid.prototype.onResize = function (msg) {
        this._syncScrollState();
    };
    /**
     * Refresh the internal dpi ratio.
     *
     * This will update the canvas size and schedule a repaint if needed.
     */
    DataGrid.prototype._refreshDPI = function () {
        // Get the best integral value for the dpi ratio.
        var dpiRatio = Math.ceil(window.devicePixelRatio);
        // Bail early if the computed dpi ratio has not changed.
        if (this._dpiRatio === dpiRatio) {
            return;
        }
        // Update the internal dpi ratio.
        this._dpiRatio = dpiRatio;
        // Schedule a full repaint of the grid.
        this.repaint();
        // Update the canvas size for the new dpi ratio.
        this._resizeCanvasIfNeeded(this._viewportWidth, this._viewportHeight);
        // Ensure the canvas style is scaled for the new ratio.
        this._canvas.style.width = this._canvas.width / this._dpiRatio + "px";
        this._canvas.style.height = this._canvas.height / this._dpiRatio + "px";
    };
    /**
     * Ensure the canvas is at least the specified size.
     *
     * This method will retain the valid canvas content.
     */
    DataGrid.prototype._resizeCanvasIfNeeded = function (width, height) {
        // Scale the size by the dpi ratio.
        width = width * this._dpiRatio;
        height = height * this._dpiRatio;
        // Compute the maximum canvas size for the given width.
        var maxW = (Math.ceil((width + 1) / 512) + 1) * 512;
        var maxH = (Math.ceil((height + 1) / 512) + 1) * 512;
        // Get the current size of the canvas.
        var curW = this._canvas.width;
        var curH = this._canvas.height;
        // Bail early if the canvas size is within bounds.
        if (curW >= width && curH >= height && curW <= maxW && curH <= maxH) {
            return;
        }
        // Compute the expanded canvas size.
        var expW = maxW - 512;
        var expH = maxH - 512;
        // Set the transforms to the identity matrix.
        this._canvasGC.setTransform(1, 0, 0, 1, 0, 0);
        this._bufferGC.setTransform(1, 0, 0, 1, 0, 0);
        // Resize the buffer width if needed.
        if (curW < width) {
            this._buffer.width = expW;
        }
        else if (curW > maxW) {
            this._buffer.width = maxW;
        }
        // Resize the buffer height if needed.
        if (curH < height) {
            this._buffer.height = expH;
        }
        else if (curH > maxH) {
            this._buffer.height = maxH;
        }
        // Test whether there is content to blit.
        var needBlit = curH > 0 && curH > 0 && width > 0 && height > 0;
        // Copy the valid content into the buffer if needed.
        if (needBlit) {
            this._bufferGC.drawImage(this._canvas, 0, 0);
        }
        // Resize the canvas width if needed.
        if (curW < width) {
            this._canvas.width = expW;
            this._canvas.style.width = expW / this._dpiRatio + "px";
        }
        else if (curW > maxW) {
            this._canvas.width = maxW;
            this._canvas.style.width = maxW / this._dpiRatio + "px";
        }
        // Resize the canvas height if needed.
        if (curH < height) {
            this._canvas.height = expH;
            this._canvas.style.height = expH / this._dpiRatio + "px";
        }
        else if (curH > maxH) {
            this._canvas.height = maxH;
            this._canvas.style.height = maxH / this._dpiRatio + "px";
        }
        // Copy the valid content from the buffer if needed.
        if (needBlit) {
            this._canvasGC.drawImage(this._buffer, 0, 0);
        }
    };
    /**
     * Sync the scroll bars and scroll state with the viewport.
     *
     * #### Notes
     * If the visibility of either scroll bar changes, a synchronous
     * fit-request will be dispatched to the data grid to immediately
     * resize the viewport.
     */
    DataGrid.prototype._syncScrollState = function () {
        // Fetch the viewport dimensions.
        var bw = this.bodyWidth;
        var bh = this.bodyHeight;
        var pw = this.pageWidth;
        var ph = this.pageHeight;
        // Get the current scroll bar visibility.
        var hasVScroll = !this._vScrollBar.isHidden;
        var hasHScroll = !this._hScrollBar.isHidden;
        // Get the minimum sizes of the scroll bars.
        var vsw = this._vScrollBarMinWidth;
        var hsh = this._hScrollBarMinHeight;
        // Get the page size as if no scroll bars are visible.
        var apw = pw + (hasVScroll ? vsw : 0);
        var aph = ph + (hasHScroll ? hsh : 0);
        // Test whether scroll bars are needed for the adjusted size.
        var needVScroll = aph < bh - 1;
        var needHScroll = apw < bw - 1;
        // Re-test the horizontal scroll if a vertical scroll is needed.
        if (needVScroll && !needHScroll) {
            needHScroll = (apw - vsw) < bw - 1;
        }
        // Re-test the vertical scroll if a horizontal scroll is needed.
        if (needHScroll && !needVScroll) {
            needVScroll = (aph - hsh) < bh - 1;
        }
        // If the visibility changes, immediately refit the grid.
        if (needVScroll !== hasVScroll || needHScroll !== hasHScroll) {
            this._vScrollBar.setHidden(!needVScroll);
            this._hScrollBar.setHidden(!needHScroll);
            this._scrollCorner.setHidden(!needVScroll || !needHScroll);
            messaging_1.MessageLoop.sendMessage(this, widgets_1.Widget.Msg.FitRequest);
        }
        // Update the scroll bar limits.
        this._vScrollBar.maximum = this.maxScrollY;
        this._vScrollBar.page = this.pageHeight;
        this._hScrollBar.maximum = this.maxScrollX;
        this._hScrollBar.page = this.pageWidth;
        // Re-clamp the scroll position.
        this.scrollTo(this._scrollX, this._scrollY);
    };
    /**
     * Sync the viewport to the given scroll position.
     *
     * #### Notes
     * This schedules a full repaint and syncs the scroll state.
     */
    DataGrid.prototype._syncViewport = function () {
        // Schedule a full repaint of the viewport.
        this.repaint();
        // Sync the scroll state after requesting the repaint.
        this._syncScrollState();
    };
    /**
     * Get the section list for the specified grid area.
     */
    DataGrid.prototype._getSectionList = function (area) {
        var list;
        switch (area) {
            case 'row':
                list = this._rowSections;
                break;
            case 'column':
                list = this._columnSections;
                break;
            case 'row-header':
                list = this._rowHeaderSections;
                break;
            case 'column-header':
                list = this._columnHeaderSections;
                break;
            default:
                throw 'unreachable';
        }
        return list;
    };
    /**
     * Set the base size for the given section list.
     *
     * #### Notes
     * This will update the scroll bars and repaint as needed.
     */
    DataGrid.prototype._setBaseSize = function (list, size) {
        // Normalize the size.
        size = Math.max(0, Math.floor(size));
        // Bail early if the size does not change.
        if (list.baseSize === size) {
            return;
        }
        // Update the list base size.
        list.baseSize = size;
        // Sync the viewport
        this._syncViewport();
    };
    /**
     * Resize a section in the given section list.
     *
     * #### Notes
     * This will update the scroll bars and repaint as needed.
     */
    DataGrid.prototype._resizeSection = function (list, index, size) {
        // Bail early if the index is out of range.
        if (index < 0 || index >= list.sectionCount) {
            return;
        }
        // Look up the old size of the section.
        var oldSize = list.sectionSize(index);
        // Normalize the new size of the section.
        var newSize = Math.max(0, Math.floor(size));
        // Bail early if the size does not change.
        if (oldSize === newSize) {
            return;
        }
        // Resize the section in the list.
        list.resizeSection(index, newSize);
        // Get the current size of the viewport.
        var vpWidth = this._viewportWidth;
        var vpHeight = this._viewportHeight;
        // If there is nothing to paint, sync the scroll state.
        if (!this._viewport.isVisible || vpWidth === 0 || vpHeight === 0) {
            this._syncScrollState();
            return;
        }
        // If a paint is already pending, sync the viewport.
        if (this._paintPending) {
            this._syncViewport();
            return;
        }
        // Compute the size delta.
        var delta = newSize - oldSize;
        // Paint the relevant dirty regions.
        switch (list) {
            case this._rowSections:
                {
                    // Look up the column header height.
                    var hh = this.headerHeight;
                    // Compute the viewport offset of the section.
                    var offset = list.sectionOffset(index) + hh - this._scrollY;
                    // Bail early if there is nothing to paint.
                    if (hh >= vpHeight || offset > vpHeight) {
                        break;
                    }
                    // Update the scroll position if the section is not visible.
                    if (offset + oldSize <= hh) {
                        this._scrollY += delta;
                        break;
                    }
                    // Compute the paint origin of the section.
                    var pos = Math.max(hh, offset);
                    // Paint from the section onward if it spans the viewport.
                    if (offset + oldSize >= vpHeight || offset + newSize >= vpHeight) {
                        this._paint(0, pos, vpWidth, vpHeight - pos);
                        break;
                    }
                    // Compute the X blit dimensions.
                    var sx = 0;
                    var sw = vpWidth;
                    var dx = 0;
                    // Compute the Y blit dimensions.
                    var sy = void 0;
                    var sh = void 0;
                    var dy = void 0;
                    if (offset + newSize <= hh) {
                        sy = hh - delta;
                        sh = vpHeight - sy;
                        dy = hh;
                    }
                    else {
                        sy = offset + oldSize;
                        sh = vpHeight - sy;
                        dy = sy + delta;
                    }
                    // Blit the valid content to the destination.
                    this._blit(this._canvas, sx, sy, sw, sh, dx, dy);
                    // Repaint the section if needed.
                    if (newSize > 0 && offset + newSize > hh) {
                        this._paint(0, pos, vpWidth, offset + newSize - pos);
                    }
                    // Paint the trailing space if needed.
                    if (delta < 0) {
                        this._paint(0, vpHeight + delta, vpWidth, -delta);
                    }
                    // Done.
                    break;
                }
            case this._columnSections:
                {
                    // Look up the row header width.
                    var hw = this.headerWidth;
                    // Compute the viewport offset of the section.
                    var offset = list.sectionOffset(index) + hw - this._scrollX;
                    // Bail early if there is nothing to paint.
                    if (hw >= vpWidth || offset > vpWidth) {
                        break;
                    }
                    // Update the scroll position if the section is not visible.
                    if (offset + oldSize <= hw) {
                        this._scrollX += delta;
                        break;
                    }
                    // Compute the paint origin of the section.
                    var pos = Math.max(hw, offset);
                    // Paint from the section onward if it spans the viewport.
                    if (offset + oldSize >= vpWidth || offset + newSize >= vpWidth) {
                        this._paint(pos, 0, vpWidth - pos, vpHeight);
                        break;
                    }
                    // Compute the Y blit dimensions.
                    var sy = 0;
                    var sh = vpHeight;
                    var dy = 0;
                    // Compute the X blit dimensions.
                    var sx = void 0;
                    var sw = void 0;
                    var dx = void 0;
                    if (offset + newSize <= hw) {
                        sx = hw - delta;
                        sw = vpWidth - sx;
                        dx = hw;
                    }
                    else {
                        sx = offset + oldSize;
                        sw = vpWidth - sx;
                        dx = sx + delta;
                    }
                    // Blit the valid content to the destination.
                    this._blit(this._canvas, sx, sy, sw, sh, dx, dy);
                    // Repaint the section if needed.
                    if (newSize > 0 && offset + newSize > hw) {
                        this._paint(pos, 0, offset + newSize - pos, vpHeight);
                    }
                    // Paint the trailing space if needed.
                    if (delta < 0) {
                        this._paint(vpWidth + delta, 0, -delta, vpHeight);
                    }
                    // Done.
                    break;
                }
            case this._rowHeaderSections:
                {
                    // Look up the offset of the section.
                    var offset = list.sectionOffset(index);
                    // Bail early if the section is fully outside the viewport.
                    if (offset >= vpWidth) {
                        break;
                    }
                    // Paint the entire tail if the section spans the viewport.
                    if (offset + oldSize >= vpWidth || offset + newSize >= vpWidth) {
                        this._paint(offset, 0, vpWidth - offset, vpHeight);
                        break;
                    }
                    // Compute the blit content dimensions.
                    var sx = offset + oldSize;
                    var sy = 0;
                    var sw = vpWidth - sx;
                    var sh = vpHeight;
                    var dx = sx + delta;
                    var dy = 0;
                    // Blit the valid contents to the destination.
                    this._blit(this._canvas, sx, sy, sw, sh, dx, dy);
                    // Repaint the header section if needed.
                    if (newSize > 0) {
                        this._paint(offset, 0, newSize, vpHeight);
                    }
                    // Paint the trailing space if needed.
                    if (delta < 0) {
                        this._paint(vpWidth + delta, 0, -delta, vpHeight);
                    }
                    // Done
                    break;
                }
            case this._columnHeaderSections:
                {
                    // Look up the offset of the section.
                    var offset = list.sectionOffset(index);
                    // Bail early if the section is fully outside the viewport.
                    if (offset >= vpHeight) {
                        break;
                    }
                    // Paint the entire tail if the section spans the viewport.
                    if (offset + oldSize >= vpHeight || offset + newSize >= vpHeight) {
                        this._paint(0, offset, vpWidth, vpHeight - offset);
                        break;
                    }
                    // Compute the blit content dimensions.
                    var sx = 0;
                    var sy = offset + oldSize;
                    var sw = vpWidth;
                    var sh = vpHeight - sy;
                    var dx = 0;
                    var dy = sy + delta;
                    // Blit the valid contents to the destination.
                    this._blit(this._canvas, sx, sy, sw, sh, dx, dy);
                    // Repaint the header section if needed.
                    if (newSize > 0) {
                        this._paint(0, offset, vpWidth, newSize);
                    }
                    // Paint the trailing space if needed.
                    if (delta < 0) {
                        this._paint(0, vpHeight + delta, vpWidth, -delta);
                    }
                    // Done
                    break;
                }
            default:
                throw 'unreachable';
        }
        // Sync the scroll state after painting.
        this._syncScrollState();
    };
    /**
     * Hit test the grid headers for a resize handle.
     */
    DataGrid.prototype._hitTestResizeHandles = function (clientX, clientY) {
        // Look up the header dimensions.
        var hw = this.headerWidth;
        var hh = this.headerHeight;
        // Convert the mouse position into local coordinates.
        var rect = this._viewport.node.getBoundingClientRect();
        var x = clientX - rect.left;
        var y = clientY - rect.top;
        // Bail early if the mouse is not over a grid header.
        if (x >= hw && y >= hh) {
            return null;
        }
        // Test for a match in the corner header first.
        if (x <= hw + 2 && y <= hh + 2) {
            // Set up the resize index data.
            var data = null;
            // Check for a column match if applicable.
            if (y <= hh) {
                data = Private.findResizeIndex(this._rowHeaderSections, x);
            }
            // Return the column match if found.
            if (data) {
                return { type: 'header-column', index: data.index, delta: data.delta };
            }
            // Check for a row match if applicable.
            if (x <= hw) {
                data = Private.findResizeIndex(this._columnHeaderSections, y);
            }
            // Return the row match if found.
            if (data) {
                return { type: 'header-row', index: data.index, delta: data.delta };
            }
            // Otherwise, there was no match.
            return null;
        }
        // Test for a match in the column header second.
        if (y <= hh) {
            // Convert the position into unscrolled coordinates.
            var pos = x + this._scrollX - hw;
            // Check for a match.
            var data = Private.findResizeIndex(this._columnSections, pos);
            // Return the column match if found.
            if (data) {
                return { type: 'body-column', index: data.index, delta: data.delta };
            }
            // Otherwise, there was no match.
            return null;
        }
        // Test for a match in the row header last.
        if (x <= hw) {
            // Convert the position into unscrolled coordinates.
            var pos = y + this._scrollY - hh;
            // Check for a match.
            var data = Private.findResizeIndex(this._rowSections, pos);
            // Return the row match if found.
            if (data) {
                return { type: 'body-row', index: data.index, delta: data.delta };
            }
            // Otherwise, there was no match.
            return null;
        }
        // Otherwise, there was no match.
        return null;
    };
    /**
     * Handle the `'keydown'` event for the data grid.
     */
    DataGrid.prototype._evtKeyDown = function (event) {
        // Stop input events during drag.
        event.preventDefault();
        event.stopPropagation();
        // Release the mouse if `Escape` is pressed.
        if (event.keyCode === 27) {
            this._releaseMouse();
        }
    };
    /**
     * Handle the `'mousedown'` event for the data grid.
     */
    DataGrid.prototype._evtMouseDown = function (event) {
        // Do nothing if the left mouse button is not pressed.
        if (event.button !== 0) {
            return;
        }
        // Extract the client position.
        var clientX = event.clientX, clientY = event.clientY;
        // Hit test the grid headers for a resize handle.
        var handle = this._hitTestResizeHandles(clientX, clientY);
        // Bail early if no resize handle is pressed.
        if (!handle) {
            return;
        }
        // Stop the event when a resize handle is pressed.
        event.preventDefault();
        event.stopPropagation();
        // Look up the cursor for the handle.
        var cursor = Private.cursorForHandle(handle);
        // Override the document cursor.
        var override = dragdrop_1.Drag.overrideCursor(cursor);
        // Set up the press data.
        this._pressData = { handle: handle, clientX: clientX, clientY: clientY, override: override };
        // Add the extra document listeners.
        document.addEventListener('mousemove', this, true);
        document.addEventListener('mouseup', this, true);
        document.addEventListener('keydown', this, true);
        document.addEventListener('contextmenu', this, true);
    };
    /**
     * Handle the `mousemove` event for the data grid.
     */
    DataGrid.prototype._evtMouseMove = function (event) {
        // If a drag is not in progress, the event is for the viewport.
        if (!this._pressData) {
            // Hit test the grid headers for a resize handle.
            var handle = this._hitTestResizeHandles(event.clientX, event.clientY);
            // Update the viewport cursor.
            this._viewport.node.style.cursor = Private.cursorForHandle(handle);
            // Done.
            return;
        }
        // Otherwise, the event is for the drag in progress.
        // Stop the event.
        event.preventDefault();
        event.stopPropagation();
        // Update the press data with the current mouse position.
        this._pressData.clientX = event.clientX;
        this._pressData.clientY = event.clientY;
        // Post a section resize request message to the viewport.
        messaging_1.MessageLoop.postMessage(this._viewport, Private.SectionResizeRequest);
    };
    /**
     * Handle the `mouseup` event for the data grid.
     */
    DataGrid.prototype._evtMouseUp = function (event) {
        // Do nothing if the left mouse button is not released.
        if (event.button !== 0) {
            return;
        }
        // Stop the event when releasing the mouse.
        event.preventDefault();
        event.stopPropagation();
        // Finalize the mouse release.
        this._releaseMouse();
    };
    /**
     * Handle the `'wheel'` event for the data grid.
     */
    DataGrid.prototype._evtWheel = function (event) {
        // Do nothing if a drag is in progress.
        if (this._pressData) {
            return;
        }
        // Do nothing if the `Ctrl` key is held.
        if (event.ctrlKey) {
            return;
        }
        // Extract the delta X and Y movement.
        var dx = event.deltaX;
        var dy = event.deltaY;
        // Convert the delta values to pixel values.
        switch (event.deltaMode) {
            case 0:
                break;
            case 1:
                dx *= this._columnSections.baseSize;
                dy *= this._rowSections.baseSize;
                break;
            case 2:
                dx *= this.pageWidth;
                dy *= this.pageHeight;
                break;
            default:
                throw 'unreachable';
        }
        // Test whether X scroll is needed.
        var needScrollX = ((dx < 0 && this.scrollX > 0) ||
            (dx > 0 && this.scrollX < this.maxScrollX));
        // Test whether Y scroll is needed.
        var needScrollY = ((dy < 0 && this.scrollY > 0) ||
            (dy > 0 && this.scrollY < this.maxScrollY));
        // Bail if no scrolling is needed.
        if (!needScrollX && !needScrollY) {
            return;
        }
        // Cancel the event if the grid is handling scrolling.
        event.preventDefault();
        event.stopPropagation();
        // Compute the desired scroll position.
        var x = Math.max(0, Math.min(this.scrollX + dx, this.maxScrollX));
        var y = Math.max(0, Math.min(this.scrollY + dy, this.maxScrollY));
        // Update the scroll bar values with the desired position.
        this._hScrollBar.value = x;
        this._vScrollBar.value = y;
        // Post a scroll request message to the viewport.
        messaging_1.MessageLoop.postMessage(this._viewport, Private.ScrollRequest);
    };
    /**
     * Release the mouse grab for the data grid.
     */
    DataGrid.prototype._releaseMouse = function () {
        // Bail early if no drag is in progress.
        if (!this._pressData) {
            return;
        }
        // Clear the press data and cursor override.
        this._pressData.override.dispose();
        this._pressData = null;
        // Remove the extra document listeners.
        document.removeEventListener('mousemove', this, true);
        document.removeEventListener('mouseup', this, true);
        document.removeEventListener('keydown', this, true);
        document.removeEventListener('contextmenu', this, true);
    };
    /**
     * Process a message sent to the viewport
     */
    DataGrid.prototype._processViewportMessage = function (msg) {
        switch (msg.type) {
            case 'scroll-request':
                this._onViewportScrollRequest(msg);
                break;
            case 'section-resize-request':
                this._onViewportSectionResizeRequest(msg);
                break;
            case 'resize':
                this._onViewportResize(msg);
                break;
            case 'paint-request':
                this._onViewportPaintRequest(msg);
                break;
            default:
                break;
        }
    };
    /**
     * A message hook invoked on a viewport `'scroll-request'` message.
     */
    DataGrid.prototype._onViewportScrollRequest = function (msg) {
        this.scrollTo(this._hScrollBar.value, this._vScrollBar.value);
    };
    /**
     * A message hook invoked on a `'section-resize-request'` message.
     */
    DataGrid.prototype._onViewportSectionResizeRequest = function (msg) {
        // Bail early if a drag is not in progress.
        if (!this._pressData) {
            return;
        }
        // Extract the relevant press data.
        var _a = this._pressData, handle = _a.handle, clientX = _a.clientX, clientY = _a.clientY;
        // Convert the client position to viewport coordinates.
        var rect = this._viewport.node.getBoundingClientRect();
        var x = clientX - rect.left;
        var y = clientY - rect.top;
        // Look up the section list and convert to section position.
        var pos;
        var list;
        switch (handle.type) {
            case 'body-row':
                pos = y + this._scrollY - this.headerHeight;
                list = this._rowSections;
                break;
            case 'body-column':
                pos = x + this._scrollX - this.headerWidth;
                list = this._columnSections;
                break;
            case 'header-row':
                pos = y;
                list = this._columnHeaderSections;
                break;
            case 'header-column':
                pos = x;
                list = this._rowHeaderSections;
                break;
            default:
                throw 'unreachable';
        }
        // Look up the offset for the handle.
        var offset = list.sectionOffset(handle.index);
        // Bail if the handle no longer exists.
        if (offset < 0) {
            return;
        }
        // Compute the new size for the section.
        var size = Math.max(4, pos - handle.delta - offset);
        // Resize the section to the computed size.
        this._resizeSection(list, handle.index, size);
    };
    /**
     * A message hook invoked on a viewport `'resize'` message.
     */
    DataGrid.prototype._onViewportResize = function (msg) {
        // Bail early if the viewport is not visible.
        if (!this._viewport.isVisible) {
            return;
        }
        // Unpack the message data.
        var width = msg.width, height = msg.height;
        // Measure the viewport node if the dimensions are unknown.
        if (width === -1) {
            width = this._viewport.node.offsetWidth;
        }
        if (height === -1) {
            height = this._viewport.node.offsetHeight;
        }
        // Round the dimensions to the nearest pixel.
        width = Math.round(width);
        height = Math.round(height);
        // Get the current size of the viewport.
        var oldWidth = this._viewportWidth;
        var oldHeight = this._viewportHeight;
        // Updated internal viewport size.
        this._viewportWidth = width;
        this._viewportHeight = height;
        // Resize the canvas if needed.
        this._resizeCanvasIfNeeded(width, height);
        // Compute the sizes of the dirty regions.
        var right = width - oldWidth;
        var bottom = height - oldHeight;
        // Bail if nothing needs to be painted.
        if (right <= 0 && bottom <= 0) {
            return;
        }
        // If there is a paint pending, ensure it paints everything.
        if (this._paintPending) {
            this.repaint();
            return;
        }
        // Paint the whole viewport if the old size was zero.
        if (oldWidth === 0 || oldHeight === 0) {
            this._paint(0, 0, width, height);
            return;
        }
        // Paint the dirty region to the right, if needed.
        if (right > 0) {
            this._paint(oldWidth, 0, right, height);
        }
        // Paint the dirty region to the bottom, if needed.
        if (bottom > 0 && width > right) {
            this._paint(0, oldHeight, width - right, bottom);
        }
    };
    /**
     * A message hook invoked on a viewport `'paint-request'` message.
     */
    DataGrid.prototype._onViewportPaintRequest = function (msg) {
        // Clear the paint pending flag.
        this._paintPending = false;
        // Bail early if the viewport is not visible.
        if (!this._viewport.isVisible) {
            return;
        }
        // Bail early if the viewport has zero area.
        if (this._viewportWidth === 0 || this._viewportHeight === 0) {
            return;
        }
        // Compute the paint bounds.
        var xMin = 0;
        var yMin = 0;
        var xMax = this._viewportWidth - 1;
        var yMax = this._viewportHeight - 1;
        // Unpack the message data.
        var x1 = msg.x1, y1 = msg.y1, x2 = msg.x2, y2 = msg.y2;
        // Bail early if the dirty rect is outside the bounds.
        if (x2 < xMin || y2 < yMin || x1 > xMax || y1 > yMax) {
            return;
        }
        // Clamp the dirty rect to the paint bounds.
        x1 = Math.max(xMin, Math.min(x1, xMax));
        y1 = Math.max(yMin, Math.min(y1, yMax));
        x2 = Math.max(xMin, Math.min(x2, xMax));
        y2 = Math.max(yMin, Math.min(y2, yMax));
        // Paint the dirty rect.
        this._paint(x1, y1, x2 - x1 + 1, y2 - y1 + 1);
    };
    /**
     * Handle the `thumbMoved` signal from a scroll bar.
     */
    DataGrid.prototype._onThumbMoved = function (sender) {
        messaging_1.MessageLoop.postMessage(this._viewport, Private.ScrollRequest);
    };
    /**
     * Handle the `pageRequested` signal from a scroll bar.
     */
    DataGrid.prototype._onPageRequested = function (sender, dir) {
        if (sender === this._vScrollBar) {
            this.scrollByPage(dir === 'decrement' ? 'up' : 'down');
        }
        else {
            this.scrollByPage(dir === 'decrement' ? 'left' : 'right');
        }
    };
    /**
     * Handle the `stepRequested` signal from a scroll bar.
     */
    DataGrid.prototype._onStepRequested = function (sender, dir) {
        if (sender === this._vScrollBar) {
            this.scrollByStep(dir === 'decrement' ? 'up' : 'down');
        }
        else {
            this.scrollByStep(dir === 'decrement' ? 'left' : 'right');
        }
    };
    /**
     * A signal handler for the data model `changed` signal.
     */
    DataGrid.prototype._onModelChanged = function (sender, args) {
        switch (args.type) {
            case 'rows-removed':
            case 'rows-inserted':
            case 'columns-removed':
            case 'columns-inserted':
                this._onSectionsChanged(args);
                break;
            case 'rows-moved':
            case 'columns-moved':
                this._onSectionsMoved(args);
                break;
            case 'cells-changed':
                this._onCellsChanged(args);
                break;
            case 'model-reset':
                this._onModelReset(args);
                break;
            default:
                throw 'unreachable';
        }
    };
    /**
     * Handle sections changing in the data model.
     */
    DataGrid.prototype._onSectionsChanged = function (args) {
        // TODO clean up this method. It's ugly.
        // Unpack the arg data.
        var region = args.region, type = args.type, index = args.index, span = args.span;
        // Bail early if there are no sections to insert.
        if (span <= 0) {
            return;
        }
        // Determine the behavior of the change type.
        var isRows = type === 'rows-inserted' || type === 'rows-removed';
        var isRemove = type === 'rows-removed' || type === 'columns-removed';
        // Look up the relevant section list.
        var list;
        if (region === 'body') {
            list = isRows ? this._rowSections : this._columnSections;
        }
        else {
            list = isRows ? this._columnHeaderSections : this._rowHeaderSections;
        }
        // Bail if the index is out of range.
        if (isRemove && (index < 0 || index >= list.sectionCount)) {
            return;
        }
        // Compute the paint offset and handle region-specific behavior.
        var offset;
        if (region !== 'body') {
            // Compute the paint offset.
            if (index >= list.sectionCount) {
                offset = list.totalSize;
            }
            else {
                offset = list.sectionOffset(index);
            }
            // Remove or insert the sections as needed.
            if (isRemove) {
                list.removeSections(index, span);
            }
            else {
                list.insertSections(index, span);
            }
        }
        else {
            // Look up the initial scroll geometry.
            var scrollPos1 = void 0;
            var maxScrollPos1 = void 0;
            if (isRows) {
                scrollPos1 = this._scrollY;
                maxScrollPos1 = this.maxScrollY;
            }
            else {
                scrollPos1 = this._scrollX;
                maxScrollPos1 = this.maxScrollX;
            }
            // Look up the target position.
            var targetPos = void 0;
            if (index >= list.sectionCount) {
                targetPos = list.totalSize;
            }
            else {
                targetPos = list.sectionOffset(index);
            }
            // Remove or Insert the sections and save the pre- and post- size.
            var size1 = list.totalSize;
            if (isRemove) {
                list.removeSections(index, span);
            }
            else {
                list.insertSections(index, span);
            }
            var size2 = list.totalSize;
            // Fetch the new max scroll position.
            var maxScrollPos2 = void 0;
            if (isRows) {
                maxScrollPos2 = this.maxScrollY;
            }
            else {
                maxScrollPos2 = this.maxScrollX;
            }
            // Adjust the scroll position as needed.
            var scrollPos2 = void 0;
            if (scrollPos1 === 0) {
                scrollPos2 = 0;
            }
            else if (scrollPos1 === maxScrollPos1) {
                scrollPos2 = maxScrollPos2;
            }
            else if (isRemove && targetPos <= scrollPos1) {
                var delta = Math.min(scrollPos1 - targetPos, size1 - size2);
                scrollPos2 = Math.min(scrollPos1 - delta, maxScrollPos2);
            }
            else if (targetPos <= scrollPos1) {
                scrollPos2 = Math.min(scrollPos1 + size2 - size1, maxScrollPos2);
            }
            else {
                scrollPos2 = scrollPos1;
            }
            // Update the scroll position and compute the paint offset.
            if (isRows) {
                this._scrollY = scrollPos2;
                offset = this.headerHeight;
            }
            else {
                this._scrollX = scrollPos2;
                offset = this.headerWidth;
            }
            // Adjust the paint offset if the scroll position did not change.
            if (scrollPos1 === scrollPos2) {
                offset = Math.max(offset, offset + targetPos - scrollPos1);
            }
        }
        // Compute the dirty area.
        var x = isRows ? 0 : offset;
        var y = isRows ? offset : 0;
        var w = this._viewportWidth - x;
        var h = this._viewportHeight - y;
        // Schedule a repaint of the dirty area, if needed.
        if (w > 0 && h > 0) {
            this.repaint(x, y, w, h);
        }
        // Sync the scroll state after queueing the repaint.
        this._syncScrollState();
    };
    /**
     * Handle sections moving in the data model.
     */
    DataGrid.prototype._onSectionsMoved = function (args) {
        // Unpack the arg data.
        var region = args.region, type = args.type, index = args.index, span = args.span, destination = args.destination;
        // Bail early if there are no sections to move.
        if (span <= 0) {
            return;
        }
        // Determine the behavior of the change type.
        var isRows = type === 'rows-moved';
        // Look up the relevant section list.
        var list;
        if (region === 'body') {
            list = isRows ? this._rowSections : this._columnSections;
        }
        else {
            list = isRows ? this._columnHeaderSections : this._rowHeaderSections;
        }
        // Bail early if the index is out of range.
        if (index < 0 || index >= list.sectionCount) {
            return;
        }
        // Clamp the move span to the limit.
        span = Math.min(span, list.sectionCount - index);
        // Clamp the destination index to the limit.
        destination = Math.min(Math.max(0, destination), list.sectionCount - span);
        // Bail early if there is no effective move.
        if (index === destination) {
            return;
        }
        // Compute the first affected index.
        var i1 = Math.min(index, destination);
        // Compute the last affected index.
        var i2 = Math.max(index + span - 1, destination + span - 1);
        // Compute the first paint boundary.
        var p1 = list.sectionOffset(i1);
        // Compute the last paint boundary.
        var p2;
        if (i2 >= list.sectionCount - 1) {
            p2 = list.totalSize - 1;
        }
        else {
            p2 = list.sectionOffset(i2 + 1) - 1;
        }
        // Move the sections in the list.
        list.moveSections(index, span, destination);
        // Fetch the row header and column header sizes.
        var hw = this.headerWidth;
        var hh = this.headerHeight;
        // Set up the initial paint limits.
        var xMin = 0;
        var yMin = 0;
        var xMax = this._viewportWidth - 1;
        var yMax = this._viewportHeight - 1;
        // Set up the initial paint region.
        var x1 = xMin;
        var y1 = yMin;
        var x2 = xMax;
        var y2 = yMax;
        // Adjust the limits and paint region.
        switch (region) {
            case 'body':
                if (isRows) {
                    yMin = hh;
                    y1 = hh + p1 - this._scrollY;
                    y2 = hh + p2 - this._scrollY;
                }
                else {
                    xMin = hw;
                    x1 = hw + p1 - this._scrollX;
                    x2 = hw + p2 - this._scrollX;
                }
                break;
            case 'row-header':
                xMax = Math.min(hw - 1, xMax);
                x1 = p1;
                x2 = p2;
                break;
            case 'column-header':
                yMax = Math.min(hh - 1, yMax);
                y1 = p1;
                y2 = p2;
                break;
            default:
                throw 'unreachable';
        }
        // Bail early if the paint limits are empty.
        if (xMax < xMin || yMax < yMin) {
            return;
        }
        // Bail early if the dirty region is out of range.
        if (x2 < xMin || x1 > xMax || y2 < yMin || y1 > yMax) {
            return;
        }
        // Compute the dirty area.
        var x = Math.max(xMin, x1);
        var y = Math.max(yMin, y1);
        var w = Math.min(x2, xMax) - x + 1;
        var h = Math.min(y2, yMax) - y + 1;
        // Schedule a repaint of the dirty area, if needed.
        if (w > 0 && h > 0) {
            this.repaint(x, y, w, h);
        }
    };
    /**
     * Handle cells changing in the data model.
     */
    DataGrid.prototype._onCellsChanged = function (args) {
        // Unpack the arg data.
        var region = args.region, rowIndex = args.rowIndex, columnIndex = args.columnIndex, rowSpan = args.rowSpan, columnSpan = args.columnSpan;
        // Bail early if there are no cells to modify.
        if (rowSpan <= 0 && columnSpan <= 0) {
            return;
        }
        // Look up the relevant row and column lists.
        var rList;
        var cList;
        switch (region) {
            case 'body':
                rList = this._rowSections;
                cList = this._columnSections;
                break;
            case 'row-header':
                rList = this._rowSections;
                cList = this._rowHeaderSections;
                break;
            case 'column-header':
                rList = this._columnHeaderSections;
                cList = this._columnSections;
                break;
            case 'corner-header':
                rList = this._columnHeaderSections;
                cList = this._rowHeaderSections;
                break;
            default:
                throw 'unreachable';
        }
        // Bail early if the changed cells are out of range.
        if (rowIndex >= rList.sectionCount || columnIndex >= cList.sectionCount) {
            return;
        }
        // Look up the unscrolled top-left corner of the range.
        var x1 = cList.sectionOffset(columnIndex);
        var y1 = rList.sectionOffset(rowIndex);
        // Look up the unscrolled bottom-right corner of the range.
        var x2;
        var y2;
        if (columnIndex + columnSpan >= cList.sectionCount) {
            x2 = cList.totalSize - 1;
        }
        else {
            x2 = cList.sectionOffset(columnIndex + columnSpan) - 1;
        }
        if (rowIndex + rowSpan >= rList.sectionCount) {
            y2 = rList.totalSize - 1;
        }
        else {
            y2 = rList.sectionOffset(rowIndex + rowSpan) - 1;
        }
        // Fetch the row header and column header sizes.
        var hw = this.headerWidth;
        var hh = this.headerHeight;
        // Set up the initial paint limits.
        var xMin = 0;
        var yMin = 0;
        var xMax = this._viewportWidth - 1;
        var yMax = this._viewportHeight - 1;
        // Adjust the limits and paint region.
        switch (region) {
            case 'body':
                xMin = hw;
                yMin = hh;
                x1 += hw - this._scrollX;
                x2 += hw - this._scrollX;
                y1 += hh - this._scrollY;
                y2 += hh - this._scrollY;
                break;
            case 'row-header':
                yMin = hh;
                xMax = Math.min(hw - 1, xMax);
                y1 += hh - this._scrollY;
                y2 += hh - this._scrollY;
                break;
            case 'column-header':
                xMin = hw;
                yMax = Math.min(hh - 1, yMax);
                x1 += hw - this._scrollX;
                x2 += hw - this._scrollX;
                break;
            case 'corner-header':
                xMax = Math.min(hw - 1, xMax);
                yMax = Math.min(hh - 1, yMax);
                break;
            default:
                throw 'unreachable';
        }
        // Bail early if the paint limits are empty.
        if (xMax < xMin || yMax < yMin) {
            return;
        }
        // Bail early if the dirty region is out of range.
        if (x2 < xMin || x1 > xMax || y2 < yMin || y1 > yMax) {
            return;
        }
        // Compute the dirty area.
        var x = Math.max(xMin, x1);
        var y = Math.max(yMin, y1);
        var w = Math.min(x2, xMax) - x + 1;
        var h = Math.min(y2, yMax) - y + 1;
        // Schedule a repaint of the dirty area, if needed.
        if (w > 0 && h > 0) {
            this.repaint(x, y, w, h);
        }
    };
    /**
     * Handle a full data model reset.
     */
    DataGrid.prototype._onModelReset = function (args) {
        // Look up the various current section counts.
        var nr = this._rowSections.sectionCount;
        var nc = this._columnSections.sectionCount;
        var nrh = this._rowHeaderSections.sectionCount;
        var nch = this._columnHeaderSections.sectionCount;
        // Compute the delta count for each region.
        var dr = this._model.rowCount('body') - nr;
        var dc = this._model.columnCount('body') - nc;
        var drh = this._model.columnCount('row-header') - nrh;
        var dch = this._model.rowCount('column-header') - nch;
        // Update the row sections, if needed.
        if (dr > 0) {
            this._rowSections.insertSections(nr, dr);
        }
        else if (dr < 0) {
            this._rowSections.removeSections(nr + dr, -dr);
        }
        // Update the column sections, if needed.
        if (dc > 0) {
            this._columnSections.insertSections(nc, dc);
        }
        else if (dc < 0) {
            this._columnSections.removeSections(nc + dc, -dc);
        }
        // Update the row header sections, if needed.
        if (drh > 0) {
            this._rowHeaderSections.insertSections(nrh, drh);
        }
        else if (drh < 0) {
            this._rowHeaderSections.removeSections(nrh + drh, -drh);
        }
        // Update the column header sections, if needed.
        if (dch > 0) {
            this._columnHeaderSections.insertSections(nch, dch);
        }
        else if (dch < 0) {
            this._columnHeaderSections.removeSections(nch + dch, -dch);
        }
        // Sync the viewport.
        this._syncViewport();
    };
    /**
     * A signal handler for the renderer map `changed` signal.
     */
    DataGrid.prototype._onRenderersChanged = function () {
        this.repaint();
    };
    /**
     * Blit content into the on-screen canvas.
     *
     * The rect should be expressed in viewport coordinates.
     *
     * This automatically accounts for the dpi ratio.
     */
    DataGrid.prototype._blit = function (source, x, y, w, h, dx, dy) {
        // Scale the blit coordinates by the dpi ratio.
        x *= this._dpiRatio;
        y *= this._dpiRatio;
        w *= this._dpiRatio;
        h *= this._dpiRatio;
        dx *= this._dpiRatio;
        dy *= this._dpiRatio;
        // Save the current gc state.
        this._canvasGC.save();
        // Set the transform to the identity matrix.
        this._canvasGC.setTransform(1, 0, 0, 1, 0, 0);
        // Draw the specified content.
        this._canvasGC.drawImage(source, x, y, w, h, dx, dy, w, h);
        // Restore the gc state.
        this._canvasGC.restore();
    };
    /**
     * Paint the grid content for the given dirty rect.
     *
     * The rect should be expressed in viewport coordinates.
     *
     * This is the primary paint entry point. The individual `_draw*`
     * methods should not be invoked directly. This method dispatches
     * to the drawing methods in the correct order.
     */
    DataGrid.prototype._paint = function (rx, ry, rw, rh) {
        // Warn and bail if recursive painting is detected.
        if (this._inPaint) {
            console.warn('Recursive paint detected.');
            return;
        }
        // Execute the actual drawing logic.
        try {
            this._inPaint = true;
            this._draw(rx, ry, rw, rh);
        }
        finally {
            this._inPaint = false;
        }
    };
    /**
     * Draw the grid content for the given dirty rect.
     *
     * This method dispatches to the relevant `_draw*` methods.
     */
    DataGrid.prototype._draw = function (rx, ry, rw, rh) {
        // Scale the canvas and buffer GC for the dpi ratio.
        this._canvasGC.setTransform(this._dpiRatio, 0, 0, this._dpiRatio, 0, 0);
        this._bufferGC.setTransform(this._dpiRatio, 0, 0, this._dpiRatio, 0, 0);
        // Clear the dirty rect of all content.
        this._canvasGC.clearRect(rx, ry, rw, rh);
        // Draw the void region.
        this._drawVoidRegion(rx, ry, rw, rh);
        // Draw the body region.
        this._drawBodyRegion(rx, ry, rw, rh);
        // Draw the row header region.
        this._drawRowHeaderRegion(rx, ry, rw, rh);
        // Draw the column header region.
        this._drawColumnHeaderRegion(rx, ry, rw, rh);
        // Draw the corner header region.
        this._drawCornerHeaderRegion(rx, ry, rw, rh);
    };
    /**
     * Draw the void region for the dirty rect.
     */
    DataGrid.prototype._drawVoidRegion = function (rx, ry, rw, rh) {
        // Look up the void color.
        var color = this._style.voidColor;
        // Bail if there is no void color.
        if (!color) {
            return;
        }
        // Fill the dirty rect with the void color.
        this._canvasGC.fillStyle = color;
        this._canvasGC.fillRect(rx, ry, rw, rh);
    };
    /**
     * Draw the body region which intersects the dirty rect.
     */
    DataGrid.prototype._drawBodyRegion = function (rx, ry, rw, rh) {
        // Get the visible content dimensions.
        var contentW = this._columnSections.totalSize - this._scrollX;
        var contentH = this._rowSections.totalSize - this._scrollY;
        // Bail if there is no content to draw.
        if (contentW <= 0 || contentH <= 0) {
            return;
        }
        // Get the visible content origin.
        var contentX = this.headerWidth;
        var contentY = this.headerHeight;
        // Bail if the dirty rect does not intersect the content area.
        if (rx + rw <= contentX) {
            return;
        }
        if (ry + rh <= contentY) {
            return;
        }
        if (rx >= contentX + contentW) {
            return;
        }
        if (ry >= contentY + contentH) {
            return;
        }
        // Get the upper and lower bounds of the dirty content area.
        var x1 = Math.max(rx, contentX);
        var y1 = Math.max(ry, contentY);
        var x2 = Math.min(rx + rw - 1, contentX + contentW - 1);
        var y2 = Math.min(ry + rh - 1, contentY + contentH - 1);
        // Convert the dirty content bounds into cell bounds.
        var r1 = this._rowSections.sectionIndex(y1 - contentY + this._scrollY);
        var c1 = this._columnSections.sectionIndex(x1 - contentX + this._scrollX);
        var r2 = this._rowSections.sectionIndex(y2 - contentY + this._scrollY);
        var c2 = this._columnSections.sectionIndex(x2 - contentX + this._scrollX);
        // Handle a dirty content area larger than the cell count.
        if (r2 < 0) {
            r2 = this._rowSections.sectionCount - 1;
        }
        if (c2 < 0) {
            c2 = this._columnSections.sectionCount - 1;
        }
        // Convert the cell bounds back to visible coordinates.
        var x = this._columnSections.sectionOffset(c1) + contentX - this._scrollX;
        var y = this._rowSections.sectionOffset(r1) + contentY - this._scrollY;
        // Set up the paint region size variables.
        var width = 0;
        var height = 0;
        // Allocate the section sizes arrays.
        var rowSizes = new Array(r2 - r1 + 1);
        var columnSizes = new Array(c2 - c1 + 1);
        // Get the row sizes for the region.
        for (var j = r1; j <= r2; ++j) {
            var size = this._rowSections.sectionSize(j);
            rowSizes[j - r1] = size;
            height += size;
        }
        // Get the column sizes for the region.
        for (var i = c1; i <= c2; ++i) {
            var size = this._columnSections.sectionSize(i);
            columnSizes[i - c1] = size;
            width += size;
        }
        // Create the paint region object.
        var rgn = {
            region: 'body',
            xMin: x1, yMin: y1,
            xMax: x2, yMax: y2,
            x: x, y: y, width: width, height: height,
            row: r1, column: c1,
            rowSizes: rowSizes, columnSizes: columnSizes
        };
        // Draw the background.
        this._drawBackground(rgn, this._style.backgroundColor);
        // Draw the row background.
        this._drawRowBackground(rgn, this._style.rowBackgroundColor);
        // Draw the column background.
        this._drawColumnBackground(rgn, this._style.columnBackgroundColor);
        // Draw the cell content for the paint region.
        this._drawCells(rgn);
        // Draw the horizontal grid lines.
        this._drawHorizontalGridLines(rgn, this._style.horizontalGridLineColor ||
            this._style.gridLineColor);
        // Draw the vertical grid lines.
        this._drawVerticalGridLines(rgn, this._style.verticalGridLineColor ||
            this._style.gridLineColor);
    };
    /**
     * Draw the row header region which intersects the dirty rect.
     */
    DataGrid.prototype._drawRowHeaderRegion = function (rx, ry, rw, rh) {
        // Get the visible content dimensions.
        var contentW = this.headerWidth;
        var contentH = this._rowSections.totalSize - this._scrollY;
        // Bail if there is no content to draw.
        if (contentW <= 0 || contentH <= 0) {
            return;
        }
        // Get the visible content origin.
        var contentX = 0;
        var contentY = this.headerHeight;
        // Bail if the dirty rect does not intersect the content area.
        if (rx + rw <= contentX) {
            return;
        }
        if (ry + rh <= contentY) {
            return;
        }
        if (rx >= contentX + contentW) {
            return;
        }
        if (ry >= contentY + contentH) {
            return;
        }
        // Get the upper and lower bounds of the dirty content area.
        var x1 = rx;
        var y1 = Math.max(ry, contentY);
        var x2 = Math.min(rx + rw - 1, contentX + contentW - 1);
        var y2 = Math.min(ry + rh - 1, contentY + contentH - 1);
        // Convert the dirty content bounds into cell bounds.
        var r1 = this._rowSections.sectionIndex(y1 - contentY + this._scrollY);
        var c1 = this._rowHeaderSections.sectionIndex(x1);
        var r2 = this._rowSections.sectionIndex(y2 - contentY + this._scrollY);
        var c2 = this._rowHeaderSections.sectionIndex(x2);
        // Handle a dirty content area larger than the cell count.
        if (r2 < 0) {
            r2 = this._rowSections.sectionCount - 1;
        }
        if (c2 < 0) {
            c2 = this._rowHeaderSections.sectionCount - 1;
        }
        // Convert the cell bounds back to visible coordinates.
        var x = this._rowHeaderSections.sectionOffset(c1);
        var y = this._rowSections.sectionOffset(r1) + contentY - this._scrollY;
        // Set up the paint region size variables.
        var width = 0;
        var height = 0;
        // Allocate the section sizes arrays.
        var rowSizes = new Array(r2 - r1 + 1);
        var columnSizes = new Array(c2 - c1 + 1);
        // Get the row sizes for the region.
        for (var j = r1; j <= r2; ++j) {
            var size = this._rowSections.sectionSize(j);
            rowSizes[j - r1] = size;
            height += size;
        }
        // Get the column sizes for the region.
        for (var i = c1; i <= c2; ++i) {
            var size = this._rowHeaderSections.sectionSize(i);
            columnSizes[i - c1] = size;
            width += size;
        }
        // Create the paint region object.
        var rgn = {
            region: 'row-header',
            xMin: x1, yMin: y1,
            xMax: x2, yMax: y2,
            x: x, y: y, width: width, height: height,
            row: r1, column: c1,
            rowSizes: rowSizes, columnSizes: columnSizes
        };
        // Draw the background.
        this._drawBackground(rgn, this._style.headerBackgroundColor);
        // Draw the cell content for the paint region.
        this._drawCells(rgn);
        // Draw the horizontal grid lines.
        this._drawHorizontalGridLines(rgn, this._style.headerHorizontalGridLineColor ||
            this._style.headerGridLineColor);
        // Draw the vertical grid lines.
        this._drawVerticalGridLines(rgn, this._style.headerVerticalGridLineColor ||
            this._style.headerGridLineColor);
    };
    /**
     * Draw the column header region which intersects the dirty rect.
     */
    DataGrid.prototype._drawColumnHeaderRegion = function (rx, ry, rw, rh) {
        // Get the visible content dimensions.
        var contentW = this._columnSections.totalSize - this._scrollX;
        var contentH = this.headerHeight;
        // Bail if there is no content to draw.
        if (contentW <= 0 || contentH <= 0) {
            return;
        }
        // Get the visible content origin.
        var contentX = this.headerWidth;
        var contentY = 0;
        // Bail if the dirty rect does not intersect the content area.
        if (rx + rw <= contentX) {
            return;
        }
        if (ry + rh <= contentY) {
            return;
        }
        if (rx >= contentX + contentW) {
            return;
        }
        if (ry >= contentY + contentH) {
            return;
        }
        // Get the upper and lower bounds of the dirty content area.
        var x1 = Math.max(rx, contentX);
        var y1 = ry;
        var x2 = Math.min(rx + rw - 1, contentX + contentW - 1);
        var y2 = Math.min(ry + rh - 1, contentY + contentH - 1);
        // Convert the dirty content bounds into cell bounds.
        var r1 = this._columnHeaderSections.sectionIndex(y1);
        var c1 = this._columnSections.sectionIndex(x1 - contentX + this._scrollX);
        var r2 = this._columnHeaderSections.sectionIndex(y2);
        var c2 = this._columnSections.sectionIndex(x2 - contentX + this._scrollX);
        // Handle a dirty content area larger than the cell count.
        if (r2 < 0) {
            r2 = this._columnHeaderSections.sectionCount - 1;
        }
        if (c2 < 0) {
            c2 = this._columnSections.sectionCount - 1;
        }
        // Convert the cell bounds back to visible coordinates.
        var x = this._columnSections.sectionOffset(c1) + contentX - this._scrollX;
        var y = this._columnHeaderSections.sectionOffset(r1);
        // Set up the paint region size variables.
        var width = 0;
        var height = 0;
        // Allocate the section sizes arrays.
        var rowSizes = new Array(r2 - r1 + 1);
        var columnSizes = new Array(c2 - c1 + 1);
        // Get the row sizes for the region.
        for (var j = r1; j <= r2; ++j) {
            var size = this._columnHeaderSections.sectionSize(j);
            rowSizes[j - r1] = size;
            height += size;
        }
        // Get the column sizes for the region.
        for (var i = c1; i <= c2; ++i) {
            var size = this._columnSections.sectionSize(i);
            columnSizes[i - c1] = size;
            width += size;
        }
        // Create the paint region object.
        var rgn = {
            region: 'column-header',
            xMin: x1, yMin: y1,
            xMax: x2, yMax: y2,
            x: x, y: y, width: width, height: height,
            row: r1, column: c1,
            rowSizes: rowSizes, columnSizes: columnSizes
        };
        // Draw the background.
        this._drawBackground(rgn, this._style.headerBackgroundColor);
        // Draw the cell content for the paint region.
        this._drawCells(rgn);
        // Draw the horizontal grid lines.
        this._drawHorizontalGridLines(rgn, this._style.headerHorizontalGridLineColor ||
            this._style.headerGridLineColor);
        // Draw the vertical grid lines.
        this._drawVerticalGridLines(rgn, this._style.headerVerticalGridLineColor ||
            this._style.headerGridLineColor);
    };
    /**
     * Draw the corner header region which intersects the dirty rect.
     */
    DataGrid.prototype._drawCornerHeaderRegion = function (rx, ry, rw, rh) {
        // Get the visible content dimensions.
        var contentW = this.headerWidth;
        var contentH = this.headerHeight;
        // Bail if there is no content to draw.
        if (contentW <= 0 || contentH <= 0) {
            return;
        }
        // Get the visible content origin.
        var contentX = 0;
        var contentY = 0;
        // Bail if the dirty rect does not intersect the content area.
        if (rx + rw <= contentX) {
            return;
        }
        if (ry + rh <= contentY) {
            return;
        }
        if (rx >= contentX + contentW) {
            return;
        }
        if (ry >= contentY + contentH) {
            return;
        }
        // Get the upper and lower bounds of the dirty content area.
        var x1 = rx;
        var y1 = ry;
        var x2 = Math.min(rx + rw - 1, contentX + contentW - 1);
        var y2 = Math.min(ry + rh - 1, contentY + contentH - 1);
        // Convert the dirty content bounds into cell bounds.
        var r1 = this._columnHeaderSections.sectionIndex(y1);
        var c1 = this._rowHeaderSections.sectionIndex(x1);
        var r2 = this._columnHeaderSections.sectionIndex(y2);
        var c2 = this._rowHeaderSections.sectionIndex(x2);
        // Handle a dirty content area larger than the cell count.
        if (r2 < 0) {
            r2 = this._columnHeaderSections.sectionCount - 1;
        }
        if (c2 < 0) {
            c2 = this._rowHeaderSections.sectionCount - 1;
        }
        // Convert the cell bounds back to visible coordinates.
        var x = this._rowHeaderSections.sectionOffset(c1);
        var y = this._columnHeaderSections.sectionOffset(r1);
        // Set up the paint region size variables.
        var width = 0;
        var height = 0;
        // Allocate the section sizes arrays.
        var rowSizes = new Array(r2 - r1 + 1);
        var columnSizes = new Array(c2 - c1 + 1);
        // Get the row sizes for the region.
        for (var j = r1; j <= r2; ++j) {
            var size = this._columnHeaderSections.sectionSize(j);
            rowSizes[j - r1] = size;
            height += size;
        }
        // Get the column sizes for the region.
        for (var i = c1; i <= c2; ++i) {
            var size = this._rowHeaderSections.sectionSize(i);
            columnSizes[i - c1] = size;
            width += size;
        }
        // Create the paint region object.
        var rgn = {
            region: 'corner-header',
            xMin: x1, yMin: y1,
            xMax: x2, yMax: y2,
            x: x, y: y, width: width, height: height,
            row: r1, column: c1,
            rowSizes: rowSizes, columnSizes: columnSizes
        };
        // Draw the background.
        this._drawBackground(rgn, this._style.headerBackgroundColor);
        // Draw the cell content for the paint region.
        this._drawCells(rgn);
        // Draw the horizontal grid lines.
        this._drawHorizontalGridLines(rgn, this._style.headerHorizontalGridLineColor ||
            this._style.headerGridLineColor);
        // Draw the vertical grid lines.
        this._drawVerticalGridLines(rgn, this._style.headerVerticalGridLineColor ||
            this._style.headerGridLineColor);
    };
    /**
     * Draw the background for the given paint region.
     */
    DataGrid.prototype._drawBackground = function (rgn, color) {
        // Bail if there is no color to draw.
        if (!color) {
            return;
        }
        // Unpack the region.
        var xMin = rgn.xMin, yMin = rgn.yMin, xMax = rgn.xMax, yMax = rgn.yMax;
        // Fill the region with the specified color.
        this._canvasGC.fillStyle = color;
        this._canvasGC.fillRect(xMin, yMin, xMax - xMin + 1, yMax - yMin + 1);
    };
    /**
     * Draw the row background for the given paint region.
     */
    DataGrid.prototype._drawRowBackground = function (rgn, colorFn) {
        // Bail if there is no color function.
        if (!colorFn) {
            return;
        }
        // Compute the X bounds for the row.
        var x1 = Math.max(rgn.xMin, rgn.x);
        var x2 = Math.min(rgn.x + rgn.width - 1, rgn.xMax);
        // Draw the background for the rows in the region.
        for (var y = rgn.y, j = 0, n = rgn.rowSizes.length; j < n; ++j) {
            // Fetch the size of the row.
            var size = rgn.rowSizes[j];
            // Skip zero sized rows.
            if (size === 0) {
                continue;
            }
            // Get the background color for the row.
            var color = colorFn(rgn.row + j);
            // Fill the row with the background color if needed.
            if (color) {
                var y1 = Math.max(rgn.yMin, y);
                var y2 = Math.min(y + size - 1, rgn.yMax);
                this._canvasGC.fillStyle = color;
                this._canvasGC.fillRect(x1, y1, x2 - x1 + 1, y2 - y1 + 1);
            }
            // Increment the running Y coordinate.
            y += size;
        }
    };
    /**
     * Draw the column background for the given paint region.
     */
    DataGrid.prototype._drawColumnBackground = function (rgn, colorFn) {
        // Bail if there is no color function.
        if (!colorFn) {
            return;
        }
        // Compute the Y bounds for the column.
        var y1 = Math.max(rgn.yMin, rgn.y);
        var y2 = Math.min(rgn.y + rgn.height - 1, rgn.yMax);
        // Draw the background for the columns in the region.
        for (var x = rgn.x, i = 0, n = rgn.columnSizes.length; i < n; ++i) {
            // Fetch the size of the column.
            var size = rgn.columnSizes[i];
            // Skip zero sized columns.
            if (size === 0) {
                continue;
            }
            // Get the background color for the column.
            var color = colorFn(rgn.column + i);
            // Fill the column with the background color if needed.
            if (color) {
                var x1 = Math.max(rgn.xMin, x);
                var x2 = Math.min(x + size - 1, rgn.xMax);
                this._canvasGC.fillStyle = color;
                this._canvasGC.fillRect(x1, y1, x2 - x1 + 1, y2 - y1 + 1);
            }
            // Increment the running X coordinate.
            x += size;
        }
    };
    /**
     * Draw the cells for the given paint region.
     */
    DataGrid.prototype._drawCells = function (rgn) {
        // Bail if there is no data model.
        if (!this._model) {
            return;
        }
        // Set up the cell config object for rendering.
        var config = {
            x: 0, y: 0, width: 0, height: 0,
            region: rgn.region, row: 0, column: 0,
            metadata: datamodel_1.DataModel.emptyMetadata, value: null
        };
        // Save the buffer gc before wrapping.
        this._bufferGC.save();
        // Wrap the buffer gc for painting the cells.
        var gc = new graphicscontext_1.GraphicsContext(this._bufferGC);
        // Compute the actual Y bounds for the cell range.
        var y1 = Math.max(rgn.yMin, rgn.y);
        var y2 = Math.min(rgn.y + rgn.height - 1, rgn.yMax);
        // Loop over the columns in the region.
        for (var x = rgn.x, i = 0, n = rgn.columnSizes.length; i < n; ++i) {
            // Fetch the size of the column.
            var width = rgn.columnSizes[i];
            // Skip zero sized columns.
            if (width === 0) {
                continue;
            }
            // Compute the column index.
            var column = rgn.column + i;
            // Get the metadata for the column.
            var metadata = void 0;
            try {
                metadata = this._model.metadata(rgn.region, column);
            }
            catch (err) {
                metadata = datamodel_1.DataModel.emptyMetadata;
                console.error(err);
            }
            // Update the config for the current column.
            config.x = x;
            config.width = width;
            config.column = column;
            config.metadata = metadata;
            // Clear the buffer rect for the column.
            gc.clearRect(x, rgn.y, width, rgn.height);
            // Save the GC state.
            gc.save();
            // Look up the renderer for the column.
            var renderer = (this._cellRenderers.get(rgn.region, metadata) || this._defaultRenderer);
            // Prepare the cell renderer for drawing the column.
            try {
                renderer.prepare(gc, config);
            }
            catch (err) {
                console.error(err);
            }
            // Loop over the rows in the column.
            for (var y = rgn.y, j = 0, n_1 = rgn.rowSizes.length; j < n_1; ++j) {
                // Fetch the size of the row.
                var height = rgn.rowSizes[j];
                // Skip zero sized rows.
                if (height === 0) {
                    continue;
                }
                // Compute the row index.
                var row = rgn.row + j;
                // Get the data value for the cell.
                var value = void 0;
                try {
                    value = this._model.data(rgn.region, row, column);
                }
                catch (err) {
                    value = undefined;
                    console.error(err);
                }
                // Update the config for the current cell.
                config.y = y;
                config.height = height;
                config.row = row;
                config.value = value;
                // Save the GC state.
                gc.save();
                // Paint the cell into the off-screen buffer.
                try {
                    renderer.paint(gc, config);
                }
                catch (err) {
                    console.error(err);
                }
                // Restore the GC state.
                gc.restore();
                // Increment the running Y coordinate.
                y += height;
            }
            // Restore the GC state.
            gc.restore();
            // Compute the actual X bounds for the column.
            var x1 = Math.max(rgn.xMin, x);
            var x2 = Math.min(x + width - 1, rgn.xMax);
            // Blit the off-screen buffer column into the on-screen canvas.
            //
            // This is *much* faster than drawing directly into the on-screen
            // canvas with a clip rect on the column. Managed column clipping
            // is required to prevent cell renderers from needing to set up a
            // clip rect for handling horizontal overflow text (slow!).
            this._blit(this._buffer, x1, y1, x2 - x1 + 1, y2 - y1 + 1, x1, y1);
            // Increment the running X coordinate.
            x += width;
        }
        // Dispose of the wrapped gc.
        gc.dispose();
        // Restore the final buffer gc state.
        this._bufferGC.restore();
    };
    /**
     * Draw the horizontal grid lines for the given paint region.
     */
    DataGrid.prototype._drawHorizontalGridLines = function (rgn, color) {
        // Bail if there is no color to draw.
        if (!color) {
            return;
        }
        // Compute the X bounds for the horizontal lines.
        var x1 = Math.max(rgn.xMin, rgn.x);
        var x2 = Math.min(rgn.x + rgn.width, rgn.xMax + 1);
        // Begin the path for the grid lines.
        this._canvasGC.beginPath();
        // Set the line width for the grid lines.
        this._canvasGC.lineWidth = 1;
        // Draw the horizontal grid lines.
        for (var y = rgn.y, j = 0, n = rgn.rowSizes.length; j < n; ++j) {
            // Fetch the size of the row.
            var size = rgn.rowSizes[j];
            // Skip zero sized rows.
            if (size === 0) {
                continue;
            }
            // Compute the Y position of the line.
            var pos = y + size - 1;
            // Draw the line if it's in range of the dirty rect.
            if (pos >= rgn.yMin && pos <= rgn.yMax) {
                this._canvasGC.moveTo(x1, pos + 0.5);
                this._canvasGC.lineTo(x2, pos + 0.5);
            }
            // Increment the running Y coordinate.
            y += size;
        }
        // Stroke the lines with the specified color.
        this._canvasGC.strokeStyle = color;
        this._canvasGC.stroke();
    };
    /**
     * Draw the vertical grid lines for the given paint region.
     */
    DataGrid.prototype._drawVerticalGridLines = function (rgn, color) {
        // Bail if there is no color to draw.
        if (!color) {
            return;
        }
        // Compute the Y bounds for the vertical lines.
        var y1 = Math.max(rgn.yMin, rgn.y);
        var y2 = Math.min(rgn.y + rgn.height, rgn.yMax + 1);
        // Begin the path for the grid lines
        this._canvasGC.beginPath();
        // Set the line width for the grid lines.
        this._canvasGC.lineWidth = 1;
        // Draw the vertical grid lines.
        for (var x = rgn.x, i = 0, n = rgn.columnSizes.length; i < n; ++i) {
            // Fetch the size of the column.
            var size = rgn.columnSizes[i];
            // Skip zero sized columns.
            if (size === 0) {
                continue;
            }
            // Compute the X position of the line.
            var pos = x + size - 1;
            // Draw the line if it's in range of the dirty rect.
            if (pos >= rgn.xMin && pos <= rgn.xMax) {
                this._canvasGC.moveTo(pos + 0.5, y1);
                this._canvasGC.lineTo(pos + 0.5, y2);
            }
            // Increment the running X coordinate.
            x += size;
        }
        // Stroke the lines with the specified color.
        this._canvasGC.strokeStyle = color;
        this._canvasGC.stroke();
    };
    return DataGrid;
}(widgets_1.Widget));
exports.DataGrid = DataGrid;
/**
 * The namespace for the `DataGrid` class statics.
 */
(function (DataGrid) {
    /**
     * The default theme for a data grid.
     */
    DataGrid.defaultStyle = {
        voidColor: '#F3F3F3',
        backgroundColor: '#FFFFFF',
        gridLineColor: 'rgba(20, 20, 20, 0.15)',
        headerBackgroundColor: '#F3F3F3',
        headerGridLineColor: 'rgba(20, 20, 20, 0.25)'
    };
})(DataGrid = exports.DataGrid || (exports.DataGrid = {}));
exports.DataGrid = DataGrid;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * A singleton `scroll-request` conflatable message.
     */
    Private.ScrollRequest = new messaging_1.ConflatableMessage('scroll-request');
    /**
     * A singleton `section-resize-request` conflatable message.
     */
    Private.SectionResizeRequest = new messaging_1.ConflatableMessage('section-resize-request');
    /**
     * Create a new zero-sized canvas element.
     */
    function createCanvas() {
        var canvas = document.createElement('canvas');
        canvas.width = 0;
        canvas.height = 0;
        return canvas;
    }
    Private.createCanvas = createCanvas;
    /**
     * A conflatable message which merges dirty paint rects.
     */
    var PaintRequest = (function (_super) {
        __extends(PaintRequest, _super);
        /**
         * Construct a new paint request messages.
         *
         * @param x1 - The top-left X coordinate of the rect.
         *
         * @param y1 - The top-left Y coordinate of the rect.
         *
         * @param x2 - The bottom-right X coordinate of the rect.
         *
         * @param y2 - The bottom-right Y coordinate of the rect.
         */
        function PaintRequest(x1, y1, x2, y2) {
            var _this = _super.call(this, 'paint-request') || this;
            _this._x1 = x1;
            _this._y1 = y1;
            _this._x2 = Math.max(x1, x2);
            _this._y2 = Math.max(y1, y2);
            return _this;
        }
        Object.defineProperty(PaintRequest.prototype, "x1", {
            /**
             * The top-left X coordinate of the rect.
             */
            get: function () {
                return this._x1;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PaintRequest.prototype, "y1", {
            /**
             * The top-left Y coordinate of the rect.
             */
            get: function () {
                return this._y1;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PaintRequest.prototype, "x2", {
            /**
             * The bottom-right X coordinate of the rect.
             */
            get: function () {
                return this._x2;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PaintRequest.prototype, "y2", {
            /**
             * The bottom-right Y coordinate of the rect.
             */
            get: function () {
                return this._y2;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Conflate this message with another paint request.
         */
        PaintRequest.prototype.conflate = function (other) {
            this._x1 = Math.min(this._x1, other._x1);
            this._y1 = Math.min(this._y1, other._y1);
            this._x2 = Math.max(this._x2, other._x2);
            this._y2 = Math.max(this._y2, other._y2);
            return true;
        };
        return PaintRequest;
    }(messaging_1.ConflatableMessage));
    Private.PaintRequest = PaintRequest;
    /**
     * Find the index of the resize handle at the given position.
     *
     * This accounts for `3px` of space on either side of a grid line,
     * for a total of `7px` handle width.
     *
     * Returns the `{ index, delta }` match or `null`.
     */
    function findResizeIndex(list, pos) {
        // Bail early if the list is empty or the position is invalid.
        if (list.sectionCount === 0 || pos < 0) {
            return null;
        }
        // Compute the delta from the end of the list.
        var d1 = pos - (list.totalSize - 1);
        // Bail if the position is out of range.
        if (d1 > 3) {
            return null;
        }
        // Test whether the hover is just past the last section.
        if (d1 >= 0) {
            return { index: list.sectionCount - 1, delta: d1 };
        }
        // Find the section at the given position.
        var i = list.sectionIndex(pos);
        // Look up the offset for the section.
        var offset = list.sectionOffset(i);
        // Compute the delta to the previous border.
        var d2 = pos - (offset - 1);
        // Test whether the position hovers the previous border.
        if (i > 0 && d2 <= 3) {
            return { index: i - 1, delta: d2 };
        }
        // Look up the size of the section.
        var size = list.sectionSize(i);
        // Compute the delta to the next border.
        var d3 = (size + offset - 1) - pos;
        // Test whether the position hovers the section border.
        if (d3 <= 3) {
            return { index: i, delta: -d3 };
        }
        // Otherwise, no resize border is hovered.
        return null;
    }
    Private.findResizeIndex = findResizeIndex;
    /**
     * Get the cursor to use for a resize handle.
     */
    function cursorForHandle(handle) {
        return handle ? cursorMap[handle.type] : '';
    }
    Private.cursorForHandle = cursorForHandle;
    /**
     * A mapping of resize handle types to cursor values.
     */
    var cursorMap = {
        'body-row': 'ns-resize',
        'body-column': 'ew-resize',
        'header-row': 'ns-resize',
        'header-column': 'ew-resize'
    };
})(Private || (Private = {}));


/***/ }),

/***/ "nGIF":
/*!**********************************************************!*\
  !*** ./node_modules/@jupyterlab/outputarea/lib/index.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__webpack_require__(/*! ../style/index.css */ "BWnT");
__export(__webpack_require__(/*! ./model */ "0XmT"));
__export(__webpack_require__(/*! ./widget */ "km5Q"));


/***/ }),

/***/ "nLT/":
/*!*******************************************!*\
  !*** ./node_modules/mdi-react/TagIcon.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var TagIcon = function TagIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M5.5,7C4.67,7 4,6.33 4,5.5C4,4.67 4.67,4 5.5,4C6.33,4 7,4.67 7,5.5C7,6.33 6.33,7 5.5,7M21.41,11.58L12.41,2.58C12.05,2.22 11.55,2 11,2H4C2.89,2 2,2.89 2,4V11C2,11.55 2.22,12.05 2.59,12.41L11.58,21.41C11.95,21.77 12.45,22 13,22C13.55,22 14.05,21.77 14.41,21.41L21.41,14.41C21.78,14.05 22,13.55 22,13C22,12.44 21.77,11.94 21.41,11.58Z' })
  );
};

module.exports = TagIcon;


/***/ }),

/***/ "nUyg":
/*!***************************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/singletonlayout.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
var messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
var layout_1 = __webpack_require__(/*! ./layout */ "yNaG");
var widget_1 = __webpack_require__(/*! ./widget */ "FmDU");
/**
 * A concrete layout implementation which holds a single widget.
 *
 * #### Notes
 * This class is useful for creating simple container widgets which
 * hold a single child. The child should be positioned with CSS.
 */
var SingletonLayout = (function (_super) {
    __extends(SingletonLayout, _super);
    function SingletonLayout() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this._widget = null;
        return _this;
    }
    /**
     * Dispose of the resources held by the layout.
     */
    SingletonLayout.prototype.dispose = function () {
        if (this._widget) {
            var widget = this._widget;
            this._widget = null;
            widget.dispose();
        }
        _super.prototype.dispose.call(this);
    };
    Object.defineProperty(SingletonLayout.prototype, "widget", {
        /**
         * Get the child widget for the layout.
         */
        get: function () {
            return this._widget;
        },
        /**
         * Set the child widget for the layout.
         *
         * #### Notes
         * Setting the child widget will cause the old child widget to be
         * automatically disposed. If that is not desired, set the parent
         * of the old child to `null` before assigning a new child.
         */
        set: function (widget) {
            // Bail early if the widget does not change.
            if (this._widget === widget) {
                return;
            }
            // Dispose of the old child widget.
            if (this._widget) {
                this._widget.dispose();
            }
            // Update the internal widget.
            this._widget = widget;
            // Attach the new child widget if needed.
            if (this.parent && widget) {
                this.attachWidget(widget);
            }
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Create an iterator over the widgets in the layout.
     *
     * @returns A new iterator over the widgets in the layout.
     */
    SingletonLayout.prototype.iter = function () {
        return this._widget ? algorithm_1.once(this._widget) : algorithm_1.empty();
    };
    /**
     * Remove a widget from the layout.
     *
     * @param widget - The widget to remove from the layout.
     *
     * #### Notes
     * A widget is automatically removed from the layout when its `parent`
     * is set to `null`. This method should only be invoked directly when
     * removing a widget from a layout which has yet to be installed on a
     * parent widget.
     *
     * This method does *not* modify the widget's `parent`.
     */
    SingletonLayout.prototype.removeWidget = function (widget) {
        // Bail early if the widget does not exist in the layout.
        if (this._widget !== widget) {
            return;
        }
        // Clear the internal widget.
        this._widget = null;
        // If the layout is parented, detach the widget from the DOM.
        if (this.parent) {
            this.detachWidget(widget);
        }
    };
    /**
     * Perform layout initialization which requires the parent widget.
     */
    SingletonLayout.prototype.init = function () {
        var _this = this;
        _super.prototype.init.call(this);
        algorithm_1.each(this, function (widget) { _this.attachWidget(widget); });
    };
    /**
     * Attach a widget to the parent's DOM node.
     *
     * @param index - The current index of the widget in the layout.
     *
     * @param widget - The widget to attach to the parent.
     *
     * #### Notes
     * This method is called automatically by the single layout at the
     * appropriate time. It should not be called directly by user code.
     *
     * The default implementation adds the widgets's node to the parent's
     * node at the proper location, and sends the appropriate attach
     * messages to the widget if the parent is attached to the DOM.
     *
     * Subclasses may reimplement this method to control how the widget's
     * node is added to the parent's node.
     */
    SingletonLayout.prototype.attachWidget = function (widget) {
        // Send a `'before-attach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.BeforeAttach);
        }
        // Add the widget's node to the parent.
        this.parent.node.appendChild(widget.node);
        // Send an `'after-attach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.AfterAttach);
        }
    };
    /**
     * Detach a widget from the parent's DOM node.
     *
     * @param widget - The widget to detach from the parent.
     *
     * #### Notes
     * This method is called automatically by the single layout at the
     * appropriate time. It should not be called directly by user code.
     *
     * The default implementation removes the widget's node from the
     * parent's node, and sends the appropriate detach messages to the
     * widget if the parent is attached to the DOM.
     *
     * Subclasses may reimplement this method to control how the widget's
     * node is removed from the parent's node.
     */
    SingletonLayout.prototype.detachWidget = function (widget) {
        // Send a `'before-detach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.BeforeDetach);
        }
        // Remove the widget's node from the parent.
        this.parent.node.removeChild(widget.node);
        // Send an `'after-detach'` message if the parent is attached.
        if (this.parent.isAttached) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.Msg.AfterDetach);
        }
    };
    return SingletonLayout;
}(layout_1.Layout));
exports.SingletonLayout = SingletonLayout;


/***/ }),

/***/ "nVxC":
/*!*************************************************************!*\
  !*** ./node_modules/@jupyterlab/fileeditor/style/index.css ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "Ki94");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "nW7/":
/*!********************************************************************!*\
  !*** ./node_modules/react-color/lib/components/twitter/Twitter.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Twitter = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _map = __webpack_require__(/*! lodash/map */ "3WF5");

var _map2 = _interopRequireDefault(_map);

var _merge = __webpack_require__(/*! lodash/merge */ "QkVN");

var _merge2 = _interopRequireDefault(_merge);

var _color = __webpack_require__(/*! ../../helpers/color */ "p8yl");

var _color2 = _interopRequireDefault(_color);

var _common = __webpack_require__(/*! ../common */ "TM95");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var Twitter = exports.Twitter = function Twitter(_ref) {
  var onChange = _ref.onChange,
      onSwatchHover = _ref.onSwatchHover,
      hex = _ref.hex,
      colors = _ref.colors,
      width = _ref.width,
      triangle = _ref.triangle,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': {
      card: {
        width: width,
        background: '#fff',
        border: '0 solid rgba(0,0,0,0.25)',
        boxShadow: '0 1px 4px rgba(0,0,0,0.25)',
        borderRadius: '4px',
        position: 'relative'
      },
      body: {
        padding: '15px 9px 9px 15px'
      },
      label: {
        fontSize: '18px',
        color: '#fff'
      },
      triangle: {
        width: '0px',
        height: '0px',
        borderStyle: 'solid',
        borderWidth: '0 9px 10px 9px',
        borderColor: 'transparent transparent #fff transparent',
        position: 'absolute'
      },
      triangleShadow: {
        width: '0px',
        height: '0px',
        borderStyle: 'solid',
        borderWidth: '0 9px 10px 9px',
        borderColor: 'transparent transparent rgba(0,0,0,.1) transparent',
        position: 'absolute'
      },
      hash: {
        background: '#F0F0F0',
        height: '30px',
        width: '30px',
        borderRadius: '4px 0 0 4px',
        float: 'left',
        color: '#98A1A4',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
      },
      input: {
        width: '100px',
        fontSize: '14px',
        color: '#666',
        border: '0px',
        outline: 'none',
        height: '28px',
        boxShadow: 'inset 0 0 0 1px #F0F0F0',
        boxSizing: 'content-box',
        borderRadius: '0 4px 4px 0',
        float: 'left',
        paddingLeft: '8px'
      },
      swatch: {
        width: '30px',
        height: '30px',
        float: 'left',
        borderRadius: '4px',
        margin: '0 6px 6px 0'
      },
      clear: {
        clear: 'both'
      }
    },
    'hide-triangle': {
      triangle: {
        display: 'none'
      },
      triangleShadow: {
        display: 'none'
      }
    },
    'top-left-triangle': {
      triangle: {
        top: '-10px',
        left: '12px'
      },
      triangleShadow: {
        top: '-11px',
        left: '12px'
      }
    },
    'top-right-triangle': {
      triangle: {
        top: '-10px',
        right: '12px'
      },
      triangleShadow: {
        top: '-11px',
        right: '12px'
      }
    }
  }, passedStyles), {
    'hide-triangle': triangle === 'hide',
    'top-left-triangle': triangle === 'top-left',
    'top-right-triangle': triangle === 'top-right'
  });

  var handleChange = function handleChange(hexcode, e) {
    _color2.default.isValidHex(hexcode) && onChange({
      hex: hexcode,
      source: 'hex'
    }, e);
  };

  return _react2.default.createElement(
    'div',
    { style: styles.card, className: 'twitter-picker ' + className },
    _react2.default.createElement('div', { style: styles.triangleShadow }),
    _react2.default.createElement('div', { style: styles.triangle }),
    _react2.default.createElement(
      'div',
      { style: styles.body },
      (0, _map2.default)(colors, function (c, i) {
        return _react2.default.createElement(_common.Swatch, {
          key: i,
          color: c,
          hex: c,
          style: styles.swatch,
          onClick: handleChange,
          onHover: onSwatchHover,
          focusStyle: {
            boxShadow: '0 0 4px ' + c
          }
        });
      }),
      _react2.default.createElement(
        'div',
        { style: styles.hash },
        '#'
      ),
      _react2.default.createElement(_common.EditableInput, {
        style: { input: styles.input },
        value: hex.replace('#', ''),
        onChange: handleChange
      }),
      _react2.default.createElement('div', { style: styles.clear })
    )
  );
};

Twitter.propTypes = {
  width: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]),
  triangle: _propTypes2.default.oneOf(['hide', 'top-left', 'top-right']),
  colors: _propTypes2.default.arrayOf(_propTypes2.default.string),
  styles: _propTypes2.default.object
};

Twitter.defaultProps = {
  width: 276,
  colors: ['#FF6900', '#FCB900', '#7BDCB5', '#00D084', '#8ED1FC', '#0693E3', '#ABB8C3', '#EB144C', '#F78DA7', '#9900EF'],
  triangle: 'top-left',
  styles: {}
};

exports.default = (0, _common.ColorWrap)(Twitter);

/***/ }),

/***/ "nWiE":
/*!*************************************************************!*\
  !*** ./node_modules/react-dropzone/dist/es/utils/styles.js ***!
  \*************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = ({
  rejected: {
    borderStyle: 'solid',
    borderColor: '#c66',
    backgroundColor: '#eee'
  },
  disabled: {
    opacity: 0.5
  },
  active: {
    borderStyle: 'solid',
    borderColor: '#6c6',
    backgroundColor: '#eee'
  },
  default: {
    width: 200,
    height: 200,
    borderWidth: 2,
    borderColor: '#666',
    borderStyle: 'dashed',
    borderRadius: 5
  }
});

/***/ }),

/***/ "nYho":
/*!*******************************************!*\
  !*** ./node_modules/punycode/punycode.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(module, global) {var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/punycode v1.4.1 by @mathias */
;(function(root) {

	/** Detect free variables */
	var freeExports = typeof exports == 'object' && exports &&
		!exports.nodeType && exports;
	var freeModule = typeof module == 'object' && module &&
		!module.nodeType && module;
	var freeGlobal = typeof global == 'object' && global;
	if (
		freeGlobal.global === freeGlobal ||
		freeGlobal.window === freeGlobal ||
		freeGlobal.self === freeGlobal
	) {
		root = freeGlobal;
	}

	/**
	 * The `punycode` object.
	 * @name punycode
	 * @type Object
	 */
	var punycode,

	/** Highest positive signed 32-bit float value */
	maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1

	/** Bootstring parameters */
	base = 36,
	tMin = 1,
	tMax = 26,
	skew = 38,
	damp = 700,
	initialBias = 72,
	initialN = 128, // 0x80
	delimiter = '-', // '\x2D'

	/** Regular expressions */
	regexPunycode = /^xn--/,
	regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
	regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators

	/** Error messages */
	errors = {
		'overflow': 'Overflow: input needs wider integers to process',
		'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
		'invalid-input': 'Invalid input'
	},

	/** Convenience shortcuts */
	baseMinusTMin = base - tMin,
	floor = Math.floor,
	stringFromCharCode = String.fromCharCode,

	/** Temporary variable */
	key;

	/*--------------------------------------------------------------------------*/

	/**
	 * A generic error utility function.
	 * @private
	 * @param {String} type The error type.
	 * @returns {Error} Throws a `RangeError` with the applicable error message.
	 */
	function error(type) {
		throw new RangeError(errors[type]);
	}

	/**
	 * A generic `Array#map` utility function.
	 * @private
	 * @param {Array} array The array to iterate over.
	 * @param {Function} callback The function that gets called for every array
	 * item.
	 * @returns {Array} A new array of values returned by the callback function.
	 */
	function map(array, fn) {
		var length = array.length;
		var result = [];
		while (length--) {
			result[length] = fn(array[length]);
		}
		return result;
	}

	/**
	 * A simple `Array#map`-like wrapper to work with domain name strings or email
	 * addresses.
	 * @private
	 * @param {String} domain The domain name or email address.
	 * @param {Function} callback The function that gets called for every
	 * character.
	 * @returns {Array} A new string of characters returned by the callback
	 * function.
	 */
	function mapDomain(string, fn) {
		var parts = string.split('@');
		var result = '';
		if (parts.length > 1) {
			// In email addresses, only the domain name should be punycoded. Leave
			// the local part (i.e. everything up to `@`) intact.
			result = parts[0] + '@';
			string = parts[1];
		}
		// Avoid `split(regex)` for IE8 compatibility. See #17.
		string = string.replace(regexSeparators, '\x2E');
		var labels = string.split('.');
		var encoded = map(labels, fn).join('.');
		return result + encoded;
	}

	/**
	 * Creates an array containing the numeric code points of each Unicode
	 * character in the string. While JavaScript uses UCS-2 internally,
	 * this function will convert a pair of surrogate halves (each of which
	 * UCS-2 exposes as separate characters) into a single code point,
	 * matching UTF-16.
	 * @see `punycode.ucs2.encode`
	 * @see <https://mathiasbynens.be/notes/javascript-encoding>
	 * @memberOf punycode.ucs2
	 * @name decode
	 * @param {String} string The Unicode input string (UCS-2).
	 * @returns {Array} The new array of code points.
	 */
	function ucs2decode(string) {
		var output = [],
		    counter = 0,
		    length = string.length,
		    value,
		    extra;
		while (counter < length) {
			value = string.charCodeAt(counter++);
			if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
				// high surrogate, and there is a next character
				extra = string.charCodeAt(counter++);
				if ((extra & 0xFC00) == 0xDC00) { // low surrogate
					output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
				} else {
					// unmatched surrogate; only append this code unit, in case the next
					// code unit is the high surrogate of a surrogate pair
					output.push(value);
					counter--;
				}
			} else {
				output.push(value);
			}
		}
		return output;
	}

	/**
	 * Creates a string based on an array of numeric code points.
	 * @see `punycode.ucs2.decode`
	 * @memberOf punycode.ucs2
	 * @name encode
	 * @param {Array} codePoints The array of numeric code points.
	 * @returns {String} The new Unicode string (UCS-2).
	 */
	function ucs2encode(array) {
		return map(array, function(value) {
			var output = '';
			if (value > 0xFFFF) {
				value -= 0x10000;
				output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
				value = 0xDC00 | value & 0x3FF;
			}
			output += stringFromCharCode(value);
			return output;
		}).join('');
	}

	/**
	 * Converts a basic code point into a digit/integer.
	 * @see `digitToBasic()`
	 * @private
	 * @param {Number} codePoint The basic numeric code point value.
	 * @returns {Number} The numeric value of a basic code point (for use in
	 * representing integers) in the range `0` to `base - 1`, or `base` if
	 * the code point does not represent a value.
	 */
	function basicToDigit(codePoint) {
		if (codePoint - 48 < 10) {
			return codePoint - 22;
		}
		if (codePoint - 65 < 26) {
			return codePoint - 65;
		}
		if (codePoint - 97 < 26) {
			return codePoint - 97;
		}
		return base;
	}

	/**
	 * Converts a digit/integer into a basic code point.
	 * @see `basicToDigit()`
	 * @private
	 * @param {Number} digit The numeric value of a basic code point.
	 * @returns {Number} The basic code point whose value (when used for
	 * representing integers) is `digit`, which needs to be in the range
	 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
	 * used; else, the lowercase form is used. The behavior is undefined
	 * if `flag` is non-zero and `digit` has no uppercase form.
	 */
	function digitToBasic(digit, flag) {
		//  0..25 map to ASCII a..z or A..Z
		// 26..35 map to ASCII 0..9
		return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
	}

	/**
	 * Bias adaptation function as per section 3.4 of RFC 3492.
	 * https://tools.ietf.org/html/rfc3492#section-3.4
	 * @private
	 */
	function adapt(delta, numPoints, firstTime) {
		var k = 0;
		delta = firstTime ? floor(delta / damp) : delta >> 1;
		delta += floor(delta / numPoints);
		for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
			delta = floor(delta / baseMinusTMin);
		}
		return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
	}

	/**
	 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
	 * symbols.
	 * @memberOf punycode
	 * @param {String} input The Punycode string of ASCII-only symbols.
	 * @returns {String} The resulting string of Unicode symbols.
	 */
	function decode(input) {
		// Don't use UCS-2
		var output = [],
		    inputLength = input.length,
		    out,
		    i = 0,
		    n = initialN,
		    bias = initialBias,
		    basic,
		    j,
		    index,
		    oldi,
		    w,
		    k,
		    digit,
		    t,
		    /** Cached calculation results */
		    baseMinusT;

		// Handle the basic code points: let `basic` be the number of input code
		// points before the last delimiter, or `0` if there is none, then copy
		// the first basic code points to the output.

		basic = input.lastIndexOf(delimiter);
		if (basic < 0) {
			basic = 0;
		}

		for (j = 0; j < basic; ++j) {
			// if it's not a basic code point
			if (input.charCodeAt(j) >= 0x80) {
				error('not-basic');
			}
			output.push(input.charCodeAt(j));
		}

		// Main decoding loop: start just after the last delimiter if any basic code
		// points were copied; start at the beginning otherwise.

		for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {

			// `index` is the index of the next character to be consumed.
			// Decode a generalized variable-length integer into `delta`,
			// which gets added to `i`. The overflow checking is easier
			// if we increase `i` as we go, then subtract off its starting
			// value at the end to obtain `delta`.
			for (oldi = i, w = 1, k = base; /* no condition */; k += base) {

				if (index >= inputLength) {
					error('invalid-input');
				}

				digit = basicToDigit(input.charCodeAt(index++));

				if (digit >= base || digit > floor((maxInt - i) / w)) {
					error('overflow');
				}

				i += digit * w;
				t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);

				if (digit < t) {
					break;
				}

				baseMinusT = base - t;
				if (w > floor(maxInt / baseMinusT)) {
					error('overflow');
				}

				w *= baseMinusT;

			}

			out = output.length + 1;
			bias = adapt(i - oldi, out, oldi == 0);

			// `i` was supposed to wrap around from `out` to `0`,
			// incrementing `n` each time, so we'll fix that now:
			if (floor(i / out) > maxInt - n) {
				error('overflow');
			}

			n += floor(i / out);
			i %= out;

			// Insert `n` at position `i` of the output
			output.splice(i++, 0, n);

		}

		return ucs2encode(output);
	}

	/**
	 * Converts a string of Unicode symbols (e.g. a domain name label) to a
	 * Punycode string of ASCII-only symbols.
	 * @memberOf punycode
	 * @param {String} input The string of Unicode symbols.
	 * @returns {String} The resulting Punycode string of ASCII-only symbols.
	 */
	function encode(input) {
		var n,
		    delta,
		    handledCPCount,
		    basicLength,
		    bias,
		    j,
		    m,
		    q,
		    k,
		    t,
		    currentValue,
		    output = [],
		    /** `inputLength` will hold the number of code points in `input`. */
		    inputLength,
		    /** Cached calculation results */
		    handledCPCountPlusOne,
		    baseMinusT,
		    qMinusT;

		// Convert the input in UCS-2 to Unicode
		input = ucs2decode(input);

		// Cache the length
		inputLength = input.length;

		// Initialize the state
		n = initialN;
		delta = 0;
		bias = initialBias;

		// Handle the basic code points
		for (j = 0; j < inputLength; ++j) {
			currentValue = input[j];
			if (currentValue < 0x80) {
				output.push(stringFromCharCode(currentValue));
			}
		}

		handledCPCount = basicLength = output.length;

		// `handledCPCount` is the number of code points that have been handled;
		// `basicLength` is the number of basic code points.

		// Finish the basic string - if it is not empty - with a delimiter
		if (basicLength) {
			output.push(delimiter);
		}

		// Main encoding loop:
		while (handledCPCount < inputLength) {

			// All non-basic code points < n have been handled already. Find the next
			// larger one:
			for (m = maxInt, j = 0; j < inputLength; ++j) {
				currentValue = input[j];
				if (currentValue >= n && currentValue < m) {
					m = currentValue;
				}
			}

			// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
			// but guard against overflow
			handledCPCountPlusOne = handledCPCount + 1;
			if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
				error('overflow');
			}

			delta += (m - n) * handledCPCountPlusOne;
			n = m;

			for (j = 0; j < inputLength; ++j) {
				currentValue = input[j];

				if (currentValue < n && ++delta > maxInt) {
					error('overflow');
				}

				if (currentValue == n) {
					// Represent delta as a generalized variable-length integer
					for (q = delta, k = base; /* no condition */; k += base) {
						t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
						if (q < t) {
							break;
						}
						qMinusT = q - t;
						baseMinusT = base - t;
						output.push(
							stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
						);
						q = floor(qMinusT / baseMinusT);
					}

					output.push(stringFromCharCode(digitToBasic(q, 0)));
					bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
					delta = 0;
					++handledCPCount;
				}
			}

			++delta;
			++n;

		}
		return output.join('');
	}

	/**
	 * Converts a Punycode string representing a domain name or an email address
	 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
	 * it doesn't matter if you call it on a string that has already been
	 * converted to Unicode.
	 * @memberOf punycode
	 * @param {String} input The Punycoded domain name or email address to
	 * convert to Unicode.
	 * @returns {String} The Unicode representation of the given Punycode
	 * string.
	 */
	function toUnicode(input) {
		return mapDomain(input, function(string) {
			return regexPunycode.test(string)
				? decode(string.slice(4).toLowerCase())
				: string;
		});
	}

	/**
	 * Converts a Unicode string representing a domain name or an email address to
	 * Punycode. Only the non-ASCII parts of the domain name will be converted,
	 * i.e. it doesn't matter if you call it with a domain that's already in
	 * ASCII.
	 * @memberOf punycode
	 * @param {String} input The domain name or email address to convert, as a
	 * Unicode string.
	 * @returns {String} The Punycode representation of the given domain name or
	 * email address.
	 */
	function toASCII(input) {
		return mapDomain(input, function(string) {
			return regexNonASCII.test(string)
				? 'xn--' + encode(string)
				: string;
		});
	}

	/*--------------------------------------------------------------------------*/

	/** Define the public API */
	punycode = {
		/**
		 * A string representing the current Punycode.js version number.
		 * @memberOf punycode
		 * @type String
		 */
		'version': '1.4.1',
		/**
		 * An object of methods to convert from JavaScript's internal character
		 * representation (UCS-2) to Unicode code points, and back.
		 * @see <https://mathiasbynens.be/notes/javascript-encoding>
		 * @memberOf punycode
		 * @type Object
		 */
		'ucs2': {
			'decode': ucs2decode,
			'encode': ucs2encode
		},
		'decode': decode,
		'encode': encode,
		'toASCII': toASCII,
		'toUnicode': toUnicode
	};

	/** Expose `punycode` */
	// Some AMD build optimizers, like r.js, check for specific condition patterns
	// like the following:
	if (
		true
	) {
		!(__WEBPACK_AMD_DEFINE_RESULT__ = (function() {
			return punycode;
		}).call(exports, __webpack_require__, exports, module),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {}

}(this));

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/module.js */ "YuTi")(module), __webpack_require__(/*! ./../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "ndfH":
/*!****************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/apputils/style/hoverbox.css ***!
  \****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2016, Jupyter Development Team.\n|\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.jp-HoverBox {\n  position: fixed;\n}\n\n.jp-HoverBox.jp-mod-outofview {\n  display: none;\n}\n", ""]);

// exports


/***/ }),

/***/ "nmnc":
/*!****************************************!*\
  !*** ./node_modules/lodash/_Symbol.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var root = __webpack_require__(/*! ./_root */ "Kz5y");

/** Built-in value references. */
var Symbol = root.Symbol;

module.exports = Symbol;


/***/ }),

/***/ "nrkQ":
/*!*******************************************************!*\
  !*** ./node_modules/codemirror/addon/mode/overlay.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

// Utility function that allows modes to be combined. The mode given
// as the base argument takes care of most of the normal mode
// functionality, but a second (typically simple) mode is used, which
// can override the style of text. Both modes get to parse all of the
// text, but when both assign a non-null style to a piece of code, the
// overlay wins, unless the combine argument was true and not overridden,
// or state.overlay.combineTokens was true, in which case the styles are
// combined.

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"));
  else {}
})(function(CodeMirror) {
"use strict";

CodeMirror.overlayMode = function(base, overlay, combine) {
  return {
    startState: function() {
      return {
        base: CodeMirror.startState(base),
        overlay: CodeMirror.startState(overlay),
        basePos: 0, baseCur: null,
        overlayPos: 0, overlayCur: null,
        streamSeen: null
      };
    },
    copyState: function(state) {
      return {
        base: CodeMirror.copyState(base, state.base),
        overlay: CodeMirror.copyState(overlay, state.overlay),
        basePos: state.basePos, baseCur: null,
        overlayPos: state.overlayPos, overlayCur: null
      };
    },

    token: function(stream, state) {
      if (stream != state.streamSeen ||
          Math.min(state.basePos, state.overlayPos) < stream.start) {
        state.streamSeen = stream;
        state.basePos = state.overlayPos = stream.start;
      }

      if (stream.start == state.basePos) {
        state.baseCur = base.token(stream, state.base);
        state.basePos = stream.pos;
      }
      if (stream.start == state.overlayPos) {
        stream.pos = stream.start;
        state.overlayCur = overlay.token(stream, state.overlay);
        state.overlayPos = stream.pos;
      }
      stream.pos = Math.min(state.basePos, state.overlayPos);

      // state.overlay.combineTokens always takes precedence over combine,
      // unless set to null
      if (state.overlayCur == null) return state.baseCur;
      else if (state.baseCur != null &&
               state.overlay.combineTokens ||
               combine && state.overlay.combineTokens == null)
        return state.baseCur + " " + state.overlayCur;
      else return state.overlayCur;
    },

    indent: base.indent && function(state, textAfter) {
      return base.indent(state.base, textAfter);
    },
    electricChars: base.electricChars,

    innerMode: function(state) { return {state: state.base, mode: base}; },

    blankLine: function(state) {
      var baseToken, overlayToken;
      if (base.blankLine) baseToken = base.blankLine(state.base);
      if (overlay.blankLine) overlayToken = overlay.blankLine(state.overlay);

      return overlayToken == null ?
        baseToken :
        (combine && baseToken != null ? baseToken + " " + overlayToken : overlayToken);
    }
  };
};

});


/***/ }),

/***/ "ntjm":
/*!******************************************************!*\
  !*** ./node_modules/source-map/lib/binary-search.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/* -*- Mode: js; js-indent-level: 2; -*- */
/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

exports.GREATEST_LOWER_BOUND = 1;
exports.LEAST_UPPER_BOUND = 2;

/**
 * Recursive implementation of binary search.
 *
 * @param aLow Indices here and lower do not contain the needle.
 * @param aHigh Indices here and higher do not contain the needle.
 * @param aNeedle The element being searched for.
 * @param aHaystack The non-empty array being searched.
 * @param aCompare Function which takes two elements and returns -1, 0, or 1.
 * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
 *     'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
 *     closest element that is smaller than or greater than the one we are
 *     searching for, respectively, if the exact element cannot be found.
 */
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  // This function terminates when one of the following is true:
  //
  //   1. We find the exact element we are looking for.
  //
  //   2. We did not find the exact element, but we can return the index of
  //      the next-closest element.
  //
  //   3. We did not find the exact element, and there is no next-closest
  //      element than the one we are searching for, so we return -1.
  var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  var cmp = aCompare(aNeedle, aHaystack[mid], true);
  if (cmp === 0) {
    // Found the element we are looking for.
    return mid;
  }
  else if (cmp > 0) {
    // Our needle is greater than aHaystack[mid].
    if (aHigh - mid > 1) {
      // The element is in the upper half.
      return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
    }

    // The exact needle element was not found in this haystack. Determine if
    // we are in termination case (3) or (2) and return the appropriate thing.
    if (aBias == exports.LEAST_UPPER_BOUND) {
      return aHigh < aHaystack.length ? aHigh : -1;
    } else {
      return mid;
    }
  }
  else {
    // Our needle is less than aHaystack[mid].
    if (mid - aLow > 1) {
      // The element is in the lower half.
      return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
    }

    // we are in termination case (3) or (2) and return the appropriate thing.
    if (aBias == exports.LEAST_UPPER_BOUND) {
      return mid;
    } else {
      return aLow < 0 ? -1 : aLow;
    }
  }
}

/**
 * This is an implementation of binary search which will always try and return
 * the index of the closest element if there is no exact hit. This is because
 * mappings between original and generated line/col pairs are single points,
 * and there is an implicit region between each of them, so a miss just means
 * that you aren't on the very start of a region.
 *
 * @param aNeedle The element you are looking for.
 * @param aHaystack The array that is being searched.
 * @param aCompare A function which takes the needle and an element in the
 *     array and returns -1, 0, or 1 depending on whether the needle is less
 *     than, equal to, or greater than the element, respectively.
 * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
 *     'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
 *     closest element that is smaller than or greater than the one we are
 *     searching for, respectively, if the exact element cannot be found.
 *     Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
 */
exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  if (aHaystack.length === 0) {
    return -1;
  }

  var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
                              aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  if (index < 0) {
    return -1;
  }

  // We have found either the exact element, or the next-closest element than
  // the one we are searching for. However, there may be more than one such
  // element. Make sure we always return the smallest of these.
  while (index - 1 >= 0) {
    if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
      break;
    }
    --index;
  }

  return index;
};


/***/ }),

/***/ "nwCA":
/*!**********************************************!*\
  !*** ./node_modules/mdi-react/UploadIcon.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var UploadIcon = function UploadIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M9,16V10H5L12,3L19,10H15V16H9M5,20V18H19V20H5Z' })
  );
};

module.exports = UploadIcon;


/***/ }),

/***/ "nyAU":
/*!*********************************************!*\
  !*** ./node_modules/domutils/lib/legacy.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var ElementType = __webpack_require__(/*! domelementtype */ "TR4g");
var isTag = exports.isTag = ElementType.isTag;

exports.testElement = function(options, element){
	for(var key in options){
		if(!options.hasOwnProperty(key));
		else if(key === "tag_name"){
			if(!isTag(element) || !options.tag_name(element.name)){
				return false;
			}
		} else if(key === "tag_type"){
			if(!options.tag_type(element.type)) return false;
		} else if(key === "tag_contains"){
			if(isTag(element) || !options.tag_contains(element.data)){
				return false;
			}
		} else if(!element.attribs || !options[key](element.attribs[key])){
			return false;
		}
	}
	return true;
};

var Checks = {
	tag_name: function(name){
		if(typeof name === "function"){
			return function(elem){ return isTag(elem) && name(elem.name); };
		} else if(name === "*"){
			return isTag;
		} else {
			return function(elem){ return isTag(elem) && elem.name === name; };
		}
	},
	tag_type: function(type){
		if(typeof type === "function"){
			return function(elem){ return type(elem.type); };
		} else {
			return function(elem){ return elem.type === type; };
		}
	},
	tag_contains: function(data){
		if(typeof data === "function"){
			return function(elem){ return !isTag(elem) && data(elem.data); };
		} else {
			return function(elem){ return !isTag(elem) && elem.data === data; };
		}
	}
};

function getAttribCheck(attrib, value){
	if(typeof value === "function"){
		return function(elem){ return elem.attribs && value(elem.attribs[attrib]); };
	} else {
		return function(elem){ return elem.attribs && elem.attribs[attrib] === value; };
	}
}

function combineFuncs(a, b){
	return function(elem){
		return a(elem) || b(elem);
	};
}

exports.getElements = function(options, element, recurse, limit){
	var funcs = Object.keys(options).map(function(key){
		var value = options[key];
		return key in Checks ? Checks[key](value) : getAttribCheck(key, value);
	});

	return funcs.length === 0 ? [] : this.filter(
		funcs.reduce(combineFuncs),
		element, recurse, limit
	);
};

exports.getElementById = function(id, element, recurse){
	if(!Array.isArray(element)) element = [element];
	return this.findOne(getAttribCheck("id", id), element, recurse !== false);
};

exports.getElementsByTagName = function(name, element, recurse, limit){
	return this.filter(Checks.tag_name(name), element, recurse, limit);
};

exports.getElementsByTagType = function(type, element, recurse, limit){
	return this.filter(Checks.tag_type(type), element, recurse, limit);
};


/***/ }),

/***/ "nyYc":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/fr.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var fr = moment.defineLocale('fr', {
    months : 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'),
    monthsShort : 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'),
    monthsParseExact : true,
    weekdays : 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),
    weekdaysShort : 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'),
    weekdaysMin : 'di_lu_ma_me_je_ve_sa'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay : '[Aujourd’hui à] LT',
        nextDay : '[Demain à] LT',
        nextWeek : 'dddd [à] LT',
        lastDay : '[Hier à] LT',
        lastWeek : 'dddd [dernier à] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'dans %s',
        past : 'il y a %s',
        s : 'quelques secondes',
        ss : '%d secondes',
        m : 'une minute',
        mm : '%d minutes',
        h : 'une heure',
        hh : '%d heures',
        d : 'un jour',
        dd : '%d jours',
        M : 'un mois',
        MM : '%d mois',
        y : 'un an',
        yy : '%d ans'
    },
    dayOfMonthOrdinalParse: /\d{1,2}(er|)/,
    ordinal : function (number, period) {
        switch (period) {
            // TODO: Return 'e' when day of month > 1. Move this case inside
            // block for masculine words below.
            // See https://github.com/moment/moment/issues/3375
            case 'D':
                return number + (number === 1 ? 'er' : '');

            // Words with masculine grammatical gender: mois, trimestre, jour
            default:
            case 'M':
            case 'Q':
            case 'DDD':
            case 'd':
                return number + (number === 1 ? 'er' : 'e');

            // Words with feminine grammatical gender: semaine
            case 'w':
            case 'W':
                return number + (number === 1 ? 're' : 'e');
        }
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return fr;

})));


/***/ }),

/***/ "o/tr":
/*!**********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotVolume3dIcon.js ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotVolume3dIcon = function PlotVolume3dIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M2 25l12 5V16L2 11zm16-9v14l12-5V11zM16 1L2 7l14 6 14-6z' })
    );
};

exports.default = PlotVolume3dIcon;

/***/ }),

/***/ "o1bE":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/ar-dz.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var arDz = moment.defineLocale('ar-dz', {
    months : 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),
    monthsShort : 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),
    weekdays : 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
    weekdaysShort : 'احد_اثنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'),
    weekdaysMin : 'أح_إث_ثلا_أر_خم_جم_سب'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay: '[اليوم على الساعة] LT',
        nextDay: '[غدا على الساعة] LT',
        nextWeek: 'dddd [على الساعة] LT',
        lastDay: '[أمس على الساعة] LT',
        lastWeek: 'dddd [على الساعة] LT',
        sameElse: 'L'
    },
    relativeTime : {
        future : 'في %s',
        past : 'منذ %s',
        s : 'ثوان',
        ss : '%d ثانية',
        m : 'دقيقة',
        mm : '%d دقائق',
        h : 'ساعة',
        hh : '%d ساعات',
        d : 'يوم',
        dd : '%d أيام',
        M : 'شهر',
        MM : '%d أشهر',
        y : 'سنة',
        yy : '%d سنوات'
    },
    week : {
        dow : 0, // Sunday is the first day of the week.
        doy : 4  // The week that contains Jan 1st is the first week of the year.
    }
});

return arDz;

})));


/***/ }),

/***/ "o21U":
/*!*********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/PanelEmpty.js ***!
  \*********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.PanelMessage = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _plotlyIcons = __webpack_require__(/*! plotly-icons */ "hwSx");

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var PanelMessage = exports.PanelMessage = function (_Component) {
  _inherits(PanelMessage, _Component);

  function PanelMessage() {
    _classCallCheck(this, PanelMessage);

    return _possibleConstructorReturn(this, (PanelMessage.__proto__ || Object.getPrototypeOf(PanelMessage)).apply(this, arguments));
  }

  _createClass(PanelMessage, [{
    key: 'render',
    value: function render() {
      var _props = this.props,
          children = _props.children,
          Icon = _props.icon;

      var heading = this.props.heading || '';

      return _react2.default.createElement(
        'div',
        { className: 'panel__empty__message' },
        Boolean(Icon) && _react2.default.createElement(
          'div',
          { className: 'panel__empty__message__icon' },
          _react2.default.createElement(Icon, null)
        ),
        Boolean(heading) && _react2.default.createElement(
          'div',
          { className: 'panel__empty__message__heading' },
          heading
        ),
        _react2.default.createElement(
          'div',
          { className: 'panel__empty__message__content' },
          children
        )
      );
    }
  }]);

  return PanelMessage;
}(_react.Component);

PanelMessage.defaultProps = {
  icon: _plotlyIcons.ChartLineIcon
};

PanelMessage.propTypes = {
  heading: _propTypes2.default.string,
  children: _propTypes2.default.node,
  icon: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func])
};

var PanelEmpty = function (_Component2) {
  _inherits(PanelEmpty, _Component2);

  function PanelEmpty() {
    _classCallCheck(this, PanelEmpty);

    return _possibleConstructorReturn(this, (PanelEmpty.__proto__ || Object.getPrototypeOf(PanelEmpty)).apply(this, arguments));
  }

  _createClass(PanelEmpty, [{
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        'div',
        { className: (0, _lib.bem)('panel', 'empty') },
        _react2.default.createElement(PanelMessage, this.props)
      );
    }
  }]);

  return PanelEmpty;
}(_react.Component);

PanelEmpty.propTypes = {
  heading: _propTypes2.default.string,
  children: _propTypes2.default.node,
  icon: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func])
};

exports.default = PanelEmpty;
//# sourceMappingURL=PanelEmpty.js.map

/***/ }),

/***/ "o4sl":
/*!*************************************************************!*\
  !*** ./node_modules/@jupyterlab/inspector/lib/inspector.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const disposable_1 = __webpack_require__(/*! @phosphor/disposable */ "uNUc");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
/**
 * The class name added to inspector panels.
 */
const PANEL_CLASS = 'jp-Inspector';
/**
 * The class name added to inspector child item widgets.
 */
const ITEM_CLASS = 'jp-InspectorItem';
/**
 * The class name added to inspector child item widgets' content.
 */
const CONTENT_CLASS = 'jp-InspectorItem-content';
/**
 * The history clear button class name.
 */
const CLEAR_CLASS = 'jp-InspectorItem-clear';
/**
 * The back button class name.
 */
const BACK_CLASS = 'jp-InspectorItem-back';
/**
 * The forward button class name.
 */
const FORWARD_CLASS = 'jp-InspectorItem-forward';
/* tslint:disable */
/**
 * The inspector panel token.
 */
exports.IInspector = new coreutils_1.Token('@jupyterlab/inspector:IInspector');
/**
 * A panel which contains a set of inspectors.
 */
class InspectorPanel extends widgets_1.TabPanel {
    /**
     * Construct an inspector.
     */
    constructor() {
        super();
        this._items = Object.create(null);
        this._source = null;
        this.addClass(PANEL_CLASS);
    }
    /**
     * The source of events the inspector panel listens for.
     */
    get source() {
        return this._source;
    }
    set source(source) {
        if (this._source === source) {
            return;
        }
        // Disconnect old signal handler.
        if (this._source) {
            this._source.standby = true;
            this._source.inspected.disconnect(this.onInspectorUpdate, this);
            this._source.disposed.disconnect(this.onSourceDisposed, this);
        }
        // Clear the inspector child items (but maintain history) if necessary.
        Object.keys(this._items).forEach(i => {
            this._items[i].content = null;
        });
        this._source = source;
        // Connect new signal handler.
        if (this._source) {
            this._source.standby = false;
            this._source.inspected.connect(this.onInspectorUpdate, this);
            this._source.disposed.connect(this.onSourceDisposed, this);
        }
    }
    /**
     * Create an inspector child item and return a disposable to remove it.
     *
     * @param item - The inspector child item being added to the inspector.
     *
     * @returns A disposable that removes the child item from the inspector.
     */
    add(item) {
        const widget = new InspectorItem();
        widget.rank = item.rank;
        widget.remembers = !!item.remembers;
        widget.title.closable = false;
        widget.title.label = item.name;
        if (item.className) {
            widget.addClass(item.className);
        }
        this._items[item.type] = widget;
        this.addWidget(widget);
        if (Object.keys(this._items).length < 2) {
            this.tabBar.hide();
        }
        else {
            this.tabBar.show();
        }
        return new disposable_1.DisposableDelegate(() => {
            if (widget.isDisposed || this.isDisposed) {
                return;
            }
            widget.dispose();
            delete this._items[item.type];
            if (Object.keys(this._items).length < 2) {
                this.tabBar.hide();
            }
            else {
                this.tabBar.show();
            }
        });
    }
    /**
     * Dispose of the resources held by the widget.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this.source = null;
        let items = this._items;
        // Dispose the inspector child items.
        Object.keys(items).forEach(i => {
            items[i].dispose();
        });
        super.dispose();
    }
    /**
     * Handle inspector update signals.
     */
    onInspectorUpdate(sender, args) {
        let widget = this._items[args.type];
        if (!widget) {
            return;
        }
        // Update the content of the inspector widget.
        widget.content = args.content;
        let items = this._items;
        // If any inspector with a higher rank has content, do not change focus.
        if (args.content) {
            for (let type in items) {
                let inspector = this._items[type];
                if (inspector.rank < widget.rank && inspector.content) {
                    return;
                }
            }
            this.currentWidget = widget;
            return;
        }
        // If the inspector was emptied, show the next best ranked inspector.
        let lowest = Infinity;
        let newWidget = null;
        for (let type in items) {
            let inspector = this._items[type];
            if (inspector.rank < lowest && inspector.content) {
                lowest = inspector.rank;
                newWidget = inspector;
            }
        }
        if (newWidget) {
            this.currentWidget = newWidget;
        }
    }
    /**
     * Handle source disposed signals.
     */
    onSourceDisposed(sender, args) {
        this.source = null;
    }
}
exports.InspectorPanel = InspectorPanel;
/**
 * A code inspector child widget.
 */
class InspectorItem extends widgets_1.Widget {
    /**
     * Construct an inspector widget.
     */
    constructor() {
        super();
        this._content = null;
        this._history = [];
        this._index = -1;
        this._rank = Infinity;
        this._remembers = false;
        this.layout = new widgets_1.PanelLayout();
        this.addClass(ITEM_CLASS);
        this._toolbar = this._createToolbar();
        this.layout.addWidget(this._toolbar);
    }
    /**
     * The text of the inspector.
     */
    get content() {
        return this._content;
    }
    set content(newValue) {
        if (newValue === this._content) {
            return;
        }
        if (this._content) {
            if (this._remembers) {
                this._content.hide();
            }
            else {
                this._content.dispose();
            }
        }
        this._content = newValue;
        if (newValue) {
            newValue.addClass(CONTENT_CLASS);
            this.layout.addWidget(newValue);
            if (this.remembers) {
                this._history.push(newValue);
                this._index++;
            }
        }
    }
    /**
     * A flag that indicates whether the inspector remembers history.
     */
    get remembers() {
        return this._remembers;
    }
    set remembers(newValue) {
        if (newValue === this._remembers) {
            return;
        }
        this._remembers = newValue;
        if (!newValue) {
            this._clear();
        }
        this.update();
    }
    /**
     * The display rank of the inspector.
     */
    get rank() {
        return this._rank;
    }
    set rank(newValue) {
        this._rank = newValue;
    }
    /**
     * Dispose of the resources held by the widget.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._history.forEach(widget => widget.dispose());
        this._toolbar.dispose();
        super.dispose();
    }
    /**
     * Navigate back in history.
     */
    _back() {
        if (this._history.length) {
            this._navigateTo(Math.max(this._index - 1, 0));
        }
    }
    /**
     * Clear history.
     */
    _clear() {
        this._history.forEach(widget => widget.dispose());
        this._history = [];
        this._index = -1;
    }
    /**
     * Navigate forward in history.
     */
    _forward() {
        if (this._history.length) {
            this._navigateTo(Math.min(this._index + 1, this._history.length - 1));
        }
    }
    /**
     * Create a history toolbar.
     */
    _createToolbar() {
        let toolbar = new apputils_1.Toolbar();
        if (!this._remembers) {
            return toolbar;
        }
        let clear = new apputils_1.ToolbarButton({
            iconClassName: CLEAR_CLASS + ' jp-Icon jp-Icon-16',
            onClick: () => {
                this._clear();
            },
            tooltip: 'Clear history.'
        });
        toolbar.addItem('clear', clear);
        let back = new apputils_1.ToolbarButton({
            iconClassName: BACK_CLASS + ' jp-Icon jp-Icon-16',
            onClick: () => {
                this._back();
            },
            tooltip: 'Navigate back in history.'
        });
        toolbar.addItem('back', back);
        let forward = new apputils_1.ToolbarButton({
            iconClassName: FORWARD_CLASS + ' jp-Icon jp-Icon-16',
            onClick: () => {
                this._forward();
            },
            tooltip: 'Navigate forward in history.'
        });
        toolbar.addItem('forward', forward);
        return toolbar;
    }
    /**
     * Navigate to a known index in history.
     */
    _navigateTo(index) {
        if (this._content) {
            this._content.hide();
        }
        this._content = this._history[index];
        this._index = index;
        this._content.show();
    }
}


/***/ }),

/***/ "o6FZ":
/*!**************************************************************!*\
  !*** ./node_modules/@jupyterlab/help-extension/lib/index.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const application_1 = __webpack_require__(/*! @jupyterlab/application */ "FkFl");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const mainmenu_1 = __webpack_require__(/*! @jupyterlab/mainmenu */ "N4Qf");
const React = __importStar(__webpack_require__(/*! react */ "q1tI"));
__webpack_require__(/*! ../style/index.css */ "DQoj");
/**
 * The command IDs used by the help plugin.
 */
var CommandIDs;
(function (CommandIDs) {
    CommandIDs.open = 'help:open';
    CommandIDs.about = 'help:about';
    CommandIDs.activate = 'help:activate';
    CommandIDs.close = 'help:close';
    CommandIDs.show = 'help:show';
    CommandIDs.hide = 'help:hide';
    CommandIDs.toggle = 'help:toggle';
    CommandIDs.launchClassic = 'help:launch-classic-notebook';
})(CommandIDs || (CommandIDs = {}));
/**
 * A flag denoting whether the application is loaded over HTTPS.
 */
const LAB_IS_SECURE = window.location.protocol === 'https:';
/**
 * The class name added to the help widget.
 */
const HELP_CLASS = 'jp-Help';
/**
 * A list of help resources.
 */
const RESOURCES = [
    {
        text: 'JupyterLab Reference',
        url: 'https://jupyterlab.readthedocs.io/en/stable/'
    },
    {
        text: 'Notebook Reference',
        url: 'https://jupyter-notebook.readthedocs.io/en/latest/'
    },
    {
        text: 'Markdown Reference',
        url: 'https://help.github.com/articles/' +
            'getting-started-with-writing-and-formatting-on-github/'
    }
];
RESOURCES.sort((a, b) => {
    return a.text.localeCompare(b.text);
});
/**
 * The help handler extension.
 */
const plugin = {
    activate,
    id: '@jupyterlab/help-extension:plugin',
    requires: [mainmenu_1.IMainMenu, apputils_1.ICommandPalette, application_1.ILayoutRestorer],
    autoStart: true
};
/**
 * Export the plugin as default.
 */
exports.default = plugin;
/**
 * Activate the help handler extension.
 *
 * @param app - The phosphide application object.
 *
 * returns A promise that resolves when the extension is activated.
 */
function activate(app, mainMenu, palette, restorer) {
    let counter = 0;
    const category = 'Help';
    const namespace = 'help-doc';
    const baseUrl = coreutils_1.PageConfig.getBaseUrl();
    const { commands, shell, info, serviceManager } = app;
    const tracker = new apputils_1.InstanceTracker({ namespace });
    // Handle state restoration.
    restorer.restore(tracker, {
        command: CommandIDs.open,
        args: widget => ({
            url: widget.content.url,
            text: widget.content.title.label
        }),
        name: widget => widget.content.url
    });
    /**
     * Create a new HelpWidget widget.
     */
    function newHelpWidget(url, text) {
        let content = new apputils_1.IFrame();
        content.url = url;
        content.addClass(HELP_CLASS);
        content.title.label = text;
        content.id = `${namespace}-${++counter}`;
        let widget = new apputils_1.MainAreaWidget({ content });
        widget.addClass('jp-Help');
        return widget;
    }
    // Populate the Help menu.
    const helpMenu = mainMenu.helpMenu;
    const labGroup = [
        CommandIDs.about,
        'faq-jupyterlab:open',
        CommandIDs.launchClassic
    ].map(command => {
        return { command };
    });
    helpMenu.addGroup(labGroup, 0);
    const resourcesGroup = RESOURCES.map(args => ({
        args,
        command: CommandIDs.open
    }));
    helpMenu.addGroup(resourcesGroup, 10);
    // Generate a cache of the kernel help links.
    const kernelInfoCache = new Map();
    serviceManager.sessions.runningChanged.connect((m, sessions) => {
        // If a new session has been added, it is at the back
        // of the session list. If one has changed or stopped,
        // it does not hurt to check it.
        if (!sessions.length) {
            return;
        }
        const sessionModel = sessions[sessions.length - 1];
        if (kernelInfoCache.has(sessionModel.kernel.name)) {
            return;
        }
        const session = serviceManager.sessions.connectTo(sessionModel);
        session.kernel.ready.then(() => {
            // Check the cache second time so that, if two callbacks get scheduled,
            // they don't try to add the same commands.
            if (kernelInfoCache.has(sessionModel.kernel.name)) {
                return;
            }
            // Set the Kernel Info cache.
            const name = session.kernel.name;
            const kernelInfo = session.kernel.info;
            kernelInfoCache.set(name, kernelInfo);
            // Utility function to check if the current widget
            // has registered itself with the help menu.
            const usesKernel = () => {
                let result = false;
                const widget = app.shell.currentWidget;
                if (!widget) {
                    return result;
                }
                helpMenu.kernelUsers.forEach(u => {
                    if (u.tracker.has(widget) &&
                        u.getKernel(widget) &&
                        u.getKernel(widget).name === name) {
                        result = true;
                    }
                });
                return result;
            };
            // Add the kernel banner to the Help Menu.
            const bannerCommand = `help-menu-${name}:banner`;
            const spec = serviceManager.specs.kernelspecs[name];
            const kernelName = spec.display_name;
            let kernelIconUrl = spec.resources['logo-64x64'];
            if (kernelIconUrl) {
                let index = kernelIconUrl.indexOf('kernelspecs');
                kernelIconUrl = baseUrl + kernelIconUrl.slice(index);
            }
            commands.addCommand(bannerCommand, {
                label: `About the ${kernelName} Kernel`,
                isVisible: usesKernel,
                isEnabled: usesKernel,
                execute: () => {
                    // Create the header of the about dialog
                    let headerLogo = React.createElement("img", { src: kernelIconUrl });
                    let title = (React.createElement("span", { className: "jp-About-header" },
                        headerLogo,
                        React.createElement("div", { className: "jp-About-header-info" }, kernelName)));
                    const banner = React.createElement("pre", null, kernelInfo.banner);
                    let body = React.createElement("div", { className: "jp-About-body" }, banner);
                    apputils_1.showDialog({
                        title,
                        body,
                        buttons: [
                            apputils_1.Dialog.createButton({
                                label: 'DISMISS',
                                className: 'jp-About-button jp-mod-reject jp-mod-styled'
                            })
                        ]
                    });
                }
            });
            helpMenu.addGroup([{ command: bannerCommand }], 20);
            // Add the kernel info help_links to the Help menu.
            const kernelGroup = [];
            (session.kernel.info.help_links || []).forEach(link => {
                const commandId = `help-menu-${name}:${link.text}`;
                commands.addCommand(commandId, {
                    label: link.text,
                    isVisible: usesKernel,
                    isEnabled: usesKernel,
                    execute: () => {
                        commands.execute(CommandIDs.open, link);
                    }
                });
                kernelGroup.push({ command: commandId });
            });
            helpMenu.addGroup(kernelGroup, 21);
            // Dispose of the session object since we no longer need it.
            session.dispose();
        });
    });
    commands.addCommand(CommandIDs.about, {
        label: `About ${info.name}`,
        execute: () => {
            // Create the header of the about dialog
            let headerLogo = React.createElement("div", { className: "jp-About-header-logo" });
            let headerWordmark = React.createElement("div", { className: "jp-About-header-wordmark" });
            let versionNumber = `Version ${info.version}`;
            let versionInfo = (React.createElement("span", { className: "jp-About-version-info" },
                React.createElement("span", { className: "jp-About-version" }, versionNumber)));
            let title = (React.createElement("span", { className: "jp-About-header" },
                headerLogo,
                React.createElement("div", { className: "jp-About-header-info" },
                    headerWordmark,
                    versionInfo)));
            // Create the body of the about dialog
            let jupyterURL = 'https://jupyter.org/about.html';
            let contributorsURL = 'https://github.com/jupyterlab/jupyterlab/graphs/contributors';
            let externalLinks = (React.createElement("span", { className: "jp-About-externalLinks" },
                React.createElement("a", { href: contributorsURL, target: "_blank", className: "jp-Button-flat" }, "CONTRIBUTOR LIST"),
                React.createElement("a", { href: jupyterURL, target: "_blank", className: "jp-Button-flat" }, "ABOUT PROJECT JUPYTER")));
            let copyright = (React.createElement("span", { className: "jp-About-copyright" }, "\u00A9 2015 Project Jupyter Contributors"));
            let body = (React.createElement("div", { className: "jp-About-body" },
                externalLinks,
                copyright));
            apputils_1.showDialog({
                title,
                body,
                buttons: [
                    apputils_1.Dialog.createButton({
                        label: 'DISMISS',
                        className: 'jp-About-button jp-mod-reject jp-mod-styled'
                    })
                ]
            });
        }
    });
    commands.addCommand(CommandIDs.open, {
        label: args => args['text'],
        execute: args => {
            const url = args['url'];
            const text = args['text'];
            // If help resource will generate a mixed content error, load externally.
            if (LAB_IS_SECURE && coreutils_1.URLExt.parse(url).protocol !== 'https:') {
                window.open(url);
                return;
            }
            let widget = newHelpWidget(url, text);
            tracker.add(widget);
            shell.addToMainArea(widget);
        }
    });
    commands.addCommand(CommandIDs.launchClassic, {
        label: 'Launch Classic Notebook',
        execute: () => {
            window.open(coreutils_1.PageConfig.getBaseUrl() + 'tree');
        }
    });
    RESOURCES.forEach(args => {
        palette.addItem({ args, command: CommandIDs.open, category });
    });
    palette.addItem({ command: 'apputils:reset', category });
    palette.addItem({ command: CommandIDs.launchClassic, category });
}


/***/ }),

/***/ "o7Pk":
/*!**************************************************!*\
  !*** ./node_modules/mdi-react/FileExportIcon.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var FileExportIcon = function FileExportIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M6,2C4.89,2 4,2.9 4,4V20C4,21.1 4.9,22 6,22H18C19.1,22 20,21.1 20,20V8L14,2M13,3.5L18.5,9H13M8.93,12.22H16V19.29L13.88,17.17L11.05,20L8.22,17.17L11.05,14.35' })
  );
};

module.exports = FileExportIcon;


/***/ }),

/***/ "o8NH":
/*!*******************************************************************!*\
  !*** ./node_modules/core-js/library/modules/es6.object.assign.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.3.1 Object.assign(target, source)
var $export = __webpack_require__(/*! ./_export */ "Y7ZC");

$export($export.S + $export.F, 'Object', { assign: __webpack_require__(/*! ./_object-assign */ "kwZ1") });


/***/ }),

/***/ "o9P/":
/*!*********************************************************!*\
  !*** ./node_modules/@jupyter-widgets/base/lib/utils.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var base64_js_1 = __webpack_require__(/*! base64-js */ "H7XF");
var coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
var _isEqual = __webpack_require__(/*! lodash/isEqual */ "Y+p1");
var isPlainObject = __webpack_require__(/*! lodash/isPlainObject */ "YO3V");
/**
 * Find all strings in the first argument that are not in the second.
 */
function difference(a, b) {
    return a.filter(function (v) { return b.indexOf(v) === -1; });
}
exports.difference = difference;
/**
 * Compare two objects deeply to see if they are equal.
 */
function isEqual(a, b) {
    return _isEqual(a, b);
}
exports.isEqual = isEqual;
/**
 * A polyfill for Object.assign
 *
 * This is from code that Typescript 2.4 generates for a polyfill.
 */
exports.assign = Object.assign || function (t) {
    for (var i = 1; i < arguments.length; i++) {
        var s = arguments[i];
        for (var p in s) {
            if (Object.prototype.hasOwnProperty.call(s, p)) {
                t[p] = s[p];
            }
        }
    }
    return t;
};
/**
 * Generate a UUID
 *
 * http://www.ietf.org/rfc/rfc4122.txt
 */
function uuid() {
    return coreutils_1.UUID.uuid4();
}
exports.uuid = uuid;
/**
 * Wrappable Error class
 *
 * The Error class doesn't actually act on `this`.  Instead it always
 * returns a new instance of Error.  Here we capture that instance so we
 * can apply it's properties to `this`.
 */
var WrappedError = /** @class */ (function (_super) {
    __extends(WrappedError, _super);
    function WrappedError(message, error) {
        var _this = _super.call(this, message) || this;
        console.warn('WrappedError has been deprecated!');
        // Keep a stack of the original error messages.
        if (error instanceof WrappedError) {
            _this.error_stack = error.error_stack;
        }
        else {
            _this.error_stack = [error];
        }
        _this.error_stack.push(_this);
        return _this;
    }
    return WrappedError;
}(Error));
exports.WrappedError = WrappedError;
/**
 * Resolve a promiseful dictionary.
 * Returns a single Promise.
 */
function resolvePromisesDict(d) {
    var keys = Object.keys(d);
    var values = [];
    keys.forEach(function (key) {
        values.push(d[key]);
    });
    return Promise.all(values).then(function (v) {
        d = {};
        for (var i = 0; i < keys.length; i++) {
            d[keys[i]] = v[i];
        }
        return d;
    });
}
exports.resolvePromisesDict = resolvePromisesDict;
/**
 * Creates a wrappable Promise rejection function.
 *
 * Creates a function that logs an error message before rethrowing
 * the original error that caused the promise to reject.
 */
function reject(message, log) {
    return function promiseRejection(error) {
        if (log) {
            console.error(new Error(message));
        }
        throw error;
    };
}
exports.reject = reject;
/**
 * Takes an object 'state' and fills in buffer[i] at 'path' buffer_paths[i]
 * where buffer_paths[i] is a list indicating where in the object buffer[i] should
 * be placed
 * Example: state = {a: 1, b: {}, c: [0, null]}
 * buffers = [array1, array2]
 * buffer_paths = [['b', 'data'], ['c', 1]]
 * Will lead to {a: 1, b: {data: array1}, c: [0, array2]}
 */
function put_buffers(state, buffer_paths, buffers) {
    for (var i = 0; i < buffer_paths.length; i++) {
        var buffer_path = buffer_paths[i];
        // say we want to set state[x][y][z] = buffers[i]
        var obj = state;
        // we first get obj = state[x][y]
        for (var j = 0; j < buffer_path.length - 1; j++) {
            obj = obj[buffer_path[j]];
        }
        // and then set: obj[z] = buffers[i]
        obj[buffer_path[buffer_path.length - 1]] = buffers[i];
    }
}
exports.put_buffers = put_buffers;
/**
 * The inverse of put_buffers, return an objects with the new state where all buffers(ArrayBuffer)
 * are removed. If a buffer is a member of an object, that object is cloned, and the key removed. If a buffer
 * is an element of an array, that array is cloned, and the element is set to null.
 * See put_buffers for the meaning of buffer_paths
 * Returns an object with the new state (.state) an array with paths to the buffers (.buffer_paths),
 * and the buffers associated to those paths (.buffers).
 */
function remove_buffers(state) {
    var buffers = [];
    var buffer_paths = [];
    // if we need to remove an object from a list, we need to clone that list, otherwise we may modify
    // the internal state of the widget model
    // however, we do not want to clone everything, for performance
    function remove(obj, path) {
        if (obj.toJSON) {
            // We need to get the JSON form of the object before recursing.
            // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON()_behavior
            obj = obj.toJSON();
        }
        if (Array.isArray(obj)) {
            var is_cloned = false;
            for (var i = 0; i < obj.length; i++) {
                var value = obj[i];
                if (value) {
                    if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
                        if (!is_cloned) {
                            obj = obj.slice();
                            is_cloned = true;
                        }
                        buffers.push(ArrayBuffer.isView(value) ? value.buffer : value);
                        buffer_paths.push(path.concat([i]));
                        // easier to just keep the array, but clear the entry, otherwise we have to think
                        // about array length, much easier this way
                        obj[i] = null;
                    }
                    else {
                        var new_value = remove(value, path.concat([i]));
                        // only assigned when the value changes, we may serialize objects that don't support assignment
                        if (new_value !== value) {
                            if (!is_cloned) {
                                obj = obj.slice();
                                is_cloned = true;
                            }
                            obj[i] = new_value;
                        }
                    }
                }
            }
        }
        else if (isPlainObject(obj)) {
            for (var key in obj) {
                var is_cloned = false;
                if (obj.hasOwnProperty(key)) {
                    var value = obj[key];
                    if (value) {
                        if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
                            if (!is_cloned) {
                                obj = __assign({}, obj);
                                is_cloned = true;
                            }
                            buffers.push(ArrayBuffer.isView(value) ? value.buffer : value);
                            buffer_paths.push(path.concat([key]));
                            delete obj[key]; // for objects/dicts we just delete them
                        }
                        else {
                            var new_value = remove(value, path.concat([key]));
                            // only assigned when the value changes, we may serialize objects that don't support assignment
                            if (new_value !== value) {
                                if (!is_cloned) {
                                    obj = __assign({}, obj);
                                    is_cloned = true;
                                }
                                obj[key] = new_value;
                            }
                        }
                    }
                }
            }
        }
        return obj;
    }
    var new_state = remove(state, []);
    return { state: new_state, buffers: buffers, buffer_paths: buffer_paths };
}
exports.remove_buffers = remove_buffers;
var hexTable = [
    '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0A', '0B', '0C', '0D', '0E', '0F',
    '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1A', '1B', '1C', '1D', '1E', '1F',
    '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2A', '2B', '2C', '2D', '2E', '2F',
    '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3A', '3B', '3C', '3D', '3E', '3F',
    '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4A', '4B', '4C', '4D', '4E', '4F',
    '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5A', '5B', '5C', '5D', '5E', '5F',
    '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6A', '6B', '6C', '6D', '6E', '6F',
    '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7A', '7B', '7C', '7D', '7E', '7F',
    '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8A', '8B', '8C', '8D', '8E', '8F',
    '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9A', '9B', '9C', '9D', '9E', '9F',
    'A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF',
    'B0', 'B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B9', 'BA', 'BB', 'BC', 'BD', 'BE', 'BF',
    'C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'CA', 'CB', 'CC', 'CD', 'CE', 'CF',
    'D0', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'DA', 'DB', 'DC', 'DD', 'DE', 'DF',
    'E0', 'E1', 'E2', 'E3', 'E4', 'E5', 'E6', 'E7', 'E8', 'E9', 'EA', 'EB', 'EC', 'ED', 'EE', 'EF',
    'F0', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'FA', 'FB', 'FC', 'FD', 'FE', 'FF'
];
/**
 * Convert an ArrayBuffer to a hex string.
 */
function bufferToHex(buffer) {
    var x = new Uint8Array(buffer);
    var s = [];
    for (var i = 0; i < x.length; i++) {
        s.push(hexTable[x[i]]);
    }
    return s.join('');
}
exports.bufferToHex = bufferToHex;
/**
 * Convert a hex string to an ArrayBuffer.
 */
function hexToBuffer(hex) {
    var x = new Uint8Array(hex.length / 2);
    for (var i = 0; i < hex.length; i += 2) {
        x[i / 2] = parseInt(hex.slice(i, i + 2), 16);
    }
    return x.buffer;
}
exports.hexToBuffer = hexToBuffer;
/**
 * Convert an ArrayBuffer to a base64 string.
 */
function bufferToBase64(buffer) {
    return base64_js_1.fromByteArray(new Uint8Array(buffer));
}
exports.bufferToBase64 = bufferToBase64;
/**
 * Convert a base64 string to an ArrayBuffer.
 */
function base64ToBuffer(base64) {
    return base64_js_1.toByteArray(base64).buffer;
}
exports.base64ToBuffer = base64ToBuffer;


/***/ }),

/***/ "oBF0":
/*!*************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/stats.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




var isNumeric = __webpack_require__(/*! fast-isnumeric */ "GbLo");
var isArrayOrTypedArray = __webpack_require__(/*! ./array */ "avjU").isArrayOrTypedArray;

/**
 * aggNums() returns the result of an aggregate function applied to an array of
 * values, where non-numerical values have been tossed out.
 *
 * @param {function} f - aggregation function (e.g., Math.min)
 * @param {Number} v - initial value (continuing from previous calls)
 *      if there's no continuing value, use null for selector-type
 *      functions (max,min), or 0 for summations
 * @param {Array} a - array to aggregate (may be nested, we will recurse,
 *                    but all elements must have the same dimension)
 * @param {Number} len - maximum length of a to aggregate
 * @return {Number} - result of f applied to a starting from v
 */
exports.aggNums = function(f, v, a, len) {
    var i,
        b;
    if(!len || len > a.length) len = a.length;
    if(!isNumeric(v)) v = false;
    if(isArrayOrTypedArray(a[0])) {
        b = new Array(len);
        for(i = 0; i < len; i++) b[i] = exports.aggNums(f, v, a[i]);
        a = b;
    }

    for(i = 0; i < len; i++) {
        if(!isNumeric(v)) v = a[i];
        else if(isNumeric(a[i])) v = f(+v, +a[i]);
    }
    return v;
};

/**
 * mean & std dev functions using aggNums, so it handles non-numerics nicely
 * even need to use aggNums instead of .length, to toss out non-numerics
 */
exports.len = function(data) {
    return exports.aggNums(function(a) { return a + 1; }, 0, data);
};

exports.mean = function(data, len) {
    if(!len) len = exports.len(data);
    return exports.aggNums(function(a, b) { return a + b; }, 0, data) / len;
};

exports.midRange = function(numArr) {
    if(numArr === undefined || numArr.length === 0) return undefined;
    return (exports.aggNums(Math.max, null, numArr) + exports.aggNums(Math.min, null, numArr)) / 2;
};

exports.variance = function(data, len, mean) {
    if(!len) len = exports.len(data);
    if(!isNumeric(mean)) mean = exports.mean(data, len);

    return exports.aggNums(function(a, b) {
        return a + Math.pow(b - mean, 2);
    }, 0, data) / len;
};

exports.stdev = function(data, len, mean) {
    return Math.sqrt(exports.variance(data, len, mean));
};

/**
 * interp() computes a percentile (quantile) for a given distribution.
 * We interpolate the distribution (to compute quantiles, we follow method #10 here:
 * http://www.amstat.org/publications/jse/v14n3/langford.html).
 * Typically the index or rank (n * arr.length) may be non-integer.
 * For reference: ends are clipped to the extreme values in the array;
 * For box plots: index you get is half a point too high (see
 * http://en.wikipedia.org/wiki/Percentile#Nearest_rank) but note that this definition
 * indexes from 1 rather than 0, so we subtract 1/2 (instead of add).
 *
 * @param {Array} arr - This array contains the values that make up the distribution.
 * @param {Number} n - Between 0 and 1, n = p/100 is such that we compute the p^th percentile.
 * For example, the 50th percentile (or median) corresponds to n = 0.5
 * @return {Number} - percentile
 */
exports.interp = function(arr, n) {
    if(!isNumeric(n)) throw 'n should be a finite number';
    n = n * arr.length - 0.5;
    if(n < 0) return arr[0];
    if(n > arr.length - 1) return arr[arr.length - 1];
    var frac = n % 1;
    return frac * arr[Math.ceil(n)] + (1 - frac) * arr[Math.floor(n)];
};


/***/ }),

/***/ "oCl/":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_getSymbolsIn.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var arrayPush = __webpack_require__(/*! ./_arrayPush */ "CH3K"),
    getPrototype = __webpack_require__(/*! ./_getPrototype */ "LcsW"),
    getSymbols = __webpack_require__(/*! ./_getSymbols */ "MvSz"),
    stubArray = __webpack_require__(/*! ./stubArray */ "0ycA");

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;

/**
 * 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;
};

module.exports = getSymbolsIn;


/***/ }),

/***/ "oDlj":
/*!**************************************************************!*\
  !*** ./node_modules/@jupyterlab/docregistry/style/index.css ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "mYkm");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "oFr5":
/*!********************************************!*\
  !*** ./node_modules/mdi-react/PlayIcon.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var PlayIcon = function PlayIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M8,5.14V19.14L19,12.14L8,5.14Z' })
  );
};

module.exports = PlayIcon;


/***/ }),

/***/ "oJl4":
/*!****************************************!*\
  !*** ./node_modules/pbkdf2/browser.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports.pbkdf2 = __webpack_require__(/*! ./lib/async */ "IG1u")
exports.pbkdf2Sync = __webpack_require__(/*! ./lib/sync */ "4Hv8")


/***/ }),

/***/ "oMAC":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/codeeditor/lib/editor.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const observables_1 = __webpack_require__(/*! @jupyterlab/observables */ "V4vH");
/**
 * A namespace for code editors.
 *
 * #### Notes
 * - A code editor is a set of common assumptions which hold for all concrete editors.
 * - Changes in implementations of the code editor should only be caused by changes in concrete editors.
 * - Common JLab services which are based on the code editor should belong to `IEditorServices`.
 */
var CodeEditor;
(function (CodeEditor) {
    /**
     * The default selection style.
     */
    CodeEditor.defaultSelectionStyle = {
        className: '',
        displayName: '',
        color: 'black'
    };
    /**
     * The default implementation of the editor model.
     */
    class Model {
        /**
         * Construct a new Model.
         */
        constructor(options) {
            this._isDisposed = false;
            this._mimeTypeChanged = new signaling_1.Signal(this);
            options = options || {};
            if (options.modelDB) {
                this.modelDB = options.modelDB;
            }
            else {
                this.modelDB = new observables_1.ModelDB();
            }
            let value = this.modelDB.createString('value');
            value.text = value.text || options.value || '';
            let mimeType = this.modelDB.createValue('mimeType');
            mimeType.set(options.mimeType || 'text/plain');
            mimeType.changed.connect(this._onMimeTypeChanged, this);
            this.modelDB.createMap('selections');
        }
        /**
         * A signal emitted when a mimetype changes.
         */
        get mimeTypeChanged() {
            return this._mimeTypeChanged;
        }
        /**
         * Get the value of the model.
         */
        get value() {
            return this.modelDB.get('value');
        }
        /**
         * Get the selections for the model.
         */
        get selections() {
            return this.modelDB.get('selections');
        }
        /**
         * A mime type of the model.
         */
        get mimeType() {
            return this.modelDB.getValue('mimeType');
        }
        set mimeType(newValue) {
            const oldValue = this.mimeType;
            if (oldValue === newValue) {
                return;
            }
            this.modelDB.setValue('mimeType', newValue);
        }
        /**
         * Whether the model is disposed.
         */
        get isDisposed() {
            return this._isDisposed;
        }
        /**
         * Dispose of the resources used by the model.
         */
        dispose() {
            if (this._isDisposed) {
                return;
            }
            this._isDisposed = true;
            signaling_1.Signal.clearData(this);
        }
        _onMimeTypeChanged(mimeType, args) {
            this._mimeTypeChanged.emit({
                name: 'mimeType',
                oldValue: args.oldValue,
                newValue: args.newValue
            });
        }
    }
    CodeEditor.Model = Model;
    /**
     * The default configuration options for an editor.
     */
    CodeEditor.defaultConfig = {
        fontFamily: null,
        fontSize: null,
        lineHeight: null,
        lineNumbers: false,
        lineWrap: 'on',
        wordWrapColumn: 80,
        readOnly: false,
        tabSize: 4,
        insertSpaces: true,
        matchBrackets: true,
        autoClosingBrackets: true
    };
})(CodeEditor = exports.CodeEditor || (exports.CodeEditor = {}));


/***/ }),

/***/ "oPLb":
/*!********************************************************************!*\
  !*** ./node_modules/react-color/lib/components/compact/Compact.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Compact = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _map = __webpack_require__(/*! lodash/map */ "3WF5");

var _map2 = _interopRequireDefault(_map);

var _merge = __webpack_require__(/*! lodash/merge */ "QkVN");

var _merge2 = _interopRequireDefault(_merge);

var _color = __webpack_require__(/*! ../../helpers/color */ "p8yl");

var _color2 = _interopRequireDefault(_color);

var _common = __webpack_require__(/*! ../common */ "TM95");

var _CompactColor = __webpack_require__(/*! ./CompactColor */ "ZQT/");

var _CompactColor2 = _interopRequireDefault(_CompactColor);

var _CompactFields = __webpack_require__(/*! ./CompactFields */ "8J/B");

var _CompactFields2 = _interopRequireDefault(_CompactFields);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var Compact = exports.Compact = function Compact(_ref) {
  var onChange = _ref.onChange,
      onSwatchHover = _ref.onSwatchHover,
      colors = _ref.colors,
      hex = _ref.hex,
      rgb = _ref.rgb,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': {
      Compact: {
        background: '#f6f6f6',
        radius: '4px'
      },
      compact: {
        paddingTop: '5px',
        paddingLeft: '5px',
        boxSizing: 'initial',
        width: '240px'
      },
      clear: {
        clear: 'both'
      }
    }
  }, passedStyles));

  var handleChange = function handleChange(data, e) {
    if (data.hex) {
      _color2.default.isValidHex(data.hex) && onChange({
        hex: data.hex,
        source: 'hex'
      }, e);
    } else {
      onChange(data, e);
    }
  };

  return _react2.default.createElement(
    _common.Raised,
    { style: styles.Compact, styles: passedStyles },
    _react2.default.createElement(
      'div',
      { style: styles.compact, className: 'compact-picker ' + className },
      _react2.default.createElement(
        'div',
        null,
        (0, _map2.default)(colors, function (c) {
          return _react2.default.createElement(_CompactColor2.default, {
            key: c,
            color: c,
            active: c.toLowerCase() === hex,
            onClick: handleChange,
            onSwatchHover: onSwatchHover
          });
        }),
        _react2.default.createElement('div', { style: styles.clear })
      ),
      _react2.default.createElement(_CompactFields2.default, { hex: hex, rgb: rgb, onChange: handleChange })
    )
  );
};

Compact.propTypes = {
  colors: _propTypes2.default.arrayOf(_propTypes2.default.string),
  styles: _propTypes2.default.object
};

Compact.defaultProps = {
  colors: ['#4D4D4D', '#999999', '#FFFFFF', '#F44E3B', '#FE9200', '#FCDC00', '#DBDF00', '#A4DD00', '#68CCCA', '#73D8FF', '#AEA1FF', '#FDA1FF', '#333333', '#808080', '#cccccc', '#D33115', '#E27300', '#FCC400', '#B0BC00', '#68BC00', '#16A5A5', '#009CE0', '#7B64FF', '#FA28FF', '#000000', '#666666', '#B3B3B3', '#9F0500', '#C45100', '#FB9E00', '#808900', '#194D33', '#0C797D', '#0062B1', '#653294', '#AB149E'],
  styles: {}
};

exports.default = (0, _common.ColorWrap)(Compact);

/***/ }),

/***/ "oPSa":
/*!*************************************************************!*\
  !*** ./node_modules/draft-js/lib/DraftFeatureFlags-core.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DraftFeatureFlags-core
 * @format
 * 
 */



var DraftFeatureFlags = {
  draft_killswitch_allow_nontextnodes: false,
  draft_segmented_entities_behavior: false,
  draft_handlebeforeinput_composed_text: false,
  draft_tree_data_support: false
};

module.exports = DraftFeatureFlags;

/***/ }),

/***/ "oQJG":
/*!*****************************************************!*\
  !*** ./node_modules/xterm/lib/CompositionHelper.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var CompositionHelper = (function () {
    function CompositionHelper(_textarea, _compositionView, _terminal) {
        this._textarea = _textarea;
        this._compositionView = _compositionView;
        this._terminal = _terminal;
        this._isComposing = false;
        this._isSendingComposition = false;
        this._compositionPosition = { start: null, end: null };
    }
    CompositionHelper.prototype.compositionstart = function () {
        this._isComposing = true;
        this._compositionPosition.start = this._textarea.value.length;
        this._compositionView.textContent = '';
        this._compositionView.classList.add('active');
    };
    CompositionHelper.prototype.compositionupdate = function (ev) {
        var _this = this;
        this._compositionView.textContent = ev.data;
        this.updateCompositionElements();
        setTimeout(function () {
            _this._compositionPosition.end = _this._textarea.value.length;
        }, 0);
    };
    CompositionHelper.prototype.compositionend = function () {
        this._finalizeComposition(true);
    };
    CompositionHelper.prototype.keydown = function (ev) {
        if (this._isComposing || this._isSendingComposition) {
            if (ev.keyCode === 229) {
                return false;
            }
            else if (ev.keyCode === 16 || ev.keyCode === 17 || ev.keyCode === 18) {
                return false;
            }
            else {
                this._finalizeComposition(false);
            }
        }
        if (ev.keyCode === 229) {
            this._handleAnyTextareaChanges();
            return false;
        }
        return true;
    };
    CompositionHelper.prototype._finalizeComposition = function (waitForPropogation) {
        var _this = this;
        this._compositionView.classList.remove('active');
        this._isComposing = false;
        this._clearTextareaPosition();
        if (!waitForPropogation) {
            this._isSendingComposition = false;
            var input = this._textarea.value.substring(this._compositionPosition.start, this._compositionPosition.end);
            this._terminal.handler(input);
        }
        else {
            var currentCompositionPosition_1 = {
                start: this._compositionPosition.start,
                end: this._compositionPosition.end
            };
            this._isSendingComposition = true;
            setTimeout(function () {
                if (_this._isSendingComposition) {
                    _this._isSendingComposition = false;
                    var input = void 0;
                    if (_this._isComposing) {
                        input = _this._textarea.value.substring(currentCompositionPosition_1.start, currentCompositionPosition_1.end);
                    }
                    else {
                        input = _this._textarea.value.substring(currentCompositionPosition_1.start);
                    }
                    _this._terminal.handler(input);
                }
            }, 0);
        }
    };
    CompositionHelper.prototype._handleAnyTextareaChanges = function () {
        var _this = this;
        var oldValue = this._textarea.value;
        setTimeout(function () {
            if (!_this._isComposing) {
                var newValue = _this._textarea.value;
                var diff = newValue.replace(oldValue, '');
                if (diff.length > 0) {
                    _this._terminal.handler(diff);
                }
            }
        }, 0);
    };
    CompositionHelper.prototype.updateCompositionElements = function (dontRecurse) {
        var _this = this;
        if (!this._isComposing) {
            return;
        }
        if (this._terminal.buffer.isCursorInViewport) {
            var cellHeight = Math.ceil(this._terminal.charMeasure.height * this._terminal.options.lineHeight);
            var cursorTop = this._terminal.buffer.y * cellHeight;
            var cursorLeft = this._terminal.buffer.x * this._terminal.charMeasure.width;
            this._compositionView.style.left = cursorLeft + 'px';
            this._compositionView.style.top = cursorTop + 'px';
            this._compositionView.style.height = cellHeight + 'px';
            this._compositionView.style.lineHeight = cellHeight + 'px';
            var compositionViewBounds = this._compositionView.getBoundingClientRect();
            this._textarea.style.left = cursorLeft + 'px';
            this._textarea.style.top = cursorTop + 'px';
            this._textarea.style.width = compositionViewBounds.width + 'px';
            this._textarea.style.height = compositionViewBounds.height + 'px';
            this._textarea.style.lineHeight = compositionViewBounds.height + 'px';
        }
        if (!dontRecurse) {
            setTimeout(function () { return _this.updateCompositionElements(true); }, 0);
        }
    };
    CompositionHelper.prototype._clearTextareaPosition = function () {
        this._textarea.style.left = '';
        this._textarea.style.top = '';
    };
    return CompositionHelper;
}());
exports.CompositionHelper = CompositionHelper;

//# sourceMappingURL=CompositionHelper.js.map


/***/ }),

/***/ "oV0L":
/*!*********************************************!*\
  !*** ./node_modules/xterm/lib/CharWidth.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.wcwidth = (function (opts) {
    var COMBINING_BMP = [
        [0x0300, 0x036F], [0x0483, 0x0486], [0x0488, 0x0489],
        [0x0591, 0x05BD], [0x05BF, 0x05BF], [0x05C1, 0x05C2],
        [0x05C4, 0x05C5], [0x05C7, 0x05C7], [0x0600, 0x0603],
        [0x0610, 0x0615], [0x064B, 0x065E], [0x0670, 0x0670],
        [0x06D6, 0x06E4], [0x06E7, 0x06E8], [0x06EA, 0x06ED],
        [0x070F, 0x070F], [0x0711, 0x0711], [0x0730, 0x074A],
        [0x07A6, 0x07B0], [0x07EB, 0x07F3], [0x0901, 0x0902],
        [0x093C, 0x093C], [0x0941, 0x0948], [0x094D, 0x094D],
        [0x0951, 0x0954], [0x0962, 0x0963], [0x0981, 0x0981],
        [0x09BC, 0x09BC], [0x09C1, 0x09C4], [0x09CD, 0x09CD],
        [0x09E2, 0x09E3], [0x0A01, 0x0A02], [0x0A3C, 0x0A3C],
        [0x0A41, 0x0A42], [0x0A47, 0x0A48], [0x0A4B, 0x0A4D],
        [0x0A70, 0x0A71], [0x0A81, 0x0A82], [0x0ABC, 0x0ABC],
        [0x0AC1, 0x0AC5], [0x0AC7, 0x0AC8], [0x0ACD, 0x0ACD],
        [0x0AE2, 0x0AE3], [0x0B01, 0x0B01], [0x0B3C, 0x0B3C],
        [0x0B3F, 0x0B3F], [0x0B41, 0x0B43], [0x0B4D, 0x0B4D],
        [0x0B56, 0x0B56], [0x0B82, 0x0B82], [0x0BC0, 0x0BC0],
        [0x0BCD, 0x0BCD], [0x0C3E, 0x0C40], [0x0C46, 0x0C48],
        [0x0C4A, 0x0C4D], [0x0C55, 0x0C56], [0x0CBC, 0x0CBC],
        [0x0CBF, 0x0CBF], [0x0CC6, 0x0CC6], [0x0CCC, 0x0CCD],
        [0x0CE2, 0x0CE3], [0x0D41, 0x0D43], [0x0D4D, 0x0D4D],
        [0x0DCA, 0x0DCA], [0x0DD2, 0x0DD4], [0x0DD6, 0x0DD6],
        [0x0E31, 0x0E31], [0x0E34, 0x0E3A], [0x0E47, 0x0E4E],
        [0x0EB1, 0x0EB1], [0x0EB4, 0x0EB9], [0x0EBB, 0x0EBC],
        [0x0EC8, 0x0ECD], [0x0F18, 0x0F19], [0x0F35, 0x0F35],
        [0x0F37, 0x0F37], [0x0F39, 0x0F39], [0x0F71, 0x0F7E],
        [0x0F80, 0x0F84], [0x0F86, 0x0F87], [0x0F90, 0x0F97],
        [0x0F99, 0x0FBC], [0x0FC6, 0x0FC6], [0x102D, 0x1030],
        [0x1032, 0x1032], [0x1036, 0x1037], [0x1039, 0x1039],
        [0x1058, 0x1059], [0x1160, 0x11FF], [0x135F, 0x135F],
        [0x1712, 0x1714], [0x1732, 0x1734], [0x1752, 0x1753],
        [0x1772, 0x1773], [0x17B4, 0x17B5], [0x17B7, 0x17BD],
        [0x17C6, 0x17C6], [0x17C9, 0x17D3], [0x17DD, 0x17DD],
        [0x180B, 0x180D], [0x18A9, 0x18A9], [0x1920, 0x1922],
        [0x1927, 0x1928], [0x1932, 0x1932], [0x1939, 0x193B],
        [0x1A17, 0x1A18], [0x1B00, 0x1B03], [0x1B34, 0x1B34],
        [0x1B36, 0x1B3A], [0x1B3C, 0x1B3C], [0x1B42, 0x1B42],
        [0x1B6B, 0x1B73], [0x1DC0, 0x1DCA], [0x1DFE, 0x1DFF],
        [0x200B, 0x200F], [0x202A, 0x202E], [0x2060, 0x2063],
        [0x206A, 0x206F], [0x20D0, 0x20EF], [0x302A, 0x302F],
        [0x3099, 0x309A], [0xA806, 0xA806], [0xA80B, 0xA80B],
        [0xA825, 0xA826], [0xFB1E, 0xFB1E], [0xFE00, 0xFE0F],
        [0xFE20, 0xFE23], [0xFEFF, 0xFEFF], [0xFFF9, 0xFFFB]
    ];
    var COMBINING_HIGH = [
        [0x10A01, 0x10A03], [0x10A05, 0x10A06], [0x10A0C, 0x10A0F],
        [0x10A38, 0x10A3A], [0x10A3F, 0x10A3F], [0x1D167, 0x1D169],
        [0x1D173, 0x1D182], [0x1D185, 0x1D18B], [0x1D1AA, 0x1D1AD],
        [0x1D242, 0x1D244], [0xE0001, 0xE0001], [0xE0020, 0xE007F],
        [0xE0100, 0xE01EF]
    ];
    function bisearch(ucs, data) {
        var min = 0;
        var max = data.length - 1;
        var mid;
        if (ucs < data[0][0] || ucs > data[max][1]) {
            return false;
        }
        while (max >= min) {
            mid = (min + max) >> 1;
            if (ucs > data[mid][1]) {
                min = mid + 1;
            }
            else if (ucs < data[mid][0]) {
                max = mid - 1;
            }
            else {
                return true;
            }
        }
        return false;
    }
    function wcwidthBMP(ucs) {
        if (ucs === 0) {
            return opts.nul;
        }
        if (ucs < 32 || (ucs >= 0x7f && ucs < 0xa0)) {
            return opts.control;
        }
        if (bisearch(ucs, COMBINING_BMP)) {
            return 0;
        }
        if (isWideBMP(ucs)) {
            return 2;
        }
        return 1;
    }
    function isWideBMP(ucs) {
        return (ucs >= 0x1100 && (ucs <= 0x115f ||
            ucs === 0x2329 ||
            ucs === 0x232a ||
            (ucs >= 0x2e80 && ucs <= 0xa4cf && ucs !== 0x303f) ||
            (ucs >= 0xac00 && ucs <= 0xd7a3) ||
            (ucs >= 0xf900 && ucs <= 0xfaff) ||
            (ucs >= 0xfe10 && ucs <= 0xfe19) ||
            (ucs >= 0xfe30 && ucs <= 0xfe6f) ||
            (ucs >= 0xff00 && ucs <= 0xff60) ||
            (ucs >= 0xffe0 && ucs <= 0xffe6)));
    }
    function wcwidthHigh(ucs) {
        if (bisearch(ucs, COMBINING_HIGH)) {
            return 0;
        }
        if ((ucs >= 0x20000 && ucs <= 0x2fffd) || (ucs >= 0x30000 && ucs <= 0x3fffd)) {
            return 2;
        }
        return 1;
    }
    var control = opts.control | 0;
    var table = null;
    function init_table() {
        var CODEPOINTS = 65536;
        var BITWIDTH = 2;
        var ITEMSIZE = 32;
        var CONTAINERSIZE = CODEPOINTS * BITWIDTH / ITEMSIZE;
        var CODEPOINTS_PER_ITEM = ITEMSIZE / BITWIDTH;
        table = (typeof Uint32Array === 'undefined')
            ? new Array(CONTAINERSIZE)
            : new Uint32Array(CONTAINERSIZE);
        for (var i = 0; i < CONTAINERSIZE; ++i) {
            var num = 0;
            var pos = CODEPOINTS_PER_ITEM;
            while (pos--) {
                num = (num << 2) | wcwidthBMP(CODEPOINTS_PER_ITEM * i + pos);
            }
            table[i] = num;
        }
        return table;
    }
    return function (num) {
        num = num | 0;
        if (num < 32) {
            return control | 0;
        }
        if (num < 127) {
            return 1;
        }
        var t = table || init_table();
        if (num < 65536) {
            return t[num >> 4] >> ((num & 15) << 1) & 3;
        }
        return wcwidthHigh(num);
    };
})({ nul: 0, control: 0 });

//# sourceMappingURL=CharWidth.js.map


/***/ }),

/***/ "oVml":
/*!****************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_object-create.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = __webpack_require__(/*! ./_an-object */ "5K7Z");
var dPs = __webpack_require__(/*! ./_object-dps */ "fpC5");
var enumBugKeys = __webpack_require__(/*! ./_enum-bug-keys */ "FpHa");
var IE_PROTO = __webpack_require__(/*! ./_shared-key */ "VVlx")('IE_PROTO');
var Empty = function () { /* empty */ };
var PROTOTYPE = 'prototype';

// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function () {
  // Thrash, waste and sodomy: IE GC bug
  var iframe = __webpack_require__(/*! ./_dom-create */ "Hsns")('iframe');
  var i = enumBugKeys.length;
  var lt = '<';
  var gt = '>';
  var iframeDocument;
  iframe.style.display = 'none';
  __webpack_require__(/*! ./_html */ "MvwC").appendChild(iframe);
  iframe.src = 'javascript:'; // eslint-disable-line no-script-url
  // createDict = iframe.contentWindow.Object;
  // html.removeChild(iframe);
  iframeDocument = iframe.contentWindow.document;
  iframeDocument.open();
  iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
  iframeDocument.close();
  createDict = iframeDocument.F;
  while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]];
  return createDict();
};

module.exports = Object.create || function create(O, Properties) {
  var result;
  if (O !== null) {
    Empty[PROTOTYPE] = anObject(O);
    result = new Empty();
    Empty[PROTOTYPE] = null;
    // add "__proto__" for Object.getPrototypeOf polyfill
    result[IE_PROTO] = O;
  } else result = createDict();
  return Properties === undefined ? result : dPs(result, Properties);
};


/***/ }),

/***/ "oVyQ":
/*!***************************************************!*\
  !*** ./node_modules/prop-types/checkPropTypes.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */



var printWarning = function() {};

if (true) {
  var ReactPropTypesSecret = __webpack_require__(/*! ./lib/ReactPropTypesSecret */ "WbBG");
  var loggedTypeFailures = {};
  var has = Function.call.bind(Object.prototype.hasOwnProperty);

  printWarning = function(text) {
    var message = 'Warning: ' + text;
    if (typeof console !== 'undefined') {
      console.error(message);
    }
    try {
      // --- Welcome to debugging React ---
      // This error was thrown as a convenience so that you can use this stack
      // to find the callsite that caused this warning to fire.
      throw new Error(message);
    } catch (x) {}
  };
}

/**
 * Assert that the values match with the type specs.
 * Error messages are memorized and will only be shown once.
 *
 * @param {object} typeSpecs Map of name to a ReactPropType
 * @param {object} values Runtime values that need to be type-checked
 * @param {string} location e.g. "prop", "context", "child context"
 * @param {string} componentName Name of the component for error messages.
 * @param {?Function} getStack Returns the component stack.
 * @private
 */
function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
  if (true) {
    for (var typeSpecName in typeSpecs) {
      if (has(typeSpecs, typeSpecName)) {
        var error;
        // Prop type validation may throw. In case they do, we don't want to
        // fail the render phase where it didn't fail before. So we log it.
        // After these have been cleaned up, we'll let them throw.
        try {
          // This is intentionally an invariant that gets caught. It's the same
          // behavior as without this statement except with a better message.
          if (typeof typeSpecs[typeSpecName] !== 'function') {
            var err = Error(
              (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +
              'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'
            );
            err.name = 'Invariant Violation';
            throw err;
          }
          error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
        } catch (ex) {
          error = ex;
        }
        if (error && !(error instanceof Error)) {
          printWarning(
            (componentName || 'React class') + ': type specification of ' +
            location + ' `' + typeSpecName + '` is invalid; the type checker ' +
            'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +
            'You may have forgotten to pass an argument to the type checker ' +
            'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
            'shape all require an argument).'
          );
        }
        if (error instanceof Error && !(error.message in loggedTypeFailures)) {
          // Only monitor this failure once because there tends to be a lot of the
          // same error.
          loggedTypeFailures[error.message] = true;

          var stack = getStack ? getStack() : '';

          printWarning(
            'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
          );
        }
      }
    }
  }
}

/**
 * Resets warning cache when testing.
 *
 * @private
 */
checkPropTypes.resetWarningCache = function() {
  if (true) {
    loggedTypeFailures = {};
  }
}

module.exports = checkPropTypes;


/***/ }),

/***/ "oW49":
/*!*********************************************!*\
  !*** ./node_modules/entities/lib/decode.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var entityMap = __webpack_require__(/*! ../maps/entities.json */ "8PLQ"),
    legacyMap = __webpack_require__(/*! ../maps/legacy.json */ "kWb8"),
    xmlMap = __webpack_require__(/*! ../maps/xml.json */ "ZLJe"),
    decodeCodePoint = __webpack_require__(/*! ./decode_codepoint.js */ "cHMM");

var decodeXMLStrict = getStrictDecoder(xmlMap),
    decodeHTMLStrict = getStrictDecoder(entityMap);

function getStrictDecoder(map) {
    var keys = Object.keys(map).join("|"),
        replace = getReplacer(map);

    keys += "|#[xX][\\da-fA-F]+|#\\d+";

    var re = new RegExp("&(?:" + keys + ");", "g");

    return function(str) {
        return String(str).replace(re, replace);
    };
}

var decodeHTML = (function() {
    var legacy = Object.keys(legacyMap).sort(sorter);

    var keys = Object.keys(entityMap).sort(sorter);

    for (var i = 0, j = 0; i < keys.length; i++) {
        if (legacy[j] === keys[i]) {
            keys[i] += ";?";
            j++;
        } else {
            keys[i] += ";";
        }
    }

    var re = new RegExp("&(?:" + keys.join("|") + "|#[xX][\\da-fA-F]+;?|#\\d+;?)", "g"),
        replace = getReplacer(entityMap);

    function replacer(str) {
        if (str.substr(-1) !== ";") str += ";";
        return replace(str);
    }

    //TODO consider creating a merged map
    return function(str) {
        return String(str).replace(re, replacer);
    };
})();

function sorter(a, b) {
    return a < b ? 1 : -1;
}

function getReplacer(map) {
    return function replace(str) {
        if (str.charAt(1) === "#") {
            if (str.charAt(2) === "X" || str.charAt(2) === "x") {
                return decodeCodePoint(parseInt(str.substr(3), 16));
            }
            return decodeCodePoint(parseInt(str.substr(2), 10));
        }
        return map[str.slice(1, -1)];
    };
}

module.exports = {
    XML: decodeXMLStrict,
    HTML: decodeHTML,
    HTMLStrict: decodeHTMLStrict
};


/***/ }),

/***/ "oX2A":
/*!*********************************************************!*\
  !*** ./node_modules/jupyterlab_plotlyhelp/lib/index.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

Object.defineProperty(exports, "__esModule", { value: true });
const IMainMenu = __webpack_require__(/*! @jupyterlab/mainmenu */ "N4Qf").IMainMenu;
const ICommandPalette = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG").ICommandPalette;

const plugin = {
    id: 'jupyterlab_plotlyhelp',
    autoStart: true,
    requires: [IMainMenu, ICommandPalette],
    activate: function(app, mainMenu, palette) {
        const category = 'Help';

        const group = [
            { command: 'help:open', args: {text: 'Plotly Python Reference', url: 'https://plot.ly/python/'}},
            { command: 'help:open', args: {text: 'Dash User Guide', url: 'https://dash.plot.ly/'}},
            { command: 'help:open', args: {text: 'Plotly Property Reference', url: 'https://plot.ly/python/reference/'}},
            { command: 'help:open', args: {text: 'Plotly R Reference', url: 'https://plot.ly/r/'}},
            { command: 'help:open', args: {text: 'Plotly R Book', url: 'https://plotly-book.cpsievert.me/'}},
        ];
        mainMenu.helpMenu.addGroup(group, 10);

        // Add to command palette
        group.forEach(item => {
            palette.addItem({ args: item.args, command: item.command, category });
        });
    }
};

exports.default = plugin;


/***/ }),

/***/ "ocgx":
/*!********************************************************************!*\
  !*** ./node_modules/draft-js/lib/keyCommandTransposeCharacters.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule keyCommandTransposeCharacters
 * @format
 * 
 */



var DraftModifier = __webpack_require__(/*! ./DraftModifier */ "fyOY");
var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");

var getContentStateFragment = __webpack_require__(/*! ./getContentStateFragment */ "DYKh");

/**
 * Transpose the characters on either side of a collapsed cursor, or
 * if the cursor is at the end of the block, transpose the last two
 * characters.
 */
function keyCommandTransposeCharacters(editorState) {
  var selection = editorState.getSelection();
  if (!selection.isCollapsed()) {
    return editorState;
  }

  var offset = selection.getAnchorOffset();
  if (offset === 0) {
    return editorState;
  }

  var blockKey = selection.getAnchorKey();
  var content = editorState.getCurrentContent();
  var block = content.getBlockForKey(blockKey);
  var length = block.getLength();

  // Nothing to transpose if there aren't two characters.
  if (length <= 1) {
    return editorState;
  }

  var removalRange;
  var finalSelection;

  if (offset === length) {
    // The cursor is at the end of the block. Swap the last two characters.
    removalRange = selection.set('anchorOffset', offset - 1);
    finalSelection = selection;
  } else {
    removalRange = selection.set('focusOffset', offset + 1);
    finalSelection = removalRange.set('anchorOffset', offset + 1);
  }

  // Extract the character to move as a fragment. This preserves its
  // styling and entity, if any.
  var movedFragment = getContentStateFragment(content, removalRange);
  var afterRemoval = DraftModifier.removeRange(content, removalRange, 'backward');

  // After the removal, the insertion target is one character back.
  var selectionAfter = afterRemoval.getSelectionAfter();
  var targetOffset = selectionAfter.getAnchorOffset() - 1;
  var targetRange = selectionAfter.merge({
    anchorOffset: targetOffset,
    focusOffset: targetOffset
  });

  var afterInsert = DraftModifier.replaceWithFragment(afterRemoval, targetRange, movedFragment);

  var newEditorState = EditorState.push(editorState, afterInsert, 'insert-fragment');

  return EditorState.acceptSelection(newEditorState, finalSelection);
}

module.exports = keyCommandTransposeCharacters;

/***/ }),

/***/ "odad":
/*!****************************************************************************!*\
  !*** ./node_modules/core-js/library/modules/es6.number.is-safe-integer.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// 20.1.2.5 Number.isSafeInteger(number)
var $export = __webpack_require__(/*! ./_export */ "Y7ZC");
var isInteger = __webpack_require__(/*! ./_is-integer */ "DNkW");
var abs = Math.abs;

$export($export.S, 'Number', {
  isSafeInteger: function isSafeInteger(number) {
    return isInteger(number) && abs(number) <= 0x1fffffffffffff;
  }
});


/***/ }),

/***/ "oeIe":
/*!****************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotScatterternaryIcon.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotScatterternaryIcon = function PlotScatterternaryIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M30.375 28.688H1.625L16 1.188zM3.75 27.313h24.375L16 4.125zM18.688 16c0 .75-.625 1.313-1.375 1.313C16.625 17.313 16 16.75 16 16s.625-1.313 1.313-1.313c.75 0 1.375.563 1.375 1.313zm2.625 4c0 .75-.563 1.313-1.313 1.313S18.687 20.75 18.687 20s.563-1.313 1.313-1.313 1.313.563 1.313 1.313zm-12 4c0 .75-.563 1.313-1.313 1.313S6.687 24.75 6.687 24 7.25 22.687 8 22.687 9.313 23.25 9.313 24zm8-12c0 .75-.563 1.313-1.313 1.313S14.687 12.75 14.687 12s.563-1.313 1.313-1.313 1.313.563 1.313 1.313zm-4 8c0 .75-.563 1.313-1.313 1.313S10.687 20.75 10.687 20s.563-1.313 1.313-1.313 1.313.563 1.313 1.313zm0 5.313c0 .75-.563 1.375-1.313 1.375s-1.313-.625-1.313-1.375c0-.688.563-1.313 1.313-1.313s1.313.625 1.313 1.313zM24 24a1.32 1.32 0 0 1-1.313 1.313c-.75 0-1.375-.563-1.375-1.313s.625-1.313 1.375-1.313A1.32 1.32 0 0 1 24 24z' })
    );
};

exports.default = PlotScatterternaryIcon;

/***/ }),

/***/ "ohE5":
/*!************************************************!*\
  !*** ./node_modules/fbjs/lib/emptyFunction.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * 
 */

function makeEmptyFunction(arg) {
  return function () {
    return arg;
  };
}

/**
 * This function accepts and discards inputs; it has no side effects. This is
 * primarily useful idiomatically for overridable function endpoints which
 * always need to be callable, since JS lacks a null-call idiom ala Cocoa.
 */
var emptyFunction = function emptyFunction() {};

emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
  return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
  return arg;
};

module.exports = emptyFunction;

/***/ }),

/***/ "oi9M":
/*!************************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/clear_responsive.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



/**
 * Clear responsive handlers (if any).
 *
 * @param {DOM node or object} gd : graph div object
 */
module.exports = function clearResponsive(gd) {
    if(gd._responsiveChartHandler) {
        window.removeEventListener('resize', gd._responsiveChartHandler);
        delete gd._responsiveChartHandler;
    }
};


/***/ }),

/***/ "olUY":
/*!***************************************!*\
  !*** ./node_modules/sha.js/sha256.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/**
 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
 * in FIPS 180-2
 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 *
 */

var inherits = __webpack_require__(/*! inherits */ "P7XM")
var Hash = __webpack_require__(/*! ./hash */ "tnIz")
var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer

var K = [
  0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
  0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
  0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
  0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
  0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
  0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
  0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
  0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
  0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
  0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
  0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
  0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
  0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
  0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
  0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
  0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
]

var W = new Array(64)

function Sha256 () {
  this.init()

  this._w = W // new Array(64)

  Hash.call(this, 64, 56)
}

inherits(Sha256, Hash)

Sha256.prototype.init = function () {
  this._a = 0x6a09e667
  this._b = 0xbb67ae85
  this._c = 0x3c6ef372
  this._d = 0xa54ff53a
  this._e = 0x510e527f
  this._f = 0x9b05688c
  this._g = 0x1f83d9ab
  this._h = 0x5be0cd19

  return this
}

function ch (x, y, z) {
  return z ^ (x & (y ^ z))
}

function maj (x, y, z) {
  return (x & y) | (z & (x | y))
}

function sigma0 (x) {
  return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)
}

function sigma1 (x) {
  return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)
}

function gamma0 (x) {
  return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)
}

function gamma1 (x) {
  return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)
}

Sha256.prototype._update = function (M) {
  var W = this._w

  var a = this._a | 0
  var b = this._b | 0
  var c = this._c | 0
  var d = this._d | 0
  var e = this._e | 0
  var f = this._f | 0
  var g = this._g | 0
  var h = this._h | 0

  for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
  for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0

  for (var j = 0; j < 64; ++j) {
    var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0
    var T2 = (sigma0(a) + maj(a, b, c)) | 0

    h = g
    g = f
    f = e
    e = (d + T1) | 0
    d = c
    c = b
    b = a
    a = (T1 + T2) | 0
  }

  this._a = (a + this._a) | 0
  this._b = (b + this._b) | 0
  this._c = (c + this._c) | 0
  this._d = (d + this._d) | 0
  this._e = (e + this._e) | 0
  this._f = (f + this._f) | 0
  this._g = (g + this._g) | 0
  this._h = (h + this._h) | 0
}

Sha256.prototype._hash = function () {
  var H = Buffer.allocUnsafe(32)

  H.writeInt32BE(this._a, 0)
  H.writeInt32BE(this._b, 4)
  H.writeInt32BE(this._c, 8)
  H.writeInt32BE(this._d, 12)
  H.writeInt32BE(this._e, 16)
  H.writeInt32BE(this._f, 20)
  H.writeInt32BE(this._g, 24)
  H.writeInt32BE(this._h, 28)

  return H
}

module.exports = Sha256


/***/ }),

/***/ "om3i":
/*!*******************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/kernel/serialize.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * Deserialize and return the unpacked message.
 *
 * #### Notes
 * Handles JSON blob strings and binary messages.
 */
function deserialize(data) {
    let value;
    if (typeof data === 'string') {
        value = JSON.parse(data);
    }
    else {
        value = deserializeBinary(data);
    }
    return value;
}
exports.deserialize = deserialize;
/**
 * Serialize a kernel message for transport.
 *
 * #### Notes
 * If there is binary content, an `ArrayBuffer` is returned,
 * otherwise the message is converted to a JSON string.
 */
function serialize(msg) {
    let value;
    if (msg.buffers && msg.buffers.length) {
        value = serializeBinary(msg);
    }
    else {
        value = JSON.stringify(msg);
    }
    return value;
}
exports.serialize = serialize;
/**
 * Deserialize a binary message to a Kernel Message.
 */
function deserializeBinary(buf) {
    let data = new DataView(buf);
    // read the header: 1 + nbufs 32b integers
    let nbufs = data.getUint32(0);
    let offsets = [];
    if (nbufs < 2) {
        throw new Error('Invalid incoming Kernel Message');
    }
    for (let i = 1; i <= nbufs; i++) {
        offsets.push(data.getUint32(i * 4));
    }
    let jsonBytes = new Uint8Array(buf.slice(offsets[0], offsets[1]));
    let msg = JSON.parse(new TextDecoder('utf8').decode(jsonBytes));
    // the remaining chunks are stored as DataViews in msg.buffers
    msg.buffers = [];
    for (let i = 1; i < nbufs; i++) {
        let start = offsets[i];
        let stop = offsets[i + 1] || buf.byteLength;
        msg.buffers.push(new DataView(buf.slice(start, stop)));
    }
    return msg;
}
/**
 * Implement the binary serialization protocol.
 *
 * Serialize Kernel message to ArrayBuffer.
 */
function serializeBinary(msg) {
    let offsets = [];
    let buffers = [];
    let encoder = new TextEncoder();
    let origBuffers = [];
    if (msg.buffers !== undefined) {
        origBuffers = msg.buffers;
        delete msg['buffers'];
    }
    let jsonUtf8 = encoder.encode(JSON.stringify(msg));
    buffers.push(jsonUtf8.buffer);
    for (let i = 0; i < origBuffers.length; i++) {
        // msg.buffers elements could be either views or ArrayBuffers
        // buffers elements are ArrayBuffers
        let b = origBuffers[i];
        buffers.push(b instanceof ArrayBuffer ? b : b.buffer);
    }
    let nbufs = buffers.length;
    offsets.push(4 * (nbufs + 1));
    for (let i = 0; i + 1 < buffers.length; i++) {
        offsets.push(offsets[offsets.length - 1] + buffers[i].byteLength);
    }
    let msgBuf = new Uint8Array(offsets[offsets.length - 1] + buffers[buffers.length - 1].byteLength);
    // use DataView.setUint32 for network byte-order
    let view = new DataView(msgBuf.buffer);
    // write nbufs to first 4 bytes
    view.setUint32(0, nbufs);
    // write offsets to next 4 * nbufs bytes
    for (let i = 0; i < offsets.length; i++) {
        view.setUint32(4 * (i + 1), offsets[i]);
    }
    // write all the buffers at their respective offsets
    for (let i = 0; i < buffers.length; i++) {
        msgBuf.set(new Uint8Array(buffers[i]), offsets[i]);
    }
    return msgBuf.buffer;
}


/***/ }),

/***/ "om78":
/*!*****************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeStreamtubeIcon.js ***!
  \*****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeStreamtubeIcon = function TraceTypeStreamtubeIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 1360 1360' }, props),
        _react2.default.createElement('path', { fill: '#09FFFF', d: 'M702.658 1295.469a41.129 41.129 0 0 1-17.609-3.965l-559.677-263.837a41.352 41.352 0 0 1-23.715-37.404v-634.01a41.35 41.35 0 0 1 24.475-37.749L685.814 68.438a41.361 41.361 0 0 1 39.367 3.062 41.341 41.341 0 0 1 18.85 34.69v625.15a41.342 41.342 0 0 1-23.969 37.521L241.021 990.756l479.294 225.948c20.66 9.736 29.502 34.378 19.771 55.03-7.051 14.961-21.919 23.735-37.428 23.735zM184.354 383.068v542.804l476.984-220.946V169.952L184.354 383.068z' }),
        _react2.default.createElement('path', { fill: '#09FFFF', d: 'M702.713 1295.469c-15.515 0-30.377-8.773-37.429-23.734-9.736-20.652-.889-45.294 19.765-55.03l479.295-225.948L685.302 768.86a41.335 41.335 0 0 1-23.963-37.521V106.19a41.346 41.346 0 0 1 58.212-37.752l559.683 250.067a41.349 41.349 0 0 1 24.476 37.749v634.008a41.351 41.351 0 0 1-23.716 37.404l-559.678 263.837a41.123 41.123 0 0 1-17.603 3.966zm41.318-590.543l476.979 220.952V383.069L744.031 169.952v534.974z' }),
        _react2.default.createElement(
            'linearGradient',
            { id: 'a', gradientUnits: 'userSpaceOnUse', x1: '569.693', y1: '609.274', x2: '490.846', y2: '472.706' },
            _react2.default.createElement('stop', { offset: '0', stopColor: '#09ffff' }),
            _react2.default.createElement('stop', { offset: '.058', stopColor: '#0be3ff' }),
            _react2.default.createElement('stop', { offset: '.135', stopColor: '#0ec5ff' }),
            _react2.default.createElement('stop', { offset: '.211', stopColor: '#10afff' }),
            _react2.default.createElement('stop', { offset: '.283', stopColor: '#11a1ff' }),
            _react2.default.createElement('stop', { offset: '.349', stopColor: '#119dff' }),
            _react2.default.createElement('stop', { offset: '.459', stopColor: '#10a4ff' }),
            _react2.default.createElement('stop', { offset: '.614', stopColor: '#0fb6ff' }),
            _react2.default.createElement('stop', { offset: '.795', stopColor: '#0cd4ff' }),
            _react2.default.createElement('stop', { offset: '.995', stopColor: '#09feff' }),
            _react2.default.createElement('stop', { offset: '1', stopColor: '#09ffff' })
        ),
        _react2.default.createElement('path', { fill: 'url(#a)', d: 'M260.692 770.274c-15.886 0-31.032-9.212-37.854-24.673-9.193-20.843.204-45.183 21-54.457.815-.369 82.487-37.934 159.691-137.073 11.965-19.586 76.511-113.551 207.528-107.458 79.605 3.699 126.375-9.453 161.124-91.65 8.885-21.036 33.155-30.877 54.18-21.986 21.036 8.891 30.876 33.144 21.986 54.185-55.841 132.117-148.918 146.361-241.13 142.058-92.273-4.328-132.827 67.379-133.227 68.101a40.6 40.6 0 0 1-3.489 5.323C379.22 720.93 281.474 764.927 277.356 766.743a41.175 41.175 0 0 1-16.664 3.531z' }),
        _react2.default.createElement(
            'linearGradient',
            { id: 'b', gradientUnits: 'userSpaceOnUse', x1: '726.132', y1: '754.813', x2: '647.261', y2: '618.205' },
            _react2.default.createElement('stop', { offset: '.382', stopColor: '#119dff' }),
            _react2.default.createElement('stop', { offset: '.984', stopColor: '#09ffff' })
        ),
        _react2.default.createElement('path', { fill: 'url(#b)', d: 'M417.123 915.811c-15.88 0-31.032-9.199-37.848-24.672-9.199-20.844.21-45.196 21.012-54.457 1.653-.753 82.876-38.441 159.671-137.068 11.966-19.578 76.364-113.594 207.537-107.457 79.61 3.711 126.38-9.453 161.123-91.65 8.885-21.042 33.155-30.872 54.179-21.993 21.041 8.891 30.884 33.155 21.993 54.186-55.842 132.115-148.9 146.353-241.143 142.062-89.349-4.174-130.5 63.441-133.291 68.232-1.075 2.012-2.013 3.364-3.427 5.192-91.28 118.279-189.025 162.29-193.143 164.104a41.21 41.21 0 0 1-16.663 3.521z' }),
        _react2.default.createElement(
            'linearGradient',
            { id: 'c', gradientUnits: 'userSpaceOnUse', x1: '886.165', y1: '896.485', x2: '807.297', y2: '759.882' },
            _react2.default.createElement('stop', { offset: '0', stopColor: '#09ffff' }),
            _react2.default.createElement('stop', { offset: '.602', stopColor: '#119dff' })
        ),
        _react2.default.createElement('path', { fill: 'url(#c)', d: 'M577.159 1057.484c-15.886 0-31.032-9.213-37.854-24.673-9.193-20.856.216-45.201 21.012-54.463 1.649-.747 82.876-38.44 159.673-137.074 11.966-19.573 76.395-113.569 207.534-107.456 79.605 3.716 126.388-9.447 161.123-91.645 8.892-21.036 33.163-30.878 54.186-21.986 21.035 8.89 30.883 33.143 21.992 54.185-55.845 132.117-148.904 146.354-241.141 142.058-89.312-4.187-130.505 63.439-133.296 68.231-1.075 2.013-2.013 3.364-3.427 5.192-91.274 118.28-189.02 162.283-193.137 164.1a41.187 41.187 0 0 1-16.665 3.531z' })
    );
};

exports.default = TraceTypeStreamtubeIcon;

/***/ }),

/***/ "opHZ":
/*!*******************************************!*\
  !*** ./node_modules/base16/lib/brewer.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'brewer',
  author: 'timothée poisot (http://github.com/tpoisot)',
  base00: '#0c0d0e',
  base01: '#2e2f30',
  base02: '#515253',
  base03: '#737475',
  base04: '#959697',
  base05: '#b7b8b9',
  base06: '#dadbdc',
  base07: '#fcfdfe',
  base08: '#e31a1c',
  base09: '#e6550d',
  base0A: '#dca060',
  base0B: '#31a354',
  base0C: '#80b1d3',
  base0D: '#3182bd',
  base0E: '#756bb1',
  base0F: '#b15928'
};
module.exports = exports['default'];

/***/ }),

/***/ "or5M":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_equalArrays.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var SetCache = __webpack_require__(/*! ./_SetCache */ "1hJj"),
    arraySome = __webpack_require__(/*! ./_arraySome */ "QoRX"),
    cacheHas = __webpack_require__(/*! ./_cacheHas */ "xYSL");

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
    COMPARE_UNORDERED_FLAG = 2;

/**
 * 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;
  }
  // Assume cyclic values are equal.
  var stacked = stack.get(array);
  if (stacked && stack.get(other)) {
    return stacked == other;
  }
  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;
}

module.exports = equalArrays;


/***/ }),

/***/ "otv/":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_cloneSymbol.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Symbol = __webpack_require__(/*! ./_Symbol */ "nmnc");

/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
    symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;

/**
 * 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)) : {};
}

module.exports = cloneSymbol;


/***/ }),

/***/ "ovjo":
/*!*********************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/boxengine.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * A sizer object for use with the box engine layout functions.
 *
 * #### Notes
 * A box sizer holds the geometry information for an object along an
 * arbitrary layout orientation.
 *
 * For best performance, this class should be treated as a raw data
 * struct. It should not typically be subclassed.
 */
var BoxSizer = (function () {
    function BoxSizer() {
        /**
         * The preferred size for the sizer.
         *
         * #### Notes
         * The sizer will be given this initial size subject to its size
         * bounds. The sizer will not deviate from this size unless such
         * deviation is required to fit into the available layout space.
         *
         * There is no limit to this value, but it will be clamped to the
         * bounds defined by [[minSize]] and [[maxSize]].
         *
         * The default value is `0`.
         */
        this.sizeHint = 0;
        /**
         * The minimum size of the sizer.
         *
         * #### Notes
         * The sizer will never be sized less than this value, even if
         * it means the sizer will overflow the available layout space.
         *
         * It is assumed that this value lies in the range `[0, Infinity)`
         * and that it is `<=` to [[maxSize]]. Failure to adhere to this
         * constraint will yield undefined results.
         *
         * The default value is `0`.
         */
        this.minSize = 0;
        /**
         * The maximum size of the sizer.
         *
         * #### Notes
         * The sizer will never be sized greater than this value, even if
         * it means the sizer will underflow the available layout space.
         *
         * It is assumed that this value lies in the range `[0, Infinity]`
         * and that it is `>=` to [[minSize]]. Failure to adhere to this
         * constraint will yield undefined results.
         *
         * The default value is `Infinity`.
         */
        this.maxSize = Infinity;
        /**
         * The stretch factor for the sizer.
         *
         * #### Notes
         * This controls how much the sizer stretches relative to its sibling
         * sizers when layout space is distributed. A stretch factor of zero
         * is special and will cause the sizer to only be resized after all
         * other sizers with a stretch factor greater than zero have been
         * resized to their limits.
         *
         * It is assumed that this value is an integer that lies in the range
         * `[0, Infinity)`. Failure to adhere to this constraint will yield
         * undefined results.
         *
         * The default value is `1`.
         */
        this.stretch = 1;
        /**
         * The computed size of the sizer.
         *
         * #### Notes
         * This value is the output of a call to [[boxCalc]]. It represents
         * the computed size for the object along the layout orientation,
         * and will always lie in the range `[minSize, maxSize]`.
         *
         * This value is output only.
         *
         * Changing this value will have no effect.
         */
        this.size = 0;
        /**
         * An internal storage property for the layout algorithm.
         *
         * #### Notes
         * This value is used as temporary storage by the layout algorithm.
         *
         * Changing this value will have no effect.
         */
        this.done = false;
    }
    return BoxSizer;
}());
exports.BoxSizer = BoxSizer;
/**
 * The namespace for the box engine layout functions.
 */
var BoxEngine;
(function (BoxEngine) {
    /**
     * Calculate the optimal layout sizes for a sequence of box sizers.
     *
     * This distributes the available layout space among the box sizers
     * according to the following algorithm:
     *
     * 1. Initialize the sizers's size to its size hint and compute the
     *    sums for each of size hint, min size, and max size.
     *
     * 2. If the total size hint equals the available space, return.
     *
     * 3. If the available space is less than the total min size, set all
     *    sizers to their min size and return.
     *
     * 4. If the available space is greater than the total max size, set
     *    all sizers to their max size and return.
     *
     * 5. If the layout space is less than the total size hint, distribute
     *    the negative delta as follows:
     *
     *    a. Shrink each sizer with a stretch factor greater than zero by
     *       an amount proportional to the negative space and the sum of
     *       stretch factors. If the sizer reaches its min size, remove
     *       it and its stretch factor from the computation.
     *
     *    b. If after adjusting all stretch sizers there remains negative
     *       space, distribute the space equally among the sizers with a
     *       stretch factor of zero. If a sizer reaches its min size,
     *       remove it from the computation.
     *
     * 6. If the layout space is greater than the total size hint,
     *    distribute the positive delta as follows:
     *
     *    a. Expand each sizer with a stretch factor greater than zero by
     *       an amount proportional to the postive space and the sum of
     *       stretch factors. If the sizer reaches its max size, remove
     *       it and its stretch factor from the computation.
     *
     *    b. If after adjusting all stretch sizers there remains positive
     *       space, distribute the space equally among the sizers with a
     *       stretch factor of zero. If a sizer reaches its max size,
     *       remove it from the computation.
     *
     * 7. return
     *
     * @param sizers - The sizers for a particular layout line.
     *
     * @param space - The available layout space for the sizers.
     *
     * @returns The delta between the provided available space and the
     *   actual consumed space. This value will be zero if the sizers
     *   can be adjusted to fit, negative if the available space is too
     *   small, and positive if the available space is too large.
     *
     * #### Notes
     * The [[size]] of each sizer is updated with the computed size.
     *
     * This function can be called at any time to recompute the layout for
     * an existing sequence of sizers. The previously computed results will
     * have no effect on the new output. It is therefore not necessary to
     * create new sizer objects on each resize event.
     */
    function calc(sizers, space) {
        // Bail early if there is nothing to do.
        var count = sizers.length;
        if (count === 0) {
            return space;
        }
        // Setup the size and stretch counters.
        var totalMin = 0;
        var totalMax = 0;
        var totalSize = 0;
        var totalStretch = 0;
        var stretchCount = 0;
        // Setup the sizers and compute the totals.
        for (var i = 0; i < count; ++i) {
            var sizer = sizers[i];
            var min = sizer.minSize;
            var max = sizer.maxSize;
            var hint = sizer.sizeHint;
            sizer.done = false;
            sizer.size = Math.max(min, Math.min(hint, max));
            totalSize += sizer.size;
            totalMin += min;
            totalMax += max;
            if (sizer.stretch > 0) {
                totalStretch += sizer.stretch;
                stretchCount++;
            }
        }
        // If the space is equal to the total size, return early.
        if (space === totalSize) {
            return 0;
        }
        // If the space is less than the total min, minimize each sizer.
        if (space <= totalMin) {
            for (var i = 0; i < count; ++i) {
                var sizer = sizers[i];
                sizer.size = sizer.minSize;
            }
            return space - totalMin;
        }
        // If the space is greater than the total max, maximize each sizer.
        if (space >= totalMax) {
            for (var i = 0; i < count; ++i) {
                var sizer = sizers[i];
                sizer.size = sizer.maxSize;
            }
            return space - totalMax;
        }
        // The loops below perform sub-pixel precision sizing. A near zero
        // value is used for compares instead of zero to ensure that the
        // loop terminates when the subdivided space is reasonably small.
        var nearZero = 0.01;
        // A counter which is decremented each time a sizer is resized to
        // its limit. This ensures the loops terminate even if there is
        // space remaining to distribute.
        var notDoneCount = count;
        // Distribute negative delta space.
        if (space < totalSize) {
            // Shrink each stretchable sizer by an amount proportional to its
            // stretch factor. If a sizer reaches its min size it's marked as
            // done. The loop progresses in phases where each sizer is given
            // a chance to consume its fair share for the pass, regardless of
            // whether a sizer before it reached its limit. This continues
            // until the stretchable sizers or the free space is exhausted.
            var freeSpace = totalSize - space;
            while (stretchCount > 0 && freeSpace > nearZero) {
                var distSpace = freeSpace;
                var distStretch = totalStretch;
                for (var i = 0; i < count; ++i) {
                    var sizer = sizers[i];
                    if (sizer.done || sizer.stretch === 0) {
                        continue;
                    }
                    var amt = sizer.stretch * distSpace / distStretch;
                    if (sizer.size - amt <= sizer.minSize) {
                        freeSpace -= sizer.size - sizer.minSize;
                        totalStretch -= sizer.stretch;
                        sizer.size = sizer.minSize;
                        sizer.done = true;
                        notDoneCount--;
                        stretchCount--;
                    }
                    else {
                        freeSpace -= amt;
                        sizer.size -= amt;
                    }
                }
            }
            // Distribute any remaining space evenly among the non-stretchable
            // sizers. This progresses in phases in the same manner as above.
            while (notDoneCount > 0 && freeSpace > nearZero) {
                var amt = freeSpace / notDoneCount;
                for (var i = 0; i < count; ++i) {
                    var sizer = sizers[i];
                    if (sizer.done) {
                        continue;
                    }
                    if (sizer.size - amt <= sizer.minSize) {
                        freeSpace -= sizer.size - sizer.minSize;
                        sizer.size = sizer.minSize;
                        sizer.done = true;
                        notDoneCount--;
                    }
                    else {
                        freeSpace -= amt;
                        sizer.size -= amt;
                    }
                }
            }
        }
        else {
            // Expand each stretchable sizer by an amount proportional to its
            // stretch factor. If a sizer reaches its max size it's marked as
            // done. The loop progresses in phases where each sizer is given
            // a chance to consume its fair share for the pass, regardless of
            // whether a sizer before it reached its limit. This continues
            // until the stretchable sizers or the free space is exhausted.
            var freeSpace = space - totalSize;
            while (stretchCount > 0 && freeSpace > nearZero) {
                var distSpace = freeSpace;
                var distStretch = totalStretch;
                for (var i = 0; i < count; ++i) {
                    var sizer = sizers[i];
                    if (sizer.done || sizer.stretch === 0) {
                        continue;
                    }
                    var amt = sizer.stretch * distSpace / distStretch;
                    if (sizer.size + amt >= sizer.maxSize) {
                        freeSpace -= sizer.maxSize - sizer.size;
                        totalStretch -= sizer.stretch;
                        sizer.size = sizer.maxSize;
                        sizer.done = true;
                        notDoneCount--;
                        stretchCount--;
                    }
                    else {
                        freeSpace -= amt;
                        sizer.size += amt;
                    }
                }
            }
            // Distribute any remaining space evenly among the non-stretchable
            // sizers. This progresses in phases in the same manner as above.
            while (notDoneCount > 0 && freeSpace > nearZero) {
                var amt = freeSpace / notDoneCount;
                for (var i = 0; i < count; ++i) {
                    var sizer = sizers[i];
                    if (sizer.done) {
                        continue;
                    }
                    if (sizer.size + amt >= sizer.maxSize) {
                        freeSpace -= sizer.maxSize - sizer.size;
                        sizer.size = sizer.maxSize;
                        sizer.done = true;
                        notDoneCount--;
                    }
                    else {
                        freeSpace -= amt;
                        sizer.size += amt;
                    }
                }
            }
        }
        // Indicate that the consumed space equals the available space.
        return 0;
    }
    BoxEngine.calc = calc;
    /**
     * Adjust a sizer by a delta and update its neighbors accordingly.
     *
     * @param sizers - The sizers which should be adjusted.
     *
     * @param index - The index of the sizer to grow.
     *
     * @param delta - The amount to adjust the sizer, positive or negative.
     *
     * #### Notes
     * This will adjust the indicated sizer by the specified amount, along
     * with the sizes of the appropriate neighbors, subject to the limits
     * specified by each of the sizers.
     *
     * This is useful when implementing box layouts where the boundaries
     * between the sizers are interactively adjustable by the user.
     */
    function adjust(sizers, index, delta) {
        // Bail early when there is nothing to do.
        if (sizers.length === 0 || delta === 0) {
            return;
        }
        // Dispatch to the proper implementation.
        if (delta > 0) {
            growSizer(sizers, index, delta);
        }
        else {
            shrinkSizer(sizers, index, -delta);
        }
    }
    BoxEngine.adjust = adjust;
    /**
     * Grow a sizer by a positive delta and adjust neighbors.
     */
    function growSizer(sizers, index, delta) {
        // Compute how much the items to the left can expand.
        var growLimit = 0;
        for (var i = 0; i <= index; ++i) {
            var sizer = sizers[i];
            growLimit += sizer.maxSize - sizer.size;
        }
        // Compute how much the items to the right can shrink.
        var shrinkLimit = 0;
        for (var i = index + 1, n = sizers.length; i < n; ++i) {
            var sizer = sizers[i];
            shrinkLimit += sizer.size - sizer.minSize;
        }
        // Clamp the delta adjustment to the limits.
        delta = Math.min(delta, growLimit, shrinkLimit);
        // Grow the sizers to the left by the delta.
        var grow = delta;
        for (var i = index; i >= 0 && grow > 0; --i) {
            var sizer = sizers[i];
            var limit = sizer.maxSize - sizer.size;
            if (limit >= grow) {
                sizer.sizeHint = sizer.size + grow;
                grow = 0;
            }
            else {
                sizer.sizeHint = sizer.size + limit;
                grow -= limit;
            }
        }
        // Shrink the sizers to the right by the delta.
        var shrink = delta;
        for (var i = index + 1, n = sizers.length; i < n && shrink > 0; ++i) {
            var sizer = sizers[i];
            var limit = sizer.size - sizer.minSize;
            if (limit >= shrink) {
                sizer.sizeHint = sizer.size - shrink;
                shrink = 0;
            }
            else {
                sizer.sizeHint = sizer.size - limit;
                shrink -= limit;
            }
        }
    }
    /**
     * Shrink a sizer by a positive delta and adjust neighbors.
     */
    function shrinkSizer(sizers, index, delta) {
        // Compute how much the items to the right can expand.
        var growLimit = 0;
        for (var i = index + 1, n = sizers.length; i < n; ++i) {
            var sizer = sizers[i];
            growLimit += sizer.maxSize - sizer.size;
        }
        // Compute how much the items to the left can shrink.
        var shrinkLimit = 0;
        for (var i = 0; i <= index; ++i) {
            var sizer = sizers[i];
            shrinkLimit += sizer.size - sizer.minSize;
        }
        // Clamp the delta adjustment to the limits.
        delta = Math.min(delta, growLimit, shrinkLimit);
        // Grow the sizers to the right by the delta.
        var grow = delta;
        for (var i = index + 1, n = sizers.length; i < n && grow > 0; ++i) {
            var sizer = sizers[i];
            var limit = sizer.maxSize - sizer.size;
            if (limit >= grow) {
                sizer.sizeHint = sizer.size + grow;
                grow = 0;
            }
            else {
                sizer.sizeHint = sizer.size + limit;
                grow -= limit;
            }
        }
        // Shrink the sizers to the left by the delta.
        var shrink = delta;
        for (var i = index; i >= 0 && shrink > 0; --i) {
            var sizer = sizers[i];
            var limit = sizer.size - sizer.minSize;
            if (limit >= shrink) {
                sizer.sizeHint = sizer.size - shrink;
                shrink = 0;
            }
            else {
                sizer.sizeHint = sizer.size - limit;
                shrink -= limit;
            }
        }
    }
})(BoxEngine = exports.BoxEngine || (exports.BoxEngine = {}));


/***/ }),

/***/ "owo8":
/*!**********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/PanelHeader.js ***!
  \**********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Button = __webpack_require__(/*! ../widgets/Button */ "rZxl");

var _Button2 = _interopRequireDefault(_Button);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _plotlyIcons = __webpack_require__(/*! plotly-icons */ "hwSx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var PanelHeader = function (_Component) {
  _inherits(PanelHeader, _Component);

  function PanelHeader() {
    _classCallCheck(this, PanelHeader);

    var _this = _possibleConstructorReturn(this, (PanelHeader.__proto__ || Object.getPrototypeOf(PanelHeader)).call(this));

    _this.state = { addPanelOpen: false };

    _this.togglePanel = _this.togglePanel.bind(_this);
    return _this;
  }

  _createClass(PanelHeader, [{
    key: 'togglePanel',
    value: function togglePanel() {
      this.setState({ addPanelOpen: !this.state.addPanelOpen });
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _ = this.context.localize;
      var _props = this.props,
          children = _props.children,
          addAction = _props.addAction,
          allowCollapse = _props.allowCollapse,
          toggleFolds = _props.toggleFolds,
          hasOpen = _props.hasOpen;

      // dropdown is styled with same styles as react-select component - see _dropdown.scss

      var icon = _react2.default.createElement(_plotlyIcons.PlusIcon, null);
      return !children && !addAction && !allowCollapse ? null : _react2.default.createElement(
        'div',
        { className: 'panel__header' },
        children && children.length ? _react2.default.createElement(
          'div',
          { className: 'panel__header__content' },
          children
        ) : null,
        _react2.default.createElement(
          'div',
          { className: 'panel__header__actions__container' },
          allowCollapse ? _react2.default.createElement(
            'div',
            { className: 'panel__header__collapse', onClick: toggleFolds },
            hasOpen ? _react2.default.createElement(
              'span',
              null,
              _react2.default.createElement(_plotlyIcons.ResizeDownIcon, null),
              _('Collapse All')
            ) : _react2.default.createElement(
              'span',
              null,
              _react2.default.createElement(_plotlyIcons.ResizeUpIcon, null),
              _('Expand All')
            )
          ) : null,
          addAction ? _react2.default.createElement(
            'div',
            { className: 'panel__header__action dropdown-container' },
            _react2.default.createElement(_Button2.default, {
              variant: 'primary',
              className: 'js-add-button',
              onClick: Array.isArray(addAction.handler) ? this.togglePanel : function () {
                return addAction.handler(_this2.context);
              },
              icon: icon,
              label: addAction.label
            }),
            this.state.addPanelOpen && _react2.default.createElement(
              'div',
              { className: 'Select' },
              _react2.default.createElement(
                'div',
                { className: 'Select-menu-outer' },
                _react2.default.createElement(
                  'div',
                  { className: 'Select-menu' },
                  addAction.handler.map(function (_ref) {
                    var label = _ref.label,
                        handler = _ref.handler;
                    return _react2.default.createElement(
                      'div',
                      {
                        className: 'Select-option',
                        key: label,
                        onClick: function onClick() {
                          handler(_this2.context);
                          _this2.togglePanel();
                        }
                      },
                      label
                    );
                  })
                )
              )
            )
          ) : null
        )
      );
    }
  }]);

  return PanelHeader;
}(_react.Component);

PanelHeader.contextTypes = {
  layout: _propTypes2.default.object,
  fullContainer: _propTypes2.default.object,
  onUpdate: _propTypes2.default.func,
  updateContainer: _propTypes2.default.func,
  localize: _propTypes2.default.func
};

PanelHeader.propTypes = {
  addAction: _propTypes2.default.object,
  allowCollapse: _propTypes2.default.bool,
  children: _propTypes2.default.node,
  hasOpen: _propTypes2.default.bool,
  toggleFolds: _propTypes2.default.func
};

exports.default = PanelHeader;
//# sourceMappingURL=PanelHeader.js.map

/***/ }),

/***/ "oxjq":
/*!****************************************************!*\
  !*** ./node_modules/escape-string-regexp/index.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;

module.exports = function (str) {
	if (typeof str !== 'string') {
		throw new TypeError('Expected a string');
	}

	return str.replace(matchOperatorsRe, '\\$&');
};


/***/ }),

/***/ "oz8K":
/*!*************************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/nested_property.js ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




var isNumeric = __webpack_require__(/*! fast-isnumeric */ "GbLo");
var isArrayOrTypedArray = __webpack_require__(/*! ./array */ "lCvc").isArrayOrTypedArray;

/**
 * convert a string s (such as 'xaxis.range[0]')
 * representing a property of nested object into set and get methods
 * also return the string and object so we don't have to keep track of them
 * allows [-1] for an array index, to set a property inside all elements
 * of an array
 * eg if obj = {arr: [{a: 1}, {a: 2}]}
 * you can do p = nestedProperty(obj, 'arr[-1].a')
 * but you cannot set the array itself this way, to do that
 * just set the whole array.
 * eg if obj = {arr: [1, 2, 3]}
 * you can't do nestedProperty(obj, 'arr[-1]').set(5)
 * but you can do nestedProperty(obj, 'arr').set([5, 5, 5])
 */
module.exports = function nestedProperty(container, propStr) {
    if(isNumeric(propStr)) propStr = String(propStr);
    else if(typeof propStr !== 'string' ||
            propStr.substr(propStr.length - 4) === '[-1]') {
        throw 'bad property string';
    }

    var j = 0;
    var propParts = propStr.split('.');
    var indexed;
    var indices;
    var i;

    // check for parts of the nesting hierarchy that are numbers (ie array elements)
    while(j < propParts.length) {
        // look for non-bracket chars, then any number of [##] blocks
        indexed = String(propParts[j]).match(/^([^\[\]]*)((\[\-?[0-9]*\])+)$/);
        if(indexed) {
            if(indexed[1]) propParts[j] = indexed[1];
            // allow propStr to start with bracketed array indices
            else if(j === 0) propParts.splice(0, 1);
            else throw 'bad property string';

            indices = indexed[2]
                .substr(1, indexed[2].length - 2)
                .split('][');

            for(i = 0; i < indices.length; i++) {
                j++;
                propParts.splice(j, 0, Number(indices[i]));
            }
        }
        j++;
    }

    if(typeof container !== 'object') {
        return badContainer(container, propStr, propParts);
    }

    return {
        set: npSet(container, propParts, propStr),
        get: npGet(container, propParts),
        astr: propStr,
        parts: propParts,
        obj: container
    };
};

function npGet(cont, parts) {
    return function() {
        var curCont = cont;
        var curPart;
        var allSame;
        var out;
        var i;
        var j;

        for(i = 0; i < parts.length - 1; i++) {
            curPart = parts[i];
            if(curPart === -1) {
                allSame = true;
                out = [];
                for(j = 0; j < curCont.length; j++) {
                    out[j] = npGet(curCont[j], parts.slice(i + 1))();
                    if(out[j] !== out[0]) allSame = false;
                }
                return allSame ? out[0] : out;
            }
            if(typeof curPart === 'number' && !isArrayOrTypedArray(curCont)) {
                return undefined;
            }
            curCont = curCont[curPart];
            if(typeof curCont !== 'object' || curCont === null) {
                return undefined;
            }
        }

        // only hit this if parts.length === 1
        if(typeof curCont !== 'object' || curCont === null) return undefined;

        out = curCont[parts[i]];
        if(out === null) return undefined;
        return out;
    };
}

/*
 * Can this value be deleted? We can delete `undefined`, and `null` except INSIDE an
 * *args* array.
 *
 * Previously we also deleted some `{}` and `[]`, in order to try and make set/unset
 * a net noop; but this causes far more complication than it's worth, and still had
 * lots of exceptions. See https://github.com/plotly/plotly.js/issues/1410
 *
 * *args* arrays get passed directly to API methods and we should respect null if
 * the user put it there, but otherwise null is deleted as we use it as code
 * in restyle/relayout/update for "delete this value" whereas undefined means
 * "ignore this edit"
 */
var ARGS_PATTERN = /(^|\.)args\[/;
function isDeletable(val, propStr) {
    return (val === undefined) || (val === null && !propStr.match(ARGS_PATTERN));
}

function npSet(cont, parts, propStr) {
    return function(val) {
        var curCont = cont;
        var propPart = '';
        var containerLevels = [[cont, propPart]];
        var toDelete = isDeletable(val, propStr);
        var curPart;
        var i;

        for(i = 0; i < parts.length - 1; i++) {
            curPart = parts[i];

            if(typeof curPart === 'number' && !isArrayOrTypedArray(curCont)) {
                throw 'array index but container is not an array';
            }

            // handle special -1 array index
            if(curPart === -1) {
                toDelete = !setArrayAll(curCont, parts.slice(i + 1), val, propStr);
                if(toDelete) break;
                else return;
            }

            if(!checkNewContainer(curCont, curPart, parts[i + 1], toDelete)) {
                break;
            }

            curCont = curCont[curPart];

            if(typeof curCont !== 'object' || curCont === null) {
                throw 'container is not an object';
            }

            propPart = joinPropStr(propPart, curPart);

            containerLevels.push([curCont, propPart]);
        }

        if(toDelete) {
            if(i === parts.length - 1) {
                delete curCont[parts[i]];

                // The one bit of pruning we still do: drop `undefined` from the end of arrays.
                // In case someone has already unset previous items, continue until we hit a
                // non-undefined value.
                if(Array.isArray(curCont) && +parts[i] === curCont.length - 1) {
                    while(curCont.length && curCont[curCont.length - 1] === undefined) {
                        curCont.pop();
                    }
                }
            }
        }
        else curCont[parts[i]] = val;
    };
}

function joinPropStr(propStr, newPart) {
    var toAdd = newPart;
    if(isNumeric(newPart)) toAdd = '[' + newPart + ']';
    else if(propStr) toAdd = '.' + newPart;

    return propStr + toAdd;
}

// handle special -1 array index
function setArrayAll(containerArray, innerParts, val, propStr) {
    var arrayVal = isArrayOrTypedArray(val);
    var allSet = true;
    var thisVal = val;
    var thisPropStr = propStr.replace('-1', 0);
    var deleteThis = arrayVal ? false : isDeletable(val, thisPropStr);
    var firstPart = innerParts[0];
    var i;

    for(i = 0; i < containerArray.length; i++) {
        thisPropStr = propStr.replace('-1', i);
        if(arrayVal) {
            thisVal = val[i % val.length];
            deleteThis = isDeletable(thisVal, thisPropStr);
        }
        if(deleteThis) allSet = false;
        if(!checkNewContainer(containerArray, i, firstPart, deleteThis)) {
            continue;
        }
        npSet(containerArray[i], innerParts, propStr.replace('-1', i))(thisVal);
    }
    return allSet;
}

/**
 * make new sub-container as needed.
 * returns false if there's no container and none is needed
 * because we're only deleting an attribute
 */
function checkNewContainer(container, part, nextPart, toDelete) {
    if(container[part] === undefined) {
        if(toDelete) return false;

        if(typeof nextPart === 'number') container[part] = [];
        else container[part] = {};
    }
    return true;
}

function badContainer(container, propStr, propParts) {
    return {
        set: function() { throw 'bad container'; },
        get: function() {},
        astr: propStr,
        parts: propParts,
        obj: container
    };
}


/***/ }),

/***/ "p/rL":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/bm.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var bm = moment.defineLocale('bm', {
    months : 'Zanwuyekalo_Fewuruyekalo_Marisikalo_Awirilikalo_Mɛkalo_Zuwɛnkalo_Zuluyekalo_Utikalo_Sɛtanburukalo_ɔkutɔburukalo_Nowanburukalo_Desanburukalo'.split('_'),
    monthsShort : 'Zan_Few_Mar_Awi_Mɛ_Zuw_Zul_Uti_Sɛt_ɔku_Now_Des'.split('_'),
    weekdays : 'Kari_Ntɛnɛn_Tarata_Araba_Alamisa_Juma_Sibiri'.split('_'),
    weekdaysShort : 'Kar_Ntɛ_Tar_Ara_Ala_Jum_Sib'.split('_'),
    weekdaysMin : 'Ka_Nt_Ta_Ar_Al_Ju_Si'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'MMMM [tile] D [san] YYYY',
        LLL : 'MMMM [tile] D [san] YYYY [lɛrɛ] HH:mm',
        LLLL : 'dddd MMMM [tile] D [san] YYYY [lɛrɛ] HH:mm'
    },
    calendar : {
        sameDay : '[Bi lɛrɛ] LT',
        nextDay : '[Sini lɛrɛ] LT',
        nextWeek : 'dddd [don lɛrɛ] LT',
        lastDay : '[Kunu lɛrɛ] LT',
        lastWeek : 'dddd [tɛmɛnen lɛrɛ] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : '%s kɔnɔ',
        past : 'a bɛ %s bɔ',
        s : 'sanga dama dama',
        ss : 'sekondi %d',
        m : 'miniti kelen',
        mm : 'miniti %d',
        h : 'lɛrɛ kelen',
        hh : 'lɛrɛ %d',
        d : 'tile kelen',
        dd : 'tile %d',
        M : 'kalo kelen',
        MM : 'kalo %d',
        y : 'san kelen',
        yy : 'san %d'
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return bm;

})));


/***/ }),

/***/ "p0j+":
/*!****************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/jupyterlab-chart-editor/style/index.css ***!
  \****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var escape = __webpack_require__(/*! ../../css-loader/lib/url/escape.js */ "sEG9");
exports = module.exports = __webpack_require__(/*! ../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/**\n  Copyright (c) Jupyter Development Team.\n  Distributed under the terms of the Modified BSD License.\n*/\n\n/* Add CSS variables to :root */\n:root {\n  --jp-icon-plotly: url(" + escape(__webpack_require__(/*! ./plotly.svg */ "hDFp")) + ");\n}\n\n/* Base styles */\n.jp-RenderedPlotlyEditor {\n  width: 100%;\n  height: 100%;\n  padding: 0;\n  overflow: hidden;\n}\n\n.jp-RenderedPlotlyEditor .container {\n  display: flex;\n  width: 100%;\n  height: 100%;\n}\n\n.jp-RenderedPlotlyEditor .plotly-editor {\n  width: 0;\n  transition: width 0.5s;\n}\n\n.jp-RenderedPlotlyEditor .plot {\n  width: 0;\n  height: 100%;\n  flex: 1;\n}\n\n/* Document styles */\n.jp-MimeDocument .jp-RenderedPlotlyEditor {\n  overflow: hidden;\n}\n\n/* Output styles */\n.jp-OutputArea .jp-RenderedPlotlyEditor {\n  min-height: 360px;\n  max-height: 540px;\n}\n\n/* Document icon */\n.jp-PlotlyIcon {\n  background-image: var(--jp-icon-plotly);\n}\n", ""]);

// exports


/***/ }),

/***/ "p0rm":
/*!***********************************************************************!*\
  !*** ./node_modules/@jupyterlab/settingeditor-extension/lib/index.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const application_1 = __webpack_require__(/*! @jupyterlab/application */ "FkFl");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const codeeditor_1 = __webpack_require__(/*! @jupyterlab/codeeditor */ "sLCx");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const rendermime_1 = __webpack_require__(/*! @jupyterlab/rendermime */ "Towz");
const settingeditor_1 = __webpack_require__(/*! @jupyterlab/settingeditor */ "plMY");
/**
 * The command IDs used by the setting editor.
 */
var CommandIDs;
(function (CommandIDs) {
    CommandIDs.debug = 'settingeditor:debug';
    CommandIDs.open = 'settingeditor:open';
    CommandIDs.revert = 'settingeditor:revert';
    CommandIDs.save = 'settingeditor:save';
})(CommandIDs || (CommandIDs = {}));
/**
 * The default setting editor extension.
 */
const plugin = {
    id: '@jupyterlab/settingeditor-extension:plugin',
    requires: [
        application_1.ILayoutRestorer,
        coreutils_1.ISettingRegistry,
        codeeditor_1.IEditorServices,
        coreutils_1.IStateDB,
        rendermime_1.IRenderMimeRegistry,
        apputils_1.ICommandPalette
    ],
    autoStart: true,
    provides: settingeditor_1.ISettingEditorTracker,
    activate
};
/**
 * Activate the setting editor extension.
 */
function activate(app, restorer, registry, editorServices, state, rendermime, palette) {
    const { commands, shell } = app;
    const namespace = 'setting-editor';
    const factoryService = editorServices.factoryService;
    const editorFactory = factoryService.newInlineEditor;
    const tracker = new apputils_1.InstanceTracker({
        namespace
    });
    let editor;
    // Handle state restoration.
    restorer.restore(tracker, {
        command: CommandIDs.open,
        args: widget => ({}),
        name: widget => namespace
    });
    commands.addCommand(CommandIDs.debug, {
        execute: () => {
            tracker.currentWidget.content.toggleDebug();
        },
        iconClass: 'jp-MaterialIcon jp-BugIcon',
        label: 'Debug User Settings In Inspector',
        isToggled: () => tracker.currentWidget.content.isDebugVisible
    });
    commands.addCommand(CommandIDs.open, {
        execute: () => {
            if (tracker.currentWidget) {
                shell.activateById(tracker.currentWidget.id);
                return;
            }
            const key = plugin.id;
            const when = app.restored;
            editor = new settingeditor_1.SettingEditor({
                commands: {
                    registry: commands,
                    debug: CommandIDs.debug,
                    revert: CommandIDs.revert,
                    save: CommandIDs.save
                },
                editorFactory,
                key,
                registry,
                rendermime,
                state,
                when
            });
            // Notify the command registry when the visibility status of the setting
            // editor's commands change. The setting editor toolbar listens for this
            // signal from the command registry.
            editor.commandsChanged.connect((sender, args) => {
                args.forEach(id => {
                    commands.notifyCommandChanged(id);
                });
            });
            editor.id = namespace;
            editor.title.label = 'Settings';
            editor.title.iconClass = 'jp-SettingsIcon';
            let main = new apputils_1.MainAreaWidget({ content: editor });
            tracker.add(main);
            shell.addToMainArea(main);
        },
        label: 'Advanced Settings Editor'
    });
    palette.addItem({ category: 'Settings', command: CommandIDs.open });
    commands.addCommand(CommandIDs.revert, {
        execute: () => {
            tracker.currentWidget.content.revert();
        },
        iconClass: 'jp-MaterialIcon jp-UndoIcon',
        label: 'Revert User Settings',
        isEnabled: () => tracker.currentWidget.content.canRevertRaw
    });
    commands.addCommand(CommandIDs.save, {
        execute: () => tracker.currentWidget.content.save(),
        iconClass: 'jp-MaterialIcon jp-SaveIcon',
        label: 'Save User Settings',
        isEnabled: () => tracker.currentWidget.content.canSaveRaw
    });
    return tracker;
}
exports.default = plugin;


/***/ }),

/***/ "p1kU":
/*!*****************************************************!*\
  !*** ./node_modules/fbjs/lib/getElementPosition.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks
 */

var getElementRect = __webpack_require__(/*! ./getElementRect */ "iatg");

/**
 * Gets an element's position in pixels relative to the viewport. The returned
 * object represents the position of the element's top left corner.
 *
 * @param {DOMElement} element
 * @return {object}
 */
function getElementPosition(element) {
  var rect = getElementRect(element);
  return {
    x: rect.left,
    y: rect.top,
    width: rect.right - rect.left,
    height: rect.bottom - rect.top
  };
}

module.exports = getElementPosition;

/***/ }),

/***/ "p5Q0":
/*!**************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/DefaultEditor.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _components = __webpack_require__(/*! ./components */ "yF51");

var _default_panels = __webpack_require__(/*! ./default_panels */ "sHuL");

var _StyleColorbarsPanel = __webpack_require__(/*! ./default_panels/StyleColorbarsPanel */ "51Cs");

var _Logo = __webpack_require__(/*! ./components/widgets/Logo */ "2mh1");

var _Logo2 = _interopRequireDefault(_Logo);

var _constants = __webpack_require__(/*! ./lib/constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var DefaultEditor = function (_Component) {
  _inherits(DefaultEditor, _Component);

  function DefaultEditor(props, context) {
    _classCallCheck(this, DefaultEditor);

    var _this = _possibleConstructorReturn(this, (DefaultEditor.__proto__ || Object.getPrototypeOf(DefaultEditor)).call(this, props, context));

    _this.hasTransforms = _this.hasTransforms.bind(_this);
    _this.hasAxes = _this.hasAxes.bind(_this);
    _this.hasMenus = _this.hasMenus.bind(_this);
    _this.hasSliders = _this.hasSliders.bind(_this);
    _this.hasColorbars = _this.hasColorbars.bind(_this);
    return _this;
  }

  _createClass(DefaultEditor, [{
    key: 'hasTransforms',
    value: function hasTransforms() {
      return this.context.fullData.some(function (d) {
        return _constants.TRANSFORMABLE_TRACES.includes(d.type);
      });
    }
  }, {
    key: 'hasAxes',
    value: function hasAxes() {
      var _this2 = this;

      return Object.keys(this.context.fullLayout._subplots).filter(function (type) {
        return !['cartesian', 'mapbox'].includes(type) && _this2.context.fullLayout._subplots[type].length > 0;
      }).length > 0;
    }
  }, {
    key: 'hasMenus',
    value: function hasMenus() {
      var _context$fullLayout$u = this.context.fullLayout.updatemenus,
          updatemenus = _context$fullLayout$u === undefined ? [] : _context$fullLayout$u;


      return updatemenus.length > 0;
    }
  }, {
    key: 'hasSliders',
    value: function hasSliders() {
      var _context$layout$slide = this.context.layout.sliders,
          sliders = _context$layout$slide === undefined ? [] : _context$layout$slide;


      return sliders.length > 0;
    }
  }, {
    key: 'hasColorbars',
    value: function hasColorbars() {
      return this.context.fullData.some(function (d) {
        return (0, _StyleColorbarsPanel.traceHasColorbar)({}, d);
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var _ = this.context.localize;
      var logo = this.props.logoSrc && _react2.default.createElement(_Logo2.default, { src: this.props.logoSrc });

      return _react2.default.createElement(
        _components.PanelMenuWrapper,
        { menuPanelOrder: this.props.menuPanelOrder },
        logo ? logo : null,
        _react2.default.createElement(_default_panels.GraphCreatePanel, { group: _('Structure'), name: _('Traces') }),
        _react2.default.createElement(_default_panels.GraphSubplotsPanel, { group: _('Structure'), name: _('Subplots') }),
        this.hasTransforms() && _react2.default.createElement(_default_panels.GraphTransformsPanel, { group: _('Structure'), name: _('Transforms') }),
        _react2.default.createElement(_default_panels.StyleLayoutPanel, { group: _('Style'), name: _('General') }),
        _react2.default.createElement(_default_panels.StyleTracesPanel, { group: _('Style'), name: _('Traces') }),
        this.hasAxes() && _react2.default.createElement(_default_panels.StyleAxesPanel, { group: _('Style'), name: _('Axes') }),
        _react2.default.createElement(_default_panels.StyleLegendPanel, { group: _('Style'), name: _('Legend') }),
        this.hasColorbars() && _react2.default.createElement(_default_panels.StyleColorbarsPanel, { group: _('Style'), name: _('Color Bars') }),
        _react2.default.createElement(_default_panels.StyleNotesPanel, { group: _('Style'), name: _('Annotation') }),
        _react2.default.createElement(_default_panels.StyleShapesPanel, { group: _('Style'), name: _('Shapes') }),
        _react2.default.createElement(_default_panels.StyleImagesPanel, { group: _('Style'), name: _('Images') }),
        this.hasSliders() && _react2.default.createElement(_default_panels.StyleSlidersPanel, { group: _('Style'), name: _('Sliders') }),
        this.hasMenus() && _react2.default.createElement(_default_panels.StyleUpdateMenusPanel, { group: _('Style'), name: _('Menus') }),
        this.props.children ? this.props.children : null
      );
    }
  }]);

  return DefaultEditor;
}(_react.Component);

DefaultEditor.propTypes = {
  children: _propTypes2.default.node,
  logoSrc: _propTypes2.default.string,
  menuPanelOrder: _propTypes2.default.array
};

DefaultEditor.contextTypes = {
  localize: _propTypes2.default.func,
  fullData: _propTypes2.default.array,
  fullLayout: _propTypes2.default.object,
  layout: _propTypes2.default.object
};

exports.default = DefaultEditor;
//# sourceMappingURL=DefaultEditor.js.map

/***/ }),

/***/ "p8yl":
/*!*******************************************************!*\
  !*** ./node_modules/react-color/lib/helpers/color.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.red = undefined;

var _each = __webpack_require__(/*! lodash/each */ "xkGU");

var _each2 = _interopRequireDefault(_each);

var _tinycolor = __webpack_require__(/*! tinycolor2 */ "Zss7");

var _tinycolor2 = _interopRequireDefault(_tinycolor);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = {
  simpleCheckForValidColor: function simpleCheckForValidColor(data) {
    var keysToCheck = ['r', 'g', 'b', 'a', 'h', 's', 'l', 'v'];
    var checked = 0;
    var passed = 0;
    (0, _each2.default)(keysToCheck, function (letter) {
      if (data[letter]) {
        checked += 1;
        if (!isNaN(data[letter])) {
          passed += 1;
        }
        if (letter === 's' || letter === 'l') {
          var percentPatt = /^\d+%$/;
          if (percentPatt.test(data[letter])) {
            passed += 1;
          }
        }
      }
    });
    return checked === passed ? data : false;
  },
  toState: function toState(data, oldHue) {
    var color = data.hex ? (0, _tinycolor2.default)(data.hex) : (0, _tinycolor2.default)(data);
    var hsl = color.toHsl();
    var hsv = color.toHsv();
    var rgb = color.toRgb();
    var hex = color.toHex();
    if (hsl.s === 0) {
      hsl.h = oldHue || 0;
      hsv.h = oldHue || 0;
    }
    var transparent = hex === '000000' && rgb.a === 0;

    return {
      hsl: hsl,
      hex: transparent ? 'transparent' : '#' + hex,
      rgb: rgb,
      hsv: hsv,
      oldHue: data.h || oldHue || hsl.h,
      source: data.source
    };
  },
  isValidHex: function isValidHex(hex) {
    // disable hex4 and hex8
    var lh = String(hex).charAt(0) === '#' ? 1 : 0;
    return hex.length !== 4 + lh && hex.length < 7 + lh && (0, _tinycolor2.default)(hex).isValid();
  },
  getContrastingColor: function getContrastingColor(data) {
    if (!data) {
      return '#fff';
    }
    var col = this.toState(data);
    if (col.hex === 'transparent') {
      return 'rgba(0,0,0,0.4)';
    }
    var yiq = (col.rgb.r * 299 + col.rgb.g * 587 + col.rgb.b * 114) / 1000;
    return yiq >= 128 ? '#000' : '#fff';
  }
};
var red = exports.red = {
  hsl: { a: 1, h: 0, l: 0.5, s: 1 },
  hex: '#ff0000',
  rgb: { r: 255, g: 0, b: 0, a: 1 },
  hsv: { h: 0, s: 1, v: 1, a: 1 }
};

/***/ }),

/***/ "pFRH":
/*!*************************************************!*\
  !*** ./node_modules/lodash/_baseSetToString.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var constant = __webpack_require__(/*! ./constant */ "cvCv"),
    defineProperty = __webpack_require__(/*! ./_defineProperty */ "O0oS"),
    identity = __webpack_require__(/*! ./identity */ "zZ0H");

/**
 * 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
  });
};

module.exports = baseSetToString;


/***/ }),

/***/ "pGKX":
/*!****************************************************************!*\
  !*** ./node_modules/plotly.js/src/components/fx/attributes.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var fontAttrs = __webpack_require__(/*! ../../plots/font_attributes */ "mEVB");

module.exports = {
    hoverlabel: {
        bgcolor: {
            valType: 'color',
            role: 'style',
            arrayOk: true,
            editType: 'none',
            description: [
                'Sets the background color of the hover labels for this trace'
            ].join(' ')
        },
        bordercolor: {
            valType: 'color',
            role: 'style',
            arrayOk: true,
            editType: 'none',
            description: [
                'Sets the border color of the hover labels for this trace.'
            ].join(' ')
        },
        font: fontAttrs({
            arrayOk: true,
            editType: 'none',
            description: 'Sets the font used in hover labels.'
        }),
        namelength: {
            valType: 'integer',
            min: -1,
            arrayOk: true,
            role: 'style',
            editType: 'none',
            description: [
                'Sets the length (in number of characters) of the trace name in',
                'the hover labels for this trace. -1 shows the whole name',
                'regardless of length. 0-3 shows the first 0-3 characters, and',
                'an integer >3 will show the whole name if it is less than that',
                'many characters, but if it is longer, will truncate to',
                '`namelength - 3` characters and add an ellipsis.'
            ].join(' ')
        },
        editType: 'calc'
    }
};


/***/ }),

/***/ "pHe9":
/*!**************************************************************!*\
  !*** ./node_modules/@phosphor/collections/lib/linkedlist.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
/**
 * A generic doubly-linked list.
 */
var LinkedList = (function () {
    /**
     * Construct a new linked list.
     */
    function LinkedList() {
        this._first = null;
        this._last = null;
        this._length = 0;
    }
    Object.defineProperty(LinkedList.prototype, "isEmpty", {
        /**
         * Whether the list is empty.
         *
         * #### Complexity
         * Constant.
         */
        get: function () {
            return this._length === 0;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(LinkedList.prototype, "length", {
        /**
         * The length of the list.
         *
         * #### Complexity
         * Constant.
         */
        get: function () {
            return this._length;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(LinkedList.prototype, "first", {
        /**
         * The first value in the list.
         *
         * This is `undefined` if the list is empty.
         *
         * #### Complexity
         * Constant.
         */
        get: function () {
            return this._first ? this._first.value : undefined;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(LinkedList.prototype, "last", {
        /**
         * The last value in the list.
         *
         * This is `undefined` if the list is empty.
         *
         * #### Complexity
         * Constant.
         */
        get: function () {
            return this._last ? this._last.value : undefined;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(LinkedList.prototype, "firstNode", {
        /**
         * The first node in the list.
         *
         * This is `null` if the list is empty.
         *
         * #### Complexity
         * Constant.
         */
        get: function () {
            return this._first;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(LinkedList.prototype, "lastNode", {
        /**
         * The last node in the list.
         *
         * This is `null` if the list is empty.
         *
         * #### Complexity
         * Constant.
         */
        get: function () {
            return this._last;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Create an iterator over the values in the list.
     *
     * @returns A new iterator starting with the first value.
     *
     * #### Complexity
     * Constant.
     */
    LinkedList.prototype.iter = function () {
        return new LinkedList.ForwardValueIterator(this._first);
    };
    /**
     * Create a reverse iterator over the values in the list.
     *
     * @returns A new iterator starting with the last value.
     *
     * #### Complexity
     * Constant.
     */
    LinkedList.prototype.retro = function () {
        return new LinkedList.RetroValueIterator(this._last);
    };
    /**
     * Create an iterator over the nodes in the list.
     *
     * @returns A new iterator starting with the first node.
     *
     * #### Complexity
     * Constant.
     */
    LinkedList.prototype.nodes = function () {
        return new LinkedList.ForwardNodeIterator(this._first);
    };
    /**
     * Create a reverse iterator over the nodes in the list.
     *
     * @returns A new iterator starting with the last node.
     *
     * #### Complexity
     * Constant.
     */
    LinkedList.prototype.retroNodes = function () {
        return new LinkedList.RetroNodeIterator(this._last);
    };
    /**
     * Add a value to the beginning of the list.
     *
     * @param value - The value to add to the beginning of the list.
     *
     * @returns The list node which holds the value.
     *
     * #### Complexity
     * Constant.
     */
    LinkedList.prototype.addFirst = function (value) {
        var node = new Private.LinkedListNode(this, value);
        if (!this._first) {
            this._first = node;
            this._last = node;
        }
        else {
            node.next = this._first;
            this._first.prev = node;
            this._first = node;
        }
        this._length++;
        return node;
    };
    /**
     * Add a value to the end of the list.
     *
     * @param value - The value to add to the end of the list.
     *
     * @returns The list node which holds the value.
     *
     * #### Complexity
     * Constant.
     */
    LinkedList.prototype.addLast = function (value) {
        var node = new Private.LinkedListNode(this, value);
        if (!this._last) {
            this._first = node;
            this._last = node;
        }
        else {
            node.prev = this._last;
            this._last.next = node;
            this._last = node;
        }
        this._length++;
        return node;
    };
    /**
     * Insert a value before a specific node in the list.
     *
     * @param value - The value to insert before the reference node.
     *
     * @param ref - The reference node of interest. If this is `null`,
     *   the value will be added to the beginning of the list.
     *
     * @returns The list node which holds the value.
     *
     * #### Notes
     * The reference node must be owned by the list.
     *
     * #### Complexity
     * Constant.
     */
    LinkedList.prototype.insertBefore = function (value, ref) {
        if (!ref || ref === this._first) {
            return this.addFirst(value);
        }
        if (!(ref instanceof Private.LinkedListNode) || ref.list !== this) {
            throw new Error('Reference node is not owned by the list.');
        }
        var node = new Private.LinkedListNode(this, value);
        var _ref = ref;
        var prev = _ref.prev;
        node.next = _ref;
        node.prev = prev;
        _ref.prev = node;
        prev.next = node;
        this._length++;
        return node;
    };
    /**
     * Insert a value after a specific node in the list.
     *
     * @param value - The value to insert after the reference node.
     *
     * @param ref - The reference node of interest. If this is `null`,
     *   the value will be added to the end of the list.
     *
     * @returns The list node which holds the value.
     *
     * #### Notes
     * The reference node must be owned by the list.
     *
     * #### Complexity
     * Constant.
     */
    LinkedList.prototype.insertAfter = function (value, ref) {
        if (!ref || ref === this._last) {
            return this.addLast(value);
        }
        if (!(ref instanceof Private.LinkedListNode) || ref.list !== this) {
            throw new Error('Reference node is not owned by the list.');
        }
        var node = new Private.LinkedListNode(this, value);
        var _ref = ref;
        var next = _ref.next;
        node.next = next;
        node.prev = _ref;
        _ref.next = node;
        next.prev = node;
        this._length++;
        return node;
    };
    /**
     * Remove and return the value at the beginning of the list.
     *
     * @returns The removed value, or `undefined` if the list is empty.
     *
     * #### Complexity
     * Constant.
     */
    LinkedList.prototype.removeFirst = function () {
        var node = this._first;
        if (!node) {
            return undefined;
        }
        if (node === this._last) {
            this._first = null;
            this._last = null;
        }
        else {
            this._first = node.next;
            this._first.prev = null;
        }
        node.list = null;
        node.next = null;
        node.prev = null;
        this._length--;
        return node.value;
    };
    /**
     * Remove and return the value at the end of the list.
     *
     * @returns The removed value, or `undefined` if the list is empty.
     *
     * #### Complexity
     * Constant.
     */
    LinkedList.prototype.removeLast = function () {
        var node = this._last;
        if (!node) {
            return undefined;
        }
        if (node === this._first) {
            this._first = null;
            this._last = null;
        }
        else {
            this._last = node.prev;
            this._last.next = null;
        }
        node.list = null;
        node.next = null;
        node.prev = null;
        this._length--;
        return node.value;
    };
    /**
     * Remove a specific node from the list.
     *
     * @param node - The node to remove from the list.
     *
     * #### Complexity
     * Constant.
     *
     * #### Notes
     * The node must be owned by the list.
     */
    LinkedList.prototype.removeNode = function (node) {
        if (!(node instanceof Private.LinkedListNode) || node.list !== this) {
            throw new Error('Node is not owned by the list.');
        }
        var _node = node;
        if (_node === this._first && _node === this._last) {
            this._first = null;
            this._last = null;
        }
        else if (_node === this._first) {
            this._first = _node.next;
            this._first.prev = null;
        }
        else if (_node === this._last) {
            this._last = _node.prev;
            this._last.next = null;
        }
        else {
            _node.next.prev = _node.prev;
            _node.prev.next = _node.next;
        }
        _node.list = null;
        _node.next = null;
        _node.prev = null;
        this._length--;
    };
    /**
     * Remove all values from the list.
     *
     * #### Complexity
     * Linear.
     */
    LinkedList.prototype.clear = function () {
        var node = this._first;
        while (node) {
            var next = node.next;
            node.list = null;
            node.prev = null;
            node.next = null;
            node = next;
        }
        this._first = null;
        this._last = null;
        this._length = 0;
    };
    return LinkedList;
}());
exports.LinkedList = LinkedList;
/**
 * The namespace for the `LinkedList` class statics.
 */
(function (LinkedList) {
    /**
     * Create a linked list from an iterable of values.
     *
     * @param values - The iterable or array-like object of interest.
     *
     * @returns A new linked list initialized with the given values.
     */
    function from(values) {
        var list = new LinkedList();
        algorithm_1.each(values, function (value) { list.addLast(value); });
        return list;
    }
    LinkedList.from = from;
    /**
     * A forward iterator for values in a linked list.
     */
    var ForwardValueIterator = (function () {
        /**
         * Construct a forward value iterator.
         *
         * @param node - The first node in the list.
         */
        function ForwardValueIterator(node) {
            this._node = node;
        }
        /**
         * Get an iterator over the object's values.
         *
         * @returns An iterator which yields the object's values.
         */
        ForwardValueIterator.prototype.iter = function () {
            return this;
        };
        /**
         * Create an independent clone of the iterator.
         *
         * @returns A new independent clone of the iterator.
         */
        ForwardValueIterator.prototype.clone = function () {
            return new ForwardValueIterator(this._node);
        };
        /**
         * Get the next value from the iterator.
         *
         * @returns The next value from the iterator, or `undefined`.
         */
        ForwardValueIterator.prototype.next = function () {
            if (!this._node) {
                return undefined;
            }
            var node = this._node;
            this._node = node.next;
            return node.value;
        };
        return ForwardValueIterator;
    }());
    LinkedList.ForwardValueIterator = ForwardValueIterator;
    /**
     * A reverse iterator for values in a linked list.
     */
    var RetroValueIterator = (function () {
        /**
         * Construct a retro value iterator.
         *
         * @param node - The last node in the list.
         */
        function RetroValueIterator(node) {
            this._node = node;
        }
        /**
         * Get an iterator over the object's values.
         *
         * @returns An iterator which yields the object's values.
         */
        RetroValueIterator.prototype.iter = function () {
            return this;
        };
        /**
         * Create an independent clone of the iterator.
         *
         * @returns A new independent clone of the iterator.
         */
        RetroValueIterator.prototype.clone = function () {
            return new RetroValueIterator(this._node);
        };
        /**
         * Get the next value from the iterator.
         *
         * @returns The next value from the iterator, or `undefined`.
         */
        RetroValueIterator.prototype.next = function () {
            if (!this._node) {
                return undefined;
            }
            var node = this._node;
            this._node = node.prev;
            return node.value;
        };
        return RetroValueIterator;
    }());
    LinkedList.RetroValueIterator = RetroValueIterator;
    /**
     * A forward iterator for nodes in a linked list.
     */
    var ForwardNodeIterator = (function () {
        /**
         * Construct a forward node iterator.
         *
         * @param node - The first node in the list.
         */
        function ForwardNodeIterator(node) {
            this._node = node;
        }
        /**
         * Get an iterator over the object's values.
         *
         * @returns An iterator which yields the object's values.
         */
        ForwardNodeIterator.prototype.iter = function () {
            return this;
        };
        /**
         * Create an independent clone of the iterator.
         *
         * @returns A new independent clone of the iterator.
         */
        ForwardNodeIterator.prototype.clone = function () {
            return new ForwardNodeIterator(this._node);
        };
        /**
         * Get the next value from the iterator.
         *
         * @returns The next value from the iterator, or `undefined`.
         */
        ForwardNodeIterator.prototype.next = function () {
            if (!this._node) {
                return undefined;
            }
            var node = this._node;
            this._node = node.next;
            return node;
        };
        return ForwardNodeIterator;
    }());
    LinkedList.ForwardNodeIterator = ForwardNodeIterator;
    /**
     * A reverse iterator for nodes in a linked list.
     */
    var RetroNodeIterator = (function () {
        /**
         * Construct a retro node iterator.
         *
         * @param node - The last node in the list.
         */
        function RetroNodeIterator(node) {
            this._node = node;
        }
        /**
         * Get an iterator over the object's values.
         *
         * @returns An iterator which yields the object's values.
         */
        RetroNodeIterator.prototype.iter = function () {
            return this;
        };
        /**
         * Create an independent clone of the iterator.
         *
         * @returns A new independent clone of the iterator.
         */
        RetroNodeIterator.prototype.clone = function () {
            return new RetroNodeIterator(this._node);
        };
        /**
         * Get the next value from the iterator.
         *
         * @returns The next value from the iterator, or `undefined`.
         */
        RetroNodeIterator.prototype.next = function () {
            if (!this._node) {
                return undefined;
            }
            var node = this._node;
            this._node = node.prev;
            return node;
        };
        return RetroNodeIterator;
    }());
    LinkedList.RetroNodeIterator = RetroNodeIterator;
})(LinkedList = exports.LinkedList || (exports.LinkedList = {}));
exports.LinkedList = LinkedList;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * The internal linked list node implementation.
     */
    var LinkedListNode = (function () {
        /**
         * Construct a new linked list node.
         *
         * @param list - The list which owns the node.
         *
         * @param value - The value for the link.
         */
        function LinkedListNode(list, value) {
            /**
             * The linked list which created and owns the node.
             */
            this.list = null;
            /**
             * The next node in the list.
             */
            this.next = null;
            /**
             * The previous node in the list.
             */
            this.prev = null;
            this.list = list;
            this.value = value;
        }
        return LinkedListNode;
    }());
    Private.LinkedListNode = LinkedListNode;
})(Private || (Private = {}));


/***/ }),

/***/ "pMAR":
/*!****************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/localize.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




var Registry = __webpack_require__(/*! ../registry */ "Nx4I");

/**
 * localize: translate a string for the current locale
 *
 * @param {object} gd: the graphDiv for context
 *  gd._context.locale determines the language (& optional region/country)
 *  the dictionary for each locale may either be supplied in
 *  gd._context.locales or globally via Plotly.register
 * @param {string} s: the string to translate
 */
module.exports = function localize(gd, s) {
    var locale = gd._context.locale;

    /*
     * Priority of lookup:
     *     contextDicts[locale],
     *     registeredDicts[locale],
     *     contextDicts[baseLocale], (if baseLocale is distinct)
     *     registeredDicts[baseLocale]
     * Return the first translation we find.
     * This way if you have a regionalization you are allowed to specify
     * only what's different from the base locale, everything else will
     * fall back on the base.
     */
    for(var i = 0; i < 2; i++) {
        var locales = gd._context.locales;
        for(var j = 0; j < 2; j++) {
            var dict = (locales[locale] || {}).dictionary;
            if(dict) {
                var out = dict[s];
                if(out) return out;
            }
            locales = Registry.localeRegistry;
        }

        var baseLocale = locale.split('-')[0];
        if(baseLocale === locale) break;
        locale = baseLocale;
    }

    return s;
};


/***/ }),

/***/ "pMj9":
/*!****************************************************************!*\
  !*** ./node_modules/react-tabs/esm/helpers/childrenDeepMap.js ***!
  \****************************************************************/
/*! exports provided: deepMap, deepForEach */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deepMap", function() { return deepMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deepForEach", function() { return deepForEach; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "q1tI");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _elementTypes__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./elementTypes */ "fxcN");
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }




function isTabChild(child) {
  return Object(_elementTypes__WEBPACK_IMPORTED_MODULE_1__["isTab"])(child) || Object(_elementTypes__WEBPACK_IMPORTED_MODULE_1__["isTabList"])(child) || Object(_elementTypes__WEBPACK_IMPORTED_MODULE_1__["isTabPanel"])(child);
}

function deepMap(children, callback) {
  return react__WEBPACK_IMPORTED_MODULE_0__["Children"].map(children, function (child) {
    // null happens when conditionally rendering TabPanel/Tab
    // see https://github.com/reactjs/react-tabs/issues/37
    if (child === null) return null;

    if (isTabChild(child)) {
      return callback(child);
    }

    if (child.props && child.props.children && typeof child.props.children === 'object') {
      // Clone the child that has children and map them too
      return Object(react__WEBPACK_IMPORTED_MODULE_0__["cloneElement"])(child, _objectSpread({}, child.props, {
        children: deepMap(child.props.children, callback)
      }));
    }

    return child;
  });
}
function deepForEach(children, callback) {
  return react__WEBPACK_IMPORTED_MODULE_0__["Children"].forEach(children, function (child) {
    // null happens when conditionally rendering TabPanel/Tab
    // see https://github.com/reactjs/react-tabs/issues/37
    if (child === null) return;

    if (Object(_elementTypes__WEBPACK_IMPORTED_MODULE_1__["isTab"])(child) || Object(_elementTypes__WEBPACK_IMPORTED_MODULE_1__["isTabPanel"])(child)) {
      callback(child);
    } else if (child.props && child.props.children && typeof child.props.children === 'object') {
      if (Object(_elementTypes__WEBPACK_IMPORTED_MODULE_1__["isTabList"])(child)) callback(child);
      deepForEach(child.props.children, callback);
    }
  });
}

/***/ }),

/***/ "pMuX":
/*!********************************************************!*\
  !*** ./node_modules/@phosphor/algorithm/lib/stride.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var iter_1 = __webpack_require__(/*! ./iter */ "DMSk");
/**
 * Iterate over an iterable using a stepped increment.
 *
 * @param object - The iterable or array-like object of interest.
 *
 * @param step - The distance to step on each iteration. A value
 *   of less than `1` will behave the same as a value of `1`.
 *
 * @returns An iterator which traverses the iterable step-wise.
 *
 * #### Example
 * ```typescript
 * import { stride, toArray } from '@phosphor/algorithm';
 *
 * let data = [1, 2, 3, 4, 5, 6];
 *
 * let stream = stride(data, 2);
 *
 * toArray(stream);  // [1, 3, 5];
 * ```
 */
function stride(object, step) {
    return new StrideIterator(iter_1.iter(object), step);
}
exports.stride = stride;
/**
 * An iterator which traverses a source iterator step-wise.
 */
var StrideIterator = (function () {
    /**
     * Construct a new stride iterator.
     *
     * @param source - The iterator of values of interest.
     *
     * @param step - The distance to step on each iteration. A value
     *   of less than `1` will behave the same as a value of `1`.
     */
    function StrideIterator(source, step) {
        this._source = source;
        this._step = step;
    }
    /**
     * Get an iterator over the object's values.
     *
     * @returns An iterator which yields the object's values.
     */
    StrideIterator.prototype.iter = function () {
        return this;
    };
    /**
     * Create an independent clone of the iterator.
     *
     * @returns A new independent clone of the iterator.
     */
    StrideIterator.prototype.clone = function () {
        return new StrideIterator(this._source.clone(), this._step);
    };
    /**
     * Get the next value from the iterator.
     *
     * @returns The next value from the iterator, or `undefined`.
     */
    StrideIterator.prototype.next = function () {
        var value = this._source.next();
        for (var n = this._step - 1; n > 0; --n) {
            this._source.next();
        }
        return value;
    };
    return StrideIterator;
}());
exports.StrideIterator = StrideIterator;


/***/ }),

/***/ "pOV6":
/*!**********************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/input.js ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _cssSyntaxError = __webpack_require__(/*! ./css-syntax-error */ "RTLL");

var _cssSyntaxError2 = _interopRequireDefault(_cssSyntaxError);

var _previousMap = __webpack_require__(/*! ./previous-map */ "3Jol");

var _previousMap2 = _interopRequireDefault(_previousMap);

var _path = __webpack_require__(/*! path */ "33yf");

var _path2 = _interopRequireDefault(_path);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var sequence = 0;

/**
 * Represents the source CSS.
 *
 * @example
 * const root  = postcss.parse(css, { from: file });
 * const input = root.source.input;
 */

var Input = function () {

    /**
     * @param {string} css    - input CSS source
     * @param {object} [opts] - {@link Processor#process} options
     */
    function Input(css) {
        var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

        _classCallCheck(this, Input);

        if (css === null || (typeof css === 'undefined' ? 'undefined' : _typeof(css)) === 'object' && !css.toString) {
            throw new Error('PostCSS received ' + css + ' instead of CSS string');
        }

        /**
         * @member {string} - input CSS source
         *
         * @example
         * const input = postcss.parse('a{}', { from: file }).input;
         * input.css //=> "a{}";
         */
        this.css = css.toString();

        if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') {
            this.css = this.css.slice(1);
        }

        if (opts.from) {
            if (/^\w+:\/\//.test(opts.from)) {
                /**
                 * @member {string} - The absolute path to the CSS source file
                 *                    defined with the `from` option.
                 *
                 * @example
                 * const root = postcss.parse(css, { from: 'a.css' });
                 * root.source.input.file //=> '/home/ai/a.css'
                 */
                this.file = opts.from;
            } else {
                this.file = _path2.default.resolve(opts.from);
            }
        }

        var map = new _previousMap2.default(this.css, opts);
        if (map.text) {
            /**
             * @member {PreviousMap} - The input source map passed from
             *                         a compilation step before PostCSS
             *                         (for example, from Sass compiler).
             *
             * @example
             * root.source.input.map.consumer().sources //=> ['a.sass']
             */
            this.map = map;
            var file = map.consumer().file;
            if (!this.file && file) this.file = this.mapResolve(file);
        }

        if (!this.file) {
            sequence += 1;
            /**
             * @member {string} - The unique ID of the CSS source. It will be
             *                    created if `from` option is not provided
             *                    (because PostCSS does not know the file path).
             *
             * @example
             * const root = postcss.parse(css);
             * root.source.input.file //=> undefined
             * root.source.input.id   //=> "<input css 1>"
             */
            this.id = '<input css ' + sequence + '>';
        }
        if (this.map) this.map.file = this.from;
    }

    Input.prototype.error = function error(message, line, column) {
        var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};

        var result = void 0;
        var origin = this.origin(line, column);
        if (origin) {
            result = new _cssSyntaxError2.default(message, origin.line, origin.column, origin.source, origin.file, opts.plugin);
        } else {
            result = new _cssSyntaxError2.default(message, line, column, this.css, this.file, opts.plugin);
        }

        result.input = { line: line, column: column, source: this.css };
        if (this.file) result.input.file = this.file;

        return result;
    };

    /**
     * Reads the input source map and returns a symbol position
     * in the input source (e.g., in a Sass file that was compiled
     * to CSS before being passed to PostCSS).
     *
     * @param {number} line   - line in input CSS
     * @param {number} column - column in input CSS
     *
     * @return {filePosition} position in input source
     *
     * @example
     * root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 }
     */


    Input.prototype.origin = function origin(line, column) {
        if (!this.map) return false;
        var consumer = this.map.consumer();

        var from = consumer.originalPositionFor({ line: line, column: column });
        if (!from.source) return false;

        var result = {
            file: this.mapResolve(from.source),
            line: from.line,
            column: from.column
        };

        var source = consumer.sourceContentFor(from.source);
        if (source) result.source = source;

        return result;
    };

    Input.prototype.mapResolve = function mapResolve(file) {
        if (/^\w+:\/\//.test(file)) {
            return file;
        } else {
            return _path2.default.resolve(this.map.consumer().sourceRoot || '.', file);
        }
    };

    /**
     * The CSS source identifier. Contains {@link Input#file} if the user
     * set the `from` option, or {@link Input#id} if they did not.
     * @type {string}
     *
     * @example
     * const root = postcss.parse(css, { from: 'a.css' });
     * root.source.input.from //=> "/home/ai/a.css"
     *
     * const root = postcss.parse(css);
     * root.source.input.from //=> "<input css 1>"
     */


    _createClass(Input, [{
        key: 'from',
        get: function get() {
            return this.file || this.id;
        }
    }]);

    return Input;
}();

exports.default = Input;

/**
 * @typedef  {object} filePosition
 * @property {string} file   - path to file
 * @property {number} line   - source line in file
 * @property {number} column - source column in file
 */

module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64, 


/***/ }),

/***/ "pSRY":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_mapCacheHas.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getMapData = __webpack_require__(/*! ./_getMapData */ "QkVE");

/**
 * 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);
}

module.exports = mapCacheHas;


/***/ }),

/***/ "pX04":
/*!******************************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/components/fx/attributes.js ***!
  \******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var fontAttrs = __webpack_require__(/*! ../../plots/font_attributes */ "9HwK");

module.exports = {
    hoverlabel: {
        bgcolor: {
            valType: 'color',
            role: 'style',
            arrayOk: true,
            editType: 'none',
            description: [
                'Sets the background color of the hover labels for this trace'
            ].join(' ')
        },
        bordercolor: {
            valType: 'color',
            role: 'style',
            arrayOk: true,
            editType: 'none',
            description: [
                'Sets the border color of the hover labels for this trace.'
            ].join(' ')
        },
        font: fontAttrs({
            arrayOk: true,
            editType: 'none',
            description: 'Sets the font used in hover labels.'
        }),
        namelength: {
            valType: 'integer',
            min: -1,
            arrayOk: true,
            role: 'style',
            editType: 'none',
            description: [
                'Sets the length (in number of characters) of the trace name in',
                'the hover labels for this trace. -1 shows the whole name',
                'regardless of length. 0-3 shows the first 0-3 characters, and',
                'an integer >3 will show the whole name if it is less than that',
                'many characters, but if it is longer, will truncate to',
                '`namelength - 3` characters and add an ellipsis.'
            ].join(' ')
        },
        editType: 'calc'
    }
};


/***/ }),

/***/ "pboZ":
/*!********************************************!*\
  !*** ./node_modules/mdi-react/GridIcon.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var GridIcon = function GridIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M10,4V8H14V4H10M16,4V8H20V4H16M16,10V14H20V10H16M16,16V20H20V16H16M14,20V16H10V20H14M8,20V16H4V20H8M8,14V10H4V14H8M8,8V4H4V8H8M10,14H14V10H10V14M4,2H20C21.1,2 22,2.9 22,4V20C22,21.1 21.1,22 20,22H4C2.92,22 2,21.1 2,20V4C2,2.9 2.9,2 4,2Z' })
  );
};

module.exports = GridIcon;


/***/ }),

/***/ "pfxX":
/*!****************************************************************!*\
  !*** ./node_modules/@jupyterlab/extensionmanager/lib/index.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__webpack_require__(/*! ../style/index.css */ "aN65");
__export(__webpack_require__(/*! ./model */ "mT+/"));
__export(__webpack_require__(/*! ./query */ "NW3o"));
__export(__webpack_require__(/*! ./widget */ "OREO"));


/***/ }),

/***/ "pg4M":
/*!**************************************************!*\
  !*** ./node_modules/draft-js/lib/editOnFocus.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule editOnFocus
 * @format
 * 
 */



var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");
var UserAgent = __webpack_require__(/*! fbjs/lib/UserAgent */ "CYTE");

function editOnFocus(editor, e) {
  var editorState = editor._latestEditorState;
  var currentSelection = editorState.getSelection();
  if (currentSelection.getHasFocus()) {
    return;
  }

  var selection = currentSelection.set('hasFocus', true);
  editor.props.onFocus && editor.props.onFocus(e);

  // When the tab containing this text editor is hidden and the user does a
  // find-in-page in a _different_ tab, Chrome on Mac likes to forget what the
  // selection was right after sending this focus event and (if you let it)
  // moves the cursor back to the beginning of the editor, so we force the
  // selection here instead of simply accepting it in order to preserve the
  // old cursor position. See https://crbug.com/540004.
  // But it looks like this is fixed in Chrome 60.0.3081.0.
  // Other browsers also don't have this bug, so we prefer to acceptSelection
  // when possible, to ensure that unfocusing and refocusing a Draft editor
  // doesn't preserve the selection, matching how textareas work.
  if (UserAgent.isBrowser('Chrome < 60.0.3081.0')) {
    editor.update(EditorState.forceSelection(editorState, selection));
  } else {
    editor.update(EditorState.acceptSelection(editorState, selection));
  }
}

module.exports = editOnFocus;

/***/ }),

/***/ "piSt":
/*!**********************************************************!*\
  !*** ./node_modules/xterm/lib/input/MouseZoneManager.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var HOVER_DURATION = 500;
var MouseZoneManager = (function () {
    function MouseZoneManager(_terminal) {
        var _this = this;
        this._terminal = _terminal;
        this._zones = [];
        this._areZonesActive = false;
        this._tooltipTimeout = null;
        this._currentZone = null;
        this._lastHoverCoords = [null, null];
        this._terminal.element.addEventListener('mousedown', function (e) { return _this._onMouseDown(e); });
        this._mouseMoveListener = function (e) { return _this._onMouseMove(e); };
        this._clickListener = function (e) { return _this._onClick(e); };
    }
    MouseZoneManager.prototype.add = function (zone) {
        this._zones.push(zone);
        if (this._zones.length === 1) {
            this._activate();
        }
    };
    MouseZoneManager.prototype.clearAll = function (start, end) {
        if (this._zones.length === 0) {
            return;
        }
        if (!end) {
            start = 0;
            end = this._terminal.rows - 1;
        }
        for (var i = 0; i < this._zones.length; i++) {
            var zone = this._zones[i];
            if ((zone.y1 > start && zone.y1 <= end + 1) ||
                (zone.y2 > start && zone.y2 <= end + 1) ||
                (zone.y1 < start && zone.y2 > end + 1)) {
                if (this._currentZone && this._currentZone === zone) {
                    this._currentZone.leaveCallback();
                    this._currentZone = null;
                }
                this._zones.splice(i--, 1);
            }
        }
        if (this._zones.length === 0) {
            this._deactivate();
        }
    };
    MouseZoneManager.prototype._activate = function () {
        if (!this._areZonesActive) {
            this._areZonesActive = true;
            this._terminal.element.addEventListener('mousemove', this._mouseMoveListener);
            this._terminal.element.addEventListener('click', this._clickListener);
        }
    };
    MouseZoneManager.prototype._deactivate = function () {
        if (this._areZonesActive) {
            this._areZonesActive = false;
            this._terminal.element.removeEventListener('mousemove', this._mouseMoveListener);
            this._terminal.element.removeEventListener('click', this._clickListener);
        }
    };
    MouseZoneManager.prototype._onMouseMove = function (e) {
        if (this._lastHoverCoords[0] !== e.pageX || this._lastHoverCoords[1] !== e.pageY) {
            this._onHover(e);
            this._lastHoverCoords = [e.pageX, e.pageY];
        }
    };
    MouseZoneManager.prototype._onHover = function (e) {
        var _this = this;
        var zone = this._findZoneEventAt(e);
        if (zone === this._currentZone) {
            return;
        }
        if (this._currentZone) {
            this._currentZone.leaveCallback();
            this._currentZone = null;
            if (this._tooltipTimeout) {
                clearTimeout(this._tooltipTimeout);
            }
        }
        if (!zone) {
            return;
        }
        this._currentZone = zone;
        if (zone.hoverCallback) {
            zone.hoverCallback(e);
        }
        this._tooltipTimeout = setTimeout(function () { return _this._onTooltip(e); }, HOVER_DURATION);
    };
    MouseZoneManager.prototype._onTooltip = function (e) {
        this._tooltipTimeout = null;
        var zone = this._findZoneEventAt(e);
        if (zone && zone.tooltipCallback) {
            zone.tooltipCallback(e);
        }
    };
    MouseZoneManager.prototype._onMouseDown = function (e) {
        if (!this._areZonesActive) {
            return;
        }
        var zone = this._findZoneEventAt(e);
        if (zone) {
            if (zone.willLinkActivate(e)) {
                e.preventDefault();
                e.stopImmediatePropagation();
            }
        }
    };
    MouseZoneManager.prototype._onClick = function (e) {
        var zone = this._findZoneEventAt(e);
        if (zone) {
            zone.clickCallback(e);
            e.preventDefault();
            e.stopImmediatePropagation();
        }
    };
    MouseZoneManager.prototype._findZoneEventAt = function (e) {
        var coords = this._terminal.mouseHelper.getCoords(e, this._terminal.screenElement, this._terminal.charMeasure, this._terminal.options.lineHeight, this._terminal.cols, this._terminal.rows);
        if (!coords) {
            return null;
        }
        var x = coords[0];
        var y = coords[1];
        for (var i = 0; i < this._zones.length; i++) {
            var zone = this._zones[i];
            if (zone.y1 === zone.y2) {
                if (y === zone.y1 && x >= zone.x1 && x < zone.x2) {
                    return zone;
                }
            }
            else {
                if ((y === zone.y1 && x >= zone.x1) ||
                    (y === zone.y2 && x < zone.x2) ||
                    (y > zone.y1 && y < zone.y2)) {
                    return zone;
                }
            }
        }
        return null;
    };
    return MouseZoneManager;
}());
exports.MouseZoneManager = MouseZoneManager;
var MouseZone = (function () {
    function MouseZone(x1, y1, x2, y2, clickCallback, hoverCallback, tooltipCallback, leaveCallback, willLinkActivate) {
        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;
        this.clickCallback = clickCallback;
        this.hoverCallback = hoverCallback;
        this.tooltipCallback = tooltipCallback;
        this.leaveCallback = leaveCallback;
        this.willLinkActivate = willLinkActivate;
    }
    return MouseZone;
}());
exports.MouseZone = MouseZone;

//# sourceMappingURL=MouseZoneManager.js.map


/***/ }),

/***/ "pif5":
/*!*****************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/index.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
__export(__webpack_require__(/*! ./boxengine */ "ovjo"));
__export(__webpack_require__(/*! ./boxlayout */ "mvme"));
__export(__webpack_require__(/*! ./boxpanel */ "N7Mi"));
__export(__webpack_require__(/*! ./commandpalette */ "eIPM"));
__export(__webpack_require__(/*! ./contextmenu */ "JcQb"));
__export(__webpack_require__(/*! ./docklayout */ "Y29x"));
__export(__webpack_require__(/*! ./dockpanel */ "rvvU"));
__export(__webpack_require__(/*! ./focustracker */ "T3Nk"));
__export(__webpack_require__(/*! ./gridlayout */ "9Td0"));
__export(__webpack_require__(/*! ./layout */ "yNaG"));
__export(__webpack_require__(/*! ./menu */ "Jrp+"));
__export(__webpack_require__(/*! ./menubar */ "V9si"));
__export(__webpack_require__(/*! ./panel */ "RlJB"));
__export(__webpack_require__(/*! ./panellayout */ "HWBy"));
__export(__webpack_require__(/*! ./scrollbar */ "vwG1"));
__export(__webpack_require__(/*! ./singletonlayout */ "nUyg"));
__export(__webpack_require__(/*! ./splitlayout */ "Jv9w"));
__export(__webpack_require__(/*! ./splitpanel */ "45tw"));
__export(__webpack_require__(/*! ./stackedlayout */ "eRtU"));
__export(__webpack_require__(/*! ./stackedpanel */ "m3yW"));
__export(__webpack_require__(/*! ./tabbar */ "g07C"));
__export(__webpack_require__(/*! ./tabpanel */ "+Keh"));
__export(__webpack_require__(/*! ./title */ "0jI2"));
__export(__webpack_require__(/*! ./widget */ "FmDU"));


/***/ }),

/***/ "pkdz":
/*!********************************************!*\
  !*** ./node_modules/xterm/lib/Terminal.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var BufferSet_1 = __webpack_require__(/*! ./BufferSet */ "9qiJ");
var Buffer_1 = __webpack_require__(/*! ./Buffer */ "MsZC");
var CompositionHelper_1 = __webpack_require__(/*! ./CompositionHelper */ "oQJG");
var EventEmitter_1 = __webpack_require__(/*! ./EventEmitter */ "t2YR");
var Viewport_1 = __webpack_require__(/*! ./Viewport */ "+0l7");
var Clipboard_1 = __webpack_require__(/*! ./handlers/Clipboard */ "APuC");
var EscapeSequences_1 = __webpack_require__(/*! ./EscapeSequences */ "XYdm");
var InputHandler_1 = __webpack_require__(/*! ./InputHandler */ "4s8G");
var Parser_1 = __webpack_require__(/*! ./Parser */ "PhsB");
var Renderer_1 = __webpack_require__(/*! ./renderer/Renderer */ "PtnK");
var Linkifier_1 = __webpack_require__(/*! ./Linkifier */ "v+jr");
var SelectionManager_1 = __webpack_require__(/*! ./SelectionManager */ "iNX9");
var CharMeasure_1 = __webpack_require__(/*! ./utils/CharMeasure */ "H54+");
var Browser = __webpack_require__(/*! ./shared/utils/Browser */ "1XL3");
var Strings = __webpack_require__(/*! ./Strings */ "hqvf");
var MouseHelper_1 = __webpack_require__(/*! ./utils/MouseHelper */ "jrO0");
var Clone_1 = __webpack_require__(/*! ./utils/Clone */ "G+QD");
var SoundManager_1 = __webpack_require__(/*! ./SoundManager */ "VAzd");
var ColorManager_1 = __webpack_require__(/*! ./renderer/ColorManager */ "3ujF");
var MouseZoneManager_1 = __webpack_require__(/*! ./input/MouseZoneManager */ "piSt");
var AccessibilityManager_1 = __webpack_require__(/*! ./AccessibilityManager */ "Im2J");
var ScreenDprMonitor_1 = __webpack_require__(/*! ./utils/ScreenDprMonitor */ "/qo6");
var KEYCODE_KEY_MAPPINGS = {
    48: ['0', ')'],
    49: ['1', '!'],
    50: ['2', '@'],
    51: ['3', '#'],
    52: ['4', '$'],
    53: ['5', '%'],
    54: ['6', '^'],
    55: ['7', '&'],
    56: ['8', '*'],
    57: ['9', '('],
    186: [';', ':'],
    187: ['=', '+'],
    188: [',', '<'],
    189: ['-', '_'],
    190: ['.', '>'],
    191: ['/', '?'],
    192: ['`', '~'],
    219: ['[', '{'],
    220: ['\\', '|'],
    221: [']', '}'],
    222: ['\'', '"']
};
var document = (typeof window !== 'undefined') ? window.document : null;
var WRITE_BUFFER_PAUSE_THRESHOLD = 5;
var WRITE_BATCH_SIZE = 300;
var DEFAULT_OPTIONS = {
    cols: 80,
    rows: 24,
    convertEol: false,
    termName: 'xterm',
    cursorBlink: false,
    cursorStyle: 'block',
    bellSound: SoundManager_1.DEFAULT_BELL_SOUND,
    bellStyle: 'none',
    enableBold: true,
    fontFamily: 'courier-new, courier, monospace',
    fontSize: 15,
    fontWeight: 'normal',
    fontWeightBold: 'bold',
    lineHeight: 1.0,
    letterSpacing: 0,
    scrollback: 1000,
    screenKeys: false,
    screenReaderMode: false,
    debug: false,
    macOptionIsMeta: false,
    cancelEvents: false,
    disableStdin: false,
    useFlowControl: false,
    allowTransparency: false,
    tabStopWidth: 8,
    theme: null,
    rightClickSelectsWord: Browser.isMac
};
var Terminal = (function (_super) {
    __extends(Terminal, _super);
    function Terminal(options) {
        if (options === void 0) { options = {}; }
        var _this = _super.call(this) || this;
        _this.browser = Browser;
        _this.options = Clone_1.clone(options);
        _this._setup();
        return _this;
    }
    Terminal.prototype._setup = function () {
        var _this = this;
        Object.keys(DEFAULT_OPTIONS).forEach(function (key) {
            if (_this.options[key] == null) {
                _this.options[key] = DEFAULT_OPTIONS[key];
            }
            _this[key] = _this.options[key];
        });
        this._parent = document ? document.body : null;
        this.cols = this.options.cols;
        this.rows = this.options.rows;
        if (this.options.handler) {
            this.on('data', this.options.handler);
        }
        this.cursorState = 0;
        this.cursorHidden = false;
        this._sendDataQueue = '';
        this._customKeyEventHandler = null;
        this.applicationKeypad = false;
        this.applicationCursor = false;
        this.originMode = false;
        this.insertMode = false;
        this.wraparoundMode = true;
        this.bracketedPasteMode = false;
        this.charset = null;
        this.gcharset = null;
        this.glevel = 0;
        this.charsets = [null];
        this.defAttr = (0 << 18) | (257 << 9) | (256 << 0);
        this.curAttr = (0 << 18) | (257 << 9) | (256 << 0);
        this.params = [];
        this.currentParam = 0;
        this.prefix = '';
        this.postfix = '';
        this.writeBuffer = [];
        this._writeInProgress = false;
        this._xoffSentToCatchUp = false;
        this._userScrolling = false;
        this._inputHandler = new InputHandler_1.InputHandler(this);
        this._parser = new Parser_1.Parser(this._inputHandler, this);
        this.renderer = this.renderer || null;
        this.selectionManager = this.selectionManager || null;
        this.linkifier = this.linkifier || new Linkifier_1.Linkifier(this);
        this._mouseZoneManager = this._mouseZoneManager || null;
        this.soundManager = this.soundManager || new SoundManager_1.SoundManager(this);
        this.buffers = new BufferSet_1.BufferSet(this);
        if (this.selectionManager) {
            this.selectionManager.clearSelection();
            this.selectionManager.initBuffersListeners();
        }
    };
    Object.defineProperty(Terminal.prototype, "buffer", {
        get: function () {
            return this.buffers.active;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Terminal, "strings", {
        get: function () {
            return Strings;
        },
        enumerable: true,
        configurable: true
    });
    Terminal.prototype.eraseAttr = function () {
        return (this.defAttr & ~0x1ff) | (this.curAttr & 0x1ff);
    };
    Terminal.prototype.focus = function () {
        if (this.textarea) {
            this.textarea.focus();
        }
    };
    Object.defineProperty(Terminal.prototype, "isFocused", {
        get: function () {
            return document.activeElement === this.textarea;
        },
        enumerable: true,
        configurable: true
    });
    Terminal.prototype.getOption = function (key) {
        if (!(key in DEFAULT_OPTIONS)) {
            throw new Error('No option with key "' + key + '"');
        }
        if (typeof this.options[key] !== 'undefined') {
            return this.options[key];
        }
        return this[key];
    };
    Terminal.prototype.setOption = function (key, value) {
        if (!(key in DEFAULT_OPTIONS)) {
            throw new Error('No option with key "' + key + '"');
        }
        switch (key) {
            case 'bellStyle':
                if (!value) {
                    value = 'none';
                }
                break;
            case 'cursorStyle':
                if (!value) {
                    value = 'block';
                }
                break;
            case 'fontWeight':
                if (!value) {
                    value = 'normal';
                }
                break;
            case 'fontWeightBold':
                if (!value) {
                    value = 'bold';
                }
                break;
            case 'lineHeight':
                if (value < 1) {
                    console.warn(key + " cannot be less than 1, value: " + value);
                    return;
                }
            case 'tabStopWidth':
                if (value < 1) {
                    console.warn(key + " cannot be less than 1, value: " + value);
                    return;
                }
                break;
            case 'theme':
                if (this.renderer) {
                    this._setTheme(value);
                    return;
                }
                break;
            case 'scrollback':
                value = Math.min(value, Buffer_1.MAX_BUFFER_SIZE);
                if (value < 0) {
                    console.warn(key + " cannot be less than 0, value: " + value);
                    return;
                }
                if (this.options[key] !== value) {
                    var newBufferLength = this.rows + value;
                    if (this.buffer.lines.length > newBufferLength) {
                        var amountToTrim = this.buffer.lines.length - newBufferLength;
                        var needsRefresh = (this.buffer.ydisp - amountToTrim < 0);
                        this.buffer.lines.trimStart(amountToTrim);
                        this.buffer.ybase = Math.max(this.buffer.ybase - amountToTrim, 0);
                        this.buffer.ydisp = Math.max(this.buffer.ydisp - amountToTrim, 0);
                        if (needsRefresh) {
                            this.refresh(0, this.rows - 1);
                        }
                    }
                }
                break;
        }
        this[key] = value;
        this.options[key] = value;
        switch (key) {
            case 'fontFamily':
            case 'fontSize':
                this.renderer.clear();
                this.charMeasure.measure(this.options);
                break;
            case 'enableBold':
            case 'letterSpacing':
            case 'lineHeight':
            case 'fontWeight':
            case 'fontWeightBold':
                this.renderer.clear();
                this.renderer.onResize(this.cols, this.rows);
                this.refresh(0, this.rows - 1);
            case 'scrollback':
                this.buffers.resize(this.cols, this.rows);
                this.viewport.syncScrollArea();
                break;
            case 'screenReaderMode':
                if (value) {
                    if (!this._accessibilityManager) {
                        this._accessibilityManager = new AccessibilityManager_1.AccessibilityManager(this);
                    }
                }
                else {
                    if (this._accessibilityManager) {
                        this._accessibilityManager.dispose();
                        this._accessibilityManager = null;
                    }
                }
                break;
            case 'tabStopWidth':
                this.buffers.setupTabStops();
                break;
        }
        if (this.renderer) {
            this.renderer.onOptionsChanged();
        }
    };
    Terminal.prototype._onTextAreaFocus = function () {
        if (this.sendFocus) {
            this.send(EscapeSequences_1.C0.ESC + '[I');
        }
        this.element.classList.add('focus');
        this.showCursor();
        this.emit('focus');
    };
    Terminal.prototype.blur = function () {
        return this.textarea.blur();
    };
    Terminal.prototype._onTextAreaBlur = function () {
        this.textarea.value = '';
        this.refresh(this.buffer.y, this.buffer.y);
        if (this.sendFocus) {
            this.send(EscapeSequences_1.C0.ESC + '[O');
        }
        this.element.classList.remove('focus');
        this.emit('blur');
    };
    Terminal.prototype._initGlobal = function () {
        var _this = this;
        this._bindKeys();
        on(this.element, 'copy', function (event) {
            if (!_this.hasSelection()) {
                return;
            }
            Clipboard_1.copyHandler(event, _this, _this.selectionManager);
        });
        var pasteHandlerWrapper = function (event) { return Clipboard_1.pasteHandler(event, _this); };
        on(this.textarea, 'paste', pasteHandlerWrapper);
        on(this.element, 'paste', pasteHandlerWrapper);
        if (Browser.isFirefox) {
            on(this.element, 'mousedown', function (event) {
                if (event.button === 2) {
                    Clipboard_1.rightClickHandler(event, _this.textarea, _this.selectionManager, _this.options.rightClickSelectsWord);
                }
            });
        }
        else {
            on(this.element, 'contextmenu', function (event) {
                Clipboard_1.rightClickHandler(event, _this.textarea, _this.selectionManager, _this.options.rightClickSelectsWord);
            });
        }
        if (Browser.isLinux) {
            on(this.element, 'auxclick', function (event) {
                if (event.button === 1) {
                    Clipboard_1.moveTextAreaUnderMouseCursor(event, _this.textarea);
                }
            });
        }
    };
    Terminal.prototype._bindKeys = function () {
        var _this = this;
        var self = this;
        on(this.element, 'keydown', function (ev) {
            if (document.activeElement !== this) {
                return;
            }
            self._keyDown(ev);
        }, true);
        on(this.element, 'keypress', function (ev) {
            if (document.activeElement !== this) {
                return;
            }
            self._keyPress(ev);
        }, true);
        on(this.element, 'keyup', function (ev) {
            if (!wasMondifierKeyOnlyEvent(ev)) {
                _this.focus();
            }
        }, true);
        on(this.textarea, 'keydown', function (ev) { return _this._keyDown(ev); }, true);
        on(this.textarea, 'keypress', function (ev) { return _this._keyPress(ev); }, true);
        on(this.textarea, 'compositionstart', function () { return _this._compositionHelper.compositionstart(); });
        on(this.textarea, 'compositionupdate', function (e) { return _this._compositionHelper.compositionupdate(e); });
        on(this.textarea, 'compositionend', function () { return _this._compositionHelper.compositionend(); });
        this.on('refresh', function () { return _this._compositionHelper.updateCompositionElements(); });
        this.on('refresh', function (data) { return _this._queueLinkification(data.start, data.end); });
    };
    Terminal.prototype.open = function (parent) {
        var _this = this;
        this._parent = parent || this._parent;
        if (!this._parent) {
            throw new Error('Terminal requires a parent element.');
        }
        this._context = this._parent.ownerDocument.defaultView;
        this._document = this._parent.ownerDocument;
        this._screenDprMonitor = new ScreenDprMonitor_1.ScreenDprMonitor();
        this._screenDprMonitor.setListener(function () { return _this.emit('dprchange', window.devicePixelRatio); });
        this.element = this._document.createElement('div');
        this.element.dir = 'ltr';
        this.element.classList.add('terminal');
        this.element.classList.add('xterm');
        this.element.setAttribute('tabindex', '0');
        this._parent.appendChild(this.element);
        var fragment = document.createDocumentFragment();
        this._viewportElement = document.createElement('div');
        this._viewportElement.classList.add('xterm-viewport');
        fragment.appendChild(this._viewportElement);
        this._viewportScrollArea = document.createElement('div');
        this._viewportScrollArea.classList.add('xterm-scroll-area');
        this._viewportElement.appendChild(this._viewportScrollArea);
        this.screenElement = document.createElement('div');
        this.screenElement.classList.add('xterm-screen');
        this._helperContainer = document.createElement('div');
        this._helperContainer.classList.add('xterm-helpers');
        this.screenElement.appendChild(this._helperContainer);
        fragment.appendChild(this.screenElement);
        this._mouseZoneManager = new MouseZoneManager_1.MouseZoneManager(this);
        this.on('scroll', function () { return _this._mouseZoneManager.clearAll(); });
        this.linkifier.attachToDom(this._mouseZoneManager);
        this.textarea = document.createElement('textarea');
        this.textarea.classList.add('xterm-helper-textarea');
        this.textarea.setAttribute('aria-label', Strings.promptLabel);
        this.textarea.setAttribute('aria-multiline', 'false');
        this.textarea.setAttribute('autocorrect', 'off');
        this.textarea.setAttribute('autocapitalize', 'off');
        this.textarea.setAttribute('spellcheck', 'false');
        this.textarea.tabIndex = 0;
        this.textarea.addEventListener('focus', function () { return _this._onTextAreaFocus(); });
        this.textarea.addEventListener('blur', function () { return _this._onTextAreaBlur(); });
        this._helperContainer.appendChild(this.textarea);
        this._compositionView = document.createElement('div');
        this._compositionView.classList.add('composition-view');
        this._compositionHelper = new CompositionHelper_1.CompositionHelper(this.textarea, this._compositionView, this);
        this._helperContainer.appendChild(this._compositionView);
        this.charMeasure = new CharMeasure_1.CharMeasure(document, this._helperContainer);
        this.element.appendChild(fragment);
        this.renderer = new Renderer_1.Renderer(this, this.options.theme);
        this.options.theme = null;
        this.viewport = new Viewport_1.Viewport(this, this._viewportElement, this._viewportScrollArea, this.charMeasure);
        this.viewport.onThemeChanged(this.renderer.colorManager.colors);
        this.on('cursormove', function () { return _this.renderer.onCursorMove(); });
        this.on('resize', function () { return _this.renderer.onResize(_this.cols, _this.rows); });
        this.on('blur', function () { return _this.renderer.onBlur(); });
        this.on('focus', function () { return _this.renderer.onFocus(); });
        this.on('dprchange', function () { return _this.renderer.onWindowResize(window.devicePixelRatio); });
        window.addEventListener('resize', function () { return _this.renderer.onWindowResize(window.devicePixelRatio); });
        this.charMeasure.on('charsizechanged', function () { return _this.renderer.onResize(_this.cols, _this.rows); });
        this.renderer.on('resize', function (dimensions) { return _this.viewport.syncScrollArea(); });
        this.selectionManager = new SelectionManager_1.SelectionManager(this, this.charMeasure);
        this.element.addEventListener('mousedown', function (e) { return _this.selectionManager.onMouseDown(e); });
        this.selectionManager.on('refresh', function (data) { return _this.renderer.onSelectionChanged(data.start, data.end); });
        this.selectionManager.on('newselection', function (text) {
            _this.textarea.value = text;
            _this.textarea.focus();
            _this.textarea.select();
        });
        this.on('scroll', function () {
            _this.viewport.syncScrollArea();
            _this.selectionManager.refresh();
        });
        this._viewportElement.addEventListener('scroll', function () { return _this.selectionManager.refresh(); });
        this.mouseHelper = new MouseHelper_1.MouseHelper(this.renderer);
        if (this.options.screenReaderMode) {
            this._accessibilityManager = new AccessibilityManager_1.AccessibilityManager(this);
        }
        this.charMeasure.measure(this.options);
        this.refresh(0, this.rows - 1);
        this._initGlobal();
        this.bindMouse();
    };
    Terminal.prototype._setTheme = function (theme) {
        var colors = this.renderer.setTheme(theme);
        if (this.viewport) {
            this.viewport.onThemeChanged(colors);
        }
    };
    Terminal.applyAddon = function (addon) {
        addon.apply(Terminal);
    };
    Terminal.prototype.bindMouse = function () {
        var _this = this;
        var el = this.element;
        var self = this;
        var pressed = 32;
        function sendButton(ev) {
            var button;
            var pos;
            button = getButton(ev);
            pos = self.mouseHelper.getRawByteCoords(ev, self.screenElement, self.charMeasure, self.options.lineHeight, self.cols, self.rows);
            if (!pos)
                return;
            sendEvent(button, pos);
            switch (ev.overrideType || ev.type) {
                case 'mousedown':
                    pressed = button;
                    break;
                case 'mouseup':
                    pressed = 32;
                    break;
                case 'wheel':
                    break;
            }
        }
        function sendMove(ev) {
            var button = pressed;
            var pos = self.mouseHelper.getRawByteCoords(ev, self.screenElement, self.charMeasure, self.options.lineHeight, self.cols, self.rows);
            if (!pos)
                return;
            button += 32;
            sendEvent(button, pos);
        }
        function encode(data, ch) {
            if (!self.utfMouse) {
                if (ch === 255) {
                    data.push(0);
                    return;
                }
                if (ch > 127)
                    ch = 127;
                data.push(ch);
            }
            else {
                if (ch === 2047) {
                    data.push(0);
                    return;
                }
                if (ch < 127) {
                    data.push(ch);
                }
                else {
                    if (ch > 2047)
                        ch = 2047;
                    data.push(0xC0 | (ch >> 6));
                    data.push(0x80 | (ch & 0x3F));
                }
            }
        }
        function sendEvent(button, pos) {
            if (self._vt300Mouse) {
                button &= 3;
                pos.x -= 32;
                pos.y -= 32;
                var data_1 = EscapeSequences_1.C0.ESC + '[24';
                if (button === 0)
                    data_1 += '1';
                else if (button === 1)
                    data_1 += '3';
                else if (button === 2)
                    data_1 += '5';
                else if (button === 3)
                    return;
                else
                    data_1 += '0';
                data_1 += '~[' + pos.x + ',' + pos.y + ']\r';
                self.send(data_1);
                return;
            }
            if (self._decLocator) {
                button &= 3;
                pos.x -= 32;
                pos.y -= 32;
                if (button === 0)
                    button = 2;
                else if (button === 1)
                    button = 4;
                else if (button === 2)
                    button = 6;
                else if (button === 3)
                    button = 3;
                self.send(EscapeSequences_1.C0.ESC + '['
                    + button
                    + ';'
                    + (button === 3 ? 4 : 0)
                    + ';'
                    + pos.y
                    + ';'
                    + pos.x
                    + ';'
                    + pos.page || 0
                    + '&w');
                return;
            }
            if (self.urxvtMouse) {
                pos.x -= 32;
                pos.y -= 32;
                pos.x++;
                pos.y++;
                self.send(EscapeSequences_1.C0.ESC + '[' + button + ';' + pos.x + ';' + pos.y + 'M');
                return;
            }
            if (self.sgrMouse) {
                pos.x -= 32;
                pos.y -= 32;
                self.send(EscapeSequences_1.C0.ESC + '[<'
                    + (((button & 3) === 3 ? button & ~3 : button) - 32)
                    + ';'
                    + pos.x
                    + ';'
                    + pos.y
                    + ((button & 3) === 3 ? 'm' : 'M'));
                return;
            }
            var data = [];
            encode(data, button);
            encode(data, pos.x);
            encode(data, pos.y);
            self.send(EscapeSequences_1.C0.ESC + '[M' + String.fromCharCode.apply(String, data));
        }
        function getButton(ev) {
            var button;
            var shift;
            var meta;
            var ctrl;
            var mod;
            switch (ev.overrideType || ev.type) {
                case 'mousedown':
                    button = ev.button != null
                        ? +ev.button
                        : ev.which != null
                            ? ev.which - 1
                            : null;
                    if (Browser.isMSIE) {
                        button = button === 1 ? 0 : button === 4 ? 1 : button;
                    }
                    break;
                case 'mouseup':
                    button = 3;
                    break;
                case 'DOMMouseScroll':
                    button = ev.detail < 0
                        ? 64
                        : 65;
                    break;
                case 'wheel':
                    button = ev.wheelDeltaY > 0
                        ? 64
                        : 65;
                    break;
            }
            shift = ev.shiftKey ? 4 : 0;
            meta = ev.metaKey ? 8 : 0;
            ctrl = ev.ctrlKey ? 16 : 0;
            mod = shift | meta | ctrl;
            if (self.vt200Mouse) {
                mod &= ctrl;
            }
            else if (!self.normalMouse) {
                mod = 0;
            }
            button = (32 + (mod << 2)) + button;
            return button;
        }
        on(el, 'mousedown', function (ev) {
            ev.preventDefault();
            _this.focus();
            if (!_this.mouseEvents || _this.selectionManager.shouldForceSelection(ev)) {
                return;
            }
            sendButton(ev);
            if (_this.vt200Mouse) {
                ev.overrideType = 'mouseup';
                sendButton(ev);
                return _this.cancel(ev);
            }
            if (_this.normalMouse)
                on(_this._document, 'mousemove', sendMove);
            if (!_this.x10Mouse) {
                var handler_1 = function (ev) {
                    sendButton(ev);
                    if (_this.normalMouse)
                        off(_this._document, 'mousemove', sendMove);
                    off(_this._document, 'mouseup', handler_1);
                    return _this.cancel(ev);
                };
                on(_this._document, 'mouseup', handler_1);
            }
            return _this.cancel(ev);
        });
        on(el, 'wheel', function (ev) {
            if (!_this.mouseEvents) {
                if (!_this.buffer.hasScrollback) {
                    var amount = _this.viewport.getLinesScrolled(ev);
                    if (amount === 0) {
                        return;
                    }
                    var sequence = EscapeSequences_1.C0.ESC + (_this.applicationCursor ? 'O' : '[') + (ev.deltaY < 0 ? 'A' : 'B');
                    var data = '';
                    for (var i = 0; i < Math.abs(amount); i++) {
                        data += sequence;
                    }
                    _this.send(data);
                }
                return;
            }
            if (_this.x10Mouse || _this._vt300Mouse || _this._decLocator)
                return;
            sendButton(ev);
            ev.preventDefault();
        });
        on(el, 'wheel', function (ev) {
            if (_this.mouseEvents)
                return;
            _this.viewport.onWheel(ev);
            return _this.cancel(ev);
        });
        on(el, 'touchstart', function (ev) {
            if (_this.mouseEvents)
                return;
            _this.viewport.onTouchStart(ev);
            return _this.cancel(ev);
        });
        on(el, 'touchmove', function (ev) {
            if (_this.mouseEvents)
                return;
            _this.viewport.onTouchMove(ev);
            return _this.cancel(ev);
        });
    };
    Terminal.prototype.destroy = function () {
        _super.prototype.destroy.call(this);
        this.handler = function () { };
        this.write = function () { };
        if (this.element && this.element.parentNode) {
            this.element.parentNode.removeChild(this.element);
        }
    };
    Terminal.prototype.refresh = function (start, end) {
        if (this.renderer) {
            this.renderer.refreshRows(start, end);
        }
    };
    Terminal.prototype._queueLinkification = function (start, end) {
        if (this.linkifier) {
            this.linkifier.linkifyRows(start, end);
        }
    };
    Terminal.prototype.showCursor = function () {
        if (!this.cursorState) {
            this.cursorState = 1;
            this.refresh(this.buffer.y, this.buffer.y);
        }
    };
    Terminal.prototype.scroll = function (isWrapped) {
        var newLine = this.blankLine(undefined, isWrapped);
        var topRow = this.buffer.ybase + this.buffer.scrollTop;
        var bottomRow = this.buffer.ybase + this.buffer.scrollBottom;
        if (this.buffer.scrollTop === 0) {
            var willBufferBeTrimmed = this.buffer.lines.length === this.buffer.lines.maxLength;
            if (bottomRow === this.buffer.lines.length - 1) {
                this.buffer.lines.push(newLine);
            }
            else {
                this.buffer.lines.splice(bottomRow + 1, 0, newLine);
            }
            if (!willBufferBeTrimmed) {
                this.buffer.ybase++;
                if (!this._userScrolling) {
                    this.buffer.ydisp++;
                }
            }
            else {
                if (this._userScrolling) {
                    this.buffer.ydisp = Math.max(this.buffer.ydisp - 1, 0);
                }
            }
        }
        else {
            var scrollRegionHeight = bottomRow - topRow + 1;
            this.buffer.lines.shiftElements(topRow + 1, scrollRegionHeight - 1, -1);
            this.buffer.lines.set(bottomRow, newLine);
        }
        if (!this._userScrolling) {
            this.buffer.ydisp = this.buffer.ybase;
        }
        this.updateRange(this.buffer.scrollTop);
        this.updateRange(this.buffer.scrollBottom);
        this.emit('scroll', this.buffer.ydisp);
    };
    Terminal.prototype.scrollLines = function (disp, suppressScrollEvent) {
        if (disp < 0) {
            if (this.buffer.ydisp === 0) {
                return;
            }
            this._userScrolling = true;
        }
        else if (disp + this.buffer.ydisp >= this.buffer.ybase) {
            this._userScrolling = false;
        }
        var oldYdisp = this.buffer.ydisp;
        this.buffer.ydisp = Math.max(Math.min(this.buffer.ydisp + disp, this.buffer.ybase), 0);
        if (oldYdisp === this.buffer.ydisp) {
            return;
        }
        if (!suppressScrollEvent) {
            this.emit('scroll', this.buffer.ydisp);
        }
        this.refresh(0, this.rows - 1);
    };
    Terminal.prototype.scrollPages = function (pageCount) {
        this.scrollLines(pageCount * (this.rows - 1));
    };
    Terminal.prototype.scrollToTop = function () {
        this.scrollLines(-this.buffer.ydisp);
    };
    Terminal.prototype.scrollToBottom = function () {
        this.scrollLines(this.buffer.ybase - this.buffer.ydisp);
    };
    Terminal.prototype.scrollToLine = function (line) {
        var scrollAmount = line - this.buffer.ydisp;
        if (scrollAmount !== 0) {
            this.scrollLines(scrollAmount);
        }
    };
    Terminal.prototype.write = function (data) {
        var _this = this;
        if (!data) {
            return;
        }
        this.writeBuffer.push(data);
        if (this.options.useFlowControl && !this._xoffSentToCatchUp && this.writeBuffer.length >= WRITE_BUFFER_PAUSE_THRESHOLD) {
            this.send(EscapeSequences_1.C0.DC3);
            this._xoffSentToCatchUp = true;
        }
        if (!this._writeInProgress && this.writeBuffer.length > 0) {
            this._writeInProgress = true;
            setTimeout(function () {
                _this._innerWrite();
            });
        }
    };
    Terminal.prototype._innerWrite = function () {
        var _this = this;
        var writeBatch = this.writeBuffer.splice(0, WRITE_BATCH_SIZE);
        while (writeBatch.length > 0) {
            var data = writeBatch.shift();
            if (this._xoffSentToCatchUp && writeBatch.length === 0 && this.writeBuffer.length === 0) {
                this.send(EscapeSequences_1.C0.DC1);
                this._xoffSentToCatchUp = false;
            }
            this._refreshStart = this.buffer.y;
            this._refreshEnd = this.buffer.y;
            var state = this._parser.parse(data);
            this._parser.setState(state);
            this.updateRange(this.buffer.y);
            this.refresh(this._refreshStart, this._refreshEnd);
        }
        if (this.writeBuffer.length > 0) {
            setTimeout(function () { return _this._innerWrite(); }, 0);
        }
        else {
            this._writeInProgress = false;
        }
    };
    Terminal.prototype.writeln = function (data) {
        this.write(data + '\r\n');
    };
    Terminal.prototype.attachCustomKeyEventHandler = function (customKeyEventHandler) {
        this._customKeyEventHandler = customKeyEventHandler;
    };
    Terminal.prototype.registerLinkMatcher = function (regex, handler, options) {
        var matcherId = this.linkifier.registerLinkMatcher(regex, handler, options);
        this.refresh(0, this.rows - 1);
        return matcherId;
    };
    Terminal.prototype.deregisterLinkMatcher = function (matcherId) {
        if (this.linkifier.deregisterLinkMatcher(matcherId)) {
            this.refresh(0, this.rows - 1);
        }
    };
    Object.defineProperty(Terminal.prototype, "markers", {
        get: function () {
            return this.buffer.markers;
        },
        enumerable: true,
        configurable: true
    });
    Terminal.prototype.addMarker = function (cursorYOffset) {
        if (this.buffer !== this.buffers.normal) {
            return;
        }
        return this.buffer.addMarker(this.buffer.ybase + this.buffer.y + cursorYOffset);
    };
    Terminal.prototype.hasSelection = function () {
        return this.selectionManager ? this.selectionManager.hasSelection : false;
    };
    Terminal.prototype.getSelection = function () {
        return this.selectionManager ? this.selectionManager.selectionText : '';
    };
    Terminal.prototype.clearSelection = function () {
        if (this.selectionManager) {
            this.selectionManager.clearSelection();
        }
    };
    Terminal.prototype.selectAll = function () {
        if (this.selectionManager) {
            this.selectionManager.selectAll();
        }
    };
    Terminal.prototype.selectLines = function (start, end) {
        if (this.selectionManager) {
            this.selectionManager.selectLines(start, end);
        }
    };
    Terminal.prototype._keyDown = function (ev) {
        if (this._customKeyEventHandler && this._customKeyEventHandler(ev) === false) {
            return false;
        }
        if (!this._compositionHelper.keydown(ev)) {
            if (this.buffer.ybase !== this.buffer.ydisp) {
                this.scrollToBottom();
            }
            return false;
        }
        var result = this._evaluateKeyEscapeSequence(ev);
        if (result.scrollLines) {
            this.scrollLines(result.scrollLines);
            return this.cancel(ev, true);
        }
        if (this._isThirdLevelShift(this.browser, ev)) {
            return true;
        }
        if (result.cancel) {
            this.cancel(ev, true);
        }
        if (!result.key) {
            return true;
        }
        this.emit('keydown', ev);
        this.emit('key', result.key, ev);
        this.showCursor();
        this.handler(result.key);
        return this.cancel(ev, true);
    };
    Terminal.prototype._isThirdLevelShift = function (browser, ev) {
        var thirdLevelKey = (browser.isMac && !this.options.macOptionIsMeta && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||
            (browser.isMSWindows && ev.altKey && ev.ctrlKey && !ev.metaKey);
        if (ev.type === 'keypress') {
            return thirdLevelKey;
        }
        return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47);
    };
    Terminal.prototype._evaluateKeyEscapeSequence = function (ev) {
        var result = {
            cancel: false,
            key: undefined,
            scrollLines: undefined
        };
        var modifiers = (ev.shiftKey ? 1 : 0) | (ev.altKey ? 2 : 0) | (ev.ctrlKey ? 4 : 0) | (ev.metaKey ? 8 : 0);
        switch (ev.keyCode) {
            case 0:
                if (ev.key === 'UIKeyInputUpArrow') {
                    if (this.applicationCursor) {
                        result.key = EscapeSequences_1.C0.ESC + 'OA';
                    }
                    else {
                        result.key = EscapeSequences_1.C0.ESC + '[A';
                    }
                }
                else if (ev.key === 'UIKeyInputLeftArrow') {
                    if (this.applicationCursor) {
                        result.key = EscapeSequences_1.C0.ESC + 'OD';
                    }
                    else {
                        result.key = EscapeSequences_1.C0.ESC + '[D';
                    }
                }
                else if (ev.key === 'UIKeyInputRightArrow') {
                    if (this.applicationCursor) {
                        result.key = EscapeSequences_1.C0.ESC + 'OC';
                    }
                    else {
                        result.key = EscapeSequences_1.C0.ESC + '[C';
                    }
                }
                else if (ev.key === 'UIKeyInputDownArrow') {
                    if (this.applicationCursor) {
                        result.key = EscapeSequences_1.C0.ESC + 'OB';
                    }
                    else {
                        result.key = EscapeSequences_1.C0.ESC + '[B';
                    }
                }
                break;
            case 8:
                if (ev.shiftKey) {
                    result.key = EscapeSequences_1.C0.BS;
                    break;
                }
                else if (ev.altKey) {
                    result.key = EscapeSequences_1.C0.ESC + EscapeSequences_1.C0.DEL;
                    break;
                }
                result.key = EscapeSequences_1.C0.DEL;
                break;
            case 9:
                if (ev.shiftKey) {
                    result.key = EscapeSequences_1.C0.ESC + '[Z';
                    break;
                }
                result.key = EscapeSequences_1.C0.HT;
                result.cancel = true;
                break;
            case 13:
                result.key = EscapeSequences_1.C0.CR;
                result.cancel = true;
                break;
            case 27:
                result.key = EscapeSequences_1.C0.ESC;
                result.cancel = true;
                break;
            case 37:
                if (modifiers) {
                    result.key = EscapeSequences_1.C0.ESC + '[1;' + (modifiers + 1) + 'D';
                    if (result.key === EscapeSequences_1.C0.ESC + '[1;3D') {
                        result.key = (this.browser.isMac) ? EscapeSequences_1.C0.ESC + 'b' : EscapeSequences_1.C0.ESC + '[1;5D';
                    }
                }
                else if (this.applicationCursor) {
                    result.key = EscapeSequences_1.C0.ESC + 'OD';
                }
                else {
                    result.key = EscapeSequences_1.C0.ESC + '[D';
                }
                break;
            case 39:
                if (modifiers) {
                    result.key = EscapeSequences_1.C0.ESC + '[1;' + (modifiers + 1) + 'C';
                    if (result.key === EscapeSequences_1.C0.ESC + '[1;3C') {
                        result.key = (this.browser.isMac) ? EscapeSequences_1.C0.ESC + 'f' : EscapeSequences_1.C0.ESC + '[1;5C';
                    }
                }
                else if (this.applicationCursor) {
                    result.key = EscapeSequences_1.C0.ESC + 'OC';
                }
                else {
                    result.key = EscapeSequences_1.C0.ESC + '[C';
                }
                break;
            case 38:
                if (modifiers) {
                    result.key = EscapeSequences_1.C0.ESC + '[1;' + (modifiers + 1) + 'A';
                    if (result.key === EscapeSequences_1.C0.ESC + '[1;3A') {
                        result.key = EscapeSequences_1.C0.ESC + '[1;5A';
                    }
                }
                else if (this.applicationCursor) {
                    result.key = EscapeSequences_1.C0.ESC + 'OA';
                }
                else {
                    result.key = EscapeSequences_1.C0.ESC + '[A';
                }
                break;
            case 40:
                if (modifiers) {
                    result.key = EscapeSequences_1.C0.ESC + '[1;' + (modifiers + 1) + 'B';
                    if (result.key === EscapeSequences_1.C0.ESC + '[1;3B') {
                        result.key = EscapeSequences_1.C0.ESC + '[1;5B';
                    }
                }
                else if (this.applicationCursor) {
                    result.key = EscapeSequences_1.C0.ESC + 'OB';
                }
                else {
                    result.key = EscapeSequences_1.C0.ESC + '[B';
                }
                break;
            case 45:
                if (!ev.shiftKey && !ev.ctrlKey) {
                    result.key = EscapeSequences_1.C0.ESC + '[2~';
                }
                break;
            case 46:
                if (modifiers) {
                    result.key = EscapeSequences_1.C0.ESC + '[3;' + (modifiers + 1) + '~';
                }
                else {
                    result.key = EscapeSequences_1.C0.ESC + '[3~';
                }
                break;
            case 36:
                if (modifiers) {
                    result.key = EscapeSequences_1.C0.ESC + '[1;' + (modifiers + 1) + 'H';
                }
                else if (this.applicationCursor) {
                    result.key = EscapeSequences_1.C0.ESC + 'OH';
                }
                else {
                    result.key = EscapeSequences_1.C0.ESC + '[H';
                }
                break;
            case 35:
                if (modifiers) {
                    result.key = EscapeSequences_1.C0.ESC + '[1;' + (modifiers + 1) + 'F';
                }
                else if (this.applicationCursor) {
                    result.key = EscapeSequences_1.C0.ESC + 'OF';
                }
                else {
                    result.key = EscapeSequences_1.C0.ESC + '[F';
                }
                break;
            case 33:
                if (ev.shiftKey) {
                    result.scrollLines = -(this.rows - 1);
                }
                else {
                    result.key = EscapeSequences_1.C0.ESC + '[5~';
                }
                break;
            case 34:
                if (ev.shiftKey) {
                    result.scrollLines = this.rows - 1;
                }
                else {
                    result.key = EscapeSequences_1.C0.ESC + '[6~';
                }
                break;
            case 112:
                if (modifiers) {
                    result.key = EscapeSequences_1.C0.ESC + '[1;' + (modifiers + 1) + 'P';
                }
                else {
                    result.key = EscapeSequences_1.C0.ESC + 'OP';
                }
                break;
            case 113:
                if (modifiers) {
                    result.key = EscapeSequences_1.C0.ESC + '[1;' + (modifiers + 1) + 'Q';
                }
                else {
                    result.key = EscapeSequences_1.C0.ESC + 'OQ';
                }
                break;
            case 114:
                if (modifiers) {
                    result.key = EscapeSequences_1.C0.ESC + '[1;' + (modifiers + 1) + 'R';
                }
                else {
                    result.key = EscapeSequences_1.C0.ESC + 'OR';
                }
                break;
            case 115:
                if (modifiers) {
                    result.key = EscapeSequences_1.C0.ESC + '[1;' + (modifiers + 1) + 'S';
                }
                else {
                    result.key = EscapeSequences_1.C0.ESC + 'OS';
                }
                break;
            case 116:
                if (modifiers) {
                    result.key = EscapeSequences_1.C0.ESC + '[15;' + (modifiers + 1) + '~';
                }
                else {
                    result.key = EscapeSequences_1.C0.ESC + '[15~';
                }
                break;
            case 117:
                if (modifiers) {
                    result.key = EscapeSequences_1.C0.ESC + '[17;' + (modifiers + 1) + '~';
                }
                else {
                    result.key = EscapeSequences_1.C0.ESC + '[17~';
                }
                break;
            case 118:
                if (modifiers) {
                    result.key = EscapeSequences_1.C0.ESC + '[18;' + (modifiers + 1) + '~';
                }
                else {
                    result.key = EscapeSequences_1.C0.ESC + '[18~';
                }
                break;
            case 119:
                if (modifiers) {
                    result.key = EscapeSequences_1.C0.ESC + '[19;' + (modifiers + 1) + '~';
                }
                else {
                    result.key = EscapeSequences_1.C0.ESC + '[19~';
                }
                break;
            case 120:
                if (modifiers) {
                    result.key = EscapeSequences_1.C0.ESC + '[20;' + (modifiers + 1) + '~';
                }
                else {
                    result.key = EscapeSequences_1.C0.ESC + '[20~';
                }
                break;
            case 121:
                if (modifiers) {
                    result.key = EscapeSequences_1.C0.ESC + '[21;' + (modifiers + 1) + '~';
                }
                else {
                    result.key = EscapeSequences_1.C0.ESC + '[21~';
                }
                break;
            case 122:
                if (modifiers) {
                    result.key = EscapeSequences_1.C0.ESC + '[23;' + (modifiers + 1) + '~';
                }
                else {
                    result.key = EscapeSequences_1.C0.ESC + '[23~';
                }
                break;
            case 123:
                if (modifiers) {
                    result.key = EscapeSequences_1.C0.ESC + '[24;' + (modifiers + 1) + '~';
                }
                else {
                    result.key = EscapeSequences_1.C0.ESC + '[24~';
                }
                break;
            default:
                if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) {
                    if (ev.keyCode >= 65 && ev.keyCode <= 90) {
                        result.key = String.fromCharCode(ev.keyCode - 64);
                    }
                    else if (ev.keyCode === 32) {
                        result.key = String.fromCharCode(0);
                    }
                    else if (ev.keyCode >= 51 && ev.keyCode <= 55) {
                        result.key = String.fromCharCode(ev.keyCode - 51 + 27);
                    }
                    else if (ev.keyCode === 56) {
                        result.key = String.fromCharCode(127);
                    }
                    else if (ev.keyCode === 219) {
                        result.key = String.fromCharCode(27);
                    }
                    else if (ev.keyCode === 220) {
                        result.key = String.fromCharCode(28);
                    }
                    else if (ev.keyCode === 221) {
                        result.key = String.fromCharCode(29);
                    }
                }
                else if ((!this.browser.isMac || this.options.macOptionIsMeta) && ev.altKey && !ev.metaKey) {
                    var keyMapping = KEYCODE_KEY_MAPPINGS[ev.keyCode];
                    var key = keyMapping && keyMapping[!ev.shiftKey ? 0 : 1];
                    if (key) {
                        result.key = EscapeSequences_1.C0.ESC + key;
                    }
                    else if (ev.keyCode >= 65 && ev.keyCode <= 90) {
                        var keyCode = ev.ctrlKey ? ev.keyCode - 64 : ev.keyCode + 32;
                        result.key = EscapeSequences_1.C0.ESC + String.fromCharCode(keyCode);
                    }
                }
                else if (this.browser.isMac && !ev.altKey && !ev.ctrlKey && ev.metaKey) {
                    if (ev.keyCode === 65) {
                        this.selectAll();
                    }
                }
                break;
        }
        return result;
    };
    Terminal.prototype.setgLevel = function (g) {
        this.glevel = g;
        this.charset = this.charsets[g];
    };
    Terminal.prototype.setgCharset = function (g, charset) {
        this.charsets[g] = charset;
        if (this.glevel === g) {
            this.charset = charset;
        }
    };
    Terminal.prototype._keyPress = function (ev) {
        var key;
        if (this._customKeyEventHandler && this._customKeyEventHandler(ev) === false) {
            return false;
        }
        this.cancel(ev);
        if (ev.charCode) {
            key = ev.charCode;
        }
        else if (ev.which == null) {
            key = ev.keyCode;
        }
        else if (ev.which !== 0 && ev.charCode !== 0) {
            key = ev.which;
        }
        else {
            return false;
        }
        if (!key || ((ev.altKey || ev.ctrlKey || ev.metaKey) && !this._isThirdLevelShift(this.browser, ev))) {
            return false;
        }
        key = String.fromCharCode(key);
        this.emit('keypress', key, ev);
        this.emit('key', key, ev);
        this.showCursor();
        this.handler(key);
        return true;
    };
    Terminal.prototype.send = function (data) {
        var _this = this;
        if (!this._sendDataQueue) {
            setTimeout(function () {
                _this.handler(_this._sendDataQueue);
                _this._sendDataQueue = '';
            }, 1);
        }
        this._sendDataQueue += data;
    };
    Terminal.prototype.bell = function () {
        var _this = this;
        this.emit('bell');
        if (this._soundBell()) {
            this.soundManager.playBellSound();
        }
        if (this._visualBell()) {
            this.element.classList.add('visual-bell-active');
            clearTimeout(this._visualBellTimer);
            this._visualBellTimer = window.setTimeout(function () {
                _this.element.classList.remove('visual-bell-active');
            }, 200);
        }
    };
    Terminal.prototype.log = function (text, data) {
        if (!this.options.debug)
            return;
        if (!this._context.console || !this._context.console.log)
            return;
        this._context.console.log(text, data);
    };
    Terminal.prototype.error = function (text, data) {
        if (!this.options.debug)
            return;
        if (!this._context.console || !this._context.console.error)
            return;
        this._context.console.error(text, data);
    };
    Terminal.prototype.resize = function (x, y) {
        if (isNaN(x) || isNaN(y)) {
            return;
        }
        if (x === this.cols && y === this.rows) {
            if (!this.charMeasure.width || !this.charMeasure.height) {
                this.charMeasure.measure(this.options);
            }
            return;
        }
        if (x < 1)
            x = 1;
        if (y < 1)
            y = 1;
        this.buffers.resize(x, y);
        this.cols = x;
        this.rows = y;
        this.buffers.setupTabStops(this.cols);
        if (this.charMeasure) {
            this.charMeasure.measure(this.options);
        }
        this.refresh(0, this.rows - 1);
        this.emit('resize', { cols: x, rows: y });
    };
    Terminal.prototype.updateRange = function (y) {
        if (y < this._refreshStart)
            this._refreshStart = y;
        if (y > this._refreshEnd)
            this._refreshEnd = y;
    };
    Terminal.prototype.maxRange = function () {
        this._refreshStart = 0;
        this._refreshEnd = this.rows - 1;
    };
    Terminal.prototype.eraseRight = function (x, y) {
        var line = this.buffer.lines.get(this.buffer.ybase + y);
        if (!line) {
            return;
        }
        var ch = [this.eraseAttr(), ' ', 1, 32];
        for (; x < this.cols; x++) {
            line[x] = ch;
        }
        this.updateRange(y);
    };
    Terminal.prototype.eraseLeft = function (x, y) {
        var line = this.buffer.lines.get(this.buffer.ybase + y);
        if (!line) {
            return;
        }
        var ch = [this.eraseAttr(), ' ', 1, 32];
        x++;
        while (x--) {
            line[x] = ch;
        }
        this.updateRange(y);
    };
    Terminal.prototype.clear = function () {
        if (this.buffer.ybase === 0 && this.buffer.y === 0) {
            return;
        }
        this.buffer.lines.set(0, this.buffer.lines.get(this.buffer.ybase + this.buffer.y));
        this.buffer.lines.length = 1;
        this.buffer.ydisp = 0;
        this.buffer.ybase = 0;
        this.buffer.y = 0;
        for (var i = 1; i < this.rows; i++) {
            this.buffer.lines.push(this.blankLine());
        }
        this.refresh(0, this.rows - 1);
        this.emit('scroll', this.buffer.ydisp);
    };
    Terminal.prototype.eraseLine = function (y) {
        this.eraseRight(0, y);
    };
    Terminal.prototype.blankLine = function (cur, isWrapped, cols) {
        var attr = cur ? this.eraseAttr() : this.defAttr;
        var ch = [attr, ' ', 1, 32];
        var line = [];
        if (isWrapped) {
            line.isWrapped = isWrapped;
        }
        cols = cols || this.cols;
        for (var i = 0; i < cols; i++) {
            line[i] = ch;
        }
        return line;
    };
    Terminal.prototype.ch = function (cur) {
        if (cur) {
            return [this.eraseAttr(), ' ', 1, 32];
        }
        return [this.defAttr, ' ', 1, 32];
    };
    Terminal.prototype.is = function (term) {
        return (this.options.termName + '').indexOf(term) === 0;
    };
    Terminal.prototype.handler = function (data) {
        if (this.options.disableStdin) {
            return;
        }
        if (this.selectionManager && this.selectionManager.hasSelection) {
            this.selectionManager.clearSelection();
        }
        if (this.buffer.ybase !== this.buffer.ydisp) {
            this.scrollToBottom();
        }
        this.emit('data', data);
    };
    Terminal.prototype.handleTitle = function (title) {
        this.emit('title', title);
    };
    Terminal.prototype.index = function () {
        this.buffer.y++;
        if (this.buffer.y > this.buffer.scrollBottom) {
            this.buffer.y--;
            this.scroll();
        }
        if (this.buffer.x >= this.cols) {
            this.buffer.x--;
        }
    };
    Terminal.prototype.reverseIndex = function () {
        if (this.buffer.y === this.buffer.scrollTop) {
            var scrollRegionHeight = this.buffer.scrollBottom - this.buffer.scrollTop;
            this.buffer.lines.shiftElements(this.buffer.y + this.buffer.ybase, scrollRegionHeight, 1);
            this.buffer.lines.set(this.buffer.y + this.buffer.ybase, this.blankLine(true));
            this.updateRange(this.buffer.scrollTop);
            this.updateRange(this.buffer.scrollBottom);
        }
        else {
            this.buffer.y--;
        }
    };
    Terminal.prototype.reset = function () {
        this.options.rows = this.rows;
        this.options.cols = this.cols;
        var customKeyEventHandler = this._customKeyEventHandler;
        var inputHandler = this._inputHandler;
        this._setup();
        this._customKeyEventHandler = customKeyEventHandler;
        this._inputHandler = inputHandler;
        this.refresh(0, this.rows - 1);
        if (this.viewport) {
            this.viewport.syncScrollArea();
        }
    };
    Terminal.prototype.tabSet = function () {
        this.buffer.tabs[this.buffer.x] = true;
    };
    Terminal.prototype.cancel = function (ev, force) {
        if (!this.options.cancelEvents && !force) {
            return;
        }
        ev.preventDefault();
        ev.stopPropagation();
        return false;
    };
    Terminal.prototype.matchColor = function (r1, g1, b1) {
        return matchColor_(r1, g1, b1);
    };
    Terminal.prototype._visualBell = function () {
        return false;
    };
    Terminal.prototype._soundBell = function () {
        return this.options.bellStyle === 'sound';
    };
    return Terminal;
}(EventEmitter_1.EventEmitter));
exports.Terminal = Terminal;
function globalOn(el, type, handler, capture) {
    if (!Array.isArray(el)) {
        el = [el];
    }
    el.forEach(function (element) {
        element.addEventListener(type, handler, capture || false);
    });
}
var on = globalOn;
function off(el, type, handler, capture) {
    if (capture === void 0) { capture = false; }
    el.removeEventListener(type, handler, capture);
}
function wasMondifierKeyOnlyEvent(ev) {
    return ev.keyCode === 16 ||
        ev.keyCode === 17 ||
        ev.keyCode === 18;
}
var matchColorCache = {};
function matchColorDistance(r1, g1, b1, r2, g2, b2) {
    return Math.pow(30 * (r1 - r2), 2)
        + Math.pow(59 * (g1 - g2), 2)
        + Math.pow(11 * (b1 - b2), 2);
}
function matchColor_(r1, g1, b1) {
    var hash = (r1 << 16) | (g1 << 8) | b1;
    if (matchColorCache[hash] != null) {
        return matchColorCache[hash];
    }
    var ldiff = Infinity;
    var li = -1;
    var i = 0;
    var c;
    var r2;
    var g2;
    var b2;
    var diff;
    for (; i < ColorManager_1.DEFAULT_ANSI_COLORS.length; i++) {
        c = ColorManager_1.DEFAULT_ANSI_COLORS[i].rgba;
        r2 = c >>> 24;
        g2 = c >>> 16 & 0xFF;
        b2 = c >>> 8 & 0xFF;
        diff = matchColorDistance(r1, g1, b1, r2, g2, b2);
        if (diff === 0) {
            li = i;
            break;
        }
        if (diff < ldiff) {
            ldiff = diff;
            li = i;
        }
    }
    return matchColorCache[hash] = li;
}

//# sourceMappingURL=Terminal.js.map


/***/ }),

/***/ "plMY":
/*!*************************************************************!*\
  !*** ./node_modules/@jupyterlab/settingeditor/lib/index.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
__webpack_require__(/*! ../style/settingeditor.css */ "TPoW");
__export(__webpack_require__(/*! ./settingeditor */ "qmQW"));
/* tslint:disable */
/**
 * The setting editor tracker token.
 */
exports.ISettingEditorTracker = new coreutils_1.Token('@jupyterlab/settingeditor:ISettingEditorTracker');


/***/ }),

/***/ "plRf":
/*!***************************************************!*\
  !*** ./node_modules/mdi-react/FacebookBoxIcon.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var FacebookBoxIcon = function FacebookBoxIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M5,3H19C20.1,3 21,3.9 21,5V19C21,20.1 20.1,21 19,21H5C3.9,21 3,20.1 3,19V5C3,3.9 3.9,3 5,3M18,5H15.5C13.57,5 12,6.57 12,8.5V11H10V14H12V21H15V14H18V11H15V9C15,8.45 15.45,8 16,8H18V5Z' })
  );
};

module.exports = FacebookBoxIcon;


/***/ }),

/***/ "pnsq":
/*!******************************************************************!*\
  !*** ./node_modules/react-json-tree/lib/getCollectionEntries.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _getIterator2 = __webpack_require__(/*! babel-runtime/core-js/get-iterator */ "FyfS");

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _getOwnPropertyNames = __webpack_require__(/*! babel-runtime/core-js/object/get-own-property-names */ "OyzN");

var _getOwnPropertyNames2 = _interopRequireDefault(_getOwnPropertyNames);

var _keys = __webpack_require__(/*! babel-runtime/core-js/object/keys */ "GQeE");

var _keys2 = _interopRequireDefault(_keys);

exports['default'] = getCollectionEntries;

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

function getLength(type, collection) {
  if (type === 'Object') {
    return (0, _keys2['default'])(collection).length;
  } else if (type === 'Array') {
    return collection.length;
  }

  return Infinity;
}

function isIterableMap(collection) {
  return typeof collection.set === 'function';
}

function getEntries(type, collection, sortObjectKeys) {
  var from = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  var to = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : Infinity;

  var res = void 0;

  if (type === 'Object') {
    var keys = (0, _getOwnPropertyNames2['default'])(collection);

    if (sortObjectKeys) {
      keys.sort(sortObjectKeys === true ? undefined : sortObjectKeys);
    }

    keys = keys.slice(from, to + 1);

    res = {
      entries: keys.map(function (key) {
        return { key: key, value: collection[key] };
      })
    };
  } else if (type === 'Array') {
    res = {
      entries: collection.slice(from, to + 1).map(function (val, idx) {
        return { key: idx + from, value: val };
      })
    };
  } else {
    var idx = 0;
    var entries = [];
    var done = true;

    var isMap = isIterableMap(collection);

    for (var _iterator = collection, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3['default'])(_iterator);;) {
      var _ref;

      if (_isArray) {
        if (_i >= _iterator.length) break;
        _ref = _iterator[_i++];
      } else {
        _i = _iterator.next();
        if (_i.done) break;
        _ref = _i.value;
      }

      var item = _ref;

      if (idx > to) {
        done = false;
        break;
      }
      if (from <= idx) {
        if (isMap && Array.isArray(item)) {
          if (typeof item[0] === 'string' || typeof item[0] === 'number') {
            entries.push({ key: item[0], value: item[1] });
          } else {
            entries.push({
              key: '[entry ' + idx + ']',
              value: {
                '[key]': item[0],
                '[value]': item[1]
              }
            });
          }
        } else {
          entries.push({ key: idx, value: item });
        }
      }
      idx++;
    }

    res = {
      hasMore: !done,
      entries: entries
    };
  }

  return res;
}

function getRanges(from, to, limit) {
  var ranges = [];
  while (to - from > limit * limit) {
    limit = limit * limit;
  }
  for (var i = from; i <= to; i += limit) {
    ranges.push({ from: i, to: Math.min(to, i + limit - 1) });
  }

  return ranges;
}

function getCollectionEntries(type, collection, sortObjectKeys, limit) {
  var from = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
  var to = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : Infinity;

  var getEntriesBound = getEntries.bind(null, type, collection, sortObjectKeys);

  if (!limit) {
    return getEntriesBound().entries;
  }

  var isSubset = to < Infinity;
  var length = Math.min(to - from, getLength(type, collection));

  if (type !== 'Iterable') {
    if (length <= limit || limit < 7) {
      return getEntriesBound(from, to).entries;
    }
  } else {
    if (length <= limit && !isSubset) {
      return getEntriesBound(from, to).entries;
    }
  }

  var limitedEntries = void 0;
  if (type === 'Iterable') {
    var _getEntriesBound = getEntriesBound(from, from + limit - 1),
        hasMore = _getEntriesBound.hasMore,
        entries = _getEntriesBound.entries;

    limitedEntries = hasMore ? [].concat(entries, getRanges(from + limit, from + 2 * limit - 1, limit)) : entries;
  } else {
    limitedEntries = isSubset ? getRanges(from, to, limit) : [].concat(getEntriesBound(0, limit - 5).entries, getRanges(limit - 4, length - 5, limit), getEntriesBound(length - 4, length - 1).entries);
  }

  return limitedEntries;
}

/***/ }),

/***/ "poX/":
/*!***************************************************************!*\
  !*** ./node_modules/plotly.js/src/plots/layout_attributes.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var fontAttrs = __webpack_require__(/*! ./font_attributes */ "mEVB");
var animationAttrs = __webpack_require__(/*! ./animation_attributes */ "W2jp");
var colorAttrs = __webpack_require__(/*! ../components/color/attributes */ "37PH");
var colorscaleAttrs = __webpack_require__(/*! ../components/colorscale/layout_attributes */ "DdeV");
var padAttrs = __webpack_require__(/*! ./pad_attributes */ "grU7");
var extendFlat = __webpack_require__(/*! ../lib/extend */ "kJIm").extendFlat;

var globalFont = fontAttrs({
    editType: 'calc',
    description: [
        'Sets the global font.',
        'Note that fonts used in traces and other',
        'layout components inherit from the global font.'
    ].join(' ')
});
globalFont.family.dflt = '"Open Sans", verdana, arial, sans-serif';
globalFont.size.dflt = 12;
globalFont.color.dflt = colorAttrs.defaultLine;

module.exports = {
    font: globalFont,
    title: {
        text: {
            valType: 'string',
            role: 'info',
            editType: 'layoutstyle',
            description: [
                'Sets the plot\'s title.',
                'Note that before the existence of `title.text`, the title\'s',
                'contents used to be defined as the `title` attribute itself.',
                'This behavior has been deprecated.'
            ].join(' ')
        },
        font: fontAttrs({
            editType: 'layoutstyle',
            description: [
                'Sets the title font.',
                'Note that the title\'s font used to be customized',
                'by the now deprecated `titlefont` attribute.'
            ].join(' ')
        }),
        xref: {
            valType: 'enumerated',
            dflt: 'container',
            values: ['container', 'paper'],
            role: 'info',
            editType: 'layoutstyle',
            description: [
                'Sets the container `x` refers to.',
                '*container* spans the entire `width` of the plot.',
                '*paper* refers to the width of the plotting area only.'
            ].join(' ')
        },
        yref: {
            valType: 'enumerated',
            dflt: 'container',
            values: ['container', 'paper'],
            role: 'info',
            editType: 'layoutstyle',
            description: [
                'Sets the container `y` refers to.',
                '*container* spans the entire `height` of the plot.',
                '*paper* refers to the height of the plotting area only.'
            ].join(' ')
        },
        x: {
            valType: 'number',
            min: 0,
            max: 1,
            dflt: 0.5,
            role: 'style',
            editType: 'layoutstyle',
            description: [
                'Sets the x position with respect to `xref` in normalized',
                'coordinates from *0* (left) to *1* (right).'
            ].join(' ')
        },
        y: {
            valType: 'number',
            min: 0,
            max: 1,
            dflt: 'auto',
            role: 'style',
            editType: 'layoutstyle',
            description: [
                'Sets the y position with respect to `yref` in normalized',
                'coordinates from *0* (bottom) to *1* (top).',
                '*auto* places the baseline of the title onto the',
                'vertical center of the top margin.'
            ].join(' ')
        },
        xanchor: {
            valType: 'enumerated',
            dflt: 'auto',
            values: ['auto', 'left', 'center', 'right'],
            role: 'info',
            editType: 'layoutstyle',
            description: [
                'Sets the title\'s horizontal alignment with respect to its x position.',
                '*left* means that the title starts at x,',
                '*right* means that the title ends at x',
                'and *center* means that the title\'s center is at x.',
                '*auto* divides `xref` by three and calculates the `xanchor`',
                'value automatically based on the value of `x`.'
            ].join(' ')
        },
        yanchor: {
            valType: 'enumerated',
            dflt: 'auto',
            values: ['auto', 'top', 'middle', 'bottom'],
            role: 'info',
            editType: 'layoutstyle',
            description: [
                'Sets the title\'s vertical alignment with respect to its y position.',
                '*top* means that the title\'s cap line is at y,',
                '*bottom* means that the title\'s baseline is at y',
                'and *middle* means that the title\'s midline is at y.',
                '*auto* divides `yref` by three and calculates the `yanchor`',
                'value automatically based on the value of `y`.'
            ].join(' ')
        },
        pad: extendFlat(padAttrs({editType: 'layoutstyle'}), {
            description: [
                'Sets the padding of the title.',
                'Each padding value only applies when the corresponding',
                '`xanchor`/`yanchor` value is set accordingly. E.g. for left',
                'padding to take effect, `xanchor` must be set to *left*.',
                'The same rule applies if `xanchor`/`yanchor` is determined automatically.',
                'Padding is muted if the respective anchor value is *middle*/*center*.'
            ].join(' ')
        }),
        editType: 'layoutstyle'
    },
    autosize: {
        valType: 'boolean',
        role: 'info',
        dflt: false,
        // autosize, width, and height get special editType treatment in _relayout
        // so we can handle noop resizes more efficiently
        editType: 'none',
        description: [
            'Determines whether or not a layout width or height',
            'that has been left undefined by the user',
            'is initialized on each relayout.',

            'Note that, regardless of this attribute,',
            'an undefined layout width or height',
            'is always initialized on the first call to plot.'
        ].join(' ')
    },
    width: {
        valType: 'number',
        role: 'info',
        min: 10,
        dflt: 700,
        editType: 'plot',
        description: [
            'Sets the plot\'s width (in px).'
        ].join(' ')
    },
    height: {
        valType: 'number',
        role: 'info',
        min: 10,
        dflt: 450,
        editType: 'plot',
        description: [
            'Sets the plot\'s height (in px).'
        ].join(' ')
    },
    margin: {
        l: {
            valType: 'number',
            role: 'info',
            min: 0,
            dflt: 80,
            editType: 'plot',
            description: 'Sets the left margin (in px).'
        },
        r: {
            valType: 'number',
            role: 'info',
            min: 0,
            dflt: 80,
            editType: 'plot',
            description: 'Sets the right margin (in px).'
        },
        t: {
            valType: 'number',
            role: 'info',
            min: 0,
            dflt: 100,
            editType: 'plot',
            description: 'Sets the top margin (in px).'
        },
        b: {
            valType: 'number',
            role: 'info',
            min: 0,
            dflt: 80,
            editType: 'plot',
            description: 'Sets the bottom margin (in px).'
        },
        pad: {
            valType: 'number',
            role: 'info',
            min: 0,
            dflt: 0,
            editType: 'plot',
            description: [
                'Sets the amount of padding (in px)',
                'between the plotting area and the axis lines'
            ].join(' ')
        },
        autoexpand: {
            valType: 'boolean',
            role: 'info',
            dflt: true,
            editType: 'plot'
        },
        editType: 'plot'
    },
    paper_bgcolor: {
        valType: 'color',
        role: 'style',
        dflt: colorAttrs.background,
        editType: 'plot',
        description: 'Sets the color of paper where the graph is drawn.'
    },
    plot_bgcolor: {
        // defined here, but set in cartesian.supplyLayoutDefaults
        // because it needs to know if there are (2D) axes or not
        valType: 'color',
        role: 'style',
        dflt: colorAttrs.background,
        editType: 'layoutstyle',
        description: [
            'Sets the color of plotting area in-between x and y axes.'
        ].join(' ')
    },
    separators: {
        valType: 'string',
        role: 'style',
        editType: 'plot',
        description: [
            'Sets the decimal and thousand separators.',
            'For example, *. * puts a \'.\' before decimals and a space',
            'between thousands. In English locales, dflt is *.,* but',
            'other locales may alter this default.'
        ].join(' ')
    },
    hidesources: {
        valType: 'boolean',
        role: 'info',
        dflt: false,
        editType: 'plot',
        description: [
            'Determines whether or not a text link citing the data source is',
            'placed at the bottom-right cored of the figure.',
            'Has only an effect only on graphs that have been generated via',
            'forked graphs from the plotly service (at https://plot.ly or on-premise).'
        ].join(' ')
    },
    showlegend: {
        // handled in legend.supplyLayoutDefaults
        // but included here because it's not in the legend object
        valType: 'boolean',
        role: 'info',
        editType: 'legend',
        description: [
            'Determines whether or not a legend is drawn.',
            'Default is `true` if there is a trace to show and any of these:',
            'a) Two or more traces would by default be shown in the legend.',
            'b) One pie trace is shown in the legend.',
            'c) One trace is explicitly given with `showlegend: true`.'
        ].join(' ')
    },
    colorway: {
        valType: 'colorlist',
        dflt: colorAttrs.defaults,
        role: 'style',
        editType: 'calc',
        description: 'Sets the default trace colors.'
    },
    colorscale: colorscaleAttrs,
    datarevision: {
        valType: 'any',
        role: 'info',
        editType: 'calc',
        description: [
            'If provided, a changed value tells `Plotly.react` that',
            'one or more data arrays has changed. This way you can modify',
            'arrays in-place rather than making a complete new copy for an',
            'incremental change.',
            'If NOT provided, `Plotly.react` assumes that data arrays are',
            'being treated as immutable, thus any data array with a',
            'different identity from its predecessor contains new data.'
        ].join(' ')
    },
    uirevision: {
        valType: 'any',
        role: 'info',
        editType: 'none',
        description: [
            'Used to allow user interactions with the plot to persist after',
            '`Plotly.react` calls that are unaware of these interactions.',
            'If `uirevision` is omitted, or if it is given and it changed from',
            'the previous `Plotly.react` call, the exact new figure is used.',
            'If `uirevision` is truthy and did NOT change, any attribute',
            'that has been affected by user interactions and did not receive a',
            'different value in the new figure will keep the interaction value.',
            '`layout.uirevision` attribute serves as the default for',
            '`uirevision` attributes in various sub-containers. For finer',
            'control you can set these sub-attributes directly. For example,',
            'if your app separately controls the data on the x and y axes you',
            'might set `xaxis.uirevision=*time*` and `yaxis.uirevision=*cost*`.',
            'Then if only the y data is changed, you can update',
            '`yaxis.uirevision=*quantity*` and the y axis range will reset but',
            'the x axis range will retain any user-driven zoom.'
        ].join(' ')
    },
    editrevision: {
        valType: 'any',
        role: 'info',
        editType: 'none',
        description: [
            'Controls persistence of user-driven changes in `editable: true`',
            'configuration, other than trace names and axis titles.',
            'Defaults to `layout.uirevision`.'
        ].join(' ')
    },
    selectionrevision: {
        valType: 'any',
        role: 'info',
        editType: 'none',
        description: [
            'Controls persistence of user-driven changes in selected points',
            'from all traces.'
        ].join(' ')
    },
    template: {
        valType: 'any',
        role: 'info',
        editType: 'calc',
        description: [
            'Default attributes to be applied to the plot. Templates can be',
            'created from existing plots using `Plotly.makeTemplate`, or',
            'created manually. They should be objects with format:',
            '`{layout: layoutTemplate, data: {[type]: [traceTemplate, ...]}, ...}`',
            '`layoutTemplate` and `traceTemplate` are objects matching the',
            'attribute structure of `layout` and a data trace. ',
            'Trace templates are applied cyclically to traces of each type.',
            'Container arrays (eg `annotations`) have special handling:',
            'An object ending in `defaults` (eg `annotationdefaults`) is applied',
            'to each array item. But if an item has a `templateitemname` key',
            'we look in the template array for an item with matching `name` and',
            'apply that instead. If no matching `name` is found we mark the item',
            'invisible. Any named template item not referenced is appended to',
            'the end of the array, so you can use this for a watermark annotation',
            'or a logo image, for example. To omit one of these items on the plot,',
            'make an item with matching `templateitemname` and `visible: false`.'
        ].join(' ')
    },
    modebar: {
        orientation: {
            valType: 'enumerated',
            values: ['v', 'h'],
            dflt: 'h',
            role: 'info',
            editType: 'modebar',
            description: 'Sets the orientation of the modebar.'
        },
        bgcolor: {
            valType: 'color',
            role: 'style',
            editType: 'modebar',
            description: 'Sets the background color of the modebar.'
        },
        color: {
            valType: 'color',
            role: 'style',
            editType: 'modebar',
            description: 'Sets the color of the icons in the modebar.'
        },
        activecolor: {
            valType: 'color',
            role: 'style',
            editType: 'modebar',
            description: 'Sets the color of the active or hovered on icons in the modebar.'
        },
        uirevision: {
            valType: 'any',
            role: 'info',
            editType: 'none',
            description: [
                'Controls persistence of user-driven changes related to the modebar,',
                'including `hovermode`, `dragmode`, and `showspikes` at both the',
                'root level and inside subplots. Defaults to `layout.uirevision`.'
            ].join(' ')
        },
        editType: 'modebar'
    },

    meta: {
        valType: 'data_array',
        editType: 'plot',
        description: [
            'Assigns extra meta information that can be used in various `text` attributes.',
            'Attributes such as the graph, axis and colorbar `title.text` and annotation `text`',
            'support `meta`. One can access `meta` fields using template strings:',
            '`%{meta[i]}` where `i` is the index of the `meta`',
            'item in question.'
        ].join(' ')
    },

    transition: extendFlat({}, animationAttrs.transition, {
        description: [
            'Sets transition options used during Plotly.react updates.'
        ].join(' '),
        editType: 'none'
    }),

    _deprecated: {
        title: {
            valType: 'string',
            role: 'info',
            editType: 'layoutstyle',
            description: [
                'Value of `title` is no longer a simple *string* but a set of sub-attributes.',
                'To set the contents of the title, please use `title.text` now.'
            ].join(' ')
        },
        titlefont: fontAttrs({
            editType: 'layoutstyle',
            description: [
                'Former `titlefont` is now the sub-attribute `font` of `title`.',
                'To customize title font properties, please use `title.font` now.'
            ].join(' ')
        })
    }
};


/***/ }),

/***/ "pocu":
/*!********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotLine3dIcon.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotLine3dIcon = function PlotLine3dIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M21.5 15.625L16.062 14l3.25 5.313zM26 8l-4.5 7.625 2.688.75 1.813-3.063 2.375 4.313-4.188-1.25-4.875 8.313-5.875-9.938-9.125 2.688L10.688 10l2.75 4.75 2.563-.75h.063l-5.375-8.688L.001 18.625h.063l-.063.063 16 8 16-8z' })
    );
};

exports.default = PlotLine3dIcon;

/***/ }),

/***/ "pq2K":
/*!*******************************************!*\
  !*** ./node_modules/base16/lib/colors.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'colors',
  author: 'mrmrs (http://clrs.cc)',
  base00: '#111111',
  base01: '#333333',
  base02: '#555555',
  base03: '#777777',
  base04: '#999999',
  base05: '#bbbbbb',
  base06: '#dddddd',
  base07: '#ffffff',
  base08: '#ff4136',
  base09: '#ff851b',
  base0A: '#ffdc00',
  base0B: '#2ecc40',
  base0C: '#7fdbff',
  base0D: '#0074d9',
  base0E: '#b10dc9',
  base0F: '#85144b'
};
module.exports = exports['default'];

/***/ }),

/***/ "prOm":
/*!*****************************************!*\
  !*** ./node_modules/fbjs/lib/Scroll.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

/**
 * @param {DOMElement} element
 * @param {DOMDocument} doc
 * @return {boolean}
 */
function _isViewportScrollElement(element, doc) {
  return !!doc && (element === doc.documentElement || element === doc.body);
}

/**
 * Scroll Module. This class contains 4 simple static functions
 * to be used to access Element.scrollTop/scrollLeft properties.
 * To solve the inconsistencies between browsers when either
 * document.body or document.documentElement is supplied,
 * below logic will be used to alleviate the issue:
 *
 * 1. If 'element' is either 'document.body' or 'document.documentElement,
 *    get whichever element's 'scroll{Top,Left}' is larger.
 * 2. If 'element' is either 'document.body' or 'document.documentElement',
 *    set the 'scroll{Top,Left}' on both elements.
 */

var Scroll = {
  /**
   * @param {DOMElement} element
   * @return {number}
   */
  getTop: function getTop(element) {
    var doc = element.ownerDocument;
    return _isViewportScrollElement(element, doc) ?
    // In practice, they will either both have the same value,
    // or one will be zero and the other will be the scroll position
    // of the viewport. So we can use `X || Y` instead of `Math.max(X, Y)`
    doc.body.scrollTop || doc.documentElement.scrollTop : element.scrollTop;
  },

  /**
   * @param {DOMElement} element
   * @param {number} newTop
   */
  setTop: function setTop(element, newTop) {
    var doc = element.ownerDocument;
    if (_isViewportScrollElement(element, doc)) {
      doc.body.scrollTop = doc.documentElement.scrollTop = newTop;
    } else {
      element.scrollTop = newTop;
    }
  },

  /**
   * @param {DOMElement} element
   * @return {number}
   */
  getLeft: function getLeft(element) {
    var doc = element.ownerDocument;
    return _isViewportScrollElement(element, doc) ? doc.body.scrollLeft || doc.documentElement.scrollLeft : element.scrollLeft;
  },

  /**
   * @param {DOMElement} element
   * @param {number} newLeft
   */
  setLeft: function setLeft(element, newLeft) {
    var doc = element.ownerDocument;
    if (_isViewportScrollElement(element, doc)) {
      doc.body.scrollLeft = doc.documentElement.scrollLeft = newLeft;
    } else {
      element.scrollLeft = newLeft;
    }
  }
};

module.exports = Scroll;

/***/ }),

/***/ "psdB":
/*!***********************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/filter_unique.js ***!
  \***********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/





/**
 * Return news array containing only the unique items
 * found in input array.
 *
 * IMPORTANT: Note that items are considered unique
 * if `String({})` is unique. For example;
 *
 *  Lib.filterUnique([ { a: 1 }, { b: 2 } ])
 *
 *  returns [{ a: 1 }]
 *
 * and
 *
 *  Lib.filterUnique([ '1', 1 ])
 *
 *  returns ['1']
 *
 *
 * @param {array} array base array
 * @return {array} new filtered array
 */
module.exports = function filterUnique(array) {
    var seen = {};
    var out = [];
    var j = 0;

    for(var i = 0; i < array.length; i++) {
        var item = array[i];

        if(seen[item] !== 1) {
            seen[item] = 1;
            out[j++] = item;
        }
    }

    return out;
};


/***/ }),

/***/ "pviQ":
/*!**********************************************!*\
  !*** ./node_modules/ajv/lib/refs/$data.json ***!
  \**********************************************/
/*! exports provided: $schema, $id, description, type, required, properties, additionalProperties, default */
/***/ (function(module) {

module.exports = {"$schema":"http://json-schema.org/draft-06/schema#","$id":"https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/$data.json#","description":"Meta-schema for $data reference (JSON-schema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false};

/***/ }),

/***/ "q+TC":
/*!********************************************************************************************!*\
  !*** ./node_modules/react-resizable-rotatable-draggable/lib/components/Rect/StyledRect.js ***!
  \********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _styledComponents = _interopRequireDefault(__webpack_require__(/*! styled-components */ "vOnD"));

var _react = _interopRequireDefault(__webpack_require__(/*! react */ "q1tI"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var _default = _styledComponents.default.div.withConfig({
  displayName: "StyledRect"
})(["position:absolute;border:1px solid #eb5648;.square{position:absolute;width:7px;height:7px;background:white;border:1px solid #eb5648;border-radius:1px;}.resizable-handler{position:absolute;width:14px;height:14px;cursor:pointer;z-index:1;&.tl,&.t,&.tr{top:-7px;}&.tl,&.l,&.bl{left:-7px;}&.bl,&.b,&.br{bottom:-7px;}&.br,&.r,&.tr{right:-7px;}&.l,&.r{margin-top:-7px;}&.t,&.b{margin-left:-7px;}}.rotate{position:absolute;cursor:pointer;left:50%;top:-26px;transform:translateX(-50%);& i{font-size:18px;display:inline-block;width:1em;height:1em;background-size:1em 1em;background-repeat:no-repeat;background-position:center center;background-image:url(\"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTQiIGhlaWdodD0iMTQiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxkZWZzPjxwYXRoIGlkPSJhIiBkPSJNOC4zIDUuNEw4IC40bDMuMiAyLjEgMS43IDF6Ii8+PG1hc2sgaWQ9ImIiIHg9IjAiIHk9IjAiIHdpZHRoPSI0LjkiIGhlaWdodD0iNC45IiBmaWxsPSIjZmZmIj48dXNlIHhsaW5rOmhyZWY9IiNhIi8+PC9tYXNrPjwvZGVmcz48ZyB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxIDEpIiBzdHJva2U9IiNGNTVENTQiIGZpbGw9Im5vbmUiIGZpbGwtcnVsZT0iZXZlbm9kZCI+PHBhdGggZD0iTTExIDkuMkE2IDYgMCAwIDEgMCA2YTYgNiAwIDAgMSAxMC43LTMuOCIvPjx1c2UgbWFzaz0idXJsKCNiKSIgc3Ryb2tlLXdpZHRoPSIyIiB0cmFuc2Zvcm09Im1hdHJpeCgtMSAwIDAgMSAyMSAwKSIgeGxpbms6aHJlZj0iI2EiLz48L2c+PC9zdmc+Cg==\");}}.t,.tl,.tr{top:-3px;}.b,.bl,.br{bottom:-3px;}.r,.tr,.br{right:-3px;}.tl,.l,.bl{left:-3px;}.l,.r{top:50%;margin-top:-3px;}.t,.b{left:50%;margin-left:-3px;}"]);

exports.default = _default;

/***/ }),

/***/ "q/j9":
/*!******************************************************************!*\
  !*** ./node_modules/@jupyterlab/docmanager/lib/widgetmanager.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const disposable_1 = __webpack_require__(/*! @phosphor/disposable */ "uNUc");
const messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
const properties_1 = __webpack_require__(/*! @phosphor/properties */ "3kwb");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
/**
 * The class name added to document widgets.
 */
const DOCUMENT_CLASS = 'jp-Document';
/**
 * A class that maintains the lifecycle of file-backed widgets.
 */
class DocumentWidgetManager {
    /**
     * Construct a new document widget manager.
     */
    constructor(options) {
        this._activateRequested = new signaling_1.Signal(this);
        this._isDisposed = false;
        this._registry = options.registry;
    }
    /**
     * A signal emitted when one of the documents is activated.
     */
    get activateRequested() {
        return this._activateRequested;
    }
    /**
     * Test whether the document widget manager is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources used by the widget manager.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        signaling_1.Signal.disconnectReceiver(this);
    }
    /**
     * Create a widget for a document and handle its lifecycle.
     *
     * @param factory - The widget factory.
     *
     * @param context - The document context object.
     *
     * @returns A widget created by the factory.
     *
     * @throws If the factory is not registered.
     */
    createWidget(factory, context) {
        let widget = factory.createNew(context);
        Private.factoryProperty.set(widget, factory);
        // Handle widget extensions.
        let disposables = new disposable_1.DisposableSet();
        algorithm_1.each(this._registry.widgetExtensions(factory.name), extender => {
            disposables.add(extender.createNew(widget, context));
        });
        Private.disposablesProperty.set(widget, disposables);
        widget.disposed.connect(this._onWidgetDisposed, this);
        this.adoptWidget(context, widget);
        context.fileChanged.connect(this._onFileChanged, this);
        context.pathChanged.connect(this._onPathChanged, this);
        context.ready.then(() => {
            this.setCaption(widget);
        });
        return widget;
    }
    /**
     * Install the message hook for the widget and add to list
     * of known widgets.
     *
     * @param context - The document context object.
     *
     * @param widget - The widget to adopt.
     */
    adoptWidget(context, widget) {
        let widgets = Private.widgetsProperty.get(context);
        widgets.push(widget);
        messaging_1.MessageLoop.installMessageHook(widget, this);
        widget.addClass(DOCUMENT_CLASS);
        widget.title.closable = true;
        widget.disposed.connect(this._widgetDisposed, this);
        Private.contextProperty.set(widget, context);
    }
    /**
     * See if a widget already exists for the given context and widget name.
     *
     * @param context - The document context object.
     *
     * @returns The found widget, or `undefined`.
     *
     * #### Notes
     * This can be used to use an existing widget instead of opening
     * a new widget.
     */
    findWidget(context, widgetName) {
        let widgets = Private.widgetsProperty.get(context);
        if (!widgets) {
            return undefined;
        }
        return algorithm_1.find(widgets, widget => {
            let factory = Private.factoryProperty.get(widget);
            if (!factory) {
                return false;
            }
            return factory.name === widgetName;
        });
    }
    /**
     * Get the document context for a widget.
     *
     * @param widget - The widget of interest.
     *
     * @returns The context associated with the widget, or `undefined`.
     */
    contextForWidget(widget) {
        return Private.contextProperty.get(widget);
    }
    /**
     * Clone a widget.
     *
     * @param widget - The source widget.
     *
     * @returns A new widget or `undefined`.
     *
     * #### Notes
     *  Uses the same widget factory and context as the source, or throws
     *  if the source widget is not managed by this manager.
     */
    cloneWidget(widget) {
        let context = Private.contextProperty.get(widget);
        if (!context) {
            return undefined;
        }
        let factory = Private.factoryProperty.get(widget);
        if (!factory) {
            return undefined;
        }
        let newWidget = this.createWidget(factory, context);
        this.adoptWidget(context, newWidget);
        return newWidget;
    }
    /**
     * Close the widgets associated with a given context.
     *
     * @param context - The document context object.
     */
    closeWidgets(context) {
        let widgets = Private.widgetsProperty.get(context);
        return Promise.all(algorithm_1.toArray(algorithm_1.map(widgets, widget => this.onClose(widget)))).then(() => undefined);
    }
    /**
     * Dispose of the widgets associated with a given context
     * regardless of the widget's dirty state.
     *
     * @param context - The document context object.
     */
    deleteWidgets(context) {
        let widgets = Private.widgetsProperty.get(context);
        return Promise.all(algorithm_1.toArray(algorithm_1.map(widgets, widget => this.onDelete(widget)))).then(() => undefined);
    }
    /**
     * Filter a message sent to a message handler.
     *
     * @param handler - The target handler of the message.
     *
     * @param msg - The message dispatched to the handler.
     *
     * @returns `false` if the message should be filtered, of `true`
     *   if the message should be dispatched to the handler as normal.
     */
    messageHook(handler, msg) {
        switch (msg.type) {
            case 'close-request':
                this.onClose(handler);
                return false;
            case 'activate-request':
                let context = this.contextForWidget(handler);
                if (context) {
                    this._activateRequested.emit(context.path);
                }
                break;
            default:
                break;
        }
        return true;
    }
    /**
     * Set the caption for widget title.
     *
     * @param widget - The target widget.
     */
    setCaption(widget) {
        let context = Private.contextProperty.get(widget);
        if (!context) {
            return;
        }
        let model = context.contentsModel;
        if (!model) {
            widget.title.caption = '';
            return;
        }
        context
            .listCheckpoints()
            .then((checkpoints) => {
            if (widget.isDisposed) {
                return;
            }
            let last = checkpoints[checkpoints.length - 1];
            let checkpoint = last ? coreutils_1.Time.format(last.last_modified) : 'None';
            let caption = `Name: ${model.name}\nPath: ${model.path}\n`;
            if (context.model.readOnly) {
                caption += 'Read-only';
            }
            else {
                caption +=
                    `Last Saved: ${coreutils_1.Time.format(model.last_modified)}\n` +
                        `Last Checkpoint: ${checkpoint}`;
            }
            widget.title.caption = caption;
        });
    }
    /**
     * Handle `'close-request'` messages.
     *
     * @param widget - The target widget.
     *
     * @returns A promise that resolves with whether the widget was closed.
     */
    onClose(widget) {
        // Handle dirty state.
        return this._maybeClose(widget)
            .then(result => {
            if (widget.isDisposed) {
                return true;
            }
            if (result) {
                widget.dispose();
            }
            return result;
        })
            .catch(error => {
            widget.dispose();
            throw error;
        });
    }
    /**
     * Dispose of widget regardless of widget's dirty state.
     *
     * @param widget - The target widget.
     */
    onDelete(widget) {
        widget.dispose();
        return Promise.resolve(void 0);
    }
    /**
     * Ask the user whether to close an unsaved file.
     */
    _maybeClose(widget) {
        // Bail if the model is not dirty or other widgets are using the model.)
        let context = Private.contextProperty.get(widget);
        if (!context) {
            return Promise.resolve(true);
        }
        let widgets = Private.widgetsProperty.get(context);
        if (!widgets) {
            return Promise.resolve(true);
        }
        // Filter by whether the factories are read only.
        widgets = algorithm_1.toArray(algorithm_1.filter(widgets, widget => {
            let factory = Private.factoryProperty.get(widget);
            if (!factory) {
                return false;
            }
            return factory.readOnly === false;
        }));
        let factory = Private.factoryProperty.get(widget);
        if (!factory) {
            return Promise.resolve(true);
        }
        let model = context.model;
        if (!model.dirty || widgets.length > 1 || factory.readOnly) {
            return Promise.resolve(true);
        }
        let fileName = widget.title.label;
        return apputils_1.showDialog({
            title: 'Close without saving?',
            body: `File "${fileName}" has unsaved changes, close without saving?`,
            buttons: [apputils_1.Dialog.cancelButton(), apputils_1.Dialog.warnButton()]
        }).then(result => {
            return result.button.accept;
        });
    }
    /**
     * Handle the disposal of a widget.
     */
    _widgetDisposed(widget) {
        let context = Private.contextProperty.get(widget);
        if (!context) {
            return;
        }
        let widgets = Private.widgetsProperty.get(context);
        if (!widgets) {
            return;
        }
        // Remove the widget.
        algorithm_1.ArrayExt.removeFirstOf(widgets, widget);
        // Dispose of the context if this is the last widget using it.
        if (!widgets.length) {
            context.dispose();
        }
    }
    /**
     * Handle the disposal of a widget.
     */
    _onWidgetDisposed(widget) {
        let disposables = Private.disposablesProperty.get(widget);
        disposables.dispose();
    }
    /**
     * Handle a file changed signal for a context.
     */
    _onFileChanged(context) {
        let widgets = Private.widgetsProperty.get(context);
        algorithm_1.each(widgets, widget => {
            this.setCaption(widget);
        });
    }
    /**
     * Handle a path changed signal for a context.
     */
    _onPathChanged(context) {
        let widgets = Private.widgetsProperty.get(context);
        algorithm_1.each(widgets, widget => {
            this.setCaption(widget);
        });
    }
}
exports.DocumentWidgetManager = DocumentWidgetManager;
/**
 * A private namespace for DocumentManager data.
 */
var Private;
(function (Private) {
    /**
     * A private attached property for a widget context.
     */
    Private.contextProperty = new properties_1.AttachedProperty({
        name: 'context',
        create: () => undefined
    });
    /**
     * A private attached property for a widget factory.
     */
    Private.factoryProperty = new properties_1.AttachedProperty({
        name: 'factory',
        create: () => undefined
    });
    /**
     * A private attached property for the widgets associated with a context.
     */
    Private.widgetsProperty = new properties_1.AttachedProperty({
        name: 'widgets',
        create: () => []
    });
    /**
     * A private attached property for a widget's disposables.
     */
    Private.disposablesProperty = new properties_1.AttachedProperty({
        name: 'disposables',
        create: () => new disposable_1.DisposableSet()
    });
})(Private || (Private = {}));


/***/ }),

/***/ "q1tI":
/*!*************************************!*\
  !*** ./node_modules/react/index.js ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


if (false) {} else {
  module.exports = __webpack_require__(/*! ./cjs/react.development.js */ "ctBr");
}


/***/ }),

/***/ "q1z7":
/*!*******************************************!*\
  !*** ./node_modules/backbone/backbone.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;//     Backbone.js 1.2.3

//     (c) 2010-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
//     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 global == 'object' && global.global == global && global);

  // Set up Backbone appropriately for the environment. Start with AMD.
  if (true) {
    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! underscore */ "F/us"), __webpack_require__(/*! jquery */ "EVdn"), 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.2.3';

  // 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;

  // 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(length, method, attribute) {
    switch (length) {
      case 1: return function() {
        return _[method](this[attribute]);
      };
      case 2: return function(value) {
        return _[method](this[attribute], value);
      };
      case 3: return function(iteratee, context) {
        return _[method](this[attribute], cb(iteratee, this), context);
      };
      case 4: return function(iteratee, defaultVal, context) {
        return _[method](this[attribute], cb(iteratee, this), defaultVal, context);
      };
      default: return function() {
        var args = slice.call(arguments);
        args.unshift(this[attribute]);
        return _[method].apply(_, args);
      };
    }
  };
  var addUnderscoreMethods = function(Class, methods, attribute) {
    _.each(methods, function(length, method) {
      if (_[method]) Class.prototype[method] = addMethod(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);
    };
  };

  // 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+/;

  // 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) {
    return internalOn(this, name, callback, context);
  };

  // Guard the `listening` argument from the public API.
  var internalOn = function(obj, name, callback, context, listening) {
    obj._events = eventsApi(onApi, obj._events || {}, name, callback, {
        context: context,
        ctx: obj,
        listening: listening
    });

    if (listening) {
      var listeners = obj._listeners || (obj._listeners = {});
      listeners[listening.id] = listening;
    }

    return obj;
  };

  // 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 = 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) {
      var thisId = this._listenId || (this._listenId = _.uniqueId('l'));
      listening = listeningTo[id] = {obj: obj, objId: id, id: thisId, listeningTo: listeningTo, count: 0};
    }

    // Bind callbacks on obj, and keep track of them on listening.
    internalOn(obj, name, callback, this, listening);
    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;
  };

  // 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 (_.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 i = 0, listening;
    var context = options.context, listeners = options.listeners;

    // Delete all events listeners and "drop" events.
    if (!name && !callback && !context) {
      var ids = _.keys(listeners);
      for (; i < ids.length; i++) {
        listening = listeners[ids[i]];
        delete listeners[listening.id];
        delete listening.listeningTo[listening.objId];
      }
      return;
    }

    var 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;

      // Replace events if there are any remaining.  Otherwise, clean up.
      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 {
          listening = handler.listening;
          if (listening && --listening.count === 0) {
            delete listeners[listening.id];
            delete listening.listeningTo[listening.objId];
          }
        }
      }

      // Update tail event if the list has any events.  Otherwise, clean up.
      if (remaining.length) {
        events[name] = remaining;
      } else {
        delete events[name];
      }
    }
    if (_.size(events)) 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, _.bind(this.off, this));
    return this.on(events, void 0, 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, _.bind(this.stopListening, 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, cb, 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;
    }
  };

  // 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.cid = _.uniqueId(this.cidPrefix);
    this.attributes = {};
    if (options.collection) this.collection = options.collection;
    if (options.parse) attrs = this.parse(attrs, options) || {};
    attrs = _.defaults({}, attrs, _.result(this, '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',

    // 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`.
      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 = {};
      for (var attr in diff) {
        var val = diff[attr];
        if (_.isEqual(old[attr], val)) continue;
        changed[attr] = val;
      }
      return _.size(changed) ? 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({}, _.defaults({validate: true}, options));
    },

    // 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;
    }

  });

  // 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 `Model#attributes`.
  addUnderscoreMethods(Model, modelMethods, 'attributes');

  // 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 = {});
    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;
    for (var 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,

    // 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] : _.clone(models);
      var removed = this._removeModels(models, options);
      if (!options.silent && 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 = _.defaults({}, options, setOptions);
      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 < 0) at += this.length + 1;

      var set = [];
      var toAdd = [];
      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;
      for (var 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);
            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(model, index) {
          return model !== 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 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) 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.
    get: function(obj) {
      if (obj == null) return void 0;
      var id = this.modelId(this._isModel(obj) ? obj.attributes : obj);
      return this._byId[obj] || this._byId[id] || this._byId[obj.cid];
    },

    // 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 = _.bind(comparator, 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 _.invoke(this.models, 'get', 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(model, resp, callbackOpts) {
        if (wait) collection.add(model, callbackOpts);
        if (success) success.call(callbackOpts.context, model, 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'];
    },

    // 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--;

        if (!options.silent) {
          options.index = index;
          model.trigger('remove', model, this, options);
        }

        removed.push(model);
        this._removeReference(model, options);
      }
      return removed.length ? removed : false;
    },

    // 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 ((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);
    }

  });

  // 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: 4,
      foldl: 4, inject: 4, reduceRight: 4, foldr: 4, 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};

  // Mix in each Underscore method as a proxy to `Collection#models`.
  addUnderscoreMethods(Collection, collectionMethods, 'models');

  // 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');
    _.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);
    },

    // 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], _.bind(method, 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);
    }

  });

  // 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 = {});
    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, {

    // 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 = _.bind(this.checkUrl, 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 root = path.slice(0, this.root.length - 1) + '/';
      return root === 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 root = this.root.slice(0, -1) || '/';
          this.location.replace(root + '#' + 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 root = this.root;
      if (fragment === '' || fragment.charAt(0) === '?') {
        root = root.slice(0, -1) || '/';
      }
      var url = root + fragment;

      // Strip the hash and decode for matching.
      fragment = this.decodeFragment(fragment.replace(pathStripper, ''));

      if (this.fragment === fragment) return;
      this.fragment = fragment;

      // 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` constructor function.
    var Surrogate = function(){ this.constructor = child; };
    Surrogate.prototype = parent.prototype;
    child.prototype = new Surrogate;

    // Add prototype properties (instance properties) to the subclass,
    // if supplied.
    if (protoProps) _.extend(child.prototype, protoProps);

    // 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;

}));

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "q4Uc":
/*!******************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/session/default.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const kernel_1 = __webpack_require__(/*! ../kernel */ "uxQ0");
const __1 = __webpack_require__(/*! .. */ "S9up");
const validate = __importStar(__webpack_require__(/*! ./validate */ "vvGI"));
/**
 * The url for the session service.
 */
const SESSION_SERVICE_URL = 'api/sessions';
/**
 * Session object for accessing the session REST api. The session
 * should be used to start kernels and then shut them down -- for
 * all other operations, the kernel object should be used.
 */
class DefaultSession {
    /**
     * Construct a new session.
     */
    constructor(options, id, kernel) {
        this._id = '';
        this._path = '';
        this._name = '';
        this._type = '';
        this._isDisposed = false;
        this._updating = false;
        this._kernelChanged = new signaling_1.Signal(this);
        this._statusChanged = new signaling_1.Signal(this);
        this._iopubMessage = new signaling_1.Signal(this);
        this._unhandledMessage = new signaling_1.Signal(this);
        this._anyMessage = new signaling_1.Signal(this);
        this._propertyChanged = new signaling_1.Signal(this);
        this._terminated = new signaling_1.Signal(this);
        this._id = id;
        this._path = options.path;
        this._type = options.type || 'file';
        this._name = options.name || '';
        this.serverSettings =
            options.serverSettings || __1.ServerConnection.makeSettings();
        Private.addRunning(this);
        this.setupKernel(kernel);
    }
    /**
     * A signal emitted when the session is shut down.
     */
    get terminated() {
        return this._terminated;
    }
    /**
     * A signal emitted when the kernel changes.
     */
    get kernelChanged() {
        return this._kernelChanged;
    }
    /**
     * A signal emitted when the kernel status changes.
     */
    get statusChanged() {
        return this._statusChanged;
    }
    /**
     * A signal emitted for a kernel messages.
     */
    get iopubMessage() {
        return this._iopubMessage;
    }
    /**
     * A signal emitted for an unhandled kernel message.
     */
    get unhandledMessage() {
        return this._unhandledMessage;
    }
    /**
     * A signal emitted for any kernel message.
     *
     * Note: The behavior is undefined if the message is modified
     * during message handling. As such, it should be treated as read-only.
     */
    get anyMessage() {
        return this._anyMessage;
    }
    /**
     * A signal emitted when a session property changes.
     */
    get propertyChanged() {
        return this._propertyChanged;
    }
    /**
     * Get the session id.
     */
    get id() {
        return this._id;
    }
    /**
     * Get the session kernel object.
     *
     * #### Notes
     * This is a read-only property, and can be altered by [changeKernel].
     */
    get kernel() {
        return this._kernel;
    }
    /**
     * Get the session path.
     */
    get path() {
        return this._path;
    }
    /**
     * Get the session type.
     */
    get type() {
        return this._type;
    }
    /**
     * Get the session name.
     */
    get name() {
        return this._name;
    }
    /**
     * Get the model associated with the session.
     */
    get model() {
        return {
            id: this.id,
            kernel: this.kernel.model,
            path: this._path,
            type: this._type,
            name: this._name
        };
    }
    /**
     * The current status of the session.
     *
     * #### Notes
     * This is a delegate to the kernel status.
     */
    get status() {
        return this._kernel ? this._kernel.status : 'dead';
    }
    /**
     * Test whether the session has been disposed.
     */
    get isDisposed() {
        return this._isDisposed === true;
    }
    /**
     * Clone the current session with a new clientId.
     */
    clone() {
        const kernel = kernel_1.Kernel.connectTo(this.kernel.model, this.serverSettings);
        return new DefaultSession({
            path: this._path,
            name: this._name,
            type: this._type,
            serverSettings: this.serverSettings
        }, this._id, kernel);
    }
    /**
     * Update the session based on a session model from the server.
     */
    update(model) {
        // Avoid a race condition if we are waiting for a REST call return.
        if (this._updating) {
            return;
        }
        let oldModel = this.model;
        this._path = model.path;
        this._name = model.name;
        this._type = model.type;
        if (this._kernel.isDisposed || model.kernel.id !== this._kernel.id) {
            let newValue = kernel_1.Kernel.connectTo(model.kernel, this.serverSettings);
            let oldValue = this._kernel;
            this.setupKernel(newValue);
            this._kernelChanged.emit({ oldValue, newValue });
            this._handleModelChange(oldModel);
            return;
        }
        this._handleModelChange(oldModel);
    }
    /**
     * Dispose of the resources held by the session.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        this._kernel.dispose();
        this._statusChanged.emit('dead');
        this._terminated.emit(void 0);
        Private.removeRunning(this);
        signaling_1.Signal.clearData(this);
    }
    /**
     * Change the session path.
     *
     * @param path - The new session path.
     *
     * @returns A promise that resolves when the session has renamed.
     *
     * #### Notes
     * This uses the Jupyter REST API, and the response is validated.
     * The promise is fulfilled on a valid response and rejected otherwise.
     */
    setPath(path) {
        if (this.isDisposed) {
            return Promise.reject(new Error('Session is disposed'));
        }
        let data = JSON.stringify({ path });
        return this._patch(data).then(() => {
            return void 0;
        });
    }
    /**
     * Change the session name.
     */
    setName(name) {
        if (this.isDisposed) {
            return Promise.reject(new Error('Session is disposed'));
        }
        let data = JSON.stringify({ name });
        return this._patch(data).then(() => {
            return void 0;
        });
    }
    /**
     * Change the session type.
     */
    setType(type) {
        if (this.isDisposed) {
            return Promise.reject(new Error('Session is disposed'));
        }
        let data = JSON.stringify({ type });
        return this._patch(data).then(() => {
            return void 0;
        });
    }
    /**
     * Change the kernel.
     *
     * @params options - The name or id of the new kernel.
     *
     * #### Notes
     * This shuts down the existing kernel and creates a new kernel,
     * keeping the existing session ID and session path.
     */
    changeKernel(options) {
        if (this.isDisposed) {
            return Promise.reject(new Error('Session is disposed'));
        }
        let data = JSON.stringify({ kernel: options });
        this._kernel.dispose();
        this._statusChanged.emit('restarting');
        return this._patch(data).then(() => this.kernel);
    }
    /**
     * Kill the kernel and shutdown the session.
     *
     * @returns - The promise fulfilled on a valid response from the server.
     *
     * #### Notes
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/sessions), and validates the response.
     * Disposes of the session and emits a [sessionDied] signal on success.
     */
    shutdown() {
        if (this.isDisposed) {
            return Promise.reject(new Error('Session is disposed'));
        }
        return Private.shutdownSession(this.id, this.serverSettings);
    }
    /**
     * Handle connections to a kernel.  This method is not meant to be
     * subclassed.
     */
    setupKernel(kernel) {
        this._kernel = kernel;
        kernel.statusChanged.connect(this.onKernelStatus, this);
        kernel.unhandledMessage.connect(this.onUnhandledMessage, this);
        kernel.iopubMessage.connect(this.onIOPubMessage, this);
        kernel.anyMessage.connect(this.onAnyMessage, this);
    }
    /**
     * Handle to changes in the Kernel status.
     */
    onKernelStatus(sender, state) {
        this._statusChanged.emit(state);
    }
    /**
     * Handle iopub kernel messages.
     */
    onIOPubMessage(sender, msg) {
        this._iopubMessage.emit(msg);
    }
    /**
     * Handle unhandled kernel messages.
     */
    onUnhandledMessage(sender, msg) {
        this._unhandledMessage.emit(msg);
    }
    /**
     * Handle any kernel messages.
     */
    onAnyMessage(sender, args) {
        this._anyMessage.emit(args);
    }
    /**
     * Send a PATCH to the server, updating the session path or the kernel.
     */
    _patch(body) {
        this._updating = true;
        let settings = this.serverSettings;
        let url = Private.getSessionUrl(settings.baseUrl, this._id);
        let init = {
            method: 'PATCH',
            body
        };
        return __1.ServerConnection.makeRequest(url, init, settings)
            .then(response => {
            this._updating = false;
            if (response.status !== 200) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            return response.json();
        })
            .then(data => {
            let model = validate.validateModel(data);
            return Private.updateFromServer(model, settings.baseUrl);
        }, error => {
            this._updating = false;
            throw error;
        });
    }
    /**
     * Handle a change to the model.
     */
    _handleModelChange(oldModel) {
        if (oldModel.name !== this._name) {
            this._propertyChanged.emit('name');
        }
        if (oldModel.type !== this._type) {
            this._propertyChanged.emit('type');
        }
        if (oldModel.path !== this._path) {
            this._propertyChanged.emit('path');
        }
    }
}
exports.DefaultSession = DefaultSession;
/**
 * The namespace for `DefaultSession` statics.
 */
(function (DefaultSession) {
    /**
     * List the running sessions.
     */
    function listRunning(settings) {
        return Private.listRunning(settings);
    }
    DefaultSession.listRunning = listRunning;
    /**
     * Start a new session.
     */
    function startNew(options) {
        return Private.startNew(options);
    }
    DefaultSession.startNew = startNew;
    /**
     * Find a session by id.
     */
    function findById(id, settings) {
        return Private.findById(id, settings);
    }
    DefaultSession.findById = findById;
    /**
     * Find a session by path.
     */
    function findByPath(path, settings) {
        return Private.findByPath(path, settings);
    }
    DefaultSession.findByPath = findByPath;
    /**
     * Connect to a running session.
     */
    function connectTo(model, settings) {
        return Private.connectTo(model, settings);
    }
    DefaultSession.connectTo = connectTo;
    /**
     * Shut down a session by id.
     */
    function shutdown(id, settings) {
        return Private.shutdownSession(id, settings);
    }
    DefaultSession.shutdown = shutdown;
    /**
     * Shut down all sessions.
     *
     * @param settings - The server settings to use.
     *
     * @returns A promise that resolves when all the sessions are shut down.
     */
    function shutdownAll(settings) {
        return Private.shutdownAll(settings);
    }
    DefaultSession.shutdownAll = shutdownAll;
})(DefaultSession = exports.DefaultSession || (exports.DefaultSession = {}));
/**
 * A namespace for session private data.
 */
var Private;
(function (Private) {
    /**
     * The running sessions mapped by base url.
     */
    const runningSessions = new Map();
    /**
     * Add a session to the running sessions.
     */
    function addRunning(session) {
        let running = runningSessions.get(session.serverSettings.baseUrl) || [];
        running.push(session);
        runningSessions.set(session.serverSettings.baseUrl, running);
    }
    Private.addRunning = addRunning;
    /**
     * Remove a session from the running sessions.
     */
    function removeRunning(session) {
        let running = runningSessions.get(session.serverSettings.baseUrl);
        if (running) {
            algorithm_1.ArrayExt.removeFirstOf(running, session);
        }
    }
    Private.removeRunning = removeRunning;
    /**
     * Connect to a running session.
     */
    function connectTo(model, settings) {
        settings = settings || __1.ServerConnection.makeSettings();
        let running = runningSessions.get(settings.baseUrl) || [];
        let session = algorithm_1.find(running, value => value.id === model.id);
        if (session) {
            return session.clone();
        }
        return createSession(model, settings);
    }
    Private.connectTo = connectTo;
    /**
     * Create a Session object.
     *
     * @returns - A promise that resolves with a started session.
     */
    function createSession(model, settings) {
        settings = settings || __1.ServerConnection.makeSettings();
        let kernel = kernel_1.Kernel.connectTo(model.kernel, settings);
        return new DefaultSession({
            path: model.path,
            type: model.type,
            name: model.name,
            serverSettings: settings
        }, model.id, kernel);
    }
    Private.createSession = createSession;
    /**
     * Find a session by id.
     */
    function findById(id, settings) {
        settings = settings || __1.ServerConnection.makeSettings();
        let running = runningSessions.get(settings.baseUrl) || [];
        let session = algorithm_1.find(running, value => value.id === id);
        if (session) {
            return Promise.resolve(session.model);
        }
        return getSessionModel(id, settings).catch(() => {
            throw new Error(`No running session for id: ${id}`);
        });
    }
    Private.findById = findById;
    /**
     * Find a session by path.
     */
    function findByPath(path, settings) {
        settings = settings || __1.ServerConnection.makeSettings();
        let running = runningSessions.get(settings.baseUrl) || [];
        let session = algorithm_1.find(running, value => value.path === path);
        if (session) {
            return Promise.resolve(session.model);
        }
        return listRunning(settings).then(models => {
            let model = algorithm_1.find(models, value => {
                return value.path === path;
            });
            if (model) {
                return model;
            }
            throw new Error(`No running session for path: ${path}`);
        });
    }
    Private.findByPath = findByPath;
    /**
     * Get a full session model from the server by session id string.
     */
    function getSessionModel(id, settings) {
        settings = settings || __1.ServerConnection.makeSettings();
        let url = getSessionUrl(settings.baseUrl, id);
        return __1.ServerConnection.makeRequest(url, {}, settings)
            .then(response => {
            if (response.status !== 200) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            return response.json();
        })
            .then(data => {
            const model = validate.validateModel(data);
            return updateFromServer(model, settings.baseUrl);
        });
    }
    Private.getSessionModel = getSessionModel;
    /**
     * Get a session url.
     */
    function getSessionUrl(baseUrl, id) {
        return coreutils_1.URLExt.join(baseUrl, SESSION_SERVICE_URL, id);
    }
    Private.getSessionUrl = getSessionUrl;
    /**
     * Kill the sessions by id.
     */
    function killSessions(id, baseUrl) {
        let running = runningSessions.get(baseUrl) || [];
        algorithm_1.each(running.slice(), session => {
            if (session.id === id) {
                session.dispose();
            }
        });
    }
    /**
     * List the running sessions.
     */
    function listRunning(settings) {
        settings = settings || __1.ServerConnection.makeSettings();
        let url = coreutils_1.URLExt.join(settings.baseUrl, SESSION_SERVICE_URL);
        return __1.ServerConnection.makeRequest(url, {}, settings)
            .then(response => {
            if (response.status !== 200) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            return response.json();
        })
            .then(data => {
            if (!Array.isArray(data)) {
                throw new Error('Invalid Session list');
            }
            for (let i = 0; i < data.length; i++) {
                data[i] = validate.validateModel(data[i]);
            }
            return updateRunningSessions(data, settings.baseUrl);
        });
    }
    Private.listRunning = listRunning;
    /**
     * Shut down a session by id.
     */
    function shutdownSession(id, settings) {
        settings = settings || __1.ServerConnection.makeSettings();
        let url = getSessionUrl(settings.baseUrl, id);
        let init = { method: 'DELETE' };
        return __1.ServerConnection.makeRequest(url, init, settings).then(response => {
            if (response.status === 404) {
                response.json().then(data => {
                    let msg = data.message || `The session "${id}"" does not exist on the server`;
                    console.warn(msg);
                });
            }
            else if (response.status === 410) {
                throw new __1.ServerConnection.ResponseError(response, 'The kernel was deleted but the session was not');
            }
            else if (response.status !== 204) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            killSessions(id, settings.baseUrl);
        });
    }
    Private.shutdownSession = shutdownSession;
    /**
     * Shut down all sessions.
     */
    function shutdownAll(settings) {
        settings = settings || __1.ServerConnection.makeSettings();
        return listRunning(settings).then(running => {
            algorithm_1.each(running, s => {
                shutdownSession(s.id, settings);
            });
        });
    }
    Private.shutdownAll = shutdownAll;
    /**
     * Start a new session.
     */
    function startNew(options) {
        if (options.path === void 0) {
            return Promise.reject(new Error('Must specify a path'));
        }
        return startSession(options).then(model => {
            return createSession(model, options.serverSettings);
        });
    }
    Private.startNew = startNew;
    /**
     * Create a new session, or return an existing session if
     * the session path already exists
     */
    function startSession(options) {
        let settings = options.serverSettings || __1.ServerConnection.makeSettings();
        let model = {
            kernel: { name: options.kernelName, id: options.kernelId },
            path: options.path,
            type: options.type || '',
            name: options.name || ''
        };
        let url = coreutils_1.URLExt.join(settings.baseUrl, SESSION_SERVICE_URL);
        let init = {
            method: 'POST',
            body: JSON.stringify(model)
        };
        return __1.ServerConnection.makeRequest(url, init, settings)
            .then(response => {
            if (response.status !== 201) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            return response.json();
        })
            .then(data => {
            const model = validate.validateModel(data);
            return updateFromServer(model, settings.baseUrl);
        });
    }
    Private.startSession = startSession;
    /**
     * Update the running sessions given an updated session Id.
     */
    function updateFromServer(model, baseUrl) {
        let running = runningSessions.get(baseUrl) || [];
        algorithm_1.each(running.slice(), session => {
            if (session.id === model.id) {
                session.update(model);
            }
        });
        return model;
    }
    Private.updateFromServer = updateFromServer;
    /**
     * Update the running sessions based on new data from the server.
     */
    function updateRunningSessions(sessions, baseUrl) {
        let running = runningSessions.get(baseUrl) || [];
        algorithm_1.each(running.slice(), session => {
            let updated = algorithm_1.find(sessions, sId => {
                if (session.id === sId.id) {
                    session.update(sId);
                    return true;
                }
                return false;
            });
            // If session is no longer running on disk, emit dead signal.
            if (!updated && session.status !== 'dead') {
                session.dispose();
            }
        });
        return sessions;
    }
    Private.updateRunningSessions = updateRunningSessions;
})(Private || (Private = {}));


/***/ }),

/***/ "q8VL":
/*!***********************************************************!*\
  !*** ./node_modules/react-json-tree/lib/JSONValueNode.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

/**
 * Renders simple values (eg. strings, numbers, booleans, etc)
 */

var JSONValueNode = function JSONValueNode(_ref) {
  var nodeType = _ref.nodeType,
      styling = _ref.styling,
      labelRenderer = _ref.labelRenderer,
      keyPath = _ref.keyPath,
      valueRenderer = _ref.valueRenderer,
      value = _ref.value,
      valueGetter = _ref.valueGetter;
  return _react2['default'].createElement(
    'li',
    styling('value', nodeType, keyPath),
    _react2['default'].createElement(
      'label',
      styling(['label', 'valueLabel'], nodeType, keyPath),
      labelRenderer(keyPath, nodeType, false, false)
    ),
    _react2['default'].createElement(
      'span',
      styling('valueText', nodeType, keyPath),
      valueRenderer.apply(undefined, [valueGetter(value), value].concat(keyPath))
    )
  );
};

JSONValueNode.propTypes = {
  nodeType: _propTypes2['default'].string.isRequired,
  styling: _propTypes2['default'].func.isRequired,
  labelRenderer: _propTypes2['default'].func.isRequired,
  keyPath: _propTypes2['default'].arrayOf(_propTypes2['default'].oneOfType([_propTypes2['default'].string, _propTypes2['default'].number])).isRequired,
  valueRenderer: _propTypes2['default'].func.isRequired,
  value: _propTypes2['default'].any,
  valueGetter: _propTypes2['default'].func
};

JSONValueNode.defaultProps = {
  valueGetter: function valueGetter(value) {
    return value;
  }
};

exports['default'] = JSONValueNode;

/***/ }),

/***/ "q9eo":
/*!*************************************************************!*\
  !*** ./node_modules/@jupyterlab/observables/lib/modeldb.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const disposable_1 = __webpack_require__(/*! @phosphor/disposable */ "uNUc");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const observablemap_1 = __webpack_require__(/*! ./observablemap */ "14pl");
const observablejson_1 = __webpack_require__(/*! ./observablejson */ "LY7c");
const observablestring_1 = __webpack_require__(/*! ./observablestring */ "eiat");
const undoablelist_1 = __webpack_require__(/*! ./undoablelist */ "VmqU");
/**
 * A concrete implementation of an `IObservableValue`.
 */
class ObservableValue {
    /**
     * Constructor for the value.
     *
     * @param initialValue: the starting value for the `ObservableValue`.
     */
    constructor(initialValue = null) {
        this._value = null;
        this._changed = new signaling_1.Signal(this);
        this._isDisposed = false;
        this._value = initialValue;
    }
    /**
     * The observable type.
     */
    get type() {
        return 'Value';
    }
    /**
     * Whether the value has been disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * The changed signal.
     */
    get changed() {
        return this._changed;
    }
    /**
     * Get the current value, or `undefined` if it has not been set.
     */
    get() {
        return this._value;
    }
    /**
     * Set the current value.
     */
    set(value) {
        let oldValue = this._value;
        if (coreutils_1.JSONExt.deepEqual(oldValue, value)) {
            return;
        }
        this._value = value;
        this._changed.emit({
            oldValue: oldValue,
            newValue: value
        });
    }
    /**
     * Dispose of the resources held by the value.
     */
    dispose() {
        if (this._isDisposed) {
            return;
        }
        this._isDisposed = true;
        signaling_1.Signal.clearData(this);
        this._value = null;
    }
}
exports.ObservableValue = ObservableValue;
/**
 * The namespace for the `ObservableValue` class statics.
 */
(function (ObservableValue) {
    /**
     * The changed args object emitted by the `IObservableValue`.
     */
    class IChangedArgs {
    }
    ObservableValue.IChangedArgs = IChangedArgs;
})(ObservableValue = exports.ObservableValue || (exports.ObservableValue = {}));
/**
 * A concrete implementation of an `IModelDB`.
 */
class ModelDB {
    /**
     * Constructor for the `ModelDB`.
     */
    constructor(options = {}) {
        /**
         * Whether the model has been populated with
         * any model values.
         */
        this.isPrepopulated = false;
        /**
         * Whether the model is collaborative.
         */
        this.isCollaborative = false;
        /**
         * A promise resolved when the model is connected
         * to its backend. For the in-memory ModelDB it
         * is immediately resolved.
         */
        this.connected = Promise.resolve(void 0);
        this._toDispose = false;
        this._isDisposed = false;
        this._disposables = new disposable_1.DisposableSet();
        this._basePath = options.basePath || '';
        if (options.baseDB) {
            this._db = options.baseDB;
        }
        else {
            this._db = new observablemap_1.ObservableMap();
            this._toDispose = true;
        }
    }
    /**
     * The base path for the `ModelDB`. This is prepended
     * to all the paths that are passed in to the member
     * functions of the object.
     */
    get basePath() {
        return this._basePath;
    }
    /**
     * Whether the database is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Get a value for a path.
     *
     * @param path: the path for the object.
     *
     * @returns an `IObservable`.
     */
    get(path) {
        return this._db.get(this._resolvePath(path));
    }
    /**
     * Whether the `IModelDB` has an object at this path.
     *
     * @param path: the path for the object.
     *
     * @returns a boolean for whether an object is at `path`.
     */
    has(path) {
        return this._db.has(this._resolvePath(path));
    }
    /**
     * Create a string and insert it in the database.
     *
     * @param path: the path for the string.
     *
     * @returns the string that was created.
     */
    createString(path) {
        let str = new observablestring_1.ObservableString();
        this._disposables.add(str);
        this.set(path, str);
        return str;
    }
    /**
     * Create an undoable list and insert it in the database.
     *
     * @param path: the path for the list.
     *
     * @returns the list that was created.
     *
     * #### Notes
     * The list can only store objects that are simple
     * JSON Objects and primitives.
     */
    createList(path) {
        let vec = new undoablelist_1.ObservableUndoableList(new undoablelist_1.ObservableUndoableList.IdentitySerializer());
        this._disposables.add(vec);
        this.set(path, vec);
        return vec;
    }
    /**
     * Create a map and insert it in the database.
     *
     * @param path: the path for the map.
     *
     * @returns the map that was created.
     *
     * #### Notes
     * The map can only store objects that are simple
     * JSON Objects and primitives.
     */
    createMap(path) {
        let map = new observablejson_1.ObservableJSON();
        this._disposables.add(map);
        this.set(path, map);
        return map;
    }
    /**
     * Create an opaque value and insert it in the database.
     *
     * @param path: the path for the value.
     *
     * @returns the value that was created.
     */
    createValue(path) {
        let val = new ObservableValue();
        this._disposables.add(val);
        this.set(path, val);
        return val;
    }
    /**
     * Get a value at a path, or `undefined if it has not been set
     * That value must already have been created using `createValue`.
     *
     * @param path: the path for the value.
     */
    getValue(path) {
        let val = this.get(path);
        if (!val || val.type !== 'Value') {
            throw Error('Can only call getValue for an ObservableValue');
        }
        return val.get();
    }
    /**
     * Set a value at a path. That value must already have
     * been created using `createValue`.
     *
     * @param path: the path for the value.
     *
     * @param value: the new value.
     */
    setValue(path, value) {
        let val = this.get(path);
        if (!val || val.type !== 'Value') {
            throw Error('Can only call setValue on an ObservableValue');
        }
        val.set(value);
    }
    /**
     * Create a view onto a subtree of the model database.
     *
     * @param basePath: the path for the root of the subtree.
     *
     * @returns an `IModelDB` with a view onto the original
     *   `IModelDB`, with `basePath` prepended to all paths.
     */
    view(basePath) {
        let view = new ModelDB({ basePath, baseDB: this });
        this._disposables.add(view);
        return view;
    }
    /**
     * Set a value at a path. Not intended to
     * be called by user code, instead use the
     * `create*` factory methods.
     *
     * @param path: the path to set the value at.
     *
     * @param value: the value to set at the path.
     */
    set(path, value) {
        this._db.set(this._resolvePath(path), value);
    }
    /**
     * Dispose of the resources held by the database.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        if (this._toDispose) {
            this._db.dispose();
        }
        this._disposables.dispose();
    }
    /**
     * Compute the fully resolved path for a path argument.
     */
    _resolvePath(path) {
        if (this._basePath) {
            path = this._basePath + '.' + path;
        }
        return path;
    }
}
exports.ModelDB = ModelDB;


/***/ }),

/***/ "q9pQ":
/*!*************************************************!*\
  !*** ./node_modules/mdi-react/ChartLineIcon.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var ChartLineIcon = function ChartLineIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M16,11.78L20.24,4.45L21.97,5.45L16.74,14.5L10.23,10.75L5.46,19H22V21H2V3H4V17.54L9.5,8L16,11.78Z' })
  );
};

module.exports = ChartLineIcon;


/***/ }),

/***/ "qHYo":
/*!********************************************************!*\
  !*** ./node_modules/plotly.js/src/plots/attributes.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var fxAttrs = __webpack_require__(/*! ../components/fx/attributes */ "pGKX");

module.exports = {
    type: {
        valType: 'enumerated',
        role: 'info',
        values: [],     // listed dynamically
        dflt: 'scatter',
        editType: 'calc+clearAxisTypes',
        _noTemplating: true // we handle this at a higher level
    },
    visible: {
        valType: 'enumerated',
        values: [true, false, 'legendonly'],
        role: 'info',
        dflt: true,
        editType: 'calc',
        description: [
            'Determines whether or not this trace is visible.',
            'If *legendonly*, the trace is not drawn,',
            'but can appear as a legend item',
            '(provided that the legend itself is visible).'
        ].join(' ')
    },
    showlegend: {
        valType: 'boolean',
        role: 'info',
        dflt: true,
        editType: 'style',
        description: [
            'Determines whether or not an item corresponding to this',
            'trace is shown in the legend.'
        ].join(' ')
    },
    legendgroup: {
        valType: 'string',
        role: 'info',
        dflt: '',
        editType: 'style',
        description: [
            'Sets the legend group for this trace.',
            'Traces part of the same legend group hide/show at the same time',
            'when toggling legend items.'
        ].join(' ')
    },
    opacity: {
        valType: 'number',
        role: 'style',
        min: 0,
        max: 1,
        dflt: 1,
        editType: 'style',
        description: 'Sets the opacity of the trace.'
    },
    name: {
        valType: 'string',
        role: 'info',
        editType: 'style',
        description: [
            'Sets the trace name.',
            'The trace name appear as the legend item and on hover.'
        ].join(' ')
    },
    uid: {
        valType: 'string',
        role: 'info',
        editType: 'plot',
        anim: true,
        description: [
            'Assign an id to this trace,',
            'Use this to provide object constancy between traces during animations',
            'and transitions.'
        ].join(' ')
    },
    ids: {
        valType: 'data_array',
        editType: 'calc',
        anim: true,
        description: [
            'Assigns id labels to each datum.',
            'These ids for object constancy of data points during animation.',
            'Should be an array of strings, not numbers or any other type.'
        ].join(' ')
    },
    customdata: {
        valType: 'data_array',
        editType: 'calc',
        description: [
            'Assigns extra data each datum.',
            'This may be useful when listening to hover, click and selection events.',
            'Note that, *scatter* traces also appends customdata items in the markers',
            'DOM elements'
        ].join(' ')
    },

    // N.B. these cannot be 'data_array' as they do not have the same length as
    // other data arrays and arrayOk attributes in general
    //
    // Maybe add another valType:
    // https://github.com/plotly/plotly.js/issues/1894
    selectedpoints: {
        valType: 'any',
        role: 'info',
        editType: 'calc',
        description: [
            'Array containing integer indices of selected points.',
            'Has an effect only for traces that support selections.',
            'Note that an empty array means an empty selection where the `unselected`',
            'are turned on for all points, whereas, any other non-array values means no',
            'selection all where the `selected` and `unselected` styles have no effect.'
        ].join(' ')
    },

    hoverinfo: {
        valType: 'flaglist',
        role: 'info',
        flags: ['x', 'y', 'z', 'text', 'name'],
        extras: ['all', 'none', 'skip'],
        arrayOk: true,
        dflt: 'all',
        editType: 'none',
        description: [
            'Determines which trace information appear on hover.',
            'If `none` or `skip` are set, no information is displayed upon hovering.',
            'But, if `none` is set, click and hover events are still fired.'
        ].join(' ')
    },
    hoverlabel: fxAttrs.hoverlabel,
    stream: {
        token: {
            valType: 'string',
            noBlank: true,
            strict: true,
            role: 'info',
            editType: 'calc',
            description: [
                'The stream id number links a data trace on a plot with a stream.',
                'See https://plot.ly/settings for more details.'
            ].join(' ')
        },
        maxpoints: {
            valType: 'number',
            min: 0,
            max: 10000,
            dflt: 500,
            role: 'info',
            editType: 'calc',
            description: [
                'Sets the maximum number of points to keep on the plots from an',
                'incoming stream.',
                'If `maxpoints` is set to *50*, only the newest 50 points will',
                'be displayed on the plot.'
            ].join(' ')
        },
        editType: 'calc'
    },
    transforms: {
        _isLinkedToArray: 'transform',
        editType: 'calc',
        description: [
            'An array of operations that manipulate the trace data,',
            'for example filtering or sorting the data arrays.'
        ].join(' ')
    },
    uirevision: {
        valType: 'any',
        role: 'info',
        editType: 'none',
        description: [
            'Controls persistence of some user-driven changes to the trace:',
            '`constraintrange` in `parcoords` traces, as well as some',
            '`editable: true` modifications such as `name` and `colorbar.title`.',
            'Defaults to `layout.uirevision`.',
            'Note that other user-driven trace attribute changes are controlled',
            'by `layout` attributes:',
            '`trace.visible` is controlled by `layout.legend.uirevision`,',
            '`selectedpoints` is controlled by `layout.selectionrevision`,',
            'and `colorbar.(x|y)` (accessible with `config: {editable: true}`)',
            'is controlled by `layout.editrevision`.',
            'Trace changes are tracked by `uid`, which only falls back on trace',
            'index if no `uid` is provided. So if your app can add/remove traces',
            'before the end of the `data` array, such that the same trace has a',
            'different index, you can still preserve user-driven changes if you',
            'give each trace a `uid` that stays with it as it moves.'
        ].join(' ')
    }
};


/***/ }),

/***/ "qJsZ":
/*!************************************************************!*\
  !*** ./node_modules/source-map/lib/source-map-consumer.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* -*- Mode: js; js-indent-level: 2; -*- */
/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var util = __webpack_require__(/*! ./util */ "Cbry");
var binarySearch = __webpack_require__(/*! ./binary-search */ "ntjm");
var ArraySet = __webpack_require__(/*! ./array-set */ "KavO").ArraySet;
var base64VLQ = __webpack_require__(/*! ./base64-vlq */ "Vywy");
var quickSort = __webpack_require__(/*! ./quick-sort */ "amaH").quickSort;

function SourceMapConsumer(aSourceMap, aSourceMapURL) {
  var sourceMap = aSourceMap;
  if (typeof aSourceMap === 'string') {
    sourceMap = util.parseSourceMapInput(aSourceMap);
  }

  return sourceMap.sections != null
    ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
    : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
}

SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
}

/**
 * The version of the source mapping spec that we are consuming.
 */
SourceMapConsumer.prototype._version = 3;

// `__generatedMappings` and `__originalMappings` are arrays that hold the
// parsed mapping coordinates from the source map's "mappings" attribute. They
// are lazily instantiated, accessed via the `_generatedMappings` and
// `_originalMappings` getters respectively, and we only parse the mappings
// and create these arrays once queried for a source location. We jump through
// these hoops because there can be many thousands of mappings, and parsing
// them is expensive, so we only want to do it if we must.
//
// Each object in the arrays is of the form:
//
//     {
//       generatedLine: The line number in the generated code,
//       generatedColumn: The column number in the generated code,
//       source: The path to the original source file that generated this
//               chunk of code,
//       originalLine: The line number in the original source that
//                     corresponds to this chunk of generated code,
//       originalColumn: The column number in the original source that
//                       corresponds to this chunk of generated code,
//       name: The name of the original symbol which generated this chunk of
//             code.
//     }
//
// All properties except for `generatedLine` and `generatedColumn` can be
// `null`.
//
// `_generatedMappings` is ordered by the generated positions.
//
// `_originalMappings` is ordered by the original positions.

SourceMapConsumer.prototype.__generatedMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  configurable: true,
  enumerable: true,
  get: function () {
    if (!this.__generatedMappings) {
      this._parseMappings(this._mappings, this.sourceRoot);
    }

    return this.__generatedMappings;
  }
});

SourceMapConsumer.prototype.__originalMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  configurable: true,
  enumerable: true,
  get: function () {
    if (!this.__originalMappings) {
      this._parseMappings(this._mappings, this.sourceRoot);
    }

    return this.__originalMappings;
  }
});

SourceMapConsumer.prototype._charIsMappingSeparator =
  function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
    var c = aStr.charAt(index);
    return c === ";" || c === ",";
  };

/**
 * Parse the mappings in a string in to a data structure which we can easily
 * query (the ordered arrays in the `this.__generatedMappings` and
 * `this.__originalMappings` properties).
 */
SourceMapConsumer.prototype._parseMappings =
  function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
    throw new Error("Subclasses must implement _parseMappings");
  };

SourceMapConsumer.GENERATED_ORDER = 1;
SourceMapConsumer.ORIGINAL_ORDER = 2;

SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
SourceMapConsumer.LEAST_UPPER_BOUND = 2;

/**
 * Iterate over each mapping between an original source/line/column and a
 * generated line/column in this source map.
 *
 * @param Function aCallback
 *        The function that is called with each mapping.
 * @param Object aContext
 *        Optional. If specified, this object will be the value of `this` every
 *        time that `aCallback` is called.
 * @param aOrder
 *        Either `SourceMapConsumer.GENERATED_ORDER` or
 *        `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
 *        iterate over the mappings sorted by the generated file's line/column
 *        order or the original's source/line/column order, respectively. Defaults to
 *        `SourceMapConsumer.GENERATED_ORDER`.
 */
SourceMapConsumer.prototype.eachMapping =
  function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
    var context = aContext || null;
    var order = aOrder || SourceMapConsumer.GENERATED_ORDER;

    var mappings;
    switch (order) {
    case SourceMapConsumer.GENERATED_ORDER:
      mappings = this._generatedMappings;
      break;
    case SourceMapConsumer.ORIGINAL_ORDER:
      mappings = this._originalMappings;
      break;
    default:
      throw new Error("Unknown order of iteration.");
    }

    var sourceRoot = this.sourceRoot;
    mappings.map(function (mapping) {
      var source = mapping.source === null ? null : this._sources.at(mapping.source);
      source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
      return {
        source: source,
        generatedLine: mapping.generatedLine,
        generatedColumn: mapping.generatedColumn,
        originalLine: mapping.originalLine,
        originalColumn: mapping.originalColumn,
        name: mapping.name === null ? null : this._names.at(mapping.name)
      };
    }, this).forEach(aCallback, context);
  };

/**
 * Returns all generated line and column information for the original source,
 * line, and column provided. If no column is provided, returns all mappings
 * corresponding to a either the line we are searching for or the next
 * closest line that has any mappings. Otherwise, returns all mappings
 * corresponding to the given line and either the column we are searching for
 * or the next closest column that has any offsets.
 *
 * The only argument is an object with the following properties:
 *
 *   - source: The filename of the original source.
 *   - line: The line number in the original source.  The line number is 1-based.
 *   - column: Optional. the column number in the original source.
 *    The column number is 0-based.
 *
 * and an array of objects is returned, each with the following properties:
 *
 *   - line: The line number in the generated source, or null.  The
 *    line number is 1-based.
 *   - column: The column number in the generated source, or null.
 *    The column number is 0-based.
 */
SourceMapConsumer.prototype.allGeneratedPositionsFor =
  function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
    var line = util.getArg(aArgs, 'line');

    // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
    // returns the index of the closest mapping less than the needle. By
    // setting needle.originalColumn to 0, we thus find the last mapping for
    // the given line, provided such a mapping exists.
    var needle = {
      source: util.getArg(aArgs, 'source'),
      originalLine: line,
      originalColumn: util.getArg(aArgs, 'column', 0)
    };

    needle.source = this._findSourceIndex(needle.source);
    if (needle.source < 0) {
      return [];
    }

    var mappings = [];

    var index = this._findMapping(needle,
                                  this._originalMappings,
                                  "originalLine",
                                  "originalColumn",
                                  util.compareByOriginalPositions,
                                  binarySearch.LEAST_UPPER_BOUND);
    if (index >= 0) {
      var mapping = this._originalMappings[index];

      if (aArgs.column === undefined) {
        var originalLine = mapping.originalLine;

        // Iterate until either we run out of mappings, or we run into
        // a mapping for a different line than the one we found. Since
        // mappings are sorted, this is guaranteed to find all mappings for
        // the line we found.
        while (mapping && mapping.originalLine === originalLine) {
          mappings.push({
            line: util.getArg(mapping, 'generatedLine', null),
            column: util.getArg(mapping, 'generatedColumn', null),
            lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
          });

          mapping = this._originalMappings[++index];
        }
      } else {
        var originalColumn = mapping.originalColumn;

        // Iterate until either we run out of mappings, or we run into
        // a mapping for a different line than the one we were searching for.
        // Since mappings are sorted, this is guaranteed to find all mappings for
        // the line we are searching for.
        while (mapping &&
               mapping.originalLine === line &&
               mapping.originalColumn == originalColumn) {
          mappings.push({
            line: util.getArg(mapping, 'generatedLine', null),
            column: util.getArg(mapping, 'generatedColumn', null),
            lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
          });

          mapping = this._originalMappings[++index];
        }
      }
    }

    return mappings;
  };

exports.SourceMapConsumer = SourceMapConsumer;

/**
 * A BasicSourceMapConsumer instance represents a parsed source map which we can
 * query for information about the original file positions by giving it a file
 * position in the generated source.
 *
 * The first parameter is the raw source map (either as a JSON string, or
 * already parsed to an object). According to the spec, source maps have the
 * following attributes:
 *
 *   - version: Which version of the source map spec this map is following.
 *   - sources: An array of URLs to the original source files.
 *   - names: An array of identifiers which can be referrenced by individual mappings.
 *   - sourceRoot: Optional. The URL root from which all sources are relative.
 *   - sourcesContent: Optional. An array of contents of the original source files.
 *   - mappings: A string of base64 VLQs which contain the actual mappings.
 *   - file: Optional. The generated file this source map is associated with.
 *
 * Here is an example source map, taken from the source map spec[0]:
 *
 *     {
 *       version : 3,
 *       file: "out.js",
 *       sourceRoot : "",
 *       sources: ["foo.js", "bar.js"],
 *       names: ["src", "maps", "are", "fun"],
 *       mappings: "AA,AB;;ABCDE;"
 *     }
 *
 * The second parameter, if given, is a string whose value is the URL
 * at which the source map was found.  This URL is used to compute the
 * sources array.
 *
 * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
 */
function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  var sourceMap = aSourceMap;
  if (typeof aSourceMap === 'string') {
    sourceMap = util.parseSourceMapInput(aSourceMap);
  }

  var version = util.getArg(sourceMap, 'version');
  var sources = util.getArg(sourceMap, 'sources');
  // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  // requires the array) to play nice here.
  var names = util.getArg(sourceMap, 'names', []);
  var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  var mappings = util.getArg(sourceMap, 'mappings');
  var file = util.getArg(sourceMap, 'file', null);

  // Once again, Sass deviates from the spec and supplies the version as a
  // string rather than a number, so we use loose equality checking here.
  if (version != this._version) {
    throw new Error('Unsupported version: ' + version);
  }

  if (sourceRoot) {
    sourceRoot = util.normalize(sourceRoot);
  }

  sources = sources
    .map(String)
    // Some source maps produce relative source paths like "./foo.js" instead of
    // "foo.js".  Normalize these first so that future comparisons will succeed.
    // See bugzil.la/1090768.
    .map(util.normalize)
    // Always ensure that absolute sources are internally stored relative to
    // the source root, if the source root is absolute. Not doing this would
    // be particularly problematic when the source root is a prefix of the
    // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
    .map(function (source) {
      return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
        ? util.relative(sourceRoot, source)
        : source;
    });

  // Pass `true` below to allow duplicate names and sources. While source maps
  // are intended to be compressed and deduplicated, the TypeScript compiler
  // sometimes generates source maps with duplicates in them. See Github issue
  // #72 and bugzil.la/889492.
  this._names = ArraySet.fromArray(names.map(String), true);
  this._sources = ArraySet.fromArray(sources, true);

  this._absoluteSources = this._sources.toArray().map(function (s) {
    return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
  });

  this.sourceRoot = sourceRoot;
  this.sourcesContent = sourcesContent;
  this._mappings = mappings;
  this._sourceMapURL = aSourceMapURL;
  this.file = file;
}

BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;

/**
 * Utility function to find the index of a source.  Returns -1 if not
 * found.
 */
BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  var relativeSource = aSource;
  if (this.sourceRoot != null) {
    relativeSource = util.relative(this.sourceRoot, relativeSource);
  }

  if (this._sources.has(relativeSource)) {
    return this._sources.indexOf(relativeSource);
  }

  // Maybe aSource is an absolute URL as returned by |sources|.  In
  // this case we can't simply undo the transform.
  var i;
  for (i = 0; i < this._absoluteSources.length; ++i) {
    if (this._absoluteSources[i] == aSource) {
      return i;
    }
  }

  return -1;
};

/**
 * Create a BasicSourceMapConsumer from a SourceMapGenerator.
 *
 * @param SourceMapGenerator aSourceMap
 *        The source map that will be consumed.
 * @param String aSourceMapURL
 *        The URL at which the source map can be found (optional)
 * @returns BasicSourceMapConsumer
 */
BasicSourceMapConsumer.fromSourceMap =
  function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
    var smc = Object.create(BasicSourceMapConsumer.prototype);

    var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
    var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
    smc.sourceRoot = aSourceMap._sourceRoot;
    smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
                                                            smc.sourceRoot);
    smc.file = aSourceMap._file;
    smc._sourceMapURL = aSourceMapURL;
    smc._absoluteSources = smc._sources.toArray().map(function (s) {
      return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
    });

    // Because we are modifying the entries (by converting string sources and
    // names to indices into the sources and names ArraySets), we have to make
    // a copy of the entry or else bad things happen. Shared mutable state
    // strikes again! See github issue #191.

    var generatedMappings = aSourceMap._mappings.toArray().slice();
    var destGeneratedMappings = smc.__generatedMappings = [];
    var destOriginalMappings = smc.__originalMappings = [];

    for (var i = 0, length = generatedMappings.length; i < length; i++) {
      var srcMapping = generatedMappings[i];
      var destMapping = new Mapping;
      destMapping.generatedLine = srcMapping.generatedLine;
      destMapping.generatedColumn = srcMapping.generatedColumn;

      if (srcMapping.source) {
        destMapping.source = sources.indexOf(srcMapping.source);
        destMapping.originalLine = srcMapping.originalLine;
        destMapping.originalColumn = srcMapping.originalColumn;

        if (srcMapping.name) {
          destMapping.name = names.indexOf(srcMapping.name);
        }

        destOriginalMappings.push(destMapping);
      }

      destGeneratedMappings.push(destMapping);
    }

    quickSort(smc.__originalMappings, util.compareByOriginalPositions);

    return smc;
  };

/**
 * The version of the source mapping spec that we are consuming.
 */
BasicSourceMapConsumer.prototype._version = 3;

/**
 * The list of original sources.
 */
Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  get: function () {
    return this._absoluteSources.slice();
  }
});

/**
 * Provide the JIT with a nice shape / hidden class.
 */
function Mapping() {
  this.generatedLine = 0;
  this.generatedColumn = 0;
  this.source = null;
  this.originalLine = null;
  this.originalColumn = null;
  this.name = null;
}

/**
 * Parse the mappings in a string in to a data structure which we can easily
 * query (the ordered arrays in the `this.__generatedMappings` and
 * `this.__originalMappings` properties).
 */
BasicSourceMapConsumer.prototype._parseMappings =
  function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
    var generatedLine = 1;
    var previousGeneratedColumn = 0;
    var previousOriginalLine = 0;
    var previousOriginalColumn = 0;
    var previousSource = 0;
    var previousName = 0;
    var length = aStr.length;
    var index = 0;
    var cachedSegments = {};
    var temp = {};
    var originalMappings = [];
    var generatedMappings = [];
    var mapping, str, segment, end, value;

    while (index < length) {
      if (aStr.charAt(index) === ';') {
        generatedLine++;
        index++;
        previousGeneratedColumn = 0;
      }
      else if (aStr.charAt(index) === ',') {
        index++;
      }
      else {
        mapping = new Mapping();
        mapping.generatedLine = generatedLine;

        // Because each offset is encoded relative to the previous one,
        // many segments often have the same encoding. We can exploit this
        // fact by caching the parsed variable length fields of each segment,
        // allowing us to avoid a second parse if we encounter the same
        // segment again.
        for (end = index; end < length; end++) {
          if (this._charIsMappingSeparator(aStr, end)) {
            break;
          }
        }
        str = aStr.slice(index, end);

        segment = cachedSegments[str];
        if (segment) {
          index += str.length;
        } else {
          segment = [];
          while (index < end) {
            base64VLQ.decode(aStr, index, temp);
            value = temp.value;
            index = temp.rest;
            segment.push(value);
          }

          if (segment.length === 2) {
            throw new Error('Found a source, but no line and column');
          }

          if (segment.length === 3) {
            throw new Error('Found a source and line, but no column');
          }

          cachedSegments[str] = segment;
        }

        // Generated column.
        mapping.generatedColumn = previousGeneratedColumn + segment[0];
        previousGeneratedColumn = mapping.generatedColumn;

        if (segment.length > 1) {
          // Original source.
          mapping.source = previousSource + segment[1];
          previousSource += segment[1];

          // Original line.
          mapping.originalLine = previousOriginalLine + segment[2];
          previousOriginalLine = mapping.originalLine;
          // Lines are stored 0-based
          mapping.originalLine += 1;

          // Original column.
          mapping.originalColumn = previousOriginalColumn + segment[3];
          previousOriginalColumn = mapping.originalColumn;

          if (segment.length > 4) {
            // Original name.
            mapping.name = previousName + segment[4];
            previousName += segment[4];
          }
        }

        generatedMappings.push(mapping);
        if (typeof mapping.originalLine === 'number') {
          originalMappings.push(mapping);
        }
      }
    }

    quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
    this.__generatedMappings = generatedMappings;

    quickSort(originalMappings, util.compareByOriginalPositions);
    this.__originalMappings = originalMappings;
  };

/**
 * Find the mapping that best matches the hypothetical "needle" mapping that
 * we are searching for in the given "haystack" of mappings.
 */
BasicSourceMapConsumer.prototype._findMapping =
  function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
                                         aColumnName, aComparator, aBias) {
    // To return the position we are searching for, we must first find the
    // mapping for the given position and then return the opposite position it
    // points to. Because the mappings are sorted, we can use binary search to
    // find the best mapping.

    if (aNeedle[aLineName] <= 0) {
      throw new TypeError('Line must be greater than or equal to 1, got '
                          + aNeedle[aLineName]);
    }
    if (aNeedle[aColumnName] < 0) {
      throw new TypeError('Column must be greater than or equal to 0, got '
                          + aNeedle[aColumnName]);
    }

    return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  };

/**
 * Compute the last column for each generated mapping. The last column is
 * inclusive.
 */
BasicSourceMapConsumer.prototype.computeColumnSpans =
  function SourceMapConsumer_computeColumnSpans() {
    for (var index = 0; index < this._generatedMappings.length; ++index) {
      var mapping = this._generatedMappings[index];

      // Mappings do not contain a field for the last generated columnt. We
      // can come up with an optimistic estimate, however, by assuming that
      // mappings are contiguous (i.e. given two consecutive mappings, the
      // first mapping ends where the second one starts).
      if (index + 1 < this._generatedMappings.length) {
        var nextMapping = this._generatedMappings[index + 1];

        if (mapping.generatedLine === nextMapping.generatedLine) {
          mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
          continue;
        }
      }

      // The last mapping for each line spans the entire line.
      mapping.lastGeneratedColumn = Infinity;
    }
  };

/**
 * Returns the original source, line, and column information for the generated
 * source's line and column positions provided. The only argument is an object
 * with the following properties:
 *
 *   - line: The line number in the generated source.  The line number
 *     is 1-based.
 *   - column: The column number in the generated source.  The column
 *     number is 0-based.
 *   - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
 *     'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
 *     closest element that is smaller than or greater than the one we are
 *     searching for, respectively, if the exact element cannot be found.
 *     Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
 *
 * and an object is returned with the following properties:
 *
 *   - source: The original source file, or null.
 *   - line: The line number in the original source, or null.  The
 *     line number is 1-based.
 *   - column: The column number in the original source, or null.  The
 *     column number is 0-based.
 *   - name: The original identifier, or null.
 */
BasicSourceMapConsumer.prototype.originalPositionFor =
  function SourceMapConsumer_originalPositionFor(aArgs) {
    var needle = {
      generatedLine: util.getArg(aArgs, 'line'),
      generatedColumn: util.getArg(aArgs, 'column')
    };

    var index = this._findMapping(
      needle,
      this._generatedMappings,
      "generatedLine",
      "generatedColumn",
      util.compareByGeneratedPositionsDeflated,
      util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
    );

    if (index >= 0) {
      var mapping = this._generatedMappings[index];

      if (mapping.generatedLine === needle.generatedLine) {
        var source = util.getArg(mapping, 'source', null);
        if (source !== null) {
          source = this._sources.at(source);
          source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
        }
        var name = util.getArg(mapping, 'name', null);
        if (name !== null) {
          name = this._names.at(name);
        }
        return {
          source: source,
          line: util.getArg(mapping, 'originalLine', null),
          column: util.getArg(mapping, 'originalColumn', null),
          name: name
        };
      }
    }

    return {
      source: null,
      line: null,
      column: null,
      name: null
    };
  };

/**
 * Return true if we have the source content for every source in the source
 * map, false otherwise.
 */
BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  function BasicSourceMapConsumer_hasContentsOfAllSources() {
    if (!this.sourcesContent) {
      return false;
    }
    return this.sourcesContent.length >= this._sources.size() &&
      !this.sourcesContent.some(function (sc) { return sc == null; });
  };

/**
 * Returns the original source content. The only argument is the url of the
 * original source file. Returns null if no original source content is
 * available.
 */
BasicSourceMapConsumer.prototype.sourceContentFor =
  function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
    if (!this.sourcesContent) {
      return null;
    }

    var index = this._findSourceIndex(aSource);
    if (index >= 0) {
      return this.sourcesContent[index];
    }

    var relativeSource = aSource;
    if (this.sourceRoot != null) {
      relativeSource = util.relative(this.sourceRoot, relativeSource);
    }

    var url;
    if (this.sourceRoot != null
        && (url = util.urlParse(this.sourceRoot))) {
      // XXX: file:// URIs and absolute paths lead to unexpected behavior for
      // many users. We can help them out when they expect file:// URIs to
      // behave like it would if they were running a local HTTP server. See
      // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
      var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
      if (url.scheme == "file"
          && this._sources.has(fileUriAbsPath)) {
        return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
      }

      if ((!url.path || url.path == "/")
          && this._sources.has("/" + relativeSource)) {
        return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
      }
    }

    // This function is used recursively from
    // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
    // don't want to throw if we can't find the source - we just want to
    // return null, so we provide a flag to exit gracefully.
    if (nullOnMissing) {
      return null;
    }
    else {
      throw new Error('"' + relativeSource + '" is not in the SourceMap.');
    }
  };

/**
 * Returns the generated line and column information for the original source,
 * line, and column positions provided. The only argument is an object with
 * the following properties:
 *
 *   - source: The filename of the original source.
 *   - line: The line number in the original source.  The line number
 *     is 1-based.
 *   - column: The column number in the original source.  The column
 *     number is 0-based.
 *   - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
 *     'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
 *     closest element that is smaller than or greater than the one we are
 *     searching for, respectively, if the exact element cannot be found.
 *     Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
 *
 * and an object is returned with the following properties:
 *
 *   - line: The line number in the generated source, or null.  The
 *     line number is 1-based.
 *   - column: The column number in the generated source, or null.
 *     The column number is 0-based.
 */
BasicSourceMapConsumer.prototype.generatedPositionFor =
  function SourceMapConsumer_generatedPositionFor(aArgs) {
    var source = util.getArg(aArgs, 'source');
    source = this._findSourceIndex(source);
    if (source < 0) {
      return {
        line: null,
        column: null,
        lastColumn: null
      };
    }

    var needle = {
      source: source,
      originalLine: util.getArg(aArgs, 'line'),
      originalColumn: util.getArg(aArgs, 'column')
    };

    var index = this._findMapping(
      needle,
      this._originalMappings,
      "originalLine",
      "originalColumn",
      util.compareByOriginalPositions,
      util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
    );

    if (index >= 0) {
      var mapping = this._originalMappings[index];

      if (mapping.source === needle.source) {
        return {
          line: util.getArg(mapping, 'generatedLine', null),
          column: util.getArg(mapping, 'generatedColumn', null),
          lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
        };
      }
    }

    return {
      line: null,
      column: null,
      lastColumn: null
    };
  };

exports.BasicSourceMapConsumer = BasicSourceMapConsumer;

/**
 * An IndexedSourceMapConsumer instance represents a parsed source map which
 * we can query for information. It differs from BasicSourceMapConsumer in
 * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
 * input.
 *
 * The first parameter is a raw source map (either as a JSON string, or already
 * parsed to an object). According to the spec for indexed source maps, they
 * have the following attributes:
 *
 *   - version: Which version of the source map spec this map is following.
 *   - file: Optional. The generated file this source map is associated with.
 *   - sections: A list of section definitions.
 *
 * Each value under the "sections" field has two fields:
 *   - offset: The offset into the original specified at which this section
 *       begins to apply, defined as an object with a "line" and "column"
 *       field.
 *   - map: A source map definition. This source map could also be indexed,
 *       but doesn't have to be.
 *
 * Instead of the "map" field, it's also possible to have a "url" field
 * specifying a URL to retrieve a source map from, but that's currently
 * unsupported.
 *
 * Here's an example source map, taken from the source map spec[0], but
 * modified to omit a section which uses the "url" field.
 *
 *  {
 *    version : 3,
 *    file: "app.js",
 *    sections: [{
 *      offset: {line:100, column:10},
 *      map: {
 *        version : 3,
 *        file: "section.js",
 *        sources: ["foo.js", "bar.js"],
 *        names: ["src", "maps", "are", "fun"],
 *        mappings: "AAAA,E;;ABCDE;"
 *      }
 *    }],
 *  }
 *
 * The second parameter, if given, is a string whose value is the URL
 * at which the source map was found.  This URL is used to compute the
 * sources array.
 *
 * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
 */
function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  var sourceMap = aSourceMap;
  if (typeof aSourceMap === 'string') {
    sourceMap = util.parseSourceMapInput(aSourceMap);
  }

  var version = util.getArg(sourceMap, 'version');
  var sections = util.getArg(sourceMap, 'sections');

  if (version != this._version) {
    throw new Error('Unsupported version: ' + version);
  }

  this._sources = new ArraySet();
  this._names = new ArraySet();

  var lastOffset = {
    line: -1,
    column: 0
  };
  this._sections = sections.map(function (s) {
    if (s.url) {
      // The url field will require support for asynchronicity.
      // See https://github.com/mozilla/source-map/issues/16
      throw new Error('Support for url field in sections not implemented.');
    }
    var offset = util.getArg(s, 'offset');
    var offsetLine = util.getArg(offset, 'line');
    var offsetColumn = util.getArg(offset, 'column');

    if (offsetLine < lastOffset.line ||
        (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
      throw new Error('Section offsets must be ordered and non-overlapping.');
    }
    lastOffset = offset;

    return {
      generatedOffset: {
        // The offset fields are 0-based, but we use 1-based indices when
        // encoding/decoding from VLQ.
        generatedLine: offsetLine + 1,
        generatedColumn: offsetColumn + 1
      },
      consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
    }
  });
}

IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;

/**
 * The version of the source mapping spec that we are consuming.
 */
IndexedSourceMapConsumer.prototype._version = 3;

/**
 * The list of original sources.
 */
Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  get: function () {
    var sources = [];
    for (var i = 0; i < this._sections.length; i++) {
      for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
        sources.push(this._sections[i].consumer.sources[j]);
      }
    }
    return sources;
  }
});

/**
 * Returns the original source, line, and column information for the generated
 * source's line and column positions provided. The only argument is an object
 * with the following properties:
 *
 *   - line: The line number in the generated source.  The line number
 *     is 1-based.
 *   - column: The column number in the generated source.  The column
 *     number is 0-based.
 *
 * and an object is returned with the following properties:
 *
 *   - source: The original source file, or null.
 *   - line: The line number in the original source, or null.  The
 *     line number is 1-based.
 *   - column: The column number in the original source, or null.  The
 *     column number is 0-based.
 *   - name: The original identifier, or null.
 */
IndexedSourceMapConsumer.prototype.originalPositionFor =
  function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
    var needle = {
      generatedLine: util.getArg(aArgs, 'line'),
      generatedColumn: util.getArg(aArgs, 'column')
    };

    // Find the section containing the generated position we're trying to map
    // to an original position.
    var sectionIndex = binarySearch.search(needle, this._sections,
      function(needle, section) {
        var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
        if (cmp) {
          return cmp;
        }

        return (needle.generatedColumn -
                section.generatedOffset.generatedColumn);
      });
    var section = this._sections[sectionIndex];

    if (!section) {
      return {
        source: null,
        line: null,
        column: null,
        name: null
      };
    }

    return section.consumer.originalPositionFor({
      line: needle.generatedLine -
        (section.generatedOffset.generatedLine - 1),
      column: needle.generatedColumn -
        (section.generatedOffset.generatedLine === needle.generatedLine
         ? section.generatedOffset.generatedColumn - 1
         : 0),
      bias: aArgs.bias
    });
  };

/**
 * Return true if we have the source content for every source in the source
 * map, false otherwise.
 */
IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  function IndexedSourceMapConsumer_hasContentsOfAllSources() {
    return this._sections.every(function (s) {
      return s.consumer.hasContentsOfAllSources();
    });
  };

/**
 * Returns the original source content. The only argument is the url of the
 * original source file. Returns null if no original source content is
 * available.
 */
IndexedSourceMapConsumer.prototype.sourceContentFor =
  function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
    for (var i = 0; i < this._sections.length; i++) {
      var section = this._sections[i];

      var content = section.consumer.sourceContentFor(aSource, true);
      if (content) {
        return content;
      }
    }
    if (nullOnMissing) {
      return null;
    }
    else {
      throw new Error('"' + aSource + '" is not in the SourceMap.');
    }
  };

/**
 * Returns the generated line and column information for the original source,
 * line, and column positions provided. The only argument is an object with
 * the following properties:
 *
 *   - source: The filename of the original source.
 *   - line: The line number in the original source.  The line number
 *     is 1-based.
 *   - column: The column number in the original source.  The column
 *     number is 0-based.
 *
 * and an object is returned with the following properties:
 *
 *   - line: The line number in the generated source, or null.  The
 *     line number is 1-based. 
 *   - column: The column number in the generated source, or null.
 *     The column number is 0-based.
 */
IndexedSourceMapConsumer.prototype.generatedPositionFor =
  function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
    for (var i = 0; i < this._sections.length; i++) {
      var section = this._sections[i];

      // Only consider this section if the requested source is in the list of
      // sources of the consumer.
      if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
        continue;
      }
      var generatedPosition = section.consumer.generatedPositionFor(aArgs);
      if (generatedPosition) {
        var ret = {
          line: generatedPosition.line +
            (section.generatedOffset.generatedLine - 1),
          column: generatedPosition.column +
            (section.generatedOffset.generatedLine === generatedPosition.line
             ? section.generatedOffset.generatedColumn - 1
             : 0)
        };
        return ret;
      }
    }

    return {
      line: null,
      column: null
    };
  };

/**
 * Parse the mappings in a string in to a data structure which we can easily
 * query (the ordered arrays in the `this.__generatedMappings` and
 * `this.__originalMappings` properties).
 */
IndexedSourceMapConsumer.prototype._parseMappings =
  function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
    this.__generatedMappings = [];
    this.__originalMappings = [];
    for (var i = 0; i < this._sections.length; i++) {
      var section = this._sections[i];
      var sectionMappings = section.consumer._generatedMappings;
      for (var j = 0; j < sectionMappings.length; j++) {
        var mapping = sectionMappings[j];

        var source = section.consumer._sources.at(mapping.source);
        source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
        this._sources.add(source);
        source = this._sources.indexOf(source);

        var name = null;
        if (mapping.name) {
          name = section.consumer._names.at(mapping.name);
          this._names.add(name);
          name = this._names.indexOf(name);
        }

        // The mappings coming from the consumer for the section have
        // generated positions relative to the start of the section, so we
        // need to offset them to be relative to the start of the concatenated
        // generated file.
        var adjustedMapping = {
          source: source,
          generatedLine: mapping.generatedLine +
            (section.generatedOffset.generatedLine - 1),
          generatedColumn: mapping.generatedColumn +
            (section.generatedOffset.generatedLine === mapping.generatedLine
            ? section.generatedOffset.generatedColumn - 1
            : 0),
          originalLine: mapping.originalLine,
          originalColumn: mapping.originalColumn,
          name: name
        };

        this.__generatedMappings.push(adjustedMapping);
        if (typeof adjustedMapping.originalLine === 'number') {
          this.__originalMappings.push(adjustedMapping);
        }
      }
    }

    quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
    quickSort(this.__originalMappings, util.compareByOriginalPositions);
  };

exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;


/***/ }),

/***/ "qPUD":
/*!***********************************************************!*\
  !*** ./node_modules/react-is/cjs/react-is.development.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/** @license React v16.8.5
 * react-is.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */





if (true) {
  (function() {
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var hasSymbol = typeof Symbol === 'function' && Symbol.for;

var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace;
var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;
var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;

function isValidElementType(type) {
  return typeof type === 'string' || typeof type === 'function' ||
  // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
  type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE);
}

/**
 * Forked from fbjs/warning:
 * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
 *
 * Only change is we use console.warn instead of console.error,
 * and do nothing when 'console' is not supported.
 * This really simplifies the code.
 * ---
 * Similar to invariant but only logs a warning if the condition is not met.
 * This can be used to log issues in development environments in critical
 * paths. Removing the logging code for production environments will keep the
 * same logic and follow the same code paths.
 */

var lowPriorityWarning = function () {};

{
  var printWarning = function (format) {
    for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      args[_key - 1] = arguments[_key];
    }

    var argIndex = 0;
    var message = 'Warning: ' + format.replace(/%s/g, function () {
      return args[argIndex++];
    });
    if (typeof console !== 'undefined') {
      console.warn(message);
    }
    try {
      // --- Welcome to debugging React ---
      // This error was thrown as a convenience so that you can use this stack
      // to find the callsite that caused this warning to fire.
      throw new Error(message);
    } catch (x) {}
  };

  lowPriorityWarning = function (condition, format) {
    if (format === undefined) {
      throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument');
    }
    if (!condition) {
      for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
        args[_key2 - 2] = arguments[_key2];
      }

      printWarning.apply(undefined, [format].concat(args));
    }
  };
}

var lowPriorityWarning$1 = lowPriorityWarning;

function typeOf(object) {
  if (typeof object === 'object' && object !== null) {
    var $$typeof = object.$$typeof;
    switch ($$typeof) {
      case REACT_ELEMENT_TYPE:
        var type = object.type;

        switch (type) {
          case REACT_ASYNC_MODE_TYPE:
          case REACT_CONCURRENT_MODE_TYPE:
          case REACT_FRAGMENT_TYPE:
          case REACT_PROFILER_TYPE:
          case REACT_STRICT_MODE_TYPE:
          case REACT_SUSPENSE_TYPE:
            return type;
          default:
            var $$typeofType = type && type.$$typeof;

            switch ($$typeofType) {
              case REACT_CONTEXT_TYPE:
              case REACT_FORWARD_REF_TYPE:
              case REACT_PROVIDER_TYPE:
                return $$typeofType;
              default:
                return $$typeof;
            }
        }
      case REACT_LAZY_TYPE:
      case REACT_MEMO_TYPE:
      case REACT_PORTAL_TYPE:
        return $$typeof;
    }
  }

  return undefined;
}

// AsyncMode is deprecated along with isAsyncMode
var AsyncMode = REACT_ASYNC_MODE_TYPE;
var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
var ContextConsumer = REACT_CONTEXT_TYPE;
var ContextProvider = REACT_PROVIDER_TYPE;
var Element = REACT_ELEMENT_TYPE;
var ForwardRef = REACT_FORWARD_REF_TYPE;
var Fragment = REACT_FRAGMENT_TYPE;
var Lazy = REACT_LAZY_TYPE;
var Memo = REACT_MEMO_TYPE;
var Portal = REACT_PORTAL_TYPE;
var Profiler = REACT_PROFILER_TYPE;
var StrictMode = REACT_STRICT_MODE_TYPE;
var Suspense = REACT_SUSPENSE_TYPE;

var hasWarnedAboutDeprecatedIsAsyncMode = false;

// AsyncMode should be deprecated
function isAsyncMode(object) {
  {
    if (!hasWarnedAboutDeprecatedIsAsyncMode) {
      hasWarnedAboutDeprecatedIsAsyncMode = true;
      lowPriorityWarning$1(false, 'The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.');
    }
  }
  return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
}
function isConcurrentMode(object) {
  return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
}
function isContextConsumer(object) {
  return typeOf(object) === REACT_CONTEXT_TYPE;
}
function isContextProvider(object) {
  return typeOf(object) === REACT_PROVIDER_TYPE;
}
function isElement(object) {
  return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
function isForwardRef(object) {
  return typeOf(object) === REACT_FORWARD_REF_TYPE;
}
function isFragment(object) {
  return typeOf(object) === REACT_FRAGMENT_TYPE;
}
function isLazy(object) {
  return typeOf(object) === REACT_LAZY_TYPE;
}
function isMemo(object) {
  return typeOf(object) === REACT_MEMO_TYPE;
}
function isPortal(object) {
  return typeOf(object) === REACT_PORTAL_TYPE;
}
function isProfiler(object) {
  return typeOf(object) === REACT_PROFILER_TYPE;
}
function isStrictMode(object) {
  return typeOf(object) === REACT_STRICT_MODE_TYPE;
}
function isSuspense(object) {
  return typeOf(object) === REACT_SUSPENSE_TYPE;
}

exports.typeOf = typeOf;
exports.AsyncMode = AsyncMode;
exports.ConcurrentMode = ConcurrentMode;
exports.ContextConsumer = ContextConsumer;
exports.ContextProvider = ContextProvider;
exports.Element = Element;
exports.ForwardRef = ForwardRef;
exports.Fragment = Fragment;
exports.Lazy = Lazy;
exports.Memo = Memo;
exports.Portal = Portal;
exports.Profiler = Profiler;
exports.StrictMode = StrictMode;
exports.Suspense = Suspense;
exports.isValidElementType = isValidElementType;
exports.isAsyncMode = isAsyncMode;
exports.isConcurrentMode = isConcurrentMode;
exports.isContextConsumer = isContextConsumer;
exports.isContextProvider = isContextProvider;
exports.isElement = isElement;
exports.isForwardRef = isForwardRef;
exports.isFragment = isFragment;
exports.isLazy = isLazy;
exports.isMemo = isMemo;
exports.isPortal = isPortal;
exports.isProfiler = isProfiler;
exports.isStrictMode = isStrictMode;
exports.isSuspense = isSuspense;
  })();
}


/***/ }),

/***/ "qSDV":
/*!*******************************************************!*\
  !*** ./node_modules/@jupyterlab/running/lib/index.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const React = __importStar(__webpack_require__(/*! react */ "q1tI"));
const ReactDOM = __importStar(__webpack_require__(/*! react-dom */ "i8i4"));
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
__webpack_require__(/*! ../style/index.css */ "VjLE");
/**
 * The class name added to a running widget.
 */
const RUNNING_CLASS = 'jp-RunningSessions';
/**
 * The class name added to a running widget header.
 */
const HEADER_CLASS = 'jp-RunningSessions-header';
/**
 * The class name added to the running terminal sessions section.
 */
const SECTION_CLASS = 'jp-RunningSessions-section';
/**
 * The class name added to the running sessions section header.
 */
const SECTION_HEADER_CLASS = 'jp-RunningSessions-sectionHeader';
/**
 * The class name added to a section container.
 */
const CONTAINER_CLASS = 'jp-RunningSessions-sectionContainer';
/**
 * The class name added to the running kernel sessions section list.
 */
const LIST_CLASS = 'jp-RunningSessions-sectionList';
/**
 * The class name added to the running sessions items.
 */
const ITEM_CLASS = 'jp-RunningSessions-item';
/**
 * The class name added to a running session item icon.
 */
const ITEM_ICON_CLASS = 'jp-RunningSessions-itemIcon';
/**
 * The class name added to a running session item label.
 */
const ITEM_LABEL_CLASS = 'jp-RunningSessions-itemLabel';
/**
 * The class name added to a running session item shutdown button.
 */
const SHUTDOWN_BUTTON_CLASS = 'jp-RunningSessions-itemShutdown';
/**
 * The class name added to a notebook icon.
 */
const NOTEBOOK_ICON_CLASS = 'jp-mod-notebook';
/**
 * The class name added to a console icon.
 */
const CONSOLE_ICON_CLASS = 'jp-mod-console';
/**
 * The class name added to a file icon.
 */
const FILE_ICON_CLASS = 'jp-mod-file';
/**
 * The class name added to a terminal icon.
 */
const TERMINAL_ICON_CLASS = 'jp-mod-terminal';
function Item(props) {
    const { model } = props;
    return (React.createElement("li", { className: ITEM_CLASS },
        React.createElement("span", { className: `${ITEM_ICON_CLASS} ${props.iconClass(model)}` }),
        React.createElement("span", { className: ITEM_LABEL_CLASS, title: props.labelTitle ? props.labelTitle(model) : '', onClick: () => props.openRequested.emit(model) }, props.label(model)),
        React.createElement("button", { className: `${SHUTDOWN_BUTTON_CLASS} jp-mod-styled`, onClick: () => props.shutdown(model) }, "SHUTDOWN")));
}
class List extends React.Component {
    constructor(props) {
        super(props);
        this.state = { models: algorithm_1.toArray(props.manager.running()) };
    }
    render() {
        return (React.createElement("ul", { className: LIST_CLASS }, this.state.models.map((m, i) => (React.createElement(Item, Object.assign({ key: i, model: m }, this.props))))));
    }
    componentDidMount() {
        if (this.props.available) {
            this.props.manager.runningChanged.connect((_, models) => this.setState({
                models: models.filter(this.props.filterRunning || (_ => true))
            }));
        }
    }
}
/**
 * The Section component contains the shared look and feel for an interactive list of kernels and sessions.
 *
 * It is specialized for each based on it's props.
 */
function Section(props) {
    function onShutdown() {
        apputils_1.showDialog({
            title: `Shutdown All ${props.name} Sessions?`,
            buttons: [apputils_1.Dialog.cancelButton(), apputils_1.Dialog.warnButton({ label: 'SHUTDOWN' })]
        }).then(result => {
            if (result.button.accept) {
                props.manager.shutdownAll();
            }
        });
    }
    return (React.createElement("div", { className: SECTION_CLASS }, props.available && (React.createElement(React.Fragment, null,
        React.createElement("header", { className: SECTION_HEADER_CLASS },
            React.createElement("h2", null,
                props.name,
                " Sessions"),
            React.createElement(apputils_1.ToolbarButtonComponent, { tooltip: `Shutdown All ${props.name} Sessions…`, iconClassName: "jp-CloseIcon jp-Icon jp-Icon-16", onClick: onShutdown })),
        React.createElement("div", { className: CONTAINER_CLASS },
            React.createElement(List, Object.assign({}, props)))))));
}
function RunningSessionsComponent({ manager, sessionOpenRequested, terminalOpenRequested }) {
    const terminalsAvailable = manager.terminals.isAvailable();
    return (React.createElement(React.Fragment, null,
        React.createElement("div", { className: HEADER_CLASS },
            React.createElement(apputils_1.ToolbarButtonComponent, { tooltip: "Refresh List", iconClassName: "jp-RefreshIcon jp-Icon jp-Icon-16", onClick: () => {
                    if (terminalsAvailable) {
                        manager.terminals.refreshRunning();
                    }
                    manager.sessions.refreshRunning();
                } })),
        React.createElement(Section, { openRequested: terminalOpenRequested, manager: manager.terminals, name: "Terminal", iconClass: () => `${ITEM_ICON_CLASS} ${TERMINAL_ICON_CLASS}`, label: m => `terminals/${m.name}`, available: terminalsAvailable, shutdown: m => manager.terminals.shutdown(m.name) }),
        React.createElement(Section, { openRequested: sessionOpenRequested, manager: manager.sessions, filterRunning: m => !!((m.name || coreutils_1.PathExt.basename(m.path)).indexOf('.') !== -1 || m.name), name: "Kernel", iconClass: m => {
                if ((m.name || coreutils_1.PathExt.basename(m.path)).indexOf('.ipynb') !== -1) {
                    return NOTEBOOK_ICON_CLASS;
                }
                else if (m.type.toLowerCase() === 'console') {
                    return CONSOLE_ICON_CLASS;
                }
                return FILE_ICON_CLASS;
            }, label: m => m.name || coreutils_1.PathExt.basename(m.path), available: true, labelTitle: m => {
                let kernelName = m.kernel.name;
                if (manager.specs) {
                    kernelName = manager.specs.kernelspecs[kernelName].display_name;
                }
                return `Path: ${m.path}\nKernel: ${kernelName}`;
            }, shutdown: m => manager.sessions.shutdown(m.id) })));
}
/**
 * A class that exposes the running terminal and kernel sessions.
 */
class RunningSessions extends widgets_1.Widget {
    /**
     * Construct a new running widget.
     */
    constructor(options) {
        super();
        this._sessionOpenRequested = new signaling_1.Signal(this);
        this._terminalOpenRequested = new signaling_1.Signal(this);
        this.options = options;
        // this can't be in the react element, because then it would be too nested
        this.addClass(RUNNING_CLASS);
    }
    onUpdateRequest(msg) {
        ReactDOM.render(React.createElement(RunningSessionsComponent, { manager: this.options.manager, sessionOpenRequested: this._sessionOpenRequested, terminalOpenRequested: this._terminalOpenRequested }), this.node);
    }
    /* Called after the widget is attached to the DOM
     *
     * Make sure the widget is rendered, even if the model has not changed.
     */
    onAfterAttach(msg) {
        this.update();
    }
    /**
     * A signal emitted when a kernel session open is requested.
     */
    get sessionOpenRequested() {
        return this._sessionOpenRequested;
    }
    /**
     * A signal emitted when a terminal session open is requested.
     */
    get terminalOpenRequested() {
        return this._terminalOpenRequested;
    }
}
exports.RunningSessions = RunningSessions;


/***/ }),

/***/ "qT3F":
/*!*************************************************!*\
  !*** ./node_modules/react-plotly.js/factory.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = plotComponentFactory;

var _react = _interopRequireWildcard(__webpack_require__(/*! react */ "q1tI"));

var _propTypes = _interopRequireDefault(__webpack_require__(/*! prop-types */ "17x9"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

// The naming convention is:
//   - events are attached as `'plotly_' + eventName.toLowerCase()`
//   - react props are `'on' + eventName`
var eventNames = ['AfterExport', 'AfterPlot', 'Animated', 'AnimatingFrame', 'AnimationInterrupted', 'AutoSize', 'BeforeExport', 'ButtonClicked', 'Click', 'ClickAnnotation', 'Deselect', 'DoubleClick', 'Framework', 'Hover', 'LegendClick', 'LegendDoubleClick', 'Relayout', 'Restyle', 'Redraw', 'Selected', 'Selecting', 'SliderChange', 'SliderEnd', 'SliderStart', 'Transitioning', 'TransitionInterrupted', 'Unhover'];
var updateEvents = ['plotly_restyle', 'plotly_redraw', 'plotly_relayout', 'plotly_doubleclick', 'plotly_animated']; // Check if a window is available since SSR (server-side rendering)
// breaks unnecessarily if you try to use it server-side.

var isBrowser = typeof window !== 'undefined';

function plotComponentFactory(Plotly) {
  var PlotlyComponent =
  /*#__PURE__*/
  function (_Component) {
    _inherits(PlotlyComponent, _Component);

    function PlotlyComponent(props) {
      var _this;

      _classCallCheck(this, PlotlyComponent);

      _this = _possibleConstructorReturn(this, _getPrototypeOf(PlotlyComponent).call(this, props));
      _this.p = Promise.resolve();
      _this.resizeHandler = null;
      _this.handlers = {};
      _this.syncWindowResize = _this.syncWindowResize.bind(_assertThisInitialized(_this));
      _this.syncEventHandlers = _this.syncEventHandlers.bind(_assertThisInitialized(_this));
      _this.attachUpdateEvents = _this.attachUpdateEvents.bind(_assertThisInitialized(_this));
      _this.getRef = _this.getRef.bind(_assertThisInitialized(_this));
      _this.handleUpdate = _this.handleUpdate.bind(_assertThisInitialized(_this));
      _this.figureCallback = _this.figureCallback.bind(_assertThisInitialized(_this));
      _this.updatePlotly = _this.updatePlotly.bind(_assertThisInitialized(_this));
      return _this;
    }

    _createClass(PlotlyComponent, [{
      key: "updatePlotly",
      value: function updatePlotly(shouldInvokeResizeHandler, figureCallbackFunction, shouldAttachUpdateEvents) {
        var _this2 = this;

        this.p = this.p.then(function () {
          if (!_this2.el) {
            var error;

            if (_this2.unmounting) {
              error = new Error('Component is unmounting');
              error.reason = 'unmounting';
            } else {
              error = new Error('Missing element reference');
            }

            throw error;
          }

          return Plotly.react(_this2.el, {
            data: _this2.props.data,
            layout: _this2.props.layout,
            config: _this2.props.config,
            frames: _this2.props.frames
          });
        }).then(function () {
          return _this2.syncWindowResize(shouldInvokeResizeHandler);
        }).then(this.syncEventHandlers).then(function () {
          return _this2.figureCallback(figureCallbackFunction);
        }).then(shouldAttachUpdateEvents ? this.attachUpdateEvents : function () {}).catch(function (err) {
          if (err.reason === 'unmounting') {
            return;
          }

          console.error('Error while plotting:', err); // eslint-disable-line no-console

          if (_this2.props.onError) {
            _this2.props.onError(err);
          }
        });
      }
    }, {
      key: "componentDidMount",
      value: function componentDidMount() {
        this.unmounting = false;
        this.updatePlotly(true, this.props.onInitialized, true);
      }
    }, {
      key: "componentDidUpdate",
      value: function componentDidUpdate(prevProps) {
        this.unmounting = false; // frames *always* changes identity so fall back to check length only :(

        var numPrevFrames = prevProps.frames && prevProps.frames.length ? prevProps.frames.length : 0;
        var numNextFrames = this.props.frames && this.props.frames.length ? this.props.frames.length : 0;
        var figureChanged = !(prevProps.layout === this.props.layout && prevProps.data === this.props.data && prevProps.config === this.props.config && numNextFrames === numPrevFrames);
        var revisionDefined = prevProps.revision !== void 0;
        var revisionChanged = prevProps.revision !== this.props.revision;

        if (!figureChanged && (!revisionDefined || revisionDefined && !revisionChanged)) {
          return;
        }

        this.updatePlotly(false, this.props.onUpdate, false);
      }
    }, {
      key: "componentWillUnmount",
      value: function componentWillUnmount() {
        this.unmounting = true;
        this.figureCallback(this.props.onPurge);

        if (this.resizeHandler && isBrowser) {
          window.removeEventListener('resize', this.resizeHandler);
          this.resizeHandler = null;
        }

        this.removeUpdateEvents();
        Plotly.purge(this.el);
      }
    }, {
      key: "attachUpdateEvents",
      value: function attachUpdateEvents() {
        var _this3 = this;

        if (!this.el || !this.el.removeListener) {
          return;
        }

        updateEvents.forEach(function (updateEvent) {
          _this3.el.on(updateEvent, _this3.handleUpdate);
        });
      }
    }, {
      key: "removeUpdateEvents",
      value: function removeUpdateEvents() {
        var _this4 = this;

        if (!this.el || !this.el.removeListener) {
          return;
        }

        updateEvents.forEach(function (updateEvent) {
          _this4.el.removeListener(updateEvent, _this4.handleUpdate);
        });
      }
    }, {
      key: "handleUpdate",
      value: function handleUpdate() {
        this.figureCallback(this.props.onUpdate);
      }
    }, {
      key: "figureCallback",
      value: function figureCallback(callback) {
        if (typeof callback === 'function') {
          var _this$el = this.el,
              data = _this$el.data,
              layout = _this$el.layout;
          var frames = this.el._transitionData ? this.el._transitionData._frames : null;
          var figure = {
            data: data,
            layout: layout,
            frames: frames
          };
          callback(figure, this.el);
        }
      }
    }, {
      key: "syncWindowResize",
      value: function syncWindowResize(invoke) {
        var _this5 = this;

        if (!isBrowser) {
          return;
        }

        if (this.props.useResizeHandler && !this.resizeHandler) {
          this.resizeHandler = function () {
            return Plotly.Plots.resize(_this5.el);
          };

          window.addEventListener('resize', this.resizeHandler);

          if (invoke) {
            this.resizeHandler();
          }
        } else if (!this.props.useResizeHandler && this.resizeHandler) {
          window.removeEventListener('resize', this.resizeHandler);
          this.resizeHandler = null;
        }
      }
    }, {
      key: "getRef",
      value: function getRef(el) {
        this.el = el;

        if (this.props.debug && isBrowser) {
          window.gd = this.el;
        }
      } // Attach and remove event handlers as they're added or removed from props:

    }, {
      key: "syncEventHandlers",
      value: function syncEventHandlers() {
        var _this6 = this;

        eventNames.forEach(function (eventName) {
          var prop = _this6.props['on' + eventName];
          var hasHandler = Boolean(_this6.handlers[eventName]);

          if (prop && !hasHandler) {
            _this6.handlers[eventName] = prop;

            _this6.el.on('plotly_' + eventName.toLowerCase(), _this6.handlers[eventName]);
          } else if (!prop && hasHandler) {
            // Needs to be removed:
            _this6.el.removeListener('plotly_' + eventName.toLowerCase(), _this6.handlers[eventName]);

            delete _this6.handlers[eventName];
          }
        });
      }
    }, {
      key: "render",
      value: function render() {
        return _react.default.createElement("div", {
          id: this.props.divId,
          style: this.props.style,
          ref: this.getRef,
          className: this.props.className
        });
      }
    }]);

    return PlotlyComponent;
  }(_react.Component);

  PlotlyComponent.propTypes = {
    data: _propTypes.default.arrayOf(_propTypes.default.object),
    config: _propTypes.default.object,
    layout: _propTypes.default.object,
    frames: _propTypes.default.arrayOf(_propTypes.default.object),
    revision: _propTypes.default.number,
    onInitialized: _propTypes.default.func,
    onPurge: _propTypes.default.func,
    onError: _propTypes.default.func,
    onUpdate: _propTypes.default.func,
    debug: _propTypes.default.bool,
    style: _propTypes.default.object,
    className: _propTypes.default.string,
    useResizeHandler: _propTypes.default.bool,
    divId: _propTypes.default.string
  };
  eventNames.forEach(function (eventName) {
    PlotlyComponent.propTypes['on' + eventName] = _propTypes.default.func;
  });
  PlotlyComponent.defaultProps = {
    debug: false,
    useResizeHandler: false,
    data: [],
    style: {
      position: 'relative',
      display: 'inline-block'
    }
  };
  return PlotlyComponent;
}
//# sourceMappingURL=factory.js.map

/***/ }),

/***/ "qTHO":
/*!**************************************************!*\
  !*** ./node_modules/ajv/lib/dotjs/multipleOf.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_multipleOf(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  out += 'var division' + ($lvl) + ';if (';
  if ($isData) {
    out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || ';
  }
  out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', ';
  if (it.opts.multipleOfPrecision) {
    out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' ';
  } else {
    out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') ';
  }
  out += ' ) ';
  if ($isData) {
    out += '  )  ';
  }
  out += ' ) {   ';
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should be multiple of ';
      if ($isData) {
        out += '\' + ' + ($schemaValue);
      } else {
        out += '' + ($schemaValue) + '\'';
      }
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}


/***/ }),

/***/ "qTWP":
/*!**************************************************************************!*\
  !*** ./node_modules/plotly.js/src/components/annotations/arrow_paths.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



/**
 * All paths are tuned for maximum scalability of the arrowhead,
 * ie throughout arrowwidth=0.3..3 the head is joined smoothly
 * to the line, with the line coming from the left and ending at (0, 0).
 *
 * `backoff` is the distance to move the arrowhead and the end of the line,
 * in order that the arrowhead points to the desired place, either at
 * the tip of the arrow or (in the case of circle or square)
 * the center of the symbol.
 *
 * `noRotate`, if truthy, says that this arrowhead should not rotate with the
 * arrow. That's the case for squares, which should always be straight, and
 * circles, for which it's irrelevant.
 */

module.exports = [
    // no arrow
    {
        path: '',
        backoff: 0
    },
    // wide with flat back
    {
        path: 'M-2.4,-3V3L0.6,0Z',
        backoff: 0.6
    },
    // narrower with flat back
    {
        path: 'M-3.7,-2.5V2.5L1.3,0Z',
        backoff: 1.3
    },
    // barbed
    {
        path: 'M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z',
        backoff: 1.55
    },
    // wide line-drawn
    {
        path: 'M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z',
        backoff: 1.6
    },
    // narrower line-drawn
    {
        path: 'M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z',
        backoff: 2
    },
    // circle
    {
        path: 'M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z',
        backoff: 0,
        noRotate: true
    },
    // square
    {
        path: 'M2,2V-2H-2V2Z',
        backoff: 0,
        noRotate: true
    }
];


/***/ }),

/***/ "qUp9":
/*!*******************************************************!*\
  !*** ./node_modules/@phosphor/signaling/lib/index.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(setImmediate) {
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
/**
 * A concrete implementation of `ISignal`.
 *
 * #### Example
 * ```typescript
 * import { ISignal, Signal } from '@phosphor/signaling';
 *
 * class SomeClass {
 *
 *   constructor(name: string) {
 *     this.name = name;
 *   }
 *
 *   readonly name: string;
 *
 *   get valueChanged: ISignal<this, number> {
 *     return this._valueChanged;
 *   }
 *
 *   get value(): number {
 *     return this._value;
 *   }
 *
 *   set value(value: number) {
 *     if (value === this._value) {
 *       return;
 *     }
 *     this._value = value;
 *     this._valueChanged.emit(value);
 *   }
 *
 *   private _value = 0;
 *   private _valueChanged = new Signal<this, number>(this);
 * }
 *
 * function logger(sender: SomeClass, value: number): void {
 *   console.log(sender.name, value);
 * }
 *
 * let m1 = new SomeClass('foo');
 * let m2 = new SomeClass('bar');
 *
 * m1.valueChanged.connect(logger);
 * m2.valueChanged.connect(logger);
 *
 * m1.value = 42;  // logs: foo 42
 * m2.value = 17;  // logs: bar 17
 * ```
 */
var Signal = (function () {
    /**
     * Construct a new signal.
     *
     * @param sender - The sender which owns the signal.
     */
    function Signal(sender) {
        this.sender = sender;
    }
    /**
     * Connect a slot to the signal.
     *
     * @param slot - The slot to invoke when the signal is emitted.
     *
     * @param thisArg - The `this` context for the slot. If provided,
     *   this must be a non-primitive object.
     *
     * @returns `true` if the connection succeeds, `false` otherwise.
     */
    Signal.prototype.connect = function (slot, thisArg) {
        return Private.connect(this, slot, thisArg);
    };
    /**
     * Disconnect a slot from the signal.
     *
     * @param slot - The slot to disconnect from the signal.
     *
     * @param thisArg - The `this` context for the slot. If provided,
     *   this must be a non-primitive object.
     *
     * @returns `true` if the connection is removed, `false` otherwise.
     */
    Signal.prototype.disconnect = function (slot, thisArg) {
        return Private.disconnect(this, slot, thisArg);
    };
    /**
     * Emit the signal and invoke the connected slots.
     *
     * @param args - The args to pass to the connected slots.
     *
     * #### Notes
     * Slots are invoked synchronously in connection order.
     *
     * Exceptions thrown by connected slots will be caught and logged.
     */
    Signal.prototype.emit = function (args) {
        Private.emit(this, args);
    };
    return Signal;
}());
exports.Signal = Signal;
/**
 * The namespace for the `Signal` class statics.
 */
(function (Signal) {
    /**
     * Remove all connections between a sender and receiver.
     *
     * @param sender - The sender object of interest.
     *
     * @param receiver - The receiver object of interest.
     *
     * #### Notes
     * If a `thisArg` is provided when connecting a signal, that object
     * is considered the receiver. Otherwise, the `slot` is considered
     * the receiver.
     */
    function disconnectBetween(sender, receiver) {
        Private.disconnectBetween(sender, receiver);
    }
    Signal.disconnectBetween = disconnectBetween;
    /**
     * Remove all connections where the given object is the sender.
     *
     * @param sender - The sender object of interest.
     */
    function disconnectSender(sender) {
        Private.disconnectSender(sender);
    }
    Signal.disconnectSender = disconnectSender;
    /**
     * Remove all connections where the given object is the receiver.
     *
     * @param receiver - The receiver object of interest.
     *
     * #### Notes
     * If a `thisArg` is provided when connecting a signal, that object
     * is considered the receiver. Otherwise, the `slot` is considered
     * the receiver.
     */
    function disconnectReceiver(receiver) {
        Private.disconnectReceiver(receiver);
    }
    Signal.disconnectReceiver = disconnectReceiver;
    /**
     * Remove all connections where an object is the sender or receiver.
     *
     * @param object - The object of interest.
     *
     * #### Notes
     * If a `thisArg` is provided when connecting a signal, that object
     * is considered the receiver. Otherwise, the `slot` is considered
     * the receiver.
     */
    function disconnectAll(object) {
        Private.disconnectAll(object);
    }
    Signal.disconnectAll = disconnectAll;
    /**
     * Clear all signal data associated with the given object.
     *
     * @param object - The object for which the data should be cleared.
     *
     * #### Notes
     * This removes all signal connections and any other signal data
     * associated with the object.
     */
    function clearData(object) {
        Private.disconnectAll(object);
    }
    Signal.clearData = clearData;
    /**
     * Get the signal exception handler.
     *
     * @returns The current exception handler.
     *
     * #### Notes
     * The default exception handler is `console.error`.
     */
    function getExceptionHandler() {
        return Private.exceptionHandler;
    }
    Signal.getExceptionHandler = getExceptionHandler;
    /**
     * Set the signal exception handler.
     *
     * @param handler - The function to use as the exception handler.
     *
     * @returns The old exception handler.
     *
     * #### Notes
     * The exception handler is invoked when a slot throws an exception.
     */
    function setExceptionHandler(handler) {
        var old = Private.exceptionHandler;
        Private.exceptionHandler = handler;
        return old;
    }
    Signal.setExceptionHandler = setExceptionHandler;
})(Signal = exports.Signal || (exports.Signal = {}));
exports.Signal = Signal;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * The signal exception handler function.
     */
    Private.exceptionHandler = function (err) {
        console.error(err);
    };
    /**
     * Connect a slot to a signal.
     *
     * @param signal - The signal of interest.
     *
     * @param slot - The slot to invoke when the signal is emitted.
     *
     * @param thisArg - The `this` context for the slot. If provided,
     *   this must be a non-primitive object.
     *
     * @returns `true` if the connection succeeds, `false` otherwise.
     */
    function connect(signal, slot, thisArg) {
        // Coerce a `null` `thisArg` to `undefined`.
        thisArg = thisArg || undefined;
        // Ensure the sender's array of receivers is created.
        var receivers = receiversForSender.get(signal.sender);
        if (!receivers) {
            receivers = [];
            receiversForSender.set(signal.sender, receivers);
        }
        // Bail if a matching connection already exists.
        if (findConnection(receivers, signal, slot, thisArg)) {
            return false;
        }
        // Choose the best object for the receiver.
        var receiver = thisArg || slot;
        // Ensure the receiver's array of senders is created.
        var senders = sendersForReceiver.get(receiver);
        if (!senders) {
            senders = [];
            sendersForReceiver.set(receiver, senders);
        }
        // Create a new connection and add it to the end of each array.
        var connection = { signal: signal, slot: slot, thisArg: thisArg };
        receivers.push(connection);
        senders.push(connection);
        // Indicate a successful connection.
        return true;
    }
    Private.connect = connect;
    /**
     * Disconnect a slot from a signal.
     *
     * @param signal - The signal of interest.
     *
     * @param slot - The slot to disconnect from the signal.
     *
     * @param thisArg - The `this` context for the slot. If provided,
     *   this must be a non-primitive object.
     *
     * @returns `true` if the connection is removed, `false` otherwise.
     */
    function disconnect(signal, slot, thisArg) {
        // Coerce a `null` `thisArg` to `undefined`.
        thisArg = thisArg || undefined;
        // Lookup the list of receivers, and bail if none exist.
        var receivers = receiversForSender.get(signal.sender);
        if (!receivers || receivers.length === 0) {
            return false;
        }
        // Bail if no matching connection exits.
        var connection = findConnection(receivers, signal, slot, thisArg);
        if (!connection) {
            return false;
        }
        // Choose the best object for the receiver.
        var receiver = thisArg || slot;
        // Lookup the array of senders, which is now known to exist.
        var senders = sendersForReceiver.get(receiver);
        // Clear the connection and schedule cleanup of the arrays.
        connection.signal = null;
        scheduleCleanup(receivers);
        scheduleCleanup(senders);
        // Indicate a successful disconnection.
        return true;
    }
    Private.disconnect = disconnect;
    /**
     * Remove all connections between a sender and receiver.
     *
     * @param sender - The sender object of interest.
     *
     * @param receiver - The receiver object of interest.
     */
    function disconnectBetween(sender, receiver) {
        // If there are no receivers, there is nothing to do.
        var receivers = receiversForSender.get(sender);
        if (!receivers || receivers.length === 0) {
            return;
        }
        // If there are no senders, there is nothing to do.
        var senders = sendersForReceiver.get(receiver);
        if (!senders || senders.length === 0) {
            return;
        }
        // Clear each connection between the sender and receiver.
        algorithm_1.each(senders, function (connection) {
            // Skip connections which have already been cleared.
            if (!connection.signal) {
                return;
            }
            // Clear the connection if it matches the sender.
            if (connection.signal.sender === sender) {
                connection.signal = null;
            }
        });
        // Schedule a cleanup of the senders and receivers.
        scheduleCleanup(receivers);
        scheduleCleanup(senders);
    }
    Private.disconnectBetween = disconnectBetween;
    /**
     * Remove all connections where the given object is the sender.
     *
     * @param sender - The sender object of interest.
     */
    function disconnectSender(sender) {
        // If there are no receivers, there is nothing to do.
        var receivers = receiversForSender.get(sender);
        if (!receivers || receivers.length === 0) {
            return;
        }
        // Clear each receiver connection.
        algorithm_1.each(receivers, function (connection) {
            // Skip connections which have already been cleared.
            if (!connection.signal) {
                return;
            }
            // Choose the best object for the receiver.
            var receiver = connection.thisArg || connection.slot;
            // Clear the connection.
            connection.signal = null;
            // Cleanup the array of senders, which is now known to exist.
            scheduleCleanup(sendersForReceiver.get(receiver));
        });
        // Schedule a cleanup of the receivers.
        scheduleCleanup(receivers);
    }
    Private.disconnectSender = disconnectSender;
    /**
     * Remove all connections where the given object is the receiver.
     *
     * @param receiver - The receiver object of interest.
     */
    function disconnectReceiver(receiver) {
        // If there are no senders, there is nothing to do.
        var senders = sendersForReceiver.get(receiver);
        if (!senders || senders.length === 0) {
            return;
        }
        // Clear each sender connection.
        algorithm_1.each(senders, function (connection) {
            // Skip connections which have already been cleared.
            if (!connection.signal) {
                return;
            }
            // Lookup the sender for the connection.
            var sender = connection.signal.sender;
            // Clear the connection.
            connection.signal = null;
            // Cleanup the array of receivers, which is now known to exist.
            scheduleCleanup(receiversForSender.get(sender));
        });
        // Schedule a cleanup of the list of senders.
        scheduleCleanup(senders);
    }
    Private.disconnectReceiver = disconnectReceiver;
    /**
     * Remove all connections where an object is the sender or receiver.
     *
     * @param object - The object of interest.
     */
    function disconnectAll(object) {
        // Clear and cleanup any receiver connections.
        var receivers = receiversForSender.get(object);
        if (receivers && receivers.length > 0) {
            algorithm_1.each(receivers, function (connection) { connection.signal = null; });
            scheduleCleanup(receivers);
        }
        // Clear and cleanup any sender connections.
        var senders = sendersForReceiver.get(object);
        if (senders && senders.length > 0) {
            algorithm_1.each(senders, function (connection) { connection.signal = null; });
            scheduleCleanup(senders);
        }
    }
    Private.disconnectAll = disconnectAll;
    /**
     * Emit a signal and invoke its connected slots.
     *
     * @param signal - The signal of interest.
     *
     * @param args - The args to pass to the connected slots.
     *
     * #### Notes
     * Slots are invoked synchronously in connection order.
     *
     * Exceptions thrown by connected slots will be caught and logged.
     */
    function emit(signal, args) {
        // If there are no receivers, there is nothing to do.
        var receivers = receiversForSender.get(signal.sender);
        if (!receivers || receivers.length === 0) {
            return;
        }
        // Invoke the slots for connections with a matching signal.
        // Any connections added during emission are not invoked.
        for (var i = 0, n = receivers.length; i < n; ++i) {
            var connection = receivers[i];
            if (connection.signal === signal) {
                invokeSlot(connection, args);
            }
        }
    }
    Private.emit = emit;
    /**
     * A weak mapping of sender to array of receiver connections.
     */
    var receiversForSender = new WeakMap();
    /**
     * A weak mapping of receiver to array of sender connections.
     */
    var sendersForReceiver = new WeakMap();
    /**
     * A set of connection arrays which are pending cleanup.
     */
    var dirtySet = new Set();
    /**
     * A function to schedule an event loop callback.
     */
    var schedule = (function () {
        var ok = typeof requestAnimationFrame === 'function';
        return ok ? requestAnimationFrame : setImmediate;
    })();
    /**
     * Find a connection which matches the given parameters.
     */
    function findConnection(connections, signal, slot, thisArg) {
        return algorithm_1.find(connections, function (connection) { return (connection.signal === signal &&
            connection.slot === slot &&
            connection.thisArg === thisArg); });
    }
    /**
     * Invoke a slot with the given parameters.
     *
     * The connection is assumed to be valid.
     *
     * Exceptions in the slot will be caught and logged.
     */
    function invokeSlot(connection, args) {
        var signal = connection.signal, slot = connection.slot, thisArg = connection.thisArg;
        try {
            slot.call(thisArg, signal.sender, args);
        }
        catch (err) {
            Private.exceptionHandler(err);
        }
    }
    /**
     * Schedule a cleanup of a connection array.
     *
     * This will add the array to the dirty set and schedule a deferred
     * cleanup of the array contents. On cleanup, any connection with a
     * `null` signal will be removed from the array.
     */
    function scheduleCleanup(array) {
        if (dirtySet.size === 0) {
            schedule(cleanupDirtySet);
        }
        dirtySet.add(array);
    }
    /**
     * Cleanup the connection lists in the dirty set.
     *
     * This function should only be invoked asynchronously, when the
     * stack frame is guaranteed to not be on the path of user code.
     */
    function cleanupDirtySet() {
        dirtySet.forEach(cleanupConnections);
        dirtySet.clear();
    }
    /**
     * Cleanup the dirty connections in a connections array.
     *
     * This will remove any connection with a `null` signal.
     *
     * This function should only be invoked asynchronously, when the
     * stack frame is guaranteed to not be on the path of user code.
     */
    function cleanupConnections(connections) {
        algorithm_1.ArrayExt.removeAllWhere(connections, isDeadConnection);
    }
    /**
     * Test whether a connection is dead.
     *
     * A dead connection has a `null` signal.
     */
    function isDeadConnection(connection) {
        return connection.signal === null;
    }
})(Private || (Private = {}));

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../timers-browserify/main.js */ "URgk").setImmediate))

/***/ }),

/***/ "qVij":
/*!**********************************************!*\
  !*** ./node_modules/browserify-rsa/index.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(Buffer) {var bn = __webpack_require__(/*! bn.js */ "OZ/i");
var randomBytes = __webpack_require__(/*! randombytes */ "Edxu");
module.exports = crt;
function blind(priv) {
  var r = getr(priv);
  var blinder = r.toRed(bn.mont(priv.modulus))
  .redPow(new bn(priv.publicExponent)).fromRed();
  return {
    blinder: blinder,
    unblinder:r.invm(priv.modulus)
  };
}
function crt(msg, priv) {
  var blinds = blind(priv);
  var len = priv.modulus.byteLength();
  var mod = bn.mont(priv.modulus);
  var blinded = new bn(msg).mul(blinds.blinder).umod(priv.modulus);
  var c1 = blinded.toRed(bn.mont(priv.prime1));
  var c2 = blinded.toRed(bn.mont(priv.prime2));
  var qinv = priv.coefficient;
  var p = priv.prime1;
  var q = priv.prime2;
  var m1 = c1.redPow(priv.exponent1);
  var m2 = c2.redPow(priv.exponent2);
  m1 = m1.fromRed();
  m2 = m2.fromRed();
  var h = m1.isub(m2).imul(qinv).umod(p);
  h.imul(q);
  m2.iadd(h);
  return new Buffer(m2.imul(blinds.unblinder).umod(priv.modulus).toArray(false, len));
}
crt.getr = getr;
function getr(priv) {
  var len = priv.modulus.byteLength();
  var r = new bn(randomBytes(len));
  while (r.cmp(priv.modulus) >=  0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)) {
    r = new bn(randomBytes(len));
  }
  return r;
}

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../buffer/index.js */ "tjlA").Buffer))

/***/ }),

/***/ "qXHa":
/*!*************************************************!*\
  !*** ./node_modules/ajv/lib/compile/resolve.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var url = __webpack_require__(/*! url */ "CxY0")
  , equal = __webpack_require__(/*! ./equal */ "gQ7D")
  , util = __webpack_require__(/*! ./util */ "+9rK")
  , SchemaObject = __webpack_require__(/*! ./schema_obj */ "ugD5")
  , traverse = __webpack_require__(/*! json-schema-traverse */ "ialn");

module.exports = resolve;

resolve.normalizeId = normalizeId;
resolve.fullPath = getFullPath;
resolve.url = resolveUrl;
resolve.ids = resolveIds;
resolve.inlineRef = inlineRef;
resolve.schema = resolveSchema;

/**
 * [resolve and compile the references ($ref)]
 * @this   Ajv
 * @param  {Function} compile reference to schema compilation funciton (localCompile)
 * @param  {Object} root object with information about the root schema for the current schema
 * @param  {String} ref reference to resolve
 * @return {Object|Function} schema object (if the schema can be inlined) or validation function
 */
function resolve(compile, root, ref) {
  /* jshint validthis: true */
  var refVal = this._refs[ref];
  if (typeof refVal == 'string') {
    if (this._refs[refVal]) refVal = this._refs[refVal];
    else return resolve.call(this, compile, root, refVal);
  }

  refVal = refVal || this._schemas[ref];
  if (refVal instanceof SchemaObject) {
    return inlineRef(refVal.schema, this._opts.inlineRefs)
            ? refVal.schema
            : refVal.validate || this._compile(refVal);
  }

  var res = resolveSchema.call(this, root, ref);
  var schema, v, baseId;
  if (res) {
    schema = res.schema;
    root = res.root;
    baseId = res.baseId;
  }

  if (schema instanceof SchemaObject) {
    v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId);
  } else if (schema !== undefined) {
    v = inlineRef(schema, this._opts.inlineRefs)
        ? schema
        : compile.call(this, schema, root, undefined, baseId);
  }

  return v;
}


/**
 * Resolve schema, its root and baseId
 * @this Ajv
 * @param  {Object} root root object with properties schema, refVal, refs
 * @param  {String} ref  reference to resolve
 * @return {Object} object with properties schema, root, baseId
 */
function resolveSchema(root, ref) {
  /* jshint validthis: true */
  var p = url.parse(ref, false, true)
    , refPath = _getFullPath(p)
    , baseId = getFullPath(this._getId(root.schema));
  if (refPath !== baseId) {
    var id = normalizeId(refPath);
    var refVal = this._refs[id];
    if (typeof refVal == 'string') {
      return resolveRecursive.call(this, root, refVal, p);
    } else if (refVal instanceof SchemaObject) {
      if (!refVal.validate) this._compile(refVal);
      root = refVal;
    } else {
      refVal = this._schemas[id];
      if (refVal instanceof SchemaObject) {
        if (!refVal.validate) this._compile(refVal);
        if (id == normalizeId(ref))
          return { schema: refVal, root: root, baseId: baseId };
        root = refVal;
      } else {
        return;
      }
    }
    if (!root.schema) return;
    baseId = getFullPath(this._getId(root.schema));
  }
  return getJsonPointer.call(this, p, baseId, root.schema, root);
}


/* @this Ajv */
function resolveRecursive(root, ref, parsedRef) {
  /* jshint validthis: true */
  var res = resolveSchema.call(this, root, ref);
  if (res) {
    var schema = res.schema;
    var baseId = res.baseId;
    root = res.root;
    var id = this._getId(schema);
    if (id) baseId = resolveUrl(baseId, id);
    return getJsonPointer.call(this, parsedRef, baseId, schema, root);
  }
}


var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']);
/* @this Ajv */
function getJsonPointer(parsedRef, baseId, schema, root) {
  /* jshint validthis: true */
  parsedRef.hash = parsedRef.hash || '';
  if (parsedRef.hash.slice(0,2) != '#/') return;
  var parts = parsedRef.hash.split('/');

  for (var i = 1; i < parts.length; i++) {
    var part = parts[i];
    if (part) {
      part = util.unescapeFragment(part);
      schema = schema[part];
      if (schema === undefined) break;
      var id;
      if (!PREVENT_SCOPE_CHANGE[part]) {
        id = this._getId(schema);
        if (id) baseId = resolveUrl(baseId, id);
        if (schema.$ref) {
          var $ref = resolveUrl(baseId, schema.$ref);
          var res = resolveSchema.call(this, root, $ref);
          if (res) {
            schema = res.schema;
            root = res.root;
            baseId = res.baseId;
          }
        }
      }
    }
  }
  if (schema !== undefined && schema !== root.schema)
    return { schema: schema, root: root, baseId: baseId };
}


var SIMPLE_INLINED = util.toHash([
  'type', 'format', 'pattern',
  'maxLength', 'minLength',
  'maxProperties', 'minProperties',
  'maxItems', 'minItems',
  'maximum', 'minimum',
  'uniqueItems', 'multipleOf',
  'required', 'enum'
]);
function inlineRef(schema, limit) {
  if (limit === false) return false;
  if (limit === undefined || limit === true) return checkNoRef(schema);
  else if (limit) return countKeys(schema) <= limit;
}


function checkNoRef(schema) {
  var item;
  if (Array.isArray(schema)) {
    for (var i=0; i<schema.length; i++) {
      item = schema[i];
      if (typeof item == 'object' && !checkNoRef(item)) return false;
    }
  } else {
    for (var key in schema) {
      if (key == '$ref') return false;
      item = schema[key];
      if (typeof item == 'object' && !checkNoRef(item)) return false;
    }
  }
  return true;
}


function countKeys(schema) {
  var count = 0, item;
  if (Array.isArray(schema)) {
    for (var i=0; i<schema.length; i++) {
      item = schema[i];
      if (typeof item == 'object') count += countKeys(item);
      if (count == Infinity) return Infinity;
    }
  } else {
    for (var key in schema) {
      if (key == '$ref') return Infinity;
      if (SIMPLE_INLINED[key]) {
        count++;
      } else {
        item = schema[key];
        if (typeof item == 'object') count += countKeys(item) + 1;
        if (count == Infinity) return Infinity;
      }
    }
  }
  return count;
}


function getFullPath(id, normalize) {
  if (normalize !== false) id = normalizeId(id);
  var p = url.parse(id, false, true);
  return _getFullPath(p);
}


function _getFullPath(p) {
  var protocolSeparator = p.protocol || p.href.slice(0,2) == '//' ? '//' : '';
  return (p.protocol||'') + protocolSeparator + (p.host||'') + (p.path||'')  + '#';
}


var TRAILING_SLASH_HASH = /#\/?$/;
function normalizeId(id) {
  return id ? id.replace(TRAILING_SLASH_HASH, '') : '';
}


function resolveUrl(baseId, id) {
  id = normalizeId(id);
  return url.resolve(baseId, id);
}


/* @this Ajv */
function resolveIds(schema) {
  var schemaId = normalizeId(this._getId(schema));
  var baseIds = {'': schemaId};
  var fullPaths = {'': getFullPath(schemaId, false)};
  var localRefs = {};
  var self = this;

  traverse(schema, {allKeys: true}, function(sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
    if (jsonPtr === '') return;
    var id = self._getId(sch);
    var baseId = baseIds[parentJsonPtr];
    var fullPath = fullPaths[parentJsonPtr] + '/' + parentKeyword;
    if (keyIndex !== undefined)
      fullPath += '/' + (typeof keyIndex == 'number' ? keyIndex : util.escapeFragment(keyIndex));

    if (typeof id == 'string') {
      id = baseId = normalizeId(baseId ? url.resolve(baseId, id) : id);

      var refVal = self._refs[id];
      if (typeof refVal == 'string') refVal = self._refs[refVal];
      if (refVal && refVal.schema) {
        if (!equal(sch, refVal.schema))
          throw new Error('id "' + id + '" resolves to more than one schema');
      } else if (id != normalizeId(fullPath)) {
        if (id[0] == '#') {
          if (localRefs[id] && !equal(sch, localRefs[id]))
            throw new Error('id "' + id + '" resolves to more than one schema');
          localRefs[id] = sch;
        } else {
          self._refs[id] = fullPath;
        }
      }
    }
    baseIds[jsonPtr] = baseId;
    fullPaths[jsonPtr] = fullPath;
  });

  return localRefs;
}


/***/ }),

/***/ "qXhn":
/*!**************************************************************!*\
  !*** ./node_modules/@jupyterlab/rendermime/lib/mimemodel.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/**
 * The default mime model implementation.
 */
class MimeModel {
    /**
     * Construct a new mime model.
     */
    constructor(options = {}) {
        this.trusted = !!options.trusted;
        this._data = options.data || {};
        this._metadata = options.metadata || {};
        this._callback = options.callback || Private.noOp;
    }
    /**
     * The data associated with the model.
     */
    get data() {
        return this._data;
    }
    /**
     * The metadata associated with the model.
     */
    get metadata() {
        return this._metadata;
    }
    /**
     * Set the data associated with the model.
     *
     * #### Notes
     * Depending on the implementation of the mime model,
     * this call may or may not have deferred effects,
     */
    setData(options) {
        this._data = options.data || this._data;
        this._metadata = options.metadata || this._metadata;
        this._callback(options);
    }
}
exports.MimeModel = MimeModel;
/**
 * The namespace for module private data.
 */
var Private;
(function (Private) {
    /**
     * A no-op callback function.
     */
    function noOp() {
        /* no-op */
    }
    Private.noOp = noOp;
})(Private || (Private = {}));


/***/ }),

/***/ "qZRx":
/*!*********************************************************!*\
  !*** ./node_modules/@jupyterlab/notebook/lib/widget.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const properties_1 = __webpack_require__(/*! @phosphor/properties */ "3kwb");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const dragdrop_1 = __webpack_require__(/*! @phosphor/dragdrop */ "v7cI");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const virtualdom_1 = __webpack_require__(/*! @phosphor/virtualdom */ "Gqu+");
const cells_1 = __webpack_require__(/*! @jupyterlab/cells */ "USP6");
const codeeditor_1 = __webpack_require__(/*! @jupyterlab/codeeditor */ "sLCx");
/**
 * The data attribute added to a widget that has an active kernel.
 */
const KERNEL_USER = 'jpKernelUser';
/**
 * The data attribute added to a widget that can run code.
 */
const CODE_RUNNER = 'jpCodeRunner';
/**
 * The data attribute added to a widget that can undo.
 */
const UNDOER = 'jpUndoer';
/**
 * The class name added to notebook widgets.
 */
const NB_CLASS = 'jp-Notebook';
/**
 * The class name added to notebook widget cells.
 */
const NB_CELL_CLASS = 'jp-Notebook-cell';
/**
 * The class name added to a notebook in edit mode.
 */
const EDIT_CLASS = 'jp-mod-editMode';
/**
 * The class name added to a notebook in command mode.
 */
const COMMAND_CLASS = 'jp-mod-commandMode';
/**
 * The class name added to the active cell.
 */
const ACTIVE_CLASS = 'jp-mod-active';
/**
 * The class name added to selected cells.
 */
const SELECTED_CLASS = 'jp-mod-selected';
/**
 * The class name added to an active cell when there are other selected cells.
 */
const OTHER_SELECTED_CLASS = 'jp-mod-multiSelected';
/**
 * The class name added to unconfined images.
 */
const UNCONFINED_CLASS = 'jp-mod-unconfined';
/**
 * The class name added to a drop target.
 */
const DROP_TARGET_CLASS = 'jp-mod-dropTarget';
/**
 * The class name added to a drop source.
 */
const DROP_SOURCE_CLASS = 'jp-mod-dropSource';
/**
 * The class name added to drag images.
 */
const DRAG_IMAGE_CLASS = 'jp-dragImage';
/**
 * The class name added to singular drag images
 */
const SINGLE_DRAG_IMAGE_CLASS = 'jp-dragImage-singlePrompt';
/**
 * The class name added to the drag image cell content.
 */
const CELL_DRAG_CONTENT_CLASS = 'jp-dragImage-content';
/**
 * The class name added to the drag image cell content.
 */
const CELL_DRAG_PROMPT_CLASS = 'jp-dragImage-prompt';
/**
 * The class name added to the drag image cell content.
 */
const CELL_DRAG_MULTIPLE_BACK = 'jp-dragImage-multipleBack';
/**
 * The mimetype used for Jupyter cell data.
 */
const JUPYTER_CELL_MIME = 'application/vnd.jupyter.cells';
/**
 * The threshold in pixels to start a drag event.
 */
const DRAG_THRESHOLD = 5;
/**
 * A widget which renders static non-interactive notebooks.
 *
 * #### Notes
 * The widget model must be set separately and can be changed
 * at any time.  Consumers of the widget must account for a
 * `null` model, and may want to listen to the `modelChanged`
 * signal.
 */
class StaticNotebook extends widgets_1.Widget {
    /**
     * Construct a notebook widget.
     */
    constructor(options) {
        super();
        this._editorConfig = StaticNotebook.defaultEditorConfig;
        this._mimetype = 'text/plain';
        this._model = null;
        this._modelChanged = new signaling_1.Signal(this);
        this._modelContentChanged = new signaling_1.Signal(this);
        this.addClass(NB_CLASS);
        this.node.dataset[KERNEL_USER] = 'true';
        this.node.dataset[UNDOER] = 'true';
        this.rendermime = options.rendermime;
        this.layout = new Private.NotebookPanelLayout();
        this.contentFactory =
            options.contentFactory || StaticNotebook.defaultContentFactory;
        this.editorConfig =
            options.editorConfig || StaticNotebook.defaultEditorConfig;
        this._mimetypeService = options.mimeTypeService;
    }
    /**
     * A signal emitted when the model of the notebook changes.
     */
    get modelChanged() {
        return this._modelChanged;
    }
    /**
     * A signal emitted when the model content changes.
     *
     * #### Notes
     * This is a convenience signal that follows the current model.
     */
    get modelContentChanged() {
        return this._modelContentChanged;
    }
    /**
     * The model for the widget.
     */
    get model() {
        return this._model;
    }
    set model(newValue) {
        newValue = newValue || null;
        if (this._model === newValue) {
            return;
        }
        let oldValue = this._model;
        this._model = newValue;
        if (oldValue && oldValue.modelDB.isCollaborative) {
            oldValue.modelDB.connected.then(() => {
                oldValue.modelDB.collaborators.changed.disconnect(this._onCollaboratorsChanged, this);
            });
        }
        if (newValue && newValue.modelDB.isCollaborative) {
            newValue.modelDB.connected.then(() => {
                newValue.modelDB.collaborators.changed.connect(this._onCollaboratorsChanged, this);
            });
        }
        // Trigger private, protected, and public changes.
        this._onModelChanged(oldValue, newValue);
        this.onModelChanged(oldValue, newValue);
        this._modelChanged.emit(void 0);
    }
    /**
     * Get the mimetype for code cells.
     */
    get codeMimetype() {
        return this._mimetype;
    }
    /**
     * A read-only sequence of the widgets in the notebook.
     */
    get widgets() {
        return this.layout.widgets;
    }
    /**
     * A configuration object for cell editor settings.
     */
    get editorConfig() {
        return this._editorConfig;
    }
    set editorConfig(value) {
        this._editorConfig = value;
        this._updateEditorConfig();
    }
    /**
     * Dispose of the resources held by the widget.
     */
    dispose() {
        // Do nothing if already disposed.
        if (this.isDisposed) {
            return;
        }
        this._model = null;
        super.dispose();
    }
    /**
     * Handle a new model.
     *
     * #### Notes
     * This method is called after the model change has been handled
     * internally and before the `modelChanged` signal is emitted.
     * The default implementation is a no-op.
     */
    onModelChanged(oldValue, newValue) {
        // No-op.
    }
    /**
     * Handle changes to the notebook model content.
     *
     * #### Notes
     * The default implementation emits the `modelContentChanged` signal.
     */
    onModelContentChanged(model, args) {
        this._modelContentChanged.emit(void 0);
    }
    /**
     * Handle changes to the notebook model metadata.
     *
     * #### Notes
     * The default implementation updates the mimetypes of the code cells
     * when the `language_info` metadata changes.
     */
    onMetadataChanged(sender, args) {
        switch (args.key) {
            case 'language_info':
                this._updateMimetype();
                break;
            default:
                break;
        }
    }
    /**
     * Handle a cell being inserted.
     *
     * The default implementation is a no-op
     */
    onCellInserted(index, cell) {
        // This is a no-op.
    }
    /**
     * Handle a cell being moved.
     *
     * The default implementation is a no-op
     */
    onCellMoved(fromIndex, toIndex) {
        // This is a no-op.
    }
    /**
     * Handle a cell being removed.
     *
     * The default implementation is a no-op
     */
    onCellRemoved(index, cell) {
        // This is a no-op.
    }
    /**
     * Handle a new model on the widget.
     */
    _onModelChanged(oldValue, newValue) {
        let layout = this.layout;
        if (oldValue) {
            oldValue.cells.changed.disconnect(this._onCellsChanged, this);
            oldValue.metadata.changed.disconnect(this.onMetadataChanged, this);
            oldValue.contentChanged.disconnect(this.onModelContentChanged, this);
            // TODO: reuse existing cell widgets if possible. Remember to initially
            // clear the history of each cell if we do this.
            while (layout.widgets.length) {
                this._removeCell(0);
            }
        }
        if (!newValue) {
            this._mimetype = 'text/plain';
            return;
        }
        this._updateMimetype();
        let cells = newValue.cells;
        algorithm_1.each(cells, (cell, i) => {
            this._insertCell(i, cell);
        });
        cells.changed.connect(this._onCellsChanged, this);
        newValue.contentChanged.connect(this.onModelContentChanged, this);
        newValue.metadata.changed.connect(this.onMetadataChanged, this);
    }
    /**
     * Handle a change cells event.
     */
    _onCellsChanged(sender, args) {
        let index = 0;
        switch (args.type) {
            case 'add':
                index = args.newIndex;
                algorithm_1.each(args.newValues, value => {
                    this._insertCell(index++, value);
                });
                break;
            case 'move':
                this._moveCell(args.oldIndex, args.newIndex);
                break;
            case 'remove':
                algorithm_1.each(args.oldValues, value => {
                    this._removeCell(args.oldIndex);
                });
                break;
            case 'set':
                // TODO: reuse existing widgets if possible.
                index = args.newIndex;
                algorithm_1.each(args.newValues, value => {
                    // Note: this ordering (insert then remove)
                    // is important for getting the active cell
                    // index for the editable notebook correct.
                    this._insertCell(index, value);
                    this._removeCell(index + 1);
                    index++;
                });
                break;
            default:
                return;
        }
    }
    /**
     * Create a cell widget and insert into the notebook.
     */
    _insertCell(index, cell) {
        let widget;
        switch (cell.type) {
            case 'code':
                widget = this._createCodeCell(cell);
                widget.model.mimeType = this._mimetype;
                break;
            case 'markdown':
                widget = this._createMarkdownCell(cell);
                break;
            default:
                widget = this._createRawCell(cell);
        }
        widget.addClass(NB_CELL_CLASS);
        let layout = this.layout;
        layout.insertWidget(index, widget);
        this.onCellInserted(index, widget);
    }
    /**
     * Create a code cell widget from a code cell model.
     */
    _createCodeCell(model) {
        let rendermime = this.rendermime;
        let contentFactory = this.contentFactory;
        const editorConfig = this.editorConfig.code;
        let options = { editorConfig, model, rendermime, contentFactory };
        return this.contentFactory.createCodeCell(options, this);
    }
    /**
     * Create a markdown cell widget from a markdown cell model.
     */
    _createMarkdownCell(model) {
        let rendermime = this.rendermime;
        let contentFactory = this.contentFactory;
        const editorConfig = this.editorConfig.markdown;
        let options = { editorConfig, model, rendermime, contentFactory };
        return this.contentFactory.createMarkdownCell(options, this);
    }
    /**
     * Create a raw cell widget from a raw cell model.
     */
    _createRawCell(model) {
        let contentFactory = this.contentFactory;
        const editorConfig = this.editorConfig.raw;
        let options = { editorConfig, model, contentFactory };
        return this.contentFactory.createRawCell(options, this);
    }
    /**
     * Move a cell widget.
     */
    _moveCell(fromIndex, toIndex) {
        let layout = this.layout;
        layout.insertWidget(toIndex, layout.widgets[fromIndex]);
        this.onCellMoved(fromIndex, toIndex);
    }
    /**
     * Remove a cell widget.
     */
    _removeCell(index) {
        let layout = this.layout;
        let widget = layout.widgets[index];
        widget.parent = null;
        this.onCellRemoved(index, widget);
        widget.dispose();
    }
    /**
     * Update the mimetype of the notebook.
     */
    _updateMimetype() {
        let info = this._model.metadata.get('language_info');
        if (!info) {
            return;
        }
        this._mimetype = this._mimetypeService.getMimeTypeByLanguage(info);
        algorithm_1.each(this.widgets, widget => {
            if (widget.model.type === 'code') {
                widget.model.mimeType = this._mimetype;
            }
        });
    }
    /**
     * Handle an update to the collaborators.
     */
    _onCollaboratorsChanged() {
        // If there are selections corresponding to non-collaborators,
        // they are stale and should be removed.
        for (let i = 0; i < this.widgets.length; i++) {
            let cell = this.widgets[i];
            for (let key of cell.model.selections.keys()) {
                if (!this._model.modelDB.collaborators.has(key)) {
                    cell.model.selections.delete(key);
                }
            }
        }
    }
    /**
     * Update editor settings for notebook cells.
     */
    _updateEditorConfig() {
        for (let i = 0; i < this.widgets.length; i++) {
            const cell = this.widgets[i];
            let config;
            switch (cell.model.type) {
                case 'code':
                    config = this._editorConfig.code;
                    break;
                case 'markdown':
                    config = this._editorConfig.markdown;
                    break;
                default:
                    config = this._editorConfig.raw;
                    break;
            }
            Object.keys(config).forEach((key) => {
                cell.editor.setOption(key, config[key]);
            });
        }
    }
}
exports.StaticNotebook = StaticNotebook;
/**
 * The namespace for the `StaticNotebook` class statics.
 */
(function (StaticNotebook) {
    /**
     * Default configuration options for cell editors.
     */
    StaticNotebook.defaultEditorConfig = {
        code: Object.assign({}, codeeditor_1.CodeEditor.defaultConfig, { lineWrap: 'off', matchBrackets: true, autoClosingBrackets: true }),
        markdown: Object.assign({}, codeeditor_1.CodeEditor.defaultConfig, { lineWrap: 'on', matchBrackets: false, autoClosingBrackets: false }),
        raw: Object.assign({}, codeeditor_1.CodeEditor.defaultConfig, { lineWrap: 'on', matchBrackets: false, autoClosingBrackets: false })
    };
    /**
     * The default implementation of an `IContentFactory`.
     */
    class ContentFactory extends cells_1.Cell.ContentFactory {
        /**
         * Create a new code cell widget.
         *
         * #### Notes
         * If no cell content factory is passed in with the options, the one on the
         * notebook content factory is used.
         */
        createCodeCell(options, parent) {
            if (!options.contentFactory) {
                options.contentFactory = this;
            }
            return new cells_1.CodeCell(options);
        }
        /**
         * Create a new markdown cell widget.
         *
         * #### Notes
         * If no cell content factory is passed in with the options, the one on the
         * notebook content factory is used.
         */
        createMarkdownCell(options, parent) {
            if (!options.contentFactory) {
                options.contentFactory = this;
            }
            return new cells_1.MarkdownCell(options);
        }
        /**
         * Create a new raw cell widget.
         *
         * #### Notes
         * If no cell content factory is passed in with the options, the one on the
         * notebook content factory is used.
         */
        createRawCell(options, parent) {
            if (!options.contentFactory) {
                options.contentFactory = this;
            }
            return new cells_1.RawCell(options);
        }
    }
    StaticNotebook.ContentFactory = ContentFactory;
    /**
     * Default content factory for the static notebook widget.
     */
    StaticNotebook.defaultContentFactory = new ContentFactory();
})(StaticNotebook = exports.StaticNotebook || (exports.StaticNotebook = {}));
/**
 * A notebook widget that supports interactivity.
 */
class Notebook extends StaticNotebook {
    /**
     * Construct a notebook widget.
     */
    constructor(options) {
        super(Private.processNotebookOptions(options));
        this._activeCellIndex = -1;
        this._activeCell = null;
        this._mode = 'command';
        this._drag = null;
        this._dragData = null;
        this._mouseMode = null;
        this._activeCellChanged = new signaling_1.Signal(this);
        this._stateChanged = new signaling_1.Signal(this);
        this._selectionChanged = new signaling_1.Signal(this);
        this.node.tabIndex = -1; // Allow the widget to take focus.
        // Allow the node to scroll while dragging items.
        this.node.setAttribute('data-p-dragscroll', 'true');
    }
    /**
     * A signal emitted when the active cell changes.
     *
     * #### Notes
     * This can be due to the active index changing or the
     * cell at the active index changing.
     */
    get activeCellChanged() {
        return this._activeCellChanged;
    }
    /**
     * A signal emitted when the state of the notebook changes.
     */
    get stateChanged() {
        return this._stateChanged;
    }
    /**
     * A signal emitted when the selection state of the notebook changes.
     */
    get selectionChanged() {
        return this._selectionChanged;
    }
    /**
     * The interactivity mode of the notebook.
     */
    get mode() {
        return this._mode;
    }
    set mode(newValue) {
        let activeCell = this.activeCell;
        if (!activeCell) {
            newValue = 'command';
        }
        if (newValue === this._mode) {
            this._ensureFocus();
            return;
        }
        // Post an update request.
        this.update();
        let oldValue = this._mode;
        this._mode = newValue;
        if (newValue === 'edit') {
            // Edit mode deselects all cells.
            algorithm_1.each(this.widgets, widget => {
                this.deselect(widget);
            });
            //  Edit mode unrenders an active markdown widget.
            if (activeCell instanceof cells_1.MarkdownCell) {
                activeCell.rendered = false;
            }
            activeCell.inputHidden = false;
        }
        else {
            // Focus on the notebook document, which blurs the active cell.
            this.node.focus();
        }
        this._stateChanged.emit({ name: 'mode', oldValue, newValue });
        this._ensureFocus();
    }
    /**
     * The active cell index of the notebook.
     *
     * #### Notes
     * The index will be clamped to the bounds of the notebook cells.
     */
    get activeCellIndex() {
        if (!this.model) {
            return -1;
        }
        return this.model.cells.length ? this._activeCellIndex : -1;
    }
    set activeCellIndex(newValue) {
        let oldValue = this._activeCellIndex;
        if (!this.model || !this.model.cells.length) {
            newValue = -1;
        }
        else {
            newValue = Math.max(newValue, 0);
            newValue = Math.min(newValue, this.model.cells.length - 1);
        }
        this._activeCellIndex = newValue;
        let cell = this.widgets[newValue];
        if (cell !== this._activeCell) {
            // Post an update request.
            this.update();
            this._activeCell = cell;
            this._activeCellChanged.emit(cell);
        }
        if (this.mode === 'edit' && cell instanceof cells_1.MarkdownCell) {
            cell.rendered = false;
        }
        this._ensureFocus();
        if (newValue === oldValue) {
            return;
        }
        this._trimSelections();
        this._stateChanged.emit({ name: 'activeCellIndex', oldValue, newValue });
    }
    /**
     * Get the active cell widget.
     *
     * #### Notes
     * This is a cell or `null` if there is no active cell.
     */
    get activeCell() {
        return this._activeCell;
    }
    /**
     * Dispose of the resources held by the widget.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._activeCell = null;
        super.dispose();
    }
    /**
     * Select a cell widget.
     *
     * #### Notes
     * It is a no-op if the value does not change.
     * It will emit the `selectionChanged` signal.
     */
    select(widget) {
        if (Private.selectedProperty.get(widget)) {
            return;
        }
        Private.selectedProperty.set(widget, true);
        this._selectionChanged.emit(void 0);
        this.update();
    }
    /**
     * Deselect a cell widget.
     *
     * #### Notes
     * It is a no-op if the value does not change.
     * It will emit the `selectionChanged` signal.
     */
    deselect(widget) {
        if (!Private.selectedProperty.get(widget)) {
            return;
        }
        Private.selectedProperty.set(widget, false);
        this._selectionChanged.emit(void 0);
        this.update();
    }
    /**
     * Whether a cell is selected.
     */
    isSelected(widget) {
        return Private.selectedProperty.get(widget);
    }
    /**
     * Whether a cell is selected or is the active cell.
     */
    isSelectedOrActive(widget) {
        if (widget === this._activeCell) {
            return true;
        }
        return Private.selectedProperty.get(widget);
    }
    /**
     * Deselect all of the cells.
     */
    deselectAll() {
        let changed = false;
        algorithm_1.each(this.widgets, widget => {
            if (Private.selectedProperty.get(widget)) {
                changed = true;
            }
            Private.selectedProperty.set(widget, false);
        });
        if (changed) {
            this._selectionChanged.emit(void 0);
        }
        // Make sure we have a valid active cell.
        this.activeCellIndex = this.activeCellIndex;
        this.update();
    }
    /**
     * Move the head of an existing contiguous selection to extend the selection.
     *
     * @param index - The new head of the existing selection.
     *
     * #### Notes
     * If there is no existing selection, the active cell is considered an
     * existing one-cell selection.
     *
     * If the new selection is a single cell, that cell becomes the active cell
     * and all cells are deselected.
     *
     * There is no change if there are no cells (i.e., activeCellIndex is -1).
     */
    extendContiguousSelectionTo(index) {
        let { head, anchor } = this.getContiguousSelection();
        let i;
        // Handle the case of no current selection.
        if (anchor === null) {
            if (index === this.activeCellIndex) {
                // Already collapsed selection, nothing more to do.
                return;
            }
            // We will start a new selection below.
            head = this.activeCellIndex;
            anchor = this.activeCellIndex;
        }
        // Move the active cell. We do this before the collapsing shortcut below.
        this.activeCellIndex = index;
        // Make sure the index is valid, according to the rules for setting and clipping the
        // active cell index. This may change the index.
        index = this.activeCellIndex;
        // Collapse the selection if it is only the active cell.
        if (index === anchor) {
            this.deselectAll();
            return;
        }
        let selectionChanged = false;
        if (head < index) {
            if (head < anchor) {
                Private.selectedProperty.set(this.widgets[head], false);
                selectionChanged = true;
            }
            // Toggle everything strictly between head and index except anchor.
            for (i = head + 1; i < index; i++) {
                if (i !== anchor) {
                    Private.selectedProperty.set(this.widgets[i], !Private.selectedProperty.get(this.widgets[i]));
                    selectionChanged = true;
                }
            }
        }
        else if (index < head) {
            if (anchor < head) {
                Private.selectedProperty.set(this.widgets[head], false);
                selectionChanged = true;
            }
            // Toggle everything strictly between index and head except anchor.
            for (i = index + 1; i < head; i++) {
                if (i !== anchor) {
                    Private.selectedProperty.set(this.widgets[i], !Private.selectedProperty.get(this.widgets[i]));
                    selectionChanged = true;
                }
            }
        }
        // Anchor and index should *always* be selected.
        if (!Private.selectedProperty.get(this.widgets[anchor])) {
            selectionChanged = true;
        }
        Private.selectedProperty.set(this.widgets[anchor], true);
        if (!Private.selectedProperty.get(this.widgets[index])) {
            selectionChanged = true;
        }
        Private.selectedProperty.set(this.widgets[index], true);
        if (selectionChanged) {
            this._selectionChanged.emit(void 0);
        }
    }
    /**
     * Get the head and anchor of a contiguous cell selection.
     *
     * The head of a contiguous selection is always the active cell.
     *
     * If there are no cells selected, `{head: null, anchor: null}` is returned.
     *
     * Throws an error if the currently selected cells do not form a contiguous
     * selection.
     */
    getContiguousSelection() {
        let cells = this.widgets;
        let first = algorithm_1.ArrayExt.findFirstIndex(cells, c => this.isSelected(c));
        // Return early if no cells are selected.
        if (first === -1) {
            return { head: null, anchor: null };
        }
        let last = algorithm_1.ArrayExt.findLastIndex(cells, c => this.isSelected(c), -1, first);
        // Check that the selection is contiguous.
        for (let i = first; i <= last; i++) {
            if (!this.isSelected(cells[i])) {
                throw new Error('Selection not contiguous');
            }
        }
        // Check that the active cell is one of the endpoints of the selection.
        let activeIndex = this.activeCellIndex;
        if (first !== activeIndex && last !== activeIndex) {
            throw new Error('Active cell not at endpoint of selection');
        }
        // Determine the head and anchor of the selection.
        if (first === activeIndex) {
            return { head: first, anchor: last };
        }
        else {
            return { head: last, anchor: first };
        }
    }
    /**
     * Scroll so that the given position is centered.
     *
     * @param position - The vertical position in the notebook widget.
     *
     * @param threshold - An optional threshold for the scroll (0-50, defaults to
     * 25).
     *
     * #### Notes
     * If the position is within the threshold percentage of the widget height,
     * measured from the center of the widget, the scroll position will not be
     * changed. A threshold of 0 means we will always scroll so the position is
     * centered, and a threshold of 50 means scrolling only happens if position is
     * outside the current window.
     */
    scrollToPosition(position, threshold = 25) {
        let node = this.node;
        let ar = node.getBoundingClientRect();
        let delta = position - ar.top - ar.height / 2;
        if (Math.abs(delta) > (ar.height * threshold) / 100) {
            node.scrollTop += delta;
        }
    }
    /**
     * Handle the DOM events for the widget.
     *
     * @param event - The DOM event sent to the widget.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the notebook panel's node. It should
     * not be called directly by user code.
     */
    handleEvent(event) {
        if (!this.model) {
            return;
        }
        switch (event.type) {
            case 'contextmenu':
                if (event.eventPhase === Event.CAPTURING_PHASE) {
                    this._evtContextMenuCapture(event);
                }
                break;
            case 'mousedown':
                if (event.eventPhase === Event.CAPTURING_PHASE) {
                    this._evtMouseDownCapture(event);
                }
                else {
                    this._evtMouseDown(event);
                }
                break;
            case 'mouseup':
                if (event.currentTarget === document) {
                    this._evtDocumentMouseup(event);
                }
                break;
            case 'mousemove':
                if (event.currentTarget === document) {
                    this._evtDocumentMousemove(event);
                }
                break;
            case 'keydown':
                this._ensureFocus(true);
                break;
            case 'dblclick':
                this._evtDblClick(event);
                break;
            case 'focusin':
                this._evtFocusIn(event);
                break;
            case 'focusout':
                this._evtFocusOut(event);
                break;
            case 'p-dragenter':
                this._evtDragEnter(event);
                break;
            case 'p-dragleave':
                this._evtDragLeave(event);
                break;
            case 'p-dragover':
                this._evtDragOver(event);
                break;
            case 'p-drop':
                this._evtDrop(event);
                break;
            default:
                break;
        }
    }
    /**
     * Handle `after-attach` messages for the widget.
     */
    onAfterAttach(msg) {
        super.onAfterAttach(msg);
        let node = this.node;
        node.addEventListener('contextmenu', this, true);
        node.addEventListener('mousedown', this, true);
        node.addEventListener('mousedown', this);
        node.addEventListener('keydown', this);
        node.addEventListener('dblclick', this);
        node.addEventListener('focusin', this);
        node.addEventListener('focusout', this);
        node.addEventListener('p-dragenter', this);
        node.addEventListener('p-dragleave', this);
        node.addEventListener('p-dragover', this);
        node.addEventListener('p-drop', this);
    }
    /**
     * Handle `before-detach` messages for the widget.
     */
    onBeforeDetach(msg) {
        let node = this.node;
        node.removeEventListener('contextmenu', this, true);
        node.removeEventListener('mousedown', this, true);
        node.removeEventListener('mousedown', this);
        node.removeEventListener('keydown', this);
        node.removeEventListener('dblclick', this);
        node.removeEventListener('focusin', this);
        node.removeEventListener('focusout', this);
        node.removeEventListener('p-dragenter', this);
        node.removeEventListener('p-dragleave', this);
        node.removeEventListener('p-dragover', this);
        node.removeEventListener('p-drop', this);
        document.removeEventListener('mousemove', this, true);
        document.removeEventListener('mouseup', this, true);
    }
    /**
     * Handle `'activate-request'` messages.
     */
    onActivateRequest(msg) {
        this._ensureFocus(true);
    }
    /**
     * Handle `update-request` messages sent to the widget.
     */
    onUpdateRequest(msg) {
        let activeCell = this.activeCell;
        // Set the appropriate classes on the cells.
        if (this.mode === 'edit') {
            this.addClass(EDIT_CLASS);
            this.removeClass(COMMAND_CLASS);
        }
        else {
            this.addClass(COMMAND_CLASS);
            this.removeClass(EDIT_CLASS);
        }
        if (activeCell) {
            activeCell.addClass(ACTIVE_CLASS);
        }
        let count = 0;
        algorithm_1.each(this.widgets, widget => {
            if (widget !== activeCell) {
                widget.removeClass(ACTIVE_CLASS);
            }
            widget.removeClass(OTHER_SELECTED_CLASS);
            if (this.isSelectedOrActive(widget)) {
                widget.addClass(SELECTED_CLASS);
                count++;
            }
            else {
                widget.removeClass(SELECTED_CLASS);
            }
        });
        if (count > 1) {
            activeCell.addClass(OTHER_SELECTED_CLASS);
        }
    }
    /**
     * Handle a cell being inserted.
     */
    onCellInserted(index, cell) {
        if (this.model && this.model.modelDB.isCollaborative) {
            let modelDB = this.model.modelDB;
            modelDB.connected.then(() => {
                if (!cell.isDisposed) {
                    // Setup the selection style for collaborators.
                    let localCollaborator = modelDB.collaborators.localCollaborator;
                    cell.editor.uuid = localCollaborator.sessionId;
                    cell.editor.selectionStyle = Object.assign({}, codeeditor_1.CodeEditor.defaultSelectionStyle, { color: localCollaborator.color });
                }
            });
        }
        cell.editor.edgeRequested.connect(this._onEdgeRequest, this);
        // If the insertion happened above, increment the active cell
        // index, otherwise it stays the same.
        this.activeCellIndex =
            index <= this.activeCellIndex
                ? this.activeCellIndex + 1
                : this.activeCellIndex;
    }
    /**
     * Handle a cell being moved.
     */
    onCellMoved(fromIndex, toIndex) {
        let i = this.activeCellIndex;
        if (fromIndex === i) {
            this.activeCellIndex = toIndex;
        }
        else if (fromIndex < i && i <= toIndex) {
            this.activeCellIndex--;
        }
        else if (toIndex <= i && i < fromIndex) {
            this.activeCellIndex++;
        }
    }
    /**
     * Handle a cell being removed.
     */
    onCellRemoved(index, cell) {
        // If the removal happened above, decrement the active
        // cell index, otherwise it stays the same.
        this.activeCellIndex =
            index <= this.activeCellIndex
                ? this.activeCellIndex - 1
                : this.activeCellIndex;
        if (this.isSelected(cell)) {
            this._selectionChanged.emit(void 0);
        }
    }
    /**
     * Handle a new model.
     */
    onModelChanged(oldValue, newValue) {
        super.onModelChanged(oldValue, newValue);
        // Try to set the active cell index to 0.
        // It will be set to `-1` if there is no new model or the model is empty.
        this.activeCellIndex = 0;
    }
    /**
     * Handle edge request signals from cells.
     */
    _onEdgeRequest(editor, location) {
        let prev = this.activeCellIndex;
        if (location === 'top') {
            this.activeCellIndex--;
            // Move the cursor to the first position on the last line.
            if (this.activeCellIndex < prev) {
                let editor = this.activeCell.editor;
                let lastLine = editor.lineCount - 1;
                editor.setCursorPosition({ line: lastLine, column: 0 });
            }
        }
        else {
            this.activeCellIndex++;
            // Move the cursor to the first character.
            if (this.activeCellIndex > prev) {
                let editor = this.activeCell.editor;
                editor.setCursorPosition({ line: 0, column: 0 });
            }
        }
        this.mode = 'edit';
    }
    /**
     * Ensure that the notebook has proper focus.
     */
    _ensureFocus(force = false) {
        let activeCell = this.activeCell;
        if (this.mode === 'edit' && activeCell) {
            if (!activeCell.editor.hasFocus()) {
                activeCell.editor.focus();
            }
        }
        if (force && !this.node.contains(document.activeElement)) {
            this.node.focus();
        }
    }
    /**
     * Find the cell index containing the target html element.
     *
     * #### Notes
     * Returns -1 if the cell is not found.
     */
    _findCell(node) {
        // Trace up the DOM hierarchy to find the root cell node.
        // Then find the corresponding child and select it.
        while (node && node !== this.node) {
            if (node.classList.contains(NB_CELL_CLASS)) {
                let i = algorithm_1.ArrayExt.findFirstIndex(this.widgets, widget => widget.node === node);
                if (i !== -1) {
                    return i;
                }
                break;
            }
            node = node.parentElement;
        }
        return -1;
    }
    /**
     * Handle `contextmenu` event.
     */
    _evtContextMenuCapture(event) {
        // Allow the event to propagate un-modified if the user
        // is holding the shift-key (and probably requesting
        // the native context menu).
        if (event.shiftKey) {
            return;
        }
        // `event.target` sometimes gives an orphaned node in Firefox 57, which
        // can have `null` anywhere in its parent tree. If we fail to find a
        // cell using `event.target`, try again using a target reconstructed from
        // the position of the click event.
        let target = event.target;
        let index = this._findCell(target);
        if (index === -1) {
            target = document.elementFromPoint(event.clientX, event.clientY);
            index = this._findCell(target);
        }
        let widget = this.widgets[index];
        if (widget && widget.editorWidget.node.contains(target)) {
            // Prevent CodeMirror from focusing the editor.
            // TODO: find an editor-agnostic solution.
            event.preventDefault();
        }
    }
    /**
     * Handle `mousedown` event in the capture phase for the widget.
     */
    _evtMouseDownCapture(event) {
        const { button, shiftKey } = event;
        // `event.target` sometimes gives an orphaned node in Firefox 57, which
        // can have `null` anywhere in its parent tree. If we fail to find a
        // cell using `event.target`, try again using a target reconstructed from
        // the position of the click event.
        let target = event.target;
        let index = this._findCell(target);
        if (index === -1) {
            target = document.elementFromPoint(event.clientX, event.clientY);
            index = this._findCell(target);
        }
        let widget = this.widgets[index];
        // On OS X, the context menu may be triggered with ctrl-left-click. In
        // Firefox, ctrl-left-click gives an event with button 2, but in Chrome,
        // ctrl-left-click gives an event with button 0 with the ctrl modifier.
        if (button === 2 &&
            !shiftKey &&
            widget &&
            widget.editorWidget.node.contains(target)) {
            this.mode = 'command';
            // Prevent CodeMirror from focusing the editor.
            // TODO: find an editor-agnostic solution.
            event.preventDefault();
        }
    }
    /**
     * Handle `mousedown` events for the widget.
     */
    _evtMouseDown(event) {
        const { button, shiftKey } = event;
        // We only handle main or secondary button actions.
        if (!(button === 0 || button === 2)) {
            return;
        }
        // Shift right-click gives the browser default behavior.
        if (shiftKey && button === 2) {
            return;
        }
        // Find the target cell.
        let target = event.target;
        let index = this._findCell(target);
        if (index === -1) {
            // `event.target` sometimes gives an orphaned node in
            // Firefox 57, which can have `null` anywhere in its parent line. If we fail
            // to find a cell using `event.target`, try again using a target
            // reconstructed from the position of the click event.
            target = document.elementFromPoint(event.clientX, event.clientY);
            index = this._findCell(target);
        }
        let widget = this.widgets[index];
        let targetArea;
        if (widget) {
            if (widget.editorWidget.node.contains(target)) {
                targetArea = 'input';
            }
            else if (widget.promptNode.contains(target)) {
                targetArea = 'prompt';
            }
            else {
                targetArea = 'cell';
            }
        }
        else {
            targetArea = 'notebook';
        }
        // Make sure we go to command mode if the click isn't in the cell editor If
        // we do click in the cell editor, the editor handles the focus event to
        // switch to edit mode.
        if (targetArea !== 'input') {
            this.mode = 'command';
        }
        if (targetArea === 'notebook') {
            this.deselectAll();
        }
        else if (targetArea === 'prompt' || targetArea === 'cell') {
            if (button === 0 && shiftKey) {
                // Prevent browser selecting text in prompt or output
                event.preventDefault();
                // Shift-click - extend selection
                try {
                    this.extendContiguousSelectionTo(index);
                }
                catch (e) {
                    console.error(e);
                    this.deselectAll();
                    return;
                }
                // Enter selecting mode
                this._mouseMode = 'select';
                document.addEventListener('mouseup', this, true);
                document.addEventListener('mousemove', this, true);
            }
            else if (button === 0 && !shiftKey) {
                // Prepare to start a drag if we are on the drag region. TODO: If there is no drag, we'll deselect on mouseup.
                if (targetArea === 'prompt' && this.isSelectedOrActive(widget)) {
                    // Prepare for a drag start
                    this._dragData = {
                        pressX: event.clientX,
                        pressY: event.clientY,
                        index: index
                    };
                    // Enter possible drag mode
                    this._mouseMode = 'couldDrag';
                    document.addEventListener('mouseup', this, true);
                    document.addEventListener('mousemove', this, true);
                    event.preventDefault();
                }
                else {
                    this.deselectAll();
                    this.activeCellIndex = index;
                }
            }
            else if (button === 2) {
                if (!this.isSelectedOrActive(widget)) {
                    this.deselectAll();
                    this.activeCellIndex = index;
                }
                event.preventDefault();
            }
        }
        else if (targetArea === 'input') {
            if (button === 2 && !this.isSelectedOrActive(widget)) {
                this.deselectAll();
                this.activeCellIndex = index;
            }
        }
        // If we didn't set focus above, make sure we get focus now.
        this._ensureFocus(true);
    }
    /**
     * Handle the `'mouseup'` event on the document.
     */
    _evtDocumentMouseup(event) {
        // Remove the event listeners we put on the document
        document.removeEventListener('mousemove', this, true);
        document.removeEventListener('mouseup', this, true);
        if (this._mouseMode === 'couldDrag') {
            // We didn't end up dragging if we are here, so treat it as a click event.
            // Find the target cell.
            let target = event.target;
            let index = this._findCell(target);
            if (index === -1) {
                // `event.target` sometimes gives an orphaned node in
                // Firefox 57, which can have `null` anywhere in its parent line. If we fail
                // to find a cell using `event.target`, try again using a target
                // reconstructed from the position of the click event.
                target = document.elementFromPoint(event.clientX, event.clientY);
                index = this._findCell(target);
            }
            this.deselectAll();
            this.activeCellIndex = index;
        }
        this._mouseMode = null;
        event.preventDefault();
        event.stopPropagation();
    }
    /**
     * Handle the `'mousemove'` event for the widget.
     */
    _evtDocumentMousemove(event) {
        event.preventDefault();
        event.stopPropagation();
        // If in select mode, update the selection
        switch (this._mouseMode) {
            case 'select':
                let target = event.target;
                let index = this._findCell(target);
                if (index !== -1) {
                    this.extendContiguousSelectionTo(index);
                }
                break;
            case 'couldDrag':
                // Check for a drag initialization.
                let data = this._dragData;
                let dx = Math.abs(event.clientX - data.pressX);
                let dy = Math.abs(event.clientY - data.pressY);
                if (dx >= DRAG_THRESHOLD || dy >= DRAG_THRESHOLD) {
                    this._mouseMode = null;
                    this._startDrag(data.index, event.clientX, event.clientY);
                }
                break;
            default:
                break;
        }
    }
    /**
     * Handle the `'p-dragenter'` event for the widget.
     */
    _evtDragEnter(event) {
        if (!event.mimeData.hasData(JUPYTER_CELL_MIME)) {
            return;
        }
        event.preventDefault();
        event.stopPropagation();
        let target = event.target;
        let index = this._findCell(target);
        if (index === -1) {
            return;
        }
        let widget = this.layout.widgets[index];
        widget.node.classList.add(DROP_TARGET_CLASS);
    }
    /**
     * Handle the `'p-dragleave'` event for the widget.
     */
    _evtDragLeave(event) {
        if (!event.mimeData.hasData(JUPYTER_CELL_MIME)) {
            return;
        }
        event.preventDefault();
        event.stopPropagation();
        let elements = this.node.getElementsByClassName(DROP_TARGET_CLASS);
        if (elements.length) {
            elements[0].classList.remove(DROP_TARGET_CLASS);
        }
    }
    /**
     * Handle the `'p-dragover'` event for the widget.
     */
    _evtDragOver(event) {
        if (!event.mimeData.hasData(JUPYTER_CELL_MIME)) {
            return;
        }
        event.preventDefault();
        event.stopPropagation();
        event.dropAction = event.proposedAction;
        let elements = this.node.getElementsByClassName(DROP_TARGET_CLASS);
        if (elements.length) {
            elements[0].classList.remove(DROP_TARGET_CLASS);
        }
        let target = event.target;
        let index = this._findCell(target);
        if (index === -1) {
            return;
        }
        let widget = this.layout.widgets[index];
        widget.node.classList.add(DROP_TARGET_CLASS);
    }
    /**
     * Handle the `'p-drop'` event for the widget.
     */
    _evtDrop(event) {
        if (!event.mimeData.hasData(JUPYTER_CELL_MIME)) {
            return;
        }
        event.preventDefault();
        event.stopPropagation();
        if (event.proposedAction === 'none') {
            event.dropAction = 'none';
            return;
        }
        let target = event.target;
        while (target && target.parentElement) {
            if (target.classList.contains(DROP_TARGET_CLASS)) {
                target.classList.remove(DROP_TARGET_CLASS);
                break;
            }
            target = target.parentElement;
        }
        let source = event.source;
        if (source === this) {
            // Handle the case where we are moving cells within
            // the same notebook.
            event.dropAction = 'move';
            let toMove = event.mimeData.getData('internal:cells');
            // Compute the to/from indices for the move.
            let fromIndex = algorithm_1.ArrayExt.firstIndexOf(this.widgets, toMove[0]);
            let toIndex = this._findCell(target);
            // This check is needed for consistency with the view.
            if (toIndex !== -1 && toIndex > fromIndex) {
                toIndex -= 1;
            }
            else if (toIndex === -1) {
                // If the drop is within the notebook but not on any cell,
                // most often this means it is past the cell areas, so
                // set it to move the cells to the end of the notebook.
                toIndex = this.widgets.length - 1;
            }
            // Don't move if we are within the block of selected cells.
            if (toIndex >= fromIndex && toIndex < fromIndex + toMove.length) {
                return;
            }
            // Move the cells one by one
            this.model.cells.beginCompoundOperation();
            if (fromIndex < toIndex) {
                algorithm_1.each(toMove, cellWidget => {
                    this.model.cells.move(fromIndex, toIndex);
                });
            }
            else if (fromIndex > toIndex) {
                algorithm_1.each(toMove, cellWidget => {
                    this.model.cells.move(fromIndex++, toIndex++);
                });
            }
            this.model.cells.endCompoundOperation();
        }
        else {
            // Handle the case where we are copying cells between
            // notebooks.
            event.dropAction = 'copy';
            // Find the target cell and insert the copied cells.
            let index = this._findCell(target);
            if (index === -1) {
                index = this.widgets.length;
            }
            let start = index;
            let model = this.model;
            let values = event.mimeData.getData(JUPYTER_CELL_MIME);
            let factory = model.contentFactory;
            // Insert the copies of the original cells.
            model.cells.beginCompoundOperation();
            algorithm_1.each(values, (cell) => {
                let value;
                switch (cell.cell_type) {
                    case 'code':
                        value = factory.createCodeCell({ cell });
                        break;
                    case 'markdown':
                        value = factory.createMarkdownCell({ cell });
                        break;
                    default:
                        value = factory.createRawCell({ cell });
                        break;
                }
                model.cells.insert(index++, value);
            });
            model.cells.endCompoundOperation();
            // Select the inserted cells.
            this.deselectAll();
            this.activeCellIndex = start;
            this.extendContiguousSelectionTo(index - 1);
        }
    }
    /**
     * Start a drag event.
     */
    _startDrag(index, clientX, clientY) {
        let cells = this.model.cells;
        let selected = [];
        let toMove = [];
        algorithm_1.each(this.widgets, (widget, i) => {
            let cell = cells.get(i);
            if (this.isSelectedOrActive(widget)) {
                widget.addClass(DROP_SOURCE_CLASS);
                selected.push(cell.toJSON());
                toMove.push(widget);
            }
        });
        let activeCell = this.activeCell;
        let dragImage = null;
        let countString;
        if (activeCell.model.type === 'code') {
            let executionCount = activeCell.model.executionCount;
            countString = ' ';
            if (executionCount) {
                countString = executionCount.toString();
            }
        }
        else {
            countString = '';
        }
        // Create the drag image.
        dragImage = Private.createDragImage(selected.length, countString, activeCell.model.value.text.split('\n')[0].slice(0, 26));
        // Set up the drag event.
        this._drag = new dragdrop_1.Drag({
            mimeData: new coreutils_1.MimeData(),
            dragImage,
            supportedActions: 'copy-move',
            proposedAction: 'copy',
            source: this
        });
        this._drag.mimeData.setData(JUPYTER_CELL_MIME, selected);
        // Add mimeData for the fully reified cell widgets, for the
        // case where the target is in the same notebook and we
        // can just move the cells.
        this._drag.mimeData.setData('internal:cells', toMove);
        // Remove mousemove and mouseup listeners and start the drag.
        document.removeEventListener('mousemove', this, true);
        document.removeEventListener('mouseup', this, true);
        this._mouseMode = null;
        this._drag.start(clientX, clientY).then(action => {
            if (this.isDisposed) {
                return;
            }
            this._drag = null;
            algorithm_1.each(toMove, widget => {
                widget.removeClass(DROP_SOURCE_CLASS);
            });
        });
    }
    /**
     * Handle `focus` events for the widget.
     */
    _evtFocusIn(event) {
        let target = event.target;
        let i = this._findCell(target);
        if (i !== -1) {
            let widget = this.widgets[i];
            // If the editor itself does not have focus, ensure command mode.
            if (!widget.editorWidget.node.contains(target)) {
                this.mode = 'command';
            }
            this.activeCellIndex = i;
            // If the editor has focus, ensure edit mode.
            let node = widget.editorWidget.node;
            if (node.contains(target)) {
                this.mode = 'edit';
            }
        }
        else {
            // No cell has focus, ensure command mode.
            this.mode = 'command';
        }
        if (this.mode === 'command' && target !== this.node) {
            delete this.node.dataset[CODE_RUNNER];
        }
        else {
            this.node.dataset[CODE_RUNNER] = 'true';
        }
    }
    /**
     * Handle `focusout` events for the notebook.
     */
    _evtFocusOut(event) {
        let relatedTarget = event.relatedTarget;
        // Bail if the window is losing focus, to preserve edit mode. This test
        // assumes that we explicitly focus things rather than calling blur()
        if (!relatedTarget) {
            return;
        }
        // Bail if the item gaining focus is another cell,
        // and we should not be entering command mode.
        const i = this._findCell(relatedTarget);
        if (i !== -1) {
            const widget = this.widgets[i];
            if (widget.editorWidget.node.contains(relatedTarget)) {
                return;
            }
        }
        // Otherwise enter command mode.
        this.mode = 'command';
    }
    /**
     * Handle `dblclick` events for the widget.
     */
    _evtDblClick(event) {
        let model = this.model;
        if (!model) {
            return;
        }
        this.deselectAll();
        // `event.target` sometimes gives an orphaned node in Firefox 57, which
        // can have `null` anywhere in its parent tree. If we fail to find a
        // cell using `event.target`, try again using a target reconstructed from
        // the position of the click event.
        let target = event.target;
        let i = this._findCell(target);
        if (i === -1) {
            target = document.elementFromPoint(event.clientX, event.clientY);
            i = this._findCell(target);
        }
        if (i === -1) {
            return;
        }
        this.activeCellIndex = i;
        if (model.cells.get(i).type === 'markdown') {
            let widget = this.widgets[i];
            widget.rendered = false;
        }
        else if (target.localName === 'img') {
            target.classList.toggle(UNCONFINED_CLASS);
        }
    }
    /**
     * Remove selections from inactive cells to avoid
     * spurious cursors.
     */
    _trimSelections() {
        for (let i = 0; i < this.widgets.length; i++) {
            if (i !== this._activeCellIndex) {
                let cell = this.widgets[i];
                cell.model.selections.delete(cell.editor.uuid);
            }
        }
    }
}
exports.Notebook = Notebook;
/**
 * The namespace for the `Notebook` class statics.
 */
(function (Notebook) {
    /**
     * The default implementation of a notebook content factory..
     *
     * #### Notes
     * Override methods on this class to customize the default notebook factory
     * methods that create notebook content.
     */
    class ContentFactory extends StaticNotebook.ContentFactory {
    }
    Notebook.ContentFactory = ContentFactory;
    Notebook.defaultContentFactory = new ContentFactory();
})(Notebook = exports.Notebook || (exports.Notebook = {}));
/**
 * A namespace for private data.
 */
var Private;
(function (Private) {
    /**
     * An attached property for the selected state of a cell.
     */
    Private.selectedProperty = new properties_1.AttachedProperty({
        name: 'selected',
        create: () => false
    });
    /**
     * A custom panel layout for the notebook.
     */
    class NotebookPanelLayout extends widgets_1.PanelLayout {
        /**
         * A message handler invoked on an `'update-request'` message.
         *
         * #### Notes
         * This is a reimplementation of the base class method,
         * and is a no-op.
         */
        onUpdateRequest(msg) {
            // This is a no-op.
        }
    }
    Private.NotebookPanelLayout = NotebookPanelLayout;
    /**
     * Create a cell drag image.
     */
    function createDragImage(count, promptNumber, cellContent) {
        if (count > 1) {
            if (promptNumber !== '') {
                return virtualdom_1.VirtualDOM.realize(virtualdom_1.h.div(virtualdom_1.h.div({ className: DRAG_IMAGE_CLASS }, virtualdom_1.h.span({ className: CELL_DRAG_PROMPT_CLASS }, '[' + promptNumber + ']:'), virtualdom_1.h.span({ className: CELL_DRAG_CONTENT_CLASS }, cellContent)), virtualdom_1.h.div({ className: CELL_DRAG_MULTIPLE_BACK }, '')));
            }
            else {
                return virtualdom_1.VirtualDOM.realize(virtualdom_1.h.div(virtualdom_1.h.div({ className: DRAG_IMAGE_CLASS }, virtualdom_1.h.span({ className: CELL_DRAG_PROMPT_CLASS }), virtualdom_1.h.span({ className: CELL_DRAG_CONTENT_CLASS }, cellContent)), virtualdom_1.h.div({ className: CELL_DRAG_MULTIPLE_BACK }, '')));
            }
        }
        else {
            if (promptNumber !== '') {
                return virtualdom_1.VirtualDOM.realize(virtualdom_1.h.div(virtualdom_1.h.div({ className: `${DRAG_IMAGE_CLASS} ${SINGLE_DRAG_IMAGE_CLASS}` }, virtualdom_1.h.span({ className: CELL_DRAG_PROMPT_CLASS }, '[' + promptNumber + ']:'), virtualdom_1.h.span({ className: CELL_DRAG_CONTENT_CLASS }, cellContent))));
            }
            else {
                return virtualdom_1.VirtualDOM.realize(virtualdom_1.h.div(virtualdom_1.h.div({ className: `${DRAG_IMAGE_CLASS} ${SINGLE_DRAG_IMAGE_CLASS}` }, virtualdom_1.h.span({ className: CELL_DRAG_PROMPT_CLASS }), virtualdom_1.h.span({ className: CELL_DRAG_CONTENT_CLASS }, cellContent))));
            }
        }
    }
    Private.createDragImage = createDragImage;
    /**
     * Process the `IOptions` passed to the notebook widget.
     *
     * #### Notes
     * This defaults the content factory to that in the `Notebook` namespace.
     */
    function processNotebookOptions(options) {
        if (options.contentFactory) {
            return options;
        }
        else {
            return {
                rendermime: options.rendermime,
                languagePreference: options.languagePreference,
                contentFactory: Notebook.defaultContentFactory,
                mimeTypeService: options.mimeTypeService
            };
        }
    }
    Private.processNotebookOptions = processNotebookOptions;
})(Private || (Private = {}));


/***/ }),

/***/ "qZTm":
/*!********************************************!*\
  !*** ./node_modules/lodash/_getAllKeys.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseGetAllKeys = __webpack_require__(/*! ./_baseGetAllKeys */ "fR/l"),
    getSymbols = __webpack_require__(/*! ./_getSymbols */ "MvSz"),
    keys = __webpack_require__(/*! ./keys */ "7GkX");

/**
 * 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);
}

module.exports = getAllKeys;


/***/ }),

/***/ "qcc5":
/*!*****************************************************************!*\
  !*** ./node_modules/@jupyter-widgets/base/lib/widget_layout.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = __webpack_require__(/*! ./utils */ "o9P/");
var widget_1 = __webpack_require__(/*! ./widget */ "rynU");
/**
 * css properties exposed by the layout widget with their default values.
 */
var css_properties = {
    align_content: null,
    align_items: null,
    align_self: null,
    border: null,
    bottom: null,
    display: null,
    flex: null,
    flex_flow: null,
    height: null,
    justify_content: null,
    left: null,
    margin: null,
    max_height: null,
    max_width: null,
    min_height: null,
    min_width: null,
    overflow: null,
    overflow_x: null,
    overflow_y: null,
    order: null,
    padding: null,
    right: null,
    top: null,
    visibility: null,
    width: null,
    // container
    grid_auto_columns: null,
    grid_auto_flow: null,
    grid_auto_rows: null,
    grid_gap: null,
    grid_template_rows: null,
    grid_template_columns: null,
    grid_template_areas: null,
    // items
    grid_row: null,
    grid_column: null,
    grid_area: null
};
var LayoutModel = /** @class */ (function (_super) {
    __extends(LayoutModel, _super);
    function LayoutModel() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    LayoutModel.prototype.defaults = function () {
        return utils_1.assign(_super.prototype.defaults.call(this), {
            _model_name: 'LayoutModel',
            _view_name: 'LayoutView'
        }, css_properties);
    };
    return LayoutModel;
}(widget_1.WidgetModel));
exports.LayoutModel = LayoutModel;
var LayoutView = /** @class */ (function (_super) {
    __extends(LayoutView, _super);
    function LayoutView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    /**
     * Public constructor
     */
    LayoutView.prototype.initialize = function (parameters) {
        this._traitNames = [];
        _super.prototype.initialize.call(this, parameters);
        // Register the traits that live on the Python side
        for (var _i = 0, _a = Object.keys(css_properties); _i < _a.length; _i++) {
            var key = _a[_i];
            this.registerTrait(key);
        }
    };
    /**
     * Register a CSS trait that is known by the model
     * @param trait
     */
    LayoutView.prototype.registerTrait = function (trait) {
        var _this = this;
        this._traitNames.push(trait);
        // Listen to changes, and set the value on change.
        this.listenTo(this.model, 'change:' + trait, function (model, value) {
            _this.handleChange(trait, value);
        });
        // Set the initial value on display.
        this.handleChange(trait, this.model.get(trait));
    };
    /**
     * Get the the name of the css property from the trait name
     * @param  model attribute name
     * @return css property name
     */
    LayoutView.prototype.css_name = function (trait) {
        return trait.replace(/_/g, '-');
    };
    /**
     * Handles when a trait value changes
     */
    LayoutView.prototype.handleChange = function (trait, value) {
        // should be synchronous so that we can measure later.
        var parent = this.options.parent;
        if (parent) {
            if (value === null) {
                parent.el.style.removeProperty(this.css_name(trait));
            }
            else {
                parent.el.style[this.css_name(trait)] = value;
            }
        }
        else {
            console.warn('Style not applied because a parent view does not exist');
        }
    };
    /**
     * Remove the styling from the parent view.
     */
    LayoutView.prototype.unlayout = function () {
        var _this = this;
        var parent = this.options.parent;
        this._traitNames.forEach(function (trait) {
            if (parent) {
                parent.el.style.removeProperty(_this.css_name(trait));
            }
            else {
                console.warn('Style not removed because a parent view does not exist');
            }
        }, this);
    };
    return LayoutView;
}(widget_1.WidgetView));
exports.LayoutView = LayoutView;


/***/ }),

/***/ "qd8s":
/*!************************************************!*\
  !*** ./node_modules/lodash.mergewith/index.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global, module) {/**
 * Lodash (Custom Build) <https://lodash.com/>
 * Build: `lodash modularize exports="npm" -o ./`
 * Copyright JS Foundation and other contributors <https://js.foundation/>
 * 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
 */

/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;

/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';

/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
    HOT_SPAN = 16;

/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;

/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
    arrayTag = '[object Array]',
    asyncTag = '[object AsyncFunction]',
    boolTag = '[object Boolean]',
    dateTag = '[object Date]',
    errorTag = '[object Error]',
    funcTag = '[object Function]',
    genTag = '[object GeneratorFunction]',
    mapTag = '[object Map]',
    numberTag = '[object Number]',
    nullTag = '[object Null]',
    objectTag = '[object Object]',
    proxyTag = '[object Proxy]',
    regexpTag = '[object RegExp]',
    setTag = '[object Set]',
    stringTag = '[object String]',
    undefinedTag = '[object Undefined]',
    weakMapTag = '[object WeakMap]';

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 `RegExp`
 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
 */
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;

/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;

/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;

/** 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;

/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;

/** 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 = typeof exports == 'object' && exports && !exports.nodeType && exports;

/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == '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 {
    return freeProcess && freeProcess.binding && freeProcess.binding('util');
  } catch (e) {}
}());

/* Node.js helper references. */
var 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);
}

/**
 * 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 `_.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);
  };
}

/**
 * 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];
}

/**
 * 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));
  };
}

/**
 * Gets the value at `key`, unless `key` is "__proto__".
 *
 * @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) {
  return key == '__proto__'
    ? undefined
    : object[key];
}

/** 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 = root['__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 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 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 ? root.Buffer : undefined,
    Symbol = root.Symbol,
    Uint8Array = root.Uint8Array,
    allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined,
    getPrototype = overArg(Object.getPrototypeOf, Object),
    objectCreate = Object.create,
    propertyIsEnumerable = objectProto.propertyIsEnumerable,
    splice = arrayProto.splice,
    symToStringTag = Symbol ? Symbol.toStringTag : undefined;

var defineProperty = (function() {
  try {
    var func = getNative(Object, 'defineProperty');
    func({}, '', {});
    return func;
  } catch (e) {}
}());

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
    nativeMax = Math.max,
    nativeNow = Date.now;

/* Built-in method references that are verified to be native. */
var Map = getNative(root, 'Map'),
    nativeCreate = getNative(Object, 'create');

/**
 * 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;
  };
}());

/**
 * 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 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;
}

/**
 * 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;
}

/**
 * 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 `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();

/**
 * 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 `_.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 `_.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 `_.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 `_.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 `_.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) {
    if (isObject(srcValue)) {
      stack || (stack = new Stack);
      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) || (srcIndex && 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 `_.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 `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
  });
};

/**
 * 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 `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);
}

/**
 * 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;
}

/**
 * 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 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;
  };
}

/**
 * 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 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;
}

/**
 * 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))
    : {};
}

/**
 * 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 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 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 `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;
}

/**
 * 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);
  };
}

/**
 * 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);

/**
 * 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);
  };
}

/**
 * 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 '';
}

/**
 * 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 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 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 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 `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 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 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 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;

/**
 * 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));
}

/**
 * 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);
}

/**
 * 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);
});

/**
 * 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;
  };
}

/**
 * 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;
}

/**
 * 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;
}

module.exports = mergeWith;

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "yLpj"), __webpack_require__(/*! ./../webpack/buildin/module.js */ "YuTi")(module)))

/***/ }),

/***/ "qeiu":
/*!*******************************************************!*\
  !*** ./node_modules/@jupyterlab/mainmenu/lib/edit.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const labmenu_1 = __webpack_require__(/*! ./labmenu */ "e7FE");
/**
 * An extensible Edit menu for the application.
 */
class EditMenu extends labmenu_1.JupyterLabMenu {
    /**
     * Construct the edit menu.
     */
    constructor(options) {
        super(options);
        this.menu.title.label = 'Edit';
        this.undoers = new Set();
        this.clearers = new Set();
        this.findReplacers = new Set();
        this.goToLiners = new Set();
    }
    /**
     * Dispose of the resources held by the edit menu.
     */
    dispose() {
        this.undoers.clear();
        this.clearers.clear();
        this.findReplacers.clear();
        super.dispose();
    }
}
exports.EditMenu = EditMenu;


/***/ }),

/***/ "qeu3":
/*!******************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/notifier.js ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




var d3 = __webpack_require__(/*! d3 */ "bljh");
var isNumeric = __webpack_require__(/*! fast-isnumeric */ "GbLo");

var NOTEDATA = [];

/**
 * notifier
 * @param {String} text The person's user name
 * @param {Number} [delay=1000] The delay time in milliseconds
 *          or 'long' which provides 2000 ms delay time.
 * @return {undefined} this function does not return a value
 */
module.exports = function(text, displayLength) {
    if(NOTEDATA.indexOf(text) !== -1) return;

    NOTEDATA.push(text);

    var ts = 1000;
    if(isNumeric(displayLength)) ts = displayLength;
    else if(displayLength === 'long') ts = 3000;

    var notifierContainer = d3.select('body')
        .selectAll('.plotly-notifier')
        .data([0]);
    notifierContainer.enter()
        .append('div')
        .classed('plotly-notifier', true);

    var notes = notifierContainer.selectAll('.notifier-note').data(NOTEDATA);

    function killNote(transition) {
        transition
            .duration(700)
            .style('opacity', 0)
            .each('end', function(thisText) {
                var thisIndex = NOTEDATA.indexOf(thisText);
                if(thisIndex !== -1) NOTEDATA.splice(thisIndex, 1);
                d3.select(this).remove();
            });
    }

    notes.enter().append('div')
        .classed('notifier-note', true)
        .style('opacity', 0)
        .each(function(thisText) {
            var note = d3.select(this);

            note.append('button')
                .classed('notifier-close', true)
                .html('&times;')
                .on('click', function() {
                    note.transition().call(killNote);
                });

            var p = note.append('p');
            var lines = thisText.split(/<br\s*\/?>/g);
            for(var i = 0; i < lines.length; i++) {
                if(i) p.append('br');
                p.append('span').text(lines[i]);
            }

            note.transition()
                    .duration(700)
                    .style('opacity', 1)
                .transition()
                    .delay(ts)
                    .call(killNote);
        });
};


/***/ }),

/***/ "qhsb":
/*!**********************************************************!*\
  !*** ./node_modules/@jupyterlab/notebook/lib/actions.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const cells_1 = __webpack_require__(/*! @jupyterlab/cells */ "USP6");
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const domutils_1 = __webpack_require__(/*! @phosphor/domutils */ "XWTc");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const React = __importStar(__webpack_require__(/*! react */ "q1tI"));
// The message to display to the user when prompting to trust the notebook.
const TRUST_MESSAGE = (React.createElement("p", null,
    "A trusted Jupyter notebook may execute hidden malicious code when you open it.",
    React.createElement("br", null),
    "Selecting trust will re-render this notebook in a trusted state.",
    React.createElement("br", null),
    "For more information, see the",
    React.createElement("a", { href: "https://jupyter-notebook.readthedocs.io/en/stable/security.html" }, "Jupyter security documentation")));
/**
 * The mimetype used for Jupyter cell data.
 */
const JUPYTER_CELL_MIME = 'application/vnd.jupyter.cells';
/**
 * A collection of actions that run against notebooks.
 *
 * #### Notes
 * All of the actions are a no-op if there is no model on the notebook.
 * The actions set the widget `mode` to `'command'` unless otherwise specified.
 * The actions will preserve the selection on the notebook widget unless
 * otherwise specified.
 */
class NotebookActions {
    /**
     * A signal that emits whenever a cell is run.
     */
    static get executed() {
        return Private.executed;
    }
    /**
     * A private constructor for the `NotebookActions` class.
     *
     * #### Notes
     * This class can never be instantiated. Its static member `executed` will be
     * merged with the `NotebookActions` namespace. The reason it exists as a
     * standalone class is because at run time, the `Private.executed` variable
     * does not yet exist, so it needs to be referenced via a getter.
     */
    constructor() { }
}
exports.NotebookActions = NotebookActions;
/**
 * A namespace for `NotebookActions` static methods.
 */
(function (NotebookActions) {
    /**
     * Split the active cell into two cells.
     *
     * @param widget - The target notebook widget.
     *
     * #### Notes
     * It will preserve the existing mode.
     * The second cell will be activated.
     * The existing selection will be cleared.
     * The leading whitespace in the second cell will be removed.
     * If there is no content, two empty cells will be created.
     * Both cells will have the same type as the original cell.
     * This action can be undone.
     */
    function splitCell(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        notebook.deselectAll();
        const nbModel = notebook.model;
        const index = notebook.activeCellIndex;
        const child = notebook.widgets[index];
        const editor = child.editor;
        const position = editor.getCursorPosition();
        const offset = editor.getOffsetAt(position);
        const orig = child.model.value.text;
        // Create new models to preserve history.
        const clone0 = Private.cloneCell(nbModel, child.model);
        const clone1 = Private.cloneCell(nbModel, child.model);
        if (clone0.type === 'code') {
            clone0.outputs.clear();
        }
        clone0.value.text = orig
            .slice(0, offset)
            .replace(/^\n+/, '')
            .replace(/\n+$/, '');
        clone1.value.text = orig
            .slice(offset)
            .replace(/^\n+/, '')
            .replace(/\n+$/, '');
        // Make the changes while preserving history.
        const cells = nbModel.cells;
        cells.beginCompoundOperation();
        cells.set(index, clone0);
        cells.insert(index + 1, clone1);
        cells.endCompoundOperation();
        notebook.activeCellIndex++;
        Private.handleState(notebook, state);
    }
    NotebookActions.splitCell = splitCell;
    /**
     * Merge the selected cells.
     *
     * @param notebook - The target notebook widget.
     *
     * #### Notes
     * The widget mode will be preserved.
     * If only one cell is selected, the next cell will be selected.
     * If the active cell is a code cell, its outputs will be cleared.
     * This action can be undone.
     * The final cell will have the same type as the active cell.
     * If the active cell is a markdown cell, it will be unrendered.
     */
    function mergeCells(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        const toMerge = [];
        const toDelete = [];
        const model = notebook.model;
        const cells = model.cells;
        const primary = notebook.activeCell;
        const active = notebook.activeCellIndex;
        // Get the cells to merge.
        notebook.widgets.forEach((child, index) => {
            if (notebook.isSelectedOrActive(child)) {
                toMerge.push(child.model.value.text);
                if (index !== active) {
                    toDelete.push(child.model);
                }
            }
        });
        // Check for only a single cell selected.
        if (toMerge.length === 1) {
            // Bail if it is the last cell.
            if (active === cells.length - 1) {
                return;
            }
            // Otherwise merge with the next cell.
            const cellModel = cells.get(active + 1);
            toMerge.push(cellModel.value.text);
            toDelete.push(cellModel);
        }
        notebook.deselectAll();
        // Create a new cell for the source to preserve history.
        const newModel = Private.cloneCell(model, primary.model);
        newModel.value.text = toMerge.join('\n\n');
        if (newModel.type === 'code') {
            newModel.outputs.clear();
        }
        // Make the changes while preserving history.
        cells.beginCompoundOperation();
        cells.set(active, newModel);
        toDelete.forEach(cell => {
            cells.removeValue(cell);
        });
        cells.endCompoundOperation();
        // If the original cell is a markdown cell, make sure
        // the new cell is unrendered.
        if (primary instanceof cells_1.MarkdownCell) {
            notebook.activeCell.rendered = false;
        }
        Private.handleState(notebook, state);
    }
    NotebookActions.mergeCells = mergeCells;
    /**
     * Delete the selected cells.
     *
     * @param notebook - The target notebook widget.
     *
     * #### Notes
     * The cell after the last selected cell will be activated.
     * It will add a code cell if all cells are deleted.
     * This action can be undone.
     */
    function deleteCells(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        Private.deleteCells(notebook);
        Private.handleState(notebook, state);
    }
    NotebookActions.deleteCells = deleteCells;
    /**
     * Insert a new code cell above the active cell.
     *
     * @param notebook - The target notebook widget.
     *
     * #### Notes
     * The widget mode will be preserved.
     * This action can be undone.
     * The existing selection will be cleared.
     * The new cell will the active cell.
     */
    function insertAbove(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        const model = notebook.model;
        const cell = model.contentFactory.createCodeCell({});
        const active = notebook.activeCellIndex;
        model.cells.insert(active, cell);
        // Make the newly inserted cell active.
        notebook.activeCellIndex = active;
        notebook.deselectAll();
        Private.handleState(notebook, state, true);
    }
    NotebookActions.insertAbove = insertAbove;
    /**
     * Insert a new code cell below the active cell.
     *
     * @param notebook - The target notebook widget.
     *
     * #### Notes
     * The widget mode will be preserved.
     * This action can be undone.
     * The existing selection will be cleared.
     * The new cell will be the active cell.
     */
    function insertBelow(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        const model = notebook.model;
        const cell = model.contentFactory.createCodeCell({});
        model.cells.insert(notebook.activeCellIndex + 1, cell);
        // Make the newly inserted cell active.
        notebook.activeCellIndex++;
        notebook.deselectAll();
        Private.handleState(notebook, state, true);
    }
    NotebookActions.insertBelow = insertBelow;
    /**
     * Move the selected cell(s) down.
     *
     * @param notebook = The target notebook widget.
     */
    function moveDown(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        const cells = notebook.model.cells;
        const widgets = notebook.widgets;
        cells.beginCompoundOperation();
        for (let i = cells.length - 2; i > -1; i--) {
            if (notebook.isSelectedOrActive(widgets[i])) {
                if (!notebook.isSelectedOrActive(widgets[i + 1])) {
                    cells.move(i, i + 1);
                    if (notebook.activeCellIndex === i) {
                        notebook.activeCellIndex++;
                    }
                    notebook.select(widgets[i + 1]);
                    notebook.deselect(widgets[i]);
                }
            }
        }
        cells.endCompoundOperation();
        Private.handleState(notebook, state, true);
    }
    NotebookActions.moveDown = moveDown;
    /**
     * Move the selected cell(s) up.
     *
     * @param widget - The target notebook widget.
     */
    function moveUp(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        const cells = notebook.model.cells;
        const widgets = notebook.widgets;
        cells.beginCompoundOperation();
        for (let i = 1; i < cells.length; i++) {
            if (notebook.isSelectedOrActive(widgets[i])) {
                if (!notebook.isSelectedOrActive(widgets[i - 1])) {
                    cells.move(i, i - 1);
                    if (notebook.activeCellIndex === i) {
                        notebook.activeCellIndex--;
                    }
                    notebook.select(widgets[i - 1]);
                    notebook.deselect(widgets[i]);
                }
            }
        }
        cells.endCompoundOperation();
        Private.handleState(notebook, state, true);
    }
    NotebookActions.moveUp = moveUp;
    /**
     * Change the selected cell type(s).
     *
     * @param notebook - The target notebook widget.
     *
     * @param value - The target cell type.
     *
     * #### Notes
     * It should preserve the widget mode.
     * This action can be undone.
     * The existing selection will be cleared.
     * Any cells converted to markdown will be unrendered.
     */
    function changeCellType(notebook, value) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        Private.changeCellType(notebook, value);
        Private.handleState(notebook, state);
    }
    NotebookActions.changeCellType = changeCellType;
    /**
     * Run the selected cell(s).
     *
     * @param notebook - The target notebook widget.
     *
     * @param session - The optional client session object.
     *
     * #### Notes
     * The last selected cell will be activated, but not scrolled into view.
     * The existing selection will be cleared.
     * An execution error will prevent the remaining code cells from executing.
     * All markdown cells will be rendered.
     */
    function run(notebook, session) {
        if (!notebook.model || !notebook.activeCell) {
            return Promise.resolve(false);
        }
        const state = Private.getState(notebook);
        const promise = Private.runSelected(notebook, session);
        Private.handleRunState(notebook, state, false);
        return promise;
    }
    NotebookActions.run = run;
    /**
     * Run the selected cell(s) and advance to the next cell.
     *
     * @param notebook - The target notebook widget.
     *
     * @param session - The optional client session object.
     *
     * #### Notes
     * The existing selection will be cleared.
     * The cell after the last selected cell will be activated and scrolled into view.
     * An execution error will prevent the remaining code cells from executing.
     * All markdown cells will be rendered.
     * If the last selected cell is the last cell, a new code cell
     * will be created in `'edit'` mode.  The new cell creation can be undone.
     */
    function runAndAdvance(notebook, session) {
        if (!notebook.model || !notebook.activeCell) {
            return Promise.resolve(false);
        }
        const state = Private.getState(notebook);
        const promise = Private.runSelected(notebook, session);
        const model = notebook.model;
        if (notebook.activeCellIndex === notebook.widgets.length - 1) {
            const cell = model.contentFactory.createCodeCell({});
            model.cells.push(cell);
            notebook.activeCellIndex++;
            notebook.mode = 'edit';
        }
        else {
            notebook.activeCellIndex++;
        }
        Private.handleRunState(notebook, state, true);
        return promise;
    }
    NotebookActions.runAndAdvance = runAndAdvance;
    /**
     * Run the selected cell(s) and insert a new code cell.
     *
     * @param notebook - The target notebook widget.
     *
     * @param session - The optional client session object.
     *
     * #### Notes
     * An execution error will prevent the remaining code cells from executing.
     * All markdown cells will be rendered.
     * The widget mode will be set to `'edit'` after running.
     * The existing selection will be cleared.
     * The cell insert can be undone.
     * The new cell will be scrolled into view.
     */
    function runAndInsert(notebook, session) {
        if (!notebook.model || !notebook.activeCell) {
            return Promise.resolve(false);
        }
        const state = Private.getState(notebook);
        const promise = Private.runSelected(notebook, session);
        const model = notebook.model;
        const cell = model.contentFactory.createCodeCell({});
        model.cells.insert(notebook.activeCellIndex + 1, cell);
        notebook.activeCellIndex++;
        notebook.mode = 'edit';
        Private.handleRunState(notebook, state, true);
        return promise;
    }
    NotebookActions.runAndInsert = runAndInsert;
    /**
     * Run all of the cells in the notebook.
     *
     * @param notebook - The target notebook widget.
     *
     * @param session - The optional client session object.
     *
     * #### Notes
     * The existing selection will be cleared.
     * An execution error will prevent the remaining code cells from executing.
     * All markdown cells will be rendered.
     * The last cell in the notebook will be activated and scrolled into view.
     */
    function runAll(notebook, session) {
        if (!notebook.model || !notebook.activeCell) {
            return Promise.resolve(false);
        }
        const state = Private.getState(notebook);
        notebook.widgets.forEach(child => {
            notebook.select(child);
        });
        const promise = Private.runSelected(notebook, session);
        Private.handleRunState(notebook, state, true);
        return promise;
    }
    NotebookActions.runAll = runAll;
    /**
     * Run all of the cells before the currently active cell (exclusive).
     *
     * @param notebook - The target notebook widget.
     *
     * @param session - The optional client session object.
     *
     * #### Notes
     * The existing selection will be cleared.
     * An execution error will prevent the remaining code cells from executing.
     * All markdown cells will be rendered.
     * The currently active cell will remain selected.
     */
    function runAllAbove(notebook, session) {
        const { activeCell, activeCellIndex, model } = notebook;
        if (!model || !activeCell || activeCellIndex < 1) {
            return Promise.resolve(false);
        }
        const state = Private.getState(notebook);
        notebook.activeCellIndex--;
        notebook.deselectAll();
        for (let i = 0; i < notebook.activeCellIndex; ++i) {
            notebook.select(notebook.widgets[i]);
        }
        const promise = Private.runSelected(notebook, session);
        notebook.activeCellIndex++;
        Private.handleRunState(notebook, state, true);
        return promise;
    }
    NotebookActions.runAllAbove = runAllAbove;
    /**
     * Run all of the cells after the currently active cell (inclusive).
     *
     * @param notebook - The target notebook widget.
     *
     * @param session - The optional client session object.
     *
     * #### Notes
     * The existing selection will be cleared.
     * An execution error will prevent the remaining code cells from executing.
     * All markdown cells will be rendered.
     * The last cell in the notebook will be activated and scrolled into view.
     */
    function runAllBelow(notebook, session) {
        if (!notebook.model || !notebook.activeCell) {
            return Promise.resolve(false);
        }
        const state = Private.getState(notebook);
        notebook.deselectAll();
        for (let i = notebook.activeCellIndex; i < notebook.widgets.length; ++i) {
            notebook.select(notebook.widgets[i]);
        }
        const promise = Private.runSelected(notebook, session);
        Private.handleRunState(notebook, state, true);
        return promise;
    }
    NotebookActions.runAllBelow = runAllBelow;
    /**
     * Select the above the active cell.
     *
     * @param notebook - The target notebook widget.
     *
     * #### Notes
     * The widget mode will be preserved.
     * This is a no-op if the first cell is the active cell.
     * The existing selection will be cleared.
     */
    function selectAbove(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        if (notebook.activeCellIndex === 0) {
            return;
        }
        const state = Private.getState(notebook);
        notebook.activeCellIndex -= 1;
        notebook.deselectAll();
        Private.handleState(notebook, state, true);
    }
    NotebookActions.selectAbove = selectAbove;
    /**
     * Select the cell below the active cell.
     *
     * @param notebook - The target notebook widget.
     *
     * #### Notes
     * The widget mode will be preserved.
     * This is a no-op if the last cell is the active cell.
     * The existing selection will be cleared.
     */
    function selectBelow(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        if (notebook.activeCellIndex === notebook.widgets.length - 1) {
            return;
        }
        const state = Private.getState(notebook);
        notebook.activeCellIndex += 1;
        notebook.deselectAll();
        Private.handleState(notebook, state, true);
    }
    NotebookActions.selectBelow = selectBelow;
    /**
     * Extend the selection to the cell above.
     *
     * @param notebook - The target notebook widget.
     *
     * #### Notes
     * This is a no-op if the first cell is the active cell.
     * The new cell will be activated.
     */
    function extendSelectionAbove(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        // Do not wrap around.
        if (notebook.activeCellIndex === 0) {
            return;
        }
        const state = Private.getState(notebook);
        notebook.mode = 'command';
        notebook.extendContiguousSelectionTo(notebook.activeCellIndex - 1);
        Private.handleState(notebook, state, true);
    }
    NotebookActions.extendSelectionAbove = extendSelectionAbove;
    /**
     * Extend the selection to the cell below.
     *
     * @param notebook - The target notebook widget.
     *
     * #### Notes
     * This is a no-op if the last cell is the active cell.
     * The new cell will be activated.
     */
    function extendSelectionBelow(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        // Do not wrap around.
        if (notebook.activeCellIndex === notebook.widgets.length - 1) {
            return;
        }
        const state = Private.getState(notebook);
        notebook.mode = 'command';
        notebook.extendContiguousSelectionTo(notebook.activeCellIndex + 1);
        Private.handleState(notebook, state, true);
    }
    NotebookActions.extendSelectionBelow = extendSelectionBelow;
    /**
     * Select all of the cells of the notebook.
     *
     * @param notebook - the target notebook widget.
     */
    function selectAll(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        notebook.widgets.forEach(child => {
            notebook.select(child);
        });
    }
    NotebookActions.selectAll = selectAll;
    /**
     * Deselect all of the cells of the notebook.
     *
     * @param notebook - the targe notebook widget.
     */
    function deselectAll(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        notebook.deselectAll();
    }
    NotebookActions.deselectAll = deselectAll;
    /**
     * Copy the selected cell data to a clipboard.
     *
     * @param notebook - The target notebook widget.
     */
    function copy(notebook) {
        Private.copyOrCut(notebook, false);
    }
    NotebookActions.copy = copy;
    /**
     * Cut the selected cell data to a clipboard.
     *
     * @param notebook - The target notebook widget.
     *
     * #### Notes
     * This action can be undone.
     * A new code cell is added if all cells are cut.
     */
    function cut(notebook) {
        Private.copyOrCut(notebook, true);
    }
    NotebookActions.cut = cut;
    /**
     * Paste cells from the application clipboard.
     *
     * @param notebook - The target notebook widget.
     *
     * @param mode - the mode of the paste operation: 'below' pastes cells
     *   below the active cell, 'above' pastes cells above the active cell,
     *   and 'replace' removes the currently selected cells and pastes cells
     *   in their place.
     *
     * #### Notes
     * The last pasted cell becomes the active cell.
     * This is a no-op if there is no cell data on the clipboard.
     * This action can be undone.
     */
    function paste(notebook, mode = 'below') {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const clipboard = apputils_1.Clipboard.getInstance();
        if (!clipboard.hasData(JUPYTER_CELL_MIME)) {
            return;
        }
        const state = Private.getState(notebook);
        const values = clipboard.getData(JUPYTER_CELL_MIME);
        const model = notebook.model;
        notebook.mode = 'command';
        const newCells = values.map(cell => {
            switch (cell.cell_type) {
                case 'code':
                    return model.contentFactory.createCodeCell({ cell });
                case 'markdown':
                    return model.contentFactory.createMarkdownCell({ cell });
                default:
                    return model.contentFactory.createRawCell({ cell });
            }
        });
        const cells = notebook.model.cells;
        let index;
        cells.beginCompoundOperation();
        // Set the starting index of the paste operation depending upon the mode.
        switch (mode) {
            case 'below':
                index = notebook.activeCellIndex;
                break;
            case 'above':
                index = notebook.activeCellIndex - 1;
                break;
            case 'replace':
                // Find the cells to delete.
                const toDelete = [];
                notebook.widgets.forEach((child, index) => {
                    const deletable = child.model.metadata.get('deletable') !== false;
                    if (notebook.isSelectedOrActive(child) && deletable) {
                        toDelete.push(index);
                    }
                });
                // If cells are not deletable, we may not have anything to delete.
                if (toDelete.length > 0) {
                    // Delete the cells as one undo event.
                    toDelete.reverse().forEach(i => {
                        cells.remove(i);
                    });
                }
                index = toDelete[0];
                break;
            default:
                break;
        }
        newCells.forEach(cell => {
            cells.insert(++index, cell);
        });
        cells.endCompoundOperation();
        notebook.activeCellIndex += newCells.length;
        notebook.deselectAll();
        Private.handleState(notebook, state);
    }
    NotebookActions.paste = paste;
    /**
     * Undo a cell action.
     *
     * @param notebook - The target notebook widget.
     *
     * #### Notes
     * This is a no-op if if there are no cell actions to undo.
     */
    function undo(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        notebook.mode = 'command';
        notebook.model.cells.undo();
        notebook.deselectAll();
        Private.handleState(notebook, state);
    }
    NotebookActions.undo = undo;
    /**
     * Redo a cell action.
     *
     * @param notebook - The target notebook widget.
     *
     * #### Notes
     * This is a no-op if there are no cell actions to redo.
     */
    function redo(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        notebook.mode = 'command';
        notebook.model.cells.redo();
        notebook.deselectAll();
        Private.handleState(notebook, state);
    }
    NotebookActions.redo = redo;
    /**
     * Toggle the line number of all cells.
     *
     * @param notebook - The target notebook widget.
     *
     * #### Notes
     * The original state is based on the state of the active cell.
     * The `mode` of the widget will be preserved.
     */
    function toggleAllLineNumbers(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        const config = notebook.editorConfig;
        const lineNumbers = !(config.code.lineNumbers &&
            config.markdown.lineNumbers &&
            config.raw.lineNumbers);
        const newConfig = {
            code: Object.assign({}, config.code, { lineNumbers }),
            markdown: Object.assign({}, config.markdown, { lineNumbers }),
            raw: Object.assign({}, config.raw, { lineNumbers })
        };
        notebook.editorConfig = newConfig;
        Private.handleState(notebook, state);
    }
    NotebookActions.toggleAllLineNumbers = toggleAllLineNumbers;
    /**
     * Clear the code outputs of the selected cells.
     *
     * @param notebook - The target notebook widget.
     *
     * #### Notes
     * The widget `mode` will be preserved.
     */
    function clearOutputs(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        algorithm_1.each(notebook.model.cells, (cell, index) => {
            const child = notebook.widgets[index];
            if (notebook.isSelectedOrActive(child) && cell.type === 'code') {
                cell.outputs.clear();
                child.outputHidden = false;
                cell.executionCount = null;
            }
        });
        Private.handleState(notebook, state);
    }
    NotebookActions.clearOutputs = clearOutputs;
    /**
     * Clear all the code outputs on the widget.
     *
     * @param notebook - The target notebook widget.
     *
     * #### Notes
     * The widget `mode` will be preserved.
     */
    function clearAllOutputs(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        algorithm_1.each(notebook.model.cells, (cell, index) => {
            const child = notebook.widgets[index];
            if (cell.type === 'code') {
                cell.outputs.clear();
                cell.executionCount = null;
                child.outputHidden = false;
            }
        });
        Private.handleState(notebook, state);
    }
    NotebookActions.clearAllOutputs = clearAllOutputs;
    /**
     * Hide the code on selected code cells.
     *
     * @param notebook - The target notebook widget.
     */
    function hideCode(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        notebook.widgets.forEach(cell => {
            if (notebook.isSelectedOrActive(cell) && cell.model.type === 'code') {
                cell.inputHidden = true;
            }
        });
        Private.handleState(notebook, state);
    }
    NotebookActions.hideCode = hideCode;
    /**
     * Show the code on selected code cells.
     *
     * @param notebook - The target notebook widget.
     */
    function showCode(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        notebook.widgets.forEach(cell => {
            if (notebook.isSelectedOrActive(cell) && cell.model.type === 'code') {
                cell.inputHidden = false;
            }
        });
        Private.handleState(notebook, state);
    }
    NotebookActions.showCode = showCode;
    /**
     * Hide the code on all code cells.
     *
     * @param notebook - The target notebook widget.
     */
    function hideAllCode(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        notebook.widgets.forEach(cell => {
            if (cell.model.type === 'code') {
                cell.inputHidden = true;
            }
        });
        Private.handleState(notebook, state);
    }
    NotebookActions.hideAllCode = hideAllCode;
    /**
     * Show the code on all code cells.
     *
     * @param widget - The target notebook widget.
     */
    function showAllCode(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        notebook.widgets.forEach(cell => {
            if (cell.model.type === 'code') {
                cell.inputHidden = false;
            }
        });
        Private.handleState(notebook, state);
    }
    NotebookActions.showAllCode = showAllCode;
    /**
     * Hide the output on selected code cells.
     *
     * @param notebook - The target notebook widget.
     */
    function hideOutput(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        notebook.widgets.forEach(cell => {
            if (notebook.isSelectedOrActive(cell) && cell.model.type === 'code') {
                cell.outputHidden = true;
            }
        });
        Private.handleState(notebook, state);
    }
    NotebookActions.hideOutput = hideOutput;
    /**
     * Show the output on selected code cells.
     *
     * @param notebook - The target notebook widget.
     */
    function showOutput(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        notebook.widgets.forEach(cell => {
            if (notebook.isSelectedOrActive(cell) && cell.model.type === 'code') {
                cell.outputHidden = false;
            }
        });
        Private.handleState(notebook, state);
    }
    NotebookActions.showOutput = showOutput;
    /**
     * Hide the output on all code cells.
     *
     * @param notebook - The target notebook widget.
     */
    function hideAllOutputs(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        notebook.widgets.forEach(cell => {
            if (cell.model.type === 'code') {
                cell.outputHidden = true;
            }
        });
        Private.handleState(notebook, state);
    }
    NotebookActions.hideAllOutputs = hideAllOutputs;
    /**
     * Show the output on all code cells.
     *
     * @param notebook - The target notebook widget.
     */
    function showAllOutputs(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        notebook.widgets.forEach(cell => {
            if (cell.model.type === 'code') {
                cell.outputHidden = false;
            }
        });
        Private.handleState(notebook, state);
    }
    NotebookActions.showAllOutputs = showAllOutputs;
    /**
     * Enable output scrolling for all selected cells.
     *
     * @param notebook - The target notebook widget.
     */
    function enableOutputScrolling(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        notebook.widgets.forEach(cell => {
            if (notebook.isSelectedOrActive(cell) && cell.model.type === 'code') {
                cell.outputsScrolled = true;
            }
        });
        Private.handleState(notebook, state);
    }
    NotebookActions.enableOutputScrolling = enableOutputScrolling;
    /**
     * Disable output scrolling for all selected cells.
     *
     * @param notebook - The target notebook widget.
     */
    function disableOutputScrolling(notebook) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        notebook.widgets.forEach(cell => {
            if (notebook.isSelectedOrActive(cell) && cell.model.type === 'code') {
                cell.outputsScrolled = false;
            }
        });
        Private.handleState(notebook, state);
    }
    NotebookActions.disableOutputScrolling = disableOutputScrolling;
    /**
     * Persists the collapsed state of all code cell outputs to the model.
     *
     * @param notebook - The target notebook widget.
     */
    function persistViewState(notebook) {
        if (!notebook.model) {
            return;
        }
        const state = Private.getState(notebook);
        notebook.widgets.forEach(cell => {
            const { model, inputHidden } = cell;
            const metadata = model.metadata;
            const jupyter = metadata.get('jupyter') || {};
            if (inputHidden) {
                jupyter.source_hidden = true;
            }
            else {
                delete jupyter.source_hidden;
            }
            if (cell.model.type === 'code') {
                const { outputHidden, outputsScrolled } = cell;
                // set both metadata keys
                // https://github.com/jupyterlab/jupyterlab/pull/3981#issuecomment-391139167
                if (outputHidden) {
                    model.metadata.set('collapsed', true);
                    jupyter.outputs_hidden = true;
                }
                else {
                    model.metadata.delete('collapsed');
                    delete jupyter.outputs_hidden;
                }
                if (outputsScrolled) {
                    model.metadata.set('scrolled', true);
                }
                else {
                    model.metadata.delete('scrolled');
                }
            }
            if (Object.keys(jupyter).length === 0) {
                metadata.delete('jupyter');
            }
            else {
                metadata.set('jupyter', jupyter);
            }
        });
        Private.handleState(notebook, state);
    }
    NotebookActions.persistViewState = persistViewState;
    /**
     * Set the markdown header level.
     *
     * @param notebook - The target notebook widget.
     *
     * @param level - The header level.
     *
     * #### Notes
     * All selected cells will be switched to markdown.
     * The level will be clamped between 1 and 6.
     * If there is an existing header, it will be replaced.
     * There will always be one blank space after the header.
     * The cells will be unrendered.
     */
    function setMarkdownHeader(notebook, level) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = Private.getState(notebook);
        const cells = notebook.model.cells;
        level = Math.min(Math.max(level, 1), 6);
        notebook.widgets.forEach((child, index) => {
            if (notebook.isSelectedOrActive(child)) {
                Private.setMarkdownHeader(cells.get(index), level);
            }
        });
        Private.changeCellType(notebook, 'markdown');
        Private.handleState(notebook, state);
    }
    NotebookActions.setMarkdownHeader = setMarkdownHeader;
    /**
     * Trust the notebook after prompting the user.
     *
     * @param notebook - The target notebook widget.
     *
     * @returns a promise that resolves when the transaction is finished.
     *
     * #### Notes
     * No dialog will be presented if the notebook is already trusted.
     */
    function trust(notebook) {
        if (!notebook.model) {
            return Promise.resolve();
        }
        // Do nothing if already trusted.
        const cells = algorithm_1.toArray(notebook.model.cells);
        const trusted = cells.every(cell => cell.trusted);
        if (trusted) {
            return apputils_1.showDialog({
                body: 'Notebook is already trusted',
                buttons: [apputils_1.Dialog.okButton()]
            }).then(() => undefined);
        }
        return apputils_1.showDialog({
            body: TRUST_MESSAGE,
            title: 'Trust this notebook?',
            buttons: [apputils_1.Dialog.cancelButton(), apputils_1.Dialog.warnButton()]
        }).then(result => {
            if (result.button.accept) {
                cells.forEach(cell => {
                    cell.trusted = true;
                });
            }
        });
    }
    NotebookActions.trust = trust;
})(NotebookActions = exports.NotebookActions || (exports.NotebookActions = {}));
/**
 * A namespace for private data.
 */
var Private;
(function (Private) {
    /**
     * A signal that emits whenever a cell is run.
     */
    Private.executed = new signaling_1.Signal({});
    /**
     * Get the state of a widget before running an action.
     */
    function getState(notebook) {
        return {
            wasFocused: notebook.node.contains(document.activeElement),
            activeCell: notebook.activeCell
        };
    }
    Private.getState = getState;
    /**
     * Handle the state of a widget after running an action.
     */
    function handleState(notebook, state, scrollIfNeeded = false) {
        const { activeCell, node } = notebook;
        if (state.wasFocused || notebook.mode === 'edit') {
            notebook.activate();
        }
        if (scrollIfNeeded) {
            domutils_1.ElementExt.scrollIntoViewIfNeeded(node, activeCell.node);
        }
    }
    Private.handleState = handleState;
    /**
     * Handle the state of a widget after running a run action.
     */
    function handleRunState(notebook, state, scroll = false) {
        if (state.wasFocused || notebook.mode === 'edit') {
            notebook.activate();
        }
        if (scroll) {
            // Scroll to the top of the previous active cell output.
            const rect = state.activeCell.inputArea.node.getBoundingClientRect();
            notebook.scrollToPosition(rect.bottom, 45);
        }
    }
    Private.handleRunState = handleRunState;
    /**
     * Clone a cell model.
     */
    function cloneCell(model, cell) {
        switch (cell.type) {
            case 'code':
                // TODO why isn't modeldb or id passed here?
                return model.contentFactory.createCodeCell({ cell: cell.toJSON() });
            case 'markdown':
                // TODO why isn't modeldb or id passed here?
                return model.contentFactory.createMarkdownCell({ cell: cell.toJSON() });
            default:
                // TODO why isn't modeldb or id passed here?
                return model.contentFactory.createRawCell({ cell: cell.toJSON() });
        }
    }
    Private.cloneCell = cloneCell;
    /**
     * Run the selected cells.
     */
    function runSelected(notebook, session) {
        notebook.mode = 'command';
        let lastIndex = notebook.activeCellIndex;
        const selected = notebook.widgets.filter((child, index) => {
            const active = notebook.isSelectedOrActive(child);
            if (active) {
                lastIndex = index;
            }
            return active;
        });
        notebook.activeCellIndex = lastIndex;
        notebook.deselectAll();
        return Promise.all(selected.map(child => runCell(notebook, child, session)))
            .then(results => {
            if (notebook.isDisposed) {
                return false;
            }
            // Post an update request.
            notebook.update();
            return results.every(result => result);
        })
            .catch(reason => {
            if (reason.message === 'KernelReplyNotOK') {
                selected.map((cell) => {
                    // Remove '*' prompt from cells that didn't execute
                    if (cell.model.executionCount == null) {
                        cell.setPrompt('');
                    }
                });
            }
            else {
                throw reason;
            }
            notebook.update();
            return false;
        });
    }
    Private.runSelected = runSelected;
    /**
     * Run a cell.
     */
    function runCell(notebook, cell, session) {
        switch (cell.model.type) {
            case 'markdown':
                cell.rendered = true;
                cell.inputHidden = false;
                Private.executed.emit({ notebook, cell });
                break;
            case 'code':
                if (session) {
                    return cells_1.CodeCell.execute(cell, session, {
                        deletedCells: notebook.model.deletedCells
                    })
                        .then(reply => {
                        notebook.model.deletedCells.splice(0, notebook.model.deletedCells.length);
                        if (cell.isDisposed) {
                            return false;
                        }
                        if (!reply) {
                            return true;
                        }
                        if (reply.content.status === 'ok') {
                            const content = reply.content;
                            if (content.payload && content.payload.length) {
                                handlePayload(content, notebook, cell);
                            }
                            return true;
                        }
                        else {
                            throw new Error('KernelReplyNotOK');
                        }
                    })
                        .catch(reason => {
                        if (reason.message !== 'Canceled') {
                            throw reason;
                        }
                        return false;
                    })
                        .then(ran => {
                        if (ran) {
                            Private.executed.emit({ notebook, cell });
                        }
                        return ran;
                    });
                }
                cell.model.executionCount = null;
                break;
            default:
                break;
        }
        return Promise.resolve(true);
    }
    /**
     * Handle payloads from an execute reply.
     *
     * #### Notes
     * Payloads are deprecated and there are no official interfaces for them in
     * the kernel type definitions.
     * See [Payloads (DEPRECATED)](https://jupyter-client.readthedocs.io/en/latest/messaging.html#payloads-deprecated).
     */
    function handlePayload(content, notebook, cell) {
        const setNextInput = content.payload.filter(i => {
            return i.source === 'set_next_input';
        })[0];
        if (!setNextInput) {
            return;
        }
        const text = setNextInput.text;
        const replace = setNextInput.replace;
        if (replace) {
            cell.model.value.text = text;
            return;
        }
        // Create a new code cell and add as the next cell.
        const newCell = notebook.model.contentFactory.createCodeCell({});
        const cells = notebook.model.cells;
        const index = algorithm_1.ArrayExt.firstIndexOf(algorithm_1.toArray(cells), cell.model);
        newCell.value.text = text;
        if (index === -1) {
            cells.push(newCell);
        }
        else {
            cells.insert(index + 1, newCell);
        }
    }
    /**
     * Copy or cut the selected cell data to the application clipboard.
     *
     * @param notebook - The target notebook widget.
     *
     * @param cut - Whether to copy or cut.
     */
    function copyOrCut(notebook, cut) {
        if (!notebook.model || !notebook.activeCell) {
            return;
        }
        const state = getState(notebook);
        const clipboard = apputils_1.Clipboard.getInstance();
        notebook.mode = 'command';
        clipboard.clear();
        let data = notebook.widgets
            .filter(cell => notebook.isSelectedOrActive(cell))
            .map(cell => cell.model.toJSON())
            .map(cellJSON => {
            if (cellJSON.metadata.deletable !== undefined) {
                delete cellJSON.metadata.deletable;
            }
            return cellJSON;
        });
        clipboard.setData(JUPYTER_CELL_MIME, data);
        if (cut) {
            deleteCells(notebook);
        }
        else {
            notebook.deselectAll();
        }
        handleState(notebook, state);
    }
    Private.copyOrCut = copyOrCut;
    /**
     * Change the selected cell type(s).
     *
     * @param notebook - The target notebook widget.
     *
     * @param value - The target cell type.
     *
     * #### Notes
     * It should preserve the widget mode.
     * This action can be undone.
     * The existing selection will be cleared.
     * Any cells converted to markdown will be unrendered.
     */
    function changeCellType(notebook, value) {
        const model = notebook.model;
        const cells = model.cells;
        cells.beginCompoundOperation();
        notebook.widgets.forEach((child, index) => {
            if (!notebook.isSelectedOrActive(child)) {
                return;
            }
            if (child.model.type !== value) {
                const cell = child.model.toJSON();
                let newCell;
                switch (value) {
                    case 'code':
                        newCell = model.contentFactory.createCodeCell({ cell });
                        break;
                    case 'markdown':
                        newCell = model.contentFactory.createMarkdownCell({ cell });
                        if (child.model.type === 'code') {
                            newCell.trusted = false;
                        }
                        break;
                    default:
                        newCell = model.contentFactory.createRawCell({ cell });
                        if (child.model.type === 'code') {
                            newCell.trusted = false;
                        }
                }
                cells.set(index, newCell);
            }
            if (value === 'markdown') {
                // Fetch the new widget and unrender it.
                child = notebook.widgets[index];
                child.rendered = false;
            }
        });
        cells.endCompoundOperation();
        notebook.deselectAll();
    }
    Private.changeCellType = changeCellType;
    /**
     * Delete the selected cells.
     *
     * @param notebook - The target notebook widget.
     *
     * #### Notes
     * The cell after the last selected cell will be activated.
     * If the last cell is deleted, then the previous one will be activated.
     * It will add a code cell if all cells are deleted.
     * This action can be undone.
     */
    function deleteCells(notebook) {
        const model = notebook.model;
        const cells = model.cells;
        const toDelete = [];
        notebook.mode = 'command';
        // Find the cells to delete.
        notebook.widgets.forEach((child, index) => {
            const deletable = child.model.metadata.get('deletable') !== false;
            if (notebook.isSelectedOrActive(child) && deletable) {
                toDelete.push(index);
                notebook.model.deletedCells.push(child.model.id);
            }
        });
        // If cells are not deletable, we may not have anything to delete.
        if (toDelete.length > 0) {
            // Delete the cells as one undo event.
            cells.beginCompoundOperation();
            // Delete cells in reverse order to maintain the correct indices.
            toDelete.reverse().forEach(index => {
                cells.remove(index);
            });
            // Add a new cell if the notebook is empty. This is done
            // within the compound operation to make the deletion of
            // a notebook's last cell undoable.
            if (!cells.length) {
                cells.push(model.contentFactory.createCodeCell({}));
            }
            cells.endCompoundOperation();
            // Select the *first* interior cell not deleted or the cell
            // *after* the last selected cell.
            // Note: The activeCellIndex is clamped to the available cells,
            // so if the last cell is deleted the previous cell will be activated.
            // The *first* index is the index of the last cell in the initial
            // toDelete list due to the `reverse` operation above.
            notebook.activeCellIndex = toDelete[0] - toDelete.length + 1;
        }
        // Deselect any remaining, undeletable cells. Do this even if we don't
        // delete anything so that users are aware *something* happened.
        notebook.deselectAll();
    }
    Private.deleteCells = deleteCells;
    /**
     * Set the markdown header level of a cell.
     */
    function setMarkdownHeader(cell, level) {
        // Remove existing header or leading white space.
        let source = cell.value.text;
        const regex = /^(#+\s*)|^(\s*)/;
        const newHeader = Array(level + 1).join('#') + ' ';
        const matches = regex.exec(source);
        if (matches) {
            source = source.slice(matches[0].length);
        }
        cell.value.text = newHeader + source;
    }
    Private.setMarkdownHeader = setMarkdownHeader;
})(Private || (Private = {}));


/***/ }),

/***/ "qiJe":
/*!******************************************************************************************!*\
  !*** ./node_modules/node-libs-browser/node_modules/string_decoder/lib/string_decoder.js ***!
  \******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.



/*<replacement>*/

var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer;
/*</replacement>*/

var isEncoding = Buffer.isEncoding || function (encoding) {
  encoding = '' + encoding;
  switch (encoding && encoding.toLowerCase()) {
    case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
      return true;
    default:
      return false;
  }
};

function _normalizeEncoding(enc) {
  if (!enc) return 'utf8';
  var retried;
  while (true) {
    switch (enc) {
      case 'utf8':
      case 'utf-8':
        return 'utf8';
      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return 'utf16le';
      case 'latin1':
      case 'binary':
        return 'latin1';
      case 'base64':
      case 'ascii':
      case 'hex':
        return enc;
      default:
        if (retried) return; // undefined
        enc = ('' + enc).toLowerCase();
        retried = true;
    }
  }
};

// Do not cache `Buffer.isEncoding` when checking encoding names as some
// modules monkey-patch it to support additional encodings
function normalizeEncoding(enc) {
  var nenc = _normalizeEncoding(enc);
  if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  return nenc || enc;
}

// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters.
exports.StringDecoder = StringDecoder;
function StringDecoder(encoding) {
  this.encoding = normalizeEncoding(encoding);
  var nb;
  switch (this.encoding) {
    case 'utf16le':
      this.text = utf16Text;
      this.end = utf16End;
      nb = 4;
      break;
    case 'utf8':
      this.fillLast = utf8FillLast;
      nb = 4;
      break;
    case 'base64':
      this.text = base64Text;
      this.end = base64End;
      nb = 3;
      break;
    default:
      this.write = simpleWrite;
      this.end = simpleEnd;
      return;
  }
  this.lastNeed = 0;
  this.lastTotal = 0;
  this.lastChar = Buffer.allocUnsafe(nb);
}

StringDecoder.prototype.write = function (buf) {
  if (buf.length === 0) return '';
  var r;
  var i;
  if (this.lastNeed) {
    r = this.fillLast(buf);
    if (r === undefined) return '';
    i = this.lastNeed;
    this.lastNeed = 0;
  } else {
    i = 0;
  }
  if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  return r || '';
};

StringDecoder.prototype.end = utf8End;

// Returns only complete characters in a Buffer
StringDecoder.prototype.text = utf8Text;

// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
StringDecoder.prototype.fillLast = function (buf) {
  if (this.lastNeed <= buf.length) {
    buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
    return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  }
  buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  this.lastNeed -= buf.length;
};

// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
// continuation byte. If an invalid byte is detected, -2 is returned.
function utf8CheckByte(byte) {
  if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
  return byte >> 6 === 0x02 ? -1 : -2;
}

// Checks at most 3 bytes at the end of a Buffer in order to detect an
// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
// needed to complete the UTF-8 character (if applicable) are returned.
function utf8CheckIncomplete(self, buf, i) {
  var j = buf.length - 1;
  if (j < i) return 0;
  var nb = utf8CheckByte(buf[j]);
  if (nb >= 0) {
    if (nb > 0) self.lastNeed = nb - 1;
    return nb;
  }
  if (--j < i || nb === -2) return 0;
  nb = utf8CheckByte(buf[j]);
  if (nb >= 0) {
    if (nb > 0) self.lastNeed = nb - 2;
    return nb;
  }
  if (--j < i || nb === -2) return 0;
  nb = utf8CheckByte(buf[j]);
  if (nb >= 0) {
    if (nb > 0) {
      if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
    }
    return nb;
  }
  return 0;
}

// Validates as many continuation bytes for a multi-byte UTF-8 character as
// needed or are available. If we see a non-continuation byte where we expect
// one, we "replace" the validated continuation bytes we've seen so far with
// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
// behavior. The continuation byte check is included three times in the case
// where all of the continuation bytes for a character exist in the same buffer.
// It is also done this way as a slight performance increase instead of using a
// loop.
function utf8CheckExtraBytes(self, buf, p) {
  if ((buf[0] & 0xC0) !== 0x80) {
    self.lastNeed = 0;
    return '\ufffd';
  }
  if (self.lastNeed > 1 && buf.length > 1) {
    if ((buf[1] & 0xC0) !== 0x80) {
      self.lastNeed = 1;
      return '\ufffd';
    }
    if (self.lastNeed > 2 && buf.length > 2) {
      if ((buf[2] & 0xC0) !== 0x80) {
        self.lastNeed = 2;
        return '\ufffd';
      }
    }
  }
}

// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
function utf8FillLast(buf) {
  var p = this.lastTotal - this.lastNeed;
  var r = utf8CheckExtraBytes(this, buf, p);
  if (r !== undefined) return r;
  if (this.lastNeed <= buf.length) {
    buf.copy(this.lastChar, p, 0, this.lastNeed);
    return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  }
  buf.copy(this.lastChar, p, 0, buf.length);
  this.lastNeed -= buf.length;
}

// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
// partial character, the character's bytes are buffered until the required
// number of bytes are available.
function utf8Text(buf, i) {
  var total = utf8CheckIncomplete(this, buf, i);
  if (!this.lastNeed) return buf.toString('utf8', i);
  this.lastTotal = total;
  var end = buf.length - (total - this.lastNeed);
  buf.copy(this.lastChar, 0, end);
  return buf.toString('utf8', i, end);
}

// For UTF-8, a replacement character is added when ending on a partial
// character.
function utf8End(buf) {
  var r = buf && buf.length ? this.write(buf) : '';
  if (this.lastNeed) return r + '\ufffd';
  return r;
}

// UTF-16LE typically needs two bytes per character, but even if we have an even
// number of bytes available, we need to check if we end on a leading/high
// surrogate. In that case, we need to wait for the next two bytes in order to
// decode the last character properly.
function utf16Text(buf, i) {
  if ((buf.length - i) % 2 === 0) {
    var r = buf.toString('utf16le', i);
    if (r) {
      var c = r.charCodeAt(r.length - 1);
      if (c >= 0xD800 && c <= 0xDBFF) {
        this.lastNeed = 2;
        this.lastTotal = 4;
        this.lastChar[0] = buf[buf.length - 2];
        this.lastChar[1] = buf[buf.length - 1];
        return r.slice(0, -1);
      }
    }
    return r;
  }
  this.lastNeed = 1;
  this.lastTotal = 2;
  this.lastChar[0] = buf[buf.length - 1];
  return buf.toString('utf16le', i, buf.length - 1);
}

// For UTF-16LE we do not explicitly append special replacement characters if we
// end on a partial character, we simply let v8 handle that.
function utf16End(buf) {
  var r = buf && buf.length ? this.write(buf) : '';
  if (this.lastNeed) {
    var end = this.lastTotal - this.lastNeed;
    return r + this.lastChar.toString('utf16le', 0, end);
  }
  return r;
}

function base64Text(buf, i) {
  var n = (buf.length - i) % 3;
  if (n === 0) return buf.toString('base64', i);
  this.lastNeed = 3 - n;
  this.lastTotal = 3;
  if (n === 1) {
    this.lastChar[0] = buf[buf.length - 1];
  } else {
    this.lastChar[0] = buf[buf.length - 2];
    this.lastChar[1] = buf[buf.length - 1];
  }
  return buf.toString('base64', i, buf.length - n);
}

function base64End(buf) {
  var r = buf && buf.length ? this.write(buf) : '';
  if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  return r;
}

// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
function simpleWrite(buf) {
  return buf.toString(this.encoding);
}

function simpleEnd(buf) {
  return buf && buf.length ? this.write(buf) : '';
}

/***/ }),

/***/ "qiq3":
/*!************************************************************!*\
  !*** ./node_modules/@jupyter-widgets/output/lib/output.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
        s = arguments[i];
        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
            t[p] = s[p];
    }
    return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
var base_1 = __webpack_require__(/*! @jupyter-widgets/base */ "Rtm6");
exports.OUTPUT_WIDGET_VERSION = '1.0.0';
var OutputModel = /** @class */ (function (_super) {
    __extends(OutputModel, _super);
    function OutputModel() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    OutputModel.prototype.defaults = function () {
        return __assign({}, _super.prototype.defaults.call(this), { _model_name: 'OutputModel', _view_name: 'OutputView', _model_module: '@jupyter-widgets/output', _view_module: '@jupyter-widgets/output', _model_module_version: exports.OUTPUT_WIDGET_VERSION, _view_module_version: exports.OUTPUT_WIDGET_VERSION });
    };
    return OutputModel;
}(base_1.DOMWidgetModel));
exports.OutputModel = OutputModel;
var OutputView = /** @class */ (function (_super) {
    __extends(OutputView, _super);
    function OutputView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return OutputView;
}(base_1.DOMWidgetView));
exports.OutputView = OutputView;


/***/ }),

/***/ "ql/k":
/*!***************************************************!*\
  !*** ./node_modules/@icons/material/CheckIcon.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

var DEFAULT_SIZE = 24;

exports.default = function (_ref) {
  var _ref$fill = _ref.fill,
      fill = _ref$fill === undefined ? 'currentColor' : _ref$fill,
      _ref$width = _ref.width,
      width = _ref$width === undefined ? DEFAULT_SIZE : _ref$width,
      _ref$height = _ref.height,
      height = _ref$height === undefined ? DEFAULT_SIZE : _ref$height,
      _ref$style = _ref.style,
      style = _ref$style === undefined ? {} : _ref$style,
      props = _objectWithoutProperties(_ref, ['fill', 'width', 'height', 'style']);

  return _react2.default.createElement(
    'svg',
    _extends({
      viewBox: '0 0 ' + DEFAULT_SIZE + ' ' + DEFAULT_SIZE,
      style: _extends({ fill: fill, width: width, height: height }, style)
    }, props),
    _react2.default.createElement('path', { d: 'M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z' })
  );
};

/***/ }),

/***/ "ql0L":
/*!*****************************************************!*\
  !*** ./node_modules/@phosphor/algorithm/lib/zip.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var iter_1 = __webpack_require__(/*! ./iter */ "DMSk");
/**
 * Iterate several iterables in lockstep.
 *
 * @param objects - The iterable or array-like objects of interest.
 *
 * @returns An iterator which yields successive tuples of values where
 *   each value is taken in turn from the provided iterables. It will
 *   be as long as the shortest provided iterable.
 *
 * #### Example
 * ```typescript
 * import { zip, toArray } from '@phosphor/algorithm';
 *
 * let data1 = [1, 2, 3];
 * let data2 = [4, 5, 6];
 *
 * let stream = zip(data1, data2);
 *
 * toArray(stream);  // [[1, 4], [2, 5], [3, 6]]
 * ```
 */
function zip() {
    var objects = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        objects[_i] = arguments[_i];
    }
    return new ZipIterator(objects.map(iter_1.iter));
}
exports.zip = zip;
/**
 * An iterator which iterates several sources in lockstep.
 */
var ZipIterator = (function () {
    /**
     * Construct a new zip iterator.
     *
     * @param source - The iterators of interest.
     */
    function ZipIterator(source) {
        this._source = source;
    }
    /**
     * Get an iterator over the object's values.
     *
     * @returns An iterator which yields the object's values.
     */
    ZipIterator.prototype.iter = function () {
        return this;
    };
    /**
     * Create an independent clone of the iterator.
     *
     * @returns A new independent clone of the iterator.
     */
    ZipIterator.prototype.clone = function () {
        return new ZipIterator(this._source.map(function (it) { return it.clone(); }));
    };
    /**
     * Get the next value from the iterator.
     *
     * @returns The next value from the iterator, or `undefined`.
     */
    ZipIterator.prototype.next = function () {
        var result = new Array(this._source.length);
        for (var i = 0, n = this._source.length; i < n; ++i) {
            var value = this._source[i].next();
            if (value === undefined) {
                return undefined;
            }
            result[i] = value;
        }
        return result;
    };
    return ZipIterator;
}());
exports.ZipIterator = ZipIterator;


/***/ }),

/***/ "qlaj":
/*!*****************************************************!*\
  !*** ./node_modules/hash.js/lib/hash/sha/common.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var utils = __webpack_require__(/*! ../utils */ "w8CP");
var rotr32 = utils.rotr32;

function ft_1(s, x, y, z) {
  if (s === 0)
    return ch32(x, y, z);
  if (s === 1 || s === 3)
    return p32(x, y, z);
  if (s === 2)
    return maj32(x, y, z);
}
exports.ft_1 = ft_1;

function ch32(x, y, z) {
  return (x & y) ^ ((~x) & z);
}
exports.ch32 = ch32;

function maj32(x, y, z) {
  return (x & y) ^ (x & z) ^ (y & z);
}
exports.maj32 = maj32;

function p32(x, y, z) {
  return x ^ y ^ z;
}
exports.p32 = p32;

function s0_256(x) {
  return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);
}
exports.s0_256 = s0_256;

function s1_256(x) {
  return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);
}
exports.s1_256 = s1_256;

function g0_256(x) {
  return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);
}
exports.g0_256 = g0_256;

function g1_256(x) {
  return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);
}
exports.g1_256 = g1_256;


/***/ }),

/***/ "qmQW":
/*!*********************************************************************!*\
  !*** ./node_modules/@jupyterlab/settingeditor/lib/settingeditor.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const React = __importStar(__webpack_require__(/*! react */ "q1tI"));
const ReactDOM = __importStar(__webpack_require__(/*! react-dom */ "i8i4"));
const plugineditor_1 = __webpack_require__(/*! ./plugineditor */ "0pX1");
const pluginlist_1 = __webpack_require__(/*! ./pluginlist */ "uP2X");
const splitpanel_1 = __webpack_require__(/*! ./splitpanel */ "wHxL");
/**
 * The ratio panes in the setting editor.
 */
const DEFAULT_LAYOUT = {
    sizes: [1, 3],
    container: {
        editor: 'raw',
        plugin: '',
        sizes: [1, 1]
    }
};
/**
 * An interface for modifying and saving application settings.
 */
class SettingEditor extends widgets_1.Widget {
    /**
     * Create a new setting editor.
     */
    constructor(options) {
        super();
        this._fetching = null;
        this._saving = false;
        this._state = coreutils_1.JSONExt.deepCopy(DEFAULT_LAYOUT);
        this.addClass('jp-SettingEditor');
        this.key = options.key;
        this.state = options.state;
        const { commands, editorFactory, rendermime } = options;
        const layout = (this.layout = new widgets_1.PanelLayout());
        const registry = (this.registry = options.registry);
        const panel = (this._panel = new splitpanel_1.SplitPanel({
            orientation: 'horizontal',
            renderer: splitpanel_1.SplitPanel.defaultRenderer,
            spacing: 1
        }));
        const instructions = (this._instructions = new widgets_1.Widget());
        const editor = (this._editor = new plugineditor_1.PluginEditor({
            commands,
            editorFactory,
            registry,
            rendermime
        }));
        const confirm = () => editor.confirm();
        const list = (this._list = new pluginlist_1.PluginList({ confirm, registry }));
        const when = options.when;
        instructions.addClass('jp-SettingEditorInstructions');
        Private.populateInstructionsNode(instructions.node);
        if (when) {
            this._when = Array.isArray(when) ? Promise.all(when) : when;
        }
        panel.addClass('jp-SettingEditor-main');
        layout.addWidget(panel);
        panel.addWidget(list);
        panel.addWidget(instructions);
        splitpanel_1.SplitPanel.setStretch(list, 0);
        splitpanel_1.SplitPanel.setStretch(instructions, 1);
        splitpanel_1.SplitPanel.setStretch(editor, 1);
        editor.stateChanged.connect(this._onStateChanged, this);
        list.changed.connect(this._onStateChanged, this);
        panel.handleMoved.connect(this._onStateChanged, this);
    }
    /**
     * Whether the raw editor revert functionality is enabled.
     */
    get canRevertRaw() {
        return this._editor.raw.canRevert;
    }
    /**
     * Whether the raw editor save functionality is enabled.
     */
    get canSaveRaw() {
        return this._editor.raw.canSave;
    }
    /**
     * Emits when the commands passed in at instantiation change.
     */
    get commandsChanged() {
        return this._editor.raw.commandsChanged;
    }
    /**
     * Whether the debug panel is visible.
     */
    get isDebugVisible() {
        return this._editor.raw.isDebugVisible;
    }
    /**
     * The currently loaded settings.
     */
    get settings() {
        return this._editor.settings;
    }
    /**
     * The inspectable raw user editor source for the currently loaded settings.
     */
    get source() {
        return this._editor.raw.source;
    }
    /**
     * Dispose of the resources held by the setting editor.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        super.dispose();
        this._editor.dispose();
        this._instructions.dispose();
        this._list.dispose();
        this._panel.dispose();
    }
    /**
     * Revert raw editor back to original settings.
     */
    revert() {
        this._editor.raw.revert();
    }
    /**
     * Save the contents of the raw editor.
     */
    save() {
        return this._editor.raw.save();
    }
    /**
     * Toggle the debug functionality.
     */
    toggleDebug() {
        this._editor.raw.toggleDebug();
    }
    /**
     * Handle `'after-attach'` messages.
     */
    onAfterAttach(msg) {
        super.onAfterAttach(msg);
        this._panel.hide();
        this._fetchState()
            .then(() => {
            this._panel.show();
            this._setState();
        })
            .catch(reason => {
            console.error('Fetching setting editor state failed', reason);
            this._panel.show();
            this._setState();
        });
    }
    /**
     * Handle `'close-request'` messages.
     */
    onCloseRequest(msg) {
        this._editor
            .confirm()
            .then(() => {
            super.onCloseRequest(msg);
            this.dispose();
        })
            .catch(() => {
            /* no op */
        });
    }
    /**
     * Get the state of the panel.
     */
    _fetchState() {
        if (this._fetching) {
            return this._fetching;
        }
        const { key, state } = this;
        const promises = [state.fetch(key), this._when];
        return (this._fetching = Promise.all(promises).then(([saved]) => {
            this._fetching = null;
            if (this._saving) {
                return;
            }
            this._state = Private.normalizeState(saved, this._state);
        }));
    }
    /**
     * Handle root level layout state changes.
     */
    _onStateChanged() {
        this._state.sizes = this._panel.relativeSizes();
        this._state.container = this._editor.state;
        this._state.container.editor = this._list.editor;
        this._state.container.plugin = this._list.selection;
        this._saveState()
            .then(() => {
            this._setState();
        })
            .catch(reason => {
            console.error('Saving setting editor state failed', reason);
            this._setState();
        });
    }
    /**
     * Set the state of the setting editor.
     */
    _saveState() {
        const { key, state } = this;
        const value = this._state;
        this._saving = true;
        return state
            .save(key, value)
            .then(() => {
            this._saving = false;
        })
            .catch((reason) => {
            this._saving = false;
            throw reason;
        });
    }
    /**
     * Set the layout sizes.
     */
    _setLayout() {
        const editor = this._editor;
        const panel = this._panel;
        const state = this._state;
        editor.state = state.container;
        // Allow the message queue (which includes fit requests that might disrupt
        // setting relative sizes) to clear before setting sizes.
        requestAnimationFrame(() => {
            panel.setRelativeSizes(state.sizes);
        });
    }
    /**
     * Set the presets of the setting editor.
     */
    _setState() {
        const editor = this._editor;
        const list = this._list;
        const panel = this._panel;
        const { container } = this._state;
        if (!container.plugin) {
            editor.settings = null;
            list.selection = '';
            this._setLayout();
            return;
        }
        if (editor.settings && editor.settings.plugin === container.plugin) {
            this._setLayout();
            return;
        }
        const instructions = this._instructions;
        this.registry
            .load(container.plugin)
            .then(settings => {
            if (instructions.isAttached) {
                instructions.parent = null;
            }
            if (!editor.isAttached) {
                panel.addWidget(editor);
            }
            editor.settings = settings;
            list.editor = container.editor;
            list.selection = container.plugin;
            this._setLayout();
        })
            .catch((reason) => {
            console.error(`Loading settings failed: ${reason.message}`);
            list.selection = this._state.container.plugin = '';
            editor.settings = null;
            this._setLayout();
        });
    }
}
exports.SettingEditor = SettingEditor;
/**
 * A namespace for private module data.
 */
var Private;
(function (Private) {
    /**
     * Populate the instructions text node.
     */
    function populateInstructionsNode(node) {
        const iconClass = `jp-SettingEditorInstructions-icon jp-JupyterIcon`;
        ReactDOM.render(React.createElement(React.Fragment, null,
            React.createElement("h2", null,
                React.createElement("span", { className: iconClass }),
                React.createElement("span", { className: "jp-SettingEditorInstructions-title" }, "Settings")),
            React.createElement("span", { className: "jp-SettingEditorInstructions-text" }, "Select a plugin from the list to view and edit its preferences.")), node);
    }
    Private.populateInstructionsNode = populateInstructionsNode;
    /**
     * Return a normalized restored layout state that defaults to the presets.
     */
    function normalizeState(saved, current) {
        if (!saved) {
            return coreutils_1.JSONExt.deepCopy(DEFAULT_LAYOUT);
        }
        if (!('sizes' in saved) || !numberArray(saved.sizes)) {
            saved.sizes = coreutils_1.JSONExt.deepCopy(DEFAULT_LAYOUT.sizes);
        }
        if (!('container' in saved)) {
            saved.container = coreutils_1.JSONExt.deepCopy(DEFAULT_LAYOUT.container);
            return saved;
        }
        const container = 'container' in saved &&
            saved.container &&
            typeof saved.container === 'object'
            ? saved.container
            : {};
        saved.container = {
            editor: container.editor === 'raw' || container.editor === 'table'
                ? container.editor
                : DEFAULT_LAYOUT.container.editor,
            plugin: typeof container.plugin === 'string'
                ? container.plugin
                : DEFAULT_LAYOUT.container.plugin,
            sizes: numberArray(container.sizes)
                ? container.sizes
                : coreutils_1.JSONExt.deepCopy(DEFAULT_LAYOUT.container.sizes)
        };
        return saved;
    }
    Private.normalizeState = normalizeState;
    /**
     * Tests whether an array consists exclusively of numbers.
     */
    function numberArray(value) {
        return Array.isArray(value) && value.every(x => typeof x === 'number');
    }
})(Private || (Private = {}));


/***/ }),

/***/ "qnky":
/*!**********************************************************!*\
  !*** ./node_modules/draft-js/lib/DraftEntityInstance.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DraftEntityInstance
 * @legacyServerCallableInstance
 * @format
 * 
 */



function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Immutable = __webpack_require__(/*! immutable */ "JPcv");

var Record = Immutable.Record;


var DraftEntityInstanceRecord = Record({
  type: 'TOKEN',
  mutability: 'IMMUTABLE',
  data: Object
});

/**
 * An instance of a document entity, consisting of a `type` and relevant
 * `data`, metadata about the entity.
 *
 * For instance, a "link" entity might provide a URI, and a "mention"
 * entity might provide the mentioned user's ID. These pieces of data
 * may be used when rendering the entity as part of a ContentBlock DOM
 * representation. For a link, the data would be used as an href for
 * the rendered anchor. For a mention, the ID could be used to retrieve
 * a hovercard.
 */

var DraftEntityInstance = function (_DraftEntityInstanceR) {
  _inherits(DraftEntityInstance, _DraftEntityInstanceR);

  function DraftEntityInstance() {
    _classCallCheck(this, DraftEntityInstance);

    return _possibleConstructorReturn(this, _DraftEntityInstanceR.apply(this, arguments));
  }

  DraftEntityInstance.prototype.getType = function getType() {
    return this.get('type');
  };

  DraftEntityInstance.prototype.getMutability = function getMutability() {
    return this.get('mutability');
  };

  DraftEntityInstance.prototype.getData = function getData() {
    return this.get('data');
  };

  return DraftEntityInstance;
}(DraftEntityInstanceRecord);

module.exports = DraftEntityInstance;

/***/ }),

/***/ "qo7M":
/*!*************************************************************!*\
  !*** ./node_modules/@mflevine/jupyterlab_html/lib/index.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Distributed under the terms of the Modified BSD License.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
__webpack_require__(/*! ../style/index.css */ "K2+N");
/**
 * The CSS class to add to the Plotly Widget.
 */
var CSS_CLASS = 'jp-RenderedIFrame';
/**
 * The CSS class for a Plotly icon.
 */
var CSS_ICON_CLASS = 'jp-MaterialIcon jp-HTMLIcon';
/**
 * The MIME type for HTML.
 */
exports.MIME_TYPE = 'application/jupyterlab_html';
exports.HTML_CLASS = 'jp-HTMLViewer';
exports.HTML_CONTAINER_CLASS = 'jp-HTMLContainer';
var RenderedIFrame = /** @class */ (function (_super) {
    __extends(RenderedIFrame, _super);
    /**
     * Create a new widget for rendering HTML.
     */
    function RenderedIFrame(options) {
        var _this = _super.call(this, { node: Private.createNode() }) || this;
        _this.addClass(CSS_CLASS);
        _this._mimeType = options.mimeType;
        return _this;
    }
    /**
     * Render HTML in IFrame into this widget's node.
     */
    RenderedIFrame.prototype.renderModel = function (model) {
        var data = model.data[this._mimeType];
        var blob = new Blob([data], { type: "text/html" });
        this.node.querySelector('iframe').setAttribute('src', URL.createObjectURL(blob));
        return Promise.resolve(void 0);
    };
    return RenderedIFrame;
}(widgets_1.Widget));
exports.RenderedIFrame = RenderedIFrame;
/**
 * A mime renderer factory for HTML data.
 */
exports.rendererFactory = {
    safe: true,
    mimeTypes: [exports.MIME_TYPE],
    createRenderer: function (options) { return new RenderedIFrame(options); }
};
var extensions = [
    {
        id: '@jupyterlab_html:factory',
        rendererFactory: exports.rendererFactory,
        rank: 0,
        dataType: "string",
        fileTypes: [{
                name: 'html',
                mimeTypes: [exports.MIME_TYPE],
                extensions: ['.html'],
                iconClass: CSS_ICON_CLASS
            }],
        documentWidgetFactoryOptions: {
            name: 'View HTML',
            primaryFileType: 'html',
            fileTypes: ['html'],
            defaultFor: ['html']
        }
    }
];
exports.default = extensions;
/**
 * A namespace for HTML widget private data.
 */
var Private;
(function (Private) {
    /**
     * Create the node for the HTML widget.
     */
    function createNode() {
        var node = document.createElement('div');
        node.className = exports.HTML_CONTAINER_CLASS;
        var iframe = document.createElement('iframe');
        iframe.style.height = '100%';
        iframe.style.width = '100%';
        iframe.className = exports.HTML_CLASS;
        iframe.setAttribute('type', exports.MIME_TYPE);
        node.appendChild(iframe);
        return node;
    }
    Private.createNode = createNode;
})(Private || (Private = {}));


/***/ }),

/***/ "qo7Q":
/*!****************************************************************!*\
  !*** ./node_modules/react-color/lib/components/alpha/Alpha.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.AlphaPicker = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _common = __webpack_require__(/*! ../common */ "TM95");

var _AlphaPointer = __webpack_require__(/*! ./AlphaPointer */ "Syy6");

var _AlphaPointer2 = _interopRequireDefault(_AlphaPointer);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var AlphaPicker = exports.AlphaPicker = function AlphaPicker(_ref) {
  var rgb = _ref.rgb,
      hsl = _ref.hsl,
      width = _ref.width,
      height = _ref.height,
      onChange = _ref.onChange,
      direction = _ref.direction,
      style = _ref.style,
      renderers = _ref.renderers,
      pointer = _ref.pointer,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var styles = (0, _reactcss2.default)({
    'default': {
      picker: {
        position: 'relative',
        width: width,
        height: height
      },
      alpha: {
        radius: '2px',
        style: style
      }
    }
  });

  return _react2.default.createElement(
    'div',
    { style: styles.picker, className: 'alpha-picker ' + className },
    _react2.default.createElement(_common.Alpha, _extends({}, styles.alpha, {
      rgb: rgb,
      hsl: hsl,
      pointer: pointer,
      renderers: renderers,
      onChange: onChange,
      direction: direction
    }))
  );
};

AlphaPicker.defaultProps = {
  width: '316px',
  height: '16px',
  direction: 'horizontal',
  pointer: _AlphaPointer2.default
};

exports.default = (0, _common.ColorWrap)(AlphaPicker);

/***/ }),

/***/ "qqOP":
/*!***************************************!*\
  !*** ./node_modules/ajv/lib/$data.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var KEYWORDS = [
  'multipleOf',
  'maximum',
  'exclusiveMaximum',
  'minimum',
  'exclusiveMinimum',
  'maxLength',
  'minLength',
  'pattern',
  'additionalItems',
  'maxItems',
  'minItems',
  'uniqueItems',
  'maxProperties',
  'minProperties',
  'required',
  'additionalProperties',
  'enum',
  'format',
  'const'
];

module.exports = function (metaSchema, keywordsJsonPointers) {
  for (var i=0; i<keywordsJsonPointers.length; i++) {
    metaSchema = JSON.parse(JSON.stringify(metaSchema));
    var segments = keywordsJsonPointers[i].split('/');
    var keywords = metaSchema;
    var j;
    for (j=1; j<segments.length; j++)
      keywords = keywords[segments[j]];

    for (j=0; j<KEYWORDS.length; j++) {
      var key = KEYWORDS[j];
      var schema = keywords[key];
      if (schema) {
        keywords[key] = {
          anyOf: [
            schema,
            { $ref: 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/$data.json#' }
          ]
        };
      }
    }
  }

  return metaSchema;
};


/***/ }),

/***/ "qrPk":
/*!*************************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/constants/numerical.js ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




module.exports = {
    /**
     * Standardize all missing data in calcdata to use undefined
     * never null or NaN.
     * That way we can use !==undefined, or !== BADNUM,
     * to test for real data
     */
    BADNUM: undefined,

    /*
     * Limit certain operations to well below floating point max value
     * to avoid glitches: Make sure that even when you multiply it by the
     * number of pixels on a giant screen it still works
     */
    FP_SAFE: Number.MAX_VALUE / 10000,

    /*
     * conversion of date units to milliseconds
     * year and month constants are marked "AVG"
     * to remind us that not all years and months
     * have the same length
     */
    ONEAVGYEAR: 31557600000, // 365.25 days
    ONEAVGMONTH: 2629800000, // 1/12 of ONEAVGYEAR
    ONEDAY: 86400000,
    ONEHOUR: 3600000,
    ONEMIN: 60000,
    ONESEC: 1000,

    /*
     * For fast conversion btwn world calendars and epoch ms, the Julian Day Number
     * of the unix epoch. From calendars.instance().newDate(1970, 1, 1).toJD()
     */
    EPOCHJD: 2440587.5,

    /*
     * Are two values nearly equal? Compare to 1PPM
     */
    ALMOST_EQUAL: 1 - 1e-6,

    /*
     * If we're asked to clip a non-positive log value, how far off-screen
     * do we put it?
     */
    LOG_CLIP: 10,

    /*
     * not a number, but for displaying numbers: the "minus sign" symbol is
     * wider than the regular ascii dash "-"
     */
    MINUS_SIGN: '\u2212'
};


/***/ }),

/***/ "qw1u":
/*!**************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/striptags.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
var __WEBPACK_AMD_DEFINE_RESULT__;/* eslint-disable */

// The MIT License (MIT)
//
// Copyright (c) [2017] [Eric Norris]
//
// 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.



var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

(function (global) {
  // minimal symbol polyfill for IE11 and others
  if (typeof _Symbol !== 'function') {
    var _Symbol = function _Symbol(name) {
      return name;
    };

    _Symbol.nonNative = true;
  }

  var STATE_PLAINTEXT = _Symbol('plaintext');
  var STATE_HTML = _Symbol('html');
  var STATE_COMMENT = _Symbol('comment');

  var ALLOWED_TAGS_REGEX = /<(\w*)>/g;
  var NORMALIZE_TAG_REGEX = /<\/?([^\s\/>]+)/;

  function striptags(html, allowable_tags, tag_replacement) {
    html = html || '';
    allowable_tags = allowable_tags || [];
    tag_replacement = tag_replacement || '';

    var context = init_context(allowable_tags, tag_replacement);

    return striptags_internal(html, context);
  }

  function init_striptags_stream(allowable_tags, tag_replacement) {
    allowable_tags = allowable_tags || [];
    tag_replacement = tag_replacement || '';

    var context = init_context(allowable_tags, tag_replacement);

    return function striptags_stream(html) {
      return striptags_internal(html || '', context);
    };
  }

  striptags.init_streaming_mode = init_striptags_stream;

  function init_context(allowable_tags, tag_replacement) {
    allowable_tags = parse_allowable_tags(allowable_tags);

    return {
      allowable_tags: allowable_tags,
      tag_replacement: tag_replacement,

      state: STATE_PLAINTEXT,
      tag_buffer: '',
      depth: 0,
      in_quote_char: ''
    };
  }

  function striptags_internal(html, context) {
    var allowable_tags = context.allowable_tags;
    var tag_replacement = context.tag_replacement;

    var state = context.state;
    var tag_buffer = context.tag_buffer;
    var depth = context.depth;
    var in_quote_char = context.in_quote_char;
    var output = '';

    for (var idx = 0, length = html.length; idx < length; idx++) {
      var char = html[idx];

      if (state === STATE_PLAINTEXT) {
        switch (char) {
          case '<':
            state = STATE_HTML;
            tag_buffer += char;
            break;

          default:
            output += char;
            break;
        }
      } else if (state === STATE_HTML) {
        switch (char) {
          case '<':
            // ignore '<' if inside a quote
            if (in_quote_char) {
              break;
            }

            // we're seeing a nested '<'
            depth++;
            break;

          case '>':
            // ignore '>' if inside a quote
            if (in_quote_char) {
              break;
            }

            // something like this is happening: '<<>>'
            if (depth) {
              depth--;

              break;
            }

            // this is closing the tag in tag_buffer
            in_quote_char = '';
            state = STATE_PLAINTEXT;
            tag_buffer += '>';

            if (allowable_tags.has(normalize_tag(tag_buffer))) {
              output += tag_buffer;
            } else {
              output += tag_replacement;
            }

            tag_buffer = '';
            break;

          case '"':
          case "'":
            // catch both single and double quotes

            if (char === in_quote_char) {
              in_quote_char = '';
            } else {
              in_quote_char = in_quote_char || char;
            }

            tag_buffer += char;
            break;

          case '-':
            if (tag_buffer === '<!-') {
              state = STATE_COMMENT;
            }

            tag_buffer += char;
            break;

          case ' ':
          case '\n':
            if (tag_buffer === '<') {
              state = STATE_PLAINTEXT;
              output += '< ';
              tag_buffer = '';

              break;
            }

            tag_buffer += char;
            break;

          default:
            tag_buffer += char;
            break;
        }
      } else if (state === STATE_COMMENT) {
        switch (char) {
          case '>':
            if (tag_buffer.slice(-2) == '--') {
              // close the comment
              state = STATE_PLAINTEXT;
            }

            tag_buffer = '';
            break;

          default:
            tag_buffer += char;
            break;
        }
      }
    }

    // save the context for future iterations
    context.state = state;
    context.tag_buffer = tag_buffer;
    context.depth = depth;
    context.in_quote_char = in_quote_char;

    return output;
  }

  function parse_allowable_tags(allowable_tags) {
    var tag_set = new Set();

    if (typeof allowable_tags === 'string') {
      var match = void 0;

      while (match = ALLOWED_TAGS_REGEX.exec(allowable_tags)) {
        tag_set.add(match[1]);
      }
    } else if (!_Symbol.nonNative && typeof allowable_tags[_Symbol.iterator] === 'function') {
      tag_set = new Set(allowable_tags);
    } else if (typeof allowable_tags.forEach === 'function') {
      // IE11 compatible
      allowable_tags.forEach(tag_set.add, tag_set);
    }

    return tag_set;
  }

  function normalize_tag(tag_buffer) {
    var match = NORMALIZE_TAG_REGEX.exec(tag_buffer);

    return match ? match[1].toLowerCase() : null;
  }

  if (true) {
    // AMD
    !(__WEBPACK_AMD_DEFINE_RESULT__ = (function module_factory() {
      return striptags;
    }).call(exports, __webpack_require__, exports, module),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  } else {}
})(undefined);
//# sourceMappingURL=striptags.js.map

/***/ }),

/***/ "qy1W":
/*!*******************************************************!*\
  !*** ./node_modules/fbjs/lib/createArrayFromMixed.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks
 */

var invariant = __webpack_require__(/*! ./invariant */ "2NuI");

/**
 * Convert array-like objects to arrays.
 *
 * This API assumes the caller knows the contents of the data type. For less
 * well defined inputs use createArrayFromMixed.
 *
 * @param {object|function|filelist} obj
 * @return {array}
 */
function toArray(obj) {
  var length = obj.length;

  // Some browsers builtin objects can report typeof 'function' (e.g. NodeList
  // in old versions of Safari).
  !(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ?  true ? invariant(false, 'toArray: Array-like object expected') : undefined : void 0;

  !(typeof length === 'number') ?  true ? invariant(false, 'toArray: Object needs a length property') : undefined : void 0;

  !(length === 0 || length - 1 in obj) ?  true ? invariant(false, 'toArray: Object should have keys for indices') : undefined : void 0;

  !(typeof obj.callee !== 'function') ?  true ? invariant(false, 'toArray: Object can\'t be `arguments`. Use rest params ' + '(function(...args) {}) or Array.from() instead.') : undefined : void 0;

  // Old IE doesn't give collections access to hasOwnProperty. Assume inputs
  // without method will throw during the slice call and skip straight to the
  // fallback.
  if (obj.hasOwnProperty) {
    try {
      return Array.prototype.slice.call(obj);
    } catch (e) {
      // IE < 9 does not support Array#slice on collections objects
    }
  }

  // Fall back to copying key by key. This assumes all keys have a value,
  // so will not preserve sparsely populated inputs.
  var ret = Array(length);
  for (var ii = 0; ii < length; ii++) {
    ret[ii] = obj[ii];
  }
  return ret;
}

/**
 * Perform a heuristic test to determine if an object is "array-like".
 *
 *   A monk asked Joshu, a Zen master, "Has a dog Buddha nature?"
 *   Joshu replied: "Mu."
 *
 * This function determines if its argument has "array nature": it returns
 * true if the argument is an actual array, an `arguments' object, or an
 * HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()).
 *
 * It will return false for other array-like objects like Filelist.
 *
 * @param {*} obj
 * @return {boolean}
 */
function hasArrayNature(obj) {
  return (
    // not null/false
    !!obj && (
    // arrays are objects, NodeLists are functions in Safari
    typeof obj == 'object' || typeof obj == 'function') &&
    // quacks like an array
    'length' in obj &&
    // not window
    !('setInterval' in obj) &&
    // no DOM node should be considered an array-like
    // a 'select' element has 'length' and 'item' properties on IE8
    typeof obj.nodeType != 'number' && (
    // a real array
    Array.isArray(obj) ||
    // arguments
    'callee' in obj ||
    // HTMLCollection/NodeList
    'item' in obj)
  );
}

/**
 * Ensure that the argument is an array by wrapping it in an array if it is not.
 * Creates a copy of the argument if it is already an array.
 *
 * This is mostly useful idiomatically:
 *
 *   var createArrayFromMixed = require('createArrayFromMixed');
 *
 *   function takesOneOrMoreThings(things) {
 *     things = createArrayFromMixed(things);
 *     ...
 *   }
 *
 * This allows you to treat `things' as an array, but accept scalars in the API.
 *
 * If you need to convert an array-like object, like `arguments`, into an array
 * use toArray instead.
 *
 * @param {*} obj
 * @return {array}
 */
function createArrayFromMixed(obj) {
  if (!hasArrayNature(obj)) {
    return [obj];
  } else if (Array.isArray(obj)) {
    return obj.slice();
  } else {
    return toArray(obj);
  }
}

module.exports = createArrayFromMixed;

/***/ }),

/***/ "r+9r":
/*!****************************************************************!*\
  !*** ./node_modules/draft-js-import-html/lib/stateFromHTML.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = stateFromHTML;

var _draftJsImportElement = __webpack_require__(/*! draft-js-import-element */ "ZM8Y");

var _parseHTML = __webpack_require__(/*! ./parseHTML */ "rbRy");

var _parseHTML2 = _interopRequireDefault(_parseHTML);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

var defaultOptions = {};

function stateFromHTML(html, options) {
  var _ref = options || defaultOptions,
      parser = _ref.parser,
      otherOptions = _objectWithoutProperties(_ref, ['parser']);

  if (parser == null) {
    parser = _parseHTML2.default;
  }
  var element = parser(html);
  return (0, _draftJsImportElement.stateFromElement)(element, otherOptions);
}

/***/ }),

/***/ "r+t4":
/*!*****************************************************!*\
  !*** ./node_modules/@jupyterlab/cells/lib/model.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const attachments_1 = __webpack_require__(/*! @jupyterlab/attachments */ "5M+I");
const codeeditor_1 = __webpack_require__(/*! @jupyterlab/codeeditor */ "sLCx");
const coreutils_2 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const outputarea_1 = __webpack_require__(/*! @jupyterlab/outputarea */ "nGIF");
function isCodeCellModel(model) {
    return model.type === 'code';
}
exports.isCodeCellModel = isCodeCellModel;
function isMarkdownCellModel(model) {
    return model.type === 'markdown';
}
exports.isMarkdownCellModel = isMarkdownCellModel;
function isRawCellModel(model) {
    return model.type === 'raw';
}
exports.isRawCellModel = isRawCellModel;
/**
 * An implementation of the cell model.
 */
class CellModel extends codeeditor_1.CodeEditor.Model {
    /**
     * Construct a cell model from optional cell content.
     */
    constructor(options) {
        super({ modelDB: options.modelDB });
        /**
         * A signal emitted when the state of the model changes.
         */
        this.contentChanged = new signaling_1.Signal(this);
        /**
         * A signal emitted when a model state changes.
         */
        this.stateChanged = new signaling_1.Signal(this);
        this.id = options.id || coreutils_2.UUID.uuid4();
        this.value.changed.connect(this.onGenericChange, this);
        let cellType = this.modelDB.createValue('type');
        cellType.set(this.type);
        let observableMetadata = this.modelDB.createMap('metadata');
        observableMetadata.changed.connect(this.onGenericChange, this);
        let cell = options.cell;
        let trusted = this.modelDB.createValue('trusted');
        trusted.changed.connect(this.onTrustedChanged, this);
        if (!cell) {
            trusted.set(false);
            return;
        }
        trusted.set(!!cell.metadata['trusted']);
        delete cell.metadata['trusted'];
        if (Array.isArray(cell.source)) {
            this.value.text = cell.source.join('');
        }
        else {
            this.value.text = cell.source;
        }
        let metadata = coreutils_1.JSONExt.deepCopy(cell.metadata);
        if (this.type !== 'raw') {
            delete metadata['format'];
        }
        if (this.type !== 'code') {
            delete metadata['collapsed'];
            delete metadata['scrolled'];
        }
        for (let key in metadata) {
            observableMetadata.set(key, metadata[key]);
        }
    }
    /**
     * The metadata associated with the cell.
     */
    get metadata() {
        return this.modelDB.get('metadata');
    }
    /**
     * Get the trusted state of the model.
     */
    get trusted() {
        return this.modelDB.getValue('trusted');
    }
    /**
     * Set the trusted state of the model.
     */
    set trusted(newValue) {
        let oldValue = this.trusted;
        if (oldValue === newValue) {
            return;
        }
        this.modelDB.setValue('trusted', newValue);
    }
    /**
     * Serialize the model to JSON.
     */
    toJSON() {
        let metadata = Object.create(null);
        for (let key of this.metadata.keys()) {
            let value = JSON.parse(JSON.stringify(this.metadata.get(key)));
            metadata[key] = value;
        }
        if (this.trusted) {
            metadata['trusted'] = true;
        }
        return {
            cell_type: this.type,
            source: this.value.text,
            metadata
        };
    }
    /**
     * Handle a change to the trusted state.
     *
     * The default implementation is a no-op.
     */
    onTrustedChanged(trusted, args) {
        /* no-op */
    }
    /**
     * Handle a change to the observable value.
     */
    onGenericChange() {
        this.contentChanged.emit(void 0);
    }
}
exports.CellModel = CellModel;
/**
 * A base implementation for cell models with attachments.
 */
class AttachmentsCellModel extends CellModel {
    /**
     * Construct a new cell with optional attachments.
     */
    constructor(options) {
        super(options);
        this._attachments = null;
        let factory = options.contentFactory || AttachmentsCellModel.defaultContentFactory;
        let attachments;
        let cell = options.cell;
        if (cell && (cell.cell_type === 'raw' || cell.cell_type === 'markdown')) {
            attachments = cell
                .attachments;
        }
        this._attachments = factory.createAttachmentsModel({
            values: attachments,
            modelDB: this.modelDB
        });
        this._attachments.stateChanged.connect(this.onGenericChange, this);
    }
    /**
     * Get the attachments of the model.
     */
    get attachments() {
        return this._attachments;
    }
    /**
     * Serialize the model to JSON.
     */
    toJSON() {
        let cell = super.toJSON();
        if (this.attachments.length) {
            cell.attachments = this.attachments.toJSON();
        }
        return cell;
    }
}
exports.AttachmentsCellModel = AttachmentsCellModel;
/**
 * The namespace for `AttachmentsCellModel` statics.
 */
(function (AttachmentsCellModel) {
    /**
     * The default implementation of an `IContentFactory`.
     */
    class ContentFactory {
        /**
         * Create an attachments model.
         */
        createAttachmentsModel(options) {
            return new attachments_1.AttachmentsModel(options);
        }
    }
    AttachmentsCellModel.ContentFactory = ContentFactory;
    /**
     * The shared `ContentFactory` instance.
     */
    AttachmentsCellModel.defaultContentFactory = new ContentFactory();
})(AttachmentsCellModel = exports.AttachmentsCellModel || (exports.AttachmentsCellModel = {}));
/**
 * An implementation of a raw cell model.
 */
class RawCellModel extends AttachmentsCellModel {
    /**
     * The type of the cell.
     */
    get type() {
        return 'raw';
    }
    /**
     * Serialize the model to JSON.
     */
    toJSON() {
        return super.toJSON();
    }
}
exports.RawCellModel = RawCellModel;
/**
 * An implementation of a markdown cell model.
 */
class MarkdownCellModel extends AttachmentsCellModel {
    /**
     * Construct a markdown cell model from optional cell content.
     */
    constructor(options) {
        super(options);
        // Use the Github-flavored markdown mode.
        this.mimeType = 'text/x-ipythongfm';
    }
    /**
     * The type of the cell.
     */
    get type() {
        return 'markdown';
    }
    /**
     * Serialize the model to JSON.
     */
    toJSON() {
        return super.toJSON();
    }
}
exports.MarkdownCellModel = MarkdownCellModel;
/**
 * An implementation of a code cell Model.
 */
class CodeCellModel extends CellModel {
    /**
     * Construct a new code cell with optional original cell content.
     */
    constructor(options) {
        super(options);
        this._outputs = null;
        let factory = options.contentFactory || CodeCellModel.defaultContentFactory;
        let trusted = this.trusted;
        let cell = options.cell;
        let outputs = [];
        let executionCount = this.modelDB.createValue('executionCount');
        if (!executionCount.get()) {
            if (cell && cell.cell_type === 'code') {
                executionCount.set(cell.execution_count || null);
                outputs = cell.outputs;
            }
            else {
                executionCount.set(null);
            }
        }
        executionCount.changed.connect(this._onExecutionCountChanged, this);
        this._outputs = factory.createOutputArea({
            trusted,
            values: outputs,
            modelDB: this.modelDB
        });
        this._outputs.changed.connect(this.onGenericChange, this);
    }
    /**
     * The type of the cell.
     */
    get type() {
        return 'code';
    }
    /**
     * The execution count of the cell.
     */
    get executionCount() {
        return this.modelDB.getValue('executionCount');
    }
    set executionCount(newValue) {
        let oldValue = this.executionCount;
        if (newValue === oldValue) {
            return;
        }
        this.modelDB.setValue('executionCount', newValue || null);
    }
    /**
     * The cell outputs.
     */
    get outputs() {
        return this._outputs;
    }
    /**
     * Dispose of the resources held by the model.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._outputs.dispose();
        this._outputs = null;
        super.dispose();
    }
    /**
     * Serialize the model to JSON.
     */
    toJSON() {
        let cell = super.toJSON();
        cell.execution_count = this.executionCount || null;
        cell.outputs = this.outputs.toJSON();
        return cell;
    }
    /**
     * Handle a change to the trusted state.
     */
    onTrustedChanged(trusted, args) {
        if (this._outputs) {
            this._outputs.trusted = args.newValue;
        }
        this.stateChanged.emit({
            name: 'trusted',
            oldValue: args.oldValue,
            newValue: args.newValue
        });
    }
    /**
     * Handle a change to the execution count.
     */
    _onExecutionCountChanged(count, args) {
        this.contentChanged.emit(void 0);
        this.stateChanged.emit({
            name: 'executionCount',
            oldValue: args.oldValue,
            newValue: args.newValue
        });
    }
}
exports.CodeCellModel = CodeCellModel;
/**
 * The namespace for `CodeCellModel` statics.
 */
(function (CodeCellModel) {
    /**
     * The default implementation of an `IContentFactory`.
     */
    class ContentFactory {
        /**
         * Create an output area.
         */
        createOutputArea(options) {
            return new outputarea_1.OutputAreaModel(options);
        }
    }
    CodeCellModel.ContentFactory = ContentFactory;
    /**
     * The shared `ContentFactory` instance.
     */
    CodeCellModel.defaultContentFactory = new ContentFactory();
})(CodeCellModel = exports.CodeCellModel || (exports.CodeCellModel = {}));


/***/ }),

/***/ "r2ia":
/*!*************************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/tokenize.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.default = tokenizer;
var SINGLE_QUOTE = 39;
var DOUBLE_QUOTE = 34;
var BACKSLASH = 92;
var SLASH = 47;
var NEWLINE = 10;
var SPACE = 32;
var FEED = 12;
var TAB = 9;
var CR = 13;
var OPEN_SQUARE = 91;
var CLOSE_SQUARE = 93;
var OPEN_PARENTHESES = 40;
var CLOSE_PARENTHESES = 41;
var OPEN_CURLY = 123;
var CLOSE_CURLY = 125;
var SEMICOLON = 59;
var ASTERISK = 42;
var COLON = 58;
var AT = 64;

var RE_AT_END = /[ \n\t\r\f\{\}\(\)'"\\;/\[\]#]/g;
var RE_WORD_END = /[ \n\t\r\f\(\)\{\}:;@!'"\\\]\[#]|\/(?=\*)/g;
var RE_BAD_BRACKET = /.[\\\/\("'\n]/;
var RE_HEX_ESCAPE = /[a-f0-9]/i;

function tokenizer(input) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

    var css = input.css.valueOf();
    var ignore = options.ignoreErrors;

    var code = void 0,
        next = void 0,
        quote = void 0,
        lines = void 0,
        last = void 0,
        content = void 0,
        escape = void 0,
        nextLine = void 0,
        nextOffset = void 0,
        escaped = void 0,
        escapePos = void 0,
        prev = void 0,
        n = void 0,
        currentToken = void 0;

    var length = css.length;
    var offset = -1;
    var line = 1;
    var pos = 0;
    var buffer = [];
    var returned = [];

    function unclosed(what) {
        throw input.error('Unclosed ' + what, line, pos - offset);
    }

    function endOfFile() {
        return returned.length === 0 && pos >= length;
    }

    function nextToken() {
        if (returned.length) return returned.pop();
        if (pos >= length) return;

        code = css.charCodeAt(pos);
        if (code === NEWLINE || code === FEED || code === CR && css.charCodeAt(pos + 1) !== NEWLINE) {
            offset = pos;
            line += 1;
        }

        switch (code) {
            case NEWLINE:
            case SPACE:
            case TAB:
            case CR:
            case FEED:
                next = pos;
                do {
                    next += 1;
                    code = css.charCodeAt(next);
                    if (code === NEWLINE) {
                        offset = next;
                        line += 1;
                    }
                } while (code === SPACE || code === NEWLINE || code === TAB || code === CR || code === FEED);

                currentToken = ['space', css.slice(pos, next)];
                pos = next - 1;
                break;

            case OPEN_SQUARE:
                currentToken = ['[', '[', line, pos - offset];
                break;

            case CLOSE_SQUARE:
                currentToken = [']', ']', line, pos - offset];
                break;

            case OPEN_CURLY:
                currentToken = ['{', '{', line, pos - offset];
                break;

            case CLOSE_CURLY:
                currentToken = ['}', '}', line, pos - offset];
                break;

            case COLON:
                currentToken = [':', ':', line, pos - offset];
                break;

            case SEMICOLON:
                currentToken = [';', ';', line, pos - offset];
                break;

            case OPEN_PARENTHESES:
                prev = buffer.length ? buffer.pop()[1] : '';
                n = css.charCodeAt(pos + 1);
                if (prev === 'url' && n !== SINGLE_QUOTE && n !== DOUBLE_QUOTE && n !== SPACE && n !== NEWLINE && n !== TAB && n !== FEED && n !== CR) {
                    next = pos;
                    do {
                        escaped = false;
                        next = css.indexOf(')', next + 1);
                        if (next === -1) {
                            if (ignore) {
                                next = pos;
                                break;
                            } else {
                                unclosed('bracket');
                            }
                        }
                        escapePos = next;
                        while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
                            escapePos -= 1;
                            escaped = !escaped;
                        }
                    } while (escaped);

                    currentToken = ['brackets', css.slice(pos, next + 1), line, pos - offset, line, next - offset];

                    pos = next;
                } else {
                    next = css.indexOf(')', pos + 1);
                    content = css.slice(pos, next + 1);

                    if (next === -1 || RE_BAD_BRACKET.test(content)) {
                        currentToken = ['(', '(', line, pos - offset];
                    } else {
                        currentToken = ['brackets', content, line, pos - offset, line, next - offset];
                        pos = next;
                    }
                }

                break;

            case CLOSE_PARENTHESES:
                currentToken = [')', ')', line, pos - offset];
                break;

            case SINGLE_QUOTE:
            case DOUBLE_QUOTE:
                quote = code === SINGLE_QUOTE ? '\'' : '"';
                next = pos;
                do {
                    escaped = false;
                    next = css.indexOf(quote, next + 1);
                    if (next === -1) {
                        if (ignore) {
                            next = pos + 1;
                            break;
                        } else {
                            unclosed('string');
                        }
                    }
                    escapePos = next;
                    while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
                        escapePos -= 1;
                        escaped = !escaped;
                    }
                } while (escaped);

                content = css.slice(pos, next + 1);
                lines = content.split('\n');
                last = lines.length - 1;

                if (last > 0) {
                    nextLine = line + last;
                    nextOffset = next - lines[last].length;
                } else {
                    nextLine = line;
                    nextOffset = offset;
                }

                currentToken = ['string', css.slice(pos, next + 1), line, pos - offset, nextLine, next - nextOffset];

                offset = nextOffset;
                line = nextLine;
                pos = next;
                break;

            case AT:
                RE_AT_END.lastIndex = pos + 1;
                RE_AT_END.test(css);
                if (RE_AT_END.lastIndex === 0) {
                    next = css.length - 1;
                } else {
                    next = RE_AT_END.lastIndex - 2;
                }

                currentToken = ['at-word', css.slice(pos, next + 1), line, pos - offset, line, next - offset];

                pos = next;
                break;

            case BACKSLASH:
                next = pos;
                escape = true;
                while (css.charCodeAt(next + 1) === BACKSLASH) {
                    next += 1;
                    escape = !escape;
                }
                code = css.charCodeAt(next + 1);
                if (escape && code !== SLASH && code !== SPACE && code !== NEWLINE && code !== TAB && code !== CR && code !== FEED) {
                    next += 1;
                    if (RE_HEX_ESCAPE.test(css.charAt(next))) {
                        while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) {
                            next += 1;
                        }
                        if (css.charCodeAt(next + 1) === SPACE) {
                            next += 1;
                        }
                    }
                }

                currentToken = ['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset];

                pos = next;
                break;

            default:
                if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
                    next = css.indexOf('*/', pos + 2) + 1;
                    if (next === 0) {
                        if (ignore) {
                            next = css.length;
                        } else {
                            unclosed('comment');
                        }
                    }

                    content = css.slice(pos, next + 1);
                    lines = content.split('\n');
                    last = lines.length - 1;

                    if (last > 0) {
                        nextLine = line + last;
                        nextOffset = next - lines[last].length;
                    } else {
                        nextLine = line;
                        nextOffset = offset;
                    }

                    currentToken = ['comment', content, line, pos - offset, nextLine, next - nextOffset];

                    offset = nextOffset;
                    line = nextLine;
                    pos = next;
                } else {
                    RE_WORD_END.lastIndex = pos + 1;
                    RE_WORD_END.test(css);
                    if (RE_WORD_END.lastIndex === 0) {
                        next = css.length - 1;
                    } else {
                        next = RE_WORD_END.lastIndex - 2;
                    }

                    currentToken = ['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset];

                    buffer.push(currentToken);

                    pos = next;
                }

                break;
        }

        pos++;
        return currentToken;
    }

    function back(token) {
        returned.push(token);
    }

    return {
        back: back,
        nextToken: nextToken,
        endOfFile: endOfFile
    };
}
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64, 


/***/ }),

/***/ "r6nK":
/*!*********************************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/components/color/attributes.js ***!
  \*********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




// IMPORTANT - default colors should be in hex for compatibility
exports.defaults = [
    '#1f77b4',  // muted blue
    '#ff7f0e',  // safety orange
    '#2ca02c',  // cooked asparagus green
    '#d62728',  // brick red
    '#9467bd',  // muted purple
    '#8c564b',  // chestnut brown
    '#e377c2',  // raspberry yogurt pink
    '#7f7f7f',  // middle gray
    '#bcbd22',  // curry yellow-green
    '#17becf'   // blue-teal
];

exports.defaultLine = '#444';

exports.lightLine = '#eee';

exports.background = '#fff';

exports.borderLine = '#BEC8D9';

// with axis.color and Color.interp we aren't using lightLine
// itself anymore, instead interpolating between axis.color
// and the background color using tinycolor.mix. lightFraction
// gives back exactly lightLine if the other colors are defaults.
exports.lightFraction = 100 * (0xe - 0x4) / (0xf - 0x4);


/***/ }),

/***/ "r8R9":
/*!*************************************************************!*\
  !*** ./node_modules/@jupyterlab/codemirror/lib/mimetype.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const mode_1 = __webpack_require__(/*! ./mode */ "Gga1");
/**
 * The mime type service for CodeMirror.
 */
class CodeMirrorMimeTypeService {
    /**
     * Returns a mime type for the given language info.
     *
     * #### Notes
     * If a mime type cannot be found returns the defaul mime type `text/plain`, never `null`.
     */
    getMimeTypeByLanguage(info) {
        let ext = info.file_extension || '';
        return mode_1.Mode.findBest(info.codemirror_mode || {
            mimetype: info.mimetype,
            name: info.name,
            ext: [ext.split('.').slice(-1)[0]]
        }).mime;
    }
    /**
     * Returns a mime type for the given file path.
     *
     * #### Notes
     * If a mime type cannot be found returns the default mime type `text/plain`, never `null`.
     */
    getMimeTypeByFilePath(path) {
        const ext = coreutils_1.PathExt.extname(path);
        if (ext === '.ipy') {
            return 'text/x-python';
        }
        else if (ext === '.md') {
            return 'text/x-ipythongfm';
        }
        let mode = mode_1.Mode.findByFileName(path) || mode_1.Mode.findBest('');
        return mode.mime;
    }
}
exports.CodeMirrorMimeTypeService = CodeMirrorMimeTypeService;


/***/ }),

/***/ "rAV9":
/*!*****************************************************************!*\
  !*** ./node_modules/draft-js/lib/DefaultDraftBlockRenderMap.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule DefaultDraftBlockRenderMap
 * @format
 * 
 */



var _require = __webpack_require__(/*! immutable */ "JPcv"),
    Map = _require.Map;

var React = __webpack_require__(/*! react */ "q1tI");

var cx = __webpack_require__(/*! fbjs/lib/cx */ "YVIB");

var UL_WRAP = React.createElement('ul', { className: cx('public/DraftStyleDefault/ul') });
var OL_WRAP = React.createElement('ol', { className: cx('public/DraftStyleDefault/ol') });
var PRE_WRAP = React.createElement('pre', { className: cx('public/DraftStyleDefault/pre') });

var DefaultDraftBlockRenderMap = Map({
  'header-one': {
    element: 'h1'
  },
  'header-two': {
    element: 'h2'
  },
  'header-three': {
    element: 'h3'
  },
  'header-four': {
    element: 'h4'
  },
  'header-five': {
    element: 'h5'
  },
  'header-six': {
    element: 'h6'
  },
  'unordered-list-item': {
    element: 'li',
    wrapper: UL_WRAP
  },
  'ordered-list-item': {
    element: 'li',
    wrapper: OL_WRAP
  },
  blockquote: {
    element: 'blockquote'
  },
  atomic: {
    element: 'figure'
  },
  'code-block': {
    element: 'pre',
    wrapper: PRE_WRAP
  },
  unstyled: {
    element: 'div',
    aliasedElements: ['p']
  }
});

module.exports = DefaultDraftBlockRenderMap;

/***/ }),

/***/ "rE/H":
/*!*****************************************************!*\
  !*** ./node_modules/json-stable-stringify/index.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var json = typeof JSON !== 'undefined' ? JSON : __webpack_require__(/*! jsonify */ "dsut");

module.exports = function (obj, opts) {
    if (!opts) opts = {};
    if (typeof opts === 'function') opts = { cmp: opts };
    var space = opts.space || '';
    if (typeof space === 'number') space = Array(space+1).join(' ');
    var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;
    var replacer = opts.replacer || function(key, value) { return value; };

    var cmp = opts.cmp && (function (f) {
        return function (node) {
            return function (a, b) {
                var aobj = { key: a, value: node[a] };
                var bobj = { key: b, value: node[b] };
                return f(aobj, bobj);
            };
        };
    })(opts.cmp);

    var seen = [];
    return (function stringify (parent, key, node, level) {
        var indent = space ? ('\n' + new Array(level + 1).join(space)) : '';
        var colonSeparator = space ? ': ' : ':';

        if (node && node.toJSON && typeof node.toJSON === 'function') {
            node = node.toJSON();
        }

        node = replacer.call(parent, key, node);

        if (node === undefined) {
            return;
        }
        if (typeof node !== 'object' || node === null) {
            return json.stringify(node);
        }
        if (isArray(node)) {
            var out = [];
            for (var i = 0; i < node.length; i++) {
                var item = stringify(node, i, node[i], level+1) || json.stringify(null);
                out.push(indent + space + item);
            }
            return '[' + out.join(',') + indent + ']';
        }
        else {
            if (seen.indexOf(node) !== -1) {
                if (cycles) return json.stringify('__cycle__');
                throw new TypeError('Converting circular structure to JSON');
            }
            else seen.push(node);

            var keys = objectKeys(node).sort(cmp && cmp(node));
            var out = [];
            for (var i = 0; i < keys.length; i++) {
                var key = keys[i];
                var value = stringify(node, key, node[key], level+1);

                if(!value) continue;

                var keyValue = json.stringify(key)
                    + colonSeparator
                    + value;
                ;
                out.push(indent + space + keyValue);
            }
            seen.splice(seen.indexOf(node), 1);
            return '{' + out.join(',') + indent + '}';
        }
    })({ '': obj }, '', obj, 0);
};

var isArray = Array.isArray || function (x) {
    return {}.toString.call(x) === '[object Array]';
};

var objectKeys = Object.keys || function (obj) {
    var has = Object.prototype.hasOwnProperty || function () { return true };
    var keys = [];
    for (var key in obj) {
        if (has.call(obj, key)) keys.push(key);
    }
    return keys;
};


/***/ }),

/***/ "rEGp":
/*!********************************************!*\
  !*** ./node_modules/lodash/_setToArray.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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;
}

module.exports = setToArray;


/***/ }),

/***/ "rHEf":
/*!************************************************************!*\
  !*** ./node_modules/xterm/lib/handlers/AltClickHandler.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var EscapeSequences_1 = __webpack_require__(/*! ../EscapeSequences */ "XYdm");
var Direction;
(function (Direction) {
    Direction["Up"] = "A";
    Direction["Down"] = "B";
    Direction["Right"] = "C";
    Direction["Left"] = "D";
})(Direction || (Direction = {}));
var AltClickHandler = (function () {
    function AltClickHandler(_mouseEvent, _terminal) {
        this._mouseEvent = _mouseEvent;
        this._terminal = _terminal;
        this._lines = this._terminal.buffer.lines;
        this._startCol = this._terminal.buffer.x;
        this._startRow = this._terminal.buffer.y;
        _a = this._terminal.mouseHelper.getCoords(this._mouseEvent, this._terminal.element, this._terminal.charMeasure, this._terminal.options.lineHeight, this._terminal.cols, this._terminal.rows, false).map(function (coordinate) {
            return coordinate - 1;
        }), this._endCol = _a[0], this._endRow = _a[1];
        var _a;
    }
    AltClickHandler.prototype.move = function () {
        if (this._mouseEvent.altKey) {
            this._terminal.send(this._arrowSequences());
        }
    };
    AltClickHandler.prototype._arrowSequences = function () {
        if (!this._terminal.buffer.hasScrollback) {
            return this._resetStartingRow() + this._moveToRequestedRow() + this._moveToRequestedCol();
        }
        return this._moveHorizontallyOnly();
    };
    AltClickHandler.prototype._resetStartingRow = function () {
        if (this._moveToRequestedRow().length === 0) {
            return '';
        }
        else {
            return repeat(this._bufferLine(this._startCol, this._startRow, this._startCol, this._startRow - this._wrappedRowsForRow(this._startRow), false).length, this._sequence(Direction.Left));
        }
    };
    AltClickHandler.prototype._moveToRequestedRow = function () {
        var startRow = this._startRow - this._wrappedRowsForRow(this._startRow);
        var endRow = this._endRow - this._wrappedRowsForRow(this._endRow);
        var rowsToMove = Math.abs(startRow - endRow) - this._wrappedRowsCount();
        return repeat(rowsToMove, this._sequence(this._verticalDirection()));
    };
    AltClickHandler.prototype._moveToRequestedCol = function () {
        var startRow;
        if (this._moveToRequestedRow().length > 0) {
            startRow = this._endRow - this._wrappedRowsForRow(this._endRow);
        }
        else {
            startRow = this._startRow;
        }
        var endRow = this._endRow;
        var direction = this._horizontalDirection();
        return repeat(this._bufferLine(this._startCol, startRow, this._endCol, endRow, direction === Direction.Right).length, this._sequence(direction));
    };
    AltClickHandler.prototype._moveHorizontallyOnly = function () {
        var direction = this._horizontalDirection();
        return repeat(Math.abs(this._startCol - this._endCol), this._sequence(direction));
    };
    AltClickHandler.prototype._wrappedRowsCount = function () {
        var wrappedRows = 0;
        var startRow = this._startRow - this._wrappedRowsForRow(this._startRow);
        var endRow = this._endRow - this._wrappedRowsForRow(this._endRow);
        for (var i = 0; i < Math.abs(startRow - endRow); i++) {
            var direction = this._verticalDirection() === Direction.Up ? -1 : 1;
            if (this._lines.get(startRow + (direction * i)).isWrapped) {
                wrappedRows++;
            }
        }
        return wrappedRows;
    };
    AltClickHandler.prototype._wrappedRowsForRow = function (currentRow) {
        var rowCount = 0;
        var lineWraps = this._lines.get(currentRow).isWrapped;
        while (lineWraps && currentRow >= 0 && currentRow < this._terminal.rows) {
            rowCount++;
            currentRow--;
            lineWraps = this._lines.get(currentRow).isWrapped;
        }
        return rowCount;
    };
    AltClickHandler.prototype._horizontalDirection = function () {
        var startRow;
        if (this._moveToRequestedRow().length > 0) {
            startRow = this._endRow - this._wrappedRowsForRow(this._endRow);
        }
        else {
            startRow = this._startRow;
        }
        if ((this._startCol < this._endCol &&
            startRow <= this._endRow) ||
            (this._startCol >= this._endCol &&
                startRow < this._endRow)) {
            return Direction.Right;
        }
        else {
            return Direction.Left;
        }
    };
    AltClickHandler.prototype._verticalDirection = function () {
        if (this._startRow > this._endRow) {
            return Direction.Up;
        }
        else {
            return Direction.Down;
        }
    };
    AltClickHandler.prototype._bufferLine = function (startCol, startRow, endCol, endRow, forward) {
        var currentCol = startCol;
        var currentRow = startRow;
        var bufferStr = '';
        while (currentCol !== endCol || currentRow !== endRow) {
            currentCol += forward ? 1 : -1;
            if (forward && currentCol > this._terminal.cols - 1) {
                bufferStr += this._terminal.buffer.translateBufferLineToString(currentRow, false, startCol, currentCol);
                currentCol = 0;
                startCol = 0;
                currentRow++;
            }
            else if (!forward && currentCol < 0) {
                bufferStr += this._terminal.buffer.translateBufferLineToString(currentRow, false, 0, startCol + 1);
                currentCol = this._terminal.cols - 1;
                startCol = currentCol;
                currentRow--;
            }
        }
        return bufferStr + this._terminal.buffer.translateBufferLineToString(currentRow, false, startCol, currentCol);
    };
    AltClickHandler.prototype._sequence = function (direction) {
        var mod = this._terminal.applicationCursor ? 'O' : '[';
        return EscapeSequences_1.C0.ESC + mod + direction;
    };
    return AltClickHandler;
}());
exports.AltClickHandler = AltClickHandler;
function repeat(count, str) {
    count = Math.floor(count);
    var rpt = '';
    for (var i = 0; i < count; i++) {
        rpt += str;
    }
    return rpt;
}

//# sourceMappingURL=AltClickHandler.js.map


/***/ }),

/***/ "rIs4":
/*!*************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/localize.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

exports.default = localize;
exports.localizeString = localizeString;

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _ = __webpack_require__(/*! ./ */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function localize(Comp) {
  var LocalizedComponent = function (_Component) {
    _inherits(LocalizedComponent, _Component);

    function LocalizedComponent(props, context) {
      _classCallCheck(this, LocalizedComponent);

      var _this = _possibleConstructorReturn(this, (LocalizedComponent.__proto__ || Object.getPrototypeOf(LocalizedComponent)).call(this, props, context));

      var dictionaries = context.dictionaries;
      var locale = context.locale;

      _this.localize = function localize(str) {
        return localizeString(dictionaries, locale, str);
      };
      return _this;
    }

    _createClass(LocalizedComponent, [{
      key: 'render',
      value: function render() {
        return _react2.default.createElement(Comp, _extends({ localize: this.localize }, this.props));
      }
    }]);

    return LocalizedComponent;
  }(_react.Component);

  LocalizedComponent.displayName = 'Localized' + (0, _.getDisplayName)(Comp);
  LocalizedComponent.contextTypes = LocalizedComponent.contextTypes || {};
  LocalizedComponent.contextTypes.dictionaries = _propTypes2.default.object;
  LocalizedComponent.contextTypes.locale = _propTypes2.default.string;

  LocalizedComponent.plotly_editor_traits = Comp.plotly_editor_traits;

  return LocalizedComponent;
}

function localizeString(dictionaries, locale, key) {
  var dict = dictionaries[locale];
  if (dict && dict.hasOwnProperty(key)) {
    return dict[key];
  }
  return key;
}
//# sourceMappingURL=localize.js.map

/***/ }),

/***/ "rJ8t":
/*!****************************************************************!*\
  !*** ./node_modules/react-color/lib/components/block/Block.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Block = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _merge = __webpack_require__(/*! lodash/merge */ "QkVN");

var _merge2 = _interopRequireDefault(_merge);

var _color = __webpack_require__(/*! ../../helpers/color */ "p8yl");

var _color2 = _interopRequireDefault(_color);

var _common = __webpack_require__(/*! ../common */ "TM95");

var _BlockSwatches = __webpack_require__(/*! ./BlockSwatches */ "uDUr");

var _BlockSwatches2 = _interopRequireDefault(_BlockSwatches);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var Block = exports.Block = function Block(_ref) {
  var onChange = _ref.onChange,
      onSwatchHover = _ref.onSwatchHover,
      hex = _ref.hex,
      colors = _ref.colors,
      width = _ref.width,
      triangle = _ref.triangle,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var transparent = hex === 'transparent';
  var handleChange = function handleChange(hexCode, e) {
    _color2.default.isValidHex(hexCode) && onChange({
      hex: hexCode,
      source: 'hex'
    }, e);
  };

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': {
      card: {
        width: width,
        background: '#fff',
        boxShadow: '0 1px rgba(0,0,0,.1)',
        borderRadius: '6px',
        position: 'relative'
      },
      head: {
        height: '110px',
        background: hex,
        borderRadius: '6px 6px 0 0',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        position: 'relative'
      },
      body: {
        padding: '10px'
      },
      label: {
        fontSize: '18px',
        color: _color2.default.getContrastingColor(hex),
        position: 'relative'
      },
      triangle: {
        width: '0px',
        height: '0px',
        borderStyle: 'solid',
        borderWidth: '0 10px 10px 10px',
        borderColor: 'transparent transparent ' + hex + ' transparent',
        position: 'absolute',
        top: '-10px',
        left: '50%',
        marginLeft: '-10px'
      },
      input: {
        width: '100%',
        fontSize: '12px',
        color: '#666',
        border: '0px',
        outline: 'none',
        height: '22px',
        boxShadow: 'inset 0 0 0 1px #ddd',
        borderRadius: '4px',
        padding: '0 7px',
        boxSizing: 'border-box'
      }
    },
    'hide-triangle': {
      triangle: {
        display: 'none'
      }
    }
  }, passedStyles), { 'hide-triangle': triangle === 'hide' });

  return _react2.default.createElement(
    'div',
    { style: styles.card, className: 'block-picker ' + className },
    _react2.default.createElement('div', { style: styles.triangle }),
    _react2.default.createElement(
      'div',
      { style: styles.head },
      transparent && _react2.default.createElement(_common.Checkboard, { borderRadius: '6px 6px 0 0' }),
      _react2.default.createElement(
        'div',
        { style: styles.label },
        hex
      )
    ),
    _react2.default.createElement(
      'div',
      { style: styles.body },
      _react2.default.createElement(_BlockSwatches2.default, { colors: colors, onClick: handleChange, onSwatchHover: onSwatchHover }),
      _react2.default.createElement(_common.EditableInput, {
        style: { input: styles.input },
        value: hex,
        onChange: handleChange
      })
    )
  );
};

Block.propTypes = {
  width: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]),
  colors: _propTypes2.default.arrayOf(_propTypes2.default.string),
  triangle: _propTypes2.default.oneOf(['top', 'hide']),
  styles: _propTypes2.default.object
};

Block.defaultProps = {
  width: 170,
  colors: ['#D9E3F0', '#F47373', '#697689', '#37D67A', '#2CCCE4', '#555555', '#dce775', '#ff8a65', '#ba68c8'],
  triangle: 'top',
  styles: {}
};

exports.default = (0, _common.ColorWrap)(Block);

/***/ }),

/***/ "rJY1":
/*!********************************************************!*\
  !*** ./node_modules/draft-js/lib/generateRandomKey.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule generateRandomKey
 * @format
 * 
 */



var seenKeys = {};
var MULTIPLIER = Math.pow(2, 24);

function generateRandomKey() {
  var key = void 0;
  while (key === undefined || seenKeys.hasOwnProperty(key) || !isNaN(+key)) {
    key = Math.floor(Math.random() * MULTIPLIER).toString(32);
  }
  seenKeys[key] = true;
  return key;
}

module.exports = generateRandomKey;

/***/ }),

/***/ "rS4v":
/*!*******************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/EmbedIconIcon.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var EmbedIconIcon = function EmbedIconIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M4.313 15.813l5.75-5.75-2.125-2.125L0 15.813l7.938 7.938 2.125-2.125zM25.188 9l-1.125-1.063-2.125 2.125 1.125 1.063 4.625 4.688-5.75 5.813 2.125 2.125 7.938-7.938zm-10.25 17.75h-3l5.563-21.5h3z' })
    );
};

exports.default = EmbedIconIcon;

/***/ }),

/***/ "rSVQ":
/*!******************************************************!*\
  !*** ./node_modules/public-encrypt/publicEncrypt.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var parseKeys = __webpack_require__(/*! parse-asn1 */ "Ku4m")
var randomBytes = __webpack_require__(/*! randombytes */ "Edxu")
var createHash = __webpack_require__(/*! create-hash */ "mObS")
var mgf = __webpack_require__(/*! ./mgf */ "9GDS")
var xor = __webpack_require__(/*! ./xor */ "g9U9")
var BN = __webpack_require__(/*! bn.js */ "OZ/i")
var withPublic = __webpack_require__(/*! ./withPublic */ "UpF+")
var crt = __webpack_require__(/*! browserify-rsa */ "qVij")
var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer

module.exports = function publicEncrypt (publicKey, msg, reverse) {
  var padding
  if (publicKey.padding) {
    padding = publicKey.padding
  } else if (reverse) {
    padding = 1
  } else {
    padding = 4
  }
  var key = parseKeys(publicKey)
  var paddedMsg
  if (padding === 4) {
    paddedMsg = oaep(key, msg)
  } else if (padding === 1) {
    paddedMsg = pkcs1(key, msg, reverse)
  } else if (padding === 3) {
    paddedMsg = new BN(msg)
    if (paddedMsg.cmp(key.modulus) >= 0) {
      throw new Error('data too long for modulus')
    }
  } else {
    throw new Error('unknown padding')
  }
  if (reverse) {
    return crt(paddedMsg, key)
  } else {
    return withPublic(paddedMsg, key)
  }
}

function oaep (key, msg) {
  var k = key.modulus.byteLength()
  var mLen = msg.length
  var iHash = createHash('sha1').update(Buffer.alloc(0)).digest()
  var hLen = iHash.length
  var hLen2 = 2 * hLen
  if (mLen > k - hLen2 - 2) {
    throw new Error('message too long')
  }
  var ps = Buffer.alloc(k - mLen - hLen2 - 2)
  var dblen = k - hLen - 1
  var seed = randomBytes(hLen)
  var maskedDb = xor(Buffer.concat([iHash, ps, Buffer.alloc(1, 1), msg], dblen), mgf(seed, dblen))
  var maskedSeed = xor(seed, mgf(maskedDb, hLen))
  return new BN(Buffer.concat([Buffer.alloc(1), maskedSeed, maskedDb], k))
}
function pkcs1 (key, msg, reverse) {
  var mLen = msg.length
  var k = key.modulus.byteLength()
  if (mLen > k - 11) {
    throw new Error('message too long')
  }
  var ps
  if (reverse) {
    ps = Buffer.alloc(k - mLen - 3, 0xff)
  } else {
    ps = nonZero(k - mLen - 3)
  }
  return new BN(Buffer.concat([Buffer.from([0, reverse ? 1 : 2]), ps, Buffer.alloc(1), msg], k))
}
function nonZero (len) {
  var out = Buffer.allocUnsafe(len)
  var i = 0
  var cache = randomBytes(len * 2)
  var cur = 0
  var num
  while (i < len) {
    if (cur === cache.length) {
      cache = randomBytes(len * 2)
      cur = 0
    }
    num = cache[cur++]
    if (num) {
      out[i++] = num
    }
  }
  return out
}


/***/ }),

/***/ "rTFf":
/*!******************************************************!*\
  !*** ./node_modules/react-json-tree/lib/JSONNode.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "QbLZ");

var _extends3 = _interopRequireDefault(_extends2);

var _objectWithoutProperties2 = __webpack_require__(/*! babel-runtime/helpers/objectWithoutProperties */ "jo6Y");

var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _objType = __webpack_require__(/*! ./objType */ "ICOY");

var _objType2 = _interopRequireDefault(_objType);

var _JSONObjectNode = __webpack_require__(/*! ./JSONObjectNode */ "7Vtj");

var _JSONObjectNode2 = _interopRequireDefault(_JSONObjectNode);

var _JSONArrayNode = __webpack_require__(/*! ./JSONArrayNode */ "L/Ch");

var _JSONArrayNode2 = _interopRequireDefault(_JSONArrayNode);

var _JSONIterableNode = __webpack_require__(/*! ./JSONIterableNode */ "gYcd");

var _JSONIterableNode2 = _interopRequireDefault(_JSONIterableNode);

var _JSONValueNode = __webpack_require__(/*! ./JSONValueNode */ "q8VL");

var _JSONValueNode2 = _interopRequireDefault(_JSONValueNode);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var JSONNode = function JSONNode(_ref) {
  var getItemString = _ref.getItemString,
      keyPath = _ref.keyPath,
      labelRenderer = _ref.labelRenderer,
      styling = _ref.styling,
      value = _ref.value,
      valueRenderer = _ref.valueRenderer,
      isCustomNode = _ref.isCustomNode,
      rest = (0, _objectWithoutProperties3['default'])(_ref, ['getItemString', 'keyPath', 'labelRenderer', 'styling', 'value', 'valueRenderer', 'isCustomNode']);

  var nodeType = isCustomNode(value) ? 'Custom' : (0, _objType2['default'])(value);

  var simpleNodeProps = {
    getItemString: getItemString,
    key: keyPath[0],
    keyPath: keyPath,
    labelRenderer: labelRenderer,
    nodeType: nodeType,
    styling: styling,
    value: value,
    valueRenderer: valueRenderer
  };

  var nestedNodeProps = (0, _extends3['default'])({}, rest, simpleNodeProps, {
    data: value,
    isCustomNode: isCustomNode
  });

  switch (nodeType) {
    case 'Object':
    case 'Error':
    case 'WeakMap':
    case 'WeakSet':
      return _react2['default'].createElement(_JSONObjectNode2['default'], nestedNodeProps);
    case 'Array':
      return _react2['default'].createElement(_JSONArrayNode2['default'], nestedNodeProps);
    case 'Iterable':
    case 'Map':
    case 'Set':
      return _react2['default'].createElement(_JSONIterableNode2['default'], nestedNodeProps);
    case 'String':
      return _react2['default'].createElement(_JSONValueNode2['default'], (0, _extends3['default'])({}, simpleNodeProps, { valueGetter: function valueGetter(raw) {
          return '"' + raw + '"';
        } }));
    case 'Number':
      return _react2['default'].createElement(_JSONValueNode2['default'], simpleNodeProps);
    case 'Boolean':
      return _react2['default'].createElement(_JSONValueNode2['default'], (0, _extends3['default'])({}, simpleNodeProps, {
        valueGetter: function valueGetter(raw) {
          return raw ? 'true' : 'false';
        }
      }));
    case 'Date':
      return _react2['default'].createElement(_JSONValueNode2['default'], (0, _extends3['default'])({}, simpleNodeProps, {
        valueGetter: function valueGetter(raw) {
          return raw.toISOString();
        }
      }));
    case 'Null':
      return _react2['default'].createElement(_JSONValueNode2['default'], (0, _extends3['default'])({}, simpleNodeProps, { valueGetter: function valueGetter() {
          return 'null';
        } }));
    case 'Undefined':
      return _react2['default'].createElement(_JSONValueNode2['default'], (0, _extends3['default'])({}, simpleNodeProps, { valueGetter: function valueGetter() {
          return 'undefined';
        } }));
    case 'Function':
    case 'Symbol':
      return _react2['default'].createElement(_JSONValueNode2['default'], (0, _extends3['default'])({}, simpleNodeProps, {
        valueGetter: function valueGetter(raw) {
          return raw.toString();
        }
      }));
    case 'Custom':
      return _react2['default'].createElement(_JSONValueNode2['default'], simpleNodeProps);
    default:
      return _react2['default'].createElement(_JSONValueNode2['default'], (0, _extends3['default'])({}, simpleNodeProps, { valueGetter: function valueGetter(raw) {
          return '<' + nodeType + '>';
        } }));
  }
};

JSONNode.propTypes = {
  getItemString: _propTypes2['default'].func.isRequired,
  keyPath: _propTypes2['default'].arrayOf(_propTypes2['default'].oneOfType([_propTypes2['default'].string, _propTypes2['default'].number])).isRequired,
  labelRenderer: _propTypes2['default'].func.isRequired,
  styling: _propTypes2['default'].func.isRequired,
  value: _propTypes2['default'].any,
  valueRenderer: _propTypes2['default'].func.isRequired,
  isCustomNode: _propTypes2['default'].func.isRequired
};

exports['default'] = JSONNode;

/***/ }),

/***/ "rTQe":
/*!**************************************************************!*\
  !*** ./node_modules/@jupyterlab/json-extension/lib/index.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const React = __importStar(__webpack_require__(/*! react */ "q1tI"));
const ReactDOM = __importStar(__webpack_require__(/*! react-dom */ "i8i4"));
const component_1 = __webpack_require__(/*! ./component */ "atcJ");
__webpack_require__(/*! ../style/index.css */ "vWBD");
/**
 * The CSS class to add to the JSON Widget.
 */
const CSS_CLASS = 'jp-RenderedJSON';
/**
 * The MIME type for JSON.
 */
exports.MIME_TYPE = 'application/json';
/**
 * A renderer for JSON data.
 */
class RenderedJSON extends widgets_1.Widget {
    /**
     * Create a new widget for rendering JSON.
     */
    constructor(options) {
        super();
        this.addClass(CSS_CLASS);
        this._mimeType = options.mimeType;
    }
    /**
     * Render JSON into this widget's node.
     */
    renderModel(model) {
        const data = model.data[this._mimeType];
        const metadata = model.metadata[this._mimeType] || {};
        const props = { data, metadata, theme: 'cm-s-jupyter' };
        return new Promise((resolve, reject) => {
            const component = React.createElement(component_1.Component, Object.assign({}, props));
            ReactDOM.render(component, this.node, () => {
                resolve();
            });
        });
    }
}
exports.RenderedJSON = RenderedJSON;
/**
 * A mime renderer factory for JSON data.
 */
exports.rendererFactory = {
    safe: true,
    mimeTypes: [exports.MIME_TYPE],
    createRenderer: options => new RenderedJSON(options)
};
const extensions = [
    {
        id: '@jupyterlab/json-extension:factory',
        rendererFactory: exports.rendererFactory,
        rank: 0,
        dataType: 'json',
        documentWidgetFactoryOptions: {
            name: 'JSON',
            primaryFileType: 'json',
            fileTypes: ['json', 'notebook'],
            defaultFor: ['json']
        }
    }
];
exports.default = extensions;


/***/ }),

/***/ "rVQt":
/*!*******************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/AxesSelector.js ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _Dropdown = __webpack_require__(/*! ../widgets/Dropdown */ "9Rtb");

var _Dropdown2 = _interopRequireDefault(_Dropdown);

var _RadioBlocks = __webpack_require__(/*! ../widgets/RadioBlocks */ "N8y9");

var _RadioBlocks2 = _interopRequireDefault(_RadioBlocks);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var AxesSelector = function (_Component) {
  _inherits(AxesSelector, _Component);

  function AxesSelector(props, context) {
    _classCallCheck(this, AxesSelector);

    var _this = _possibleConstructorReturn(this, (AxesSelector.__proto__ || Object.getPrototypeOf(AxesSelector)).call(this, props, context));

    var _ = context.localize;


    if (!context.axesTargetHandler) {
      throw new Error(_('AxesSelector must be nested within a connectAxesToPlot component'));
    }
    return _this;
  }

  _createClass(AxesSelector, [{
    key: 'render',
    value: function render() {
      var _context = this.context,
          axesTargetHandler = _context.axesTargetHandler,
          axesTarget = _context.axesTarget,
          fullLayout = _context.fullLayout,
          _ = _context.localize;
      var axesOptions = this.props.axesOptions;

      var maxCharsThatFitInRadio = 27;
      var maxOptions = axesOptions.length > 4; // eslint-disable-line

      var multipleSublots = fullLayout && fullLayout._subplots && Object.values(fullLayout._subplots).some(function (s) {
        return s.length > 1;
      });

      var options = multipleSublots ? axesOptions.map(function (option) {
        return option.value === 'allaxes' ? option : {
          label: option.title,
          value: option.value
        };
      }) : axesOptions;

      var totalCharsInOptions = options && options.map(function (o) {
        return o.label;
      }).reduce(function (acc, o) {
        return acc + o.length;
      }, 0) || 0;

      return maxOptions || totalCharsInOptions >= maxCharsThatFitInRadio ? _react2.default.createElement(
        _Field2.default,
        _extends({}, this.props, { label: _('Axis to Style') }),
        _react2.default.createElement(_Dropdown2.default, {
          options: options,
          value: axesTarget,
          onChange: axesTargetHandler,
          clearable: false
        })
      ) : _react2.default.createElement(
        _Field2.default,
        _extends({}, this.props, { center: true }),
        _react2.default.createElement(_RadioBlocks2.default, {
          options: options,
          activeOption: axesTarget,
          onOptionChange: axesTargetHandler
        })
      );
    }
  }]);

  return AxesSelector;
}(_react.Component);

AxesSelector.contextTypes = {
  axesTargetHandler: _propTypes2.default.func,
  axesTarget: _propTypes2.default.string,
  fullLayout: _propTypes2.default.object,
  localize: _propTypes2.default.func
};

AxesSelector.propTypes = {
  axesOptions: _propTypes2.default.array
};

exports.default = AxesSelector;
//# sourceMappingURL=AxesSelector.js.map

/***/ }),

/***/ "rWXM":
/*!****************************************************!*\
  !*** ./node_modules/fbjs/lib/memoizeStringOnly.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * 
 * @typechecks static-only
 */



/**
 * Memoizes the return value of a function that accepts one string argument.
 */

function memoizeStringOnly(callback) {
  var cache = {};
  return function (string) {
    if (!cache.hasOwnProperty(string)) {
      cache[string] = callback.call(this, string);
    }
    return cache[string];
  };
}

module.exports = memoizeStringOnly;

/***/ }),

/***/ "rXFu":
/*!**************************************************************!*\
  !*** ./node_modules/readable-stream/lib/_stream_readable.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors.
//
// 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.



/*<replacement>*/

var pna = __webpack_require__(/*! process-nextick-args */ "lm0R");
/*</replacement>*/

module.exports = Readable;

/*<replacement>*/
var isArray = __webpack_require__(/*! isarray */ "2Nt0");
/*</replacement>*/

/*<replacement>*/
var Duplex;
/*</replacement>*/

Readable.ReadableState = ReadableState;

/*<replacement>*/
var EE = __webpack_require__(/*! events */ "+qE3").EventEmitter;

var EElistenerCount = function (emitter, type) {
  return emitter.listeners(type).length;
};
/*</replacement>*/

/*<replacement>*/
var Stream = __webpack_require__(/*! ./internal/streams/stream */ "QpuX");
/*</replacement>*/

/*<replacement>*/

var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer;
var OurUint8Array = global.Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
  return Buffer.from(chunk);
}
function _isUint8Array(obj) {
  return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}

/*</replacement>*/

/*<replacement>*/
var util = __webpack_require__(/*! core-util-is */ "Onz0");
util.inherits = __webpack_require__(/*! inherits */ "P7XM");
/*</replacement>*/

/*<replacement>*/
var debugUtil = __webpack_require__(/*! util */ 2);
var debug = void 0;
if (debugUtil && debugUtil.debuglog) {
  debug = debugUtil.debuglog('stream');
} else {
  debug = function () {};
}
/*</replacement>*/

var BufferList = __webpack_require__(/*! ./internal/streams/BufferList */ "Xhqo");
var destroyImpl = __webpack_require__(/*! ./internal/streams/destroy */ "RoFp");
var StringDecoder;

util.inherits(Readable, Stream);

var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];

function prependListener(emitter, event, fn) {
  // Sadly this is not cacheable as some libraries bundle their own
  // event emitter implementation with them.
  if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);

  // This is a hack to make sure that our error handler is attached before any
  // userland ones.  NEVER DO THIS. This is here only because this code needs
  // to continue to work with older versions of Node.js that do not include
  // the prependListener() method. The goal is to eventually remove this hack.
  if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
}

function ReadableState(options, stream) {
  Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ "sZro");

  options = options || {};

  // Duplex streams are both readable and writable, but share
  // the same options object.
  // However, some cases require setting options to different
  // values for the readable and the writable sides of the duplex stream.
  // These options can be provided separately as readableXXX and writableXXX.
  var isDuplex = stream instanceof Duplex;

  // object stream flag. Used to make read(n) ignore n and to
  // make all the buffer merging and length checks go away
  this.objectMode = !!options.objectMode;

  if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;

  // the point at which it stops calling _read() to fill the buffer
  // Note: 0 is a valid value, means "don't call _read preemptively ever"
  var hwm = options.highWaterMark;
  var readableHwm = options.readableHighWaterMark;
  var defaultHwm = this.objectMode ? 16 : 16 * 1024;

  if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;

  // cast to ints.
  this.highWaterMark = Math.floor(this.highWaterMark);

  // A linked list is used to store data chunks instead of an array because the
  // linked list can remove elements from the beginning faster than
  // array.shift()
  this.buffer = new BufferList();
  this.length = 0;
  this.pipes = null;
  this.pipesCount = 0;
  this.flowing = null;
  this.ended = false;
  this.endEmitted = false;
  this.reading = false;

  // a flag to be able to tell if the event 'readable'/'data' is emitted
  // immediately, or on a later tick.  We set this to true at first, because
  // any actions that shouldn't happen until "later" should generally also
  // not happen before the first read call.
  this.sync = true;

  // whenever we return null, then we set a flag to say
  // that we're awaiting a 'readable' event emission.
  this.needReadable = false;
  this.emittedReadable = false;
  this.readableListening = false;
  this.resumeScheduled = false;

  // has it been destroyed
  this.destroyed = false;

  // Crypto is kind of old and crusty.  Historically, its default string
  // encoding is 'binary' so we have to make this configurable.
  // Everything else in the universe uses 'utf8', though.
  this.defaultEncoding = options.defaultEncoding || 'utf8';

  // the number of writers that are awaiting a drain event in .pipe()s
  this.awaitDrain = 0;

  // if true, a maybeReadMore has been scheduled
  this.readingMore = false;

  this.decoder = null;
  this.encoding = null;
  if (options.encoding) {
    if (!StringDecoder) StringDecoder = __webpack_require__(/*! string_decoder/ */ "qiJe").StringDecoder;
    this.decoder = new StringDecoder(options.encoding);
    this.encoding = options.encoding;
  }
}

function Readable(options) {
  Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ "sZro");

  if (!(this instanceof Readable)) return new Readable(options);

  this._readableState = new ReadableState(options, this);

  // legacy
  this.readable = true;

  if (options) {
    if (typeof options.read === 'function') this._read = options.read;

    if (typeof options.destroy === 'function') this._destroy = options.destroy;
  }

  Stream.call(this);
}

Object.defineProperty(Readable.prototype, 'destroyed', {
  get: function () {
    if (this._readableState === undefined) {
      return false;
    }
    return this._readableState.destroyed;
  },
  set: function (value) {
    // we ignore the value if the stream
    // has not been initialized yet
    if (!this._readableState) {
      return;
    }

    // backward compatibility, the user is explicitly
    // managing destroyed
    this._readableState.destroyed = value;
  }
});

Readable.prototype.destroy = destroyImpl.destroy;
Readable.prototype._undestroy = destroyImpl.undestroy;
Readable.prototype._destroy = function (err, cb) {
  this.push(null);
  cb(err);
};

// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function (chunk, encoding) {
  var state = this._readableState;
  var skipChunkCheck;

  if (!state.objectMode) {
    if (typeof chunk === 'string') {
      encoding = encoding || state.defaultEncoding;
      if (encoding !== state.encoding) {
        chunk = Buffer.from(chunk, encoding);
        encoding = '';
      }
      skipChunkCheck = true;
    }
  } else {
    skipChunkCheck = true;
  }

  return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
};

// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function (chunk) {
  return readableAddChunk(this, chunk, null, true, false);
};

function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  var state = stream._readableState;
  if (chunk === null) {
    state.reading = false;
    onEofChunk(stream, state);
  } else {
    var er;
    if (!skipChunkCheck) er = chunkInvalid(state, chunk);
    if (er) {
      stream.emit('error', er);
    } else if (state.objectMode || chunk && chunk.length > 0) {
      if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
        chunk = _uint8ArrayToBuffer(chunk);
      }

      if (addToFront) {
        if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
      } else if (state.ended) {
        stream.emit('error', new Error('stream.push() after EOF'));
      } else {
        state.reading = false;
        if (state.decoder && !encoding) {
          chunk = state.decoder.write(chunk);
          if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
        } else {
          addChunk(stream, state, chunk, false);
        }
      }
    } else if (!addToFront) {
      state.reading = false;
    }
  }

  return needMoreData(state);
}

function addChunk(stream, state, chunk, addToFront) {
  if (state.flowing && state.length === 0 && !state.sync) {
    stream.emit('data', chunk);
    stream.read(0);
  } else {
    // update the buffer info.
    state.length += state.objectMode ? 1 : chunk.length;
    if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);

    if (state.needReadable) emitReadable(stream);
  }
  maybeReadMore(stream, state);
}

function chunkInvalid(state, chunk) {
  var er;
  if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
    er = new TypeError('Invalid non-string/buffer chunk');
  }
  return er;
}

// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes.  This is to work around cases where hwm=0,
// such as the repl.  Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
  return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
}

Readable.prototype.isPaused = function () {
  return this._readableState.flowing === false;
};

// backwards compatibility.
Readable.prototype.setEncoding = function (enc) {
  if (!StringDecoder) StringDecoder = __webpack_require__(/*! string_decoder/ */ "qiJe").StringDecoder;
  this._readableState.decoder = new StringDecoder(enc);
  this._readableState.encoding = enc;
  return this;
};

// Don't raise the hwm > 8MB
var MAX_HWM = 0x800000;
function computeNewHighWaterMark(n) {
  if (n >= MAX_HWM) {
    n = MAX_HWM;
  } else {
    // Get the next highest power of 2 to prevent increasing hwm excessively in
    // tiny amounts
    n--;
    n |= n >>> 1;
    n |= n >>> 2;
    n |= n >>> 4;
    n |= n >>> 8;
    n |= n >>> 16;
    n++;
  }
  return n;
}

// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function howMuchToRead(n, state) {
  if (n <= 0 || state.length === 0 && state.ended) return 0;
  if (state.objectMode) return 1;
  if (n !== n) {
    // Only flow one buffer at a time
    if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  }
  // If we're asking for more than the current hwm, then raise the hwm.
  if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  if (n <= state.length) return n;
  // Don't have enough
  if (!state.ended) {
    state.needReadable = true;
    return 0;
  }
  return state.length;
}

// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function (n) {
  debug('read', n);
  n = parseInt(n, 10);
  var state = this._readableState;
  var nOrig = n;

  if (n !== 0) state.emittedReadable = false;

  // if we're doing read(0) to trigger a readable event, but we
  // already have a bunch of data in the buffer, then just trigger
  // the 'readable' event and move on.
  if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
    debug('read: emitReadable', state.length, state.ended);
    if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
    return null;
  }

  n = howMuchToRead(n, state);

  // if we've ended, and we're now clear, then finish it up.
  if (n === 0 && state.ended) {
    if (state.length === 0) endReadable(this);
    return null;
  }

  // All the actual chunk generation logic needs to be
  // *below* the call to _read.  The reason is that in certain
  // synthetic stream cases, such as passthrough streams, _read
  // may be a completely synchronous operation which may change
  // the state of the read buffer, providing enough data when
  // before there was *not* enough.
  //
  // So, the steps are:
  // 1. Figure out what the state of things will be after we do
  // a read from the buffer.
  //
  // 2. If that resulting state will trigger a _read, then call _read.
  // Note that this may be asynchronous, or synchronous.  Yes, it is
  // deeply ugly to write APIs this way, but that still doesn't mean
  // that the Readable class should behave improperly, as streams are
  // designed to be sync/async agnostic.
  // Take note if the _read call is sync or async (ie, if the read call
  // has returned yet), so that we know whether or not it's safe to emit
  // 'readable' etc.
  //
  // 3. Actually pull the requested chunks out of the buffer and return.

  // if we need a readable event, then we need to do some reading.
  var doRead = state.needReadable;
  debug('need readable', doRead);

  // if we currently have less than the highWaterMark, then also read some
  if (state.length === 0 || state.length - n < state.highWaterMark) {
    doRead = true;
    debug('length less than watermark', doRead);
  }

  // however, if we've ended, then there's no point, and if we're already
  // reading, then it's unnecessary.
  if (state.ended || state.reading) {
    doRead = false;
    debug('reading or ended', doRead);
  } else if (doRead) {
    debug('do read');
    state.reading = true;
    state.sync = true;
    // if the length is currently zero, then we *need* a readable event.
    if (state.length === 0) state.needReadable = true;
    // call internal read method
    this._read(state.highWaterMark);
    state.sync = false;
    // If _read pushed data synchronously, then `reading` will be false,
    // and we need to re-evaluate how much data we can return to the user.
    if (!state.reading) n = howMuchToRead(nOrig, state);
  }

  var ret;
  if (n > 0) ret = fromList(n, state);else ret = null;

  if (ret === null) {
    state.needReadable = true;
    n = 0;
  } else {
    state.length -= n;
  }

  if (state.length === 0) {
    // If we have nothing in the buffer, then we want to know
    // as soon as we *do* get something into the buffer.
    if (!state.ended) state.needReadable = true;

    // If we tried to read() past the EOF, then emit end on the next tick.
    if (nOrig !== n && state.ended) endReadable(this);
  }

  if (ret !== null) this.emit('data', ret);

  return ret;
};

function onEofChunk(stream, state) {
  if (state.ended) return;
  if (state.decoder) {
    var chunk = state.decoder.end();
    if (chunk && chunk.length) {
      state.buffer.push(chunk);
      state.length += state.objectMode ? 1 : chunk.length;
    }
  }
  state.ended = true;

  // emit 'readable' now to make sure it gets picked up.
  emitReadable(stream);
}

// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow.  This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
  var state = stream._readableState;
  state.needReadable = false;
  if (!state.emittedReadable) {
    debug('emitReadable', state.flowing);
    state.emittedReadable = true;
    if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
  }
}

function emitReadable_(stream) {
  debug('emit readable');
  stream.emit('readable');
  flow(stream);
}

// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data.  that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
  if (!state.readingMore) {
    state.readingMore = true;
    pna.nextTick(maybeReadMore_, stream, state);
  }
}

function maybeReadMore_(stream, state) {
  var len = state.length;
  while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
    debug('maybeReadMore read 0');
    stream.read(0);
    if (len === state.length)
      // didn't get any data, stop spinning.
      break;else len = state.length;
  }
  state.readingMore = false;
}

// abstract method.  to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function (n) {
  this.emit('error', new Error('_read() is not implemented'));
};

Readable.prototype.pipe = function (dest, pipeOpts) {
  var src = this;
  var state = this._readableState;

  switch (state.pipesCount) {
    case 0:
      state.pipes = dest;
      break;
    case 1:
      state.pipes = [state.pipes, dest];
      break;
    default:
      state.pipes.push(dest);
      break;
  }
  state.pipesCount += 1;
  debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);

  var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;

  var endFn = doEnd ? onend : unpipe;
  if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);

  dest.on('unpipe', onunpipe);
  function onunpipe(readable, unpipeInfo) {
    debug('onunpipe');
    if (readable === src) {
      if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
        unpipeInfo.hasUnpiped = true;
        cleanup();
      }
    }
  }

  function onend() {
    debug('onend');
    dest.end();
  }

  // when the dest drains, it reduces the awaitDrain counter
  // on the source.  This would be more elegant with a .once()
  // handler in flow(), but adding and removing repeatedly is
  // too slow.
  var ondrain = pipeOnDrain(src);
  dest.on('drain', ondrain);

  var cleanedUp = false;
  function cleanup() {
    debug('cleanup');
    // cleanup event handlers once the pipe is broken
    dest.removeListener('close', onclose);
    dest.removeListener('finish', onfinish);
    dest.removeListener('drain', ondrain);
    dest.removeListener('error', onerror);
    dest.removeListener('unpipe', onunpipe);
    src.removeListener('end', onend);
    src.removeListener('end', unpipe);
    src.removeListener('data', ondata);

    cleanedUp = true;

    // if the reader is waiting for a drain event from this
    // specific writer, then it would cause it to never start
    // flowing again.
    // So, if this is awaiting a drain, then we just call it now.
    // If we don't know, then assume that we are waiting for one.
    if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  }

  // If the user pushes more data while we're writing to dest then we'll end up
  // in ondata again. However, we only want to increase awaitDrain once because
  // dest will only emit one 'drain' event for the multiple writes.
  // => Introduce a guard on increasing awaitDrain.
  var increasedAwaitDrain = false;
  src.on('data', ondata);
  function ondata(chunk) {
    debug('ondata');
    increasedAwaitDrain = false;
    var ret = dest.write(chunk);
    if (false === ret && !increasedAwaitDrain) {
      // If the user unpiped during `dest.write()`, it is possible
      // to get stuck in a permanently paused state if that write
      // also returned false.
      // => Check whether `dest` is still a piping destination.
      if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
        debug('false write response, pause', src._readableState.awaitDrain);
        src._readableState.awaitDrain++;
        increasedAwaitDrain = true;
      }
      src.pause();
    }
  }

  // if the dest has an error, then stop piping into it.
  // however, don't suppress the throwing behavior for this.
  function onerror(er) {
    debug('onerror', er);
    unpipe();
    dest.removeListener('error', onerror);
    if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  }

  // Make sure our error handler is attached before userland ones.
  prependListener(dest, 'error', onerror);

  // Both close and finish should trigger unpipe, but only once.
  function onclose() {
    dest.removeListener('finish', onfinish);
    unpipe();
  }
  dest.once('close', onclose);
  function onfinish() {
    debug('onfinish');
    dest.removeListener('close', onclose);
    unpipe();
  }
  dest.once('finish', onfinish);

  function unpipe() {
    debug('unpipe');
    src.unpipe(dest);
  }

  // tell the dest that it's being piped to
  dest.emit('pipe', src);

  // start the flow if it hasn't been started already.
  if (!state.flowing) {
    debug('pipe resume');
    src.resume();
  }

  return dest;
};

function pipeOnDrain(src) {
  return function () {
    var state = src._readableState;
    debug('pipeOnDrain', state.awaitDrain);
    if (state.awaitDrain) state.awaitDrain--;
    if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
      state.flowing = true;
      flow(src);
    }
  };
}

Readable.prototype.unpipe = function (dest) {
  var state = this._readableState;
  var unpipeInfo = { hasUnpiped: false };

  // if we're not piping anywhere, then do nothing.
  if (state.pipesCount === 0) return this;

  // just one destination.  most common case.
  if (state.pipesCount === 1) {
    // passed in one, but it's not the right one.
    if (dest && dest !== state.pipes) return this;

    if (!dest) dest = state.pipes;

    // got a match.
    state.pipes = null;
    state.pipesCount = 0;
    state.flowing = false;
    if (dest) dest.emit('unpipe', this, unpipeInfo);
    return this;
  }

  // slow case. multiple pipe destinations.

  if (!dest) {
    // remove all.
    var dests = state.pipes;
    var len = state.pipesCount;
    state.pipes = null;
    state.pipesCount = 0;
    state.flowing = false;

    for (var i = 0; i < len; i++) {
      dests[i].emit('unpipe', this, unpipeInfo);
    }return this;
  }

  // try to find the right one.
  var index = indexOf(state.pipes, dest);
  if (index === -1) return this;

  state.pipes.splice(index, 1);
  state.pipesCount -= 1;
  if (state.pipesCount === 1) state.pipes = state.pipes[0];

  dest.emit('unpipe', this, unpipeInfo);

  return this;
};

// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function (ev, fn) {
  var res = Stream.prototype.on.call(this, ev, fn);

  if (ev === 'data') {
    // Start flowing on next tick if stream isn't explicitly paused
    if (this._readableState.flowing !== false) this.resume();
  } else if (ev === 'readable') {
    var state = this._readableState;
    if (!state.endEmitted && !state.readableListening) {
      state.readableListening = state.needReadable = true;
      state.emittedReadable = false;
      if (!state.reading) {
        pna.nextTick(nReadingNextTick, this);
      } else if (state.length) {
        emitReadable(this);
      }
    }
  }

  return res;
};
Readable.prototype.addListener = Readable.prototype.on;

function nReadingNextTick(self) {
  debug('readable nexttick read 0');
  self.read(0);
}

// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function () {
  var state = this._readableState;
  if (!state.flowing) {
    debug('resume');
    state.flowing = true;
    resume(this, state);
  }
  return this;
};

function resume(stream, state) {
  if (!state.resumeScheduled) {
    state.resumeScheduled = true;
    pna.nextTick(resume_, stream, state);
  }
}

function resume_(stream, state) {
  if (!state.reading) {
    debug('resume read 0');
    stream.read(0);
  }

  state.resumeScheduled = false;
  state.awaitDrain = 0;
  stream.emit('resume');
  flow(stream);
  if (state.flowing && !state.reading) stream.read(0);
}

Readable.prototype.pause = function () {
  debug('call pause flowing=%j', this._readableState.flowing);
  if (false !== this._readableState.flowing) {
    debug('pause');
    this._readableState.flowing = false;
    this.emit('pause');
  }
  return this;
};

function flow(stream) {
  var state = stream._readableState;
  debug('flow', state.flowing);
  while (state.flowing && stream.read() !== null) {}
}

// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function (stream) {
  var _this = this;

  var state = this._readableState;
  var paused = false;

  stream.on('end', function () {
    debug('wrapped end');
    if (state.decoder && !state.ended) {
      var chunk = state.decoder.end();
      if (chunk && chunk.length) _this.push(chunk);
    }

    _this.push(null);
  });

  stream.on('data', function (chunk) {
    debug('wrapped data');
    if (state.decoder) chunk = state.decoder.write(chunk);

    // don't skip over falsy values in objectMode
    if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;

    var ret = _this.push(chunk);
    if (!ret) {
      paused = true;
      stream.pause();
    }
  });

  // proxy all the other methods.
  // important when wrapping filters and duplexes.
  for (var i in stream) {
    if (this[i] === undefined && typeof stream[i] === 'function') {
      this[i] = function (method) {
        return function () {
          return stream[method].apply(stream, arguments);
        };
      }(i);
    }
  }

  // proxy certain important events.
  for (var n = 0; n < kProxyEvents.length; n++) {
    stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  }

  // when we try to consume some more bytes, simply unpause the
  // underlying stream.
  this._read = function (n) {
    debug('wrapped _read', n);
    if (paused) {
      paused = false;
      stream.resume();
    }
  };

  return this;
};

Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function () {
    return this._readableState.highWaterMark;
  }
});

// exposed for testing purposes only.
Readable._fromList = fromList;

// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromList(n, state) {
  // nothing buffered
  if (state.length === 0) return null;

  var ret;
  if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
    // read it all, truncate the list
    if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
    state.buffer.clear();
  } else {
    // read part of list
    ret = fromListPartial(n, state.buffer, state.decoder);
  }

  return ret;
}

// Extracts only enough buffered data to satisfy the amount requested.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromListPartial(n, list, hasStrings) {
  var ret;
  if (n < list.head.data.length) {
    // slice is the same for buffers and strings
    ret = list.head.data.slice(0, n);
    list.head.data = list.head.data.slice(n);
  } else if (n === list.head.data.length) {
    // first chunk is a perfect match
    ret = list.shift();
  } else {
    // result spans more than one buffer
    ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  }
  return ret;
}

// Copies a specified amount of characters from the list of buffered data
// chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBufferString(n, list) {
  var p = list.head;
  var c = 1;
  var ret = p.data;
  n -= ret.length;
  while (p = p.next) {
    var str = p.data;
    var nb = n > str.length ? str.length : n;
    if (nb === str.length) ret += str;else ret += str.slice(0, n);
    n -= nb;
    if (n === 0) {
      if (nb === str.length) {
        ++c;
        if (p.next) list.head = p.next;else list.head = list.tail = null;
      } else {
        list.head = p;
        p.data = str.slice(nb);
      }
      break;
    }
    ++c;
  }
  list.length -= c;
  return ret;
}

// Copies a specified amount of bytes from the list of buffered data chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBuffer(n, list) {
  var ret = Buffer.allocUnsafe(n);
  var p = list.head;
  var c = 1;
  p.data.copy(ret);
  n -= p.data.length;
  while (p = p.next) {
    var buf = p.data;
    var nb = n > buf.length ? buf.length : n;
    buf.copy(ret, ret.length - n, 0, nb);
    n -= nb;
    if (n === 0) {
      if (nb === buf.length) {
        ++c;
        if (p.next) list.head = p.next;else list.head = list.tail = null;
      } else {
        list.head = p;
        p.data = buf.slice(nb);
      }
      break;
    }
    ++c;
  }
  list.length -= c;
  return ret;
}

function endReadable(stream) {
  var state = stream._readableState;

  // If we get here before consuming all the bytes, then that is a
  // bug in node.  Should never happen.
  if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');

  if (!state.endEmitted) {
    state.ended = true;
    pna.nextTick(endReadableNT, state, stream);
  }
}

function endReadableNT(state, stream) {
  // Check that we didn't get one last unshift.
  if (!state.endEmitted && state.length === 0) {
    state.endEmitted = true;
    stream.readable = false;
    stream.emit('end');
  }
}

function indexOf(xs, x) {
  for (var i = 0, l = xs.length; i < l; i++) {
    if (xs[i] === x) return i;
  }
  return -1;
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "yLpj"), __webpack_require__(/*! ./../../process/browser.js */ "8oxB")))

/***/ }),

/***/ "rZxl":
/*!**************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/Button.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Button = function (_Component) {
  _inherits(Button, _Component);

  function Button(props) {
    _classCallCheck(this, Button);

    return _possibleConstructorReturn(this, (Button.__proto__ || Object.getPrototypeOf(Button)).call(this, props));
  }

  _createClass(Button, [{
    key: 'render',
    value: function render() {
      var _props = this.props,
          children = _props.children,
          className = _props.className,
          icon = _props.icon,
          label = _props.label,
          variant = _props.variant,
          rest = _objectWithoutProperties(_props, ['children', 'className', 'icon', 'label', 'variant']);

      var classes = 'button';

      if (variant) {
        classes += ' button--' + variant;
      } else {
        classes += ' button--default';
      }

      if (className) {
        classes += ' ' + className;
      }

      var Icon = icon ? _react2.default.createElement(
        'div',
        { className: (0, _lib.bem)('button', 'icon') },
        icon
      ) : null;

      return _react2.default.createElement(
        'button',
        _extends({ className: classes }, rest),
        _react2.default.createElement(
          'div',
          { className: (0, _lib.bem)('button', 'wrapper') },
          Icon,
          _react2.default.createElement(
            'div',
            { className: 'button__label' },
            label ? label : children
          )
        )
      );
    }
  }]);

  return Button;
}(_react.Component);

Button.propTypes = {
  children: _propTypes2.default.node,
  className: _propTypes2.default.any,
  icon: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]),
  label: _propTypes2.default.any,
  variant: _propTypes2.default.string
};

exports.default = Button;
//# sourceMappingURL=Button.js.map

/***/ }),

/***/ "raLr":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/uk.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


function plural(word, num) {
    var forms = word.split('_');
    return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]);
}
function relativeTimeWithPlural(number, withoutSuffix, key) {
    var format = {
        'ss': withoutSuffix ? 'секунда_секунди_секунд' : 'секунду_секунди_секунд',
        'mm': withoutSuffix ? 'хвилина_хвилини_хвилин' : 'хвилину_хвилини_хвилин',
        'hh': withoutSuffix ? 'година_години_годин' : 'годину_години_годин',
        'dd': 'день_дні_днів',
        'MM': 'місяць_місяці_місяців',
        'yy': 'рік_роки_років'
    };
    if (key === 'm') {
        return withoutSuffix ? 'хвилина' : 'хвилину';
    }
    else if (key === 'h') {
        return withoutSuffix ? 'година' : 'годину';
    }
    else {
        return number + ' ' + plural(format[key], +number);
    }
}
function weekdaysCaseReplace(m, format) {
    var weekdays = {
        'nominative': 'неділя_понеділок_вівторок_середа_четвер_п’ятниця_субота'.split('_'),
        'accusative': 'неділю_понеділок_вівторок_середу_четвер_п’ятницю_суботу'.split('_'),
        'genitive': 'неділі_понеділка_вівторка_середи_четверга_п’ятниці_суботи'.split('_')
    };

    if (!m) {
        return weekdays['nominative'];
    }

    var nounCase = (/(\[[ВвУу]\]) ?dddd/).test(format) ?
        'accusative' :
        ((/\[?(?:минулої|наступної)? ?\] ?dddd/).test(format) ?
            'genitive' :
            'nominative');
    return weekdays[nounCase][m.day()];
}
function processHoursFunction(str) {
    return function () {
        return str + 'о' + (this.hours() === 11 ? 'б' : '') + '] LT';
    };
}

var uk = moment.defineLocale('uk', {
    months : {
        'format': 'січня_лютого_березня_квітня_травня_червня_липня_серпня_вересня_жовтня_листопада_грудня'.split('_'),
        'standalone': 'січень_лютий_березень_квітень_травень_червень_липень_серпень_вересень_жовтень_листопад_грудень'.split('_')
    },
    monthsShort : 'січ_лют_бер_квіт_трав_черв_лип_серп_вер_жовт_лист_груд'.split('_'),
    weekdays : weekdaysCaseReplace,
    weekdaysShort : 'нд_пн_вт_ср_чт_пт_сб'.split('_'),
    weekdaysMin : 'нд_пн_вт_ср_чт_пт_сб'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D MMMM YYYY р.',
        LLL : 'D MMMM YYYY р., HH:mm',
        LLLL : 'dddd, D MMMM YYYY р., HH:mm'
    },
    calendar : {
        sameDay: processHoursFunction('[Сьогодні '),
        nextDay: processHoursFunction('[Завтра '),
        lastDay: processHoursFunction('[Вчора '),
        nextWeek: processHoursFunction('[У] dddd ['),
        lastWeek: function () {
            switch (this.day()) {
                case 0:
                case 3:
                case 5:
                case 6:
                    return processHoursFunction('[Минулої] dddd [').call(this);
                case 1:
                case 2:
                case 4:
                    return processHoursFunction('[Минулого] dddd [').call(this);
            }
        },
        sameElse: 'L'
    },
    relativeTime : {
        future : 'за %s',
        past : '%s тому',
        s : 'декілька секунд',
        ss : relativeTimeWithPlural,
        m : relativeTimeWithPlural,
        mm : relativeTimeWithPlural,
        h : 'годину',
        hh : relativeTimeWithPlural,
        d : 'день',
        dd : relativeTimeWithPlural,
        M : 'місяць',
        MM : relativeTimeWithPlural,
        y : 'рік',
        yy : relativeTimeWithPlural
    },
    // M. E.: those two are virtually unused but a user might want to implement them for his/her website for some reason
    meridiemParse: /ночі|ранку|дня|вечора/,
    isPM: function (input) {
        return /^(дня|вечора)$/.test(input);
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 4) {
            return 'ночі';
        } else if (hour < 12) {
            return 'ранку';
        } else if (hour < 17) {
            return 'дня';
        } else {
            return 'вечора';
        }
    },
    dayOfMonthOrdinalParse: /\d{1,2}-(й|го)/,
    ordinal: function (number, period) {
        switch (period) {
            case 'M':
            case 'd':
            case 'DDD':
            case 'w':
            case 'W':
                return number + '-й';
            case 'D':
                return number + '-го';
            default:
                return number;
        }
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return uk;

})));


/***/ }),

/***/ "rbRy":
/*!************************************************************!*\
  !*** ./node_modules/draft-js-import-html/lib/parseHTML.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = parseHTML;
function parseHTML(html) {
  var doc = void 0;
  if (typeof DOMParser !== 'undefined') {
    var parser = new DOMParser();
    doc = parser.parseFromString(html, 'text/html');
  } else {
    doc = document.implementation.createHTMLDocument('');
    if (doc.documentElement) {
      doc.documentElement.innerHTML = html;
    }
  }
  // This makes Flow happy
  return doc.body || doc.createElement('body');
}

/***/ }),

/***/ "rhNM":
/*!***************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/loggers.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



/* eslint-disable no-console */

var dfltConfig = __webpack_require__(/*! ../plot_api/plot_config */ "P/XJ").dfltConfig;

var loggers = module.exports = {};

/**
 * ------------------------------------------
 * debugging tools
 * ------------------------------------------
 */

loggers.log = function() {
    if(dfltConfig.logging > 1) {
        var messages = ['LOG:'];

        for(var i = 0; i < arguments.length; i++) {
            messages.push(arguments[i]);
        }

        apply(console.trace || console.log, messages);
    }
};

loggers.warn = function() {
    if(dfltConfig.logging > 0) {
        var messages = ['WARN:'];

        for(var i = 0; i < arguments.length; i++) {
            messages.push(arguments[i]);
        }

        apply(console.trace || console.log, messages);
    }
};

loggers.error = function() {
    if(dfltConfig.logging > 0) {
        var messages = ['ERROR:'];

        for(var i = 0; i < arguments.length; i++) {
            messages.push(arguments[i]);
        }

        apply(console.error, messages);
    }
};

/*
 * Robust apply, for IE9 where console.log doesn't support
 * apply like other functions do
 */
function apply(f, args) {
    if(f && f.apply) {
        try {
            // `this` should always be console, since here we're always
            // applying a method of the console object.
            f.apply(console, args);
            return;
        }
        catch(e) { /* in case apply failed, fall back on the code below */ }
    }

    // no apply - just try calling the function on each arg independently
    for(var i = 0; i < args.length; i++) {
        try {
            f(args[i]);
        }
        catch(e) {
            // still fails - last resort simple console.log
            console.log(args[i]);
        }
    }
}


/***/ }),

/***/ "rhW2":
/*!**********************************************!*\
  !*** ./node_modules/mdi-react/MenuUpIcon.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var MenuUpIcon = function MenuUpIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M7,15L12,10L17,15H7Z' })
  );
};

module.exports = MenuUpIcon;


/***/ }),

/***/ "rlhY":
/*!********************************************!*\
  !*** ./node_modules/xterm/lib/Charsets.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.CHARSETS = {};
exports.DEFAULT_CHARSET = exports.CHARSETS['B'];
exports.CHARSETS['0'] = {
    '`': '\u25c6',
    'a': '\u2592',
    'b': '\u0009',
    'c': '\u000c',
    'd': '\u000d',
    'e': '\u000a',
    'f': '\u00b0',
    'g': '\u00b1',
    'h': '\u2424',
    'i': '\u000b',
    'j': '\u2518',
    'k': '\u2510',
    'l': '\u250c',
    'm': '\u2514',
    'n': '\u253c',
    'o': '\u23ba',
    'p': '\u23bb',
    'q': '\u2500',
    'r': '\u23bc',
    's': '\u23bd',
    't': '\u251c',
    'u': '\u2524',
    'v': '\u2534',
    'w': '\u252c',
    'x': '\u2502',
    'y': '\u2264',
    'z': '\u2265',
    '{': '\u03c0',
    '|': '\u2260',
    '}': '\u00a3',
    '~': '\u00b7'
};
exports.CHARSETS['A'] = {
    '#': '£'
};
exports.CHARSETS['B'] = null;
exports.CHARSETS['4'] = {
    '#': '£',
    '@': '¾',
    '[': 'ij',
    '\\': '½',
    ']': '|',
    '{': '¨',
    '|': 'f',
    '}': '¼',
    '~': '´'
};
exports.CHARSETS['C'] =
    exports.CHARSETS['5'] = {
        '[': 'Ä',
        '\\': 'Ö',
        ']': 'Å',
        '^': 'Ü',
        '`': 'é',
        '{': 'ä',
        '|': 'ö',
        '}': 'å',
        '~': 'ü'
    };
exports.CHARSETS['R'] = {
    '#': '£',
    '@': 'à',
    '[': '°',
    '\\': 'ç',
    ']': '§',
    '{': 'é',
    '|': 'ù',
    '}': 'è',
    '~': '¨'
};
exports.CHARSETS['Q'] = {
    '@': 'à',
    '[': 'â',
    '\\': 'ç',
    ']': 'ê',
    '^': 'î',
    '`': 'ô',
    '{': 'é',
    '|': 'ù',
    '}': 'è',
    '~': 'û'
};
exports.CHARSETS['K'] = {
    '@': '§',
    '[': 'Ä',
    '\\': 'Ö',
    ']': 'Ü',
    '{': 'ä',
    '|': 'ö',
    '}': 'ü',
    '~': 'ß'
};
exports.CHARSETS['Y'] = {
    '#': '£',
    '@': '§',
    '[': '°',
    '\\': 'ç',
    ']': 'é',
    '`': 'ù',
    '{': 'à',
    '|': 'ò',
    '}': 'è',
    '~': 'ì'
};
exports.CHARSETS['E'] =
    exports.CHARSETS['6'] = {
        '@': 'Ä',
        '[': 'Æ',
        '\\': 'Ø',
        ']': 'Å',
        '^': 'Ü',
        '`': 'ä',
        '{': 'æ',
        '|': 'ø',
        '}': 'å',
        '~': 'ü'
    };
exports.CHARSETS['Z'] = {
    '#': '£',
    '@': '§',
    '[': '¡',
    '\\': 'Ñ',
    ']': '¿',
    '{': '°',
    '|': 'ñ',
    '}': 'ç'
};
exports.CHARSETS['H'] =
    exports.CHARSETS['7'] = {
        '@': 'É',
        '[': 'Ä',
        '\\': 'Ö',
        ']': 'Å',
        '^': 'Ü',
        '`': 'é',
        '{': 'ä',
        '|': 'ö',
        '}': 'å',
        '~': 'ü'
    };
exports.CHARSETS['='] = {
    '#': 'ù',
    '@': 'à',
    '[': 'é',
    '\\': 'ç',
    ']': 'ê',
    '^': 'î',
    '_': 'è',
    '`': 'ô',
    '{': 'ä',
    '|': 'ö',
    '}': 'ü',
    '~': 'û'
};

//# sourceMappingURL=Charsets.js.map


/***/ }),

/***/ "roQf":
/*!**********************************************!*\
  !*** ./node_modules/evp_bytestokey/index.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer
var MD5 = __webpack_require__(/*! md5.js */ "9XZ3")

/* eslint-disable camelcase */
function EVP_BytesToKey (password, salt, keyBits, ivLen) {
  if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary')
  if (salt) {
    if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary')
    if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length')
  }

  var keyLen = keyBits / 8
  var key = Buffer.alloc(keyLen)
  var iv = Buffer.alloc(ivLen || 0)
  var tmp = Buffer.alloc(0)

  while (keyLen > 0 || ivLen > 0) {
    var hash = new MD5()
    hash.update(tmp)
    hash.update(password)
    if (salt) hash.update(salt)
    tmp = hash.digest()

    var used = 0

    if (keyLen > 0) {
      var keyStart = key.length - keyLen
      used = Math.min(keyLen, tmp.length)
      tmp.copy(key, keyStart, 0, used)
      keyLen -= used
    }

    if (used < tmp.length && ivLen > 0) {
      var ivStart = iv.length - ivLen
      var length = Math.min(ivLen, tmp.length - used)
      tmp.copy(iv, ivStart, used, used + length)
      ivLen -= length
    }
  }

  tmp.fill(0)
  return { key: key, iv: iv }
}

module.exports = EVP_BytesToKey


/***/ }),

/***/ "rqNV":
/*!*******************************************************!*\
  !*** ./node_modules/@phosphor/algorithm/lib/index.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
__export(__webpack_require__(/*! ./array */ "PB3p"));
__export(__webpack_require__(/*! ./chain */ "FvI0"));
__export(__webpack_require__(/*! ./empty */ "Bm3m"));
__export(__webpack_require__(/*! ./filter */ "Cdfm"));
__export(__webpack_require__(/*! ./find */ "JKFw"));
__export(__webpack_require__(/*! ./iter */ "DMSk"));
__export(__webpack_require__(/*! ./map */ "jQqP"));
__export(__webpack_require__(/*! ./range */ "Gxzi"));
__export(__webpack_require__(/*! ./reduce */ "ExqO"));
__export(__webpack_require__(/*! ./repeat */ "CVh7"));
__export(__webpack_require__(/*! ./retro */ "flHX"));
__export(__webpack_require__(/*! ./sort */ "n/zs"));
__export(__webpack_require__(/*! ./stride */ "pMuX"));
__export(__webpack_require__(/*! ./string */ "Gbhj"));
__export(__webpack_require__(/*! ./take */ "kBvz"));
__export(__webpack_require__(/*! ./zip */ "ql0L"));


/***/ }),

/***/ "rr1i":
/*!****************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_property-desc.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

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


/***/ }),

/***/ "rsfS":
/*!*******************************************************************!*\
  !*** ./node_modules/@jupyterlab/inspector/lib/kernelconnector.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
/**
 * The default connector for making inspection requests from the Jupyter API.
 */
class KernelConnector extends coreutils_1.DataConnector {
    /**
     * Create a new kernel connector for inspection requests.
     *
     * @param options - The instatiation options for the kernel connector.
     */
    constructor(options) {
        super();
        this._session = options.session;
    }
    /**
     * Fetch inspection requests.
     *
     * @param request - The inspection request text and details.
     */
    fetch(request) {
        const kernel = this._session.kernel;
        if (!kernel) {
            return Promise.reject(new Error('Inspection fetch requires a kernel.'));
        }
        const contents = {
            code: request.text,
            cursor_pos: request.offset,
            detail_level: 0
        };
        return kernel.requestInspect(contents).then(msg => {
            const response = msg.content;
            if (response.status !== 'ok' || !response.found) {
                throw new Error('Inspection fetch failed to return successfully.');
            }
            return { data: response.data, metadata: response.metadata };
        });
    }
}
exports.KernelConnector = KernelConnector;


/***/ }),

/***/ "rvvU":
/*!*********************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/dockpanel.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
var coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
var domutils_1 = __webpack_require__(/*! @phosphor/domutils */ "XWTc");
var dragdrop_1 = __webpack_require__(/*! @phosphor/dragdrop */ "v7cI");
var messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
var properties_1 = __webpack_require__(/*! @phosphor/properties */ "3kwb");
var signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
var docklayout_1 = __webpack_require__(/*! ./docklayout */ "Y29x");
var tabbar_1 = __webpack_require__(/*! ./tabbar */ "g07C");
var widget_1 = __webpack_require__(/*! ./widget */ "FmDU");
/**
 * A widget which provides a flexible docking area for widgets.
 */
var DockPanel = (function (_super) {
    __extends(DockPanel, _super);
    /**
     * Construct a new dock panel.
     *
     * @param options - The options for initializing the panel.
     */
    function DockPanel(options) {
        if (options === void 0) { options = {}; }
        var _this = _super.call(this) || this;
        _this._drag = null;
        _this._pressData = null;
        _this._layoutModified = new signaling_1.Signal(_this);
        _this.addClass('p-DockPanel');
        _this._mode = options.mode || 'multiple-document';
        _this._renderer = options.renderer || DockPanel.defaultRenderer;
        // Toggle the CSS mode attribute.
        _this.dataset['mode'] = _this._mode;
        // Create the delegate renderer for the layout.
        var renderer = {
            createTabBar: function () { return _this._createTabBar(); },
            createHandle: function () { return _this._createHandle(); }
        };
        // Set up the dock layout for the panel.
        _this.layout = new docklayout_1.DockLayout({ renderer: renderer, spacing: options.spacing });
        // Set up the overlay drop indicator.
        _this.overlay = options.overlay || new DockPanel.Overlay();
        _this.node.appendChild(_this.overlay.node);
        return _this;
    }
    /**
     * Dispose of the resources held by the panel.
     */
    DockPanel.prototype.dispose = function () {
        // Ensure the mouse is released.
        this._releaseMouse();
        // Hide the overlay.
        this.overlay.hide(0);
        // Cancel a drag if one is in progress.
        if (this._drag) {
            this._drag.dispose();
        }
        // Dispose of the base class.
        _super.prototype.dispose.call(this);
    };
    Object.defineProperty(DockPanel.prototype, "layoutModified", {
        /**
         * A signal emitted when the layout configuration is modified.
         *
         * #### Notes
         * This signal is emitted whenever the current layout configuration
         * may have changed.
         *
         * This signal is emitted asynchronously in a collapsed fashion, so
         * that multiple synchronous modifications results in only a single
         * emit of the signal.
         */
        get: function () {
            return this._layoutModified;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DockPanel.prototype, "renderer", {
        /**
         * The renderer used by the dock panel.
         */
        get: function () {
            return this.layout.renderer;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DockPanel.prototype, "spacing", {
        /**
         * Get the spacing between the widgets.
         */
        get: function () {
            return this.layout.spacing;
        },
        /**
         * Set the spacing between the widgets.
         */
        set: function (value) {
            this.layout.spacing = value;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DockPanel.prototype, "mode", {
        /**
         * Get the mode for the dock panel.
         */
        get: function () {
            return this._mode;
        },
        /**
         * Set the mode for the dock panel.
         *
         * #### Notes
         * Changing the mode is a destructive operation with respect to the
         * panel's layout configuration. If layout state must be preserved,
         * save the current layout config before changing the mode.
         */
        set: function (value) {
            // Bail early if the mode does not change.
            if (this._mode === value) {
                return;
            }
            // Update the internal mode.
            this._mode = value;
            // Toggle the CSS mode attribute.
            this.dataset['mode'] = value;
            // Get the layout for the panel.
            var layout = this.layout;
            // Configure the layout for the specified mode.
            switch (value) {
                case 'multiple-document':
                    algorithm_1.each(layout.tabBars(), function (tabBar) { tabBar.show(); });
                    break;
                case 'single-document':
                    layout.restoreLayout(Private.createSingleDocumentConfig(this));
                    break;
                default:
                    throw 'unreachable';
            }
            // Schedule an emit of the layout modified signal.
            messaging_1.MessageLoop.postMessage(this, Private.LayoutModified);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DockPanel.prototype, "isEmpty", {
        /**
         * Whether the dock panel is empty.
         */
        get: function () {
            return this.layout.isEmpty;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Create an iterator over the user widgets in the panel.
     *
     * @returns A new iterator over the user widgets in the panel.
     *
     * #### Notes
     * This iterator does not include the generated tab bars.
     */
    DockPanel.prototype.widgets = function () {
        return this.layout.widgets();
    };
    /**
     * Create an iterator over the selected widgets in the panel.
     *
     * @returns A new iterator over the selected user widgets.
     *
     * #### Notes
     * This iterator yields the widgets corresponding to the current tab
     * of each tab bar in the panel.
     */
    DockPanel.prototype.selectedWidgets = function () {
        return this.layout.selectedWidgets();
    };
    /**
     * Create an iterator over the tab bars in the panel.
     *
     * @returns A new iterator over the tab bars in the panel.
     *
     * #### Notes
     * This iterator does not include the user widgets.
     */
    DockPanel.prototype.tabBars = function () {
        return this.layout.tabBars();
    };
    /**
     * Create an iterator over the handles in the panel.
     *
     * @returns A new iterator over the handles in the panel.
     */
    DockPanel.prototype.handles = function () {
        return this.layout.handles();
    };
    /**
     * Select a specific widget in the dock panel.
     *
     * @param widget - The widget of interest.
     *
     * #### Notes
     * This will make the widget the current widget in its tab area.
     */
    DockPanel.prototype.selectWidget = function (widget) {
        // Find the tab bar which contains the widget.
        var tabBar = algorithm_1.find(this.tabBars(), function (bar) {
            return bar.titles.indexOf(widget.title) !== -1;
        });
        // Throw an error if no tab bar is found.
        if (!tabBar) {
            throw new Error('Widget is not contained in the dock panel.');
        }
        // Ensure the widget is the current widget.
        tabBar.currentTitle = widget.title;
    };
    /**
     * Activate a specified widget in the dock panel.
     *
     * @param widget - The widget of interest.
     *
     * #### Notes
     * This will select and activate the given widget.
     */
    DockPanel.prototype.activateWidget = function (widget) {
        this.selectWidget(widget);
        widget.activate();
    };
    /**
     * Save the current layout configuration of the dock panel.
     *
     * @returns A new config object for the current layout state.
     *
     * #### Notes
     * The return value can be provided to the `restoreLayout` method
     * in order to restore the layout to its current configuration.
     */
    DockPanel.prototype.saveLayout = function () {
        return this.layout.saveLayout();
    };
    /**
     * Restore the layout to a previously saved configuration.
     *
     * @param config - The layout configuration to restore.
     *
     * #### Notes
     * Widgets which currently belong to the layout but which are not
     * contained in the config will be unparented.
     *
     * The dock panel automatically reverts to `'multiple-document'`
     * mode when a layout config is restored.
     */
    DockPanel.prototype.restoreLayout = function (config) {
        // Reset the mode.
        this._mode = 'multiple-document';
        // Restore the layout.
        this.layout.restoreLayout(config);
        // Flush the message loop on IE and Edge to prevent flicker.
        if (domutils_1.Platform.IS_EDGE || domutils_1.Platform.IS_IE) {
            messaging_1.MessageLoop.flush();
        }
        // Schedule an emit of the layout modified signal.
        messaging_1.MessageLoop.postMessage(this, Private.LayoutModified);
    };
    /**
     * Add a widget to the dock panel.
     *
     * @param widget - The widget to add to the dock panel.
     *
     * @param options - The additional options for adding the widget.
     *
     * #### Notes
     * If the panel is in single document mode, the options are ignored
     * and the widget is always added as tab in the hidden tab bar.
     */
    DockPanel.prototype.addWidget = function (widget, options) {
        if (options === void 0) { options = {}; }
        // Add the widget to the layout.
        if (this._mode === 'single-document') {
            this.layout.addWidget(widget);
        }
        else {
            this.layout.addWidget(widget, options);
        }
        // Schedule an emit of the layout modified signal.
        messaging_1.MessageLoop.postMessage(this, Private.LayoutModified);
    };
    /**
     * Process a message sent to the widget.
     *
     * @param msg - The message sent to the widget.
     */
    DockPanel.prototype.processMessage = function (msg) {
        if (msg.type === 'layout-modified') {
            this._layoutModified.emit(undefined);
        }
        else {
            _super.prototype.processMessage.call(this, msg);
        }
    };
    /**
     * Handle the DOM events for the dock panel.
     *
     * @param event - The DOM event sent to the panel.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the panel's DOM node. It should
     * not be called directly by user code.
     */
    DockPanel.prototype.handleEvent = function (event) {
        switch (event.type) {
            case 'p-dragenter':
                this._evtDragEnter(event);
                break;
            case 'p-dragleave':
                this._evtDragLeave(event);
                break;
            case 'p-dragover':
                this._evtDragOver(event);
                break;
            case 'p-drop':
                this._evtDrop(event);
                break;
            case 'mousedown':
                this._evtMouseDown(event);
                break;
            case 'mousemove':
                this._evtMouseMove(event);
                break;
            case 'mouseup':
                this._evtMouseUp(event);
                break;
            case 'keydown':
                this._evtKeyDown(event);
                break;
            case 'contextmenu':
                event.preventDefault();
                event.stopPropagation();
                break;
        }
    };
    /**
     * A message handler invoked on a `'before-attach'` message.
     */
    DockPanel.prototype.onBeforeAttach = function (msg) {
        this.node.addEventListener('p-dragenter', this);
        this.node.addEventListener('p-dragleave', this);
        this.node.addEventListener('p-dragover', this);
        this.node.addEventListener('p-drop', this);
        this.node.addEventListener('mousedown', this);
    };
    /**
     * A message handler invoked on an `'after-detach'` message.
     */
    DockPanel.prototype.onAfterDetach = function (msg) {
        this.node.removeEventListener('p-dragenter', this);
        this.node.removeEventListener('p-dragleave', this);
        this.node.removeEventListener('p-dragover', this);
        this.node.removeEventListener('p-drop', this);
        this.node.removeEventListener('mousedown', this);
        this._releaseMouse();
    };
    /**
     * A message handler invoked on a `'child-added'` message.
     */
    DockPanel.prototype.onChildAdded = function (msg) {
        // Ignore the generated tab bars.
        if (Private.isGeneratedTabBarProperty.get(msg.child)) {
            return;
        }
        // Add the widget class to the child.
        msg.child.addClass('p-DockPanel-widget');
    };
    /**
     * A message handler invoked on a `'child-removed'` message.
     */
    DockPanel.prototype.onChildRemoved = function (msg) {
        // Ignore the generated tab bars.
        if (Private.isGeneratedTabBarProperty.get(msg.child)) {
            return;
        }
        // Remove the widget class from the child.
        msg.child.removeClass('p-DockPanel-widget');
        // Schedule an emit of the layout modified signal.
        messaging_1.MessageLoop.postMessage(this, Private.LayoutModified);
    };
    /**
     * Handle the `'p-dragenter'` event for the dock panel.
     */
    DockPanel.prototype._evtDragEnter = function (event) {
        // If the factory mime type is present, mark the event as
        // handled in order to get the rest of the drag events.
        if (event.mimeData.hasData('application/vnd.phosphor.widget-factory')) {
            event.preventDefault();
            event.stopPropagation();
        }
    };
    /**
     * Handle the `'p-dragleave'` event for the dock panel.
     */
    DockPanel.prototype._evtDragLeave = function (event) {
        // Mark the event as handled.
        event.preventDefault();
        event.stopPropagation();
        // Get the node into which the drag is entering.
        var related = event.relatedTarget;
        // Hide the overlay if the drag is leaving the dock panel.
        if (!related || !this.node.contains(related)) {
            this.overlay.hide(0);
        }
    };
    /**
     * Handle the `'p-dragover'` event for the dock panel.
     */
    DockPanel.prototype._evtDragOver = function (event) {
        // Mark the event as handled.
        event.preventDefault();
        event.stopPropagation();
        // Show the drop indicator overlay and update the drop
        // action based on the drop target zone under the mouse.
        if (this._showOverlay(event.clientX, event.clientY) === 'invalid') {
            event.dropAction = 'none';
        }
        else {
            event.dropAction = event.proposedAction;
        }
    };
    /**
     * Handle the `'p-drop'` event for the dock panel.
     */
    DockPanel.prototype._evtDrop = function (event) {
        // Mark the event as handled.
        event.preventDefault();
        event.stopPropagation();
        // Hide the drop indicator overlay.
        this.overlay.hide(0);
        // Bail if the proposed action is to do nothing.
        if (event.proposedAction === 'none') {
            event.dropAction = 'none';
            return;
        }
        // Find the drop target under the mouse.
        var clientX = event.clientX, clientY = event.clientY;
        var _a = Private.findDropTarget(this, clientX, clientY), zone = _a.zone, target = _a.target;
        // Bail if the drop zone is invalid.
        if (zone === 'invalid') {
            event.dropAction = 'none';
            return;
        }
        // Bail if the factory mime type has invalid data.
        var mimeData = event.mimeData;
        var factory = mimeData.getData('application/vnd.phosphor.widget-factory');
        if (typeof factory !== 'function') {
            event.dropAction = 'none';
            return;
        }
        // Bail if the factory does not produce a widget.
        var widget = factory();
        if (!(widget instanceof widget_1.Widget)) {
            event.dropAction = 'none';
            return;
        }
        // Bail if the widget is an ancestor of the dock panel.
        if (widget.contains(this)) {
            event.dropAction = 'none';
            return;
        }
        // Find the reference widget for the drop target.
        var ref = target ? Private.getDropRef(target.tabBar) : null;
        // Add the widget according to the indicated drop zone.
        switch (zone) {
            case 'root-all':
                this.addWidget(widget);
                break;
            case 'root-top':
                this.addWidget(widget, { mode: 'split-top' });
                break;
            case 'root-left':
                this.addWidget(widget, { mode: 'split-left' });
                break;
            case 'root-right':
                this.addWidget(widget, { mode: 'split-right' });
                break;
            case 'root-bottom':
                this.addWidget(widget, { mode: 'split-bottom' });
                break;
            case 'widget-all':
                this.addWidget(widget, { mode: 'tab-after', ref: ref });
                break;
            case 'widget-top':
                this.addWidget(widget, { mode: 'split-top', ref: ref });
                break;
            case 'widget-left':
                this.addWidget(widget, { mode: 'split-left', ref: ref });
                break;
            case 'widget-right':
                this.addWidget(widget, { mode: 'split-right', ref: ref });
                break;
            case 'widget-bottom':
                this.addWidget(widget, { mode: 'split-bottom', ref: ref });
                break;
            default:
                throw 'unreachable';
        }
        // Accept the proposed drop action.
        event.dropAction = event.proposedAction;
        // Activate the dropped widget.
        this.activateWidget(widget);
    };
    /**
     * Handle the `'keydown'` event for the dock panel.
     */
    DockPanel.prototype._evtKeyDown = function (event) {
        // Stop input events during drag.
        event.preventDefault();
        event.stopPropagation();
        // Release the mouse if `Escape` is pressed.
        if (event.keyCode === 27) {
            // Finalize the mouse release.
            this._releaseMouse();
            // Schedule an emit of the layout modified signal.
            messaging_1.MessageLoop.postMessage(this, Private.LayoutModified);
        }
    };
    /**
     * Handle the `'mousedown'` event for the dock panel.
     */
    DockPanel.prototype._evtMouseDown = function (event) {
        // Do nothing if the left mouse button is not pressed.
        if (event.button !== 0) {
            return;
        }
        // Find the handle which contains the mouse target, if any.
        var layout = this.layout;
        var target = event.target;
        var handle = algorithm_1.find(layout.handles(), function (handle) { return handle.contains(target); });
        if (!handle) {
            return;
        }
        // Stop the event when a handle is pressed.
        event.preventDefault();
        event.stopPropagation();
        // Add the extra document listeners.
        document.addEventListener('keydown', this, true);
        document.addEventListener('mouseup', this, true);
        document.addEventListener('mousemove', this, true);
        document.addEventListener('contextmenu', this, true);
        // Compute the offset deltas for the handle press.
        var rect = handle.getBoundingClientRect();
        var deltaX = event.clientX - rect.left;
        var deltaY = event.clientY - rect.top;
        // Override the cursor and store the press data.
        var style = window.getComputedStyle(handle);
        var override = dragdrop_1.Drag.overrideCursor(style.cursor);
        this._pressData = { handle: handle, deltaX: deltaX, deltaY: deltaY, override: override };
    };
    /**
     * Handle the `'mousemove'` event for the dock panel.
     */
    DockPanel.prototype._evtMouseMove = function (event) {
        // Bail early if no drag is in progress.
        if (!this._pressData) {
            return;
        }
        // Stop the event when dragging a handle.
        event.preventDefault();
        event.stopPropagation();
        // Compute the desired offset position for the handle.
        var rect = this.node.getBoundingClientRect();
        var xPos = event.clientX - rect.left - this._pressData.deltaX;
        var yPos = event.clientY - rect.top - this._pressData.deltaY;
        // Set the handle as close to the desired position as possible.
        var layout = this.layout;
        layout.moveHandle(this._pressData.handle, xPos, yPos);
    };
    /**
     * Handle the `'mouseup'` event for the dock panel.
     */
    DockPanel.prototype._evtMouseUp = function (event) {
        // Do nothing if the left mouse button is not released.
        if (event.button !== 0) {
            return;
        }
        // Stop the event when releasing a handle.
        event.preventDefault();
        event.stopPropagation();
        // Finalize the mouse release.
        this._releaseMouse();
        // Schedule an emit of the layout modified signal.
        messaging_1.MessageLoop.postMessage(this, Private.LayoutModified);
    };
    /**
     * Release the mouse grab for the dock panel.
     */
    DockPanel.prototype._releaseMouse = function () {
        // Bail early if no drag is in progress.
        if (!this._pressData) {
            return;
        }
        // Clear the override cursor.
        this._pressData.override.dispose();
        this._pressData = null;
        // Remove the extra document listeners.
        document.removeEventListener('keydown', this, true);
        document.removeEventListener('mouseup', this, true);
        document.removeEventListener('mousemove', this, true);
        document.removeEventListener('contextmenu', this, true);
    };
    /**
     * Show the overlay indicator at the given client position.
     *
     * Returns the drop zone at the specified client position.
     *
     * #### Notes
     * If the position is not over a valid zone, the overlay is hidden.
     */
    DockPanel.prototype._showOverlay = function (clientX, clientY) {
        // Find the dock target for the given client position.
        var _a = Private.findDropTarget(this, clientX, clientY), zone = _a.zone, target = _a.target;
        // If the drop zone is invalid, hide the overlay and bail.
        if (zone === 'invalid') {
            this.overlay.hide(100);
            return zone;
        }
        // Setup the variables needed to compute the overlay geometry.
        var top;
        var left;
        var right;
        var bottom;
        var box = domutils_1.ElementExt.boxSizing(this.node); // TODO cache this?
        var rect = this.node.getBoundingClientRect();
        // Compute the overlay geometry based on the dock zone.
        switch (zone) {
            case 'root-all':
                top = box.paddingTop;
                left = box.paddingLeft;
                right = box.paddingRight;
                bottom = box.paddingBottom;
                break;
            case 'root-top':
                top = box.paddingTop;
                left = box.paddingLeft;
                right = box.paddingRight;
                bottom = rect.height * Private.GOLDEN_RATIO;
                break;
            case 'root-left':
                top = box.paddingTop;
                left = box.paddingLeft;
                right = rect.width * Private.GOLDEN_RATIO;
                bottom = box.paddingBottom;
                break;
            case 'root-right':
                top = box.paddingTop;
                left = rect.width * Private.GOLDEN_RATIO;
                right = box.paddingRight;
                bottom = box.paddingBottom;
                break;
            case 'root-bottom':
                top = rect.height * Private.GOLDEN_RATIO;
                left = box.paddingLeft;
                right = box.paddingRight;
                bottom = box.paddingBottom;
                break;
            case 'widget-all':
                top = target.top;
                left = target.left;
                right = target.right;
                bottom = target.bottom;
                break;
            case 'widget-top':
                top = target.top;
                left = target.left;
                right = target.right;
                bottom = target.bottom + target.height / 2;
                break;
            case 'widget-left':
                top = target.top;
                left = target.left;
                right = target.right + target.width / 2;
                bottom = target.bottom;
                break;
            case 'widget-right':
                top = target.top;
                left = target.left + target.width / 2;
                right = target.right;
                bottom = target.bottom;
                break;
            case 'widget-bottom':
                top = target.top + target.height / 2;
                left = target.left;
                right = target.right;
                bottom = target.bottom;
                break;
            default:
                throw 'unreachable';
        }
        // Show the overlay with the computed geometry.
        this.overlay.show({ top: top, left: left, right: right, bottom: bottom });
        // Finally, return the computed drop zone.
        return zone;
    };
    /**
     * Create a new tab bar for use by the panel.
     */
    DockPanel.prototype._createTabBar = function () {
        // Create the tab bar.
        var tabBar = this._renderer.createTabBar();
        // Set the generated tab bar property for the tab bar.
        Private.isGeneratedTabBarProperty.set(tabBar, true);
        // Hide the tab bar when in single document mode.
        if (this._mode === 'single-document') {
            tabBar.hide();
        }
        // Enforce necessary tab bar behavior.
        // TODO do we really want to enforce *all* of these?
        tabBar.tabsMovable = true;
        tabBar.allowDeselect = false;
        tabBar.removeBehavior = 'select-previous-tab';
        tabBar.insertBehavior = 'select-tab-if-needed';
        // Connect the signal handlers for the tab bar.
        tabBar.tabMoved.connect(this._onTabMoved, this);
        tabBar.currentChanged.connect(this._onCurrentChanged, this);
        tabBar.tabCloseRequested.connect(this._onTabCloseRequested, this);
        tabBar.tabDetachRequested.connect(this._onTabDetachRequested, this);
        tabBar.tabActivateRequested.connect(this._onTabActivateRequested, this);
        // Return the initialized tab bar.
        return tabBar;
    };
    /**
     * Create a new handle for use by the panel.
     */
    DockPanel.prototype._createHandle = function () {
        return this._renderer.createHandle();
    };
    /**
     * Handle the `tabMoved` signal from a tab bar.
     */
    DockPanel.prototype._onTabMoved = function () {
        messaging_1.MessageLoop.postMessage(this, Private.LayoutModified);
    };
    /**
     * Handle the `currentChanged` signal from a tab bar.
     */
    DockPanel.prototype._onCurrentChanged = function (sender, args) {
        // Extract the previous and current title from the args.
        var previousTitle = args.previousTitle, currentTitle = args.currentTitle;
        // Hide the previous widget.
        if (previousTitle) {
            previousTitle.owner.hide();
        }
        // Show the current widget.
        if (currentTitle) {
            currentTitle.owner.show();
        }
        // Flush the message loop on IE and Edge to prevent flicker.
        if (domutils_1.Platform.IS_EDGE || domutils_1.Platform.IS_IE) {
            messaging_1.MessageLoop.flush();
        }
        // Schedule an emit of the layout modified signal.
        messaging_1.MessageLoop.postMessage(this, Private.LayoutModified);
    };
    /**
     * Handle the `tabActivateRequested` signal from a tab bar.
     */
    DockPanel.prototype._onTabActivateRequested = function (sender, args) {
        args.title.owner.activate();
    };
    /**
     * Handle the `tabCloseRequested` signal from a tab bar.
     */
    DockPanel.prototype._onTabCloseRequested = function (sender, args) {
        args.title.owner.close();
    };
    /**
     * Handle the `tabDetachRequested` signal from a tab bar.
     */
    DockPanel.prototype._onTabDetachRequested = function (sender, args) {
        var _this = this;
        // Do nothing if a drag is already in progress.
        if (this._drag) {
            return;
        }
        // Release the tab bar's hold on the mouse.
        sender.releaseMouse();
        // Extract the data from the args.
        var title = args.title, tab = args.tab, clientX = args.clientX, clientY = args.clientY;
        // Setup the mime data for the drag operation.
        var mimeData = new coreutils_1.MimeData();
        var factory = function () { return title.owner; };
        mimeData.setData('application/vnd.phosphor.widget-factory', factory);
        // Create the drag image for the drag operation.
        var dragImage = tab.cloneNode(true);
        // Create the drag object to manage the drag-drop operation.
        this._drag = new dragdrop_1.Drag({
            mimeData: mimeData, dragImage: dragImage,
            proposedAction: 'move',
            supportedActions: 'move',
        });
        // Hide the tab node in the original tab.
        tab.classList.add('p-mod-hidden');
        // Create the cleanup callback.
        var cleanup = (function () {
            _this._drag = null;
            tab.classList.remove('p-mod-hidden');
        });
        // Start the drag operation and cleanup when done.
        this._drag.start(clientX, clientY).then(cleanup);
    };
    return DockPanel;
}(widget_1.Widget));
exports.DockPanel = DockPanel;
/**
 * The namespace for the `DockPanel` class statics.
 */
(function (DockPanel) {
    /**
     * A concrete implementation of `IOverlay`.
     *
     * This is the default overlay implementation for a dock panel.
     */
    var Overlay = (function () {
        /**
         * Construct a new overlay.
         */
        function Overlay() {
            this._timer = -1;
            this._hidden = true;
            this.node = document.createElement('div');
            this.node.classList.add('p-DockPanel-overlay');
            this.node.classList.add('p-mod-hidden');
            this.node.style.position = 'absolute';
        }
        /**
         * Show the overlay using the given overlay geometry.
         *
         * @param geo - The desired geometry for the overlay.
         */
        Overlay.prototype.show = function (geo) {
            // Update the position of the overlay.
            var style = this.node.style;
            style.top = geo.top + "px";
            style.left = geo.left + "px";
            style.right = geo.right + "px";
            style.bottom = geo.bottom + "px";
            // Clear any pending hide timer.
            clearTimeout(this._timer);
            this._timer = -1;
            // If the overlay is already visible, we're done.
            if (!this._hidden) {
                return;
            }
            // Clear the hidden flag.
            this._hidden = false;
            // Finally, show the overlay.
            this.node.classList.remove('p-mod-hidden');
        };
        /**
         * Hide the overlay node.
         *
         * @param delay - The delay (in ms) before hiding the overlay.
         *   A delay value <= 0 will hide the overlay immediately.
         */
        Overlay.prototype.hide = function (delay) {
            var _this = this;
            // Do nothing if the overlay is already hidden.
            if (this._hidden) {
                return;
            }
            // Hide immediately if the delay is <= 0.
            if (delay <= 0) {
                clearTimeout(this._timer);
                this._timer = -1;
                this._hidden = true;
                this.node.classList.add('p-mod-hidden');
                return;
            }
            // Do nothing if a hide is already pending.
            if (this._timer !== -1) {
                return;
            }
            // Otherwise setup the hide timer.
            this._timer = setTimeout(function () {
                _this._timer = -1;
                _this._hidden = true;
                _this.node.classList.add('p-mod-hidden');
            }, delay);
        };
        return Overlay;
    }());
    DockPanel.Overlay = Overlay;
    /**
     * The default implementation of `IRenderer`.
     */
    var Renderer = (function () {
        function Renderer() {
        }
        /**
         * Create a new tab bar for use with a dock panel.
         *
         * @returns A new tab bar for a dock panel.
         */
        Renderer.prototype.createTabBar = function () {
            var bar = new tabbar_1.TabBar();
            bar.addClass('p-DockPanel-tabBar');
            return bar;
        };
        /**
         * Create a new handle node for use with a dock panel.
         *
         * @returns A new handle node for a dock panel.
         */
        Renderer.prototype.createHandle = function () {
            var handle = document.createElement('div');
            handle.className = 'p-DockPanel-handle';
            return handle;
        };
        return Renderer;
    }());
    DockPanel.Renderer = Renderer;
    /**
     * The default `Renderer` instance.
     */
    DockPanel.defaultRenderer = new Renderer();
})(DockPanel = exports.DockPanel || (exports.DockPanel = {}));
exports.DockPanel = DockPanel;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * A fraction used for sizing root panels; ~= `1 / golden_ratio`.
     */
    Private.GOLDEN_RATIO = 0.618;
    /**
     * The size of the edge dock zone for the root panel, in pixels.
     */
    Private.EDGE_SIZE = 40;
    /**
     * A singleton `'layout-modified'` conflatable message.
     */
    Private.LayoutModified = new messaging_1.ConflatableMessage('layout-modified');
    /**
     * An attached property used to track generated tab bars.
     */
    Private.isGeneratedTabBarProperty = new properties_1.AttachedProperty({
        name: 'isGeneratedTabBar',
        create: function () { return false; }
    });
    /**
     * Create a single document config for the widgets in a dock panel.
     */
    function createSingleDocumentConfig(panel) {
        // Return an empty config if the panel is empty.
        if (panel.isEmpty) {
            return { main: null };
        }
        // Get a flat array of the widgets in the panel.
        var widgets = algorithm_1.toArray(panel.widgets());
        // Get the first selected widget in the panel.
        var selected = panel.selectedWidgets().next();
        // Compute the current index for the new config.
        var currentIndex = selected ? widgets.indexOf(selected) : -1;
        // Return the single document config.
        return { main: { type: 'tab-area', widgets: widgets, currentIndex: currentIndex } };
    }
    Private.createSingleDocumentConfig = createSingleDocumentConfig;
    /**
     * Find the drop target at the given client position.
     */
    function findDropTarget(panel, clientX, clientY) {
        // Bail if the mouse is not over the dock panel.
        if (!domutils_1.ElementExt.hitTest(panel.node, clientX, clientY)) {
            return { zone: 'invalid', target: null };
        }
        // Look up the layout for the panel.
        var layout = panel.layout;
        // If the layout is empty, indicate the entire root drop zone.
        if (layout.isEmpty) {
            return { zone: 'root-all', target: null };
        }
        // Test the edge zones when in multiple document mode.
        if (panel.mode === 'multiple-document') {
            // Get the client rect for the dock panel.
            var panelRect = panel.node.getBoundingClientRect();
            // Compute the distance to each edge of the panel.
            var pl = clientX - panelRect.left + 1;
            var pt = clientY - panelRect.top + 1;
            var pr = panelRect.right - clientX;
            var pb = panelRect.bottom - clientY;
            // Find the minimum distance to an edge.
            var pd = Math.min(pl, pt, pr, pb);
            // Return a root zone if the mouse is within an edge.
            if (pd <= Private.EDGE_SIZE) {
                var zone_1;
                switch (pd) {
                    case pl:
                        zone_1 = 'root-left';
                        break;
                    case pt:
                        zone_1 = 'root-top';
                        break;
                    case pr:
                        zone_1 = 'root-right';
                        break;
                    case pb:
                        zone_1 = 'root-bottom';
                        break;
                    default:
                        throw 'unreachable';
                }
                return { zone: zone_1, target: null };
            }
        }
        // Hit test the dock layout at the given client position.
        var target = layout.hitTestTabAreas(clientX, clientY);
        // Bail if no target area was found.
        if (!target) {
            return { zone: 'invalid', target: null };
        }
        // Return the whole tab area when in single document mode.
        if (panel.mode === 'single-document') {
            return { zone: 'widget-all', target: target };
        }
        // Compute the distance to each edge of the tab area.
        var al = target.x - target.left + 1;
        var at = target.y - target.top + 1;
        var ar = target.left + target.width - target.x;
        var ab = target.top + target.height - target.y;
        // Get the X and Y edge sizes for the area.
        var rx = Math.round(target.width / 3);
        var ry = Math.round(target.height / 3);
        // If the mouse is not within an edge, indicate the entire area.
        if (al > rx && ar > rx && at > ry && ab > ry) {
            return { zone: 'widget-all', target: target };
        }
        // Scale the distances by the slenderness ratio.
        al /= rx;
        at /= ry;
        ar /= rx;
        ab /= ry;
        // Find the minimum distance to the area edge.
        var ad = Math.min(al, at, ar, ab);
        // Find the widget zone for the area edge.
        var zone;
        switch (ad) {
            case al:
                zone = 'widget-left';
                break;
            case at:
                zone = 'widget-top';
                break;
            case ar:
                zone = 'widget-right';
                break;
            case ab:
                zone = 'widget-bottom';
                break;
            default:
                throw 'unreachable';
        }
        // Return the final drop target.
        return { zone: zone, target: target };
    }
    Private.findDropTarget = findDropTarget;
    /**
     * Get the drop reference widget for a tab bar.
     */
    function getDropRef(tabBar) {
        if (tabBar.titles.length === 0) {
            return null;
        }
        if (tabBar.currentTitle) {
            return tabBar.currentTitle.owner;
        }
        return tabBar.titles[tabBar.titles.length - 1].owner;
    }
    Private.getDropRef = getDropRef;
})(Private || (Private = {}));


/***/ }),

/***/ "rynU":
/*!**********************************************************!*\
  !*** ./node_modules/@jupyter-widgets/base/lib/widget.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var utils = __webpack_require__(/*! ./utils */ "o9P/");
var backbonePatch = __webpack_require__(/*! ./backbone-patch */ "X1dy");
var Backbone = __webpack_require__(/*! backbone */ "q1z7");
var $ = __webpack_require__(/*! jquery */ "EVdn");
var nativeview_1 = __webpack_require__(/*! ./nativeview */ "XFcd");
var widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
var messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
var version_1 = __webpack_require__(/*! ./version */ "tLa0");
/**
 * Replace model ids with models recursively.
 */
function unpack_models(value, manager) {
    var unpacked;
    if (Array.isArray(value)) {
        unpacked = [];
        value.forEach(function (sub_value, key) {
            unpacked.push(unpack_models(sub_value, manager));
        });
        return Promise.all(unpacked);
    }
    else if (value instanceof Object) {
        unpacked = {};
        Object.keys(value).forEach(function (key) {
            unpacked[key] = unpack_models(value[key], manager);
        });
        return utils.resolvePromisesDict(unpacked);
    }
    else if (typeof value === 'string' && value.slice(0, 10) === 'IPY_MODEL_') {
        // get_model returns a promise already
        return manager.get_model(value.slice(10, value.length));
    }
    else {
        return Promise.resolve(value);
    }
}
exports.unpack_models = unpack_models;
var WidgetModel = /** @class */ (function (_super) {
    __extends(WidgetModel, _super);
    function WidgetModel() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    /**
     * The default attributes.
     */
    WidgetModel.prototype.defaults = function () {
        return {
            _model_module: '@jupyter-widgets/base',
            _model_name: 'WidgetModel',
            _model_module_version: version_1.JUPYTER_WIDGETS_VERSION,
            _view_module: '@jupyter-widgets/base',
            _view_name: null,
            _view_module_version: version_1.JUPYTER_WIDGETS_VERSION,
            _view_count: null,
        };
    };
    /**
     * Test to see if the model has been synced with the server.
     *
     * #### Notes
     * As of backbone 1.1, backbone ignores `patch` if it thinks the
     * model has never been pushed.
     */
    WidgetModel.prototype.isNew = function () {
        return false;
    };
    /**
     * Constructor
     *
     * Initializes a WidgetModel instance. Called by the Backbone constructor.
     *
     * Parameters
     * ----------
     * widget_manager : WidgetManager instance
     * model_id : string
     *      An ID unique to this model.
     * comm : Comm instance (optional)
     */
    WidgetModel.prototype.initialize = function (attributes, options) {
        _super.prototype.initialize.call(this, attributes, options);
        // Attributes should be initialized here, since user initialization may depend on it
        this.widget_manager = options.widget_manager;
        this.model_id = options.model_id;
        var comm = options.comm;
        this.views = Object.create(null);
        this.state_change = Promise.resolve();
        this._closed = false;
        this._state_lock = null;
        this._msg_buffer = null;
        this._msg_buffer_callbacks = null;
        this._pending_msgs = 0;
        // _buffered_state_diff must be created *after* the super.initialize
        // call above. See the note in the set() method below.
        this._buffered_state_diff = {};
        if (comm) {
            // Remember comm associated with the model.
            this.comm = comm;
            // Hook comm messages up to model.
            comm.on_close(this._handle_comm_closed.bind(this));
            comm.on_msg(this._handle_comm_msg.bind(this));
            this.comm_live = true;
        }
        else {
            this.comm_live = false;
        }
    };
    Object.defineProperty(WidgetModel.prototype, "comm_live", {
        get: function () {
            return this._comm_live;
        },
        set: function (x) {
            this._comm_live = x;
            this.trigger('comm_live_update');
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Send a custom msg over the comm.
     */
    WidgetModel.prototype.send = function (content, callbacks, buffers) {
        if (this.comm !== undefined) {
            var data = { method: 'custom', content: content };
            this.comm.send(data, callbacks, {}, buffers);
        }
    };
    /**
     * Close model
     *
     * @param comm_closed - true if the comm is already being closed. If false, the comm will be closed.
     *
     * @returns - a promise that is fulfilled when all the associated views have been removed.
     */
    WidgetModel.prototype.close = function (comm_closed) {
        var _this = this;
        if (comm_closed === void 0) { comm_closed = false; }
        // can only be closed once.
        if (this._closed) {
            return;
        }
        this._closed = true;
        if (this.comm && !comm_closed) {
            this.comm.close();
        }
        this.stopListening();
        this.trigger('destroy', this);
        if (this.comm) {
            delete this.comm;
        }
        // Delete all views of this model
        var views = Object.keys(this.views).map(function (id) {
            return _this.views[id].then(function (view) { return view.remove(); });
        });
        delete this.views;
        return Promise.all(views).then(function () { return; });
    };
    /**
     * Handle when a widget comm is closed.
     */
    WidgetModel.prototype._handle_comm_closed = function (msg) {
        this.trigger('comm:close');
        this.close(true);
    };
    /**
     * Handle incoming comm msg.
     */
    WidgetModel.prototype._handle_comm_msg = function (msg) {
        var _this = this;
        var method = msg.content.data.method;
        switch (method) {
            case 'update':
                this.state_change = this.state_change
                    .then(function () {
                    var state = msg.content.data.state;
                    var buffer_paths = msg.content.data.buffer_paths || [];
                    // Make sure the buffers are DataViews
                    var buffers = (msg.buffers || []).map(function (b) {
                        if (b instanceof DataView) {
                            return b;
                        }
                        else {
                            return new DataView(b instanceof ArrayBuffer ? b : b.buffer);
                        }
                    });
                    utils.put_buffers(state, buffer_paths, buffers);
                    return _this.constructor._deserialize_state(state, _this.widget_manager);
                }).then(function (state) {
                    _this.set_state(state);
                }).catch(utils.reject("Could not process update msg for model id: " + this.model_id, true));
                return this.state_change;
            case 'custom':
                this.trigger('msg:custom', msg.content.data.content, msg.buffers);
                return Promise.resolve();
        }
    };
    /**
     * Handle when a widget is updated from the backend.
     *
     * This function is meant for internal use only. Values set here will not be propagated on a sync.
     */
    WidgetModel.prototype.set_state = function (state) {
        this._state_lock = state;
        try {
            this.set(state);
        }
        catch (e) {
            console.error("Error setting state: " + e.message);
        }
        finally {
            this._state_lock = null;
        }
    };
    /**
     * Get the serializable state of the model.
     *
     * If drop_default is truthy, attributes that are equal to their default
     * values are dropped.
     */
    WidgetModel.prototype.get_state = function (drop_defaults) {
        var fullState = this.attributes;
        if (drop_defaults) {
            // if defaults is a function, call it
            var d = this.defaults;
            var defaults_1 = (typeof d === 'function') ? d.call(this) : d;
            var state_1 = {};
            Object.keys(fullState).forEach(function (key) {
                if (!(utils.isEqual(fullState[key], defaults_1[key]))) {
                    state_1[key] = fullState[key];
                }
            });
            return state_1;
        }
        else {
            return __assign({}, fullState);
        }
    };
    /**
     * Handle status msgs.
     *
     * execution_state : ('busy', 'idle', 'starting')
     */
    WidgetModel.prototype._handle_status = function (msg) {
        if (this.comm !== void 0) {
            if (msg.content.execution_state === 'idle') {
                this._pending_msgs--;
                // Send buffer if one is waiting and we are below the throttle.
                if (this._msg_buffer !== null
                    && this._pending_msgs < 1) {
                    this.send_sync_message(this._msg_buffer, this._msg_buffer_callbacks);
                    this._msg_buffer = null;
                    this._msg_buffer_callbacks = null;
                }
            }
        }
    };
    /**
     * Create msg callbacks for a comm msg.
     */
    WidgetModel.prototype.callbacks = function (view) {
        return this.widget_manager.callbacks(view);
    };
    /**
     * Set one or more values.
     *
     * We just call the super method, in which val and options are optional.
     * Handles both "key", value and {key: value} -style arguments.
     */
    WidgetModel.prototype.set = function (key, val, options) {
        // Call our patched backbone set. See #1642 and #1643.
        var return_value = backbonePatch.set.call(this, key, val, options);
        // Backbone only remembers the diff of the most recent set()
        // operation.  Calling set multiple times in a row results in a
        // loss of change information.  Here we keep our own running diff.
        //
        // We don't buffer the state set in the constructor (including
        // defaults), so we first check to see if we've initialized _buffered_state_diff.
        // which happens after the constructor sets attributes at creation.
        if (this._buffered_state_diff !== void 0) {
            var attrs = this.changedAttributes() || {};
            // The state_lock lists attributes that are currently being changed
            // right now from a kernel message. We don't want to send these
            // non-changes back to the kernel, so we delete them out of attrs if
            // they haven't changed from their state_lock value.
            // The state lock could be null or undefined (if set is being called from
            // the initializer).
            if (this._state_lock) {
                for (var _i = 0, _a = Object.keys(this._state_lock); _i < _a.length; _i++) {
                    var key_1 = _a[_i];
                    if (attrs[key_1] === this._state_lock[key_1]) {
                        delete attrs[key_1];
                    }
                }
            }
            this._buffered_state_diff = utils.assign(this._buffered_state_diff, attrs);
        }
        return return_value;
    };
    /**
     * Handle sync to the back-end.  Called when a model.save() is called.
     *
     * Make sure a comm exists.
     *
     * Parameters
     * ----------
     * method : create, update, patch, delete, read
     *   create/update always send the full attribute set
     *   patch - only send attributes listed in options.attrs, and if we
     *   are queuing up messages, combine with previous messages that have
     *   not been sent yet
     * model : the model we are syncing
     *   will normally be the same as `this`
     * options : dict
     *   the `attrs` key, if it exists, gives an {attr: value} dict that
     *   should be synced, otherwise, sync all attributes.
     *
     */
    WidgetModel.prototype.sync = function (method, model, options) {
        if (options === void 0) { options = {}; }
        // the typing is to return `any` since the super.sync method returns a JqXHR, but we just return false if there is an error.
        if (this.comm === undefined) {
            throw 'Syncing error: no comm channel defined';
        }
        var attrs = (method === 'patch') ? options.attrs : model.get_state(options.drop_defaults);
        // The state_lock lists attributes that are currently being changed
        // right now from a kernel message. We don't want to send these
        // non-changes back to the kernel, so we delete them out of attrs if
        // they haven't changed from their state_lock value.
        // The state lock could be null or undefined (if this is triggered
        // from the initializer).
        if (this._state_lock) {
            for (var _i = 0, _a = Object.keys(this._state_lock); _i < _a.length; _i++) {
                var key = _a[_i];
                if (attrs[key] === this._state_lock[key]) {
                    delete attrs[key];
                }
            }
        }
        var msgState = this.serialize(attrs);
        if (Object.keys(msgState).length > 0) {
            // If this message was sent via backbone itself, it will not
            // have any callbacks.  It's important that we create callbacks
            // so we can listen for status messages, etc...
            var callbacks = options.callbacks || this.callbacks();
            // Check throttle.
            if (this._pending_msgs >= 1) {
                // The throttle has been exceeded, buffer the current msg so
                // it can be sent once the kernel has finished processing
                // some of the existing messages.
                // Combine updates if it is a 'patch' sync, otherwise replace updates
                switch (method) {
                    case 'patch':
                        this._msg_buffer = utils.assign(this._msg_buffer || {}, msgState);
                        break;
                    case 'update':
                    case 'create':
                        this._msg_buffer = msgState;
                        break;
                    default:
                        throw 'unrecognized syncing method';
                }
                this._msg_buffer_callbacks = callbacks;
            }
            else {
                // We haven't exceeded the throttle, send the message like
                // normal.
                this.send_sync_message(attrs, callbacks);
                // Since the comm is a one-way communication, assume the message
                // arrived and was processed successfully.
                // Don't call options.success since we don't have a model back from
                // the server. Note that this means we don't have the Backbone
                // 'sync' event.
            }
        }
    };
    /**
     * Serialize widget state.
     *
     * A serializer is a function which takes in a state attribute and a widget,
     * and synchronously returns a JSONable object. The returned object will
     * have toJSON called if possible, and the final result should be a
     * primitive object that is a snapshot of the widget state that may have
     * binary array buffers.
     */
    WidgetModel.prototype.serialize = function (state) {
        var serializers = this.constructor.serializers || {};
        for (var _i = 0, _a = Object.keys(state); _i < _a.length; _i++) {
            var k = _a[_i];
            try {
                if (serializers[k] && serializers[k].serialize) {
                    state[k] = (serializers[k].serialize)(state[k], this);
                }
                else {
                    // the default serializer just deep-copies the object
                    state[k] = JSON.parse(JSON.stringify(state[k]));
                }
                if (state[k] && state[k].toJSON) {
                    state[k] = state[k].toJSON();
                }
            }
            catch (e) {
                console.error('Error serializing widget state attribute: ', k);
                throw e;
            }
        }
        return state;
    };
    /**
     * Send a sync message to the kernel.
     */
    WidgetModel.prototype.send_sync_message = function (state, callbacks) {
        var _this = this;
        if (callbacks === void 0) { callbacks = {}; }
        try {
            callbacks.iopub = callbacks.iopub || {};
            var statuscb_1 = callbacks.iopub.status;
            callbacks.iopub.status = function (msg) {
                _this._handle_status(msg);
                if (statuscb_1) {
                    statuscb_1(msg);
                }
            };
            // split out the binary buffers
            var split = utils.remove_buffers(state);
            this.comm.send({
                method: 'update',
                state: split.state,
                buffer_paths: split.buffer_paths
            }, callbacks, {}, split.buffers);
            this._pending_msgs++;
        }
        catch (e) {
            console.error('Could not send widget sync message', e);
        }
    };
    /**
     * Push this model's state to the back-end
     *
     * This invokes a Backbone.Sync.
     */
    WidgetModel.prototype.save_changes = function (callbacks) {
        if (this.comm_live) {
            var options = { patch: true };
            if (callbacks) {
                options.callbacks = callbacks;
            }
            this.save(this._buffered_state_diff, options);
            this._buffered_state_diff = {};
        }
    };
    /**
     * on_some_change(['key1', 'key2'], foo, context) differs from
     * on('change:key1 change:key2', foo, context).
     * If the widget attributes key1 and key2 are both modified,
     * the second form will result in foo being called twice
     * while the first will call foo only once.
     */
    WidgetModel.prototype.on_some_change = function (keys, callback, context) {
        this.on('change', function () {
            if (keys.some(this.hasChanged, this)) {
                callback.apply(context, arguments);
            }
        }, this);
    };
    /**
     * Serialize the model.  See the deserialization function at the top of this file
     * and the kernel-side serializer/deserializer.
     */
    WidgetModel.prototype.toJSON = function (options) {
        return "IPY_MODEL_" + this.model_id;
    };
    /**
     * Returns a promise for the deserialized state. The second argument
     * is an instance of widget manager, which is required for the
     * deserialization of widget models.
     */
    WidgetModel._deserialize_state = function (state, manager) {
        var serializers = this.serializers;
        var deserialized;
        if (serializers) {
            deserialized = {};
            for (var k in state) {
                if (serializers[k] && serializers[k].deserialize) {
                    deserialized[k] = (serializers[k].deserialize)(state[k], manager);
                }
                else {
                    deserialized[k] = state[k];
                }
            }
        }
        else {
            deserialized = state;
        }
        return utils.resolvePromisesDict(deserialized);
    };
    return WidgetModel;
}(Backbone.Model));
exports.WidgetModel = WidgetModel;
var DOMWidgetModel = /** @class */ (function (_super) {
    __extends(DOMWidgetModel, _super);
    function DOMWidgetModel() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    DOMWidgetModel.prototype.defaults = function () {
        return utils.assign(_super.prototype.defaults.call(this), {
            _dom_classes: []
            // We do not declare defaults for the layout and style attributes.
            // Those defaults are constructed on the kernel side and synced here
            // as needed, and our code here copes with those attributes being
            // undefined. See
            // https://github.com/jupyter-widgets/ipywidgets/issues/1620 and
            // https://github.com/jupyter-widgets/ipywidgets/pull/1621
        });
    };
    DOMWidgetModel.serializers = __assign({}, WidgetModel.serializers, { layout: { deserialize: unpack_models }, style: { deserialize: unpack_models } });
    return DOMWidgetModel;
}(WidgetModel));
exports.DOMWidgetModel = DOMWidgetModel;
var WidgetView = /** @class */ (function (_super) {
    __extends(WidgetView, _super);
    /**
     * Public constructor.
     */
    function WidgetView(options) {
        return _super.call(this, options) || this;
    }
    /**
     * Initializer, called at the end of the constructor.
     */
    WidgetView.prototype.initialize = function (parameters) {
        var _this = this;
        this.listenTo(this.model, 'change', function () {
            var changed = Object.keys(_this.model.changedAttributes() || {});
            if (changed[0] === '_view_count' && changed.length === 1) {
                // Just the view count was updated
                return;
            }
            _this.update();
        });
        this.options = parameters.options;
        this.once('remove', function () {
            if (typeof (_this.model.get('_view_count')) === 'number') {
                _this.model.set('_view_count', _this.model.get('_view_count') - 1);
                _this.model.save_changes();
            }
        });
        this.once('displayed', function () {
            if (typeof (_this.model.get('_view_count')) === 'number') {
                _this.model.set('_view_count', _this.model.get('_view_count') + 1);
                _this.model.save_changes();
            }
        });
        this.displayed = new Promise(function (resolve, reject) {
            _this.once('displayed', resolve);
        });
    };
    /**
     * Triggered on model change.
     *
     * Update view to be consistent with this.model
     */
    WidgetView.prototype.update = function (options) {
        return;
    };
    /**
     * Render a view
     *
     * @returns the view or a promise to the view.
     */
    WidgetView.prototype.render = function () {
        return;
    };
    /**
     * Create and promise that resolves to a child view of a given model
     */
    WidgetView.prototype.create_child_view = function (child_model, options) {
        if (options === void 0) { options = {}; }
        var that = this;
        options = __assign({ parent: this }, options);
        return this.model.widget_manager.create_view(child_model, options)
            .catch(utils.reject('Could not create child view', true));
    };
    /**
     * Create msg callbacks for a comm msg.
     */
    WidgetView.prototype.callbacks = function () {
        return this.model.callbacks(this);
    };
    /**
     * Send a custom msg associated with this view.
     */
    WidgetView.prototype.send = function (content, buffers) {
        this.model.send(content, this.callbacks(), buffers);
    };
    WidgetView.prototype.touch = function () {
        this.model.save_changes(this.callbacks());
    };
    WidgetView.prototype.remove = function () {
        // Raise a remove event when the view is removed.
        _super.prototype.remove.call(this);
        this.trigger('remove');
        return this;
    };
    return WidgetView;
}(nativeview_1.NativeView));
exports.WidgetView = WidgetView;
var JupyterPhosphorWidget = /** @class */ (function (_super) {
    __extends(JupyterPhosphorWidget, _super);
    function JupyterPhosphorWidget(options) {
        var _this = this;
        var view = options.view;
        delete options.view;
        _this = _super.call(this, options) || this;
        _this._view = view;
        return _this;
    }
    /**
     * Dispose the widget.
     *
     * This causes the view to be destroyed as well with 'remove'
     */
    JupyterPhosphorWidget.prototype.dispose = function () {
        if (this.isDisposed) {
            return;
        }
        _super.prototype.dispose.call(this);
        if (this._view) {
            this._view.remove();
        }
        this._view = null;
    };
    /**
     * Process the phosphor message.
     *
     * Any custom phosphor widget used inside a Jupyter widget should override
     * the processMessage function like this.
     */
    JupyterPhosphorWidget.prototype.processMessage = function (msg) {
        _super.prototype.processMessage.call(this, msg);
        this._view.processPhosphorMessage(msg);
    };
    return JupyterPhosphorWidget;
}(widgets_1.Widget));
exports.JupyterPhosphorWidget = JupyterPhosphorWidget;
var DOMWidgetView = /** @class */ (function (_super) {
    __extends(DOMWidgetView, _super);
    function DOMWidgetView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    /**
     * Public constructor
     */
    DOMWidgetView.prototype.initialize = function (parameters) {
        var _this = this;
        _super.prototype.initialize.call(this, parameters);
        this.listenTo(this.model, 'change:_dom_classes', function (model, new_classes) {
            var old_classes = model.previous('_dom_classes');
            _this.update_classes(old_classes, new_classes);
        });
        this.layoutPromise = Promise.resolve();
        this.listenTo(this.model, 'change:layout', function (model, value) {
            _this.setLayout(value, model.previous('layout'));
        });
        this.stylePromise = Promise.resolve();
        this.listenTo(this.model, 'change:style', function (model, value) {
            _this.setStyle(value, model.previous('style'));
        });
        this.displayed.then(function () {
            _this.update_classes([], _this.model.get('_dom_classes'));
            _this.setLayout(_this.model.get('layout'));
            _this.setStyle(_this.model.get('style'));
        });
        this._comm_live_update();
        this.listenTo(this.model, 'comm_live_update', function () {
            _this._comm_live_update();
        });
    };
    DOMWidgetView.prototype.setLayout = function (layout, oldLayout) {
        var _this = this;
        if (layout) {
            this.layoutPromise = this.layoutPromise.then(function (oldLayoutView) {
                if (oldLayoutView) {
                    oldLayoutView.unlayout();
                    _this.stopListening(oldLayoutView.model);
                    oldLayoutView.remove();
                }
                return _this.create_child_view(layout).then(function (view) {
                    // Trigger the displayed event of the child view.
                    return _this.displayed.then(function () {
                        view.trigger('displayed');
                        _this.listenTo(view.model, 'change', function () {
                            // Post (asynchronous) so layout changes can take
                            // effect first.
                            messaging_1.MessageLoop.postMessage(_this.pWidget, widgets_1.Widget.ResizeMessage.UnknownSize);
                        });
                        messaging_1.MessageLoop.postMessage(_this.pWidget, widgets_1.Widget.ResizeMessage.UnknownSize);
                        return view;
                    });
                }).catch(utils.reject('Could not add LayoutView to DOMWidgetView', true));
            });
        }
    };
    DOMWidgetView.prototype.setStyle = function (style, oldStyle) {
        var _this = this;
        if (style) {
            this.stylePromise = this.stylePromise.then(function (oldStyleView) {
                if (oldStyleView) {
                    oldStyleView.unstyle();
                    _this.stopListening(oldStyleView.model);
                    oldStyleView.remove();
                }
                return _this.create_child_view(style).then(function (view) {
                    // Trigger the displayed event of the child view.
                    return _this.displayed.then(function () {
                        view.trigger('displayed');
                        // Unlike for the layout attribute, style changes don't
                        // trigger phosphor resize messages.
                        return view;
                    });
                }).catch(utils.reject('Could not add styleView to DOMWidgetView', true));
            });
        }
    };
    /**
     * Update the DOM classes applied to an element, default to this.el.
     */
    DOMWidgetView.prototype.update_classes = function (old_classes, new_classes, el) {
        if (el === undefined) {
            el = this.el;
        }
        utils.difference(old_classes, new_classes).map(function (c) {
            if (el.classList) { // classList is not supported by IE for svg elements
                el.classList.remove(c);
            }
            else {
                el.setAttribute('class', el.getAttribute('class').replace(c, ''));
            }
        });
        utils.difference(new_classes, old_classes).map(function (c) {
            if (el.classList) { // classList is not supported by IE for svg elements
                el.classList.add(c);
            }
            else {
                el.setAttribute('class', el.getAttribute('class').concat(' ', c));
            }
        });
    };
    /**
     * Update the DOM classes applied to the widget based on a single
     * trait's value.
     *
     * Given a trait value classes map, this function automatically
     * handles applying the appropriate classes to the widget element
     * and removing classes that are no longer valid.
     *
     * Parameters
     * ----------
     * class_map: dictionary
     *  Dictionary of trait values to class lists.
     *  Example:
     *      {
     *          success: ['alert', 'alert-success'],
     *          info: ['alert', 'alert-info'],
     *          warning: ['alert', 'alert-warning'],
     *          danger: ['alert', 'alert-danger']
     *      };
     * trait_name: string
     *  Name of the trait to check the value of.
     * el: optional DOM element handle, defaults to this.el
     *  Element that the classes are applied to.
     */
    DOMWidgetView.prototype.update_mapped_classes = function (class_map, trait_name, el) {
        var key = this.model.previous(trait_name);
        var old_classes = class_map[key] ? class_map[key] : [];
        key = this.model.get(trait_name);
        var new_classes = class_map[key] ? class_map[key] : [];
        this.update_classes(old_classes, new_classes, el || this.el);
    };
    DOMWidgetView.prototype.set_mapped_classes = function (class_map, trait_name, el) {
        var key = this.model.get(trait_name);
        var new_classes = class_map[key] ? class_map[key] : [];
        this.update_classes([], new_classes, el || this.el);
    };
    DOMWidgetView.prototype._setElement = function (el) {
        if (this.pWidget) {
            this.pWidget.dispose();
        }
        this.$el = el instanceof $ ? el : $(el);
        this.el = this.$el[0];
        this.pWidget = new JupyterPhosphorWidget({
            node: el,
            view: this
        });
    };
    DOMWidgetView.prototype.remove = function () {
        if (this.pWidget) {
            this.pWidget.dispose();
        }
        return _super.prototype.remove.call(this);
    };
    DOMWidgetView.prototype.processPhosphorMessage = function (msg) {
        switch (msg.type) {
            case 'after-attach':
                this.trigger('displayed');
                break;
        }
    };
    DOMWidgetView.prototype._comm_live_update = function () {
        if (this.model.comm_live) {
            this.pWidget.removeClass('jupyter-widgets-disconnected');
        }
        else {
            this.pWidget.addClass('jupyter-widgets-disconnected');
        }
    };
    return DOMWidgetView;
}(WidgetView));
exports.DOMWidgetView = DOMWidgetView;


/***/ }),

/***/ "rzV7":
/*!***********************************************!*\
  !*** ./node_modules/fbjs/lib/shallowEqual.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks
 * 
 */

/*eslint-disable no-self-compare */



var hasOwnProperty = Object.prototype.hasOwnProperty;

/**
 * inlined Object.is polyfill to avoid requiring consumers ship their own
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
 */
function is(x, y) {
  // SameValue algorithm
  if (x === y) {
    // Steps 1-5, 7-10
    // Steps 6.b-6.e: +0 != -0
    // Added the nonzero y check to make Flow happy, but it is redundant
    return x !== 0 || y !== 0 || 1 / x === 1 / y;
  } else {
    // Step 6.a: NaN == NaN
    return x !== x && y !== y;
  }
}

/**
 * Performs equality by iterating through keys on an object and returning false
 * when any key has values which are not strictly equal between the arguments.
 * Returns true when the values of all keys are strictly equal.
 */
function shallowEqual(objA, objB) {
  if (is(objA, objB)) {
    return true;
  }

  if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
    return false;
  }

  var keysA = Object.keys(objA);
  var keysB = Object.keys(objB);

  if (keysA.length !== keysB.length) {
    return false;
  }

  // Test for A's keys different from B.
  for (var i = 0; i < keysA.length; i++) {
    if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
      return false;
    }
  }

  return true;
}

module.exports = shallowEqual;

/***/ }),

/***/ "s+uk":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/de-at.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


function processRelativeTime(number, withoutSuffix, key, isFuture) {
    var format = {
        'm': ['eine Minute', 'einer Minute'],
        'h': ['eine Stunde', 'einer Stunde'],
        'd': ['ein Tag', 'einem Tag'],
        'dd': [number + ' Tage', number + ' Tagen'],
        'M': ['ein Monat', 'einem Monat'],
        'MM': [number + ' Monate', number + ' Monaten'],
        'y': ['ein Jahr', 'einem Jahr'],
        'yy': [number + ' Jahre', number + ' Jahren']
    };
    return withoutSuffix ? format[key][0] : format[key][1];
}

var deAt = moment.defineLocale('de-at', {
    months : 'Jänner_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'),
    monthsShort : 'Jän._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'),
    monthsParseExact : true,
    weekdays : 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'),
    weekdaysShort : 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'),
    weekdaysMin : 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT: 'HH:mm',
        LTS: 'HH:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D. MMMM YYYY',
        LLL : 'D. MMMM YYYY HH:mm',
        LLLL : 'dddd, D. MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay: '[heute um] LT [Uhr]',
        sameElse: 'L',
        nextDay: '[morgen um] LT [Uhr]',
        nextWeek: 'dddd [um] LT [Uhr]',
        lastDay: '[gestern um] LT [Uhr]',
        lastWeek: '[letzten] dddd [um] LT [Uhr]'
    },
    relativeTime : {
        future : 'in %s',
        past : 'vor %s',
        s : 'ein paar Sekunden',
        ss : '%d Sekunden',
        m : processRelativeTime,
        mm : '%d Minuten',
        h : processRelativeTime,
        hh : '%d Stunden',
        d : processRelativeTime,
        dd : processRelativeTime,
        M : processRelativeTime,
        MM : processRelativeTime,
        y : processRelativeTime,
        yy : processRelativeTime
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return deAt;

})));


/***/ }),

/***/ "s/Uv":
/*!**********************************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/text_editors/RichText/StyleButtonGroup.js ***!
  \**********************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _StyleButton = __webpack_require__(/*! ./StyleButton */ "mfsF");

var _StyleButton2 = _interopRequireDefault(_StyleButton);

var _configuration = __webpack_require__(/*! ./configuration */ "3Mxs");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var StyleButtonGroup = function (_Component) {
  _inherits(StyleButtonGroup, _Component);

  function StyleButtonGroup() {
    _classCallCheck(this, StyleButtonGroup);

    return _possibleConstructorReturn(this, (StyleButtonGroup.__proto__ || Object.getPrototypeOf(StyleButtonGroup)).apply(this, arguments));
  }

  _createClass(StyleButtonGroup, [{
    key: 'render',
    value: function render() {
      var _props = this.props,
          currentStyle = _props.currentStyle,
          linkIsSelected = _props.linkIsSelected,
          styles = _props.styles,
          onToggle = _props.onToggle;


      var isActive = function isActive(currentStyle, value) {
        if (value === _configuration.LINK) {
          return linkIsSelected;
        }

        if (typeof currentStyle.has === 'function') {
          return currentStyle.has(value);
        }

        return Boolean(currentStyle.value);
      };

      return _react2.default.createElement(
        'div',
        { className: 'rich-text-editor__controls' },
        styles.map(function (_ref) {
          var label = _ref.label,
              value = _ref.value;
          return _react2.default.createElement(_StyleButton2.default, {
            key: value,
            active: isActive(currentStyle, value),
            label: label,
            onToggle: onToggle,
            value: value
          });
        })
      );
    }
  }]);

  return StyleButtonGroup;
}(_react.Component);

StyleButtonGroup.propTypes = {
  onToggle: _propTypes2.default.func.isRequired,
  styles: _propTypes2.default.arrayOf(_propTypes2.default.shape({
    label: _propTypes2.default.element.isRequired,
    value: _propTypes2.default.string.isRequired
  })).isRequired,

  // A draft-js DraftInlineStyle instance
  // https://facebook.github.io/draft-js/docs/api-reference-editor-state.html#getcurrentinlinestyle
  currentStyle: _propTypes2.default.object,
  linkIsSelected: _propTypes2.default.bool
};

exports.default = StyleButtonGroup;
//# sourceMappingURL=StyleButtonGroup.js.map

/***/ }),

/***/ "s3Ml":
/*!***********************************************************************!*\
  !*** ./node_modules/babel-runtime/core-js/object/set-prototype-of.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = { "default": __webpack_require__(/*! core-js/library/fn/object/set-prototype-of */ "JbBM"), __esModule: true };

/***/ }),

/***/ "s4NR":
/*!***********************************************!*\
  !*** ./node_modules/querystring-es3/index.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.decode = exports.parse = __webpack_require__(/*! ./decode */ "kd2E");
exports.encode = exports.stringify = __webpack_require__(/*! ./encode */ "4JlD");


/***/ }),

/***/ "s6NM":
/*!******************************************************************!*\
  !*** ./node_modules/react-base16-styling/lib/colorConverters.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.yuv2rgb = yuv2rgb;
exports.rgb2yuv = rgb2yuv;
function yuv2rgb(yuv) {
  var y = yuv[0],
      u = yuv[1],
      v = yuv[2],
      r,
      g,
      b;

  r = y * 1 + u * 0 + v * 1.13983;
  g = y * 1 + u * -0.39465 + v * -0.58060;
  b = y * 1 + u * 2.02311 + v * 0;

  r = Math.min(Math.max(0, r), 1);
  g = Math.min(Math.max(0, g), 1);
  b = Math.min(Math.max(0, b), 1);

  return [r * 255, g * 255, b * 255];
}

function rgb2yuv(rgb) {
  var r = rgb[0] / 255,
      g = rgb[1] / 255,
      b = rgb[2] / 255;

  var y = r * 0.299 + g * 0.587 + b * 0.114;
  var u = r * -0.14713 + g * -0.28886 + b * 0.436;
  var v = r * 0.615 + g * -0.51499 + b * -0.10001;

  return [y, u, v];
};

/***/ }),

/***/ "s7xW":
/*!*************************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeHistogram2dcontourIcon.js ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeHistogram2dcontourIcon = function TraceTypeHistogram2dcontourIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement('path', { fill: 'none', d: 'M0 0h46v46H0z' }),
        _react2.default.createElement('path', { d: 'M40.616 19.3a16.387 16.387 0 0 0-1.352-3.904 9.836 9.836 0 0 0-4.225-4.015c-6.17-3.152-13.563-4.731-20.021-1.298a23.665 23.665 0 0 0-4.74 3.47 14.357 14.357 0 0 0-3.28 3.934c-1.636 3.205-.982 6.997-.015 10.433a7.81 7.81 0 0 0 1.083 2.555 8.344 8.344 0 0 0 2.63 2.1c2.611 1.526 5.352 2.845 8.089 4.161a13.223 13.223 0 0 0 2.59 1.028 11.867 11.867 0 0 0 3.048.229 8.678 8.678 0 0 0 3.538-.623 8.95 8.95 0 0 0 2.162-1.622l6.115-5.645c2.223-2.053 4.584-4.37 4.83-7.288a10.951 10.951 0 0 0-.452-3.515zm-5.174 2.942c-.29 1.988-1.825 3.679-3.153 4.984a88.579 88.579 0 0 1-3.648 3.367 5.915 5.915 0 0 1-1.32.94 5.617 5.617 0 0 1-2.098.423 7.835 7.835 0 0 1-1.807-.076 9.038 9.038 0 0 1-1.8-.557 31.794 31.794 0 0 1-5.487-2.889 7.104 7.104 0 0 1-1.758-1.487q-.114-.146-.212-.3a5.426 5.426 0 0 1-.622-1.396 11.172 11.172 0 0 1-.476-3.496 6.775 6.775 0 0 1 .752-2.988 9.108 9.108 0 0 1 2.07-2.44 13.848 13.848 0 0 1 3.042-2.08 11.145 11.145 0 0 1 1.363-.556c3.693-1.236 7.762-.478 11.257 1.23a7.12 7.12 0 0 1 2.765 2.381 6.918 6.918 0 0 1 .995 2.566 6.94 6.94 0 0 1 .137 2.374z', fill: '#25fdfc', stroke: '#1d9bfb', strokeMiterlimit: '10', strokeWidth: '2' }),
        _react2.default.createElement('path', { d: 'M34.31 17.302a7.12 7.12 0 0 0-2.765-2.382c-3.495-1.709-7.564-2.466-11.257-1.23a11.145 11.145 0 0 0-1.363.556 13.848 13.848 0 0 0-3.043 2.081 9.108 9.108 0 0 0-2.07 2.44 6.775 6.775 0 0 0-.75 2.987 11.172 11.172 0 0 0 .475 3.496 5.426 5.426 0 0 0 .622 1.397q.099.153.212.3a7.104 7.104 0 0 0 1.758 1.486 31.794 31.794 0 0 0 5.486 2.889 9.038 9.038 0 0 0 1.801.558 7.835 7.835 0 0 0 1.807.075 5.617 5.617 0 0 0 2.099-.423 5.915 5.915 0 0 0 1.319-.94 88.299 88.299 0 0 0 3.648-3.366c1.328-1.306 2.863-2.996 3.153-4.985a6.94 6.94 0 0 0-.137-2.373 6.918 6.918 0 0 0-.995-2.566z', fill: '#25fdfc', stroke: '#1d9bfb', opacity: '.25', strokeMiterlimit: '10', strokeWidth: '2' }),
        _react2.default.createElement('path', { d: 'M25.457 25.996c-1.787.083-3.494-1.142-4.914-2.724a2.032 2.032 0 0 1-.452-.69 2.44 2.44 0 0 1 .028-1.4 3.985 3.985 0 0 1 1.368-2.08 4.888 4.888 0 0 1 1.922-.854 6.99 6.99 0 0 1 5.948.96c1.604 1.233-.197 4.086-1.018 5.142a3.975 3.975 0 0 1-2.882 1.646z', fill: '#fff', stroke: '#1d9bfb', strokeMiterlimit: '10', strokeWidth: '2' })
    );
};

exports.default = TraceTypeHistogram2dcontourIcon;

/***/ }),

/***/ "s8ra":
/*!*****************************************************!*\
  !*** ./node_modules/draft-js/lib/KeyBindingUtil.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule KeyBindingUtil
 * @format
 * 
 */



var UserAgent = __webpack_require__(/*! fbjs/lib/UserAgent */ "CYTE");

var isOSX = UserAgent.isPlatform('Mac OS X');

var KeyBindingUtil = {
  /**
   * Check whether the ctrlKey modifier is *not* being used in conjunction with
   * the altKey modifier. If they are combined, the result is an `altGraph`
   * key modifier, which should not be handled by this set of key bindings.
   */
  isCtrlKeyCommand: function isCtrlKeyCommand(e) {
    return !!e.ctrlKey && !e.altKey;
  },

  isOptionKeyCommand: function isOptionKeyCommand(e) {
    return isOSX && e.altKey;
  },

  hasCommandModifier: function hasCommandModifier(e) {
    return isOSX ? !!e.metaKey && !e.altKey : KeyBindingUtil.isCtrlKeyCommand(e);
  }
};

module.exports = KeyBindingUtil;

/***/ }),

/***/ "sBIJ":
/*!*****************************************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/text_editors/RichText/getSelectionCoordinates.js ***!
  \*****************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var getCoordinates = function getCoordinates() {
  var coordinates = { x: 0, y: 0 };

  var rect = document.getElementsByClassName('text-editor')[0].getBoundingClientRect();

  var LINK_POP_UP_WIDTH = 158.5;

  if (rect) {
    // Add to the offset
    coordinates.x += rect.width * 0.5 - LINK_POP_UP_WIDTH / 2;
    coordinates.y += rect.height * 0.5;
  }

  return coordinates;
};

exports.default = getCoordinates;
//# sourceMappingURL=getSelectionCoordinates.js.map

/***/ }),

/***/ "sBam":
/*!**********************************************!*\
  !*** ./node_modules/base16/lib/grayscale.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'grayscale',
  author: 'alexandre gavioli (https://github.com/alexx2/)',
  base00: '#101010',
  base01: '#252525',
  base02: '#464646',
  base03: '#525252',
  base04: '#ababab',
  base05: '#b9b9b9',
  base06: '#e3e3e3',
  base07: '#f7f7f7',
  base08: '#7c7c7c',
  base09: '#999999',
  base0A: '#a0a0a0',
  base0B: '#8e8e8e',
  base0C: '#868686',
  base0D: '#686868',
  base0E: '#747474',
  base0F: '#5e5e5e'
};
module.exports = exports['default'];

/***/ }),

/***/ "sEG9":
/*!***************************************************!*\
  !*** ./node_modules/css-loader/lib/url/escape.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = function escape(url) {
    if (typeof url !== 'string') {
        return url
    }
    // If url is already wrapped in quotes, remove them
    if (/^['"].*['"]$/.test(url)) {
        url = url.slice(1, -1);
    }
    // Should url be wrapped?
    // See https://drafts.csswg.org/css-values-3/#urls
    if (/["'() \t\n]/.test(url)) {
        return '"' + url.replace(/"/g, '\\"').replace(/\n/g, '\\n') + '"'
    }

    return url
}


/***/ }),

/***/ "sEf8":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_baseUnary.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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);
  };
}

module.exports = baseUnary;


/***/ }),

/***/ "sEfC":
/*!*****************************************!*\
  !*** ./node_modules/lodash/debounce.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isObject = __webpack_require__(/*! ./isObject */ "GoyQ"),
    now = __webpack_require__(/*! ./now */ "QIyF"),
    toNumber = __webpack_require__(/*! ./toNumber */ "tLB3");

/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max,
    nativeMin = Math.min;

/**
 * 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.
        timerId = setTimeout(timerExpired, wait);
        return invokeFunc(lastCallTime);
      }
    }
    if (timerId === undefined) {
      timerId = setTimeout(timerExpired, wait);
    }
    return result;
  }
  debounced.cancel = cancel;
  debounced.flush = flush;
  return debounced;
}

module.exports = debounce;


/***/ }),

/***/ "sHIV":
/*!************************************************************!*\
  !*** ./node_modules/prop-types/factoryWithTypeCheckers.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */



var ReactIs = __webpack_require__(/*! react-is */ "TOwV");
var assign = __webpack_require__(/*! object-assign */ "MgzW");

var ReactPropTypesSecret = __webpack_require__(/*! ./lib/ReactPropTypesSecret */ "WbBG");
var checkPropTypes = __webpack_require__(/*! ./checkPropTypes */ "oVyQ");

var has = Function.call.bind(Object.prototype.hasOwnProperty);
var printWarning = function() {};

if (true) {
  printWarning = function(text) {
    var message = 'Warning: ' + text;
    if (typeof console !== 'undefined') {
      console.error(message);
    }
    try {
      // --- Welcome to debugging React ---
      // This error was thrown as a convenience so that you can use this stack
      // to find the callsite that caused this warning to fire.
      throw new Error(message);
    } catch (x) {}
  };
}

function emptyFunctionThatReturnsNull() {
  return null;
}

module.exports = function(isValidElement, throwOnDirectAccess) {
  /* global Symbol */
  var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
  var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.

  /**
   * Returns the iterator method function contained on the iterable object.
   *
   * Be sure to invoke the function with the iterable as context:
   *
   *     var iteratorFn = getIteratorFn(myIterable);
   *     if (iteratorFn) {
   *       var iterator = iteratorFn.call(myIterable);
   *       ...
   *     }
   *
   * @param {?object} maybeIterable
   * @return {?function}
   */
  function getIteratorFn(maybeIterable) {
    var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
    if (typeof iteratorFn === 'function') {
      return iteratorFn;
    }
  }

  /**
   * Collection of methods that allow declaration and validation of props that are
   * supplied to React components. Example usage:
   *
   *   var Props = require('ReactPropTypes');
   *   var MyArticle = React.createClass({
   *     propTypes: {
   *       // An optional string prop named "description".
   *       description: Props.string,
   *
   *       // A required enum prop named "category".
   *       category: Props.oneOf(['News','Photos']).isRequired,
   *
   *       // A prop named "dialog" that requires an instance of Dialog.
   *       dialog: Props.instanceOf(Dialog).isRequired
   *     },
   *     render: function() { ... }
   *   });
   *
   * A more formal specification of how these methods are used:
   *
   *   type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
   *   decl := ReactPropTypes.{type}(.isRequired)?
   *
   * Each and every declaration produces a function with the same signature. This
   * allows the creation of custom validation functions. For example:
   *
   *  var MyLink = React.createClass({
   *    propTypes: {
   *      // An optional string or URI prop named "href".
   *      href: function(props, propName, componentName) {
   *        var propValue = props[propName];
   *        if (propValue != null && typeof propValue !== 'string' &&
   *            !(propValue instanceof URI)) {
   *          return new Error(
   *            'Expected a string or an URI for ' + propName + ' in ' +
   *            componentName
   *          );
   *        }
   *      }
   *    },
   *    render: function() {...}
   *  });
   *
   * @internal
   */

  var ANONYMOUS = '<<anonymous>>';

  // Important!
  // Keep this list in sync with production version in `./factoryWithThrowingShims.js`.
  var ReactPropTypes = {
    array: createPrimitiveTypeChecker('array'),
    bool: createPrimitiveTypeChecker('boolean'),
    func: createPrimitiveTypeChecker('function'),
    number: createPrimitiveTypeChecker('number'),
    object: createPrimitiveTypeChecker('object'),
    string: createPrimitiveTypeChecker('string'),
    symbol: createPrimitiveTypeChecker('symbol'),

    any: createAnyTypeChecker(),
    arrayOf: createArrayOfTypeChecker,
    element: createElementTypeChecker(),
    elementType: createElementTypeTypeChecker(),
    instanceOf: createInstanceTypeChecker,
    node: createNodeChecker(),
    objectOf: createObjectOfTypeChecker,
    oneOf: createEnumTypeChecker,
    oneOfType: createUnionTypeChecker,
    shape: createShapeTypeChecker,
    exact: createStrictShapeTypeChecker,
  };

  /**
   * inlined Object.is polyfill to avoid requiring consumers ship their own
   * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
   */
  /*eslint-disable no-self-compare*/
  function is(x, y) {
    // SameValue algorithm
    if (x === y) {
      // Steps 1-5, 7-10
      // Steps 6.b-6.e: +0 != -0
      return x !== 0 || 1 / x === 1 / y;
    } else {
      // Step 6.a: NaN == NaN
      return x !== x && y !== y;
    }
  }
  /*eslint-enable no-self-compare*/

  /**
   * We use an Error-like object for backward compatibility as people may call
   * PropTypes directly and inspect their output. However, we don't use real
   * Errors anymore. We don't inspect their stack anyway, and creating them
   * is prohibitively expensive if they are created too often, such as what
   * happens in oneOfType() for any type before the one that matched.
   */
  function PropTypeError(message) {
    this.message = message;
    this.stack = '';
  }
  // Make `instanceof Error` still work for returned errors.
  PropTypeError.prototype = Error.prototype;

  function createChainableTypeChecker(validate) {
    if (true) {
      var manualPropTypeCallCache = {};
      var manualPropTypeWarningCount = 0;
    }
    function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
      componentName = componentName || ANONYMOUS;
      propFullName = propFullName || propName;

      if (secret !== ReactPropTypesSecret) {
        if (throwOnDirectAccess) {
          // New behavior only for users of `prop-types` package
          var err = new Error(
            'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
            'Use `PropTypes.checkPropTypes()` to call them. ' +
            'Read more at http://fb.me/use-check-prop-types'
          );
          err.name = 'Invariant Violation';
          throw err;
        } else if ("development" !== 'production' && typeof console !== 'undefined') {
          // Old behavior for people using React.PropTypes
          var cacheKey = componentName + ':' + propName;
          if (
            !manualPropTypeCallCache[cacheKey] &&
            // Avoid spamming the console because they are often not actionable except for lib authors
            manualPropTypeWarningCount < 3
          ) {
            printWarning(
              'You are manually calling a React.PropTypes validation ' +
              'function for the `' + propFullName + '` prop on `' + componentName  + '`. This is deprecated ' +
              'and will throw in the standalone `prop-types` package. ' +
              'You may be seeing this warning due to a third-party PropTypes ' +
              'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.'
            );
            manualPropTypeCallCache[cacheKey] = true;
            manualPropTypeWarningCount++;
          }
        }
      }
      if (props[propName] == null) {
        if (isRequired) {
          if (props[propName] === null) {
            return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
          }
          return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
        }
        return null;
      } else {
        return validate(props, propName, componentName, location, propFullName);
      }
    }

    var chainedCheckType = checkType.bind(null, false);
    chainedCheckType.isRequired = checkType.bind(null, true);

    return chainedCheckType;
  }

  function createPrimitiveTypeChecker(expectedType) {
    function validate(props, propName, componentName, location, propFullName, secret) {
      var propValue = props[propName];
      var propType = getPropType(propValue);
      if (propType !== expectedType) {
        // `propValue` being instance of, say, date/regexp, pass the 'object'
        // check, but we can offer a more precise error message here rather than
        // 'of type `object`'.
        var preciseType = getPreciseType(propValue);

        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
      }
      return null;
    }
    return createChainableTypeChecker(validate);
  }

  function createAnyTypeChecker() {
    return createChainableTypeChecker(emptyFunctionThatReturnsNull);
  }

  function createArrayOfTypeChecker(typeChecker) {
    function validate(props, propName, componentName, location, propFullName) {
      if (typeof typeChecker !== 'function') {
        return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
      }
      var propValue = props[propName];
      if (!Array.isArray(propValue)) {
        var propType = getPropType(propValue);
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
      }
      for (var i = 0; i < propValue.length; i++) {
        var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret);
        if (error instanceof Error) {
          return error;
        }
      }
      return null;
    }
    return createChainableTypeChecker(validate);
  }

  function createElementTypeChecker() {
    function validate(props, propName, componentName, location, propFullName) {
      var propValue = props[propName];
      if (!isValidElement(propValue)) {
        var propType = getPropType(propValue);
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
      }
      return null;
    }
    return createChainableTypeChecker(validate);
  }

  function createElementTypeTypeChecker() {
    function validate(props, propName, componentName, location, propFullName) {
      var propValue = props[propName];
      if (!ReactIs.isValidElementType(propValue)) {
        var propType = getPropType(propValue);
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement type.'));
      }
      return null;
    }
    return createChainableTypeChecker(validate);
  }

  function createInstanceTypeChecker(expectedClass) {
    function validate(props, propName, componentName, location, propFullName) {
      if (!(props[propName] instanceof expectedClass)) {
        var expectedClassName = expectedClass.name || ANONYMOUS;
        var actualClassName = getClassName(props[propName]);
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
      }
      return null;
    }
    return createChainableTypeChecker(validate);
  }

  function createEnumTypeChecker(expectedValues) {
    if (!Array.isArray(expectedValues)) {
      if (true) {
        if (arguments.length > 1) {
          printWarning(
            'Invalid arguments supplied to oneOf, expected an array, got ' + arguments.length + ' arguments. ' +
            'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).'
          );
        } else {
          printWarning('Invalid argument supplied to oneOf, expected an array.');
        }
      }
      return emptyFunctionThatReturnsNull;
    }

    function validate(props, propName, componentName, location, propFullName) {
      var propValue = props[propName];
      for (var i = 0; i < expectedValues.length; i++) {
        if (is(propValue, expectedValues[i])) {
          return null;
        }
      }

      var valuesString = JSON.stringify(expectedValues, function replacer(key, value) {
        var type = getPreciseType(value);
        if (type === 'symbol') {
          return String(value);
        }
        return value;
      });
      return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + String(propValue) + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
    }
    return createChainableTypeChecker(validate);
  }

  function createObjectOfTypeChecker(typeChecker) {
    function validate(props, propName, componentName, location, propFullName) {
      if (typeof typeChecker !== 'function') {
        return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
      }
      var propValue = props[propName];
      var propType = getPropType(propValue);
      if (propType !== 'object') {
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
      }
      for (var key in propValue) {
        if (has(propValue, key)) {
          var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
          if (error instanceof Error) {
            return error;
          }
        }
      }
      return null;
    }
    return createChainableTypeChecker(validate);
  }

  function createUnionTypeChecker(arrayOfTypeCheckers) {
    if (!Array.isArray(arrayOfTypeCheckers)) {
       true ? printWarning('Invalid argument supplied to oneOfType, expected an instance of array.') : undefined;
      return emptyFunctionThatReturnsNull;
    }

    for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
      var checker = arrayOfTypeCheckers[i];
      if (typeof checker !== 'function') {
        printWarning(
          'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' +
          'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.'
        );
        return emptyFunctionThatReturnsNull;
      }
    }

    function validate(props, propName, componentName, location, propFullName) {
      for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
        var checker = arrayOfTypeCheckers[i];
        if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) {
          return null;
        }
      }

      return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
    }
    return createChainableTypeChecker(validate);
  }

  function createNodeChecker() {
    function validate(props, propName, componentName, location, propFullName) {
      if (!isNode(props[propName])) {
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
      }
      return null;
    }
    return createChainableTypeChecker(validate);
  }

  function createShapeTypeChecker(shapeTypes) {
    function validate(props, propName, componentName, location, propFullName) {
      var propValue = props[propName];
      var propType = getPropType(propValue);
      if (propType !== 'object') {
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
      }
      for (var key in shapeTypes) {
        var checker = shapeTypes[key];
        if (!checker) {
          continue;
        }
        var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
        if (error) {
          return error;
        }
      }
      return null;
    }
    return createChainableTypeChecker(validate);
  }

  function createStrictShapeTypeChecker(shapeTypes) {
    function validate(props, propName, componentName, location, propFullName) {
      var propValue = props[propName];
      var propType = getPropType(propValue);
      if (propType !== 'object') {
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
      }
      // We need to check all keys in case some are required but missing from
      // props.
      var allKeys = assign({}, props[propName], shapeTypes);
      for (var key in allKeys) {
        var checker = shapeTypes[key];
        if (!checker) {
          return new PropTypeError(
            'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' +
            '\nBad object: ' + JSON.stringify(props[propName], null, '  ') +
            '\nValid keys: ' +  JSON.stringify(Object.keys(shapeTypes), null, '  ')
          );
        }
        var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
        if (error) {
          return error;
        }
      }
      return null;
    }

    return createChainableTypeChecker(validate);
  }

  function isNode(propValue) {
    switch (typeof propValue) {
      case 'number':
      case 'string':
      case 'undefined':
        return true;
      case 'boolean':
        return !propValue;
      case 'object':
        if (Array.isArray(propValue)) {
          return propValue.every(isNode);
        }
        if (propValue === null || isValidElement(propValue)) {
          return true;
        }

        var iteratorFn = getIteratorFn(propValue);
        if (iteratorFn) {
          var iterator = iteratorFn.call(propValue);
          var step;
          if (iteratorFn !== propValue.entries) {
            while (!(step = iterator.next()).done) {
              if (!isNode(step.value)) {
                return false;
              }
            }
          } else {
            // Iterator will provide entry [k,v] tuples rather than values.
            while (!(step = iterator.next()).done) {
              var entry = step.value;
              if (entry) {
                if (!isNode(entry[1])) {
                  return false;
                }
              }
            }
          }
        } else {
          return false;
        }

        return true;
      default:
        return false;
    }
  }

  function isSymbol(propType, propValue) {
    // Native Symbol.
    if (propType === 'symbol') {
      return true;
    }

    // falsy value can't be a Symbol
    if (!propValue) {
      return false;
    }

    // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
    if (propValue['@@toStringTag'] === 'Symbol') {
      return true;
    }

    // Fallback for non-spec compliant Symbols which are polyfilled.
    if (typeof Symbol === 'function' && propValue instanceof Symbol) {
      return true;
    }

    return false;
  }

  // Equivalent of `typeof` but with special handling for array and regexp.
  function getPropType(propValue) {
    var propType = typeof propValue;
    if (Array.isArray(propValue)) {
      return 'array';
    }
    if (propValue instanceof RegExp) {
      // Old webkits (at least until Android 4.0) return 'function' rather than
      // 'object' for typeof a RegExp. We'll normalize this here so that /bla/
      // passes PropTypes.object.
      return 'object';
    }
    if (isSymbol(propType, propValue)) {
      return 'symbol';
    }
    return propType;
  }

  // This handles more types than `getPropType`. Only used for error messages.
  // See `createPrimitiveTypeChecker`.
  function getPreciseType(propValue) {
    if (typeof propValue === 'undefined' || propValue === null) {
      return '' + propValue;
    }
    var propType = getPropType(propValue);
    if (propType === 'object') {
      if (propValue instanceof Date) {
        return 'date';
      } else if (propValue instanceof RegExp) {
        return 'regexp';
      }
    }
    return propType;
  }

  // Returns a string that is postfixed to a warning about an invalid type.
  // For example, "undefined" or "of type array"
  function getPostfixForTypeWarning(value) {
    var type = getPreciseType(value);
    switch (type) {
      case 'array':
      case 'object':
        return 'an ' + type;
      case 'boolean':
      case 'date':
      case 'regexp':
        return 'a ' + type;
      default:
        return type;
    }
  }

  // Returns class name of the object, if any.
  function getClassName(propValue) {
    if (!propValue.constructor || !propValue.constructor.name) {
      return ANONYMOUS;
    }
    return propValue.constructor.name;
  }

  ReactPropTypes.checkPropTypes = checkPropTypes;
  ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache;
  ReactPropTypes.PropTypes = ReactPropTypes;

  return ReactPropTypes;
};


/***/ }),

/***/ "sHuL":
/*!*********************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/default_panels/index.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.GraphSubplotsPanel = exports.StyleUpdateMenusPanel = exports.StyleColorbarsPanel = exports.StyleTracesPanel = exports.StyleImagesPanel = exports.StyleSlidersPanel = exports.StyleShapesPanel = exports.StyleNotesPanel = exports.StyleLegendPanel = exports.StyleAxesPanel = exports.StyleLayoutPanel = exports.GraphTransformsPanel = exports.GraphCreatePanel = undefined;

var _GraphCreatePanel = __webpack_require__(/*! ./GraphCreatePanel */ "V6Tf");

var _GraphCreatePanel2 = _interopRequireDefault(_GraphCreatePanel);

var _GraphTransformsPanel = __webpack_require__(/*! ./GraphTransformsPanel */ "jRlY");

var _GraphTransformsPanel2 = _interopRequireDefault(_GraphTransformsPanel);

var _StyleLayoutPanel = __webpack_require__(/*! ./StyleLayoutPanel */ "6LUF");

var _StyleLayoutPanel2 = _interopRequireDefault(_StyleLayoutPanel);

var _StyleAxesPanel = __webpack_require__(/*! ./StyleAxesPanel */ "UpXw");

var _StyleAxesPanel2 = _interopRequireDefault(_StyleAxesPanel);

var _StyleLegendPanel = __webpack_require__(/*! ./StyleLegendPanel */ "9txC");

var _StyleLegendPanel2 = _interopRequireDefault(_StyleLegendPanel);

var _StyleNotesPanel = __webpack_require__(/*! ./StyleNotesPanel */ "y0JR");

var _StyleNotesPanel2 = _interopRequireDefault(_StyleNotesPanel);

var _StyleShapesPanel = __webpack_require__(/*! ./StyleShapesPanel */ "Ybq/");

var _StyleShapesPanel2 = _interopRequireDefault(_StyleShapesPanel);

var _StyleSlidersPanel = __webpack_require__(/*! ./StyleSlidersPanel */ "E1lr");

var _StyleSlidersPanel2 = _interopRequireDefault(_StyleSlidersPanel);

var _StyleImagesPanel = __webpack_require__(/*! ./StyleImagesPanel */ "QN1r");

var _StyleImagesPanel2 = _interopRequireDefault(_StyleImagesPanel);

var _StyleTracesPanel = __webpack_require__(/*! ./StyleTracesPanel */ "bVuD");

var _StyleTracesPanel2 = _interopRequireDefault(_StyleTracesPanel);

var _StyleColorbarsPanel = __webpack_require__(/*! ./StyleColorbarsPanel */ "51Cs");

var _StyleColorbarsPanel2 = _interopRequireDefault(_StyleColorbarsPanel);

var _StyleUpdateMenusPanel = __webpack_require__(/*! ./StyleUpdateMenusPanel */ "MGuP");

var _StyleUpdateMenusPanel2 = _interopRequireDefault(_StyleUpdateMenusPanel);

var _GraphSubplotsPanel = __webpack_require__(/*! ./GraphSubplotsPanel */ "VLFu");

var _GraphSubplotsPanel2 = _interopRequireDefault(_GraphSubplotsPanel);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.GraphCreatePanel = _GraphCreatePanel2.default;
exports.GraphTransformsPanel = _GraphTransformsPanel2.default;
exports.StyleLayoutPanel = _StyleLayoutPanel2.default;
exports.StyleAxesPanel = _StyleAxesPanel2.default;
exports.StyleLegendPanel = _StyleLegendPanel2.default;
exports.StyleNotesPanel = _StyleNotesPanel2.default;
exports.StyleShapesPanel = _StyleShapesPanel2.default;
exports.StyleSlidersPanel = _StyleSlidersPanel2.default;
exports.StyleImagesPanel = _StyleImagesPanel2.default;
exports.StyleTracesPanel = _StyleTracesPanel2.default;
exports.StyleColorbarsPanel = _StyleColorbarsPanel2.default;
exports.StyleUpdateMenusPanel = _StyleUpdateMenusPanel2.default;
exports.GraphSubplotsPanel = _GraphSubplotsPanel2.default;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ "sJIH":
/*!***********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/LocationSelector.js ***!
  \***********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _Radio = __webpack_require__(/*! ./Radio */ "5Riz");

var _Radio2 = _interopRequireDefault(_Radio);

var _Dropdown = __webpack_require__(/*! ./Dropdown */ "dRXW");

var _DataSelector = __webpack_require__(/*! ./DataSelector */ "dv5i");

var _DataSelector2 = _interopRequireDefault(_DataSelector);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var LocationmodeVisible = (0, _lib.connectToContainer)(_Dropdown.UnconnectedDropdown, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    if (!plotProps.fullValue) {
      plotProps.isVisible = true;
      plotProps.fullValue = plotProps.container.locationmode;
      return;
    }
  }
});

var UnconnectedLocation = function (_Component) {
  _inherits(UnconnectedLocation, _Component);

  function UnconnectedLocation() {
    _classCallCheck(this, UnconnectedLocation);

    return _possibleConstructorReturn(this, (UnconnectedLocation.__proto__ || Object.getPrototypeOf(UnconnectedLocation)).apply(this, arguments));
  }

  _createClass(UnconnectedLocation, [{
    key: 'render',
    value: function render() {
      var _ = this.context.localize;


      return _react2.default.createElement(
        _react.Fragment,
        null,
        _react2.default.createElement(_DataSelector2.default, { label: _('Locations'), attr: 'locations' }),
        _react2.default.createElement(LocationmodeVisible, {
          label: _('Location Format'),
          attr: 'locationmode',
          clearable: false,
          options: [{ label: _('Country Names'), value: 'country names' }, { label: _('Country Abbreviations (ISO-3)'), value: 'ISO-3' }, {
            label: _('USA State Abbreviations (e.g. NY)'),
            value: 'USA-states'
          }]
        })
      );
    }
  }]);

  return UnconnectedLocation;
}(_react.Component);

UnconnectedLocation.propTypes = _extends({
  attr: _propTypes2.default.string
}, _Field2.default.propTypes);

UnconnectedLocation.contextTypes = {
  localize: _propTypes2.default.func,
  updateContainer: _propTypes2.default.func
};

var Location = (0, _lib.connectToContainer)(UnconnectedLocation);

var UnconnectedLocationSelector = function (_Component2) {
  _inherits(UnconnectedLocationSelector, _Component2);

  function UnconnectedLocationSelector(props, context) {
    _classCallCheck(this, UnconnectedLocationSelector);

    var _this2 = _possibleConstructorReturn(this, (UnconnectedLocationSelector.__proto__ || Object.getPrototypeOf(UnconnectedLocationSelector)).call(this, props, context));

    _this2.state = {
      mode: props.container.locations ? 'location' : 'latlon'
    };

    _this2.setMode = _this2.setMode.bind(_this2);
    return _this2;
  }

  _createClass(UnconnectedLocationSelector, [{
    key: 'componentWillMount',
    value: function componentWillMount() {
      this.setState({
        mode: this.props.container.locations ? 'location' : 'latlon'
      });
    }
  }, {
    key: 'setMode',
    value: function setMode(mode) {
      this.setState({ mode: mode });
      this.props.updateContainer(mode === 'latlon' ? {
        locations: null,
        locationmode: null,
        locationssrc: null,
        locationmodesrc: null
      } : { lat: null, lon: null, latsrc: null, lonsrc: null });
    }
  }, {
    key: 'render',
    value: function render() {
      var mode = this.state.mode;
      var _context = this.context,
          _ = _context.localize,
          type = _context.container.type;


      return type === 'scattergeo' ? _react2.default.createElement(
        _react.Fragment,
        null,
        _react2.default.createElement(
          _Field2.default,
          _extends({}, this.props, { attr: this.props.attr }),
          _react2.default.createElement(_Radio2.default, {
            options: [{ value: 'latlon', label: _('Lat/Lon') }, { value: 'location', label: _('Location') }],
            fullValue: mode,
            updatePlot: this.setMode,
            attr: this.props.attr
          })
        ),
        mode === 'latlon' ? _react2.default.createElement(
          _react.Fragment,
          null,
          _react2.default.createElement(_DataSelector2.default, { label: _('Latitude'), attr: 'lat' }),
          _react2.default.createElement(_DataSelector2.default, { label: _('Longitude'), attr: 'lon' })
        ) : _react2.default.createElement(Location, { attr: 'type' })
      ) : type === 'choropleth' ? _react2.default.createElement(Location, { attr: 'type' }) : _react2.default.createElement(
        _react.Fragment,
        null,
        _react2.default.createElement(_DataSelector2.default, { label: _('Latitude'), attr: 'lat' }),
        _react2.default.createElement(_DataSelector2.default, { label: _('Longitude'), attr: 'lon' })
      );
    }
  }]);

  return UnconnectedLocationSelector;
}(_react.Component);

UnconnectedLocationSelector.propTypes = _extends({
  fullValue: _propTypes2.default.any,
  updatePlot: _propTypes2.default.func,
  attr: _propTypes2.default.string
}, _Field2.default.propTypes);

UnconnectedLocationSelector.contextTypes = {
  container: _propTypes2.default.object,
  localize: _propTypes2.default.func,
  updateContainer: _propTypes2.default.func
};

exports.default = (0, _lib.connectToContainer)(UnconnectedLocationSelector);
//# sourceMappingURL=LocationSelector.js.map

/***/ }),

/***/ "sK/K":
/*!*******************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/codemirror/theme/hopscotch.css ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*\n\n    Name:       Hopscotch\n    Author:     Jan T. Sott\n\n    CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror)\n    Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16)\n\n*/\n\n.cm-s-hopscotch.CodeMirror {background: #322931; color: #d5d3d5;}\n.cm-s-hopscotch div.CodeMirror-selected {background: #433b42 !important;}\n.cm-s-hopscotch .CodeMirror-gutters {background: #322931; border-right: 0px;}\n.cm-s-hopscotch .CodeMirror-linenumber {color: #797379;}\n.cm-s-hopscotch .CodeMirror-cursor {border-left: 1px solid #989498 !important;}\n\n.cm-s-hopscotch span.cm-comment {color: #b33508;}\n.cm-s-hopscotch span.cm-atom {color: #c85e7c;}\n.cm-s-hopscotch span.cm-number {color: #c85e7c;}\n\n.cm-s-hopscotch span.cm-property, .cm-s-hopscotch span.cm-attribute {color: #8fc13e;}\n.cm-s-hopscotch span.cm-keyword {color: #dd464c;}\n.cm-s-hopscotch span.cm-string {color: #fdcc59;}\n\n.cm-s-hopscotch span.cm-variable {color: #8fc13e;}\n.cm-s-hopscotch span.cm-variable-2 {color: #1290bf;}\n.cm-s-hopscotch span.cm-def {color: #fd8b19;}\n.cm-s-hopscotch span.cm-error {background: #dd464c; color: #989498;}\n.cm-s-hopscotch span.cm-bracket {color: #d5d3d5;}\n.cm-s-hopscotch span.cm-tag {color: #dd464c;}\n.cm-s-hopscotch span.cm-link {color: #c85e7c;}\n\n.cm-s-hopscotch .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;}\n.cm-s-hopscotch .CodeMirror-activeline-background { background: #302020; }\n", ""]);

// exports


/***/ }),

/***/ "sLCx":
/*!**********************************************************!*\
  !*** ./node_modules/@jupyterlab/codeeditor/lib/index.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
__webpack_require__(/*! ../style/index.css */ "uq1y");
__export(__webpack_require__(/*! ./editor */ "oMAC"));
__export(__webpack_require__(/*! ./jsoneditor */ "hBOs"));
__export(__webpack_require__(/*! ./widget */ "eGGc"));
__export(__webpack_require__(/*! ./mimetype */ "fNmR"));
/* tslint:disable */
/**
 * Code editor services token.
 */
exports.IEditorServices = new coreutils_1.Token('@jupyterlab/codeeditor:IEditorServices');


/***/ }),

/***/ "sQiz":
/*!*****************************************************!*\
  !*** ./node_modules/source-map/lib/mapping-list.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* -*- Mode: js; js-indent-level: 2; -*- */
/*
 * Copyright 2014 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var util = __webpack_require__(/*! ./util */ "Cbry");

/**
 * Determine whether mappingB is after mappingA with respect to generated
 * position.
 */
function generatedPositionAfter(mappingA, mappingB) {
  // Optimized for most common case
  var lineA = mappingA.generatedLine;
  var lineB = mappingB.generatedLine;
  var columnA = mappingA.generatedColumn;
  var columnB = mappingB.generatedColumn;
  return lineB > lineA || lineB == lineA && columnB >= columnA ||
         util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
}

/**
 * A data structure to provide a sorted view of accumulated mappings in a
 * performance conscious manner. It trades a neglibable overhead in general
 * case for a large speedup in case of mappings being added in order.
 */
function MappingList() {
  this._array = [];
  this._sorted = true;
  // Serves as infimum
  this._last = {generatedLine: -1, generatedColumn: 0};
}

/**
 * Iterate through internal items. This method takes the same arguments that
 * `Array.prototype.forEach` takes.
 *
 * NOTE: The order of the mappings is NOT guaranteed.
 */
MappingList.prototype.unsortedForEach =
  function MappingList_forEach(aCallback, aThisArg) {
    this._array.forEach(aCallback, aThisArg);
  };

/**
 * Add the given source mapping.
 *
 * @param Object aMapping
 */
MappingList.prototype.add = function MappingList_add(aMapping) {
  if (generatedPositionAfter(this._last, aMapping)) {
    this._last = aMapping;
    this._array.push(aMapping);
  } else {
    this._sorted = false;
    this._array.push(aMapping);
  }
};

/**
 * Returns the flat, sorted array of mappings. The mappings are sorted by
 * generated position.
 *
 * WARNING: This method returns internal data without copying, for
 * performance. The return value must NOT be mutated, and should be treated as
 * an immutable borrow. If you want to take ownership, you must make your own
 * copy.
 */
MappingList.prototype.toArray = function MappingList_toArray() {
  if (!this._sorted) {
    this._array.sort(util.compareByGeneratedPositionsInflated);
    this._sorted = true;
  }
  return this._array;
};

exports.MappingList = MappingList;


/***/ }),

/***/ "sVjb":
/*!*******************************************************************************!*\
  !*** ./node_modules/react-color/lib/components/photoshop/PhotoshopPointer.js ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.PhotoshopPointerCircle = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PhotoshopPointerCircle = exports.PhotoshopPointerCircle = function PhotoshopPointerCircle() {
  var styles = (0, _reactcss2.default)({
    'default': {
      triangle: {
        width: 0,
        height: 0,
        borderStyle: 'solid',
        borderWidth: '4px 0 4px 6px',
        borderColor: 'transparent transparent transparent #fff',
        position: 'absolute',
        top: '1px',
        left: '1px'
      },
      triangleBorder: {
        width: 0,
        height: 0,
        borderStyle: 'solid',
        borderWidth: '5px 0 5px 8px',
        borderColor: 'transparent transparent transparent #555'
      },

      left: {
        Extend: 'triangleBorder',
        transform: 'translate(-13px, -4px)'
      },
      leftInside: {
        Extend: 'triangle',
        transform: 'translate(-8px, -5px)'
      },

      right: {
        Extend: 'triangleBorder',
        transform: 'translate(20px, -14px) rotate(180deg)'
      },
      rightInside: {
        Extend: 'triangle',
        transform: 'translate(-8px, -5px)'
      }
    }
  });

  return _react2.default.createElement(
    'div',
    { style: styles.pointer },
    _react2.default.createElement(
      'div',
      { style: styles.left },
      _react2.default.createElement('div', { style: styles.leftInside })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.right },
      _react2.default.createElement('div', { style: styles.rightInside })
    )
  );
};

exports.default = PhotoshopPointerCircle;

/***/ }),

/***/ "sYGr":
/*!*********************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/root.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _container = __webpack_require__(/*! ./container */ "+9U2");

var _container2 = _interopRequireDefault(_container);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * Represents a CSS file and contains all its parsed nodes.
 *
 * @extends Container
 *
 * @example
 * const root = postcss.parse('a{color:black} b{z-index:2}');
 * root.type         //=> 'root'
 * root.nodes.length //=> 2
 */
var Root = function (_Container) {
    _inherits(Root, _Container);

    function Root(defaults) {
        _classCallCheck(this, Root);

        var _this = _possibleConstructorReturn(this, _Container.call(this, defaults));

        _this.type = 'root';
        if (!_this.nodes) _this.nodes = [];
        return _this;
    }

    Root.prototype.removeChild = function removeChild(child, ignore) {
        var index = this.index(child);

        if (!ignore && index === 0 && this.nodes.length > 1) {
            this.nodes[1].raws.before = this.nodes[index].raws.before;
        }

        return _Container.prototype.removeChild.call(this, child);
    };

    Root.prototype.normalize = function normalize(child, sample, type) {
        var nodes = _Container.prototype.normalize.call(this, child);

        if (sample) {
            if (type === 'prepend') {
                if (this.nodes.length > 1) {
                    sample.raws.before = this.nodes[1].raws.before;
                } else {
                    delete sample.raws.before;
                }
            } else if (this.first !== sample) {
                for (var _iterator = nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
                    var _ref;

                    if (_isArray) {
                        if (_i >= _iterator.length) break;
                        _ref = _iterator[_i++];
                    } else {
                        _i = _iterator.next();
                        if (_i.done) break;
                        _ref = _i.value;
                    }

                    var node = _ref;

                    node.raws.before = sample.raws.before;
                }
            }
        }

        return nodes;
    };

    /**
     * Returns a {@link Result} instance representing the root’s CSS.
     *
     * @param {processOptions} [opts] - options with only `to` and `map` keys
     *
     * @return {Result} result with current root’s CSS
     *
     * @example
     * const root1 = postcss.parse(css1, { from: 'a.css' });
     * const root2 = postcss.parse(css2, { from: 'b.css' });
     * root1.append(root2);
     * const result = root1.toResult({ to: 'all.css', map: true });
     */


    Root.prototype.toResult = function toResult() {
        var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

        var LazyResult = __webpack_require__(/*! ./lazy-result */ "A7MO");
        var Processor = __webpack_require__(/*! ./processor */ "jTUL");

        var lazy = new LazyResult(new Processor(), this, opts);
        return lazy.stringify();
    };

    /**
     * @memberof Root#
     * @member {object} raws - Information to generate byte-to-byte equal
     *                         node string as it was in the origin input.
     *
     * Every parser saves its own properties,
     * but the default CSS parser uses:
     *
     * * `after`: the space symbols after the last child to the end of file.
     * * `semicolon`: is the last child has an (optional) semicolon.
     *
     * @example
     * postcss.parse('a {}\n').raws //=> { after: '\n' }
     * postcss.parse('a {}').raws   //=> { after: '' }
     */

    return Root;
}(_container2.default);

exports.default = Root;
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64, 


/***/ }),

/***/ "sYhS":
/*!***********************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/launcher-extension/style/index.css ***!
  \***********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n", ""]);

// exports


/***/ }),

/***/ "sZro":
/*!************************************************************!*\
  !*** ./node_modules/readable-stream/lib/_stream_duplex.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.

// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.



/*<replacement>*/

var pna = __webpack_require__(/*! process-nextick-args */ "lm0R");
/*</replacement>*/

/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
  var keys = [];
  for (var key in obj) {
    keys.push(key);
  }return keys;
};
/*</replacement>*/

module.exports = Duplex;

/*<replacement>*/
var util = __webpack_require__(/*! core-util-is */ "Onz0");
util.inherits = __webpack_require__(/*! inherits */ "P7XM");
/*</replacement>*/

var Readable = __webpack_require__(/*! ./_stream_readable */ "rXFu");
var Writable = __webpack_require__(/*! ./_stream_writable */ "3BRs");

util.inherits(Duplex, Readable);

{
  // avoid scope creep, the keys array can then be collected
  var keys = objectKeys(Writable.prototype);
  for (var v = 0; v < keys.length; v++) {
    var method = keys[v];
    if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  }
}

function Duplex(options) {
  if (!(this instanceof Duplex)) return new Duplex(options);

  Readable.call(this, options);
  Writable.call(this, options);

  if (options && options.readable === false) this.readable = false;

  if (options && options.writable === false) this.writable = false;

  this.allowHalfOpen = true;
  if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;

  this.once('end', onend);
}

Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function () {
    return this._writableState.highWaterMark;
  }
});

// the no-half-open enforcer
function onend() {
  // if we allow half-open state, or if the writable side ended,
  // then we're ok.
  if (this.allowHalfOpen || this._writableState.ended) return;

  // no more data can be written.
  // But allow more writes to happen in this tick.
  pna.nextTick(onEndNT, this);
}

function onEndNT(self) {
  self.end();
}

Object.defineProperty(Duplex.prototype, 'destroyed', {
  get: function () {
    if (this._readableState === undefined || this._writableState === undefined) {
      return false;
    }
    return this._readableState.destroyed && this._writableState.destroyed;
  },
  set: function (value) {
    // we ignore the value if the stream
    // has not been initialized yet
    if (this._readableState === undefined || this._writableState === undefined) {
      return;
    }

    // backward compatibility, the user is explicitly
    // managing destroyed
    this._readableState.destroyed = value;
    this._writableState.destroyed = value;
  }
});

Duplex.prototype._destroy = function (err, cb) {
  this.push(null);
  this.end();

  pna.nextTick(cb, err);
};

/***/ }),

/***/ "sagP":
/*!***********************************************!*\
  !*** ./node_modules/ajv/lib/compile/async.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var MissingRefError = __webpack_require__(/*! ./error_classes */ "iZoB").MissingRef;

module.exports = compileAsync;


/**
 * Creates validating function for passed schema with asynchronous loading of missing schemas.
 * `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.
 * @this  Ajv
 * @param {Object}   schema schema object
 * @param {Boolean}  meta optional true to compile meta-schema; this parameter can be skipped
 * @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function.
 * @return {Promise} promise that resolves with a validating function.
 */
function compileAsync(schema, meta, callback) {
  /* eslint no-shadow: 0 */
  /* global Promise */
  /* jshint validthis: true */
  var self = this;
  if (typeof this._opts.loadSchema != 'function')
    throw new Error('options.loadSchema should be a function');

  if (typeof meta == 'function') {
    callback = meta;
    meta = undefined;
  }

  var p = loadMetaSchemaOf(schema).then(function () {
    var schemaObj = self._addSchema(schema, undefined, meta);
    return schemaObj.validate || _compileAsync(schemaObj);
  });

  if (callback) {
    p.then(
      function(v) { callback(null, v); },
      callback
    );
  }

  return p;


  function loadMetaSchemaOf(sch) {
    var $schema = sch.$schema;
    return $schema && !self.getSchema($schema)
            ? compileAsync.call(self, { $ref: $schema }, true)
            : Promise.resolve();
  }


  function _compileAsync(schemaObj) {
    try { return self._compile(schemaObj); }
    catch(e) {
      if (e instanceof MissingRefError) return loadMissingSchema(e);
      throw e;
    }


    function loadMissingSchema(e) {
      var ref = e.missingSchema;
      if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved');

      var schemaPromise = self._loadingSchemas[ref];
      if (!schemaPromise) {
        schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref);
        schemaPromise.then(removePromise, removePromise);
      }

      return schemaPromise.then(function (sch) {
        if (!added(ref)) {
          return loadMetaSchemaOf(sch).then(function () {
            if (!added(ref)) self.addSchema(sch, ref, undefined, meta);
          });
        }
      }).then(function() {
        return _compileAsync(schemaObj);
      });

      function removePromise() {
        delete self._loadingSchemas[ref];
      }

      function added(ref) {
        return self._refs[ref] || self._schemas[ref];
      }
    }
  }
}


/***/ }),

/***/ "sca4":
/*!******************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/index.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.RectanglePositioner = exports.DefaultEditor = exports.EditorControls = exports.walkObject = exports.localizeString = exports.localize = exports.dereference = exports.connectTraceToPlot = exports.connectRangeSelectorToAxis = exports.connectToContainer = exports.connectLayoutToPlot = exports.connectAggregationToTransform = exports.connectTransformToTrace = exports.connectAxesToLayout = exports.connectImageToLayout = exports.connectShapeToLayout = exports.connectAnnotationToLayout = exports.connectNonCartesianSubplotToLayout = exports.connectCartesianSubplotToLayout = exports.TraceSelector = exports.TraceRequiredPanel = exports.TraceMarkerSection = exports.TraceAccordion = exports.TextEditor = exports.SymbolSelector = exports.StyleTracesPanel = exports.StyleImagesPanel = exports.StyleShapesPanel = exports.StyleNotesPanel = exports.StyleLegendPanel = exports.StyleLayoutPanel = exports.StyleColorbarsPanel = exports.StyleAxesPanel = exports.GraphTransformsPanel = exports.SingleSidebarItem = exports.Section = exports.PlotlySection = exports.Radio = exports.PanelMenuWrapper = exports.PanelEmpty = exports.Panel = exports.PlotlyPanel = exports.Text = exports.AxisRangeValue = exports.Numeric = exports.LineShapeSelector = exports.LineDashSelector = exports.LayoutSection = exports.LayoutPanel = exports.NumericFractionInverse = exports.PositioningNumeric = exports.NumericFraction = exports.Info = exports.GraphCreatePanel = exports.FontSelector = exports.Fold = exports.PlotlyFold = exports.Flaglist = exports.RangesliderVisible = exports.EDITOR_ACTIONS = exports.Dropzone = exports.Dropdown = exports.DataSelector = exports.ErrorBars = exports.ContourNumeric = exports.PieColorscalePicker = exports.ColorscalePicker = exports.ColorwayPicker = exports.PanelMessage = exports.ColorPicker = exports.Button = exports.AxesSelector = exports.DTicksInterval = exports.DTicks = exports.NTicks = exports.AxesRange = exports.AxesFold = exports.TransformAccordion = exports.ArrowSelector = exports.PositioningRef = exports.AnnotationRef = exports.AnnotationArrowRef = exports.RangeSelectorAccordion = exports.ImageAccordion = exports.ShapeAccordion = exports.AnnotationAccordion = undefined;

var _PlotlyEditor = __webpack_require__(/*! ./PlotlyEditor */ "MD8t");

var _PlotlyEditor2 = _interopRequireDefault(_PlotlyEditor);

var _DefaultEditor = __webpack_require__(/*! ./DefaultEditor */ "p5Q0");

var _DefaultEditor2 = _interopRequireDefault(_DefaultEditor);

var _EditorControls = __webpack_require__(/*! ./EditorControls */ "i8+h");

var _EditorControls2 = _interopRequireDefault(_EditorControls);

var _lib = __webpack_require__(/*! ./lib */ "RXjw");

var _constants = __webpack_require__(/*! ./lib/constants */ "5Bkx");

var _components = __webpack_require__(/*! ./components */ "yF51");

var _default_panels = __webpack_require__(/*! ./default_panels */ "sHuL");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.AnnotationAccordion = _components.AnnotationAccordion;
exports.ShapeAccordion = _components.ShapeAccordion;
exports.ImageAccordion = _components.ImageAccordion;
exports.RangeSelectorAccordion = _components.RangeSelectorAccordion;
exports.AnnotationArrowRef = _components.AnnotationArrowRef;
exports.AnnotationRef = _components.AnnotationRef;
exports.PositioningRef = _components.PositioningRef;
exports.ArrowSelector = _components.ArrowSelector;
exports.TransformAccordion = _components.TransformAccordion;
exports.AxesFold = _components.AxesFold;
exports.AxesRange = _components.AxesRange;
exports.NTicks = _components.NTicks;
exports.DTicks = _components.DTicks;
exports.DTicksInterval = _components.DTicksInterval;
exports.AxesSelector = _components.AxesSelector;
exports.Button = _components.Button;
exports.ColorPicker = _components.ColorPicker;
exports.PanelMessage = _components.PanelMessage;
exports.ColorwayPicker = _components.ColorwayPicker;
exports.ColorscalePicker = _components.ColorscalePicker;
exports.PieColorscalePicker = _components.PieColorscalePicker;
exports.ContourNumeric = _components.ContourNumeric;
exports.ErrorBars = _components.ErrorBars;
exports.DataSelector = _components.DataSelector;
exports.Dropdown = _components.Dropdown;
exports.Dropzone = _components.Dropzone;
exports.EDITOR_ACTIONS = _constants.EDITOR_ACTIONS;
exports.RangesliderVisible = _components.RangesliderVisible;
exports.Flaglist = _components.Flaglist;
exports.PlotlyFold = _components.PlotlyFold;
exports.Fold = _components.Fold;
exports.FontSelector = _components.FontSelector;
exports.GraphCreatePanel = _default_panels.GraphCreatePanel;
exports.Info = _components.Info;
exports.NumericFraction = _components.NumericFraction;
exports.PositioningNumeric = _components.PositioningNumeric;
exports.NumericFractionInverse = _components.NumericFractionInverse;
exports.LayoutPanel = _components.LayoutPanel;
exports.LayoutSection = _components.LayoutSection;
exports.LineDashSelector = _components.LineDashSelector;
exports.LineShapeSelector = _components.LineShapeSelector;
exports.Numeric = _components.Numeric;
exports.AxisRangeValue = _components.AxisRangeValue;
exports.Text = _components.Text;
exports.PlotlyPanel = _components.PlotlyPanel;
exports.Panel = _components.Panel;
exports.PanelEmpty = _components.PanelEmpty;
exports.PanelMenuWrapper = _components.PanelMenuWrapper;
exports.Radio = _components.Radio;
exports.PlotlySection = _components.PlotlySection;
exports.Section = _components.Section;
exports.SingleSidebarItem = _components.SingleSidebarItem;
exports.GraphTransformsPanel = _default_panels.GraphTransformsPanel;
exports.StyleAxesPanel = _default_panels.StyleAxesPanel;
exports.StyleColorbarsPanel = _default_panels.StyleColorbarsPanel;
exports.StyleLayoutPanel = _default_panels.StyleLayoutPanel;
exports.StyleLegendPanel = _default_panels.StyleLegendPanel;
exports.StyleNotesPanel = _default_panels.StyleNotesPanel;
exports.StyleShapesPanel = _default_panels.StyleShapesPanel;
exports.StyleImagesPanel = _default_panels.StyleImagesPanel;
exports.StyleTracesPanel = _default_panels.StyleTracesPanel;
exports.SymbolSelector = _components.SymbolSelector;
exports.TextEditor = _components.TextEditor;
exports.TraceAccordion = _components.TraceAccordion;
exports.TraceMarkerSection = _components.TraceMarkerSection;
exports.TraceRequiredPanel = _components.TraceRequiredPanel;
exports.TraceSelector = _components.TraceSelector;
exports.connectCartesianSubplotToLayout = _lib.connectCartesianSubplotToLayout;
exports.connectNonCartesianSubplotToLayout = _lib.connectNonCartesianSubplotToLayout;
exports.connectAnnotationToLayout = _lib.connectAnnotationToLayout;
exports.connectShapeToLayout = _lib.connectShapeToLayout;
exports.connectImageToLayout = _lib.connectImageToLayout;
exports.connectAxesToLayout = _lib.connectAxesToLayout;
exports.connectTransformToTrace = _lib.connectTransformToTrace;
exports.connectAggregationToTransform = _lib.connectAggregationToTransform;
exports.connectLayoutToPlot = _lib.connectLayoutToPlot;
exports.connectToContainer = _lib.connectToContainer;
exports.connectRangeSelectorToAxis = _lib.connectRangeSelectorToAxis;
exports.connectTraceToPlot = _lib.connectTraceToPlot;
exports.dereference = _lib.dereference;
exports.localize = _lib.localize;
exports.localizeString = _lib.localizeString;
exports.walkObject = _lib.walkObject;
exports.EditorControls = _EditorControls2.default;
exports.DefaultEditor = _DefaultEditor2.default;
exports.RectanglePositioner = _components.RectanglePositioner;
exports.default = _PlotlyEditor2.default;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ "seXi":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_equalObjects.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getAllKeys = __webpack_require__(/*! ./_getAllKeys */ "qZTm");

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1;

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * 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;
    }
  }
  // Assume cyclic values are equal.
  var stacked = stack.get(object);
  if (stacked && stack.get(other)) {
    return stacked == other;
  }
  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;
}

module.exports = equalObjects;


/***/ }),

/***/ "sgcl":
/*!********************************************************!*\
  !*** ./node_modules/mdi-react/FormatAlignRightIcon.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var FormatAlignRightIcon = function FormatAlignRightIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M3,3H21V5H3V3M9,7H21V9H9V7M3,11H21V13H3V11M9,15H21V17H9V15M3,19H21V21H3V19Z' })
  );
};

module.exports = FormatAlignRightIcon;


/***/ }),

/***/ "shjB":
/*!*****************************************!*\
  !*** ./node_modules/lodash/isLength.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;

/**
 * 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;
}

module.exports = isLength;


/***/ }),

/***/ "siaY":
/*!*************************************************!*\
  !*** ./node_modules/plotlywidget/src/Figure.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var widgets = __webpack_require__(/*! @jupyter-widgets/base */ "Rtm6");
var _ = __webpack_require__(/*! lodash */ "LvDl");

window.PlotlyConfig = {MathJaxConfig: 'local'};
var Plotly = __webpack_require__(/*! plotly.js/dist/plotly.min */ "n9MJ");
var PlotlyIndex = __webpack_require__(/*! plotly.js/src/lib/index */ "NLw+");
var semver_range = "^" + __webpack_require__(/*! ../package.json */ "Ri4F").version;

// Model
// =====
/**
 * A FigureModel holds a mirror copy of the state of a FigureWidget on
 * the Python side.  There is a one-to-one relationship between JavaScript
 * FigureModels and Python FigureWidgets. The JavaScript FigureModel is
 * initialized as soon as a Python FigureWidget initialized, this happens
 * even before the widget is first displayed in the Notebook
 * @type {widgets.DOMWidgetModel}
 */
var FigureModel = widgets.DOMWidgetModel.extend({

    defaults: _.extend(widgets.DOMWidgetModel.prototype.defaults(), {
        // Model metadata
        // --------------
        _model_name: "FigureModel",
        _view_name: "FigureView",
        _model_module: "plotlywidget",
        _view_module: "plotlywidget",
        _view_module_version: semver_range,
        _model_module_version: semver_range,

        // Data and Layout
        // ---------------
        // The _data and _layout properties are synchronized with the
        // Python side on initialization only.  After initialization, these
        // properties are kept in sync through the use of the _py2js_*
        // messages
        _data: [],
        _layout: {},
        _config: {},

        // Python -> JS messages
        // ---------------------
        // Messages are implemented using trait properties. This is done so
        // that we can take advantage of ipywidget's binary serialization
        // protocol.
        //
        // Messages are sent by the Python side by assigning the message
        // contents to the appropriate _py2js_* property, and then immediately
        // setting it to None.  Messages are received by the JavaScript
        // side by registering property change callbacks in the initialize
        // methods for FigureModel and FigureView. e.g. (where this is a
        // FigureModel):
        //
        //      this.on('change:_py2js_addTraces', this.do_addTraces, this);
        //
        // Message handling methods, do_addTraces, are responsible for
        // performing the appropriate action if the message contents are
        // not null

        /**
         * @typedef {null|Object} Py2JsAddTracesMsg
         * @property {Array.<Object>} trace_data
         *  Array of traces to append to the end of the figure's current traces
         * @property {Number} trace_edit_id
         *  Edit ID to use when returning trace deltas using
         *  the _js2py_traceDeltas message.
         * @property {Number} layout_edit_id
         *  Edit ID to use when returning layout deltas using
         *  the _js2py_layoutDelta message.
         */
        _py2js_addTraces: null,

        /**
         * @typedef {null|Object} Py2JsDeleteTracesMsg
         * @property {Array.<Number>} delete_inds
         *  Array of indexes of traces to be deleted, in ascending order
         * @property {Number} trace_edit_id
         *  Edit ID to use when returning trace deltas using
         *  the _js2py_traceDeltas message.
         * @property {Number} layout_edit_id
         *  Edit ID to use when returning layout deltas using
         *  the _js2py_layoutDelta message.
         */
        _py2js_deleteTraces: null,

        /**
         * @typedef {null|Object} Py2JsMoveTracesMsg
         * @property {Array.<Number>} current_trace_inds
         *  Array of the current indexes of traces to be moved
         * @property {Array.<Number>} new_trace_inds
         *  Array of the new indexes that traces should be moved to.
         */
        _py2js_moveTraces: null,


        /**
         * @typedef {null|Object} Py2JsRestyleMsg
         * @property {Object} restyle_data
         *  Restyle data as accepted by Plotly.restyle
         * @property {null|Array.<Number>} restyle_traces
         *  Array of indexes of the traces that the resytle operation applies
         *  to, or null to apply the operation to all traces
         * @property {Number} trace_edit_id
         *  Edit ID to use when returning trace deltas using
         *  the _js2py_traceDeltas message
         * @property {Number} layout_edit_id
         *  Edit ID to use when returning layout deltas using
         *  the _js2py_layoutDelta message
         * @property {null|String} source_view_id
         *  view_id of the FigureView that triggered the original restyle
         *  event (e.g. by clicking the legend), or null if the restyle was
         *  triggered from Python
         */
        _py2js_restyle: null,

        /**
         * @typedef {null|Object} Py2JsRelayoutMsg
         * @property {Object} relayout_data
         *  Relayout data as accepted by Plotly.relayout
         * @property {Number} layout_edit_id
         *  Edit ID to use when returning layout deltas using
         *  the _js2py_layoutDelta message
         * @property {null|String} source_view_id
         *  view_id of the FigureView that triggered the original relayout
         *  event (e.g. by clicking the zoom button), or null if the
         *  relayout was triggered from Python
         */
        _py2js_relayout: null,

        /**
         * @typedef {null|Object} Py2JsUpdateMsg
         * @property {Object} style_data
         *  Style data as accepted by Plotly.update
         * @property {Object} layout_data
         *  Layout data as accepted by Plotly.update
         * @property {Array.<Number>} style_traces
         *  Array of indexes of the traces that the update operation applies
         *  to, or null to apply the operation to all traces
         * @property {Number} trace_edit_id
         *  Edit ID to use when returning trace deltas using
         *  the _js2py_traceDeltas message
         * @property {Number} layout_edit_id
         *  Edit ID to use when returning layout deltas using
         *  the _js2py_layoutDelta message
         * @property {null|String} source_view_id
         *  view_id of the FigureView that triggered the original update
         *  event (e.g. by clicking a button), or null if the update was
         *  triggered from Python
         */
        _py2js_update: null,

        /**
         * @typedef {null|Object} Py2JsAnimateMsg
         * @property {Object} style_data
         *  Style data as accepted by Plotly.animate
         * @property {Object} layout_data
         *  Layout data as accepted by Plotly.animate
         * @property {Array.<Number>} style_traces
         *  Array of indexes of the traces that the animate operation applies
         *  to, or null to apply the operation to all traces
         * @property {Object} animation_opts
         *  Animation options as accepted by Plotly.animate
         * @property {Number} trace_edit_id
         *  Edit ID to use when returning trace deltas using
         *  the _js2py_traceDeltas message
         * @property {Number} layout_edit_id
         *  Edit ID to use when returning layout deltas using
         *  the _js2py_layoutDelta message
         * @property {null|String} source_view_id
         *  view_id of the FigureView that triggered the original animate
         *  event (e.g. by clicking a button), or null if the update was
         *  triggered from Python
         */
        _py2js_animate: null,

        /**
         * @typedef {null|Object} Py2JsRemoveLayoutPropsMsg
         * @property {Array.<Array.<String|Number>>} remove_props
         *  Array of property paths to remove. Each propery path is an
         *  array of property names or array indexes that locate a property
         *  inside the _layout object
         */
        _py2js_removeLayoutProps: null,

        /**
         * @typedef {null|Object} Py2JsRemoveTracePropsMsg
         * @property {Number} remove_trace
         *  The index of the trace from which to remove properties
         * @property {Array.<Array.<String|Number>>} remove_props
         *  Array of property paths to remove. Each propery path is an
         *  array of property names or array indexes that locate a property
         *  inside the _data[remove_trace] object
         */
        _py2js_removeTraceProps: null,


        // JS -> Python messages
        // ---------------------
        // Messages are sent by the JavaScript side by assigning the
        // message contents to the appropriate _js2py_* property and then
        // calling the `touch` method on the view that triggered the
        // change. e.g. (where this is a FigureView):
        //
        //      this.model.set('_js2py_restyle', data);
        //      this.touch();
        //
        // The Python side is responsible for setting the property to None
        // after receiving the message.
        //
        // Message trigger logic is described in the corresponding
        // handle_plotly_* methods of FigureView

        /**
         * @typedef {null|Object} Js2PyRestyleMsg
         * @property {Object} style_data
         *  Style data that was passed to Plotly.restyle
         * @property {Array.<Number>} style_traces
         *  Array of indexes of the traces that the restyle operation
         *  was applied to, or null if applied to all traces
         * @property {String} source_view_id
         *  view_id of the FigureView that triggered the original restyle
         *  event (e.g. by clicking the legend)
         */
        _js2py_restyle: null,

        /**
         * @typedef {null|Object} Js2PyRelayoutMsg
         * @property {Object} relayout_data
         *  Relayout data that was passed to Plotly.relayout
         * @property {String} source_view_id
         *  view_id of the FigureView that triggered the original relayout
         *  event (e.g. by clicking the zoom button)
         */
        _js2py_relayout: null,

        /**
         * @typedef {null|Object} Js2PyUpdateMsg
         * @property {Object} style_data
         *  Style data that was passed to Plotly.update
         * @property {Object} layout_data
         *  Layout data that was passed to Plotly.update
         * @property {Array.<Number>} style_traces
         *  Array of indexes of the traces that the update operation applied
         *  to, or null if applied to all traces
         * @property {String} source_view_id
         *  view_id of the FigureView that triggered the original relayout
         *  event (e.g. by clicking the zoom button)
         */
        _js2py_update: null,

        /**
         * @typedef {null|Object} Js2PyLayoutDeltaMsg
         * @property {Object} layout_delta
         *  The layout delta object that contains all of the properties of
         *  _fullLayout that are not identical to those in the
         *  FigureModel's _layout property
         * @property {Number} layout_edit_id
         *  Edit ID of message that triggered the creation of layout delta
         */
        _js2py_layoutDelta: null,

        /**
         * @typedef {null|Object} Js2PyTraceDeltasMsg
         * @property {Array.<Object>} trace_deltas
         *  Array of trace delta objects. Each trace delta contains the
         *  trace's uid along with all of the properties of _fullData that
         *  are not identical to those in the FigureModel's _data property
         * @property {Number} trace_edit_id
         *  Edit ID of message that triggered the creation of trace deltas
         */
        _js2py_traceDeltas: null,


        /**
         * Object representing a collection of points for use in click, hover,
         * and selection events
         * @typedef {Object} Points
         * @property {Array.<Number>} trace_indexes
         *  Array of the trace index for each point
         * @property {Array.<Number>} point_indexes
         *  Array of the index of each point in its own trace
         * @property {null|Array.<Number>} xs
         *  Array of the x coordinate of each point (for cartesian trace types)
         *  or null (for non-cartesian trace types)
         * @property {null|Array.<Number>} ys
         *  Array of the y coordinate of each point (for cartesian trace types)
         *  or null (for non-cartesian trace types
         * @property {null|Array.<Number>} zs
         *  Array of the z coordinate of each point (for 3D cartesian
         *  trace types)
         *  or null (for non-3D-cartesian trace types)
         */

        /**
         * Object representing the state of the input devices during a
         * plotly event
         * @typedef {Object} InputDeviceState
         * @property {boolean} alt - true if alt key pressed,
         * false otherwise
         * @property {boolean} ctrl - true if ctrl key pressed,
         * false otherwise
         * @property {boolean} meta - true if meta key pressed,
         * false otherwise
         * @property {boolean} shift - true if shift key pressed,
         * false otherwise
         *
         * @property {boolean} button
         *  Indicates which button was pressed on the mouse to trigger the
         *  event.
         *    0: Main button pressed, usually the left button or the
         *       un-initialized state
         *    1: Auxiliary button pressed, usually the wheel button or
         *       the middle button (if present)
         *    2: Secondary button pressed, usually the right button
         *    3: Fourth button, typically the Browser Back button
         *    4: Fifth button, typically the Browser Forward button
         *
         * @property {boolean} buttons
         *  Indicates which buttons were pressed on the mouse when the event
         *  is triggered.
         *    0  : No button or un-initialized
         *    1  : Primary button (usually left)
         *    2  : Secondary button (usually right)
         *    4  : Auxilary button (usually middle or mouse wheel button)
         *    8  : 4th button (typically the "Browser Back" button)
         *    16 : 5th button (typically the "Browser Forward" button)
         *
         *  Combinations of buttons are represented by the sum of the codes
         *  above. e.g. a value of 7 indicates buttons 1 (primary),
         *  2 (secondary), and 4 (auxilary) were pressed during the event
         */

        /**
         * @typedef {Object} BoxSelectorState
         * @property {Array.<Number>} xrange
         *  Two element array containing the x-range of the box selection
         * @property {Array.<Number>} yrange
         *  Two element array containing the y-range of the box selection
         */

        /**
         * @typedef {Object} LassoSelectorState
         * @property {Array.<Number>} xs
         *  Array of the x-coordinates of the lasso selection region
         * @property {Array.<Number>} ys
         *  Array of the y-coordinates of the lasso selection region
         */

        /**
         * Object representing the state of the selection tool during a
         * plotly_select event
         * @typedef {Object} Selector
         * @property {String} type
         *  Selection type. One of: 'box', or 'lasso'
         * @property {BoxSelectorState|LassoSelectorState} selector_state
         */

        /**
         * @typedef {null|Object} Js2PyPointsCallbackMsg
         * @property {string} event_type
         *  Name of the triggering event. One of 'plotly_click',
         *  'plotly_hover', 'plotly_unhover', or 'plotly_selected'
         * @property {null|Points} points
         *  Points object for event
         * @property {null|InputDeviceState} device_state
         *  InputDeviceState object for event
         * @property {null|Selector} selector
         *  State of the selection tool for 'plotly_selected' events, null
         *  for other event types
         */
        _js2py_pointsCallback: null,

        // Message tracking
        // ----------------
        /**
         * @type {Number}
         * layout_edit_id of the last layout modification operation
         * requested by the Python side
         */
        _last_layout_edit_id: 0,

        /**
         * @type {Number}
         * trace_edit_id of the last trace modification operation
         * requested by the Python side
         */
        _last_trace_edit_id: 0
    }),

    /**
     * Initialize FigureModel. Called when the Python FigureWidget is first
     * constructed
     */
    initialize: function() {
        FigureModel.__super__.initialize.apply(this, arguments);

        this.on("change:_data", this.do_data, this);
        this.on("change:_layout", this.do_layout, this);
        this.on("change:_py2js_addTraces", this.do_addTraces, this);
        this.on("change:_py2js_deleteTraces", this.do_deleteTraces, this);
        this.on("change:_py2js_moveTraces", this.do_moveTraces, this);
        this.on("change:_py2js_restyle", this.do_restyle, this);
        this.on("change:_py2js_relayout", this.do_relayout, this);
        this.on("change:_py2js_update", this.do_update, this);
        this.on("change:_py2js_animate", this.do_animate, this);
        this.on("change:_py2js_removeLayoutProps",
            this.do_removeLayoutProps, this);
        this.on("change:_py2js_removeTraceProps",
            this.do_removeTraceProps, this);
    },

    /**
     * Input a trace index specification and return an Array of trace
     * indexes where:
     *
     *  - null|undefined -> Array of all traces
     *  - Trace index as Number -> Single element array of input index
     *  - Array of trace indexes -> Input array unchanged
     *
     * @param {undefined|null|Number|Array.<Number>} trace_indexes
     * @returns {Array.<Number>}
     *  Array of trace indexes
     * @private
     */
    _normalize_trace_indexes: function (trace_indexes) {
        if (trace_indexes === null || trace_indexes === undefined) {
            var numTraces = this.get("_data").length;
            trace_indexes = _.range(numTraces);
        }
        if (!Array.isArray(trace_indexes)) {
            // Make sure idx is an array
            trace_indexes = [trace_indexes];
        }
        return trace_indexes
    },

    /**
     * Log changes to the _data trait
     *
     * This should only happed on FigureModel initialization
     */
    do_data: function () {

    },

    /**
     * Log changes to the _layout trait
     *
     * This should only happed on FigureModel initialization
     */
    do_layout: function () {

    },

    /**
     * Handle addTraces message
     */
    do_addTraces: function () {
        // add trace to plot
        /** @type {Py2JsAddTracesMsg} */
        var msgData = this.get("_py2js_addTraces");

        if (msgData !== null) {
            var currentTraces = this.get("_data");
            var newTraces = msgData.trace_data;
            _.forEach(newTraces, function (newTrace) {
                currentTraces.push(newTrace);
            })
        }
    },

    /**
     * Handle deleteTraces message
     */
    do_deleteTraces: function () {
        // remove traces from plot

        /** @type {Py2JsDeleteTracesMsg} */
        var msgData = this.get("_py2js_deleteTraces");

        if (msgData !== null) {
            var delete_inds = msgData.delete_inds;
            var tracesData = this.get("_data");

            // Remove del inds in reverse order so indexes remain valid
            // throughout loop
            delete_inds.slice().reverse().forEach(function (del_ind) {
                tracesData.splice(del_ind, 1);
            });
        }
    },

    /**
     * Handle moveTraces message
     */
    do_moveTraces: function () {

        /** @type {Py2JsMoveTracesMsg} */
        var msgData = this.get("_py2js_moveTraces");

        if (msgData !== null) {
            var tracesData = this.get("_data");
            var currentInds = msgData.current_trace_inds;
            var newInds = msgData.new_trace_inds;

            performMoveTracesLike(tracesData, currentInds, newInds);
        }
    },

    /**
     * Handle restyle message
     */
    do_restyle: function () {

        /** @type {Py2JsRestyleMsg} */
        var msgData = this.get("_py2js_restyle");
        if (msgData !== null) {
            var restyleData = msgData.restyle_data;
            var restyleTraces = this._normalize_trace_indexes(
                msgData.restyle_traces);
            performRestyleLike(this.get("_data"), restyleData, restyleTraces);
        }
    },

    /**
     * Handle relayout message
     */
    do_relayout: function () {

        /** @type {Py2JsRelayoutMsg} */
        var msgData = this.get("_py2js_relayout");

        if (msgData !== null) {
            performRelayoutLike(this.get("_layout"), msgData.relayout_data);
        }
    },

    /**
     * Handle update message
     */
    do_update: function() {

        /** @type {Py2JsUpdateMsg} */
        var msgData = this.get("_py2js_update");

        if (msgData !== null) {
            var style = msgData.style_data;
            var layout = msgData.layout_data;
            var styleTraces = this._normalize_trace_indexes(
                msgData.style_traces);
            performRestyleLike(this.get("_data"), style, styleTraces);
            performRelayoutLike(this.get("_layout"), layout);
        }
    },

    /**
     * Handle animate message
     */
    do_animate: function () {

        /** @type {Py2JsAnimateMsg} */
        var msgData = this.get("_py2js_animate");
        if (msgData !== null) {

            var styles = msgData.style_data;
            var layout = msgData.layout_data;
            var trace_indexes = this._normalize_trace_indexes(
                msgData.style_traces);

            for (var i = 0; i < styles.length; i++) {
                var style = styles[i];
                var trace_index = trace_indexes[i];
                var trace = this.get("_data")[trace_index];
                performRelayoutLike(trace, style);
            }

            performRelayoutLike(this.get("_layout"), layout);
        }
    },

    /**
     * Handle removeLayoutProps message
     */
    do_removeLayoutProps: function () {
        /** @type {Py2JsRemoveLayoutPropsMsg} */
        var msgData = this.get("_py2js_removeLayoutProps");

        if (msgData !== null) {
            var keyPaths = msgData.remove_props;
            var layout = this.get("_layout");
            performRemoveProps(layout, keyPaths);
        }
    },

    /**
     * Handle removeTraceProps message
     */
    do_removeTraceProps: function () {
        /** @type {Py2JsRemoveTracePropsMsg} */
        var msgData = this.get("_py2js_removeTraceProps");
        if (msgData !== null) {
            var keyPaths = msgData.remove_props;
            var traceIndex = msgData.remove_trace;
            var trace = this.get("_data")[traceIndex];

            performRemoveProps(trace, keyPaths);
        }
    }
}, {
    serializers: _.extend({
        _data: { deserialize: py2js_deserializer,
            serialize: js2py_serializer},
        _layout: { deserialize: py2js_deserializer,
            serialize: js2py_serializer},
        _py2js_addTraces: { deserialize: py2js_deserializer,
            serialize: js2py_serializer},
        _py2js_deleteTraces: { deserialize: py2js_deserializer,
            serialize: js2py_serializer},
        _py2js_moveTraces: { deserialize: py2js_deserializer,
            serialize: js2py_serializer},
        _py2js_restyle: { deserialize: py2js_deserializer,
            serialize: js2py_serializer},
        _py2js_relayout: { deserialize: py2js_deserializer,
            serialize: js2py_serializer},
        _py2js_update: { deserialize: py2js_deserializer,
            serialize: js2py_serializer},
        _py2js_animate: { deserialize: py2js_deserializer,
            serialize: js2py_serializer},
        _py2js_removeLayoutProps: { deserialize: py2js_deserializer,
            serialize: js2py_serializer},
        _py2js_removeTraceProps: { deserialize: py2js_deserializer,
            serialize: js2py_serializer},
        _js2py_restyle: { deserialize: py2js_deserializer,
            serialize: js2py_serializer},
        _js2py_relayout: { deserialize: py2js_deserializer,
            serialize: js2py_serializer},
        _js2py_update: { deserialize: py2js_deserializer,
            serialize: js2py_serializer},
        _js2py_layoutDelta: { deserialize: py2js_deserializer,
            serialize: js2py_serializer},
        _js2py_traceDeltas: { deserialize: py2js_deserializer,
            serialize: js2py_serializer},
        _js2py_pointsCallback: { deserialize: py2js_deserializer,
            serialize: js2py_serializer}
    }, widgets.DOMWidgetModel.serializers)
});

// View
// ====
/**
 * A FigureView manages the visual presentation of a single Plotly.js
 * figure for a single notebook output cell. Each FigureView has a
 * reference to FigureModel.  Multiple views may share a single model
 * instance, as is the case when a Python FigureWidget is displayed in
 * multiple notebook output cells.
 *
 * @type {widgets.DOMWidgetView}
 */
var FigureView = widgets.DOMWidgetView.extend({

    /**
     * The perform_render method is called by processPhosphorMessage
     * after the widget's DOM element has been attached to the notebook
     * output cell. This happens after the initialize of the
     * FigureModel, and it won't happen at all if the Python FigureWidget
     * is never displayed in a notebook output cell
     */
    perform_render: function() {

        var that = this;

        // Wire up message property callbacks
        // ----------------------------------
        // Python -> JS event properties
        this.model.on("change:_py2js_addTraces",
            this.do_addTraces, this);
        this.model.on("change:_py2js_deleteTraces",
            this.do_deleteTraces, this);
        this.model.on("change:_py2js_moveTraces",
            this.do_moveTraces, this);
        this.model.on("change:_py2js_restyle",
            this.do_restyle, this);
        this.model.on("change:_py2js_relayout",
            this.do_relayout, this);
        this.model.on("change:_py2js_update",
            this.do_update, this);
        this.model.on("change:_py2js_animate",
            this.do_animate, this);

        // MathJax configuration
        // ---------------------
        if (window.MathJax) {
            MathJax.Hub.Config({SVG: {font: "STIX-Web"}});
        }

        // Get message ids
        // ---------------------
        var layout_edit_id = this.model.get("_last_layout_edit_id");
        var trace_edit_id = this.model.get("_last_trace_edit_id");

        // Set view UID
        // ------------
        this.viewID = PlotlyIndex.randstr();

        // Initialize Plotly.js figure
        // ---------------------------
        // We must clone the model's data and layout properties so that
        // the model is not directly mutated by the Plotly.js library.
        var initialTraces = _.cloneDeep(this.model.get("_data"));
        var initialLayout = _.cloneDeep(this.model.get("_layout"));
        var config = this.model.get("_config");

        Plotly.newPlot(that.el, initialTraces, initialLayout, config).then(
            function () {

                // ### Send trace deltas ###
                // We create an array of deltas corresponding to the new
                // traces.
                that._sendTraceDeltas(trace_edit_id);

                // ### Send layout delta ###
                that._sendLayoutDelta(layout_edit_id);

                // Wire up plotly event callbacks
                that.el.on("plotly_restyle",
                    function (update) {
                        that.handle_plotly_restyle(update)
                    });
                that.el.on("plotly_relayout",
                    function (update) {
                        that.handle_plotly_relayout(update)
                    });
                that.el.on("plotly_update",
                    function (update) {
                        that.handle_plotly_update(update)
                    });
                that.el.on("plotly_click",
                    function (update) {
                        that.handle_plotly_click(update)
                    });
                that.el.on("plotly_hover",
                    function (update) {
                        that.handle_plotly_hover(update)
                    });
                that.el.on("plotly_unhover",
                    function (update) {
                        that.handle_plotly_unhover(update)
                    });
                that.el.on("plotly_selected",
                    function (update) {
                        that.handle_plotly_selected(update)
                    });
                that.el.on("plotly_doubleclick",
                    function (update) {
                        that.handle_plotly_doubleclick(update)
                    });

                // Emit event indicating that the widget has finished
                // rendering
                var event = new CustomEvent("plotlywidget-after-render",
                    { "detail": {"element": that.el, 'viewID': that.viewID}});

                // Dispatch/Trigger/Fire the event
                document.dispatchEvent(event);
            });
    },

    /**
     * Respond to phosphorjs events
     */
    processPhosphorMessage: function(msg) {
        FigureView.__super__.processPhosphorMessage.apply(this, arguments);
        var that = this;
        switch (msg.type) {
            case 'before-attach':
                // Render an initial empty figure. This establishes with
                // the page that the element will not be empty, avoiding
                // some occasions where the dynamic sizing behavior leads
                // to collapsed figure dimensions.
                var axisHidden = {
                    showgrid: false, showline: false, tickvals: []};

                Plotly.newPlot(that.el, [], {
                    xaxis: axisHidden, yaxis: axisHidden
                });

                window.addEventListener("resize", function(){
                    that.autosizeFigure();
                });
                break;
            case 'after-attach':
                // Rendering actual figure in the after-attach event allows
                // Plotly.js to size the figure to fill the available element
                this.perform_render();
                break;
            case 'resize':
                this.autosizeFigure();
                break
        }
    },

    autosizeFigure: function() {
        var that = this;
        var layout = that.model.get('_layout');
        if (_.isNil(layout) ||
            _.isNil(layout.width)) {
            Plotly.Plots.resize(that.el).then(function(){
                var layout_edit_id = that.model.get(
                    "_last_layout_edit_id");
                that._sendLayoutDelta(layout_edit_id);
            });
        }
    },

    /**
     * Purge Plotly.js data structures from the notebook output display
     * element when the view is destroyed
     */
    destroy: function() {
        Plotly.purge(this.el);
    },

    /**
     * Return the figure's _fullData array merged with its data array
     *
     * The merge ensures that for any properties that el._fullData and
     * el.data have in common, we return the version from el.data
     *
     * Named colorscales are one example of why this is needed. The el.data
     * array will hold named colorscale strings (e.g. 'Viridis'), while the
     * el._fullData array will hold the actual colorscale array. e.g.
     *
     *      el.data[0].marker.colorscale == 'Viridis' but
     *      el._fullData[0].marker.colorscale = [[..., ...], ...]
     *
     * Performing the merge allows our FigureModel to retain the 'Viridis'
     * string, rather than having it overridded by the colorscale array.
     *
     */
    getFullData: function () {
        return _.mergeWith({}, this.el._fullData, this.el.data,
            fullMergeCustomizer)
    },

    /**
     * Return the figure's _fullLayout object merged with its layout object
     *
     * See getFullData documentation for discussion of why the merge is
     * necessary
     */
    getFullLayout: function () {
        return _.mergeWith({}, this.el._fullLayout, this.el.layout,
            fullMergeCustomizer);
    },

    /**
     * Build Points data structure from data supplied by the plotly_click,
     * plotly_hover, or plotly_select events
     * @param {Object} data
     * @returns {null|Points}
     */
    buildPointsObject: function (data) {

        var pointsObject;
        if (data.hasOwnProperty("points")) {
            // Most cartesian plots
            var pointObjects = data["points"];
            var numPoints = pointObjects.length;
            pointsObject = {
                "trace_indexes": new Array(numPoints),
                "point_indexes": new Array(numPoints),
                "xs": new Array(numPoints),
                "ys": new Array(numPoints)};


                for (var p = 0; p < numPoints; p++) {
                pointsObject["trace_indexes"][p] =
                    pointObjects[p]["curveNumber"];
                pointsObject["point_indexes"][p] =
                    pointObjects[p]["pointNumber"];
                pointsObject["xs"][p] =
                    pointObjects[p]["x"];
                pointsObject["ys"][p] =
                    pointObjects[p]["y"];
            }

            // Add z if present
            var hasZ = pointObjects[0] !==
                undefined && pointObjects[0].hasOwnProperty("z");
            if (hasZ) {
                pointsObject["zs"] = new Array(numPoints);
                for (p = 0; p < numPoints; p++) {
                    pointsObject["zs"][p] = pointObjects[p]["z"];
                }
            }

            return pointsObject
        } else {
            return null
        }
    },

    /**
     * Build InputDeviceState data structure from data supplied by the
     * plotly_click, plotly_hover, or plotly_select events
     * @param {Object} data
     * @returns {null|InputDeviceState}
     */
    buildInputDeviceStateObject: function (data) {
        var event = data["event"];
        if (event === undefined) {
            return null;
        } else {
            /** @type {InputDeviceState} */
            var inputDeviceState = {
                // Keyboard modifiers
                "alt": event["altKey"],
                "ctrl": event["ctrlKey"],
                "meta": event["metaKey"],
                "shift": event["shiftKey"],

                // Mouse buttons
                "button": event["button"],
                "buttons": event["buttons"]
            };
            return inputDeviceState
        }
    },

    /**
     * Build Selector data structure from data supplied by the
     * plotly_select event
     * @param data
     * @returns {null|Selector}
     */
    buildSelectorObject: function(data) {

        var selectorObject;

        if (data.hasOwnProperty("range")) {
            // Box selection
            selectorObject = {
                type: "box",
                selector_state: {
                    xrange: data["range"]["x"],
                    yrange: data["range"]["y"]
                }
            };
        } else if (data.hasOwnProperty("lassoPoints")) {
            // Lasso selection
            selectorObject = {
                type: "lasso",
                selector_state: {
                    xs: data["lassoPoints"]["x"],
                    ys: data["lassoPoints"]["y"]
                }
            };
        } else {
            selectorObject = null;
        }
        return selectorObject
    },

    /**
     * Handle ploty_restyle events emitted by the Plotly.js library
     * @param data
     */
    handle_plotly_restyle: function (data) {

        if (data === null || data === undefined) {
            // No data to report to the Python side
            return
        }

        if (data[0] && data[0].hasOwnProperty("_doNotReportToPy")) {
            // Restyle originated on the Python side
            return
        }

        // Unpack data
        var styleData = data[0];
        var styleTraces = data[1];

        // Construct restyle message to send to the Python side
        /** @type {Js2PyRestyleMsg} */
        var restyleMsg = {
            style_data: styleData,
            style_traces: styleTraces,
            source_view_id: this.viewID
        };

        this.model.set("_js2py_restyle", restyleMsg);
        this.touch();
    },

    /**
     * Handle plotly_relayout events emitted by the Plotly.js library
     * @param data
     */
    handle_plotly_relayout: function (data) {

        if (data === null || data === undefined) {
            // No data to report to the Python side
            return
        }

        if (data.hasOwnProperty("_doNotReportToPy")) {
            // Relayout originated on the Python side
            return
        }

        /** @type {Js2PyRelayoutMsg} */
        var relayoutMsg = {
            relayout_data: data,
            source_view_id: this.viewID
        };

        this.model.set("_js2py_relayout", relayoutMsg);
        this.touch();
    },

    /**
     * Handle plotly_update events emitted by the Plotly.js library
     * @param data
     */
    handle_plotly_update: function (data) {

        if (data === null || data === undefined) {
            // No data to report to the Python side
            return
        }

        if (data["data"] &&
            data["data"][0].hasOwnProperty("_doNotReportToPy")) {
            // Update originated on the Python side
            return
        }

        /** @type {Js2PyUpdateMsg} */
        var updateMsg = {
            style_data: data["data"][0],
            style_traces: data["data"][1],
            layout_data: data["layout"],
            source_view_id: this.viewID
        };

        // Log message
        this.model.set("_js2py_update", updateMsg);
        this.touch();
    },

    /**
     * Handle plotly_click events emitted by the Plotly.js library
     * @param data
     */
    handle_plotly_click: function (data) {
        this._send_points_callback_message(data, "plotly_click");
    },

    /**
     * Handle plotly_hover events emitted by the Plotly.js library
     * @param data
     */
    handle_plotly_hover: function (data) {
        this._send_points_callback_message(data, "plotly_hover");
    },

    /**
     * Handle plotly_unhover events emitted by the Plotly.js library
     * @param data
     */
    handle_plotly_unhover: function (data) {
        this._send_points_callback_message(data, "plotly_unhover");
    },

    /**
     * Handle plotly_selected events emitted by the Plotly.js library
     * @param data
     */
    handle_plotly_selected: function (data) {
        this._send_points_callback_message(data, "plotly_selected");
    },

    /**
     * Build and send a points callback message to the Python side
     *
     * @param {Object} data
     *  data object as provided by the plotly_click, plotly_hover,
     *  plotly_unhover, or plotly_selected events
     * @param {String} event_type
     *  Name of the triggering event. One of 'plotly_click',
     *  'plotly_hover', 'plotly_unhover', or 'plotly_selected'
     * @private
     */
    _send_points_callback_message: function (data, event_type) {
        if (data === null || data === undefined) {
            // No data to report to the Python side
            return;
        }

        /** @type {Js2PyPointsCallbackMsg} */
        var pointsMsg = {
            event_type: event_type,
            points: this.buildPointsObject(data),
            device_state: this.buildInputDeviceStateObject(data),
            selector: this.buildSelectorObject(data)
        };

        if (pointsMsg["points"] !== null &&
            pointsMsg["points"] !== undefined) {

            this.model.set("_js2py_pointsCallback", pointsMsg);
            this.touch();
        }
    },

    /**
     * Stub for future handling of plotly_doubleclick
     * @param data
     */
    handle_plotly_doubleclick: function (data) {},


    /**
     * Handle Plotly.addTraces request
     */
    do_addTraces: function () {

        /** @type {Py2JsAddTracesMsg} */
        var msgData = this.model.get("_py2js_addTraces");

        if (msgData !== null) {

            // Save off original number of traces
            var prevNumTraces = this.el.data.length;

            var that = this;
            Plotly.addTraces(this.el, msgData.trace_data).then(function () {

                // ### Send trace deltas ###
                that._sendTraceDeltas(msgData.trace_edit_id);

                // ### Send layout delta ###
                var layout_edit_id = msgData.layout_edit_id;
                that._sendLayoutDelta(layout_edit_id);
            });
        }
    },

    /**
     * Handle Plotly.deleteTraces request
     */
    do_deleteTraces: function () {

        /** @type {Py2JsDeleteTracesMsg} */
        var msgData = this.model.get("_py2js_deleteTraces");

        if (msgData  !== null){
            var delete_inds = msgData.delete_inds;
            var that = this;
            Plotly.deleteTraces(this.el, delete_inds).then(function () {

                // ### Send trace deltas ###
                var trace_edit_id = msgData.trace_edit_id;
                that._sendTraceDeltas(trace_edit_id);

                // ### Send layout delta ###
                var layout_edit_id = msgData.layout_edit_id;
                that._sendLayoutDelta(layout_edit_id);
            });
        }
    },

    /**
     * Handle Plotly.moveTraces request
     */
    do_moveTraces: function () {

        /** @type {Py2JsMoveTracesMsg} */
        var msgData = this.model.get("_py2js_moveTraces");

        if (msgData !== null){
            // Unpack message
            var currentInds = msgData.current_trace_inds;
            var newInds = msgData.new_trace_inds;

            // Check if the new trace indexes are actually different than
            // the current indexes
            var inds_equal = _.isEqual(currentInds, newInds);

            if (!inds_equal) {
                Plotly.moveTraces(this.el, currentInds, newInds)
            }
        }
    },

    /**
     * Handle Plotly.restyle request
     */
    do_restyle: function () {

        /** @type {Py2JsRestyleMsg} */
        var msgData = this.model.get("_py2js_restyle");
        if (msgData !== null) {
            var restyleData = msgData.restyle_data;
            var traceIndexes = this.model._normalize_trace_indexes(
                msgData.restyle_traces);

            restyleData["_doNotReportToPy"] = true;
            Plotly.restyle(this.el, restyleData, traceIndexes);

            // ### Send trace deltas ###
            // We create an array of deltas corresponding to the restyled
            // traces.
            this._sendTraceDeltas(msgData.trace_edit_id);

            // ### Send layout delta ###
            var layout_edit_id = msgData.layout_edit_id;
            this._sendLayoutDelta(layout_edit_id);
        }
    },

    /**
     * Handle Plotly.relayout request
     */
    do_relayout: function () {

        /** @type {Py2JsRelayoutMsg} */
        var msgData = this.model.get("_py2js_relayout");
        if (msgData !== null) {
            if (msgData.source_view_id !== this.viewID) {
                var relayoutData = msgData.relayout_data;
                relayoutData["_doNotReportToPy"] = true;
                Plotly.relayout(this.el, msgData.relayout_data);
            }

            // ### Send layout delta ###
            var layout_edit_id = msgData.layout_edit_id;
            this._sendLayoutDelta(layout_edit_id);
        }
    },

    /**
     * Handle Plotly.update request
     */
    do_update: function () {

        /** @type {Py2JsUpdateMsg} */
        var msgData = this.model.get("_py2js_update");

        if (msgData !== null) {
            var style = msgData.style_data || {};
            var layout = msgData.layout_data || {};
            var traceIndexes = this.model._normalize_trace_indexes(
                msgData.style_traces);

            style["_doNotReportToPy"] = true;
                Plotly.update(this.el, style, layout, traceIndexes);

            // ### Send trace deltas ###
            // We create an array of deltas corresponding to the updated
            // traces.
            this._sendTraceDeltas(msgData.trace_edit_id);

            // ### Send layout delta ###
            var layout_edit_id = msgData.layout_edit_id;
            this._sendLayoutDelta(layout_edit_id);
        }
    },

    /**
     * Handle Plotly.animate request
     */
    do_animate: function() {

        /** @type {Py2JsAnimateMsg} */
        var msgData = this.model.get("_py2js_animate");

        if (msgData !== null) {

            // Unpack params
            // var animationData = msgData[0];
            var animationOpts = msgData.animation_opts;

            var styles = msgData.style_data;
            var layout = msgData.layout_data;
            var traceIndexes = this.model._normalize_trace_indexes(
                msgData.style_traces);

            var animationData = {
                data: styles,
                layout: layout,
                traces: traceIndexes
            };

            animationData["_doNotReportToPy"] = true;
            var that = this;

            Plotly.animate(this.el, animationData, animationOpts).then(
                function () {

                    // ### Send trace deltas ###
                    // We create an array of deltas corresponding to the
                    // animated traces.
                    that._sendTraceDeltas(msgData.trace_edit_id);

                    // ### Send layout delta ###
                    var layout_edit_id = msgData.layout_edit_id;
                    that._sendLayoutDelta(layout_edit_id);
                });

        }
    },

    /**
     * Construct layout delta object and send layoutDelta message to the
     * Python side
     *
     * @param layout_edit_id
     *  Edit ID of message that triggered the creation of the layout delta
     * @private
     */
    _sendLayoutDelta: function(layout_edit_id) {
        // ### Handle layout delta ###
        var layout_delta = createDeltaObject(
            this.getFullLayout(),
            this.model.get("_layout"));

        /** @type{Js2PyLayoutDeltaMsg} */
        var layoutDeltaMsg = {
            layout_delta: layout_delta,
            layout_edit_id: layout_edit_id};

        this.model.set("_js2py_layoutDelta", layoutDeltaMsg);
        this.touch();
    },

    /**
     * Construct trace deltas array for the requested trace indexes and
     * send traceDeltas message to the Python side
     *  Array of indexes of traces for which to compute deltas
     * @param trace_edit_id
     *  Edit ID of message that triggered the creation of trace deltas
     * @private
     */
    _sendTraceDeltas: function (trace_edit_id) {

        var trace_data = this.model.get("_data");
        var traceIndexes = _.range(trace_data.length);
        var trace_deltas = new Array(traceIndexes.length);

        var fullData = this.getFullData();
        for (var i = 0; i < traceIndexes.length; i++) {
            var traceInd = traceIndexes[i];
            trace_deltas[i] = createDeltaObject(
                fullData[traceInd], trace_data[traceInd]);
        }

        /** @type{Js2PyTraceDeltasMsg} */
        var traceDeltasMsg = {
            trace_deltas: trace_deltas,
            trace_edit_id: trace_edit_id};

        this.model.set("_js2py_traceDeltas", traceDeltasMsg);
        this.touch();
    }
});

// Serialization
/**
 * Create a mapping from numpy dtype strings to corresponding typed array
 * constructors
 */
var numpy_dtype_to_typedarray_type = {
    int8: Int8Array,
    int16: Int16Array,
    int32: Int32Array,
    uint8: Uint8Array,
    uint16: Uint16Array,
    uint32: Uint32Array,
    float32: Float32Array,
    float64: Float64Array
};

function serializeTypedArray(v) {
    var numpyType;
    if (v instanceof Int8Array) {
        numpyType = 'int8';
    } else if (v instanceof Int16Array) {
        numpyType = 'int16';
    } else if (v instanceof Int32Array) {
        numpyType = 'int32';
    } else if (v instanceof Uint8Array) {
        numpyType = 'uint8';
    } else if (v instanceof Uint16Array) {
        numpyType = 'uint16';
    } else if (v instanceof Uint32Array) {
        numpyType = 'uint32';
    } else if (v instanceof Float32Array) {
        numpyType = 'float32';
    } else if (v instanceof Float64Array) {
        numpyType = 'float64';
    } else {
        // Don't understand it, return as is
        return v;
    }
    var res = {
        dtype: numpyType,
        shape: [v.length],
        value: v.buffer
    };
    return res
}

/**
 * ipywidget JavaScript -> Python serializer
 */
function js2py_serializer(v, widgetManager) {
    var res;

    if (_.isTypedArray(v)) {
        res = serializeTypedArray(v);
    } else if (Array.isArray(v)) {
        // Serialize array elements recursively
        res = new Array(v.length);
        for (var i = 0; i < v.length; i++) {
            res[i] = js2py_serializer(v[i]);
        }
    } else if (_.isPlainObject(v)) {
        // Serialize object properties recursively
        res = {};
        for (var p in v) {
            if (v.hasOwnProperty(p)) {
                res[p] = js2py_serializer(v[p]);
            }
        }
    } else if (v === undefined) {
        // Translate undefined into '_undefined_' sentinal string. The
        // Python _js_to_py deserializer will convert this into an
        // Undefined object
        res = "_undefined_";
    } else {
        // Primitive value to transfer directly
        res = v;
    }
    return res
}

/**
 * ipywidget Python -> Javascript deserializer
 */
function py2js_deserializer(v, widgetManager) {
    var res;

    if (Array.isArray(v)) {
        // Deserialize array elements recursively
        res = new Array(v.length);
        for (var i = 0; i < v.length; i++) {
            res[i] = py2js_deserializer(v[i]);
        }
    } else if (_.isPlainObject(v)) {
        if ((_.has(v, 'value') || _.has(v, 'buffer')) &&
            _.has(v, 'dtype') &&
            _.has(v, 'shape')) {
            // Deserialize special buffer/dtype/shape objects into typed arrays
            // These objects correspond to numpy arrays on the Python side
            //
            // Note plotly.py<=3.1.1 called the buffer object `buffer`
            // This was renamed `value` in 3.2 to work around a naming conflict
            // when saving widget state to a notebook.
            var typedarray_type = numpy_dtype_to_typedarray_type[v.dtype];
            var buffer = _.has(v, 'value')? v.value.buffer: v.buffer.buffer;
            res = new typedarray_type(buffer);
        } else {
            // Deserialize object properties recursively
            res = {};
            for (var p in v) {
                if (v.hasOwnProperty(p)) {
                    res[p] = py2js_deserializer(v[p]);
                }
            }
        }
    } else if (v === "_undefined_") {
        // Convert the _undefined_ sentinal into undefined
        res = undefined;
    } else {
        // Accept primitive value directly
        res = v;
    }
    return res
}

/**
 * Return whether the input value is a typed array
 * @param potentialTypedArray
 *  Value to examine
 * @returns {boolean}
 */
function isTypedArray(potentialTypedArray) {
    return ArrayBuffer.isView(potentialTypedArray) &&
        !(potentialTypedArray instanceof DataView);
}

/**
 * Customizer for use with lodash's mergeWith function
 *
 * The customizer ensures that typed arrays are not converted into standard
 * arrays during the recursive merge
 *
 * See: https://lodash.com/docs/latest#mergeWith
 */
function fullMergeCustomizer(objValue, srcValue, key) {
    if (key[0] === '_') {
        // Don't recurse into private properties
        return null
    } else if (isTypedArray(srcValue)) {
        // Return typed arrays directly, don't recurse inside
        return srcValue
    }
}

/**
 * Reform a Plotly.relayout like operation on an input object
 *
 * @param {Object} parentObj
 *  The object that the relayout operation should be applied to
 * @param {Object} relayoutData
 *  An relayout object as accepted by Plotly.relayout
 *
 *  Examples:
 *      var d = {foo {bar [5, 10]}};
 *      performRelayoutLike(d, {'foo.bar': [0, 1]});
 *      d -> {foo: {bar: [0, 1]}}
 *
 *      var d = {foo {bar [5, 10]}};
 *      performRelayoutLike(d, {'baz': 34});
 *      d -> {foo: {bar: [5, 10]}, baz: 34}
 *
 *      var d = {foo: {bar: [5, 10]};
 *      performRelayoutLike(d, {'foo.baz[1]': 17});
 *      d -> {foo: {bar: [5, 17]}}
 *
 */
function performRelayoutLike(parentObj, relayoutData) {
    // Perform a relayout style operation on a given parent object
    for (var rawKey in relayoutData) {
        if (!relayoutData.hasOwnProperty(rawKey)) {
            continue
        }

        // Extract value for this key
        var relayoutVal = relayoutData[rawKey];

        // Set property value
        if (relayoutVal === null) {
            _.unset(parentObj, rawKey);
        } else {
            _.set(parentObj, rawKey, relayoutVal);
        }
    }
}

/**
 * Perform a Plotly.restyle like operation on an input object array
 *
 * @param {Array.<Object>} parentArray
 *  The object that the restyle operation should be applied to
 * @param {Object} restyleData
 *  A restyle object as accepted by Plotly.restyle
 * @param {Array.<Number>} restyleTraces
 *  Array of indexes of the traces that the resytle operation applies to
 *
 *  Examples:
 *      var d = [{foo: {bar: 1}}, {}, {}]
 *      performRestyleLike(d, {'foo.bar': 2}, [0])
 *      d -> [{foo: {bar: 2}}, {}, {}]
 *
 *      var d = [{foo: {bar: 1}}, {}, {}]
 *      performRestyleLike(d, {'foo.bar': 2}, [0, 1, 2])
 *      d -> [{foo: {bar: 2}}, {foo: {bar: 2}}, {foo: {bar: 2}}]
 *
 *      var d = [{foo: {bar: 1}}, {}, {}]
 *      performRestyleLike(d, {'foo.bar': [2, 3, 4]}, [0, 1, 2])
 *      d -> [{foo: {bar: 2}}, {foo: {bar: 3}}, {foo: {bar: 4}}]
 *
 */
function performRestyleLike(parentArray, restyleData, restyleTraces) {
    // Loop over the properties of restyleData
    for (var rawKey in restyleData) {
        if (!restyleData.hasOwnProperty(rawKey)) { continue }

        // Extract value for property and normalize into a value list
        var valArray = restyleData[rawKey];
        if (!Array.isArray(valArray)) {
            valArray = [valArray]
        }

        // Loop over the indexes of the traces being restyled
        for (var i = 0; i < restyleTraces.length; i++) {

            // Get trace object
            var traceInd = restyleTraces[i];
            var trace = parentArray[traceInd];

            // Extract value for this trace
            var singleVal = valArray[i % valArray.length];

            // Set property value
            if (singleVal === null) {
                _.unset(trace, rawKey);
            } else if (singleVal !== undefined){
                _.set(trace, rawKey, singleVal);
            }
        }
    }
}

/**
 * Perform a Plotly.moveTraces like operation on an input object array
 * @param parentArray
 *  The object that the moveTraces operation should be applied to
 * @param currentInds
 *  Array of the current indexes of traces to be moved
 * @param newInds
 *  Array of the new indexes that traces selected by currentInds should be
 *  moved to.
 *
 *  Examples:
 *      var d = [{foo: 0}, {foo: 1}, {foo: 2}]
 *      performMoveTracesLike(d, [0, 1], [2, 0])
 *      d -> [{foo: 1}, {foo: 2}, {foo: 0}]
 *
 *      var d = [{foo: 0}, {foo: 1}, {foo: 2}]
 *      performMoveTracesLike(d, [0, 2], [1, 2])
 *      d -> [{foo: 1}, {foo: 0}, {foo: 2}]
 */
function performMoveTracesLike(parentArray, currentInds, newInds) {

    // ### Remove by currentInds in reverse order ###
    var movingTracesData = [];
    for (var ci = currentInds.length - 1; ci >= 0; ci--) {
        // Insert moving parentArray at beginning of the list
        movingTracesData.splice(0, 0, parentArray[currentInds[ci]]);
        parentArray.splice(currentInds[ci], 1);
    }

    // ### Sort newInds and movingTracesData by newInds ###
    var newIndexSortedArrays = _(newInds).zip(movingTracesData)
        .sortBy(0)
        .unzip()
        .value();

    newInds = newIndexSortedArrays[0];
    movingTracesData = newIndexSortedArrays[1];

    // ### Insert by newInds in forward order ###
    for (var ni = 0; ni < newInds.length; ni++) {
        parentArray.splice(newInds[ni], 0, movingTracesData[ni]);
    }
}

/**
 * Remove nested properties from a parent object
 * @param {Object} parentObj
 *  Parent object from which properties or nested properties should be removed
 * @param {Array.<Array.<Number|String>>} keyPaths
 *  Array of key paths for properties that should be removed. Each key path
 *  is an array of properties names or array indexes that reference a
 *  property to be removed
 *
 *  Examples:
 *      var d = {foo: [{bar: 0}, {bar: 1}], baz: 32}
 *      performRemoveProps(d, ['baz'])
 *      d -> {foo: [{bar: 0}, {bar: 1}]}
 *
 *      var d = {foo: [{bar: 0}, {bar: 1}], baz: 32}
 *      performRemoveProps(d, ['foo[1].bar', 'baz'])
 *      d -> {foo: [{bar: 0}, {}]}
 *
 */
function performRemoveProps(parentObj, keyPaths) {

    for(var i=0; i < keyPaths.length; i++) {
        var keyPath = keyPaths[i];
        _.unset(parentObj, keyPath);
    }
}


/**
 * Return object that contains all properties in fullObj that are not
 * identical to the corresponding properties in removeObj
 *
 * Properties of fullObj and removeObj may be objects or arrays of objects
 *
 * Returned object is a deep clone of the properties of the input objects
 *
 * @param {Object} fullObj
 * @param {Object} removeObj
 *
 *  Examples:
 *      var fullD = {foo: [{bar: 0}, {bar: 1}], baz: 32}
 *      var removeD = {baz: 32}
 *      createDeltaObject(fullD, removeD)
 *          -> {foo: [{bar: 0}, {bar: 1}]}
 *
 *      var fullD = {foo: [{bar: 0}, {bar: 1}], baz: 32}
 *      var removeD = {baz: 45}
 *      createDeltaObject(fullD, removeD)
 *          -> {foo: [{bar: 0}, {bar: 1}], baz: 32}
 *
 *      var fullD = {foo: [{bar: 0}, {bar: 1}], baz: 32}
 *      var removeD = {foo: [{bar: 0}, {bar: 1}]}
 *      createDeltaObject(fullD, removeD)
 *          -> {baz: 32}
 *
 */
function createDeltaObject(fullObj, removeObj) {

    // Initialize result as object or array
    var res;
    if(Array.isArray(fullObj)) {
        res = new Array(fullObj.length);
    } else {
        res = {};
    }

    // Initialize removeObj to empty object if not specified
    if (removeObj === null || removeObj === undefined) {
        removeObj = {};
    }

    // Iterate over object properties or array indices
    for (var p in fullObj) {
        if (p[0] !== "_" &&  // Don't consider private properties
            fullObj.hasOwnProperty(p) &&  // Exclude parent properties
            fullObj[p] !== null  // Exclude cases where fullObj doesn't
                                 // have the property
        ) {
            // Compute object equality
            var props_equal;
            props_equal = _.isEqual(fullObj[p], removeObj[p]);

            // Perform recursive comparison if props are not equal
            if (!props_equal || p === "uid") {  // Let uids through

                // property has non-null value in fullObj that doesn't
                // match the value in removeObj
                var fullVal = fullObj[p];
                if (removeObj.hasOwnProperty(p) &&
                    typeof fullVal === "object") {
                    // Recurse over object properties
                    if(Array.isArray(fullVal)) {

                        if (fullVal.length > 0 &&
                            typeof(fullVal[0]) === "object") {
                            // We have an object array
                            res[p] = new Array(fullVal.length);
                            for (var i = 0; i < fullVal.length; i++) {
                                if (!Array.isArray(removeObj[p]) ||
                                    removeObj[p].length <= i) {

                                    res[p][i] = fullVal[i]
                                } else {
                                    res[p][i] = createDeltaObject(fullVal[i],
                                        removeObj[p][i]);
                                }
                            }
                        } else {
                            // We have a primitive array or typed array
                            res[p] = fullVal;
                        }
                    } else { // object
                        var full_obj = createDeltaObject(fullVal,
                            removeObj[p]);
                        if (Object.keys(full_obj).length > 0) {
                            // new object is not empty
                            res[p] = full_obj;
                        }
                    }
                } else if (typeof fullVal === "object" &&
                    !Array.isArray(fullVal)) {
                    // Return 'clone' of fullVal
                    // We don't use a standard clone method so that we keep
                    // the special case handling of this method
                    res[p] = createDeltaObject(fullVal, {});

                } else if (fullVal !== undefined &&
                    typeof fullVal !== 'function') {
                    // No recursion necessary, Just keep value from fullObj.
                    // But skip values with function type
                    res[p] = fullVal;
                }
            }
        }
    }
    return res
}

module.exports = {
    FigureView : FigureView,
    FigureModel: FigureModel
};


/***/ }),

/***/ "sjHq":
/*!****************************************************************!*\
  !*** ./node_modules/@jupyterlab/plotly-extension/lib/index.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const plotly_1 = __importDefault(__webpack_require__(/*! plotly.js/dist/plotly */ "+1d/"));
__webpack_require__(/*! ../style/index.css */ "3hqu");
/**
 * The CSS class to add to the Plotly Widget.
 */
const CSS_CLASS = 'jp-RenderedPlotly';
/**
 * The CSS class for a Plotly icon.
 */
const CSS_ICON_CLASS = 'jp-MaterialIcon jp-PlotlyIcon';
/**
 * The MIME type for Plotly.
 * The version of this follows the major version of Plotly.
 */
exports.MIME_TYPE = 'application/vnd.plotly.v1+json';
class RenderedPlotly extends widgets_1.Widget {
    /**
     * Create a new widget for rendering Plotly.
     */
    constructor(options) {
        super();
        this.addClass(CSS_CLASS);
        this._mimeType = options.mimeType;
    }
    /**
     * Render Plotly into this widget's node.
     */
    renderModel(model) {
        const { data, layout, frames, config } = model.data[this._mimeType];
        // const metadata = model.metadata[this._mimeType] as any || {};
        return plotly_1.default.react(this.node, data, layout, config).then(plot => {
            this.update();
            if (frames) {
                plotly_1.default.addFrames(this.node, frames).then(() => {
                    plotly_1.default.animate(this.node);
                });
            }
            if (this.node.offsetWidth > 0 && this.node.offsetHeight > 0) {
                plotly_1.default.toImage(plot, {
                    format: 'png',
                    width: this.node.offsetWidth,
                    height: this.node.offsetHeight
                }).then((url) => {
                    const imageData = url.split(',')[1];
                    if (model.data['image/png'] !== imageData) {
                        model.setData({
                            data: Object.assign({}, model.data, { 'image/png': imageData })
                        });
                    }
                });
            }
        });
    }
    /**
     * A message handler invoked on an `'after-show'` message.
     */
    onAfterShow(msg) {
        this.update();
    }
    /**
     * A message handler invoked on a `'resize'` message.
     */
    onResize(msg) {
        this.update();
    }
    /**
     * A message handler invoked on an `'update-request'` message.
     */
    onUpdateRequest(msg) {
        if (this.isVisible) {
            plotly_1.default.redraw(this.node).then(() => {
                plotly_1.default.Plots.resize(this.node);
            });
        }
    }
}
exports.RenderedPlotly = RenderedPlotly;
/**
 * A mime renderer factory for Plotly data.
 */
exports.rendererFactory = {
    safe: true,
    mimeTypes: [exports.MIME_TYPE],
    createRenderer: options => new RenderedPlotly(options)
};
const extensions = [
    {
        id: '@jupyterlab/plotly-extension:factory',
        rendererFactory: exports.rendererFactory,
        rank: 0,
        dataType: 'json',
        fileTypes: [
            {
                name: 'plotly',
                mimeTypes: [exports.MIME_TYPE],
                extensions: ['.plotly', '.plotly.json'],
                iconClass: CSS_ICON_CLASS
            }
        ],
        documentWidgetFactoryOptions: {
            name: 'Plotly',
            primaryFileType: 'plotly',
            fileTypes: ['plotly', 'json'],
            defaultFor: ['plotly']
        }
    }
];
exports.default = extensions;


/***/ }),

/***/ "sk9p":
/*!*************************************************************!*\
  !*** ./node_modules/babel-runtime/helpers/slicedToArray.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _isIterable2 = __webpack_require__(/*! ../core-js/is-iterable */ "k/8l");

var _isIterable3 = _interopRequireDefault(_isIterable2);

var _getIterator2 = __webpack_require__(/*! ../core-js/get-iterator */ "FyfS");

var _getIterator3 = _interopRequireDefault(_getIterator2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = function () {
  function sliceIterator(arr, i) {
    var _arr = [];
    var _n = true;
    var _d = false;
    var _e = undefined;

    try {
      for (var _i = (0, _getIterator3.default)(arr), _s; !(_n = (_s = _i.next()).done); _n = true) {
        _arr.push(_s.value);

        if (i && _arr.length === i) break;
      }
    } catch (err) {
      _d = true;
      _e = err;
    } finally {
      try {
        if (!_n && _i["return"]) _i["return"]();
      } finally {
        if (_d) throw _e;
      }
    }

    return _arr;
  }

  return function (arr, i) {
    if (Array.isArray(arr)) {
      return arr;
    } else if ((0, _isIterable3.default)(Object(arr))) {
      return sliceIterator(arr, i);
    } else {
      throw new TypeError("Invalid attempt to destructure non-iterable instance");
    }
  };
}();

/***/ }),

/***/ "sp3z":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/lo.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var lo = moment.defineLocale('lo', {
    months : 'ມັງກອນ_ກຸມພາ_ມີນາ_ເມສາ_ພຶດສະພາ_ມິຖຸນາ_ກໍລະກົດ_ສິງຫາ_ກັນຍາ_ຕຸລາ_ພະຈິກ_ທັນວາ'.split('_'),
    monthsShort : 'ມັງກອນ_ກຸມພາ_ມີນາ_ເມສາ_ພຶດສະພາ_ມິຖຸນາ_ກໍລະກົດ_ສິງຫາ_ກັນຍາ_ຕຸລາ_ພະຈິກ_ທັນວາ'.split('_'),
    weekdays : 'ອາທິດ_ຈັນ_ອັງຄານ_ພຸດ_ພະຫັດ_ສຸກ_ເສົາ'.split('_'),
    weekdaysShort : 'ທິດ_ຈັນ_ອັງຄານ_ພຸດ_ພະຫັດ_ສຸກ_ເສົາ'.split('_'),
    weekdaysMin : 'ທ_ຈ_ອຄ_ພ_ພຫ_ສກ_ສ'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'ວັນdddd D MMMM YYYY HH:mm'
    },
    meridiemParse: /ຕອນເຊົ້າ|ຕອນແລງ/,
    isPM: function (input) {
        return input === 'ຕອນແລງ';
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 12) {
            return 'ຕອນເຊົ້າ';
        } else {
            return 'ຕອນແລງ';
        }
    },
    calendar : {
        sameDay : '[ມື້ນີ້ເວລາ] LT',
        nextDay : '[ມື້ອື່ນເວລາ] LT',
        nextWeek : '[ວັນ]dddd[ໜ້າເວລາ] LT',
        lastDay : '[ມື້ວານນີ້ເວລາ] LT',
        lastWeek : '[ວັນ]dddd[ແລ້ວນີ້ເວລາ] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'ອີກ %s',
        past : '%sຜ່ານມາ',
        s : 'ບໍ່ເທົ່າໃດວິນາທີ',
        ss : '%d ວິນາທີ' ,
        m : '1 ນາທີ',
        mm : '%d ນາທີ',
        h : '1 ຊົ່ວໂມງ',
        hh : '%d ຊົ່ວໂມງ',
        d : '1 ມື້',
        dd : '%d ມື້',
        M : '1 ເດືອນ',
        MM : '%d ເດືອນ',
        y : '1 ປີ',
        yy : '%d ປີ'
    },
    dayOfMonthOrdinalParse: /(ທີ່)\d{1,2}/,
    ordinal : function (number) {
        return 'ທີ່' + number;
    }
});

return lo;

})));


/***/ }),

/***/ "srvI":
/*!*****************************************************!*\
  !*** ./node_modules/react-color/lib/helpers/hue.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var calculateChange = exports.calculateChange = function calculateChange(e, skip, props, container) {
  e.preventDefault();
  var containerWidth = container.clientWidth;
  var containerHeight = container.clientHeight;
  var x = typeof e.pageX === 'number' ? e.pageX : e.touches[0].pageX;
  var y = typeof e.pageY === 'number' ? e.pageY : e.touches[0].pageY;
  var left = x - (container.getBoundingClientRect().left + window.pageXOffset);
  var top = y - (container.getBoundingClientRect().top + window.pageYOffset);

  if (props.direction === 'vertical') {
    var h = void 0;
    if (top < 0) {
      h = 359;
    } else if (top > containerHeight) {
      h = 0;
    } else {
      var percent = -(top * 100 / containerHeight) + 100;
      h = 360 * percent / 100;
    }

    if (props.hsl.h !== h) {
      return {
        h: h,
        s: props.hsl.s,
        l: props.hsl.l,
        a: props.hsl.a,
        source: 'rgb'
      };
    }
  } else {
    var _h = void 0;
    if (left < 0) {
      _h = 0;
    } else if (left > containerWidth) {
      _h = 359;
    } else {
      var _percent = left * 100 / containerWidth;
      _h = 360 * _percent / 100;
    }

    if (props.hsl.h !== _h) {
      return {
        h: _h,
        s: props.hsl.s,
        l: props.hsl.l,
        a: props.hsl.a,
        source: 'rgb'
      };
    }
  }
  return null;
};

/***/ }),

/***/ "sxmJ":
/*!*************************************************!*\
  !*** ./node_modules/mdi-react/ChevronUpIcon.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var ChevronUpIcon = function ChevronUpIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M7.41,15.41L12,10.83L16.59,15.41L18,14L12,8L6,14L7.41,15.41Z' })
  );
};

module.exports = ChevronUpIcon;


/***/ }),

/***/ "t+aO":
/*!************************************************!*\
  !*** ./node_modules/ajv/lib/dotjs/required.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_required(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $vSchema = 'schema' + $lvl;
  if (!$isData) {
    if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) {
      var $required = [];
      var arr1 = $schema;
      if (arr1) {
        var $property, i1 = -1,
          l1 = arr1.length - 1;
        while (i1 < l1) {
          $property = arr1[i1 += 1];
          var $propertySch = it.schema.properties[$property];
          if (!($propertySch && it.util.schemaHasRules($propertySch, it.RULES.all))) {
            $required[$required.length] = $property;
          }
        }
      }
    } else {
      var $required = $schema;
    }
  }
  if ($isData || $required.length) {
    var $currentErrorPath = it.errorPath,
      $loopRequired = $isData || $required.length >= it.opts.loopRequired,
      $ownProperties = it.opts.ownProperties;
    if ($breakOnError) {
      out += ' var missing' + ($lvl) + '; ';
      if ($loopRequired) {
        if (!$isData) {
          out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
        }
        var $i = 'i' + $lvl,
          $propertyPath = 'schema' + $lvl + '[' + $i + ']',
          $missingProperty = '\' + ' + $propertyPath + ' + \'';
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
        }
        out += ' var ' + ($valid) + ' = true; ';
        if ($isData) {
          out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
        }
        out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined ';
        if ($ownProperties) {
          out += ' &&   Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) ';
        }
        out += '; if (!' + ($valid) + ') break; } ';
        if ($isData) {
          out += '  }  ';
        }
        out += '  if (!' + ($valid) + ') {   ';
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'';
            if (it.opts._errorDataPathProperty) {
              out += 'is a required property';
            } else {
              out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
            }
            out += '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += ' } else { ';
      } else {
        out += ' if ( ';
        var arr2 = $required;
        if (arr2) {
          var $propertyKey, $i = -1,
            l2 = arr2.length - 1;
          while ($i < l2) {
            $propertyKey = arr2[$i += 1];
            if ($i) {
              out += ' || ';
            }
            var $prop = it.util.getProperty($propertyKey),
              $useData = $data + $prop;
            out += ' ( ( ' + ($useData) + ' === undefined ';
            if ($ownProperties) {
              out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
            }
            out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) ';
          }
        }
        out += ') {  ';
        var $propertyPath = 'missing' + $lvl,
          $missingProperty = '\' + ' + $propertyPath + ' + \'';
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
        }
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'';
            if (it.opts._errorDataPathProperty) {
              out += 'is a required property';
            } else {
              out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
            }
            out += '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += ' } else { ';
      }
    } else {
      if ($loopRequired) {
        if (!$isData) {
          out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
        }
        var $i = 'i' + $lvl,
          $propertyPath = 'schema' + $lvl + '[' + $i + ']',
          $missingProperty = '\' + ' + $propertyPath + ' + \'';
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
        }
        if ($isData) {
          out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) {  var err =   '; /* istanbul ignore else */
          if (it.createErrors !== false) {
            out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
            if (it.opts.messages !== false) {
              out += ' , message: \'';
              if (it.opts._errorDataPathProperty) {
                out += 'is a required property';
              } else {
                out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
              }
              out += '\' ';
            }
            if (it.opts.verbose) {
              out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
            }
            out += ' } ';
          } else {
            out += ' {} ';
          }
          out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { ';
        }
        out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined ';
        if ($ownProperties) {
          out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) ';
        }
        out += ') {  var err =   '; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'';
            if (it.opts._errorDataPathProperty) {
              out += 'is a required property';
            } else {
              out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
            }
            out += '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ';
        if ($isData) {
          out += '  }  ';
        }
      } else {
        var arr3 = $required;
        if (arr3) {
          var $propertyKey, i3 = -1,
            l3 = arr3.length - 1;
          while (i3 < l3) {
            $propertyKey = arr3[i3 += 1];
            var $prop = it.util.getProperty($propertyKey),
              $missingProperty = it.util.escapeQuotes($propertyKey),
              $useData = $data + $prop;
            if (it.opts._errorDataPathProperty) {
              it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
            }
            out += ' if ( ' + ($useData) + ' === undefined ';
            if ($ownProperties) {
              out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
            }
            out += ') {  var err =   '; /* istanbul ignore else */
            if (it.createErrors !== false) {
              out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
              if (it.opts.messages !== false) {
                out += ' , message: \'';
                if (it.opts._errorDataPathProperty) {
                  out += 'is a required property';
                } else {
                  out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
                }
                out += '\' ';
              }
              if (it.opts.verbose) {
                out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
              }
              out += ' } ';
            } else {
              out += ' {} ';
            }
            out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
          }
        }
      }
    }
    it.errorPath = $currentErrorPath;
  } else if ($breakOnError) {
    out += ' if (true) {';
  }
  return out;
}


/***/ }),

/***/ "t0w/":
/*!***********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/ColorscalePicker.js ***!
  \***********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UnconnectedColorscalePicker = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _ColorscalePicker = __webpack_require__(/*! ../widgets/ColorscalePicker */ "7/El");

var _ColorscalePicker2 = _interopRequireDefault(_ColorscalePicker);

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _constants = __webpack_require__(/*! ../../lib/constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UnconnectedColorscalePicker = exports.UnconnectedColorscalePicker = function (_Component) {
  _inherits(UnconnectedColorscalePicker, _Component);

  function UnconnectedColorscalePicker() {
    _classCallCheck(this, UnconnectedColorscalePicker);

    var _this = _possibleConstructorReturn(this, (UnconnectedColorscalePicker.__proto__ || Object.getPrototypeOf(UnconnectedColorscalePicker)).call(this));

    _this.onUpdate = _this.onUpdate.bind(_this);
    return _this;
  }

  _createClass(UnconnectedColorscalePicker, [{
    key: 'onUpdate',
    value: function onUpdate(colorscale, colorscaleType) {
      if (Array.isArray(colorscale)) {
        this.props.updatePlot(colorscale.map(function (c, i) {
          var step = i / (colorscale.length - 1);
          if (i === 0) {
            step = 0;
          }
          return [step, c];
        }), colorscaleType);
        this.context.onUpdate({
          type: _constants.EDITOR_ACTIONS.UPDATE_TRACES,
          payload: {
            update: { autocolorscale: false },
            traceIndexes: [this.props.fullContainer.index]
          }
        });
      }
    }
  }, {
    key: 'render',
    value: function render() {
      var fullValue = this.props.fullValue;

      var colorscale = Array.isArray(fullValue) ? fullValue.map(function (v) {
        return v[1];
      }) : null;

      return _react2.default.createElement(
        _Field2.default,
        _extends({}, this.props, { fieldContainerClassName: 'field__colorscale' }),
        _react2.default.createElement(_ColorscalePicker2.default, {
          selected: colorscale,
          onColorscaleChange: this.onUpdate,
          initialCategory: this.props.initialCategory,
          disableCategorySwitch: this.props.disableCategorySwitch
        })
      );
    }
  }]);

  return UnconnectedColorscalePicker;
}(_react.Component);

UnconnectedColorscalePicker.propTypes = _extends({
  labelWidth: _propTypes2.default.number,
  fullValue: _propTypes2.default.any,
  fullContainer: _propTypes2.default.object,
  updatePlot: _propTypes2.default.func,
  initialCategory: _propTypes2.default.string
}, _Field2.default.propTypes);

UnconnectedColorscalePicker.contextTypes = {
  container: _propTypes2.default.object,
  graphDiv: _propTypes2.default.object,
  onUpdate: _propTypes2.default.func
};

exports.default = (0, _lib.connectToContainer)(UnconnectedColorscalePicker);
//# sourceMappingURL=ColorscalePicker.js.map

/***/ }),

/***/ "t2Dn":
/*!**************************************************!*\
  !*** ./node_modules/lodash/_assignMergeValue.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseAssignValue = __webpack_require__(/*! ./_baseAssignValue */ "hypo"),
    eq = __webpack_require__(/*! ./eq */ "ljhN");

/**
 * 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;


/***/ }),

/***/ "t2Lz":
/*!*******************************************************!*\
  !*** ./node_modules/@jupyterlab/tooltip/lib/index.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
__webpack_require__(/*! ../style/index.css */ "yhJu");
__export(__webpack_require__(/*! ./widget */ "zd6B"));
/* tslint:disable */
/**
 * The tooltip manager token.
 */
exports.ITooltipManager = new coreutils_1.Token('@jupyterlab/tooltip:ITooltipManager');


/***/ }),

/***/ "t2YR":
/*!************************************************!*\
  !*** ./node_modules/xterm/lib/EventEmitter.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var EventEmitter = (function () {
    function EventEmitter() {
        this._events = this._events || {};
    }
    EventEmitter.prototype.on = function (type, listener) {
        this._events[type] = this._events[type] || [];
        this._events[type].push(listener);
    };
    EventEmitter.prototype.addDisposableListener = function (type, handler) {
        var _this = this;
        this.on(type, handler);
        return {
            dispose: function () {
                if (!handler) {
                    return;
                }
                _this.off(type, handler);
                handler = null;
            }
        };
    };
    EventEmitter.prototype.off = function (type, listener) {
        if (!this._events[type]) {
            return;
        }
        var obj = this._events[type];
        var i = obj.length;
        while (i--) {
            if (obj[i] === listener) {
                obj.splice(i, 1);
                return;
            }
        }
    };
    EventEmitter.prototype.removeAllListeners = function (type) {
        if (this._events[type]) {
            delete this._events[type];
        }
    };
    EventEmitter.prototype.emit = function (type) {
        var args = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            args[_i - 1] = arguments[_i];
        }
        if (!this._events[type]) {
            return;
        }
        var obj = this._events[type];
        for (var i = 0; i < obj.length; i++) {
            obj[i].apply(this, args);
        }
    };
    EventEmitter.prototype.listeners = function (type) {
        return this._events[type] || [];
    };
    EventEmitter.prototype.destroy = function () {
        this._events = {};
    };
    return EventEmitter;
}());
exports.EventEmitter = EventEmitter;

//# sourceMappingURL=EventEmitter.js.map


/***/ }),

/***/ "t33a":
/*!**********************************************!*\
  !*** ./node_modules/fbjs/lib/emptyObject.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */



var emptyObject = {};

if (true) {
  Object.freeze(emptyObject);
}

module.exports = emptyObject;

/***/ }),

/***/ "t3iM":
/*!************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/noop.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



// Simple helper functions
// none of these need any external deps

module.exports = function noop() {};


/***/ }),

/***/ "t7hN":
/*!************************************************!*\
  !*** ./node_modules/mdi-react/ViewListIcon.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var ViewListIcon = function ViewListIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M9,5V9H21V5M9,19H21V15H9M9,14H21V10H9M4,9H8V5H4M4,19H8V15H4M4,14H8V10H4V14Z' })
  );
};

module.exports = ViewListIcon;


/***/ }),

/***/ "t8r4":
/*!**********************************************************************!*\
  !*** ./node_modules/react-color/lib/components/swatches/Swatches.js ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Swatches = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _map = __webpack_require__(/*! lodash/map */ "3WF5");

var _map2 = _interopRequireDefault(_map);

var _merge = __webpack_require__(/*! lodash/merge */ "QkVN");

var _merge2 = _interopRequireDefault(_merge);

var _color = __webpack_require__(/*! ../../helpers/color */ "p8yl");

var _color2 = _interopRequireDefault(_color);

var _materialColors = __webpack_require__(/*! material-colors */ "wME1");

var material = _interopRequireWildcard(_materialColors);

var _common = __webpack_require__(/*! ../common */ "TM95");

var _SwatchesGroup = __webpack_require__(/*! ./SwatchesGroup */ "Efrf");

var _SwatchesGroup2 = _interopRequireDefault(_SwatchesGroup);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var Swatches = exports.Swatches = function Swatches(_ref) {
  var width = _ref.width,
      height = _ref.height,
      onChange = _ref.onChange,
      onSwatchHover = _ref.onSwatchHover,
      colors = _ref.colors,
      hex = _ref.hex,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': {
      picker: {
        width: width,
        height: height
      },
      overflow: {
        height: height,
        overflowY: 'scroll'
      },
      body: {
        padding: '16px 0 6px 16px'
      },
      clear: {
        clear: 'both'
      }
    }
  }, passedStyles));

  var handleChange = function handleChange(data, e) {
    _color2.default.isValidHex(data) && onChange({
      hex: data,
      source: 'hex'
    }, e);
  };

  return _react2.default.createElement(
    'div',
    { style: styles.picker, className: 'swatches-picker ' + className },
    _react2.default.createElement(
      _common.Raised,
      null,
      _react2.default.createElement(
        'div',
        { style: styles.overflow },
        _react2.default.createElement(
          'div',
          { style: styles.body },
          (0, _map2.default)(colors, function (group) {
            return _react2.default.createElement(_SwatchesGroup2.default, {
              key: group.toString(),
              group: group,
              active: hex,
              onClick: handleChange,
              onSwatchHover: onSwatchHover
            });
          }),
          _react2.default.createElement('div', { style: styles.clear })
        )
      )
    )
  );
};

Swatches.propTypes = {
  width: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]),
  height: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]),
  colors: _propTypes2.default.arrayOf(_propTypes2.default.arrayOf(_propTypes2.default.string)),
  styles: _propTypes2.default.object

  /* eslint-disable max-len */
};Swatches.defaultProps = {
  width: 320,
  height: 240,
  colors: [[material.red['900'], material.red['700'], material.red['500'], material.red['300'], material.red['100']], [material.pink['900'], material.pink['700'], material.pink['500'], material.pink['300'], material.pink['100']], [material.purple['900'], material.purple['700'], material.purple['500'], material.purple['300'], material.purple['100']], [material.deepPurple['900'], material.deepPurple['700'], material.deepPurple['500'], material.deepPurple['300'], material.deepPurple['100']], [material.indigo['900'], material.indigo['700'], material.indigo['500'], material.indigo['300'], material.indigo['100']], [material.blue['900'], material.blue['700'], material.blue['500'], material.blue['300'], material.blue['100']], [material.lightBlue['900'], material.lightBlue['700'], material.lightBlue['500'], material.lightBlue['300'], material.lightBlue['100']], [material.cyan['900'], material.cyan['700'], material.cyan['500'], material.cyan['300'], material.cyan['100']], [material.teal['900'], material.teal['700'], material.teal['500'], material.teal['300'], material.teal['100']], ['#194D33', material.green['700'], material.green['500'], material.green['300'], material.green['100']], [material.lightGreen['900'], material.lightGreen['700'], material.lightGreen['500'], material.lightGreen['300'], material.lightGreen['100']], [material.lime['900'], material.lime['700'], material.lime['500'], material.lime['300'], material.lime['100']], [material.yellow['900'], material.yellow['700'], material.yellow['500'], material.yellow['300'], material.yellow['100']], [material.amber['900'], material.amber['700'], material.amber['500'], material.amber['300'], material.amber['100']], [material.orange['900'], material.orange['700'], material.orange['500'], material.orange['300'], material.orange['100']], [material.deepOrange['900'], material.deepOrange['700'], material.deepOrange['500'], material.deepOrange['300'], material.deepOrange['100']], [material.brown['900'], material.brown['700'], material.brown['500'], material.brown['300'], material.brown['100']], [material.blueGrey['900'], material.blueGrey['700'], material.blueGrey['500'], material.blueGrey['300'], material.blueGrey['100']], ['#000000', '#525252', '#969696', '#D9D9D9', '#FFFFFF']],
  styles: {}
};

exports.default = (0, _common.ColorWrap)(Swatches);

/***/ }),

/***/ "t9FE":
/*!************************************************!*\
  !*** ./node_modules/util-deprecate/browser.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global) {
/**
 * Module exports.
 */

module.exports = deprecate;

/**
 * Mark that a method should not be used.
 * Returns a modified function which warns once by default.
 *
 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
 *
 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
 * will throw an Error when invoked.
 *
 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
 * will invoke `console.trace()` instead of `console.error()`.
 *
 * @param {Function} fn - the function to deprecate
 * @param {String} msg - the string to print to the console when `fn` is invoked
 * @returns {Function} a new "deprecated" version of `fn`
 * @api public
 */

function deprecate (fn, msg) {
  if (config('noDeprecation')) {
    return fn;
  }

  var warned = false;
  function deprecated() {
    if (!warned) {
      if (config('throwDeprecation')) {
        throw new Error(msg);
      } else if (config('traceDeprecation')) {
        console.trace(msg);
      } else {
        console.warn(msg);
      }
      warned = true;
    }
    return fn.apply(this, arguments);
  }

  return deprecated;
}

/**
 * Checks `localStorage` for boolean values for the given `name`.
 *
 * @param {String} name
 * @returns {Boolean}
 * @api private
 */

function config (name) {
  // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  try {
    if (!global.localStorage) return false;
  } catch (_) {
    return false;
  }
  var val = global.localStorage[name];
  if (null == val) return false;
  return String(val).toLowerCase() === 'true';
}

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "t9bh":
/*!*********************************************!*\
  !*** ./node_modules/mdi-react/CloseIcon.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var CloseIcon = function CloseIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z' })
  );
};

module.exports = CloseIcon;


/***/ }),

/***/ "tEej":
/*!************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_to-length.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// 7.1.15 ToLength
var toInteger = __webpack_require__(/*! ./_to-integer */ "Ojgd");
var min = Math.min;
module.exports = function (it) {
  return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};


/***/ }),

/***/ "tGlX":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/de.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


function processRelativeTime(number, withoutSuffix, key, isFuture) {
    var format = {
        'm': ['eine Minute', 'einer Minute'],
        'h': ['eine Stunde', 'einer Stunde'],
        'd': ['ein Tag', 'einem Tag'],
        'dd': [number + ' Tage', number + ' Tagen'],
        'M': ['ein Monat', 'einem Monat'],
        'MM': [number + ' Monate', number + ' Monaten'],
        'y': ['ein Jahr', 'einem Jahr'],
        'yy': [number + ' Jahre', number + ' Jahren']
    };
    return withoutSuffix ? format[key][0] : format[key][1];
}

var de = moment.defineLocale('de', {
    months : 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'),
    monthsShort : 'Jan._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'),
    monthsParseExact : true,
    weekdays : 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'),
    weekdaysShort : 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'),
    weekdaysMin : 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT: 'HH:mm',
        LTS: 'HH:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D. MMMM YYYY',
        LLL : 'D. MMMM YYYY HH:mm',
        LLLL : 'dddd, D. MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay: '[heute um] LT [Uhr]',
        sameElse: 'L',
        nextDay: '[morgen um] LT [Uhr]',
        nextWeek: 'dddd [um] LT [Uhr]',
        lastDay: '[gestern um] LT [Uhr]',
        lastWeek: '[letzten] dddd [um] LT [Uhr]'
    },
    relativeTime : {
        future : 'in %s',
        past : 'vor %s',
        s : 'ein paar Sekunden',
        ss : '%d Sekunden',
        m : processRelativeTime,
        mm : '%d Minuten',
        h : processRelativeTime,
        hh : '%d Stunden',
        d : processRelativeTime,
        dd : processRelativeTime,
        M : processRelativeTime,
        MM : processRelativeTime,
        y : processRelativeTime,
        yy : processRelativeTime
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return de;

})));


/***/ }),

/***/ "tJ7k":
/*!*******************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/terminal/default.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const __1 = __webpack_require__(/*! .. */ "S9up");
const terminal_1 = __webpack_require__(/*! ./terminal */ "lV/m");
/**
 * The url for the terminal service.
 */
const TERMINAL_SERVICE_URL = 'api/terminals';
/**
 * An implementation of a terminal interface.
 */
class DefaultTerminalSession {
    /**
     * Construct a new terminal session.
     */
    constructor(name, options = {}) {
        this._isDisposed = false;
        this._isReady = false;
        this._messageReceived = new signaling_1.Signal(this);
        this._terminated = new signaling_1.Signal(this);
        this._ws = null;
        this._noOp = () => {
            /* no-op */
        };
        this._reconnectLimit = 7;
        this._reconnectAttempt = 0;
        this._name = name;
        this.serverSettings =
            options.serverSettings || __1.ServerConnection.makeSettings();
        this._readyPromise = this._initializeSocket();
    }
    /**
     * A signal emitted when the session is shut down.
     */
    get terminated() {
        return this._terminated;
    }
    /**
     * A signal emitted when a message is received from the server.
     */
    get messageReceived() {
        return this._messageReceived;
    }
    /**
     * Get the name of the terminal session.
     */
    get name() {
        return this._name;
    }
    /**
     * Get the model for the terminal session.
     */
    get model() {
        return { name: this._name };
    }
    /**
     * Test whether the session is ready.
     */
    get isReady() {
        return this._isReady;
    }
    /**
     * A promise that fulfills when the session is ready.
     */
    get ready() {
        return this._readyPromise;
    }
    /**
     * Test whether the session is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources held by the session.
     */
    dispose() {
        if (this._isDisposed) {
            return;
        }
        this.terminated.emit(undefined);
        this._isDisposed = true;
        if (this._ws) {
            this._ws.close();
            this._ws = null;
        }
        delete Private.running[this._url];
        signaling_1.Signal.clearData(this);
    }
    /**
     * Send a message to the terminal session.
     */
    send(message) {
        if (this._isDisposed || !message.content) {
            return;
        }
        const msg = [message.type, ...message.content];
        const socket = this._ws;
        const value = JSON.stringify(msg);
        if (this._isReady && socket) {
            socket.send(value);
            return;
        }
        this.ready.then(() => {
            const socket = this._ws;
            if (socket) {
                socket.send(value);
            }
        });
    }
    /**
     * Reconnect to the terminal.
     *
     * @returns A promise that resolves when the terminal has reconnected.
     */
    reconnect() {
        this._reconnectAttempt = 0;
        this._readyPromise = this._initializeSocket();
        return this._readyPromise;
    }
    /**
     * Shut down the terminal session.
     */
    shutdown() {
        const { name, serverSettings } = this;
        return DefaultTerminalSession.shutdown(name, serverSettings);
    }
    /**
     * Clone the current session object.
     */
    clone() {
        const { name, serverSettings } = this;
        return new DefaultTerminalSession(name, { serverSettings });
    }
    /**
     * Connect to the websocket.
     */
    _initializeSocket() {
        const name = this._name;
        let socket = this._ws;
        if (socket) {
            // Clear the websocket event handlers and the socket itself.
            socket.onopen = this._noOp;
            socket.onclose = this._noOp;
            socket.onerror = this._noOp;
            socket.onmessage = this._noOp;
            socket.close();
            this._ws = null;
        }
        this._isReady = false;
        return new Promise((resolve, reject) => {
            const settings = this.serverSettings;
            const token = this.serverSettings.token;
            this._url = Private.getTermUrl(settings.baseUrl, this._name);
            Private.running[this._url] = this;
            let wsUrl = coreutils_1.URLExt.join(settings.wsUrl, `terminals/websocket/${name}`);
            if (token) {
                wsUrl = wsUrl + `?token=${encodeURIComponent(token)}`;
            }
            socket = this._ws = new settings.WebSocket(wsUrl);
            socket.onmessage = (event) => {
                if (this._isDisposed) {
                    return;
                }
                const data = JSON.parse(event.data);
                if (this._reconnectAttempt > 0) {
                    // After reconnection, ignore all messages until a 'setup' message.
                    if (data[0] === 'setup') {
                        this._reconnectAttempt = 0;
                    }
                    return;
                }
                this._messageReceived.emit({
                    type: data[0],
                    content: data.slice(1)
                });
            };
            socket.onopen = (event) => {
                if (!this._isDisposed) {
                    this._isReady = true;
                    resolve(undefined);
                }
            };
            socket.onerror = (event) => {
                if (!this._isDisposed) {
                    reject(event);
                }
            };
            socket.onclose = (event) => {
                console.warn(`Terminal websocket closed: ${event.code}`);
                this._reconnectSocket();
            };
        });
    }
    _reconnectSocket() {
        if (this._isDisposed || !this._ws) {
            return;
        }
        const attempt = this._reconnectAttempt;
        const limit = this._reconnectLimit;
        if (attempt >= limit) {
            console.log(`Terminal reconnect aborted: ${attempt} attempts`);
            return;
        }
        const timeout = Math.pow(2, attempt);
        console.log(`Terminal will attempt to reconnect in ${timeout}s`);
        this._isReady = false;
        this._reconnectAttempt += 1;
        setTimeout(() => {
            if (this.isDisposed) {
                return;
            }
            this._initializeSocket()
                .then(() => {
                console.log('Terminal reconnected');
            })
                .catch(reason => {
                console.warn(`Terminal reconnect failed`, reason);
            });
        }, 1e3 * timeout);
    }
}
exports.DefaultTerminalSession = DefaultTerminalSession;
/**
 * The static namespace for `DefaultTerminalSession`.
 */
(function (DefaultTerminalSession) {
    /**
     * Whether the terminal service is available.
     */
    function isAvailable() {
        let available = String(coreutils_1.PageConfig.getOption('terminalsAvailable'));
        return available.toLowerCase() === 'true';
    }
    DefaultTerminalSession.isAvailable = isAvailable;
    /**
     * Start a new terminal session.
     *
     * @param options - The session options to use.
     *
     * @returns A promise that resolves with the session instance.
     */
    function startNew(options = {}) {
        if (!terminal_1.TerminalSession.isAvailable()) {
            throw Private.unavailableMsg;
        }
        let serverSettings = options.serverSettings || __1.ServerConnection.makeSettings();
        let url = Private.getServiceUrl(serverSettings.baseUrl);
        let init = { method: 'POST' };
        return __1.ServerConnection.makeRequest(url, init, serverSettings)
            .then(response => {
            if (response.status !== 200) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            return response.json();
        })
            .then((data) => {
            let name = data.name;
            return new DefaultTerminalSession(name, Object.assign({}, options, { serverSettings }));
        });
    }
    DefaultTerminalSession.startNew = startNew;
    /*
     * Connect to a running session.
     *
     * @param name - The name of the target session.
     *
     * @param options - The session options to use.
     *
     * @returns A promise that resolves with the new session instance.
     *
     * #### Notes
     * If the session was already started via `startNew`, the existing
     * session object is used as the fulfillment value.
     *
     * Otherwise, if `options` are given, we resolve the promise after
     * confirming that the session exists on the server.
     *
     * If the session does not exist on the server, the promise is rejected.
     */
    function connectTo(name, options = {}) {
        if (!terminal_1.TerminalSession.isAvailable()) {
            return Promise.reject(Private.unavailableMsg);
        }
        let serverSettings = options.serverSettings || __1.ServerConnection.makeSettings();
        let url = Private.getTermUrl(serverSettings.baseUrl, name);
        if (url in Private.running) {
            return Promise.resolve(Private.running[url].clone());
        }
        return listRunning(serverSettings).then(models => {
            let index = algorithm_1.ArrayExt.findFirstIndex(models, model => {
                return model.name === name;
            });
            if (index !== -1) {
                let session = new DefaultTerminalSession(name, Object.assign({}, options, { serverSettings }));
                return Promise.resolve(session);
            }
            return Promise.reject('Could not find session');
        });
    }
    DefaultTerminalSession.connectTo = connectTo;
    /**
     * List the running terminal sessions.
     *
     * @param settings - The server settings to use.
     *
     * @returns A promise that resolves with the list of running session models.
     */
    function listRunning(settings) {
        if (!terminal_1.TerminalSession.isAvailable()) {
            return Promise.reject(Private.unavailableMsg);
        }
        settings = settings || __1.ServerConnection.makeSettings();
        let url = Private.getServiceUrl(settings.baseUrl);
        return __1.ServerConnection.makeRequest(url, {}, settings)
            .then(response => {
            if (response.status !== 200) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            return response.json();
        })
            .then((data) => {
            if (!Array.isArray(data)) {
                throw new Error('Invalid terminal data');
            }
            // Update the local data store.
            let urls = algorithm_1.toArray(algorithm_1.map(data, item => {
                return coreutils_1.URLExt.join(url, item.name);
            }));
            algorithm_1.each(Object.keys(Private.running), runningUrl => {
                if (urls.indexOf(runningUrl) === -1) {
                    let session = Private.running[runningUrl];
                    session.dispose();
                }
            });
            return data;
        });
    }
    DefaultTerminalSession.listRunning = listRunning;
    /**
     * Shut down a terminal session by name.
     *
     * @param name - The name of the target session.
     *
     * @param settings - The server settings to use.
     *
     * @returns A promise that resolves when the session is shut down.
     */
    function shutdown(name, settings) {
        if (!terminal_1.TerminalSession.isAvailable()) {
            return Promise.reject(Private.unavailableMsg);
        }
        settings = settings || __1.ServerConnection.makeSettings();
        let url = Private.getTermUrl(settings.baseUrl, name);
        let init = { method: 'DELETE' };
        return __1.ServerConnection.makeRequest(url, init, settings).then(response => {
            if (response.status === 404) {
                return response.json().then(data => {
                    console.warn(data['message']);
                    Private.killTerminal(url);
                });
            }
            if (response.status !== 204) {
                throw new __1.ServerConnection.ResponseError(response);
            }
            Private.killTerminal(url);
        });
    }
    DefaultTerminalSession.shutdown = shutdown;
    /**
     * Shut down all terminal sessions.
     *
     * @param settings - The server settings to use.
     *
     * @returns A promise that resolves when all the sessions are shut down.
     */
    function shutdownAll(settings) {
        settings = settings || __1.ServerConnection.makeSettings();
        return listRunning(settings).then(running => {
            algorithm_1.each(running, s => {
                shutdown(s.name, settings);
            });
        });
    }
    DefaultTerminalSession.shutdownAll = shutdownAll;
})(DefaultTerminalSession = exports.DefaultTerminalSession || (exports.DefaultTerminalSession = {}));
/**
 * A namespace for private data.
 */
var Private;
(function (Private) {
    /**
     * A mapping of running terminals by url.
     */
    Private.running = Object.create(null);
    /**
     * A promise returned for when terminals are unavailable.
     */
    Private.unavailableMsg = 'Terminals Unavailable';
    /**
     * Get the url for a terminal.
     */
    function getTermUrl(baseUrl, name) {
        return coreutils_1.URLExt.join(baseUrl, TERMINAL_SERVICE_URL, name);
    }
    Private.getTermUrl = getTermUrl;
    /**
     * Get the base url.
     */
    function getServiceUrl(baseUrl) {
        return coreutils_1.URLExt.join(baseUrl, TERMINAL_SERVICE_URL);
    }
    Private.getServiceUrl = getServiceUrl;
    /**
     * Kill a terminal by url.
     */
    function killTerminal(url) {
        // Update the local data store.
        if (Private.running[url]) {
            let session = Private.running[url];
            session.dispose();
        }
    }
    Private.killTerminal = killTerminal;
})(Private || (Private = {}));


/***/ }),

/***/ "tKF0":
/*!************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TooltipCompareIcon.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TooltipCompareIcon = function TooltipCompareIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 17.993999481201172 16' }, props),
        _react2.default.createElement('path', { d: 'M2.998 1.019V1L.006 4.008 3 7h15V1.019H2.998zm0 7.988v-.015L.006 11.994 3 15h15V9l-15.002.007z' })
    );
};

exports.default = TooltipCompareIcon;

/***/ }),

/***/ "tKWh":
/*!********************************************************!*\
  !*** ./node_modules/fbjs/lib/getViewportDimensions.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function getViewportWidth() {
  var width = void 0;
  if (document.documentElement) {
    width = document.documentElement.clientWidth;
  }

  if (!width && document.body) {
    width = document.body.clientWidth;
  }

  return width || 0;
} /**
   * Copyright (c) 2013-present, Facebook, Inc.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *
   * 
   * @typechecks
   */

function getViewportHeight() {
  var height = void 0;
  if (document.documentElement) {
    height = document.documentElement.clientHeight;
  }

  if (!height && document.body) {
    height = document.body.clientHeight;
  }

  return height || 0;
}

/**
 * Gets the viewport dimensions including any scrollbars.
 */
function getViewportDimensions() {
  return {
    width: window.innerWidth || getViewportWidth(),
    height: window.innerHeight || getViewportHeight()
  };
}

/**
 * Gets the viewport dimensions excluding any scrollbars.
 */
getViewportDimensions.withoutScrollbars = function () {
  return {
    width: getViewportWidth(),
    height: getViewportHeight()
  };
};

module.exports = getViewportDimensions;

/***/ }),

/***/ "tLB3":
/*!*****************************************!*\
  !*** ./node_modules/lodash/toNumber.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var isObject = __webpack_require__(/*! ./isObject */ "GoyQ"),
    isSymbol = __webpack_require__(/*! ./isSymbol */ "/9aa");

/** Used as references for various `Number` constants. */
var NAN = 0 / 0;

/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;

/** 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 = value.replace(reTrim, '');
  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;


/***/ }),

/***/ "tLa0":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyter-widgets/base/lib/version.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.JUPYTER_WIDGETS_VERSION = '1.1.0';
exports.PROTOCOL_VERSION = '2.0.0';


/***/ }),

/***/ "tMB7":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_listCacheGet.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var assocIndexOf = __webpack_require__(/*! ./_assocIndexOf */ "y1pI");

/**
 * 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];
}

module.exports = listCacheGet;


/***/ }),

/***/ "tNxU":
/*!******************************************************!*\
  !*** ./node_modules/@jupyterlab/mainmenu/lib/run.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const labmenu_1 = __webpack_require__(/*! ./labmenu */ "e7FE");
/**
 * An extensible Run menu for the application.
 */
class RunMenu extends labmenu_1.JupyterLabMenu {
    /**
     * Construct the run menu.
     */
    constructor(options) {
        super(options);
        this.menu.title.label = 'Run';
        this.codeRunners = new Set();
    }
    /**
     * Dispose of the resources held by the run menu.
     */
    dispose() {
        this.codeRunners.clear();
        super.dispose();
    }
}
exports.RunMenu = RunMenu;


/***/ }),

/***/ "tOiH":
/*!**************************************************************!*\
  !*** ./node_modules/browserify-sign/browser/algorithms.json ***!
  \**************************************************************/
/*! exports provided: sha224WithRSAEncryption, RSA-SHA224, sha256WithRSAEncryption, RSA-SHA256, sha384WithRSAEncryption, RSA-SHA384, sha512WithRSAEncryption, RSA-SHA512, RSA-SHA1, ecdsa-with-SHA1, sha256, sha224, sha384, sha512, DSA-SHA, DSA-SHA1, DSA, DSA-WITH-SHA224, DSA-SHA224, DSA-WITH-SHA256, DSA-SHA256, DSA-WITH-SHA384, DSA-SHA384, DSA-WITH-SHA512, DSA-SHA512, DSA-RIPEMD160, ripemd160WithRSA, RSA-RIPEMD160, md5WithRSAEncryption, RSA-MD5, default */
/***/ (function(module) {

module.exports = {"sha224WithRSAEncryption":{"sign":"rsa","hash":"sha224","id":"302d300d06096086480165030402040500041c"},"RSA-SHA224":{"sign":"ecdsa/rsa","hash":"sha224","id":"302d300d06096086480165030402040500041c"},"sha256WithRSAEncryption":{"sign":"rsa","hash":"sha256","id":"3031300d060960864801650304020105000420"},"RSA-SHA256":{"sign":"ecdsa/rsa","hash":"sha256","id":"3031300d060960864801650304020105000420"},"sha384WithRSAEncryption":{"sign":"rsa","hash":"sha384","id":"3041300d060960864801650304020205000430"},"RSA-SHA384":{"sign":"ecdsa/rsa","hash":"sha384","id":"3041300d060960864801650304020205000430"},"sha512WithRSAEncryption":{"sign":"rsa","hash":"sha512","id":"3051300d060960864801650304020305000440"},"RSA-SHA512":{"sign":"ecdsa/rsa","hash":"sha512","id":"3051300d060960864801650304020305000440"},"RSA-SHA1":{"sign":"rsa","hash":"sha1","id":"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{"sign":"ecdsa","hash":"sha1","id":""},"sha256":{"sign":"ecdsa","hash":"sha256","id":""},"sha224":{"sign":"ecdsa","hash":"sha224","id":""},"sha384":{"sign":"ecdsa","hash":"sha384","id":""},"sha512":{"sign":"ecdsa","hash":"sha512","id":""},"DSA-SHA":{"sign":"dsa","hash":"sha1","id":""},"DSA-SHA1":{"sign":"dsa","hash":"sha1","id":""},"DSA":{"sign":"dsa","hash":"sha1","id":""},"DSA-WITH-SHA224":{"sign":"dsa","hash":"sha224","id":""},"DSA-SHA224":{"sign":"dsa","hash":"sha224","id":""},"DSA-WITH-SHA256":{"sign":"dsa","hash":"sha256","id":""},"DSA-SHA256":{"sign":"dsa","hash":"sha256","id":""},"DSA-WITH-SHA384":{"sign":"dsa","hash":"sha384","id":""},"DSA-SHA384":{"sign":"dsa","hash":"sha384","id":""},"DSA-WITH-SHA512":{"sign":"dsa","hash":"sha512","id":""},"DSA-SHA512":{"sign":"dsa","hash":"sha512","id":""},"DSA-RIPEMD160":{"sign":"dsa","hash":"rmd160","id":""},"ripemd160WithRSA":{"sign":"rsa","hash":"rmd160","id":"3021300906052b2403020105000414"},"RSA-RIPEMD160":{"sign":"rsa","hash":"rmd160","id":"3021300906052b2403020105000414"},"md5WithRSAEncryption":{"sign":"rsa","hash":"md5","id":"3020300c06082a864886f70d020505000410"},"RSA-MD5":{"sign":"rsa","hash":"md5","id":"3020300c06082a864886f70d020505000410"}};

/***/ }),

/***/ "tP0r":
/*!*******************************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/text_editors/RichText/DraftCommands.js ***!
  \*******************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.cursorHasLink = cursorHasLink;
exports.getEntityByKey = getEntityByKey;
exports.getEntityKeyAt = getEntityKeyAt;
exports.handleKeyCommand = handleKeyCommand;
exports.insertSoftNewline = insertSoftNewline;
exports.toggleInlineStyle = toggleInlineStyle;
exports.toggleLink = toggleLink;
exports.toggleMutuallyExclusiveStyles = toggleMutuallyExclusiveStyles;

var _draftJs = __webpack_require__(/*! draft-js */ "v83y");

var _DraftModifier = __webpack_require__(/*! draft-js/lib/DraftModifier */ "fyOY");

var _configuration = __webpack_require__(/*! ./configuration */ "3Mxs");

/**
 * Check whether the current selection is over a link
 *
 * @param   {EditorState} editorState   The DraftJS editor state
 * @param   {SelectionState} selection  A DraftJS selection state
 * @returns {Boolean}                   `true` if selection is over a link
 */
function selectionHasLink(editorState, selection) {
  // If nothing is selected, bail early.
  if (selection.isCollapsed()) {
    return false;
  }

  return cursorHasLink(editorState, selection);
}

/**
 * Check whether the cursor position is over a link
 *
 * @param   {EditorState} editorState   The DraftJS editor state
 * @param   {SelectionState} selection  A DraftJS selection state
 * @returns {Boolean}                   `true` if cursor is over a link
 */
/*
 * This module exports functions that act on a DraftJS EditorState to
 * effect commands.
 */

function cursorHasLink(editorState, selection) {
  var entity = getEntityByKey(getEntityKeyAt(editorState, selection));

  return Boolean(entity && entity.get('type') === _configuration.LINK);
}

/**
 * Get an entity by its key
 * Links are represented as DraftJS entities.
 * https://facebook.github.io/draft-js/docs/api-reference-entity.html#content
 *
 * @param   {String} entityKey    The entity key
 * @returns {DraftEntityInstance} The entity for the key, or `null` if not found
 */
function getEntityByKey(entityKey) {
  if (!entityKey) {
    return null;
  }

  return _draftJs.Entity.get(entityKey);
}

/**
 * For a given SelectionState, get the underlying entity key.
 *
 * @param   {EditorState} editorState  The DraftJS editor state
 * @param   {SelectionState} selection The DraftJS selection state
 * @returns {String}                   The entity key, or `null` if not found
 */
function getEntityKeyAt(editorState, selection) {
  if (!selection) {
    return null;
  }

  var blockStartKey = selection.getStartKey();
  var selectionOffset = selection.getStartOffset();

  var contentState = editorState.getCurrentContent();
  var block = contentState.getBlockForKey(blockStartKey);

  return block.getEntityAt(selectionOffset);
}

/**
 * Handle a keyboard command.
 * TODO: add custom CMD-k command for link button.
 * https://github.com/plotly/streambed/issues/6384
 *
 * @param   {EditorState} editorState The DraftJS editor state
 * @param   {String} command          The command string representation
 * @returns {EditorState}             The new editor state
 */
function handleKeyCommand(editorState, command) {
  switch (command) {
    case 'split-block':
      // Never split editor content into `<p>` blocks.
      return insertSoftNewline(editorState);
    case 'bold':
      return toggleInlineStyle(editorState, _configuration.BOLD);
    case 'italic':
      return toggleInlineStyle(editorState, _configuration.ITALIC);
    default:
      return false;
  }
}

/**
 * Insert a soft newline `\n` that converts to `<br>` in HTML.
 *
 * @param   {EditorState} editorState The DraftJS editor state
 * @returns {EditorState}             The new editor state
 */
function insertSoftNewline(editorState) {
  var newEditorState = editorState;

  // Terminate all current inline styles
  var currentStyleSet = newEditorState.getCurrentInlineStyle();
  newEditorState = currentStyleSet.reduce(function (reducedEditorState, style) {
    return _draftJs.RichUtils.toggleInlineStyle(reducedEditorState, style);
  }, newEditorState);

  // If text is selected, delete text first.
  var selectionState = newEditorState.getSelection();
  var selectionStart = selectionState.getStartOffset();
  var selectionEnd = selectionState.getEndOffset();

  if (selectionEnd - selectionStart !== 0) {
    var contentState = (0, _DraftModifier.removeRange)(newEditorState.getCurrentContent(), selectionState, 'back');

    newEditorState = _draftJs.EditorState.push(newEditorState, contentState, 'backspace-character');
  }

  // Insert a newline
  return _draftJs.RichUtils.insertSoftNewline(newEditorState);
}

/**
 * Toggle an inline style on/off
 *
 * @param   {EditorState} editorState The DraftJS editor state
 * @param   {String} inlineStyle      The inline style string representation
 * @returns {EditorState}             The new editor state
 */
function toggleInlineStyle(editorState, inlineStyle) {
  /*
     * TODO tech-debt. Link toggles should not go via toggleInlineStyle.
     * https://github.com/plotly/streambed/issues/6354
     */

  if (inlineStyle === _configuration.LINK) {
    return toggleLink(editorState);
  }

  // <sub> and <sup> should be mutually exclusive.
  var updatedEditorState = toggleMutuallyExclusiveStyles(editorState, inlineStyle);

  // Add the new style.
  return _draftJs.RichUtils.toggleInlineStyle(updatedEditorState, inlineStyle);
}

/**
 * Toggle a link on/off
 *
 * @param   {EditorState} editorState The DraftJS editor state
 * @returns {EditorState}             The new editor state
 */
function toggleLink(editorState) {
  var selection = editorState.getSelection();

  if (selectionHasLink(editorState, selection)) {
    // Remove link
    return _draftJs.RichUtils.toggleLink(editorState, selection, null);
  }

  // Create a link with an empty URL
  var entityKey = _draftJs.Entity.create(_configuration.LINK, 'MUTABLE', { url: '' });

  return _draftJs.RichUtils.toggleLink(editorState, selection, entityKey);
}

/**
 * For the current selection, if a SUPERSCRIPT or SUBSCRIPT style is
 * to be applied, un-apply the other style.
 *
 * @param {EditorState} editorState The DraftJS editor state
 * @param {String} inlineStyle      Style about to be applied
 * @returns {EditorState}           The new editor state
 */
function toggleMutuallyExclusiveStyles(editorState, inlineStyle) {
  var currentStyleSet = editorState.getCurrentInlineStyle();

  if (inlineStyle === _configuration.SUBSCRIPT && currentStyleSet.includes(_configuration.SUPERSCRIPT)) {
    return _draftJs.RichUtils.toggleInlineStyle(editorState, _configuration.SUPERSCRIPT);
  }

  if (inlineStyle === _configuration.SUPERSCRIPT && currentStyleSet.includes(_configuration.SUBSCRIPT)) {
    return _draftJs.RichUtils.toggleInlineStyle(editorState, _configuration.SUBSCRIPT);
  }

  return editorState;
}
//# sourceMappingURL=DraftCommands.js.map

/***/ }),

/***/ "tQ3M":
/*!***************************************************!*\
  !*** ./node_modules/mdi-react/ContentSaveIcon.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var ContentSaveIcon = function ContentSaveIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M15,9H5V5H15M12,19C10.34,19 9,17.66 9,16C9,14.34 10.34,13 12,13C13.66,13 15,14.34 15,16C15,17.66 13.66,19 12,19M17,3H5C3.89,3 3,3.9 3,5V19C3,20.1 3.9,21 5,21H19C20.1,21 21,20.1 21,19V7L17,3Z' })
  );
};

module.exports = ContentSaveIcon;


/***/ }),

/***/ "tRRp":
/*!************************************************!*\
  !*** ./node_modules/entities/maps/decode.json ***!
  \************************************************/
/*! exports provided: 0, 128, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 158, 159, default */
/***/ (function(module) {

module.exports = {"0":65533,"128":8364,"130":8218,"131":402,"132":8222,"133":8230,"134":8224,"135":8225,"136":710,"137":8240,"138":352,"139":8249,"140":338,"142":381,"145":8216,"146":8217,"147":8220,"148":8221,"149":8226,"150":8211,"151":8212,"152":732,"153":8482,"154":353,"155":8250,"156":339,"158":382,"159":376};

/***/ }),

/***/ "tSWc":
/*!**************************************************!*\
  !*** ./node_modules/hash.js/lib/hash/sha/512.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var utils = __webpack_require__(/*! ../utils */ "w8CP");
var common = __webpack_require__(/*! ../common */ "7ckf");
var assert = __webpack_require__(/*! minimalistic-assert */ "2j6C");

var rotr64_hi = utils.rotr64_hi;
var rotr64_lo = utils.rotr64_lo;
var shr64_hi = utils.shr64_hi;
var shr64_lo = utils.shr64_lo;
var sum64 = utils.sum64;
var sum64_hi = utils.sum64_hi;
var sum64_lo = utils.sum64_lo;
var sum64_4_hi = utils.sum64_4_hi;
var sum64_4_lo = utils.sum64_4_lo;
var sum64_5_hi = utils.sum64_5_hi;
var sum64_5_lo = utils.sum64_5_lo;

var BlockHash = common.BlockHash;

var sha512_K = [
  0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
  0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
  0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
  0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
  0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
  0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
  0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
  0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
  0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
  0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
  0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
  0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
  0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
  0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
  0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
  0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
  0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
  0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
  0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
  0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
  0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
  0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
  0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
  0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
  0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
  0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
  0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
  0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
  0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
  0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
  0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
  0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
  0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
  0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
  0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
  0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
  0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
  0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
  0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
  0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
];

function SHA512() {
  if (!(this instanceof SHA512))
    return new SHA512();

  BlockHash.call(this);
  this.h = [
    0x6a09e667, 0xf3bcc908,
    0xbb67ae85, 0x84caa73b,
    0x3c6ef372, 0xfe94f82b,
    0xa54ff53a, 0x5f1d36f1,
    0x510e527f, 0xade682d1,
    0x9b05688c, 0x2b3e6c1f,
    0x1f83d9ab, 0xfb41bd6b,
    0x5be0cd19, 0x137e2179 ];
  this.k = sha512_K;
  this.W = new Array(160);
}
utils.inherits(SHA512, BlockHash);
module.exports = SHA512;

SHA512.blockSize = 1024;
SHA512.outSize = 512;
SHA512.hmacStrength = 192;
SHA512.padLength = 128;

SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
  var W = this.W;

  // 32 x 32bit words
  for (var i = 0; i < 32; i++)
    W[i] = msg[start + i];
  for (; i < W.length; i += 2) {
    var c0_hi = g1_512_hi(W[i - 4], W[i - 3]);  // i - 2
    var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
    var c1_hi = W[i - 14];  // i - 7
    var c1_lo = W[i - 13];
    var c2_hi = g0_512_hi(W[i - 30], W[i - 29]);  // i - 15
    var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
    var c3_hi = W[i - 32];  // i - 16
    var c3_lo = W[i - 31];

    W[i] = sum64_4_hi(
      c0_hi, c0_lo,
      c1_hi, c1_lo,
      c2_hi, c2_lo,
      c3_hi, c3_lo);
    W[i + 1] = sum64_4_lo(
      c0_hi, c0_lo,
      c1_hi, c1_lo,
      c2_hi, c2_lo,
      c3_hi, c3_lo);
  }
};

SHA512.prototype._update = function _update(msg, start) {
  this._prepareBlock(msg, start);

  var W = this.W;

  var ah = this.h[0];
  var al = this.h[1];
  var bh = this.h[2];
  var bl = this.h[3];
  var ch = this.h[4];
  var cl = this.h[5];
  var dh = this.h[6];
  var dl = this.h[7];
  var eh = this.h[8];
  var el = this.h[9];
  var fh = this.h[10];
  var fl = this.h[11];
  var gh = this.h[12];
  var gl = this.h[13];
  var hh = this.h[14];
  var hl = this.h[15];

  assert(this.k.length === W.length);
  for (var i = 0; i < W.length; i += 2) {
    var c0_hi = hh;
    var c0_lo = hl;
    var c1_hi = s1_512_hi(eh, el);
    var c1_lo = s1_512_lo(eh, el);
    var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);
    var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
    var c3_hi = this.k[i];
    var c3_lo = this.k[i + 1];
    var c4_hi = W[i];
    var c4_lo = W[i + 1];

    var T1_hi = sum64_5_hi(
      c0_hi, c0_lo,
      c1_hi, c1_lo,
      c2_hi, c2_lo,
      c3_hi, c3_lo,
      c4_hi, c4_lo);
    var T1_lo = sum64_5_lo(
      c0_hi, c0_lo,
      c1_hi, c1_lo,
      c2_hi, c2_lo,
      c3_hi, c3_lo,
      c4_hi, c4_lo);

    c0_hi = s0_512_hi(ah, al);
    c0_lo = s0_512_lo(ah, al);
    c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);
    c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);

    var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);
    var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);

    hh = gh;
    hl = gl;

    gh = fh;
    gl = fl;

    fh = eh;
    fl = el;

    eh = sum64_hi(dh, dl, T1_hi, T1_lo);
    el = sum64_lo(dl, dl, T1_hi, T1_lo);

    dh = ch;
    dl = cl;

    ch = bh;
    cl = bl;

    bh = ah;
    bl = al;

    ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);
    al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);
  }

  sum64(this.h, 0, ah, al);
  sum64(this.h, 2, bh, bl);
  sum64(this.h, 4, ch, cl);
  sum64(this.h, 6, dh, dl);
  sum64(this.h, 8, eh, el);
  sum64(this.h, 10, fh, fl);
  sum64(this.h, 12, gh, gl);
  sum64(this.h, 14, hh, hl);
};

SHA512.prototype._digest = function digest(enc) {
  if (enc === 'hex')
    return utils.toHex32(this.h, 'big');
  else
    return utils.split32(this.h, 'big');
};

function ch64_hi(xh, xl, yh, yl, zh) {
  var r = (xh & yh) ^ ((~xh) & zh);
  if (r < 0)
    r += 0x100000000;
  return r;
}

function ch64_lo(xh, xl, yh, yl, zh, zl) {
  var r = (xl & yl) ^ ((~xl) & zl);
  if (r < 0)
    r += 0x100000000;
  return r;
}

function maj64_hi(xh, xl, yh, yl, zh) {
  var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
  if (r < 0)
    r += 0x100000000;
  return r;
}

function maj64_lo(xh, xl, yh, yl, zh, zl) {
  var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
  if (r < 0)
    r += 0x100000000;
  return r;
}

function s0_512_hi(xh, xl) {
  var c0_hi = rotr64_hi(xh, xl, 28);
  var c1_hi = rotr64_hi(xl, xh, 2);  // 34
  var c2_hi = rotr64_hi(xl, xh, 7);  // 39

  var r = c0_hi ^ c1_hi ^ c2_hi;
  if (r < 0)
    r += 0x100000000;
  return r;
}

function s0_512_lo(xh, xl) {
  var c0_lo = rotr64_lo(xh, xl, 28);
  var c1_lo = rotr64_lo(xl, xh, 2);  // 34
  var c2_lo = rotr64_lo(xl, xh, 7);  // 39

  var r = c0_lo ^ c1_lo ^ c2_lo;
  if (r < 0)
    r += 0x100000000;
  return r;
}

function s1_512_hi(xh, xl) {
  var c0_hi = rotr64_hi(xh, xl, 14);
  var c1_hi = rotr64_hi(xh, xl, 18);
  var c2_hi = rotr64_hi(xl, xh, 9);  // 41

  var r = c0_hi ^ c1_hi ^ c2_hi;
  if (r < 0)
    r += 0x100000000;
  return r;
}

function s1_512_lo(xh, xl) {
  var c0_lo = rotr64_lo(xh, xl, 14);
  var c1_lo = rotr64_lo(xh, xl, 18);
  var c2_lo = rotr64_lo(xl, xh, 9);  // 41

  var r = c0_lo ^ c1_lo ^ c2_lo;
  if (r < 0)
    r += 0x100000000;
  return r;
}

function g0_512_hi(xh, xl) {
  var c0_hi = rotr64_hi(xh, xl, 1);
  var c1_hi = rotr64_hi(xh, xl, 8);
  var c2_hi = shr64_hi(xh, xl, 7);

  var r = c0_hi ^ c1_hi ^ c2_hi;
  if (r < 0)
    r += 0x100000000;
  return r;
}

function g0_512_lo(xh, xl) {
  var c0_lo = rotr64_lo(xh, xl, 1);
  var c1_lo = rotr64_lo(xh, xl, 8);
  var c2_lo = shr64_lo(xh, xl, 7);

  var r = c0_lo ^ c1_lo ^ c2_lo;
  if (r < 0)
    r += 0x100000000;
  return r;
}

function g1_512_hi(xh, xl) {
  var c0_hi = rotr64_hi(xh, xl, 19);
  var c1_hi = rotr64_hi(xl, xh, 29);  // 61
  var c2_hi = shr64_hi(xh, xl, 6);

  var r = c0_hi ^ c1_hi ^ c2_hi;
  if (r < 0)
    r += 0x100000000;
  return r;
}

function g1_512_lo(xh, xl) {
  var c0_lo = rotr64_lo(xh, xl, 19);
  var c1_lo = rotr64_lo(xl, xh, 29);  // 61
  var c2_lo = shr64_lo(xh, xl, 6);

  var r = c0_lo ^ c1_lo ^ c2_lo;
  if (r < 0)
    r += 0x100000000;
  return r;
}


/***/ }),

/***/ "tT1j":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/coreutils/lib/statedb.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
/* tslint:disable */
/**
 * The default state database token.
 */
exports.IStateDB = new coreutils_1.Token('@jupyterlab/coreutils:IStateDB');
/**
 * The default concrete implementation of a state database.
 */
class StateDB {
    /**
     * Create a new state database.
     *
     * @param options - The instantiation options for a state database.
     */
    constructor(options) {
        /**
         * The maximum allowed length of the data after it has been serialized.
         */
        this.maxLength = 2000;
        this._changed = new signaling_1.Signal(this);
        const { namespace, transform, windowName } = options;
        this.namespace = namespace;
        this._window = windowName || '';
        this._ready = (transform || Promise.resolve(null)).then(transformation => {
            if (!transformation) {
                return;
            }
            const { contents, type } = transformation;
            switch (type) {
                case 'cancel':
                    return;
                case 'clear':
                    this._clear();
                    return;
                case 'merge':
                    this._merge(contents || {});
                    return;
                case 'overwrite':
                    this._overwrite(contents || {});
                    return;
                default:
                    return;
            }
        });
    }
    /**
     * A signal that emits the change type any time a value changes.
     */
    get changed() {
        return this._changed;
    }
    /**
     * Clear the entire database.
     */
    clear(silent = false) {
        return this._ready.then(() => {
            this._clear();
            if (silent) {
                return;
            }
            this._changed.emit({ id: null, type: 'clear' });
        });
    }
    /**
     * Retrieve a saved bundle from the database.
     *
     * @param id - The identifier used to retrieve a data bundle.
     *
     * @returns A promise that bears a data payload if available.
     *
     * #### Notes
     * The `id` values of stored items in the state database are formatted:
     * `'namespace:identifier'`, which is the same convention that command
     * identifiers in JupyterLab use as well. While this is not a technical
     * requirement for `fetch()`, `remove()`, and `save()`, it *is* necessary for
     * using the `fetchNamespace()` method.
     *
     * The promise returned by this method may be rejected if an error occurs in
     * retrieving the data. Non-existence of an `id` will succeed with `null`.
     */
    fetch(id) {
        return this._ready.then(() => this._fetch(id));
    }
    /**
     * Retrieve all the saved bundles for a namespace.
     *
     * @param namespace - The namespace to retrieve.
     *
     * @returns A promise that bears a collection of payloads for a namespace.
     *
     * #### Notes
     * Namespaces are entirely conventional entities. The `id` values of stored
     * items in the state database are formatted: `'namespace:identifier'`, which
     * is the same convention that command identifiers in JupyterLab use as well.
     *
     * If there are any errors in retrieving the data, they will be logged to the
     * console in order to optimistically return any extant data without failing.
     * This promise will always succeed.
     */
    fetchNamespace(namespace) {
        return this._ready.then(() => {
            const prefix = `${this._window}:${this.namespace}:`;
            const mask = (key) => key.replace(prefix, '');
            return StateDB.fetchNamespace(`${prefix}${namespace}:`, mask);
        });
    }
    /**
     * Remove a value from the database.
     *
     * @param id - The identifier for the data being removed.
     *
     * @returns A promise that is rejected if remove fails and succeeds otherwise.
     */
    remove(id) {
        return this._ready.then(() => {
            this._remove(id);
            this._changed.emit({ id, type: 'remove' });
        });
    }
    /**
     * Save a value in the database.
     *
     * @param id - The identifier for the data being saved.
     *
     * @param value - The data being saved.
     *
     * @returns A promise that is rejected if saving fails and succeeds otherwise.
     *
     * #### Notes
     * The `id` values of stored items in the state database are formatted:
     * `'namespace:identifier'`, which is the same convention that command
     * identifiers in JupyterLab use as well. While this is not a technical
     * requirement for `fetch()`, `remove()`, and `save()`, it *is* necessary for
     * using the `fetchNamespace()` method.
     */
    save(id, value) {
        return this._ready.then(() => {
            this._save(id, value);
            this._changed.emit({ id, type: 'save' });
        });
    }
    /**
     * Return a serialized copy of the state database's entire contents.
     *
     * @returns A promise that bears the database contents as JSON.
     */
    toJSON() {
        return this._ready.then(() => {
            const prefix = `${this._window}:${this.namespace}:`;
            const mask = (key) => key.replace(prefix, '');
            return StateDB.toJSON(prefix, mask);
        });
    }
    /**
     * Clear the entire database.
     *
     * #### Notes
     * Unlike the public `clear` method, this method is synchronous.
     */
    _clear() {
        const { localStorage } = window;
        const prefix = `${this._window}:${this.namespace}:`;
        let i = localStorage.length;
        while (i) {
            let key = localStorage.key(--i);
            if (key && key.indexOf(prefix) === 0) {
                localStorage.removeItem(key);
            }
        }
    }
    /**
     * Fetch a value from the database.
     *
     * #### Notes
     * Unlike the public `fetch` method, this method is synchronous.
     */
    _fetch(id) {
        const key = `${this._window}:${this.namespace}:${id}`;
        const value = window.localStorage.getItem(key);
        if (value) {
            const envelope = JSON.parse(value);
            return envelope.v;
        }
        return undefined;
    }
    /**
     * Merge data into the state database.
     */
    _merge(contents) {
        Object.keys(contents).forEach(key => {
            this._save(key, contents[key]);
        });
    }
    /**
     * Overwrite the entire database with new contents.
     */
    _overwrite(contents) {
        this._clear();
        this._merge(contents);
    }
    /**
     * Remove a key in the database.
     *
     * #### Notes
     * Unlike the public `remove` method, this method is synchronous.
     */
    _remove(id) {
        const key = `${this._window}:${this.namespace}:${id}`;
        window.localStorage.removeItem(key);
    }
    /**
     * Save a key and its value in the database.
     *
     * #### Notes
     * Unlike the public `save` method, this method is synchronous.
     */
    _save(id, value) {
        const key = `${this._window}:${this.namespace}:${id}`;
        const envelope = { v: value };
        const serialized = JSON.stringify(envelope);
        const length = serialized.length;
        const max = this.maxLength;
        if (length > max) {
            throw new Error(`Data length (${length}) exceeds maximum (${max})`);
        }
        window.localStorage.setItem(key, serialized);
    }
}
exports.StateDB = StateDB;
/**
 * A namespace for StateDB statics.
 */
(function (StateDB) {
    /**
     * Retrieve all the saved bundles for a given namespace in local storage.
     *
     * @param prefix - The namespace to retrieve.
     *
     * @param mask - Optional mask function to transform each key retrieved.
     *
     * @returns A collection of data payloads for a given prefix.
     *
     * #### Notes
     * If there are any errors in retrieving the data, they will be logged to the
     * console in order to optimistically return any extant data without failing.
     */
    function fetchNamespace(namespace, mask = key => key) {
        const { localStorage } = window;
        let items = [];
        let i = localStorage.length;
        while (i) {
            let key = localStorage.key(--i);
            if (key && key.indexOf(namespace) === 0) {
                let value = localStorage.getItem(key);
                try {
                    let envelope = JSON.parse(value);
                    items.push({
                        id: mask(key),
                        value: envelope ? envelope.v : undefined
                    });
                }
                catch (error) {
                    console.warn(error);
                    localStorage.removeItem(key);
                }
            }
        }
        return items;
    }
    StateDB.fetchNamespace = fetchNamespace;
    /**
     * Return a serialized copy of a namespace's contents from local storage.
     *
     * @returns The namespace contents as JSON.
     */
    function toJSON(namespace, mask = key => key) {
        return fetchNamespace(namespace, mask).reduce((acc, val) => {
            acc[val.id] = val.value;
            return acc;
        }, {});
    }
    StateDB.toJSON = toJSON;
})(StateDB = exports.StateDB || (exports.StateDB = {}));


/***/ }),

/***/ "tT3J":
/*!************************************************!*\
  !*** ./node_modules/moment/locale/tzm-latn.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var tzmLatn = moment.defineLocale('tzm-latn', {
    months : 'innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir'.split('_'),
    monthsShort : 'innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir'.split('_'),
    weekdays : 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'),
    weekdaysShort : 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'),
    weekdaysMin : 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay: '[asdkh g] LT',
        nextDay: '[aska g] LT',
        nextWeek: 'dddd [g] LT',
        lastDay: '[assant g] LT',
        lastWeek: 'dddd [g] LT',
        sameElse: 'L'
    },
    relativeTime : {
        future : 'dadkh s yan %s',
        past : 'yan %s',
        s : 'imik',
        ss : '%d imik',
        m : 'minuḍ',
        mm : '%d minuḍ',
        h : 'saɛa',
        hh : '%d tassaɛin',
        d : 'ass',
        dd : '%d ossan',
        M : 'ayowr',
        MM : '%d iyyirn',
        y : 'asgas',
        yy : '%d isgasn'
    },
    week : {
        dow : 6, // Saturday is the first day of the week.
        doy : 12  // The week that contains Jan 1st is the first week of the year.
    }
});

return tzmLatn;

})));


/***/ }),

/***/ "tUCv":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/jv.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var jv = moment.defineLocale('jv', {
    months : 'Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_Nopember_Desember'.split('_'),
    monthsShort : 'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nop_Des'.split('_'),
    weekdays : 'Minggu_Senen_Seloso_Rebu_Kemis_Jemuwah_Septu'.split('_'),
    weekdaysShort : 'Min_Sen_Sel_Reb_Kem_Jem_Sep'.split('_'),
    weekdaysMin : 'Mg_Sn_Sl_Rb_Km_Jm_Sp'.split('_'),
    longDateFormat : {
        LT : 'HH.mm',
        LTS : 'HH.mm.ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY [pukul] HH.mm',
        LLLL : 'dddd, D MMMM YYYY [pukul] HH.mm'
    },
    meridiemParse: /enjing|siyang|sonten|ndalu/,
    meridiemHour : function (hour, meridiem) {
        if (hour === 12) {
            hour = 0;
        }
        if (meridiem === 'enjing') {
            return hour;
        } else if (meridiem === 'siyang') {
            return hour >= 11 ? hour : hour + 12;
        } else if (meridiem === 'sonten' || meridiem === 'ndalu') {
            return hour + 12;
        }
    },
    meridiem : function (hours, minutes, isLower) {
        if (hours < 11) {
            return 'enjing';
        } else if (hours < 15) {
            return 'siyang';
        } else if (hours < 19) {
            return 'sonten';
        } else {
            return 'ndalu';
        }
    },
    calendar : {
        sameDay : '[Dinten puniko pukul] LT',
        nextDay : '[Mbenjang pukul] LT',
        nextWeek : 'dddd [pukul] LT',
        lastDay : '[Kala wingi pukul] LT',
        lastWeek : 'dddd [kepengker pukul] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'wonten ing %s',
        past : '%s ingkang kepengker',
        s : 'sawetawis detik',
        ss : '%d detik',
        m : 'setunggal menit',
        mm : '%d menit',
        h : 'setunggal jam',
        hh : '%d jam',
        d : 'sedinten',
        dd : '%d dinten',
        M : 'sewulan',
        MM : '%d wulan',
        y : 'setaun',
        yy : '%d taun'
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return jv;

})));


/***/ }),

/***/ "taFK":
/*!*******************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/ZoomMinusIcon.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var ZoomMinusIcon = function ZoomMinusIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 16 16' }, props),
        _react2.default.createElement('path', { d: 'M.004 1v14h14V1h-14zM11 9H3V7h8v2z' })
    );
};

exports.default = ZoomMinusIcon;

/***/ }),

/***/ "tadb":
/*!******************************************!*\
  !*** ./node_modules/lodash/_DataView.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getNative = __webpack_require__(/*! ./_getNative */ "Cwc5"),
    root = __webpack_require__(/*! ./_root */ "Kz5y");

/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView');

module.exports = DataView;


/***/ }),

/***/ "tcrS":
/*!*****************************************!*\
  !*** ./node_modules/ripemd160/index.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var Buffer = __webpack_require__(/*! buffer */ "tjlA").Buffer
var inherits = __webpack_require__(/*! inherits */ "P7XM")
var HashBase = __webpack_require__(/*! hash-base */ "k+aG")

var ARRAY16 = new Array(16)

var zl = [
  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
  7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
  3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
  1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
  4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
]

var zr = [
  5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
  6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
  15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
  8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
  12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
]

var sl = [
  11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
  7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
  11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
  11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
  9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
]

var sr = [
  8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
  9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
  9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
  15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
  8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
]

var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]
var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]

function RIPEMD160 () {
  HashBase.call(this, 64)

  // state
  this._a = 0x67452301
  this._b = 0xefcdab89
  this._c = 0x98badcfe
  this._d = 0x10325476
  this._e = 0xc3d2e1f0
}

inherits(RIPEMD160, HashBase)

RIPEMD160.prototype._update = function () {
  var words = ARRAY16
  for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4)

  var al = this._a | 0
  var bl = this._b | 0
  var cl = this._c | 0
  var dl = this._d | 0
  var el = this._e | 0

  var ar = this._a | 0
  var br = this._b | 0
  var cr = this._c | 0
  var dr = this._d | 0
  var er = this._e | 0

  // computation
  for (var i = 0; i < 80; i += 1) {
    var tl
    var tr
    if (i < 16) {
      tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i])
      tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i])
    } else if (i < 32) {
      tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i])
      tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i])
    } else if (i < 48) {
      tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i])
      tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i])
    } else if (i < 64) {
      tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i])
      tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i])
    } else { // if (i<80) {
      tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i])
      tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i])
    }

    al = el
    el = dl
    dl = rotl(cl, 10)
    cl = bl
    bl = tl

    ar = er
    er = dr
    dr = rotl(cr, 10)
    cr = br
    br = tr
  }

  // update state
  var t = (this._b + cl + dr) | 0
  this._b = (this._c + dl + er) | 0
  this._c = (this._d + el + ar) | 0
  this._d = (this._e + al + br) | 0
  this._e = (this._a + bl + cr) | 0
  this._a = t
}

RIPEMD160.prototype._digest = function () {
  // create padding and handle blocks
  this._block[this._blockOffset++] = 0x80
  if (this._blockOffset > 56) {
    this._block.fill(0, this._blockOffset, 64)
    this._update()
    this._blockOffset = 0
  }

  this._block.fill(0, this._blockOffset, 56)
  this._block.writeUInt32LE(this._length[0], 56)
  this._block.writeUInt32LE(this._length[1], 60)
  this._update()

  // produce result
  var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20)
  buffer.writeInt32LE(this._a, 0)
  buffer.writeInt32LE(this._b, 4)
  buffer.writeInt32LE(this._c, 8)
  buffer.writeInt32LE(this._d, 12)
  buffer.writeInt32LE(this._e, 16)
  return buffer
}

function rotl (x, n) {
  return (x << n) | (x >>> (32 - n))
}

function fn1 (a, b, c, d, e, m, k, s) {
  return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0
}

function fn2 (a, b, c, d, e, m, k, s) {
  return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0
}

function fn3 (a, b, c, d, e, m, k, s) {
  return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0
}

function fn4 (a, b, c, d, e, m, k, s) {
  return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0
}

function fn5 (a, b, c, d, e, m, k, s) {
  return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0
}

module.exports = RIPEMD160


/***/ }),

/***/ "thcq":
/*!**************************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/warn-once.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.default = warnOnce;
var printed = {};

function warnOnce(message) {
    if (printed[message]) return;
    printed[message] = true;

    if (typeof console !== 'undefined' && console.warn) console.warn(message);
}
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndhcm4tb25jZS5lczYiXSwibmFtZXMiOlsid2Fybk9uY2UiLCJwcmludGVkIiwibWVzc2FnZSIsImNvbnNvbGUiLCJ3YXJuIl0sIm1hcHBpbmdzIjoiOzs7a0JBRXdCQSxRO0FBRnhCLElBQUlDLFVBQVUsRUFBZDs7QUFFZSxTQUFTRCxRQUFULENBQWtCRSxPQUFsQixFQUEyQjtBQUN0QyxRQUFLRCxRQUFRQyxPQUFSLENBQUwsRUFBd0I7QUFDeEJELFlBQVFDLE9BQVIsSUFBbUIsSUFBbkI7O0FBRUEsUUFBSyxPQUFPQyxPQUFQLEtBQW1CLFdBQW5CLElBQWtDQSxRQUFRQyxJQUEvQyxFQUFzREQsUUFBUUMsSUFBUixDQUFhRixPQUFiO0FBQ3pEIiwiZmlsZSI6Indhcm4tb25jZS5qcyIsInNvdXJjZXNDb250ZW50IjpbImxldCBwcmludGVkID0geyB9O1xuXG5leHBvcnQgZGVmYXVsdCBmdW5jdGlvbiB3YXJuT25jZShtZXNzYWdlKSB7XG4gICAgaWYgKCBwcmludGVkW21lc3NhZ2VdICkgcmV0dXJuO1xuICAgIHByaW50ZWRbbWVzc2FnZV0gPSB0cnVlO1xuXG4gICAgaWYgKCB0eXBlb2YgY29uc29sZSAhPT0gJ3VuZGVmaW5lZCcgJiYgY29uc29sZS53YXJuICkgY29uc29sZS53YXJuKG1lc3NhZ2UpO1xufVxuIl19


/***/ }),

/***/ "thoC":
/*!**************************************************!*\
  !*** ./node_modules/mdi-react/CodeBracesIcon.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var CodeBracesIcon = function CodeBracesIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M8,3C6.9,3 6,3.9 6,5V9C6,10.1 5.1,11 4,11H3V13H4C5.1,13 6,13.9 6,15V19C6,20.1 6.9,21 8,21H10V19H8V14C8,12.9 7.1,12 6,12C7.1,12 8,11.1 8,10V5H10V3M16,3C17.1,3 18,3.9 18,5V9C18,10.1 18.9,11 20,11H21V13H20C18.9,13 18,13.9 18,15V19C18,20.1 17.1,21 16,21H14V19H16V14C16,12.9 16.9,12 18,12C16.9,12 16,11.1 16,10V5H14V3H16Z' })
  );
};

module.exports = CodeBracesIcon;


/***/ }),

/***/ "tjlA":
/*!**************************************!*\
  !*** ./node_modules/buffer/index.js ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
 * @license  MIT
 */
/* eslint-disable no-proto */



var base64 = __webpack_require__(/*! base64-js */ "H7XF")
var ieee754 = __webpack_require__(/*! ieee754 */ "kVK+")
var isArray = __webpack_require__(/*! isarray */ "IzUq")

exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50

/**
 * If `Buffer.TYPED_ARRAY_SUPPORT`:
 *   === true    Use Uint8Array implementation (fastest)
 *   === false   Use Object implementation (most compatible, even IE6)
 *
 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
 * Opera 11.6+, iOS 4.2+.
 *
 * Due to various browser bugs, sometimes the Object implementation will be used even
 * when the browser supports typed arrays.
 *
 * Note:
 *
 *   - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
 *     See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
 *
 *   - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
 *
 *   - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
 *     incorrect length in some situations.

 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
 * get the Object implementation, which is slower but behaves correctly.
 */
Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  ? global.TYPED_ARRAY_SUPPORT
  : typedArraySupport()

/*
 * Export kMaxLength after typed array support is determined.
 */
exports.kMaxLength = kMaxLength()

function typedArraySupport () {
  try {
    var arr = new Uint8Array(1)
    arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
    return arr.foo() === 42 && // typed array instances can be augmented
        typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
        arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  } catch (e) {
    return false
  }
}

function kMaxLength () {
  return Buffer.TYPED_ARRAY_SUPPORT
    ? 0x7fffffff
    : 0x3fffffff
}

function createBuffer (that, length) {
  if (kMaxLength() < length) {
    throw new RangeError('Invalid typed array length')
  }
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    // Return an augmented `Uint8Array` instance, for best performance
    that = new Uint8Array(length)
    that.__proto__ = Buffer.prototype
  } else {
    // Fallback: Return an object instance of the Buffer class
    if (that === null) {
      that = new Buffer(length)
    }
    that.length = length
  }

  return that
}

/**
 * The Buffer constructor returns instances of `Uint8Array` that have their
 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
 * returns a single octet.
 *
 * The `Uint8Array` prototype remains unmodified.
 */

function Buffer (arg, encodingOrOffset, length) {
  if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
    return new Buffer(arg, encodingOrOffset, length)
  }

  // Common case.
  if (typeof arg === 'number') {
    if (typeof encodingOrOffset === 'string') {
      throw new Error(
        'If encoding is specified then the first argument must be a string'
      )
    }
    return allocUnsafe(this, arg)
  }
  return from(this, arg, encodingOrOffset, length)
}

Buffer.poolSize = 8192 // not used by this implementation

// TODO: Legacy, not needed anymore. Remove in next major version.
Buffer._augment = function (arr) {
  arr.__proto__ = Buffer.prototype
  return arr
}

function from (that, value, encodingOrOffset, length) {
  if (typeof value === 'number') {
    throw new TypeError('"value" argument must not be a number')
  }

  if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
    return fromArrayBuffer(that, value, encodingOrOffset, length)
  }

  if (typeof value === 'string') {
    return fromString(that, value, encodingOrOffset)
  }

  return fromObject(that, value)
}

/**
 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
 * if value is a number.
 * Buffer.from(str[, encoding])
 * Buffer.from(array)
 * Buffer.from(buffer)
 * Buffer.from(arrayBuffer[, byteOffset[, length]])
 **/
Buffer.from = function (value, encodingOrOffset, length) {
  return from(null, value, encodingOrOffset, length)
}

if (Buffer.TYPED_ARRAY_SUPPORT) {
  Buffer.prototype.__proto__ = Uint8Array.prototype
  Buffer.__proto__ = Uint8Array
  if (typeof Symbol !== 'undefined' && Symbol.species &&
      Buffer[Symbol.species] === Buffer) {
    // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
    Object.defineProperty(Buffer, Symbol.species, {
      value: null,
      configurable: true
    })
  }
}

function assertSize (size) {
  if (typeof size !== 'number') {
    throw new TypeError('"size" argument must be a number')
  } else if (size < 0) {
    throw new RangeError('"size" argument must not be negative')
  }
}

function alloc (that, size, fill, encoding) {
  assertSize(size)
  if (size <= 0) {
    return createBuffer(that, size)
  }
  if (fill !== undefined) {
    // Only pay attention to encoding if it's a string. This
    // prevents accidentally sending in a number that would
    // be interpretted as a start offset.
    return typeof encoding === 'string'
      ? createBuffer(that, size).fill(fill, encoding)
      : createBuffer(that, size).fill(fill)
  }
  return createBuffer(that, size)
}

/**
 * Creates a new filled Buffer instance.
 * alloc(size[, fill[, encoding]])
 **/
Buffer.alloc = function (size, fill, encoding) {
  return alloc(null, size, fill, encoding)
}

function allocUnsafe (that, size) {
  assertSize(size)
  that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  if (!Buffer.TYPED_ARRAY_SUPPORT) {
    for (var i = 0; i < size; ++i) {
      that[i] = 0
    }
  }
  return that
}

/**
 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
 * */
Buffer.allocUnsafe = function (size) {
  return allocUnsafe(null, size)
}
/**
 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
 */
Buffer.allocUnsafeSlow = function (size) {
  return allocUnsafe(null, size)
}

function fromString (that, string, encoding) {
  if (typeof encoding !== 'string' || encoding === '') {
    encoding = 'utf8'
  }

  if (!Buffer.isEncoding(encoding)) {
    throw new TypeError('"encoding" must be a valid string encoding')
  }

  var length = byteLength(string, encoding) | 0
  that = createBuffer(that, length)

  var actual = that.write(string, encoding)

  if (actual !== length) {
    // Writing a hex string, for example, that contains invalid characters will
    // cause everything after the first invalid character to be ignored. (e.g.
    // 'abxxcd' will be treated as 'ab')
    that = that.slice(0, actual)
  }

  return that
}

function fromArrayLike (that, array) {
  var length = array.length < 0 ? 0 : checked(array.length) | 0
  that = createBuffer(that, length)
  for (var i = 0; i < length; i += 1) {
    that[i] = array[i] & 255
  }
  return that
}

function fromArrayBuffer (that, array, byteOffset, length) {
  array.byteLength // this throws if `array` is not a valid ArrayBuffer

  if (byteOffset < 0 || array.byteLength < byteOffset) {
    throw new RangeError('\'offset\' is out of bounds')
  }

  if (array.byteLength < byteOffset + (length || 0)) {
    throw new RangeError('\'length\' is out of bounds')
  }

  if (byteOffset === undefined && length === undefined) {
    array = new Uint8Array(array)
  } else if (length === undefined) {
    array = new Uint8Array(array, byteOffset)
  } else {
    array = new Uint8Array(array, byteOffset, length)
  }

  if (Buffer.TYPED_ARRAY_SUPPORT) {
    // Return an augmented `Uint8Array` instance, for best performance
    that = array
    that.__proto__ = Buffer.prototype
  } else {
    // Fallback: Return an object instance of the Buffer class
    that = fromArrayLike(that, array)
  }
  return that
}

function fromObject (that, obj) {
  if (Buffer.isBuffer(obj)) {
    var len = checked(obj.length) | 0
    that = createBuffer(that, len)

    if (that.length === 0) {
      return that
    }

    obj.copy(that, 0, 0, len)
    return that
  }

  if (obj) {
    if ((typeof ArrayBuffer !== 'undefined' &&
        obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
      if (typeof obj.length !== 'number' || isnan(obj.length)) {
        return createBuffer(that, 0)
      }
      return fromArrayLike(that, obj)
    }

    if (obj.type === 'Buffer' && isArray(obj.data)) {
      return fromArrayLike(that, obj.data)
    }
  }

  throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}

function checked (length) {
  // Note: cannot use `length < kMaxLength()` here because that fails when
  // length is NaN (which is otherwise coerced to zero.)
  if (length >= kMaxLength()) {
    throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
                         'size: 0x' + kMaxLength().toString(16) + ' bytes')
  }
  return length | 0
}

function SlowBuffer (length) {
  if (+length != length) { // eslint-disable-line eqeqeq
    length = 0
  }
  return Buffer.alloc(+length)
}

Buffer.isBuffer = function isBuffer (b) {
  return !!(b != null && b._isBuffer)
}

Buffer.compare = function compare (a, b) {
  if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
    throw new TypeError('Arguments must be Buffers')
  }

  if (a === b) return 0

  var x = a.length
  var y = b.length

  for (var i = 0, len = Math.min(x, y); i < len; ++i) {
    if (a[i] !== b[i]) {
      x = a[i]
      y = b[i]
      break
    }
  }

  if (x < y) return -1
  if (y < x) return 1
  return 0
}

Buffer.isEncoding = function isEncoding (encoding) {
  switch (String(encoding).toLowerCase()) {
    case 'hex':
    case 'utf8':
    case 'utf-8':
    case 'ascii':
    case 'latin1':
    case 'binary':
    case 'base64':
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return true
    default:
      return false
  }
}

Buffer.concat = function concat (list, length) {
  if (!isArray(list)) {
    throw new TypeError('"list" argument must be an Array of Buffers')
  }

  if (list.length === 0) {
    return Buffer.alloc(0)
  }

  var i
  if (length === undefined) {
    length = 0
    for (i = 0; i < list.length; ++i) {
      length += list[i].length
    }
  }

  var buffer = Buffer.allocUnsafe(length)
  var pos = 0
  for (i = 0; i < list.length; ++i) {
    var buf = list[i]
    if (!Buffer.isBuffer(buf)) {
      throw new TypeError('"list" argument must be an Array of Buffers')
    }
    buf.copy(buffer, pos)
    pos += buf.length
  }
  return buffer
}

function byteLength (string, encoding) {
  if (Buffer.isBuffer(string)) {
    return string.length
  }
  if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
      (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
    return string.byteLength
  }
  if (typeof string !== 'string') {
    string = '' + string
  }

  var len = string.length
  if (len === 0) return 0

  // Use a for loop to avoid recursion
  var loweredCase = false
  for (;;) {
    switch (encoding) {
      case 'ascii':
      case 'latin1':
      case 'binary':
        return len
      case 'utf8':
      case 'utf-8':
      case undefined:
        return utf8ToBytes(string).length
      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return len * 2
      case 'hex':
        return len >>> 1
      case 'base64':
        return base64ToBytes(string).length
      default:
        if (loweredCase) return utf8ToBytes(string).length // assume utf8
        encoding = ('' + encoding).toLowerCase()
        loweredCase = true
    }
  }
}
Buffer.byteLength = byteLength

function slowToString (encoding, start, end) {
  var loweredCase = false

  // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  // property of a typed array.

  // This behaves neither like String nor Uint8Array in that we set start/end
  // to their upper/lower bounds if the value passed is out of range.
  // undefined is handled specially as per ECMA-262 6th Edition,
  // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  if (start === undefined || start < 0) {
    start = 0
  }
  // Return early if start > this.length. Done here to prevent potential uint32
  // coercion fail below.
  if (start > this.length) {
    return ''
  }

  if (end === undefined || end > this.length) {
    end = this.length
  }

  if (end <= 0) {
    return ''
  }

  // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  end >>>= 0
  start >>>= 0

  if (end <= start) {
    return ''
  }

  if (!encoding) encoding = 'utf8'

  while (true) {
    switch (encoding) {
      case 'hex':
        return hexSlice(this, start, end)

      case 'utf8':
      case 'utf-8':
        return utf8Slice(this, start, end)

      case 'ascii':
        return asciiSlice(this, start, end)

      case 'latin1':
      case 'binary':
        return latin1Slice(this, start, end)

      case 'base64':
        return base64Slice(this, start, end)

      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return utf16leSlice(this, start, end)

      default:
        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
        encoding = (encoding + '').toLowerCase()
        loweredCase = true
    }
  }
}

// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
// Buffer instances.
Buffer.prototype._isBuffer = true

function swap (b, n, m) {
  var i = b[n]
  b[n] = b[m]
  b[m] = i
}

Buffer.prototype.swap16 = function swap16 () {
  var len = this.length
  if (len % 2 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 16-bits')
  }
  for (var i = 0; i < len; i += 2) {
    swap(this, i, i + 1)
  }
  return this
}

Buffer.prototype.swap32 = function swap32 () {
  var len = this.length
  if (len % 4 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 32-bits')
  }
  for (var i = 0; i < len; i += 4) {
    swap(this, i, i + 3)
    swap(this, i + 1, i + 2)
  }
  return this
}

Buffer.prototype.swap64 = function swap64 () {
  var len = this.length
  if (len % 8 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 64-bits')
  }
  for (var i = 0; i < len; i += 8) {
    swap(this, i, i + 7)
    swap(this, i + 1, i + 6)
    swap(this, i + 2, i + 5)
    swap(this, i + 3, i + 4)
  }
  return this
}

Buffer.prototype.toString = function toString () {
  var length = this.length | 0
  if (length === 0) return ''
  if (arguments.length === 0) return utf8Slice(this, 0, length)
  return slowToString.apply(this, arguments)
}

Buffer.prototype.equals = function equals (b) {
  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  if (this === b) return true
  return Buffer.compare(this, b) === 0
}

Buffer.prototype.inspect = function inspect () {
  var str = ''
  var max = exports.INSPECT_MAX_BYTES
  if (this.length > 0) {
    str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
    if (this.length > max) str += ' ... '
  }
  return '<Buffer ' + str + '>'
}

Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  if (!Buffer.isBuffer(target)) {
    throw new TypeError('Argument must be a Buffer')
  }

  if (start === undefined) {
    start = 0
  }
  if (end === undefined) {
    end = target ? target.length : 0
  }
  if (thisStart === undefined) {
    thisStart = 0
  }
  if (thisEnd === undefined) {
    thisEnd = this.length
  }

  if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
    throw new RangeError('out of range index')
  }

  if (thisStart >= thisEnd && start >= end) {
    return 0
  }
  if (thisStart >= thisEnd) {
    return -1
  }
  if (start >= end) {
    return 1
  }

  start >>>= 0
  end >>>= 0
  thisStart >>>= 0
  thisEnd >>>= 0

  if (this === target) return 0

  var x = thisEnd - thisStart
  var y = end - start
  var len = Math.min(x, y)

  var thisCopy = this.slice(thisStart, thisEnd)
  var targetCopy = target.slice(start, end)

  for (var i = 0; i < len; ++i) {
    if (thisCopy[i] !== targetCopy[i]) {
      x = thisCopy[i]
      y = targetCopy[i]
      break
    }
  }

  if (x < y) return -1
  if (y < x) return 1
  return 0
}

// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  // Empty buffer means no match
  if (buffer.length === 0) return -1

  // Normalize byteOffset
  if (typeof byteOffset === 'string') {
    encoding = byteOffset
    byteOffset = 0
  } else if (byteOffset > 0x7fffffff) {
    byteOffset = 0x7fffffff
  } else if (byteOffset < -0x80000000) {
    byteOffset = -0x80000000
  }
  byteOffset = +byteOffset  // Coerce to Number.
  if (isNaN(byteOffset)) {
    // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
    byteOffset = dir ? 0 : (buffer.length - 1)
  }

  // Normalize byteOffset: negative offsets start from the end of the buffer
  if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  if (byteOffset >= buffer.length) {
    if (dir) return -1
    else byteOffset = buffer.length - 1
  } else if (byteOffset < 0) {
    if (dir) byteOffset = 0
    else return -1
  }

  // Normalize val
  if (typeof val === 'string') {
    val = Buffer.from(val, encoding)
  }

  // Finally, search either indexOf (if dir is true) or lastIndexOf
  if (Buffer.isBuffer(val)) {
    // Special case: looking for empty string/buffer always fails
    if (val.length === 0) {
      return -1
    }
    return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  } else if (typeof val === 'number') {
    val = val & 0xFF // Search for a byte value [0-255]
    if (Buffer.TYPED_ARRAY_SUPPORT &&
        typeof Uint8Array.prototype.indexOf === 'function') {
      if (dir) {
        return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
      } else {
        return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
      }
    }
    return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  }

  throw new TypeError('val must be string, number or Buffer')
}

function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  var indexSize = 1
  var arrLength = arr.length
  var valLength = val.length

  if (encoding !== undefined) {
    encoding = String(encoding).toLowerCase()
    if (encoding === 'ucs2' || encoding === 'ucs-2' ||
        encoding === 'utf16le' || encoding === 'utf-16le') {
      if (arr.length < 2 || val.length < 2) {
        return -1
      }
      indexSize = 2
      arrLength /= 2
      valLength /= 2
      byteOffset /= 2
    }
  }

  function read (buf, i) {
    if (indexSize === 1) {
      return buf[i]
    } else {
      return buf.readUInt16BE(i * indexSize)
    }
  }

  var i
  if (dir) {
    var foundIndex = -1
    for (i = byteOffset; i < arrLength; i++) {
      if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
        if (foundIndex === -1) foundIndex = i
        if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
      } else {
        if (foundIndex !== -1) i -= i - foundIndex
        foundIndex = -1
      }
    }
  } else {
    if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
    for (i = byteOffset; i >= 0; i--) {
      var found = true
      for (var j = 0; j < valLength; j++) {
        if (read(arr, i + j) !== read(val, j)) {
          found = false
          break
        }
      }
      if (found) return i
    }
  }

  return -1
}

Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  return this.indexOf(val, byteOffset, encoding) !== -1
}

Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}

Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}

function hexWrite (buf, string, offset, length) {
  offset = Number(offset) || 0
  var remaining = buf.length - offset
  if (!length) {
    length = remaining
  } else {
    length = Number(length)
    if (length > remaining) {
      length = remaining
    }
  }

  // must be an even number of digits
  var strLen = string.length
  if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')

  if (length > strLen / 2) {
    length = strLen / 2
  }
  for (var i = 0; i < length; ++i) {
    var parsed = parseInt(string.substr(i * 2, 2), 16)
    if (isNaN(parsed)) return i
    buf[offset + i] = parsed
  }
  return i
}

function utf8Write (buf, string, offset, length) {
  return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}

function asciiWrite (buf, string, offset, length) {
  return blitBuffer(asciiToBytes(string), buf, offset, length)
}

function latin1Write (buf, string, offset, length) {
  return asciiWrite(buf, string, offset, length)
}

function base64Write (buf, string, offset, length) {
  return blitBuffer(base64ToBytes(string), buf, offset, length)
}

function ucs2Write (buf, string, offset, length) {
  return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}

Buffer.prototype.write = function write (string, offset, length, encoding) {
  // Buffer#write(string)
  if (offset === undefined) {
    encoding = 'utf8'
    length = this.length
    offset = 0
  // Buffer#write(string, encoding)
  } else if (length === undefined && typeof offset === 'string') {
    encoding = offset
    length = this.length
    offset = 0
  // Buffer#write(string, offset[, length][, encoding])
  } else if (isFinite(offset)) {
    offset = offset | 0
    if (isFinite(length)) {
      length = length | 0
      if (encoding === undefined) encoding = 'utf8'
    } else {
      encoding = length
      length = undefined
    }
  // legacy write(string, encoding, offset, length) - remove in v0.13
  } else {
    throw new Error(
      'Buffer.write(string, encoding, offset[, length]) is no longer supported'
    )
  }

  var remaining = this.length - offset
  if (length === undefined || length > remaining) length = remaining

  if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
    throw new RangeError('Attempt to write outside buffer bounds')
  }

  if (!encoding) encoding = 'utf8'

  var loweredCase = false
  for (;;) {
    switch (encoding) {
      case 'hex':
        return hexWrite(this, string, offset, length)

      case 'utf8':
      case 'utf-8':
        return utf8Write(this, string, offset, length)

      case 'ascii':
        return asciiWrite(this, string, offset, length)

      case 'latin1':
      case 'binary':
        return latin1Write(this, string, offset, length)

      case 'base64':
        // Warning: maxLength not taken into account in base64Write
        return base64Write(this, string, offset, length)

      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return ucs2Write(this, string, offset, length)

      default:
        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
        encoding = ('' + encoding).toLowerCase()
        loweredCase = true
    }
  }
}

Buffer.prototype.toJSON = function toJSON () {
  return {
    type: 'Buffer',
    data: Array.prototype.slice.call(this._arr || this, 0)
  }
}

function base64Slice (buf, start, end) {
  if (start === 0 && end === buf.length) {
    return base64.fromByteArray(buf)
  } else {
    return base64.fromByteArray(buf.slice(start, end))
  }
}

function utf8Slice (buf, start, end) {
  end = Math.min(buf.length, end)
  var res = []

  var i = start
  while (i < end) {
    var firstByte = buf[i]
    var codePoint = null
    var bytesPerSequence = (firstByte > 0xEF) ? 4
      : (firstByte > 0xDF) ? 3
      : (firstByte > 0xBF) ? 2
      : 1

    if (i + bytesPerSequence <= end) {
      var secondByte, thirdByte, fourthByte, tempCodePoint

      switch (bytesPerSequence) {
        case 1:
          if (firstByte < 0x80) {
            codePoint = firstByte
          }
          break
        case 2:
          secondByte = buf[i + 1]
          if ((secondByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
            if (tempCodePoint > 0x7F) {
              codePoint = tempCodePoint
            }
          }
          break
        case 3:
          secondByte = buf[i + 1]
          thirdByte = buf[i + 2]
          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
            if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
              codePoint = tempCodePoint
            }
          }
          break
        case 4:
          secondByte = buf[i + 1]
          thirdByte = buf[i + 2]
          fourthByte = buf[i + 3]
          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
            if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
              codePoint = tempCodePoint
            }
          }
      }
    }

    if (codePoint === null) {
      // we did not generate a valid codePoint so insert a
      // replacement char (U+FFFD) and advance only 1 byte
      codePoint = 0xFFFD
      bytesPerSequence = 1
    } else if (codePoint > 0xFFFF) {
      // encode to utf16 (surrogate pair dance)
      codePoint -= 0x10000
      res.push(codePoint >>> 10 & 0x3FF | 0xD800)
      codePoint = 0xDC00 | codePoint & 0x3FF
    }

    res.push(codePoint)
    i += bytesPerSequence
  }

  return decodeCodePointsArray(res)
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000

function decodeCodePointsArray (codePoints) {
  var len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }

  // Decode in chunks to avoid "call stack size exceeded".
  var res = ''
  var i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}

function asciiSlice (buf, start, end) {
  var ret = ''
  end = Math.min(buf.length, end)

  for (var i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i] & 0x7F)
  }
  return ret
}

function latin1Slice (buf, start, end) {
  var ret = ''
  end = Math.min(buf.length, end)

  for (var i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i])
  }
  return ret
}

function hexSlice (buf, start, end) {
  var len = buf.length

  if (!start || start < 0) start = 0
  if (!end || end < 0 || end > len) end = len

  var out = ''
  for (var i = start; i < end; ++i) {
    out += toHex(buf[i])
  }
  return out
}

function utf16leSlice (buf, start, end) {
  var bytes = buf.slice(start, end)
  var res = ''
  for (var i = 0; i < bytes.length; i += 2) {
    res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  }
  return res
}

Buffer.prototype.slice = function slice (start, end) {
  var len = this.length
  start = ~~start
  end = end === undefined ? len : ~~end

  if (start < 0) {
    start += len
    if (start < 0) start = 0
  } else if (start > len) {
    start = len
  }

  if (end < 0) {
    end += len
    if (end < 0) end = 0
  } else if (end > len) {
    end = len
  }

  if (end < start) end = start

  var newBuf
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    newBuf = this.subarray(start, end)
    newBuf.__proto__ = Buffer.prototype
  } else {
    var sliceLen = end - start
    newBuf = new Buffer(sliceLen, undefined)
    for (var i = 0; i < sliceLen; ++i) {
      newBuf[i] = this[i + start]
    }
  }

  return newBuf
}

/*
 * Need to make sure that buffer isn't trying to write out of bounds.
 */
function checkOffset (offset, ext, length) {
  if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}

Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  offset = offset | 0
  byteLength = byteLength | 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  var val = this[offset]
  var mul = 1
  var i = 0
  while (++i < byteLength && (mul *= 0x100)) {
    val += this[offset + i] * mul
  }

  return val
}

Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  offset = offset | 0
  byteLength = byteLength | 0
  if (!noAssert) {
    checkOffset(offset, byteLength, this.length)
  }

  var val = this[offset + --byteLength]
  var mul = 1
  while (byteLength > 0 && (mul *= 0x100)) {
    val += this[offset + --byteLength] * mul
  }

  return val
}

Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 1, this.length)
  return this[offset]
}

Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 2, this.length)
  return this[offset] | (this[offset + 1] << 8)
}

Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 2, this.length)
  return (this[offset] << 8) | this[offset + 1]
}

Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 4, this.length)

  return ((this[offset]) |
      (this[offset + 1] << 8) |
      (this[offset + 2] << 16)) +
      (this[offset + 3] * 0x1000000)
}

Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset] * 0x1000000) +
    ((this[offset + 1] << 16) |
    (this[offset + 2] << 8) |
    this[offset + 3])
}

Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  offset = offset | 0
  byteLength = byteLength | 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  var val = this[offset]
  var mul = 1
  var i = 0
  while (++i < byteLength && (mul *= 0x100)) {
    val += this[offset + i] * mul
  }
  mul *= 0x80

  if (val >= mul) val -= Math.pow(2, 8 * byteLength)

  return val
}

Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  offset = offset | 0
  byteLength = byteLength | 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  var i = byteLength
  var mul = 1
  var val = this[offset + --i]
  while (i > 0 && (mul *= 0x100)) {
    val += this[offset + --i] * mul
  }
  mul *= 0x80

  if (val >= mul) val -= Math.pow(2, 8 * byteLength)

  return val
}

Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 1, this.length)
  if (!(this[offset] & 0x80)) return (this[offset])
  return ((0xff - this[offset] + 1) * -1)
}

Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 2, this.length)
  var val = this[offset] | (this[offset + 1] << 8)
  return (val & 0x8000) ? val | 0xFFFF0000 : val
}

Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 2, this.length)
  var val = this[offset + 1] | (this[offset] << 8)
  return (val & 0x8000) ? val | 0xFFFF0000 : val
}

Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset]) |
    (this[offset + 1] << 8) |
    (this[offset + 2] << 16) |
    (this[offset + 3] << 24)
}

Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset] << 24) |
    (this[offset + 1] << 16) |
    (this[offset + 2] << 8) |
    (this[offset + 3])
}

Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 4, this.length)
  return ieee754.read(this, offset, true, 23, 4)
}

Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 4, this.length)
  return ieee754.read(this, offset, false, 23, 4)
}

Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 8, this.length)
  return ieee754.read(this, offset, true, 52, 8)
}

Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 8, this.length)
  return ieee754.read(this, offset, false, 52, 8)
}

function checkInt (buf, value, offset, ext, max, min) {
  if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  if (offset + ext > buf.length) throw new RangeError('Index out of range')
}

Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset | 0
  byteLength = byteLength | 0
  if (!noAssert) {
    var maxBytes = Math.pow(2, 8 * byteLength) - 1
    checkInt(this, value, offset, byteLength, maxBytes, 0)
  }

  var mul = 1
  var i = 0
  this[offset] = value & 0xFF
  while (++i < byteLength && (mul *= 0x100)) {
    this[offset + i] = (value / mul) & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset | 0
  byteLength = byteLength | 0
  if (!noAssert) {
    var maxBytes = Math.pow(2, 8 * byteLength) - 1
    checkInt(this, value, offset, byteLength, maxBytes, 0)
  }

  var i = byteLength - 1
  var mul = 1
  this[offset + i] = value & 0xFF
  while (--i >= 0 && (mul *= 0x100)) {
    this[offset + i] = (value / mul) & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  this[offset] = (value & 0xff)
  return offset + 1
}

function objectWriteUInt16 (buf, value, offset, littleEndian) {
  if (value < 0) value = 0xffff + value + 1
  for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
    buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
      (littleEndian ? i : 1 - i) * 8
  }
}

Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = (value & 0xff)
    this[offset + 1] = (value >>> 8)
  } else {
    objectWriteUInt16(this, value, offset, true)
  }
  return offset + 2
}

Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = (value >>> 8)
    this[offset + 1] = (value & 0xff)
  } else {
    objectWriteUInt16(this, value, offset, false)
  }
  return offset + 2
}

function objectWriteUInt32 (buf, value, offset, littleEndian) {
  if (value < 0) value = 0xffffffff + value + 1
  for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
    buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  }
}

Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset + 3] = (value >>> 24)
    this[offset + 2] = (value >>> 16)
    this[offset + 1] = (value >>> 8)
    this[offset] = (value & 0xff)
  } else {
    objectWriteUInt32(this, value, offset, true)
  }
  return offset + 4
}

Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = (value >>> 24)
    this[offset + 1] = (value >>> 16)
    this[offset + 2] = (value >>> 8)
    this[offset + 3] = (value & 0xff)
  } else {
    objectWriteUInt32(this, value, offset, false)
  }
  return offset + 4
}

Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) {
    var limit = Math.pow(2, 8 * byteLength - 1)

    checkInt(this, value, offset, byteLength, limit - 1, -limit)
  }

  var i = 0
  var mul = 1
  var sub = 0
  this[offset] = value & 0xFF
  while (++i < byteLength && (mul *= 0x100)) {
    if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
      sub = 1
    }
    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) {
    var limit = Math.pow(2, 8 * byteLength - 1)

    checkInt(this, value, offset, byteLength, limit - 1, -limit)
  }

  var i = byteLength - 1
  var mul = 1
  var sub = 0
  this[offset + i] = value & 0xFF
  while (--i >= 0 && (mul *= 0x100)) {
    if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
      sub = 1
    }
    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  if (value < 0) value = 0xff + value + 1
  this[offset] = (value & 0xff)
  return offset + 1
}

Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = (value & 0xff)
    this[offset + 1] = (value >>> 8)
  } else {
    objectWriteUInt16(this, value, offset, true)
  }
  return offset + 2
}

Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = (value >>> 8)
    this[offset + 1] = (value & 0xff)
  } else {
    objectWriteUInt16(this, value, offset, false)
  }
  return offset + 2
}

Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = (value & 0xff)
    this[offset + 1] = (value >>> 8)
    this[offset + 2] = (value >>> 16)
    this[offset + 3] = (value >>> 24)
  } else {
    objectWriteUInt32(this, value, offset, true)
  }
  return offset + 4
}

Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  if (value < 0) value = 0xffffffff + value + 1
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = (value >>> 24)
    this[offset + 1] = (value >>> 16)
    this[offset + 2] = (value >>> 8)
    this[offset + 3] = (value & 0xff)
  } else {
    objectWriteUInt32(this, value, offset, false)
  }
  return offset + 4
}

function checkIEEE754 (buf, value, offset, ext, max, min) {
  if (offset + ext > buf.length) throw new RangeError('Index out of range')
  if (offset < 0) throw new RangeError('Index out of range')
}

function writeFloat (buf, value, offset, littleEndian, noAssert) {
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  }
  ieee754.write(buf, value, offset, littleEndian, 23, 4)
  return offset + 4
}

Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  return writeFloat(this, value, offset, true, noAssert)
}

Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  return writeFloat(this, value, offset, false, noAssert)
}

function writeDouble (buf, value, offset, littleEndian, noAssert) {
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  }
  ieee754.write(buf, value, offset, littleEndian, 52, 8)
  return offset + 8
}

Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  return writeDouble(this, value, offset, true, noAssert)
}

Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  return writeDouble(this, value, offset, false, noAssert)
}

// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  if (!start) start = 0
  if (!end && end !== 0) end = this.length
  if (targetStart >= target.length) targetStart = target.length
  if (!targetStart) targetStart = 0
  if (end > 0 && end < start) end = start

  // Copy 0 bytes; we're done
  if (end === start) return 0
  if (target.length === 0 || this.length === 0) return 0

  // Fatal error conditions
  if (targetStart < 0) {
    throw new RangeError('targetStart out of bounds')
  }
  if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  if (end < 0) throw new RangeError('sourceEnd out of bounds')

  // Are we oob?
  if (end > this.length) end = this.length
  if (target.length - targetStart < end - start) {
    end = target.length - targetStart + start
  }

  var len = end - start
  var i

  if (this === target && start < targetStart && targetStart < end) {
    // descending copy from end
    for (i = len - 1; i >= 0; --i) {
      target[i + targetStart] = this[i + start]
    }
  } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
    // ascending copy from start
    for (i = 0; i < len; ++i) {
      target[i + targetStart] = this[i + start]
    }
  } else {
    Uint8Array.prototype.set.call(
      target,
      this.subarray(start, start + len),
      targetStart
    )
  }

  return len
}

// Usage:
//    buffer.fill(number[, offset[, end]])
//    buffer.fill(buffer[, offset[, end]])
//    buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
  // Handle string cases:
  if (typeof val === 'string') {
    if (typeof start === 'string') {
      encoding = start
      start = 0
      end = this.length
    } else if (typeof end === 'string') {
      encoding = end
      end = this.length
    }
    if (val.length === 1) {
      var code = val.charCodeAt(0)
      if (code < 256) {
        val = code
      }
    }
    if (encoding !== undefined && typeof encoding !== 'string') {
      throw new TypeError('encoding must be a string')
    }
    if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
      throw new TypeError('Unknown encoding: ' + encoding)
    }
  } else if (typeof val === 'number') {
    val = val & 255
  }

  // Invalid ranges are not set to a default, so can range check early.
  if (start < 0 || this.length < start || this.length < end) {
    throw new RangeError('Out of range index')
  }

  if (end <= start) {
    return this
  }

  start = start >>> 0
  end = end === undefined ? this.length : end >>> 0

  if (!val) val = 0

  var i
  if (typeof val === 'number') {
    for (i = start; i < end; ++i) {
      this[i] = val
    }
  } else {
    var bytes = Buffer.isBuffer(val)
      ? val
      : utf8ToBytes(new Buffer(val, encoding).toString())
    var len = bytes.length
    for (i = 0; i < end - start; ++i) {
      this[i + start] = bytes[i % len]
    }
  }

  return this
}

// HELPER FUNCTIONS
// ================

var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g

function base64clean (str) {
  // Node strips out invalid characters like \n and \t from the string, base64-js does not
  str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  // Node converts strings with length < 2 to ''
  if (str.length < 2) return ''
  // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  while (str.length % 4 !== 0) {
    str = str + '='
  }
  return str
}

function stringtrim (str) {
  if (str.trim) return str.trim()
  return str.replace(/^\s+|\s+$/g, '')
}

function toHex (n) {
  if (n < 16) return '0' + n.toString(16)
  return n.toString(16)
}

function utf8ToBytes (string, units) {
  units = units || Infinity
  var codePoint
  var length = string.length
  var leadSurrogate = null
  var bytes = []

  for (var i = 0; i < length; ++i) {
    codePoint = string.charCodeAt(i)

    // is surrogate component
    if (codePoint > 0xD7FF && codePoint < 0xE000) {
      // last char was a lead
      if (!leadSurrogate) {
        // no lead yet
        if (codePoint > 0xDBFF) {
          // unexpected trail
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
          continue
        } else if (i + 1 === length) {
          // unpaired lead
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
          continue
        }

        // valid lead
        leadSurrogate = codePoint

        continue
      }

      // 2 leads in a row
      if (codePoint < 0xDC00) {
        if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
        leadSurrogate = codePoint
        continue
      }

      // valid surrogate pair
      codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
    } else if (leadSurrogate) {
      // valid bmp char, but last char was a lead
      if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
    }

    leadSurrogate = null

    // encode utf8
    if (codePoint < 0x80) {
      if ((units -= 1) < 0) break
      bytes.push(codePoint)
    } else if (codePoint < 0x800) {
      if ((units -= 2) < 0) break
      bytes.push(
        codePoint >> 0x6 | 0xC0,
        codePoint & 0x3F | 0x80
      )
    } else if (codePoint < 0x10000) {
      if ((units -= 3) < 0) break
      bytes.push(
        codePoint >> 0xC | 0xE0,
        codePoint >> 0x6 & 0x3F | 0x80,
        codePoint & 0x3F | 0x80
      )
    } else if (codePoint < 0x110000) {
      if ((units -= 4) < 0) break
      bytes.push(
        codePoint >> 0x12 | 0xF0,
        codePoint >> 0xC & 0x3F | 0x80,
        codePoint >> 0x6 & 0x3F | 0x80,
        codePoint & 0x3F | 0x80
      )
    } else {
      throw new Error('Invalid code point')
    }
  }

  return bytes
}

function asciiToBytes (str) {
  var byteArray = []
  for (var i = 0; i < str.length; ++i) {
    // Node's code seems to be doing this and not & 0x7F..
    byteArray.push(str.charCodeAt(i) & 0xFF)
  }
  return byteArray
}

function utf16leToBytes (str, units) {
  var c, hi, lo
  var byteArray = []
  for (var i = 0; i < str.length; ++i) {
    if ((units -= 2) < 0) break

    c = str.charCodeAt(i)
    hi = c >> 8
    lo = c % 256
    byteArray.push(lo)
    byteArray.push(hi)
  }

  return byteArray
}

function base64ToBytes (str) {
  return base64.toByteArray(base64clean(str))
}

function blitBuffer (src, dst, offset, length) {
  for (var i = 0; i < length; ++i) {
    if ((i + offset >= dst.length) || (i >= src.length)) break
    dst[i + offset] = src[i]
  }
  return i
}

function isnan (val) {
  return val !== val // eslint-disable-line no-self-compare
}

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "yLpj")))

/***/ }),

/***/ "tkb2":
/*!*******************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/FontSelector.js ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _Dropdown = __webpack_require__(/*! ./Dropdown */ "dRXW");

var _Dropdown2 = _interopRequireDefault(_Dropdown);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/* eslint-disable react/prop-types */
var styledRenderer = function styledRenderer(_ref) {
  var value = _ref.value,
      label = _ref.label;
  return _react2.default.createElement(
    'span',
    { style: { fontFamily: value } },
    label
  );
};
/* eslint-enable react/prop-types */

var FontSelector = function FontSelector(props, context) {
  return _react2.default.createElement(_Dropdown2.default, _extends({}, props, {
    options: context.fontOptions,
    valueRenderer: styledRenderer,
    optionRenderer: styledRenderer
  }));
};

FontSelector.propTypes = _extends({}, _Dropdown2.default.propTypes);

FontSelector.defaultProps = {
  clearable: false
};

FontSelector.contextTypes = {
  fontOptions: _propTypes2.default.array
};

exports.default = FontSelector;
//# sourceMappingURL=FontSelector.js.map

/***/ }),

/***/ "tn3U":
/*!************************************************************************!*\
  !*** ./node_modules/@jupyter-widgets/jupyterlab-manager/lib/plugin.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const disposable_1 = __webpack_require__(/*! @phosphor/disposable */ "uNUc");
const renderer_1 = __webpack_require__(/*! ./renderer */ "uRb0");
const manager_1 = __webpack_require__(/*! ./manager */ "Z/Y6");
const output_1 = __webpack_require__(/*! ./output */ "hNpt");
const base = __importStar(__webpack_require__(/*! @jupyter-widgets/base */ "Rtm6"));
const version_1 = __webpack_require__(/*! @jupyter-widgets/controls/lib/version */ "VKie");
__webpack_require__(/*! @jupyter-widgets/base/css/index.css */ "ZDkZ");
__webpack_require__(/*! @jupyter-widgets/controls/css/widgets-base.css */ "LiaU");
const WIDGET_MIMETYPE = 'application/vnd.jupyter.widget-view+json';
class NBWidgetExtension {
    constructor() {
        this._registry = [];
    }
    /**
     * Create a new extension object.
     */
    createNew(nb, context) {
        let wManager = new manager_1.WidgetManager(context, nb.rendermime);
        this._registry.forEach(data => wManager.register(data));
        nb.rendermime.addFactory({
            safe: false,
            mimeTypes: [WIDGET_MIMETYPE],
            createRenderer: (options) => new renderer_1.WidgetRenderer(options, wManager)
        }, 0);
        return new disposable_1.DisposableDelegate(() => {
            if (nb.rendermime) {
                nb.rendermime.removeMimeType(WIDGET_MIMETYPE);
            }
            wManager.dispose();
        });
    }
    /**
     * Register a widget module.
     */
    registerWidget(data) {
        this._registry.push(data);
    }
}
exports.NBWidgetExtension = NBWidgetExtension;
/**
 * The widget manager provider.
 */
const widgetManagerProvider = {
    id: 'jupyter.extensions.nbWidgetManager',
    provides: base.IJupyterWidgetRegistry,
    activate: activateWidgetExtension,
    autoStart: true
};
exports.default = widgetManagerProvider;
/**
 * Activate the widget extension.
 */
function activateWidgetExtension(app) {
    let extension = new NBWidgetExtension();
    extension.registerWidget({
        name: '@jupyter-widgets/base',
        version: base.JUPYTER_WIDGETS_VERSION,
        exports: {
            WidgetModel: base.WidgetModel,
            WidgetView: base.WidgetView,
            DOMWidgetView: base.DOMWidgetView,
            DOMWidgetModel: base.DOMWidgetModel,
            LayoutModel: base.LayoutModel,
            LayoutView: base.LayoutView,
            StyleModel: base.StyleModel,
            StyleView: base.StyleView
        }
    });
    extension.registerWidget({
        name: '@jupyter-widgets/controls',
        version: version_1.JUPYTER_CONTROLS_VERSION,
        exports: () => {
            return new Promise((resolve, reject) => {
                Promise.all(/*! require.ensure | @jupyter-widgets/controls */[__webpack_require__.e("vendors~@jupyter-widgets/controls~vega"), __webpack_require__.e("vendors~@jupyter-widgets/controls")]).then(((require) => {
                    resolve(__webpack_require__(/*! @jupyter-widgets/controls */ "XPeQ"));
                }).bind(null, __webpack_require__)).catch((err) => {
                    reject(err);
                });
            });
        }
    });
    extension.registerWidget({
        name: '@jupyter-widgets/output',
        version: output_1.OUTPUT_WIDGET_VERSION,
        exports: { OutputModel: output_1.OutputModel, OutputView: output_1.OutputView }
    });
    app.docRegistry.addWidgetExtension('Notebook', extension);
    return {
        registerWidget(data) {
            extension.registerWidget(data);
        }
    };
}


/***/ }),

/***/ "tnIz":
/*!*************************************!*\
  !*** ./node_modules/sha.js/hash.js ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer

// prototype class for hash functions
function Hash (blockSize, finalSize) {
  this._block = Buffer.alloc(blockSize)
  this._finalSize = finalSize
  this._blockSize = blockSize
  this._len = 0
}

Hash.prototype.update = function (data, enc) {
  if (typeof data === 'string') {
    enc = enc || 'utf8'
    data = Buffer.from(data, enc)
  }

  var block = this._block
  var blockSize = this._blockSize
  var length = data.length
  var accum = this._len

  for (var offset = 0; offset < length;) {
    var assigned = accum % blockSize
    var remainder = Math.min(length - offset, blockSize - assigned)

    for (var i = 0; i < remainder; i++) {
      block[assigned + i] = data[offset + i]
    }

    accum += remainder
    offset += remainder

    if ((accum % blockSize) === 0) {
      this._update(block)
    }
  }

  this._len += length
  return this
}

Hash.prototype.digest = function (enc) {
  var rem = this._len % this._blockSize

  this._block[rem] = 0x80

  // zero (rem + 1) trailing bits, where (rem + 1) is the smallest
  // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize
  this._block.fill(0, rem + 1)

  if (rem >= this._finalSize) {
    this._update(this._block)
    this._block.fill(0)
  }

  var bits = this._len * 8

  // uint32
  if (bits <= 0xffffffff) {
    this._block.writeUInt32BE(bits, this._blockSize - 4)

  // uint64
  } else {
    var lowBits = (bits & 0xffffffff) >>> 0
    var highBits = (bits - lowBits) / 0x100000000

    this._block.writeUInt32BE(highBits, this._blockSize - 8)
    this._block.writeUInt32BE(lowBits, this._blockSize - 4)
  }

  this._update(this._block)
  var hash = this._hash()

  return enc ? hash.toString(enc) : hash
}

Hash.prototype._update = function () {
  throw new Error('_update must be implemented by subclass')
}

module.exports = Hash


/***/ }),

/***/ "tpL1":
/*!*******************************************************!*\
  !*** ./node_modules/browserify-sign/browser/index.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(Buffer) {var createHash = __webpack_require__(/*! create-hash */ "mObS")
var stream = __webpack_require__(/*! stream */ "1IWx")
var inherits = __webpack_require__(/*! inherits */ "P7XM")
var sign = __webpack_require__(/*! ./sign */ "b+dc")
var verify = __webpack_require__(/*! ./verify */ "mAz1")

var algorithms = __webpack_require__(/*! ./algorithms.json */ "tOiH")
Object.keys(algorithms).forEach(function (key) {
  algorithms[key].id = new Buffer(algorithms[key].id, 'hex')
  algorithms[key.toLowerCase()] = algorithms[key]
})

function Sign (algorithm) {
  stream.Writable.call(this)

  var data = algorithms[algorithm]
  if (!data) throw new Error('Unknown message digest')

  this._hashType = data.hash
  this._hash = createHash(data.hash)
  this._tag = data.id
  this._signType = data.sign
}
inherits(Sign, stream.Writable)

Sign.prototype._write = function _write (data, _, done) {
  this._hash.update(data)
  done()
}

Sign.prototype.update = function update (data, enc) {
  if (typeof data === 'string') data = new Buffer(data, enc)

  this._hash.update(data)
  return this
}

Sign.prototype.sign = function signMethod (key, enc) {
  this.end()
  var hash = this._hash.digest()
  var sig = sign(hash, key, this._hashType, this._signType, this._tag)

  return enc ? sig.toString(enc) : sig
}

function Verify (algorithm) {
  stream.Writable.call(this)

  var data = algorithms[algorithm]
  if (!data) throw new Error('Unknown message digest')

  this._hash = createHash(data.hash)
  this._tag = data.id
  this._signType = data.sign
}
inherits(Verify, stream.Writable)

Verify.prototype._write = function _write (data, _, done) {
  this._hash.update(data)
  done()
}

Verify.prototype.update = function update (data, enc) {
  if (typeof data === 'string') data = new Buffer(data, enc)

  this._hash.update(data)
  return this
}

Verify.prototype.verify = function verifyMethod (key, sig, enc) {
  if (typeof sig === 'string') sig = new Buffer(sig, enc)

  this.end()
  var hash = this._hash.digest()
  return verify(sig, hash, key, this._signType, this._tag)
}

function createSign (algorithm) {
  return new Sign(algorithm)
}

function createVerify (algorithm) {
  return new Verify(algorithm)
}

module.exports = {
  Sign: createSign,
  Verify: createVerify,
  createSign: createSign,
  createVerify: createVerify
}

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../buffer/index.js */ "tjlA").Buffer))

/***/ }),

/***/ "tr+V":
/*!*****************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/application/style/images.css ***!
  \*****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.jp-ImageJupyterLab {\n  background-image: var(--jp-image-jupyterlab);\n}\n\n.jp-ImageJupyterLab-wordmark {\n  background-image: var(--jp-image-jupyterlab-wordmark);\n}\n\n.jp-ImageJupyter-favicon {\n  background-image: var(--jp-image-jupyter-favicon);\n}\n\n.jp-JupyterIcon {\n  background-image: var(--jp-image-jupyter);\n  background-size: 16px;\n  margin: 2px;\n  margin-left: 8px;\n  margin-right: 0px;\n  padding-right: 0px;\n}\n", ""]);

// exports


/***/ }),

/***/ "trA2":
/*!*******************************************************************!*\
  !*** ./node_modules/react-color/lib/components/hue/HuePointer.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SliderPointer = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var SliderPointer = exports.SliderPointer = function SliderPointer(_ref) {
  var direction = _ref.direction;

  var styles = (0, _reactcss2.default)({
    'default': {
      picker: {
        width: '18px',
        height: '18px',
        borderRadius: '50%',
        transform: 'translate(-9px, -1px)',
        backgroundColor: 'rgb(248, 248, 248)',
        boxShadow: '0 1px 4px 0 rgba(0, 0, 0, 0.37)'
      }
    },
    'vertical': {
      picker: {
        transform: 'translate(-3px, -9px)'
      }
    }
  }, { vertical: direction === 'vertical' });

  return _react2.default.createElement('div', { style: styles.picker });
};

exports.default = SliderPointer;

/***/ }),

/***/ "tu5P":
/*!*******************************************************************************!*\
  !*** ./node_modules/react-color/lib/components/chrome/ChromePointerCircle.js ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ChromePointerCircle = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var ChromePointerCircle = exports.ChromePointerCircle = function ChromePointerCircle() {
  var styles = (0, _reactcss2.default)({
    'default': {
      picker: {
        width: '12px',
        height: '12px',
        borderRadius: '6px',
        boxShadow: 'inset 0 0 0 1px #fff',
        transform: 'translate(-6px, -6px)'
      }
    }
  });

  return _react2.default.createElement('div', { style: styles.picker });
};

exports.default = ChromePointerCircle;

/***/ }),

/***/ "tuJh":
/*!************************************************************!*\
  !*** ./node_modules/draft-js/lib/keyCommandPlainDelete.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule keyCommandPlainDelete
 * @format
 * 
 */



var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");
var UnicodeUtils = __webpack_require__(/*! fbjs/lib/UnicodeUtils */ "jLRO");

var moveSelectionForward = __webpack_require__(/*! ./moveSelectionForward */ "DEWG");
var removeTextWithStrategy = __webpack_require__(/*! ./removeTextWithStrategy */ "8d//");

/**
 * Remove the selected range. If the cursor is collapsed, remove the following
 * character. This operation is Unicode-aware, so removing a single character
 * will remove a surrogate pair properly as well.
 */
function keyCommandPlainDelete(editorState) {
  var afterRemoval = removeTextWithStrategy(editorState, function (strategyState) {
    var selection = strategyState.getSelection();
    var content = strategyState.getCurrentContent();
    var key = selection.getAnchorKey();
    var offset = selection.getAnchorOffset();
    var charAhead = content.getBlockForKey(key).getText()[offset];
    return moveSelectionForward(strategyState, charAhead ? UnicodeUtils.getUTF16Length(charAhead, 0) : 1);
  }, 'forward');

  if (afterRemoval === editorState.getCurrentContent()) {
    return editorState;
  }

  var selection = editorState.getSelection();

  return EditorState.push(editorState, afterRemoval.set('selectionBefore', selection), selection.isCollapsed() ? 'delete-character' : 'remove-range');
}

module.exports = keyCommandPlainDelete;

/***/ }),

/***/ "tui4":
/*!*******************************************!*\
  !*** ./node_modules/json-parser/index.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var esprima = __webpack_require__(/*! esprima */ "+wB9");

exports.tokenize = tokenize;
exports.parse = parse;


function tokenize (code) {
  var list = esprima.tokenize(code, {
    comment: true,
    loc: true
  });
  if (list.comment) {
    return list;
  }

  var result = [];
  var comments = [];
  list.map(function (t) {
    if (t.type === 'LineComment') {
      t.type = 'Line';
      comments.push(t);
    } else if (t.type === 'BlockComment') {
      t.type = 'Block';
      comments.push(t);
    } else {
      result.push(t);
    }
  });
  result.comments = comments;
  return result;
}

var tokens;
var current;
var index;
var reviver;
var remove_comments;

function parse (code, rev, no_comments) {
  tokens = tokenize(code);
  reviver = rev;
  remove_comments = no_comments;

  if (!tokens.length) {
    unexpected_end();
  }

  sort_comment_tokens();

  index = -1;
  next();

  var result = walk();

  if (Object(result) === result && !remove_comments) {
    if (tokens.head_comments.length) {
      result['//^'] = tokens.head_comments;
    }

    if (tokens.foot_comments.length) {
      result['//$'] = tokens.foot_comments;
    }
  }

  result = transform('', result);
  reviver = null;
  return result;
}


function transform (k, v) {
  return reviver
    ? reviver(k, v)
    : v;
}


function walk () {
  var tt = type();
  var negative = '';
  if (tt === '-') {
      next();
      tt = type();
      negative = '-';
  }
  switch (tt) {
    case '{':
      next();
      return parse_object();
    case '[':
      next();
      return parse_array();
    case 'String':
    case 'Boolean':
    case 'Null':
    case 'Numeric':
      var value = current.value;
      next();
      return JSON.parse(negative + value);
  }

  unexpected();
}


function next () {
  return current = tokens[++ index];
}


function expect (a) {
  if (!is(a)) {
    unexpected();
  }
}


function unexpected () {
  throw new SyntaxError('Unexpected token ' + current.value.slice(0, 1));
}

function unexpected_end () {
  throw new SyntaxError('Unexpected end of input');
}


function parse_object () {
  var obj = {};
  var comment;
  var started;
  var name;
  while (!is('}')){
    if (started) {
      expect(',');
      next();
    }
    started = true;
    expect('String');
    name = JSON.parse(current.value);
    if (current.comments && !remove_comments) {
      obj['// ' + name] = current.comments;
    }
    next();
    expect(':');
    next();
    obj[name] = transform(name, walk());
  }
  next();
  return obj;
}


function parse_array () {
  var array = [];
  var started;
  var i = 0;
  while(!is(']')){
    if (started) {
      expect(',');
      next();
    }
    started = true;
    array[i] = transform(i, walk());
    i ++;
  }
  next();
  return array;
}


function type () {
  if (!current) {
    unexpected_end();
  }

  return current.type === 'Punctuator'
    ? current.value
    : current.type;
}


function is (t) {
  return type() === t;
}


function sort_comment_tokens () {
  var ts = tokens;
  var comments = ts.comments;
  if (!comments) {
    return;
  }

  function compare_to_then_push (condition, to, setup) {
    var comment;
    var first = true;
    var host;
    while((comment = comments[ci ++]) && condition(comment, to)){
      if (first) {
        host = setup();
      }
      first = false;
      host.push(comment_content(comment));
    }

    ci --;
    // Whether there are comments left.
    return !!comment;
  }
  
  var head_comments = [];
  var foot_comments = [];

  var first = ts[0];
  var ci = 0;
  var comment = compare_to_then_push(left, first, function () {
    return head_comments;
  });

  var i = 0;
  var token;
  var next;
  for (; i < ts.length; i ++) {
    if (!comment) {
      break;
    }

    token = ts[i];
    next = ts[i + 1];

    if (token.type === 'String' && next && next.value === ':') {
      comment = compare_to_then_push(left, token, function () {
        token.comments || (token.comments = []);
        return token.comments[0] || (token.comments[0] = []);
      });

      if (!comment) {
        break;
      }

      comment = compare_to_then_push(right, token, function () {
        token.comments || (token.comments = []);
        return token.comments[1] || (token.comments[1] = []);
      });
    }
  }

  compare_to_then_push(function () {
    return true
  }, null, function () {
    return foot_comments;
  });

  comments.length = 0;
  delete ts.comments;

  tokens.head_comments = head_comments;
  tokens.foot_comments = foot_comments;
}


function left (a, b) {
  return a 
    && (
      a.loc.start.line < b.loc.start.line
      ||
        a.loc.start.line === b.loc.start.line
        && a.loc.start.column < b.loc.start.column
    );
}


function right (a, b) {
  return a 
    && a.loc.start.line === b.loc.start.line
    && a.loc.start.column > b.loc.start.column;
}


function comment_content (comment) {
  return comment.type === 'Block'
    ? '/*' + comment.value + '*/'
    : '//' + comment.value;
}


/***/ }),

/***/ "tz+M":
/*!************************************************************!*\
  !*** ./node_modules/elliptic/lib/elliptic/ec/signature.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var BN = __webpack_require__(/*! bn.js */ "OZ/i");

var elliptic = __webpack_require__(/*! ../../elliptic */ "MzeL");
var utils = elliptic.utils;
var assert = utils.assert;

function Signature(options, enc) {
  if (options instanceof Signature)
    return options;

  if (this._importDER(options, enc))
    return;

  assert(options.r && options.s, 'Signature without r or s');
  this.r = new BN(options.r, 16);
  this.s = new BN(options.s, 16);
  if (options.recoveryParam === undefined)
    this.recoveryParam = null;
  else
    this.recoveryParam = options.recoveryParam;
}
module.exports = Signature;

function Position() {
  this.place = 0;
}

function getLength(buf, p) {
  var initial = buf[p.place++];
  if (!(initial & 0x80)) {
    return initial;
  }
  var octetLen = initial & 0xf;
  var val = 0;
  for (var i = 0, off = p.place; i < octetLen; i++, off++) {
    val <<= 8;
    val |= buf[off];
  }
  p.place = off;
  return val;
}

function rmPadding(buf) {
  var i = 0;
  var len = buf.length - 1;
  while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
    i++;
  }
  if (i === 0) {
    return buf;
  }
  return buf.slice(i);
}

Signature.prototype._importDER = function _importDER(data, enc) {
  data = utils.toArray(data, enc);
  var p = new Position();
  if (data[p.place++] !== 0x30) {
    return false;
  }
  var len = getLength(data, p);
  if ((len + p.place) !== data.length) {
    return false;
  }
  if (data[p.place++] !== 0x02) {
    return false;
  }
  var rlen = getLength(data, p);
  var r = data.slice(p.place, rlen + p.place);
  p.place += rlen;
  if (data[p.place++] !== 0x02) {
    return false;
  }
  var slen = getLength(data, p);
  if (data.length !== slen + p.place) {
    return false;
  }
  var s = data.slice(p.place, slen + p.place);
  if (r[0] === 0 && (r[1] & 0x80)) {
    r = r.slice(1);
  }
  if (s[0] === 0 && (s[1] & 0x80)) {
    s = s.slice(1);
  }

  this.r = new BN(r);
  this.s = new BN(s);
  this.recoveryParam = null;

  return true;
};

function constructLength(arr, len) {
  if (len < 0x80) {
    arr.push(len);
    return;
  }
  var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
  arr.push(octets | 0x80);
  while (--octets) {
    arr.push((len >>> (octets << 3)) & 0xff);
  }
  arr.push(len);
}

Signature.prototype.toDER = function toDER(enc) {
  var r = this.r.toArray();
  var s = this.s.toArray();

  // Pad values
  if (r[0] & 0x80)
    r = [ 0 ].concat(r);
  // Pad values
  if (s[0] & 0x80)
    s = [ 0 ].concat(s);

  r = rmPadding(r);
  s = rmPadding(s);

  while (!s[0] && !(s[1] & 0x80)) {
    s = s.slice(1);
  }
  var arr = [ 0x02 ];
  constructLength(arr, r.length);
  arr = arr.concat(r);
  arr.push(0x02);
  constructLength(arr, s.length);
  var backHalf = arr.concat(s);
  var res = [ 0x30 ];
  constructLength(res, backHalf.length);
  res = res.concat(backHalf);
  return utils.encode(res, enc);
};


/***/ }),

/***/ "u/dz":
/*!******************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/ColorPicker.js ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UnconnectedColorPicker = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _ColorPicker = __webpack_require__(/*! ../widgets/ColorPicker */ "S8Va");

var _ColorPicker2 = _interopRequireDefault(_ColorPicker);

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UnconnectedColorPicker = exports.UnconnectedColorPicker = function (_Component) {
  _inherits(UnconnectedColorPicker, _Component);

  function UnconnectedColorPicker(props, context) {
    _classCallCheck(this, UnconnectedColorPicker);

    var _this = _possibleConstructorReturn(this, (UnconnectedColorPicker.__proto__ || Object.getPrototypeOf(UnconnectedColorPicker)).call(this, props, context));

    _this.state = {
      empty: !_this.props.fullValue && _this.props.handleEmpty
    };
    return _this;
  }

  _createClass(UnconnectedColorPicker, [{
    key: 'render',
    value: function render() {
      var _this2 = this;

      if (this.state.empty) {
        return _react2.default.createElement(
          _Field2.default,
          this.props,
          _react2.default.createElement(
            'div',
            { className: 'js-test-info' },
            'This color is computed from other parts of the figure but you can',
            ' ',
            _react2.default.createElement(
              'a',
              {
                onClick: function onClick() {
                  _this2.setState({ empty: false });
                  _this2.props.updatePlot(_this2.props.defaultColor);
                }
              },
              'override it'
            ),
            '.'
          )
        );
      }

      return _react2.default.createElement(
        _Field2.default,
        this.props,
        _react2.default.createElement(_ColorPicker2.default, {
          selectedColor: this.props.fullValue,
          onColorChange: this.props.updatePlot
        })
      );
    }
  }]);

  return UnconnectedColorPicker;
}(_react.Component);

UnconnectedColorPicker.propTypes = _extends({
  fullValue: _propTypes2.default.any,
  updatePlot: _propTypes2.default.func,
  handleEmpty: _propTypes2.default.bool,
  defaultColor: _propTypes2.default.string
}, _Field2.default.propTypes);

exports.default = (0, _lib.connectToContainer)(UnconnectedColorPicker);
//# sourceMappingURL=ColorPicker.js.map

/***/ }),

/***/ "u0Sq":
/*!*************************************************!*\
  !*** ./node_modules/hash.js/lib/hash/ripemd.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var utils = __webpack_require__(/*! ./utils */ "w8CP");
var common = __webpack_require__(/*! ./common */ "7ckf");

var rotl32 = utils.rotl32;
var sum32 = utils.sum32;
var sum32_3 = utils.sum32_3;
var sum32_4 = utils.sum32_4;
var BlockHash = common.BlockHash;

function RIPEMD160() {
  if (!(this instanceof RIPEMD160))
    return new RIPEMD160();

  BlockHash.call(this);

  this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
  this.endian = 'little';
}
utils.inherits(RIPEMD160, BlockHash);
exports.ripemd160 = RIPEMD160;

RIPEMD160.blockSize = 512;
RIPEMD160.outSize = 160;
RIPEMD160.hmacStrength = 192;
RIPEMD160.padLength = 64;

RIPEMD160.prototype._update = function update(msg, start) {
  var A = this.h[0];
  var B = this.h[1];
  var C = this.h[2];
  var D = this.h[3];
  var E = this.h[4];
  var Ah = A;
  var Bh = B;
  var Ch = C;
  var Dh = D;
  var Eh = E;
  for (var j = 0; j < 80; j++) {
    var T = sum32(
      rotl32(
        sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),
        s[j]),
      E);
    A = E;
    E = D;
    D = rotl32(C, 10);
    C = B;
    B = T;
    T = sum32(
      rotl32(
        sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
        sh[j]),
      Eh);
    Ah = Eh;
    Eh = Dh;
    Dh = rotl32(Ch, 10);
    Ch = Bh;
    Bh = T;
  }
  T = sum32_3(this.h[1], C, Dh);
  this.h[1] = sum32_3(this.h[2], D, Eh);
  this.h[2] = sum32_3(this.h[3], E, Ah);
  this.h[3] = sum32_3(this.h[4], A, Bh);
  this.h[4] = sum32_3(this.h[0], B, Ch);
  this.h[0] = T;
};

RIPEMD160.prototype._digest = function digest(enc) {
  if (enc === 'hex')
    return utils.toHex32(this.h, 'little');
  else
    return utils.split32(this.h, 'little');
};

function f(j, x, y, z) {
  if (j <= 15)
    return x ^ y ^ z;
  else if (j <= 31)
    return (x & y) | ((~x) & z);
  else if (j <= 47)
    return (x | (~y)) ^ z;
  else if (j <= 63)
    return (x & z) | (y & (~z));
  else
    return x ^ (y | (~z));
}

function K(j) {
  if (j <= 15)
    return 0x00000000;
  else if (j <= 31)
    return 0x5a827999;
  else if (j <= 47)
    return 0x6ed9eba1;
  else if (j <= 63)
    return 0x8f1bbcdc;
  else
    return 0xa953fd4e;
}

function Kh(j) {
  if (j <= 15)
    return 0x50a28be6;
  else if (j <= 31)
    return 0x5c4dd124;
  else if (j <= 47)
    return 0x6d703ef3;
  else if (j <= 63)
    return 0x7a6d76e9;
  else
    return 0x00000000;
}

var r = [
  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
  7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
  3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
  1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
  4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
];

var rh = [
  5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
  6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
  15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
  8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
  12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
];

var s = [
  11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
  7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
  11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
  11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
  9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
];

var sh = [
  8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
  9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
  9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
  15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
  8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
];


/***/ }),

/***/ "u1VM":
/*!**************************************************************!*\
  !*** ./node_modules/react-json-tree/lib/themes/solarized.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'solarized',
  author: 'ethan schoonover (http://ethanschoonover.com/solarized)',
  base00: '#002b36',
  base01: '#073642',
  base02: '#586e75',
  base03: '#657b83',
  base04: '#839496',
  base05: '#93a1a1',
  base06: '#eee8d5',
  base07: '#fdf6e3',
  base08: '#dc322f',
  base09: '#cb4b16',
  base0A: '#b58900',
  base0B: '#859900',
  base0C: '#2aa198',
  base0D: '#268bd2',
  base0E: '#6c71c4',
  base0F: '#d33682'
};

/***/ }),

/***/ "u2j1":
/*!**********************************************!*\
  !*** ./node_modules/mdi-react/FilterIcon.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var FilterIcon = function FilterIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M14,12V19.88C14.04,20.18 13.94,20.5 13.71,20.71C13.32,21.1 12.69,21.1 12.3,20.71L10.29,18.7C10.06,18.47 9.96,18.16 10,17.87V12H9.97L4.21,4.62C3.87,4.19 3.95,3.56 4.38,3.22C4.57,3.08 4.78,3 5,3V3H19V3C19.22,3 19.43,3.08 19.62,3.22C20.05,3.56 20.13,4.19 19.79,4.62L14.03,12H14Z' })
  );
};

module.exports = FilterIcon;


/***/ }),

/***/ "u3GI":
/*!*********************************************!*\
  !*** ./node_modules/moment/locale/de-ch.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


function processRelativeTime(number, withoutSuffix, key, isFuture) {
    var format = {
        'm': ['eine Minute', 'einer Minute'],
        'h': ['eine Stunde', 'einer Stunde'],
        'd': ['ein Tag', 'einem Tag'],
        'dd': [number + ' Tage', number + ' Tagen'],
        'M': ['ein Monat', 'einem Monat'],
        'MM': [number + ' Monate', number + ' Monaten'],
        'y': ['ein Jahr', 'einem Jahr'],
        'yy': [number + ' Jahre', number + ' Jahren']
    };
    return withoutSuffix ? format[key][0] : format[key][1];
}

var deCh = moment.defineLocale('de-ch', {
    months : 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'),
    monthsShort : 'Jan._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'),
    monthsParseExact : true,
    weekdays : 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'),
    weekdaysShort : 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'),
    weekdaysMin : 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT: 'HH:mm',
        LTS: 'HH:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D. MMMM YYYY',
        LLL : 'D. MMMM YYYY HH:mm',
        LLLL : 'dddd, D. MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay: '[heute um] LT [Uhr]',
        sameElse: 'L',
        nextDay: '[morgen um] LT [Uhr]',
        nextWeek: 'dddd [um] LT [Uhr]',
        lastDay: '[gestern um] LT [Uhr]',
        lastWeek: '[letzten] dddd [um] LT [Uhr]'
    },
    relativeTime : {
        future : 'in %s',
        past : 'vor %s',
        s : 'ein paar Sekunden',
        ss : '%d Sekunden',
        m : processRelativeTime,
        mm : '%d Minuten',
        h : processRelativeTime,
        hh : '%d Stunden',
        d : processRelativeTime,
        dd : processRelativeTime,
        M : processRelativeTime,
        MM : processRelativeTime,
        y : processRelativeTime,
        yy : processRelativeTime
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return deCh;

})));


/***/ }),

/***/ "u6YH":
/*!**********************************************!*\
  !*** ./node_modules/mdi-react/WrenchIcon.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var WrenchIcon = function WrenchIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M22.7,19L13.6,9.9C14.5,7.6 14,4.9 12.1,3C10.1,1 7.1,0.6 4.7,1.7L9,6L6,9L1.6,4.7C0.4,7.1 0.9,10.1 2.9,12.1C4.8,14 7.5,14.5 9.8,13.6L18.9,22.7C19.3,23.1 19.9,23.1 20.3,22.7L22.6,20.4C23.1,20 23.1,19.3 22.7,19Z' })
  );
};

module.exports = WrenchIcon;


/***/ }),

/***/ "u84l":
/*!**********************************************!*\
  !*** ./node_modules/mdi-react/LogoutIcon.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var LogoutIcon = function LogoutIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M16,17V14H9V10H16V7L21,12L16,17M14,2C15.1,2 16,2.9 16,4V6H14V4H5V20H14V18H16V20C16,21.1 15.1,22 14,22H5C3.9,22 3,21.1 3,20V4C3,2.9 3.9,2 5,2H14Z' })
  );
};

module.exports = LogoutIcon;


/***/ }),

/***/ "u8Dt":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_hashGet.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var nativeCreate = __webpack_require__(/*! ./_nativeCreate */ "YESw");

/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * 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;
}

module.exports = hashGet;


/***/ }),

/***/ "uA+y":
/*!**************************************************!*\
  !*** ./node_modules/mdi-react/FullscreenIcon.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var FullscreenIcon = function FullscreenIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M5,5H10V7H7V10H5V5M14,5H19V10H17V7H14V5M17,14H19V19H14V17H17V14M10,17V19H5V14H7V17H10Z' })
  );
};

module.exports = FullscreenIcon;


/***/ }),

/***/ "uDDF":
/*!*************************************************!*\
  !*** ./node_modules/mdi-react/AnimationIcon.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var AnimationIcon = function AnimationIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M4,2C2.89,2 2,2.89 2,4V14H4V4H14V2H4M8,6C6.89,6 6,6.89 6,8V18H8V8H18V6H8M12,10C10.89,10 10,10.89 10,12V20C10,21.11 10.89,22 12,22H20C21.11,22 22,21.11 22,20V12C22,10.89 21.11,10 20,10H12Z' })
  );
};

module.exports = AnimationIcon;


/***/ }),

/***/ "uDUr":
/*!************************************************************************!*\
  !*** ./node_modules/react-color/lib/components/block/BlockSwatches.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.BlockSwatches = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _map = __webpack_require__(/*! lodash/map */ "3WF5");

var _map2 = _interopRequireDefault(_map);

var _common = __webpack_require__(/*! ../common */ "TM95");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var BlockSwatches = exports.BlockSwatches = function BlockSwatches(_ref) {
  var colors = _ref.colors,
      onClick = _ref.onClick,
      onSwatchHover = _ref.onSwatchHover;

  var styles = (0, _reactcss2.default)({
    'default': {
      swatches: {
        marginRight: '-10px'
      },
      swatch: {
        width: '22px',
        height: '22px',
        float: 'left',
        marginRight: '10px',
        marginBottom: '10px',
        borderRadius: '4px'
      },
      clear: {
        clear: 'both'
      }
    }
  });

  return _react2.default.createElement(
    'div',
    { style: styles.swatches },
    (0, _map2.default)(colors, function (c) {
      return _react2.default.createElement(_common.Swatch, {
        key: c,
        color: c,
        style: styles.swatch,
        onClick: onClick,
        onHover: onSwatchHover,
        focusStyle: {
          boxShadow: '0 0 4px ' + c
        }
      });
    }),
    _react2.default.createElement('div', { style: styles.clear })
  );
};

exports.default = BlockSwatches;

/***/ }),

/***/ "uDfV":
/*!***************************************!*\
  !*** ./node_modules/sha.js/sha384.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var inherits = __webpack_require__(/*! inherits */ "P7XM")
var SHA512 = __webpack_require__(/*! ./sha512 */ "T9HO")
var Hash = __webpack_require__(/*! ./hash */ "tnIz")
var Buffer = __webpack_require__(/*! safe-buffer */ "hwdV").Buffer

var W = new Array(160)

function Sha384 () {
  this.init()
  this._w = W

  Hash.call(this, 128, 112)
}

inherits(Sha384, SHA512)

Sha384.prototype.init = function () {
  this._ah = 0xcbbb9d5d
  this._bh = 0x629a292a
  this._ch = 0x9159015a
  this._dh = 0x152fecd8
  this._eh = 0x67332667
  this._fh = 0x8eb44a87
  this._gh = 0xdb0c2e0d
  this._hh = 0x47b5481d

  this._al = 0xc1059ed8
  this._bl = 0x367cd507
  this._cl = 0x3070dd17
  this._dl = 0xf70e5939
  this._el = 0xffc00b31
  this._fl = 0x68581511
  this._gl = 0x64f98fa7
  this._hl = 0xbefa4fa4

  return this
}

Sha384.prototype._hash = function () {
  var H = Buffer.allocUnsafe(48)

  function writeInt64BE (h, l, offset) {
    H.writeInt32BE(h, offset)
    H.writeInt32BE(l, offset + 4)
  }

  writeInt64BE(this._ah, this._al, 0)
  writeInt64BE(this._bh, this._bl, 8)
  writeInt64BE(this._ch, this._cl, 16)
  writeInt64BE(this._dh, this._dl, 24)
  writeInt64BE(this._eh, this._el, 32)
  writeInt64BE(this._fh, this._fl, 40)

  return H
}

module.exports = Sha384


/***/ }),

/***/ "uEye":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/nn.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var nn = moment.defineLocale('nn', {
    months : 'januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember'.split('_'),
    monthsShort : 'jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'),
    weekdays : 'sundag_måndag_tysdag_onsdag_torsdag_fredag_laurdag'.split('_'),
    weekdaysShort : 'sun_mån_tys_ons_tor_fre_lau'.split('_'),
    weekdaysMin : 'su_må_ty_on_to_fr_lø'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D. MMMM YYYY',
        LLL : 'D. MMMM YYYY [kl.] H:mm',
        LLLL : 'dddd D. MMMM YYYY [kl.] HH:mm'
    },
    calendar : {
        sameDay: '[I dag klokka] LT',
        nextDay: '[I morgon klokka] LT',
        nextWeek: 'dddd [klokka] LT',
        lastDay: '[I går klokka] LT',
        lastWeek: '[Føregåande] dddd [klokka] LT',
        sameElse: 'L'
    },
    relativeTime : {
        future : 'om %s',
        past : '%s sidan',
        s : 'nokre sekund',
        ss : '%d sekund',
        m : 'eit minutt',
        mm : '%d minutt',
        h : 'ein time',
        hh : '%d timar',
        d : 'ein dag',
        dd : '%d dagar',
        M : 'ein månad',
        MM : '%d månader',
        y : 'eit år',
        yy : '%d år'
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return nn;

})));


/***/ }),

/***/ "uMpD":
/*!***************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/getAllAxes.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = getAllAxes;
exports.traceTypeToAxisType = traceTypeToAxisType;
exports.axisIdToAxisName = axisIdToAxisName;
exports.getAxisTitle = getAxisTitle;
exports.getSubplotTitle = getSubplotTitle;

var _constants = __webpack_require__(/*! ./constants */ "5Bkx");

var _2 = __webpack_require__(/*! ./ */ "RXjw");

function getAllAxes(fullLayout) {
  var axes = [];
  // Plotly.js should really have a helper function for this, but until it does..
  if (fullLayout && fullLayout._subplots) {
    Object.keys(fullLayout._subplots).filter(
    // xaxis and yaxis already included separately in _fullLayout._subplots
    function (type) {
      return type !== 'cartesian' && fullLayout._subplots[type].length !== 0;
    }).forEach(function (type) {
      fullLayout._subplots[type].forEach(function (subplot) {
        if (['xaxis', 'yaxis'].includes(type)) {
          // subplot will look like x2, x45, convert it to xaxis2, xaxis45
          subplot = // eslint-disable-line no-param-reassign
          subplot.length > 1 ? subplot.slice(0, 1) + 'axis' + subplot.slice(1) : subplot + 'axis';

          fullLayout[subplot]._subplot = subplot;
          fullLayout[subplot]._axisGroup = type;
          axes.push(fullLayout[subplot]);
        } else {
          Object.keys(fullLayout[subplot]).filter(function (key) {
            return key.includes('axis');
          }).forEach(function (axis) {
            fullLayout[subplot][axis]._subplot = subplot;
            fullLayout[subplot][axis]._axisGroup = type;

            // it should be in plotly.js, but it's not there for geo axes..
            if (!fullLayout[subplot][axis]._name) {
              fullLayout[subplot][axis]._name = axis;
            }
            axes.push(fullLayout[subplot][axis]);
          });
        }
      });
    });
  }

  return axes;
}

function traceTypeToAxisType(traceType) {
  var subplot = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

  // plotly.js actually allows traces with no type and just
  // defaults them to scatter, so do this here as well.
  if (!traceType) {
    traceType = 'scatter'; // eslint-disable-line
  }

  var category = null;
  var traceToAxis = _constants.TRACE_TO_AXIS;
  if (subplot) {
    Object.assign(traceToAxis, _constants.TRACE_TO_AXIS, { scene: _constants.TRACE_TO_AXIS.gl3d });
    delete traceToAxis.gl3d;
  }

  Object.keys(traceToAxis).forEach(function (c) {
    if (traceToAxis[c].includes(traceType)) {
      category = c;
    }
  });

  if (category) {
    return category;
  }

  return null;
}

function axisIdToAxisName(id) {
  return id.charAt(0) + 'axis' + id.slice(1);
}

function getAxisNumber(axis) {
  var splitSubplot = axis._subplot ? axis._subplot.split(axis._axisGroup) : [];
  return splitSubplot[1] ? Number(splitSubplot[1]) : axis._name.split('axis')[1];
}

function getAxisTitle(axis) {
  var axisType = (0, _2.capitalize)(axis._name.split('axis')[0]);
  var subplotNumber = getAxisNumber(axis) || 1;

  return axis._input && axis._input.title ? (0, _2.striptags)(axisType + ': ' + axis._input.title.text) : (0, _2.striptags)(axisType + ' ' + subplotNumber);
}

function getSubplotNumber(subplot, type) {
  return Number(subplot.split(type)[1]);
}

function getSubplotTitle(subplot, type, _) {
  var axisName = (0, _constants.subplotName)(type, _);
  var subplotNumber = getSubplotNumber(subplot, _constants.SUBPLOT_TO_ATTR[type].layout) || '';

  return axisName + ' ' + subplotNumber;
}
//# sourceMappingURL=getAllAxes.js.map

/***/ }),

/***/ "uNUc":
/*!********************************************************!*\
  !*** ./node_modules/@phosphor/disposable/lib/index.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
/**
 * A disposable object which delegates to a callback function.
 */
var DisposableDelegate = (function () {
    /**
     * Construct a new disposable delegate.
     *
     * @param fn - The callback function to invoke on dispose.
     */
    function DisposableDelegate(fn) {
        this._fn = fn;
    }
    Object.defineProperty(DisposableDelegate.prototype, "isDisposed", {
        /**
         * Test whether the delegate has been disposed.
         */
        get: function () {
            return !this._fn;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Dispose of the delegate and invoke the callback function.
     */
    DisposableDelegate.prototype.dispose = function () {
        if (!this._fn) {
            return;
        }
        var fn = this._fn;
        this._fn = null;
        fn();
    };
    return DisposableDelegate;
}());
exports.DisposableDelegate = DisposableDelegate;
/**
 * An object which manages a collection of disposable items.
 */
var DisposableSet = (function () {
    /**
     * Construct a new disposable set.
     */
    function DisposableSet() {
        this._disposed = false;
        this._items = new Set();
    }
    Object.defineProperty(DisposableSet.prototype, "isDisposed", {
        /**
         * Test whether the set has been disposed.
         */
        get: function () {
            return this._disposed;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Dispose of the set and the items it contains.
     *
     * #### Notes
     * Items are disposed in the order they are added to the set.
     */
    DisposableSet.prototype.dispose = function () {
        if (this._disposed) {
            return;
        }
        this._disposed = true;
        this._items.forEach(function (item) { item.dispose(); });
        this._items.clear();
    };
    /**
     * Test whether the set contains a specific item.
     *
     * @param item - The item of interest.
     *
     * @returns `true` if the set contains the item, `false` otherwise.
     */
    DisposableSet.prototype.contains = function (item) {
        return this._items.has(item);
    };
    /**
     * Add a disposable item to the set.
     *
     * @param item - The item to add to the set.
     *
     * #### Notes
     * If the item is already contained in the set, this is a no-op.
     */
    DisposableSet.prototype.add = function (item) {
        this._items.add(item);
    };
    /**
     * Remove a disposable item from the set.
     *
     * @param item - The item to remove from the set.
     *
     * #### Notes
     * If the item is not contained in the set, this is a no-op.
     */
    DisposableSet.prototype.remove = function (item) {
        this._items.delete(item);
    };
    /**
     * Remove all items from the set.
     */
    DisposableSet.prototype.clear = function () {
        this._items.clear();
    };
    return DisposableSet;
}());
exports.DisposableSet = DisposableSet;
/**
 * The namespace for the `DisposableSet` class statics.
 */
(function (DisposableSet) {
    /**
     * Create a disposable set from an iterable of items.
     *
     * @param items - The iterable or array-like object of interest.
     *
     * @returns A new disposable initialized with the given items.
     */
    function from(items) {
        var set = new DisposableSet();
        algorithm_1.each(items, function (item) { set.add(item); });
        return set;
    }
    DisposableSet.from = from;
})(DisposableSet = exports.DisposableSet || (exports.DisposableSet = {}));
exports.DisposableSet = DisposableSet;


/***/ }),

/***/ "uOPS":
/*!**********************************************************!*\
  !*** ./node_modules/core-js/library/modules/_library.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = true;


/***/ }),

/***/ "uP2X":
/*!******************************************************************!*\
  !*** ./node_modules/@jupyterlab/settingeditor/lib/pluginlist.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const React = __importStar(__webpack_require__(/*! react */ "q1tI"));
const ReactDOM = __importStar(__webpack_require__(/*! react-dom */ "i8i4"));
/**
 * A list of plugins with editable settings.
 */
class PluginList extends widgets_1.Widget {
    /**
     * Create a new plugin list.
     */
    constructor(options) {
        super();
        this._changed = new signaling_1.Signal(this);
        this._editor = 'raw';
        this._scrollTop = 0;
        this._selection = '';
        this.registry = options.registry;
        this.addClass('jp-PluginList');
        this._confirm = options.confirm;
        this.registry.pluginChanged.connect(() => {
            this.update();
        }, this);
    }
    /**
     * A signal emitted when a list user interaction happens.
     */
    get changed() {
        return this._changed;
    }
    /**
     * The editor type currently selected.
     */
    get editor() {
        return this._editor;
    }
    set editor(editor) {
        if (this._editor === editor) {
            return;
        }
        this._editor = editor;
        this.update();
    }
    /**
     * The selection value of the plugin list.
     */
    get scrollTop() {
        return this.node.querySelector('ul').scrollTop;
    }
    /**
     * The selection value of the plugin list.
     */
    get selection() {
        return this._selection;
    }
    set selection(selection) {
        if (this._selection === selection) {
            return;
        }
        this._selection = selection;
        this.update();
    }
    /**
     * Handle the DOM events for the widget.
     *
     * @param event - The DOM event sent to the widget.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the plugin list's node. It should
     * not be called directly by user code.
     */
    handleEvent(event) {
        switch (event.type) {
            case 'mousedown':
                this._evtMousedown(event);
                break;
            default:
                break;
        }
    }
    /**
     * Handle `'after-attach'` messages.
     */
    onAfterAttach(msg) {
        this.node.addEventListener('mousedown', this);
        this.update();
    }
    /**
     * Handle `before-detach` messages for the widget.
     */
    onBeforeDetach(msg) {
        this.node.removeEventListener('mousedown', this);
    }
    /**
     * Handle `'update-request'` messages.
     */
    onUpdateRequest(msg) {
        const { node, registry } = this;
        const type = this._editor;
        const selection = this._selection;
        Private.populateList(registry, type, selection, node);
        node.querySelector('ul').scrollTop = this._scrollTop;
    }
    /**
     * Handle the `'mousedown'` event for the plugin list.
     *
     * @param event - The DOM event sent to the widget
     */
    _evtMousedown(event) {
        event.preventDefault();
        let target = event.target;
        let id = target.getAttribute('data-id');
        if (id === this._selection) {
            return;
        }
        const editor = target.getAttribute('data-editor');
        if (editor) {
            this._editor = editor;
            this._changed.emit(undefined);
            this.update();
            return;
        }
        if (!id) {
            while (!id && target !== this.node) {
                target = target.parentElement;
                id = target.getAttribute('data-id');
            }
        }
        if (!id) {
            return;
        }
        this._confirm()
            .then(() => {
            this._scrollTop = this.scrollTop;
            this._selection = id;
            this._changed.emit(undefined);
            this.update();
        })
            .catch(() => {
            /* no op */
        });
    }
}
exports.PluginList = PluginList;
/**
 * A namespace for private module data.
 */
var Private;
(function (Private) {
    /**
     * Check the plugin for a rendering hint's value.
     *
     * #### Notes
     * The order of priority for overridden hints is as follows, from most
     * important to least:
     * 1. Data set by the end user in a settings file.
     * 2. Data set by the plugin author as a schema default.
     * 3. Data set by the plugin author as a top-level key of the schema.
     */
    function getHint(key, registry, plugin) {
        // First, give priority to checking if the hint exists in the user data.
        let hint = plugin.data.user[key];
        // Second, check to see if the hint exists in composite data, which folds
        // in default values from the schema.
        if (!hint) {
            hint = plugin.data.composite[key];
        }
        // Third, check to see if the plugin schema has defined the hint.
        if (!hint) {
            hint = plugin.schema[key];
        }
        // Finally, use the defaults from the registry schema.
        if (!hint) {
            const { properties } = registry.schema;
            hint = properties && properties[key] && properties[key].default;
        }
        return typeof hint === 'string' ? hint : '';
    }
    /**
     * Populate the plugin list.
     */
    function populateList(registry, type, selection, node) {
        const plugins = sortPlugins(registry.plugins);
        const items = plugins.map(plugin => {
            const itemTitle = `(${plugin.id}) ${plugin.schema.description}`;
            const image = getHint(coreutils_1.ICON_CLASS_KEY, registry, plugin);
            const iconClass = `jp-PluginList-icon${image ? ' ' + image : ''}`;
            const iconTitle = getHint(coreutils_1.ICON_LABEL_KEY, registry, plugin);
            return (React.createElement("li", { className: plugin.id === selection ? 'jp-mod-selected' : '', "data-id": plugin.id, key: plugin.id, title: itemTitle },
                React.createElement("span", { className: iconClass, title: iconTitle }),
                React.createElement("span", null, plugin.schema.title || plugin.id)));
        });
        ReactDOM.unmountComponentAtNode(node);
        ReactDOM.render(React.createElement(React.Fragment, null,
            React.createElement("div", { className: "jp-PluginList-switcher" },
                React.createElement("button", { "data-editor": "raw", disabled: type === 'raw' }, "Raw View"),
                React.createElement("button", { "data-editor": "table", disabled: type === 'table' }, "Table View")),
            React.createElement("ul", null, items)), node);
    }
    Private.populateList = populateList;
    /**
     * Sort a list of plugins by ID.
     */
    function sortPlugins(plugins) {
        return plugins.sort((a, b) => {
            return (a.schema.title || a.id).localeCompare(b.schema.title || b.id);
        });
    }
})(Private || (Private = {}));


/***/ }),

/***/ "uPSP":
/*!***********************************************!*\
  !*** ./node_modules/jsonify/lib/stringify.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
    escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
    gap,
    indent,
    meta = {    // table of character substitutions
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        '"' : '\\"',
        '\\': '\\\\'
    },
    rep;

function quote(string) {
    // If the string contains no control characters, no quote characters, and no
    // backslash characters, then we can safely slap some quotes around it.
    // Otherwise we must also replace the offending characters with safe escape
    // sequences.
    
    escapable.lastIndex = 0;
    return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
        var c = meta[a];
        return typeof c === 'string' ? c :
            '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
    }) + '"' : '"' + string + '"';
}

function str(key, holder) {
    // Produce a string from holder[key].
    var i,          // The loop counter.
        k,          // The member key.
        v,          // The member value.
        length,
        mind = gap,
        partial,
        value = holder[key];
    
    // If the value has a toJSON method, call it to obtain a replacement value.
    if (value && typeof value === 'object' &&
            typeof value.toJSON === 'function') {
        value = value.toJSON(key);
    }
    
    // If we were called with a replacer function, then call the replacer to
    // obtain a replacement value.
    if (typeof rep === 'function') {
        value = rep.call(holder, key, value);
    }
    
    // What happens next depends on the value's type.
    switch (typeof value) {
        case 'string':
            return quote(value);
        
        case 'number':
            // JSON numbers must be finite. Encode non-finite numbers as null.
            return isFinite(value) ? String(value) : 'null';
        
        case 'boolean':
        case 'null':
            // If the value is a boolean or null, convert it to a string. Note:
            // typeof null does not produce 'null'. The case is included here in
            // the remote chance that this gets fixed someday.
            return String(value);
            
        case 'object':
            if (!value) return 'null';
            gap += indent;
            partial = [];
            
            // Array.isArray
            if (Object.prototype.toString.apply(value) === '[object Array]') {
                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }
                
                // Join all of the elements together, separated with commas, and
                // wrap them in brackets.
                v = partial.length === 0 ? '[]' : gap ?
                    '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
                    '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }
            
            // If the replacer is an array, use it to select the members to be
            // stringified.
            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    k = rep[i];
                    if (typeof k === 'string') {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            }
            else {
                // Otherwise, iterate through all of the keys in the object.
                for (k in value) {
                    if (Object.prototype.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            }
            
        // Join all of the member texts together, separated with commas,
        // and wrap them in braces.

        v = partial.length === 0 ? '{}' : gap ?
            '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
            '{' + partial.join(',') + '}';
        gap = mind;
        return v;
    }
}

module.exports = function (value, replacer, space) {
    var i;
    gap = '';
    indent = '';
    
    // If the space parameter is a number, make an indent string containing that
    // many spaces.
    if (typeof space === 'number') {
        for (i = 0; i < space; i += 1) {
            indent += ' ';
        }
    }
    // If the space parameter is a string, it will be used as the indent string.
    else if (typeof space === 'string') {
        indent = space;
    }

    // If there is a replacer, it must be a function or an array.
    // Otherwise, throw an error.
    rep = replacer;
    if (replacer && typeof replacer !== 'function'
    && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) {
        throw new Error('JSON.stringify');
    }
    
    // Make a fake root object containing our value under the key of ''.
    // Return the result of stringifying the value.
    return str('', {'': value});
};


/***/ }),

/***/ "uR0c":
/*!**************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/SliderAccordion.js ***!
  \**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _PlotlyFold = __webpack_require__(/*! ./PlotlyFold */ "mQPs");

var _PlotlyFold2 = _interopRequireDefault(_PlotlyFold);

var _TraceRequiredPanel = __webpack_require__(/*! ./TraceRequiredPanel */ "IBvg");

var _TraceRequiredPanel2 = _interopRequireDefault(_TraceRequiredPanel);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var SliderFold = (0, _lib.connectSliderToLayout)(_PlotlyFold2.default);

var SliderAccordion = function (_Component) {
  _inherits(SliderAccordion, _Component);

  function SliderAccordion() {
    _classCallCheck(this, SliderAccordion);

    return _possibleConstructorReturn(this, (SliderAccordion.__proto__ || Object.getPrototypeOf(SliderAccordion)).apply(this, arguments));
  }

  _createClass(SliderAccordion, [{
    key: 'render',
    value: function render() {
      var _context = this.context,
          _context$layout$slide = _context.layout.sliders,
          sliders = _context$layout$slide === undefined ? [] : _context$layout$slide,
          _ = _context.localize;
      var children = this.props.children;


      var content = sliders.length > 0 && sliders.map(function (sli, i) {
        return _react2.default.createElement(
          SliderFold,
          { key: i, sliderIndex: i, name: _('Slider') + (' ' + (i + 1)) },
          children
        );
      });

      return _react2.default.createElement(
        _TraceRequiredPanel2.default,
        null,
        content ? content : null
      );
    }
  }]);

  return SliderAccordion;
}(_react.Component);

SliderAccordion.contextTypes = {
  layout: _propTypes2.default.object,
  localize: _propTypes2.default.func
};

SliderAccordion.propTypes = {
  children: _propTypes2.default.node
};

exports.default = SliderAccordion;
//# sourceMappingURL=SliderAccordion.js.map

/***/ }),

/***/ "uRb0":
/*!**************************************************************************!*\
  !*** ./node_modules/@jupyter-widgets/jupyterlab-manager/lib/renderer.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
/**
 * A renderer for widgets.
 */
class WidgetRenderer extends widgets_1.Panel {
    constructor(options, manager) {
        super();
        this.mimeType = options.mimeType;
        this._manager = manager;
    }
    renderModel(model) {
        return __awaiter(this, void 0, void 0, function* () {
            const source = model.data[this.mimeType];
            // If there is no model id, the view was removed, so hide the node.
            if (source.model_id === '') {
                this.hide();
                return Promise.resolve();
            }
            const modelPromise = this._manager.get_model(source.model_id);
            if (modelPromise) {
                try {
                    let wModel = yield modelPromise;
                    let widget = yield this._manager.display_model(void 0, wModel, void 0);
                    this.addWidget(widget);
                    // If the widget is disposed, hide this container and make sure we
                    // change the output model to reflect the view was closed.
                    widget.disposed.connect(() => {
                        this.hide();
                        source.model_id = '';
                    });
                }
                catch (err) {
                    console.log('Error displaying widget');
                    console.log(err);
                    this.node.textContent = 'Error displaying widget';
                    this.addClass('jupyter-widgets');
                }
            }
            else {
                this.node.textContent = 'Error creating widget: could not find model';
                this.addClass('jupyter-widgets');
                return Promise.resolve();
            }
        });
    }
    /**
     * Get whether the manager is disposed.
     *
     * #### Notes
     * This is a read-only property.
     */
    get isDisposed() {
        return this._manager === null;
    }
    /**
     * Dispose the resources held by the manager.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        super.dispose();
        this._manager = null;
    }
}
exports.WidgetRenderer = WidgetRenderer;


/***/ }),

/***/ "uSCx":
/*!****************************************************!*\
  !*** ./node_modules/ajv/lib/dotjs/dependencies.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_dependencies(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $schemaDeps = {},
    $propertyDeps = {},
    $ownProperties = it.opts.ownProperties;
  for ($property in $schema) {
    var $sch = $schema[$property];
    var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
    $deps[$property] = $sch;
  }
  out += 'var ' + ($errs) + ' = errors;';
  var $currentErrorPath = it.errorPath;
  out += 'var missing' + ($lvl) + ';';
  for (var $property in $propertyDeps) {
    $deps = $propertyDeps[$property];
    if ($deps.length) {
      out += ' if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
      if ($ownProperties) {
        out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') ';
      }
      if ($breakOnError) {
        out += ' && ( ';
        var arr1 = $deps;
        if (arr1) {
          var $propertyKey, $i = -1,
            l1 = arr1.length - 1;
          while ($i < l1) {
            $propertyKey = arr1[$i += 1];
            if ($i) {
              out += ' || ';
            }
            var $prop = it.util.getProperty($propertyKey),
              $useData = $data + $prop;
            out += ' ( ( ' + ($useData) + ' === undefined ';
            if ($ownProperties) {
              out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
            }
            out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) ';
          }
        }
        out += ')) {  ';
        var $propertyPath = 'missing' + $lvl,
          $missingProperty = '\' + ' + $propertyPath + ' + \'';
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
        }
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'should have ';
            if ($deps.length == 1) {
              out += 'property ' + (it.util.escapeQuotes($deps[0]));
            } else {
              out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
            }
            out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
      } else {
        out += ' ) { ';
        var arr2 = $deps;
        if (arr2) {
          var $propertyKey, i2 = -1,
            l2 = arr2.length - 1;
          while (i2 < l2) {
            $propertyKey = arr2[i2 += 1];
            var $prop = it.util.getProperty($propertyKey),
              $missingProperty = it.util.escapeQuotes($propertyKey),
              $useData = $data + $prop;
            if (it.opts._errorDataPathProperty) {
              it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
            }
            out += ' if ( ' + ($useData) + ' === undefined ';
            if ($ownProperties) {
              out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
            }
            out += ') {  var err =   '; /* istanbul ignore else */
            if (it.createErrors !== false) {
              out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
              if (it.opts.messages !== false) {
                out += ' , message: \'should have ';
                if ($deps.length == 1) {
                  out += 'property ' + (it.util.escapeQuotes($deps[0]));
                } else {
                  out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
                }
                out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
              }
              if (it.opts.verbose) {
                out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
              }
              out += ' } ';
            } else {
              out += ' {} ';
            }
            out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
          }
        }
      }
      out += ' }   ';
      if ($breakOnError) {
        $closingBraces += '}';
        out += ' else { ';
      }
    }
  }
  it.errorPath = $currentErrorPath;
  var $currentBaseId = $it.baseId;
  for (var $property in $schemaDeps) {
    var $sch = $schemaDeps[$property];
    if (it.util.schemaHasRules($sch, it.RULES.all)) {
      out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
      if ($ownProperties) {
        out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') ';
      }
      out += ') { ';
      $it.schema = $sch;
      $it.schemaPath = $schemaPath + it.util.getProperty($property);
      $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property);
      out += '  ' + (it.validate($it)) + ' ';
      $it.baseId = $currentBaseId;
      out += ' }  ';
      if ($breakOnError) {
        out += ' if (' + ($nextValid) + ') { ';
        $closingBraces += '}';
      }
    }
  }
  if ($breakOnError) {
    out += '   ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
  }
  out = it.util.cleanUpCode(out);
  return out;
}


/***/ }),

/***/ "uTOq":
/*!**************************************************************!*\
  !*** ./node_modules/codemirror/addon/search/searchcursor.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"))
  else {}
})(function(CodeMirror) {
  "use strict"
  var Pos = CodeMirror.Pos

  function regexpFlags(regexp) {
    var flags = regexp.flags
    return flags != null ? flags : (regexp.ignoreCase ? "i" : "")
      + (regexp.global ? "g" : "")
      + (regexp.multiline ? "m" : "")
  }

  function ensureFlags(regexp, flags) {
    var current = regexpFlags(regexp), target = current
    for (var i = 0; i < flags.length; i++) if (target.indexOf(flags.charAt(i)) == -1)
      target += flags.charAt(i)
    return current == target ? regexp : new RegExp(regexp.source, target)
  }

  function maybeMultiline(regexp) {
    return /\\s|\\n|\n|\\W|\\D|\[\^/.test(regexp.source)
  }

  function searchRegexpForward(doc, regexp, start) {
    regexp = ensureFlags(regexp, "g")
    for (var line = start.line, ch = start.ch, last = doc.lastLine(); line <= last; line++, ch = 0) {
      regexp.lastIndex = ch
      var string = doc.getLine(line), match = regexp.exec(string)
      if (match)
        return {from: Pos(line, match.index),
                to: Pos(line, match.index + match[0].length),
                match: match}
    }
  }

  function searchRegexpForwardMultiline(doc, regexp, start) {
    if (!maybeMultiline(regexp)) return searchRegexpForward(doc, regexp, start)

    regexp = ensureFlags(regexp, "gm")
    var string, chunk = 1
    for (var line = start.line, last = doc.lastLine(); line <= last;) {
      // This grows the search buffer in exponentially-sized chunks
      // between matches, so that nearby matches are fast and don't
      // require concatenating the whole document (in case we're
      // searching for something that has tons of matches), but at the
      // same time, the amount of retries is limited.
      for (var i = 0; i < chunk; i++) {
        if (line > last) break
        var curLine = doc.getLine(line++)
        string = string == null ? curLine : string + "\n" + curLine
      }
      chunk = chunk * 2
      regexp.lastIndex = start.ch
      var match = regexp.exec(string)
      if (match) {
        var before = string.slice(0, match.index).split("\n"), inside = match[0].split("\n")
        var startLine = start.line + before.length - 1, startCh = before[before.length - 1].length
        return {from: Pos(startLine, startCh),
                to: Pos(startLine + inside.length - 1,
                        inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length),
                match: match}
      }
    }
  }

  function lastMatchIn(string, regexp) {
    var cutOff = 0, match
    for (;;) {
      regexp.lastIndex = cutOff
      var newMatch = regexp.exec(string)
      if (!newMatch) return match
      match = newMatch
      cutOff = match.index + (match[0].length || 1)
      if (cutOff == string.length) return match
    }
  }

  function searchRegexpBackward(doc, regexp, start) {
    regexp = ensureFlags(regexp, "g")
    for (var line = start.line, ch = start.ch, first = doc.firstLine(); line >= first; line--, ch = -1) {
      var string = doc.getLine(line)
      if (ch > -1) string = string.slice(0, ch)
      var match = lastMatchIn(string, regexp)
      if (match)
        return {from: Pos(line, match.index),
                to: Pos(line, match.index + match[0].length),
                match: match}
    }
  }

  function searchRegexpBackwardMultiline(doc, regexp, start) {
    regexp = ensureFlags(regexp, "gm")
    var string, chunk = 1
    for (var line = start.line, first = doc.firstLine(); line >= first;) {
      for (var i = 0; i < chunk; i++) {
        var curLine = doc.getLine(line--)
        string = string == null ? curLine.slice(0, start.ch) : curLine + "\n" + string
      }
      chunk *= 2

      var match = lastMatchIn(string, regexp)
      if (match) {
        var before = string.slice(0, match.index).split("\n"), inside = match[0].split("\n")
        var startLine = line + before.length, startCh = before[before.length - 1].length
        return {from: Pos(startLine, startCh),
                to: Pos(startLine + inside.length - 1,
                        inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length),
                match: match}
      }
    }
  }

  var doFold, noFold
  if (String.prototype.normalize) {
    doFold = function(str) { return str.normalize("NFD").toLowerCase() }
    noFold = function(str) { return str.normalize("NFD") }
  } else {
    doFold = function(str) { return str.toLowerCase() }
    noFold = function(str) { return str }
  }

  // Maps a position in a case-folded line back to a position in the original line
  // (compensating for codepoints increasing in number during folding)
  function adjustPos(orig, folded, pos, foldFunc) {
    if (orig.length == folded.length) return pos
    for (var min = 0, max = pos + Math.max(0, orig.length - folded.length);;) {
      if (min == max) return min
      var mid = (min + max) >> 1
      var len = foldFunc(orig.slice(0, mid)).length
      if (len == pos) return mid
      else if (len > pos) max = mid
      else min = mid + 1
    }
  }

  function searchStringForward(doc, query, start, caseFold) {
    // Empty string would match anything and never progress, so we
    // define it to match nothing instead.
    if (!query.length) return null
    var fold = caseFold ? doFold : noFold
    var lines = fold(query).split(/\r|\n\r?/)

    search: for (var line = start.line, ch = start.ch, last = doc.lastLine() + 1 - lines.length; line <= last; line++, ch = 0) {
      var orig = doc.getLine(line).slice(ch), string = fold(orig)
      if (lines.length == 1) {
        var found = string.indexOf(lines[0])
        if (found == -1) continue search
        var start = adjustPos(orig, string, found, fold) + ch
        return {from: Pos(line, adjustPos(orig, string, found, fold) + ch),
                to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold) + ch)}
      } else {
        var cutFrom = string.length - lines[0].length
        if (string.slice(cutFrom) != lines[0]) continue search
        for (var i = 1; i < lines.length - 1; i++)
          if (fold(doc.getLine(line + i)) != lines[i]) continue search
        var end = doc.getLine(line + lines.length - 1), endString = fold(end), lastLine = lines[lines.length - 1]
        if (endString.slice(0, lastLine.length) != lastLine) continue search
        return {from: Pos(line, adjustPos(orig, string, cutFrom, fold) + ch),
                to: Pos(line + lines.length - 1, adjustPos(end, endString, lastLine.length, fold))}
      }
    }
  }

  function searchStringBackward(doc, query, start, caseFold) {
    if (!query.length) return null
    var fold = caseFold ? doFold : noFold
    var lines = fold(query).split(/\r|\n\r?/)

    search: for (var line = start.line, ch = start.ch, first = doc.firstLine() - 1 + lines.length; line >= first; line--, ch = -1) {
      var orig = doc.getLine(line)
      if (ch > -1) orig = orig.slice(0, ch)
      var string = fold(orig)
      if (lines.length == 1) {
        var found = string.lastIndexOf(lines[0])
        if (found == -1) continue search
        return {from: Pos(line, adjustPos(orig, string, found, fold)),
                to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold))}
      } else {
        var lastLine = lines[lines.length - 1]
        if (string.slice(0, lastLine.length) != lastLine) continue search
        for (var i = 1, start = line - lines.length + 1; i < lines.length - 1; i++)
          if (fold(doc.getLine(start + i)) != lines[i]) continue search
        var top = doc.getLine(line + 1 - lines.length), topString = fold(top)
        if (topString.slice(topString.length - lines[0].length) != lines[0]) continue search
        return {from: Pos(line + 1 - lines.length, adjustPos(top, topString, top.length - lines[0].length, fold)),
                to: Pos(line, adjustPos(orig, string, lastLine.length, fold))}
      }
    }
  }

  function SearchCursor(doc, query, pos, options) {
    this.atOccurrence = false
    this.doc = doc
    pos = pos ? doc.clipPos(pos) : Pos(0, 0)
    this.pos = {from: pos, to: pos}

    var caseFold
    if (typeof options == "object") {
      caseFold = options.caseFold
    } else { // Backwards compat for when caseFold was the 4th argument
      caseFold = options
      options = null
    }

    if (typeof query == "string") {
      if (caseFold == null) caseFold = false
      this.matches = function(reverse, pos) {
        return (reverse ? searchStringBackward : searchStringForward)(doc, query, pos, caseFold)
      }
    } else {
      query = ensureFlags(query, "gm")
      if (!options || options.multiline !== false)
        this.matches = function(reverse, pos) {
          return (reverse ? searchRegexpBackwardMultiline : searchRegexpForwardMultiline)(doc, query, pos)
        }
      else
        this.matches = function(reverse, pos) {
          return (reverse ? searchRegexpBackward : searchRegexpForward)(doc, query, pos)
        }
    }
  }

  SearchCursor.prototype = {
    findNext: function() {return this.find(false)},
    findPrevious: function() {return this.find(true)},

    find: function(reverse) {
      var result = this.matches(reverse, this.doc.clipPos(reverse ? this.pos.from : this.pos.to))

      // Implements weird auto-growing behavior on null-matches for
      // backwards-compatiblity with the vim code (unfortunately)
      while (result && CodeMirror.cmpPos(result.from, result.to) == 0) {
        if (reverse) {
          if (result.from.ch) result.from = Pos(result.from.line, result.from.ch - 1)
          else if (result.from.line == this.doc.firstLine()) result = null
          else result = this.matches(reverse, this.doc.clipPos(Pos(result.from.line - 1)))
        } else {
          if (result.to.ch < this.doc.getLine(result.to.line).length) result.to = Pos(result.to.line, result.to.ch + 1)
          else if (result.to.line == this.doc.lastLine()) result = null
          else result = this.matches(reverse, Pos(result.to.line + 1, 0))
        }
      }

      if (result) {
        this.pos = result
        this.atOccurrence = true
        return this.pos.match || true
      } else {
        var end = Pos(reverse ? this.doc.firstLine() : this.doc.lastLine() + 1, 0)
        this.pos = {from: end, to: end}
        return this.atOccurrence = false
      }
    },

    from: function() {if (this.atOccurrence) return this.pos.from},
    to: function() {if (this.atOccurrence) return this.pos.to},

    replace: function(newText, origin) {
      if (!this.atOccurrence) return
      var lines = CodeMirror.splitLines(newText)
      this.doc.replaceRange(lines, this.pos.from, this.pos.to, origin)
      this.pos.to = Pos(this.pos.from.line + lines.length - 1,
                        lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0))
    }
  }

  CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) {
    return new SearchCursor(this.doc, query, pos, caseFold)
  })
  CodeMirror.defineDocExtension("getSearchCursor", function(query, pos, caseFold) {
    return new SearchCursor(this, query, pos, caseFold)
  })

  CodeMirror.defineExtension("selectMatches", function(query, caseFold) {
    var ranges = []
    var cur = this.getSearchCursor(query, this.getCursor("from"), caseFold)
    while (cur.findNext()) {
      if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) break
      ranges.push({anchor: cur.from(), head: cur.to()})
    }
    if (ranges.length)
      this.setSelections(ranges, 0)
  })
});


/***/ }),

/***/ "uXwI":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/lv.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var units = {
    'ss': 'sekundes_sekundēm_sekunde_sekundes'.split('_'),
    'm': 'minūtes_minūtēm_minūte_minūtes'.split('_'),
    'mm': 'minūtes_minūtēm_minūte_minūtes'.split('_'),
    'h': 'stundas_stundām_stunda_stundas'.split('_'),
    'hh': 'stundas_stundām_stunda_stundas'.split('_'),
    'd': 'dienas_dienām_diena_dienas'.split('_'),
    'dd': 'dienas_dienām_diena_dienas'.split('_'),
    'M': 'mēneša_mēnešiem_mēnesis_mēneši'.split('_'),
    'MM': 'mēneša_mēnešiem_mēnesis_mēneši'.split('_'),
    'y': 'gada_gadiem_gads_gadi'.split('_'),
    'yy': 'gada_gadiem_gads_gadi'.split('_')
};
/**
 * @param withoutSuffix boolean true = a length of time; false = before/after a period of time.
 */
function format(forms, number, withoutSuffix) {
    if (withoutSuffix) {
        // E.g. "21 minūte", "3 minūtes".
        return number % 10 === 1 && number % 100 !== 11 ? forms[2] : forms[3];
    } else {
        // E.g. "21 minūtes" as in "pēc 21 minūtes".
        // E.g. "3 minūtēm" as in "pēc 3 minūtēm".
        return number % 10 === 1 && number % 100 !== 11 ? forms[0] : forms[1];
    }
}
function relativeTimeWithPlural(number, withoutSuffix, key) {
    return number + ' ' + format(units[key], number, withoutSuffix);
}
function relativeTimeWithSingular(number, withoutSuffix, key) {
    return format(units[key], number, withoutSuffix);
}
function relativeSeconds(number, withoutSuffix) {
    return withoutSuffix ? 'dažas sekundes' : 'dažām sekundēm';
}

var lv = moment.defineLocale('lv', {
    months : 'janvāris_februāris_marts_aprīlis_maijs_jūnijs_jūlijs_augusts_septembris_oktobris_novembris_decembris'.split('_'),
    monthsShort : 'jan_feb_mar_apr_mai_jūn_jūl_aug_sep_okt_nov_dec'.split('_'),
    weekdays : 'svētdiena_pirmdiena_otrdiena_trešdiena_ceturtdiena_piektdiena_sestdiena'.split('_'),
    weekdaysShort : 'Sv_P_O_T_C_Pk_S'.split('_'),
    weekdaysMin : 'Sv_P_O_T_C_Pk_S'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD.MM.YYYY.',
        LL : 'YYYY. [gada] D. MMMM',
        LLL : 'YYYY. [gada] D. MMMM, HH:mm',
        LLLL : 'YYYY. [gada] D. MMMM, dddd, HH:mm'
    },
    calendar : {
        sameDay : '[Šodien pulksten] LT',
        nextDay : '[Rīt pulksten] LT',
        nextWeek : 'dddd [pulksten] LT',
        lastDay : '[Vakar pulksten] LT',
        lastWeek : '[Pagājušā] dddd [pulksten] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'pēc %s',
        past : 'pirms %s',
        s : relativeSeconds,
        ss : relativeTimeWithPlural,
        m : relativeTimeWithSingular,
        mm : relativeTimeWithPlural,
        h : relativeTimeWithSingular,
        hh : relativeTimeWithPlural,
        d : relativeTimeWithSingular,
        dd : relativeTimeWithPlural,
        M : relativeTimeWithSingular,
        MM : relativeTimeWithPlural,
        y : relativeTimeWithSingular,
        yy : relativeTimeWithPlural
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return lv;

})));


/***/ }),

/***/ "uY1N":
/*!******************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/codemirror/theme/xq-light.css ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*\nCopyright (C) 2011 by MarkLogic Corporation\nAuthor: Mike Brevoort <mike@brevoort.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*/\n.cm-s-xq-light span.cm-keyword { line-height: 1em; font-weight: bold; color: #5A5CAD; }\n.cm-s-xq-light span.cm-atom { color: #6C8CD5; }\n.cm-s-xq-light span.cm-number { color: #164; }\n.cm-s-xq-light span.cm-def { text-decoration:underline; }\n.cm-s-xq-light span.cm-variable { color: black; }\n.cm-s-xq-light span.cm-variable-2 { color:black; }\n.cm-s-xq-light span.cm-variable-3, .cm-s-xq-light span.cm-type { color: black; }\n.cm-s-xq-light span.cm-property {}\n.cm-s-xq-light span.cm-operator {}\n.cm-s-xq-light span.cm-comment { color: #0080FF; font-style: italic; }\n.cm-s-xq-light span.cm-string { color: red; }\n.cm-s-xq-light span.cm-meta { color: yellow; }\n.cm-s-xq-light span.cm-qualifier { color: grey; }\n.cm-s-xq-light span.cm-builtin { color: #7EA656; }\n.cm-s-xq-light span.cm-bracket { color: #cc7; }\n.cm-s-xq-light span.cm-tag { color: #3F7F7F; }\n.cm-s-xq-light span.cm-attribute { color: #7F007F; }\n.cm-s-xq-light span.cm-error { color: #f00; }\n\n.cm-s-xq-light .CodeMirror-activeline-background { background: #e8f2ff; }\n.cm-s-xq-light .CodeMirror-matchingbracket { outline:1px solid grey;color:black !important;background:yellow; }\n", ""]);

// exports


/***/ }),

/***/ "uagp":
/*!********************************************************!*\
  !*** ./node_modules/elliptic/lib/elliptic/ec/index.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var BN = __webpack_require__(/*! bn.js */ "OZ/i");
var HmacDRBG = __webpack_require__(/*! hmac-drbg */ "aqI/");
var elliptic = __webpack_require__(/*! ../../elliptic */ "MzeL");
var utils = elliptic.utils;
var assert = utils.assert;

var KeyPair = __webpack_require__(/*! ./key */ "uzSA");
var Signature = __webpack_require__(/*! ./signature */ "tz+M");

function EC(options) {
  if (!(this instanceof EC))
    return new EC(options);

  // Shortcut `elliptic.ec(curve-name)`
  if (typeof options === 'string') {
    assert(elliptic.curves.hasOwnProperty(options), 'Unknown curve ' + options);

    options = elliptic.curves[options];
  }

  // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
  if (options instanceof elliptic.curves.PresetCurve)
    options = { curve: options };

  this.curve = options.curve.curve;
  this.n = this.curve.n;
  this.nh = this.n.ushrn(1);
  this.g = this.curve.g;

  // Point on curve
  this.g = options.curve.g;
  this.g.precompute(options.curve.n.bitLength() + 1);

  // Hash for function for DRBG
  this.hash = options.hash || options.curve.hash;
}
module.exports = EC;

EC.prototype.keyPair = function keyPair(options) {
  return new KeyPair(this, options);
};

EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
  return KeyPair.fromPrivate(this, priv, enc);
};

EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
  return KeyPair.fromPublic(this, pub, enc);
};

EC.prototype.genKeyPair = function genKeyPair(options) {
  if (!options)
    options = {};

  // Instantiate Hmac_DRBG
  var drbg = new HmacDRBG({
    hash: this.hash,
    pers: options.pers,
    persEnc: options.persEnc || 'utf8',
    entropy: options.entropy || elliptic.rand(this.hash.hmacStrength),
    entropyEnc: options.entropy && options.entropyEnc || 'utf8',
    nonce: this.n.toArray()
  });

  var bytes = this.n.byteLength();
  var ns2 = this.n.sub(new BN(2));
  do {
    var priv = new BN(drbg.generate(bytes));
    if (priv.cmp(ns2) > 0)
      continue;

    priv.iaddn(1);
    return this.keyFromPrivate(priv);
  } while (true);
};

EC.prototype._truncateToN = function truncateToN(msg, truncOnly) {
  var delta = msg.byteLength() * 8 - this.n.bitLength();
  if (delta > 0)
    msg = msg.ushrn(delta);
  if (!truncOnly && msg.cmp(this.n) >= 0)
    return msg.sub(this.n);
  else
    return msg;
};

EC.prototype.sign = function sign(msg, key, enc, options) {
  if (typeof enc === 'object') {
    options = enc;
    enc = null;
  }
  if (!options)
    options = {};

  key = this.keyFromPrivate(key, enc);
  msg = this._truncateToN(new BN(msg, 16));

  // Zero-extend key to provide enough entropy
  var bytes = this.n.byteLength();
  var bkey = key.getPrivate().toArray('be', bytes);

  // Zero-extend nonce to have the same byte size as N
  var nonce = msg.toArray('be', bytes);

  // Instantiate Hmac_DRBG
  var drbg = new HmacDRBG({
    hash: this.hash,
    entropy: bkey,
    nonce: nonce,
    pers: options.pers,
    persEnc: options.persEnc || 'utf8'
  });

  // Number of bytes to generate
  var ns1 = this.n.sub(new BN(1));

  for (var iter = 0; true; iter++) {
    var k = options.k ?
        options.k(iter) :
        new BN(drbg.generate(this.n.byteLength()));
    k = this._truncateToN(k, true);
    if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
      continue;

    var kp = this.g.mul(k);
    if (kp.isInfinity())
      continue;

    var kpX = kp.getX();
    var r = kpX.umod(this.n);
    if (r.cmpn(0) === 0)
      continue;

    var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
    s = s.umod(this.n);
    if (s.cmpn(0) === 0)
      continue;

    var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
                        (kpX.cmp(r) !== 0 ? 2 : 0);

    // Use complement of `s`, if it is > `n / 2`
    if (options.canonical && s.cmp(this.nh) > 0) {
      s = this.n.sub(s);
      recoveryParam ^= 1;
    }

    return new Signature({ r: r, s: s, recoveryParam: recoveryParam });
  }
};

EC.prototype.verify = function verify(msg, signature, key, enc) {
  msg = this._truncateToN(new BN(msg, 16));
  key = this.keyFromPublic(key, enc);
  signature = new Signature(signature, 'hex');

  // Perform primitive values validation
  var r = signature.r;
  var s = signature.s;
  if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
    return false;
  if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
    return false;

  // Validate signature
  var sinv = s.invm(this.n);
  var u1 = sinv.mul(msg).umod(this.n);
  var u2 = sinv.mul(r).umod(this.n);

  if (!this.curve._maxwellTrick) {
    var p = this.g.mulAdd(u1, key.getPublic(), u2);
    if (p.isInfinity())
      return false;

    return p.getX().umod(this.n).cmp(r) === 0;
  }

  // NOTE: Greg Maxwell's trick, inspired by:
  // https://git.io/vad3K

  var p = this.g.jmulAdd(u1, key.getPublic(), u2);
  if (p.isInfinity())
    return false;

  // Compare `p.x` of Jacobian point with `r`,
  // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the
  // inverse of `p.z^2`
  return p.eqXToP(r);
};

EC.prototype.recoverPubKey = function(msg, signature, j, enc) {
  assert((3 & j) === j, 'The recovery param is more than two bits');
  signature = new Signature(signature, enc);

  var n = this.n;
  var e = new BN(msg);
  var r = signature.r;
  var s = signature.s;

  // A set LSB signifies that the y-coordinate is odd
  var isYOdd = j & 1;
  var isSecondKey = j >> 1;
  if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
    throw new Error('Unable to find sencond key candinate');

  // 1.1. Let x = r + jn.
  if (isSecondKey)
    r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);
  else
    r = this.curve.pointFromX(r, isYOdd);

  var rInv = signature.r.invm(n);
  var s1 = n.sub(e).mul(rInv).umod(n);
  var s2 = s.mul(rInv).umod(n);

  // 1.6.1 Compute Q = r^-1 (sR -  eG)
  //               Q = r^-1 (sR + -eG)
  return this.g.mulAdd(s1, r, s2);
};

EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
  signature = new Signature(signature, enc);
  if (signature.recoveryParam !== null)
    return signature.recoveryParam;

  for (var i = 0; i < 4; i++) {
    var Qprime;
    try {
      Qprime = this.recoverPubKey(e, signature, i);
    } catch (e) {
      continue;
    }

    if (Qprime.eq(Q))
      return i;
  }
  throw new Error('Unable to find valid recovery factor');
};


/***/ }),

/***/ "ubXF":
/*!****************************************************!*\
  !*** ./node_modules/comment-json/lib/stringify.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


module.exports = stringify;

/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Modified from Douglas Crockford's JSON2: 
// https://github.com/douglascrockford/JSON-js
/////////////////////////////////////////////////////////////////////////////////////////////////////////

var OBJ_PROTO = Object.prototype;
var KEY_PREFIX = '// ';
var KEY_PREFIX_LENGTH = 3;

// Format integers to have at least two digits.
function format_int(n) {
  return n < 10 ? '0' + n : n;
}


var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
// table of character substitutions
var meta = {
  '\b': '\\b',
  '\t': '\\t',
  '\n': '\\n',
  '\f': '\\f',
  '\r': '\\r',
  '"' : '\\"',
  '\\': '\\\\'
};

function escape (string) {
  escapable.lastIndex = 0;
  if (!escapable.test(string)) {
    return string;
  }

  return string.replace(escapable, function(a) {
    var c = meta[a];
    return typeof c === 'string' 
      ? c 
      : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  });
}


function quote(string) {
  // Escape no control characters, no quote characters, 
  // and no backslash characters, 
  // then we can safely slap some quotes around it.
  return '"' + escape(string) + '"';
}


function is_array (subject) {
  return OBJ_PROTO.toString.apply(subject) === '[object Array]';
}


function is_object (subject) {
  return subject && typeof subject === 'object';
}


// @param {string} key
// @param {Object} holder
// @param {function()|Array} replacer
// @param {string} indent
// @param {string} gap
function str(key, holder, replacer, indent, gap) {
  var value = holder[key];

  // If the value has a toJSON method, call it to obtain a replacement value.
  if (is_object(value) && typeof value.toJSON === 'function') {
    value = value.toJSON(key);
  }

  // If we were called with a replacer function, then call the replacer to
  // obtain a replacement value.
  if (typeof replacer === 'function') {
    value = replacer.call(holder, key, value);
  }

  switch (typeof value) {
    case 'string':
      return quote(value);

    case 'number':
      // JSON numbers must be finite. Encode non-finite numbers as null.
      return isFinite(value) ? String(value) : 'null';

    case 'boolean':
    case 'null':

      // If the value is a boolean or null, convert it to a string. Note:
      // typeof null does not produce 'null'. The case is included here in
      // the remote chance that this gets fixed someday.
      return String(value);

    // If the type is 'object', we might be dealing with an object or an array or
    // null.
    case 'object':

      // Due to a specification blunder in ECMAScript, typeof null is 'object',
      // so watch out for that case.
      if (!value) {
        return 'null';
      }

      var deeper_gap = gap + indent;
      // Make an array to hold the partial results of stringifying this object value.
      var partial = [];
      var length;
      var i;

      if (is_array(value)) {
        // The value is an array. Stringify every element. Use null as a placeholder
        // for non-JSON values.
        length = value.length;
        for (i = 0; i < length; i += 1) {
          partial[i] = str(i, value, replacer, indent, deeper_gap) || 'null';
        }

        // Join all of the elements together, separated with commas, and wrap them in
        // brackets.
        return partial.length === 0 
          ? '[]' 
          : deeper_gap
            ? '[\n'
              + deeper_gap + partial.join(',\n' + deeper_gap) + '\n' 
              + gap + ']' 
            : '[' + partial.join(',') + ']';
      }

      // If the replacer is an array, use it to select the members to be stringified.
      var k; // key
      var v;

      if (replacer && is_array(replacer)) {
        length = replacer.length;
        for (i = 0; i < length; i += 1) {
          if (typeof replacer[i] === 'string') {
            k = rep[i];
            v = str(k, value, replacer, indent, deeper_gap);
            if (v) {
              partial.push(deeper_gap + quote(k) + (deeper_gap ? ': ' : ':') + v + ',\n');
            }
          }
        }

      } else {
        var comment;
        var push_prev = function (last) {
          if (!prev) {
            return;
          }

          var v = prev[0];
          if (!deeper_gap) {
            partial.push(v);
            return;
          }
          
          var top = join(prev, 1, '\n' + deeper_gap);
          var right = prev[2];
          if (top) {
            // ```js
            // {
            //   '// a': {
            //     pos: 'top',
            //     body: '// comments'
            //   },
            //   a: 1
            // }
            // ```
            // -> 
            // ```
            // {
            //   // comments
            //   a: 1
            // }
            // ```
            v = deeper_gap + top + '\n' + v;
          }

          if (!last) {
            v += ',';
          }

          if (right) {
            // ```js
            // {
            //   '// a': {
            //     pos: 'right',
            //     body: '// comments'
            //   },
            //   a: 1
            // }
            // ```
            // -> 
            // ```
            // {
            //   a: 1 // comments
            // }
            // ```
            v += ' ' + join_comments(right);
          }
          partial.push(v + (last ? '' : '\n'));
        }

        var prev;

        // Otherwise, iterate through all of the keys in the object.
        for (k in value) {
          if (OBJ_PROTO.hasOwnProperty.call(value, k) && !is_comment(k, value)) {
            v = str(k, value, replacer, indent, deeper_gap);
            if (v) {
              push_prev();
              prev = [deeper_gap + quote(k) + (deeper_gap ? ': ' : ':') + v];

              // Only apply comments when argument `space` is not empty.
              if (deeper_gap && (comment = value[KEY_PREFIX + k])) {
                prev = prev.concat(comment);
              }
            }
          }
        }
      }

      push_prev(true);

      // Join all of the member texts together, separated with commas,
      // and wrap them in braces.
      return partial.length === 0 
        ? '{}' 
        : deeper_gap
          ? '{\n' 
            + partial.join('').replace(/,\n$/, '') + '\n' 
            + gap + '}'
          : '{' + partial.join(',') + '}';
  }
}


function is_comment (key, holder) {
  return key === '//^'
    || key === '//$'
    || !!~key.indexOf(KEY_PREFIX)
      // And the corresponding property must exist
      && key.slice(KEY_PREFIX_LENGTH) in holder;
}


// @param {function()|Array} replacer
// @param {string|number} space
function stringify (value, replacer, space) {

  // The stringify method takes a value and an optional replacer, and an optional
  // space parameter, and returns a JSON text. The replacer can be a function
  // that can replace values, or an array of strings that will select the keys.
  // A default replacer method can be provided. Use of the space parameter can
  // produce text that is more easily readable.

  // If the space parameter is a number, make an indent string containing that
  // many spaces.
  var i;
  var indent = '';
  if (typeof space === 'number') {
    for (i = 0; i < space; i += 1) {
      indent += ' ';
    }

  // If the space parameter is a string, it will be used as the indent string.
  } else if (typeof space === 'string') {
    indent = space;
  }

  // If there is a replacer, it must be a function or an array.
  // Otherwise, throw an error.
  if (replacer && typeof replacer !== 'function' && !is_array(replacer)) {
    throw new Error('JSON.stringify');
  }

  if (!is_object(value)) {
    return str('', {'': value}, replacer, indent, '');
  }

  var head_comments = join(value, '//^');
  var foot_comments = join(value, '//$');

  var result = str('', {'': value}, replacer, indent, '');

  // Make a fake root object containing our value under the key of ''.
  // Return the result of stringifying the value.
  return indent
    ? [head_comments, result, foot_comments]
      // filter empty `head_comments` or `foot_comments`
      .filter(Boolean)
      .join('\n')
    : result;
};


function join (host, key, joiner) {
  return host[key]
    ? join_comments(host[key], joiner)
    : '';
}


function join_comments (value, joiner) {
  return is_array(value)
    ? value.join(joiner || '\n')
    : value;
}


/***/ }),

/***/ "ubbP":
/*!********************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeScattermapboxIcon.js ***!
  \********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeScattermapboxIcon = function TraceTypeScattermapboxIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement('path', { fill: 'none', d: 'M0 0h46v46H0z' }),
        _react2.default.createElement('path', { fill: '#25fdfc', stroke: '#1d9bfb', d: 'M17.87 20.197l2.827-2.829 6.364 6.364-2.828 2.829z', strokeMiterlimit: '10', strokeWidth: '2' }),
        _react2.default.createElement('path', { d: 'M27.06 26.56a6 6 0 0 0 0 8.486l8.486-8.485a6 6 0 0 0-8.485 0z', fill: '#fff' }),
        _react2.default.createElement('path', { d: 'M27.06 26.56a6 6 0 0 0 0 8.486l8.486-8.485a6 6 0 0 0-8.485 0z', fill: 'none', stroke: '#1d9bfb', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2' }),
        _react2.default.createElement('path', { fill: '#fff', stroke: '#1d9bfb', d: 'M31.303 30.803l1.415 1.415', strokeLinecap: 'round', strokeMiterlimit: '10', strokeWidth: '2' }),
        _react2.default.createElement('path', { fill: '#fff', stroke: '#1d9bfb', d: 'M7.968 30.096l7.778-7.778 5.657 5.657-7.778 7.778zM19.8 23.482l-1.142 1.143', strokeMiterlimit: '10', strokeWidth: '2' }),
        _react2.default.createElement('path', { fill: '#25fdfc', stroke: '#1d9bfb', d: 'M13.979 24.086l5.657 5.657M12.565 25.5l5.657 5.657m-7.071-4.243l5.657 5.657m-7.072-4.243l5.657 5.657', strokeMiterlimit: '10' }),
        _react2.default.createElement('path', { fill: '#fff', stroke: '#1d9bfb', d: 'M36.254 13.125l-7.779 7.779-5.656-5.657 7.778-7.778zM24.232 19.49l1.414-1.415', strokeMiterlimit: '10', strokeWidth: '2' }),
        _react2.default.createElement('path', { fill: '#25fdfc', stroke: '#1d9bfb', d: 'M24.586 13.479l5.657 5.657M26 12.065l5.657 5.657m-4.243-7.071l5.657 5.657m-4.243-7.072l5.657 5.657', strokeMiterlimit: '10' }),
        _react2.default.createElement('path', { d: 'M16.454 15.954a2 2 0 0 1 2.829 0l1.414 1.414-2.829 2.829-1.414-1.415a2 2 0 0 1 0-2.828z', fill: 'none', stroke: '#1d9bfb', strokeMiterlimit: '10', strokeWidth: '2' })
    );
};

exports.default = TraceTypeScattermapboxIcon;

/***/ }),

/***/ "ucVw":
/*!************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/connectCartesianSubplotToLayout.js ***!
  \************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

exports.default = connectCartesianSubplotToLayout;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _lib = __webpack_require__(/*! ../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function connectCartesianSubplotToLayout(WrappedComponent) {
  var SubplotConnectedComponent = function (_Component) {
    _inherits(SubplotConnectedComponent, _Component);

    function SubplotConnectedComponent(props, context) {
      _classCallCheck(this, SubplotConnectedComponent);

      var _this = _possibleConstructorReturn(this, (SubplotConnectedComponent.__proto__ || Object.getPrototypeOf(SubplotConnectedComponent)).call(this, props, context));

      _this.updateSubplot = _this.updateSubplot.bind(_this);
      _this.setLocals(props, context);
      return _this;
    }

    _createClass(SubplotConnectedComponent, [{
      key: 'componentWillReceiveProps',
      value: function componentWillReceiveProps(nextProps, nextContext) {
        this.setLocals(nextProps, nextContext);
      }
    }, {
      key: 'setLocals',
      value: function setLocals(props, context) {
        var xaxis = props.xaxis,
            yaxis = props.yaxis,
            traceIndexes = props.traceIndexes;
        var container = context.container,
            fullContainer = context.fullContainer,
            data = context.data;


        this.container = {
          xaxis: container[xaxis],
          yaxis: container[yaxis]
        };
        this.fullContainer = {
          xaxis: fullContainer[xaxis],
          yaxis: fullContainer[yaxis]
        };

        var trace = traceIndexes.length > 0 ? data[traceIndexes[0]] : {};
        var fullTrace = (0, _lib.getFullTrace)(props, context);

        if (trace && fullTrace) {
          this.icon = (0, _lib.renderTraceIcon)((0, _lib.plotlyTraceToCustomTrace)(trace));
          this.name = fullTrace.name;
        }
      }
    }, {
      key: 'getChildContext',
      value: function getChildContext() {
        var _this2 = this;

        return {
          getValObject: function getValObject(attr) {
            return !_this2.context.getValObject ? null : _this2.context.getValObject(attr.replace('xaxis', _this2.props.xaxis).replace('yaxis', _this2.props.yaxis));
          },
          updateContainer: this.updateSubplot,
          deleteContainer: this.deleteSubplot,
          container: this.container,
          fullContainer: this.fullContainer
        };
      }
    }, {
      key: 'updateSubplot',
      value: function updateSubplot(update) {
        var newUpdate = {};
        for (var key in update) {
          var newKey = key.replace('xaxis', this.props.xaxis).replace('yaxis', this.props.yaxis);
          newUpdate[newKey] = update[key];
        }
        this.context.updateContainer(newUpdate);
      }
    }, {
      key: 'render',
      value: function render() {
        return _react2.default.createElement(WrappedComponent, _extends({ name: this.name, icon: this.icon }, this.props));
      }
    }]);

    return SubplotConnectedComponent;
  }(_react.Component);

  SubplotConnectedComponent.displayName = 'SubplotConnected' + (0, _lib.getDisplayName)(WrappedComponent);

  SubplotConnectedComponent.propTypes = {
    xaxis: _propTypes2.default.string.isRequired,
    yaxis: _propTypes2.default.string.isRequired
  };

  SubplotConnectedComponent.contextTypes = {
    container: _propTypes2.default.object,
    fullContainer: _propTypes2.default.object,
    data: _propTypes2.default.array,
    fullData: _propTypes2.default.array,
    onUpdate: _propTypes2.default.func,
    updateContainer: _propTypes2.default.func,
    getValObject: _propTypes2.default.func
  };

  SubplotConnectedComponent.childContextTypes = {
    updateContainer: _propTypes2.default.func,
    deleteContainer: _propTypes2.default.func,
    container: _propTypes2.default.object,
    fullContainer: _propTypes2.default.object,
    getValObject: _propTypes2.default.func
  };

  var plotly_editor_traits = WrappedComponent.plotly_editor_traits;

  SubplotConnectedComponent.plotly_editor_traits = plotly_editor_traits;

  return SubplotConnectedComponent;
}
//# sourceMappingURL=connectCartesianSubplotToLayout.js.map

/***/ }),

/***/ "ueFs":
/*!*****************************************************************!*\
  !*** ./node_modules/draft-js/lib/convertFromRawToDraftState.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule convertFromRawToDraftState
 * @format
 * 
 */



var _assign = __webpack_require__(/*! object-assign */ "MgzW");

var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var ContentBlock = __webpack_require__(/*! ./ContentBlock */ "8uQm");
var ContentBlockNode = __webpack_require__(/*! ./ContentBlockNode */ "JL7T");
var ContentState = __webpack_require__(/*! ./ContentState */ "LpQA");
var DraftEntity = __webpack_require__(/*! ./DraftEntity */ "TzU/");
var DraftFeatureFlags = __webpack_require__(/*! ./DraftFeatureFlags */ "cX45");
var DraftTreeAdapter = __webpack_require__(/*! ./DraftTreeAdapter */ "PFU8");
var Immutable = __webpack_require__(/*! immutable */ "JPcv");
var SelectionState = __webpack_require__(/*! ./SelectionState */ "hMpd");

var createCharacterList = __webpack_require__(/*! ./createCharacterList */ "TlXQ");
var decodeEntityRanges = __webpack_require__(/*! ./decodeEntityRanges */ "bNdj");
var decodeInlineStyleRanges = __webpack_require__(/*! ./decodeInlineStyleRanges */ "RCR6");
var generateRandomKey = __webpack_require__(/*! ./generateRandomKey */ "rJY1");
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");

var experimentalTreeDataSupport = DraftFeatureFlags.draft_tree_data_support;

var List = Immutable.List,
    Map = Immutable.Map,
    OrderedMap = Immutable.OrderedMap;


var decodeBlockNodeConfig = function decodeBlockNodeConfig(block, entityMap) {
  var key = block.key,
      type = block.type,
      data = block.data,
      text = block.text,
      depth = block.depth;


  var blockNodeConfig = {
    text: text,
    depth: depth || 0,
    type: type || 'unstyled',
    key: key || generateRandomKey(),
    data: Map(data),
    characterList: decodeCharacterList(block, entityMap)
  };

  return blockNodeConfig;
};

var decodeCharacterList = function decodeCharacterList(block, entityMap) {
  var text = block.text,
      rawEntityRanges = block.entityRanges,
      rawInlineStyleRanges = block.inlineStyleRanges;


  var entityRanges = rawEntityRanges || [];
  var inlineStyleRanges = rawInlineStyleRanges || [];

  // Translate entity range keys to the DraftEntity map.
  return createCharacterList(decodeInlineStyleRanges(text, inlineStyleRanges), decodeEntityRanges(text, entityRanges.filter(function (range) {
    return entityMap.hasOwnProperty(range.key);
  }).map(function (range) {
    return _extends({}, range, { key: entityMap[range.key] });
  })));
};

var addKeyIfMissing = function addKeyIfMissing(block) {
  return _extends({}, block, {
    key: block.key || generateRandomKey()
  });
};

/**
 * Node stack is responsible to ensure we traverse the tree only once
 * in depth order, while also providing parent refs to inner nodes to
 * construct their links.
 */
var updateNodeStack = function updateNodeStack(stack, nodes, parentRef) {
  var nodesWithParentRef = nodes.map(function (block) {
    return _extends({}, block, {
      parentRef: parentRef
    });
  });

  // since we pop nodes from the stack we need to insert them in reverse
  return stack.concat(nodesWithParentRef.reverse());
};

/**
 * This will build a tree draft content state by creating the node
 * reference links into a single tree walk. Each node has a link
 * reference to "parent", "children", "nextSibling" and "prevSibling"
 * blockMap will be created using depth ordering.
 */
var decodeContentBlockNodes = function decodeContentBlockNodes(blocks, entityMap) {
  return blocks
  // ensure children have valid keys to enable sibling links
  .map(addKeyIfMissing).reduce(function (blockMap, block, index) {
    !Array.isArray(block.children) ?  true ? invariant(false, 'invalid RawDraftContentBlock can not be converted to ContentBlockNode') : undefined : void 0;

    // ensure children have valid keys to enable sibling links
    var children = block.children.map(addKeyIfMissing);

    // root level nodes
    var contentBlockNode = new ContentBlockNode(_extends({}, decodeBlockNodeConfig(block, entityMap), {
      prevSibling: index === 0 ? null : blocks[index - 1].key,
      nextSibling: index === blocks.length - 1 ? null : blocks[index + 1].key,
      children: List(children.map(function (child) {
        return child.key;
      }))
    }));

    // push root node to blockMap
    blockMap = blockMap.set(contentBlockNode.getKey(), contentBlockNode);

    // this stack is used to ensure we visit all nodes respecting depth ordering
    var stack = updateNodeStack([], children, contentBlockNode);

    // start computing children nodes
    while (stack.length > 0) {
      // we pop from the stack and start processing this node
      var node = stack.pop();

      // parentRef already points to a converted ContentBlockNode
      var parentRef = node.parentRef;
      var siblings = parentRef.getChildKeys();
      var _index = siblings.indexOf(node.key);
      var isValidBlock = Array.isArray(node.children);

      if (!isValidBlock) {
        !isValidBlock ?  true ? invariant(false, 'invalid RawDraftContentBlock can not be converted to ContentBlockNode') : undefined : void 0;
        break;
      }

      // ensure children have valid keys to enable sibling links
      var _children = node.children.map(addKeyIfMissing);

      var _contentBlockNode = new ContentBlockNode(_extends({}, decodeBlockNodeConfig(node, entityMap), {
        parent: parentRef.getKey(),
        children: List(_children.map(function (child) {
          return child.key;
        })),
        prevSibling: _index === 0 ? null : siblings.get(_index - 1),
        nextSibling: _index === siblings.size - 1 ? null : siblings.get(_index + 1)
      }));

      // push node to blockMap
      blockMap = blockMap.set(_contentBlockNode.getKey(), _contentBlockNode);

      // this stack is used to ensure we visit all nodes respecting depth ordering
      stack = updateNodeStack(stack, _children, _contentBlockNode);
    }

    return blockMap;
  }, OrderedMap());
};

var decodeContentBlocks = function decodeContentBlocks(blocks, entityMap) {
  return OrderedMap(blocks.map(function (block) {
    var contentBlock = new ContentBlock(decodeBlockNodeConfig(block, entityMap));
    return [contentBlock.getKey(), contentBlock];
  }));
};

var decodeRawBlocks = function decodeRawBlocks(rawState, entityMap) {
  var isTreeRawBlock = Array.isArray(rawState.blocks[0].children);
  var rawBlocks = experimentalTreeDataSupport && !isTreeRawBlock ? DraftTreeAdapter.fromRawStateToRawTreeState(rawState).blocks : rawState.blocks;

  if (!experimentalTreeDataSupport) {
    return decodeContentBlocks(isTreeRawBlock ? DraftTreeAdapter.fromRawTreeStateToRawState(rawState).blocks : rawBlocks, entityMap);
  }

  return decodeContentBlockNodes(rawBlocks, entityMap);
};

var decodeRawEntityMap = function decodeRawEntityMap(rawState) {
  var rawEntityMap = rawState.entityMap;

  var entityMap = {};

  // TODO: Update this once we completely remove DraftEntity
  Object.keys(rawEntityMap).forEach(function (rawEntityKey) {
    var _rawEntityMap$rawEnti = rawEntityMap[rawEntityKey],
        type = _rawEntityMap$rawEnti.type,
        mutability = _rawEntityMap$rawEnti.mutability,
        data = _rawEntityMap$rawEnti.data;

    // get the key reference to created entity

    entityMap[rawEntityKey] = DraftEntity.__create(type, mutability, data || {});
  });

  return entityMap;
};

var convertFromRawToDraftState = function convertFromRawToDraftState(rawState) {
  !Array.isArray(rawState.blocks) ?  true ? invariant(false, 'invalid RawDraftContentState') : undefined : void 0;

  // decode entities
  var entityMap = decodeRawEntityMap(rawState);

  // decode blockMap
  var blockMap = decodeRawBlocks(rawState, entityMap);

  // create initial selection
  var selectionState = blockMap.isEmpty() ? new SelectionState() : SelectionState.createEmpty(blockMap.first().getKey());

  return new ContentState({
    blockMap: blockMap,
    entityMap: entityMap,
    selectionBefore: selectionState,
    selectionAfter: selectionState
  });
};

module.exports = convertFromRawToDraftState;

/***/ }),

/***/ "ugD5":
/*!****************************************************!*\
  !*** ./node_modules/ajv/lib/compile/schema_obj.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var util = __webpack_require__(/*! ./util */ "+9rK");

module.exports = SchemaObject;

function SchemaObject(obj) {
  util.copy(obj, this);
}


/***/ }),

/***/ "ujuU":
/*!****************************************************************************!*\
  !*** ./node_modules/draft-js/lib/keyCommandMoveSelectionToStartOfBlock.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule keyCommandMoveSelectionToStartOfBlock
 * @format
 * 
 */



var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");

/**
 * Collapse selection at the start of the first selected block. This is used
 * for Firefox versions that attempt to navigate forward/backward instead of
 * moving the cursor. Other browsers are able to move the cursor natively.
 */
function keyCommandMoveSelectionToStartOfBlock(editorState) {
  var selection = editorState.getSelection();
  var startKey = selection.getStartKey();
  return EditorState.set(editorState, {
    selection: selection.merge({
      anchorKey: startKey,
      anchorOffset: 0,
      focusKey: startKey,
      focusOffset: 0,
      isBackward: false
    }),
    forceSelection: true
  });
}

module.exports = keyCommandMoveSelectionToStartOfBlock;

/***/ }),

/***/ "umhg":
/*!************************************************************!*\
  !*** ./node_modules/@jupyterlab/docmanager/lib/dialogs.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
/**
 * The class name added to file dialogs.
 */
const FILE_DIALOG_CLASS = 'jp-FileDialog';
/**
 * The class name added for the new name label in the rename dialog
 */
const RENAME_NEWNAME_TITLE_CLASS = 'jp-new-name-title';
/**
 * Rename a file with a dialog.
 */
function renameDialog(manager, oldPath) {
    return apputils_1.showDialog({
        title: 'Rename File',
        body: new RenameHandler(oldPath),
        focusNodeSelector: 'input',
        buttons: [apputils_1.Dialog.cancelButton(), apputils_1.Dialog.okButton({ label: 'RENAME' })]
    }).then(result => {
        if (!result.value) {
            return;
        }
        if (!isValidFileName(result.value)) {
            apputils_1.showErrorMessage('Rename Error', Error(`"${result.value}" is not a valid name for a file. ` +
                `Names must have nonzero length, ` +
                `and cannot include "/", "\\", or ":"`));
            return null;
        }
        let basePath = coreutils_1.PathExt.dirname(oldPath);
        let newPath = coreutils_1.PathExt.join(basePath, result.value);
        return renameFile(manager, oldPath, newPath);
    });
}
exports.renameDialog = renameDialog;
/**
 * Rename a file, asking for confirmation if it is overwriting another.
 */
function renameFile(manager, oldPath, newPath) {
    return manager.rename(oldPath, newPath).catch(error => {
        if (error.message.indexOf('409') === -1) {
            throw error;
        }
        return shouldOverwrite(newPath).then(value => {
            if (value) {
                return manager.overwrite(oldPath, newPath);
            }
            return Promise.reject('File not renamed');
        });
    });
}
exports.renameFile = renameFile;
/**
 * Ask the user whether to overwrite a file.
 */
function shouldOverwrite(path) {
    let options = {
        title: 'Overwrite file?',
        body: `"${path}" already exists, overwrite?`,
        buttons: [apputils_1.Dialog.cancelButton(), apputils_1.Dialog.warnButton({ label: 'OVERWRITE' })]
    };
    return apputils_1.showDialog(options).then(result => {
        return Promise.resolve(result.button.accept);
    });
}
exports.shouldOverwrite = shouldOverwrite;
/**
 * Test whether a name is a valid file name
 *
 * Disallows "/", "\", and ":" in file names, as well as names with zero length.
 */
function isValidFileName(name) {
    const validNameExp = /[\/\\:]/;
    return name.length > 0 && !validNameExp.test(name);
}
exports.isValidFileName = isValidFileName;
/**
 * A widget used to rename a file.
 */
class RenameHandler extends widgets_1.Widget {
    /**
     * Construct a new "rename" dialog.
     */
    constructor(oldPath) {
        super({ node: Private.createRenameNode(oldPath) });
        this.addClass(FILE_DIALOG_CLASS);
        let ext = coreutils_1.PathExt.extname(oldPath);
        let value = (this.inputNode.value = coreutils_1.PathExt.basename(oldPath));
        this.inputNode.setSelectionRange(0, value.length - ext.length);
    }
    /**
     * Get the input text node.
     */
    get inputNode() {
        return this.node.getElementsByTagName('input')[0];
    }
    /**
     * Get the value of the widget.
     */
    getValue() {
        return this.inputNode.value;
    }
}
/*
 * A widget used to open a file directly.
 */
class OpenDirectWidget extends widgets_1.Widget {
    /**
     * Construct a new open file widget.
     */
    constructor() {
        super({ node: Private.createOpenNode() });
    }
    /**
     * Get the value of the widget.
     */
    getValue() {
        return this.inputNode.value;
    }
    /**
     * Get the input text node.
     */
    get inputNode() {
        return this.node.getElementsByTagName('input')[0];
    }
}
/**
 * Create the node for the open handler.
 */
function getOpenPath(contentsManager) {
    return apputils_1.showDialog({
        title: 'Open File',
        body: new OpenDirectWidget(),
        buttons: [apputils_1.Dialog.cancelButton(), apputils_1.Dialog.okButton({ label: 'OPEN' })],
        focusNodeSelector: 'input'
    }).then((result) => {
        if (result.button.label === 'OPEN') {
            return result.value;
        }
        return;
    });
}
exports.getOpenPath = getOpenPath;
/**
 * A namespace for private data.
 */
var Private;
(function (Private) {
    /**
     * Create the node for a rename handler.
     */
    function createRenameNode(oldPath) {
        let body = document.createElement('div');
        let existingLabel = document.createElement('label');
        existingLabel.textContent = 'File Path';
        let existingPath = document.createElement('span');
        existingPath.textContent = oldPath;
        let nameTitle = document.createElement('label');
        nameTitle.textContent = 'New Name';
        nameTitle.className = RENAME_NEWNAME_TITLE_CLASS;
        let name = document.createElement('input');
        body.appendChild(existingLabel);
        body.appendChild(existingPath);
        body.appendChild(nameTitle);
        body.appendChild(name);
        return body;
    }
    Private.createRenameNode = createRenameNode;
    /**
     * Create the node for a open widget.
     */
    function createOpenNode() {
        let body = document.createElement('div');
        let existingLabel = document.createElement('label');
        existingLabel.textContent = 'File Path:';
        let input = document.createElement('input');
        input.value = '';
        input.placeholder = '/path/to/file';
        body.appendChild(existingLabel);
        body.appendChild(input);
        return body;
    }
    Private.createOpenNode = createOpenNode;
})(Private || (Private = {}));


/***/ }),

/***/ "up8o":
/*!**************************************************!*\
  !*** ./node_modules/mdi-react/RotateLeftIcon.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var RotateLeftIcon = function RotateLeftIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M13,4.07V1L8.45,5.55L13,10V6.09C15.84,6.57 18,9.03 18,12C18,14.97 15.84,17.43 13,17.91V19.93C16.95,19.44 20,16.08 20,12C20,7.92 16.95,4.56 13,4.07M7.1,18.32C8.26,19.22 9.61,19.76 11,19.93V17.9C10.13,17.75 9.29,17.41 8.54,16.87L7.1,18.32M6.09,13H4.07C4.24,14.39 4.79,15.73 5.69,16.89L7.1,15.47C6.58,14.72 6.23,13.88 6.09,13M7.11,8.53L5.7,7.11C4.8,8.27 4.24,9.61 4.07,11H6.09C6.23,10.13 6.58,9.28 7.11,8.53Z' })
  );
};

module.exports = RotateLeftIcon;


/***/ }),

/***/ "uq1y":
/*!*************************************************************!*\
  !*** ./node_modules/@jupyterlab/codeeditor/style/index.css ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "3u4H");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "usKN":
/*!****************************************************!*\
  !*** ./node_modules/browserify-aes/modes/index.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var modeModules = {
  ECB: __webpack_require__(/*! ./ecb */ "AUX7"),
  CBC: __webpack_require__(/*! ./cbc */ "wRn4"),
  CFB: __webpack_require__(/*! ./cfb */ "NQVK"),
  CFB8: __webpack_require__(/*! ./cfb8 */ "YskG"),
  CFB1: __webpack_require__(/*! ./cfb1 */ "Ujlg"),
  OFB: __webpack_require__(/*! ./ofb */ "UWVS"),
  CTR: __webpack_require__(/*! ./ctr */ "at63"),
  GCM: __webpack_require__(/*! ./ctr */ "at63")
}

var modes = __webpack_require__(/*! ./list.json */ "6F8h")

for (var key in modes) {
  modes[key].module = modeModules[modes[key].mode]
}

module.exports = modes


/***/ }),

/***/ "ut/Y":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_baseIteratee.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseMatches = __webpack_require__(/*! ./_baseMatches */ "ZCpW"),
    baseMatchesProperty = __webpack_require__(/*! ./_baseMatchesProperty */ "GDhZ"),
    identity = __webpack_require__(/*! ./identity */ "zZ0H"),
    isArray = __webpack_require__(/*! ./isArray */ "Z0cm"),
    property = __webpack_require__(/*! ./property */ "+c4W");

/**
 * 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);
}

module.exports = baseIteratee;


/***/ }),

/***/ "utho":
/*!********************************************************!*\
  !*** ./node_modules/@jupyterlab/cells/style/index.css ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "H7Er");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "utxS":
/*!************************************************************!*\
  !*** ./node_modules/plotlywidget/src/jupyterlab-plugin.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var plotly = __webpack_require__(/*! ./index */ "P2i7");
var base = __webpack_require__(/*! @jupyter-widgets/base */ "Rtm6");

/**
 * The widget manager provider.
 */
module.exports = {
  id: 'plotlywidget',
  requires: [base.IJupyterWidgetRegistry],
  activate: function(app, widgets) {
      widgets.registerWidget({
          name: 'plotlywidget',
          version: plotly.version,
          exports: plotly
      });
    },
  autoStart: true
};


/***/ }),

/***/ "uxIL":
/*!*************************************************!*\
  !*** ./node_modules/mdi-react/ArrowDownIcon.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var ArrowDownIcon = function ArrowDownIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M11,4H13V16L18.5,10.5L19.92,11.92L12,19.84L4.08,11.92L5.5,10.5L11,16V4Z' })
  );
};

module.exports = ArrowDownIcon;


/***/ }),

/***/ "uxQ0":
/*!***************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/kernel/index.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(__webpack_require__(/*! ./kernel */ "0ks7"));
__export(__webpack_require__(/*! ./manager */ "d4k2"));
__export(__webpack_require__(/*! ./messages */ "Wg3t"));


/***/ }),

/***/ "uzSA":
/*!******************************************************!*\
  !*** ./node_modules/elliptic/lib/elliptic/ec/key.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var BN = __webpack_require__(/*! bn.js */ "OZ/i");
var elliptic = __webpack_require__(/*! ../../elliptic */ "MzeL");
var utils = elliptic.utils;
var assert = utils.assert;

function KeyPair(ec, options) {
  this.ec = ec;
  this.priv = null;
  this.pub = null;

  // KeyPair(ec, { priv: ..., pub: ... })
  if (options.priv)
    this._importPrivate(options.priv, options.privEnc);
  if (options.pub)
    this._importPublic(options.pub, options.pubEnc);
}
module.exports = KeyPair;

KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
  if (pub instanceof KeyPair)
    return pub;

  return new KeyPair(ec, {
    pub: pub,
    pubEnc: enc
  });
};

KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
  if (priv instanceof KeyPair)
    return priv;

  return new KeyPair(ec, {
    priv: priv,
    privEnc: enc
  });
};

KeyPair.prototype.validate = function validate() {
  var pub = this.getPublic();

  if (pub.isInfinity())
    return { result: false, reason: 'Invalid public key' };
  if (!pub.validate())
    return { result: false, reason: 'Public key is not a point' };
  if (!pub.mul(this.ec.curve.n).isInfinity())
    return { result: false, reason: 'Public key * N != O' };

  return { result: true, reason: null };
};

KeyPair.prototype.getPublic = function getPublic(compact, enc) {
  // compact is optional argument
  if (typeof compact === 'string') {
    enc = compact;
    compact = null;
  }

  if (!this.pub)
    this.pub = this.ec.g.mul(this.priv);

  if (!enc)
    return this.pub;

  return this.pub.encode(enc, compact);
};

KeyPair.prototype.getPrivate = function getPrivate(enc) {
  if (enc === 'hex')
    return this.priv.toString(16, 2);
  else
    return this.priv;
};

KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
  this.priv = new BN(key, enc || 16);

  // Ensure that the priv won't be bigger than n, otherwise we may fail
  // in fixed multiplication method
  this.priv = this.priv.umod(this.ec.curve.n);
};

KeyPair.prototype._importPublic = function _importPublic(key, enc) {
  if (key.x || key.y) {
    // Montgomery points only have an `x` coordinate.
    // Weierstrass/Edwards points on the other hand have both `x` and
    // `y` coordinates.
    if (this.ec.curve.type === 'mont') {
      assert(key.x, 'Need x coordinate');
    } else if (this.ec.curve.type === 'short' ||
               this.ec.curve.type === 'edwards') {
      assert(key.x && key.y, 'Need both x and y coordinate');
    }
    this.pub = this.ec.curve.point(key.x, key.y);
    return;
  }
  this.pub = this.ec.curve.decodePoint(key, enc);
};

// ECDH
KeyPair.prototype.derive = function derive(pub) {
  return pub.mul(this.priv).getX();
};

// ECDSA
KeyPair.prototype.sign = function sign(msg, enc, options) {
  return this.ec.sign(msg, this, enc, options);
};

KeyPair.prototype.verify = function verify(msg, signature) {
  return this.ec.verify(msg, signature, this);
};

KeyPair.prototype.inspect = function inspect() {
  return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
         ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
};


/***/ }),

/***/ "v+jr":
/*!*********************************************!*\
  !*** ./node_modules/xterm/lib/Linkifier.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Types_1 = __webpack_require__(/*! ./Types */ "Ltj7");
var MouseZoneManager_1 = __webpack_require__(/*! ./input/MouseZoneManager */ "piSt");
var EventEmitter_1 = __webpack_require__(/*! ./EventEmitter */ "t2YR");
var Linkifier = (function (_super) {
    __extends(Linkifier, _super);
    function Linkifier(_terminal) {
        var _this = _super.call(this) || this;
        _this._terminal = _terminal;
        _this._linkMatchers = [];
        _this._nextLinkMatcherId = 0;
        _this._rowsToLinkify = {
            start: null,
            end: null
        };
        return _this;
    }
    Linkifier.prototype.attachToDom = function (mouseZoneManager) {
        this._mouseZoneManager = mouseZoneManager;
    };
    Linkifier.prototype.linkifyRows = function (start, end) {
        var _this = this;
        if (!this._mouseZoneManager) {
            return;
        }
        if (this._rowsToLinkify.start === null) {
            this._rowsToLinkify.start = start;
            this._rowsToLinkify.end = end;
        }
        else {
            this._rowsToLinkify.start = Math.min(this._rowsToLinkify.start, start);
            this._rowsToLinkify.end = Math.max(this._rowsToLinkify.end, end);
        }
        this._mouseZoneManager.clearAll(start, end);
        if (this._rowsTimeoutId) {
            clearTimeout(this._rowsTimeoutId);
        }
        this._rowsTimeoutId = setTimeout(function () { return _this._linkifyRows(); }, Linkifier.TIME_BEFORE_LINKIFY);
    };
    Linkifier.prototype._linkifyRows = function () {
        this._rowsTimeoutId = null;
        for (var i = this._rowsToLinkify.start; i <= this._rowsToLinkify.end; i++) {
            this._linkifyRow(i);
        }
        this._rowsToLinkify.start = null;
        this._rowsToLinkify.end = null;
    };
    Linkifier.prototype.registerLinkMatcher = function (regex, handler, options) {
        if (options === void 0) { options = {}; }
        if (!handler) {
            throw new Error('handler must be defined');
        }
        var matcher = {
            id: this._nextLinkMatcherId++,
            regex: regex,
            handler: handler,
            matchIndex: options.matchIndex,
            validationCallback: options.validationCallback,
            hoverTooltipCallback: options.tooltipCallback,
            hoverLeaveCallback: options.leaveCallback,
            willLinkActivate: options.willLinkActivate,
            priority: options.priority || 0
        };
        this._addLinkMatcherToList(matcher);
        return matcher.id;
    };
    Linkifier.prototype._addLinkMatcherToList = function (matcher) {
        if (this._linkMatchers.length === 0) {
            this._linkMatchers.push(matcher);
            return;
        }
        for (var i = this._linkMatchers.length - 1; i >= 0; i--) {
            if (matcher.priority <= this._linkMatchers[i].priority) {
                this._linkMatchers.splice(i + 1, 0, matcher);
                return;
            }
        }
        this._linkMatchers.splice(0, 0, matcher);
    };
    Linkifier.prototype.deregisterLinkMatcher = function (matcherId) {
        for (var i = 0; i < this._linkMatchers.length; i++) {
            if (this._linkMatchers[i].id === matcherId) {
                this._linkMatchers.splice(i, 1);
                return true;
            }
        }
        return false;
    };
    Linkifier.prototype._linkifyRow = function (rowIndex) {
        var absoluteRowIndex = this._terminal.buffer.ydisp + rowIndex;
        if (absoluteRowIndex >= this._terminal.buffer.lines.length) {
            return;
        }
        if (this._terminal.buffer.lines.get(absoluteRowIndex).isWrapped) {
            if (rowIndex !== 0) {
                return;
            }
            do {
                rowIndex--;
                absoluteRowIndex--;
            } while (this._terminal.buffer.lines.get(absoluteRowIndex).isWrapped);
        }
        var text = this._terminal.buffer.translateBufferLineToString(absoluteRowIndex, false);
        var currentIndex = absoluteRowIndex + 1;
        while (currentIndex < this._terminal.buffer.lines.length &&
            this._terminal.buffer.lines.get(currentIndex).isWrapped) {
            text += this._terminal.buffer.translateBufferLineToString(currentIndex++, false);
        }
        for (var i = 0; i < this._linkMatchers.length; i++) {
            this._doLinkifyRow(rowIndex, text, this._linkMatchers[i]);
        }
    };
    Linkifier.prototype._doLinkifyRow = function (rowIndex, text, matcher, offset) {
        var _this = this;
        if (offset === void 0) { offset = 0; }
        var match = text.match(matcher.regex);
        if (!match || match.length === 0) {
            return;
        }
        var uri = match[typeof matcher.matchIndex !== 'number' ? 0 : matcher.matchIndex];
        var index = text.indexOf(uri);
        if (matcher.validationCallback) {
            matcher.validationCallback(uri, function (isValid) {
                if (_this._rowsTimeoutId) {
                    return;
                }
                if (isValid) {
                    _this._addLink(offset + index, rowIndex, uri, matcher);
                }
            });
        }
        else {
            this._addLink(offset + index, rowIndex, uri, matcher);
        }
        var remainingStartIndex = index + uri.length;
        var remainingText = text.substr(remainingStartIndex);
        if (remainingText.length > 0) {
            this._doLinkifyRow(rowIndex, remainingText, matcher, offset + remainingStartIndex);
        }
    };
    Linkifier.prototype._addLink = function (x, y, uri, matcher) {
        var _this = this;
        var x1 = x % this._terminal.cols;
        var y1 = y + Math.floor(x / this._terminal.cols);
        var x2 = (x1 + uri.length) % this._terminal.cols;
        var y2 = y1 + Math.floor((x1 + uri.length) / this._terminal.cols);
        if (x2 === 0) {
            x2 = this._terminal.cols;
            y2--;
        }
        this._mouseZoneManager.add(new MouseZoneManager_1.MouseZone(x1 + 1, y1 + 1, x2 + 1, y2 + 1, function (e) {
            if (matcher.handler) {
                return matcher.handler(e, uri);
            }
            window.open(uri, '_blank');
        }, function (e) {
            _this.emit(Types_1.LinkHoverEventTypes.HOVER, _this._createLinkHoverEvent(x1, y1, x2, y2));
            _this._terminal.element.classList.add('xterm-cursor-pointer');
        }, function (e) {
            _this.emit(Types_1.LinkHoverEventTypes.TOOLTIP, _this._createLinkHoverEvent(x1, y1, x2, y2));
            if (matcher.hoverTooltipCallback) {
                matcher.hoverTooltipCallback(e, uri);
            }
        }, function () {
            _this.emit(Types_1.LinkHoverEventTypes.LEAVE, _this._createLinkHoverEvent(x1, y1, x2, y2));
            _this._terminal.element.classList.remove('xterm-cursor-pointer');
            if (matcher.hoverLeaveCallback) {
                matcher.hoverLeaveCallback();
            }
        }, function (e) {
            if (matcher.willLinkActivate) {
                return matcher.willLinkActivate(e, uri);
            }
            return true;
        }));
    };
    Linkifier.prototype._createLinkHoverEvent = function (x1, y1, x2, y2) {
        return { x1: x1, y1: y1, x2: x2, y2: y2, cols: this._terminal.cols };
    };
    Linkifier.TIME_BEFORE_LINKIFY = 200;
    return Linkifier;
}(EventEmitter_1.EventEmitter));
exports.Linkifier = Linkifier;

//# sourceMappingURL=Linkifier.js.map


/***/ }),

/***/ "v43d":
/*!**********************************************!*\
  !*** ./node_modules/ajv/lib/dotjs/_limit.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate__limit(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $isMax = $keyword == 'maximum',
    $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum',
    $schemaExcl = it.schema[$exclusiveKeyword],
    $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data,
    $op = $isMax ? '<' : '>',
    $notOp = $isMax ? '>' : '<',
    $errorKeyword = undefined;
  if ($isDataExcl) {
    var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr),
      $exclusive = 'exclusive' + $lvl,
      $exclType = 'exclType' + $lvl,
      $exclIsNumber = 'exclIsNumber' + $lvl,
      $opExpr = 'op' + $lvl,
      $opStr = '\' + ' + $opExpr + ' + \'';
    out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; ';
    $schemaValueExcl = 'schemaExcl' + $lvl;
    out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { ';
    var $errorKeyword = $exclusiveKeyword;
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = ''; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
      if (it.opts.messages !== false) {
        out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError([' + (__err) + ']); ';
      } else {
        out += ' validate.errors = [' + (__err) + ']; return false; ';
      }
    } else {
      out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    }
    out += ' } else if ( ';
    if ($isData) {
      out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
    }
    out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\';';
  } else {
    var $exclIsNumber = typeof $schemaExcl == 'number',
      $opStr = $op;
    if ($exclIsNumber && $isData) {
      var $opExpr = '\'' + $opStr + '\'';
      out += ' if ( ';
      if ($isData) {
        out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
      }
      out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { ';
    } else {
      if ($exclIsNumber && $schema === undefined) {
        $exclusive = true;
        $errorKeyword = $exclusiveKeyword;
        $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
        $schemaValue = $schemaExcl;
        $notOp += '=';
      } else {
        if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema);
        if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) {
          $exclusive = true;
          $errorKeyword = $exclusiveKeyword;
          $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
          $notOp += '=';
        } else {
          $exclusive = false;
          $opStr += '=';
        }
      }
      var $opExpr = '\'' + $opStr + '\'';
      out += ' if ( ';
      if ($isData) {
        out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
      }
      out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { ';
    }
  }
  $errorKeyword = $errorKeyword || $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should be ' + ($opStr) + ' ';
      if ($isData) {
        out += '\' + ' + ($schemaValue);
      } else {
        out += '' + ($schemaValue) + '\'';
      }
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += ' } ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}


/***/ }),

/***/ "v6Iv":
/*!*****************************************************************************!*\
  !*** ./node_modules/draft-js-import-element/lib/lib/replaceTextWithMeta.js ***!
  \*****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = replaceTextWithMeta;
function replaceTextWithMeta(subject, searchText, replaceText) {
  var text = subject.text,
      characterMeta = subject.characterMeta;

  var searchTextLength = searchText.length;
  var replaceTextLength = replaceText.length;
  var resultTextParts = [];
  // Get empty set of same kind as characterMeta.
  var resultCharMeta = characterMeta.slice(0, 0);
  var lastEndIndex = 0;
  var index = text.indexOf(searchText);
  while (index !== -1) {
    resultTextParts.push(text.slice(lastEndIndex, index) + replaceText);
    resultCharMeta = resultCharMeta.concat(characterMeta.slice(lastEndIndex, index),
    // Use the metadata of the first char we are replacing.
    repeatSeq(characterMeta.slice(index, index + 1), replaceTextLength));
    lastEndIndex = index + searchTextLength;
    index = text.indexOf(searchText, lastEndIndex);
  }
  resultTextParts.push(text.slice(lastEndIndex));
  resultCharMeta = resultCharMeta.concat(characterMeta.slice(lastEndIndex));
  return { text: resultTextParts.join(''), characterMeta: resultCharMeta };
}

function repeatSeq(seq, count) {
  var result = seq.slice(0, 0);
  while (count-- > 0) {
    result = result.concat(seq);
  }
  return result;
}

/***/ }),

/***/ "v7cI":
/*!******************************************************!*\
  !*** ./node_modules/@phosphor/dragdrop/lib/index.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var disposable_1 = __webpack_require__(/*! @phosphor/disposable */ "uNUc");
/**
 * An object which manages a drag-drop operation.
 *
 * A drag object dispatches four different events to drop targets:
 *
 * - `'p-dragenter'` - Dispatched when the mouse enters the target
 *   element. This event must be canceled in order to receive any
 *   of the other events.
 *
 * - `'p-dragover'` - Dispatched when the mouse moves over the drop
 *   target. It must cancel the event and set the `dropAction` to one
 *   of the supported actions in order to receive drop events.
 *
 * - `'p-dragleave'` - Dispatched when the mouse leaves the target
 *   element. This includes moving the mouse into child elements.
 *
 * - `'p-drop'`- Dispatched when the mouse is released over the target
 *   element when the target indicates an appropriate drop action. If
 *   the event is canceled, the indicated drop action is returned to
 *   the initiator through the resolved promise.
 *
 * A drag operation can be terminated at any time by pressing `Escape`
 * or by disposing the drag object.
 *
 * A drag object has the ability to automatically scroll a scrollable
 * element when the mouse is hovered near one of its edges. To enable
 * this, add the `data-p-dragscroll` attribute to any element which
 * the drag object should consider for scrolling.
 *
 * #### Notes
 * This class is designed to be used when dragging and dropping custom
 * data *within* a single application. It is *not* a replacement for
 * the native drag-drop API. Instead, it provides an API which allows
 * drag operations to be initiated programmatically and enables the
 * transfer of arbitrary non-string objects; features which are not
 * possible with the native drag-drop API.
 */
var Drag = (function () {
    /**
     * Construct a new drag object.
     *
     * @param options - The options for initializing the drag.
     */
    function Drag(options) {
        var _this = this;
        /**
         * The scroll loop handler function.
         */
        this._onScrollFrame = function () {
            // Bail early if there is no scroll target.
            if (!_this._scrollTarget) {
                return;
            }
            // Unpack the scroll target.
            var _a = _this._scrollTarget, element = _a.element, edge = _a.edge, distance = _a.distance;
            // Calculate the scroll delta using nonlinear acceleration.
            var d = Private.SCROLL_EDGE_SIZE - distance;
            var f = Math.pow(d / Private.SCROLL_EDGE_SIZE, 2);
            var s = Math.max(1, Math.round(f * Private.SCROLL_EDGE_SIZE));
            // Scroll the element in the specified direction.
            switch (edge) {
                case 'top':
                    element.scrollTop -= s;
                    break;
                case 'left':
                    element.scrollLeft -= s;
                    break;
                case 'right':
                    element.scrollLeft += s;
                    break;
                case 'bottom':
                    element.scrollTop += s;
                    break;
            }
            // Request the next cycle of the scroll loop.
            requestAnimationFrame(_this._onScrollFrame);
        };
        this._disposed = false;
        this._dropAction = 'none';
        this._override = null;
        this._currentTarget = null;
        this._currentElement = null;
        this._promise = null;
        this._scrollTarget = null;
        this._resolve = null;
        this.mimeData = options.mimeData;
        this.dragImage = options.dragImage || null;
        this.proposedAction = options.proposedAction || 'copy';
        this.supportedActions = options.supportedActions || 'all';
        this.source = options.source || null;
    }
    /**
     * Dispose of the resources held by the drag object.
     *
     * #### Notes
     * This will cancel the drag operation if it is active.
     */
    Drag.prototype.dispose = function () {
        // Do nothing if the drag object is already disposed.
        if (this._disposed) {
            return;
        }
        this._disposed = true;
        // If there is a current target, dispatch a drag leave event.
        if (this._currentTarget) {
            var event_1 = Private.createMouseEvent('mouseup', -1, -1);
            Private.dispatchDragLeave(this, this._currentTarget, null, event_1);
        }
        // Finalize the drag object with `'none'`.
        this._finalize('none');
    };
    Object.defineProperty(Drag.prototype, "isDisposed", {
        /**
         * Test whether the drag object is disposed.
         */
        get: function () {
            return this._disposed;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Start the drag operation at the specified client position.
     *
     * @param clientX - The client X position for the drag start.
     *
     * @param clientY - The client Y position for the drag start.
     *
     * @returns A promise which resolves to the result of the drag.
     *
     * #### Notes
     * If the drag has already been started, the promise created by the
     * first call to `start` is returned.
     *
     * If the drag operation has ended, or if the drag object has been
     * disposed, the returned promise will resolve to `'none'`.
     *
     * The drag object will be automatically disposed when drag operation
     * completes. This means `Drag` objects are for single-use only.
     *
     * This method assumes the left mouse button is already held down.
     */
    Drag.prototype.start = function (clientX, clientY) {
        var _this = this;
        // If the drag object is already disposed, resolve to `None`.
        if (this._disposed) {
            return Promise.resolve('none');
        }
        // If the drag has already been started, return the promise.
        if (this._promise) {
            return this._promise;
        }
        // Install the document listeners for the drag object.
        this._addListeners();
        // Attach the drag image at the specified client position.
        this._attachDragImage(clientX, clientY);
        // Create the promise which will be resolved on completion.
        this._promise = new Promise(function (resolve, reject) {
            _this._resolve = resolve;
        });
        // Trigger a fake move event to kick off the drag operation.
        var event = Private.createMouseEvent('mousemove', clientX, clientY);
        document.dispatchEvent(event);
        // Return the pending promise for the drag operation.
        return this._promise;
    };
    /**
     * Handle the DOM events for the drag operation.
     *
     * @param event - The DOM event sent to the drag object.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the document. It should not be
     * called directly by user code.
     */
    Drag.prototype.handleEvent = function (event) {
        switch (event.type) {
            case 'mousemove':
                this._evtMouseMove(event);
                break;
            case 'mouseup':
                this._evtMouseUp(event);
                break;
            case 'keydown':
                this._evtKeyDown(event);
                break;
            default:
                // Stop all other events during drag-drop.
                event.preventDefault();
                event.stopPropagation();
                break;
        }
    };
    /**
     * Handle the `'mousemove'` event for the drag object.
     */
    Drag.prototype._evtMouseMove = function (event) {
        // Stop all input events during drag-drop.
        event.preventDefault();
        event.stopPropagation();
        // Update the current target node and dispatch enter/leave events.
        this._updateCurrentTarget(event);
        // Update the drag scroll element.
        this._updateDragScroll(event);
        // Move the drag image to the specified client position. This is
        // performed *after* dispatching to prevent unnecessary reflows.
        this._moveDragImage(event.clientX, event.clientY);
    };
    /**
     * Handle the `'mouseup'` event for the drag object.
     */
    Drag.prototype._evtMouseUp = function (event) {
        // Stop all input events during drag-drop.
        event.preventDefault();
        event.stopPropagation();
        // Do nothing if the left button is not released.
        if (event.button !== 0) {
            return;
        }
        // Update the current target node and dispatch enter/leave events.
        // This prevents a subtle issue where the DOM mutates under the
        // cursor after the last move event but before the drop event.
        this._updateCurrentTarget(event);
        // If there is no current target, finalize with `'none'`.
        if (!this._currentTarget) {
            this._finalize('none');
            return;
        }
        // If the last drop action was `'none'`, dispatch a leave event
        // to the current target and finalize the drag with `'none'`.
        if (this._dropAction === 'none') {
            Private.dispatchDragLeave(this, this._currentTarget, null, event);
            this._finalize('none');
            return;
        }
        // Dispatch the drop event at the current target and finalize
        // with the resulting drop action.
        var action = Private.dispatchDrop(this, this._currentTarget, event);
        this._finalize(action);
    };
    /**
     * Handle the `'keydown'` event for the drag object.
     */
    Drag.prototype._evtKeyDown = function (event) {
        // Stop all input events during drag-drop.
        event.preventDefault();
        event.stopPropagation();
        // Cancel the drag if `Escape` is pressed.
        if (event.keyCode === 27) {
            this.dispose();
        }
    };
    /**
     * Add the document event listeners for the drag object.
     */
    Drag.prototype._addListeners = function () {
        document.addEventListener('mousedown', this, true);
        document.addEventListener('mousemove', this, true);
        document.addEventListener('mouseup', this, true);
        document.addEventListener('mouseenter', this, true);
        document.addEventListener('mouseleave', this, true);
        document.addEventListener('mouseover', this, true);
        document.addEventListener('mouseout', this, true);
        document.addEventListener('keydown', this, true);
        document.addEventListener('keyup', this, true);
        document.addEventListener('keypress', this, true);
        document.addEventListener('contextmenu', this, true);
    };
    /**
     * Remove the document event listeners for the drag object.
     */
    Drag.prototype._removeListeners = function () {
        document.removeEventListener('mousedown', this, true);
        document.removeEventListener('mousemove', this, true);
        document.removeEventListener('mouseup', this, true);
        document.removeEventListener('mouseenter', this, true);
        document.removeEventListener('mouseleave', this, true);
        document.removeEventListener('mouseover', this, true);
        document.removeEventListener('mouseout', this, true);
        document.removeEventListener('keydown', this, true);
        document.removeEventListener('keyup', this, true);
        document.removeEventListener('keypress', this, true);
        document.removeEventListener('contextmenu', this, true);
    };
    /**
     * Update the drag scroll element under the mouse.
     */
    Drag.prototype._updateDragScroll = function (event) {
        // Find the scroll target under the mouse.
        var target = Private.findScrollTarget(event);
        // Bail if there is nothing to scroll.
        if (!this._scrollTarget && !target) {
            return;
        }
        // Start the scroll loop if needed.
        if (!this._scrollTarget) {
            setTimeout(this._onScrollFrame, 500);
        }
        // Update the scroll target.
        this._scrollTarget = target;
    };
    /**
     * Update the current target node using the given mouse event.
     */
    Drag.prototype._updateCurrentTarget = function (event) {
        // Fetch common local state.
        var prevTarget = this._currentTarget;
        var currTarget = this._currentTarget;
        var prevElem = this._currentElement;
        // Find the current indicated element at the given position.
        var currElem = document.elementFromPoint(event.clientX, event.clientY);
        // Update the current element reference.
        this._currentElement = currElem;
        // If the indicated element changes from the previous iteration,
        // and is different from the current target, dispatch the exit
        // event to the target.
        if (currElem !== prevElem && currElem !== currTarget) {
            Private.dispatchDragExit(this, currTarget, currElem, event);
        }
        // If the indicated element changes from the previous iteration,
        // and is different from the current target, dispatch the enter
        // event and compute the new target element.
        if (currElem !== prevElem && currElem !== currTarget) {
            currTarget = Private.dispatchDragEnter(this, currElem, currTarget, event);
        }
        // If the current target element has changed, update the current
        // target reference and dispatch the leave event to the old target.
        if (currTarget !== prevTarget) {
            this._currentTarget = currTarget;
            Private.dispatchDragLeave(this, prevTarget, currTarget, event);
        }
        // Dispatch the drag over event and update the drop action.
        var action = Private.dispatchDragOver(this, currTarget, event);
        this._setDropAction(action);
    };
    /**
     * Attach the drag image element at the specified location.
     *
     * This is a no-op if there is no drag image element.
     */
    Drag.prototype._attachDragImage = function (clientX, clientY) {
        if (!this.dragImage) {
            return;
        }
        this.dragImage.classList.add('p-mod-drag-image');
        var style = this.dragImage.style;
        style.pointerEvents = 'none';
        style.position = 'fixed';
        style.top = clientY + "px";
        style.left = clientX + "px";
        document.body.appendChild(this.dragImage);
    };
    /**
     * Move the drag image element to the specified location.
     *
     * This is a no-op if there is no drag image element.
     */
    Drag.prototype._moveDragImage = function (clientX, clientY) {
        if (!this.dragImage) {
            return;
        }
        var style = this.dragImage.style;
        style.top = clientY + "px";
        style.left = clientX + "px";
    };
    /**
     * Detach the drag image element from the DOM.
     *
     * This is a no-op if there is no drag image element.
     */
    Drag.prototype._detachDragImage = function () {
        if (!this.dragImage) {
            return;
        }
        var parent = this.dragImage.parentNode;
        if (!parent) {
            return;
        }
        parent.removeChild(this.dragImage);
    };
    /**
     * Set the internal drop action state and update the drag cursor.
     */
    Drag.prototype._setDropAction = function (action) {
        action = Private.validateAction(action, this.supportedActions);
        if (this._override && this._dropAction === action) {
            return;
        }
        switch (action) {
            case 'none':
                this._dropAction = action;
                this._override = Drag.overrideCursor('no-drop');
                break;
            case 'copy':
                this._dropAction = action;
                this._override = Drag.overrideCursor('copy');
                break;
            case 'link':
                this._dropAction = action;
                this._override = Drag.overrideCursor('alias');
                break;
            case 'move':
                this._dropAction = action;
                this._override = Drag.overrideCursor('move');
                break;
        }
    };
    /**
     * Finalize the drag operation and resolve the drag promise.
     */
    Drag.prototype._finalize = function (action) {
        // Store the resolve function as a temp variable.
        var resolve = this._resolve;
        // Remove the document event listeners.
        this._removeListeners();
        // Detach the drag image.
        this._detachDragImage();
        // Dispose of the cursor override.
        if (this._override) {
            this._override.dispose();
            this._override = null;
        }
        // Clear the mime data.
        this.mimeData.clear();
        // Clear the rest of the internal drag state.
        this._disposed = true;
        this._dropAction = 'none';
        this._currentTarget = null;
        this._currentElement = null;
        this._scrollTarget = null;
        this._promise = null;
        this._resolve = null;
        // Finally, resolve the promise to the given drop action.
        if (resolve) {
            resolve(action);
        }
    };
    return Drag;
}());
exports.Drag = Drag;
/**
 * The namespace for the `Drag` class statics.
 */
(function (Drag) {
    /**
     * Override the cursor icon for the entire document.
     *
     * @param cursor - The string representing the cursor style.
     *
     * @returns A disposable which will clear the override when disposed.
     *
     * #### Notes
     * The most recent call to `overrideCursor` takes precedence.
     * Disposing an old override has no effect on the current override.
     *
     * This utility function is used by the `Drag` class to override the
     * mouse cursor during a drag-drop operation, but it can also be used
     * by other classes to fix the cursor icon during normal mouse drags.
     *
     * #### Example
     * ```typescript
     * import { Drag } from '@phosphor/dragdrop';
     *
     * // Force the cursor to be 'wait' for the entire document.
     * let override = Drag.overrideCursor('wait');
     *
     * // Clear the override by disposing the return value.
     * override.dispose();
     * ```
     */
    function overrideCursor(cursor) {
        var id = ++overrideCursorID;
        document.body.style.cursor = cursor;
        document.body.classList.add('p-mod-override-cursor');
        return new disposable_1.DisposableDelegate(function () {
            if (id === overrideCursorID) {
                document.body.style.cursor = '';
                document.body.classList.remove('p-mod-override-cursor');
            }
        });
    }
    Drag.overrideCursor = overrideCursor;
    /**
     * The internal id for the active cursor override.
     */
    var overrideCursorID = 0;
})(Drag = exports.Drag || (exports.Drag = {}));
exports.Drag = Drag;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * The size of a drag scroll edge, in pixels.
     */
    Private.SCROLL_EDGE_SIZE = 20;
    /**
     * Validate the given action is one of the supported actions.
     *
     * Returns the given action or `'none'` if the action is unsupported.
     */
    function validateAction(action, supported) {
        return (actionTable[action] & supportedTable[supported]) ? action : 'none';
    }
    Private.validateAction = validateAction;
    /**
     * Create a left mouse event at the given position.
     *
     * @param type - The event type for the mouse event.
     *
     * @param clientX - The client X position.
     *
     * @param clientY - The client Y position.
     *
     * @returns A newly created and initialized mouse event.
     */
    function createMouseEvent(type, clientX, clientY) {
        var event = document.createEvent('MouseEvent');
        event.initMouseEvent(type, true, true, window, 0, 0, 0, clientX, clientY, false, false, false, false, 0, null);
        return event;
    }
    Private.createMouseEvent = createMouseEvent;
    /**
     * Find the drag scroll target under the mouse, if any.
     */
    function findScrollTarget(event) {
        // Look up the client mouse position.
        var x = event.clientX;
        var y = event.clientY;
        // Get the element under the mouse.
        var element = document.elementFromPoint(x, y);
        // Search for a scrollable target based on the mouse position.
        // The null assert in third clause of for-loop is required due to:
        // https://github.com/Microsoft/TypeScript/issues/14143
        for (; element; element = element.parentElement) {
            // Ignore elements which are not marked as scrollable.
            if (!element.hasAttribute('data-p-dragscroll')) {
                continue;
            }
            // Set up the coordinate offsets for the element.
            var offsetX = 0;
            var offsetY = 0;
            if (element === document.body) {
                offsetX = window.pageXOffset;
                offsetY = window.pageYOffset;
            }
            // Get the element bounds in viewport coordinates.
            var r = element.getBoundingClientRect();
            var top_1 = r.top + offsetY;
            var left = r.left + offsetX;
            var right = left + r.width;
            var bottom = top_1 + r.height;
            // Skip the element if it's not under the mouse.
            if (x < left || x >= right || y < top_1 || y >= bottom) {
                continue;
            }
            // Compute the distance to each edge.
            var dl = x - left + 1;
            var dt = y - top_1 + 1;
            var dr = right - x;
            var db = bottom - y;
            // Find the smallest of the edge distances.
            var distance = Math.min(dl, dt, dr, db);
            // Skip the element if the mouse is not within a scroll edge.
            if (distance > Private.SCROLL_EDGE_SIZE) {
                continue;
            }
            // Set up the edge result variable.
            var edge = void 0;
            // Find the edge for the computed distance.
            switch (distance) {
                case db:
                    edge = 'bottom';
                    break;
                case dt:
                    edge = 'top';
                    break;
                case dr:
                    edge = 'right';
                    break;
                case dl:
                    edge = 'left';
                    break;
                default:
                    throw 'unreachable';
            }
            // Compute how much the element can scroll in width and height.
            var dsw = element.scrollWidth - element.clientWidth;
            var dsh = element.scrollHeight - element.clientHeight;
            // Determine if the element should be scrolled for the edge.
            var shouldScroll = void 0;
            switch (edge) {
                case 'top':
                    shouldScroll = dsh > 0 && element.scrollTop > 0;
                    break;
                case 'left':
                    shouldScroll = dsw > 0 && element.scrollLeft > 0;
                    break;
                case 'right':
                    shouldScroll = dsw > 0 && element.scrollLeft < dsw;
                    break;
                case 'bottom':
                    shouldScroll = dsh > 0 && element.scrollTop < dsh;
                    break;
                default:
                    throw 'unreachable';
            }
            // Skip the element if it should not be scrolled.
            if (!shouldScroll) {
                continue;
            }
            // Return the drag scroll target.
            return { element: element, edge: edge, distance: distance };
        }
        // No drag scroll target was found.
        return null;
    }
    Private.findScrollTarget = findScrollTarget;
    /**
     * Dispatch a drag enter event to the indicated element.
     *
     * @param drag - The drag object associated with the action.
     *
     * @param currElem - The currently indicated element, or `null`. This
     *   is the "immediate user selection" from the whatwg spec.
     *
     * @param currTarget - The current drag target element, or `null`. This
     *   is the "current target element" from the whatwg spec.
     *
     * @param event - The mouse event related to the action.
     *
     * @returns The element to use as the current drag target. This is the
     *   "current target element" from the whatwg spec, and may be `null`.
     *
     * #### Notes
     * This largely implements the drag enter portion of the whatwg spec:
     * https://html.spec.whatwg.org/multipage/interaction.html#drag-and-drop-processing-model
     */
    function dispatchDragEnter(drag, currElem, currTarget, event) {
        // If the current element is null, return null as the new target.
        if (!currElem) {
            return null;
        }
        // Dispatch a drag enter event to the current element.
        var dragEvent = createDragEvent('p-dragenter', drag, event, currTarget);
        var canceled = !currElem.dispatchEvent(dragEvent);
        // If the event was canceled, use the current element as the new target.
        if (canceled) {
            return currElem;
        }
        // If the current element is the document body, keep the original target.
        if (currElem === document.body) {
            return currTarget;
        }
        // Dispatch a drag enter event on the document body.
        dragEvent = createDragEvent('p-dragenter', drag, event, currTarget);
        document.body.dispatchEvent(dragEvent);
        // Ignore the event cancellation, and use the body as the new target.
        return document.body;
    }
    Private.dispatchDragEnter = dispatchDragEnter;
    /**
     * Dispatch a drag exit event to the indicated element.
     *
     * @param drag - The drag object associated with the action.
     *
     * @param prevTarget - The previous target element, or `null`. This
     *   is the previous "current target element" from the whatwg spec.
     *
     * @param currTarget - The current drag target element, or `null`. This
     *   is the "current target element" from the whatwg spec.
     *
     * @param event - The mouse event related to the action.
     *
     * #### Notes
     * This largely implements the drag exit portion of the whatwg spec:
     * https://html.spec.whatwg.org/multipage/interaction.html#drag-and-drop-processing-model
     */
    function dispatchDragExit(drag, prevTarget, currTarget, event) {
        // If the previous target is null, do nothing.
        if (!prevTarget) {
            return;
        }
        // Dispatch the drag exit event to the previous target.
        var dragEvent = createDragEvent('p-dragexit', drag, event, currTarget);
        prevTarget.dispatchEvent(dragEvent);
    }
    Private.dispatchDragExit = dispatchDragExit;
    /**
     * Dispatch a drag leave event to the indicated element.
     *
     * @param drag - The drag object associated with the action.
     *
     * @param prevTarget - The previous target element, or `null`. This
     *   is the previous "current target element" from the whatwg spec.
     *
     * @param currTarget - The current drag target element, or `null`. This
     *   is the "current target element" from the whatwg spec.
     *
     * @param event - The mouse event related to the action.
     *
     * #### Notes
     * This largely implements the drag leave portion of the whatwg spec:
     * https://html.spec.whatwg.org/multipage/interaction.html#drag-and-drop-processing-model
     */
    function dispatchDragLeave(drag, prevTarget, currTarget, event) {
        // If the previous target is null, do nothing.
        if (!prevTarget) {
            return;
        }
        // Dispatch the drag leave event to the previous target.
        var dragEvent = createDragEvent('p-dragleave', drag, event, currTarget);
        prevTarget.dispatchEvent(dragEvent);
    }
    Private.dispatchDragLeave = dispatchDragLeave;
    /**
     * Dispatch a drag over event to the indicated element.
     *
     * @param drag - The drag object associated with the action.
     *
     * @param currTarget - The current drag target element, or `null`. This
     *   is the "current target element" from the whatwg spec.
     *
     * @param event - The mouse event related to the action.
     *
     * @returns The `DropAction` result of the drag over event.
     *
     * #### Notes
     * This largely implements the drag over portion of the whatwg spec:
     * https://html.spec.whatwg.org/multipage/interaction.html#drag-and-drop-processing-model
     */
    function dispatchDragOver(drag, currTarget, event) {
        // If there is no current target, the drop action is none.
        if (!currTarget) {
            return 'none';
        }
        // Dispatch the drag over event to the current target.
        var dragEvent = createDragEvent('p-dragover', drag, event, null);
        var canceled = !currTarget.dispatchEvent(dragEvent);
        // If the event was canceled, return the drop action result.
        if (canceled) {
            return dragEvent.dropAction;
        }
        // Otherwise, the effective drop action is none.
        return 'none';
    }
    Private.dispatchDragOver = dispatchDragOver;
    /**
     * Dispatch a drop event to the indicated element.
     *
     * @param drag - The drag object associated with the action.
     *
     * @param currTarget - The current drag target element, or `null`. This
     *   is the "current target element" from the whatwg spec.
     *
     * @param event - The mouse event related to the action.
     *
     * @returns The `DropAction` result of the drop event.
     *
     * #### Notes
     * This largely implements the drag over portion of the whatwg spec:
     * https://html.spec.whatwg.org/multipage/interaction.html#drag-and-drop-processing-model
     */
    function dispatchDrop(drag, currTarget, event) {
        // If there is no current target, the drop action is none.
        if (!currTarget) {
            return 'none';
        }
        // Dispatch the drop event to the current target.
        var dragEvent = createDragEvent('p-drop', drag, event, null);
        var canceled = !currTarget.dispatchEvent(dragEvent);
        // If the event was canceled, return the drop action result.
        if (canceled) {
            return dragEvent.dropAction;
        }
        // Otherwise, the effective drop action is none.
        return 'none';
    }
    Private.dispatchDrop = dispatchDrop;
    /**
     * A lookup table from drop action to bit value.
     */
    var actionTable = {
        'none': 0x0,
        'copy': 0x1,
        'link': 0x2,
        'move': 0x4
    };
    /**
     * A lookup table from supported action to drop action bit mask.
     */
    var supportedTable = {
        'none': actionTable['none'],
        'copy': actionTable['copy'],
        'link': actionTable['link'],
        'move': actionTable['move'],
        'copy-link': actionTable['copy'] | actionTable['link'],
        'copy-move': actionTable['copy'] | actionTable['move'],
        'link-move': actionTable['link'] | actionTable['move'],
        'all': actionTable['copy'] | actionTable['link'] | actionTable['move']
    };
    /**
     * Create a new initialized `IDragEvent` from the given data.
     *
     * @param type - The event type for the drag event.
     *
     * @param drag - The drag object to use for seeding the drag data.
     *
     * @param event - The mouse event to use for seeding the mouse data.
     *
     * @param related - The related target for the event, or `null`.
     *
     * @returns A new object which implements `IDragEvent`.
     */
    function createDragEvent(type, drag, event, related) {
        // Create a new mouse event to use as the drag event. Currently,
        // JS engines do now allow user-defined Event subclasses.
        var dragEvent = document.createEvent('MouseEvent');
        // Initialize the mouse event data.
        dragEvent.initMouseEvent(type, true, true, window, 0, event.screenX, event.screenY, event.clientX, event.clientY, event.ctrlKey, event.altKey, event.shiftKey, event.metaKey, event.button, related);
        // Forcefully add the custom drag event properties.
        dragEvent.dropAction = 'none';
        dragEvent.mimeData = drag.mimeData;
        dragEvent.proposedAction = drag.proposedAction;
        dragEvent.supportedActions = drag.supportedActions;
        dragEvent.source = drag.source;
        // Return the fully initialized drag event.
        return dragEvent;
    }
})(Private || (Private = {}));


/***/ }),

/***/ "v83y":
/*!********************************************!*\
  !*** ./node_modules/draft-js/lib/Draft.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule Draft
 * @format
 * 
 */



var AtomicBlockUtils = __webpack_require__(/*! ./AtomicBlockUtils */ "fyRy");
var BlockMapBuilder = __webpack_require__(/*! ./BlockMapBuilder */ "YeVe");
var CharacterMetadata = __webpack_require__(/*! ./CharacterMetadata */ "lFJn");
var CompositeDraftDecorator = __webpack_require__(/*! ./CompositeDraftDecorator */ "84lc");
var ContentBlock = __webpack_require__(/*! ./ContentBlock */ "8uQm");
var ContentState = __webpack_require__(/*! ./ContentState */ "LpQA");
var DefaultDraftBlockRenderMap = __webpack_require__(/*! ./DefaultDraftBlockRenderMap */ "rAV9");
var DefaultDraftInlineStyle = __webpack_require__(/*! ./DefaultDraftInlineStyle */ "0TRD");
var DraftEditor = __webpack_require__(/*! ./DraftEditor.react */ "6tyx");
var DraftEditorBlock = __webpack_require__(/*! ./DraftEditorBlock.react */ "DthY");
var DraftEntity = __webpack_require__(/*! ./DraftEntity */ "TzU/");
var DraftModifier = __webpack_require__(/*! ./DraftModifier */ "fyOY");
var DraftEntityInstance = __webpack_require__(/*! ./DraftEntityInstance */ "qnky");
var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");
var KeyBindingUtil = __webpack_require__(/*! ./KeyBindingUtil */ "s8ra");
var RichTextEditorUtil = __webpack_require__(/*! ./RichTextEditorUtil */ "Nx4+");
var SelectionState = __webpack_require__(/*! ./SelectionState */ "hMpd");

var convertFromDraftStateToRaw = __webpack_require__(/*! ./convertFromDraftStateToRaw */ "/y+l");
var convertFromHTMLToContentBlocks = __webpack_require__(/*! ./convertFromHTMLToContentBlocks */ "1qq2");
var convertFromRawToDraftState = __webpack_require__(/*! ./convertFromRawToDraftState */ "ueFs");
var generateRandomKey = __webpack_require__(/*! ./generateRandomKey */ "rJY1");
var getDefaultKeyBinding = __webpack_require__(/*! ./getDefaultKeyBinding */ "AyB5");
var getVisibleSelectionRect = __webpack_require__(/*! ./getVisibleSelectionRect */ "zxN+");

var DraftPublic = {
  Editor: DraftEditor,
  EditorBlock: DraftEditorBlock,
  EditorState: EditorState,

  CompositeDecorator: CompositeDraftDecorator,
  Entity: DraftEntity,
  EntityInstance: DraftEntityInstance,

  BlockMapBuilder: BlockMapBuilder,
  CharacterMetadata: CharacterMetadata,
  ContentBlock: ContentBlock,
  ContentState: ContentState,
  SelectionState: SelectionState,

  AtomicBlockUtils: AtomicBlockUtils,
  KeyBindingUtil: KeyBindingUtil,
  Modifier: DraftModifier,
  RichUtils: RichTextEditorUtil,

  DefaultDraftBlockRenderMap: DefaultDraftBlockRenderMap,
  DefaultDraftInlineStyle: DefaultDraftInlineStyle,

  convertFromHTML: convertFromHTMLToContentBlocks,
  convertFromRaw: convertFromRawToDraftState,
  convertToRaw: convertFromDraftStateToRaw,
  genKey: generateRandomKey,
  getDefaultKeyBinding: getDefaultKeyBinding,
  getVisibleSelectionRect: getVisibleSelectionRect
};

module.exports = DraftPublic;

/***/ }),

/***/ "v8QY":
/*!**********************************************!*\
  !*** ./node_modules/mdi-react/PencilIcon.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var PencilIcon = function PencilIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M20.71,7.04C21.1,6.65 21.1,6 20.71,5.63L18.37,3.29C18,2.9 17.35,2.9 16.96,3.29L15.12,5.12L18.87,8.87M3,17.25V21H6.75L17.81,9.93L14.06,6.18L3,17.25Z' })
  );
};

module.exports = PencilIcon;


/***/ }),

/***/ "vGKN":
/*!********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotCone3dIcon.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotCone3dIcon = function PlotCone3dIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M16 3.875c-5.813 0-11.75 1.688-11.75 4.813 0 .75.313 1.438.875 1.938l8.188 15.813c.5 1 1.563 1.625 2.688 1.625s2.188-.625 2.688-1.625l8.188-15.813c.563-.5.875-1.188.875-1.938 0-3.125-5.938-4.813-11.75-4.813zm0 2.25c5.813 0 9 1.563 9.438 2.438L25 9.376c-1.063.813-4.125 1.938-9 1.938s-7.938-1.125-9-1.938l-.438-.813C7 7.688 10.187 6.125 16 6.125zm.688 19.313c-.125.25-.375.438-.688.438s-.563-.188-.688-.438L8.624 12.5c2.375.688 4.875 1.063 7.375 1.063s5-.375 7.375-1.063z' })
    );
};

exports.default = PlotCone3dIcon;

/***/ }),

/***/ "vIqA":
/*!******************************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/map-generator.js ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {

exports.__esModule = true;

var _sourceMap = __webpack_require__(/*! source-map */ "3HS5");

var _sourceMap2 = _interopRequireDefault(_sourceMap);

var _path = __webpack_require__(/*! path */ "33yf");

var _path2 = _interopRequireDefault(_path);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var MapGenerator = function () {
    function MapGenerator(stringify, root, opts) {
        _classCallCheck(this, MapGenerator);

        this.stringify = stringify;
        this.mapOpts = opts.map || {};
        this.root = root;
        this.opts = opts;
    }

    MapGenerator.prototype.isMap = function isMap() {
        if (typeof this.opts.map !== 'undefined') {
            return !!this.opts.map;
        } else {
            return this.previous().length > 0;
        }
    };

    MapGenerator.prototype.previous = function previous() {
        var _this = this;

        if (!this.previousMaps) {
            this.previousMaps = [];
            this.root.walk(function (node) {
                if (node.source && node.source.input.map) {
                    var map = node.source.input.map;
                    if (_this.previousMaps.indexOf(map) === -1) {
                        _this.previousMaps.push(map);
                    }
                }
            });
        }

        return this.previousMaps;
    };

    MapGenerator.prototype.isInline = function isInline() {
        if (typeof this.mapOpts.inline !== 'undefined') {
            return this.mapOpts.inline;
        }

        var annotation = this.mapOpts.annotation;
        if (typeof annotation !== 'undefined' && annotation !== true) {
            return false;
        }

        if (this.previous().length) {
            return this.previous().some(function (i) {
                return i.inline;
            });
        } else {
            return true;
        }
    };

    MapGenerator.prototype.isSourcesContent = function isSourcesContent() {
        if (typeof this.mapOpts.sourcesContent !== 'undefined') {
            return this.mapOpts.sourcesContent;
        }
        if (this.previous().length) {
            return this.previous().some(function (i) {
                return i.withContent();
            });
        } else {
            return true;
        }
    };

    MapGenerator.prototype.clearAnnotation = function clearAnnotation() {
        if (this.mapOpts.annotation === false) return;

        var node = void 0;
        for (var i = this.root.nodes.length - 1; i >= 0; i--) {
            node = this.root.nodes[i];
            if (node.type !== 'comment') continue;
            if (node.text.indexOf('# sourceMappingURL=') === 0) {
                this.root.removeChild(i);
            }
        }
    };

    MapGenerator.prototype.setSourcesContent = function setSourcesContent() {
        var _this2 = this;

        var already = {};
        this.root.walk(function (node) {
            if (node.source) {
                var from = node.source.input.from;
                if (from && !already[from]) {
                    already[from] = true;
                    var relative = _this2.relative(from);
                    _this2.map.setSourceContent(relative, node.source.input.css);
                }
            }
        });
    };

    MapGenerator.prototype.applyPrevMaps = function applyPrevMaps() {
        for (var _iterator = this.previous(), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
            var _ref;

            if (_isArray) {
                if (_i >= _iterator.length) break;
                _ref = _iterator[_i++];
            } else {
                _i = _iterator.next();
                if (_i.done) break;
                _ref = _i.value;
            }

            var prev = _ref;

            var from = this.relative(prev.file);
            var root = prev.root || _path2.default.dirname(prev.file);
            var map = void 0;

            if (this.mapOpts.sourcesContent === false) {
                map = new _sourceMap2.default.SourceMapConsumer(prev.text);
                if (map.sourcesContent) {
                    map.sourcesContent = map.sourcesContent.map(function () {
                        return null;
                    });
                }
            } else {
                map = prev.consumer();
            }

            this.map.applySourceMap(map, from, this.relative(root));
        }
    };

    MapGenerator.prototype.isAnnotation = function isAnnotation() {
        if (this.isInline()) {
            return true;
        } else if (typeof this.mapOpts.annotation !== 'undefined') {
            return this.mapOpts.annotation;
        } else if (this.previous().length) {
            return this.previous().some(function (i) {
                return i.annotation;
            });
        } else {
            return true;
        }
    };

    MapGenerator.prototype.toBase64 = function toBase64(str) {
        if (Buffer) {
            if (Buffer.from && Buffer.from !== Uint8Array.from) {
                return Buffer.from(str).toString('base64');
            } else {
                return new Buffer(str).toString('base64');
            }
        } else {
            return window.btoa(unescape(encodeURIComponent(str)));
        }
    };

    MapGenerator.prototype.addAnnotation = function addAnnotation() {
        var content = void 0;

        if (this.isInline()) {

            content = 'data:application/json;base64,' + this.toBase64(this.map.toString());
        } else if (typeof this.mapOpts.annotation === 'string') {
            content = this.mapOpts.annotation;
        } else {
            content = this.outputFile() + '.map';
        }

        var eol = '\n';
        if (this.css.indexOf('\r\n') !== -1) eol = '\r\n';

        this.css += eol + '/*# sourceMappingURL=' + content + ' */';
    };

    MapGenerator.prototype.outputFile = function outputFile() {
        if (this.opts.to) {
            return this.relative(this.opts.to);
        } else if (this.opts.from) {
            return this.relative(this.opts.from);
        } else {
            return 'to.css';
        }
    };

    MapGenerator.prototype.generateMap = function generateMap() {
        this.generateString();
        if (this.isSourcesContent()) this.setSourcesContent();
        if (this.previous().length > 0) this.applyPrevMaps();
        if (this.isAnnotation()) this.addAnnotation();

        if (this.isInline()) {
            return [this.css];
        } else {
            return [this.css, this.map];
        }
    };

    MapGenerator.prototype.relative = function relative(file) {
        if (file.indexOf('<') === 0) return file;
        if (/^\w+:\/\//.test(file)) return file;

        var from = this.opts.to ? _path2.default.dirname(this.opts.to) : '.';

        if (typeof this.mapOpts.annotation === 'string') {
            from = _path2.default.dirname(_path2.default.resolve(from, this.mapOpts.annotation));
        }

        file = _path2.default.relative(from, file);
        if (_path2.default.sep === '\\') {
            return file.replace(/\\/g, '/');
        } else {
            return file;
        }
    };

    MapGenerator.prototype.sourcePath = function sourcePath(node) {
        if (this.mapOpts.from) {
            return this.mapOpts.from;
        } else {
            return this.relative(node.source.input.from);
        }
    };

    MapGenerator.prototype.generateString = function generateString() {
        var _this3 = this;

        this.css = '';
        this.map = new _sourceMap2.default.SourceMapGenerator({ file: this.outputFile() });

        var line = 1;
        var column = 1;

        var lines = void 0,
            last = void 0;
        this.stringify(this.root, function (str, node, type) {
            _this3.css += str;

            if (node && type !== 'end') {
                if (node.source && node.source.start) {
                    _this3.map.addMapping({
                        source: _this3.sourcePath(node),
                        generated: { line: line, column: column - 1 },
                        original: {
                            line: node.source.start.line,
                            column: node.source.start.column - 1
                        }
                    });
                } else {
                    _this3.map.addMapping({
                        source: '<no source>',
                        original: { line: 1, column: 0 },
                        generated: { line: line, column: column - 1 }
                    });
                }
            }

            lines = str.match(/\n/g);
            if (lines) {
                line += lines.length;
                last = str.lastIndexOf('\n');
                column = str.length - last;
            } else {
                column += str.length;
            }

            if (node && type !== 'start') {
                if (node.source && node.source.end) {
                    _this3.map.addMapping({
                        source: _this3.sourcePath(node),
                        generated: { line: line, column: column - 1 },
                        original: {
                            line: node.source.end.line,
                            column: node.source.end.column
                        }
                    });
                } else {
                    _this3.map.addMapping({
                        source: '<no source>',
                        original: { line: 1, column: 0 },
                        generated: { line: line, column: column - 1 }
                    });
                }
            }
        });
    };

    MapGenerator.prototype.generate = function generate() {
        this.clearAnnotation();

        if (this.isMap()) {
            return this.generateMap();
        } else {
            var result = '';
            this.stringify(this.root, function (i) {
                result += i;
            });
            return [result];
        }
    };

    return MapGenerator;
}();

exports.default = MapGenerator;
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64, 

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../buffer/index.js */ "tjlA").Buffer))

/***/ }),

/***/ "vMpC":
/*!*********************************************!*\
  !*** ./node_modules/mdi-react/ShareIcon.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var ShareIcon = function ShareIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M21,11L14,4V8C7,9 4,14 3,19C5.5,15.5 9,13.9 14,13.9V18L21,11Z' })
  );
};

module.exports = ShareIcon;


/***/ }),

/***/ "vMpn":
/*!************************************************************!*\
  !*** ./node_modules/@jupyterlab/docmanager/lib/manager.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const coreutils_2 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const docregistry_1 = __webpack_require__(/*! @jupyterlab/docregistry */ "jTF0");
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const coreutils_3 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const properties_1 = __webpack_require__(/*! @phosphor/properties */ "3kwb");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const savehandler_1 = __webpack_require__(/*! ./savehandler */ "5dP4");
const widgetmanager_1 = __webpack_require__(/*! ./widgetmanager */ "q/j9");
/* tslint:disable */
/**
 * The document registry token.
 */
exports.IDocumentManager = new coreutils_3.Token('@jupyterlab/docmanager:IDocumentManager');
/**
 * The document manager.
 *
 * #### Notes
 * The document manager is used to register model and widget creators,
 * and the file browser uses the document manager to create widgets. The
 * document manager maintains a context for each path and model type that is
 * open, and a list of widgets for each context. The document manager is in
 * control of the proper closing and disposal of the widgets and contexts.
 */
class DocumentManager {
    /**
     * Construct a new document manager.
     */
    constructor(options) {
        this._activateRequested = new signaling_1.Signal(this);
        this._contexts = [];
        this._isDisposed = false;
        this._autosave = true;
        this.registry = options.registry;
        this.services = options.manager;
        this._opener = options.opener;
        this._when = options.when || options.manager.ready;
        let widgetManager = new widgetmanager_1.DocumentWidgetManager({ registry: this.registry });
        widgetManager.activateRequested.connect(this._onActivateRequested, this);
        this._widgetManager = widgetManager;
        this._setBusy = options.setBusy;
    }
    /**
     * A signal emitted when one of the documents is activated.
     */
    get activateRequested() {
        return this._activateRequested;
    }
    /**
     * Whether to autosave documents.
     */
    get autosave() {
        return this._autosave;
    }
    set autosave(value) {
        this._autosave = value;
        // For each existing context, start/stop the autosave handler as needed.
        this._contexts.forEach(context => {
            const handler = Private.saveHandlerProperty.get(context);
            if (value === true && !handler.isActive) {
                handler.start();
            }
            else if (value === false && handler.isActive) {
                handler.stop();
            }
        });
    }
    /**
     * Get whether the document manager has been disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources held by the document manager.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        // Clear any listeners for our signals.
        signaling_1.Signal.clearData(this);
        // Close all the widgets for our contexts and dispose the widget manager.
        this._contexts.forEach(context => {
            this._widgetManager.closeWidgets(context);
        });
        this._widgetManager.dispose();
        // Clear the context list.
        this._contexts.length = 0;
    }
    /**
     * Clone a widget.
     *
     * @param widget - The source widget.
     *
     * @returns A new widget or `undefined`.
     *
     * #### Notes
     *  Uses the same widget factory and context as the source, or returns
     *  `undefined` if the source widget is not managed by this manager.
     */
    cloneWidget(widget) {
        return this._widgetManager.cloneWidget(widget);
    }
    /**
     * Close all of the open documents.
     *
     * @returns A promise resolving when the widgets are closed.
     */
    closeAll() {
        return Promise.all(this._contexts.map(context => this._widgetManager.closeWidgets(context))).then(() => undefined);
    }
    /**
     * Close the widgets associated with a given path.
     *
     * @param path - The target path.
     *
     * @returns A promise resolving when the widgets are closed.
     */
    closeFile(path) {
        const close = this._contextsForPath(path).map(c => this._widgetManager.closeWidgets(c));
        return Promise.all(close).then(x => undefined);
    }
    /**
     * Get the document context for a widget.
     *
     * @param widget - The widget of interest.
     *
     * @returns The context associated with the widget, or `undefined` if no such
     * context exists.
     */
    contextForWidget(widget) {
        return this._widgetManager.contextForWidget(widget);
    }
    /**
     * Copy a file.
     *
     * @param fromFile - The full path of the original file.
     *
     * @param toDir - The full path to the target directory.
     *
     * @returns A promise which resolves to the contents of the file.
     */
    copy(fromFile, toDir) {
        return this.services.contents.copy(fromFile, toDir);
    }
    /**
     * Create a new file and return the widget used to view it.
     *
     * @param path - The file path to create.
     *
     * @param widgetName - The name of the widget factory to use. 'default' will use the default widget.
     *
     * @param kernel - An optional kernel name/id to override the default.
     *
     * @returns The created widget, or `undefined`.
     *
     * #### Notes
     * This function will return `undefined` if a valid widget factory
     * cannot be found.
     */
    createNew(path, widgetName = 'default', kernel) {
        return this._createOrOpenDocument('create', path, widgetName, kernel);
    }
    /**
     * Delete a file.
     *
     * @param path - The full path to the file to be deleted.
     *
     * @returns A promise which resolves when the file is deleted.
     *
     * #### Notes
     * If there is a running session associated with the file and no other
     * sessions are using the kernel, the session will be shut down.
     */
    deleteFile(path) {
        return this.services.sessions
            .stopIfNeeded(path)
            .then(() => {
            return this.services.contents.delete(path);
        })
            .then(() => {
            this._contextsForPath(path).forEach(context => this._widgetManager.deleteWidgets(context));
            return Promise.resolve(void 0);
        });
    }
    /**
     * See if a widget already exists for the given path and widget name.
     *
     * @param path - The file path to use.
     *
     * @param widgetName - The name of the widget factory to use. 'default' will use the default widget.
     *
     * @returns The found widget, or `undefined`.
     *
     * #### Notes
     * This can be used to find an existing widget instead of opening
     * a new widget.
     */
    findWidget(path, widgetName = 'default') {
        let newPath = coreutils_1.PathExt.normalize(path);
        if (widgetName === 'default') {
            let factory = this.registry.defaultWidgetFactory(newPath);
            if (!factory) {
                return undefined;
            }
            widgetName = factory.name;
        }
        for (let context of this._contextsForPath(newPath)) {
            let widget = this._widgetManager.findWidget(context, widgetName);
            if (widget) {
                return widget;
            }
        }
        return undefined;
    }
    /**
     * Create a new untitled file.
     *
     * @param options - The file content creation options.
     */
    newUntitled(options) {
        if (options.type === 'file') {
            options.ext = options.ext || '.txt';
        }
        return this.services.contents.newUntitled(options);
    }
    /**
     * Open a file and return the widget used to view it.
     *
     * @param path - The file path to open.
     *
     * @param widgetName - The name of the widget factory to use. 'default' will use the default widget.
     *
     * @param kernel - An optional kernel name/id to override the default.
     *
     * @returns The created widget, or `undefined`.
     *
     * #### Notes
     * This function will return `undefined` if a valid widget factory
     * cannot be found.
     */
    open(path, widgetName = 'default', kernel, options) {
        return this._createOrOpenDocument('open', path, widgetName, kernel, options);
    }
    /**
     * Open a file and return the widget used to view it.
     * Reveals an already existing editor.
     *
     * @param path - The file path to open.
     *
     * @param widgetName - The name of the widget factory to use. 'default' will use the default widget.
     *
     * @param kernel - An optional kernel name/id to override the default.
     *
     * @returns The created widget, or `undefined`.
     *
     * #### Notes
     * This function will return `undefined` if a valid widget factory
     * cannot be found.
     */
    openOrReveal(path, widgetName = 'default', kernel, options) {
        let widget = this.findWidget(path, widgetName);
        if (widget) {
            this._opener.open(widget, options || {});
            return widget;
        }
        return this.open(path, widgetName, kernel, options || {});
    }
    /**
     * Overwrite a file.
     *
     * @param oldPath - The full path to the original file.
     *
     * @param newPath - The full path to the new file.
     *
     * @returns A promise containing the new file contents model.
     */
    overwrite(oldPath, newPath) {
        // Cleanly overwrite the file by moving it, making sure the original does
        // not exist, and then renaming to the new path.
        const tempPath = `${newPath}.${coreutils_2.UUID.uuid4()}`;
        const cb = () => this.rename(tempPath, newPath);
        return this.rename(oldPath, tempPath)
            .then(() => {
            return this.deleteFile(newPath);
        })
            .then(cb, cb);
    }
    /**
     * Rename a file or directory.
     *
     * @param oldPath - The full path to the original file.
     *
     * @param newPath - The full path to the new file.
     *
     * @returns A promise containing the new file contents model.  The promise
     * will reject if the newPath already exists.  Use [[overwrite]] to overwrite
     * a file.
     */
    rename(oldPath, newPath) {
        return this.services.contents.rename(oldPath, newPath);
    }
    /**
     * Find a context for a given path and factory name.
     */
    _findContext(path, factoryName) {
        return algorithm_1.find(this._contexts, context => {
            return context.path === path && context.factoryName === factoryName;
        });
    }
    /**
     * Get the contexts for a given path.
     *
     * #### Notes
     * There may be more than one context for a given path if the path is open
     * with multiple model factories (for example, a notebook can be open with a
     * notebook model factory and a text model factory).
     */
    _contextsForPath(path) {
        return this._contexts.filter(context => context.path === path);
    }
    /**
     * Create a context from a path and a model factory.
     */
    _createContext(path, factory, kernelPreference) {
        // TODO: Make it impossible to open two different contexts for the same
        // path. Or at least prompt the closing of all widgets associated with the
        // old context before opening the new context. This will make things much
        // more consistent for the users, at the cost of some confusion about what
        // models are and why sometimes they cannot open the same file in different
        // widgets that have different models.
        // Allow options to be passed when adding a sibling.
        let adopter = (widget, options) => {
            this._widgetManager.adoptWidget(context, widget);
            this._opener.open(widget, options);
        };
        let modelDBFactory = this.services.contents.getModelDBFactory(path) || undefined;
        let context = new docregistry_1.Context({
            opener: adopter,
            manager: this.services,
            factory,
            path,
            kernelPreference,
            modelDBFactory,
            setBusy: this._setBusy
        });
        let handler = new savehandler_1.SaveHandler({ context });
        Private.saveHandlerProperty.set(context, handler);
        context.ready.then(() => {
            if (this.autosave) {
                handler.start();
            }
        });
        context.disposed.connect(this._onContextDisposed, this);
        this._contexts.push(context);
        return context;
    }
    /**
     * Handle a context disposal.
     */
    _onContextDisposed(context) {
        algorithm_1.ArrayExt.removeFirstOf(this._contexts, context);
    }
    /**
     * Get the widget factory for a given widget name.
     */
    _widgetFactoryFor(path, widgetName) {
        let { registry } = this;
        if (widgetName === 'default') {
            let factory = registry.defaultWidgetFactory(path);
            if (!factory) {
                return undefined;
            }
            widgetName = factory.name;
        }
        return registry.getWidgetFactory(widgetName);
    }
    /**
     * Creates a new document, or loads one from disk, depending on the `which` argument.
     * If `which==='create'`, then it creates a new document. If `which==='open'`,
     * then it loads the document from disk.
     *
     * The two cases differ in how the document context is handled, but the creation
     * of the widget and launching of the kernel are identical.
     */
    _createOrOpenDocument(which, path, widgetName = 'default', kernel, options) {
        let widgetFactory = this._widgetFactoryFor(path, widgetName);
        if (!widgetFactory) {
            return undefined;
        }
        let modelName = widgetFactory.modelName || 'text';
        let factory = this.registry.getModelFactory(modelName);
        if (!factory) {
            return undefined;
        }
        // Handle the kernel pereference.
        let preference = this.registry.getKernelPreference(path, widgetFactory.name, kernel);
        let context = null;
        let ready = Promise.resolve(undefined);
        // Handle the load-from-disk case
        if (which === 'open') {
            // Use an existing context if available.
            context = this._findContext(path, factory.name) || null;
            if (!context) {
                context = this._createContext(path, factory, preference);
                // Populate the model, either from disk or a
                // model backend.
                ready = this._when.then(() => context.initialize(false));
            }
        }
        else if (which === 'create') {
            context = this._createContext(path, factory, preference);
            // Immediately save the contents to disk.
            ready = this._when.then(() => context.initialize(true));
        }
        let widget = this._widgetManager.createWidget(widgetFactory, context);
        this._opener.open(widget, options || {});
        // If the initial opening of the context fails, dispose of the widget.
        ready.catch(err => {
            widget.close();
        });
        return widget;
    }
    /**
     * Handle an activateRequested signal from the widget manager.
     */
    _onActivateRequested(sender, args) {
        this._activateRequested.emit(args);
    }
}
exports.DocumentManager = DocumentManager;
/**
 * A namespace for private data.
 */
var Private;
(function (Private) {
    /**
     * An attached property for a context save handler.
     */
    Private.saveHandlerProperty = new properties_1.AttachedProperty({
        name: 'saveHandler',
        create: () => undefined
    });
})(Private || (Private = {}));


/***/ }),

/***/ "vOnD":
/*!******************************************************************************!*\
  !*** ./node_modules/styled-components/dist/styled-components.browser.esm.js ***!
  \******************************************************************************/
/*! exports provided: default, css, keyframes, injectGlobal, isStyledComponent, consolidateStreamedStyles, ThemeProvider, withTheme, ServerStyleSheet, StyleSheetManager, __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(process, module) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "css", function() { return css; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "keyframes", function() { return keyframes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "injectGlobal", function() { return injectGlobal; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isStyledComponent", function() { return isStyledComponent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "consolidateStreamedStyles", function() { return consolidateStreamedStyles; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ThemeProvider", function() { return ThemeProvider; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "withTheme", function() { return withTheme; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ServerStyleSheet", function() { return ServerStyleSheet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StyleSheetManager", function() { return StyleSheetManager; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS", function() { return __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS; });
/* harmony import */ var fbjs_lib_hyphenateStyleName__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! fbjs/lib/hyphenateStyleName */ "+8Ar");
/* harmony import */ var fbjs_lib_hyphenateStyleName__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fbjs_lib_hyphenateStyleName__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "q1tI");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var stylis__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! stylis */ "2q7i");
/* harmony import */ var stylis__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(stylis__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var stylis_rule_sheet__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! stylis-rule-sheet */ "TAZq");
/* harmony import */ var stylis_rule_sheet__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(stylis_rule_sheet__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! prop-types */ "17x9");
/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(prop_types__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! hoist-non-react-statics */ "2mql");
/* harmony import */ var hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var react_is__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! react-is */ "TOwV");
/* harmony import */ var react_is__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(react_is__WEBPACK_IMPORTED_MODULE_6__);








var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  return typeof obj;
} : function (obj) {
  return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};

var classCallCheck = function (instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
};

var createClass = function () {
  function defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor) descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }

  return function (Constructor, protoProps, staticProps) {
    if (protoProps) defineProperties(Constructor.prototype, protoProps);
    if (staticProps) defineProperties(Constructor, staticProps);
    return Constructor;
  };
}();

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var inherits = function (subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  }

  subClass.prototype = Object.create(superClass && superClass.prototype, {
    constructor: {
      value: subClass,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
  if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var possibleConstructorReturn = function (self, call) {
  if (!self) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }

  return call && (typeof call === "object" || typeof call === "function") ? call : self;
};

// 
var isPlainObject = (function (x) {
  return (typeof x === 'undefined' ? 'undefined' : _typeof(x)) === 'object' && x.constructor === Object;
});

// 


/**
 * Parse errors.md and turn it into a simple hash of code: message
 */
var ERRORS =  true ? {
  "1": "Cannot create styled-component for component: %s.\n\n",
  "2": "Can't collect styles once you've consumed a `ServerStyleSheet`'s styles! `ServerStyleSheet` is a one off instance for each server-side render cycle.\n\n* Are you trying to reuse it across renders?\n* Are you accidentally calling collectStyles twice?\n\n",
  "3": "Streaming SSR is only supported in a Node.js environment; Please do not try to call this method in the browser.\n\n",
  "4": "The `StyleSheetManager` expects a valid target or sheet prop!\n\n* Does this error occur on the client and is your target falsy?\n* Does this error occur on the server and is the sheet falsy?\n\n",
  "5": "The clone method cannot be used on the client!\n\n* Are you running in a client-like environment on the server?\n* Are you trying to run SSR on the client?\n\n",
  "6": "Trying to insert a new style tag, but the given Node is unmounted!\n\n* Are you using a custom target that isn't mounted?\n* Does your document not have a valid head element?\n* Have you accidentally removed a style tag manually?\n\n",
  "7": "ThemeProvider: Please return an object from your \"theme\" prop function, e.g.\n\n```js\ntheme={() => ({})}\n```\n\n",
  "8": "ThemeProvider: Please make your \"theme\" prop an object.\n\n",
  "9": "Missing document `<head>`\n\n",
  "10": "Cannot find a StyleSheet instance. Usually this happens if there are multiple copies of styled-components loaded at once. Check out this issue for how to troubleshoot and fix the common cases where this situation can happen: https://github.com/styled-components/styled-components/issues/1941#issuecomment-417862021\n\n",
  "11": "A plain React class (%s) has been interpolated into styles, probably as a component selector (https://www.styled-components.com/docs/advanced#referring-to-other-components). Only styled-component classes can be targeted in this fashion."
} : undefined;

/**
 * super basic version of sprintf
 */
function format() {
  for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
    args[_key] = arguments[_key];
  }

  var a = args[0];
  var b = [];
  var c = void 0;

  for (c = 1; c < args.length; c += 1) {
    b.push(args[c]);
  }

  b.forEach(function (d) {
    a = a.replace(/%[a-z]/, d);
  });

  return a;
}

/**
 * Create an error file out of errors.md for development and a simple web link to the full errors
 * in production mode.
 */

var StyledComponentsError = function (_Error) {
  inherits(StyledComponentsError, _Error);

  function StyledComponentsError(code) {
    classCallCheck(this, StyledComponentsError);

    for (var _len2 = arguments.length, interpolations = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
      interpolations[_key2 - 1] = arguments[_key2];
    }

    if (false) { var _this; } else {
      var _this = possibleConstructorReturn(this, _Error.call(this, format.apply(undefined, [ERRORS[code]].concat(interpolations))));
    }
    return possibleConstructorReturn(_this);
  }

  return StyledComponentsError;
}(Error);

// 

var objToCss = function objToCss(obj, prevKey) {
  var css = Object.keys(obj).filter(function (key) {
    var chunk = obj[key];
    return chunk !== undefined && chunk !== null && chunk !== false && chunk !== '';
  }).map(function (key) {
    if (isPlainObject(obj[key])) return objToCss(obj[key], key);
    return fbjs_lib_hyphenateStyleName__WEBPACK_IMPORTED_MODULE_0___default()(key) + ': ' + obj[key] + ';';
  }).join(' ');
  return prevKey ? prevKey + ' {\n  ' + css + '\n}' : css;
};

var flatten = function flatten(chunks, executionContext) {
  return chunks.reduce(function (ruleSet, chunk) {
    /* Remove falsey values */
    if (chunk === undefined || chunk === null || chunk === false || chunk === '') {
      return ruleSet;
    }

    /* Flatten ruleSet */
    if (Array.isArray(chunk)) {
      ruleSet.push.apply(ruleSet, flatten(chunk, executionContext));
      return ruleSet;
    }

    /* Handle other components */
    if (chunk.hasOwnProperty('styledComponentId')) {
      // $FlowFixMe not sure how to make this pass
      ruleSet.push('.' + chunk.styledComponentId);
      return ruleSet;
    }

    /* Either execute or defer the function */
    if (typeof chunk === 'function') {
      if (executionContext) {
        var nextChunk = chunk(executionContext);
        /* Throw if a React Element was given styles */
        if (react__WEBPACK_IMPORTED_MODULE_1___default.a.isValidElement(nextChunk)) {
          var elementName = chunk.displayName || chunk.name;
          throw new StyledComponentsError(11, elementName);
        }
        ruleSet.push.apply(ruleSet, flatten([nextChunk], executionContext));
      } else ruleSet.push(chunk);

      return ruleSet;
    }

    /* Handle objects */
    ruleSet.push(
    // $FlowFixMe have to add %checks somehow to isPlainObject
    isPlainObject(chunk) ? objToCss(chunk) : chunk.toString());

    return ruleSet;
  }, []);
};

// 

var COMMENT_REGEX = /^\s*\/\/.*$/gm;

// NOTE: This stylis instance is only used to split rules from SSR'd style tags
var stylisSplitter = new stylis__WEBPACK_IMPORTED_MODULE_2___default.a({
  global: false,
  cascade: true,
  keyframe: false,
  prefix: false,
  compress: false,
  semicolon: true
});

var stylis = new stylis__WEBPACK_IMPORTED_MODULE_2___default.a({
  global: false,
  cascade: true,
  keyframe: false,
  prefix: true,
  compress: false,
  semicolon: false // NOTE: This means "autocomplete missing semicolons"
});

// Wrap `insertRulePlugin to build a list of rules,
// and then make our own plugin to return the rules. This
// makes it easier to hook into the existing SSR architecture

var parsingRules = [];
// eslint-disable-next-line consistent-return
var returnRulesPlugin = function returnRulesPlugin(context) {
  if (context === -2) {
    var parsedRules = parsingRules;
    parsingRules = [];
    return parsedRules;
  }
};

var parseRulesPlugin = stylis_rule_sheet__WEBPACK_IMPORTED_MODULE_3___default()(function (rule) {
  parsingRules.push(rule);
});

stylis.use([parseRulesPlugin, returnRulesPlugin]);
stylisSplitter.use([parseRulesPlugin, returnRulesPlugin]);

var stringifyRules = function stringifyRules(rules, selector, prefix) {
  var flatCSS = rules.join('').replace(COMMENT_REGEX, ''); // replace JS comments

  var cssStr = selector && prefix ? prefix + ' ' + selector + ' { ' + flatCSS + ' }' : flatCSS;

  return stylis(prefix || !selector ? '' : selector, cssStr);
};

var splitByRules = function splitByRules(css) {
  return stylisSplitter('', css);
};

// 

function isStyledComponent(target) /* : %checks */{
  return (
    // $FlowFixMe TODO: flow for styledComponentId
    typeof target === 'function' && typeof target.styledComponentId === 'string'
  );
}

// 

/* This function is DEPRECATED and will be removed on the next major version release.
 * It was needed to rehydrate all style blocks prepended to chunks before React
 * tries to rehydrate its HTML stream. Since the master StyleSheet will now detect
 * the use of streamed style tags and will perform the rehydration earlier when needed
 * this function will not be needed anymore */
function consolidateStreamedStyles() {
  if (true) {
    // eslint-disable-next-line no-console
    console.warn('styled-components automatically does streaming SSR rehydration now.\n' + 'Calling consolidateStreamedStyles manually is no longer necessary and a noop now.\n' + '- Please remove the consolidateStreamedStyles call from your client.');
  }
}

// 
/* eslint-disable no-bitwise */

/* This is the "capacity" of our alphabet i.e. 2x26 for all letters plus their capitalised
 * counterparts */
var charsLength = 52;

/* start at 75 for 'a' until 'z' (25) and then start at 65 for capitalised letters */
var getAlphabeticChar = function getAlphabeticChar(code) {
  return String.fromCharCode(code + (code > 25 ? 39 : 97));
};

/* input a number, usually a hash and convert it to base-52 */
var generateAlphabeticName = function generateAlphabeticName(code) {
  var name = '';
  var x = void 0;

  /* get a char and divide by alphabet-length */
  for (x = code; x > charsLength; x = Math.floor(x / charsLength)) {
    name = getAlphabeticChar(x % charsLength) + name;
  }

  return getAlphabeticChar(x % charsLength) + name;
};

// 

var interleave = (function (strings, interpolations) {
  var result = [strings[0]];

  for (var i = 0, len = interpolations.length; i < len; i += 1) {
    result.push(interpolations[i], strings[i + 1]);
  }

  return result;
});

// 
var EMPTY_ARRAY = Object.freeze([]);
var EMPTY_OBJECT = Object.freeze({});

// 

var css = (function (styles) {
  for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    interpolations[_key - 1] = arguments[_key];
  }

  if (typeof styles === 'function' || isPlainObject(styles)) {
    // $FlowFixMe
    return flatten(interleave(EMPTY_ARRAY, [styles].concat(interpolations)));
  }

  // $FlowFixMe
  return flatten(interleave(styles, interpolations));
});

// 


var SC_ATTR = typeof process !== 'undefined' && process.env.SC_ATTR || 'data-styled-components';
var SC_STREAM_ATTR = 'data-styled-streamed';
var CONTEXT_KEY = '__styled-components-stylesheet__';

var IS_BROWSER = typeof window !== 'undefined' && 'HTMLElement' in window;

var DISABLE_SPEEDY = "development" !== 'production';

// 
var SC_COMPONENT_ID = /^[^\S\n]*?\/\* sc-component-id:\s*(\S+)\s+\*\//gm;

var extractComps = (function (maybeCSS) {
  var css = '' + (maybeCSS || ''); // Definitely a string, and a clone
  var existingComponents = [];
  css.replace(SC_COMPONENT_ID, function (match, componentId, matchIndex) {
    existingComponents.push({ componentId: componentId, matchIndex: matchIndex });
    return match;
  });
  return existingComponents.map(function (_ref, i) {
    var componentId = _ref.componentId,
        matchIndex = _ref.matchIndex;

    var nextComp = existingComponents[i + 1];
    var cssFromDOM = nextComp ? css.slice(matchIndex, nextComp.matchIndex) : css.slice(matchIndex);
    return { componentId: componentId, cssFromDOM: cssFromDOM };
  });
});

// 
/* eslint-disable camelcase, no-undef */

var getNonce = (function () {
  return  true ? __webpack_require__.nc : undefined;
});

// 
// Helper to call a given function, only once
var once = (function (cb) {
  var called = false;

  return function () {
    if (!called) {
      called = true;
      cb();
    }
  };
});

// 
/* These are helpers for the StyleTags to keep track of the injected
 * rule names for each (component) ID that they're keeping track of.
 * They're crucial for detecting whether a name has already been
 * injected.
 * (This excludes rehydrated names) */

/* adds a new ID:name pairing to a names dictionary */
var addNameForId = function addNameForId(names, id, name) {
  if (name) {
    // eslint-disable-next-line no-param-reassign
    var namesForId = names[id] || (names[id] = Object.create(null));
    namesForId[name] = true;
  }
};

/* resets an ID entirely by overwriting it in the dictionary */
var resetIdNames = function resetIdNames(names, id) {
  // eslint-disable-next-line no-param-reassign
  names[id] = Object.create(null);
};

/* factory for a names dictionary checking the existance of an ID:name pairing */
var hasNameForId = function hasNameForId(names) {
  return function (id, name) {
    return names[id] !== undefined && names[id][name];
  };
};

/* stringifies names for the html/element output */
var stringifyNames = function stringifyNames(names) {
  var str = '';
  // eslint-disable-next-line guard-for-in
  for (var id in names) {
    str += Object.keys(names[id]).join(' ') + ' ';
  }
  return str.trim();
};

/* clones the nested names dictionary */
var cloneNames = function cloneNames(names) {
  var clone = Object.create(null);
  // eslint-disable-next-line guard-for-in
  for (var id in names) {
    clone[id] = _extends({}, names[id]);
  }
  return clone;
};

// 

/* These are helpers that deal with the insertRule (aka speedy) API
 * They are used in the StyleTags and specifically the speedy tag
 */

/* retrieve a sheet for a given style tag */
var sheetForTag = function sheetForTag(tag) {
  // $FlowFixMe
  if (tag.sheet) return tag.sheet;

  /* Firefox quirk requires us to step through all stylesheets to find one owned by the given tag */
  var size = document.styleSheets.length;
  for (var i = 0; i < size; i += 1) {
    var sheet = document.styleSheets[i];
    // $FlowFixMe
    if (sheet.ownerNode === tag) return sheet;
  }

  /* we should always be able to find a tag */
  throw new StyledComponentsError(10);
};

/* insert a rule safely and return whether it was actually injected */
var safeInsertRule = function safeInsertRule(sheet, cssRule, index) {
  /* abort early if cssRule string is falsy */
  if (!cssRule) return false;

  var maxIndex = sheet.cssRules.length;

  try {
    /* use insertRule and cap passed index with maxIndex (no of cssRules) */
    sheet.insertRule(cssRule, index <= maxIndex ? index : maxIndex);
  } catch (err) {
    /* any error indicates an invalid rule */
    return false;
  }

  return true;
};

/* deletes `size` rules starting from `removalIndex` */
var deleteRules = function deleteRules(sheet, removalIndex, size) {
  var lowerBound = removalIndex - size;
  for (var i = removalIndex; i > lowerBound; i -= 1) {
    sheet.deleteRule(i);
  }
};

// 

/* this marker separates component styles and is important for rehydration */
var makeTextMarker = function makeTextMarker(id) {
  return '\n/* sc-component-id: ' + id + ' */\n';
};

/* add up all numbers in array up until and including the index */
var addUpUntilIndex = function addUpUntilIndex(sizes, index) {
  var totalUpToIndex = 0;
  for (var i = 0; i <= index; i += 1) {
    totalUpToIndex += sizes[i];
  }

  return totalUpToIndex;
};

/* create a new style tag after lastEl */
var makeStyleTag = function makeStyleTag(target, tagEl, insertBefore) {
  var el = document.createElement('style');
  el.setAttribute(SC_ATTR, '');

  var nonce = getNonce();
  if (nonce) {
    el.setAttribute('nonce', nonce);
  }

  /* Work around insertRule quirk in EdgeHTML */
  el.appendChild(document.createTextNode(''));

  if (target && !tagEl) {
    /* Append to target when no previous element was passed */
    target.appendChild(el);
  } else {
    if (!tagEl || !target || !tagEl.parentNode) {
      throw new StyledComponentsError(6);
    }

    /* Insert new style tag after the previous one */
    tagEl.parentNode.insertBefore(el, insertBefore ? tagEl : tagEl.nextSibling);
  }

  return el;
};

/* takes a css factory function and outputs an html styled tag factory */
var wrapAsHtmlTag = function wrapAsHtmlTag(css, names) {
  return function (additionalAttrs) {
    var nonce = getNonce();
    var attrs = [nonce && 'nonce="' + nonce + '"', SC_ATTR + '="' + stringifyNames(names) + '"', additionalAttrs];

    var htmlAttr = attrs.filter(Boolean).join(' ');
    return '<style ' + htmlAttr + '>' + css() + '</style>';
  };
};

/* takes a css factory function and outputs an element factory */
var wrapAsElement = function wrapAsElement(css, names) {
  return function () {
    var _props;

    var props = (_props = {}, _props[SC_ATTR] = stringifyNames(names), _props);

    var nonce = getNonce();
    if (nonce) {
      // $FlowFixMe
      props.nonce = nonce;
    }

    // eslint-disable-next-line react/no-danger
    return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement('style', _extends({}, props, { dangerouslySetInnerHTML: { __html: css() } }));
  };
};

var getIdsFromMarkersFactory = function getIdsFromMarkersFactory(markers) {
  return function () {
    return Object.keys(markers);
  };
};

/* speedy tags utilise insertRule */
var makeSpeedyTag = function makeSpeedyTag(el, getImportRuleTag) {
  var names = Object.create(null);
  var markers = Object.create(null);
  var sizes = [];

  var extractImport = getImportRuleTag !== undefined;
  /* indicates whther getImportRuleTag was called */
  var usedImportRuleTag = false;

  var insertMarker = function insertMarker(id) {
    var prev = markers[id];
    if (prev !== undefined) {
      return prev;
    }

    markers[id] = sizes.length;
    sizes.push(0);
    resetIdNames(names, id);

    return markers[id];
  };

  var insertRules = function insertRules(id, cssRules, name) {
    var marker = insertMarker(id);
    var sheet = sheetForTag(el);
    var insertIndex = addUpUntilIndex(sizes, marker);

    var injectedRules = 0;
    var importRules = [];
    var cssRulesSize = cssRules.length;

    for (var i = 0; i < cssRulesSize; i += 1) {
      var cssRule = cssRules[i];
      var mayHaveImport = extractImport; /* @import rules are reordered to appear first */
      if (mayHaveImport && cssRule.indexOf('@import') !== -1) {
        importRules.push(cssRule);
      } else if (safeInsertRule(sheet, cssRule, insertIndex + injectedRules)) {
        mayHaveImport = false;
        injectedRules += 1;
      }
    }

    if (extractImport && importRules.length > 0) {
      usedImportRuleTag = true;
      // $FlowFixMe
      getImportRuleTag().insertRules(id + '-import', importRules);
    }

    sizes[marker] += injectedRules; /* add up no of injected rules */
    addNameForId(names, id, name);
  };

  var removeRules = function removeRules(id) {
    var marker = markers[id];
    if (marker === undefined) return;

    var size = sizes[marker];
    var sheet = sheetForTag(el);
    var removalIndex = addUpUntilIndex(sizes, marker);
    deleteRules(sheet, removalIndex, size);
    sizes[marker] = 0;
    resetIdNames(names, id);

    if (extractImport && usedImportRuleTag) {
      // $FlowFixMe
      getImportRuleTag().removeRules(id + '-import');
    }
  };

  var css = function css() {
    var _sheetForTag = sheetForTag(el),
        cssRules = _sheetForTag.cssRules;

    var str = '';

    // eslint-disable-next-line guard-for-in
    for (var id in markers) {
      str += makeTextMarker(id);
      var marker = markers[id];
      var end = addUpUntilIndex(sizes, marker);
      var size = sizes[marker];
      for (var i = end - size; i < end; i += 1) {
        var rule = cssRules[i];
        if (rule !== undefined) {
          str += rule.cssText;
        }
      }
    }

    return str;
  };

  return {
    clone: function clone() {
      throw new StyledComponentsError(5);
    },

    css: css,
    getIds: getIdsFromMarkersFactory(markers),
    hasNameForId: hasNameForId(names),
    insertMarker: insertMarker,
    insertRules: insertRules,
    removeRules: removeRules,
    sealed: false,
    styleTag: el,
    toElement: wrapAsElement(css, names),
    toHTML: wrapAsHtmlTag(css, names)
  };
};

var makeTextNode = function makeTextNode(id) {
  return document.createTextNode(makeTextMarker(id));
};

var makeBrowserTag = function makeBrowserTag(el, getImportRuleTag) {
  var names = Object.create(null);
  var markers = Object.create(null);

  var extractImport = getImportRuleTag !== undefined;

  /* indicates whther getImportRuleTag was called */
  var usedImportRuleTag = false;

  var insertMarker = function insertMarker(id) {
    var prev = markers[id];
    if (prev !== undefined) {
      return prev;
    }

    markers[id] = makeTextNode(id);
    el.appendChild(markers[id]);
    names[id] = Object.create(null);

    return markers[id];
  };

  var insertRules = function insertRules(id, cssRules, name) {
    var marker = insertMarker(id);
    var importRules = [];
    var cssRulesSize = cssRules.length;

    for (var i = 0; i < cssRulesSize; i += 1) {
      var rule = cssRules[i];
      var mayHaveImport = extractImport;
      if (mayHaveImport && rule.indexOf('@import') !== -1) {
        importRules.push(rule);
      } else {
        mayHaveImport = false;
        var separator = i === cssRulesSize - 1 ? '' : ' ';
        marker.appendData('' + rule + separator);
      }
    }

    addNameForId(names, id, name);

    if (extractImport && importRules.length > 0) {
      usedImportRuleTag = true;
      // $FlowFixMe
      getImportRuleTag().insertRules(id + '-import', importRules);
    }
  };

  var removeRules = function removeRules(id) {
    var marker = markers[id];
    if (marker === undefined) return;

    /* create new empty text node and replace the current one */
    var newMarker = makeTextNode(id);
    el.replaceChild(newMarker, marker);
    markers[id] = newMarker;
    resetIdNames(names, id);

    if (extractImport && usedImportRuleTag) {
      // $FlowFixMe
      getImportRuleTag().removeRules(id + '-import');
    }
  };

  var css = function css() {
    var str = '';
    // eslint-disable-next-line guard-for-in
    for (var id in markers) {
      str += markers[id].data;
    }
    return str;
  };

  return {
    clone: function clone() {
      throw new StyledComponentsError(5);
    },

    css: css,
    getIds: getIdsFromMarkersFactory(markers),
    hasNameForId: hasNameForId(names),
    insertMarker: insertMarker,
    insertRules: insertRules,
    removeRules: removeRules,
    sealed: false,
    styleTag: el,
    toElement: wrapAsElement(css, names),
    toHTML: wrapAsHtmlTag(css, names)
  };
};

var makeServerTagInternal = function makeServerTagInternal(namesArg, markersArg) {
  var names = namesArg === undefined ? Object.create(null) : namesArg;
  var markers = markersArg === undefined ? Object.create(null) : markersArg;

  var insertMarker = function insertMarker(id) {
    var prev = markers[id];
    if (prev !== undefined) {
      return prev;
    }

    return markers[id] = [''];
  };

  var insertRules = function insertRules(id, cssRules, name) {
    var marker = insertMarker(id);
    marker[0] += cssRules.join(' ');
    addNameForId(names, id, name);
  };

  var removeRules = function removeRules(id) {
    var marker = markers[id];
    if (marker === undefined) return;
    marker[0] = '';
    resetIdNames(names, id);
  };

  var css = function css() {
    var str = '';
    // eslint-disable-next-line guard-for-in
    for (var id in markers) {
      var cssForId = markers[id][0];
      if (cssForId) {
        str += makeTextMarker(id) + cssForId;
      }
    }
    return str;
  };

  var clone = function clone() {
    var namesClone = cloneNames(names);
    var markersClone = Object.create(null);

    // eslint-disable-next-line guard-for-in
    for (var id in markers) {
      markersClone[id] = [markers[id][0]];
    }

    return makeServerTagInternal(namesClone, markersClone);
  };

  var tag = {
    clone: clone,
    css: css,
    getIds: getIdsFromMarkersFactory(markers),
    hasNameForId: hasNameForId(names),
    insertMarker: insertMarker,
    insertRules: insertRules,
    removeRules: removeRules,
    sealed: false,
    styleTag: null,
    toElement: wrapAsElement(css, names),
    toHTML: wrapAsHtmlTag(css, names)
  };

  return tag;
};

var makeServerTag = function makeServerTag() {
  return makeServerTagInternal();
};

var makeTag = function makeTag(target, tagEl, forceServer, insertBefore, getImportRuleTag) {
  if (IS_BROWSER && !forceServer) {
    var el = makeStyleTag(target, tagEl, insertBefore);

    if (DISABLE_SPEEDY) {
      return makeBrowserTag(el, getImportRuleTag);
    } else {
      return makeSpeedyTag(el, getImportRuleTag);
    }
  }

  return makeServerTag();
};

/* wraps a given tag so that rehydration is performed once when necessary */
var makeRehydrationTag = function makeRehydrationTag(tag, els, extracted, immediateRehydration) {
  /* rehydration function that adds all rules to the new tag */
  var rehydrate = once(function () {
    /* add all extracted components to the new tag */
    for (var i = 0, len = extracted.length; i < len; i += 1) {
      var _extracted$i = extracted[i],
          componentId = _extracted$i.componentId,
          cssFromDOM = _extracted$i.cssFromDOM;

      var cssRules = splitByRules(cssFromDOM);
      tag.insertRules(componentId, cssRules);
    }

    /* remove old HTMLStyleElements, since they have been rehydrated */
    for (var _i = 0, _len = els.length; _i < _len; _i += 1) {
      var el = els[_i];
      if (el.parentNode) {
        el.parentNode.removeChild(el);
      }
    }
  });

  if (immediateRehydration) rehydrate();

  return _extends({}, tag, {
    /* add rehydration hook to insertion methods */
    insertMarker: function insertMarker(id) {
      rehydrate();
      return tag.insertMarker(id);
    },
    insertRules: function insertRules(id, cssRules, name) {
      rehydrate();
      return tag.insertRules(id, cssRules, name);
    }
  });
};

// 

var SPLIT_REGEX = /\s+/;

/* determine the maximum number of components before tags are sharded */
var MAX_SIZE = void 0;
if (IS_BROWSER) {
  /* in speedy mode we can keep a lot more rules in a sheet before a slowdown can be expected */
  MAX_SIZE = DISABLE_SPEEDY ? 40 : 1000;
} else {
  /* for servers we do not need to shard at all */
  MAX_SIZE = -1;
}

var sheetRunningId = 0;
var master = void 0;

var StyleSheet = function () {
  /* a map from ids to tags */
  /* deferred rules for a given id */
  /* this is used for not reinjecting rules via hasNameForId() */
  /* when rules for an id are removed using remove() we have to ignore rehydratedNames for it */
  /* a list of tags belonging to this StyleSheet */
  /* a tag for import rules */
  /* current capacity until a new tag must be created */
  /* children (aka clones) of this StyleSheet inheriting all and future injections */

  function StyleSheet() {
    var _this = this;

    var target = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : IS_BROWSER ? document.head : null;
    var forceServer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    classCallCheck(this, StyleSheet);

    this.getImportRuleTag = function () {
      var importRuleTag = _this.importRuleTag;

      if (importRuleTag !== undefined) {
        return importRuleTag;
      }

      var firstTag = _this.tags[0];
      var insertBefore = true;

      return _this.importRuleTag = makeTag(_this.target, firstTag ? firstTag.styleTag : null, _this.forceServer, insertBefore);
    };

    sheetRunningId += 1;
    this.id = sheetRunningId;
    this.forceServer = forceServer;
    this.target = forceServer ? null : target;
    this.tagMap = {};
    this.deferred = {};
    this.rehydratedNames = {};
    this.ignoreRehydratedNames = {};
    this.tags = [];
    this.capacity = 1;
    this.clones = [];
  }

  /* rehydrate all SSR'd style tags */


  StyleSheet.prototype.rehydrate = function rehydrate() {
    if (!IS_BROWSER || this.forceServer) {
      return this;
    }

    var els = [];
    var extracted = [];
    var isStreamed = false;

    /* retrieve all of our SSR style elements from the DOM */
    var nodes = document.querySelectorAll('style[' + SC_ATTR + ']');
    var nodesSize = nodes.length;

    /* abort rehydration if no previous style tags were found */
    if (nodesSize === 0) {
      return this;
    }

    for (var i = 0; i < nodesSize; i += 1) {
      // $FlowFixMe: We can trust that all elements in this query are style elements
      var el = nodes[i];

      /* check if style tag is a streamed tag */
      if (!isStreamed) isStreamed = !!el.getAttribute(SC_STREAM_ATTR);

      /* retrieve all component names */
      var elNames = (el.getAttribute(SC_ATTR) || '').trim().split(SPLIT_REGEX);
      var elNamesSize = elNames.length;
      for (var j = 0; j < elNamesSize; j += 1) {
        var name = elNames[j];
        /* add rehydrated name to sheet to avoid readding styles */
        this.rehydratedNames[name] = true;
      }

      /* extract all components and their CSS */
      extracted.push.apply(extracted, extractComps(el.textContent));

      /* store original HTMLStyleElement */
      els.push(el);
    }

    /* abort rehydration if nothing was extracted */
    var extractedSize = extracted.length;
    if (extractedSize === 0) {
      return this;
    }

    /* create a tag to be used for rehydration */
    var tag = this.makeTag(null);
    var rehydrationTag = makeRehydrationTag(tag, els, extracted, isStreamed);

    /* reset capacity and adjust MAX_SIZE by the initial size of the rehydration */
    this.capacity = Math.max(1, MAX_SIZE - extractedSize);
    this.tags.push(rehydrationTag);

    /* retrieve all component ids */
    for (var _j = 0; _j < extractedSize; _j += 1) {
      this.tagMap[extracted[_j].componentId] = rehydrationTag;
    }

    return this;
  };

  /* retrieve a "master" instance of StyleSheet which is typically used when no other is available
   * The master StyleSheet is targeted by injectGlobal, keyframes, and components outside of any
    * StyleSheetManager's context */


  /* reset the internal "master" instance */
  StyleSheet.reset = function reset() {
    var forceServer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

    master = new StyleSheet(undefined, forceServer).rehydrate();
  };

  /* adds "children" to the StyleSheet that inherit all of the parents' rules
   * while their own rules do not affect the parent */


  StyleSheet.prototype.clone = function clone() {
    var sheet = new StyleSheet(this.target, this.forceServer);

    /* add to clone array */
    this.clones.push(sheet);

    /* clone all tags */
    sheet.tags = this.tags.map(function (tag) {
      var ids = tag.getIds();
      var newTag = tag.clone();

      /* reconstruct tagMap */
      for (var i = 0; i < ids.length; i += 1) {
        sheet.tagMap[ids[i]] = newTag;
      }

      return newTag;
    });

    /* clone other maps */
    sheet.rehydratedNames = _extends({}, this.rehydratedNames);
    sheet.deferred = _extends({}, this.deferred);

    return sheet;
  };

  /* force StyleSheet to create a new tag on the next injection */


  StyleSheet.prototype.sealAllTags = function sealAllTags() {
    this.capacity = 1;

    this.tags.forEach(function (tag) {
      // eslint-disable-next-line no-param-reassign
      tag.sealed = true;
    });
  };

  StyleSheet.prototype.makeTag = function makeTag$$1(tag) {
    var lastEl = tag ? tag.styleTag : null;
    var insertBefore = false;

    return makeTag(this.target, lastEl, this.forceServer, insertBefore, this.getImportRuleTag);
  };

  /* get a tag for a given componentId, assign the componentId to one, or shard */
  StyleSheet.prototype.getTagForId = function getTagForId(id) {
    /* simply return a tag, when the componentId was already assigned one */
    var prev = this.tagMap[id];
    if (prev !== undefined && !prev.sealed) {
      return prev;
    }

    var tag = this.tags[this.tags.length - 1];

    /* shard (create a new tag) if the tag is exhausted (See MAX_SIZE) */
    this.capacity -= 1;

    if (this.capacity === 0) {
      this.capacity = MAX_SIZE;
      tag = this.makeTag(tag);
      this.tags.push(tag);
    }

    return this.tagMap[id] = tag;
  };

  /* mainly for injectGlobal to check for its id */


  StyleSheet.prototype.hasId = function hasId(id) {
    return this.tagMap[id] !== undefined;
  };

  /* caching layer checking id+name to already have a corresponding tag and injected rules */


  StyleSheet.prototype.hasNameForId = function hasNameForId(id, name) {
    /* exception for rehydrated names which are checked separately */
    if (this.ignoreRehydratedNames[id] === undefined && this.rehydratedNames[name]) {
      return true;
    }

    var tag = this.tagMap[id];
    return tag !== undefined && tag.hasNameForId(id, name);
  };

  /* registers a componentId and registers it on its tag */


  StyleSheet.prototype.deferredInject = function deferredInject(id, cssRules) {
    /* don't inject when the id is already registered */
    if (this.tagMap[id] !== undefined) return;

    var clones = this.clones;

    for (var i = 0; i < clones.length; i += 1) {
      clones[i].deferredInject(id, cssRules);
    }

    this.getTagForId(id).insertMarker(id);
    this.deferred[id] = cssRules;
  };

  /* injects rules for a given id with a name that will need to be cached */


  StyleSheet.prototype.inject = function inject(id, cssRules, name) {
    var clones = this.clones;


    for (var i = 0; i < clones.length; i += 1) {
      clones[i].inject(id, cssRules, name);
    }

    var tag = this.getTagForId(id);

    /* add deferred rules for component */
    if (this.deferred[id] !== undefined) {
      // Combine passed cssRules with previously deferred CSS rules
      // NOTE: We cannot mutate the deferred array itself as all clones
      // do the same (see clones[i].inject)
      var rules = this.deferred[id].concat(cssRules);
      tag.insertRules(id, rules, name);

      this.deferred[id] = undefined;
    } else {
      tag.insertRules(id, cssRules, name);
    }
  };

  /* removes all rules for a given id, which doesn't remove its marker but resets it */


  StyleSheet.prototype.remove = function remove(id) {
    var tag = this.tagMap[id];
    if (tag === undefined) return;

    var clones = this.clones;

    for (var i = 0; i < clones.length; i += 1) {
      clones[i].remove(id);
    }

    /* remove all rules from the tag */
    tag.removeRules(id);
    /* ignore possible rehydrated names */
    this.ignoreRehydratedNames[id] = true;
    /* delete possible deferred rules */
    this.deferred[id] = undefined;
  };

  StyleSheet.prototype.toHTML = function toHTML() {
    return this.tags.map(function (tag) {
      return tag.toHTML();
    }).join('');
  };

  StyleSheet.prototype.toReactElements = function toReactElements() {
    var id = this.id;


    return this.tags.map(function (tag, i) {
      var key = 'sc-' + id + '-' + i;
      return Object(react__WEBPACK_IMPORTED_MODULE_1__["cloneElement"])(tag.toElement(), { key: key });
    });
  };

  createClass(StyleSheet, null, [{
    key: 'master',
    get: function get$$1() {
      return master || (master = new StyleSheet().rehydrate());
    }

    /* NOTE: This is just for backwards-compatibility with jest-styled-components */

  }, {
    key: 'instance',
    get: function get$$1() {
      return StyleSheet.master;
    }
  }]);
  return StyleSheet;
}();

var _StyleSheetManager$ch;

var StyleSheetManager = function (_Component) {
  inherits(StyleSheetManager, _Component);

  function StyleSheetManager() {
    classCallCheck(this, StyleSheetManager);
    return possibleConstructorReturn(this, _Component.apply(this, arguments));
  }

  StyleSheetManager.prototype.getChildContext = function getChildContext() {
    var _ref;

    return _ref = {}, _ref[CONTEXT_KEY] = this.sheetInstance, _ref;
  };

  StyleSheetManager.prototype.componentWillMount = function componentWillMount() {
    if (this.props.sheet) {
      this.sheetInstance = this.props.sheet;
    } else if (this.props.target) {
      this.sheetInstance = new StyleSheet(this.props.target);
    } else {
      throw new StyledComponentsError(4);
    }
  };

  StyleSheetManager.prototype.render = function render() {
    /* eslint-disable react/prop-types */
    // Flow v0.43.1 will report an error accessing the `children` property,
    // but v0.47.0 will not. It is necessary to use a type cast instead of
    // a "fixme" comment to satisfy both Flow versions.
    return react__WEBPACK_IMPORTED_MODULE_1___default.a.Children.only(this.props.children);
  };

  return StyleSheetManager;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]);

StyleSheetManager.childContextTypes = (_StyleSheetManager$ch = {}, _StyleSheetManager$ch[CONTEXT_KEY] = prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.instanceOf(StyleSheet), prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.instanceOf(ServerStyleSheet)]).isRequired, _StyleSheetManager$ch);
 true ? StyleSheetManager.propTypes = {
  sheet: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.instanceOf(StyleSheet), prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.instanceOf(ServerStyleSheet)]),
  target: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.shape({
    appendChild: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.func.isRequired
  })
} : undefined;

// 

var ServerStyleSheet = function () {
  function ServerStyleSheet() {
    classCallCheck(this, ServerStyleSheet);

    /* The master sheet might be reset, so keep a reference here */
    this.masterSheet = StyleSheet.master;
    this.instance = this.masterSheet.clone();
    this.closed = false;
  }

  ServerStyleSheet.prototype.complete = function complete() {
    if (!this.closed) {
      /* Remove closed StyleSheets from the master sheet */
      var index = this.masterSheet.clones.indexOf(this.instance);
      this.masterSheet.clones.splice(index, 1);
      this.closed = true;
    }
  };

  ServerStyleSheet.prototype.collectStyles = function collectStyles(children) {
    if (this.closed) {
      throw new StyledComponentsError(2);
    }

    return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(
      StyleSheetManager,
      { sheet: this.instance },
      children
    );
  };

  ServerStyleSheet.prototype.getStyleTags = function getStyleTags() {
    this.complete();
    return this.instance.toHTML();
  };

  ServerStyleSheet.prototype.getStyleElement = function getStyleElement() {
    this.complete();
    return this.instance.toReactElements();
  };

  ServerStyleSheet.prototype.interleaveWithNodeStream = function interleaveWithNodeStream(readableStream) {
    var _this = this;

    {
      throw new StyledComponentsError(3);
    }

    /* the tag index keeps track of which tags have already been emitted */
    var instance = this.instance;

    var instanceTagIndex = 0;

    var streamAttr = SC_STREAM_ATTR + '="true"';

    var transformer = new stream.Transform({
      transform: function appendStyleChunks(chunk, /* encoding */_, callback) {
        var tags = instance.tags;

        var html = '';

        /* retrieve html for each new style tag */
        for (; instanceTagIndex < tags.length; instanceTagIndex += 1) {
          var tag = tags[instanceTagIndex];
          html += tag.toHTML(streamAttr);
        }

        /* force our StyleSheets to emit entirely new tags */
        instance.sealAllTags();

        /* prepend style html to chunk */
        this.push(html + chunk);
        callback();
      }
    });

    readableStream.on('end', function () {
      return _this.complete();
    });
    readableStream.on('error', function (err) {
      _this.complete();

      // forward the error to the transform stream
      transformer.emit('error', err);
    });

    return readableStream.pipe(transformer);
  };

  return ServerStyleSheet;
}();

// 

var LIMIT = 200;

var createWarnTooManyClasses = (function (displayName) {
  var generatedClasses = {};
  var warningSeen = false;

  return function (className) {
    if (!warningSeen) {
      generatedClasses[className] = true;
      if (Object.keys(generatedClasses).length >= LIMIT) {
        // Unable to find latestRule in test environment.
        /* eslint-disable no-console, prefer-template */
        console.warn('Over ' + LIMIT + ' classes were generated for component ' + displayName + '. \n' + 'Consider using the attrs method, together with a style object for frequently changed styles.\n' + 'Example:\n' + '  const Component = styled.div.attrs({\n' + '    style: ({ background }) => ({\n' + '      background,\n' + '    }),\n' + '  })`width: 100%;`\n\n' + '  <Component />');
        warningSeen = true;
        generatedClasses = {};
      }
    }
  };
});

// 

var determineTheme = (function (props, fallbackTheme, defaultProps) {
  // Props should take precedence over ThemeProvider, which should take precedence over
  // defaultProps, but React automatically puts defaultProps on props.

  /* eslint-disable react/prop-types */
  var isDefaultTheme = defaultProps && props.theme === defaultProps.theme;
  var theme = props.theme && !isDefaultTheme ? props.theme : fallbackTheme;
  /* eslint-enable */

  return theme;
});

// 
var escapeRegex = /[[\].#*$><+~=|^:(),"'`-]+/g;
var dashesAtEnds = /(^-|-$)/g;

/**
 * TODO: Explore using CSS.escape when it becomes more available
 * in evergreen browsers.
 */
function escape(str) {
  return str
  // Replace all possible CSS selectors
  .replace(escapeRegex, '-')

  // Remove extraneous hyphens at the start and end
  .replace(dashesAtEnds, '');
}

// 

function getComponentName(target) {
  return target.displayName || target.name || 'Component';
}

// 

function isTag(target) /* : %checks */{
  return typeof target === 'string';
}

// 

function generateDisplayName(target) {
  return isTag(target) ? 'styled.' + target : 'Styled(' + getComponentName(target) + ')';
}

// 
/* eslint-disable max-len */
/**
 * Trying to avoid the unknown-prop errors on styled components by filtering by
 * React's attribute whitelist.
 *
 * To regenerate this regex:
 *
 * 1. `npm i -g regexgen` (https://github.com/devongovett/regexgen)
 * 2. Run `regexgen` with the list of space-separated words below as input
 * 3. Surround the emitted regex with this: `/^(GENERATED_REGEX)$/` -- this will ensure a full string match
 *    and no false positives from partials
 * */
/*
children dangerouslySetInnerHTML key ref autoFocus defaultValue valueLink defaultChecked checkedLink innerHTML suppressContentEditableWarning onFocusIn onFocusOut className onCopy onCut onPaste onCompositionEnd onCompositionStart onCompositionUpdate onKeyDown onKeyPress onKeyUp onFocus onBlur onChange onInput onInvalid onSubmit onReset onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave onMouseMove onMouseOut onMouseOver onMouseUp onSelect onTouchCancel onTouchEnd onTouchMove onTouchStart onScroll onWheel onAbort onCanPlay onCanPlayThrough onDurationChange onEmptied onEncrypted onEnded onError onLoadedData onLoadedMetadata onLoadStart onPause onPlay onPlaying onProgress onRateChange onSeeked onSeeking onStalled onSuspend onTimeUpdate onVolumeChange onWaiting onLoad onAnimationStart onAnimationEnd onAnimationIteration onTransitionEnd onCopyCapture onCutCapture onPasteCapture onCompositionEndCapture onCompositionStartCapture onCompositionUpdateCapture onKeyDownCapture onKeyPressCapture onKeyUpCapture onFocusCapture onBlurCapture onChangeCapture onInputCapture onSubmitCapture onResetCapture onClickCapture onContextMenuCapture onDoubleClickCapture onDragCapture onDragEndCapture onDragEnterCapture onDragExitCapture onDragLeaveCapture onDragOverCapture onDragStartCapture onDropCapture onMouseDownCapture onMouseEnterCapture onMouseLeaveCapture onMouseMoveCapture onMouseOutCapture onMouseOverCapture onMouseUpCapture onSelectCapture onTouchCancelCapture onTouchEndCapture onTouchMoveCapture onTouchStartCapture onScrollCapture onWheelCapture onAbortCapture onCanPlayCapture onCanPlayThroughCapture onDurationChangeCapture onEmptiedCapture onEncryptedCapture onEndedCapture onErrorCapture onLoadedDataCapture onLoadedMetadataCapture onLoadStartCapture onPauseCapture onPlayCapture onPlayingCapture onProgressCapture onRateChangeCapture onSeekedCapture onSeekingCapture onStalledCapture onSuspendCapture onTimeUpdateCapture onVolumeChangeCapture onWaitingCapture onLoadCapture onAnimationStartCapture onAnimationEndCapture onAnimationIterationCapture onTransitionEndCapture accept acceptCharset accessKey action allowFullScreen allowTransparency alt as async autoComplete autoPlay capture cellPadding cellSpacing charSet challenge checked cite classID className cols colSpan content contentEditable contextMenu controlsList controls coords crossOrigin data dateTime default defer dir disabled download draggable encType form formAction formEncType formMethod formNoValidate formTarget frameBorder headers height hidden high href hrefLang htmlFor httpEquiv icon id inputMode integrity is keyParams keyType kind label lang list loop low manifest marginHeight marginWidth max maxLength media mediaGroup method min minLength multiple muted name nonce noValidate open optimum pattern placeholder playsInline poster preload profile radioGroup readOnly referrerPolicy rel required reversed role rows rowSpan sandbox scope scoped scrolling seamless selected shape size sizes span spellCheck src srcDoc srcLang srcSet start step style summary tabIndex target title type useMap value width wmode wrap about datatype inlist prefix property resource typeof vocab autoCapitalize autoCorrect autoSave color itemProp itemScope itemType itemID itemRef results security unselectable accentHeight accumulate additive alignmentBaseline allowReorder alphabetic amplitude arabicForm ascent attributeName attributeType autoReverse azimuth baseFrequency baseProfile baselineShift bbox begin bias by calcMode capHeight clip clipPath clipRule clipPathUnits colorInterpolation colorInterpolationFilters colorProfile colorRendering contentScriptType contentStyleType cursor cx cy d decelerate descent diffuseConstant direction display divisor dominantBaseline dur dx dy edgeMode elevation enableBackground end exponent externalResourcesRequired fill fillOpacity fillRule filter filterRes filterUnits floodColor floodOpacity focusable fontFamily fontSize fontSizeAdjust fontStretch fontStyle fontVariant fontWeight format from fx fy g1 g2 glyphName glyphOrientationHorizontal glyphOrientationVertical glyphRef gradientTransform gradientUnits hanging horizAdvX horizOriginX ideographic imageRendering in in2 intercept k k1 k2 k3 k4 kernelMatrix kernelUnitLength kerning keyPoints keySplines keyTimes lengthAdjust letterSpacing lightingColor limitingConeAngle local markerEnd markerMid markerStart markerHeight markerUnits markerWidth mask maskContentUnits maskUnits mathematical mode numOctaves offset opacity operator order orient orientation origin overflow overlinePosition overlineThickness paintOrder panose1 pathLength patternContentUnits patternTransform patternUnits pointerEvents points pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits r radius refX refY renderingIntent repeatCount repeatDur requiredExtensions requiredFeatures restart result rotate rx ry scale seed shapeRendering slope spacing specularConstant specularExponent speed spreadMethod startOffset stdDeviation stemh stemv stitchTiles stopColor stopOpacity strikethroughPosition strikethroughThickness string stroke strokeDasharray strokeDashoffset strokeLinecap strokeLinejoin strokeMiterlimit strokeOpacity strokeWidth surfaceScale systemLanguage tableValues targetX targetY textAnchor textDecoration textRendering textLength to transform u1 u2 underlinePosition underlineThickness unicode unicodeBidi unicodeRange unitsPerEm vAlphabetic vHanging vIdeographic vMathematical values vectorEffect version vertAdvY vertOriginX vertOriginY viewBox viewTarget visibility widths wordSpacing writingMode x xHeight x1 x2 xChannelSelector xlinkActuate xlinkArcrole xlinkHref xlinkRole xlinkShow xlinkTitle xlinkType xmlBase xmlns xmlnsXlink xmlLang xmlSpace y y1 y2 yChannelSelector z zoomAndPan onPointerDown onPointerMove onPointerUp onPointerCancel onGotPointerCapture onLostPointerCapture onPointerEnter onPointerLeave onPointerOver onPointerOut class for autofocus allow allowUserMedia allowPaymentRequest
*/
/* eslint-enable max-len */

var ATTRIBUTE_REGEX = /^((?:s(?:uppressContentEditableWarn|croll|pac)|(?:shape|image|text)Render|(?:letter|word)Spac|vHang|hang)ing|(?:on(?:AnimationIteration|C(?:o(?:mposition(?:Update|Start|End)|ntextMenu|py)|anPlayThrough|anPlay|hange|lick|ut)|(?:Animation|Touch|Load|Drag)Start|(?:(?:Duration|Volume|Rate)Chang|(?:MouseLea|(?:Touch|Mouse)Mo|DragLea)v|Paus)e|Loaded(?:Metad|D)ata|(?:(?:T(?:ransition|ouch)|Animation)E|Suspe)nd|DoubleClick|(?:TouchCanc|Whe)el|Lo(?:stPointer|ad)|TimeUpdate|(?:Mouse(?:Ent|Ov)e|Drag(?:Ent|Ov)e|Erro)r|GotPointer|MouseDown|(?:E(?:n(?:crypt|d)|mpti)|S(?:tall|eek))ed|KeyPress|(?:MouseOu|DragExi|S(?:elec|ubmi)|Rese|Inpu)t|P(?:rogress|laying)|DragEnd|Key(?:Down|Up)|(?:MouseU|Dro)p|(?:Wait|Seek)ing|Scroll|Focus|Paste|Abort|Drag|Play|Blur)Captur|alignmentBaselin|(?:limitingConeAng|xlink(?:(?:Arcr|R)o|Tit)|s(?:urfaceSca|ty|ca)|unselectab|baseProfi|fontSty|(?:focus|dragg)ab|multip|profi|tit)l|d(?:ominantBaselin|efaultValu)|onPointerLeav|a(?:uto(?:Capitaliz|Revers|Sav)|dditiv)|(?:(?:formNoValid|xlinkActu|noValid|accumul|rot)a|autoComple|decelera)t|(?:(?:attribute|item)T|datat)yp|onPointerMov|(?:attribute|glyph)Nam|playsInlin|(?:writing|input|edge)Mod|(?:formE|e)ncTyp|(?:amplitu|mo)d|(?:xlinkTy|itemSco|keyTy|slo)p|(?:xmlSpa|non)c|fillRul|(?:dateTi|na)m|r(?:esourc|ol)|xmlBas|wmod)e|(?:glyphOrientationHorizont|loc)al|(?:externalResourcesRequir|select|revers|mut)ed|c(?:o(?:lorInterpolationFilter|ord)s|o(?:lor(?:Interpolation)?|nt(?:rols|ent))|(?:ontentS(?:cript|tyle)Typ|o(?:ntentEditab|lorProfi)l|l(?:assNam|ipRul)|a(?:lcMod|ptur)|it)e|olorRendering|l(?:ipPathUnits|assID)|(?:ontrolsLis|apHeigh)t|h(?:eckedLink|a(?:llenge|rSet)|ildren|ecked)|ell(?:Spac|Padd)ing|o(?:ntextMenu|ls)|(?:rossOrigi|olSpa)n|l(?:ip(?:Path)?|ass)|ursor|[xy])|glyphOrientationVertical|d(?:angerouslySetInnerHTML|efaultChecked|ownload|isabled|isplay|[xy])|(?:s(?:trikethroughThickn|eaml)es|(?:und|ov)erlineThicknes|r(?:equiredExtension|adiu)|(?:requiredFeatur|tableValu|stitchTil|numOctav|filterR)e|key(?:(?:Splin|Tim)e|Param)|auto[Ff]ocu|header|bia)s|(?:(?:st(?:rikethroughPosi|dDevia)|(?:und|ov)erlinePosi|(?:textDecor|elev)a|orienta)tio|(?:strokeLinejo|orig)i|on(?:PointerDow|FocusI)|formActio|zoomAndPa|directio|(?:vers|act)io|rowSpa|begi|ico)n|o(?:n(?:AnimationIteration|C(?:o(?:mposition(?:Update|Start|End)|ntextMenu|py)|anPlayThrough|anPlay|hange|lick|ut)|(?:(?:Duration|Volume|Rate)Chang|(?:MouseLea|(?:Touch|Mouse)Mo|DragLea)v|Paus)e|Loaded(?:Metad|D)ata|(?:Animation|Touch|Load|Drag)Start|(?:(?:T(?:ransition|ouch)|Animation)E|Suspe)nd|DoubleClick|(?:TouchCanc|Whe)el|(?:Mouse(?:Ent|Ov)e|Drag(?:Ent|Ov)e|Erro)r|TimeUpdate|(?:E(?:n(?:crypt|d)|mpti)|S(?:tall|eek))ed|MouseDown|P(?:rogress|laying)|(?:MouseOu|DragExi|S(?:elec|ubmi)|Rese|Inpu)t|KeyPress|DragEnd|Key(?:Down|Up)|(?:Wait|Seek)ing|(?:MouseU|Dro)p|Scroll|Paste|Focus|Abort|Drag|Play|Load|Blur)|rient)|p(?:reserveAspectRatio|ointsAt[X-Z]|anose1)|(?:(?:allowPaymentReque|(?:fontSize|length)Adju|manife)s|strokeMiterlimi|(?:(?:specularE|e)xpon|renderingInt|asc)en|(?:specularConsta|repeatCou|fontVaria)n|d(?:iffuseConsta|esce)n|baselineShif|vectorEffec|onPointerOu|(?:(?:mar(?:ker|gin)|x)H|accentH|fontW)eigh|markerStar|a(?:utoCorrec|bou)|onFocusOu|intercep|restar|forma|inlis|heigh|lis)t|(?:patternContent|ma(?:sk(?:Content)?|rker)|primitive|gradient|pattern|filter)Units|(?:(?:allowTranspar|baseFrequ)enc|re(?:ferrerPolic|adOnl)|(?:(?:st(?:roke|op)O|floodO|fillO|o)pac|integr|secur)it|visibilit|fontFamil|accessKe|propert|summar)y|(?:gradientT|patternT|t)ransform|(?:(?:st(?:rokeDasho|artO)|o)ffs|acceptChars|formTarg|viewTarg|srcS)et|(?:[xy]ChannelSelect|lightingCol|textAnch|floodCol|stopCol|operat|htmlF)or|(?:(?:enableBackgrou|markerE)n|s(?:p(?:readMetho|ee)|ee)|formMetho|(?:markerM|onInval)i|preloa|metho|kin)d|k(?:ernel(?:UnitLength|Matrix)|[1-4])|strokeDasharray|(?:onPointerCanc|lab)el|(?:allowFullScre|hidd)en|a(?:l(?:lowUserMedia|phabetic|t)|rabicForm|sync)|systemLanguage|(?:(?:o(?:nPointer(?:Ent|Ov)|rd)|allowReord|placehold|frameBord|paintOrd|post)e|repeatDu|d(?:efe|u))r|(?:pointerEve|keyPoi)nts|preserveAlpha|(?:strokeLineca|onPointerU|itemPro|useMa|wra|loo)p|v(?:Mathematical|ert(?:Origin[XY]|AdvY)|alues|ocab)|unicodeRange|h(?:oriz(?:Origin|Adv)X|ttpEquiv)|(?:vI|i)deographic|mathematical|u(?:nicodeBidi|[12])|(?:fontStretc|hig)h|vAlphabetic|(?:(?:mar(?:ker|gin)W|strokeW)id|azimu)th|(?:xmlnsXl|valueL)ink|mediaGroup|spellCheck|(?:text|m(?:in|ax))Length|(?:unitsPerE|optimu|fro)m|r(?:adioGroup|e(?:sults|f[XY]|l)|ows|[xy])|pathLength|(?:xlinkHr|glyphR)ef|innerHTML|xlinkShow|f(?:o(?:ntSize|rm?)|il(?:ter|l))|(?:tabInde|(?:sand|b)bo|viewBo)x|autoPlay|r(?:e(?:quired|sult|f))?|(?:(?:href|xml|src)La|kerni)ng|o(?:verflow|pen)|i(?:temRef|n2|s)|p(?:attern|oints)|unicode|d(?:efault|ata|ir)?|divisor|t(?:arget[XY]|o)|(?:stri|la)ng|(?:width|size)s|prefix|typeof|srcDoc|s(?:coped|te(?:m[hv]|p)|pan)|s(?:t(?:roke|art)|hape|cope|rc)|a(?:ccept|llow|s)|itemID|t(?:arget|ype)|m(?:edia|a(?:sk|x)|in)|value|width|x(?:mlns)?|size|href|k(?:ey)?|end|low|by|x[12]|y[12]|g[12]|i[dn]|f[xy]|[yz])$/;
/* From DOMProperty */
var ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD';
var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040';
var isCustomAttribute = RegExp.prototype.test.bind(new RegExp('^(x|data|aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$'));

var validAttr = (function (name) {
  return ATTRIBUTE_REGEX.test(name) || isCustomAttribute(name.toLowerCase());
});

// 

function hasInInheritanceChain(child, parent) {
  var target = child;

  while (target) {
    target = Object.getPrototypeOf(target);

    if (target && target === parent) {
      return true;
    }
  }

  return false;
}

// 
/**
 * Creates a broadcast that can be listened to, i.e. simple event emitter
 *
 * @see https://github.com/ReactTraining/react-broadcast
 */

var createBroadcast = function createBroadcast(initialState) {
  var listeners = {};
  var id = 0;
  var state = initialState;

  function publish(nextState) {
    state = nextState;

    // eslint-disable-next-line guard-for-in, no-restricted-syntax
    for (var key in listeners) {
      var listener = listeners[key];
      if (listener === undefined) {
        // eslint-disable-next-line no-continue
        continue;
      }

      listener(state);
    }
  }

  function subscribe(listener) {
    var currentId = id;
    listeners[currentId] = listener;
    id += 1;
    listener(state);
    return currentId;
  }

  function unsubscribe(unsubID) {
    listeners[unsubID] = undefined;
  }

  return { publish: publish, subscribe: subscribe, unsubscribe: unsubscribe };
};

var _contextShape, _ThemeProvider$contex;

// NOTE: DO NOT CHANGE, changing this is a semver major change!
var CHANNEL = '__styled-components__';
var CHANNEL_NEXT = CHANNEL + 'next__';

var CONTEXT_CHANNEL_SHAPE = prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.shape({
  getTheme: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.func,
  subscribe: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.func,
  unsubscribe: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.func
});

var contextShape = (_contextShape = {}, _contextShape[CHANNEL] = prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.func, _contextShape[CHANNEL_NEXT] = CONTEXT_CHANNEL_SHAPE, _contextShape);

var warnChannelDeprecated = void 0;
if (true) {
  warnChannelDeprecated = once(function () {
    // eslint-disable-next-line no-console
    console.warn('Warning: Usage of `context.' + CHANNEL + '` as a function is deprecated. It will be replaced with the object on `.context.' + CHANNEL_NEXT + '` in a future version.');
  });
}

var isFunction = function isFunction(test) {
  return typeof test === 'function';
};

/**
 * Provide a theme to an entire react component tree via context and event listeners (have to do
 * both context and event emitter as pure components block context updates)
 */

var ThemeProvider = function (_Component) {
  inherits(ThemeProvider, _Component);

  function ThemeProvider() {
    classCallCheck(this, ThemeProvider);

    var _this = possibleConstructorReturn(this, _Component.call(this));

    _this.unsubscribeToOuterId = -1;

    _this.getTheme = _this.getTheme.bind(_this);
    return _this;
  }

  ThemeProvider.prototype.componentWillMount = function componentWillMount() {
    var _this2 = this;

    // If there is a ThemeProvider wrapper anywhere around this theme provider, merge this theme
    // with the outer theme
    var outerContext = this.context[CHANNEL_NEXT];
    if (outerContext !== undefined) {
      this.unsubscribeToOuterId = outerContext.subscribe(function (theme) {
        _this2.outerTheme = theme;

        if (_this2.broadcast !== undefined) {
          _this2.publish(_this2.props.theme);
        }
      });
    }

    this.broadcast = createBroadcast(this.getTheme());
  };

  ThemeProvider.prototype.getChildContext = function getChildContext() {
    var _this3 = this,
        _babelHelpers$extends;

    return _extends({}, this.context, (_babelHelpers$extends = {}, _babelHelpers$extends[CHANNEL_NEXT] = {
      getTheme: this.getTheme,
      subscribe: this.broadcast.subscribe,
      unsubscribe: this.broadcast.unsubscribe
    }, _babelHelpers$extends[CHANNEL] = function (subscriber) {
      if (true) {
        warnChannelDeprecated();
      }

      // Patch the old `subscribe` provide via `CHANNEL` for older clients.
      var unsubscribeId = _this3.broadcast.subscribe(subscriber);
      return function () {
        return _this3.broadcast.unsubscribe(unsubscribeId);
      };
    }, _babelHelpers$extends));
  };

  ThemeProvider.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
    if (this.props.theme !== nextProps.theme) {
      this.publish(nextProps.theme);
    }
  };

  ThemeProvider.prototype.componentWillUnmount = function componentWillUnmount() {
    if (this.unsubscribeToOuterId !== -1) {
      this.context[CHANNEL_NEXT].unsubscribe(this.unsubscribeToOuterId);
    }
  };

  // Get the theme from the props, supporting both (outerTheme) => {} as well as object notation


  ThemeProvider.prototype.getTheme = function getTheme(passedTheme) {
    var theme = passedTheme || this.props.theme;

    if (isFunction(theme)) {
      var mergedTheme = theme(this.outerTheme);

      if ("development" !== 'production' && (mergedTheme === null || Array.isArray(mergedTheme) || (typeof mergedTheme === 'undefined' ? 'undefined' : _typeof(mergedTheme)) !== 'object')) {
        throw new StyledComponentsError(7);
      }

      return mergedTheme;
    }

    if (theme === null || Array.isArray(theme) || (typeof theme === 'undefined' ? 'undefined' : _typeof(theme)) !== 'object') {
      throw new StyledComponentsError(8);
    }

    return _extends({}, this.outerTheme, theme);
  };

  ThemeProvider.prototype.publish = function publish(theme) {
    this.broadcast.publish(this.getTheme(theme));
  };

  ThemeProvider.prototype.render = function render() {
    if (!this.props.children) {
      return null;
    }

    return react__WEBPACK_IMPORTED_MODULE_1___default.a.Children.only(this.props.children);
  };

  return ThemeProvider;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]);

ThemeProvider.childContextTypes = contextShape;
ThemeProvider.contextTypes = (_ThemeProvider$contex = {}, _ThemeProvider$contex[CHANNEL_NEXT] = CONTEXT_CHANNEL_SHAPE, _ThemeProvider$contex);

var _babelHelpers$extends;

// HACK for generating all static styles without needing to allocate
// an empty execution context every single time...
var STATIC_EXECUTION_CONTEXT = {};

var modifiedContextShape = _extends({}, contextShape, (_babelHelpers$extends = {}, _babelHelpers$extends[CONTEXT_KEY] = prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.instanceOf(StyleSheet), prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.instanceOf(ServerStyleSheet)]), _babelHelpers$extends));

var identifiers = {};

/* We depend on components having unique IDs */
var generateId = function generateId(ComponentStyle, _displayName, parentComponentId) {
  var displayName = typeof _displayName !== 'string' ? 'sc' : escape(_displayName);

  /**
   * This ensures uniqueness if two components happen to share
   * the same displayName.
   */
  var nr = (identifiers[displayName] || 0) + 1;
  identifiers[displayName] = nr;

  var componentId = displayName + '-' + ComponentStyle.generateName(displayName + nr);

  return parentComponentId !== undefined ? parentComponentId + '-' + componentId : componentId;
};

var warnExtendDeprecated = function warnExtendDeprecated() {};
if (true) {
  warnExtendDeprecated = once(function () {
    // eslint-disable-next-line no-console
    console.warn('Warning: The "extend" API will be removed in the upcoming v4.0 release. Use styled(StyledComponent) instead. You can find more information here: https://github.com/styled-components/styled-components/issues/1546');
  });
}

// $FlowFixMe

var BaseStyledComponent = function (_Component) {
  inherits(BaseStyledComponent, _Component);

  function BaseStyledComponent() {
    var _temp, _this, _ret;

    classCallCheck(this, BaseStyledComponent);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.attrs = {}, _this.state = {
      theme: null,
      generatedClassName: ''
    }, _this.unsubscribeId = -1, _temp), possibleConstructorReturn(_this, _ret);
  }

  BaseStyledComponent.prototype.unsubscribeFromContext = function unsubscribeFromContext() {
    if (this.unsubscribeId !== -1) {
      this.context[CHANNEL_NEXT].unsubscribe(this.unsubscribeId);
    }
  };

  BaseStyledComponent.prototype.buildExecutionContext = function buildExecutionContext(theme, props) {
    var attrs = this.constructor.attrs;

    var context = _extends({}, props, { theme: theme });
    if (attrs === undefined) {
      return context;
    }

    this.attrs = Object.keys(attrs).reduce(function (acc, key) {
      var attr = attrs[key];

      // eslint-disable-next-line no-param-reassign
      acc[key] = typeof attr === 'function' && !hasInInheritanceChain(attr, react__WEBPACK_IMPORTED_MODULE_1__["Component"]) ? attr(context) : attr;
      return acc;
    }, {});

    return _extends({}, context, this.attrs);
  };

  BaseStyledComponent.prototype.generateAndInjectStyles = function generateAndInjectStyles(theme, props) {
    var _constructor = this.constructor,
        attrs = _constructor.attrs,
        componentStyle = _constructor.componentStyle,
        warnTooManyClasses = _constructor.warnTooManyClasses;

    var styleSheet = this.context[CONTEXT_KEY] || StyleSheet.master;

    // statically styled-components don't need to build an execution context object,
    // and shouldn't be increasing the number of class names
    if (componentStyle.isStatic && attrs === undefined) {
      return componentStyle.generateAndInjectStyles(STATIC_EXECUTION_CONTEXT, styleSheet);
    } else {
      var executionContext = this.buildExecutionContext(theme, props);
      var className = componentStyle.generateAndInjectStyles(executionContext, styleSheet);

      if ("development" !== 'production' && warnTooManyClasses !== undefined) {
        warnTooManyClasses(className);
      }

      return className;
    }
  };

  BaseStyledComponent.prototype.componentWillMount = function componentWillMount() {
    var _this2 = this;

    var componentStyle = this.constructor.componentStyle;

    var styledContext = this.context[CHANNEL_NEXT];

    // If this is a statically-styled component, we don't need to the theme
    // to generate or build styles.
    if (componentStyle.isStatic) {
      var generatedClassName = this.generateAndInjectStyles(STATIC_EXECUTION_CONTEXT, this.props);
      this.setState({ generatedClassName: generatedClassName });
      // If there is a theme in the context, subscribe to the event emitter. This
      // is necessary due to pure components blocking context updates, this circumvents
      // that by updating when an event is emitted
    } else if (styledContext !== undefined) {
      var subscribe = styledContext.subscribe;

      this.unsubscribeId = subscribe(function (nextTheme) {
        // This will be called once immediately
        var theme = determineTheme(_this2.props, nextTheme, _this2.constructor.defaultProps);

        var generatedClassName = _this2.generateAndInjectStyles(theme, _this2.props);

        _this2.setState({ theme: theme, generatedClassName: generatedClassName });
      });
    } else {
      // eslint-disable-next-line react/prop-types
      var theme = this.props.theme || EMPTY_OBJECT;
      var _generatedClassName = this.generateAndInjectStyles(theme, this.props);
      this.setState({ theme: theme, generatedClassName: _generatedClassName });
    }
  };

  BaseStyledComponent.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
    var _this3 = this;

    // If this is a statically-styled component, we don't need to listen to
    // props changes to update styles
    var componentStyle = this.constructor.componentStyle;

    if (componentStyle.isStatic) {
      return;
    }

    this.setState(function (prevState) {
      var theme = determineTheme(nextProps, prevState.theme, _this3.constructor.defaultProps);
      var generatedClassName = _this3.generateAndInjectStyles(theme, nextProps);

      return { theme: theme, generatedClassName: generatedClassName };
    });
  };

  BaseStyledComponent.prototype.componentWillUnmount = function componentWillUnmount() {
    this.unsubscribeFromContext();
  };

  BaseStyledComponent.prototype.render = function render() {
    // eslint-disable-next-line react/prop-types
    var innerRef = this.props.innerRef;
    var generatedClassName = this.state.generatedClassName;
    var _constructor2 = this.constructor,
        styledComponentId = _constructor2.styledComponentId,
        target = _constructor2.target;


    var isTargetTag = isTag(target);

    var className = [
    // eslint-disable-next-line react/prop-types
    this.props.className, styledComponentId, this.attrs.className, generatedClassName].filter(Boolean).join(' ');

    var baseProps = _extends({}, this.attrs, {
      className: className
    });

    if (isStyledComponent(target)) {
      baseProps.innerRef = innerRef;
    } else {
      baseProps.ref = innerRef;
    }

    var propsForElement = baseProps;
    var key = void 0;

    for (key in this.props) {
      // Don't pass through non HTML tags through to HTML elements
      // always omit innerRef
      if (key !== 'innerRef' && key !== 'className' && (!isTargetTag || validAttr(key))) {
        propsForElement[key] = key === 'style' && key in this.attrs ? _extends({}, this.attrs[key], this.props[key]) : this.props[key];
      }
    }

    return Object(react__WEBPACK_IMPORTED_MODULE_1__["createElement"])(target, propsForElement);
  };

  return BaseStyledComponent;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]);

var _StyledComponent = (function (ComponentStyle, constructWithOptions) {
  var createStyledComponent = function createStyledComponent(target, options, rules) {
    var _options$isClass = options.isClass,
        isClass = _options$isClass === undefined ? !isTag(target) : _options$isClass,
        _options$displayName = options.displayName,
        displayName = _options$displayName === undefined ? generateDisplayName(target) : _options$displayName,
        _options$componentId = options.componentId,
        componentId = _options$componentId === undefined ? generateId(ComponentStyle, options.displayName, options.parentComponentId) : _options$componentId,
        _options$ParentCompon = options.ParentComponent,
        ParentComponent = _options$ParentCompon === undefined ? BaseStyledComponent : _options$ParentCompon,
        extendingRules = options.rules,
        attrs = options.attrs;


    var styledComponentId = options.displayName && options.componentId ? escape(options.displayName) + '-' + options.componentId : options.componentId || componentId;

    var componentStyle = new ComponentStyle(extendingRules === undefined ? rules : extendingRules.concat(rules), attrs, styledComponentId);

    var StyledComponent = function (_ParentComponent) {
      inherits(StyledComponent, _ParentComponent);

      function StyledComponent() {
        classCallCheck(this, StyledComponent);
        return possibleConstructorReturn(this, _ParentComponent.apply(this, arguments));
      }

      StyledComponent.withComponent = function withComponent(tag) {
        var previousComponentId = options.componentId,
            optionsToCopy = objectWithoutProperties(options, ['componentId']);


        var newComponentId = previousComponentId && previousComponentId + '-' + (isTag(tag) ? tag : escape(getComponentName(tag)));

        var newOptions = _extends({}, optionsToCopy, {
          componentId: newComponentId,
          ParentComponent: StyledComponent
        });

        return createStyledComponent(tag, newOptions, rules);
      };

      createClass(StyledComponent, null, [{
        key: 'extend',
        get: function get$$1() {
          var rulesFromOptions = options.rules,
              parentComponentId = options.componentId,
              optionsToCopy = objectWithoutProperties(options, ['rules', 'componentId']);


          var newRules = rulesFromOptions === undefined ? rules : rulesFromOptions.concat(rules);

          var newOptions = _extends({}, optionsToCopy, {
            rules: newRules,
            parentComponentId: parentComponentId,
            ParentComponent: StyledComponent
          });

          warnExtendDeprecated();

          return constructWithOptions(createStyledComponent, target, newOptions);
        }
      }]);
      return StyledComponent;
    }(ParentComponent);

    StyledComponent.attrs = attrs;
    StyledComponent.componentStyle = componentStyle;
    StyledComponent.contextTypes = modifiedContextShape;
    StyledComponent.displayName = displayName;
    StyledComponent.styledComponentId = styledComponentId;
    StyledComponent.target = target;


    if (true) {
      StyledComponent.warnTooManyClasses = createWarnTooManyClasses(displayName);
    }

    if (isClass) {
      hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_5___default()(StyledComponent, target, {
        // all SC-specific things should not be hoisted
        attrs: true,
        componentStyle: true,
        displayName: true,
        extend: true,
        styledComponentId: true,
        target: true,
        warnTooManyClasses: true,
        withComponent: true
      });
    }

    return StyledComponent;
  };

  return createStyledComponent;
});

// Source: https://github.com/garycourt/murmurhash-js/blob/master/murmurhash2_gc.js
function murmurhash(str) {
  var l = str.length | 0,
      h = l | 0,
      i = 0,
      k;

  while (l >= 4) {
    k = str.charCodeAt(i) & 0xff | (str.charCodeAt(++i) & 0xff) << 8 | (str.charCodeAt(++i) & 0xff) << 16 | (str.charCodeAt(++i) & 0xff) << 24;

    k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16);
    k ^= k >>> 24;
    k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16);

    h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16) ^ k;

    l -= 4;
    ++i;
  }

  switch (l) {
    case 3:
      h ^= (str.charCodeAt(i + 2) & 0xff) << 16;
    case 2:
      h ^= (str.charCodeAt(i + 1) & 0xff) << 8;
    case 1:
      h ^= str.charCodeAt(i) & 0xff;
      h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16);
  }

  h ^= h >>> 13;
  h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16);
  h ^= h >>> 15;

  return h >>> 0;
}

// 

var areStylesCacheable = IS_BROWSER;

var isStaticRules = function isStaticRules(rules, attrs) {
  for (var i = 0, len = rules.length; i < len; i += 1) {
    var rule = rules[i];

    // recursive case
    if (Array.isArray(rule) && !isStaticRules(rule)) {
      return false;
    } else if (typeof rule === 'function' && !isStyledComponent(rule)) {
      // functions are allowed to be static if they're just being
      // used to get the classname of a nested styled component
      return false;
    }
  }

  if (attrs !== undefined) {
    // eslint-disable-next-line guard-for-in, no-restricted-syntax
    for (var key in attrs) {
      if (typeof attrs[key] === 'function') {
        return false;
      }
    }
  }

  return true;
};

var isHMREnabled = typeof module !== 'undefined' && module.hot && "development" !== 'production';

/*
 ComponentStyle is all the CSS-specific stuff, not
 the React-specific stuff.
 */
var _ComponentStyle = (function (nameGenerator, flatten, stringifyRules) {
  /* combines hashStr (murmurhash) and nameGenerator for convenience */
  var generateRuleHash = function generateRuleHash(str) {
    return nameGenerator(murmurhash(str));
  };

  var ComponentStyle = function () {
    function ComponentStyle(rules, attrs, componentId) {
      classCallCheck(this, ComponentStyle);

      this.rules = rules;
      this.isStatic = !isHMREnabled && isStaticRules(rules, attrs);
      this.componentId = componentId;

      if (!StyleSheet.master.hasId(componentId)) {
        var placeholder =  true ? ['.' + componentId + ' {}'] : undefined;

        StyleSheet.master.deferredInject(componentId, placeholder);
      }
    }

    /*
     * Flattens a rule set into valid CSS
     * Hashes it, wraps the whole chunk in a .hash1234 {}
     * Returns the hash to be injected on render()
     * */


    ComponentStyle.prototype.generateAndInjectStyles = function generateAndInjectStyles(executionContext, styleSheet) {
      var isStatic = this.isStatic,
          componentId = this.componentId,
          lastClassName = this.lastClassName;

      if (areStylesCacheable && isStatic && lastClassName !== undefined && styleSheet.hasNameForId(componentId, lastClassName)) {
        return lastClassName;
      }

      var flatCSS = flatten(this.rules, executionContext);
      var name = generateRuleHash(this.componentId + flatCSS.join(''));

      if (!styleSheet.hasNameForId(componentId, name)) {
        styleSheet.inject(this.componentId, stringifyRules(flatCSS, '.' + name), name);
      }

      this.lastClassName = name;
      return name;
    };

    ComponentStyle.generateName = function generateName(str) {
      return generateRuleHash(str);
    };

    return ComponentStyle;
  }();

  return ComponentStyle;
});

// 
// Thanks to ReactDOMFactories for this handy list!

var domElements = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr',

// SVG
'circle', 'clipPath', 'defs', 'ellipse', 'foreignObject', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan'];

// 

var _styled = (function (styledComponent, constructWithOptions) {
  var styled = function styled(tag) {
    return constructWithOptions(styledComponent, tag);
  };

  // Shorthands for all valid HTML Elements
  domElements.forEach(function (domElement) {
    styled[domElement] = styled(domElement);
  });

  return styled;
});

// 

var replaceWhitespace = function replaceWhitespace(str) {
  return str.replace(/\s|\\n/g, '');
};

var _keyframes = (function (nameGenerator, stringifyRules, css) {
  return function () {
    var styleSheet = StyleSheet.master;
    var rules = css.apply(undefined, arguments);
    var name = nameGenerator(murmurhash(replaceWhitespace(JSON.stringify(rules))));
    var id = 'sc-keyframes-' + name;

    if (!styleSheet.hasNameForId(id, name)) {
      styleSheet.inject(id, stringifyRules(rules, name, '@keyframes'), name);
    }

    return name;
  };
});

// 

var _injectGlobal = (function (stringifyRules, css) {
  var injectGlobal = function injectGlobal() {
    var styleSheet = StyleSheet.master;
    var rules = css.apply(undefined, arguments);
    var hash = murmurhash(JSON.stringify(rules));
    var id = 'sc-global-' + hash;

    if (!styleSheet.hasId(id)) {
      styleSheet.inject(id, stringifyRules(rules));
    }
  };

  return injectGlobal;
});

// 

var _constructWithOptions = (function (css) {
  var constructWithOptions = function constructWithOptions(componentConstructor, tag) {
    var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : EMPTY_OBJECT;

    if (!Object(react_is__WEBPACK_IMPORTED_MODULE_6__["isValidElementType"])(tag)) {
      throw new StyledComponentsError(1, String(tag));
    }

    /* This is callable directly as a template function */
    // $FlowFixMe: Not typed to avoid destructuring arguments
    var templateFunction = function templateFunction() {
      return componentConstructor(tag, options, css.apply(undefined, arguments));
    };

    /* If config methods are called, wrap up a new template function and merge options */
    templateFunction.withConfig = function (config) {
      return constructWithOptions(componentConstructor, tag, _extends({}, options, config));
    };
    templateFunction.attrs = function (attrs) {
      return constructWithOptions(componentConstructor, tag, _extends({}, options, {
        attrs: _extends({}, options.attrs || EMPTY_OBJECT, attrs)
      }));
    };

    return templateFunction;
  };

  return constructWithOptions;
});

// 

var withTheme = (function (Component$$1) {
  var isStatelessFunctionalComponent = typeof Component$$1 === 'function' &&
  // $FlowFixMe TODO: flow for prototype
  !(Component$$1.prototype && 'isReactComponent' in Component$$1.prototype);

  // NOTE: We can't pass a ref to a stateless functional component
  var shouldSetInnerRef = isStyledComponent(Component$$1) || isStatelessFunctionalComponent;

  var WithTheme = function (_React$Component) {
    inherits(WithTheme, _React$Component);

    function WithTheme() {
      var _temp, _this, _ret;

      classCallCheck(this, WithTheme);

      for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      return _ret = (_temp = (_this = possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = EMPTY_OBJECT, _this.unsubscribeId = -1, _temp), possibleConstructorReturn(_this, _ret);
    }

    // NOTE: This is so that isStyledComponent passes for the innerRef unwrapping


    WithTheme.prototype.componentWillMount = function componentWillMount() {
      var _this2 = this;

      var defaultProps = this.constructor.defaultProps;

      var styledContext = this.context[CHANNEL_NEXT];
      var themeProp = determineTheme(this.props, undefined, defaultProps);
      if (styledContext === undefined && themeProp === undefined && "development" !== 'production') {
        // eslint-disable-next-line no-console
        console.warn('[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps');
      } else if (styledContext === undefined && themeProp !== undefined) {
        this.setState({ theme: themeProp });
      } else {
        var subscribe = styledContext.subscribe;

        this.unsubscribeId = subscribe(function (nextTheme) {
          var theme = determineTheme(_this2.props, nextTheme, defaultProps);
          _this2.setState({ theme: theme });
        });
      }
    };

    WithTheme.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
      var defaultProps = this.constructor.defaultProps;

      this.setState(function (oldState) {
        var theme = determineTheme(nextProps, oldState.theme, defaultProps);

        return { theme: theme };
      });
    };

    WithTheme.prototype.componentWillUnmount = function componentWillUnmount() {
      if (this.unsubscribeId !== -1) {
        this.context[CHANNEL_NEXT].unsubscribe(this.unsubscribeId);
      }
    };

    WithTheme.prototype.render = function render() {
      var props = _extends({
        theme: this.state.theme
      }, this.props);

      if (!shouldSetInnerRef) {
        props.ref = props.innerRef;
        delete props.innerRef;
      }

      return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(Component$$1, props);
    };

    return WithTheme;
  }(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component);

  WithTheme.contextTypes = contextShape;
  WithTheme.displayName = 'WithTheme(' + getComponentName(Component$$1) + ')';
  WithTheme.styledComponentId = 'withTheme';


  return hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_5___default()(WithTheme, Component$$1);
});

// 

/* eslint-disable */
var __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS = {
  StyleSheet: StyleSheet
};

// 

/* Warning if you've imported this file on React Native */
if ("development" !== 'production' && typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {
  // eslint-disable-next-line no-console
  console.warn("It looks like you've imported 'styled-components' on React Native.\n" + "Perhaps you're looking to import 'styled-components/native'?\n" + 'Read more about this at https://www.styled-components.com/docs/basics#react-native');
}

/* Warning if there are several instances of styled-components */
if ("development" !== 'production' && "development" !== 'test' && typeof window !== 'undefined' && typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Node.js') === -1 && navigator.userAgent.indexOf('jsdom') === -1) {
  window['__styled-components-init__'] = window['__styled-components-init__'] || 0;

  if (window['__styled-components-init__'] === 1) {
    // eslint-disable-next-line no-console
    console.warn("It looks like there are several instances of 'styled-components' initialized in this application. " + 'This may cause dynamic styles not rendering properly, errors happening during rehydration process ' + 'and makes your application bigger without a good reason.\n\n' + 'See https://s-c.sh/2BAXzed for more info.');
  }

  window['__styled-components-init__'] += 1;
}

/* Instantiate singletons */
var ComponentStyle = _ComponentStyle(generateAlphabeticName, flatten, stringifyRules);
var constructWithOptions = _constructWithOptions(css);
var StyledComponent = _StyledComponent(ComponentStyle, constructWithOptions);

/* Instantiate exported singletons */
var keyframes = _keyframes(generateAlphabeticName, stringifyRules, css);
var injectGlobal = _injectGlobal(stringifyRules, css);
var styled = _styled(StyledComponent, constructWithOptions);

/* harmony default export */ __webpack_exports__["default"] = (styled);

//# sourceMappingURL=styled-components.browser.esm.js.map

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ "8oxB"), __webpack_require__(/*! ./../../webpack/buildin/harmony-module.js */ "3UD+")(module)))

/***/ }),

/***/ "vR7t":
/*!***********************************************************!*\
  !*** ./node_modules/@nteract/transform-vdom/lib/index.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _cloneDeep2 = __webpack_require__(/*! lodash/cloneDeep */ "BkRI");

var _cloneDeep3 = _interopRequireDefault(_cloneDeep2);

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _objectToReact = __webpack_require__(/*! ./object-to-react */ "yNAP");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var VDOM = function (_React$Component) {
  _inherits(VDOM, _React$Component);

  function VDOM() {
    _classCallCheck(this, VDOM);

    return _possibleConstructorReturn(this, (VDOM.__proto__ || Object.getPrototypeOf(VDOM)).apply(this, arguments));
  }

  _createClass(VDOM, [{
    key: "shouldComponentUpdate",
    value: function shouldComponentUpdate(nextProps) {
      return nextProps.data !== this.props.data;
    }
  }, {
    key: "render",
    value: function render() {
      try {
        // objectToReactElement is mutatitve so we'll clone our object
        var obj = (0, _cloneDeep3.default)(this.props.data);
        return (0, _objectToReact.objectToReactElement)(obj);
      } catch (err) {
        return _react2.default.createElement(
          "div",
          null,
          _react2.default.createElement(
            "pre",
            null,
            "There was an error rendering VDOM data from the kernel or notebook"
          ),
          _react2.default.createElement(
            "code",
            null,
            JSON.stringify(err, null, 2)
          )
        );
      }
    }
  }]);

  return VDOM;
}(_react2.default.Component);

VDOM.MIMETYPE = "application/vdom.v1+json";
exports.default = VDOM;

/***/ }),

/***/ "vRxK":
/*!**************************************************!*\
  !*** ./node_modules/mdi-react/GooglePlusIcon.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var GooglePlusIcon = function GooglePlusIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M23,11H21V9H19V11H17V13H19V15H21V13H23M8,11V13.4H12C11.8,14.4 10.8,16.4 8,16.4C5.6,16.4 3.7,14.4 3.7,12C3.7,9.6 5.6,7.6 8,7.6C9.4,7.6 10.3,8.2 10.8,8.7L12.7,6.9C11.5,5.7 9.9,5 8,5C4.1,5 1,8.1 1,12C1,15.9 4.1,19 8,19C12,19 14.7,16.2 14.7,12.2C14.7,11.7 14.7,11.4 14.6,11H8Z' })
  );
};

module.exports = GooglePlusIcon;


/***/ }),

/***/ "vS4K":
/*!*******************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/AxesFold.js ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _AxesSelector = __webpack_require__(/*! ../fields/AxesSelector */ "rVQt");

var _AxesSelector2 = _interopRequireDefault(_AxesSelector);

var _PlotlyFold = __webpack_require__(/*! ./PlotlyFold */ "mQPs");

var _PlotlyFold2 = _interopRequireDefault(_PlotlyFold);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var AxesFold = function (_Component) {
  _inherits(AxesFold, _Component);

  function AxesFold() {
    _classCallCheck(this, AxesFold);

    return _possibleConstructorReturn(this, (AxesFold.__proto__ || Object.getPrototypeOf(AxesFold)).apply(this, arguments));
  }

  _createClass(AxesFold, [{
    key: 'render',
    value: function render() {
      var _props = this.props,
          children = _props.children,
          options = _props.options;

      return options.length && children ? _react2.default.createElement(
        _PlotlyFold2.default,
        this.props,
        options.length === 1 ? null : _react2.default.createElement(_AxesSelector2.default, { axesOptions: options }),
        children
      ) : null;
    }
  }]);

  return AxesFold;
}(_react.Component);

AxesFold.propTypes = {
  children: _propTypes2.default.any,
  options: _propTypes2.default.array
};

AxesFold.plotly_editor_traits = { foldable: true };

exports.default = (0, _lib.connectAxesToLayout)(AxesFold);
//# sourceMappingURL=AxesFold.js.map

/***/ }),

/***/ "vVvC":
/*!**************************************************!*\
  !*** ./node_modules/ajv/lib/dotjs/properties.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_properties(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $key = 'key' + $lvl,
    $idx = 'idx' + $lvl,
    $dataNxt = $it.dataLevel = it.dataLevel + 1,
    $nextData = 'data' + $dataNxt,
    $dataProperties = 'dataProperties' + $lvl;
  var $schemaKeys = Object.keys($schema || {}),
    $pProperties = it.schema.patternProperties || {},
    $pPropertyKeys = Object.keys($pProperties),
    $aProperties = it.schema.additionalProperties,
    $someProperties = $schemaKeys.length || $pPropertyKeys.length,
    $noAdditional = $aProperties === false,
    $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length,
    $removeAdditional = it.opts.removeAdditional,
    $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional,
    $ownProperties = it.opts.ownProperties,
    $currentBaseId = it.baseId;
  var $required = it.schema.required;
  if ($required && !(it.opts.v5 && $required.$data) && $required.length < it.opts.loopRequired) var $requiredHash = it.util.toHash($required);
  if (it.opts.patternGroups) {
    var $pgProperties = it.schema.patternGroups || {},
      $pgPropertyKeys = Object.keys($pgProperties);
  }
  out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;';
  if ($ownProperties) {
    out += ' var ' + ($dataProperties) + ' = undefined;';
  }
  if ($checkAdditional) {
    if ($ownProperties) {
      out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
    } else {
      out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
    }
    if ($someProperties) {
      out += ' var isAdditional' + ($lvl) + ' = !(false ';
      if ($schemaKeys.length) {
        if ($schemaKeys.length > 5) {
          out += ' || validate.schema' + ($schemaPath) + '[' + ($key) + '] ';
        } else {
          var arr1 = $schemaKeys;
          if (arr1) {
            var $propertyKey, i1 = -1,
              l1 = arr1.length - 1;
            while (i1 < l1) {
              $propertyKey = arr1[i1 += 1];
              out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' ';
            }
          }
        }
      }
      if ($pPropertyKeys.length) {
        var arr2 = $pPropertyKeys;
        if (arr2) {
          var $pProperty, $i = -1,
            l2 = arr2.length - 1;
          while ($i < l2) {
            $pProperty = arr2[$i += 1];
            out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') ';
          }
        }
      }
      if (it.opts.patternGroups && $pgPropertyKeys.length) {
        var arr3 = $pgPropertyKeys;
        if (arr3) {
          var $pgProperty, $i = -1,
            l3 = arr3.length - 1;
          while ($i < l3) {
            $pgProperty = arr3[$i += 1];
            out += ' || ' + (it.usePattern($pgProperty)) + '.test(' + ($key) + ') ';
          }
        }
      }
      out += ' ); if (isAdditional' + ($lvl) + ') { ';
    }
    if ($removeAdditional == 'all') {
      out += ' delete ' + ($data) + '[' + ($key) + ']; ';
    } else {
      var $currentErrorPath = it.errorPath;
      var $additionalProperty = '\' + ' + $key + ' + \'';
      if (it.opts._errorDataPathProperty) {
        it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
      }
      if ($noAdditional) {
        if ($removeAdditional) {
          out += ' delete ' + ($data) + '[' + ($key) + ']; ';
        } else {
          out += ' ' + ($nextValid) + ' = false; ';
          var $currErrSchemaPath = $errSchemaPath;
          $errSchemaPath = it.errSchemaPath + '/additionalProperties';
          var $$outStack = $$outStack || [];
          $$outStack.push(out);
          out = ''; /* istanbul ignore else */
          if (it.createErrors !== false) {
            out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } ';
            if (it.opts.messages !== false) {
              out += ' , message: \'should NOT have additional properties\' ';
            }
            if (it.opts.verbose) {
              out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
            }
            out += ' } ';
          } else {
            out += ' {} ';
          }
          var __err = out;
          out = $$outStack.pop();
          if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
            if (it.async) {
              out += ' throw new ValidationError([' + (__err) + ']); ';
            } else {
              out += ' validate.errors = [' + (__err) + ']; return false; ';
            }
          } else {
            out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
          }
          $errSchemaPath = $currErrSchemaPath;
          if ($breakOnError) {
            out += ' break; ';
          }
        }
      } else if ($additionalIsSchema) {
        if ($removeAdditional == 'failing') {
          out += ' var ' + ($errs) + ' = errors;  ';
          var $wasComposite = it.compositeRule;
          it.compositeRule = $it.compositeRule = true;
          $it.schema = $aProperties;
          $it.schemaPath = it.schemaPath + '.additionalProperties';
          $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
          $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
          var $passData = $data + '[' + $key + ']';
          $it.dataPathArr[$dataNxt] = $key;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
          } else {
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
          }
          out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; }  ';
          it.compositeRule = $it.compositeRule = $wasComposite;
        } else {
          $it.schema = $aProperties;
          $it.schemaPath = it.schemaPath + '.additionalProperties';
          $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
          $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
          var $passData = $data + '[' + $key + ']';
          $it.dataPathArr[$dataNxt] = $key;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
          } else {
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
          }
          if ($breakOnError) {
            out += ' if (!' + ($nextValid) + ') break; ';
          }
        }
      }
      it.errorPath = $currentErrorPath;
    }
    if ($someProperties) {
      out += ' } ';
    }
    out += ' }  ';
    if ($breakOnError) {
      out += ' if (' + ($nextValid) + ') { ';
      $closingBraces += '}';
    }
  }
  var $useDefaults = it.opts.useDefaults && !it.compositeRule;
  if ($schemaKeys.length) {
    var arr4 = $schemaKeys;
    if (arr4) {
      var $propertyKey, i4 = -1,
        l4 = arr4.length - 1;
      while (i4 < l4) {
        $propertyKey = arr4[i4 += 1];
        var $sch = $schema[$propertyKey];
        if (it.util.schemaHasRules($sch, it.RULES.all)) {
          var $prop = it.util.getProperty($propertyKey),
            $passData = $data + $prop,
            $hasDefault = $useDefaults && $sch.default !== undefined;
          $it.schema = $sch;
          $it.schemaPath = $schemaPath + $prop;
          $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey);
          $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers);
          $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey);
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            $code = it.util.varReplace($code, $nextData, $passData);
            var $useData = $passData;
          } else {
            var $useData = $nextData;
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ';
          }
          if ($hasDefault) {
            out += ' ' + ($code) + ' ';
          } else {
            if ($requiredHash && $requiredHash[$propertyKey]) {
              out += ' if ( ' + ($useData) + ' === undefined ';
              if ($ownProperties) {
                out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
              }
              out += ') { ' + ($nextValid) + ' = false; ';
              var $currentErrorPath = it.errorPath,
                $currErrSchemaPath = $errSchemaPath,
                $missingProperty = it.util.escapeQuotes($propertyKey);
              if (it.opts._errorDataPathProperty) {
                it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
              }
              $errSchemaPath = it.errSchemaPath + '/required';
              var $$outStack = $$outStack || [];
              $$outStack.push(out);
              out = ''; /* istanbul ignore else */
              if (it.createErrors !== false) {
                out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
                if (it.opts.messages !== false) {
                  out += ' , message: \'';
                  if (it.opts._errorDataPathProperty) {
                    out += 'is a required property';
                  } else {
                    out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
                  }
                  out += '\' ';
                }
                if (it.opts.verbose) {
                  out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                }
                out += ' } ';
              } else {
                out += ' {} ';
              }
              var __err = out;
              out = $$outStack.pop();
              if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                if (it.async) {
                  out += ' throw new ValidationError([' + (__err) + ']); ';
                } else {
                  out += ' validate.errors = [' + (__err) + ']; return false; ';
                }
              } else {
                out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
              }
              $errSchemaPath = $currErrSchemaPath;
              it.errorPath = $currentErrorPath;
              out += ' } else { ';
            } else {
              if ($breakOnError) {
                out += ' if ( ' + ($useData) + ' === undefined ';
                if ($ownProperties) {
                  out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
                }
                out += ') { ' + ($nextValid) + ' = true; } else { ';
              } else {
                out += ' if (' + ($useData) + ' !== undefined ';
                if ($ownProperties) {
                  out += ' &&   Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
                }
                out += ' ) { ';
              }
            }
            out += ' ' + ($code) + ' } ';
          }
        }
        if ($breakOnError) {
          out += ' if (' + ($nextValid) + ') { ';
          $closingBraces += '}';
        }
      }
    }
  }
  if ($pPropertyKeys.length) {
    var arr5 = $pPropertyKeys;
    if (arr5) {
      var $pProperty, i5 = -1,
        l5 = arr5.length - 1;
      while (i5 < l5) {
        $pProperty = arr5[i5 += 1];
        var $sch = $pProperties[$pProperty];
        if (it.util.schemaHasRules($sch, it.RULES.all)) {
          $it.schema = $sch;
          $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty);
          $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty);
          if ($ownProperties) {
            out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
          } else {
            out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
          }
          out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { ';
          $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
          var $passData = $data + '[' + $key + ']';
          $it.dataPathArr[$dataNxt] = $key;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
          } else {
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
          }
          if ($breakOnError) {
            out += ' if (!' + ($nextValid) + ') break; ';
          }
          out += ' } ';
          if ($breakOnError) {
            out += ' else ' + ($nextValid) + ' = true; ';
          }
          out += ' }  ';
          if ($breakOnError) {
            out += ' if (' + ($nextValid) + ') { ';
            $closingBraces += '}';
          }
        }
      }
    }
  }
  if (it.opts.patternGroups && $pgPropertyKeys.length) {
    var arr6 = $pgPropertyKeys;
    if (arr6) {
      var $pgProperty, i6 = -1,
        l6 = arr6.length - 1;
      while (i6 < l6) {
        $pgProperty = arr6[i6 += 1];
        var $pgSchema = $pgProperties[$pgProperty],
          $sch = $pgSchema.schema;
        if (it.util.schemaHasRules($sch, it.RULES.all)) {
          $it.schema = $sch;
          $it.schemaPath = it.schemaPath + '.patternGroups' + it.util.getProperty($pgProperty) + '.schema';
          $it.errSchemaPath = it.errSchemaPath + '/patternGroups/' + it.util.escapeFragment($pgProperty) + '/schema';
          out += ' var pgPropCount' + ($lvl) + ' = 0;  ';
          if ($ownProperties) {
            out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
          } else {
            out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
          }
          out += ' if (' + (it.usePattern($pgProperty)) + '.test(' + ($key) + ')) { pgPropCount' + ($lvl) + '++; ';
          $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
          var $passData = $data + '[' + $key + ']';
          $it.dataPathArr[$dataNxt] = $key;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
          } else {
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
          }
          if ($breakOnError) {
            out += ' if (!' + ($nextValid) + ') break; ';
          }
          out += ' } ';
          if ($breakOnError) {
            out += ' else ' + ($nextValid) + ' = true; ';
          }
          out += ' }  ';
          if ($breakOnError) {
            out += ' if (' + ($nextValid) + ') { ';
            $closingBraces += '}';
          }
          var $pgMin = $pgSchema.minimum,
            $pgMax = $pgSchema.maximum;
          if ($pgMin !== undefined || $pgMax !== undefined) {
            out += ' var ' + ($valid) + ' = true; ';
            var $currErrSchemaPath = $errSchemaPath;
            if ($pgMin !== undefined) {
              var $limit = $pgMin,
                $reason = 'minimum',
                $moreOrLess = 'less';
              out += ' ' + ($valid) + ' = pgPropCount' + ($lvl) + ' >= ' + ($pgMin) + '; ';
              $errSchemaPath = it.errSchemaPath + '/patternGroups/minimum';
              out += '  if (!' + ($valid) + ') {   ';
              var $$outStack = $$outStack || [];
              $$outStack.push(out);
              out = ''; /* istanbul ignore else */
              if (it.createErrors !== false) {
                out += ' { keyword: \'' + ('patternGroups') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { reason: \'' + ($reason) + '\', limit: ' + ($limit) + ', pattern: \'' + (it.util.escapeQuotes($pgProperty)) + '\' } ';
                if (it.opts.messages !== false) {
                  out += ' , message: \'should NOT have ' + ($moreOrLess) + ' than ' + ($limit) + ' properties matching pattern "' + (it.util.escapeQuotes($pgProperty)) + '"\' ';
                }
                if (it.opts.verbose) {
                  out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                }
                out += ' } ';
              } else {
                out += ' {} ';
              }
              var __err = out;
              out = $$outStack.pop();
              if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                if (it.async) {
                  out += ' throw new ValidationError([' + (__err) + ']); ';
                } else {
                  out += ' validate.errors = [' + (__err) + ']; return false; ';
                }
              } else {
                out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
              }
              out += ' } ';
              if ($pgMax !== undefined) {
                out += ' else ';
              }
            }
            if ($pgMax !== undefined) {
              var $limit = $pgMax,
                $reason = 'maximum',
                $moreOrLess = 'more';
              out += ' ' + ($valid) + ' = pgPropCount' + ($lvl) + ' <= ' + ($pgMax) + '; ';
              $errSchemaPath = it.errSchemaPath + '/patternGroups/maximum';
              out += '  if (!' + ($valid) + ') {   ';
              var $$outStack = $$outStack || [];
              $$outStack.push(out);
              out = ''; /* istanbul ignore else */
              if (it.createErrors !== false) {
                out += ' { keyword: \'' + ('patternGroups') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { reason: \'' + ($reason) + '\', limit: ' + ($limit) + ', pattern: \'' + (it.util.escapeQuotes($pgProperty)) + '\' } ';
                if (it.opts.messages !== false) {
                  out += ' , message: \'should NOT have ' + ($moreOrLess) + ' than ' + ($limit) + ' properties matching pattern "' + (it.util.escapeQuotes($pgProperty)) + '"\' ';
                }
                if (it.opts.verbose) {
                  out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                }
                out += ' } ';
              } else {
                out += ' {} ';
              }
              var __err = out;
              out = $$outStack.pop();
              if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                if (it.async) {
                  out += ' throw new ValidationError([' + (__err) + ']); ';
                } else {
                  out += ' validate.errors = [' + (__err) + ']; return false; ';
                }
              } else {
                out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
              }
              out += ' } ';
            }
            $errSchemaPath = $currErrSchemaPath;
            if ($breakOnError) {
              out += ' if (' + ($valid) + ') { ';
              $closingBraces += '}';
            }
          }
        }
      }
    }
  }
  if ($breakOnError) {
    out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
  }
  out = it.util.cleanUpCode(out);
  return out;
}


/***/ }),

/***/ "vWBD":
/*!*****************************************************************!*\
  !*** ./node_modules/@jupyterlab/json-extension/style/index.css ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "Rfbk");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "vX2W":
/*!******************************************************!*\
  !*** ./node_modules/htmlparser2/lib/ProxyHandler.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = ProxyHandler;

function ProxyHandler(cbs) {
    this._cbs = cbs || {};
}

var EVENTS = __webpack_require__(/*! ./ */ "hS6j").EVENTS;
Object.keys(EVENTS).forEach(function(name) {
    if (EVENTS[name] === 0) {
        name = "on" + name;
        ProxyHandler.prototype[name] = function() {
            if (this._cbs[name]) this._cbs[name]();
        };
    } else if (EVENTS[name] === 1) {
        name = "on" + name;
        ProxyHandler.prototype[name] = function(a) {
            if (this._cbs[name]) this._cbs[name](a);
        };
    } else if (EVENTS[name] === 2) {
        name = "on" + name;
        ProxyHandler.prototype[name] = function(a, b) {
            if (this._cbs[name]) this._cbs[name](a, b);
        };
    } else {
        throw Error("wrong number of arguments");
    }
});


/***/ }),

/***/ "vYwu":
/*!****************************************************************!*\
  !*** ./node_modules/draft-js/lib/applyEntityToContentBlock.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule applyEntityToContentBlock
 * @format
 * 
 */



var CharacterMetadata = __webpack_require__(/*! ./CharacterMetadata */ "lFJn");

function applyEntityToContentBlock(contentBlock, start, end, entityKey) {
  var characterList = contentBlock.getCharacterList();
  while (start < end) {
    characterList = characterList.set(start, CharacterMetadata.applyEntity(characterList.get(start), entityKey));
    start++;
  }
  return contentBlock.set('characterList', characterList);
}

module.exports = applyEntityToContentBlock;

/***/ }),

/***/ "vZ2G":
/*!***********************************************!*\
  !*** ./node_modules/browserify-aes/incr32.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

function incr32 (iv) {
  var len = iv.length
  var item
  while (len--) {
    item = iv.readUInt8(len)
    if (item === 255) {
      iv.writeUInt8(0, len)
    } else {
      item++
      iv.writeUInt8(item, len)
      break
    }
  }
}
module.exports = incr32


/***/ }),

/***/ "vcNX":
/*!**************************************************************!*\
  !*** ./node_modules/draft-js/lib/keyCommandBackspaceWord.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule keyCommandBackspaceWord
 * @format
 * 
 */



var DraftRemovableWord = __webpack_require__(/*! ./DraftRemovableWord */ "SF5q");
var EditorState = __webpack_require__(/*! ./EditorState */ "3sOJ");

var moveSelectionBackward = __webpack_require__(/*! ./moveSelectionBackward */ "kWjT");
var removeTextWithStrategy = __webpack_require__(/*! ./removeTextWithStrategy */ "8d//");

/**
 * Delete the word that is left of the cursor, as well as any spaces or
 * punctuation after the word.
 */
function keyCommandBackspaceWord(editorState) {
  var afterRemoval = removeTextWithStrategy(editorState, function (strategyState) {
    var selection = strategyState.getSelection();
    var offset = selection.getStartOffset();
    // If there are no words before the cursor, remove the preceding newline.
    if (offset === 0) {
      return moveSelectionBackward(strategyState, 1);
    }
    var key = selection.getStartKey();
    var content = strategyState.getCurrentContent();
    var text = content.getBlockForKey(key).getText().slice(0, offset);
    var toRemove = DraftRemovableWord.getBackward(text);
    return moveSelectionBackward(strategyState, toRemove.length || 1);
  }, 'backward');

  if (afterRemoval === editorState.getCurrentContent()) {
    return editorState;
  }

  return EditorState.push(editorState, afterRemoval, 'remove-range');
}

module.exports = keyCommandBackspaceWord;

/***/ }),

/***/ "vmI6":
/*!*************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/TraceAccordion.js ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _PlotlyFold = __webpack_require__(/*! ./PlotlyFold */ "mQPs");

var _PlotlyFold2 = _interopRequireDefault(_PlotlyFold);

var _TraceRequiredPanel = __webpack_require__(/*! ./TraceRequiredPanel */ "IBvg");

var _TraceRequiredPanel2 = _interopRequireDefault(_TraceRequiredPanel);

var _PlotlyPanel = __webpack_require__(/*! ./PlotlyPanel */ "54u7");

var _PlotlyPanel2 = _interopRequireDefault(_PlotlyPanel);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _constants = __webpack_require__(/*! ../../lib/constants */ "5Bkx");

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _reactTabs = __webpack_require__(/*! react-tabs */ "GTV5");

var _traceTypes = __webpack_require__(/*! ../../lib/traceTypes */ "M2ap");

var _PanelEmpty = __webpack_require__(/*! ./PanelEmpty */ "o21U");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var TraceFold = (0, _lib.connectTraceToPlot)(_PlotlyFold2.default);

var TraceAccordion = function (_Component) {
  _inherits(TraceAccordion, _Component);

  function TraceAccordion(props, context) {
    _classCallCheck(this, TraceAccordion);

    var _this = _possibleConstructorReturn(this, (TraceAccordion.__proto__ || Object.getPrototypeOf(TraceAccordion)).call(this, props, context));

    _this.setLocals(props, context);
    return _this;
  }

  _createClass(TraceAccordion, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps, nextContext) {
      this.setLocals(nextProps, nextContext);
    }
  }, {
    key: 'setLocals',
    value: function setLocals(props, context) {
      var _this2 = this;

      var base = props.canGroup ? context.fullData : context.data;
      var traceFilterCondition = this.props.traceFilterCondition || function () {
        return true;
      };

      this.filteredTracesDataIndexes = [];
      this.filteredTraces = [];

      if (base && base.length && context.fullData.length) {
        this.filteredTraces = base.filter(function (t, i) {
          var fullTrace = props.canGroup ? t : context.fullData.filter(function (tr) {
            return tr.index === i;
          })[0];

          if (fullTrace) {
            var trace = context.data[fullTrace.index];
            if (traceFilterCondition(trace, fullTrace)) {
              _this2.filteredTracesDataIndexes.push(fullTrace.index);
              return true;
            }
          }

          return false;
        });
      }
    }
  }, {
    key: 'renderGroupedTraceFolds',
    value: function renderGroupedTraceFolds() {
      var _this3 = this;

      if (!this.filteredTraces.length || this.filteredTraces.length <= 1) {
        return null;
      }

      var _ = this.context.localize;

      var dataArrayPositionsByTraceType = {};
      var fullDataArrayPositionsByTraceType = {};

      this.filteredTraces.forEach(function (trace) {
        var traceType = (0, _lib.plotlyTraceToCustomTrace)(trace);
        if (!dataArrayPositionsByTraceType[traceType]) {
          dataArrayPositionsByTraceType[traceType] = [];
        }

        if (!fullDataArrayPositionsByTraceType[traceType]) {
          fullDataArrayPositionsByTraceType[traceType] = [];
        }

        dataArrayPositionsByTraceType[traceType].push(trace.index);
        // _expandedIndex is the trace's index in the fullData array
        fullDataArrayPositionsByTraceType[traceType].push(trace._expandedIndex);
      });

      return Object.keys(fullDataArrayPositionsByTraceType).map(function (type, index) {
        return _react2.default.createElement(
          TraceFold,
          {
            key: index,
            traceIndexes: dataArrayPositionsByTraceType[type],
            name: (0, _traceTypes.traceTypes)(_).find(function (t) {
              return t.value === type;
            }).label,
            fullDataArrayPosition: fullDataArrayPositionsByTraceType[type]
          },
          _this3.props.children
        );
      });
    }
  }, {
    key: 'renderUngroupedTraceFolds',
    value: function renderUngroupedTraceFolds() {
      var _this4 = this;

      if (this.filteredTraces.length) {
        return this.filteredTraces.map(function (d, i) {
          return _react2.default.createElement(
            TraceFold,
            {
              key: i,
              traceIndexes: [d.index],
              canDelete: _this4.props.canAdd,
              fullDataArrayPosition: [d._expandedIndex]
            },
            _this4.props.children
          );
        });
      }
      return null;
    }
  }, {
    key: 'renderTraceFolds',
    value: function renderTraceFolds() {
      var _this5 = this;

      if (this.filteredTraces.length) {
        return this.filteredTraces.map(function (d, i) {
          return _react2.default.createElement(
            TraceFold,
            {
              key: i,
              traceIndexes: [_this5.filteredTracesDataIndexes[i]],
              canDelete: _this5.props.canAdd
            },
            _this5.props.children
          );
        });
      }
      return null;
    }
  }, {
    key: 'renderTracePanelHelp',
    value: function renderTracePanelHelp() {
      var _ = this.context.localize;
      return _react2.default.createElement(
        _PanelEmpty.PanelMessage,
        { heading: _('Trace your data.') },
        _react2.default.createElement(
          'p',
          null,
          _('Traces of various types like bar and line are the building blocks of your figure.')
        ),
        _react2.default.createElement(
          'p',
          null,
          _('You can add as many as you like, mixing and matching types and arranging them into subplots.')
        ),
        _react2.default.createElement(
          'p',
          null,
          _('Click on the + button above to add a trace.')
        )
      );
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          canAdd = _props.canAdd,
          canGroup = _props.canGroup;

      var _ = this.context.localize;

      if (canAdd) {
        var addAction = {
          label: _('Trace'),
          handler: function handler(_ref) {
            var onUpdate = _ref.onUpdate;

            if (onUpdate) {
              onUpdate({
                type: _constants.EDITOR_ACTIONS.ADD_TRACE
              });
            }
          }
        };
        var traceFolds = this.renderTraceFolds();
        return _react2.default.createElement(
          _PlotlyPanel2.default,
          { addAction: addAction },
          traceFolds ? traceFolds : this.renderTracePanelHelp()
        );
      }

      if (canGroup) {
        if (this.filteredTraces.length === 1) {
          return _react2.default.createElement(
            _TraceRequiredPanel2.default,
            null,
            this.renderUngroupedTraceFolds()
          );
        }

        if (this.filteredTraces.length > 1) {
          return _react2.default.createElement(
            _TraceRequiredPanel2.default,
            { noPadding: true },
            _react2.default.createElement(
              _reactTabs.Tabs,
              null,
              _react2.default.createElement(
                _reactTabs.TabList,
                null,
                _react2.default.createElement(
                  _reactTabs.Tab,
                  null,
                  _('Individually')
                ),
                _react2.default.createElement(
                  _reactTabs.Tab,
                  null,
                  _('By Type')
                )
              ),
              _react2.default.createElement(
                _reactTabs.TabPanel,
                null,
                _react2.default.createElement(
                  _PlotlyPanel2.default,
                  null,
                  this.renderUngroupedTraceFolds()
                )
              ),
              _react2.default.createElement(
                _reactTabs.TabPanel,
                null,
                _react2.default.createElement(
                  _PlotlyPanel2.default,
                  null,
                  this.renderGroupedTraceFolds()
                )
              )
            )
          );
        }
      }

      return _react2.default.createElement(
        _TraceRequiredPanel2.default,
        null,
        this.renderTraceFolds()
      );
    }
  }]);

  return TraceAccordion;
}(_react.Component);

TraceAccordion.contextTypes = {
  fullData: _propTypes2.default.array,
  data: _propTypes2.default.array,
  localize: _propTypes2.default.func
};

TraceAccordion.propTypes = {
  canAdd: _propTypes2.default.bool,
  canGroup: _propTypes2.default.bool,
  children: _propTypes2.default.node,
  traceFilterCondition: _propTypes2.default.func
};

exports.default = TraceAccordion;
//# sourceMappingURL=TraceAccordion.js.map

/***/ }),

/***/ "vn1i":
/*!**************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/PieColorscalePicker.js ***!
  \**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _ColorscalePicker = __webpack_require__(/*! ../widgets/ColorscalePicker */ "7/El");

var _ColorscalePicker2 = _interopRequireDefault(_ColorscalePicker);

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UnconnectedPieColorscalePicker = function (_Component) {
  _inherits(UnconnectedPieColorscalePicker, _Component);

  function UnconnectedPieColorscalePicker(props) {
    _classCallCheck(this, UnconnectedPieColorscalePicker);

    var _this = _possibleConstructorReturn(this, (UnconnectedPieColorscalePicker.__proto__ || Object.getPrototypeOf(UnconnectedPieColorscalePicker)).call(this, props));

    _this.onUpdate = _this.onUpdate.bind(_this);
    return _this;
  }

  _createClass(UnconnectedPieColorscalePicker, [{
    key: 'onUpdate',
    value: function onUpdate(colorscale, colorscaleType) {
      if (Array.isArray(colorscale)) {
        var numPieSlices = this.context.graphDiv.calcdata[0].length + 1;
        var adjustedColorscale = (0, _lib.adjustColorscale)(colorscale, numPieSlices, colorscaleType, {
          repeat: true
        });
        this.props.updatePlot(adjustedColorscale);
      }
    }
  }, {
    key: 'render',
    value: function render() {
      var fullValue = this.props.fullValue;

      var colorscale = Array.isArray(fullValue) ? fullValue : null;

      return _react2.default.createElement(
        _Field2.default,
        this.props,
        _react2.default.createElement(_ColorscalePicker2.default, {
          selected: colorscale,
          onColorscaleChange: this.onUpdate,
          initialCategory: 'categorical'
        })
      );
    }
  }]);

  return UnconnectedPieColorscalePicker;
}(_react.Component);

UnconnectedPieColorscalePicker.propTypes = _extends({
  fullValue: _propTypes2.default.any,
  updatePlot: _propTypes2.default.func
}, _Field2.default.propTypes);

UnconnectedPieColorscalePicker.contextTypes = {
  container: _propTypes2.default.object,
  graphDiv: _propTypes2.default.object
};

exports.default = (0, _lib.connectToContainer)(UnconnectedPieColorscalePicker, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    if (context && context.container && context.graphDiv && (!plotProps.fullValue || Array.isArray(plotProps.fullValue) && !plotProps.fullValue.length) && context.graphDiv.calcdata) {
      plotProps.fullValue = context.graphDiv.calcdata[0].map(function (d) {
        return d.color;
      });
    }

    if (context.traceIndexes.length > 1) {
      plotProps.isVisible = false;
    }
  }
});
//# sourceMappingURL=PieColorscalePicker.js.map

/***/ }),

/***/ "vncK":
/*!*******************************************************!*\
  !*** ./node_modules/mdi-react/FormatAlignLeftIcon.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var FormatAlignLeftIcon = function FormatAlignLeftIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M3,3H21V5H3V3M3,7H15V9H3V7M3,11H21V13H3V11M3,15H15V17H3V15M3,19H21V21H3V19Z' })
  );
};

module.exports = FormatAlignLeftIcon;


/***/ }),

/***/ "vvGI":
/*!*******************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/session/validate.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const validate_1 = __webpack_require__(/*! ../kernel/validate */ "idGr");
/**
 * Validate a property as being on an object, and optionally
 * of a given type.
 */
function validateProperty(object, name, typeName) {
    if (!object.hasOwnProperty(name)) {
        throw Error(`Missing property '${name}'`);
    }
    if (typeName !== void 0) {
        let valid = true;
        let value = object[name];
        switch (typeName) {
            case 'array':
                valid = Array.isArray(value);
                break;
            case 'object':
                valid = typeof value !== 'undefined';
                break;
            default:
                valid = typeof value === typeName;
        }
        if (!valid) {
            throw new Error(`Property '${name}' is not of type '${typeName}'`);
        }
    }
}
/**
 * Validate an `Session.IModel` object.
 */
function validateModel(data) {
    let model = {
        id: data.id,
        kernel: data.kernel,
        name: data.name,
        path: data.path,
        type: data.type
    };
    // Support legacy session model.
    if (data.path === undefined && data.notebook !== undefined) {
        model.path = data.notebook.path;
        model.type = 'notebook';
        model.name = '';
    }
    validateProperty(model, 'id', 'string');
    validateProperty(model, 'type', 'string');
    validateProperty(model, 'name', 'string');
    validateProperty(model, 'path', 'string');
    validateProperty(model, 'kernel', 'object');
    validate_1.validateModel(model.kernel);
    return model;
}
exports.validateModel = validateModel;


/***/ }),

/***/ "vwG1":
/*!*********************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/scrollbar.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var domutils_1 = __webpack_require__(/*! @phosphor/domutils */ "XWTc");
var dragdrop_1 = __webpack_require__(/*! @phosphor/dragdrop */ "v7cI");
var signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
var widget_1 = __webpack_require__(/*! ./widget */ "FmDU");
/**
 * A widget which implements a canonical scroll bar.
 */
var ScrollBar = (function (_super) {
    __extends(ScrollBar, _super);
    /**
     * Construct a new scroll bar.
     *
     * @param options - The options for initializing the scroll bar.
     */
    function ScrollBar(options) {
        if (options === void 0) { options = {}; }
        var _this = _super.call(this, { node: Private.createNode() }) || this;
        /**
         * A timeout callback for repeating the mouse press.
         */
        _this._onRepeat = function () {
            // Clear the repeat timer id.
            _this._repeatTimer = -1;
            // Bail if the mouse has been released.
            if (!_this._pressData) {
                return;
            }
            // Look up the part that was pressed.
            var part = _this._pressData.part;
            // Bail if the thumb was pressed.
            if (part === 'thumb') {
                return;
            }
            // Schedule the timer for another repeat.
            _this._repeatTimer = setTimeout(_this._onRepeat, 20);
            // Get the current mouse position.
            var mouseX = _this._pressData.mouseX;
            var mouseY = _this._pressData.mouseY;
            // Handle a decrement button repeat.
            if (part === 'decrement') {
                // Bail if the mouse is not over the button.
                if (!domutils_1.ElementExt.hitTest(_this.decrementNode, mouseX, mouseY)) {
                    return;
                }
                // Emit the step requested signal.
                _this._stepRequested.emit('decrement');
                // Finished.
                return;
            }
            // Handle an increment button repeat.
            if (part === 'increment') {
                // Bail if the mouse is not over the button.
                if (!domutils_1.ElementExt.hitTest(_this.incrementNode, mouseX, mouseY)) {
                    return;
                }
                // Emit the step requested signal.
                _this._stepRequested.emit('increment');
                // Finished.
                return;
            }
            // Handle a track repeat.
            if (part === 'track') {
                // Bail if the mouse is not over the track.
                if (!domutils_1.ElementExt.hitTest(_this.trackNode, mouseX, mouseY)) {
                    return;
                }
                // Fetch the thumb node.
                var thumbNode = _this.thumbNode;
                // Bail if the mouse is over the thumb.
                if (domutils_1.ElementExt.hitTest(thumbNode, mouseX, mouseY)) {
                    return;
                }
                // Fetch the client rect for the thumb.
                var thumbRect = thumbNode.getBoundingClientRect();
                // Determine the direction for the page request.
                var dir = void 0;
                if (_this._orientation === 'horizontal') {
                    dir = mouseX < thumbRect.left ? 'decrement' : 'increment';
                }
                else {
                    dir = mouseY < thumbRect.top ? 'decrement' : 'increment';
                }
                // Emit the page requested signal.
                _this._pageRequested.emit(dir);
                // Finished.
                return;
            }
        };
        _this._value = 0;
        _this._page = 10;
        _this._maximum = 100;
        _this._repeatTimer = -1;
        _this._pressData = null;
        _this._thumbMoved = new signaling_1.Signal(_this);
        _this._stepRequested = new signaling_1.Signal(_this);
        _this._pageRequested = new signaling_1.Signal(_this);
        _this.addClass('p-ScrollBar');
        _this.setFlag(widget_1.Widget.Flag.DisallowLayout);
        // Set the orientation.
        _this._orientation = options.orientation || 'vertical';
        _this.dataset['orientation'] = _this._orientation;
        // Parse the rest of the options.
        if (options.maximum !== undefined) {
            _this._maximum = Math.max(0, options.maximum);
        }
        if (options.page !== undefined) {
            _this._page = Math.max(0, options.page);
        }
        if (options.value !== undefined) {
            _this._value = Math.max(0, Math.min(options.value, _this._maximum));
        }
        return _this;
    }
    Object.defineProperty(ScrollBar.prototype, "thumbMoved", {
        /**
         * A signal emitted when the user moves the scroll thumb.
         *
         * #### Notes
         * The payload is the current value of the scroll bar.
         */
        get: function () {
            return this._thumbMoved;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ScrollBar.prototype, "stepRequested", {
        /**
         * A signal emitted when the user clicks a step button.
         *
         * #### Notes
         * The payload is whether a decrease or increase is requested.
         */
        get: function () {
            return this._stepRequested;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ScrollBar.prototype, "pageRequested", {
        /**
         * A signal emitted when the user clicks the scroll track.
         *
         * #### Notes
         * The payload is whether a decrease or increase is requested.
         */
        get: function () {
            return this._pageRequested;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ScrollBar.prototype, "orientation", {
        /**
         * Get the orientation of the scroll bar.
         */
        get: function () {
            return this._orientation;
        },
        /**
         * Set the orientation of the scroll bar.
         */
        set: function (value) {
            // Do nothing if the orientation does not change.
            if (this._orientation === value) {
                return;
            }
            // Release the mouse before making changes.
            this._releaseMouse();
            // Update the internal orientation.
            this._orientation = value;
            this.dataset['orientation'] = value;
            // Schedule an update the scroll bar.
            this.update();
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ScrollBar.prototype, "value", {
        /**
         * Get the current value of the scroll bar.
         */
        get: function () {
            return this._value;
        },
        /**
         * Set the current value of the scroll bar.
         *
         * #### Notes
         * The value will be clamped to the range `[0, maximum]`.
         */
        set: function (value) {
            // Clamp the value to the allowable range.
            value = Math.max(0, Math.min(value, this._maximum));
            // Do nothing if the value does not change.
            if (this._value === value) {
                return;
            }
            // Update the internal value.
            this._value = value;
            // Schedule an update the scroll bar.
            this.update();
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ScrollBar.prototype, "page", {
        /**
         * Get the page size of the scroll bar.
         *
         * #### Notes
         * The page size is the amount of visible content in the scrolled
         * region, expressed in data units. It determines the size of the
         * scroll bar thumb.
         */
        get: function () {
            return this._page;
        },
        /**
         * Set the page size of the scroll bar.
         *
         * #### Notes
         * The page size will be clamped to the range `[0, Infinity]`.
         */
        set: function (value) {
            // Clamp the page size to the allowable range.
            value = Math.max(0, value);
            // Do nothing if the value does not change.
            if (this._page === value) {
                return;
            }
            // Update the internal page size.
            this._page = value;
            // Schedule an update the scroll bar.
            this.update();
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ScrollBar.prototype, "maximum", {
        /**
         * Get the maximum value of the scroll bar.
         */
        get: function () {
            return this._maximum;
        },
        /**
         * Set the maximum value of the scroll bar.
         *
         * #### Notes
         * The max size will be clamped to the range `[0, Infinity]`.
         */
        set: function (value) {
            // Clamp the value to the allowable range.
            value = Math.max(0, value);
            // Do nothing if the value does not change.
            if (this._maximum === value) {
                return;
            }
            // Update the internal values.
            this._maximum = value;
            // Clamp the current value to the new range.
            this._value = Math.min(this._value, value);
            // Schedule an update the scroll bar.
            this.update();
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ScrollBar.prototype, "decrementNode", {
        /**
         * The scroll bar decrement button node.
         *
         * #### Notes
         * Modifying this node directly can lead to undefined behavior.
         */
        get: function () {
            return this.node.getElementsByClassName('p-ScrollBar-button')[0];
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ScrollBar.prototype, "incrementNode", {
        /**
         * The scroll bar increment button node.
         *
         * #### Notes
         * Modifying this node directly can lead to undefined behavior.
         */
        get: function () {
            return this.node.getElementsByClassName('p-ScrollBar-button')[1];
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ScrollBar.prototype, "trackNode", {
        /**
         * The scroll bar track node.
         *
         * #### Notes
         * Modifying this node directly can lead to undefined behavior.
         */
        get: function () {
            return this.node.getElementsByClassName('p-ScrollBar-track')[0];
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ScrollBar.prototype, "thumbNode", {
        /**
         * The scroll bar thumb node.
         *
         * #### Notes
         * Modifying this node directly can lead to undefined behavior.
         */
        get: function () {
            return this.node.getElementsByClassName('p-ScrollBar-thumb')[0];
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Handle the DOM events for the scroll bar.
     *
     * @param event - The DOM event sent to the scroll bar.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the scroll bar's DOM node.
     *
     * This should not be called directly by user code.
     */
    ScrollBar.prototype.handleEvent = function (event) {
        switch (event.type) {
            case 'mousedown':
                this._evtMouseDown(event);
                break;
            case 'mousemove':
                this._evtMouseMove(event);
                break;
            case 'mouseup':
                this._evtMouseUp(event);
                break;
            case 'keydown':
                this._evtKeyDown(event);
                break;
            case 'contextmenu':
                event.preventDefault();
                event.stopPropagation();
                break;
        }
    };
    /**
     * A method invoked on a 'before-attach' message.
     */
    ScrollBar.prototype.onBeforeAttach = function (msg) {
        this.node.addEventListener('mousedown', this);
        this.update();
    };
    /**
     * A method invoked on an 'after-detach' message.
     */
    ScrollBar.prototype.onAfterDetach = function (msg) {
        this.node.removeEventListener('mousedown', this);
        this._releaseMouse();
    };
    /**
     * A method invoked on an 'update-request' message.
     */
    ScrollBar.prototype.onUpdateRequest = function (msg) {
        // Convert the value and page into percentages.
        var value = this._value * 100 / this._maximum;
        var page = this._page * 100 / (this._page + this._maximum);
        // Clamp the value and page to the relevant range.
        value = Math.max(0, Math.min(value, 100));
        page = Math.max(0, Math.min(page, 100));
        // Fetch the thumb style.
        var thumbStyle = this.thumbNode.style;
        // Update the thumb style for the current orientation.
        if (this._orientation === 'horizontal') {
            thumbStyle.top = '';
            thumbStyle.height = '';
            thumbStyle.left = value + "%";
            thumbStyle.width = page + "%";
            thumbStyle.transform = "translate(" + -value + "%, 0%)";
        }
        else {
            thumbStyle.left = '';
            thumbStyle.width = '';
            thumbStyle.top = value + "%";
            thumbStyle.height = page + "%";
            thumbStyle.transform = "translate(0%, " + -value + "%)";
        }
    };
    /**
     * Handle the `'keydown'` event for the scroll bar.
     */
    ScrollBar.prototype._evtKeyDown = function (event) {
        // Stop all input events during drag.
        event.preventDefault();
        event.stopPropagation();
        // Ignore anything except the `Escape` key.
        if (event.keyCode !== 27) {
            return;
        }
        // Fetch the previous scroll value.
        var value = this._pressData ? this._pressData.value : -1;
        // Release the mouse.
        this._releaseMouse();
        // Restore the old scroll value if possible.
        if (value !== -1) {
            this._moveThumb(value);
        }
    };
    /**
     * Handle the `'mousedown'` event for the scroll bar.
     */
    ScrollBar.prototype._evtMouseDown = function (event) {
        // Do nothing if it's not a left mouse press.
        if (event.button !== 0) {
            return;
        }
        // Do nothing if the mouse is already captured.
        if (this._pressData) {
            return;
        }
        // Find the pressed scroll bar part.
        var part = Private.findPart(this, event.target);
        // Do nothing if the part is not of interest.
        if (!part) {
            return;
        }
        // Stop the event propagation.
        event.preventDefault();
        event.stopPropagation();
        // Override the mouse cursor.
        var override = dragdrop_1.Drag.overrideCursor('default');
        // Set up the press data.
        this._pressData = {
            part: part, override: override,
            delta: -1, value: -1,
            mouseX: event.clientX,
            mouseY: event.clientY
        };
        // Add the extra event listeners.
        document.addEventListener('mousemove', this, true);
        document.addEventListener('mouseup', this, true);
        document.addEventListener('keydown', this, true);
        document.addEventListener('contextmenu', this, true);
        // Handle a thumb press.
        if (part === 'thumb') {
            // Fetch the thumb node.
            var thumbNode = this.thumbNode;
            // Fetch the client rect for the thumb.
            var thumbRect = thumbNode.getBoundingClientRect();
            // Update the press data delta for the current orientation.
            if (this._orientation === 'horizontal') {
                this._pressData.delta = event.clientX - thumbRect.left;
            }
            else {
                this._pressData.delta = event.clientY - thumbRect.top;
            }
            // Add the active class to the thumb node.
            thumbNode.classList.add('p-mod-active');
            // Store the current value in the press data.
            this._pressData.value = this._value;
            // Finished.
            return;
        }
        // Handle a track press.
        if (part === 'track') {
            // Fetch the client rect for the thumb.
            var thumbRect = this.thumbNode.getBoundingClientRect();
            // Determine the direction for the page request.
            var dir = void 0;
            if (this._orientation === 'horizontal') {
                dir = event.clientX < thumbRect.left ? 'decrement' : 'increment';
            }
            else {
                dir = event.clientY < thumbRect.top ? 'decrement' : 'increment';
            }
            // Start the repeat timer.
            this._repeatTimer = setTimeout(this._onRepeat, 350);
            // Emit the page requested signal.
            this._pageRequested.emit(dir);
            // Finished.
            return;
        }
        // Handle a decrement button press.
        if (part === 'decrement') {
            // Add the active class to the decrement node.
            this.decrementNode.classList.add('p-mod-active');
            // Start the repeat timer.
            this._repeatTimer = setTimeout(this._onRepeat, 350);
            // Emit the step requested signal.
            this._stepRequested.emit('decrement');
            // Finished.
            return;
        }
        // Handle an increment button press.
        if (part === 'increment') {
            // Add the active class to the increment node.
            this.incrementNode.classList.add('p-mod-active');
            // Start the repeat timer.
            this._repeatTimer = setTimeout(this._onRepeat, 350);
            // Emit the step requested signal.
            this._stepRequested.emit('increment');
            // Finished.
            return;
        }
    };
    /**
     * Handle the `'mousemove'` event for the scroll bar.
     */
    ScrollBar.prototype._evtMouseMove = function (event) {
        // Do nothing if no drag is in progress.
        if (!this._pressData) {
            return;
        }
        // Stop the event propagation.
        event.preventDefault();
        event.stopPropagation();
        // Update the mouse position.
        this._pressData.mouseX = event.clientX;
        this._pressData.mouseY = event.clientY;
        // Bail if the thumb is not being dragged.
        if (this._pressData.part !== 'thumb') {
            return;
        }
        // Get the client rect for the thumb and track.
        var thumbRect = this.thumbNode.getBoundingClientRect();
        var trackRect = this.trackNode.getBoundingClientRect();
        // Fetch the scroll geometry based on the orientation.
        var trackPos;
        var trackSpan;
        if (this._orientation === 'horizontal') {
            trackPos = event.clientX - trackRect.left - this._pressData.delta;
            trackSpan = trackRect.width - thumbRect.width;
        }
        else {
            trackPos = event.clientY - trackRect.top - this._pressData.delta;
            trackSpan = trackRect.height - thumbRect.height;
        }
        // Compute the desired value from the scroll geometry.
        var value = trackSpan === 0 ? 0 : trackPos * this._maximum / trackSpan;
        // Move the thumb to the computed value.
        this._moveThumb(value);
    };
    /**
     * Handle the `'mouseup'` event for the scroll bar.
     */
    ScrollBar.prototype._evtMouseUp = function (event) {
        // Do nothing if it's not a left mouse release.
        if (event.button !== 0) {
            return;
        }
        // Stop the event propagation.
        event.preventDefault();
        event.stopPropagation();
        // Release the mouse.
        this._releaseMouse();
    };
    /**
     * Release the mouse and restore the node states.
     */
    ScrollBar.prototype._releaseMouse = function () {
        // Bail if there is no press data.
        if (!this._pressData) {
            return;
        }
        // Clear the repeat timer.
        clearTimeout(this._repeatTimer);
        this._repeatTimer = -1;
        // Clear the press data.
        this._pressData.override.dispose();
        this._pressData = null;
        // Remove the extra event listeners.
        document.removeEventListener('mousemove', this, true);
        document.removeEventListener('mouseup', this, true);
        document.removeEventListener('keydown', this, true);
        document.removeEventListener('contextmenu', this, true);
        // Remove the active classes from the nodes.
        this.thumbNode.classList.remove('p-mod-active');
        this.decrementNode.classList.remove('p-mod-active');
        this.incrementNode.classList.remove('p-mod-active');
    };
    /**
     * Move the thumb to the specified position.
     */
    ScrollBar.prototype._moveThumb = function (value) {
        // Clamp the value to the allowed range.
        value = Math.max(0, Math.min(value, this._maximum));
        // Bail if the value does not change.
        if (this._value === value) {
            return;
        }
        // Update the internal value.
        this._value = value;
        // Schedule an update of the scroll bar.
        this.update();
        // Emit the thumb moved signal.
        this._thumbMoved.emit(value);
    };
    return ScrollBar;
}(widget_1.Widget));
exports.ScrollBar = ScrollBar;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * Create the DOM node for a scroll bar.
     */
    function createNode() {
        var node = document.createElement('div');
        var decrement = document.createElement('div');
        var increment = document.createElement('div');
        var track = document.createElement('div');
        var thumb = document.createElement('div');
        decrement.className = 'p-ScrollBar-button';
        increment.className = 'p-ScrollBar-button';
        decrement.dataset['action'] = 'decrement';
        increment.dataset['action'] = 'increment';
        track.className = 'p-ScrollBar-track';
        thumb.className = 'p-ScrollBar-thumb';
        track.appendChild(thumb);
        node.appendChild(decrement);
        node.appendChild(track);
        node.appendChild(increment);
        return node;
    }
    Private.createNode = createNode;
    /**
     * Find the scroll bar part which contains the given target.
     */
    function findPart(scrollBar, target) {
        // Test the thumb.
        if (scrollBar.thumbNode.contains(target)) {
            return 'thumb';
        }
        // Test the track.
        if (scrollBar.trackNode.contains(target)) {
            return 'track';
        }
        // Test the decrement button.
        if (scrollBar.decrementNode.contains(target)) {
            return 'decrement';
        }
        // Test the increment button.
        if (scrollBar.incrementNode.contains(target)) {
            return 'increment';
        }
        // Indicate no match.
        return null;
    }
    Private.findPart = findPart;
})(Private || (Private = {}));


/***/ }),

/***/ "vwZP":
/*!***************************************************************!*\
  !*** ./node_modules/@jupyterlab/vega4-extension/lib/index.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
__webpack_require__(/*! ../style/index.css */ "mPu1");
/**
 * The CSS class to add to the Vega and Vega-Lite widget.
 */
const VEGA_COMMON_CLASS = 'jp-RenderedVegaCommon4';
/**
 * The CSS class to add to the Vega.
 */
const VEGA_CLASS = 'jp-RenderedVega4';
/**
 * The CSS class to add to the Vega-Lite.
 */
const VEGALITE_CLASS = 'jp-RenderedVegaLite2';
/**
 * The MIME type for Vega.
 *
 * #### Notes
 * The version of this follows the major version of Vega.
 */
exports.VEGA_MIME_TYPE = 'application/vnd.vega.v4+json';
/**
 * The MIME type for Vega-Lite.
 *
 * #### Notes
 * The version of this follows the major version of Vega-Lite.
 */
exports.VEGALITE_MIME_TYPE = 'application/vnd.vegalite.v2+json';
/**
 * A widget for rendering Vega or Vega-Lite data, for usage with rendermime.
 */
class RenderedVega extends widgets_1.Widget {
    /**
     * Create a new widget for rendering Vega/Vega-Lite.
     */
    constructor(options) {
        super();
        this._mimeType = options.mimeType;
        this._resolver = options.resolver;
        this.addClass(VEGA_COMMON_CLASS);
        this.addClass(this._mimeType === exports.VEGA_MIME_TYPE ? VEGA_CLASS : VEGALITE_CLASS);
    }
    /**
     * Render Vega/Vega-Lite into this widget's node.
     */
    renderModel(model) {
        return __awaiter(this, void 0, void 0, function* () {
            const spec = model.data[this._mimeType];
            const metadata = model.metadata[this._mimeType];
            const embedOptions = metadata && metadata.embed_options ? metadata.embed_options : {};
            const mode = this._mimeType === exports.VEGA_MIME_TYPE ? 'vega' : 'vega-lite';
            const vega = Private.vega != null ? Private.vega : yield Private.ensureVega();
            const path = yield this._resolver.resolveUrl('');
            const baseURL = yield this._resolver.getDownloadUrl(path);
            const el = document.createElement('div');
            // clear the output before attaching a chart
            this.node.innerHTML = '';
            this.node.appendChild(el);
            this._result = yield vega.default(el, spec, Object.assign({ actions: true, defaultStyle: true }, embedOptions, { mode, loader: {
                    baseURL,
                    http: { credentials: 'same-origin' }
                } }));
            if (model.data['image/png']) {
                return;
            }
            // Add png representation of vega chart to output
            const imageURL = yield this._result.view.toImageURL('png');
            model.setData({
                data: Object.assign({}, model.data, { 'image/png': imageURL.split(',')[1] })
            });
        });
    }
    dispose() {
        if (this._result) {
            this._result.view.finalize();
        }
        super.dispose();
    }
}
exports.RenderedVega = RenderedVega;
/**
 * A mime renderer factory for vega data.
 */
exports.rendererFactory = {
    safe: true,
    mimeTypes: [exports.VEGA_MIME_TYPE, exports.VEGALITE_MIME_TYPE],
    createRenderer: options => new RenderedVega(options)
};
const extension = {
    id: '@jupyterlab/vega-extension:factory',
    rendererFactory: exports.rendererFactory,
    rank: 50,
    dataType: 'json',
    documentWidgetFactoryOptions: [
        {
            name: 'Vega',
            primaryFileType: 'vega4',
            fileTypes: ['vega4', 'json'],
            defaultFor: ['vega4']
        },
        {
            name: 'Vega-Lite',
            primaryFileType: 'vega-lite2',
            fileTypes: ['vega-lite2', 'json'],
            defaultFor: ['vega-lite2']
        }
    ],
    fileTypes: [
        {
            mimeTypes: [exports.VEGA_MIME_TYPE],
            name: 'vega4',
            extensions: ['.vg', '.vg.json', '.vega'],
            iconClass: 'jp-MaterialIcon jp-VegaIcon'
        },
        {
            mimeTypes: [exports.VEGALITE_MIME_TYPE],
            name: 'vega-lite2',
            extensions: ['.vl', '.vl.json', '.vegalite'],
            iconClass: 'jp-MaterialIcon jp-VegaIcon'
        }
    ]
};
exports.default = extension;
/**
 * A namespace for private module data.
 */
var Private;
(function (Private) {
    /**
     * Lazy-load and cache the vega-embed library
     */
    function ensureVega() {
        if (Private.vegaReady) {
            return Private.vegaReady;
        }
        Private.vegaReady = new Promise((resolve, reject) => {
            Promise.all(/*! require.ensure | vega */[__webpack_require__.e("vendors~@jupyter-widgets/controls~vega"), __webpack_require__.e("vendors~vega"), __webpack_require__.e("vega")]).then((require => {
                Private.vega = __webpack_require__(/*! vega-embed */ "etOl");
                resolve(Private.vega);
            }).bind(null, __webpack_require__)).catch((error) => {
                console.error(error);
                reject();
            });
        });
        return Private.vegaReady;
    }
    Private.ensureVega = ensureVega;
})(Private || (Private = {}));


/***/ }),

/***/ "vwuL":
/*!**************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_object-gopd.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var pIE = __webpack_require__(/*! ./_object-pie */ "NV0k");
var createDesc = __webpack_require__(/*! ./_property-desc */ "rr1i");
var toIObject = __webpack_require__(/*! ./_to-iobject */ "NsO/");
var toPrimitive = __webpack_require__(/*! ./_to-primitive */ "G8Mo");
var has = __webpack_require__(/*! ./_has */ "B+OT");
var IE8_DOM_DEFINE = __webpack_require__(/*! ./_ie8-dom-define */ "eUtF");
var gOPD = Object.getOwnPropertyDescriptor;

exports.f = __webpack_require__(/*! ./_descriptors */ "jmDH") ? gOPD : function getOwnPropertyDescriptor(O, P) {
  O = toIObject(O);
  P = toPrimitive(P, true);
  if (IE8_DOM_DEFINE) try {
    return gOPD(O, P);
  } catch (e) { /* empty */ }
  if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]);
};


/***/ }),

/***/ "vy9w":
/*!*********************************************************!*\
  !*** ./node_modules/@jupyterlab/inspector/lib/index.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__webpack_require__(/*! ../style/index.css */ "XwjZ");
__export(__webpack_require__(/*! ./handler */ "QKod"));
__export(__webpack_require__(/*! ./inspector */ "o4sl"));
__export(__webpack_require__(/*! ./kernelconnector */ "rsfS"));


/***/ }),

/***/ "vz/y":
/*!*********************************************************!*\
  !*** ./node_modules/@jupyterlab/console/lib/history.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
/**
 * A console history manager object.
 */
class ConsoleHistory {
    /**
     * Construct a new console history object.
     */
    constructor(options) {
        this._cursor = 0;
        this._hasSession = false;
        this._history = [];
        this._placeholder = '';
        this._setByHistory = false;
        this._isDisposed = false;
        this._editor = null;
        this._filtered = [];
        this.session = options.session;
        this._handleKernel();
        this.session.kernelChanged.connect(this._handleKernel, this);
    }
    /**
     * The current editor used by the history manager.
     */
    get editor() {
        return this._editor;
    }
    set editor(value) {
        if (this._editor === value) {
            return;
        }
        let prev = this._editor;
        if (prev) {
            prev.edgeRequested.disconnect(this.onEdgeRequest, this);
            prev.model.value.changed.disconnect(this.onTextChange, this);
        }
        this._editor = value;
        if (value) {
            value.edgeRequested.connect(this.onEdgeRequest, this);
            value.model.value.changed.connect(this.onTextChange, this);
        }
    }
    /**
     * The placeholder text that a history session began with.
     */
    get placeholder() {
        return this._placeholder;
    }
    /**
     * Get whether the console history manager is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources held by the console history manager.
     */
    dispose() {
        this._isDisposed = true;
        this._history.length = 0;
        signaling_1.Signal.clearData(this);
    }
    /**
     * Get the previous item in the console history.
     *
     * @param placeholder - The placeholder string that gets temporarily added
     * to the history only for the duration of one history session. If multiple
     * placeholders are sent within a session, only the first one is accepted.
     *
     * @returns A Promise for console command text or `undefined` if unavailable.
     */
    back(placeholder) {
        if (!this._hasSession) {
            this._hasSession = true;
            this._placeholder = placeholder;
            // Filter the history with the placeholder string.
            this.setFilter(placeholder);
            this._cursor = this._filtered.length - 1;
        }
        --this._cursor;
        this._cursor = Math.max(0, this._cursor);
        let content = this._filtered[this._cursor];
        return Promise.resolve(content);
    }
    /**
     * Get the next item in the console history.
     *
     * @param placeholder - The placeholder string that gets temporarily added
     * to the history only for the duration of one history session. If multiple
     * placeholders are sent within a session, only the first one is accepted.
     *
     * @returns A Promise for console command text or `undefined` if unavailable.
     */
    forward(placeholder) {
        if (!this._hasSession) {
            this._hasSession = true;
            this._placeholder = placeholder;
            // Filter the history with the placeholder string.
            this.setFilter(placeholder);
            this._cursor = this._filtered.length;
        }
        ++this._cursor;
        this._cursor = Math.min(this._filtered.length - 1, this._cursor);
        let content = this._filtered[this._cursor];
        return Promise.resolve(content);
    }
    /**
     * Add a new item to the bottom of history.
     *
     * @param item The item being added to the bottom of history.
     *
     * #### Notes
     * If the item being added is undefined or empty, it is ignored. If the item
     * being added is the same as the last item in history, it is ignored as well
     * so that the console's history will consist of no contiguous repetitions.
     */
    push(item) {
        if (item && item !== this._history[this._history.length - 1]) {
            this._history.push(item);
        }
        this.reset();
    }
    /**
     * Reset the history navigation state, i.e., start a new history session.
     */
    reset() {
        this._cursor = this._history.length;
        this._hasSession = false;
        this._placeholder = '';
    }
    /**
     * Populate the history collection on history reply from a kernel.
     *
     * @param value The kernel message history reply.
     *
     * #### Notes
     * History entries have the shape:
     * [session: number, line: number, input: string]
     * Contiguous duplicates are stripped out of the API response.
     */
    onHistory(value) {
        this._history.length = 0;
        let last = '';
        let current = '';
        for (let i = 0; i < value.content.history.length; i++) {
            current = value.content.history[i][2];
            if (current !== last) {
                this._history.push((last = current));
            }
        }
        // Reset the history navigation cursor back to the bottom.
        this._cursor = this._history.length;
    }
    /**
     * Handle a text change signal from the editor.
     */
    onTextChange() {
        if (this._setByHistory) {
            this._setByHistory = false;
            return;
        }
        this.reset();
    }
    /**
     * Handle an edge requested signal.
     */
    onEdgeRequest(editor, location) {
        let model = editor.model;
        let source = model.value.text;
        if (location === 'top') {
            this.back(source).then(value => {
                if (this.isDisposed || !value) {
                    return;
                }
                if (model.value.text === value) {
                    return;
                }
                this._setByHistory = true;
                model.value.text = value;
                editor.setCursorPosition({ line: 0, column: 0 });
            });
        }
        else {
            this.forward(source).then(value => {
                if (this.isDisposed) {
                    return;
                }
                let text = value || this.placeholder;
                if (model.value.text === text) {
                    return;
                }
                this._setByHistory = true;
                model.value.text = text;
                let pos = editor.getPositionAt(text.length);
                if (pos) {
                    editor.setCursorPosition(pos);
                }
            });
        }
    }
    /**
     * Handle the current kernel changing.
     */
    _handleKernel() {
        let kernel = this.session.kernel;
        if (!kernel) {
            this._history.length = 0;
            return;
        }
        kernel.requestHistory(Private.initialRequest).then(v => {
            this.onHistory(v);
        });
    }
    /**
     * Set the filter data.
     *
     * @param filterStr - The string to use when filtering the data.
     */
    setFilter(filterStr = '') {
        // Apply the new filter and remove contiguous duplicates.
        this._filtered.length = 0;
        let last = '';
        let current = '';
        for (let i = 0; i < this._history.length; i++) {
            current = this._history[i];
            if (current !== last &&
                filterStr === current.slice(0, filterStr.length)) {
                this._filtered.push((last = current));
            }
        }
        this._filtered.push(filterStr);
    }
}
exports.ConsoleHistory = ConsoleHistory;
/**
 * A namespace for private data.
 */
var Private;
(function (Private) {
    Private.initialRequest = {
        output: false,
        raw: true,
        hist_access_type: 'tail',
        n: 500
    };
})(Private || (Private = {}));


/***/ }),

/***/ "vzE1":
/*!*********************************************!*\
  !*** ./node_modules/number-is-nan/index.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = Number.isNaN || function (x) {
	return x !== x;
};


/***/ }),

/***/ "w+wy":
/*!******************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/throttle.js ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



var timerCache = {};

/**
 * Throttle a callback. `callback` executes synchronously only if
 * more than `minInterval` milliseconds have already elapsed since the latest
 * call (if any). Otherwise we wait until `minInterval` is over and execute the
 * last callback received while waiting.
 * So the first and last events in a train are always executed (eventually)
 * but some of the events in the middle can be dropped.
 *
 * @param {string} id: an identifier to mark events to throttle together
 * @param {number} minInterval: minimum time, in milliseconds, between
 *   invocations of `callback`
 * @param {function} callback: the function to throttle. `callback` itself
 *   should be a purely synchronous function.
 */
exports.throttle = function throttle(id, minInterval, callback) {
    var cache = timerCache[id];
    var now = Date.now();

    if(!cache) {
        /*
         * Throw out old items before making a new one, to prevent the cache
         * getting overgrown, for example from old plots that have been replaced.
         * 1 minute age is arbitrary.
         */
        for(var idi in timerCache) {
            if(timerCache[idi].ts < now - 60000) {
                delete timerCache[idi];
            }
        }
        cache = timerCache[id] = {ts: 0, timer: null};
    }

    _clearTimeout(cache);

    function exec() {
        callback();
        cache.ts = Date.now();
        if(cache.onDone) {
            cache.onDone();
            cache.onDone = null;
        }
    }

    if(now > cache.ts + minInterval) {
        exec();
        return;
    }

    cache.timer = setTimeout(function() {
        exec();
        cache.timer = null;
    }, minInterval);
};

exports.done = function(id) {
    var cache = timerCache[id];
    if(!cache || !cache.timer) return Promise.resolve();

    return new Promise(function(resolve) {
        var previousOnDone = cache.onDone;
        cache.onDone = function onDone() {
            if(previousOnDone) previousOnDone();
            resolve();
            cache.onDone = null;
        };
    });
};

/**
 * Clear the throttle cache for one or all timers
 * @param {optional string} id:
 *   if provided, clear just this timer
 *   if omitted, clear all timers (mainly useful for testing)
 */
exports.clear = function(id) {
    if(id) {
        _clearTimeout(timerCache[id]);
        delete timerCache[id];
    }
    else {
        for(var idi in timerCache) exports.clear(idi);
    }
};

function _clearTimeout(cache) {
    if(cache && cache.timer !== null) {
        clearTimeout(cache.timer);
        cache.timer = null;
    }
}


/***/ }),

/***/ "w/2H":
/*!**********************************************************!*\
  !*** ./node_modules/codemirror/addon/runmode/runmode.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"));
  else {}
})(function(CodeMirror) {
"use strict";

CodeMirror.runMode = function(string, modespec, callback, options) {
  var mode = CodeMirror.getMode(CodeMirror.defaults, modespec);
  var ie = /MSIE \d/.test(navigator.userAgent);
  var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9);

  if (callback.appendChild) {
    var tabSize = (options && options.tabSize) || CodeMirror.defaults.tabSize;
    var node = callback, col = 0;
    node.innerHTML = "";
    callback = function(text, style) {
      if (text == "\n") {
        // Emitting LF or CRLF on IE8 or earlier results in an incorrect display.
        // Emitting a carriage return makes everything ok.
        node.appendChild(document.createTextNode(ie_lt9 ? '\r' : text));
        col = 0;
        return;
      }
      var content = "";
      // replace tabs
      for (var pos = 0;;) {
        var idx = text.indexOf("\t", pos);
        if (idx == -1) {
          content += text.slice(pos);
          col += text.length - pos;
          break;
        } else {
          col += idx - pos;
          content += text.slice(pos, idx);
          var size = tabSize - col % tabSize;
          col += size;
          for (var i = 0; i < size; ++i) content += " ";
          pos = idx + 1;
        }
      }

      if (style) {
        var sp = node.appendChild(document.createElement("span"));
        sp.className = "cm-" + style.replace(/ +/g, " cm-");
        sp.appendChild(document.createTextNode(content));
      } else {
        node.appendChild(document.createTextNode(content));
      }
    };
  }

  var lines = CodeMirror.splitLines(string), state = (options && options.state) || CodeMirror.startState(mode);
  for (var i = 0, e = lines.length; i < e; ++i) {
    if (i) callback("\n");
    var stream = new CodeMirror.StringStream(lines[i]);
    if (!stream.string && mode.blankLine) mode.blankLine(state);
    while (!stream.eol()) {
      var style = mode.token(stream, state);
      callback(stream.current(), style, i, stream.start, state);
      stream.start = stream.pos;
    }
  }
};

});


/***/ }),

/***/ "w/wX":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_baseIsSet.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getTag = __webpack_require__(/*! ./_getTag */ "QqLw"),
    isObjectLike = __webpack_require__(/*! ./isObjectLike */ "ExA7");

/** `Object#toString` result references. */
var setTag = '[object Set]';

/**
 * 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;
}

module.exports = baseIsSet;


/***/ }),

/***/ "w0JW":
/*!*********************************************!*\
  !*** ./node_modules/mdi-react/EmailIcon.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var EmailIcon = function EmailIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M20,8L12,13L4,8V6L12,11L20,6M20,4H4C2.89,4 2,4.89 2,6V18C2,19.1 2.9,20 4,20H20C21.1,20 22,19.1 22,18V6C22,4.89 21.1,4 20,4Z' })
  );
};

module.exports = EmailIcon;


/***/ }),

/***/ "w2d+":
/*!********************************************************************!*\
  !*** ./node_modules/core-js/library/modules/es6.array.iterator.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var addToUnscopables = __webpack_require__(/*! ./_add-to-unscopables */ "hDam");
var step = __webpack_require__(/*! ./_iter-step */ "UO39");
var Iterators = __webpack_require__(/*! ./_iterators */ "SBuE");
var toIObject = __webpack_require__(/*! ./_to-iobject */ "NsO/");

// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = __webpack_require__(/*! ./_iter-define */ "MPFp")(Array, 'Array', function (iterated, kind) {
  this._t = toIObject(iterated); // target
  this._i = 0;                   // next index
  this._k = kind;                // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function () {
  var O = this._t;
  var kind = this._k;
  var index = this._i++;
  if (!O || index >= O.length) {
    this._t = undefined;
    return step(1);
  }
  if (kind == 'keys') return step(0, index);
  if (kind == 'values') return step(0, O[index]);
  return step(0, [index, O[index]]);
}, 'values');

// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;

addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');


/***/ }),

/***/ "w6GO":
/*!**************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_object-keys.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = __webpack_require__(/*! ./_object-keys-internal */ "5vMV");
var enumBugKeys = __webpack_require__(/*! ./_enum-bug-keys */ "FpHa");

module.exports = Object.keys || function keys(O) {
  return $keys(O, enumBugKeys);
};


/***/ }),

/***/ "w8CP":
/*!************************************************!*\
  !*** ./node_modules/hash.js/lib/hash/utils.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var assert = __webpack_require__(/*! minimalistic-assert */ "2j6C");
var inherits = __webpack_require__(/*! inherits */ "P7XM");

exports.inherits = inherits;

function isSurrogatePair(msg, i) {
  if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) {
    return false;
  }
  if (i < 0 || i + 1 >= msg.length) {
    return false;
  }
  return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00;
}

function toArray(msg, enc) {
  if (Array.isArray(msg))
    return msg.slice();
  if (!msg)
    return [];
  var res = [];
  if (typeof msg === 'string') {
    if (!enc) {
      // Inspired by stringToUtf8ByteArray() in closure-library by Google
      // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
      // Apache License 2.0
      // https://github.com/google/closure-library/blob/master/LICENSE
      var p = 0;
      for (var i = 0; i < msg.length; i++) {
        var c = msg.charCodeAt(i);
        if (c < 128) {
          res[p++] = c;
        } else if (c < 2048) {
          res[p++] = (c >> 6) | 192;
          res[p++] = (c & 63) | 128;
        } else if (isSurrogatePair(msg, i)) {
          c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF);
          res[p++] = (c >> 18) | 240;
          res[p++] = ((c >> 12) & 63) | 128;
          res[p++] = ((c >> 6) & 63) | 128;
          res[p++] = (c & 63) | 128;
        } else {
          res[p++] = (c >> 12) | 224;
          res[p++] = ((c >> 6) & 63) | 128;
          res[p++] = (c & 63) | 128;
        }
      }
    } else if (enc === 'hex') {
      msg = msg.replace(/[^a-z0-9]+/ig, '');
      if (msg.length % 2 !== 0)
        msg = '0' + msg;
      for (i = 0; i < msg.length; i += 2)
        res.push(parseInt(msg[i] + msg[i + 1], 16));
    }
  } else {
    for (i = 0; i < msg.length; i++)
      res[i] = msg[i] | 0;
  }
  return res;
}
exports.toArray = toArray;

function toHex(msg) {
  var res = '';
  for (var i = 0; i < msg.length; i++)
    res += zero2(msg[i].toString(16));
  return res;
}
exports.toHex = toHex;

function htonl(w) {
  var res = (w >>> 24) |
            ((w >>> 8) & 0xff00) |
            ((w << 8) & 0xff0000) |
            ((w & 0xff) << 24);
  return res >>> 0;
}
exports.htonl = htonl;

function toHex32(msg, endian) {
  var res = '';
  for (var i = 0; i < msg.length; i++) {
    var w = msg[i];
    if (endian === 'little')
      w = htonl(w);
    res += zero8(w.toString(16));
  }
  return res;
}
exports.toHex32 = toHex32;

function zero2(word) {
  if (word.length === 1)
    return '0' + word;
  else
    return word;
}
exports.zero2 = zero2;

function zero8(word) {
  if (word.length === 7)
    return '0' + word;
  else if (word.length === 6)
    return '00' + word;
  else if (word.length === 5)
    return '000' + word;
  else if (word.length === 4)
    return '0000' + word;
  else if (word.length === 3)
    return '00000' + word;
  else if (word.length === 2)
    return '000000' + word;
  else if (word.length === 1)
    return '0000000' + word;
  else
    return word;
}
exports.zero8 = zero8;

function join32(msg, start, end, endian) {
  var len = end - start;
  assert(len % 4 === 0);
  var res = new Array(len / 4);
  for (var i = 0, k = start; i < res.length; i++, k += 4) {
    var w;
    if (endian === 'big')
      w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
    else
      w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
    res[i] = w >>> 0;
  }
  return res;
}
exports.join32 = join32;

function split32(msg, endian) {
  var res = new Array(msg.length * 4);
  for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
    var m = msg[i];
    if (endian === 'big') {
      res[k] = m >>> 24;
      res[k + 1] = (m >>> 16) & 0xff;
      res[k + 2] = (m >>> 8) & 0xff;
      res[k + 3] = m & 0xff;
    } else {
      res[k + 3] = m >>> 24;
      res[k + 2] = (m >>> 16) & 0xff;
      res[k + 1] = (m >>> 8) & 0xff;
      res[k] = m & 0xff;
    }
  }
  return res;
}
exports.split32 = split32;

function rotr32(w, b) {
  return (w >>> b) | (w << (32 - b));
}
exports.rotr32 = rotr32;

function rotl32(w, b) {
  return (w << b) | (w >>> (32 - b));
}
exports.rotl32 = rotl32;

function sum32(a, b) {
  return (a + b) >>> 0;
}
exports.sum32 = sum32;

function sum32_3(a, b, c) {
  return (a + b + c) >>> 0;
}
exports.sum32_3 = sum32_3;

function sum32_4(a, b, c, d) {
  return (a + b + c + d) >>> 0;
}
exports.sum32_4 = sum32_4;

function sum32_5(a, b, c, d, e) {
  return (a + b + c + d + e) >>> 0;
}
exports.sum32_5 = sum32_5;

function sum64(buf, pos, ah, al) {
  var bh = buf[pos];
  var bl = buf[pos + 1];

  var lo = (al + bl) >>> 0;
  var hi = (lo < al ? 1 : 0) + ah + bh;
  buf[pos] = hi >>> 0;
  buf[pos + 1] = lo;
}
exports.sum64 = sum64;

function sum64_hi(ah, al, bh, bl) {
  var lo = (al + bl) >>> 0;
  var hi = (lo < al ? 1 : 0) + ah + bh;
  return hi >>> 0;
}
exports.sum64_hi = sum64_hi;

function sum64_lo(ah, al, bh, bl) {
  var lo = al + bl;
  return lo >>> 0;
}
exports.sum64_lo = sum64_lo;

function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
  var carry = 0;
  var lo = al;
  lo = (lo + bl) >>> 0;
  carry += lo < al ? 1 : 0;
  lo = (lo + cl) >>> 0;
  carry += lo < cl ? 1 : 0;
  lo = (lo + dl) >>> 0;
  carry += lo < dl ? 1 : 0;

  var hi = ah + bh + ch + dh + carry;
  return hi >>> 0;
}
exports.sum64_4_hi = sum64_4_hi;

function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
  var lo = al + bl + cl + dl;
  return lo >>> 0;
}
exports.sum64_4_lo = sum64_4_lo;

function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
  var carry = 0;
  var lo = al;
  lo = (lo + bl) >>> 0;
  carry += lo < al ? 1 : 0;
  lo = (lo + cl) >>> 0;
  carry += lo < cl ? 1 : 0;
  lo = (lo + dl) >>> 0;
  carry += lo < dl ? 1 : 0;
  lo = (lo + el) >>> 0;
  carry += lo < el ? 1 : 0;

  var hi = ah + bh + ch + dh + eh + carry;
  return hi >>> 0;
}
exports.sum64_5_hi = sum64_5_hi;

function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
  var lo = al + bl + cl + dl + el;

  return lo >>> 0;
}
exports.sum64_5_lo = sum64_5_lo;

function rotr64_hi(ah, al, num) {
  var r = (al << (32 - num)) | (ah >>> num);
  return r >>> 0;
}
exports.rotr64_hi = rotr64_hi;

function rotr64_lo(ah, al, num) {
  var r = (ah << (32 - num)) | (al >>> num);
  return r >>> 0;
}
exports.rotr64_lo = rotr64_lo;

function shr64_hi(ah, al, num) {
  return ah >>> num;
}
exports.shr64_hi = shr64_hi;

function shr64_lo(ah, al, num) {
  var r = (ah << (32 - num)) | (al >>> num);
  return r >>> 0;
}
exports.shr64_lo = shr64_lo;


/***/ }),

/***/ "wF/u":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_baseIsEqual.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseIsEqualDeep = __webpack_require__(/*! ./_baseIsEqualDeep */ "e5cp"),
    isObjectLike = __webpack_require__(/*! ./isObjectLike */ "ExA7");

/**
 * 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);
}

module.exports = baseIsEqual;


/***/ }),

/***/ "wGmf":
/*!********************************************************!*\
  !*** ./node_modules/@jupyterlab/notebook/lib/model.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const docregistry_1 = __webpack_require__(/*! @jupyterlab/docregistry */ "jTF0");
const cells_1 = __webpack_require__(/*! @jupyterlab/cells */ "USP6");
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const coreutils_2 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const celllist_1 = __webpack_require__(/*! ./celllist */ "Uia9");
/**
 * An implementation of a notebook Model.
 */
class NotebookModel extends docregistry_1.DocumentModel {
    /**
     * Construct a new notebook model.
     */
    constructor(options = {}) {
        super(options.languagePreference, options.modelDB);
        this._nbformat = coreutils_1.nbformat.MAJOR_VERSION;
        this._nbformatMinor = coreutils_1.nbformat.MINOR_VERSION;
        let factory = options.contentFactory || NotebookModel.defaultContentFactory;
        this.contentFactory = factory.clone(this.modelDB.view('cells'));
        this._cells = new celllist_1.CellList(this.modelDB, this.contentFactory);
        // Add an initial code cell by default.
        if (!this._cells.length) {
            this._cells.push(factory.createCodeCell({}));
        }
        this._cells.changed.connect(this._onCellsChanged, this);
        // Handle initial metadata.
        let metadata = this.modelDB.createMap('metadata');
        if (!metadata.has('language_info')) {
            let name = options.languagePreference || '';
            metadata.set('language_info', { name });
        }
        this._ensureMetadata();
        metadata.changed.connect(this.triggerContentChange, this);
        this._deletedCells = [];
    }
    /**
     * The metadata associated with the notebook.
     */
    get metadata() {
        return this.modelDB.get('metadata');
    }
    /**
     * Get the observable list of notebook cells.
     */
    get cells() {
        return this._cells;
    }
    /**
     * The major version number of the nbformat.
     */
    get nbformat() {
        return this._nbformat;
    }
    /**
     * The minor version number of the nbformat.
     */
    get nbformatMinor() {
        return this._nbformatMinor;
    }
    /**
     * The default kernel name of the document.
     */
    get defaultKernelName() {
        let spec = this.metadata.get('kernelspec');
        return spec ? spec.name : '';
    }
    /**
     * The default kernel name of the document.
     */
    get deletedCells() {
        return this._deletedCells;
    }
    /**
     * The default kernel language of the document.
     */
    get defaultKernelLanguage() {
        let info = this.metadata.get('language_info');
        return info ? info.name : '';
    }
    /**
     * Dispose of the resources held by the model.
     */
    dispose() {
        // Do nothing if already disposed.
        if (this.cells === null) {
            return;
        }
        let cells = this.cells;
        this._cells = null;
        cells.dispose();
        super.dispose();
    }
    /**
     * Serialize the model to a string.
     */
    toString() {
        return JSON.stringify(this.toJSON());
    }
    /**
     * Deserialize the model from a string.
     *
     * #### Notes
     * Should emit a [contentChanged] signal.
     */
    fromString(value) {
        this.fromJSON(JSON.parse(value));
    }
    /**
     * Serialize the model to JSON.
     */
    toJSON() {
        let cells = [];
        for (let i = 0; i < this.cells.length; i++) {
            let cell = this.cells.get(i);
            cells.push(cell.toJSON());
        }
        this._ensureMetadata();
        let metadata = Object.create(null);
        for (let key of this.metadata.keys()) {
            metadata[key] = JSON.parse(JSON.stringify(this.metadata.get(key)));
        }
        return {
            metadata,
            nbformat_minor: this._nbformatMinor,
            nbformat: this._nbformat,
            cells
        };
    }
    /**
     * Deserialize the model from JSON.
     *
     * #### Notes
     * Should emit a [contentChanged] signal.
     */
    fromJSON(value) {
        let cells = [];
        let factory = this.contentFactory;
        for (let cell of value.cells) {
            switch (cell.cell_type) {
                case 'code':
                    cells.push(factory.createCodeCell({ cell }));
                    break;
                case 'markdown':
                    cells.push(factory.createMarkdownCell({ cell }));
                    break;
                case 'raw':
                    cells.push(factory.createRawCell({ cell }));
                    break;
                default:
                    continue;
            }
        }
        this.cells.beginCompoundOperation();
        this.cells.clear();
        this.cells.pushAll(cells);
        this.cells.endCompoundOperation();
        let oldValue = 0;
        let newValue = 0;
        this._nbformatMinor = coreutils_1.nbformat.MINOR_VERSION;
        this._nbformat = coreutils_1.nbformat.MAJOR_VERSION;
        if (value.nbformat !== this._nbformat) {
            oldValue = this._nbformat;
            this._nbformat = newValue = value.nbformat;
            this.triggerStateChange({ name: 'nbformat', oldValue, newValue });
        }
        if (value.nbformat_minor > this._nbformatMinor) {
            oldValue = this._nbformatMinor;
            this._nbformatMinor = newValue = value.nbformat_minor;
            this.triggerStateChange({ name: 'nbformatMinor', oldValue, newValue });
        }
        // Update the metadata.
        this.metadata.clear();
        let metadata = value.metadata;
        for (let key in metadata) {
            // orig_nbformat is not intended to be stored per spec.
            if (key === 'orig_nbformat') {
                continue;
            }
            this.metadata.set(key, metadata[key]);
        }
        this._ensureMetadata();
        this.dirty = true;
    }
    /**
     * Initialize the model with its current state.
     */
    initialize() {
        super.initialize();
        this.cells.clearUndo();
    }
    /**
     * Handle a change in the cells list.
     */
    _onCellsChanged(list, change) {
        switch (change.type) {
            case 'add':
                change.newValues.forEach(cell => {
                    cell.contentChanged.connect(this.triggerContentChange, this);
                });
                break;
            case 'remove':
                break;
            case 'set':
                change.newValues.forEach(cell => {
                    cell.contentChanged.connect(this.triggerContentChange, this);
                });
                break;
            default:
                break;
        }
        let factory = this.contentFactory;
        // Add code cell if there are no cells remaining.
        if (!this.cells.length) {
            // Add the cell in a new context to avoid triggering another
            // cell changed event during the handling of this signal.
            requestAnimationFrame(() => {
                if (!this.isDisposed && !this.cells.length) {
                    this.cells.push(factory.createCodeCell({}));
                }
            });
        }
        this.triggerContentChange();
    }
    /**
     * Make sure we have the required metadata fields.
     */
    _ensureMetadata() {
        let metadata = this.metadata;
        if (!metadata.has('language_info')) {
            metadata.set('language_info', { name: '' });
        }
        if (!metadata.has('kernelspec')) {
            metadata.set('kernelspec', { name: '', display_name: '' });
        }
    }
}
exports.NotebookModel = NotebookModel;
/**
 * The namespace for the `NotebookModel` class statics.
 */
(function (NotebookModel) {
    /**
     * The default implementation of an `IContentFactory`.
     */
    class ContentFactory {
        /**
         * Create a new cell model factory.
         */
        constructor(options) {
            this.codeCellContentFactory =
                options.codeCellContentFactory || cells_1.CodeCellModel.defaultContentFactory;
            this.modelDB = options.modelDB;
        }
        /**
         * Create a new code cell.
         *
         * @param source - The data to use for the original source data.
         *
         * @returns A new code cell. If a source cell is provided, the
         *   new cell will be initialized with the data from the source.
         *   If the contentFactory is not provided, the instance
         *   `codeCellContentFactory` will be used.
         */
        createCodeCell(options) {
            if (options.contentFactory) {
                options.contentFactory = this.codeCellContentFactory;
            }
            if (this.modelDB) {
                if (!options.id) {
                    options.id = coreutils_2.UUID.uuid4();
                }
                options.modelDB = this.modelDB.view(options.id);
            }
            return new cells_1.CodeCellModel(options);
        }
        /**
         * Create a new markdown cell.
         *
         * @param source - The data to use for the original source data.
         *
         * @returns A new markdown cell. If a source cell is provided, the
         *   new cell will be initialized with the data from the source.
         */
        createMarkdownCell(options) {
            if (this.modelDB) {
                if (!options.id) {
                    options.id = coreutils_2.UUID.uuid4();
                }
                options.modelDB = this.modelDB.view(options.id);
            }
            return new cells_1.MarkdownCellModel(options);
        }
        /**
         * Create a new raw cell.
         *
         * @param source - The data to use for the original source data.
         *
         * @returns A new raw cell. If a source cell is provided, the
         *   new cell will be initialized with the data from the source.
         */
        createRawCell(options) {
            if (this.modelDB) {
                if (!options.id) {
                    options.id = coreutils_2.UUID.uuid4();
                }
                options.modelDB = this.modelDB.view(options.id);
            }
            return new cells_1.RawCellModel(options);
        }
        /**
         * Clone the content factory with a new IModelDB.
         */
        clone(modelDB) {
            return new ContentFactory({
                modelDB: modelDB,
                codeCellContentFactory: this.codeCellContentFactory
            });
        }
    }
    NotebookModel.ContentFactory = ContentFactory;
    /**
     * The default `ContentFactory` instance.
     */
    NotebookModel.defaultContentFactory = new ContentFactory({});
})(NotebookModel = exports.NotebookModel || (exports.NotebookModel = {}));


/***/ }),

/***/ "wHxL":
/*!******************************************************************!*\
  !*** ./node_modules/@jupyterlab/settingeditor/lib/splitpanel.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
/**
 * A deprecated split panel that will be removed when the phosphor split panel
 * supports a handle moved signal. See https://github.com/phosphorjs/phosphor/issues/297.
 */
class SplitPanel extends widgets_1.SplitPanel {
    constructor() {
        super(...arguments);
        /**
         * Emits when the split handle has moved.
         */
        this.handleMoved = new signaling_1.Signal(this);
    }
    handleEvent(event) {
        super.handleEvent(event);
        if (event.type === 'mouseup') {
            this.handleMoved.emit(undefined);
        }
    }
}
exports.SplitPanel = SplitPanel;


/***/ }),

/***/ "wI5Q":
/*!**************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeSurfaceIcon.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeSurfaceIcon = function TraceTypeSurfaceIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement(
            'defs',
            null,
            _react2.default.createElement(
                'linearGradient',
                { id: 'a', x1: '23.445', y1: '12.605', x2: '23.445', y2: '28.002', gradientUnits: 'userSpaceOnUse' },
                _react2.default.createElement('stop', { offset: '0', stopColor: '#1d9cfc' }),
                _react2.default.createElement('stop', { offset: '1', stopColor: '#25fdfc' })
            )
        ),
        _react2.default.createElement('path', { fill: 'none', d: 'M0 0h46v46H0z' }),
        _react2.default.createElement('path', { fill: '#25fdfc', stroke: '#1d9bfb', d: 'M23.511 23.571l.005-15.302L37 14.295v15.75l-13.489-6.474z', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2' }),
        _react2.default.createElement('path', { fill: '#25fdfc', stroke: '#1d9bfb', d: 'M23.511 23.571L9.516 30.045l13.929 6.319L37 30.045l-13.489-6.474z', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2' }),
        _react2.default.createElement('path', { fill: '#25fdfc', stroke: '#1d9bfb', d: 'M9.516 30.045v-15.75l13.999-6.026-.004 15.302-13.995 6.474z', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2' }),
        _react2.default.createElement('path', { d: 'M16.565 29.746c1.795-.942 3.07-4.294 3.07-9.292a3.81 3.81 0 1 1 7.62 0c0 4.998 1.275 8.35 3.07 9.292', stroke: '#1d9bfb', fill: 'url(#a)', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2' })
    );
};

exports.default = TraceTypeSurfaceIcon;

/***/ }),

/***/ "wJg7":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_isIndex.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;

/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;

/**
 * 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);
}

module.exports = isIndex;


/***/ }),

/***/ "wK5+":
/*!********************************************************!*\
  !*** ./node_modules/@jupyterlab/console/lib/widget.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const cells_1 = __webpack_require__(/*! @jupyterlab/cells */ "USP6");
const observables_1 = __webpack_require__(/*! @jupyterlab/observables */ "V4vH");
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const foreign_1 = __webpack_require__(/*! ./foreign */ "wplO");
const history_1 = __webpack_require__(/*! ./history */ "vz/y");
/**
 * The data attribute added to a widget that has an active kernel.
 */
const KERNEL_USER = 'jpKernelUser';
/**
 * The data attribute added to a widget can run code.
 */
const CODE_RUNNER = 'jpCodeRunner';
/**
 * The class name added to console widgets.
 */
const CONSOLE_CLASS = 'jp-CodeConsole';
/**
 * The class name added to the console banner.
 */
const BANNER_CLASS = 'jp-CodeConsole-banner';
/**
 * The class name of a cell whose input originated from a foreign session.
 */
const FOREIGN_CELL_CLASS = 'jp-CodeConsole-foreignCell';
/**
 * The class name of the active prompt cell.
 */
const PROMPT_CLASS = 'jp-CodeConsole-promptCell';
/**
 * The class name of the panel that holds cell content.
 */
const CONTENT_CLASS = 'jp-CodeConsole-content';
/**
 * The class name of the panel that holds prompts.
 */
const INPUT_CLASS = 'jp-CodeConsole-input';
/**
 * The timeout in ms for execution requests to the kernel.
 */
const EXECUTION_TIMEOUT = 250;
/**
 * A widget containing a Jupyter console.
 *
 * #### Notes
 * The CodeConsole class is intended to be used within a ConsolePanel
 * instance. Under most circumstances, it is not instantiated by user code.
 */
class CodeConsole extends widgets_1.Widget {
    /**
     * Construct a console widget.
     */
    constructor(options) {
        super();
        this._banner = null;
        this._executed = new signaling_1.Signal(this);
        this._mimetype = 'text/x-ipython';
        this._promptCellCreated = new signaling_1.Signal(this);
        this.addClass(CONSOLE_CLASS);
        this.node.dataset[KERNEL_USER] = 'true';
        this.node.dataset[CODE_RUNNER] = 'true';
        this.node.tabIndex = -1; // Allow the widget to take focus.
        // Create the panels that hold the content and input.
        const layout = (this.layout = new widgets_1.PanelLayout());
        this._cells = new observables_1.ObservableList();
        this._content = new widgets_1.Panel();
        this._input = new widgets_1.Panel();
        this.contentFactory =
            options.contentFactory || CodeConsole.defaultContentFactory;
        this.modelFactory = options.modelFactory || CodeConsole.defaultModelFactory;
        this.rendermime = options.rendermime;
        this.session = options.session;
        this._mimeTypeService = options.mimeTypeService;
        // Add top-level CSS classes.
        this._content.addClass(CONTENT_CLASS);
        this._input.addClass(INPUT_CLASS);
        // Insert the content and input panes into the widget.
        layout.addWidget(this._content);
        layout.addWidget(this._input);
        // Set up the foreign iopub handler.
        this._foreignHandler = new foreign_1.ForeignHandler({
            session: this.session,
            parent: this,
            cellFactory: () => this._createCodeCell()
        });
        this._history = new history_1.ConsoleHistory({
            session: this.session
        });
        this._onKernelChanged();
        this.session.kernelChanged.connect(this._onKernelChanged, this);
        this.session.statusChanged.connect(this._onKernelStatusChanged, this);
    }
    /**
     * A signal emitted when the console finished executing its prompt cell.
     */
    get executed() {
        return this._executed;
    }
    /**
     * A signal emitted when a new prompt cell is created.
     */
    get promptCellCreated() {
        return this._promptCellCreated;
    }
    /**
     * The list of content cells in the console.
     *
     * #### Notes
     * This list does not include the current banner or the prompt for a console.
     * It may include previous banners as raw cells.
     */
    get cells() {
        return this._cells;
    }
    /*
     * The console input prompt cell.
     */
    get promptCell() {
        let inputLayout = this._input.layout;
        return inputLayout.widgets[0] || null;
    }
    /**
     * Add a new cell to the content panel.
     *
     * @param cell - The cell widget being added to the content panel.
     *
     * #### Notes
     * This method is meant for use by outside classes that want to inject content
     * into a console. It is distinct from the `inject` method in that it requires
     * rendered code cell widgets and does not execute them.
     */
    addCell(cell) {
        this._content.addWidget(cell);
        this._cells.push(cell);
        cell.disposed.connect(this._onCellDisposed, this);
        this.update();
    }
    addBanner() {
        if (this._banner) {
            // An old banner just becomes a normal cell now.
            let cell = this._banner;
            this._cells.push(this._banner);
            cell.disposed.connect(this._onCellDisposed, this);
        }
        // Create the banner.
        let model = this.modelFactory.createRawCell({});
        model.value.text = '...';
        let banner = (this._banner = new cells_1.RawCell({
            model,
            contentFactory: this.contentFactory
        }));
        banner.addClass(BANNER_CLASS);
        banner.readOnly = true;
        this._content.addWidget(banner);
    }
    /**
     * Clear the code cells.
     */
    clear() {
        // Dispose all the content cells
        let cells = this._cells;
        while (cells.length > 0) {
            cells.get(0).dispose();
        }
    }
    /**
     * Dispose of the resources held by the widget.
     */
    dispose() {
        // Do nothing if already disposed.
        if (this.isDisposed) {
            return;
        }
        this._cells.clear();
        this._history.dispose();
        this._foreignHandler.dispose();
        super.dispose();
    }
    /**
     * Set whether the foreignHandler is able to inject foreign cells into a
     * console.
     */
    get showAllActivity() {
        return this._foreignHandler.enabled;
    }
    set showAllActivity(value) {
        this._foreignHandler.enabled = value;
    }
    /**
     * Execute the current prompt.
     *
     * @param force - Whether to force execution without checking code
     * completeness.
     *
     * @param timeout - The length of time, in milliseconds, that the execution
     * should wait for the API to determine whether code being submitted is
     * incomplete before attempting submission anyway. The default value is `250`.
     */
    execute(force = false, timeout = EXECUTION_TIMEOUT) {
        if (this.session.status === 'dead') {
            return Promise.resolve(void 0);
        }
        const promptCell = this.promptCell;
        if (!promptCell) {
            return Promise.reject('Cannot execute without a prompt cell');
        }
        promptCell.model.trusted = true;
        if (force) {
            // Create a new prompt cell before kernel execution to allow typeahead.
            this.newPromptCell();
            return this._execute(promptCell);
        }
        // Check whether we should execute.
        return this._shouldExecute(timeout).then(should => {
            if (this.isDisposed) {
                return;
            }
            if (should) {
                // Create a new prompt cell before kernel execution to allow typeahead.
                this.newPromptCell();
                this.promptCell.editor.focus();
                return this._execute(promptCell);
            }
            else {
                // add a newline if we shouldn't execute
                promptCell.editor.newIndentedLine();
            }
        });
    }
    /**
     * Inject arbitrary code for the console to execute immediately.
     *
     * @param code - The code contents of the cell being injected.
     *
     * @returns A promise that indicates when the injected cell's execution ends.
     */
    inject(code) {
        let cell = this._createCodeCell();
        cell.model.value.text = code;
        this.addCell(cell);
        return this._execute(cell);
    }
    /**
     * Insert a line break in the prompt cell.
     */
    insertLinebreak() {
        let promptCell = this.promptCell;
        if (!promptCell) {
            return;
        }
        promptCell.editor.newIndentedLine();
    }
    /**
     * Serialize the output.
     *
     * #### Notes
     * This only serializes the code cells and the prompt cell if it exists, and
     * skips any old banner cells.
     */
    serialize() {
        const cells = [];
        algorithm_1.each(this._cells, cell => {
            let model = cell.model;
            if (cells_1.isCodeCellModel(model)) {
                cells.push(model.toJSON());
            }
        });
        if (this.promptCell) {
            cells.push(this.promptCell.model.toJSON());
        }
        return cells;
    }
    /**
     * Handle the DOM events for the widget.
     *
     * @param event - The DOM event sent to the widget.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the notebook panel's node. It should
     * not be called directly by user code.
     */
    handleEvent(event) {
        switch (event.type) {
            case 'keydown':
                this._evtKeyDown(event);
                break;
            case 'click':
                this._evtClick(event);
                break;
            default:
                break;
        }
    }
    /**
     * Handle `after_attach` messages for the widget.
     */
    onAfterAttach(msg) {
        let node = this.node;
        node.addEventListener('keydown', this, true);
        node.addEventListener('click', this);
        // Create a prompt if necessary.
        if (!this.promptCell) {
            this.newPromptCell();
        }
        else {
            this.promptCell.editor.focus();
            this.update();
        }
    }
    /**
     * Handle `before-detach` messages for the widget.
     */
    onBeforeDetach(msg) {
        let node = this.node;
        node.removeEventListener('keydown', this, true);
        node.removeEventListener('click', this);
    }
    /**
     * Handle `'activate-request'` messages.
     */
    onActivateRequest(msg) {
        let editor = this.promptCell && this.promptCell.editor;
        if (editor) {
            editor.focus();
        }
        this.update();
    }
    /**
     * Make a new prompt cell.
     */
    newPromptCell() {
        let promptCell = this.promptCell;
        let input = this._input;
        // Make the last prompt read-only, clear its signals, and move to content.
        if (promptCell) {
            promptCell.readOnly = true;
            promptCell.removeClass(PROMPT_CLASS);
            signaling_1.Signal.clearData(promptCell.editor);
            let child = input.widgets[0];
            child.parent = null;
            this.addCell(promptCell);
        }
        // Create the new prompt cell.
        let factory = this.contentFactory;
        let options = this._createCodeCellOptions();
        promptCell = factory.createCodeCell(options);
        promptCell.model.mimeType = this._mimetype;
        promptCell.addClass(PROMPT_CLASS);
        this._input.addWidget(promptCell);
        // Suppress the default "Enter" key handling.
        let editor = promptCell.editor;
        editor.addKeydownHandler(this._onEditorKeydown);
        this._history.editor = editor;
        this._promptCellCreated.emit(promptCell);
    }
    /**
     * Handle `update-request` messages.
     */
    onUpdateRequest(msg) {
        Private.scrollToBottom(this._content.node);
    }
    /**
     * Handle the `'keydown'` event for the widget.
     */
    _evtKeyDown(event) {
        let editor = this.promptCell && this.promptCell.editor;
        if (!editor) {
            return;
        }
        if (event.keyCode === 13 && !editor.hasFocus()) {
            event.preventDefault();
            editor.focus();
        }
    }
    /**
     * Handle the `'click'` event for the widget.
     */
    _evtClick(event) {
        if (this.promptCell &&
            this.promptCell.node.contains(event.target)) {
            this.promptCell.editor.focus();
        }
    }
    /**
     * Execute the code in the current prompt cell.
     */
    _execute(cell) {
        let source = cell.model.value.text;
        this._history.push(source);
        // If the source of the console is just "clear", clear the console as we
        // do in IPython or QtConsole.
        if (source === 'clear' || source === '%clear') {
            this.clear();
            return Promise.resolve(void 0);
        }
        cell.model.contentChanged.connect(this.update, this);
        let onSuccess = (value) => {
            if (this.isDisposed) {
                return;
            }
            if (value && value.content.status === 'ok') {
                let content = value.content;
                // Use deprecated payloads for backwards compatibility.
                if (content.payload && content.payload.length) {
                    let setNextInput = content.payload.filter(i => {
                        return i.source === 'set_next_input';
                    })[0];
                    if (setNextInput) {
                        let text = setNextInput.text;
                        // Ignore the `replace` value and always set the next cell.
                        cell.model.value.text = text;
                    }
                }
            }
            cell.model.contentChanged.disconnect(this.update, this);
            this.update();
            this._executed.emit(new Date());
        };
        let onFailure = () => {
            if (this.isDisposed) {
                return;
            }
            cell.model.contentChanged.disconnect(this.update, this);
            this.update();
        };
        return cells_1.CodeCell.execute(cell, this.session).then(onSuccess, onFailure);
    }
    /**
     * Update the console based on the kernel info.
     */
    _handleInfo(info) {
        this._banner.model.value.text = info.banner;
        let lang = info.language_info;
        this._mimetype = this._mimeTypeService.getMimeTypeByLanguage(lang);
        if (this.promptCell) {
            this.promptCell.model.mimeType = this._mimetype;
        }
    }
    /**
     * Create a new foreign cell.
     */
    _createCodeCell() {
        let factory = this.contentFactory;
        let options = this._createCodeCellOptions();
        let cell = factory.createCodeCell(options);
        cell.readOnly = true;
        cell.model.mimeType = this._mimetype;
        cell.addClass(FOREIGN_CELL_CLASS);
        return cell;
    }
    /**
     * Create the options used to initialize a code cell widget.
     */
    _createCodeCellOptions() {
        let contentFactory = this.contentFactory;
        let modelFactory = this.modelFactory;
        let model = modelFactory.createCodeCell({});
        let rendermime = this.rendermime;
        return { model, rendermime, contentFactory };
    }
    /**
     * Handle cell disposed signals.
     */
    _onCellDisposed(sender, args) {
        if (!this.isDisposed) {
            this._cells.removeValue(sender);
        }
    }
    /**
     * Test whether we should execute the prompt cell.
     */
    _shouldExecute(timeout) {
        const promptCell = this.promptCell;
        if (!promptCell) {
            return Promise.resolve(false);
        }
        let model = promptCell.model;
        let code = model.value.text;
        return new Promise((resolve, reject) => {
            let timer = setTimeout(() => {
                resolve(true);
            }, timeout);
            let kernel = this.session.kernel;
            if (!kernel) {
                resolve(false);
                return;
            }
            kernel
                .requestIsComplete({ code })
                .then(isComplete => {
                clearTimeout(timer);
                if (this.isDisposed) {
                    resolve(false);
                }
                if (isComplete.content.status !== 'incomplete') {
                    resolve(true);
                    return;
                }
                resolve(false);
            })
                .catch(() => {
                resolve(true);
            });
        });
    }
    /**
     * Handle a keydown event on an editor.
     */
    _onEditorKeydown(editor, event) {
        // Suppress "Enter" events.
        return event.keyCode === 13;
    }
    /**
     * Handle a change to the kernel.
     */
    _onKernelChanged() {
        this.clear();
        if (this._banner) {
            this._banner.dispose();
            this._banner = null;
        }
        this.addBanner();
    }
    /**
     * Handle a change to the kernel status.
     */
    _onKernelStatusChanged() {
        if (this.session.status === 'connected') {
            // we just had a kernel restart or reconnect - reset banner
            let kernel = this.session.kernel;
            if (!kernel) {
                return;
            }
            kernel
                .requestKernelInfo()
                .then(() => {
                if (this.isDisposed || !kernel || !kernel.info) {
                    return;
                }
                this._handleInfo(this.session.kernel.info);
            })
                .catch(err => {
                console.error('could not get kernel info');
            });
        }
        else if (this.session.status === 'restarting') {
            this.addBanner();
        }
    }
}
exports.CodeConsole = CodeConsole;
/**
 * A namespace for CodeConsole statics.
 */
(function (CodeConsole) {
    /**
     * Default implementation of `IContentFactory`.
     */
    class ContentFactory extends cells_1.Cell.ContentFactory {
        /**
         * Create a new code cell widget.
         *
         * #### Notes
         * If no cell content factory is passed in with the options, the one on the
         * notebook content factory is used.
         */
        createCodeCell(options) {
            if (!options.contentFactory) {
                options.contentFactory = this;
            }
            return new cells_1.CodeCell(options);
        }
        /**
         * Create a new raw cell widget.
         *
         * #### Notes
         * If no cell content factory is passed in with the options, the one on the
         * notebook content factory is used.
         */
        createRawCell(options) {
            if (!options.contentFactory) {
                options.contentFactory = this;
            }
            return new cells_1.RawCell(options);
        }
    }
    CodeConsole.ContentFactory = ContentFactory;
    /**
     * A default content factory for the code console.
     */
    CodeConsole.defaultContentFactory = new ContentFactory();
    /**
     * The default implementation of an `IModelFactory`.
     */
    class ModelFactory {
        /**
         * Create a new cell model factory.
         */
        constructor(options = {}) {
            this.codeCellContentFactory =
                options.codeCellContentFactory || cells_1.CodeCellModel.defaultContentFactory;
        }
        /**
         * Create a new code cell.
         *
         * @param source - The data to use for the original source data.
         *
         * @returns A new code cell. If a source cell is provided, the
         *   new cell will be initialized with the data from the source.
         *   If the contentFactory is not provided, the instance
         *   `codeCellContentFactory` will be used.
         */
        createCodeCell(options) {
            if (!options.contentFactory) {
                options.contentFactory = this.codeCellContentFactory;
            }
            return new cells_1.CodeCellModel(options);
        }
        /**
         * Create a new raw cell.
         *
         * @param source - The data to use for the original source data.
         *
         * @returns A new raw cell. If a source cell is provided, the
         *   new cell will be initialized with the data from the source.
         */
        createRawCell(options) {
            return new cells_1.RawCellModel(options);
        }
    }
    CodeConsole.ModelFactory = ModelFactory;
    /**
     * The default `ModelFactory` instance.
     */
    CodeConsole.defaultModelFactory = new ModelFactory({});
})(CodeConsole = exports.CodeConsole || (exports.CodeConsole = {}));
/**
 * A namespace for console widget private data.
 */
var Private;
(function (Private) {
    /**
     * Jump to the bottom of a node.
     *
     * @param node - The scrollable element.
     */
    function scrollToBottom(node) {
        node.scrollTop = node.scrollHeight - node.clientHeight;
    }
    Private.scrollToBottom = scrollToBottom;
})(Private || (Private = {}));


/***/ }),

/***/ "wKab":
/*!*************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotAreaStackedIcon.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotAreaStackedIcon = function PlotAreaStackedIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M0 25.25v6.125h32v-10.25h-1.813L20.124 25l-7.313-6.688zm0-8.312v4.5l12.813-6.813 7.25 6.813 9.938-3.813h2v-16l-9.813 10.688-8.313-8.875z' })
    );
};

exports.default = PlotAreaStackedIcon;

/***/ }),

/***/ "wLZx":
/*!********************************************************************!*\
  !*** ./node_modules/@jupyterlab/completer/lib/contextconnector.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
/**
 * A context connector for completion handlers.
 */
class ContextConnector extends coreutils_1.DataConnector {
    /**
     * Create a new context connector for completion requests.
     *
     * @param options - The instatiation options for the context connector.
     */
    constructor(options) {
        super();
        this._editor = options.editor;
    }
    /**
     * Fetch completion requests.
     *
     * @param request - The completion request text and details.
     */
    fetch(request) {
        return new Promise(resolve => {
            resolve(Private.contextHint(this._editor));
        });
    }
}
exports.ContextConnector = ContextConnector;
/**
 * A namespace for Private functionality.
 */
var Private;
(function (Private) {
    /**
     * Get a list of completion hints from a tokenization
     * of the editor.
     */
    function contextHint(editor) {
        // Find the token at the cursor
        const cursor = editor.getCursorPosition();
        const token = editor.getTokenForPosition(cursor);
        // Get the list of matching tokens.
        const tokenList = getCompletionTokens(token, editor);
        // Only choose the ones that have a non-empty type
        // field, which are likely to be of interest.
        const completionList = tokenList.filter(t => t.type).map(t => t.value);
        // Remove duplicate completsions from the list
        const matches = Array.from(new Set(completionList));
        return {
            start: token.offset,
            end: token.offset + token.value.length,
            matches,
            metadata: {}
        };
    }
    Private.contextHint = contextHint;
    /**
     * Get a list of tokens that match the completion request,
     * but are not identical to the completion request.
     */
    function getCompletionTokens(token, editor) {
        const candidates = editor.getTokens();
        // Only get the tokens that have a common start, but
        // are not identical.
        return candidates.filter(t => t.value.indexOf(token.value) === 0 && t.value !== token.value);
    }
})(Private || (Private = {}));


/***/ }),

/***/ "wME1":
/*!************************************************************!*\
  !*** ./node_modules/material-colors/dist/colors.es2015.js ***!
  \************************************************************/
/*! exports provided: red, pink, purple, deepPurple, indigo, blue, lightBlue, cyan, teal, green, lightGreen, lime, yellow, amber, orange, deepOrange, brown, grey, blueGrey, darkText, lightText, darkIcons, lightIcons, white, black, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "red", function() { return red; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pink", function() { return pink; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "purple", function() { return purple; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deepPurple", function() { return deepPurple; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "indigo", function() { return indigo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "blue", function() { return blue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "lightBlue", function() { return lightBlue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cyan", function() { return cyan; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "teal", function() { return teal; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "green", function() { return green; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "lightGreen", function() { return lightGreen; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "lime", function() { return lime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yellow", function() { return yellow; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "amber", function() { return amber; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "orange", function() { return orange; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deepOrange", function() { return deepOrange; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "brown", function() { return brown; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "grey", function() { return grey; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "blueGrey", function() { return blueGrey; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "darkText", function() { return darkText; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "lightText", function() { return lightText; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "darkIcons", function() { return darkIcons; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "lightIcons", function() { return lightIcons; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "white", function() { return white; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "black", function() { return black; });
var red = {"50":"#ffebee","100":"#ffcdd2","200":"#ef9a9a","300":"#e57373","400":"#ef5350","500":"#f44336","600":"#e53935","700":"#d32f2f","800":"#c62828","900":"#b71c1c","a100":"#ff8a80","a200":"#ff5252","a400":"#ff1744","a700":"#d50000"};
var pink = {"50":"#fce4ec","100":"#f8bbd0","200":"#f48fb1","300":"#f06292","400":"#ec407a","500":"#e91e63","600":"#d81b60","700":"#c2185b","800":"#ad1457","900":"#880e4f","a100":"#ff80ab","a200":"#ff4081","a400":"#f50057","a700":"#c51162"};
var purple = {"50":"#f3e5f5","100":"#e1bee7","200":"#ce93d8","300":"#ba68c8","400":"#ab47bc","500":"#9c27b0","600":"#8e24aa","700":"#7b1fa2","800":"#6a1b9a","900":"#4a148c","a100":"#ea80fc","a200":"#e040fb","a400":"#d500f9","a700":"#aa00ff"};
var deepPurple = {"50":"#ede7f6","100":"#d1c4e9","200":"#b39ddb","300":"#9575cd","400":"#7e57c2","500":"#673ab7","600":"#5e35b1","700":"#512da8","800":"#4527a0","900":"#311b92","a100":"#b388ff","a200":"#7c4dff","a400":"#651fff","a700":"#6200ea"};
var indigo = {"50":"#e8eaf6","100":"#c5cae9","200":"#9fa8da","300":"#7986cb","400":"#5c6bc0","500":"#3f51b5","600":"#3949ab","700":"#303f9f","800":"#283593","900":"#1a237e","a100":"#8c9eff","a200":"#536dfe","a400":"#3d5afe","a700":"#304ffe"};
var blue = {"50":"#e3f2fd","100":"#bbdefb","200":"#90caf9","300":"#64b5f6","400":"#42a5f5","500":"#2196f3","600":"#1e88e5","700":"#1976d2","800":"#1565c0","900":"#0d47a1","a100":"#82b1ff","a200":"#448aff","a400":"#2979ff","a700":"#2962ff"};
var lightBlue = {"50":"#e1f5fe","100":"#b3e5fc","200":"#81d4fa","300":"#4fc3f7","400":"#29b6f6","500":"#03a9f4","600":"#039be5","700":"#0288d1","800":"#0277bd","900":"#01579b","a100":"#80d8ff","a200":"#40c4ff","a400":"#00b0ff","a700":"#0091ea"};
var cyan = {"50":"#e0f7fa","100":"#b2ebf2","200":"#80deea","300":"#4dd0e1","400":"#26c6da","500":"#00bcd4","600":"#00acc1","700":"#0097a7","800":"#00838f","900":"#006064","a100":"#84ffff","a200":"#18ffff","a400":"#00e5ff","a700":"#00b8d4"};
var teal = {"50":"#e0f2f1","100":"#b2dfdb","200":"#80cbc4","300":"#4db6ac","400":"#26a69a","500":"#009688","600":"#00897b","700":"#00796b","800":"#00695c","900":"#004d40","a100":"#a7ffeb","a200":"#64ffda","a400":"#1de9b6","a700":"#00bfa5"};
var green = {"50":"#e8f5e9","100":"#c8e6c9","200":"#a5d6a7","300":"#81c784","400":"#66bb6a","500":"#4caf50","600":"#43a047","700":"#388e3c","800":"#2e7d32","900":"#1b5e20","a100":"#b9f6ca","a200":"#69f0ae","a400":"#00e676","a700":"#00c853"};
var lightGreen = {"50":"#f1f8e9","100":"#dcedc8","200":"#c5e1a5","300":"#aed581","400":"#9ccc65","500":"#8bc34a","600":"#7cb342","700":"#689f38","800":"#558b2f","900":"#33691e","a100":"#ccff90","a200":"#b2ff59","a400":"#76ff03","a700":"#64dd17"};
var lime = {"50":"#f9fbe7","100":"#f0f4c3","200":"#e6ee9c","300":"#dce775","400":"#d4e157","500":"#cddc39","600":"#c0ca33","700":"#afb42b","800":"#9e9d24","900":"#827717","a100":"#f4ff81","a200":"#eeff41","a400":"#c6ff00","a700":"#aeea00"};
var yellow = {"50":"#fffde7","100":"#fff9c4","200":"#fff59d","300":"#fff176","400":"#ffee58","500":"#ffeb3b","600":"#fdd835","700":"#fbc02d","800":"#f9a825","900":"#f57f17","a100":"#ffff8d","a200":"#ffff00","a400":"#ffea00","a700":"#ffd600"};
var amber = {"50":"#fff8e1","100":"#ffecb3","200":"#ffe082","300":"#ffd54f","400":"#ffca28","500":"#ffc107","600":"#ffb300","700":"#ffa000","800":"#ff8f00","900":"#ff6f00","a100":"#ffe57f","a200":"#ffd740","a400":"#ffc400","a700":"#ffab00"};
var orange = {"50":"#fff3e0","100":"#ffe0b2","200":"#ffcc80","300":"#ffb74d","400":"#ffa726","500":"#ff9800","600":"#fb8c00","700":"#f57c00","800":"#ef6c00","900":"#e65100","a100":"#ffd180","a200":"#ffab40","a400":"#ff9100","a700":"#ff6d00"};
var deepOrange = {"50":"#fbe9e7","100":"#ffccbc","200":"#ffab91","300":"#ff8a65","400":"#ff7043","500":"#ff5722","600":"#f4511e","700":"#e64a19","800":"#d84315","900":"#bf360c","a100":"#ff9e80","a200":"#ff6e40","a400":"#ff3d00","a700":"#dd2c00"};
var brown = {"50":"#efebe9","100":"#d7ccc8","200":"#bcaaa4","300":"#a1887f","400":"#8d6e63","500":"#795548","600":"#6d4c41","700":"#5d4037","800":"#4e342e","900":"#3e2723"};
var grey = {"50":"#fafafa","100":"#f5f5f5","200":"#eeeeee","300":"#e0e0e0","400":"#bdbdbd","500":"#9e9e9e","600":"#757575","700":"#616161","800":"#424242","900":"#212121"};
var blueGrey = {"50":"#eceff1","100":"#cfd8dc","200":"#b0bec5","300":"#90a4ae","400":"#78909c","500":"#607d8b","600":"#546e7a","700":"#455a64","800":"#37474f","900":"#263238"};
var darkText = {"primary":"rgba(0, 0, 0, 0.87)","secondary":"rgba(0, 0, 0, 0.54)","disabled":"rgba(0, 0, 0, 0.38)","dividers":"rgba(0, 0, 0, 0.12)"};
var lightText = {"primary":"rgba(255, 255, 255, 1)","secondary":"rgba(255, 255, 255, 0.7)","disabled":"rgba(255, 255, 255, 0.5)","dividers":"rgba(255, 255, 255, 0.12)"};
var darkIcons = {"active":"rgba(0, 0, 0, 0.54)","inactive":"rgba(0, 0, 0, 0.38)"};
var lightIcons = {"active":"rgba(255, 255, 255, 1)","inactive":"rgba(255, 255, 255, 0.5)"};
var white = "#ffffff";
var black = "#000000";

/* harmony default export */ __webpack_exports__["default"] = ({
  red: red,
  pink: pink,
  purple: purple,
  deepPurple: deepPurple,
  indigo: indigo,
  blue: blue,
  lightBlue: lightBlue,
  cyan: cyan,
  teal: teal,
  green: green,
  lightGreen: lightGreen,
  lime: lime,
  yellow: yellow,
  amber: amber,
  orange: orange,
  deepOrange: deepOrange,
  brown: brown,
  grey: grey,
  blueGrey: blueGrey,
  darkText: darkText,
  lightText: lightText,
  darkIcons: darkIcons,
  lightIcons: lightIcons,
  white: white,
  black: black
});


/***/ }),

/***/ "wQXC":
/*!*********************************************************************!*\
  !*** ./node_modules/@mflevine/jupyterlab_html/style/html5-icon.svg ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA1MTIgNTEyIj4NCgk8dGl0bGU+SFRNTDUgTG9nbzwvdGl0bGU+DQoJPHBhdGggZD0iTTEwOC40IDBoMjN2MjIuOGgyMS4yVjBoMjN2NjloLTIzVjQ2aC0yMXYyM2gtMjMuMk0yMDYgMjNoLTIwLjNWMGg2My43djIzSDIyOXY0NmgtMjNNMjU5LjUgMGgyNC4xbDE0LjggMjQuM0wzMTMuMiAwaDI0LjF2NjloLTIzVjM0LjhsLTE2LjEgMjQuOGwtMTYuMS0yNC44djM0LjJoLTIyLjZNMzQ4LjcgMGgyM3Y0Ni4yaDMyLjZWNjloLTU1LjYiLz4NCgk8cGF0aCBmaWxsPSIjZTQ0ZDI2IiBkPSJNMTA3LjYgNDcxbC0zMy0zNzAuNGgzNjIuOGwtMzMgMzcwLjJMMjU1LjcgNTEyIi8+DQoJPHBhdGggZmlsbD0iI2YxNjUyOSIgZD0iTTI1NiA0ODAuNVYxMzFINDA0LjNMMzc2IDQ0NyIvPg0KCTxwYXRoIGZpbGw9IiNlYmViZWIiIGQ9Ik0xNDIgMTc2LjNoMTE0djQ1LjRoLTY0LjJsNC4yIDQ2LjVoNjB2NDUuM0gxNTQuNE0xNTYuNCAzMzYuM0gyMDJsMy4yIDM2LjMgNTAuOCAxMy42djQ3LjRsLTkzLjItMjYiLz4NCgk8cGF0aCBmaWxsPSIjZmZmIiBkPSJNMzY5LjYgMTc2LjNIMjU1Ljh2NDUuNGgxMDkuNk0zNjEuMyAyNjguMkgyNTUuOHY0NS40aDU2bC01LjMgNTktNTAuNyAxMy42djQ3LjJsOTMtMjUuOCIvPg0KPC9zdmc+"

/***/ }),

/***/ "wQk9":
/*!*******************************************!*\
  !*** ./node_modules/moment/locale/tzm.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var tzm = moment.defineLocale('tzm', {
    months : 'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split('_'),
    monthsShort : 'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split('_'),
    weekdays : 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'),
    weekdaysShort : 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'),
    weekdaysMin : 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS: 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay: '[ⴰⵙⴷⵅ ⴴ] LT',
        nextDay: '[ⴰⵙⴽⴰ ⴴ] LT',
        nextWeek: 'dddd [ⴴ] LT',
        lastDay: '[ⴰⵚⴰⵏⵜ ⴴ] LT',
        lastWeek: 'dddd [ⴴ] LT',
        sameElse: 'L'
    },
    relativeTime : {
        future : 'ⴷⴰⴷⵅ ⵙ ⵢⴰⵏ %s',
        past : 'ⵢⴰⵏ %s',
        s : 'ⵉⵎⵉⴽ',
        ss : '%d ⵉⵎⵉⴽ',
        m : 'ⵎⵉⵏⵓⴺ',
        mm : '%d ⵎⵉⵏⵓⴺ',
        h : 'ⵙⴰⵄⴰ',
        hh : '%d ⵜⴰⵙⵙⴰⵄⵉⵏ',
        d : 'ⴰⵙⵙ',
        dd : '%d oⵙⵙⴰⵏ',
        M : 'ⴰⵢoⵓⵔ',
        MM : '%d ⵉⵢⵢⵉⵔⵏ',
        y : 'ⴰⵙⴳⴰⵙ',
        yy : '%d ⵉⵙⴳⴰⵙⵏ'
    },
    week : {
        dow : 6, // Saturday is the first day of the week.
        doy : 12  // The week that contains Jan 1st is the first week of the year.
    }
});

return tzm;

})));


/***/ }),

/***/ "wQnj":
/*!************************************************************!*\
  !*** ./node_modules/pure-color/parse/extractComponents.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

var component = /-?\d+(\.\d+)?%?/g;
function extractComponents(color) {
  return color.match(component);
}

module.exports = extractComponents;

/***/ }),

/***/ "wRn4":
/*!**************************************************!*\
  !*** ./node_modules/browserify-aes/modes/cbc.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var xor = __webpack_require__(/*! buffer-xor */ "jIre")

exports.encrypt = function (self, block) {
  var data = xor(block, self._prev)

  self._prev = self._cipher.encryptBlock(data)
  return self._prev
}

exports.decrypt = function (self, block) {
  var pad = self._prev

  self._prev = block
  var out = self._cipher.decryptBlock(block)

  return xor(out, pad)
}


/***/ }),

/***/ "wSGS":
/*!**************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/apputils/style/dialog.css ***!
  \**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, Jupyter Development Team.\n|\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.jp-Dialog {\n  position: absolute;\n  z-index: 10000;\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  top: 0px;\n  left: 0px;\n  margin: 0;\n  padding: 0;\n  width: 100%;\n  height: 100%;\n  background: var(--jp-dialog-background);\n}\n\n.jp-Dialog-content {\n  display: flex;\n  flex-direction: column;\n  margin-left: auto;\n  margin-right: auto;\n  background: var(--jp-layout-color1);\n  padding: 24px;\n  padding-bottom: 12px;\n  min-width: 300px;\n  min-height: 150px;\n  max-width: 500px;\n  max-height: 500px;\n  box-sizing: border-box;\n  box-shadow: var(--jp-elevation-z20);\n  word-wrap: break-word;\n  border-radius: var(--jp-border-radius);\n  /* This is needed so that all font sizing of children done in ems is\n   * relative to this base size */\n  font-size: var(--jp-ui-font-size1);\n  color: var(--jp-ui-font-color1);\n}\n\n.jp-Dialog-header {\n  flex: 0 0 auto;\n  padding-bottom: 12px;\n  font-size: var(--jp-ui-font-size3);\n  font-weight: 400;\n  color: var(--jp-ui-font-color0);\n}\n\n.jp-Dialog-body {\n  display: flex;\n  flex-direction: column;\n  flex: 1 1 auto;\n  font-size: var(--jp-ui-font-size1);\n  background: var(--jp-layout-color1);\n  overflow: auto;\n}\n\n.jp-Dialog-footer {\n  display: flex;\n  flex-direction: row;\n  justify-content: flex-end;\n  flex: 0 0 auto;\n  margin-left: -12px;\n  margin-right: -12px;\n  padding: 12px;\n}\n\n.jp-Dialog-title {\n  overflow: hidden;\n  white-space: nowrap;\n  text-overflow: ellipsis;\n}\n\n.jp-Dialog-body > .jp-select-wrapper {\n  width: 100%;\n}\n\n.jp-Dialog-body > button {\n  padding: 0px 16px;\n}\n\n.jp-Dialog-body > label {\n  padding-top: 4px;\n  padding-bottom: 8px;\n  line-height: 1.4;\n  color: var(--jp-ui-font-color0);\n}\n\n.jp-Dialog-button.jp-mod-styled:not(:last-child) {\n  margin-right: 12px;\n}\n", ""]);

// exports


/***/ }),

/***/ "wTZr":
/*!*******************************************************!*\
  !*** ./node_modules/draft-js-import-html/lib/main.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _stateFromHTML = __webpack_require__(/*! ./stateFromHTML */ "r+9r");

Object.defineProperty(exports, 'stateFromHTML', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_stateFromHTML).default;
  }
});

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/***/ }),

/***/ "wWcZ":
/*!*********************************************************************!*\
  !*** ./node_modules/sanitize-html/node_modules/postcss/lib/node.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _cssSyntaxError = __webpack_require__(/*! ./css-syntax-error */ "RTLL");

var _cssSyntaxError2 = _interopRequireDefault(_cssSyntaxError);

var _stringifier = __webpack_require__(/*! ./stringifier */ "ZyGS");

var _stringifier2 = _interopRequireDefault(_stringifier);

var _stringify = __webpack_require__(/*! ./stringify */ "3ZTG");

var _stringify2 = _interopRequireDefault(_stringify);

var _warnOnce = __webpack_require__(/*! ./warn-once */ "thcq");

var _warnOnce2 = _interopRequireDefault(_warnOnce);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var cloneNode = function cloneNode(obj, parent) {
    var cloned = new obj.constructor();

    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        var value = obj[i];
        var type = typeof value === 'undefined' ? 'undefined' : _typeof(value);

        if (i === 'parent' && type === 'object') {
            if (parent) cloned[i] = parent;
        } else if (i === 'source') {
            cloned[i] = value;
        } else if (value instanceof Array) {
            cloned[i] = value.map(function (j) {
                return cloneNode(j, cloned);
            });
        } else {
            if (type === 'object' && value !== null) value = cloneNode(value);
            cloned[i] = value;
        }
    }

    return cloned;
};

/**
 * All node classes inherit the following common methods.
 *
 * @abstract
 */

var Node = function () {

    /**
     * @param {object} [defaults] - value for node properties
     */
    function Node() {
        var defaults = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

        _classCallCheck(this, Node);

        this.raws = {};
        if ((typeof defaults === 'undefined' ? 'undefined' : _typeof(defaults)) !== 'object' && typeof defaults !== 'undefined') {
            throw new Error('PostCSS nodes constructor accepts object, not ' + JSON.stringify(defaults));
        }
        for (var name in defaults) {
            this[name] = defaults[name];
        }
    }

    /**
     * Returns a CssSyntaxError instance containing the original position
     * of the node in the source, showing line and column numbers and also
     * a small excerpt to facilitate debugging.
     *
     * If present, an input source map will be used to get the original position
     * of the source, even from a previous compilation step
     * (e.g., from Sass compilation).
     *
     * This method produces very useful error messages.
     *
     * @param {string} message     - error description
     * @param {object} [opts]      - options
     * @param {string} opts.plugin - plugin name that created this error.
     *                               PostCSS will set it automatically.
     * @param {string} opts.word   - a word inside a node’s string that should
     *                               be highlighted as the source of the error
     * @param {number} opts.index  - an index inside a node’s string that should
     *                               be highlighted as the source of the error
     *
     * @return {CssSyntaxError} error object to throw it
     *
     * @example
     * if ( !variables[name] ) {
     *   throw decl.error('Unknown variable ' + name, { word: name });
     *   // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
     *   //   color: $black
     *   // a
     *   //          ^
     *   //   background: white
     * }
     */


    Node.prototype.error = function error(message) {
        var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

        if (this.source) {
            var pos = this.positionBy(opts);
            return this.source.input.error(message, pos.line, pos.column, opts);
        } else {
            return new _cssSyntaxError2.default(message);
        }
    };

    /**
     * This method is provided as a convenience wrapper for {@link Result#warn}.
     *
     * @param {Result} result      - the {@link Result} instance
     *                               that will receive the warning
     * @param {string} text        - warning message
     * @param {object} [opts]      - options
     * @param {string} opts.plugin - plugin name that created this warning.
     *                               PostCSS will set it automatically.
     * @param {string} opts.word   - a word inside a node’s string that should
     *                               be highlighted as the source of the warning
     * @param {number} opts.index  - an index inside a node’s string that should
     *                               be highlighted as the source of the warning
     *
     * @return {Warning} created warning object
     *
     * @example
     * const plugin = postcss.plugin('postcss-deprecated', () => {
     *   return (root, result) => {
     *     root.walkDecls('bad', decl => {
     *       decl.warn(result, 'Deprecated property bad');
     *     });
     *   };
     * });
     */


    Node.prototype.warn = function warn(result, text, opts) {
        var data = { node: this };
        for (var i in opts) {
            data[i] = opts[i];
        }return result.warn(text, data);
    };

    /**
     * Removes the node from its parent and cleans the parent properties
     * from the node and its children.
     *
     * @example
     * if ( decl.prop.match(/^-webkit-/) ) {
     *   decl.remove();
     * }
     *
     * @return {Node} node to make calls chain
     */


    Node.prototype.remove = function remove() {
        if (this.parent) {
            this.parent.removeChild(this);
        }
        this.parent = undefined;
        return this;
    };

    /**
     * Returns a CSS string representing the node.
     *
     * @param {stringifier|syntax} [stringifier] - a syntax to use
     *                                             in string generation
     *
     * @return {string} CSS string of this node
     *
     * @example
     * postcss.rule({ selector: 'a' }).toString() //=> "a {}"
     */


    Node.prototype.toString = function toString() {
        var stringifier = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _stringify2.default;

        if (stringifier.stringify) stringifier = stringifier.stringify;
        var result = '';
        stringifier(this, function (i) {
            result += i;
        });
        return result;
    };

    /**
     * Returns a clone of the node.
     *
     * The resulting cloned node and its (cloned) children will have
     * a clean parent and code style properties.
     *
     * @param {object} [overrides] - new properties to override in the clone.
     *
     * @example
     * const cloned = decl.clone({ prop: '-moz-' + decl.prop });
     * cloned.raws.before  //=> undefined
     * cloned.parent       //=> undefined
     * cloned.toString()   //=> -moz-transform: scale(0)
     *
     * @return {Node} clone of the node
     */


    Node.prototype.clone = function clone() {
        var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

        var cloned = cloneNode(this);
        for (var name in overrides) {
            cloned[name] = overrides[name];
        }
        return cloned;
    };

    /**
     * Shortcut to clone the node and insert the resulting cloned node
     * before the current node.
     *
     * @param {object} [overrides] - new properties to override in the clone.
     *
     * @example
     * decl.cloneBefore({ prop: '-moz-' + decl.prop });
     *
     * @return {Node} - new node
     */


    Node.prototype.cloneBefore = function cloneBefore() {
        var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

        var cloned = this.clone(overrides);
        this.parent.insertBefore(this, cloned);
        return cloned;
    };

    /**
     * Shortcut to clone the node and insert the resulting cloned node
     * after the current node.
     *
     * @param {object} [overrides] - new properties to override in the clone.
     *
     * @return {Node} - new node
     */


    Node.prototype.cloneAfter = function cloneAfter() {
        var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

        var cloned = this.clone(overrides);
        this.parent.insertAfter(this, cloned);
        return cloned;
    };

    /**
     * Inserts node(s) before the current node and removes the current node.
     *
     * @param {...Node} nodes - node(s) to replace current one
     *
     * @example
     * if ( atrule.name == 'mixin' ) {
     *   atrule.replaceWith(mixinRules[atrule.params]);
     * }
     *
     * @return {Node} current node to methods chain
     */


    Node.prototype.replaceWith = function replaceWith() {
        if (this.parent) {
            for (var _len = arguments.length, nodes = Array(_len), _key = 0; _key < _len; _key++) {
                nodes[_key] = arguments[_key];
            }

            for (var _iterator = nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
                var _ref;

                if (_isArray) {
                    if (_i >= _iterator.length) break;
                    _ref = _iterator[_i++];
                } else {
                    _i = _iterator.next();
                    if (_i.done) break;
                    _ref = _i.value;
                }

                var node = _ref;

                this.parent.insertBefore(this, node);
            }

            this.remove();
        }

        return this;
    };

    Node.prototype.moveTo = function moveTo(newParent) {
        (0, _warnOnce2.default)('Node#moveTo was deprecated. Use Container#append.');
        this.cleanRaws(this.root() === newParent.root());
        this.remove();
        newParent.append(this);
        return this;
    };

    Node.prototype.moveBefore = function moveBefore(otherNode) {
        (0, _warnOnce2.default)('Node#moveBefore was deprecated. Use Node#before.');
        this.cleanRaws(this.root() === otherNode.root());
        this.remove();
        otherNode.parent.insertBefore(otherNode, this);
        return this;
    };

    Node.prototype.moveAfter = function moveAfter(otherNode) {
        (0, _warnOnce2.default)('Node#moveAfter was deprecated. Use Node#after.');
        this.cleanRaws(this.root() === otherNode.root());
        this.remove();
        otherNode.parent.insertAfter(otherNode, this);
        return this;
    };

    /**
     * Returns the next child of the node’s parent.
     * Returns `undefined` if the current node is the last child.
     *
     * @return {Node|undefined} next node
     *
     * @example
     * if ( comment.text === 'delete next' ) {
     *   const next = comment.next();
     *   if ( next ) {
     *     next.remove();
     *   }
     * }
     */


    Node.prototype.next = function next() {
        if (!this.parent) return undefined;
        var index = this.parent.index(this);
        return this.parent.nodes[index + 1];
    };

    /**
     * Returns the previous child of the node’s parent.
     * Returns `undefined` if the current node is the first child.
     *
     * @return {Node|undefined} previous node
     *
     * @example
     * const annotation = decl.prev();
     * if ( annotation.type == 'comment' ) {
     *  readAnnotation(annotation.text);
     * }
     */


    Node.prototype.prev = function prev() {
        if (!this.parent) return undefined;
        var index = this.parent.index(this);
        return this.parent.nodes[index - 1];
    };

    /**
     * Insert new node before current node to current node’s parent.
     *
     * Just alias for `node.parent.insertBefore(node, add)`.
     *
     * @param {Node|object|string|Node[]} add - new node
     *
     * @return {Node} this node for methods chain.
     *
     * @example
     * decl.before('content: ""');
     */


    Node.prototype.before = function before(add) {
        this.parent.insertBefore(this, add);
        return this;
    };

    /**
     * Insert new node after current node to current node’s parent.
     *
     * Just alias for `node.parent.insertAfter(node, add)`.
     *
     * @param {Node|object|string|Node[]} add - new node
     *
     * @return {Node} this node for methods chain.
     *
     * @example
     * decl.after('color: black');
     */


    Node.prototype.after = function after(add) {
        this.parent.insertAfter(this, add);
        return this;
    };

    Node.prototype.toJSON = function toJSON() {
        var fixed = {};

        for (var name in this) {
            if (!this.hasOwnProperty(name)) continue;
            if (name === 'parent') continue;
            var value = this[name];

            if (value instanceof Array) {
                fixed[name] = value.map(function (i) {
                    if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object' && i.toJSON) {
                        return i.toJSON();
                    } else {
                        return i;
                    }
                });
            } else if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && value.toJSON) {
                fixed[name] = value.toJSON();
            } else {
                fixed[name] = value;
            }
        }

        return fixed;
    };

    /**
     * Returns a {@link Node#raws} value. If the node is missing
     * the code style property (because the node was manually built or cloned),
     * PostCSS will try to autodetect the code style property by looking
     * at other nodes in the tree.
     *
     * @param {string} prop          - name of code style property
     * @param {string} [defaultType] - name of default value, it can be missed
     *                                 if the value is the same as prop
     *
     * @example
     * const root = postcss.parse('a { background: white }');
     * root.nodes[0].append({ prop: 'color', value: 'black' });
     * root.nodes[0].nodes[1].raws.before   //=> undefined
     * root.nodes[0].nodes[1].raw('before') //=> ' '
     *
     * @return {string} code style value
     */


    Node.prototype.raw = function raw(prop, defaultType) {
        var str = new _stringifier2.default();
        return str.raw(this, prop, defaultType);
    };

    /**
     * Finds the Root instance of the node’s tree.
     *
     * @example
     * root.nodes[0].nodes[0].root() === root
     *
     * @return {Root} root parent
     */


    Node.prototype.root = function root() {
        var result = this;
        while (result.parent) {
            result = result.parent;
        }return result;
    };

    Node.prototype.cleanRaws = function cleanRaws(keepBetween) {
        delete this.raws.before;
        delete this.raws.after;
        if (!keepBetween) delete this.raws.between;
    };

    Node.prototype.positionInside = function positionInside(index) {
        var string = this.toString();
        var column = this.source.start.column;
        var line = this.source.start.line;

        for (var i = 0; i < index; i++) {
            if (string[i] === '\n') {
                column = 1;
                line += 1;
            } else {
                column += 1;
            }
        }

        return { line: line, column: column };
    };

    Node.prototype.positionBy = function positionBy(opts) {
        var pos = this.source.start;
        if (opts.index) {
            pos = this.positionInside(opts.index);
        } else if (opts.word) {
            var index = this.toString().indexOf(opts.word);
            if (index !== -1) pos = this.positionInside(index);
        }
        return pos;
    };

    /**
     * @memberof Node#
     * @member {string} type - String representing the node’s type.
     *                         Possible values are `root`, `atrule`, `rule`,
     *                         `decl`, or `comment`.
     *
     * @example
     * postcss.decl({ prop: 'color', value: 'black' }).type //=> 'decl'
     */

    /**
     * @memberof Node#
     * @member {Container} parent - the node’s parent node.
     *
     * @example
     * root.nodes[0].parent == root;
     */

    /**
     * @memberof Node#
     * @member {source} source - the input source of the node
     *
     * The property is used in source map generation.
     *
     * If you create a node manually (e.g., with `postcss.decl()`),
     * that node will not have a `source` property and will be absent
     * from the source map. For this reason, the plugin developer should
     * consider cloning nodes to create new ones (in which case the new node’s
     * source will reference the original, cloned node) or setting
     * the `source` property manually.
     *
     * ```js
     * // Bad
     * const prefixed = postcss.decl({
     *   prop: '-moz-' + decl.prop,
     *   value: decl.value
     * });
     *
     * // Good
     * const prefixed = decl.clone({ prop: '-moz-' + decl.prop });
     * ```
     *
     * ```js
     * if ( atrule.name == 'add-link' ) {
     *   const rule = postcss.rule({ selector: 'a', source: atrule.source });
     *   atrule.parent.insertBefore(atrule, rule);
     * }
     * ```
     *
     * @example
     * decl.source.input.from //=> '/home/ai/a.sass'
     * decl.source.start      //=> { line: 10, column: 2 }
     * decl.source.end        //=> { line: 10, column: 12 }
     */

    /**
     * @memberof Node#
     * @member {object} raws - Information to generate byte-to-byte equal
     *                         node string as it was in the origin input.
     *
     * Every parser saves its own properties,
     * but the default CSS parser uses:
     *
     * * `before`: the space symbols before the node. It also stores `*`
     *   and `_` symbols before the declaration (IE hack).
     * * `after`: the space symbols after the last child of the node
     *   to the end of the node.
     * * `between`: the symbols between the property and value
     *   for declarations, selector and `{` for rules, or last parameter
     *   and `{` for at-rules.
     * * `semicolon`: contains true if the last child has
     *   an (optional) semicolon.
     * * `afterName`: the space between the at-rule name and its parameters.
     * * `left`: the space symbols between `/*` and the comment’s text.
     * * `right`: the space symbols between the comment’s text
     *   and <code>*&#47;</code>.
     * * `important`: the content of the important statement,
     *   if it is not just `!important`.
     *
     * PostCSS cleans selectors, declaration values and at-rule parameters
     * from comments and extra spaces, but it stores origin content in raws
     * properties. As such, if you don’t change a declaration’s value,
     * PostCSS will use the raw value with comments.
     *
     * @example
     * const root = postcss.parse('a {\n  color:black\n}')
     * root.first.first.raws //=> { before: '\n  ', between: ':' }
     */

    return Node;
}();

exports.default = Node;

/**
 * @typedef {object} position
 * @property {number} line   - source line in file
 * @property {number} column - source column in file
 */

/**
 * @typedef {object} source
 * @property {Input} input    - {@link Input} with input file
 * @property {position} start - The starting position of the node’s source
 * @property {position} end   - The ending position of the node’s source
 */

module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64, 


/***/ }),

/***/ "wXb+":
/*!***************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/notebook/style/toolbar.css ***!
  \***************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n/*-----------------------------------------------------------------------------\n| Variables\n|----------------------------------------------------------------------------*/\n\n/*-----------------------------------------------------------------------------\n\n/*-----------------------------------------------------------------------------\n| Styles\n|----------------------------------------------------------------------------*/\n\n.jp-NotebookPanel-toolbar {\n  padding: 2px;\n}\n\n/* select wrapper */\n.jp-Toolbar-item.jp-Notebook-toolbarCellType > .jp-select-wrapper {\n  height: 100%;\n  background-color: var(--jp-notebook-select-background);\n}\n\n.jp-Toolbar-item.jp-Notebook-toolbarCellType .jp-select-wrapper.jp-mod-focused {\n  border: none;\n  box-shadow: none;\n}\n\n/* Actual select element */\n.jp-Notebook-toolbarCellType select.jp-Notebook-toolbarCellTypeDropdown {\n  font-size: var(--jp-ui-font-size1);\n  background-size: 16px;\n  padding-right: 16px;\n  border: none;\n  border-radius: 0;\n  outline: none;\n  background-color: var(--jp-layout-color1);\n}\n", ""]);

// exports


/***/ }),

/***/ "wXyd":
/*!***********************************************!*\
  !*** ./node_modules/ajv/lib/compile/rules.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var ruleModules = __webpack_require__(/*! ./_rules */ "8sNi")
  , toHash = __webpack_require__(/*! ./util */ "+9rK").toHash;

module.exports = function rules() {
  var RULES = [
    { type: 'number',
      rules: [ { 'maximum': ['exclusiveMaximum'] },
               { 'minimum': ['exclusiveMinimum'] }, 'multipleOf', 'format'] },
    { type: 'string',
      rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] },
    { type: 'array',
      rules: [ 'maxItems', 'minItems', 'uniqueItems', 'contains', 'items' ] },
    { type: 'object',
      rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames',
               { 'properties': ['additionalProperties', 'patternProperties'] } ] },
    { rules: [ '$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf' ] }
  ];

  var ALL = [ 'type' ];
  var KEYWORDS = [
    'additionalItems', '$schema', 'id', 'title',
    'description', 'default', 'definitions'
  ];
  var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ];
  RULES.all = toHash(ALL);
  RULES.types = toHash(TYPES);

  RULES.forEach(function (group) {
    group.rules = group.rules.map(function (keyword) {
      var implKeywords;
      if (typeof keyword == 'object') {
        var key = Object.keys(keyword)[0];
        implKeywords = keyword[key];
        keyword = key;
        implKeywords.forEach(function (k) {
          ALL.push(k);
          RULES.all[k] = true;
        });
      }
      ALL.push(keyword);
      var rule = RULES.all[keyword] = {
        keyword: keyword,
        code: ruleModules[keyword],
        implements: implKeywords
      };
      return rule;
    });

    if (group.type) RULES.types[group.type] = group;
  });

  RULES.keywords = toHash(ALL.concat(KEYWORDS));
  RULES.custom = {};

  return RULES;
};


/***/ }),

/***/ "wajC":
/*!**************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/completer/style/index.css ***!
  \**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2016, Jupyter Development Team.\n|\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n:root {\n  --jp-private-completer-item-height: 22px;\n  /* Shift the baseline of the type character to align with the match text */\n  --jp-private-completer-type-offset: 2px;\n}\n\n.jp-Completer {\n  box-shadow: var(--jp-elevation-z6);\n  background: var(--jp-layout-color1);\n  color: var(--jp-content-font-color1);\n  border: var(--jp-border-width) solid var(--jp-border-color1);\n  list-style-type: none;\n  overflow-y: scroll;\n  overflow-x: auto;\n  padding: 0;\n  /* Position the completer relative to the text editor, align the '.' */\n  margin: 4px 0 0 -30px;\n  max-height: calc(\n    (10 * var(--jp-private-completer-item-height)) +\n      (2 * var(--jp-border-width))\n  );\n  min-height: calc(\n    var(--jp-private-completer-item-height) + (2 * var(--jp-border-width))\n  );\n  z-index: 10001;\n}\n\n.jp-Completer-item {\n  display: table-row;\n  box-sizing: border-box;\n  margin: 0;\n  padding: 0;\n  height: var(--jp-private-completer-item-height);\n  min-width: 150px;\n}\n\n.jp-Completer-item .jp-Completer-match {\n  display: table-cell;\n  box-sizing: border-box;\n  margin: 0;\n  padding: 0 8px 0 6px;\n  height: var(--jp-private-completer-item-height);\n  font-family: var(--jp-code-font-family);\n  font-size: var(--jp-code-font-size);\n  line-height: var(--jp-private-completer-item-height);\n}\n\n.jp-Completer-item .jp-Completer-type {\n  display: table-cell;\n  box-sizing: border-box;\n  height: var(--jp-private-completer-item-height);\n  text-align: center;\n  background: transparent;\n  color: white;\n  width: var(--jp-private-completer-item-height);\n  font-family: var(--jp-ui-font-family);\n  font-size: var(--jp-ui-font-size1);\n  line-height: calc(\n    var(--jp-private-completer-item-height) -\n      var(--jp-private-completer-type-offset)\n  );\n  padding-bottom: var(--jp-private-completer-type-offset);\n}\n\n.jp-Completer-item .jp-Completer-typeExtended {\n  display: table-cell;\n  box-sizing: border-box;\n  height: var(--jp-private-completer-item-height);\n  text-align: right;\n  background: transparent;\n  color: var(--jp-ui-font-color2);\n  font-family: var(--jp-code-font-family);\n  font-size: var(--jp-code-font-size);\n  line-height: var(--jp-private-completer-item-height);\n  padding-right: 8px;\n}\n\n.jp-Completer-item:hover {\n  background: var(--jp-layout-color2);\n  opacity: 0.8;\n}\n\n.jp-Completer-item.jp-mod-active {\n  background: var(--jp-brand-color1);\n  color: white;\n}\n\n.jp-Completer-item .jp-Completer-match mark {\n  font-weight: bold;\n  background: inherit;\n  color: inherit;\n}\n\n.jp-Completer-type[data-color-index='0'] {\n  background: transparent;\n}\n\n.jp-Completer-type[data-color-index='1'] {\n  background: #1f77b4;\n}\n\n.jp-Completer-type[data-color-index='2'] {\n  background: #ff7f0e;\n}\n\n.jp-Completer-type[data-color-index='3'] {\n  background: #2ca02c;\n}\n\n.jp-Completer-type[data-color-index='4'] {\n  background: #d62728;\n}\n\n.jp-Completer-type[data-color-index='5'] {\n  background: #9467bd;\n}\n\n.jp-Completer-type[data-color-index='6'] {\n  background: #8c564b;\n}\n\n.jp-Completer-type[data-color-index='7'] {\n  background: #e377c2;\n}\n\n.jp-Completer-type[data-color-index='8'] {\n  background: #7f7f7f;\n}\n\n.jp-Completer-type[data-color-index='9'] {\n  background: #bcbd22;\n}\n\n.jp-Completer-type[data-color-index='10'] {\n  background: #17becf;\n}\n", ""]);

// exports


/***/ }),

/***/ "wclG":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_setToString.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseSetToString = __webpack_require__(/*! ./_baseSetToString */ "pFRH"),
    shortOut = __webpack_require__(/*! ./_shortOut */ "88Gu");

/**
 * 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);

module.exports = setToString;


/***/ }),

/***/ "wd/R":
/*!***************************************!*\
  !*** ./node_modules/moment/moment.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(module) {var require;//! moment.js

;(function (global, factory) {
     true ? module.exports = factory() :
    undefined
}(this, (function () { 'use strict';

var hookCallback;

function hooks () {
    return hookCallback.apply(null, arguments);
}

// This is done to register the method called with moment()
// without creating circular dependencies.
function setHookCallback (callback) {
    hookCallback = callback;
}

function isArray(input) {
    return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
}

function isObject(input) {
    // IE8 will treat undefined and null as object if it wasn't for
    // input != null
    return input != null && Object.prototype.toString.call(input) === '[object Object]';
}

function isObjectEmpty(obj) {
    if (Object.getOwnPropertyNames) {
        return (Object.getOwnPropertyNames(obj).length === 0);
    } else {
        var k;
        for (k in obj) {
            if (obj.hasOwnProperty(k)) {
                return false;
            }
        }
        return true;
    }
}

function isUndefined(input) {
    return input === void 0;
}

function isNumber(input) {
    return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]';
}

function isDate(input) {
    return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
}

function map(arr, fn) {
    var res = [], i;
    for (i = 0; i < arr.length; ++i) {
        res.push(fn(arr[i], i));
    }
    return res;
}

function hasOwnProp(a, b) {
    return Object.prototype.hasOwnProperty.call(a, b);
}

function extend(a, b) {
    for (var i in b) {
        if (hasOwnProp(b, i)) {
            a[i] = b[i];
        }
    }

    if (hasOwnProp(b, 'toString')) {
        a.toString = b.toString;
    }

    if (hasOwnProp(b, 'valueOf')) {
        a.valueOf = b.valueOf;
    }

    return a;
}

function createUTC (input, format, locale, strict) {
    return createLocalOrUTC(input, format, locale, strict, true).utc();
}

function defaultParsingFlags() {
    // We need to deep clone this object.
    return {
        empty           : false,
        unusedTokens    : [],
        unusedInput     : [],
        overflow        : -2,
        charsLeftOver   : 0,
        nullInput       : false,
        invalidMonth    : null,
        invalidFormat   : false,
        userInvalidated : false,
        iso             : false,
        parsedDateParts : [],
        meridiem        : null,
        rfc2822         : false,
        weekdayMismatch : false
    };
}

function getParsingFlags(m) {
    if (m._pf == null) {
        m._pf = defaultParsingFlags();
    }
    return m._pf;
}

var some;
if (Array.prototype.some) {
    some = Array.prototype.some;
} else {
    some = function (fun) {
        var t = Object(this);
        var len = t.length >>> 0;

        for (var i = 0; i < len; i++) {
            if (i in t && fun.call(this, t[i], i, t)) {
                return true;
            }
        }

        return false;
    };
}

function isValid(m) {
    if (m._isValid == null) {
        var flags = getParsingFlags(m);
        var parsedParts = some.call(flags.parsedDateParts, function (i) {
            return i != null;
        });
        var isNowValid = !isNaN(m._d.getTime()) &&
            flags.overflow < 0 &&
            !flags.empty &&
            !flags.invalidMonth &&
            !flags.invalidWeekday &&
            !flags.weekdayMismatch &&
            !flags.nullInput &&
            !flags.invalidFormat &&
            !flags.userInvalidated &&
            (!flags.meridiem || (flags.meridiem && parsedParts));

        if (m._strict) {
            isNowValid = isNowValid &&
                flags.charsLeftOver === 0 &&
                flags.unusedTokens.length === 0 &&
                flags.bigHour === undefined;
        }

        if (Object.isFrozen == null || !Object.isFrozen(m)) {
            m._isValid = isNowValid;
        }
        else {
            return isNowValid;
        }
    }
    return m._isValid;
}

function createInvalid (flags) {
    var m = createUTC(NaN);
    if (flags != null) {
        extend(getParsingFlags(m), flags);
    }
    else {
        getParsingFlags(m).userInvalidated = true;
    }

    return m;
}

// Plugins that add properties should also add the key here (null value),
// so we can properly clone ourselves.
var momentProperties = hooks.momentProperties = [];

function copyConfig(to, from) {
    var i, prop, val;

    if (!isUndefined(from._isAMomentObject)) {
        to._isAMomentObject = from._isAMomentObject;
    }
    if (!isUndefined(from._i)) {
        to._i = from._i;
    }
    if (!isUndefined(from._f)) {
        to._f = from._f;
    }
    if (!isUndefined(from._l)) {
        to._l = from._l;
    }
    if (!isUndefined(from._strict)) {
        to._strict = from._strict;
    }
    if (!isUndefined(from._tzm)) {
        to._tzm = from._tzm;
    }
    if (!isUndefined(from._isUTC)) {
        to._isUTC = from._isUTC;
    }
    if (!isUndefined(from._offset)) {
        to._offset = from._offset;
    }
    if (!isUndefined(from._pf)) {
        to._pf = getParsingFlags(from);
    }
    if (!isUndefined(from._locale)) {
        to._locale = from._locale;
    }

    if (momentProperties.length > 0) {
        for (i = 0; i < momentProperties.length; i++) {
            prop = momentProperties[i];
            val = from[prop];
            if (!isUndefined(val)) {
                to[prop] = val;
            }
        }
    }

    return to;
}

var updateInProgress = false;

// Moment prototype object
function Moment(config) {
    copyConfig(this, config);
    this._d = new Date(config._d != null ? config._d.getTime() : NaN);
    if (!this.isValid()) {
        this._d = new Date(NaN);
    }
    // Prevent infinite loop in case updateOffset creates new moment
    // objects.
    if (updateInProgress === false) {
        updateInProgress = true;
        hooks.updateOffset(this);
        updateInProgress = false;
    }
}

function isMoment (obj) {
    return obj instanceof Moment || (obj != null && obj._isAMomentObject != null);
}

function absFloor (number) {
    if (number < 0) {
        // -0 -> 0
        return Math.ceil(number) || 0;
    } else {
        return Math.floor(number);
    }
}

function toInt(argumentForCoercion) {
    var coercedNumber = +argumentForCoercion,
        value = 0;

    if (coercedNumber !== 0 && isFinite(coercedNumber)) {
        value = absFloor(coercedNumber);
    }

    return value;
}

// compare two arrays, return the number of differences
function compareArrays(array1, array2, dontConvert) {
    var len = Math.min(array1.length, array2.length),
        lengthDiff = Math.abs(array1.length - array2.length),
        diffs = 0,
        i;
    for (i = 0; i < len; i++) {
        if ((dontConvert && array1[i] !== array2[i]) ||
            (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
            diffs++;
        }
    }
    return diffs + lengthDiff;
}

function warn(msg) {
    if (hooks.suppressDeprecationWarnings === false &&
            (typeof console !==  'undefined') && console.warn) {
        console.warn('Deprecation warning: ' + msg);
    }
}

function deprecate(msg, fn) {
    var firstTime = true;

    return extend(function () {
        if (hooks.deprecationHandler != null) {
            hooks.deprecationHandler(null, msg);
        }
        if (firstTime) {
            var args = [];
            var arg;
            for (var i = 0; i < arguments.length; i++) {
                arg = '';
                if (typeof arguments[i] === 'object') {
                    arg += '\n[' + i + '] ';
                    for (var key in arguments[0]) {
                        arg += key + ': ' + arguments[0][key] + ', ';
                    }
                    arg = arg.slice(0, -2); // Remove trailing comma and space
                } else {
                    arg = arguments[i];
                }
                args.push(arg);
            }
            warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack);
            firstTime = false;
        }
        return fn.apply(this, arguments);
    }, fn);
}

var deprecations = {};

function deprecateSimple(name, msg) {
    if (hooks.deprecationHandler != null) {
        hooks.deprecationHandler(name, msg);
    }
    if (!deprecations[name]) {
        warn(msg);
        deprecations[name] = true;
    }
}

hooks.suppressDeprecationWarnings = false;
hooks.deprecationHandler = null;

function isFunction(input) {
    return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
}

function set (config) {
    var prop, i;
    for (i in config) {
        prop = config[i];
        if (isFunction(prop)) {
            this[i] = prop;
        } else {
            this['_' + i] = prop;
        }
    }
    this._config = config;
    // Lenient ordinal parsing accepts just a number in addition to
    // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
    // TODO: Remove "ordinalParse" fallback in next major release.
    this._dayOfMonthOrdinalParseLenient = new RegExp(
        (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +
            '|' + (/\d{1,2}/).source);
}

function mergeConfigs(parentConfig, childConfig) {
    var res = extend({}, parentConfig), prop;
    for (prop in childConfig) {
        if (hasOwnProp(childConfig, prop)) {
            if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
                res[prop] = {};
                extend(res[prop], parentConfig[prop]);
                extend(res[prop], childConfig[prop]);
            } else if (childConfig[prop] != null) {
                res[prop] = childConfig[prop];
            } else {
                delete res[prop];
            }
        }
    }
    for (prop in parentConfig) {
        if (hasOwnProp(parentConfig, prop) &&
                !hasOwnProp(childConfig, prop) &&
                isObject(parentConfig[prop])) {
            // make sure changes to properties don't modify parent config
            res[prop] = extend({}, res[prop]);
        }
    }
    return res;
}

function Locale(config) {
    if (config != null) {
        this.set(config);
    }
}

var keys;

if (Object.keys) {
    keys = Object.keys;
} else {
    keys = function (obj) {
        var i, res = [];
        for (i in obj) {
            if (hasOwnProp(obj, i)) {
                res.push(i);
            }
        }
        return res;
    };
}

var defaultCalendar = {
    sameDay : '[Today at] LT',
    nextDay : '[Tomorrow at] LT',
    nextWeek : 'dddd [at] LT',
    lastDay : '[Yesterday at] LT',
    lastWeek : '[Last] dddd [at] LT',
    sameElse : 'L'
};

function calendar (key, mom, now) {
    var output = this._calendar[key] || this._calendar['sameElse'];
    return isFunction(output) ? output.call(mom, now) : output;
}

var defaultLongDateFormat = {
    LTS  : 'h:mm:ss A',
    LT   : 'h:mm A',
    L    : 'MM/DD/YYYY',
    LL   : 'MMMM D, YYYY',
    LLL  : 'MMMM D, YYYY h:mm A',
    LLLL : 'dddd, MMMM D, YYYY h:mm A'
};

function longDateFormat (key) {
    var format = this._longDateFormat[key],
        formatUpper = this._longDateFormat[key.toUpperCase()];

    if (format || !formatUpper) {
        return format;
    }

    this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
        return val.slice(1);
    });

    return this._longDateFormat[key];
}

var defaultInvalidDate = 'Invalid date';

function invalidDate () {
    return this._invalidDate;
}

var defaultOrdinal = '%d';
var defaultDayOfMonthOrdinalParse = /\d{1,2}/;

function ordinal (number) {
    return this._ordinal.replace('%d', number);
}

var defaultRelativeTime = {
    future : 'in %s',
    past   : '%s ago',
    s  : 'a few seconds',
    ss : '%d seconds',
    m  : 'a minute',
    mm : '%d minutes',
    h  : 'an hour',
    hh : '%d hours',
    d  : 'a day',
    dd : '%d days',
    M  : 'a month',
    MM : '%d months',
    y  : 'a year',
    yy : '%d years'
};

function relativeTime (number, withoutSuffix, string, isFuture) {
    var output = this._relativeTime[string];
    return (isFunction(output)) ?
        output(number, withoutSuffix, string, isFuture) :
        output.replace(/%d/i, number);
}

function pastFuture (diff, output) {
    var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
    return isFunction(format) ? format(output) : format.replace(/%s/i, output);
}

var aliases = {};

function addUnitAlias (unit, shorthand) {
    var lowerCase = unit.toLowerCase();
    aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
}

function normalizeUnits(units) {
    return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
}

function normalizeObjectUnits(inputObject) {
    var normalizedInput = {},
        normalizedProp,
        prop;

    for (prop in inputObject) {
        if (hasOwnProp(inputObject, prop)) {
            normalizedProp = normalizeUnits(prop);
            if (normalizedProp) {
                normalizedInput[normalizedProp] = inputObject[prop];
            }
        }
    }

    return normalizedInput;
}

var priorities = {};

function addUnitPriority(unit, priority) {
    priorities[unit] = priority;
}

function getPrioritizedUnits(unitsObj) {
    var units = [];
    for (var u in unitsObj) {
        units.push({unit: u, priority: priorities[u]});
    }
    units.sort(function (a, b) {
        return a.priority - b.priority;
    });
    return units;
}

function zeroFill(number, targetLength, forceSign) {
    var absNumber = '' + Math.abs(number),
        zerosToFill = targetLength - absNumber.length,
        sign = number >= 0;
    return (sign ? (forceSign ? '+' : '') : '-') +
        Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
}

var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;

var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;

var formatFunctions = {};

var formatTokenFunctions = {};

// token:    'M'
// padded:   ['MM', 2]
// ordinal:  'Mo'
// callback: function () { this.month() + 1 }
function addFormatToken (token, padded, ordinal, callback) {
    var func = callback;
    if (typeof callback === 'string') {
        func = function () {
            return this[callback]();
        };
    }
    if (token) {
        formatTokenFunctions[token] = func;
    }
    if (padded) {
        formatTokenFunctions[padded[0]] = function () {
            return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
        };
    }
    if (ordinal) {
        formatTokenFunctions[ordinal] = function () {
            return this.localeData().ordinal(func.apply(this, arguments), token);
        };
    }
}

function removeFormattingTokens(input) {
    if (input.match(/\[[\s\S]/)) {
        return input.replace(/^\[|\]$/g, '');
    }
    return input.replace(/\\/g, '');
}

function makeFormatFunction(format) {
    var array = format.match(formattingTokens), i, length;

    for (i = 0, length = array.length; i < length; i++) {
        if (formatTokenFunctions[array[i]]) {
            array[i] = formatTokenFunctions[array[i]];
        } else {
            array[i] = removeFormattingTokens(array[i]);
        }
    }

    return function (mom) {
        var output = '', i;
        for (i = 0; i < length; i++) {
            output += isFunction(array[i]) ? array[i].call(mom, format) : array[i];
        }
        return output;
    };
}

// format date using native date object
function formatMoment(m, format) {
    if (!m.isValid()) {
        return m.localeData().invalidDate();
    }

    format = expandFormat(format, m.localeData());
    formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);

    return formatFunctions[format](m);
}

function expandFormat(format, locale) {
    var i = 5;

    function replaceLongDateFormatTokens(input) {
        return locale.longDateFormat(input) || input;
    }

    localFormattingTokens.lastIndex = 0;
    while (i >= 0 && localFormattingTokens.test(format)) {
        format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
        localFormattingTokens.lastIndex = 0;
        i -= 1;
    }

    return format;
}

var match1         = /\d/;            //       0 - 9
var match2         = /\d\d/;          //      00 - 99
var match3         = /\d{3}/;         //     000 - 999
var match4         = /\d{4}/;         //    0000 - 9999
var match6         = /[+-]?\d{6}/;    // -999999 - 999999
var match1to2      = /\d\d?/;         //       0 - 99
var match3to4      = /\d\d\d\d?/;     //     999 - 9999
var match5to6      = /\d\d\d\d\d\d?/; //   99999 - 999999
var match1to3      = /\d{1,3}/;       //       0 - 999
var match1to4      = /\d{1,4}/;       //       0 - 9999
var match1to6      = /[+-]?\d{1,6}/;  // -999999 - 999999

var matchUnsigned  = /\d+/;           //       0 - inf
var matchSigned    = /[+-]?\d+/;      //    -inf - inf

var matchOffset    = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z

var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123

// any word (or two) characters or numbers including two/three word month in arabic.
// includes scottish gaelic two word and hyphenated months
var matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i;

var regexes = {};

function addRegexToken (token, regex, strictRegex) {
    regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
        return (isStrict && strictRegex) ? strictRegex : regex;
    };
}

function getParseRegexForToken (token, config) {
    if (!hasOwnProp(regexes, token)) {
        return new RegExp(unescapeFormat(token));
    }

    return regexes[token](config._strict, config._locale);
}

// Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
function unescapeFormat(s) {
    return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
        return p1 || p2 || p3 || p4;
    }));
}

function regexEscape(s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}

var tokens = {};

function addParseToken (token, callback) {
    var i, func = callback;
    if (typeof token === 'string') {
        token = [token];
    }
    if (isNumber(callback)) {
        func = function (input, array) {
            array[callback] = toInt(input);
        };
    }
    for (i = 0; i < token.length; i++) {
        tokens[token[i]] = func;
    }
}

function addWeekParseToken (token, callback) {
    addParseToken(token, function (input, array, config, token) {
        config._w = config._w || {};
        callback(input, config._w, config, token);
    });
}

function addTimeToArrayFromToken(token, input, config) {
    if (input != null && hasOwnProp(tokens, token)) {
        tokens[token](input, config._a, config, token);
    }
}

var YEAR = 0;
var MONTH = 1;
var DATE = 2;
var HOUR = 3;
var MINUTE = 4;
var SECOND = 5;
var MILLISECOND = 6;
var WEEK = 7;
var WEEKDAY = 8;

// FORMATTING

addFormatToken('Y', 0, 0, function () {
    var y = this.year();
    return y <= 9999 ? '' + y : '+' + y;
});

addFormatToken(0, ['YY', 2], 0, function () {
    return this.year() % 100;
});

addFormatToken(0, ['YYYY',   4],       0, 'year');
addFormatToken(0, ['YYYYY',  5],       0, 'year');
addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');

// ALIASES

addUnitAlias('year', 'y');

// PRIORITIES

addUnitPriority('year', 1);

// PARSING

addRegexToken('Y',      matchSigned);
addRegexToken('YY',     match1to2, match2);
addRegexToken('YYYY',   match1to4, match4);
addRegexToken('YYYYY',  match1to6, match6);
addRegexToken('YYYYYY', match1to6, match6);

addParseToken(['YYYYY', 'YYYYYY'], YEAR);
addParseToken('YYYY', function (input, array) {
    array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
});
addParseToken('YY', function (input, array) {
    array[YEAR] = hooks.parseTwoDigitYear(input);
});
addParseToken('Y', function (input, array) {
    array[YEAR] = parseInt(input, 10);
});

// HELPERS

function daysInYear(year) {
    return isLeapYear(year) ? 366 : 365;
}

function isLeapYear(year) {
    return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}

// HOOKS

hooks.parseTwoDigitYear = function (input) {
    return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
};

// MOMENTS

var getSetYear = makeGetSet('FullYear', true);

function getIsLeapYear () {
    return isLeapYear(this.year());
}

function makeGetSet (unit, keepTime) {
    return function (value) {
        if (value != null) {
            set$1(this, unit, value);
            hooks.updateOffset(this, keepTime);
            return this;
        } else {
            return get(this, unit);
        }
    };
}

function get (mom, unit) {
    return mom.isValid() ?
        mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
}

function set$1 (mom, unit, value) {
    if (mom.isValid() && !isNaN(value)) {
        if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) {
            mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month()));
        }
        else {
            mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
        }
    }
}

// MOMENTS

function stringGet (units) {
    units = normalizeUnits(units);
    if (isFunction(this[units])) {
        return this[units]();
    }
    return this;
}


function stringSet (units, value) {
    if (typeof units === 'object') {
        units = normalizeObjectUnits(units);
        var prioritized = getPrioritizedUnits(units);
        for (var i = 0; i < prioritized.length; i++) {
            this[prioritized[i].unit](units[prioritized[i].unit]);
        }
    } else {
        units = normalizeUnits(units);
        if (isFunction(this[units])) {
            return this[units](value);
        }
    }
    return this;
}

function mod(n, x) {
    return ((n % x) + x) % x;
}

var indexOf;

if (Array.prototype.indexOf) {
    indexOf = Array.prototype.indexOf;
} else {
    indexOf = function (o) {
        // I know
        var i;
        for (i = 0; i < this.length; ++i) {
            if (this[i] === o) {
                return i;
            }
        }
        return -1;
    };
}

function daysInMonth(year, month) {
    if (isNaN(year) || isNaN(month)) {
        return NaN;
    }
    var modMonth = mod(month, 12);
    year += (month - modMonth) / 12;
    return modMonth === 1 ? (isLeapYear(year) ? 29 : 28) : (31 - modMonth % 7 % 2);
}

// FORMATTING

addFormatToken('M', ['MM', 2], 'Mo', function () {
    return this.month() + 1;
});

addFormatToken('MMM', 0, 0, function (format) {
    return this.localeData().monthsShort(this, format);
});

addFormatToken('MMMM', 0, 0, function (format) {
    return this.localeData().months(this, format);
});

// ALIASES

addUnitAlias('month', 'M');

// PRIORITY

addUnitPriority('month', 8);

// PARSING

addRegexToken('M',    match1to2);
addRegexToken('MM',   match1to2, match2);
addRegexToken('MMM',  function (isStrict, locale) {
    return locale.monthsShortRegex(isStrict);
});
addRegexToken('MMMM', function (isStrict, locale) {
    return locale.monthsRegex(isStrict);
});

addParseToken(['M', 'MM'], function (input, array) {
    array[MONTH] = toInt(input) - 1;
});

addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
    var month = config._locale.monthsParse(input, token, config._strict);
    // if we didn't find a month name, mark the date as invalid.
    if (month != null) {
        array[MONTH] = month;
    } else {
        getParsingFlags(config).invalidMonth = input;
    }
});

// LOCALES

var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
function localeMonths (m, format) {
    if (!m) {
        return isArray(this._months) ? this._months :
            this._months['standalone'];
    }
    return isArray(this._months) ? this._months[m.month()] :
        this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()];
}

var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
function localeMonthsShort (m, format) {
    if (!m) {
        return isArray(this._monthsShort) ? this._monthsShort :
            this._monthsShort['standalone'];
    }
    return isArray(this._monthsShort) ? this._monthsShort[m.month()] :
        this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
}

function handleStrictParse(monthName, format, strict) {
    var i, ii, mom, llc = monthName.toLocaleLowerCase();
    if (!this._monthsParse) {
        // this is not used
        this._monthsParse = [];
        this._longMonthsParse = [];
        this._shortMonthsParse = [];
        for (i = 0; i < 12; ++i) {
            mom = createUTC([2000, i]);
            this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
            this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
        }
    }

    if (strict) {
        if (format === 'MMM') {
            ii = indexOf.call(this._shortMonthsParse, llc);
            return ii !== -1 ? ii : null;
        } else {
            ii = indexOf.call(this._longMonthsParse, llc);
            return ii !== -1 ? ii : null;
        }
    } else {
        if (format === 'MMM') {
            ii = indexOf.call(this._shortMonthsParse, llc);
            if (ii !== -1) {
                return ii;
            }
            ii = indexOf.call(this._longMonthsParse, llc);
            return ii !== -1 ? ii : null;
        } else {
            ii = indexOf.call(this._longMonthsParse, llc);
            if (ii !== -1) {
                return ii;
            }
            ii = indexOf.call(this._shortMonthsParse, llc);
            return ii !== -1 ? ii : null;
        }
    }
}

function localeMonthsParse (monthName, format, strict) {
    var i, mom, regex;

    if (this._monthsParseExact) {
        return handleStrictParse.call(this, monthName, format, strict);
    }

    if (!this._monthsParse) {
        this._monthsParse = [];
        this._longMonthsParse = [];
        this._shortMonthsParse = [];
    }

    // TODO: add sorting
    // Sorting makes sure if one month (or abbr) is a prefix of another
    // see sorting in computeMonthsParse
    for (i = 0; i < 12; i++) {
        // make the regex if we don't have it already
        mom = createUTC([2000, i]);
        if (strict && !this._longMonthsParse[i]) {
            this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
            this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
        }
        if (!strict && !this._monthsParse[i]) {
            regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
            this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
        }
        // test the regex
        if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
            return i;
        } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
            return i;
        } else if (!strict && this._monthsParse[i].test(monthName)) {
            return i;
        }
    }
}

// MOMENTS

function setMonth (mom, value) {
    var dayOfMonth;

    if (!mom.isValid()) {
        // No op
        return mom;
    }

    if (typeof value === 'string') {
        if (/^\d+$/.test(value)) {
            value = toInt(value);
        } else {
            value = mom.localeData().monthsParse(value);
            // TODO: Another silent failure?
            if (!isNumber(value)) {
                return mom;
            }
        }
    }

    dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
    mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
    return mom;
}

function getSetMonth (value) {
    if (value != null) {
        setMonth(this, value);
        hooks.updateOffset(this, true);
        return this;
    } else {
        return get(this, 'Month');
    }
}

function getDaysInMonth () {
    return daysInMonth(this.year(), this.month());
}

var defaultMonthsShortRegex = matchWord;
function monthsShortRegex (isStrict) {
    if (this._monthsParseExact) {
        if (!hasOwnProp(this, '_monthsRegex')) {
            computeMonthsParse.call(this);
        }
        if (isStrict) {
            return this._monthsShortStrictRegex;
        } else {
            return this._monthsShortRegex;
        }
    } else {
        if (!hasOwnProp(this, '_monthsShortRegex')) {
            this._monthsShortRegex = defaultMonthsShortRegex;
        }
        return this._monthsShortStrictRegex && isStrict ?
            this._monthsShortStrictRegex : this._monthsShortRegex;
    }
}

var defaultMonthsRegex = matchWord;
function monthsRegex (isStrict) {
    if (this._monthsParseExact) {
        if (!hasOwnProp(this, '_monthsRegex')) {
            computeMonthsParse.call(this);
        }
        if (isStrict) {
            return this._monthsStrictRegex;
        } else {
            return this._monthsRegex;
        }
    } else {
        if (!hasOwnProp(this, '_monthsRegex')) {
            this._monthsRegex = defaultMonthsRegex;
        }
        return this._monthsStrictRegex && isStrict ?
            this._monthsStrictRegex : this._monthsRegex;
    }
}

function computeMonthsParse () {
    function cmpLenRev(a, b) {
        return b.length - a.length;
    }

    var shortPieces = [], longPieces = [], mixedPieces = [],
        i, mom;
    for (i = 0; i < 12; i++) {
        // make the regex if we don't have it already
        mom = createUTC([2000, i]);
        shortPieces.push(this.monthsShort(mom, ''));
        longPieces.push(this.months(mom, ''));
        mixedPieces.push(this.months(mom, ''));
        mixedPieces.push(this.monthsShort(mom, ''));
    }
    // Sorting makes sure if one month (or abbr) is a prefix of another it
    // will match the longer piece.
    shortPieces.sort(cmpLenRev);
    longPieces.sort(cmpLenRev);
    mixedPieces.sort(cmpLenRev);
    for (i = 0; i < 12; i++) {
        shortPieces[i] = regexEscape(shortPieces[i]);
        longPieces[i] = regexEscape(longPieces[i]);
    }
    for (i = 0; i < 24; i++) {
        mixedPieces[i] = regexEscape(mixedPieces[i]);
    }

    this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
    this._monthsShortRegex = this._monthsRegex;
    this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
    this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
}

function createDate (y, m, d, h, M, s, ms) {
    // can't just apply() to create a date:
    // https://stackoverflow.com/q/181348
    var date = new Date(y, m, d, h, M, s, ms);

    // the date constructor remaps years 0-99 to 1900-1999
    if (y < 100 && y >= 0 && isFinite(date.getFullYear())) {
        date.setFullYear(y);
    }
    return date;
}

function createUTCDate (y) {
    var date = new Date(Date.UTC.apply(null, arguments));

    // the Date.UTC function remaps years 0-99 to 1900-1999
    if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) {
        date.setUTCFullYear(y);
    }
    return date;
}

// start-of-first-week - start-of-year
function firstWeekOffset(year, dow, doy) {
    var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
        fwd = 7 + dow - doy,
        // first-week day local weekday -- which local weekday is fwd
        fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;

    return -fwdlw + fwd - 1;
}

// https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
    var localWeekday = (7 + weekday - dow) % 7,
        weekOffset = firstWeekOffset(year, dow, doy),
        dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
        resYear, resDayOfYear;

    if (dayOfYear <= 0) {
        resYear = year - 1;
        resDayOfYear = daysInYear(resYear) + dayOfYear;
    } else if (dayOfYear > daysInYear(year)) {
        resYear = year + 1;
        resDayOfYear = dayOfYear - daysInYear(year);
    } else {
        resYear = year;
        resDayOfYear = dayOfYear;
    }

    return {
        year: resYear,
        dayOfYear: resDayOfYear
    };
}

function weekOfYear(mom, dow, doy) {
    var weekOffset = firstWeekOffset(mom.year(), dow, doy),
        week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
        resWeek, resYear;

    if (week < 1) {
        resYear = mom.year() - 1;
        resWeek = week + weeksInYear(resYear, dow, doy);
    } else if (week > weeksInYear(mom.year(), dow, doy)) {
        resWeek = week - weeksInYear(mom.year(), dow, doy);
        resYear = mom.year() + 1;
    } else {
        resYear = mom.year();
        resWeek = week;
    }

    return {
        week: resWeek,
        year: resYear
    };
}

function weeksInYear(year, dow, doy) {
    var weekOffset = firstWeekOffset(year, dow, doy),
        weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
    return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
}

// FORMATTING

addFormatToken('w', ['ww', 2], 'wo', 'week');
addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');

// ALIASES

addUnitAlias('week', 'w');
addUnitAlias('isoWeek', 'W');

// PRIORITIES

addUnitPriority('week', 5);
addUnitPriority('isoWeek', 5);

// PARSING

addRegexToken('w',  match1to2);
addRegexToken('ww', match1to2, match2);
addRegexToken('W',  match1to2);
addRegexToken('WW', match1to2, match2);

addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
    week[token.substr(0, 1)] = toInt(input);
});

// HELPERS

// LOCALES

function localeWeek (mom) {
    return weekOfYear(mom, this._week.dow, this._week.doy).week;
}

var defaultLocaleWeek = {
    dow : 0, // Sunday is the first day of the week.
    doy : 6  // The week that contains Jan 1st is the first week of the year.
};

function localeFirstDayOfWeek () {
    return this._week.dow;
}

function localeFirstDayOfYear () {
    return this._week.doy;
}

// MOMENTS

function getSetWeek (input) {
    var week = this.localeData().week(this);
    return input == null ? week : this.add((input - week) * 7, 'd');
}

function getSetISOWeek (input) {
    var week = weekOfYear(this, 1, 4).week;
    return input == null ? week : this.add((input - week) * 7, 'd');
}

// FORMATTING

addFormatToken('d', 0, 'do', 'day');

addFormatToken('dd', 0, 0, function (format) {
    return this.localeData().weekdaysMin(this, format);
});

addFormatToken('ddd', 0, 0, function (format) {
    return this.localeData().weekdaysShort(this, format);
});

addFormatToken('dddd', 0, 0, function (format) {
    return this.localeData().weekdays(this, format);
});

addFormatToken('e', 0, 0, 'weekday');
addFormatToken('E', 0, 0, 'isoWeekday');

// ALIASES

addUnitAlias('day', 'd');
addUnitAlias('weekday', 'e');
addUnitAlias('isoWeekday', 'E');

// PRIORITY
addUnitPriority('day', 11);
addUnitPriority('weekday', 11);
addUnitPriority('isoWeekday', 11);

// PARSING

addRegexToken('d',    match1to2);
addRegexToken('e',    match1to2);
addRegexToken('E',    match1to2);
addRegexToken('dd',   function (isStrict, locale) {
    return locale.weekdaysMinRegex(isStrict);
});
addRegexToken('ddd',   function (isStrict, locale) {
    return locale.weekdaysShortRegex(isStrict);
});
addRegexToken('dddd',   function (isStrict, locale) {
    return locale.weekdaysRegex(isStrict);
});

addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
    var weekday = config._locale.weekdaysParse(input, token, config._strict);
    // if we didn't get a weekday name, mark the date as invalid
    if (weekday != null) {
        week.d = weekday;
    } else {
        getParsingFlags(config).invalidWeekday = input;
    }
});

addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
    week[token] = toInt(input);
});

// HELPERS

function parseWeekday(input, locale) {
    if (typeof input !== 'string') {
        return input;
    }

    if (!isNaN(input)) {
        return parseInt(input, 10);
    }

    input = locale.weekdaysParse(input);
    if (typeof input === 'number') {
        return input;
    }

    return null;
}

function parseIsoWeekday(input, locale) {
    if (typeof input === 'string') {
        return locale.weekdaysParse(input) % 7 || 7;
    }
    return isNaN(input) ? null : input;
}

// LOCALES

var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
function localeWeekdays (m, format) {
    if (!m) {
        return isArray(this._weekdays) ? this._weekdays :
            this._weekdays['standalone'];
    }
    return isArray(this._weekdays) ? this._weekdays[m.day()] :
        this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()];
}

var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
function localeWeekdaysShort (m) {
    return (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort;
}

var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
function localeWeekdaysMin (m) {
    return (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin;
}

function handleStrictParse$1(weekdayName, format, strict) {
    var i, ii, mom, llc = weekdayName.toLocaleLowerCase();
    if (!this._weekdaysParse) {
        this._weekdaysParse = [];
        this._shortWeekdaysParse = [];
        this._minWeekdaysParse = [];

        for (i = 0; i < 7; ++i) {
            mom = createUTC([2000, 1]).day(i);
            this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
            this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
            this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
        }
    }

    if (strict) {
        if (format === 'dddd') {
            ii = indexOf.call(this._weekdaysParse, llc);
            return ii !== -1 ? ii : null;
        } else if (format === 'ddd') {
            ii = indexOf.call(this._shortWeekdaysParse, llc);
            return ii !== -1 ? ii : null;
        } else {
            ii = indexOf.call(this._minWeekdaysParse, llc);
            return ii !== -1 ? ii : null;
        }
    } else {
        if (format === 'dddd') {
            ii = indexOf.call(this._weekdaysParse, llc);
            if (ii !== -1) {
                return ii;
            }
            ii = indexOf.call(this._shortWeekdaysParse, llc);
            if (ii !== -1) {
                return ii;
            }
            ii = indexOf.call(this._minWeekdaysParse, llc);
            return ii !== -1 ? ii : null;
        } else if (format === 'ddd') {
            ii = indexOf.call(this._shortWeekdaysParse, llc);
            if (ii !== -1) {
                return ii;
            }
            ii = indexOf.call(this._weekdaysParse, llc);
            if (ii !== -1) {
                return ii;
            }
            ii = indexOf.call(this._minWeekdaysParse, llc);
            return ii !== -1 ? ii : null;
        } else {
            ii = indexOf.call(this._minWeekdaysParse, llc);
            if (ii !== -1) {
                return ii;
            }
            ii = indexOf.call(this._weekdaysParse, llc);
            if (ii !== -1) {
                return ii;
            }
            ii = indexOf.call(this._shortWeekdaysParse, llc);
            return ii !== -1 ? ii : null;
        }
    }
}

function localeWeekdaysParse (weekdayName, format, strict) {
    var i, mom, regex;

    if (this._weekdaysParseExact) {
        return handleStrictParse$1.call(this, weekdayName, format, strict);
    }

    if (!this._weekdaysParse) {
        this._weekdaysParse = [];
        this._minWeekdaysParse = [];
        this._shortWeekdaysParse = [];
        this._fullWeekdaysParse = [];
    }

    for (i = 0; i < 7; i++) {
        // make the regex if we don't have it already

        mom = createUTC([2000, 1]).day(i);
        if (strict && !this._fullWeekdaysParse[i]) {
            this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\.?') + '$', 'i');
            this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\.?') + '$', 'i');
            this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\.?') + '$', 'i');
        }
        if (!this._weekdaysParse[i]) {
            regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
            this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
        }
        // test the regex
        if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
            return i;
        } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
            return i;
        } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
            return i;
        } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
            return i;
        }
    }
}

// MOMENTS

function getSetDayOfWeek (input) {
    if (!this.isValid()) {
        return input != null ? this : NaN;
    }
    var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
    if (input != null) {
        input = parseWeekday(input, this.localeData());
        return this.add(input - day, 'd');
    } else {
        return day;
    }
}

function getSetLocaleDayOfWeek (input) {
    if (!this.isValid()) {
        return input != null ? this : NaN;
    }
    var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
    return input == null ? weekday : this.add(input - weekday, 'd');
}

function getSetISODayOfWeek (input) {
    if (!this.isValid()) {
        return input != null ? this : NaN;
    }

    // behaves the same as moment#day except
    // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
    // as a setter, sunday should belong to the previous week.

    if (input != null) {
        var weekday = parseIsoWeekday(input, this.localeData());
        return this.day(this.day() % 7 ? weekday : weekday - 7);
    } else {
        return this.day() || 7;
    }
}

var defaultWeekdaysRegex = matchWord;
function weekdaysRegex (isStrict) {
    if (this._weekdaysParseExact) {
        if (!hasOwnProp(this, '_weekdaysRegex')) {
            computeWeekdaysParse.call(this);
        }
        if (isStrict) {
            return this._weekdaysStrictRegex;
        } else {
            return this._weekdaysRegex;
        }
    } else {
        if (!hasOwnProp(this, '_weekdaysRegex')) {
            this._weekdaysRegex = defaultWeekdaysRegex;
        }
        return this._weekdaysStrictRegex && isStrict ?
            this._weekdaysStrictRegex : this._weekdaysRegex;
    }
}

var defaultWeekdaysShortRegex = matchWord;
function weekdaysShortRegex (isStrict) {
    if (this._weekdaysParseExact) {
        if (!hasOwnProp(this, '_weekdaysRegex')) {
            computeWeekdaysParse.call(this);
        }
        if (isStrict) {
            return this._weekdaysShortStrictRegex;
        } else {
            return this._weekdaysShortRegex;
        }
    } else {
        if (!hasOwnProp(this, '_weekdaysShortRegex')) {
            this._weekdaysShortRegex = defaultWeekdaysShortRegex;
        }
        return this._weekdaysShortStrictRegex && isStrict ?
            this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
    }
}

var defaultWeekdaysMinRegex = matchWord;
function weekdaysMinRegex (isStrict) {
    if (this._weekdaysParseExact) {
        if (!hasOwnProp(this, '_weekdaysRegex')) {
            computeWeekdaysParse.call(this);
        }
        if (isStrict) {
            return this._weekdaysMinStrictRegex;
        } else {
            return this._weekdaysMinRegex;
        }
    } else {
        if (!hasOwnProp(this, '_weekdaysMinRegex')) {
            this._weekdaysMinRegex = defaultWeekdaysMinRegex;
        }
        return this._weekdaysMinStrictRegex && isStrict ?
            this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
    }
}


function computeWeekdaysParse () {
    function cmpLenRev(a, b) {
        return b.length - a.length;
    }

    var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [],
        i, mom, minp, shortp, longp;
    for (i = 0; i < 7; i++) {
        // make the regex if we don't have it already
        mom = createUTC([2000, 1]).day(i);
        minp = this.weekdaysMin(mom, '');
        shortp = this.weekdaysShort(mom, '');
        longp = this.weekdays(mom, '');
        minPieces.push(minp);
        shortPieces.push(shortp);
        longPieces.push(longp);
        mixedPieces.push(minp);
        mixedPieces.push(shortp);
        mixedPieces.push(longp);
    }
    // Sorting makes sure if one weekday (or abbr) is a prefix of another it
    // will match the longer piece.
    minPieces.sort(cmpLenRev);
    shortPieces.sort(cmpLenRev);
    longPieces.sort(cmpLenRev);
    mixedPieces.sort(cmpLenRev);
    for (i = 0; i < 7; i++) {
        shortPieces[i] = regexEscape(shortPieces[i]);
        longPieces[i] = regexEscape(longPieces[i]);
        mixedPieces[i] = regexEscape(mixedPieces[i]);
    }

    this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
    this._weekdaysShortRegex = this._weekdaysRegex;
    this._weekdaysMinRegex = this._weekdaysRegex;

    this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
    this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
    this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
}

// FORMATTING

function hFormat() {
    return this.hours() % 12 || 12;
}

function kFormat() {
    return this.hours() || 24;
}

addFormatToken('H', ['HH', 2], 0, 'hour');
addFormatToken('h', ['hh', 2], 0, hFormat);
addFormatToken('k', ['kk', 2], 0, kFormat);

addFormatToken('hmm', 0, 0, function () {
    return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
});

addFormatToken('hmmss', 0, 0, function () {
    return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) +
        zeroFill(this.seconds(), 2);
});

addFormatToken('Hmm', 0, 0, function () {
    return '' + this.hours() + zeroFill(this.minutes(), 2);
});

addFormatToken('Hmmss', 0, 0, function () {
    return '' + this.hours() + zeroFill(this.minutes(), 2) +
        zeroFill(this.seconds(), 2);
});

function meridiem (token, lowercase) {
    addFormatToken(token, 0, 0, function () {
        return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
    });
}

meridiem('a', true);
meridiem('A', false);

// ALIASES

addUnitAlias('hour', 'h');

// PRIORITY
addUnitPriority('hour', 13);

// PARSING

function matchMeridiem (isStrict, locale) {
    return locale._meridiemParse;
}

addRegexToken('a',  matchMeridiem);
addRegexToken('A',  matchMeridiem);
addRegexToken('H',  match1to2);
addRegexToken('h',  match1to2);
addRegexToken('k',  match1to2);
addRegexToken('HH', match1to2, match2);
addRegexToken('hh', match1to2, match2);
addRegexToken('kk', match1to2, match2);

addRegexToken('hmm', match3to4);
addRegexToken('hmmss', match5to6);
addRegexToken('Hmm', match3to4);
addRegexToken('Hmmss', match5to6);

addParseToken(['H', 'HH'], HOUR);
addParseToken(['k', 'kk'], function (input, array, config) {
    var kInput = toInt(input);
    array[HOUR] = kInput === 24 ? 0 : kInput;
});
addParseToken(['a', 'A'], function (input, array, config) {
    config._isPm = config._locale.isPM(input);
    config._meridiem = input;
});
addParseToken(['h', 'hh'], function (input, array, config) {
    array[HOUR] = toInt(input);
    getParsingFlags(config).bigHour = true;
});
addParseToken('hmm', function (input, array, config) {
    var pos = input.length - 2;
    array[HOUR] = toInt(input.substr(0, pos));
    array[MINUTE] = toInt(input.substr(pos));
    getParsingFlags(config).bigHour = true;
});
addParseToken('hmmss', function (input, array, config) {
    var pos1 = input.length - 4;
    var pos2 = input.length - 2;
    array[HOUR] = toInt(input.substr(0, pos1));
    array[MINUTE] = toInt(input.substr(pos1, 2));
    array[SECOND] = toInt(input.substr(pos2));
    getParsingFlags(config).bigHour = true;
});
addParseToken('Hmm', function (input, array, config) {
    var pos = input.length - 2;
    array[HOUR] = toInt(input.substr(0, pos));
    array[MINUTE] = toInt(input.substr(pos));
});
addParseToken('Hmmss', function (input, array, config) {
    var pos1 = input.length - 4;
    var pos2 = input.length - 2;
    array[HOUR] = toInt(input.substr(0, pos1));
    array[MINUTE] = toInt(input.substr(pos1, 2));
    array[SECOND] = toInt(input.substr(pos2));
});

// LOCALES

function localeIsPM (input) {
    // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
    // Using charAt should be more compatible.
    return ((input + '').toLowerCase().charAt(0) === 'p');
}

var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
function localeMeridiem (hours, minutes, isLower) {
    if (hours > 11) {
        return isLower ? 'pm' : 'PM';
    } else {
        return isLower ? 'am' : 'AM';
    }
}


// MOMENTS

// Setting the hour should keep the time, because the user explicitly
// specified which hour he wants. So trying to maintain the same hour (in
// a new timezone) makes sense. Adding/subtracting hours does not follow
// this rule.
var getSetHour = makeGetSet('Hours', true);

var baseConfig = {
    calendar: defaultCalendar,
    longDateFormat: defaultLongDateFormat,
    invalidDate: defaultInvalidDate,
    ordinal: defaultOrdinal,
    dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
    relativeTime: defaultRelativeTime,

    months: defaultLocaleMonths,
    monthsShort: defaultLocaleMonthsShort,

    week: defaultLocaleWeek,

    weekdays: defaultLocaleWeekdays,
    weekdaysMin: defaultLocaleWeekdaysMin,
    weekdaysShort: defaultLocaleWeekdaysShort,

    meridiemParse: defaultLocaleMeridiemParse
};

// internal storage for locale config files
var locales = {};
var localeFamilies = {};
var globalLocale;

function normalizeLocale(key) {
    return key ? key.toLowerCase().replace('_', '-') : key;
}

// pick the locale from the array
// try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
// substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
function chooseLocale(names) {
    var i = 0, j, next, locale, split;

    while (i < names.length) {
        split = normalizeLocale(names[i]).split('-');
        j = split.length;
        next = normalizeLocale(names[i + 1]);
        next = next ? next.split('-') : null;
        while (j > 0) {
            locale = loadLocale(split.slice(0, j).join('-'));
            if (locale) {
                return locale;
            }
            if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
                //the next array item is better than a shallower substring of this one
                break;
            }
            j--;
        }
        i++;
    }
    return globalLocale;
}

function loadLocale(name) {
    var oldLocale = null;
    // TODO: Find a better way to register and load all the locales in Node
    if (!locales[name] && (typeof module !== 'undefined') &&
            module && module.exports) {
        try {
            oldLocale = globalLocale._abbr;
            var aliasedRequire = require;
            __webpack_require__("RnhZ")("./" + name);
            getSetGlobalLocale(oldLocale);
        } catch (e) {}
    }
    return locales[name];
}

// This function will load locale and then set the global locale.  If
// no arguments are passed in, it will simply return the current global
// locale key.
function getSetGlobalLocale (key, values) {
    var data;
    if (key) {
        if (isUndefined(values)) {
            data = getLocale(key);
        }
        else {
            data = defineLocale(key, values);
        }

        if (data) {
            // moment.duration._locale = moment._locale = data;
            globalLocale = data;
        }
        else {
            if ((typeof console !==  'undefined') && console.warn) {
                //warn user if arguments are passed but the locale could not be set
                console.warn('Locale ' + key +  ' not found. Did you forget to load it?');
            }
        }
    }

    return globalLocale._abbr;
}

function defineLocale (name, config) {
    if (config !== null) {
        var locale, parentConfig = baseConfig;
        config.abbr = name;
        if (locales[name] != null) {
            deprecateSimple('defineLocaleOverride',
                    'use moment.updateLocale(localeName, config) to change ' +
                    'an existing locale. moment.defineLocale(localeName, ' +
                    'config) should only be used for creating a new locale ' +
                    'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.');
            parentConfig = locales[name]._config;
        } else if (config.parentLocale != null) {
            if (locales[config.parentLocale] != null) {
                parentConfig = locales[config.parentLocale]._config;
            } else {
                locale = loadLocale(config.parentLocale);
                if (locale != null) {
                    parentConfig = locale._config;
                } else {
                    if (!localeFamilies[config.parentLocale]) {
                        localeFamilies[config.parentLocale] = [];
                    }
                    localeFamilies[config.parentLocale].push({
                        name: name,
                        config: config
                    });
                    return null;
                }
            }
        }
        locales[name] = new Locale(mergeConfigs(parentConfig, config));

        if (localeFamilies[name]) {
            localeFamilies[name].forEach(function (x) {
                defineLocale(x.name, x.config);
            });
        }

        // backwards compat for now: also set the locale
        // make sure we set the locale AFTER all child locales have been
        // created, so we won't end up with the child locale set.
        getSetGlobalLocale(name);


        return locales[name];
    } else {
        // useful for testing
        delete locales[name];
        return null;
    }
}

function updateLocale(name, config) {
    if (config != null) {
        var locale, tmpLocale, parentConfig = baseConfig;
        // MERGE
        tmpLocale = loadLocale(name);
        if (tmpLocale != null) {
            parentConfig = tmpLocale._config;
        }
        config = mergeConfigs(parentConfig, config);
        locale = new Locale(config);
        locale.parentLocale = locales[name];
        locales[name] = locale;

        // backwards compat for now: also set the locale
        getSetGlobalLocale(name);
    } else {
        // pass null for config to unupdate, useful for tests
        if (locales[name] != null) {
            if (locales[name].parentLocale != null) {
                locales[name] = locales[name].parentLocale;
            } else if (locales[name] != null) {
                delete locales[name];
            }
        }
    }
    return locales[name];
}

// returns locale data
function getLocale (key) {
    var locale;

    if (key && key._locale && key._locale._abbr) {
        key = key._locale._abbr;
    }

    if (!key) {
        return globalLocale;
    }

    if (!isArray(key)) {
        //short-circuit everything else
        locale = loadLocale(key);
        if (locale) {
            return locale;
        }
        key = [key];
    }

    return chooseLocale(key);
}

function listLocales() {
    return keys(locales);
}

function checkOverflow (m) {
    var overflow;
    var a = m._a;

    if (a && getParsingFlags(m).overflow === -2) {
        overflow =
            a[MONTH]       < 0 || a[MONTH]       > 11  ? MONTH :
            a[DATE]        < 1 || a[DATE]        > daysInMonth(a[YEAR], a[MONTH]) ? DATE :
            a[HOUR]        < 0 || a[HOUR]        > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR :
            a[MINUTE]      < 0 || a[MINUTE]      > 59  ? MINUTE :
            a[SECOND]      < 0 || a[SECOND]      > 59  ? SECOND :
            a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND :
            -1;

        if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
            overflow = DATE;
        }
        if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
            overflow = WEEK;
        }
        if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
            overflow = WEEKDAY;
        }

        getParsingFlags(m).overflow = overflow;
    }

    return m;
}

// Pick the first defined of two or three arguments.
function defaults(a, b, c) {
    if (a != null) {
        return a;
    }
    if (b != null) {
        return b;
    }
    return c;
}

function currentDateArray(config) {
    // hooks is actually the exported moment object
    var nowValue = new Date(hooks.now());
    if (config._useUTC) {
        return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
    }
    return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
}

// convert an array to a date.
// the array should mirror the parameters below
// note: all values past the year are optional and will default to the lowest possible value.
// [year, month, day , hour, minute, second, millisecond]
function configFromArray (config) {
    var i, date, input = [], currentDate, expectedWeekday, yearToUse;

    if (config._d) {
        return;
    }

    currentDate = currentDateArray(config);

    //compute day of the year from weeks and weekdays
    if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
        dayOfYearFromWeekInfo(config);
    }

    //if the day of the year is set, figure out what it is
    if (config._dayOfYear != null) {
        yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);

        if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) {
            getParsingFlags(config)._overflowDayOfYear = true;
        }

        date = createUTCDate(yearToUse, 0, config._dayOfYear);
        config._a[MONTH] = date.getUTCMonth();
        config._a[DATE] = date.getUTCDate();
    }

    // Default to current date.
    // * if no year, month, day of month are given, default to today
    // * if day of month is given, default month and year
    // * if month is given, default only year
    // * if year is given, don't default anything
    for (i = 0; i < 3 && config._a[i] == null; ++i) {
        config._a[i] = input[i] = currentDate[i];
    }

    // Zero out whatever was not defaulted, including time
    for (; i < 7; i++) {
        config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
    }

    // Check for 24:00:00.000
    if (config._a[HOUR] === 24 &&
            config._a[MINUTE] === 0 &&
            config._a[SECOND] === 0 &&
            config._a[MILLISECOND] === 0) {
        config._nextDay = true;
        config._a[HOUR] = 0;
    }

    config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
    expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay();

    // Apply timezone offset from input. The actual utcOffset can be changed
    // with parseZone.
    if (config._tzm != null) {
        config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
    }

    if (config._nextDay) {
        config._a[HOUR] = 24;
    }

    // check for mismatching day of week
    if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday) {
        getParsingFlags(config).weekdayMismatch = true;
    }
}

function dayOfYearFromWeekInfo(config) {
    var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow;

    w = config._w;
    if (w.GG != null || w.W != null || w.E != null) {
        dow = 1;
        doy = 4;

        // TODO: We need to take the current isoWeekYear, but that depends on
        // how we interpret now (local, utc, fixed offset). So create
        // a now version of current config (take local/utc/offset flags, and
        // create now).
        weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year);
        week = defaults(w.W, 1);
        weekday = defaults(w.E, 1);
        if (weekday < 1 || weekday > 7) {
            weekdayOverflow = true;
        }
    } else {
        dow = config._locale._week.dow;
        doy = config._locale._week.doy;

        var curWeek = weekOfYear(createLocal(), dow, doy);

        weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);

        // Default to current week.
        week = defaults(w.w, curWeek.week);

        if (w.d != null) {
            // weekday -- low day numbers are considered next week
            weekday = w.d;
            if (weekday < 0 || weekday > 6) {
                weekdayOverflow = true;
            }
        } else if (w.e != null) {
            // local weekday -- counting starts from begining of week
            weekday = w.e + dow;
            if (w.e < 0 || w.e > 6) {
                weekdayOverflow = true;
            }
        } else {
            // default to begining of week
            weekday = dow;
        }
    }
    if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
        getParsingFlags(config)._overflowWeeks = true;
    } else if (weekdayOverflow != null) {
        getParsingFlags(config)._overflowWeekday = true;
    } else {
        temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
        config._a[YEAR] = temp.year;
        config._dayOfYear = temp.dayOfYear;
    }
}

// iso 8601 regex
// 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;

var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;

var isoDates = [
    ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
    ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
    ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
    ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
    ['YYYY-DDD', /\d{4}-\d{3}/],
    ['YYYY-MM', /\d{4}-\d\d/, false],
    ['YYYYYYMMDD', /[+-]\d{10}/],
    ['YYYYMMDD', /\d{8}/],
    // YYYYMM is NOT allowed by the standard
    ['GGGG[W]WWE', /\d{4}W\d{3}/],
    ['GGGG[W]WW', /\d{4}W\d{2}/, false],
    ['YYYYDDD', /\d{7}/]
];

// iso time formats and regexes
var isoTimes = [
    ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
    ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
    ['HH:mm:ss', /\d\d:\d\d:\d\d/],
    ['HH:mm', /\d\d:\d\d/],
    ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
    ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
    ['HHmmss', /\d\d\d\d\d\d/],
    ['HHmm', /\d\d\d\d/],
    ['HH', /\d\d/]
];

var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;

// date from iso format
function configFromISO(config) {
    var i, l,
        string = config._i,
        match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
        allowTime, dateFormat, timeFormat, tzFormat;

    if (match) {
        getParsingFlags(config).iso = true;

        for (i = 0, l = isoDates.length; i < l; i++) {
            if (isoDates[i][1].exec(match[1])) {
                dateFormat = isoDates[i][0];
                allowTime = isoDates[i][2] !== false;
                break;
            }
        }
        if (dateFormat == null) {
            config._isValid = false;
            return;
        }
        if (match[3]) {
            for (i = 0, l = isoTimes.length; i < l; i++) {
                if (isoTimes[i][1].exec(match[3])) {
                    // match[2] should be 'T' or space
                    timeFormat = (match[2] || ' ') + isoTimes[i][0];
                    break;
                }
            }
            if (timeFormat == null) {
                config._isValid = false;
                return;
            }
        }
        if (!allowTime && timeFormat != null) {
            config._isValid = false;
            return;
        }
        if (match[4]) {
            if (tzRegex.exec(match[4])) {
                tzFormat = 'Z';
            } else {
                config._isValid = false;
                return;
            }
        }
        config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
        configFromStringAndFormat(config);
    } else {
        config._isValid = false;
    }
}

// RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/;

function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
    var result = [
        untruncateYear(yearStr),
        defaultLocaleMonthsShort.indexOf(monthStr),
        parseInt(dayStr, 10),
        parseInt(hourStr, 10),
        parseInt(minuteStr, 10)
    ];

    if (secondStr) {
        result.push(parseInt(secondStr, 10));
    }

    return result;
}

function untruncateYear(yearStr) {
    var year = parseInt(yearStr, 10);
    if (year <= 49) {
        return 2000 + year;
    } else if (year <= 999) {
        return 1900 + year;
    }
    return year;
}

function preprocessRFC2822(s) {
    // Remove comments and folding whitespace and replace multiple-spaces with a single space
    return s.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').trim();
}

function checkWeekday(weekdayStr, parsedInput, config) {
    if (weekdayStr) {
        // TODO: Replace the vanilla JS Date object with an indepentent day-of-week check.
        var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
            weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay();
        if (weekdayProvided !== weekdayActual) {
            getParsingFlags(config).weekdayMismatch = true;
            config._isValid = false;
            return false;
        }
    }
    return true;
}

var obsOffsets = {
    UT: 0,
    GMT: 0,
    EDT: -4 * 60,
    EST: -5 * 60,
    CDT: -5 * 60,
    CST: -6 * 60,
    MDT: -6 * 60,
    MST: -7 * 60,
    PDT: -7 * 60,
    PST: -8 * 60
};

function calculateOffset(obsOffset, militaryOffset, numOffset) {
    if (obsOffset) {
        return obsOffsets[obsOffset];
    } else if (militaryOffset) {
        // the only allowed military tz is Z
        return 0;
    } else {
        var hm = parseInt(numOffset, 10);
        var m = hm % 100, h = (hm - m) / 100;
        return h * 60 + m;
    }
}

// date and time from ref 2822 format
function configFromRFC2822(config) {
    var match = rfc2822.exec(preprocessRFC2822(config._i));
    if (match) {
        var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]);
        if (!checkWeekday(match[1], parsedArray, config)) {
            return;
        }

        config._a = parsedArray;
        config._tzm = calculateOffset(match[8], match[9], match[10]);

        config._d = createUTCDate.apply(null, config._a);
        config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);

        getParsingFlags(config).rfc2822 = true;
    } else {
        config._isValid = false;
    }
}

// date from iso format or fallback
function configFromString(config) {
    var matched = aspNetJsonRegex.exec(config._i);

    if (matched !== null) {
        config._d = new Date(+matched[1]);
        return;
    }

    configFromISO(config);
    if (config._isValid === false) {
        delete config._isValid;
    } else {
        return;
    }

    configFromRFC2822(config);
    if (config._isValid === false) {
        delete config._isValid;
    } else {
        return;
    }

    // Final attempt, use Input Fallback
    hooks.createFromInputFallback(config);
}

hooks.createFromInputFallback = deprecate(
    'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +
    'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +
    'discouraged and will be removed in an upcoming major release. Please refer to ' +
    'http://momentjs.com/guides/#/warnings/js-date/ for more info.',
    function (config) {
        config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
    }
);

// constant that refers to the ISO standard
hooks.ISO_8601 = function () {};

// constant that refers to the RFC 2822 form
hooks.RFC_2822 = function () {};

// date from string and format string
function configFromStringAndFormat(config) {
    // TODO: Move this to another part of the creation flow to prevent circular deps
    if (config._f === hooks.ISO_8601) {
        configFromISO(config);
        return;
    }
    if (config._f === hooks.RFC_2822) {
        configFromRFC2822(config);
        return;
    }
    config._a = [];
    getParsingFlags(config).empty = true;

    // This array is used to make a Date, either with `new Date` or `Date.UTC`
    var string = '' + config._i,
        i, parsedInput, tokens, token, skipped,
        stringLength = string.length,
        totalParsedInputLength = 0;

    tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];

    for (i = 0; i < tokens.length; i++) {
        token = tokens[i];
        parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
        // console.log('token', token, 'parsedInput', parsedInput,
        //         'regex', getParseRegexForToken(token, config));
        if (parsedInput) {
            skipped = string.substr(0, string.indexOf(parsedInput));
            if (skipped.length > 0) {
                getParsingFlags(config).unusedInput.push(skipped);
            }
            string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
            totalParsedInputLength += parsedInput.length;
        }
        // don't parse if it's not a known token
        if (formatTokenFunctions[token]) {
            if (parsedInput) {
                getParsingFlags(config).empty = false;
            }
            else {
                getParsingFlags(config).unusedTokens.push(token);
            }
            addTimeToArrayFromToken(token, parsedInput, config);
        }
        else if (config._strict && !parsedInput) {
            getParsingFlags(config).unusedTokens.push(token);
        }
    }

    // add remaining unparsed input length to the string
    getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
    if (string.length > 0) {
        getParsingFlags(config).unusedInput.push(string);
    }

    // clear _12h flag if hour is <= 12
    if (config._a[HOUR] <= 12 &&
        getParsingFlags(config).bigHour === true &&
        config._a[HOUR] > 0) {
        getParsingFlags(config).bigHour = undefined;
    }

    getParsingFlags(config).parsedDateParts = config._a.slice(0);
    getParsingFlags(config).meridiem = config._meridiem;
    // handle meridiem
    config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);

    configFromArray(config);
    checkOverflow(config);
}


function meridiemFixWrap (locale, hour, meridiem) {
    var isPm;

    if (meridiem == null) {
        // nothing to do
        return hour;
    }
    if (locale.meridiemHour != null) {
        return locale.meridiemHour(hour, meridiem);
    } else if (locale.isPM != null) {
        // Fallback
        isPm = locale.isPM(meridiem);
        if (isPm && hour < 12) {
            hour += 12;
        }
        if (!isPm && hour === 12) {
            hour = 0;
        }
        return hour;
    } else {
        // this is not supposed to happen
        return hour;
    }
}

// date from string and array of format strings
function configFromStringAndArray(config) {
    var tempConfig,
        bestMoment,

        scoreToBeat,
        i,
        currentScore;

    if (config._f.length === 0) {
        getParsingFlags(config).invalidFormat = true;
        config._d = new Date(NaN);
        return;
    }

    for (i = 0; i < config._f.length; i++) {
        currentScore = 0;
        tempConfig = copyConfig({}, config);
        if (config._useUTC != null) {
            tempConfig._useUTC = config._useUTC;
        }
        tempConfig._f = config._f[i];
        configFromStringAndFormat(tempConfig);

        if (!isValid(tempConfig)) {
            continue;
        }

        // if there is any input that was not parsed add a penalty for that format
        currentScore += getParsingFlags(tempConfig).charsLeftOver;

        //or tokens
        currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;

        getParsingFlags(tempConfig).score = currentScore;

        if (scoreToBeat == null || currentScore < scoreToBeat) {
            scoreToBeat = currentScore;
            bestMoment = tempConfig;
        }
    }

    extend(config, bestMoment || tempConfig);
}

function configFromObject(config) {
    if (config._d) {
        return;
    }

    var i = normalizeObjectUnits(config._i);
    config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) {
        return obj && parseInt(obj, 10);
    });

    configFromArray(config);
}

function createFromConfig (config) {
    var res = new Moment(checkOverflow(prepareConfig(config)));
    if (res._nextDay) {
        // Adding is smart enough around DST
        res.add(1, 'd');
        res._nextDay = undefined;
    }

    return res;
}

function prepareConfig (config) {
    var input = config._i,
        format = config._f;

    config._locale = config._locale || getLocale(config._l);

    if (input === null || (format === undefined && input === '')) {
        return createInvalid({nullInput: true});
    }

    if (typeof input === 'string') {
        config._i = input = config._locale.preparse(input);
    }

    if (isMoment(input)) {
        return new Moment(checkOverflow(input));
    } else if (isDate(input)) {
        config._d = input;
    } else if (isArray(format)) {
        configFromStringAndArray(config);
    } else if (format) {
        configFromStringAndFormat(config);
    }  else {
        configFromInput(config);
    }

    if (!isValid(config)) {
        config._d = null;
    }

    return config;
}

function configFromInput(config) {
    var input = config._i;
    if (isUndefined(input)) {
        config._d = new Date(hooks.now());
    } else if (isDate(input)) {
        config._d = new Date(input.valueOf());
    } else if (typeof input === 'string') {
        configFromString(config);
    } else if (isArray(input)) {
        config._a = map(input.slice(0), function (obj) {
            return parseInt(obj, 10);
        });
        configFromArray(config);
    } else if (isObject(input)) {
        configFromObject(config);
    } else if (isNumber(input)) {
        // from milliseconds
        config._d = new Date(input);
    } else {
        hooks.createFromInputFallback(config);
    }
}

function createLocalOrUTC (input, format, locale, strict, isUTC) {
    var c = {};

    if (locale === true || locale === false) {
        strict = locale;
        locale = undefined;
    }

    if ((isObject(input) && isObjectEmpty(input)) ||
            (isArray(input) && input.length === 0)) {
        input = undefined;
    }
    // object construction must be done this way.
    // https://github.com/moment/moment/issues/1423
    c._isAMomentObject = true;
    c._useUTC = c._isUTC = isUTC;
    c._l = locale;
    c._i = input;
    c._f = format;
    c._strict = strict;

    return createFromConfig(c);
}

function createLocal (input, format, locale, strict) {
    return createLocalOrUTC(input, format, locale, strict, false);
}

var prototypeMin = deprecate(
    'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
    function () {
        var other = createLocal.apply(null, arguments);
        if (this.isValid() && other.isValid()) {
            return other < this ? this : other;
        } else {
            return createInvalid();
        }
    }
);

var prototypeMax = deprecate(
    'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
    function () {
        var other = createLocal.apply(null, arguments);
        if (this.isValid() && other.isValid()) {
            return other > this ? this : other;
        } else {
            return createInvalid();
        }
    }
);

// Pick a moment m from moments so that m[fn](other) is true for all
// other. This relies on the function fn to be transitive.
//
// moments should either be an array of moment objects or an array, whose
// first element is an array of moment objects.
function pickBy(fn, moments) {
    var res, i;
    if (moments.length === 1 && isArray(moments[0])) {
        moments = moments[0];
    }
    if (!moments.length) {
        return createLocal();
    }
    res = moments[0];
    for (i = 1; i < moments.length; ++i) {
        if (!moments[i].isValid() || moments[i][fn](res)) {
            res = moments[i];
        }
    }
    return res;
}

// TODO: Use [].sort instead?
function min () {
    var args = [].slice.call(arguments, 0);

    return pickBy('isBefore', args);
}

function max () {
    var args = [].slice.call(arguments, 0);

    return pickBy('isAfter', args);
}

var now = function () {
    return Date.now ? Date.now() : +(new Date());
};

var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond'];

function isDurationValid(m) {
    for (var key in m) {
        if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) {
            return false;
        }
    }

    var unitHasDecimal = false;
    for (var i = 0; i < ordering.length; ++i) {
        if (m[ordering[i]]) {
            if (unitHasDecimal) {
                return false; // only allow non-integers for smallest unit
            }
            if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
                unitHasDecimal = true;
            }
        }
    }

    return true;
}

function isValid$1() {
    return this._isValid;
}

function createInvalid$1() {
    return createDuration(NaN);
}

function Duration (duration) {
    var normalizedInput = normalizeObjectUnits(duration),
        years = normalizedInput.year || 0,
        quarters = normalizedInput.quarter || 0,
        months = normalizedInput.month || 0,
        weeks = normalizedInput.week || 0,
        days = normalizedInput.day || 0,
        hours = normalizedInput.hour || 0,
        minutes = normalizedInput.minute || 0,
        seconds = normalizedInput.second || 0,
        milliseconds = normalizedInput.millisecond || 0;

    this._isValid = isDurationValid(normalizedInput);

    // representation for dateAddRemove
    this._milliseconds = +milliseconds +
        seconds * 1e3 + // 1000
        minutes * 6e4 + // 1000 * 60
        hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
    // Because of dateAddRemove treats 24 hours as different from a
    // day when working around DST, we need to store them separately
    this._days = +days +
        weeks * 7;
    // It is impossible to translate months into days without knowing
    // which months you are are talking about, so we have to store
    // it separately.
    this._months = +months +
        quarters * 3 +
        years * 12;

    this._data = {};

    this._locale = getLocale();

    this._bubble();
}

function isDuration (obj) {
    return obj instanceof Duration;
}

function absRound (number) {
    if (number < 0) {
        return Math.round(-1 * number) * -1;
    } else {
        return Math.round(number);
    }
}

// FORMATTING

function offset (token, separator) {
    addFormatToken(token, 0, 0, function () {
        var offset = this.utcOffset();
        var sign = '+';
        if (offset < 0) {
            offset = -offset;
            sign = '-';
        }
        return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
    });
}

offset('Z', ':');
offset('ZZ', '');

// PARSING

addRegexToken('Z',  matchShortOffset);
addRegexToken('ZZ', matchShortOffset);
addParseToken(['Z', 'ZZ'], function (input, array, config) {
    config._useUTC = true;
    config._tzm = offsetFromString(matchShortOffset, input);
});

// HELPERS

// timezone chunker
// '+10:00' > ['10',  '00']
// '-1530'  > ['-15', '30']
var chunkOffset = /([\+\-]|\d\d)/gi;

function offsetFromString(matcher, string) {
    var matches = (string || '').match(matcher);

    if (matches === null) {
        return null;
    }

    var chunk   = matches[matches.length - 1] || [];
    var parts   = (chunk + '').match(chunkOffset) || ['-', 0, 0];
    var minutes = +(parts[1] * 60) + toInt(parts[2]);

    return minutes === 0 ?
      0 :
      parts[0] === '+' ? minutes : -minutes;
}

// Return a moment from input, that is local/utc/zone equivalent to model.
function cloneWithOffset(input, model) {
    var res, diff;
    if (model._isUTC) {
        res = model.clone();
        diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf();
        // Use low-level api, because this fn is low-level api.
        res._d.setTime(res._d.valueOf() + diff);
        hooks.updateOffset(res, false);
        return res;
    } else {
        return createLocal(input).local();
    }
}

function getDateOffset (m) {
    // On Firefox.24 Date#getTimezoneOffset returns a floating point.
    // https://github.com/moment/moment/pull/1871
    return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
}

// HOOKS

// This function will be called whenever a moment is mutated.
// It is intended to keep the offset in sync with the timezone.
hooks.updateOffset = function () {};

// MOMENTS

// keepLocalTime = true means only change the timezone, without
// affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
// 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
// +0200, so we adjust the time as needed, to be valid.
//
// Keeping the time actually adds/subtracts (one hour)
// from the actual represented time. That is why we call updateOffset
// a second time. In case it wants us to change the offset again
// _changeInProgress == true case, then we have to adjust, because
// there is no such time in the given timezone.
function getSetOffset (input, keepLocalTime, keepMinutes) {
    var offset = this._offset || 0,
        localAdjust;
    if (!this.isValid()) {
        return input != null ? this : NaN;
    }
    if (input != null) {
        if (typeof input === 'string') {
            input = offsetFromString(matchShortOffset, input);
            if (input === null) {
                return this;
            }
        } else if (Math.abs(input) < 16 && !keepMinutes) {
            input = input * 60;
        }
        if (!this._isUTC && keepLocalTime) {
            localAdjust = getDateOffset(this);
        }
        this._offset = input;
        this._isUTC = true;
        if (localAdjust != null) {
            this.add(localAdjust, 'm');
        }
        if (offset !== input) {
            if (!keepLocalTime || this._changeInProgress) {
                addSubtract(this, createDuration(input - offset, 'm'), 1, false);
            } else if (!this._changeInProgress) {
                this._changeInProgress = true;
                hooks.updateOffset(this, true);
                this._changeInProgress = null;
            }
        }
        return this;
    } else {
        return this._isUTC ? offset : getDateOffset(this);
    }
}

function getSetZone (input, keepLocalTime) {
    if (input != null) {
        if (typeof input !== 'string') {
            input = -input;
        }

        this.utcOffset(input, keepLocalTime);

        return this;
    } else {
        return -this.utcOffset();
    }
}

function setOffsetToUTC (keepLocalTime) {
    return this.utcOffset(0, keepLocalTime);
}

function setOffsetToLocal (keepLocalTime) {
    if (this._isUTC) {
        this.utcOffset(0, keepLocalTime);
        this._isUTC = false;

        if (keepLocalTime) {
            this.subtract(getDateOffset(this), 'm');
        }
    }
    return this;
}

function setOffsetToParsedOffset () {
    if (this._tzm != null) {
        this.utcOffset(this._tzm, false, true);
    } else if (typeof this._i === 'string') {
        var tZone = offsetFromString(matchOffset, this._i);
        if (tZone != null) {
            this.utcOffset(tZone);
        }
        else {
            this.utcOffset(0, true);
        }
    }
    return this;
}

function hasAlignedHourOffset (input) {
    if (!this.isValid()) {
        return false;
    }
    input = input ? createLocal(input).utcOffset() : 0;

    return (this.utcOffset() - input) % 60 === 0;
}

function isDaylightSavingTime () {
    return (
        this.utcOffset() > this.clone().month(0).utcOffset() ||
        this.utcOffset() > this.clone().month(5).utcOffset()
    );
}

function isDaylightSavingTimeShifted () {
    if (!isUndefined(this._isDSTShifted)) {
        return this._isDSTShifted;
    }

    var c = {};

    copyConfig(c, this);
    c = prepareConfig(c);

    if (c._a) {
        var other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
        this._isDSTShifted = this.isValid() &&
            compareArrays(c._a, other.toArray()) > 0;
    } else {
        this._isDSTShifted = false;
    }

    return this._isDSTShifted;
}

function isLocal () {
    return this.isValid() ? !this._isUTC : false;
}

function isUtcOffset () {
    return this.isValid() ? this._isUTC : false;
}

function isUtc () {
    return this.isValid() ? this._isUTC && this._offset === 0 : false;
}

// ASP.NET json date format regex
var aspNetRegex = /^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/;

// from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
// somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
// and further modified to allow for strings containing both week and day
var isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;

function createDuration (input, key) {
    var duration = input,
        // matching against regexp is expensive, do it on demand
        match = null,
        sign,
        ret,
        diffRes;

    if (isDuration(input)) {
        duration = {
            ms : input._milliseconds,
            d  : input._days,
            M  : input._months
        };
    } else if (isNumber(input)) {
        duration = {};
        if (key) {
            duration[key] = input;
        } else {
            duration.milliseconds = input;
        }
    } else if (!!(match = aspNetRegex.exec(input))) {
        sign = (match[1] === '-') ? -1 : 1;
        duration = {
            y  : 0,
            d  : toInt(match[DATE])                         * sign,
            h  : toInt(match[HOUR])                         * sign,
            m  : toInt(match[MINUTE])                       * sign,
            s  : toInt(match[SECOND])                       * sign,
            ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match
        };
    } else if (!!(match = isoRegex.exec(input))) {
        sign = (match[1] === '-') ? -1 : (match[1] === '+') ? 1 : 1;
        duration = {
            y : parseIso(match[2], sign),
            M : parseIso(match[3], sign),
            w : parseIso(match[4], sign),
            d : parseIso(match[5], sign),
            h : parseIso(match[6], sign),
            m : parseIso(match[7], sign),
            s : parseIso(match[8], sign)
        };
    } else if (duration == null) {// checks for null or undefined
        duration = {};
    } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
        diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to));

        duration = {};
        duration.ms = diffRes.milliseconds;
        duration.M = diffRes.months;
    }

    ret = new Duration(duration);

    if (isDuration(input) && hasOwnProp(input, '_locale')) {
        ret._locale = input._locale;
    }

    return ret;
}

createDuration.fn = Duration.prototype;
createDuration.invalid = createInvalid$1;

function parseIso (inp, sign) {
    // We'd normally use ~~inp for this, but unfortunately it also
    // converts floats to ints.
    // inp may be undefined, so careful calling replace on it.
    var res = inp && parseFloat(inp.replace(',', '.'));
    // apply sign while we're at it
    return (isNaN(res) ? 0 : res) * sign;
}

function positiveMomentsDifference(base, other) {
    var res = {milliseconds: 0, months: 0};

    res.months = other.month() - base.month() +
        (other.year() - base.year()) * 12;
    if (base.clone().add(res.months, 'M').isAfter(other)) {
        --res.months;
    }

    res.milliseconds = +other - +(base.clone().add(res.months, 'M'));

    return res;
}

function momentsDifference(base, other) {
    var res;
    if (!(base.isValid() && other.isValid())) {
        return {milliseconds: 0, months: 0};
    }

    other = cloneWithOffset(other, base);
    if (base.isBefore(other)) {
        res = positiveMomentsDifference(base, other);
    } else {
        res = positiveMomentsDifference(other, base);
        res.milliseconds = -res.milliseconds;
        res.months = -res.months;
    }

    return res;
}

// TODO: remove 'name' arg after deprecation is removed
function createAdder(direction, name) {
    return function (val, period) {
        var dur, tmp;
        //invert the arguments, but complain about it
        if (period !== null && !isNaN(+period)) {
            deprecateSimple(name, 'moment().' + name  + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' +
            'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.');
            tmp = val; val = period; period = tmp;
        }

        val = typeof val === 'string' ? +val : val;
        dur = createDuration(val, period);
        addSubtract(this, dur, direction);
        return this;
    };
}

function addSubtract (mom, duration, isAdding, updateOffset) {
    var milliseconds = duration._milliseconds,
        days = absRound(duration._days),
        months = absRound(duration._months);

    if (!mom.isValid()) {
        // No op
        return;
    }

    updateOffset = updateOffset == null ? true : updateOffset;

    if (months) {
        setMonth(mom, get(mom, 'Month') + months * isAdding);
    }
    if (days) {
        set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
    }
    if (milliseconds) {
        mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
    }
    if (updateOffset) {
        hooks.updateOffset(mom, days || months);
    }
}

var add      = createAdder(1, 'add');
var subtract = createAdder(-1, 'subtract');

function getCalendarFormat(myMoment, now) {
    var diff = myMoment.diff(now, 'days', true);
    return diff < -6 ? 'sameElse' :
            diff < -1 ? 'lastWeek' :
            diff < 0 ? 'lastDay' :
            diff < 1 ? 'sameDay' :
            diff < 2 ? 'nextDay' :
            diff < 7 ? 'nextWeek' : 'sameElse';
}

function calendar$1 (time, formats) {
    // We want to compare the start of today, vs this.
    // Getting start-of-today depends on whether we're local/utc/offset or not.
    var now = time || createLocal(),
        sod = cloneWithOffset(now, this).startOf('day'),
        format = hooks.calendarFormat(this, sod) || 'sameElse';

    var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);

    return this.format(output || this.localeData().calendar(format, this, createLocal(now)));
}

function clone () {
    return new Moment(this);
}

function isAfter (input, units) {
    var localInput = isMoment(input) ? input : createLocal(input);
    if (!(this.isValid() && localInput.isValid())) {
        return false;
    }
    units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
    if (units === 'millisecond') {
        return this.valueOf() > localInput.valueOf();
    } else {
        return localInput.valueOf() < this.clone().startOf(units).valueOf();
    }
}

function isBefore (input, units) {
    var localInput = isMoment(input) ? input : createLocal(input);
    if (!(this.isValid() && localInput.isValid())) {
        return false;
    }
    units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
    if (units === 'millisecond') {
        return this.valueOf() < localInput.valueOf();
    } else {
        return this.clone().endOf(units).valueOf() < localInput.valueOf();
    }
}

function isBetween (from, to, units, inclusivity) {
    inclusivity = inclusivity || '()';
    return (inclusivity[0] === '(' ? this.isAfter(from, units) : !this.isBefore(from, units)) &&
        (inclusivity[1] === ')' ? this.isBefore(to, units) : !this.isAfter(to, units));
}

function isSame (input, units) {
    var localInput = isMoment(input) ? input : createLocal(input),
        inputMs;
    if (!(this.isValid() && localInput.isValid())) {
        return false;
    }
    units = normalizeUnits(units || 'millisecond');
    if (units === 'millisecond') {
        return this.valueOf() === localInput.valueOf();
    } else {
        inputMs = localInput.valueOf();
        return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
    }
}

function isSameOrAfter (input, units) {
    return this.isSame(input, units) || this.isAfter(input,units);
}

function isSameOrBefore (input, units) {
    return this.isSame(input, units) || this.isBefore(input,units);
}

function diff (input, units, asFloat) {
    var that,
        zoneDelta,
        output;

    if (!this.isValid()) {
        return NaN;
    }

    that = cloneWithOffset(input, this);

    if (!that.isValid()) {
        return NaN;
    }

    zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;

    units = normalizeUnits(units);

    switch (units) {
        case 'year': output = monthDiff(this, that) / 12; break;
        case 'month': output = monthDiff(this, that); break;
        case 'quarter': output = monthDiff(this, that) / 3; break;
        case 'second': output = (this - that) / 1e3; break; // 1000
        case 'minute': output = (this - that) / 6e4; break; // 1000 * 60
        case 'hour': output = (this - that) / 36e5; break; // 1000 * 60 * 60
        case 'day': output = (this - that - zoneDelta) / 864e5; break; // 1000 * 60 * 60 * 24, negate dst
        case 'week': output = (this - that - zoneDelta) / 6048e5; break; // 1000 * 60 * 60 * 24 * 7, negate dst
        default: output = this - that;
    }

    return asFloat ? output : absFloor(output);
}

function monthDiff (a, b) {
    // difference in months
    var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
        // b is in (anchor - 1 month, anchor + 1 month)
        anchor = a.clone().add(wholeMonthDiff, 'months'),
        anchor2, adjust;

    if (b - anchor < 0) {
        anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
        // linear across the month
        adjust = (b - anchor) / (anchor - anchor2);
    } else {
        anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
        // linear across the month
        adjust = (b - anchor) / (anchor2 - anchor);
    }

    //check for negative zero, return zero if negative zero
    return -(wholeMonthDiff + adjust) || 0;
}

hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';

function toString () {
    return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
}

function toISOString(keepOffset) {
    if (!this.isValid()) {
        return null;
    }
    var utc = keepOffset !== true;
    var m = utc ? this.clone().utc() : this;
    if (m.year() < 0 || m.year() > 9999) {
        return formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ');
    }
    if (isFunction(Date.prototype.toISOString)) {
        // native implementation is ~50x faster, use it when we can
        if (utc) {
            return this.toDate().toISOString();
        } else {
            return new Date(this.valueOf() + this.utcOffset() * 60 * 1000).toISOString().replace('Z', formatMoment(m, 'Z'));
        }
    }
    return formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ');
}

/**
 * Return a human readable representation of a moment that can
 * also be evaluated to get a new moment which is the same
 *
 * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
 */
function inspect () {
    if (!this.isValid()) {
        return 'moment.invalid(/* ' + this._i + ' */)';
    }
    var func = 'moment';
    var zone = '';
    if (!this.isLocal()) {
        func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
        zone = 'Z';
    }
    var prefix = '[' + func + '("]';
    var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY';
    var datetime = '-MM-DD[T]HH:mm:ss.SSS';
    var suffix = zone + '[")]';

    return this.format(prefix + year + datetime + suffix);
}

function format (inputString) {
    if (!inputString) {
        inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat;
    }
    var output = formatMoment(this, inputString);
    return this.localeData().postformat(output);
}

function from (time, withoutSuffix) {
    if (this.isValid() &&
            ((isMoment(time) && time.isValid()) ||
             createLocal(time).isValid())) {
        return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
    } else {
        return this.localeData().invalidDate();
    }
}

function fromNow (withoutSuffix) {
    return this.from(createLocal(), withoutSuffix);
}

function to (time, withoutSuffix) {
    if (this.isValid() &&
            ((isMoment(time) && time.isValid()) ||
             createLocal(time).isValid())) {
        return createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix);
    } else {
        return this.localeData().invalidDate();
    }
}

function toNow (withoutSuffix) {
    return this.to(createLocal(), withoutSuffix);
}

// If passed a locale key, it will set the locale for this
// instance.  Otherwise, it will return the locale configuration
// variables for this instance.
function locale (key) {
    var newLocaleData;

    if (key === undefined) {
        return this._locale._abbr;
    } else {
        newLocaleData = getLocale(key);
        if (newLocaleData != null) {
            this._locale = newLocaleData;
        }
        return this;
    }
}

var lang = deprecate(
    'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
    function (key) {
        if (key === undefined) {
            return this.localeData();
        } else {
            return this.locale(key);
        }
    }
);

function localeData () {
    return this._locale;
}

function startOf (units) {
    units = normalizeUnits(units);
    // the following switch intentionally omits break keywords
    // to utilize falling through the cases.
    switch (units) {
        case 'year':
            this.month(0);
            /* falls through */
        case 'quarter':
        case 'month':
            this.date(1);
            /* falls through */
        case 'week':
        case 'isoWeek':
        case 'day':
        case 'date':
            this.hours(0);
            /* falls through */
        case 'hour':
            this.minutes(0);
            /* falls through */
        case 'minute':
            this.seconds(0);
            /* falls through */
        case 'second':
            this.milliseconds(0);
    }

    // weeks are a special case
    if (units === 'week') {
        this.weekday(0);
    }
    if (units === 'isoWeek') {
        this.isoWeekday(1);
    }

    // quarters are also special
    if (units === 'quarter') {
        this.month(Math.floor(this.month() / 3) * 3);
    }

    return this;
}

function endOf (units) {
    units = normalizeUnits(units);
    if (units === undefined || units === 'millisecond') {
        return this;
    }

    // 'date' is an alias for 'day', so it should be considered as such.
    if (units === 'date') {
        units = 'day';
    }

    return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
}

function valueOf () {
    return this._d.valueOf() - ((this._offset || 0) * 60000);
}

function unix () {
    return Math.floor(this.valueOf() / 1000);
}

function toDate () {
    return new Date(this.valueOf());
}

function toArray () {
    var m = this;
    return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
}

function toObject () {
    var m = this;
    return {
        years: m.year(),
        months: m.month(),
        date: m.date(),
        hours: m.hours(),
        minutes: m.minutes(),
        seconds: m.seconds(),
        milliseconds: m.milliseconds()
    };
}

function toJSON () {
    // new Date(NaN).toJSON() === null
    return this.isValid() ? this.toISOString() : null;
}

function isValid$2 () {
    return isValid(this);
}

function parsingFlags () {
    return extend({}, getParsingFlags(this));
}

function invalidAt () {
    return getParsingFlags(this).overflow;
}

function creationData() {
    return {
        input: this._i,
        format: this._f,
        locale: this._locale,
        isUTC: this._isUTC,
        strict: this._strict
    };
}

// FORMATTING

addFormatToken(0, ['gg', 2], 0, function () {
    return this.weekYear() % 100;
});

addFormatToken(0, ['GG', 2], 0, function () {
    return this.isoWeekYear() % 100;
});

function addWeekYearFormatToken (token, getter) {
    addFormatToken(0, [token, token.length], 0, getter);
}

addWeekYearFormatToken('gggg',     'weekYear');
addWeekYearFormatToken('ggggg',    'weekYear');
addWeekYearFormatToken('GGGG',  'isoWeekYear');
addWeekYearFormatToken('GGGGG', 'isoWeekYear');

// ALIASES

addUnitAlias('weekYear', 'gg');
addUnitAlias('isoWeekYear', 'GG');

// PRIORITY

addUnitPriority('weekYear', 1);
addUnitPriority('isoWeekYear', 1);


// PARSING

addRegexToken('G',      matchSigned);
addRegexToken('g',      matchSigned);
addRegexToken('GG',     match1to2, match2);
addRegexToken('gg',     match1to2, match2);
addRegexToken('GGGG',   match1to4, match4);
addRegexToken('gggg',   match1to4, match4);
addRegexToken('GGGGG',  match1to6, match6);
addRegexToken('ggggg',  match1to6, match6);

addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
    week[token.substr(0, 2)] = toInt(input);
});

addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
    week[token] = hooks.parseTwoDigitYear(input);
});

// MOMENTS

function getSetWeekYear (input) {
    return getSetWeekYearHelper.call(this,
            input,
            this.week(),
            this.weekday(),
            this.localeData()._week.dow,
            this.localeData()._week.doy);
}

function getSetISOWeekYear (input) {
    return getSetWeekYearHelper.call(this,
            input, this.isoWeek(), this.isoWeekday(), 1, 4);
}

function getISOWeeksInYear () {
    return weeksInYear(this.year(), 1, 4);
}

function getWeeksInYear () {
    var weekInfo = this.localeData()._week;
    return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
}

function getSetWeekYearHelper(input, week, weekday, dow, doy) {
    var weeksTarget;
    if (input == null) {
        return weekOfYear(this, dow, doy).year;
    } else {
        weeksTarget = weeksInYear(input, dow, doy);
        if (week > weeksTarget) {
            week = weeksTarget;
        }
        return setWeekAll.call(this, input, week, weekday, dow, doy);
    }
}

function setWeekAll(weekYear, week, weekday, dow, doy) {
    var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
        date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);

    this.year(date.getUTCFullYear());
    this.month(date.getUTCMonth());
    this.date(date.getUTCDate());
    return this;
}

// FORMATTING

addFormatToken('Q', 0, 'Qo', 'quarter');

// ALIASES

addUnitAlias('quarter', 'Q');

// PRIORITY

addUnitPriority('quarter', 7);

// PARSING

addRegexToken('Q', match1);
addParseToken('Q', function (input, array) {
    array[MONTH] = (toInt(input) - 1) * 3;
});

// MOMENTS

function getSetQuarter (input) {
    return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
}

// FORMATTING

addFormatToken('D', ['DD', 2], 'Do', 'date');

// ALIASES

addUnitAlias('date', 'D');

// PRIOROITY
addUnitPriority('date', 9);

// PARSING

addRegexToken('D',  match1to2);
addRegexToken('DD', match1to2, match2);
addRegexToken('Do', function (isStrict, locale) {
    // TODO: Remove "ordinalParse" fallback in next major release.
    return isStrict ?
      (locale._dayOfMonthOrdinalParse || locale._ordinalParse) :
      locale._dayOfMonthOrdinalParseLenient;
});

addParseToken(['D', 'DD'], DATE);
addParseToken('Do', function (input, array) {
    array[DATE] = toInt(input.match(match1to2)[0]);
});

// MOMENTS

var getSetDayOfMonth = makeGetSet('Date', true);

// FORMATTING

addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');

// ALIASES

addUnitAlias('dayOfYear', 'DDD');

// PRIORITY
addUnitPriority('dayOfYear', 4);

// PARSING

addRegexToken('DDD',  match1to3);
addRegexToken('DDDD', match3);
addParseToken(['DDD', 'DDDD'], function (input, array, config) {
    config._dayOfYear = toInt(input);
});

// HELPERS

// MOMENTS

function getSetDayOfYear (input) {
    var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
    return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
}

// FORMATTING

addFormatToken('m', ['mm', 2], 0, 'minute');

// ALIASES

addUnitAlias('minute', 'm');

// PRIORITY

addUnitPriority('minute', 14);

// PARSING

addRegexToken('m',  match1to2);
addRegexToken('mm', match1to2, match2);
addParseToken(['m', 'mm'], MINUTE);

// MOMENTS

var getSetMinute = makeGetSet('Minutes', false);

// FORMATTING

addFormatToken('s', ['ss', 2], 0, 'second');

// ALIASES

addUnitAlias('second', 's');

// PRIORITY

addUnitPriority('second', 15);

// PARSING

addRegexToken('s',  match1to2);
addRegexToken('ss', match1to2, match2);
addParseToken(['s', 'ss'], SECOND);

// MOMENTS

var getSetSecond = makeGetSet('Seconds', false);

// FORMATTING

addFormatToken('S', 0, 0, function () {
    return ~~(this.millisecond() / 100);
});

addFormatToken(0, ['SS', 2], 0, function () {
    return ~~(this.millisecond() / 10);
});

addFormatToken(0, ['SSS', 3], 0, 'millisecond');
addFormatToken(0, ['SSSS', 4], 0, function () {
    return this.millisecond() * 10;
});
addFormatToken(0, ['SSSSS', 5], 0, function () {
    return this.millisecond() * 100;
});
addFormatToken(0, ['SSSSSS', 6], 0, function () {
    return this.millisecond() * 1000;
});
addFormatToken(0, ['SSSSSSS', 7], 0, function () {
    return this.millisecond() * 10000;
});
addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
    return this.millisecond() * 100000;
});
addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
    return this.millisecond() * 1000000;
});


// ALIASES

addUnitAlias('millisecond', 'ms');

// PRIORITY

addUnitPriority('millisecond', 16);

// PARSING

addRegexToken('S',    match1to3, match1);
addRegexToken('SS',   match1to3, match2);
addRegexToken('SSS',  match1to3, match3);

var token;
for (token = 'SSSS'; token.length <= 9; token += 'S') {
    addRegexToken(token, matchUnsigned);
}

function parseMs(input, array) {
    array[MILLISECOND] = toInt(('0.' + input) * 1000);
}

for (token = 'S'; token.length <= 9; token += 'S') {
    addParseToken(token, parseMs);
}
// MOMENTS

var getSetMillisecond = makeGetSet('Milliseconds', false);

// FORMATTING

addFormatToken('z',  0, 0, 'zoneAbbr');
addFormatToken('zz', 0, 0, 'zoneName');

// MOMENTS

function getZoneAbbr () {
    return this._isUTC ? 'UTC' : '';
}

function getZoneName () {
    return this._isUTC ? 'Coordinated Universal Time' : '';
}

var proto = Moment.prototype;

proto.add               = add;
proto.calendar          = calendar$1;
proto.clone             = clone;
proto.diff              = diff;
proto.endOf             = endOf;
proto.format            = format;
proto.from              = from;
proto.fromNow           = fromNow;
proto.to                = to;
proto.toNow             = toNow;
proto.get               = stringGet;
proto.invalidAt         = invalidAt;
proto.isAfter           = isAfter;
proto.isBefore          = isBefore;
proto.isBetween         = isBetween;
proto.isSame            = isSame;
proto.isSameOrAfter     = isSameOrAfter;
proto.isSameOrBefore    = isSameOrBefore;
proto.isValid           = isValid$2;
proto.lang              = lang;
proto.locale            = locale;
proto.localeData        = localeData;
proto.max               = prototypeMax;
proto.min               = prototypeMin;
proto.parsingFlags      = parsingFlags;
proto.set               = stringSet;
proto.startOf           = startOf;
proto.subtract          = subtract;
proto.toArray           = toArray;
proto.toObject          = toObject;
proto.toDate            = toDate;
proto.toISOString       = toISOString;
proto.inspect           = inspect;
proto.toJSON            = toJSON;
proto.toString          = toString;
proto.unix              = unix;
proto.valueOf           = valueOf;
proto.creationData      = creationData;
proto.year       = getSetYear;
proto.isLeapYear = getIsLeapYear;
proto.weekYear    = getSetWeekYear;
proto.isoWeekYear = getSetISOWeekYear;
proto.quarter = proto.quarters = getSetQuarter;
proto.month       = getSetMonth;
proto.daysInMonth = getDaysInMonth;
proto.week           = proto.weeks        = getSetWeek;
proto.isoWeek        = proto.isoWeeks     = getSetISOWeek;
proto.weeksInYear    = getWeeksInYear;
proto.isoWeeksInYear = getISOWeeksInYear;
proto.date       = getSetDayOfMonth;
proto.day        = proto.days             = getSetDayOfWeek;
proto.weekday    = getSetLocaleDayOfWeek;
proto.isoWeekday = getSetISODayOfWeek;
proto.dayOfYear  = getSetDayOfYear;
proto.hour = proto.hours = getSetHour;
proto.minute = proto.minutes = getSetMinute;
proto.second = proto.seconds = getSetSecond;
proto.millisecond = proto.milliseconds = getSetMillisecond;
proto.utcOffset            = getSetOffset;
proto.utc                  = setOffsetToUTC;
proto.local                = setOffsetToLocal;
proto.parseZone            = setOffsetToParsedOffset;
proto.hasAlignedHourOffset = hasAlignedHourOffset;
proto.isDST                = isDaylightSavingTime;
proto.isLocal              = isLocal;
proto.isUtcOffset          = isUtcOffset;
proto.isUtc                = isUtc;
proto.isUTC                = isUtc;
proto.zoneAbbr = getZoneAbbr;
proto.zoneName = getZoneName;
proto.dates  = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
proto.years  = deprecate('years accessor is deprecated. Use year instead', getSetYear);
proto.zone   = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone);
proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted);

function createUnix (input) {
    return createLocal(input * 1000);
}

function createInZone () {
    return createLocal.apply(null, arguments).parseZone();
}

function preParsePostFormat (string) {
    return string;
}

var proto$1 = Locale.prototype;

proto$1.calendar        = calendar;
proto$1.longDateFormat  = longDateFormat;
proto$1.invalidDate     = invalidDate;
proto$1.ordinal         = ordinal;
proto$1.preparse        = preParsePostFormat;
proto$1.postformat      = preParsePostFormat;
proto$1.relativeTime    = relativeTime;
proto$1.pastFuture      = pastFuture;
proto$1.set             = set;

proto$1.months            =        localeMonths;
proto$1.monthsShort       =        localeMonthsShort;
proto$1.monthsParse       =        localeMonthsParse;
proto$1.monthsRegex       = monthsRegex;
proto$1.monthsShortRegex  = monthsShortRegex;
proto$1.week = localeWeek;
proto$1.firstDayOfYear = localeFirstDayOfYear;
proto$1.firstDayOfWeek = localeFirstDayOfWeek;

proto$1.weekdays       =        localeWeekdays;
proto$1.weekdaysMin    =        localeWeekdaysMin;
proto$1.weekdaysShort  =        localeWeekdaysShort;
proto$1.weekdaysParse  =        localeWeekdaysParse;

proto$1.weekdaysRegex       =        weekdaysRegex;
proto$1.weekdaysShortRegex  =        weekdaysShortRegex;
proto$1.weekdaysMinRegex    =        weekdaysMinRegex;

proto$1.isPM = localeIsPM;
proto$1.meridiem = localeMeridiem;

function get$1 (format, index, field, setter) {
    var locale = getLocale();
    var utc = createUTC().set(setter, index);
    return locale[field](utc, format);
}

function listMonthsImpl (format, index, field) {
    if (isNumber(format)) {
        index = format;
        format = undefined;
    }

    format = format || '';

    if (index != null) {
        return get$1(format, index, field, 'month');
    }

    var i;
    var out = [];
    for (i = 0; i < 12; i++) {
        out[i] = get$1(format, i, field, 'month');
    }
    return out;
}

// ()
// (5)
// (fmt, 5)
// (fmt)
// (true)
// (true, 5)
// (true, fmt, 5)
// (true, fmt)
function listWeekdaysImpl (localeSorted, format, index, field) {
    if (typeof localeSorted === 'boolean') {
        if (isNumber(format)) {
            index = format;
            format = undefined;
        }

        format = format || '';
    } else {
        format = localeSorted;
        index = format;
        localeSorted = false;

        if (isNumber(format)) {
            index = format;
            format = undefined;
        }

        format = format || '';
    }

    var locale = getLocale(),
        shift = localeSorted ? locale._week.dow : 0;

    if (index != null) {
        return get$1(format, (index + shift) % 7, field, 'day');
    }

    var i;
    var out = [];
    for (i = 0; i < 7; i++) {
        out[i] = get$1(format, (i + shift) % 7, field, 'day');
    }
    return out;
}

function listMonths (format, index) {
    return listMonthsImpl(format, index, 'months');
}

function listMonthsShort (format, index) {
    return listMonthsImpl(format, index, 'monthsShort');
}

function listWeekdays (localeSorted, format, index) {
    return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
}

function listWeekdaysShort (localeSorted, format, index) {
    return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
}

function listWeekdaysMin (localeSorted, format, index) {
    return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
}

getSetGlobalLocale('en', {
    dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
    ordinal : function (number) {
        var b = number % 10,
            output = (toInt(number % 100 / 10) === 1) ? 'th' :
            (b === 1) ? 'st' :
            (b === 2) ? 'nd' :
            (b === 3) ? 'rd' : 'th';
        return number + output;
    }
});

// Side effect imports

hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale);
hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale);

var mathAbs = Math.abs;

function abs () {
    var data           = this._data;

    this._milliseconds = mathAbs(this._milliseconds);
    this._days         = mathAbs(this._days);
    this._months       = mathAbs(this._months);

    data.milliseconds  = mathAbs(data.milliseconds);
    data.seconds       = mathAbs(data.seconds);
    data.minutes       = mathAbs(data.minutes);
    data.hours         = mathAbs(data.hours);
    data.months        = mathAbs(data.months);
    data.years         = mathAbs(data.years);

    return this;
}

function addSubtract$1 (duration, input, value, direction) {
    var other = createDuration(input, value);

    duration._milliseconds += direction * other._milliseconds;
    duration._days         += direction * other._days;
    duration._months       += direction * other._months;

    return duration._bubble();
}

// supports only 2.0-style add(1, 's') or add(duration)
function add$1 (input, value) {
    return addSubtract$1(this, input, value, 1);
}

// supports only 2.0-style subtract(1, 's') or subtract(duration)
function subtract$1 (input, value) {
    return addSubtract$1(this, input, value, -1);
}

function absCeil (number) {
    if (number < 0) {
        return Math.floor(number);
    } else {
        return Math.ceil(number);
    }
}

function bubble () {
    var milliseconds = this._milliseconds;
    var days         = this._days;
    var months       = this._months;
    var data         = this._data;
    var seconds, minutes, hours, years, monthsFromDays;

    // if we have a mix of positive and negative values, bubble down first
    // check: https://github.com/moment/moment/issues/2166
    if (!((milliseconds >= 0 && days >= 0 && months >= 0) ||
            (milliseconds <= 0 && days <= 0 && months <= 0))) {
        milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
        days = 0;
        months = 0;
    }

    // The following code bubbles up values, see the tests for
    // examples of what that means.
    data.milliseconds = milliseconds % 1000;

    seconds           = absFloor(milliseconds / 1000);
    data.seconds      = seconds % 60;

    minutes           = absFloor(seconds / 60);
    data.minutes      = minutes % 60;

    hours             = absFloor(minutes / 60);
    data.hours        = hours % 24;

    days += absFloor(hours / 24);

    // convert days to months
    monthsFromDays = absFloor(daysToMonths(days));
    months += monthsFromDays;
    days -= absCeil(monthsToDays(monthsFromDays));

    // 12 months -> 1 year
    years = absFloor(months / 12);
    months %= 12;

    data.days   = days;
    data.months = months;
    data.years  = years;

    return this;
}

function daysToMonths (days) {
    // 400 years have 146097 days (taking into account leap year rules)
    // 400 years have 12 months === 4800
    return days * 4800 / 146097;
}

function monthsToDays (months) {
    // the reverse of daysToMonths
    return months * 146097 / 4800;
}

function as (units) {
    if (!this.isValid()) {
        return NaN;
    }
    var days;
    var months;
    var milliseconds = this._milliseconds;

    units = normalizeUnits(units);

    if (units === 'month' || units === 'year') {
        days   = this._days   + milliseconds / 864e5;
        months = this._months + daysToMonths(days);
        return units === 'month' ? months : months / 12;
    } else {
        // handle milliseconds separately because of floating point math errors (issue #1867)
        days = this._days + Math.round(monthsToDays(this._months));
        switch (units) {
            case 'week'   : return days / 7     + milliseconds / 6048e5;
            case 'day'    : return days         + milliseconds / 864e5;
            case 'hour'   : return days * 24    + milliseconds / 36e5;
            case 'minute' : return days * 1440  + milliseconds / 6e4;
            case 'second' : return days * 86400 + milliseconds / 1000;
            // Math.floor prevents floating point math errors here
            case 'millisecond': return Math.floor(days * 864e5) + milliseconds;
            default: throw new Error('Unknown unit ' + units);
        }
    }
}

// TODO: Use this.as('ms')?
function valueOf$1 () {
    if (!this.isValid()) {
        return NaN;
    }
    return (
        this._milliseconds +
        this._days * 864e5 +
        (this._months % 12) * 2592e6 +
        toInt(this._months / 12) * 31536e6
    );
}

function makeAs (alias) {
    return function () {
        return this.as(alias);
    };
}

var asMilliseconds = makeAs('ms');
var asSeconds      = makeAs('s');
var asMinutes      = makeAs('m');
var asHours        = makeAs('h');
var asDays         = makeAs('d');
var asWeeks        = makeAs('w');
var asMonths       = makeAs('M');
var asYears        = makeAs('y');

function clone$1 () {
    return createDuration(this);
}

function get$2 (units) {
    units = normalizeUnits(units);
    return this.isValid() ? this[units + 's']() : NaN;
}

function makeGetter(name) {
    return function () {
        return this.isValid() ? this._data[name] : NaN;
    };
}

var milliseconds = makeGetter('milliseconds');
var seconds      = makeGetter('seconds');
var minutes      = makeGetter('minutes');
var hours        = makeGetter('hours');
var days         = makeGetter('days');
var months       = makeGetter('months');
var years        = makeGetter('years');

function weeks () {
    return absFloor(this.days() / 7);
}

var round = Math.round;
var thresholds = {
    ss: 44,         // a few seconds to seconds
    s : 45,         // seconds to minute
    m : 45,         // minutes to hour
    h : 22,         // hours to day
    d : 26,         // days to month
    M : 11          // months to year
};

// helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
    return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
}

function relativeTime$1 (posNegDuration, withoutSuffix, locale) {
    var duration = createDuration(posNegDuration).abs();
    var seconds  = round(duration.as('s'));
    var minutes  = round(duration.as('m'));
    var hours    = round(duration.as('h'));
    var days     = round(duration.as('d'));
    var months   = round(duration.as('M'));
    var years    = round(duration.as('y'));

    var a = seconds <= thresholds.ss && ['s', seconds]  ||
            seconds < thresholds.s   && ['ss', seconds] ||
            minutes <= 1             && ['m']           ||
            minutes < thresholds.m   && ['mm', minutes] ||
            hours   <= 1             && ['h']           ||
            hours   < thresholds.h   && ['hh', hours]   ||
            days    <= 1             && ['d']           ||
            days    < thresholds.d   && ['dd', days]    ||
            months  <= 1             && ['M']           ||
            months  < thresholds.M   && ['MM', months]  ||
            years   <= 1             && ['y']           || ['yy', years];

    a[2] = withoutSuffix;
    a[3] = +posNegDuration > 0;
    a[4] = locale;
    return substituteTimeAgo.apply(null, a);
}

// This function allows you to set the rounding function for relative time strings
function getSetRelativeTimeRounding (roundingFunction) {
    if (roundingFunction === undefined) {
        return round;
    }
    if (typeof(roundingFunction) === 'function') {
        round = roundingFunction;
        return true;
    }
    return false;
}

// This function allows you to set a threshold for relative time strings
function getSetRelativeTimeThreshold (threshold, limit) {
    if (thresholds[threshold] === undefined) {
        return false;
    }
    if (limit === undefined) {
        return thresholds[threshold];
    }
    thresholds[threshold] = limit;
    if (threshold === 's') {
        thresholds.ss = limit - 1;
    }
    return true;
}

function humanize (withSuffix) {
    if (!this.isValid()) {
        return this.localeData().invalidDate();
    }

    var locale = this.localeData();
    var output = relativeTime$1(this, !withSuffix, locale);

    if (withSuffix) {
        output = locale.pastFuture(+this, output);
    }

    return locale.postformat(output);
}

var abs$1 = Math.abs;

function sign(x) {
    return ((x > 0) - (x < 0)) || +x;
}

function toISOString$1() {
    // for ISO strings we do not use the normal bubbling rules:
    //  * milliseconds bubble up until they become hours
    //  * days do not bubble at all
    //  * months bubble up until they become years
    // This is because there is no context-free conversion between hours and days
    // (think of clock changes)
    // and also not between days and months (28-31 days per month)
    if (!this.isValid()) {
        return this.localeData().invalidDate();
    }

    var seconds = abs$1(this._milliseconds) / 1000;
    var days         = abs$1(this._days);
    var months       = abs$1(this._months);
    var minutes, hours, years;

    // 3600 seconds -> 60 minutes -> 1 hour
    minutes           = absFloor(seconds / 60);
    hours             = absFloor(minutes / 60);
    seconds %= 60;
    minutes %= 60;

    // 12 months -> 1 year
    years  = absFloor(months / 12);
    months %= 12;


    // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
    var Y = years;
    var M = months;
    var D = days;
    var h = hours;
    var m = minutes;
    var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
    var total = this.asSeconds();

    if (!total) {
        // this is the same as C#'s (Noda) and python (isodate)...
        // but not other JS (goog.date)
        return 'P0D';
    }

    var totalSign = total < 0 ? '-' : '';
    var ymSign = sign(this._months) !== sign(total) ? '-' : '';
    var daysSign = sign(this._days) !== sign(total) ? '-' : '';
    var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';

    return totalSign + 'P' +
        (Y ? ymSign + Y + 'Y' : '') +
        (M ? ymSign + M + 'M' : '') +
        (D ? daysSign + D + 'D' : '') +
        ((h || m || s) ? 'T' : '') +
        (h ? hmsSign + h + 'H' : '') +
        (m ? hmsSign + m + 'M' : '') +
        (s ? hmsSign + s + 'S' : '');
}

var proto$2 = Duration.prototype;

proto$2.isValid        = isValid$1;
proto$2.abs            = abs;
proto$2.add            = add$1;
proto$2.subtract       = subtract$1;
proto$2.as             = as;
proto$2.asMilliseconds = asMilliseconds;
proto$2.asSeconds      = asSeconds;
proto$2.asMinutes      = asMinutes;
proto$2.asHours        = asHours;
proto$2.asDays         = asDays;
proto$2.asWeeks        = asWeeks;
proto$2.asMonths       = asMonths;
proto$2.asYears        = asYears;
proto$2.valueOf        = valueOf$1;
proto$2._bubble        = bubble;
proto$2.clone          = clone$1;
proto$2.get            = get$2;
proto$2.milliseconds   = milliseconds;
proto$2.seconds        = seconds;
proto$2.minutes        = minutes;
proto$2.hours          = hours;
proto$2.days           = days;
proto$2.weeks          = weeks;
proto$2.months         = months;
proto$2.years          = years;
proto$2.humanize       = humanize;
proto$2.toISOString    = toISOString$1;
proto$2.toString       = toISOString$1;
proto$2.toJSON         = toISOString$1;
proto$2.locale         = locale;
proto$2.localeData     = localeData;

proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1);
proto$2.lang = lang;

// Side effect imports

// FORMATTING

addFormatToken('X', 0, 0, 'unix');
addFormatToken('x', 0, 0, 'valueOf');

// PARSING

addRegexToken('x', matchSigned);
addRegexToken('X', matchTimestamp);
addParseToken('X', function (input, array, config) {
    config._d = new Date(parseFloat(input, 10) * 1000);
});
addParseToken('x', function (input, array, config) {
    config._d = new Date(toInt(input));
});

// Side effect imports


hooks.version = '2.21.0';

setHookCallback(createLocal);

hooks.fn                    = proto;
hooks.min                   = min;
hooks.max                   = max;
hooks.now                   = now;
hooks.utc                   = createUTC;
hooks.unix                  = createUnix;
hooks.months                = listMonths;
hooks.isDate                = isDate;
hooks.locale                = getSetGlobalLocale;
hooks.invalid               = createInvalid;
hooks.duration              = createDuration;
hooks.isMoment              = isMoment;
hooks.weekdays              = listWeekdays;
hooks.parseZone             = createInZone;
hooks.localeData            = getLocale;
hooks.isDuration            = isDuration;
hooks.monthsShort           = listMonthsShort;
hooks.weekdaysMin           = listWeekdaysMin;
hooks.defineLocale          = defineLocale;
hooks.updateLocale          = updateLocale;
hooks.locales               = listLocales;
hooks.weekdaysShort         = listWeekdaysShort;
hooks.normalizeUnits        = normalizeUnits;
hooks.relativeTimeRounding  = getSetRelativeTimeRounding;
hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
hooks.calendarFormat        = getCalendarFormat;
hooks.prototype             = proto;

// currently HTML5 input type only supports 24-hour formats
hooks.HTML5_FMT = {
    DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm',             // <input type="datetime-local" />
    DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss',  // <input type="datetime-local" step="1" />
    DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS',   // <input type="datetime-local" step="0.001" />
    DATE: 'YYYY-MM-DD',                             // <input type="date" />
    TIME: 'HH:mm',                                  // <input type="time" />
    TIME_SECONDS: 'HH:mm:ss',                       // <input type="time" step="1" />
    TIME_MS: 'HH:mm:ss.SSS',                        // <input type="time" step="0.001" />
    WEEK: 'YYYY-[W]WW',                             // <input type="week" />
    MONTH: 'YYYY-MM'                                // <input type="month" />
};

return hooks;

})));

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/module.js */ "YuTi")(module)))

/***/ }),

/***/ "weFL":
/*!******************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/AnnotationAccordion.js ***!
  \******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _PlotlyFold = __webpack_require__(/*! ./PlotlyFold */ "mQPs");

var _PlotlyFold2 = _interopRequireDefault(_PlotlyFold);

var _derived = __webpack_require__(/*! ./derived */ "ykRn");

var _PanelEmpty = __webpack_require__(/*! ./PanelEmpty */ "o21U");

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var AnnotationFold = (0, _lib.connectAnnotationToLayout)(_PlotlyFold2.default);

var AnnotationAccordion = function (_Component) {
  _inherits(AnnotationAccordion, _Component);

  function AnnotationAccordion() {
    _classCallCheck(this, AnnotationAccordion);

    return _possibleConstructorReturn(this, (AnnotationAccordion.__proto__ || Object.getPrototypeOf(AnnotationAccordion)).apply(this, arguments));
  }

  _createClass(AnnotationAccordion, [{
    key: 'render',
    value: function render() {
      var _context = this.context,
          _context$layout = _context.layout,
          _context$layout$annot = _context$layout.annotations,
          annotations = _context$layout$annot === undefined ? [] : _context$layout$annot,
          _context$layout$meta = _context$layout.meta,
          meta = _context$layout$meta === undefined ? [] : _context$layout$meta,
          _ = _context.localize;
      var _props = this.props,
          canAdd = _props.canAdd,
          children = _props.children;


      var content = annotations.length && annotations.map(function (ann, i) {
        return _react2.default.createElement(
          AnnotationFold,
          {
            key: i,
            annotationIndex: i,
            name: (0, _lib.getParsedTemplateString)(ann.text, meta),
            canDelete: canAdd
          },
          children
        );
      });

      var addAction = {
        label: _('Annotation'),
        handler: function handler(_ref) {
          var layout = _ref.layout,
              updateContainer = _ref.updateContainer;

          var annotationIndex = void 0;
          if (Array.isArray(layout.annotations)) {
            annotationIndex = layout.annotations.length;
          } else {
            annotationIndex = 0;
          }

          var key = 'annotations[' + annotationIndex + ']';
          var value = { text: _('new text') };

          if (updateContainer) {
            updateContainer(_defineProperty({}, key, value));
          }
        }
      };

      return _react2.default.createElement(
        _derived.LayoutPanel,
        { addAction: canAdd ? addAction : null },
        content ? content : _react2.default.createElement(
          _PanelEmpty.PanelMessage,
          { heading: _('Call out your data.') },
          _react2.default.createElement(
            'p',
            null,
            _('Annotations are text and arrows you can use to point out specific parts of your figure.')
          ),
          _react2.default.createElement(
            'p',
            null,
            _('Click on the + button above to add an annotation.')
          )
        )
      );
    }
  }]);

  return AnnotationAccordion;
}(_react.Component);

AnnotationAccordion.contextTypes = {
  layout: _propTypes2.default.object,
  localize: _propTypes2.default.func
};

AnnotationAccordion.propTypes = {
  children: _propTypes2.default.node,
  canAdd: _propTypes2.default.bool
};

exports.default = AnnotationAccordion;
//# sourceMappingURL=AnnotationAccordion.js.map

/***/ }),

/***/ "werx":
/*!***************************************************!*\
  !*** ./node_modules/react-paginate/dist/index.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _PaginationBoxView = __webpack_require__(/*! ./PaginationBoxView */ "kzof");

var _PaginationBoxView2 = _interopRequireDefault(_PaginationBoxView);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = _PaginationBoxView2.default;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ "wgeU":
/*!**********************************************************************!*\
  !*** ./node_modules/core-js/library/modules/es6.object.to-string.js ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "wjpj":
/*!*******************************************************************************!*\
  !*** ./node_modules/react-resizable-rotatable-draggable/lib/ResizableRect.js ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _propTypes = _interopRequireDefault(__webpack_require__(/*! prop-types */ "17x9"));

var _react = _interopRequireWildcard(__webpack_require__(/*! react */ "q1tI"));

var _Rect = _interopRequireDefault(__webpack_require__(/*! ./components/Rect */ "DnSU"));

var _utils = __webpack_require__(/*! ./utils */ "Pkh7");

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } _setPrototypeOf(subClass.prototype, superClass && superClass.prototype); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) { return o.__proto__; }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var centerToTL = function centerToTL(state) {
  var _state$position = state.position,
      centerX = _state$position.centerX,
      centerY = _state$position.centerY,
      _state$size = state.size,
      width = _state$size.width,
      height = _state$size.height,
      rotateAngle = state.transform.rotateAngle;
  var top = centerY - height / 2;
  var left = centerX - width / 2;
  return {
    top: top,
    left: left,
    width: width,
    height: height,
    rotateAngle: rotateAngle
  };
};

var tLToCenter = function tLToCenter(props) {
  var width = props.width,
      height = props.height,
      top = props.top,
      left = props.left,
      rotateAngle = props.rotateAngle;
  return {
    position: {
      centerX: left + width / 2,
      centerY: top + height / 2
    },
    size: {
      width: width,
      height: height
    },
    transform: {
      rotateAngle: rotateAngle
    }
  };
};

var ResizableRect = function (_Component) {
  function ResizableRect() {
    var _getPrototypeOf2;

    var _temp, _this;

    _classCallCheck(this, ResizableRect);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _possibleConstructorReturn(_this, (_temp = _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(ResizableRect)).call.apply(_getPrototypeOf2, [this].concat(args))), _defineProperty(_defineProperty(_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleRotate", function (angle, startAngle) {
      if (!_this.props.onRotate) return;
      var rotateAngle = Math.round(startAngle + angle);

      if (rotateAngle >= 360) {
        rotateAngle -= 360;
      } else if (rotateAngle < 0) {
        rotateAngle += 360;
      }

      if (rotateAngle > 356 || rotateAngle < 4) {
        rotateAngle = 0;
      } else if (rotateAngle > 86 && rotateAngle < 94) {
        rotateAngle = 90;
      } else if (rotateAngle > 176 && rotateAngle < 184) {
        rotateAngle = 180;
      } else if (rotateAngle > 266 && rotateAngle < 274) {
        rotateAngle = 270;
      }

      _this.props.onRotate(rotateAngle);
    }), "handleResize", function (length, alpha, rect, type, isShiftKey) {
      if (!_this.props.onResize) return;
      var _this$props = _this.props,
          rotateAngle = _this$props.rotateAngle,
          aspectRatio = _this$props.aspectRatio,
          minWidth = _this$props.minWidth,
          minHeight = _this$props.minHeight,
          parentRotateAngle = _this$props.parentRotateAngle;
      var beta = alpha - (0, _utils.degToRadian)(rotateAngle + parentRotateAngle);
      var deltaW = length * Math.cos(beta);
      var deltaH = length * Math.sin(beta);
      var ratio = isShiftKey && !aspectRatio ? rect.width / rect.height : aspectRatio;
      var style = (0, _utils.getNewStyle)(type, _objectSpread({}, rect, {
        rotateAngle: rotateAngle
      }), deltaW, deltaH, ratio, minWidth, minHeight);

      _this.props.onResize(centerToTL(_objectSpread({}, style, {
        transform: {
          rotateAngle: rotateAngle
        }
      })), isShiftKey, type);
    }), "handleDrag", function (deltaX, deltaY) {
      _this.props.onDrag && _this.props.onDrag(deltaX, deltaY);
    }), _temp));
  }

  _createClass(ResizableRect, [{
    key: "render",
    value: function render() {
      var styles = tLToCenter(this.props);
      var _this$props2 = this.props,
          zoomable = _this$props2.zoomable,
          rotatable = _this$props2.rotatable,
          parentRotateAngle = _this$props2.parentRotateAngle;
      return _react.default.createElement(_Rect.default, {
        zoomable: zoomable,
        rotatable: rotatable && this.props.onRotate ? true : false,
        styles: styles,
        parentRotateAngle: parentRotateAngle,
        onResizeStart: this.props.onResizeStart,
        onResize: this.handleResize,
        onResizeEnd: this.props.onResizeEnd,
        onRotateStart: this.props.onRotateStart,
        onRotate: this.handleRotate,
        onRotateEnd: this.props.onRotateEnd,
        onDragStart: this.props.onDragStart,
        onDrag: this.handleDrag,
        onDragEnd: this.props.onDragEnd
      });
    }
  }]);

  _inherits(ResizableRect, _Component);

  return ResizableRect;
}(_react.Component);

_defineProperty(_defineProperty(ResizableRect, "propTypes", {
  left: _propTypes.default.number.isRequired,
  top: _propTypes.default.number.isRequired,
  width: _propTypes.default.number.isRequired,
  height: _propTypes.default.number.isRequired,
  rotatable: _propTypes.default.bool,
  rotateAngle: _propTypes.default.number,
  parentRotateAngle: _propTypes.default.number,
  zoomable: _propTypes.default.string,
  minWidth: _propTypes.default.number,
  minHeight: _propTypes.default.number,
  aspectRatio: _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.bool]),
  onRotateStart: _propTypes.default.func,
  onRotate: _propTypes.default.func,
  onRotateEnd: _propTypes.default.func,
  onResizeStart: _propTypes.default.func,
  onResize: _propTypes.default.func,
  onResizeEnd: _propTypes.default.func,
  onDragStart: _propTypes.default.func,
  onDrag: _propTypes.default.func,
  onDragEnd: _propTypes.default.func
}), "defaultProps", {
  parentRotateAngle: 0,
  rotateAngle: 0,
  rotatable: true,
  zoomable: '',
  minWidth: 10,
  minHeight: 10
});

var _default = ResizableRect;
exports.default = _default;

/***/ }),

/***/ "wk3p":
/*!*****************************************************!*\
  !*** ./node_modules/diffie-hellman/lib/primes.json ***!
  \*****************************************************/
/*! exports provided: modp1, modp2, modp5, modp14, modp15, modp16, modp17, modp18, default */
/***/ (function(module) {

module.exports = {"modp1":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},"modp2":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},"modp5":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},"modp14":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},"modp15":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},"modp16":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},"modp17":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},"modp18":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"}};

/***/ }),

/***/ "wkn1":
/*!**************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/apputils/style/iframe.css ***!
  \**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\n.jp-IFrame {\n  width: 100%;\n  height: 100%;\n}\n\n.jp-IFrame > iframe {\n  border: none;\n}\n\n/*\nWhen drag events occur, `p-mod-override-cursor` is added to the body.\nBecause iframes steal all cursor events, the following two rules are necessary\nto suppress pointer events while resize drags are occurring. There may be a\nbetter solution to this problem.\n*/\nbody.p-mod-override-cursor .jp-IFrame {\n  position: relative;\n}\n\nbody.p-mod-override-cursor .jp-IFrame:before {\n  content: '';\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background: transparent;\n}\n", ""]);

// exports


/***/ }),

/***/ "wkyg":
/*!************************************************************!*\
  !*** ./node_modules/react-color/lib/components/hue/Hue.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.HuePicker = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _merge = __webpack_require__(/*! lodash/merge */ "QkVN");

var _merge2 = _interopRequireDefault(_merge);

var _common = __webpack_require__(/*! ../common */ "TM95");

var _HuePointer = __webpack_require__(/*! ./HuePointer */ "trA2");

var _HuePointer2 = _interopRequireDefault(_HuePointer);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var HuePicker = exports.HuePicker = function HuePicker(_ref) {
  var width = _ref.width,
      height = _ref.height,
      onChange = _ref.onChange,
      hsl = _ref.hsl,
      direction = _ref.direction,
      pointer = _ref.pointer,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': {
      picker: {
        position: 'relative',
        width: width,
        height: height
      },
      hue: {
        radius: '2px'
      }
    }
  }, passedStyles));

  // Overwrite to provide pure hue color
  var handleChange = function handleChange(data) {
    return onChange({ a: 1, h: data.h, l: 0.5, s: 1 });
  };

  return _react2.default.createElement(
    'div',
    { style: styles.picker, className: 'hue-picker ' + className },
    _react2.default.createElement(_common.Hue, _extends({}, styles.hue, {
      hsl: hsl,
      pointer: pointer,
      onChange: handleChange,
      direction: direction
    }))
  );
};

HuePicker.propTypes = {
  styles: _propTypes2.default.object
};
HuePicker.defaultProps = {
  width: '316px',
  height: '16px',
  direction: 'horizontal',
  pointer: _HuePointer2.default,
  styles: {}
};

exports.default = (0, _common.ColorWrap)(HuePicker);

/***/ }),

/***/ "wplO":
/*!*********************************************************!*\
  !*** ./node_modules/@jupyterlab/console/lib/foreign.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
/**
 * A handler for capturing API messages from other sessions that should be
 * rendered in a given parent.
 */
class ForeignHandler {
    /**
     * Construct a new foreign message handler.
     */
    constructor(options) {
        this._cells = new Map();
        this._enabled = false;
        this._isDisposed = false;
        this.session = options.session;
        this.session.iopubMessage.connect(this.onIOPubMessage, this);
        this._factory = options.cellFactory;
        this._parent = options.parent;
    }
    /**
     * Set whether the handler is able to inject foreign cells into a console.
     */
    get enabled() {
        return this._enabled;
    }
    set enabled(value) {
        this._enabled = value;
    }
    /**
     * The foreign handler's parent receiver.
     */
    get parent() {
        return this._parent;
    }
    /**
     * Test whether the handler is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose the resources held by the handler.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        this._cells.clear();
        signaling_1.Signal.clearData(this);
    }
    /**
     * Handler IOPub messages.
     *
     * @returns `true` if the message resulted in a new cell injection or a
     * previously injected cell being updated and `false` for all other messages.
     */
    onIOPubMessage(sender, msg) {
        // Only process messages if foreign cell injection is enabled.
        if (!this._enabled) {
            return false;
        }
        let kernel = this.session.kernel;
        if (!kernel) {
            return false;
        }
        // Check whether this message came from an external session.
        let parent = this._parent;
        let session = msg.parent_header.session;
        if (session === kernel.clientId) {
            return false;
        }
        let msgType = msg.header.msg_type;
        let parentHeader = msg.parent_header;
        let parentMsgId = parentHeader.msg_id;
        let cell;
        switch (msgType) {
            case 'execute_input':
                let inputMsg = msg;
                cell = this._newCell(parentMsgId);
                let model = cell.model;
                model.executionCount = inputMsg.content.execution_count;
                model.value.text = inputMsg.content.code;
                model.trusted = true;
                parent.update();
                return true;
            case 'execute_result':
            case 'display_data':
            case 'stream':
            case 'error':
                if (!this._cells.has(parentMsgId)) {
                    // This is an output from an input that was broadcast before our
                    // session started listening. We will ignore it.
                    console.warn('Ignoring output with no associated input cell.');
                    return false;
                }
                let output = msg.content;
                cell = this._cells.get(parentMsgId);
                if (cell) {
                    output.output_type = msgType;
                    cell.model.outputs.add(output);
                }
                parent.update();
                return true;
            case 'clear_output':
                let wait = msg.content.wait;
                cell = this._cells.get(parentMsgId);
                if (cell) {
                    cell.model.outputs.clear(wait);
                }
                return true;
            default:
                return false;
        }
    }
    /**
     * Create a new code cell for an input originated from a foreign session.
     */
    _newCell(parentMsgId) {
        let cell = this._factory();
        this._cells.set(parentMsgId, cell);
        this._parent.addCell(cell);
        return cell;
    }
}
exports.ForeignHandler = ForeignHandler;


/***/ }),

/***/ "wq4j":
/*!*****************************************************!*\
  !*** ./node_modules/readable-stream/passthrough.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(/*! ./readable */ "43KI").PassThrough


/***/ }),

/***/ "wrZu":
/*!************************************************!*\
  !*** ./node_modules/lodash/_initCloneByTag.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var cloneArrayBuffer = __webpack_require__(/*! ./_cloneArrayBuffer */ "+K+b"),
    cloneDataView = __webpack_require__(/*! ./_cloneDataView */ "XYm9"),
    cloneRegExp = __webpack_require__(/*! ./_cloneRegExp */ "b2z7"),
    cloneSymbol = __webpack_require__(/*! ./_cloneSymbol */ "otv/"),
    cloneTypedArray = __webpack_require__(/*! ./_cloneTypedArray */ "yP5f");

/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
    dateTag = '[object Date]',
    mapTag = '[object Map]',
    numberTag = '[object Number]',
    regexpTag = '[object RegExp]',
    setTag = '[object Set]',
    stringTag = '[object String]',
    symbolTag = '[object Symbol]';

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]';

/**
 * 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);
  }
}

module.exports = initCloneByTag;


/***/ }),

/***/ "wwzI":
/*!**************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotScatterChartIcon.js ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotScatterChartIcon = function PlotScatterChartIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M32.375 7.625c-.125 0-.125.125-.25 0v-.313h-.25c0-.375-.25-.625-.25-1.063-.188 0-.313 0-.313-.125l-.25.25c-.125 0 0-.125-.125-.125-.25.438-.375.938-.25 1.375-.125.125-.125.375-.125.5h-.313c0 .125 0 .25-.125.25-.375.188-.813.313-1.188.313-.125 0-.375 0-.563.125-.125.125-.25.375-.375.5s-.25.125-.25.313c.125.125.125.25.125.375-.438.688-1.063.375-1.625.688 0 .125.125.25.125.375-.5.688-1.188 1.063-1.813 1.5-.188 0-.438-.188-.563-.313 0-.25.25-.5.375-.625 0-.438-.125-.813-.375-1.063l-.375.375c-.188 0-.188-.125-.188-.25.438-.125.188-.813.313-.938-.125 0-.125-.125-.125-.125-.438 0-.688-.438-.938 0 0 .125.125 0 .125.125-.125 0-.125 0-.25.125 0 .25.125.375-.188.375 0-.125.188-.25 0-.375-.25.375-.375.938-.375 1.438.375.438.25 1.063-.125 1.5l-.125.125c-.813-.688-.313-2.125-.125-2.938-.188.25-.313.375-.563.563.25-.563.375-.938.563-1.25.25 0 .625-.125.938-.25h.75c-.125 0-.25-.125-.125-.375h-.375v-.313c-.438.188-.938.313-1.375.313 0-.313-.25-.313-.5-.313h-.125c.125-.25.125-.375.375-.5-.25 0-.5.125-.625.375-.313.125-.563.313-.813.438 0-.125-.313 0-.313-.125 0 0 .188-.188.188-.313-.313.125-.438.125-.688.125.25-.25.375-.375.688-.625.25-.125.5-.313.625-.438-.25 0-.5 0-.625-.125-.188.125-.438.125-.563 0l-.125-.125c-.25-.125-.563-.125-.938-.125-.125-.125-.25-.125-.563-.125-.125-.125 0-.563-.25-.563-.125 0 0 .313-.125.313-4.813 0-9.625-.563-14.25-1.875.125.625.125.938.125 1.188-.125 0-.25-.125-.125-.25-.125 0-.125 0-.25.125-.313-.125-.563-.313-.813-.438-.125.438 0 .813.125 1.25h-.125s0 .125.125.125c-.125.125-.25.25 0 .375-.125 0-.125.125-.125.125-.438.813-.688 1.625-1.188 2.25 0 .188 0 .438-.188.563 0 .563-.125 1.063-.375 1.438.375.313 0 .813.125 1.125.125.125.25.375.25.625 0 .125 0 .438.188.438-.188.25 0 .625.25.75 0 .188-.125.188-.125.313 0 .5.5.75.5 1.313v.563c.438.125.813.375 1.188.625v.125c.438.125.688.563.563 1.063.375.188.938.313 1.438.313 0 .125-.125 0-.125.125.563.25 1.063.625 1.625 1.063.813.375 1.563.5 2.5.688 0-.188 0-.313.188-.438.375.125.75.125 1.063.125.25.438.5.688.75.938.313.125.438.438.438.688.25.375.5.688.938.813.125-.313.375-.563.625-.688.688 0 1.375.688 1.375 1.313.25.125.25.563.5.688-.125.938.938 1.188 1.5 1.313-.125-.5-.125-1.063 0-1.438.625-.438 1.313-.813 1.875-1.188.625-.313 1.313-.313 2-.125 0-.313-.313 0-.313-.188.313-.25.438.188.688.188v.125c.125.125.25.125.375.125.188-.125.188-.125.313-.125.125.125-.125.125 0 .125.125-.125.25-.25.25-.438 0 .188.5.438.5.188-.125 0-.25-.188-.5-.313.125 0 .25-.25.125-.375-.125.125-.125.125-.25.125.125-.375.5-.375 1.063-.375 0 0 0-.313.125-.313s.125.313 0 .313c.563-.438 1.313-.313 1.875.25.25 0 .5-.125.688-.438.625 0 .5.563 1.063.563.25.25 0 .938.25 1.188v-.25h.125c0 .125-.125.25-.125.25.125.25.375.563.5.688l.188-.125c.125.125.125.25.125.375.25 0 .5.25.5.563.125-.125.25-.125.563-.125 0 .25-.438.25-.438.5.313-.125.438-.375.563-.688-.125 0 0 .188-.125.188.125-.813-.125-1.625-.563-2.313 0 0 .125 0 .125-.125-.625-.5-1.063-1.563-.75-2.5.125-.188.25-.438.25-.563.25-.125.5-.375.625-.688 0-.375.188-.625.563-.625h.125c0-.813.938-.563.938-1.063-.125.125-.25.125-.375 0 .125.125.25-.125.125-.313.125.188.375 0 .5-.125v-.125h-.25c.125 0 .25 0 .25-.125-.125-.25-.25-.563-.375-.813h-.25c.125-.125-.125-.25-.125-.375h.125a.657.657 0 0 0-.313-.563c.188 0 0-.125.188-.125-.313-.125-.313-.813 0-.938-.188.125.125.25-.188.563.188 0 0 0 .188.25.125.125.25.125.25.25v-.25c.375.125 0 .688.25.938.25-.563.25-.938.25-1.5-.25-.125-.375-.25-.375-.5.125.25.25.375.375.375v.125c.438-.375.563-.75.438-1.313h-.125c.125 0 0-.125.125-.125v-.125c.375-.438.938-.688 1.438-.938 0-.125 0-.125.125-.25 0 .125 0 .125-.125.25.125-.125.25-.25.563-.25 0-.125 0-.313-.313-.313.188.188.188.188.188.313-.313.25-.438-.438-.688-.313 0-.375 0-.75.125-1.188.25 0 .375-.125.563-.25v-.375s.125 0 .125.125-.125 0-.125.125c.25-.125.375-.25.375-.438 0 .188 0 .188.125.188s-.125-.188-.125-.313c.25.125.813-.375.375-.625zM5.313 13.313h2.688v2.688H5.313zm0-4h2.688v2.688H5.313zm-4 0h2.688v2.688H1.313zm0 4h2.688v2.688H1.313zm12 4h2.688v2.688h-2.688zm4-8h2.688v2.688h-2.688zm0 4h2.688v2.688h-2.688zm0 4h2.688v2.688h-2.688zm-4-8h2.688v2.688h-2.688zm0 4h2.688v2.688h-2.688zm8 0h2.688v2.688h-2.688zm0 4h2.688v2.688h-2.688zm4-4h2.688v2.688h-2.688zm-16-4h2.688v2.688H9.313zm0 4h2.688v2.688H9.313zm0 4h2.688v2.688H9.313z' })
    );
};

exports.default = PlotScatterChartIcon;

/***/ }),

/***/ "x1Ex":
/*!********************************************!*\
  !*** ./node_modules/mdi-react/LockIcon.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var LockIcon = function LockIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M12,17C13.1,17 14,16.1 14,15C14,13.89 13.1,13 12,13C10.9,13 10,13.9 10,15C10,16.1 10.9,17 12,17M18,8C19.1,8 20,8.9 20,10V20C20,21.1 19.1,22 18,22H6C4.9,22 4,21.1 4,20V10C4,8.89 4.9,8 6,8H7V6C7,3.24 9.24,1 12,1C14.76,1 17,3.24 17,6V8H18M12,3C10.34,3 9,4.34 9,6V8H15V6C15,4.34 13.66,3 12,3Z' })
  );
};

module.exports = LockIcon;


/***/ }),

/***/ "x5nQ":
/*!******************************************************!*\
  !*** ./node_modules/mdi-react/InboxArrowDownIcon.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var InboxArrowDownIcon = function InboxArrowDownIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M16,10H14V7H10V10H8L12,14M19,15H15C15,16.66 13.66,18 12,18C10.34,18 9,16.66 9,15H5V5H19M19,3H5C3.89,3 3,3.9 3,5V19C3,20.1 3.9,21 5,21H19C20.1,21 21,20.1 21,19V5C21,3.9 20.1,3 19,3Z' })
  );
};

module.exports = InboxArrowDownIcon;


/***/ }),

/***/ "x6pH":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/he.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var he = moment.defineLocale('he', {
    months : 'ינואר_פברואר_מרץ_אפריל_מאי_יוני_יולי_אוגוסט_ספטמבר_אוקטובר_נובמבר_דצמבר'.split('_'),
    monthsShort : 'ינו׳_פבר׳_מרץ_אפר׳_מאי_יוני_יולי_אוג׳_ספט׳_אוק׳_נוב׳_דצמ׳'.split('_'),
    weekdays : 'ראשון_שני_שלישי_רביעי_חמישי_שישי_שבת'.split('_'),
    weekdaysShort : 'א׳_ב׳_ג׳_ד׳_ה׳_ו׳_ש׳'.split('_'),
    weekdaysMin : 'א_ב_ג_ד_ה_ו_ש'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D [ב]MMMM YYYY',
        LLL : 'D [ב]MMMM YYYY HH:mm',
        LLLL : 'dddd, D [ב]MMMM YYYY HH:mm',
        l : 'D/M/YYYY',
        ll : 'D MMM YYYY',
        lll : 'D MMM YYYY HH:mm',
        llll : 'ddd, D MMM YYYY HH:mm'
    },
    calendar : {
        sameDay : '[היום ב־]LT',
        nextDay : '[מחר ב־]LT',
        nextWeek : 'dddd [בשעה] LT',
        lastDay : '[אתמול ב־]LT',
        lastWeek : '[ביום] dddd [האחרון בשעה] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'בעוד %s',
        past : 'לפני %s',
        s : 'מספר שניות',
        ss : '%d שניות',
        m : 'דקה',
        mm : '%d דקות',
        h : 'שעה',
        hh : function (number) {
            if (number === 2) {
                return 'שעתיים';
            }
            return number + ' שעות';
        },
        d : 'יום',
        dd : function (number) {
            if (number === 2) {
                return 'יומיים';
            }
            return number + ' ימים';
        },
        M : 'חודש',
        MM : function (number) {
            if (number === 2) {
                return 'חודשיים';
            }
            return number + ' חודשים';
        },
        y : 'שנה',
        yy : function (number) {
            if (number === 2) {
                return 'שנתיים';
            } else if (number % 10 === 0 && number !== 10) {
                return number + ' שנה';
            }
            return number + ' שנים';
        }
    },
    meridiemParse: /אחה"צ|לפנה"צ|אחרי הצהריים|לפני הצהריים|לפנות בוקר|בבוקר|בערב/i,
    isPM : function (input) {
        return /^(אחה"צ|אחרי הצהריים|בערב)$/.test(input);
    },
    meridiem : function (hour, minute, isLower) {
        if (hour < 5) {
            return 'לפנות בוקר';
        } else if (hour < 10) {
            return 'בבוקר';
        } else if (hour < 12) {
            return isLower ? 'לפנה"צ' : 'לפני הצהריים';
        } else if (hour < 18) {
            return isLower ? 'אחה"צ' : 'אחרי הצהריים';
        } else {
            return 'בערב';
        }
    }
});

return he;

})));


/***/ }),

/***/ "x9uK":
/*!******************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/DualNumeric.js ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UnconnectedDualNumericFraction = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _NumericInput = __webpack_require__(/*! ../widgets/NumericInput */ "2NAh");

var _NumericInput2 = _interopRequireDefault(_NumericInput);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _nested_property = __webpack_require__(/*! plotly.js/src/lib/nested_property */ "dNZO");

var _nested_property2 = _interopRequireDefault(_nested_property);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UnconnectedDualNumericFraction = exports.UnconnectedDualNumericFraction = function (_Component) {
  _inherits(UnconnectedDualNumericFraction, _Component);

  function UnconnectedDualNumericFraction(props, context) {
    _classCallCheck(this, UnconnectedDualNumericFraction);

    var _this = _possibleConstructorReturn(this, (UnconnectedDualNumericFraction.__proto__ || Object.getPrototypeOf(UnconnectedDualNumericFraction)).call(this, props, context));

    _this.updatePlot = _this.updatePlot.bind(_this);
    _this.updatePlot2 = _this.updatePlot2.bind(_this);
    return _this;
  }

  _createClass(UnconnectedDualNumericFraction, [{
    key: 'updatePlot',
    value: function updatePlot(value) {
      this.props.updatePlot(this.props.percentage ? value / 100 : value);
    }
  }, {
    key: 'updatePlot2',
    value: function updatePlot2(value) {
      this.props.updateContainer(_defineProperty({}, this.props.attr2, this.props.percentage ? value / 100 : value));
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          percentage = _props.percentage,
          multiValued = _props.multiValued,
          attr2 = _props.attr2,
          step = _props.step,
          min = _props.min,
          max = _props.max;

      var fullValue = percentage ? Math.round(100 * this.props.fullValue) : this.props.fullValue;
      var fullValue2 = (0, _nested_property2.default)(this.context.fullContainer, attr2).get();
      if (percentage) {
        fullValue2 = Math.round(100 * fullValue2);
      }
      var placeholder = void 0;
      var placeholder2 = void 0;
      if (multiValued) {
        placeholder = fullValue;
        placeholder2 = fullValue2;
        fullValue = '';
        fullValue2 = '';
      }

      return _react2.default.createElement(
        _Field2.default,
        this.props,
        _react2.default.createElement(
          'div',
          { className: 'numeric-input__wrapper' },
          _react2.default.createElement(_NumericInput2.default, {
            value: fullValue,
            defaultValue: this.props.defaultValue,
            placeholder: placeholder,
            step: step,
            min: min,
            max: max,
            onChange: this.updatePlot,
            onUpdate: this.updatePlot,
            showArrows: !this.props.hideArrows,
            showSlider: false
          }),
          _react2.default.createElement(_NumericInput2.default, {
            value: fullValue2,
            defaultValue: this.props.defaultValue,
            placeholder: placeholder2,
            step: step,
            min: min,
            max: max,
            onChange: this.updatePlot2,
            onUpdate: this.updatePlot2,
            showArrows: !this.props.hideArrows,
            showSlider: false
          })
        )
      );
    }
  }]);

  return UnconnectedDualNumericFraction;
}(_react.Component);

UnconnectedDualNumericFraction.propTypes = _extends({
  defaultValue: _propTypes2.default.any,
  fullValue: _propTypes2.default.any,
  min: _propTypes2.default.number,
  max: _propTypes2.default.number,
  multiValued: _propTypes2.default.bool,
  hideArrows: _propTypes2.default.bool,
  showSlider: _propTypes2.default.bool,
  step: _propTypes2.default.number,
  updatePlot: _propTypes2.default.func,
  attr2: _propTypes2.default.any,
  percentage: _propTypes2.default.bool
}, _Field2.default.propTypes);

UnconnectedDualNumericFraction.contextTypes = {
  fullContainer: _propTypes2.default.object
};

exports.default = (0, _lib.connectToContainer)(UnconnectedDualNumericFraction);
//# sourceMappingURL=DualNumeric.js.map

/***/ }),

/***/ "xDYf":
/*!**********************************************!*\
  !*** ./node_modules/mdi-react/DomainIcon.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var DomainIcon = function DomainIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M18,15H16V17H18M18,11H16V13H18M20,19H12V17H14V15H12V13H14V11H12V9H20M10,7H8V5H10M10,11H8V9H10M10,15H8V13H10M10,19H8V17H10M6,7H4V5H6M6,11H4V9H6M6,15H4V13H6M6,19H4V17H6M12,7V3H2V21H22V7H12Z' })
  );
};

module.exports = DomainIcon;


/***/ }),

/***/ "xLLm":
/*!*******************************************************!*\
  !*** ./node_modules/fbjs/lib/ExecutionEnvironment.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */



var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);

/**
 * Simple, lightweight module assisting with the detection and context of
 * Worker. Helps avoid circular dependencies and allows code to reason about
 * whether or not they are in a Worker, even if they never include the main
 * `ReactWorker` dependency.
 */
var ExecutionEnvironment = {

  canUseDOM: canUseDOM,

  canUseWorkers: typeof Worker !== 'undefined',

  canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent),

  canUseViewport: canUseDOM && !!window.screen,

  isInWorker: !canUseDOM // For now, this is true - might change in the future.

};

module.exports = ExecutionEnvironment;

/***/ }),

/***/ "xSJi":
/*!******************************************************!*\
  !*** ./node_modules/react-day-picker/lib/src/Day.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _DateUtils = __webpack_require__(/*! ./DateUtils */ "mHnu");

var _Helpers = __webpack_require__(/*! ./Helpers */ "VJCR");

var _classNames = __webpack_require__(/*! ./classNames */ "ZE44");

var _classNames2 = _interopRequireDefault(_classNames);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint-disable jsx-a11y/no-static-element-interactions, react/forbid-prop-types */

function handleEvent(handler, day, modifiers) {
  if (!handler) {
    return undefined;
  }
  return function (e) {
    e.persist();
    handler(day, modifiers, e);
  };
}

var Day = function (_Component) {
  _inherits(Day, _Component);

  function Day() {
    _classCallCheck(this, Day);

    return _possibleConstructorReturn(this, (Day.__proto__ || Object.getPrototypeOf(Day)).apply(this, arguments));
  }

  _createClass(Day, [{
    key: 'shouldComponentUpdate',
    value: function shouldComponentUpdate(nextProps) {
      var _this2 = this;

      var propNames = Object.keys(this.props);
      var nextPropNames = Object.keys(nextProps);
      if (propNames.length !== nextPropNames.length) {
        return true;
      }
      return propNames.some(function (name) {
        if (name === 'modifiers' || name === 'modifiersStyles' || name === 'classNames') {
          var prop = _this2.props[name];
          var nextProp = nextProps[name];
          var modifiers = Object.keys(prop);
          var nextModifiers = Object.keys(nextProp);
          if (modifiers.length !== nextModifiers.length) {
            return true;
          }
          return modifiers.some(function (mod) {
            return !(0, _Helpers.hasOwnProp)(nextProp, mod) || prop[mod] !== nextProp[mod];
          });
        }
        if (name === 'day') {
          return !(0, _DateUtils.isSameDay)(_this2.props[name], nextProps[name]);
        }
        return !(0, _Helpers.hasOwnProp)(nextProps, name) || _this2.props[name] !== nextProps[name];
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          classNames = _props.classNames,
          modifiersStyles = _props.modifiersStyles,
          day = _props.day,
          tabIndex = _props.tabIndex,
          empty = _props.empty,
          modifiers = _props.modifiers,
          onMouseEnter = _props.onMouseEnter,
          onMouseLeave = _props.onMouseLeave,
          onMouseUp = _props.onMouseUp,
          onMouseDown = _props.onMouseDown,
          onClick = _props.onClick,
          onKeyDown = _props.onKeyDown,
          onTouchStart = _props.onTouchStart,
          onTouchEnd = _props.onTouchEnd,
          onFocus = _props.onFocus,
          ariaLabel = _props.ariaLabel,
          ariaDisabled = _props.ariaDisabled,
          ariaSelected = _props.ariaSelected,
          children = _props.children;


      var className = classNames.day;
      if (classNames !== _classNames2.default) {
        // When using CSS modules prefix the modifier as required by the BEM syntax
        className += ' ' + Object.keys(modifiers).join(' ');
      } else {
        className += Object.keys(modifiers).map(function (modifier) {
          return ' ' + className + '--' + modifier;
        }).join('');
      }

      var style = void 0;
      if (modifiersStyles) {
        Object.keys(modifiers).filter(function (modifier) {
          return !!modifiersStyles[modifier];
        }).forEach(function (modifier) {
          style = _extends({}, style, modifiersStyles[modifier]);
        });
      }

      if (empty) {
        return _react2.default.createElement('div', { 'aria-disabled': true, className: className, style: style });
      }
      return _react2.default.createElement(
        'div',
        {
          className: className,
          tabIndex: tabIndex,
          style: style,
          role: 'gridcell',
          'aria-label': ariaLabel,
          'aria-disabled': ariaDisabled,
          'aria-selected': ariaSelected,
          onClick: handleEvent(onClick, day, modifiers),
          onKeyDown: handleEvent(onKeyDown, day, modifiers),
          onMouseEnter: handleEvent(onMouseEnter, day, modifiers),
          onMouseLeave: handleEvent(onMouseLeave, day, modifiers),
          onMouseUp: handleEvent(onMouseUp, day, modifiers),
          onMouseDown: handleEvent(onMouseDown, day, modifiers),
          onTouchEnd: handleEvent(onTouchEnd, day, modifiers),
          onTouchStart: handleEvent(onTouchStart, day, modifiers),
          onFocus: handleEvent(onFocus, day, modifiers)
        },
        children
      );
    }
  }]);

  return Day;
}(_react.Component);

Day.defaultProps = {
  tabIndex: -1
};
Day.defaultProps = {
  modifiers: {},
  modifiersStyles: {},
  empty: false
};
exports.default = Day;
Day.propTypes =  true ? {
  classNames: _propTypes2.default.shape({
    day: _propTypes2.default.string.isRequired
  }).isRequired,

  day: _propTypes2.default.instanceOf(Date).isRequired,
  children: _propTypes2.default.node.isRequired,

  ariaDisabled: _propTypes2.default.bool,
  ariaLabel: _propTypes2.default.string,
  ariaSelected: _propTypes2.default.bool,
  empty: _propTypes2.default.bool,
  modifiers: _propTypes2.default.object,
  modifiersStyles: _propTypes2.default.object,
  onClick: _propTypes2.default.func,
  onKeyDown: _propTypes2.default.func,
  onMouseEnter: _propTypes2.default.func,
  onMouseLeave: _propTypes2.default.func,
  onMouseDown: _propTypes2.default.func,
  onMouseUp: _propTypes2.default.func,
  onTouchEnd: _propTypes2.default.func,
  onTouchStart: _propTypes2.default.func,
  onFocus: _propTypes2.default.func,
  tabIndex: _propTypes2.default.number
} : undefined;
//# sourceMappingURL=Day.js.map

/***/ }),

/***/ "xVS5":
/*!**************************************************!*\
  !*** ./node_modules/xterm/lib/addons/fit/fit.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function proposeGeometry(term) {
    if (!term.element.parentElement) {
        return null;
    }
    var parentElementStyle = window.getComputedStyle(term.element.parentElement);
    var parentElementHeight = parseInt(parentElementStyle.getPropertyValue('height'));
    var parentElementWidth = Math.max(0, parseInt(parentElementStyle.getPropertyValue('width')));
    var elementStyle = window.getComputedStyle(term.element);
    var elementPadding = {
        top: parseInt(elementStyle.getPropertyValue('padding-top')),
        bottom: parseInt(elementStyle.getPropertyValue('padding-bottom')),
        right: parseInt(elementStyle.getPropertyValue('padding-right')),
        left: parseInt(elementStyle.getPropertyValue('padding-left'))
    };
    var elementPaddingVer = elementPadding.top + elementPadding.bottom;
    var elementPaddingHor = elementPadding.right + elementPadding.left;
    var availableHeight = parentElementHeight - elementPaddingVer;
    var availableWidth = parentElementWidth - elementPaddingHor - term.viewport.scrollBarWidth;
    var geometry = {
        cols: Math.floor(availableWidth / term.renderer.dimensions.actualCellWidth),
        rows: Math.floor(availableHeight / term.renderer.dimensions.actualCellHeight)
    };
    return geometry;
}
exports.proposeGeometry = proposeGeometry;
function fit(term) {
    var geometry = proposeGeometry(term);
    if (geometry) {
        if (term.rows !== geometry.rows || term.cols !== geometry.cols) {
            term.renderer.clear();
            term.resize(geometry.cols, geometry.rows);
        }
    }
}
exports.fit = fit;
function apply(terminalConstructor) {
    terminalConstructor.prototype.proposeGeometry = function () {
        return proposeGeometry(this);
    };
    terminalConstructor.prototype.fit = function () {
        fit(this);
    };
}
exports.apply = apply;

//# sourceMappingURL=fit.js.map


/***/ }),

/***/ "xYL2":
/*!*****************************************************************!*\
  !*** ./node_modules/font-awesome/fonts/fontawesome-webfont.eot ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__.p + "674f50d287a8c48dc19ba404d20fe713.eot";

/***/ }),

/***/ "xYSL":
/*!******************************************!*\
  !*** ./node_modules/lodash/_cacheHas.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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);
}

module.exports = cacheHas;


/***/ }),

/***/ "xbjo":
/*!************************************************************************!*\
  !*** ./node_modules/react-color/lib/components/circle/CircleSwatch.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CircleSwatch = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _common = __webpack_require__(/*! ../common */ "TM95");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var CircleSwatch = exports.CircleSwatch = function CircleSwatch(_ref) {
  var color = _ref.color,
      onClick = _ref.onClick,
      onSwatchHover = _ref.onSwatchHover,
      hover = _ref.hover,
      active = _ref.active,
      circleSize = _ref.circleSize,
      circleSpacing = _ref.circleSpacing;

  var styles = (0, _reactcss2.default)({
    'default': {
      swatch: {
        width: circleSize,
        height: circleSize,
        marginRight: circleSpacing,
        marginBottom: circleSpacing,
        transform: 'scale(1)',
        transition: '100ms transform ease'
      },
      Swatch: {
        borderRadius: '50%',
        background: 'transparent',
        boxShadow: 'inset 0 0 0 ' + circleSize / 2 + 'px ' + color,
        transition: '100ms box-shadow ease'
      }
    },
    'hover': {
      swatch: {
        transform: 'scale(1.2)'
      }
    },
    'active': {
      Swatch: {
        boxShadow: 'inset 0 0 0 3px ' + color
      }
    }
  }, { hover: hover, active: active });

  return _react2.default.createElement(
    'div',
    { style: styles.swatch },
    _react2.default.createElement(_common.Swatch, {
      style: styles.Swatch,
      color: color,
      onClick: onClick,
      onHover: onSwatchHover,
      focusStyle: { boxShadow: styles.Swatch.boxShadow + ', 0 0 5px ' + color }
    })
  );
};

CircleSwatch.defaultProps = {
  circleSize: 28,
  circleSpacing: 14
};

exports.default = (0, _reactcss.handleHover)(CircleSwatch);

/***/ }),

/***/ "xhLm":
/*!************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/lib/connectAxesToLayout.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

exports.default = connectAxesToLayout;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _nested_property = __webpack_require__(/*! plotly.js/src/lib/nested_property */ "dNZO");

var _nested_property2 = _interopRequireDefault(_nested_property);

var _multiValues = __webpack_require__(/*! ./multiValues */ "l26e");

var _lib = __webpack_require__(/*! ../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function computeAxesOptions(axes, props, context) {
  var _ = context.localize;
  var filteredAxes = axes;
  if (props.axisFilter) {
    filteredAxes = axes.filter(props.axisFilter);
  }

  var options = [];
  for (var i = 0; i < filteredAxes.length; i++) {
    var ax = filteredAxes[i];
    var label = (0, _lib.capitalize)(ax._name.split('axis')[0]);
    var value = (ax._subplot && !ax._subplot.includes('xaxis') && !ax._subplot.includes('yaxis') ? ax._subplot + '.' + ax._name : ax._subplot).trim();

    options[i] = {
      label: label,
      value: value,
      axisGroup: ax._axisGroup,
      title: (0, _lib.getAxisTitle)(ax)
    };
  }

  return options.length > 1 ? [{ label: _('All'), value: 'allaxes' }].concat(options) : options;
}

function connectAxesToLayout(WrappedComponent) {
  var AxesConnectedComponent = function (_Component) {
    _inherits(AxesConnectedComponent, _Component);

    function AxesConnectedComponent(props, context) {
      _classCallCheck(this, AxesConnectedComponent);

      var _this = _possibleConstructorReturn(this, (AxesConnectedComponent.__proto__ || Object.getPrototypeOf(AxesConnectedComponent)).call(this, props, context));

      _this.axes = (0, _lib.getAllAxes)(context.fullContainer);
      _this.axesOptions = computeAxesOptions(_this.axes, props, context);

      // this.axesOptions can be an empty array when we have a filter on an AxesFold
      // and no axes correspond to the condition
      var defaultAxesTarget = null;
      if (_this.axesOptions.length === 1) {
        defaultAxesTarget = _this.axesOptions[0].value;
      }
      if (_this.axesOptions.length > 1) {
        defaultAxesTarget = _this.axesOptions[1].value;
      }

      _this.state = {
        axesTarget: defaultAxesTarget
      };

      _this.axesTargetHandler = _this.axesTargetHandler.bind(_this);
      _this.updateContainer = _this.updateContainer.bind(_this);

      _this.setLocals(props, _this.state, context);
      return _this;
    }

    _createClass(AxesConnectedComponent, [{
      key: 'componentWillUpdate',
      value: function componentWillUpdate(nextProps, nextState, nextContext) {
        this.axes = (0, _lib.getAllAxes)(nextContext.fullContainer);
        this.axesOptions = computeAxesOptions(this.axes, nextProps, nextContext);
        // This is not enough, what if plotly.js adds new axes...
        this.setLocals(nextProps, nextState, nextContext);
      }
    }, {
      key: 'setLocals',
      value: function setLocals(nextProps, nextState, nextContext) {
        var container = nextContext.container,
            fullContainer = nextContext.fullContainer;
        var axesTarget = nextState.axesTarget;


        if (axesTarget === 'allaxes') {
          var multiValuedContainer = (0, _multiValues.deepCopyPublic)(this.axes[0]);
          this.axes.slice(1).forEach(function (ax) {
            return Object.keys(ax).forEach(function (key) {
              return (0, _multiValues.setMultiValuedContainer)(multiValuedContainer, (0, _multiValues.deepCopyPublic)(ax), key, {
                searchArrays: true
              });
            });
          });
          this.fullContainer = multiValuedContainer;
          this.defaultContainer = this.axes[0];
          this.container = {};
        } else if (axesTarget) {
          this.fullContainer = (0, _nested_property2.default)(fullContainer, axesTarget).get();
          this.container = this.container = (0, _nested_property2.default)(container, axesTarget).get() || {};
        }
      }
    }, {
      key: 'getChildContext',
      value: function getChildContext() {
        var _this2 = this;

        return {
          getValObject: function getValObject(attr) {
            return !_this2.context.getValObject ? null : _this2.context.getValObject(_this2.state.axesTarget + '.' + attr);
          },
          axesOptions: this.axesOptions,
          axesTarget: this.state.axesTarget,
          axesTargetHandler: this.axesTargetHandler,
          container: this.container,
          defaultContainer: this.defaultContainer,
          fullContainer: this.fullContainer,
          updateContainer: this.updateContainer
        };
      }
    }, {
      key: 'axesTargetHandler',
      value: function axesTargetHandler(axesTarget) {
        this.setState({ axesTarget: axesTarget });
      }
    }, {
      key: 'updateContainer',
      value: function updateContainer(update) {
        var newUpdate = {};
        var axesTarget = this.state.axesTarget;


        var axes = this.axes;
        if (axesTarget !== 'allaxes') {
          // only the selected container
          axes = [this.fullContainer];
        }

        var keys = Object.keys(update);
        for (var i = 0; i < keys.length; i++) {
          for (var j = 0; j < axes.length; j++) {
            var subplot = axes[j]._subplot;
            var axesKey = axes[j]._name;

            if (subplot && !subplot.includes('xaxis') && !subplot.includes('yaxis')) {
              axesKey = subplot + '.' + axesKey;
            }

            var newkey = axesKey + '.' + keys[i];
            newUpdate[newkey] = update[keys[i]];
          }
        }

        this.context.updateContainer(newUpdate);
      }
    }, {
      key: 'render',
      value: function render() {
        return _react2.default.createElement(WrappedComponent, _extends({}, this.props, { options: this.axesOptions }));
      }
    }]);

    return AxesConnectedComponent;
  }(_react.Component);

  AxesConnectedComponent.displayName = 'AxesConnected' + (0, _lib.getDisplayName)(WrappedComponent);

  AxesConnectedComponent.contextTypes = {
    container: _propTypes2.default.object.isRequired,
    fullContainer: _propTypes2.default.object.isRequired,
    updateContainer: _propTypes2.default.func,
    localize: _propTypes2.default.func,
    getValObject: _propTypes2.default.func
  };

  AxesConnectedComponent.childContextTypes = {
    axesOptions: _propTypes2.default.array,
    axesTarget: _propTypes2.default.string,
    axesTargetHandler: _propTypes2.default.func,
    container: _propTypes2.default.object,
    defaultContainer: _propTypes2.default.object,
    fullContainer: _propTypes2.default.object,
    updateContainer: _propTypes2.default.func,
    getValObject: _propTypes2.default.func
  };

  var plotly_editor_traits = WrappedComponent.plotly_editor_traits;

  AxesConnectedComponent.plotly_editor_traits = plotly_editor_traits;

  return AxesConnectedComponent;
}
//# sourceMappingURL=connectAxesToLayout.js.map

/***/ }),

/***/ "xkGU":
/*!*************************************!*\
  !*** ./node_modules/lodash/each.js ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(/*! ./forEach */ "bNQv");


/***/ }),

/***/ "xkL0":
/*!*********************************************!*\
  !*** ./node_modules/mdi-react/CheckIcon.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(__webpack_require__(/*! react */ "q1tI"));

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var CheckIcon = function CheckIcon(_ref) {
  var _ref$color = _ref.color,
      color = _ref$color === undefined ? 'currentColor' : _ref$color,
      _ref$size = _ref.size,
      size = _ref$size === undefined ? 24 : _ref$size,
      children = _ref.children,
      props = objectWithoutProperties(_ref, ['color', 'size', 'children']);

  var className = 'mdi-icon ' + (props.className || '');

  return React.createElement(
    'svg',
    _extends({}, props, { className: className, width: size, height: size, fill: color, viewBox: '0 0 24 24' }),
    React.createElement('path', { d: 'M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z' })
  );
};

module.exports = CheckIcon;


/***/ }),

/***/ "xocI":
/*!**********************************************************!*\
  !*** ./node_modules/draft-js/lib/getSafeBodyFromHTML.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule getSafeBodyFromHTML
 * @format
 * 
 */



var UserAgent = __webpack_require__(/*! fbjs/lib/UserAgent */ "CYTE");

var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "2NuI");

var isOldIE = UserAgent.isBrowser('IE <= 9');

// Provides a dom node that will not execute scripts
// https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation.createHTMLDocument
// https://developer.mozilla.org/en-US/Add-ons/Code_snippets/HTML_to_DOM

function getSafeBodyFromHTML(html) {
  var doc;
  var root = null;
  // Provides a safe context
  if (!isOldIE && document.implementation && document.implementation.createHTMLDocument) {
    doc = document.implementation.createHTMLDocument('foo');
    !doc.documentElement ?  true ? invariant(false, 'Missing doc.documentElement') : undefined : void 0;
    doc.documentElement.innerHTML = html;
    root = doc.getElementsByTagName('body')[0];
  }
  return root;
}

module.exports = getSafeBodyFromHTML;

/***/ }),

/***/ "xotT":
/*!*************************************************************!*\
  !*** ./node_modules/@jupyterlab/docregistry/lib/context.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const services_1 = __webpack_require__(/*! @jupyterlab/services */ "S9up");
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const disposable_1 = __webpack_require__(/*! @phosphor/disposable */ "uNUc");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const coreutils_2 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const rendermime_1 = __webpack_require__(/*! @jupyterlab/rendermime */ "Towz");
/**
 * An implementation of a document context.
 *
 * This class is typically instantiated by the document manager.
 */
class Context {
    /**
     * Construct a new document context.
     */
    constructor(options) {
        this._path = '';
        this._contentsModel = null;
        this._populatedPromise = new coreutils_1.PromiseDelegate();
        this._isPopulated = false;
        this._isReady = false;
        this._isDisposed = false;
        this._pathChanged = new signaling_1.Signal(this);
        this._fileChanged = new signaling_1.Signal(this);
        this._saveState = new signaling_1.Signal(this);
        this._disposed = new signaling_1.Signal(this);
        let manager = (this._manager = options.manager);
        this._factory = options.factory;
        this._opener = options.opener || Private.noOp;
        this._path = options.path;
        const localPath = this._manager.contents.localPath(this._path);
        let lang = this._factory.preferredLanguage(coreutils_2.PathExt.basename(localPath));
        let dbFactory = options.modelDBFactory;
        if (dbFactory) {
            const localPath = manager.contents.localPath(this._path);
            this._modelDB = dbFactory.createNew(localPath);
            this._model = this._factory.createNew(lang, this._modelDB);
        }
        else {
            this._model = this._factory.createNew(lang);
        }
        this._readyPromise = manager.ready.then(() => {
            return this._populatedPromise.promise;
        });
        let ext = coreutils_2.PathExt.extname(this._path);
        this.session = new apputils_1.ClientSession({
            manager: manager.sessions,
            path: this._path,
            type: ext === '.ipynb' ? 'notebook' : 'file',
            name: coreutils_2.PathExt.basename(localPath),
            kernelPreference: options.kernelPreference || { shouldStart: false },
            setBusy: options.setBusy
        });
        this.session.propertyChanged.connect(this._onSessionChanged, this);
        manager.contents.fileChanged.connect(this._onFileChanged, this);
        this.urlResolver = new rendermime_1.RenderMimeRegistry.UrlResolver({
            session: this.session,
            contents: manager.contents
        });
    }
    /**
     * A signal emitted when the path changes.
     */
    get pathChanged() {
        return this._pathChanged;
    }
    /**
     * A signal emitted when the model is saved or reverted.
     */
    get fileChanged() {
        return this._fileChanged;
    }
    /**
     * A signal emitted on the start and end of a saving operation.
     */
    get saveState() {
        return this._saveState;
    }
    /**
     * A signal emitted when the context is disposed.
     */
    get disposed() {
        return this._disposed;
    }
    /**
     * Get the model associated with the document.
     */
    get model() {
        return this._model;
    }
    /**
     * The current path associated with the document.
     */
    get path() {
        return this._path;
    }
    /**
     * The current local path associated with the document.
     * If the document is in the default notebook file browser,
     * this is the same as the path.
     */
    get localPath() {
        return this._manager.contents.localPath(this._path);
    }
    /**
     * The current contents model associated with the document.
     *
     * #### Notes
     * The contents model will be null until the context is populated.
     * It will have an  empty `contents` field.
     */
    get contentsModel() {
        return this._contentsModel;
    }
    /**
     * Get the model factory name.
     *
     * #### Notes
     * This is not part of the `IContext` API.
     */
    get factoryName() {
        return this.isDisposed ? '' : this._factory.name;
    }
    /**
     * Test whether the context is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources held by the context.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        this.session.dispose();
        if (this._modelDB) {
            this._modelDB.dispose();
        }
        this._model.dispose();
        this._disposed.emit(void 0);
        signaling_1.Signal.clearData(this);
    }
    /**
     * Whether the context is ready.
     */
    get isReady() {
        return this._isReady;
    }
    /**
     * A promise that is fulfilled when the context is ready.
     */
    get ready() {
        return this._readyPromise;
    }
    /**
     * Initialize the context.
     *
     * @param isNew - Whether it is a new file.
     *
     * @returns a promise that resolves upon initialization.
     */
    initialize(isNew) {
        if (isNew) {
            this._model.initialize();
            return this._save();
        }
        if (this._modelDB) {
            return this._modelDB.connected.then(() => {
                if (this._modelDB.isPrepopulated) {
                    this._model.initialize();
                    this._save();
                    return void 0;
                }
                else {
                    return this._revert(true);
                }
            });
        }
        else {
            return this._revert(true);
        }
    }
    /**
     * Save the document contents to disk.
     */
    save() {
        return this.ready.then(() => {
            return this._save();
        });
    }
    /**
     * Save the document to a different path chosen by the user.
     */
    saveAs() {
        return this.ready
            .then(() => {
            return Private.getSavePath(this._path);
        })
            .then(newPath => {
            if (this.isDisposed || !newPath) {
                return;
            }
            if (newPath === this._path) {
                return this.save();
            }
            // Make sure the path does not exist.
            return this._manager.ready
                .then(() => {
                return this._manager.contents.get(newPath);
            })
                .then(() => {
                return this._maybeOverWrite(newPath);
            })
                .catch(err => {
                if (!err.response || err.response.status !== 404) {
                    throw err;
                }
                return this._finishSaveAs(newPath);
            });
        });
    }
    /**
     * Revert the document contents to disk contents.
     */
    revert() {
        return this.ready.then(() => {
            return this._revert();
        });
    }
    /**
     * Create a checkpoint for the file.
     */
    createCheckpoint() {
        let contents = this._manager.contents;
        return this._manager.ready.then(() => {
            return contents.createCheckpoint(this._path);
        });
    }
    /**
     * Delete a checkpoint for the file.
     */
    deleteCheckpoint(checkpointId) {
        let contents = this._manager.contents;
        return this._manager.ready.then(() => {
            return contents.deleteCheckpoint(this._path, checkpointId);
        });
    }
    /**
     * Restore the file to a known checkpoint state.
     */
    restoreCheckpoint(checkpointId) {
        let contents = this._manager.contents;
        let path = this._path;
        return this._manager.ready.then(() => {
            if (checkpointId) {
                return contents.restoreCheckpoint(path, checkpointId);
            }
            return this.listCheckpoints().then(checkpoints => {
                if (this.isDisposed || !checkpoints.length) {
                    return;
                }
                checkpointId = checkpoints[checkpoints.length - 1].id;
                return contents.restoreCheckpoint(path, checkpointId);
            });
        });
    }
    /**
     * List available checkpoints for a file.
     */
    listCheckpoints() {
        let contents = this._manager.contents;
        return this._manager.ready.then(() => {
            return contents.listCheckpoints(this._path);
        });
    }
    /**
     * Add a sibling widget to the document manager.
     *
     * @param widget - The widget to add to the document manager.
     *
     * @param options - The desired options for adding the sibling.
     *
     * @returns A disposable used to remove the sibling if desired.
     *
     * #### Notes
     * It is assumed that the widget has the same model and context
     * as the original widget.
     */
    addSibling(widget, options = {}) {
        let opener = this._opener;
        if (opener) {
            opener(widget, options);
        }
        return new disposable_1.DisposableDelegate(() => {
            widget.close();
        });
    }
    /**
     * Handle a change on the contents manager.
     */
    _onFileChanged(sender, change) {
        if (change.type !== 'rename') {
            return;
        }
        let oldPath = change.oldValue && change.oldValue.path;
        let newPath = change.newValue && change.newValue.path;
        if (newPath && this._path.indexOf(oldPath) === 0) {
            let changeModel = change.newValue;
            // When folder name changed, `oldPath` is `foo`, `newPath` is `bar` and `this._path` is `foo/test`,
            // we should update `foo/test` to `bar/test` as well
            if (oldPath !== this._path) {
                newPath = this._path.replace(new RegExp(`^${oldPath}`), newPath);
                oldPath = this._path;
                // Update client file model from folder change
                changeModel = {
                    last_modified: change.newValue.created,
                    path: newPath
                };
            }
            this._path = newPath;
            this.session.setPath(newPath);
            const updateModel = Object.assign({}, this._contentsModel, changeModel);
            const localPath = this._manager.contents.localPath(newPath);
            this.session.setName(coreutils_2.PathExt.basename(localPath));
            this._updateContentsModel(updateModel);
            this._pathChanged.emit(this._path);
        }
    }
    /**
     * Handle a change to a session property.
     */
    _onSessionChanged(sender, type) {
        if (type !== 'path') {
            return;
        }
        let path = this.session.path;
        if (path !== this._path) {
            this._path = path;
            this._pathChanged.emit(path);
        }
    }
    /**
     * Update our contents model, without the content.
     */
    _updateContentsModel(model) {
        let newModel = {
            path: model.path,
            name: model.name,
            type: model.type,
            content: undefined,
            writable: model.writable,
            created: model.created,
            last_modified: model.last_modified,
            mimetype: model.mimetype,
            format: model.format
        };
        let mod = this._contentsModel ? this._contentsModel.last_modified : null;
        this._contentsModel = newModel;
        if (!mod || newModel.last_modified !== mod) {
            this._fileChanged.emit(newModel);
        }
    }
    /**
     * Handle an initial population.
     */
    _populate() {
        this._isPopulated = true;
        this._isReady = true;
        this._populatedPromise.resolve(void 0);
        // Add a checkpoint if none exists and the file is writable.
        return this._maybeCheckpoint(false).then(() => {
            if (this.isDisposed) {
                return;
            }
            // Update the kernel preference.
            let name = this._model.defaultKernelName || this.session.kernelPreference.name;
            this.session.kernelPreference = Object.assign({}, this.session.kernelPreference, { name, language: this._model.defaultKernelLanguage });
            this.session.initialize();
        });
    }
    /**
     * Save the document contents to disk.
     */
    _save() {
        this._saveState.emit('started');
        let model = this._model;
        let content;
        if (this._factory.fileFormat === 'json') {
            content = model.toJSON();
        }
        else {
            content = model.toString();
        }
        let options = {
            type: this._factory.contentType,
            format: this._factory.fileFormat,
            content
        };
        return this._manager.ready
            .then(() => {
            if (!model.modelDB.isCollaborative) {
                return this._maybeSave(options);
            }
            return this._manager.contents.save(this._path, options);
        })
            .then(value => {
            if (this.isDisposed) {
                return;
            }
            model.dirty = false;
            this._updateContentsModel(value);
            if (!this._isPopulated) {
                return this._populate();
            }
        })
            .catch(err => {
            // If the save has been canceled by the user,
            // throw the error so that whoever called save()
            // can decide what to do.
            if (err.message === 'Cancel') {
                throw err;
            }
            // Otherwise show an error message and throw the error.
            const localPath = this._manager.contents.localPath(this._path);
            const name = coreutils_2.PathExt.basename(localPath);
            this._handleError(err, `File Save Error for ${name}`);
            throw err;
        })
            .then(value => {
            // Capture all success paths and emit completion.
            this._saveState.emit('completed');
            return value;
        }, err => {
            // Capture all error paths and emit failure.
            this._saveState.emit('failed');
            throw err;
        })
            .catch();
    }
    /**
     * Revert the document contents to disk contents.
     *
     * @param initializeModel - call the model's initialization function after
     * deserializing the content.
     */
    _revert(initializeModel = false) {
        let opts = {
            format: this._factory.fileFormat,
            type: this._factory.contentType,
            content: true
        };
        let path = this._path;
        let model = this._model;
        return this._manager.ready
            .then(() => {
            return this._manager.contents.get(path, opts);
        })
            .then(contents => {
            if (this.isDisposed) {
                return;
            }
            let dirty = false;
            if (contents.format === 'json') {
                model.fromJSON(contents.content);
                if (initializeModel) {
                    model.initialize();
                }
            }
            else {
                let content = contents.content;
                // Convert line endings if necessary, marking the file
                // as dirty.
                if (content.indexOf('\r') !== -1) {
                    dirty = true;
                    content = content.replace(/\r\n|\r/g, '\n');
                }
                model.fromString(content);
                if (initializeModel) {
                    model.initialize();
                }
            }
            this._updateContentsModel(contents);
            model.dirty = dirty;
            if (!this._isPopulated) {
                return this._populate();
            }
        })
            .catch(err => {
            const localPath = this._manager.contents.localPath(this._path);
            const name = coreutils_2.PathExt.basename(localPath);
            if (err.message === 'Invalid response: 400 bad format') {
                err = new Error('JupyterLab is unable to open this file type.');
            }
            this._handleError(err, `File Load Error for ${name}`);
            throw err;
        });
    }
    /**
     * Save a file, dealing with conflicts.
     */
    _maybeSave(options) {
        let path = this._path;
        // Make sure the file has not changed on disk.
        let promise = this._manager.contents.get(path, { content: false });
        return promise.then(model => {
            if (this.isDisposed) {
                return Promise.reject(new Error('Disposed'));
            }
            // We want to check last_modified (disk) > last_modified (client)
            // (our last save)
            // In some cases the filesystem reports an inconsistent time,
            // so we allow 0.5 seconds difference before complaining.
            let modified = this.contentsModel && this.contentsModel.last_modified;
            let tClient = new Date(modified);
            let tDisk = new Date(model.last_modified);
            if (modified && tDisk.getTime() - tClient.getTime() > 500) {
                // 500 ms
                return this._timeConflict(tClient, model, options);
            }
            return this._manager.contents.save(path, options);
        }, err => {
            if (err.response && err.response.status === 404) {
                return this._manager.contents.save(path, options);
            }
            throw err;
        });
    }
    /**
     * Handle a save/load error with a dialog.
     */
    _handleError(err, title) {
        let buttons = [apputils_1.Dialog.okButton()];
        // Check for a more specific error message.
        if (err instanceof services_1.ServerConnection.ResponseError) {
            err.response.text().then(text => {
                let body = '';
                try {
                    body = JSON.parse(text).message;
                }
                catch (e) {
                    body = text;
                }
                body = body || err.message;
                apputils_1.showDialog({ title, body, buttons });
            });
        }
        else {
            let body = err.message;
            apputils_1.showDialog({ title, body, buttons });
        }
    }
    /**
     * Add a checkpoint the file is writable.
     */
    _maybeCheckpoint(force) {
        let writable = this._contentsModel && this._contentsModel.writable;
        let promise = Promise.resolve(void 0);
        if (!writable) {
            return promise;
        }
        if (force) {
            promise = this.createCheckpoint();
        }
        else {
            promise = this.listCheckpoints().then(checkpoints => {
                writable = this._contentsModel && this._contentsModel.writable;
                if (!this.isDisposed && !checkpoints.length && writable) {
                    return this.createCheckpoint().then(() => {
                        /* no-op */
                    });
                }
            });
        }
        return promise.catch(err => {
            // Handle a read-only folder.
            if (!err.response || err.response.status !== 403) {
                throw err;
            }
        });
    }
    /**
     * Handle a time conflict.
     */
    _timeConflict(tClient, model, options) {
        let tDisk = new Date(model.last_modified);
        console.warn(`Last saving performed ${tClient} ` +
            `while the current file seems to have been saved ` +
            `${tDisk}`);
        let body = `The file has changed on disk since the last time it ` +
            `was opened or saved. ` +
            `Do you want to overwrite the file on disk with the version ` +
            ` open here, or load the version on disk (revert)?`;
        let revertBtn = apputils_1.Dialog.okButton({ label: 'REVERT' });
        let overwriteBtn = apputils_1.Dialog.warnButton({ label: 'OVERWRITE' });
        return apputils_1.showDialog({
            title: 'File Changed',
            body,
            buttons: [apputils_1.Dialog.cancelButton(), revertBtn, overwriteBtn]
        }).then(result => {
            if (this.isDisposed) {
                return Promise.reject(new Error('Disposed'));
            }
            if (result.button.label === 'OVERWRITE') {
                return this._manager.contents.save(this._path, options);
            }
            if (result.button.label === 'REVERT') {
                return this.revert().then(() => {
                    return model;
                });
            }
            return Promise.reject(new Error('Cancel')); // Otherwise cancel the save.
        });
    }
    /**
     * Handle a time conflict.
     */
    _maybeOverWrite(path) {
        let body = `"${path}" already exists. Do you want to replace it?`;
        let overwriteBtn = apputils_1.Dialog.warnButton({ label: 'OVERWRITE' });
        return apputils_1.showDialog({
            title: 'File Overwrite?',
            body,
            buttons: [apputils_1.Dialog.cancelButton(), overwriteBtn]
        }).then(result => {
            if (this.isDisposed) {
                return Promise.reject(new Error('Disposed'));
            }
            if (result.button.label === 'OVERWRITE') {
                return this._manager.contents.delete(path).then(() => {
                    this._finishSaveAs(path);
                });
            }
        });
    }
    /**
     * Finish a saveAs operation given a new path.
     */
    _finishSaveAs(newPath) {
        this._path = newPath;
        return this.session
            .setPath(newPath)
            .then(() => {
            this.session.setName(newPath.split('/').pop());
            return this.save();
        })
            .then(() => {
            this._pathChanged.emit(this._path);
            return this._maybeCheckpoint(true);
        });
    }
}
exports.Context = Context;
/**
 * A namespace for private data.
 */
var Private;
(function (Private) {
    /**
     * Get a new file path from the user.
     */
    function getSavePath(path) {
        let saveBtn = apputils_1.Dialog.okButton({ label: 'SAVE' });
        return apputils_1.showDialog({
            title: 'Save File As..',
            body: new SaveWidget(path),
            buttons: [apputils_1.Dialog.cancelButton(), saveBtn]
        }).then(result => {
            if (result.button.label === 'SAVE') {
                return result.value;
            }
            return;
        });
    }
    Private.getSavePath = getSavePath;
    /**
     * A no-op function.
     */
    function noOp() {
        /* no-op */
    }
    Private.noOp = noOp;
    /*
     * A widget that gets a file path from a user.
     */
    class SaveWidget extends widgets_1.Widget {
        /**
         * Construct a new save widget.
         */
        constructor(path) {
            super({ node: createSaveNode(path) });
        }
        /**
         * Get the value for the widget.
         */
        getValue() {
            return this.node.value;
        }
    }
    /**
     * Create the node for a save widget.
     */
    function createSaveNode(path) {
        let input = document.createElement('input');
        input.value = path;
        return input;
    }
})(Private || (Private = {}));


/***/ }),

/***/ "xqmc":
/*!********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotViolinIcon.js ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotViolinIcon = function PlotViolinIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M7.313 12.063c-.688-.688-1.25-1.25-1.25-2.375V5.813c0-.375-.25-.688-.625-.688s-.625.313-.625.688v3.875c0 1.125-.625 1.688-1.375 2.375-.813.75-1.813 1.688-1.813 3.688 0 2.188 1 3.188 1.875 3.938.688.688 1.313 1.188 1.313 2.438v3.813c0 .375.25.688.625.688s.625-.313.625-.688v-3.813c0-1.25.563-1.75 1.25-2.438.875-.813 1.813-1.813 1.813-3.938 0-2-1-2.938-1.813-3.688zm-2.125 5.5c-.875 0-1.563-.688-1.563-1.5 0-.875.75-1.563 1.563-1.563s1.563.688 1.563 1.563c0 .813-.688 1.5-1.563 1.5zm12.687.375c-.75-.688-1.25-1.063-1.25-1.875v-3.25c0-.375-.25-.688-.625-.688s-.625.313-.625.688v3.25c0 .813-.438 1.188-1.25 1.875-.875.625-1.875 1.5-1.875 3.188 0 1.938 1 2.75 1.875 3.438.688.563 1.188 1 1.188 1.938v3.188c0 .375.25.688.625.688.438 0 .688-.313.688-.688v-3.188c0-.938.5-1.375 1.25-1.938.813-.688 1.875-1.5 1.875-3.438 0-1.75-1-2.563-1.875-3.188zm-1.687 4.812a1.548 1.548 0 0 1-1.563-1.563c0-.813.75-1.5 1.563-1.5.875 0 1.563.688 1.563 1.5 0 .875-.688 1.563-1.563 1.563zM28.563 9.688c-.75-.813-1.375-1.438-1.375-2.813V2.312c0-.375-.25-.688-.625-.688s-.625.313-.625.688v4.563c0 1.375-.563 2-1.313 2.813-.813.938-1.75 1.938-1.75 4.188 0 2.438.938 3.563 1.813 4.438.75.813 1.25 1.438 1.25 2.938v4.5c0 .375.25.688.625.688.438 0 .688-.313.688-.688v-4.5c0-1.5.625-2.125 1.375-2.938.813-.938 1.75-2 1.75-4.438 0-2.25-.938-3.313-1.813-4.188zM26.875 15.5c-.875 0-1.563-.688-1.563-1.5 0-.875.688-1.563 1.563-1.563.813 0 1.5.688 1.5 1.563 0 .813-.688 1.5-1.5 1.5z' })
    );
};

exports.default = PlotViolinIcon;

/***/ }),

/***/ "y0JR":
/*!*******************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/default_panels/StyleNotesPanel.js ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _components = __webpack_require__(/*! ../components */ "yF51");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var StyleNotesPanel = function StyleNotesPanel(props, _ref) {
  var _ = _ref.localize;
  return _react2.default.createElement(
    _components.AnnotationAccordion,
    { canAdd: true },
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Note Text'), attr: 'text' },
      _react2.default.createElement(_components.TextEditor, { attr: 'text' }),
      _react2.default.createElement(_components.FontSelector, { label: _('Typeface'), attr: 'font.family' }),
      _react2.default.createElement(_components.Numeric, { label: _('Font Size'), attr: 'font.size', units: 'px' }),
      _react2.default.createElement(_components.ColorPicker, { label: _('Font Color'), attr: 'font.color' }),
      _react2.default.createElement(_components.Numeric, { label: _('Angle'), attr: 'textangle', units: '\xB0' }),
      _react2.default.createElement(_components.Dropdown, {
        label: _('Horizontal Alignment'),
        clearable: false,
        attr: 'align',
        options: [{ label: _('Left'), value: 'left' }, { label: _('Center'), value: 'center' }, { label: _('Right'), value: 'right' }]
      }),
      _react2.default.createElement(_components.Dropdown, {
        label: _('Vertical Alignment'),
        clearable: false,
        attr: 'valign',
        options: [{ label: _('Left'), value: 'left' }, { label: _('Center'), value: 'center' }, { label: _('Right'), value: 'right' }]
      })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Arrow') },
      _react2.default.createElement(_components.Radio, {
        attr: 'showarrow',
        options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
      }),
      _react2.default.createElement(_components.Numeric, { label: _('Line Width'), attr: 'arrowwidth', units: 'px' }),
      _react2.default.createElement(_components.ColorPicker, { label: _('Color'), attr: 'arrowcolor' }),
      _react2.default.createElement(_components.ArrowSelector, { label: _('Arrowhead'), attr: 'arrowhead' }),
      _react2.default.createElement(_components.Numeric, { label: _('Scale'), step: 0.1, attr: 'arrowsize', units: 'px' }),
      _react2.default.createElement(_components.AnnotationArrowRef, { label: _('X Offset'), attr: 'axref' }),
      _react2.default.createElement(_components.AnnotationArrowRef, { label: _('Y Offset'), attr: 'ayref' }),
      _react2.default.createElement(_components.NumericOrDate, { label: _('X Vector'), attr: 'ax' }),
      _react2.default.createElement(_components.NumericOrDate, { label: _('Y Vector'), attr: 'ay' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Horizontal Positioning') },
      _react2.default.createElement(_components.Dropdown, {
        label: _('Anchor Point'),
        clearable: false,
        attr: 'xanchor',
        options: [{ label: _('Auto'), value: 'auto' }, { label: _('Left'), value: 'left' }, { label: _('Center'), value: 'center' }, { label: _('Right'), value: 'right' }]
      }),
      _react2.default.createElement(_components.PositioningNumeric, { label: _('Position'), attr: 'x' }),
      _react2.default.createElement(_components.AnnotationRef, { label: _('Relative To'), attr: 'xref' })
    ),
    _react2.default.createElement(
      _components.PlotlySection,
      { name: _('Vertical Positioning') },
      _react2.default.createElement(_components.Dropdown, {
        label: _('Anchor Point'),
        clearable: false,
        attr: 'yanchor',
        options: [{ label: _('Auto'), value: 'auto' }, { label: _('Top'), value: 'top' }, { label: _('Middle'), value: 'middle' }, { label: _('Bottom'), value: 'bottom' }]
      }),
      _react2.default.createElement(_components.PositioningNumeric, { label: _('Position'), attr: 'y' }),
      _react2.default.createElement(_components.AnnotationRef, { label: _('Relative To'), attr: 'yref' })
    )
  );
};

StyleNotesPanel.contextTypes = {
  localize: _propTypes2.default.func
};

exports.default = StyleNotesPanel;
//# sourceMappingURL=StyleNotesPanel.js.map

/***/ }),

/***/ "y1AW":
/*!************************************************************!*\
  !*** ./node_modules/xterm/lib/renderer/atlas/CharAtlas.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var CharAtlasGenerator_1 = __webpack_require__(/*! ../../shared/atlas/CharAtlasGenerator */ "0CHe");
var CharAtlasUtils_1 = __webpack_require__(/*! ./CharAtlasUtils */ "jNJa");
var charAtlasCache = [];
function acquireCharAtlas(terminal, colors, scaledCharWidth, scaledCharHeight) {
    var newConfig = CharAtlasUtils_1.generateConfig(scaledCharWidth, scaledCharHeight, terminal, colors);
    for (var i = 0; i < charAtlasCache.length; i++) {
        var entry = charAtlasCache[i];
        var ownedByIndex = entry.ownedBy.indexOf(terminal);
        if (ownedByIndex >= 0) {
            if (CharAtlasUtils_1.configEquals(entry.config, newConfig)) {
                return entry.bitmap;
            }
            else {
                if (entry.ownedBy.length === 1) {
                    charAtlasCache.splice(i, 1);
                }
                else {
                    entry.ownedBy.splice(ownedByIndex, 1);
                }
                break;
            }
        }
    }
    for (var i = 0; i < charAtlasCache.length; i++) {
        var entry = charAtlasCache[i];
        if (CharAtlasUtils_1.configEquals(entry.config, newConfig)) {
            entry.ownedBy.push(terminal);
            return entry.bitmap;
        }
    }
    var canvasFactory = function (width, height) {
        var canvas = document.createElement('canvas');
        canvas.width = width;
        canvas.height = height;
        return canvas;
    };
    var newEntry = {
        bitmap: CharAtlasGenerator_1.generateCharAtlas(window, canvasFactory, newConfig),
        config: newConfig,
        ownedBy: [terminal]
    };
    charAtlasCache.push(newEntry);
    return newEntry.bitmap;
}
exports.acquireCharAtlas = acquireCharAtlas;

//# sourceMappingURL=CharAtlas.js.map


/***/ }),

/***/ "y1J4":
/*!******************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeRangeSliderIcon.js ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeRangeSliderIcon = function TraceTypeRangeSliderIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement('path', { fill: 'none', d: 'M0 0h46v46H0z' }),
        _react2.default.createElement('path', { fill: 'none', stroke: '#1d9bfb', d: 'M5.087 16.308L9.516 18.5l5.152-3.607 6.206 2.569 9.384-4.962 10.046 12.725', strokeMiterlimit: '10', strokeWidth: '2.348' }),
        _react2.default.createElement('path', { fill: '#1d9bfb', d: 'M5 33h15v6H5zm26 0h10v6H31z' }),
        _react2.default.createElement('path', { fill: '#25fdfc', d: 'M20 33h11v6H20z' }),
        _react2.default.createElement('path', { fill: 'none', stroke: '#25fdfc', d: 'M5 23l5 3 4-4 9 3 18-12', strokeMiterlimit: '10', strokeWidth: '2.348' }),
        _react2.default.createElement('path', { fill: 'none', stroke: '#1d9bfb', d: 'M23 42h-3V30h3m5 12h3V30h-3', strokeMiterlimit: '10', strokeWidth: '2.348' })
    );
};

exports.default = TraceTypeRangeSliderIcon;

/***/ }),

/***/ "y1pI":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_assocIndexOf.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var eq = __webpack_require__(/*! ./eq */ "ljhN");

/**
 * 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;
}

module.exports = assocIndexOf;


/***/ }),

/***/ "y48C":
/*!**************************************************!*\
  !*** ./node_modules/sanitize-html/dist/index.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var htmlparser = __webpack_require__(/*! htmlparser2 */ "hS6j");
var extend = __webpack_require__(/*! xtend */ "U6jy");
var quoteRegexp = __webpack_require__(/*! lodash.escaperegexp */ "AvKE");
var cloneDeep = __webpack_require__(/*! lodash.clonedeep */ "zT9C");
var mergeWith = __webpack_require__(/*! lodash.mergewith */ "qd8s");
var isString = __webpack_require__(/*! lodash.isstring */ "mfmY");
var isPlainObject = __webpack_require__(/*! lodash.isplainobject */ "zZPE");
var srcset = __webpack_require__(/*! srcset */ "4qD0");
var postcss = __webpack_require__(/*! postcss */ "ESK+");
var url = __webpack_require__(/*! url */ "CxY0");

function each(obj, cb) {
  if (obj) Object.keys(obj).forEach(function (key) {
    cb(obj[key], key);
  });
}

// Avoid false positives with .__proto__, .hasOwnProperty, etc.
function has(obj, key) {
  return {}.hasOwnProperty.call(obj, key);
}

// Returns those elements of `a` for which `cb(a)` returns truthy
function filter(a, cb) {
  var n = [];
  each(a, function (v) {
    if (cb(v)) {
      n.push(v);
    }
  });
  return n;
}

module.exports = sanitizeHtml;

// A valid attribute name.
// We use a tolerant definition based on the set of strings defined by
// html.spec.whatwg.org/multipage/parsing.html#before-attribute-name-state
// and html.spec.whatwg.org/multipage/parsing.html#attribute-name-state .
// The characters accepted are ones which can be appended to the attribute
// name buffer without triggering a parse error:
//   * unexpected-equals-sign-before-attribute-name
//   * unexpected-null-character
//   * unexpected-character-in-attribute-name
// We exclude the empty string because it's impossible to get to the after
// attribute name state with an empty attribute name buffer.
var VALID_HTML_ATTRIBUTE_NAME = /^[^\0\t\n\f\r /<=>]+$/;

// Ignore the _recursing flag; it's there for recursive
// invocation as a guard against this exploit:
// https://github.com/fb55/htmlparser2/issues/105

function sanitizeHtml(html, options, _recursing) {
  var result = '';

  function Frame(tag, attribs) {
    var that = this;
    this.tag = tag;
    this.attribs = attribs || {};
    this.tagPosition = result.length;
    this.text = ''; // Node inner text

    this.updateParentNodeText = function () {
      if (stack.length) {
        var parentFrame = stack[stack.length - 1];
        parentFrame.text += that.text;
      }
    };
  }

  if (!options) {
    options = sanitizeHtml.defaults;
    options.parser = htmlParserDefaults;
  } else {
    options = extend(sanitizeHtml.defaults, options);
    if (options.parser) {
      options.parser = extend(htmlParserDefaults, options.parser);
    } else {
      options.parser = htmlParserDefaults;
    }
  }

  // Tags that contain something other than HTML, or where discarding
  // the text when the tag is disallowed makes sense for other reasons.
  // If we are not allowing these tags, we should drop their content too.
  // For other tags you would drop the tag but keep its content.
  var nonTextTagsArray = options.nonTextTags || ['script', 'style', 'textarea'];
  var allowedAttributesMap;
  var allowedAttributesGlobMap;
  if (options.allowedAttributes) {
    allowedAttributesMap = {};
    allowedAttributesGlobMap = {};
    each(options.allowedAttributes, function (attributes, tag) {
      allowedAttributesMap[tag] = [];
      var globRegex = [];
      attributes.forEach(function (obj) {
        if (isString(obj) && obj.indexOf('*') >= 0) {
          globRegex.push(quoteRegexp(obj).replace(/\\\*/g, '.*'));
        } else {
          allowedAttributesMap[tag].push(obj);
        }
      });
      allowedAttributesGlobMap[tag] = new RegExp('^(' + globRegex.join('|') + ')$');
    });
  }
  var allowedClassesMap = {};
  each(options.allowedClasses, function (classes, tag) {
    // Implicitly allows the class attribute
    if (allowedAttributesMap) {
      if (!has(allowedAttributesMap, tag)) {
        allowedAttributesMap[tag] = [];
      }
      allowedAttributesMap[tag].push('class');
    }

    allowedClassesMap[tag] = classes;
  });

  var transformTagsMap = {};
  var transformTagsAll;
  each(options.transformTags, function (transform, tag) {
    var transFun;
    if (typeof transform === 'function') {
      transFun = transform;
    } else if (typeof transform === "string") {
      transFun = sanitizeHtml.simpleTransform(transform);
    }
    if (tag === '*') {
      transformTagsAll = transFun;
    } else {
      transformTagsMap[tag] = transFun;
    }
  });

  var depth = 0;
  var stack = [];
  var skipMap = {};
  var transformMap = {};
  var skipText = false;
  var skipTextDepth = 0;

  var parser = new htmlparser.Parser({
    onopentag: function onopentag(name, attribs) {
      if (skipText) {
        skipTextDepth++;
        return;
      }
      var frame = new Frame(name, attribs);
      stack.push(frame);

      var skip = false;
      var hasText = frame.text ? true : false;
      var transformedTag;
      if (has(transformTagsMap, name)) {
        transformedTag = transformTagsMap[name](name, attribs);

        frame.attribs = attribs = transformedTag.attribs;

        if (transformedTag.text !== undefined) {
          frame.innerText = transformedTag.text;
        }

        if (name !== transformedTag.tagName) {
          frame.name = name = transformedTag.tagName;
          transformMap[depth] = transformedTag.tagName;
        }
      }
      if (transformTagsAll) {
        transformedTag = transformTagsAll(name, attribs);

        frame.attribs = attribs = transformedTag.attribs;
        if (name !== transformedTag.tagName) {
          frame.name = name = transformedTag.tagName;
          transformMap[depth] = transformedTag.tagName;
        }
      }

      if (options.allowedTags && options.allowedTags.indexOf(name) === -1) {
        skip = true;
        if (nonTextTagsArray.indexOf(name) !== -1) {
          skipText = true;
          skipTextDepth = 1;
        }
        skipMap[depth] = true;
      }
      depth++;
      if (skip) {
        // We want the contents but not this tag
        return;
      }
      result += '<' + name;
      if (!allowedAttributesMap || has(allowedAttributesMap, name) || allowedAttributesMap['*']) {
        each(attribs, function (value, a) {
          if (!VALID_HTML_ATTRIBUTE_NAME.test(a)) {
            // This prevents part of an attribute name in the output from being
            // interpreted as the end of an attribute, or end of a tag.
            delete frame.attribs[a];
            return;
          }
          var parsed;
          // check allowedAttributesMap for the element and attribute and modify the value
          // as necessary if there are specific values defined.
          var passedAllowedAttributesMapCheck = false;
          if (!allowedAttributesMap || has(allowedAttributesMap, name) && allowedAttributesMap[name].indexOf(a) !== -1 || allowedAttributesMap['*'] && allowedAttributesMap['*'].indexOf(a) !== -1 || has(allowedAttributesGlobMap, name) && allowedAttributesGlobMap[name].test(a) || allowedAttributesGlobMap['*'] && allowedAttributesGlobMap['*'].test(a)) {
            passedAllowedAttributesMapCheck = true;
          } else if (allowedAttributesMap && allowedAttributesMap[name]) {
            var _iteratorNormalCompletion = true;
            var _didIteratorError = false;
            var _iteratorError = undefined;

            try {
              for (var _iterator = allowedAttributesMap[name][Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
                var o = _step.value;

                if (isPlainObject(o) && o.name && o.name === a) {
                  passedAllowedAttributesMapCheck = true;
                  var newValue = '';
                  if (o.multiple === true) {
                    // verify the values that are allowed
                    var splitStrArray = value.split(' ');
                    var _iteratorNormalCompletion2 = true;
                    var _didIteratorError2 = false;
                    var _iteratorError2 = undefined;

                    try {
                      for (var _iterator2 = splitStrArray[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
                        var s = _step2.value;

                        if (o.values.indexOf(s) !== -1) {
                          if (newValue === '') {
                            newValue = s;
                          } else {
                            newValue += ' ' + s;
                          }
                        }
                      }
                    } catch (err) {
                      _didIteratorError2 = true;
                      _iteratorError2 = err;
                    } finally {
                      try {
                        if (!_iteratorNormalCompletion2 && _iterator2.return) {
                          _iterator2.return();
                        }
                      } finally {
                        if (_didIteratorError2) {
                          throw _iteratorError2;
                        }
                      }
                    }
                  } else if (o.values.indexOf(value) >= 0) {
                    // verified an allowed value matches the entire attribute value
                    newValue = value;
                  }
                  value = newValue;
                }
              }
            } catch (err) {
              _didIteratorError = true;
              _iteratorError = err;
            } finally {
              try {
                if (!_iteratorNormalCompletion && _iterator.return) {
                  _iterator.return();
                }
              } finally {
                if (_didIteratorError) {
                  throw _iteratorError;
                }
              }
            }
          }
          if (passedAllowedAttributesMapCheck) {
            if (options.allowedSchemesAppliedToAttributes.indexOf(a) !== -1) {
              if (naughtyHref(name, value)) {
                delete frame.attribs[a];
                return;
              }
            }
            if (name === 'iframe' && a === 'src') {
              try {
                // naughtyHref is in charge of whether protocol relative URLs
                // are cool. We should just accept them
                parsed = url.parse(value, false, true);
                if (options.allowedIframeHostnames) {
                  var whitelistedHostnames = options.allowedIframeHostnames.find(function (hostname) {
                    return hostname === parsed.hostname;
                  });
                  if (!whitelistedHostnames) {
                    delete frame.attribs[a];
                    return;
                  }
                }
              } catch (e) {
                // Unparseable iframe src
                delete frame.attribs[a];
                return;
              }
            }
            if (a === 'srcset') {
              try {
                parsed = srcset.parse(value);
                each(parsed, function (value) {
                  if (naughtyHref('srcset', value.url)) {
                    value.evil = true;
                  }
                });
                parsed = filter(parsed, function (v) {
                  return !v.evil;
                });
                if (!parsed.length) {
                  delete frame.attribs[a];
                  return;
                } else {
                  value = srcset.stringify(filter(parsed, function (v) {
                    return !v.evil;
                  }));
                  frame.attribs[a] = value;
                }
              } catch (e) {
                // Unparseable srcset
                delete frame.attribs[a];
                return;
              }
            }
            if (a === 'class') {
              value = filterClasses(value, allowedClassesMap[name]);
              if (!value.length) {
                delete frame.attribs[a];
                return;
              }
            }
            if (a === 'style') {
              try {
                var abstractSyntaxTree = postcss.parse(name + " {" + value + "}");
                var filteredAST = filterCss(abstractSyntaxTree, options.allowedStyles);

                value = stringifyStyleAttributes(filteredAST);

                if (value.length === 0) {
                  delete frame.attribs[a];
                  return;
                }
              } catch (e) {
                delete frame.attribs[a];
                return;
              }
            }
            result += ' ' + a;
            if (value.length) {
              result += '="' + escapeHtml(value) + '"';
            }
          } else {
            delete frame.attribs[a];
          }
        });
      }
      if (options.selfClosing.indexOf(name) !== -1) {
        result += " />";
      } else {
        result += ">";
        if (frame.innerText && !hasText && !options.textFilter) {
          result += frame.innerText;
        }
      }
    },
    ontext: function ontext(text) {
      if (skipText) {
        return;
      }
      var lastFrame = stack[stack.length - 1];
      var tag;

      if (lastFrame) {
        tag = lastFrame.tag;
        // If inner text was set by transform function then let's use it
        text = lastFrame.innerText !== undefined ? lastFrame.innerText : text;
      }

      if (tag === 'script' || tag === 'style') {
        // htmlparser2 gives us these as-is. Escaping them ruins the content. Allowing
        // script tags is, by definition, game over for XSS protection, so if that's
        // your concern, don't allow them. The same is essentially true for style tags
        // which have their own collection of XSS vectors.
        result += text;
      } else {
        var escaped = escapeHtml(text);
        if (options.textFilter) {
          result += options.textFilter(escaped);
        } else {
          result += escaped;
        }
      }
      if (stack.length) {
        var frame = stack[stack.length - 1];
        frame.text += text;
      }
    },
    onclosetag: function onclosetag(name) {

      if (skipText) {
        skipTextDepth--;
        if (!skipTextDepth) {
          skipText = false;
        } else {
          return;
        }
      }

      var frame = stack.pop();
      if (!frame) {
        // Do not crash on bad markup
        return;
      }
      skipText = false;
      depth--;
      if (skipMap[depth]) {
        delete skipMap[depth];
        frame.updateParentNodeText();
        return;
      }

      if (transformMap[depth]) {
        name = transformMap[depth];
        delete transformMap[depth];
      }

      if (options.exclusiveFilter && options.exclusiveFilter(frame)) {
        result = result.substr(0, frame.tagPosition);
        return;
      }

      frame.updateParentNodeText();

      if (options.selfClosing.indexOf(name) !== -1) {
        // Already output />
        return;
      }

      result += "</" + name + ">";
    }
  }, options.parser);
  parser.write(html);
  parser.end();

  return result;

  function escapeHtml(s) {
    if (typeof s !== 'string') {
      s = s + '';
    }
    return s.replace(/&(?![a-zA-Z0-9#]{1,7};)/g, '&amp;') // Match ampersands not part of existing HTML entity
    .replace(/</g, '&lt;').replace(/\>/g, '&gt;').replace(/\"/g, '&quot;');
  }

  function naughtyHref(name, href) {
    // Browsers ignore character codes of 32 (space) and below in a surprising
    // number of situations. Start reading here:
    // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Embedded_tab
    href = href.replace(/[\x00-\x20]+/g, '');
    // Clobber any comments in URLs, which the browser might
    // interpret inside an XML data island, allowing
    // a javascript: URL to be snuck through
    href = href.replace(/<\!\-\-.*?\-\-\>/g, '');
    // Case insensitive so we don't get faked out by JAVASCRIPT #1
    var matches = href.match(/^([a-zA-Z]+)\:/);
    if (!matches) {
      // Protocol-relative URL starting with any combination of '/' and '\'
      if (href.match(/^[\/\\]{2}/)) {
        return !options.allowProtocolRelative;
      }

      // No scheme
      return false;
    }
    var scheme = matches[1].toLowerCase();

    if (has(options.allowedSchemesByTag, name)) {
      return options.allowedSchemesByTag[name].indexOf(scheme) === -1;
    }

    return !options.allowedSchemes || options.allowedSchemes.indexOf(scheme) === -1;
  }

  /**
   * Filters user input css properties by whitelisted regex attributes.
   *
   * @param {object} abstractSyntaxTree  - Object representation of CSS attributes.
   * @property {array[Declaration]} abstractSyntaxTree.nodes[0] - Each object cointains prop and value key, i.e { prop: 'color', value: 'red' }.
   * @param {object} allowedStyles       - Keys are properties (i.e color), value is list of permitted regex rules (i.e /green/i).
   * @return {object}                    - Abstract Syntax Tree with filtered style attributes.
   */
  function filterCss(abstractSyntaxTree, allowedStyles) {
    if (!allowedStyles) {
      return abstractSyntaxTree;
    }

    var filteredAST = cloneDeep(abstractSyntaxTree);
    var astRules = abstractSyntaxTree.nodes[0];
    var selectedRule;

    // Merge global and tag-specific styles into new AST.
    if (allowedStyles[astRules.selector] && allowedStyles['*']) {
      selectedRule = mergeWith(cloneDeep(allowedStyles[astRules.selector]), allowedStyles['*'], function (objValue, srcValue) {
        if (Array.isArray(objValue)) {
          return objValue.concat(srcValue);
        }
      });
    } else {
      selectedRule = allowedStyles[astRules.selector] || allowedStyles['*'];
    }

    if (selectedRule) {
      filteredAST.nodes[0].nodes = astRules.nodes.reduce(filterDeclarations(selectedRule), []);
    }

    return filteredAST;
  }

  /**
   * Extracts the style attribues from an AbstractSyntaxTree and formats those
   * values in the inline style attribute format.
   *
   * @param  {AbstractSyntaxTree} filteredAST
   * @return {string}             - Example: "color:yellow;text-align:center;font-family:helvetica;"
   */
  function stringifyStyleAttributes(filteredAST) {
    return filteredAST.nodes[0].nodes.reduce(function (extractedAttributes, attributeObject) {
      extractedAttributes.push(attributeObject.prop + ':' + attributeObject.value + ';');
      return extractedAttributes;
    }, []).join('');
  }

  /**
    * Filters the existing attributes for the given property. Discards any attributes
    * which don't match the whitelist.
    *
    * @param  {object} selectedRule             - Example: { color: red, font-family: helvetica }
    * @param  {array} allowedDeclarationsList   - List of declarations which pass whitelisting.
    * @param  {object} attributeObject          - Object representing the current css property.
    * @property {string} attributeObject.type   - Typically 'declaration'.
    * @property {string} attributeObject.prop   - The CSS property, i.e 'color'.
    * @property {string} attributeObject.value  - The corresponding value to the css property, i.e 'red'.
    * @return {function}                        - When used in Array.reduce, will return an array of Declaration objects
    */
  function filterDeclarations(selectedRule) {
    return function (allowedDeclarationsList, attributeObject) {
      // If this property is whitelisted...
      if (selectedRule.hasOwnProperty(attributeObject.prop)) {
        var matchesRegex = selectedRule[attributeObject.prop].some(function (regularExpression) {
          return regularExpression.test(attributeObject.value);
        });

        if (matchesRegex) {
          allowedDeclarationsList.push(attributeObject);
        }
      }
      return allowedDeclarationsList;
    };
  }

  function filterClasses(classes, allowed) {
    if (!allowed) {
      // The class attribute is allowed without filtering on this tag
      return classes;
    }
    classes = classes.split(/\s+/);
    return classes.filter(function (clss) {
      return allowed.indexOf(clss) !== -1;
    }).join(' ');
  }
}

// Defaults are accessible to you so that you can use them as a starting point
// programmatically if you wish

var htmlParserDefaults = {
  decodeEntities: true
};
sanitizeHtml.defaults = {
  allowedTags: ['h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'nl', 'li', 'b', 'i', 'strong', 'em', 'strike', 'code', 'hr', 'br', 'div', 'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre', 'iframe'],
  allowedAttributes: {
    a: ['href', 'name', 'target'],
    // We don't currently allow img itself by default, but this
    // would make sense if we did. You could add srcset here,
    // and if you do the URL is checked for safety
    img: ['src']
  },
  // Lots of these won't come up by default because we don't allow them
  selfClosing: ['img', 'br', 'hr', 'area', 'base', 'basefont', 'input', 'link', 'meta'],
  // URL schemes we permit
  allowedSchemes: ['http', 'https', 'ftp', 'mailto'],
  allowedSchemesByTag: {},
  allowedSchemesAppliedToAttributes: ['href', 'src', 'cite'],
  allowProtocolRelative: true
};

sanitizeHtml.simpleTransform = function (newTagName, newAttribs, merge) {
  merge = merge === undefined ? true : merge;
  newAttribs = newAttribs || {};

  return function (tagName, attribs) {
    var attrib;
    if (merge) {
      for (attrib in newAttribs) {
        attribs[attrib] = newAttribs[attrib];
      }
    } else {
      attribs = newAttribs;
    }

    return {
      tagName: newTagName,
      attribs: attribs
    };
  };
};

/***/ }),

/***/ "y4Pm":
/*!****************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeErrorBarsIcon.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeErrorBarsIcon = function TraceTypeErrorBarsIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 46 46' }, props),
        _react2.default.createElement('path', { fill: 'none', d: 'M0 0h46v46H0z' }),
        _react2.default.createElement('circle', { cx: '23', cy: '31', r: '3', fill: '#1d9bfb' }),
        _react2.default.createElement('path', { fill: 'none', stroke: '#1d9bfb', d: 'M23 23v16m4 0h-8m8-16h-8', strokeMiterlimit: '10', strokeWidth: '2' }),
        _react2.default.createElement('circle', { cx: '11', cy: '23', r: '3', fill: '#1d9bfb' }),
        _react2.default.createElement('path', { fill: 'none', stroke: '#1d9bfb', d: 'M11 11v24m4 0H7m8-24H7', strokeMiterlimit: '10', strokeWidth: '2' }),
        _react2.default.createElement('circle', { cx: '35', cy: '21', r: '3', fill: '#1d9bfb' }),
        _react2.default.createElement('path', { fill: 'none', stroke: '#1d9bfb', d: 'M35 9v24m4 0h-8m8-24h-8', strokeMiterlimit: '10', strokeWidth: '2' })
    );
};

exports.default = TraceTypeErrorBarsIcon;

/***/ }),

/***/ "y4qi":
/*!*********************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/SubplotCreator.js ***!
  \*********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _Dropdown = __webpack_require__(/*! ./Dropdown */ "dRXW");

var _Dropdown2 = _interopRequireDefault(_Dropdown);

var _Info = __webpack_require__(/*! ./Info */ "iOcY");

var _Info2 = _interopRequireDefault(_Info);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _constants = __webpack_require__(/*! ../../lib/constants */ "5Bkx");

var _Button = __webpack_require__(/*! ../widgets/Button */ "rZxl");

var _Button2 = _interopRequireDefault(_Button);

var _plotlyIcons = __webpack_require__(/*! plotly-icons */ "hwSx");

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _2 = __webpack_require__(/*! ./.. */ "yF51");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UnconnectedSingleSubplotCreator = function (_Component) {
  _inherits(UnconnectedSingleSubplotCreator, _Component);

  function UnconnectedSingleSubplotCreator() {
    _classCallCheck(this, UnconnectedSingleSubplotCreator);

    return _possibleConstructorReturn(this, (UnconnectedSingleSubplotCreator.__proto__ || Object.getPrototypeOf(UnconnectedSingleSubplotCreator)).apply(this, arguments));
  }

  _createClass(UnconnectedSingleSubplotCreator, [{
    key: 'canAddSubplot',
    value: function canAddSubplot() {
      var _this2 = this;

      var currentAxisId = this.props.fullContainer[this.props.attr];
      var currentTraceIndex = this.props.fullContainer.index;
      return this.context.fullData.some(function (d) {
        return d.index !== currentTraceIndex && d[_this2.props.attr] === currentAxisId;
      });
    }
  }, {
    key: 'addAndUpdateSubplot',
    value: function addAndUpdateSubplot() {
      var _props = this.props,
          attr = _props.attr,
          layoutAttr = _props.layoutAttr,
          updateContainer = _props.updateContainer;
      var subplots = this.context.fullLayout._subplots;

      var lastSubplotNumber = Number(subplots[layoutAttr][subplots[layoutAttr].length - 1].split(_constants.SUBPLOT_TO_ATTR[layoutAttr].layout)[1]) || 1;

      updateContainer(_defineProperty({}, attr, _constants.SUBPLOT_TO_ATTR[layoutAttr].layout + (lastSubplotNumber + 1)));
    }
  }, {
    key: 'updateSubplot',
    value: function updateSubplot(update) {
      var _this3 = this;

      var currentSubplotId = this.props.fullContainer[_constants.SUBPLOT_TO_ATTR[this.props.layoutAttr].data];
      var subplotToBeGarbageCollected = null;

      // When we select another subplot, make sure no unused axes are left
      if (currentSubplotId !== update && !this.context.fullData.some(function (trace) {
        return trace[_constants.SUBPLOT_TO_ATTR[_this3.props.layoutAttr].data] === currentSubplotId && trace.index !== _this3.props.fullContainer.index;
      })) {
        subplotToBeGarbageCollected = currentSubplotId;
      }

      this.context.onUpdate({
        type: _constants.EDITOR_ACTIONS.UPDATE_TRACES,
        payload: {
          subplotToBeGarbageCollected: subplotToBeGarbageCollected,
          update: _defineProperty({}, this.props.attr, update),
          traceIndexes: [this.props.fullContainer.index]
        }
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var _this4 = this;

      var icon = _react2.default.createElement(_plotlyIcons.PlusIcon, null);
      var extraComponent = this.canAddSubplot() ? _react2.default.createElement(_Button2.default, { variant: 'no-text', icon: icon, onClick: function onClick() {
          return _this4.addAndUpdateSubplot();
        } }) : _react2.default.createElement(_Button2.default, { variant: 'no-text--disabled', icon: icon, onClick: function onClick() {} });

      return _react2.default.createElement(_Dropdown2.default, {
        label: this.props.label,
        attr: this.props.attr,
        clearable: false,
        options: this.props.options,
        updatePlot: function updatePlot(u) {
          return _this4.updateSubplot(u);
        },
        extraComponent: extraComponent
      });
    }
  }]);

  return UnconnectedSingleSubplotCreator;
}(_react.Component);

UnconnectedSingleSubplotCreator.propTypes = {
  attr: _propTypes2.default.string,
  layoutAttr: _propTypes2.default.string,
  label: _propTypes2.default.string,
  options: _propTypes2.default.array,
  container: _propTypes2.default.object,
  fullContainer: _propTypes2.default.object,
  updateContainer: _propTypes2.default.func
};

UnconnectedSingleSubplotCreator.contextTypes = {
  fullLayout: _propTypes2.default.object,
  data: _propTypes2.default.array,
  fullData: _propTypes2.default.array,
  onUpdate: _propTypes2.default.func
};

var SingleSubplotCreator = (0, _lib.connectToContainer)(UnconnectedSingleSubplotCreator);

var UnconnectedSubplotCreator = function (_Component2) {
  _inherits(UnconnectedSubplotCreator, _Component2);

  function UnconnectedSubplotCreator() {
    _classCallCheck(this, UnconnectedSubplotCreator);

    return _possibleConstructorReturn(this, (UnconnectedSubplotCreator.__proto__ || Object.getPrototypeOf(UnconnectedSubplotCreator)).apply(this, arguments));
  }

  _createClass(UnconnectedSubplotCreator, [{
    key: 'render',
    value: function render() {
      var _this6 = this;

      var subplotType = (0, _lib.traceTypeToAxisType)(this.props.container.type);
      if (!['geo', 'mapbox', 'polar', 'gl3d', 'ternary'].some(function (t) {
        return t === subplotType;
      })) {
        return null;
      }

      var isFirstTraceOfAxisType = this.context.data.filter(function (d) {
        return (0, _lib.traceTypeToAxisType)(d.type) === subplotType;
      }).length === 1;
      if (isFirstTraceOfAxisType) {
        return null;
      }

      var _context = this.context,
          fullLayout = _context.fullLayout,
          _ = _context.localize;


      function getOptions(subplotType) {
        return fullLayout._subplots[subplotType].map(function (subplotId) {
          return {
            label: (0, _lib.getSubplotTitle)(subplotId, subplotType, _),
            value: subplotId
          };
        });
      }

      return _react2.default.createElement(
        _2.PlotlySection,
        { name: _('Subplots to Use') },
        _react2.default.createElement(SingleSubplotCreator, {
          attr: _constants.SUBPLOT_TO_ATTR[subplotType].data,
          layoutAttr: subplotType,
          label: _constants.SUBPLOT_TO_ATTR[subplotType].layout,
          options: getOptions(subplotType)
        }),
        _react2.default.createElement(
          _Info2.default,
          null,
          _('You can style and position your subplots in the '),
          _react2.default.createElement(
            'a',
            { onClick: function onClick() {
                return _this6.context.setPanel('Structure', 'Subplots');
              } },
            _('Subplots')
          ),
          _(' panel.')
        )
      );
    }
  }]);

  return UnconnectedSubplotCreator;
}(_react.Component);

UnconnectedSubplotCreator.propTypes = {
  container: _propTypes2.default.object,
  fullContainer: _propTypes2.default.object
};

UnconnectedSubplotCreator.contextTypes = {
  data: _propTypes2.default.array,
  fullData: _propTypes2.default.array,
  fullLayout: _propTypes2.default.object,
  localize: _propTypes2.default.func,
  setPanel: _propTypes2.default.func
};

exports.default = (0, _lib.connectToContainer)(UnconnectedSubplotCreator, {
  modifyPlotProps: function modifyPlotProps(props, context, plotProps) {
    var data = context.data;
    var fullContainer = plotProps.fullContainer;


    plotProps.isVisible = data.length > 1 && data[fullContainer.index] && ['geo', 'mapbox', 'polar', 'gl3d', 'ternary'].some(function (t) {
      return t === (0, _lib.traceTypeToAxisType)(data[fullContainer.index].type);
    });
  }
});
//# sourceMappingURL=SubplotCreator.js.map

/***/ }),

/***/ "y5KU":
/*!**********************************************************!*\
  !*** ./node_modules/@phosphor/datagrid/lib/datamodel.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
/**
 * An object which provides the data for a data grid.
 *
 * #### Notes
 * If the predefined data models are insufficient for a particular use
 * case, a custom model can be defined which derives from this class.
 */
var DataModel = (function () {
    function DataModel() {
        this._changed = new signaling_1.Signal(this);
    }
    Object.defineProperty(DataModel.prototype, "changed", {
        /**
         * A signal emitted when the data model has changed.
         */
        get: function () {
            return this._changed;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Get the metadata for a column in the data model.
     *
     * @param region - The cell region of interest.
     *
     * @param column - The index of the column of interest.
     *
     * @returns The metadata for the column.
     *
     * #### Notes
     * The returned metadata should be treated as immutable.
     *
     * Models which support columnar data may reimplement this method to
     * return the metadata for a column.
     *
     * The metadata can be used by custom cell renderers and cell editors
     * to customize handling of specific cell data types.
     *
     * This method is called often, and so should be efficient.
     *
     * The default implementation returns `{}`.
     */
    DataModel.prototype.metadata = function (region, column) {
        return DataModel.emptyMetadata;
    };
    /**
     * Emit the `changed` signal for the data model.
     *
     * #### Notes
     * Subclass should call this method whenever the data model has
     * changed so that attached data grids can update themselves.
     */
    DataModel.prototype.emitChanged = function (args) {
        this._changed.emit(args);
    };
    return DataModel;
}());
exports.DataModel = DataModel;
/**
 * The namespace for the `DataModel` class statics.
 */
(function (DataModel) {
    /**
     * A singleton empty metadata object.
     */
    DataModel.emptyMetadata = Object.freeze({});
})(DataModel = exports.DataModel || (exports.DataModel = {}));
exports.DataModel = DataModel;


/***/ }),

/***/ "y7cq":
/*!******************************************!*\
  !*** ./node_modules/path-posix/index.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors.
//
// 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.


var util = __webpack_require__(/*! util */ "7tlc");
var isString = function (x) {
  return typeof x === 'string';
};


// resolves . and .. elements in a path array with directory names there
// must be no slashes or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
  var res = [];
  for (var i = 0; i < parts.length; i++) {
    var p = parts[i];

    // ignore empty parts
    if (!p || p === '.')
      continue;

    if (p === '..') {
      if (res.length && res[res.length - 1] !== '..') {
        res.pop();
      } else if (allowAboveRoot) {
        res.push('..');
      }
    } else {
      res.push(p);
    }
  }

  return res;
}

// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe =
    /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var posix = {};


function posixSplitPath(filename) {
  return splitPathRe.exec(filename).slice(1);
}


// path.resolve([from ...], to)
// posix version
posix.resolve = function() {
  var resolvedPath = '',
      resolvedAbsolute = false;

  for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    var path = (i >= 0) ? arguments[i] : process.cwd();

    // Skip empty and invalid entries
    if (!isString(path)) {
      throw new TypeError('Arguments to path.resolve must be strings');
    } else if (!path) {
      continue;
    }

    resolvedPath = path + '/' + resolvedPath;
    resolvedAbsolute = path.charAt(0) === '/';
  }

  // At this point the path should be resolved to a full absolute path, but
  // handle relative paths to be safe (might happen when process.cwd() fails)

  // Normalize the path
  resolvedPath = normalizeArray(resolvedPath.split('/'),
                                !resolvedAbsolute).join('/');

  return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};

// path.normalize(path)
// posix version
posix.normalize = function(path) {
  var isAbsolute = posix.isAbsolute(path),
      trailingSlash = path.substr(-1) === '/';

  // Normalize the path
  path = normalizeArray(path.split('/'), !isAbsolute).join('/');

  if (!path && !isAbsolute) {
    path = '.';
  }
  if (path && trailingSlash) {
    path += '/';
  }

  return (isAbsolute ? '/' : '') + path;
};

// posix version
posix.isAbsolute = function(path) {
  return path.charAt(0) === '/';
};

// posix version
posix.join = function() {
  var path = '';
  for (var i = 0; i < arguments.length; i++) {
    var segment = arguments[i];
    if (!isString(segment)) {
      throw new TypeError('Arguments to path.join must be strings');
    }
    if (segment) {
      if (!path) {
        path += segment;
      } else {
        path += '/' + segment;
      }
    }
  }
  return posix.normalize(path);
};


// path.relative(from, to)
// posix version
posix.relative = function(from, to) {
  from = posix.resolve(from).substr(1);
  to = posix.resolve(to).substr(1);

  function trim(arr) {
    var start = 0;
    for (; start < arr.length; start++) {
      if (arr[start] !== '') break;
    }

    var end = arr.length - 1;
    for (; end >= 0; end--) {
      if (arr[end] !== '') break;
    }

    if (start > end) return [];
    return arr.slice(start, end + 1);
  }

  var fromParts = trim(from.split('/'));
  var toParts = trim(to.split('/'));

  var length = Math.min(fromParts.length, toParts.length);
  var samePartsLength = length;
  for (var i = 0; i < length; i++) {
    if (fromParts[i] !== toParts[i]) {
      samePartsLength = i;
      break;
    }
  }

  var outputParts = [];
  for (var i = samePartsLength; i < fromParts.length; i++) {
    outputParts.push('..');
  }

  outputParts = outputParts.concat(toParts.slice(samePartsLength));

  return outputParts.join('/');
};


posix._makeLong = function(path) {
  return path;
};


posix.dirname = function(path) {
  var result = posixSplitPath(path),
      root = result[0],
      dir = result[1];

  if (!root && !dir) {
    // No dirname whatsoever
    return '.';
  }

  if (dir) {
    // It has a dirname, strip trailing slash
    dir = dir.substr(0, dir.length - 1);
  }

  return root + dir;
};


posix.basename = function(path, ext) {
  var f = posixSplitPath(path)[2];
  // TODO: make this comparison case-insensitive on windows?
  if (ext && f.substr(-1 * ext.length) === ext) {
    f = f.substr(0, f.length - ext.length);
  }
  return f;
};


posix.extname = function(path) {
  return posixSplitPath(path)[3];
};


posix.format = function(pathObject) {
  if (!util.isObject(pathObject)) {
    throw new TypeError(
        "Parameter 'pathObject' must be an object, not " + typeof pathObject
    );
  }

  var root = pathObject.root || '';

  if (!isString(root)) {
    throw new TypeError(
        "'pathObject.root' must be a string or undefined, not " +
        typeof pathObject.root
    );
  }

  var dir = pathObject.dir ? pathObject.dir + posix.sep : '';
  var base = pathObject.base || '';
  return dir + base;
};


posix.parse = function(pathString) {
  if (!isString(pathString)) {
    throw new TypeError(
        "Parameter 'pathString' must be a string, not " + typeof pathString
    );
  }
  var allParts = posixSplitPath(pathString);
  if (!allParts || allParts.length !== 4) {
    throw new TypeError("Invalid path '" + pathString + "'");
  }
  allParts[1] = allParts[1] || '';
  allParts[2] = allParts[2] || '';
  allParts[3] = allParts[3] || '';

  return {
    root: allParts[0],
    dir: allParts[0] + allParts[1].slice(0, allParts[1].length - 1),
    base: allParts[2],
    ext: allParts[3],
    name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
  };
};


posix.sep = '/';
posix.delimiter = ':';

  module.exports = posix;

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../process/browser.js */ "8oxB")))

/***/ }),

/***/ "yF51":
/*!*****************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/index.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.AxisInterval = exports.NumericOrDate = exports.HovermodeDropdown = exports.HoveronDropdown = exports.LocationSelector = exports.RectanglePositioner = exports.DropdownCustom = exports.VisibilitySelect = exports.MultiColorPicker = exports.MarkerColor = exports.MarkerSize = exports.TextPosition = exports.Dropzone = exports.UpdateMenuButtons = exports.TraceTypeSection = exports.TraceSelector = exports.TraceRequiredPanel = exports.TraceOrientation = exports.TraceMarkerSection = exports.TraceAccordion = exports.SubplotAccordion = exports.TextEditor = exports.SymbolSelector = exports.GroupCreator = exports.SubplotCreator = exports.AxesCreator = exports.SingleSidebarItem = exports.Section = exports.PlotlySection = exports.Radio = exports.PanelMenuWrapper = exports.PanelEmpty = exports.Panel = exports.PlotlyPanel = exports.Text = exports.AxisRangeValue = exports.DualNumeric = exports.Numeric = exports.LineShapeSelector = exports.LineDashSelector = exports.LayoutPanel = exports.NumericFractionInverse = exports.PositioningNumeric = exports.NumericFractionDomain = exports.NumericFraction = exports.Info = exports.HoverTemplateSwitch = exports.HoverTemplateText = exports.HoverInfo = exports.FontSelector = exports.Fold = exports.PlotlyFold = exports.Flaglist = exports.FilterValue = exports.FilterOperation = exports.FillDropdown = exports.ErrorBars = exports.Dropdown = exports.DataSelector = exports.ContourNumeric = exports.PieColorscalePicker = exports.ColorwayPicker = exports.ColorscalePicker = exports.ColorPicker = exports.Button = exports.AxesSelector = exports.LayoutSection = exports.AxesRange = exports.AxesFold = exports.ArrowSelector = exports.PositioningRef = exports.AnnotationRef = exports.RangesliderVisible = exports.TransformAccordion = exports.AnnotationArrowRef = exports.UpdateMenuAccordion = exports.ImageAccordion = exports.SliderAccordion = exports.RangeSelectorAccordion = exports.ShapeAccordion = exports.DTicksInterval = exports.DTicks = exports.NTicks = exports.AxisSide = exports.AxisOverlayDropdown = exports.AxisAnchorDropdown = exports.AnnotationAccordion = exports.PanelMessage = exports.TickFormat = undefined;

var _fields = __webpack_require__(/*! ./fields */ "OfDz");

var _containers = __webpack_require__(/*! ./containers */ "Te0A");

var _widgets = __webpack_require__(/*! ./widgets */ "VizT");

var _PanelMenuWrapper = __webpack_require__(/*! ./PanelMenuWrapper */ "leYh");

var _PanelMenuWrapper2 = _interopRequireDefault(_PanelMenuWrapper);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.TickFormat = _fields.TickFormat;
exports.PanelMessage = _containers.PanelMessage;
exports.AnnotationAccordion = _containers.AnnotationAccordion;
exports.AxisAnchorDropdown = _fields.AxisAnchorDropdown;
exports.AxisOverlayDropdown = _fields.AxisOverlayDropdown;
exports.AxisSide = _fields.AxisSide;
exports.NTicks = _fields.NTicks;
exports.DTicks = _fields.DTicks;
exports.DTicksInterval = _fields.DTicksInterval;
exports.ShapeAccordion = _containers.ShapeAccordion;
exports.RangeSelectorAccordion = _containers.RangeSelectorAccordion;
exports.SliderAccordion = _containers.SliderAccordion;
exports.ImageAccordion = _containers.ImageAccordion;
exports.UpdateMenuAccordion = _containers.UpdateMenuAccordion;
exports.AnnotationArrowRef = _fields.AnnotationArrowRef;
exports.TransformAccordion = _containers.TransformAccordion;
exports.RangesliderVisible = _fields.RangesliderVisible;
exports.AnnotationRef = _fields.AnnotationRef;
exports.PositioningRef = _fields.PositioningRef;
exports.ArrowSelector = _fields.ArrowSelector;
exports.AxesFold = _containers.AxesFold;
exports.AxesRange = _fields.AxesRange;
exports.LayoutSection = _containers.LayoutSection;
exports.AxesSelector = _fields.AxesSelector;
exports.Button = _widgets.Button;
exports.ColorPicker = _fields.ColorPicker;
exports.ColorscalePicker = _fields.ColorscalePicker;
exports.ColorwayPicker = _fields.ColorwayPicker;
exports.PieColorscalePicker = _fields.PieColorscalePicker;
exports.ContourNumeric = _fields.ContourNumeric;
exports.DataSelector = _fields.DataSelector;
exports.Dropdown = _fields.Dropdown;
exports.ErrorBars = _fields.ErrorBars;
exports.FillDropdown = _fields.FillDropdown;
exports.FilterOperation = _fields.FilterOperation;
exports.FilterValue = _fields.FilterValue;
exports.Flaglist = _fields.Flaglist;
exports.PlotlyFold = _containers.PlotlyFold;
exports.Fold = _containers.Fold;
exports.FontSelector = _fields.FontSelector;
exports.HoverInfo = _fields.HoverInfo;
exports.HoverTemplateText = _fields.HoverTemplateText;
exports.HoverTemplateSwitch = _fields.HoverTemplateSwitch;
exports.Info = _fields.Info;
exports.NumericFraction = _fields.NumericFraction;
exports.NumericFractionDomain = _fields.NumericFractionDomain;
exports.PositioningNumeric = _fields.PositioningNumeric;
exports.NumericFractionInverse = _fields.NumericFractionInverse;
exports.LayoutPanel = _containers.LayoutPanel;
exports.LineDashSelector = _fields.LineDashSelector;
exports.LineShapeSelector = _fields.LineShapeSelector;
exports.Numeric = _fields.Numeric;
exports.DualNumeric = _fields.DualNumeric;
exports.AxisRangeValue = _fields.AxisRangeValue;
exports.Text = _fields.Text;
exports.PlotlyPanel = _containers.PlotlyPanel;
exports.Panel = _containers.Panel;
exports.PanelEmpty = _containers.PanelEmpty;
exports.PanelMenuWrapper = _PanelMenuWrapper2.default;
exports.Radio = _fields.Radio;
exports.PlotlySection = _containers.PlotlySection;
exports.Section = _containers.Section;
exports.SingleSidebarItem = _containers.SingleSidebarItem;
exports.AxesCreator = _fields.AxesCreator;
exports.SubplotCreator = _fields.SubplotCreator;
exports.GroupCreator = _fields.GroupCreator;
exports.SymbolSelector = _fields.SymbolSelector;
exports.TextEditor = _fields.TextEditor;
exports.SubplotAccordion = _containers.SubplotAccordion;
exports.TraceAccordion = _containers.TraceAccordion;
exports.TraceMarkerSection = _containers.TraceMarkerSection;
exports.TraceOrientation = _fields.TraceOrientation;
exports.TraceRequiredPanel = _containers.TraceRequiredPanel;
exports.TraceSelector = _fields.TraceSelector;
exports.TraceTypeSection = _containers.TraceTypeSection;
exports.UpdateMenuButtons = _fields.UpdateMenuButtons;
exports.Dropzone = _fields.Dropzone;
exports.TextPosition = _fields.TextPosition;
exports.MarkerSize = _fields.MarkerSize;
exports.MarkerColor = _fields.MarkerColor;
exports.MultiColorPicker = _fields.MultiColorPicker;
exports.VisibilitySelect = _fields.VisibilitySelect;
exports.DropdownCustom = _fields.DropdownCustom;
exports.RectanglePositioner = _fields.RectanglePositioner;
exports.LocationSelector = _fields.LocationSelector;
exports.HoveronDropdown = _fields.HoveronDropdown;
exports.HovermodeDropdown = _fields.HovermodeDropdown;
exports.NumericOrDate = _fields.NumericOrDate;
exports.AxisInterval = _fields.AxisInterval;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ "yGk4":
/*!*************************************!*\
  !*** ./node_modules/lodash/_Set.js ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var getNative = __webpack_require__(/*! ./_getNative */ "Cwc5"),
    root = __webpack_require__(/*! ./_root */ "Kz5y");

/* Built-in method references that are verified to be native. */
var Set = getNative(root, 'Set');

module.exports = Set;


/***/ }),

/***/ "yHx3":
/*!************************************************!*\
  !*** ./node_modules/lodash/_initCloneArray.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * 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;
}

module.exports = initCloneArray;


/***/ }),

/***/ "yLpj":
/*!***********************************!*\
  !*** (webpack)/buildin/global.js ***!
  \***********************************/
/*! no static exports found */
/***/ (function(module, exports) {

var g;

// This works in non-strict mode
g = (function() {
	return this;
})();

try {
	// This works if eval is allowed (see CSP)
	g = g || Function("return this")() || (1, eval)("this");
} catch (e) {
	// This works if the window reference is available
	if (typeof window === "object") g = window;
}

// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}

module.exports = g;


/***/ }),

/***/ "yNAP":
/*!*********************************************************************!*\
  !*** ./node_modules/@nteract/transform-vdom/lib/object-to-react.js ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

exports.objectToReactElement = objectToReactElement;
exports.arrayToReactChildren = arrayToReactChildren;


/**
 * The original copy of this comes from
 * https://github.com/remarkablemark/REON/blob/1f126e71c17f96daad518abffdb2c53b66b8b792/lib/object-to-react.js
 *
 * MIT License
 *
 * Copyright (c) 2016 Menglin "Mark" Xu <mark@remarkablemark.org>
 *
 * 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.
 */

var React = __webpack_require__(/*! react */ "q1tI");

/**
 * Convert an object to React element(s).
 *
 * The object schema should be similar to React element's.
 * Note: The object passed in this function will be mutated.
 *
 * @param  {Object}       obj - The element object.
 * @return {ReactElement}
 */
function objectToReactElement(obj) {
  // Pack args for React.createElement
  var args = [];

  if (!obj.tagName || typeof obj.tagName !== "string") {
    throw new Error("Invalid tagName on " + JSON.stringify(obj, null, 2));
  }
  if (!obj.attributes || _typeof(obj.attributes) !== "object") {
    throw new Error("Attributes must exist on a VDOM Object");
  }

  // `React.createElement` 1st argument: type
  args[0] = obj.tagName;
  args[1] = obj.attributes;

  var children = obj.children;

  if (children) {
    if (Array.isArray(children)) {
      // to be safe (although this should never happen)
      if (args[1] === undefined) {
        args[1] = null;
      }
      args = args.concat(arrayToReactChildren(children));
    } else if (typeof children === "string") {
      args[2] = children;
    } else if ((typeof children === "undefined" ? "undefined" : _typeof(children)) === "object") {
      args[2] = objectToReactElement(children);
    } else {
      console.warn("invalid vdom data passed", children);
    }
  }

  // $FlowFixMe: React
  return React.createElement.apply({}, args);
}

/**
 * Convert an array of items to React children.
 *
 * @param  {Array} arr - The array.
 * @return {Array}     - The array of mixed values.
 */
function arrayToReactChildren(arr) {
  // similar to `props.children`
  var result = [];
  // child of `props.children`

  // iterate through the `children`
  for (var i = 0, len = arr.length; i < len; i++) {
    // child can have mixed values: text, React element, or array
    var item = arr[i];
    if (Array.isArray(item)) {
      result.push(arrayToReactChildren(item));
    } else if (typeof item === "string") {
      result.push(item);
    } else if ((typeof item === "undefined" ? "undefined" : _typeof(item)) === "object") {
      var keyedItem = item;
      item.key = i;
      result.push(objectToReactElement(keyedItem));
    } else {
      console.warn("invalid vdom data passed", item);
    }
  }

  return result;
}

/***/ }),

/***/ "yNaG":
/*!******************************************************!*\
  !*** ./node_modules/@phosphor/widgets/lib/layout.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
var algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
var domutils_1 = __webpack_require__(/*! @phosphor/domutils */ "XWTc");
var messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
var properties_1 = __webpack_require__(/*! @phosphor/properties */ "3kwb");
var signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
var widget_1 = __webpack_require__(/*! ./widget */ "FmDU");
/**
 * An abstract base class for creating Phosphor layouts.
 *
 * #### Notes
 * A layout is used to add widgets to a parent and to arrange those
 * widgets within the parent's DOM node.
 *
 * This class implements the base functionality which is required of
 * nearly all layouts. It must be subclassed in order to be useful.
 *
 * Notably, this class does not define a uniform interface for adding
 * widgets to the layout. A subclass should define that API in a way
 * which is meaningful for its intended use.
 */
var Layout = (function () {
    /**
     * Construct a new layout.
     *
     * @param options - The options for initializing the layout.
     */
    function Layout(options) {
        if (options === void 0) { options = {}; }
        this._disposed = false;
        this._parent = null;
        this._fitPolicy = options.fitPolicy || 'set-min-size';
    }
    /**
     * Dispose of the resources held by the layout.
     *
     * #### Notes
     * This should be reimplemented to clear and dispose of the widgets.
     *
     * All reimplementations should call the superclass method.
     *
     * This method is called automatically when the parent is disposed.
     */
    Layout.prototype.dispose = function () {
        this._parent = null;
        this._disposed = true;
        signaling_1.Signal.clearData(this);
        properties_1.AttachedProperty.clearData(this);
    };
    Object.defineProperty(Layout.prototype, "isDisposed", {
        /**
         * Test whether the layout is disposed.
         */
        get: function () {
            return this._disposed;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Layout.prototype, "parent", {
        /**
         * Get the parent widget of the layout.
         */
        get: function () {
            return this._parent;
        },
        /**
         * Set the parent widget of the layout.
         *
         * #### Notes
         * This is set automatically when installing the layout on the parent
         * widget. The parent widget should not be set directly by user code.
         */
        set: function (value) {
            if (this._parent === value) {
                return;
            }
            if (this._parent) {
                throw new Error('Cannot change parent widget.');
            }
            if (value.layout !== this) {
                throw new Error('Invalid parent widget.');
            }
            this._parent = value;
            this.init();
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Layout.prototype, "fitPolicy", {
        /**
         * Get the fit policy for the layout.
         *
         * #### Notes
         * The fit policy controls the computed size constraints which are
         * applied to the parent widget by the layout.
         *
         * Some layout implementations may ignore the fit policy.
         */
        get: function () {
            return this._fitPolicy;
        },
        /**
         * Set the fit policy for the layout.
         *
         * #### Notes
         * The fit policy controls the computed size constraints which are
         * applied to the parent widget by the layout.
         *
         * Some layout implementations may ignore the fit policy.
         *
         * Changing the fit policy will clear the current size constraint
         * for the parent widget and then re-fit the parent.
         */
        set: function (value) {
            // Bail if the policy does not change
            if (this._fitPolicy === value) {
                return;
            }
            // Update the internal policy.
            this._fitPolicy = value;
            // Clear the size constraints and schedule a fit of the parent.
            if (this._parent) {
                var style = this._parent.node.style;
                style.minWidth = '';
                style.minHeight = '';
                style.maxWidth = '';
                style.maxHeight = '';
                this._parent.fit();
            }
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Process a message sent to the parent widget.
     *
     * @param msg - The message sent to the parent widget.
     *
     * #### Notes
     * This method is called by the parent widget to process a message.
     *
     * Subclasses may reimplement this method as needed.
     */
    Layout.prototype.processParentMessage = function (msg) {
        switch (msg.type) {
            case 'resize':
                this.onResize(msg);
                break;
            case 'update-request':
                this.onUpdateRequest(msg);
                break;
            case 'fit-request':
                this.onFitRequest(msg);
                break;
            case 'before-show':
                this.onBeforeShow(msg);
                break;
            case 'after-show':
                this.onAfterShow(msg);
                break;
            case 'before-hide':
                this.onBeforeHide(msg);
                break;
            case 'after-hide':
                this.onAfterHide(msg);
                break;
            case 'before-attach':
                this.onBeforeAttach(msg);
                break;
            case 'after-attach':
                this.onAfterAttach(msg);
                break;
            case 'before-detach':
                this.onBeforeDetach(msg);
                break;
            case 'after-detach':
                this.onAfterDetach(msg);
                break;
            case 'child-removed':
                this.onChildRemoved(msg);
                break;
            case 'child-shown':
                this.onChildShown(msg);
                break;
            case 'child-hidden':
                this.onChildHidden(msg);
                break;
        }
    };
    /**
     * Perform layout initialization which requires the parent widget.
     *
     * #### Notes
     * This method is invoked immediately after the layout is installed
     * on the parent widget.
     *
     * The default implementation reparents all of the widgets to the
     * layout parent widget.
     *
     * Subclasses should reimplement this method and attach the child
     * widget nodes to the parent widget's node.
     */
    Layout.prototype.init = function () {
        var _this = this;
        algorithm_1.each(this, function (widget) {
            widget.parent = _this.parent;
        });
    };
    /**
     * A message handler invoked on a `'resize'` message.
     *
     * #### Notes
     * The layout should ensure that its widgets are resized according
     * to the specified layout space, and that they are sent a `'resize'`
     * message if appropriate.
     *
     * The default implementation of this method sends an `UnknownSize`
     * resize message to all widgets.
     *
     * This may be reimplemented by subclasses as needed.
     */
    Layout.prototype.onResize = function (msg) {
        algorithm_1.each(this, function (widget) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.ResizeMessage.UnknownSize);
        });
    };
    /**
     * A message handler invoked on an `'update-request'` message.
     *
     * #### Notes
     * The layout should ensure that its widgets are resized according
     * to the available layout space, and that they are sent a `'resize'`
     * message if appropriate.
     *
     * The default implementation of this method sends an `UnknownSize`
     * resize message to all widgets.
     *
     * This may be reimplemented by subclasses as needed.
     */
    Layout.prototype.onUpdateRequest = function (msg) {
        algorithm_1.each(this, function (widget) {
            messaging_1.MessageLoop.sendMessage(widget, widget_1.Widget.ResizeMessage.UnknownSize);
        });
    };
    /**
     * A message handler invoked on a `'before-attach'` message.
     *
     * #### Notes
     * The default implementation of this method forwards the message
     * to all widgets. It assumes all widget nodes are attached to the
     * parent widget node.
     *
     * This may be reimplemented by subclasses as needed.
     */
    Layout.prototype.onBeforeAttach = function (msg) {
        algorithm_1.each(this, function (widget) {
            messaging_1.MessageLoop.sendMessage(widget, msg);
        });
    };
    /**
     * A message handler invoked on an `'after-attach'` message.
     *
     * #### Notes
     * The default implementation of this method forwards the message
     * to all widgets. It assumes all widget nodes are attached to the
     * parent widget node.
     *
     * This may be reimplemented by subclasses as needed.
     */
    Layout.prototype.onAfterAttach = function (msg) {
        algorithm_1.each(this, function (widget) {
            messaging_1.MessageLoop.sendMessage(widget, msg);
        });
    };
    /**
     * A message handler invoked on a `'before-detach'` message.
     *
     * #### Notes
     * The default implementation of this method forwards the message
     * to all widgets. It assumes all widget nodes are attached to the
     * parent widget node.
     *
     * This may be reimplemented by subclasses as needed.
     */
    Layout.prototype.onBeforeDetach = function (msg) {
        algorithm_1.each(this, function (widget) {
            messaging_1.MessageLoop.sendMessage(widget, msg);
        });
    };
    /**
     * A message handler invoked on an `'after-detach'` message.
     *
     * #### Notes
     * The default implementation of this method forwards the message
     * to all widgets. It assumes all widget nodes are attached to the
     * parent widget node.
     *
     * This may be reimplemented by subclasses as needed.
     */
    Layout.prototype.onAfterDetach = function (msg) {
        algorithm_1.each(this, function (widget) {
            messaging_1.MessageLoop.sendMessage(widget, msg);
        });
    };
    /**
     * A message handler invoked on a `'before-show'` message.
     *
     * #### Notes
     * The default implementation of this method forwards the message to
     * all non-hidden widgets. It assumes all widget nodes are attached
     * to the parent widget node.
     *
     * This may be reimplemented by subclasses as needed.
     */
    Layout.prototype.onBeforeShow = function (msg) {
        algorithm_1.each(this, function (widget) {
            if (!widget.isHidden) {
                messaging_1.MessageLoop.sendMessage(widget, msg);
            }
        });
    };
    /**
     * A message handler invoked on an `'after-show'` message.
     *
     * #### Notes
     * The default implementation of this method forwards the message to
     * all non-hidden widgets. It assumes all widget nodes are attached
     * to the parent widget node.
     *
     * This may be reimplemented by subclasses as needed.
     */
    Layout.prototype.onAfterShow = function (msg) {
        algorithm_1.each(this, function (widget) {
            if (!widget.isHidden) {
                messaging_1.MessageLoop.sendMessage(widget, msg);
            }
        });
    };
    /**
     * A message handler invoked on a `'before-hide'` message.
     *
     * #### Notes
     * The default implementation of this method forwards the message to
     * all non-hidden widgets. It assumes all widget nodes are attached
     * to the parent widget node.
     *
     * This may be reimplemented by subclasses as needed.
     */
    Layout.prototype.onBeforeHide = function (msg) {
        algorithm_1.each(this, function (widget) {
            if (!widget.isHidden) {
                messaging_1.MessageLoop.sendMessage(widget, msg);
            }
        });
    };
    /**
     * A message handler invoked on an `'after-hide'` message.
     *
     * #### Notes
     * The default implementation of this method forwards the message to
     * all non-hidden widgets. It assumes all widget nodes are attached
     * to the parent widget node.
     *
     * This may be reimplemented by subclasses as needed.
     */
    Layout.prototype.onAfterHide = function (msg) {
        algorithm_1.each(this, function (widget) {
            if (!widget.isHidden) {
                messaging_1.MessageLoop.sendMessage(widget, msg);
            }
        });
    };
    /**
     * A message handler invoked on a `'child-removed'` message.
     *
     * #### Notes
     * This will remove the child widget from the layout.
     *
     * Subclasses should **not** typically reimplement this method.
     */
    Layout.prototype.onChildRemoved = function (msg) {
        this.removeWidget(msg.child);
    };
    /**
     * A message handler invoked on a `'fit-request'` message.
     *
     * #### Notes
     * The default implementation of this handler is a no-op.
     */
    Layout.prototype.onFitRequest = function (msg) { };
    /**
     * A message handler invoked on a `'child-shown'` message.
     *
     * #### Notes
     * The default implementation of this handler is a no-op.
     */
    Layout.prototype.onChildShown = function (msg) { };
    /**
     * A message handler invoked on a `'child-hidden'` message.
     *
     * #### Notes
     * The default implementation of this handler is a no-op.
     */
    Layout.prototype.onChildHidden = function (msg) { };
    return Layout;
}());
exports.Layout = Layout;
/**
 * The namespace for the `Layout` class statics.
 */
(function (Layout) {
    /**
     * Get the horizontal alignment for a widget.
     *
     * @param widget - The widget of interest.
     *
     * @returns The horizontal alignment for the widget.
     *
     * #### Notes
     * If the layout width allocated to a widget is larger than its max
     * width, the horizontal alignment controls how the widget is placed
     * within the extra horizontal space.
     *
     * If the allocated width is less than the widget's max width, the
     * horizontal alignment has no effect.
     *
     * Some layout implementations may ignore horizontal alignment.
     */
    function getHorizontalAlignment(widget) {
        return Private.horizontalAlignmentProperty.get(widget);
    }
    Layout.getHorizontalAlignment = getHorizontalAlignment;
    /**
     * Set the horizontal alignment for a widget.
     *
     * @param widget - The widget of interest.
     *
     * @param value - The value for the horizontal alignment.
     *
     * #### Notes
     * If the layout width allocated to a widget is larger than its max
     * width, the horizontal alignment controls how the widget is placed
     * within the extra horizontal space.
     *
     * If the allocated width is less than the widget's max width, the
     * horizontal alignment has no effect.
     *
     * Some layout implementations may ignore horizontal alignment.
     *
     * Changing the horizontal alignment will post an `update-request`
     * message to widget's parent, provided the parent has a layout
     * installed.
     */
    function setHorizontalAlignment(widget, value) {
        Private.horizontalAlignmentProperty.set(widget, value);
    }
    Layout.setHorizontalAlignment = setHorizontalAlignment;
    /**
     * Get the vertical alignment for a widget.
     *
     * @param widget - The widget of interest.
     *
     * @returns The vertical alignment for the widget.
     *
     * #### Notes
     * If the layout height allocated to a widget is larger than its max
     * height, the vertical alignment controls how the widget is placed
     * within the extra vertical space.
     *
     * If the allocated height is less than the widget's max height, the
     * vertical alignment has no effect.
     *
     * Some layout implementations may ignore vertical alignment.
     */
    function getVerticalAlignment(widget) {
        return Private.verticalAlignmentProperty.get(widget);
    }
    Layout.getVerticalAlignment = getVerticalAlignment;
    /**
     * Set the vertical alignment for a widget.
     *
     * @param widget - The widget of interest.
     *
     * @param value - The value for the vertical alignment.
     *
     * #### Notes
     * If the layout height allocated to a widget is larger than its max
     * height, the vertical alignment controls how the widget is placed
     * within the extra vertical space.
     *
     * If the allocated height is less than the widget's max height, the
     * vertical alignment has no effect.
     *
     * Some layout implementations may ignore vertical alignment.
     *
     * Changing the horizontal alignment will post an `update-request`
     * message to widget's parent, provided the parent has a layout
     * installed.
     */
    function setVerticalAlignment(widget, value) {
        Private.verticalAlignmentProperty.set(widget, value);
    }
    Layout.setVerticalAlignment = setVerticalAlignment;
})(Layout = exports.Layout || (exports.Layout = {}));
exports.Layout = Layout;
/**
 * An object which assists in the absolute layout of widgets.
 *
 * #### Notes
 * This class is useful when implementing a layout which arranges its
 * widgets using absolute positioning.
 *
 * This class is used by nearly all of the built-in Phosphor layouts.
 */
var LayoutItem = (function () {
    /**
     * Construct a new layout item.
     *
     * @param widget - The widget to be managed by the item.
     *
     * #### Notes
     * The widget will be set to absolute positioning.
     */
    function LayoutItem(widget) {
        this._top = NaN;
        this._left = NaN;
        this._width = NaN;
        this._height = NaN;
        this._minWidth = 0;
        this._minHeight = 0;
        this._maxWidth = Infinity;
        this._maxHeight = Infinity;
        this._disposed = false;
        this.widget = widget;
        this.widget.node.style.position = 'absolute';
    }
    /**
     * Dispose of the the layout item.
     *
     * #### Notes
     * This will reset the positioning of the widget.
     */
    LayoutItem.prototype.dispose = function () {
        // Do nothing if the item is already disposed.
        if (this._disposed) {
            return;
        }
        // Mark the item as disposed.
        this._disposed = true;
        // Reset the widget style.
        var style = this.widget.node.style;
        style.position = '';
        style.top = '';
        style.left = '';
        style.width = '';
        style.height = '';
    };
    Object.defineProperty(LayoutItem.prototype, "minWidth", {
        /**
         * The computed minimum width of the widget.
         *
         * #### Notes
         * This value can be updated by calling the `fit` method.
         */
        get: function () {
            return this._minWidth;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(LayoutItem.prototype, "minHeight", {
        /**
         * The computed minimum height of the widget.
         *
         * #### Notes
         * This value can be updated by calling the `fit` method.
         */
        get: function () {
            return this._minHeight;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(LayoutItem.prototype, "maxWidth", {
        /**
         * The computed maximum width of the widget.
         *
         * #### Notes
         * This value can be updated by calling the `fit` method.
         */
        get: function () {
            return this._maxWidth;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(LayoutItem.prototype, "maxHeight", {
        /**
         * The computed maximum height of the widget.
         *
         * #### Notes
         * This value can be updated by calling the `fit` method.
         */
        get: function () {
            return this._maxHeight;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(LayoutItem.prototype, "isDisposed", {
        /**
         * Whether the layout item is disposed.
         */
        get: function () {
            return this._disposed;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(LayoutItem.prototype, "isHidden", {
        /**
         * Whether the managed widget is hidden.
         */
        get: function () {
            return this.widget.isHidden;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(LayoutItem.prototype, "isVisible", {
        /**
         * Whether the managed widget is visible.
         */
        get: function () {
            return this.widget.isVisible;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(LayoutItem.prototype, "isAttached", {
        /**
         * Whether the managed widget is attached.
         */
        get: function () {
            return this.widget.isAttached;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Update the computed size limits of the managed widget.
     */
    LayoutItem.prototype.fit = function () {
        var limits = domutils_1.ElementExt.sizeLimits(this.widget.node);
        this._minWidth = limits.minWidth;
        this._minHeight = limits.minHeight;
        this._maxWidth = limits.maxWidth;
        this._maxHeight = limits.maxHeight;
    };
    /**
     * Update the position and size of the managed widget.
     *
     * @param left - The left edge position of the layout box.
     *
     * @param top - The top edge position of the layout box.
     *
     * @param width - The width of the layout box.
     *
     * @param height - The height of the layout box.
     */
    LayoutItem.prototype.update = function (left, top, width, height) {
        // Clamp the size to the computed size limits.
        var clampW = Math.max(this._minWidth, Math.min(width, this._maxWidth));
        var clampH = Math.max(this._minHeight, Math.min(height, this._maxHeight));
        // Ajdust the left edge for the horizontal alignment, if needed.
        if (clampW < width) {
            switch (Layout.getHorizontalAlignment(this.widget)) {
                case 'left':
                    break;
                case 'center':
                    left += (width - clampW) / 2;
                    break;
                case 'right':
                    left += width - clampW;
                    break;
                default:
                    throw 'unreachable';
            }
        }
        // Ajdust the top edge for the vertical alignment, if needed.
        if (clampH < height) {
            switch (Layout.getVerticalAlignment(this.widget)) {
                case 'top':
                    break;
                case 'center':
                    top += (height - clampH) / 2;
                    break;
                case 'bottom':
                    top += height - clampH;
                    break;
                default:
                    throw 'unreachable';
            }
        }
        // Set up the resize variables.
        var resized = false;
        var style = this.widget.node.style;
        // Update the top edge of the widget if needed.
        if (this._top !== top) {
            this._top = top;
            style.top = top + "px";
        }
        // Update the left edge of the widget if needed.
        if (this._left !== left) {
            this._left = left;
            style.left = left + "px";
        }
        // Update the width of the widget if needed.
        if (this._width !== clampW) {
            resized = true;
            this._width = clampW;
            style.width = clampW + "px";
        }
        // Update the height of the widget if needed.
        if (this._height !== clampH) {
            resized = true;
            this._height = clampH;
            style.height = clampH + "px";
        }
        // Send a resize message to the widget if needed.
        if (resized) {
            var msg = new widget_1.Widget.ResizeMessage(clampW, clampH);
            messaging_1.MessageLoop.sendMessage(this.widget, msg);
        }
    };
    return LayoutItem;
}());
exports.LayoutItem = LayoutItem;
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * The attached property for a widget horizontal alignment.
     */
    Private.horizontalAlignmentProperty = new properties_1.AttachedProperty({
        name: 'horizontalAlignment',
        create: function () { return 'center'; },
        changed: onAlignmentChanged
    });
    /**
     * The attached property for a widget vertical alignment.
     */
    Private.verticalAlignmentProperty = new properties_1.AttachedProperty({
        name: 'verticalAlignment',
        create: function () { return 'top'; },
        changed: onAlignmentChanged
    });
    /**
     * The change handler for the attached alignment properties.
     */
    function onAlignmentChanged(child) {
        if (child.parent && child.parent.layout) {
            child.parent.update();
        }
    }
})(Private || (Private = {}));


/***/ }),

/***/ "yOY4":
/*!*****************************************************************!*\
  !*** ./node_modules/react-color/lib/components/common/Alpha.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Alpha = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _reactcss = __webpack_require__(/*! reactcss */ "/FUP");

var _reactcss2 = _interopRequireDefault(_reactcss);

var _alpha = __webpack_require__(/*! ../../helpers/alpha */ "THLb");

var alpha = _interopRequireWildcard(_alpha);

var _Checkboard = __webpack_require__(/*! ./Checkboard */ "Nq3d");

var _Checkboard2 = _interopRequireDefault(_Checkboard);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Alpha = exports.Alpha = function (_ref) {
  _inherits(Alpha, _ref);

  function Alpha() {
    var _ref2;

    var _temp, _this, _ret;

    _classCallCheck(this, Alpha);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref2 = Alpha.__proto__ || Object.getPrototypeOf(Alpha)).call.apply(_ref2, [this].concat(args))), _this), _this.handleChange = function (e, skip) {
      var change = alpha.calculateChange(e, skip, _this.props, _this.container);
      change && _this.props.onChange && _this.props.onChange(change, e);
    }, _this.handleMouseDown = function (e) {
      _this.handleChange(e, true);
      window.addEventListener('mousemove', _this.handleChange);
      window.addEventListener('mouseup', _this.handleMouseUp);
    }, _this.handleMouseUp = function () {
      _this.unbindEventListeners();
    }, _this.unbindEventListeners = function () {
      window.removeEventListener('mousemove', _this.handleChange);
      window.removeEventListener('mouseup', _this.handleMouseUp);
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(Alpha, [{
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      this.unbindEventListeners();
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var rgb = this.props.rgb;
      var styles = (0, _reactcss2.default)({
        'default': {
          alpha: {
            absolute: '0px 0px 0px 0px',
            borderRadius: this.props.radius
          },
          checkboard: {
            absolute: '0px 0px 0px 0px',
            overflow: 'hidden',
            borderRadius: this.props.radius
          },
          gradient: {
            absolute: '0px 0px 0px 0px',
            background: 'linear-gradient(to right, rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ', 0) 0%,\n           rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ', 1) 100%)',
            boxShadow: this.props.shadow,
            borderRadius: this.props.radius
          },
          container: {
            position: 'relative',
            height: '100%',
            margin: '0 3px'
          },
          pointer: {
            position: 'absolute',
            left: rgb.a * 100 + '%'
          },
          slider: {
            width: '4px',
            borderRadius: '1px',
            height: '8px',
            boxShadow: '0 0 2px rgba(0, 0, 0, .6)',
            background: '#fff',
            marginTop: '1px',
            transform: 'translateX(-2px)'
          }
        },
        'vertical': {
          gradient: {
            background: 'linear-gradient(to bottom, rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ', 0) 0%,\n           rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ', 1) 100%)'
          },
          pointer: {
            left: 0,
            top: rgb.a * 100 + '%'
          }
        },
        'overwrite': _extends({}, this.props.style)
      }, {
        vertical: this.props.direction === 'vertical',
        overwrite: true
      });

      return _react2.default.createElement(
        'div',
        { style: styles.alpha },
        _react2.default.createElement(
          'div',
          { style: styles.checkboard },
          _react2.default.createElement(_Checkboard2.default, { renderers: this.props.renderers })
        ),
        _react2.default.createElement('div', { style: styles.gradient }),
        _react2.default.createElement(
          'div',
          {
            style: styles.container,
            ref: function ref(container) {
              return _this2.container = container;
            },
            onMouseDown: this.handleMouseDown,
            onTouchMove: this.handleChange,
            onTouchStart: this.handleChange
          },
          _react2.default.createElement(
            'div',
            { style: styles.pointer },
            this.props.pointer ? _react2.default.createElement(this.props.pointer, this.props) : _react2.default.createElement('div', { style: styles.slider })
          )
        )
      );
    }
  }]);

  return Alpha;
}(_react.PureComponent || _react.Component);

exports.default = Alpha;

/***/ }),

/***/ "yP5f":
/*!*************************************************!*\
  !*** ./node_modules/lodash/_cloneTypedArray.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var cloneArrayBuffer = __webpack_require__(/*! ./_cloneArrayBuffer */ "+K+b");

/**
 * 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);
}

module.exports = cloneTypedArray;


/***/ }),

/***/ "yPMs":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/sq.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var sq = moment.defineLocale('sq', {
    months : 'Janar_Shkurt_Mars_Prill_Maj_Qershor_Korrik_Gusht_Shtator_Tetor_Nëntor_Dhjetor'.split('_'),
    monthsShort : 'Jan_Shk_Mar_Pri_Maj_Qer_Kor_Gus_Sht_Tet_Nën_Dhj'.split('_'),
    weekdays : 'E Diel_E Hënë_E Martë_E Mërkurë_E Enjte_E Premte_E Shtunë'.split('_'),
    weekdaysShort : 'Die_Hën_Mar_Mër_Enj_Pre_Sht'.split('_'),
    weekdaysMin : 'D_H_Ma_Më_E_P_Sh'.split('_'),
    weekdaysParseExact : true,
    meridiemParse: /PD|MD/,
    isPM: function (input) {
        return input.charAt(0) === 'M';
    },
    meridiem : function (hours, minutes, isLower) {
        return hours < 12 ? 'PD' : 'MD';
    },
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd, D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay : '[Sot në] LT',
        nextDay : '[Nesër në] LT',
        nextWeek : 'dddd [në] LT',
        lastDay : '[Dje në] LT',
        lastWeek : 'dddd [e kaluar në] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'në %s',
        past : '%s më parë',
        s : 'disa sekonda',
        ss : '%d sekonda',
        m : 'një minutë',
        mm : '%d minuta',
        h : 'një orë',
        hh : '%d orë',
        d : 'një ditë',
        dd : '%d ditë',
        M : 'një muaj',
        MM : '%d muaj',
        y : 'një vit',
        yy : '%d vite'
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return sq;

})));


/***/ }),

/***/ "yVpg":
/*!***************************************************************************************!*\
  !*** ./node_modules/@plotly/draft-js-export-html/lib/helpers/combineOrderedStyles.js ***!
  \***************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

function combineOrderedStyles(customMap, defaults) {
  if (customMap == null) {
    return defaults;
  }

  var _defaults = _slicedToArray(defaults, 2),
      defaultStyleMap = _defaults[0],
      defaultStyleOrder = _defaults[1];

  var styleMap = _extends({}, defaultStyleMap);
  var styleOrder = [].concat(_toConsumableArray(defaultStyleOrder));
  var _iteratorNormalCompletion = true;
  var _didIteratorError = false;
  var _iteratorError = undefined;

  try {
    for (var _iterator = Object.keys(customMap)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
      var _styleName = _step.value;

      if (defaultStyleMap.hasOwnProperty(_styleName)) {
        var defaultStyles = defaultStyleMap[_styleName];
        styleMap[_styleName] = _extends({}, defaultStyles, customMap[_styleName]);
      } else {
        styleMap[_styleName] = customMap[_styleName];
        styleOrder.push(_styleName);
      }
    }
  } catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion && _iterator.return) {
        _iterator.return();
      }
    } finally {
      if (_didIteratorError) {
        throw _iteratorError;
      }
    }
  }

  return [styleMap, styleOrder];
}

exports.default = combineOrderedStyles;

/***/ }),

/***/ "yYMQ":
/*!*****************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/widgets/FlaglistCheckboxGroup.js ***!
  \*****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _CheckboxGroup = __webpack_require__(/*! ./CheckboxGroup */ "gBRr");

var _CheckboxGroup2 = _interopRequireDefault(_CheckboxGroup);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

// Component handles activeOption with shape "x+y+z"
// and ties it to the CheckboxGroup Component
var FlaglistCheckboxGroup = function (_Component) {
  _inherits(FlaglistCheckboxGroup, _Component);

  function FlaglistCheckboxGroup(props) {
    _classCallCheck(this, FlaglistCheckboxGroup);

    var _this = _possibleConstructorReturn(this, (FlaglistCheckboxGroup.__proto__ || Object.getPrototypeOf(FlaglistCheckboxGroup)).call(this, props));

    var currentActiveOption = void 0;
    if (props.activeOption !== null) {
      currentActiveOption = props.activeOption;
    } else {
      currentActiveOption = '';
    }

    _this.state = {
      activeOption: _this.parseFlags(currentActiveOption)
    };

    _this.handleChange = _this.handleChange.bind(_this);
    return _this;
  }

  // convert plotly.js's "all" or "none" option in its `flaglist` type
  // to a series of options separated by `+` that our component can handle


  _createClass(FlaglistCheckboxGroup, [{
    key: 'parseFlags',
    value: function parseFlags(option) {
      var activeOption = void 0;
      if (option === 'all') {
        activeOption = this.props.options.map(function (o) {
          return o.value;
        }).join('+');
      } else if (option === 'none') {
        activeOption = '';
      } else {
        activeOption = option;
      }
      return activeOption;
    }

    // Sync local state to parent props.

  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      this.setState({ activeOption: this.parseFlags(nextProps.activeOption) });
    }

    // Called whenever a checkbox is changed, this updates the local
    // state to reflect the new activeOptions and then called props.onChange with
    // the new options.

  }, {
    key: 'handleChange',
    value: function handleChange(newOptions) {
      var newActiveOptions = '';

      newOptions.map(function (option) {
        if (option.checked === true) {
          newActiveOptions += option.value + '+';
        }
      });

      newActiveOptions = newActiveOptions.slice(0, -1);

      if (newActiveOptions.length === 0) {
        newActiveOptions = 'none';
      }

      this.setState({ activeOption: newActiveOptions });
      this.props.onChange(newActiveOptions);
    }

    // Turns the activeOptions "e.g "x+y+z" into an array that
    // the CheckboxGroup component can handle

  }, {
    key: 'renderCheckedOption',
    value: function renderCheckedOption() {
      var activeOptions = typeof this.state.activeOption === 'string' ? this.state.activeOption.split('+') : [this.state.activeOption];
      var allOptions = this.props.options;
      var newOptions = [];

      allOptions.map(function (option) {
        var currentChecked = void 0;

        if (activeOptions.indexOf(option.value) > -1) {
          currentChecked = true;
        } else {
          currentChecked = false;
        }

        newOptions.push({
          label: option.label,
          value: option.value,
          checked: currentChecked
        });
      });

      return newOptions;
    }
  }, {
    key: 'render',
    value: function render() {
      return _react2.default.createElement(_CheckboxGroup2.default, {
        options: this.renderCheckedOption(),
        onChange: this.handleChange,
        className: this.props.className,
        orientation: this.props.orientation
      });
    }
  }]);

  return FlaglistCheckboxGroup;
}(_react.Component);

FlaglistCheckboxGroup.propTypes = {
  options: _propTypes2.default.arrayOf(_propTypes2.default.shape({
    value: _propTypes2.default.any.isRequired,
    label: _propTypes2.default.string.isRequired
  })).isRequired,
  activeOption: _propTypes2.default.any,
  onChange: _propTypes2.default.func,
  className: _propTypes2.default.string,
  orientation: _propTypes2.default.string
};

exports.default = FlaglistCheckboxGroup;
//# sourceMappingURL=FlaglistCheckboxGroup.js.map

/***/ }),

/***/ "yZE0":
/*!************************************************!*\
  !*** ./node_modules/base16/lib/greenscreen.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'green screen',
  author: 'chris kempson (http://chriskempson.com)',
  base00: '#001100',
  base01: '#003300',
  base02: '#005500',
  base03: '#007700',
  base04: '#009900',
  base05: '#00bb00',
  base06: '#00dd00',
  base07: '#00ff00',
  base08: '#007700',
  base09: '#009900',
  base0A: '#007700',
  base0B: '#00bb00',
  base0C: '#005500',
  base0D: '#009900',
  base0E: '#00bb00',
  base0F: '#005500'
};
module.exports = exports['default'];

/***/ }),

/***/ "ydF4":
/*!***********************************************************************!*\
  !*** ./node_modules/@jupyterlab/extensionmanager/lib/build-helper.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const React = __importStar(__webpack_require__(/*! react */ "q1tI"));
/**
 * Instruct the server to perform a build
 *
 * @param builder the build manager
 */
function doBuild(builder) {
    if (builder.isAvailable) {
        return builder
            .build()
            .then(() => {
            return apputils_1.showDialog({
                title: 'Build Complete',
                body: 'Build successfully completed, reload page?',
                buttons: [
                    apputils_1.Dialog.cancelButton(),
                    apputils_1.Dialog.warnButton({ label: 'RELOAD' })
                ]
            });
        })
            .then(result => {
            if (result.button.accept) {
                location.reload();
            }
        })
            .catch(err => {
            apputils_1.showDialog({
                title: 'Build Failed',
                body: React.createElement("pre", null, err.message)
            });
        });
    }
    return Promise.resolve();
}
exports.doBuild = doBuild;


/***/ }),

/***/ "yhJu":
/*!**********************************************************!*\
  !*** ./node_modules/@jupyterlab/tooltip/style/index.css ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "T/NO");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "yhkN":
/*!**********************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils/lib/toolbar.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const vdom_1 = __webpack_require__(/*! ./vdom */ "PbVF");
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
const properties_1 = __webpack_require__(/*! @phosphor/properties */ "3kwb");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const React = __importStar(__webpack_require__(/*! react */ "q1tI"));
/**
 * The class name added to toolbars.
 */
const TOOLBAR_CLASS = 'jp-Toolbar';
/**
 * The class name added to toolbar items.
 */
const TOOLBAR_ITEM_CLASS = 'jp-Toolbar-item';
/**
 * The class name added to toolbar kernel name text.
 */
const TOOLBAR_KERNEL_NAME_CLASS = 'jp-Toolbar-kernelName';
/**
 * The class name added to toolbar spacer.
 */
const TOOLBAR_SPACER_CLASS = 'jp-Toolbar-spacer';
/**
 * The class name added to toolbar kernel status icon.
 */
const TOOLBAR_KERNEL_STATUS_CLASS = 'jp-Toolbar-kernelStatus';
/**
 * The class name added to a busy kernel indicator.
 */
const TOOLBAR_BUSY_CLASS = 'jp-FilledCircleIcon';
const TOOLBAR_IDLE_CLASS = 'jp-CircleIcon';
/**
 * A layout for toolbars.
 *
 * #### Notes
 * This layout automatically collapses its height if there are no visible
 * toolbar widgets, and expands to the standard toolbar height if there are
 * visible toolbar widgets.
 */
class ToolbarLayout extends widgets_1.PanelLayout {
    constructor() {
        super(...arguments);
        this._dirty = false;
    }
    /**
     * A message handler invoked on a `'fit-request'` message.
     *
     * If any child widget is visible, expand the toolbar height to the normal
     * toolbar height.
     */
    onFitRequest(msg) {
        super.onFitRequest(msg);
        if (this.parent.isAttached) {
            // If there are any widgets not explicitly hidden, expand the toolbar to
            // accommodate them.
            if (algorithm_1.some(this.widgets, w => !w.isHidden)) {
                this.parent.node.style.minHeight = 'var(--jp-private-toolbar-height)';
            }
            else {
                this.parent.node.style.minHeight = '';
            }
        }
        // Set the dirty flag to ensure only a single update occurs.
        this._dirty = true;
        // Notify the ancestor that it should fit immediately. This may
        // cause a resize of the parent, fulfilling the required update.
        if (this.parent.parent) {
            messaging_1.MessageLoop.sendMessage(this.parent.parent, widgets_1.Widget.Msg.FitRequest);
        }
        // If the dirty flag is still set, the parent was not resized.
        // Trigger the required update on the parent widget immediately.
        if (this._dirty) {
            messaging_1.MessageLoop.sendMessage(this.parent, widgets_1.Widget.Msg.UpdateRequest);
        }
    }
    /**
     * A message handler invoked on an `'update-request'` message.
     */
    onUpdateRequest(msg) {
        super.onUpdateRequest(msg);
        if (this.parent.isVisible) {
            this._dirty = false;
        }
    }
    /**
     * A message handler invoked on a `'child-shown'` message.
     */
    onChildShown(msg) {
        super.onChildShown(msg);
        // Post a fit request for the parent widget.
        this.parent.fit();
    }
    /**
     * A message handler invoked on a `'child-hidden'` message.
     */
    onChildHidden(msg) {
        super.onChildHidden(msg);
        // Post a fit request for the parent widget.
        this.parent.fit();
    }
    /**
     * A message handler invoked on a `'before-attach'` message.
     */
    onBeforeAttach(msg) {
        super.onBeforeAttach(msg);
        // Post a fit request for the parent widget.
        this.parent.fit();
    }
    /**
     * Attach a widget to the parent's DOM node.
     *
     * @param index - The current index of the widget in the layout.
     *
     * @param widget - The widget to attach to the parent.
     *
     * #### Notes
     * This is a reimplementation of the superclass method.
     */
    attachWidget(index, widget) {
        super.attachWidget(index, widget);
        // Post a fit request for the parent widget.
        this.parent.fit();
    }
    /**
     * Detach a widget from the parent's DOM node.
     *
     * @param index - The previous index of the widget in the layout.
     *
     * @param widget - The widget to detach from the parent.
     *
     * #### Notes
     * This is a reimplementation of the superclass method.
     */
    detachWidget(index, widget) {
        super.detachWidget(index, widget);
        // Post a fit request for the parent widget.
        this.parent.fit();
    }
}
/**
 * A class which provides a toolbar widget.
 */
class Toolbar extends widgets_1.Widget {
    /**
     * Construct a new toolbar widget.
     */
    constructor() {
        super();
        this.addClass(TOOLBAR_CLASS);
        this.layout = new ToolbarLayout();
    }
    /**
     * Get an iterator over the ordered toolbar item names.
     *
     * @returns An iterator over the toolbar item names.
     */
    names() {
        let layout = this.layout;
        return algorithm_1.map(layout.widgets, widget => {
            return Private.nameProperty.get(widget);
        });
    }
    /**
     * Add an item to the end of the toolbar.
     *
     * @param name - The name of the widget to add to the toolbar.
     *
     * @param widget - The widget to add to the toolbar.
     *
     * @param index - The optional name of the item to insert after.
     *
     * @returns Whether the item was added to toolbar.  Returns false if
     *   an item of the same name is already in the toolbar.
     *
     * #### Notes
     * The item can be removed from the toolbar by setting its parent to `null`.
     */
    addItem(name, widget) {
        let layout = this.layout;
        return this.insertItem(layout.widgets.length, name, widget);
    }
    /**
     * Insert an item into the toolbar at the specified index.
     *
     * @param index - The index at which to insert the item.
     *
     * @param name - The name of the item.
     *
     * @param widget - The widget to add.
     *
     * @returns Whether the item was added to the toolbar. Returns false if
     *   an item of the same name is already in the toolbar.
     *
     * #### Notes
     * The index will be clamped to the bounds of the items.
     * The item can be removed from the toolbar by setting its parent to `null`.
     */
    insertItem(index, name, widget) {
        let existing = algorithm_1.find(this.names(), value => value === name);
        if (existing) {
            return false;
        }
        widget.addClass(TOOLBAR_ITEM_CLASS);
        let layout = this.layout;
        layout.insertWidget(index, widget);
        Private.nameProperty.set(widget, name);
        return true;
    }
    /**
     * Handle the DOM events for the widget.
     *
     * @param event - The DOM event sent to the widget.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the dock panel's node. It should
     * not be called directly by user code.
     */
    handleEvent(event) {
        switch (event.type) {
            case 'click':
                if (!this.node.contains(document.activeElement) && this.parent) {
                    this.parent.activate();
                }
                break;
            default:
                break;
        }
    }
    /**
     * Handle `after-attach` messages for the widget.
     */
    onAfterAttach(msg) {
        this.node.addEventListener('click', this);
    }
    /**
     * Handle `before-detach` messages for the widget.
     */
    onBeforeDetach(msg) {
        this.node.removeEventListener('click', this);
    }
}
exports.Toolbar = Toolbar;
/**
 * The namespace for Toolbar class statics.
 */
(function (Toolbar) {
    /**
     * Create an interrupt toolbar item.
     */
    function createInterruptButton(session) {
        return new ToolbarButton({
            iconClassName: 'jp-StopIcon jp-Icon jp-Icon-16',
            onClick: () => {
                if (session.kernel) {
                    session.kernel.interrupt();
                }
            },
            tooltip: 'Interrupt the kernel'
        });
    }
    Toolbar.createInterruptButton = createInterruptButton;
    /**
     * Create a restart toolbar item.
     */
    function createRestartButton(session) {
        return new ToolbarButton({
            iconClassName: 'jp-RefreshIcon jp-Icon jp-Icon-16',
            onClick: () => {
                session.restart();
            },
            tooltip: 'Restart the kernel'
        });
    }
    Toolbar.createRestartButton = createRestartButton;
    /**
     * Create a toolbar spacer item.
     *
     * #### Notes
     * It is a flex spacer that separates the left toolbar items
     * from the right toolbar items.
     */
    function createSpacerItem() {
        return new Private.Spacer();
    }
    Toolbar.createSpacerItem = createSpacerItem;
    /**
     * Create a kernel name indicator item.
     *
     * #### Notes
     * It will display the `'display_name`' of the current kernel,
     * or `'No Kernel!'` if there is no kernel.
     * It can handle a change in context or kernel.
     */
    function createKernelNameItem(session) {
        return new Private.KernelName({ session });
    }
    Toolbar.createKernelNameItem = createKernelNameItem;
    /**
     * Create a kernel status indicator item.
     *
     * #### Notes
     * It show display a busy status if the kernel status is
     * not idle.
     * It will show the current status in the node title.
     * It can handle a change to the context or the kernel.
     */
    function createKernelStatusItem(session) {
        return new Private.KernelStatus(session);
    }
    Toolbar.createKernelStatusItem = createKernelStatusItem;
})(Toolbar = exports.Toolbar || (exports.Toolbar = {}));
/**
 * React component for a toolbar button.
 *
 * @param props - The props for ToolbarButtonComponent.
 */
function ToolbarButtonComponent(props) {
    const handleMouseDown = (event) => {
        event.preventDefault();
        props.onClick();
    };
    return (React.createElement("button", { className: props.className
            ? props.className + ' jp-ToolbarButtonComponent'
            : 'jp-ToolbarButtonComponent', disabled: props.enabled === false, onMouseDown: handleMouseDown, title: props.tooltip || props.iconLabel },
        props.iconClassName && (React.createElement("span", { className: props.iconClassName + ' jp-ToolbarButtonComponent-icon' })),
        props.label && (React.createElement("span", { className: "jp-ToolbarButtonComponent-label" }, props.label))));
}
exports.ToolbarButtonComponent = ToolbarButtonComponent;
/**
 * Phosphor Widget version of ToolbarButtonComponent.
 */
class ToolbarButton extends vdom_1.ReactElementWidget {
    /**
     * Create a ToolbarButton.
     *
     * @param props - Props for ToolbarButtonComponent.
     */
    constructor(props = {}) {
        super(React.createElement(ToolbarButtonComponent, Object.assign({}, props)));
        this.addClass('jp-ToolbarButton');
    }
}
exports.ToolbarButton = ToolbarButton;
/**
 * React component for a toolbar button that wraps a command.
 *
 * This wraps the ToolbarButtonComponent and watches the command registry
 * for changes to the command.
 */
class CommandToolbarButtonComponent extends React.Component {
    constructor(props) {
        super(props);
        props.commands.commandChanged.connect(this._onChange, this);
        this._childProps = Private.propsFromCommand(this.props);
    }
    render() {
        return React.createElement(ToolbarButtonComponent, Object.assign({}, this._childProps));
    }
    _onChange(sender, args) {
        if (args.id !== this.props.id) {
            return; // Not our command
        }
        if (args.type !== 'changed') {
            return; // Not a change
        }
        this._childProps = Private.propsFromCommand(this.props);
        this.forceUpdate();
    }
}
exports.CommandToolbarButtonComponent = CommandToolbarButtonComponent;
/**
 * Phosphor Widget version of ToolbarButtonComponent.
 */
class CommandToolbarButton extends vdom_1.ReactElementWidget {
    constructor(props) {
        super(React.createElement(CommandToolbarButtonComponent, Object.assign({}, props)));
        this.addClass('jp-CommandToolbarButton');
    }
}
exports.CommandToolbarButton = CommandToolbarButton;
/**
 * A namespace for private data.
 */
var Private;
(function (Private) {
    function propsFromCommand(options) {
        let { commands, id } = options;
        const iconClassName = commands.iconClass(id);
        const iconLabel = commands.iconLabel(id);
        const label = commands.label(id);
        let className = commands.className(id);
        // Add the boolean state classes.
        if (commands.isToggled(id)) {
            className += ' p-mod-toggled';
        }
        if (!commands.isVisible(id)) {
            className += ' p-mod-hidden';
        }
        const tooltip = commands.caption(id) || label || iconLabel;
        const onClick = () => {
            commands.execute(id);
        };
        const enabled = commands.isEnabled(id);
        return { className, iconClassName, tooltip, onClick, enabled };
    }
    Private.propsFromCommand = propsFromCommand;
    /**
     * An attached property for the name of a toolbar item.
     */
    Private.nameProperty = new properties_1.AttachedProperty({
        name: 'name',
        create: () => ''
    });
    /**
     * A no-op function.
     */
    function noOp() {
        /* no-op */
    }
    Private.noOp = noOp;
    /**
     * A spacer widget.
     */
    class Spacer extends widgets_1.Widget {
        /**
         * Construct a new spacer widget.
         */
        constructor() {
            super();
            this.addClass(TOOLBAR_SPACER_CLASS);
        }
    }
    Private.Spacer = Spacer;
    /**
     * React component for a kernel name button.
     *
     * This wraps the ToolbarButtonComponent and watches the kernel
     * session for changes.
     */
    class KernelNameComponent extends React.Component {
        constructor(props) {
            super(props);
            props.session.kernelChanged.connect(this._onKernelChanged, this);
            this._childProps = {
                className: TOOLBAR_KERNEL_NAME_CLASS,
                onClick: () => {
                    this.props.session.selectKernel();
                },
                tooltip: 'Switch kernel',
                label: props.session.kernelDisplayName
            };
        }
        render() {
            return React.createElement(ToolbarButtonComponent, Object.assign({}, this._childProps));
        }
        /**
         * Update the text of the kernel name item.
         */
        _onKernelChanged(session) {
            this._childProps.label = session.kernelDisplayName;
            this.forceUpdate();
        }
    }
    Private.KernelNameComponent = KernelNameComponent;
    /**
     * Phosphor Widget version of ToolbarButtonComponent.
     */
    class KernelName extends vdom_1.ReactElementWidget {
        constructor(props) {
            super(React.createElement(KernelNameComponent, Object.assign({}, props)));
            this.addClass('jp-KernelName');
        }
    }
    Private.KernelName = KernelName;
    /**
     * A toolbar item that displays kernel status.
     */
    class KernelStatus extends widgets_1.Widget {
        /**
         * Construct a new kernel status widget.
         */
        constructor(session) {
            super();
            this.addClass(TOOLBAR_KERNEL_STATUS_CLASS);
            this._onStatusChanged(session);
            session.statusChanged.connect(this._onStatusChanged, this);
        }
        /**
         * Handle a status on a kernel.
         */
        _onStatusChanged(session) {
            if (this.isDisposed) {
                return;
            }
            let status = session.status;
            this.toggleClass(TOOLBAR_IDLE_CLASS, status === 'idle');
            this.toggleClass(TOOLBAR_BUSY_CLASS, status !== 'idle');
            let title = 'Kernel ' + status[0].toUpperCase() + status.slice(1);
            this.node.title = title;
        }
    }
    Private.KernelStatus = KernelStatus;
})(Private || (Private = {}));


/***/ }),

/***/ "yjZJ":
/*!******************************************************************!*\
  !*** ./node_modules/@jupyterlab/services/lib/workspace/index.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const serverconnection_1 = __webpack_require__(/*! ../serverconnection */ "ZWV2");
/**
 * The url for the lab workspaces service.
 */
const SERVICE_WORKSPACES_URL = 'api/workspaces';
/**
 * The workspaces API service manager.
 */
class WorkspaceManager {
    /**
     * Create a new workspace manager.
     */
    constructor(options = {}) {
        this.serverSettings =
            options.serverSettings || serverconnection_1.ServerConnection.makeSettings();
    }
    /**
     * Fetch a workspace.
     *
     * @param id - The workspaces's ID.
     *
     * @returns A promise that resolves if successful.
     */
    fetch(id) {
        return __awaiter(this, void 0, void 0, function* () {
            const { serverSettings } = this;
            const { baseUrl, pageUrl } = serverSettings;
            const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;
            const base = baseUrl + pageUrl;
            const url = Private.url(base, id);
            const response = yield makeRequest(url, {}, serverSettings);
            if (response.status !== 200) {
                throw new ResponseError(response);
            }
            return response.json();
        });
    }
    /**
     * Fetch the list of workspace IDs that exist on the server.
     *
     * @returns A promise that resolves if successful.
     */
    list() {
        return __awaiter(this, void 0, void 0, function* () {
            const { serverSettings } = this;
            const { baseUrl, pageUrl } = serverSettings;
            const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;
            const base = baseUrl + pageUrl;
            const url = Private.url(base, '');
            const response = yield makeRequest(url, {}, serverSettings);
            if (response.status !== 200) {
                throw new ResponseError(response);
            }
            const result = yield response.json();
            return result.workspaces;
        });
    }
    /**
     * Remove a workspace from the server.
     *
     * @param id - The workspaces's ID.
     *
     * @returns A promise that resolves if successful.
     */
    remove(id) {
        return __awaiter(this, void 0, void 0, function* () {
            const { serverSettings } = this;
            const { baseUrl, pageUrl } = serverSettings;
            const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;
            const base = baseUrl + pageUrl;
            const url = Private.url(base, id);
            const init = { method: 'DELETE' };
            const response = yield makeRequest(url, init, serverSettings);
            if (response.status !== 204) {
                throw new ResponseError(response);
            }
        });
    }
    /**
     * Save a workspace.
     *
     * @param id - The workspace's ID.
     *
     * @param workspace - The workspace being saved.
     *
     * @returns A promise that resolves if successful.
     */
    save(id, workspace) {
        return __awaiter(this, void 0, void 0, function* () {
            const { serverSettings } = this;
            const { baseUrl, pageUrl } = serverSettings;
            const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;
            const base = baseUrl + pageUrl;
            const url = Private.url(base, id);
            const init = { body: JSON.stringify(workspace), method: 'PUT' };
            const response = yield makeRequest(url, init, serverSettings);
            if (response.status !== 204) {
                throw new ResponseError(response);
            }
        });
    }
}
exports.WorkspaceManager = WorkspaceManager;
/**
 * A namespace for private data.
 */
var Private;
(function (Private) {
    /**
     * Get the url for a workspace.
     */
    function url(base, id) {
        return coreutils_1.URLExt.join(base, SERVICE_WORKSPACES_URL, id);
    }
    Private.url = url;
})(Private || (Private = {}));


/***/ }),

/***/ "ykRn":
/*!******************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/derived.js ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.TraceTypeSection = exports.LayoutSection = exports.LayoutPanel = undefined;

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _PlotlyPanel = __webpack_require__(/*! ./PlotlyPanel */ "54u7");

var _PlotlyPanel2 = _interopRequireDefault(_PlotlyPanel);

var _PlotlySection = __webpack_require__(/*! ./PlotlySection */ "aR6p");

var _PlotlySection2 = _interopRequireDefault(_PlotlySection);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var LayoutPanel = (0, _lib.connectLayoutToPlot)(_PlotlyPanel2.default);
var LayoutSection = (0, _lib.connectLayoutToPlot)(_PlotlySection2.default);

var TraceTypeSection = function TraceTypeSection(props, context) {
  var fullContainer = context.fullContainer,
      fullData = context.fullData;
  var mode = props.mode,
      traceTypes = props.traceTypes;


  var ifConnectedToTrace = mode === 'trace' && fullContainer && traceTypes.includes(fullContainer.type);

  var ifConnectedToLayout = mode === 'layout' && fullData && fullData.some(function (t) {
    return traceTypes.includes(t.type);
  });

  if (ifConnectedToTrace || ifConnectedToLayout) {
    return _react2.default.createElement(_PlotlySection2.default, props);
  }

  return null;
};

TraceTypeSection.contextTypes = _lib.containerConnectedContextTypes;
TraceTypeSection.propTypes = {
  children: _propTypes2.default.node,
  name: _propTypes2.default.string,
  traceTypes: _propTypes2.default.array,
  mode: _propTypes2.default.string
};

TraceTypeSection.defaultProps = {
  traceTypes: [],
  mode: 'layout'
};

exports.LayoutPanel = LayoutPanel;
exports.LayoutSection = LayoutSection;
exports.TraceTypeSection = TraceTypeSection;
//# sourceMappingURL=derived.js.map

/***/ }),

/***/ "yuBE":
/*!***********************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/NotebookMIconIcon.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var NotebookMIconIcon = function NotebookMIconIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M27.625 32H5.812a.722.722 0 0 1-.75-.75V.75c0-.438.313-.75.75-.75h21.813c.438 0 .75.313.75.75v30.5c0 .438-.313.75-.75.75zM6.563 30.563h20.375V1.438H6.563zm.687-24.75H4.375c-.438 0-.75-.313-.75-.75s.313-.688.75-.688H7.25c.438 0 .75.25.75.688s-.313.75-.75.75zm0 4.375H4.375c-.438 0-.75-.313-.75-.75s.313-.688.75-.688H7.25c.438 0 .75.25.75.688s-.313.75-.75.75zm0 4.375H4.375c-.438 0-.75-.313-.75-.75s.313-.75.75-.75H7.25c.438 0 .75.313.75.75s-.313.75-.75.75zm0 4.375H4.375c-.438 0-.75-.313-.75-.75s.313-.75.75-.75H7.25c.438 0 .75.313.75.75s-.313.75-.75.75zm0 4.312H4.375c-.438 0-.75-.25-.75-.688s.313-.75.75-.75H7.25c.438 0 .75.313.75.75s-.313.688-.75.688zm0 4.375H4.375c-.438 0-.75-.25-.75-.688s.313-.75.75-.75H7.25c.438 0 .75.313.75.75s-.313.688-.75.688zm5.813-6.125v-11h2.188l2.625 7.813c.313.75.438 1.313.625 1.625.125-.438.25-1 .563-1.75l2.625-7.688h1.875v11h-1.438v-9.313l-3.188 9.188H17.75l-3.188-9.313V21.5zm-3.625-2h2.063v2H9.438z' })
    );
};

exports.default = NotebookMIconIcon;

/***/ }),

/***/ "yxyD":
/*!**************************************************************!*\
  !*** ./node_modules/draft-js/lib/encodeInlineStyleRanges.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule encodeInlineStyleRanges
 * @format
 * 
 */



var UnicodeUtils = __webpack_require__(/*! fbjs/lib/UnicodeUtils */ "jLRO");

var findRangesImmutable = __webpack_require__(/*! ./findRangesImmutable */ "Taje");

var areEqual = function areEqual(a, b) {
  return a === b;
};
var isTruthy = function isTruthy(a) {
  return !!a;
};
var EMPTY_ARRAY = [];

/**
 * Helper function for getting encoded styles for each inline style. Convert
 * to UTF-8 character counts for storage.
 */
function getEncodedInlinesForType(block, styleList, styleToEncode) {
  var ranges = [];

  // Obtain an array with ranges for only the specified style.
  var filteredInlines = styleList.map(function (style) {
    return style.has(styleToEncode);
  }).toList();

  findRangesImmutable(filteredInlines, areEqual,
  // We only want to keep ranges with nonzero style values.
  isTruthy, function (start, end) {
    var text = block.getText();
    ranges.push({
      offset: UnicodeUtils.strlen(text.slice(0, start)),
      length: UnicodeUtils.strlen(text.slice(start, end)),
      style: styleToEncode
    });
  });

  return ranges;
}

/*
 * Retrieve the encoded arrays of inline styles, with each individual style
 * treated separately.
 */
function encodeInlineStyleRanges(block) {
  var styleList = block.getCharacterList().map(function (c) {
    return c.getStyle();
  }).toList();
  var ranges = styleList.flatten().toSet().map(function (style) {
    return getEncodedInlinesForType(block, styleList, style);
  });

  return Array.prototype.concat.apply(EMPTY_ARRAY, ranges.toJS());
}

module.exports = encodeInlineStyleRanges;

/***/ }),

/***/ "yyUu":
/*!*******************************************!*\
  !*** ./node_modules/base16/lib/embers.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'embers',
  author: 'jannik siebert (https://github.com/janniks)',
  base00: '#16130F',
  base01: '#2C2620',
  base02: '#433B32',
  base03: '#5A5047',
  base04: '#8A8075',
  base05: '#A39A90',
  base06: '#BEB6AE',
  base07: '#DBD6D1',
  base08: '#826D57',
  base09: '#828257',
  base0A: '#6D8257',
  base0B: '#57826D',
  base0C: '#576D82',
  base0D: '#6D5782',
  base0E: '#82576D',
  base0F: '#825757'
};
module.exports = exports['default'];

/***/ }),

/***/ "yzbm":
/*!******************************************************!*\
  !*** ./node_modules/react-dropzone/dist/es/index.js ***!
  \******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "q1tI");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! prop-types */ "17x9");
/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(prop_types__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils */ "Cwia");
/* harmony import */ var _utils_styles__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils/styles */ "nWiE");
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/* global process */
/* eslint prefer-template: 0 */






var Dropzone = function (_React$Component) {
  _inherits(Dropzone, _React$Component);

  function Dropzone(props, context) {
    _classCallCheck(this, Dropzone);

    var _this = _possibleConstructorReturn(this, (Dropzone.__proto__ || Object.getPrototypeOf(Dropzone)).call(this, props, context));

    _this.renderChildren = function (children, isDragActive, isDragAccept, isDragReject) {
      if (typeof children === 'function') {
        return children(_extends({}, _this.state, {
          isDragActive: isDragActive,
          isDragAccept: isDragAccept,
          isDragReject: isDragReject
        }));
      }
      return children;
    };

    _this.composeHandlers = _this.composeHandlers.bind(_this);
    _this.onClick = _this.onClick.bind(_this);
    _this.onDocumentDrop = _this.onDocumentDrop.bind(_this);
    _this.onDragEnter = _this.onDragEnter.bind(_this);
    _this.onDragLeave = _this.onDragLeave.bind(_this);
    _this.onDragOver = _this.onDragOver.bind(_this);
    _this.onDragStart = _this.onDragStart.bind(_this);
    _this.onDrop = _this.onDrop.bind(_this);
    _this.onFileDialogCancel = _this.onFileDialogCancel.bind(_this);
    _this.onInputElementClick = _this.onInputElementClick.bind(_this);

    _this.setRef = _this.setRef.bind(_this);
    _this.setRefs = _this.setRefs.bind(_this);

    _this.isFileDialogActive = false;

    _this.state = {
      draggedFiles: [],
      acceptedFiles: [],
      rejectedFiles: []
    };
    return _this;
  }

  _createClass(Dropzone, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      var preventDropOnDocument = this.props.preventDropOnDocument;

      this.dragTargets = [];

      if (preventDropOnDocument) {
        document.addEventListener('dragover', _utils__WEBPACK_IMPORTED_MODULE_2__["onDocumentDragOver"], false);
        document.addEventListener('drop', this.onDocumentDrop, false);
      }
      if (this.fileInputEl != null) {
        this.fileInputEl.addEventListener('click', this.onInputElementClick, false);
      }
      window.addEventListener('focus', this.onFileDialogCancel, false);
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      var preventDropOnDocument = this.props.preventDropOnDocument;

      if (preventDropOnDocument) {
        document.removeEventListener('dragover', _utils__WEBPACK_IMPORTED_MODULE_2__["onDocumentDragOver"]);
        document.removeEventListener('drop', this.onDocumentDrop);
      }
      if (this.fileInputEl != null) {
        this.fileInputEl.removeEventListener('click', this.onInputElementClick, false);
      }
      window.removeEventListener('focus', this.onFileDialogCancel, false);
    }
  }, {
    key: 'composeHandlers',
    value: function composeHandlers(handler) {
      if (this.props.disabled) {
        return null;
      }

      return handler;
    }
  }, {
    key: 'onDocumentDrop',
    value: function onDocumentDrop(evt) {
      if (this.node && this.node.contains(evt.target)) {
        // if we intercepted an event for our instance, let it propagate down to the instance's onDrop handler
        return;
      }
      evt.preventDefault();
      this.dragTargets = [];
    }
  }, {
    key: 'onDragStart',
    value: function onDragStart(evt) {
      if (this.props.onDragStart) {
        this.props.onDragStart.call(this, evt);
      }
    }
  }, {
    key: 'onDragEnter',
    value: function onDragEnter(evt) {
      var _this2 = this;

      evt.preventDefault();

      // Count the dropzone and any children that are entered.
      if (this.dragTargets.indexOf(evt.target) === -1) {
        this.dragTargets.push(evt.target);
      }

      evt.persist();

      Promise.resolve(this.props.getDataTransferItems(evt)).then(function (draggedFiles) {
        _this2.setState({
          isDragActive: true, // Do not rely on files for the drag state. It doesn't work in Safari.
          draggedFiles: draggedFiles
        });
      });
      if (this.props.onDragEnter) {
        this.props.onDragEnter.call(this, evt);
      }
    }
  }, {
    key: 'onDragOver',
    value: function onDragOver(evt) {
      // eslint-disable-line class-methods-use-this
      evt.preventDefault();
      evt.stopPropagation();
      try {
        // The file dialog on Chrome allows users to drag files from the dialog onto
        // the dropzone, causing the browser the crash when the file dialog is closed.
        // A drop effect of 'none' prevents the file from being dropped
        evt.dataTransfer.dropEffect = this.isFileDialogActive ? 'none' : 'copy'; // eslint-disable-line no-param-reassign
      } catch (err) {
        // continue regardless of error
      }

      if (this.props.onDragOver) {
        this.props.onDragOver.call(this, evt);
      }
      return false;
    }
  }, {
    key: 'onDragLeave',
    value: function onDragLeave(evt) {
      var _this3 = this;

      evt.preventDefault();

      // Only deactivate once the dropzone and all children have been left.
      this.dragTargets = this.dragTargets.filter(function (el) {
        return el !== evt.target && _this3.node.contains(el);
      });
      if (this.dragTargets.length > 0) {
        return;
      }

      // Clear dragging files state
      this.setState({
        isDragActive: false,
        draggedFiles: []
      });

      if (this.props.onDragLeave) {
        this.props.onDragLeave.call(this, evt);
      }
    }
  }, {
    key: 'onDrop',
    value: function onDrop(evt) {
      var _this4 = this;

      var _props = this.props,
          onDrop = _props.onDrop,
          onDropAccepted = _props.onDropAccepted,
          onDropRejected = _props.onDropRejected,
          multiple = _props.multiple,
          disablePreview = _props.disablePreview,
          accept = _props.accept,
          getDataTransferItems = _props.getDataTransferItems;

      // Stop default browser behavior

      evt.preventDefault();

      // Persist event for later usage
      evt.persist();

      // Reset the counter along with the drag on a drop.
      this.dragTargets = [];
      this.isFileDialogActive = false;

      // Clear files value
      this.draggedFiles = null;

      // Reset drag state
      this.setState({
        isDragActive: false,
        draggedFiles: []
      });

      Promise.resolve(getDataTransferItems(evt)).then(function (fileList) {
        var acceptedFiles = [];
        var rejectedFiles = [];

        fileList.forEach(function (file) {
          if (!disablePreview) {
            try {
              file.preview = window.URL.createObjectURL(file); // eslint-disable-line no-param-reassign
            } catch (err) {
              if (true) {
                console.error('Failed to generate preview for file', file, err); // eslint-disable-line no-console
              }
            }
          }

          if (Object(_utils__WEBPACK_IMPORTED_MODULE_2__["fileAccepted"])(file, accept) && Object(_utils__WEBPACK_IMPORTED_MODULE_2__["fileMatchSize"])(file, _this4.props.maxSize, _this4.props.minSize)) {
            acceptedFiles.push(file);
          } else {
            rejectedFiles.push(file);
          }
        });

        if (!multiple && acceptedFiles.length > 1) {
          // if not in multi mode add any extra accepted files to rejected.
          // This will allow end users to easily ignore a multi file drop in "single" mode.
          rejectedFiles.push.apply(rejectedFiles, _toConsumableArray(acceptedFiles.splice(0)));
        }

        if (onDrop) {
          onDrop.call(_this4, acceptedFiles, rejectedFiles, evt);
        }

        if (rejectedFiles.length > 0 && onDropRejected) {
          onDropRejected.call(_this4, rejectedFiles, evt);
        }

        if (acceptedFiles.length > 0 && onDropAccepted) {
          onDropAccepted.call(_this4, acceptedFiles, evt);
        }

        // Update `acceptedFiles` and `rejectedFiles` state
        // This will make children render functions receive the appropriate
        // values
        _this4.setState({ acceptedFiles: acceptedFiles, rejectedFiles: rejectedFiles });
      });
    }
  }, {
    key: 'onClick',
    value: function onClick(evt) {
      var _props2 = this.props,
          onClick = _props2.onClick,
          disableClick = _props2.disableClick;

      if (!disableClick) {
        evt.stopPropagation();

        if (onClick) {
          onClick.call(this, evt);
        }

        // in IE11/Edge the file-browser dialog is blocking, ensure this is behind setTimeout
        // this is so react can handle state changes in the onClick prop above above
        // see: https://github.com/react-dropzone/react-dropzone/issues/450
        if (Object(_utils__WEBPACK_IMPORTED_MODULE_2__["isIeOrEdge"])()) {
          setTimeout(this.open.bind(this), 0);
        } else {
          this.open();
        }
      }
    }
  }, {
    key: 'onInputElementClick',
    value: function onInputElementClick(evt) {
      evt.stopPropagation();
      if (this.props.inputProps && this.props.inputProps.onClick) {
        this.props.inputProps.onClick();
      }
    }
  }, {
    key: 'onFileDialogCancel',
    value: function onFileDialogCancel() {
      var _this5 = this;

      // timeout will not recognize context of this method
      var onFileDialogCancel = this.props.onFileDialogCancel;
      // execute the timeout only if the FileDialog is opened in the browser

      if (this.isFileDialogActive) {
        setTimeout(function () {
          if (_this5.fileInputEl != null) {
            // Returns an object as FileList
            var files = _this5.fileInputEl.files;


            if (!files.length) {
              _this5.isFileDialogActive = false;
            }
          }

          if (typeof onFileDialogCancel === 'function') {
            onFileDialogCancel();
          }
        }, 300);
      }
    }
  }, {
    key: 'setRef',
    value: function setRef(ref) {
      this.node = ref;
    }
  }, {
    key: 'setRefs',
    value: function setRefs(ref) {
      this.fileInputEl = ref;
    }
    /**
     * Open system file upload dialog.
     *
     * @public
     */

  }, {
    key: 'open',
    value: function open() {
      this.isFileDialogActive = true;
      this.fileInputEl.value = null;
      this.fileInputEl.click();
    }
  }, {
    key: 'render',
    value: function render() {
      var _props3 = this.props,
          accept = _props3.accept,
          acceptClassName = _props3.acceptClassName,
          activeClassName = _props3.activeClassName,
          children = _props3.children,
          disabled = _props3.disabled,
          disabledClassName = _props3.disabledClassName,
          inputProps = _props3.inputProps,
          multiple = _props3.multiple,
          name = _props3.name,
          rejectClassName = _props3.rejectClassName,
          rest = _objectWithoutProperties(_props3, ['accept', 'acceptClassName', 'activeClassName', 'children', 'disabled', 'disabledClassName', 'inputProps', 'multiple', 'name', 'rejectClassName']);

      var acceptStyle = rest.acceptStyle,
          activeStyle = rest.activeStyle,
          _rest$className = rest.className,
          className = _rest$className === undefined ? '' : _rest$className,
          disabledStyle = rest.disabledStyle,
          rejectStyle = rest.rejectStyle,
          style = rest.style,
          props = _objectWithoutProperties(rest, ['acceptStyle', 'activeStyle', 'className', 'disabledStyle', 'rejectStyle', 'style']);

      var _state = this.state,
          isDragActive = _state.isDragActive,
          draggedFiles = _state.draggedFiles;

      var filesCount = draggedFiles.length;
      var isMultipleAllowed = multiple || filesCount <= 1;
      var isDragAccept = filesCount > 0 && Object(_utils__WEBPACK_IMPORTED_MODULE_2__["allFilesAccepted"])(draggedFiles, this.props.accept);
      var isDragReject = filesCount > 0 && (!isDragAccept || !isMultipleAllowed);
      var noStyles = !className && !style && !activeStyle && !acceptStyle && !rejectStyle && !disabledStyle;

      if (isDragActive && activeClassName) {
        className += ' ' + activeClassName;
      }
      if (isDragAccept && acceptClassName) {
        className += ' ' + acceptClassName;
      }
      if (isDragReject && rejectClassName) {
        className += ' ' + rejectClassName;
      }
      if (disabled && disabledClassName) {
        className += ' ' + disabledClassName;
      }

      if (noStyles) {
        style = _utils_styles__WEBPACK_IMPORTED_MODULE_3__["default"].default;
        activeStyle = _utils_styles__WEBPACK_IMPORTED_MODULE_3__["default"].active;
        acceptStyle = _utils_styles__WEBPACK_IMPORTED_MODULE_3__["default"].active;
        rejectStyle = _utils_styles__WEBPACK_IMPORTED_MODULE_3__["default"].rejected;
        disabledStyle = _utils_styles__WEBPACK_IMPORTED_MODULE_3__["default"].disabled;
      }

      var appliedStyle = _extends({ position: 'relative' }, style);
      if (activeStyle && isDragActive) {
        appliedStyle = _extends({}, appliedStyle, activeStyle);
      }
      if (acceptStyle && isDragAccept) {
        appliedStyle = _extends({}, appliedStyle, acceptStyle);
      }
      if (rejectStyle && isDragReject) {
        appliedStyle = _extends({}, appliedStyle, rejectStyle);
      }
      if (disabledStyle && disabled) {
        appliedStyle = _extends({}, appliedStyle, disabledStyle);
      }

      var inputAttributes = {
        accept: accept,
        disabled: disabled,
        type: 'file',
        style: _extends({
          position: 'absolute',
          top: 0,
          right: 0,
          bottom: 0,
          left: 0,
          opacity: 0.00001,
          pointerEvents: 'none'
        }, inputProps.style),
        multiple: _utils__WEBPACK_IMPORTED_MODULE_2__["supportMultiple"] && multiple,
        ref: this.setRefs,
        onChange: this.onDrop,
        autoComplete: 'off'
      };

      if (name && name.length) {
        inputAttributes.name = name;
      }

      // Destructure custom props away from props used for the div element
      /* eslint-disable no-unused-vars */

      var acceptedFiles = props.acceptedFiles,
          preventDropOnDocument = props.preventDropOnDocument,
          disablePreview = props.disablePreview,
          disableClick = props.disableClick,
          onDropAccepted = props.onDropAccepted,
          onDropRejected = props.onDropRejected,
          onFileDialogCancel = props.onFileDialogCancel,
          maxSize = props.maxSize,
          minSize = props.minSize,
          getDataTransferItems = props.getDataTransferItems,
          divProps = _objectWithoutProperties(props, ['acceptedFiles', 'preventDropOnDocument', 'disablePreview', 'disableClick', 'onDropAccepted', 'onDropRejected', 'onFileDialogCancel', 'maxSize', 'minSize', 'getDataTransferItems']);
      /* eslint-enable no-unused-vars */

      /* eslint-disable jsx-a11y/no-static-element-interactions */
      /* eslint-disable jsx-a11y/click-events-have-key-events */


      return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(
        'div',
        _extends({
          className: className,
          style: appliedStyle
        }, divProps /* expand user provided props first so event handlers are never overridden */
        , {
          onClick: this.composeHandlers(this.onClick),
          onDragStart: this.composeHandlers(this.onDragStart),
          onDragEnter: this.composeHandlers(this.onDragEnter),
          onDragOver: this.composeHandlers(this.onDragOver),
          onDragLeave: this.composeHandlers(this.onDragLeave),
          onDrop: this.composeHandlers(this.onDrop),
          ref: this.setRef,
          'aria-disabled': disabled
        }),
        this.renderChildren(children, isDragActive, isDragAccept, isDragReject),
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement('input', _extends({}, inputProps /* expand user provided inputProps first so inputAttributes override them */
        , inputAttributes))
      );
    }
  }]);

  return Dropzone;
}(react__WEBPACK_IMPORTED_MODULE_0___default.a.Component);

/* harmony default export */ __webpack_exports__["default"] = (Dropzone);

Dropzone.propTypes = {
  /**
   * Allow specific types of files. See https://github.com/okonet/attr-accept for more information.
   * Keep in mind that mime type determination is not reliable across platforms. CSV files,
   * for example, are reported as text/plain under macOS but as application/vnd.ms-excel under
   * Windows. In some cases there might not be a mime type set at all.
   * See: https://github.com/react-dropzone/react-dropzone/issues/276
   */
  accept: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.arrayOf(prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.string)]),

  /**
   * Contents of the dropzone
   */
  children: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.node, prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.func]),

  /**
   * Disallow clicking on the dropzone container to open file dialog
   */
  disableClick: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.bool,

  /**
   * Enable/disable the dropzone entirely
   */
  disabled: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.bool,

  /**
   * Enable/disable preview generation
   */
  disablePreview: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.bool,

  /**
   * If false, allow dropped items to take over the current browser window
   */
  preventDropOnDocument: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.bool,

  /**
   * Pass additional attributes to the `<input type="file"/>` tag
   */
  inputProps: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.object,

  /**
   * Allow dropping multiple files
   */
  multiple: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.bool,

  /**
   * `name` attribute for the input tag
   */
  name: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.string,

  /**
   * Maximum file size (in bytes)
   */
  maxSize: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.number,

  /**
   * Minimum file size (in bytes)
   */
  minSize: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.number,

  /**
   * className
   */
  className: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.string,

  /**
   * className to apply when drag is active
   */
  activeClassName: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.string,

  /**
   * className to apply when drop will be accepted
   */
  acceptClassName: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.string,

  /**
   * className to apply when drop will be rejected
   */
  rejectClassName: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.string,

  /**
   * className to apply when dropzone is disabled
   */
  disabledClassName: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.string,

  /**
   * CSS styles to apply
   */
  style: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.object,

  /**
   * CSS styles to apply when drag is active
   */
  activeStyle: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.object,

  /**
   * CSS styles to apply when drop will be accepted
   */
  acceptStyle: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.object,

  /**
   * CSS styles to apply when drop will be rejected
   */
  rejectStyle: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.object,

  /**
   * CSS styles to apply when dropzone is disabled
   */
  disabledStyle: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.object,

  /**
   * getDataTransferItems handler
   * @param {Event} event
   * @returns {Array} array of File objects
   */
  getDataTransferItems: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.func,

  /**
   * onClick callback
   * @param {Event} event
   */
  onClick: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.func,

  /**
   * onDrop callback
   */
  onDrop: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.func,

  /**
   * onDropAccepted callback
   */
  onDropAccepted: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.func,

  /**
   * onDropRejected callback
   */
  onDropRejected: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.func,

  /**
   * onDragStart callback
   */
  onDragStart: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.func,

  /**
   * onDragEnter callback
   */
  onDragEnter: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.func,

  /**
   * onDragOver callback
   */
  onDragOver: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.func,

  /**
   * onDragLeave callback
   */
  onDragLeave: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.func,

  /**
   * Provide a callback on clicking the cancel button of the file dialog
   */
  onFileDialogCancel: prop_types__WEBPACK_IMPORTED_MODULE_1___default.a.func
};

Dropzone.defaultProps = {
  preventDropOnDocument: true,
  disabled: false,
  disablePreview: false,
  disableClick: false,
  inputProps: {},
  multiple: true,
  maxSize: Infinity,
  minSize: 0,
  getDataTransferItems: _utils__WEBPACK_IMPORTED_MODULE_2__["getDataTransferItems"]
};

/***/ }),

/***/ "z/AG":
/*!****************************************************************!*\
  !*** ./node_modules/@jupyterlab/apputils/lib/clientsession.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const coreutils_2 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const coreutils_3 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const React = __importStar(__webpack_require__(/*! react */ "q1tI"));
const dialog_1 = __webpack_require__(/*! ./dialog */ "DZkP");
/**
 * The default implementation of client session object.
 */
class ClientSession {
    /**
     * Construct a new client session.
     */
    constructor(options) {
        this._path = '';
        this._name = '';
        this._type = '';
        this._prevKernelName = '';
        this._isDisposed = false;
        this._session = null;
        this._ready = new coreutils_3.PromiseDelegate();
        this._initializing = false;
        this._isReady = false;
        this._terminated = new signaling_1.Signal(this);
        this._kernelChanged = new signaling_1.Signal(this);
        this._statusChanged = new signaling_1.Signal(this);
        this._iopubMessage = new signaling_1.Signal(this);
        this._unhandledMessage = new signaling_1.Signal(this);
        this._propertyChanged = new signaling_1.Signal(this);
        this._dialog = null;
        this._busyDisposable = null;
        this.manager = options.manager;
        this._path = options.path || coreutils_2.UUID.uuid4();
        this._type = options.type || '';
        this._name = options.name || '';
        this._setBusy = options.setBusy;
        this._kernelPreference = options.kernelPreference || {};
    }
    /**
     * A signal emitted when the session is shut down.
     */
    get terminated() {
        return this._terminated;
    }
    /**
     * A signal emitted when the kernel changes.
     */
    get kernelChanged() {
        return this._kernelChanged;
    }
    /**
     * A signal emitted when the status changes.
     */
    get statusChanged() {
        return this._statusChanged;
    }
    /**
     * A signal emitted for iopub kernel messages.
     */
    get iopubMessage() {
        return this._iopubMessage;
    }
    /**
     * A signal emitted for an unhandled kernel message.
     */
    get unhandledMessage() {
        return this._unhandledMessage;
    }
    /**
     * A signal emitted when a session property changes.
     */
    get propertyChanged() {
        return this._propertyChanged;
    }
    /**
     * The current kernel of the session.
     */
    get kernel() {
        return this._session ? this._session.kernel : null;
    }
    /**
     * The current path of the session.
     */
    get path() {
        return this._path;
    }
    /**
     * The current name of the session.
     */
    get name() {
        return this._name;
    }
    /**
     * The type of the client session.
     */
    get type() {
        return this._type;
    }
    /**
     * The kernel preference of the session.
     */
    get kernelPreference() {
        return this._kernelPreference;
    }
    set kernelPreference(value) {
        this._kernelPreference = value;
    }
    /**
     * The current status of the session.
     */
    get status() {
        if (!this.isReady) {
            return 'starting';
        }
        return this._session ? this._session.status : 'dead';
    }
    /**
     * Whether the session is ready.
     */
    get isReady() {
        return this._isReady;
    }
    /**
     * A promise that is fulfilled when the session is ready.
     */
    get ready() {
        return this._ready.promise;
    }
    /**
     * The display name of the current kernel.
     */
    get kernelDisplayName() {
        let kernel = this.kernel;
        if (!kernel) {
            return 'No Kernel!';
        }
        let specs = this.manager.specs;
        if (!specs) {
            return 'Unknown!';
        }
        let spec = specs.kernelspecs[kernel.name];
        return spec ? spec.display_name : kernel.name;
    }
    /**
     * Test whether the context is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources held by the context.
     */
    dispose() {
        if (this._isDisposed) {
            return;
        }
        this._isDisposed = true;
        if (this._session) {
            this._session = null;
        }
        if (this._dialog) {
            this._dialog.dispose();
        }
        signaling_1.Signal.clearData(this);
    }
    /**
     * Change the current kernel associated with the document.
     */
    changeKernel(options) {
        return this.initialize().then(() => {
            if (this.isDisposed) {
                return Promise.reject('Disposed');
            }
            return this._changeKernel(options);
        });
    }
    /**
     * Select a kernel for the session.
     */
    selectKernel() {
        return this.initialize().then(() => {
            if (this.isDisposed) {
                return Promise.reject('Disposed');
            }
            return this._selectKernel(true);
        });
    }
    /**
     * Kill the kernel and shutdown the session.
     *
     * @returns A promise that resolves when the session is shut down.
     */
    shutdown() {
        const session = this._session;
        if (this.isDisposed || !session) {
            return Promise.resolve();
        }
        this._session = null;
        return session.shutdown();
    }
    /**
     * Restart the session.
     *
     * @returns A promise that resolves with whether the kernel has restarted.
     *
     * #### Notes
     * If there is a running kernel, present a dialog.
     * If there is no kernel, we start a kernel with the last run
     * kernel name and resolves with `true`.
     */
    restart() {
        return this.initialize().then(() => {
            if (this.isDisposed) {
                return Promise.reject('session already disposed');
            }
            let kernel = this.kernel;
            if (!kernel) {
                if (this._prevKernelName) {
                    return this.changeKernel({ name: this._prevKernelName }).then(() => true);
                }
                // Bail if there is no previous kernel to start.
                return Promise.reject('No kernel to restart');
            }
            return ClientSession.restartKernel(kernel);
        });
    }
    /**
     * Change the session path.
     *
     * @param path - The new session path.
     *
     * @returns A promise that resolves when the session has renamed.
     *
     * #### Notes
     * This uses the Jupyter REST API, and the response is validated.
     * The promise is fulfilled on a valid response and rejected otherwise.
     */
    setPath(path) {
        if (this.isDisposed || this._path === path) {
            return Promise.resolve();
        }
        this._path = path;
        if (this._session) {
            return this._session.setPath(path);
        }
        this._propertyChanged.emit('path');
        return Promise.resolve();
    }
    /**
     * Change the session name.
     */
    setName(name) {
        if (this.isDisposed || this._name === name) {
            return Promise.resolve();
        }
        this._name = name;
        if (this._session) {
            return this._session.setName(name);
        }
        this._propertyChanged.emit('name');
        return Promise.resolve();
    }
    /**
     * Change the session type.
     */
    setType(type) {
        if (this.isDisposed || this._type === type) {
            return Promise.resolve();
        }
        this._type = type;
        if (this._session) {
            return this._session.setType(name);
        }
        this._propertyChanged.emit('type');
        return Promise.resolve();
    }
    /**
     * Initialize the session.
     *
     * #### Notes
     * If a server session exists on the current path, we will connect to it.
     * If preferences include disabling `canStart` or `shouldStart`, no
     * server session will be started.
     * If a kernel id is given, we attempt to start a session with that id.
     * If a default kernel is available, we connect to it.
     * Otherwise we ask the user to select a kernel.
     */
    initialize() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this._initializing || this._isReady) {
                return this._ready.promise;
            }
            this._initializing = true;
            let manager = this.manager;
            yield manager.ready;
            let model = algorithm_1.find(manager.running(), item => {
                return item.path === this._path;
            });
            if (model) {
                try {
                    let session = manager.connectTo(model);
                    this._handleNewSession(session);
                }
                catch (err) {
                    this._handleSessionError(err);
                }
            }
            yield this._startIfNecessary();
            this._isReady = true;
            this._ready.resolve(undefined);
        });
    }
    /**
     * Start the session if necessary.
     */
    _startIfNecessary() {
        let preference = this.kernelPreference;
        if (this.isDisposed ||
            this.kernel ||
            preference.shouldStart === false ||
            preference.canStart === false) {
            return Promise.resolve();
        }
        // Try to use an existing kernel.
        if (preference.id) {
            return this._changeKernel({ id: preference.id })
                .then(() => undefined)
                .catch(() => this._selectKernel(false));
        }
        let name = ClientSession.getDefaultKernel({
            specs: this.manager.specs,
            sessions: this.manager.running(),
            preference
        });
        if (name) {
            return this._changeKernel({ name })
                .then(() => undefined)
                .catch(() => this._selectKernel(false));
        }
        return this._selectKernel(false);
    }
    /**
     * Change the kernel.
     */
    _changeKernel(options) {
        if (this.isDisposed) {
            return Promise.reject('Disposed');
        }
        let session = this._session;
        if (session) {
            return session.changeKernel(options);
        }
        else {
            return this._startSession(options);
        }
    }
    /**
     * Select a kernel.
     *
     * @param cancelable: whether the dialog should have a cancel button.
     */
    _selectKernel(cancelable) {
        if (this.isDisposed) {
            return Promise.resolve();
        }
        const buttons = cancelable
            ? [dialog_1.Dialog.cancelButton(), dialog_1.Dialog.okButton({ label: 'SELECT' })]
            : [dialog_1.Dialog.okButton({ label: 'SELECT' })];
        let dialog = (this._dialog = new dialog_1.Dialog({
            title: 'Select Kernel',
            body: new Private.KernelSelector(this),
            buttons
        }));
        return dialog
            .launch()
            .then(result => {
            if (this.isDisposed || !result.button.accept) {
                return;
            }
            let model = result.value;
            if (model === null && this._session) {
                return this.shutdown().then(() => {
                    this._kernelChanged.emit({ oldValue: null, newValue: null });
                });
            }
            if (model) {
                return this._changeKernel(model).then(() => undefined);
            }
        })
            .then(() => {
            this._dialog = null;
        });
    }
    /**
     * Start a session and set up its signals.
     */
    _startSession(model) {
        if (this.isDisposed) {
            return Promise.reject('Session is disposed.');
        }
        return this.manager
            .startNew({
            path: this._path,
            type: this._type,
            name: this._name,
            kernelName: model ? model.name : undefined,
            kernelId: model ? model.id : undefined
        })
            .then(session => {
            return this._handleNewSession(session);
        })
            .catch(err => {
            this._handleSessionError(err);
            return Promise.reject(err);
        });
    }
    /**
     * Handle a new session object.
     */
    _handleNewSession(session) {
        if (this.isDisposed) {
            throw Error('Disposed');
        }
        if (this._session) {
            this._session.dispose();
        }
        this._session = session;
        if (session.path !== this._path) {
            this._path = session.path;
            this._propertyChanged.emit('path');
        }
        if (session.name !== this._name) {
            this._name = session.name;
            this._propertyChanged.emit('name');
        }
        if (session.type !== this._type) {
            this._type = session.type;
            this._propertyChanged.emit('type');
        }
        session.terminated.connect(this._onTerminated, this);
        session.propertyChanged.connect(this._onPropertyChanged, this);
        session.kernelChanged.connect(this._onKernelChanged, this);
        session.statusChanged.connect(this._onStatusChanged, this);
        session.iopubMessage.connect(this._onIopubMessage, this);
        session.unhandledMessage.connect(this._onUnhandledMessage, this);
        this._prevKernelName = session.kernel.name;
        // The session kernel was disposed above when the session was disposed, so
        // the oldValue should be null.
        this._kernelChanged.emit({ oldValue: null, newValue: session.kernel });
        return session.kernel;
    }
    /**
     * Handle an error in session startup.
     */
    _handleSessionError(err) {
        return err.response
            .text()
            .then(text => {
            let message = err.message;
            try {
                message = JSON.parse(text)['traceback'];
            }
            catch (err) {
                // no-op
            }
            let dialog = (this._dialog = new dialog_1.Dialog({
                title: 'Error Starting Kernel',
                body: React.createElement("pre", null, message),
                buttons: [dialog_1.Dialog.okButton()]
            }));
            return dialog.launch();
        })
            .then(() => {
            this._dialog = null;
        });
    }
    /**
     * Handle a session termination.
     */
    _onTerminated() {
        let kernel = this.kernel;
        if (this._session) {
            this._session.dispose();
        }
        this._session = null;
        this._terminated.emit(undefined);
        if (kernel) {
            this._kernelChanged.emit({ oldValue: null, newValue: null });
        }
    }
    /**
     * Handle a change to a session property.
     */
    _onPropertyChanged(sender, property) {
        switch (property) {
            case 'path':
                this._path = sender.path;
                break;
            case 'name':
                this._name = sender.name;
                break;
            default:
                this._type = sender.type;
                break;
        }
        this._propertyChanged.emit(property);
    }
    /**
     * Handle a change to the kernel.
     */
    _onKernelChanged(sender, args) {
        this._kernelChanged.emit(args);
    }
    /**
     * Handle a change to the session status.
     */
    _onStatusChanged() {
        // Set that this kernel is busy, if we haven't already
        // If we have already, and now we aren't busy, dispose
        // of the busy disposable.
        if (this._setBusy) {
            if (this.status === 'busy') {
                if (!this._busyDisposable) {
                    this._busyDisposable = this._setBusy();
                }
            }
            else {
                if (this._busyDisposable) {
                    this._busyDisposable.dispose();
                    this._busyDisposable = null;
                }
            }
        }
        this._statusChanged.emit(this.status);
    }
    /**
     * Handle an iopub message.
     */
    _onIopubMessage(sender, message) {
        this._iopubMessage.emit(message);
    }
    /**
     * Handle an unhandled message.
     */
    _onUnhandledMessage(sender, message) {
        this._unhandledMessage.emit(message);
    }
}
exports.ClientSession = ClientSession;
/**
 * A namespace for `ClientSession` statics.
 */
(function (ClientSession) {
    /**
     * Restart a kernel if the user accepts the risk.
     *
     * Returns a promise resolving with whether the kernel was restarted.
     */
    function restartKernel(kernel) {
        let restartBtn = dialog_1.Dialog.warnButton({ label: 'RESTART ' });
        return dialog_1.showDialog({
            title: 'Restart Kernel?',
            body: 'Do you want to restart the current kernel? All variables will be lost.',
            buttons: [dialog_1.Dialog.cancelButton(), restartBtn]
        }).then(result => {
            if (kernel.isDisposed) {
                return Promise.resolve(false);
            }
            if (result.button.accept) {
                return kernel.restart().then(() => {
                    return true;
                });
            }
            return false;
        });
    }
    ClientSession.restartKernel = restartKernel;
    /**
     * Get the default kernel name given select options.
     */
    function getDefaultKernel(options) {
        return Private.getDefaultKernel(options);
    }
    ClientSession.getDefaultKernel = getDefaultKernel;
    /**
     * Populate a kernel dropdown list.
     *
     * @param node - The node to populate.
     *
     * @param options - The options used to populate the kernels.
     *
     * #### Notes
     * Populates the list with separated sections:
     *   - Kernels matching the preferred language (display names).
     *   - "None" signifying no kernel.
     *   - The remaining kernels.
     *   - Sessions matching the preferred language (file names).
     *   - The remaining sessions.
     * If no preferred language is given or no kernels are found using
     * the preferred language, the default kernel is used in the first
     * section.  Kernels are sorted by display name.  Sessions display the
     * base name of the file with an ellipsis overflow and a tooltip with
     * the explicit session information.
     */
    function populateKernelSelect(node, options) {
        return Private.populateKernelSelect(node, options);
    }
    ClientSession.populateKernelSelect = populateKernelSelect;
})(ClientSession = exports.ClientSession || (exports.ClientSession = {}));
/**
 * The namespace for module private data.
 */
var Private;
(function (Private) {
    /**
     * A widget that provides a kernel selection.
     */
    class KernelSelector extends widgets_1.Widget {
        /**
         * Create a new kernel selector widget.
         */
        constructor(session) {
            super({ node: createSelectorNode(session) });
        }
        /**
         * Get the value of the kernel selector widget.
         */
        getValue() {
            let selector = this.node.querySelector('select');
            return JSON.parse(selector.value);
        }
    }
    Private.KernelSelector = KernelSelector;
    /**
     * Create a node for a kernel selector widget.
     */
    function createSelectorNode(session) {
        // Create the dialog body.
        let body = document.createElement('div');
        let text = document.createElement('label');
        text.innerHTML = `Select kernel for: "${session.name}"`;
        body.appendChild(text);
        let options = getKernelSearch(session);
        let selector = document.createElement('select');
        ClientSession.populateKernelSelect(selector, options);
        body.appendChild(selector);
        return body;
    }
    /**
     * Get the default kernel name given select options.
     */
    function getDefaultKernel(options) {
        let { specs, preference } = options;
        let { name, language, shouldStart, canStart, autoStartDefault } = preference;
        if (!specs || shouldStart === false || canStart === false) {
            return null;
        }
        let defaultName = autoStartDefault ? specs.default : null;
        if (!name && !language) {
            return defaultName;
        }
        // Look for an exact match of a spec name.
        for (let specName in specs.kernelspecs) {
            if (specName === name) {
                return name;
            }
        }
        // Bail if there is no language.
        if (!language) {
            return defaultName;
        }
        // Check for a single kernel matching the language.
        let matches = [];
        for (let specName in specs.kernelspecs) {
            let kernelLanguage = specs.kernelspecs[specName].language;
            if (language === kernelLanguage) {
                matches.push(specName);
            }
        }
        if (matches.length === 1) {
            let specName = matches[0];
            console.log('No exact match found for ' +
                specName +
                ', using kernel ' +
                specName +
                ' that matches ' +
                'language=' +
                language);
            return specName;
        }
        // No matches found.
        return defaultName;
    }
    Private.getDefaultKernel = getDefaultKernel;
    /**
     * Populate a kernel select node for the session.
     */
    function populateKernelSelect(node, options) {
        while (node.firstChild) {
            node.removeChild(node.firstChild);
        }
        let { preference, sessions, specs } = options;
        let { name, id, language, canStart, shouldStart } = preference;
        if (!specs || canStart === false) {
            node.appendChild(optionForNone());
            node.value = 'null';
            node.disabled = true;
            return;
        }
        node.disabled = false;
        // Create mappings of display names and languages for kernel name.
        let displayNames = Object.create(null);
        let languages = Object.create(null);
        for (let name in specs.kernelspecs) {
            let spec = specs.kernelspecs[name];
            displayNames[name] = spec.display_name;
            languages[name] = spec.language;
        }
        // Handle a kernel by name.
        let names = [];
        if (name && name in specs.kernelspecs) {
            names.push(name);
        }
        // Then look by language.
        if (language) {
            for (let specName in specs.kernelspecs) {
                if (name !== specName && languages[specName] === language) {
                    names.push(specName);
                }
            }
        }
        // Use the default kernel if no kernels were found.
        if (!names.length) {
            names.push(specs.default);
        }
        // Handle a preferred kernels in order of display name.
        let preferred = document.createElement('optgroup');
        preferred.label = 'Start Preferred Kernel';
        names.sort((a, b) => displayNames[a].localeCompare(displayNames[b]));
        for (let name of names) {
            preferred.appendChild(optionForName(name, displayNames[name]));
        }
        if (preferred.firstChild) {
            node.appendChild(preferred);
        }
        // Add an option for no kernel
        node.appendChild(optionForNone());
        let other = document.createElement('optgroup');
        other.label = 'Start Other Kernel';
        // Add the rest of the kernel names in alphabetical order.
        let otherNames = [];
        for (let specName in specs.kernelspecs) {
            if (names.indexOf(specName) !== -1) {
                continue;
            }
            otherNames.push(specName);
        }
        otherNames.sort((a, b) => displayNames[a].localeCompare(displayNames[b]));
        for (let otherName of otherNames) {
            other.appendChild(optionForName(otherName, displayNames[otherName]));
        }
        // Add a separator option if there were any other names.
        if (otherNames.length) {
            node.appendChild(other);
        }
        // Handle the default value.
        if (shouldStart === false) {
            node.value = 'null';
        }
        else {
            node.selectedIndex = 0;
        }
        // Bail if there are no sessions.
        if (!sessions) {
            return;
        }
        // Add the sessions using the preferred language first.
        let matchingSessions = [];
        let otherSessions = [];
        algorithm_1.each(sessions, session => {
            if (language &&
                languages[session.kernel.name] === language &&
                session.kernel.id !== id) {
                matchingSessions.push(session);
            }
            else if (session.kernel.id !== id) {
                otherSessions.push(session);
            }
        });
        let matching = document.createElement('optgroup');
        matching.label = 'Use Kernel from Preferred Session';
        node.appendChild(matching);
        if (matchingSessions.length) {
            matchingSessions.sort((a, b) => {
                return a.path.localeCompare(b.path);
            });
            algorithm_1.each(matchingSessions, session => {
                let name = displayNames[session.kernel.name];
                matching.appendChild(optionForSession(session, name));
            });
        }
        let otherSessionsNode = document.createElement('optgroup');
        otherSessionsNode.label = 'Use Kernel from Other Session';
        node.appendChild(otherSessionsNode);
        if (otherSessions.length) {
            otherSessions.sort((a, b) => {
                return a.path.localeCompare(b.path);
            });
            algorithm_1.each(otherSessions, session => {
                let name = displayNames[session.kernel.name] || session.kernel.name;
                otherSessionsNode.appendChild(optionForSession(session, name));
            });
        }
    }
    Private.populateKernelSelect = populateKernelSelect;
    /**
     * Get the kernel search options given a client session and sesion manager.
     */
    function getKernelSearch(session) {
        return {
            specs: session.manager.specs,
            sessions: session.manager.running(),
            preference: session.kernelPreference
        };
    }
    /**
     * Create an option element for a kernel name.
     */
    function optionForName(name, displayName) {
        let option = document.createElement('option');
        option.text = displayName;
        option.value = JSON.stringify({ name });
        return option;
    }
    /**
     * Create an option for no kernel.
     */
    function optionForNone() {
        let group = document.createElement('optgroup');
        group.label = 'Use No Kernel';
        let option = document.createElement('option');
        option.text = 'No Kernel';
        option.value = 'null';
        group.appendChild(option);
        return group;
    }
    /**
     * Create an option element for a session.
     */
    function optionForSession(session, displayName) {
        let option = document.createElement('option');
        let sessionName = session.name || coreutils_1.PathExt.basename(session.path);
        option.text = sessionName;
        option.value = JSON.stringify({ id: session.kernel.id });
        option.title =
            `Path: ${session.path}\n` +
                `Name: ${sessionName}\n` +
                `Kernel Name: ${displayName}\n` +
                `Kernel Id: ${session.kernel.id}`;
        return option;
    }
})(Private || (Private = {}));


/***/ }),

/***/ "z1FC":
/*!*******************************************!*\
  !*** ./node_modules/moment/locale/tzl.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


// After the year there should be a slash and the amount of years since December 26, 1979 in Roman numerals.
// This is currently too difficult (maybe even impossible) to add.
var tzl = moment.defineLocale('tzl', {
    months : 'Januar_Fevraglh_Març_Avrïu_Mai_Gün_Julia_Guscht_Setemvar_Listopäts_Noemvar_Zecemvar'.split('_'),
    monthsShort : 'Jan_Fev_Mar_Avr_Mai_Gün_Jul_Gus_Set_Lis_Noe_Zec'.split('_'),
    weekdays : 'Súladi_Lúneçi_Maitzi_Márcuri_Xhúadi_Viénerçi_Sáturi'.split('_'),
    weekdaysShort : 'Súl_Lún_Mai_Már_Xhú_Vié_Sát'.split('_'),
    weekdaysMin : 'Sú_Lú_Ma_Má_Xh_Vi_Sá'.split('_'),
    longDateFormat : {
        LT : 'HH.mm',
        LTS : 'HH.mm.ss',
        L : 'DD.MM.YYYY',
        LL : 'D. MMMM [dallas] YYYY',
        LLL : 'D. MMMM [dallas] YYYY HH.mm',
        LLLL : 'dddd, [li] D. MMMM [dallas] YYYY HH.mm'
    },
    meridiemParse: /d\'o|d\'a/i,
    isPM : function (input) {
        return 'd\'o' === input.toLowerCase();
    },
    meridiem : function (hours, minutes, isLower) {
        if (hours > 11) {
            return isLower ? 'd\'o' : 'D\'O';
        } else {
            return isLower ? 'd\'a' : 'D\'A';
        }
    },
    calendar : {
        sameDay : '[oxhi à] LT',
        nextDay : '[demà à] LT',
        nextWeek : 'dddd [à] LT',
        lastDay : '[ieiri à] LT',
        lastWeek : '[sür el] dddd [lasteu à] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'osprei %s',
        past : 'ja%s',
        s : processRelativeTime,
        ss : processRelativeTime,
        m : processRelativeTime,
        mm : processRelativeTime,
        h : processRelativeTime,
        hh : processRelativeTime,
        d : processRelativeTime,
        dd : processRelativeTime,
        M : processRelativeTime,
        MM : processRelativeTime,
        y : processRelativeTime,
        yy : processRelativeTime
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

function processRelativeTime(number, withoutSuffix, key, isFuture) {
    var format = {
        's': ['viensas secunds', '\'iensas secunds'],
        'ss': [number + ' secunds', '' + number + ' secunds'],
        'm': ['\'n míut', '\'iens míut'],
        'mm': [number + ' míuts', '' + number + ' míuts'],
        'h': ['\'n þora', '\'iensa þora'],
        'hh': [number + ' þoras', '' + number + ' þoras'],
        'd': ['\'n ziua', '\'iensa ziua'],
        'dd': [number + ' ziuas', '' + number + ' ziuas'],
        'M': ['\'n mes', '\'iens mes'],
        'MM': [number + ' mesen', '' + number + ' mesen'],
        'y': ['\'n ar', '\'iens ar'],
        'yy': [number + ' ars', '' + number + ' ars']
    };
    return isFuture ? format[key][0] : (withoutSuffix ? format[key][0] : format[key][1]);
}

return tzl;

})));


/***/ }),

/***/ "z3Vd":
/*!*******************************************!*\
  !*** ./node_modules/moment/locale/tlh.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var numbersNouns = 'pagh_wa’_cha’_wej_loS_vagh_jav_Soch_chorgh_Hut'.split('_');

function translateFuture(output) {
    var time = output;
    time = (output.indexOf('jaj') !== -1) ?
    time.slice(0, -3) + 'leS' :
    (output.indexOf('jar') !== -1) ?
    time.slice(0, -3) + 'waQ' :
    (output.indexOf('DIS') !== -1) ?
    time.slice(0, -3) + 'nem' :
    time + ' pIq';
    return time;
}

function translatePast(output) {
    var time = output;
    time = (output.indexOf('jaj') !== -1) ?
    time.slice(0, -3) + 'Hu’' :
    (output.indexOf('jar') !== -1) ?
    time.slice(0, -3) + 'wen' :
    (output.indexOf('DIS') !== -1) ?
    time.slice(0, -3) + 'ben' :
    time + ' ret';
    return time;
}

function translate(number, withoutSuffix, string, isFuture) {
    var numberNoun = numberAsNoun(number);
    switch (string) {
        case 'ss':
            return numberNoun + ' lup';
        case 'mm':
            return numberNoun + ' tup';
        case 'hh':
            return numberNoun + ' rep';
        case 'dd':
            return numberNoun + ' jaj';
        case 'MM':
            return numberNoun + ' jar';
        case 'yy':
            return numberNoun + ' DIS';
    }
}

function numberAsNoun(number) {
    var hundred = Math.floor((number % 1000) / 100),
    ten = Math.floor((number % 100) / 10),
    one = number % 10,
    word = '';
    if (hundred > 0) {
        word += numbersNouns[hundred] + 'vatlh';
    }
    if (ten > 0) {
        word += ((word !== '') ? ' ' : '') + numbersNouns[ten] + 'maH';
    }
    if (one > 0) {
        word += ((word !== '') ? ' ' : '') + numbersNouns[one];
    }
    return (word === '') ? 'pagh' : word;
}

var tlh = moment.defineLocale('tlh', {
    months : 'tera’ jar wa’_tera’ jar cha’_tera’ jar wej_tera’ jar loS_tera’ jar vagh_tera’ jar jav_tera’ jar Soch_tera’ jar chorgh_tera’ jar Hut_tera’ jar wa’maH_tera’ jar wa’maH wa’_tera’ jar wa’maH cha’'.split('_'),
    monthsShort : 'jar wa’_jar cha’_jar wej_jar loS_jar vagh_jar jav_jar Soch_jar chorgh_jar Hut_jar wa’maH_jar wa’maH wa’_jar wa’maH cha’'.split('_'),
    monthsParseExact : true,
    weekdays : 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'),
    weekdaysShort : 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'),
    weekdaysMin : 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd, D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay: '[DaHjaj] LT',
        nextDay: '[wa’leS] LT',
        nextWeek: 'LLL',
        lastDay: '[wa’Hu’] LT',
        lastWeek: 'LLL',
        sameElse: 'L'
    },
    relativeTime : {
        future : translateFuture,
        past : translatePast,
        s : 'puS lup',
        ss : translate,
        m : 'wa’ tup',
        mm : translate,
        h : 'wa’ rep',
        hh : translate,
        d : 'wa’ jaj',
        dd : translate,
        M : 'wa’ jar',
        MM : translate,
        y : 'wa’ DIS',
        yy : translate
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});

return tlh;

})));


/***/ }),

/***/ "z6H5":
/*!*********************************************************!*\
  !*** ./node_modules/plotly.js/src/lib/get_graph_div.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/



/**
 * Allow referencing a graph DOM element either directly
 * or by its id string
 *
 * @param {HTMLDivElement|string} gd: a graph element or its id
 *
 * @returns {HTMLDivElement} the DOM element of the graph
 */
module.exports = function(gd) {
    var gdElement;

    if(typeof gd === 'string') {
        gdElement = document.getElementById(gd);

        if(gdElement === null) {
            throw new Error('No DOM element with id \'' + gd + '\' exists on the page.');
        }

        return gdElement;
    }
    else if(gd === null || gd === undefined) {
        throw new Error('DOM element provided is null or undefined');
    }

    return gd;  // otherwise assume that gd is a DOM element
};


/***/ }),

/***/ "z6eE":
/*!****************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/lib/search.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




var isNumeric = __webpack_require__(/*! fast-isnumeric */ "GbLo");
var loggers = __webpack_require__(/*! ./loggers */ "B+Rx");
var identity = __webpack_require__(/*! ./identity */ "Qhhf");

// don't trust floating point equality - fraction of bin size to call
// "on the line" and ensure that they go the right way specified by
// linelow
var roundingError = 1e-9;


/**
 * findBin - find the bin for val - note that it can return outside the
 * bin range any pos. or neg. integer for linear bins, or -1 or
 * bins.length-1 for explicit.
 * bins is either an object {start,size,end} or an array length #bins+1
 * bins can be either increasing or decreasing but must be monotonic
 * for linear bins, we can just calculate. For listed bins, run a binary
 * search linelow (truthy) says the bin boundary should be attributed to
 * the lower bin rather than the default upper bin
 */
exports.findBin = function(val, bins, linelow) {
    if(isNumeric(bins.start)) {
        return linelow ?
            Math.ceil((val - bins.start) / bins.size - roundingError) - 1 :
            Math.floor((val - bins.start) / bins.size + roundingError);
    }
    else {
        var n1 = 0;
        var n2 = bins.length;
        var c = 0;
        var binSize = (n2 > 1) ? (bins[n2 - 1] - bins[0]) / (n2 - 1) : 1;
        var n, test;
        if(binSize >= 0) {
            test = linelow ? lessThan : lessOrEqual;
        } else {
            test = linelow ? greaterOrEqual : greaterThan;
        }
        val += binSize * roundingError * (linelow ? -1 : 1) * (binSize >= 0 ? 1 : -1);
        // c is just to avoid infinite loops if there's an error
        while(n1 < n2 && c++ < 100) {
            n = Math.floor((n1 + n2) / 2);
            if(test(bins[n], val)) n1 = n + 1;
            else n2 = n;
        }
        if(c > 90) loggers.log('Long binary search...');
        return n1 - 1;
    }
};

function lessThan(a, b) { return a < b; }
function lessOrEqual(a, b) { return a <= b; }
function greaterThan(a, b) { return a > b; }
function greaterOrEqual(a, b) { return a >= b; }

exports.sorterAsc = function(a, b) { return a - b; };
exports.sorterDes = function(a, b) { return b - a; };

/**
 * find distinct values in an array, lumping together ones that appear to
 * just be off by a rounding error
 * return the distinct values and the minimum difference between any two
 */
exports.distinctVals = function(valsIn) {
    var vals = valsIn.slice();  // otherwise we sort the original array...
    vals.sort(exports.sorterAsc);

    var l = vals.length - 1;
    var minDiff = (vals[l] - vals[0]) || 1;
    var errDiff = minDiff / (l || 1) / 10000;
    var v2 = [vals[0]];

    for(var i = 0; i < l; i++) {
        // make sure values aren't just off by a rounding error
        if(vals[i + 1] > vals[i] + errDiff) {
            minDiff = Math.min(minDiff, vals[i + 1] - vals[i]);
            v2.push(vals[i + 1]);
        }
    }

    return {vals: v2, minDiff: minDiff};
};

/**
 * return the smallest element from (sorted) array arrayIn that's bigger than val,
 * or (reverse) the largest element smaller than val
 * used to find the best tick given the minimum (non-rounded) tick
 * particularly useful for date/time where things are not powers of 10
 * binary search is probably overkill here...
 */
exports.roundUp = function(val, arrayIn, reverse) {
    var low = 0;
    var high = arrayIn.length - 1;
    var mid;
    var c = 0;
    var dlow = reverse ? 0 : 1;
    var dhigh = reverse ? 1 : 0;
    var rounded = reverse ? Math.ceil : Math.floor;
    // c is just to avoid infinite loops if there's an error
    while(low < high && c++ < 100) {
        mid = rounded((low + high) / 2);
        if(arrayIn[mid] <= val) low = mid + dlow;
        else high = mid - dhigh;
    }
    return arrayIn[low];
};

/**
 * Tweak to Array.sort(sortFn) that improves performance for pre-sorted arrays
 *
 * Note that newer browsers (such as Chrome v70+) are starting to pick up
 * on pre-sorted arrays which may render the following optimization unnecessary
 * in the future.
 *
 * Motivation: sometimes we need to sort arrays but the input is likely to
 * already be sorted. Browsers don't seem to pick up on pre-sorted arrays,
 * and in fact Chrome is actually *slower* sorting pre-sorted arrays than purely
 * random arrays. FF is at least faster if the array is pre-sorted, but still
 * not as fast as it could be.
 * Here's how this plays out sorting a length-1e6 array:
 *
 * Calls to Sort FN  |  Chrome bare  |  FF bare  |  Chrome tweak  |  FF tweak
 *                   |  v68.0 Mac    |  v61.0 Mac|                |
 * ------------------+---------------+-----------+----------------+------------
 * ordered           |  30.4e6       |  10.1e6   |  1e6           |  1e6
 * reversed          |  29.4e6       |  9.9e6    |  1e6 + reverse |  1e6 + reverse
 * random            |  ~21e6        |  ~18.7e6  |  ~21e6         |  ~18.7e6
 *
 * So this is a substantial win for pre-sorted (ordered or exactly reversed)
 * arrays. Including this wrapper on an unsorted array adds a penalty that will
 * in general be only a few calls to the sort function. The only case this
 * penalty will be significant is if the array is mostly sorted but there are
 * a few unsorted items near the end, but the penalty is still at most N calls
 * out of (for N=1e6) ~20N total calls
 *
 * @param {Array} array: the array, to be sorted in place
 * @param {function} sortFn: As in Array.sort, function(a, b) that puts
 *     item a before item b if the return is negative, a after b if positive,
 *     and no change if zero.
 * @return {Array}: the original array, sorted in place.
 */
exports.sort = function(array, sortFn) {
    var notOrdered = 0;
    var notReversed = 0;
    for(var i = 1; i < array.length; i++) {
        var pairOrder = sortFn(array[i], array[i - 1]);
        if(pairOrder < 0) notOrdered = 1;
        else if(pairOrder > 0) notReversed = 1;
        if(notOrdered && notReversed) return array.sort(sortFn);
    }
    return notReversed ? array : array.reverse();
};

/**
 * find index in array 'arr' that minimizes 'fn'
 *
 * @param {array} arr : array where to search
 * @param {fn (optional)} fn : function to minimize,
 *   if not given, fn is the identity function
 * @return {integer}
 */
exports.findIndexOfMin = function(arr, fn) {
    fn = fn || identity;

    var min = Infinity;
    var ind;

    for(var i = 0; i < arr.length; i++) {
        var v = fn(arr[i]);
        if(v < min) {
            min = v;
            ind = i;
        }
    }
    return ind;
};


/***/ }),

/***/ "z71Z":
/*!*******************************************************!*\
  !*** ./node_modules/asn1.js/lib/asn1/decoders/der.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var inherits = __webpack_require__(/*! inherits */ "P7XM");

var asn1 = __webpack_require__(/*! ../../asn1 */ "f3pb");
var base = asn1.base;
var bignum = asn1.bignum;

// Import DER constants
var der = asn1.constants.der;

function DERDecoder(entity) {
  this.enc = 'der';
  this.name = entity.name;
  this.entity = entity;

  // Construct base tree
  this.tree = new DERNode();
  this.tree._init(entity.body);
};
module.exports = DERDecoder;

DERDecoder.prototype.decode = function decode(data, options) {
  if (!(data instanceof base.DecoderBuffer))
    data = new base.DecoderBuffer(data, options);

  return this.tree._decode(data, options);
};

// Tree methods

function DERNode(parent) {
  base.Node.call(this, 'der', parent);
}
inherits(DERNode, base.Node);

DERNode.prototype._peekTag = function peekTag(buffer, tag, any) {
  if (buffer.isEmpty())
    return false;

  var state = buffer.save();
  var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"');
  if (buffer.isError(decodedTag))
    return decodedTag;

  buffer.restore(state);

  return decodedTag.tag === tag || decodedTag.tagStr === tag ||
    (decodedTag.tagStr + 'of') === tag || any;
};

DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) {
  var decodedTag = derDecodeTag(buffer,
                                'Failed to decode tag of "' + tag + '"');
  if (buffer.isError(decodedTag))
    return decodedTag;

  var len = derDecodeLen(buffer,
                         decodedTag.primitive,
                         'Failed to get length of "' + tag + '"');

  // Failure
  if (buffer.isError(len))
    return len;

  if (!any &&
      decodedTag.tag !== tag &&
      decodedTag.tagStr !== tag &&
      decodedTag.tagStr + 'of' !== tag) {
    return buffer.error('Failed to match tag: "' + tag + '"');
  }

  if (decodedTag.primitive || len !== null)
    return buffer.skip(len, 'Failed to match body of: "' + tag + '"');

  // Indefinite length... find END tag
  var state = buffer.save();
  var res = this._skipUntilEnd(
      buffer,
      'Failed to skip indefinite length body: "' + this.tag + '"');
  if (buffer.isError(res))
    return res;

  len = buffer.offset - state.offset;
  buffer.restore(state);
  return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
};

DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) {
  while (true) {
    var tag = derDecodeTag(buffer, fail);
    if (buffer.isError(tag))
      return tag;
    var len = derDecodeLen(buffer, tag.primitive, fail);
    if (buffer.isError(len))
      return len;

    var res;
    if (tag.primitive || len !== null)
      res = buffer.skip(len)
    else
      res = this._skipUntilEnd(buffer, fail);

    // Failure
    if (buffer.isError(res))
      return res;

    if (tag.tagStr === 'end')
      break;
  }
};

DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder,
                                                    options) {
  var result = [];
  while (!buffer.isEmpty()) {
    var possibleEnd = this._peekTag(buffer, 'end');
    if (buffer.isError(possibleEnd))
      return possibleEnd;

    var res = decoder.decode(buffer, 'der', options);
    if (buffer.isError(res) && possibleEnd)
      break;
    result.push(res);
  }
  return result;
};

DERNode.prototype._decodeStr = function decodeStr(buffer, tag) {
  if (tag === 'bitstr') {
    var unused = buffer.readUInt8();
    if (buffer.isError(unused))
      return unused;
    return { unused: unused, data: buffer.raw() };
  } else if (tag === 'bmpstr') {
    var raw = buffer.raw();
    if (raw.length % 2 === 1)
      return buffer.error('Decoding of string type: bmpstr length mismatch');

    var str = '';
    for (var i = 0; i < raw.length / 2; i++) {
      str += String.fromCharCode(raw.readUInt16BE(i * 2));
    }
    return str;
  } else if (tag === 'numstr') {
    var numstr = buffer.raw().toString('ascii');
    if (!this._isNumstr(numstr)) {
      return buffer.error('Decoding of string type: ' +
                          'numstr unsupported characters');
    }
    return numstr;
  } else if (tag === 'octstr') {
    return buffer.raw();
  } else if (tag === 'objDesc') {
    return buffer.raw();
  } else if (tag === 'printstr') {
    var printstr = buffer.raw().toString('ascii');
    if (!this._isPrintstr(printstr)) {
      return buffer.error('Decoding of string type: ' +
                          'printstr unsupported characters');
    }
    return printstr;
  } else if (/str$/.test(tag)) {
    return buffer.raw().toString();
  } else {
    return buffer.error('Decoding of string type: ' + tag + ' unsupported');
  }
};

DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) {
  var result;
  var identifiers = [];
  var ident = 0;
  while (!buffer.isEmpty()) {
    var subident = buffer.readUInt8();
    ident <<= 7;
    ident |= subident & 0x7f;
    if ((subident & 0x80) === 0) {
      identifiers.push(ident);
      ident = 0;
    }
  }
  if (subident & 0x80)
    identifiers.push(ident);

  var first = (identifiers[0] / 40) | 0;
  var second = identifiers[0] % 40;

  if (relative)
    result = identifiers;
  else
    result = [first, second].concat(identifiers.slice(1));

  if (values) {
    var tmp = values[result.join(' ')];
    if (tmp === undefined)
      tmp = values[result.join('.')];
    if (tmp !== undefined)
      result = tmp;
  }

  return result;
};

DERNode.prototype._decodeTime = function decodeTime(buffer, tag) {
  var str = buffer.raw().toString();
  if (tag === 'gentime') {
    var year = str.slice(0, 4) | 0;
    var mon = str.slice(4, 6) | 0;
    var day = str.slice(6, 8) | 0;
    var hour = str.slice(8, 10) | 0;
    var min = str.slice(10, 12) | 0;
    var sec = str.slice(12, 14) | 0;
  } else if (tag === 'utctime') {
    var year = str.slice(0, 2) | 0;
    var mon = str.slice(2, 4) | 0;
    var day = str.slice(4, 6) | 0;
    var hour = str.slice(6, 8) | 0;
    var min = str.slice(8, 10) | 0;
    var sec = str.slice(10, 12) | 0;
    if (year < 70)
      year = 2000 + year;
    else
      year = 1900 + year;
  } else {
    return buffer.error('Decoding ' + tag + ' time is not supported yet');
  }

  return Date.UTC(year, mon - 1, day, hour, min, sec, 0);
};

DERNode.prototype._decodeNull = function decodeNull(buffer) {
  return null;
};

DERNode.prototype._decodeBool = function decodeBool(buffer) {
  var res = buffer.readUInt8();
  if (buffer.isError(res))
    return res;
  else
    return res !== 0;
};

DERNode.prototype._decodeInt = function decodeInt(buffer, values) {
  // Bigint, return as it is (assume big endian)
  var raw = buffer.raw();
  var res = new bignum(raw);

  if (values)
    res = values[res.toString(10)] || res;

  return res;
};

DERNode.prototype._use = function use(entity, obj) {
  if (typeof entity === 'function')
    entity = entity(obj);
  return entity._getDecoder('der').tree;
};

// Utility methods

function derDecodeTag(buf, fail) {
  var tag = buf.readUInt8(fail);
  if (buf.isError(tag))
    return tag;

  var cls = der.tagClass[tag >> 6];
  var primitive = (tag & 0x20) === 0;

  // Multi-octet tag - load
  if ((tag & 0x1f) === 0x1f) {
    var oct = tag;
    tag = 0;
    while ((oct & 0x80) === 0x80) {
      oct = buf.readUInt8(fail);
      if (buf.isError(oct))
        return oct;

      tag <<= 7;
      tag |= oct & 0x7f;
    }
  } else {
    tag &= 0x1f;
  }
  var tagStr = der.tag[tag];

  return {
    cls: cls,
    primitive: primitive,
    tag: tag,
    tagStr: tagStr
  };
}

function derDecodeLen(buf, primitive, fail) {
  var len = buf.readUInt8(fail);
  if (buf.isError(len))
    return len;

  // Indefinite form
  if (!primitive && len === 0x80)
    return null;

  // Definite form
  if ((len & 0x80) === 0) {
    // Short form
    return len;
  }

  // Long form
  var num = len & 0x7f;
  if (num > 4)
    return buf.error('length octect is too long');

  len = 0;
  for (var i = 0; i < num; i++) {
    len <<= 8;
    var j = buf.readUInt8(fail);
    if (buf.isError(j))
      return j;
    len |= j;
  }

  return len;
}


/***/ }),

/***/ "zAxo":
/*!************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotScattergeoIcon.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotScattergeoIcon = function PlotScattergeoIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 32 32' }, props),
        _react2.default.createElement('path', { d: 'M32.375 7.625c-.125 0-.125.125-.25 0v-.313h-.25c0-.375-.25-.625-.25-1.063-.188 0-.313 0-.313-.125l-.25.25c-.125 0 0-.125-.125-.125-.25.438-.375.938-.25 1.375-.125.125-.125.375-.125.5h-.313c0 .125 0 .25-.125.25-.375.188-.813.313-1.188.313-.125 0-.375 0-.563.125-.125.125-.25.375-.375.5s-.25.125-.25.313c.125.125.125.25.125.375-.438.688-1.063.375-1.625.688 0 .125.125.25.125.375-.5.688-1.188 1.063-1.813 1.5-.188 0-.438-.188-.563-.313 0-.25.25-.5.375-.625 0-.438-.125-.813-.375-1.063l-.375.375c-.188 0-.188-.125-.188-.25.438-.125.188-.813.313-.938-.125 0-.125-.125-.125-.125-.438 0-.688-.438-.938 0 0 .125.125 0 .125.125-.125 0-.125 0-.25.125 0 .25.125.375-.188.375 0-.125.188-.25 0-.375-.25.375-.375.938-.375 1.438.375.438.25 1.063-.125 1.5l-.125.125c-.813-.688-.313-2.125-.125-2.938-.188.25-.313.375-.563.563.25-.563.375-.938.563-1.25.25 0 .625-.125.938-.25h.75c-.125 0-.25-.125-.125-.375h-.375v-.313c-.438.188-.938.313-1.375.313 0-.313-.25-.313-.5-.313h-.125c.125-.25.125-.375.375-.5-.25 0-.5.125-.625.375-.313.125-.563.313-.813.438 0-.125-.313 0-.313-.125 0 0 .188-.188.188-.313-.313.125-.438.125-.688.125.25-.25.375-.375.688-.625.25-.125.5-.313.625-.438-.25 0-.5 0-.625-.125-.188.125-.438.125-.563 0l-.125-.125c-.25-.125-.563-.125-.938-.125-.125-.125-.25-.125-.563-.125-.125-.125 0-.563-.25-.563-.125 0 0 .313-.125.313-4.813 0-9.625-.563-14.25-1.875.125.625.125.938.125 1.188-.125 0-.25-.125-.125-.25-.125 0-.125 0-.25.125-.313-.125-.563-.313-.813-.438-.125.438 0 .813.125 1.25h-.125s0 .125.125.125c-.125.125-.25.25 0 .375-.125 0-.125.125-.125.125-.438.813-.688 1.625-1.188 2.25 0 .188 0 .438-.188.563 0 .563-.125 1.063-.375 1.438.375.313 0 .813.125 1.125.125.125.25.375.25.625 0 .125 0 .438.188.438-.188.25 0 .625.25.75 0 .188-.125.188-.125.313 0 .5.5.75.5 1.313v.563c.438.125.813.375 1.188.625v.125c.438.125.688.563.563 1.063.375.188.938.313 1.438.313 0 .125-.125 0-.125.125.563.25 1.063.625 1.625 1.063.813.375 1.563.5 2.5.688 0-.188 0-.313.188-.438.375.125.75.125 1.063.125.25.438.5.688.75.938.313.125.438.438.438.688.25.375.5.688.938.813.125-.313.375-.563.625-.688.688 0 1.375.688 1.375 1.313.25.125.25.563.5.688-.125.938.938 1.188 1.5 1.313-.125-.5-.125-1.063 0-1.438.625-.438 1.313-.813 1.875-1.188.625-.313 1.313-.313 2-.125 0-.313-.313 0-.313-.188.313-.25.438.188.688.188v.125c.125.125.25.125.375.125.188-.125.188-.125.313-.125.125.125-.125.125 0 .125.125-.125.25-.25.25-.438 0 .188.5.438.5.188-.125 0-.25-.188-.5-.313.125 0 .25-.25.125-.375-.125.125-.125.125-.25.125.125-.375.5-.375 1.063-.375 0 0 0-.313.125-.313s.125.313 0 .313c.563-.438 1.313-.313 1.875.25.25 0 .5-.125.688-.438.625 0 .5.563 1.063.563.25.25 0 .938.25 1.188v-.25h.125c0 .125-.125.25-.125.25.125.25.375.563.5.688l.188-.125c.125.125.125.25.125.375.25 0 .5.25.5.563.125-.125.25-.125.563-.125 0 .25-.438.25-.438.5.313-.125.438-.375.563-.688-.125 0 0 .188-.125.188.125-.813-.125-1.625-.563-2.313 0 0 .125 0 .125-.125-.625-.5-1.063-1.563-.75-2.5.125-.188.25-.438.25-.563.25-.125.5-.375.625-.688 0-.375.188-.625.563-.625h.125c0-.813.938-.563.938-1.063-.125.125-.25.125-.375 0 .125.125.25-.125.125-.313.125.188.375 0 .5-.125v-.125h-.25c.125 0 .25 0 .25-.125-.125-.25-.25-.563-.375-.813h-.25c.125-.125-.125-.25-.125-.375h.125a.657.657 0 0 0-.313-.563c.188 0 0-.125.188-.125-.313-.125-.313-.813 0-.938-.188.125.125.25-.188.563.188 0 0 0 .188.25.125.125.25.125.25.25v-.25c.375.125 0 .688.25.938.25-.563.25-.938.25-1.5-.25-.125-.375-.25-.375-.5.125.25.25.375.375.375v.125c.438-.375.563-.75.438-1.313h-.125c.125 0 0-.125.125-.125v-.125c.375-.438.938-.688 1.438-.938 0-.125 0-.125.125-.25 0 .125 0 .125-.125.25.125-.125.25-.25.563-.25 0-.125 0-.313-.313-.313.188.188.188.188.188.313-.313.25-.438-.438-.688-.313 0-.375 0-.75.125-1.188.25 0 .375-.125.563-.25v-.375s.125 0 .125.125-.125 0-.125.125c.25-.125.375-.25.375-.438 0 .188 0 .188.125.188s-.125-.188-.125-.313c.25.125.813-.375.375-.625zM5.313 13.313h2.688v2.688H5.313zm0-4h2.688v2.688H5.313zm-4 0h2.688v2.688H1.313zm0 4h2.688v2.688H1.313zm12 4h2.688v2.688h-2.688zm4-8h2.688v2.688h-2.688zm0 4h2.688v2.688h-2.688zm0 4h2.688v2.688h-2.688zm-4-8h2.688v2.688h-2.688zm0 4h2.688v2.688h-2.688zm8 0h2.688v2.688h-2.688zm0 4h2.688v2.688h-2.688zm4-4h2.688v2.688h-2.688zm-16-4h2.688v2.688H9.313zm0 4h2.688v2.688H9.313zm0 4h2.688v2.688H9.313z' })
    );
};

exports.default = PlotScattergeoIcon;

/***/ }),

/***/ "zBpB":
/*!******************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/PlotConeIcon.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PlotConeIcon = function PlotConeIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 1360 1360' }, props),
        _react2.default.createElement('path', { fill: 'currentColor', d: 'M225.789 819.922l222.98-96.366-104.28-115.568zM560.889 447.017L773.026 328.73l-115.36-104.498zM652.143 812.807l232.156-71.453-91.035-126.252zM925.186 966.93l238.652-45.326-76.505-135.553zM294.912 1135.768l233.006-68.614-89.48-127.343zM928.172 538.308l236.041-57.275-83.24-131.544z' })
    );
};

exports.default = PlotConeIcon;

/***/ }),

/***/ "zBqG":
/*!******************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/fields/MarkerColor.js ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Field = __webpack_require__(/*! ./Field */ "UXQq");

var _Field2 = _interopRequireDefault(_Field);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _RadioBlocks = __webpack_require__(/*! ../widgets/RadioBlocks */ "N8y9");

var _RadioBlocks2 = _interopRequireDefault(_RadioBlocks);

var _MultiColorPicker = __webpack_require__(/*! ./MultiColorPicker */ "/lhS");

var _MultiColorPicker2 = _interopRequireDefault(_MultiColorPicker);

var _ColorscalePicker = __webpack_require__(/*! ./ColorscalePicker */ "t0w/");

var _ColorscalePicker2 = _interopRequireDefault(_ColorscalePicker);

var _Numeric = __webpack_require__(/*! ./Numeric */ "E01D");

var _Numeric2 = _interopRequireDefault(_Numeric);

var _Radio = __webpack_require__(/*! ./Radio */ "5Riz");

var _Radio2 = _interopRequireDefault(_Radio);

var _Info = __webpack_require__(/*! ./Info */ "iOcY");

var _Info2 = _interopRequireDefault(_Info);

var _DataSelector = __webpack_require__(/*! ./DataSelector */ "dv5i");

var _DataSelector2 = _interopRequireDefault(_DataSelector);

var _VisibilitySelect = __webpack_require__(/*! ./VisibilitySelect */ "a9J7");

var _VisibilitySelect2 = _interopRequireDefault(_VisibilitySelect);

var _constants = __webpack_require__(/*! ../../lib/constants */ "5Bkx");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UnconnectedMarkerColor = function (_Component) {
  _inherits(UnconnectedMarkerColor, _Component);

  function UnconnectedMarkerColor(props, context) {
    _classCallCheck(this, UnconnectedMarkerColor);

    var _this = _possibleConstructorReturn(this, (UnconnectedMarkerColor.__proto__ || Object.getPrototypeOf(UnconnectedMarkerColor)).call(this, props, context));

    var type = null;
    if (!props.container.marker || props.container.marker && !props.container.marker.colorsrc) {
      type = 'constant';
    } else if (props.container.marker && Array.isArray(props.container.marker.color) && props.fullContainer.marker && Array.isArray(props.fullContainer.marker.color)) {
      type = 'variable';
    }

    _this.state = {
      type: type,
      value: {
        constant: type === 'constant' ? props.fullValue : _constants.COLORS.mutedBlue,
        variable: type === 'variable' ? props.fullValue : null
      },
      selectedConstantColorOption: type === 'constant' && props.multiValued ? 'multiple' : 'single'
    };

    _this.setType = _this.setType.bind(_this);
    _this.setColor = _this.setColor.bind(_this);
    _this.setColorScale = _this.setColorScale.bind(_this);
    _this.onConstantColorOptionChange = _this.onConstantColorOptionChange.bind(_this);
    return _this;
  }

  _createClass(UnconnectedMarkerColor, [{
    key: 'setType',
    value: function setType(type) {
      if (this.state.type !== type) {
        this.setState({ type: type });
        this.props.updatePlot(this.state.value[type]);
        if (type === 'constant') {
          var _context$updateContai;

          this.context.updateContainer((_context$updateContai = {}, _defineProperty(_context$updateContai, 'marker.colorsrc', null), _defineProperty(_context$updateContai, 'marker.colorscale', null), _defineProperty(_context$updateContai, 'marker.showscale', null), _context$updateContai));
          this.setState({ colorscale: null });
        } else {
          var _context$updateContai2;

          this.context.updateContainer((_context$updateContai2 = {}, _defineProperty(_context$updateContai2, 'marker.color', null), _defineProperty(_context$updateContai2, 'marker.colorsrc', null), _defineProperty(_context$updateContai2, 'marker.colorscale', null), _context$updateContai2));
        }
      }
    }
  }, {
    key: 'setColor',
    value: function setColor(inputValue) {
      var type = this.state.type;


      this.setState(type === 'constant' ? { value: { constant: inputValue } } : { value: { variable: inputValue } });
      this.props.updatePlot(inputValue);
    }
  }, {
    key: 'setColorScale',
    value: function setColorScale(inputValue) {
      this.setState({ colorscale: inputValue });
      this.context.updateContainer(_defineProperty({}, 'marker.colorscale', inputValue));
    }
  }, {
    key: 'isMultiValued',
    value: function isMultiValued() {
      return this.props.multiValued || Array.isArray(this.props.fullValue) && this.props.fullValue.includes(_constants.MULTI_VALUED) || this.props.container.marker && this.props.container.marker.colorscale && this.props.container.marker.colorscale === _constants.MULTI_VALUED || this.props.container.marker && this.props.container.marker.colorsrc && this.props.container.marker.colorsrc === _constants.MULTI_VALUED || this.props.container.marker && this.props.container.marker.color && Array.isArray(this.props.container.marker.color) && this.props.container.marker.color.includes(_constants.MULTI_VALUED);
    }
  }, {
    key: 'onConstantColorOptionChange',
    value: function onConstantColorOptionChange(value) {
      this.setState({
        selectedConstantColorOption: value
      });
    }
  }, {
    key: 'renderConstantControls',
    value: function renderConstantControls() {
      var _ = this.context.localize;
      return _react2.default.createElement(_MultiColorPicker2.default, {
        attr: 'marker.color',
        multiColorMessage: _('Each trace will be colored according to the selected colorscale.'),
        singleColorMessage: _('All traces will be colored in the the same color.'),
        setColor: this.setColor,
        setColorScale: this.setColorScale,
        onConstantColorOptionChange: this.onConstantColorOptionChange,
        parentSelectedConstantColorOption: this.state.selectedConstantColorOption
      });
    }
  }, {
    key: 'renderVariableControls',
    value: function renderVariableControls() {
      var multiValued = this.props.container && this.props.container.marker && (this.props.container.marker.colorscale && this.props.container.marker.colorscale === _constants.MULTI_VALUED || this.props.container.marker.colorsrc && this.props.container.marker.colorsrc === _constants.MULTI_VALUED);
      return _react2.default.createElement(
        _Field2.default,
        { multiValued: multiValued },
        _react2.default.createElement(_DataSelector2.default, { suppressMultiValuedMessage: true, attr: 'marker.color' }),
        this.props.container.marker && this.props.container.marker.colorscale === _constants.MULTI_VALUED ? null : _react2.default.createElement(_ColorscalePicker2.default, {
          suppressMultiValuedMessage: true,
          attr: 'marker.colorscale',
          updatePlot: this.setColorScale,
          colorscale: this.state.colorscale
        })
      );
    }
  }, {
    key: 'render',
    value: function render() {
      var attr = this.props.attr;
      var _context = this.context,
          _ = _context.localize,
          container = _context.container;

      // TO DO: https://github.com/plotly/react-chart-editor/issues/654

      var noSplitsPresent = container && (!container.transforms || !container.transforms.filter(function (t) {
        return t.type === 'groupby';
      }).length);

      if (noSplitsPresent) {
        var type = this.state.type;

        var options = [{ label: _('Constant'), value: 'constant' }, { label: _('Variable'), value: 'variable' }];

        return _react2.default.createElement(
          _react.Fragment,
          null,
          _react2.default.createElement(
            _Field2.default,
            _extends({}, this.props, { attr: attr }),
            _react2.default.createElement(
              _Field2.default,
              { multiValued: this.isMultiValued() && !this.state.type },
              _react2.default.createElement(_RadioBlocks2.default, { options: options, activeOption: type, onOptionChange: this.setType }),
              !type ? null : _react2.default.createElement(
                _Info2.default,
                null,
                type === 'constant' ? _('All points in a trace are colored in the same color.') : _('Each point in a trace is colored according to data.')
              )
            ),
            !type ? null : type === 'constant' ? this.renderConstantControls() : this.renderVariableControls()
          ),
          type === 'constant' ? null : _react2.default.createElement(
            _react.Fragment,
            null,
            _react2.default.createElement(_Radio2.default, {
              label: _('Colorscale Direction'),
              attr: 'marker.reversescale',
              options: [{ label: _('Normal'), value: false }, { label: _('Reversed'), value: true }]
            }),
            _react2.default.createElement(_Radio2.default, {
              label: _('Color Bar'),
              attr: 'marker.showscale',
              options: [{ label: _('Show'), value: true }, { label: _('Hide'), value: false }]
            }),
            _react2.default.createElement(
              _VisibilitySelect2.default,
              {
                label: _('Colorscale Range'),
                attr: 'marker.cauto',
                options: [{ label: _('Auto'), value: true }, { label: _('Custom'), value: false }],
                showOn: false,
                defaultOpt: true
              },
              _react2.default.createElement(_Numeric2.default, { label: _('Min'), attr: 'marker.cmin' }),
              _react2.default.createElement(_Numeric2.default, { label: _('Max'), attr: 'marker.cmax' })
            )
          )
        );
      }

      return _react2.default.createElement(
        _Field2.default,
        _extends({}, this.props, { attr: attr }),
        this.renderConstantControls()
      );
    }
  }]);

  return UnconnectedMarkerColor;
}(_react.Component);

UnconnectedMarkerColor.propTypes = _extends({
  fullValue: _propTypes2.default.any,
  updatePlot: _propTypes2.default.func
}, _Field2.default.propTypes);

UnconnectedMarkerColor.contextTypes = {
  localize: _propTypes2.default.func,
  updateContainer: _propTypes2.default.func,
  traceIndexes: _propTypes2.default.array,
  container: _propTypes2.default.object
};

exports.default = (0, _lib.connectToContainer)(UnconnectedMarkerColor);
//# sourceMappingURL=MarkerColor.js.map

/***/ }),

/***/ "zEVN":
/*!**************************************!*\
  !*** ./node_modules/lodash/isMap.js ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var baseIsMap = __webpack_require__(/*! ./_baseIsMap */ "Gi0A"),
    baseUnary = __webpack_require__(/*! ./_baseUnary */ "sEf8"),
    nodeUtil = __webpack_require__(/*! ./_nodeUtil */ "mdPL");

/* Node.js helper references. */
var nodeIsMap = nodeUtil && nodeUtil.isMap;

/**
 * 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;

module.exports = isMap;


/***/ }),

/***/ "zFpJ":
/*!******************************************!*\
  !*** ./node_modules/base16/lib/ashes.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports['default'] = {
  scheme: 'ashes',
  author: 'jannik siebert (https://github.com/janniks)',
  base00: '#1C2023',
  base01: '#393F45',
  base02: '#565E65',
  base03: '#747C84',
  base04: '#ADB3BA',
  base05: '#C7CCD1',
  base06: '#DFE2E5',
  base07: '#F3F4F5',
  base08: '#C7AE95',
  base09: '#C7C795',
  base0A: '#AEC795',
  base0B: '#95C7AE',
  base0C: '#95AEC7',
  base0D: '#AE95C7',
  base0E: '#C795AE',
  base0F: '#C79595'
};
module.exports = exports['default'];

/***/ }),

/***/ "zGJM":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/codemirror/lib/editor.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
            t[p[i]] = s[p[i]];
    return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const codemirror_1 = __importDefault(__webpack_require__(/*! codemirror */ "VrN/"));
const coreutils_1 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const algorithm_1 = __webpack_require__(/*! @phosphor/algorithm */ "rqNV");
const disposable_1 = __webpack_require__(/*! @phosphor/disposable */ "uNUc");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const codeeditor_1 = __webpack_require__(/*! @jupyterlab/codeeditor */ "sLCx");
const coreutils_2 = __webpack_require__(/*! @phosphor/coreutils */ "iadR");
const mode_1 = __webpack_require__(/*! ./mode */ "Gga1");
__webpack_require__(/*! codemirror/addon/comment/comment.js */ "cokd");
__webpack_require__(/*! codemirror/addon/edit/matchbrackets.js */ "jDMi");
__webpack_require__(/*! codemirror/addon/edit/closebrackets.js */ "ELLl");
__webpack_require__(/*! codemirror/addon/scroll/scrollpastend.js */ "0tVu");
__webpack_require__(/*! codemirror/addon/search/searchcursor */ "uTOq");
__webpack_require__(/*! codemirror/addon/search/search */ "C2zF");
__webpack_require__(/*! codemirror/addon/search/jump-to-line */ "GP5n");
__webpack_require__(/*! codemirror/keymap/emacs.js */ "Lm6R");
__webpack_require__(/*! codemirror/keymap/sublime.js */ "mki7");
__webpack_require__(/*! codemirror/keymap/vim.js */ "dfh3");
/**
 * The class name added to CodeMirrorWidget instances.
 */
const EDITOR_CLASS = 'jp-CodeMirrorEditor';
/**
 * The class name added to read only cell editor widgets.
 */
const READ_ONLY_CLASS = 'jp-mod-readOnly';
/**
 * The class name for the hover box for collaborator cursors.
 */
const COLLABORATOR_CURSOR_CLASS = 'jp-CollaboratorCursor';
/**
 * The class name for the hover box for collaborator cursors.
 */
const COLLABORATOR_HOVER_CLASS = 'jp-CollaboratorCursor-hover';
/**
 * The key code for the up arrow key.
 */
const UP_ARROW = 38;
/**
 * The key code for the down arrow key.
 */
const DOWN_ARROW = 40;
/**
 * The time that a collaborator name hover persists.
 */
const HOVER_TIMEOUT = 1000;
/**
 * CodeMirror editor.
 */
class CodeMirrorEditor {
    /**
     * Construct a CodeMirror editor.
     */
    constructor(options) {
        /**
         * A signal emitted when either the top or bottom edge is requested.
         */
        this.edgeRequested = new signaling_1.Signal(this);
        this.selectionMarkers = {};
        this._keydownHandlers = new Array();
        this._changeGuard = false;
        this._uuid = '';
        this._needsRefresh = false;
        this._isDisposed = false;
        this._lastChange = null;
        this._timer = -1;
        let host = (this.host = options.host);
        host.classList.add(EDITOR_CLASS);
        host.classList.add('jp-Editor');
        host.addEventListener('focus', this, true);
        host.addEventListener('blur', this, true);
        host.addEventListener('scroll', this, true);
        this._uuid = options.uuid || coreutils_2.UUID.uuid4();
        // Handle selection style.
        let style = options.selectionStyle || {};
        this._selectionStyle = Object.assign({}, codeeditor_1.CodeEditor.defaultSelectionStyle, style);
        let model = (this._model = options.model);
        let config = options.config || {};
        let fullConfig = (this._config = Object.assign({}, CodeMirrorEditor.defaultConfig, config));
        let editor = (this._editor = Private.createEditor(host, fullConfig));
        let doc = editor.getDoc();
        // Handle initial values for text, mimetype, and selections.
        doc.setValue(model.value.text);
        this.clearHistory();
        this._onMimeTypeChanged();
        this._onCursorActivity();
        this._timer = window.setInterval(() => {
            this._checkSync();
        }, 3000);
        // Connect to changes.
        model.value.changed.connect(this._onValueChanged, this);
        model.mimeTypeChanged.connect(this._onMimeTypeChanged, this);
        model.selections.changed.connect(this._onSelectionsChanged, this);
        codemirror_1.default.on(editor, 'keydown', (editor, event) => {
            let index = algorithm_1.ArrayExt.findFirstIndex(this._keydownHandlers, handler => {
                if (handler(this, event) === true) {
                    event.preventDefault();
                    return true;
                }
                return false;
            });
            if (index === -1) {
                this.onKeydown(event);
            }
        });
        codemirror_1.default.on(editor, 'cursorActivity', () => this._onCursorActivity());
        codemirror_1.default.on(editor.getDoc(), 'beforeChange', (instance, change) => {
            this._beforeDocChanged(instance, change);
        });
        codemirror_1.default.on(editor.getDoc(), 'change', (instance, change) => {
            // Manually refresh after setValue to make sure editor is properly sized.
            if (change.origin === 'setValue' && this.hasFocus()) {
                this.refresh();
            }
            this._lastChange = change;
        });
        // Manually refresh on paste to make sure editor is properly sized.
        editor.getWrapperElement().addEventListener('paste', () => {
            if (this.hasFocus()) {
                this.refresh();
            }
        });
    }
    /**
     * The uuid of this editor;
     */
    get uuid() {
        return this._uuid;
    }
    set uuid(value) {
        this._uuid = value;
    }
    /**
     * The selection style of this editor.
     */
    get selectionStyle() {
        return this._selectionStyle;
    }
    set selectionStyle(value) {
        this._selectionStyle = value;
    }
    /**
     * Get the codemirror editor wrapped by the editor.
     */
    get editor() {
        return this._editor;
    }
    /**
     * Get the codemirror doc wrapped by the widget.
     */
    get doc() {
        return this._editor.getDoc();
    }
    /**
     * Get the number of lines in the editor.
     */
    get lineCount() {
        return this.doc.lineCount();
    }
    /**
     * Returns a model for this editor.
     */
    get model() {
        return this._model;
    }
    /**
     * The height of a line in the editor in pixels.
     */
    get lineHeight() {
        return this._editor.defaultTextHeight();
    }
    /**
     * The widget of a character in the editor in pixels.
     */
    get charWidth() {
        return this._editor.defaultCharWidth();
    }
    /**
     * Tests whether the editor is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources held by the widget.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        this.host.removeEventListener('focus', this, true);
        this.host.removeEventListener('blur', this, true);
        this.host.removeEventListener('scroll', this, true);
        this._keydownHandlers.length = 0;
        window.clearInterval(this._timer);
        signaling_1.Signal.clearData(this);
    }
    /**
     * Get a config option for the editor.
     */
    getOption(option) {
        return this._config[option];
    }
    /**
     * Set a config option for the editor.
     */
    setOption(option, value) {
        // Don't bother setting the option if it is already the same.
        if (this._config[option] !== value) {
            this._config[option] = value;
            Private.setOption(this.editor, option, value, this._config);
        }
    }
    /**
     * Returns the content for the given line number.
     */
    getLine(line) {
        return this.doc.getLine(line);
    }
    /**
     * Find an offset for the given position.
     */
    getOffsetAt(position) {
        return this.doc.indexFromPos({
            ch: position.column,
            line: position.line
        });
    }
    /**
     * Find a position for the given offset.
     */
    getPositionAt(offset) {
        const { ch, line } = this.doc.posFromIndex(offset);
        return { line, column: ch };
    }
    /**
     * Undo one edit (if any undo events are stored).
     */
    undo() {
        this.doc.undo();
    }
    /**
     * Redo one undone edit.
     */
    redo() {
        this.doc.redo();
    }
    /**
     * Clear the undo history.
     */
    clearHistory() {
        this.doc.clearHistory();
    }
    /**
     * Brings browser focus to this editor text.
     */
    focus() {
        this._editor.focus();
    }
    /**
     * Test whether the editor has keyboard focus.
     */
    hasFocus() {
        return this._editor.getWrapperElement().contains(document.activeElement);
    }
    /**
     * Explicitly blur the editor.
     */
    blur() {
        this._editor.getInputField().blur();
    }
    /**
     * Repaint editor.
     */
    refresh() {
        this._editor.refresh();
        this._needsRefresh = false;
    }
    /**
     * Refresh the editor if it is focused;
     * otherwise postpone refreshing till focusing.
     */
    resizeToFit() {
        if (this.hasFocus()) {
            this.refresh();
        }
        else {
            this._needsRefresh = true;
        }
        this._clearHover();
    }
    /**
     * Add a keydown handler to the editor.
     *
     * @param handler - A keydown handler.
     *
     * @returns A disposable that can be used to remove the handler.
     */
    addKeydownHandler(handler) {
        this._keydownHandlers.push(handler);
        return new disposable_1.DisposableDelegate(() => {
            algorithm_1.ArrayExt.removeAllWhere(this._keydownHandlers, val => val === handler);
        });
    }
    /**
     * Set the size of the editor in pixels.
     */
    setSize(dimension) {
        if (dimension) {
            this._editor.setSize(dimension.width, dimension.height);
        }
        else {
            this._editor.setSize(null, null);
        }
        this._needsRefresh = false;
    }
    /**
     * Reveal the given position in the editor.
     */
    revealPosition(position) {
        const cmPosition = this._toCodeMirrorPosition(position);
        this._editor.scrollIntoView(cmPosition);
    }
    /**
     * Reveal the given selection in the editor.
     */
    revealSelection(selection) {
        const range = this._toCodeMirrorRange(selection);
        this._editor.scrollIntoView(range);
    }
    /**
     * Get the window coordinates given a cursor position.
     */
    getCoordinateForPosition(position) {
        const pos = this._toCodeMirrorPosition(position);
        const rect = this.editor.charCoords(pos, 'page');
        return rect;
    }
    /**
     * Get the cursor position given window coordinates.
     *
     * @param coordinate - The desired coordinate.
     *
     * @returns The position of the coordinates, or null if not
     *   contained in the editor.
     */
    getPositionForCoordinate(coordinate) {
        return this._toPosition(this.editor.coordsChar(coordinate)) || null;
    }
    /**
     * Returns the primary position of the cursor, never `null`.
     */
    getCursorPosition() {
        const cursor = this.doc.getCursor();
        return this._toPosition(cursor);
    }
    /**
     * Set the primary position of the cursor.
     *
     * #### Notes
     * This will remove any secondary cursors.
     */
    setCursorPosition(position) {
        const cursor = this._toCodeMirrorPosition(position);
        this.doc.setCursor(cursor);
        // If the editor does not have focus, this cursor change
        // will get screened out in _onCursorsChanged(). Make an
        // exception for this method.
        if (!this.editor.hasFocus()) {
            this.model.selections.set(this.uuid, this.getSelections());
        }
    }
    /**
     * Returns the primary selection, never `null`.
     */
    getSelection() {
        return this.getSelections()[0];
    }
    /**
     * Set the primary selection. This will remove any secondary cursors.
     */
    setSelection(selection) {
        this.setSelections([selection]);
    }
    /**
     * Gets the selections for all the cursors, never `null` or empty.
     */
    getSelections() {
        const selections = this.doc.listSelections();
        if (selections.length > 0) {
            return selections.map(selection => this._toSelection(selection));
        }
        const cursor = this.doc.getCursor();
        const selection = this._toSelection({ anchor: cursor, head: cursor });
        return [selection];
    }
    /**
     * Sets the selections for all the cursors, should not be empty.
     * Cursors will be removed or added, as necessary.
     * Passing an empty array resets a cursor position to the start of a document.
     */
    setSelections(selections) {
        const cmSelections = this._toCodeMirrorSelections(selections);
        this.doc.setSelections(cmSelections, 0);
    }
    /**
     * Get a list of tokens for the current editor text content.
     */
    getTokens() {
        let tokens = [];
        for (let i = 0; i < this.lineCount; ++i) {
            const lineTokens = this.editor.getLineTokens(i).map(t => ({
                offset: this.getOffsetAt({ column: t.start, line: i }),
                value: t.string,
                type: t.type || ''
            }));
            tokens = tokens.concat(lineTokens);
        }
        return tokens;
    }
    /**
     * Get the token at a given editor position.
     */
    getTokenForPosition(position) {
        const cursor = this._toCodeMirrorPosition(position);
        const token = this.editor.getTokenAt(cursor);
        return {
            offset: this.getOffsetAt({ column: token.start, line: cursor.line }),
            value: token.string,
            type: token.type
        };
    }
    /**
     * Insert a new indented line at the current cursor position.
     */
    newIndentedLine() {
        this.execCommand('newlineAndIndent');
    }
    /**
     * Execute a codemirror command on the editor.
     *
     * @param command - The name of the command to execute.
     */
    execCommand(command) {
        this._editor.execCommand(command);
    }
    /**
     * Handle keydown events from the editor.
     */
    onKeydown(event) {
        let position = this.getCursorPosition();
        let { line, column } = position;
        if (line === 0 && column === 0 && event.keyCode === UP_ARROW) {
            if (!event.shiftKey) {
                this.edgeRequested.emit('top');
            }
            return false;
        }
        let lastLine = this.lineCount - 1;
        let lastCh = this.getLine(lastLine).length;
        if (line === lastLine &&
            column === lastCh &&
            event.keyCode === DOWN_ARROW) {
            if (!event.shiftKey) {
                this.edgeRequested.emit('bottom');
            }
            return false;
        }
        return false;
    }
    /**
     * Converts selections to code mirror selections.
     */
    _toCodeMirrorSelections(selections) {
        if (selections.length > 0) {
            return selections.map(selection => this._toCodeMirrorSelection(selection));
        }
        const position = { line: 0, ch: 0 };
        return [{ anchor: position, head: position }];
    }
    /**
     * Handles a mime type change.
     */
    _onMimeTypeChanged() {
        const mime = this._model.mimeType;
        let editor = this._editor;
        mode_1.Mode.ensure(mime).then(spec => {
            editor.setOption('mode', spec.mime);
        });
        let extraKeys = editor.getOption('extraKeys') || {};
        const isCode = mime !== 'text/plain' && mime !== 'text/x-ipythongfm';
        if (isCode) {
            extraKeys['Backspace'] = 'delSpaceToPrevTabStop';
        }
        else {
            delete extraKeys['Backspace'];
        }
        editor.setOption('extraKeys', extraKeys);
    }
    /**
     * Handles a selections change.
     */
    _onSelectionsChanged(selections, args) {
        const uuid = args.key;
        if (uuid !== this.uuid) {
            this._cleanSelections(uuid);
            if (args.type !== 'remove' && args.newValue) {
                this._markSelections(uuid, args.newValue);
            }
        }
    }
    /**
     * Clean selections for the given uuid.
     */
    _cleanSelections(uuid) {
        const markers = this.selectionMarkers[uuid];
        if (markers) {
            markers.forEach(marker => {
                marker.clear();
            });
        }
        delete this.selectionMarkers[uuid];
    }
    /**
     * Marks selections.
     */
    _markSelections(uuid, selections) {
        const markers = [];
        // If we are marking selections corresponding to an active hover,
        // remove it.
        if (uuid === this._hoverId) {
            this._clearHover();
        }
        // If we can id the selection to a specific collaborator,
        // use that information.
        let collaborator;
        if (this._model.modelDB.collaborators) {
            collaborator = this._model.modelDB.collaborators.get(uuid);
        }
        // Style each selection for the uuid.
        selections.forEach(selection => {
            // Only render selections if the start is not equal to the end.
            // In that case, we don't need to render the cursor.
            if (!coreutils_1.JSONExt.deepEqual(selection.start, selection.end)) {
                const { anchor, head } = this._toCodeMirrorSelection(selection);
                let markerOptions;
                if (collaborator) {
                    markerOptions = this._toTextMarkerOptions(Object.assign({}, selection.style, { color: collaborator.color }));
                }
                else {
                    markerOptions = this._toTextMarkerOptions(selection.style);
                }
                markers.push(this.doc.markText(anchor, head, markerOptions));
            }
            else if (collaborator) {
                let caret = this._getCaret(collaborator);
                markers.push(this.doc.setBookmark(this._toCodeMirrorPosition(selection.end), {
                    widget: caret
                }));
            }
        });
        this.selectionMarkers[uuid] = markers;
    }
    /**
     * Handles a cursor activity event.
     */
    _onCursorActivity() {
        // Only add selections if the editor has focus. This avoids unwanted
        // triggering of cursor activity due to collaborator actions.
        if (this._editor.hasFocus()) {
            const selections = this.getSelections();
            this.model.selections.set(this.uuid, selections);
        }
    }
    /**
     * Converts a code mirror selection to an editor selection.
     */
    _toSelection(selection) {
        return {
            uuid: this.uuid,
            start: this._toPosition(selection.anchor),
            end: this._toPosition(selection.head),
            style: this.selectionStyle
        };
    }
    /**
     * Converts the selection style to a text marker options.
     */
    _toTextMarkerOptions(style) {
        let r = parseInt(style.color.slice(1, 3), 16);
        let g = parseInt(style.color.slice(3, 5), 16);
        let b = parseInt(style.color.slice(5, 7), 16);
        let css = `background-color: rgba( ${r}, ${g}, ${b}, 0.15)`;
        return {
            className: style.className,
            title: style.displayName,
            css
        };
    }
    /**
     * Converts an editor selection to a code mirror selection.
     */
    _toCodeMirrorSelection(selection) {
        // Selections only appear to render correctly if the anchor
        // is before the head in the document. That is, reverse selections
        // do not appear as intended.
        let forward = selection.start.line < selection.end.line ||
            (selection.start.line === selection.end.line &&
                selection.start.column <= selection.end.column);
        let anchor = forward ? selection.start : selection.end;
        let head = forward ? selection.end : selection.start;
        return {
            anchor: this._toCodeMirrorPosition(anchor),
            head: this._toCodeMirrorPosition(head)
        };
    }
    /**
     * Converts an editor selection to a code mirror selection.
     */
    _toCodeMirrorRange(range) {
        return {
            from: this._toCodeMirrorPosition(range.start),
            to: this._toCodeMirrorPosition(range.end)
        };
    }
    /**
     * Convert a code mirror position to an editor position.
     */
    _toPosition(position) {
        return {
            line: position.line,
            column: position.ch
        };
    }
    /**
     * Convert an editor position to a code mirror position.
     */
    _toCodeMirrorPosition(position) {
        return {
            line: position.line,
            ch: position.column
        };
    }
    /**
     * Handle model value changes.
     */
    _onValueChanged(value, args) {
        if (this._changeGuard) {
            return;
        }
        this._changeGuard = true;
        let doc = this.doc;
        switch (args.type) {
            case 'insert':
                let pos = doc.posFromIndex(args.start);
                doc.replaceRange(args.value, pos, pos);
                break;
            case 'remove':
                let from = doc.posFromIndex(args.start);
                let to = doc.posFromIndex(args.end);
                doc.replaceRange('', from, to);
                break;
            case 'set':
                doc.setValue(args.value);
                break;
            default:
                break;
        }
        this._changeGuard = false;
    }
    /**
     * Handles document changes.
     */
    _beforeDocChanged(doc, change) {
        if (this._changeGuard) {
            return;
        }
        this._changeGuard = true;
        let value = this._model.value;
        let start = doc.indexFromPos(change.from);
        let end = doc.indexFromPos(change.to);
        let inserted = change.text.join('\n');
        if (end !== start) {
            value.remove(start, end);
        }
        if (inserted) {
            value.insert(start, inserted);
        }
        this._changeGuard = false;
    }
    /**
     * Handle the DOM events for the editor.
     *
     * @param event - The DOM event sent to the editor.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the editor's DOM node. It should
     * not be called directly by user code.
     */
    handleEvent(event) {
        switch (event.type) {
            case 'focus':
                this._evtFocus(event);
                break;
            case 'blur':
                this._evtBlur(event);
                break;
            case 'scroll':
                this._evtScroll();
                break;
            default:
                break;
        }
    }
    /**
     * Handle `focus` events for the editor.
     */
    _evtFocus(event) {
        if (this._needsRefresh) {
            this.refresh();
        }
        this.host.classList.add('jp-mod-focused');
        // Update the selections on editor gaining focus because
        // the onCursorActivity function filters usual cursor events
        // based on the editor's focus.
        this._onCursorActivity();
    }
    /**
     * Handle `blur` events for the editor.
     */
    _evtBlur(event) {
        this.host.classList.remove('jp-mod-focused');
    }
    /**
     * Handle `scroll` events for the editor.
     */
    _evtScroll() {
        // Remove any active hover.
        this._clearHover();
    }
    /**
     * Clear the hover for a caret, due to things like
     * scrolling, resizing, deactivation, etc, where
     * the position is no longer valid.
     */
    _clearHover() {
        if (this._caretHover) {
            window.clearTimeout(this._hoverTimeout);
            document.body.removeChild(this._caretHover);
            this._caretHover = null;
        }
    }
    /**
     * Construct a caret element representing the position
     * of a collaborator's cursor.
     */
    _getCaret(collaborator) {
        let name = collaborator ? collaborator.displayName : 'Anonymous';
        let color = collaborator ? collaborator.color : this._selectionStyle.color;
        let caret = document.createElement('span');
        caret.className = COLLABORATOR_CURSOR_CLASS;
        caret.style.borderBottomColor = color;
        caret.onmouseenter = () => {
            this._clearHover();
            this._hoverId = collaborator.sessionId;
            let rect = caret.getBoundingClientRect();
            // Construct and place the hover box.
            let hover = document.createElement('div');
            hover.className = COLLABORATOR_HOVER_CLASS;
            hover.style.left = String(rect.left) + 'px';
            hover.style.top = String(rect.bottom) + 'px';
            hover.textContent = name;
            hover.style.backgroundColor = color;
            // If the user mouses over the hover, take over the timer.
            hover.onmouseenter = () => {
                window.clearTimeout(this._hoverTimeout);
            };
            hover.onmouseleave = () => {
                this._hoverTimeout = window.setTimeout(() => {
                    this._clearHover();
                }, HOVER_TIMEOUT);
            };
            this._caretHover = hover;
            document.body.appendChild(hover);
        };
        caret.onmouseleave = () => {
            this._hoverTimeout = window.setTimeout(() => {
                this._clearHover();
            }, HOVER_TIMEOUT);
        };
        return caret;
    }
    /**
     * Check for an out of sync editor.
     */
    _checkSync() {
        let change = this._lastChange;
        if (!change) {
            return;
        }
        this._lastChange = null;
        let editor = this._editor;
        let doc = editor.getDoc();
        if (doc.getValue() === this._model.value.text) {
            return;
        }
        apputils_1.showDialog({
            title: 'Code Editor out of Sync',
            body: 'Please open your browser JavaScript console for bug report instructions'
        });
        console.log('Please paste the following to https://github.com/jupyterlab/jupyterlab/issues/2951');
        console.log(JSON.stringify({
            model: this._model.value.text,
            view: doc.getValue(),
            selections: this.getSelections(),
            cursor: this.getCursorPosition(),
            lineSep: editor.getOption('lineSeparator'),
            mode: editor.getOption('mode'),
            change
        }));
    }
}
exports.CodeMirrorEditor = CodeMirrorEditor;
/**
 * The namespace for `CodeMirrorEditor` statics.
 */
(function (CodeMirrorEditor) {
    /**
     * The default configuration options for an editor.
     */
    CodeMirrorEditor.defaultConfig = Object.assign({}, codeeditor_1.CodeEditor.defaultConfig, { mode: 'null', theme: 'jupyter', smartIndent: true, electricChars: true, keyMap: 'default', extraKeys: null, gutters: [], fixedGutter: true, showCursorWhenSelecting: false, coverGutterNextToScrollbar: false, dragDrop: true, lineSeparator: null, scrollbarStyle: 'native', lineWiseCopyCut: true, scrollPastEnd: false });
    /**
     * Add a command to CodeMirror.
     *
     * @param name - The name of the command to add.
     *
     * @param command - The command function.
     */
    function addCommand(name, command) {
        codemirror_1.default.commands[name] = command;
    }
    CodeMirrorEditor.addCommand = addCommand;
})(CodeMirrorEditor = exports.CodeMirrorEditor || (exports.CodeMirrorEditor = {}));
/**
 * The namespace for module private data.
 */
var Private;
(function (Private) {
    function createEditor(host, config) {
        let { autoClosingBrackets, fontFamily, fontSize, insertSpaces, lineHeight, lineWrap, wordWrapColumn, tabSize, readOnly } = config, otherOptions = __rest(config, ["autoClosingBrackets", "fontFamily", "fontSize", "insertSpaces", "lineHeight", "lineWrap", "wordWrapColumn", "tabSize", "readOnly"]);
        let bareConfig = Object.assign({ autoCloseBrackets: autoClosingBrackets, indentUnit: tabSize, indentWithTabs: !insertSpaces, lineWrapping: lineWrap === 'off' ? false : true, readOnly }, otherOptions);
        return codemirror_1.default(el => {
            if (fontFamily) {
                el.style.fontFamily = fontFamily;
            }
            if (fontSize) {
                el.style.fontSize = fontSize + 'px';
            }
            if (lineHeight) {
                el.style.lineHeight = lineHeight.toString();
            }
            if (readOnly) {
                el.classList.add(READ_ONLY_CLASS);
            }
            if (lineWrap === 'wordWrapColumn') {
                const lines = el.querySelector('.CodeMirror-lines');
                lines.style.width = `${wordWrapColumn}ch`;
            }
            if (lineWrap === 'bounded') {
                const lines = el.querySelector('.CodeMirror-lines');
                lines.style.maxWidth = `${wordWrapColumn}ch`;
            }
            host.appendChild(el);
        }, bareConfig);
    }
    Private.createEditor = createEditor;
    /**
     * Indent or insert a tab as appropriate.
     */
    function indentMoreOrinsertTab(cm) {
        let doc = cm.getDoc();
        let from = doc.getCursor('from');
        let to = doc.getCursor('to');
        let sel = !posEq(from, to);
        if (sel) {
            codemirror_1.default.commands['indentMore'](cm);
            return;
        }
        // Check for start of line.
        let line = doc.getLine(from.line);
        let before = line.slice(0, from.ch);
        if (/^\s*$/.test(before)) {
            codemirror_1.default.commands['indentMore'](cm);
        }
        else {
            if (cm.getOption('indentWithTabs')) {
                codemirror_1.default.commands['insertTab'](cm);
            }
            else {
                codemirror_1.default.commands['insertSoftTab'](cm);
            }
        }
    }
    Private.indentMoreOrinsertTab = indentMoreOrinsertTab;
    /**
     * Delete spaces to the previous tab stob in a codemirror editor.
     */
    function delSpaceToPrevTabStop(cm) {
        let doc = cm.getDoc();
        let from = doc.getCursor('from');
        let to = doc.getCursor('to');
        let sel = !posEq(from, to);
        if (sel) {
            let ranges = doc.listSelections();
            for (let i = ranges.length - 1; i >= 0; i--) {
                let head = ranges[i].head;
                let anchor = ranges[i].anchor;
                doc.replaceRange('', codemirror_1.default.Pos(head.line, head.ch), codemirror_1.default.Pos(anchor.line, anchor.ch));
            }
            return;
        }
        let cur = doc.getCursor();
        let tabsize = cm.getOption('tabSize');
        let chToPrevTabStop = cur.ch - (Math.ceil(cur.ch / tabsize) - 1) * tabsize;
        from = { ch: cur.ch - chToPrevTabStop, line: cur.line };
        let select = doc.getRange(from, cur);
        if (select.match(/^\ +$/) !== null) {
            doc.replaceRange('', from, cur);
        }
        else {
            codemirror_1.default.commands['delCharBefore'](cm);
        }
    }
    Private.delSpaceToPrevTabStop = delSpaceToPrevTabStop;
    /**
     * Test whether two CodeMirror positions are equal.
     */
    function posEq(a, b) {
        return a.line === b.line && a.ch === b.ch;
    }
    Private.posEq = posEq;
    /**
     * Set a config option for the editor.
     */
    function setOption(editor, option, value, config) {
        let el = editor.getWrapperElement();
        switch (option) {
            case 'lineWrap':
                const lineWrapping = value === 'off' ? false : true;
                const lines = el.querySelector('.CodeMirror-lines');
                const maxWidth = value === 'bounded' ? `${config.wordWrapColumn}ch` : null;
                const width = value === 'wordWrapColumn' ? `${config.wordWrapColumn}ch` : null;
                lines.style.maxWidth = maxWidth;
                lines.style.width = width;
                editor.setOption('lineWrapping', lineWrapping);
                break;
            case 'wordWrapColumn':
                const { lineWrap } = config;
                if (lineWrap === 'wordWrapColumn' || lineWrap === 'bounded') {
                    const lines = el.querySelector('.CodeMirror-lines');
                    const prop = lineWrap === 'wordWrapColumn' ? 'width' : 'maxWidth';
                    lines.style[prop] = `${value}ch`;
                }
                break;
            case 'tabSize':
                editor.setOption('indentUnit', value);
                break;
            case 'insertSpaces':
                editor.setOption('indentWithTabs', !value);
                break;
            case 'autoClosingBrackets':
                editor.setOption('autoCloseBrackets', value);
                break;
            case 'readOnly':
                el.classList.toggle(READ_ONLY_CLASS, value);
                editor.setOption(option, value);
                break;
            case 'fontFamily':
                el.style.fontFamily = value;
                break;
            case 'fontSize':
                el.style.fontSize = value ? value + 'px' : null;
                break;
            case 'lineHeight':
                el.style.lineHeight = value ? value.toString() : null;
                break;
            default:
                editor.setOption(option, value);
                break;
        }
    }
    Private.setOption = setOption;
})(Private || (Private = {}));
/**
 * Add a CodeMirror command to delete until previous non blanking space
 * character or first multiple of tabsize tabstop.
 */
CodeMirrorEditor.addCommand('delSpaceToPrevTabStop', Private.delSpaceToPrevTabStop);
/**
 * Add a CodeMirror command to indent or insert a tab as appropriate.
 */
CodeMirrorEditor.addCommand('indentMoreOrinsertTab', Private.indentMoreOrinsertTab);


/***/ }),

/***/ "zLkG":
/*!**********************************************************!*\
  !*** ./node_modules/core-js/library/modules/_wks-ext.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports.f = __webpack_require__(/*! ./_wks */ "UWiX");


/***/ }),

/***/ "zORg":
/*!*******************************************************************!*\
  !*** ./node_modules/draft-js/lib/getSelectionOffsetKeyForNode.js ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule getSelectionOffsetKeyForNode
 * @format
 * 
 */



/**
 * Get offset key from a node or it's child nodes. Return the first offset key
 * found on the DOM tree of given node.
 */

function getSelectionOffsetKeyForNode(node) {
  if (node instanceof Element) {
    var offsetKey = node.getAttribute('data-offset-key');
    if (offsetKey) {
      return offsetKey;
    }
    for (var ii = 0; ii < node.childNodes.length; ii++) {
      var childOffsetKey = getSelectionOffsetKeyForNode(node.childNodes[ii]);
      if (childOffsetKey) {
        return childOffsetKey;
      }
    }
  }
  return null;
}

module.exports = getSelectionOffsetKeyForNode;

/***/ }),

/***/ "zOct":
/*!************************************************************************!*\
  !*** ./node_modules/plotly-icons/lib/components/TraceTypeSplomIcon.js ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _IconBase = __webpack_require__(/*! ./IconBase.js */ "iisS");

var _IconBase2 = _interopRequireDefault(_IconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TraceTypeSplomIcon = function TraceTypeSplomIcon(props) {
    return _react2.default.createElement(
        _IconBase2.default,
        _extends({ viewBox: '0 0 1360 1360' }, props),
        _react2.default.createElement('path', { fill: '#119DFF', d: 'M1228.136 100.738H142.678c-13.995 0-25.34 11.345-25.34 25.34v353.428c-.406 1.799-.638 3.666-.638 5.587s.232 3.788.638 5.587v358.063a25.342 25.342 0 0 0-.638 5.588c0 1.921.232 3.787.638 5.587v351.618c0 13.995 11.345 25.34 25.34 25.34h1085.458c13.995 0 25.34-11.345 25.34-25.34V126.078c0-13.995-11.345-25.34-25.34-25.34zM522.775 828.992V510.434h318.557v318.559H522.775zm318.557 50.68v306.525H522.775V879.672h318.557zM168.018 510.434h304.078v318.558H168.018V510.434zm354.757-50.68V151.418h318.557v308.336H522.775zm369.237 50.68h310.784v318.559H892.012V510.434zm310.784-50.68H892.012V151.418h310.784v308.336zM472.095 151.418v308.336H168.018V151.418h304.077zM168.018 879.672h304.078v306.525H168.018V879.672zm723.994 306.525V879.672h310.784v306.525H892.012z' }),
        _react2.default.createElement('path', { fill: '#09FFFF', d: 'M208.282 1104.347c13.151-13.15 34.473-13.15 47.622 0 13.153 13.15 13.153 34.473 0 47.623-13.149 13.151-34.471 13.151-47.622 0-13.153-13.151-13.153-34.473 0-47.623zM325.674 931.91c28.12-28.129 73.727-28.129 101.854 0 28.12 28.12 28.12 73.725 0 101.847-28.127 28.129-73.734 28.129-101.854 0-28.126-28.122-28.126-73.727 0-101.847zM387.282 1104.347c13.147-13.15 34.471-13.15 47.622 0 13.151 13.15 13.151 34.475 0 47.623-13.15 13.151-34.475 13.151-47.622 0-13.151-13.149-13.151-34.473 0-47.623z' }),
        _react2.default.createElement('path', { fill: '#119DFF', d: 'M208.281 925.345c13.149-13.148 34.473-13.148 47.624 0 13.151 13.151 13.151 34.475 0 47.626-13.151 13.148-34.475 13.148-47.624 0-13.149-13.152-13.149-34.475 0-47.626z' }),
        _react2.default.createElement('circle', { fill: '#119DFF', cx: '595.908', cy: '949.158', r: '33.675' }),
        _react2.default.createElement('circle', { fill: '#09FFFF', cx: '595.907', cy: '1128.158', r: '33.675' }),
        _react2.default.createElement('path', { fill: '#119DFF', d: 'M798.722 1073.902c21.554 21.555 21.554 56.511 0 78.067-21.56 21.558-56.513 21.558-78.069 0-21.557-21.557-21.557-56.513 0-78.067 21.556-21.553 56.509-21.553 78.069 0z' }),
        _react2.default.createElement('circle', { fill: '#119DFF', cx: '231.272', cy: '582.929', r: '33.674' }),
        _react2.default.createElement('path', { fill: '#09FFFF', d: 'M364.205 630.639c23.534 23.53 23.534 61.688 0 85.224-23.529 23.53-61.691 23.53-85.221 0-23.534-23.536-23.534-61.694 0-85.224 23.529-23.534 61.691-23.534 85.221 0z' }),
        _react2.default.createElement('circle', { fill: '#119DFF', cx: '231.272', cy: '761.929', r: '33.675' }),
        _react2.default.createElement('circle', { fill: '#119DFF', cx: '410.273', cy: '761.929', r: '33.676' }),
        _react2.default.createElement('path', { fill: '#09FFFF', d: 'M1160.494 244.144c-13.15 13.151-34.473 13.151-47.621 0-13.152-13.15-13.152-34.473 0-47.623 13.148-13.151 34.471-13.151 47.621 0 13.153 13.15 13.153 34.472 0 47.623z' }),
        _react2.default.createElement('circle', { fill: '#119DFF', cx: '957.683', cy: '220.332', r: '33.675' }),
        _react2.default.createElement('path', { fill: '#09FFFF', d: 'M981.495 423.146c-13.149 13.148-34.473 13.148-47.624 0-13.15-13.151-13.15-34.475 0-47.625 13.151-13.149 34.475-13.149 47.624 0 13.149 13.15 13.149 34.474 0 47.625z' }),
        _react2.default.createElement('path', { fill: '#119DFF', d: 'M1076.321 338.152c-16.09 16.091-42.185 16.091-58.28 0-16.092-16.094-16.092-42.189 0-58.283 16.096-16.091 42.19-16.091 58.28 0 16.092 16.094 16.092 42.189 0 58.283z' }),
        _react2.default.createElement('circle', { fill: '#119DFF', cx: '772.868', cy: '399.333', r: '33.674' }),
        _react2.default.createElement('path', { fill: '#119DFF', d: 'M686.262 304.905c-28.111-28.106-28.111-73.687 0-101.797 28.109-28.106 73.691-28.106 101.796 0 28.113 28.11 28.113 73.691 0 101.797-28.105 28.106-73.687 28.106-101.796 0zM570.055 244.144c-13.148-13.149-13.148-34.473 0-47.624 13.151-13.151 34.475-13.151 47.626 0 13.148 13.15 13.148 34.475 0 47.624-13.151 13.149-34.474 13.149-47.626 0z' }),
        _react2.default.createElement('path', { fill: '#09FFFF', d: 'M1113.691 789.371c-13.15-13.15-13.15-34.471 0-47.621s34.475-13.15 47.623 0c13.151 13.15 13.151 34.471 0 47.621-13.148 13.154-34.472 13.154-47.623 0z' }),
        _react2.default.createElement('circle', { fill: '#119DFF', cx: '1047.183', cy: '675.24', r: '23.151' }),
        _react2.default.createElement('path', { fill: '#119DFF', d: 'M1082.674 641.393c-21.72-21.716-21.72-56.928 0-78.644 21.713-21.711 56.927-21.711 78.639 0 21.721 21.716 21.721 56.928 0 78.644-21.712 21.711-56.926 21.711-78.639 0z' }),
        _react2.default.createElement('path', { fill: '#09FFFF', d: 'M934.689 610.374c-13.146-13.151-13.146-34.475 0-47.625 13.152-13.151 34.475-13.151 47.626 0 13.148 13.151 13.148 34.475 0 47.625-13.151 13.147-34.473 13.147-47.626 0z' }),
        _react2.default.createElement('circle', { fill: '#09FFFF', cx: '593.867', cy: '309.011', r: '15.942' }),
        _react2.default.createElement('circle', { fill: '#119DFF', cx: '958.503', cy: '309.012', r: '20.059' }),
        _react2.default.createElement('circle', { fill: '#119DFF', cx: '1137.502', cy: '399.333', r: '20.059' }),
        _react2.default.createElement('circle', { fill: '#09FFFF', cx: '1047.182', cy: '220.332', r: '20.326' }),
        _react2.default.createElement('circle', { fill: '#119DFF', cx: '321.593', cy: '1128.156', r: '21.759' }),
        _react2.default.createElement('circle', { fill: '#119DFF', cx: '686.228', cy: '1037.833', r: '21.278' }),
        _react2.default.createElement('path', { fill: '#119DFF', d: 'M607.18 1026.563c6.225 6.223 6.225 16.319 0 22.545-6.226 6.226-16.32 6.226-22.546 0s-6.226-16.322 0-22.545c6.226-6.225 16.321-6.225 22.546 0z' })
    );
};

exports.default = TraceTypeSplomIcon;

/***/ }),

/***/ "zT9C":
/*!************************************************!*\
  !*** ./node_modules/lodash.clonedeep/index.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global, module) {/**
 * lodash (Custom Build) <https://lodash.com/>
 * Build: `lodash modularize exports="npm" -o ./`
 * Copyright jQuery Foundation and other contributors <https://jquery.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
 */

/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;

/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';

/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;

/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
    arrayTag = '[object Array]',
    boolTag = '[object Boolean]',
    dateTag = '[object Date]',
    errorTag = '[object Error]',
    funcTag = '[object Function]',
    genTag = '[object GeneratorFunction]',
    mapTag = '[object Map]',
    numberTag = '[object Number]',
    objectTag = '[object Object]',
    promiseTag = '[object Promise]',
    regexpTag = '[object RegExp]',
    setTag = '[object Set]',
    stringTag = '[object String]',
    symbolTag = '[object Symbol]',
    weakMapTag = '[object WeakMap]';

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 `RegExp`
 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
 */
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;

/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;

/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;

/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;

/** 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;

/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;

/** 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 = typeof exports == 'object' && exports && !exports.nodeType && exports;

/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;

/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;

/**
 * Adds the key-value `pair` to `map`.
 *
 * @private
 * @param {Object} map The map to modify.
 * @param {Array} pair The key-value pair to add.
 * @returns {Object} Returns `map`.
 */
function addMapEntry(map, pair) {
  // Don't return `map.set` because it's not chainable in IE 11.
  map.set(pair[0], pair[1]);
  return map;
}

/**
 * Adds `value` to `set`.
 *
 * @private
 * @param {Object} set The set to modify.
 * @param {*} value The value to add.
 * @returns {Object} Returns `set`.
 */
function addSetEntry(set, value) {
  // Don't return `set.add` because it's not chainable in IE 11.
  set.add(value);
  return set;
}

/**
 * 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 ? array.length : 0;

  while (++index < length) {
    if (iteratee(array[index], index, array) === false) {
      break;
    }
  }
  return array;
}

/**
 * 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 ? array.length : 0;

  if (initAccum && length) {
    accumulator = array[++index];
  }
  while (++index < length) {
    accumulator = iteratee(accumulator, array[index], index, array);
  }
  return accumulator;
}

/**
 * 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;
}

/**
 * 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 `value` is a host object in IE < 9.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
 */
function isHostObject(value) {
  // Many host objects are `Object` objects that can coerce to strings
  // despite having improperly defined `toString` methods.
  var result = false;
  if (value != null && typeof value.toString != 'function') {
    try {
      result = !!(value + '');
    } catch (e) {}
  }
  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));
  };
}

/**
 * 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;
}

/** 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 = root['__core-js_shared__'];

/** 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 decompiled source of functions. */
var funcToString = funcProto.toString;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var objectToString = objectProto.toString;

/** 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 ? root.Buffer : undefined,
    Symbol = root.Symbol,
    Uint8Array = root.Uint8Array,
    getPrototype = overArg(Object.getPrototypeOf, Object),
    objectCreate = Object.create,
    propertyIsEnumerable = objectProto.propertyIsEnumerable,
    splice = arrayProto.splice;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols,
    nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
    nativeKeys = overArg(Object.keys, Object);

/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView'),
    Map = getNative(root, 'Map'),
    Promise = getNative(root, 'Promise'),
    Set = getNative(root, 'Set'),
    WeakMap = getNative(root, 'WeakMap'),
    nativeCreate = getNative(Object, 'create');

/** 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;

/**
 * Creates a hash object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function Hash(entries) {
  var index = -1,
      length = entries ? entries.length : 0;

  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) : {};
}

/**
 * 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) {
  return this.has(key) && delete this.__data__[key];
}

/**
 * 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__;
  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 ? entries.length : 0;

  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__ = [];
}

/**
 * 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);
  }
  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) {
    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 ? entries.length : 0;

  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.__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) {
  return getMapData(this, key)['delete'](key);
}

/**
 * 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) {
  getMapData(this, key).set(key, value);
  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 a stack cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function Stack(entries) {
  this.__data__ = new ListCache(entries);
}

/**
 * Removes all key-value entries from the stack.
 *
 * @private
 * @name clear
 * @memberOf Stack
 */
function stackClear() {
  this.__data__ = new ListCache;
}

/**
 * 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) {
  return this.__data__['delete'](key);
}

/**
 * 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 cache = this.__data__;
  if (cache instanceof ListCache) {
    var pairs = cache.__data__;
    if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
      pairs.push([key, value]);
      return this;
    }
    cache = this.__data__ = new MapCache(pairs);
  }
  cache.set(key, value);
  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) {
  // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
  // Safari 9 makes `arguments.length` enumerable in strict mode.
  var result = (isArray(value) || isArguments(value))
    ? baseTimes(value.length, String)
    : [];

  var length = result.length,
      skipIndexes = !!length;

  for (var key in value) {
    if ((inherited || hasOwnProperty.call(value, key)) &&
        !(skipIndexes && (key == 'length' || isIndex(key, length)))) {
      result.push(key);
    }
  }
  return result;
}

/**
 * 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))) {
    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;
}

/**
 * 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 `_.clone` and `_.cloneDeep` which tracks
 * traversed objects.
 *
 * @private
 * @param {*} value The value to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @param {boolean} [isFull] Specify a clone including 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, isDeep, isFull, customizer, key, object, stack) {
  var result;
  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)) {
      if (isHostObject(value)) {
        return object ? value : {};
      }
      result = initCloneObject(isFunc ? {} : value);
      if (!isDeep) {
        return copySymbols(value, baseAssign(result, value));
      }
    } else {
      if (!cloneableTags[tag]) {
        return object ? value : {};
      }
      result = initCloneByTag(value, tag, baseClone, 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 (!isArr) {
    var props = isFull ? getAllKeys(value) : keys(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, isDeep, isFull, customizer, key, value, stack));
  });
  return result;
}

/**
 * The base implementation of `_.create` without support for assigning
 * properties to the created object.
 *
 * @private
 * @param {Object} prototype The object to inherit from.
 * @returns {Object} Returns the new object.
 */
function baseCreate(proto) {
  return isObject(proto) ? objectCreate(proto) : {};
}

/**
 * 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`.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */
function baseGetTag(value) {
  return objectToString.call(value);
}

/**
 * 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) || isHostObject(value)) ? reIsNative : reIsHostCtor;
  return pattern.test(toSource(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;
}

/**
 * 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 result = new buffer.constructor(buffer.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 `map`.
 *
 * @private
 * @param {Object} map The map to clone.
 * @param {Function} cloneFunc The function to clone values.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the cloned map.
 */
function cloneMap(map, isDeep, cloneFunc) {
  var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map);
  return arrayReduce(array, addMapEntry, new map.constructor);
}

/**
 * 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 `set`.
 *
 * @private
 * @param {Object} set The set to clone.
 * @param {Function} cloneFunc The function to clone values.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the cloned set.
 */
function cloneSet(set, isDeep, cloneFunc) {
  var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set);
  return arrayReduce(array, addSetEntry, new set.constructor);
}

/**
 * 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);
}

/**
 * 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) {
  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;

    assignValue(object, key, newValue === undefined ? source[key] : newValue);
  }
  return object;
}

/**
 * Copies own symbol properties 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);
}

/**
 * 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);
}

/**
 * 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 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;
}

/**
 * Creates an array of the own enumerable symbol properties of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of symbols.
 */
var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray;

/**
 * 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,
// for data views in Edge < 14, and promises in Node.js.
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 = objectToString.call(value),
        Ctor = result == objectTag ? value.constructor : undefined,
        ctorString = Ctor ? toSource(Ctor) : undefined;

    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;
  };
}

/**
 * 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 = 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`, `Number`, `RegExp`, or `String`.
 *
 * @private
 * @param {Object} object The object to clone.
 * @param {string} tag The `toStringTag` of the object to clone.
 * @param {Function} cloneFunc The function to clone values.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the initialized clone.
 */
function initCloneByTag(object, tag, cloneFunc, 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 cloneMap(object, isDeep, cloneFunc);

    case numberTag:
    case stringTag:
      return new Ctor(object);

    case regexpTag:
      return cloneRegExp(object);

    case setTag:
      return cloneSet(object, isDeep, cloneFunc);

    case symbolTag:
      return cloneSymbol(object);
  }
}

/**
 * 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) {
  length = length == null ? MAX_SAFE_INTEGER : length;
  return !!length &&
    (typeof value == 'number' || reIsUint.test(value)) &&
    (value > -1 && value % 1 == 0 && value < length);
}

/**
 * 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 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 `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;
}

/**
 * Converts `func` to its source code.
 *
 * @private
 * @param {Function} func The function to process.
 * @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 '';
}

/**
 * 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, true, true);
}

/**
 * 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 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
 */
function isArguments(value) {
  // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
  return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
    (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
}

/**
 * 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 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 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 `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) {
  // The use of `Object#toString` avoids issues with the `typeof` operator
  // in Safari 8-9 which returns 'object' for typed array and other constructors.
  var tag = isObject(value) ? objectToString.call(value) : '';
  return tag == funcTag || tag == genTag;
}

/**
 * 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 && (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 && typeof value == 'object';
}

/**
 * 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);
}

/**
 * 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;
}

module.exports = cloneDeep;

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "yLpj"), __webpack_require__(/*! ./../webpack/buildin/module.js */ "YuTi")(module)))

/***/ }),

/***/ "zZ0H":
/*!*****************************************!*\
  !*** ./node_modules/lodash/identity.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * 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;
}

module.exports = identity;


/***/ }),

/***/ "zZGF":
/*!**********************************************************!*\
  !*** ./node_modules/browserify-sign/browser/curves.json ***!
  \**********************************************************/
/*! exports provided: 1.3.132.0.10, 1.3.132.0.33, 1.2.840.10045.3.1.1, 1.2.840.10045.3.1.7, 1.3.132.0.34, 1.3.132.0.35, default */
/***/ (function(module) {

module.exports = {"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"};

/***/ }),

/***/ "zZPE":
/*!****************************************************!*\
  !*** ./node_modules/lodash.isplainobject/index.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * lodash (Custom Build) <https://lodash.com/>
 * Build: `lodash modularize exports="npm" -o ./`
 * Copyright jQuery Foundation and other contributors <https://jquery.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
 */

/** `Object#toString` result references. */
var objectTag = '[object Object]';

/**
 * Checks if `value` is a host object in IE < 9.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
 */
function isHostObject(value) {
  // Many host objects are `Object` objects that can coerce to strings
  // despite having improperly defined `toString` methods.
  var result = false;
  if (value != null && typeof value.toString != 'function') {
    try {
      result = !!(value + '');
    } catch (e) {}
  }
  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));
  };
}

/** 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);

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var objectToString = objectProto.toString;

/** Built-in value references. */
var getPrototype = overArg(Object.getPrototypeOf, Object);

/**
 * 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 && typeof value == '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) ||
      objectToString.call(value) != objectTag || isHostObject(value)) {
    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;


/***/ }),

/***/ "zcT5":
/*!*****************************************************************************************!*\
  !*** ./node_modules/react-chart-editor/lib/components/containers/TransformAccordion.js ***!
  \*****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _PlotlyFold = __webpack_require__(/*! ./PlotlyFold */ "mQPs");

var _PlotlyFold2 = _interopRequireDefault(_PlotlyFold);

var _PlotlyPanel = __webpack_require__(/*! ./PlotlyPanel */ "54u7");

var _PlotlyPanel2 = _interopRequireDefault(_PlotlyPanel);

var _propTypes = __webpack_require__(/*! prop-types */ "17x9");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __webpack_require__(/*! react */ "q1tI");

var _react2 = _interopRequireDefault(_react);

var _lib = __webpack_require__(/*! ../../lib */ "RXjw");

var _PanelEmpty = __webpack_require__(/*! ./PanelEmpty */ "o21U");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var TransformFold = (0, _lib.connectTransformToTrace)(_PlotlyFold2.default);

var TransformAccordion = function (_Component) {
  _inherits(TransformAccordion, _Component);

  function TransformAccordion() {
    _classCallCheck(this, TransformAccordion);

    return _possibleConstructorReturn(this, (TransformAccordion.__proto__ || Object.getPrototypeOf(TransformAccordion)).apply(this, arguments));
  }

  _createClass(TransformAccordion, [{
    key: 'render',
    value: function render() {
      var _context = this.context,
          _context$fullContaine = _context.fullContainer.transforms,
          transforms = _context$fullContaine === undefined ? [] : _context$fullContaine,
          _ = _context.localize,
          container = _context.container,
          dataSourceOptions = _context.dataSourceOptions;
      var children = this.props.children;


      var transformTypes = [{ label: _('Filter'), type: 'filter' }, { label: _('Split'), type: 'groupby' }, { label: _('Aggregate'), type: 'aggregate' }, { label: _('Sort'), type: 'sort' }];

      var transformBy = container.transforms && container.transforms.map(function (tr) {
        var foldNameSuffix = '';
        if (tr.groupssrc) {
          var groupssrc = dataSourceOptions && dataSourceOptions.find(function (d) {
            return d.value === tr.groupssrc;
          });
          foldNameSuffix = ': ' + (groupssrc && groupssrc.label ? groupssrc.label : tr.groupssrc);
        } else if (tr.targetsrc) {
          var targetsrc = dataSourceOptions && dataSourceOptions.find(function (d) {
            return d.value === tr.targetsrc;
          });
          foldNameSuffix = ': ' + (targetsrc && targetsrc.label ? targetsrc.label : tr.targetsrc);
        }
        return foldNameSuffix;
      });

      var filteredTransforms = transforms.filter(function (_ref) {
        var type = _ref.type;
        return Boolean(type);
      });
      var content = filteredTransforms.length && filteredTransforms.map(function (tr, i) {
        return _react2.default.createElement(
          TransformFold,
          {
            key: i,
            transformIndex: i,
            name: '' + transformTypes.filter(function (_ref2) {
              var type = _ref2.type;
              return type === tr.type;
            })[0].label + (transformBy && transformBy[i]),
            canDelete: true
          },
          children
        );
      });

      // cannot have 2 Split transforms on one trace:
      // https://github.com/plotly/plotly.js/issues/1742
      var addActionOptions = container.transforms && container.transforms.some(function (t) {
        return t.type === 'groupby';
      }) ? transformTypes.filter(function (t) {
        return t.type !== 'groupby';
      }) : transformTypes;

      var addAction = {
        label: _('Transform'),
        handler: addActionOptions.map(function (_ref3) {
          var label = _ref3.label,
              type = _ref3.type;

          return {
            label: label,
            handler: function handler(context) {
              var fullContainer = context.fullContainer,
                  updateContainer = context.updateContainer;

              if (updateContainer) {
                var transformIndex = Array.isArray(fullContainer.transforms) ? fullContainer.transforms.length : 0;
                var key = 'transforms[' + transformIndex + ']';

                var payload = { type: type };
                if (type === 'filter') {
                  payload.target = [];
                  payload.targetsrc = null;
                } else if (type !== 'sort') {
                  payload.groupssrc = null;
                  payload.groups = null;
                }

                if (type === 'groupby') {
                  payload.styles = [];
                }

                updateContainer(_defineProperty({}, key, payload));
              }
            }
          };
        })
      };

      return _react2.default.createElement(
        _PlotlyPanel2.default,
        { addAction: addAction },
        content ? content : _react2.default.createElement(
          _PanelEmpty.PanelMessage,
          { icon: null },
          _react2.default.createElement(
            'div',
            { style: { textAlign: 'left' } },
            _react2.default.createElement(
              'p',
              null,
              _react2.default.createElement(
                'strong',
                null,
                _('Filter')
              ),
              ' ',
              _(' transforms allow you to filter data out from a trace.')
            ),
            _react2.default.createElement(
              'p',
              null,
              _react2.default.createElement(
                'strong',
                null,
                _('Split')
              ),
              ' ',
              _(' transforms allow you to create multiple traces from one source trace, so as to style them differently.')
            ),
            _react2.default.createElement(
              'p',
              null,
              _react2.default.createElement(
                'strong',
                null,
                _('Aggregate')
              ),
              ' ',
              _(' transforms allow you to summarize a trace using an aggregate function like "average" or "minimum".')
            ),
            _react2.default.createElement(
              'p',
              null,
              _react2.default.createElement(
                'strong',
                null,
                _('Sort')
              ),
              ' ',
              _(' transforms allow you to sort a trace, so as to control marker overlay or line connection order.')
            )
          ),
          _react2.default.createElement(
            'p',
            null,
            _('Click on the + button above to add a transform.')
          )
        )
      );
    }
  }]);

  return TransformAccordion;
}(_react.Component);

TransformAccordion.contextTypes = {
  fullContainer: _propTypes2.default.object,
  localize: _propTypes2.default.func,
  container: _propTypes2.default.object,
  dataSourceOptions: _propTypes2.default.array
};

TransformAccordion.propTypes = {
  children: _propTypes2.default.node
};

exports.default = TransformAccordion;
//# sourceMappingURL=TransformAccordion.js.map

/***/ }),

/***/ "zd6B":
/*!********************************************************!*\
  !*** ./node_modules/@jupyterlab/tooltip/lib/widget.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const widgets_1 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const widgets_2 = __webpack_require__(/*! @phosphor/widgets */ "pif5");
const apputils_1 = __webpack_require__(/*! @jupyterlab/apputils */ "AQjG");
const rendermime_1 = __webpack_require__(/*! @jupyterlab/rendermime */ "Towz");
/**
 * The class name added to each tooltip.
 */
const TOOLTIP_CLASS = 'jp-Tooltip';
/**
 * The class name added to the tooltip content.
 */
const CONTENT_CLASS = 'jp-Tooltip-content';
/**
 * The class added to the body when a tooltip exists on the page.
 */
const BODY_CLASS = 'jp-mod-tooltip';
/**
 * The minimum height of a tooltip widget.
 */
const MIN_HEIGHT = 20;
/**
 * The maximum height of a tooltip widget.
 */
const MAX_HEIGHT = 250;
/**
 * A flag to indicate that event handlers are caught in the capture phase.
 */
const USE_CAPTURE = true;
/**
 * A tooltip widget.
 */
class Tooltip extends widgets_2.Widget {
    /**
     * Instantiate a tooltip.
     */
    constructor(options) {
        super();
        this._content = null;
        const layout = (this.layout = new widgets_1.PanelLayout());
        const model = new rendermime_1.MimeModel({ data: options.bundle });
        this.anchor = options.anchor;
        this.addClass(TOOLTIP_CLASS);
        this._editor = options.editor;
        this._rendermime = options.rendermime;
        const mimeType = this._rendermime.preferredMimeType(options.bundle, 'any');
        if (!mimeType) {
            return;
        }
        this._content = this._rendermime.createRenderer(mimeType);
        this._content.renderModel(model);
        this._content.addClass(CONTENT_CLASS);
        layout.addWidget(this._content);
    }
    /**
     * Dispose of the resources held by the widget.
     */
    dispose() {
        if (this._content) {
            this._content.dispose();
            this._content = null;
        }
        super.dispose();
    }
    /**
     * Handle the DOM events for the widget.
     *
     * @param event - The DOM event sent to the widget.
     *
     * #### Notes
     * This method implements the DOM `EventListener` interface and is
     * called in response to events on the dock panel's node. It should
     * not be called directly by user code.
     */
    handleEvent(event) {
        if (this.isHidden || this.isDisposed) {
            return;
        }
        const { node } = this;
        const target = event.target;
        switch (event.type) {
            case 'keydown':
                if (node.contains(target)) {
                    return;
                }
                this.dispose();
                break;
            case 'mousedown':
                if (node.contains(target)) {
                    this.activate();
                    return;
                }
                this.dispose();
                break;
            case 'scroll':
                this._evtScroll(event);
                break;
            default:
                break;
        }
    }
    /**
     * Handle `'activate-request'` messages.
     */
    onActivateRequest(msg) {
        this.node.tabIndex = -1;
        this.node.focus();
    }
    /**
     * Handle `'after-attach'` messages.
     */
    onAfterAttach(msg) {
        document.body.classList.add(BODY_CLASS);
        document.addEventListener('keydown', this, USE_CAPTURE);
        document.addEventListener('mousedown', this, USE_CAPTURE);
        this.anchor.node.addEventListener('scroll', this, USE_CAPTURE);
        this.update();
    }
    /**
     * Handle `before-detach` messages for the widget.
     */
    onBeforeDetach(msg) {
        document.body.classList.remove(BODY_CLASS);
        document.removeEventListener('keydown', this, USE_CAPTURE);
        document.removeEventListener('mousedown', this, USE_CAPTURE);
        this.anchor.node.removeEventListener('scroll', this, USE_CAPTURE);
    }
    /**
     * Handle `'update-request'` messages.
     */
    onUpdateRequest(msg) {
        this._setGeometry();
        super.onUpdateRequest(msg);
    }
    /**
     * Handle scroll events for the widget
     */
    _evtScroll(event) {
        // All scrolls except scrolls in the actual hover box node may cause the
        // referent editor that anchors the node to move, so the only scroll events
        // that can safely be ignored are ones that happen inside the hovering node.
        if (this.node.contains(event.target)) {
            return;
        }
        this.update();
    }
    /**
     * Set the geometry of the tooltip widget.
     */
    _setGeometry() {
        // Find the start of the current token for hover box placement.
        const editor = this._editor;
        const cursor = editor.getCursorPosition();
        const end = editor.getOffsetAt(cursor);
        const line = editor.getLine(cursor.line);
        if (!line) {
            return;
        }
        const tokens = line.substring(0, end).split(/\W+/);
        const last = tokens[tokens.length - 1];
        const start = last ? end - last.length : end;
        const position = editor.getPositionAt(start);
        if (!position) {
            return;
        }
        const anchor = editor.getCoordinateForPosition(position);
        const style = window.getComputedStyle(this.node);
        const paddingLeft = parseInt(style.paddingLeft, 10) || 0;
        // Calculate the geometry of the tooltip.
        apputils_1.HoverBox.setGeometry({
            anchor,
            host: editor.host,
            maxHeight: MAX_HEIGHT,
            minHeight: MIN_HEIGHT,
            node: this.node,
            offset: { horizontal: -1 * paddingLeft },
            privilege: 'below',
            style: style
        });
    }
}
exports.Tooltip = Tooltip;


/***/ }),

/***/ "zdsp":
/*!****************************************************************!*\
  !*** ./node_modules/@jupyterlab/faq-extension/style/index.css ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "PrNZ");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),

/***/ "ze2x":
/*!**************************************************************!*\
  !*** ./node_modules/react-day-picker/lib/src/LocaleUtils.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.formatDay = formatDay;
exports.formatMonthTitle = formatMonthTitle;
exports.formatWeekdayShort = formatWeekdayShort;
exports.formatWeekdayLong = formatWeekdayLong;
exports.getFirstDayOfWeek = getFirstDayOfWeek;
exports.getMonths = getMonths;
var WEEKDAYS_LONG = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

var WEEKDAYS_SHORT = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];

var MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

function formatDay(day) {
  return day.toDateString();
}

function formatMonthTitle(d) {
  return MONTHS[d.getMonth()] + ' ' + d.getFullYear();
}

function formatWeekdayShort(i) {
  return WEEKDAYS_SHORT[i];
}

function formatWeekdayLong(i) {
  return WEEKDAYS_LONG[i];
}

function getFirstDayOfWeek() {
  return 0;
}

function getMonths() {
  return MONTHS;
}

exports.default = {
  formatDay: formatDay,
  formatMonthTitle: formatMonthTitle,
  formatWeekdayShort: formatWeekdayShort,
  formatWeekdayLong: formatWeekdayLong,
  getFirstDayOfWeek: getFirstDayOfWeek,
  getMonths: getMonths
};
//# sourceMappingURL=LocaleUtils.js.map

/***/ }),

/***/ "zgGE":
/*!***********************************************************!*\
  !*** ./node_modules/@jupyterlab/completer/lib/handler.js ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
const coreutils_1 = __webpack_require__(/*! @jupyterlab/coreutils */ "hI0s");
const messaging_1 = __webpack_require__(/*! @phosphor/messaging */ "hpl1");
const signaling_1 = __webpack_require__(/*! @phosphor/signaling */ "qUp9");
/**
 * A class added to editors that can host a completer.
 */
const COMPLETER_ENABLED_CLASS = 'jp-mod-completer-enabled';
/**
 * A class added to editors that have an active completer.
 */
const COMPLETER_ACTIVE_CLASS = 'jp-mod-completer-active';
/**
 * A completion handler for editors.
 */
class CompletionHandler {
    /**
     * Construct a new completion handler for a widget.
     */
    constructor(options) {
        this._editor = null;
        this._enabled = false;
        this._pending = 0;
        this._isDisposed = false;
        this.completer = options.completer;
        this.completer.selected.connect(this.onCompletionSelected, this);
        this.completer.visibilityChanged.connect(this.onVisibilityChanged, this);
        this._connector = options.connector;
    }
    /**
     * The data connector used to populate completion requests.
     *
     * #### Notes
     * The only method of this connector that will ever be called is `fetch`, so
     * it is acceptable for the other methods to be simple functions that return
     * rejected promises.
     */
    get connector() {
        return this._connector;
    }
    set connector(connector) {
        this._connector = connector;
    }
    /**
     * The editor used by the completion handler.
     */
    get editor() {
        return this._editor;
    }
    set editor(newValue) {
        if (newValue === this._editor) {
            return;
        }
        let editor = this._editor;
        // Clean up and disconnect from old editor.
        if (editor && !editor.isDisposed) {
            const model = editor.model;
            editor.host.classList.remove(COMPLETER_ENABLED_CLASS);
            model.selections.changed.disconnect(this.onSelectionsChanged, this);
            model.value.changed.disconnect(this.onTextChanged, this);
        }
        // Reset completer state.
        this.completer.reset();
        this.completer.editor = newValue;
        // Update the editor and signal connections.
        editor = this._editor = newValue;
        if (editor) {
            const model = editor.model;
            this._enabled = false;
            model.selections.changed.connect(this.onSelectionsChanged, this);
            model.value.changed.connect(this.onTextChanged, this);
            // On initial load, manually check the cursor position.
            this.onSelectionsChanged();
        }
    }
    /**
     * Get whether the completion handler is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources used by the handler.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        signaling_1.Signal.clearData(this);
    }
    /**
     * Invoke the handler and launch a completer.
     */
    invoke() {
        messaging_1.MessageLoop.sendMessage(this, CompletionHandler.Msg.InvokeRequest);
    }
    /**
     * Process a message sent to the completion handler.
     */
    processMessage(msg) {
        switch (msg.type) {
            case CompletionHandler.Msg.InvokeRequest.type:
                this.onInvokeRequest(msg);
                break;
            default:
                break;
        }
    }
    /**
     * Get the state of the text editor at the given position.
     */
    getState(editor, position) {
        return {
            text: editor.model.value.text,
            lineHeight: editor.lineHeight,
            charWidth: editor.charWidth,
            line: position.line,
            column: position.column
        };
    }
    /**
     * Handle a completion selected signal from the completion widget.
     */
    onCompletionSelected(completer, value) {
        const model = completer.model;
        const editor = this._editor;
        if (!editor || !model) {
            return;
        }
        const patch = model.createPatch(value);
        if (!patch) {
            return;
        }
        const { offset, text } = patch;
        editor.model.value.text = text;
        const position = editor.getPositionAt(offset);
        if (position) {
            editor.setCursorPosition(position);
        }
    }
    /**
     * Handle `invoke-request` messages.
     */
    onInvokeRequest(msg) {
        // If there is no completer model, bail.
        if (!this.completer.model) {
            return;
        }
        // If a completer session is already active, bail.
        if (this.completer.model.original) {
            return;
        }
        let editor = this._editor;
        if (editor) {
            this._makeRequest(editor.getCursorPosition()).catch(reason => {
                console.log('Invoke request bailed', reason);
            });
        }
    }
    /**
     * Handle selection changed signal from an editor.
     *
     * #### Notes
     * If a sub-class reimplements this method, then that class must either call
     * its super method or it must take responsibility for adding and removing
     * the completer completable class to the editor host node.
     *
     * Despite the fact that the editor widget adds a class whenever there is a
     * primary selection, this method checks independently for two reasons:
     *
     * 1. The editor widget connects to the same signal to add that class, so
     *    there is no guarantee that the class will be added before this method
     *    is invoked so simply checking for the CSS class's existence is not an
     *    option. Secondarily, checking the editor state should be faster than
     *    querying the DOM in either case.
     * 2. Because this method adds a class that indicates whether completer
     *    functionality ought to be enabled, relying on the behavior of the
     *    `jp-mod-has-primary-selection` to filter out any editors that have
     *    a selection means the semantic meaning of `jp-mod-completer-enabled`
     *    is obscured because there may be cases where the enabled class is added
     *    even though the completer is not available.
     */
    onSelectionsChanged() {
        const model = this.completer.model;
        const editor = this._editor;
        if (!editor) {
            return;
        }
        const host = editor.host;
        // If there is no model, return.
        if (!model) {
            this._enabled = false;
            host.classList.remove(COMPLETER_ENABLED_CLASS);
            return;
        }
        const position = editor.getCursorPosition();
        const line = editor.getLine(position.line);
        if (!line) {
            this._enabled = false;
            model.reset(true);
            host.classList.remove(COMPLETER_ENABLED_CLASS);
            return;
        }
        const { start, end } = editor.getSelection();
        // If there is a text selection, return.
        if (start.column !== end.column || start.line !== end.line) {
            this._enabled = false;
            model.reset(true);
            host.classList.remove(COMPLETER_ENABLED_CLASS);
            return;
        }
        // If the part of the line before the cursor is white space, return.
        if (line.slice(0, position.column).match(/^\s*$/)) {
            this._enabled = false;
            model.reset(true);
            host.classList.remove(COMPLETER_ENABLED_CLASS);
            return;
        }
        // Enable completion.
        if (!this._enabled) {
            this._enabled = true;
            host.classList.add(COMPLETER_ENABLED_CLASS);
        }
        // Dispatch the cursor change.
        model.handleCursorChange(this.getState(editor, editor.getCursorPosition()));
    }
    /**
     * Handle a text changed signal from an editor.
     */
    onTextChanged() {
        const model = this.completer.model;
        if (!model || !this._enabled) {
            return;
        }
        // If there is a text selection, no completion is allowed.
        const editor = this.editor;
        if (!editor) {
            return;
        }
        const { start, end } = editor.getSelection();
        if (start.column !== end.column || start.line !== end.line) {
            return;
        }
        // Dispatch the text change.
        model.handleTextChange(this.getState(editor, editor.getCursorPosition()));
    }
    /**
     * Handle a visibility change signal from a completer widget.
     */
    onVisibilityChanged(completer) {
        // Completer is not active.
        if (completer.isDisposed || completer.isHidden) {
            if (this._editor) {
                this._editor.host.classList.remove(COMPLETER_ACTIVE_CLASS);
                this._editor.focus();
            }
            return;
        }
        // Completer is active.
        if (this._editor) {
            this._editor.host.classList.add(COMPLETER_ACTIVE_CLASS);
        }
    }
    /**
     * Make a completion request.
     */
    _makeRequest(position) {
        const editor = this.editor;
        if (!editor) {
            return Promise.reject(new Error('No active editor'));
        }
        const text = editor.model.value.text;
        const offset = coreutils_1.Text.jsIndexToCharIndex(editor.getOffsetAt(position), text);
        const pending = ++this._pending;
        const state = this.getState(editor, position);
        const request = { text, offset };
        return this._connector
            .fetch(request)
            .then(reply => {
            if (this.isDisposed) {
                throw new Error('Handler is disposed');
            }
            // If a newer completion request has created a pending request, bail.
            if (pending !== this._pending) {
                throw new Error('A newer completion request is pending');
            }
            this._onReply(state, reply);
        })
            .catch(reason => {
            // Completion request failures or negative results fail silently.
            const model = this.completer.model;
            if (model) {
                model.reset(true);
            }
        });
    }
    /**
     * Receive a completion reply from the connector.
     *
     * @param state - The state of the editor when completion request was made.
     *
     * @param reply - The API response returned for a completion request.
     */
    _onReply(state, reply) {
        const model = this.completer.model;
        const text = state.text;
        if (!model) {
            return;
        }
        // Update the original request.
        model.original = state;
        // Dedupe the matches.
        const matches = [];
        const matchSet = new Set(reply.matches || []);
        if (reply.matches) {
            matchSet.forEach(match => {
                matches.push(match);
            });
        }
        // Extract the optional type map. The current implementation uses
        // _jupyter_types_experimental which provide string type names. We make no
        // assumptions about the names of the types, so other kernels can provide
        // their own types.
        // Even though the `metadata` field is required, it has historically not
        // been used. Defensively check if it exists.
        const metadata = reply.metadata || {};
        const types = metadata._jupyter_types_experimental;
        const typeMap = {};
        if (types) {
            types.forEach((item) => {
                // For some reason the _jupyter_types_experimental list has two entries
                // for each match, with one having a type of "<unknown>". Discard those
                // and use undefined to indicate an unknown type.
                const text = item.text;
                const type = item.type;
                if (matchSet.has(text) && type !== '<unknown>') {
                    typeMap[text] = type;
                }
            });
        }
        // Update the options, including the type map.
        model.setOptions(matches, typeMap);
        // Update the cursor.
        model.cursor = {
            start: coreutils_1.Text.charIndexToJsIndex(reply.start, text),
            end: coreutils_1.Text.charIndexToJsIndex(reply.end, text)
        };
    }
}
exports.CompletionHandler = CompletionHandler;
/**
 * A namespace for cell completion handler statics.
 */
(function (CompletionHandler) {
    /**
     * A namespace for completion handler messages.
     */
    let Msg;
    (function (Msg) {
        /* tslint:disable */
        /**
         * A singleton `'invoke-request'` message.
         */
        Msg.InvokeRequest = new messaging_1.Message('invoke-request');
        /* tslint:enable */
    })(Msg = CompletionHandler.Msg || (CompletionHandler.Msg = {}));
})(CompletionHandler = exports.CompletionHandler || (exports.CompletionHandler = {}));


/***/ }),

/***/ "zjAe":
/*!*********************************************************!*\
  !*** ./node_modules/xterm/lib/utils/RenderDebouncer.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var RenderDebouncer = (function () {
    function RenderDebouncer(_terminal, _callback) {
        this._terminal = _terminal;
        this._callback = _callback;
        this._animationFrame = null;
    }
    RenderDebouncer.prototype.dispose = function () {
        if (this._animationFrame) {
            window.cancelAnimationFrame(this._animationFrame);
            this._animationFrame = null;
        }
    };
    RenderDebouncer.prototype.refresh = function (rowStart, rowEnd) {
        var _this = this;
        rowStart = rowStart || 0;
        rowEnd = rowEnd || this._terminal.rows - 1;
        this._rowStart = this._rowStart !== undefined ? Math.min(this._rowStart, rowStart) : rowStart;
        this._rowEnd = this._rowEnd !== undefined ? Math.max(this._rowEnd, rowEnd) : rowEnd;
        if (this._animationFrame) {
            return;
        }
        this._animationFrame = window.requestAnimationFrame(function () { return _this._innerRefresh(); });
    };
    RenderDebouncer.prototype._innerRefresh = function () {
        this._rowStart = Math.max(this._rowStart, 0);
        this._rowEnd = Math.min(this._rowEnd, this._terminal.rows - 1);
        this._callback(this._rowStart, this._rowEnd);
        this._rowStart = null;
        this._rowEnd = null;
        this._animationFrame = null;
    };
    return RenderDebouncer;
}());
exports.RenderDebouncer = RenderDebouncer;

//# sourceMappingURL=RenderDebouncer.js.map


/***/ }),

/***/ "zkAc":
/*!******************************************************************************************!*\
  !*** ./node_modules/css-loader!./node_modules/@jupyterlab/application/style/buttons.css ***!
  \******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(/*! ../../../css-loader/lib/css-base.js */ "I1BE")(false);
// imports


// module
exports.push([module.i, "/*-----------------------------------------------------------------------------\n| Variables\n|----------------------------------------------------------------------------*/\n\n:root {\n  --jp-flat-button-height: 24px;\n  --jp-flat-button-padding: 8px 12px;\n}\n\n/*-----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n\nbutton {\n  border-radius: var(--jp-border-radius);\n}\n\nbutton.jp-mod-styled.jp-mod-accept {\n  background: var(--jp-brand-color1);\n  color: white;\n  border: 1px solid var(--jp-brand-color1);\n}\n\nbutton.jp-mod-styled.jp-mod-reject {\n  background: var(--md-grey-500);\n  border: 1px solid var(--md-grey-500);\n  color: white;\n}\n\nbutton.jp-mod-styled.jp-mod-warn {\n  background: var(--jp-error-color1);\n  color: white;\n  border: 1px solid var(--jp-error-color1);\n}\n\n.jp-Button-flat {\n  text-decoration: none;\n  padding: var(--jp-flat-button-padding);\n  color: var(--jp-warn-color1);\n  font-weight: 500;\n  background-color: transparent;\n  height: var(--jp-private-running-shutdown-button-height);\n  line-height: var(--jp-private-running-shutdown-button-height);\n  transition: background-color 0.1s ease;\n  border-radius: 2px;\n}\n\n.jp-Button-flat:hover {\n  background-color: rgba(153, 153, 153, 0.1);\n}\n\n.jp-Button-flat:focus {\n  border: none;\n  box-shadow: none;\n  background-color: rgba(153, 153, 153, 0.2);\n}\n", ""]);

// exports


/***/ }),

/***/ "zlY5":
/*!*****************************************************************!*\
  !*** ./node_modules/draft-js/lib/getRangeBoundingClientRect.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule getRangeBoundingClientRect
 * @format
 * 
 */



var getRangeClientRects = __webpack_require__(/*! ./getRangeClientRects */ "158f");

/**
 * Like range.getBoundingClientRect() but normalizes for browser bugs.
 */
function getRangeBoundingClientRect(range) {
  // "Return a DOMRect object describing the smallest rectangle that includes
  // the first rectangle in list and all of the remaining rectangles of which
  // the height or width is not zero."
  // http://www.w3.org/TR/cssom-view/#dom-range-getboundingclientrect
  var rects = getRangeClientRects(range);
  var top = 0;
  var right = 0;
  var bottom = 0;
  var left = 0;

  if (rects.length) {
    // If the first rectangle has 0 width, we use the second, this is needed
    // because Chrome renders a 0 width rectangle when the selection contains
    // a line break.
    if (rects.length > 1 && rects[0].width === 0) {
      var _rects$ = rects[1];
      top = _rects$.top;
      right = _rects$.right;
      bottom = _rects$.bottom;
      left = _rects$.left;
    } else {
      var _rects$2 = rects[0];
      top = _rects$2.top;
      right = _rects$2.right;
      bottom = _rects$2.bottom;
      left = _rects$2.left;
    }

    for (var ii = 1; ii < rects.length; ii++) {
      var rect = rects[ii];
      if (rect.height !== 0 && rect.width !== 0) {
        top = Math.min(top, rect.top);
        right = Math.max(right, rect.right);
        bottom = Math.max(bottom, rect.bottom);
        left = Math.min(left, rect.left);
      }
    }
  }

  return {
    top: top,
    right: right,
    bottom: bottom,
    left: left,
    width: right - left,
    height: bottom - top
  };
}

module.exports = getRangeBoundingClientRect;

/***/ }),

/***/ "zn7N":
/*!*************************************************************!*\
  !*** ./node_modules/core-js/library/modules/_object-sap.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// most Object methods by ES6 should accept primitives
var $export = __webpack_require__(/*! ./_export */ "Y7ZC");
var core = __webpack_require__(/*! ./_core */ "WEpk");
var fails = __webpack_require__(/*! ./_fails */ "KUxP");
module.exports = function (KEY, exec) {
  var fn = (core.Object || {})[KEY] || Object[KEY];
  var exp = {};
  exp[KEY] = exec(fn);
  $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp);
};


/***/ }),

/***/ "zoYe":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_baseToString.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Symbol = __webpack_require__(/*! ./_Symbol */ "nmnc"),
    arrayMap = __webpack_require__(/*! ./_arrayMap */ "eUgh"),
    isArray = __webpack_require__(/*! ./isArray */ "Z0cm"),
    isSymbol = __webpack_require__(/*! ./isSymbol */ "/9aa");

/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;

/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
    symbolToString = symbolProto ? symbolProto.toString : undefined;

/**
 * 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;
}

module.exports = baseToString;


/***/ }),

/***/ "ztYK":
/*!****************************************************************************************!*\
  !*** ./node_modules/plotlywidget/node_modules/plotly.js/src/constants/interactions.js ***!
  \****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/




module.exports = {
    /**
     * Timing information for interactive elements
     */
    SHOW_PLACEHOLDER: 100,
    HIDE_PLACEHOLDER: 1000,

    // ms between first mousedown and 2nd mouseup to constitute dblclick...
    // we don't seem to have access to the system setting
    DBLCLICKDELAY: 300,

    // opacity dimming fraction for points that are not in selection
    DESELECTDIM: 0.2
};


/***/ }),

/***/ "zx6S":
/*!******************************************!*\
  !*** ./node_modules/moment/locale/sr.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

//! moment.js locale configuration

;(function (global, factory) {
    true ? factory(__webpack_require__(/*! ../moment */ "wd/R")) :
   undefined
}(this, (function (moment) { 'use strict';


var translator = {
    words: { //Different grammatical cases
        ss: ['sekunda', 'sekunde', 'sekundi'],
        m: ['jedan minut', 'jedne minute'],
        mm: ['minut', 'minute', 'minuta'],
        h: ['jedan sat', 'jednog sata'],
        hh: ['sat', 'sata', 'sati'],
        dd: ['dan', 'dana', 'dana'],
        MM: ['mesec', 'meseca', 'meseci'],
        yy: ['godina', 'godine', 'godina']
    },
    correctGrammaticalCase: function (number, wordKey) {
        return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]);
    },
    translate: function (number, withoutSuffix, key) {
        var wordKey = translator.words[key];
        if (key.length === 1) {
            return withoutSuffix ? wordKey[0] : wordKey[1];
        } else {
            return number + ' ' + translator.correctGrammaticalCase(number, wordKey);
        }
    }
};

var sr = moment.defineLocale('sr', {
    months: 'januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar'.split('_'),
    monthsShort: 'jan._feb._mar._apr._maj_jun_jul_avg._sep._okt._nov._dec.'.split('_'),
    monthsParseExact: true,
    weekdays: 'nedelja_ponedeljak_utorak_sreda_četvrtak_petak_subota'.split('_'),
    weekdaysShort: 'ned._pon._uto._sre._čet._pet._sub.'.split('_'),
    weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'),
    weekdaysParseExact : true,
    longDateFormat: {
        LT: 'H:mm',
        LTS : 'H:mm:ss',
        L: 'DD.MM.YYYY',
        LL: 'D. MMMM YYYY',
        LLL: 'D. MMMM YYYY H:mm',
        LLLL: 'dddd, D. MMMM YYYY H:mm'
    },
    calendar: {
        sameDay: '[danas u] LT',
        nextDay: '[sutra u] LT',
        nextWeek: function () {
            switch (this.day()) {
                case 0:
                    return '[u] [nedelju] [u] LT';
                case 3:
                    return '[u] [sredu] [u] LT';
                case 6:
                    return '[u] [subotu] [u] LT';
                case 1:
                case 2:
                case 4:
                case 5:
                    return '[u] dddd [u] LT';
            }
        },
        lastDay  : '[juče u] LT',
        lastWeek : function () {
            var lastWeekDays = [
                '[prošle] [nedelje] [u] LT',
                '[prošlog] [ponedeljka] [u] LT',
                '[prošlog] [utorka] [u] LT',
                '[prošle] [srede] [u] LT',
                '[prošlog] [četvrtka] [u] LT',
                '[prošlog] [petka] [u] LT',
                '[prošle] [subote] [u] LT'
            ];
            return lastWeekDays[this.day()];
        },
        sameElse : 'L'
    },
    relativeTime : {
        future : 'za %s',
        past   : 'pre %s',
        s      : 'nekoliko sekundi',
        ss     : translator.translate,
        m      : translator.translate,
        mm     : translator.translate,
        h      : translator.translate,
        hh     : translator.translate,
        d      : 'dan',
        dd     : translator.translate,
        M      : 'mesec',
        MM     : translator.translate,
        y      : 'godinu',
        yy     : translator.translate
    },
    dayOfMonthOrdinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 7  // The week that contains Jan 1st is the first week of the year.
    }
});

return sr;

})));


/***/ }),

/***/ "zxN+":
/*!**************************************************************!*\
  !*** ./node_modules/draft-js/lib/getVisibleSelectionRect.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule getVisibleSelectionRect
 * @format
 * 
 */



var getRangeBoundingClientRect = __webpack_require__(/*! ./getRangeBoundingClientRect */ "zlY5");

/**
 * Return the bounding ClientRect for the visible DOM selection, if any.
 * In cases where there are no selected ranges or the bounding rect is
 * temporarily invalid, return null.
 */
function getVisibleSelectionRect(global) {
  var selection = global.getSelection();
  if (!selection.rangeCount) {
    return null;
  }

  var range = selection.getRangeAt(0);
  var boundingRect = getRangeBoundingClientRect(range);
  var top = boundingRect.top,
      right = boundingRect.right,
      bottom = boundingRect.bottom,
      left = boundingRect.left;

  // When a re-render leads to a node being removed, the DOM selection will
  // temporarily be placed on an ancestor node, which leads to an invalid
  // bounding rect. Discard this state.

  if (top === 0 && right === 0 && bottom === 0 && left === 0) {
    return null;
  }

  return boundingRect;
}

module.exports = getVisibleSelectionRect;

/***/ }),

/***/ "zzB/":
/*!************************************************************!*\
  !*** ./node_modules/@jupyterlab/completer/style/index.css ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(/*! !../../../css-loader!./index.css */ "wajC");

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "aET+")(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ })

}]);
//# sourceMappingURL=vendors~main.3fa4f4c4a818775b0546.js.map